4923648	4923630	C# getters, setters declaration	public string Name { get; private set; }	0
6169782	6169755	linq group by with join	var query =\n    from first in db.FirstTable\n    select\n        new\n        {\n            first.foreignId,\n            countFromSecond = db.SecondTable\n                .Where(arg => arg.foreignId == first.foreignId)\n                .Count(),\n            first.fieldFromFirst\n        };	0
6582979	6582904	What is the best way to read in a text file from the server in asp.net-mvc	var fileContents = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/file.txt"));	0
15825364	15825278	sqlexception cannot insert duplicate key row	string basestring = "student{0}@email.com";\nstring userName = "Student{0}";\n\nusing (Database dc = new Database())\n{\n\n    for (int i = 0; i < 400; i++)\n    {\n         dc.Connection.Open();\n        string email = string.Format(basestring,i);\n        string sName = string.Format(userName, i);\n        User u = new User(){ Name = sName, UserName = email, InstitutionUniqueID = email, Email = email, CreationDate=DateTime.Now, InstitutionsID=1, GUID= Guid.NewGuid() };\n        dc.Users.InsertOnSubmit(u); \n        dc.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);\n        dc.Connection.Close();\n    }\n\n}	0
34115978	34115919	How to make a field unique ASP.NET MVC5	using System.ComponentModel.DataAnnotations.Schema;	0
28440276	28439628	change asp.net panel visibility based on return value of popup window javascript	function GetSelectedItem(x) {\n    if (x.value == 4) {\n        if (confirm("Are you sure you want to cancel support ticket ?")) {\n            document.getElementById("pnl_Cancel").style.display = 'block';\n        } else {\n            x.value = "";\n        }\n    }\n}	0
24797226	24797099	How to get data from yesterday	var date = DateTime.Now.AddDays(-1);\nvar model = _orderRepo.GetAll().Where(x => x.DateCreated.Year == date.Year\n                        && x.DateCreated.Month == date.Month\n                        && x.DateCreated.Day == date.Day);	0
18631870	18631415	C# XML Deserialization of array	[Serializable()]\n    [System.Xml.Serialization.XmlRoot("export")]\n    public class NotificationCollection\n    {\n        [XmlElement("notificationSZType", Type = typeof(notificationSZType))]\n        [XmlElement("notificationPOType", Type = typeof(notificationPOType))]\n        [XmlElement("notificationZKType", Type = typeof(notificationZKType))]\n        [XmlElement("notificationEFType", Type = typeof(notificationEFType))]\n        [XmlElement("notificationOKType", Type = typeof(notificationOKType))]\n        public notificationType[] notification { get; set; }\n    }	0
17352157	17351484	How to Sort Listview Columns Containing Strings & Integers?	If Integer.TryParse(xText, VBNull) Then\n      xText = xText.PadLeft(6, "0"c)\nEnd If\nIf Integer.TryParse(yText, VBNull) Then\n      yText = yText.PadLeft(6, "0"c)\nEnd If\nReturn xText.CompareTo(yText) * IIf(Me.ascending, 1, -1)	0
15622944	15622828	Open all closed forms in my project one at a time	var form = (Form)Activator.CreateInstance(myType);\nform.ShowDialog();	0
8047456	8015587	How to change email subject in C# using Exchange Web Services	var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1)\n                      {\n                          UseDefaultCredentials = true,\n                          Url = new Uri("https://casserver/ews/exchange.asmx")\n                      };\nItem item = Item.Bind(service, new Itemid(msgid));\nitem.Subject = "test";\nitem.Update(ConflictResolutionMode.AutoResolve);	0
25669048	25668789	How to access TextArea from code-behind from a MasterPage	var txtTaskNotes = (System.Web.UI.HtmlControls.HtmlTextArea)ContentMain.FindControl("taskNotes");	0
7293190	7293166	Is it possible to disable a function in C#	[Conditional("DEBUG")]\nprivate void log(string text){\n   logtextbox.Text = text;\n}	0
14940039	14683292	How to get assembly information of a web application converted from web site	System.Reflection.Assembly.Load("assemblyname").GetName().Version.ToString()	0
8312381	8312304	Move rectangle with same mouse position in regard to rectangle?	private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e) \n{ \n    if (e.Button == MouseButtons.Left) \n    { \n        rect.X = e.X - downPos.X; \n        rect.Y = e.Y - downPos.Y; \n\n        rect.Width = rect.Width; \n        rect.Height = rect.Height; \n        pictureBox1.Invalidate(); \n    } \n}	0
12142660	12142659	LINQ with Entity Framework, getting calculated sum	(from b in data\nwhere b.Number.HasValue\nselect new\n{\n    Number = b.Number.Value,\n    b.Factor\n}).Sum(o => (decimal?)(o.Number * ((decimal)o.Factor / 100))) ?? 0;	0
8547289	8540327	Building dynamic where clause, Linq To Sql	IQueryable<LinkTable> linkQuery = db.Set<LinkTable>().AsQueryable();\n\nMethodCallExpression internalQueryWhere = Expression.Call(typeof(Queryable), "Where", new Type[] { linkQuery.ElementType }, linkQuery.Expression,Expression.Lambda<Func<LinkTable, bool>>(myfilters, new ParameterExpression[] { filterParameter })); \n\nlinkQuery = linkQuery.Provider.CreateQuery<LinkTable>(internalQueryWhere);\n\nExpression anyMethodExpr = Expression.Call(typeof(Queryable), "Any", new Type[] { linkQuery.ElementType }, linkQuery.Expression);	0
25199762	25199662	How do I access the children of a TableView in Xamarin.Forms	SwitchCell sc = (SwitchCell)tv.Root[0][0];\nbool booleanprop = sc.On;	0
25066296	25065596	Calculating the size of a generic struct where generic parameters are restricted to primitive types	Marshal.SizeOf(typeof(T))	0
1065502	1061851	Column with same name in multiple tables causing problem in SubSonic Select	...\nsq.Where(TableTwo.NameColumn).Like("A%");	0
11949748	11878353	Database provisioning of a multi tenant application	RESTORE FILELISTONLY\nFROM DISK = 'C:\BaackUpFile.bak'\n\nRESTORE DATABASE DbName\nFROM DISK = 'C:\BaackUpFile.bak'\nWITH MOVE 'YourMDFLogicalName' TO 'C:\DataYourMDFFile.mdf',\nMOVE 'YourLDFLogicalName' TO 'C:\DataYourLDFFile.ldf'	0
10542548	10541062	Json.NET output only value in C#	var yourObjectList = List<YourObject>(){.....}\n\nstring s = JsonConvert.SerializeObject(GetObjectArray(yourObjectList));\n\npublic static IEnumerable<object> GetObjectArray<T>(IEnumerable<T> obj)\n{\n    return obj.Select(o => o.GetType().GetProperties().Select(p => p.GetValue(o, null)));\n}	0
27986861	27986760	Proper way of creating a property path for a dynamically created Binding object?	Binding b = new Binding();\nb.Path = new PropertyPath("(0)", DataField.OwnerProperty);	0
33740610	33739618	SQL Query taking too long to execute in VS2012 but instantly in MSSQL	declare @value sql_variant\n\nselect @value = SESSIONPROPERTY('ARITHABORT') \nif @value <> 1 \nbegin \n  USE master \n  ALTER DATABASE [yourDataBaseName] SET ARITHABORT ON WITH NO_WAIT \nuse yourDataBaseName	0
19691009	19690662	How to use DirectoryInfo to populate a listbox	//load all image here\npublic Form1()\n{\n    InitializeComponent();\n    //set your directory\n    DirectoryInfo myDirectory = new DirectoryInfo(@"E:\MyImages");\n    //set file type\n    FileInfo[] allFiles = myDirectory.GetFiles("*.jpg");\n    //loop through all files with that file type and add it to listBox\n    foreach (FileInfo file in allFiles)\n    {\n            listBox1.Items.Add(file);\n    }\n}\n\n//bind clicked image with picturebox\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    //Make selected item an image object\n    Image clickedImage = Image.FromFile(@"E:\MyImages\" + listBox1.SelectedItem.ToString());\n    pictureBox1.Image = clickedImage;\n    pictureBox1.Height = clickedImage.Height;\n    pictureBox1.Width = clickedImage.Width;\n}	0
11150159	11150105	How to pass a thrown exception from a C# class to a C# Form	catch (Exception ex) {\n    throw;\n}	0
2410845	2410788	Parse a TSV file	Microsoft.VisualBasic.FileIO	0
13003470	13003377	How to test with deferred execution?	var result = _items.SelectMany (x => x.Get (something));	0
14554861	14552750	Elmah - inspect server variables	try\n {\n\n   ...\n } \n catch (Exception ex)\n {\n    Elmah.ErrorSignal.FromCurrentContext()\n       .Raise(new CustomException(ex,<insert method variables here>));\n }	0
11158426	11158385	Can I access entire DataTable if all I have is a single DataRow?	if(row.Table == null)\n{\n}\nelse\n{\n}	0
25785441	25784627	Read XML file which is referring another xml file	XmlReaderSettings settings = new XmlReaderSettings();\nsettings.DtdProcessing = DtdProcessing.Parse;\nXmlReader reader = XmlReader.Create("test.xml", settings);\n\nvar XmlData = XElement.Load(reader);	0
9275004	9274933	Filling XML data to DataSet	string xmlFilename = "XmlFilePath.xml";\n         DataSet yourDataset = new DataSet();\n         yourDataset.ReadXml(xmlFilename);\n         // do with your filled Dataset	0
1338267	726864	Problem retrieving Hostaddress from Win32_TCPIPPrinterPort	ConnectionOptions connOptions = new ConnectionOptions();\nconnOptions.EnablePrivileges = true;\n\nManagementScope mgmtScope = new ManagementScope("root\\CIMV2", connOptions);\nmgmtScope.Connect();\n\nObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort");\nManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mgmtScope, objQuery);\n\nforeach (ManagementObject mo in moSearcher.Get())\n{\n    Console.WriteLine(String.Format("PortName={0} HostAddress={1}", mo["Name"], mo["HostAddress"]));\n}	0
31352809	31351256	How to stop animator	Animation animation = GetComponent<Animation>();\n string animationClipName = "1";\n\n animation[animationClipName].speed = 0;	0
5098150	5098126	C# try catch pattern help	public T TryCatch<T>(Func<T> theFunction)\n{\n  try\n  {\n    return theFunction();\n  }\n  catch(Exception e)\n  {\n    // You'll need to either rethrow here, or return default(T) etc\n  }\n}	0
4782356	4782337	Programme performance	public Class1()\n{\n    Stopwatch stopWatch = new Stopwatch();\n    stopWatch.Start();\n\n    // Do your stuff here...\n\n    stopWatch.Stop();\n\n    // Format and display the TimeSpan value.\n    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n        ts.Hours, ts.Minutes, ts.Seconds,\n        ts.Milliseconds / 10);\n    Console.WriteLine(elapsedTime, "RunTime");\n}	0
10073655	10073619	DataFormatString rounding decimal to larger value	r = (v < 0.01 && r > 0.0) ? 0.01 : v;	0
28111285	28069549	Setting Value on DataGridViewComboBox column very slow	private void AddClassCombobox()\n    {\n        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();\n        cmb.HeaderText = "New Class";\n        cmb.Name = "cmb";\n        cmb.DataPropertyName = "Class";  // << Added this\n\n        foreach (DataGridViewRow row in dgClasses.Rows)\n        {\n            if (row.Cells[0].Value != null)\n            {\n                cmb.Items.Add(row.Cells[0].Value);\n            }\n        }\n\n        dgProducts.Columns.Add(cmb);\n    }	0
33595334	33594971	How to cut picture from pictureBox by rectangle on it	using (Bitmap bmp = new Bitmap(pictureBox1.Image))\n{\n    var newImg = bmp.Clone(\n        new Rectangle { X = 10, Y = 10, Width = bmp.Width / 2, Height = bmp.Height / 2 }, \n        bmp.PixelFormat);\n    pictureBox2.Image = newImg;\n}	0
27170571	27170382	LINQ - GROUP BY on object to create string	var states = Version.States.Aggregate(string.Empty, (c, state) => c + state.ToString() + ",").TrimEnd(new []{','});\n    var dates = Version.Dates.Aggregate(string.Empty, (c, date) => c + date.ToString() + ",").TrimEnd(new []{','});	0
5777564	5777552	how to declare list and later add items from other deep function	public IDictionary<string,int[]> alphabetletters = new Dictionary<string,int[]>();	0
19753402	19753380	Need "Method return type" of data selected with LINQ from DataTable	IEnumerable<SomeClass>	0
29733564	29733515	How count number of objects created with a static class variable?	public class Student\n{\n    public static int count = 0;\n    public Student()\n    {\n        // Thread safe since this is a static property\n        Interlocked.Increment(ref count);\n    }\n\n    // use properties!\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public string BirthDate { get; set; }\n}	0
3773538	3773473	Any tool that says how long each method takes to run?	Stopwatch stopwatch = new Stopwatch();\nstopwatch.Start(); // Start timing\n\n// This is what we want to time\nDoSomethingWeSuspectIsSlow();\n\nstopwatch.Stop();\nConsole.WriteLine("It took {0} ms.", stopwatch.ElapsedMilliseconds);	0
30652278	30652226	How do i use regex to parse text between two any strings?	Regex r1 = new Regex(startTag + @"([A-Za-z0-9\-]+)" + endTag);	0
3012233	3012214	Need to know when application is closing	AppDomain.ProcessExit	0
25215810	24222862	Configure Entity Framework to pick connection strings from Azure CloudConfiguration File?	base(CloudConfigurationManager.GetSetting("YourEntities"))	0
10936310	10935970	Insert random amount of dots to string with minimum different places?	Random rand = new Random();\nstring[] words = iTemplate.Text.Split(' ');\n// Insert dots onto at least 4 words\nint numInserts = rand.Next(4, words.Count());\n// Used later to store which indexes have already been used\nDictionary<int, bool> usedIndexes = new Dictionary<int, bool>();\nfor (int i = 0; i < numInserts; i++)\n{\n    int idx = rand.Next(1, words.Count());\n    // Don't process the same word twice\n    while (usedIndexes.ContainsKey(idx))\n    {\n        idx = rand.Next(1, words.Count());\n    }\n     // Mark this index as used\n    usedIndexes.Add(idx, true);\n    // Append the dots\n    words[idx] = words[idx] + new String('.', rand.Next(1, 7));\n}\n// String.Join will put the separator between each word,\n// without the trailing " "\nstring result = String.Join(" ", words);\nConsole.WriteLine(result);	0
10632377	10632277	Best way to trim value in textbox before save/insert using formview into datasource	formView.Controls\n    .OfType<System.Web.UI.WebControls.TextBox>()\n    .ToList()\n    .ForEach(t => t.Text = t.Text.Trim());	0
11848770	11848610	Using HTMLAgilityPack to convert links into BBCODE?	HtmlDocument doc = new HtmlDocument();\ndoc.Load(myTestFile);\n\nforeach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))\n{\n    node.ParentNode.ReplaceChild(doc.CreateTextNode("[url=" + node.GetAttributeValue("href", null) +"]" + node.InnerHtml + "[/url]"), node);\n}	0
14280048	14279969	Xml Serialization and deserialization fails	public static string Serialize<T>(T o)\n{\n    using (var sw = new StringWriter())\n    {\n        using (var xw = XmlWriter.Create(sw))\n        {\n            var xs = new XmlSerializer(typeof(T));\n            xs.Serialize(xw, o);\n            return sw.ToString();\n        }\n    }\n}\n...\n// we don't need to explicitly define MyClass as the type, it's inferred\nvar a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });\nvar b = XmlHelper.Deserialize<MyClass>(a);	0
15074601	15074586	Using lambdas in C# to perform multiple functions on an array	string[] parts = s.Split(',').Select(x => x.Trim()).ToArray();	0
10230015	10229944	Saving a variable data to disk	public void SerializeObject<T>(string filename, T obj)\n   {\n      Stream stream = File.Open(filename, FileMode.Create);\n      BinaryFormatter binaryFormatter = new BinaryFormatter();\n      binaryFormatter.Serialize(stream, obj);\n      stream.Close();\n   }\n\n   public T DeSerializeObject<T> (string filename)\n   {\n      T objectToBeDeSerialized;\n      Stream stream = File.Open(filename, FileMode.Open);\n      BinaryFormatter binaryFormatter = new BinaryFormatter();\n      objectToBeDeSerialized= (T)binaryFormatter.Deserialize(stream);\n      stream.Close();\n      return objectToBeDeSerialized;\n   }\n\n[Serializable]\nstruct MyStruct\n{\n    byte[] ByteData;\n    int MyInt;\n    double MyDouble;\n}	0
2377964	2363721	How to create the Google DataTable JSON expected source using C#?	System.Data.DataTable	0
8707228	8707208	Find the highest occuring words in a string C#	Regex.Split("Hello World This is a great world, This World is simply great".ToLower(), @"\W+")\n    .Where(s => s.Length > 3)\n    .GroupBy(s => s)\n    .OrderByDescending(g => g.Count())	0
28243904	28243783	Where do ASP.NET validation controls validate data?	// If user disables java script, IsValid will return false.\nif (IsValid)\n{\n    // Then you validate inputs based on your business logic.\n}	0
9291463	9291396	Read string in string	foreach(string n in txtList)\n{\n  int startindex = n.IndexOf(@"\.") + 2;\n  Console.WriteLine(n.Substring( startindex, n.Length-startindex-1));\n}	0
5788128	5788080	C# Create Control From a String Value	var textBoxType = typeof(Control).Assembly.GetType("System.Windows.Forms.TextBox", true);\nvar textBox = Activator.CreateInstance(textBoxType);	0
28948225	28939439	add checkbox to button	using System.Windows.Forms.VisualStyles;\n\npublic class ButtonWithCheckBox : Button {\n  public bool OptionChecked { get; set; }\n\n  protected override void OnMouseDown(MouseEventArgs e) {\n    if (GetCheckBoxRectangle().Contains(e.Location)) {\n      this.OptionChecked = !this.OptionChecked;\n      this.Invalidate();\n    } else {\n      base.OnMouseDown(e);\n    }\n  }\n\n  protected override void OnPaint(PaintEventArgs e) {\n    base.OnPaint(e);\n    CheckBoxRenderer.DrawCheckBox(e.Graphics,\n      GetCheckBoxRectangle().Location,\n      this.OptionChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);\n  }\n\n  private Rectangle GetCheckBoxRectangle() {\n    Rectangle result = Rectangle.Empty;\n    using (Graphics g = this.CreateGraphics()) {\n      Size sz = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal);\n      result = new Rectangle(new Point(this.ClientSize.Width - (sz.Width + 8), 8), sz);\n    }\n    return result;\n  }\n}	0
15403062	15402892	How to select All the Tables in Access DataBase 2007 using query	string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myAccess2007file.accdb;Persist Security Info=False;";\nOleDbConnection conn = new OleDbConnection(connectionString);\nconn.Open();\nDataTable tables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});\nconn.Close();	0
12293214	12293191	How to add more Attribute in XElement?	bc.SkuList.Select(x => new XElement("SKUs", new XAttribute("Sku", x.SkuName),\n                                            new XAttribute("Quantity", x.Quantity),\n                                            new XAttribute("PurchaseType", x.PurchaseType)\n                                    ))	0
19914497	19914379	How to request client cookies on server ASP.NET	if(Request.Cookies["userName"] != null)\n    Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);	0
15378205	15354340	Is it possible to do data type conversion on SQLBulkUpload from IDataReader?	public override object GetValue(int i)\n{\n  var landingColumn = GetName(i);\n  string landingValue = base.GetValue(i).ToString();\n\n  object stagingValue = null;\n  switch (landingColumn)\n    {\n    case "D4DTE": stagingValue = landingValue.FromStringDate(); break;\n    case "D4BRAR": stagingValue = landingValue.ToDecimal(); break;\n\n    default:\n        stagingValue = landingValue;\n        break;\n    }\n  return stagingValue;\n}	0
16933613	16933585	string: extract a word from sentence	Regex.Match("Meeting with developer 60min", @"(\d+min)").Groups[1].ToString();	0
14008785	14008778	Get datetime value from X days go?	MyNewDateValue = MyDateNow.AddDays(-MyDateInteger);	0
3879712	3879685	C# image manipulation using a console application throwing 'Out of Memory' Exception	Bitmap.Clone	0
25545901	25545812	How to format string to datetime?	var date = new Date("Thu Aug 28 2014 00:00:00 GMT+0300")\nvar sDate = date.toISOString();	0
14280439	14280195	App Current Shutdown closing window prompting	public class X \n{\n    private static bool isClosingHandled = false;\n\n    public static void HandleClose()\n    {\n        //// app closing logic\n        isClosingHandled = true;\n    }\n}\n\nprivate void Window_Closing_1(object sender, CancelEventArgs e)\n{\n    X.HandleClose();   \n}	0
5180152	5180110	C#: how to do basic BackgroundWorkerThread	var f = new FormProgress()\n\nf.ProgressAmount = 10;\nvar worker = new BackgroundWorker();\nworker.DoWork += (o, e) => RetrieveAndDisplayResults();\nworker.RunWorkerCompleted += (o, e) => \n{\n    f.ProgressAmount = 100;\n    f.Close();\n}\n\nworker.RunWorkerAsync();	0
6589027	6588974	Get Imagesource from Memorystream in c# wpf	using (MemoryStream memoryStream = ...)\n{\n    var imageSource = new BitmapImage();\n    imageSource.BeginInit();\n    imageSource.StreamSource = memoryStream;\n    imageSource.EndInit();\n\n    // Assign the Source property of your image\n    image.Source = imageSource;\n}	0
10090251	10090139	How to use different labels in one for cycle	Label myLabel = this.FindControl("Label"+i+"1") as Label; \nmyLabel.Text = "my text";	0
1860429	1860333	Extension method for fill rectangular array in C#	public static void Fill<T>(this Array source, T value)\n{\nFill(0, source, new long[source.Rank], value);\n}\n\nstatic void Fill<T>(int dimension, Array array, long[] indexes, T value)\n{\nvar lowerBound = array.GetLowerBound(dimension);\nvar upperBound = array.GetUpperBound(dimension);\nfor (int i = lowerBound; i <= upperBound; i++)\n{\nindexes[dimension] = i;\nif (dimension < array.Rank - 1)\n{\nFill(dimension + 1, array, indexes, value);\n}\nelse\n{\narray.SetValue(value, indexes);\n}\n}\n}	0
11353821	11304775	RASEnumDevices with Port name?	using DotRas;\n\nIEnumerable<RasDevice> devices = RasDevice.GetDevices();	0
397695	266082	How do I tell if my application is running as a 32-bit or 64-bit application?	if (IntPtr.Size == 8) \n{\n    // 64 bit machine\n} \nelse if (IntPtr.Size == 4) \n{\n    // 32 bit machine\n}	0
10841964	10788987	How to load and refresh user control on button click	var dataprovider = (System.Windows.Data.XmlDataProvider) (\n  ((UserControl1) (elementHost1.Child)).Resources ["rssData"]\n);\ndataprovider.Refresh ();	0
28542817	28542684	Multiple CheckBox Selection Result using Linq without hardcoding	var employee = db.Employee.AsQueryable():\nvar predicate = PredicateBuilder.False<Employee>();\nif (model.IsSicked == true)\n    predicate = predicate.Or(p => p.IsSick == model.IsSick);\nif (model.IsRetired == true)\n    predicate = predicate.Or(p => p.IsRetired == model.IsRetired);\nif (model.IsHoliday == true)\n    predicate = predicate.Or(p => p.IsHoliday == model.IsHoliday);\nvar result = employee.AsExpandable().Where(c => predicate.Invoke(c)).ToList()	0
4010615	4010543	Lock() in a static method	static object SpinLock = new object();\n\nlock(SpinLock)\n{\n   //Statements\n}	0
8611152	8609180	Best way to identify a WPF control?	public void DoSomething(Textbox tb)\n{\n   if(tb == tbOne)\n   {\n   }\n   else if (tb == tbTwo)\n   {\n   }\n}	0
19521833	19521435	Correct way to get total number of logical cores from remote pc	row["Cores"] = obj["NumberOfLogicalProcessors"].ToString();	0
5922531	5922473	Is it possible to list our all the string variable names and values out	using System;\n\nclass Car\n{\n    public string Color;\n    public string Model;\n    public string Made;\n}\n\nclass Example\n{\n    static void Main()\n    {\n        var car = new Car\n        {\n            Color = "Red",\n            Model = "NISSAN",\n            Made = "Japan"\n        };\n\n        foreach (var field in typeof(Car).GetFields())\n        {\n            Console.WriteLine("{0}: {1}", field.Name, field.GetValue(car));\n        }\n    }    \n}	0
8169016	8168860	How to compute CRC (checksum) for array of struct?	u32 hash_mystruct(mystruct[] data, u32 count) {\n      return hash((u8*)data, sizeof(mystruct) * count);\n  }\n  u32 hash(u8* data, u32 size) {    \n    u32 hash = 19;\n    for (u32 i = 0; i < size; i++) {\n      u8 c = *data++;\n      if (c != 0) { // usually when doing on strings this wouldn't be needed\n        hash *= c;\n      }\n      hash += 7;\n    }\n  }	0
7562364	7562209	How to show some certain columns in datagridview in C#	datagridview.Columns[0].Visible = false	0
19501037	19500739	DotNetZip - Adding Folders	bool recurseDirectories = true;\n  using (ZipFile zip = new ZipFile())\n  {\n    zip.AddSelectedFiles("*", @TempLoc, string.Empty, recurseDirectories);\n    zip.Save(ZipFileToCreate);\n  }	0
33487074	33486734	c# finding a string in a text file then do something?	var allLinesInFile = System.IO.File.ReadAllLines(file);\nvar isPlayerScore = false;\nvar linesToWrite = new List<string>();\nvar linesToAdd = new List<string> {\n  "itemDef\n\r",\n  "{",\n  " name \"zombiecounter\"\n\r",\n  //and so on\n  "}"\n};\n\nforeach (var line in allLinesInFile)\n{\n  linesToWrite.Add(line);\n\n  if (line.IndexOf("playerscores", StringComparison.OrdinalIgnoreCase) >= 0)\n  { \n     //starting of data detected. \n     isPlayerScore = true;\n  }\n  else if (isPlayerScore == true && line.IndexOf("}") >= 0)\n  {\n     //end of data detected\n     isPlayerScore = false;\n     linesToWrite.AddRange(linesToAdd);\n  }\n}\n\nSystem.IO.File.WriteAllLines(file, linesToWrite);\nMessageBox.Show("done");	0
18544211	18544160	Keep Checking A Value Without Stack Overflow	private void button_Click(object sender, EventArgs e)\n{\n     if(input=="YES" || input=="Y")\n        //do stuff\n     else\n        //reshow question\n}	0
19608456	19608317	How to get all non .NET framework assemblies in AppDomain?	Assembly a = Assembly.GetAssembly(typeof(Task));\n        CustomAttributeData attributeData = a.CustomAttributes.First(attribute => attribute.AttributeType == typeof(AssemblyProductAttribute));\n        string value = attributeData.ConstructorArguments[0].Value as string;	0
17612333	17612045	How to use feature like Contains in LINQ to Entity	where listId.Contains((int)error.battery_id)	0
17847350	17837637	multiple pictures with coordinates C#	private void buttonLayout_Click(object sender, EventArgs e)\n    {\n        int x=0;\n        int y=0;          \n        for (int index = 0; index < 6;index++ )\n        {\n            string path = @"C:\Pictures\" + index.ToString() + ".png";\n            if (!File.Exists(path))\n            {\n                continue;\n            }\n            Image image=Image.FromFile(path);\n            PictureBox pictureBox = new PictureBox();\n            pictureBox.Image = image;\n            pictureBox.BorderStyle = BorderStyle.FixedSingle;\n            pictureBox.Left = x;\n            pictureBox.Top = y;\n            pictureBox.Width = image.Width;\n            pictureBox.Height = image.Height;\n            pictureBox.SizeMode = PictureBoxSizeMode.Normal;\n            panelPictures.Controls.Add(pictureBox);\n            x += pictureBox.Image.Width;               \n        }            \n    }	0
17751375	17750295	GridView - Hide Column but Use Value	Private IDColumnIndex As Integer      //Class scope - we need to use it in multiple methods\n\nPublic Sub PageLoad() Handles Me.Load //or wherever your databind is happening\n    Dim source As New DataTable()\n    IDColumnIndex = source.Columns("id").Ordinal   //Gets column index of "ID" column\n\n    view.DataSource = source\n    view.DataBind()\nEnd Sub\n\n//Hide our "ID" auto-generated column.\nPublic Sub view_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles view.RowCreated\n    e.Row.Cells(IDColumnIndex).Visible = False\nEnd Sub	0
1880125	1879666	C#: How to Delete the matching substring between 2 strings?	string string1 = textBox1.Text;\nstring string2 = textBox2.Text;\n\nstring string1_part1=string1.Substring(0, string1.IndexOf(string2));\nstring string1_part2=string1.Substring(\n    string1.IndexOf(string2)+string2.Length, string1.Length - (string1.IndexOf(string2)+string2.Length));\n\nstring1 = string1_part1 + string1_part2;	0
11758596	11735220	Can I get the index of an inserted node in a treeview?	private void treeViewProduct_AfterSelect(object sender, TreeViewEventArgs e)\n    {\n\n        if (insertMode)\n        {\n\n            treeViewProduct.NotifyAboutInsert(e.Node.Index);\n        }\n...\n}	0
26620073	26614982	How do I remove entries in a tuple with duplicated properties?	var distincts = fileList.GroupBy(t => t.Item1 + "," + t.Item3)\n                        .Where(g => g.Count() == 1)\n                        .Select(g => g.Single());\n\nforeach (var item in distincts)\n{\n  Console.WriteLine(item);\n}	0
23545212	20353940	Executing DB2 Mainframe SP Using EL 6	var db = new DatabaseProviderFactory().Create("the_name_you_gave_your_connection_string");\nusing (var cmd = db.GetStoredProcCommand("sp_name"))\n{\n    db.DiscoverParameters(cmd);\n\n    // Set the parameter values either directly or through an IParameterMapper or an accessor. \n    // Here's an example of setting them directly:\n    cmd.Parameters["@P1"].Value = "some value";\n\n    // if you want to retrieve a DataSet:\n    using (var ds = db.ExecuteDataSet(cmd))\n    {\n    // ... do something with the returned data.\n    }\n\n    // If you just want to call the stored procedure:\n    db.ExecuteNonQuery(cmd);\n}	0
6191541	3135365	Drawing polygonal line with gradient in GDI+	Graphics g = e.Graphics;\n    Pen p = new Pen(Color.Brown, 15);\n\n    // round ends\n    p.StartCap = LineCap.Round;\n    p.EndCap = LineCap.Round;\n    g.DrawLine(p, 30, 80, Width - 50, 80);//can be replace with you code	0
5775670	5775648	OleDbConnection Source Variable in C#	OleDbConnection dbConnection = new OleDbConnection( String.Format( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;""", filePath ) );	0
3474261	3474254	How to make a first letter capital in C#	public static string ToUpperFirstLetter(this string source)\n{\n    if (string.IsNullOrEmpty(source))\n        return string.Empty;\n    // convert to char array of the string\n    char[] letters = source.ToCharArray();\n    // upper case the first char\n    letters[0] = char.ToUpper(letters[0]);\n    // return the array made of the new char array\n    return new string(letters);\n}	0
31492708	31492226	WPF Lost-Focus issue in same control	Focusable="False"	0
7584163	7510693	How to use Castle.Windsor in an assembly loaded using reflection	AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n{\n     string typeToLoad = args.Name;\n     string myPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;\n     return Assembly.LoadFile(...); //or return Assembly.GetExecutingAssembly() etc.\n};	0
16971199	16970753	"Send mail with attachment" from ASP.NET Page	var attachment = new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.PostedFile.FileName);	0
29644079	29643745	How to show number of users in chart control in asp.net?	var groups = context.Profiles\n                     .Where(u => u.CreatedOn.Year == <someYear>)\n                     .GroupBy(u => u.CreatedOn.Month)\n                              .Select(g => new {\n                                      month = g.Key,\n                                      nbUsers = g.Count()\n                                      });	0
19957704	19956253	Unable to prevent access to secure ASP.NET MVC4 pages after logging out	[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]	0
23193615	23193209	Regx : How to extract some fields in text	string text = File.ReadAllText("sample.txt");\nstring[] items = Regex.Matches(text, "add .*?(?=\r\nadd|$)", RegexOptions.Singleline)\n                      .Cast<Match>()\n                      .Select(m => m.Value)\n                      .ToArray();\nforeach (string item in items)\n{\n    string line = Regex.Replace(item, @"\\\s*\r\n\s*", string.Empty);\n    KeyValuePair<string, string>[] pairs = Regex.Matches(line, @"(?<name>\w+)=(?<value>.*?)(?=\w+=|$)")\n                                                .Cast<Match>()\n                                                .Select(m => new KeyValuePair<string, string>(m.Groups["name"].Value, m.Groups["value"].Value))\n                                                .ToArray();\n\n    Console.WriteLine(line);\n    foreach (var pair in pairs)\n        Console.WriteLine("{0} = {1}", pair.Key, pair.Value);\n}	0
11038113	11038099	Why can I not compare this string array ITEM to a string?	if(slist[i].Trim() != "")	0
8623523	8560218	Getting Installed softwares from remote host using wmi	#PRAGMA AUTORECOVER\n[dynamic, provider("RegProv"),\nProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"),   \nClassContext("local|HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\n\\CurrentVersion\\Uninstall")] \nclass InstalledSoftware \n{\n   [key] string KeyName;\n   [read, propertycontext("DisplayName")]      string DisplayName;\n   [read, propertycontext("DisplayVersion")]   string  DisplayVersion;\n   [read, propertycontext("InstallDate")]      string InstallDate;\n   [read, propertycontext("Publisher")]        string Publisher;\n};	0
24727502	24727483	How can I login to a website using WatiN asynchronously?	Thread t = new Thread(() =>\n{\n    StartDownload();\n    Application.Run();\n});\nt.SetApartmentState(ApartmentState.STA);\nt.Start();	0
21753172	21752944	C# : Serialize objects to XML without reflection	new XmlSerializer(type)	0
11119761	11119412	Close window and open another one from ViewModel with Mediator pattern	protected override void OnStartup(StartupEventArgs e)\n    {\n        //...\n        ShutdownMode = ShutdownMode.OnExplicitShutdown;\n        var vm = new LoginVM();\n        var loginwindow = new LoginWindow();\n        loginwindow.DataContext = vm;\n\n        if (!result.HasValue || !result.Value || !IsValidUser)\n        {\n             Shutdown();\n             return;\n        }   \n\n        //...\n        var mainWindow = new MainWindow(new MainWindowViewModel(vm.Settings));\n\n        mainWindow.Loaded += (sender, args) => splashScreen.Close();\n        this.MainWindow = mainWindow;\n        ShutdownMode = ShutdownMode.OnMainWindowClose;\n        this.MainWindow.Show();\n\n }	0
1603859	1603843	reading a url and getting back a csv file	// Download the file to a specified path. Using the WebClient class we can download \n// files directly from a provided url, like in this case.\n\nSystem.Net.WebClient client = new WebClient();\nclient.DownloadFile(url, csvPath);	0
5451782	5451302	Programatically setting Horizontal alignment of Dock Panel	myDockPanel.HorizontalAlignment = HorizontalAlignment.Center;	0
27971961	27971404	How can I determine free space on a Windows CE device?	String executingFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;\nString executingDirectory = System.IO.Path.GetDirectoryName( executingFileName );\n\nUInt64 userFreeBytes, totalDiskBytes, totalFreeBytes;\nif( GetDiskFreeSpaceEx( executingDirectory, out userFreeBytes, out totalDiskBytes, totalFreeBytes ) {\n    // `userFreeBytes` is the number of bytes available for your program to write to on the mounted volume that contains your application code.\n}	0
33444073	33400569	How to query Elasticsearch from C# via HTTP?	string url_req = "http://localhost:9200/my_index/my_type/_search?pretty";\n\nstring s = "{\"query\": {\"match\": { \"name\" : \"john\" }}}";\n\nusing (var client = new WebClient())\n{\n    Console.Write(client.UploadString(url_req, "POST", s));\n}	0
34075872	34075673	How to display different text to a user than the actual string in C#	string input = "t1326".Replace("t", "").PadLeft(4, '0');\n\n string pattern = "HHmm";\n DateTime dt;\n\n DateTime.TryParseExact(input, pattern, null, \n     DateTimeStyles.None, out dt);\n Console.WriteLine(dt.ToString("h:mm tt")); //outputs 1:26 PM\n\n string reverse = String.Format("t{0}",dt.ToString("HHmm"));\n Console.WriteLine(reverse); //outputs t1326	0
2008120	2008057	How to walk through the collection of subreports in Crystal Reports 2008?	ReportDocument reportDocument = new ReportDocument();\nreportDocument.Load(...);\nforeach (ReportDocument subreportDocument in reportDocument.Subreports) {   \n  // do something here\n}	0
21731227	21730800	Android HTTP to C# Server	RequestParams params = new RequestParams();\nparams.put("A_KEY_TO_IDENTIFY_YOUR_STRING", "THE_STRING_YOU_WANT_TO_SEND");\n\nAsyncHttpClient client = new AsyncHttpClient();\nclient.post("http://www.yourserver.com", params, new AsyncHttpResponseHandler() {\n    @Override\n    public void onSuccess(String response) {\n        // handle your response from the server here\n        System.out.println(response);\n    }\n});	0
2046301	2046274	Convert "\n" to actual newline in SQL Server	UPDATE\n    <tablename> \nSET\n    <fieldname> = replace(<fieldname>,'\n',char(13)+char(10)),\n    <otherfieldname> = replace(< otherfieldname >,'\n',char(13)+char(10))	0
9273548	9273262	How to use ISession and Session Variable in same .cs file and pass Session variable inHttpHandler?	"ImageId"	0
16846699	16846573	Using DialogResult Correctly	using (Form1 form = new Form1())\n{\n    DialogResult dr = form.ShowDialog();\n    if(dr == DialogResult.OK)\n    {\n        string custName = form.CustomerName;\n        SaveToFile(custName);\n    }\n\n}	0
18514960	18514881	Match expression not starting with	(?<!})<input>	0
10443313	10443255	Change duration of splash screen?	private void Application_Startup(object sender, StartupEventArgs e)\n{\n   SplashScreen screen = new SplashScreen("splashScreen.png");\n   screen.Show(false);\n}	0
8001099	8001038	How to change source image property from code behind	importantTag.Attributes["src"] = "yourNewImageUrl";	0
23853504	23852849	Open, select and add a .jpg file inside a form	private void button1_Click(object sender, EventArgs e)\n    {\n        pictureBox1.Visible = true;\n        string Chosen_File = "";\n        Chosen_File = openFileDialog1.FileName;\n        openFileDialog1.Title = "Insert an image";\n        openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);\n        openFileDialog1.FileName = "";\n        openFileDialog1.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|All Files|";\n        //openFileDialog1.ShowDialog();\n        if (openFileDialog1.ShowDialog() != DialogResult.Cancel)\n        {\n            Chosen_File = openFileDialog1.FileName;\n            pictureBox1.Image = Image.FromFile(Chosen_File);\n\n        }\n    }	0
26349507	26348890	How to pass a delegate with different number of arguments than originally designed	public static Func<double[], double[], double> NewDistanceMethodWithParams(double alpha, double beta)\n{                       \n    Func<double[], double[], double> dist = (vec1, vec2) =>\n    {\n         //do some calculations on vec1 and vec2 with alpha, beta params                     \n    };\n\n    return dist;\n}	0
7854002	7715752	Remote unit testin of a WebService in Visual Studio 2010	[TestMethod]\n        public void LoginEmptyDataTest()\n        {\n            using (var userServiceClient = new Services.UserServiceClient(\n                                        "BasicHttpBinding_IUserService", \n                                        "http://someremotehost/userservice.svc"))\n            {\n                var result = userServiceClient.Login("user", "password");\n\n                // asserts go here\n            }\n        }	0
16026559	16012601	How to add hyperlink in meeting body using EWS to c#?	appointment.Body = "The <a href="http://your.link">appointment</a> is with Dr. Smith.";	0
21235864	20395904	Adding a home button to your wpf browser	string input = Microsoft.VisualBasic.Interaction.InputBox("Please set your home page", "Settings");	0
19959900	19959683	how to add array elements in one array according to condition in other array in C#?	int[] newchartValues = new int[] { 1, 2, 3, 4, 5, 6 };\nstring[] newdates = new string[] { "11", "11", "11", "11", "12", "12" };\n\nList<int> result = new List<int>();\nif (newdates.Length == 0)\n    return;\nstring last = newdates[0];\nint cursum = newchartValues[0];\nfor (var i = 1; i <= newdates.Length; i++)\n{\n    if (i == newdates.Length || newdates[i] != last)\n    {\n        result.Add(cursum);\n        if (i == newdates.Length)\n            break;\n        last = newdates[i];\n        cursum = 0;\n    }\n    cursum += newchartValues[i];\n}	0
10329693	10329677	How do you split elements in an array and return it as a new array	string[] sportsNewArray = sports.SelectMany(s=>s.Split('/')).ToArray();	0
20609336	20607187	use custom control in windows forms checked list box	.ToString()	0
25698220	25697744	Dispose process with unknown runtime remaining	public void Destroy(List<PhantomProcessModel> discardedProcesses)\n{\n    ThreadPool.QueueUserWorkItem( (someobj) => \n    {\n        process.WaitForExit(15000);\n        process.Close();\n        process.Dispose();\n        // instance members of List<> are not thread safe\n        lock(discardedProcesses) \n        {\n            discardedProcesses.Remove(this);\n        }\n    });\n}	0
22414778	22413643	Need to enable or disable tabs in RadTabStrip based on a session variable	case "1":\n                    BillPayNavigationRadTabStrip.Tabs[0].Enabled = true;\n                    BillPayNavigationRadTabStrip.Tabs[0].Selected = true;\n                    BillPayNavigationRadTabStrip.Tabs[1].Enabled = false;\n                    BillPayNavigationRadTabStrip.Tabs[2].Enabled = false;\n                    BillPayNavigationRadTabStrip.Tabs[3].Enabled = false;\n                    BillPayNavigationRadTabStrip.Tabs[4].Enabled = false;\n                    BillPayRadMultiPage.SelectedIndex = 0;\n                    break;	0
23853235	23853205	Cannot get SQL query to store results into variables	int interest 01 = (Int16)dr["I01"];	0
11226674	11224711	When to access Static Button in ListView EmptyItemTemplate and ItemTemplate?	OnItemDataBound event\n\nprotected void Expenses_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n\n    if (e.Item.ItemType == ListViewItemType.DataItem)\n    {\n\n       TextBox tbEditAbout = (TextBox)e.Item.FindControl("tbEditAbout");\n    }\n}	0
23457929	23457651	Access to inner attribute with XMLSerializer	public class A_el\n{\n    [System.Xml.Serialization.XmlAttribute("ID")]\n    public int id { get; set; }\n\n    [System.Xml.Serialization.XmlArray(ElementName = "Fields")]\n    [System.Xml.Serialization.XmlArrayItem("Field", typeof(Field))]\n    public Field[] Fields { get; set; }\n\n    private string[] _A_elements;\n    private string[] A_elements\n    {\n        get\n        {\n            if(null == _A_elements)\n            {\n                _A_elements = (from field in Fields select field.Value).ToArray();\n            }\n            return _A_elements;\n        }\n    }\n}\n\n[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]\npublic partial class Field\n{\n    public string Title { get; set; }\n    public string Value { get; set; }\n\n    [System.Xml.Serialization.XmlAttributeAttribute()]\n    public string Hint { get; set; }\n}	0
5476552	5476361	How do I remove a row in one table based on another table?	delete from TableA\nwhere ColID in (select colid from tableB)	0
25937198	25936298	Uploading file via WebClient	try\n    {\n        //some cool stuff with webClient\n    }\n    catch (WebException ex)\n    {\n        using (var stream = ex.Response.GetResponseStream())\n        using (var reader = new StreamReader(stream))\n        {\n            var s = reader.ReadToEnd();\n\n            throw new Exception(s, ex);\n        }\n    }\n    catch (Exception e)\n    {\n        throw e;\n    }	0
14853948	14853836	How yield works in c#	Return\nGoto	0
1598374	1598320	How to set the length of a vector (in xna)	vec = Vector3.Normalize(vec) * length;	0
3570665	3570631	Dictionary<Foo, List<Bar>> How to assign the list to a property of the key with LINQ?	var foos = myDict.Select(kvp =>\n           {\n               kvp.Key.Bars = kvp.Value;\n\n               return kvp.Key;\n           }).ToList();	0
18917098	18916564	Removing items from an object where linked model has 0 items	car.Features.ToList().Count	0
27419067	27418954	How to get a String in a StringList ? C#	m_Category = new StringList() { x.Value };	0
6167986	6167865	Can't think of query that solves this many to many	var courseViews = from c in db.Courses\n                  select new CourseView()\n                  {\n                      CourseID = c.ID,\n                      ProfessorName = (from l in c.Leturers \n                                       where l.Is_Professor \n                                       select l.Name).FirstOrDefault(),\n                      AssistantNames = (from l in c.Leturers \n                                        where !l.Is_Professor \n                                        select l.Name).ToList()\n                  };	0
18648151	18603858	How to fill AvalonDock 2.0 application only with AnchorableWindows - no DocumentPane	if (emptyPane is LayoutDocumentPane &&\n                    this.Descendents().OfType<LayoutDocumentPane>().Count(c => c != emptyPane) == 0)\n                    continue;	0
13231863	7566426	WebP library for C#	using (Image image = Image.FromFile("image.jpg"))\n{\n   Bitmap bitmap = new Bitmap(image);\n   WebPFormat.SaveToFile("image.webp", bitmap);\n}	0
31995671	31995361	Searching through many excel files in same folder (C#)	public static string[] GetFiles(\n    string path,\n    string searchPattern,\n    SearchOption searchOption\n)\n\nforeach (string fil in Directory.GetFiles(dir, "*.xls"))\n{\n  //do some stuff with your .xls files\n}	0
9362943	9362900	How to increment a variable every n iterates according to some condition?	int scale = dt.Rows.Count > 0 ? 2 : 3;\n\nfor (int i = 0; i < Main_dt.Rows.Count; i++)\n{\n    int j = i / scale;\n    ...\n}	0
25379172	25336280	How to wait for a specific thread of Threadpool	try\n        {\n\n            IAsyncResult result = addProgress.BeginInvoke(session, progress, null, null);\n           result.AsyncWaitHandle.WaitOne(timeoutValue);\n\n\n        }\n        catch (Exception ex)\n        {\n\n        }\n        finally\n        {\n            addProgress = null;\n\n        }\n\n\n    }	0
6533615	6533433	Creating XML file with write access given to all the windows account users	System.Security.AccessControl.FileSecurity fsec = System.IO.File.GetAccessControl(fileName);\nfsec.AddAccessRule( new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.Modify, System.Security.AccessControl.AccessControlType.Allow));\nSystem.IO.File.SetAccessControl(fileName, fsec);	0
33068230	33068145	linq select parent element from xml based on multiple child element	XElement record = xmldoc.Element("config")\n    // from all client elements\n    .Elements("client")    \n    // filter the one that has child element <domain> with value domain_name\n    .Where(x=>x.Descendants("domain").Any(v=>v.Value == domain_name))\n    // select only one or default\n    .SingleOrDefault();	0
15179648	15179360	Fluent NHibernate automatically deletes data	.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true))	0
942504	942458	Use Attribute to create Request IP constraint	public class InternalOnly : FilterAttribute\n{\n    public void OnAuthorization (AuthorizationContext filterContext)\n    {\n    if (!IsIntranet (filterContext.HttpContext.Request.UserHostAddress))\n    {\n    throw new HttpException ((int)HttpStatusCode.Forbidden, "Access forbidden.");\n    }\n    }\n\n    private bool IsIntranet (string userIP)\n    {\n    // match an internal IP (ex: 127.0.0.1)\n    return !string.IsNullOrEmpty (userIP) && Regex.IsMatch (userIP, "^127");\n    }\n}	0
34153038	34152874	Data rows are being added with no data in my table, need a if statement to stop this?	if(!string.IsNullOrEmpty(Navn) && !string.IsNullOrEmpty(Emne) && !string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Besked))\n{\n    cmd.CommandText = "INSERT INTO Kontakt (Navn, Emne, Email, Besked) VALUES (@Navn, @Emne, @Email, @Besked)";\n    cmd.Parameters.AddWithValue("@Navn", Navn);\n    cmd.Parameters.AddWithValue("@Emne", Emne);\n    cmd.Parameters.AddWithValue("@Email", Email);\n    cmd.Parameters.AddWithValue("@Besked", Besked);\n\n    conn.Open();\n    cmd.ExecuteNonQuery();\n    conn.Close();\n}	0
32974919	32974237	How do I draw a grid with 3 columns where 2 columns size to content?	modelTitle.LayoutParameters = new TableRow.LayoutParams(0, LayoutParams.WrapContent, 1f);	0
14813731	14813674	Setting only a setter property	public class SomeModel\n{\n    private string someString = "";\n\n    public string SomeString {\n        get { return this.someString; }\n        set {\n            this.someString = value;\n            this.DoSomeWork();\n        }\n    }\n\n   public void DoSomeWork()\n   {\n      ....\n   }\n}	0
1414900	1414893	LINQ to SQL value BETWEEN two double values	var result = from db.MyTable.Where(d => (double)d.Price >= minValue \n                                         && (double)d.Price <= maxValue)	0
13752500	13752427	Unity - Resolution of the dependency failed (without registering)	.Resolve<MyClass>	0
29213572	29213355	c# how to get XML tag values from a simple XML schema	internal class Data\n{\n    public string UId { get; set; }\n    public string Status { get; set; }\n\n    public Data(string text)\n    {\n        string strRegex = @"<uid>(.*?)</uid>.*?<status>(.*?)</status>";\n        Regex myRegex = new Regex(strRegex, RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);\n\n        var match = myRegex.Match(text);\n        UId = match.Groups[1].Value;\n        Status = match.Groups[2].Value;\n    }\n}	0
10207488	10207447	Remove space from String	string_text = Regex.Replace(string_text, @"\s+", " ");	0
9839547	9837336	Comparing two IEnumerable to detect changes	enum1pos = -1;\nenum2pos = 0;\n  Value2 = enum2.Next()\n  enum2pos++;\nList<int> SkipList = new SkipList();\nwhile(enum1 has values left)\n{\n  Value1 = enum1.Next()\n  enum1pos++;\n  //Skip over moved items.\n  while (SkipList.Count > 0 && SkipList[0] == enum2.Position)\n  {\n    Value2 = enum2.Next()\n    enum2pos++;\n  }\n  if (Value1 == Value2)\n    Value2 = enum2.Next()\n    enum2pos++;\n    continue;\n\n  int temp = enum2pos;\n  while(Value1 !=Value and enum2 has more values)\n  {\n    Value2 = enum2.Next();\n    enum2pos++;\n  }\n  if(Value1 != Value2)\n    ItemDeleted(Value1);\n  else\n  {\n    ItemMoved(Value1, enum2pos);\n    SkipList.Add(enum2pos);\n  }\n  //This is expensive for IEnumerable!\n  enum2.First();\n  loop temp times\n    enum2.Next();\n  //if \n}\nwhile (enum2 has values left)\n{\n  while (SkipList.Count > 0 && SkipList[0] == enum2.Position)\n  {\n    Value2 = enum2.Next()\n    enum2pos++;\n  }\n  if (enum2 has values left)\n  Added(Value2, enum2pos)\n}	0
19789358	19787920	LINQ or REGEX to extract certain text from a string	private static void regexString()\n{\n    string myString = "[{\"ta_id\":97497,\"partner_id\":\"229547\",\"partner_url\":\"http://partner.com/deeplink/to/229547\"},{\"ta_id\":97832,\"partner_id\":\"id34234\",\"partner_url\":\"http://partner.com/deeplink/to/id34234\"}]";\n\n    string[] stringList = Regex.Split(myString, "},{");\n\n    for (int i=0; i<stringList.Length ;i++)\n    {\n        stringList[i] = Regex.Split(Regex.Split(stringList[i], "partner_id\\\":\\\"")[1], "\\\",\\\"partner_url\\\"")[0];\n    }\n}	0
6831470	6553002	WinForms - Embedding CNN Live Video URL	protected void webBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)\n    {\n        if (webBrowser.ReadyState == WebBrowserReadyState.Complete && DefaultPage == BrowserPage.CNN)\n        {\n            HtmlElement head = webBrowser.Document.GetElementsByTagName("head")[0];\n            HtmlElement scriptElement = webBrowser.Document.CreateElement("script");\n            IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;\n            string popupBlocker = "if(typeof settings != 'undefined') { settings.FORCE_POPUP = false; }";\n            element.text = popupBlocker;\n            head.AppendChild(scriptElement);\n        }\n    }	0
29568081	29567432	Linq to XML: Bind child nodes to DataList	var products = XElement.Load(Server.MapPath("/app_data/productList.xml"));\nvar childDetails = from child in products.Descendants("product")\n    where (string)child.Element("sku").Value == strSku\n    from childProducts in products.Descendants("child-product")\n    select new\n    {\n        childSku = childProducts.Elements("child-sku").First().Value,\n        childName =  childProducts.Elements("child-name").First().Value,\n        childPrice = childProducts.Elements("child-price").First().Value\n    }\nchildItems.DataSource = childDetails;\nchildItems.DataBind();	0
9431190	9431067	Read bytes from NetworkStream (Hangs)	string server = "google.com";\n  int port = 80;\n  string message = "GET /\n";	0
1428474	1428435	One way to compare array	if(list1.Count == list2.Count)\n{\n    var list3 = list1.Intersect(list2);\n    return list3.Count == list1.Count();\n}	0
24903553	24857138	Windows Phone - link to the publisher in the app store	zune://search/?publisher=Henry%20Chong;	0
19585344	19585164	Accessing a method from a static routine c#	public static void CreateLogFile(string path, string msg)\n    { \n        string sLogFormat;\n        string sErrorTime;\n\n        //sLogFormat used to create log files format :\n        // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message\n        sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";\n\n        //this variable used to create log filename format "\n        //for example filename : ErrorLogYYYYMMDD\n        string sYear = DateTime.Now.Year.ToString();\n        string sMonth = DateTime.Now.Month.ToString();\n        string sDay = DateTime.Now.Day.ToString();\n        sErrorTime = sYear + sMonth + sDay;\n\n        StreamWriter sw = new StreamWriter(path + sErrorTime, true);\n        sw.WriteLine(sLogFormat + msg);\n        sw.Flush();\n        sw.Close();\n\n    }	0
17974687	17974607	how to use eager loading without string for related entities?	using System.Data.Entity;	0
23649773	23649701	Creating an instance from a class defined by a string	IModel model = (IModel)Activator.CreateInstance(Type.GetType(typeName));	0
14236008	14235468	Numeric TextEdit control +/- sign	textEdit1.Properties.Mask.EditMask = "+#0.00;-#0.00";\ntextEdit1.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;\ntextEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;	0
25811917	25811613	How many threads is optimal in this scenario	Parralel.For	0
11788831	11788811	Dynamically add content in C#	foreach (var status in facebookStatus)\n    {\n        Label lblStatus = new Label();\n        lblStatus.Text = status;\n        this.Controls.Add(lblStatus);\n    }	0
13094766	11829643	Windows 8 Metro RichTextColumns embed hyperlinks and images	public void AddLink(XElement element)\n    {\n        var link = element.Attribute("href").Value;\n\n        InlineUIContainer uc = new InlineUIContainer();\n        TextBlock tb = new TextBlock();\n        tb.Margin = new Thickness(0, 0, 0, 0);\n        var run = new Run();\n        run.Text = element.Value;\n        tb.Inlines.Add(run);\n        tb.Tapped += (s, e) =>\n        {\n            Launcher.LaunchUriAsync(new Uri(link, UriKind.Absolute));\n        };\n        uc.Child = tb;\n        paragraph.Inlines.Add(uc);\n    }	0
16667366	16667244	Controlling a PictureBox from a class	private void pictureBox1_Click(object sender, EventArgs e)\n{\n    Access ac = new Access();\n    ac.PictureClicked(sender);\n}\n\n\n public void PictureClicked(Object Sender)\n{\n           picBox = (PictureBox)Sender;\n           picBox.Image = Properties.Resources.apple;\n }	0
3125721	3125676	Generating a good hash code (GetHashCode) for a BitArray	public int GetHashCode()\n{\n    int hash = 17;\n    hash = hash * 23 + field1.GetHashCode();\n    hash = hash * 23 + field2.GetHashCode();\n    hash = hash * 23 + field3.GetHashCode();\n    return hash;\n}	0
4059196	4059164	A way to avoid a virtual call in constructor	abstract class Car\n{\n    public abstract Engine CarEngine { get; protected set; }\n\n    public Car(Engine carEngine)\n    {\n        CarEngine = carEngine;\n        CarEngine.EngineOverheating += new EventHandler(CarEngine_EngineOverheating);\n    }\n\n    void CarEngine_EngineOverheating(object sender, EventArgs e)\n    {\n        // Subscribing to the event of all engines \n    }\n}\n\nsealed class Toyota : Car\n{\n    public Toyota()\n        : base(new ToyotaEngine())\n    {\n    }\n\n\n    public override Engine CarEngine { get; protected set; }\n}	0
8406334	8405643	Calculate bounds multiple elements silverlight	List<Point> Points = new List<Point>();\n\n        foreach (UIElement x in cvsMain.Children.Where(ui => ui.GetType() == typeof(Rectangle)))\n        {\n            // Obtain transform information based off element you need to find position within\n            GeneralTransform gt = x.TransformToVisual(cvsMain);\n\n            // Find the four corners of the element\n            Points.Add(gt.Transform(new Point(0, 0)));\n            Points.Add(gt.Transform(new Point((x as Rectangle).Width, 0)));\n            Points.Add(gt.Transform(new Point(0, (x as Rectangle).Height)));\n            Points.Add(gt.Transform(new Point((x as Rectangle).Width, (x as Rectangle).Height)));\n        }\n\n        Double Left = Points.Min(p => p.X);\n        Double Right = Points.Max(p => p.X);\n        Double Top = Points.Min(p => p.Y);\n        Double Bottom = Points.Max(p => p.Y);	0
18674140	18671464	Resource design to get user's activities	/users\n/user/{userId}\n/user/{userId}/activities\n/user/{userId}/activity/{activityId}	0
12667539	12667415	Determine if string has all unique characters	bool[] array = new bool[256]; // or larger for Unicode\n\nforeach (char value in text)\n  if (array[(int)value])\n    return false;\n  else\n    array[(int)value] = true;\n\nreturn true;	0
4938851	4938821	referencing a table in a dataset by name	myDataSet.Tables["AdvBusiness"]	0
28189969	28189383	Inserting a row in MS Access from c#	string my_querry2 = "INSERT INTO Table(id, field1, field2, field3, field4)VALUES(@paramPath,@paramLength,@paramName,@paramValue3,@paramDate)";\n        OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);\n        cmd2.Parameters.Add(new OleDbParameter("@paramPath", path));\n        cmd2.Parameters.Add(new OleDbParameter("@paramLength", length));\n        cmd2.Parameters.Add(new OleDbParameter("@paramName", name));\n        cmd2.Parameters.Add(new OleDbParameter("@paramValue3", value3));\n        cmd2.Parameters.Add(new OleDbParameter("@paramDate", date));\n        cmd2.ExecuteNonQuery();	0
11385304	11385235	how to Get a Process CurrentThreadId in C#?	public void GetProcessId()\n    {\n        var processList = System.Diagnostics.Process.GetProcessesByName("taskmgr");\n\n        // note that you get a list, there may be multiple processes returned\n        foreach (var process in processList)\n        {\n            // print out the process id\n            System.Console.WriteLine("Process Id=" + process.Id);\n        }\n    }	0
10002392	10002346	Print File With .Net	Print()	0
4015327	4015288	Pick a date from the datetimepicker	var timeSpan = dateTimePicker2.Value - dateTimePicker1.Value;\nvar rentalDays = timeSpan.Days;\n...	0
2255293	2255129	Comma Separated string Built In .NET	List<string> temp = new List<string>();\n    temp.Add("a");\n    temp.Add("b");\n    temp.Add("c");\n    CommaDelimitedStringCollection cdsc = new CommaDelimitedStringCollection();\n    cdsc.AddRange(temp.ToArray());\n    Console.WriteLine(cdsc.ToString());	0
15880533	15877828	How to implement Matlab's "rate transition" (in C#)	% Sampling frequency\nFs1 = 10e3;\nFs2 = 4e3;\n\n% Load your data\ny = load('yourdata'); %y=sin(0:1/Fs1:1);\nTtime = (length(y)-1)*(1/Fs1);\n\n% X-Axis\nx  = 0:1/Fs1:Ttime;\nxi = 0:1/Fs2:Ttime;\n\n% Zero-order hold\nyi = zeros(length(xi),1);\njj = 1;\nxi(1) = x(1);\nfor ii=2:length(y)\n    % Update value\n    if (x(ii)>=xi(jj)),\n        yi(jj) = y(ii-1);\n        jj = jj+1;\n    end\nend\n\n% Plot\nfigure\nhold on\nscatter(x,y,'b');\nscatter(xi,yi,'r');\nhold off\nlegend('Fs=10k','Fs=4k')	0
12179301	12178985	Determining a FileAttribute for a file in case of "Access Denied":	private void SearchDirectory(string folder)\n{\n    foreach (string file in Directory.GetFiles(folder))\n    {\n        try \n        {\n            // do work;\n        }\n        catch \n        {\n            // access to the file has been denied\n        }\n    }\n    foreach (string subDir in Directory.GetDirectories(folder))\n    {\n        try \n        {   \n             SearchDirectory(subDir);\n        }\n        catch \n        {\n            // access to the folder has been denied\n        }\n\n    }\n}	0
24489452	24489316	get/set a property by expression	public void AddMapping<T>(fieldName, Expression<Func<TParent, T>> propExpr)\n{\n    var memberExpr = (MemberExpression)propExpr.Body;\n    PropertyInfo property = (PropertyInfo)memberExpr.Member;\n    ...\n}	0
7445261	7445182	Find out File Owner/Creator in C#	string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();	0
29958477	29958244	taking multiple strings from text boxes and entering them into a Checked List Box C#	private void addButton_Click(object sender, EventArgs e)\n{\n    string newItem = String.Format("{0} - {1} - {2} - {3}",\n        titleTextBox.Text, \n        descriptionTextBox.Text, \n        priorityTrackbar.Value,\n        endDateTimePicker.Value.ToShortDateString()\n        );\n\n    this.checkListBox.Items.Add(newItem);\n}	0
4250947	4250910	Remove Elements from one Queue that are present in another queue	var qN = new Queue<int>(new[]{3, 4, 9, 11});\nvar qA = new Queue<int>(new[]{1, 2, 3, 4, 8, 9, 11, 12, 13});\nvar qR = qA.Except(qN);	0
30769991	30769762	How to select documents by field range of values in MongoDB C# driver?	var collection = database.GetCollection<Item>("Item");\nvar list = await collection.Find(x => locationIds.Contains(x.LocationId)).ToListAsync();	0
7821274	7821175	LinkButton on GridView - after selected	protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n    int selectedRowIndex = Convert.ToInt32(e.CommandArgument);\n    var row = Gv.Rows[selectedRowIndex ];\n    var btn = row.FindControl("LinkButton1") as LinkButton;\n    if(btn != null)\n    {\n       btn.visible = false;\n    }\n\n}	0
23231197	23231101	long value to date c#	long dateL = 13928550480000;\n\n    DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n    DateTime date = start.AddMilliseconds(dateL/10).ToLocalTime();\n                                         //    ***\n                                         //     ^------\n\n    var dtstr1 = date.ToString("MM/dd/yyyy");  // 02/19/2014	0
25728316	25724186	How to check if Map center point is changed in windows phone 8	bool callcenter = false;\nbool morecenter = false;\nif (callcenter == false)\n{\n    callpcenter = true;\n    //DO SOMETHING\n    callcenter = false;\n    if (morecenter == true)\n    {\n        //CALL FUNCTION AGAIN\n        morecenter = false;\n    }\n    else\n    {\n       morecenter = true;\n    }\n}	0
9026041	9025957	Get the number of word occurrences in text	string original = "peter piper picked a pack of pickled peppers, the peppers were sweet and sower for peter, peter thought";\n\nvar words = original.Split(new[] {' ',','}, StringSplitOptions.RemoveEmptyEntries);\nvar groups = words.GroupBy(w => w);\n\nforeach(var item in groups)\n    Console.WriteLine("Word {0}: {1}", item.Key, item.Count());	0
23912439	23912218	Display pop up with animated gif while loading file	//...\nf.Show();\nBackgroundWorker bw = new BackgroundWorker();\n\nbw.DoWork += (ss, ee) =>\n{\n    ee.Result = PrepareData(directory); // prepare all data required to build the Tree\n}\n\nbw.RunWorkerCompleted += (ss, ee) => \n{\n    BuildTreeByData(ee.Result, addInMe, clicked);\n    f.Close();\n}\n\nbw.RunWorkerAsync();	0
15312331	15312212	Get string of item from checkboxlist	string s = "";\nforeach (var item in checkedListBox1.Items)\n{\n        s = item.ToString();\n         // do something with the string\n}	0
976596	976576	How to use regex to split set-cookie header	Dim r as Regex = new Regex("(.+?)=(.+)")\nDim cookie as string = "test_cookie=blah;bleh"\nDim name as string = r.Match(cookie).Groups(1).ToString()\nDim value as string = r.Match(cookie).Groups(2).ToString()	0
25160552	25160486	c# Numbers stored in string to variables conversion	string numbers = "1234 456 78 4.25847";\n\n    string[] splitedNumbers =  numbers.Split(' ');\n\n    int a = Convert.ToInt32(splitedNumbers[0]);\n    int b =Convert.ToInt32(splitedNumbers[1]);\n    int c = Convert.ToInt32(splitedNumbers[2]);\n    double d = Convert.ToDouble(splitedNumbers[3]);	0
8807227	8807163	How to get a value from a child node using a dataset	ds.Tables[1].Rows[0]["ligne1"].ToString();	0
1216698	1216681	What is the best method to loop through TreeView nodes and retrieve a node based on certain value?	Dictionary<string, TreeNode>	0
27985747	27980575	Programmatical vcard generation. Url Parameter any differences between outlook and non outlook?	URL;TYPE=WORK:http://MySeite.com	0
11328079	11327888	Table layout panel cell bounds and control collision	if (direction != Direction.Vertical)\n{\n    container.Left = Math.Max(0, e.X + container.Left - DragStart.X);\n    container.Left = Math.Min(container.Left, container.Parent.Width - container.Width;\n}\nif (direction != Direction.Horizontal)\n{\n    container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);\n    container.Top = Math.Min(container.Top, container.Parent.Height - container.Height;\n}	0
27834686	27834288	Find Enum Type from string and return enum values as List<string>	public Type DeepSearchType(string name)\n{\n    if(string.IsNullOrWhiteSpace(name))\n       return null;\n\n    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())\n    {\n        foreach (Type t in a.GetTypes())\n        {\n            if(t.Name.ToUpper() == name.ToUpper())\n               return t;\n        }\n    }\n\n    return null;\n}\n\npublic List<string> GetEnumValues(string enumName)\n{\n    List<string> result = null;\n\n    var enumType = Type.GetType(enumName);\n\n    if(enumType == null)\n       enumType = DeepSearchType(enumName);\n\n    if(enumType != null)\n    {\n        result = new List<string>();\n\n        var enumValues = Enum.GetValues(enumType);\n\n        foreach(var val in enumValues)\n            result.Add(val.ToString());\n    }\n\n    return result;\n}	0
8352590	8352234	How to Correctly Multi-Thread a DLL Called at Run-Time in C#	public void SomeMethod()\n    {\n\n\n        Thread thread = new Thread(new ThreadStart(() =>\n        {\n            // this code is going to be executed in a separate thread\n            MessageBox.Show("hello");    \n\n            // place additional code that you need to be executed on a separate thread in here            \n\n        }));\n\n        thread.Start();\n    }	0
5989647	5989623	process argument with spaces	p.StartInfo.Arguments = "-R -H -h sinsscm01.ds.net \"/SASE Lab Tools\"";	0
20638668	20626503	render content in regular model view	public class PhoneController : TwilioController  \n   public ActionResult Hello() {\n\n      var response = new TwilioResponse();\n      response.Say(name);\n\n      return TwiML(response);    \n   }\n}	0
911729	911717	Split string, convert ToList<int>() in one line	var numbers = sNumbers.Split(',').Select(Int32.Parse).ToList();	0
22692898	22692503	XCData and White Spaces	node.Add(new XElement("NodeName", "  ", new XCData("Value")));	0
11313734	11313664	LINQ-Query with multiple groupby	list.GroupBy(o => new { o.Name, o.Value, o.Date })\n    .Select(g => new { g.Key.Name, g.Key.Value, g.Key.Date, Count = g.Count() })	0
31400042	31399889	write generic method for paging	public static bool FindPage<T>(object modelId, IEnumerable<T> entities, int pageSize, int calculatedPage, int? id)\n    {\n        if (modelId != null) {\n            calculatedPage = 0;\n            IEnumerable<IEnumerable<T>> pp = entities.Partition(pageSize);\n            int page = 0;\n            bool found = false;\n            foreach (var item in pp) {\n                page++;\n                IEnumerable<T> inner = item as IEnumerable<T>;\n                foreach (var product in inner) {\n                    if (id == (int)modelId) {\n                        found = true;\n                        break;\n                    }\n                }\n                if (found)\n                    break;\n            }\n            if (found)\n                calculatedPage = page;\n            else\n                calculatedPage = 0;\n\n            return found;\n        }\n        return false;\n    }	0
4004191	4004173	C# : How to add data data from a ListView control to a Dictionary	Dictionary<String, String> Dic = listView.Items\n    .Cast<ListViewItem>()\n    .ToDictionary(x => x.Text, x => x.SubItems[0].Text);	0
21475211	21475168	VBA Match to C#	result = Application.WorksheetFunction.Match(stringA, Range(stringB), 0);\nif (iTemp_result == 0) \nDoStuff();	0
2375762	2375735	Doing a Math.Round(x,2) on a decimal value, but need to ensure 2 numbers after decimal as its money	money.ToString("0.00")	0
32420218	32419909	C# : how to get value from specific column from SQL Server and store into variable	while (dr.Read())\n    {\n           string userid=dr["sql_column_name"].ToString();\n           //rest of the code...\n    }	0
15763975	15763881	Get Count of DataSet.Tables rows based on criteria	int rowCount = MyDatabaseDataSet.Tables["Table2"].AsEnumerable()\n    .Count(r => r.Field<int>("ID") == 250);	0
9499565	9498193	How can I add text to my rowheaders in a datagridview, C#?	/// <summary>\n    /// Which row is currently being rendered\n    /// </summary>\n    protected int RowIndex { get; set; }\n\n    protected override void OnLoad(EventArgs e)\n    {      \n      this.RowIndex = 0;\n      this.DataGrid.DataSource = new string[] { "a", "b", "c" }; // bind the contents\n      this.DataGrid.DataBind();      \n    }\n\n    /// <summary>\n    /// When an item is bound\n    /// </summary>\n    protected void OnItemDataBound(object sender, DataGridItemEventArgs e)\n    {\n      this.RowIndex++;\n      Label label = e.Item.FindControl("RowLabel") as Label;\n      if (label != null)\n      {\n        label.Text = this.RowIndex.ToString();\n      }\n    }	0
3423787	3423487	Show MDI child Always on top of other MDI child	static Form f1 = new Form();\n  static Form f2 = new Form();\n  static Form f3 = new Form();\n\n  [STAThread]\n  static void Main()\n  {\n     f1.IsMdiContainer = true;\n     f2.MdiParent = f1;\n     f3.MdiParent = f1;\n     f1.Show();\n     f2.Show();\n     f3.Show();\n     f2.Activated += new EventHandler(f2_Activated);\n     Application.Run(f1);\n  }\n\n  static void f2_Activated(object sender, EventArgs e)\n  {\n     f3.Activate();\n  }	0
29361795	29360980	Show data from two model with same column name same value in ASP.NET	var Query=Register.Join(Due,r=>r.Location,d=>d.Location,(r,d)=>new {r,d}).Where(\nX=>X.r.Location = X.d.Location &&  X.r.Item = X.d.Item).Select(X=>new {\nLOCATION_1 =X.r.Location;\nITEM_1=X.r.Item;\nLOCATION_2=X.d.Location;\nITEM_2=X.d.Item;\nDWEEK=X.d.DWeek;\nDTEAR=X.d.DYear;\nMODEL=X.r.Model;\nTAGNO_1=X.r.Tag_No;\nTAGNO_1=X.d.Tag_No;\n}).ToList();	0
4502953	4502920	c# how to get the row number from a datatable	int index = dt.Rows.IndexOf(row);	0
19776009	19775452	Regex masking of words that contain a digit	string input = "this is a a1234 b5678 test string";\nstring output = "";\nstring[] temp = input.Trim().Split(' ');\nbool previousNum = false;\nstring tempOutput = "";\nforeach (string word in temp)\n{\n    if (word.ToCharArray().Where(x => char.IsDigit(x)).Count() > 0)\n    {\n        previousNum = true;\n        tempOutput = tempOutput + word;\n    }\n    else\n    {\n        if (previousNum)\n        {\n            if (tempOutput.Length >= 4) tempOutput = "xxxx" + tempOutput.Substring(tempOutput.Length - 4, 4);\n            output = output + " " + tempOutput;\n            previousNum = false;\n        }\n        output = output + " " + word;\n    }\n}\nif (previousNum)\n{\n    if (tempOutput.Length >= 4) tempOutput = "xxxx" + tempOutput.Substring(tempOutput.Length - 4, 4);\n    output = output + " " + tempOutput;\n    previousNum = false;\n}	0
11675920	11675630	htmlagilitypack: Find second table within a div	var secondTable = res.SelectSingleNode("//table[2]");	0
6336263	6336239	Copy DataGridView's rows into another DataGridView	private DataGridView CopyDataGridView(DataGridView dgv_org)\n{\n    DataGridView dgv_copy = new DataGridView();\n    try\n    {\n        if (dgv_copy.Columns.Count == 0)\n        {\n            foreach (DataGridViewColumn dgvc in dgv_org.Columns)\n            {\n                dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);\n            }\n        }\n\n        DataGridViewRow row = new DataGridViewRow();\n\n        for (int i = 0; i < dgv_org.Rows.Count; i++)\n        {\n            row = (DataGridViewRow)dgv_org.Rows[i].Clone();\n            int intColIndex = 0;\n            foreach (DataGridViewCell cell in dgv_org.Rows[i].Cells)\n            {\n                row.Cells[intColIndex].Value = cell.Value;\n                intColIndex++;\n            }\n            dgv_copy.Rows.Add(row);\n        }\n        dgv_copy.AllowUserToAddRows = false;\n        dgv_copy.Refresh();\n\n    }\n    catch (Exception ex)\n    {\n        cf.ShowExceptionErrorMsg("Copy DataGridViw", ex);\n    }\n    return dgv_copy;\n}	0
33989168	33988933	Turn dat file into matrix, include empty spaces	//read all lines\nvar lines = System.IO.File.ReadAllLines("C:/path/to/file.txt");\n\n//loop through all lines\nforeach(var line in lines)\n{\n    //split the line\n    var splitString = line.Split(new char[] { '\t' });\n\n    //pull out some data from the 6th column\n    double avDP = double.Parse(splitString[5]);\n\n    //save the data wherever you want\n}	0
32345817	32331302	In Castle Windsor WCF Facility, how do I access endpoint address?	var service = container.Resolve<IService>();\nvar meta = (IWcfChannelHolder) service;\nvar channel = (IClientChannel) meta.Channel;\nvar address = channel.RemoteAddress;	0
638981	638859	how to update listbox items with INotifyPropertyChanged	private void button1_Click(object sender, EventArgs e)\n{\n    Person newStart = (Person)listBox1.SelectedItem;\n    if (newStart != null)\n    {\n        PersonManager.Instance.StartPerson = newStart;\n        newStart.Name = newStart.Name; // Dumb, but forces a PropertyChanged event so the binding updates\n    }\n}	0
23740281	23739839	Mass Updating Single Database in MVC App	return View();	0
1741331	1741327	C# how to use the \ character in a char datatype	MyString.Value.TrimEnd('\\');	0
19723605	19723314	Updating DataGrid from multiple threads	this.Invoke((Action)delegate\n{\n    //Edit the DataGrid however you like in here\n});	0
14058291	14058249	read text file and writing to a list	File\n    .ReadAllLines(path)\n    .Select(a => a.Split(new[] { '|' }, StringSplitOptions.None))\n    .Select(a => new {\n        Column1 = a[2].Trim(),\n        Column2 = a[5].Trim(),\n        Column3 = a[6].Trim(),\n        Column4 = a[11].Trim()\n    })\n    .ToList();	0
10314390	10314280	Sorting one table result by highest count of items from another table	var topVotedProducts = \n    Votes.Where(v => v.DateTimeCreated > DateTime.Now.AddHours(-24))\n        .GroupBy(v => v.ProductID)\n        .Join(Products, g => g.Key, p => p.ID, (g,p) => new { cnt = g.Count(), prod = p.Name })\n        .OrderByDescending(result => result.cnt);	0
34568220	34568093	How pass in data from a .txt file and construct them separately in a inherited class	string line;\nList<product> promotions = new List<product>();\n\n// Read the file and display it line by line.\nSystem.IO.StreamReader file = \n    new System.IO.StreamReader(@"c:\yourFile.txt");\nwhile((line = file.ReadLine()) != null)\n{\n    string[] words = line.Split(',');\n    if(words.length == 4)\n    {\n        promotions.Add(new Promotion(words[0],words[1],words[2],words[3]));\n    }\n    else\n    {\n        promotions.Add(new product(words[0],words[1],words[2]));\n    }\n}\n\nfile.Close();	0
10433123	10433098	Directory name from path	Path.GetFileName()	0
26837631	26795287	Get user shared tasks from Outlook interop using C#	var module = (Outlook.TasksModule)oApp.ActiveExplorer().NavigationPane.Modules.GetNavigationModule(Outlook.OlNavigationModuleType.olModuleTasks);\nforeach (Outlook.NavigationGroup navigationGroup in module.NavigationGroups)\n  {\n    foreach (Outlook.NavigationFolder navigationFolder in navigationGroup.NavigationFolders)\n    {   \n      LoadTasksFromFolder(navigationFolder.Folder,dbTasks,navigationFolder.Session.Categories);\n    }\n  }	0
10233701	10233334	How to Improve Split Every nth character AND not cut off words	int idx = 0;\nwhile (idx < str.Length)\n{\n    int endIdx = idx + chunkSize;\n    if (endIdx >= str.Length)\n        endIdx = str.Length;\n    else if (splitAtSpaces)\n    {\n        while (str[endIdx] != ' ')\n            --endIdx;\n    }\n    yield return str.Substring(idx, endIdx - idx);\n    idx = endIdx;\n}	0
12598842	12597414	How to correctly extract records from this table?	var innerAssoc = from assoc in user_group\n                 where assoc.group_id == group_id\n                 && dateFrom.Date <= assoc.date.Date\n                 && date.Date <= dateTo.Date\n                 select assoc;\n\nvar outerAssoc = from assoc in user_group\n                 where assoc.group_id == group_id\n                 && assoc.date.Date == user_group\n                 .Where(a => a.user_id == assoc.user_id && a.date.Date <= dateFrom.Date)\n                 .Select(a => a.date.Date).Max()\n                 select assoc;\n\nvar res = innerAssoc.Union(outerAssoc);	0
30076670	30076192	How to send parameters to a webservice method that only accepts one argument in C#	rmcService.CreateCar(new CreateCarServiceRequest\n                    {\n                        UserName = userName,\n                        ViewedUserType = Enum.Parse(typeof(ViewedUserType), viewedUserType)\n                        Accounts = accounts,\n                        CarName = carName\n                    });	0
3244291	3240349	listing all contents of a folder in tfs	var myFolderAtChangeset17 = versionControlServer.GetItems("$/MyFolder", new ChangesetVersionSpec(17), RecursionType.Full);	0
9078773	9078649	Getting DataGrid row details	((class)yourGrid.SelectedItem).ID	0
6985173	6983815	How to broadcast a UDP packet on WP7 Mango?	socket.ConnectAsync(a);	0
5212812	5212739	Repopulate a combo box	threadComboBox.Clear();\n    ListStore store = new ListStore(typeof (string));\n    threadComboBox.Model = store;\n\n    foreach(string s in entries)\n    {\n        string[] fields = someSplit(s);\n        store.AppendValues (fields[0]);          \n    }	0
5458826	5458682	How to save the image to the database after streaming it from an IP camera?	Stream stream = resp.GetResponseStream();\nbyte[] data;\nusing (MemoryStream ms = new MemoryStream())\n{\n  int num_bytes = 0;\n  byte[] temp = new byte[4096];\n  while ((num_bytes = stream.Read(temp, 0, temp.Length)) > 0)\n    ms.Write(temp, 0, bytes);\n  data = ms.ToArray();\n}	0
2332623	2329160	Problem with SerialPort in a C# application	port.Read()	0
24312184	24312042	Wpf TreeView get data item used to bind template	private void BtnSelect_OnClick(object sender, RoutedEventArgs e)\n{\n   var button = sender as Button;\n\n   var dataitem = button.DataContext as [Your DataItem Class Here];\n\n   dataitem.[DoStuffHere]();\n}	0
17974623	14305724	Replace non-decimal in KeyUp	string result = Regex.Replace(Txt, @"[^\d.,]|(?<=[.,][^.,]*)[.,]", "");	0
19451957	19451441	Get items with Active == true only	gridData.Where(c => c.Item.Active).Select([...]);	0
6084990	6084965	Getting clicks to "fall through" a panel	topPanel_OnClick() { bottomPanel_OnClick(topPanel, EventArgs.Empty); }	0
5637587	5637328	Creating 2 numbers from a one #C	int checkCount = 12345;\nint even = 0;\nint odd = 0;\nint reverseEven = 0;\nint reverseOdd = 0;\n\nwhile (checkCount > 0) {\n    int current = checkCount % 10;\n    if (current % 2 == 0) {\n        reverseEven = 10 * reverseEven + current;\n    } else {\n        reverseOdd = 10 * reverseOdd + current;\n    }\n\n    checkCount /= 10;\n}\n\n\nwhile (reverseEven > 0) {\n    even = 10 * even + reverseEven % 10;\n    reverseEven /= 10;\n}\n\nwhile (reverseOdd > 0) {\n    odd = 10 * odd + reverseOdd % 10;\n    reverseOdd /= 10;\n}\n\nConsole.WriteLine("even: {0}", even);\nConsole.WriteLine("odd: {0}", odd);	0
23195122	23194993	How to get all Forms and User Controls in WinForms project?	foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies().Where(a=>!a.FullName.StartsWith("System.") || !a.FullName.StartsWith("Microsoft.")))\n            {\n                var types = a.GetTypes().Where(t => (typeof(Form).IsAssignableFrom(t) || typeof(UserControl).IsAssignableFrom(t) )&& t.IsClass && t.FullName.StartsWith("YourNamespace."));\n\n\n            }	0
21577713	21577541	How can i excute a list of methods using either Action, Delegate or List?	var methods = new List<Action<string, string>> { \n    Method1,\n    Method2,\n    Method3\n};\n\nforeach (var method in methods) {\n    item(a, b);\n)	0
18009514	18009371	Closing with buttons won't end task C#	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication4\n{\n    public partial class Form1 : Form\n    {\n        private Process _process;\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            this._process = Process.Start("notepad.exe");\n        }\n\n        private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n        {\n            if (this._process != null) {\n                this._process.CloseMainWindow();\n                this._process.Close();\n            }\n        }\n    }\n}	0
5438173	5438152	How to get only NEW text from TextBox?	private string old_text = "";\n\nprivate void tbLog_TextChanged(object sender, TextChangedEventArgs e)\n{\n    if(old_text != tbLog.Text)\n    {\n        writeLog(tbLog.Text);\n        old_text = tbLog.Text;\n    }\n}	0
19931151	19930965	How to have lists sharing a same struct instance?	using System;\nusing System.Collections.Generic;\n\nnamespace Test {\n  public class Ptr<T> where T : struct {\n    public T Value { get; set; }\n  }\n\n  class Program {\n    static void Main(string[] args) {\n      var a = new List<Ptr<int>>();\n      var b = new List<Ptr<int>>();\n\n      var ptr = new Ptr<int> { Value = 7 };\n      a.Add(ptr);\n      b.Add(ptr);\n\n      a[0].Value = 3;\n      Console.Out.WriteLine(b[0].Value);\n    }\n  }\n}	0
10290441	10290386	I can I map from a string to a constructor in C#?	var d = new Dictionary<string, Func<IObject>>();\nd.Add("Object1", () => new Object1());\nd.Add("Object2", () => new Object2());\nd.Add("Object3", () => new Object3());\nstring typename = GetAStringFromSomewhere();\nIObject foo = d[typename]();	0
7833151	7832975	Building ffmpeg on Windows	sh configure --enable-static --enable-shared\nmake test\nmake install	0
9836484	9836328	Regex split string on multiple separators with quotes	string test = "\"abc def ghi\" \"%1\" \"%2\"";\n        var splits = test.Split(new string[]{"\" \"","\""},StringSplitOptions.RemoveEmptyEntries);\n        foreach (var split in splits)\n        {\n            Console.WriteLine(split);\n        }	0
4951556	4951294	XML Deserialization not deserializing element	public class Mileage\n{\n   [XmlAttribute(AttributeName = "Unit")]\n   public string Unit {get; set;}\n\n   [XmlText]\n   public int Mileage {get; set;}\n}	0
14338054	14338004	Create array of unique items from DataTable	DataTable myDataTable = new DataTable();\n//......\nstring[] uniqueItems = myDataTable.AsEnumerable()\n                                  .Select(r=> r.Field<string>("MyColumn"))\n                                  .Distinct()\n                                  .ToArray();	0
17747566	17747277	Using C# to send values to Java application	var process = System.Diagnostics.Process.Start(new ProcessStartInfo { RedirectStandardInput = true, RedirectStandardOutput = true, FileName = "javaapp.exe" });\nprocess.StandardInput.WriteLine("Hello");\nvar response = process.StandardOutput.ReadLine();	0
14018149	14017886	Reverse words of a sentence without using String.Split in C#	string inp = "hai how are you?";\nStringBuilder strb = new StringBuilder();\nList<char> charlist = new List<char>();\nfor (int c = 0; c < inp.Length; c++ )\n{\n\n    if (inp[c] == ' ' || c == inp.Length - 1)\n    {\n        if (c == inp.Length - 1)\n            charlist.Add(inp[c]);\n        for (int i = charlist.Count - 1; i >= 0; i--)\n            strb.Append(charlist[i]);\n\n        strb.Append(' ');\n        charlist = new List<char>();\n    }\n    else\n        charlist.Add(inp[c]);\n}\nstring output = strb.ToString();	0
3519563	3519539	How to check if a String contains any of some strings	String.IndexOfAny()	0
8327199	8326672	Looking for a way to have a base36 sequence in C#	public static string Inc(string s){\n\n    System.Func<char,int> v = c => (int)((c<='9')?(c-'0'):(c-'A'+10));\n    System.Func<int,char> ch = d => (char)(d+((d<10)?'0':('A'-10)));    \n\n    s = s.ToUpper();    \n    var sb = new System.Text.StringBuilder(s.Length);\n    sb.Length = s.Length;\n\n    int carry = 1;\n    for(int i=s.Length-1; i>=0; i--){\n        int x = v(s[i])+carry;    \n        carry = x/36;\n        sb[i] = ch(x%36);\n    }\n    if (carry>0)\n        return ch(carry) + sb.ToString();\n    else\n        return sb.ToString();\n}	0
10388645	10388609	simple linq needed	var dic = links.GroupBy(x=>x.SourceID)\n               .ToDictionary(x=> x.Key, x => x.Select(y=>y.TargetId).ToList());	0
1879886	1871811	WPF Save Changes in DataGrid to DataTable	private void dataGrid_CurrentCellChanged(object sender, EventArgs e)\n    {\n        DataTable dt = ((DataView)dataGridQueue.ItemsSource).ToTable();\n        /*Set the value of my datatable to the the changed version before \n         * writing it so a file        \n         */\n        dt.WriteXMLScema(...\n    }	0
23041809	23040176	How to set DataTemplate element during initialization - 'System.Reflection.TargetInvocationException'	ToggleSwitch ts = sender as ToggleSwitch;\n//another lines with code	0
12622743	12620875	call converter in XAML if property of a object in the observable collection changes	public class WorldViewModel : INotifyPropertyChanged\n{\n   private BindingList<Person> m_People;\n   public BindingList<Person> People\n   {\n      get { return m_People; }\n      set\n      {\n         if(value != m_People)\n         {\n            m_People = value;\n            if(m_People != null)\n            {\n               m_People.ListChanged += delegate(object sender, ListChangedEventArgs args)\n               {\n                  OnPeopleListChanged(this);\n               };\n            }\n            RaisePropertyChanged("People");\n         }\n      }\n   }\n\n   private static void OnPeopleListChanged(WorldViewModel vm)\n   {\n      vm.RaisePropertyChanged("People");\n   }\n\n   public event PropertyChangedEventHandler PropertyChanged;\n   void RaisePropertyChanged(String prop)\n   {\n      PropertyChangedEventHandler handler = this.PropertyChanged;\n      if (handler != null)\n      {\n          handler(this, new PropertyChangedEventArgs(prop));\n      }\n   }\n}	0
8811433	8811028	fubumvc - rendering a collection as a drop down list	this.Editors\n    .If(e => e.Accessor.PropertyType.IsEnum)\n    .BuildBy(er =>\n    {\n        var tag = new HtmlTag("select");\n        var enumValues = Enum.GetValues(er.Accessor.PropertyType);\n        foreach (var enumValue in enumValues)\n        {\n            tag.Children.Add(new HtmlTag("option").Text(enumValue.ToString()));\n        }\n\n        return tag;\n    });	0
16571260	16571164	How to return SqlDataReader in C# WCF?	// for instance\nList<string> list = new List<string>();\n\nif (sqlReader != null)\n    {\n        if (sqlReader.HasRows)\n        {\n            while (sqlReader.Read())\n            {\n                //return sqlReader[0].ToString();\n                list.Add(sqlReader[0].ToString());\n            }\n            sqlConn.Close();\n        }\n        else\n        {\n            return null;\n        }\n    }\nreturn list; // ta-da	0
7778053	7777978	How to Display a form with the same name selected in the subitem of listviewitem	var txt = listView1.SelectedItems[0].SubItems[1].Text;\nvar form = new Form();\nform.Text = txt;\nform.ShowDialog();	0
7094576	7093811	How can I find an IndexSet's path in Examine?	IndexSetCollection sets = Examine.LuceneEngine.Config.IndexSets.Instance.Sets;\nIndexSet set = sets["Set_Name"];\nDirectoryInfo dir = set.IndexDirectory;\nstring path = Path.Combine(dir.FullName, "Index");	0
13560881	13560840	How to change CreationTime.ToShortDateString() date format?	fileInfo.CreationTime.ToString("dd/MM/yyyy")	0
24944828	24915671	Bind a value to a custom control inside a repeater	public string paddockName {\n    get { return Convert.ToString(ViewState("paddockName")); }\n    set { ViewState("paddockName") = value; }\n}	0
26858326	26857274	Finding out if a TextBox is valid	var result = Validation.GetErrors([TextBoxInstance]);\nif (result.Count > 0) // has errors.\n{\n    //write your logic here.\n}	0
10920630	10919038	Getting IP address/interface number after a RasDial	using DotRas;\n\nvar conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == "Your Entry").FirstOrDefault();\nRasPppIp ipInfo = conn.GetProjectionInfo(RasProjectionType.IP);	0
25843046	25842238	Get the cell value from cellClick in ObjectListView's TreeListView	private void treeListView1_CellClick(object sender, BrightIdeasSoftware.CellClickEventArgs e)\n    {\n        string s = e.SubItem.ModelValue.ToString();\n    }	0
22575176	22575107	How to extract sub-string in format hh:mm:ss.sssz from any string?	using System.Text.RegularExpressions;\n\n    static void Main(string[] args)\n    {\n\n        string str = "mynewtime10:20:13.458atcertainplace";\n        string patt = @"([0-9:.]+)";\n        Regex rgx = new Regex(patt, RegexOptions.IgnoreCase);\n        MatchCollection matches = rgx.Matches(str);\n        if (matches.Count > 0)\n        {\n            Console.WriteLine("{0} ({1} matches):", str, matches.Count);\n            foreach (Match match in matches)\n                Console.WriteLine("   " + match.Value);\n        }\n            Console.ReadLine();\n    }	0
11794645	11794579	How to round a decimal up?	var val = 96.154M;\n\nvar result = Math.Ceiling(val * 100) / 100.0M;	0
3154388	3154369	Convert VB to C#	if (this.OrdersDataGridView.SelectedRows.Count > 0)\n{\n    NorthwindDataSet.OrdersRow row = (NorthwindDataSet.OrdersRow)\n                                       ((DataRowView)this.OrdersDataGridView\n                                            .SelectedRows(0).DataBoundIte).Row;\n\n    Order editForm = new Order(\n                           this.NorthwindDataSet,\n                           this.NorthwindDataSet.Orders.Rows.IndexOf(row));\n\n    editForm.Show();\n}	0
3572099	3572044	Find parent based on children properties linq to sql	from p in context.Parents\nwhere p.Children.Count == 2 // sounds like you can skip this one\nwhere p.Children.Any(c => c.Number == 0)\nwhere p.Children.Any(c => c.Number == 1)\nselect p;	0
6877375	6877347	How to save image into sql-server using linq?	MyObject.BinaryProperty = new Binary(bytes);	0
13484910	13484901	How to clear default select clause on IQueryable resultset	pQuery = pQuery.Select(e => new EntityResult { \n    ShortDescription = e.ShortDescription \n});	0
8432710	8432637	Focus on last entry in listbox	this.ListBox1.Items.Add(new ListItem("Hello", "1"));\nthis.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;	0
3892879	3891623	c# Granting "Log On As Service" permission to a windows user	private static void GrantLogonAsServiceRight(string username)\n{\n   using (LsaWrapper lsa = new LsaWrapper())\n   {\n      lsa.AddPrivileges(username, "SeServiceLogonRight");\n   }\n}	0
15834288	15834184	Set TextBox Text programmatically and update the model	private string _myValue;\npublic string MyValue\n{\n    get { return _value; }\n    set\n    {\n        _myValue = value;\n        NotifyOfPropertyChanged("MyValue");\n    }\n}	0
3969691	3969476	How to Pass a variable to another Thread	using System;  \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading; \n\nnamespace ConsoleApplication1 \n{ \n  class Program \n  { \n    static void Main(string[] args) \n    { \n        Console.WriteLine("Taking data from Main Thread\n->"); \n        string message = Console.ReadLine(); \n\n        //Put something into the CallContext\n        CallContext.LogicalSetData("time", DateTime.Now);\n\n        ThreadStart newThread = new ThreadStart(delegate { Write(message); }); \n\n        Thread myThread = new Thread(newThread); \n\n    } \n\n    public static void Write(string msg) \n    { \n        Console.WriteLine(msg); \n        //Get it back out of the CallContext\n        Console.WriteLine(CallContext.LogicalGetData("time"));\n        Console.Read(); \n    } \n  } \n}	0
8305776	8239150	Get Windows Service and ASP website on Windows 2008 to read same Registry Keys?	RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)	0
27656724	27656641	Pass parameters to Stored Procedure with single quotes	var name = "Sefa";\nvar query = string.Format("INSERT INTO [People](Name) VALUES('{0}')",name);	0
23426687	23426629	Keep only first 60 characters of a string	string data = Model.Products[i].Description;\nstring temp = string.Empty;\nif(!string.IsNullOrEmpty(data) && data.Length >= 60)\n   temp = data.Substring(0,60);\nelse\n   temp = data;	0
14565703	14564980	Filtering HTML document with 1-10k keywords	IEnumerable<string> keywords = LoadKeywords();\nList<string> list = new List<string>();\nkeywords.AsParallel()\n    .Aggregate(list, (seed, keyword) =>\n    {\n        if(doc.DocumentNode.InnerHtml.Contains(keyword))\n            seed.Add(keyword);\n        return seed;\n    });	0
17860044	17859861	How to use winsock2.h in C#?	using System.Net.Sockets;	0
5403710	5403102	Converting string to UniqueIdentifier - asp.net SQL search based on asp:Label	Guid yourGuid = new Guid(yourString);	0
11153525	11153346	How to assign sql selected result to label from code behind?	lblA.Text = lblB.Text = ... = "No records found";\nusing (var con = new SqlConnection("Data Source=myServerAddress;" +\n        "Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"))\n{\n    con.Open();\n    var com = con.CreateCommand();\n    com.CommandType = CommandType.Text;\n    com.CommandText = @"\n        select s.Name, count(1)as Records from tbl_Case tc\n        inner join tbl_subcase ts on ts.id = tc.Id\n        inner join tbl_supercase tsc on tsc.id = tc.supercaseid\n        inner join course c on c.id = b.courseid\n        where s.isvalid = 1 group by s.Name";\n    using (var read = com.ExecuteReader())\n    {\n        while (read.Read())\n        {\n            if (read["Name"] as string == "A")\n                lblA.Text = Convert.ToString(read["tc"]);\n            else if (read["Name"] as string == "B")\n                lblA.Text = Convert.ToString(read["tc"]);\n            ...\n        }\n    }\n}	0
15784293	15784117	Storing table column value into variable (SQL Server)	string sUserName = txtBoxUsername.Text;\n    SqlConnection conn2 = new SqlConnection("Your SQL Connection");\n\n        SqlCommand myCommand = new SqlCommand("SELECT Email FROM aspnet_Membership WHERE UserName = '"+ sUserName  + "'", conn2);\n\n        SqlDataReader rdr = myCommand.ExecuteReader();\n     if (dr.HasRows)\n    {\n          while (rdr.Read())\n        {\n                 // User exist - get email\n\n                 string email = rdr["Email "].toString();\n\n         }\n    }\n    else\n    {\n          //Error! user not exist\n    }	0
23168808	23164251	Set control text for WPF application	AutomationElement rootElement = AutomationElement.RootElement;\n\nif (rootElement != null)\n{\n    Condition condition =\n            new PropertyCondition(AutomationElement.NameProperty, "WindowSplash");\n\n    AutomationElement appElement =\n            rootElement.FindFirst(TreeScope.Children, condition);\n\n    if (appElement != null)\n    {\n        Condition condition =\n            new PropertyCondition(\n                    AutomationElement.AutomationIdProperty, "element1");\n        AutomationElement element =\n            parentElement.FindFirst(TreeScope.Descendants, condition);\n\n        if (element != null)\n        {\n            ValuePattern valuePatternB =\n                    element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;\n            valuePatternB.SetValue("hello automation world!");\n        }\n    }\n}	0
28799760	28798978	How to Dynamically Create Views?	string connectionString = fmDbSelect();\n        using (SqlConnection connection = new SqlConnection(connectionString))\n        {\n\n            using (SqlCommand command = new SqlCommand())\n            {\n                command.Connection = connection;\n                connection.Open();\n                var scripts = Regex.Split(sql, @"\bGO\b", RegexOptions.Multiline);\n                //var scripts = sql.Split(new string[] { "GO" }, StringSplitOptions.None);\n                foreach (var splitScript in scripts)\n                {\n                    command.CommandText = splitScript;\n                    command.ExecuteNonQuery();\n\n                }\n\n\n            }\n        }	0
28785895	28785470	How to round with fractional digits in C#?	double value = 0.01 * Math.Ceiling(100.0 * originalValue)	0
495587	495557	How can I read a value from an INI file in C#?	using System.IO;\n\nStreamReader reader = new StreamReader(filename);\nwhile(reader.ReadLine() != "[DEVICE]") { continue; }\n\nconst string DeviceNameString = "DeviceName=";\nwhile(true) {\nstring line = reader.ReadLine();\nif(line.Length < DeviceNameString.Length) { continue; }\nelse if(line.Substring(0, DeviceNameString.Length) != DeviceNameString) { continue; }\nreturn line.Substring(DeviceNameString.Length);\n}	0
29149722	29149274	Managing Active Directory securely from another computer	SessionOptions.SecureSocketLayer = true;	0
7443034	7401983	Customize chart in ASP.NET (Microsoft's Chart Controls): how to get x-axis labelling?	string[] xval = { "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX", "ElementX" };\n        for (int i = 0; i < xval.Length; i++)\n        {\n            Chart1.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(i + 0.5, i + 1.5, xval[i]);\n            Chart1.ChartAreas["ChartArea1"].AxisX.CustomLabels[i].GridTicks = GridTickTypes.TickMark;\n        }\n\n        // second label row\n        Chart1.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(0, 5.5, "Group1", 1, LabelMarkStyle.LineSideMark);\n        Chart1.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(5.5, 12.5, "Group2", 1, LabelMarkStyle.LineSideMark);\n        Chart1.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(12.5, 21.5, "Group3", 1, LabelMarkStyle.LineSideMark);	0
12131403	12131205	Execution of a batch file not as expected in c#	process.StartInfo.WorkingDirectory = @"c:\";	0
17512302	17511742	Unit test with sqlite in vs2012 c#	[TestMethod]\n[DeploymentItem("test.db")] \npublic void TestMethod1()\n{\n   Program.exec1();\n}	0
13369342	13367929	How to retrieve an object's Property name/value pairs on a custom object?	foreach (PropertyInfo n in typeof(configurationItem).GetProperties())\n   {\n     Response.Write(string.Format("{0}:  {1}<br/>", n.Name, n.GetValue(CI, null)));\n   }	0
2064059	2064028	Convert enum from object to long without a try block?	if (n is int)\n        ii = (int)n;//doesnt get here.\n    if (n is long)\n        ll = (long)n;//doesnt get here.\n    if (l is int)\n        ii = (int)l;//doesnt get here\n    if (l is long)\n        ll = (long)l;//doesnt get here	0
10946620	10921695	WinCE registry value monitor	[DllImport("coredll.dll", SetLastError = true)]\n    static extern int RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, out UIntPtr phkResult);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    static extern UIntPtr CeFindFirstRegChange(UIntPtr hKey, [In, MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, uint dwNotifyFilter);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    public static extern UInt32 WaitForSingleObject(UIntPtr Handle, UInt32 Wait);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    static extern Int32 CeFindNextRegChange(UIntPtr hChangeHandle);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    static extern Int32 CeFindCloseRegChange(UIntPtr hChangeHandle);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    public static extern int RegCloseKey(UIntPtr hKey);	0
19813427	19811708	call async methods in synchronized method in windows phone 8	public bool Sync() \n{ \n    Task.Run(async () => await MyClass.DoSync());\n}	0
13791120	13788221	how to insert the text in the editor in the TextAdornment template in Visual Studio?	IWpfTextCreationListener.TextViewCreated	0
11076318	11076289	Best way to convert file containing ASCII representations of bytes to real bytes C# .NET	private ICollection<byte> HexString2Ascii(string hexString)\n{\n    var bytes = new List<byte>(hexString.Length / 2);\n    for (int i = 0; i <= hexString.Length - 2; i += 2)\n        bytes.Add(byte.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));\n    return bytes;\n}	0
3712968	3712938	How do you change the text colour of a label programmatically in Microsoft Expression Blend 4	myLBL.Foreground = Brushes.Black;	0
12089876	12089268	Extracting Zip file save to disk	private static void ExtractFromUrl(Uri uri, string directoryPath)\n{\n    using (var webClient = new WebClient())\n    {\n        var data = webClient.DownloadData(uri);\n        using (var memoryStream = new MemoryStream(data))\n        using (var zipFile = ZipFile.Read(memoryStream))\n        {\n            zipFile.ExtractAll(directoryPath);\n        }                \n    }\n}	0
29385249	29385056	Select some of rows in C# database connection	DataTable dt = new DataTable(); // get your data into this datatable\n\n        DataRow[] dr;\n        dr = dt.Select("WHERE Select_ID = 12");\n        if (dr.Length > 0)\n        {\n            //do something\n        }	0
28990040	28989445	Login TFS programmatically using Windows Credentials	TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("http://__xxx__tfs:8080/tfs/__xxx__"));\n        tpc.EnsureAuthenticated();	0
5175063	5171862	PRISM + MEF -- Import & ImportMany	[Export(typeof(IFooService))]\n[Export("Foo1", typeof(IFooService))]\npublic class Foo1 : IFooService\n{\n    public int Foo() { return 1; }\n}\n\n[Export(typeof(IFooService))]\n[Export("Foo2", typeof(IFooService))]\npublic class Foo2 : IFooService\n{\n    public int Foo() { return 2; }\n}	0
34251976	34251913	Convert string (long date and time in 12-hour format) to DateTime	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Globalization;\n\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string strDate = "December 13, 2015 09:55 PM";\n            DateTime date = DateTime.ParseExact(strDate, "MMMM dd, yyyy hh:mm tt", CultureInfo.InvariantCulture);\n\n        }\n    }\n}\n???	0
11598042	11597940	Android Phone Browser Detection	if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {\n // some code..\n}	0
3702635	3702512	How do I dynamically implement the Proxy Pattern?	public void Intercept(IInvocation invocation)\n{\n    // Call your other method first...  then proceed\n    invocation.Proceed();\n}	0
22465202	22464987	How to add and subtract two datetime values?	DateTime d1 = Convert.ToDateTime(TextBoxtime1.Text);\nDateTime d2 = Convert.ToDateTime(TextBoxtime2.Text);\n\nif (d2 < d1)\n{\n    TimeSpan result = TimeSpan.FromHours(24) + (d2 - d1);\n    // ... do as you please with the result\n}	0
5831478	5817870	repositioning for minimap location	x = (xennemy-xplayer)/factor +150\ny = (yennemy-yplayer)/factor +150	0
34201770	34201583	Datetime ticks minus ticks results in negative number in the first run	while (true)\n{\n    var delta = DateTime.Now.Ticks - DateTime.Now.Ticks;\n    if (delta != 0)\n        Console.WriteLine(delta);\n}	0
1410599	1410579	Using base objects as parameters in a generic function	public class SomeNiceObject : ObjectBase\n{\n  public string Field1{ get; set; }\n}\n\npublic interface IFromDatabase\n{\n  bool ReadAllFromDatabase();\n}\n\npublic class CollectionBase<ObjectBase>() : IFromDatabase\n{\n  public bool ReadAllFromDatabase();\n}\n\npublic class SomeNiceObjectCollection : CollectionBase<SomeNiceObject>\n{\n\n}\n\npublic class DAL\n{\n\n public SomeNiceObjectCollection Read()\n {\n  return ReadFromDB<SomeNiceObjectCollection>();\n }\n\n T ReadFromDB<T>() where T : IFromDatabase, new()\n {\n  T col = new T();\n  col.ReadAllFromDatabase();\n  return col;          \n }\n}	0
7419623	7419418	C# Save a textures content path as string	FileStream fs = new FileStream("myFile.png", FileMode.OpenOrCreate);\nmyTexture.SaveAsPng(fs, myTexture.Width, myTexture.Height);\nfs.Flush();	0
7427543	7425439	nhibernate: remove object from collection without deleting it	cascade="all-delete-orphan"	0
21139541	21121812	Create file programmatically for import into Quicken?	!Account\nNJoint Brokerage Account\nTInvst\n^	0
1228348	1228335	How do I use a C# Class Library in a project?	using MyLibrary;	0
3433715	3433694	How to run the stored procedure that has OUTPUT parameter from C#?	using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn))\n{\n    cmd.CommandType = CommandType.StoredProcedure;\n    SqlParameter parm = new SqlParameter("@pkid", SqlDbType.Int);\n    parm.Value = 1;\n    parm.Direction = ParameterDirection.Input;\n    cmd.Parameters.Add(parm);\n\n    SqlParameter parm2 = new SqlParameter("@ProductName", SqlDbType.VarChar);\n    parm2.Size = 50;\n    parm2.Direction = ParameterDirection.Output; // This is important!\n    cmd.Parameters.Add(parm2);\n\n    cn.Open();\n    cmd.ExecuteNonQuery();\n    cn.Close();\n}	0
3736434	3736385	How can I parse two subjects from a string?	Input.IndexOf(Subject1.Name.ToLower()) < Input.IndexOf(Subject2.Name.ToLower())	0
7820517	7820502	How can I pass Data in URL	Server.URLEncode("http://www.w3schools.com?mykey=datavalue");	0
11347716	11347647	How to copy MenuItem from one ContextMenu to another ContextMenu	foreach(MenuItem mi in menuOptions.Items) \n{      \n     menuOptions.Items.Remove(mi);\n     entityRightClick.Items.Add(mi);\n }	0
9237090	9236870	I want to sorting step by in c# in gui	int i;\nvoid SelectionSort()\n{\n    clearFontColor();\n    int j, temp;\n    min = i;\n    for (j = i + 1; j < 10; j++)\n    {\n        if (input[min] > input[j])\n        {\n            min = j;\n        }\n    }\n    if (min != i)\n    {\n        temp = input[i];\n        input[i] = input[min];\n        input[min] = temp;\n    }\n    show(input);\n}	0
32560423	32560200	Add element at specific position in XML-file C#	var query=from n in xml.Root.Descendants("Note")\n    select n;\n\n\nforeach(var elem in query.ToList())\n    elem.ReplaceWith(new XElement("notedate", new XAttribute("date", "date here"), elem));	0
4346400	4346394	Need help with manipulating some string	s = s.ToLower().Replace(" ", "");	0
21960071	21956476	select data from sqlite database and binding values to listbox item in windows phone 8 apps	scheduleListbox.ItemsSource = retrievedTasks;	0
2327340	2327199	Index in a Foreach	var companies = baseRows\n  .Select((row, index) => new Company(row, symbRows[index]))\n  .ToList();	0
23730671	23730575	Find frequencies of a specific property value in a list<object>	var countByAge = people.GroupBy(x => x.Age)\n                       .ToDictionary(g => g.Key, g => g.Count());\n\nforeach(var person in people)\n{\n    person.Frequency = countByAge[person.Age];\n}	0
16363861	16362121	Change value of all controls of a specific type without causing indefinite loop	foreach (var control in controls)\n    {\n        if (control.Tag != null)\n            if (control.Tag.ToString() == "Weight")\n                if((control as LookUpEdit).EditValue != (sender as LookUpEdit).Text)\n                    (control as LookUpEdit).EditValue = (sender as LookUpEdit).Text;\n    }	0
8926104	8925900	Match and Replace a regular expression patteren	string value1 = "firstValue";\n        string value2 = "secondValue";\n\n        Regex expression = new Regex(string.Format("$[{0}]$test$[{1}]$", value1, value2));\n        expression.Match(input);	0
15499463	15499400	Using SQLLite to deleting 50 records from 60K data takes more time(17560 ms)	Delete from Analysis where AnalysisKey between 34 and 73	0
19568314	19567340	Specify Value for enumeration element in xsd	private static readonly int[][] _conversion =\n        {\n            new[] {(int) ColorCode.Red, 0x12},\n            new[] {(int) ColorCode.Orange, 0x13},\n            new[] {(int) ColorCode.LightGreen, 0x17},\n            .....\n        };\n\n    static int ToValue(ColorCode color)\n    {\n        if (_conversion.Any(c => c[0] == (int) color))\n            return _conversion.First(c => c[0] == (int) color)[1];\n\n        throw new NotImplementedException(string.Format("Color conversion is not in the dictionary! ({0})", color));\n    }\n\n    static ColorCode ToEnum(int value)\n    {\n        if (_conversion.Any(c => c[1] == value))\n            return (ColorCode)_conversion.First(c => c[1] == value)[0];\n\n        throw new NotImplementedException(string.Format("Value conversion is not in the dictionary! ({0})", value));\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(ToEnum(0x13));\n        Console.WriteLine(ToValue(ColorCode.Red));\n    }	0
29920268	29775614	How to detect NumLock on/off status in WPF	bool isNumLockedPressed = System.Windows.Input.Keyboard.IsKeyToggled(System.Windows.Input.Key.NumLock);\n\nint numLockStatus { get; set; }\n\npublic MainWindow()\n{\n            if (isNumLockedPressed == true)\n            {\n                numLockStatus = 1;\n                NumLock.Foreground = System.Windows.Media.Brushes.White;\n            }\n\n            else\n            {\n                numLockStatus = 0;\n                NumLock.Foreground = System.Windows.Media.Brushes.Red;\n            }\n\n}   \n\nprivate void NumLockKey_Press(object sender, KeyEventArgs e)\n        {\n            if (e.Key == Key.NumLock && e.IsToggled)\n            {\n                numLockStatus = 1;\n                NumLock.Foreground = System.Windows.Media.Brushes.White;\n            }\n\n            else if (e.Key == Key.NumLock && e.IsToggled == false)\n            {\n                numLockStatus = 0;\n                NumLock.Foreground = System.Windows.Media.Brushes.Red;\n            }\n        }	0
12217505	12217387	Open a .chm file on local network in a c# application	Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]\n"MaxAllowedZone"=dword:00000001\n\n[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\HTMLHelp\1.x\ItssRestrictions]\n"MaxAllowedZone"=dword:00000001	0
5556136	5556031	Implement Custom MembershipUser and Custom MembershipProvider	return (iTwitterMembershipUser) GetUser(login);	0
4271423	4271291	WriteProcessMemory with an int value	public class Cheat\n{\n    [DllImport("kernel32.dll",SetLastError = true)]\n    static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte [] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);\n\n    public static void SetPort(IntPtr GameHandle, IntPtr WriteAddress, int i)\n    {\n        var array = BitConverter.GetBytes(i);\n        int bytesWritten;\n        WriteProcessMemory(GameHandle, WriteAddress, array, (uint)array.Length, out bytesWritten);\n    }\n{	0
24111930	24111894	How to know whether a name exists on a particular sql table in c#?	using(SqlCommand cmd = new SqlCommand("IF EXISTS (SELECT TOP 1 1 FROM users WHERE user_userName = @userName) SELECT 1 ELSE SELECT 0", connection))\n{\n    cmd.Paramaters.AddWithValue("userName", "TestUserName");\n    object result = cmd.ExecuteScalar();\n    if(DBNull.Value.Equals(result) || result == null || (int)result == 0)\n    {\n        // user does not exist\n    }\n}	0
12246549	12246524	Take a value from the list and convert it to a enum	int roleAsInt = 1;\nRole role = (Role) roleAsInt;	0
32907252	32888453	Datetimepicker text value changes but value doesn't give the expected value	DateTimePickerImpl dtp = new DateTimePickerImpl();\ndtp.Location = new Point(3, 254);\ndtp.Name = "dtp";\ndtp.Size = new Size(271, 26);\ndtp.TabIndex = 25;\npanel1.Controls.Add(dtp);	0
28041811	28041593	Given a DayOfTheWeek how do i get the date from an existing datetime	DateTime selectedDate = DateTime.Now; //your selected date\n\n        DayOfWeek s = selectedDate.DayOfWeek; // your selected day of the selecteddate.\n        DayOfWeek selectedWeek = DayOfWeek.Friday; //your selected weekday.\n\n        DateTime output = selectedDate.AddDays((int)selectedWeek - (int)s); //output.	0
32702714	32702480	Sequentially call asynchronous methods in a loop	TaskCompletionSource<object> tcs = null;\n\nasync void Loop()\n{\n    for (int i = 0; i < 100; i++)\n    {\n        tcs = new TaskCompletionSource<object>();\n        Update(i);\n        await tcs.Task;\n    }\n}\n\nvoid Update(int i)\n{\n    //asynchronous - returns immediately\n}\n\nvoid UpdateComplete()//called from another thread\n{\n    tcs.TrySetResult(null);\n    //unblock further calls to Update();\n}	0
24292924	24292574	Loop for resending smtp email on failure to send	public void MusicDownloadEmail(string email)\n{\n    int tryAgain = 10;\n    bool failed = false;\n    do\n    {\n        try\n        {\n            failed = false;\n\n            var smtp = new SmtpClient();\n            var mail = new MailMessage();\n            const string mailBody = "Body text";\n            mail.To.Add(email);\n            mail.Subject = "Mail subject";\n            mail.Body = mailBody;\n            mail.IsBodyHtml = true;\n            smtp.Send(mail);\n        }\n        catch (Exception ex) // I would avoid catching all exceptions equally, but ymmv\n        {                \n            failed = true;\n            tryAgain--;\n            var exception = ex.Message.ToString();\n            //Other code for saving exception message to a log.\n        }\n    }while(failed  && tryAgain !=0)\n}	0
31474478	31474079	How to bind multiple view models to controller using knockout and asp.net mvc	function EmployeeProfileAndHistory() {\n    var profile = new FullEmployeeProfile();\n    var history = new employeeHistory();\n}	0
12621756	12621209	Check for any null values in an object	using System.Reflection;\n\nGetInfoRequest objGetInfoRequest;\nType getInfoRequestType = objGetInfoRequest.GetType();\nPropertyInfo[] myProps = getInfoRequestType.GetProperties();	0
7785115	7784251	two 0 to 1 directions in a loop	if(a>b) {\n   hi=a;\n   lo=b;\n} else {\n   hi=b;\n   lo=a;\n}\n\nd=hi-lo;\n\nif( (d>0.5 && greater_segment_needed) || (d<=0.5 && !greater_segment_needed)) { \n    result=lo+d/2\n} else\n    result=lo+d/2+0.5; //the marvels of geometry\n}\n\nif(result>1) result-=1; //handling possible overflow\nreturn result;	0
15059234	15059021	Referring to local settings in a shared form	If settings.Contains(Application.ExecutablePath & "_" & Me.Name & "_Location") Then\n    SuidenSettings(Application.ExecutablePath & "_" & Me.Name & "_Location") = Me.Location\nEnd If	0
17570018	17520602	textbox password gets shown on alert message	if(your alert box condition)\n{\n    //your alert box coding\n    txt_pass.Text = ""; // or make text as you wish.\n}\nelse.....	0
9492422	9492320	C# spliting string with three pieces	string input = "L 02/28/2012 - 06:14:22: \"Acid<1><VALVE_ID_PENDING><CT>\" killed \"Player<2><VALVE_ID_PENDING><TERRORIST>\" with \"m249\"";\nRegex reg = new Regex("[^\"]+\"([^<]+)<[^\"]+\" killed \"([A-Za-z0-9]+)[^\"]+\" with \"([A-Za-z0-9]+)\"");\nMatch m = reg.Match(input);\nif (m.Success)\n{\n    string player1 = m.Groups[1].ToString();\n    string player2 = m.Groups[2].ToString();\n    string weapon = m.Groups[3].ToString();\n}	0
9899358	9899339	Evaluating and comparing a variable to key pairs of a Dictionary	if (Math.Abs(diameter - key) <= 0.2F)	0
7395788	7395741	C# IPAddress from string	System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example	0
8766648	8694748	Compare two Datetimes one from Datetimepicker and one from MySql Database	String sql = "select * from orders where date_purchased < @DatePurchased";\n\nMySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);\nadapter.SelectCommand.Parameters.Add("DatePurchased", MySqlType.DateTime).Value = varDate; \nadapter.Fill(dataSet);	0
2817523	2817498	WCF class implementing two operation contracts in different service contracts with same name	[ServiceContract]\npublic interface IContract1\n{\n    [OperationContract(Name="AddInt")]\n    double Add(int ip);\n}\n\n[ServiceContract]\npublic interface IContract2\n{\n    [OperationContract(Name="AddDouble")]\n    double Add(double ip);\n}	0
5159367	5158878	How do I change the current Resource Manager at runtime to switch languages?	System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");	0
5888593	5888560	Is it Safe? Storing database access method in library	[assembly: InternalsVisibleTo("OtherLib.Domain.Stuff")]	0
16139485	9191736	Not Able to Select multiple CheckBoxs in Telerik Grid using C#	void radGridView1_ValueChanged(object sender, EventArgs e) \n { \n\n  RadCheckBoxEditor editor = sender as RadCheckBoxEditor; \n\n  if (editor != null && (bool)editor.Value == true) \n\n   { \n\n    this.radGridView1.GridElement.BeginUpdate(); \n\n    foreach (GridViewDataRowInfo row in this.radGridView1.Rows) \n\n    { \n\n        if (row != this.radGridView1.CurrentRow) \n\n        { \n\n            row.Cells["Bool"].Value = false; \n\n        } \n\n    } \n\n    this.radGridView1.GridElement.EndUpdate(); \n\n}	0
66710	66382	Is it possible to cache a value evaluated in a lambda expression?	private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)\n{\n    return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient);\n}\n\npublic static Expression<Func<Potion, bool>>\nContainsIngredients(string ingredientType, params string[] ingredients)\n{\n    var predicate = PredicateBuilder.False<Potion>();\n    // Here, I'm accessing p.Ingredients several times in one \n    // expression.  Is there any way to cache this value and\n    // reference the cached value in the expression?\n    foreach (var ingredient in ingredients)\n    {\n        var temp = ingredient;\n        predicate = predicate.Or(\n            p => IsIngredientPresent(p.Ingredients, ingredientType, temp));\n    }\n\n    return predicate;\n}	0
8627377	8627326	C# Parsing json into generic collection	JArray jobj = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(jStr);\nforeach (var x in jobj[0][1])\n{\n     Console.WriteLine(x[0][0] + " " + x[1][2]);\n}	0
19359844	19344379	Object used in Twitter WindowsPhone App	private void Application_Launching(object sender, LaunchingEventArgs e)\n{\n    Microsoft.Phone.Controls.TiltEffect.SetIsTiltEnabled(RootFrame, true);\n}\n\nprivate void Application_Activated(object sender, ActivatedEventArgs e)\n{\n    Microsoft.Phone.Controls.TiltEffect.SetIsTiltEnabled(RootFrame, true);\n}	0
21124824	21123478	obtain the number of rows been selected from ListView	ListView1.DataSourceID = null;\n                  ListView1.DataSource = rdvItems;\n\n                  int numberOfRecords = rdvItems.Count();\n                  if (numberOfRecords == 0)\n                  {\n                      lblMessage.Text = "No Apointement are available";\n\n                  }\n\n\n                  ListView1.DataBind();	0
20916248	20913066	Write a linq query with many to many scenario and other table	from user in context.UserProfiles\n                    from business in context.BusinessProfiles\n                    join bid in context.Bids on new { UserProfileId = user.Id, BusinessProfileId = business.Id } equals new { bid.UserProfileId, bid.BusinessProfileId }\n                    join tender in context.Tenders on new { TenderId = bid.TenderId } equals new { TenderId = tender.Id }\n                    where business.Id == businessProfileId && user.Id == userProfileId && tender.Id == tenderId\nselect new CustomObject\n{\n...\n}	0
21620870	21620757	How to have return type from async	public async Task<int> ExampleMethodAsync()\n{\n    var httpClient = new HttpClient();\n    int exampleInt = (await httpClient.GetStringAsync("http://msdn.microsoft.com")).Length;\n    ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";\n    // After the following return statement, any method that's awaiting\n    // ExampleMethodAsync (in this case, StartButton_Click) can get the \n    // integer result.\n    return exampleInt;\n}	0
2160362	2160338	How to hide console after creating form in console application	[DllImport("user32.dll")]\n    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n\n    [DllImport("user32.dll")]\n    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n    static void Main(string[] args)\n    {\n        Console.Title = "ConsoleApplication1";\n\n        IntPtr h=FindWindow(null, "ConsoleApplication1");\n\n        ShowWindow(h, 0); // 0 = hide\n\n        Form f = new Form();\n\n        f.ShowDialog();\n\n        ShowWindow(h, 1); // 1 = show\n\n    }	0
15835072	15835016	C# Control.Invoke a method group	Dispatcher.BeginInvoke(DispatcherPriority.Background, new MethodInvoker(() =>   \n                {\n                   //Your Update code\n                }));	0
30841633	30841450	add value to subject field in reply window - MS OUTLOOK	using Outlook = Microsoft.Office.Interop.Outlook;\n\n\n //Create the email with the settings\n Outlook.Application outlookApp = new Outlook.Application();\n Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);\n mailItem.Subject = mailSubject;\n mailItem.Attachments.Add(totalPath);\n mailItem.Body = mailBody;\n mailItem.Importance = Outlook.OlImportance.olImportanceNormal;\n try\n {\n     //Try to open outlook, set message if its not possible to open outlook\n     mailItem.Display(true);\n }\n catch (Exception ex)\n {\n     MessageBox.Show(ex.Message);\n     return false;\n }	0
1108670	1108644	C#: Making sure DateTime.Now returns a GMT + 1 time	DateTime MyTime = new DateTime(1990, 12, 02, 19, 31, 30, DateTimeKind.Utc);\n\nDateTime MyTimeInWesternEurope = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(MyTime, "W. Europe Standard Time");	0
27122097	27120203	NHibernate takes first enum value instead just return null	public virtual SchemaStatus? Status\n{\n    get;\n    set;\n}	0
27338945	27337192	How can I load and sort button controls dynamically, based on changing data?	flowLayoutPanel.FlowDirection = FlowDirection.LeftToRight;\nflowLayoutPanel.WrapContents = true;	0
18911801	18910901	How to add Multiple User Roles in Membership by clicking on button	protected void cmdUpdateRole_Click(object sender, EventArgs e)\n{\n    foreach (GridViewRow row in GridView1.Rows)\n    {\n        List<string> roles=new List<string>();\n        Label username = (Label)row.FindControl("Label1");\n        CheckBox chkAdmin = (CheckBox)row.FindControl("chkAdmin");\n        CheckBox chkUser = (CheckBox)row.FindControl("chkUser");\n        CheckBox chkgen = (CheckBox)row.FindControl("chkgen");\n        if (chkAdmin.Checked)\n            roles.Add("Admin");  \n        if (chkUser.Checked)\n            roles.Add("DPAO User");\n        if (chkgen.Checked)\n            roles.Add("GeneralUser");\n        if (Roles.GetRolesForUser(username.Text).Length > 0)\n        {\n            Roles.RemoveUserFromRoles(username.Text, Roles.GetRolesForUser(username.Text));\n        }\n        if (roles.Count > 0)\n        {\n            Roles.AddUserToRoles(username.Text, roles.ToArray());\n        }\n        BindGridviewData();\n    }\n}	0
26298089	26298018	Bitwise Logic knowing what was enabled from the server	i & A != 0  // true if A is set in i\ni & B != 0  // true if B is set in i	0
14878544	14757145	How to create incremented XML element names when serializing a list	public class Answer : IXmlSerializable\n{\n    public List<string> list = new List<string>();\n    public string this[int pos]\n    {\n        get\n        {\n            return list[pos];\n        }\n\n        set\n        {\n            list[pos] = value;\n        }\n    }\n\n    public void ReadXml ( XmlReader reader )\n    {\n        reader.ReadToDescendant("a");\n        while ( reader.Name != "Answers" )\n        {\n            if ( reader.IsStartElement() )\n            {\n                list.Add(reader.ReadElementContentAsString());\n            }\n        }\n\n        reader.Read();\n    }\n\n    public void WriteXml ( XmlWriter writer )\n    {\n        for ( int i = 0; i < list.Count; i++ )\n        {\n            writer.WriteElementString(((char)(97 + i)).ToString(), list[i]);\n        }\n    }\n\n    public XmlSchema GetSchema()\n    {\n        return(null);\n    }\n}	0
20974993	20974846	Any way to tell if the user clicked on the last row in a datagridview?	if (dataGridView1.Rows[e.RowIndex].DataBoundItem == null)\n{\n  //Last row\n  ...\n}	0
8954145	8954079	int to binary function without recursion?	int g = 2323;\n\nfor (uint mask = 0x80000000; mask != 0; mask >>= 1)\n    Console.Write(((uint)g & mask) != 0 ? "1" : "0");	0
13010409	13001215	Detect if Modifier Key is Pressed in KeyRoutedEventArgs Event	var state = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift);\nreturn (state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;	0
3165846	3165746	Have a WPF Control Class being a template class	x:TypeArguments	0
1572742	1572722	How can i extract value of properties from anonymous class?	var o = new { name = "Bruce", Age = 21 };\nConsole.WriteLine( "name={0},age={1}, o.name, o.Age );	0
18992516	18992274	complex LINQ multiple tables with many to many	var map =\n  from garage in Garages\n  join car in Cars on garage.ID equals car.GarageID\n  join car_dealership in Car_Dealerships on car.ID equals car_dealership.CarID\n  join dealer in Dealers on car_dealership.DealerID equals dealer.ID\n  group dealer by garage;\n\nforeach (var garage in map)\n{\n  Console.WriteLine("Garage: " + garage.Key.Name);\n\n  foreach (var dealer in garage)\n    Console.WriteLine("  Dealer: " + dealer.Name);\n}	0
16274992	16273485	Entity Framework select one of each group by date	var query = Posts.GroupBy(p => p.Type)\n                  .Select(g => g.OrderByDescending(p => p.Date)\n                                .FirstOrDefault()\n                   )	0
33629311	33613828	Get City Name from Reverse Geocoding with latitude and longitude	XmlDocument xDoc = new XmlDocument();\n        xDoc.Load("https://maps.googleapis.com/maps/api/geocode/xml?latlng=" +coordinate+"&location_type=ROOFTOP&result_type=street_address&key=YOURAPIKEY");\n\n        XmlNodeList xNodelst = xDoc.GetElementsByTagName("result");\n        XmlNode xNode = xNodelst.Item(0);\n        string adress = xNode.SelectSingleNode("formatted_address").InnerText;\n        string mahalle = xNode.SelectSingleNode("address_component[3]/long_name").InnerText;\n        string ilce = xNode.SelectSingleNode("address_component[4]/long_name").InnerText;\n        string il = xNode.SelectSingleNode("address_component[5]/long_name").InnerText;	0
24512576	24500562	Mapping a 3D point to 2D context	xscr=x/z;\nyscr=y/z;	0
8891458	8868905	How to handle selectedindexchange of a combobox	IdComboBox.SelectedValue = abc.Tables[0].Rows[0]["Id"];	0
27254433	27254228	Calling a method which return Int32 within a foreach	public ActionResult Index()\n {\n      var model = db.Stores.OrderBy(s => s.StoreName)\n                  .Select (s => new StoreDetails {\n                       ID = s.ID,\n                       Name = s.StoreName,\n                       CountOfItems = s.Items.Count(),\n                       CountOfBigType = s.Items.Count(x=>x.Size > 100) <--\n                       //other counts if i can get this one working\n                       });\n      return View(model);\n }	0
20437184	20437099	How do I get multiple substrings in a large string in C#?	var pins = Regex.Matches(html, @"pin=([0-9]*)");\nvar pinArray = (from Match pin in pins select Convert.ToInt32(pin.Groups[1].Value)).ToArray();	0
28462498	28427588	How do I implement synchronous copying of a single blob in Azure SDK that only has StartCopyFromBlob()?	CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(sourcePath);\nCloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(targetPath);\nvar copyToken = targetBlob.StartCopyFromBlob(sourceBlob.Uri);\nif(targetBlob.CopyState.Status == CopyStatus.Success)\n{\n    // Copy completed successfully\n}	0
10464569	10464516	Changing a point in a list	for (int i = listOfPoint.Count -1; i > 0; i--)\n{\n    //Pass the value not the pointer\n    listOfPoint[i] = new Point(listOfPoint[i-1].X, listOfPoint[i-1].Y);\n}	0
14124615	14123864	looping through specifc set of items	List<NItem> item = new List<NItem>();   \n\nStringBuilder build = new StringBuilder();\nbuild.Append("<table>");\n\n// Increment the counter by the number of columns\nfor (int q = 0; q < item.Count; q += columns)\n{\n    build.Append("<tr>");\n\n    for (int i = 0; i < columns; i++)\n    {               \n        build.Append("<td>");\n\n        if (q + i < item.Count)\n        {\n            // Grab the item for this column by adding the column index to the item index that we started with\n            var currentItem = item[q + i];\n            build.Append(string.Format("<a title= \"{0}\" href=\"{1}\" target=\"_blank\">{2}</a> ", currentItem.ToolTip, currentItem.Link, currentItem.LinkDescription));\n        }\n\n        build.Append("</td>");\n    }\n    build.Append("</tr>");\n}\n\nbuild.Append("</table>");	0
23721107	23720748	VS 2013 - Store > Create App Packages Disabled	Bin\Release	0
22381933	22381053	Reading dynamically created hidden field from Code behind	protected void Page_PreInit(object sender, EventArgs e)\n{\n    // whatever other code you have up here\n\n    HtmlTableCell tCellJson= new HtmlTableCell();\n    HiddenField hdnJson = new HiddenField();\n    hdnJson.ID = "hdnJson"+ count;\n\n    tCellJson.Controls.Add(hdnJson);\n    tRow.Cells.Add(tCellJson);\n}	0
24698192	24697940	XmlDocumentFragment equivalent in LINQ to XML?	var xml = String.Concat(myNodes);	0
28045621	28043374	how to add new TextRange.Run to PowerPoint textbox?	for (int k = 0; k < sourceShapeProps.textFrame.TextRange.Runs.Count; k++)\n   {\n    var run = sourceShapeProps.textFrame.TextRange.get_Runs(k + 1, 1);\n    var characters = cell.Shape.TextFrame2.TextRange.get_Characters(run.Start, run.Length);\n    characters.Font.Fill.ForeColor.RGB = run.Font.Fill.ForeColor.RGB;\n    characters.Font.Bold = run.Font.Bold;\n    characters.Font.Italic = run.Font.Italic;\n   }	0
16751296	16747320	Custom Model Binder inheriting from DefaultModelBinder	public class InterfaceModelBinder : DefaultModelBinder\n{\n    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n    {\n        if (bindingContext.ModelType.IsInterface)\n        {\n            Type desiredType = Type.GetType(\n                EncryptionService.Decrypt(\n                    (string)bindingContext.ValueProvider.GetValue("AssemblyQualifiedName").ConvertTo(typeof(string))));\n            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, desiredType);\n        }\n\n        return base.BindModel(controllerContext, bindingContext);\n    }\n}	0
30083639	30082130	Selectively populate properties in a SelectMany using LINQ?	Person lastPerson = null;\nRelative lastRelative = null;\nvar records = report.Persons.SelectMany(\n    person => person.Relatives.Select(relative =>\n    {\n        FlattenedRecord r = new FlattenedRecord\n        {\n            ReportNumber = report.ReportNumber,\n            ReportDate = report.ReportDate,\n            PersonAge = lastPerson != person ? person.Age : "",\n            PersonSex = lastPerson != person ? person.Sex : "",\n            PersonRace = lastPerson != person ? person.Race : "",\n            RelativesAge = lastRelative != relative ? relative.Age : "",\n            RelativesSex = lastRelative != relative ? relative.Sex : "",\n            RelativesRace = lastRelative != relative ? relative.Race : "",\n            Relationship = lastRelative != relative ? relative.Relationship : ""\n        };\n\n        lastPerson = person;\n        lastRelative = relative;\n\n        return r;\n    }));	0
8953764	7200841	Linq - How to get types participating in expression	public class QueryExpressionVisitor : ExpressionVisitor\n{\n    public List<Type> Types\n    {\n        get;\n        private set;\n    }\n\n\n    public QueryExpressionVisitor()\n    {\n        Types = new List<Type>();\n\n    }\n    public override Expression Visit(Expression node)\n    {\n        return base.Visit(node);\n    }\n\n    protected override Expression VisitConstant(ConstantExpression node)\n    {\n        if (node.Type.IsGenericTypeDefinition && node.Type.GetGenericTypeDefinition() == typeof(IQueryable<>))\n            CheckType(node.Type.GetGenericArguments()[0]);\n        return base.VisitConstant(node);\n    }\n\n    protected override Expression VisitMember(MemberExpression node)\n    {\n        CheckType(node.Member.DeclaringType);\n        return base.VisitMember(node);\n    }\n\n\n\n    private void CheckType(Type t)\n    {\n        if (!Types.Contains(t))\n        {\n            Types.Add(t);\n        }\n    }\n}	0
11919151	11919140	Posting file to a remote PC C#	\\ComputerName\PublicShare\folder\structure\you\want	0
20474686	20474557	Hook into login (MVC4)	public class AuthenticateAndAuthorizeAcsMvcAttribute : System.Web.Mvc.AuthorizeAttribute\n{\n    public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)\n    {\n        var principal = filterContext.HttpContext.User;\n        if (principal == null || !principal.Identity.IsAuthenticated)\n        {\n            filterContext.Result = new ViewResult()\n            {\n                ViewName = "AcsLogin",\n                ViewData = filterContext.Controller.ViewData,\n                TempData = filterContext.Controller.TempData\n            };\n            return;\n\n        }\n        base.OnAuthorization(filterContext);\n    }\n\n}	0
22952668	22949458	Open a PDF in a new tab	Options = new Dictionary<string, string>\n    {\n        {"Content-Type", "application/pdf"},\n        {"Content-Disposition", "inline; filename=\"mypdf.pdf\";"}\n    };	0
15776060	15775941	Deallocate and re-instantiate new a singleton	public static class SingletonAccessor\n{\n    private static SomeClass _instance;\n    private static object _lock = new Object();\n\n    public static SomeClass Singleton\n    {\n        get\n        {\n            lock (_lock)\n            {\n                if (_instance == null)\n                {\n                    _instance = new SomeClass();\n                }\n\n                return _instance;\n            }\n        }\n    }\n\n    public static void Recycle()\n    {\n        lock (_lock)\n        {\n            if (_instance != null)\n            {\n                // Do any cleanup, perhaps call .Dispose if it's needed\n\n                _instance = null;\n            }\n        }\n    }\n}	0
4699743	4698252	Error with ViewResult and ActionResult containing same parameters	[HttpGet]\npublic ViewResult Edit(int id)\n{\n    //build and populate view model\n    var viewModel = new EditViewModel();\n    viewModel.Id = id;\n    viewModel.Name = //go off to populate fields\n\n    return View("", viewModel)\n}\n\n[HttpPost]\npublic ActionResult Edit(EditViewModel viewModel)\n{\n    //use data from viewModel and save in database\n}	0
32216302	32211221	Deserialize a specified object by a user of a JSON file	public static string GetMovieTitle(string json, string enteredNumberText)\n    {\n        var root = JsonConvert.DeserializeObject<RootObject>(json);\n        try\n        {\n            var enteredNumber = Int32.Parse(enteredNumberText);\n            if (enteredNumber < 0 || enteredNumber >= root.movies.Count)\n                return null;\n            return root.movies[enteredNumber].title;\n        }\n        catch (System.FormatException)\n        {\n            // Invalid number typed by the user.  Handle if desired.\n            throw;\n        }\n        catch (System.OverflowException)\n        {\n            // Too large or small number typed by the user.  Handle if desired.\n            throw;\n        }\n    }	0
25106140	25106061	How to remove make new folder FolderBrowserDialog	var x = new FolderBrowserDialog();\nx.ShowNewFolderButton = false;	0
10615789	10615750	How to get the user initials programmatically in Windows Forms	string username = Environment.UserName;	0
8790002	8789370	How to judge the node of json exists	if (jo["data"].Select("prevtime") != null) \n{\n        status.Prevtime = jo["data"].Value<string>("prevtime");\n        status.Nexttime = jo["data"].Value<string>("nexttime");\n}	0
2643411	2643383	Order by descending based on condition	// Common code:\nvar hosters = from e in context.Hosters_HostingProviderDetail\n              where e.ActiveStatusID == pendingStateId;\n\n// The difference between ASC and DESC:\nhosters = (sortOrder == SortOrder.ASC ? hosters.OrderBy(e => e.HostingProviderName) : hosters.OrderByDescending(e => e.HostingProviderName));\n\n// More common code:\nreturnList = hosters.ToList<Hosters_HostingProviderDetail>();	0
13375672	13342582	How to set date in Winforms Datetimepicker	int year = Convert.ToDateTime(dateTimePicker1.Text).Year;\n        int month = Convert.ToDateTime(dateTimePicker1.Text).Month;\n        dateTimePicker1.Text = DateTime.ParseExact("01." + month.ToString() + "." + year.ToString(), "dd.mm.yyyy",System.Globalization.CultureInfo.InvariantCulture).ToString();	0
23455907	23455687	How to determine the locale (culture) used by a WPF control?	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {   \n        // Thread settings are separate and optional  \n        // affect Parse and ToString:       \n        // Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("nl-NL");\n        // affect resource loading:\n        // Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("nl-NL");\n\n        FrameworkElement.LanguageProperty.OverrideMetadata(\n              typeof(FrameworkElement),\n              new FrameworkPropertyMetadata(\n                    XmlLanguage.GetLanguage(\n                          CultureInfo.CurrentCulture.IetfLanguageTag)));\n\n        base.OnStartup(e);\n    }	0
6688787	6686204	How to get receiver email from a sent email in EWS?	var toRecipients = string.Join(", ",\n    mail.ToRecipients.Select(\n        address => string.Format("\"{0}\" <{1}", address.Name, address.Address)));	0
8253587	8252923	C# On keypress - exit program	int exitKeysCount = 0;\nprivate void TrollFrm_KeyDown(object sender, KeyEventArgs e)\n{\n    if (exitKeysCount == 0 && e.KeyCode == Keys.T)\n        exitKeysCount = 1;\n    else if (exitKeysCount == 1 && e.KeyCode == Keys.E)\n        exitKeysCount = 2;\n    else if (exitKeysCount == 2 && e.KeyCode == Keys.S)\n        exitKeysCount = 3;\n    else if (exitKeysCount == 3 && e.KeyCode == Keys.T)\n        this.Close();\n    else exitKeysCount = 0;\n}	0
9224815	9196041	passing " from c# to sql server	thisCommand.CommandType = CommandType.Text;	0
17918741	17918682	Replace string one by one at run-time in datagridview c#	private void button1_Click(object sender, EventArgs e)\n  {\n     // change the cell = counter\n     counter++;\n  }	0
19013059	19012986	How to get first record in each group using Linq	var res = from element in list\n              group element by element.F1\n                  into groups\n                  select groups.OrderBy(p => p.F2).First();	0
16532866	16532791	What data structure can I use to access its contents randomly?	public static void Shuffle<T>(this IList<T> list)  \n{  \n    Random rng = new Random();  \n    int n = list.Count;  \n    while (n > 1) {  \n        n--;  \n        int k = rng.Next(n + 1);  \n        T value = list[k];  \n        list[k] = list[n];  \n        list[n] = value;  \n    }  \n}\n\nList<Product> products = GetProducts();\nproducts.Shuffle();	0
6029098	6029017	Simple IF statement in my SiteMaster file?	String pageName  = Request.FilePath;\n\n//return like that /example.aspx\n\nif (pageName == "/default.aspx") \n{\n// your code\n}	0
26634578	26634357	How to unit test OnPropertyChanged event handler in ViewModel	public class Program\n{\n    private static void Main(string[] args)\n    {\n        TestableProgram2 tp = new TestableProgram2();\n        tp.b_PropertyChanged(new Program(), "bang");\n    }\n}\n\npublic class Program2\n{\n    protected void b_PropertyChanged(object sender, string e)\n    {\n        Debug.Write(e);\n    }\n}\n\npublic class TestableProgram2 : Program2\n{\n    public new void b_PropertyChanged(object sender, string e)\n    {\n         e = "altered";       // here to demonstrate this code is entered.\n        base.b_PropertyChanged(sender, e);\n    }\n}	0
3450191	3450163	How to align my submit and cancel buttons(in tr) to the bottom of the table	style="vertical-align: bottom;"	0
17256753	17256537	Display random line from .txt file - c#	string[] lines = File.ReadAllLines(@"C:\...\....\YourFile.txt");\n\ntextBox1.Text = lines[new Random().Next(lines.Length)];	0
16915574	16911116	varbinary pdf from database has been crash?	byte[] pdfFile= null;\nvar obj = DBContext.MyTable.Where(x => x.ID == 1 ).SingleOrDefault().pdfColumn;\n\npdfFile = obj.ToArray();\n\n if (pdfFile!= null)\n   {\n Response.ClearHeaders();\n Response.Clear();\n Response.AddHeader("Content-Type", "application/pdf");\n Response.AddHeader("Content-Length", pdfFile.Length.ToString());\n Response.AddHeader("Content-Disposition", "inline; filename=sample.pdf");\n Response.BinaryWrite(pdfFile);\n Response.Flush();\n Response.End();\n   }	0
25555876	25554985	How to convert physical path to virtual path	string path = @"C:\Users\AlphaDog\Desktop\Alumni Revised\AlumiTrackingSystem\AlumiTrackingSystem\AlumiTrackingSystem\AlumiTrackingSystem\image\Vince\Tulips.jpg";\n    string[] splitPath = path.Split('\\');\n    int start = 0;\n    foreach (string s in splitPath) {\n         if (s == "image")\n             break;\n         else\n             start++;\n    }\n    string virtualPath = "~/";\n    for (int i = start; start < splitPath.Length; start++) {\n         virtualPath += (i > start ? "/" : "") + splitPath[start];\n    }	0
13143202	13143135	How to rewrite multiple else conditions in c#	if (condition && condition2)\n{\n    do();\n}\nelse \n{\n    myVar="test";\n}	0
450020	450009	How to get serial number of USB-Stick in C#	// add a reference to the System.Management assembly and\n// import the System.Management namespace at the top in your "using" statement.\n// Then in a method, or on a button click:\n\nManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");\nforeach (ManagementObject currentObject in theSearcher.Get())\n{\n   ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");\n   MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());\n}	0
13011704	13011599	Displaying random XML file in DataGrid	dataGrid1.DataMember = dsAuthors.Tables[0].Tablename;	0
5349644	5349321	Generate random bytes for TripleDES key C#	var rng = new RNGCryptoServiceProvider();\nvar key = new byte[24];\nrng.GetBytes(key);\n\nfor(var i = 0; i < key.Length; ++i)\n{\n    int keyByte = key[i] & 0xFE;\n    var parity = 0;\n    for (var b = keyByte; b != 0; b >>= 1) parity ^= b & 1;\n    key[i] = (byte)(keyByte | (parity == 0 ? 1 : 0));\n}\n\nreturn key;	0
2163223	2163061	Objects / Entities: Many to Many + Many to One	internal virtual void AddProduct(Product product)\n{\n    this.Products.Add(product);\n}	0
5977638	5977445	How to get Windows Display settings?	float dpiX, dpiY;\nGraphics graphics = this.CreateGraphics();\ndpiX = graphics.DpiX;\ndpiY = graphics.DpiY;	0
21611594	21611543	C# get string from string	var numbers = str.Split(new [] { '"','-' },StringSplitOptions.RemoveEmptyEntries)\n                 .Where(word => word.All(char.IsDigit) && word.Length > 1)\n                 .ToList();	0
9618482	9618342	How to invoke some method in some time (500 millisecond ) in SilverLight	Task.Factory.StartNew( () => \n{\n    Methdd1();\n    Thread.Sleep(500);\n    Method2();\n});	0
32677026	32676895	How to load content of website as mobile web browser in my winform web browser C#	webBrowser.Navigate("http://localhost/run.php", null, null,\n                string.Format("User-Agent: {0}", "Opera/9.80 (J2ME/MIDP; Opera Mini/9 (Compatible; MSIE:9.0; iPhone; BlackBerry9700; AppleWebKit/24.746; U; en) Presto/2.5.25 Version/10.54"));	0
11795091	11613584	Exception from HRESULT: 0x80040E01	using (FullTextSqlQuery q = GetFullTextSqlQuery(web))\n                    {\n                        q.QueryText = sqlQuery.ToString();\n                        rt = ((ResultTableCollection)q.Execute())[ResultType.RelevantResults];\n                        Logging.LogMessage(rt.RowCount.ToString());\n                    }	0
8972972	8972874	How to eagerly fetch all child collections?	var myObjectList = \n    SessionHolder.Current\n                 .CreateCriteria(typeof(MyObject))\n                 .SetFetchMode("Clients", FetchMode.Eager)\n                 .SetFetchMode("Locations", FetchMode.Eager)\n                 .SetFetchMode("Contracts", FetchMode.Eager)\n                 .SetResultTransformer(new DistinctRootEntityResultTransformer())\n                 .List<MyObject>();	0
4670255	4670218	How do you convert a double to a formatted string?	string s = String.Format("{0:0.00}", 0.8);	0
541455	541420	How to I access an attached property in code behind?	Canvas.SetLeft(theObject, 50)	0
20159947	20159587	How can i access a listbox from another pc in C#	Dispatcher.BeginInvoke((Action)(() => \n{ \n    ListMessage.Items.Add(string.Format("Friend: {0}", recievedMessage)) \n}));	0
23812374	23812193	trying to pass model data from view to controller	public class ShoppingModel\n{\n    [Required]\n    public CartSummaryModel.DeliveryModel delivery { get; set; };\n    [Required]\n    public CartSummaryModel.PaymentModel payment { get; set; };\n    [Required]\n    public CartSummaryModel cartSummary { get; set; };\n    [Required]\n    public StudentModel student { get; set; };\n    [Required]\n    public RootObject midas { get; set; };\n\n}	0
7293328	7293315	Add dir to List DirectoryInfo	Directory.Add(new DirectoryInfo("C:\\test"));	0
12168902	12168845	mvc3 database first model defaults	if (String.IsNullOrEmpty(formModel.MyString)) formModel.MyString = null;	0
9723305	9723233	Should I trim white space from SQL statements before executing them?	string query = @"\n    select columns\n    from table\n    where condition = 1\n";	0
29406069	29406024	Tool to measure the time taken for a code to run in visual studio 2010 ide	using System;\nusing System.Diagnostics;\nusing System.Threading;\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Stopwatch stopWatch = new Stopwatch();\n        stopWatch.Start();\n        Thread.Sleep(10000);\n        stopWatch.Stop();\n        // Get the elapsed time as a TimeSpan value.\n        TimeSpan ts = stopWatch.Elapsed;\n\n        // Format and display the TimeSpan value. \n        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n            ts.Hours, ts.Minutes, ts.Seconds,\n            ts.Milliseconds / 10);\n        Console.WriteLine("RunTime " + elapsedTime);\n    }\n}	0
7700622	7700570	Grouping 2 Tables, Counting Values And Then Saving The Results In A Dictionary	using(DbEntities db = new DbEntities())\n{\n  var fromDate = new DateTime(2011,8,1);\n  var toDate = new DateTime(2011,8,31);\n  var dictionary =\n            (from t1 in db.TABLE1\n            join t2 in db.TABLE2.Where(x => x.VALUE == 1 && x.DATE >= fromDate && x.DATE <= toDate)\n            on t1.NAME_ID equals t2.NAME_ID into t2_j\n            from t2s in t2_j.DefaultIfEmpty()\n            group t2s by t1.NAME into grouped\n            select new { Name = grouped.Key, Count = grouped.Sum(x => x.VALUE) }).\n            Where(x => x.Count.HasValue).\n            ToDictionary(o => o.Name,o => o.Count);\n   return dictionary;\n\n}	0
12324036	12323633	Any design patterns for initialization? C#	public static class Initializer\n    {\n        public static void Initialize()\n        {\n            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n                foreach (var type in assembly.GetTypes())\n                    if (type.IsDefined(typeof(InitializeAttribute), true))\n                        Console.WriteLine("Need to initialize {0}", type.FullName);\n        }\n    }\n\n    [AttributeUsage(AttributeTargets.Class)]\n    public sealed class InitializeAttribute : Attribute\n    { \n    }\n\n    [Initialize]\n    public sealed class ToBeInitialized\n    { \n    }	0
19057952	19057457	How do you get all project macros and their values from .vcxproj file	Microsoft.Build.Evaluation.Project	0
12312024	12312000	After passing variable to async method, how will setting variable to new instance in main thread affect async method?	void SomeMethod()\n{\n    MyObject o = new MyObject();\n    // Do stuff with o\n    SomeAsyncMethod(o);\n    o.Id = 2222; // will change objects Id property, which will \n                 // be reflected in another thread\n}	0
15900738	15900680	Assign anonymous in IF-ELSE statements	var Final = result.OrderBy(p => p.AreaCode).ThenBy(p => p.PCode);\n\nif (PageSize > 0)\n    Final = Final.Skip(PageSize * (PageNo - 1)).Take(PageSize);	0
18096451	18096218	How do i find only part of the directory AppData\\Local?	Environment.GetEnvironmentVariable("UserProfile");	0
28616822	28615841	Get Navigation data in View Model Windows phone 8	GalaSoft.MvvmLight.Views.NavigationService _navigationService = [..] // Get your NS instance here or create a new one.\nvar m = _navigationService.GetAndRemoveParameter(NavigationContext);\n// Try to cast:\nMyModel model = m as MyModel;\n// Deny if it's not a valid object\nif (model == null)\n    return;	0
4470751	4470700	How to save Console.WriteLine output to text file?	static public void Main ()\n{\n    FileStream ostrm;\n    StreamWriter writer;\n    TextWriter oldOut = Console.Out;\n    try\n    {\n        ostrm = new FileStream ("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);\n        writer = new StreamWriter (ostrm);\n    }\n    catch (Exception e)\n    {\n        Console.WriteLine ("Cannot open Redirect.txt for writing");\n        Console.WriteLine (e.Message);\n        return;\n    }\n    Console.SetOut (writer);\n    Console.WriteLine ("This is a line of text");\n    Console.WriteLine ("Everything written to Console.Write() or");\n    Console.WriteLine ("Console.WriteLine() will be written to a file");\n    Console.SetOut (oldOut);\n    writer.Close();\n    ostrm.Close();\n    Console.WriteLine ("Done");\n}	0
17618215	17618055	Linq Query with a special case for 0 values	var DataSource = from m in product\n                 select new { \n                     Class = m.Class, \n                     Id = m.Id == 0 ? "None" : (new Make(m.Id)).ProductName\n                 };	0
7974335	7973981	XML file to html table (loop) C#	var xmlDoc = XDocument.Load(new XmlTextReader(Server.MapPath("NewsSrc.xml")));\nforeach(var descendant in xmlDoc.Descendants("NewsItem"))\n{\n   var title = descendant.Element("Title").Value;\n   var summary = descendant.Element("Summary").Value;\n   var details = descendant.Element("Details").Value;\n   var id = descendant.Attribute("id").Value;\n}	0
12580341	12578959	How to improve performance of TestApi's Keyboard.Type method?	private void setText(AutomationElement aEditableTextField, string aText)\n    {\n        ValuePattern pattern = aEditableTextField.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;\n\n        if (pattern != null)\n        {\n            pattern.SetValue(aText);\n        }\n    }	0
4468966	4468427	how to make accordian headers all collapsed initially on page load?	SelectedIndex="-1"	0
10654582	10654512	How to shown one form screen while waiting event to trigger	private void GPS_PositionReceived(string Lat, string Lon)\n{\n    arrLon = Lon.Split(new char[] { '?', '"' }, StringSplitOptions.RemoveEmptyEntries);\n    dblLon = double.Parse(arrLon[0]) + double.Parse(arrLon[1], new System.Globalization.NumberFormatInfo()) / 60;\n    deciLon = arrLon[2] == "E" ? dblLon : -dblLon;\n\n    //some more code \n\n    // LOAD FORM 1\n    // CLOSE THIS FORM (FORM 2)\n}	0
4658331	4658272	Remove characters with regex in c#	resultString = Regex.Replace(subjectString, @"\^+\|", "|");	0
15505296	15505231	Out of range exception of a dataset	if(ds.Tables[0].Rows.Count > 0)\n{\n    object a = ds.Tables[0].Rows[0]["pic"];\n    string test = a.ToString();\n}\nelse\n{\n    Response.Write("No rows for the ID=" + passedID;\n}	0
19916978	19916757	How do I copy from an array<unsigned short> to an unsigned short[] in C CLI?	results.uShorts[0] = (unsigned short)UnsignedShorts[0];	0
16982509	16982304	How to find if an element of a list is in another list and the name of element?	List<string> list1 = new List<string> { "A", "C", "F", "H", "I" };\n        List<string> list2 = new List<string> { "B", "D", "F", "G", "L" };\n        String sel = list1.Intersect(list2).FirstOrDefault()??"";\n\n        Console.WriteLine(sel);	0
34008413	34004249	How to setup multiple queues in RabbitMQ and connect using MassTransit 3?	var busControl = Bus.Factory.CreateUsingRabbitMq(x =>\n{\n    x.AutoDelete = false;\n    x.UseJsonSerializer();\n    x.UseTransaction();\n    x.ExchangeType = "direct";\n    x.Durable = true;\n    var host = x.Host(new Uri("rabbitmq://localhost/"), h =>\n    {\n        h.Username("guest");\n        h.Password("guest");\n    });\n    x.UseRetry(Retry.Immediate(2));\n\n    x.ReceiveEndpoint("Dev_Queue", e =>\n    {\n        e.Consumer(() => new MyConsumer());\n    })\n});	0
23199329	23198786	Show the beginning of scrollable panel, when starting program	panel1.Controls[0].Select();	0
6368518	6368424	Any simple recommendations for creating a Password Salt and Hashing it?	private static string CreateSalt(int size)\n{\n  // Generate a cryptographic random number using the cryptographic\n  // service provider\n  RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\n  byte[] buff = new byte[size];\n  rng.GetBytes(buff);\n  // Return a Base64 string representation of the random number\n  return Convert.ToBase64String(buff);\n}	0
7473922	7473866	String from codebehind to array in Javascript	var availableTags = <% =prodNames %>;	0
5337411	5337118	C# Add TimeSpan to DateTime by considering BusinessDays	public DateTime AddBusinessDays(List<DateTime> businessDays, DateTime startDate, TimeSpan span)\n{\n    // Add the initial timespan\n    DateTime endDate = startDate.Add(span);\n\n    // Calculate the number of holidays by taking off the number of business days during the period\n    int noOfHolidays = span.Days - businessDays.Where(d => d >= startDate && d <= endDate).Count();\n\n    // Add the no. of holidays found\n    endDate.AddDays(noOfHolidays);\n\n    // Skip the end date if it lands on a holiday\n    while (businessDays.Contains(endDate))\n        endDate = endDate.AddDays(1);\n\n    return endDate;\n}	0
17328669	17328213	Failure to convert FileStream length to int	// Read bytes in from file, capture length of returned array\nvar bytes = File.ReadAllBytes(szFileName);\nvar nLength = bytes.Length;\n\n// Your unmanaged pointer.\nIntPtr pUnmanagedBytes = new IntPtr(0);\n\n// Allocate some unmanaged memory for those bytes.\npUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);\n\n// Copy the managed byte array into the unmanaged array.\nMarshal.Copy(bytes, 0, pUnmanagedBytes, nLength);\n\n// Send the unmanaged bytes to the printer.\nvar bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);\n\n// Free the unmanaged memory that you allocated earlier.\nMarshal.FreeCoTaskMem(pUnmanagedBytes);\n\nreturn bSuccess;	0
27681355	27680180	Eliminating Possible Duplicate Of MDIChildren	foreach(Form child in this.MdiChildren)\n        {\n            if (child is FAnalysis)\n            {\n                if (child.WindowState == FormWindowState.Minimized)\n                {\n                    child.WindowState = FormWindowState.Normal;\n                }\n                child.BringToFront();\n                return; // stop looking and exit the method\n            }\n        }\n\n        // no match was found; create a new child:\n        FAnalysis fanalysis = new FAnalysis();\n        fanalysis.MdiParent = this;\n        fanalysis.Show();\n        changeVisible(false, false, true, true, true, true);	0
5650385	5650293	C# - Get all interfaces from a folder in an assembly	string directory = "/";\n    foreach (string file in Directory.GetFiles(directory,"*.dll"))\n    {\n        Assembly assembly = Assembly.LoadFile(file);\n        foreach (Type ti in assembly.GetTypes().Where(x=>x.IsInterface))\n        {\n            if(ti.GetCustomAttributes(true).OfType<ServiceContractAttribute>().Any())\n            {\n                // ....\n\n            }\n        } \n    }	0
757541	757458	How to make this linq efficient	public IEnumerable<IJMonikeElements> GetElements() {\n    // Do some magic here to determine which elements are selected\n    return (from e in this.allElements where e.IsSelected select e).AsEnumerable();\n\n//  This could also be a complicated loop\n//  while (someCondition()) {\n//      bool isSelected = false;\n//      var item = this.allItems[i++];\n\n        // Complicated logic determine if item is selected\n//      if (isSelected) {\n//          yield return item;\n//      }\n    }\n}\n\npublic IEnumerable<BusinessObject> GetSelectedObjects() {\n    return m_oIJSelectSet.GetElements().Cast<BusinessObject>();\n}	0
11214015	11213966	How to read a text file from a Windows Service?	System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Foo.xml");	0
6176760	6176628	how to get date from string like this?	static void Main(string[] args)\n        {\n            string source = "HTTP test [17] 20110515150601.log";\n            Regex regex = new Regex(@"(\d{8})\d*\.log");\n            var match = regex.Match(source);\n            if (match.Success)\n            {\n                DateTime date;\n                if (DateTime.TryParseExact(match.Groups[1].Value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))\n                {\n                    Console.WriteLine("Parsed date to {0}", date);\n                }\n                else\n                {\n                    Console.WriteLine("Could not parse date");\n                }\n            }\n            else\n            {\n                Console.WriteLine("The input is not a match.");\n            }\n            Console.ReadLine();\n        }	0
4396487	4396416	How to send HTTPS request from login box in C#	string username = "user";\nstring password = "pass";\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");\nrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";\n\nrequest.Method = "POST";\n\nusing (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))\n{\n    writer.Write("nick=" + username + "&password=" + password);\n}	0
10354317	10354269	Accessing different elements in an array returned from a WebMethod	msg.d[0]	0
849741	849558	Saving XML stream in C# says that it's being used by another process	lock(some_shared_object)\n{\n    //Your code here\n}	0
1323371	1323283	How to match URL in c#?	Regex r = new Regex("(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*");\n// Match the regular expression pattern against a text string.\nMatch m = r.Match(text);\nwhile (m.Success) \n{\n   //do things with your matching text \n   m = m.NextMatch();\n}	0
24302461	24302195	NHibernate query to get record matching the max of a column	// the inner (sub) select resulting in just max TimeStamp\nvar maxTimestamp = DetachedCriteria.For<HealthCheckReport>()\n    .SetProjection(Projections.Max("TimeStamp"));\n\n// the root query with a WHERE\nvar criteria = session.CreateCriteria<HealthCheckReport>()\n    .Add(Subqueries.PropertyEq("TimeStamp", maxTimestamp));\n\n// the most fresh one\nvar result = criteria\n    .UniqueResult();	0
22745381	22743530	How to figure out is the paragraph wrapped in a RichTextBox	TextPointer contentStart = _richTextBox.Document.ContentStart;\nTextPointer contentEnd = _richTextBox.Document.ContentEnd;\n\nwhile (true)\n{\n    var tpStart = contentStart.GetLineStartPosition(0);\n    var tpEnd = contentEnd.GetLineStartPosition(0);\n    var offset = tpStart.GetOffsetToPosition(tpEnd);\n    if (offset != 0)\n    {\n        _richTextBox.FontSize -= 1; // at least two lines\n    }\n    else\n    {\n        break; // one line\n    }\n}	0
17018509	17017864	Only Allow to enter Numeric values Datagridview specific column	private void dataGridView1_EditingControlShowing(object sender, \n    DataGridViewEditingControlShowingEventArgs e)    \n{\nString sCellName =  dataGridView1.Columns(e.ColumnIndex).Name; \n    If (UCase(sCellName) == "QUANTITY") //----change with yours\n    {\n\n        e.Control.KeyPress  += new EventHandler(CheckKey);\n\n     }\n}\n\nprivate void CheckKey(object sender, KeyPressEventArgs e)\n{\n    if (!char.IsControl(e.KeyChar) \n        && !char.IsDigit(e.KeyChar) \n        && e.KeyChar != '.')\n    {\n        e.Handled = true;\n    }   \n}	0
892826	879675	Show/Hide an accordion panel in Jquery when clicking edit in a gridview?	ClientScript.RegisterStartupScript\n(Me.GetType(), "ClientScript", "$(document).ready(function(){$('#accordion').accordion('activate', parseInt(theIndex));}", True)	0
4491008	4490826	ObjectDataSource could not find a non-generic method	public DataTable GetBrokers() { \n              return GetBrokers(null);\n}	0
11220485	11217246	How to share services across projects in Service Stack?	public AppHost()\n    : base("Combined Services", \n        typeof(ServiceX).Assembly, \n        typeof(ServiceD).Assembly)\n{\n}	0
13301989	13301945	Detect OS version - Windows Phone 7 or Windows Phone 8?	Environment.OSVersion	0
21090500	21090366	Fastest way to extract variable width signed integer from byte[]	static int[] Base64ToIntArray3(string base64, int size) {\n  byte[] data = Convert.FromBase64String(base64);\n  int cnt = data.Length / size;\n  int[] res = new int[cnt];\n  for (int i = 0; i < cnt; i++) {\n    switch (size) {\n      case 1: res[i] = data[i]; break;\n      case 2: res[i] = BitConverter.ToInt16(data, i * 2); break;\n      case 3: res[i] = data[i * 3] + data[i * 3 + 1] * 256 + data[i * 3 + 2] * 65536; break;\n      case 4: res[i] = BitConverter.ToInt32(data, i * 4); break;\n    }\n  }\n  return res;\n}	0
7401379	7401239	Problem with accessing xml node value in asp.net	XmlNode chartNode = doc.GetElementsByTagName("Chart")[0];\n        XmlNode colorNode = doc.GetElementsByTagName("Chart")[0].ChildNodes[0].ChildNodes[0];\n\n        string minvalue = colorNode.Attributes["minValue"].Value;\n        string bgColor = chartNode.Attributes["bgColor"].Value;	0
23084474	23083643	How to get value of some object in XML string in C#?	const string example_xml = "<RESPONSE> <SINGLE> <KEY name=\"sitename\"> <VALUE>Stackoverflow</VALUE> </KEY> <KEY name=\"username\"> <VALUE>this value</VALUE> </KEY> </SINGLE> </RESPONSE>";\n\nXDocument doc = XDocument.Parse(example_xml);\nvar keys = doc.Descendants("KEY");\nvar userKeys = keys.Where(item => item.Attribute("name").Value == "username").ToList();\nuserKeys.ForEach(item => Console.WriteLine(item.Value));	0
12568278	12531342	Import data from multiple CSV files to an Excel sheet	public static System.Data.DataTable GetDataTable(string strFileName)\n\n{\n        System.Data.OleDb.OleDbConnection dbConnect = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + ";Extended Properties = \"Text;HDR=YES;FMT=TabDelimited\"");\n        dbConnect.Open();\n        string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";\n        System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, dbConnect);\n        System.Data.DataSet dSet = new System.Data.DataSet("CSV File");\n        adapter.Fill(dSet);\n        dbConnect.Close();\n        return dSet.dbTables[0];\n }	0
7634168	7634113	Is it possible to get data from web response in a right encoding	using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) //<----- Get http responce, if this is not http respone you need to know what encoding\n{       \n    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet))) //<----- If not HTTP responce, then response.CharacterSet must be replaced by predefined encoding, i.e. UTF-8\n    {\n        string tmpStreamData = reader.ReadToEnd(); // <----- Read whole stream to string\n        MessageBox.Show(tmpStreamData);\n    }\n}	0
8203927	8203900	how get yesterday and tomorrow datetime in c#	today = System.DateTime.Now\n      answer  = today.AddDays(36)\n      answer2 = today.AddDays(-36)	0
1155812	1155797	Send a email with a HTML file as body (C#)	using (StreamReader reader = File.OpenText(htmlFilePath)) // Path to your \n{                                                         // HTML file\n    MailMessage myMail = new MailMessage();\n    myMail.From = "from@microsoft.com";\n    myMail.To = "to@microsoft.com";\n    myMail.Subject = "HTML Message";\n    myMail.BodyFormat = MailFormat.Html;\n\n    myMail.Body = reader.ReadToEnd();  // Load the content from your file...\n    //...\n}	0
6638498	6638454	Having trouble finding out how to call this extension method on a Dictionary<T,T>	namespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Dictionary<string, string> dict = new Dictionary<string, string>();\n            dict.AttributesToString();\n        }\n    }\n\n    public static class Extensions\n    {\n        public static string AttributesToString<T, T1>(this Dictionary<T, T1> dict)\n        {\n            StringBuilder sb = new StringBuilder();\n\n            foreach (KeyValuePair<T, T1> kv in dict)\n            {\n                sb.Append(" " + kv.Key + "=\"" + kv.Value + "\"");\n            }\n\n            return sb.ToString();\n        }\n    }\n}	0
7154636	7154536	C# Interfaces - How Can I Do This?	public interface IWorkPerson\n{\n    string FirstName { get; set; }\n    string LastName  { get; set; }\n    string WorkPhone { get; set; }\n}\npublic interface IHomePerson\n{\n    string FirstName { get; set; }\n    string LastName  { get; set; }\n    string HomePhone { get; set; }\n}\npublic class Person : IWorkPerson , IHomePerson\n{\n    public string FirstName { get; set; }\n    public string LastName  { get; set; }\n    public string WorkPhone { get; set; }\n    public string HomePhone { get; set; }\n}	0
18785718	18782396	hosting win32 into wpf not working in windows 7	while (process.MainWindowHandle == IntPtr.Zero)\n{\n   Thread.Sleep(100);\n   process.Refresh();\n}	0
33031934	33031530	Custom exception with properties	[Serializable()]\n        public class YourCustomException : Exception, ISerializable\n        {\n            public Int Id { get; set; }\n            public Int ErrorCode { get; set; }\n            public YourCustomException() : base() { }\n            public YourCustomException(string message) : base(message) { }\n            public YourCustomException(string message, System.Exception inner) : base(message, inner) { }\n            public YourCustomException(SerializationInfo info, StreamingContext context) : base(info, context) { }\n            public YourCustomException(string message, int Id, int ErrorCode)\n                : base(message)\n            {\n                this.Id = Id;\n                this.ErrorCode = ErrorCode;\n            }\n        }	0
5435001	5434709	Using SystemParametersInfo from C# (SPI_GETSCREENREADER SPI_SETSCREENREADER)	[DllImport("user32.dll", SetLastError = true)]\nstatic extern bool SystemParametersInfo(int uiAction, int uiParam, IntPtr pvParam, int fWinIni);	0
12474951	12474908	How to get All static property and it's values of a class using reflection	public static Dictionary<string, string> GetFieldValues(object obj)\n{\n    return obj.GetType()\n              .GetFields(BindingFlags.Public | BindingFlags.Static)\n              .Where(f => f.FieldType == typeof(string))\n              .ToDictionary(f => f.Name,\n                            f => (string) f.GetValue(null));\n}	0
8406657	8406582	Union of two arrays	function merge(left,right)\n    var list result\n    while length(left) > 0 or length(right) > 0\n        if length(left) > 0 and length(right) > 0\n            if first(left) ??? first(right)\n                append first(left) to result\n                left = rest(left)\n            else\n                append first(right) to result\n                right = rest(right)\n        else if length(left) > 0\n            append first(left) to result\n            left = rest(left)\n        else if length(right) > 0\n            append first(right) to result\n            right = rest(right)\n    end while\n    return result	0
15926866	15879461	DataGridView without selected row at the beginning	dataGridView1.DefaultCellStyle.SelectionBackColor = dataGridView1.DefaultCellStyle.BackColor;\ndataGridView1.DefaultCellStyle.SelectionForeColor = dataGridView1.DefaultCellStyle.ForeColor;	0
28038622	28038145	How to insert hyphen "-" after 2 digits automatically in TextBox?	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        string sVal = textBox1.Text;\n\n        if (!string.IsNullOrEmpty(sVal) && e.KeyCode != Keys.Back)\n        {\n            sVal = sVal.Replace("-", "");\n            string newst = Regex.Replace(sVal, ".{2}", "$0-");\n            textBox1.Text = newst;\n            textBox1.SelectionStart = textBox1.Text.Length;\n        }\n    }	0
25810795	25810641	Convert Func<T, TProperty> to Expression<Func<T, Property>>	private readonly Expression<Func<TEntity, TKey>> _keySelector;\n\nprotected Expression<Func<TEntity, TKey>> KeySelector {\n    get {\n        return _keySelector;\n    }\n}\n\nprotected RepositoryBase(Expression<Func<TEntity, TKey>> selector) {\n    _keySelector = selector;\n}	0
17149074	17148856	Using Angular to Download a File via Ajax	window.location='url'	0
28812525	28805851	How to Find and change words to Italic in Office Interop Word	private void FindAndItalicize(Microsoft.Office.Interop.Word.Application doc, object findText)\n    {\n        var rng = doc.Selection.Range;\n\n        while(rng.Find.Execute(findText))\n        {\n            rng.Font.Italic = 1;\n        }\n    }	0
6989675	6989501	How to bind a Grid in WPF when using MVC?	List<ColumnData>	0
8321830	8321771	How to separate numbers and characters with RegEx?	string s = "123.45ms";\n        Match m = Regex.Match(s, @"(\d+([.,]\d+)?) *(ms|s)");\n\n        if (m.Success)\n        {\n            Console.WriteLine(m.Groups[1]);\n            Console.WriteLine(m.Groups[3]);\n        }	0
30983188	30983023	Sort Array by contains specific char count	var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToList();	0
18264221	18264102	linq: check if there are entries from the same day or week in a particular table	//first get to the last monday i.e. start of the week\n\nint delta = DayOfWeek.Monday - currentDate.date.DayOfWeek;\nDateTime monday = currentDate.date.AddDays(delta);\n\n\nvar submitCount = from campaignMessages in dcCRData.Mytable\n                  where  campaignMessages.Created >= monday &&  campaignMessages.Created <= monday.AddDays(7)    \n                  select campaignMessages;	0
6373040	6372987	How to properly redirect (while setting a cookie) in MVC3/Razor?	return RedirectToAction("Home", "Index")	0
16339706	16339237	How to implement a sealed, public nested class that can only be created by its enclosing class?	static Outer()\n{\n    System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof (Inner).TypeHandle);\n}	0
4932055	4932029	Key value pair as enum	public enum infringementCategory\n{ \n    [Description("INF0001")]\n    Infringement,\n    [Description("INF0002")]\n    OFN\n}	0
1266892	1266863	Correct String Escaping for T-SQL string literals	PreparedStatement ps = con.prepareStatement("SELECT * FROM Books WHERE BookTitle IN (?, ?)");\nps.setString(1, "Mars and Venus");\nps.setString(2, "Stack's Overflow\nand \n");\n\nResultSet rs = ps.executeQuery();\n....	0
25778246	25778169	Separating a line of code to find a specific part	string str = @"<tabBar contentMode=""scaleToFill"" translatesAutoresizingMaskIntoConstraints=""NO"" id=""ZTF-8n-Y8A"">\n    <rect key=""frame"" x=""2"" y=""431"" width=""320"" height=""49""/>\n    <autoresizingMask key=""autoresizingMask"" widthSizable=""YES"" flexibleMinY=""YES""/>\n    <color key=""backgroundColor"" white=""0.0"" alpha=""0.0"" colorSpace=""calibratedWhite""/>\n    <items>\n          <tabBarItem title=""Item"" id=""vcz-nP-1al""/>\n          <tabBarItem title=""Item"" id=""9mv-O2-GXB""/>\n    </items>\n</tabBar>";\n\n XDocument xdoc = XDocument.Parse(str);\n string width = xdoc.Root.Element("rect").Attribute("width").Value;	0
28924563	28924523	c# I want to know if the first 3 characters in a string is letter?	var input = "abc123";\nvar result = input.Take(3).All(char.IsLetter);	0
16610080	16609973	How to generate an XML file dynamically using XDocument?	XmlDocument xml = new XmlDocument();\nXmlElement root = xml.CreateElement("children");\nxml.AppendChild(root);\n\nXmlComment comment = xml.CreateComment("Children below...");\nroot.AppendChild(comment);\n\nfor(int i = 1; i < 10; i++)\n{\n    XmlElement child = xml.CreateElement("child");\n    child.SetAttribute("age", i.ToString());\n    root.AppendChild(child);\n}\nstring s = xml.OuterXml;	0
7818659	7818625	save a username to registry each time	System.Collections.Specialized.StringCollection	0
13889193	13889063	Add Thousand Separator To A Double Value(Control Decimals, Remove Zero Decimals)	string str_Money = "";\nif (money % != 0) // test for decimals\n{\n    str_Money = string.Format("{0:n0}", money); // no decimals.\n}\nelse\n{\n    str_Money = string.Format("{0:n}", money);\n}	0
302891	302821	Serialization in C# without using file system	StringWriter outStream = new StringWriter();\nXmlSerializer s = new XmlSerializer(typeof(List<List<string>>));\ns.Serialize(outStream, myObj);\nproperties.AfterProperties["myNoteField"] = outStream.ToString();	0
15320890	15313666	Cannot inherit a Base Controller class which has no default constructor	protected BaseController(){}	0
19027169	19027048	Set string value from clipboard contents C#	[STAThreadAttribute]\nstatic void Main( string[] args )	0
442368	442337	Detect change of resolution c# WinForms	Microsoft.Win32.SystemEvents.DisplaySettingsChanged	0
12064456	12064010	XPath for selecting a node under a specific node with zero or more nodes in between	string schemaXPath = "//parent[@name='Iam']//toy[@name='wii']";\n        XPathNavigator schemaNavigator  = oXmlDocument.CreateNavigator();\n        XPathNodeIterator nodeIter = schemaNavigator.Select(schemaXPath, namespaceMgr);\n\n        while (nodeIter.MoveNext() == true)\n        {\n            Console.WriteLine(nodeIter.Current.Name);\n        }	0
1113439	1113345	sending mail along with embedded image using asp.net	string html = @"<html><body><img src=""cid:YourPictureId""></body></html>";\nAlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);\n\nLinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);\nyourPictureRes.ContentId = "YourPictureId";\naltView.LinkedResources.Add(yourPictureRes);\n\nMailMessage mail = new MailMessage();\nmail.AlternateViews.Add(altView);	0
10302463	10301885	How to create a DateTimeOffset set to Midnight in Pacific Standard Time	DateTime dateInDestinationTimeZone = System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, System.TimeZoneInfo.Utc.Id, "Pacific Standard Time").Date;	0
20537040	20536956	calling image in grid view from sql	img.Src = Server.MapPath("~/images/test.png");	0
14067185	14067112	Syntax for checking multiple conditions in an 'if' statement	var accepted = new HashSet<int>(new[] {1, 5, 7, 8, 9, 10});\n\n@if (accepted.Contains(item.TotalImages))\n{\n   string mystring = "string one"\n}	0
6531797	6531693	Linq to SQL cascading delete with reflection	ON CASCADE DELETE	0
6832581	6832508	Month/Year SQL to correct format	SELECT\n  *\nFROM\n  members\nWHERE\n  signupdate BETWEEN @param AND DATEADD(MONTH, 1, @param) - 1	0
7064606	7064208	How to show a sub object property in GridView with LINQ	public string IssueTitle\n{\n    get { return issues.Title; }\n}	0
9666631	9666562	How to get the unit test method name at runtime from within the unit test?	[Test]\npublic void ShouldRegisterThenVerifyEmailThenSignInSuccessfully()\n{\n    string testMethodName = TestContext.CurrentContext.Test.Name;\n}	0
1700922	1700894	Comparing ICompositeUserType objects in nHibernate	var criteria = session.CreateCriteria(typeof(MoneyObject), "m")\n                             .CreateAlias("m.MoneyAmmount", "a")\n                             .Add(Expression.Lt("a.Ammount", money));	0
32723817	32723570	Entity framework takes about 10 minutes to get data from Azure sql	var messages = context.Messages.AsNoTracking()\n         .Where(m => (m.Timestamp > StartTime) && (m.Timestamp < EndTime))\n         .Where(x => x.Channel.ChannelName == Channelname)\n         .ToArray();	0
96907	96871	How can I build C# ImageList Images from smaller component images?	Bitmap image1 = ...\nBitmap image2 = ...\n\nBitmap combined = new Bitmap(image1.Width, image1.Height);\nusing (Graphics g = Graphics.FromImage(combined)) {\n  g.DrawImage(image1, new Point(0, 0));\n  g.DrawImage(image2, new Point(0, 0);\n}\n\nimageList.Add(combined);	0
11973777	11969097	NHibernate - Order by Max() of Collection property in Detached Criteria	var subQuery = DetachedCriteria\n    .For<SubNote>("sn")\n    .SetProjection(\n        Projections.Alias(Projections.Max("Date"), "maxDate"))\n    .Add(Restrictions.EqProperty("**sn.COLUMNNAME**", "n.Id"));\n\nvar results = CurrentSession.CreateCriteria<Note>("n")\n    .Add(Subqueries.Select(subQuery))\n    .SetProjection(\n        Projections.Alias("n.Id", "Id"))\n    .AddOrder(Order.Desc("maxDate")))\n    .List<Note>();	0
5147031	5147001	Convert a sequence of arrays T myArray[] to IEnumerable<T> in c#	foreach (var fi in objectType.GetFields(...))\n    yield return fi;	0
21284921	21271985	C# GeckoFX Browser - How to click/set value to XPath?	GeckoHtmlElement element = (GeckoHtmlElement)gWB.Document.GetSingleElement(x.ToString());\nif (element != null)\n{\n    element.Click();        \n}	0
26566445	26566406	why does my tab control disappear if I call a page twice in a row?	tabControl1.SelectedTab = tabMain;	0
8286297	8286270	how to decrypt a string in c#	string decoded = Encoding.Unicode.GetString( Convert.FromBase64String( encoded ) );	0
29903138	29902736	How to play a wave file using SlimDX.DirectSound?	public void setting()\n    {\n        m_DirectSound = new DirectSound();\n        m_DirectSound.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority);\n        m_DirectSound.IsDefaultPool = false;\n\n        using (WaveStream waveFile = new WaveStream(fileName))\n        {\n\n            SoundBufferDescription desc = new SoundBufferDescription();\n            desc.SizeInBytes = (int)waveFile.Length;\n            desc.Flags = BufferFlags.None;\n            desc.Format = waveFile.Format;\n\n            m_DSoundBuffer = new SecondarySoundBuffer(m_DirectSound, desc);\n            byte[] data = new byte[desc.SizeInBytes];\n            waveFile.Read(data, 0, (int)waveFile.Length);\n            m_DSoundBuffer.Write(data, 0, LockFlags.None);\n        }	0
29590394	29581903	DataMember Property with Custom Get?	[DataMember(Name = "someEpochDateTime")]\nprivate long someEpochDateTime;\n\npublic DateTime test\n{\n    get { return DateTimeConverter.FromUnixTime(someEpochDateTime); }\n}	0
21938913	21915502	Intuit IPP QBO - Get Purchase	foreach (Line invoiceLine in x.Line)\n                {\n                    itm = new LineItem();\n\n                    if (invoiceLine.Amount != 0)\n                    {\n                        itm.Description = invoiceLine.Description;\n                        itm.Description = String.IsNullOrEmpty(itm.Description) ? "n/a" : itm.Description;\n\nif (invoiceLine.DetailType == LineDetailTypeEnum.AccountBasedExpenseLineDetail)\n                        {\n                            AccountBasedExpenseLineDetail itemLineDetail =\n                                invoiceLine.AnyIntuitObject as AccountBasedExpenseLineDetail;\n\n                            itm.Quantity = 1;\n                            itm.UnitAmount = invoiceLine.Amount;\n                            itm.AccountCode = itemLineDetail.AccountRef.Value;\n                        }	0
2279208	2279003	Substring outofindex	int noZeroes = Int32.Parse(ext.Substring(i + 1))\next = ext.Substring(0, i);\nstring zeroString = new string('0', noZeroes)\n\next += zeroString;	0
6980204	6979905	Getting value of boundfield in gridview from C#	void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)\n  {\n\n    //Check if it's the right CommandName... \n    if(e.CommandName=="Add")\n    {\n      //Get the Row Index\n      int index = Convert.ToInt32(e.CommandArgument);\n\n      // Retrieve the row\n      GridViewRow row = ContactsGridView.Rows[index];\n\n      // Here you can access the Row Cells \n      row.Cells[1].Text\n\n    }\n  }	0
9288433	9288369	How to extract a value from an XML node?	var product = XElement.Parse(xmlString);\nvar price = (decimal)product.Element("price");	0
898299	898286	How to build up a Linq to Sql where clause bit by bit?	if (parameters.Value1 != null)\n{\n    results = results.Where(x => <some condition>);\n}\n\nif (parameters.Value2 != null)\n{\n    results = results.Where(x => <some other condition>);\n}	0
13292361	13292337	How to Coalesce a Lambda Delegate	_runner = runner ?? sRunner ?? (() => "Hey!");	0
28786536	28784789	How does StreamReader read all chars, including 0x0D 0x0A chars?	char[] acBuf = null;\nint iReadLength = 100;\nwhile (srFile.Peek() >= 0) {\n    acBuf = new char[iReadLength];\n    srFile.Read(acBuf, 0, iReadLength);\n    string s = new string(acBuf);\n}	0
19435532	19435477	Group Collection by value	var groups = Values.GroupBy(zi => zi.TypeQ)\n                   .Select(g => new Scores\n                         {\n                         TypeQ = g.Key, \n                         High  = g.Sum(zi=> zi.High), \n                         Low   = g.Sum(zi=> zi.Low)\n                         }\n              );	0
1737349	1737318	I want to edit my xml file	class Program\n{\n    static void Main(string[] args)\n    {\n        string path = "D:\\Documents and Settings\\Umaid\\My Documents\\Visual Studio 2008\\Projects\\EditXML\\EditXML\\testing.xml";\n        XmlDocument doc = new XmlDocument();\n        doc.Load(path);\n        var itemNode = doc.SelectSingleNode("rule/one-of/item");\n        if (itemNode != null)\n        {\n            itemNode.InnerText = "Umaid";\n        }\n        doc.Save(path);\n    }\n}	0
9115961	9115926	Avoiding repeatedly allocating an Action object without a variable / member	Action<T>	0
20698370	20698308	Strip out string from string in C#	var searchForStart = "<p class=\"how-pkg\">";\nint startIndex = input.IndexOf(searchForStart ) + searchFor.Length;\nvar searchForStop = "</p>";\nint stopIndex = input.IndexIf(searchForStop, startIndex);\n\nvar output = text.Substring(startIndex, stopIndex - startIndex);	0
1701587	1701539	How can I get a generic list from a datatable with the lowest overhead?	protected IEnumerable<Employee> GetEmployees ()\n{\n   List<Employee> list = new List<Employee>();\n   DataSet ds = Employee.searchEmployees("Byron");\n\n   foreach (DataRow dr in ds.Tables[0].Rows)\n   {\n       yield return new Employee(dr);\n   }\n}	0
22693379	22690857	Marshaling fixed size array as a member of a C# class doesn't work	[DllImport("my-lib.dll", EntryPoint="run_agency_model")]\npublic static extern void RunAgencyModel(AgencyModelInput input, [Out] AgencyModelOutput output);	0
18838940	18838795	unequal size lists to merge	List<ClassA> listA = GetListA()// ...\nList<ClassB> listB = GetListA()// ...\n\n\nif(listB.Count % listA.Count != 0)     \n      throw new Exception("Unable to match listA to listB");\n\nvar datasPerHeader = listB.Count / listA.Count;\n\nfor(int i = 0; i < listA.Count;i++)\n{\n    ClassA header = listA[i];\n    IEnumerable<ListB> datas = listB.Skip(datasPerHeader*i).Take(datasPerHeader);\n    Console.WriteLine(header.ToString());\n    foreach(var data in datas)\n    {\n          Console.WriteLine("\t{0}", data.ToString());\n    } \n}	0
28200931	28199297	VS2010 Chart control, how to display a blank chart?	// short reference for our dummy:\nSeries S0 = chart1.Series[0];\n// a simple type\nS0.ChartType = SeriesChartType.Line;\n// set 10 point with x-values going from 0-100 and y-values going from 1-10:\nfor (int i = 0; i < 100; i +=10)  S0.Points.AddXY(i , i / 10);\n// or add only a few, e.g. the first and last points:\n//S0.Points.AddXY(100, 10);\n//S0.Points.AddXY(0, 10);\n// hide the line:\nS0.Color = Color.Transparent;\n// hide the legend text (it will still take up a little space, though)\nS0.LegendText = " ";\n// limit the axis to the target values\nchart1.ChartAreas[0].AxisX.Maximum = 100;\nchart1.ChartAreas[0].AxisX.Minimum = 0;	0
11625584	11625554	DateTime comparison without time part?	s.okuma_tarihi.Value.Date == startDate.Date	0
23017565	23017532	WPF ComboBox to ObservableCollection binding	ComboBox ItemsSource="{Binding OSCollection}" DisplayMemberPath="Name"	0
5066706	5066179	EF4 - Many to many relationship, querying with contains and List<int>	var officers = db.Officers\n    .Where(o => o.Enabled == true \n        && o.Geographies.Any(g => geographyIds.Contains(g.Id)));	0
12913979	12900380	I need to be able to cancel a long running NHibernate query that just reads data	_session.CancelQuery();	0
30868315	30868250	How to get current memory page size in C#	Environment.SystemPageSize	0
21050982	21050883	Is there a way to detect if a user drops more than one file on my C# icon?	var args = Environment.GetCommandLineArgs()\nif(args.Length > 0) {\n    foreach(var s in args) {\n       Console.WriteLine(s);\n    }\n}	0
1861102	1861049	Use XmlSerializer to add a namespace without a prefix	var x = new XmlSerializer(\n    typeof(OrderContainer), \n    "http://blabla/api/products");\nvar ns = new XmlSerializerNamespaces();\nns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");\nx.Serialize(stream, orderContainer, ns);	0
22690457	22689473	Unittesting Confirmation in WPF Prism	sut.CopyProjectConfirmationRequest.Raised += (s, e) =>\n  {\n    Confirmation context = e.Context as Confirmation;\n    context.Confirmed = true;\n    e.Callback();\n  };	0
26234251	26233799	Remove expire attribute in cookies	DateTime.MaxValue;	0
13863661	13863114	Show position of item in a list	public int getPosition(fruit_trees tree)\n{\n fruit_trees ft = first_tree;\n if(ft.tree_type == tree.tree_type)\n {\n      return 0; //or return 1 depending on how you want to index stuff\n }\n int i = 1;//possibly set to 2 if returning 1 above\n while(ft.next_tree != null)\n {\n     ft = ft.next_tree;\n     if(ft.tree_type == tree.tree_type)\n     {\n        return i; \n     }\n     i++;\n }\n\n return -1; //or something else here to show that its not in the list\n\n}	0
6392348	6392327	Finding the client ID of dynamically created controls?	protected Label loneStar = new Label { ID = "loneStar", Text = "Raspeberry", ForeColor = System.Drawing.Color.DarkGray};	0
544377	544310	Best way to change the value of an element in C#	XDocument xdoc = XDocument.Load("file.xml");\n        var element = xdoc.Elements("MyXmlElement").Single();\n        element.Value = "foo";\n        xdoc.Save("file.xml");	0
10588539	10588467	How to stop multithread start by for loop condition	Thread[] threads = new Thread[8];\nfor (int i = 0; i < 8; i++)\n{\n    doImages    = new DoImages(this, TCPPORT + i);\n    var thread  = new Thread(doImages.ThreadProc);\n    threads[i] = thread;\n    thread.Name = "Imaging";\n    var param = (i + 1).ToString();                    \n    thread.Start(param);\n}\nfor (int i = 0; i < 8; i++)\n{\n    threads[i].Join();\n}	0
4379449	4378719	Updating an embedded document in MongoDB with official C# driver	var division = GetDivisionById(1);\ndivision.Name = "New Name";\n// change any other properties of division you want\ncollection.Update(\n    Query.EQ("Divisions._id", 1),\n    Update.Set("Divisions.$", BsonDocumentWrapper.Create<IDivision>(division))\n);	0
14375260	14375233	Build a string from a string[] without using any loops	string[] strArr = { "Abc", "DEF", "GHI" };\n\n    //    int i = 0;\n    //    string final=string.Empty;\n    //IterationStart:\n    //    if (i < strArr.Length)\n    //    {\n    //        final += strArr[i] + ",";\n    //        i++;\n    //        goto IterationStart;\n    //    }\n    //Console.WriteLine(final);\n\n     string str = string.Join(",", strArr);\n     Console.WriteLine(str);	0
21706862	21706667	How to receive focus when clicking on the background of a stackpanel?	Panel.Zindex	0
1076084	1075992	How can I organize this data into the objects I want with LINQ?	// GetAnonymousCollection() is hard to define... ;)\nvar anonymous = GetAnonymousCollection();\n\nIEnumerable<Agency> result = anonymous\n    .GroupBy(a => a.AgencyID)\n    .Select(ag => new Agency()\n    {\n        AgencyID = ag.Key,\n        AgencyName = ag.First().AgencyName,\n        Rules = ag\n            .GroupBy(agr => agr.AudiRuleID)\n            .Select(agrg => new AuditRule()\n            {\n                AuditRuleID = agrg.Key,\n                AuditRuleName = agrg.First().AuditRuleName,\n                AvgDaysWorked = (Int32)agrg.Average(agrgr => agrgr.DaysWorked)\n            })\n      });	0
12977399	12976756	Can somebody provide a simple C# coding example for capturing SharePoint details for a single file?	string fullItemUri = "http://community.xx.com/yada/blah/MyFile.xls";\n\nusing (SPSite site = new SPSite(fullItemUri))\nusing (SPWeb web = site.OpenWeb())\n{\n   SPListItem item = web.GetListItem(fullItemUri);\n\n   string modifiedBy = item[SPBuiltInFieldId.Modified_x0020_By] as string;\n   DateTime timeLastModified = item[SPBuiltInFieldId.Last_x0020_Modified] as DateTime;\n   int uniqueID = item.ID;\n   string fileType = item[SPBuiltInFieldId.FileType] as string;\n   string title = item[SPBuiltInFieldId.Title] as string;\n}	0
34342797	34338499	Have object being displaced, want to randomize time of displacement within set parameters, then loop that	public class thingBumps : MonoBehaviour {\n\npublic float thrust = 10; // give some default value \nRigidbody rb;// you dont need it to be public\nfloat nextKick = 0;\nfloat kickTimer = 0;\npublic float MinKickTime=1, MaxKickTime=10;//seconds\n\nvoid Start() {\n    rb = GetComponent<Rigidbody>();\n    nextKick = Random.Range(MinKickTime,MaxKickTime);\n}\n\nvoid FixedUpdate()\n{\n    kickTimer+=Time.fixedDeltaTime;\n    if(kickTimer>nextKick)\n    {\n         rb.AddForce (transform.up * thrust, ForceMode.Impulse);\n         kickTimer=0;\n         nextKick = Random.Range(MinKickTime,MaxKickTime);\n    }\n    if (Input.GetKey(KeyCode.DownArrow))\n        rb.AddForce(-transform.up * thrust,ForceMode.Impulse);\n}\n\n}	0
17623432	17623399	Get the name of the parent user control WPF C#	VisualTreeHelper.GetParent	0
15866034	15865525	I need to make insert statement with several data types in sql server using C#	public void AddCustomer(string companyName, string telephone, DateTime firstOrderDate)\n{\n   // get your connection string\n   string connectionString = ConfigurationManager.ConnectionStrings["YourConnString"].ConnectionString;\n\n   // define your query - using parameters!\n   string insertStmt = "INSERT INTO dbo.Customer(CompanyName, Telephone, DateOfFirstOrder) VALUES (@Company, @Phone, @OrderDate)";\n\n   // establish SQL connection and command\n   using(SqlConnection conn = new SqlConnection(connectionString))\n   using (SqlCommand cmd = new SqlCommand(insertStmt, conn))\n   {\n      // define parameters and set values\n      cmd.Parameters.Add("@Company", SqlDbType.NVarChar, 50).Value = companyName;\n      cmd.Parameters.Add("@Phone", SqlDbType.VarChar, 10).Value = telephone;\n      cmd.Parameters.Add("@OrderDate", SqlDbType.DateTime).Value = firstOrderDate;\n\n      // open connection, insert data, close connection\n      conn.Open();\n      cmd.ExecuteNonQuery();\n      conn.Close();\n   }\n}	0
3883771	3883762	How to convert chained static class names and a property value to a string?	public static class A\n{\n    public static class B\n    {\n        public static string c\n        {\n            get\n            {\n                return "hi";\n            }\n        }\n    }\n\n}\nclass Program\n{\n    static void Main( string[] args )\n    {\n\n        Console.WriteLine(typeof(A.B).FullName.Replace("+",".") + "." +  A.B.c  ) ;\n    }\n\n\n}	0
15432157	15432120	How does one create a List<Guid> from components of a List<struct> item?	List<Guid> guids = productShortData.Select(p => p.Id).ToList();	0
2329683	2321420	ProcessRequest from RequestInterceptor never ends [WCF]	responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";	0
14177970	14177857	How can I get the type of thrown exception from CompletedEventArgs?	if( e.Error is TimeoutException )	0
31717749	31717522	How to pass the List of class objects from Web Service to Windows Forms app	foreach (var item in webServiceComarch.ListaOsoba())\n{\n  nowaOsoba.indentyfikator = item.indentyfikator;\n  nowaOsoba.imie = item.imie;\n  ....\n  ....\n  ....\n  listaOsob.Add(nowaOsoba);\n}	0
34340180	34340092	How to trim slash using Expression in SSRS	StrDate = "2015/01"  \nStrDate = StrDate.replace("/","")  \nOUTPUT---> StrDate = "201501"	0
17248670	17241359	Issue with Updating Array	public void WriteData()\n      {\n           Console.SetCursorPosition(0, 4);\n           for (int col = 0; col < 3; col++)\n           {\n                for (int row = 0; row < 3; row++)\n                {\n                    Console.Write("{0}\t", myNos[col, row]);\n                }\n                Console.WriteLine();\n            }\n            //This was the modification\n            menu = "a";\n     }	0
21281348	21281273	Removing more than 1 item in listbox	while(listbox.SelectedItems.Count > 0)\n {\n    listbox.Items.Remove(listbox.SelectedItem);\n }	0
19596194	19596135	Reading JSON files with C# and JSON.net	dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);\n\nvar urls = new List<string>();\n\nforeach(var file in result.version.files)\n{\n    urls.Add(file.url); \n}	0
27122906	27122719	issue with saving doc file	// To search and replace content in a document part.\npublic static void SearchAndReplace(string document)\n{\n    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))\n    {\n        string docText = null;\n        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))\n        {\n            docText = sr.ReadToEnd();\n        }\n\n        Regex regexText = new Regex("Hello world!");\n        docText = regexText.Replace(docText, "Hi Everyone!");\n\n        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))\n        {\n            sw.Write(docText);\n        }\n    }\n}	0
15633460	15522541	Registering a custom PageHandlerFactory through code	public class MyHttpModule : IHttpModule\n{\n    void IHttpModule.Dispose() {\n    }\n\n    void IHttpModule.Init(HttpApplication context) {\n        context.PreRequestHandlerExecute += \n            this.PreRequestHandlerExecute;\n    }\n\n    private void PreRequestHandlerExecute(object s, EventArgs e) {\n        IHttpHandler handler = \n            this.application.Context.CurrentHandler;\n\n        // CurrentHandler can be null\n        if (handler != null) {\n            // TODO: Initialization here.\n        }            \n    }\n}	0
1109504	1109441	How do I use C# Generics for this implementation when the Generic Decision is based on a DB Value	public static class MediaInterfaceFactory\n{\n    public static IContentTypeDownloader Create(int mediaId)\n    {\n       switch (mediaId)\n       {\n            case 1:\n                return new GifDownloader();\n            case 2:\n                return new Mp3Downloader();\n\n    }\n}	0
21531221	21531045	How to convert to int and then compare in linq query c#	var idList = dt.AsEnumerable().Select(d => (int) d["Id"]).ToList();\nlist = list.Where(x => idList.Contains(x.Id));	0
7523758	7523733	Return multiple values from a method	public DataTable ValidateUser(string username, string password, out int result)\n{\n    result = 0;\n    try\n    {\n        //Calls the Data Layer (Base Class)\n    if (objDL != null)\n    {\n        int intRet = 0;\n        sqlDT = objDL.ValidateUser(username, password, out intRet);\n        result = intRet;\n    }\n//....	0
10644825	10644788	C# DataGridView date time formatting of a column	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    // If the column is the DATED column, check the\n    // value.\n    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED")\n    {\n        ShortFormDateFormat(e);\n    }\n}\n\nprivate static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)\n{\n    if (formatting.Value != null)\n    {\n        try\n        {\n            DateTime theDate = DateTime.Parse(formatting.Value.ToString());\n            String dateString = theDate.toString("dd-MM-yy");    \n            formatting.Value = dateString;\n            formatting.FormattingApplied = true;\n        }\n        catch (FormatException)\n        {\n            // Set to false in case there are other handlers interested trying to\n            // format this DataGridViewCellFormattingEventArgs instance.\n            formatting.FormattingApplied = false;\n        }\n    }\n}	0
31442585	31442331	Parsing HTML source using a loop	if (let == '>')\n{\n    inside = false;   \n    if (arrayIndex > 0 && array[arrayIndex - 1] != ' ')\n    {\n        array[arrayIndex] = ' '; \n        arrayIndex++;\n    }\n    continue;\n}	0
12067533	12067452	Find a file with particular substring in name	string name = textBox2.Text;\nstring[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours\nforeach (string file in allFiles)\n    {\n        if (file.Contains(name))\n        {\n            MessageBox.Show("Match Found : " + file);\n        }\n    }	0
23868018	23867903	using foreach to store names of one array in another in c#	directory = new DirectoryInfo(camera_dir);    \nstring[] date = new string[directory.GetFiles().Length];\nint i=0;\nforeach (FileInfo file in directory.GetFiles())\n{ \n    name[i] = file.Name.Substring(11, 6);\n    i++;\n}	0
26666703	26643656	How to make a C++-cli Windows Runtime Component to use for C#	namespace MyProject\n{\n  public ref class Foo sealed\n  {\n    //\n  };\n}	0
13367049	13366732	Getting the argument names along with values in a dynamic method invoke	var names = binder.CallInfo.ArgumentNames;\nvar numberOfArguments = binder.CallInfo.ArgumentCount;\nvar numberOfNames = names.Count;\n\nvar allNames = Enumerable.Repeat<string>(null, numberOfArguments - numberOfNames).Concat(names);\narguments.AddRange(allNames.Zip(args, (flag, value) => new Argument(flag, value)));	0
916041	916012	How to find a resource in a UserControl from a DataTemplateSelector class in WPF?	public class MyUserControl : UserControl\n{\n    public MyUserControl()\n    {\n        Resources["MyDataTemplateSelector"] = new MyDataTemplateSelector(this);\n        InitializeComponent();\n    }\n}\n\npublic class MyDataTemplateSelector : DataTemplateSelector\n{\n    private MyUserControl parent;\n    public MyDataTemplateSelector(MyUserControl parent)\n    {\n        this.parent = parent;\n    }\n\n    public override DataTemplate SelectTemplate(object item, DependencyObject container)\n    {\n        parent.DoStuff();\n    }\n}	0
398510	398501	Return values from stored procedures in C#	Create Procedure MyProc\n  @Name varchar(20),\n  @DOB DateTime,\n  @EmployeeId Integer Output = Null\n  As\n  Set NoCount On\n\n     If @EmployeeId Is Null \n       Begin\n          Insert Employees(Name, DateofBirth)\n          Values (@Name, @DOB)\n          Set @EmployeeId = Scope_Identity()\n       End\n     Else If Exists(Select * From Employees\n                    Where EmployeeId =@EmployeeId)\n       Begin\n           Update Employees Set\n              Name = Isnull(@Name, Name),\n              DateOfBirth = IsNull(@DOB, DateOfBirth)\n           Where EmployeeId = @EmployeeId\n       End\n     Else\n        Raiserror('EmployeeId %d is missing or has been deleted.',\n                   16, 1, @EmployeeId)\n\n     Return 0	0
21857224	21856981	How to read Ajax class response send from a ASP.NET MVC Contoller?	public JsonResult Function(String Parameter)\n    {\n        response returnVal = new response();\n        returnVal.attr1 = "Dummy1";\n        returnVal.attr2 = "Dummy2";\n        returnVal.attr3 = "Dummy3";\n        return Json(returnVal);\n    }	0
12499885	12499856	Remove double quotes from JSON returned string	var array = eval("[[10, 10], [15, 20], [20, 25], [32, 40], [43, 50], [55, 60], [60, 70], [70, 80], [90, 100]]");\n\nvar array = JSON.parse("[[10, 10], [15, 20], [20, 25], [32, 40], [43, 50], [55, 60], [60, 70], [70, 80], [90, 100]]");	0
6182726	6171623	How to paste table to the end of a Ms-Word document using C#	Object objUnit = Word.WdUnits.wdStory;\n\n          oWord.Selection.EndKey(ref objUnit, ref oMissing);\n\n          oWord.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);	0
12767761	12767712	How to dynamically generate html with .ascx?	//Creat the Table and Add it to the Page\n            Table table = new Table();\n            table.ID = "Table1";\n            Page.Form.Controls.Add(table);\n            // Now iterate through the table and add your controls \n            for (int i = 0; i < rowsCount; i++)\n            {\n                TableRow row = new TableRow();\n                for (int j = 0; j < colsCount; j++)\n                {\n                    TableCell cell = new TableCell();\n                    TextBox tb = new TextBox();\n\n                    // Set a unique ID for each TextBox added\n                    tb.ID = "TextBoxRow_" + i + "Col_" + j;\n\n                    // Add the control to the TableCell\n                    cell.Controls.Add(tb);\n                    // Add the TableCell to the TableRow\n                    row.Cells.Add(cell);\n                }\n                // Add the TableRow to the Table\n                table.Rows.Add(row);\n            }	0
9828405	9828110	a way to open a new window while closing the previous window	//Somewhere in your class \nYourOtherForm otherForm = null;\n\n//then, on the event handler\nprivate void button2_Click(object sender, RoutedEventArgs e)  {\n    if((otherForm.IsDisposed) || (null == otherForm)) {\n         otherForm = new YourOtherForm();\n         // or, this is an MDI or something\n         // otherForm = new YourOtherForm(this);\n         // assuming you have an extra constructor to pass the parent\n    }\n    otherForm.Show();\n    this.Close(); // or this.Hide(); if it's the main form\n}	0
3211082	3209973	Apply dynamic where clause to joined table	int? someID = null;\nint? someOtherID = 4;\n\nvar myQuery = from tab1 in context.Table1 \n              join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID \n              where tab1.TypeCode == 3 \n               && (someID == null || tab2.SomeID == someID)\n               && (someOtherID == null || tab2.SomeOtherID == someOtherID)\n              select tab1.ID;	0
16291221	16290791	Searching a list using an array as the parameter list using LINQ	var namesToActions = new Dictionary<string, string>()\n    {\n        { "marge" , "get dye" },\n        { "homer", "mmm beer"},\n        { "lisa", "blow saxophone"},\n        { "bart", "have a cow"},\n        { "maggie", "bang"}\n    };\n\nsomeActions.ForEach(a => callRoutine(namesToActions[a]));	0
2233713	2233691	Parse hour and AM/PM value from a string - C#	string input = "9:00 PM";\n\nDateTime result;\nif (!DateTime.TryParse(input, out result))\n{\n    // Handle\n}\n\nint hour = result.Hour == 0 ? 12 \n           : result.Hour <= 12 ? result.Hour \n           : result.Hour - 12;\nstring AMPM = result.Hour < 12 ? "AM" : "PM";	0
30894178	30718322	Read uploaded pptx file with Open XML SDK	using DocumentFormat.OpenXml.Packaging;\nusing DocumentFormat.OpenXml.Presentation;\nusing DocumentFormat.OpenXml;	0
730818	702765	Format Excel Chart Background using C#	xlChart.Interior.Color = ColorTranslator.ToOle(Color.LightSkyBlue);\nchart.ChartArea.Fill.TwoColorGradient(\n       Microsoft.Office.Core.MsoGradientStyle.msoGradientHorizontal, \n       1);	0
1326568	1326529	How to modify data within datatable in C#	public static class ReportsExtensions\n{\n\n    public static GetChangedList(this ReportsTable tbl)\n    {\n        foreach(DataRow report in tbl)  \n        {  \n             Guid reportId = new Guid(report["ReportId"].ToString());  \n             string reportTitle = GetReportTitle(conn, reportId, UserId, GetReportLanguage(reportId));  \n             report["ReportName"] = reportTitle;  \n        }  \n    }\n}\nGridView1.DataSource = dtReportList.GetChangedList();  \nGridView1.DataBind();	0
10975707	10975674	How to check if all items belong to same type using LINQ	bool isValid = products.All(x => x.Type == products.First().Type);	0
27174758	27166800	How to increase the padding of a MSChart Datapoint label	point.LabelBorderWidth = 7;\npoint.LabelBorderColor = point.LabelBackColor;	0
12696545	12587096	Forcing Gridview to display x number of rows including empty rows	DataTable dt1 = new DataTable();\nDataRow dr1;\ndt1.Columns.Add("ProjectID");\ndt1.Columns.Add("ProjectName");\ndt1.Columns.Add("Country");\nfor (int i = 0; i < 10; i++)\n{\n     dr1 = dt1.NewRow();\n     dr1["ProjectID"] = dr1["ProjectName"] = dr1["Country"] = "";\n     dt1.Rows.Add(dr1);\n}\ndt1.AcceptChanges();\nProjectListGridView.DataSource = dt1;\nProjectListGridView.DataBind();	0
15355755	15355531	Restrict Duplicate Value in DataGrid View in C# from Listview?	ArrayList arrListChkIDs = new ArrayList();\n//Now Get and Check The Code from List View or put the Index Number  at subItems\nstring Code = listView.SelectedItems[0].SubItems["Code"].Text;\nif (!arrListChkIDs.Contains(Code))\n{\n\n}\nelse\n{\n    MessageBox.Show("Row Already Exist!",\n                    MessageBoxButtons.OK, \n                    MessageBoxIcon.Error);\n    return;\n}	0
8833442	8833240	Tips for a shared transaction with multi-threading	// In the base class\nprotected SqlTransaction Transaction;\n\npublic void Save() \n{ \n    ... \n    using (var transaction = BeginSharedTransaction())\n    {\n        Save(Transaction);\n\n        transaction.Commit();\n    }\n    ... \n}\n\npublic void Save(SqlTransaction transaction) \n{ \n    Transaction = transaction;\n    SaveItem();\n}\n\nprotected virtual void SaveItem() { ... /* uses Transaction on all SQL commands */ ... }\n\n// in the derived class\npublic override void SaveItem()\n{\n    other1.Save(Transaction);\n    base.SaveItem();\n    other2.Save(Transaction);\n}\n\n\n// In the base class (or another helper class)\npublic static SqlTransaction BeginSharedTransaction()\n{\n    return ... // conn.BeginTransaction();\n}	0
13370107	13369871	Accessing session from static method called via AJAX	[WebMethod(EnableSession = true)]\npublic List<string> GetData(string parameter)	0
30274940	30271935	Json deserialization with different variable names (FIXED Posted Solution)	dynamic data = JsonConvert.DeserializeObject(responseData);\nIDictionary<string, JToken> cards = data;\n\nforeach (var card in cards)\n{\n    var key = card.Key;\n    var value = card.Value;\n}	0
21722347	21709259	Excel add-in c# find	Excel.Application exc = new Excel.Application();\n    if (exc == null)\n    {\n        Console.WriteLine("ERROR: EXCEL couldn't be started!");\n    }\n\n    Workbooks workbooks = exc.Workbooks;\n    Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);\n    Sheets sheets = workbook.Worksheets;\n    Worksheet worksheet = (Worksheet)sheets.get_Item(1);\n\n    if (worksheet == null)\n    {\n        Console.WriteLine("ERROR: worksheet == null");\n    }      \n    Excel.Range range = worksheet.UsedRange;\n    Excel.Range currentFind; \n\n    currentFind = range.Cells.Find(txtFind.Text.ToString(), Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole,\n                    Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, false, false);\n    if (currentFind != null)\n    {\n        MessageBox.Show("found");\n    }\n    else\n    {\n        MessageBox.Show("not found");\n    }	0
2914795	2914665	Unable to read values from Nested SortedDictionary in C#	foreach (string key1 in baseItemCounts.Keys)\n        {\n            foreach (string key2 in baseItemCounts[key1].Keys)\n            {\n                Console.WriteLine("{0}, {1}, {2}", key1, key2, baseItemCounts[key1][key2]);\n            }\n        }	0
18156045	18147357	Generic grouping with Crystal Reports	//Temp string to receive column name\nString temp = Ds.Customer.Column3Column.ToString();\n\n\n//objRpt is my instancied report : objRpt = new CrystalReport1();\n//I set the formulafield[0] with the column name\nobjRpt.DataDefinition.FormulaFields[0].Text = "{Customer." + temp.Replace("{", "") + "}";	0
27017417	27017256	Hiding dropdownlist in templatefield in gridview asp.net C# after insert into the database	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        DropDownList ddl = e.Row.Cells[4].FindControl("DropDownList2") as DropDownList;\n        if (ddl != null)\n        {\n            // if (your_condition == true)\n            //{\n                    ddl .Visible = false;\n\n            //}\n\n        }\n    }\n}	0
20582635	20582591	Same path works fine with files and does not with folder	Directory.Move(@"\\192.168.1.244\old_name", @"\\192.168.1.244\new_name");	0
23859415	23859369	How to add multiple canvases to a picturebox?	private void Form1_Load(object sender, EventArgs e)\n{\n    listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;\n}\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (listBox1.SelectedItem == "Circle")\n    {\n        pictureBox1.Image = circle;\n    }\n}	0
8848539	8848434	TCP Sending Simple Flood Control And Sync - P2P Webcam	Image latestUnsentImage	0
3140896	3140880	Getting a foreach to run once	dateQuery.First().Element("HistoryCreation").Value	0
17448552	17448465	send pdf file to a printer - print pdf	private void SendToPrinter()\n    {\n        ProcessStartInfo info = new ProcessStartInfo();\n        info.Verb = "print";\n        info.FileName = @"c:\output.pdf";\n        info.CreateNoWindow = true;\n        info.WindowStyle = ProcessWindowStyle.Hidden;\n\n        Process p = new Process();\n        p.StartInfo = info;\n        p.Start();\n\n        p.WaitForInputIdle();\n        System.Threading.Thread.Sleep(3000);\n        if (false == p.CloseMainWindow())\n            p.Kill();\n    }	0
28677333	28673361	Send embedded image email from web application	oXml.LoadXml(@"");	0
14790230	14789709	Printing over several pages	pageCount = 1;\n    Index = 0;	0
7396025	7395836	Converting from bitstring to integer	static int GetIntegerFromBinaryString(string binary, int bitCount)\n    {\n        if (binary.Length == bitCount && binary[0] == '1')\n            return Convert.ToInt32(binary.PadLeft(32, '1'),2);\n        else\n            return Convert.ToInt32(binary,2);\n    }	0
14065587	14065527	How to view a bitmap file that was created from my program?	string extension = "";\nswitch (format)\n{\n case (System.Drawing.Imaging.ImageFormat.Jpeg);\n    extension = ".jpg"; break;\n    .\n    .\n    .\n}\nbitMap.Save("testImage"+extension, System.Drawing.Imaging.ImageFormat.Jpeg);	0
32791791	32790232	Azure Service Bus Queue processing messages asynchronously in parallel	// Configure the callback options\nOnMessageOptions options = new OnMessageOptions();\noptions.AutoComplete = false;\noptions.MaxConcurrentCalls = 5;\noptions.AutoRenewTimeout = TimeSpan.FromMinutes(1);	0
1173674	1173626	C# Custom Attribute Alternatives	static Dictionary<string, PropertyInfo> propertyMap = new Dictionary<string, PropertyInfo>();\n\nstatic MyClass()\n{\n     Type myClass = typeof(MyClass);\n     // For each property you want to support:\n     propertyMap.Add("as_billaddress", MyClass.GetProperty("BillAddress"));\n     // ...\n}	0
11240938	11240790	C# Intersecting Partial Matches	Path.GetFilename	0
11833195	11833064	Convert gridview string to varchar for sql insert statement in c#	cmd.Parameters.AddWithValue("@ord", ord);	0
206739	206718	Using Session[] with Page Load	var data = Cache["Record_999"] as DataTable;\nif (data == null) {\n    // get from db\n    // insert into cache\n}\nSetDataSource(data);	0
28945838	28945687	How to save listbox value into database in MVC4 and EF?	[HttpPost]\npublic ActionResult Create(userViewModel model)\n{           \n\n    TryUpdateModel(model);\n    if (ModelState.IsValid) //<= The value of MENU not getting updated\n    {               \n        model.User.MENU = string.Join(",", model.MenuIds);\n        _db.Entry(model.User).State = EntityState.Modified;\n        _db.SaveChanges();\n    }\n    return RedirectToAction("Create");\n}	0
2646006	2645960	How to split string into numerics and alphabets using Regex	string[] data = Regex.Split("001A", "([A-Z])");\ndata[0] -> "001"\ndata[1] -> "A"	0
10260975	10260955	Is there a LINQ method to join/concat an unknown number of lists?	var newList = myChildren.SelectMany(c => c.TChildren);	0
31617650	31617552	What's the correct way to add a collection of file locations to a List?	Directory.GetFiles( [...] ).ToList()	0
32333731	32332316	Unity - how can I show / hide 3D Text	public YourMonoBehaviour : MonoBehaviour\n{\n  public TextMesh text_tap;\n\n  float awakeTime;\n\n  void Awake()\n  {\n    // Remember to activate the GO 3dtext in the scene! \n    text_tap = GameObject.Find("3dtext").GetComponent<TextMesh>():\n\n    awakeTime = Time.time\n  }\n\n\n   void Update()\n   {\n     if ((Time.time - awakeTime) > 5) \n     {\n\n       // second try but it I cant attach my 3d text to my script\n       text_tap.gameObject.SetActive(true);\n\n     }\n\n   }\n}	0
27960157	27959381	C# Convert String to Date Time Whereas string has AM : PM formate	var date = string.Format("{0:yyyy-MM-dd HH:mm tt}", DateTime.Parse("06:45 AM"));\nConsole.WriteLine(date);	0
2520206	2520179	Wait until all threads teminated in ThreadPool	int toProcess = 10;\nusing(ManualResetEvent resetEvent = new ManualResetEvent(false))\n{\n    var list = new List<int>();\n    for(int i=0;i<10;i++) list.Add(i); \n    for(int i=0;i<10;i++)\n    {\n        ThreadPool.QueueUserWorkItem(\n           new WaitCallback(x => {\n              Console.WriteLine(x);  \n              // Safely decrement the counter\n              if (Interlocked.Decrement(ref toProcess)==0)\n                 resetEvent.Set();\n\n           }),list[i]);\n    } \n\n    resetEvent.WaitOne();\n}\n// When the code reaches here, the 10 threads will be done\nConsole.WriteLine("Done");	0
6552985	6539571	How to resize multidimensional (2D) array in C#?	void ResizeArray<T>(ref T[,] original, int newCoNum, int newRoNum)\n    {\n        var newArray = new T[newCoNum,newRoNum];\n        int columnCount = original.GetLength(1);\n        int columnCount2 = newRoNum;\n        int columns = original.GetUpperBound(0);\n        for (int co = 0; co <= columns; co++)\n            Array.Copy(original, co * columnCount, newArray, co * columnCount2, columnCount);\n        original = newArray;\n    }	0
2329309	2329278	expire ASP.Net page	Response.Redirect()	0
25817629	25816843	Select all text from textbox in repeater and copy to clipboard when button clicked	btnCopy.Attributes.Add("onclick", "alert('button is clicked');");	0
18793790	18793558	Building with Code Contracts?	public class CustomContract\n{\n    public static void Requires<TException>( bool Predicate, string Message )\n        where TException : Exception, new()\n    {\n       if ( !Predicate )\n       {\n          Debug.WriteLine( Message );\n          throw new TException();\n       }\n    }\n}	0
8641493	8641390	How to open pdf file directly without asking open,save options(prompt window)	F:\Project Files\OO\Source\VCRT\StockListDocument\57-StockListPDF27December11111505179.pdf	0
12677077	12676873	technique to iterate through the FirstName, LastName to create username	//Store the first possible name.\nvar possibleUsername = string.Format("{0}{1}", tbLname.Text, tbFname.Text.Substring(0,1))\n\n//Don't hit the database N times, instead get all the possible names in one shot.\nvar existingUsers = entities.Users.Where(u => u.Username.StartsWith(possibleUsername)).ToList();\n\n//Find the first possible open username.\nif (existingUsers.Count == 0) {\n    //Create the user since the username is open.\n} else {\n    //Iterate through all the possible usernames and create it when a spot is open.\n    for(var i = 1; i < existingUsers.Count; i++) {\n        if (existingUsers.FirstOrDefault(u => u.Username == string.Format("{0}{1}", tbLname.Text, tbFname.Text.Substring(0, i))) == null) {\n            //Create the user since the user name is open.\n        }\n    }\n}	0
4317130	4315905	How to pass parameters to a method by reflection	public void WriteTrace(object sender, EventArgs e, string eventName)\n{\n    Control c = (Control)sender;\n    Console.WriteLine("Control: " + f.Name + ", Event: " + eventName);\n}\n\npublic void SubscribeEvent(Control control, string eventName) {\n    EventInfo eInfo = control.GetType().GetEvent(eventName);\n\n    if (eInfo != null) {\n        // create a dummy, using a closure to capture the eventName parameter\n        // this is to make use of the C# closure mechanism\n        EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eventName);\n\n        // Delegate.Method returns the MethodInfo for the delegated method\n        Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);\n\n        eInfo.AddEventHandler(control, realDelegate);\n    }\n}	0
7777227	7773160	Issue with variable nested dependencies	public class IProviderFactory {\n    IProvider Create(ProviderSettings settings);\n}	0
32313229	32312222	parse specific json string on wp8 app	var jsonStr = "{\"ver\":\"1\",\"item1\":{\"name\":\"name1\",\"desc\":\"desc1\"},\"item2\":{\"name\":\"name2\",\"desc\":\"desc2\"},\"item3\":{\"name\":\"name3\",\"desc\":\"desc3\"}}";\n\nList<string> names = new List<string>();\n\nJObject jsonObject = JObject.Parse(jsonStr);\njsonObject.Remove("ver");\n\nforeach (JToken jsonRow in jsonObject.Children())\n{\n    foreach (JToken item in jsonRow)\n    {\n        foreach (JToken itemProperty in item)\n        {\n            var property = itemProperty as JProperty;\n            if (property != null && property.Name == "name")\n            {\n                if (property.Value != null)\n                {\n                    names.Add(property.Value.ToString());\n                }\n            }\n        }\n    }\n}	0
10384237	10384208	DataSource parameter in connection string yields "Keyword not supported"	Data Source	0
6428691	6428581	implementing a generic interface with type constraints	public interface IComparison<EXPECTED_PARAM, RETURNED_PARAM>\n{\n    Result Compare(RETURNED_PARAM returned);\n}\n\npublic class GreaterThan<EXPECTED_PARAM, RETURNED_PARAM> : IComparison<EXPECTED_PARAM, RETURNED_PARAM> where RETURNED_PARAM : IComparable<EXPECTED_PARAM>\n{\n    private EXPECTED_PARAM expected_;      \n    public GreaterThan(EXPECTED_PARAM expected)     \n    {         expected_ = expected;     }      \n\n    public Result Compare(RETURNED_PARAM returned)          \n    {\n        return ((returned == null && expected_ == null) || \n            (returned != null && returned.CompareTo( expected_ ) > 0)) ?                \n            Result.Fail : Result.Pass;\n    }\n}	0
7316834	7316724	Drawing specific rectangle of a Bitmap into another Bitmap	private void drawMap(Graphics g, ref Point location)\n{\n    // Draw the specified section of the source bitmap to the new one\n    g.DrawImage(Map, location.X, location.Y, viewSize.Width, viewSize.Height);\n}	0
4988910	4988873	Proper way to sort a multi-object list?	studentList.OrderByDescending(p => p.rank).ToList();	0
29076390	29076175	Parse and transform XML string into list of objects using C#?	var str = @"<rows>\n  <row>\n    <id>\n      <old>2125</old>\n    </id>\n    <name>\n      <old>test</old>\n    </name>\n    <amount>\n      <old>62</old>\n    </amount>\n  </row>\n</rows>";\n\n var elements = XElement.Parse(str);\n\n var rows = elements.Elements("row");\n\n  var list = new List<Row>();\n\n  foreach(var row in rows)\n  {\n     var id = Int32.Parse(row.Element("id").Element("old").Value);\n\n     var name = row.Element("name").Element("old").Value;\n\n     var amount = row.Element("amount").Element("old").Value;\n\n     var fields = string.Format("id|{0}^name|{1}^amount|{2}",id, name, amount);\n\n     list.Add(new Row { Id = id, Fields = fields});\n  }\n\n\n}	0
18641069	16299794	MediaElement Speed ratio for Windows Phone 8	Microsoft.Web.Media.SmoothStreaming	0
4113795	4113755	Open Windows' Calculator in my C# Win Application?	System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");\np.WaitForInputIdle();\nNativeMethods.SetParent(p.MainWindowHandle, this.Handle);	0
26438746	26438708	Method for checking if a string has been passed into a list	return _identifiers.Contains(id);	0
5769399	5769272	C# Open files from listbox file listing	private void populateList( string path )\n{\n    string[] files = Directory.GetFiles(path, "*.fbi", SearchOption.AllDirectories);\n    foreach (string f in files)\n    {\n        string entry1 = Path.GetFullPath(f);\n        string entry = Path.GetFileName(f);\n        listBox1.Items.Add(entry);\n    }\n}	0
3942149	3938343	how to display custom error message using rhino mocks	step 1\nstep 2\nstep 3\nstep 4\nstep 5	0
1586100	1586078	Getting all selected values from an ASP ListBox	// GetSelectedIndices\nforeach (int i in ListBox1.GetSelectedIndices())\n{\n    // ListBox1.Items[i] ...\n}\n\n// Items collection\nforeach (ListItem item in ListBox1.Items)\n{\n    if (item.Selected)\n    {\n        // item ...\n    }\n}\n\n// LINQ over Items collection (must cast Items)\nvar query = from ListItem item in ListBox1.Items where item.Selected select item;\nforeach (ListItem item in query)\n{\n    // item ...\n}\n\n// LINQ lambda syntax\nvar query = ListBox1.Items.Cast<ListItem>().Where(item => item.Selected);	0
17268270	17268219	Store two different objects in a var array?	var my_models = new IEnumerable<object>[] { user_model, product_model };	0
33683657	33682644	Problems with XML deserialize	public class ExceptionClass\n    {\n        [XmlElement(Namespace="")]\n        public String Name { get; set; }\n        [XmlElement(Namespace = "")]\n        public String Message { get; set; }\n        [XmlElement(Namespace = "")]\n        public String DataPoints { get; set; }\n    }	0
6036350	6035241	Devexpress Aspx Gridview Control. Don't want to show any rows until at least one filter is applied	protected void SqlDataSource2_Selecting(object sender, System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs e) {\n    e.Cancel = ASPxGridView1.FilterExpression == string.Empty;\n}	0
17697096	17696827	How can I invoke javascript functions with c# with Gekofx Browser	mybrowser.Navigate("javascript:YourJavascriptFunction('yourArgument1', 'youArgument2')");	0
23150338	23149861	Linq to Sql selecting last row in a joined table	var results = context.Personel.Where(p => !p.Resign && p.KGBT > new \nDateTime(2012,1,15)).Join(context.PerLanguage, p => p.ID, pl => pl.ID, (p, pl) => \nnew { p.ID, p.NameSurname, pl.EarnedDate, pl.Degree }).GroupBy(r => r.ID)\n.Select(g => g.OrderByDescending(r => r.EarnedDate).First()).ToList();	0
15209029	15208936	List of numbers in C# and getting min and max value without retaining variables stored in previous loop	if (goOn.ToUpper() == "Y")\n{\n    maxValue= Double.MinValue;\n    minValue= Double.MaxValue;\n    Console.WriteLine("Please enter your set of numbers.");\n    Console.WriteLine("Remember not to enter -99 unless you want the series to end.");\n}	0
3234518	3234451	Declaring of arrays in C#	Seasonal[] seasonal = new Seasonal[n];\nfor (int l = 0; l < seasonal.Length; l++)\n{\n    seasonal[l] = new Seasonal();\n}\nSeasonal[] s = new Seasonal[n];\nfor (int l = 0; l < s.Length; l++)\n{\n    s[l] = new Seasonal();\n}	0
19714459	19712325	How can my data object reject changes from a databound control? (Control is not displaying actual value)	comboBox_Speed.TextUpdate += new EventHandler(comboBox_Speed_TextUpdate);\n\nvoid comboBox_Speed_TextUpdate(object sender, EventArgs e)\n    {\n        comboBox_Speed.DataBindings["Text"].WriteValue();\n        comboBox_Speed.DataBindings["Text"].ReadValue();\n    }	0
25141466	25141096	Load a texture in List of Texture2D XNA	paddles.Add(Content.Load<Texture2D>("Graphics/First Paddle"));	0
25637645	25637544	MySQL net timeout not set	comm.CommandTimeout=99999;	0
27147672	27147553	Substring add free space after each 4 character	Regex.Replace(value, ".{4}", "$0 ").Trim()	0
17089029	17088861	How to deserialize JSON request from EXT.NET on ASP.NET Web Api side	public string odobri(HttpRequestMessage request)\n{\n    Dictionary<string, string> values = request.Content.ReadAsAsync<Dictionary<string, string>>().Result;\n\n    RootObject c = null;\n    foreach (string s in values.Values)\n    {\n        List<RootObject> tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RootObject>>(s);\n        c = tmp.First();\n        break;\n    }\n    return c.Broj;\n\n}	0
3978861	3978815	Handling a DateTime DBNull	DateTime?	0
14751054	14749527	drop data on scheduler	private void Scheduler_AppointmentDrop(object sender, AppointmentDragEventArgs e)\n{\n   if (isAllowed)\n   {\n      MyDataSource.Add(e.EditedAppointment);\n   }\n}\n\nprivate void Scheduler_DragDrop(object sender, DragEventArgs e)\n{\n   SchedulerStorage.RefreshData();\n}	0
3918190	3918128	How to auto-update the Modified property on a Entity in Entity Framework 4 when saving?	partial void OnContextCreated() {\n    this.SavingChanges += Context_SavingChanges;\n}\n\nvoid Context_SavingChanges(object sender, EventArgs e) {\n\n    IEnumerable objectStateEntries =\n            from ose\n            in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | \n                                                            EntityState.Modified)\n            where ose.Entity is Product\n            select ose;\n\n    Product product = objectStateEntries.Single().Entity as Product;\n\n    product.ModifiedDate = DateTime.Now;\n    product.ComplexProperty.Revision++;\n}	0
1757475	1750323	fxcop custom rules - Inspecting source code to look for new keyword	public override ProblemCollection Check(Member member)\n{\nif (member is Method)\n{\nthis.Visit(member);\n}\n\nreturn this.Problems;\n}\n\npublic override void VisitConstruct(Construct construct)\n{\nbase.VisitConstruct(construct);\n\nif (!this.AllowTypeToBeNewed(construct.Type))\n{\nthis.Problems.Add(new Problem(this.GetResolution(), construct));\n}\n}\n\nprivate bool AllowTypeToBeNewed(TypeNode type)\n{\nthrow new NotImplementedException();\n}	0
24165208	24164909	How to correctly implement a multi-window application in C#?	Thread thread = new Thread(() => Application.Run(new MainForm()))\n{\n    IsBackground = false\n};\n\nthread.Start();	0
30954038	30949212	Cannot read InputStream from HttpListenerRequest	"permissions": [\n"contextMenus",\n"http://localhost/",\n"nativeMessaging"\n]	0
29237654	29234016	Add stored proc and call it from a service	public IQueryable<Entities.Customer> AllCustomerRanges(int CId, int ItemID)\n        {\n            var c = myDataContext.spCustomerRanges(CId, ItemID).ToList();\n\n            if (c == null)\n                return null;\n\n            var customers = c.Select(a => new Entities.Customer\n            {\n                FirstName=a.spResultFirstName,\n                LastName = a.spResultLastName\n                //this just example conversion, change it as needed. \n            });\n\n\n            return customers;\n\n        }	0
4266897	4266854	Help with Google Contacts	var domains = (from contact in cr.GetContacts().Entries\n               from email in contact.Emails\n               let address = email.Address\n               select address.Substring(address.LastIndexOf('@') + 1))\n              .Distinct(StringComparer.OrdinalIgnoreCase)\n              .ToList();	0
23262532	23262468	Reading a binary file into a textblock	byte[] bytes = File.ReadAllBytes(FPath);\ntextBox.Text = Encoding.Default.GetString(bytes);	0
1531892	1531851	How to count the elements of a list in a list in a list using LINQ?	int  iTotalListCounter = listRoot.Sum(x => (x.Count + x.Sum(y => y.Count)));	0
1666378	1666346	String.Format an integer to use a thousands separator without decimal places or leading 0 for small integers	String.Format("{0:#,0} {1:#,0}", 5, 5000); // 5 5,000	0
15894781	15894189	Get PDF Printout from console application programatically in background	private void PrintPdf(string fileName)\n{\n    var hkeyLocalMachine = Registry.LocalMachine.OpenSubKey(@"Software\Classes\Software\Adobe\Acrobat");\n    if (hkeyLocalMachine != null)\n    {\n        var exe = hkeyLocalMachine.OpenSubKey("Exe");\n        if (exe != null)\n        {\n            var acrobatPath = exe.GetValue(null).ToString();\n\n            if (!string.IsNullOrEmpty(acrobatPath))\n            {\n                var process = new Process\n                {\n                    StartInfo =\n                    {\n                        UseShellExecute = false,\n                        FileName = acrobatPath,\n                        Arguments = string.Format(CultureInfo.CurrentCulture, "/T {0}", fileName)\n                    }\n                };\n\n                process.Start();\n            }\n        }\n    }\n}	0
15892762	15122811	WPF DataBinding ObservableCollection<T> to DataGrid	public static class QuotePreview\n{\n    public static ObservableCollection<PurchasableItem> LineItems { get; private set; }\n\n    static QuotePreview()\n    {\n        LineItems = new ObservableCollection<PurchasableItem>();\n    }\n\n    public static void Add(List<PurchasableItems> selections)\n    {\n        foreach (var selection in selections)\n        {\n            LineItems.Add(selection);\n        }\n    }\n\n    public static void Clear()\n    {\n        LineItems.Clear();\n    }\n}\n\npublic class QuoteTab : TabItem\n{\n    public ObservableCollection<PurchasableItem> PreviewItems { get; private set; }\n\n    public QuoteTab()\n    {          \n        Initialize()\n\n        PreviewItems = QuotePreview.LineItems;\n\n        DataGrid.ItemSource = PreviewItems\n    }\n}	0
14051401	14049612	using C# to assign a value into Visio's Shape.Text causing exception	shape.get_CellsSRC((short)VisSectionIndices.visSectionObject,\n                   (short)VisRowIndice??s.visRowLock,\n                   (short)VisCellIndices.visLockTextEdit).FormulaU = "0"; //to remove protection	0
25041676	25017675	Multiple queues using single IBus	var consumer = bus.Subscribe<MyMessage>( ....\n...\n// stop consuming:\nconsumer.Dispose();	0
13091605	13091200	attach a panel to TreeView control	private void timer1_Tick(object sender, EventArgs e) {\n        var node = treeView1.SelectedNode;\n        if (node == null || !node.IsVisible) panel1.Visible = false;\n        else {\n            panel1.Visible = true;\n            var nodepos = treeView1.PointToScreen(node.Bounds.Location);\n            var panelpos = panel1.Parent.PointToClient(nodepos);\n            panel1.Top = panelpos.Y;\n        }\n    }	0
10507929	10507720	How to search a DataGridView for a unique id	foreach (DataRow row in mainGrid.Rows)\n        {\n            if (row["ColumnName"].ToString() == SearchtextBox.Text )\n            {\n            return CustID;\n            }\n        }	0
32439766	32439625	How do i stop part of a method being called?	public static class Program\n{\n    private static int TotalScore;\n\n    static public void Score()\n    {\n        TotalScore++;\n    }\n    //... Other stuff\n}	0
32789770	32785088	Failed to load viewstate in GridView1_RowEditing	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        BindGridView(this.txtSearch.Text);\n\n\n    }\n}\n\nprotected void BindGridView(string column1)\n{\n\n    SqlCommand cmd = new SqlCommand("select * from table1 where (column1 like '%" + txtSearch.Text + "%')", con);\n    con.Open();\n    cmd.Parameters.AddWithValue("@column1 ", column1 );\n    GridView1.DataSource = cmd.ExecuteReader();\n    GridView1.DataBind();\n    con.Close();\n\n}\n\n  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n{\n    GridView1.EditIndex = e.NewEditIndex;\n    BindGridView(this.txtSearch.Text);\n\n}\n\n  protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)\n{\n    GridView1.EditIndex = -1;\n    BindGridView(this.txtSearch.Text);\n}	0
21777836	21629965	StackOverflowException in recursive ASP.NET treeview population	int rand = r.Next(10,100);\nitemList.Add(new TreeviewItem("test " + rand.ToString(), rand.ToString(), val));	0
9742666	9742637	loop through controls on tabitem	// Enumerate all the descendants of the visual object.\nstatic public void EnumVisual(Visual myVisual)\n{\n    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)\n    {\n        // Retrieve child visual at specified index value.\n        Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);\n\n        // Do processing of the child visual object.\n\n        // Enumerate children of the child visual object.\n        EnumVisual(childVisual);\n    }\n}	0
14204142	14187947	DrawingGroup - crossthreading	MyImage.Source	0
8460608	8460603	Console Write to cursor position	for (int x = 0; x < 80; x++)\n{\n    Console.SetCursorPosition(x, 12);\n    Console.Write("?");\n}\n\nfor (int y = 0; y < 25; y++)\n{\n    Console.SetCursorPosition(40, y);\n    Console.Write("|");\n}\n\nConsole.SetCursorPosition(40, 12);\nConsole.Write("?");	0
22943182	22943061	Date time formatting from seconds	string.Format("{0:c}", TimeSpan.FromSeconds(seconds));	0
3487650	3487613	How to implement "Handles" via Codedom	AddHandler btnStart.Click, AddressOf Startup	0
29428021	29427381	Import large XML file into SQL Server CE	using (SqlCeBulkCopy bulkInsert = new SqlCeBulkCopy(connString))\n{\n   bulkInsert.DestinationTableName = "testtable";\n   bulkInsert.WriteToServer(table);\n}	0
8096526	8095597	How to set the name of a new SPListItem programmatically?	//Create root folder\n            SPListItem rootItem = navigation.Items.Add();\n            SPContentType contentType = navigation.ContentTypes["ListLevel"];\n\n            rootItem["ContentTypeId"] = contentType.Id;\n            rootItem["Title"] = "root";\n            rootItem.Update();\n            navigation.Update();\n\n            rootItem = navigation.GetItemById(rootItem.ID);\n            rootItem["Name"] = "root";\n            rootItem.Update();	0
19722962	19722923	Dropdown For next 10 years	Enumerable.Range(DateTime.Now.Year, 10)	0
15980108	15958498	WPF Combobox selection behavior	private bool _comboMouseDown = false;\nprivate bool _comboSelectionDisabled = false;\n\nprivate void ComboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n{\n    _comboMouseDown = true;\n}\n\nprivate void ComboBox_DropDownOpened(object sender, EventArgs e)\n{\n    if (_comboMouseDown)\n    {\n        //Don't enable selection until the user releases the mouse button:\n        _comboSelectionDisabled = true;\n    }\n}\n\nprivate void ComboBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)\n{\n    if (_comboSelectionDisabled)\n    {\n        //Stop the accompanying "MouseUp" event (which would select an item) from firing:\n        e.Handled = true;\n\n        _comboSelectionDisabled = false;\n    }\n\n    _comboMouseDown = false;\n}	0
8630817	8630669	How to store the suggestion that will be sent to the Admin in the database?	using System.Data.SqlClient;\n....\n    SqlConnection objConn = new SqlConnection("Data Source=MYDBSERVER,3306;User ID=kingRoland;Password=12345;Initial Catalog=suggestionDB");\n    objConn.Open();\n    SqlCommand objCMD = new SqlCommand();\n    objCMD.Connection = objConn;\n    objCMD.CommandText = "INSERT INTO SuggestionLog (Title,Description,Username) VALUES(@title, @desc, @user)";\n    objCMD.Parameters.Clear();\n    objCMD.Parameters.AddWithValue("title",strTitle);\n    objCMD.Parameters.AddWithValue("desc",strDesc);\n    objCMD.Parameters.AddWithValue("user",strUser);\n\n    try\n    {\n        objCMD.ExecuteNonQuery();\n    }\n    catch (SqlException e)\n    {\n        writeToLog(e.InnerException.ToString());\n    }\n    objConn.Close();	0
24677208	24676844	ShowDialog in WPF throwing not agree with the current state	lock (mycollection){\n    //modify the collection in a threadsafe manner\n}	0
17556226	17556147	How to test to ensure an interface has no other methods than those listed?	Type myType =(typeof(IPlugin));\n\n// Get the public methods.\nMethodInfo[] myArrayMethodInfo = myType.GetMethods();\n\nConsole.WriteLine("The number of public methods is {0}.", myArrayMethodInfo.Length);	0
27318862	27318772	C# preventing combox selectionChanged event from recalling itself	private bool _alreadyChanging = false;\n\nprivate void txtLocation_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    if (!_alreadyChanging)\n    {\n        _alreadyChanging = true;\n        MessageBox.Show("Must have a repair report.", "No Report");\n        txtLocation.SelectedItem = MAIN_BACKGROUND.UserName;\n        _alreadyChanging = false;\n    }\n}	0
2396746	2396411	How to merge detected edges to a colour capture in Emgu CV	private void processFunction(object sender, EventArgs e) {\n        Image<Bgr, Byte> frame = c0.QueryFrame();\n        Image<Gray, Byte> grayscale = frame.Convert<Gray, Byte>();\n        grayscale = grayscale.Canny(new Gray(0), new Gray(255)).Not(); //invert with Not()\n        frame = frame.And(grayscale.Convert<Bgr, Byte>(), grayscale); //And function in action\n        imageBox1.Image = frame;\n\n    }	0
6799053	6775707	C# set location of a minimized form	formName.Dock = DockStyle.Fill;	0
7911384	7523504	Json.NET: Deserialization with list of objects	[DataContract]\npublic class serviceresponse\n{\n    [DataMember]\n    public String company;\n    [DataMember]\n    public String success;\n    [DataMember]\n    public List<product> products;\n    [DataMember]\n    public String callbackformore;\n    [DataMember]\n    public String message;\n}\n[DataContract]\npublic class product\n{\n    [DataMember(Name = "product")]\n    public product2 _product;\n}\n[DataContract(Name = "product")]\npublic class product2\n{\n    [DataMember]\n    public String Name;\n    [DataMember]\n    public String ExpiryDate;\n    [DataMember]\n    public String Price;\n    [DataMember]\n    public String Sizes;\n}	0
2359485	2359471	Need to write files to disk, how can I reference the folder in a web application?	Server.MapPath("~/files/ ")	0
24596095	24585987	GetConstructors in Xamarin PCL library	var info = type.GetTypeInfo ();\nforeach (var ctor in info.DeclaredConstructors) {\n    // find the .ctor you want...\n}	0
24257699	24256940	Registering types with lambda expression	container.RegisterType<IDummy>(new InjectionFactory(context => new Dummy()));	0
1398152	1398108	How do I format a DateTime? in c#?	string StringValue = MyDate.HasValue ? MyDate.Value.ToString("dd.MM.yyyy HH:mm:ss") : string.Empty;	0
16775328	16775239	Fill a string[] array using split	var input = "text1:text2";\nvar temp = new [] {"", "", ""};\nvar split = input.Split(':');\nArray.Copy(split, temp, split.Length <= 3 ? split.Length : 3);	0
32619145	32618784	C# - LINQ to unflatten items into a hierarchical collection	// create a mapping: id => obj\nvar mapping = collectionFlat.ToDictionary(x => x.ID);\n\n// target collection\nvar output = new ObservableCollection<Register>();\n\nforeach (var obj in mapping.Values)\n{\n    // if the parent id is an empty Guid, this is a top-level entry; otherwise\n    // get the parent element from the mapping, and add to its children collection\n    if (obj.IDParent == Guid.Empty)\n        output.Add(x);\n    else\n        mapping[obj.IDParent].Children.Add(obj);\n}	0
23740639	23740513	Smoothly lerp a rigidbody	bool moveLeft = false;\n\nvoid FixedUpdate() \n{\n\n    if(Input.GetMouseButtonDown(0)\n        && (Input.mousePosition.x < (Screen.width*2)/3 && Input.mousePosition.y > Screen.height/3))\n    {\n        moveLeft = true;\n    }\n\n    if (moveLeft\n        && (position == middle))\n    {\n        MoveLeft();\n    }\n    else\n    {\n        moveLeft = false;\n    }\n}\n\nvoid MoveLeft()\n{\n    var pos = rigidbody.position;\n    float xPosition = left.transform.position.x;\n    pos.x = Mathf.Lerp(pos.x, xPosition, speed * Time.deltaTime);\n    rigidbody.position = pos;\n}	0
8322448	8322345	how do I show a string as html content in web form	Literal1.Text=data_from_DB;	0
10684490	10684174	Navigate to a View without ViewModel in MvvmCross	public class StaticViewModel : BaseViewModel\n  {\n      public enum WhichOne\n      {\n          AboutPage,\n          InfoPage,\n          HelpPage,\n          // etc\n      }\n\n      public WhichOne WhichPage { get; set; }\n\n      public StaticViewModel(string which)\n      {\n          WhichPage = (WhichOne) Enum.Parse(typeof(WhichOne), which, false);\n      }\n  }	0
5103244	5096285	Clarification about how ColorMatrix transformations work	((247/255) * -1 + 1) * 255 = 8\nor\n247 * -1 + 255 = 8	0
4542860	4542838	Update object in EF	[Function(Name="GetDate", IsComposable=true)]\npublic DateTime GetSystemDate()\n{\n  MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;\n  return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue;\n}	0
31211744	31210979	Add an action result cache with a file dependency in ASP.NET MVC 5	Response.AddCacheDependency(new CacheDependency(filename));	0
1876935	1867085	It's there a way to invoke a generic methodInfo?	public class ConvertTable<TOuter, TInner>\n    where TInner : class\n    where TOuter : class\n  {\n    public TOuter FromT { get; set; }\n    public TInner InnerT { get; set; }\n    public ConvertTable(TOuter fromT, TInner innerT)\n    {\n      FromT = fromT;\n      InnerT = innerT;\n    }\n  }	0
13948350	13948199	How to RowFilter a column with a period in the name?	dataTable.Columns["Stock Qty"].ColumnName = \n                 dataTable.Columns["Stock Qty"].ColumnName.Replace(" ", "_");	0
869522	384426	Looking for a simple OpenType API for .NET	Dim gTypeface = New GlyphTypeface(New Uri("c:\GoudyForumPro.otf"))\n\ngTypeface.Copyrights\ngTypeface.Descriptions\ngTypeface.FamilyNames\ngTypeface.FaceNames\n'...	0
1072390	1072375	Open My Computer Properties in C# Windows App	Process.Start("sysdm.cpl");	0
16609612	16608792	ListView EditItemLayout cancel action	protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)\n{\n    ListView1.EditIndex = -1;\n    ListView1.DataBind();\n}	0
17576279	17571152	How to save existing StorageFile using FileSavePicker?	var curItem = (SampleDataItem)flipView.SelectedItem;\n        StorageFile currentImage = await StorageFile.GetFileFromPathAsync(curItem.UniqueId);\n        byte[] buffer;\n        Stream stream = await currentImage.OpenStreamForReadAsync();\n        buffer = new byte[stream.Length];\n        await stream.ReadAsync(buffer, 0, (int)stream.Length); \n        var savePicker = new FileSavePicker();\n        savePicker.FileTypeChoices.Add("JPEG-Image",new List<string>() { ".jpg"});\n        savePicker.FileTypeChoices.Add("PNG-Image", new List<string>() { ".png" });\n        savePicker.SuggestedSaveFile = currentImage;\n        savePicker.SuggestedFileName = currentImage.Name;\n        var file = await savePicker.PickSaveFileAsync();\n        if (file != null)\n        {\n            CachedFileManager.DeferUpdates(file);\n            await FileIO.WriteBytesAsync(file, buffer);\n            CachedFileManager.CompleteUpdatesAsync(file);\n        }	0
20609678	20567288	Access Web.Config path from ServerManager object	ServerManager manager = ServerManager.OpenRemote("::1");\nstring physicalPath = manager.Sites[siteName].Applications[virtualDirPath].VirtualDirectories[0].PhysicalPath\n\nstring webConfigLocation = Path.Combine(physicalPath, "web.config");	0
5205319	5205244	get average color from bmp	Color.GetHue\nColor.GetSaturation\nColor.GetBrightness	0
21030219	21026464	Overlaying a bitmap over a white background using a resize method	private Bitmap overlayBitmap(Bitmap sourceBMP, int width, int height) {\n        Bitmap result = new Bitmap(width + (width/3), height + (height/3));\n        using (Graphics g = Graphics.FromImage(result)) {\n            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;\n            g.DrawImage(sourceBMP, width / 6, height / 6, width, height);\n        }\n        return result;\n    }	0
3310713	3310661	Exposing events of underlying control	public event EventHandler SelectedIndexChanged \n    {\n        add { inner.SelectedIndexChanged += value; }\n        remove { inner.SelectedIndexChanged -= value; }\n    }	0
10170987	10170882	Dapper simple mapping	var sql = \n@"select * from #Posts p \nleft join #Users u on u.Id = p.OwnerId \nOrder by p.Id";\n\nvar data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});\nvar post = data.First();\n\npost.Content.IsEqualTo("Sams Post1");\npost.Id.IsEqualTo(1);\npost.Owner.Name.IsEqualTo("Sam");\npost.Owner.Id.IsEqualTo(99);	0
7065387	7035437	How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010	Show All Files	0
8195117	8195098	Deleting item from a List<Type>	List<ItemClass> itemsToErase = new List<ItemClass>();\nitemsToErase.RemoveAll( itm => itm.ToBeRemoved );	0
25557125	25556684	Performing operations after reading the last line of a file with a StreamReader	using (StreamReader file = new StreamReader(@"D:\Downloads\testfile.txt"))\n{\n    string str = "";\n    while ((str = file.ReadLine()) != null || str == null)\n    {\n        if (str == null)\n        {\n            Console.WriteLine("Hey! We've already passed the EOF!");\n            break;\n        }\n\n        Console.WriteLine(str);\n    }\n}	0
5703219	5703000	How to properly update a model entity instance in EF?	[HttpPost]\npublic ActionResult Edit(TableA formdata)\n{\n    TableA temp = myDB.TableA.First(a=>a.Id == formdata.Id);\n    temp.TableB = myDB.TableB.First(a => a.Id == formdata.TableB.Id);\n\n    AutoMapper.Mapper.Map(formdata, temp);\n    myDB.SaveChanges();\n    return RedirectToAction("Index");\n}	0
24556721	24556633	Get number of columns that have certain prefix in DataTable?	var count = yourDataTable.Columns\n                         .Cast<DataColumn>()\n                         .Count(x => x.ColumnName.StartsWith("cat-"));	0
9417547	5097946	How can I programmatically check-out an item for edit in TFS?	var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(fileName);\nusing (var server = new TfsTeamProjectCollection(workspaceInfo.ServerUri))\n{\n    var workspace = workspaceInfo.GetWorkspace(server);    \n    workspace.PendEdit(fileName);\n}	0
17715482	17715314	Deny access to documents outside application	using (var fileStream = File.OpenWrite(theFileName))\n using (var memoryStream = new MemoryStream())\n {\n// Serialize to memory instead of to file\nvar formatter = new BinaryFormatter();\nformatter.Serialize(memoryStream, customer);\n\n// This resets the memory stream position for the following read operation\nmemoryStream.Seek(0, SeekOrigin.Begin);\n\n// Get the bytes\nvar bytes = new byte[memoryStream.Length];\nmemoryStream.Read(bytes, 0, (int)memoryStream.Length);\n\n\nvar encryptedBytes = yourCrypto.Encrypt(bytes);\nfileStream.Write(encryptedBytes, 0, encryptedBytes.Length);\n}	0
5271368	5270597	Insert/Update/Delete of EF in Business layer	public class BusinessBaseCollection\n{\n    protected EFBaseCollection _efObject = null;\n\n    public BusinessBaseCollection(EFBaseCollection efObject)\n    {\n        _efObject = efObject;\n    }\n\n    public Add(BusinessBase obj)\n    {\n        _efObject.Add(obj);\n    }\n\n    //Add other CRUD stuff here\n}	0
26789057	26788799	How can I set focus to an object outside of a DataGridView	customerComboBox.Select();	0
22056383	22056103	Rewrite dynamic URLs in lots of HTML files	var links = html.DocumentNode\n           .Descendants("tr")\n           .Where(tr => tr.GetAttributeValue("class", "").Contains("alt"))\n           .SelectMany(tr => tr.Descendants("a"))\n           .ToArray();	0
27716614	27716296	How to instantiate an object in a default constructor of another class and access it from main class?	public class A {\n    public B b;\n    public A() {\n        b=new B();\n    }\n}\npublic class B { }\npublic class M {\n    public static void Main() {\n        A a=new A();\n        // use `a.b` here\n    }\n}	0
8586985	8586954	Replacing digits in C# string	string input = "test12345.txt";\n\n// replace all numbers with a single *\nstring replacedstar = Regex.Replace( input, "[0-9]{2,}", "*" );\n\n// replace remaining single digits with ?\nstring replacedqm = Regex.Replace( input, "[0-9]", "?" );	0
33803804	33796164	C# Dynamic Set DataRow	foreach(var session in ITS.GetSessions())\n{\n    Type t = session.GetType();\n    PropertyInfo[] propinfo = t.GetProperties();\n    var list = new List<object>();\n    foreach (PropertyInfo prop in propinfo)\n    {\n        list.Add(prop.GetValue(session, null));\n    }\n    DTable.Rows.Add(list.ToArray());   \n}	0
4059531	4059503	My RichTextBox change backgroundcolor when Enabled is set to false	class CustomRichTextBox : System.Windows.Forms.RichTextBox {\n     public override System.Drawing.Color BackColor {\n          get { return System.Drawing.Color.White; }\n          set { base.BackColor = System.Drawing.Color.White; }\n     }\n}	0
26484590	26484491	Get Month of out System Datetime	where c.DepartureDate.Month == DateTime.Now.AddMonths(-1).Month	0
31305398	31305074	Stop EF from trying to create initial DB	Database.SetInitializer<YourContextClass>(null);	0
4517167	4517136	Can I make xmlreader to use the specific encoding	var xml  = XmlReader.Create(new StreamReader(file, Encoding.ASCII))	0
9211070	9211019	C# Currency format	totalLabel.Text = String.Format("{0:C}", cmd.ExecuteScalar());	0
10874074	10874047	Operate QL 500 P-Touch label Printer in C# Application	bpac.DocumentClass doc = new DocumentClass();\nif (doc.Open("templateFile.lbx"))\n{\n    doc.GetObject("field1").Text = "...";\n    doc.GetObject("field2").Text = "...";\n\n    doc.StartPrint("", PrintOptionConstants.bpoDefault);\n    doc.PrintOut(1, PrintOptionConstants.bpoDefault);\n    doc.EndPrint();\n    doc.Close();\n}	0
2434712	2434465	sorting a gridview in class	public string GetSortDirection(string column, StateBag viewState) {\n    // Your code here.\n}	0
7112875	7112681	union of unknown set of xmls	IEnumerable<string> filenames = { "filename1.xml", "filename2.xml" };\n\nIEnumerable<XDocument> documents = filenames.Select(XDocument.Load);\nIEnumerable<IEnumerable<XElement>> documentsElements = documents.Select(document => document.Descendants("parent"));\nIEnumerable<XElement> elements = documentsElements.Aggregate((working, next) => working.Union(next));	0
1756818	1755572	IronPython ScriptRuntime equivalent to CPython PYTHONPATH	var engine = Python.CreateEngine(DefaultEngineOptions());\nvar paths = engine.GetSearchPaths();\npaths.Add("c:\\my_libs");\nengine.SetSearchPaths(paths);	0
2122753	2122749	How to create a single executable file in Visual Studio 2008?	bin/Release	0
18468026	18304604	match value in one list with another and write value to other list	switched the state list to a dictionary and matched the values by the key value pair by using the TryGetValue method.	0
29712846	29712803	How to cast value from database entity to a list of strings?	var fA = (from f in entities.Friends\n                    where f.Friend_B == User.Identity.Name && f.AreFriends\n                    select f.Friend_A).ToList();	0
32226477	32226355	how to use different color for backcolor in textbox?	private static Random s_Gen = new Random();\n...\n\n// Controls coundn't be (semi-)transparent, so alpha must be 255\ntextBox1.BackColor = Color.FromArgb(255, Color.FromArgb(s_Gen.Next()));	0
24977824	24973140	How to update the checkbox in wp8 app	IsChecked="{Binding file, Mode="TwoWay"}"	0
8373345	8373333	Explicitly setting a test to pass/fail?	[ExpectedException( typeof( UserCannotExecuteCommandException) )]	0
11861639	11861553	Simple ConsoleProgram with IDisposable - No memory decrease - we have a leak?	Dispose()	0
2026940	2026228	C#: Marshalling a "pointer to an int array" from a SendMessage() lParam	int[] parts = new int[]{ 1, 2, 3, 4 };\nint nParts = parts.Length;\nIntPtr pointer = Marshal.AllocHGlobal(nParts * Marshal.SizeOf(typeof(int)));\nfor (int i = 0; i < nParts; i++) {\n    Marshal.WriteInt32(pointer, i * Marshal.SizeOf(typeof(int), parts[i]));\n}\n// Call SendMessage with WPARAM = nParts and LPARAM = Pointer\nMarshal.FreeHGlobal(pointer);	0
17859979	17859802	Replace single chars in string at position x	...\n      StringBuilder temp = new StringBuilder(lblWord.Text);\n      temp[i] = letter; // <- It is possible here\n      lblWord.Text = temp.ToString();  \n  ...	0
5475643	5474086	Loading Crystal Report from embedded resource	var report = new CrystalReport1();\nreport.SetDataSource(datasource);\nCrystalReportViewer1.ReportSource = report;	0
3619314	3619284	Converting an IEnumerable list to a grouped list in Linq	var transactions = ctx.ExportTranactions\n                      .Where(x => x.Id != null)\n                      .GroupBy(x => x.Name);	0
30507215	30501040	How to use ResourceDictionary in DLL from ConsoleApp?	if (!UriParser.IsKnownScheme("pack"))\n{\n    Application app = Application.Current;\n}	0
22017675	22016544	Showing animated gif in Winforms without locking the file	using (var fs = new System.IO.FileStream(...)) {\n     var ms = new System.IO.MemoryStream();\n     fs.CopyTo(ms);\n     ms.Position = 0;                               // <=== here\n     if (pic.Image != null) pic.Image.Dispose(); \n     pic.Image = Image.FromStream(ms);\n }	0
627391	627304	Programatically Clear Selection in WPF ComboBox	comboBox.SelectedIndex = -1;	0
14493336	14492798	Fully instantiating an object through reflection without constructor	PopulateType(Object obj)\n{\n    //A dictionary of values to set for found properties\n    Dictionary<String, Object> defaultValues = new Dictionary<String, Object>();\n    defaultValues.Add("BirthPlace", "Amercia");\n    for (var defaultValue in defaultValues)\n    {\n        //Here is an example that just set BirthPlace to a known value Amercia\n        PropertyInfo prop = obj.GetType().GetProperty(defaultValue.Key, BindingFlags.Public | BindingFlags.Instance);\n        if(null != prop && prop.CanWrite)\n        {\n            prop.SetValue(obj, defaultValue.Value, null);\n        }\n    }\n}	0
27359733	27359656	vb net button do two things	Dim visit As Integer = 0;\n Private Sub Button1_MouseClick(sender As Object, e As MouseEventArgs) Handles Button1.MouseClick\n\n    If (visit = 0) Then\n       Button2.BackColor = Color.BlueViolet\n       Button3.BackColor = Color.Aqua\n       visit = 1\n    ElseIf (visit = 1) Then\n       Button2.BackColor = Color.Brown\n       Button3.BackColor = Color.Bisque\n       visit = 0\n    End If\n\n End Sub	0
8563357	8563261	Saving a excel file using Web service	System.IO.File	0
18790992	18790852	Preventing program from closing	class Program\n{\n  static void Main(string[] args)\n  {\n    using(var host = new ServiceHost(typeof(XServer), new Uri("net.pipe://localhost")))\n    {\n      host.AddServiceEndpoint(typeof(IXServer), new NetNamedPipeBinding(), "XServer");\n      host.Open();\n      create an exit event\n      while (true)\n      {\n        begin asynchronous read\n        wait on asynchronous read or exit event <- puts thread to sleep\n        if event was exit event, break out of while loop\n        parse read data\n      }\n      destroy exit event\n    }\n  }\n}	0
6281545	6281355	ListView ItemChanged puzzle with MessageBoxes - ItemSelectionChanged called twice	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private bool ShowMessageBox()\n    {\n        return MessageBox.Show("Change to first item instead?", "test", MessageBoxButtons.YesNo) == DialogResult.Yes;\n    }\n\n    private void listView1_Click(object sender, EventArgs e)\n    {\n        if (ShowMessageBox())\n            listView1.TopItem.Selected = true;\n            label1.Text += "item selected   ";\n    }\n}	0
3944381	3944358	Random numbers in c#	private void SetRandomNumber(int min, int max)\n{\n   int num = new Random().Next(min, max); \n   lblPickFive_1.Text=num;\n}	0
33170927	32870942	Create Treeview depending on DataGridView in C#	{\n.............\nTreeNode tn = new TreeNode(this.DataGridView2.Rows[0].Cells[0].Value.ToString());//text\ntn.Tag = this.DataGridView2.Rows[0].Cells[4].Value.ToString();// id\ntn.Name = this.DataGridView2.Rows[0].Cells[5].Value.ToString();//directorid\n                treeView1.Nodes.Add(tn);\n                settree(tn);\n            }\n            public void settree(TreeNode ns)\n        {\n            foreach (DataGridViewRow dr in DataGridView2.Rows)\n            {\n                if (dr.Cells[5].Value.ToString() == ns.Tag.ToString())\n                {\n                    TreeNode tsn = new TreeNode(dr.Cells[0].Value.ToString());\n                    tsn.Tag = dr.Cells[4].Value.ToString();\n                    tsn.Name = dr.Cells[5].Value.ToString();\n                    ns.Nodes.Add(tsn);\n                    settree(tsn);\n                }\n            }\n        }	0
19213742	19213646	Database insertion troubles because of character (')	var value1 = //fetch what you want to insert\nvar value2 = //fetch what you want to insert\n\nusing (SqlConnection con = new SqlConnection(connectionString))\nusing (SqlCommand cmd = new SqlCommand("INSERT INTO myTable VALUES (@value1, @value2)", con))\n{\n    cmd.Parameters.AddWithValue("@value1", value1);\n    cmd.Parameters.AddWithValue("@value2", value2);\n    con.Open();\n    try\n    {\n        cmd.ExecuteNonQuery();\n    }\n    catch (SqlException ex)\n    {\n        Console.WriteLine(ex.Message)\n    }\n}	0
6499302	6493715	How to get current Product Version in C#?	//using System.Deployment.Application;\n  //using System.Reflection;\n   public string CurrentVersion\n    {\n        get\n        {\n            return ApplicationDeployment.IsNetworkDeployed\n                   ? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()\n                   : Assembly.GetExecutingAssembly().GetName().Version.ToString();\n        }\n    }	0
16862436	16862388	Data not getting inserted into SQL Server	cmd.ExecuteNonQuery();	0
26840742	26840653	Code for contact page to send Email ASP.NET	public bool SendMail(string SendTo, string Subject, string Body)\n    {\n        try\n        {\n            string admin_email = "email"\n            string admin_emailpwd = "password"\n\n            MailMessage mail = new MailMessage();\n            mail.To.Add(SendTo);\n            mail.From = new MailAddress(admin_email);\n            mail.Subject = Subject;\n            mail.Body = Body;\n            mail.IsBodyHtml = true;\n            SmtpClient smtp = new SmtpClient();\n            smtp.Host = "SMTP.gmail.com";\n          //  smtp.Port = 587;\n            smtp.Credentials = new System.Net.NetworkCredential(admin_email, admin_emailpwd);\n            smtp.EnableSsl = true;\n            smtp.Send(mail);\n        }\n        catch\n        {\n            return false;\n        }\n        return true;\n    }	0
33381334	33380538	How to loop through the number at each index in byte array?	for(int i = 0; i < requestBytes.Length; i++)\n                {\n                    var v = requestBytes[i];\n                    if (v == 99)\n                    {\n                        Console.WriteLine("Sending Failure..");\n                    }\n                    else if(v == 999)\n                    {\n                        Console.WriteLine("Message Failure..");\n                    }\n                    else if (v == 01)\n                    {\n                        Console.WriteLine("Sending Success..");\n                    }\n\n                }	0
13347357	13346326	Console Output Formatting and Console Alloc	[DllImport("kernel32.dll", SetLastError = true)]\n  static extern bool AttachConsole(uint dwProcessId);\n\n...(!AttachConsole(ATTACH_PARENT_PROCESS)...	0
20404470	20402129	Converting from base 16 to base 10 in reverse byte order	byte a1 = 0x23;\nbyte a2 = 0x00;\n\nushort a12 = (ushort)(a1 << 8 | a2); //This what you receive\nushort a21 = (ushort)((a12 & 0xFF00) >> 8 | (a12 & 0xFF) << 8);	0
33199305	33199194	Can I use a string value to replace + or - operator in a C# calculation?	var coef = operationComboBox.Text == "-" ? -1 : 1;\n\nequation3XCoeff = equations[index1].XCoeff + coef * equations[index2].XCoeff;\nequation3YCoeff = equations[index1].YCoeff + coef * equations[index2].YCoeff;\nequation3Answer = equations[index1].Answer + coef * equations[index2].Answer;	0
11986121	11949117	How to localize JQUERY UI Date Picker in Orchard?	ui.datepicker-<language>.js	0
4413418	4413363	Using Linq to get groups from a collection	List<string> strings = ...\nList<List<string>> groups = strings\n    .Select((s, idx) => new { Item = s, Group = idx / 20 })\n    .GroupBy(s => s.Group)\n    .Select(grp => grp.Select(g => g.Item).ToList())\n    .ToList();	0
34073033	34072405	How to let the user select a specific column and row in mysql database using c# to retrieve data?	private void select_btn_Click(object sender, EventArgs e)\n{\n  string today = (System.DateTime.Now.DayOfWeek.ToString());\n  string colName = lunchTimes.Text;\n\n  string constring = "......";\n  string Query2 = "select " + colName + " from database.timeslots2 " + \n                  "where day= @day";\n  using(MySqlConnection conDataBase2 = new MySqlConnection(constring))\n  using(MySqlCommand cmdDataBase2 = new MySqlCommand(Query2, conDataBase2))\n  {\n     conDataBase2.Open();\n     cmdDataBase2.Parameters.Add("@day", MySqlDbType.VarChar).Value = today;\n     using(MySqlDataReader reader = cmdDataBase2.ExecuteReader())\n     {\n         while(reader.Read())\n             Console.WriteLine(today + " value is " + reader[0].ToString());\n     }\n  }\n}	0
12303218	12302759	Regex: optional-ignore double quotes	\s*(?<Key>[^\s]+)\s*(?<Value>.*)	0
22327846	22325665	A concise way to handle multiple checkboxes for a model	private void AddSongs(Song song, List<int> tagIds)\n{\n    _db.Songs.Add(song);\n    foreach(var tagId in tagIds)\n    {\n        var tag = _db.Tags.SingleOrDefault(tagId);\n\n        if(tag != null) song.Tags.Add(tag);\n    }\n    _db.SaveChanges();\n}	0
10082339	10075310	How to access bitlocker recovery tab programmatically to backup recovery passwords	de.Properties["your-property-here"].Value	0
9409633	9408671	Regex split and replace	string input = @"Welcome to home | %brand %productName";\n            string pattern = @"%\S+";\n            var matches = Regex.Matches(input, pattern);\n            string result = string.Empty;\n            for (int i = 0; i < matches.Count; i++)\n            {\n                result += "match " + i + ",value:" + matches[i].Value + "\n";\n            }\n            Console.WriteLine(result);	0
4262881	4262826	DIO Control Code Needed	#define CTL_CODE( DeviceType, Function, Method, Access ) (                 \\n    ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \\n)\n\n#define METHOD_BUFFERED                 0\n\n#define FILE_ANY_ACCESS                 0\n\n#define FILE_DEVICE_MASS_STORAGE        0x0000002d\n\n#define IOCTL_STORAGE_BASE FILE_DEVICE_MASS_STORAGE\n\n#define IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER CTL_CODE(IOCTL_STORAGE_BASE, 0x0304, METHOD_BUFFERED, FILE_ANY_ACCESS)	0
1853702	1853650	Replacing a Regex Match Collection in C#	// This will require a reference to System.Text\nStringBuilder input =new StringBuilder(Input);\n  foreach (Block block in Blocks)\n  {\n    input = input.Replace("[" + block.OrginalText + "]", block.Process);\n  }\n  return input.ToString();	0
12591217	12589772	Window Loaded and WPF	public MainWindow()\n{\n    InitializeComponent();\n\n    this.Loaded += new RoutedEventHandler(MainWindow_Loaded);\n}\n\nvoid MainWindow_Loaded(object sender, RoutedEventArgs e)\n{\n    ShellViewModel.Instance.WindowLoadedCommand.Execute(null);\n}	0
18912162	16457498	Entity Framework mapping of object containing list of same objects	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<Subject>().\n        HasMany(m => m.Prerequisites).\n        WithMany()\n        .Map(m =>\n            {\n                m.ToTable("SubjectPrerequisite");\n                m.MapLeftKey("SubjectId");\n                m.MapRightKey("PrerequisiteId");\n            });\n}	0
16151943	16151889	ASP.NET how to get file name in specific folder on server	string[] filePaths = Directory.GetFiles(@"c:\MyDir\");	0
13931348	13930955	Create new instance of an object from an array of unknown types	public object[] Copy(object obj) {\n    using (var memoryStream = new MemoryStream()) {\n        BinaryFormatter formatter = new BinaryFormatter();\n        formatter.Serialize(memoryStream, obj);\n        memoryStream.Position = 0;\n\n        return (object[])formatter.Deserialize(memoryStream);\n    }\n}\n\n[Serializable]\nclass testobj {\n    public string Name { get; set; }\n}\n\nclass Program {\n    static object[] list = new object[] { new testobj() { Name = "TEST" } };\n\n    static void Main(string[] args) {\n\n        object[] clonedList = Copy(list);\n\n        (clonedList[0] as testobj).Name = "BLAH";\n\n        Console.WriteLine((list[0] as testobj).Name); // prints "TEST"\n        Console.WriteLine((clonedList[0] as testobj).Name); // prints "BLAH"\n    }\n}	0
24298247	24298054	No access to MessageBox class in Windows Phone	new MessageDialog("Your Message Content").ShowAsync();	0
15928568	15928517	Hold the console window open using c#	string process = @"C:\WINNT\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe " + sourcePath + @" \Application.sln /t:rebuild";\nSystem.Diagnostics.Process csc = System.Diagnostics.Process.Start(@"%windir%\system32\cmd.exe", process);	0
26051540	26051414	Generics help needed	public T GetRoot<T>() where T:Class\n{\n}	0
3713099	3712952	Promote field's IBindingList to class's	//methods\n    public void AddIndex(PropertyDescriptor property)\n    {\n        m_theList.AddIndex(property);\n    }\n\n    public object AddNew()\n    {\n        return m_theList.AddNew();\n    }\n\n    //properties\n\n    public bool AllowEdit\n    {\n        get { return m_theList.AllowEdit; }\n    }\n\n    ....\n    //for events you can use add/remove syntax \n\n    public event ListChangedEventHandler ListChanged\n    {\n        add { m_theList.ListChanged += value; }\n        remove { m_theList.ListChanged -= value; }\n    }\n\n    ....\n    //indexer...\n    public object this[int index]\n    {\n        get\n        {\n            return m_theList[index];\n        }\n        set\n        {\n            m_theList[index] = value;\n        }\n    }	0
5708975	5708939	Reading the registry with set and get properties	rvalue = Int32.Parse((string)myKey.GetValue("DebugLog"));	0
5926476	5926252	Howto render a Func<Object, TemplateWriter> to string in Razor view engine Html Helper?	public String IncludeOnce(Func<Object, TemplateWriter> text) {\n   string output = text(Model).ToString();\n\n   //Do Stuff\n\n   return output \n}	0
844471	844461	return only Digits 0-9 from a String	reg_replace(/\D+/g, '', your_string)	0
10697213	10696657	An empty DataTable with column names from SharePoint 2010 List	DataTable _dt = new DataTable();\n\nforeach (SPField spf in _lst.Fields)\n{\n   _dt.Columns.Add(spf.InternalName.ToString(), spf.Type.GetType());\n}	0
11477677	11477593	How do you get all the post request variables in C#?	foreach(string key in Request.Form.Keys ) \n{\n  Response.Write ( key );\n}	0
8053090	8053046	how to add two data set to a grid view table	ds.Merge(ds1);\nGrid_Messagetable.DataSource = ds;	0
13669497	13669480	Get file's size from bytes array (without saving to disc)	array.Length	0
14548527	14548482	Something is going wrong with my EventWaithandle, it doesn't change to signaled?	await LoadFacebookData(parameters);	0
23447538	23447366	Parsing URL Only Using XPATH In C#	var content = link.Attributes["href"].Value	0
6344432	6344287	c# Regex remove words of less than 3 letters?	public static string StripWordsWithLessThanXLetters(string input, int x)\n{\n    var inputElements = input.Split(' ');\n    var resultBuilder = new StringBuilder();\n    foreach (var element in inputElements)\n    {\n        if (element.Length >= x)\n        {\n            resultBuilder.Append(element + " ");\n        }\n    }\n    return resultBuilder.ToString().Trim();\n}	0
30869130	30868883	Search or Find IO Serialized objects in file with c#	Dictionary<string,string> Index = new Dictionary<string,string>();\nIndex.Add(fileIdentifierThatYouWouldSearchOn,fileName);	0
6794391	6794371	Array of ValueType in C# goes to Heap or Stack?	public class X\n{\n    public int Y;\n}	0
9529491	9527908	Add checkbox with CheckedChanged Event to a Dynamic GridView	TableCell tcCheckCell = new TableCell();\n    var checkBox = new CheckBox();\n    checkBox.CheckedChanged += checkBox_CheckedChanged;\n    tcCheckCell.Controls.Add(checkBox);\n    gridView.Rows[0].Cells.AddAt(0, tcCheckCell);\n\n    void checkBox_CheckedChanged(object sender, EventArgs e)\n    {\n        //do something: You can use Krishna Thota's Code.\n    }	0
6665254	6665187	How to set dynamic value in my Attribute	enum SpecialConfigurationValues\n{\n    MachineName\n    // , other special ones\n}\n\nclass ConfigurationKeyAttribute : Attribute\n{\n    private string _key;\n    private string _value;\n\n    public ConfigurationKeyAttribute(string key, string value)\n    {\n        // ...\n    }\n\n    public ConfigurationKeyAttribute(string key, SpecialConfigurationValues specialValue)\n    {\n        _key = key;\n        switch (specialValue)\n        {\n            case SpecialConfigurationValues.MachineName:\n                _value = Environment.MachineName;\n                break;\n            // case <other special ones>\n        }\n    }\n}\n\n[ConfigurationKey("MonitoringService", SpecialConfigurationValues.MachineName)]	0
25448030	25448029	How to access WordPress logged in username via C# HttpModule	private static String GetWpLoginCookie(HttpContext context)\n{\n    String[] cookieKeys = context.Request.Cookies.AllKeys;\n    foreach (var cookieKey in cookieKeys)\n    {\n        if (cookieKey.StartsWith("wordpress_logged_in"))\n        {\n            return WebUtility.UrlDecode(context.Request.Cookies[cookieKey].Value);\n        }\n    }\n    return "Not found";\n}	0
16507085	16506653	Accessing a property in one ViewModel from another	public class MainVM\n{\n    private static MainVM _instance = new MainVM();\n    public static MainVM Instance { get { return _instance; } }\n\n    public List<XX> MyList { get; set; }\n    //other stuff here\n}\n\n//From within OtherVM:\nMainVM.Instance.MyList.Add(stuff);	0
12482148	12481518	Add Image Control inside DataList Template through C#	Image TabImages = new Image();\n     TabImages.ID = "TabImages";\n     TabImages.ImageUrl = "~/imagepath";\n     DataListCampaign.Items[0].Controls.Add(TabImages);	0
19912075	19912030	how to check value of an element is not null before assigning using linqtoxml	void Main()\n{\n    var doc = XDocument.Load(@"C:\Test\test.xml");\n\n    var city = doc.Descendants("address_component").FirstOrDefault(e => e.Element("type") != null \n                            && e.Element("type").Value =="locality");\n\n    if(city != null){                       \n     Console.WriteLine (city.GetElementIfExists("short_name"));\n    } else {\n     Console.WriteLine ("No short name found");\n    }\n}\n\npublic static class Extensions {\n public static string GetElementIfExists(this XElement @this, string element){\n   return @this.Element(element) != null ? @this.Element(element).Value : String.Empty;\n }\n}	0
4706920	4706910	how to paint link that i visit and link that i dont visit with green ? (asp.net)	a, a:visited {\n    color: green;\n}	0
16467246	16466905	find a control inside a tabpage that is created with a usercontrol	UserControl1 uc1 = tabControl1.TabPages["0"].Controls[0] as UserControl1;\nif (uc1 != null) {\n  TextBox sel = uc1.Controls["textBox1"] as TextBox;\n  if (sel != null) {\n    sel.Text = "ssss";\n  }\n}	0
18355557	18355263	How to save ListView selected item	private void OnLoad(object sender, EventArgs eventArgs)\n {\n    int selectedItem = Properties.Settings.Default.SelectedItem;\n    if (selectedItem != -1)\n    {\n       this.listView1.Items[selectedItem].Selected = true;\n    }\n  }	0
19390523	19390413	Using the selected value of a dropdown list in an if statement	if (ddlHours.SelectedItem.Text == "Part-Time")	0
16563573	16563292	What is the best way to attach a label to an enum value	var text = normalComment.GetName();\n\n\npublic static class EnumExtension\n{\n        public static string GetName(this eCommentType type)\n        {\n            return Strings.ResourceManager.GetString(type.ToString());\n        }\n}	0
16748572	16748536	Sort a List<String[]> numerically	list = list.OrderBy(x => int.Parse(x[3])).ToList();	0
7045630	7045594	XML and SelectNodes	XmlNamespaceManager nsmgr = new XmlNamespaceManager(index.NameTable);\nnsmgr.AddNamespace("x", "http://subsonic.org/restapi");\n\nXmlNodeList xnList = index.SelectNodes("/x:subsonic-response/x:indexes/x:index", nsmgr);\nXmlNode mainnode = index.SelectSingleNode("/x:subsonic-response", nsmgr);	0
19797642	19797016	Polygon difference - strange results from Clipperlib	PolyTree solutiontree = new PolyTree();\n      cpr.Execute(ClipType.ctDifference, solutiontree, \n          PolyFillType.pftNonZero, PolyFillType.pftNonZero);\n      solution = new Polygons(solutiontree.ChildCount);\n      foreach (PolyNode pn in solutiontree.Childs)\n        solution.Add(pn.Contour);	0
21027850	21027400	C# how to read standard output line by line?	string standard_output;\n            while ((standard_output = myProcess.StandardOutput.ReadLine())!=null) \n            {\n                if (standard_output.Contains("xx"))\n                {\n                   //do something\n                    break;\n                }\n            }	0
4639058	4639036	Get distinct items from a list	List<int> result = YourListObject.Select(o => o.FirstInteger).Distinct().ToList();	0
19413274	19413194	Using validation to check a persons age from todays date	MyDateRangeValidator.MinimumValue = DateTime.Now.AddYears(-25).ToString(/* format */);\nMyDateRangeValidator.MaximumValue = DateTime.Now.AddYears(-18).ToString(/* format */);	0
3015380	3015040	Get just the hour of day from DateTime using either 12 or 24 hour format as defined by the current culture	// displays "15" because my current culture is en-GB\nConsole.WriteLine(DateTime.Now.ToHourString());\n\n// displays "3 pm"\nConsole.WriteLine(DateTime.Now.ToHourString(new CultureInfo("en-US")));\n\n// displays "15"\nConsole.WriteLine(DateTime.Now.ToHourString(new CultureInfo("de-DE")));\n\n// ...\n\npublic static class DateTimeExtensions\n{\n    public static string ToHourString(this DateTime dt)\n    {\n        return dt.ToHourString(null);\n    }\n\n    public static string ToHourString(this DateTime dt, IFormatProvider provider)\n    {\n        DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(provider);\n\n        string format = Regex.Replace(dtfi.ShortTimePattern, @"[^hHt\s]", "");\n        format = Regex.Replace(format, @"\s+", " ").Trim();\n\n        if (format.Length == 0)\n            return "";\n\n        if (format.Length == 1)\n            format = '%' + format;\n\n        return dt.ToString(format, dtfi);\n    }\n}	0
25766036	25765957	Check if byte stored as string of bits is set at a given position	Byte result = Convert.ToByte(reader[1].ToString(), 2);	0
13921188	13921061	How to add references using Reflection.Emit	Reflection.Emit	0
168182	168173	Change name of file sent to client?	Response.AddHeader("content-disposition", "attachment; filename=NewFileName.csv");	0
3104640	3104615	Best way to display decimal without trailing zeros in c#	static void Main(string[] args)\n    {\n        var dList = new decimal[] { 20, 20.00m, 20.5m, 20.5000m, 20.125m, 20.12500m, 0.000m };\n\n        foreach (var d in dList)\n            Console.WriteLine(d.ToString("0.#####"));\n    }	0
1378992	279296	Adding Days to a Date but Excluding Weekends	var dateTime = DateTime.Now.AddBusinessDays(4);	0
10054040	10034024	Index Change event for Combobox of gridtemplateColumn in Telerik	protected void cmbGrp_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)\n{\n    RadComboBox ddlCtrl = sender as RadComboBox;\n    GridEditableItem dataItem = ddlCtrl.NamingContainer as GridEditableItem;\n    RadComboBox cmbCtrl = dataItem.FindControl("cmbSetNo") as RadComboBox;\n    RadTextBox txtCtrl = dataItem.FindControl("cmbSetNo") as RadTextBox;\n    txtCtrl.Text = ddlctrl.SelectedValue.ToString();\n    string qury = "QUERY";\n    ds.Clear();\n    ds = c.getDataSet(qury);\n    cmbCtrl.DataSource = ds.Tables[0];\n    cmbCtrl.DataTextField = "NO";\n    cmbCtrl.DataValueField = "RecordID";\n    cmbCtrl.DataBind();\n}	0
10426745	10426680	combobox value in c sharp	sqlCon = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Anbar;Integrated Security=True");\n  SqlDataAdapter da = new SqlDataAdapter("Select StudentName from School", sqlCon);\n        DataTable dt = new DataTable();\n        da.Fill(dt);\n        yourComboBox.DataSource = dt;\n        yourComboBox.DisplayMember = "StudentName";\n        yourComboBox.ValueMember = "StudentName";	0
331430	331004	How to map a string to Uri type using the Entity Framework?	public partial class MyClass\n    {\n        public Uri MyUri\n        {\n            get\n                { return new Uri(StringUriPropertyFromDB); }\n        }\n    }	0
9440813	9440009	Creating a list of static objects in asp.net	IList<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies();\n\nList<Type> allTypes = new List<Type>();\n\nforeach (Assembly assembly in assemblies)\n{\n    var types = from t in assembly.GetTypes()\n                where bootStrapperType.IsAssignableFrom(t)\n                    && !t.IsInterface && !t.IsAbstract\n                select t;\n\n    allTypes.AddRange(types);\n}\n\nforeach(Type type in allTypes)\n{\n    var fieldsPublic = type.GetFields(BindingFlags.Public|BindingFlags.Static);\n    foreach(var field in fieldsPublic)\n    {\n       var nameAndValue = field.Name + " = " + field.GetValue(null);\n       // Do something\n    }\n    var fieldsPrivate = type.GetFields(BindingFlags.Private|BindingFlags.Static);\n    foreach(var field in fieldsPrivate)\n    {\n       var nameAndValue = field.Name + " = " + field.GetValue(null);\n       // Do something.\n    }\n}	0
953228	953191	Forbidding access to Inherited winform controls	// set the Modifiers property on tabControl1 to "Private" then implement this\npublic TabControl.TabPageCollection TabPages\n{\n    get { return tabControl1.TabPages; }\n}	0
1207487	1207472	Force an iteration of a loop	continue; // Goto the next iteration\nbreak; // Exit the loop	0
7790168	7790151	Can I make internals visible to all assemblies signed with same key?	[InternalsVisibleTo(...)]	0
20329536	20329360	How to set DefaultValueAttribute on List<Color> collection property (set default colors)?	private List<Color> _gradientColorList = new List<Color>(new List<Color>(new Color[] { Color.FromArgb(116, 194, 225), Color.FromArgb(1, 145, 200), Color.FromArgb(0, 91, 154) }));	0
32805003	32803454	How to setup a webapi controller for POST method	Content-Type: application/json	0
2934155	2929587	How to replace values in multi-valued ESE column?	JET_RETRIEVECOLUMN retrievecolumn = new JET_RETRIEVECOLUMN();\nretrievecolumn.columnid = multivalueColumn;\nretrievecolumn.itagSequence = 0;\nApi.JetRetrieveColumns(sesid, tableid, new[] { retrievecolumn }, 1); \nConsole.WriteLine("{0}", retrievecolumn.itagSequence);	0
12771241	12755543	List of Web.Ui.Controls to apply Style on in one method	public static void Atdd(Control htmlOrWebCntrl, string prop, string value)\n        {\n            if (htmlOrWebCntrl.GetType().IsSubclassOf(typeof(WebControl)))\n            {\n                WebControl wc = htmlOrWebCntrl as WebControl;\n                wc.Style.Add(prop, value);\n            }\n            else\n                if (htmlOrWebCntrl.GetType().IsSubclassOf(typeof(HtmlControl)))\n                {\n\n                    HtmlControl HtmlCtrl = htmlOrWebCntrl as HtmlControl;\n\n                    HtmlCtrl.Style.Add(prop, value);\n                }\n\n        }	0
12724596	12724197	How do I populate my CheckBoxList with values from my database?	chkBoxDaysList.DataSource = tempds.Tables(0)\nchkBoxDaysList.DataTextField = "SeatID"\nchkBoxDaysList.DataValueField = "Flag"\nchkBoxDaysList.DataBind()	0
1680446	1679986	ZIP file created with SharpZipLib cannot be opened on Mac OS X	using (var outStream = new FileStream("Out3.zip", FileMode.Create))\n        {\n            using (var zipStream = new ZipOutputStream(outStream))\n            {\n                Crc32 crc = new Crc32();\n\n                foreach (string pathname in pathnames)\n                {\n                    byte[] buffer = File.ReadAllBytes(pathname);\n\n                    ZipEntry entry = new ZipEntry(Path.GetFileName(pathname));\n                    entry.DateTime = now;\n                    entry.Size = buffer.Length;\n\n                    crc.Reset();\n                    crc.Update(buffer);\n\n                    entry.Crc = crc.Value;\n\n                    zipStream.PutNextEntry(entry);\n                    zipStream.Write(buffer, 0, buffer.Length);\n                }\n\n                zipStream.Finish();\n\n                // I dont think this is required at all\n                zipStream.Flush();\n                zipStream.Close();\n\n            }\n        }	0
5891207	5890403	Specify the MySql assembly for NHibernate?	connection.driver_class	0
17904740	17901338	Ninject C# - Get concrete type at runtime from reading configuration	Bind<IAction>().To<Action1>().When(ctx => IsAction1Configured());\nBind<IAction>().To<Action2>().When(ctx => IsAction2Configured());	0
15584465	15584000	How to search (predefined) locations (Latitude/Longitude) within a Rectangular, using Sql?	DECLARE @Bounds AS Geography = GEOMETRY::STGeomFromText('polygon-wkt-here',0)\n\nSELECT columns-list\nFROM   table\nWHERE  1 = @Bounds.STIntersects(table.point-column)	0
17114596	17114212	Get name of "parent" database from assembly	using (SqlConnection conn = new SqlConnection("context connection=true"))\n{\n    conn.Open();\n    string dbName = conn.Database\n}	0
2400952	2400889	xml invalid character in the given encoding	using (var reader = XmlReader.Create(new StringReader(xml), settings)) { ...	0
27435181	27434910	Cannot get value for first column on a selected row in listview	MessageBox.Show(PlotListView.SelectedItems[0].SubItems[0].Text);	0
7740949	7740911	 read local image in wp7	private WriteableBitmap ReadLocalImage(string Uri)\n        {\n            StreamResourceInfo sri = null;\n            Uri uri = new Uri(Uri, UriKind.Relative);\n            sri = Application.GetResourceStream(uri);\n            BitmapImage bitmap = new BitmapImage();\n            bitmap.CreateOptions = BitmapCreateOptions.None;\n            bitmap.SetSource(sri.Stream);\n            WriteableBitmap wb = new WriteableBitmap(bitmap);\n            return wb;\n\n        }	0
30542593	30531888	Best way to provide params to a state transition in a FSM	class MyStateMachine\n{\n  private readonly Func<string> askForName;\n\n  public MyStateMachine(Func<string> askForName)\n  {\n    this.askForName = askForName;\n  }\n\n  // ...\n\n  void StateTransitionForActionX()\n  {\n    var name = askForName();\n\n    // ...\n  }\n}\n\npublic MyStateMachine CreateMachine()\n{\n  return new MyStateMachine\n   (\n     () => \n     {\n       Console.WriteLine("Please, enter your name: ");\n       return Console.ReadLine();\n     }\n   );\n}	0
1577671	1577361	Get the first few words from a long summary(plain string or HTML)	// retrieve a summary of html, with no less than 'max' words\nstring GetSummary(string html, int max)\n{\nstring summaryHtml = string.Empty;\n\n// load our html document\nHtmlDocument htmlDoc = new HtmlDocument();\nhtmlDoc.LoadHtml(html);\n\nint wordCount = 0;\n\n\nforeach (var element in htmlDoc.DocumentNode.ChildNodes)\n{\n// inner text will strip out all html, and give us plain text\nstring elementText = element.InnerText;\n\n// we split by space to get all the words in this element\nstring[] elementWords = elementText.Split(new char[] { ' ' });\n\n// and if we haven't used too many words ...\nif (wordCount <= max)\n{\n// add the *outer* HTML (which will have proper \n// html formatting for this fragment) to the summary\nsummaryHtml += element.OuterHtml;\n\nwordCount += elementWords.Count() + 1;\n}\nelse \n{ \nbreak; \n}\n}\n\nreturn summaryHtml;\n}	0
2980499	2980423	wait for process to exit when using CreateProcessAsUser	const UInt32 INFINITE = 0xFFFFFFFF;\n\n // Declare variables\n PROCESS_INFORMATION pi;\n STARTUPINFO si;\n System.IntPtr hToken;\n\n // Create structs\n SECURITY_ATTRIBUTES saThreadAttributes = new SECURITY_ATTRIBUTES();    \n\n // Now create the process as the user\n if (!CreateProcessAsUser(hToken, String.Empty, commandLine,\n null, saThreadAttributes, false, 0, IntPtr.Zero, 0, si, pi))\n {\n // Throw exception\n throw new Exception("Failed to CreateProcessAsUser");\n }\n\n WaitForSingleObject(pi.hProcess, (int)INFINITE);	0
26047972	26047852	DateTime parse C#	string dateString = "2014-09-26t1505";\n  string format = "yyyy-MM-dd't'HHmm";\n  CultureInfo provider = CultureInfo.InvariantCulture;\n  try {\n     DateTime result = DateTime.ParseExact(dateString, format, provider);\n     Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());\n  }\n  catch (FormatException) {\n     Console.WriteLine("{0} is not in the correct format.", dateString);\n  }	0
32113714	32113251	How to remove values from database that doesn't have a certain value	var stockItem = quoteItem.BodyType.Name == "Royal Corrugated" || \n                quoteItem.BodyType.Name == "Royal Smooth Riveted" \n                    ? db.StockItems.Where(x => x.StockCode == "AEX165").First() \n                    : null;\n\nif(stockItem != null)\n{\n   var qisg = new QuoteItemSectionGroup\n   {\n      SectionGroup = db.SectionGroups.Where(x => x.Name == "Ali Bottom Rail" && x.Section == TruckSection.FrontEndRequirments).First(),\n      StockItem = stockItem,\n   };\n\n   qisg.Quantity = 1;\n   qisg.Weight = Math.Round(((double)qisg.Length * (double)qisg.Quantity) * (double)qisg.StockItem.Mass, 2);\n   qisg.Cost = Math.Round(((double)qisg.Length * (double)qisg.Quantity) * (double)qisg.StockItem.UnitCost, 2);\n\n   quoteItem.SectionGroups.Add(qisg);\n}	0
15036220	15035251	Asp.net web api post action parameters	public class EmptyParameterBinding : HttpParameterBinding\n{\n    public EmptyParameterBinding(HttpParameterDescriptor descriptor)\n        : base(descriptor)\n    {\n    }\n\n    public override bool WillReadBody\n    {\n        get\n        {\n            return false;\n        }\n    }\n\n    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n    {\n        return Task.FromResult(0);\n    }\n}	0
32773555	32773489	WPF control Gridview	ListViewName.ItemsSource = bla bla;	0
4744455	4742619	Copy paste excel data into Rich text box + remove grid lines	private void richTextBox1_KeyDown(object sender, KeyEventArgs e)\n        {\n            if (e.Control == true && e.KeyCode == Keys.V)\n            {\n                e.Handled = true;\n                string st = Clipboard.GetText();\n                richTextBox1.Text = st;\n            }\n        }	0
6779142	6779012	Stream with openWrite not writing until it is closed	byte[] data = new byte[dataChunkSize];\nint bytesRead = reader.Read(data, 0, dataChunkSize);\nwriter.Write(data, 0, bytesRead);\nwriter.Flush();	0
13080181	13059548	DBContext Find with Includes - where lambda with Primary keys	public DALEntity Get(string ID, IEnumerable<string> IncludeEntities = null)\n{\n  var set = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<DALEntity>();\n  var entitySet = set.EntitySet;\n  string[] keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();\n  Debug.Assert(keyNames.Length == 1, "DAL does not work with composite primary keys or tables without primary keys");\n\n  IQueryable<DALEntity> query = dbSet;\n  query = IncludeEntities.Aggregate(query, (current, includePath) => current.Include(includePath));\n\n  query = query.Where(keyNames[0] + "= @0", ID);\n  return query.FirstOrDefault();\n}	0
30720433	30720186	Run VBScript from C# with hidden window and capture output	process.StartInfo.CreateNoWindow = true;	0
3115634	3115627	How to get filename from a file "template.docx.amp" in c#?	var nameWithoutExtension = filename.Split('.')[0];	0
7726184	7726097	How to compare the datetime picker value with some folder name 	public static void ProcessDirectory(string targetDirectory) \n{\n    // Process the list of files found in the directory.\n    string [] fileEntries = Directory.GetFiles(targetDirectory);\n    foreach(string fileName in fileEntries)\n      Do work here which you need.\n}	0
12429420	12423426	How to write join with composite key clause in FSharp query expressions?	query {\n  for o in DataContext.OTable do\n  join k in DataContext.Catalogs on\n   ((o.IDENT, o.VZ) = (k.IDENT, k.VZ))\n  select (o.IDENT, k.VZ)\n}	0
22922197	22798132	How to show FileSystem.DeleteFile dialog as top most or set the parent/owner?	string message = string.Format("Are you sure you want to move '{0}' to the recycling bin?", Path.GetFileNameWithoutExtension(path));\n            var result = MessageBox.Show(this, message, @"Move To Recycling Bin?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\n            if (result == DialogResult.Yes)\n            {\n                Send(path, FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_NOERRORUI | FileOperationFlags.FOF_SILENT);\n            }	0
29601505	29600790	How do I Reset value of IntegerUpDown to minimum if it exceeds maximum	private void IntegerUpDown_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n    {\n        var updown = (sender as IntegerUpDown);\n        if (updown.Value == updown.Maximum)\n            updown.Value = updown.Minimum;\n    }	0
24646807	24646153	how to clone a list object	public object Clone()\n{\n    return new GrossTemplates()\n    {\n        tempId = this.tempId,\n        PreferenceName = this.PreferenceName,\n        PreferenceValue = this.PreferenceValue,\n        IsDefault = this.IsDefault\n    };\n}	0
7035157	7035110	C# dedupe List based on split	var list = new string[]\n                    {\n                        "apple|pear|fruit|basket",\n                        "orange|mango|fruit|turtle",\n                        "purple|red|black|green",\n                        "hero|thor|ironman|hulk "\n                    };\n\nvar dedup  = new List<string>();\nvar filtered = new List<string>();\nforeach (var s in list)\n{\n    var filter = s.Split('|')[2];\n    if (dedup.Contains(filter)) continue;\n    filtered.Add(s);\n    dedup.Add(filter);\n}\n\n\n// Console.WriteLine(filtered);	0
5614573	5607807	Open Event of Window and Handle of Window	Process[] processes = Process.GetProcessesByName("OUTLOOK");\n\n                    foreach (Process p in processes)\n                    {\n\n                        if (p.MainWindowTitle == mail.GetInspector.Caption)\n                        {\n\n                            handle = p.MainWindowHandle;\n\n                            break;\n                        }\n\n                    }	0
24798498	24795912	a build script that can compile and test the solution from the command line	MSBuild.exe MyProj.csproj /property:Configuration=Debug	0
4185370	4185248	execute custom sql with entity framework4	context.ExecuteStoreQuery<vwWorkOrder>(sql);	0
27608602	27606170	How to read excel list elements (data validation) using C# Excel Interop?	List<string> ReadDropDownValues(Excel.Workbook xlWorkBook, Excel.Range dropDownCell)\n{\n    List<string> result = new List<string>();\n\n    string formulaRange = dropDownCell.Validation.Formula1;\n    string[] formulaRangeWorkSheetAndCells = formulaRange.Substring(1, formulaRange.Length - 1).Split('!');\n    string[] splitFormulaRange = formulaRangeWorkSheetAndCells[1].Split(':');\n    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(formulaRangeWorkSheetAndCells[0]);\n\n    Excel.Range valRange = (Excel.Range)xlWorkSheet.get_Range(splitFormulaRange[0], splitFormulaRange[1]);\n    for (int nRows = 1; nRows <= valRange.Rows.Count; nRows++)\n    {\n        for (int nCols = 1; nCols <= valRange.Columns.Count; nCols++)\n        {\n            Excel.Range aCell = (Excel.Range)valRange.Cells[nRows, nCols];\n            if (aCell.Value2 != null)\n            {\n                result.Add(aCell.Value2.ToString());\n            }\n        }\n    }\n\n    return result;\n}	0
1439098	1439086	detect ctrl+left click in winforms application	btn.Click += new EventHandler(btn_Click);\n\n    private void btn_Click(object sender, EventArgs e)\n    {\n        if (Form.ModifierKeys == Keys.Control)\n        {\n            // Do Ctrl-Left Click Work\n        }\n    }	0
16167836	16167755	C# WPF Change datagrid cell background after CellEditEnding event	private void DataGridMeterValues_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e)\n{\n\n        FrameworkElement element = e.Column.GetCellContent(DataGridMeterValues.SelectedItem);\n        (element.Parent as DataGridCell).Background = new SolidColorBrush(Colors.Red);\n\n}	0
1174851	1174792	How can I update a specific XElement?	XDocument doc;\n...\nXElement penItemValue = doc\n     .Elements("MyStore")\n     .Elements("Category")\n     .Elements("itemName")\n     .Single(itemName => itemName.Value == "Pen")\n     .Parent\n     .Element("itemValue");\npenItemValue.Value = "123";	0
21326969	21313198	Change proxy settings in Gecko Webbrowser at execution time?	GeckoPreferences.Default["network.proxy.type"] = 1;\nGeckoPreferences.Default["network.proxy.http"] = proxyAddress.Host;\nGeckoPreferences.Default["network.proxy.http_port"] = proxyAddress.Port;\nGeckoPreferences.Default["network.proxy.ssl"] = proxyAddress.Host;\nGeckoPreferences.Default["network.proxy.ssl_port"] = proxyAddress.Port;	0
16206004	16205991	Format DateTime in C# to append to file name	DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss")	0
34423258	34422361	Datareader Exception Thrown Database - DateTime	private void ITemail()\n{\n     string FinEmail;\n     clsDBConnector dbConnector = new clsDBConnector();\n     OleDbDataReader dr;\n     dbConnector.Connect();\n     var sqlStr = "SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName "\n        + "FROM tblAudit WHERE (ClientName = '" + Client + "') AND Created = #" + ToDate() + "#";\n     dr = dbConnector.DoSQL(sqlStr);\n     while (dr.Read())\n     {\n         txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()\n                + dr[7].ToString() + dr[8].ToString();\n     }\n}\nprivate string ToDate()\n{\n    return DateTime.Today.ToString("yyyy'/'MM'/'dd");\n}	0
3029166	3029156	Application shortcut	WshShell = new WshShellClass();\n\n// Create the shortcut\nIWshRuntimeLibrary.IWshShortcut MyShortcut;\n\n// Choose the path for the shortcut\nMyShortcut = IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(@"C:\MyShortcut.lnk");\n\n// Where the shortcut should point to\nMyShortcut.TargetPath = Application.ExecutablePath;\n\n// Description for the shortcut\nMyShortcut.Description = "Launch My Application";\n\n// Location for the shortcut's icon\nMyShortcut.IconLocation = Application.StartupPath + @"\app.ico";\n\n// Create the shortcut at the given path\nMyShortcut.Save();	0
3773464	3773312	Change the Implement Interface template	PropertyStub.snippet	0
5713974	5713730	c# press a button from a window using user32 dll	SendMessage(ptrChild, WM_LBUTTONDOWN, 0, IntPtr.Zero);   //send left button mouse down\n  SendMessage(ptrChild, WM_LBUTTONUP, 0, IntPtr.Zero);     //send left button mouse up\n  SendMessage(ptrChild, BM_SETSTATE,1 , IntPtr.Zero);     //send change state	0
27229150	27227534	Select a block of lines from a text file	using System.IO;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nnamespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var tokens = new List<string>();\n            foreach (string line in File.ReadAllLines("C:\\temp\\test.txt"))\n            {\n                if (Regex.IsMatch(line, @"^\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d"))\n                {\n                    tokens.Add(line);\n                }\n                else if(tokens.Count > 0)\n                {\n                    tokens[tokens.Count - 1] += "\r\n" + line;\n                }\n            }\n        }\n    }\n}	0
150132	149909	How can I use a type with generic arguments as a constraint?	public abstract class FooBase\n{\n  private FooBase() {} // Not inheritable by anyone else\n  public class Foo<U> : FooBase {...generic stuff ...}\n\n  ... nongeneric stuff ...\n}\n\npublic class Bar<T> where T: FooBase { ... }\n...\nnew Bar<FooBase.Foo<string>>()	0
6004547	6004500	Can't reach to specific xml nodes	XmlNodeList elemList = doc.GetElementsByTagName("x:Property");	0
31925355	31924604	Get list of X509Certificate from cert store C# MVC	X509Store store = new X509Store(StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);\nforeach (X509Certificate2 certificate in store.Certificates)\n{\n    // TODO\n}	0
1603151	1602043	How to manage SQL Connections with a utility class?	public List<User> GetUsers()\n{\n    List<User> result = new List<User>();\n\n    Database db = new\n    Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(this.connectionString);\n    DbCommand cmd = db.GetStoredProcCommand("GetUsers");\n\n    using (IDataReader rdr = db.ExecuteReader(cmd))\n    {\n        while (rdr.Read())\n        {\n            User user = new User();\n            FillUser(rdr, user);                   \n            result.Add(user);\n        }\n    }\n    return result;\n\n}	0
28662146	28662086	How to randomize the text in a label	string[] lines = File.ReadAllLines(file_location);\nRandom rand = new Random();\nreturn lines[rand.Next(lines.Length)];	0
33272409	33272223	Add image from a folder to Excel worksheet	// Variable\nstring[] filesDirectory = Directory.GetFiles(Server.MapPath("~/Image"));\nint count = 0;\n\nforeach(string img in filesDirectory)\n{\n    count++;\n    ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Worksheet - " + count);\n\n    // img variable actually is your image path\n    System.Drawing.Image myImage = System.Drawing.Image.FromFile(img);\n\n    var pic = ws.Drawings.AddPicture("NAME", myImage);\n\n    // Row, RowoffsetPixel, Column, ColumnOffSetPixel\n    pic.SetPosition(1, 0, 2, 0);\n}	0
2968345	2968316	Make a c# / wpf event fire only once?	EventHandler h = null;\n\nh = delegate(Object sender, EventArgs e) {\n  FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h"\n  // Do stuff\n}\n\nFiringControl.TheEvent += h;	0
25450162	25448318	How to programmatically add a value to a file combo box for automation using TestStack.White	var fileNameTextBox = fileUploadWindow.Get<TextBox>(SearchCriteria.ByAutomationId("fileComboBox"));\nfileNameTextBox.Text = fileName;	0
29120627	29120252	How to show multiple message boxes	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;\n\nnamespace WindowsFormsApplication2\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        public static int t = 1800;\n        public static bool msg = false;\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            timer1.Enabled = true;\n            timer1.Interval = t;\n        }\n\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n            if (msg == false)\n            {\n                msg = true;\n                MessageBox.Show("Some text here.", "");\n                msg = false;\n            }\n        }\n    }\n}	0
3859931	3859900	Using integer based enum	class Program\n{\n   [Flags]   // <--\n   private enum Subject \n   { \n       History = 1, Math = 2, Geography = 4    // <-- Powers of 2\n   }\n    static void Main(string[] args)\n    {\n        Console.WriteLine(addSubject(Subject.History));\n    }\n    private static Subject addSubject(Subject H)\n    {\n        return H | Subject.Math;\n    }\n}	0
14535723	14535218	Best way to find table match	static bool match(TableRow row, string _Name, string _Hair, string _Eyes)\n        {\n                return (row.Name == _Name || row.Name == "*") && (row.Hair == _Hair || row.Hair == "*") && (row.Eyes == _Eyes || row.Eyes == "*");\n        }\n\n        static int score(TableRow row)\n        {\n                //can assume these already "match"\n                var score = 0;\n                score +=  row.Name == "*" ? 1000 : 2000; \n                score +=  row.Hair == "*" ? 100 : 200; \n                score +=  row.Eyes == "*" ? 10 : 20; \n                return score;\n        }\n\n        static int FindID(string _Name, string _Hair, string _Eyes)\n        {\n\n            var s = from row in _MyTable.Table\n                        where match(row, _Name, _Hair, _Eyes)\n                        orderby score(row) descending\n                        select row;\n\n\n            var match = s.FirstOrDefault();\n            if(match != null) return match.ID;\n            return -1; //i guess?\n        }	0
27421749	27421708	pass alt code combination as parameter	string a = "\u0149";	0
1520860	1520827	Sorting a Dictionary<string,Dictionary<string,string>> by the value of the inner Dictionary value using LINQ?	from outerPair in outer\nfrom innerPair in outerPair.Value\norderby innerPair.Value\nselect new {\n    OuterKey = outerPair.Key,\n    InnerKey = innerPair.Key,\n    Value = innerPair.Value\n};	0
8305468	8304498	Deciding how to pass selected file from Open File Dialog to another form	public partial class Form1 : Form\n        {\n            Form2 frm2;\n            public Form1()\n            {\n                InitializeComponent();\n                frm2 = new Form2();\n            }\n            private void btnOpenFile_Click(object sender, EventArgs e)\n            {\n                if (openFileDialog1.ShowDialog() == DialogResult.OK)\n                {\n                    frm2.FileName = openFileDialog1.FileName;\n                    frm2.Show();\n                }\n            }\n        }\n\n    public partial class Form2 : Form\n    {\n        string _fileName = "";\n         public string FileName\n        {\n            get\n            {\n                return this._fileName;\n            }\n            set\n            {\n                this._fileName = value;\n            }\n        }\n    }	0
4482412	4482297	How can I get DateTime.DaysInMonth without weekends?	class Program\n{\n    static void Main(string[] args)\n    {\n        int month = DateTime.Today.Month;\n        int year = DateTime.Today.Year;\n\n        int daysInMonthMinusFridayAndSaturday = 0;\n\n        for (int i = 1; i <= DateTime.DaysInMonth(year,month); i++)\n        {\n            DateTime thisDay = new DateTime(year,month,i);\n            if(thisDay.DayOfWeek != DayOfWeek.Friday && thisDay.DayOfWeek != DayOfWeek.Saturday)\n            {\n                daysInMonthMinusFridayAndSaturday += 1;\n            }\n        }\n\n        Console.WriteLine(daysInMonthMinusFridayAndSaturday);\n        Console.ReadLine();\n    }\n}	0
12923964	12923556	Retrieve Dictionary value from GridView in WPF	foreach (KeyValuePair<Files, string> pair in files)\n    {\n        if (pair.Key.File == "1")\n        { \n           pair.Value// This will be return 4\n        }\n    }	0
4988934	4988770	Error With Dynamically Created SQL Insert statement	cmd.CommandText = "INSERT INTO LogIn([Username],[Password]) VALUES('" + AddUsernameTextBox.Text + "','" + AddPasswordTextBox.Text + "')";	0
12782945	12782853	Server side single quote breaking javascript string	string js = new JavaScriptSerializer().Serialize(new[]{"a","b","c"});	0
15454213	15453841	I want to get or set data to each cell of DataGridView based on combobox selection	strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS where Area_ID="+cbxMyCombox.SelectedIndex;	0
18383677	18382822	Converting a method argument into an enum	public string doSomething(string param1, int status)\n{\n    if (IsValidEnum<Status>(status))\n    {\n        Account.Status = (Status)status;\n    }\n    ...\n}\n\nprivate bool IsValidEnum<T>(int value)\n{\n    var validValues = Enum.GetValues(typeof(T));\n    var validIntValues = validValues.Cast<int>();\n    return validIntValues.Any(v => v == value);\n}	0
21988630	21756607	Padding a string with ASCII control characters - Objective C	NSString * Password = @"test12";\n\nint padding = 16 - ([Password length] % 16);\n\nint asciiCode = padding;\n\nfor(int i=0;i<padding;i++)\n{\n    Password = [Password stringByAppendingString:[NSString stringWithFormat:@"%c", asciiCode]];\n}\n\nNSLog(@"Password after padding: %@", Password);\n\nNSLog(@"Padding: %d", padding);\n\nNSString *base64EncodedString = [[Password dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];\nNSLog(@"Encoded Padded PWD: %@", base64EncodedString);	0
19864919	19864565	How can I format a regex capture string so it can be formatted with String.Format()?	static void Main(string[] args)\n{\n    var index = 0;\n    var input = "this FOO is FOO a FOO test";\n    var pattern = "FOO";\n    var result = Regex.Replace(input, pattern, m => "{" + (index++) + "}");\n\n    Console.WriteLine(result); // produces "this {0} is {1} a {2} test"\n}	0
30519567	30519485	How can i add a BehaviourScript to an Instantiated GameObject in Unity3D?	// This is the line of code that you're already using to spawn a cube:\nGameObject cube = GameObject.Instantiate(cubePrefab) as GameObject;\n\n// This is the line of code needed to attach a script:\ncube.AddComponent<RotateOnKeys>();	0
5310239	5301039	Generate PDF from set of JPEGs	Document document = new Document();\nPdfWriter.getInstance(document, new FileOutputStream(yourOutFile));\ndocument.open();\n\nfor(int i=0;i<numberOfImages;i++){\n  Image image1 = Image.getInstance("myImage"+i+".jpg");\n  image1.scalePercent(23f);\n  document.newPage();\n  document.add(image1);\n}\ndocument.close();	0
17122726	17122664	How to handle a method that might return null and generate a System.NullReferenceException	var fruit = store.GetAFruit(...);\nif(fruit != null) {\n    //... Do stuff\n}	0
24786894	24771527	Log in to Gmail API	// Create OAuth Credential.\nUserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(\n    new ClientSecrets\n    {\n        ClientId = "CLIENT_ID",\n        ClientSecret = "CLIENT_SECRET"\n    },\n    new[] { GmailService.Scope.GmailModify },\n    "user",\n    CancellationToken.None).Result;\n\n// Create the service.\nvar service = new GmailService(new BaseClientService.Initializer()\n{\n    HttpClientInitializer = credential,\n    ApplicationName = "Draft Sender",\n});\n\nListDraftsResponse draftsResponse = service.Users.Drafts.List("me").Execute();	0
17216838	17216445	Convert string value to date from FormCollection	string input = "new Date(2012,9,3)";\n\nvar dateTimeString = input.Split(new[] {'(', ')'}, \n                                 StringSplitOptions.RemoveEmptyEntries)\n                          .Last();\n\nvar datetime = DateTime.ParseExact(dateTimeString, \n                                   "yyyy,M,d", CultureInfo.InvariantCulture);	0
6925387	6925354	Is there a way to provide failure message with ExpectedException attribute?	[Test]\n[ExpectedException(typeof(ArgumentNullException))]\npublic void EmptyNameInConstructorThrowsExceptionTest()\n{\n    SomeClass someClass = new SomeClass(null);\n    Assert.Fail("Exception not thrown");\n}	0
24713661	24713558	C# interweave two uneven List into a new List	int length = Math.Min(list1.Count, list2.Count);\n\n// Combine the first 'length' elements from both lists into pairs\nlist1.Take(length)\n.Zip(list2.Take(length), (a, b) => new int[] { a, b })\n// Flatten out the pairs\n.SelectMany(array => array)\n// Concatenate the remaining elements in the lists)\n.Concat(list1.Skip(length))\n.Concat(list2.Skip(length));	0
1426312	1027051	How to autoscroll on WPF datagrid	if (mainDataGrid.Items.Count > 0)\n        {\n            var border = VisualTreeHelper.GetChild(mainDataGrid, 0) as Decorator;\n            if (border != null)\n            {\n                var scroll = border.Child as ScrollViewer;\n                if (scroll != null) scroll.ScrollToEnd();\n            }\n        }	0
20327354	20284263	Telerik grid, add Id parameter into column commands possible?	.DataKeys(x =>\n                {\n                    x.Add(y => y.Id).RouteKey("Id");\n                })\n\n\n\n var nop_gModel = new PictureModel.myPictureModel()\n                {\n                    Id = x.Id,//Changed as you are getting picture by Id\n                    PictureUrl = _pictureService.GetPictureUrl(x.PictureID),\n                    DisplayOrder = x.OrderNumber,\n                    Description = x.Description\n                };\n\n\n\nvar galleryPicture = _galleryItemService.GetGalleryPictureById(model.Id);	0
24735977	24712198	How can I print GMap.NET maps?	string path = Path.GetTempPath() + Path.GetRandomFileName() + @".png";\n        _tmpImage = View.gmap.ToImage();\n        if (_tmpImage == null) return;\n        _tmpImage.Save(path);\n\n        PrintDocument doc = new PrintDocument { DocumentName = "Map printing file" };\n        doc.PrintPage += DocOnPrintPage;\n        PrintDialog dialog = new PrintDialog { Document = doc };\n        DialogResult result = dialog.ShowDialog();\n        if (result == DialogResult.OK) doc.Print();	0
16294858	16294344	Get values of dynamically created controls (comboboxes)	private void btnSaveFilter_Click(object sender, EventArgs e)\n{\n    foreach (Control control in panelFiltri.Controls)\n    {\n        if (control is ComboBox)\n        {\n            string valueInComboBox = control.Text;\n            // Do something with this value\n        }\n    }\n}	0
27494447	27478035	How can I modify a rotated transfom's position	transform.up * distance_to_move	0
8789980	8789908	WCF Service namespace colision, all in same solution	/namespace	0
6526496	6526242	Linq query to get a duplicate key once along with multiple values out of a dictionary	var a = selectedDrivers.GroupBy(a=>a.Value)\n            .Where(g=>g.Count() > 1)\n            .ToDictionary(g => g.Key, g => g.Select(a=>a.Key).ToList());	0
23792081	23785535	How can I show plus minus for nodes with children count in c# winform treeview	internal class EmptyTreeNode : TreeNode { }\n\nprivate void PopulateSubModes(...)\n{\n    // ...\n\n    if (hasChildren) node.Nodes.Add(new EmptyTreeNode());\n\n    // ...\n}\n\nprivate static void TreeView1OnBeforeExpand(object sender, TreeViewCancelEventArgs args)\n{\n    // If this isn't one of our special nodes... abort.\n    if (args.Node.Nodes.Count == 0 || !(args.Node.Nodes[0] is EmptyTreeNode))\n        return;\n\n    args.Node.Nodes.Clear();\n\n    // -- Do whatever to REALLY populate it\n    args.Node.Nodes.Add( new TreeNode( "Weeeeeeeee" ) );\n    args.Node.Nodes.Add( new TreeNode( "Hooooooah!" ) );\n}	0
5227442	5226987	How can I format text with borders and get it printed?	private bool Test(string pdf_file) \n    {\n        bool ret = false;\n        Document doc = new Document(PageSize.A4);\n\n        try\n        {\n            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdf_file, FileMode.Create));\n            doc.Open();\n\n            PdfPTable table = new PdfPTable(3);\n            PdfPCell cell = new PdfPCell(new Phrase("Header Column"));\n            cell.Colspan = 3;\n            cell.HorizontalAlignment = 1; \n            table.AddCell(cell);\n            table.AddCell("row1:col1");\n            table.AddCell("row1:col2");\n            table.AddCell("row1:col3");\n            doc.Add(table);\n\n            ret = true;\n        }\n        catch (DocumentException de)\n        {\n            MessageBox.Show(de.Message);\n        }\n        catch (IOException ioe)\n        {\n            MessageBox.Show(ioe.Message);\n        }\n\n        doc.Close();\n\n        if(ret)\n            MessageBox.Show("File has been created");\n\n        return ret;\n    }	0
8958253	8958234	How to check if a string can be obtained using another string's characters in c#?	int[] Count(string s) {\n    int[] res = new int[256];\n    foreach (var c in s) {\n        res[c]++;\n    }\n    return res;\n}\nint ShortInLong(string ss, string ls) {\n    var sc = Count(ss);\n    var lc = Count(ls);\n    int res = int.MaxValue;\n    foreach (var c in ss) {\n        int d = lc[c] / sc[c]; // sc[c] is never 0 because of the way we constructed it\n        res = Math.Min(res, d);\n    }\n    return res;\n}	0
8138866	8138734	disable all windows that are related with the current application	foreach (Form openedForm in Application.OpenForms) {\n    if (openedForm.GetType() == FormToClose) {\n        openedForm.Hide();\n    }\n}	0
23753168	23753052	Remove elements from an array in C#	arr = arr.Where(x => x != "").ToArray();	0
2136307	2136275	EF- How to do a 'Not In' using Linq to Entities	public static IQueryable<T> WhereNotIn<T, TValue>(\n    this IQueryable<T> query,\n    Expression<Func<T, TValue>> propertySelector,\n    IEnumerable<TValue> values)\n{\n    if (propertySelector == null)\n    {\n        throw new ArgumentNullException("propertySelector");\n    }\n\n    if (values == null || !values.Any())\n    {\n        return query.Where(i => true);\n    }\n\n    var param = propertySelector.Parameters.Single();\n    var unequals = values.Select(value => (Expression)Expression.NotEqual(propertySelector.Body, Expression.Constant(value, typeof(TValue))));\n    var body = unequals.Aggregate<Expression>((accumulate, unequal) => Expression.And(accumulate, unequal));\n    var lambda = Expression.Lambda<Func<T, bool>>(body, param);\n\n    return query.Where(lambda);\n}	0
12632176	12632059	Session timeout after period of inactivity	function logout() { \n    location.href = '/your/logout/page.aspx';\n}\n\nvar timeout = setTimeout(300000, logout);\nfunction resetTimeout() {\n    clearTimeout(timeout);\n    timeout = setTimeout(300000, logout);\n}\n\ndocument.onclick = resetTimeout;	0
6186220	6186166	Any chance of failing one query while using two queries in ExecuteScalar	Execute*	0
1731061	1731050	IEnumerable to array of parameter	string[] ids = query.Select(x => x.Value).ToArray();	0
7858192	7834450	SqlBulkCopy giving InvalidOperationException Error that I am inserting Null Values, but all values are non-null in the table	bulkCopy.DestinationTableName = this.Adapter.TableMappings[0].DataSetTable;\nfor (int i = 0; i < this.Adapter.TableMappings[0].ColumnMappings.Count; i++)\n    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(\n                this.Adapter.TableMappings[0].ColumnMappings[i].SourceColumn.ToString(),\n                this.Adapter.TableMappings[0].ColumnMappings[i].DataSetColumn.ToString()));\nbulkCopy.BatchSize = BatchSize;\n\n\nbulkCopy.WriteToServer(InsertTable);	0
11661017	11660760	Detect property selection in propertyGrid	private void propertyGrid1_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)\n    {\n        MessageBox.Show(e.NewSelection.Label);\n\n    }	0
32031812	32031754	Rearrange Table Data using Linq	from d in data\ngroup d by d.Date into g\nselect new {Date = g.Key, People = g.Select(gg=>new{Person = gg.Person, Hours = gg.Hours})}	0
21833116	21832965	How to distinguish between VS build and csc.exe build?	public bool IsDebugBuild\n{\n    get\n    {\n    #if DEBUG\n        return true;\n    #else\n        return false;\n    #endif\n    }\n}	0
13483028	13482975	Use a method in Regex.Replace()	var result = Regex.Replace(input, pattern, match => \n{\n    // $1 is equivalent to match.Groups[1].Value,\n    // so do whatever you want and return the value here\n});	0
11437919	11437661	Adding strings with special characters within in SQL Server database by C# ASP.NET application	command.CommandText = "insert into table (column) values(@p1)";\ncommand.Parameters.AddWithValue("p1", "email@address.com");	0
5349073	5349041	Printing in Winform Application	printForm1.Print();	0
5770934	5763784	Retrieve database structure in dataset	scmd=new SqlCommand("select * from AdminUser",scon);\n        scon.Open();\n\n    sdr = scmd.ExecuteReader(CommandBehavior.KeyInfo);\n    sdr.Read();\n    dt = sdr.GetSchemaTable();\n    scon.Close();	0
1068623	1068598	Event firing in WPF	e.Handled = true;	0
24871698	24834917	Snapping drawn rectangles to each other	var x = Math.Min(endPos.X, startPos.X);\n var y = Math.Min(endPos.Y, startPos.Y);\n\n var w = Math.Max(endPos.X, startPos.X) - x;\n var h = Math.Max(endPos.Y, startPos.Y) - y;	0
3832188	3831823	Rename an element using XPathNavigator	(XElement)(navigator.UnderlyingObject).Name = ...	0
9238149	9231803	One-or-nothing implementation in MEF container	[PartCreationPolicy(CreationPolicy.NonShared)]	0
26786411	26780444	Exception while using Regex with richtextbox in C#	private bool _updatingTextBox;\n\nprivate void myrichTextBox1_TextChanged(object sender, EventArgs e)\n{\n    if (_updatingTextBox)\n    {\n        return;\n    }\n\n    _updatingTextBox = true;\n\n    try\n    {\n       // all your updating code goes here\n    }\n    finally\n    {\n        _updatingTextBox = false;\n    }\n}	0
21236197	21235970	How to set inherited parent property for a Control Child on Code Behind	Canvas.SetLeft(btn, 30);\n...\nDragCanvas.SetCanBeDragged(btn,true);	0
23795352	23795327	Use loop to initialize multiple objects	Features = Enumerable.Range(1, 58)\n            .Select(x => new Feature(array[x - 1], x.ToString()))\n            .ToList()	0
5982827	5978879	How do I read MessageBox text using WinAPI	TCHAR text[51] = {0};\nHWND msgBox = ::FindWindow(NULL, TEXT("MessageBoxCaption"));\nHWND label = ::GetDlgItem(msgBox, 0xFFFF);\n::GetWindowText(label, text, sizeof(text)-1);	0
7420652	7420282	C#- editing excel chart data	chartRange = xlWorkSheet.get_Range("A1", "B" + dataGridView1.RowCount);	0
6167452	6167424	How to return part of folder name in C#	string folderName = "Fri 11.4.97"\nstring[] parts = folderName.Split(' ');\nstring lastPart = parts[parts.Length - 1];	0
16421045	16420921	Adding string to XML file without deleting existing string	el.SetElementValue("notes", el.value + " " + note);	0
18075275	18067755	How to take a screenshot of the iPhone/iPad programmatically with Xamarin.iOS (C#)?	UIScreen.MainScreen.Capture ();	0
21331246	21327343	Parsing result data of ZXING Barcode	// "result" is an instance of the barcode scanning result\nvar parsedResult = ResultParser.parseResult(result) as AddressBookParsedResult;\nif (parsedResult != null)\n{\n   // N value\n   var nValue = parsedResult.Names;\n   // ORG value\n   var orgValue = parsedResult.Org;\n   // do something with the values\n   ...\n}	0
1536598	1536508	WPF toolkit, change date format in DatePicker	CultureInfo.CurrentCulture	0
31550836	31550444	c# How to use the new Version Helper API	VersionHelpers.h	0
18482251	18482216	Delete Issue with stored procedure	cmdBestellDetailsDELETE.CommandType = CommandType.StoredProcedure;	0
1465687	1464797	How to receive message from a private workgroup queue	HKLM\SOFTWARE\Microsoft\n  \MSMQ\Parameters\Security\NewRemoteReadServerAllowNoneSecurityClient	0
2948356	2948255	XML file creation Using XDocument in C#	List<string> list = ...;\n\nXDocument doc =\n  new XDocument(\n    new XElement("file",\n      new XElement("name", new XAttribute("filename", "sample")),\n      new XElement("date", new XAttribute("modified", DateTime.Now)),\n      new XElement("info",\n        list.Select(x => new XElement("data", new XAttribute("value", x)))\n      )\n    )\n  );	0
25563767	25563610	Sort through a dictionary and concatenate values depending on keys	Dictionary<int, byte[]> results = new Dictionary<int, byte[]>();\n    foreach(var grp in data.OrderBy(pair => pair.Key)\n               .GroupBy(pair => (int)pair.Key, pair => pair.Value))\n    {\n        byte[] result;\n        if (grp.Count() == 1)\n        {\n            result = grp.Single();\n        }\n        else {\n            result = new byte[grp.Sum(arr => arr.Length)];\n            int offset = 0;\n            foreach(byte[] arr in grp)\n            {\n                Buffer.BlockCopy(arr, 0, result, offset, arr.Length);\n                offset += arr.Length;\n            }\n        }\n        results.Add(grp.Key, result);\n    }	0
6489892	6413267	Load a picturebox from a WIA ImageFile?	var imageBytes = (byte[])image.FileData.get_BinaryData(); \nvar ms = new MemoryStream(imageBytes);\nvar img = Image.FromStream(ms);	0
300689	300660	How to find the index of the first char in a string that is not in a list	public static char FindFirstNotAny(this string value, params char[] charset)\n{\n    return value.TrimStart(charset)[0];\n}	0
17670181	17669874	How to validate multiple phone number using regular expression	string regexPattern = @"^+46[0-9]{9}$";\n    Regex r = new Regex(regexPattern);\n\n    foreach(string s in numbers)\n    {\n        if (r.Match(s).Success)\n        {\n            Console.WriteLine("Match");\n        }\n    }	0
25305962	25305092	How to create a JSON string in c#/NETMF?	string json = JsonSerializer.SerializeObject(o, DateTimeFormat.Default);	0
28530838	28530671	Getting data from database to textbox?	string phone = (string)reader["telefonszam"].ToString();	0
5718577	5718473	c# ProcessStartInfo.Start - reading output but with a timeout	ProcessStartInfo processInfo = new ProcessStartInfo("Write500Lines.exe");\nprocessInfo.ErrorDialog = false;\nprocessInfo.UseShellExecute = false;\nprocessInfo.RedirectStandardOutput = true;\nprocessInfo.RedirectStandardError = true;\n\nProcess proc = Process.Start(processInfo);\n\n// You can pass any delegate that matches the appropriate \n// signature to ErrorDataReceived and OutputDataReceived\nproc.ErrorDataReceived += (sender, errorLine) => { if (errorLine.Data != null) Trace.WriteLine(errorLine.Data); };\nproc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) Trace.WriteLine(outputLine.Data); };\nproc.BeginErrorReadLine();\nproc.BeginOutputReadLine();\n\nproc.WaitForExit();	0
2954693	2954682	Default value for public properties	[DefaultValue]	0
15109823	15067300	Execute schtasks in a ASP site running on IIS	startInfo.UseShellExecute = false;\n            startInfo.WorkingDirectory = @"C:\Windows\System32";\n            startInfo.FileName = @"C:\Windows\System32\schtasks.exe";\n            startInfo.Arguments = "/create /tn <taskname> /tr <theEXE> /ru <user> /rp <password> /sc daily ";\n            startInfo.RedirectStandardError = true;\n            startInfo.RedirectStandardOutput = true;\n            startInfo.CreateNoWindow = false;\n            startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n            proc = Process.Start(startInfo);	0
10293575	10248704	Adding root certificate with CF 3.5	ProcessStartInfo psi = new ProcessStartInfo(appPath + "cert.cer", "");\npsi.UseShellExecute = true;\nProcess.Start(psi);	0
25988500	25988149	How to show all values that repeat in an array.	var numbers = new int[]{3, 5, 3, 6, 6, 6, 7};\nvar counterDic = new Dictionary<int,int>();\n    foreach(var num in numbers)\n    {\n        if (!counterDic.ContainsKey(num))\n{\n            counterDic[num] = 1;\n}\nelse \n{\n        counterDic[num] ++;\n}\n    }	0
11440613	11439893	Calling a SQL Server stored procedure with linq service through c#	var result = context.spSearchResults(Your list of parameters...);	0
4895555	4885085	What to use? Tao, SharpGL, OpenTK, DirectX P/Invoke, XNA, MDX, SlimDX, Windows API Codec Pack	private void Render()\n{\n   // Every frame\n   GL.MatrixMode(MatrixMode.Modelview);\n   GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);\n   GL.LoadMatrix(ref cameraMatrix);\n\n   GL.Begin(BeginMode.Points);\n\n   // Here I can add lots of points. I add 200k without any big problem.\n   // It seems these points could have been passed in as an array pointer too,\n   //  but I'll look at that later.\n   GL.Vertex3(x2, y2, z2);\n\n   GL.End();\n   glControl.SwapBuffers();\n}	0
19866701	19866523	Getting an XElement via XPathSelectElements	var xDoc = XDocument.Parse(@"<?xml version='1.0' encoding='utf-8'?>\n    <A1 xmlns='urn:sample'>\n        <B2>\n            <C3 id='1'>\n                <D7><E5 id='abc' /></D7>\n                <D4 id='1'><E5 id='abc' /></D4>\n                <D4 id='2'><E5 id='abc' /></D4>\n            </C3>\n        </B2>\n    </A1>");\n\n// Notice this\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());\nnsmgr.AddNamespace("sample", "urn:sample");\n\nstring xPath = "//sample:B2/sample:C3/sample:D4";\n\nvar eleList = xDoc.XPathSelectElements(xPath, nsmgr).ToList();\nforeach (var xElement in eleList)\n{\n    Console.WriteLine(xElement);\n}	0
24343941	24322278	Bullet Physics Convex hulls with cubes	// Create a ConvexTriangleMeshShape from the points\nconst int indexStride = 3 * sizeof(int);\nconst int vertexStride = 12;\nint vertexCount = points.Count;\nint indexCount = vertexCount / 3;\n\nTriangleIndexVertexArray vertexArray = new TriangleIndexVertexArray();\nIndexedMesh mesh = new IndexedMesh();\nmesh.Allocate(vertexCount, vertexStride, indexCount, indexStride);\nVector3Array vdata = mesh.Vertices;\nIntArray idata = mesh.TriangleIndices;\nfor (int i = 0; i < vertexCount; i++)\n{\n    vdata[i] = points[i];\n    idata[i] = i;\n}\nvertexArray.AddIndexedMesh(mesh);\nConvexTriangleMeshShape shape = new ConvexTriangleMeshShape(vertexArray, true);\n\n// Calculate center of mass\nMatrix center = Matrix.Identity;\nVector3 inertia;\nfloat volume;\nshape.CalculatePrincipalAxisTransform(ref center, out inertia, out volume);\n\n// Create a CompoundShape with COM offset\nCompoundShape compound = new CompoundShape();\ncompound.AddChildShape(Matrix.Invert(center), shape);	0
10830201	10830126	Copy 1 file content in another in c#	var doc = new HtmlWeb().Load(url);\nvar comments = doc.Descendants("div")\n                  .Where(div => div.GetAttributeValue("class", "") == "comment");	0
769573	769529	How do I convert a "Keys" enum value to an "int" character in C#?	int value = -1;\nif(e.KeyValue >= ((int)Keys.NumPad0) && e.KeyValue <= ((int)Keys.NumPad9)){ // numpad\n    value = e.KeyValue - ((int)Keys.NumPad0);\n}else if(e.KeyValue >= ((int)Keys.D0) && e.KeyValue <= ((int)Keys.D9)){ // regular numbers\n    value = e.KeyValue - ((int)Keys.D0);\n}	0
9653117	9653112	How to: Create a Key In the Registry (Visual C#)?	Microsoft.Win32.RegistryKey key;\nkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");\nkey.SetValue("Name", "Isabella");\nkey.Close();	0
11279987	11279852	Valid div identiier names ASP.NET	runat="SERVER"	0
28689137	28688992	Convert C# DateTime into GregorianCalendar date	Calendar.set(Calendar.MILLISECOND, value);	0
15553073	15552810	Using a Non-Const String as a CategoryAttribute Name	MessageResourceType = typeof (MyResource), MessageResourceName = "MyResourceKey")	0
94151	93811	WinForm - draw resizing frame using a single-pixel border	Point lastPoint = Point.Empty;\nPanel leftResizer = new Panel();\nleftResizer.Cursor = System.Windows.Forms.Cursors.SizeWE;\nleftResizer.Dock = System.Windows.Forms.DockStyle.Left;\nleftResizer.Size = new System.Drawing.Size(1, 100);\nleftResizer.MouseDown += delegate(object sender, MouseEventArgs e) { \n  lastPoint = leftResizer.PointToScreen(e.Location); \n  leftResizer.Capture = true;\n}\nleftResizer.MouseMove += delegate(object sender, MouseEventArgs e) {\n  if (lastPoint != Point.Empty) {\n    Point newPoint = leftResizer.PointToScreen(e.Location);\n    Location = new Point(Location.X + (newPoint.X - lastPoint.X), Location.Y);\n    Width = Math.Max(MinimumSize.Width, Width - (newPoint.X - lastPoint.X));\n    lastPoint = newPoint;\n  }\n}\nleftResizer.MouseUp += delegate (object sender, MouseEventArgs e) { \n  lastPoint = Point.Empty;\n  leftResizer.Capture = false;\n}\n\nform.BorderStyle = BorderStyle.None;\nform.Add(leftResizer);	0
24351269	24351104	Losing spaces when parsing XML with HTML tags to CSV	var XML =\n    "<Doc><Description><![CDATA[<p><strong>Nokia</strong> connecting people</p>]]></Description></Doc>";\nXmlReader reader = XmlReader.Create(new StringReader(XML));\n\nstring description ="";\n\n\nwhile (reader.Read())\n{\n    if (reader.Name == "Description")\n    {\n        while (reader.NodeType != XmlNodeType.EndElement)\n        {\n            reader.Read();\n            if (reader.NodeType == XmlNodeType.CDATA)\n                description = reader.Value;\n        }\n    }\n}\n\n\nConsole.Write(description);	0
16339001	16335736	Tinyint as byte nhibernate	session.CreateQuery("from Foo where TinyIntColumn = :b").SetParameter("b", 1)\nsession.QueryOver<Foo>().Where(x => x.TinyIntColumn == 1)\nsession.Query<Foo>().Where(x => x.TinyIntColumn == 1)	0
407748	407729	Determine if a sequence contains all elements of another sequence using Linq	bool contained = !subset.Except(superset).Any();	0
400534	400522	Matching version number parts with regular expressions	(?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?	0
10708286	10708132	Dynamic tooltip depending on mouse over on a row in a datagrid(NOT datagridview)	private void dataGrid_MouseMove(object sender, MouseEventArgs e) {\n var point = dataGrid.PointToClient(e.X, e.Y);\n var hittest = dataGrid.HitTest(point.X, point.Y);\n toolTip1.SetToolTip(dataGrid, hittest.Row); // add Tooltip conotrol to the form!!!\n}	0
11179646	11179588	How can I determine which port will be assigned to a client?	var servicePoint=ServicePointManager.FindServicePoint(myServiceUri);\nservicePoint.BindIPEndPointDelegate = (sp, remoteEndPoint, retryCount) =>\n    new IPEndPoint(localEndpointDetailsGoHere)	0
14323303	14323192	Convert a sql query with a subquery into a linq statement	from ahf in db.ACCOUNT_HISTORY_FACT\nwhere ahf.ACCOUNT_LEVEL == 1 &&\n      ahf.TOP_ACCOUNT_KEY == db.ACCOUNT_HISTORY_FACT\n                               .Where(x => x.account_hcc_id == "3362") \n                               .Select(x => x.TOP_ACCOUNT_KEY)\n                               .FirstOrDefault() \nselect new { ahf.account_hcc_id, ahf.account_name };	0
2261485	2261427	Accessing a property in a Datagrid in C#	dataGridView1.CurrentRow.Cells["ID"].Value	0
542755	542690	Need a custom currency format to use with String.Format	string.Format("{0:$#,##0.00;($#,##0.00);''}", value)	0
15663084	15660781	Get iOS screen resolution without UI in MonoTouch	bool check_ui = UIApplication.CheckForIllegalCrossThreadCalls;\nUIApplication.CheckForIllegalCrossThreadCall = false;\nvar screen_bounds = UIScreen.MainScreen.Bounds;\nUIApplication.CheckForIllegalCrossThreadCalls = check_ui;	0
25258375	25258075	How to Filter Datatable or Dataview with common Rows	DataTable dt = new DataTable();\n        DataView dv = new DataView(dt, string.Format("InvoiceNumber='{0}'", 1),"",DataViewRowState.CurrentRows);\n        dt = dv.ToTable();	0
27066572	27066328	How to set the model in a viewmodel (MVVM)	MyViewModel viewmodel = new MyViewModel(this);\nvar app = new System.Windows.Application();\napp.Run(new ApplicationShellView(viewmodel));	0
2038149	2038104	Parsing HTML to get content using C#	string html;\n// obtain some arbitrary html....\nusing (var client = new WebClient()) {\n    html = client.DownloadString("http://stackoverflow.com/questions/2038104");\n}\n// use the html agility pack: http://www.codeplex.com/htmlagilitypack\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(html);\nStringBuilder sb = new StringBuilder();\nforeach (HtmlTextNode node in doc.DocumentNode.SelectNodes("//text()")) {\n    sb.AppendLine(node.Text);\n}\nstring final = sb.ToString();	0
16996731	16651616	PreviewKeyDown for Windows Store App ListBox	public MainPage()\n{\n    this.InitializeComponent();\n    Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += (s, args) =>\n    {\n        if ((args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown \n            || args.EventType == CoreAcceleratorKeyEventType.KeyDown)\n            && (args.VirtualKey == VirtualKey.Up))\n        {\n            MoveUp();\n        }\n        else if ((args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown \n            || args.EventType == CoreAcceleratorKeyEventType.KeyDown)\n            && (args.VirtualKey == VirtualKey.Down))\n        {\n            MoveDown();\n        }\n    };\n}\n\nprivate void MoveUp()\n{\n    // this part is up to you\n    throw new NotImplementedException();\n}\n\nprivate void MoveDown()\n{\n    // this part is up to you\n    throw new NotImplementedException();\n}	0
16454508	16442497	How to get Generated Html form HtmlGenericControl	// create you generic controls\nHtmlGenericControl mainDiv = new HtmlGenericControl("div");\n// setting required attributes and properties\n// adding more generic controls to it\n// finally, get the html when its ready\nStringBuilder generatedHtml = new StringBuilder();\nusing (var htmlStringWriter = new StringWriter(generatedHtml))\n{\n    using(var htmlTextWriter = new HtmlTextWriter(htmlStringWriter))\n    {\n        mainDiv.RenderControl(htmlTextWriter);\n        output = generatedHtml.ToString();       \n    }\n}	0
31893618	31893237	How to combine mulitiple LINQ to objects requests into single one	return\n  Auctions.List().ToList()  //--> ToList() not needed here?\n  .Where\n  ( a =>\n    AuctionIsLive(a) ||\n    AuctionIsOpen(a) ||\n    a.StartDate >= DateTime.UtcNow\n  )\n  .OrderBy\n  ( a => \n    AuctionIsLive( a ) ? 0 :\n    AuctionIsOpen( a ) ? 1 : 2\n  )\n  .ThenBy( a => a.StartDate )\n  .FirstOrDefaut();	0
2672746	2672259	extend web server to serve static files	return Convert.ToBase64String(File.ReadAllBytes(path));	0
1943755	1943531	How to create a relationship between ASP.Net MembershipServices user and other tables?	object key = Membership.GetUser().ProviderUserKey;\ncustomization.UserId = (Guid)key;	0
33871901	33871791	Calling a function dynamically based on an integer value	void Main()\n{\n    Dictionary<int, Func<bool>> funcMap = new Dictionary<int, Func<bool>>() {\n        {1, Function1},\n        {2, Function2}\n    };\n\n\n    Console.WriteLine(funcMap[1]());\n    Console.WriteLine(funcMap[2]());\n}\n\n// Define other methods and classes here\n\n\nbool Function1()\n{\n    return true;\n}\n\nbool Function2()\n{\n    return false;\n}	0
27726441	27726365	C# - Check file size while writing - Change file in middle	if (myPaths.Length >= 60000)\n        {\n            myStream.Close();\n            outFile = "c:\\dirA\\GS_dirData_" + (FileCounter += 1).ToString() + ".txt";\n            myStream = new StreamWriter(outFile);\n        }	0
1947873	1947855	Need regex (using C#) to condense all whitepace into single whitespaces	RegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@"\s+", options);     \ntempo = regex.Replace(tempo, @" ");	0
5888727	5888708	Get filename of current configuration file	AppDomain.CurrentDomain.SetupInformation.ConfigurationFile	0
9983578	9973240	How can I create multistyled cell with EPPlus library for Excel	FileInfo fi = new FileInfo(@"c:\Book1.xlsx");\n\n      using (ExcelPackage package = new ExcelPackage(fi))\n      {\n        // add a new worksheet to the empty workbook\n        ExcelWorksheet worksheet = package.Workbook.Worksheets["Inv"];\n        //Add the headers\n\n        worksheet.Cells[2, 1].IsRichText = true;\n        ExcelRichText ert = worksheet.Cells[2, 1].RichText.Add("bugaga");\n        ert.Bold = true;\n        ert.Color = System.Drawing.Color.Red;\n        ert.Italic = true;\n\n        ert = worksheet.Cells[2, 1].RichText.Add("alohaaaaa");\n        ert.Bold = true;\n        ert.Color = System.Drawing.Color.Purple;\n        ert.Italic = true;\n\n        ert = worksheet.Cells[2, 1].RichText.Add("mm");\n        ert.Color = System.Drawing.Color.Peru;\n        ert.Italic = false;\n        ert.Bold = false;\n\n\n        package.Save();\n      }	0
31814704	31814617	Csharp substring text and add it to list	using(var sr = new StreamReader(path))\n{\n    var folders = sr.ReadToEnd()\n    .Split(new char[]{';','\n','\r'}, StringSplitOptions.RemoveEmptyEntries)\n    .Select(o => o.Replace("folder=",""))\n    .ToArray();\n    Folders.AddRange(folders);\n}	0
14661389	14661294	SQL Server Date Conversion from String	SqlConnection cn;\nSqlCommand cmd;\nSqlDataAdapter da;\n\nint n=4;\nprotected void Page_Load(object sender, EventArgs e)\n{\ncn = new SqlConnection(<Connection String>);\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    try\n    {\n      string query = "insert into temp values(@date))";\n      cn.Open();\n      cmd = new SqlCommand(query, cn);\n      cmd.Parameters.AddWithValue("@date",Convert.DateTime(TextBox1.Text));\n      cmd.ExecuteNonQuery();\n      cn.Close();\n      Response.Write("Record inserted successfully");\n    }\n    catch (Exception ex)\n    {\n     Response.Write(ex.Message);\n    }\n\n}	0
8858704	8858683	Get a DateTime by subtracting seconds from the current date	DateTime.Now.AddSeconds(-1300);	0
5675691	5621311	Compare column against valid values	var noSubject =\n  ds.Student.AsEnumerable().Where(s => ds.Subject.Rows.Find(s.Subject) == null);	0
2014371	2014364	How do I limit the number of elements iterated over in a foreach loop?	foreach(var rssItem in rss.Channel.Items.Take(6))	0
33302619	33302482	Combining ViewModels and Partial Views	public ActionResult Index(Combined model)\n{\n   var q = _ctx.tblNews.OrderByDescending(x => x.newsCreateDate)\n   .Where(x => x.WebsiteID == 2 && x.newsPublish).ToList();\n\n   model.NewsList = new List<NewsList>(); // "new it up"\n\n   foreach (var n in q)\n   {\n       model.NewsList.Add(new NewsList\n           {\n               NewsId = n.newsID,\n               NewsTitle = n.newsTitle,\n               NewsStandFirst = n.newsStandFirst,\n               NewsCreateDate = n.newsCreateDate\n           }\n       );\n    }\n    return View(model);\n}	0
11202113	11201361	How to open a new tab/window on clicking on ItemTemplate asp:Image Button with Query String?	protected void ibtmImage_Command(object sender, CommandEventArgs e)\n{\n     string strJS = ("<script type='text/javascript'>window.open('ItemList.aspx?Id=" + e.CommandArgument.ToString() + "','_blank');</script>");\n     Page.ClientScript.RegisterStartupScript(this.GetType(), "strJSAlert", strJS);\n}	0
26594912	26594618	How to check that a dictionary / collection can be iterated over?	Dictionary.Count	0
6748534	6748447	Return distinct values dynamically	List<object> test = (from x in BusinessObjectCollection select x.GetType().GetProperty ("thePropertyName").GetGetMethod().Invoke(x,null)).Distinct().ToList();	0
24511268	24509852	BackgroundMediaPlayer set Uri source of Media library item	StorageFile file = (await KnownFolders.MusicLibrary.GetFilesAsync()).FirstOrDefault();\nBackgroundMediaPlayer.Current.SetUriSource(new Uri(file.Path, UriKind.RelativeOrAbsolute));	0
27594948	27556457	How to attach a LineObj y value to a specific Y axis?	//reference to the graph to draw on\nGraphPane oPane = ZedGraph.MasterPane[0];\n\ndouble fMinX = 0;\ndouble fMaxX = 100;\ndouble fYvalue = 42;\n\n//values for the point pair list to define the horizontal line\nvar oPPL = new PointPairList();\noPPL.Add(fMinX, fYvalue);\noPPL.Add(fMaxX, fYvalue);\n\n//draw the line as a curve object, then format....\nvar oPoints = oPane.AddCurve(string.Empty, oPPL, Color.Red, SymbolType.None);\noPoints.Line.IsVisible = true;\noPoints.Line.Style = System.Drawing.Drawing2D.DashStyle.Dash;\noPoints.Line.Width = 3F;\noPoints.Symbol.IsVisible = false;\n\n//and hang on to the curve object so you can move the line around as needed\n            oPoints.Clear();\n            oPoints.AddPoint(blah blah blah...	0
6324823	6324811	Returned integer using number of value c#	return (coin() == 'heads' ? g1 : g2);	0
8698260	8697666	Need the sequence Order of Quarters of FY2011-12 based on a date given as input	public string GetQuarter(DateTime date)\n{\n   // we just need to check the month irrespective of the other parts(year, day)\n   // so we will have all the dates with year part common\n   DateTime dummyDate = new DateTime(1900, date.Month, date.Day);\n\n   if (dummyDate < new DateTime(1900, 7, 1) && dummyDate >= new DateTime(1900, 4, 1))\n   {\n      return "Q1";\n   }\n   else if (dummyDate < new DateTime(1900, 10, 1) && dummyDate >= new DateTime(1900, 7, 1))\n   {\n       return "Q2";\n   }\n   else if (dummyDate < new DateTime(1900, 1, 1) && dummyDate >= new DateTime(1900, 10, 1))\n   {\n       return "Q3";\n   }\n   else\n   {\n       return "Q4";\n   }\n}	0
26206302	26206288	Entity to json error - A circular reference was detected	db.Configuration.ProxyCreationEnabled = false;\n  User ma = db.user.First(x => x.u_id == id);\n  return Json(ma, JsonRequestBehavior.AllowGet);	0
5292865	5291094	Parsing large xml files to add new line between elements really slow	using (var streamOut = new StreamWriter(outputFileName)\n{\n  using (var streamIn = new StreamReader(inputFileName)\n  {\n     while (!streamIn.EndOfStream)\n     {\n        string line = streamIn.ReadLine();\n        line = line.Replace("AddNewLine", "\n\r\n");\n        streamOut.WriteLine(line);\n     }\n  }\n}	0
13632681	13632573	regex that only accepts numbers 2 and up	int enteredValue;\n\nif(Int32.TryParse(TextBox1.Text, out enteredValue))\n{\n    if(enteredValue >= 2 )\n    {\n       //....\n    }\n}	0
19682955	19682304	In a WinForms menu is there a way to batch update	Stopwatch sw = new Stopwatch();\nsw.Start();\n\nvar items = new ToolStripItem[menuStrip1.Items.Count];\nmenuStrip1.Items.CopyTo(items, 0);\n\nvar itemList = new List<ToolStripItem>(items);\n\nfor (int i = 0; i < 1000; i++)\n    itemList.Insert(2, new ToolStripMenuItem { Text = "Hello" + i.ToString() });\n\nmenuStrip1.Items.Clear();\nmenuStrip1.Items.AddRange(itemList.ToArray());\n\nsw.Stop();\nlabel1.Text = sw.ElapsedMilliseconds.ToString();	0
34263965	34263910	App not closing MySql connection properly	using(MySqlConnection conn = new MySqlConnetion(local_connection_string)\n{\n    conn.open();\n    MySqlCommand query = new MySqlCommand(\n                "here some mysql command"\n                , connect);\n            query.ExecuteNonQuery();\n\n}	0
23974321	23974302	Get the next number in a list of numbers using LINQ	double result = mylist.SkipWhile(n => n != 8).Skip(1).First();	0
18619972	18618569	Select datetime column from SQL Server 2008 R2 table	SET DATEFORMAT	0
7958477	7875666	EF. Required validation error for string fields raise without [Required] attribute	[Required(AllowEmptyString=true)]	0
8083244	8083159	datagrid not getting displayed	SqlCommand command = new SqlCommand();\ncommand.CommandText = "SELECT * FROM Product WHERE Product.ID=@PROD_ID";\ncommand.Parameters.Add(new SqlParameter("@PROD_ID", 100));\n\n// Execute the SQL Server command...\nSqlDataReader reader = command.ExecuteReader();\nDataTable tblProducts = new DataTable();\ntblProducts.Load(reader);\n\nforeach (DataRow rowProduct in tblProducts.Rows)\n{\n    // Use the data...\n}	0
28176889	28176133	How I run On Group And Calc	int numberOfNewMessage = msgs.GroupBy(m => m.ChatMateId)\n                             .Count(m => m.Any(x => !x.read));	0
30100343	30099613	Dynamically add roles to authorize attribute for controller	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\npublic class MyCustomAuthorizationAttribute : AuthorizeAttribute\n{\n    protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        // Do some logic here to pull authorised roles from backing store (AppSettings, MSSQL, MySQL, MongoDB etc)\n        ...\n        // Check that the user belongs to one or more of these roles \n        bool isUserAuthorized = ....;\n\n        if(isUserAuthorized) \n            return true;\n\n        return base.AuthorizeCore(httpContext);\n    }\n}	0
10154526	10152833	Approach for primary key generation	create table YourTableName(\n   pkID int not null identity primary key,\n   ... the rest of the columns declared next.\n)	0
2380958	2380946	Calculate total content length of HttpFileCollection using Lambda expressions	int totalLength = files.AllKeys.Select(k => files[k]).Sum(f => f.ContentLength);	0
9477904	9477602	How to Crop Image without changing the aspect ratio	public void Crop(Bitmap bm, int cropX, int cropY,int cropWidth,int cropHeight)\n {\n       var rect = new System.Drawing.Rectangle(cropX,cropY,cropWidth,cropHeight);\n\n       Bitmap newBm = bm.Clone(rect, bm.PixelFormat);\n\n       newBm.Save("image2.jpg");\n }	0
16425995	16423922	How to do custom paging with EntitySetController	public class MyController : EntitySetController<Poco, int>\n{\n    public IQueryable<Poco> Get()\n    {\n        var result = _myBusinessLogic.Search(QueryOptions.Top.Value);\n        RemoveQueryString(Request, "$top");\n        return result.AsQueryable()\n    }    \n\n    // This method relies that code that looks for query strings uses the extension\n    // method Request.GetQueryNameValuePairs that relies on cached implementation to \n    // not parse request uri again and again.\n    public static void RemoveQueryString(HttpRequestMessage request, string name)\n    {\n        request.Properties[HttpPropertyKeys.RequestQueryNameValuePairsKey] = request.GetQueryNameValuePairs().Where(kvp => kvp.Key != name);\n    }\n}	0
34556450	34556183	Implement Pagination On frequently changing Table Data	public IQueryable<ChatMessage> GetChatMessage(int pageSize, int ownerUserId, int friendUserId, DateTime oldestMessageDate)\n{\n   var query = this.GetQueryable().\n              Where(x => ((x.Sender.Identifier == ownerUserId && x.Receiver.Identifier == friendUserId) \n                     || (x.Sender.Identifier == friendUserId && x.Receiver.Identifier == ownerUserId)) \n                     && x.MessageTime < oldestMessageDate); \n    //query now has all the messages older than messages shown to the user\n\n    query = query.OrderByDescending(x => x.Identifier).Take(PageSize);\n    return query;\n}	0
5992689	5949735	How can I pass command-line arguments in IronPython?	engine.Sys.argv = List.Make(args);	0
12043640	12043608	how do i catch an exception in if Statement?	try {\n\n   operationThatThrowsException();\n\n} catch(Exception e) {\n   //You will be here if the exception was thrown.\n}	0
4503178	4503024	Assign multiple values to enum elements	public Country GetCountryByTaxID(int taxID)\n        {\n            if (taxID == 3 || taxID == 4)\n            {\n                return Country.USA;\n            }\n            else \n            {\n                return Country.Canada;\n            }\n        }	0
22538657	22538494	Creating Dictionary<string, Dictionary<T, T[]>[]>	Dictionary<string, string[]>	0
6574925	6573785	Determining the correct data type from a name	public enum FieldDataTypes \n{\n    [FormTypeMetadata(typeof(string))]\n    PlainText = 0, \n    [FormTypeMetadata(typeof(int))]\n    Number = 1,\n    [FormTypeMetadata(typeof(decimal))]\n    Currency = 2\n}\n\npublic class FormTypeMetadataAttribute : Attribute\n{\n    private readonly Type _baseType = typeof(object);\n    public FormTypeMetadataAttribute(Type baseType)\n    {\n        if (baseType == null) throw new ArgumentNullException("baseType");\n        _baseType = baseType;\n    }\n\n    public Type BaseType { get { return _baseType; } }\n}\n\n// your 'FieldData' implementation would look like this...\n\npublic class FieldData\n{\n    public FieldDataTypes FieldType { get; set; }\n\n    public object Value { get; set; }\n}	0
3633158	3632422	How to change location of app.config	int Main(string[] args)\n{\n   string currentExecutable = Assembly.GetExecutingAssembly().Location;\n\n   bool inChild = false;\n   List<string> xargs = new List<string>();\n   foreach (string arg in xargs)\n   {\n      if (arg.Equals("-child"))\n      {\n         inChild = true;\n      }\n      /* Parse other command line arguments */\n      else\n      {\n         xargs.Add(arg);\n      }\n   }\n\n   if (!inChild)\n   {\n      AppDomainSetup info = new AppDomainSetup();\n      info.ConfigurationFile = /* Path to desired App.Config File */;\n      Evidence evidence = AppDomain.CurrentDomain.Evidence;\n      AppDomain domain = AppDomain.CreateDomain(friendlyName, evidence, info);\n\n      xargs.Add("-child"); // Prevent recursion\n\n      return domain.ExecuteAssembly(currentExecutable, evidence, xargs.ToArray());\n   }\n\n   // Execute actual Main-Code, we are in the child domain with the custom app.config\n\n   return 0;\n}	0
9830745	9830681	sort datatable by a field	var view = new DataView(dt) { Sort = "id" };	0
5346241	5346194	how to use string.join to join value from an object array?	string.Join(",",objs.Select(w=>w.stringValue))	0
4876403	3681236	Calculate whether one coordinate is within range of another	var distance = coordinateA.GetDistanceTo(coordinateB);	0
8027306	8026705	Open xml getting images from .pptx file	SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId);\n\n                    Slide slide = slidePart.Slide;\n                    ImagePart imagePart = (ImagePart)slide.SlidePart.GetPartById("rId3");\n                    System.Drawing.Image img = System.Drawing.Image.FromStream(imagePart.GetStream());	0
6422086	6422047	Parse a list to a string	string msg = string.Join("\n", layoutListNames);	0
11001781	10231134	Local RDLC Report showing '#Error' where report parameters should be displayed	Warning[] warnings;\n        string mimeType;\n        string[] streamids;\n        string encoding;\n        string filenameExtension;\n\n        var viewer = new ReportViewer();\n        viewer.ProcessingMode = ProcessingMode.Local;\n\n        viewer.LocalReport.ReportPath = @"Labels\ShippingLabel.rdlc";\n        viewer.LocalReport.EnableExternalImages = true;\n\n        var shipLabel = new ShippingLabel { ShipmentId = shipment.ShipmentId, Barcode = GetBarcode(shipment.ShipmentId) };\n\n        viewer.LocalReport.DataSources.Add(new ReportDataSource("ShippingLabel", new List<ShippingLabel> { shipLabel }));\n        viewer.LocalReport.Refresh();\n\n        var bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);	0
34057618	34056293	Issues with displaying images on buttons with xaml	x:Shared="False"	0
125611	125610	How can I hyperlink to a file that is not in my Web Application?	/virtdirect/somefolder/	0
20247737	20244595	Convert a string to a bitmap in c#	List<string> splitBytes = new List<string>();\nstring byteString = "";\nforeach (var chr in rsstring)\n        {\n            byteString += chr;\n\n            if (byteString.Length == 3)\n            {\n                splitBytes.Add(byteString);\n                byteString = "";\n            }\n        }\n\n        var pixelCount = splitBytes.Count / 3;\n        var numRows = pixelCount / 4;\n        var numCols = pixelCount / 4;\n\n        System.Drawing.Bitmap map = new System.Drawing.Bitmap(numRows, numCols);\n\n        var curPixel = 0;\n        for (int y = 0; y < numCols; y++)\n        {\n            for (int x = 0; x < numRows; x++ )\n            {\n                map.SetPixel(x, y, System.Drawing.Color.FromArgb(\n                    Convert.ToInt32(splitBytes[curPixel * 3]),\n                    Convert.ToInt32(splitBytes[curPixel * 3 + 1]),\n                    Convert.ToInt32(splitBytes[curPixel * 3 + 2])));\n\n                curPixel++;\n            }\n        }\n        //Do something with image	0
20548356	20548039	Retrieve Column By Header Name	var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0; HDR=YES", fileName);\n\n        var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);\n        var ds = new DataSet();\n\n        adapter.Fill(ds, "mySheet");\n        var data = ds.Tables["mySheet"].AsEnumerable();\n\n        foreach (DataRow dataRow in data)\n        {\n            Console.WriteLine(dataRow["MyColumnName"].ToString());    \n            Console.WriteLine(dataRow.Field<string>("MyColumnName").ToString());\n        }	0
33948001	33947887	Fetch Data from database to Fullcalendar.io using Json	public JsonResult GetEvents()\n{\n    using (var db = new MyDatabaseEntities())\n    {\n        var events = from cevent in db.EventTables\n                     select cevent;\n        var rows = events.ToList().Select(cevent => new {\n                         id = cevent.Id,\n                         start = cevent.Start_Time.AddSeconds(1).ToString("yyyy-MM-ddTHH:mm:ssZ"),\n                         end = cevent.End_Time.ToString("yyyy-MM-ddTHH:mm:ssZ")\n                     }).ToArray();\n        return Json(rows, JsonRequestBehavior.AllowGet);\n    }            \n}	0
7741904	7741778	How do I write one method to handle all permutations of an advanced search feature in ASP.NET?	var query = dc.MyTable; // Base query here\nif (Field1.Text != "") // Filter Field1\n    query = query.Where(x => x.Field1 == Field1.Text);\n\nif (Field2.Text != "") // Filter Field2\n    query = query.Where(x => x.Field2 == Field2.Text);\n\ngrid.DataSource = query;	0
19632156	19631680	Rendering a UserControl in code rather than XAML	var width = VideoContainer.ActualWidth;\nvar height = VideoContainer.ActualHeight;\n\nvfoc.Measure(new Size(width, height));\nvfoc.Arrange(new Rect(0, 0, width, height));\nvfoc.InvalidateVisual();	0
16182394	16182355	How to sum a field grouped by another in LINQ?	from d in dataset\ngroup d by new { d.RecipeName } into g\nselect new {\n     g.Key.RecipeName,\n     ReceiptWeight = g.sum(o => o.ReceiptWeight)\n}	0
3445828	3445811	Compare two ArrayList Contents using c#	var copyOfExisting = new ArrayList( ExistingProcess );\n    var copyOfCurrent = new ArrayList( CurrentProcess );\n\n    foreach( var p in ExistingProcess ) copyOfCurrent.Remove( p );\n    foreach( var p in CurrentProcess ) copyOfExisting.Remove( p );	0
12652365	10407769	Directly sending keystrokes to another process via hooking	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nnamespace keybound\n{\nclass WindowHook\n{\n    [DllImport("user32.dll")]\n    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n    [DllImport("user32.dll")]\n    public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n    [DllImport("user32.dll")]\n    public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\n    public static void sendKeystroke(ushort k)\n    {\n        const uint WM_KEYDOWN = 0x100;\n        const uint WM_SYSCOMMAND = 0x018;\n        const uint SC_CLOSE = 0x053;\n\n        IntPtr WindowToFind = FindWindow(null, "Untitled1 - Notepad++");\n\n        IntPtr result3 = SendMessage(WindowToFind, WM_KEYDOWN, ((IntPtr)k), (IntPtr)0);\n        //IntPtr result3 = SendMessage(WindowToFind, WM_KEYUP, ((IntPtr)c), (IntPtr)0);\n    }\n}\n}	0
31005037	31003594	How to hide Shut Down and Log Off through commandline(script) without reboot	GPUpdate /force	0
19681793	19681715	changing text of button with timeout in c#	Timer t = new Timer(5000); // Set up the timer to trigger on 5 seconds\nt.SynchronizingObject = this; // Set the timer event to run on the same thread as the current class, i.e. the UI\nt.AutoReset = false; // Only execute the event once\nt.Elapsed += new ElapsedEventHandler(t_Elapsed); // Add an event handler to the timer\nt.Enabled = true; // Starts the timer\n\n// Once 5 seconds has elapsed, your method will be called\nvoid t_Elapsed(object sender, ElapsedEventArgs e)\n{\n    // The Timer class automatically runs this on the UI thread\n    button1.Text = "Start";\n}	0
20559441	20559108	Extract values from Ajax call with XML type in ASP.NET	Request.Form["type"]	0
18033362	18033349	Applying a percentage operation on a decimal type	decimal result = (val1 + val2 + val3 + val4 + val5 + val6 + val7) * 0.6M; // <- 0.6M is Decimal, not Double	0
27073403	27072552	Get properties of underlying interface in c#	static void Main(string[] args)\n        {\n            ClassA a = new ClassA();\n            IterateInterfaceProperties(a.GetType());\n            Console.ReadLine();\n        }\n\n    private static void IterateInterfaceProperties(Type type)\n    {\n        foreach (var face in type.GetInterfaces())\n        {\n            foreach (PropertyInfo prop in face.GetProperties())\n            {\n                Console.WriteLine("{0}:: {1} [{2}]", face.Name, prop.Name, prop.PropertyType);\n            }\n        }\n    }	0
3238810	3238728	Using items from List<string> in SQL query	StringBuilder partNumbers = new StringBuilder();\nforeach (string queryValue in ImportedParts)\n{\n    string q = "PartNumber LIKE '%" + queryValue + "%'";\n    if (string.IsNullOrEmpty(partNumbers.ToString())\n    {\n       partNumbers.Append(q);\n    }\n    else\n    {\n       partNumbers.Append(" OR " + q);\n    }\n}\n\nstring query = string.Format("SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') " +\n           "AND (FilePath NOT LIKE '%js91162%') AND ({0}) " +\n           "ORDER BY CreatedOn DESC;", partNumbers.ToString());	0
10973897	10973889	Is there a C# idiom to create then add to a collection?	private readonly List<myClass> myCollection = new List<myCollection>();	0
18220222	18218443	How to retrieve Oracle Clob more than 4000 characters ODP.NET	using (OracleConnection oConn = new OracleConnection())\n{\n  oConn.ConnectionString = pConnstr;\n  oConn.Open();\n  using (OracleCommand oCmd = new OracleCommand("select varchar_column, clob_column from test", oConn))\n  {\n    oCmd.InitialLOBFetchSize = -1;\n    string key, value;\n    var rd = oCmd.ExecuteReader();\n    while (rd.Read())\n    {\n      if (rd.IsDBNull(1)) { value = ""; }\n      else\n      {\n        key = rd.GetValue(0).ToString();\n        value = rd.GetValue(1).ToString(); \n      }\n    }\n  }\n}	0
34218735	34217825	White tests - folder browser dialog	var wrapper = new WindowWrapper(this);\n\n dialog.ShowDialog(wrapper)	0
30645079	30645021	Distinct items in List	List<string> lst = new List<string>();\nstring item;\n\nfor (i=2; i<2001; i++)\n{\n    item = ws.cells[i,3];\n    if(!lst.Contains(item))\n    {\n        lst.Add(item);\n    }\n}	0
17873811	17873730	How to trigger radio button's event handler programmatically?	public Form1()\n{\n   InitializeComponent();\n   calculator = new Calculator();\n\n   maleRadio_CheckedChanged(maleRadio, null);\n   englishRadio_CheckedChanged(englishRadio, null);\n}	0
22877288	22877231	how to parse a markup element?	var str = "<University id=\"1396677467961079\" name=\"Oxford\"/>";\nvar el = XElement.Parse(str);\nvar attr = el.Attribute("id");\nvar id = attr != null ? attr.Value : string.Empty;	0
20441166	20441069	how to use MarshalByRefObject to call class in different app domain	var newSearch = (diffDomain)domain.CreateInstanceAndUnwrap(\n                            typeof(diffDomain).Assembly.FullName,\n                            typeof(diffDomain).FullName);	0
12428823	12428797	How do I bind a dataset to a drop down box starting at the second index of the drop down box?	//...\nddlSourceDatabases.DataBind();\nddlSourceDatabases.Items.Insert(0, "Select Source Database");\n//...	0
24848937	24846745	WPF How to always select the 2nd column of selected row	//handle the SelectionChanged event\nprivate void dgvConfig_SelectionChanged(object sender, \n                                        SelectionChangedEventArgs e){\n   //set the CurrentCell to the cell on the current row \n   //in the second column\n   if(dgvConfig.Columns.Count > 1){\n      dgvConfig.CurrentCell = new DataGridCellInfo(dgvConfig.SelectedItem,\n                                                   dgvConfig.Columns[1]);\n   }\n}	0
13050758	13050535	How to check for read access on files using C#	using System.IO;\nusing System.Security.AccessControl;\n\n...\n\nFileSecurity security = File.GetAccessControl(@"C:\MyFolder\My File.txt");\n\nAuthorizationRuleCollection acl = security.GetAccessRules(\n   true, true, typeof(System.Security.Principal.NTAccount));\nforeach (FileSystemAccessRule ace in acl)\n{\n   var user = ace.IdentityReference.Value;\n   var rights = ace.FileSystemRights;\n   var allowOrDeny = ace.AccessControlType;\n   // ...\n}	0
26064246	26063790	How to get a distinct, case-insensitive list using Linq and Entity Framework	var distinct = list.Distinct(new CaseInsensitiveComparer());\n\npublic class CaseInsensitiveComparer : IEqualityComparer<A>\n{\n    public bool Equals(A x, A y)\n    {\n        return x.Code.Equals(y.Code, StringComparison.OrdinalIgnoreCase) &&\n               x.Description.Equals(y.Description, StringComparison.OrdinalIgnoreCase);\n    }\n\n    public int GetHashCode(A obj)\n    {\n        return obj.Code.ToLowerInvariant().GetHashCode();\n    }\n}	0
6388723	6388692	To search for strings with in a string (search for all hrefs in HTML source)	string html = "your HTML here";\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n\ndoc.LoadHtml(html);\n\nvar links = doc.DocumentNodes.DescendantNodes()\n   .Where(n => n.Name == "a" && n.Attributes.Contains("href")\n   .Select(n => n.Attributes["href"].Value);	0
24253458	24253439	Using Generic Types with As operator	T CheckIsType<T>(Thing thing)\n    where T: class\n{\n    return thing as T;\n}	0
23990130	23990044	How to pass value to sql command in c#	sqlCmd.CommandText = keyProcesses;\nsqlCmd.Parameters.AddWithValue("@companyName", compnyName);\nusing(var reader = sqlCmd.ExecuteReader()) {\n    dtb1.Load(reader);\n}	0
10139858	10139558	Get columns values from dataGridView and append them to the hosts file?	var lines = grid.Rows.Cast<DataGridViewRow>()\n            .Select(r => String.Join("\t", r.Cells.Cast<DataGridViewCell>()\n            .Select(c => c.Value)) + Environment.NewLine);\nSystem.IO.File.AppendAllLines(path, lines);	0
10082446	10082415	How to convert control.background(brush) to bitmap?	public BitmapSource ConvertToBitmapSource(UIElement element)\n{\n    var target = new RenderTargetBitmap((int)(element.RenderSize.Width), (int)(element.RenderSize.Height), 96, 96, PixelFormats.Pbgra32);\n\n    var brush = new VisualBrush(element);\n\n    var visual = new DrawingVisual();\n    var drawingContext = visual.RenderOpen();\n\n\n    drawingContext.DrawRectangle(brush, null, new Rect(new Point(0, 0), new Point(element.RenderSize.Width, element.RenderSize.Height)));\n\n    drawingContext.Close();\n\n    target.Render(visual);\n\n    return target;\n}	0
4455480	4455364	Use GDI+ with C# to create an image for a site	private void button1_Click( object sender, EventArgs e )\n{\n    using( Font f = new Font( "Times New Roman", 22f ) )\n    {\n        pictureBox1.Image = CreateImage( "TEXT", pictureBox1.Size, f, Color.Black );\n    }\n}\n\nBitmap CreateImage( string text, Size imageSize, Font font, Color fontColor )\n{\n    Bitmap image = new Bitmap( imageSize.Width, imageSize.Height );\n    using( Graphics g = Graphics.FromImage( image ) )\n    using( Brush brush = new SolidBrush( fontColor ) )\n    {\n        g.DrawString( text, font, brush, new PointF( 0, 0 ) );\n    }\n\n    return image;\n}	0
11070415	11070396	How to create general lists / template lists in C#	IList<ExpandingWindow> windows = new List<ExpandingWindow>();\n\n// initialize them via constructor\nwindows.Add(new MainMenu(A, B));    \nwindows.Add(new SideMenu(A, B, C));\n\nforeach(var window in windows) {\n    window.Draw();\n}	0
17747020	17741424	Retrieve Credentials from Windows Credentials Store using C#	public UserPass GetCredentials()\n    {\n        var cm = new Credential {Target = CredentialName};\n        if (!cm.Exists())\n            return null;\n\n        cm.Load();\n        var up = new UserPass(cm);\n        return up;\n    }\n\n    public bool SetCredentials(UserPass up)\n    {\n        var cm = new Credential {Target = CredentialName, PersistanceType =  PersistanceType.Enterprise, Username = up.UserName, Password = up.Password};\n        return cm.Save();\n    }\n\n    public void RemoveCredentials()\n    {\n        var cm = new Credential { Target = CredentialName };\n        cm.Delete();\n\n    }	0
18923912	18923545	How get return from callback	string result = SaveNewFile(e.UploadedFile);\n        e.CallbackData = result;\n        lblret.Text = String.Format(\n                           "processed at {0} with a result of: {1}", \n                            DateTime.Now,  \n                            result);	0
33445366	33444766	c# InnerException of socket in XamlParseException	private UdpClient broadcast_receiver= new UdpClient(15069);	0
15007334	15007243	how to read a sql column containing commas as one field with c#	myWriter.WriteLine("\"{0}\", \"{1}\", \"{2}\", \"{3}\",", myPlayer, myPosition, myCurTeam, myCollege);	0
10503713	10503644	String.Format() - Repassing params but adding more parameters	public string GetMessage(params object[] otherValues)\n{\n    return String.Format(this.Message, new[] { this.FirstValue }.Concat(otherValues).ToArray<object>());\n}	0
4321816	4321778	DataGridVIew populated with anonymous type, how to filter?	class DocumentRow {\n    public int DocumentId {get;set;}\n    public bool Rilevante {get;set;}\n    public int TopicId {get;set;}\n}\n...\nList<DocumentRow> allData;\n...\nallData = rawTopics.SelectMany(t => t.Documents)\n    .Select(d => new DocumentRow\n        {\n           DocumentId = d.Id,\n           Rilevante = d.IsRelevant,\n           TopicId = d.Topic.Id // foreign key\n        }).ToList();\n...\nrawDocumentsDataGridView.DataSource = allData\n   .Where(d => d.TopicId == tid).ToList();	0
14392663	14249994	Load a Module on demand from multiple points	(...)\n\n var module = this.moduleCatalog.Modules.FirstOrDefault(m => m.ModuleName == "MyModule");\n            if (module != null)\n            {\n                if (module.State != ModuleState.Initialized)\n                {\n                    moduleManager.LoadModuleCompleted += moduleManager_LoadModuleCompleted;\n                    moduleManager.LoadModule("MyModule");\n                }\n                else\n                {\n\n                    //Initialization logic\n\n                }\n            }\n        }\n\n        void moduleManager_LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e)\n        {\n            moduleManager.LoadModuleCompleted -= moduleManager_LoadModuleCompleted;\n\n            if (e.ModuleInfo.ModuleName == "MyModule")\n            {\n                //Initialization logic\n            }\n        }\n\n(...)	0
25283613	25283517	How do I open maximized internet explorer?	ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");\nstartInfo.WindowStyle = ProcessWindowStyle.Maximized;\nstartInfo.Arguments = "www.google.com";\n\nProcess.Start(startInfo);	0
19322953	19322760	matching string to item ids in LINQ	strCheckedCategories.Split(new []{';'}).Any(x => x == m2.SearchTypeId.ToString())	0
7487241	7106887	not able to transfer all valuesof particular selected row in datagrid view to another form	int selectedrowindex= productgridview.SelectedCells[0].RowIndex;\nDataGridViewRow selectedRow = productgridview.Rows[selectedrowindex];\nstring desc = Convert.ToString(selectedRow.Cells["productdescr"].Value);	0
10624870	10624815	How can I use bigint with C#?	System.Numerics.BigInteger	0
25161277	25161070	Using validation on base class variables	public string PartitionKey \n{ \n  get { return base.PartitionKey; } \n  set { base.PartitionKey = value; }\n }	0
8312783	8311261	Access a DataGridView via a parent (TabControl) to set value -- C# form	Control[] ctrls = languageTabs.TabPages[1].Controls.Find("EnglishGrid", true);\n                            if (ctrls[0] != null)\n                            {\n                                DataGridView dgv = ctrls[0] as DataGridView;\n                                dgv.Rows[r].Cells[0].Value = 1;\n                            }	0
14574708	14574475	How to update the whole list of entities with ApplyCurrentValues?	//update all tasks with status of 1 to status of 2\ncontext.Tasks.Update(\n    t => t.StatusId == 1, \n    t2 => new Task {StatusId = 2});\n\n//example of using an IQueryable as the filter for the update\nvar users = context.Users.Where(u => u.FirstName == "firstname");\ncontext.Users.Update(users, u => new User {FirstName = "newfirstname"});	0
12097514	12097306	How can ADO.NET be forced to infer the type of Excel columns as String rather than Double?	string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +\n     "Data Source=" + savePath +\n      "; Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;"\n      + (char)34;	0
14693733	14693664	Assign OberservableCollection to ListBox and exclude some entries	var list = new List<Instance>();\n\n//.. add all items to your list here.\n\n\nObservableCollection<Instance> OCI = new ObservableCollection<Instance>(list.OfType<classa>());\n// the above will generate a new ObservableCollection which contains all items of type classa from list.	0
20212206	20212175	How do I store a collection of ObservableCollection<T> with different types for T?	Dictionary<Type, IActiveList>	0
10034437	10034289	How should I increment a number for a round robin threading scenario with least contention?	public int GetNextNumber()\n{\n  int initial, computed;\n  do\n  {\n    initial = _lastNumber;\n    computed = initial + 1;\n    computed = computed > _maxNumbers ? computed = 1 : computed;\n  } \n  while (Interlocked.CompareExchange(ref _lastNumber, computed, initial) != initial);\n  return computed;\n}	0
33102464	33095040	Using log4net to log in Api from class library	using (var context = new DataContext())\n{\n    // log is a log4net logger\n    context.Database.Log = message => log.Debug(message);\n\n    // insert the entity\n}	0
4302628	4302610	how to perform division in timespan	long ticks1 = tsp1.Ticks;\nlong ticks2 = tsp2.Ticks;\n\nlong remainder;\nlong count = Math.DivRem(ticks1, ticks2, out remainder);\n\nTimeSpan remainderSpan = TimeSpan.FromTicks(remainder);\n\nConsole.WriteLine("tsp1/tsp2 = {0}, remainder {1}", count, remainderSpan);	0
9438733	9433146	MVC Routing: How to map two names to one action	routes.MapRoute(\n    "the hi route",\n    "{controllerName}/{actionName}/{id}",\n    new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional },\n    new { controllerName = @"welcome|bienvenu", actionName = @"sayhi|direallo" }\n);	0
10351919	10344966	dbset.local updating database: a duplicate value cannot be inserted into a unique index	//Sort the list (based on previous session stored in database) \nvar sortList = PropertyList.OrderBy(x => x.Sort).ToList(); \nPropertyList.Clear(); \nsortList.ForEach(PropertyList.Add);	0
28537865	28537822	Variables in preprocessor IFs not found ReSharper	// ReSharper disable UnusedVariable.Compiler\n        private int num;\n        private Person p;\n// ReSharper restore UnusedVariable.Compiler	0
32794004	32761751	Ninject Web Api "Make sure that the controller has a parameterless public constructor."	GlobalConfiguration.Configuration.DependencyResolver = myResolverImpl;	0
7672346	7668456	openfiledialog getting data as multidimensional array with string split	private void button1_Click_1(object sender, EventArgs e)\n{\n\n    List<String> Lines = new List<String>();\n\n    try \n    {\n        DialogResult result = openFileDialog1.ShowDialog();\n        if (result == DialogResult.OK)\n        {\n\n            using (StreamReader sr = new StreamReader(openFileDialog1.FileName))\n            {\n                while ((data = sr.ReadLine()) != null)\n                {\n                    Lines.Add(data);\n                }\n            }\n            FilePath.Text = openFileDialog1.FileName;\n        }\n    }\n    catch(IOException ex) \n    {\n\n        MessageBox.Show("there is an error" + ex+ "in the file please try again");\n    }\n}	0
13596674	13596265	Removing consecutive repeating characters using regex	str = Regex.Replace(str, @"[\. ]*\. *", ".", RegexOptions.Multiline)	0
21597729	21596822	How to add controls into a new tab page which is dynamically created?	void AddTab()\n{\n    TabPage tbp = new TabPage();\n    tbp.Name=TabControl1.TabPages.Count.ToString();\n    MyUserControl cnt = new MyUserControl();\n    cnt.Name="Cnt" + tbp.Name;\n    cnt.Dock=DockStyle.Fill;\n    tbp.Controls.Add(cnt);\n}	0
21485097	21475505	Json Deserialization and controlling the instantiation	JsConfig<CatalogueItem>.RawDeserializeFn\nJsConfig<CatalogueItem>.DeSerializeFn\nJsConfig<CatalogueItem>.OnDeserializedFn	0
21987066	21986670	Remove duplicate child lists from a parent list ignoring the order	class Program\n{\n    static void Main(string[] args)\n    {\n        List<List<string>> ParentList = new List<List<string>>();\n\n\n        List<string> ChildList1 = new List<string> { "B1", "B2", "B3" };\n        List<string> ChildList2 = new List<string> { "B1", "B3", "B2" };\n        List<string> ChildList3 = new List<string> { "B1", "B2" };\n        List<string> ChildList4 = new List<string> { "B5", "B3", "B2", "B4" };\n\n        ParentList.Add(ChildList1);\n        ParentList.Add(ChildList2);\n        ParentList.Add(ChildList3);\n        ParentList.Add(ChildList4);\n\n        var result = ParentList.Distinct(new Comparer()).ToList();\n    }\n}\n\ninternal class Comparer : IEqualityComparer<List<string>>\n{\n    public bool Equals(List<string> list1, List<string> list2)\n    {\n        return list1.All(x => list2.Contains(x)) && list2.All(x => list1.Contains(x));\n    }\n\n    public int GetHashCode(List<string> obj)\n    {\n        return obj.Count;\n    }\n}	0
24946694	24945566	Can't open windows 7 help files standalone	using System;\nusing WinHelp = APClientHelpPane;\n\nclass Program {\n    static void Main(string[] args) {\n        var obj = new WinHelp.HxHelpPaneServer();\n        string docpath = @"C:\Windows\Help\Windows\ContentStore\en-US\windowsclient.mshc";\n        obj.DisplayContents(docpath);\n    }\n}	0
21628145	21627961	Looping through elements in a div in CsQuery	CQ page_ptags = document_div.Cq().Find("p");	0
15030612	15030498	Is there a way to clear a certain part of the console?	// Clear method\nConsole.WriteLine("Line1");\nConsole.WriteLine("Line2");\nConsole.WriteLine("Line3 to erase");\nConsole.Clear();\nConsole.WriteLine("Line1");\nConsole.WriteLine("Line2");\n\n// SetCursorPosition method\nConsole.WriteLine("Line1");\nConsole.WriteLine("Line2");\nConsole.WriteLine("Line3 to erase");\nConsole.SetCursorPosition(0, 2);\nConsole.WriteLine("                           ");	0
17730003	17583010	var di = new DirectoryInfo(path) throws exception until I use Windows Explorer to open the path for a first time	Process.Start(dir);	0
24697211	24696426	browse folder and get user input to create a new file	private void SaveButton_Click(object sender, EventArgs e)\n{\n    // Set your default directory\n    saveFileDialog1.InitialDirectory = @"C:\";\n\n    // Set the title of your dialog\n    saveFileDialog1.Title = "Save file";\n\n    // Do not display an alert when the user uses a non existing file\n    saveFileDialog1.CheckFileExists = false;\n\n    // Default extension, in this sample txt.\n    saveFileDialog1.DefaultExt = "txt";\n\n    if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n    {\n        // DO WHAT YOU WANT WHEN THE FILE AS BEEN CHOSEN\n    }\n}\n\n// This method handles the FileOK event. It checks if the file already exists\nprivate void saveFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)\n{\n    if (File.Exists(saveFileDialog1.FileName))\n    {\n        // The file already exists, the user must select an other file\n        MessageBox.Show("Please select a new file, not an existing one");\n        e.Cancel = true;\n    }\n}	0
4684566	4684513	How to trigger a timer tick programmatically?	myTimer.Start();\nProcessTick();\n\nprivate void MyTimer_Tick(...)\n{\n    ProcessTick();\n}\n\nprivate void ProcessTick()\n{\n    ...\n}	0
12655147	12655106	Class auto generated from XSD return all the same values from array?	class Program\n{\n    static void Main(string[] args)\n    {\n\n        users allUsers = new users();\n        allUsers.user = new usersUser[3];\n        usersUser userConfig = new usersUser();\n\n        userConfig.username = "Jim";\n        allUsers.user[0] = userConfig;\n        Console.WriteLine(allUsers.user[0].username);\n\n        userConfig = new usersUser();\n        userConfig.username = "Frank";\n        allUsers.user[1] = userConfig;\n        Console.WriteLine(allUsers.user[1].username);\n\n        userConfig = new usersUser();\n        userConfig.username = "James";\n        allUsers.user[2] = userConfig;\n        Console.WriteLine(allUsers.user[2].username);\n\n        Console.WriteLine("");\n\n        Console.WriteLine(allUsers.user[0].username);\n        Console.WriteLine(allUsers.user[1].username);\n        Console.WriteLine(allUsers.user[2].username);\n\n        Console.ReadLine();\n    }\n}	0
17149395	17149254	How to get the full Path of the file upload control in a string variable in asp .net?	string fileBasePath = Server.MapPath("~/");\n                string fileName = Path.GetFileName(this.MyFileUploader.FileName);\n                string fullFilePath = fileBasePath + fileName;	0
6105970	6105228	How to ensure all properties have loaded in Silverlight ViewModel pattern (Concurrency Control?)	public IEnumerable<IResult> GoForward()\n    {\n        yield return Loader.Show("Downloading...");\n        yield return new LoadCatalog("Caliburn.Micro.Coroutines.External.xap");\n        yield return Loader.Hide();\n        yield return new ShowScreen("ExternalScreen");\n    }	0
22374933	22212274	Gif File Specification - Comment property of frames	internal byte[] GetBuffer()\n        {            \n            List<byte> list = new List<byte>();\n            list.Add(GifExtensions.ExtensionIntroducer); // 0x21\n            list.Add(GifExtensions.CommentLabel); // 0xFE\n            foreach (string coment in CommentDatas)\n            {\n                char[] commentCharArray = coment.ToCharArray();\n                list.Add((byte)commentCharArray.Length);\n                foreach (char c in commentCharArray)\n                {\n                    list.Add((byte)c);\n                }\n            }\n            list.Add(GifExtensions.Terminator); // 0\n            return list.ToArray();\n        }	0
23596849	23596802	Calculate middle point of Bezier Curve	R = H/2 + W^2/8H	0
9706842	9706803	C# elapsed time on a timer?	Stopwatch stopWatch = new Stopwatch();\nstopWatch.Start();\n\n// do stuff\n\nstopWatch.Stop();\nlong duration = stopWatch.ElapsedMilliseconds;	0
2129500	2129414	How to insert XML comments in XML Serialization?	static public MemoryStream SerializeToXML(MyWrapper list)\n{\n    XmlSerializer serializer = new XmlSerializer(typeof(MyWrapper));\n    MemoryStream stream = new MemoryStream();\n    XmlWriter writer = XmlWriter.Create(stream);\n    writer.WriteStartDocument();\n    writer.WriteComment("Product XY Version 1.0.0.0");\n    serializer.Serialize(writer, course);\n    writer.WriteEndDocument();\n    writer.Flush();\n    return stream;\n}	0
13878190	13878004	Parsing xml with inner nodes	XDocument xdoc = XDocument.Load(path_to_xml);\nvar query = from date in xdoc.Descendants("ItemDate")\n            let type = date.Element("ItemType")\n            let url = type.Element("ItemUrl")\n            select new Item()\n            {\n                ItemDate = ((XText)date.FirstNode).Value,\n                ItemType = ((XText)type.FirstNode).Value,\n                ItemUrl = (string)url,\n                ItemTitle = (string)url.Attribute("title"),\n            };	0
24511559	15838836	Accessing Web.config from another Project	var filePath = @"D:\PathToConfig\Web.config";\nvar map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };\nvar configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);	0
7262660	7262633	How can a block diagram be dynamically generated in ASP.NET?	System.Drawing	0
25774442	25774365	Using task scheduler for scheduling job in C#	foreach (int day in days) \n{\n    td.DaysOfWeek |= (DaysOfTheWeek)day;\n}	0
5046546	5046524	List all db from an mysql server with c#	show databases	0
28574229	28571165	Get element of known type in a list	private void GetChild<T>() where T : Parent, new()\n{\n   T item = myList.FirstOrDefault(ch => ch is T) as T;\n   if(item == null)\n   {\n      item = new T();\n      myList.Add(item);\n   }\n   OtherMethod(item);\n}	0
21765008	21764801	How to use insert and update command using c#	if not exists (select task_id from mytable where task_id = @task_id)  \ninsert into myTable(TASK_ID, USR_ID, UPDT_DT) values(@TASK_ID, @USR_ID, @UPDT_DT)\nelse\nupdate mytable set USR_ID = @USR_ID, UPDT_DT = @UPDT_DT where task_id = @TASK_ID	0
15626188	15537185	MigrateDatabaseToLatestVersion initializer failing to create database	MyDbContext.MyEntity.Add(new MyEntity { Name = "Nelson" });\n// Or\nMyDb.Context.Database.Initialize(true); // force the initialization	0
13656734	13568888	windows phone, reading level from txt file	var assembly = System.Reflection.Assembly.GetExecutingAssembly();\nvar stream = assembly.GetManifestResourceStream("View.Maps.Breakout_" + _breakoutSelection + ".txt");\n\nusing (var streamReader = new StreamReader(stream))\n{\n    int y = 0;\n\n    while (!streamReader.EndOfStream)\n    {\n        string data = streamReader.ReadLine();\n\n        int x = 0;\n\n        foreach (var mapSquare in data)\n        { code here }\n    }\n}	0
17697972	17685822	Populating xml elements representitave of a table structure containing a header and body	var fieldNames = new[] { "Field1", "Field2", "Field3" };\nvar doc = XDocument.Load("c:/somewhere.xml").Root;\n\nforeach (var row in doc.Elements("tablerow"))\n{\n    var i=0;  // index into fieldNames array\n    foreach (var cell in row.Elements("cell"))\n    {\n        cell.Add(new XText(fieldNames[i++]));  // take one, and increment\n    }\n}\ndoc.Save("c:/somewhere.xml");	0
2527588	2525828	How do I add/remove items to a ListView in virtual mode?	Invalidate()	0
23678611	23678334	Programatically Create an Excel Sheet that Auto-sizes Columns	range.EntireColumn.AutoFit();\nrange.EntireRow.AutoFit();	0
3786592	3786554	How to access contents of Object If I don't know the structure in c#?	public static void ShowProperties(object o)\n{\n    if (o == null)\n    {\n        Console.WriteLine("Null: no properties");\n        return;\n    }\n    Type type = o.GetType();\n    var properties = type.GetProperties(BindingFlags.Public \n                                        | BindingFlags.Instance);\n    // Potentially put more filtering in here\n    foreach (var property in properties.Where\n                 (p => p.CanRead && p.GetIndexParameters().Length == 0))\n    {\n        Console.WriteLine("{0}: {1}", property.Name, property.GetValue(o, null));\n    }\n}	0
18390753	18389257	Setting jagged array values within a class	public class Place\n{\n    private string[][] places = new string[2][]\n    {\n        new string[] { "Canada", "United States" },\n        new string[] { "Calgary", "Edmonton", "Toronto" },\n    };\n\n    public void enumerate()\n    {\n        Console.WriteLine(places[0][1]);\n    }\n}	0
9113838	9101987	NServiceBus in WebApp	new DataBusProperty<IEnumerable<byte[]>>	0
10109600	10109568	How to optimize and clear code for parse string?	try / catch	0
32862017	32861445	Send some pdf files as email attachments stored in a db in c#	string[] itemList = Regex.Split(RecoveryAtt, @"(?=D:)").Where(x => !string.IsNullOrEmpty(x)).ToArray();\nCommaseplist = String.Join("; ", itemList);\nResponse.Write(Commaseplist);	0
8929089	8928611	Drag'n'drop to a Windows form issue	void Form1_DragDrop(object sender, DragEventArgs e) {\n    object data = e.Data.GetData(DataFormats.FileDrop);\n}\nvoid Form1_DragEnter(object sender, DragEventArgs e) {\n    if(e.Data.GetDataPresent(DataFormats.FileDrop)) {\n        e.Effect = DragDropEffects.Copy;\n    }\n}	0
23048273	23048051	checking if a checkbox is selected using a variable as the checkbox name	if (this.Controls.Find(regday.Groups[0].Value).Checked)	0
30772148	30701963	Data Binding SQLIte to Listbox(containing three controls) Windows phone 8	Height="Auto" Width="Auto"	0
7444784	7444675	How can I set a file to be writeable by all users?	SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);	0
3583890	3583382	How to disable dropdown list value in the current form that was selected in the previous page	DropDownList oldvalue = (DropDownList)PreviousPage.FindControl("DropDownList1");\n    string str = oldvalue.SelectedValue.ToString();\n\n    ListItem i = DropDownList1.Items.FindByValue(str);\n    i.Attributes.Add("style", "color:gray;");\n    i.Attributes.Add("disabled", "true");	0
12119252	12119232	Access value of variable whose name is stored in another variable	Dictionary<string,string> myDictionary = new Dictionary<string,string>();\n\nmyDictionary["str"] = "ABCDEF";\n\nvar valueinstr = myDictionary["str"];	0
1799856	1799843	How to left/right truncate numbers without strings (Euler #37)	w <- n\nd <- 1\nwhile (w <> 0)\n  test primality of w\n  w <- w / 10\n  d <- d * 10\nend\nw <- n\nwhile (d <> 10)\n  d <- d / 10\n  w <- w % d\n  test primality of w\nend	0
31667203	31667125	How to close a XML FileStream	private void Form1_Load(object sender, EventArgs e)\n    {\n        if (File.Exists("data.xml"))\n        {\n            using (FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read))\n           {\n                XmlSerializer xs = new XmlSerializer(typeof(Information))\n                Information info = (Information)xs.Deserialize(read);\n\n                 data1.Text = info.Data1;\n                 data2.Text = info.Data2;\n                 data4.Text = info.Data3;\n                 data4.Text = info.Data4;\n          }\n        }\n    }\n\n\nclass SaveXML\n{\n    public static void SaveData(object obj, string filename)\n    {\n        using(TextWriter writer = new StreamWriter(filename))\n        {\n            XmlSerializer sr = new XmlSerializer(obj.GetType());\n\n            sr.Serialize(writer, obj);\n        }     \n    }\n}	0
14068574	14068379	Sorting a list, ignoring every nth element?	var list = ...; // Get hold of the whole list.\nvar sortedElements = list.Where((value, index) => index % 3 != 2)\n                         .OrderBy(x => x)\n                         .ToList();\nfor (int i = 0; i < sortedElements.Count; i++)\n{\n    int index = (i / 2) * 3 + i % 2;\n    list[index] = sortedElements[i];\n}	0
25718028	25697737	exact foreach loop to access ragridview row	List<class> variable= new List<class>();\n\nfor (i = 0; i < count; i++)\n       {\n           (class)row = (class)sender.Items[i];\n           {\n               variable.Add(row);\n           }\n       }	0
4023930	4023731	How do I get certificate's key size	this.PublicKey.Key.KeySize;	0
11260881	11260691	How to make coded UI test to select newest folder in C#	DirectoryInfo root = new DirectoryInfo(@"C:\");\nDirectoryInfo[] folders = root.GetDirectories();\n\nDirectoryInfo max = folders[0];\nforeach (var dir in folders)\n{\n    if (dir.CreationTime.CompareTo(max.CreationTime) > 0)\n        max = dir;\n}\n\n// Last created directory is max	0
8427478	8424696	C# string serializer converted to Qt	QString YourClass::serialize( const QStringList& list )\n{\n    QString output;\n\n    foreach( QString str, list )\n    {\n        output.append( QString( "%1%2%3" )\n           .arg( QString::number( str.length() ).length() )\n           .arg( str.length() )\n           .arg( str ) );\n    }\n\n    return output;\n}	0
34313211	34312862	How to eliminate Escape character from a string	var escapedString ="\"{ \\\"path\\\" : \\\"a.crx\\\", \\\"uniteDeVolume\\\" : \\\"g or ml\\\", \\\"unites\\\" : \\\"Acts/Volume\\\", \\\"nbIndevMin\\\" : \\\"20\\\", \\\"nbJours\\\" : \\\"6 to 7\\\", \\\"ventilDepart\\\" : \\\"20051\\\" }\"";\nvar unescapedString = Regex.Unescape(escapedString);	0
1445580	1445523	Append to a Select Command	private void bttnfilter_Click(object sender, ImageClickEventArgs e)\n{\n    string filterText = TextBox1.Text.Trim().ToLower();\n\n    if (!String.IsNullOrEmpty(filterText))\n        SqlDataSource1.FilterExpression = \n            string.Format("field LIKE '%{0}%'",filterText);         \n}	0
13282982	13282774	Convert Lambda Expression Group By to LINQ Version	var result=   from p in data\n    group p by new \n   { Criterion = p.Contains(p.Group) ? "A" : p.Contains(p.Group) ? "B" : "N/a" } \n    into g  select new {KEY = g.Key, VALUE = g.Count()};	0
3181280	3181274	Assign a reference of an integer in a class	class Reference<T> {\n    public T Value { get; set; }\n    public Reference(T value) { Value = value; }\n}	0
4806661	4806459	translate from sql statement to lambda expression statement	var ids = new[] { 1, 2, 3 };\n\nvar employees = yourEmployeeStore.Where(e => ids.Contains(e.id));	0
31060289	31059875	Convert http post variables to an anonymous type	mc.GetType().GetProperties()\n    .Where (x => context.Request.Form.AllKeys.Contains(x.Name)).ToList()\n    .ForEach(x => \n        x.SetValue(mc, Convert.ChangeType(context.Request.Form[x.Name], x.PropertyType)));	0
32027265	32027246	Creating valid file extension list	var whitelist = new[]\n{\n    ".txt", ".bat", ".con"\n};\n\nstring extension = Path.GetExtension(files[i]);\nif (whitelist.Contains(extension))\n{\n    DoSomething(files[i]);\n}	0
4802062	4801990	How to get a dimension (slice) from a multidimensional array	using System;\nstatic class ArraySliceExt\n{\n    public static ArraySlice2D<T> Slice<T>(this T[,] arr, int firstDimension)\n    {\n        return new ArraySlice2D<T>(arr, firstDimension);\n    }\n}\nclass ArraySlice2D<T>\n{\n    private readonly T[,] arr;\n    private readonly int firstDimension;\n    private readonly int length;\n    public int Length { get { return length; } }\n    public ArraySlice2D(T[,] arr, int firstDimension)\n    {\n        this.arr = arr;\n        this.firstDimension = firstDimension;\n        this.length = arr.GetUpperBound(1) + 1;\n    }\n    public T this[int index]\n    {\n        get { return arr[firstDimension, index]; }\n        set { arr[firstDimension, index] = value; }\n    }\n}\npublic static class Program\n{\n    static void Main()\n    {\n        double[,] d = new double[,] { { 1, 2, 3, 4, 5 }, { 5, 4, 3, 2, 1 } };\n        var slice = d.Slice(0);\n        for (int i = 0; i < slice.Length; i++)\n        {\n            Console.WriteLine(slice[i]);\n        }\n    }\n}	0
15699273	15402493	Convert flat text file to XML in C#	//path of your RDF file i.e. txt file used delimeter |\n\nString filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"RdfFile/RDF.txt");\n\nIEnumerable<String> source = File.ReadLines(filePath);\n\n XElement scans = new XElement("Test",\n\n\n        from str in source\n        let fields = str.Split('|')\n        select new XElement("Product",\n           new XAttribute("Action", FileName),\n           new XAttribute("EnsureDefaultVariant", "1"),\n           new XAttribute("ID", fields[0]),\n\n\n\n            new XElement("Summary", fields[2]),\n            new XElement("ImageFilenameOverride", fields[1])\n\n\n            )\n\n    );\n//path in which xml file you want to save result.\n\n String filePath_Xml = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,\n @"XMLFile/RDF__Scans_Add_XMLFile.xml");\n\n scans.Save(filePath_Xml);	0
24074037	24073960	how to delete dynamically allocated array c#	if( btnNums!=null)\n    {   for (int i = 0; i < btnNums.Count; i++)\n             btnNums[i].Dispose();\n    }	0
32129481	32129324	Get value from txt file c#	private List<string> GetIPAddress()\n{\n    var list = new List<string>();\n    var input = File.ReadAllText("file.txt");\n    var r = new Regex(@"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");\n    foreach (Match match in r.Matches(input))\n    {\n         string ip = match.Groups[1].Value;\n         string port = match.Groups[2].Value;\n         list.Add(ip);\n         // you can also add port in the list\n     }\n     return list;\n}	0
10893866	10882635	Run function whenever a change is made in database	foreach (User user in changeSet.Inserts.Concat(changeSet.Updates).Concat(changeSet.Deletes) \n{\n    this.doSomeStuff();\n}	0
21752469	21752413	Math.Round a label in C#	label1.Text = Math.Round(output, 2).ToString();	0
10651419	10651262	Using LINQ how to split string (not on character but on index)	var str = "ABCDEFGHI";\nvar tmp = str.Select((i, index) => new { i, index })\n             .GroupBy(g => g.index / 3, e => e.i)\n             .Select(g => String.Join("", g));\nvar final_string = String.Join(", ", tmp);	0
2572690	2572664	problem in case of window service	InstallUtil.exe [YourService].exe	0
13285448	13270089	c# How to get a meaninful name of website or executable	public static string getApplicationName()\n{\n    return string.IsNullOrEmpty(HttpRuntime.AppDomainAppId)?\n        Assembly.GetEntryAssembly().GetName().Name : \n        new DirectoryInfo(HttpContext.Current.Server.MapPath("")).Name;\n}	0
2468678	2461318	How to fix basicHttpBinding in WCF when using multiple proxy clients?	ServicePointManager.DefaultConnectionLimit	0
6523997	6523953	A simple Read-Write huge input file problem	static void Main(string[] args)\n{\n    Regex pattern = new Regex(@"[ ]{2,}");   //Pattern = 2 or more space in a string.\n\n    using (StreamReader reader = new StreamReader(@"C:\CSharpProject\in\abc.txt"))\n    using (StreamWriter writer = new StreamWriter(@"C:\CSharpProject\out\abc.txt"))\n    {\n       string content;\n       while (null != (content = reader.ReadLine()));\n          writer.WriteLine (pattern.Replace (content, " "));\n\n       writer.Close();\n       reader.Close();\n    }\n}	0
26553892	26553848	Parse HTTP response in C#	var coll = System.Web.HttpUtility.ParseQueryString(queryString);\nstring url = coll["url"];\nstring type = coll["type"];	0
28109241	28106231	How to dected Excel was starting by automation (VSTO Addin context)	bool isExcelStartedByAutomation = (Environment.GetCommandLineArgs().Contains("/automation") && Environment.GetCommandLineArgs().Contains("-Embedding"));	0
25531693	25531473	Accessing members of inner generics in C#	public TESTClass()\n{\n    interval = new I()\n    {\n        left = 0,\n        data = //Reads data property, \n        {\n            value = 0 //set data.value to 0\n        }\n    }\n}	0
860484	860468	Including */ in a C-style block comment	#if 0\nwhatever you want can go here, comments or not\n#endif	0
14525617	14525601	How to chain NInject modules together	Kernel.Load(new [] { new [YourModule]() });	0
735966	735775	What is the best way to see if a RadioButtonList has a selected value?	public static class MyExtenstionMethods \n{   \n  public static bool HasSelectedValue(this RadioButtonList list) \n  {\n    return list.SelectedItem != null;\n  }\n}\n\n\n...\n\nif (RadioButtonList_VolunteerType.HasSelectedValue)\n{\n // do stuff\n}	0
34119595	34119324	How I can refresh listbox Items from another class in WPF Application?	this.Dispatcher.Invoke((Action)(() =>\n    {\n        ...// your code refresh listbox Items\n    }));	0
20645913	20645737	LINQ to SQL Order of Evaluation of a Boolean	obj.Guid	0
1565713	1565674	Execute sql file on a SQL Server using C#	protected virtual void ExecuteScript(SqlConnection connection, string script)\n    {\n        string[] commandTextArray = System.Text.RegularExpressions.Regex.Split(script, "\r\n[\t ]*GO");\n\n        SqlCommand _cmd = new SqlCommand(String.Empty, connection);\n\n        foreach (string commandText in commandTextArray)\n        {\n            if (commandText.Trim() == string.Empty) continue;\n            if ((commandText.Length >= 3) && (commandText.Substring(0, 3).ToUpper() == "USE"))\n            {\n                throw new Exception("Create-script contains USE-statement. Please provide non-database specific create-scripts!");\n            }\n\n            _cmd.CommandText = commandText;\n            _cmd.ExecuteNonQuery();\n        }\n\n    }	0
6746709	6746577	C# : Printing variables and text in a textbox	foreach (int lineNumber in lineItems)\n{\n    if (lineNumber > 10)\n        textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";\n}	0
24994811	24994683	Convert my value from String to Int	public ActionResult Edit(demo demo)\n{\n    var val = Request.Form["id"]; //could be an object here.\n    int id = 0;\n    double dblId = 0.0;\n\n    if (int.TryParse(val, out id))\n    {\n        //id is an int here!\n    }\n\n    if (double.TryParse(val, out dblId))\n    {\n        //dblId is a double here!\n\n        //you can convert the double to an int if you wish:\n        id = Convert.ToInt32(dblId);\n    }\n}	0
4128206	4123633	store selected value of multiple list box items in asp.net	protected void Button1_Click(object sender, EventArgs e)\n{\n    string msg = "";\n\n    foreach (ListItem li in ListBox_SubModel.Items)\n    {\n        if (li.Selected == true)\n        {\n            msg += "<br />" + li.Value + " is selected";\n        }\n    }\n    Label_SubModel.Text = msg;\n}	0
4252121	3624544	ListView [VirtualMode] change selected index	listView1.SelectedIndices.Clear();\nlistView1.SelectedIndices.Add(indexToSelect);	0
15452104	15452070	Create a new Rectangle next to other object Location	Rectangle newRect = new Rectangle(\n  pictureBox1.Location.X + 10, \n  pictureBox1.Location.Y, \n  pictureBox1.Width, \n  pictureBox1.Heigth);	0
19824153	19823201	How to get the "ID" of element by the name with asp.net	foreach (var control in Page.Form.Controls)\n{\n    if (control is HtmlInputControl)\n    {\n        var htmlInputControl = control as HtmlInputControl;\n        string controlName = htmlInputControl.Name;\n        string controlId = htmlInputControl.ID;\n    }\n}	0
27154057	27153894	How to detect invalid command in speech recognition c#?	switch (speech)\n  {\n    case "1":\n      Bill.Speak("Command 1");\n      break;\n    case "2":\n      Bill.Speak("Command 2");\n      break;\n    default:\n      Bill.Speak("You have given an invalid command. Please try again.");\n      break;\n   }	0
20698777	20698715	How to group by on multiple columns from datatable with linq?	List<DataTable> tables = ds.Tables[0].AsEnumerable()\n                           .GroupBy(row => new {\n                               Email = row.Field<string>("EMAIL"), \n                               Name = row.Field<string>("NAME") \n                           }).Select(g => g.CopyToDataTable()).ToList();	0
29006782	29006620	XML - Select xmlNode depending on innertext	XDocument doc = ...; // However you load the XML\nXElement element = doc.Root\n                      .Elements("Project")\n                      .Elements("Name")\n                      .Where(x => x.Value == projectName)\n                      .SingleOrDefault();\n// Check whether or not element is null (if so, you haven't found it)	0
4833728	4833720	C# CSearch Tuple list with wildcards	list.RemoveAll(t => t.Item1 == cond1 && t.Item3 == cond3);	0
14808296	14799940	Different-sized Tiles in Windows App	public class VariableGrid : GridView\n{\n    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n    {\n        ITileItem tile = item as ITileItem;\n        if (tile != null)\n        {\n            GridViewItem griditem = element as GridViewItem;\n            if (griditem != null)\n            {\n                VariableSizedWrapGrid.SetColumnSpan(griditem, tile.ColumnSpan);\n                VariableSizedWrapGrid.SetRowSpan(griditem, tile.RowSpan);\n            }\n        }\n        base.PrepareContainerForItemOverride(element, item);\n    }\n}	0
7746287	7746269	Directly increasing an int in a List of objects	objects[0] = ((int)objects[0]) + 10;	0
25168506	25168445	How to determine if color is close to other color	bool ColorsAreClose(Color a, Color b, int threshold = 50)\n{\n    int r = (int)a.R - b.R,\n        g = (int)a.G - b.G,\n        b = (int)a.B - b.B;\n    return (r*r + g*g + b*b) <= threshold*threshold;\n}	0
2996549	2996208	How to find version of an application installed using c#	FileVersionInfo.GetVersionInfo("some.dll");	0
13077993	13077969	How do I check for duplicate answers in this array? c#	bool allUnique = Numbers.Distinct().Count() == Numbers.Length;	0
18708194	18674086	Capture Mouse Event in Application when AxShockwaveFlash Full Screen	using MouseKeyboardActivityMonitor;\nusing MouseKeyboardActivityMonitor.WinApi;\nusing MouseEventArgs = System.Windows.Forms.MouseEventArgs;\n\nprivate readonly MouseHookListener _mMouseHookManager;\n\n\n_mMouseHookManager = new MouseHookListener(new GlobalHooker()) {Enabled = true};\n_mMouseHookManager.MouseDown += HookManager_MouseDown;	0
30207479	30205718	How to unit test an abstract class using Microsft Fakes framework	class TestableProvideBase : ProvideBase{}\n\n[TestMethod]\npublic void TestTagProperty() {\n    var sut = new TestableProvideBase();\n\n    Assert.AreEqual(String.Empty, sut.Tag);\n\n    sut.Tag = "someValue";\n\n    Assert.AreEqual("someValue", sut.Tag);\n}	0
26053718	26053668	Split a string on comma and space at the same time	string[] str = line.Split(new[] { ',', ' ' }, \n                                StringSplitOptions.RemoveEmptyEntries);	0
29834723	29122352	AddAttachment from MemoryStream	fileByteArray = new byte[getBlob.Properties.Length];\ngetBlob.DownloadToByteArray(fileByteArray, 0);\nattachmentFileStream = new MemoryStream(fileByteArray);\nemailMessage.AddAttachment(attachmentFileStream, fileUploadLink.Name);	0
8831618	8831537	Correct way parsing a text file	using(var reader = GetStreamReader())\n{\n    bool justReadATag = false;\n    string line = string.Empty;\n\n    while((line = reader.ReadLine()) != null)\n    {\n        if(IsTag(line)) \n        {\n            // do some work with the paragraph tag\n            justReadATag = true;\n        }else{\n            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n            if(justReadATag) \n            {\n                // do some work with the column names\n                justReadATag = false;    \n            }else\n            {\n                // do some work with the cell values\n            }\n        }\n    }\n}	0
20569861	20560044	Sending Bulk Message to Twilio "Bad Request"	message = client.SendMessage("5555555555","5555555555","asdasd");\nif (message.RestException != null) { /* something broke */ }	0
11414007	11407068	How to drag and drop a button from one panel to another panel?	public Form1() {\n  InitializeComponent();\n\n  panel1.AllowDrop = true;\n  panel2.AllowDrop = true;\n\n  panel1.DragEnter += panel_DragEnter;\n  panel2.DragEnter += panel_DragEnter;\n\n  panel1.DragDrop += panel_DragDrop;\n  panel2.DragDrop += panel_DragDrop;\n\n  button1.MouseDown += button1_MouseDown;\n}\n\nvoid button1_MouseDown(object sender, MouseEventArgs e) {\n  button1.DoDragDrop(button1, DragDropEffects.Move);\n}\n\nvoid panel_DragEnter(object sender, DragEventArgs e) {\n  e.Effect = DragDropEffects.Move;\n}\n\nvoid panel_DragDrop(object sender, DragEventArgs e) {\n  ((Button)e.Data.GetData(typeof(Button))).Parent = (Panel)sender;\n}	0
7802511	7801573	how to use serial port throughout my Windows Forms application?	static SerialPort port;\nstatic public void Main()          \n{             \n    port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);\n    port.Open();              \n    Application.Run(new EAS_ControlForm());         \n}	0
7554736	7554087	Check if Datatype from schematable and user data match	try\n    {\n        object o = Convert.ChangeType(row["Input"], Type.GetType(row["DataType"]));\n    }\n    catch (Exception ex)\n    {\n\n        // Its not a type\n    }	0
17271209	17271143	How to get the DataType and Size of a column using the SqlDataReader?	Type type = reader.GetFieldType(0);	0
3272626	3272267	DataGrid how to get the value of the CurrentCell	var cellInfo = dataGrid.CurrentCell;\nif (cellInfo != null)\n{\n    var column = cellInfo.Column as DataGridBoundColumn;\n    if (column != null)\n    {\n        var element = new FrameworkElement() { DataContext = cellInfo.Item };\n        BindingOperations.SetBinding(element, FrameworkElement.TagProperty, column.Binding);\n        var cellValue = element.Tag;\n    }\n}	0
22144132	22144069	how to know if all items are selected in checkedlistbox	if (checkedListBox1.CheckedItems.Count == checkedListBox1.Items.Count)\n      {\n                   //your code goes here  \n      }	0
10687490	10686813	Alternative to OnPaintBackground in wpf .	protected override void OnRender(DrawingContext dc)\n{\n    SolidColorBrush mySolidColorBrush  = new SolidColorBrush();\n    mySolidColorBrush.Color = Colors.LimeGreen;\n    Pen myPen = new Pen(Brushes.Blue, 10);\n    Rect myRect = new Rect(0, 0, 500, 500);\n    dc.DrawRectangle(mySolidColorBrush, myPen, myRect);\n}	0
13737252	13737162	How to Fix the X Axis values length in Microsoft chart controls	MSChart.ChartAreas[0].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;\n       MSChart.ChartAreas[0].AxisX.IsLabelAutoFit = true;	0
4411071	4410849	C# SMTPClient sending attachment which locates in a url	Download*	0
4956383	4946133	How to retrieve objects of an anonymous type from db4o	using System;\nusing Db4objects.Db4o;\n\nnamespace TestAnonymousTypes\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var obj = new {Name = "Foo", Id = "Bar"};\n\n            if (args.Length == 0)\n            {\n                using (var db = Db4oEmbedded.OpenFile("TestAnonymous.odb"))\n                {\n                    db.Store(obj);\n                }\n                return;\n            }\n\n            using (var db = Db4oEmbedded.OpenFile("TestAnonymous.odb"))\n            {\n                var query = db.Query();\n                query.Constrain(obj.GetType());\n\n                var result = query.Execute();\n\n                var y = result[0];\n                Console.WriteLine(y);\n            }\n        }\n    }\n}	0
28602160	28602053	Adding Partial View with Switch Case in Controller	switch (btnReturn)\n{\n    case "Register":\n        return DashboardRegister(model1, Role, formCollection);\n    case "Login":\n        return DashboardLogin(model2, returnUrl);\n}	0
16752356	16752260	Removing Dynamically created controls in Panel	for (int i = 0; i < panel1.Controls.Count; i++)\n{                \n  Control c = panel1.Controls[i];\n  lastChar = c.Name[c.Name.Length - 1];\n  lastValue = (int)Char.GetNumericValue(lastChar);\n  MessageBox.Show("second " + c.Name);\n\n  if (lastValue > 0 && lastValue < count)\n  {\n    panel1.Controls.Remove(c);\n    c.Dispose();\n    i--;\n  }\n }	0
30928185	30927869	How to find the the start and end of a yesterday with Noda Time?	public static void DefineYesterday( out LocalDateTime yesterdayStartOfDay , out LocalDateTime yesterdayEndOfDay )\n{\n  BclDateTimeZone tz         = NodaTime.TimeZones.BclDateTimeZone.ForSystemDefault() ;\n  LocalDateTime   now        = SystemClock.Instance.Now.InZone(tz).LocalDateTime ;\n  LocalDateTime   startOfDay = now.PlusTicks( - now.TickOfDay ) ;\n\n  yesterdayStartOfDay = startOfDay.PlusDays(  -1 ) ;\n  yesterdayEndOfDay   = startOfDay.PlusTicks( -1 ) ;\n\n  return;\n}	0
7306236	7306214	Append lines to a file using a StreamWriter	new StreamWriter("c:\\file.txt", true);	0
13132552	13131305	Threading serial port query and using the result in a ListView control	public static void queryDevice()\n    {\n        SerialPort _serialPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);\n        _serialPort.Handshake = Handshake.None;\n        ObservableCollection<string> store= new ObservableCollection<string> { " ", " ", " " };\n        string[] query = new string[3] { "t02", "t03", "t04" };\n        Thread thread = new Thread(delegate(){Process(store,query,_serialPort);});\n        thread.Start();\n    }\n\n\n\n     public static void Process(ObservableCollection<string> store, string[] query, SerialPort _serialPort)\n     {\n         while (true)\n         {\n             for (int i = 0; i < 3; i++)\n             {\n                 string add = SerialCom.returnData(query[i], _serialPort);\n                 if (store[i] != add)\n                 {\n                     store.Add(add);\n                 }\n             }\n             Thread.Sleep(300);\n         }\n     }	0
5998885	5998832	Get value from a generic object property by reflection	string value = element.GetValue(justAuditElementProperties.GetValue(genericObject, null), null).ToString();	0
21193230	21193187	Take arguments in strings in C#	string input = "function(aa, bb, cc);";\n\n    string pattern = @"\((?<str>.+)\)";\n\n    Regex regex = new Regex(pattern);\n    Match m = regex.Match(input);\n\n    if(m.Success)\n    {\n        string str = m.Groups["str"].Value;\n        Console.WriteLine(str);\n        string[] args = str.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);\n\n    } else {\n        // unable to parse\n    }	0
31195547	31195168	How do I embed views programmatically in Xamarin?	var tab = new UITabBarController ();\n\n        var nav1 = new UINavigationController (new MyViewController1 ());\n        var nav2 = new UINavigationController (new MyViewController2 ());\n        var nav3 = new UINavigationController (new MyViewController3 ());\n\n        tab.ChildViewControllers = new [] { nav1, nav2, nav3 };\n\n        Window.RootViewController = tab;	0
4716819	4716792	How to compare multiple object values against each other?	result = d1.Year.CompareTo(d2.Year)\nif (result != 0) return result;\n\nresult = d1.Month.CompareTo(d2.Month)\nif (result != 0) return result;\n\n...\n\nreturn 0;   //All properties were equal	0
28172473	28169231	WCF self hosted HTTPS with custom UserNamePasswordValidator	BasicHttpBinding b = default(BasicHttpBinding);\nif (bUseSSL) {\n  //check for ssl msg credential bypass\n    if (bSSLMsgCredentialBypass) {\n      b = new   BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);\n    } else {\n      b = new BasicHttpBinding(BasicHttpSecurityMode.Transport);\n    }\n\n    b.TransferMode = TransferMode.Buffered;\n    b.MaxReceivedMessageSize = int.MaxValue;\n    b.MessageEncoding = WSMessageEncoding.Text;\n    b.TextEncoding = System.Text.Encoding.UTF8;\n    b.BypassProxyOnLocal = false;\n    //b.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;\n}	0
17179283	17173111	A more efficient way of showing adds/deletes in a context	public List<UserInfo>(int userID 1)\n{\n    var data = (from ctx in context.UserInfo\n                where ctx.UserID == userID\n                select ctx).ToList();\n\n    List<UserInfo> user = (from ctx in context.UserInfo.Local\n                           where ctx.UserID == userID\n                           select ctx).ToList();\n\n    return user;\n}	0
8145563	8145553	show only 100 result from a select	string str="select top 100 * tableA where id > 56";	0
10681048	10680910	Inserting a List<> into SQL Server table	// define the INSERT statement using **PARAMETERS**\nstring insertStmt = "INSERT INTO dbo.REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED) " + \n                    "VALUES(@ReportID, @RoleID, 'SYSTEM', CURRENT_TIMESTAMP)";\n\n// set up connection and command objects in ADO.NET\nusing(SqlConnection conn = new SqlConnection(-your-connection-string-here))\nusing(SqlCommand cmd = new SqlCommand(insertStmt, conn)\n{\n    // define parameters - ReportID is the same for each execution, so set value here\n    cmd.Parameters.Add("@ReportID", SqlDbType.Int).Value = YourReportID;\n    cmd.Parameters.Add("@RoleID", SqlDbType.Int);\n\n    conn.Open();\n\n    // iterate over all RoleID's and execute the INSERT statement for each of them\n    foreach(int roleID in ListOfRoleIDs)\n    {\n      cmd.Parameters["@RoleID"].Value = roleID;\n      cmd.ExecuteNonQuery();\n    }\n\n    conn.Close();\n}	0
8670053	8670005	How do I make the number "0" display in a textbox?	.ToString("N0")	0
1032207	1032181	c# Use two validators on the same field	((19|20)\d\d[- /.](0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])|((19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])))	0
8807844	8807258	Is there a way to make DateTime.IsDaylightSavingTime work on a machine with GMT/UTC time?	DateTime f = new DateTime(2012, 8, 1); //A date on summer \nTimeZoneInfo tzf2=TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");\nDateTime f2 = TimeZoneInfo.ConvertTime(f, tzf2);\nvar isSummer = tzf2.IsDaylightSavingTime(f2);	0
12702496	12702243	A potentially dangerous Request.Path value was detected from the client?	//In Site Map \n\n    <siteMapNode title="Shipping rate" nopResource="Admin.Configuration.Shipping.Rate" controller="Shipping" action="SomeAction"/> \n\n\n//In Shipping Controller \n\n\n    public ActionResult SomeAction()\n    {\n         return RedirectToAction("ConfigureProvider", new { systemName = "Shipping.ByWeight" });\n    }\n\n\n    public ActionResult ConfigureProvider(string systemName)\n    {\n\n    }	0
543758	543750	How to display 1 instead of 01 in ToString();	ToString("#,0")	0
32982369	32973691	How can I use ExchangeService to access a shared mailbox (Outlook 2013)	public UseExchangeServer(string mailBox)\n{\n    _service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);\n    _service.UseDefaultCredentials = true;\n    _service.AutodiscoverUrl(mailBox);\n}\n\n public FindItemsResults<Item> GetLastItems(int numberOfItems,string mailBox)\n{\n    FolderId FolderToAccess = new FolderId(WellKnownFolderName.Inbox,mailBox);\n    return _service.FindItems(FolderToAccess, new ItemView(numberOfItems));\n}\n\npublic IEnumerable<EmailMessage> LoadMessages(int numberOfMessages)\n{\n    var findResults = GetLastItems(numberOfMessages);\n\n    foreach (var item in findResults.Items)\n    {\n        var message = EmailMessage.Bind(_service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));\n        message.Load();\n        yield return message;\n    }\n}	0
8205633	8205410	C#: If listbox has a certain word delete that item?	for (int n = listBox1.Items.count - 1; n >= 0; --n)\n{\n    string removelistitem = "HI";\n    if (listBox1.Items[n].ToString().Contains(removelistitem))\n    {\n        listBox1.Items.RemoveAt(n);\n    }\n}	0
6108148	6108066	Calling a method from a backgroundworker	void DoWork(...)\n{\n    YourMethod();\n}\n\nvoid YourMethod()\n{\n    if(yourControl.InvokeRequired)\n        yourControl.Invoke((Action)(() => YourMethod()));\n    else\n    {\n        //Access controls\n    }\n}	0
2965401	2965315	retrieve file line one by one using C#?	string[] arr = System.IO.File.ReadAllLines(filename)\nfor (int i = 0; i<arr.Length; i += 2)\n{\n  // do whatever you need here\n}	0
11989757	11989197	Load Array values values from Controller: MVC WInforms	XmlSerializer serializer = new XmlSerializer(_users.GetType());            \n\nusing (FileStream fileStream = new FileStream("Users.xml", FileMode.Create))\n{\n    serializer.Serialize(fileStream, _users);\n}	0
7403637	7403554	Error: can't declare a virtual/ abstract member private	class Base\n{    \n    protected virtual string Member1() { return null; }    \n}\n\nclass Derived : Base\n{\n    protected override string Member1() { return null; }   \n}	0
28200849	28200487	Recreating a list with values from an updated database	// Allocate positions \n    for (var i = 0; i < bidList.Count; i++)\n    {\n        var position = i + 1;\n\n        bidList[i].Position = position;\n\n        query = "UPDATE bid SET position='" + position + "' WHERE operator_id='" + bidList[i].OperatorId +\n                    "'";\n        var dbObject = new DbConnect();\n        dbObject.InsertBooking(query);\n    }\n\n    return bidList.OrderBy(bid => bid.Position);	0
7697207	7697093	Setting static events to null using reflection	foreach (EventInfo eventInfo in GetType().GetEvents(BindingFlags.Static | BindingFlags.Public))\n   {\n      FieldInfo field = GetType().GetField(eventInfo.Name, BindingFlags.Static | BindingFlags.NonPublic);\n      field.SetValue(null, null);             \n   }	0
1110356	1110246	How do I programatically save an image from a URL?	WebClient webClient = new WebClient();\nwebClient.DownloadFile(remoteFileUrl, localFileName);	0
715594	715346	Data Binding to an object in C#	MyDataSource.DataSource = new MyClass();\nTextBox1.DataSource = MyDataSource;	0
12001019	12000978	When I force downloading a file from a page, it split te file name by SPACE /C#?	Response.AddHeader("Content-disposition", \n                   "Attachment; Filename=\"" + file + "\"");	0
28637195	28634520	C# Pubnub SDK usage pattern	EndPendingRequests()	0
15416271	15415980	Board game pawn movement algorithm	List<Spot> CheckMoves(Spot curSpot, int remainingMoves, List<Spot> moveHistory)\n{\n    List<Spot> retMoves = new List<Spot>();\n    if( remainingMoves == 0 )\n    {\n        retMoves.Add(curSpot);\n        return retMoves;\n    }\n    else\n    {\n        moveHistory.Add(curSpot);\n        if( !moveHistory.Contains(Spot.North) )\n        {\n\n            retMoves.AddRange( CheckMoves( Spot.North, remainingMoves - 1, moveHistory );\n        }\n        /* Repeat for E, W, S */\n    }\n}	0
1412703	1412392	Set a dynamically created button's CommandArgument in a gridview or listview	protected void ListView1_RowCommand(object sender, GridViewCommandEventArgs e)\n  {\n      GridViewRow row = (GridViewRow) \n               ((( Button) e.CommandSource ).NamingContainer);\n      Label pk = (Label) row.FindControl("lblPKey");\n      int showRecordPKey = Convert.ToInt32(pk.Text); \n  }	0
3611002	3610300	'Master Object' needs to exist without database calls	abstract class Template { \n    ICollection<Statistics> DefaultData;\n}\n\nclass CharacterTemplate : Template { \n    private CharacterTemplate() {\n        //appropriate data initialization\n    }\n\n    private static readonly CharacterTemplate _instance = new CharacterTemplate();\n    public static Template Instance { get { return _instance; } }\n}\n\nclass Character { \n    Template template = CharacterTemplate.Instance; /* CharacterTemplate */\n    ICollection<Statistics> Data ;\n}	0
1947638	1947533	Triggering a non-static class from a static class?	class nonStaticDLLCLASS\n{\n   public event Event1;\n\n   public CallStaticMethod()\n  {\n     StaticTestClass.GoStaticMethod(this);\n  }\n}\n\nclass StaticTestClass\n{\n   public static GoStaticMethod(nonStaticDLLCLASS instance)\n   {\n     // Here I want to fire Event1 in the nonStaticDLLCLASS\n     // I know the following line is not correct but can I do something like that?\n\n     instance.Event1();\n\n   }\n}	0
14359049	14358913	manually adding rows in DataGridView	if ((string)row.Cells[1].Value == "Yes")\n                row.DefaultCellStyle.ForeColor = Color.Red;\n            else\n                row.DefaultCellStyle.ForeColor = Color.Green;	0
13069791	13069740	Read content as integer of empty XML element	int number;\n  bool result = Int32.TryParse(xNode.ReadElementContentAsString, out number);	0
11438397	11438235	Splitting LINQ query based on predicate	/// <summary>Splits an enumeration based on a predicate.</summary>\n/// <remarks>\n/// This method drops partitioning elements.\n/// </remarks>\npublic static IEnumerable<IEnumerable<TSource>> Split<TSource>(\n    this IEnumerable<TSource> source,\n    Func<TSource, bool> partitionBy,\n    bool removeEmptyEntries = false,\n    int count = -1)\n{\n    int yielded = 0;\n    var items = new List<TSource>();\n    foreach (var item in source)\n    {\n        if (!partitionBy(item))\n            items.Add(item);\n        else if (!removeEmptyEntries || items.Count > 0)\n        {\n            yield return items.ToArray();\n            items.Clear();\n\n            if (count > 0 && ++yielded == count) yield break;\n        }\n    }\n\n    if (items.Count > 0) yield return items.ToArray();\n}	0
20248108	20245270	Cannot access SQL Server CE DB after installation	Environment.SpecialFolder.ApplicationData	0
7764862	7764812	How to write C# Scheduler	private void OnTimerTick()\n{\n    if(DateTime.Now.Minutes%15==0)\n    {\n        //Do something\n    }\n}	0
5397877	5384303	WCF REST Service JSON Post data	[OperationContract]\n[WebInvoke\n   (UriTemplate="/BOB",\n    Method = "POST",\n    BodyStyle = WebMessageBodyStyle.WrappedRequest)]\npublic string BOB (Stream streamdata)\n{\n    StreamReader reader = new StreamReader(streamdata);\n    string res = reader.ReadToEnd();\n    reader.Close();\n    reader.Dispose();\n    return "Received: " + res;\n}	0
15225357	15222675	Align an image to the left in a UINavigationBar	UINavigationBar.Appearance.SetBackgroundImage(image, UIBarMetrics.Default);	0
5418663	5411490	How can I Map a substring to a property with a Fluent Nhibernate Mapping Override?	public override(AutoMapping<MyClass> mapping) \n{\n    mapping.Map(x=>x.PartNumberPortion).Formula("SUBSTRING(PartNumber, 4, 20)");\n}	0
3518666	3472945	How to enable sorting on a DataGridView that is bound to a LINQ to Entities query?	q.sort();	0
15397193	15396073	GetRoomLists succeeds but returns no data	private List<string> GetConfRooms(string filter)\n{\n    List<string> sRooms = new List<string>();\n\n    DirectoryEntry deDomain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().GetDirectoryEntry();\n    DirectorySearcher dsRooms = new DirectorySearcher(deDomain);\n\n    dsRooms.Filter = string.Format("(&(&(&(mailNickname={0}*)(objectcategory=person)(objectclass=user)(msExchRecipientDisplayType=7))))", filter);\n\n    dsRooms.PropertiesToLoad.Add("sn");\n    dsRooms.PropertiesToLoad.Add("mail");\n\n    foreach (SearchResult sr in dsRooms.FindAll())\n    {\n        sRooms.Add(sr.Properties["mail"][0].ToString());\n    }\n\n    return sRooms;\n}	0
28189660	28189460	X-axis is inverted when changing from front to behind using RotateAround	camera.position += camera.transform.up * _LeftStickScale * _ComandValues[5]	0
10106437	10105396	Given an Automation Element how do i simulate a single left click on it	AutomationElement child = walker.GetFirstChild(el);\nSystem.Windows.Point p = child.GetClickablePoint();\nMouse.Move((int)p.X, (int)p.Y);\nMouse.Click(MouseButton.Left);	0
17194474	17136687	Composite C1 How would I rewrite this Sql update statement to work in c#?	for (int i = 0; i < q.Length; i++)\n{\n  var propimages = connection.Get<ALocal.propimage>().Where(o => o.PropId = propid && p.PropImageId = q[i]);\n  foreach (var o in propimages) \n  {\n     o.OrderSeq = i + 1;\n  }\n\n  connection.Update(propimages);\n}	0
24643228	24643195	Periodically Run a Method	public class Example\n{\n   private static Timer aTimer;\n\n   public static void Main()\n   {\n        // Create a timer with a two second interval.\n        aTimer = new System.Timers.Timer(2000);\n        // Hook up the Elapsed event for the timer. \n        aTimer.Elapsed += OnTimedEvent;\n        aTimer.Enabled = true;\n\n        Console.WriteLine("Press the Enter key to exit the program... ");\n        Console.ReadLine();\n        Console.WriteLine("Terminating the application...");\n   }\n\n    private static void OnTimedEvent(Object source, ElapsedEventArgs e)\n    {\n        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);\n    }\n}	0
5153095	5153068	How to get version of used dll	Assembly.GetCallingAssembly();\n        Assembly.GetExecutingAssembly();	0
14722363	14721633	Search items in the listbox using index	private void button1_Click(object sender, EventArgs e)\n{\n    int index = listBox1.FindString(textBox6.Text);\n    if (index > -1)\n    {\n        listBox1.SelectedIndex = index;\n    }\n}	0
33607084	30835887	Regex for Nested Quotes from bbcode	void Main()\n{\n    String s = "[quote=\"bob\"]I can't believe that you said this: [quote=\"joe\"]I love lamp.[/quote] That's hilarious![/quote]";\n    Regex r = new Regex(@"\[quote=""(\w+)""\](.*?)\[/quote]");\n    while (r.Match(s).Success)\n        s = r.Replace(s, "<fieldset class=\"bbquote\"><legend>$1</legend>$2</fieldset>");\n    Console.WriteLine(s);\n}	0
2053632	2053614	Output values of xml file in a text file with format	File.WriteAllLines( \n    XElement.Load(filename)\n            .Descendants("Keyword")\n            .Attributes("name")\n            .Select(n => "textbox.Settings.Keywords.Add(\"" + n.Value + "\");")\n            .ToArray()\n    );	0
30236094	30235849	How to make an anonymous type property nullable in the select of a linq to sql query	var testNull = (from student in studentList\n                select new\n                {\n                    RollNo = default(int?),\n                    Name = student.Name\n                }).ToList();	0
24076130	24075905	Json Deserialize Exception	var results = jsonObj["stations"].Children();	0
1416503	1416500	Initializing a string array in a method call as a parameter in C#	DoSomething(10, new[] {"One", "Two", "Three"});	0
6167574	6167543	How can I change an attribute value of a XML file in c#?	XmlDocument doc = new XmlDocument();\ndoc.Load("Your.xml");\nXmlNodeList elementList = doc.GetElementsByTagName("add");\nfor (int i = 0; i < elementList.Count; i++)\n{\n    if(elementList[i].Attributes["key"].Value == "A1")\n       elementList[i].Attributes["value"].Value = "NewValue";\n}	0
20305705	20305618	C# recursive method converting to loop	double SRloop(int n)\n{\n    var r = Math.Sqrt(2);\n\n    for (var i = 2; i <= n; i++)\n    {\n        r = Math.Sqrt(2 + r);\n    }\n\n    return r;\n}	0
20764938	20764834	change color of a cell in gridview	(e.Row.Cells[i].Text).Trim()	0
2040749	2040702	How to reverse a number as an integer and not as a string?	int n = 12345;\nint left = n;\nint rev = 0;\nwhile(left>0)\n{\n   r = left % 10;   \n   rev = rev * 10 + r;\n   left = left / 10;  //left = Math.floor(left / 10); \n}\n\nConsole.WriteLine(rev);	0
23618776	23618421	How to control post back progammatically?	protected void drp1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n//Check TextBox first\nif(TextBoxID.Text==string.Empty)\n{\n        int ProductID = Convert.ToInt16(drp1.SelectedValue);\n        DataTable Signing = new DataTable();\n        SqlConnection conn = new SqlConnection(connection);\n        SqlDataAdapter da = new SqlDataAdapter("SELECT SigningID, SigningDetail FROM dbo.Signing WHERE ProductID = "+ ProductID, conn);\n        conn.Open();\n        da.Fill(Signing);\n        conn.Close();\n        drp2.DataSource = Signing;\n        drp2.DataValueField = "SigningID";\n        drp2.DataTextField = "SigningDetail";\n        drp2.DataBind();\n        drp2.Items.Insert(0, new ListItem("---Select Signing Detail---", "0"));\n    }\n}	0
17960905	17960722	Changing the Value of an XElement	if (translate.Count > 0)\n        {\n            foreach (XText node in xml.Descendants().Nodes().OfType<XText>())\n            {\n                if (translate.ContainsKey(node.Value.ToLower()))\n                    node.Value = translate[node.Value.ToLower()];\n            }\n        }	0
5355198	5339999	How can i get the names from the selected ListViewItems?	private void listViewCards_KeyDown(object sender, KeyEventArgs e)\n{\n     IList selectedListViewItems = listViewCards.SelectedItems;\n     if (selectedListViewItems.Count > 1)\n     {\n         //delete all selected items from xml:\n         var collection = selectedListViewItems.Cast<XmlNode>();  //assuming your underlying data is XmlNode\n         foreach(XmlNode node in collection)\n         {\n             //do whatever you want to do with node\n             if (node.InnerText.Equals( ??? ))\n             {\n                 //mark for deleting\n             }\n         }\n     }\n}	0
33632935	33632746	C# Replicate This Code - JSON with Object with JSON	public class MoveItemValues\n{\n    public string Pile;\n    public Int64 Id;\n}\n\npublic class MoveItemRequestValues\n{\n    public IList<MoveItemValues> ItemData;\n\n    public MoveItemRequestValues()\n    {\n        ItemData = new List<MoveItemValues>();\n    }\n}\n\nstatic void MoveItem(Int64 itemId, string pile)\n{\n    string moveItemResponse;\n    MoveItemRequestValues bodyContent = new MoveItemRequestValues();\n    bodyContent.ItemData = new List<MoveItemValues>()\n    {\n        new MoveItemValues {Pile = pile, Id = itemId}\n    };\n    var camelCaseFormatter = new JsonSerializerSettings\n    {\n        ContractResolver = new CamelCasePropertyNamesContractResolver()\n    };\n    string jsonContent = JsonConvert.SerializeObject(bodyContent, camelCaseFormatter);\n    byte[] byteArray = Encoding.UTF8.GetBytes(jsonContent);\n    Console.WriteLine(jsonContent);\n}\n\nstatic void Main(string[] args)\n{\n    MoveItem(100997087277, "trade");\n    Console.ReadLine();\n}	0
8376839	3444331	How can I run RavenDB in a shared hosting environment?	public static class Store\n{\n    private static IDocumentStore store = createStore();\n\n    private static EmbeddableDocumentStore createStore()\n    {\n        var returnStore = new EmbeddableDocumentStore();\n        returnStore.DataDirectory = @"./PersistedData";\n        returnStore.Initialize();\n        return returnStore;\n    }\n\n    public static xxx Read(string key)\n    {\n        using (var session = store.OpenSession())\n        {\n\n            var anEntity = session.Query<xxx>().\n                Where(item => item.key == key).Single();\n            return anEntity;\n        }\n    }\n\n    public static void Write(xxx)\n    {\n        using (var session = store.OpenSession())\n        {\n            session.Store(xxx);\n            session.SaveChanges();\n        }\n    }\n}	0
32768548	32768218	How to extract SOAP Header from WS Response	var cookieIndex = OperationContext.Current.IncomingMessageHeaders.FindHeader("Cookie", "");\nXmlReader reader = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(cookieIndex).ReadSubtree();	0
18100529	18099257	Concat strings in a projection (Linq)	data = MyEntity.GetEntities(_db).OrderBy(a=> a.name)\n                .Select(b=> new NameIdentity\n                {\n                    ID = b.entityID,\n                    Name =  b.year +"-" + b.name\n                });	0
7697605	7697358	Setting a value in DataTable fires SelectedIndexChanged event	private TextBox_OntextChanged(object sender, EventArgs args)\n{\n    this.supressEvents = true;\n    //Do your stuff here\n    this.supressEvents = false;\n}\n\nprivate void ListBox_OnSelectionChanged(object sender, EventArgs args)\n{\n    if (this.supressEvents)\n    {\n        return;\n    }\n\n    //Do your stuff here\n}	0
6948395	6948312	Checking for existence of node in Linq to XML	XDocument doc = XDocument.Load("");\nvar x = (from node in doc.Descendants("sb_sbgp")\n     select new\n     {\n         title = node.Element("itemtitle").Value,\n         type = node.Element("itemtype").Value,\n         audience = (node.Element("sb_sbgp_audience") != null) ? node.Element("sb_sbgp_audience").Value : null\n     });	0
33478948	30144995	ASP.Net Create Two Models With One Controller	public MotorcycleViewModel GetModelData(int commentId, int postId)\n{\n    MotorcycleViewModel result =new MotorcycleViewModel();\n    using (var context = new CommentDBContext())\n    {\n       var post = (from pst in context.Post where pst.ID == postId  select pst).FirstOrDefault();\n       var comment = (from cmt in context.Comment where cmt.ID == commentId select cmt).FirstOrDefault();\n       result.CommentPointer = comment;\n       result.PostPointer = post;\n       return result;\n    }\n}	0
13135473	13134323	BitmapData size in windows mobile	var result = new Bitmap((int)info.width,(int)info.height,PixelFormat.Format24bppRgb);\nvar data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);\nint y, ptr = data.Scan0.ToInt32();\nint[] lines = new int[result.Height];\nfor (y = 0; y < lines.Length; y++)\n{\n    lines[y] = ptr;\n    ptr += data.Stride;\n}\nbool success = ReadFullImage(lines, ref info, ref png);\nresult.UnlockBits(data);\nif (!success)\n    return null;\nelse\n{\n    return result;\n}	0
8742590	8742047	How can you access icons from a Multi-Icon (.ico) file using index in C#	Stream iconStream = new FileStream ( @"C:\yourfilename.ico", FileMode.Open );\nIconBitmapDecoder decoder = new IconBitmapDecoder ( \n        iconStream, \n        BitmapCreateOptions.PreservePixelFormat, \n        BitmapCacheOption.None );\n\n// loop through images inside the file\nforeach ( var item in decoder.Frames )\n{\n  //Do whatever you want to do with the single images inside the file\n  this.panel.Children.Add ( new Image () { Source = item } );\n}\n\n// or just get exactly the 4th image:\nvar frame = decoder.Frames[3];\n\n// save file as PNG\nBitmapEncoder encoder = new PngBitmapEncoder();\nencoder.Frames.Add(frame);\nusing ( Stream saveStream = new FileStream ( @"C:\target.png", FileMode.Create ))\n{\n  encoder.Save( saveStream );\n}	0
16173679	16173631	RemotingServices.Marshal(foo, uri) only works for a short period of time. How to keep it working?	public override object InitializeLifetimeService(){\n  return null;\n}	0
20675784	20675667	Passing input parameters to controller method Html.BeginForm	[HttpPost]\n    public ActionResult GetPassword(YourModel yourmodel)\n    {\n        ViewModel model = new ViewModel();\n\n        model.VerifyUserExists(yourmodel.EmailForgotPassword);\n        return View(model);\n    }	0
21837886	21837248	How to pick an element into repeater in codebehind?	foreach (RepeaterItem item in repeatername.Items)\n        {\n          ((TextBox)item.FindControl("tbxKey")).Text = "hello";\n          ((LinkButton) item.FindControl("LinkButton")).Enabled = false;\n        }	0
17937052	17936880	Populating ComboBox Value with Object - Object is populated using XML Data	public class Item {\n   public string FullName {get;set;}\n   public string ID {get;set;}\n}\n//your array of Item\nItem[] items = ...\n//Bind your array to your combobox\ncomboBox.DataSource = items;\ncomboBox.DisplayMember = "FullName";\ncomboBox.ValueMember = "ID";	0
27413487	27407947	How to set BindingContext of multiple pages to the same ViewModel in Xamarin.Forms?	public static class ViewModelLocator\n{\n    private static MyViewModel _myViewModel = new MyViewModel();\n    public static MyViewModel MainViewModel\n    {\n        get\n        {\n            return _myViewModel;\n        } \n    } \n}\n\n...\n\npublic partial class MainView : ContentPage\n{\n    public MainView()\n    {\n        BindingContext = ViewModelLocator.MainViewModel;\n    }\n}\n\n...\n\npublic partial class SomeOtherView : ContentPage\n{\n    public SomeOtherView()\n    {\n        BindingContext = ViewModelLocator.MainViewModel;\n    }\n}	0
29662342	29662199	Casting ICollection to Collection and while casting their parameters as well	[NotMapped]\npublic IEnumerable<IUzytkownikGrupa> Uzytkownicy    {\n    get { return this.UzytkownicyEF; }\n}	0
9534095	9534059	Is possible to create a new route with only a action name?	routes.MapRoute(\n    "UnderConstruction", // Route name\n    "UnderConstruction", // URL with parameters\n    new { controller = "Alert", action = "UnderConstruction"} // Parameter defaults\n);\n\n//default route	0
18067392	18067290	Retrieving data from a dataset	foreach (DataRow row in usersDataset1.Administrators.Rows)\n{\n  //Do stuff here...\n}	0
5958171	5958129	wpf how to find a canvas inside a grid in a specific Row/column	int x = 0;\nint y = 1;\nvar target = (from UIElement c in grid.Children\n         where Grid.GetRow(c) == y && Grid.GetColumn(c) == x\n         select c).First();	0
16911318	16911294	Removing all methods from Eventhandler	private void RemoveClickEvent(Button b)\n{\n    FieldInfo f1 = typeof(Control).GetField("EventClick", \n    BindingFlags.Static | BindingFlags.NonPublic);\n    object obj = f1.GetValue(b);\n    PropertyInfo pi = b.GetType().GetProperty("Events",  \n    BindingFlags.NonPublic | BindingFlags.Instance);\n    EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);\n    list.RemoveHandler(obj, list[obj]);\n}	0
11169365	11169289	how to use same name class libraries on a solution	using xyz.myclassname;	0
16919453	16919376	which control is clicked in datagridview	TextBox tx = e.Control as TextBox;\n DataGridViewTextBoxCell cell = prol04DataGridView.CurrentCell as DataGridViewTextBoxCell;\n if (tx != null && cell != null && cell.OwningColumn == prol04DataGridView.Columns[5])\n {\n       tx.TextChanged -= new EventHandler(tx_TextChanged);\n       tx.TextChanged += new EventHandler(tx_TextChanged);\n\n }	0
7854022	7853744	.Net SimpleJson: Deserialize JSON to dynamic object	// NOTE: uncomment the following line to enable dynamic support.\n//#define SIMPLE_JSON_DYNAMIC	0
2646055	2646009	can some one help me how to use IList in c#	foreach(var item in MethodThatReturnsIList())\n{\n   // Do whatever\n}	0
4609444	4609412	Is there a "first run" flag in WP7	private static bool hasSeenIntro;\n\n    /// <summary>Will return false only the first time a user ever runs this.\n    /// Everytime thereafter, a placeholder file will have been written to disk\n    /// and will trigger a value of true.</summary>\n    public static bool HasUserSeenIntro()\n    {\n        if (hasSeenIntro) return true;\n\n        using (var store = IsolatedStorageFile.GetUserStoreForApplication())\n        {\n            if (!store.FileExists(LandingBitFileName))\n            {\n                // just write a placeholder file one byte long so we know they've landed before\n                using (var stream = store.OpenFile(LandingBitFileName, FileMode.Create))\n                {\n                    stream.Write(new byte[] { 1 }, 0, 1);\n                }\n                return false;\n            }\n\n            hasSeenIntro = true;\n            return true;\n        }\n    }	0
15748060	15747851	convert Dictionary<string, myClass> to List<double[]> using c# linq	List<double[]> list = rates\n            .GroupBy(pair => pair.Value.Class, pair => pair.Value.Value)\n            .Select(doubles => doubles.Select(d => d).ToArray())\n            .ToList();	0
2338985	2338402	faster implementation of sum ( for Codility test )	int equi ( int[] A ) {\n    int equi = -1;\n\n    long lower = 0;\n    long upper = 0;\n    foreach (int i in A)\n        upper += i;\n\n    for (int i = 0; i < A.Length; i++)\n    {\n        upper -= A[i];\n        if (upper == lower)\n        {\n            equi = i;\n            break;\n        }\n        else\n            lower += A[i];\n    }\n\n    return equi;\n}	0
6564884	6564841	Only show X and minimize button on wpf	ResizeMode="CanMinimize"	0
1399354	1399314	2 buttons in a view to perform different actions in asp.net mvc	public actionresult SomeMethod(FormCollection form)\n{\n  if (form.AllKeys.Contains("Button1")\n  {\n    doSomething();\n  }\n  else // assuming only two submit buttons\n  {\n    doSomethingElse();\n  }\n}	0
11790459	11784343	Facebook C# SDK Post to page wall Issue	parameters.actions = new\n            {\n                name = "title",\n                link = "http://website.com",\n            };	0
4548704	4548453	How to specify a day and time as breakpoint in sql?	Set DateFirst 3\nDeclare @CurrentDate datetime,\n        @Start datetime,\n        @End datetime\n\nSelect @CurrentDate = getdate()\n\nSelect  @Start = Case \n        When (DATEPART(DW, @CurrentDate) = 6 and DATEPART(hour, @currentDate) > 18)\n                or (DATEPART(DW, @CurrentDate) > 6 ) Then \n            DateAdd(day, ((7 - DATEPART(dw, @CurrentDate)+1) + 7), @CurrentDate)\n            Else DateAdd(day, ((7 - DATEPART(dw, @CurrentDate)+1)), @CurrentDate)\n         End\n\nSelect @End = DATEADD(day, 6, @start)\n\nSelect @CurrentDate, @Start, @End	0
2830242	2830146	How to use reflection to call a method and pass parameters whose types are unknown at compile time?	void Main(string[] args)\n{\n ClassA a = new ClassA();\n System.Type[] types = new Type[(args.Length -1) / 2];\n object[] ParamArray = new object[types.Length];\n\n for (int i=0; i < types.Length; i++)\n {\n      if(args[i*2 + 1].EndsWith("&"))\n    {\n        var type = System.Type.GetType(args[i*2 + 1].Substring(0,args[i*2 +1].Length - 1)); \n        ParamArray[i] = Convert.ChangeType(args[i*2 + 2],type);\n        types[i] = System.Type.GetType(args[i*2 + 1]);\n    }\n    else\n    {\n        types[i] = System.Type.GetType(args[i*2 + 1]);\n        ParamArray[i] = Convert.ChangeType(args[i*2 + 2],types[i]);\n    }      \n }\n\n MethodInfo callInfo = typeof(ClassA).GetMethod(args[0],types);\n callInfo.Invoke(a, ParamArray);	0
10372445	10372360	How to get Mac and IP address using ASP.NET C# of the login User	using System.Net;\n\nPrivate string GetIP()\n{\nstring strHostName = "";\nstrHostName = System.Net.Dns.GetHostName();\n\nIPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);\n\nIPAddress[] addr = ipEntry.AddressList;\n\nreturn addr[addr.Length-1].ToString();\n\n}	0
2152888	2152883	Get Email ID Formate from string?	var regex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled);    \nvar s = "Yunnan Coffee with the scientific name-Coffee test@example.com Arabica L was the variation of Arabia Coffee.";\nforeach (Match email in regex.Matches(s))\n{\n    Console.WriteLine(email.Value);\n}	0
2410093	2410088	How do I convert a binary file to a byte array?	File.ReadAllBytes(@"C:\MyPicture.jpg")	0
7584402	7584074	how to read xml data from a DATASET object in c#	public XmlDocument document = new XmlDocument();\ndocument.LoadXml(ds.GetXml());\nXmlNode ht = document.DocumentElement.SelectSingleNode("/Schedule/AudioVedioPlayer/Height");	0
586455	586356	How to let the user to download an xml file	FileInfo file = new FileInfo(filePath); // full file path on disk\nResponse.ClearContent(); // neded to clear previous (if any) written content\nResponse.AddHeader("Content-Disposition", \n    "attachment; filename=" + file.Name);\nResponse.AddHeader("Content-Length", file.Length.ToString());\nResponse.ContentType = "text/xml"; //RFC 3023\nResponse.TransmitFile(file.FullName);\nResponse.End();	0
6389926	6389867	LINQ To XML Getting a value without the nodes inside	var element = XElement.Parse(@"<chunk type=""manufacturer_info"" ...");\n\nvar result = string.Concat(element.Nodes().OfType<XText>());\n// result == "test: "	0
2426875	2426746	How to work with a generic dictionary in a generic dictionary?	Dictionary<string, KeyValuePair<string, File>>	0
16017409	16017188	How to trim decimal?	decimal a = (decimal) 0.8537056986486486486486486486;\nString test = (Math.Truncate(100000000 * a) / 100000000).ToString();	0
29079929	29079797	Remove hyperlink from all the excel cells in a xls (MS-Interop) document using c#	ClearHyperlinks()	0
17587512	17587308	Is there a performance sacrifice when calling a C# helper from razor?	User.GetFriendlyName()	0
7461682	7460564	Creating a breadcrumb like hierarchy using LINQ	var image = db.Images.FirstOrDefault(i => i.Id == currImageId);\n\nvar imagesHierarchy = new List<Image>();\nif (image != null)\n{\n    var parent = image.Parent;\n    while (parent != null)\n    {\n        imagesHierarchy.Insert(0, parent);\n        parent = parent.Parent;\n    }\n}\n\nvar breadcrumb = string.Join(" > ", imagesHierarchy.Select(i => i.Name));	0
18522121	18521912	Put Windows Store App images into another assembly?	ms-appx:///MyImageLibrary/Images/foo.jpg	0
31685703	31685597	How to fix mono using 100% CPU?	cpulimit -l 50 COMMAND	0
28392368	28391737	Datastructure algorithm needs an explanation	List<Tuple<int, int>> input = new List<Tuple<int, int>>\n{\n    new Tuple<int, int>(5,4),\n    new Tuple<int, int>(6,2),\n    new Tuple<int, int>(9,3),\n    new Tuple<int, int>(2,5),\n    new Tuple<int, int>(4,9)\n};\n\nList<Tuple<int, int>> output = new List<Tuple<int, int>>();\n\nvoid Main()\n{   \n    var firstTuple = input.First(item => !(input.Exists(item1 => item1.Item2 == item.Item1)));  \n    output.Add(firstTuple);\n    AddNextTuple(output[0]);\n    AddNextTuple(output[1]);\n    AddNextTuple(output[2]);\n    AddNextTuple(output[3]);\n    // Output: (6,2),(2,5),(5,4),(4,9),(9,3)\n}\n\nvoid AddNextTuple(Tuple<int, int> current){\n    output.Add(input.First(item1 => input.Exists(item => item1.Item1 == current.Item2)));   \n}	0
19208444	19208272	Loading the information from a 2D-Array in a class so it can be used in the main class. C# Wpf	namespace WpfApplication1\n       {\n       class Da_Ba\n       {\n       public int[,] db_array; \n       public void GetDB()\n       {\n       db_array = new int[100, 10];\n       db_array[0, 1] = 10;\n       }}}	0
28257225	28257179	c# windows app writing text to file	if (p2 > 210 && p2 < 235 && p1 > 339 && p1 < 367) \n  { \n        string dave = Environment.NewLine + Text3.Text + "," + Text4.Text;\n        File.WriteAllText(@"C:\myfile.txt", dave);\n  }	0
6074437	6074387	Compare datetime without millisecond	DateTime a, b;\n// fill a and b with the values you need\nif (Math.Abs((a-b).TotalSeconds) < 1)\n    Console.WriteLine("File doesn't need to be copied");\nelse\n    Console.WriteLine("File needs to be copied");	0
16761629	16761539	How to perform a double loop jump?	void f () {\n        foreach(string s in list) {\n            switch(j) {\n                case 1:\n                //do something\n                return; \n                case 2:\n                //do another\n                continue;//break \n                ..other cases;\n             }\n         //do some stuff\n        }\n}\n\n// ... later somewhere\nwhile (condition) {\n    f();\n}	0
13855102	13855028	How to remove all unwanted TreeView Branches	//DISCLAIMER: I didn't compile or test this method.\nvoid TrimTree(TreeNodeCollection nodes, List<string> l)\n{\n    TreeNode node = null;\n    for (int ndx = nodes.Count; ndx > 0; ndx--)\n    {\n        node = nodes[ndx - 1];\n        TrimTree(node.ChildNodes, l);\n        if (node.ChildNodes.Count  == 0 && !l.Contains(node.Value))\n            nodes.Remove(node);\n    }\n}	0
11816931	11816761	Insert new item into WPF listbox before the old items	ListBox.Items.Insert(0, "Message");	0
12145581	12145540	How to split string based on another string	string splittedFileName = fileName.Split(new string[]{"REINSTMT"},\n                                                  StringSplitOptions.None)[0];	0
18404180	18403897	How to create a buy application prompt on a certain amount of start-up times	writer.BaseStream.Length % 2 == 0	0
22472393	22472020	Adding font color to text in Windows Phone 8 Application	(App.Current.Resources["PhoneForegroundBrush"] as SolidColorBrush).Color = Colors.Purple;	0
4467426	4467412	Cannot assign a delegate of one type to another even though signature matches	// C# 2, 3, 4 (C# 1 doesn't come into it because of generics)\nBinaryOperation b1 = new BinaryOperation(addThem);\n\n// C# 3, 4\nBinaryOperation b1 = (x, y) => addThem(x, y);\nvar b1 = new BinaryOperation(addThem);	0
3640224	3640174	Generating every character combination up to a certain word length	int maxlength = 12;\n    string ValidChars;\n    private void Dive(string prefix, int level)\n    {\n        level += 1;\n        foreach (char c in ValidChars)\n        {\n            Console.WriteLine(prefix + c);\n            if (level < maxlength)\n            {\n                Dive(prefix + c, level);\n            }\n        }\n    }	0
16417487	16412077	Get executing assembly name from referenced DLL in MonoTouch?	var path = System.Reflection.Assembly.GetExecutingAssembly ().Location;\nvar name = System.IO.Path.GetFileName (path);	0
32120929	32119246	How to create a Loading screen in Unity?	public void onButtonClick() {\n  StartCoroutine(DisplayLoadingScreen(levelToLoad));\n}	0
8841454	8841129	Regex + Remove all text before match	string test = "hello, test matching";\n\nstring regexStrTest;\nregexStrTest = @"test\s\w+";       \nMatchCollection m1 = Regex.Matches(test, regexStrTest);\n//gets the second matched value\nstring value = m1[1].Value;	0
31556889	31556725	How can i set visible to true value in c# thread?	chart1.Dispatcher.Invoke(() =>chart1.Visible = true);	0
9301945	9299928	Creating a nested OR statement using NHibernate Criteria API	var disjunction = new Disjunction()\n    .Add(Restriction.Eq("WindowID", item1))\n    .Add(Restriction.Eq("WindowID", item2))\n    .Add(Restriction.Eq("WindowID", item3));\n// Or use a loop if you like...\n\nvar list = CurrentSession.CreateCriteria<Table1Entity>()\n    .Add(Restrictions.Eq("ColorID", colorID))\n    .CreateCriteria("Table2EntityList")\n    .Add(disjunction);	0
29106885	29106350	Query string from C# using UNION - VarChar to Numeric error	string strSQL = "SELECT DISTINCT CAST(LTRIM(RTRIM(CIT_NBR)) AS Decimal(12,2)) AS CIT_NBR \nFROM VW_MOS_DPL_AccountValidation \nWHERE CUST_NUM = '" + TBAccountNum.Text + "' \nUNION \nSELECT 0.0\nORDER BY CAST(LTRIM(RTRIM(CIT_NBR)) AS Decimal(12,2)) DESC";	0
21421100	21420951	How to get the 'access_token' in Facebook App for Unity3D	FB.UserId	0
1404484	1404454	java to c# how to do custom painting in a panel	protected override void OnPaint(PaintEventArgs pe)\n{\n  Graphics gfx = pe.Graphics;\n  using (Pen pen = new Pen(Color.Blue))\n  {\n    gfx.DrawEllipse(pen, 10,10,10,10);\n  }\n}	0
14724876	14724822	How Can I add properties to a class on runtime in C#?	typeBuilder.SetParent(typeof(MyClass));\ntypeBuilder.DefineProperty("Prop1", ..., typeof(System.Int32), null);\n...	0
10446427	10446314	Change Label.Text in nested Master Pages from Content on button click	ContentPlaceHolder plchldr= this.Master.Master.FindControl("YourMainMasterContentID") as ContentPlaceHolder;\n            Label lbl = plchldr.FindControl("lblText") as Label;\n             if(lbl !=null)\n             { \n               lbl.Text="SomeText"\n             }	0
33463343	33463224	Set 'cshtml' data and return a string	string template = yourHtmlCodeAsString;\nstring result = Razor.Parse(template, new { ConfirmLink = "http://.../" });	0
697388	697227	Is there a way to create a second console to output to in .NET when writing a console application?	ProcessStartInfo psi = new ProcessStartInfo("cmd.exe")\n{\n    RedirectStandardError = true,\n    RedirectStandardInput = true,\n    RedirectStandardOutput = true,\n    UseShellExecute = false\n};\n\nProcess p = Process.Start(psi);\n\nStreamWriter sw = p.StandardInput;\nStreamReader sr = p.StandardOutput;\n\nsw.WriteLine("Hello world!");\nsr.Close();	0
32577578	32577289	How to change Font Name from TextFrame in adobe illustrator?	textFrame[FrameNumber].textRange.characterAttributes.textFont.name = app.textFonts.getByName("FontFamilyName");	0
28336756	28336370	How to remove duplicate row from datagridview in c#?	DataTable items = new DataTable();\nitems.Columns.Add("Backsn");\nitems.Columns.Add("Oprn Name");\nfor (int i = 0; i < dataGridView1.Rows.Count;i++ )\n{\n   DataRow rw = items.NewRow();\n   rw[0] = dataGridView1.Rows[i].Cells[2].Value.ToString();\n   rw[1] = dataGridView1.Rows[i].Cells[8].Value.ToString();\n   if (!items.Rows.Cast<DataRow>().Any(row => row["Backsn"].Equals(rw["Backsn"]) && row["Oprn Name"].Equals(rw["Oprn Name"])))\n       items.Rows.Add(rw);\n}	0
13464395	13461702	XNA - Extract rotation vector (angles) from world matrix	world.Decompose(out traslation, out rotation , out scale);	0
20311094	20311055	parsing multiple elements from a node without knowing their names	var xdoc = XDocument.Load(path_to_xml);\nvar section1 = xdoc.Descendants("set") // or xdoc.Root.Elements()\n                   .ToDictionary(s => (string)s.Attribute("name"),\n                                 s => (string)s);\n\nvar set2 = section1["set2"]; // "value2"	0
32974884	32974486	Getting dir from .txt file	string dir="";\nusing(StreamReader sr=new StreamReader("FileToGetDirFrom.txt")\n{\n  dir=sr.ReadLine();\n}	0
15879755	15832049	Trying to update single row in SQL database using LINQ to SQL using a WCF service	DailySale d = new DailySale();\n            var query = (from q in cont.DailySales where q.Date.Equals(Date) select q);\n\n\n            foreach (var z in query)\n            {\n                counter++;\n            }\n\n\n            if (counter>0)\n            {\n                foreach (var r in query)\n                {\n\n                    r.Takings = r.Takings + (decimal)price; //  here i was using d instead of r\n                    r.Profit = r.Takings - r.Expenses;\n                }\n                cont.SubmitChanges();	0
3435503	3435485	Linq - Group by multiple tables	var orders = from o in Orders \n            select new { IsOrder = true, o.Date };\nvar calls = from c in Calls \n            select new { IsOrder = false, c.Date };\n\nvar result = from x in orders.Concat(calls)        \n            group x by x.Date into og\n            select new {Date = og.Key, Orders= og.Count(o=>o.IsOrder), Calls = og.Count(c=>!c.IsTrue)};	0
11432537	11432374	How to compile a .NET source file into executable using PHP?	exec("gmcs -pkg:dotnet toolbar.cs");	0
6905726	6905640	registering a dll in GAC	Mscorcfg.msc	0
21847323	21845298	C# How to Retrieve DateSet Value in SqlDataAdapter?	adapter.Fill(dataSet);	0
6164202	6164155	Using Linq with a DbDataReader	mList.AddRange(from t in lReader.AsEnumerable() \n                select new MyObject { Name = t.GetString(0) });	0
32025489	32025270	Find if a full video was watched with unity ads	if(Advertisement.IsReady("rewardedVideoZone")) {\n    var showOptions = new ShowOptions();\n    showOptions.resultCallback += ResultCallback;\n    Advertisement.Show("rewardedVideoZone", showOptions);\n}\n\nprivate void ResultCallback (ShowResult result) {\n    if(result == ShowResult.Finished) {\n        currency += 10;\n    }\n    else {\n        Debug.Log ("No award given. Result was :: "+result);\n    }\n}	0
8622122	8621788	Cannot access data object after dispose even though its a list	List<AdSlot> list;\nusing(var dbc = new DbDataContext())\n{\n    var loadOptions = new DataLoadOptions();\n    loadOptions.LoadWith<AdSlot>(n => n.AdSize);\n    dbc.LoadOptions = loadOptions;\n\n    list = dbc.AdSlots.Where(a => a.PublisherId == publisherId).ToList();\n}\n\nViewData["AdSlots"] = list;	0
27860236	27860137	Invalid ConnectionString format for parameter "Version 3"	Version=3;	0
22976565	22968761	How to serialize Name/Value pairs as Attributes	public class MyStuff : IXmlSerializable {\n    public string Name { get; set; }\n\n    public List<Annotation> Annotations { get; set; }\n\n    public XmlSchema GetSchema() {\n        return null;\n    }\n\n    public void ReadXml(XmlReader reader) {\n        // customized deserialization\n        // reader.GetAttribute() or whatever\n    }\n\n    public void WriteXml(XmlWriter writer) {\n        // customized serialization\n        // writer.WriteAttributeString() or whatever\n    }\n\n}	0
21382111	21381817	Is my logic correct? I'm trying to get data from combobox(dropdownlist) and use that data to search and display information in checkedlistbox	string strMedications = "SELECT medicationName FROM MEDICATION WHERE medicationType=   ('" + selectedMedication + "')";	0
4498419	4498396	Exception in property when setting a binary value	private byte[] m_ImageTIFF;\npublic byte[] ImageTIFF \n{\n  get{...}\n  set { m_ImageTIFF = value;}\n}	0
1634325	1634264	Is there a way to find a control's owner thread?	private Thread GetControlOwnerThread(Control ctrl)\n{\n    if (ctrl.InvokeRequired)\n        ctrl.BeginInvoke(\n            new Action<Control>(GetControlOwnerThread),\n            new object[] {ctrl});\n    else\n        return System.Threading.Thread.CurrentThread;\n}	0
12004078	12003907	Breaking code into manageable chunks	#region Tab 1\n#region Variables\n#endregion\n#region Properties\n#endregion\n#region Methods\n#endregion\n #endregion	0
13157694	13157514	Split and Export a Database Table Based on Size	public void Export( int fileSize )\n{\n    SqlDataReader reader = // command to return the recordset to export...\n\n    int bytesLeft = fileSize;\n\n    // open first output file\n    while ( reader.Read() )\n    {\n        // write the row\n        bytesLeft -= // length of the row you just wrote\n\n        if ( bytesLeft <= 0 )\n        {\n            // close this file\n            // open the next file\n            bytesLeft = fileSize;\n        }\n    }\n\n    // close the last file.\n}	0
9900026	9899984	WITH(nolock) in every SELECT - NHibernate	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED	0
15674650	15674607	Add column to DataTable and move columns to right	DataTable workTable = new DataTable("Customers");\n\n    DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));\n    workCol.AllowDBNull = false;\n    workCol.Unique = true;\n\n    workTable.Columns.Add("CustLName", typeof(String));\n    workTable.Columns.Add("CustFName", typeof(String));\n    workTable.Columns.Add("Purchases", typeof(Double));	0
6545386	6536965	Update a document inside a document and inside a document	var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings._id", settingId)); \nvar update = Update.AddToSetWrapped("Settings.Overrides", overrideViewModel.ToBsonDocument()); \nRun(database => database.Applications().Update(query, update, UpdateFlags.Upsert, SafeMode.True));	0
16419180	16419136	Trimming the end of a last element of a List	int lastPos = lstTopicsDisplay.Count - 1;\n lstTopicsDisplay[lastPos] = lstTopicsDisplay[lastPos].TrimEnd(';')	0
3458058	3458046	How to include quotes in a string	"I want to learn \"C#\""	0
25113089	25112997	Windows store publishing bug or something else	App submission and certification	0
23997079	23996564	How to get metadata custom attributes?	var type = typeof (T);\nvar metadataType = type.GetCustomAttributes(typeof(MetadataTypeAttribute), true)\n    .OfType<MetadataTypeAttribute>().FirstOrDefault();\nvar metaData = (metadataType != null)\n    ? ModelMetadataProviders.Current.GetMetadataForType(null, metadataType.MetadataClassType)\n    : ModelMetadataProviders.Current.GetMetadataForType(null, type);\n\nvar propertMetaData = metaData.Properties\n    .Where(e =>\n    {\n        var attribute = metaData.ModelType.GetProperty(e.PropertyName)\n            .GetCustomAttributes(typeof(ExportItemAttribute), false)\n            .FirstOrDefault() as ExportItemAttribute;\n        return attribute == null || !attribute.Exclude;\n    })\n    .ToList();	0
20185093	20185084	Easiest way to convert list to a comma separated string by a Specific Property?	string sCategories = string.Join(",", categories.Select(x => x.Name));	0
20401917	20401165	Find data at a specified interval	Declare @int INT\nSet @int = 45\nSELECT * FROM Table WHERE OtherID='A' AND (@int Between MinNumber And MaxNumber)	0
10813673	10813053	Handling Master Page Panels with Base Control Class	public newManageClass()\n{\n    private oldManagedVBClass _old;\n\n    //.ctor\n    public newManageClass()\n    {\n        _old = new oldManagedVBClass();\n    }\n\n    public void makePanelsVisible()\n    {\n        _old.MakePanelsVisible();\n    }\n}	0
7209655	7209568	String split with delimiter in C#/ASP.Net	void Main()\n{\n    string text = "Hello, how are you?";\n    List<SplitDefinition> splitDefinitionList = CustomSplit(text, new char[] { 'h', 'o' });\n}\n\npublic List<SplitDefinition> CustomSplit(string source, char[] delimiters)\n{\n    List<SplitDefinition> splitDefinitionList = new List<SplitDefinition>();\n\n    foreach(char d in delimiters)\n    {\n        SplitDefinition sd = new SplitDefinition(d, source.Split(d));           \n        splitDefinitionList.Add(sd);\n    }\n\n    return splitDefinitionList;\n}\n\npublic class SplitDefinition\n{\n    public SplitDefinition(char delimiter, string[] splits)\n    {\n        this.delimiter = delimiter;\n        this.splits = splits;\n    }\n\n    public char delimiter { get; set; }\n    public string[] splits { get; set; }\n}	0
4868701	4860430	Is there a way to set HttpResponse?	protected void SetFormValue(string key, string value)\n{\n    var collection = HttpContext.Current.Request.Form;\n\n    // Get the "IsReadOnly" protected instance property. \n    var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);\n\n    // Mark the collection as NOT "IsReadOnly" \n    propInfo.SetValue(collection, false, new object[] { });\n\n    // Change the value of the key. \n    collection[key] = value;\n\n    // Mark the collection back as "IsReadOnly" \n    propInfo.SetValue(collection, true, new object[] { });\n}	0
25132220	25123394	How to load the data from Parse synchronously?	findObjectsInBackgroundWithBlock:	0
934942	934930	Can I change a private readonly field in C# using reflection?	typeof(Foo)\n   .GetField("bar",BindingFlags.Instance|BindingFlags.NonPublic)\n   .SetValue(foo,567);	0
5785893	5785794	How to make compilation different between Debug against Release?	[Conditional("DEBUG")]\npublic static void DebugLog(string fmt, params object[] args) {\n    // etc..\n}	0
23170296	22272114	NLog filter by LogLevel as MappedDiagnosticsContext	rule92.Filters.Add(new ConditionBasedFilter { Condition = "(equals('${mdc:ModuleCoreLogLevel}', 'LogLevel.Trace') and level < LogLevel.Trace)", Action = FilterResult.IgnoreFinal });	0
16192320	16192253	Add new data with Entity Framework	public void AddDevelopperButton_Click(object sender, EventArgs e)\n{\n    this.AddDevelopper(txb_name.Text, txb_firtname.Text);\n}\n\npublic Developper AddDevelopper(string name, string firstName)\n{\n    Developper devAdded = new Developper();\n    devAdded.Name = name;\n    devAdded.FirstName = firstName;\n\n    using(BugTrackerDBContainer db = new BugTrackerDBContainer())\n    {\n        db.AddToDevelopper(devAdded);\n        db.SaveChanges();\n    }\n    return devAdded;\n}	0
10373299	10372736	How to read graphic image from database and paste it to clipboard as a file?	public static void CopyLogo(Company company)\n    {\n        if (company.CompanyLogo != null)\n        {\n            MemoryStream ms = new MemoryStream(company.CompanyLogo.Image, 0, company.CompanyLogo.Image.Length);\n\n            using (ms)\n            {\n                //saving image on current project directory\n                Image img = Image.FromStream(ms);\n                img.Save(Environment.CurrentDirectory+"\\"+ company.CompanyLogo.Name);\n\n                //copying to clipboard\n                StringCollection paths = new StringCollection();\n                paths.Add(Environment.CurrentDirectory + "\\" + company.CompanyLogo.Name);\n                Clipboard.SetFileDropList(paths);\n            }\n\n        }\n    }	0
14370657	14370574	How to query child tables values	var result = poHeaders.Where(e => e.PODetails.Any(a => a.ItemId == intItemId));	0
5556932	5556917	writing a foreach statement to loop within a collection	foreach (ObjectID id in TheListOfIDs)\n{\n   // Just for example...\n   int x = id.ObjectID;\n   byte b = id.Var1;\n}	0
6030380	6030360	return code of console application	echo %errorlevel%	0
4364255	4364228	summing selected values of datagridview	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n    {\n        for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)\n        {\n            if (!dataGridView1.SelectedCells.Contains(dataGridView1.Rows[i].Cells["cLoadName"]))\n            {\n                float nextNumber = 0;\n                float sumNumbers = 0;\n\n                    if (float.TryParse(dataGridView1.SelectedCells[i].FormattedValue.ToString(), out nextNumber))\n                        sumNumbers += nextNumber;\n\n\n                tsslSumSelected.Text = "????: " + sumNumbers;\n                tsslTotalSelected.Text = "?????????: " + dataGridView1.SelectedCells.Count.ToString();\n            }\n            else\n            {\n\n            }\n        }    \n\n    }	0
5866428	5866366	How do I detect selected items in a Telerik grid & updated their values in the database?	Telerik.Web.UI.GridDataItem Row = (Telerik.Web.UI.GridDataItem)chkIsActive.NamingContainer;	0
33714965	33714499	How to improve the following code	-- your code, reduced\nif (!IsPostBack)\n{\n    var dataSource = BindDDlCategory();\n    PrepareDDL(ddlCategory, dataSource);\n    PrepareDDL(ddlCategoryNP, dataSource);\n}\n\n-- new method\nprivate void PrepareDDL(DropDownList ddl, DataTable dataSource)\n{\n    ddl.DataSource = dataSource;\n    ddl.DataTextField = "Name";\n    ddl.DataValueField = "Id";\n    ddl.DataBind();\n\n    string message = ddl.Items.Count\n        ? "N??o h?? nenhuma categoria cadastrada"\n        : "Todas as categorias";\n    ddl.Items.Insert(0, new ListItem(message, "108", true));\n}\n\n-- and the existing method\nprotected DataTable BindDDlCategory()\n{\n    return new Read().Category();\n}	0
30114237	30113910	Passing a property through lambda expression, and sorting on its properties	var sortedList = list.OrderBy(x => expr(x).PropertyA)\n                     .ThenBy(x => expr(x).PropertyB)\n                     .ToList();	0
33922901	27090547	Implement JWT authentication	var securityKey = new InMemorySymmetricSecurityKey(Encoding.Default.GetBytes("MySecretKey"));\nvar header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest));\nvar payload = new JwtPayload();\n\nvar claims = new List<Claim>\n{\n    new Claim(ClaimTypes.Email, "jdoe@gmail.com"),\n    ...\n};\n\npayload.AddClaims(claims);\n\n// if you need something more complex than string/string data\npayload.Add("tags", new List<string> { "admin", "user" });\n\nvar token = new JwtSecurityToken(header, payload);\nvar tokenString = securityTokenHandler.WriteToken(token);	0
15201046	4625825	Catching Exceptions in WPF at the FrameWork Level	protected override void OnStartup(StartupEventArgs e)\n{\n  Application.Current.DispatcherUnhandledException +=\n    new DispatcherUnhandledExceptionEventHandler(DispatcherUnhandledExceptionHandler);\n\n  base.OnStartup(e);\n}\n\nvoid DispatcherUnhandledExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs args)\n{\n  args.Handled = true;\n  // implement recovery\n  // execution will now continue...\n}	0
17754168	17754097	LINQ to SQL two contexts	db = context1\ndb2 = context2\n\nvar upcId = (from p in db2.PROD_SKU \n            where p.UPC_NBR.ToString() == upc\n            select p.pID).Single();\n\nvar query = from m in db.Merch\n            join d in db.Dept on m.merchDept equals d.deptID.ToString()         \n            join f in db.FOB on d.fobCode equals f.fobID\n            join w in db.Item on m.merchID equals w.merchID\n            join i in db.Doc on m.merchID equals i.MerchID\n                        where m.pID == upcId;	0
24458548	24456366	opening binary files from SQL using LINQ	private byte[] GetData(int id)\n    {\n        byte[] data = (from a in sd.UDocuments\n            where a.DocID == id\n            select a.DocData).First().ToArray();\n       return data;\n    }\n\nprotected void GridView1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        int docid = Convert.ToInt16(GridView1.SelectedRow.Cells[1].Text);\n        string name = GridView1.SelectedRow.Cells[2].Text;\n        string contentType = GridView1.SelectedRow.Cells[3].Text;\n\n        Response.Clear();\n        Response.ContentType = contentType; //"application/octet-stream";\n        Response.AddHeader("Content-Disposition", "attachment;filename=" + name);\n        Response.BinaryWrite(GetData(docid));\n        Response.End();\n    }	0
8491381	8490977	Windows Live Writer Automation	static void Main(string[] args)\n{\n\n    WindowsLiveWriterApplication wlw = new WindowsLiveWriterApplication();\n    ((IWindowsLiveWriterApplication2)wlw).BlogThisHtml("test", "testhtml");\n\n}	0
15533221	15530693	Check ListBox before Adding New Item	if (!string.IsNullOrEmpty(TeamNameTextBox.Text))\n{\n    if (!TeamNameListBox.Items.Contains(TeamNameTextBox.Text))\n    {\n        TeamNameListBox.Items.Add(TeamNameTextBox.Text);\n    }\n    else\n    {\n        // item already exists in listbox\n    }\n}\nelse\n{\n    // textbox is empty\n}	0
9514248	9514213	C# - how to retrieve items you ave added using Attributes.Add?	TextBox1.Attributes["type"]	0
11295167	11295016	Telerik RadDatePicker Control	DateTime? selectedDate = RadDatePicker1.SelectedDate;\n//to string\nstring date="";\nif(selectedDate!=null)\n{\n   date=selectedDate.Value.ToShortDateString();//or selectedDate.Value.ToString("d");\n}\nelse\n{\n   //handle the case when user has not selected any date, and selectedDate is null\n}	0
5968375	5968074	equivalent CreateGraphics in wpf	public class MyControl : Control {\n\n    public MyControl() {\n       this.Rects = new ObservableCollection<Rect>();\n       // TODO: attach to CollectionChanged to know when to invalidate visual\n    }\n\n    public ObservableCollection<Rect> Rects { get; private set; }\n\n    protected override void OnRender(DrawingContext dc) {\n        SolidColorBrush mySolidColorBrush  = new SolidColorBrush();\n        mySolidColorBrush.Color = Colors.LimeGreen;\n        Pen myPen = new Pen(Brushes.Blue, 10);\n\n        foreach (Rect rect in this.Rects)\n            dc.DrawRectangle(mySolidColorBrush, myPen, rect);\n    }\n}	0
6818631	6818069	Get TreeViewItem's parent in HierarchicalDataTemplate in WPF	public static class TreeViewItemExtensions\n{\n    public static int GetDepth(this TreeViewItem item)\n    {\n        DependencyObject target = item;\n        var depth = 0;\n        while (target != null)\n        {\n            if (target is TreeView)\n                return depth;\n            if (target is TreeViewItem)\n                depth++;\n\n            target = VisualTreeHelper.GetParent(target);\n        }\n        return 0;\n    }\n}	0
18794489	18794468	Get value from specific row	int qNum = query.Skip(2).First().questionId;	0
7939517	7939339	How to write a transaction to cover Moving a file and Inserting record in database?	// Wrap a file copy and a database insert in the same transaction\nTxFileManager fileMgr = new TxFileManager();\nusing (TransactionScope scope1 = new TransactionScope())\n{\n    // Copy a file\n    fileMgr.Copy(srcFileName, destFileName);\n\n    // Insert a database record\n    dbMgr.ExecuteNonQuery(insertSql);\n\n    scope1.Complete();\n}	0
32848264	32846281	Get specific data row in gridview?	var studentID = grvRow.Cells[0].Text;\nvar courseNumber = grvRow.Cells[1].Text;	0
7634827	7613267	how can I get the first element of a XElement	var desireElement = new XElement(existXElement.Where(w => (string)w.Attribute("title") == "Javascript").First());\n\n desireElement.RemoveNodes();	0
1064302	1064284	How can I add an extra item in this LINQ query?	var groupings =\n    from agency in agencies\n    from businessUnit in agency.BusinessUnits\n    from client in businessUnit.Clients\n    group client by new { businessUnit.ID, businessUnit.Name } into clients\n    select clients;\n\nvar businessUnits =\n    from grouping in groupings\n    select new\n    {\n        ID = grouping.Key.ID,\n        Name = grouping.Key.Name,\n        AmountSpent = grouping.Sum(client => client.AmountSpent),\n        Clients = grouping\n    };	0
2463025	2462441	Can I convert a Stream object to a FileInfo object?	public ExcelPackage( Stream stream ) {\n    _package = Package.Open( stream, FileMode.Create, FileAccess.ReadWrite );\n\n    Uri uriDefaultContentType = new Uri( "/default.xml", UriKind.Relative );\n    PackagePart partTemp = _package.CreatePart( uriDefaultContentType, "application/xml" );\n\n    XmlDocument workbook = Workbook.WorkbookXml; \n\n    _package.CreateRelationship( Workbook.WorkbookUri, TargetMode.Internal, schemaRelationships + "/officeDocument" );\n\n    _package.DeletePart( uriDefaultContentType );\n}	0
17846569	17845431	I need a dynamic collection type that exposes the array	Array.Resize()	0
29132556	29132441	ASP.NET set default value for cookies	public int CookieWidth {\n  get {\n    int width;\n    var str = String.Format("{0}", cookie["width"]);\n    if (!Integer.TryParse(str, width)) {\n      width = 1;\n    }\n    return width;\n  }\n  set {\n    cookie["width"] = value;\n  }\n}	0
18164665	18163527	How to add new grid rows without clearing existing data	protected void Page_Load(object sender, EventArgs e)\n{      \n    if (!Page.IsPostBack)\n    {           \n        AddNewRow();\n    }        \n}\n\nprivate void AddNewRow()\n{           \n    DataTable dt = new DatatTable(); \n    dt.Columns.Add("sno");\n    dt.Columns.Add("name");\n    foreach (GridViewRow gvRow in gvCommissions.Rows)\n    {\n        DataRow dr = dt.NewRow();\n        dr["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;\n        dr["name"] = ((Label)gvRow.FindControl("txtName")).Text;\n        dt.Rows.Add(dr);\n    }\n\n    DataRow dr1 = dt.NewRow();\n    dr1["sno"] = "";\n    dr1["name"] = "";\n    dt.Rows.Add(dr1);\n\n    gvCommissions.DataSource = dt;\n    gvCommissions.DataBind();\n\n}\n\n\nprotected void btnAddRow_Click(object sender, EventArgs e)\n{\n    AddNewRow();            \n}	0
13622087	13621814	Show array in a ComboBox (C#) from query SQL	SqlCeConnection connection = new SqlCeConnection(conSTR);\n                SqlCeCommand cmd = new SqlCeCommand("SELECT colour FROM tableColours", connection);\n                connection.Open();\n                DataTable colours = new DataTable();\n                colours.Load(cmd.ExecuteReader());\n                DataRow dr = null;\n                for (int i = 0; i < Colors.Rows.Count; i++)\n                {\n                    dr = colours.Rows[i];\n                    comboBoxEESS.Items.Add(dr[0].ToString());\n\n                }\n                connection.Close();	0
9012065	9007728	Parsing html page in WinForm,C#	var url = "http://eximguru.com/traderesources/pincode.aspx?&GridInfo=Pincode01";\nvar web = new HtmlWeb();\nvar results = new List<Pincode>();\nwhile (!String.IsNullOrWhiteSpace(url))\n{\n    var doc = web.Load(url);\n    var query = doc.DocumentNode\n        .SelectNodes("//div[@class='Search']/div[3]//tr")\n        .Skip(1)\n        .Select(row => row.SelectNodes("td"))\n        .Select(row => new Pincode\n        {\n            PinCode = row[0].InnerText,\n            District = row[1].InnerText,\n            State = row[2].InnerText,\n            Area = row[3].InnerText,\n        });\n    results.AddRange(query);\n\n    var next = doc.DocumentNode\n        .SelectSingleNode("//div[@class='slistFooter']//a[last()]");\n    if (next != null && next.InnerText == "Next")\n    {\n        url = next.Attributes["href"].Value;\n    }\n    else\n    {\n        url = null;\n    }\n}	0
11031804	10533501	Best way to make website for multiple languages	void Application_BeginRequest(Object sender, EventArgs e)\n        {\n            // Code that runs on application startup\n            HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];\n            if (cookie != null &amp;&amp; cookie.Value != null)\n            {\n                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);\n                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);\n            }\n            else\n            {\n                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");\n                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");\n            }\n        }	0
33619927	33618681	Push Item to the end of an array	public class PushPopIntArray\n{\n    private int[] _vals = new int[10];\n    private int _nextIndex = 0;\n\n    public void Push(int val)\n    {\n        if (_nextIndex >= _vals.Length)\n            throw new InvalidOperationException("No more values left to push");\n        _vals[_nextIndex] = val;\n        _nextIndex++;\n    }\n\n    public int Pop()\n    {\n        if (_nextIndex <= 0)\n            throw new InvalidOperationException("No more values left to pop");\n        _nextIndex--;\n        return _vals[_nextIndex];\n    }\n}	0
10998562	10998528	take time and append to date to make datetime?	class Program\n{\n    static void Main()\n    {\n        string s = "06/01/2012 8:00am";\n        string format = "dd/MM/yyyy h:mmtt";\n        DateTime date;\n        if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))\n        {\n            Console.WriteLine(date);\n        }\n    }\n}	0
22170718	22168442	count number of entries in table	var currentPageHits = pageHits\n    .GroupBy(x => x.Url)\n    .Select(x => new \n    {\n        LastEntry = x.OrderByDesc(y => y.TimeStamp).First(),\n        NumberOfHits = x.Count(),\n        Url = x.Key,\n     })\n    .Select(x => new\n    {\n        LastTimeStamp = x.LastEntry.TimeStamp,\n        LastUser = x.LastEntry.User,\n        x.NumberOfHits,\n        x.User,\n    })	0
27247689	27247114	How can I tell AutoFixture to always create TDerived when it instantiates a TBase?	fixture.Customizations.Add(\n    new TypeRelay(\n        typeof(TBase),\n        typeof(TDerived));	0
6392020	6391980	Calling _Paint on button click	public void UserInkControl_Click(object sender, EventArgs ea)\n{\n   UserInkControl.Refresh ();  // Causes repainting immediately\n   // or\n   UserInkControl.Invalidate ();  // Invalidates the whole painting surface, \n   //so when the message loop catches up, it gets repainted.\n   // There is also an overload of Invalidate that\n   // lets you invalidate a particular part of the button,\n   // So only this area is redrawn.  This can reduce flicker.\n}	0
7293883	7293863	Regex - remove the last <p> segment of an HTML string	string html = GetRSS();\nint pStartIndex = html.LastIndexOf("<p>");\nint pEndIndex = html.LastIndexOf("</p>");\nstring result = html.Remove(pStartIndex, pEndIndex - pStartIndex + 4);	0
2958003	2957457	Removing a querystring from url in asp.net	if (Request.QueryString["UserID"] != null) {\n    this.LinkButton.PostBackUrl = "http://UserProfileManager.com";\n} else {\n    // other address\n}	0
9160571	9049375	Why Link Button control variable dosen't get any value?	PostBackUrl='<%# "AddItem.aspx?CategoryID=" + Eval("CollectionID")%>' />	0
5941325	5941258	NHibernate IList as a Drop Down datasource?	ddlStatus.DataTextField = "StatusName";\n   ddlStatus.DataValueField = "StatusId";	0
29498405	29498074	how to get data in a row column format from an excel file in c#.net	int rowCount = range.Rows.Count;\nint colCount = range.Columns.Count;\nstring[] headers = new string[colCount+1];\nfor (cCnt = 1; cCnt <= colCount; cCnt++)\n    {\n        headers[cCnt]  = (Convert.ToString((range.Cells[1, cCnt] as Excel.Range).Value2));\n    }\n\nfor (rCnt = 2; rCnt <= rowCount; rCnt++)\n{\n    for (cCnt = 1; cCnt <= colCount; cCnt++)\n    {                \n        str = (Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2));\n        Console.Write(heasders[cCnt]);\n        Console.Write(" ");\n        Console.WriteLine(str);\n    }\n    Console.WriteLine("----------------");\n}\nConsole.ReadLine();	0
21843837	21115575	trouble in receiveing byte [] from wcf ksoap2 to android	SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);\n            SoapSerializationEnvelope soapEnvelop;\n            soapEnvelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);\n            soapEnvelop.dotNet = true;\n            soapEnvelop.setOutputSoapObject(Request);\n            HttpTransportSE htps = new HttpTransportSE(URL);\n\n            htps.call(SOAP_ACTION, soapEnvelop);\n            response = (SoapObject) soapEnvelop.getResponse();    \n            ar = new String[response.getPropertyCount()];\n\n            arrays = new ArrayList<Byte>();\n\n            if (response != null) {\n\n                if (response.getPropertyCount() > 0) {                  \n\n                    for (int i = 0; i < response.getPropertyCount(); i++) {\n\n                        arrays.add( (Byte) response.getProperty(i)); \n                    }\n                }\n            }	0
19248668	16105339	Passing an IDispatch parameter from C#	Type t = theScript.GetType();\nobject ret = t.InvokeMember(theObject, BindingFlags.InvokeMethod, null, theScriptName, new object[] { });	0
22266139	22266089	How to attach a RAR file to an email in c#?	var attachmentToSend = new Attachment(pathOfYourFile);\nmailMessage.Attachments.Add(attachmentToSend);	0
22696044	22695971	How do I send output of ASP.NET webforms site to a string/email ?	System.Net.Mail	0
10044774	10044679	How to access a file which is stored on a unknown folder name?	string userName = "Sandbox";\nstring[] folders = Directory.GetDirectories("C:\\Users\\" + userName  + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\", "*.default");	0
25343131	25342800	Using XML elements	// outside any method:\nprivate List<string> names = new List<string>();\n\nvoid myLoadMethod()\n{\n    ...\n    foreach(var HandlingName in query)\n    {\n        //string Names = HandlingName.HandlingName;\n        Names.Add(HandlingName.HandlingName);\n    }  \n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    comboBox1.Items.Add( Names);\n}	0
25034350	25034090	ASP.NET MVC4 application with nested areas	public override string AreaName\n{\n     get\n     {\n         return "CRM/Areas/MangeAppointment";\n     }\n}	0
27947242	27947138	Inserting values into selected column trouble	string str = @"INSERT INTO Cardiology \n                (Name, Designation,Qualification,Shift, Appointment_Timings) \n                values  \n                (@Name,@Designation,@Qualification,@Shift,@Appointment_Timings)";	0
3289420	3289268	How to hook a mouse wheel event to a form that has a panel and a scroll bar	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.MouseWheel += new MouseEventHandler(MouseWheelEvent);\n        this.MouseMove += new MouseEventHandler(MouseWheelEvent);\n    }\n\n    private void MouseWheelEvent(object sender, MouseEventArgs e)\n    {\n        Console.Out.WriteLine(e.Delta);\n    }\n}	0
3028761	3027075	c# sending sms from computer	private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {\n        string response = serialPort1.ReadLine();\n        this.BeginInvoke(new MethodInvoker(\n            () => textBox1.AppendText(response + "\r\n")\n        ));\n    }	0
1647922	1647656	"(503) Server Unavailable" with call to XSL Transform in Windows Server 2008	using(MemoryStream ms = new MemoryStream())\n{\n    XmlReader reader = XmlReader.Create(new StringReader(SomeXmlString));\n    XmlWriter writer = XmlWriter.Create(ms);\n    xslt.Transform(reader, xslArgs, writer, null); //Passing null here prevents resolving...\n    ms.Position = 0;\n    ret = new XPathDocument(ms);\n}	0
23202398	23202215	UDP based client server model	string text_to_send = Console.ReadLine();	0
1306614	1305813	Infragistics UltraListView auto scroll	UltraListViewItem i = listView.Items[listView.Items.Count - 1];    \nISelectionManager selectionManager = listView as Infragistics.Win.ISelectionManager;    \nselectionManager.SelectItem(i, true);    \ni.Activate();	0
7812337	7812254	Windows Mobile Wifi Networking After Wake Up From Sleep	try {\n    // your code \n}\ncatch (Exception ex)\n{\n    // add some logging\n}	0
842578	842533	In C# how do i query the list of running services on a windows server?	static void EnumServices(string host, string username, string password)\n{\n    string ns = @"root\cimv2";\n    string query = "select * from Win32_Service";\n\n    ConnectionOptions options = new ConnectionOptions();\n    if (!string.IsNullOrEmpty(username))\n    {\n        options.Username = username;\n        options.Password = password;\n    }\n\n    ManagementScope scope = \n        new ManagementScope(string.Format(@"\\{0}\{1}", host, ns), options);\n    scope.Connect();\n\n    ManagementObjectSearcher searcher = \n        new ManagementObjectSearcher(scope, new ObjectQuery(query));\n    ManagementObjectCollection retObjectCollection = searcher.Get();\n    foreach (ManagementObject mo in retObjectCollection)\n    {\n        Console.WriteLine(mo.GetText(TextFormat.Mof));\n    }\n}	0
23158899	23157124	Unity -- using information from request to resolve dependencies	container.RegisterType<IRepository>( \n     new InjectionFactory( \n        c => {\n           // whatever, consult the database\n           // whatever, consult the url\n           return ...; \n        } );	0
13097335	13096930	How to use Entity Framework 5 (CodeFirst) with DataContract from REST service	public class ProductContext : DbContext\n\n{\n\n    public DbSet<Category> Categories { get; set; }\n\n    public DbSet<Product> Products { get; set; }\n\n}	0
13311788	13311202	How to insert multiple rows into SQL Server CE database?	int n = 20;\n    for ( int i = 4; i < n; i++) {\n        for ( int j = 0; j < 4; j ++ ) {\n            System.out.print(j + 1);\n        }\n        System.out.println(i + 1);\n    }	0
19659427	19659322	C# regex capture gets two results instead of one	Regex.Match(url, "^http://the.site.com/some/path/(?<picid>.*?)$", RegexOptions.ExplicitCapture);	0
29684179	23253399	Serialize expression tree	public class JsonNetAdapter : IOconSerializer\n{\n    private readonly JsonSerializerSettings _settings;\n\n    public JsonNetAdapter(JsonSerializerSettings settings = null)\n    {\n        var defaultSettings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects};\n        defaultSettings.Converters.Add(new ExpressionJsonConverter(Assembly.GetAssembly(typeof(IOconSituation))));\n        _settings = settings ?? defaultSettings;\n    }\n\n    public string Serialize<T>(T obj)\n    {\n        return JsonConvert.SerializeObject(obj, _settings);\n    }\n\n    public T Deserialize<T>(string json)\n    {\n        return JsonConvert.DeserializeObject<T>(json, _settings);\n    }\n}	0
9946599	9930318	Is a cursor parameter really to be declared differently than a "regular" parameter?	_UserName = AUserName;\n// From the DevArtisans:\nString query = "select roleid from ABCrole where ABCid = :ABCID";\nDevart.Data.Oracle.OracleCommand cmd = new Devart.Data.Oracle.OracleCommand(query, con);\ncmd.CommandType = CommandType.Text;\nint _ABCID = GetABCIDForUserName();\ncmd.Parameters.Add("ABCID", _ABCID);\ncmd.Parameters["ABCID"].Direction = ParameterDirection.Input;\ncmd.Parameters["ABCID"].DbType = DbType.String;\nDevart.Data.Oracle.OracleDataReader odr = cmd.ExecuteReader();\nwhile (odr.Read()) {\n  ACurrentUserRoles.Add(odr.GetString(0));\n}	0
31765647	31765508	iterating over columns in a list of tuples with Linq	List<Tuple<string[], double[]>> result = tt.Select(x => \n    Tuple.Create(\n        x.Item1, \n        x.Item2.Select((y, i) => y / tt.Count(z => z.Item2[i] > 0))\n    .ToArray())).ToList();	0
7726648	7725313	How can I use databinding for 3D elements like Visual3D or UIElement3D	var visual = new Spherical3D();\nvar tx = new TranslateTransform3D();\nBindingOperations.SetBinding(tx, TranslateTransform3D.OffsetXProperty, \n                             new Binding("X") { Source = myDataObject });\nBindingOperations.SetBinding(tx, TranslateTransform3D.OffsetYProperty, \n                             new Binding("Y") { Source = myDataObject });\nBindingOperations.SetBinding(tx, TranslateTransform3D.OffsetZProperty, \n                             new Binding("Z") { Source = myDataObject });\nvisual.Transform = tx;\nChildren.Add(visual);\nAddVisual3DChild(visual);	0
5727777	5726940	How to go to Edit Mode in FormView?	fvReport.ChangeMode(DetailsViewMode.Edit);	0
4960104	4958889	c# Lambda subqueries (linq2sql)	ProjectBudgetAdjustment\n.Where( pba => pba.ProductBudget.Products.Code == "xxx")\n.Where( pba => (pba.Metrics.Description == "Hours" \n             || pba.Metrics.Description == "Amount"))\n.GroupBy(   pba => pba.ProductBudget.adGroupsId )\n.Select (\n    r => new\n    {\n        adGroupsId = r.Key,\n        Hours  = r.Sum(i=> (i.Metrics.Description == "Hours"  ? i.value : 0m)),\n        Amount = r.Sum(i=> (i.Metrics.Description == "Amount" ? i.value : 0m))\n    }\n);	0
8011624	8011555	How to prevent my textbox from clearing text on postback.	protected void Page_Load(object sender, EventArgs e) {\n   if (IsPostBack) {\n      // re-populate javascript-fill UI\n   } else {\n   } \n   Initialize();\n}	0
8253320	8253262	how to format Json output?	JObject json = JObject.Parse(text);\nstring formatted = json.ToString();	0
21143580	21143467	Hex string to plain text	var convertedString = new StringBuilder();\n\nforeach(var hex in hexString.Split('-'))\n{\n    var unicode = int.Parse(hex, NumberStyles.HexNumber);\n    convertedString.Append((char)unicode);\n}\n\nreturn convertedString.ToString();	0
14296018	14295923	How to display List contents in FormView	Authors:\n<asp:Panel ID="pnAddTransition" runat="server" Visible="false">\n    <asp:Label ID="AuthorsLabel" runat="server" Text='<%# String.Join( ",", ((List<string>)Eval("Authors")).ToArray()) %>' />\n<br />	0
5653414	5653296	c# how to check that the string that the user input in the textbox is Chinese?	// Warning, this code only works for common Han ideographs inside the BMP. (Surrogate code points will need special care, and additional ranges within the BMP contain rare, historic, and uncommon characters.)\nconst double hannessThreshold = 0.25d;\nconst char lowestHanCodepoint = '\u4E00';\nconst char highestHanCodepoint = '\u9FFF';\nstring text = myTextBox.Text;\nint hanCharacterCount = 0;\nforeach (char c in text)\n    if (lowestHanCodepoint <= c && c <= highestHanCodepoint)\n        hanCharacterCount++;\ndouble hannessScore = (double)hanCharacterCount / text.Length;\nif (hannessScore >= hannessThreshold)\n    MessageBox.Show("You are typing in Chinese, Japanese, or Korean!");	0
16663254	16659546	How to get text from the node in xml file, that contains text and child node?	XmlNodeList itemNode = xmlDoc.SelectNodes("/");\nXmlNode titleNode = itemNode.SelectSingleNode("title");\nXmlNode nemodNode = itemNode.SelectSingleNode("nemod");\nif((titleNode != null) && (dateNode != null))\n    Console.WriteLine(titleNode.InnerText + " " + nemodNode.InnerText);	0
22392551	22392503	Convert a string containing a special character to string array	string[] arr = test.Split('_');	0
32763043	32719333	Get the more similar string from a list	var bestPath  = remotePaths.OrderByDescending(i => i.ID_FILE_PATH.Length)\n                               .ToList()\n                               .FirstOrDefault(i => rootPath.StartsWith(i.ID_FILE_PATH, StringComparison.InvariantCultureIgnoreCase));	0
1678448	1664043	Insert a Row with a sorted DataGridView	DataRowView drv = (DataRowView)source.AddNew();\n    grupoTableAdapter.Update(drv.Row);\n    grupoBindingSource.Position = grupoBindingSource.Find("ID", drv.Row.ItemArray[0]);	0
4423461	4423435	c# validation all text box that start with the same name	foreach (TextBox box in this.Controls.OfType<TextBox>()\n       .Where(tb => tb.Name.StartsWith("tbwin")))\n{\n    int result;\n    if(!int.TryParse(box.Text, out result))\n    {\n         //Not OK. Inform user\n         MessageBox.Show("You need to write a valid number in " + box.Name);\n    } \n}	0
30541587	30541562	Joining two tables with LINQ while also returning null records from the second table	var resultTable = from m in messages \n    join i in images on m.ImageID equals i.ImageID into imgJoin\n    from img in imgJoin.DefaultIfEmpty()\n    select new\n    {\n        MessageID = m.MessageID,\n        TimeStamp = m.TimeStamp,\n        Text = m.Text,\n        RoomID = m.RoomID,\n        ImageID = m.ImageID,\n        UserID = m.UserID,\n        Path = img != null ? img.Path : ""\n    };	0
25818194	25744460	Visualisation of JSON Data with Google Chart API	/* "obj" is your json object\n * this creates a DataTable containing:\n *     Category\n *     Timestamp\n *     Key\n *     Value\n * entries for each entity in each product\n */\nvar data = new google.visualization.DataTable();\ndata.addColumn('string', 'Category');\ndata.addColumn('number', 'Timestamp');\ndata.addColumn('string', 'Key');\ndata.addColumn('number', 'Value');\n\nvar p, c, t, e;\nfor (var i = 0; i < obj.products.length; i++) {\n    p = obj.products[i];\n    c = p.category;\n    t = parseInt(p.timestamp);\n    for (var j = 0; j < p.entities.length; j++) {\n        e = p.entities[j];\n        data.addRow([c, t, e.key, parseInt(e.value)]);\n    }\n}	0
2475822	2475795	Check for missing number in sequence	var list = new List<int>(new[] { 1, 2, 4, 7, 9 });\nvar result = Enumerable.Range(0, 10).Except(list);	0
3198035	3196729	Referencing a class that may exist in one of two assemblies	interface IQueueInfoProvider\n{\n   DataStructure FetchData();\n}\n\nclass Version1QueueInfoProvider : IQueInfoProvider\n{\n   DataStructure FetchData()\n   {\n      //Fetch using Version1 Assemblies.\n   }\n}\n\nclass Version2QueueInfoProvider : IQueInfoProvider\n{\n   DataStructure FetchData()\n   {\n       //Fetch using Version2 Assemblies.\n   }\n}	0
16216906	16216458	My application will not automatically start with windows - what is wrong here?	private void RegisterInStartup(bool isChecked)\n{\n   RegistryKey registryKey = Registry.CurrentUser.OpenSubKey\n        ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n   if (isChecked)\n   {\n       registryKey.SetValue("ApplicationName", Application.ExecutablePath);\n   }\n   else\n   {\n     registryKey.DeleteValue("ApplicationName");\n   }\n}	0
12127863	12127843	Generating a random string	_random.Next	0
11121907	11121419	How to insert hyperlinks in ListView	private void button1_Click(object sender, EventArgs e)\n    {\n        listView1.Items.Add(textbox1.Text);\n        listView1.HotTracking = true;\n\n        listView1.Items[i].SubItems.Add("hyperlynk2.text");\n    }	0
6283159	6283114	Piping output to a text file in C#	var file = File.AppendText(@"c:\output.txt");\n\nforeach (string tmpLine in File.ReadAllLines(@"c:\filename.txt"))\n{\n    if (File.Exists(tmpLine))\n    {       \n        file.WriteLine(tmpLine);\n    }\n}\n\nfile.Close();	0
7671767	7671708	Linq-to-SQL ToDictionary	Invoices = tag.AsEnumerable().ToDictionary(a => new AllocationDictionaryKey() { ID = a.ID, InvoiceReference = a.InvoiceReference }, a => a.Amount)	0
8657146	8655104	Outlook 2007 vsto add-in. Get email sender address	private string GetSmtpAddress(Outlook.MailItem oItem)\n{\n    Outlook.Recipient recip;\n    Outlook.ExchangeUser exUser;\n    string sAddress;\n\n    if (oItem.SenderEmailType.ToLower() == "ex")\n    {\n        recip = Globals.ThisAddIn.Application.GetNamespace("MAPI").CreateRecipient(oItem.SenderEmailAddress);\n        exUser = recip.AddressEntry.GetExchangeUser();\n        sAddress = exUser.PrimarySmtpAddress;\n    }\n    else\n    {\n        sAddress = oItem.SenderEmailAddress.Replace("'", "");\n    }\n    return sAddress;\n}	0
25682087	25680917	Cannot change int values created in main using a class function	private void SomeMethod()\n{\n    var score = 0;\n    var pointRadiusCounter = 0;\n    if (CollisionOccurred(...))\n    {\n        score++;\n        pointRadiusCounter++;\n    }\n    ...\n    ...\n    ...\n}\n\npublic bool CollisionOccurred(Control player,Control pointRadius,Control topPipe,Control bottomPipe,Control gameOver,int force,bool timer)\n{\n    if (player.Right > pointRadius.Left && player.Left < pointRadius.Right - player.Width / 2 && player.Bottom > pointRadius.Top)\n    {\n        if (timer == true && pointRadiusCounter == 0)\n        {\n            return true;\n        }\n    }\n    return false;\n}	0
29033049	29032705	Date input validation asp.net	[AttributeUsage(AttributeTargets.Property)]\npublic class FutureDateValidation : ValidationAttribute {\n    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {\n        DateTime inputDate = (DateTime)value;\n\n        if (inputDate > DateTime.Now) {\n            return ValidationResult.Success;\n        } else {\n            return new ValidationResult("Please, provide a date greather than today.", new string[] { validationContext.MemberName });\n        }\n    }\n}\n\n\npublic class Group {\n    [FutureDateValidation()]\n    [DataType(DataType.Date, ErrorMessage = "Please provide a valid date.")]\n    public DateTime GroupDateTime { get; set; }\n}	0
29402133	29397791	How to insert hyperlink into RTFBODY property of Outlook Appointment?	item.RTFBody = System.Text.Encoding.UTF8.GetBytes(rtb.Rtf);	0
14842687	14842572	Properties that update each other	private string _foo;\nprivate string _bar;\n\npublic string Foo\n{\n   get { return _foo; }\n   set {\n      _foo = value;\n      _bar = _foo.Substring(3, 5);\n   }\n}\n\npublic string Bar\n{\n   get { return _bar; }\n   set {\n      _bar = value;\n      _foo = "XXX" + _bar;\n   }\n}	0
13395657	13395595	How can I traverse this list in this manner?	foreach (var group in items.GroupBy(i => i.ID))\n{\n    foreach (var item in group)\n    {\n    } \n}	0
10242449	10241022	how to create custom authorize filter in asp.net mvc3	[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class, AllowMultiple = false)]\npublic class  MyAuthorizeAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        base.OnAuthorization(filterContext);\n        var ctx = filterContext.HttpContext;\n        var name = ctx.User.Identity.Name;\n\n        //get user id from db where username= name   \n\n        var urlId = Int32.Parse(ctx.Request.Params["id"]);\n        if (userId!=urlId)\n            filterContext.Result = new HttpUnauthorizedResult();\n    }\n}	0
24438130	24413148	Dotnetcharting stacked bar chart displaying like regular bar chart	timeLossStackedBarChart.SeriesCollection[0].YAxis.Scale = Scale.Stacked;	0
2208592	2208530	Should a User Control's Controls be backed by Properties?	public string CityText\n{\n    get { return this.txtCity.Text; }\n}	0
24498410	24463198	Validation ErrorMessage value	var errorMsg = FormatErrorMessage(invoice.Amount.ToString());\nreturn new ValidationResult(errorMsg);	0
3057092	3056281	How can I use linq to select the columns of a jagged array	IEnumerable<IEnumerable<int>> columns = values\n  .SelectMany((row, ri) => row\n    .Select((x, ci) => new {cell = x, ci, ri}))\n  .GroupBy(z => z.ci)\n  .Select(g => g.Select(z => z.cell));	0
2848707	2848689	C# Tell static GIFs apart from animated ones	Image i = Image.FromFile(Server.MapPath("AnimatedGIF.gif"));\n\nImaging.FrameDimension FrameDimensions = \n    new Imaging.FrameDimension(i.FrameDimensionsList[0]);\n\nint frames = i.GetFrameCount(FrameDimensions);\n\nif (frames > 1) \n    Response.Write("Image is an animated GIF with " + frames + " frames");\nelse \n    Response.Write("Image is not an animated GIF.");	0
24014774	24014644	Make sure that the controller has a parameterless public constructor	public class AnalyticController : ApiController\n{\n   public AnalyticController()\n   {\n   }\n\n   // Variables and methods are the same as before\n}	0
32392986	32392734	how to disable asp:radiobutton list via c#?	this.rblCreateEvent.Enabled = false;\nthis.rblCreateEvent.Attributes.Remove("onClick");	0
33645113	33644928	Sorting a List of Lists by the amount of intergers of the same type they contain	var list = new List<List<int>>() \n{ \n    new List<int> { 0, 1, 2, 3 }, \n    new List<int> { 0, 1, 1, 1 }, \n    new List<int> { 0, 2, 2, 2 } \n};\n\nvar result = list.OrderByDescending(c => c.Count(y => y == 1)).ToList();	0
6957754	6957288	DependencyProperty data binding	SwitchLanguage()	0
9436467	9436263	A set that mantains insert order and allows accessing elements by its index	import java.util.*;\n\npublic class ArraySet<T> {\n    private final Map<Integer, T> indexToElem;\n    private final Map<T, Integer> elemToIndex;\n\n    public ArraySet() {\n        indexToElem = new HashMap<Integer, T>();\n        elemToIndex = new HashMap<T, Integer>();\n    }\n\n    public T get(int index) {\n        if (index < 0 || index >= size())\n            throw new IndexOutOfBoundsException();\n        return indexToElem.get(index);\n    }\n\n    public void add(T elem) {\n        if (!contains(elem)) {\n            int index = indexToElem.size();\n            indexToElem.put(index, elem);\n            elemToIndex.put(elem, index);\n        }\n    }\n\n    // Doesn't work; see comment.\n    /*public void remove(T elem) {\n        int index = elemToIndex.get(elem);\n        indexToElem.remove(index);\n        elemToIndex.remove(elem);\n    }*/\n\n    public boolean contains(T elem) {\n        return elemToIndex.containsKey(elem);\n    }\n\n    public int size() {\n        return indexToElem.size();\n    }\n}	0
13998141	13997464	How to read a text file line by line Windows RT?	// READ FILE\n    public async void ReadFile()\n    {\n        // settings\n        var path = @"MyFolder\MyFile.txt";\n        var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;\n\n\n        // acquire file\n        var file = await folder.GetFileAsync(path);\n        var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);\n        foreach (var line in readFile)\n        {\n            Debug.WriteLine("" + line.Split(';')[0]);\n        }\n     }	0
9419073	9411240	Drawing in MonoMac	public class MyDrawing : NSView\n{\n    public override void DrawRect (RectangleF dirtyRect)\n    {\n        var context = NSGraphicsContext.CurrentContext.GraphicsPort;\n        context.SetStrokeColor (new CGColor(1.0, 0, 0)); // red\n        context.SetLineWidth (1.0F);\n        context.StrokeEllipseInRect (new RectangleF(5, 5, 10, 10));\n    }\n}	0
4626927	4626820	NHibernate Unable to convert MySQL date/time value to System.DateTime	Convert Zero Datetime=true;	0
3640818	3624432	how to set a DataGridViewColumn cells to unselectable?	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n{\n            if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == mySpecifiedColumn.Name)\n                dataGridView1.CurrentCell.Selected = false;\n}	0
30648459	30647584	How to filter a list with linq depends on counting a property at the same list and take a random group at least minimun total	var ips= new[]{\n  new {ip="100.100.101",VLanID=(int?)100,isReserved=0,PackageId=0},\n  new {ip="100.100.102",VLanID=(int?)100,isReserved=0,PackageId=0},\n  new {ip="200.200.201",VLanID=(int?)200,isReserved=0,PackageId=0},\n  new {ip="200.200.202",VLanID=(int?)200,isReserved=0,PackageId=1},\n  new {ip="300.300.301",VLanID=(int?)null,isReserved=0,PackageId=0},\n  new {ip="300.300.302",VLanID=(int?)null,isReserved=0,PackageId=0},\n  new {ip="400.400.401",VLanID=(int?)400,isReserved=0,PackageId=0},\n  new {ip="400.400.402",VLanID=(int?)400,isReserved=0,PackageId=0}\n};\nvar numOfIps=2;\nvar result=ips.GroupBy(k=>k.VLanID)\n .Where(v=>v.Count()>=numOfIps)\n .Where(v=>v.All(i=>i.isReserved==0))\n /*.Where(v=>v.Key!=null)  Remove null vlans */\n /*.OrderBy(x => Guid.NewGuid()) Pseudo Randomize */\n .First(v=>v.All(i=>i.PackageId==0))\n .Select(v=>v);\n\nresult.Dump();	0
28622158	28621533	Display current datetime depending on client	new Date().gettimezoneOffset()	0
29954908	29953970	Redis Docker - Unable to connect from C# client	docker run -d --name redisDev -p 6379:6379 redis	0
25457013	25456983	Image quality degraded after scaling	e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;	0
10215484	10215443	Unable to call a method from another class	P90XPRogramt.ProgramLoginBOL.TestParsing(txtStartDate.Text);	0
6791650	6791533	Can I assign a static class to a variable?	using a = SomeNamespace.AClassWithALongNameIDontWantToType;	0
12814314	12814139	How can I redirect to different views on authorization failure?	context.Result = new RedirectResult(urlHelper.Action("Test", "Redirect"));	0
8898179	8898121	select elements with the name attribute name in special xml structure	XmlNodeList attrElements\n    = yourDocument.SelectNodes("/nodes/node/attribute[@name='a']");	0
11761410	11761110	HTTPClient Requesting JSON with login Credentials C# Sharepoint	private void login_Click(object sender, EventArgs e)\n{\n    string username = uname.Text;\n    string password = pword.Text;\n    string url = "THE SITE URL HERE";\n    var req = (HttpWebRequest)WebRequest.Create(url);\n    req.Credentials = new NetworkCredential(username, password);\n    var response = req.GetResponse();\n    //Do Stuff with response\n}	0
19699488	19699473	Moving files from one folder to another C#	string rootFolderPath = @"F:\model_RCCMREC\";\nstring destinationPath = @"F:\model_RCCMrecTransfered\";	0
11555411	11555043	Get string array from C using marshalling in C#	public static extern void GetCharArray(IntPtr[] results);\n\nIntPtr[] pointers = new IntPtr[1000];\nGetCharArray(pointers);\nstring[] results = new string[1000];\n        for (int i = 0; i < 1000; i++)\n        {\n            results[i] = Marshal.PtrToStringAnsi(pointers[i]);\n        }	0
19550353	19550099	EventToCommand Missing For Windows Phone App	xmlns:Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"	0
2647032	2646578	Using AutoMapper to dynamically map objects including arrays	if (aProp.Name == bProp.Name)\n    {\n        if (aProp.PropertyType.IsArray)\n        {\n            MapDataObjects(aProp.PropertyType.GetElementType(), bProp.PropertyType.GetElementType());\n            seenTypes.Add(aProp.PropertyType.GetElementType());\n            break;\n        }\n        else\n        {\n            MapDataObjects(aProp.PropertyType, bProp.PropertyType);\n            seenTypes.Add(aProp.PropertyType);\n            break;\n        }\n    }	0
4414057	4413913	Filter a tree using recursion	void FilterNode(Node node) {\n    foreach (Node child in node.Children) {\n        FilterNode(child);\n    }\n    if (node.Type != NodeType.A) {\n        foreach (Node child in node.Children) {\n            node.Parent.InsertAfter(node, child);\n        }\n        node.Parent.RemoveNode(node);\n    }\n}	0
484996	484293	WPF: ListView with icons view?	ScrollViewer.HorizontalScrollBarVisibility="Disabled" \nScrollViewer.VerticalScrollBarVisibility="Auto"	0
18760861	18760696	writing byte array data into csv file	File.AppendAllText(filePath, BitConverter.ToString(image));	0
13413064	13413038	Getting all column names / column values from datarow when debugging	var colNames = dr.Table.Columns.Cast(Of DataColumn)\n                               .Select(x => x.ColumnName).ToList()	0
27637499	27634891	How to insert data in a table with foreign key	insertCommande1.Parameters.AddWithValue("@IdCategorie",  idCategorieComboBox.SelectedValue.ToString());	0
8207465	8207449	How to dynamically add a code behind for button	bn.Click += MyClick;\n\n...\n\nprivate void MyClick(object sender, EventArgs e) {\n    MessageBox.Show("hello");\n}	0
26283804	26282143	How to create a fake FtpWebResponse	FtpResponse response;\n\n        using (ShimsContext.Create())\n        {\n            ShimFtpWebRequest.AllInstances.GetResponse = request => new ShimFtpWebResponse();\n            ShimFtpWebResponse.AllInstances.StatusDescriptionGet = getDescritpion => "226 Transfer complete.";\n            _ftpConnection.Put(_fileContent);\n            response = new FtpResponse("226 Transfer complete.", false);\n        }\n        Assert.AreEqual(response.Message, "226 Transfer complete.");\n        Assert.IsFalse(response.HasError);	0
27805739	24189065	Allowing Membership.ValidateUser to validate username or email from AD	bool isValid = false;\nif(user.Contains("@fullyqualifieddomain"))\n{\n  isValid = Membership.ValidateUser(user, password)\n}\nelse if(user.Contains("@"))\n{\n  isValid = Membership.ValidateUser(Membership.GetUserNameByEmail(user),password);\n}\nelse\n{\n isValid = Membership.ValidateUser(user+"fullyqualifieddomain");\n}	0
13252373	13252156	Regular Expression to split by ;	(;#)?[0-9]+;#	0
11277898	11277569	Settings Trouble in C#?	public Form8(Form1 frm1): this()\n{\n    // Restore the settings when loading the form\n    checkBox1.Checked = Properties.Settings.Default.checkBox1;\n}\n\nprivate void form8_closing(object sender, FormClosingEventArgs e)\n{\n    if (DialogResult.Yes == MessageBox.Show("Do you want to Save your Settings?",\n                    "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))\n    {\n        // Set the setting and save it\n        Properties.Settings.Default.checkBox1 = checkBox1.Checked;\n        Properties.Settings.Default.Save();\n    }\n}	0
13247293	13247273	Convert String to Nullable DateTime	DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);	0
15574876	15573960	ListView - How to respond to double click on non-item?	private void list_MouseDown(object sender, MouseEventArgs e)\n{\n    if ( e.Clicks == 2 )\n        list_MouseDoubleClick(sender, e);\n}	0
28436087	28435843	Select items in row on a created list	public ExpandWindow(int jobId)\n    {\n        InitializeComponent();\n        List<JobComponent.JobList> jobDetail = JobComponent.SelectJobBooking(jobId);\n\n        if(jobDetail == null) return;\n\n        var item = jobDetail.FirstOrDefault();\n        if(item == null) return;\n\n        yourDatetimeControl.Value = item.JobDateTime;\n    }	0
12764325	12764267	C# Serial Communication	using (var sp = new System.IO.Ports.SerialPort("COM11", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One))\n    {\n        sp.Open();\n\n        sp.WriteLine("Hello!");\n\n        var readData = sp.ReadLine();\n        Console.WriteLine(readData);\n    }	0
3605734	3605695	handling null byte array values in a LINQ query	docTypes = (from c in context.Citizenships join\n            cdt in context.Citizenship_Document_Types\n            on c.Country_Code equals cdt.Country_Code\n            from cd in context.Citizenship_Documents.Where(\n                cd => cd.Citizenship_Id == c.Citizenship_ID).DefaultIfEmpty()\n            where c.Citizenship_ID == citizenshipId\n            select new CitizenshipDocument\n            {\n                Id = (int?)cd.Citizenship_Document_Id??-1,\n                CitizenshipId = c.Citizenship_ID,\n                DocumentTypeId = cdt.Citizenship_Document_Type_Id,\n                DocumentTypeName = cdt.Citizenship_Document_Type_Name,\n                DocumentCode = cd.Citizenship_Document_Code == null ?\n                    null : \n                    cd.Citizenship_Document_Code.ToArray(),\n                ExpirationDate = cd.Expiration_Date,\n                IssueDate = cd.Issue_Date\n            }).ToList();	0
7796777	7796736	Relaxing Constraints for a data table adapter	ubsmysDataSet ds = new ubsmysDataSet();\n\nubsmysDataSet.FormSaveDataDataTable dt = new ubsmysDataSet.FormSaveDataDataTable();\n\nds.Tables.Add(dt);\n\nds.EnforceConstraints = false;\n\nubsmysDataSetTableAdapters.FormSaveDataTableAdapter ta = new ubsmysDataSetTableAdapters.FormSaveDataTableAdapter();\n\nif (isAdmin)\n{\n\n}\nelse\n{\n    ta.FillByUserId(dt,130559)\n}\n\nds.EnforceConstraints = true;	0
12681376	12681045	Is this a valid use of a WCF Service Application	public class UserService1 : System.ServiceProcess.ServiceBase  \n{\n\n    public UserService1() \n    {\n        this.ServiceName = "MyService2";\n        this.CanStop = true;\n        this.CanPauseAndContinue = true;\n        this.AutoLog = true;\n    }\n    public static void Main()\n    {\n        System.ServiceProcess.ServiceBase.Run(new UserService1());\n    }\n    protected override void OnStart(string[] args)\n    {\n        // Insert code here to define processing.\n    }\n    protected override void OnStop()\n    { \n        // Whatever is required to stop processing\n    }\n}	0
20244195	20243895	Accessing A Shared Outlook Calendar Without Installing Outlook?	Dim objRedemption As New Redemption.RDOSession\n    objRedemption.Logon()\n    Dim objCal = objRedemption.GetSharedDefaultFolder("Dunkin Donuts", Redemption.rdoDefaultFolders.olFolderCalendar)\n    objRedemption.Logoff()	0
25525789	25524938	find and get + set item value to another Iqueryable list of same type	var value = currentOrderlist.SingleOrDefault(x => x.item == curOrder.item);\nif(value != null)\n{\n    if (String.IsNullOrEmpty(value.Qty.ToString()))\n    {\n       gridinfo.Qty = value;\n    }\n}	0
18897679	18897110	ASP.NET MVC4 - A library to draw a world map and to draw circles on the map given a latitude/longitude and radius	function initialize() {\n  var mapOptions = {\n    zoom: 4,\n    center: new google.maps.LatLng(34.052234, -118.243684),\n    mapTypeId: google.maps.MapTypeId.TERRAIN\n  };\n\n  var map = new google.maps.Map(document.getElementById("map-canvas"),\n      mapOptions);\n\n  var circleOptions = {\n      strokeColor: "#FF0000",\n      strokeOpacity: 0.8,\n      strokeWeight: 2,\n      fillColor: "#FF0000",\n      fillOpacity: 0.35,\n      map: map,\n      center: new google.maps.LatLng(34.052234, -118.243684),\n      radius: 2000000\n  };\n  var circle = new google.maps.Circle(circleOptions);\n}	0
12663517	12609367	How can I add an external image to a word document using OpenXml?	using (WordprocessingDocument newDoc = WordprocessingDocument.Open(@"c:\temp\external_img.docx", true))\n{\n    var run = new Run();\n\n    var picture = new Picture();\n\n    var shape = new Shape() { Id = "_x0000_i1025", Style = "width:453.5pt;height:270.8pt" };\n    var imageData = new ImageData() { RelationshipId = "rId56" };\n\n    shape.Append(imageData);\n\n    picture.Append(shape);\n\n    run.Append(picture);\n\n    var paragraph = newdoc.MainDocumentPart.Document.Body.Elements<Paragraph>().FirstOrDefault();\n\n    paragraph.Append(run);      \n\n    newDoc.MainDocumentPart.AddExternalRelationship(\n       "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",\n       new System.Uri("<url to your picture>", System.UriKind.Absolute), "rId56");\n}	0
25783568	25058472	Get UserId right after login without reloading page	public ActionResult ExternalLoginCallback()\n{\n    AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback"));\n    if (!result.IsSuccessful)\n    {\n        return RedirectToAction("ExternalLoginFailure");\n    }\n    if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))\n    {\n        var db = new MyDataClassesDataContext();\n        var user = db.ExecuteQuery<UserProfile>("SELECT TOP 1 up.* FROM [dbo].webpages_OAuthMembership oam JOIN [dbo].UserProfile up ON (up.UserId = oam.UserId) WHERE oam.ProviderUserId = '" + result.ProviderUserId + "'").FirstOrDefault();\n        // Do your post login stuff here\n        return RedirectToAction("SomewhereAfterLogin");\n    }\n    // Here goes creating a new account in case external wasn't in the system before\n}	0
28351708	28351675	Convert integer to byte array	BitConverter.GetBytes(366);	0
15837357	15811020	Database looping algorithm driving me crazy	for (var i = 0; i < GoodDT.Rows.Count; i++)\n{\n    for (var x = 0; x < GoodDT.Columns.Count; x++)\n    {\n        if (BadDT.Columns[x].ColumnName != "skip1" && BadDT.Columns[x].ColumnName != "skip2")\n        {\n            BadDT.Rows[i][x] = GoodDT.Rows[i][x];\n        }\n    }\n}	0
32512336	32506628	How to force focus on a XAML ListView for Windows 10 apps (UWP)?	private void ListView_OnLoaded(object sender, RoutedEventArgs e)\n    {\n        var lv = sender as ListView;\n\n        if(lv != null)\n            lv.SelectedIndex = 0;\n    }	0
18874502	6996399	Storing Enums as strings in MongoDB	// Set up MongoDB conventions\nvar pack = new ConventionPack\n{\n    new EnumRepresentationConvention(BsonType.String)\n};\n\nConventionRegistry.Register("EnumStringConvention", pack, t => true);	0
24334281	24333655	Getting complete value from ElasticSearch query	{\n  "fields": [\n    "_parent",\n    "_source"\n  ],\n  "query": {\n    "terms": {\n      "Id": [\n        "12738"\n      ]\n    }\n  }\n}	0
29099415	28937751	Gembox, colorify Excell row	ef.Worksheets[0].Rows[myRowIndex].Style\n                                 .FillPattern\n// When solid is specified, the PatternForegroundColor is the only color rendered.\n                                 .SetPattern(FillPatternStyle.Solid, selectedColor, Color.Empty);	0
20400565	20400532	Email address validation in C# MVC 4 application: with or without using Regex	[EmailAddress(ErrorMessage = "Invalid Email Address")]\npublic string Email { get; set; }	0
14394097	14378249	break in a if else loop with a counter C#	if (condition1 &&  ( counter != 1 || counter != 2 ||          .... counter!= n )\n{\n// do something\n}\nelse if (condition2 && (counter != 2 || ..            || counter!= n )\n{\n// do something\n}\n\nand so on \nelse\n{\n// do this\n }	0
6091569	6090492	How to Design a MVVM UserControl WPF and hosted it into a Windows Forms ElementHost?	if (System.Windows.Application.Current == null)\n    new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };\nelse\n    System.Windows.Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;	0
15720770	15720314	Combining these two expression into a single LINQ expression	return (\n    from result in \n        from item in doc.DocumentNode.SelectNodes("//div[@class='product']")\n        from input in item.Descendants("span")\n        where input.Attributes["class"].Value == "Bold"\n        where input.InnerHtml.ToUpper() == "GetItem"\n        select input\n    select result\n    ).First();	0
3826033	3825979	C#: Limit the length of a string?	const int MaxLength = 5;\n\n\nvar name = "Christopher";\nif (name.Length > MaxLength)\n    name = name.Substring(0, MaxLength); // name = "Chris"	0
8653464	8500952	How to configure windsor for passing dependency as argument through dependency tree?	public class TransientA\n{\n    public SingletonC SingletonC { get; set; }\n    public ILogger Logger { get; set; }\n}\n\npublic class TransientB\n{\n    public SingletonC SingletonC { get; set; }\n    public ILogger Logger { get; set; }\n}\n\npublic class SingletonC\n{\n    public ILogger Logger { get; set; }\n}	0
21005649	21004860	convert this into linq or lambda c#	var StudentsByCourseId = from s in db.Students\n            join c in db.Classes on s.ClassId equals c.Id\n            join t in db.Teachers on c.TeacherId equals t.Id\n            group s by new { s.ClassId, Class = c.Name, Teacher = t.Name } \n            into g\n            select new\n            {\n              StudentInClass = g.Count(),\n              g.Key.Class,\n              g.Key.Teacher,\n            };	0
12675114	12631290	XML columns in a Code-First application	public String XmlContent { get; set; }\n\npublic XElement XmlValueWrapper\n{\n    get { return XElement.Parse(XmlContent); }\n    set { XmlContent = value.ToString(); }\n}\n\npublic partial class XmlEntityMap : EntityTypeConfiguration<XmlEntity>\n{\n    public FilterMap()\n    {\n        // ...\n        this.Property(c => c.XmlContent).HasColumnType("xml");\n\n        this.Ignore(c => c.XmlValueWrapper);\n    }\n}	0
23731886	23731817	How to extract a specific text from text file in c#	string text = File.ReadAllText(@"E:\file.txt");\n\nint positionOfFirstLineEnd = text.IndexOf('\n');\n\nstring title = text.Substring(0, positionOfFirstLineEnd);\nstring description = text.Substring(positionOfFirstLineEnd + 1);	0
25685072	25684965	LINQ Dynamic sort with nullable fields	string sortField = "MyField";\nvar orderByParam = Expression.Parameter(typeof(MyType), "MyType");\nvar sortExpression = Expression.Lambda<Func<MyType, object>>(\n  Expression.Convert(Expression.Property(orderByParam, sortField), \n  typeof(object)), orderByParam);	0
6421761	6413090	How to add a sharpPDF into a Word document?	string tempNameFilePdf = "C:\\temp\\temp" + DateTime.Now.Ticks + ".pdf";\npdfDocument pdfDocument = getPdf();\n\npdfDocument.createPDF(tempNameFilePdf);\nobject oBookMarkId = "Schema";\n\nobject missing = System.Reflection.Missing.Value;\n\nobject fileNameObject = tempNameFilePdf;\nobject classType = "AcroRd32.Document";\nobject oFalse = false;\n\nwordDocument.Bookmarks.get_Item(ref oBookMarkId).Range.InlineShapes.AddOLEObject(\n             ref classType, ref fileNameObject, ref missing, ref missing,\n             ref missing, ref missing, ref missing, ref missing);	0
26576437	26576285	How can I get the sign-bit of a double?	private static readonly long SignMask = BitConverter.DoubleToInt64Bits(-0.0) ^\n    BitConverter.DoubleToInt64Bits(+0.0);\n\npublic static bool signbit(double arg)\n{\n    return (BitConverter.DoubleToInt64Bits(arg) & SignMask) == SignMask;\n}	0
21206233	21206227	How to send a session to another ASP.NET WebForm page?	Response.Redirect("~/ViewInvoices.aspx", false);	0
1496533	1496516	Get First 6 character from string which is distinct	IEnumerable<string> firstInGroup =\n   arr\n   .GroupBy(s => s.Substring(0, 6))\n   .Select(g => g.First());	0
23044938	23044643	How to use Random C#?	Random rand=new Random();\n    int value= rand.next(0,600);\n    while(value>=200 && value<=300)\n      {\n        value=rand.next(0,600);\n      }	0
6883293	6882802	How to center image in picturebox on resize?	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\ninternal class PicturePanel : Panel {\n    public PicturePanel() {\n        this.DoubleBuffered = true;\n        this.AutoScroll = true;\n        this.BackgroundImageLayout = ImageLayout.Center;\n    }\n    public override Image BackgroundImage {\n        get { return base.BackgroundImage; }\n        set { \n            base.BackgroundImage = value;\n            if (value != null) this.AutoScrollMinSize = value.Size;\n        }\n    }\n}	0
7116760	7091787	How to Send C++ Struct Message from C# Socket?	[StructLayout(LayoutKind.Sequential)]\n        public struct LoginMessage\n        {\n            public int msgSize;\n            public int msgId;\n\n            [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)]\n            public string szUser;\n\n            [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)]\n            public string szPass;\n        }	0
21402808	21401208	How to get time from Timepicker in hh:mm format in windows phone 8 app?	DateTime? _datetime = Timepicker.Value;\nString Time = _datetime.Value.Hour + ":" + _datetime.Value.Minute;	0
5904706	5874551	Using SSH to run custom scripts on a Unix server in C#	PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("some IP", "user", "pass");\n\ntry\n{\n    using (var client = new SshClient(connectionInfo))\n    {\n        client.Connect();\n        var input = new MemoryStream(Encoding.ASCII.GetBytes(command));\n        var shell = client.CreateShell(input, Console.Out, Console.Out, "xterm", 80, 24, 800, 600, "");\n        shell.Stopped += delegate(object sender, EventArgs e)\n        {\n            Console.WriteLine("\nDisconnected...");\n        };\n        shell.Start();\n        Thread.Sleep(1000);\n        shell.Stop();\n        client.Disconnect();\n    }   \n}\ncatch (Exception ex)\n{\n    // Exception stuff\n}	0
30819502	30819086	Count items in MongoDB	db.collection.CountAsync(new BsonDocument());	0
1570216	1570202	Mocking a call to an object with a property of type List	var mockAsset = new Mock<ISecureAsset>();\n\nvar listOfContexts = new List<SecurityContext>();\n//add any fake contexts here\n\nmockAsset.Setup(x => x.Contexts).Returns(listOfContexts);	0
6421612	6421292	How Can I Get The Button Controls in Windows Form - Panel	List<Control> list = new List<Control>();\n\n            GetAllControl(this, list);\n\n            foreach (Control control in list)\n            {\n                if (control.GetType() == typeof(Button))\n                {\n                    //all btn\n                }\n            }\n\n        private void GetAllControl(Control c , List<Control> list)\n        {\n            foreach (Control control in c.Controls)\n            {\n                list.Add(control);\n\n                if (control.GetType() == typeof(Panel))\n                    GetAllControl(control , list);\n            }\n        }	0
27092558	27072679	Find a range of text with specific formatting with Word interop	rng.Find.Font.Underline  = wdUnderline.wdUnderlineSingle;	0
12852818	12852793	How to replace the URL using C#	string word = "www.abc/def/ghf/ijk/default.aspx";\nstring[] words = word.Split('/');\nwords[words.Length -1] = "newValueHere"\nword = String.Join("/", words);	0
25266380	25265892	Get returnvalue in xmlcomment	string xml = "<root>" + text + "</root>";\nXDocument doc = XDocument.Parse(xml);\nXElement returns = doc.Root.Element("returns");\nif (returns != null)\n{\n    string returnsDescription = returns.Value;\n    ...\n}	0
17048866	17048154	Test to compare array method fails	{ null, "19.75"}	0
1230147	1230136	Is it possible to release a variable in c#?	{\n    string x = "billy bob";    \n}\n{\n    string x = "some other string";\n}\n{\n    int x = 329;\n}	0
12265727	12262498	How to share a document in Google Drive in VB or C#	permissions.insert	0
6035988	6035832	Creating treeview from database	if ((int)dr["boss_id"] == XXX && DBNull.Value != dr["boss_id"])\n    {\n        TreeNode parent = new TreeNode();\n        parent.Text = dr["name"].ToString() + dr["surname"].ToString();\n        string value = dr["employe_id"].ToString();\n        parent.Expand();\n        treeView1.Nodes.Add(parent);\n        sublevel(parent, value);\n    }	0
21289409	21288899	SQL Server Stored Procedures - Read an existing decimal value and add another decimal value from a passed in parameter	CREATE PROCEDURE ProcName\n@keyColumnValue datatype,\n@valueToAdd decimal(10,2)\nAS\n\nUPDATE TableName\nSET DecimalColumnName = DecimalColumnName + @valueToAdd\nWHERE TableName.keyColumn= @keyColumnValue	0
2391850	2385003	How can you block the image to appear on WebBrowser Control?	string content = new WebClient().DownloadString(@"http://www.google.com/");\nstring contentWithoutImages = Regex.Replace(content, @"<img(.|\n)*?>", string.Empty);\nwebBrowser1.DocumentText = contentWithoutImages;	0
18248201	18248168	DataTable Join all Rows Data	var text = string.Join(",", table.AsEnumerable()\n                                 .Select(x=>x["EMAIL"].ToString())\n                                 .ToArray());	0
28626967	28626805	How to get count of a generic list in C# and no need to consider items with null or empty values in the count?	listStudent.Where(\n  s => !string.IsNullOrWhiteSpace(s.Name) && s.Age != null\n).Count();	0
8391066	8390931	Create a Linq Expression with StartsWith, EndsWith and Contains passing a Expression<Func<T, string>>	public static Expression<Func<T, bool>> AddFilterToStringProperty<T>(\n    Expression<Func<T, string>> expression, string filter, FilterType type)\n{\n    return Expression.Lambda<Func<T, bool>>(\n        Expression.Call(\n            expression.Body,\n            type.ToString(),\n            null,\n            Expression.Constant(filter)),\n        expression.Parameters);\n}	0
29698007	29697374	how to replace array values in C#?	public static void Main(string[] args)\n    {\n      string[] test = { "value1", "value2", "value3" };\n\n      string resultString = string.Empty;\n\n      foreach (String s in test)\n      {\n          resultString += String.Format("%'{0}'%, ", s);\n      }\n\n      Console.WriteLine(resultString);\n      Console.ReadLine();         \n    }	0
17937504	17518894	DbMigrations in .NET w/ Code First: How to Repeat Instructions with Expressions	protected override void Seed(Fideli100.Models.Fideli100Context context)\n{\n    context.Companies.AddOrUpdate(\n            p => p.Name,\n            Enumerable.Range(1, 10).\n            Select( x => new Company { Name = Faker.Company.Name() }).ToArray()\n    );\n}	0
7789761	7789363	Sorting by Name (alphabetic) - Dual arrays	Array.Sort(YourStringArray); // Ascending\n\nArray.Reverse(YourStringArray); // Descending	0
12848012	12847960	Centering text in C# console app only working with some input	private static void centerText(String text)\n{\n    Console.Write(new string(' ', (Console.WindowWidth - text.Length) / 2));\n    Console.WriteLine(text);\n}	0
33365044	33280360	How to implement a MouseEnter Event on a Merged menustrip	private void eventoaelementos()\n {\n foreach(ToolStripMenuItem t in this.menuStrip1.Items)\n  {\n    t.MouseEnter += new EventHandler(metodoMouseEnter);\n    t.MouseLeave += new EventHandler(metodoMouseLeave);\n    foreach(ToolStripItem t2 in t.DropDownItems)\n    {\n      if(t2 is ToolStripMenuItem)\n      {\n         //To discard the ToolStripSeparator's case in which I \n        //obtain an exception\n          t2.MouseEnter += new EventHandler(metodoMouseEnter);\n          t2.MouseLeave += new EventHandler(metodoMouseLeave);\n       }\n     }\n   }\n}\n\nprivate void metodoMouseLeave(object sender, EventArgs e)\n    {\n      this.toolStripStatusLabel1.Text = "";\n    }\n\n    private void metodoMouseEnter(object sender, EventArgs e)\n    {\n      ToolStripItem t = sender as ToolStripItem;\n      if(t!=null)\n        {\n            this.toolStripStatusLabel1.Text = t.Text;\n        }\n    }	0
3787342	3787299	Subscribe to event of changing time on local system	Microsoft.Win32.SystemEvents.TimeChanged += \n    new EventHandler(SystemEvents_TimeChanged);\n\nvoid SystemEvents_TimeChanged(object sender, EventArgs e)\n{\n    // The system time was changed\n}	0
20995549	20995301	How to write DelegateCommand function parameters in VB.net	New DelegateCommand(Of Book)(AddressOf RemoveBook, AddressOf CanRemoveBook)	0
21899079	21898956	Postsharp: How to set the return value after an exception	public override void OnException(MethodExecutionArgs args)\n    {\n        args.FlowBehavior = FlowBehavior.Return;\n        args.ReturnValue = "Error Getting Value";\n    }	0
15197411	15197195	How to pass structure as pointer in C dll from C#	[DllImport("Tapi32.dll", SetLastError=true)]\nunsafe private static extern int lineDevSpecific(int* hLine, IntPtr lpParams);\n\nunsafe static void Main(string[] args) {\n    int vline=int.Parse("Ext101");\n    int* hline=&vline;\n\n    var sizeUserRec=Marshal.SizeOf(typeof(UserRec));\n    var userRec=Marshal.AllocHGlobal(sizeUserRec);\n    lineDevSpecific(hline, userRec);\n    var x=(UserRec)Marshal.PtrToStructure(userRec, typeof(UserRec));\n    Marshal.FreeHGlobal(userRec);\n}	0
21056270	21055854	Parsing strings that contain time values to a DateTime value	public DateTime convert(string date)\n{\n    int hour = int.Parse(date.Substring(0, 2));\n    int minute = int.Parse(date.Substring(2, 2));\n    if (hour < 12 && date.Substring(4, 2) == "PM")\n    {\n        hour = hour + 12;\n    }\n\n    return new DateTime(2014, 1, 10, hour, minute, 0);\n}	0
2437794	2437774	How to exit a method in the OnEntry method of a PostSharp aspect based on condition	[AttributeUsage(AttributeTargets.Method)] \n    public class IgnoreIfInactiveAttribute : OnMethodBoundaryAspect \n    { \n        public override void OnEntry(MethodExecutionEventArgs eventArgs) \n        { \n             if (condition) \n            { \n                eventArgs.FlowBehavior = FlowBehavior.Return;\n            } \n        } \n    }	0
13141600	13141473	Find width of a tree node	Graphics.MeasureString	0
8086011	8073710	Prevent databound DataGridView from sorting while editing	private void MyDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {\n        dirtyCellListenerEnabled = false;\n\n        SORT_ORDER.ValueType = MyDataGridView.Columns[e.ColumnIndex].ValueType;\n\n        foreach(DataGridViewRow r in MyDataGridView.Rows) {\n            r.Cells[SORT_ORDER.Index].Value = r.Cells[e.ColumnIndex].Value;\n        }\n\n        switch(MyDataGridView.SortOrder) {\n            case System.Windows.Forms.SortOrder.None:\n                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);\n                break;\n            case System.Windows.Forms.SortOrder.Ascending:\n                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Descending);\n                break;\n            case System.Windows.Forms.SortOrder.Descending:\n                MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);\n                break;\n        }\n        dirtyCellListenerEnabled = true;\n    }	0
32436401	32432578	Xamarin iOS hide placeholder on click	string _placeHolderText = "Some Test Placeholder...";\n\n  public override void ViewWillAppear (bool animated)\n  {\n     base.ViewWillAppear (animated);\n\n     var textView1 = new UITextField (new CGRect (0, 0, UIScreen.MainScreen.Bounds.Width, 100)) {\n        Placeholder = _placeHolderText,\n        BorderStyle = UITextBorderStyle.Line\n     };\n     textView1.EditingDidBegin += (object sender, EventArgs e) =>\n     {\n        textView1.Placeholder = string.Empty;\n     };\n     textView1.EditingDidEnd += (object sender, EventArgs e) =>\n     {\n        textView1.Placeholder = _placeHolderText;\n     };\n\n     var textView2 = new UITextField (new CGRect (0, textView1.Frame.Bottom, UIScreen.MainScreen.Bounds.Width, 100)) {\n        Placeholder = _placeHolderText,\n        BorderStyle = UITextBorderStyle.Line\n     };\n\n     this.View.AddSubviews (textView1, textView2);\n  }	0
7613901	7613576	How to open text in Notepad from .NET?	System.IO.File.WriteAllText(@"C:\test.txt", textBox.Text);\nSystem.Diagnostics.Process.Start(@"C:\test.txt");	0
9436459	9436381	C# RegEx string extraction	string text = "ImageDimension=655x0;ThumbnailDimension=0x0";\nRegex pattern = new Regex(@"ImageDimension=(?<imageWidth>\d+)x(?<imageHeight>\d+);ThumbnailDimension=(?<thumbWidth>\d+)x(?<thumbHeight>\d+)");\nMatch match = pattern.Match(text);\nint imageWidth = int.Parse(match.Groups["imageWidth"].Value);\nint imageHeight = int.Parse(match.Groups["imageHeight"].Value);\nint thumbWidth = int.Parse(match.Groups["thumbWidth"].Value);\nint thumbHeight = int.Parse(match.Groups["thumbHeight"].Value);	0
21532045	21531455	Word interop, table border	public void inserir_tabela(int numero_de_linhas, int numero_de_colunas) // insert table, here live my problema\n{\n    Word.Range range = w_doc.Range(ref missing, ref missing);\n    Word.Table myTable = range.Tables.Add(range, numero_de_linhas, numero_de_colunas);\n\n    myTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;\n    myTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;\n}	0
20028280	20028224	Issue with contains in linq to sql	string[] split = new string[] { };\n                if (Helper.DepartmentFilter != null)\n                {\n                    split = Helper.DepartmentFilter.Split(',');\n                }\n                var splitLength = split.Length;\n                using (dbEntities Context = new dbEntities())\n                {\n                    var result = (from me in Context.master_employee\n                                  join ud in Context.user_detail on me.employeeid equals ud.employeeid\n                                  where me.status.Equals("A")\n                                  && (splitLength  == 0 || split.Contains(me.department))\n                                  select new\n                                  {\n                                      ud.email,\n                                      me.employeeid,\n                                      me.name\n                                  }).ToList();\n\n                    return result;\n                }	0
1490782	1485245	My app domain won't unload	class Program\n{\n    static void Main(string[] args)\n    {\n        AppDomain appDomain = AppDomain.CreateDomain("MyTemp");\n        appDomain.DoCallBack(loadAssembly);\n        appDomain.DomainUnload += appDomain_DomainUnload;\n\n        AppDomain.Unload(appDomain);\n\n        AppDomain appDomain2 = AppDomain.CreateDomain("MyTemp2");\n        appDomain2.DoCallBack(loadAssembly);\n    }\n\n    private static void loadAssembly()\n    {\n        string fullPath = "LoadMe1.dll";\n        var assembly = Assembly.LoadFrom(fullPath);\n        foreach (Type type in assembly.GetExportedTypes())\n        {\n            foreach (MemberInfo memberInfo in type.GetMembers())\n            {\n                string name = memberInfo.Name;\n                Console.Out.WriteLine("name = {0}", name);\n            }\n        }\n    }\n\n    private static void appDomain_DomainUnload(object sender, EventArgs e)\n    {\n        Console.Out.WriteLine("unloaded");\n    }\n}	0
32450999	32450856	How I can make a button for browse a folder?	private void browse_Click(object sender, EventArgs e) \n{\n     if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n     {\n         textBox1.Text = folderBrowserDialog1.SelectedPath;\n     }\n}	0
5179687	5179638	Read width value in runtime	Double a = this.Column1.ActualWidth.Value;	0
18504401	18504227	how to remove windows service entry manually	sc delete "servicename"	0
15144073	15143969	Retrieve an ancestor attribute	Server = project.Ancestors("Server").Single().Attribute("Name").Value;\nDatabase = project.Ancestors("Database").Single().Attribute("Name").Value;	0
3727748	3727698	most efficient way to find largest of three doubles in .NET Microframework?	double result = accel[0];\nif (accel[1] > result) result = accel[1];\nif (accel[2] > result) result = accel[2];\nreturn result;	0
16282362	16281732	How to properly search and parse an array using a sequence of elements as the target	List<byte[]> Split(byte[] bArray)\n        {\n            List<byte[]> result = new List<byte[]>();\n            List<byte> tmp = new List<byte>();\n            int i, n = bArray.Length;\n            for (i = 0; i < n; i++)\n            {\n                if (bArray[i] == 0x13 && (i + 1 < n && bArray[i + 1] == 0x10))\n                {\n                    result.Add(tmp.ToArray());\n                    tmp.Clear();\n                    i++;\n                }\n                else\n                    tmp.Add(bArray[i]);\n            }\n            if (tmp.Count > 0)\n                result.Add(tmp.ToArray());\n            return result;\n        }	0
8673709	8673563	Listening for new processes: simple explanation needed	ManagementScope theScope = new ManagementScope("\\\\ComputerName\\root\\cimv2");\nObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_ProcessStartTrace");\nManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);\nManagementObjectCollection theCollection = theSearcher.Get();\nforeach (ManagementObject theCurObject in theCollection)\n{\n  MessageBox.Show(theCurObject["whatever properties you are looking for"].ToString());\n}	0
30773287	30771648	list view selection mode none in windows form applications	For Each item As ListViewItem In Me.List_Item.Items\n     item.Selected = false       \n Next	0
28222258	28221774	How to do Asyncronous Database calls on a background thread in C#	//setting up your background worker.\nvar worker = new BackgroundWorker();\nworker.DoWork += bgw_DoWork;\nworker.RunWorkerCompleted += bgw_WorkCompleted;\nworker.ProgressChanged += bgw_ProgressChanged;\n\nprivate void bgw_DoWork(object sender, DoWorkEventArgs e)\n{   \n    e.Result = ProjectDbInteraction.QueryProject(currentProjDb);\n}\n\nprivate void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    //Here you can inspect the worker and update UI if needed.\n}\n\nprivate void bgw_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    //check for errors, and other unexpected results first...\n    //assuming that savedProj is some private member variable of your class, \n    //just assign the variable to the Result here.\n    savedProj = (Project.Project)e.Result;\n}	0
717717	717595	c#: how to convert image field to int[]?	[TestMethod]\npublic void TestMethod1()\n{\n    int[] intArray = { 4, 8, 15, 16, 23, 42, 108, 342, 815, 1087, 6717 };\n\n    byte[] inputBytes = new byte[intArray.GetLength(0) * 4];\n\n    Buffer.BlockCopy(intArray, 0, inputBytes, 0, intArray.GetLength(0) * 4);\n\n    int[] outputInts = new int[intArray.GetLength(0)];\n\n    Buffer.BlockCopy(inputBytes, 0, outputInts, 0, intArray.GetLength(0) * 4);\n\n    Assert.IsTrue(Enumerable.SequenceEqual(intArray, outputInts));\n\n}	0
21554765	21554723	Swapping each word in a string into a certain order	txtOutputBox.Text = String.Join(" ", txtInputBox.Text.Split().Reverse());	0
18700260	18699717	Setting ToolTip for DataGridView automatically created columns	void payloadDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n{\n    string tooltip = null;\n\n    switch (e.Column.Header.ToString())\n    {\n        case "Column 1":\n            tooltip = "Tooltip 1";\n            break;\n        case "Column 2":\n            tooltip = "Tooltip 2";\n            break;\n    }\n\n    if (tooltip != null)\n    {\n        var style = new Style(typeof(DataGridCell));\n        style.Setters.Add(new Setter(ToolTipService.ToolTipProperty, tooltip));\n        e.Column.CellStyle = style;\n    }\n}	0
31541511	31541418	C# Move file from bool	foreach (var file in directory.EnumerateFiles().Where(file => !allowedCLEOFiles.Contains(file.Name)) {\n    File.Move(file.Name, destination);\n}	0
10086390	10086213	Can I change the web.config connection string due to a Request parameter?	string strDevConnection = @"Data Source=DEVELOPMENT\SQLEXPRESS;Initial Catalog=sqlDB;Persist Security Info=True;User ID= ;Password= ";\n\nstring strLiveConnection = @"Data Source=PRODUCTION\SQLEXPRESS;Initial Catalog=sqlDB;User id= ;password= ";\n\nConfiguration myWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");\nif (Request["connectionToUse"] + "" == "constr1")\n\n{\n\nmyWebConfig.ConnectionStrings.ConnectionStrings["constr1"].ConnectionString = strDevConnection; //constr1 is the name of the current connectionstring in the web.config\n\n}\n\nelse\n\n{\n\nmyWebConfig.ConnectionStrings.ConnectionStrings["constr2"].ConnectionString = strLiveConnection;\n\n}\n myWebConfig.Save(); //Save the changes to web config	0
32848275	32847773	How to play a streaming audio file using the default audio player in Xamarin iOS	UIApplication.OpenUrl	0
4875746	4875501	New Picturebox in a TableLayoutPanel?	pb.BringToFront();	0
26519484	26494072	How to display a Modal form in Windows Phone 8.1	private async void Button_Click(object sender, RoutedEventArgs e)\n{\n    ContentDialog1 cd = new ContentDialog1();\n    cd.TestData = "Lorem ipsum";\n    await cd.ShowAsync();\n}	0
9709464	9709317	Searching ListBox control and programmatically selecting closest match	match = lbBranches.SelectedItem.ToString();	0
15160236	15160179	Pointing variables at other variables in c#	private <type> prox\n{\n    get { return SharedResources.proxTelescope; }\n    set { SharedResources.proxTelescope = value }\n}	0
30318120	30318076	How to get only the Time from DateTime datatype	var model = from Ts in db.TimeSpans \n            let time = EntityFunctions.CreateTime(Ts.StartTime.Hours,\n                                                  Ts.StartTime.Minutes,\n                                                  Ts.StartTime.Seconds)\n            where time < startTime \n            select Ts;	0
2717270	2717250	Is it possible to use Data Annotations to validate parameters passed to an Action method of a Controller?	public ActionResult MyAction [ModelBinder(typeof(StringBinder)] string param1, [ModelBinder(typeof(StringBinder2)] string param2)\n{\n  .........\n}	0
9370727	9107576	Is it possible to return a specific exit code when user abruptly close my console app?	static void Main(string[] args)\n    {\n        Environment.ExitCode = -1;\n        for (int i = 0; i < 20; i++)\n        {\n            Thread.Sleep(1000);\n        }\n\n        Environment.ExitCode = 0;\n        Console.WriteLine("Done!");\n    }	0
25033324	25033186	Invalid date time with 1 month digit instead of 2	startDate = startDate.replace(/(\b\d\b)/g, "0$1");	0
20745485	20745323	Object to URL String	var obj = new example { ... };\nvar result = new List<string>();\nforeach (var property in TypeDescriptor.GetProperties(obj))\n{\n    result.Add(property.Name + "=" + property.GetValue(obj));\n}\n\nreturn string.Join("&", result);	0
34517681	34516296	C# using a return variable instead of a global variable	public static class ThisAddInManager\n{\n    struct someProperties\n    {\n        public string foo, bar;\n    }\n\n    public static var SomeProperties { private get; set; } = new someProperties();\n    public static var UI { private get; set; } = new formClass();\n\n    public static void OpenUI() => UI.showDialog();\n    public static void RunFunction() => doSomethingWith(SomeProperties);   \n}	0
32906215	32905974	Checking for alphanumeric values with asp:RegularExpressionValidator alwas shows ErrorMessage	ValidationExpression="[A-Za-z0-9]+"	0
895785	895778	How Do I Get the Selected DataRow in a DataGridView?	var drv = bindingSoure1.Current as DataRowView;\nif (drv != null)\n  var row = drv.Row as MyRowType;	0
12833441	12833433	Remove all entry with -1	var i2 = i1.Where(m => m!= -1).ToArray()	0
9412927	9412865	Generics in XML documentation issue	/// <summary>\n /// Calls <see cref="DoSomething{T}"/>.\n /// </summary>\n public void CallsDoSomething()\n {\n\n }\n\n public void DoSomething<T>()\n {\n\n }	0
16842676	16842611	How to get the center part of string on C#	string[] result = temp.Split(new string[] { "<a href=\"http://example.com/index.php?action=profile\"><span>" , "</span></a>" }, StringSplitOptions.RemoveEmptyEntries);	0
10063814	10063580	WinForm: multiple keys pressed	private enum ShipMotionState { NotMoving, MovingLeft, MovingRight };\n    private ShipMotionState shipMotion = ShipMotionState.NotMoving;\n\n    protected override void OnKeyDown(KeyEventArgs e) {\n        if (e.KeyData == Keys.Left)  shipMotion = ShipMotionState.MovingLeft;\n        if (e.KeyData == Keys.Right) shipMotion = ShipMotionState.MovingRight;\n        base.OnKeyDown(e);\n    }\n    protected override void OnKeyUp(KeyEventArgs e) {\n        if ((e.KeyData == Keys.Left  && shipMotion == ShipMotionState.MovingLeft) ||\n            (e.KeyData == Keys.Right && shipMotion == ShipMotionState.MovingRight) {\n            shipMotion = ShipMotionState.NotMoving;\n        }\n        base.OnKeyUp(e);\n    }\n\n    private void GameLoop_Tick(object sender, EventArgs e) {\n        if (shipMotion == ShipMotionState.MovingLeft)  spaceShip.MoveLeft();\n        if (shipMotion == ShipMotionState.MovingRight) spaceShip.MoveRight();\n        // etc..\n    }	0
22331383	22330600	Searching for the nearest file name in many folders	var file = "20140316182212.jpg";    \nvar fileNum = Convert.ToInt64(Path.GetFileNameWithoutExtension(file));\n\nvar minDiff = Directory.EnumerateFiles(searchPath, "*.jpg", SearchOption.AllDirectories)\n             .Select(path => Convert.ToInt64(Path.GetFileNameWithoutExtension(path)))\n             .Min(num => Math.Abs(fileNum - num));\n\nvar result = Directory.EnumerateFiles(searchPath, "*.jpg", SearchOption.AllDirectories)\n            .First(path => Math.Abs(fileNum - Convert.ToInt64(Path.GetFileNameWithoutExtension(path))) == minDiff);	0
28136266	28136198	How to access a file in the dll's folder instead of the executable?	Assembly.GetExecutingAssembly().Location	0
6828326	6828010	Read column from dataGridView and place it in a string array	for (int i = 0; i < dataGridView1.Rows.Count; i++)\n    colB[i] = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);	0
5499445	5499379	find out if long/lat within rectangle	return new Rect(topLeftLat, topLeftLong, bottomRightLat - topLeftLat, bottomRightLong - topLeftLong)\n      .Contains(testLat, testLong);	0
5888210	5888144	converting an array in a json string into a list	string theArray = "1,2,3,4,5";\n\nList<int> theList = (\n  from string s in theArray.Split(',') \n  select Convert.ToInt32(s)\n).ToList<int>();	0
6530171	6525765	when changing DataGridView combobox to Default Value, it throws exception	void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e)\n{\n     if (e.Column == dt.Columns["myColumn"])\n     {\n         if (e.ProposedValue == null)\n         {\n              e.ProposedValue = DBNull.Value;\n         }\n     }\n}	0
23961489	23961432	Sort List<Point> ListOfPoints that reside on a straight line in C#	ListOfPoints.OrderBy(pt => pt.X).ThenBy(pt => pt.Y).ToList();	0
25751657	25749893	How can I get a windows users session id using C#?	ITerminalServicesManager manager = new TerminalServicesManager();\n        using (ITerminalServer server = manager.GetLocalServer())\n        {\n            server.Open();\n            var result = server.GetSessions().Where(x => x.UserName == "name").SingleOrDefault();\n\n            Console.WriteLine(result.SessionId);\n        }	0
31960090	31959955	Search for decimal 250 in NotSupportedException in Code	else if (Divide > RESULT_MAXVALUE) //RESULT_MAXVALUE is an const public decimal = 250\n        {\n            if (RESULT_MAXVALUE == 250)\n                Console.WriteLine("Everything's fine");\n            else \n                throw new NotSupportedException()\n        }	0
30324084	30324029	string join append each element text	var arrayWithText = arr.Select(a => "{\"text\":\"" + a + "\"}");\nvar result = string.Join(",", arrayWithText);	0
18322644	18321744	How to change Location(Url) of a Web Service and Update Web Reference programmatically?	interface IMyData \n{\n      string GetLastName();\n}\n\nclass MyDataFromOldWebService\n{\n    MyApi.MyApiV1 service;\n    MyDataFromOldWebService(MyApi.MyApiV1 service)\n    {\n      this.service = service;\n    }\n    public string GetLastName()...\n}\n\nDictionary<string, IMyData> services = new Dictionary<string, IMyData>()\n  {\n      { "Old Service", new MyDataFromOldWebService(new MyApi.MyApiV1(url))}\n  };	0
13265826	13265762	How to add a rtf formatting in the text string for a Richt Text Box?	rtfTxt.Rtf = @"{\rtf1\ansi This is some \b bold\b0 text.}";	0
30179401	30177564	.Net Reformat data in the List of List of Sting	List<List<string>> lstStrings = new List<List<string>>{\n               new List<string>() {"A1","A2","A3"},\n               new List<string> {"B1","B2","B3"},\n               new List<string> {"C1","C2","C3"}\n                };\n                List<List<string>> newList = new List<List<string>>();\n                int j=0;\n                 foreach(String s in lstStrings[0])\n                 {\n\n                     List<string> innerList = new List<string>();\n                     for(int i=0;i<lstStrings.Count;i++)\n                    {\n                        innerList.Add(lstStrings[i][j]);    \n                    }\n                    j++;\n                    newList.Add(innerList);\n            }\n            foreach(List<string> lstInner in newList)\n            {\n                foreach(string s in lstInner)\n                {\n                    Console.Write(s);    \n                }\n                Console.WriteLine();\n            }	0
28764491	27098718	how to remove a route from routes table	//Create the object of particular router\nvar rr = new System.Web.Routing.Route(tblcmspage.PageUrlName, new MvcRouteHandler())\n            {\n                Defaults = new System.Web.Routing.RouteValueDictionary(new { controller = "MyPages", action = "en" }),\n                DataTokens = new System.Web.Routing.RouteValueDictionary(new { namespaces = new[] { "MGP_RealState.Controllers" } })\n            };\n\n//delete the router                \nSystem.Web.Routing.RouteTable.Routes.Remove(rr);	0
4922315	4921423	Trying to read a blob	using(reader)\n{\n      //Obtain the first row of data.\n      reader.Read();\n      //Obtain the LOBs (all 3 varieties).\n      OracleLob BLOB = reader.GetOracleLob(1);\n      ...\n\n      //Example - Reading binary data (in chunks).\n      byte[] buffer = new byte[100];\n      while((actual = BLOB.Read(buffer, 0, buffer.Length)) >0)\n         Console.WriteLine(BLOB.LobType + ".Read(" + buffer + ", " + buffer.Length + ") => " + actual);\n\n      ...\n}	0
3816300	3815492	External alias in XAML	namespace Alias\n{\n    public class MenuItem : System.Windows.Controls.MenuItem\n    {\n    }\n}	0
3268367	3268325	Getting rid of multiple periods in a filename using RegEx	string s = "1.0.1.21 -- Confidential...doc";\ns = Regex.Replace(s, @"\.(?=.*\.)", "");\nConsole.WriteLine(s);	0
15904660	15904574	How to stop Paint events from stacking up	// Label temp = new Label();\n      // temp.Text = userList[i].Text;\n      // temp.Width = panelUsers.Width;\n      // temp.Height = 50;\n      // temp.BorderStyle = BorderStyle.FixedSingle;\n      // temp.Location = new Point(0, i * 50);\n      // temp.TextAlign = ContentAlignment.MiddleCenter;\n      // panelUsers.Controls.Add(temp);	0
33258922	33258423	How to control instantiated prefabs at runtime as children	gameObject.transform.parent = GameObject.Find("Name of game object").transform;	0
6295900	6295715	Convert VBScript to C#	using System;\nusing System.Linq;\nusing System.IO;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nstatic class Program\n{\n  static void Main ()\n  {\n     string filename = "filename";\n     string [] needles = new [] {"Goo", "Moo"};\n     Dictionary<string,int> dicNeedles = needles.ToDictionary (s => s, s => 0);\n     string ex = string.Join ("|", needles);\n     string all = File.ReadAllText (filename);\n     Regex regex = new Regex (ex);\n     string newFile = regex.Replace (all, m => ("N" + (++dicNeedles[m.Value]) + " " + m.Value));\n     File.WriteAllText (filename, newFile);\n  }\n}	0
6535042	6508815	Facebook c# sdk - how to make "Share" link show up when publishing post	var result = client.Post(string.Format("/{0}/links", profileId), messagePost);	0
29577682	29577639	In C#, how can I filter a list using a StartsWith() condition of another list?	var resultList = fullNameList.Where(r => searchList.Any(f=>r.StartsWith(f)));	0
10367062	10367013	CookieContainer manual cookie override	new Cookie("cookie", HttpUtility.UrlEncode("val1%2Cval2"))	0
30567725	30567479	Simple previous\next slider using angular	> <li ng-repeat="datalist in datalists | pagination: curPage * pageSize\n> | limitTo: pageSize">	0
3916130	3916049	Convert SQL Binary to byte array	using System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary\n\npublic byte[] ToBytes(string hex)\n{\n    var shb = SoapHexBinary.Parse(hex);\n    return shb.Value;\n}\n\npublic void TestConvert()\n{\n    byte[] someBytes = ToBytes("83C8BB02E96F2383870CC1619B6EC");\n}	0
14012997	14012926	Analyze identification number with 12 digits	[WebMethod]\npublic string ID(string number)\n{\n    int fullInt = Int32.Parse(number);// if (Regex.IsMatch(number, @"\D")) throw new ArgumentException();\n    string City1_S = "Date of birth: " + number.Substring(0, 2);\n    string City2_S = "Month: " + number.Substring(2,2);\n    string City3_S = "Year: 1" + number.Substring(4, 3);\n\n    string City4_S = "";\n    var digitStr = number.Substring(7, 2);\n    switch (digitStr)\n    {\n        case "40":\n             City4_S = "City: London";\n             break;\n        case "45":\n             City4_S = "City: NY";\n             break;\n    }\n\n    string[] Array = new [] { City1_S,  City2_S, City3_S, City4_S };\n\n    return Array.ToString();//something wrong =)\n    //return string.Join(" ", Array);\n    //return Array[0] + " " + Array[1] + " " + Array[2] + " " + Array[3];\n}	0
20425599	20425383	Possible to temporarily store a file locally before sending to ftp server?	client.UploadData()	0
30927592	30927436	C# - Is it possible to pass a derived type from a BaseModel to a Repository<T> that needs the type?	public class BaseModel<T> // T will be your derived type\n{\n    public string Id { get; set; }\n    public DateTime Created { get; set; }\n\n    public void Save()\n    {\n        // T will be your derived type now\n        using(var repository = new Repository<T>()) {\n            repository.Save(this);\n        }\n    }\n}\n\npublic class Repository<T>\n{\n    // Save method must use base type here\n    public void Save(BaseModel<T> item )\n    {\n\n    }\n}\n\n// BaseModel will get the derived type as type parameter\npublic class DerivedModel : BaseModel<DerivedModel>\n{\n    public string Name { get; set; }\n}	0
3990942	3990809	How to persist DateTime Kind while storing a datetime object into a data table?	var col = new DataColumn("Date1", typeof(DateTime));\ncol.DateTimeMode = DataSetDateTime.Utc;\ntable.Columns.Add(col);	0
12659528	12659472	How Use From HTMLAgilityPack For Finding A String in nested divs	document.DocumentNode.SelectSingleNode("//div[@class='class1 class2 class3']/div[@class='class4 class5']/span[@class='class6']").InnerText;	0
4311510	4309702	whats is the best way of getting the name of the controller action that i am currently in	var action = RouteData.Values["action"];	0
28049182	28029819	Debugging Custom Control Not Hitting Breakpoint	AreaPickerDotNet()	0
31045110	31040961	Delete Row In a DataGrid for a WPF browser Application	private void Delete_Click(object sender, RoutedEventArgs e)\n    {\n         dataset.foodSupplier.DefaultView.Delete(foodSupplierDataGrid.SelectedIndex);\n         this.DataContext = dataset.foodSupplier.DefaultView;\n    }	0
957953	957938	Multiplying strings in C#	public static string Multiply(this string source, int multiplier)\n{\n   StringBuilder sb = new StringBuilder(multiplier * source.Length);\n   for (int i = 0; i < multiplier; i++)\n   {\n       sb.Append(source);\n   }\n\n   return sb.ToString();\n}\n\nstring s = "</li></ul>".Multiply(10);	0
34306107	34305891	How to pass JSON parameter with $ajax to asmx web service	// remove the outer quotes so they are json objects then json encode.\nvar pMaster = JSON.stringify({"tid" : "474", "fid":"2"});\nvar pDetail = JSON.stringify(\n    {"[{"recid":5618,"tid":"474","itemid":"1435","nar1":""}, \n    {"recid":5619,"tid":"474","itemid":"1203","nar1":""},\n    {"recid":5620,"tid":"474","itemid":"1205","nar1":""}]);\n// then create e by stringify a second time\n\nvar e = JSON.stringify({PurcMast: pMaster , PurDetail: pDetail });	0
26762860	26760142	Need to change sql server query into linq	// Model class for View\npublic class UsersPerTeamCount\n{\n    public string TeamName { get; set; }\n    public string Description { get; set; }\n    public int Count { get; set; }\n}\n\n// ...\n\npublic ActionResult PlayersPerTeam()\n{\n    var model = from t in db.Teams\n                    join u in db.Users on t.TeamId equals u.TeamId into joinedRecords\n                    select new UsersPerTeamCount()\n                    {\n                        Name = t.TeamName,\n                        Description = t.Description,\n                        PlayerCount = joinedRecords.Count()\n                    };\n\n    return View(model);\n}	0
12867190	12867169	get default value for a type	pro.SetValue(objT, row.IsNull(pro.Name) ? null : row[pro.Name], null);	0
4224029	4223860	How to add a label apon mouse click on the same spot in C#?	public Form1()\n{\n    InitializeComponent();\n    MouseClick += new MouseEventHandler(Form1_MouseClick);\n}\n\nprivate void Form1_MouseClick (object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        ContextMenuStrip ctxMenu = new ContextMenuStrip();\n\n        // following line creates an anonymous delegate\n        // and captures the "e" MouseEventArgs from \n        // this method\n        ctxMenu.Items.Add(new ToolStripMenuItem(\n           "Insert info", null, (s, args) => InsertInfoPoint(e.Location)));\n\n        ctxMenu.Show(this, e.Location);\n    }\n}\n\nprivate void InsertInfoPoint(Point location)\n{\n    // insert actual "info point"\n    Label lbl = new Label()\n    {\n        Text = "new label",\n        BorderStyle = BorderStyle.FixedSingle,\n        Left = location.X, Top = location.Y\n    };\n    this.Controls.Add(lbl);\n}	0
6080119	6059149	How to listen to a TCP port which is already being listened by another app	'/*Variables Initialization*/\ndim objSocket, strServicePort, strIpAddr, strResult, strMsgTo, strMsgResponse   \nstrServicePort = "6002"\nstrIpAddr = "127.0.0.1"\n\n'/* Create a TCP/IP socket. */\nobjSocket = Server.CreateObject("Intrafoundation.TCPClient.3")\nobjSocket.ClearLog()\n\n'/* Establish socket connection. */\nobjSocket.Open (strIpAddr,strServicePort)\nobjSocket.Timeout=60.0 \nstrMsgTo ="---- Message here ----"\n\n'/* Send request message to plugin  */\n\nobjSocket.SendRN(strMsgTo) \n\n'/* receive XML Request Message from plugin  */\nstrMsgResponse = objSocket.Recv()\nstrMsgResponse = Replace(strMsgResponse, vbLf, "")\n\nobjSocket.Close()	0
17967472	17966904	how to set the X:Name property through C# in wpf datagrid column	//Registe it in a Method of a Window class\nthis.RegisterName("mark", clm);\n//Use it in another Method like this\nDataGridTextColumn clm2 = this.FindName("mark") as DataGridTextColumn;	0
17610825	17609805	Crystal Report: hide some objects with Format Object - Suppress Formula	{MyModel.Show1} = true	0
10758623	10757666	Dependency Property - Unable to Set Value From XAML	public static void SetPassColor(DependencyObject obj, string passColor)\n    {\n        obj.SetValue(PassColorProperty, passColor);\n    }\n\n    public static string GetPassColor(DependencyObject obj)\n    {\n        return (string)obj.GetValue(PassColorProperty);\n    }	0
5065454	5065422	Is it possible, in MVC3, to have the same controller name in different areas?	//Map routes for the main site. This specifies a namespace so that areas can have controllers with the same name\nroutes.MapRoute(\n        "Default",\n        "{controller}/{action}/{id}",\n        new { controller = "Home", action = "Index", id = UrlParameter.Optional },\n        new[]{"MyProject.Web.Controllers"}\n );	0
27216943	27216126	What is the proper way to turn a bitmap around a certain point, with a certain degree?	private Bitmap HourHand;\n    private int HourDegree =45;\n\n    private void pictureBox1_Paint(object sender, PaintEventArgs e)\n    {\n        Graphics g = e.Graphics;\n        g.TranslateTransform(pictureBox1.Width / 2, pictureBox1.Height / 2);\n        g.RotateTransform(HourDegree);\n        g.DrawImage(HourHand, new Point(0, 0));\n    }	0
23566767	23566683	Specifying 2 dimensional array of strings elegantly	int[] numContacts = { 32, 24, 48, 32 };\n\nString[][] descriptions = numContacts.Select(c => new string[c]).ToArray();	0
32658971	32658504	How to make validation with for loop inside if statement	int categoryIdIndex = 7;\nint productIdIndex = 3;\nint quantityRequestedIndex = 5;\n\nList<string> errors = new List<string>()\nfor (int index = 0; index < this.gridagree.Rows.Count; index++)\n{\n  Row row = gridagree.Rows[index];\n  int categoryId = Convert.ToInt32(row.Cells[categoryIdIndex].Text);\n  int productId = Convert.ToInt32(row.Cells[productIdIndex].Text);\n  int quantityRequested = Convert.ToInt32(row.Cells[quantityRequestedIndex].Text);\n  int availableQuantity = s.getprodqun(productId);\n\n  if(quantityRequested > availableQuantity)\n  {\n    errors.Add(string.Format("Inventory contains insufficient items for product id {0} ", productId));\n  }\n}\n\nif(errors.Count == 0)\n{\n  ... process the orders ...\n}\nelse\n{\n  ... show the errors\n}	0
7672558	7650420	Running Multiple WebRequests at the same time with $.ajax	[SessionState(SessionStateBehavior.Disabled)]\npublic class SomeController	0
29794917	29777662	Multiple connections with different connection strings	DataSet ds = new DataSet();\nds.Tables.Add(GetData(GetConnectionString(conStringBlm), CmdStrBlm));\n//... do this for each connection string \nDataTable dtAll = ds.Tables[0].Copy();\n        for (var i = 1; i < ds.Tables.Count; i++)\n        {\n            dtAll.Merge(ds.Tables[i]);\n        }\n        dataGridView1.AutoGenerateColumns = true;\n        dataGridView1.DataSource = dtAll;	0
2423095	2423075	new string of string in code 	string x = @"Hello\nworld";	0
22289830	22289555	How to access a variable from another class	public class CurrentUser\n{\n  private string _user;\n  public string User\n  {\n    get { return _user; }\n    set { _user = value; }\n  }\n  //this gets pushed in the beginning of the program\n  private void btn_click(object sender, RoutedEventArgs e)\n  {\n     if(String.IsNullOrEmpty(txtUsername.Text)\n     {\n         _user = "No name";\n     }\n     else\n     {\n         _user= txtUsername.Text;\n     }\n  }\n}\n\npublic class Game\n{\n     public void DoSomething()\n     {\n         var myCurrentUser = new CurrentUser();\n         var user = myCurrentUser.User;\n         Console.WriteLine(user);\n     }\n}	0
32361871	32361747	How to check an array for an element	var memberDescription = result.Members["description"] as PSObject[];\n\nif (memberDescription != null && memberDescription.Value != null){\n    foreach (PSObject d in memberDescription.Value )\n    {\n        paramDesc.Append(d.Members["Text"].Value);\n    }\n}	0
14157269	14140395	Preventing OnClientClick to newtab of Button to trigger Other clicks on the page	btnPrint.Attributes.Add("onclick", "window.open('yourpage.aspx'); return false;");	0
10372873	10372495	Rotation around a point	Vector3 Origin;     // Stationary Object\n\n  float Yaw, Pitch;   // Angles \n\n  float Distance;     \n\n  Vector3 OrbitOffset = Vector3.UnitX * Distance;\n\n  // Other approach that consider the initial pos of the object to rotate\n  // Vector3 OrbitOffset = OrbitPos - Origin;       \n\n  Matrix Rotation = Matrix.CreateFromYawPitchRoll(Yaw, Pitch, 0);\n\n  Vector3.Transform(ref OrbitOffset, ref Rotation, out OrbitOffset);\n\n  Vector3 OrbitPos = Origin + OrbitOffset;  // Final position of the rotated object	0
13853550	13853400	Removing the user interaction from a Javascript pop up	popwin = window.open(URL, '" + id + "','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=750, height=600,left = 262,top = 84');\nSetTimeOut(function(){ popwin.close()},2000);	0
23877076	23875388	How to sort GridView by a 2-level object property	public Expression<Func<T, object>> GetLambdaExpressionForSortProperty(string propertyname) where T : class\n{\n    Expression member = null;\n    var propertyParts = propertyname.Split(new[]{'.'}, StringSplitOptions.RemoveEmptyEntries);\n    var param = Expression.Parameter(typeof(T), "arg");\n    Expression previous = param;\n\n    foreach(string s in propertyParts)\n    {\n        member = Expression.Property(previous, s);\n        previous = member;\n    }\n\n    if(member.Type.IsValueType)\n    {\n        member = Expression.Convert(member, typeof(object));\n    }\n\n    return Expression.Lambda<Func<T, object>>(member, param);\n}\n\nprotected void gridView_OnSorting(object sender, GridViewSortEventArgs e)\n{\n    var orderby = GetLambdaExpressionForSortProperty<DataModel>(e.SortExpression);\n    var sortedData = YourDataArray.OrderByAscending(orderby).ToList();\n    gridView.DataSource = sortedData;\n    gridView.DataBind();\n}	0
18804662	18804346	Superfluous scroll bars in WinForms	private void listView1_Resize(object sender, EventArgs e) {\n        this.BeginInvoke(new Action(() => {\n            var lv = (ListView)sender;\n            var w = 0;\n            for (int ix = 0; ix < lv.Columns.Count - 1; ++ix) w += lv.Columns[ix].Width;\n            w = Math.Max(0, lv.ClientSize.Width - w);\n            lv.Columns[lv.Columns.Count - 1].Width = w;\n        }));\n    }	0
28193373	28193294	How to join a list of lists in a unique list using Linq	LIST1.SelectMany(a => a.LIST2.Select(b => b.Id)).Distinct();	0
32184400	32184161	How to get the name of a control that has started an event?	private void ClearTable_Click(object sender, RoutedEventArgs e)\n{\n    // Try to cast the sender to a Control\n    Control ctrl = sender as Control;\n    if (ctrl != null)\n    {\n        // Get the control name\n        string name = ctrl.Name;\n\n        // Get parent control name\n        Control parent = (Control) ctrl.Parent;\n        string parentName = parent.Name\n    }\n}	0
5153624	5153600	How to check that object implements interface	if(b is A)\n{\n    // do something\n}	0
6050174	6050052	Add generic EntityObject to ObjectContext	ObjectContext.CreateObjectSet<YourEntityType>().AddObject(yourEntity)	0
30786119	30786092	select random data from database in mvc4 C#	(from p in products orderby  Guid.NewGuid() select p).Take(10).ToList()	0
18906403	18905468	What is the SQL to get the first val in a column in a table?	public string GetVersion()\n{\n    using (var connection = new SqlCeConnection("my connection string"))\n    {\n        connection.Open();\n        using (var command = new SqlCeCommand("SELECT id FROM invHeader", connection))\n        using (var reader = command.ExecuteReader())\n        {\n            if (reader.Read())\n            {\n                return reader.GetString(0);\n            }\n            else\n            {\n                // no result\n                return null;\n            }\n        }\n    }\n}	0
27612042	27611982	Issue with SubString function	if(!string.IsNullOrEmpty(X)) \n{\n  char.ToUpper(X[0]) + X.Substring(1)\n}	0
2210485	2210392	How can I mock a collection using Moq	mockItem.SetupGet(x => x.Attributes).Returns(mockAttributes);\n\nmockAttributes.SetupGet(x => x[It.IsAny<System.Type>()])\n              .Returns(deviceAttribute);	0
13350760	13350262	Group by same value and contiguous date	int currentValue = 0;\nint groupCounter = 0;\n\nFunc<KeyValuePair<DateTime, int>, int> keyGenerator = kvp =>\n{\n  if (kvp.Value != currentValue)\n  {\n    groupCounter += 1;\n    currentValue = kvp.Value;\n  }\n  return groupCounter;\n}\n\nList<IGrouping<int, KeyValuePair<DateTime, int>> groups =\n  myDictionary.GroupBy(keyGenerator).ToList();	0
32736703	32735389	Dynamic search in C# ListView	textbox_textChanged(Sender sender, SomeArgs args)\n{\n    lv.Clear();\n    foreach(var item in originalCollection)\n    {\n        if(item.name.Contains(textbox.Text)\n            lv.Add(item);\n    }\n}	0
5166082	5152723	cURL with user authentication in C#	request.ContentType = "text/xml";	0
16807648	16807567	How to get distinct values in my dropdown list MVC	lstRefrenceDataReturn = context.JobsRoles\n  .GroupBy(r => r.RoleName)\n  .Select(g => g.FirstOrDefault())\n  .Select(items => new RefrenceDataModel() { RefrenceDataName = items.RoleName, RefrenceDataID = items.RoleID }).ToList<RefrenceDataModel>();	0
11632683	11632561	set javascript array from DataTable in code behind	int[] videoQarray = new int[dt_questionVideo.Rows.Count - 1];\n        for (var i = 0; i < dt_questionVideo.Rows.Count - 1; i++) {\n            videoQarray[i] = Convert.ToInt32(dt_questionVideo.Rows[i][0]);\n        }\n\n        string createArrayScript = string.Format("var videoQarray = [{0}];", string.Join(",", videoQarray));\n\n        Page.ClientScript.RegisterStartupScript(this.GetType(), "registerVideoQArray", createArrayScript, true);	0
6378017	6377753	C# : How to sign in and keep it valid and make another webrequest?	//this only has login/password info, you may need other parameters to trigger the appropriate action:\n        const string Parameters = "Login1$username=pfadmin&Login1$Password=password";\n\n        System.Net.HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("http://[WebApp]/Login.aspx");\n\n        req.Method = "GET";\n        req.CookieContainer = new CookieContainer();\n        System.Net.HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n\n        //Create POST request and transfer session cookies from initial request\n        req = (HttpWebRequest)System.Net.WebRequest.Create("http://localhost/AdminWeb/Login.aspx");\n        req.CookieContainer = new CookieContainer();\n        foreach (Cookie c in resp.Cookies)\n        {\n            req.CookieContainer.Add(c);\n        }\n        req.ContentType = "application/x-www-form-urlencoded";\n        //...continue on with your form POST	0
4291091	4291077	Add events to controls added dynamically	// create some dynamic button\nButton b = new Button();\n// assign some event to it\nb.Click += (sender, e) => \n{\n    MessageBox.Show("the button was clicked");\n};\n// add the button to the form\nControls.Add(b);	0
13186697	9888280	Simplest way to flatten document to a view in RavenDB	public class A_View : AbstractIndexCreationTask<DocA, ViewA>\n{\n    public A_View()\n    {\n        Map = docs => from doc in docs\n                      select new ViewA\n                      {\n                          Id = doc.Id,\n                          Name = doc.Name,\n                          CurrencyName = doc.Currency.Name\n                      };\n\n        // Top-level properties on ViewA that match those on DocA\n        // do not need to be stored in the index.\n        Store(x => x.CurrencyName, FieldStorage.Yes);\n    }\n}	0
28685991	28662524	C# Selenium - Finding Element On Continuously Growing Page	IWebElement bio = SeleniumDriver.FindElement(By.XPath("path"));\n                Actions actions = new Actions(SeleniumDriver);\n                actions.MoveToElement(bio);\n                actions.Perform();	0
4601255	4601228	Round any n-digit number to (n-1) zero-digits	public int Round( int number)\n{\n    int power = number.ToString().Length - 1;\n    int sz = Math.Pow(10, power);\n\n    int rounded = (int)Math.Round( number / sz );\n\n    return rounded * sz;\n}	0
21556661	21556410	Split list into current and archive items	var maxList = yourList.GroupBy(x => x.Name)\n                      .Select(x => x.Where(y => y.Id == x.Max(z => z.Id)))\n                      .SelectMany(x => x);\n\nvar theRest = yourList.Except(maxList);	0
8581313	8538698	Set SelectedValue in DataGridViewComboBoxColumn or DataGridViewComboBoxCell	dgrDetalle.DataSource = dataTable("select * from yourTable");\n   DataTable dtCombo = dataTableCombo("select COL_ID DETOC_COL_FK,COL_DESCRIPCION from yourTable2");\n   string[] strColumns = new string[] { "COL_DESCRIPCION" };\n   MultiColumnDictionary map = new MultiColumnDictionary(dtCombo, "DETOC_COL_FK", strColumns, 0);\n   dgrDetalle.Cols["DETOC_COL_FK"].DataMap = map;	0
6852544	3555097	Evaluating an expression stored as a string	bcParser.NET	0
11391026	11390561	Select Value of List of KeyValuePair	var matches = from val in myList where val.Key == 5 select val.Value;\nforeach (var match in matches)\n{\n    foreach (Property prop in match)\n    {\n        // do stuff\n    }\n}	0
19943677	19943584	Change Visiblity and Change text for hidden Hyper Link from Code Behind	void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n   if(e.Row.RowType == DataControlRowType.DataRow)\n   {\n      var idLinkBtn = e.Row.FindControl("idLinkBtn") as HyperLink;\n\n      // The as operator will return null if the cast fails,\n      // so check for null before you try to use the hyper link\n      if(idLinkBtn != null)\n      {\n          idLinkBtn.Visible = true;\n      }\n   }\n}	0
6431812	6431751	How to set endpoint in runtime	public class PBMBService : IService\n{\n    private void btnPing_Click(object sender, EventArgs e)\n    {\n        ServiceClient service = new ServiceClient();\n        service.Endpoint.Address = new EndpointAddress("http://the.new.address/to/the/service");\n        tbInfo.Text = service.Ping().Replace("\n", "\r\n");\n        service.Close();\n    }\n}	0
2420763	2420085	Accessing a static property of a child in a parent method	static virtual	0
10116374	10116355	Local Variable Declaration Issue	DateTime origin = DateTime.Parse(this.dob);	0
14564458	14561548	Add a key value pair in config file at runtime in Azure Webrole	using (var server = new ServerManager())\n            {\n                    var siteNameFromServiceModel = "Web";\n                    var siteName =\n                        string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);\n\n                    string configFilePath = server.Sites[siteName].Applications[0].VirtualDirectories[0].PhysicalPath + "\\Web.config";\n                    XElement element = XElement.Load(configFilePath);\n\n                    element.Element("appSettings").Elements("add").Where(X => X.Attribute("key").Value == "YourKeyName").Single().Attribute("value").Value = "YourValue";\n                    element.Save(configFilePath);\n             }	0
27829347	27829156	how to populate combobox with mysql database stored procedures	private void frmNewClient_Load(object sender, EventArgs e)\n{\n    var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;\n    using(MySqlConnection cnn = new MySqlConnection(connectionString))\n    using(MySqlCommand cmd = cnn.CreateCommand())\n    {\n        cnn.Open();\n        cmd.CommandText = "sp_clearing_agent";\n        cmd.CommandType = CommandType.StoredProcedure;\n        DataTable dt = new DataTable();\n        using(MySqlDataAdapter da = new MySqlDataAdapter(cmd))\n        {\n            da.Fill(dt);\n            combobox.DisplayMember = "clearing_agent_name";\n            combobox.ValueMember = "clearing_agent_id";\n            combobox.DataSource = dt;\n\n        }\n    }\n}	0
3012225	3012151	How to put exe file in windows Startup	HKCU\Software\Microsoft\Windows\CurrentVersion\Run	0
22761521	22760364	Many to Many relationship Entity Framework creating new rows	DbContext.Entry(entity).State = EntityState.Unmodified	0
23044681	23044414	Resharper space between equals	Align Assignments	0
31295325	31294841	Path to directory after click once publish	string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);	0
10510735	10499147	Adding event to custom control for windows phone	protected virtual void OnValChanged(int oldvalue, int newvalue)\n        {\n            if (ValueChanged != null)\n                ValueChanged(this, new ValueChangedEventArgs { OldValue = oldvalue, NewValue = newvalue });\n        }\n\n\n        public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);\n\n        public event ValueChangedEventHandler ValueChanged;	0
7227884	7227788	Concatenate output of multiple processes to StreamReader	var info = new StringBuilder();\ninfo.Append(InvokeProcess(argument1));\ninfo.Append(InvokeProcess(argument2));\ninfo.Append(InvokeProcess(argument3));	0
29478688	29478291	Dynamic checkBox text above checkbox	CheckBox chk = new CheckBox();\nchk.AutoSize = true;\nchk.Text = new DirectoryInfo(folder).Name;\nchk.Location = new Point(10, i * 25);\npanelSubfolders.Controls.Add(chk);          \ni++;	0
2554257	2554220	Logic to skip repeating values in a variable	String[] strings = new String[] { "1", "2", "3", "4", "2", "5", "4", "6", "7" };\nStringCollection unique = new StringCollection();\n\nforeach (String s in strings)\n{\n     if (!unique.Contains(s))\n         unique.Add(s);\n}\n\nforeach (String s in unique)\n{\n     Console.WriteLine(s);\n}	0
13611367	13611322	Windows phone live background	while (true) Dispatcher.BeginInvoke(...);	0
21874325	21873440	Dispose datatable object which i need to return from my method	public DataTable getDataTable()\n    {\n        using (SqlConnection sqlCon = new SqlConnection("connectionString"))\n        using (SqlCommand cmd = new SqlCommand("sp_getData", sqlCon))\n        {\n            try\n            {\n                cmd.CommandType = CommandType.StoredProcedure;\n                sqlCon.Open();\n                using (SqlDataReader dr = cmd.ExecuteReader())\n                {\n                    DataTable dt = new DataTable();\n                    dt.Load(dr);\n                    return dt;\n                }\n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.Message);\n            }\n            return null;\n        }\n    }	0
6524015	5549988	Create new Word document with macro in C#	//create new document, location = path to template\n    Document doc = Globals.ThisAddIn.Application.Documents.Add(location);\n    //auto run macro \n    doc.RunAutoMacro(WdAutoMacros.wdAutoOpen);	0
3339705	3339649	Improve readability of a short snippet while keeping StyleCop happy	bool isFile = value == ConfigType.FILE;\nbool isDatabase = value == ConfigType.DATABASE; // or isDatabase = !isFile\n\nDebug.Assert(isFile || isDatabase, \n"Configuration type must be either 'File-based' or 'Database-based'; it was: " \n+ value.ToString()); \n\nthis.fileBasedRadioButton.Checked = isFile;\nthis.databaseBasedRadioButton.Checked = isDatabase;	0
7451528	7451515	initializing the button	return new Button {\n    FlatStyle = System.Windows.Forms.FlatStyle.System,\n    Location = new System.Drawing.Point(16, 16),\n    Name = "button",\n    Size = new System.Drawing.Size(168, 24),\n    TabIndex = 5,\n    Text = "button"\n};	0
28946155	28946067	Converting number a and b to number between c and d	new_value = (((old_value - old_min) / (old_max - old_min)) * (new_max - new_min)) + new_min	0
12502065	12499155	Unable to change background colour for new button	Button btn = new Button(); \nbtn.Background = Brushes.Green;    \nbtn.Height = 100; btn.Width = 100;\nbtn.Content = i.ToString();\n\nThemeManager.SetThemeName(btn, "None");\n\n_stockButtons.Add(btn);	0
6202839	6202744	How to select null values with LINQ to SQL and DbLinq?	db.Table.Where(\n            item => item.IsApproved.HasValue == isApproved.HasValue && \n            (!item.IsApproved.HasValue || item.IsApproved.Value==isApproved.Value ) \n ).Count();	0
13952512	13952242	Can I access more than one table via the same DataContext object simultaneously?	.AsEnumerable	0
3034518	3034379	Regex expression is too greedy	var exp = new Regex(@"^  Performed by '?(?<performer>.*?)('? \(qv\))?$");	0
14718887	14718351	Printing a pictureBox in a MdiChild	public Form1() {\n  InitializeComponent();\n  printDocument1.PrintPage += printDocument1_PrintPage;\n}	0
8649976	8637939	Object oriented database models	// Note that ModelsContainer derives from DbContext\n        ModelsContainer context = new ModelsContainer();\n\n        var weapons = context.Items.OfType<Weapon>();\n\n        foreach (var weapon in weapons)\n        {\n            Console.WriteLine(weapon.Name + ":" + weapon.Attack);\n        }\n\n        var armours = context.Items.OfType<Armour>();\n\n        foreach (var armour in armours)\n        {\n            Console.WriteLine(armour.Name + ":" + armour.Defense);\n        }	0
9476267	9356471	How to get the list of databases in an analysis services using xmlaclient in c#	XmlaClient xmlConn = new XmlaClient();\nxmlConn.Discover("DBSCHEMA_CATALOGS", "", "", out outParam, false, false, false);	0
17726229	17725602	How to make sliders match values	private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n    {\n        if (slider1 == null || slider2 == null)\n            return;\n        if (slider1.Value >= slider2.Value)\n        {\n            slider2.Value = slider1.Value;\n        }\n\n\n\n    }\n\n    private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n    {\n        if (slider1 == null || slider2 == null)\n            return;\n        if (slider2.Value <= slider1.Value)\n        {\n            slider1.Value = slider2.Value;\n        }\n\n\n    }	0
24492473	24492263	store variable within linq	myCollection.Select(g => { \n    var sect_code = g.Contract.Station.Sector.SECT_CODE;\n    var sector = sectors.FirstOrDefault(s => s.SECT_CODE.Equals(sect_code));\n    var firstName = sector != null ? \n        (sector.USER != null ? sector.USER.USER_FIRSTNAME: "") : \n        "";\n    var lastName = sector != null ? \n        (sector.USER != null ? sector.USER.LASTNAME : "") : \n        "";\n    return new ReportLine\n    {\n        cds = string.Format("{0} {1}", firstName, lastName)\n    };\n});	0
21029208	21028351	Retrieve information from Table cell	foreach (var a in ((wbSocial.Document as HTMLDocument).getElementById("j_idt29:gridDadosTrabalhador").children as IHTMLElementCollection))\n                    foreach (var b in (a as HTMLTableSection).rows)\n                    {\n                        if ((b as HTMLTableRow).rowIndex == 0) { continue; }\n                        else\n                        {\n                            foreach (var c in (b as HTMLTableRow).cells)	0
33935061	33934798	DateTime.Compare(start, end) resulting weired in my system	int t1 = DateTime.Compare(\n  new DateTime(start.Ticks - (start.Ticks % TimeSpan.TicksPerSecond), start.Kind),\n  new DateTime(end.Ticks - (end.Ticks % TimeSpan.TicksPerSecond), end.Kind));	0
9724755	9724314	Algorithm - create xml from structure	XmlSerializer serializer = new XmlSerializer(typeof(THEOBJECT));\n        string THEOBJECTXMLSTRING;\n\n        using (var stream = new MemoryStream())\n        {\n            serializer.Serialize(stream, THEINSTANCEOFTHEOBJECT);\n            stream.Seek(0, SeekOrigin.Begin);\n            var sr = new StreamReader(stream);\n            THEOBJECTXMLSTRING = sr.ReadToEnd();\n        }\n\n        return THEOBJECTXMLSTRING;	0
16301774	16301598	FileSystemWatcher files in subdirectory	private static void file_created(object sender, FileSystemEventArgs e)\n{\n    if (e.ChangeType == WatcherChangeTypes.Created)\n    {\n        if (Directory.Exists(e.FullPath))\n        {\n            foreach (string file in Directory.GetFiles(e.FullPath))\n            {\n                var eventArgs = new FileSystemEventArgs(\n                    WatcherChangeTypes.Created,\n                    Path.GetDirectoryName(file),\n                    Path.GetFileName(file));\n                file_created(sender, eventArgs);\n            }\n        }\n        else\n        {\n            Console.WriteLine("{0} created.",e.FullPath);\n        }\n    }\n}	0
30641265	30641204	Entity framework add multiple collections to collection with one query	var newsArticles = (from a in db.NewsArticles\n               where keywords.Contains(a.Title)\n               select a).ToList();	0
569267	569249	MethodInfo.Invoke with out Parameter	public static bool TryParse( string text, out int number ) { .... }\n\nMethodInfo method = GetTryParseMethodInfo();\nobject[] parameters = new object[]{ "12345", null }\nobject result = method.Invoke( null, parameters );\nbool blResult = (bool)result;\nif ( blResult ) {\n    int parsedNumber = parameters[1];\n}	0
5867858	5867697	MEF and Factory Pattern	var sut = new TwitterCrawler();\nsut.TwitterClientFactory = new FakeTwitterClientFactory();	0
17697810	17697692	A using namespace directive can only be applied to namespaces	using System; \n\nDateTime returnedDate = DateTime.Now();	0
18603636	18603310	MVC WebMail Helper - Is It Possible to Send An Email With Attachments Without Saving Them First?	message.Attachments.Add(new Attachment(postedFile.Stream, postedFile.Name, postedFile.ContentType));	0
9430998	9430960	C# make wget request	string page;\nusing(var client = new WebClient()) {\n    client.Credentials = new NetworkCredential("user", "password");\n    page = client.DownloadString("http://www.example.com/");\n}	0
18432521	18432200	Rotate an image in a PictureBox with a value	public partial class WiiMoteControl: PictureBox {\n\n    public Bitmap wiimote;\n    private float _angle;\n    public float Angle { \n         get { return _angle; } \n         set { _angle = value; Invalidate( ); } \n    }\n\n    protected override void OnPaint( PaintEventArgs pe ) {\n        base.OnPaint( pe );\n        pe.Graphics.ResetTransform( );\n        pe.Graphics.TranslateTransform( Size.Width / 2, Size.Height / 2 );\n        pe.Graphics.RotateTransform( Angle );\n        pe.Graphics.TranslateTransform( -Size.Width / 2, -Size.Height / 2 );\n        if (wiimote != null) {\n            pe.Graphics.DrawImage( wiimote, 0, 0, Size.Width, Size.Height );\n        }\n    }\n}	0
32453797	32453640	HtmlAgilityPack - wrong automatic conversion of text to date	DateTime myDate = DateTime.ParseExact("9/7/2015","M.d.yyyy",System.Globalization.CultureInfo.InvariantCulture)	0
280960	269263	Find the address of a DLL in memory	String appToHookTo = "applicationthatloadedthedll";\nProcess[] foundProcesses = Process.GetProcessesByName(appToHookTo)\nProcessModuleCollection modules = foundProcesses[0].Modules;\nProcessModule dllBaseAdressIWant = null;\nforeach (ProcessModule i in modules) {\nif (i.ModuleName == "nameofdlliwantbaseadressof") {\n                    dllBaseAdressIWant = i;\n                }\n        }	0
18068500	18068483	Send Keys with 10 second delay - C#	System.Diagnostics.Process.Start(@"C:\Program Files\Google\Chrome\Application");\nSystem.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));\nSendKeys.Send("{ENTER}");	0
4861905	4861520	Share ComboBox DataSource	// combobox.DataSource = list;\nvar curr = new BindingSource(list, null);        \ncombobox.DataSource = curr;	0
2099996	2099988	How to Reflect on the main app from a DLL with .NET?	Assembly.GetEntryAssembly()	0
13750320	13750170	How focus out the Cursor from textbox in wpf?	FocusManager.SetFocusedElement(AnotherElementID);	0
6230378	6230142	Html Agility Pack cannot find list option using xpath	HtmlNode.ElementsFlags.Remove("option");	0
676329	676296	how to tokenize/parse string literals from javascript source code	string modifiedJavascriptText =\n   Regex.Replace\n   (\n      javascriptText, \n      @"([""'])(?:(?!\1)[^\\]|\\.)*\1", // Note the escaped quote\n      new MatchEvaluator\n      (\n         delegate(Match m) \n         { \n            return m.Value.ToUpper(); \n         }\n      )\n   );	0
8410625	8410554	C# ASPX ASP.NET - Add & Delete Table Row	Protected void Page_Load(object sender, EventArgs e)\n{\n    GridView.DataSource = Webservice.someMethodCall(param1, param2);\n    GridView.DataBind();\n}	0
30710370	30709034	How to get TextRange of text written by user in RichTextBox	public void ReWriteStream()\n{\n    var myText = new TextRange(rtb.CaretPosition.GetLineStartPosition(0), rtb.CaretPosition.GetLineStartPosition(1) ?? rtb.CaretPosition.DocumentEnd).Text;    \n    ...\n\n}	0
3880513	3880484	How can I pass a runtime method to a custom attribute or viable alternative approach	posts\{GetBlogId()}	0
12104715	12104665	XML node parsing using C# linq	XDocument xDoc = XDocument.Parse(xml);\nvar demographics =  xDoc\n        .Descendants("country")\n        .Select(c => new\n        {\n            Country = c.Attribute("value").Value,\n            Id = c.Attribute("id").Value,\n            States = c.Descendants("state")\n                        .Select(s => new\n                        {\n                            State = s.Attribute("value").Value,\n                            Id = s.Attribute("id").Value,\n                            Cities = s.Descendants("city").Select(x => x.Value).ToList()\n                        })\n                        .ToList()\n        })\n        .ToList();	0
31310268	31293115	Extract Bulleted Text From Powerpoint	PowerPoint.BulletFormat bulletFormat = textRange.Paragraphs(x).ParagraphFormat.Bullet;\n\n    if( bulletFormat.Type == PowerPoint.PpBulletType.ppBulletNone )\n                           // Not Bulleted\n    else\n                        // Bulleted	0
25256238	25256202	How to determine an alphabetic character that is not uppercase or lowercase	password.Any(c => Char.IsLetter(c) &&\n                  !Char.IsUpper(c) &&\n                  !Char.IsLower(c))	0
16973607	16973465	Convert string to type in object	public void Update<T>(string fieldName, string fieldValue)\n{\n    System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);\n    Type propertyType = propertyInfo.PropertyType;\n\n    TypeConverter converter = TypeDescriptor.GetConverter(type);\n    if (converter.CanConvertFrom(typeof(string)))\n    {\n        var a = converter.ConvertFrom(fieldValue, type);\n        ...\n    }\n}	0
19876626	19875484	C++ -> C# using SWIG: how to use default constructor for a class	%typemap(cscode) TInt %{\n    //this will be added to the generated wrapper for TInt class\n    public static implicit operator TInt(int d)\n    {\n        return new TInt(d);\n    }\n%}	0
4612730	4561864	Force rebuild after Spring config file edit	Embedded Resource	0
22474830	22474794	C# Convert DateTime in the CurrentCulture	var myDate = DateTime.Parse(myDate, CultureInfo.CurrentCulture);	0
4453970	4405684	Specifying the name of a column in Entity Framework for a Referenced Object	public class Category\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public ICollection<Product> Products { get; set; }\n}\n\npublic class Product\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public Category Category { get; set; }\n}\n\npublic class MyContext : DbContext\n{\n    public DbSet<Product> Products { get; set; }\n    public DbSet<Category> Categories { get; set; }\n\n    protected override void OnModelCreating(ModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Product>()\n            .HasRequired(p => p.Category)\n            .WithMany(c => c.Products)\n            .IsIndependent()\n            .Map(mc => mc.MapKey(c => c.Id, "CategoryId")); \n    }\n}	0
16919441	16919191	Get top 5 created subsites in sharepoint without for loop	var newestSites = clientSiteCollection.AllWebs.OrderByDescending(p=>p.CreatedDate).ToList().Take(5);\n// Now NewestSites is a collection of your top 5 newest created Sites.	0
30560101	30559768	MouseRightClick on ListBox crashes the app	private void LstStat_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)\n{\n    e.Handled = true;\n}\n\nprivate void LstStat_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n{\n    e.Handled = true;\n}	0
8206469	8206418	Transfering data from Excel to dataGridView	string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""";	0
21454370	21453902	Display week dates on label	protected void Calendar1_SelectionChanged(object sender, EventArgs e)\n       {\n            DateTime input = Calendar1.SelectedDate;\n            int delta = DayOfWeek.Sunday - input.DayOfWeek;\n            DateTime firstDay = input.AddDays(delta);\n\n            Label2.Text = string.Empty;\n\n            for (int i = 0; i < 6; i++)\n                Label2.Text += ((DateTime)(firstDay.Add(new TimeSpan(i, 0, 0, 0)))).ToShortDateString() + "  ";\n        }	0
16679536	16679484	Load distinct values from database into List<>	var events = db.Records.Distinct().ToList();	0
19513017	19512851	How to Move File and Rename it in C#, after receiving it from the server?	if (File.Exists(myFile))\n{\n    File.Delete(myFile);\n}\nFile.Move(myServerfile, myFile);	0
1992698	1992430	Need solution for troubled null problem	IEnumerable<int> fidListE = (fidList != null) ? fidList.Distinct() : Enumerable.Empty<int>();	0
16151511	16151191	Return HttpResponseMessage with XML data	[HttpGet]\npublic HttpResponseMessage GetPerson(int personId)\n{\n    var doc = XDocument.Load(path);\n    var result = doc\n        .Element("Persons")\n        .Elements("Person")\n        .Single(x => (int)x.Element("PersonID") == personId);\n\n    var xml = new XElement("TheRootNode", result).ToString();\n    return new HttpResponseMessage \n    { \n        Content = new StringContent(xml, Encoding.UTF8, "application/xml") \n    };\n}	0
361678	361661	Populate TreeView from DataBase	//In Page load\nforeach (DataRow row in topics.Rows)\n{\n    TreeNode node = new TreeNode(dr["name"], dr["topicId"])\n    node.PopulateOnDemand = true;\n\n     TreeView1.Nodes.Add(node);\n }\n ///\n protected void PopulateNode(Object sender, TreeNodeEventArgs e)\n {\n     string topicId = e.Node.Value;\n     //select from topic where parentId = topicId.\n     foreach (DataRow row in topics.Rows)\n     {\n         TreeNode node = new TreeNode(dr["name"], dr["topicId"])\n         node.PopulateOnDemand = true;\n\n         e.Node.ChildNodes.Add(node);\n     }\n\n }	0
25939574	25939310	WCF Configuration enhancement	void SetNewEndpointAddress(string endpointName, string contractName, string newValue)\n    {\n        bool settingsFound = false;\n        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n        ClientSection section = config.GetSection("system.serviceModel/client") as ClientSection;\n        foreach (ChannelEndpointElement ep in section.Endpoints)\n        {\n            if (ep.Name == endpointName && ep.Contract == contractName)\n            {\n                settingsFound = true;\n                ep.Address = new Uri(newValue);\n                config.Save(ConfigurationSaveMode.Full);\n            }\n        }\n        if (!settingsFound)\n        {\n            throw new Exception(string.Format("Settings for Endpoint '{0}' and Contract '{1}' was not found!", endpointName, contractName));\n        }\n    }	0
9364380	9364067	Avoid returning nulls in JSON for AJAX calls	public EmptyJsonResult()\n    {\n    Data = new\n        {\n            Empty = true\n        };\n    }	0
22767153	22707876	Unable to refresh DataGridView after updating database	secaloFormulaDataSet.GetChanges();\n            materialPriceTableAdapter.Fill(secaloFormulaDataSet.materialPrice);	0
6993316	6992411	How to create system user on window server 2003 in C# asp.net?	using (var context = new PrincipalContext(ContextType.Machine, "MachineName", "AdminUserName", "AdminPassword"))\n{\n    UserPrincipal user = new UserPrincipal(context, username, password, true);\n    user.Description = "Test User from .NET";\n    user.Save();\n\n    var guestGroup = GroupPrincipal.FindByIdentity(context, "Guests");\n    if (guestGroup != null)\n    {\n        guestGroup.Members.Add(user);\n        guestGroup.Save();\n    }\n}	0
7824071	7823966	Milliseconds in my DateTime changes when stored in SQL Server	2011-06-06 23:59:59.997	0
2249398	2249280	How can I swallow all exceptions and protect my application from crashing?	obj = null	0
29181749	29180494	How to detect source code changes in async method body	var module = ModuleDefinition.ReadModule("MethodBodyChangeDetector.exe");\n\nvar typeDefinition = module.Types.First(t => t.FullName == typeof(Changed).FullName);\n\n// Retrieve all method bodies (IL instructions as string)\nvar methodInstructions = typeDefinition.Methods\n    .Where(m => m.HasBody)\n    .SelectMany(x => x.Body.Instructions)\n    .Select(i => i.ToString());\n\nvar nestedMethodInstructions = typeDefinition.NestedTypes\n    .SelectMany(x=>x.Methods)\n    .Where(m => m.HasBody)\n    .SelectMany(x => x.Body.Instructions)\n    .Select(i => i.ToString());\n\n\nMd5(string.Join("", methodInstructions) + string.Join("", nestedMethodInstructions));	0
19958744	19955611	How do I create a identity column that doesn't skip 10000 every time service restarts with EF?	CREATE TABLE [MyTable]\n(\n    [ID] [bigint] PRIMARY KEY NOT NULL,\n    [Title] [nvarchar](64) NOT NULL\n)\n\nCREATE SEQUENCE MyTableID\n    AS BIGINT\n    START WITH 1\n    INCREMENT BY 1\n    NO CACHE\n    ;\nGO\n\nCREATE TABLE [MyTable]\n(\n    [ID] [bigint] PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR dbo.MyTableID),\n    [Title] [nvarchar](64) NOT NULL\n);	0
23547480	17536651	Configuring Fluent NHibernate with System.Data.OracleClient	FluentConfiguration configuration = Fluently.Configure()                \n            .Database(\n            OracleClientConfiguration.Oracle10\n            .ConnectionString(x => x.FromConnectionStringWithKey(connString))\n            .Provider<NHibernate.Connection.DriverConnectionProvider>()\n            .Driver<NHibernate.Driver.OracleClientDriver>()            \n               )	0
17629790	17629635	Display value from Database to TextBox	EmpAge.Text = item.subItems[3].Text ;//column's width is 0\n\nEmpAddress.Text = item.subItems[4].Text ;//column's width is 0	0
16505663	16505265	GridView paging control issue	protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    GridView gridview = (GridView)sender;\n\n    gridview.PageIndex = e.NewPageIndex;\n\n    Button1_Click(null, null);\n\n    gridview.DataBind();\n}	0
23415927	23414380	How to get my animation to play in unity when my character jumps	void OnCollisionEnter(Collision collision){\n\n  foreach(ContactPoint contact in collision.contacts){\n    rigidbody.velocity = transform.up*10;\n    audio.Play();\n    animator.SetTrigger("Jump");\n  }\n}	0
20272078	20271814	Retrieve last id from Firebird db table	var con = OpenFB2Connection();\nvar trans = con.BeginTransaction();\n\nvar command = new OleDbCommand("INSERT INTO ... VALUES ...  RETURNING Id");\n\ncmd.Parameters.Add("Id", OleDbType.Integer).Direction = ParameterDirection.Output;\n\n\nvar Id = (int)cmd.ExecuteScalar(); //Here is your Id	0
17680471	17680105	How to use reader.GetDecimal() for a column in a separate table?	SqlCeCommand AlertQuery = new SqlCeCommand("SELECT S.*,A.AccountTotal from Students S Inner Join Accounts A ON S.AlertAccountID = A.AccountID");	0
2203565	2203545	Using Reflection to set a static variable value before object's initialization?	var type = typeof(SomeClass);\nvar field = type.GetField("SomeField");\nfield.SetValue(null, 42);	0
17752317	17745859	How to write Shape's properties in Visio C#?	var newPropertyValue = "cool new value";\ntstShape.Cells["Prop.SuperCustomPropertyName"].FormulaU = "\"" + newPropertyValue + "\"";	0
19466086	19466016	Interface for Attributes	public abstract class A\n{\n     [XmlType]\n     public void F()\n     {\n          InnerF();\n     }\n\n     protected abstract InnerF();\n}\n\npublic class B extends A\n{\n     protected void InnerF()\n     {\n     }\n}	0
8065945	8065856	How to Programmatically Log in to a Website	string formUrl = "http://ratings-plus.webs.com/apps/auth/doLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag\nstring formParams = string.Format("next=apps%2Flinks%2F&why=pw&email={0}&password={1}&fw_human=", "your email", "your password");\nstring cookieHeader;\nWebRequest req = WebRequest.Create(formUrl);\nreq.ContentType = "application/x-www-form-urlencoded";\nreq.Method = "POST";\nbyte[] bytes = Encoding.ASCII.GetBytes(formParams);\nreq.ContentLength = bytes.Length;\nusing (Stream os = req.GetRequestStream())\n{\n    os.Write(bytes, 0, bytes.Length);\n}\nWebResponse resp = req.GetResponse();\ncookieHeader = resp.Headers["Set-cookie"];	0
25165449	25165261	VB to C# Optional Parameters	protected void LoadData(string ProcedureName, long NumOuts, Label Label1, Label Label2 = null, Label Label3 = null) {	0
11718729	11718653	Split by multiple characters	string[] list = b.Split(new string[] { "ab" }, StringSplitOptions.None);	0
5030875	5028206	How to catch HttpRequestValidationException in production	protected void Application_Error(object sender, EventArgs e)\n{\n    var context = HttpContext.Current;\n    var exception = context.Server.GetLastError();\n    if (exception is HttpRequestValidationException)\n    {\n        context.Server.ClearError();    // Here is the new line.\n        Response.Clear();\n        Response.StatusCode = 200;\n        Response.Write(@"<html><head></head><body>hello</body></html>");\n        Response.End();\n        return;\n    }\n}	0
28658675	28632802	Find KeyAttribute of a class, defined using HasKey method	ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;\n            ObjectSet<Entity> set = objectContext.CreateObjectSet<Entity>();\n            IEnumerable<string> keyNames = set.EntitySet.ElementType\n                                                        .KeyMembers\n                                                        .Select(k => k.Name);\n\n            string keyName = keyNames.FirstOrDefault();	0
3279480	3279465	How to breakup/run a large SQL query?	Dictionary<T,V>	0
15206256	15173190	assign chart object to chart control	ChartArea[] ca = new ChartArea[1];\nChart1.ChartAreas.CopyTo(ca, 0);\nChartControl1.ChartAreas.Add(ca[0]);\n\nSeries[] s = new Series[5];\nChart1.Series.CopyTo(s, 0);\nforeach (Series ss in s)\n{\n  if (ss != null)\n  {\n    ChartControl1.Series.Add(ss);\n  }\n}        \nLegend[] l = new Legend[5];\nChart1.Legends.CopyTo(l, 0);\nforeach (Legend ll in l)\n{\n  if (ll != null)\n  {\n    ChartControl1.Legends.Add(ll);\n  }\n}	0
10725484	10725406	LINQ orderby from specific value	var query = aux\n  .OrderBy(i => i < 2 ? 2 : 1) //small numbers last\n  .ThenBy(i => i < 2 ? -i : i); //large numbers asc, small numbers desc	0
18961719	18925141	How to open an Excel document and read values using Open XML in C#	FileInfo uploadedFile = new FileInfo(FileDirectory);\n            using (ASC.ExcelPackage.ExcelPackage xlPackage = new ASC.ExcelPackage.ExcelPackage(uploadedFile))\n            {\n                ASC.ExcelPackage.ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];\n                Int32 currentRow = 1;\n                while (worksheet.Cell(currentRow, 1) != null && !string.IsNullOrEmpty(worksheet.Cell(currentRow, 1).Value))\n                {\n                    string value = worksheet.Cell(currentRow, 1).Value;\n\n                    currentRow++;\n                }\n            }	0
1191159	1190721	Inconsistency in file before and after upload to Oracle DB	br.BaseStream.Position = 0;	0
4456118	4446342	ASP C# | MessageBox Keeps Displaying	if(IsPostBack)\n         new myFunctions().HideUserMessage(ErrorMessageLabel);	0
13574011	13573384	how to post arbitrary json object to webapi	public HttpResponseMessage Post(HttpRequestMessage req)\n    {\n        var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity...\n        ...\n\n    }	0
6073706	6073550	get folder to treeview	void Recurse(string path, TreeNode parentNode)\n{\n    DirectoryInfo info = new DirectoryInfo(path);\n    TreeNode node = new TreeNode(info.Name);\n\n    if (parentNode == null)\n        MailTree.Nodes.Add(node);\n    else\n        parentNode.Nodes.Add(node);\n\n    string[] sub = Directory.GetDirectories(path);\n    if (sub.Length != 0)\n    {\n        foreach(string i in sub)\n        {       \n            Recurse(i, node);                  \n        }\n    }   \n}	0
5707462	368001	Is it possible to test a COM-exposed assembly from .NET?	using System;\nclass ComClass\n{\n    public bool CallFunction(arg1, arg2)\n    {\n        Type ComType;\n        object ComObject;\n\n        ComType = Type.GetTypeFromProgID("Registered.ComClass");\n        // Create an instance of your COM Registered Object.\n        ComObject = Activator.CreateInstance(ComType);\n\n        object[] args = new object[2];\n        args[0] = arg1;\n        args[1] = arg2;\n\n        // Call the Method and cast return to whatever it should be.\n        return (bool)ComType.InvokeMember("MethodToCall", BindingFlags.InvokeMethod, null, ComObject, args))\n    }\n}	0
27444540	27444419	Add items to the ROT( Running Objects Table)	Form.Activate	0
3745705	3744668	Bind Console Output to RichEdit	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        button1.Click += button1_Click;\n        Console.SetOut(new MyLogger(richTextBox1));\n    }\n    class MyLogger : System.IO.TextWriter {\n        private RichTextBox rtb;\n        public MyLogger(RichTextBox rtb) { this.rtb = rtb; }\n        public override Encoding Encoding { get { return null; } }\n        public override void Write(char value) {\n            if (value != '\r') rtb.AppendText(new string(value, 1));\n        }\n    }\n    private void button1_Click(object sender, EventArgs e) {\n        Console.WriteLine(DateTime.Now);\n    }\n}	0
3519825	3519785	dynamicly move records in a dataset into a class is there a way to do it in c#?	var query = (from row in DataTable.Rows.Cast<DataRow>()\n            select new \n            {\n                 ID = row.Field<int>("ID"),\n                 Name = row.Field<string>("Caption"),\n                 \\etc etc etc\n            }).ToArray();	0
9060292	9060249	How to divide FOR loop in N even parts for parallel execution given constant input data for each iteration?	Parallel.For( 0, 2048, n=>\n   {\n         output_data[n] = function(constant_input_data, n);\n    });	0
17878874	17878730	How to Automatically Click a button On a form application?	protected override void OnShown(EventArgs e)\n {\n    base.OnShown(e);\n    this.BtnClick(null, null);\n }	0
17191902	17191451	check if string contains dictionary Key -> remove key and add value	Dictionary<char, string> pairs = new Dictionary<char, string>();\npairs.Add('a', "09001");\n...\n\nforeach(KeyValuePair<string, string> entry in pairs)\n{\n    if (source.Contains(entry.key))\n    {\n      source = source.Replace(entry.key, "") + entry.Value;\n      break;\n    }\n}\n\nreturn source;\n....	0
3993016	3991922	How to build message from tcp segments	write(sock, "GET / HTTP/1.0\r\n\r\n", len);\n\nwrite(sock, "GET / HTTP/1.0\r\n", len);\nwrite(sock, "\r\n", 2);\n\nwrite(sock, "GET / HTTP/1.0\r\n", len);\nsleep(1);\nwrite(sock, "\r\n", 2);	0
11467703	11450331	RDLC Alternating rows	protected void Page_Init( object sender, EventArgs e ) {\n    ...\n    ReportViewer.LocalReport.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));\n    ...\n}	0
25807968	25807862	Parameter count mismatch at Invoke	object Invoke = getMethod.Invoke(null, new object[] { parameters, false });	0
9888707	9888659	How do i remove root folder name from URL?	Virtual Path	0
31808642	31808581	hierarchical-data with possible null object	_data = record?.RltdPties?.DbtrAcct?.Id?.Item	0
10596643	10596580	Lamda expression to obtain a list of types from the attributes of other types	List<Guid> identifiers = MyClass.AllMyClass.Where(x => x.ForeignKey == foreignKey).Select(x => x.Identifier).ToList();	0
14485713	14483022	Getting XML formatted output but not JSON output from WCF	public class RestServiceImpl : IRestServiceImpl\n{\n    public JSONResponse JSONData(string id)\n    {\n        return new JSONResponse { Response = "You requested product " + id };\n    }\n}\n\npublic class JSONResponse\n{\n    public string Response { get; set; }\n}	0
2901025	2901013	response redirect with '+'	Response.Redirect("Default2.aspx?Name=" + Server.UrlEncode(TextBox1.Text));	0
13803161	13769168	How to find a UserPrincipal where a property is not set using a PrincipalSearcher?	public class MyAdvancedFilters : AdvancedFilters\n{\n    /// <summary>\n    /// Initializes a new instance of the <see cref="MyAdvancedFilters"/> class.\n    /// </summary>\n    /// <param name="principal">The source <see cref="Principal"/></param>\n    public MyAdvancedFilters(Principal principal) : base(principal) { }\n\n    public void WhereCompanyNotSet()\n    {\n        this.AdvancedFilterSet("company", "*", typeof(string), MatchType.NotEquals);\n    }\n}	0
7024770	7023830	Is there a way to hardcode connection string to RDLC?	ReportViewer1.Reset()\nReportViewer1.LocalReport.DataSources.Clear()\nReportViewer1.LocalReport.ReportPath = <yourfilepath>\nReportViewer1.LocalReport.DataSources.Add(<yourdatasource>)\nReportViewer1.LocalReport.Refresh()	0
18658097	18654952	How do I reassign a task in cDevworkFlow?	string oTaskId = ""; //get the taskId which you want to assign \n        string oNewUserId = ""; //get the target userid\n\n        bool oFlag = oRuntime.reAssignTask(oTaskId, oNewUserId);	0
7770173	7770069	add tooltips to programmatically created controls	//...\nToolTip ttip = new ToolTip();\nfor (int i = 0; i < 7; i++) {\n    for (int j = 0; j < 4; j++) {\n        Button btn = new Button();\n        // ...\n        ttip.SetToolTip(btn, "Some text on my tooltip.");\n    }\n}\n//...	0
32207384	32206463	How to create zip archive contains files with certain extensions only	IList<FileInfo> info = null;    \nDirectoryInfo dirInfo = new DirectoryInfo(path);\n\ninfo = dirInfo\n       .GetFiles("*.*", SearchOption.AllDirectories)\n       .Where( f => f.Extension\n                    .Equals(".exe", StringComparison.CurrentCultureIgnoreCase)\n                 || f.Extension\n                    .Equals(".bat", StringComparison.CurrentCultureIgnoreCase)\n        )\n        .ToList()\n        ;	0
20801474	20801247	How to get the address of ouput file from user in C#?	public void WriteKCore(string path, string fileName, string content)\n{\n    using (var writer = new StreamWriter(Path.Combine(path, fileName), true))\n    {\n        writer.Write(content);\n    }\n}	0
7739792	7739244	How to get localized version of built-in windows 'Network Service' account?	var account = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null).Translate(typeof(NTAccount)).Value;	0
6047853	5941595	Getting an ID of a value from dropdown list	resultSummaryViewModel.Value = value;\n        resultSummaryViewModel.ReportFrame = new FramedViewModel();\n\n        if(value !="")\n        {\n            string viewValue = value.Substring(0, value.IndexOf("|"));\n            string viewType = value.Substring(value.IndexOf("|") + 1);\n\n            resultSummaryViewModel.ReportFrame.SourceURL =\n                WebPathHelper.MapUrlFromRoot(\n                    string.Format(\n                        "Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}",\n                        resultSummaryViewModel.BeginDate, resultSummaryViewModel.EndDate, viewValue,\n                        viewType));\n        }\n        var viewData = new Dictionary<string, string>();\n        viewData.Add("Schools", "|allschools");\n        viewData.Add("Classes", "|allclasses");	0
7339669	7339642	a cleaner way of representing double quote?	var s = "123 ' 456 '".Replace("'", "\"");	0
24914526	24901791	How to specify dimension of Google Charts in asp.net	str.Append("chart.draw(data, {height: 300, title: 'Company Performance'");	0
10398861	10398751	Merging IDictionary - is there a more efficient method than this?	var result = dictionaries.SelectMany(d => d)\n                         .ToLookup(kvp => kvp.Key, kvp => kvp.Value)\n                         .ToDictionary(g => g.Key, g => string.Concat(g));	0
27145600	27143855	Selenium wait for user captcha input C#	WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));\nwait.Until((d) =>\n{\n    return d.FindElement(?); // here you can use any locator that identifies a successful / failed login\n});	0
25013512	25008897	How to rotate a grid in wpf using Render Transform	private void AddRectangle() {\n    Rectangle rotatedRectangle = new Rectangle();\n    rotatedRectangle.Width = 200;\n    rotatedRectangle.Height = 50;\n    rotatedRectangle.Fill = Brushes.Blue;\n    rotatedRectangle.Opacity = 0.5;\n    RotateTransform rotateTransform1 = new RotateTransform(45, -50, 50);\n    rotatedRectangle.RenderTransform = rotateTransform1;\n\n    MyGridContainer.Children.Add(rotatedRectangle);\n}	0
9748834	9745845	LINQ query with variable in where clause	public void DoSomething(List<TheObj> objs, string lnameStr)\n    {\n      if(objs != null && !string.IsNullOrEmpty(lnameStr))   \n       {\n        var pQuery = (from o in objs\n                      where !string.IsNullOrEmpty(p.Lname) && \n                            o.Lname.Contains(lnameStr)\n                      select o).ToList();\n\n        foreach (var theObj in pQuery)\n        {\n            Trace.WriteLine(theObj.Fname);\n        }\n      }\n    }	0
9016769	9014477	Obtaining the value of another process' CLR Memory Performance Counter	using System;\nusing System.Diagnostics;\n\nclass Program {\n    static void Main(string[] args) {\n        var process = "devenv";   // Modify this\n        var ctr = new PerformanceCounter(".NET CLR Memory", "Gen 2 heap size", process);\n        Console.WriteLine(ctr.RawValue);\n        Console.ReadLine();\n    }\n}	0
34122822	34122769	C# lambda variable initialization	private string m\n{\n    get { return string.Empty; }\n}	0
6768179	6768128	how do i write an extension method on ConcurrentDictionary	public static ConcurrentDictionary<int, DirtyFlag> GetDirtyRoutes(this ConcurrentDictionary<int, DirtyFlag> wholeDictionary)\n{\n    return new ConcurrentDictionary<int, DirtyFlag>(\n        wholeDictionary.Where(a => a.Value == DirtyFlag.Dirty)\n    );\n}	0
31694425	31694344	How to run multiple tasks in c# and get an event on complete of these tasks?	Task.WaitAll(tasks.ToArray());	0
30483150	30482955	Is there a way to pull information from one variable created inside a function, and use it in another	static void NewElement(string EleWeight)\n{\n    ...\n}\n\nstatic void ElementData(string EleName, string EleSymbol, string EleNumber, string EleWeight)\n{\n    Console.WriteLine("Element: " + EleName);\n    Console.WriteLine("Symbol: " + EleSymbol);\n    Console.WriteLine("Atomic Number: " + EleNumber);\n    Console.WriteLine("Atomic Weight: " + EleWeight);\n    NewElement(EleWeight);\n}	0
10396201	10379391	How to import local files to SVN with sharpsvn using C#.NET	client.Import(fileName, \nnew Uri("https://koteshwar:8443/svn/"+comboBox1.SelectedItem+"/trunk"), ca, out result);.	0
13701968	13701823	Inserting data from two tables into one c#	//create the object\nTask task = new Task{\n\ntask_name = src.taskName,\ntask_description = src.taskDescription\n\n}\n\ncontext.Tasks.InsertOnSubmit(task);\ncontext.SubmitChanges();\n\n//do second insert\nInt32 taskIDFromLastInsert = task.task_id;\n\nResource res = new Resource{\n\nresource_name = scr.ResourceName,\ntask_id = taskIDFromLastInsert // optional if you want to change your structure\n\n}	0
10156983	10156954	Best way to uniquely identify a type	Type.GUID	0
20126261	20126223	How do I sort these arrays of objects in ascending order in C#?	foreach(var item in gameConsole.OrderBy(r=> r.GameID))\n{\n   item.display();\n}	0
11917703	3578172	Using WPF custom compositefont from dll resource	new FontFamily(new Uri("pack://application:,,,"),\n    "MyLibraryDll;Component/Fonts/#My Font from composite font");	0
13083832	13083790	How to fix 'Remove property setter' build error?	private readonly List<Foo> items = new List<Foo>();\npublic List<Foo> Items { get { return items; } }	0
252389	252365	Creating a TCP Client Connection with SSL	TcpClient _tcpClient = new TcpClient("host", 110);\n\nStreamReader reader = \n   new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));\n\nConsole.WriteLine(reader.ReadToEnd());	0
19032520	19021463	Wrap grid ItemHeight binding in windows store app	ItemHeight="{Binding Path=ItemHeight}"	0
9988063	9987931	Is there a way to place compilator in a program?	Microsoft.CSharp	0
4553019	4552670	Is there any real world reason to use throw ex?	//Possible but not useful.\n    object ref1 = null;\n\n    ref1.ToString();	0
15394772	15394631	How can I compare a string to char[] with no memory allocations?	int len = Math.Min(array.Length, s.Length);\nfor (int i = 0; i < len; i++) {\n    if (s[i] < array[i]) return -1;\n    if (s[i] > array[i]) return +1;\n}\nreturn s.Length.Compare(array.Length);	0
21858342	21858043	check the url of current page in if statement	if (Path.GetFileName(Request.Url.LocalPath) == "ParentPage.aspx")\n{ element.visible = false; }\nelse\n{ element.visible = true; }	0
22753582	22752127	Inconsistencies in data retrieval from csv file	var myfavitems = collection_of_objects.Where(a => a.GotCar == "1").ToList();\n\n// let us know this value. is this 458?\nint totalItemsCount = myfavitems.Count;\n\nvar groupedItems = myfavitems.GroupBy(a => a.Metal_Type);\n\n// let us know this value. is this 160?\nint totalGroupsOnChart = groupedItems.Keys.Count();\n\nforeach (var t in groupedItems)\n{\n // Do something/ display on graph\n}	0
6985372	6985308	Where clause of LINQ statement to find instances of a string within a List<string> collection?	query = query.Where(x => AccountNumbers.Contains(x.AccountNumber));	0
18427181	18427160	how to know loop duration in c#	Stopwatch stopWatch = new Stopwatch();\n    stopWatch.Start();\n\n    // stuff you want to time here...\n\n    stopWatch.Stop();\n\n    // Get the elapsed time as a TimeSpan value.\n    TimeSpan ts = stopWatch.Elapsed;\n\n    // Format and display the TimeSpan value. \n    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n        ts.Hours, ts.Minutes, ts.Seconds,\n        ts.Milliseconds / 10);\n    Console.WriteLine("RunTime " + elapsedTime);	0
19913720	19913677	Set a setting at runtime	DBce_TEST2.Properties.Settings.Default.dbLocation = fileName;\nDBce_TEST2.Properties.Settings.Default.Save();	0
3480230	3480213	Databinding multiple controls to a single LINQ query	var result = from c in dc.whatevers select c;\nList<whatevers> resultList = result.ToList(); // Query runs here\n\nddlItem1.DataSource = new List<whatevers>(resultList); // Copy of the list\nddlItem2.DataSource = new List<whatevers>(resultList); // Copy of the list\nddlItem3.DataSource = new List<whatevers>(resultList); // Copy of the list	0
6657108	6657030	What is the standard practice for starting a task with multiple parameters	myTask = new Task<bool>(() => MyMethod(xyz, abc), _cancelToken);	0
4458652	4458626	Way to fill List<> with elements	retVal.AddRange(Enumerable.Repeat(value, somesize));	0
11903591	11903552	how to change XML node values	XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet");	0
1067329	1067312	How to use MethodInfo.Invoke to set property value?	object o;\n//...\nType type = o.GetType();\nPropertyInfo pi = type.GetProperty("Value");\npi.SetValue(o, 23, null);	0
32106323	31935133	Force EndpointNotFoundException raise from WCF service	WebOperationContext ctx = WebOperationContext.Current;\nctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;	0
33871109	33818853	Take screenshot of the options in dropdown in selenium c#	try {\n\n    //Get the size of the screen stored in toolkit object\n    Toolkit tk = Toolkit.getDefaultToolkit();\n    Dimension d = tk.getScreenSize();\n\n    //Create Rectangle object using height and width of screen\n    //Here entire screen is captured, change it if you need particular area\n    Rectangle rect = new Rectangle(0, 0, d.width, d.height);  \n\n    //Creates an image containing pixels read from the screen \n    Robot r = new Robot();\n    BufferedImage img = r.createScreenCapture(rect);\n\n    //Write the above generated buffered image to a file\n    File f = new File("myimage.jpg");\n\n    //Convert BufferedImage to a png/jpg image\n    ImageIO.write(img, "jpg", f);\n\n} catch (Exception e) {\n    System.out.println(e.getMessage());\n}	0
13740431	13740343	Logic behind a bubble sort	public void BubbleSort<T>(IList<T> list);\n{\n    BubbleSort<T>(list, Comparer<T>.Default);\n}\n\npublic void BubbleSortImproved<T>(IList<T> list, IComparer<T> comparer)\n{\n    bool stillGoing = true;\n    int k = 0;\n    while (stillGoing)\n    {\n        stillGoing = false;\n        for (int i = 0; i < list.Count - 1 - k; i++)\n        {\n            T x = list[i];\n            T y = list[i + 1];\n            if (comparer.Compare(x, y) > 0)\n            {\n                list[i] = y;\n                list[i + 1] = x;\n                stillGoing = true;\n            }\n        }\n        k++;\n    }\n}	0
15658515	15658417	c# templates how can i apply constraints to a class that derives from something	class TVIRoot<TLabelHandler> : OURTreeNodeImpl where TLabelHandler : SomeClass { } //yes	0
2869432	2869256	Getting values from datagrid view column to list<>	List<int> listOfMinutes = new List<int>();\n\nfor (int i = 0;i < dataGridView1.Rows.Count; i++)\n{\n    // either ".Text" or ".Value"...can't remember\n    listOfMinutes.Add(int.Parse(dataGridView1.Rows[i].Cells[7].Text));\n}	0
3250631	3250609	convert decimal to a string - in thousands with rounding	value = Math.Round(value / 1000);	0
6818931	6818851	Change StackPanel location on a Canvas programatically	Canvas.SetLeft(myStackPanel, 50);	0
1525865	1519727	Need a good way to manage the status - was the data changed since last save - under MVVM	public class MainWindowViewModel : ViewModel\n{\n    [RaisePropertyChanged]\n    public string Message { get; set; }\n\n    [RaisePropertyChanged]\n    [SetsHasChanged]\n    public string DataThatCausesModifyDialog { get; set; }\n\n    // ...\n}	0
18813545	18813494	c# List<> select specific variables	var result =product.getProducts().Select(x=> \n          new {Name = x.name ,\n                  Price= x.price})\n         .ToList();	0
20985425	20984994	How can I get my Drop Down List to Navigate to Another Page on Item Selection	protected void Page_Load(object sender, EventArgs e)\n    {\n        DropDownList1.Items.Add("Home");\n        DropDownList1.Items.Add("Login");\n        DropDownList1.Items.Add("Signup");\n    }\n    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        string sUrl = DropDownList1.SelectedItem.Text + ".aspx";\n        Response.Redirect(sUrl);\n    }	0
5003526	4995597	How do you use portable databases with MsBuild?	"sqlite3.exe" %dbFilename% < Database.sql	0
4773719	4773564	In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first?	File.AppendText("filename")	0
6324241	6324032	Inserting a Dictionary into a preexisting excel file, by date	private void FindAndSetDate(WorkSheet ws, Dictionary<DateTime,string> dict)\n{\n    Range find = null;\n    foreach(KeyValuePair<DateTime,String> kvp in Dict)\n    {\n        find = ws.Cells.Find(kvp.Key, Type.Missing,\n        Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,\n        Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false,\n        Type.Missing, Type.Missing);\n\n        if(find!=null) find.Offset[0,1].Value=kvp.Value;    \n    }   \n\n}	0
34422140	34412014	How to disable autofilter in closedXml c#?	ws.Tables.FirstOrDefault().ShowAutoFilter = false;	0
2814889	1842995	Gridview footer data format string	protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    double dVal = 0.0;\n\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        dVal += Convert.ToDouble(e.Row.Cells[1].Text);\n    }\n\n    if (e.Row.RowType == DataControlRowType.Footer)\n    {\n        e.Row.Cells[1].Text = dVal.ToString("c");\n    }\n}	0
15445323	15443976	How to get ListView Item Id	void CheckBox_Click_1(object sender, RoutedEventArgs e)\n{\n    var cb = sender as CheckBox;\n    dynamic itemVM = cb.DataContext;\n    var id = itemVM.Id;\n}	0
11854319	11853840	Render object properties with one line	public static class HtmlHelperExtensions\n{\n    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper,\n        object model)\n    {\n        if (model == null)\n            throw new ArgumentNullException("'model' is null");\n\n        return CheckBoxesForModel(helper, model.GetType());\n    }\n\n    public static MvcHtmlString CheckBoxesForModel(this HtmlHelper helper,\n        Type modelType)\n    {\n        if (modelType == null)\n            throw new ArgumentNullException("'modelType' is null");\n\n        string output = string.Empty;\n        var properties = modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public);\n\n        foreach (var property in properties)\n            output += helper.CheckBox(property.Name, new { @disabled = "disabled" });\n\n        return MvcHtmlString.Create(output);\n    }\n}	0
8885384	8885008	xml to datatable	public DataTable getTable()\n{\n    string file = @"E:\...\Players.xml";\n    DataSet ds = new DataSet();\n    ds.ReadXml(file);\n    return ds.Tables["Player"]; // The name of the table in the dataset is "Player"\n\n}	0
2947132	2945730	How could I implement a bleach bypass shader effect for WPF?	float4 bypassPS(QuadVertexOutput IN, uniform sampler2D SceneSampler) : COLOR\n{\n    float4 base = tex2D(SceneSampler, IN.UV);\n    float3 lumCoeff = float3(0.25,0.65,0.1);\n    float lum = dot(lumCoeff,base.rgb);\n    float3 blend = lum.rrr;\n    float L = min(1,max(0,10*(lum- 0.45)));\n    float3 result1 = 2.0f * base.rgb * blend;\n    float3 result2 = 1.0f - 2.0f*(1.0f-blend)*(1.0f-base.rgb);\n    float3 newColor = lerp(result1,result2,L);\n    float A2 = Opacity * base.a;\n    float3 mixRGB = A2 * newColor.rgb;\n    mixRGB += ((1.0f-A2) * base.rgb);\n    return float4(mixRGB,base.a);\n}	0
14512835	14503374	Is there a pattern for subscribing to hierarchical property changes with Reactive UI?	this.WhenAny(x => x.Address.Line, x => x.Value)\n    .Subscribe(x => Console.WriteLine("Either Address or Address.Line changed!"));	0
5458131	5458049	detect the first character in a variable c#	string input = GetInput();\nstring remainingPart = input.Substring(1); // get string without first character\nswitch (input[0])\n{\n    case 'R':\n        {\n            DoSomething(remainingPart);\n            break;\n        }\n    case 'T':\n        {\n            DoSomethingElse(remainingPart);\n            break;\n        }\n    // more case clauses follow here\n    default:\n        {\n            break;\n        }\n}	0
7705310	7705279	C# Silverlight move a control	MyStackPanel1.Children.Remove(SomeControl);\nMyStackPanel2.Children.Add(SomeControl);	0
1557350	1557338	Modfying a collection (Generics) in a persistent object leads to exceptions or loss of data	protected volatile _alreadySavedData;\n\n    List AlreadySavedData\n      {\n       get\n          {\n             lock(_alreadySavedData)\n             {\n                //Rough Syntax maybe incorrect - but in actual application is correct\n               _alreadySavedData= _alreadySavedData.Find(Delegate (Data d {return d.CreatedOn.Date == DateTime.Now.Data;}));               \n\n                return _alreadySavedData;\n             }\n          }\n    }	0
488090	488071	C# constructors with same parameter signatures	public class Thing\n{\n    private string connectionString;\n\n    private string filename;\n\n    private Thing()\n    {\n        /* Make this private to clear things up */\n    }\n\n    public static Thing WithConnection(string connectionString)\n    {\n        var thing = new Thing();\n        thing.connectionString = connectionString;\n        return thing;\n    }\n\n    public static Thing WithFilename(string filename)\n    {\n        var thing = new Thing();\n        thing.filename = filename;\n        return thing;\n    }\n}	0
10499874	10499771	Accessing xlsx sheets using c++/cli	IEnumerable<Sheet^>	0
11079555	11079510	How can I identify the client of my service?	System.ServiceModel.ServiceSecurityContext.Current	0
18752098	18751919	How to search a webpage with keywords from a .txt list?	string[] keywords = System.IO.File.ReadAllLines(@"C:\Temp\keywords.txt");\n\nList<string> nomatch = new List<string>();\n\nSystem.Net.WebClient wc = new System.Net.WebClient();\n\nforeach (string word in keywords)\n{\n    string response = wc.DownloadString("http://www.website.com/search.php?word=" + word);\n\n    if (response != null && response.Contains("No matches found"))\n        nomatch.Add(word);\n}\n\nif (nomatch.Count > 0)\n    System.IO.File.WriteAllLines(@"C:\Temp\nomatch.txt", nomatch.ToArray());	0
9593077	9592166	Unique number in random?	public static void FisherYatesShuffle<T>(T[] array)\n{\n    Random r = new Random();\n    for (int i = array.Length - 1; i > 0; i--)\n    {\n        int j = r.Next(0, i + 1);\n        T temp = array[j];\n        array[j] = array[i];\n        array[i] = temp;\n    }\n}\n\nint[] array = new int[10000];\n\nfor (int i = 0; i < array.Length; i++) array[i] = i;\nFisherYatesShuffle(array);	0
8581153	8581106	How do I stop casting in this scenario?	class APlugin<TAction> where TAction : AAction\n{\n    TAction _action;\n\n    APlugin(TAction action)\n    {\n        _action = action;\n    }\n\n}\n\nclass BluePlugin: APlugin<BlueAction>\n{\n    BluePlugin(): base(new BlueAction());\n    {\n    }\n\n    void Foo()\n    {\n        // do stuff with BlueAction's methods\n        _action.Foo1();\n        _action.Foo2();\n    }\n}	0
9308489	9303898	ServiceDescriptionImporter cannot find definition for web service namespace	if (externalSchema is XmlSchemaImport)	0
24662888	24662412	Remove duplicates with lamda leaving last item (from dupes) alive	items = items.GroupBy(i => new {i.X, i.Y, i.Z}).Select(i => i.Last()).ToList();	0
21451287	21182830	How to add data source to Lookup Edit at run time?	yourLookUpEdit.Properties.DataSource = //Your List or DataTable	0
1073808	1073783	Is it possible to programmatically create a DBLink in SQL server 2005 in C#?	EXEC sp_addlinkedserver\n    @server = 'OracleHost',\n    @srvproduct = 'Oracle',\n    @provider = 'MSDAORA',\n    @datasrc = 'MyServer'	0
4067344	4067311	How to Check for the nullable dates in the linq query	&& x.DateOfBirth.HasValue &&	0
4036644	4036507	Replace part of text in a dynamic string	Regex r = new Regex("(?<part1>/media.*)");\nvar result = r.Match(@"D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf");\nif (result.Success)\n{\n    string value = "../" + result.Groups["part1"].Value.ToString();\n    Console.WriteLine(value);\n}	0
4319654	4319516	How to get the max timestamp and groupby another field in LINQ to Entities	var q1 = \n    from req in myEntity\n    group req by req.TaskId into g\n    let topReq = g.OrderByDescending(r => r.Timestamp).FirstOrDefault()\n    select new\n    {\n        topReq.TaskId,\n        topReq.SubTaskId,\n        topReq.Timestamp\n    };	0
5855091	5854807	how to set the link at end of the columns in datagrid in winforms	dataGridView1.Columns["Column7"].DisplayIndex = dataGridView1.Columns.Count - 1;	0
18747261	18747138	Get numerical part of a string	var fileName = "1000/Refuse5.jpg";\nvar match = Regex.Match(fileName, @"(?<=\D+)(\d+)(?=\.)");\n\nif(match.Success)\n{\n    var value = int.Parse(match.Value);\n}	0
4639431	4639387	Calculate rotation between two Vector2s around a pivot	Vector2 a = Pivot - Previous, b = Current - pivot;\ndouble angle = a.X * b.Y - a.Y * b.X;	0
1250715	1250676	How to pass a variable from one app domain to another	static voide Main(string[] args) {\n    _str = "abc";\n\n    AppDomainSetup setup = new AppDomainSetup();\n    setup.AppDomainInitializer = new AppDomainInitializer(MyNewAppDomainMethod);\n    setup.AppDomainInitializerArguments = new string[] { _str };\n\n    AppDomain domain = AppDomain.CreateDomain(\n        "Domain666",\n        new Evidence(AppDomain.CurrentDomain.Evidence),\n        setup);\n\n    Console.WriteLine("Finished");\n    Console.ReadKey();\n}\n\nstatic void MyNewAppDomainMethod(string[] args) {\n    ...\n}	0
13921086	13921031	Zip files using ZipFiles	zip.AddFile("C:\\ReadMe.txt", "");	0
7928441	7928412	Fastest way of converting IPv6 dotted format string to colon format ? C#	var result = new IPAddress(x.Split('.').Select(byte.Parse).ToArray()).ToString();\n// result == "805b:2d9d:dc28:650a:a01:fc57:16c8:1fff"	0
4252869	4252735	Double click to Windows form in C#	MouseButtons _lastButtonUp = MouseButtons.None;\n\nprivate void Form1_MouseUp(object sender, MouseEventArgs e)\n{\n    _lastButtonUp = e.Button;\n}\n\nprivate void Form1_DoubleClick(object sender, EventArgs e)\n{\n    switch (_lastButtonUp)\n    {\n        case System.Windows.Forms.MouseButtons.Left:\n            MessageBox.Show("left double click");\n            break;\n        case System.Windows.Forms.MouseButtons.Right:\n            MessageBox.Show("right double click");\n            break;\n        case System.Windows.Forms.MouseButtons.Middle:\n            MessageBox.Show("middle double click");\n            break;\n    }\n\n}	0
3377501	3377499	Access web.config key from codebehind	string from = ConfigurationManager.AppSettings["MailFrom"];	0
21034072	21032225	Playing sound on button click while moving to other page C#	using Windows.ApplicationModel;\nusing Windows.Storage;\n\nprivate async void ButtonPlay_Click(object sender, RoutedEventArgs e)\n{\n    MediaElement snd = new MediaElement();\n    StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");\n    StorageFile file = await folder.GetFileAsync("Alarm01.wav");\n    var stream = await file.OpenAsync(FileAccessMode.Read);\n    snd.SetSource(stream, file.ContentType);\n    snd.Play();\n    this.Frame.Navigate(typeof(Game));\n\n }	0
13107771	13107752	How to make a textbox disable but selectable	textbox.ReadOnly = true;	0
20218643	20218424	Compare Size of Text File to a Value	string file1 = "firstFile.txt";\n\n\n  // Placing these resources (FileStream and TextWriter) in using blocks ensures that their resources are released when you are done\n  // with them.\n  using (Stream fs = new FileStream(file1, FileMode.Append))\n  using (TextWriter tx1 = new StreamWriter(fs))\n  {\n\n    // This will only keep track of the file information when you call it.\n    // Any subsequent changes to the file will not update this variable.\n    FileInfo fi1 = new FileInfo(file1);\n\n    if (fi1.Length < 1024)\n    {\n      tx1.WriteLine("Babloooooooooooooooooo ");\n\n      // If you don't flush this line, you won't get an up to date value for 'length' below.\n      // Comment it out, and see for yourself.\n      tx1.Flush();\n      Console.WriteLine("The length is...", fs.Length);\n    }\n    else\n    {\n      Console.WriteLine("Limit reached");\n    }\n  }	0
16547379	16546850	AutoFixture: how to CreateAnonymous from a System.Type	var specimen = new SpecimenContext(fixture).Resolve(type);	0
19577224	19576504	Find available numbers from a list of numbers in a particular range	//assuming already sorted\nvar a = Enumerable.Range(0, 10000);\n//assuming alredy sorted\nvar b = new List<int>(){0, 1, 2, 4, 20, 21, 22};\n//get the values not used yet in sorted order\nvar c = a.Except(b).ToList();\n//store the list range\nList<string> range = new List<string>();\n\nfor(int i = 0; i < c.Count; i++)\n{\n    //current start range\n    int current = c[i];\n    string r = current.ToString();\n\n    int next;\n    if(current > b.Last())\n        next = c.Last() + 1;\n    else\n        next = b.FirstOrDefault( x => x > current);\n\n\n    if( next != current+1)\n        r += "-" + (next-1).ToString();\n\n   range.Add(r);\n\n\n   while(c[i] < next-1) i++;\n }	0
9086022	9084795	Loading An Assembly Into An Application Domain With Lower Security	FileIOPermissionAccess.PathDiscovery	0
8797769	8797082	How to count down and display time before next timer tick?	private void tmrClickInterval_Tick(object sender, EventArgs e)\n    {\n        stopWatch.Stop();\n        stopWatch.Reset();         \n        stopWatch.Start();\n        tmrNextClick.Start();\n        content++;\n        label1.Text = content.ToString();\n    }\n\n    private void tmrNextClick_Tick(object sender, EventArgs e)\n    {\n        nextClick = (((tmrClickInterval.Interval) - stopWatch.ElapsedMilliseconds) / 10) * 10;\n        if (!(nextClick < 0))\n        {\n            lblNextClickCount.Text = nextClick.ToString();\n        }\n    }	0
14450619	14450449	MonoGame loading a png file	Content/background	0
4814654	4814552	How do you send a serialized object over net?	TcpClient client = (TcpClient) connection;\n\nusing(StreamWriter streamWriter = new StreamWriter(tcpClient.GetStream()))\n{\n    BinaryFormatter binaryFormatter = new BinaryFormatter();\n    binaryFormatter.Serialize(streamWriter, savedObject);\n}	0
1179987	1179970	How to find the most recent file in a directory using .NET, and without looping?	var directory = new DirectoryInfo("C:\\MyDirectory");\nvar myFile = (from f in directory.GetFiles()\n             orderby f.LastWriteTime descending\n             select f).First();\n\n// or...\nvar myFile = directory.GetFiles()\n             .OrderByDescending(f => f.LastWriteTime)\n             .First();	0
1800302	1797526	How to determine if a Publishing Page in Sharepoint 2007 is actually published	PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();\nforeach (PublishingPage page in pages)\n{\n    if(!page.ListItem.File.Level == SPFileLevel.Published)\n       return;\n    // logic\n}	0
7255895	7255745	Problem with getting last inserted ID from database - asp.net	cmd.CommandText = "INSERT INTO tbl_user (...) OUTPUT inserted.Id VALUES (...)";\nvar id = Convert.ToInt32(cmd.ExecuteScalar());	0
27901393	27901293	Invalid attempt to call Read when reader is closed on WCF service with windows froms application	using (SqlDataReader dataReader = cmd.ExecuteReader())\n    {\n            dtScriptDetails.Load(dataReader);\n     }	0
17385288	17385078	How would one bind a SortedSet in WPF?	public class ObservableSortedSet<T> : INotifyCollectionChanged, ISet<T>\n{\n    public event NotifyCollectionChangedEventHandler CollectionChanged;\n    private readonly SortedSet<T> _sortedSet;\n\n    public ObservableSortedSet()\n    {\n        _sortedSet = new SortedSet<T>();\n    }\n\n    public bool Add(T item)\n    {\n        bool result = _sortedSet.Add(item);\n        OnCollectionChanged(NotifyCollectionChangedAction.Add);\n        return true;\n    }\n\n    private void OnCollectionChanged(NotifyCollectionChangedAction action)\n    {\n        if (CollectionChanged != null)\n            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));\n    }\n\n    // all the rest of ISet implementation goes here...\n}	0
5006152	5005983	Determine the difference between two DateTimes, only counting opening hours	DateTime start = DateTime.Parse("15/02/2011 16:00");\nDateTime end = DateTime.Parse("16/02/2011 10:00");\n\nint count = 0;\n\nfor (var i = start; i < end; i = i.AddHours(1))\n{\n    if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)\n    {\n        if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)\n        {\n            count++;\n        }\n    }\n}\n\nConsole.WriteLine(count);	0
21979039	21899599	How to get SubstringValues from Textbox	string Input = TeInput.Text, Store1 = string.Empty, store2 = string.Empty;\n            int Start = 0, End = 0;\n            Start = int.Parse(TeStart.Text);\n\n            End = int.Parse(TeEnd.Text);\n            string Output = TeOutput.Text;\n\n            Store1 = Input.Remove(0, Start).Trim();\n            store2 = Store1.Remove(Store1.Length-End).Trim();\n            TeOutput.Text = store2;	0
1605594	1605566	Custom Control in TextBox Help?	public partial class PreTextBox : TextBox\n{\n    public PreTextBox()\n    {\n        InitializeComponent();\n        Text = PreText;\n        ForeColor = Color.Gray;\n    }\n    public string PreText\n    {\n        set{Text = value;} \n        get{return Text;}\n    }\n}	0
4950696	4950206	Deserialize JSON object array in C# using LitJson	{\n    result:[\n                {"building_id":"1","building_level":"0","workers":"0","building_health":"100"},\n                {"building_id":"2","building_level":"0","workers":"0","building_health":"100"},...\n                {"building_id":"32","building_level":"0","workers":"0","building_health":"100"}\n           ]\n}	0
14091500	14087165	Automatically flush data to database	class MainConfigProxy : MainConfig\n{\n    public override Enabled\n    {\n         get { return base.Enabled; }\n         set\n         {\n             base.Enabled = value;\n             mainSession.Save();\n         }\n    }\n}	0
21307446	21307313	watching multiple string-property changes from another class?	var dict = new StringDictionary();\ndict.Add("Text1", "yadayad");\n// add the rest\n\n\nvar val = dict[property_name];\nif (val != null)\n{\n   Console.WriteLine(val);\n}	0
10510259	10381271	Sub menus fallback to jqGrid	#jqGridDiv\n{\nposition:relative;\nz-index:1;\n}	0
13254936	13252738	Launch the new mail dialog from within Outlook add in	using Outlook = Microsoft.Office.Interop.Outlook;\n\nOutlook.MailItem mail = Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);\nmail.UserProperties.Add("IsSecure", Outlook.OlUserPropertyType.olYesNo);\nmail.Display();	0
1327375	1327293	How to store a factory used in a derived class to initialize its base class?	Func<ResourceManager, Resource>	0
14439655	14439389	Sending JSON with SignalR	chat.server.send2(frage);	0
4603538	4366090	c# check if the user member of a group?	public bool AuthenticateGroup(string userName, string password, string domain, string group)\n    {\n\n\n        if (userName == "" || password == "")\n        {\n            return false;\n        }\n\n        try\n        {\n            DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);\n            DirectorySearcher mySearcher = new DirectorySearcher(entry);\n            mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";\n            SearchResult result = mySearcher.FindOne();\n\n            foreach (string GroupPath in result.Properties["memberOf"])\n            {\n                if (GroupPath.Contains(group))\n                {\n                    return true;\n                }\n            }\n        }\n        catch (DirectoryServicesCOMException)\n        {\n        }\n        return false;\n    }	0
26776254	26775710	c# WPF prevent splashscreen (image -> buildaction -> Splashscreen) on special parameter startup	SplashScreen oSplashScreen = new SplashScreen("Resources\\splash-screen.jpg");\n\n        if (!bMinimizedStartup)\n        {\n            oSplashScreen.Show(true, true);\n        }	0
27478660	27443314	Issue in Inserting and retrieveing document in MongoDB using C# for dynamic datatype fields	var elemDoc = BsonExtensionMethods.ToBsonDocument(value);\ndoc["filedName"] = elemDoc;\ncollection.Insert(doc);	0
9194936	9194475	Populating a listview from another thread	using System;\nusing System.Windows.Forms;\n\nnamespace TestWinFormsThreding\n{\n    class TestFormCotrolHelper\n    {\n        delegate void UniversalVoidDelegate();\n\n        /// <summary>\n        /// Call form controll action from different thread\n        /// </summary>\n        public static void ControlInvike(Control control, Action function)\n        {\n            if (control.IsDisposed || control.Disposing)\n                return;\n\n            if (control.InvokeRequired)\n            {\n                control.Invoke(new UniversalVoidDelegate(() => ControlInvike(control, function)));\n                return;\n            }\n            function();\n        }\n    }\n\n    public partial class TestMainForm : Form\n    {\n    // ...\n    // This will be called from thread not the same as MainForm thread\n    private void TestFunction()\n    {\n        TestFormCotrolHelper.ControlInvike(listView1, () => listView1.Items.Add("Test"));\n    }   \n    //...\n    }\n}	0
5768647	5768588	java C# vb: how do we dynamically create an instance of a class from a string input (class name)	object myObject = (Framework.Asd.Human)Activator.CreateInstance(TypeOf(Framework.Asd.Human), new object[] { "John", 100, 200 });	0
30747859	30745942	How can I deploy an app using Identity Model to Production on Azure?	Windows Azure Services	0
7348340	7348283	How to start making an Audio and Video Streaming Application in c#	vlc.playlist.add("FileName/Stream IP/Drive Letter","Display Text", "Options");\n\nvlc.playlist.play();	0
21987710	21987581	Inheritance same methods implementation	dClass d = new dClass();\niAclass a = (iAclass)d;\na.addition(123);  // Calls implementation for iAclass\niBclass b = (iBclass)d;\nb.addition(123);  // Calls implementation for iBclass	0
14083098	14083007	Data in GridView is not being displayed correctly	SqlDataAdapter dataadapter = new SqlDataAdapter();\n    DataSet ds = new DataSet();\n    conn.Open();\n    dataadapter.Fill(ds, "Your table name");\n    conn.Close() ;\n    DataGridView1.DataSource = ds;\n    DataGridView1.DataMember = "Your table name";	0
22347308	22345799	how to count conditioned continuous values in a list with linq?	int groupCount = 0;\nvar result = query\n    .Select((x, i) => new { Value = x, Index = i })\n    .SkipWhile(x => x.Value != 0)                   // Skip until first 0 is reached\n    .TakeWhile(x => x.Value == 0 || x.Value == 1)   // Take a continuous series of 0 and 1\n    .Where(x => x.Value == 0)                       // Filter out the 1s\n    .GroupBy(x =>\n        // Treat as a new group if it's:\n        // 1) the 1st element, or\n        // 2) doesn't equal to previous number\n        x.Index == 0 || x.Value != query.ElementAt(x.Index - 1)\n            ? ++groupCount\n            : groupCount)\n    .Select(x => new\n    {\n        Count = x.Count(),\n        Start = x.First().Index,\n        End = x.Last().Index\n    });	0
6560128	6560105	Change PictureBox's image to image from my resources?	picturebox.Image = project.Properties.Resources.imgfromresource	0
1605998	1605831	C#: Displaying images based on number of views and random	List<KeyValuePair<string, decimal>> list = new List<KeyValuePair<string, decimal>>();\n\n            for (int iItem = 0; iItem < 10; iItem++)\n                list.Add(new KeyValuePair<string, decimal>(iItem.ToString(), iItem/10m));\n\n            Random rnd = new Random();\n\n            list.Sort(  delegate(KeyValuePair<string, decimal> item1, KeyValuePair<string, decimal> item2) \n                        {\n                            if (item1.Value == item2.Value)\n                                return 0;\n                            decimal weight1 = 1 / (item1.Value == 0 ? 0.01m : item1.Value);\n                            decimal weight2 = 1 / (item2.Value == 0 ? 0.01m : item2.Value);\n                            return (weight1 * rnd.Next()).CompareTo(weight2 * rnd.Next()); \n                        });\n            list.Reverse();	0
9161490	9140773	How to obtain values in JSON in C#?	var postTitles = from p in JO["data"].Children()\n                             select new\n                             {\n                                 Names = (string)p["from"]["name"],\n                                 Msg = (string)p["message"],\n                             };	0
1654214	1654209	How to access index in IEnumerator object in C#?	var myProducts = Models.Products.ToList();\nfor(i=0; i< myProducts.Count ; i++)\n{\n      //myProducts[i];\n}	0
9776955	9776716	Using LINQ to select item in List<T> and add integer to populate new List<T>	var n = 6;\n\nList<string> strList = new List<string>() {"20","26","32"}; \n// list can also be {null, "26", null} , {null, "N", "32"} , \n//                  {"N", "26", null } etc...\n\nvar list = strList.Select(s =>\n{\n   int v;\n   if(string.IsNullOrEmpty(s) || !int.TryParse(s,out v))\n      return (int?)null;\n   return v;\n});\n\nvar firstValidVal = list.Select((Num, Index) => new { Num, Index })\n                        .FirstOrDefault(x => x.Num.HasValue);\nif(firstValidVal == null)\n    throw new Exception("No valid number found");\n\nvar bases = Enumerable.Range(0, strList.Count).Select(i => i * n);\nint startVal = firstValidVal.Num.Value - bases.ElementAt(firstValidVal.Index);\n\nvar completeSequence = bases.Select(x => x + startVal);	0
14755477	14752723	Find requested page from masterpage load?	public class BasePage : Page\n{\n    /// <summary>\n    /// \n    /// </summary>\n    /// <param name="e"></param>\n    protected override void OnInit(EventArgs e)\n    {\n        if (Session["Usuario"] == null)\n        {\n            Response.Redirect(ResolveClientUrl("~/Login.aspx"));\n        }        \n    }\n}	0
2499896	2499707	Deserialized xml - check if has child nodes without knowing specific type	XElement x = XElement.Load("myfile.xml");\nif (x.Nodes.Count() > 0)\n{\n  // do whatever\n}	0
7419013	7418258	Using polymorphic queries over interfaces in RavenDB	// ByName\nfrom doc in docs\nselect new { doc.Name }	0
12420146	12420132	How to remove a given particular symbol from a string using C#	value = value.Replace("{", "").Replace("}", "");	0
3251580	3249740	Bulk Insert or Another way to load a lot of data at once using C# and SQL server?	INSERT INTO Files (ProjectId,FileId) \n SELECT 2 As ProjectId, FileId\n FROM Files WHERE ProjectId = 1	0
15554855	15554783	for loop with different order in C#	foreach (int x in list.OrderBy(i=>Math.abs(i))\n{\n    // Do Stuff\n}	0
1288315	1288294	Possible to output to console from within a class library C#?	Console.WriteLine	0
1301221	1301127	How to ignore a certificate error with c# 2.0 WebClient - without the certificate	public static void InitiateSSLTrust()\n{\n    try\n    {\n        //Change SSL checks so that all checks pass\n        ServicePointManager.ServerCertificateValidationCallback =\n           new RemoteCertificateValidationCallback(\n                delegate\n                { return true; }\n            );\n    }\n    catch (Exception ex)\n    {\n        ActivityLog.InsertSyncActivity(ex);\n    }\n}	0
19870946	19867217	Validation of incoming XML - should I use both a XSD file and in code validation	xs:assertion	0
18661491	18659481	Setting Reminders in Windows Phone 7 & 8 to Go Off Every Other Day	string fileTitle = "Foo";\nstring fileContent = "Bar";\nvar action = ScheduledActionService.Find(fileTitle);\nif (action == null)\n{\n    // shouldn't be null if it was already added from the app itself.\n    // should get the date the user actually wants the alarm to go off.\n    DateTime date = DateTime.Now.AddSeconds(30);\n    action = new Reminder(fileTitle) { Title = fileTitle, Content = fileContent, BeginTime = date };\n}\nelse if (action.IsScheduled == false)\n{\n    ScheduledActionService.Remove(fileTitle);\n    // most likely fired today, add two days to the begin time.\n    // best to also add some logic if BeginTime.Date == Today\n    action.BeginTime = action.BeginTime.AddDays(2);\n}\nScheduledActionService.Add(action);	0
9322233	9319656	How to encode a path that contains a hash?	// Build Uri by explicitly specifying the constituent parts. This way, the hash is not confused with fragment identifier\nUriBuilder uriBuilder = new UriBuilder("http", "www.contoso.com", 80, "/code/c#/somecode.cs");\n\nDebug.WriteLine(uriBuilder.Uri);\n// This outputs: http://www.contoso.com/code/c%23/somecode.cs	0
22808305	22808043	How do I capitalized specific two letter word in a string in addition to the first letter of any word?	var input = "dr. david BOWIE md";\n        TextInfo tCase = new CultureInfo("en-US", false).TextInfo;\n        var result = tCase.ToTitleCase(input.ToLower());\n\n        var wordsToCapitalize = new []{"nw", "dw", "md"};\n\n        result = string.Join(" ", result.Split(' ')\n            .Select(i => (i.Length == 2 && wordsToCapitalize.Contains(i.ToLower())) ? i.ToUpperInvariant() : i));\n\n        Assert.That(result, Is.EqualTo("Dr. David Bowie MD"));	0
10329652	10329492	Accessing a common variable in WebMethod and jQuery	Public class CustomClass\n{\n    public string HTML { get; set; }\n    public bool Load  { get; set; }\n}\n\n[WebMethod()]\npublic static StatusViewModel  GetDataFromServer()\n{\n    // do work\n    return CustomObject;\n}	0
25117269	25117146	Delete a whole element in a XML-File	var xml = XElement.Load(File.OpenRead(@"XmlLocation"));\n\nvar elementsToDelete =\n    xml.Descendants("dependentAssembly")\n       .Where(x => x.Attribute("dependencyType") != null && \n                   x.Attribute("dependencyType").Value != "preRequisite");\n\nforeach (var xElement in elementsToDelete)\n{\n    xElement.Remove();\n}	0
7093197	6940269	Plugin crashes on refreshing page from app on Win 7	public App () {\n        ...\n\n    App.Current.InstallStateChanged += new EventHandler(Current_InstallStateChanged);\n}\n\nvoid Current_InstallStateChanged(object sender, EventArgs e) {\n    if(App.Current.InstallState == System.Windows.InstallState.Installed) {\n        HtmlPage.Document.Submit();\n    }\n}	0
9532818	9532761	How to get an underlying DataTable from a control (i.e. under DataGridView)?	DataTable dt = ((DataSet)dataGridView1.DataSource).Tables[index];	0
27110266	27108418	c# Update Access Database Table with DataSet	c#:\nOleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);\nforeach(DataRow dr in csrst2.Tables[0].Rows)\n{\n    var findfirst = csrst1.Tables[0].Select("[L1]=" + dr[0] + "  AND [D1]=#" + dr[1] + "#");\n    if(findfirst.Count() < 1)\n    {\n        var newRow = csrst1.Tables[0].NewRow();\n        //...new row fields set\n        csrst1.Tables[0].Rows.Add(newRow);\n        adapter.Update(csrst1.Tables[0]);\n    }\n    else\n    {   \n        findfirst[0].BeginEdit();\n        //...rows edited\n        findfirst[0].AcceptChanges();\n        adapter.Update(csrst1.Tables[0]);\n    }\n}	0
4810444	4810415	C# "must declare a body because it is not marked abstract, extern, or partial"	private int hour;\npublic int Hour\n{\n    get { return hour; }\n    set\n    {\n        //make sure hour is positive\n        if (value < MIN_HOUR)\n        {\n            hour = 0;\n            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),\n            "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n        }\n        else\n        {\n            //take the modulus to ensure always less than 24 hours\n            //works even if the value is already within range, or value equal to 24\n            hour = value % MAX_HOUR;\n        }\n    }\n}	0
23405100	23399272	Return Custom HTTP Status Code from WebAPI 2 endpoint	using System.Net;\nusing System.Net.Http;\nusing System.Web.Http;\n\nnamespace CompanyName.Controllers.Api\n{\n    [RoutePrefix("services/noop")]\n    [AllowAnonymous]\n    public class NoOpController : ApiController\n    {\n        [Route]\n        [HttpGet]\n        public IHttpActionResult GetNoop()\n        {\n            return new System.Web.Http.Results.ResponseMessageResult(\n                Request.CreateErrorResponse(\n                    (HttpStatusCode)422,\n                    new HttpError("Something goes wrong")\n                )\n            );\n        }\n    }\n}	0
12322402	12321864	How to catch own C# events in Javascript code in Win8 Metro apps?	App.myclass.addEventListener("nowevent", function onReady() {\n        console.error("hello");\n    });	0
17325313	17324071	Handle app closing events with active GUI updates	private void MyApp_FormClosing(object sender, FormClosingEventArgs e)\n{\n    lblMainStatus.Text = "Closing app, please wait.";\n    foreach(MyResource r in AppResources)\n    {\n        System.Threading.Thread.Sleep(1000);\n        lblMinorStatus.Text = "Freeing resources - remaining : " + AppResources.Count;\n        r.discard();\n        this.Refresh();\n    }\n    lblMinorStatus.Text = "Done.";\n    // And so on...\n}	0
8878185	8878138	Get just the time from System.DateTime	myDateTime.ToShortTimeString();\n\nmyDateTime.ToString("hh:mm:ss"); //for 12 hour clock\n\nmyDateTime.ToString("HH:mm:ss"); //for 24 hour clock	0
16962307	16962005	Add an Index to a list that resets depending on Id group	var indexList = list\n    .GroupBy(item => item.Id)\n    .SelectMany(grp => grp\n        .Select((item, index) => new { index = index, t = item }))\n    .ToList();	0
4229226	4229201	C# - Get selected cell's row's first cell's value	DataGridView.SelectedRow.Cells[0]	0
9888271	9888242	Required parameters based on other parameters	public static void MyMethod (string p1, string p2)\n{\n   MyMethod(p1, p2, "", "");\n}\n\npublic static void MyMethod (string p1, string p2, string p3, string p4)\n{\n   ...\n}	0
9884027	9883927	Not getting selected value from drop down box	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!Page.IsPostBack)\n        {\n            LoadTable();\n        }\n\n\n    }	0
9036096	9035860	Reflection: Calling Method with generic list as a result	// Create generic type\nType myClassType = typeof(MyClass<>);\nType[] typeArgs = { typeof(object) };   \nType constructed = myClassType.MakeGenericType(typeArgs);\n\n// Create instance of generic type\nvar myClassInstance = Activator.CreateInstance(constructed);    \n\n// Find GetAll() method and invoke\nMethodInfo getAllMethod = constructed.GetMethod("GetAll");\nobject result = getAllMethod.Invoke(myClassInstance, null);	0
11506680	11506535	Removing a Selective Section from a String	var originalString = @"<DIV style='TEXT-ALIGN: center'><span style='text-decoration:underline;'> some text   </span> </span></DIV>";\n\n        var lastIndex = originalString.LastIndexOf("</span>");\n\n        var newwString = originalString.Substring(0, lastIndex) + originalString.Substring(lastIndex + 7);	0
5816612	5815984	Prevent Expansion of Environment Variables	RegistryValueOptions.DoNotExpandEnvironmentNames	0
7744444	7744320	C# XMLElement.OuterXML in a single line rather than format	logger.Info(XElement.Parse(request.OuterXml).ToString());	0
16941935	16923664	Using one view for index and create in mvc4	public ActionResult Index(int patid = 0, Lab lab = null)\n        {\n            ViewBag.Finalize = PatientSubmitted(patid);\n            ViewBag.DispPatientId = patid;\n            ViewBag.CheckButtonStatus = ButtonSubmitted(patid);\n            var labs = db.Labs.Where(l => l.PatientId == patid && l.Active);\n            LabIndexViewModel model = new LabIndexViewModel();\n            if (lab == null)\n                lab = new Lab();\n            lab.PatientId = patid;\n            model.Labs = labs.ToList();\n            model.Lab = lab;\n            SetViewBagLists();\n            return View(model);\n        }	0
14686366	14686301	How do i check whether connection details to MySql Server are valid?	private bool checkConnectionSuccess(string host, string user, string pass, string dbname)\n{\n   string connectionString = "Data Source=" + host + ";Database=" + dbname + ";User ID=" + user + ";Password=" + pass;\n\n   bool sucessful = true;\n\n   using (MySqlConnection conn = new MySqlConnection (connectionString))\n   {\n     try\n     {\n       conn.Open();\n     }\n     catch (MySqlException ex)\n     {\n       sucessful = false;\n     }\n   }\n    return sucessful;\n}	0
27451446	27451250	MySQL with C# problems	using(MySqlConnection con = new MySqlConnection("myConnectionString"))\nusing(MySqlCommand cmd = con.CreateCommand());\n{\n    con.Open();\n\n    // BUILD an unique string with the INSERT INTO \n    // followed by the SELECT (with semicolon to divide)\n    string sqlInsertText = @"INSERT INTO yourTable (field1, FieldX) VALUES (value1, ValueX);\n                            SELECT LAST_INSERT_ID();";\n    cmd.CommandText = sqlInsertText;\n\n    // ExecuteScalar will execute the text of the command and returns the first column of the \n    // first row retrieved by the last statement executed \n    // (in this case the result of SELECT LAST_INSERT_ID()\n    object result = cmd.ExecuteScalar();\n    if(result != null)\n    {\n\n       int lastID = Convert.ToInt32(result);\n       .....\n    }\n}	0
25427128	25426819	Finding out if a Hex color is dark or light	System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FF2233");\n        if (col.R * 0.2126 + col.G * 0.7152 + col.B * 0.0722 > 255 / 2)\n        {\n            //dark color\n        }\n        else\n        {\n            //light color\n        }	0
14495614	14471929	Use 'dynamic' throw a RuntimeBinderException	dynamic dy;\n            List<dynamic> result = new List<dynamic>(); \n\n            foreach (var item in ItemSource)\n            {\n                dy = new ExpandoObject();\n                var d = dy as IDictionary<string, object>;\n\n                foreach (var property in item.GetType().GetProperties())\n                {\n                    d.Add(property.Name, item.GetType().GetProperty(property.Name).GetValue(item, null));\n                }\n\n                result.Add(dy);\n            }\n\n            foreach (var item in result)\n            {\n                var r = ((dynamic)item) as IDictionary<string, object>;\n                foreach (var k in r.Keys)\n                {\n                    Console.WriteLine(r[k] as string);\n                }\n            }	0
16927758	16927382	sizeof gives a different result depending on field order	[StructLayout(LayoutKind.Sequential, Pack=1)]	0
25230939	25230537	How do I create a Modal UITypeEditor for a string property?	if (svc.ShowDialog(form) == DialogResult.OK)\n {\n     value = form.Value;\n }	0
24306110	24305943	Label.Image gradually increase with for loop	private async void button1_Click(object sender, EventArgs e)\n{\n    foreach (Image image in imageList1)\n    {\n        await Task.Delay(1000); //wait for one second before changing\n        label1.Image = image;\n    }            \n}	0
4436826	4436795	C# How to convert irregular date and time String into DateTime?	DateTime result;\nstring dateToParse = "Thu Dec  9 05:12:42 2010";\nstring format = "ddd MMM d HH:mm:ss yyyy";\n\nif (DateTime.TryParseExact(\n    dateToParse, \n    format,\n    CultureInfo.InvariantCulture, \n    DateTimeStyles.AllowWhiteSpaces, \n    out result)\n)\n{\n    // The date was successfully parsed => use the result here\n}	0
13310178	13310112	Custom Attribute above a controller function	public class FirstTimeAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        if(filterContext.HttpContext.Session != null)\n        {\n          var user = filterContext.HttpContext.Session["User"] as User;\n          if(user != null && string.IsNullOrEmpty(user.FirstName))\n              filterContext.Result = new RedirectResult("/home/firstname");\n          else\n          {\n              //what ever you want, or nothing at all\n          }\n         }\n    }\n}	0
21479268	21479149	How to change some range values in entire list with Linq	var query = Enumerable.Range(0, 999).Select((n, index) =>\n            {\n                if (index <= 333)\n                    return 0;\n                else if (index <= 666)\n                    return 1;\n                else\n                    return 2;\n            });	0
11293490	10947717	How to calculate checksum	private string CalculateChecksum(string dataToCalculate)\n{\n    byte[] byteToCalculate = Encoding.ASCII.GetBytes(dataToCalculate);\n    int checksum = 0;\n    foreach (byte chData in byteToCalculate)\n    {\n        checksum += chData;\n    }\n    checksum &= 0xff;\n    return checksum.ToString("X2");\n}	0
19576041	19575999	Allowing backspace in winforms input field	if (!Char.IsNumber(e.KeyChar) && \n    !Char.IsControl(e.KeyChar))\n{\n    e.Handled = true;\n}	0
6913083	6913022	Collection of criteria that a bool CriteriaAreMet method checks	public delegate bool AdvancementCriterion(Player player);\npublic List<AdvancementCriterion> AdvancementCriteria { get; }\n\nAdvancementCriteria.Add(p => p.Thingy > x);\n\nif (AdvancementCriteria.All(c => c(Player))	0
1900265	1899855	Two methods that differ only in LINQ where part - delegate?	internal List<int> GetOldDoctorsIDs()\n{\n    return GetDoctorsIDs((doctor) => doctor.Age > 30);\n}\n\ninternal List<int> GetExpensiveDoctorsIDs()\n{\n    return GetDoctorsIDs((doctor) => doctor.Cost > 30000);\n}\n\ninternal List<int> GetDoctorsIDs(Func<DataRow, bool> Condition)\n{\n    var Result = from DataRow doctor in DoctorTable.Rows\n                 where Condition(doctor)\n                 select doctor.ID\n    List<int> Doctors = new List<int>();\n    foreach (int id in Result)\n    {\n         //Register getting data\n         Database.LogAccess("GetOldDoctorsID: " + id.ToString());\n         if (Database.AllowAccess(DoctorsTable, id))\n         {\n             Doctors.Add(id);\n         }\n    }\n}	0
30151894	30151677	Regex replace number after string	var txt = new Regex(@"(?si)\(`(\d+)\[\],([a-z]+\.[a-z]+)\{`(\d+).`{2}(\d+).`{2}(\d+)\}\)");\nvar res = txt.Replace(@"(`0[],System.Func{`0,``0,``1})", m =>\n            "(T" + string.Format("{0}", (Int32.Parse(m.Groups[1].Value) + 1)) +\n            "[]," + m.Groups[2].Value + "{T" + string.Format("{0}", (Int32.Parse(m.Groups[3].Value) + 1)) +\n            ",Tm" + string.Format("{0}", (Int32.Parse(m.Groups[4].Value) + 1)) +\n            ",Tm" + string.Format("{0}", (Int32.Parse(m.Groups[5].Value) + 1)) + "})");	0
1512168	1512145	How do I convert an array on the client into a byte[] on the server?	class A{\n      public static void Main()\n      {\n       byte[] a = new byte[]{143,147,31,70,195,72,228,190,152,222,65,240,152,183,0,161};\n       string s = System.Convert.ToBase64String(a);\n       System.Console.WriteLine(s);\n       byte[] b = System.Convert.FromBase64String(s);\n       System.Console.Write("[");\n       foreach (var n in b)\n           System.Console.Write(n+",");\n       System.Console.WriteLine("]");\n      }\n}	0
9632385	9631776	Call Javascript from GridView TemplateField	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow) \n    { \n         Button btn = (Button)e.Row.FindControl("btnItem");\n         btn.Attributes.Add("OnClick","SearchReqsult(this.id);");\n    } \n }	0
12576459	12576391	Replace int numbers with the corresponding months(strings) without using If-else	using System.Globalization;\n\nvar month = 7;\nvar dtf = CultureInfo.CurrentCulture.DateTimeFormat;\nstring monthName = dtf.GetMonthName(month);\nstring abbreviatedMonthName = dtf.GetAbbreviatedMonthName(month);	0
12733394	12733339	How can I reference a field of a subclass from the abstract superclass?	[TestFixture]\npublic class TravisSerialisationTest\n{\n    [Test]\n    public void GetPropertyValueTest()\n    {\n        var volvo = "Volvo";\n        var viewModel = new ViewModel() { Car = volvo };\n        var field = viewModel.GetField(() => viewModel.Car);\n        Assert.AreEqual(volvo,field);\n    }\n}\n\npublic class ViewModel : BaseClass\n{\n    public string Car { get; set; }\n}\n\npublic abstract class BaseClass\n{\n    public T GetField<T>(Expression<Func<T>> propertyExpression )\n    {\n        return propertyExpression.Compile().Invoke();\n    }\n}	0
30401203	30393231	Telerik WinUI GridView uses formating for wrong cell if scrolled	if (dataCell.ColumnInfo.Name.ToLower() == "unitprice")\n        {\n            dataCell.ForeColor = System.Drawing.Color.Blue;\n            dataCell.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0);\n        }\n\nelse\n{\ne.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local);\n}	0
7553819	7553747	Changing the Nhibernate entity to point to new table	Table("Counterparty")	0
17221116	17220816	Regex capture value within bracket, value contain brackets as well	\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*(?(DEPTH)(?!)))\)	0
1404	9	How do I calculate someone's age in C#?	DateTime today = DateTime.Today;\nint age = today.Year - bday.Year;\nif (bday > today.AddYears(-age)) age--;	0
3368570	3353173	ESENT database engine file access denied	m_Dictionary = new PersistentDictionary<string, PropertyStruct>(@"c:\Data\BaseEstateCachedPropertySummary2");	0
24134007	24133969	How to calculate the average value in 2 textboxes in C#?	((Convert.ToDouble(txtSt1.Text) + Convert.ToDouble(txtSt2.Text)) / 2).ToString();	0
30584605	30584470	Validate user's input	var state1 = string.IsNullOrWhiteSpace(textbox1.Text);\nvar state2 = string.IsNullOrWhiteSpace(textbox2.Text);\nvar state3 = string.IsNullOrWhiteSpace(textbox3.Text);\n\nif (!(state1 || state2 || state3))\n{\n    return "Please Enter a Search Parameter";\n}\nif (!(state1 ^ state2 ^ state3))\n{\n    return "Please only enter one Criteria";\n}\nif (state1)\n{\n    return "Something else";\n}\nif (state2)\n{\n    return "Something there";\n}\nreturn "Something here";	0
1862087	1862016	Dynamically setting value on array of pointers to integers	unsafe static void MyMethod(int** array)\n{\n    array[10] = (int*)0xdeadbeef;\n}\n\nprivate static unsafe void Main()\n{\n    int*[, , ,] array = new int*[10, 10, 10, 10];\n\n    fixed (int** ptr = array)\n    {\n        MyMethod(ptr);\n    }\n\n    int* x = array[0, 0, 1, 0]; // == 0xdeadbeef\n}	0
309119	309101	How do I get Gridview to render THEAD?	gv.HeaderRow.TableSection = TableRowSection.TableHeader;	0
5742474	5742318	How to set Header for DataGridview RowHeader?	grid.TopLeftHeaderCell.Value = "Text";	0
24267194	24267034	How to include a batch file command?	CreateNoWindow = true	0
16029962	15982013	Terminate Roslyn script early in C#	Execute(string)	0
10947528	10947399	How to implement and do OCR in a C# project?	using MODI;\nstatic void Main(string[] args)\n{\n    DocumentClass myDoc = new DocumentClass();\n    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension\n    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);\n\n    foreach (Image anImage in myDoc.Images)\n    {\n        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.\n    }\n}	0
7892075	7891903	SQL Server Database Connection String	Integrated Security=SSPI	0
21153670	20512623	How to deserialize json with class name as dynamic values	JToken token = JObject.Parse(response);\n        var justDaily = token["data"];\n        ProjectList = new List<Project>();\n        foreach (JToken child in justDaily.Children())\n        {\n            foreach (JToken grandChild in child)\n            {\n                Project temp = JsonConvert.DeserializeObject<Project>(grandChild.ToString().Replace("\r\n", ""));\n\n                    ProjectList.Add(temp);\n            }\n\n        }	0
19736133	19736067	Using inline object method call vs. declaring a new variable	new MyClass().nonStaticMethod();	0
13343373	13343324	Binding WPF datagrid to a List<List<object>>	List<SomeClass>	0
17910951	17910879	Reverse search a lists of lists	public class Tree\n{\n    private static Random rand = new Random();\n    public List<Tree> Children = new List<Tree>();\n\n    public Tree Parent;\n\n    public string Name;\n\n    public Tree(Tree parent)\n    {\n        Parent = parent;\n        Name = rand.Next(10000).ToString();\n    }\n\n    // Removing without tree traversal.\n    public void DeleteParent()\n    {\n        this.Parent.Parent.Children.Remove(this.Parent);\n    }\n\n    public bool Remove(string name)\n    {\n        for(int i = Children.Count - 1; i >= 0; i--)\n        {\n            if (Children[i].Remove(name))\n            {\n                // Use a for-loop with index to remove the child right away.\n                Children.Remove(Children[i]);\n                // Extra remove handling\n                i--;\n            }\n        }\n\n        // Remove condition.\n        return this.Name.Contains(name);\n    }\n}	0
1998515	1983966	Windows Mobile notification dialog	Microsoft.WindowsCE.Forms.Notification	0
27298119	27297861	How can i replace in console application image file format with the same file name but different format?	using System.Drawing.Imaging;\nusing System.IO;\nusing System.Drawing;\n\nnamespace ConvertImagesFormats\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string sourceDirectory = @"C:\test";\n            string targetDirectory = @"C:\test";\n            ImageFormat imageFormat = ImageFormat.Gif;\n\n            foreach(var image in Directory.GetFiles(sourceDirectory, "*.jpg"))\n            {\n                using (Bitmap bmp = new Bitmap(image))\n                {\n                    string targetName = Path.GetFileNameWithoutExtension(image) + "." + imageFormat;\n                    bmp.Save(Path.Combine(targetDirectory, targetName), imageFormat);\n                }\n            }\n        }\n    }\n}	0
15475254	15473471	EditText Input Format	EditText zipcode = FindViewById<EditText>(Resource.Id.zipcode);\nzipcode.InputType = Android.Text.InputTypes.ClassNumber;\nbool numberMode = true;\nzipcode.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {\n    if(zipcode.Text.Length == 4){\n        if(numberMode){\n            numberMode = false;\n            zipcode.Text = zipcode.Text + " ";\n            zipcode.SetSelection(zipcode.Text.Length);\n        }\n    }\n\n    if(zipcode.Text.Length > 4){\n        numberMode = false;\n        zipcode.InputType = Android.Text.InputTypes.ClassText;\n    }\n\n    if(zipcode.Text.Length <= 4){\n        numberMode = true;\n        zipcode.InputType = Android.Text.InputTypes.ClassNumber;\n    }\n};	0
5140726	5140674	How to make a HTTP PUT request?	using(var client = new System.Net.WebClient()) {\n    client.UploadData(address,"PUT",data);\n}	0
19449252	19449161	Receiving email and downloading attachment through a C# Application	var client = new POPClient();\nclient.Connect("pop.gmail.com", 995, true);\nclient.Authenticate("admin@bendytree.com", "YourPasswordHere");\nvar count = client.GetMessageCount();\nMessage message = client.GetMessage(count);\nConsole.WriteLine(message.Headers.Subject);	0
26256378	26232858	Force new lines in text, inserted in existing pdf using iTextSharp	PdfReader pdf = new PdfReader("Test1.pdf");\n        File.Delete("C:/Blocks.pdf");\n        PdfStamper stp = new PdfStamper(pdf, new FileStream("C:/Blocks.pdf", FileMode.OpenOrCreate));\n\n        var canvas = stp.GetOverContent(1);\n\n        PdfPTable table = new PdfPTable(1);\n        table.SetTotalWidth(new float[] { 100 });\n        Phrase phrase = new Phrase();\n        phrase.Hyphenation = new HyphenationAuto("ru", "RU", 2, 2);\n        var bf = BaseFont.CreateFont("c:/windows/fonts/arialbd.ttf", "Cp1251", BaseFont.EMBEDDED);\n        phrase.Add(new Chunk("? ???? ?? ??? ??????? ???????? ???? ???????? ? ??? ?? ??? ????????", new Font(bf, 12)));\n\n        PdfPCell cell = new PdfPCell(phrase);\n        cell.Border = Rectangle.NO_BORDER;\n        table.AddCell(cell);\n        table.WriteSelectedRows(0, 1, 200, 200, canvas);\n\n        stp.Close();	0
30753084	30753003	How to pass images through url?	public byte[] imageToByteArray(System.Drawing.Image imageIn)\n{\n    MemoryStream ms = new MemoryStream();\n    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);\n    return  ms.ToArray();\n}\n\npublic Image byteArrayToImage(byte[] byteArrayIn)\n{\n     MemoryStream ms = new MemoryStream(byteArrayIn);\n     Image returnImage = Image.FromStream(ms);\n     return returnImage;\n}	0
16899835	16899710	Making a object bounce	loop used to animate the ellipse\nbefore moving, check the position:\n\nif right-most position == right wall\n    invert x velocity\nif left-most position == left wall\n    invert x velocity\nif top-most position == top wall\n    invert y velocity\nif bottom-most position == bottom wall\n    invert y velocity\n\nmove ellipse to next position	0
5504536	5504241	Check compatibility of a method with a given Delegate?	Delegate.CreateDelegate(typeof(TargetDelegate), methodInfo, false) != null	0
16911901	16644392	SaveFileDialog disables webpart buttons in Sharepoint using C#	OnClientClick="window.setTimeout(function() { _spFormOnSubmitCalled = false; }, 10);"	0
26792581	26791643	Refresh page and open new new window	public partial class WebForm1 : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        btn.Text = "Refreshed";\n        if (Request.Params["btnPressed"] != null && Request.Params["btnPressed"] == "true")\n        {\n            ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('MyPage.aspx');", true);\n        }\n    }\n\n    protected void btn_Click(object sender, EventArgs e)\n    {\n\n        btn.Text = "Not Refreshed";\n        lbl.Text = "Not Refreshed";\n        System.Threading.Thread.Sleep(1000);\n        ////to refresh the page\n        Page.Response.Redirect(HttpContext.Current.Request.Url.ToString()+"?btnPressed=true", true);\n    }\n}	0
30383005	30382816	Dynamically add pictures to Windows forms application	picBox.Parent = this;\n\n picBox.BringToFront();	0
21437095	21436439	Showing Unable to create a constant value of type ''. Only primitive types ('such as Int32, String, and Guid') are supported in this context	var query = (\n     from emp in ctx.Employees\n     join resg in ctx.Resignations \n              on emp.EmployeeID equals resg.EmployeeID into resglist\n     from leftresg in resglist.DefaultIfEmpty()\n\n     //put the where clause on EmpJobPositions here\n     join jpos in ctx.EmpJobPositions.Where(x => empjList.Contains(x.EmpJobPositionId))\n              on emp.EmployeeID equals jpos.EmployeeId into jposList\n     from leftjpos in jposList.DefaultIfEmpty()\n         //don't understand this line, are you missing a where ?\n         //(leftresg == null || leftresg.HasLeft == false) && emp.CompanyID == 1\n     select new EmployeesViewModel()).ToList();	0
1681592	1674217	Getting NHibernate to generate a HiLo string ID	public class ManufacturerMap : ClassMap<Manufacturer>\n{\n    public ManufacturerMap()\n    {\n        Id(x => x.ID).GeneratedBy.Custom<StringTableHiLoGenerator>(a => a.AddParam("max_lo", Nexus3General.HiLoGeneratorMaxLoSize.ToString()));\n        Map(x => x.Name);\n    }\n}\n\npublic class StringTableHiLoGenerator : TableHiLoGenerator\n{\n    public override object Generate(ISessionImplementor session, object obj)\n    {\n        return base.Generate(session, obj).ToString();\n    }\n\n    public override void Configure(IType type, System.Collections.Generic.IDictionary<string, string> parms, NHibernate.Dialect.Dialect dialect)\n    {\n        base.Configure(NHibernateUtil.Int32, parms, dialect);\n    }\n}	0
6007264	6007234	How to display data result from database in C#	TextBox1.Text= A;	0
7839054	7837281	Checking restrictions on insert or submit of linq-to-sql items to db	OnValidate()	0
10503869	10503501	get matching text in dynamically changing tags	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\nvar links =doc.DocumentNode\n              .Descendants("a")\n              .Select(n => n.Attributes["href"].Value).ToArray();	0
5838552	5838528	Store a reference to a method	Action<string> L = MyDebug.Log;	0
5893805	5893787	How do I distinguish a file or a folder in a drag and drop event in c#?	FileAttributes attr = File.GetAttributes(path);\nbool isFolder = (attr & FileAttributes.Directory) == FileAttributes.Directory;	0
25537188	25377225	Send data to WCF from Android using KSOAP2	[CollectionDataContract(Name = "Custom{0}List", ItemName = "CustomItem")]\npublic class Items : List<clsitems>\n{\n}	0
4844421	4844222	Busy cursor when mouse over scroll bar in ScrollableControl	using System;\nusing System.Windows.Forms;\n\nclass MyPanel : Panel {\n    protected override void WndProc(ref Message m) {\n        if (m.Msg == 0x20) {  // Trap WM_SETCURSOR\n            Cursor.Current = Cursors.Default;\n            m.Result = (IntPtr)1;\n        }\n        else base.WndProc(ref m);\n    }\n}	0
2902771	2898925	Casting an object to two interfaces at the same time, to call a generic method	interface IC : IA, IB { }\n\nvoid bar(object obj)\n{\n  if (obj is IA && obj is IB)\n  {\n    IC x = (dynamic)obj;\n    foo(x);\n  }\n}	0
3934152	3934097	get control by clientID	public static System.Web.UI.Control FindControlIterative(System.Web.UI.Control root, string id)\n    {\n        System.Web.UI.Control ctl = root;\n        var ctls = new LinkedList<System.Web.UI.Control>();\n\n        while (ctl != null)\n        {\n            if (ctl.ID == id)\n                return ctl;\n            foreach (System.Web.UI.Control child in ctl.Controls)\n            {\n                if (child.ID == id)\n                    return child;\n                if (child.HasControls())\n                    ctls.AddLast(child);\n            }\n            if (ctls.First != null)\n            {\n                ctl = ctls.First.Value;\n                ctls.Remove(ctl);\n            }\n            else return null;\n        }\n        return null;\n    }	0
20219220	20219163	Removing column in a list<T> in linq	var newList = myList.Select(l => new {\n     l.SeriesNumber , l.RiskRegisterType\n    }).ToList();	0
5701555	5701482	How to pass parameter to sql 'in' statement?	string[] numbers = new string[] { "123", "234" };\n\nNpgsqlCommands cmd = new NpgsqlCommands("select * from products where number = ANY(:numbers)");\nNpgsqlParameter p = new NpgsqlParameter("numbers", NpgsqlDbType.Array | NpgsqlDbType.Text);\np.value = numbers;\ncommand.Parameters.Add(p);	0
4024964	4024922	Setting port in FtpWebRequest	FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://10.0.0.1:12345");	0
26583892	26578050	Making a rotating object rotate with a parent object	ChildWorldTransform = ChildLocalTransform * ParentWorldTransform	0
8594325	8594161	Prevent repeated DB calls because of object oriented approach in MVC3 app	[Caching(300)]\nComment GetComment(int commentId);	0
20142638	20142488	How to append data into a excel sheet column?	int _lastRow = xlWorkSheet.Cells.Find(\n                              "*",\n                              xlWorkSheet.Cells[1,1],\n                              Excel.XlFindLookIn.xlFormulas,\n                              Excel.XlLookAt.xlPart,\n                              Excel.XlSearchOrder.xlByRows,\n                              Excel.XlSearchDirection.xlPrevious,\n                              misValue,\n                              misValue,\n                              misValue\n                              ).Row + 1;	0
6210337	6210282	how to make json web service in asp.net?	[WebMethod(Description = "Your Description")]\n    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n    public string FunctionName()\n    {           \n        // Return JSON data\n        JavaScriptSerializer js = new JavaScriptSerializer();\n        string retJSON = js.Serialize(Object);\n        return retJSON;\n\n    }	0
22043179	22043061	how to use retrieve and use setting value to connect to adatabase	SqlConnection conn = new SqlConnection("Data Source=" + serv.ToString() + ";Initial Catalog=" + db.ToString() + ";User ID=" + userid.ToString() + ";password= " + pass.ToString());	0
9568010	9567804	C# Key Press; display key in Label	...\nmyForm.KeyPreview = true;\n...\n\nprivate void CommsTesterUI_KeyDown(object sender, KeyEventArgs e)\n{\n    label1.Text = e.KeyCode.ToString();\n}	0
17744851	17744638	Stopwatch for performance testing	Stopwatch watch = Stopwatch.StartNew();\n  ...\n  // Estimated code here \n  ...\n  watch.Stop();\n\n  // Microseconds\n  int microSeconds = (int)(watch.ElapsedTicks * 1.0e6 / Stopwatch.Frequency + 0.4999);\n  // Nanoseconds (estimation)\n  int nanoSeconds = (int)(watch.ElapsedTicks * 1.0e9 / Stopwatch.Frequency + 0.4999);	0
21724497	21724390	XDocument Add multiple XElements	document = new XDocument(new XElement("root", elem1, elem2));	0
478974	478968	Sum of digits in C#	sum = 0;\nwhile (n != 0) {\n    sum += n % 10;\n    n /= 10;\n}	0
12285086	12284841	Reading Dll parameters	.text:77D6EA11\n.text:77D6EA11 ; int __stdcall MessageBoxA(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType)\n.text:77D6EA11	0
5644746	5641839	Programmatically add an application to all profile Windows Firewall (Vista+)	using System;\nusing NetFwTypeLib;\n\nnamespace FirewallManager\n\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));\n        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;\n        firewallRule.Description = "Allow notepad";\n        firewallRule.ApplicationName = @"C:\Windows\notepad.exe";\n        firewallRule.Enabled = true;\n        firewallRule.InterfaceTypes = "All";\n        firewallRule.Name = "Notepad";\n\n        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(\n            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));\n        firewallPolicy.Rules.Add(firewallRule);\n\n    }\n  }\n}	0
7451726	7451681	how to find out the path of the program using c#	System.IO.File.Exists("path_to_program.exe");	0
21304113	21304016	IoException while writing in text file in c#	File.Create(textfilename).Close();	0
31672047	31671846	converting array of string to json object in C#	namespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string[] request = new String[2];\n            request[0] = "Name";\n            request[1] = "Occupaonti";\n            string json = JsonConvert.SerializeObject(request);\n        }\n    }\n}	0
1368158	1368126	Xml Serialization Problem for 60mb file	using(var file = new FileStream(...))\nusing(var streamWriter = new StreamWriter(file))\n{\n    xmlWriter.Serialize(streamWriter, obj);\n}	0
1340019	1339902	Setting a timeout in a .net desktop application	static void Main(string[] args)\n{\n    Mutex flag = new Mutex(false, "UNIQUE_NAME");\n    bool acquired = flag.WaitOne(TimeSpan.FromMilliseconds(0));  // 0 or more milliseconds\n    if (acquired)\n    {\n        Console.WriteLine("Ok, this is the only instance allowed to run.");\n\n        // do your work, here simulated with a Sleep call\n        Thread.Sleep(TimeSpan.FromSeconds(5));\n\n        flag.ReleaseMutex();\n        Console.WriteLine("Done!");\n    }\n    else\n    {\n        Console.WriteLine("Another instance is running.");\n    }\n    Console.WriteLine("Press RETURN to close...");\n    Console.ReadLine();\n}	0
33923430	33923115	Using C# to check if string contains a string in string array and how to connect it	do\n{\n  Console.Write("PLease enter the year (not earlier than 1812) as 4 digits  >> ");\n\n} while (!int.TryParse(Console.ReadLine(), out y) || y < 1812);\n\n\ndo\n{\n  Console.Write("Please enter the month as a three letter character ( e.g 'Jul'>> ");\n}   while (!isCorrectMonth(Console.ReadLine()) );       \n\n\n\n\n\nstatic bool isCorrectMonth(string monthToCheck)\n{\n  string stringToCheck = monthToCheck.ToLower();\n  string[] stringArray = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" };\n  foreach (string x in stringArray)\n  {\n    if (x.Contains(stringToCheck))\n    {\n        // Process..\n        return true;\n    }\n    else\n    {\n        return false;\n    }\n  }\n  return false;\n}	0
24905380	24904837	How can I convert data held as 01010 bits into fields in a class object?	public List<AnswerRow> makeAnswers(string c, string r)\n{\n   var result = new List<AnswerRow>();\n   for(var i=0; i<r.Length; i++)\n   {\n       result.Add(\n        new AnswerRow { \n                 Correct = c!=null?new Nullable<bool>(c[i]=='1'):null,\n                 Response = r[i]=='1'\n        });\n   }\n   return result;\n}	0
28595832	28571860	Issues with INavigationAware in Prism 5	public class ModuleAViewModel : BindableBase, IConfirmNavigationRequest, INavigationAware, IRegionMemberLifetime\n{\n ...\n        bool IRegionMemberLifetime.KeepAlive\n    {\n        get { return false; }\n    }\n}	0
6784179	6783888	Suggestions to Ensure Encapsulation	[assembly: InternalsVisibleTo("AssemblyName")]	0
13873400	13873372	Remove table from <div> tag	function removeElement(el) {\n    el.parentNode.removeChild(el);\n}	0
27418542	27416115	How do I give an attributes to array list item during serialization in c#	public querySeat_Main querySeat([XmlAttribute] string signature, string operator_code, string route_id, string trip_no, string depart_date, string counter_from, string counter_to, string bus_type)\n{\n    querySeat_Main main = new querySeat_Main();\n    querySeat_status status = new querySeat_status();\n    querySeat_status.detail detail = new querySeat_status.detail();\n    detail.available = "no";\n    detail.seat_no = "7";\n    status.code = 0;\n    status.details = new List<querySeat_status.detail>();\n    status.details.Add(detail);\n    status.msg = "success";\n    main.querySeat_status = status;\n    return main;\n}	0
15004259	15001583	See what a Cookie Container contains?	if(Request.Cookies["key"]!=null)\n{\n   var value=Request.Cookies["key"].Value;\n}	0
8056355	8056323	ASP.net, adding objects to a session variable	Supply sup =  Supplies.GetSupply(supplyItemID); \nvar cartObjects =  (Session["CartObjects"] as List<Supply>) ?? new List<Supply>();\ncartObjects.Add(sup);\nSession["CartObjects"] = cartObjects;	0
11687681	11687633	Click event for button in loop C# WPF	bnt.Click += (source, e) =>\n{\n    //type the method's code here, using bnt to reference the button \n};	0
28352019	28331244	keep getting A second operation started on this context before a previous asynchronous operation completed	_unitOfWork = _UnitOfWorkFactory.createUnitOfWorkAsync();\n\n        IEnumerable<Relatie> relaties = await getRelatieAsync(_unitOfWork, relatieId).ConfigureAwait(true);\n\n        _relatieTypeTypes = await getRelatieTypeTypesAsync(_unitOfWork, relatieId).ConfigureAwait(true);\n        _relatie = relaties.FirstOrDefault();\n\n        _unitOfWork.Dispose();	0
12452124	12445217	create cookie in web method	context.Response.Cookies.Add(cook);	0
28281664	28281229	Use a generic method with a list of different type/class	public static IList<T> SearchGridView<T>(IList<T> list, String term) \n{\n    IList<PropertyInfo> properties = typeof(T).GetProperties();\n    var t = term.ToLower();\n    return list\n        .Where(item =>\n            properties\n                .Select(p => p.GetValue(item).ToString())\n                .Any(v => v.Contains(t)))\n        .ToList();\n}	0
8409532	8409499	returning c string to a C# program	void function (const char* str, char* output, size_t outputLength)	0
16666514	16666430	TRIGGER show two row affected T-SQL	CREATE TRIGGER examplex on MyTABLE1 INSTEAD OF INSERT\nAS\nINSERT    MyTABLE1 (USERNAME, USERDATE, NAME, SURNAME)\nSELECT\n    'sysUser1212'\n    , '2004-09-02 00:00:00.000'\n    , NAME\n    , SURNAME\nFROM inserted   \n\n\n-- The following disapear\n/*\nCREATE TRIGGER example on MyTABLE1 AFTER INSERT\nAS\nUPDATE    MyTABLE1\nSET       USERNAME = 'sysUser1212' and USERDATE = '2004-09-02 00:00:00.000'\n--*/	0
1821884	1821835	how to get RSS or ATOM feed url from blogurl	XmlReader reader = XmlReader.Create(feedUriString);\nSyndicationFeed feed = SyndicationFeed.Load(reader);\nforeach (SyndicationItem item in feed.Items)\n{\n//your code for rendering each item\n}	0
18839204	18839056	Storing DataGrid in List	public void ReadDataGridView(int ProcessId)\n{\n    ProgramToWatchDataGrid updateGrid = null;\n\n    //read and store every row\n    int i=0;\n    while(i<=totalRowsInGrid)\n    {\n        //create a new instance\n        updateGrid = new ProgramToWatchDataGrid();\n        updateGrid.ListId = DataGrid.Rows[i].Cells[0].Value;\n        updateGrid.Name = DataGrid.Rows[i].Cells[1].Value;\n        updateGrid.Mail = DataGrid.Rows[i].Cells[2].Value;\n\n        ProgramToWatchDictionary[ProcessID].BEDataGrid.Insert(i, updateGrid);\n        Display(ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);\n    }\n\n    Display("Elements: " + ProgramToWatchDictionary[ProcessID].BeDataGrid.Count);\n\n    //display every rows mail\n    i=0;\n    while(i<=totalRowsInGrid)\n    {\n        Display("HI: " + ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);\n        i++;\n    }\n}	0
10096308	10095740	Missing a step in setting up my database Visual Studio 2010	DataContext db = new DataContext(@"C:\Temp\Test.mdf");\nTable<Table1> myTable = db.GetTable<Table1>();	0
5426051	5425972	C# Control Parent	public Form1() {\n        InitializeComponent();\n        pictureBox1.Left = tabControl1.Left + 15;\n    }	0
7801633	7801551	How do I use Clutter in conjunction with C#?	using System;\nusing Clutter;\n\nnamespace HelloWorld {\n    public class HelloWorld {\n        public int Main () {            \n\n            // Init declaration produces error: \n            // Expression denotes a 'type', where a 'method group' was expected\n            Clutter c = new Clutter();\n            c.Init();\n\n            Stage stage = Stage.Default;\n            stage.Color = new Clutter.Color (0, 0, 0, 255);\n            stage.SetSize (512, 512);\n\n            stage.Show();\n\n            // Main declaration produces error: \n            // Expression denotes a 'type', where a 'method group' was expected\n            c.Main();\n\n            return 0;\n        }\n    }\n}	0
10723238	10723136	Showing variable text in MVC View	Message1_TypeA\nMessage2_TypeB	0
10984812	10984737	C# Declaring Multiple Instances of the Same Table	var data = CreateDataSource();\n\nfor(x = 1; x < 28; x++)\n{\n    DropDownList dl = new DropDownList();\n    dl.ID = "TrendList" + x.ToString();\n    dl.AutoPostBack = true;\n    dl.SelectedIndexChanged += new EventHandler(this.Selection_Change);\n    dl.DataSource = data;\n    dl.DataTextField = "ColorTextField";\n    dl.DataValueField = "ColorValueField";\n    dl.DataBind();\n    // add it to the cell here too\n}	0
2467369	2050161	Validating DataAnnotations with Validator class	TypeDescriptor.AddProviderTransparent(\n            new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Persona), typeof(Persona_Validation)), typeof(Persona));\n\nValidationContext context = new ValidationContext(p, null, null);\nList<ValidationResult> results = new List<ValidationResult>();\n\nbool valid = Validator.TryValidateObject(p, context, results, true);	0
18472777	18472741	Accessing a ManyToMany associated table	myUser.Roles.Add(someRole);	0
32258542	32257852	How to convert a signed decimal into a HEX 24-bits twos-complement signed number	WriteBytes(decimal value, Stream stream)\n{\n    Int32 intValue = (int)(value * 32768);\n    byte byte1 = (byte)(intValue & 255);\n    intValue >>=8;\n    byte byte2 = (byte)(intValue & 255);\n    intValue >>=8;\n    byte byte3 = (byte)(intValue & 255);\n    stream.Write(byte3);\n    stream.Write(byte2);\n    stream.Write(byte1);\n}	0
23427900	23427377	Can't get data from related table	var pizzas = db.Pizzas.Include("PizzaToppings");\nvar pizza = pizzas.Where()... // select your specific pizza	0
13175641	13174819	wpf sharepoint 2010 file picker	Dim dialog As New Microsoft.Win32.OpenFileDialog\nDim result = dialog.ShowDialog	0
33013212	33012115	How do I change DataBinding index possition programmatically	BindingContext[myList].Position = myList.FindIndex(person => person.name.StartsWith("MyName2"));	0
6103187	6103172	How to use the type 'Type'	Type t = someClassInstance.GetType();\nobject o = Activator.CreateInstance(t);	0
12572432	12572352	Converting 32 bit bmp to 24 bit	public static Bitmap ConvertTo24bpp(Image img) {\n  var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);\n  using (var gr = Graphics.FromImage(bmp))\n    gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));\n  return bmp;\n}	0
16683741	16668470	changing the forecolor in array of dynamically created combobox based on item in c#.net	public partial class Form1 : Form\n{\n    ComboBox[] cb = new ComboBox[28];\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n\n   for (int ii = 0; ii < 28; ii++)\n   {\n\n\n            cb[ii] = new ComboBox();\n            cb[ii].Items.Add("OK");\n            cb[ii].Items.Add("NOT OK");\n\n            cb[ii].SelectedIndex = 0; \n            cb[ii].ForeColor = Color.Black;  \n            cb[ii].SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged);\n\n   }\n}\n\nprivate void comboBox_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        ComboBox cbx = sender as ComboBox;\n        if (cbx.Text == "OK")\n        {\n            cbx.ForeColor = Color.Black;\n        }\n        else\n        {\n            cbx.ForeColor = Color.Red;\n        }\n    }\n\n}	0
6799681	6799631	Removing control characters from a UTF-8 string	public static string RemoveControlCharacters(string inString)\n{\n    if (inString == null) return null;\n    StringBuilder newString = new StringBuilder();\n    char ch;\n    for (int i = 0; i < inString.Length; i++)\n    {\n        ch = inString[i];\n        if (!char.IsControl(ch))\n        {\n            newString.Append(ch);\n        }\n    }\n    return newString.ToString();\n}	0
16926695	16926459	Combining data using Linq	var query = from i1 in items\n            join i2 in items2 on i1.seq equals i2.seq\n            join i3 in items3 on i1.seq equals i3.seq\n            select new { i1, i2, i3 };\n\nforeach(var x in query)\n{\n    double first = Convert.ToDouble(x.i1.GOIL);\n    ....	0
639579	639533	How do I close a popup window on a press of a button and initiate postback on the window opening the popup?	ClientScript.RegisterStartupScript(typeof(string), "auto_refreshparent", @" window.opener.location.reload(); ", true);\nClientScript.RegisterStartupScript(typeof(Page), "ThatsAllFolks", "window.close();", true);	0
22443008	22442530	Cannot get Values from Gridview	for (int i = 0; i < FolderGridView.Rows.Count; i++){\n    CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");\n    if (chk.Checked == true){\n       foreach (Control ctl in FolderGridView.Rows(i).Cells(1).Controls) {\n           if (ctl is LinkButton) {\n           string filename = ((LinkButton)ctl).Text;\n           }\n    }\n}	0
15560473	15560445	Interface method marked as Obsolete does not issue a message from the compiler when implemented	public interface IAnimal\n    {\n        [Obsolete("Animals can't eat anymore", true)]\n        void Eat();\n    }\n\n    public class Animal : IAnimal\n    {\n        [Obsolete("Animals can't eat anymore", true)]\n        public void Eat()\n        {\n            Console.WriteLine("Hello");\n        }\n    }	0
25426353	25425325	How do I do a table join using LINQ and entity framework 6?	var info = from p in db.Exam \n           join q in db.objective on p.objectiveid equals q.id\n           join r in db.objectivedetails on q.objectivedeailsId equals r.id\n           select new\n                       {\n                           ExamId  = p.ExamId \n                           SubjectId= p.SubjectId\n                           ObjectiveId= q.ObjectiveId\n                           Number = q.Number\n                           ObjectiveDetailId = r.ObjectiveDetailId\n                           Text = r.Text\n                       } into x\n           select x;	0
15793185	15792979	How to apply Control resource on a Control using code	public class MyTabItem : TabItem\n{\n   public MyTabItem()\n   {\n      Loaded += MyLoadedExtras;\n   }\n\n   private void MyLoadedExtras( object sender, EventArgs e )\n   {\n      object basis = TryFindResource("XKeyValueFromYourTabItemStyle");\n      if (basis != null)\n         Style = (Style)basis;\n\n      // disconnect from loaded event after our one time in\n      Loaded -= MyLoadedExtras;\n   }\n}	0
30335221	30335016	Accessing Folder In Group Account C# Outlook	Sub ResolveName() \n Dim myNamespace As Outlook.NameSpace \n Dim myRecipient As Outlook.Recipient \n Dim CalendarFolder As Outlook.Folder \n Set myNamespace = Application.GetNamespace("MAPI") \n Set myRecipient = myNamespace.CreateRecipient("mm@abc.com") \n myRecipient.Resolve \n If myRecipient.Resolved Then \n   Call ShowCalendar(myNamespace, myRecipient) \n End If \nEnd Sub \n\nSub ShowCalendar(myNamespace, myRecipient) \n Dim CalendarFolder As Outlook.Folder \n Set CalendarFolder = _ \n myNamespace.GetSharedDefaultFolder _ \n (myRecipient, olFolderCalendar) \n CalendarFolder.Display \nEnd Sub	0
12052153	12052065	Writing access to private objects via public readOnly property	secondClassObject.FirstClassObject.membVar1 = 42	0
998497	998448	how to set image type column to null in sql server using parameters in c#	SqlParameter myParam = new SqlParameter("@NameOfParameter",SqlDbType.Image);	0
17496683	17496658	String to Hex stored in an int	Convert.ToInt32("4E4DBC", 16);	0
8357646	8357106	StackOverFlowException in WPF when call method from C++ library	bool ok = MSR_InitComm("COM1", 9600);\ntry {\n    throw new Exception("Fpu reset intended");\n}\ncatch (Exception) {\n}	0
32380818	32380475	how to send email with attachment from server path in asp.net c#	foreach (FileInfo file in dir.GetFiles("*.*"))\n{\n   if (file.Exists) \n   {\n      mailMessage.Attachments.Add(new Attachment(file.FullName));\n   }\n}	0
12190359	12181483	How to add connection string for a windows form applicaton in C#	AppDomain.CurrentDomain.SetData(?DataDirectory?,?c:\anypath?);\n\nSqlConnection c = new SqlConnection (?Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Initial Catalog=Master");	0
33929625	33929342	C# - Regex - separate N words	String Input = "Please write down my phone: 999999 - Vinicius Lacerda Andrioni and I have 90 years old.";\n\nString[] Results = Input.Split(new String[] {": ", "- ", " and" }, StringSplitOptions.None);\n\n// of course you'll want to add error checking....\nMessageBox.Show(Results[1]);\nMessageBox.Show(Results[2]);	0
4147039	4146989	How to elegantly access thread-safe collection and use AutoResetEvent	int value = 0;\n\nwhile (true)\n{\n    lock (m_Locker)\n    {\n        if (m_Queue.Count > 0)\n        {\n            value = m_Queue.Dequeue();\n            break;\n        }\n    }\n\n    m_AutoResetEvent.WaitOne();\n}	0
15551499	15551246	Get control from specific position supporting WinForms interop	public Rect HostRect\n    {\n        get\n        {\n            var transform = _Host.TransformToVisual(this);\n            return new Rect(transform.Transform(new Point(0, 0)), new Point(_Host.ActualWidth, _Host.ActualHeight));\n        }\n    }	0
22180018	22179996	Method Array Sum	static void TotalOfEvenNegatives(int[] array)\n{\n    int sum = 0;\n    for (int i = 0; i < array.Length; i++)\n    {\n        if (array[i] % 2 == 0 && array[i] < 0)\n        {\n\n            sum += array[i];\n        }\n    }\n}	0
15752301	15744178	Fill of a Rectangle with SolidColorBrush does not work	Color red = new Color() { R = 255, G = 39, B = 0, A = 255 };	0
3209418	3209393	Calling sqlCommand in a loop increasing exec time every step	System.Data.SqlClient.SqlBulkCopy	0
16536959	16536921	Assign TextBox Text into variables	string firstVal = textbox1.Text;\nstring secondVal = textbox2.Text;	0
20110044	20088567	How do I create a ComplexSignal object from a Signal object in Accord.NET?	string fileName = "mu1.wav";\n        WaveDecoder sourceDecoder = new WaveDecoder(fileName);\n        Signal sourceSignal = sourceDecoder.Decode();\n\n        //Create Hamming window so that signal will fit into power of 2:           \n        RaisedCosineWindow window = RaisedCosineWindow.Hamming(1024);\n\n        // Splits the source signal by walking each 512 samples, then creating \n        // a 1024 sample window. Note that this will result in overlapped windows.\n        Signal[] windows = sourceSignal.Split(window, 512);\n\n        // You might need to import Accord.Math in order to call this:\n        ComplexSignal[] complex = windows.Apply(ComplexSignal.FromSignal);\n\n        // Forward to the Fourier domain\n        complex.ForwardFourierTransform(); //Complete!\n\n        //Recommend building a histogram to see the results	0
20542704	20542617	Change datasource on button click in Winforms app	private void viewHire_Click(object sender, EventArgs e)\n    {\n        dataGridView1.DataSource = hireBindingSource;\n    }	0
3863357	3856291	How to create a hash code in C# on object graph supplied by a WCF service	private static byte[] CalculateHashCode(SomeComplexTypeDefinedAsDataContract objectGraph)\n    {\n        using (RIPEMD160 crypto = new RIPEMD160Managed())\n        {\n            using (MemoryStream memStream = new MemoryStream())\n            {\n                DataContractSerializer x = new DataContractSerializer(typeof(SomeComplexTypeDefinedAsDataContract ));\n                x.WriteObject(memStream, objectGraph);\n                memStream.Position = 0;\n                return crypto.ComputeHash(memStream);\n            }\n        }\n    }	0
13844704	13795449	Why does Data service not return values to application, but returns it to browser? How to fix it?	WebClient wc = new WebClient();\nwc.UseDefaultCredentials = true;\n\nXDocument xdoc = XDocument.Parse(wc.DownloadString(new Uri(request)));\nvar res = xdoc.Root.Descendants( ((XNamespace)@"http://schemas.microsoft.com/ado/2007/08/dataservices") + \n                                            "element");\n\npreresult = res.Select(xe => xe.Value).ToList();	0
14192555	12300154	Unable to render excel download from aspx page	Response.Headers.Set("Cache-Control", "private, max-age=0");	0
16676575	16671689	Get source property type from BindingExpression	string[] splits = expr.ParentBinding.Path.Path.Split('.');\nType type = expr.DataItem.GetType();\nforeach (string split in splits) {\n    type = type.GetProperty(split).PropertyType;\n}	0
28636973	28403073	how to set client name in libtorrent	settings.user_agent = "My Own Client/" LIBTORRENT_VERSION;	0
4363184	4362111	How do I show a console output/window in a forms application?	using System.Runtime.InteropServices;\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    AllocConsole();\n}\n\n[DllImport("kernel32.dll", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool AllocConsole();	0
22809667	10647016	Windows phone: how get current application id	var appId = Windows.ApplicationModel.Store.CurrentApp.AppId;	0
7531655	7531614	Use of Response.End in an MVC3 Action	return new HttpUnauthorizedResult();	0
20741499	20741420	Insert date into database winforms	conn.Open();\n    cmd.CommandText = "INSERT INTO Boek (ItemID, DVU, AuteurID, BoekGenreID,\n    BindwijzeID, TaalID, ISBN10, ISBN13, AantalPagina) \n    VALUES (@itemID, @dvu, @auteur, @genre, @bindwijze, \n    @taal, @isbn10, @isbn13, @paginas);";\n    cmd.ExecuteNonQuery();\n    conn.Close();	0
8945189	8945050	RoutedPropertyChangedEventHandler on custom UserControl - XamlParseException	ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", ..., typeof(RoutedPropertyChangedEventHandler<double>), typeof(NumericUpDown));	0
5357847	5357797	C# - Running / Executing "Excel to CSV File Converter" Console App from C# WinForm App	Process covertFilesProcess = new Process();\n\ncovertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";\ncovertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";\ncovertFilesProcess.StartInfo.Arguments = "^ " + targetFolderBrowserDialog.SelectedPath + "^" + sourceFileOpenFileDialog.FileName + ".csv";\ncovertFilesProcess.StartInfo.UseShellExecute = true;\ncovertFilesProcess.StartInfo.CreateNoWindow = true;\ncovertFilesProcess.StartInfo.RedirectStandardOutput = true;\ncovertFilesProcess.StartInfo.RedirectStandardError = true;\ncovertFilesProcess.Start();\n\nStreamReader sOut = covertFilesProcess.StandardOutput;\nStreamReader sErr = covertFilesProcess.StandardError;	0
13936013	13935868	Finding something specific from HTML	var str1 = "<br /><br />\n\n<p><font size=\"4\" face=\"Courier New\"> TSX Symbol Changes -December 17th - December 21st</font><br>";\n    var str2 = str1.Substring(str1.IndexOf("TSX Symbol Changes")).Replace("</font><br>","");	0
21850263	21849791	Update TextBox in a page displayed inside a frame from a ribbon	((Page1)frame1.Content).TextBox1.Text = "Hello, World";	0
18133054	18133022	How to check repeated letters in a string c#	repeatedWord.Count()-1	0
31219630	31219578	Linq statement to select strings containing all of the letters	string test1 = "sdfasdosdfe";\nstring test2 = "sdfasdasodfeasdfasd";\nstring test3 = "sdfsdfsdfsdfds";\nstring searchString = "aeo";\n\nList<string> wordList = new List<string>() { test1, test2, test3 };\nIEnumerable<string> resultList = \n     wordList.Where(q => searchString.ToCharArray().All(p => q.Contains(p)));	0
9394883	9394842	Json Deserialization to a class	using System.Collections.Generic;\nusing System;\nusing Newtonsoft.Json;\n\nnamespace ConsoleApplication1\n{\n   class Program\n   {\n          static void Main(string[] args)\n          {\n              string json = "[{\"_34\":{ \"Id\":\"34\", \"Z\":[\"42b23718-bbb8-416e-9241-538ff54c28c9\",\"c25ef97a-89a5-4ed7-89c7-9c6a17c2413b\"], \"C\":[] } }]";\n              var result = JsonConvert.DeserializeObject<Dictionary<string, Result>[]>(json);\n              Console.WriteLine(result[0]["_34"].Z[1]);\n           }\n   }\n\n   public class Result\n   {\n        public string Id { get; set; }\n        public string[] Z { get; set; }\n        public string[] C { get; set; }\n   }\n}	0
27979747	27858132	How to 'sneak' interface behind 3rd party objects	interface IFooBar\n{\n    string A { get; set; }\n    string B { get; set; }\n}\n\nclass FooAdapter : IFooBar\n{\n    private readonly Foo _foo;\n\n    public FooAdapter(Foo foo)\n    {\n        _foo = foo;\n    }\n\n    public string A\n    {\n        get { return _foo.A; }\n        set { _foo.A = value; }\n    }\n\n    public string B\n    {\n        get { return _foo.B; }\n        set { _foo.B = value; }\n    }\n}\n\n\nclass BarAdapter : IFooBar\n{\n    private readonly Bar _bar;\n\n    public BarAdapter(Bar bar)\n    {\n        _bar = bar;\n    }\n\n    public string A\n    {\n        get { return _bar.A; }\n        set { _bar.A = value; }\n    }\n\n    public string B\n    {\n        get { return _bar.B; }\n        set { _bar.B = value; }\n    }\n}	0
2696877	2696858	Get textboxes in to a list! c#	public class ListAcc \n{\n            private static List<Account> UserList;\n            public static List<Account> Data() \n            { \n                 return UserList;\n            } \n        }\nprivate void textBox1_TextChanged(object sender, EventArgs e) \n    { \n            UserList = new List<Account>(); \n            //example of adding user account \n            Account acc = new Account(); \n            acc.Username = textBox1.Text; \n            UserList.Add(acc); \n    }	0
3346354	3336148	How do I look up a SiteMapNode by its URL (or other key)?	var node = SiteMap.Provider.FindSiteMapNodeFromKey(key);	0
29209464	29170856	Service Bus Queue how to map Task<BrokeredMessage> to Task<MyClass>	public async Task<IQueueMessage> ReceiveAsycn(TimeSpan serverWaitTime)\n        {\n            var task = QueueClient\n                                      .ReceiveAsync(serverWaitTime)\n                                      .ContinueWith(bm => bm.Result==null ? null : new QueueMessage { Message=bm.Result});\n            return await task;\n        }	0
24422250	24419923	argumentnullexception was unhandled insert into	cmd.Parameters.Add(new SqlCeParameter("@item", Convert.ToString(dataGridView1.Rows[i].Cells[0].Value)));	0
824854	824802	C#: How to get all public (both get and set) string properties of a type	public static void ReplaceEmptyStrings<T>(List<T> list, string replacement)\n{\n    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n    foreach (PropertyInfo p in properties)\n    {\n        // Only work with strings\n        if (p.PropertyType != typeof(string)) { continue; }\n\n        // If not writable then cannot null it; if not readable then cannot check it's value\n        if (!p.CanWrite || !p.CanRead) { continue; }\n\n        MethodInfo mget = p.GetGetMethod(false);\n        MethodInfo mset = p.GetSetMethod(false);\n\n        // Get and set methods have to be public\n        if (mget == null) { continue; }\n        if (mset == null) { continue; }\n\n        foreach (T item in list)\n        {\n            if (string.IsNullOrEmpty((string)p.GetValue(item, null)))\n            {\n                p.SetValue(item, replacement, null);\n            }\n        }\n    }\n}	0
18383959	18383892	Most elegant way to check to see if a NameValueCollection has value	lead.InternalCompany = nvCollection["ic"] ?? string.Empty;	0
3935519	3919978	Larger File Sizes are being incorrectly transfered with a NetworkStream	private string ReadandSaveFileFromServer(TcpClient clientATF, NetworkStream currentStream, string locationToSave)\n    {\n        int fileSize = 0;\n        string fileName = "";\n        int bytesRead = 0;\n\n        fileName = ReadStringFromServer(clientATF, currentStream);\n        fileSize = ReadIntFromServer(clientATF, currentStream);\n\n        FileStream fs = new FileStream(locationToSave + "\\" + fileName, FileMode.Create);\n\n        byte[] fileSent = new byte[fileSize];\n\n        while (fs.Length != fileSize)\n        {\n\n                bytesRead = currentStream.Read(fileSent, 0, fileSent.Length);\n                fs.Write(fileSent, 0, bytesRead);\n\n        }\n\n        fs.Flush();\n        fs.Close();\n\n        return fileName;\n    }	0
24847902	24837344	Get Data from DatagridView from to Object Array then populate ComboBox	public class Departmentinfo\n{\n    public string departmentname;\n\n    private void Departmentinfo(string s)\n    {\n        this.departmentname = s;\n    }\n}\n\nList<Departmentinfo> DepInfo = new List<Departmentinfo>();\n\nprivate void getdepartments()\n{\n    for (int i = 0; i < dataGridView1.RowCount; i++)\n        {\n            DepInfo.Add(new Departmentinfo(Convert.ToString(dataGridView1.Rows[i].Cells[0].Value)));\n        }\n}\n\nprivate void putdepartments()\n{\n    foreach (Departmentinfo dep in DepInfo)\n    {\n        comboBox4.Items.Add(dep.departmentname);\n    }\n}	0
10609731	10608978	How do I stop ValueInjecter from mapping null values?	protected override bool Match(ConventionInfo c){\n    //Use ConventionInfo parameter to access the source property value\n    //For instance, return true if the property value is not null.\n}	0
1017082	1017030	Verify integrity Ceritifcate { RSACryptoServiceProvider - SHA1 - thumbprint }	X509Certificate2 x2 = new X509Certificate2(certificatEnCours);\nbool verif = x2.Verify();	0
5832732	5829821	Save string array and float array from c# to Excel file	using(TextWriter tw = new StreamWriter("sample.csv") {\n  // Header  \n  tw.WriteLine("X,Y");\n\n  foreach(var item in Data) {\n    tw.WriteLine(item.X.ToString(InvariantCulture) + "," + item.Y.ToString(InvariantCulture));\n  }  \n}	0
4178603	4178570	How do create a class property that is a collection of another class?	public class Client\n{\n    public int Id {get;set;}\n    // Client Properties\n\n    private List<Project> _projects = new List<Project>();\n    public List<Project> Projects { get { return _projects; } }\n}\n\npublic class Project\n{\n    public int Id { get; set; }\n    public int ClientId { get; set; }\n\n    // Project Properties\n\n    private List<Task> _tasks = new List<Task>();\n    public List<Task> Tasks { get { return _tasks; } }\n}\n\npublic class Task\n{\n    public int Id { get; set; }\n    public int ProjectId { get; set; }\n\n    // Task Properties\n}	0
8170643	8169188	How to draw a rectangle on a form picturebox from another form	using (Graphics g = Graphics.FromImage(pictureBox1.Image))\n  g.FillRectangle(Brushes.Red, new Rectangle(10, 10, 32, 32));\n\npictureBox1.Invalidate();	0
4557563	4553349	Sending Castle Proxy from NHibernate with MassTransit over MSMQ causes StackOverflowException	bus.Publish(msg)	0
5019793	5019615	Using a ASP .NET MVC model value to validate another model value?	public class DayTotalAttribute : ValidationAttribute\n{\n    ProjectDBContext db = new ProjectDBContext();\n\n    protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n    {\n        if (value != null)\n        {\n            var model = (SomeClass)validationContext.ObjectInstance;\n            var products = from p in db.EmployeeDayMax\n                       where p.EmployeeId = model.EmployeeId\n\n            bool somethingIsWrong = // do your validation here\n\n            if (somethingIsWrong)\n            {\n                return ValidationResult("Error Message");\n            }\n        }\n\n        return base.IsValid(value, validationContext);\n    }    \n}	0
19986113	19986063	Inconsistent Accessibility using lists	public partial class Reports24Hours : Form\n{\n    string category = "";\n    public int WhichReciept = 0;\n    public static List<ReportReciepts> recieptlist { get; set; } //Error here\n    ...\n}\n\n\n\npublic class ReportReciepts\n{\n    public string[] Quantity { get; set; }\n    public string[] ItemName { get; set; }\n    public string[] Price { get; set; }\n}	0
16823131	16822389	Serilize List<List<string>> in ProtoBuf-net and Deserialize as a C++ vector<vector<string>>	message Outer {\n    repeated Inner items = 1;\n}\nmessage Inner {\n    repeated string items = 1;\n}	0
14340201	14340009	Loop files in a folder and add each to a thread, but only run one of the threads at a time	Queue<CustomerFile> files = new Queue<CustomerFile>()\nforeach (CustomerFile f in CF)\n  files.Enqueue(f);\n\nBackgroundWorker bwk = new BackgroundWorker();\nbwk.DoWork+=()=>{\n    //Process the queue here\n    // if you update the UI don't forget to call that on the UI thread\n};\n\nbwk.RunWorkerAsync();	0
7585838	7585574	List to single dimension of multidimensional array	List l = new List { 1, 2, 3, 4, 5 }; \nint [,] a = new int[5, 3]; //5 rows 3 columns \n\nint i = 0;\nl.ForEach(item => a[i++, 2] = item);	0
21918427	21917591	ServiceStack 4 new licensing	License Exception	0
7853374	7853249	Setting a ref to a member field in C#	public class End\n{\n    public StringBuilder parameter;\n\n    public End(StringBuilder parameter)\n    {\n        this.parameter = parameter;\n        this.Init();\n        Console.WriteLine("Inside: {0}", parameter);\n    }\n\n    public void Init()\n    {\n        this.parameter.Clear();\n        this.parameter.Append("success");\n    }\n}\n\nclass MainClass\n{\n    public static void Main(string[] args)\n    {\n        StringBuilder s = new StringBuilder("failed");\n        End e = new End(s);\n        Console.WriteLine("After: {0}", s);\n    }\n}	0
20876040	20874795	OleDBConnection Connection string	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;\nExtended Properties="Excel 12.0 Xml;HDR=YES";	0
14495555	14495505	c# how to get the result string from object	string GetParamStringFromArrayObject(object obj)\n{\n   Array array = obj as Array;\n   if (array != null)\n   {\n       int demesion = array.Rank;\n       // etc.\n    }\n}	0
28265564	28265530	Is it possible to assign multiple actions to the same controller method?	public ActionResult PortfolioCollection(string id)\n{\n    const string folder = @"~/Content/images/portfolio/";\n\n    var files = Directory\n        .EnumerateFiles(Server.MapPath(folder + id))\n        .Select(Path.GetFileName);\n\n    return View(files);\n}	0
25173511	25172948	StackOverflowException after returning private variable, only while stepping through code	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        var obj = new TModel();\n    }\n}\n\nclass TModel {\n    public override string ToString() {\n        return " " + ToString();\n    }\n}	0
16507964	16507729	Update line in database	private void button_Click(object sender, EventArgs e)\n    {\n        using (DbEntities db = new DbEntities())\n        {\n           Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);\n           // firstArticle is not null anyways as you are calling FirstOrDefault()\n         **EDIT** // In case nothing has status = false, you will get a new Articles object, so instead of the below null check, you have to check for other property like id or name that will be unique.\n            if (firstArticle != null)\n            {\n                firstArticle.statusArticle = true;\n                db.SaveChanges();\n                MessageBox.Show("Article validated", "OK");\n                this.Refresh();\n            }\n        }\n    }	0
17339629	17339578	Search list of object based on specific attribute c#	bool hasCheese = arts.Any(a => a.Name == "Cheese");	0
6263175	6262973	Server side and client side method	function getHtml() {\n    MyHtmlRequest('/html/villages/1/people', function(response) {\n        var html = response.Text;\n        return html;\n    });\n}	0
31922574	31920562	Marshalling an array of array of structs (2D struct array)	ByVal table() As myStruct	0
10189756	10189630	How can I use the same DataSource for multiple DataGridViews with a different filter applied on each?	DataView view1 = new DataView(tables[0]);\nDataView view2 = new DataView(tables[0]);\nDataView view3 = new DataView(tables[0]);\n\n\nBindingSource source1 = new BindingSource();\nsource1.DataSource = view1;\nsource1.Filter = "color = 'red'";\ngridView1.DataSource = source1;\n\nBindingSource source2 = new BindingSource();\nsource2.DataSource = view2;\nsource2.Filter = "color = 'white'";\ngridView2.DataSource = source2;\n\nBindingSource source3 = new BindingSource();\nsource3.DataSource = view3;\nsource3.Filter = "color = 'blue'";\ngridView3.DataSource = source3;	0
5732340	5732225	How to get nullable item from a LINQ2SQL query?	getPayeeID.First().GetValueOrDefault()	0
1457558	1457542	Starting a new process with arguments	var pattern = "\".*?\"";\nvar regex = new Regex(pattern);\nvar cmdString = "\"C:\\Files\\App 1\\App.exe\" \"-param1:true -blah\"";\n\nvar matches = regex.Matches(cmdString)\n                   .OfType<Match>()\n                   .Select(m => m.Value.Trim('\"'))\n                   .ToArray();\n\nvar cmd = matches[0];\nvar arg = matches[1];\n\nvar proc = Process.Start(cmd, arg);\nif (proc.Start())\n    proc.WaitForExit();	0
34567326	34548837	Determining the parent of a UIElementCollection	var idx = collection.Add(parentDetectionElement);\nvar isGrid = VisualTreeHelper.GetParent(collection[idx]) is Grid;\ncollection.RemoveAt(idx);\nif(!isGrid)\n{ \n    throw new ArgumentException("The UIElementCollection's Parent is not a Grid. Please provide a Grid.Children UIElementCollection.");\n}	0
19486793	19486668	How to Set value to XmlNode without using InnerText	//Create a new node and add it to the document. \n//The text node is the content of the price element.\nXmlElement elem = doc.CreateElement("price");\nXmlText text = doc.CreateTextNode("19.95");\ndoc.DocumentElement.AppendChild(elem);\ndoc.DocumentElement.LastChild.AppendChild(text);	0
3825255	3809995	Kicking off a Performance Monitor Data Collector Set via PowerShell?	logman start "My DataCollectorSet"\nlogman stop "My DataCollectorSet"	0
27215925	27215909	"Specified cast is not valid" when casting array of string to array of int	var ff = nums.Select(x => Convert.ToInt32(x)).ToArray();	0
32223201	32223148	Asp.net razor datetime validation	[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm}")]	0
31453211	31452556	Replace string occurences with list entries	String source = "foo () bar ()";\n\n  var guiIdentifierList = new List<String> { \n    "x", "y", "z", "x", "y" };\n\n  int guiIdentifierIndex = 0; \n\n  // result == "foo (x) bar (y)"\n  String result = Regex.Replace(source, @"\(\)", (MatchEvaluator) (\n    (match) => "(" + (guiIdentifierIndex < guiIdentifierList.Count \n                      ? guiIdentifierList[guiIdentifierIndex++] \n                      : "") + ")"\n  ));	0
5342763	5342732	c# Get all available FontFamily	FontFamily[] ffArray = FontFamily.Families;\nforeach (FontFamily ff in ffArray)\n{\n    //Add ff.Name to your drop-down list\n}	0
11819602	11819591	How to use myString.PadLeft?	myString = myString.PadLeft(5, '_');	0
22381829	22381613	How to dynamically define class variable as argument in function	private void textBoxSource_Leave(object sender, EventArgs e)\n{\n    showErrorLabel(labelSourceError, textBoxSource.Text, val => r.source = val);\n}\n\nprivate void showErrorLabelString(Label l, string textboxtext, Action<string> update)\n{\n    if ((string.IsNullOrEmpty(s)) || (s.Length > 50))\n    {\n        isError = isError && false;\n        l.Text = "Please Enter Data and Should be smaller than 50 Character";\n        l.Visible = true;\n    }\n    else\n    {\n        update(textboxtext);\n    }\n}	0
23399328	23398526	Inserting a value one at a time	CREATE PROCEDURE add_Score\n @userID         INT\n @questionNumber INT,\n @score          INT\nAS\n    DECLARE @ColumnaName VARCHAR(100)\n    DECLARE @sql         VARCHAR(1000)\n    SET @ColumnName = \n    ( CASE @questionNumber\n        WHEN 1 THEN 'ColumnOne'\n        WHEN 2 THEN 'ColumnTwo'\n        WHEN 3 THEN 'ColumnThree'\n        WHEN 4 THEN 'ColumnFour'\n      END )\n\n    IF EXISTS(SELECT * FROM Questionire_Form WHERE UserID = @userID) THEN\n    BEGIN\n        SET @sql = 'UPDATE Questionire_Form SET ' + @ColumnName + ' = ' + @score + ' WHERE UserID = ' + @userID\n    END\n    ELSE\n    BEGIN\n        SET @sql = 'INSERT INTO Questionire_Form (UserID, ' + @ColumnName + ') VALUES(' + @userID + ', ' + @score + ')'\n    END\n\n    EXEC(@sql)	0
34442551	34442419	Getting the variable name for NullReferenceException	void Foo(Bar b)\n{\n   if (b == null) throw new ArgumentNullException(nameof(b));\n\n   ...\n}	0
26167244	26139336	How to handle Checkbox in asp c#	bool isitchecked = txtIsPaid.checked;\n Console.WriteLine(isitchecked);	0
1285677	1285520	Accessing a Label from a Textbox through AssociatedControlID	for = "txtName"	0
34105132	34079177	Reading columns in excel to c#	List<string> ColumnValues = new List<string>();\n                for (int n = 2; n < rowCount; n++)\n                {\n                    for (int m = 1; m < colCount; m++)\n                    {\n                        Excel.Range some = worksheet.UsedRange.Columns[m];\n\n                        System.Array myvalues = (System.Array)some.Cells.Value;\n                        string[] Data = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();\n                        ColumnValues = Data.ToList();\n                        System.Console.WriteLine(ColumnValues);\n                        //String Types\n                        if (ColumnValues.Contains("Name"))\n                        {\n                            string tagval = "Product_Array[0].Name";\n                            string[] result = ColumnValues.Skip(1).ToArray();\n\n                        }\n\n\n                    }\n\n\n                }\n\n        }	0
18764641	18763904	OpenXml-SDK: How to insert Plaintext with CarriageReturn/Linefeed	public static void SetNotes(this WordprocessingDocument doc, string value)\n{\n    MainDocumentPart main = doc.MainDocumentPart;\n    string altChunkId = "AltChunkId" + Guid.NewGuid().ToString().Replace("-", "");\n    var chunk = main.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.TextPlain, altChunkId);\n\n    using (var mStream = new MemoryStream())\n    {\n        using (var writer = new StreamWriter(mStream))\n        {\n            writer.Write(value);\n            writer.Flush();\n            mStream.Position = 0;\n            chunk.FeedData(mStream);\n        }\n    }\n\n    var altChunk = new AltChunk();\n    altChunk.Id = altChunkId;\n\n    OpenXmlElement afterThat = null;\n    foreach (var para in main.Document.Body.Descendants<Paragraph>())\n    {\n        if (para.InnerText.Equals("Notes:"))\n        {\n            afterThat = para;\n        }\n    }\n    main.Document.Body.InsertAfter(altChunk, afterThat);\n}	0
25202163	25202128	Insert into database with c#	string sql = "INSERT INTO Messages (Id, UserName, Message2, Sentdate)" + \n" VALUES(" + User.Identity.GetUserId()+", " + \nUser.Identity.Name +", "+\ntxtMessage.Text +", " +\nDateTime.Now.ToString() +");"	0
11185050	11184799	How to create 2 multidmensional string array (remove blank strings)?	string[][] movieNext =  {\nnew [] { "superhero", "action", "waltdisney", "bat"},\nnew []  {"superhero", "action", "marvel"}, <and so on>\n};	0
21465893	21464785	Trigger a Click event in javascript using c#(WebBrowser control)	ClientScript.RegisterStartupScript(this.GetType(), "DateTimeFromServer", string.Format(@"<script>  \n                                                                                $(function () {{\n                                                                                        $('#connectbtn').trigger('click','{0}');\n                                                                                    }});\n                                                                          </script>", DateTime.Now));	0
26733293	26732487	Downloading more files from URLs paralell	int rowcount = dataGridView1.Rows.Count;\n        List<Task> tasks = new List<Task>()\n        for (int i = 0; i < rowcount; i++)\n        {\n           string filename = patch;\n           var tsk = Task.Factory.StartNew(() =>\n           {\n                  try\n                  {\n                       var integerString = (i+1).ToString();\n                       WebClient webc = new WebClient();\n                       webc.DownloadFile(dataGridView1.Rows[i].Cells[0].Value.ToString(), patch + "\\" + "alap" + integeString + ".mp4");\n                  }\n                  catch\n                  {\n                     //log\n                  }\n           });\n           tasks.add(tsk);\n        }\n        Task.WaitAll(tasks.ToArray());	0
9975539	9974369	Same table NHibernate mapping	m.OneToOne(c => c.rootStructure, a => a.Lazy(LazyRelation.Proxy))	0
30111129	30110061	Set an Elements Visibility Based on Cell Value of Bound Datatable	protected void NamesGV_RowDataBound(object sender, GridViewRowEventArgs e) \n {\n    if (e.Row.RowType == DataControlRowType.Header) \n    {\n        for (int i = 0; i < e.Row.Cells.Count; i++) \n        {\n            e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;\n        }\n    }\n\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n         //Get reference to the button you want to hide/show\n         LinkButton delButton = CType(e.Row.Cells(2).FindControl("lbYourLinkButtonId"), LinkButton);\n\n         //check your data for value\n         bool visible = (bool)DoACheckForAValue(NamesGV.DataKeys(e.Row.RowIndex).Value);\n         delButton.Visible = visible;\n    }\n}	0
30668847	30668228	C# union with string	var path1 = @"C:\aaaa\bbbb\cccc";\nvar path2 = @"cccc\dddd";\n\nvar x = string.Join(\n    new string(Path.DirectorySeparatorChar, 1), \n    path1.Split(Path.DirectorySeparatorChar)\n         .Concat(path2.Split(Path.DirectorySeparatorChar))\n         .Distinct()\n         .ToArray());\n\n// path1 = C:\aaaa\bbbb\cccc\n// path2 = cccc\dddd\n// result = C:\aaaa\bbbb\cccc\dddd\n\n// path1 = C:\aaaa\bbbb\cccc\dddd\n// path2 = cccc\dddd\n// result = C:\aaaa\bbbb\cccc\dddd	0
32512769	32511234	Matlab builder NE 2012A x64 migreting to 2014B X64	[assembly: MathWorks.MATLAB.NET.Utility.MWMCROption ("- nojit")]	0
14531320	14529217	SqlBulkInsert with a DataTable to a Linked Server	Inserting into remote tables or views is not allowed by using the BCP utility or by using BULK INSERT.	0
8380488	8380359	WinForms: How to check for minimum amount of characters in textbox in C#?	protected override void OnLoad(object sender, EventArgs e)\n{\n    base.OnLoad(sender, e);\n\n    txtPassword.KeyDown += OnPasswordKeydown;     \n}\n\nprotected void OnPasswordKeydown(object sender, KeyEventArgs e)\n{\n    bool isValid = txtPassword.Text.Length < 6;\n\n    ErrorText.Visible = isValid;\n    AcceptButton.Visible = isValid;\n}	0
11369722	11368636	Reading Windows Event Payload Including Complex Data	public class Event\n{\n    [XmlArrayItem(typeof(Data))]\n    [XmlArrayItem(typeof(ComplexData))]\n    public object[] EventData;\n}\n\npublic class Data\n{\n    [XmlAttribute]\n    public string Name { get; set; }\n\n    [XmlText]\n    public string Value { get; set; }\n}\n\npublic class ComplexData\n{\n    [XmlAttribute]\n    public string Name { get; set; }\n\n    [XmlText(DataType = "hexBinary")]\n    public byte[] Encoded { get; set; }\n}	0
9732126	9731877	How to perform a reference assign?	class ProxyTerm : ITerm {\n\n     ITerm Reference { get; set; }\n\n     ITerm.SomeMethod() {\n          Reference.SomeMethod();\n     }\n\n}	0
5524365	5524335	DateTime.Now missing 1 hour daylight savings	System.Threading.Thread.CurrentThread.CurrentCulture	0
15304251	15303532	ComboBox refreshes ListBox	Public Class MyListBox\n  Inherits ListBox\n\n  Private WM_KILLFOCUS As Integer = &H8\n\n  Protected Overrides Sub WndProc(ByRef m As Message)\n    If m.Msg <> WM_KILLFOCUS Then\n      MyBase.WndProc(m)\n    End If\n  End Sub\n\nEnd Class	0
11967970	11967953	Getting enumerate value	status = (int) Status.Stack;	0
11207391	11202770	How to remove wordwrap from a webbrowser and or set font size smaller	html.Append("<ins style=\"white-space:nowrap; display:inline; background:#e6ffe6;\">")\n        .Append(text)\n        .Append("</ins>");	0
19167810	19167510	Windows Store App Textbox keeps loosing focus	private void Canvas_PointerReleased(object sender, PointerRoutedEventArgs e)\n{\n    textBoxMain.Focus(Windows.UI.Xaml.FocusState.Programmatic);\n}\n\n\nprivate void textBoxMain_GotFocus(object sender, RoutedEventArgs e)\n{\n    textBoxMain.Focus(Windows.UI.Xaml.FocusState.Programmatic);\n}	0
19910684	19910488	Using a for each loop to give multiple pictureboxes a random image VB.NET	For Each pb As PictureBox In New PictureBox() {steen1, steen2, steen3, steen4, steen5, steen6}\n  Select Case RandomNumber.Next(1, 7)\n    Case 1 : pb.Image = Game.My.Resources.Een\n    Case 2 : pb.Image = Game.My.Resources.Twee\n    Case 3 : pb.Image = Game.My.Resources.Drie\n    Case 4 : pb.Image = Game.My.Resources.Vier\n    Case 5 : pb.Image = Game.My.Resources.Vijf\n    Case 6 : pb.Image = Game.My.Resources.Zes\n  End Select\nNext	0
16416218	16416196	How to Discard Null Values in Data Table when Checking with IF Condition inside a For Loop	for (int x = 0; x <= dt.Rows.Count-1; x++)	0
16171828	16171731	How to add a new group in Active Directory using LDAP in C#	public void Create(string ouPath, string name)\n{\n    if (!DirectoryEntry.Exists("LDAP://CN=" + name + "," + ouPath))\n    {\n        try\n        {\n            // bind to the container, e.g. LDAP://cn=Users,dc=...\n            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);\n\n            // create group entry\n            DirectoryEntry group = entry.Children.Add("CN=" + name, "group");\n\n            // set properties\n            group.Properties["sAmAccountName"].Value = name;\n\n            // save group\n            group.CommitChanges();\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(e.Message.ToString());\n        }\n    }\n    else { Console.WriteLine(path + " already exists"); }\n}	0
31447287	31446915	Best way for a switch statement for multiple if-else	bool _condition = Convert.ToString(dataRow["IsEmployee"]);\n\nswitch(strImageFormat)\n{\ncase "JPG":\n            ImagePath = _condition  ? string.Format("{0}{1}", fileNameUpper, ".JPEG") : ImagePath = string.Format("{0}{1}", fileNamelabel, ".JPEG") ;\n            break;\ncase "GIF":\n            ImagePath = _condition  ? string.Format("{0}{1}", fileNameUpper, ".GIF") : ImagePath = string.Format("{0}{1}", fileNamelabel, ".GIF") ;\n            break;\n.\n.\n.\n.\n.\n.\ndefault:\n       // DO SOMETHING\n}	0
26445151	26444822	How to upload video in ASP.NET MVC 5 and pass the video file from a view to a method?	[HttpPost]\n    public ActionResult UploadFile()\n    {\n           var httpPostedFile = Request.Files[0];\n           if (httpPostedFile != null) {\n\n                // Validate the uploaded file if you want like content length(optional)\n\n                // Get the complete file path\n                var uploadFilesDir = System.Web.HttpContext.Current.Server.MapPath("~/Content/Videos");\n                if (!Directory.Exists(uploadFilesDir)) {\n                    Directory.CreateDirectory(uploadFilesDir);\n                }\n                var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);\n\n                // Save the uploaded file to "UploadedFiles" folder\n                httpPostedFile.SaveAs(fileSavePath);\n\n            }\n\n            return Content("Uploaded Successfully");\n    }	0
26507923	18620664	How to invoke Dynamically a method of an instantied object in c#	return (string)myType.InvokeMember("getChave", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, myObj, null);	0
15204917	15204739	Is it possible to deserialize an encrypted file via DataContractSerializer?	using(var cryptoStream = \n      new CryptoStream(fileStream, crypt.CreateDecryptor(), CryptoStreamMode.Read))\n{               \n    using(var reader = new StreamReader(cryptoStream))\n    {\n        var s = reader.ReadToEnd().TrimEnd(new char[]{'\0'});\n\n        using(var stream = new MemoryStream(Encoding.ASCII.GetBytes(s)))\n        {\n            o = (t)serializer.ReadObject(stream);\n        }\n    }\n}	0
10941855	10941579	Using ColorDialog to set colors in datagrid	Color c = Color.Red;\nint redColor = c.ToArgb();\n\n//...\n\nthis.BackColor = Color.FromArgb(redColor);	0
890982	890896	How can I fire an event without waiting for the event listeners to run?	void OnUpdated(EventArgs e) {\n   EventHandler h = this.Updated;\n   if (h != null) h(e);\n}\n\nvoid DoStuff() {\n   BigMethod();\n   ThreadPool.QueueUserWorkItem(OnUpdated, EventArgs.Empty);\n   BigMethod2();\n}	0
15146557	15146178	Extract Image from Combined Image	Bitmap bitmapLeft = bitmap.Clone(new Rectangle(0, 0, widthLeft, heightLeft), PixelFormat.DontCare);\nBitmap bitmapRight = bitmap.Clone(new Rectangle(widthLeft, 0, widthRight, heightRight), PixelFormat.DontCare);	0
610057	609927	Custom Caret for WinForms TextBox	public partial class Form1 : Form\n{\n    [DllImport("user32.dll")]\n    static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);\n    [DllImport("user32.dll")]\n    static extern bool ShowCaret(IntPtr hWnd);\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Shown(object sender, EventArgs e)\n    {\n        CreateCaret(textBox1.Handle, IntPtr.Zero, 10, textBox1.Height);\n        ShowCaret(textBox1.Handle);\n    }\n}	0
4277701	4274588	Printing Multiple Windows Using PrintVisual()	RenderTargetBitmap()	0
22790812	22790362	How to run PowerShell script file without SDK?	powershell.exe -ExecutionPolicy Bypass	0
19992135	19992105	Get a refined list using Linq	public List<DataGroups> GetDataGroupsByName(string name) {\n     return _allGroups.Where(x => x.Title == name);\n}	0
339369	339353	Remove single backslashes, convert doubles to single in string	Regex.Replace(input, @"\\(.|$)", "$1");	0
24962071	24961971	Database Design - Column has values of different types stored as varchar	ItemTable\nId | Itemname | ItemBrand | ItemBand\n1  | Foobar   | 2         | 3     \n\nCategoryTable\nId | CategoryName\n1  | Foo\n2  | Bar\n3  | Baz	0
2315093	2197620	how to set focus and launch the already running application on button click event in c#.net3.5?	[DllImport( "user32.dll" )]\npublic static extern bool ShowWindowAsync( HandleRef hWnd, int nCmdShow );\npublic const int SW_RESTORE = 9;\n\npublic void SwitchToCurrent() {\n  IntPtr hWnd = IntPtr.Zero;\n  Process process = Process.GetCurrentProcess();\n  Process[] processes = Process.GetProcessesByName( process.ProcessName );\n  foreach ( Process _process in processes ) {\n    // Get the first instance that is not this instance, has the\n    // same process name and was started from the same file name\n    // and location. Also check that the process has a valid\n    // window handle in this session to filter out other user's\n    // processes.\n    if ( _process.Id != process.Id &&\n      _process.MainModule.FileName == process.MainModule.FileName &&\n      _process.MainWindowHandle != IntPtr.Zero ) {\n      hWnd = _process.MainWindowHandle;\n\n      ShowWindowAsync( NativeMethods.HRef( hWnd ), SW_RESTORE );\n      break;\n    }\n  }\n }	0
5690564	5690521	Sending files from Client to Server	if (clientSocket!=null)\n   clientSocket.Close();	0
7000956	7000604	Set referenced DLL path at runtime	Assembly assembly = Assembly.LoadFile(pathOfAssembly);\nInterfaceName instance = (InterfaceName)assembly.CreateInstance("fully qualified type name", true);	0
29334841	29334207	How to filter the data bound to GridView control by the QueryString?	private void bindGrid()\n{\n    Item itemObj = new Item();\n    if(Request.QueryString["ItemId"] != null) \n    {\n        itemObj.ItemId = Convert.ToInt32(Request.QueryString["ItemId"]);\n    }\n    var result = itemObj.getData(itemObj).ToList();\n    gvItems.DataSource = itemObj.getData(itemObj);\n    gvItems.DataBind();\n}	0
14639922	14639280	XML with .NET - Build in code or read from a file?	const string cChart1 = @"<chart type='pie'>\n    <total>{0}</total>\n    <sections count={1}>\n        <section>{2}</section>\n        <section>{3}</section>\n        <section>{4}</section>\n    </section>\n    </chart>";\n\n    XmlDocument xmlChart1 = new XmlDocument();\n    xmlChart1.LoadXML(String.format(cChart1, somevalue1, somevalue2, somevalue3, somevalue4, somevalue5));\n\n    3rdPartyChartComponent cc = new 3rdPartyChartComponent(xmlChart1);	0
31956206	31955840	Infinite For Loop Crash	public Form1()\n{\n    InitializeComponent();\n\n    backgroundWorker1.DoWork += backgroundWorker1_DoWork;\n    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    backgroundWorker1.RunWorkerAsync();\n}\n\nprivate void backgroundWorker1_DoWork(object sender,            System.ComponentModel.DoWorkEventArgs e)\n{\n     // Your infinite loop here, example is given below\n     for (int i = 0; i < 100000; i++)\n     {\n        Console.WriteLine(i);\n         Thread.Sleep(1000);\n     }\n}	0
3154277	3154262	How to check if all of the elements in a list return true for a property using Linq?	var allValid = myList.All(item => item.IsValid);	0
16147273	16147223	How to use https in c#?	&& !req.IsLocal	0
31738740	31738430	how to convert string into Date only in C# asp.net	String datePickerInput = "31.07.2015";\nString format = "dd.MM.yyyy";\nDateTime dte = DateTime.ParseExact(s, format, CultureInfo.InvariantCulture);	0
12492372	12492257	Key recognition speed in dictionaries	hashCode modulo array.Length	0
7854788	7854597	Parsing XDocument using UTF-8 format and saving to MySQL as UTF-8 error	Contents = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Default.GetBytes(a.Value))	0
3114261	3114201	Binding to a property of an instance of a class, or modifying the properties from code	var viewModel = new SomeAwesomeViewModel();\nDataContext = viewModel;	0
17211192	17205359	Configure WCF Service to enable HTTPS and Transport Credential with User Name and Password	clientCredentialType="Basic"	0
3794220	3794200	give <a> style in code behind	CPCSS.Attributes.Add("class", "bag_d");	0
16731145	16730547	How do I provide multiple vsFindOptions in TextDocument.ReplacePattern?	[...].ReplacePattern(@"<span (.\w.+?>)", string.Empty,\n    vsFindOptions.vsFindOptionsRegularExpression | \n    vsFindOptions.vsFindOptionsMatchWholeWord);	0
34375335	34375197	C# Splitting List based on element variable and element position	List<List<YouObjectType>> SplitList(List<YourObjectType> listToSplit) {\n    List<List<YouObjectType>> listOfLists = new List<List<YourObjectType>>();\n    List<YourObjectType> tmp = new List<YourObjectType>();\n    foreach(YourObjectType item in listToSplit) {\n        if (tmp.Count > 0\n            && tmp[tmp.Count - 1] != item) {\n            // Compare you items here as you wish, \n            // I'm not sure what kind of objects\n            // and what kind of comparison you are going to use\n            listOfLists.Add(tmp);\n            tmp = new List<YourObjectType>();\n        }\n        tmp.Add(item);\n    }\n    if (tmp.Count > 0) {\n        listOfLists.Add(tmp);\n    }\n    return listOfLists;\n}	0
24719895	24719811	Generate custom URL - showing description in URL	[Route("detail/{productName:string")]\npublic ViewResult Detail(string productName)\n{\n   return View();\n}	0
31716844	31716735	C# Converting an int into an array of 2 bytes	//profile_num[0] = (byte) ((profile_number & 0xFF00));\n profile_num[0] = (byte) ((profile_number & 0xFF00) >> 8);\n profile_num[1] = (byte) ((profile_number & 0x00FF));	0
25782405	25781938	How to convert object[,] to datatable in C#	var rowCount = valueArray.GetLength(0);\nvar columnCount = valueArray.GetLength(1);\n\nvar dtTemp = new DataTable();\nforeach(var c in Enumerable.Range(1, columnCount))\n    dtTemp.Columns.Add();\nforeach (var r in Enumerable.Range(1, rowCount))\n    dtTemp.Rows.Add(Enumerable.Range(1, columnCount)\n        .Select(c => valueArray[r - 1, c - 1]).ToArray());	0
8969143	8966259	How to pass data from a visible form to another visible form?	partial class FormB\n{\n\n     private FormA reftoA; \n\n     public FormB(FormA formref, int Data)\n     {\n          reftoA= formref;\n     }\n\n     private void SomeMethodToChangeSomethinginFormA()\n     {\n              reftoA.SomeProp= 4;\n     }\n}	0
25772006	25771911	How to pass input value from the form which is not part of any model?	public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person, string FetchDate, string FetchTime) {\n    if (ModelState.IsValid) {\n        db.Entry(person).State = EntityState.Modified;\n        db.SaveChanges();\n        return RedirectToAction("Index");\n    }\n    return View(person);\n}	0
5849075	4591664	Change image resolution in FreeImage	FreeImage.SetResolutionX(forSaving, (uint)dpiValue);\nFreeImage.SetResolutionY(forSaving, (uint)dpiValue);\nFREE_IMAGE_SAVE_FLAGS compression = getJpegQuality(quality);\nFreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, forSaving, filename, compression);	0
9654869	9654783	Find files between a certain alpha range	A[a-e].*	0
15346730	15343848	How to display Image When Value will be True or False in Database	SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z w?asnymi batonami\Baza z w?asnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");\n    SqlCommand cmd = new SqlCommand();\n    SqlDataReader dr;\n    cn.Open();\n    cmd.CommandText = "SELECT oddal FROM TableName WHERE (Your = Condition)";\n    dr = cmd.ExecuteReader();\n    if dr.Read()\n    {\n            if dr("oddal")\n            {\n            //Set picture box to image 1\n            } \n            else \n            { //Set picture box to image 1\n            }\n    }\n    cn.Close();	0
20778802	20778645	Upload Different Video Formats	using System;\nusing System.IO;\n\nnamespace HeaderReader\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            byte[] bytesFile = new byte[7]; // Read the first 7 Bytes\n            using (FileStream FileS = File.OpenRead("MyFile")) //the uploaded file\n            {\n                FileS.Read(bytesFile, 0, 7);\n                FileS.Close();\n            }\n            string data = BitConverter.ToString(bytesFile); //convert data to get info\n            Console.WriteLine("This is the data:" + data);\n        }\n    }\n}	0
21454107	21454062	Package whole C# Console application in one file?	var assembly = Assembly.GetExecutingAssembly();\n var stream = assembly.GetManifestResourceStream("MyNamespace.MyResourceFileName");\n\n // ... do something with stream, e.g. write it out to a file.	0
22547041	22540030	list Values to dataTable	for (int i = 1; i < list.Count; i += 2)\n{\n    DataRow row = table.NewRow();\n    row["ItemNumber"] = list[i-1];\n    row["Price"] = list[i];\n\n    table.Rows.Add(row);\n}	0
25274225	25273157	T-SQL: Lock a table manually for some minutes	BEGIN TRAN  \nSELECT 1 FROM TABLE WITH (TABLOCKX)\nWAITFOR DELAY '00:02:00' \nROLLBACK TRAN   \nGO	0
28907098	28906676	How to prevent TreeView rename from making a duplicate	void treProducts_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {\n  foreach (TreeNode tn in e.Node.Parent.Nodes) {\n    if (tn.Text == e.Label) {\n      e.CancelEdit = true;\n    }\n  }\n}	0
18194831	18194749	How do I get the element that the cursor is over during a keypress?	var elementundermouse = Mouse.DirectlyOver as FrameworkElement;	0
11071972	11071947	Converting ObservableCollection<T> to ObservableCollection<String>	var newCollection = new ObservableCollection<string>(myCollection.Select(x => x.ToString()));	0
8420510	8418326	WPF Binding a textbox to Current selected row of a datagrid	private bool AcceptingTheChanges = false;\nprivate DataRowView myRecord;\npublic DataRowView MyRecord\n{\n   get { return myRecord; }\n   set {\n          if (myRecord != null)\n                myRecord.Row.Table.AcceptChanges();\n\n          // Now, get the incoming value and re-store into private\n          myRecord = value;\n          // Finally, raise event that it changed to refresh window...\n          RaisePropertyChanged("MyRecord");\n       }\n}	0
7957009	7956943	Which part of a GUID is most worth keeping?	var g = Guid.NewGuid();\nvar s = Convert.ToBase64String(g.ToByteArray());\n\nConsole.WriteLine(g);\nConsole.WriteLine(s);	0
7666623	3074857	AxAcroPDF swallowing keys, how to get it to stop?	DateTime _lastRenav = DateTime.MinValue;\n\npublic Form1()\n{\n    InitializeComponent();\n\n    listBox1.LostFocus += new EventHandler(listBox1_LostFocus);\n}\n\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    axAcroPDF1.src = "sample.pdf";  //this will cause adobe to take away the focus\n    _lastRenav = DateTime.Now;\n}\n\nvoid listBox1_LostFocus(object sender, EventArgs e)\n{\n    //restores focus if it were the result of a listbox navigation\n    if ((DateTime.Now - _lastRenav).TotalSeconds < 1)\n        listBox1.Focus();\n}	0
31892007	31889000	SqlDataReader prints multiple rows, how can I split?	string query = "select title, rating, dor from movie where title like '%"+name+"%';";\n\nusing (SqlConnection conn = new SqlConnection(cs))\n{\n    SqlCommand cmd = new SqlCommand(query, conn);\n    conn.Open();\n\n    SqlDataReader reader = cmd.ExecuteReader();\n\n    if (reader.HasRows)\n    {\n        while (reader.Read())\n        {\n            Response.Write(reader[0].ToString());\n            Response.Write(reader[1].ToString());\n            Response.Write(reader[2].ToString());\n            Response.Write("------------------------");//whatever separator you want to use\n        }\n    }\n    else\n    {\n        Response.Write("No rows found");\n    }\n\n    reader.Close();\n}	0
25572745	25572683	LINQ: How to use a variable field list in an orderBy clause	using System.Linq.Dynamic;\n..\nvar instruments = db.Instruments.OrderBy("Field1").ThenBy("Field2");	0
31464236	31463955	how to remove a row from an 2-D Array	var data = new[] {\n                new { Date = "01/07", Price = 10 },\n                new { Date = "02/07", Price = 20 },\n                new { Date = "", Price = 30 },\n                new { Date = "03/07", Price = 40 }\n            };\n\nvar noBlanks = (from d in data \n                where !string.IsNullOrWhiteSpace(d.Date) \n                select d).ToArray();	0
29628668	29628447	How can I get the parent (Expander control in this case) of my DataTemplate in a Click Event?	Expander expander = FindMyParentHelper<Expander>.FindAncestor(boton);\n\npublic static class FindMyParentHelper<T> where T : DependencyObject\n{\n    public static T FindAncestor(DependencyObject dependencyObject)\n    {\n        var parent = VisualTreeHelper.GetParent(dependencyObject);\n\n        if (parent == null) return null;\n\n        var parentT = parent as T;\n        return parentT ?? FindAncestor(parent);\n    }\n}	0
1865155	1865070	How to know that I have another thread running apart from the main thread?	private volatile Thread _Thread;\n\n...\n\nif (_Thread == null)\n{\n    _Thread = new Thread(new ThreadStart(Some_Work));\n    _Thread.Start();\n}\n\nprivate void Some_Work()\n{\n    try\n    {\n        // your thread code here\n    }\n    finally\n    {\n        _Thread = null;\n    }\n}	0
1644612	1644519	Compare date in javascript	totaltime = new Date("1988/02/21 08:08");\nd = new Date();\nif (totaltime.getTime() < d.getTime())\n    alert("Date is valid");\nelse\n    alert("Try again, Date is not valid");	0
12286199	12286042	Parse file with multiples values lines C#	var result =File.ReadLines(fileName)\n    .Select(line => line.Split(new string[]{"User:", "Name:", "Last:", "Email:"}, StringSplitOptions.RemoveEmptyEntries))\n    .Select(parts => new Conctact(){ Name = parts[1], Last = parts[2], Email = parts[3] })\n    .ToArray();	0
8534296	8534213	Can an application compile and create another application?	Microsoft.CSharp.CSharpCodeProvider	0
7012261	7012168	Importing a CSV File that contains more than one value in a field	string[] result = input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);	0
23379827	23363580	How to add xml text in existing xml file if my xml having same node twice	var doc = XDocument.Parse("your xml string");\n   //namespace\n   var nspace = doc.Root.Name.Namespace;\n    foreach (var item in doc.Descendants(nspace+"DataSet"))\n    {\n\n        var str = new StringBuilder();\n        var str1 = new StringBuilder();\n        str.Append("<Field Name='CommunicationDataValueId'>");\n        str.Append("<DataField>CommunicationDataValueId</DataField>");\n        str.Append("<TypeName>System.Int64</TypeName>");\n        str.Append("</Field>");\n        str1.Append("<Field Name='DeviceMasterId'>");\n        str1.Append("<DataField>DeviceMasterId</DataField>");\n        str1.Append("<TypeName>System.Int32</TypeName>");\n        str1.Append("</Field>");\n        item.Add(XElement.Parse(str.ToString()));\n        item.Add(XElement.Parse(str1.ToString()));\n    }	0
910433	910400	Reading from Excel (Range into multidimensional Array) C#	using (MSExcel.Application app = MSExcel.Application.CreateApplication()) \n{\n    MSExcel.Workbook book1 = app.Workbooks.Open( this.txtOpen_FilePath.Text);\n    MSExcel.Worksheet sheet = (MSExcel.Worksheet)book1.Worksheets[1];\n    MSExcel.Range range = sheet.GetRange("A1", "F13");\n\n    object value = range.Value; //the value is boxed two-dimensional array\n}	0
17735344	17735235	How to pass predicate to linq expression	where predicate == null || predicate(student)	0
12016964	12016946	How to Split an XML file into multiple XML Files	XDocument doc = XDocument.Load("test.xml");\nvar newDocs = doc.Descendants("DOC")\n                 .Select(d => new XDocument(new XElement("DATABASE", d)));\nforeach (var newDoc in newDocs)\n{\n    newDoc.Save(/* work out filename here */);\n}	0
8053743	8053587	how to append IQueryable within a loop	var productIds = store.BasketItems.Select(x => x.ProductID).ToList();\nvar query = from p in db.Products\n            where p.Active && productIds.Contains(p.ProductID)\n            select new\n            {\n                p.ProductID,\n                p.ProductName,\n                p.BriefDescription,\n                p.Details,\n                p.ProductCode,\n                p.Barcode,\n                p.Price\n            };	0
2868213	2868156	Encrypt column data with LINQ	public partial class DbTableItem\n{\n  public String UnencryptedPass\n  {\n    get\n    {\n       return  Crypter.Decrypt(this.Pass);\n    }\n\n    set\n    {\n       this.Pass = Crypter.Encrypt(value)\n    }\n  }\n}	0
9100396	9100174	Opening a website when a button on the form is clicked	webBrowser1.Navigate("www.google.com");	0
16725411	16725215	convert two dimensional string array to two dimensional int array	int[,] inner = new int[4,2];	0
3837142	3821717	Encoding of URL paramaters	Regex regex = new Regex(@"foo=(.*?)(&|\z)");\nstring myFooParameter = regex.Match(Request.RawUrl).Groups[1].Value;\nmyFooParameter = HttpUtility.UrlDecode(myFooParameter, Encoding.GetEncoding(28591));	0
25298930	25298663	Use One Month Calendar to Populate 2 Text Boxes	public Form1()\n    {\n        InitializeComponent();\n        mthCalendarMaster.DateSelected += mthCalendarMaster_DateSelected;\n    }\n\n    private void mthCalendarMaster_DateSelected(object sender, DateRangeEventArgs e)\n    {\n        if (string.IsNullOrWhiteSpace(textBox1.Text))\n            textBox1.Text = e.Start.ToShortDateString();\n        else\n            textBox2.Text = e.Start.ToShortDateString();\n    }	0
23107998	23107252	sending updates to clients with SignalR using publish-subscribe pattern	Install-Package SignalR.EventAggregatorProxy	0
31325476	31325418	How to delay an action on WP 8.1	await System.Threading.Tasks.Task.Delay(500);	0
18460029	18447022	Recommended Optimization package for ILNumerics	.... inside ILNumerics function\n using (ILScope.Enter(inparameter1,inparameter2)) {\n    ....\n    ILArray<double> A = zeros(1000,1000);  // allocate memory for external use\n    var aArray = A.GetArrayForWrite();     // fetch reference to underlying System.Array  \n    callOtherLib(aArray);                  // let other lib use and fill the array\n    // proceed normally with A... \n    return A + 1 * 2 ... ; \n }	0
18538469	18538428	Loading a .json file into c# program	JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));\n\n// read JSON directly from a file\nusing (StreamReader file = File.OpenText(@"c:\videogames.json"))\nusing (JsonTextReader reader = new JsonTextReader(file))\n{\n  JObject o2 = (JObject) JToken.ReadFrom(reader);\n}	0
18037820	567216	Is there a "All Children loaded" event in WPF	Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => {code that should be executed after all children are loaded} ));	0
8172389	8172079	Copy files over network via file share, user authentication	Private Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUserName As String, ByVal strPassword As String)\n    Dim ProcessStartInfo As New System.Diagnostics.ProcessStartInfo\n    ProcessStartInfo.FileName = "net"\n    ProcessStartInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword\n    ProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden\n    System.Diagnostics.Process.Start(ProcessStartInfo)\n    System.Threading.Thread.Sleep(2000)\nEnd Sub	0
25458419	25458181	How can we modify the date of folder in file explorer	string n = @"C:\test\dirToChange";\n//Create two variables to use to set the time.\nDateTime dtime1 = new DateTime(2002, 1, 3);\n\n//Set the creation time to a variable DateTime value.\nDirectory.SetCreationTime(n, dtime1);	0
11785666	11696856	How to add EOFB (End of facsimile block) in tif image	private void AddEOFB(string imgFileName)\n    {\n        var fs = new FileStream(imgFileName, FileMode.Append, FileAccess.Write);\n        try\n        {\n            fs.Seek(0, SeekOrigin.End);\n            var buf = BitConverter.GetBytes(0x00100100);\n            fs.Write(buf, 0, buf.Length);\n        }\n        catch { throw; }\n        finally\n        {\n            fs.Close();\n            fs.Dispose();\n        }\n    }	0
14487837	14487671	Prefixing control IDs in MVC3 to ensure uniqueness. I am losing all of my data when posting back to server	public ActionResult SomeAction([Bind(Prefix = "SomePrefix")] ViewModel model){...}	0
20419467	20215830	Umbraco: Get "Last Edits" values from content	foreach (var node in recentUpdatedNodes)\n{\n    @node.Name\n    @node.Url\n    @node.Id\n}	0
20270068	19562505	Assert to compare two lists of objects C#	public class MyPersonEqualityComparer : IEqualityComparer<MyPerson>\n{\npublic bool Equals(MyPerson x, MyPerson y)\n{\n    if (object.ReferenceEquals(x, y)) return true;\n\n    if (object.ReferenceEquals(x, null)||object.ReferenceEquals(y, null)) return false;\n\n    return x.Name == y.Name && x.Age == y.Age;\n}\n\npublic int GetHashCode(MyPerson obj)\n{\n    if (object.ReferenceEquals(obj, null)) return 0;\n\n    int hashCodeName = obj.Name == null ? 0 : obj.Name.GetHashCode();\n    int hasCodeAge = obj.Age.GetHashCode();\n\n    return hashCodeName ^ hasCodeAge;\n}	0
14193984	14159055	Linq to Sql: Select only items from DB1-table1 that don't exist on DB2-table2	//DB1\ndb1DataContext db1 = new db1DataContext();\n//DB2\ndb2DataContext db2 = new db2DataContext();\n\n\n//SELECT ALL DATA FROM DB1\nvar result1 = (from e in db1.Items\n               select e\n              ).ToList();\n\n//SELECT ALL DATA FROM DB2\nvar result2 = (from e in db2.Item2s\n               select e\n              ).ToList();\n\n//SELECT ALL ELEMENTS FROM DB2.TABLE THAT DO NOT EXISTS ON DB1.TABLE BASED ON EXISTING ID's            \nvar resultFinal = ( from e in result1\n                    where !(from m in result2\n                            select m.Id).Contains(e.Id)\n                    select e\n                  ).ToList();	0
14025201	14024836	How to delete a specific text showed in a ListView in WPF?	public partial class MainWindow : Window\n{\n    List<Familiy> familiys = new List<Familiy>();\n    public MainWindow()\n    {\n        InitializeComponent();\n\n\n        familiys.Add( new Familiy("FirstName1", "LastName1"));\n        familiys.Add(new Familiy("FirstName2", "LastName2"));\n        familiys.Add(new Familiy("FirstName3", "LastName3"));\n        familiys.Add(new Familiy("FirstName4", "LastName4"));\n        listView1.ItemsSource = familiys;\n\n    }\n    private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        familiys.Remove(familiys.Find(delegate(Familiy f) { return f.FirstName == firstnametxt.Text; }));\n        listView1.ItemsSource = "";\n        listView1.ItemsSource = familiys;\n    }\n}	0
13561885	13248013	VisualTreeHelper not finding children of DependencyObject, How can I reliably find objects?	var header = container.ListBox.Items.Cast<ListBoxItem>()\n    .Select(item => (MyType) item.Content)\n    .FirstOrDefault(myType => myType.dpHeader.Name == "whatever").dpHeader;	0
32829092	32739832	How do I get reasonable performance out of C# WebClient UploadString	ASP.NET Applications\Requests/Sec	0
28229389	28210004	How to make auto remove from DataBase with NHibernate?	cascade="all-delete-orphan"	0
9084954	9084923	Changing AVI File Title Property with C#	TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = "New Album Title";\nf.Save();	0
10842633	10841627	Accessing Impersonated users key store	using (var ctx = new ImpersonationContext("svcAcctUserName", "domain", "password"))\n{\n   var store = new X509Store(StoreLocation.LocalMachine);\n   store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);\n   var clientCert = store.Certificates.Find(X509FindType.FindByIssuerName, "IssuerNameHere", false);\n   var clientCert2 = new X509Certificate2(clientCert[0]);\n}	0
21236680	21234908	Access Denied when saving a file, Windows 8 App	Windows.Storage.StorageFolder sf = await ApplicationData.Current.LocalFolder.CreateFolderAsync("EMP", CreationCollisionOption.OpenIfExists); \nStorageFile st = await sf.CreateFileAsync("Employee.xml", CreationCollisionOption.OpenIfExists); \nawait dom.SaveToFileAsync(st);	0
22383750	22383691	Decrypting objects back to original message in sha256 encoding scheme	hash --> string	0
22974295	22972706	Get an id from a dataGridView	private void dg_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n    Console.WriteLine("Clicked row: " + e.RowIndex);\n    Console.WriteLine("Clicked column: " + e.ColumnIndex);\n    Console.WriteLine("Cell value: " + dg.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);\n}	0
5581157	5581086	How to change font for concrete TreeListNode?	using DevExpress.XtraTreeList;\n\nprivate void treeList1_NodeCellStyle(object sender, GetCustomNodeCellStyleEventArgs e)\n{\n  // Modifying the appearance settings used to paint the "Budget" column's cells\n  // whose values are greater than 500,000 .\n  if (e.Column.FieldName != "Budget") return;\n  if (Convert.ToInt32(e.Node.GetValue(e.Column.AbsoluteIndex)) > 500000)\n  {\n    e.Appearance.BackColor = Color.FromArgb(80, 255, 0, 255);\n    e.Appearance.ForeColor = Color.White;\n    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);\n  }\n}	0
24819867	24819799	LINQ : Group by Multiple Columns with Maximum for one column	from prd in Entities.Products\nwhere prd.prdEnabled == true\ngroup prd by prd.prdCode into gcs \norderby gcs.Key\nselect new { prdCode = gcs.Key, prdID= gcs.Max(g => g.prdID) }	0
14557130	14557091	How to export mvc table data to excel?	public ActionResult ExportToExcel()\n{\n    Response.AddHeader("Content-Type", "application/vnd.ms-excel");\n    return PartialView("_Table");\n}	0
15890074	15889966	make server-client work unlimitedly	while(true)\n{\n       byte[] buffer = new byte[100];\n       s.Receive(buffer);\n       //Do something with data...\n}	0
7927220	7927031	splliting a complex string in 3 parts	string result = "-3.546714E-10A,+0.000000E+00,+5.120000E+02\n";\nvar parts = result.Split(',');\n\ndouble current = double.Parse(parts[0].Remove(parts[0].Length - 1),\n                        NumberStyles.AllowExponent | NumberStyles.Number);\ndouble time = double.Parse(parts[1],\n                        NumberStyles.AllowExponent | NumberStyles.Number);	0
21479229	21468651	Grab SelectedValue of Dropdownlist in Gridview	protected void btn_Clicked(object sender, EventArgs e)\n{\n    int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;\n    DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));\n    //Continue the method\n}	0
21389493	21389337	Binding data to gridview not showing grid asp	dropGridView.DataSource = dt;\ndropGridView.DataBind();	0
5444205	5439442	How to get data from listview/gridview and populate another listview/gridview?	private void ProductsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n    {\n        //moves items from top grid to bottom grid\n        OrderContents.Items.Add(ProductsList.SelectedValue);   \n    }	0
13495562	13495528	How do I write this loop as a single line?	lstAllMonsters = dsAllMonsters.Tables[0].Rows\n   .Cast<DataRow>()\n   .Select(r => r["pokemonId"].ToString())\n   .ToList();	0
8431789	8414324	convert svg to image programatically	string svgFileName = HttpContext.Current.Server.MapPath("sample.svg");\nstring PngRelativeDirectory = "C:\\";\nstring pngName = "svgpieresult.png";\nstring pngFileName = HttpContext.Current.Server.MapPath(pngName);\n\n\n/* ignored assume sample.svg is in the web app directory\nusing (StreamWriter writer = new StreamWriter(svgFileName, false))\n{\n    writer.Write(svgXml);\n}\n */\n\nstring inkscapeArgs = string.Format(@"-f ""{0}"" -e ""{1}""", svgFileName, pngFileName);\n\nProcess inkscape = Process.Start(\n  new ProcessStartInfo( "C:\\Program Files\\inkscape\\inkscape.exe", inkscapeArgs));\n\ninkscape.WaitForExit(3000);\n//Context.RewritePath(pngName);\nthis.Response.Redirect(pngName);	0
14644083	14640518	How to write a query to check database value with session value	public ActionResult Index()\n{          \n    var user = Session["User"];\n    using (var db = new YourEntity())\n    {\n        var data = from u in db.EmployeeTabs.Where(p => p.EmpName == user).Select(v => v.Designation);\n        if (data == null)\n        {\n           return RedirectToAction("Register");\n        }\n\n        Switch(data.First().Designation)\n        {\n           case "Receptionist":\n               return RedirectToAction(Register);\n        }\n   }\n\n   return View();\n}\n\npublic public ActionResult Register()\n{\n    return View();\n}	0
19668241	19668074	Make dapper SQL be syntax colorized	This Visual Studio 2010 extension adds basic SQL syntax highlighting (keywords, functions and variables) to string literals.	0
28656518	28656497	How to handle SQL Server NULL values	Signature  = dr["Signature"] != DBNull.Value ? (string)dr["Signature"] : "No value",\nLikes = dr["Likes"] != DBNull.Value ? Convert.ToInt32(dr["Likes"]) : 0,	0
5106388	5102205	How to sort items in ToolStripItemCollection?	Private Sub ResortToolStripItemCollection(coll As ToolStripItemCollection)\n    Dim oAList As New System.Collections.ArrayList(coll)\n    oAList.Sort(new ToolStripItemComparer())\n    coll.Clear()\n\n    For Each oItem As ToolStripItem In oAList\n        coll.Add(oItem)\n    Next\nEnd Sub\n\nPrivate Class ToolStripItemComparer Implements System.Collections.IComparer\n    Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare\n        Dim oItem1 As ToolStripItem = DirectCast(x, ToolStripItem)\n        Dim oItem2 As ToolStripItem = DirectCast(y, ToolStripItem)\n        Return String.Compare(oItem1.Text,oItem2.Text,True)\n    End Function\nEnd Class	0
31315092	31314835	How to clear DataGridView in C# windows forms?	dataGridView1.Columns.Clear();	0
18504617	18504548	Saving Images to a folder with a numeric system C#	bitmap.Save("C:/Users/G73/Desktop/My OVMK Photos//OpenVMK" + DateTime.Now.ToString(yyyyMMddHHmmss) + ".jpg", ImageFormat.Jpeg);	0
32461054	32460888	How to stop ReSharper from adding blank lines in my C# structs?	ReSharper -> Options -> Code Editing -> C# -> Blank Lines	0
18484441	18462095	How to diplay a web page as alert	String js = "window.open('Signature.aspx', '_blank');";\nScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Open Signature.aspx", js, true);	0
20755177	20755042	Get the data from the given specific date to 'now' by the interval of 15 minutes	var Date = Convert.ToDateTime(dr["Date_Time"]);\nDate = Date.AddMinutes(15);\nMessageBox.Show(Date.ToString());	0
7225902	7128212	Testing WPF Control Without Adding it to a Window	public static void RaiseLoadedEvent(FrameworkElement element)\n{\n    MethodInfo eventMethod = typeof(FrameworkElement).GetMethod("OnLoaded",\n        BindingFlags.Instance | BindingFlags.NonPublic);\n\n    RoutedEventArgs args = new RoutedEventArgs(FrameworkElement.LoadedEvent);\n\n    eventMethod.Invoke(element, new object[] { args });\n}	0
31574725	31544178	How can I make a file generated on a web page available to the user as a download?	protected void ExportExcelFile(object Sender, EventArgs e) { //export to excel\n        var grdResults = new DataGrid(); // REF: http://stackoverflow.com/q/28155089/153923\n        if (periodCriteria.SelectedValue == "year") {\n            grdResults = RollupDG;\n        } else {\n            grdResults = QuarterDG;\n        }\n        var response = HttpContext.Current.Response;\n        response.Clear();\n        response.Charset = String.Empty;\n        response.ContentType = "application/vnd.ms-excel";\n        response.AddHeader("Content-Disposition", "attachment; filename=GlBudgetReport.xls");\n        using (var sw = new StringWriter()) {\n            using (var htw = new HtmlTextWriter(sw)) {\n                grdResults.RenderControl(htw);\n                response.Write(sw.ToString());\n                response.End();\n            }\n        }\n}	0
7313603	7313470	How to set a struct value T from Type	ToNullable<Type.GetType(r.DataType)>()	0
29775130	29774695	Disable asp imagebutton	ImageButton b = (ImageButton)lvEmpList.FindControl("DrillUp");\nb.Visible = false;	0
20545044	20454783	Print all rows in GTK Treeview Mono	TreeIter iter;\nmyTreeView.GetIterFirst(out iter);\nfor (int i = 0; i < myTreeView.IterNChildren(); i++)\n{\n    myTreeView.GetValue(iter, ... );\n    //Do stuff.  \n    myTreeView.IterNext(ref iter);   \n}	0
12120420	12120339	How to check if a long string is a valid XML?	WebClient wc = new WebClient();\nwc.Encoding = Encoding.UTF8;\nstring data = wc.DownloadString("http://1pezeshk.com/");\ndata = data.Remove(0, data.IndexOf("<html"));\nXmlDocument xml = new XmlDocument();\nxml.LoadXml(data);	0
31782965	31782626	Command line argument from batch file containing UTF-8 character causes trouble	CHCP 1252	0
3067294	3067282	How to write the content of a dictionary to a text file?	using (var file = File.OpenWrite("myfile.txt"))\n    foreach (var entry in dictionary)\n        file.WriteLine("[{0} {1}]", entry.Key, entry.Value);	0
14918410	14918346	How to Search and find Word ( No sensitivity to upper or lower character )	string strSearch = textBox1.Text;\nXDocument xdoc;\nList<string> lstItemsForAdd;\nlstItemsForAdd = xdoc.Descendants("name")\n                        .Where(item => item.Value.IndexOf(strSearch. StringComparison.OrdinalIgnoreCase) >= 0)\n                        .Select(item => item.Value)\n                        .Take(5)\n                        .OrderBy(item => item)\n                        .ToList();	0
4138402	4138374	How to launch IE7 from a Windows Phone App?	var wbt = new WebBrowserTask();\nwbt.URL = "http://stackoverflow.com/";\nwbt.Show();	0
19089529	19089385	c# cachedependency dispose pattern	protected override void DependencyDispose()\n        {\n            CacheDependency[] array = null;\n            bool flag = false;\n            try\n            {\n                Monitor.Enter(this, ref flag);\n                this._disposed = true;\n                if (this._dependencies != null)\n                {\n                    array = (CacheDependency[])this._dependencies.ToArray(typeof(CacheDependency));\n                    this._dependencies = null;\n                }\n            }\n            finally\n            {\n                if (flag)\n                {\n                    Monitor.Exit(this);\n                }\n            }\n            if (array != null)\n            {\n                CacheDependency[] array2 = array;\n                for (int i = 0; i < array2.Length; i++)\n                {\n                    CacheDependency cacheDependency = array2[i];\n                    cacheDependency.DisposeInternal();\n                }\n            }\n        }	0
1229788	1229770	C# LINQ-TO-SQL OR-Statement in JOIN	from o in orders\njoin iA in items on o.ID equals iA.OrderA \njoin iB in items on o.ID equals iB.OrderB\nset i = (iA == null ? iB : iA)\nselect new { Order = o, Item = i }	0
3928856	3928822	Comparing 2 Dictionary<string, string> Instances	var contentsEqual = source.DictionaryEqual(target);\n\n// ...\n\npublic static bool DictionaryEqual<TKey, TValue>(\n    this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)\n{\n    return first.DictionaryEqual(second, null);\n}\n\npublic static bool DictionaryEqual<TKey, TValue>(\n    this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second,\n    IEqualityComparer<TValue> valueComparer)\n{\n    if (first == second) return true;\n    if ((first == null) || (second == null)) return false;\n    if (first.Count != second.Count) return false;\n\n    valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;\n\n    foreach (var kvp in first)\n    {\n        TValue secondValue;\n        if (!second.TryGetValue(kvp.Key, out secondValue)) return false;\n        if (!valueComparer.Equals(kvp.Value, secondValue)) return false;\n    }\n    return true;\n}	0
24525601	24524880	Dropdownlist index starts at -1	protected void Page_Load(object sender, EventArgs e)\n{\n    if(dropDownList1.SelectedIndex == 1)\n    {\n        myVariable = 1;\n    }\n    else\n    {\n        myVariable = dropDownList1.SelectedIndex;\n    }\n}	0
1178516	1178273	Connecting to a database from the beginning	using System.Data.SQLClient;\n\nnamespace YourNamespace\n{\n    public class DatabaseConnect\n    {\n         public DataType getData()\n         {\n            DataType dataObj = new DataType();\n\n            SqlConnection testConn = new SqlConnection("connection string here");\n            SqlCommand testCommand = new SqlCommand("select * from dataTable", testConn);\n            testConn.Open()\n             using (SqlDataReader reader = testCommand.ExecuteReader())\n            {\n                while (reader.Read())\n                {\n                   //Get data from reader and set into DataType object\n                }\n            }\n\n            return dataObj;\n         }\n    }\n}	0
1504369	1504301	Binding a dropdown	if (!IsPostBack)\n{\n  for(int i = 2000, i <= DateTime.Now.Year; i++)\n  {\n    MyDropDownList.Items.Add(i.ToString());\n  }\n  //Select the current year initially\n  MyDropDownList.SelectedIndex = MyDropDownList.Items.Count - 1;\n}\n\n//Later on in your Page_Load\nMyGridView.DataSource = MyMethodOfFetchingData(MyDropDownList.SelectedValue);\nMyGridView.DataBind();	0
3466665	3466556	how to make a property grid like context menu for button?	private void Button1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n {\n  if (e.Button == MouseButtons.Right)\n  {\n    PropertyGridForm f = new PropertyGridForm();\n    f.PropertyGrid.SelectedObject = Button1; // (or sender?) whatever you need\n    f.Location = e.Location;\n    f.Show(); //or ShowDialog? \n  }\n }	0
20065144	20065103	query to Combine all childlist of all parent objects in one collection	collection.SelectMany(a => a.ListChild)	0
475182	474165	validating user input tags	SELECT\nq.TechQuestionID,\nq.SubjectLine,\nq.QuestionBody\nFROM\nTag t INNER JOIN TechQuestionTag qt\nON t.TagID = qt.TagID AND qt.Active = 1\nINNER JOIN TechQuestion q\nON qt.TechQuestionID = q.TechQuestionID\nWHERE\nt.TagText = @tagText	0
4143599	4143579	Easy way to change value of bolean	return !CheckBoxOnContolOnForm.Checked;	0
11803728	11803434	C# delete column from datatable where all values are zero	DataTable dt;\nint dataWidth = 5;  //use a loop or something to determine how many columns will have data\nbool[] emptyCols = new bool[datawidth];  //initialize all values to true\nforeach(Row r in dt)\n{\n    for(int i = 0; i < dataWidth; i++)\n    {\n        if(r[i].Contents != 0))\n           emptyCols[i] = false;\n    }\n}\n\nfor(int i = 0; i < emptyCols.Length; i++)\n{\n     if(emptyCols[i])\n        dt.Columns.RemoveAt(i);\n}	0
22700387	22700300	How does OrderBy work with regard to strings in C#?	var sorted = strings2.OrderBy(x => x, StringComparer.InvariantCulture)	0
12952492	12951717	How to trigger the auto-hide icon in c#?	private Timer _timer;\nprivate int _ticks;\n\npublic Form1()\n{\n    _timer = new Timer { Interval = 1000, Enabled = true };\n    _timer.Tick += TimerTick;\n\n    Activated += Form1_Activated;\n    MouseMove += Form1_MouseMove;\n    //notifyIcon1 is an icon set through the designer\n    notifyIcon1.MouseMove += NotifyIcon1MouseMove;\n}\n\nprotected void TimerTick(object sender, EventArgs e)\n{\n    //After 5 seconds the app will be hidden\n    if (_ticks++ == 5)\n    {\n        WindowState = FormWindowState.Minimized;\n        Hide();\n        _timer.Stop();\n        _ticks = 0;\n    }\n}\n\nprotected void NotifyIcon1MouseMove(object sender, MouseEventArgs e)\n{\n    WindowState = FormWindowState.Normal;\n    Show();\n    _ticks = 0;\n    _timer.Start();\n}\n\nprotected void Form1_MouseMove(object sender, MouseEventArgs e)\n{\n    _ticks = 0;\n}	0
9387915	9387850	Append information to Excel file on GridView Export in ASP.NET C#	Response.Write(style);\nResponse.Write("Pretty Excel Export File\n");\nResponse.Write("Generated on " + DateTime.Now.ToShortDateString() + "\n\n");\nResponse.Write(swriter.ToString());\nResponse.End();	0
39467	39447	How can I expose only a fragment of IList<>?	IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {\n    foreach ( T item in input )\n        if (  /* criterion is met */ )\n            yield return item;\n}	0
6777828	6777692	How to return the newest file in a directory as a string?	string res = Directory.EnumerateFiles(direcory)\n    .OrderByDescending(f => new FileInfo(f).CreationTime).FirstOrDefault();	0
17817978	17817932	Converting a LINQ result to 2D string array	string[][] teams = db.Teams.Where(t => t.isActive).Select(t => new[] {t.TeamID, t.TeamName}).ToArray();	0
18657886	18657802	How to use local variables in a lambda expression	HashSet<string> inconsistantIDs = new HashSet<string>(\n           pr.Select(p => p.id).Where(p => \n                  {\n                    var count = tem.FindAll(t => t.id == p).Count;\n                    return count == 0 || count % 2 != 0;\n                  }\n           ));	0
15653426	15653301	Size of image increases after cropping	// Construct a bitmap from the button image resource.\nBitmap bmp1 = new Bitmap(typeof(Button), "Button.bmp");\n\n// Save the image as a GIF.\nbmp1.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Gif);	0
10914801	10914610	Set a usercontrol as content to another window's content at run time	mywindow.Content = new MyuserControl();	0
23903951	23903790	How to fill dropdowlist in ASP.NET with two range of the year	var startYear = 2013;\nvar rangeCount = 10;\nvar ranges = Enumerable.Range( 2013, rangeCount ).Select( y => y + "-" + ( y + 1 ) );\n\nyourDropDownList.DataSource = ranges;\nyourDropDownList.DataBind();	0
9380249	9380214	`using` statement with uninitialized variable not possible, nor is finally, so how to properly dispose it?	DisposableObject worker = null;\ntry\n{\n    if(/*condition*/)\n        worker = new DisposableObject(/*args*/)\n    else\n        worker = new DisposableObject(/*other args*/)\n    worker.DoStuff();\n}\nfinally\n{\n    if(worker != null)\n        worker.Dispose();\n}	0
13297831	13295161	Is it possible to extent FluentApiMapper to set the default value ?	protected override void Seed(DbContext context)\n{\n    context.Database.ExecuteSqlCommand(\n        "ALTER TABLE [T70_AccountService] ADD DEFAULT (getutcdate()) FOR [Created]");\n}	0
27563225	27563151	C# convert string array output to double	var units = Convert.ToDouble(product[1]);	0
9758250	9758146	asp.net lock page method until action finished	static object lockObject = new Object();\nstatic bool inProgress = false;\n\nstatic void MyProcess()\n{\n  if(inProgress) return;\n\n  lock(lockObject)\n  {\n    try{\n      inProgress = true;\n      // critical code here\n    }\n    finally\n    {\n      inProgress = false;\n    }\n  }\n}	0
1832129	1832120	c#, listbox, stackOverflow exception	protected override void OnSelectedIndexChanged(EventArgs e)\n{                       \n       CancelEventArgs cArgs = new CancelEventArgs();\n       OnSelectedIndexChanged(cArgs); // Clearly calling yourself indefinitely.\n       //...\n}	0
24986370	24986294	Reading an XML document with XMLDocument C# 'password' string not returning	wifiProfile.Load(path);\n\nXmlNamespaceManager mgr = new XmlNamespaceManager(wifiProfile.NameTable);\nmgr.AddNamespace("ns", "http://www.microsoft.com/networking/WLAN/profile/v1");\n\nXmlNodeList sharedKeyNodes = wifiProfile.SelectNodes("//ns:WLANProfile/ns:MSM/ns:security/ns:sharedKey",mgr);	0
8089239	8089018	Insert only those objects that are not already in the database	var tags = context.Tags.Where(t => t.ItemId = itemId) // search via your item\n   .Select(t => t.TagValue);\n\nvar newTags = myItem.Tags.Where(t => !tags.Contains(t.TagValue));\nvar existingTags = myItem.Tags.Where(t => tags.Contains(t.TagValue));	0
12671333	12652115	How to print RDLC Report in Firefox	Warning[] warnings;\nstring[] streamIds;\nstring mimeType = string.Empty;\nstring encoding = string.Empty;\nstring extension = string.Empty;\nstring filename = "YourFileName";\n\n\n// Setup the report viewer object and get the array of bytes\nReportViewer viewer = new ReportViewer();\nviewer.ProcessingMode = ProcessingMode.Local;\nviewer.LocalReport.ReportPath = "YourReportHere.rdlc";\n\n\nbyte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);\n\n\n// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.\nResponse.Buffer = true;\nResponse.Clear();\nResponse.ContentType = mimeType;\nResponse.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension);\nResponse.BinaryWrite(bytes); // create the file\nResponse.Flush(); // send it to the client to download	0
31981271	31981187	How to bring a Windows Form on top?	public void BringToTop()\n{\n    //Checks if the method is called from UI thread or not\n    if (this.InvokeRequired)\n    {\n        this.Invoke(new Action(BringToTop));\n    }\n    else\n    {\n        if (this.WindowState == FormWindowState.Minimized)\n        {\n            this.WindowState = FormWindowState.Normal;\n        }\n        //Keeps the current topmost status of form\n        bool top = TopMost;\n        //Brings the form to top\n        TopMost = true;\n        //Set form's topmost status back to whatever it was\n        TopMost = top;\n    }\n}	0
8015974	8015926	User login in partial view with error display	return View("LoginViewNameGoesHere")	0
31018790	31017499	Displaying progress of processing collection	Command = ReactiveCommand.CreateAsyncObservable(_ => {\n\n  return items.ToObservable()\n              .SelectMany(RunSlowProcess, \n                         (item, itemIndex, processed) => itemIndex);\n\n})\n.ObserveOn(RxApp.MainThreadScheduler)\n.Subscribe(i => Progress = i);	0
3864342	3862466	How to use ISynchronizeInvoke without a reference to the Form	MainForm main = new MainForm();\nEnvironmentService.UI = main;\nEnvironmentService.UIContext = SynchronizationContext.Current;\nApplication.Run(main);	0
29511309	29511256	c# write anywhere in a file	SetLength()	0
27640938	27640795	Set an initial hour to the timer component	private void SetTimer() {\n        var now = DateTime.Now;\n        var next = now.Date.AddHours(now.Hour + 1);\n        var msec = (next - now).TotalMilliseconds;\n        timer1.Interval = (int)msec;\n        timer1.Enabled = true;\n    }\n\n    private void timer1_Tick(object sender, EventArgs e) {\n        SetTimer();\n        // etc...\n    }	0
20063425	20049547	Declare non column member in class used for table sqlite Windows Phone 8	[Ignore]	0
29645258	29642068	How to get EF 6 to handle DEFAULT CONSTRAINT on a database during INSERT	public class DBUpdateTest\n/* public partial class DBUpdateTest*/ //version for database first\n{\n   private _DefValue1 = 200;\n   private _DefValue2 = 30;\n\n   public DbUpdateTest()\n   {\n      DefSecond = DateTime.Second;\n   }\n\n   public DefSecond { get; set; }\n\n   public DefValue1\n   {\n      get { return _DefValue1; }\n      set { _DefValue1 = value; }\n   }\n\n   public DefValue2\n   {\n      get { return _DefValue2; }\n      set { _DefValue2 = value; }\n   }\n}	0
33347784	33312769	Display comma list in gridview from child entity	public partial class DEALER\n{\n    public string ModelList { \n        get \n        {\n            if (MODEL_NAME != null)\n            {\n                return string.Join(",", DEALER_MODEL.Select(i => i.MODEL_NAME.ToString()).ToArray());\n            }\n            return "";\n        }\n    }\n}	0
12607406	12607356	How to cast object type based on parameter?	public static T GetDataFromFile<T>(string path) where T : class\n{ \n    if (!File.Exists(path)) \n    { \n        return null; \n    } \n\n    try \n    { \n        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T)); \n        StreamReader tempReader = new StreamReader(path); \n        T result = (T)x.Deserialize(tempReader); \n        tempReader.Close(); \n        return result; \n    } \n    catch \n    { \n        return null; \n    } \n}	0
24813118	24812744	TFS SDK 2013 Get Team names in a given team project	this.teamService = this.teamProjectCollection.GetService<TfsTeamService>();\n\npublic List<string> ListTeams()\n{\n    var teams = this.teamService.QueryTeams(this.projectInfo.Uri);\n    return (from t in teams select t.Name).ToList();\n}	0
6753516	6746345	How to change position/size of the Shape Data Window	Application.ActiveWindow.Windows.ItemFromID(visWinIDPanZoom)	0
26154483	23863210	How do you find textbox controls by their names from a string in C#?	for (int i = 0; i < 111; i++)\n        {\n            string currentbox = "TextBoxT" + i.ToString();\n            TextBox currentTextBox = (TextBox)this.FindControl(currentbox);\n            currentTextBox.BackColor = getColour(time.moments[i]);\n\n        }	0
5028060	5028027	Get Dates between Ranges, c#	var allDates = Enumerable.Range(0, int.MaxValue)\n                         .Select(x => fromDate.Date.AddDays(x))\n                         .TakeWhile(x => x <= toDate.Date);	0
30462547	30462199	concurrent user read and update to mysql using c#	public class Dal\n{\n    private static object syncObject = new object();\n\n    public static void InsertUpdate(...) \n    {\n        lock (syncObject)\n        {\n            // 1. Get the document type = "inv" , current year and current month,\n            // 2. If not found. create a new document type , year and month record with the running number 0001.\n            // 3. if found. running + 1.\n        }\n    }\n}	0
24637337	24637287	Getting Specific Cell Value from GridView	string txt = specialPricingSheetGridView.Rows[4].Cells[2].Text;	0
12577835	12577511	Leading illegal characters after XSLT transformation	ms.Position	0
8611799	8611705	Getting the clicked mouse coordinates from a Image Box in C#/WPF	Point pos = Mouse.GetPosition(myElement);	0
9892764	9892690	Dynamic Lambda Expression For Filtering	var data = GetData();\n\nvar sourceFilter = SourceDropDown.Value;\nif (!string.IsNullOrEmpty(sourceFilter))\n    data = data.Where(d => d.Source == sourceFilter);\n\nvar categoryFilter = CategoryDropDown.Value;\nif (!string.IsNullOrEmpty(categoryFilter))\n    data = data.Where(d => d.Category == categoryFilter);\n\nDateTime startDateFilter, endDateFilter;\nif (DateTime.TryParse(TxtStartDate.Text, out startDateFilter) &&\n    DateTime.TryParse(TxtEndDate.Text, out endDateFilter))\n    data = data.Where(d => d.DT >= startDateFilter && d.DT <= endDateFilter);\n\nreturn data.ToList();	0
26920414	26919415	How to troubleshooting a MySQL fatal error? C# front end	string query = string.Format("SELECT * FROM MESSAGE WHERE {0}", string.Join(" AND ", wheres));\n                conn.Open();\n                MySqlCommand cmd = new MySqlCommand(query, conn);\n                cmd.Parameters.Add(new MySqlParameter(@"PatientMob", MySqlDbType.VarChar)).Value = PatientMobile.Text;\n                cmd.Parameters.Add(new MySqlParameter(@"UserID", MySqlDbType.VarChar)).Value = UserID.Text;	0
10095315	10095141	Bind a property to a custom control	var age = People[ddlTest.SelectedIndex].Age;	0
1953853	1953839	C# accessing folder/files thru webservice	System.IO	0
15712179	15711985	How to display float and double values in 0,00E+00 form?	double value = 12345.6789;\nConsole.WriteLine(value.ToString("E", CultureInfo.InvariantCulture));\n// Displays 1.234568E+004\n\nConsole.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture));\n// Displays 1.2345678900E+004\n\nConsole.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture));\n// Displays 1.2346e+004\n\nConsole.WriteLine(value.ToString("E", CultureInfo.CreateSpecificCulture("fr-FR")));\n// Displays 1,234568E+004	0
8970112	8969751	Linq-to-SQL Timeout	using (MainContext db = new MainContext())\n{\n    db.CommandTimeout = 3 * 60; // 3 Mins\n}	0
6039412	6039383	In my typed dataset, will the Update method run as a transaction?	using (TransactionScope ts = new TransactionScope())\n{\n     // your old code here\n     ts.Complete();\n}	0
7293962	7283541	WIF return to the RP application	var claims = new List<Claim>\n    {\n        new Claim(WSIdentityConstants.ClaimTypes.Name, User.Identity.Name),\n        new Claim(ClaimTypes.AuthenticationMethod, FormsAuthenticationHelper.GetAuthenticationMethod(User.Identity))\n    };\n\n        var identity = new ClaimsIdentity(claims, STS.TokenServiceIssueTypes.Native);\n        var principal = ClaimsPrincipal.CreateFromIdentity(identity);\n\n        FederatedPassiveSecurityTokenServiceOperations.ProcessRequest(\n            Request,\n            principal,\n            StarterTokenServiceConfiguration.Current.CreateSecurityTokenService(),\n            Response);	0
15688851	15576603	Getting interface methods from a dynamically loaded class in .NET	Type myClassType = Type.GetTypeFromProgID("MyClass.Myclass.1");\nmyClassIntrface classObj = \n   Activator.CreateInstance(myClassType) as myClassIntrface;\nclassObj.CallSomeInterfaceMethod();	0
2393966	2393887	How to replace special characters with their equivalent (such as " ? " for " a") in C#?	var decomposed = "???".Normalise(NormalizationForm.FormD);\nvar filtered = decomposed.Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark);\nvar newString = new String(filtered.ToArray());	0
3158253	3157788	How can i use FindControl method in asp.net?	protected void Button1_Click(object sender, EventArgs e) \n        { \n          //  SetRecursiveTextBoxAndLabels(PlaceHolder1); \n            CreateForm creater = new CreateForm(); \n            creater.Holder = PlaceHolder1; \n            creater.SetAccessForm(); \n\n            if (PlaceHolder1.Controls.Count > 0) \n            { \n                foreach (Control item in PlaceHolder1.Controls) \n                { \n                     if (item is TextBox)\n                         TextBox t1=(TextBox)PlaceHolder1.FindControl(item.ID);\n                } \n            } \n        }	0
20524107	20522210	How to Convert Datetime to OracleTimeStamp	Command.Parameters.Add("return", OracleDbType.Varchar2, 1000, null, ParameterDirection.ReturnValue);	0
18910225	18909536	Linq Grouping with Include	var idQuery = ctx.ItemMovements\n    .GroupBy(e => e.ItemID)\n    .Select(g => new { ItemID = g.Key, QuantitySum = g.Sum(Quantity) } )\n    .Where(e => e.QuantitySum > 10)\n    .Select(e => e.ItemID);\n\nvar query = ctx.ItemMovements\n    .Include("Item")\n    .Where(e => idQuery.Contains(e.ItemID));	0
23585165	23583754	Changing Menu active class with Master Page	Request.Url.AbsoluteUri	0
24498218	24498191	C# - Lambda / LINQ - Conversion From Dictionary<string, string>[] to List<string[]>	arrayOfStringDictionaries.Select(dict => dict.Values.ToArray()).ToList();	0
3425383	3425349	Enum stubs in Interfaces?	public interface ISampleInterface \n{    \n    MyEnum FileType\n    {\n        get;\n    }\n}	0
26197343	26197190	Finding words in array?	void Main()\n{\n    string[] search = { "CAKE", "COFFEE", "TEA", "HONEY", "SUGAR", "CINNEMON" }; \n    string[] wordsToFind = { "CAKE", "TEAPOT" }; \n\n    List<String> wordCollected = search.Where(s => s == wordsToFind[0]).ToList();   \n    wordCollected.Dump();\n    wordCollected = search.Where(x => wordsToFind.Any(w => w == x)).ToList();   \n    wordCollected.Dump(); \n}	0
13227677	13226609	How to set the starting position for table in pdf generated by iTextSharp?	Private mywriter As PdfWriter\n        Dim Theight = Table.CalculateHeights\n        Dim DirectC As PdfContentByte = mywriter.DirectContent\n        Dim templ = DirectC.CreateTemplate(Table.TotalWidth, Theight)\n        Table.WriteSelectedRows(0, -1, 0.0F, Theight, templ)\n        Dim myimage = Image.GetInstance(templ)\n\n        Dim CenterH = (Doc.Top + Doc.BottomMargin) / 2\n\n        Dim NewPosH = CenterH - myimage.Height / 2\n\n        Dim CenterW = mywriter.PageSize.Width / 2\n        Dim NewPosW = CenterW - myimage.Width / 2\n\n        myimage.SetAbsolutePosition(NewPosW, NewPosH)\n        DirectC.AddImage(myimage)	0
6918523	6918490	Calling function from a class in project 1 from project 2	using MyClass=Project1.MyClass;  // A\n\nusing Project1.MyClass;  // B	0
18760398	18747149	Automapper: Convert an int to a string	Mapper.CreateMap<Job, JobViewModel>()\n              .ForMember(d => d.JobNumberFull,\n                         expression =>\n                         expression.ResolveUsing(j => string.Format("{0}-{1}-{2}", j.Prefix, j.JobNumber, j.Year)));	0
20075446	20074917	How to show parsed xml in TextBlock in WPF?	protected string FormatXml(string xmlFile)\n{\n    XmlDocument doc = new XmlDocument();\n    FileStream fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);\n    doc.Load(fs);\n    StringBuilder sb = new StringBuilder();\n    System.IO.TextWriter tr = new System.IO.StringWriter(sb);\n    XmlTextWriter wr = new XmlTextWriter(tr);\n    wr.Formatting = Formatting.Indented;\n    doc.Save(wr);\n    wr.Close();\n    return sb.ToString();\n}	0
20485249	20485226	Trying to do somthing multiple times	string HTML = null;\n        for (int i = 0; i < 3; i++)\n        {\n            HTML = TryGetPageHtml(link, getrandomproxy());\n            if (HTML != null)\n                break;\n        }	0
15555073	15554847	How to set up a connection to a database for a program that will be distributed	Data Source=\\servername\sharename\path\to\data\file.accdb;	0
25140545	25139915	Loop through a specific node of XML with XmlNodeList	foreach (XmlNode result in info.SelectNodes("./CRM/result"))\n{\n    string Key = result.Attributes["key"].Value;\n    string Value = result.Attributes["value"].Value;\n    .....\n    .....\n}	0
6530984	6530957	Make end date value show exactly 1 year after user inputs start date and account for leap years	dateTimePicker1.Value.AddYears(1).AddDays(-1);	0
5794174	5793783	How do I use XPath to get the value of an attribute in c#?	var doc = new XPathDocument(stream);\nvar nav = doc.CreateNavigator();    \nforeach (XPathNavigator test in nav.Select("test"))\n{\n    string type = test.SelectSingleNode("@type").Value;\n    string nice = test.SelectSingleNode("nice").Value;\n    Console.WriteLine(string.Format("Type: {0} - Nice: {1}", type, nice));\n}	0
13172786	13137992	not able to logout from facebook using facebook c# sdk	public ActionResult LogOut(string accessToken)\n    {\n        var oauth = new FacebookClient();\n\n        var logoutParameters = new Dictionary<string, object>\n              {\n                 {"access_token", accessToken},\n                  { "next", "http://localhost:8691" }\n              };\n\n        var logoutUrl = oauth.GetLogoutUrl(logoutParameters);\n\n        return Redirect(logoutUrl.ToString());\n    }	0
5135774	5135760	Drawing Bitmap with unsafe per pixel access results in empty image	UnlockBits()	0
6215097	6214701	C# binary data from port convert to hex string	string Data = "123";\n    string hex = "";\n    foreach (char c in Data)\n    {\n        hex += String.Format("{0:x2}", (byte)c);\n    }	0
1167089	1167071	What's the best way to set all values in a C# Dictionary<string,bool>?	foreach (var key in dict.Keys.ToList())\n{\n    dict[key] = false;\n}	0
29768982	29768200	C# sorting multidimensional array by multiple columns	using System;
\nusing System.Collections.Generic;
\nusing System.Linq;
\nusing System.Text;
\n
\nnamespace ConsoleApplication19
\n{
\n    class Program
\n    {
\n        static void Main(string[] args)
\n        {
\n            List<List<int>> multiarray = new List<List<int>>{    
\n                new List<int> { 8, 63  },
\n                new List<int>  { 4, 2   }, 
\n                new List<int>  { 0, -55 }, 
\n                new List<int>  { 8, 57  }, 
\n                new List<int>  { 2, -120}, 
\n                new List<int>  { 8, 53  }  
\n            };
\n           
\n
\n            List<List<int>> sortedList = multiarray.OrderBy(x => x[1]).OrderBy(y => y[0]).ToList();
\n
\n        }
\n    }
\n}	0
12767868	12767853	how to populate asp:DropDownList from C# side	ddl.Items.Add(new ListItem("Your Text", "0"));	0
33037345	33037133	.Net MVC5 - Validation to check if string being entered already exists in the json file	[AllowAnonymous]\n public async Task<JsonResult> doesProductExist(string Product)\n {\n    var result = \n    await userManager.FindByNameAsync(Product) ?? \n    await userManager.FindByEmailAsync(Product);\n    return Json(result == null, JsonRequestBehavior.AllowGet);\n }	0
26056233	26054830	ListAdapter On Xamarin for Android	void _DataService_DownloadCompleted(object sender, EventArgs e)\n        {\n            var raw = ((DownloadEventArgs)e).ResultDownload;\n            if(raw!=null)\n            {\n                _DataTopStories = JsonConvert.DeserializeObject<TopStoriesViewModel>(raw);\n                RunOnUiThread(() => CreateList());\n                //CreateList();\n                Log.Info("ds", "download completed");\n            }\n        }	0
10955034	10953771	Loading all files in a directory onto webpage ASP.NET	Directory.GetFiles(Path.Combine(myPath, @"All Plots 1 Year\"), "*" + Request.QueryString["model"] + "*")	0
7840172	7839953	Access site directory path with streamreader in asp.net	string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;\n    StreamReader sr = new StreamReader(filePath + @"\Questions.aspx");	0
4766790	4766778	How to encode U+FFFD in order to do a replace?	string s = s.Replace('\uFFFD','\'');	0
29850793	29850559	Change XML structure with Linq and having a foreach issue	MyClass myObject = new MyClass;\nXmlSerializer ser = new XmlSerializer(myObject.GetType());\nusing (FileStream fs = new FileStream(FilePath, FileMode.Open))\n{\n    XmlTextReader reader = new XmlTextReader(fs);\n    myObject = (MyClass)ser.Deserialize(reader);\n}	0
13937677	13936892	WCF string method that also serves a download with response.write - Only working in IE so far	/******************************************/\nHttpContext.Current.Response.ClearHeaders();\nHttpContext.Current.Response.Clear();\n/******************************************/\n\nHttpContext.Current.Response.ContentType = "text/csv";\nHttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=ImportErrors.csv");\n//rest of your code sample	0
20249416	20249318	How to start a loop upon button click, then stop it upon same button click again	private void timer1_Tick(object sender, EventArgs e)\n    {\n        // Change your image here\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        // Toggle the timer's enabled state\n        timer1.Enabled = !timer1.Enabled;\n    }	0
61257	61143	Recursive lambda expression to traverse a tree in C#	class TreeNode\n{\n    public string Value { get; set;}\n    public List<TreeNode> Nodes { get; set;}\n\n\n    public TreeNode()\n    {\n        Nodes = new List<TreeNode>();\n    }\n}\n\nAction<TreeNode> traverse = null;\n\ntraverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};\n\nvar root = new TreeNode { Value = "Root" };\nroot.Nodes.Add(new TreeNode { Value = "ChildA"} );\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" });\nroot.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" });\nroot.Nodes.Add(new TreeNode { Value = "ChildB"} );\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" });\nroot.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" });\n\ntraverse(root);	0
16618308	16618070	How to find out the font size of window caption?	SystemFonts.CaptionFontSizeKey	0
28314686	28288551	How i can see the products (or items) from a SaleItemLineDetail from Quick Books?	QueryService<Invoice> bill1QueryService = new QueryService<Invoice>(context);\nInvoice bill11 = bill1QueryService.ExecuteIdsQuery("select * from Invoice").FirstOrDefault<Invoice>();\n\n\n SalesItemLineDetail a1 = (SalesItemLineDetail)bill11.Line[0].AnyIntuitObject;\n\n                        if(a1.TaxCodeRef.Value=="TAX")\n                        {\n                            string taxCodeid = a1.ItemRef.Value;\n                            object unitprice = a1.AnyIntuitObject;\n                            decimal quantity = a1.Qty;\n                        }	0
16695445	16693234	List users by a category	var Sql = "SELECT * from Locations Order by Branch";\n\n        pcm.CommandText = Sql;\n        prs = pcm.ExecuteReader();\n        var rowcount = 0;\n        var prvBranch="";\n\n        while (prs.Read())\n        {\n            rowcount++;       \n        if(prvBranch!=prs["Branch"].ToString())\n        {%>\n            <h4><%= prs["Branch"].ToString() %></h4>\n        <%} %>\n        <%= prs["Name"].ToString() %>\n\n    <%\n        prvBranch = prs["Branch"].ToString();\n\n        }\n        prs.Close();\n        pcn.Close();\n    %>	0
23415104	23411822	How to get Publish location in code when using ClickOnce?	if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)\n{\n     var deploy = System.Deployment.Application.ApplicationDeployment.CurrentDeployment;\n     var uri = deploy.ActivationUri;\n     // Also:\n     //deploy.DataDirectory\n     //deploy.UpdateLocation\n}	0
33309832	33309189	Delete all values within a registry key using C#	string keyPath64Bit = "SOFTWARE\\Wow6432Node\\Krondorian";\n        RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);\n        RegistryKey key64Bit = localMachine.OpenSubKey(keyPath64Bit, true);\n\n        if (key64Bit != null)\n        {\n            var namesArray = key64Bit.GetValueNames();\n            foreach (string valueName in namesArray)\n            {\n                key64Bit.DeleteValue(valueName);\n            }\n        }	0
22208039	22201689	I want to throw a star in the direction of drag done by user	Vector2 startSwipePos; // When the user starts swiping\nVector2 endSwipePos; // When the user ends swiping, define those two\nVector2 difference = endSwipePos - startSwipePos;\ndifference.Normalize(); // Get only the direction, you don't have to do this,\n                        // you can also make the speed less instead.\nVector2 velocity = difference * (SPEED HERE IN FLOAT);\npos += velocity;	0
26628586	26275435	Accumulate values in chart series - WPF DevExpress	foreach (var item in lstSPCPrintID)            \n{\n    string seriesName = String.Format("Position: {0}", Convert.ToString(item));\n    LineStackedSeries2D series = new LineStackedSeries2D();\n    series.ArgumentScaleType = ScaleType.Numerical;\n    series.DisplayName = seriesName;\n    series.SeriesAnimation = new Line2DUnwindAnimation();\n\n    var meas = from x in lstSPCChart\n               where x.intSPCPrintID == item\n               select new { x.dblSPCMeas };\n\n    var measDistinctCount = meas.GroupBy(x => x.dblSPCMeas).Select(group => new { Meas = group.Key, Count = group.Count() }).OrderBy(y => y.Meas);\n\n    foreach (var item2 in measDistinctCount)\n    {\n        series.Points.Add(new SeriesPoint(item2.Meas, item2.Count));\n    }\n\n    dxcSPCDiagram.Series.Add(series);\n\n    series.Animate();\n}	0
11228514	11228273	Asp.net generic data binding method for Web UI controls	public static void  AnyUIObjectDataBinder(ListControl anyUIcontrol, int id, string dataTextField, string dataValueField)\n{\n    anyUIcontrol.DataSource = GetList(id);\n    anyUIcontrol.DataTextField = dataTextField;\n    anyUIcontrol.DataValueField = dataValueField;\n    anyUIcontrol.DataBind();\n}	0
5346028	5345903	How to wait for Textbox to finish rendering?	Textbox.AppendText("New text\r\n");\nApplication.DoEvents();	0
2744853	2744840	Invoking a URL - c#	var request = (HttpWebRequest)WebRequest.Create(url);\nrequest.GetResponse();	0
2072750	2072727	How should I save my data?	DateTime time	0
2009603	2009057	download file from server asp.net	string filepath = Server.MapPath("test.txt");	0
23810790	23809866	How do I differentiate between processes with the same name	using (ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = 1234"))\n{\n    foreach (ManagementObject mo in mos.Get())\n    {\n        Console.WriteLine(mo["CommandLine"]);\n    }\n}	0
24806775	24805271	Select a node based on name in html agility pack	doc.DocumentNode.SelectSingleNode("//form[@name='name1']")	0
8617855	8617792	Can't read a simple xml file	var doc = XDocument.Parse(xml);\n\nvar result = doc\n    .Root.Elements("song")\n    .Select(e => \n        new { Name = (string)e.Element("Name"), Artist = (string)e.Element("Artist") });\n\nforeach (var val in result)\n{\n    Console.WriteLine(val);\n}	0
20776897	15846355	How to use MessagePack in C#?	public byte[] Serialize<T>(T thisObj)\n{\n    var serializer = MessagePackSerializer.Create<T>();\n\n    using (var byteStream = new MemoryStream())\n    {\n        serializer.Pack(byteStream, thisObj);\n        return byteStream.ToArray();\n    }\n}\n\npublic T Deserialize<T>(byte[] bytes)\n{\n    var serializer = MessagePackSerializer.Create<T>();\n    using (var byteStream = new MemoryStream(bytes))\n    {\n        return serializer.Unpack(byteStream);\n    }\n}	0
20519907	20519423	Regex parsing of a multi-line entry with optional newline characters	([\w ]\S+\/*)*\w([\w]+\.(\w+))\n\nusing System;\nusing System.Text.RegularExpressions;\n\npublic class Test\n{\n    public static void Main()\n    {\n        string patternDir = @"([\w ]\S+\/*)*\w([\w]+\.(pj))";\n\n        string pathDir = @"d:\ARCTest\_MyProject\Sources\CMInterfaces\project.pj subsandbox ";\n        string pathFile = @"CMAccess.sln archived";\n\n        Console.WriteLine((Regex.IsMatch(pathDir,patternDir))? "It's dir!" : "It's not a dir");\n        Console.WriteLine((Regex.IsMatch(pathFile,patternDir))? "It's dir!" : "It's not a dir");\n\n        Console.ReadKey();\n    }\n}	0
17040207	17040149	Interface with generic function	public interface ITableData<T> where T : TableData\n{\n    List<T> ListAll();\n    void Insert(Object o);\n}\n\npublic class BookData : ITableData<Book>\n{\n    public List<Book> ListAll()\n    {\n        List<Book> bookList =XXXXXX;\n        //some code here\n        return bookList;\n    }\n}	0
12459328	12455867	Get Label text-value from Listview label in C#	protected void imgbtn5_Click(object sender, EventArgs e)\n{\n    Session["theme"] = lbl5.Text;\n    foreach (ListViewItem item in theme5.Items)\n    {\n        Label country = (Label)item.FindControl("lblcountry");\n// here insted of country.ToString() you Should use \n        Session["country"] = country.Text.ToString();        \n        Label price = (Label)item.FindControl("lblprice");\n        Session["price"] = price.Text.ToString();         \n    }       \n}	0
330484	330471	c# why cant a nullable int be assigned null as a value	int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));	0
22211954	22211829	Multiple string comparsions	var strings = new List<string>{a,b,c,d};\n\nif(strings.All(s=>s == "something")){\n}	0
13056351	13056324	C# LINQ get objects with field value that do not match a string array blacklist	var objects = \n      myObjects.Where(m => !namesToExclude.Contains(m.Name)).ToList();	0
8289936	8289681	Get handle of NumericUpDown's edit part	var box = (TextBox)numericUpDown1.Controls[1];	0
19008094	18988679	How to get the Activities of a Workflow from within the rehosted WorkflowDesigner	Found my answer :\n\n  IEnumerable<ModelItem> xyz = modelService.Find(modelService.Root, typeof(Activity));	0
5685530	5685501	How to change mdi statusstrip label from a child form	((ActualMdiParentFormType) this.MdiParent).statusStripLabel.Text = "Value";	0
20841551	20841354	How do I delete a row with specified index in datagridview	dg1.Rows.RemoveAt(i);	0
7037359	7036380	Importing from oracle database validation check	TRUNC(LOAD_DATE)	0
7514148	7514080	Syntax error in INSERT INTO statement for MS Access	string ConnString = Utils.GetConnString();\nstring SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";\nusing (OleDbConnection conn = new OleDbConnection(ConnString))\n{\n  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))\n  {\n    cmd.CommandType = CommandType.Text;\n    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);\n    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);\n    conn.Open();\n    cmd.ExecuteNonQuery();\n  }\n}	0
27354187	26359192	How to return ActionResult with specific View (not the controller name)	return View("ResetPassword", new ResetPassword\n            {\n                fields= fields\n            });	0
1775096	1775094	How to empty a List<T>?	MyList.Clear();	0
13431391	3420990	How to create Sub Item on Xml Linq	XElement xml = new XElement("MyMenu",\n    //from c in db.Orders\n    from c in db.Orders\n    orderby c.OrderID\n    select new XElement("Item",\n        c.OrderID == null ? null : new XAttribute("OrderID", c.OrderID),\n        c.ShipName == null ? null : new XAttribute("ShipName", c.ShipName),\n        c.OrderDate == null ? null : new XAttribute("OrderDate", c.OrderDate),\n        from od in db.Order_Details\n        where od.OrderID == c.OrderID\n        select new XElement("SubItem", \n            od.OrderID == null ? null : new XAttribute("OrderID", od.OrderID),\n            od.ProductID == null ? null : new XAttribute("ProductID", od.ProductID),\n            od.Quantity == null ? null : new XAttribute("Quantity", od.Quantity)\n        )\n    ));	0
7848003	7823010	Setting ACL on Exchange Mailbox	IExchangeMailbox exMb = (IExchangeMailbox)userDe.NativeObject;\n            IADsSecurityDescriptor securityDescriptor = (IADsSecurityDescriptor)exMb.MailboxRights;\n            IADsAccessControlList acl = (IADsAccessControlList)securityDescriptor.DiscretionaryAcl;\n            AccessControlEntry ace = new AccessControlEntry();\n            ace.Trustee = groupName;\n            ace.AccessMask = 1;\n            ace.AceFlags = 2;\n            ace.AceType = 0;\n\n            acl.AddAce(ace);\n            securityDescriptor.DiscretionaryAcl = acl;\n            IADsUser iadsUser = (IADsUser)userDe.NativeObject;\n            iadsUser.Put("msExchMailboxSecurityDescriptor", securityDescriptor);\n\n            iadsUser.SetInfo();	0
5050040	5049958	How to validate the given address using USPS?	///Create a new instance of the USPS Manager class\n///The constructor takes 2 arguments, the first is\n///your USPS Web Tools User ID and the second is \n///true if you want to use the USPS Test Servers.\nUSPSManager m = new USPSManager("YOUR_USER_ID", true);\nAddress a = new Address();\na.Address2 = "6406 Ivy Lane";\na.City = "Greenbelt";\na.State = "MD";\n\n///By calling ValidateAddress on the USPSManager object,\n///you get an Address object that has been validated by the\n///USPS servers\nAddress validatedAddress = m.ValidateAddress(a);	0
11428135	11427972	How to preserve default values in .net serialization	You will have to add EmitDefaultValue on you field\n\n [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, EmitDefaultValue=false)]\n    public bool Is_ActiveNull {\n\nand then \n\n[OnDeserializing]\n    void BeforeDeserialization(StreamingContext ctx)\n    {\n        this.Is_ActiveNull = false;\n    }	0
4317844	4308779	Convert CSV to XML when CSV contains both character and number data	var lines = File.ReadAllLines(@"C:\text.csv");\n\nvar xml = new XElement("TopElement",\n   lines.Select(line => new XElement("Item",\n      SplitCSV(line)\n          .Select((column, index) => new XElement("Column" + index, column)))));\n\nxml.Save(@"C:\xmlout.xml");	0
26529477	26515449	Add contact programmatically, with number phone	IDictionary<string, object> props = await contact.GetPropertiesAsync();\n   props.Add(KnownContactProperties.Telephone, "yourtelephone");\n        props.Add(KnownContactProperties.MobileTelephone, "mobileTele");\n        props.Add(KnownContactProperties.AlternateMobileTelephone, "mobileTele");\n        props.Add(KnownContactProperties.WorkTelephone, "mobileTele");\n        props.Add(KnownContactProperties.AlternateWorkTelephone, "mobileTele");	0
30720663	30697193	How to save changes to original excel file using c# interop?	private void releaseObject(object obj)\n    {\n        try\n        {\n            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);\n            obj = null;\n        }\n        catch (Exception ex)\n        {\n            obj = null;\n            MessageBox.Show("Unable to release the Object " + ex.ToString());\n        }\n        finally\n        {\n            GC.Collect();\n        }\n    }	0
32971354	32970859	Change data in repeater when date changes in .datepicker	if(IsPostBack == false)\n{\n   //code for initializing your date picker\n}	0
5911513	5911037	Two Controls Reference One-Another Correctly	othercontrol.SelectedChanged -= othercontrol_SelectedChanged;\nothercontrol.value = value;\nothercontrol.SelectedChanged += othercontrol_SelectedChanged;	0
6262034	6261697	What is the best way of converting a Html table to datatable	var doc = new HtmlDocument();\ndoc.Load(url);\n\nvar nodes = doc.DocumentNode.SelectNodes("//table/tr");\nvar table = new DataTable("MyTable");\n\nvar headers = nodes[0]\n    .Elements("th")\n    .Select(th => th.InnerText.Trim());\nforeach (var header in headers)\n{\n    table.Columns.Add(header);\n}\n\nvar rows = nodes.Skip(1).Select(tr => tr\n    .Elements("td")\n    .Select(td => td.InnerText.Trim())\n    .ToArray());\nforeach (var row in rows)\n{\n    table.Rows.Add(row);\n}	0
25637922	25637875	String doesn't parse to Int32 when concatenated with a string	Console.WriteLine("Your age in 10 years will be: " +(FirstName + 10));	0
8947139	8947115	How can I use RegEx (Or Should I) to extract a string between the starting string '__' and ending with '__' or 'nothing'	var firmware = PNP.Split(new[] {'_'}, StringSplitOptions.RemoveEmptyEntries)[1].Split('\\')[0];	0
20316344	20315190	Program interruptions in Keyboardhook program lock up Windows	hook chain	0
29005048	29004250	Prevent Sandcastle from building in Visual studio	Build > Configuration Manager	0
6242102	6235345	How to parse and execute a command-line style string?	string data = null;\nbool help   = false;\nint verbose = 0;\nvar p = new OptionSet () {\n    { "file=",      v => data = v },\n    { "v|verbose",  v => { ++verbose } },\n    { "h|?|help",   v => help = v != null },\n};\nList<string> extra = p.Parse (args);	0
23553516	23546232	How to validate a messagebox popup in c#?	Window messageBox = WindowFactory.Desktop\n                                 .DesktopWindows()\n                                 .Find(w => w.Title.Contains("MessageBoxTitle"));\nButton ok = messageBox.Get<Button>(SearchCriteria.ByText("OK"));\nok.Click();	0
29635505	29634957	How to find currently focused ListBox	public ListBox FocusedListBox()\n{\n    DependencyObject currentObject = (UIElement)FocusManager.GetFocusedElement(this);\n\n    while(currentObject != Application.Current.MainWindow)\n    {\n        if(currentObject == listBox1 || currentObject == listBox2)\n        {\n            return currentObject as ListBox;\n        }\n        else\n        {\n            currentObject = LogicalTreeHelper.GetParent(currentObject);\n        }\n    }\n\n    return null;\n}	0
22235765	22235304	How to automatically assign/copy all fields from an object A to object B without cloning?	public static class Utils \n{\n    public static void CopyFields<T>(T source, T destination)\n    {\n        var fields = source.GetType().GetFields();\n        foreach(var field in fields)\n        {\n            field.SetValue(destination, field.GetValue(source));    \n        }            \n    }\n}	0
10237395	10237348	how to get a last value from Page.Request.Url?	public ActionResult MyAction(string q) {...}	0
15220218	15220156	how to get value from combobox bind From List<>	var item =  fiscalYearComboBox.SelectedItem as FiscalYear\n if(item!=null)\n   _fPeriod.FiscalYear = item.FiscalYearName;	0
12768616	12768133	Programmatically changing form controls	UserControl _step1Control = new UcStep1Control;\nUserControl _step2Control = new UcStep2Control;\nprivate void SetStep(int stepNumber)\n{\n    panel1.Controls.Clear();\n    switch(stepNumber)\n    {\n        case 1:\n            panel.Controls.Add(_step1Control);\n            break;\n        case 2:\n            panel1.Controls.Add(_step2Control);\n            break;\n        default:\n            break;\n      }\n}	0
6583631	6583527	Is there a way to use a C# script to change the inside html of a tag?	document.getElementById('myTagId').innerHTML = 'Downloads';	0
544994	544974	How can I do search efficiently data in Database except using fullsearch	-- DataTable is the big table that holds all of the data\n-- SearchTable is the narrow table that holds the bits of searchable data\n\nSELECT \n  MainTable.ID, \n  MainTable.Name, \n  MainTable.Whatever \nFROM \n  MainTable, SearchTable \nWHERE \n  MainTable.ID = SearchTable.ID \n  AND SearchTable.State IN ('PA', 'DE')\n  AND SearchTable.Age < 40\n  AND SearchTable.Status = 3	0
5677193	5673921	Change file LastWriteDate in Compact Framework	[DllImport("coredll.dll")]\nprivate static extern bool SetFileTime(string path,\n                                      ref long creationTime,\n                                      ref long lastAccessTime,\n                                      ref long lastWriteTime);\n\npublic void SetFileTimes(string path, DateTime time)\n{\n    var ft = time.ToFileTime();\n    SetFileTime(path, ref ft, ref ft, ref ft);\n}	0
33857276	33855298	Overriding Configuration Values in config.json file in Azure Web App in ASP.Net 5	AppSettings:SiteEmailAddress	0
3709276	3709240	File for download in ASP.NET	Response.ContentType = "Application/pdf";\n\nResponse.AppendHeader("content-disposition", "attachment; filename=" + FilePath);\n\nResponse.TransmitFile( Server.MapPath(filepath) );\n\nResponse.End();	0
2568531	2568460	How can I load a Class contained in a website from a DLL referenced by that website?	Type t = (from asm in AppDomain.CurrentDomain.GetAssemblies()\n      from type in asm.GetTypes()\n      where type.Name.StartsWith("MyType")\n      select type).FirstOrDefault();	0
10967042	10966972	entry point of the application	Assembly.GetEntryAssembly()	0
24698899	24698737	C# multidimensional array value changes unexpectedly	screen.CopyTo(buffer, 0);	0
10512570	10509732	Convert from flat XML file to hierarchical XML file using LINQ to XML	var xVar = XElement.Load("XMLFile1.xml");\n\n        var query = xVar.Elements("vSection").\n            GroupBy(grp => (string)grp.Attribute("sectionTitle")).\n            Select(grp => new XElement("section", grp.First().Attributes(),\n                grp.Select(vsec => new XElement("category",\n                    vsec.Element("vCategory").Attributes(),\n                    vsec.Element("vCategory").Elements()))\n                )\n            )\n        ;\n\n        var xml = new XElement("workflows", query);	0
31961019	31960883	Text Box custom source as data table	string[] postSource = dt_1\n                    .AsEnumerable()\n                    .Select<System.Data.DataRow, String>(x => x.Field<String>("MoM_ID"))\n                    .ToArray();\n\nvar source = new AutoCompleteStringCollection();\nsource.AddRange(postSource);\n  TextBox_FormID.AutoCompleteCustomSource = source;\n  TextBox_FormID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n  TextBox_FormID.AutoCompleteSource = AutoCompleteSource.CustomSource;	0
16935108	16932662	Websockets - disconnects on server message	byte[] send = new byte[3 + 2];\nsend[0] = 0x81; // last frame, text\nsend[1] = 3; // not masked, length 3\nsend[2] = 0x41;\nsend[3] = 0x42;\nsend[4] = 0x43;\nnwStream.Write(send, 0, send.Length); // nwStream = client.GetStream(), client is a TcpClient	0
27260409	27196779	Recovery result of a function via a webservice and stored in a variable	void client_RoleCompleted(object sender, RoleCompletedEventArgs e) { \n            role = e.Result.ToString();\n            Thread.Sleep(1000);\n\n\n        }	0
23143075	23128192	How can I get strings between two strings, where the two strings are repetitive?	using System;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main()\n    {\n        string s = File.ReadAllText(@"D:\Data.txt");\n        var matches = Regex.Matches(s, "(?<=start-student)((?!end-student).)*");\n        foreach(var m in matches)\n        {\n            Console.Out.WriteLine(m);\n        }\n    }\n}	0
4816600	4816557	Change color in part of my message	string message1 = "something";\nstring message2 = "<font color='red'>something</font>";\nmessage += "My message is " + message1 + " and " + message2;	0
1198926	1198910	Ignoring a property during deserialization	[XmlIgnore]\npublic int DoNotSerialize { get { ... } set { ... } }	0
27978429	27978022	Sum(with Coalesce) with Group By in linq (for EF6)	var list = from partyList in localDb.Parties\n           join reservationList in localDb.Reservations on partyList.PartyID equals reservationList.PartyID into comboList\n           from details in comboList.DefaultIfEmpty() // Left join\n           group details by new {partyList.PartyID, partyList.PartyDate} into grouped // So that the group have both keys and all items in details\n           select new PartyAmounts\n           {\n             PartyID = grouped.Key.PartyID,\n             PartyDate = grouped.Key.PartyDate,\n             AmountPaid = grouped.Sum(x => x.AmountPaid ?? 0)}\n           };	0
19266266	19241067	Call parent page javascript from within UpdatePanel inside iFrame	protected override void Page_Load(object sender, System.EventArgs e)\n{\n    base.Page_Load(sender, e);\n\n    if (IsPostBack) //If it is a postback close the popup\n    {\n        StringBuilder scriptStringB = new StringBuilder();\n        scriptStringB.Append("<script type=\"text/javascript\">");\n        scriptStringB.Append(" CloseiFrameThroughParent();");\n        scriptStringB.Append("</script>");\n\n        RegisterClientStartupScript("CloseiFrameThroughParent", scriptStringB.ToString());\n    }\n}	0
26278708	26273676	How to change color of line under WizardControl?	public class MyWizardControl : WizardControl {\n    protected override WizardPainter CreatePainter() {\n        return new MyWizardPainter();\n    }\n}\npublic class MyWizardPainter : WizardPainter {\n    protected override WizardClientPainterBase CreateClientPainter(WizardViewInfo viewInfo) {\n        return new MyWizardAeroClientPainter(viewInfo);\n    }\n}\npublic class MyWizardAeroClientPainter : WizardAeroClientPainter {\n    public MyWizardAeroClientPainter(WizardViewInfo viewInfo) : base(viewInfo) { }\n    protected override void DrawDividers(GraphicsInfoArgs e) {\n        base.DrawDividers(e);\n        int bottom = ViewInfo.GetContentBounds().Bottom;\n        e.Graphics.DrawLine(Pens.White, ClientRect.Left, bottom, ClientRect.Right, bottom);\n        e.Graphics.DrawLine(Pens.LightPink, ClientRect.Left, bottom + 1, ClientRect.Right, bottom + 1);\n    }\n}	0
27794440	27794230	get one cell of data from database	private void btnLogin_Click(object sender, EventArgs e)\n    {\n        string requiredUserId;\n\n        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True");\n\n        SqlDataAdapter sda = new SqlDataAdapter("Select Count(userID),UserId From MsUser where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' Group By userID",cn);\n\n        DataTable dt = new DataTable();\n        sda.Fill(dt);\n        if (dt.Rows[0][0].ToString()=="1")\n            {\n                this.Hide();\n                requiredUserId=dt.Rows[0][1].ToString(); //Use this requiredUserId in your next form!!\n            }\n        else\n        {\n            MessageBox.Show("your id or password is wrong");\n        }\n\n    }	0
10315283	10315188	Open file dialog and select a file using WPF controls and C#	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    // Create OpenFileDialog \n    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();\n\n\n\n    // Set filter for file extension and default file extension \n    dlg.DefaultExt = ".png";\n    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; \n\n\n    // Display OpenFileDialog by calling ShowDialog method \n    Nullable<bool> result = dlg.ShowDialog();\n\n\n    // Get the selected file name and display in a TextBox \n    if (result == true)\n    {\n        // Open document \n        string filename = dlg.FileName;\n        textBox1.Text = filename;\n    }\n}	0
31026902	31026355	How would be the xml to satisfy c# condition?	var script = new XmlDocument();\n        script.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">test</signature>");\n        XmlNodeList signature = script.GetElementsByTagName("signature", "http://www.w3.org/2000/09/xmldsig#");\n\n        if (signature != null)\n        {\n            if (signature.Count > 0)\n            {\n                return true;\n            }\n        }\n        return false;	0
32540835	32540796	Writing max array value to console window	Console.Write("The highest number in the array is: {0} ", newArray.Max());	0
1172711	1172692	How to I add an item to a Dictionary<string, Dictionary<string, object>>?	public void AddMainContentView(string moduleKey, string viewKey, object view)\n{\n    Dictionary<string, object> viewDict = null;\n    if (!MainContentViews.TryGetValue(moduleKey, out viewDict)) {\n        viewDict = new Dictionary<string, object>();\n        MainContentViews.Add(moduleKey, viewDict);\n    }\n    if (viewDict.ContainsKey(viewKey)) {\n        viewDict[viewKey] = view;\n    } else {\n        viewDict.Add(viewKey, view);\n    }\n}	0
689970	689940	Hashtable with MultiDimensional Key in C#	struct Key {\n  public readonly int Dimension1;\n  public readonly bool Dimension2;\n  public Key(int p1, bool p2) {\n    Dimension1 = p1;\n    Dimension2 = p2;\n  }\n  // Equals and GetHashCode ommitted\n}	0
9501060	9500391	How to add new form using envDTE	string templateItem = ((Solution2)_applicationObject.Solution).GetProjectItemTemplate("Windows Form", "CSharp");\n_applicationObject.Solution.Projects.Item(1).ProjectItems.AddFromTemplate(templateItem, "MyForm.cs");	0
15177764	15177355	Using HtmlAgilityPack with c# to Find Nested repeated class name section	HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class = 'top2 bigone']//span[@class = 'counts numbers']");\n\nif (node != null)\n{\n    string number = node.InnerText; // 200\n}\nelse\n{\n     MessageBox.Show("node = null");\n}	0
29040077	29039839	Convert string to int C# and place to the array	bool b;\nint tempNumber;\nforeach (string line in lines)\n{\n    string[] words = line.Split(' ');\n    foreach (string word in words)\n    {\n        b = Int32.TryParse(word, out tempNumber);\n        if (b) // success\n        {\n            tab[i] = tempNumber;\n            Console.WriteLine(tab[i]);\n            i++;\n        }\n        else // handle error\n        {\n           Console.WriteLine("Error: '" + word + "' could not be parsed as an Int32");\n        }\n    }\n}	0
30159240	30145556	Changing an image's source in Windows phone	tactImgList[0] = new BitmapImage(new Uri(@"ms-appx:///Assets/Images/1.png");	0
31068157	31067994	Input string was not in a correct format occurs in c#	private void txtbox_BattMmnt_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back /*|| e.KeyChar == (char)5*/ || e.KeyChar == 46)\n    {\n        e.Handled = false;\n    }\n    else\n    {\n        e.Handled = true;\n        MessageBox.Show("Please Enter Only Numeric Value", "Error", MessageBoxButtons.OK);\n        return;//return if it is not numeric.\n    }\n    double i = 0;\n    Double.TryParse(txtbox_BattMmnt.Text, out i);\n    if (i <= 2.9 || i >= 3.35)\n    { e.Handled = false; }\n    else\n    {\n        e.Handled = true;\n        MessageBox.Show("Please Enter Only from 2.9 to 3.35", "Error", MessageBoxButtons.OK);\n    }\n}	0
25286327	25286261	Two exe file in the same project	Process.Start()	0
20278495	20267097	use of stringArray in C# and spliting it into 2 parts for autocomplete box	if (txtphone.Text.StartsWith("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O"))\n            {\n                this.txtphone.SuggestionsSource = stringArray2;\n            }	0
7094571	7092761	AutoSuggest in a asp.net using Ajax controls toolkit and passing values to array	[WebMethod(EnableSession = true), ScriptMethod()]\npublic static string[] GetCompletionList(string prefixText, int count, string \n    contextKey)\n{ \n   var useremail = Session["useremail"] ?? null;\n   //...\n}	0
1067002	1066915	getting the mime of text files	using (DirectoryEntry directory = new DirectoryEntry("IIS://Localhost/MimeMap")) {\n    PropertyValueCollection mimeMap = directory.Properties["MimeMap"];\n    foreach (object Value in mimeMap) {\n        IISOle.MimeMap mimetype = (IISOle.MimeMap)Value;\n        //use mimetype.Extension and mimetype.MimeType to determine \n        //if it matches the type you are looking for\n    }\n }	0
4501898	1507973	Mouse click detection and Transformation2D in Direct3D	Foreach sprite\n    Matrix inverse = tranz.Invert()\n    objectCoords = mouseCoords * inverse;\n    if (objectCoords in (0,0,width, height))\n        return sprite\n\nreturn null;	0
24836111	24835562	Temporary disabling of impersonation in MVC5	using (var impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero))	0
2041024	2027189	How do I use .Net Remoting through a web proxy?	private static void SetChannelProxy(HttpClientChannel channel, IWebProxy proxy)\n    {\n        FieldInfo proxyObjectFieldInfo = typeof(HttpClientChannel).GetField("_proxyObject", BindingFlags.Instance | BindingFlags.NonPublic);\n\n        proxyObjectFieldInfo.SetValue(channel, proxy);\n    }	0
16123121	16123114	How to read data from two different column in same table and return in string builder?	while (dremail.Read())\n{\n    sb.AppendFormat("{0}, {1}", dr[0].ToString(), dr[1].ToString());\n}	0
17444206	17444158	How do i open a text file with openFileDialog when the content of the file is also with hebrew letters?	Encoding enc = Encoding.GetEncoding("Windows-1255");\nstring s = File.ReadAllText(file1, enc);	0
8971826	8971761	Windows Phone 7 Navigation passing parameter	if (this.NavigationContext.QueryString.ContainsKey("customerId")) \n{\n    string customerId = this.NavigationContext.QueryString["customerId"];\n}\n\nif (this.NavigationContext.QueryString.ContainsKey("selectedItem")) \n{\n    string selectedItem = this.NavigationContext.QueryString["selectedItem"];\n}	0
2221760	2221748	System.Drawing.Color in console application	System.Drawing.dll	0
32658167	32657750	Remove & Update Selected Row or Item from Datagrid In WPF	private void DeleteButtonClick(object sender, MouseEventArgs e)\n{\n    if (dataGrid.SelectedItem == null)\n        return;\n    DataRowView rowView = (DataRowView)dataGrid.SelectedItem; // Assuming that you are having a DataTable.DefaultView as ItemsSource;\n\n    DB.Execute("DELETE FROM TABLE WHERE myCol=" + rowView["myCol"]); // rowView[ColumnName] retrieves the value for you, Use your Primary Column's name here;\n}	0
24989030	24988396	Performance : What is the best way to increase the performance of binding multiple comboboxes with same DisplayMemberPath and SelectedValuePath	private void BindYears(Combobox box)\n{\n    box.ItemsSource = listOfYears;\n    box.DisplayMemberPath = "YearID";\n    box.SelectedValuePath = "YearID";\n}\n\nprivate void BindBoxes()\n{\n    BindYears(cbBeginYear);\n    BindYears(cbEnd_Year);\n    BindYears(cbExactYear);\n    BindYears(cbStart_Year);\n    BindYears(cbEndYear);\n}	0
22605024	22604866	I need to store '/' separated strings in a tree-like structure in C#, how should I do it?	class Vegetable : Dictionary<string, List<Vegetable>>	0
22768205	22767900	xpath search for multiple keywords	//text()[contains(., 'Frozen') and contains(., 'obamacare')]	0
21449780	21449706	Convert ShortTime string to DateTime format	DateTime time = DateTime.Now;\n\nstring newTime = time.ToShortTimeString();\n\nDateTime dt = new DateTime();\nDateTime.TryParse(newTime,out dt);	0
27091042	27090972	How can I save the path of an image in OpenFileDialog to a string?	private void uploadButton_Click(object sender, EventArgs e)\n{\n    try\n    {\n        OpenFileDialog OpenFd = new OpenFileDialog();\n        // REMOVED HERE .... pathToImage = OpenFd.FileName\n        OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";\n        DialogResult rd = OpenFd.ShowDialog();\n        if (rd == System.Windows.Forms.DialogResult.OK)\n        {\n            playerPictureBox.Image = Image.FromFile(OpenFd.FileName);\n\n            myStruct aNewStruct = new myStruct(5);\n            aNewStruct = (myStruct)dataList[currentEntryShown];\n            aNewStruct.imagePath = OpenFd.FileName;  // Changed this line...\n            dataList[currentEntryShown] = aNewStruct;\n        }\n\n        // no much sense this here if the user cancel the dialogbox \n        // MessageBox.Show(pathToImage);\n\n    }	0
10704398	10704068	Bind DatePicker to List of Dates	DateTime end = DateTime.MaxValue;\nDateTime start = DateTime.MinValue;\nList<DateTime> datesIHave= new List<DateTime>();\ndatesIHave.Add(DateTime.Now);\nList<DateTime> allDates = Enumerable.Range(0, 1 + end.Subtract(start).Days).Select(offset => start.AddDays(offset)).ToList();\nList<DateTime> blackoutDates = (from a in allDates \n                                where !datesIHave.Contains(a)\n                                select a).ToList();	0
18373506	15942503	AppDomain + Named pipe serialization performance	public OrderPrice DoAction()\n{\n    Task<OrderPrice> task = Task<OrderPrice>.Factory.StartNew(NamedPipeClient);\n\n    if (domain == null)\n        domain = AppDomain.CreateDomain(DOMAINNAME);\n    domain.DoCallBack(AppDomainCallback);\n\n    return task.Result; \n}	0
31146535	31145296	Converting a DataTable value to a Generic Type	public static Nullable<T> getDBSpecifiedType<T>(string columnName, DataTable table, int index = 0)\n{\n    if (getDB<T>(columnName, table, index) != String.Empty)\n    return (T)Convert.ChangeType(table.Rows[index][columnName], typeof(T));\n\n    return null;\n}	0
10993450	10993343	Get current location of a visitor	navigator.geolocation.getCurrentPosition(\n      onSuccess,\n      onError, {\n        enableHighAccuracy: true,\n        timeout: 20000,\n        maximumAge: 120000\n      });\n\nfunction onSuccess(position) {\n      //the following are available to use\n  //position.coords.latitude\n  //position.coords.longitude\n // position.coords.altitude\n // position.coords.accuracy\n // position.coords.altitudeAccuracy\n // position.coords.heading\n // position.coords.speed \n\n\n}	0
12498116	12496289	Open XML Paragraph Spacing	new ContextualSpacing() { Val = false }	0
1533349	1533115	Get GenericType-Name in good format using Reflection on C#	static string GetFullName(Type t)\n{\n    if (!t.IsGenericType)\n        return t.Name;\n    StringBuilder sb=new StringBuilder();\n\n    sb.Append(t.Name.Substring(0, t.Name.LastIndexOf("`")));\n    sb.Append(t.GetGenericArguments().Aggregate("<",\n\n        delegate(string aggregate,Type type)\n            {\n                return aggregate + (aggregate == "<" ? "" : ",") + GetFullName(type);\n            }  \n        ));\n    sb.Append(">");\n\n    return sb.ToString();\n}	0
23278096	23277992	update the number with total value	string cmd = string.Format("update project.material set number = {0} where name= '{1}'",\n                           total,\n                           this.txt.Text);	0
24895848	24895695	How can i switch between two icons to make them flash smooth?	+Elapsed	0
22528205	22527980	In Entity Framework, how to get the sql translated by EF?	testdb.Database.Log = Console.WriteLine;\ntestdb.SaveChanges();	0
28230343	28230222	how to insert data into multiple tables at once	using (var connection = new SqlConnection(ConnectionString))\nusing (var command = connection.CreateCommand())\n{\n    connection.Open();\n    command.CommandText = @"insert into Stock([Product]) values (@Product);\n                        insert into LandhuisMisje([Product]) values (@Product);\n                        insert into TheWineCellar([Product]) values (@Product);"\n    command.Parameters.AddWithValue("@Product", AddProductTables.Text);\n    command.ExecuteNonQuery()\n}	0
9745309	9745280	How to unsubscribe an anonymous function in Dispose method of a class?	public class A : IDisposable\n{\n    private readonly EventHandler handler;\n\n    public A()\n    {\n        handler = (sender, e) =>\n        {\n           Line 1\n           Line 2\n           Line 3\n           Line 4\n        };\n\n        B_Object.DataLoaded += handler;\n     }\n\n     public override void Dispose()\n     {\n        B_Object.DataLoaded -= handler;\n     }\n}	0
15286256	15286140	String to datagridview	public DataTable Accountlocked()\n        {\n           //DirectoryEntry entry = new DirectoryEntry("LDAP://Mytechnet.com");\n           DirectoryEntry entry = new DirectoryEntry("LDAP://User");\n           DirectorySearcher Dsearch = new DirectorySearcher(entry);\n\n           Dsearch.Filter = "(&(&(&(&(&(objectCategory=person)(objectClass=user)>>(lockoutTime:1.2.840.113556.1.4.804:=4294967295))))))";\n\n           DataTable dt = new DataTable();\n           dt.Columns.Add("AccountName");\n           dt.Columns.Add("Name");\n                foreach (SearchResult sResultSet in Dsearch.FindAll())\n                {\n                   DataRow dr = dt.NewRow();          \n                   dr[0] = (GetProperty(sResultSet, "samaccountname"));\n                   dr[1] = (GetProperty(sResultSet, "name"));\n                   dt.Rows.Add(dr);\n                }\n                return dt;\n            }\n        }\n\n\ndataGridView1.DataSource = Accountlocked();	0
6547265	4758344	Axapta method return List<Array> , how to convert it in c#	List<string> magazynierzy = new List<string>();\n        while(axContainer.ReadNext())\n            magazynierzy.Add(axContainer.get_Item(1).ToString());\n        return magazynierzy;	0
13172951	13172319	Search contain in xml if found replace whole node	XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load("Path");\n XmlNodeList nodeList = xmlDoc.SelectNodes("section") ;\n\n foreach (XmlNode node in nodeList)\n   {\n      XmlNode childNode = node.SelectSingleNode("placeholder");\n        if (childNode.Value.Contains("sam"))\n          {\n              childNode.Value = "sam,pam,sam2";\n              childNode.Attributes["width"].Value = "4,5,91";\n\n           }\n   }\n\n xmlDoc.Save("Path");	0
8751405	8751299	Using FormattedText to create a Bitmap	var bmp = new Bitmap(480, 480);\nusing (var gr = Graphics.FromImage(bmp)) {\n    gr.Clear(Color.White);\n    TextRenderer.DrawText(gr, textBox1.Text, this.Font, \n        new Rectangle(0, 0, bmp.Width, bmp.Height), \n        Color.Black, Color.White,\n        TextFormatFlags.WordBreak | TextFormatFlags.Left);\n}\nif (pictureBox1.Image != null) pictureBox1.Image.Dispose();\npictureBox1.Image = bmp;	0
27947035	27946664	Looking for a design pattern for populating classes without a database	public interface ICar\n{\n    string GetMake();\n    string GetModel();\n}\n\npublic class ToyotaCamry : ICar\n{\n    #region ICar Members\n\n    public string GetMake()\n    {\n        return "Toyota";\n    }\n\n    public string GetModel()\n    {\n        return "Camry";\n    }\n\n    #endregion\n}\n\npublic class FordMustang : ICar\n{\n    #region ICar Members\n\n    public string GetMake()\n    {\n        return "Ford";\n    }\n\n    public string GetModel()\n    {\n        return "Mustang";\n    }\n    #endregion\n}\n\npublic enum CarType\n{\n    FordMustang,\n    ToyotaCamry\n}\n\n/// <summary>\n/// Implementation of Factory - Used to create objects\n/// </summary>\npublic class Factory\n{\n    public ICar GetCar(CarType type)\n    {\n        switch (type)\n        {\n            case CarType.FordMustang :\n                return new FordMustang();\n            case CarType.ToyotaCamry:\n                return new ToyotaCamry();\n        }\n        return null;\n    }\n}	0
33240128	33238939	Run a windows form while my console application still running	using System.Windows.Forms;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n\nclass Program\n{\n\n    public static bool run = true;\n    static void Main(string[] args)\n    {\n\n        Startthread();\n        Application.Run(new Form1());\n        Console.ReadLine();\n\n\n    }\n\n    private static void Startthread()\n    {\n        var thread = new Thread(() =>\n        {\n\n            while (run)\n            {\n                Console.WriteLine("console is running...");\n                Thread.Sleep(1000);\n            }\n        });\n\n        thread.Start();\n    }\n  }\n }	0
7362228	7362174	Tightest Byte Representation of YYYYMMDDHHMMSS?	//Helpers\nprivate static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\npublic static long toUnixTime(this DateTime d)\n{\n    return (long)((d.ToUniversalTime() - Jan1st1970).TotalMilliseconds);\n}\n\npublic static string Base64Encode(long toEncode)\n{\n    return Convert.ToBase64String(BitConverter.GetBytes(toEncode));\n}\n\n//Encode\npublic static string PackDate(DateTime toPack)\n{\n    return Base64Encode(toPack.toUnixTime()/1000);\n}\n\n//Decode\npublic static DateTime UnpackDate(string toUnpack)\n{\n    long time = BitConverter.ToInt64(Convert.FromBase64String(toUnpack),0);\n    return Jan1st1970.AddSeconds(time); //you may or may not want a "ToLocaltime()" call here.\n}	0
12682340	11597295	How do I use File.ReadAllBytes In chunks	private void button1_Click(object sender, EventArgs e)\n{\n    const int MAX_BUFFER = 2048;\n    byte[] Buffer = new byte[MAX_BUFFER];\n    int BytesRead;\n    using (System.IO.FileStream fileStream = new FileStream(textBox2.Text, FileMode.Open, FileAccess.Read))\n        while ((BytesRead = fileStream.Read(Buffer, 0, MAX_BUFFER)) != 0)\n        {\n            string text = (Convert.ToBase64String(Buffer));\n            textBox1.Text = text;\n\n        }\n}	0
17025813	17025716	Drag image from desktop and save it in bitmap	private delegate void DragDropDelegate(String[] s);\n\n    private void pnlImage_DragEnter(object sender, DragEventArgs e)\n    {\n        if (e.Data.GetDataPresent(DataFormats.FileDrop))\n        {\n            e.Effect = DragDropEffects.Copy;\n        }\n        else\n        {\n            e.Effect = DragDropEffects.None;\n        }\n    }\n\n    private void pnlImage_DragDrop(object sender, DragEventArgs e)\n    {\n        try\n        {\n            String[] a = (String[])e.Data.GetData(DataFormats.FileDrop);\n\n            if (a != null)\n            {\n                this.BeginInvoke(new DragDropDelegate(DelegateDragDrop), new Object[] { a });\n                this.Activate(); // This avoids some odd behaviour\n            }\n        }\n        catch (Exception ex)\n        {\n            Trace.WriteLine("Error in DragDrop function: " + ex.Message);\n        }\n    }\n\n    private void DelegateDragDrop(String[] files)\n    {\n        // Verify file formats and do something with the files.\n\n    }	0
15957165	15957164	How to force Task.Factory.StartNew to a background thread?	Task.Factory.StartNew(action,\n                      CancellationToken.None,\n                      TaskCreationOptions.None,\n                      TaskScheduler.Default).ContinueWith(completeAction);	0
5633917	5624934	Convert string into MongoDB BsonDocument	string json = "{ 'foo' : 'bar' }";\nMongoDB.Bson.BsonDocument document\n    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);	0
3678380	3678316	Dynamically extend SQL statement - page search	SqlCommand cmd = new SqlCommand(); \ncmd.Connection = connection; \ncmd.CommandType = System.Data.CommandType.Text; \nstring sql = "SELECT * FROM ForumThread WHERE ";\n// assuming you have at least 1 item always in wordsFromTxtSearche\nint count = 1;\nforeach (string word in wordsFromTxtSearche)\n{\n    if (count > 1) sql += " AND ";\n    sql += "Text LIKE @Text" + count.ToString();\n    cmd.Parameters.Add(new SqlParameter("@Text" + count.ToString(),\n        string.Format("%{0}%", word)));\n    count++;\n}\ncmd.CommandText = sql;	0
1314692	1314538	How do I cancel a WinForms TreeView ExpandAll?	private void treeView1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Multiply)\n    {\n        e.Handled = true;\n        e.SuppressKeyPress = true;\n    }\n}	0
8620896	8620846	How to manage xmlns to be able to execute an xpath query?	int count = readDoc.SelectNodes("//html:html/html:body/html:div/html:span[@class='layout']",xmlnsManager).Count;	0
1817582	1817542	How to set an autoproperty in the constructor of a struct?	public struct MyStruct \n{\n    public MyStruct(double value) : this()\n    {\n        MyProperty = value;\n    }\n\n    public double MyProperty { get; set; }\n}	0
2796402	2796386	How to select all the attributes that contain certain String in an XML Document using LINQ	elem.DescendantsAndSelf().Attributes().Where(a => a.Name.LocalName.Contains("Foo"))	0
23616457	23590193	How can I get all HTML attributes with GeckoFX/C#	public string GetElementAttributes(GeckoElement element)\n{\n   var result = new StringBuilder();\n   foreach(var a in element.Attributes)\n   {\n       result.Append(String.Format(" {0} = '{1}' ", a.NodeName, a.NodeValue));\n   }\n\n   return result.ToString();\n}	0
24833425	24828840	Start an Activity from DialogFragment in Android Xamarin Studio	var activity2 = new Intent (this.Activity, typeof(ImportScreen));	0
30828058	30828026	Split array into another array	var result = Array.SelectMany(x => x.Split(new[]\n    {\n        '(', ')'\n    }, StringSplitOptions.RemoveEmptyEntries)).ToArray();	0
15645789	15645412	String manipulation of Serial Port data	string pattern = @"^GPS:(?<gps>.{8}),N,(?<n>.{10}),WMAG:(\+|\-)(?<wmag>.{3})\\r\\n$";\n\n        string gps = string.Empty;\n        string n = string.Empty;\n        string wmag = string.Empty;\n\n        string input = @"GPS:050.1347,N,00007.3612,WMAG:+231\r\n";\n\n        Regex regex = new Regex(pattern);\n\n        if (regex.IsMatch(input))\n        {\n            Match match = regex.Match(input);\n\n            foreach (Capture capture in match.Groups["gps"].Captures)\n                gps = capture.Value;\n\n            foreach (Capture capture in match.Groups["n"].Captures)\n                n = capture.Value;\n\n            foreach (Capture capture in match.Groups["wmag"].Captures)\n                wmag = capture.Value;\n        }\n\n        Console.Write("GPS: ");\n        Console.WriteLine(gps);\n\n        Console.Write("N: ");\n        Console.WriteLine(n);\n\n        Console.Write("WMAG: ");\n        Console.WriteLine(wmag);\n\n        Console.ReadLine();	0
6935198	6935010	How to use Contains() in a many-to-many scenario?	from post in session.Query<Post>\nfrom tag in post.Tags \nwhere tag.Name.StartsWith("blah")\nselect post	0
9352077	9346606	Methods of manipulating/controling Windows Save As/Open File dialogs?	public class folderLocation\n    {\n        public string folderPath { get; set; }\n        public string folderName { get; set; }\n        public Keys hotKey { get; set; }\n    }	0
1422623	1422594	Launch External Process With Time To Live	ProcessStartInfo psi = new ProcessStartInfo();\n// configure psi here - FileName, UseShellExecute etc.\nProcess p = Process.Start(psi);\nif (!p.WaitForExit(N * 1000)) // time in millisecs \n    p.Kill(); // terminate with extreme prejudice	0
15136009	15100204	Exchange Webservice Managed API - Find items by extended properties	ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);\n        service.AutodiscoverUrl("someone@somewhere.com");\n\n        ExtendedPropertyDefinition def = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "AppointmenId", MapiPropertyType.String);\n\n        Guid testid = Guid.NewGuid ();\n\n        Appointment appointment = new Appointment(service);\n        appointment.Subject = "Test";\n        appointment.Start = DateTime.Now.AddHours(1);\n        appointment.End = DateTime.Now.AddHours(2);\n        appointment.SetExtendedProperty(def, testid.ToString());\n        appointment.Save(WellKnownFolderName.Calendar);\n\n        SearchFilter filter = new SearchFilter.IsEqualTo(def, testid.ToString());\n\n        FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Calendar, filter, new ItemView(10));	0
21194721	21192490	Key char on Windows Phone	private void myTextbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)\n{\n   char added = myTextbox.Text.ElementAt(myTextbox.Text.Length - 1);\n}	0
28241486	28241468	Order results of LINQ expression by an Enum	var itineraries = t.Itineraries.OrderBy(x => x.Type).ThenBy(x => x.Date).ToList();	0
20901687	20900348	Windows Phone 8 Long List Selector - scroll to bottom after data loaded async	private async Task DoAndScroll()\n{\n   await App.MessagesViewModel.LoadData();\n   var lastMessage = App.MessagesViewModel.Messages.LastOrDefault();\n   llsMessages.ScrollTo(lastMessage);\n}\n\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n{\n   string contactId = "";\n   if (NavigationContext.QueryString.TryGetValue("contactId", out contactId))\n   {\n      DataContext = App.MessagesViewModel;  \n      DoAndScroll();     \n   }\n}	0
255958	255951	Re-implementing an interface that another interface already inherits	namespace DotNetInterfaceTest {\n    class Program {\n    static void Main(string[] args) {\n    A c = new C();\n    }\n    }\n\n    interface A {\n    void foo();\n    }\n\n    interface B : A {\n    void bar();\n    }\n\n    class C : B {\n    public void bar() {}\n    public void foo() {}\n    }\n}	0
4380648	4380639	How to display the current time and date in C#	labelName.Text = DateTime.Now.ToString();	0
15100100	15100049	Accessing Methods on Web API after being authenticated	blog post	0
15879537	15878454	C# Finding text in a string, then extract a variable	for(int i = 0; i <= deserializedResult.Count; i++)\n{\n    if(deserializedResult[i] == 440)\n        ....\n}	0
22259499	22259425	How do you loop through a class passed to a method and retrieve it's property values in C#	StudProp.GetValue(oStud, null).ToString();	0
7046744	7044277	Determining the expected type of a DynamicObject member access	var or dynamic	0
22333729	16444695	Seeding Many to Many EF Code First Relationship	var messages = new List<Message>()\n    {\n        new Message()\n        {\n            Id = 1,\n            SenderId = 2,\n            Recipients = new List<User>()\n            {\n               users.Single(u => u.Id == 1),\n               users.Single(u => u.Id == 2)\n        }\n    }	0
21649508	21649188	Find the closest value in an array of floats?	float x = 2.25;\nfloat closest_value=array[0];\nfloat subtract_result = Math.Abs(closest_value - x) ;\n\nfor (int i = 1; i < array.length; i++)\n{\n    if (Math.Abs(array[i] - x) < subtract_result)\n    {\n        subtract_result = Math.Abs(array[i] - x);\n        closest_value = array[i];\n    }\n}	0
7662917	7662766	How to eliminate duplicates from a list?	public class infoContactComparer : IEqualityComparer<infoContact>\n{\n    public bool Equals(infoContact x, infoContact y)\n    {\n        return x.contacts_first_nameField == y.contacts_first_nameField\n            && x.contacts_last_nameField == y.contacts_last_nameField\n            && ...\n    }\n\n    public int GetHashCode(infoContact obj)\n    {\n        return obj.contacts_first_nameField.GetHashCode();\n    }\n}	0
13174531	13174511	How to get the reference of new Object in two variables at same time?	Object o1 ,o2;\no1 = o2 = new Object();	0
19704959	19704646	value just after a string and before <br> in a string	decimal value = decimal.Parse(\n                input.Split("<br>")\n                .Where(x => x.StartsWith("State withhold"))\n                .First().Split('=').ToArray()[1]);	0
444504	444440	Dynamically add multiple instances of the same user control type when button is clicked	for (int i = 0; i < NumberOfAttachments; i++) {\n    Panel.Controls.Add(new MyControl());\n}	0
17744939	17744529	WPF play "Click" animation on button. Simulate click from code	var element = AutomationElement.RootElement.FindFirst(\n                TreeScope.Descendants,\n                new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button), new PropertyCondition(AutomationElement.NameProperty, "Start", PropertyConditionFlags.IgnoreCase))\n            );\nvar pattern = (InvokePattern)element.GetCurrentPattern(InvokePattern.Pattern);\npattern.Invoke();	0
27533913	27533706	Editting a 2D array with Linq and ForEach	mas = mas\n    .Select((a, i) => a.Select((c, j) => j > i ? 0 : c).ToArray())\n    .ToArray();	0
27398110	27397691	select from table sql ce server between date returning 0	string commandText = "select A.ItemName, B.Site, B.OrderId, A.Qty, B.Requester, B.Receiver, B.Date ";\n            commandText += "From tblOrderLine AS A Inner join tblOrder As B on A.OrderId=B.OrderId ";\n            commandText += "where A.ItemName='" + searchWord + "' and CONVERT(NVARCHAR(10),B.Date,121) >= CONVERT(NVARCHAR(10),'" + dateFrom.ToString("yyyy-MM-dd") + "',121) and CONVERT(NVARCHAR(10),B.Date,121) <= CONVERT(NVARCHAR(10),'" + dateTo.ToString("yyyy-MM-dd") + "',121) Order By A.OrderId DESC";	0
20216216	20216199	Search in string list and return as bool	if (!Test.Contains("Teststring"))\n{\n   Test.Add("Teststring");\n}	0
1495217	1495179	Remove Entity from DataContext so that its not inserted (Linq-to-SQL)	A.B = null;	0
20218468	20213916	Finding version of Microsoft Office installed on system at runtime in Visual Studio	office 14 primary interop assemblies	0
2426395	2426190	How to read file binary in C#?	byte[] fileBytes = File.ReadAllBytes(inputFilename);\nStringBuilder sb = new StringBuilder();\n\nforeach(byte b in fileBytes)\n{\n    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  \n}\n\nFile.WriteAllText(outputFilename, sb.ToString());	0
13350093	13326352	PostMessage call steals focus from siblings	[DllImportAttribute("user32.dll", EntryPoint = "SetForegroundWindow")]\n[return: MarshalAsAttribute(UnmanagedType.Bool)]\npublic static extern bool SetForegroundWindow([InAttribute()] IntPtr hWnd);\n\n[DllImportAttribute("user32.dll", EntryPoint = "GetForegroundWindow")]\npublic static extern IntPtr GetForegroundWindow();\n\n[DllImportAttribute("user32.dll", EntryPoint = "BringWindowToTop")]\n[return: MarshalAsAttribute(UnmanagedType.Bool)]\npublic static extern bool BringWindowToTop([InAttribute()] IntPtr hWnd);\n\nIntPtr old = GetForegroundWindow();\nLeftClick(hw, x, y);\nSetForegroundWindow(old);\nBringWindowToTop(old);	0
12527741	12497660	Facebook c# SDK logout, Silverlight	private void SetFacebookLogoutSource()\n{\n    var fbClient = new Facebook.FacebookClient();\n\n    var logoutParameters = new Dictionary<string, object>\n              {\n                  { "next", GenerateLoginUrl(fbClient, "publish_actions").AbsoluteUri },\n                  { "access_token", [user's_access_token] }\n              };\n\n    var logoutUrl = fbClient.GetLogoutUrl(logoutParameters);\n\n    webBrowser.Navigate(logoutUrl);\n}	0
9924234	9924115	how to convert code to winform?	private void button1_Click(object sender, EventArgs e)\n            {\n    listbox1.items.add("Operating System Detaiils");\n     OperatingSystem os = Environment.OSVersion;\nlistbox1.items.add("OS Version: " + os.Version.ToString());\n    // and so on...\n\n    }	0
15058619	15058584	Randomize Next Page	protected void newWindow(object sender, EventArgs e)\n{\n    int next = new Random().Next( 10 ) + 1; // 1..10\n    Response.Redirect(string.Format( "Question{0}.aspx", next ));\n}	0
31241093	28473710	How to scroll to element with Selenium WebDriver using C#	WebElement element = driver.findElement(By.id("element-id"));\nActions actions = new Actions(driver);\nactions.moveToElement(element);\nactions.perform();	0
1175960	1175952	Why couldn't I check for a null reference on a connection string?	if ((ConfigurationManager.ConnectionStrings["PrimaryConnectionString"] != null)\n&& (ConfigurationManager.ConnectionStrings["PrimaryConnectionString"].ConnectionString != null))\n  { etc etc }	0
5608428	5608235	WPF Correct programatic binding for bound ComboBox	var enumValues =  Enum.GetValues(Model.component.GetType().GetProperty(attribute.PropertyName).PropertyType);\nforeach (var e in enumValues) {\n    combo.Items.Add(e);\n}	0
11587390	11587152	Sorting a client heartbeat from an actual data return?	if ( packet.type == PacketTypes.HeartBeat )\n    //keep alive the client\nelse\n    //it's data (or another packet)	0
11579064	11578350	Retrieve keys from JArray	var keys = from m in foo\n           select m["episode_key"];	0
26124037	26122545	Get Route with Variable Placeholder in ServiceStack (C#)	var route = base.Request.GetRoute();\nroute.Path.Print(); //= /foo/{Name}	0
7407869	7407796	Get output of PHP script from C#	System.Diagnostics.Process.Start	0
29434473	29434303	How to remove blank lines from HTML with HTMLAgilityPack?	html = Regex.Replace(html, @"( |\t|\r?\n)\1+", "$1");	0
34303357	34303036	How to use linq with enum type	return (productEvents.Where(s => event == s.Type));	0
1357567	1357522	Load foreign key value with linq to entities	var location_ids = (from m in _db.Admins\n                    where m.Users.UserId.Equals( \n                        new Guid("c5d3dc0e-81e6-4d6b-a9c3-faa802e10b7d")) &&   \n                        m.LocationId.Equals(conf.umisteni.Budova.ID)\n                    select m.LocationId);	0
32509610	32508798	Query SQL to Lambda Expression	var segmentoIds = pb.MaquinasRelSegm\n    .Where(a => a.idMaquina == 67)\n    .Select(a => a.idSegmento)\n    .ToList();\n\nvar description = pb.MantenimientosTipos\n    .Where(a => a.Activo && segmentoIds.Contains(a.idSegmento))\n    .Select(a => a.Description);	0
13146872	13144615	RenderTargetBitmap renders image of a wrong size	for (int i = 0; i < paginator.PageCount; i++)\n{\n    DocumentPage page = paginator.GetPage(i);\n    double width = page.Size.Width;\n    double height = page.Size.Height;\n    double maxWidth = Math.Round(21.0 / 2.54 * 96.0); // A4 width in pixels at 96 dpi\n    double maxHeight = Math.Round(29.7 / 2.54 * 96.0); // A4 height in pixels at 96 dpi\n    double scale = 1.0;\n    scale = Math.Min(scale, maxWidth / width);\n    scale = Math.Min(scale, maxHeight / height);\n\n    ContainerVisual containerVisual = new ContainerVisual();\n    containerVisual.Transform = new ScaleTransform(scale, scale);\n    containerVisual.Children.Add(page.Visual);\n\n    RenderTargetBitmap bitmap = new RenderTargetBitmap(\n        (int)(width * scale), (int)(height * scale), 96, 96, PixelFormats.Default);\n\n    bitmap.Render(containerVisual);\n\n    ...\n}	0
14853133	14852885	convert a given char varialble to string, representing it's code in my encoding	// get the encoding\nEncoding encoding = Encoding.GetEncoding(1251);\n\n// for each character you want to encode\nbyte b = encoding.GetBytes("" + c)[0];\nstring hex = b.ToString("x");\nstring output = @"\'" + hex;	0
29306576	29290614	Quick CRUD access for simple SQL schema	IEnumerable<TModel> result;\n    using (MySqlConnection conn = new MySqlConnection(_mysqlConnString))\n    {\n        // "Query" is a Dapper extension method that stuffs the datareader into objects based on the column names\n        result = conn.Query<TModel>("Select * from YourTable");\n    }\n    // do stuff with result	0
11800548	11800480	Illegal characters in path with web.downloadstring	string mainurl = "http://www.cpso.on.ca/docsearch/details.aspx?view=1&id=+" + numberurl;	0
29372239	29368044	XAML -> C# Update a Text property from Resources in C#	private string GetResources(string key)\n{\n   ResourceLoader rl = ResourceLoader("../Resources");\n   string resources = rl.GetString(key);\n\n   return resources;\n}\n\nprivate void ChangeTitle()\n{\n   if (something)\n   Exemples.Text = GetResources("Mytitle_1/Text");\n   else\n   Exemples.Text = GetResources("Mytitle_2/text");\n}	0
27870058	27869986	Finding the most recent record in a table matching a specific condition	var date = context.corresps.OrderByDescending(x => x.tevent)\n  .Where(x => x.cMethod == "W")\n  .Select(x => x.tevent)\n  .FirstOrDefault());	0
4613802	4613756	How to open or run unknown file coverted into byte[]	byte[] bytes = GetYourBytesFromDataBase();\n  string extension = GetYourFileExtension(); //.doc for example\n  string path = Path.GetTempFileName() + extension;\n  try\n  {\n      using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))\n      {\n         writer.Write(yourBytes);\n      }\n\n      // open it with default application based in the\n      // file extension\n      Process p = System.Diagnostics.Process.Start(path);\n      p.Wait();\n  }\n  finally\n  {\n      //clean the tmp file\n      File.Delete(path);\n  }	0
4254730	4254724	In code behind how do I make a validator to not validate?	rfvtxtAdd.Enabled = false;	0
11872804	11872752	Get querystring value	System.Web.dll	0
3004760	3001235	WPF DataGrid HeaderTemplate Mysterious Padding	protected override Size ArrangeOverride(Size arrangeSize)\n   {\n     //...\n     if (padding.Equals(new Thickness()))\n     {\n       padding = DefaultPadding;\n     }\n     //...\n     child.Arrange(new Rect(padding.Left, padding.Top, childWidth, childHeight));\n   }	0
30683816	30683664	How convert Gregorian date to Persian date?	string GregorianDate = "Thursday, October 24, 2013";\nDateTime d = DateTime.Parse(GregorianDate);\nPersianCalendar pc = new PersianCalendar();\nConsole.WriteLine(string.Format("{0}/{1}/{2}", pc.GetYear(d), pc.GetMonth(d), pc.GetDayOfMonth(d)));	0
3887717	3887640	Splitting strings in a "Google" style way	var testString = "This \"test will\" fail";\nvar termsMatches = Regex.Matches(testString, "(\\w+)|\"([\\w ]+[^ ])\"");	0
2655115	2655088	Exploding a range of dates with LINQ	var result = listOfPairs.SelectMany(pair =>\n                 Enumerable.Range(0, (pair.Item2 - pair.Item1).TotalDays)\n                           .Select(days => pair.Item1.AddDays(days)));	0
20840201	20840120	System.FormatException: @name : as - Input string was not in a correct format	string cmd = "SELECT  sid AS [Student ID], sname AS [Student Name], " + \n            "contact AS [Contact No] FROM Student WHERE sname LIKE @name";\n....\na.SelectCommand.Parameters.AddWithValue("@name", "%" + textBox1.Text + "%") ;	0
26584684	26584565	C# Remove tab from string, Tabs Identificaton	string strWithTabs = "here is a string          with a tab and with      spaces";\n\nstring line = strWithTabs.Replace("\t", " ");\nwhile(line.IndexOf("  ") > 0)\n{\nline = line.Replace("  ", " ");\n}	0
20702253	20701923	How to find position of dynamically created textbox?	x.Name = "new_textbox";	0
2684671	2684587	Succinct LINQ to XML Query	var images = xml.Descentants("image");\n\nreturn images.Where(i => i.Descendants("imageType")\n                          .All(c => c.Value == imageType))\n             .Select(i => i.Descendants("imagedata")\n                           .Select(id => id.Attribute("fileref"))\n                           .FirstOrDefault())\n             .FirstOrDefault();	0
3634404	3634335	Merging dictionaries in key level and then in value level	var dictionary = dictionary1.Concat(dictionary2)\n                            .ToLookup(pair => pair.Key, pair => pair.Value)\n                            .ToDictionary(x => x.Key, x => x.First());	0
7439485	7439465	C# Load items from file and split into array	foreach(String line in File.ReadAllLines("item.ids")) \n{\n    items = line.Split(':');\n\n    foreach (String part in items)\n    {\n        addToList(specs, part);\n    }\n}	0
21541949	21538140	Do changes need to be made to my responses to correctly serialize JSON in ServiceStack 4? the objects worked perfectly in 3.9	[Serializable]	0
2882891	2882797	How can I provide property-level string formatting?	private string encryptedProperty2;\n public string MyProperty2\n {\n      get { return this.Decrypt( this.encryptedProperty2 ); }\n      set { this.encryptedProperty2 = this.Encrypt( value ); }\n }\n\n private void Init()\n {\n     ...\n     this.encryptedProperty2 = ... read from file ...\n     ...\n }\n\n public void Save()\n {\n      ...\n      writer.Write( this.encryptedProperty2 );\n      ...\n }	0
7887905	7887829	LIstbox Selected Item content to textblock	selectionText.Text= "This is the " + selection.Content.ToString();	0
2640722	2640410	Add Ellipsis to a Path in a WinForms Program without Win32 API call (revisited)	string ellipsisedPath = OriginalPath + '\0';	0
3127077	3127012	How can I return a specific array using an index in a multi-dimensional array in .NET?	public static class ext{\n            public static string[] twodim(this string[,] inarr, int row) {\n                string[] ret = new string[inarr.GetLength(1)];\n                for (int i = 0; i < inarr.GetLength(1); i++)\n                    ret[i] = inarr[row, i];\n                return ret;\n            }\n        }\n public class Program{\n       static void dump(string name, string[] arr){\n           Console.WriteLine(name);\n           for (int i = 0; i < arr.Length; i++)\n               Console.WriteLine("  {0}  ", arr[i]);\n       }\n  static void Main(string[] args){\n     string[,] table = new string[,] {\n            {"Apple", "Banana", "Clementine", "Damson"},\n            {"Elderberry", "Fig", "Grape", "Huckleberry"},\n            {"Indian Prune", "Jujube", "Kiwi", "Lime"}\n        };\n\n     dump("Row 0", table.twodim(0));\n    dump("Row 0", table.twodim(1));\ndump("Row 0", table.twodim(2));\n\n  }	0
522518	522468	Finding blank fields in an object - C#	public static IEnumerable<string> FindBlankFields(Staff staff)\n{\n    return staff.GetType()\n        .GetProperties(BindingFlags.Instance | BindingFlags.Public |\n            BindingFlags.NonPublic)\n        .Where(p => p.CanRead)\n        .Select(p => new { Property = p, Value = p.GetValue(staff, null) })\n        .Where(a => a.Value == null || String.IsNullOrEmpty(a.Value.ToString()))\n        .Select(a => a.Property.Name);\n}	0
18375359	18375190	How to get PRIMARY KEY column name of a table	string sql = "SELECT ColumnName = col.column_name FROM information_schema.table_constraints tc INNER JOIN information_schema.key_column_usage col ON col.Constraint_Name = tc.Constraint_Name AND col.Constraint_schema = tc.Constraint_schema WHERE tc.Constraint_Type = 'Primary Key' AND col.Table_name = '" + _lstview_item + "'";	0
12930975	12930840	How to select rows from DataTable based on Index / Row Number?	var result = table.AsEnumerable()\n                  .Where((row, index) => index > 1)\n                  .CopyToDataTable()	0
713761	713222	How to use CodeVariableDeclaraionStament to declare Arrays	Int32[] ints = INTARR();\nCodeExpression[] intExps = new CodePrimitiveExpression[ints.Length];\nfor (int i = 0; i < ints.Length; i++)\n   intExps[i] = new CodePrimitiveExpression(ints[i]);\nCodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(\n   "Int32[]", "x", new CodeArrayCreateExpression("Int32", intExps));	0
31648991	31647702	How to format double value as price without currency sign and with special case for no decimals	price.ToString(@"#,0.00;-#,0.00;0\,-").Replace(".00", ",-");	0
10720110	4796865	Are there standard naming conventions for this example of The Template Method Pattern?	public abstract class Widget\n{\n    public void PerformAction()\n    {\n        this.PerformActionImpl();\n    }\n\n    protected virtual void PerformActionImpl(){}\n}	0
28536134	28536092	Simple means of making a function non-blocking / async in C#?	private void button_Click(object sender, EventArgs e)\n{\n   Task.Run( () => SendEMail(address, subject, body) );\n}	0
27371329	27371126	Using secured websocket in C#	Server.MapPath("~/App_Data/MyCert.pfx")	0
1005466	1005454	Using the switch statement in a Windows Forms application	listBox1.Items.Add("Here is the text of the list box item");	0
19887889	19884486	How to adjust jpeg quality with ImageMagick.Net	using (MagickImage sprite = images.AppendHorizontally())\n{\n  sprite.Format = MagickFormat.Jpeg;\n  sprite.Quality = 10;\n  sprite.Resize(40, 40);\n  sprite.Write(spriteFile);\n}	0
3248610	3247771	How to handle events of members from another class/instance	Public Class ContextMenuManager\n    Public Event Click As EventHandler\n    Private WithEvents _myToolstripMenuItem As ToolStripMenuItem\n\n    Public Sub New()\n        ''...\n    End Sub\n\n    Private Sub _myToolstripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _myToolstripMenuItem.Click\n        RaiseEvent Click(Me, e)\n    End Sub\nEnd Class	0
5501853	5501815	Call c# from c++: how to pass nullptr to DateTime?	MyClass->DoSomething(Nullable<DateTime>());	0
29796554	29796253	ListView Refresh causes update of header view	public static void getListViewSize(ListView myListView) {\n        ListAdapter myListAdapter = myListView.getAdapter();\n        if (myListAdapter == null) {\n            //do nothing return null\n            return;\n        }\n        //set listAdapter in loop for getting final size\n        int totalHeight = 0;\n        for (int size = 0; size < myListAdapter.getCount(); size++) {\n            View listItem = myListAdapter.getView(size, null, myListView);\n            listItem.measure(0, 0);\n            totalHeight += listItem.getMeasuredHeight();\n        }\n      //setting listview item in adapter\n        ViewGroup.LayoutParams params = myListView.getLayoutParams();\n        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));\n        myListView.setLayoutParams(params);\n    }	0
26067104	26065600	How to get my time of my system in micro second?	string ZamanShoru = DateTime.Now.ToString("H:mm:ss.ffff")	0
16440303	16438543	Add text to word table in c# using word interop	thedocument.CustomDocumentProperties["NameOfTheCustomProperty"].Value = 1;	0
648055	611921	How do I delete a directory with read-only files in C#?	private static void DeleteFileSystemInfo(FileSystemInfo fileSystemInfo)\n{\n    var directoryInfo = fileSystemInfo as DirectoryInfo;    \n    if (directoryInfo != null)\n    {\n        foreach (var childInfo in directoryInfo.GetFileSystemInfos())\n        {\n            DeleteFileSystemInfo(childInfo);\n        }\n    }\n\n    fileSystemInfo.Attributes = FileAttributes.Normal;\n    fileSystemInfo.Delete();\n}	0
16986144	16981951	Getting RefCursor and VarChar outputs from the same Stored Procedure	OracleDataReader dr = ((OracleRefCursor)pRefcursor.Value).GetDataReader();	0
23659878	23608889	How do I redirect to another page from RadPane in ASP.NET?	window.top.location = "the-page-i-want-to-go-to.aspx"	0
12752059	12752008	Reading XML into a class that contains a List<Class>	tags = x.Element("tags").Elements("tag").Select(r => new Tag() { Column=r.Attribute("column"), Value = r.Value } );	0
17311378	17301945	Is it possible to use contextual bindings with StructureMap	x.For<MyThingyController>() \n// or better interface \n// x.For<IMyThingyController>()\n   .Use<MyThingyController>()\n    .Ctor<IThingy>("thingy1")\n     .Is<LegacyThingy>()\n    .Ctor<IThingy>("thingy2")\n     .Is<ShinyNewThingy>();	0
20691619	20691379	Hide certain text that displays in gridview	protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            if (e.Row.Cells[0].Text.Contains("Complete"))\n            {\n                e.Row.Cells[1].BackColor = System.Drawing.Color.Lime;\n            }\n        }\n    }	0
5915664	5915615	How to use string.Contains for list of values	new[]{"Ansi_nulls","Encrypted","Quoted_identifer", ...}.Contains(xmlNode);	0
32755260	32741949	Windows UI Automation select item of combobox	public void SetSelectedItem(string itemName, ITimeout timeout = null)\n{\n    this.GetSelf(timeout).Expand();\n\n    var list = this.GetSelf(timeout).FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List), timeout);\n    var listItem = list.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, itemName), timeout);\n\n    listItem.Select();\n}	0
13058135	13057990	Determining the path to the the local SQL Server CE database using Data Source	#if DEBUG\n    public static readonly string ConnectionString =\n        string.Format(@"Data Source=..\..\DbTest\{0}; password='{1}'", DbFileName, DbPassword);\n#else\n    public static readonly string ConnectionString =\n        string.Format(@"Data Source=|DataDirectory|\{0}; password='{1}'", DbFileName, DbPassword);\n#endif	0
8678188	8678154	Get Image size while uploading file to SQL 2008	Image img=Image.FromStream(stream);\nint width=img.Width;\nint height=img.Height;	0
9142643	9142628	Thread a sub with two arguments?	...\nstring kom = ...\nstring ddm = ...\n\nThread t = new Thread( () => send2( kom, ddm ) );	0
18375730	18375556	Linq SQL join on same table with group and sum	DailyStatistics\n.Join\n(\n    DailyStatistics,\n    x=>new{x.EntryDate, x.SiteID},\n    x=>new{x.EntryDate, x.SiteID},\n    (o,i)=>new \n    {\n        VisitorEntry=i.Metric,\n        VisitEntry=o.Metric,\n        VisitorDate = i.EntryDate ,\n        VisitDate = o.EntryDate ,\n        i.SiteID,\n        VisitorValue = i.Value,\n        VisitValue = o.Value\n    }\n)\n.GroupBy\n(\n    x=>\n    new\n    {\n        x.SiteID,\n        x.VisitDate\n    }\n)\n.Where\n(\n    x=>\n    x.VisitorEntry == "MyVisitors" &&\n    x.VisitEntry== "MyVisits" &&\n    x.VisitDate >= DateTime.Parse("2013-08-15")  &&\n    x.VisitDate <= DateTime.Parse("2013-08-21")\n)\n.Select\n(\n    x=>\n    new\n    {\n        x.Key.SiteID, \n        x.Key.VisitDate, \n        SumVisits = s.Sum(t => t.VisitValue ), \n        SumVisitors = s.Sum(x => x.VisitorValue ) \n    }\n)\n.OrderBy\n(\n    x=>x.VisitDate\n)	0
2686723	2686678	In .NET, at runtime: How to get the default value of a type from a Type object?	public object GetDefaultValue(Type t)\n{\n    if (t.IsValueType)\n    {\n        return Activator.CreateInstance(t);\n    }\n    else\n    {\n        return null;\n    }\n}	0
937820	937807	Is there a way in Linq to apply different calculations based on different conditions	var query = from p In products() \n              group p by p.Category into g \n              select new { Category = g.Key, \n                  TotalUnitsInStock = (g.key=="b") ? g.Avg(p => p.UnitsInStock) :\n                                      g.Sum(p => p.UnitsInStock));	0
11998344	11997210	Add notification sound file to exe in c#	var player = new System.Media.SoundPlayer();\nplayer.Stream = Properties.Resources.tada;\nplayer.Play();	0
22520146	22364320	NHibernate - Populating Collection with Stored Proc	Notice that stored procedures currently only return scalars and entities. \n<return-join> and <load-collection> are not supported	0
1079761	1079720	Problem with retrieving XML via HTTP and writing to file	XmlDocument doc = new XmlDocument();\ndoc.Load(url);\ndoc.Save(filename);	0
32923477	32922282	How to send an email to multiple email addresses in the database using Postal in ASP.NET MVC	//Email\nvar emailQuery = from o in db.Orders\n    from h in o.Hospital\n    where o.DeliveryID = model.ID \n//i'm not sure where this order comes from but if you \n//don't really have that then you may need to use your DeliverVM instead\n    select new { Email = h.Email };\n\nvar emails = emailQuery.ToList();\n\ndynamic email = new Email("Example");\nemail.ID = order.DeliveryID;\nemail.To = emails.Join(";"); // you can have more that one email because you have multiple orders\nemail.Send();	0
28345320	28343004	how to tell if my asp.net mvc application is accessed via a proxy?	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\npublic class BlockProxyAccessAttribute : ActionFilterAttribute\n{\n    private static readonly string[] HEADER_KEYS = { "VIA", "FORWARDED", "X-FORWARDED-FOR", "CLIENT-IP" };\n    private const string PROXY_REDIR_URL = "/error/proxy";\n\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        var isProxy = filterContext.HttpContext.Request.Headers.AllKeys.Any(x => HEADER_KEYS.Contains(x));\n\n        if (isProxy)\n            filterContext.Result = new RedirectResult(PROXY_REDIR_URL);\n    }\n}	0
5855009	5854973	Extracting tokens from a string with regular expressions in .NET	Regex.Split(s, @"(\[[A-Z]+\])")	0
357801	357790	C# Round Value of a Textbox	tb2_kva.Text = Math.Round(z, # Places).ToString();	0
9572768	9572722	Validating a console input	String venName = null;\nwhile (String.IsNullOrEmpty(venName)) {\n    Console.WriteLine("Venue Name - ");\n    venName = Console.ReadLine();\n}	0
26780690	26780558	Regex Help need to pull NFL Team name from a string	(=[A-Z])(\w|\%20|\.)+	0
30757436	30756880	What is the scope of public variable in different methods of a same class in Console C#	class Program\n{\n    static void Main(string[] args)\n    {\n        var obj = new Data();\n        obj.setData("First", "Last");\n        obj.GetDataToXml();\n        Console.ReadLine();\n    }\n}\n\nclass Data\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n\n    public void setData(string firstName, string lastName)\n    {\n        FirstName = firstName;\n        LastName = lastName;\n    }\n    public XDocument GetDataToXml()\n    {\n        XDocument doc = new XDocument(\n           new XElement("FirstName ", FirstName),\n           new XElement("LastName", LastName));\n        return doc;\n    }\n}	0
8633744	8633680	Easiest way in C# to find out if an app is running from a network drive?	private bool IsRunningFromNetworkDrive()\n    {\n        var dir = AppDomain.CurrentDomain.BaseDirectory;\n        var driveLetter = dir.First();\n        if (!Char.IsLetter(driveLetter))\n            return true;\n        if (new DriveInfo(driveLetter.ToString()).DriveType == DriveType.Network)\n            return true;\n        return false;\n    }	0
1393482	1393451	Select a random element from IList<> other than this one	public Element GetAnyoneElseFromTheList(Element el)\n{\n  Random rndElement = new Random();\n  int index;\n  if (this.ElementList.Count>1) \n  {\n     index = rndElement.Next(0,this.ElementList.Count-1);\n     if (this.ElementList[index] == el)\n        return this.ElementList[this.ElementList.Count-1];\n     else\n        return this.ElementList[index];\n  }\n else return null;\n}	0
17717489	17716370	How to copy format of one row to another row in Excel with c#	Range RngToCopy = ws.get_Range(StartCell, EndCell).EntireRow;\nRange RngToInsert = ws.get_Range(StartCell, Type.Missing).EntireRow;\noRngToInsert.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, oRngToCopy.Copy(Type.Missing));\n\n//ws is the worksheet object, set StartCell and EndCell as per your requirement	0
9396561	9375241	Active Directory: How to get a list of users according to a specific Organization unit	string selectedOu = ((System.Data.DataRowView)OuCBox.SelectedValue)).Row.ItemArray[0].ToString();	0
11117261	11117117	Complex sorting of XML using Linq	XDocument xDoc = XDocument.Load(....);\nforeach(var trans in xDoc.Descendants("Trans"))\n{\n    trans.ReplaceAll( trans.Elements().OrderBy(x=>x.Name.LocalName));\n}\n\nstring newXml = xDoc.ToString();	0
3534601	3534481	Width of items in ItemsControl	DimsContainer.ItemContainerGenerator.ContainerFromIndex(i);	0
18741610	18717878	Selenium WebDriver - If element present select it, if not ignore it and continue to next element	//Displayed\npublic static bool IsElementDisplayed(this IWebDriver driver, By element)\n{\n    if (driver.FindElements(element).Count > 0)\n    {\n        if (driver.FindElement(element).Displayed)\n            return true;\n        else\n            return false;\n    }\n    else\n    {\n        return false;\n    }\n}\n\n//Enabled\npublic static bool IsElementEnabled(this IWebDriver driver, By element)\n{\n    if (driver.FindElements(element).Count > 0)\n    {\n        if (driver.FindElement(element).Enabled)\n            return true;\n        else\n            return false;\n    }\n    else\n    {\n        return false;\n    }\n}	0
1143304	1143233	Inheritting from ListViewItemCollection	public class MyListViewItemCollection : ListView.ListViewItemCollection\n{\n    public MyListViewItemCollection(ListView owner)\n        : base(owner)\n    {\n    }\n}	0
7738349	7708734	How to transfer item from one datalist to other datalist?	ArrayList ImgArry = new ArrayList();\n    path = objGetBaseCase.GetImages(TotImgIds);\n    ImgArry.Add(SelImgId);\n    ImgArry.Add(SelImgpath);//image name\n    ImgArry.Add(SelImgName);//image path\n    //path.Remove(ImgArry);\n    List<ArrayList> t = new List<ArrayList>();\n    if (newpath.Count > 0)\n        t = newpath;\n    t.Add(ImgArry);\n    newpath = t;\n    for (int i = 0; i < newpath.Count; i++)\n    {\n        ArrayList alst = newpath[i];\n        newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);\n\n    }\n    dlstSelectedImages.DataSource = newtb;\n    DataBind();\n\n    path = objGetBaseCase.GetImages(TotImgIds);\n    for (int i = 0; i < path.Count; i++)\n    {\n        ArrayList alst = path[i];\n        tb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);\n\n    }\n    dlstImage.DataSource = tb;\n    DataBind();	0
6644892	6605530	Getting events from the scrollbar buttons?	foreach( var o in horizontalBar.GetVisualDescendants( ) )\n            {\n               if(o is RepeatButton)\n               {\n                     //set call back based on the name of the repeatbutton\n                }\n}	0
25696052	25696014	Depth First Search without stack	Console.WriteLine(node.Text);\nfor (Int i = 0; i < node.Nodes.Count; i++)\n    Foo(root.Nodes[i]);	0
2877356	2876527	Safe & Simple Access to Explicit Interface Members in C#	public static class Converter\n{\n    public static T ReturnAs<T>(T item)\n    {\n        return item;\n    }\n}\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var item = new MyType();\n\n        // Option 1 - Implicit cast. Compile time checked but takes two lines.\n        IMyType item2 = item;\n        System.Console.WriteLine(item2.SayHello());\n\n        // Option 2 - One line but risks an InvalidCastException at runtime if MyType changes.\n        System.Console.WriteLine(((IMyType)item).SayHello());\n\n        // Option 3 - One line but risks a NullReferenceException at runtime if MyType changes.\n        System.Console.WriteLine((item as IMyType).SayHello());\n\n        // Option 4 - compile time one liner\n        Converter.ReturnAs<IMyType>(item).SayHello();\n    }\n}	0
31483190	31480365	How to include spaces between equal sign when working with ini files c#?	IniOptions options = new IniOptions();\noptions.KeySpaceAroundDelimiter = true;\n\nIniFile ini = new IniFile(options);\nini.Load("path to your input INI file");\n\n// Do something with file's sections and their keys ...\n\nini.Save("path to your output INI file");	0
4829015	4828803	How to encrypt a string with private key and decrypt with public key?	static byte[] GenerateDigitalSignature(byte[] data, RSAParameters asymmetricKey)\n{\n  using (var rcsp = new RSACryptoServiceProvider())\n  using (var cp = new SHA1CryptoServiceProvider())\n  {\n    rcsp.ImportParameters(asymmetricKey);\n\n    return rcsp.SignData(data, cp);\n  }\n}	0
3074369	3074356	add behavior to group of windows form controls	using System;\nusing System.Windows.Forms;\nusing System.Drawing;\n\nclass MyTextBox : TextBox\n{\n    public MyTextBox()\n    {\n        SetStyle(ControlStyles.UserPaint, true);\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        if (string.IsNullOrEmpty(this.Text))\n        {\n            e.Graphics.DrawString("My info string...", this.Font, System.Drawing.Brushes.Gray, new System.Drawing.PointF(0, 0));\n        }\n        else\n        {\n            e.Graphics.DrawString(Text, this.Font, new SolidBrush(this.ForeColor) , new System.Drawing.PointF(0, 0));\n        }\n    }\n\n    protected override void OnTextChanged(EventArgs e)\n    {\n        Invalidate();\n        base.OnTextChanged(e);\n    }\n}	0
18745986	18745045	Placing an ellipse on a canvas programmatically on a Windows 8 store app	Canvas.SetLeft(newEllipse, aCanvas.ActualWidth/2.0);\nCanvas.SetTop(newEllipse, aCanvas.ActualHeight/2.0);	0
19809005	19808855	Calculate the sum of gridview column data and store its value in a variable	var gridView = sender as GridView;\nvar dataSource = gridView.DataSource as IEnumerable<YourDataObject>;\ne.Row.Cells[3].Text = dataSource.Sum(item => item.YourProperty).ToString();	0
1225832	1225829	how to get users' application data folder using C#?	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
22845646	22833564	Can I re-use AutoNumber value during INSERT to populate another field? C# & Access Database	OleDbConnection cnJetDB = new OleDbConnection(strDB);\n\n        OleDbCommand cmd = new OleDbCommand();\n        cmd.CommandText = "INSERT INTO tableComponents (ComponentDesc) VALUES (@ComponentDesc)";\n        cmd.Parameters.AddWithValue("@ComponentDesc", partDesc);\n\n        cnJetDB.Open();\n\n        cmd.Connection = cnJetDB;\n        cmd.ExecuteNonQuery();\n\n        cmd.CommandText = "SELECT @@IDENTITY";\n        int newID = (int)cmd.ExecuteScalar();\n        MessageBox.Show(newID.ToString());\n\n        OleDbCommand cmd2 = new OleDbCommand();\n        cmd2.CommandText = "UPDATE tableComponents SET ComponentCode=@CompCode WHERE ComponentID="+newID;\n        cmd2.Parameters.AddWithValue("@CompCode", "PREFIX" + newID.ToString());\n\n        cmd2.Connection = cnJetDB;\n        cmd2.ExecuteNonQuery();\n\n        cnJetDB.Close();	0
30602798	30602622	How to populate UL from code-behind	foreach (string wrWG in workGroupLists)\n{\n  HtmlGenericControl li = new HtmlGenericControl("li");\n  li.InnerText = wrWG; \n  ulO.Controls.Add(li);\n}	0
4835596	4835523	How do i redirect input output to file instead of stdout?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            String s;\n            while ((s = Console.In.ReadLine())!= null)\n            {\n                Console.Out.WriteLine(s);\n            }\n        }\n    }\n}	0
21017791	21017005	Replace exponential values to double in mathematical expression	String formula = "10993.657030812325*8.20681165367255E-05";\n  String pattern = @"(([1-9][0-9]*\.?[0-9]*)|(\.[0-9]+))([Ee][+-]?[0-9]+)"; \n\n  // Let's change format of each double precision in the formula:\n  String result = Regex.Replace(formula, pattern, (match) => {\n    // Simple formating; may be you should use more elaborated one\n    Double db = Double.Parse(match.Value, CultureInfo.InvariantCulture);\n    // Now, you should format out the Double db:\n    // First eliminate exponent (F99 is the maximum possible; F100 won't do) \n    String St = db.ToString("F99", CultureInfo.InvariantCulture);\n\n    // Next eliminate trailing '0' \n    if (St.IndexOf('.') >= 0)\n      St = St.TrimEnd('0');\n\n    return St.TrimEnd('.'); \n  });	0
1642721	1642659	Is it more efficient to compare ints and ints or strings and strings	System.Diagnostics.Stopwatch sw=new System.Diagnostics.Stopwatch();\n\n\nint a  = 5;\nstring b = "5";\n\nsw.Start();\n\nfor (int i=0;i<1000000;i++)\n{\nif(a == int.Parse(b))\n{\n\n} \n}\n\nsw.Stop();\n\nConsole.WriteLine("a == int.Parse(b) milliseconds: " + sw.ElapsedMilliseconds);\n\nsw.Reset();\n\nsw.Start();\n\nfor (int i=0;i<1000000;i++)\n{\nif(a.ToString() == b)\n{\n\n}\n}\n\nsw.Stop();\n\nConsole.WriteLine("a.ToString() == b milliseconds: " + sw.ElapsedMilliseconds);	0
15619633	15429268	How to force IRuleBuilder in AbstractValidator to act as 'if' statement?	RuleFor(x => x.Content)   \n    .Cascade(CascadeMode.StopOnFirstFailure)    \n        .NotEmpty()   \n        .Must(content => content.Trim().Length > 0);	0
5463537	5463519	How can I add a click event to my div from code behind?	c#\n_myButton.Attributes.Add("onclick", "return confirm_delete();");\n\njavascript:\nfunction confirm_delete()\n{\n  if (confirm("Are you sure you want to delete the custom search?")==true)\n    return true;\n  else\n    return false;\n}	0
1819145	1819106	How to reset the trackbar in Visual C#?	trackBar1.Value = trackBar1.Minimum	0
6034312	6034297	Replacing all the '\' chars to '/' with C#	string input = @"c:\abc\def";\nstring result = input.Replace(@"\", "/");	0
10062292	10062217	How to access controls in Main Master page from content page in Nested Master Page	TextBox txtBox = this.Master.Master.FindControl("txtMasterPageMaster") as TextBox;	0
28556819	28153494	Parse.com retrieving count of last day sale in unity	IEnumerator GetSales()\n{   \n    int result = -1;\n\n    ParseQuery<ParseObject> USQuery = ParseObject.GetQuery ("Sales").WhereEqualTo ("transactionType", "Purchase").WhereGreaterThan ("createdAt",DateTime.Now.AddDays(-1));\n\n    USQuery.CountAsync().ContinueWith(t =>\n    {\n        result=t.Result;  \n    });\n\n    while (result == -1) yield return new WaitForSenOfFrame();\n    labelUSSale.text=result.ToString();\n\n}	0
26075847	26075697	Repeatedly Iterating Through a List	int currentElementIndex = 0;\n//..\n\nif (nextElementIsNeeded)\n{ \n  currentElementIndex = (currentElementIndex + 1) % foo.Count;\n  thing = foo[currentElementIndex]; \n}	0
31070656	31070443	How to find out the duplicate characters in a string?	string test = "aababc";\n        var result = test.GroupBy(c => c).Where(c => c.Count() > 1).Select(c => new { charName = c.Key, charCount = c.Count()});	0
9913407	9913373	modifier key combination input	private void MyRTB_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (Keyboard.Modifiers == ModifierKeys.Control)\n        {\n            if (e.Key == Key.B) \n            {\n                MakeBold();\n            }\n            else if (e.Key == Key.I)\n            {\n                MakeItalic();\n            }\n            else if (e.Key == Key.U)\n            {\n                Underline();\n            }\n        }\n    }	0
1820948	1820915	How can I format DateTime to web UTC format?	string foo = yourDateTime.ToUniversalTime()\n                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");	0
5890037	5878023	HDI: Constrain Property Set on Linq-To-Sql class	public partial class MyLinqToSqlClass\n{\n    partial void OnNumberChanging(int value)\n    {\n        //your code here\n        //throw exception if necessary when validating\n    }\n}	0
33297403	32160583	How to bind bar series in telerik c# to my DataTable	barSeries.DataPoints.Add(new CategoricalDataPoint(expAmount,expType)); ( in a while loop)	0
1050688	1050663	Get a boolean value from DataTable	if(((bool)dbDataSet.Tables["productGeneral"].Rows[0]["Active"] == false))	0
24715672	23871110	StackExchange.Redis failing to connect with Mono in Mac OS X	./monobuild.bash	0
8474268	8473344	Get filenames by URL Directory in WinService or WinForms application	string\n    storeLocation = "C:\\dump",\n    fileName = "",\n    baseURL = "http://download.geonames.org/export/dump/";\n\nWebClient r = new WebClient();            \nstring content = r.DownloadString(baseURL);\nforeach (Match m in Regex.Matches(content, "<a href=\\\"[^\\.]+\\.zip\">"))\n{\n    fileName = Regex.Match(m.Value, "\\w+\\.zip").Value;\n    r.DownloadFile(baseURL + fileName, Path.Combine(storeLocation, fileName));\n}	0
8645081	8644815	Move object for a specified distance over a specific amount of time	public Form1()\n{\n    InitializeComponent();\n\n    const int maxWidth = 200;\n    const int maxTicks = 10;\n    var currentTick = 0;\n\n    // Create panel and add it to this form\n    var panel = new Panel { Location = new Point(1, 1), BackColor = Color.Blue, Width = 0, Height = 5 };\n    Controls.Add(panel);\n\n    // Create timer that handles updates\n    var t = new Timer { Interval = 1000 };\n    t.Tick += delegate\n    {\n        panel.Width = maxWidth / maxTicks * currentTick;\n        if (currentTick++ != maxTicks)\n            return;\n        panel.BackColor = Color.Green;\n        t.Dispose();\n    };\n    t.Start();\n}	0
25424192	25424112	Get properties that are of type ICollection<BaseEntity>	var baseEntProps = properties\n.Where(p => p.PropertyType.IsGenericType &&\n            p.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) &&\n            typeof(BaseEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0]));	0
26027427	26027103	adding two styles to a button in windows store app using xaml and c#	ControlButton.Style = Application.Current.Resources["buttonStyle2"] as Style	0
25991130	25990354	Need help for c# Regex	var strings = new List<string>() { "Real Madrid", "Real Madrid,Madrid", "Real Madrid(Spain)", "Real Madrid,Madrid(Spain)" };\n\nforeach (var str in strings)\n{\n    var match = Regex.Match(str, @"^(?<club>[^,]+)(?:,(?<city>[^\(]+))?(?:\((?<nation>[^\)]+)\))?$");\n\n    var name = match.Groups["club"].Value;\n    var city = match.Groups["city"].Value;\n    var country = match.Groups["nation"].Value;\n}	0
23081585	23081106	GotKeyboardFocus event from child to parent window	public partial class App : Application\n{\n    public App()\n    {\n        EventManager.RegisterClassHandler(\n            typeof (UIElement),             \n            UIElement.GotKeyboardFocusEvent,\n            new RoutedEventHandler(GotKeyboardFocusEventHandler));\n\n        EventManager.RegisterClassHandler(\n            typeof (UIElement), \n            UIElement.LostKeyboardFocusEvent,\n            new RoutedEventHandler(LostKeyboardFocusEventHandler));\n    }\n\n    private void GotKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)\n    {\n       ...\n    }\n\n    private void LostKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)\n    {\n       ...\n    }\n}	0
17492130	17474082	Assembly created dynamically from Webservice - how to get the .CS code at runtime?	TextWriter tw = new IndentedTextWriter(new StreamWriter(PathAndName + ".cs", false), "    ");\ncompiler.GenerateCodeFromCompileUnit(codeUnit, tw, new CodeGeneratorOptions());	0
10710567	10710465	How to highlight a whole word, given its ending index	var prevSpace = richTextBox.Text.LastIndexOf(' ', offset);\nvar length = prevSpace = -1 ? offset + 1 : offset - prevspace;	0
8145376	8145340	What's a good syntax in C# for "If foo isn't null, return a property of it, otherwise null"	return _data != null ? _data.name : null;	0
3004644	3004513	How to use interfaces in exception handling	class MyClass\n{\n    public MyClass(IMyExceptionLogger exceptionLogger)\n    {\n        ....\n        exceptionLogger.LogException(e);\n    }\n}	0
25876567	20322525	Replace checkboxes while exporting grid to excel	protected void Export_to_Excel(object sender, EventArgs e)\n    {\n        //System.Diagnostics.Debugger.Break();\n        Response.Clear();\n        Response.AddHeader("content-disposition", "attachment;filename=PatientSearchReport.xls");\n        Response.ContentType = "application/vnd.xlsx";\n        System.IO.StringWriter stringWrite = new System.IO.StringWriter();\n        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);  \n        GridView1.RenderControl(htmlWrite);\n        string html2 = Regex.Replace(stringWrite.ToString(), @"(<input type=""image""\/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        html2 = Regex.Replace(html2, @"(<input class=""checkbox""\/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        html2 = Regex.Replace(html2, @"(<a \/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        Response.Write(html2.ToString());\n        Response.End();\n    }	0
1328254	1328220	split ARGB into byte values	b = (byte)(myColor & 0xFF);\ng = (byte)((myColor >> 8) & 0xFF);\nr = (byte)((myColor >> 16) & 0xFF);\na = (byte)((myColor >> 24) & 0xFF);	0
7065140	7064950	Run Custom Command in C# Windows Service	procStartInfo.RedirectStandardError = true;\n...\nstring error = proc.StandardError.ReadToEnd(); \nproc.WaitForExit();	0
33304085	33303634	How do you force a Console App Project to include a folder in the build?	xcopy /E "$(ProjectDir)\Content" "$(TargetDir)\Content\*"	0
20220079	20220078	Matrix of double values to RGB image in .NET	int colorindex = (int)(x*k);\nif(colorindex==k)   // handle the case x==1.0\n   colorindex--;	0
29581930	29581863	how to assign MouseMove, MouseDown and MouseClick functions to several controls creates dynamiqumement?	private void label1_MouseMove(object sender, MouseEventArgs e)\n{\n\n    Label label = (Label)sender;\n\n    if (e.Button == System.Windows.Forms.MouseButtons.Left)\n    {\n        label.Left = e.X + label.Left - MouseDownLocation.X;\n        label.Top = e.Y + label.Top - MouseDownLocation.Y;\n    }\n}	0
32130093	32130015	Filtering a UserDefinedFunctionCollection using LINQ?	private void DebugSqlUserDefinedFunctions(SqlCommand cmd)\n{\n    Server svr = new Server(new ServerConnection(cmd.Connection));\n    foreach (var udf in svr.Databases[cmd.Connection.Database].UserDefinedFunctions.Cast<Microsoft.SqlServer.Management.Smo.UserDefinedFunction>().Where(udf => !udf.IsSystemObject))\n    {\n        System.Diagnostics.Debug.WriteLine(udf.Name);\n    }\n}	0
12389302	12389199	How do I assign array of Datagridview in winform in C#	DataGridView [] myArray = new DataGridView [5];\nmyArray[0] = new DataGridView();\n// ...	0
6939837	6939436	C# remove extra carriage returns from Stream	string text = File.ReadAllText(FilePath);\n\ntext = text.Replace("\r\r", "\r");\n\nFile.WriteAllText(FilePath + ".modified", text);	0
30370236	30369862	Dynamically adding textbox value to XML file	var xmlNode = new XElement("TextBoxes");\nforeach (TextBox text in this.Controls.OfType<TextBox>())\n    {\n        xmlNode.Add(new XElement("TextBox",\n                    new XElement("name", text.Name.ToString())\n                )\n            );\n    }  \nxmlNode.Save("Test.xml");	0
34221591	34212543	Microsoft Automation UI mouse click on a given position	using Microsoft.Test.Input;\nusing System.Drawing;\n\nMouse.MoveTo(new Point(1000, 1000));\nMouse.Click(MouseButton.Right);	0
23522798	23522439	Capture mouse events outside of the control	protected override void WndProc(ref Message m)\n{\n    base.WndProc(ref m);\n\n    const int WM_CAPTURECHANGED = 0x0215;\n    if (m.Msg == WM_CAPTURECHANGED)\n    {\n        if (!textBox1.Capture && textBox1.Focused && textBox1.Visible)\n        {\n            textBox1.Visible = false;\n        }\n    }\n}	0
27978548	27978483	Convert custom date to mysql datetime	string strd = "6/11/2014 9:00";\nDateTime dt ;\n//convert datetime string to datetime\nif(DateTime.TryParse(strd, out dt))\n{\n  //convert datetime to custom datetime format \n  Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}", \n                   dt); ;\n}	0
4037117	4036896	Calling Method of a Class within StructureMap Registry Configuration	For<IScheduler>().Use(c => c.GetInstance<ISchedulerFactory>().GetScheduler());	0
23714932	23714559	Docking a WPF window to left/right sides of the screen windows 7/8	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\n\nnamespace StackOverflowWPF\n{\n   /// <summary>\n   /// Interaction logic for MainWindow.xaml\n   /// </summary>\n   public partial class MainWindow : Window\n   {\n      public MainWindow()\n      {\n         InitializeComponent();\n      }\n\n      private void Button_Click_1(object sender, RoutedEventArgs e)\n      {\n         this.Top = 0;\n         this.Left = 0;\n         System.Drawing.Rectangle screenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;\n         this.Width = screenBounds.Width / 2;\n         this.Height = screenBounds.Height;\n      }\n   }\n}	0
2579672	2579648	Background worker while loop	while(true)	0
16141261	16139140	How to update db according to the changes of C# DataGridView?	private void SaveButton_Click(object sender, EventArgs e)\n    { \n     System.Data.DataTable dsnew = ((DataView)gridView1.DataSource).Table;\n    }	0
17285121	17285071	MySql get number of rows	using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))\n{\n    connect.Open();\n    return Convert.ToInt32(cmd.ExecuteScalar());\n}	0
16730579	16730079	Replacing some substring occurence inside a string	string patternClassName = @"(?<=class\s)\s*\S*";\nstring patternClassConstructor = @"(?<=public\s)\s*\S*";\n\nprivate string Change(string source, string newName)\n        {\n            string changeClassNameResult = Regex.Replace(source, patternClassName, newName, RegexOptions.IgnoreCase);\n\n            Match match = new Regex(patternClassName).Match(source);\n\n            if (match.Success)\n            {\n                return Regex.Replace(changeClassNameResult, patternClassConstructor + match.Value, newName, RegexOptions.IgnoreCase);\n            }\n            else\n            {\n                return changeClassNameResult;\n            }\n        }	0
32091108	32091021	Call a function when button is clicked in a different window (WPF app)	namespace AppWpf10\n{\n    public partial class Prepare : System.Windows.Controls.Page\n    {\n        private void button_Click(object sender, RoutedEventArgs e)\n        {\n            Choice win2 = new Choice();\n            win2.Show();\n            win2.button1.Click += clickEventHandler;\n        }\n\n        private void clickEventHandler(object sender, RoutedEventArgs e)\n        {\n            DoStuff();\n        }\n\n        public void DoStuff()\n        {\n            //\n        }\n    }\n}	0
5894503	5894354	How to get host domain from asp.net	Request.Url.GetLeftPart(UriPartial.Authority)	0
16361979	16361685	How to get Name by string Value from a .NET resource (RESX) file	private string GetResxNameByValue(string value)\n    {\n            System.Resources.ResourceManager rm = new System.Resources.ResourceManager("YourNamespace.YourResxFileName", this.GetType().Assembly);\n\n\n        var entry=\n            rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true)\n              .OfType<DictionaryEntry>()\n              .FirstOrDefault(e => e.Value.ToString() ==value);\n\n        var key = entry.Key.ToString();\n        return key;\n\n    }	0
16041661	16040624	MSBuild custom rules	error: <message>\n<filename>: error: <message>\n<filename> (<line>): error: <message>\n<filename> (<line>,<column>): error: <message>	0
9400660	9400449	how to set raddatepicker date input box with c#	rdpShipDate.SelectedDate = DateTime.Today;	0
33658042	33657854	Implementing an event inherited from an interface	public class Shell : IShell\n    {\n        public event ModuleShownEventHandler ModuleShown;\n\n        public void OnModuleShown()\n        {\n            ModuleShownEventHandler handler = ModuleShown;\n            if (handler != null)\n            {\n                handler(this, new ModuleShownEventArgs());\n            }\n        }\n    }	0
26317421	26315409	c# regex to get a text onto the same line	private static string congatenateMultiLineHeaderStrings(string output, string[] headersArray)\n{\n    string[] outputLinesArray = output.Split('\n');\n    string outputOneLinePerHeader = "";\n    for (int lineNo = 0; lineNo < outputLinesArray.Length; lineNo++) //for each line\n    {\n        bool hasHeader = false;\n        for (int headerNo = 0; headerNo < headersArray.Length; headerNo++) //for each header....\n        {\n            if (outputLinesArray[lineNo].Contains(headersArray[headerNo])) //if the line contains a header...\n            {\n                hasHeader = true;\n            }\n        }\n        if (!hasHeader)\n        {\n            outputOneLinePerHeader += " "+outputLinesArray[lineNo]; //outputLinesArray[lineNo];//attach this line to prev\n        }\n        else\n            outputOneLinePerHeader += "\n" + outputLinesArray[lineNo];\n    }\n    return outputOneLinePerHeader;\n}	0
18569421	18567575	How to get checkbox checked value from Treeview in c#?	private List<TreeNode> AllCheckedNodes = new List<TreeNode>();\n\nprivate void GetAllCheckedNodes()\n{\n    for (int i = 0; i < TreeView1.CheckedNodes.Count; i++)\n    {\n        AllCheckedNodes.Add(TreeView1.CheckedNodes[i]);\n    }\n}	0
10423567	10406786	RichTextBox Help saving *custom* links	foreach (ListViewItem keyword in Keywords.Items)\n            {\n                System.Text.RegularExpressions.Regex oKeyword = new System.Text.RegularExpressions.Regex(@"\b" + keyword.Text + @"\b");\n\n                foreach (System.Text.RegularExpressions.Match match in oKeyword.Matches(rtb.Text))\n                {\n                    int index = match.Index;\n                    int length = match.Length;\n\n                    rtb.Select(index, length);\n                    //This next bit is made available through the use of http://www.codeproject.com/Articles/9196/Links-with-arbitrary-text-in-a-RichTextBox\n                    rtb.InsertLink(match.Value);  \n                }\n            }	0
8350842	8349513	HTML Scraping using Html Agility Pack	HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(html);\n\nstring imgValue = doc.DocumentNode.SelectSingleNode("//img[@id = \"captcha_img\"]").GetAttributeValue("src", "0");	0
10796072	10794356	facebook api with private message multiple to (friends)	var publish = \n\n    {\n              method: 'stream.publish',\n              message: 'Some kind of test',\n              uid: uid,\n              attachment: {\n                name: 'Test',\n                caption: 'Facebook API Test',\n                description: ('Sure hope it worked!'),\n                href: 'http://www.test.com/',\n                media: [\n                  {\n                    type: 'image',\n                    href: 'http://test.com/',\n                    src: 'http://test.com/image.jpg'\n                  }\n                ]\n              },\n              action_links: [\n                { text: 'Your text', href: 'http://www.test.com/' }\n              ],\n              user_prompt_message: 'Share your thoughts about test'\n    };\n\n    publish.target_id = friendID;\n    FB.ui(publish);\n\n    publish.target_id = friendID;\n    FB.ui(publish);\n\n            return false;	0
34244213	34244135	C# How to use regex to find all ints in a big string	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string input = "[{\"a\":{\"e\":{\"e\":161,\"a\":\"blue\",\"d\":{\"e\":-14,\"a\":\"red\",\"d\":{\"c\":\"yellow\",\"a\":[-35,0],\"b\":\"orange\",\"d\":";\n            string pattern = @"[-+]?\d+";\n            MatchCollection matches = Regex.Matches(input, pattern);\n            List<int> output = new List<int>();\n            foreach (Match match in matches)\n            {\n                output.Add(int.Parse(match.Value));\n            }\n            int sum = output.Sum();\n\n        }\n    }\n}\n???	0
1474301	1474292	need an example of a get and set	public static string FormatStr\n{\n    get\n    {\n         return Product == "test" ? "something" : "other";\n    }\n}	0
15033814	15033697	How to draw with replacement instead of blending	Bitmap bmp = new Bitmap(50, 50, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);\nusing (Graphics g = Graphics.FromImage(bmp))\n{\n    g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;\n    g.FillRectangle(Brushes.Black, 0, 0, 50, 50);\n    g.FillEllipse(Brushes.Transparent, 25, 0, 25, 25);\n    g.DrawLine(Pens.Transparent, 0, 0, 50, 50);\n    g.Flush();\n}\nbmp.Save("Test.bmp");	0
28362796	28361556	MVC4 C# Project: Provide a single instance of an object across the application	var builder = new ContainerBuilder();\nbuilder.RegisterType<YourClassGoesHere>().SingleInstance();	0
15318143	15318091	Indented JSON From Entity Framework	JsonConvert.SerializeObject()	0
3053673	3053646	Problems changing properties on a control using the controls name	private Control FindControl(Control ctr, string name)\n{\n    Control c = null;\n    for (int i = 0; i < ctr.Controls.Count; i++)\n    {\n        if (string.Equals(ctr.Controls[i].ID, name, StringComparison.CurrentCultureIgnoreCase))\n        {\n            c = ctr.Controls[i];\n            break;\n        }\n        if (ctr.Controls[i].Controls.Count > 0)\n        {\n            c = FindControl(ctr.Controls[i], name);\n            if (c != null)\n                break;\n        }\n    }\n\n    return c;\n}	0
15523424	15153303	Replacing values in XML file	string oldText = File.ReadAllText(filePath);\nstring newText = oldText.Replace("&<", "and<");\nFile.WriteAllText(filePath, newText, Encoding.UTF8);\nxmlDoc = new XmlDocument();\nxmlDoc.Load(filePath);	0
12608305	12607525	Custom Assembly Attribute Issue Across Assemblies	string assemblyFile = @"D:\My Documents\Visual Studio 2008\Projects\ClassLibrary1\bin\x64\Debug\AssemblyB.dll";\nbyte[] assemblyBytes = File.ReadAllBytes(assemblyFile);\n\nvar assembly = Assembly.Load(assemblyBytes); // Get assembly B \nvar description = assembly.GetCustomAttributes(false).OfType<AssemblyDescriptionAttribute>().SingleOrDefault(); \nvar category = assembly.GetCustomAttributes(false).OfType<AssemblyCategoryAttribute>().SingleOrDefault();	0
33294025	33293934	Updating a WinForm label value from code without buttons	void UpdateCounter()\n{\n    if (InvokeRequired)\n    {\n        BeginInvoke(new MethodInvoker(UpdateCounter));\n        return;\n    }\n    CounterValue.Text = Counter.ToString();\n}	0
13366721	13365331	Can my MVC view display only the date portion of a SQL datetime field?	using System.ComponentModel.DataAnnotations;\nclass myModel {\n  [DataType(DataType.Date)]\n  public DateTime OccurencDate {get;set;}\n}	0
5211178	5210950	How to detect an application executed by a Process whether the application stops working due to an invalid input?	p.WaitForExit();\nif (p.ExitCode == 0) {\n    // Success\n} else {\n    // Failure\n}	0
28045190	28045111	Compare two strings in two different ways	(U+200E)	0
5433573	5432380	using fluent nhibernate, is there anyway to have a private property mapped	Map(Reveal.Member<string>("privateProperty"))	0
16111351	16111303	How to delete all files but leave directory structure intact?	foreach (var file in Directory.EnumerateFiles("path", "*", System.IO.SearchOption.AllDirectories))\n{\n    //TODO consider error handling\n    File.Delete(file);\n}	0
22162574	22159248	How to stub 2nd call of method?	[TestMethod]\npublic void TestMethod1()\n{\n    using (ShimsContext.Create())\n    {\n        Something.Fakes.ShimClassA.MethodA = () =>\n        {\n            Something.Fakes.ShimClassA.MethodA = () =>\n            {\n                return "Second";\n            };\n            return "first";\n        };\n        var f = Something.ClassA.MethodA();      // first\n        var s = Something.ClassA.MethodA();      // second\n        var t = Something.ClassA.MethodA();      // second\n    }\n\n    var orig = Something.ClassA.MethodA();      // This will use the original implementation of MethodA\n\n}	0
8425643	8425153	rijindael writing and reading back key from file	// Save key and IV\nusing (var rijndael = new RijndaelManaged())\nusing (var writer = new BinaryWriter(File.Create("yyy.dat")))\n{\n    writer.Write(rijndael.Key, 0, 32);\n    writer.Write(rijndael.IV, 0, 16);\n}\n\n// Restore key and IV\nusing (var rijndael = new RijndaelManaged())\nusing (var reader = new BinaryReader(File.OpenRead("yyy.dat")))\n{\n    rijndael.Key = reader.ReadBytes(32);\n    rijndael.IV = reader.ReadBytes(16);\n}	0
5961354	5961229	How to get reference of DropDownList into codebehind?	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    DropDownList DropDownList2 = ((DropDownList)((DropDownList)sender).Parent.FindControl("DropDownList2"));\n}	0
22108974	22108169	Subtract the lowest number from the given array	double[] myCharges = { 20, 33.89, 84, 61.55 };\n\nConsole.WriteLine("Total of MyCharges are {0:C}", myCharges.Sum());\n\n// Here is the trick: remove the smallest charge from the bill<br />\nmyCharges = myCharges.Where(n => n != myCharges.Min()).ToArray();\n\nConsole.WriteLine("New Total After Smallest Charge Removed {0:C}", myCharges.Sum());\nConsole.WriteLine("Average of MyCharges are {0:C}", myCharges.Average().ToString("0.00"));\nConsole.ReadKey();	0
19048151	18880521	How to access custom headers on received reply message in my REST client?	WebOperationContext.Current.IncomingResponse	0
10445971	10445831	Programmatically clicking on dataGridView header cells	datagridview.sort(DataGridviewColumn column, System.ComponentModel.ListSortDirection direction);	0
21347443	21344684	Getting single response from SQL Server stored procedure with C#	IF @UserID > 0\n        BEGIN\n            INSERT [Audit] ([GUID], Created, UserID, ActionType, Action, Level)\n            VALUES (@GUID, getdate(), @UserID, 'Authentication', 'Test Authentication', 'Success')\n\n            SELECT  'http://www.ttfakedomain.com/Logon.aspx?id=' + CAST(@GUID AS nvarchar(50))\n        END\n    ELSE\n        SELECT 'Couldn''t find a user record for the CCOID ' + @CCOID\n\n\nRETURN	0
13611631	13598840	Offsetting a 3D object in the camera's view	float verticalOffset = 1.65f;  \nfloat longitudinalOffset = 0f;  \nfloat lateralOffset = .2f;  \n\nGunWorldMatrix = Matrix.Invert(view); // GunWorldMatrix is now a world space version of the camera's Matrix with position & orientation of the camera  \nVector3 camPosition = GunWorldMatrix.Translation;// note position of camera so when setting gun position, we have a starting point.  \n\nGunWorldMatrix *= Matrix.CreateFromAxisAngle(GunWorldMatrix.Up, 0.15f); // gives the gun that slight angle to point towards target while laterally offset a bit  \n\nVector3 gunPositionOffsets = (GunWorldMatrix.Up * verticalOffset) +  \n                                (GunWorldMatrix.Forward * longitudinalOffset) +  \n                                (GunWorldMatrix.Right * lateralOffset);  \n\nGunWorldMatrix.Translation = camPosition + gunPositionOffsets;	0
33175528	33175381	How we can refresh items text in ListBox without reinserting it?	listBox1.Items[0] = listBox1.Items[0];	0
15239894	15239855	String functions to show a substring	if (myString.Length > 90)\n{\n    myString = myString.Substring(0, 90) + "..."\n}	0
31450998	31450066	How to solve threads conflict because of long time cost of SQL statements?	list=DataBaseO.getdata();\nif(list.id not in DataBaseB)\n{\nlock(theLock) {\n        insert data into DatabaseA;\n}\nlock (theLock) {\n        insert log into DatabaseB;\n}\n}	0
23800600	23800555	how we get data from xml file using c#	var doc = XDocument.Parse(\n    @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>\n    <result>\n        <country>India</country>\n        <pincode>700001</pincode>\n        <paymode>Prepaid</paymode>\n        <service>Yes</service>\n    </result>");\n\n\nvar country = doc.Root.Descendants().Single(d => d.Name == "country").Value;\nvar pincode = doc.Root.Descendants().Single(d => d.Name == "pincode").Value;\nvar paymode = doc.Root.Descendants().Single(d => d.Name == "paymode").Value;\nvar service = doc.Root.Descendants().Single(d => d.Name == "service").Value;	0
1257891	1257841	How to set NotifyIcon behavior to AlwaysShow in C#?	NotifyIcon icon = ...;\nicon.Visible = true;	0
26130852	26130552	Branch coverage with foreach?	void Main()\n{\n    Random r = new Random();\n    List<int> list = Enumerable.Range(1,Int16.MaxValue)\n                               .Select (e => r.Next(0,Int16.MaxValue))\n                               .ToList();\n\n    // Firts attempt with a non empty collection\n    MethodToTest(new Collection<int>(list));\n\n    // Second attempt with an empty collection\n    MethodToTest(new Collection<int>());\n}\n\n// Define other methods and classes here\npublic void MethodToTest(Collection<int> collection)\n{\n    var sum = collection.Sum (i => i);\n    // do something with it. If you're just voiding it and it doesn't get \n    // used, it might be removed by compiler.\n}	0
25201689	25201643	How to OrderBy() 2 or more parameters?	var sortedList = ObjectCollection.OrderBy(x => x.Name).ThenBy(x => x.SecondPropertyToOrderBy).ToList();	0
10755649	10752565	How do i exit a block of code after error detection	return;	0
1590118	1590097	How do I get/set a winforms application's working directory?	using System;\nusing System.IO;\n\nclass Test \n{\n    public static void Main() \n    {\n        try \n        {\n            // Get the current directory.\n            string path = Directory.GetCurrentDirectory();\n            string target = @"c:\temp";\n            Console.WriteLine("The current directory is {0}", path);\n            if (!Directory.Exists(target)) \n            {\n                Directory.CreateDirectory(target);\n            }\n\n            // Change the current directory.\n            Environment.CurrentDirectory = (target);\n            if (path.Equals(Directory.GetCurrentDirectory())) \n            {\n                Console.WriteLine("You are in the temp directory.");\n            } \n            else \n            {\n                Console.WriteLine("You are not in the temp directory.");\n            }\n        } \n        catch (Exception e) \n        {\n            Console.WriteLine("The process failed: {0}", e.ToString());\n        }\n    }	0
1912965	1912312	Catching FaultException in WebServices	FaultException faultException = (FaultException)exception;\nMessageFault msgFault = faultException.CreateMessageFault();\nXmlElement elm = msgFault.GetDetail<XmlElement>();	0
5698584	5693501	Extending parameters for Membership.CreateUser method	((YourProviderType)Membership.Provider).CreateUser(yourParameters);	0
7206381	7206316	Most efficeint way to see if variable is equal to any of these strings	var data = new List<string>();\n// add some:\n\ndata.Add("Stack");\ndata.Add("Overflow");\ndata.Add("Is");\ndata.Add("Awesome");\n\nstring test = "Stack";\n\n// does our list contain our test?\nbool found = data.Contains(test);	0
22149455	22149431	Calling a method of an object that resides within a dictionary?	foreach (var resourcePair in ResourceDictionary.Values)\n{\n    resourcePair.CreateNode(ref xElement);\n}	0
11551983	11551947	Select from mysql database with c#.net winforms - how to check response?	public void Select(string filename)\n{\n        string query = "SELECT * FROM banners WHERE file = '"+filename+"'";\n\n        //open connection\n        if (this.OpenConnection() == true)\n        {\n                //create command and assign the query and connection from the constructor\n                MySqlCommand cmd = new MySqlCommand(query, connection);\n\n                //Get the DataReader from the comment using ExecuteReader\n                            MySqlDataReader reader = cmd.ExecuteReader(); \n                while (myReader.Read())  \n                { \n                    //Use GetString etc depending on the column datatypes.\n                    Console.WriteLine(myReader.GetInt32(0)); \n                } \n\n                //close connection\n                this.CloseConnection();\n        }\n}	0
6311544	6311401	NHibernate - Set foreign key column to null when deleting	entityA.EntityBs.ToList().ForEach(b => b.EntityA = null );\n\nRepository.Remove(entityA);\nRepository.Flush();	0
31615708	31615684	how would i retrieve json data in code behind	Request["id"]	0
19675437	19666785	Access the textbox value from gridview	GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;\n TextBox TextBox1 = row.FindControl("TextBox1") as TextBox; \n\n  //Access TextBox1 here.\n  string myString = TextBox1.Text;	0
10137537	10137467	Neatest way to 'reset' all static variables in a .NET application	myStaticData = new SomeExpensiveThreadSafeCacheDictionary();\nGlobalKillSwitch.ResetCache += delegate { myStaticData.Clear(); };	0
16622651	16590184	Metro Application Issue with BackgroundTask NOT triggered	StorageFile file = await folder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);\nBackgroundDownloader downloader = new BackgroundDownloader();\nDownloadOperation download = downloader.CreateDownload(new Uri(filePath), file);	0
13334369	13334053	How to implement a abstract nongeneric base class, for generic derived classes in c#?	public interface ISomeInterface\n{\n    string AMember { get; }\n}\n\npublic abstract class BaseClass\n{\n    public ISomeInterface AObject { get { return GetAObjectImpl(); } }     \n    public IEnumerable<ISomeInterface> AMethod() { return AMethodImpl(); }\n\n    protected abstract ISomeInterface GetAObjectImpl();\n    protected abstract IEnumerable<ISomeInterface> AMethodImpl();\n}\n\npublic class DerivedClass<T> : BaseClass where T : ISomeInterface\n{\n    public new T AObject { get; private set; }\n\n    public new IEnumerable<T> AMethod() { return Enumerable.Empty<T>(); }\n\n    protected override ISomeInterface GetAObjectImpl() \n    {\n        return AObject;\n    }\n\n    protected override IEnumerable<ISomeInterface> AMethodImpl()\n    {\n        return AMethod();\n    }\n}	0
9620796	9617418	Filter datagridview deadline row between 2 datetimepickers	if(starttime<= deadline && deadline<= endtime)	0
21095487	21095401	How do i change path to folder location when writing a .txt document?	try\n{\n    Order o = IoC.Resolve<IOrderService>().GetOrderById(orderID);\n    Customer ThisCustomer = o.Customer;\n\n    // Specify file, instructions, and privelegdes\n    string path = System.Web.HttpContext.Current.Request.PhysicalPath;\n    int index = path.LastIndexOf("\\");\n    string realPath = path.Substring(0, index + 1);\n    FileStream file = new FileStream(realPath + "/../FedEx/" +\n        orderID.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);\n}	0
15013448	14947037	Merging Collections of Many to Many linked Entity	IEnumerable<Tag> results = aEntities.SelectMany(e=>e.Tags).Distinct();	0
30302242	30299931	MongoDB 2 - query array without hardcoding name	var filter = Builders<Issue>.Filter.AnyEq(x => x.AssignedTo, id.ToString());	0
2332126	2332098	How to add gridview rows to a datatable?	DataTable dt = new DataTable();    \n    for (int j = 0; j < grdList.Rows.Count; j++)\n    {\n        DataRow dr;\n        GridViewRow row = grdList.Rows[j];\n        dr = dt.NewRow();\n        for (int i = 0; i < row.Cells.Count; i++)\n        {\n            dr[i] = row.Cells[i].Text;\n        }\n\n        dt.Rows.Add(dr);\n    }\n\nSqlBulkCopy sbc = new SqlBulkCopy(targetConnStr);\nsbc.DestinationTableName = "yourDestinationTable";\nsbc.WriteToServer(dt);\nsbc.Close();	0
10139525	10121911	Download files from FTP if they are created within the last hour	foreach (var fileName in filesNamesFromFtpFolder)\n        {\n            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(@"ftp://" + host + @"/" + folder + @"/" + fileName);\n\n            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;\n            request.Proxy = null;\n\n            using (FtpWebResponse resp = (FtpWebResponse)request.GetResponse())\n            {\n                if (DateTime.Now.Subtract(TimeSpan.FromMinutes(60)) < resp.LastModified)\n                {\n                    //download this file...\n                }\n            }\n        }	0
25798509	25755793	How to Properly Read from a SerialPort in .NET	port.BaseStream.ReadAsync	0
23747581	23747470	How to create DataGridsViews on tabs that are being auto generated	foreach (DataRow row in dt1.Rows) {\n    string name = row["TABLE_NAME"].ToString();\n    var tabPage = new TabPage(name);\n    var grid = new DataGridView();\n\n    tabPage.Controls.Add(grid);\n    comboBox1.Items.Add(name);        \n    tabControl2.TabPages.Add(tapPage);\n}	0
16330636	16330274	How to update a cell in dataset using C#	const string news = "news";\nconst string status = "status";\nconst string notCompleted = "'NOT COMPLETED'";\n\nDataSet ds = new DataSet();\nds.Tables.Add(news);\nds.Tables[news].Columns.Add(status);\nds.Tables[news].Rows.Add("test");\nds.Tables[news].Rows.Add(notCompleted);\nds.Tables[news].Rows.Add("dummy");\nIEnumerable<DataRow> dataRows = ds.Tables[news].Rows.Cast<DataRow>().Where(row => row[status].ToString() == notCompleted);	0
1036835	1036829	How to return List of Strings in c#	public static List<string> GetCities()\n{\n  List<string> cities = new List<string>();\n  cities.Add("Istanbul");\n  cities.Add("Athens");\n  cities.Add("Sofia");\n  return cities;\n}	0
4585570	4585532	How to clear a checkbox that is populated from a list in C#?	myCheckBox.Checked = false;	0
13221276	13221184	Persistent data for chat	Application[]	0
31664291	31663246	Write SqlDataReader to XML file	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Data;\nusing System.Data.SqlClient;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        const string FILENAME = @"C:\temp\test.xml";\n        static void Main(string[] args)\n        {\n            string connstr = "Enter your connection string here";\n            string SQL = "Enter your SQL Here";\n\n            SqlDataAdapter adapter = new SqlDataAdapter(SQL, connstr);\n            SqlCommand cmd = adapter.SelectCommand;\n            cmd.Parameters.Add("abc", SqlDbType.VarChar);\n\n\n            adapter.SelectCommand.ExecuteNonQuery();\n\n            DataSet ds = new DataSet();\n            adapter.Fill(ds);\n\n            ds.WriteXml(FILENAME, XmlWriteMode.WriteSchema);\n        }\n    }\n}	0
5461399	5461295	Using IsAssignableFrom with generics	public static bool IsAssignableToGenericType(Type givenType, Type genericType)\n{\n    var interfaceTypes = givenType.GetInterfaces();\n\n    foreach (var it in interfaceTypes)\n    {\n        if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)\n            return true;\n    }\n\n    if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)\n        return true;\n\n    Type baseType = givenType.BaseType;\n    if (baseType == null) return false;\n\n    return IsAssignableToGenericType(baseType, genericType);\n}	0
1833197	1833151	Is it possible (and how) to add ConnectionString to app.config at runtime in C#?	System.Configuration.ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("new name", "new string");	0
30822970	30822229	await for another method	var byteCount = await Task.Factory.FromAsync(\n    (callback, s) =>\n    {\n        return clientSocket.BeginReceive(\n            m_szLookupSocketBuffer, \n            0, \n            cm_szLookupSocketBuffer.Length,\n            SocketFlags.None, \n            callback,\n            sSocketName);\n    },\n    result => clientSocket.EndReceive(result),\n    null);	0
23575865	23553213	WinRT: Running concurrently two tasks that share resources	// Stores the frames coming from different threads.\nConcurrentQueue<byte[]> _queue = new ConcurrentQueue<byte[]>();\n\n// Begins recording.\npublic void Start()\n{\n    if (!IsRecording)\n    {\n        IsRecording = true;\n    }\n\n    Task.Run(() =>\n    {\n        while (IsRecording || _queue.Count > 0)\n        {\n            byte[] pixels;\n\n            if (_queue.TryDequeue(out pixels))\n            {\n                RecordBitmap(pixels);\n            }\n        }\n    });\n}\n\n// Stops recording.\npublic void Stop()\n{\n    if (IsRecording)\n    {\n        IsRecording = false;\n    }\n}\n\n// Updates the frames (called from FrameArrived).\npublic void Update(byte[] pixels)\n{\n    _queue.Enqueue(pixels);\n}	0
8214427	8214208	Get Area/Zones boundaries from Matrix	if (surrounding 8 squares has at least one with different region)\n{\n    for each 3 squares, above, below, left and right\n    {\n        if (less than 3 are different, and the middle is different)\n        {\n            is a boundry\n        }\n    }\n\n    for each 3 squares, above, below\n    {\n        for each 3 squares, left, right\n        {\n            if(all 3 from outer loop and all 3 from inner loop are different)\n            {\n                is a boundry\n            }\n        }\n    }\n\n    not a boundry\n}\nelse\n{\n    not a boundry\n}	0
6989314	6989242	Searching a DataGridView for a match or partial match	string searchForText = "whatever";\n\nDataGridViewRow rowFound = mainView.Rows.OfType<DataGridViewRow>()\n  .FirstOrDefault(row => row.Cells.OfType<DataGridViewCell>()\n      .Any(cell => ((dynamic)cell.Value).StringID.Contains(searchForText)));\n\nif (rowFound != null) {\n    mainView.Rows[rowFound.Index].Selected = true;\n    mainView.FirstDisplayedScrollingRowIndex = rowFound.Index;\n}	0
51737	51700	Property default values using Properties.Settings.Default	public static T FromXml<T>(string xml)\n{\n    XmlSerializer xmlser = new XmlSerializer(typeof(T));\n    using (System.IO.StringReader sr = new System.IO.StringReader(xml))\n    {\n        return (T)xmlser.Deserialize(sr);\n    }\n}	0
20407831	20407594	Get last/next week Wednesday date in C#	DateTime nextWednesday = DateTime.Now.AddDays(1);\nwhile (nextWednesday.DayOfWeek != DayOfWeek.Wednesday)\n    nextWednesday = nextWednesday.AddDays(1);\nDateTime lastWednesday = DateTime.Now.AddDays(-1);\nwhile (lastWednesday.DayOfWeek != DayOfWeek.Wednesday)\n    lastWednesday = lastWednesday.AddDays(-1);	0
22542118	22542079	Random int while loop generating similar results every iteration	Random random = new Random();\n\n    int i = 0;\n\n    while (i <= 4)\n    {                              \n        int randomInt = random.Next(1, 6);\n        int randomInt2 = random.Next(1, 6);\n        Console.WriteLine(randomInt.ToString() + ", " + randomInt2.ToString());\n        i++;\n    }	0
4676846	4676169	Compiling to XML doc with csc -- Errors	csc /out:abba.dll /target:library /doc:abba.xml abba.domain.cs abba.service.cs abba.style.manager.cs abba.cs	0
6647594	6647550	Adding custom components programmatically at runtime	public Form1()\n{\n    InitializeComponent();\n\n    UserControl1 test = new UserControl1();\n    test.BackColor = Color.Transparent;\n    test.Location = new Point(0, 110);\n    test.Width = 660;\n    test.Height = 478;\n\n    PictureBox b = new PictureBox();\n    b.Location = new Point(100, 100);\n    b.Width = 320;\n    b.Height = 475;\n    b.Image = Properties.Resources.movie;\n    test.Controls.Add(b);\n    this.Controls.Add(test);//<- here\n}	0
4107338	4107233	List<T> to a Dictionary	CustomObject instance = new CustomObject();\nvar dict = instance.GetType().GetProperties()\n    .ToDictionary(p => p.Name, p => p.GetValue(instance, null));	0
21709180	21708856	How can I read the location of pixels from one particular colour?	Bitmap myBitmap = new Bitmap("yourimage.jpg");\nList<Point> BlackList = new List<Point>();\nList<Point> WhileList = new List<Point>();\n\n// Get the color of a pixel within myBitmap.\nColor pixelColor = myBitmap.GetPixel(x, y);\nif (pixelColor = Color.Black)\n{\n    //Add it to black pixel collection\n    BlackList.Add(new Point(x,y));\n}\nelse\n{\n    //Add it to white pixel collection\n    WhiteList.Add(new Point(x,y));\n}	0
21742388	21741974	How to use a specific media formatter with a specifc route in Web Api	per-controller configuration	0
13748634	13747524	ASP.NET MVC4: How to create a lookup table so entries aren't repeated	this.HasMany(i => i.Softwares)\n            .WithMany(c => c.Locations)\n            .Map(mc =>\n            {\n                mc.MapLeftKey("SoftwareId");\n                mc.MapRightKey("LocationId");\n                mc.ToTable("SoftwareLocations");\n            });	0
12949839	12949635	Convert present Datagrid data into DataTable	DataTable dt = new DataTable();  \n        DataColumn[] dcs = new DataColumn[]{};  \n\n        foreach (DataGridViewColumn c in dgv.Columns)  \n        {  \n            DataColumn dc = new DataColumn();  \n            dc.ColumnName = c.Name;  \n            dc.DataType = c.ValueType;  \n            dt.Columns.Add(dc);  \n\n        }  \n\n        foreach (DataGridViewRow r in dgv.Rows)  \n        {  \n            DataRow drow = dt.NewRow();  \n\n            foreach (DataGridViewCell cell in r.Cells)  \n            {  \n                drow[cell.OwningColumn.Name] = cell.Value;  \n            }  \n\n            dt.Rows.Add(drow);  \n        }	0
15261369	15235130	threadsafe re-entrant queue using peek	// If action already in progress, add new\n    //  action to queue and return.\n    // If no action in progress, begin processing\n    //  the new action and continue processing\n    //  actions added to the queue in the meantime.\n    void SequenceAction(Action action) {\n       lock (_SequenceActionQueueLock) {\n          _SequenceActionQueue.Enqueue(action);\n          if (_SequenceActionQueue.Count > 1) {\n             return;\n          }\n       }\n       // Would have returned if queue was not empty\n       //  when queue was locked and item was enqueued.\n       for (;;) {\n          action();\n          lock (_SequenceActionQueueLock) {\n             _SequenceActionQueue.Dequeue();\n             if (_SequenceActionQueue.Count == 0) {\n                return;\n             }\n             action = _SequenceActionQueue.Peek();\n          }\n       }\n    }	0
4749348	4749265	Regular expression to find unbroken text and insert space	resultString = Regex.Replace(subjectString, \n    @"(?<=     # Assert that the current position follows...\n     \s        # a whitespace character\n     |         # or\n     ^         # the start of the string\n     |         # or\n     \G        # the end of the previous match.\n    )          # End of lookbehind assertion\n    (?!(?:ht|f)tps?://|www\.)  # Assert that we're not at the start of a URL.\n    (\S{150})  # Match 150 characters, capture them.", \n    "$1 ", RegexOptions.IgnorePatternWhitespace);	0
28311080	28286535	Issues resuming app with PickFolderAndContinue method	Frame rootFrame = CreateRootFrame();\n    await RestoreStatusAsync(e.PreviousExecutionState);\n\n    if (rootFrame.Content == null)\n    {\n        rootFrame.Navigate(typeof(SettingsPage));\n    }	0
13221183	13218394	Separating textures by randomly generated lines	//extract pixel data from texture\nTexture2D topTexture = ...\nColor[] topTextureData = new Color[topTexture.Width * topTexture.Height];\ntopTexture.GetData<Color>(topTextureData);\n\nfor(int x = 0; x < topTexture.Width; x++)\n{\n    //depending on how you represent lines, set transparent all the pixels at and below line\n    //basically, for each x dimension, you find where the line is - you have to\n    //write the method for getting this y, as I don't know how you represent lines\n    int lineY = GetLineYAtThisX(x);\n\n    //all the pixels at (and below) the line are set transparent\n    for(int y = lineY; y < topTexture.Height; y++)\n    {\n        topTextureData[x + y * topTexture.Width] = Color.Transparent;\n    }  \n}\n\n//save this data into another texture, so you don't ruin the original one.\nTexture2D maskedTopTexture = new Texture2D(GraphicsDevice, topTexture.Width, topTexture.Height);\nmaskedTopTexture.SetData<Color>(topTextureData);	0
32997205	32997049	Make timer decrement actual seconds	spinTime = spinTime.Subtract(TimeSpan.FromSeconds(1));	0
22326075	22298261	Copy from one DataTable to another using Row and columns	for (int i = 0; i < table1.Rows.Count; i++)\n{\n    string colVal = table1.Rows[i]["Parameter Name"].ToString();\n    if (table2.Columns.Contains(colVal))\n    {\n        table1.Rows[i]["P90 point"] = table2.Rows[4][colVal].ToString();\n        table1.Rows[i]["P10 point"] = table2.Rows[1][colVal].ToString();\n    }\n}	0
9410907	9410507	Add listbox to session	ListBox mylist = new ListBox();\n    mylist.Items.Add(new ListItem("Tahir", "Tahir"));\n    Session["ITEM"] = mylist;\n    foreach (ListItem Item in ((ListBox)(Session["ITEM"])).Items)\n    {          \n        mylist.Items.Add(new ListItem(Item.Text, Item.Value));\n    }	0
19021557	19021503	Custom properties in EF database first	public partial class Person\n{\n    public string Gender\n    {\n        get\n        {\n            if(isFemale) return "female";\n            else return "male";\n         }\n    }\n}	0
6543080	6423524	How to launch a Windows Form from within a .dll launched at runtime	// Execute the method from the requested .dll using reflection (System.Reflection).\n    Assembly DLL = Assembly.LoadFrom(strDllPath);\n    Type classType = DLL.GetType(String.Format("{0}.{0}", strNsCn));\n    object classInst = Activator.CreateInstance(classType, paramObj);\n    Form dllWinForm = (Form)classInst;  \n    dllWinForm.ShowDialog();	0
17093992	17090823	Windows Phone 8 async await usage	public async Task GetAddress()\n{\n    WebApiWorker webApi = new WebApiWorker();\n    var geoResponse = await webApi.GetGeocodeAsync("address");\n}	0
26757249	26757085	Accurate DateTime string format	var myDate = DateTime.Now.ToString("o");	0
14933051	14932909	How can i get from a string not only match cases?	private const string LocalKeyword = "Local Keyword";\nprivate static readonly Dictionary<string, string> keywords = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n{\n    { "Localy KeyWord:", LocalKeyword },\n    { "Localy Keyword", LocalKeyword },\n    { "Local Keyword:", LocalKeyword },\n    { ... }\n}\n\nif (!keywords.TryGetValue(rawKeyword, out realKeyword))\n{\n    throw new ApplicationException("Unknown keyword or keyword alias!");\n}\nColorText.ColorListBox(realKeyword, e)	0
30020059	30019737	getting GridView data from buttonField press?	GridView.Rows[index](columnIndex)	0
5645964	5645902	How Can I in WP7 VB.Net Add An Event Handler For A WebClient?	AddHandler client.OpenReadCompleted, AddressOf myEventHandler	0
20654303	20654106	Centering Column text and Rows content in a datagridview	dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;	0
11725861	11724907	Obtain Total CPU Time of Idle Process in Windows similar to Task Manager	static Program\n{\n    private static PerformanceCounter cpuCounter = new PerformanceCounter() { \n        CategoryName = "Processor", \n        CounterName = "% Processor Time", \n        InstanceName = "_Total" };\n\n    static void Main()\n    {\n        cpuCounter.NextValue();\n        // Do your processing here.\n        float totalCpuUsagePercentage = cpuCounter.NextValue();\n    }\n}	0
15717499	15716864	XML C# - trying to get a List of elements from an xml document	var origin = "Canberra+Australia";\nvar dest = "sydney+Australia";\nvar baseUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin={0}&destination={1}&sensor=false&departure_time=1343605500&mode=driving";\n\nvar req = string.Format(baseUrl, origin, dest);\nvar resp = new System.Net.WebClient().DownloadString(req);\nvar doc = XDocument.Parse(resp);\n\nvar total = doc.Root.Element("route").Element("leg").Element("distance").Element("value").Value;\ntotal.Dump();\n\nvar steps = (from row in doc.Root.Element("route").Element("leg").Elements("step")\n             select new \n             { \n                Duration = row.Element("duration").Element("value").Value,\n                Distance = row.Element("distance").Element("value").Value\n             }).ToList();\nsteps.Dump();	0
29471048	29470914	Update datetype date	_query = "UPDATE Regs SET `LastLogin` = @today WHERE Email = @mail";\n_command = new MySqlCommand(_query, _msqlCon);\n_command.Parameters.AddWithValue("@today", today);\n_command.Parameters.AddWithValue("@mail", userEmail);	0
20356337	20356121	How to create RequiredFieldValidator at the same time as textboxes that I generated in C#?	...\nTextBox t = new TextBox();\nt.ID = "textBoxName" + num.ToString();\ndiv.Controls.Add(ipLabel);\ndiv.Controls.Add(t);\n\nvar rfv = new RequiredFieldValidator();\nrfv.ID = "RequiredFieldValidator" + num;\nrfv.ControlToValidate = t.ID;\nrfv.ErrorMessage = num + " is required.";\ndiv.Controls.Add(rfv);\n\nphDynamicTextBox.Controls.Add(div);\n...	0
32297374	32296946	Read a specific row from database using a variable	private void intrebarea(int ni)\n{\n    con.Open();\n    SqlCommand cmd = new SqlCommand("Select * from tbl Where Id = @Id", con);\n    cmd.Parameters.Add(new SqlParameter("@Id", System.Data.SqlDbType.Int)));\n    cmd.Parameters["@Id"].Value = ni;\n    SqlDataReader rdr = cmd.ExecuteReader();\n\n    rdr.Read();\n}	0
18917144	18902294	How to Convert ColorDialog color to KML color format	string color\nstring polyColor;\nint opacity;\ndecimal percentOpacity;\nstring opacityString;\n\n//This allows the user to set the color with a colorDialog adding the chosen color to a string in HEX (without opacity (BBGGRR))\nprivate void btnColor_Click(object sender, EventArgs e)\n{\n    if (colorDialog1.ShowDialog() == DialogResult.OK)\n    {\n        btnColor.BackColor = colorDialog1.Color;\n        Color clr = colorDialog1.Color;\n        color = String.Format("{0:X2}{1:X2}{2:X2}", clr.B, clr.G, clr.R);\n    }\n}\n\n//This method takes the Opacity (0% - 100%) set by a textbox and gets the HEX value. Then adds Opacity to Color and adds it to a string.\nprivate void PolyColor()\n{\n    percentOpacity = ((Convert.ToDecimal(txtOpacity.Text) / 100) * 255);\n    percentOpacity = Math.Floor(percentOpacity);  //rounds down\n    opacity = Convert.ToInt32(percentOpacity);\n    opacityString = opacity.ToString("x");\n    polyColor = opacityString + color;\n\n}	0
22644525	22644406	Change absolute positioning in Canvas from code	Path myPath = ....; // obtain your path here\n   Canvas.SetLeft(myPath,25);\n   Canvas.SetTop(myPath,25);	0
9611915	9611784	How to detect the Retina Display in MonoTouch	bool retina = (UIScreen.MainScreen.Scale > 1.0);	0
26865660	26865415	How to loop through Dictionary other than using foreach(keyvaluepair)?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace ConsoleApplication2\n{\n    class Program\n    {\n        static void Main()\n        {\n            var dict = new Dictionary<string, string>();\n            dict.Add("toto","this is toto");\n            dict.Add("tata", "this is tata");\n            var keys = dict.Where(p => p.Key == "toto"); // LINQ expression is here\n            foreach (var key in keys)\n            {\n                Console.WriteLine(key);\n            }\n            Console.Read();\n        }\n    }\n}	0
6773365	6768248	DbLinq generic extension method - string as keyselector?	public static int MaxId<T>(this DbLinq.Data.Linq.Table<T> table) where T : class\n    {\n        var param = Expression.Parameter(typeof(T), "p");\n        var body = Expression.PropertyOrField(param, "ID");\n        var lambda = Expression.Lambda<Func<T, int>>(body, param);\n\n        var val = table.OrderByDescending(lambda).FirstOrDefault();\n        return Convert.ToInt32(val.GetType().GetProperty("ID").GetGetMethod().Invoke(val, null));\n    }	0
27714218	27705765	Angular controller structure for multipart view	myPageController\n    tablesData : IData1Model[];\n    userSelectedTable : IData1Model;	0
15385148	15385094	Cannot get textbox value from textbox in itemtemplate	TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");	0
3648192	3648177	how to convert string to listviewitem?	ListViewItem item = new ListViewItem(az);	0
18757725	18757096	Accessing inner text from XML in C#	XmlNamespaceManager nsm = new XmlNamespaceManager(xml.NameTable);\nnsm.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2013-01-09T15:23:27");\nnsm.AddNamespace("x", "http://www.w3.org/1999/xhtml");\n\nXmlNodeList nodelist1 = xml.SelectNodes("my:myFields/my:ProjectDescription/x:html",nsm);\nforeach (XmlNode node in nodelist1)\n    Console.WriteLine(node["p"].InnerText);	0
28234779	28234668	How do i work with abstract and concrete models in .net tutorial?	public abstract class Person\n{\n    public int ID { get; set; }\n\n    [Required]\n    [StringLength(50)]\n    [Display(Name = "Last Name")]\n    public string LastName { get; set; }\n    [Required]\n    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]\n    [Column("FirstName")]\n    [Display(Name = "First Name")]\n    public string FirstMidName { get; set; }\n\n    [Display(Name = "Full Name")]\n    public string FullName\n    {\n        get\n        {\n            return LastName + ", " + FirstMidName;\n        }\n    }\n}	0
30714021	30712230	How to convert a List<string> to an IEnumerable<ServiceReference.datatable> C# Silverlight WCF RIA Services LINQ to SQL	IEnumerable<LoginInfo> list = ...\n        list = list.OrderBy(t => t.username).ToList();	0
1389338	1376300	Adding items to multiple tables with linq to sql	static void SaveCustomer(Customer customer)\n{\n    using(var dc = new TestDC())\n    {\n        dc.Customers.InsertOnSubmit(customer);\n        dc.SubmitChanges();\n\n        foreach (CustomerAddress address in customer.CustomerAddresses)\n        {\n            address.CustomerId = customer.Id;\n            dc.CustomerAddresses.InsertOnSubmit(address);\n            dc.SubmitChanges()\n        }\n    }\n}	0
15578810	15578557	Is this a correct implementation of the Strategy pattern with the FizzBuzz exercise?	class Foo\n{\n   public IOutputFormatter Formatter {get;set;}\n}\n\nvar foo = new Foo();\nfoo.Formatter = new GeneralFormatter();\nConsole.WriteLine(foo.formatter.FormatValue("one");\n\nfoo.Formatter = new FizzBuzzFormatter();\nConsole.WriteLine(foo.formatter.FormatValue("one");	0
1075533	1075504	prefixing DTO / POCOS - naming conventions?	Customer myCustomer = new Customer();\nDto.Customer dtoCustomer = ....;	0
24876989	23704739	How can I make my asp calendar a popup?	calendarClass{\n    background: white; \n    position: absolute;\n}	0
15531283	15520585	Find a specific Table (after a bookmark) in open xml	IEnumerable<TableProperties> tableProperties = bd.Descendants<TableProperties>().Where(tp => tp.TableCaption != null);\nforeach(TableProperties tProp in tableProperties)\n{\n    if(tProp.TableCaption.Val.Equals("myCaption")) // see comment, this is actually StringValue\n    {\n        // do something for table with myCaption\n        Table table = (Table) tProp.Parent;\n    }\n}	0
3823082	3818506	Passing a Parameter to ViewModel constructor	public partial class MyDataGridView : IMyListView\n{\n    public MyDataGridView()\n    {\n      InitializeComponent();\n    }\n\n    public MyDataGridView(MyListViewModel viewModel)\n    {\n      InitializeComponent();\n\n      DataContext = viewModel;\n }\n}	0
28938932	28481702	How to insert Huge dummy data to Sql server	DECLARE @values TABLE (DataValue int, RandValue INT)\n\n;WITH mycte AS\n(\nSELECT 1 DataValue\nUNION all\nSELECT DataValue + 1\nFROM    mycte   \nWHERE   DataValue + 1 <= 1000000\n)\nINSERT INTO @values(DataValue,RandValue)\nSELECT \n        DataValue,\n        convert(int, convert (varbinary(4), NEWID(), 1)) AS RandValue\nFROM mycte m \nOPTION (MAXRECURSION 0)\n\n\nSELECT \n        v.DataValue,\n        v.RandValue,\n        (SELECT TOP 1 [User_ID] FROM tblUsers ORDER BY NEWID())\nFROM    @values v	0
31140810	31129381	Send Cookies With HttpWebRequest	string login_info = "login=login&redirect=http%3A%2F%2F"+WebUtility.UrlEncode(populated_config.domain)+"%2Fchat%2F%3FchannelName%3DPublic&username=" + WebUtility.UrlEncode(populated_config.username) + "&password=" + WebUtility.UrlEncode(populated_config.password) + "&channelName=Public&lang=en&submit=Login";\n        request = (HttpWebRequest)WebRequest.Create(populated_config.domain + "ucp.php?mode=login");\n        request.Method = "POST";\n        //manually populate cookies\n        Console.WriteLine(cc.GetCookieHeader(new Uri(populated_config.domain)));\n        request.Headers.Add(HttpRequestHeader.Cookie,cc.GetCookieHeader(new Uri(populated_config.domain)));\n        StreamWriter sw = new StreamWriter(request.GetRequestStream());\n        sw.Write(login_info);\n        response = (HttpWebResponse)request.GetResponse();	0
29108851	29108070	Using QueryOver, how do I conditionally filter results based on a method argument?	public static IEnumerable<ProjectAssignment> GetProjectAssignments(int projectId, bool includeAlternates)\n{\n    using (ISession session = DataContext.GetSession())\n    {\n        var query = session.QueryOver<ProjectAssignment>()\n                       .Where(p => p.ProjectId == projectId);\n\n        if (!includeAlternates) \n        {\n            query.And(p => !p.IsAlternate);\n        }\n\n        List<ProjectAssignment> results = query.List().ToList();\n        return results;\n    }\n}	0
18626450	18626372	Storing numbers project in c#	1 - On Form1, once the button to open Form2 is clicked, make sure you do Form1.Hide() or Form1.Visible = false, and ppen Form2.\n\n2 - In Form2 there is a textbox and a button.\n\n3 - Once that button is clicked, get the text of the textbox, and split it by "space" to get an array of numbers, MyArray.\n\n4 - Finally, display a MessageBox containing MyArray.Length;\n\n5 - Form2.Hide(), Form1.Show()	0
19819267	19818777	Range of Colors in DataGridView C#	if(colorVal > 0)\n{\n    var whiteness = 255 - Convert.ToInt32(colorval * 255);\n    myCell.BackColor = Color.FromArgb(whiteness, 255, whiteness); //green\n}\nelse\n{\n    var whiteness = 255 - Convert.ToInt32(colorval * -255);\n    myCell.BackColor = Color.FromArgb(255, whiteness, whiteness); //red\n}	0
23147951	23147721	C# Get Separate ListBox Items as strings	for (int i = 1; i <= test; i++)\n    {\n        worksheet.Cells[i, 0] = new Cell(ItemsList.Items[i-1]);\n    }	0
23870207	23870061	How to set values of user control from class	public IEValue IE_Value\n{\n    get\n    {\n        return new IEValue() {\n            IsEmrino = txtIsEmriNo.Text,\n            Nevi = txtNevi.Text,\n            BrutKg = txtBrutKg.Text,\n            NetKg = txtNetKg.Text\n        };\n    }\n    set\n    {\n        txtIsEmriNo.Text = value.IsEmrino;\n        txtNevi.Text = value.Nevi;\n        txtBrutKg.Text = value.BrutKg;\n        txtNetKg.Text = value.NetKg;\n    }\n}	0
15955802	15955738	Wrap automatically inserted TextBoxes with HTML in ASP.NET	foreach (var Field in db.A_Settings)\n{\n    TextBox t = new TextBox();\n    t.ID = Field.ID.ToString();\n    t.CssClass = "smallinput";\n    t.Text = Field.Text;\n    //add literal control containing html that should appear before textbox\n    LabelPlaceHolder.Controls.Add(new LiteralControl("html before"));\n    LabelPlaceHolder.Controls.Add(t);\n    //add literal control containing html that should appear after textbox\n    LabelPlaceHolder.Controls.Add(new LiteralControl("html after"));\n}	0
7880456	7880421	InsertQuery from C# to MySql	var tableName = "volumen";\n\nstring myInsertQuery = String.Format("INSERT INTO {8} (date, time, bidvol, bidprice, askprice, askvol, lastprice, volume) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})", now_date_marketlast, now_time_marketlast, bidvol, bidprice, askprice, askvol, ePrice1, e.Volume, tableName);	0
30407208	30405145	Not able to get the exact source for a URL	WebBrowser wb = new WebBrowser();\nprivate void button1_Click(object sender, EventArgs e) {\n    wb.Navigate("http://kissanime.com/Anime/One-Piece");\n    wb.ScriptSupress = true;\n    wb.DocumentCompleted += pageLoaded;\n}\n\nprivate void pageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e) {\n    string src = wb.DocumentText;\n}	0
1572994	1572948	put names in table into arraylist?	List<string> names = new List<string>();\nusing(SqlConnection db = new SqlConnection(ConfigurationManager...))\n{\n    db.Open();\n    SqlCommand cmd = new SqlCommand("Select ....", db);\n\n    using(SqlDataReader rd = cmd.ExecuteReader())\n    {\n        while(rd.Read())\n        {\n           names.Add(rd.GetString(0));\n        }\n    }\n}	0
28308796	28308680	How can I read a CSV from Webserver using c# with LINQ? (ClickOnce deployment)	public string TestCSV(string id)\n    {\n\n    List<string> splitted = new List<string>();\n    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://mywebsite.com/data.csv");\n    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n\n    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))\n    {\n    string currentline = sr.ReadLine();\n    if (currentline != string.IsNullOrWhiteSpace)\n    {\n\n        var res = currentline.Split(new char[] { ',' });\n\n        if (res[0] == id)\n        {\n            splitted.Add(res[1]);\n        }\n\n        foreach (var line in splitted)\n        {\n\n            return line;\n        } \n     }\n  }\n return null;\n}	0
3544424	3544399	Anyone know how to do a List<string> case insensitve comparison	names.Contains("tOm", StringComparer.CurrentCultureIgnoreCase);	0
24747550	24742708	Is it possible to disable file indexing in a specific directory?	File.SetAttributes(Core.Main.pictureBox1.ImageLocation, FileAttributes.NotContentIndexed);	0
23764696	23764607	Changing visibility properties of a form from a class	CheckVisibility()	0
30556748	30556560	Convert a small C++ code snippet to a C# code	if(e[0] == 0.0) ..	0
5932645	5932580	How to determine if a object type is a built in system type	myName.GetType().Namespace	0
29637628	29637530	RegEx conditional based on which letter	\b(?:[1-9]N|(?:[1-9]|[1-3][0-9]|4[01])S)\b\n\nvar pattern = @"\b(?:[1-9]N|(?:[1-9]|[1-3][0-9]|4[01])S)\b";	0
23339925	23339688	C# RDP application with STUN	// Create new socket for STUN client.\nSocket socket = new Socket\n    (AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);\nsocket.Bind(new IPEndPoint(IPAddress.Any,0));\n\n// Query STUN server\nSTUN_Result result = STUN_Client.Query("stunserver.org",3478,socket);\nif(result.NetType != STUN_NetType.UdpBlocked){\n    // UDP blocked or !!!! bad STUN server\n}\nelse{\n    IPEndPoint publicEP = result.PublicEndPoint;\n    // Do your stuff\n}	0
4585989	4585939	Comparing strings and get the first place where they vary from eachother	string a1 = "AAAB";\nstring a2 = "AAAAC";\n\nint index = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count() + 1;	0
24570489	24523121	How to add a composite unique key using EF 6 Fluent Api?	public class Table\n{\n    int Id{set;get;}    \n    int ProjectId {set;get;}\n    string SectionOdKey{set;get;}\n}\n\npublic class TableMap : EntityTypeConfiguration<Table>\n{\n   this.Property(t => t.ProjectId).HasColumnName("ProjectId")\n                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 1){IsUnique = true}));\n   this.Property(t => t.SectionOdKey).HasColumnName("SectionOdKey")\n                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 2){IsUnique = true}));\n}	0
29707500	29706111	How to change content of cell in GridView based on content of another cell?	visible='<%# (Eval("FileName") != null && Eval("FileName") != "") ? true : false %>'	0
16516660	16516341	Open File Which is already open in window explorer	if (openFileDialog1.FileName != "" && resultSaveDialog == System.Windows.Forms.DialogResult.OK)\n{\n string path = Path.GetDirectoryName(openFileDialog1.FileName);\n string filename = Path.GetFileName(openFileDialog1.FileName);\n txtFileName.Text = filename;\n}	0
14282062	14281981	Sandboxing a .NET Assembly - Upload a DLL and then Reflection	Assembly.ReflectionOnlyLoadFrom	0
33401164	33400597	Change a Windows Store App's title text	using Windows.UI.ViewManagement;\n\n...\n\nApplicationView appView = ApplicationView.GetForCurrentView();\nappView.Title = "Title text goes here";	0
4684280	4684195	Calculating in radians the rotation of one point around another	Vector2 difference = pointB - pointA;\n\ndouble rotationInRadians = Math.Atan2(difference.Y, difference.X);	0
21480728	21480453	Get data from clicked item in ListBox	private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)\n{\n    if (listBox1.SelectedIndex == -1) return;\n\n    Attractions first = listbox1.SelectedItem as Attractions ;\n    Attractions second = (Attractions)listBox1.Items[listBox1.SelectedIndex];\n    Attractions third = (sender as ListBox).SelectedItem as Attractions;\n    Attractions fourth = args.AddedItems[0] as Attractions;\n\n    Debug.WriteLine(" You selected " + first.AttractionName);\n}	0
32627859	32627585	How to filter null value in sql	SELECT\n   td.teacherId,\n   teacherName,\n   applicationName,\n   class,\n   grade\nFROM\n   [AppUser_Detail] as aud\nLEFT OUTER JOIN [Teacher_Detail] as td ON aud.teacherId = td.teacherId\nLEFT OUTER JOIN [Application_Detail] as ad ON aud.applicationId = ad.applicationId\nLEFT OUTER JOIN [Class_Detail] as cd ON aud.classId = cd.classId\nWHERE\ntd.teacherId is not null OR class is not null OR grade is not null	0
13619063	13619040	Array of Array into one array c#	var res = allcats.Select(a => string.Join("", a)).ToArray();	0
18745192	18743888	How Add A String To Variables,Methods,Threads,... Names	int Parallel_Count = int.Parse(nudParallelCount.Text);\n\nThread[] threads = new Thread[Parallel_Count];\n\nfor (int i = 0; i < Parallel_Count; i++)\n{\n    threads[i] = new Thread(/*fill thread start here*/);\n    threads[i].Start();\n}	0
8897820	8897768	c# Context Error on Variable used within a Method	string sqlStat = System.String.Empty;\n\nif (paramField == "load")\n{\n    sqlStat = "SELECT...";	0
33350846	33350260	Converting long hex string to binary string throws OverflowException	public static string HexStringToBinaryString(string hexString)\n{\n    var result = new StringBuilder();\n\n    string[] lookup =\n    {\n        "0000", "0001", "0010", "0011",\n        "0100", "0101", "0110", "0111",\n        "1000", "1001", "1010", "1011",\n        "1100", "1101", "1110", "1111"\n    };\n\n    foreach (char nibble in hexString.Select(char.ToUpper))\n        result.Append((nibble > '9') ? lookup[10+nibble-'A'] : lookup[nibble-'0']);\n\n    return result.ToString();\n}	0
21594082	21594019	Display random number and sorting	Random rnd = new Random();\n\nConsole.WriteLine("\n5 random integers from -100 to 100:");\nfor (int X = 1; X <= 5; X++)\n{\n    int y = rnd.Next(-100, 100);\n    if (y >= 0)\n    {\n        Console.WriteLine("These are the positive numbers: {0}", y.ToString());\n    }\n    else\n    {\n        Console.WriteLine("These are the negative numbers: {0}", y.ToString());\n    }\n}\nConsole.ReadLine();	0
751418	751370	Suggestions For String and DateTime utility functions' Library using Extension Methods	public static bool IsNullOrEmpty(this string value){\n    return string.IsNullOrEmpty(value);\n}\npublic static string Reverse(this string value) {\n    if (!string.IsNullOrEmpty(value)) {\n        char[] chars = value.ToCharArray();\n        Array.Reverse(chars);\n        value = new string(chars);\n    }\n    return value;\n}\npublic static string ToTitleCase(this string value) {\n    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);\n}\npublic static string ToTitleCaseInvariant(this string value) {\n    return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(value);\n}	0
8037857	8037309	Parsing text to create XML	char sep = '???';  //whatever. copy/paste with care. \nXElement lastStudent = null, lastDegrees = null;\n\nforeach (var line in lineCollection)\n{\n    string[] parts = line.Split(sep);\n\n    int leading = parts.TakeWhile(s => s == "").Count();\n\n    if (leading == 0)  // Student\n    {\n        // todo: validate parts.length, part[0]\n\n        lastStudent = new XElement("Student",\n            new XAttribute("name", parts[1]),\n            new XAttribute("surname", parts[2]));\n\n        doc.Root.Add(lastStudent);            \n    }\n    else if (leading == 1)  // Subject\n    {\n        // todo: validate \n\n        lastDegrees = new XElement("degrees",\n                 parts.Skip(2).Select(p => new XElement("degree", p)) );\n\n        lastStudent.Add(new XElement(parts[1], lastDegrees);               \n    }\n    else ...\n\n}	0
6735933	6735833	Updating a row using entity framework	AccessRepository rep = new AccessRepository();\nrep.Add(details);\nAccessDetails detailUpdate = rep.GetByID(item.AccessDetailsTableID);\ndetailUpdate.Imported = true;\nrep.Save();//this calls SaveChanges on a single data context	0
20418346	20418119	Compare time in 24 hour format in c#	comboBox1.Text = "03:00";\ncomboBox2.Text = "18:00";\nint t1 = Int32.Parse(comboBox1.Text.Replace(":", ""));\nint t2 = Int32.Parse(comboBox2.Text.Replace(":", ""));\nvar comp = t1 == t2 ? 0 : (t1 < t2 ? -1 : 1);	0
33330820	33328280	PLinq parallel summing performance inconsistency	private static IEnumerable<Company> GenerateSmallCompanies()\n{\n    return Enumerable\n        .Range(0, 10000000)\n        .Select(number => new Company {EvaluatedMarketValue = number});\n}	0
10143149	10142742	Change the default selected item to none	private void Form1_Load(object sender, EventArgs e)  \n{ \n  this.ActiveControl = label1;       \n}	0
24025831	24025579	C# Microsoft SQL Server 2012 GRANT syntax	GRANT <permission> [ ,...n ] ON \n    [ OBJECT :: ][ schema_name ]. object_name [ ( column [ ,...n ] ) ]\n    TO <database_principal> [ ,...n ] \n    [ WITH GRANT OPTION ]\n    [ AS <database_principal> ]\n    <permission> ::=\n    ALL [ PRIVILEGES ] | permission [ ( column [ ,...n ] ) ]\n    <database_principal> ::= \n        Database_user \n    | Database_role \n    | Application_role \n    | Database_user_mapped_to_Windows_User \n    | Database_user_mapped_to_Windows_Group \n    | Database_user_mapped_to_certificate \n    | Database_user_mapped_to_asymmetric_key \n    | Database_user_with_no_login	0
12886826	12884600	How to calculate simple moving average faster in C#?	decimal buffer[] = new decimal[period];\ndecimal output[] = new decimal[data.Length];\ncurrent_index = 0;\nfor (int i=0; i<data.Length; i++)\n    {\n        buffer[current_index] = data[i]/period;\n        decimal ma = 0.0;\n        for (int j=0;j<period;j++)\n            {\n                ma += buffer[j];\n            }\n        output[i] = ma;\n        current_index = (current_index + 1) % period;\n    }\nreturn output;	0
2747035	2746995	WCF: Use a Message Contract to make a Soap Header	[MessageContract]\npublic class YourMessageType\n{\n  // This is in the SOAP Header\n  [MessageHeader] public string UserName {get;set;}\n  [MessageHeader] public string Password {get;set;}\n\n  // This is in the SOAP body\n  [MessageBodyMember] public string OtherData {get;set;}\n  ...\n}	0
10493870	10493661	How to Remove Previously Saved messages from ModelState in asp.net mvc3	Modelstate.Remove("yourkey"); //remove one\n\nModelstate.Clear(); //remove all	0
5786626	5784924	How does ActivityContext, LocationReferenceEnvironment, Arguments and Variables work in WF4?	var wf = new Sequence()\n{\n    Variables =\n    {\n        new Variable<string>("var1", "Some value"),\n        new Variable<int>("var2", c=> Environment.TickCount),\n    },\n    Activities =\n    {\n        new WriteLine() {\n            Text = new VisualBasicValue<string>("\"String value: \" & var1 ")\n        },\n        new WriteLine() {\n            Text = new VisualBasicValue<string>("\"Int value: \" & var2 ")\n        }\n\n    }\n};\n\nWorkflowInvoker.Invoke(wf);	0
8421999	8421174	How do I group query results by calendar month and other variables using Linq2Sql?	from b in Billings\ngroup b by new { b.UserID, b.Type, Month = b.Date.Value.Month, b.Description } into groupItem\nselect new \n{\n    groupItem.Key.UserID,\n    groupItem.Key.Type,\n    groupItem.Key.Month,\n    groupItem.Key.Description,\n    Total = groupItem.Sum (b => b.Amount)\n}	0
12971459	12970866	Insert query refinement - SQL Server	;with cte as\n(\n    select JourneyID, StartDate,EndDate,Days\n    from yourtable s unpivot (active for days in (Monday, tuesday, wednesday, ...)) u\n    where active = 1\n)\n    select JourneyID, JourneyDate\n    from (\n        select \n            DATEADD(D, number, (Select MIN(startdate) from cte)) as JourneyDate\n        from master..spt_values \n        where type='p' \n        and number < (select datediff(d,MIN(StartDate),max(enddate)) from cte)\n    ) numbers\n        cross join cte\n    where \n        days = datename(weekday, JourneyDate) \n        and JourneyDatebetween StartDate and EndDate\n    order by JourneyDate, JourneyID	0
10364775	10364726	How to Combine an IF and For/Foreach for checking multiple items?	if(!string.IsNullOrEmpty(textBox2.Text) && Heb[Line].Def.Contains(textBox2.Text))\n{ \n    Success(); \n}\nelse\n{\n    Fail();\n}	0
3923885	3923814	Check a CheckBox using Membership ASP:NET	MembershipUser myUser = (MembershipUser)e.Row.DataItem;\nCheckBox activeCheckBox = (CheckBox)e.Row.FindControl("uxActiveCheckBoxSelector");\nactiveCheckBox.Checked = myUser.IsApproved;	0
26533119	26532526	In a Custom Control, getting notified when a DepenencyProperty of type IEnumerable changes	protected static void OnMyCollectionItemsSourceChanged(DependencyObject property, DependencyPropertyChangedEventArgs args)\n    {\n        if( args.OldValue is INotifyCollectionChanged)\n           (args.OldValue as INotifyCollectionChanged ).CollectionChanged -= CollectionChangedHandler;\n       if(args.NewValue is INotifyCollectionChanged)\n           (args.OldValue as INotifyCollectionChanged).CollectionChanged += CollectionChangedHandler;\n\n    }\n\n    private static void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)\n    {\n      //\n    }	0
18157325	18156795	Parsing HTML to get script variable value	var html = @"<html>\n             // Some HTML\n             <script>\n               var spect = [['temper', 'init', []],\n               ['fw\/lib', 'init', [{staticRoot: '//site.com/js/'}]],\n               [""cap"",""dm"",[{""tackmod"":""profile"",""xMod"":""timed""}]]];\n             </script>\n             // More HTML\n             </html>";\n\n// Grab the content of the first script element\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\nvar script = doc.DocumentNode.Descendants()\n                             .Where(n => n.Name == "script")\n                             .First().InnerText;\n\n// Return the data of spect and stringify it into a proper JSON object\nvar engine = new Jurassic.ScriptEngine();\nvar result = engine.Evaluate("(function() { " + script + " return spect; })()");\nvar json = JSONObject.Stringify(engine, result);\n\nConsole.WriteLine(json);\nConsole.ReadKey();	0
8922065	8921878	How to get valid url	List< string > urls = new List< string >\nurls.add("www.google.com");\nurls.add("www.ggg.com");\n\nforeach(var url in urls)\n{\n     //cast string to HttpResponse will need here...\n     if( GetHeaders(url).ToString() == "400" )\n         MessageBox.Show(url + " status code is 400");\n}	0
4424654	4424595	Gridview grouping - using gridviewheper	If (dataitem.TableSection != TableRowSection.TableHeader) {\nobject rows; \n//Rest of the code goes here...\n}	0
10529750	10527802	Reference sqlite Database in App.config	connectionString="Data Source=App_Data\RVEST_V1.DB"	0
22381640	22339673	Handle post (from iOS) with image in asp.net server	if (file.ContentLength > 0)\n            {\n                var fileName = Path.GetFileName(file.FileName);\n                var path = Path.Combine(Server.MapPath("~/Content/images"), fileName);\n                file.SaveAs(path);\n            }	0
11708649	11701534	Skydrive API change permission of folder?	...\n    void Properties_Completed(object sender, LiveOperationCompletedEventArgs e)//completed\n    {\n        if (e.Error == null)\n        {\n            IDictionary<string,object> result = e.Result;\n            object shr = result["shared_with"];\n            IDictionary<string, object> permission = shr as IDictionary<string, object>;\n            string access = permission["access"].ToString();\n        }\n    {	0
18611732	18600891	Take & remove elements from collection	public static IEnumerable<T> TakeAndRemove<T>(Queue<T> queue, int count)\n{\n   for (int i = 0; i < Math.Min(queue.Count, count); i++)\n      yield return queue.Dequeue();\n}	0
32120488	32043694	Read Control Characters GS RS	static void Main(string[] args)\n    {\n\n        ConsoleKeyInfo cki;\n\n        Console.WriteLine("Press the Escape (Esc) key to quit: \n");\n        do\n        {\n            cki = Console.ReadKey();\n            Console.Write(" --- You pressed ");\n            Console.WriteLine(cki.Key.ToString());\n        } while (cki.Key != ConsoleKey.Escape);\n\n    }	0
5594592	5594448	Comparing two Lists of Type Product	ListA.Clear();\nListA.AddRange(ListB.Items);	0
969797	969679	How do I read RSS feed through a proxy using RSS.NET?	string url = "http://sourceforge.net/export/rss2_sfnews.php?feed";\nstring proxyUrl = "http://proxy.example.com:80/";\nHttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);\nWebProxy proxy = new WebProxy(proxyUrl,true);\nwebReq.Proxy = proxy;\nRssFeed feed = RssFeed.Read(webReq);	0
6178871	6170728	Select the next row after nth duplicate rows	int[] coinTossResults = {0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1};\nvar tails = (from x in coinTossResults.WithAdjacentGrouping()\n             group x by x into g\n             where g.Count() > 1 && g.Key == 1\n             select g);	0
3169807	3169730	Access bindingsource column value	DataRowView current = (DataRowView)CustomersBindingSource.Current;\ncurrent["CustomerID"] = Guid.NewGuid();	0
12025449	12015838	how to determine between 2 mouse clicks of treeviews	private void cmnuAddNode_Click(object sender, EventArgs e)\n    {\n\n        NewNode n = new NewNode();\n        n.ShowDialog();\n        TreeNode nod = new TreeNode();\n        nod.Name = n.NewNodeName.ToString();\n        nod.Text = n.NewNodeText.ToString();\n\n        n.Close();\n\n        if (treeviewindex== 1)\n        {\n            treeView1.SelectedNode.Nodes.Add(nod);\n            treeView1.SelectedNode.ExpandAll();\n\n        }\n        if (treeviewindex==2)\n        {\n            treeView2.SelectedNode.Nodes.Add(nod);\n            treeView2.SelectedNode.ExpandAll();\n        }\n        if (treeviewindex == 3)\n        {\n            treeView3.SelectedNode.Nodes.Add(nod);\n            treeView3.SelectedNode.ExpandAll();\n        }\n    }	0
6947562	6947518	Create a BackgroundWorker in a Child Form that reports progress to the Parent Form	backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);	0
12867171	12867107	how to check xmlnode for innertext or value in c#?	var xElem = XElement.Parse(xml);\n\nvar leafElements = xElem.Descendants()\n                        .Where(e => !e.HasElements)\n                        .ToList();	0
25273944	25273742	Show outline of empty label in Visual Studio	// Check for design mode. \nif ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue)) \n{\n    myTextBlock.Text = "*** DESIGN ***";\n}	0
3060285	3060042	How to represent datetime of different time zones in C#	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        var s = "2009/01/10 17:18:44 -0800";\n        var dto = DateTimeOffset.ParseExact(s, "yyyy/MM/dd HH:mm:ss zzzz", null);\n        var utc = dto.UtcDateTime;\n        Console.WriteLine(utc);\n        Console.ReadLine();\n    }\n}	0
29583101	29582887	Bitmap - wrong coordinates	Bmp.SetResolution(g.DpiX, g.DpiY);\ng.DrawImage(Bmp, 0, 0);	0
24146263	24146088	C# Session Variables	ArrayList ar_IMGID = new ArrayList();\nArrayList ar_Ext = new ArrayList();\n\nwhile (transportFbReader.Read())\n            {\n                ImageID = transportFbReader.GetString(0);\n                extention = transportFbReader.GetString(1);\n                //Open PDF:\n                if (ImageID != "")\n                {\n\n                    ar_IMGID.Add(ImageID);\n                    ar_Ext.Add(extention);\n                 }\n             }\nSession.Add("IMGID", ar_ImageID);\nSession.Add("Ext", ar_Ext);	0
34295199	34294895	filter if min sequence number is equal to Status of specific type	public Expression<Func<IPTORequest, bool>> BuildPendingOrderedSequencePTORequestFilter\n                                                             (IPublicReadContext context)\n{\n    return\n        r =>\n           r.Activity.ActivitySteps.Where(s => s.Status == ActivityStepStatus.Pending)\n                .OrderBy(s => s.Sequence)\n                .FirstOrDefault()\n                .ActivityStepType == ActivityStepType.Approval;\n\n}	0
17976720	17976548	Copy information from Cmd Promt Window into Console Application	// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = "Write500Lines.exe";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();	0
9056757	9054469	how to check if exe is set as LARGEADDRESSAWARE	IsLargeAware("some.exe");\n\nstatic bool IsLargeAware(string file)\n{\n    using (var fs = File.OpenRead(file))\n    {\n        return IsLargeAware(fs);\n    }\n}\n/// <summary>\n/// Checks if the stream is a MZ header and if it is large address aware\n/// </summary>\n/// <param name="stream">Stream to check, make sure its at the start of the MZ header</param>\n/// <exception cref=""></exception>\n/// <returns></returns>\nstatic bool IsLargeAware(Stream stream)\n{\n    const int IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x20;\n\n    var br = new BinaryReader(stream);\n\n    if (br.ReadInt16() != 0x5A4D)       //No MZ Header\n        return false;\n\n    br.BaseStream.Position = 0x3C;\n    var peloc = br.ReadInt32();         //Get the PE header location.\n\n    br.BaseStream.Position = peloc;\n    if (br.ReadInt32() != 0x4550)       //No PE header\n        return false;\n\n    br.BaseStream.Position += 0x12;\n    return (br.ReadInt16() & IMAGE_FILE_LARGE_ADDRESS_AWARE) == IMAGE_FILE_LARGE_ADDRESS_AWARE;\n}	0
22514545	22512768	Add items to ComboBox from Database using SQLDataReader	private void LoadCourse()\n {\n    SqlConnection conn = new SqlConnection(sasdbConnectionString);\n    string query = "SELECT CourseId,CourseName FROM Courses";\n    SqlDataAdapter da = new SqlDataAdapter(query, conn);\n    conn.Open();\n    DataSet ds = new DataSet();\n    da.Fill(ds, "Course");\n    courseComboBox.DisplayMember =  "CourseName";\n    courseComboBox.ValueMember = "CourseId";\n    courseComboBox.DataSource = ds.Tables["Course"];\n }	0
8126079	8125932	How to assign args value coming in the event handler to a variable?	AssemblyName assemblyName = new AssemblyName(args.Name);\ncls.UserClassAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);	0
9088661	9088540	How can I add visible information to C# classes using attributes?	[Obsolete]\nclass BlackAndWhiteTelevision {}	0
30034408	30012912	How to Get Mapper by BaseType	var mapper = AutoMapper.Mapper\n     .GetAllTypeMaps()\n     .Where(a => a.SourceType == typeof(Book) && typeof(ListItemModelBase).IsAssignableFrom(a.DestinationType)                                        && !a.DestinationType.IsAbstract)\n     .FirstOrDefault()	0
34012836	34011077	Hide specific context menu in datagrid upon selected row wpf mvvm	private void Dgrd_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)\n    {\n        SomeEntity item = (SomeEntity) Dgrd.CurrentItem; \n\n        if(item.Donate > 100)\n            viewModel.SyncColumnVisibility = Visibility.Collapsed;\n        else\n            viewModel.SyncColumnVisibility = Visibility.Visible;    \n    }	0
5272640	5272387	C# How do I know what methods need to be reimplemented for a class based on a interface that is to be used with a datagridview?	public class MyClass : IBindingList	0
16526254	10094652	Facebook C# SDK Get Current User	var facebookClient = new FacebookClient(FacebookAccessToken);\nvar me = facebookClient.Get("me") as JsonObject;\nvar uid = me["id"];	0
5241383	5241347	how to write content of a session to database just before expiring-MVC	protected void Session_End(Object sender, EventArgs e)\n{\n    //save to db\n}	0
877725	877505	accessing Datagridview cell value while its value is being edited	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        var key = new KeyEventArgs(keyData);\n\n        ShortcutKey(this, key);\n\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n\n    protected virtual void ShortcutKey(object sender, KeyEventArgs key)\n    {\n        switch (key.KeyCode)\n        {\n            case Keys.F2:\ndataGridView1.EndEdit();\n                MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());\n                break;\n        }\n    }	0
24210814	24209746	Getting a Handle to a button in another window	int hwnd = FindWindow("CommunicatorMainWindowClass", null);\n\nAutomationElement lync = AutomationElement.FromHandle((IntPtr)hwnd);\nAutomationElement optionsButton = lync.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options"));\n((InvokePattern)optionsButton.GetCurrentPattern(InvokePattern.Pattern)).Invoke();	0
3218096	3218075	How to explicitly specify the size of an array parameter passed to a function	Contract.Requires(inputIV.Length == 16);	0
25546387	25545856	Find Angle Between Two Vectors	// the angle between the two vectors is less than 90 degrees. \nVector2.Dot(vector1.Normalize(), vector2.Normalize()) > 0 \n\n// the angle between the two vectors is more than 90 degrees. \nVector2.Dot(vector1.Normalize(), vector2.Normalize()) < 0 \n\n// the angle between the two vectors is 90 degrees; that is, the vectors are orthogonal. \nVector2.Dot(vector1.Normalize(), vector2.Normalize()) == 0 \n\n// the angle between the two vectors is 0 degrees; that is, the vectors point in the same direction and are parallel. \nVector2.Dot(vector1.Normalize(), vector2.Normalize()) == 1 \n\n// the angle between the two vectors is 180 degrees; that is, the vectors point in opposite directions and are parallel. \nVector2.Dot(vector1.Normalize(), vector2.Normalize()) == -1	0
14087460	14087406	Open a file only one time for a program (like MS Word) in C# 4.0 Winform	CreateMutex() / OpenMutex()\n FindWindow() / CreateWindow()\n SendMessage() / PostMessage()\n ShowWindow()/ SetWindowPosition()/BringWinToTop()	0
10315817	10315769	Specifying that a constrained generic class is a subclass?	public abstract class AbstractListViewModel<T>  : AbstractWorkspaceViewModel\n    where T : AbstractWorkspaceViewModel	0
19662398	19662264	Xamarin Android application	protected override void OnCreate(Bundle bundle)\n    {\n        base.OnCreate(bundle);\n\n        SetContentView(Resource.Layout.Index);\n        Button Contact = FindViewById<Button>(Resource.Id.BtnContact);\n        Contact.Click += (sender, e) =>\n        {\n            StartActivity(new Intent(this, typeof(/* whatever activity you want */ )));\n\n            // e.g.\n            //StartActivity(new Intent(this, typeof(SplashActivity)));\n        };\n\n    }	0
1791516	1791510	Can lambdas be used without Linq?	Action blah = () => { System.Console.WriteLine("Hello World!"); }\nblah(); // will write Hello World! to the console	0
3007322	3007218	iTextSharp for PDF - how add file attachments?	its.Document PDFD = new its.Document(its.PageSize.LETTER);\nits.pdf.PdfWriter writer;\nwriter = its.pdf.PdfWriter.GetInstance(PDFD, new FileStream(targetpath, FileMode.Create));\nits.pdf.PdfFileSpecification pfs = its.pdf.PdfFileSpecification.FileEmbedded(writer, "C:\\test.xml", "New.xml", null);\nwriter.AddFileAttachment(pfs);	0
21140532	21140326	Get the current logged in user from a Windows 8 store application	var username = await Windows.System.UserProfile.UserInformation.GetDomainNameAsync();	0
25631270	25631079	How do I return one item at a time with each button click?	protected void Page_Load(object sender, EventArgs e)\n    {           \n        int? count = Session["count"] as int?;\n        count = (count == null) ? 0 : count;\n        Response.Write(Colors[count.Value]);\n        count = (count + 1) % Colors.Length;\n        Session["count"] = count;\n    }	0
5616815	5616653	ASP.NET MVC 3 Custom Action Filter - How to add incoming model to TempData?	public override void OnActionExecuting(ActionExecutingContext filterContext)\n{\n   if (!filterContext.Controller.ViewData.ModelState.IsValid)\n      return;\n\n   var model = filterContext.ActionParameters.SingleOrDefault(ap => ap.Key == "model").Value;\n   if (model != null)\n   {\n      // Found the model - add it to tempdata\n      filterContext.Controller.TempData.Add(TempDataKey, model);\n   }\n}	0
9826480	9821021	In PostSharp is it possible to modify the value of a single argument to a method?	args.Method	0
10014727	10014322	performance of copying directories	void CopyAll (string SourcePath, string DestinationPath)\n{\n    //Now Create all of the directories\n    foreach (string dirPath in Directory.GetDirectories(SourcePath, "*.*", \n    SearchOption.AllDirectories))\n    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));\n\n    //Copy all the files\n    foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", \n    SearchOption.AllDirectories))\n    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));\n}	0
13413762	13410210	Creating a class to interact with a SQL database	var companies = Company.GetCompanyDetails();	0
14906469	14906440	How to make some classes implement an interface while these classes are built into assembly	interface IWithM\n{\n  void M();\n}\n\nclass MyA : A, IWithM\n{\n  // IWithM.M will be picked from A.M\n}	0
1588323	1588306	Base64 encoded string to file	File.WriteAllBytes(@"c:\yourfile", Convert.FromBase64String(yourBase64String));	0
10781356	10781334	How to get list of available SQL Servers using C# Code?	string myServer = Environment.MachineName;\n\nDataTable servers = SqlDataSourceEnumerator.Instance.GetDataSources();\nfor (int i = 0; i < servers.Rows.Count; i++)\n{\n    if (myServer == servers.Rows[i]["ServerName"].ToString()) ///// used to get the servers in the local machine////\n     {\n         if ((servers.Rows[i]["InstanceName"] as string) != null)\n            CmbServerName.Items.Add(servers.Rows[i]["ServerName"] + "\\" + servers.Rows[i]["InstanceName"]);\n         else\n            CmbServerName.Items.Add(servers.Rows[i]["ServerName"]);\n      }\n  }	0
19211246	19210991	Can I use tryParse output parameters to populate an array in a for-loop?	String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };\n        Dictionary<string, int> hours = new Dictionary<string, int>();\n        for (int i = 0; i < days.Length; i++)\n        {\n            int dailyHours;\n            Console.Write("{0}'s study hours: ", days[i]);\n            while (int.TryParse(Console.ReadLine(), out dailyHours) != true)\n            {\n                Console.WriteLine("Wrong input,must be only numbers!!!");\n                Console.Write("{0}'s study hours: ", days[i]);\n            }\n            //if(int.TryParse(Console.ReadLine(),out dailyHours))\n            hours.Add(days[i], dailyHours);\n        }	0
8472111	8472005	Efficient DataTable Group By	var result = from row in dt.AsEnumerable()\n              group row by row.Field<int>("TeamID") into grp\n               select new\n                 {\n                 TeamID = grp.Key,\n                  MemberCount = grp.Count()\n                  };\n foreach (var t in result)\n     Console.WriteLine(t.TeamID + " " + t.MemberCount);	0
15387241	15387212	How to convert text string to speech sound	using System.Speech.Synthesis;\n\nnamespace ConsoleApplication5\n{\n    class Program\n    {\n\n        static void Main(string[] args)\n        {\n            SpeechSynthesizer synthesizer = new SpeechSynthesizer();\n            synthesizer.Volume = 100;  // 0...100\n            synthesizer.Rate = -2;     // -10...10\n\n            // Synchronous\n            synthesizer.Speak("Hello World");\n\n            // Asynchronous\n            synthesizer.SpeakAsync("Hello World");\n\n\n\n        }\n\n    }\n}	0
4823098	4823048	How to have the DataGridView do the following	DataGridViewCellMouseEventArgs e\nrow = e.RowIndex\ncolumn = e.ColumnIndex	0
7700510	7700483	WebClient: how to cancel a long running HTTP request?	client.CancelAsync()	0
22521766	22521442	XML file generated in windows not loading in linux environment	???<?xml version="1.0" encoding="utf-8"?>	0
13051656	13051604	Stopwatch and resetting time after button click	private void button1_Click(object sender, EventArgs e)\n{\n    sw = Stopwatch.StartNew();\n\n    // ... do something ...\n\n    sw.Stop();\n\n    textBox1.Text = sw.Elapsed.ToString();\n}	0
23985841	23979292	Open multiple website in a single window in different tabs	private void button1_Click(object sender, EventArgs e)\n    {\n        Process.Start("http://www.google.com", "_blank");\n        Thread.Sleep(2000);\n        Process.Start("http://www.google.com", "_blank");\n    }	0
9161915	9161617	check if a process runs on a remote machine for a certain user	tasklist /S \\<server> /V > tasklist.txt	0
3310952	3304625	sorting a DataSet between reading and writing to XML	DataSet ds = new DataSet();\nds.ReadXml(@"D:\foo.xml");\nDataTable tbl = ds.Tables["cj"];\ntbl.PrimaryKey = new DataColumn[] { tbl.Columns["a"] };\nDataView view = tbl.DefaultView;\nview.Sort = "a ASC";\nDataTable sortedBy_a = view.ToTable();\n\n//remove all the CJ tables -- they're currently unsorted\nds.Tables.Remove("cj");\n\n//add in all the sorted CJ tables\nds.Tables.Add(sortedBy_a);\n\nStringWriter sw = new StringWriter();\nds.WriteXml(sw);	0
19840389	19840292	LINQ orderby string with integer where 1,11,12,13 are not next to eachother?	// 1st alternative\nservers.OrderBy(s => s.Length).OrderBy(s => s.Name);\n\n// 2nd alternative\nservers.OrderBy(s => Int32.Parse(s.Substring(6)));	0
30818518	30818486	Updating a record using a class object with Entity Framework in C#	void updateBranch(Branches branch)\n{\n    using (var dbContext = new entitiesContext())\n    {\n        dbContext.Branches.Attach(branch);\n        dbContext.Entry(branch).State = EntityState.Modified;              \n        dbContext.SaveChanges();\n    }\n}	0
26800026	22604183	How to insert SDO_GEOMETRY object variable from C# code into oracle table containing coloumn of sdo_geometry type?	OracleParameter endGeometry = cmd.CreateParameter();\nendGeometry.OracleDbType = OracleDbType.Object;\nendGeometry.UdtTypeName = "MDSYS.SDO_GEOMETRY";\nendGeometry.Value = routeSegment.endPointGeometry;\nendGeometry.ParameterName = "P_END_GEOM";    \n\nparameter.Add(endGeometry);	0
11970228	11970145	C# Finding element in List of String Arrays	var max = list.Max(t => double.Parse(t[1]));\nlist.First(s => double.Parse(s[1]) == max)[0]; // If list is not empty	0
25076615	25076164	Comparing namespaces to see if they match	private static IEnumerable<string> GetAllowedNamespaces(Type type)\n{\n    const string System = "System";\n    string thisNamespace = type.Namespace;\n    HashSet<string> hashset = new HashSet<string>();\n    hashset.Add(thisNamespace);\n    hashset.Add(System);\n    var parts = thisNamespace.Split('.');\n    if (parts.Length > 1)\n    {\n        string previous = string.Empty;\n        foreach (var part in parts)\n        {\n            var current = string.IsNullOrEmpty(previous)\n                ? part\n                : string.Format("{0}.{1}", previous, part);\n            previous = current;\n            hashset.Add(current);\n        }\n\n        previous = string.Empty;\n        foreach (var part in new[] { System  }.Concat(parts.Skip(1)))\n        {\n            var current = string.IsNullOrEmpty(previous)\n                ? part\n                : string.Format("{0}.{1}", previous, part);\n            previous = current;\n            hashset.Add(current);\n        }\n    }\n\n    return hashset;\n}	0
16522670	16522431	change the variable name inside a loop	List<TextElement> list = new List<TextElement>();\nfor(int i = 0; i < dt.Rows.Count; i++)\n{\n    String wholetext = dt.Rows[i][1].ToString() + "--" + dt.Rows[i][1].ToString();\n\n    list.Add(new TextElement(wholetext));\n }\n superMarquee1.Elements.AddRange(list.ToArray());	0
4264075	4263786	Parsing XML with inner nodes?	var list = from item in doc.Descendants("client")\n             let tradeinfoelement = item.Element("trade_info")\n             select new\n             {\n               Client = new\n               {\n                 Id = (string)item.Element("id"),\n                 Name = (string)item.Element("name"),\n                 Desc = (string)item.Element("desc")\n               },\n               TradeInfo = new\n               {\n                 BuyPrice = tradeinfoelement.Element("buy_price_rate")  != null ? (int?)tradeinfoelement.Element("buy_price_rate") : null,\n                 Tabs = tradeinfoelement.Descendants("tab") != null ? tradeinfoelement.Descendants("tab").Select(t => (string)t).ToList() : null\n               }\n             };	0
4335083	4335040	How can I add a combobox in control designer properties for a WinForms custom control?	public enum Gender\n{\n    Man,\n    Woman,\n}\n\npublic class MyCustomControl : UserControl\n{\n    public Gender UserGender { get; set; }\n}	0
1244224	1244143	C# WinForms App Maxing Processor But Doing Nothing Strenuous!	\\live.sysinternals.com\tools\procmon.exe	0
4065187	4065110	Ways to quit application after launching multiple winforms?	Application.Run(form1);	0
15099007	15098611	Unable to Set Radio Button value when two windows are opened using the same ViewModel	public class EnumToBoolConverter : BaseConverterMarkupExtension<object, bool>\n    {\n        public override bool Convert(object value, Type targetType, object parameter)\n        {\n            if (value == null)\n                return false;\n\n            return value.Equals(Enum.Parse(value.GetType(), (string)parameter, true));\n        }\n\n        public override object ConvertBack(bool value, Type targetType, object parameter)\n        {\n            return value.Equals(false) ? DependencyProperty.UnsetValue : parameter;\n        }\n    }	0
33222239	33222118	opening multiple browser tabs but only one will open	//This code inside loop\nstring pageurl = "Label.aspx?booking=" + v.booking + "&pallet=" + v.palletId;\nstring script += "window.open('" + pageurl + "','_blank'); "\n\n//This code outside loop\nScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", script, true);	0
40217	40211	How to Compare Flags in C#?	if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)\n{\n     // Do something\n}	0
32864381	32864289	How to check data when loop entity framework?	var flag = db.PRODUCTes.Any(e => e.Code == C1 && e.Check && e.Num == 15) ? 1 : 2;	0
16508216	16508175	ASP.Net assign event handler to asp button click	Page.IsPostBack	0
12209551	12106280	remove html node from htmldocument :HTMLAgilityPack	List<string> xpaths = new List<string>();\n    foreach (HtmlNode node in doc.DocumentNode.DescendantNodes())\n    {\n                        if (node.Name.ToLower() == "img")\n                        {\n                            string src = node.Attributes["src"].Value;\n                            if (string.IsNullOrEmpty(src))\n                            {\n                                xpaths.Add(node.XPath);\n                                continue;\n                            }\n                        }\n    }\n\n    foreach (string xpath in xpaths)\n    {\n            doc.DocumentNode.SelectSingleNode(xpath).Remove();\n    }	0
15985310	15975591	Linq query with 2 many to many relations	var itemPerCategories = \n        db.Category.ToDictionary(\n            c => c.CategoryName,\n            c => c.Tags.SelectMany(t => t.Items)).ToList())\n        );	0
24134135	24133864	How to compare enumerations of elements in list?	public bool IsStraightFlush(IHand hand)\n    {\n        var sortedCards = hand.Cards.OrderBy(card => card.Face).ThenBy(card => card.Suit).ToList();\n        bool straightFlush = true;\n        for (int i = 1; i < sortedCards.Count(); i++)\n        {\n            if ((int)sortedCards[i].Face != (int)sortedCards[i - 1].Face + 1)\n            {\n                straightFlush = false;\n                break;\n            }\n        }\n        return straightFlush;\n    }	0
13644435	13643628	selectively disabling elements from an array of controls with one CanExecute	private void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)\n{\n    if (e.Source == button1)\n        e.CanExecute = checkBox1.IsChecked.HasValue ? checkBox1.IsChecked.Value : false;\n    if (e.Source == button2)\n        e.CanExecute = checkBox2.IsChecked.HasValue ? checkBox2.IsChecked.Value : false;\n    if (e.Source == button3)\n        e.CanExecute = checkBox3.IsChecked.HasValue ? checkBox3.IsChecked.Value : false;\n}	0
3617982	3617934	Take data from clicked ListView	private void LikeButtonClick(object sender, RoutedEventArgs e) { \n    Button btn = (Button)sender; \n    NewsFeedResources obj = btn.DataContext as NewsFeedResources;  \n    if(null != obj){ \n         MessageBox.Show(obj.IdPost);\n    } \n}	0
33082962	33039588	Saving 32-bit Unsigned Byte Array to File System	Bitmap bitmap = new Bitmap(150, 150, PixelFormat.Format32bppRgb);\nBitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);\nIntPtr pNative = bmData.Scan0;\nMarshal.Copy(image, 0, pNative, image.Length);\nbitmap.UnlockBits(bmData);\nbitmap.Save(path, ImageFormat.Png);	0
8797846	8788014	Multiple types were found that match the controller named 'Home' - In two different Areas	public static void RegisterRoutes(RouteCollection routes)\n{\n    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n    routes.MapRoute(\n        "Default", // Route name\n        "{controller}/{action}/{id}", // URL with parameters\n        new { controller = "Home", action = "Index", id = UrlParameter.Optional },\n        new string[] { "BaseAdminMVC.Areas.TitomsAdmin.Controllers" }\n    );\n}	0
10826666	10826389	Convert MembershipProvider from OBDC to SQL throwing exception	SqlCommand cmd = new SqlCommand("SELECT UserID, Email, PasswordQuestion," +\n    " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +\n    " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +\n    " FROM Users WHERE Email = @email AND ApplicationName = @applicationname", conn);	0
13312369	13311461	How do I setup two one-to-many relationships in entity framework?	public class YourContext : DbContext\n{\n   ...\n   protected override OnModelCreating(DbModelBuilder modelBuilder)\n   {\n      modelBuilder.Entity<Car>()\n         .HasRequired(c => c.Owner)\n         .WithMany(p => p.CarsOwned)\n         .HasForeignKey(c => c.OwnerId)\n         .WillCascadeOnDelete(false);\n          // Otherwise you might get a "cascade causes cycles" error\n\n      modelBuilder.Entity<Car>()\n         .HasRequired(c => c.MainDriver)\n         .WithMany() // No reverse navigation property\n         .HasForeignKey(c => c.MainDriverId)\n         .WillCascadeOnDelete(false);\n   }\n}	0
6775738	6596037	How can I check a range of an array contains zeros?	var sixThroughTenAreZero = new int[] {1,2,3,4,5,0,0,0,0,0,2,3}\n                                    .Skip(5)\n                                    .Take(5)\n                                    .All(x => x == 0);	0
22046284	22046142	Accessing variable from differnet wpf window	FooWindow a = new FooWindow();\na.owner = this;	0
1114583	1114555	A view model mvvm design issue	class PersonModel {\n    public string Name { get; set; }\n}\n\nclass PersonViewModel {\n    private PersonModel Person { get; set;}\n    public string Name { get { return this.Person.Name; } }\n    public bool IsSelected { get; set; } // example of state exposed by view model\n\n    public PersonViewModel(PersonModel person) {\n        this.Person = person;\n    }\n}	0
15486037	15485579	findnext() method in xml document	//Assumes i is declared somewhere else \nfor (i ; i < smss.Count; i++)\n{\n    if (smss[i].Attributes["body"].InnerText.Contains(searchText))\n    {\n        txtName.Text = smss[i].Attributes["body"].InnerText +\n                       smss[i].Attributes["time"].Value;\n        break;\n    }\n}	0
34075637	34075533	console text padding without background color	int x = 5;\nfor (int i = 1; i <= 10; i++)\n{\n    Console.ResetColor();\n    if (x > 5)\n    {\n        Console.Write(new String(' ', x - 5));\n    }\n\n    if (i % 2 == 0)\n    {\n        Console.BackgroundColor = ConsoleColor.DarkYellow;\n    }\n\n    x = x + 1;\n    string str = "word";\n    Console.WriteLine(str);\n}\nConsole.ReadLine();	0
14458222	14344161	Image flickering in Windows RT App	IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);\nBitmapImage bitmapImage = new BitmapImage();\n\nif (await bitmapImage.SetSourceAsync(stream))\n{\n    image1.source = bitmapImage;\n}	0
13029903	13029873	Reading value from web.config file?	using System.Configuration;\n\nstring connString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();	0
10743925	10742807	OleDb - Retrieving Excel worksheet names also retrieves Defined Names	OleDbConnection connExcel = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;"\n        + @"Data Source=c:\test.xlsx;"\n        + @"Extended Properties=""Excel 12.0 Xml;HDR=Yes;""");\n\n        OleDbCommand cmdExcel = new OleDbCommand();\n        cmdExcel.Connection = connExcel;\n        connExcel.Open();\n\n        DataTable testTable = connExcel.GetSchema("Tables");\n\n        String[] excelSheets = new String[testTable.Rows.Count];\n        int i = 0;\n\n        foreach (DataRow row in testTable.Rows)\n        {\n            excelSheets[i] = row["TABLE_NAME"].ToString();\n\n            if (excelSheets[i].EndsWith("$"))\n            {\n                Console.WriteLine(excelSheets[i] = row["TABLE_NAME"].ToString());\n                i++;\n            }\n            else\n            {\n                i++;\n            }\n\n        }\n\n        Console.ReadLine();	0
16896534	16896466	Unable to install a Windows Service programmatically	public static class SelfInstaller\n{\n    private static readonly string _exePath = Assembly.GetExecutingAssembly().Location;\n\n    public static bool InstallMyService()\n    {\n        try\n        {\n            ManagedInstallerClass.InstallHelper(new string[] { _exePath });\n        }\n        catch\n        {\n            return false;\n        }\n        return true;\n    }\n\n    public static bool UninstallMyService()\n    {\n        try\n        {\n            ManagedInstallerClass.InstallHelper(new string[] { "/u", _exePath });\n        }\n        catch\n        {\n            return false;\n        }\n        return true;\n    }\n    public static bool IsInstalled(string serviceName)\n    {\n         var serviceExists = ServiceController.GetServices().Any(s => s.ServiceName == serviceName);\n         if (serviceExists == null) return false;\n         return true;\n    }\n}	0
3007567	3007308	Alphanumeric Counter	public const int MAX_VALUE = 38885;\n\npublic static IEnumerable<string> CustomCounter()\n{\n    for (int i = 0; i <= MAX_VALUE; ++i)\n        yield return Format(i);\n}\n\npublic static string Format(int i)\n{\n    if (i < 0)\n        throw new Exception("Negative values not supported.");\n    if (i > MAX_VALUE)\n        throw new Exception("Greater than MAX_VALUE");\n\n    return String.Format("{0}{1}{2}{3}",\n                         FormatDigit(CalculateDigit(1000, ref i)),\n                         FormatDigit(CalculateDigit(100, ref i)),\n                         FormatDigit(CalculateDigit(10, ref i)),\n                         FormatDigit(i));\n}\n\nprivate static int CalculateDigit(int m, ref int i)\n{\n    var r = i / m;\n    i = i % m;\n    if (r > 35)\n    {\n        i += (r - 35) * m;\n        r = 35;\n    }\n    return r;\n}\n\nprivate static char FormatDigit(int d)\n{\n    return (char)(d < 10 ? '0' + d : 'A' + d - 10);\n}	0
7420936	7418807	Show Day of the week numeric value in Grid row for whole week	from s in SupplyDeliveries\ngroup s by s.product_id into g\nselect new \n{\n    ProductId = g.Key, \n    MondayMin = (from x in g where x.DayOfTheWeek == 1 select x.MinNo).FirstOrDefault(),\n    MondayMax = (from x in g where x.DayOfTheWeek == 1 select x.MaxNo).FirstOrDefault(),\n    TuesdayMin = ...\n}	0
11300677	11300575	How do I merge all the cases into One?	string ControlIdSuffix = mole < 10 ? "0" : "" + mole.ToString();\n        Control[] picBoxes = this.Controls.Find("p" + ControlIdSuffix, true);\n        if (picBoxes.Length > 0)\n        {\n            PictureBox p = picBoxes[0] as PictureBox;\n            if (p != null) {\n               if (p.Image == pmiss.Image && MoleHill.Image == pHill.Image)\n                  molesMissed++;\n               p.Image = MoleHill.Image;\n            }\n        }	0
19814900	19814866	Outputting a lists contents in a label in unity	debugList.ForEach(item => outputContent.text += item);	0
5278938	5278889	Use string as public string name?	String mystring = "pspeed";\nPropertyInfo pi = typeof(dvar).GetProperty(mystring);\npi.SetValue(dvar, 1, new Object[0]);	0
6497889	6497841	C#, using a regular expression to find and replace certain characters in a word?	Regex.Replace("This is dummy text %with% percent signs", "%(.*?)%", @"[$1]");	0
20393290	20392491	How to remove list of kvp from a list of kvp using LINQ?	var newMainList = MainList.Select(e=> \n                             new KeyValuePair<string,List<KeyValuePair<string,object>>>(\n                                     e.Key,\n                                     e=>e.Value\n                                         .Where(x=>!SubList.Any(a=>a.Key==x.Key))\n                                         .ToList())).ToList();	0
3122601	3119034	How to handle application start event in ASP.NET module	static string test; \n        public void Init(HttpApplication application)\n        {\n\n\n            application.BeginRequest +=(new EventHandler(this.Application_BeginRequest));\n            test = "hi"; \n            application.EndRequest +=(new EventHandler(this.Application_EndRequest));\n\n\n        }\n       private void Application_BeginRequest(Object source,EventArgs e)\n        {\n            {\n                HttpApplication application = (HttpApplication)source ;\n                HttpContext context = application.Context;\n                context.Response.Write(test);\n            }\n\n\n        }	0
18957562	18956740	How to find the Largest Difference in an Array	public int solution(int[] A)\n{\n    int N = A.Length;\n    if (N < 1) return 0;\n\n    int max = 0;\n    int result = 0;\n\n    for(int i = N-1; i >= 0; --i)\n    {\n        if(A[i] > max)\n            max = A[i];\n\n        var tmpResult = max - A[i];        \n        if(tmpResult > result)\n            result = tmpResult;\n    }\n\n    return result;\n}	0
11812829	11195930	Implementing a Factory Pattern with CSLA.NET	var form = (Form)Csla.DataPortal.Create(formType, new Csla.Server.EmptyCriteria);	0
17118007	17117902	Dictionary to XML using LINQ	new XElement("UserClassDictionary",\n      from kvp in UserClassDict\n      select new XElement("User",\n          new XAttribute("id", kvp.Key),\n          new XElement("ControlNumbers",\n               from cn in kvp.Value.ControlNumber\n               select new XElement("ControlNumber", cn)\n          )\n      );	0
34383728	34383465	Marshalling a fixed-size buffer from C# to extern	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]\npublic struct WIN32_FIND_STREAM_DATA\n{\n    public long StreamSize;\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH+36)]\n    public string StreamName;\n}	0
29892999	29891409	LINQ-EF Query grouping multiple tables	results.GroupBy(r => r.ParticipientId).Select(p => new\n                {\n                    StudentId = p.Key,\n                    Count = p.GroupBy(pr => pr.Answer.QuestionId).Select( cc => new {\n// any correct answer is not selected or any incorrect answer is selected\n                        notCorrect = cc.Any(q => !q.IsSelected && q.Answer.IsAnswerCorrect) || cc.Any(q => q.IsSelected && !q.Answer.IsAnswerCorrect)\n                    }).Count(res => !res.notCorrect)\n                });	0
12149878	12146833	Byte packing like mongdbo objectid	1204578057.ToString("X")	0
23848600	23848577	Unable to use DateTime.AddTicks	Console.WriteLine(StartTime.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss.fff") + " + " + timer.Interval + " = " + end.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss.fff"));	0
25247274	25246154	Add new register automatic according date time	INSERT INTO FINE (IDLoan, Date)\nSELECT IDLoan, GETDATE()\nFROM LOAN L\nLEFT JOIN FINE F ON F.IDLoan = L.IDLoan\nWHERE (L.Date >= DATEADD(DD,-3,GETDATE()) AND F.IDLoan IS NULL	0
32993710	32993466	How to mock this MVC Controller	public Controller\n{\n\n  private ISettings<FirstSettingsDto> _admin;\n\n  public Controller(ISettings<FirstSettingsDto> admin = null)\n  {\n    _admin = admin ?? new GetSettingsConfiguration();\n  }\n\n  [HttpGet]\n  public ActionResult GetInformation()\n  {\n      var config = _admin.GetSettings();\n  }\n}	0
13988539	13988269	How can I generate a thumbnail from an image in server folder?	public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)\n  {\n      var ratio = (double)maxHeight / image.Height;\n      var newWidth = (int)(image.Width * ratio);\n      var newHeight = (int)(image.Height * ratio);\n      var newImage = new Bitmap(newWidth, newHeight);\n      using (var g = Graphics.FromImage(newImage))\n      {\n          g.DrawImage(image, 0, 0, newWidth, newHeight);\n      }\n      return newImage;\n  }	0
22054336	22054212	XMLDocument compared to another file	protected bool AreFilesTheSame(XmlDocument doc, string fileToCompareTo)\n    {\n        if (!File.Exists(fileToCompareTo))\n            return (false);\n\n        try\n        {\n            XmlDocument doc2 = new XmlDocument();\n            doc2.Load(fileToCompareTo);\n\n            return doc.OuterXml == doc2.OuterXml;\n        }\n        catch\n        {\n            return (false);\n        }\n    }	0
26325269	26312474	Copying a generic list to another, with different data types takes too long (C#)	this.SomePropertyX = log.SomePropertyX	0
4696660	4696602	How to check IF expriation date occured	if(DateTime.Now > expirationDate) { /* TODO:... */ }	0
7867403	7867377	Checking if a string array contains a value, and if so, getting its position	string[] stringArray = { "text1", "text2", "text3", "text4" };\nstring value = "text3";\nint pos = Array.IndexOf(stringArray, value);\nif (pos > -1)\n{\n    // the array contains the string and the pos variable\n    // will have its position in the array\n}	0
7381814	7381764	lock inside a simple property - can it deadlock?	return isMouseInside;	0
28863562	28800235	keyboard input in C# with razer switchblade sdk	SharpBlade.Switchblade sbInstance = SharpBlade.Switchblade.Instance;\nsbInstance.StartKeyboardCapture(Control, Boolean);	0
13947691	13947530	Fail to invoke class in dynamic loaded DLL from windows service	Assembly assembly = Assembly.LoadFrom("ABC.dll");\nobject o = Activator.CreateInstance(assembly.GetType("ClassName"));\n/// then invoke the method	0
28936053	28935917	Creating folders and files in Parallel	var clientPath = @"C:\foo\bar";\nif (Directory.Exists(clientPath)) continue;\nif (Directory.CreateDirectory(clientPath).Exists)	0
12858896	12838720	ASP:Chart from datatable with many series	foreach (DataRow dataRow in users.Rows)\n    {\n        Series s = new Series("Userid_" + dataRow["userid"]);\n        s.ChartType = SeriesChartType.Spline;\n\n        s.Color = colors[i % colors.Count()];\n\n        var userRows = dataTable.Rows.Cast<DataRow>().Select(r=>r["userid"]==dataRow["userid"]).ToArray();\n\n        s.Points.DataBindXY(userRows,"AddedDate",userRows,"CountElements");\n\n        mainChart.Series.Add(s);\n        i++;\n    }	0
14120786	14120494	WebApi XML Deserialization - Node with multiple child nodes is not correctly deserialized as array of childnode objects	[Serializable]\npublic class grandparentnode\n{\n    public parentnode parentnode { get; set; }\n}\n\n[Serializable]\npublic class parentnode\n{\n    [XmlElement]\n    public childnode[] childnode { get; set; }\n}\n\n[Serializable]\npublic class childnode\n{\n    public string foo { get; set; }\n    public string bar { get; set; }\n    public string baz { get; set; }\n}	0
25405648	25390586	How to add leading zeros in DataTable columns	foreach (DataRow row in table.Rows)\n{\n      row["SRNumber"] = row["SRNumber"].ToString().PadLeft(6, '0');\n}\ntable.AcceptChanges();	0
12879543	12879535	C# while loop not working with server side controls	while (dr.Read())\n{\n    String a1 = dr[0].ToString();\n    repvals += a1;\n}	0
11557356	11557137	How to implement funcitonality that can be used on different kinds of objects?	class MySearchableDataListBase<T> : INotifyPropertyChanged\n{\n   List<T> _list = new List<T>();\n   string _currentFilterString = "";\n\n   abstract bool FilterItemPredicate(T item, string query);\n\n   public abstract IEnumerable<T> FilteredItems\n   {\n      get {\n         return _list.Where(i => FilterItemPredicate(i, _currentFilterString)).ToArray();\n      }\n   }\n\n   public string FilterQuery\n   {\n      get { return _currentFilterString; }\n      set {\n         if (value != _currentFilterString)\n         {\n             _currentFilterString = value;\n             OnPropertyChanged("FilterQuery");\n             OnPropertyChanged("FilteredItems");\n         }\n      }\n   }\n}	0
33568896	33568349	Make click on last element	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        MessageBox.Show("1");\n    }\n    private void button2_Click(object sender, RoutedEventArgs e)\n    {\n        MessageBox.Show("2");\n    }\n\n    private void Button1_OnPreviewMouseUp(object sender, MouseButtonEventArgs e)\n    {\n        button1_Click(sender,e);\n    }\n    private void Button2_OnPreviewMouseUp(object sender, MouseButtonEventArgs e)\n    {\n        button2_Click(sender,e);\n    }\n\n    private void Button1_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)\n    {\n        e.Handled = true;\n    }\n    private void Button2_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)\n    {\n        e.Handled = true;\n    }	0
13076206	13076094	How to query a date range from a varchar column using LINQ	var rows = cxt.TableOfRandomDateColumn.Where(x => x.Date >= myStrDateStr && x.Date <= myStpDateStr).ToList();	0
34052601	34048076	Duplicating the values of a column in ultrawingrid	foreach(DataRow dr in ds.Tables[0].Rows)\n{ \n    dr["Amount"] = dr["Balance"]; \n}	0
30931538	30689085	Validation DataGridView Windows Forms	this.CausesValidation = false	0
11513453	11513426	How to retrieve all values for all the inputs on MVC page	//This is your initial HTTP GET request.\npublic ActionResult SomeAction() {\n    MyViewModel model;\n\n    model = new MyViewModel();\n    //Populate the good stuff here.\n\n    return View(model);\n}\n\n//Here is your HTTP POST request; notice both actions use the same model.\n[HttpPost]\npublic ActionResult SomeAction(MyViewModel model) {\n    //Do something with the data in the model object.\n}	0
6641943	6641862	How to Run a C# console app with the console hidden style?	p.CreateNoWindow = true;	0
25354	25349	What would be the fastest way to remove Newlines from a String in C#?	string s = "foobar\ngork";\nstring v = s.Replace(Environment.NewLine,",");\nSystem.Console.WriteLine(v);	0
2686819	2686792	Replacing several different characters in a string	string s1 = "14/04/2010 17:12:1";\n\nstring s2 = s1.Replace("/","%").Replace(" ","%").Replace(":","%");	0
12293351	12293286	How to get windows unlock event in c# windows application?	using System;\nusing Microsoft.Win32;\n\n// Based on: http://stackoverflow.com/a/604042/700926\nnamespace WinLockMonitor\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);\n            Console.ReadLine();\n        }\n\n        static void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)\n        {\n            if (e.Reason == SessionSwitchReason.SessionLock)\n            {\n                //I left my desk\n                Console.WriteLine("I left my desk");\n            }\n            else if (e.Reason == SessionSwitchReason.SessionUnlock)\n            {\n                //I returned to my desk\n                Console.WriteLine("I returned to my desk");\n            }\n        }\n    }\n}	0
1085352	1085307	Is there an Attribute I can use on a property to tell DataGridView how to format the column?	private class MyClass {\n  [DisplayName("Foo/Bar")]\n  public string FooBar { get; private set; }\n  [Browsable(False)]\n  public decimal Baz { get; private set; }\n  [DisplayName("Baz")]\n  public CurrencyBaz\n  {\n        get { return string.Format(Baz, "C2"); }\n  }\n}	0
8524651	8521249	Creating Statistics of a SharePoint list	var cItems = new System.Collections.Generic.Dictionary<string, DateTime>();\n        foreach (SPListItem item in allData)\n        {\n            string sName;\n            DateTime dtDate;\n\n            sName = item.GetFormattedValue("Name");\n            dtDate = (DateTime)item.GetFormattedValue("latestDate");\n\n            if (cItems.ContainsKey(sName))\n            {\n                // later\n            }\n            else\n            {\n                cItems.Add(sName, dtDate);\n            }\n        }	0
32693071	32692929	Implementing generic interface that takes a generic interface as a parameter	public interface ITransformer<in TInput,out TOutput>\n{\n    TOutput Transform(TInput input);\n}\n\npublic interface ITransform<TInput>\n{\n    TOutput Transform<TOutput>(ITransformer<TInput, TOutput> transformer);\n}\n\npublic class MessageLogs : ITransform<MessageLogs>\n{\n    public TOutput Transform<TOutput>(ITransformer<MessageLogs, TOutput> transformer)\n    {\n        return transformer.Transform(this);\n    }\n}	0
18144071	18144026	Let a thread wait for n number of pulses	CountdownEvent waiter = new CountdownEvent(n);\n\n// notifying thread\nwaiter.Signal();\n\n// waiting thread\nwaiter.Wait();	0
28252669	28252520	value of asp:textbox is not being changed after written over it	If(!IsPostback)\n{\n    reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();    \n}	0
8154697	7968916	Click on any other cell while a cell of same row of datagridvew is in edit mode causes Operation is not valid reentrant call	this.BeginInvoke(new MethodInvoker(Refresh_dataGridView1));	0
6617406	6616588	how do i parse this xml in one linq statement	XDocument document = XDocument.Parse("<Fruit><Apple><Pear>dar</Pear><Orange/><Starfruit>har</Starfruit></Apple><Lemon><Melon>yar</Melon><Lime>blah</Lime></Lemon></Fruit>");\n\nvar megafruit = (from x in document.Descendants("Fruit")\n                 select new\n                 {\n                     Pear = x.Element("Apple").Element("Pear").Value,\n                     Orange = x.Element("Apple").Element("Orange").Value,\n                     Starfruit = x.Element("Apple").Element("Starfruit").Value,\n                     Melon = x.Element("Lemon").Element("Melon").Value,\n                     Lime = x.Element("Lemon").Element("Lime").Value\n                 }).SingleOrDefault();	0
22020179	22019866	Getting table from mysql database to fill datalist	List <string> datalist1 = new List<string>();\n\ndatalist1.DataSource = _dtTable1;\n\ndatalist1.DataBind();	0
26609574	26609146	WPF: Image stretched when placed in StackPanel in button	UseLayoutRounding="True"	0
6282331	6281460	How to copy data from one UnamangedMemoryStream to another	_memoryPointer = tempMemoryPointer;	0
25574253	25573736	How to emit signals with dbus-sharp?	public class Blah : MarshalByRefObject\n{\n    public event MyEventHandler OnEvent;\n\n    public void EventHandler()\n    {\n        if(OnEvent != null) { OnEvent(); }\n    }\n}	0
20675926	20675862	How to compare two arrays in c# and find the exact match of arrays	if (numbers.SequenceEqual(numbers2)) {\n    // do something\n} else {\n    // do something else\n}	0
17144338	17144273	How do I restrict the number of character of data before inserting it to the a table?	If (sAddress != null && sAddress.Length > 40) {\n    sAddress = sAddress.SubString(0, 40)\n}	0
2711594	2711558	How to get service instance's endpoint uri?	var uri = OperationContext\n    .Current\n    .EndpointDispatcher\n    .EndpointAddress\n    .Uri;	0
11006833	11006786	What's a Standard Output Stream?	dir | fndstr  hi	0
3554586	3554559	Regex to find a file in folder	IEnumerable<string> files = Directory\n    .EnumerateFiles(@"c:\somePath")\n    .Where(name => Regex.IsMatch(name, "SOME REGEX"));	0
21533780	21533178	C# MVC with jQuery Datatables: Retrieving variables from GET	NameValueCollection queryCollection = HttpUtility.ParseQueryString(Request.Url.Query);\nvar items = queryCollection\n                 .AllKeys\n                 .SelectMany(queryCollection.GetValues, (k, v) => new { key = k, value = v })\n                 .Where(p => p.key.Contains("bSortable"))\n                 .ToList();	0
29116112	29115689	C# Regex second character to last character Pattern Matching	private static string ReplaceTailWithStars(string s)\n{\n    if (string.IsNullOrEmpty(s))\n        return "";\n\n    return s.First() + new string('*', s.Length - 1);\n}	0
4745407	4743450	How do I get selected text from a non-editable textbox in silverlight for wp7	TextBox.IsReadOnly	0
26124833	26124616	Wrap c++ function that needs function pointer	public delegate void GenericFunction(string param1, string param2);\n\n[DllImport("externalLib.dll", SetLastError = true)]\npublic static extern uint NativeFunction(uint parameter, [MarshalAs(UnmanagedType.FunctionPtr)]GenericFunction func);	0
21595772	21595709	How to get server element id on click event in asp.net?	protected void Button_Click(object sender, EventArgs eventArgs)\n{\n   var menuItem = sender as MenuItem;\n   if(menuItem!=null)\n   {\n    var prop = menuItem./*any property you want here*/\n   }\n}	0
14750021	14744155	panel hide and show in NGUI	void OnClick(){\n  GameObject panel2  = GameObject.Find("Panel2");\n  NGUITools.SetActive(panel2,true);       \n  GameObject panel1  = GameObject.Find("Panel1");         \n  NGUITools.SetActive(panel1,false);\n\n}	0
3561132	3561083	string in an Enum	String x = String.Format("{0:X2}", Int.Parse(myInteger));	0
21846294	13240084	How to profile only a class library?	%localappdata%\Microsoft\VisualStudio\11.0\ComponentModelCache	0
30205199	30201787	How to use a variable for the type parameter of a generic method	public object ParseEnum(Type enumType, string value)\n    {\n        return Enum.Parse(enumType, value, true);\n    }	0
4051791	4050599	Adding a value to the end of a column in an array of strings to export to CSV	StringBuilder sb=new StringBuilder(); \nfor (long rowCounter = 1; rowCounter <= iRows; rowCounter++)\n {\n    for (long colCounter = 1; colCounter <= iCols; colCounter++)\n    {\n        sb.Append(Convert.ToString(saRet[rowCounter, colCounter]));\n        sb.Append(",");       \n     }\nsb=sb.ToString().TrimEnd(',');\nsb.Append("\n");\n}	0
20582530	20579346	ASP.NET Identity: verify newly entered password of logged in user	var user = await UserManager.FindAsync(User.Identity.Name,VerifyViewModel.Password)	0
9156741	9156704	How to Make Structure as Null in C#?	EMPLOYEE?	0
18233425	18233097	How to generate dynamic C# images?	public ActionResult DynamicImage()\n    {\n        using (Bitmap image = new Bitmap(200, 200))\n        {\n            using (Graphics g = Graphics.FromImage(image))\n            {\n                string text = "Hello World!";\n\n                Font drawFont = new Font("Arial", 10);\n                SolidBrush drawBrush = new SolidBrush(Color.Black);\n                PointF stringPonit = new PointF(0, 0);\n\n                g.DrawString(text, drawFont, drawBrush, stringPonit);\n            }\n\n            MemoryStream ms = new MemoryStream();\n\n            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);\n\n            return File(ms.ToArray(), "image/png");\n        }\n    }	0
13896014	13895938	Trying to save zip to stream	var output = new MemoryStream();\n        using (var zip = new ZipFile())\n        {\n            foreach (var file in files)\n            {\n                var ms = new MemoryStream(file.Value);\n                ms.Seek(0, SeekOrigin.Begin);\n                zip.AddEntry(file.Key, ms);\n\n            }\n            zip.Save(output);\n        }\n        return output;	0
20758148	20757672	DateTime render different formats	DateTime v_Date = new DateTime(2013, 12, 22);\n\nConsole.WriteLine("{0}", v_Date);\n\nConsole.WriteLine("{0}", v_Date.ToString("dd/MM/yyy"));\n\nConsole.WriteLine("{0:dd/MM/yyy}", v_Date);	0
1019869	1019862	How to Look for a binary sequence in a file	byte[] bytes = System.IO.File.ReadAllBytes(fileName);	0
9412465	9411711	How to add HtmlGenericControl to a HtmlNode?	XmlDocument doc = new XmlDocument();\n//Load your xml here TODO\nvar divEl = doc.DocumentElement.SelectSingleNode("//div[@id='test']"); //Change your xpath here TODO\nvar newdiv = new HtmlGenericControl("div"); \nnewdiv.Attributes.Add("id", "id"); \nnewdiv.Attributes.Add("text", "text"); \nnewdiv.Attributes.Add("class", "class");\n\nXmlNode newNode = doc.CreateNode("NodeType", "NodeName", "URI/if/any"); //update your variables here\nnewNode.InnerXml = newdiv.InnerHtml;\ndivEl.AppendChild(newNode);	0
14756459	14755682	Restricting use of a structure in C#	public struct A\n{\n    private string s;\n    private int i;\n    internal bool valid;\n    internal A(string s, int i)\n    {\n        this.s = s;\n        this.i = i;\n        this.valid = true;\n    } \n    ...	0
2636140	2636117	Own component with panel	[Designer(typeof(NavigationalUserControl.Designer))]\n  public partial class NavigationalUserControl : UserControl\n  {\n    class Designer : ControlDesigner \n    {\n      public override void Initialize(IComponent component)\n      {\n        base.Initialize(component);\n        var nc = component as NavigationalUserControl;\n        EnableDesignMode(nc.panel2, "ContainerPanel"); \n        EnableDesignMode(nc.bottomPanel, "BottomPanel");\n      }\n    }\n\n    // rest of normal class\n  }	0
3509998	3509963	Is any rule to detect that object is serializable in C#?	ToString()	0
12868670	12868637	c# asp.net click button to "save as", but downloaded file becomes unintentionally modified	response.End()	0
5199087	5199045	Replace all values in IQueryable with string based on results using LINQ	var values = new [] {"StrValue1", "StrValue2", "StrValue"};\n\nvar AssessmentList = assessment                    \n    .AsEnumerable()\n    .Select(p => new LogManagementViewModel\n        {\n            newValue = values[p.NewValue],\n        });	0
9172501	9172026	List Compare with LINQ	var listOY1 = OY1.Split(',');\nbool b = OX1.Split(',').Any(x=>listOY1.Contains(x));	0
8500435	8500134	How to implement automatic printing with background threads?	if (this.InvokeRequired)                 \n    this.Invoke(new MethodInvoker(AutomaticPrintA4Delegate));	0
30549473	30549339	C# Building a Integer value with Binary operations from "Bits"	public static void Main()\n{\n    byte[] buf = new byte[] { 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };\n    byte result = 0;\n    foreach(var b in buf.Reverse())\n    {\n        result <<= 1;\n        if(b == 0xFF) result |= 1;\n    }\n    Console.WriteLine(result);\n}	0
8090432	8085333	Passing string arrays from COM to C#	static SAFEARRAY *CreateSafeStringArray(long nElements, TCHAR *elements[])\n{\nSAFEARRAYBOUND saBound[1];\n\nsaBound[0].cElements = nElements;\nsaBound[0].lLbound = 0;\n\nSAFEARRAY *pSA = SafeArrayCreate(VT_BSTR, 1, saBound);\n\nif (pSA == NULL)\n{\n    return NULL;\n}\n\nfor (int ix = 0; ix < nElements; ix++)\n{\n    BSTR pData = SysAllocString(elements[ix]);\n\n    long rgIndicies[1];\n\n    rgIndicies[0] = saBound[0].lLbound + ix;\n\n    HRESULT hr = SafeArrayPutElement(pSA, rgIndicies, pData);\n\n    _tprintf(TEXT("%d"), hr);\n}\n\nreturn pSA;\n}	0
3867730	3862781	How to apply difference in DateTime to a list of DateTime objects in c#	DateTime[] dateTimeArray = {DateTime.Now};\n        foreach (DateTime dateTime in dateTimeArray)\n        {\n            dateTime.Add(timeSpan);\n        }	0
20947864	20947788	How to retrieve public calendars from EWS?	string impName = @"impy";\nstring impPassword = @"password";\nstring impDomain = @"domain";\nstring impEmail = @"impy@domain.com";\n\nExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);\nservice.Credentials = new NetworkCredential(impName, impPassword, impDomain);\nservice.AutodiscoverUrl(impEmail);\n\n// This will work as if you are that car.\nservice.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, @"CAR1@domain.com");	0
14779665	14779415	Group by and find MAx value in a DataTable rows	var grouped = memberSelectedTiers.AsEnumerable()\n                                 .GroupBy(r => r.Field<int>("EmpId"))\n                                 .Select(grp => \n                                     new { \n                                         EmpId = grp.Key\n                                       , MaxDate = grp.Max(e => e.Field<DateTime>("Insert_Date"))\n                                     });	0
19594736	18257122	Ignore TransactionScope for specific query	public override int SaveChanges() {\ntry {\n    return base.SaveChanges();\n} catch (Exception ex) {\n\n    string message = /*stuff to log from the context*/;\n    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))\n    {\n        LogRepo.Log(msg);\n\n    }\n\n    throw;\n}	0
69769	69748	Split a list by distinct date	var q  = from date in allDates \n         group date by date.Year into datesByYear\n         select datesByYear.ToList();\nq.ToList(); //returns List<List<DateTime>>	0
12776223	12746815	How to get the datafield function to change to count from sum in EPPlus?	pivotTable.DataFields.Add(dataField);\npivotTable.DataFields[0].Function = DataFieldFunctions.Count;	0
12707058	12458998	How to select existing Chart in Excel using C#	Excel.ChartObject chartObject11 = (Excel.ChartObject)Ws.ChartObjects(1);\nchartObject11.Activate();	0
5006964	5006565	Multiple record select from Access	oledbcommand cmd1= new oledbcommand("select * from table1 where name in (" + allnames + ")",myconnection)	0
27021495	27020962	combo box acces level	String item = comboBox.SelectedItem.ToString();\nint value = int.Parse(item);\nemployeeAccessLevel = value;	0
18624260	18624189	How to set enum to public in namespace C++	namespace foo {\n    enum foo {\n        bar,\n        baz\n    };\n}	0
1643212	935215	UpdateCellValue() in a Datagridview	if (form.ShowDialog() == DialogResult.OK)\n{\n    _dataGridView.SuspendLayout();\n\n    _dataGridView.CurrentRow.Cells[e.ColumnIndex].Value = form.TextBoxText;\n    _dataGridView.UpdateCellValue(e.ColumnIndex, e.RowIndex);\n\n    _dataGridView.ResumeLayout(true);\n}	0
1071045	1071032	Searching if value exists in a list of objects using Linq	using System.Linq;\n...\n    bool has = list.Any(cus => cus.FirstName == "John");	0
33444111	33443284	How do I receive server responses in Windows Universal Apps?	reader.InputStreamOptions = InputStreamOptions.Partial;\n            await reader.LoadAsync(250);\n            Response.Text = "\"" + reader.ReadString(reader.UnconsumedBufferLength) + "\" read successfully.";	0
29678552	29678098	How can I call a method within a method and use the same variables	static void Main(string[] args)\n{\n    string first;\n    string last;\n    string birthday;\n    GetStudentInfo(out first,out last,out birthday); \n    PrintStudentDetails (first, last, birthday);    \n    GetTeacherInfo();\n    GetCourseInfo();\n    GetProgramInfo();\n    GetDegreeInfo();\n}\nstatic void GetStudentInfo(out string firstName ,out string lastName,out string birthDay)\n{\n    Console.WriteLine("Enter the student's first name: ");\n    firstName = Console.ReadLine();\n    Console.WriteLine("Enter the student's last name: ");\n    lastName = Console.ReadLine();\n    Console.WriteLine("Enter the student's birthday: ");\n    birthDay = Console.ReadLine(); \n}\nstatic void PrintStudentDetails(string first, string last, string birthday)\n{\n    Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday);\n    Console.ReadLine();\n}	0
24918997	24918641	Create a Bitmap Image from a Listbox items	int oh = listBox1.Height;\n    listBox1.Height = listBox1.ItemHeight * listBox1.Items.Count\n                   + (listBox1.Height - listBox1.ClientSize.Height);\n\n    Bitmap bmp = new Bitmap(this.listBox1.Width, this.listBox1.Height);\n    this.listBox1.DrawToBitmap(bmp, this.listBox1.ClientRectangle);\n    bmp.Save(@"Data.png" , System.Drawing.Imaging.ImageFormat.Png);\n\n    listBox1.Height = oh;	0
24911213	24821484	How to download the attach files in jira using C#	using (WebClient webClient = new WebClient())\n{\n\n    webClient.DownloadFile(new Uri(remoteUri + "?&os_username=usernamehere&os_password=passwordhere"), dPath);\n\n}	0
1477723	1474100	Access .NET generic objects from VBA	public object GetProperty(object Instance, string Property)\npublic object InvokeMethod(object Instance, string Method)\npublic object InvokeMethod_OneParm(object Instance, string Method, object Parm1)\npublic object InvokeMethod_TwoParms(object Instance, string Method, object Parm1, object Parm2)\npublic void SetProperty(object Instance, string Property, object Value)	0
1806420	1806402	How to call native VC++6 library (with std::string as parameters) from C#	[System.Runtime.InteropServices.DllImport("somedll.dll")]\npublic static extern int Fun1(int n, IntPtr[] lpNames);\n\n\n//////////////////////////////////////////////////////////////////////////\nList<string> strList = new List<string>();\n\nIntPtr[] strPointerArr = new IntPtr[strList.Count];\nfor(int i=0; i<strList.Count; ++i){\n    strPointerArr[i] = System.Runtime.InteropServices.Marshal.StringToHGlobalUni(strList[i]);\n}\nFun1(strList.Count, strPointerArr);\n\n//////////////////////////////////////////////////////////////////////////	0
12405150	12404136	How to filter IEnumerable based on an entity input parameter	static IQueryable<T> Filter<T>(IQueryable<T> col, T filter)\n{\n    foreach (var pi in typeof(T).GetProperties())\n    {\n        if (pi.GetValue(filter) != null)\n        {\n            var param = Expression.Parameter(typeof(T), "t");\n            var body = Expression.Equal(\n                Expression.PropertyOrField(param, pi.Name),\n                Expression.PropertyOrField(Expression.Constant(filter), pi.Name));\n            var lambda = Expression.Lambda<Func<T, bool>>(body, param);\n            col = col.Where(lambda);\n        }\n    }\n\n    return col;\n}	0
14705524	14705406	linq ordering grouped elements after groupby	var TheQuery = (from a in MyDC.TableFruits\n                where TheListOfBasketIDs.Contains(a.BasketID)\n                group a by a.BasketID into g\n                let lastFruitKind = g.OrderByDescending(x => x.HarvestTime)\n                                     .First().FruitKind\n                where lastFruitKind == 3 ||\n                      lastFruitKind == 4 \n                select g.Key).ToList();	0
7305744	7305679	Drawing a Bitmap?	// In initializecomponent()\nbutton1.Click += button1_Click;\n\n\n// The click handler \nprivate void button1_Click(object sender, EventArgs e)\n{\n   if (open.ShowDialog() == DialogResult.OK)\n   {          \n      dir.Text = open.FileName.ToString();   \n      image = new Bitmap(dir.Text);        \n      pictureBox1.Image = image;\n   }\n}	0
16992235	13105809	How can I get the PinchZoom ended event in Windows 8?	private void ScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)\n{\n  if(!e.IsIntermediate)\n  {\n    //Load new image depending on the zoom factor\n  }\n}	0
8591900	8591866	How to avoid duplicate data when doing SQL INSERT from CSV	insert into Order\n  select * from Order_Temp\n  WHERE NOT EXISTS\n  (\n    SELECT X\n    FROM Order o\n    WHERE o.NO_ORDRE = Order_Temp.NO_ORDRE\n    AND o.CODE_CLIENT = Order_Temp.CODE_CLIENT\n  )	0
7995634	7995524	C# - Use runtime-defined type as parameter in generic method	var genericType = typeof (List<>).MakeGenericType(t.GetType());\nvar magicalList = Activator.CreateInstance(genericType);	0
1544181	1544168	Calculating very large whole numbers	System.Numerics.BigInteger	0
15790324	15753887	Sort a datagrid column by an enum type	_colDefs["Subtype"] = new DataGridTextColumn()\n{       \n    Binding = new Binding("Subtype"),\n    SortMemberPath = "Subtype"\n};	0
10432337	10431816	Sending Messages From NServiceBus Host	using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew))\n{\n    _bus.Send(new LogFatalMessage(ex));\n    ts.Complete();\n}	0
21000677	20952297	How to (if possible) set the orientation of a CustomLabel in the Microsoft Chart Control?	var label = new CustomLabel(pos - intervalOffset, pos + intervalOffset, convertValue(pos), labelRow: 0, markStyle: LabelMarkStyle.None);	0
6883487	6883356	C# - How to create updatable enumerator?	foreach (Obj obj in yourBaseObjects) {\n    Obj localObj = obj; // See Dans comment!!!\n    Button button = new Button(); // however you create your buttons\n    button.Click += {\n         // do something with obj\n         Console.WriteLine(localObj);\n    }\n}	0
20996425	20996124	Lost trying to draw a line of x length y degrees	int endX = Convert.ToInt32(Math.Round(x - wSpeed * Math.Sin(Calcs.Radians(angle))));	0
24720084	24626876	How to dynamically position a listbox in relation to textbox in winforms	private void textBox1_Enter(object sender, EventArgs e)\n    {\n        TextBox TextB = (TextBox)sender;\n\n        listBox1.Location = new Point(TextB.Location.X, TextB.Location.Y + TextB.Height + 5);\n        listBox1.Visible = true;\n    }\n\n    private void textBox1_Leave(object sender, EventArgs e)\n    {\n        listBox1.Visible = false;\n    }	0
11245519	11245167	Setting properties from one class to another via GetProperties	public class A \n    {\n        public int Id;\n        public string Name;\n        public string Hash;\n        public C c;\n    }\n\n    public class B \n    {\n        public int id;\n        public string name;\n        public C c;\n    }\n\n    public class C \n    {\n        public string name;\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var a = new A() { Id = 123, Name = "something", Hash = "somehash" };\n            var b = new B();\n\n            AutoMapper.Mapper.CreateMap<A, B>();\n\n            b = AutoMapper.Mapper.Map<A, B>(a);\n\n\n            Console.WriteLine(b.id);\n            Console.WriteLine(b.name);\n\n            Console.ReadLine();\n        }\n}	0
6022912	5997326	Extract pkcs7 (byte[]) from a pdf file using IText or ITextSharp or BouncyCastle	public static byte[] ExtractPKCS7From(string path)\n{\n    AcroFields acroFields = new PdfReader(path).AcroFields;\n    List<string> names = acroFields.GetSignatureNames();\n\n    foreach(var name in names)\n    {\n        PdfDictionary dict = acroFields.GetSignatureDictionary(name);\n        PdfString contents =\n            (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));\n\n        return contents.GetOriginalBytes();\n    }\n    return null;\n}	0
4602068	4602058	how to get the path before filename	System.IO.Path.GetDirectoryName()	0
18562282	18562002	C# DataGridView refresh after insert	//in Form A\nprivate void btnOpenFromB_Click(sender,event)\n{\nFormB B =new FormB();\nif(B.ShowDialog()==DilogResult.Yes)\n   //Call RefreshMethod of DG\n}\n\n\n//In Form B\n //in Constructor\npublic FromB()\n{\n   initilizeComponents();\n   DialogResult=DialogResult.No;\n}\n//In Insert Button Click\nprivate void InserClick(sender,event)\n{\n    if(Checking()==true)\n     { \n        //Insert Operations\n        DialogResult=DilogResult.Yes;\n        this.Close();\n      }\n}	0
13554013	13553966	remove duplicates from two string arrays c#	var c = b.Except(a).ToArray(); // gives you { "5", "6" }	0
3481950	3481923	In c# convert anonymous type into key/value array?	var a = new { data1 = "test1", data2 = "sam", data3 = "bob" };\nvar type = a.GetType();\nvar props = type.GetProperties();\nvar pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();\nvar result = string.Join("&", pairs);	0
9728834	9728439	How to split datagrid into same rectangles	int c = ran.Next(1, 5);\n\nfor (int i = 0; i < box_width; i += 2)\n{\n    for (int j = 0; j < box_height; j += 2)\n    {\n        Color cellColor;\n\n        switch (c)\n        {\n            case 1:\n                cellColor = Color.Yellow;\n                break;\n            case 2:\n                cellColor = Color.LightGray;\n                break;\n            case 3:\n                cellColor = Color.LightBlue;\n                break;\n            case 4:\n                cellColor = Color.Blue;\n                break;\n        }\n\n        MyClass.grid.Rows[j].Cells[i].Style.BackColor = cellColor;\n        MyClass.grid.Rows[j].Cells[i+1].Style.BackColor = cellColor;\n        MyClass.grid.Rows[j+1].Cells[i].Style.BackColor = cellColor;\n        MyClass.grid.Rows[j+1].Cells[i+1].Style.BackColor = cellColor;\n    }\n}	0
9840603	9840539	How do i get the difference in two lists in C#?	var difference = songs.Except(attributes.Select(s=>s.name)).ToList();	0
15328104	15328096	C# Lambda with no inputs (params)?	public void test()\n{\n    exc(()=>1);\n}	0
3241025	3240803	How can I prevent windows from showing in .NET?	[DllImport("user32.dll")]\n   static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); \n\n   static void MinimizeProcess(string procName)\n    {\n        foreach (Process p in Process.GetProcesses())\n        {\n            if (p.ProcessName == procName)\n            {\n                ShowWindow(p.MainWindowHandle,11);\n\n            }\n        }\n    }	0
2248651	2248583	Comparing list of strings with an available dictionary/thesaurus	// Read words from file.\nstring [] words = ReadFromFile();\n\nDictionary<String, List<String>> permuteDict = new Dictionary<String, List<String>>(StringComparer.OrdinalIgnoreCase);\n\nforeach (String word in words) {\n    String sortedWord = new String(word.ToArray().Sort());\n    if (!permuteDict.ContainsKey(sortedWord)) {\n        permuteDict[sortedWord] = new List<String>();\n    }\n    permuteDict[sortedWord].Add(word);\n}\n\n// To do a lookup you can just use\n\nString sortedWordToLook = new String(wordToLook.ToArray().Sort());\n\nList<String> outWords;\nif (permuteDict.TryGetValue(sortedWordToLook, out outWords)) {\n    foreach (String outWord in outWords) {\n        Console.WriteLine(outWord);\n    }\n}	0
2782415	2782356	C# Serial Communications - Received Data Lost	private SerialPort sp;\nprivate List<byte> byte_buffer = new List<byte>();    \n\nprivate void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n   byte_buffer.Clear();\n\n   while (sp.BytesToRead > 0)\n   {\n      byte_buffer.Add((byte)sp.ReadByte());\n   }\n}	0
205347	205287	Preserve white space in string with XmlTextWriter.WriteString	class Program\n{\n    static void Main(string[] args)\n    {\n\n        XmlWriter w = XmlTextWriter.Create("./foo.xml");\n        w.WriteStartElement("foo");\n        w.WriteString(" THIS   HAS VARYING     SPACeS ");\n        w.WriteEndElement();\n        w.Close();\n\n        StreamReader sr = new StreamReader("./foo.xml");\n        Console.WriteLine(sr.ReadToEnd());\n        Console.ReadKey();\n    }\n}	0
8590823	8590621	How to simplify this piece of code?	char[] strIN = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '1', '_' };\n        char[] strOut = { '2', '3', '4', '5', '6', '7', '8', '9', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'X', 'Y', '_' };\n\n\n        char init = 'C';\n\n        int index = Array.IndexOf(strIN, init);\n        char output = strOut[index];	0
18405951	18405831	Multiple parameters in seed lambda expression	foreach (var pd in PatientDrugs)\n{\n    context.PatientDrugs\n        .AddOrUpdate(p => new { p.DispenseDate, p.DrugId }, pd);\n}	0
24989016	24962857	Read XML file from URL, comes up empty	XmlDocument xDoc = new XmlDocument(); \n    xDoc.Load(@"http://www.boi.org.il//currency.xml"); \n    XmlNodeList xmllist = xDoc.GetElementsByTagName("CURRENCIES"); \n    Console.WriteLine(xmllist.Count);	0
4182249	4182127	Validate short dates based on culture information	System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("fr-FR");\n\nDateTime dt = DateTime.ParseExact("15.11.2009",cultureinfo.DateTimeFormat.ShortDatePattern,cultureinfo); \n// will throw error\nbut  not \n\nDateTime dt = DateTime.ParseExact("15/11/2009",cultureinfo.DateTimeFormat.ShortDatePattern,cultureinfo);	0
4058257	4058208	How to safely check arrays bounds	for(int x = 1; x < Size-1; x++)  // these all have x-1 and x+1 neighbours	0
23929540	23929240	How to add to first array element?	string[][] mergeBlockData = \n     new List<string[]>{ dt.Columns.OfType<DataColumn>().Select(dc => dc.ColumnName).ToArray() }.Concat(\n     dt.Rows.OfType<DataRow>()\n         .Select(\n        r => dt.Columns.OfType<DataColumn>()\n            .Select(c => r[c.ColumnName].ToString()).ToArray()\n         )\n     )\n    .ToArray();	0
4671750	4671695	How to simulate key presses in C#	var number = 2011;\n   InputSimulator.SimulateTextEntry(number.ToString());	0
29032119	24959014	Output MSIL in separate file	Build Events	0
14955314	14955093	Custom JSON in Apple push notification	{"aps":{"alert":"You got a new message","badge":1,"sound":"beep.wav"},"message":"Message bla bla","type":1,"data":"Tekst"}	0
32159307	32159126	Validate relation one to one EF and data-annotations	[Range(1, int.MaxValue)]\npublic int IdCategory{ get; set; }	0
23720768	23720343	Asp.Net change value of textbox in grid on selected Index changed	protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        DropDownList ddl = (DropDownList)sender;\n        GridViewRow row = (GridViewRow)ddl.NamingContainer;\n        TextBox txtName = (TextBox)row.FindControl("txtCp");\n        txtName.Text = "*****";\n\n    }	0
33891065	33890305	How to Create Datatable Columns With DataType From Array?	public static Dictionary<string, Type> PrimitiveTypes = new Dictionary<string, Type>\n      {\n         {"int",typeof(int)},\n         {"string",typeof(string)}\n      };\n\n    public static void Main(string[] args)\n    {\n        DataTable dtColorList = new DataTable();\n\n        string[,] values = new string[,] { { "ID", "int" }, { "Name", "string" } };\n        AddDataTableColWithType(dtColorList, values);\n\n        Console.ReadLine();\n    }\n\n    public static void AddDataTableColWithType(DataTable dtName, string[,] colNameAndType)\n    {\n        for (int i = 0; i < colNameAndType.Length / 2; i++)\n        {\n            dtName.Columns.Add(colNameAndType[i, 0], PrimitiveTypes[colNameAndType[i, 1]]);\n        }\n    }	0
26779659	26779400	How to calculate how many checkboxes are checked in asp.net?	protected void click(object sender, EventArgs e)\n{ \n    int count=0;\n    if(checkbox1.checked)\n    {\n        count ++;\n    }\n    if(checkbox2.checked)\n    {\n        count ++;\n    }\n    if(checkbox3.checked)\n    {\n        count ++;\n    }\n\n    textbox.text = count.ToString();\n}	0
6797319	6797048	how can get innerhtml of a server side element with c# (with another server-side controls inside)	var sb = new StringBuilder();\nmainDiv.RenderControl(new HtmlTextWriter(new StringWriter(sb)));\n\nstring s = sb.ToString();	0
12137739	12090286	Datagridview ComboBoxCell set default value?	private void dataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)\n    {\n        e.Row.Cells[4].Value = "DropDown";\n    }	0
32713365	32712421	Find bankbalance with Dataset	var id = (from DataRow dr in dt.Rows\n          where Convert.ToString(dr["AccountNo"]) == accountNumber\n          select dr["Balance"]).FirstOrDefault();\n\nreturn id.ToString();	0
21113787	21113554	How can I redirect to the same page and keep textbox values in asp.net?	protected void Page_Load(object sender, EventArgs e)\n{\n    if(ViewState["SomeInformation"] != null)\n        NameLabel.Text = ViewState["SomeInformation"].ToString();\n    else\n        NameLabel.Text = "Not set yet...";\n}	0
20410085	20409867	Fluent API many to one relation	User = new Users();	0
1566871	1566865	In a Property Setter is it Beneficial to only Set if Value Differs?	class Something : INotifyPropertyChanged\n{\n      public int TestID \n      {\n           get { return testId; }\n           set \n           {\n                if (testId != value)\n                {\n                     testId = value;\n                     RaisePropertyChangedEvent("TestID");\n                }\n           }\n      }\n }	0
6586342	6586189	convert object to array of objects	// Object { 7="XXX", 9="YYY" }\nvar bad = {\n    7 : "XXX",\n    9 : "YYY"\n};\n\nfunction fix(input)\n{\n    var output = [], index;\n\n    for(index in input) {\n        output.push({\n            "KEY" : index,\n            "VALUE" : input[index]\n        });\n    }\n\n    return output;\n}\n\n// [Object { Key=7, Value="XXX"}, Object { Key=9, Value="YYY"}]\nvar good = fix(bad);	0
5429656	5429626	How to remove the selecterow style in a gridview on cancel button - asp.net	this.gvArticles.selectedIndex = -1;	0
27605958	27605637	How to place a Rectangle in a new image with different size, while preserving the size and quality of the orignial Rectangle?	Bitmap newLetterBitmap = new Bitmap(260, 260);\nGraphics g = Graphics.FromImage(newLetterBitmap);\ng.DrawImageUnscaled(newImage, 0, 0);	0
9565267	9565118	Save a file to SQL database using Silverlight and LINQ	var stream = openFileDialog.File.OpenRead();\n        using (var memStream = new System.IO.MemoryStream())\n        {\n            stream.CopyTo(memStream);\n            return memStream.ToArray();\n        }	0
9928155	9928124	Get directly dictionary<int, object> first key without foreach in C#	using System.Linq;\n\n...\n\ndictionary.First().Key // Returns 75\ndictionary.First().Value // returns the related SimpleObject	0
1618035	1617990	Mapping switch statements to data classes	public static MetaData CreateMetaDataFrom(IEnumerable<TextFrame> textFrames)\n{\n    return new MetaData()\n    {\n        metaData.AlbumArtist = textFrames.Where(frame => frame.Descriptor.ID = "TPE1").SingleOrDefault().Content,\n        metaData.AlbumTitle = textFrames.Where(frame => frame.Descriptor.ID = "TALB").SingleOrDefault().Content, \n        metaData.SongTitle = textFrames.Where(frame => frame.Descriptor.ID = "TIT2").SingleOrDefault().Content;\n        metaData.Year = textFrames.Where(frame => frame.Descriptor.ID = "TYER").SingleOrDefault().Content;\n    };\n}	0
3463170	3463045	Best way to get all bits of an enum flag?	Enum.GetValues(typeof(Enum)).Cast<int>().Sum();	0
9973623	9907820	Can't get proper JSON response from face.com API	public FaceAPI faces_detect(List<string> urls, string filename, List<string> ownerIds, List<string> attributes, string callBackUrl)\n{\n    List<string> list = this.prep_lists(urls, ownerIds, attributes);\n    Dictionary<string, string> dict = new Dictionary<string, string>();\n\n    dict.Add("urls", list[0]);\n    dict.Add("owner_ids", list[1]);\n    dict.Add("attributes", list[2]);\n    dict.Add("_file", "@" + filename);\n    dict.Add("callback_url", callBackUrl);\n\n    return this.call_method("faces/detect", dict);\n}	0
5803699	5083405	How to control windows-ce 5.0 backlight?	DsLightSensor lightSensor = new DsLightSensor();\nif (DapServices.DS_EXECUTION_OK ==\n    DapServices.DapService(DapServicesCode.DS_GET_LIGHT_SENSOR, lightSensor))\n{\n    lightSensor.dwIntensity = hScrollBarIntensity.Value;\n    DapServices.DapService(DapServicesCode.DS_SET_LIGHT_SENSOR, lightSensor);\n}	0
9318552	9318473	Best way to represent time duration in a log entry	0h 0m 2s 7.815ms	0
22564912	22564846	C# compare two DateTimes	TimeSpan difference = _effective_date - date_of_submission;\nif(difference.TotalDays > 90)\n{\n  // Bingo!\n}	0
12970081	12970048	How to extract the raw generic type out of generic type with type parameters	Type.GetGenericTypeDefinition	0
17338166	17337186	how to get all the translated words from google translation through C#?	GoogleTranslator.cs	0
28536682	28536132	Unable to post json using c# to google cloud endpoint	client.Headers.Add(HttpRequestHeader.ContentType, "application/json");	0
25019480	25019365	Passing a List of values and rerturning a Dictionary for their associated results	private IDictionary<string, string> Lookup(List<string> des)\n{\n    var query = (from r in repo.Context.MyTable\n        where des.Contains(r.Description)\n        select r);\n    return query.ToDictionary(r => r.Key, r => r.Description);\n}	0
17361025	17360866	Getting the ip adress of the user connected to asp application	protected string GetIPAddress()\n        {\n            System.Web.HttpContext context = System.Web.HttpContext.Current;\n\n            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];\n\n            if (!string.IsNullOrEmpty(ipAddress))\n            {\n                string[] addresses = ipAddress.Split(',');\n                if (addresses.Length != 0)\n                {\n                    return addresses[0];\n                }\n            }\n\n            return context.Request.ServerVariables["REMOTE_ADDR"];\n        }	0
21645303	21645196	Getting responsefrom a TCP Client	TcpClient tcpClient = new TcpClient ();\n\n// Uses the GetStream public method to return the NetworkStream.\nNetworkStream netStream = tcpClient.GetStream ();\n\nif (netStream.CanRead)\n    {\n        // Reads NetworkStream into a byte buffer. \n        byte[] bytes = new byte[tcpClient.ReceiveBufferSize];\n\n        // Read can return anything from 0 to numBytesToRead.  \n        // This method blocks until at least one byte is read.\n        netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);\n\n        // Returns the data received from the host to the console. \n        string returndata = Encoding.UTF8.GetString (bytes);\n\n        Console.WriteLine ("This is what the host returned to you: " + returndata);\n\n    }	0
26872900	26872393	How to refactor EF data access code to avoid context issues	var repo = new StoresRepository(connectionString);\n\nvar store = repo.GetStore(1);\n\nrepo.Update(store);	0
6689920	6679587	Use Microsoft Solver Foundation in C#	"The referenced assembly "Microsoft.Solver.Foundation, Version=3.0.1.10599, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" could not be resolved because it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project."	0
2343044	2292126	How to edit a pdf in the browser and save it to the server	gswin32c.exe -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r300 -sOutputFile=output.jpg input.pdf	0
11247038	11246948	Executing JavaScript on a Button Click in Code Behind	protected void btnDoRegister_Click(object sender, System.Web.UI.ImageClickEventArgs e)\n{\n     C# code is here doing form processing\n     // Now I need to Execute javascript here.\n     string script = "<script type=\"text/javascript\"> functionToExecute(); </script>";\n     ClientScript.RegisterClientScriptBlock(this.GetType(), "myscript", script);\n}	0
841251	840310	How to export Excel worksheets into new workbooks	worksheet.SaveAs(Filename:=filePath)	0
18908774	18908746	Name a list with a combination of previously defined variables in C#?	Dictionary<string,List<string>>	0
9307735	9305622	How do I fill ONE View from Separate Tables using Linq?	var view = Teachers.Select( \n              t => new { t.FirstName, t.LastName, t.Email } ).\n           Union( Students.Select( \n              t => new { t.FirstName, t.LastName, t.Email }) ).ToList();	0
17673004	17672899	How do I fill a textbox with text if it is empty?	void c_TextChanged(object sender, EventArgs e)\n{\n    textBox1.Text = ((TextBox)sender).Text;\n}	0
25223555	25223546	how to block the events of the parent when a child element is clicked	void Button_Click_1(object sender, RoutedEventArgs e)\n    {\n        //Handler code here\n        e.Handled = true;\n    }	0
25304309	25304000	Traversing all descendants of an object	Action<IEnumerable<Unit>> process = null;\nvar processed = new HashSet<Unit>();\nprocess = list => {\n   foreach(var u in list.Where (processed.Add))\n    {\n        // do something here with u\n        //... and then process children\n        process(u.ChildUnits);\n    }\n};\n\nprocess(myList); // do the actual processing	0
1722502	1722474	Read referenced namespaces from Type	var namespaces = type.GetProperties()\n                     .Select(p => p.PropertyType.Namespace)\n                     .Distinct();	0
14190043	14189995	Create an event to watch for a change of variable	class Foo\n{\n    Boolean _booleanValue;\n\n    public bool BooleanValue\n    {\n        get { return _booleanValue; }\n        set\n        {\n            _booleanValue = value;\n            if (ValueChanged != null) ValueChanged(value);\n        }\n    }\n\n    public event ValueChangedEventHandler ValueChanged;\n}\n\ndelegate void ValueChangedEventHandler(bool value);	0
13597148	13597104	how do i split string in c#?	var address = "#306, Los Angel,opp Line Tower,3rd cross\nAng Mo Kio Al-mera 520506\nDubai".Split(new [] {',', '\n' })\nvar array = address.Split(new [] {',', '\n' })	0
20616855	20616729	How to populate two separate arrays from one comma-delimited list?	int[20] scores = {10,10,20,20,30,35,40,50,45,50,45,50,50,50,20,20,45,90,85,85};\n\nint[10] earned;\nint[10] possible;\n\nint a = 0;\nfor(int x=0; x<10; x++)\n{\n    earned[x] = scores[a++];\n    possible[x] = scores[a++];\n}	0
19087672	19087651	What is the most elegant way to load a string array into a List<int>?	List<int> intList = intArray.Select(str => int.Parse(str)).ToList();	0
30005589	29978530	Scale and translate transformations on a matrix	var tt1 = new TranslateTransform(x,y);\nvar matrix=_touchMatrix* tt1.Value;\n\nvar sc=new ScaleTransform(scaleX, scaleY);\nmatrix = matrix *sc.Value;\n\nvar tt2 = new TranslateTransform(-x,-y);\nmatrix =matrix*tt2.Value ;	0
22972594	22956518	Unity3d - How to get Animator's Layer -->Sub-State --> State namehash?	static int rollState = Animator.StringToHash ("Jump_Fall_Roll.Roll");	0
21759447	21759383	C# Syntax lambdas with curly braces	AddDelegate ad = (a, b) =>\n                 {\n                     return a + b;\n                 };	0
2313366	2313326	how to substring from a string using c#?	string theString = "FirstName=ABC;LastName=XZY;Username=User1;Password=1234";\nstring username = theString.Split(";").Where(s => s.Split("=")[0].Equals("Username")).ToArray()[0].Split("=")[1];	0
7856469	7855201	How do you display a vertical scrollbar on the .NET WebBrowser control only when it's needed?	html, body\n{\n    overflow: auto;\n}	0
1724755	1724596	How can I use a threadpool to process each connection in a new thread	public void Start()\n{\n    this.listener.Start();\n    Console.WriteLine("Server running...");\n\n    while (true)\n    {\n        Socket s = this.listener.AcceptSocket();\n        ThreadPool.QueueUserWorkItem(this.WorkMethod, s);\n    }\n}\n\nprivate void WorkMethod(object state)\n{\n    using (Socket s = (Socket)state)\n    {\n        byte[] buffer = new byte[100];\n        int count = s.Receive(buffer);\n        string message = "Hello from the server";\n        byte[] response = Encoding.ASCII.GetBytes(message);\n        s.Send(response);\n    }\n}	0
4587605	4587415	How to capture Shell command output in C#?	string parms = @"QUERY \\machine\HKEY_USERS";\n        string output = "";\n        string error = string.Empty;\n\n        ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms);\n\n        psi.RedirectStandardOutput = true;\n        psi.RedirectStandardError = true;\n        psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;\n        psi.UseShellExecute = false;\n        System.Diagnostics.Process reg;\n        reg = System.Diagnostics.Process.Start(psi);\n        using (System.IO.StreamReader myOutput = reg.StandardOutput)\n        {\n            output = myOutput.ReadToEnd();\n        }\n        using(System.IO.StreamReader myError = reg.StandardError)\n        {\n            error = myError.ReadToEnd();\n\n        }	0
29008684	29008589	C# Enter Timestamp at Enter in Richtexbox	private void richTextBox2_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Return)\n    {\n        richTextBox2.SelectedText = DateTime.Now.ToString() + " --";\n        e.Handled = true;\n    }\n}	0
10289609	10275384	Exchange Web Services using FindItems on large folders	items = folder.FindItems(new ItemView(100)\n                {\n                    Traversal = ItemTraversal.Shallow,\n                    PropertySet = PropertySet.IdOnly\n                });\n\nservice.LoadPropertiesForItems(items, new PropertySet(ItemSchema.DateTimeReceived, \n                    ItemSchema.Subject));	0
8795656	8795550	Casting a result to float in method returning float changes result	x * y / z	0
8469566	8426134	add crosshair to charts in a winform project	cursor_Y = Chart1.ChartAreas["ChartArea1"].CursorY;\ncursor_X = Chart1.ChartAreas["ChartArea1"].CursorX;\ncursor_Y.LineWidth = 2;\ncursor_Y.LineDashStyle = ChartDashStyle.DashDot;\ncursor_Y.LineColor = Color.Red;\ncursor_Y.SelectionColor = Color.Yellow;\n\ncursor_X.LineWidth = 2;\ncursor_X.LineDashStyle = ChartDashStyle.DashDot;\ncursor_X.LineColor = Color.Red;\n\nChart1.MouseMove += new MouseEventHandler(Chart1_MouseMove);\n...\nPointF _point = new PointF(2,2);\n\nvoid Chart1_MouseMove(object sender, MouseEventArgs e)\n{\n    _point.X = e.Location.X;\n    _point.Y = e.Location.Y;\n\n    Chart1.ChartAreas["ChartArea1"].CursorY.SetCursorPixelPosition(_point, true);\n    Chart1.ChartAreas["ChartArea1"].CursorX.SetCursorPixelPosition(_point, true);\n}	0
22913602	22913170	how current a big(max) Column	int max = 0;\n\n    for (int j = 0; j < SIZE; j++)\n    {\n        int currentColumn = 0;\n        for (int i = 0; i < SIZE; i++)\n        {\n            currentColumn = currentColumn + Table[i, j];\n            if (max < Table[i, j])\n            {\n                max = Table[i, j];\n            }\n\n\n        }\n\n\n        Console.Write();\n        Console.Write("\t");\n\n    }\n\n    Console.WriteLine("The maximum value for the table is {0}", max);	0
2222117	2146358	How to convert a shape from Directx to gdi+ using c#	public Form1()\n{\n    InitializeComponent();\n\n    this.Paint += new PaintEventHandler(Form1_Paint);\n\n    // This works too\n    //this.Paint += (_, args) => DrawCircle(args.Graphics);  \n}\n\nvoid Form1_Paint(object sender, PaintEventArgs e)\n{\n    DrawCircle(e.Graphics);\n}\n\nprivate void DrawCircle(Graphics g)\n{\n    int x = 0;\n    int y = 0;\n    int radius = 50;\n\n    // The x,y coordinates here represent the upper left corner\n    // so if you have the center coordinates (cenX, cenY), you will have to\n    // substract radius from  both cenX and cenY in order to represent the \n    // upper left corner.\n\n    // The width and height represents that of the bounding rectangle of the circle\n    g.DrawEllipse(Pens.Black, x, y, radius * 2, radius * 2);\n\n    // Use this instead if you need a filled circle\n    //g.FillEllipse(Brushes.Black, x, y, radius * 2, radius * 2);\n\n}	0
5011163	5011091	What C# data structure should I use to map a varying number of key/value pairs to a list of strings?	class ContactInfo\n{\n   string Name;\n   string TelephoneNumber;\n}\n\nDictionary<string, ICollection<ContactInfo>> addressAndPeopleLivingThere = \n    new Dictionary<string, ICollection<ContactInfo>>();\n\naddressAndPeopleLivingThere.Add("1 Some Street", new List<ContactInfo>());\naddressAndPeopleLivingThere["1 Some Street"].Add(new ContactInfo { Name = "Name", TelephoneNumber = "000-000-0000" });	0
1598646	1598620	Direct access to TableLayoutPanel Cells	layoutPanel.GetControlFromPosition(x,y);	0
8211078	8210973	How to retrieve style of the HTML server control programmatically?	toggleText.Style["Display"];	0
6424660	6424606	How can I parse the int from a String in C#?	str = Regex.Replace(str, "\D+", String.Empty);\nif (str.Length > 0) {\n  int value = Int32.Parse(str);\n  // here you can use the value\n}	0
18805526	18805491	How can I perform operation in SQL query?	(dateTimePicker1.Value- duedate.Value).TotalDays*50	0
2968874	2968859	Linq-to-sql join/where?	var q = from u in usertypes\n        join t in types on u.typeid equals t.id\n        where t.isBool == false && usertypes.user == id\n        select u;	0
19368754	19368618	In Entity Framework 5 CodeFirst, how to create a query that will return when any pair of values are found?	var concatenatedkeys = keys.Select(m => m[0] + "~" + m[1]).ToList();\n\nvar filtered = \n     dataContext.T.Where(s => concatenatedKeys.Contains(\n                                             s.Column0 ?? string.Empty + \n                                             "~" + \n                                             s.Column1));	0
8040380	8040109	covert timezone info into datetime	var myDate = DateTime.ParseExact("2011-11-27 23:59:59 EST", \n    "yyyy-MM-dd HH:mm:ss EST", CultureInfo.InvariantCulture);	0
4722165	4722010	Enum from string, int, etc	public static class EnumHelper\n{\n   public static T FromInt<T>(int value)\n   {\n       return (T)value;\n   }\n\n  public static T FromString<T>(string value)\n  {\n     return (T) Enum.Parse(typeof(T),value);\n  }\n}	0
17166188	17149426	Formatting a data bound control according to bound data	private void dataRepeater1_DrawItem(object sender, Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs e)\n    {\n        CheckBox cbSchoolMon = e.DataRepeaterItem.Controls["cbSchoolMon"] as CheckBox;\n        Label lbTeacherIDMon = e.DataRepeaterItem.Controls["lbTeacherIDMon"] as Label;\n\n        PictureBox pbMon = e.DataRepeaterItem.Controls["pbMon"] as PictureBox;\n\n        if (cbSchool.Checked)\n        {\n            pbMon.BackColor = Color.Red;\n        }\n        else\n        {\n            pbMon.BackColor = Color.Yellow;\n        }\n    }	0
2725797	2700421	PDF files with XML files attached	using System;\nusing org.pdfbox.pdmodel;\nusing org.pdfbox.util;\n\nnamespace PDFReader\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        PDDocument doc = PDDocument.load("lopreacamasa.pdf");\n        PDFTextStripper pdfStripper = new PDFTextStripper();\n        Console.Write(pdfStripper.getText(doc));\n    }\n}\n}	0
30860106	30853842	How to create a PDFsharp table with dynamic data?	regex.Match(colorStr.Replace(" ", ""));	0
33131122	33129912	How to convert a group_concat, join, and union query into linq lambda?	var allitems =\n    _programContentService\n    .Products\n    .Select(x => new { x.FullName, x.TypeId, x.Id })\n    .Union(\n        _programContentService\n        .Programs\n        .Select(x => new { x.FullName, x.TypeId, x.Id }))\n    .Join(\n        _programContentService.SpecialtyMembers,\n        type => new { type.TypeId, type.Id },\n        member => new { TypeId = member.ItemType, Id = member.ItemId },\n        (type, member) => new { type.FullName, member.Category })\n    .Join(\n        _programContentService.Specialties,\n        x => x.Category,\n        specialty => specialty.Id,\n        (x, specialty) => new { x.FullName, specialty.CategoryName })\n    .GroupBy(x => x.FullName)\n    .AsEnumerable()\n    .Select(x => new SelectListItem \n        { \n            Value = x.Key, \n            Text = String.Join(",", x.Select(y => y.CategoryName))\n        });	0
27641057	27640230	How to find if a user has a membership to a specific Global Group in a service?	if (!String.Equals(group, @"DOMAIN\DeployUsersProd", StringComparison.OrdinalIgnoreCase)) { continue; }	0
9666314	9666073	Word Document Paragraph break	Paragraph.KeepTogether	0
14069724	14069669	Detecting an empty array without looping	List<T>	0
33134711	33134376	trying to create a try catch exception where if a file can't be found a new file with values of the old file is loaded instead	string[] newCredentials, data, parts;\nif (!File.Exists(@"C:\Users\Scott\Documents\dict.csv"))\n{\n    //create .csv file\n    newCredentials = new string[2];\n    newCredentials[0] = "Bob2,password";\n    newCredentials[1] = "user,pass";\n    File.WriteAllLines(@"C:\Users\Scott\Documents\newdict.csv", newCredentials))\n    Credentials.Add("bob2", "password");                          \n    Credentials.Add("user", "pass");\n}\nelse\n{\n    data = File.ReadAllLines(@"C:\Users\Scott\Documents\dict.csv");\n    foreach(string login in data)\n    {\n        parts = login.Split(',');\n        Credentials.Add(parts[0].Trim(), parts[1].Trim());\n    }\n}	0
27019262	27019176	How compare SQL Server Datetime from C#	date.ToString("yyyy-MM-dd HH:mm:SS")	0
16424301	16424196	Using reflection and a List<>, can one return an array of specific properties via an extension method?	var propDouble = listOfClasses.Select(x => typeof(someClass)\n                                           .GetProperty("someDouble")\n                                           .GetValue(x)).ToArray();	0
23635420	23612719	How to override method and call base in stub with Microsoft Fakes	var stubPotato = new StubPotato()\n{\n    PeelPeelingMethod = (p) =>\n    {\n        //Base method call\n        MethodInfo methodInfo = typeof(Potato).GetMethod("Peel", BindingFlags.Instance | BindingFlags.Public);\n        var methodPtr = methodInfo.MethodHandle.GetFunctionPointer();\n        var baseMethod = (Func<PeelingMethod,string>)Activator.CreateInstance(typeof(Func<PeelingMethod,string>), stubPotato , methodPtr);\n        string baseResult = baseMethod(p);\n\n        //Code for the "override"\n        Console.WriteLine("Hello world");\n    }\n}	0
7403712	7403126	Accessing webservice through HTTPS gives ArgumentException	new System.ServiceModel.WSHttpBinding()	0
32727638	32698695	Universal Windows App, cant execute doc.LoadXml(string)	private async void button_Click(object sender, RoutedEventArgs e)\n\n{\nstring url = String.Format("http://url");\n            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); \n            StreamReader reader = new StreamReader(response.GetResponseStream());\n            XmlDocument elementdData = new XmlDocument();\n            woeidData.Load(reader);\n            XmlNodeList element = woeidData.GetElementsByTagName("elementID");\n}	0
14899315	14898936	Reference tables in FluentNHibernate	public ProductMap()\n{\n    Id(x => x.Id);\n    Map(x => x.Name).Length(255).Nullable();\n    HasManyToMany(x => x.Stores)\n        .AsBag()\n        .Table("StoreProduct")\n}	0
10011697	4364780	How to retrieve the 3D rotation angle on each axis?	double rotationX = Vector3D.AngleBetween(new Vector3D(1, 0, 0), yourMatrix3D.Transform(new Vector3D(1, 0, 0)));\n double rotationY = Vector3D.AngleBetween(new Vector3D(0, 1, 0), yourMatrix3D.Transform(new Vector3D(0, 1, 0)));\n double rotationZ = Vector3D.AngleBetween(new Vector3D(0, 0, 1), yourMatrix3D.Transform(new Vector3D(0, 0, 1)));	0
3677103	3677016	To uncomment a commented node in a XML file using C#	string xml = @"\n    <root>\n      <!--<reltable toc='no' class='- map/reltable '>\n      <relheader class='- map/relheader '>\n        <relcolspec type='concept' class='- map/relcolspec '/>      \n      </relheader>         \n    </reltable> -->\n\n    <!--<reltable toc='no' class='- map '>\n      <relheader class='- map/relheader '>\n        <relcolspec type='concept' class='- map/relcolspec '/>      \n      </relheader>          \n    </reltable> -->\n  </root>";\n\n  XmlDocument xdoc = new XmlDocument();\n  xdoc.LoadXml(xml);\n\n  XmlNodeList commentedNodes = xdoc.SelectNodes("//comment()");\n  var commentNode = (from comment in commentedNodes.Cast<XmlNode>()\n              where comment.Value.Contains("class='- map '")\n              select comment).FirstOrDefault();\n\n  if (commentNode != null)\n  {\n    XmlReader nodeReader = XmlReader.Create(new StringReader(commentNode.Value));\n    XmlNode newNode = xdoc.ReadNode(nodeReader);\n    commentNode.ParentNode.ReplaceChild(newNode, commentNode);\n  }	0
20221725	17943651	Validate Data that is being read from an Excel File with EP Plus	var paretnCodeValidation = codeSheet.DataValidations.AddTextLengthValidation("B:B");\n        paretnCodeValidation.ShowErrorMessage = true;\n        paretnCodeValidation.ErrorStyle = ExcelDataValidationWarningStyle.stop;\n        paretnCodeValidation.ErrorTitle = "An invalid value was entered";\n        paretnCodeValidation.Error = "Parent must be between 1 and 50 digits in length";\n        paretnCodeValidation.Formula.Value = 1;\n        paretnCodeValidation.Formula2.Value = 50;	0
4142311	4142284	Check the number of rows updated	cmd.ExecuteNonQuery()	0
9624867	9622530	Migradoc Image in paragraph line	Paragraph paragraph = section.AddParagraph("Some text ...");\nparagraph.Format.RightIndent = "6cm";	0
5539332	5539001	using ninject with a remoting server	public class ServiceFacade : IService\n{\n    private readonly IService service;\n\n    // default constructor\n    public ServiceFacade()\n    {\n        this.service = YourContainer.Current.Resolve<IService>();\n    }\n\n    void IService.ServiceOperation()\n    {\n        this.service.ServiceOperation();\n    }\n}	0
10779775	10779661	Pre-select checkBox from database fields in asp.net using c#	if (chkBoxDaysList.Items[j].Value == s[i])\n        {\n            chkBoxDaysList.Items[j].Selected = true;\n            break;\n        }	0
6514236	6514198	how to know the id of server control inside the ItemTemplate of a GridView?	Dim tempRow As System.Web.UI.WebControls.GridViewRow\n    Dim tempLabel As Label\n    Dim tempHyperlink As HyperLink\n\n    For Each tempRow In GridView1.Rows\n        tempLabel = CType(tempRow.FindControl("Label1"), Label)\n        tempHyperlink = CType(tempRow.FindControl("FixHyperLink"), HyperLink)\n        If tempLabel.Text.Trim <> String.Empty Then\n            tempHyperlink.Visible = True\n        Else\n            tempHyperlink.Visible = False\n        End If\n    Next	0
7735832	7735781	Regular Expression to validate Data	bool isValid = Regex.IsMatch("YourInput", @"^\d{8}$");	0
11896643	11896381	Forms - How to POST default field values in C#	document.getElementByTagname('form').submit();	0
15460285	15459924	Write a set of characters to serial port in c#	String stringToSend = "123456";\n        serialPort1.Write(stringToSend.ToCharArray(), 0, stringToSend.Length);	0
24552711	24552399	BackgroundWorker with ProgressBar - Cross-thread operation not valid	private delegate void ToDoDelegate();\n    void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n    {\n        Invoke(new ToDoDelegate(() => progressBar1.Visible = false));\n    }	0
653535	653512	Internal interfaces - exposing my ignorance	public interface IEditActions\n{\n  void Action_Commit() {}\n  void Action_Undo() {}\n}\n\npublic interface IStateMachine\n{\n  void Initialize(IEditActions editActions);\n}\n\npublic class EditField : IEditField\n{\n  private class EditActions : IEditActions\n  {\n    EditField _editField;\n\n    public EditActions(EditField editField)\n    {\n      _editField = editField;\n    }\n\n    public void Action_Commit()\n    {\n      _editField.Action_Commit();\n    }\n    public void Action_Undo()\n    {\n      _editField.Action_Undo();\n    }\n  }\n\n  public EditField() {}\n  public EditField(IStateMachine stateMachine)\n  {\n    stateMachine.Initialize(new EditActions(this));\n  }\n\n  private void Action_Commit() {}\n  private void Action_Undo() {}\n}	0
9907337	9907264	Run outputType library project	In order to fix the above error, right click the Solution name in Visual \nStudio 2005/2008 and select Set as StartUp Project option from the popup menu.	0
4108392	2150621	How to create a soap client without WSDL	// Takes an input of the SOAP service URL (url) and the XML to be sent to the\n// service (xml).  \npublic void PostXml(string url, string xml) \n{\n    byte[] bytes = Encoding.UTF8.GetBytes(xml);\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n    request.Method = "POST";\n    request.ContentLength = bytes.Length;\n    request.ContentType = "text/xml";\n\n    using (Stream requestStream = request.GetRequestStream())\n    {\n       requestStream.Write(bytes, 0, bytes.Length);\n    }\n\n    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n    {\n        if (response.StatusCode != HttpStatusCode.OK)\n        {\n            string message = String.Format("POST failed with HTTP {0}", \n                                           response.StatusCode);\n            throw new ApplicationException(message);\n        }\n    }\n}	0
10804069	10804002	Trying to get a list distinct values count per column in the same result column	var result = dt.Columns\n    .Cast<DataColumn>()\n    .Select(dc => new {\n        Name = dc.ColumnName,\n        Values = dt.Rows\n            .Cast<DataRow>()\n            .Select(row => row[dc])\n            .Distinct()\n            .Count()})\n    .OrderBy(item => item.Values);	0
26854513	26854318	Assign parent and children to Node	// Added to Node class:\npublic int GetDepthRecursive()\n{\n    return Parent == null ? 0 : (Parent.GetDepthRecursive() + 1);\n}\n\n// To parse the text file into a node tree:\nNode rootNode = new Node { Number = 0 }; // You need a node for all those zero nodes to hang off\nNode currentNode = rootNode;\nforeach (var row in rows)\n{\n    rowDepth = row.StartingSpaces.Count(); // Use any method you want to count these spaces\n    var rowNode = new Node { Number = int.Parse(row) };\n\n    // The new row node is at the same or lower depth than us\n    // Go back up the tree to find the right parent for it\n    while (currentNode.GetDepthRecursive() > rowDepth)\n    {\n        currentNode = currentNode.Parent;\n    }\n\n    rowNode.Parent = currentNode;\n    currentNode = rowNode;\n}	0
1499690	1499655	What is the most efficient way in C# to determine if a string starts with a number and then get all following numbers up until the first non-numeric character?	public int GetLeadingNumber(string input)\n{\n    char[] chars = input.ToCharArray();\n    int lastValid = -1;\n\n    for(int i = 0; i < chars.Length; i++)\n    {\n        if(Char.IsDigit(chars[i]))\n        {\n            lastValid = i;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    if(lastValid >= 0)\n    {\n        return int.Parse(new string(chars, 0, lastValid + 1));\n    }\n    else\n    {\n        return -1;\n    }\n}	0
19659569	19659352	How I create a linq to xml query for binding xml to DropDownList with my structure?	var x = XDocument.Load(@"~\App_Data\DropDown\Title.xml");\nvar list = x.Descendants("values")\n    .Where(el => el.Attribute("id").Value == "de")\n    .Descendants("value")\n    .Select(el => new\n    {\n        value = el.Attribute("value").Value,\n        display = el.Attribute("display").Value\n    )\n    .ToList();\n\ndrp_GuestListViewAddDialog_GuestTitle.DataValueField = "value";\ndrp_GuestListViewAddDialog_GuestTitle.DataTextField = "display";\ndrp_GuestListViewAddDialog_GuestTitle.DataSource = list;\ndrp_GuestListViewAddDialog_GuestTitle.DataBind();	0
21663652	21663478	Returning a value from textbox in a class	t = new TicketUser();\nt.firstName=txtfirstName.Text;\nt.lastName=txtlastName.Text;\nt.userName=txtUsername.Text;	0
20410100	20409872	Change text color of cells in Account column (C# datagridview)	this.dataGridView1.Columns["Account"].DefaultCellStyle.ForeColor = Color.Blue;	0
15392511	15392438	32 bit winform application doesn't run on 64 bit OS	/platform:x86	0
12689959	12689877	ASCIIEncoding and Lower Control Characters	string newStr = "";\nforeach (char c in MyString) {\n    if ((int.Parse(c) < 32)) {\n        c = "?";\n    }\n    newStr = (newStr + c.ToString);\n}	0
8947732	8947481	How to convert dictionary with object to list of that type?	List<Items> items = statsCont.OrderByDescending(x => x.Value.NumberOfItems)\n    .Take(10)\n    .Select(x => x.Value)\n    .ToList();	0
9500863	9500563	Transparent window application to overlay in Windows	[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]\n   public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);\n\n   private const int MOUSEEVENTF_LEFTDOWN = 0x02;\n   private const int MOUSEEVENTF_LEFTUP = 0x04;\n   private const int MOUSEEVENTF_RIGHTDOWN = 0x08;\n   private const int MOUSEEVENTF_RIGHTUP = 0x10;\n\nprivate void Form_MouseClick(object sender, MouseEventArgs e)\n{\n   this.Hide();\n   Point p = this.PointToScreen(e.Location);\n   mouse_event(MOUSEEVENTF_LEFTDOWN , p.X, p.Y, 0, 0);\n   mouse_event(MOUSEEVENTF_LEFTUP, p.X, p.Y, 0, 0);\n   this.Show();//since this.opacity = 0; form will never be really visible\n}	0
14987491	14987431	Capslock ON & OFF with Application	AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnExit);\n\npublic void OnExit(object sender, EventArgs e)\n{\n    // check and turn caps off if neccessary\n}	0
13072849	13072797	Read data from database and display it in a txt file	using (SqlConnection conn = new SqlConnection(connectionString))\n{\n    SqlCommand com = new SqlCommand("Select * from mytable", conn);\n    DataReader reader = com.ExecuteReader();\n\n    using (TextWriter writer = new TextWriter("myFile.txt"))\n    {\n        while (reader.Read())\n        {\n            StringBuilder myData = new StringBuilder();\n            myData.Append(reader["Fname"].ToString();\n            //etc - see how you want to format it\n\n            writer.WriteLine(myData.ToString());\n        }\n    }\n}	0
32802140	32802102	model passed into dictionary is of type A but required of type B	public async Task<ActionResult> Register(RegisterViewModelForm model)	0
12287757	12287586	C# Connecting two tcp sockets together	public class ByPass\n{\n    public ByPass(Stream s1, Stream s2)\n    {\n\n        Task.Factory.StartNew(() => Process(s1, s2));\n        Task.Factory.StartNew(() => Process(s2, s1));\n    }\n\n    public void Process(Stream sIn, Stream sOut)\n    {\n        byte[] buf = new byte[0x10000];\n        while (true)\n        {\n            int len = sIn.Read(buf, 0, buf.Length);\n            sOut.Write(buf, 0, len);\n        }\n    }\n}	0
582769	582669	C# Make one picture using various pictures	Bitmap bitmap = new Bitmap(totalWidthOfAllImages, totalHeightOfAllImages);\nusing(Graphics g = Graphics.FromBitmap(bitmap))\n{\n    foreach(Bitmap b in myBitmaps)\n        g.DrawImage(/* do positioning stuff based on image position */)\n}\n\npictureBox1.Image = bitmap;	0
28081332	28081011	C# Split namevaluepair string with delimitter in values using regex	var data = "FirstName=John, LastName=Smith, Address:1 Wall Street, NY, USA, TestKey=TestValue";\nvar dic = new Dictionary<string, string>();\nvar reg = @"([^=:,]*)[=:](.*?)(?:$|,\s*(?=[^=:,]*[=:]))";\nforeach (Match m in Regex.Matches(data, reg)) {\n    var key = m.Groups[1].Value;\n    var val = m.Groups[2].Value;\n    dic[key] = val;\n    Console.WriteLine("{0} = {1}", key, val);\n}	0
19509565	19504758	ASP MenuItem OnMenuItemClick not firing without Text/Value on MenuItem	_sub_menu = new MenuItem();\n//_sub_menu.NavigateUrl = "";\n_sub_menu.ImageUrl = "~/_image/release.png";\n_sub_menu.ToolTip = "Release User";\n_sub_menu.Value = " "; //or another dummy value\nSecureMenu.Items.Add(_sub_menu);	0
11831699	11831365	Creating namespace for XML element	xmlDoc.CreateElementNS("using:Dictionary.Common", "local2:elementName")	0
17059637	17044533	Simple.Mocking, how to expect any IEnumerable as parameter?	Any<IEnumerable<MyModel>>.Value.AsInterface	0
7002991	7002869	Adding and Couting items in a list	List<string> items = new List<string>{"128590", "128590", "128588", "128587", "128587", "128590"};\n    Dictionary<string,int> result = new Dictionary<string,int>();\n\n    foreach( int item in items )\n    {\n        if(result.ContainsKey(item) )\n            result[item]++;\n        else\n            result.Add(item,1);\n    }\n\n    foreach( var item in result )\n        Console.Out.WriteLine( item.Key + ":" + item.Value );	0
17914389	17914372	Get value from string in IEnumerable	var param = "Boy";\nvar someBoy = GetAll().Where(g => g.Description == param).Select(g => g.Value).Single();	0
6755467	6755222	Programmatically setting startin location when starting a process	//System.Diagnostics.Process.Start("C:\\Program Files (x86)\\MyPDFConvertor\\MyPDFConvertor.exe", "C:\\MyFiles\\This is a test word document.docx");\nProcessStartInfo start = new ProcessStartInfo();\n//must exist, and be fully qualified:\nstart.FileName = Path.GetFullPath("C:\\Program Files (x86)\\MyPDFConvertor\\MyPDFConvertor.exe");\n//set working directory:\nstart.WorkingDirectory = Path.GetFullPath("C:\Program Files (x86)\MyPDFConvertor\SomeSubfolder\SomeSubSubFolder");\n//arguments must be quoted:\nconst char quote = '"';\nstart.Arguments = quote + "C:\\MyFiles\\This is a test word document.docx" + quote;\n//disable the error dialog\nstart.ErrorDialog = false;\ntry\n{\n    Process process = Process.Start(start);\n    if(process == null)\n    {//started but we don't have access\n\n    }\n    else\n    {\n        process.WaitForExit();\n        int exitCode = process.ExitCode;\n    }\n}\ncatch\n{\n    Console.WriteLine("failed to start the program.");\n}	0
19353078	19352956	YYYY/MM/DD date format regular expression	\d{4}(?:/\d{1,2}){2}	0
26300799	26300673	Set value to [Flags] Enum from list c#	var result = values.Aggregate((x, y) => x |= y);	0
15389652	15389521	Match start of line return text after match	new Regex(@"(?<=Last name:).*");	0
18784351	18784327	Reading an array from an array	var sourceArray = object[50];\nvar newArray = object[10];\n// Copy 10 elements, starting at index 12, to newArray (starting at index 0)\nArray.Copy(sourceArray, 12, newArray, 0, 10);	0
3518554	3518508	Recursively traversing a tree in C# from top down by row	public Node FindFirstByBreadthFirst(this Node node, Predicate<Node> match)\n{\n    var queue = new Queue<Node>();\n    queue.Enqueue(tree.RootNode);\n\n    while (queue.Count > 0)\n    {\n        // Take the next node from the front of the queue\n        var node = queue.Dequeue();\n\n        // Process the node 'node'\n        if (match(node))\n            return node;\n\n        // Add the node?s children to the back of the queue\n        foreach (var child in node.Children)\n            queue.Enqueue(child);\n    }\n\n    // None of the nodes matched the specified predicate.\n    return null;\n}	0
27290632	27290044	NullReferenceException loading RenderWindowControl for vtk in WPF	public VtkTabView()\n{\n    InitializeComponent();\n    // initialize your sphrere and actor\n\n    RenderControl.Load += MyRenderWindowControlOnLoad;\n}\n\nprivate void MyRenderWindowControlOnLoad(object sender_in, EventArgs eventArgs_in){\n\n//access the RenderWindow here\n\n}	0
30686180	30686073	Creating class objects using LINQ with a highly nested XML	String xData = System.IO.File.ReadAllText(@"C:\Temp\MyFile.xml");\n        XmlSerializer x = new XmlSerializer(typeof(root));\n        root dataConverted = (root)x.Deserialize(new StringReader(xData));\n        // root object contains all XML data.	0
28530860	28530634	How do I modify a XML Node?	foreach( XmlNode xn in xmlDoc.SelectNodes("//Tasks"))\n{\n    // Do something\n}	0
840177	840120	Timespan formatting	TimeSpan ts = new TimeSpan(0, 70, 0);\nString.Format("{0} hour{1} {2} minute{3}", \n              ts.Hours, \n              ts.Hours == 1 ? "" : "s",\n              ts.Minutes, \n              ts.Minutes == 1 ? "" : "s")	0
6015147	6015131	Substring value retrieved from database in .NET / C#	while (reader.Read()) \n        {\n            string body = reader["body"] is DBNull ? "" : Convert.ToString(reader["body"]);\n\n            if(body.Length > 20)\n              body = body .Substring(0, 20);\n\n            newsLabel.Text += "<div style='float:left;'>" + body  + "</div>";   \n        }	0
7631073	7630394	How to switch first letters in each word of RichTextBox.Text to upper case?	string[] str = richTextBox1.Text.Split(' ');\nstring a="";\nstring b="";\nfor (int i = 0; i < str.Length; i++)\n{\n    if (str.GetValue(i).ToString().Length > 2)\n    {\n        b = str.GetValue(i).ToString().Replace(str.GetValue(i).ToString().Substring(0, 1),   str.GetValue(i).ToString().Substring(0, 1).ToUpper());\n    }\n    else\n    {\n        b = str.GetValue(i).ToString();\n    }\n    a = a + " " + b;              \n}\nrichTextBox1.Text = a;	0
6804811	6804794	C# The simplest way to obtain XML Data	XDocument doc = XDocument.Load("test.xml");\nforeach (var delimiter in doc.Descendants("Delimiters").Elements())\n    Console.WriteLine(string.Format("{0} : {1}", delimiter.Name, delimiter.Value));\n\nforeach (var type in doc.Descendants("SourceType").Elements())\n    Console.WriteLine(string.Format("{0} : {1}", type.Name, type.Value));	0
5998030	5997916	Custom Column Headers in Data Grid View C# from ArrayList	List<T>	0
19975801	19975501	Simple form post always sends null to controller	[HttpPost]\npublic ActionResult NewPlaces(EnrolleePlaces dd) // any name other than "places"\n{\n       if (ModelState.IsValid)\n       {\n           repo.SaveEnrolleePlaces(places);\n           return RedirectToAction("Settings");\n       }\n       return View("EditPlaces", places);\n}	0
3623805	1338933	How do I find the absolute path of a controller action?	public static string AbsoluteAction(this UrlHelper url, string action, string controller, object routeValues)\n{\n    Uri requestUrl = url.RequestContext.HttpContext.Request.Url;\n\n    string absoluteAction = string.Format("{0}://{1}{2}",\n                                          requestUrl.Scheme,\n                                          requestUrl.Authority,\n                                          url.Action(action, controller, routeValues, null));\n    return absoluteAction;\n}	0
24556794	24556506	Looking for a Post-Constructor Event of a Control	protected override void InitLayout()\n{\n    // do something here\n    base.InitLayout();\n}	0
20468549	20468355	Fluent NHibernate Insert to table with int Identity	Table("[User]");	0
364154	364141	Database Constants in a Class	public enum FilmType {\n   Horror = 1,\n   Comedy = 2\n}	0
5148304	5097913	GET ALL Skype Friends using skype APIs With C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing SKYPE4COMLib;\n\nnamespace Example\n{\n    class SkypeExample\n    {\n        static void Main(string[] args)\n        {\n            SkypeClass _skype = new SkypeClass();\n            _skype.Attach(7, false);\n\n            IEnumerable<SKYPE4COMLib.User> users = _skype.Friends.OfType<SKYPE4COMLib.User>();\n\n            users\n                .Where(u => u.OnlineStatus == TOnlineStatus.olsOnline)\n                .OrderBy(u => u.FullName)\n                .ToList()\n                .ForEach(u => Console.WriteLine("'{0}' is an online friend.", u.FullName));\n\n            Console.ReadKey();\n        }\n    }\n}	0
1750522	1750263	Is it possible to constrain a generic parameter to be a subtype of the current object?	abstract class Animal\n{\n    public void Mate<T>(T t) where T : this { ... CENSORED ... }\n}\n...\nAnimal x1 = new Giraffe(); \nMammal x2 = new Tiger();\nx1.Mate<Mammal>(x2);	0
13092336	13092299	Email a graph generated with ASP	var chart = new Chart\n{\n    Height = 300,\n    Width = 500\n};\nchart.Legends.Add(new Legend());\nchart.Series.Add(new Series());\nchart.ChartAreas.Add(new ChartArea());\nchart.Titles.Add(new Title());\nchart.SaveImage(savePath);	0
4429374	4429354	How to edit Windows Forms controls from different threads	tab1text.Invoke(new Action(delegate(){ tab1text.Text = inputLine }));	0
6602069	6592573	How to capture screen to be video using C# .Net?	private void CaptureMoni()\n        {\n\n            try\n            {\n                Rectangle _screenRectangle = Screen.PrimaryScreen.Bounds;\n                _screenCaptureJob = new ScreenCaptureJob();\n                _screenCaptureJob.CaptureRectangle = _screenRectangle;\n                _screenCaptureJob.ShowFlashingBoundary = true;\n                _screenCaptureJob.ScreenCaptureVideoProfile.FrameRate = 20;\n                _screenCaptureJob.CaptureMouseCursor = true;\n\n                _screenCaptureJob.OutputScreenCaptureFileName = string.Format(@"C:\test.wmv");\n                if (File.Exists(_screenCaptureJob.OutputScreenCaptureFileName))\n                {\n                    File.Delete(_screenCaptureJob.OutputScreenCaptureFileName);\n                }\n                _screenCaptureJob.Start();\n            }\n            catch(Exception e) { }\n        }	0
18955298	18454457	Distribute application without installing CrystalReports	setup.exe	0
13355930	13355723	Convert each row of matrix( float) in to a vector	static float[][] ToVectors(float[,] matrix)\n    {\n\n        var array = new float[matrix.GetLength(0)][];\n\n        for (int i = 0; i < array.Length; i++)\n        {\n            array[i]=new float[matrix.GetLength(1)];\n            Buffer.BlockCopy(matrix, i * matrix.GetLength(1), array[i], 0, matrix.GetLength(1) * sizeof(float));\n        }\n\n\n        return array;\n\n    }	0
3598321	3597428	Do in-memory objects limited to user/session scope need to be thread-safe?	Session[User.ID]	0
29531792	29531632	How can I compare date of two rows	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n        {\n\n            //Checking the RowType of the Row  \n            if (e.Row.RowType == DataControlRowType.DataRow)\n            {\n                DateTime firstDateValue = Convert.ToDateTime(e.Row.Cells[1].Text);\n                DateTime secondDateValue = Convert.ToDateTime(e.Row.Cells[2].Text);\n\n                 TimeSpan timespan = secondDateValue - firstDateValue; \n\n                if (timespan.Hours > 2)\n                {\n                    e.Row.BackColor = Color.Cyan;\n                }\n            }\n        }	0
3261325	3261307	How to add MenuItems when MDI children are merging their menus	menuWindow = (MenuItem)sender;\n        if (dockPanel.ActiveDocument != null)\n        {\n            foreach (MenuItem item in ((Form)dockPanel.ActiveDocument).MergedMenu.MenuItems)\n            {\n                if (item.Text == "&Window")\n                {\n                    menuWindow = item;\n                }\n            }\n        }	0
5683968	5682012	Listbox events firing strangely	private void listBox1_MouseMove(object sender, MouseEventArgs e)\n{\n\n    if (e.X > listBox1.Width - 1 || e.Y > listBox1.Height - 1 || e.X < 0 || e.Y < 0) \n    {\n        Console.WriteLine("drag out");\n    }\n    else\n        Console.WriteLine("mouse move {0}/{1}", e.X, e.Y);\n}	0
28010533	28010505	Apply style to radio button	radioButton1.CheckAlign = ContentAlignment.BottomCenter;\nradioButton1.TextAlign = ContentAlignment.TopCenter;	0
1298173	1298126	Is it possible to add system time in Windows NumericUpDown Button control?	DateTimePicker dateTimePicker1 = new DateTimePicker();\ndateTimePicker1.Format = DateTimePickerFormat.Time;\ndateTimePicker1.ShowUpDown = true;\ndateTimePicker1.Value = DateTime.Now;	0
4895307	4895199	How can I find the visible columns of a list in Sharepoint?	SPList l = SPContext.Current.Web.Lists[new Guid(ddl_Lists.SelectedValue)];\n        List<string> visFields = new List<string>();\n        foreach (SPField field in l.Fields)\n        {\n            if (!field.Hidden)\n            {\n                visFields.Add(field.Title);\n            }\n        }	0
13095665	13095557	Given two sets of numbers, find the smallest set from each where the sum is equal	var result = (from a in seta.Subsets()\n               from b in setb.Subsets()\n               where a.Count() > 0 && b.Count() > 0\n               where a.Sum() == b.Sum()\n               orderby a.Count() + b.Count()\n               select new MagicResult { SetA = a.ToArray(), SetB = b.ToArray() }\n              ).First();	0
781733	780545	How to Raise Event from ActiveX control	public EventHandler<EventArgs> Button1Clicked;\nprivate void button1_Click(object sender, EventArgs e)\n{\n    if (this.Button1Clicked != null)\n    {\n        this.Button1Clicked(sender, e);\n    }\n}	0
12121932	12121750	how to seek position in datatable before writing to the file	const char special = '\\';\n\nstring maintype ="";\nstring subtype ="";\n\nstring field = dRow[i].ToString();\nif (field.IndexOf(special)>-1)\n{\n  string[] splitted = field.Split(special);\n  maintype = splitted[0];\n  subtype = splitted[1];\n}	0
17434156	17434119	How to get frequency of elements from List in c#	using System.Linq;\n\nList<int> ids = //\n\nforeach(var grp in ids.GroupBy(i => i))\n{\n    Console.WriteLine("{0} : {1}", grp.Key, grp.Count());\n}	0
2879061	2879033	How do you draw a line on a canvas in WPF that is 1 pixel thick	myLine.SnapsToDevicePixels = true;\nmyLine.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);	0
28200732	28200318	Searching a static array on Multiple Indexes C#	IEnumerable<rlsSoftwareVersions> result = rlsSoftwareVersions.Where(item => item.dReleaseNumber == 4.0);\n\nforeach(var rlsSoftwareVersion in result)\n{\n    // do something\n}	0
5393154	5392821	c# gridview with lightbox	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n   if (e.Row.RowType == DataControlRowType.DataRow)\n   {\n      HyperLink hpl = (HyperLink)e.Row.Cells[0].FindControl("hyplink");\n      hpl.Attributes.Add("rel", "insert");\n      LinkButton lkb = (LinkButton)e.Row.Cells[0].FindControl("link");\n      lkb.Attributes.Add("rel", "insert");\n   }\n}	0
28242485	28241904	lambda and linq expression	var items = db.Missions.Where(m => m.CriteriaList\n                                    .Any(c => CriteriaSelected.Contains(c.CriteriaID )));	0
9000201	8999462	How to add effects to image	public List<Rectangle> detect(Bitmap inputImage)\n        {\n            inImage = new Image<Bgr, byte>(inputImage);\n            grayImage = inImage.Convert<Gray, Byte>();\n\n            List<Rectangle> faceRects = new List<Rectangle>();\n\n            var faces = grayImage.DetectHaarCascade(haar, 1.1, 1, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(inImage.Width, inImage.Height))[0];\n\n            grayImage.Dispose();\n\n            foreach (var face in faces)\n            {\n                faceRects.Add(face.rect);                \n            }\n\n            inImage.Dispose();\n            return faceRects;\n        }	0
13030501	12266367	Save Extra Infromation after editing DataGrid	Class TaskViewModel\n{\n    private Task task;\n    public Boolean IsScheduled\n    {\n        get\n        {\n            return task.IsScheduled;\n        }\n        set\n        {\n            this.task.IsScheduled = value;\n            this.task.IsScheduledDate = Date.Now();\n        }\n\n    TaskViewModel(Task task)\n    {\n       this.task = task;\n    }\n}	0
9923322	9906234	Socket accepts Multiple Clients, but i'm unable able to open the file	using System;\nusing System.IO;\nusing System.Net.Sockets;\nusing System.Text;\n\nnamespace AClient\n{\n    class Client\n    {\n        static void Main()\n        {\n            using (var client = new TcpClient("localhost", 8888))\n            {\n                Console.WriteLine(">> Client Started");\n\n                using (var r = new StreamReader(@"E:\input.txt", Encoding.UTF8))\n                using (var w = new StreamWriter(client.GetStream(), Encoding.UTF8))\n                {\n                    string line;\n                    while (null != (line = r.ReadLine()))\n                    {\n                        w.WriteLine(line);\n                        w.Flush(); // probably not necessary, but I'm too lazy to find the docs\n                    }\n                }\n\n                Console.WriteLine(">> Goodbye");\n            }\n        }\n    }\n}	0
20670435	20670151	Writing to a struct to a text file using StreamWriter	static void AddNew(CustomerStruct[] _NewCustomer)\n{\nConsole.Clear();\n\nusing (StreamWriter sw = new StreamWriter(@"..\..\..\Files\Customer.txt", true))\n{\n    Console.Write("\n\n Enter Customer Number: ");\n    sw.WriteLine(_NewCustomer[RecCount].CustomerNo=Console.ReadLine());\n\n    Console.Write("\n\n Enter Customer Surname: ");\n    sw.WriteLine(_NewCustomer[RecCount].Surname=Console.ReadLine());\n\n    Console.Write("\n\n Enter Customer Forname: ");\n    sw.WriteLine(_NewCustomer[RecCount].Forename=Console.ReadLine());\n\n    Console.Write("\n\n Enter Customer Street address: ");\n    sw.WriteLine(_NewCustomer[RecCount].Street=Console.ReadLine());\n\n    Console.Write("\n\n Enter Customer Town: ");\n    sw.WriteLine(_NewCustomer[RecCount].Town=Console.ReadLine());\n\n    Console.Write("\n\n Enter Customer DOB: ");\n    sw.WriteLine(_NewCustomer[RecCount].DOB=Console.ReadLine());\n\n    RecCount++;\n}\n\nConsole.ReadLine();\n}	0
19718596	19666257	How to compile MethodCallExpression without DynamicInvoke?	var date = DateTime.UtcNow.AddDays(-10);\nvar actualExpression = TestExpression<UserModel>( u => u.CreatedDate == date );	0
9250822	9249725	how to position camera in XNA 10 units away but not from behind?	cameraPosition = objectPosition +\n                 object.Backward * 10 +\n                 object.Up * 5;\n\ncameraTarget = objectPosition +\n               object.Up * 3;	0
9025319	9024342	How to make the process of scanning TCP ports faster?	using (var tcp = new TcpClient())\n{\n    var ar = tcp.BeginConnect(host, port, null, null);\n    using (ar.AsyncWaitHandle)\n    {\n        //Wait 2 seconds for connection.\n        if (ar.AsyncWaitHandle.WaitOne(2000, false))\n        {\n            try\n            {\n                tcp.EndConnect(ar);\n                //Connect was successful.\n            }\n            catch\n            {\n                //EndConnect threw an exception.\n                //Most likely means the server refused the connection.\n            }\n        }\n        else\n        {\n            //Connection timed out.\n        }\n    }\n}	0
19397252	19390198	Is there a breaking change in Spring AOP 1.3.2	Application.Logic.ActivityMonitorBlo	0
29180450	29180415	How i can split comma separated string in a group using LINQ	var quantity = 3; \n\nyourList.Select((x, i) => new { Index = i, Value = x })\n        .GroupBy(x => x.Index / quantity )\n        .Select(x => x.Select(v => v.Value).ToList())\n        .ToList();	0
22486521	22486184	How can I get output results from my Queue<T> in C#?	private Bitmap RandomImageSelection()\n{\n    Bitmap image = null;\n\n    if (randomGenerator.Next(2) == 0 && !line1.TryDequeue(out image))\n    {\n        line2.TryDequeue(out image)\n    }\n\n    if (image != null) \n    {\n        pictureBox3.Invoke(new Action(() => pictureBox3.Image = image));\n    }\n\n    return image;\n}	0
6485168	6485156	Adding strings to a RichTextBox in C#	richTextBox2.AppendText(Environment.NewLine + DateTime.Today + " Hello");	0
6586561	6586269	If I have a reference to a button how can I programatically fire the click event?	if (button is Button)\n{\n    ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);\n\n    IInvokeProvider ip = (IInvokeProvider)peer;\n    ip.Invoke();\n}	0
5018735	5017651	Custom Control ClientRectangle	....\nswitch (m.Msg)\n{\n    case WM_NCCALCSIZE:\n        if (m.WParam != IntPtr.Zero)\n        {\n            NCCALCSIZE_PARAMS csp;\n\n....	0
9195815	9195727	Removing elements from binding list	var itemToRemove = UserList.Where(x => x.id == ID).ToList();\nforeach (var item in itemToRemove)\n{\n  UserList.Remove(item);\n}	0
16417581	16417543	Sort a List<T> by one of T's property	List<yourType> yourCollection = YourSourceList.OrderBy(e=>e.YourProperty).ToList();	0
26998054	26997744	Add data to a TextBox from a DropDownList in a DetailsView field	protected void  DetailsView1_ItemCommand(object sender, System.Web.UI.WebControls.DetailsViewCommandEventArgs e) \n{ \n    if (e.CommandName == "Update") { \n        DropDownList yourddl = DetailsView1.FindControl("yourdropdownlist"); \n        if (yourddl.SelectedIndex > 0) { \n            var tbox = DetailsView1.FindControl("yourtextbox");\n            tbox.text = Now().ToString; \n        } \n    } \n}	0
7241482	7241443	White Page Bug with ASP.Net and Datasource	Response.Write("Test");	0
19505707	19505557	Meta tag from c# linq to xml display &lt;	XElement contact = (from xml2 in XMLDoc.Descendants("Keywords")\n                    where xml2.Element("ID").Value == id\n                    select xml2).FirstOrDefault();\n\nHtmlMeta meta = new HtmlMeta();\nmeta.Name = "keywords";\nmeta.Content = contact.Attribute("name").Value;	0
8005851	8005632	textbox custom validation	public bool ValidateMail(string mailAdress)\n{\n    if (String.IsNullOrEmpty(mailAdress))\n    {\n        ShowError("please enter email id!!");\n        return false;\n    }\n    //The regular expression matches at:\n    //[anything]-@-[anything except "."]-.-[2 or 3 chars after the "."]\n    else if (!Regex.Match(mailAdress, @".+\@[^\.]+\..{2,3}")\n                            .Length == mailAdress.Length)\n    {\n        ShowError("please enter correct email id!");\n        return false;\n    }\n    return true\n}	0
5945758	5913712	Determining normal/exceptional exit from a using block in .net	public void Dispose(){\n    if(Marshal.GetExceptionCode()==0){\n        // disposing normally\n        Commit();\n    }else{\n        // disposing because of exception.\n        Rollback();\n    }\n}	0
20088408	20088241	Efficient way to perform calculation	List<decimal> data =....\ndecimal multiplier = 1.0;\nfor (var i = 0; i < data.Count; i++)\n{\n   var oldMultipleir = multiplier;\n   multiplier *= (1 - data[i]);\n   data[i] *= oldMultiplier;\n}	0
9075560	9075354	Legacy ASMX webservice - How to use automagically generated async method	protected void Button1_Click\n(object sender, EventArgs e)\n{\n     BookSupplier1.WebService1 supplier1 = new BookSupplier1.WebService1();\n\n     supplier1.GetCostCompleted += new BookSupplier1.GetCostCompletedEventHandler(supplier1_GetCostCompleted);\n\n     supplier1.GetCostAsync(TextBox1.Text, BulletedList1);\n\n}\n\n\nvoid supplier1_GetCostCompleted(object sender, BookSupplier1.GetCostCompletedEventArgs e)\n{\n     if (e.Error != null)\n     {\n         throw e.Error;\n     }\n     BulletedList list = (BulletedList)e.UserState;\n     list.Items.Add("Quote from BookSupplier1 : " + e.Result.ToString("C"));\n}	0
4871134	4871005	How can I split a word from within brackets using the Split method in C#?	string justWord = "(animal)".Replace("(","").Replace(")","")	0
30764204	30764171	Remove last string from the output of my loop	for (int i = 1; i < 6; i++)\n{\n    Console.Write(i + (i != 5 ? " potato " : string.Empty));\n}	0
22591948	22591777	Code to open application based on other processes	cd "C:\\path\to\your\app"\nstart /min yourapp.exe\ncd "C:\\path\to\notepad"\nstart notepad.exe	0
4645964	4645880	HTML Agility Pack - Can only load xml document from file system, not from web	String PostUrl = "http://www.web.com/doc.xml"; \nWebResponse webResponse = WebRequest.Create(PostUrl).GetResponse();\nStreamReader sr = new StreamReader(webResponse.GetResponseStream());\n\nString Result = sr.ReadToEnd().Trim();\n\nXmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(Result);	0
26336839	26336536	Generic objects managed automatically by a ListBox control?	public class ListBoxItem<T>\n{\n    private Func<T, string> _getText;\n\n    public T Item { get; private set; }\n\n    public ListBoxItem<T>(T item, Func<T, string> getText)\n    {\n        Item = item;\n        _getText = getText;\n    }\n\n    public override string ToString()\n    {\n        return _getText(Item);\n    }\n}	0
24471328	24466936	How do you Automatically open(play) file after it is saved to isolation storage? WP8	using (IsolatedStorageFileStream fileStream =  IsolatedStorageFile.GetUserStoreForApplication).CreateFile(data.SavePath))                     \n{                         \nargs.Result.Seek(0, SeekOrigin.Begin);\nargs.Result.CopyTo(fileStream);\nAudioPlayer.SetSource(fileStream); \nAudioPlayer.Play();	0
8657538	8645224	Resetting message sequence numbers without reconnecting	ResetOnLogon=Y \nResetOnLogout=Y \nResetOnDisconnect=Y	0
32243292	32219400	Jumping forward within panels	panel8.Visibility = true;\npanel9.Visibility = true;\npanel10.Visibility = true;	0
26961149	26950253	Incomplete undo on local context with Entity Framework	switch (entry.State)\n        {\n            case EntityState.Modified:\n                entry.State = EntityState.Unchanged;\n                break;\n            case EntityState.Added:\n                entry.State = EntityState.Detached;\n                break;                    \n            case EntityState.Deleted:\n                entry.State = EntityState.Unchanged;\n                break;\n            default: break;\n        }	0
225027	224865	How do I get all installed fixed-width fonts?	foreach (FontFamily ff in System.Drawing.FontFamily.Families)\n{\n    if (ff.IsStyleAvailable(FontStyle.Regular))\n    {\n        Font font = new Font(ff, 10);\n        LOGFONT lf = new LOGFONT();\n        font.ToLogFont(lf);\n        if (lf.lfPitchAndFamily ^ 1)\n        {\n            do stuff here......\n        }\n    }\n}	0
7847711	7847559	SQL Server routine of inserting multiple rows after checking if they don't exist - how can i improve my perfomance?	-- Table "links" with column "url"\nMERGE links AS L\nUSING (SELECT url FROM links WHERE url = @url) AS I (url)\nON (L.url = I.url)\nWHEN NOT MATCHED THEN INSERT (url) VALUES (@url)	0
25292305	25292218	Generate Datatable with millions of records in C#	List<T>	0
18630803	18617628	Add UserControls on LayoutControl via Code	//Create a layout item and add it to the root group.    \nLayoutControlItem item1 = layoutControl.Root.AddItem();\n\nitem1.Name = "item1";\nctrlProgramm programm = new ctrlProgramm();\n\n// Set the item's Control and caption.    \nitem1.Control = programm;\nitem1.Text = "Program:";	0
27584034	27583968	How to add minutes to UTC time in C#	string currentTime = DateTime.UtcNow.AddMinutes(20).ToString("HH:mm:ss");	0
6113456	6111691	Assign value from ASP:DataSource query to variable in c#?	textbox1.Text = YourDBMethodThatReturnsSum();	0
14750788	14749868	How to get folder by path in multiple Accounts Outlook c#	OutLook.Application oApp = new OutLook.Application();\n        OutLook.NameSpace oNS = (OutLook.NameSpace)oApp.GetNamespace("MAPI");\n        oNS.Logon(Missing.Value, Missing.Value, false, true);\n\n        foreach (OutLook.MAPIFolder folder in oNS.Folders)\n        {\n            string folderName = folder.Name;\n\n            GetFolders(folder);\n\n        }\n\n\n\n   public void GetFolders(MAPIFolder folder)\n    {\n        if (folder.Folders.Count == 0)\n        {\n            string path = folder.FullFolderPath;\n\n\n            if (foldersTocheck.Contains(path))\n            { \n                //GET EMAILS.....\n                foreach (OutLook.MailItem item in folder.Items)\n                {\n                    Console.WriteLine(item.SenderEmailAddress + " " + item.Subject + "\n" + item.Body);\n\n\n                }\n            }\n        }\n        else\n        {\n            foreach (MAPIFolder subFolder in folder.Folders)\n            {\n                GetFolders(subFolder);\n            }\n        }\n    }	0
14351618	14351575	JSON multi-dimensional array/Dictionary in C# for MailChimp	data.Add("merge_vars", new Dictionary<string, string> { {"FNAME", firstname} });	0
3935565	3935514	Finding and extracting data from Excel	int contDateRow=0;\nint firstBlankRowAfterContDate=0;\n\nfor (int row=1;row<=woksheet.Rows.Count;++row)\n  if (worksheet.Cells[row,1].Value=="Cont Date")\n  {\n    contDateRow=row; \n    break;\n  }\n\nif (contDateRow!=0)\n{\n  for (int row=contDateRow;row<=woksheet.Rows.Count;++row)\n    if (worksheet.Cells[row,1].Value=="")\n    {\n      firstBlankRowAfterContDate=row; \n      break;\n    }\n}\n\n// Do something with contDateRow and firstBlankRowAfterContDate...	0
21025834	21025757	Transform a DataTable with a single column to a Dictionary where the index is the key	Dictionary<int, double> dict = dataTable.AsEnumerable()\n    .Select((row, index) => new { row, index })\n    .ToDictionary(x=> x.index + 1, x=> x.row.Field<double>(0));	0
1643246	1643235	String Assignment -Clarification	Console.WriteLine(string.IsNullOrEmpty(x));	0
29752249	29751884	Is there a 'Hot' equivalent of Observable.Interval	var published = Observable\n   .Interval(...)\n   .Select(...)\n   .Publish();\n\nvar connectionSubscription = published.Connect();\nvar observerSubscription = published.Subscribe(...);	0
4178781	4178770	Running a method with parameters in a thread in c#	new Thread(delegate () {\n    updateProgress(count, totalRows);\n}).Start();	0
29690613	29690461	How to delete a Registry key?	var hklm = Microsoft.Win32.Registry.LocalMachine;\nvar subkey = hklm.OpenSubKey("Software\\Wow6432Node\\WindowsApplication1", true);\nsubkey.DeleteSubKey("Status");	0
18732669	18729963	Binding controls dynamically to PlaceHolder in asp:DataList	Control ctrl = (Control)Page.LoadControl("MyControl.ascx"); \n        // MyControl ctrl = new MyControl();\n        ctrl.SomeProp = "xyz";\n        ph.Controls.Add(ctrl);	0
7856878	7856854	How to check if a date has passed in C#?	public bool HasPassed2hoursFrom(DateTime fromDate, DateTime expireDate) \n{\n    return expireDate - fromDate > TimeSpan.FromHours(2);\n}	0
15072200	15070627	Managing a Faux Tree in C#	List<TreeItem> orphanedItems = new List<TreeItem>();\nforeach (TreeItem item in results)\n{\n    if (item.ParentTreeItemID != Guid.Empty &&\n        !results.Any(tree => tree.ID == item.ParentTreeItemID)\n    {\n        orphanedItems.Add(item);\n    }\n}\nforeach (TreeItem orphan in orphanedItems)\n    results.Remove(orphan);	0
21848325	21847324	Sorting based on the keys in dictionary	Dictionary<string, string> d = dic.OrderBy(x => int.Parse(x.Key.Split('_')[0])).ThenBy(x => int.Parse(x.Key.Split('_')[1])).ToDictionary(j => j.Key, j => j.Value);	0
1865787	1855228	Getting DropDownList values in a repeater	Control parent = ((Control)sender).Parent;\nDropDownList GeneralDDL = (DropDownList)parent.FindControl("GeneralDDL");	0
9130077	9129860	Parsing Log using something else than string split c#	string myRegex = @"(?<=^(?:[^""]*""[^""]*"")*[^""]*),";\nstring[] outputArray = Regex.Split(myStr, myRegex);	0
25315692	25315520	Determine the number of threads that a method uses	public class MyThreadingClass\n{\n   int threadCount = 0;\n   public void DoLotsOfWork()\n   {\n      Task.Factory.StartNew(() => SomeMethod());\n   }\n   public void SomeMethod()\n   {\n      Interlocked.Increment(threadCount);\n      try\n      {\n         // Some Code\n      }\n      finally\n      {\n         Interlocked.Decrement(threadCount);\n      }\n   }\n}	0
27358614	27358434	Generate QRcode in a picturebox	// Generate QR-Code and encode barcode to gif format\nqrcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;\nqrcode.drawBarcode("C:\\qrcode.gif"); \n/*\nYou can also call other drawing methods to generate barcodes          \npublic void drawBarcode(Graphics graphics);\npublic void drawBarcode(string filename);    \npublic Bitmap drawBarcode();\npublic void drawBarcode(Stream stream);             \n*/	0
1367508	1367504	converting list<int> to int[]	list.ToArray()	0
24191029	24190651	Convert Hex string to Binary string C#	string value = "0x001";\nstring binary = Convert.ToString(Convert.ToInt32(value, 16), 2).PadLeft(12, '0');	0
9554148	9554105	How to put elements next to each other horizontally?	.evenCulomn .oddCulom\n{\n    float: left;\n    width: 200px;\n}	0
17355412	17315541	Getting access token for google+ with requested permissions	string pollActiveWindowForAuthCode(int sleepTime){\n        string activeTitle = GetActiveWindowTitle();\n        while (!activeTitle.StartsWith("Success"))\n        {\n            activeTitle = GetActiveWindowTitle();\n            Thread.Sleep(sleepTime);\n        }\n        // strip to start of auth code\n        string trimToAuthCode = activeTitle.Substring(activeTitle.LastIndexOf("=") + 1);\n        // trim the " - Google Chrome" text\n        return trimToAuthCode.Substring(0, trimToAuthCode.IndexOf(' '));\n    }	0
4815688	4815629	How do i pass variables to a buttons event method?	class MyButton : Button\n{\n    private Type m_TYpe;\n\n    private object m_Object;\n\n    public object Object\n    {\n        get { return m_Object; }\n        set { m_Object = value; }\n    }\n\n    public Type TYpe\n    {\n        get { return m_TYpe; }\n        set { m_TYpe = value; }\n    }\n}\n\n\n\n\nButton1Click(object sender, EventArgs args)\n{\n  MyButton mb = (sender as MyButton);\n\n  //then you can access Mb.Type\n  //and  Mb.object\n}	0
15581985	15581745	Find all occurences of substring in string	\{\n([0-z\[\]" ,-\.=]+;\n)+\}	0
18511056	18510934	How can i take only particular fields from the model in mvc4?	public class UpdateViewModel\n{\n    public string givenName { get; set;}\n}\n\npublic ActionMethod Put()\n{\n    var original = GetOriginalLeaveModelSomehow();\n    var viewModel = new UpdateViewModel();\n\n    viewModel.givenName = original.givenName;\n    // The idea is that the viewModel class contains only the fields you want to display to the user.\n\n    return View(viewModel);\n}\n\n[HttpPost]\npublic ActionMethod Put(UpdateViewModel viewModel)\n{\n    var original = GetOriginalLeaveModelSomehow();\n\n    originalMode.givenName = viewModel.givenName;\n\n    Ileave.Update(original);\n}	0
1726879	1726851	Read HTML Elements from Code Behind using asp.net C#	Request.Form("Name") != null	0
28616491	28615788	GDI+ Rotate Gauge Needle	using (var needle = Graphics.FromImage(bmp))\n{\n    needle.TranslateTransform(182, 211);\n    needle.RotateTransform(angle);\n    needle.TranslateTransform(-68, -39);\n    needle.DrawImage(Image.FromFile(@"C:\temp\needle.png"), new PointF(0, 0));\n}	0
28168	26354	Print a barcode to a Intermec PB20 via the LinePrinter API	Intermec.Print.LinePrinter lp;\n\nint escapeCharacter = int.Parse("1b", NumberStyles.HexNumber);\nchar[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };\n\nlp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL");\nlp.Open();\n\nlp.Write(charArray2); //switch to ez print mode\n\nstring testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}";\nlp.Write(testBarcode);\n\nlp.Write("{LP}"); //switch from ez print mode back to line printer mode\n\nlp.NewLine();\nlp.Write("Test"); //verify line printer mode is working	0
11735869	11735797	Using lookup tables with Entity Framework	var result = (from p in context.People\n              where p.PS_Lookup.Any(ps => ps.ID == 1)\n              select new { p.ID, p.PersonName })\n             .ToList();	0
3966522	3966503	C# apply Color to Font	var myTextBox = new TextBox();\nmyTextBox.ForeColor = col;\nmyTextBox.Font = birthdayFont;\nmyTextBox.Text = "Happy birthday!";\n\nthis.Controls.Add(myTextBox);	0
10999085	10998961	Adding values to a dictionary via inline initialization of its container	AllCities.Add(new City("Rome") { Names = { { "DE", "Rom" }, { "...", "..." } } });	0
17640123	17613613	Are there anyway to make ListBox items to word wrap if string width is higher than ListBox width?	lst.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;\nlst.MeasureItem += lst_MeasureItem;\nlst.DrawItem += lst_DrawItem;\n\nprivate void lst_MeasureItem(object sender, MeasureItemEventArgs e)\n{\n    e.ItemHeight = (int)e.Graphics.MeasureString(lst.Items[e.Index].ToString(), lst.Font, lst.Width).Height;\n}\n\nprivate void lst_DrawItem(object sender, DrawItemEventArgs e)\n{\n    e.DrawBackground();\n    e.DrawFocusRectangle();\n    e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);\n}	0
26061076	26060939	How to Populate a Dropdownlist in VB.NET or C# From an xml with two different values while joining them using a delimiter	DropDownList.Items.Add(strArr(count) & "," & strArr1(count))	0
28026082	27901550	Image file to PDF Conversion in Windows Phone Silverlight 8.1	using C1.Phone.Pdf;\nusing C1.Phone.PdfViewer;\n\nC1PdfDocument pdf = new C1PdfDocument(PaperKind.PrcEnvelopeNumber3Rotated);\npdf.Landscape = true;\n\nvar rc = new System.Windows.Rect(20,30,300,200);\npdf.DrawImage(wbitmp, rc);\n\nvar fillingName = "Test.pdf";\nvar gettingFile = IsolatedStorageFile.GetUserStoreForApplication();\n\nusing (var loadingFinalStream = gettingFile.CreateFile(fillingName))\n{\n   pdf.Save(loadingFinalStream);\n}	0
25597700	25597699	How to access base class from within subclass?	public class Base\n{\n    private float a;\n    protected float b;\n    public float c;\n\n}\n\n\npublic class Sub : Base\n{\n    public void DoSomething()\n    {\n       float x = base.a; // Error cannot access private member a\n\n       // Note that putting base before b and c here is optional\n       // though it does help with naming conflicts \n       // if Sub would also have a member b you could differentiate the two\n       // using this.b and base.b\n       float y = base.b; // Works\n       float z = base.c; // Works\n    }\n}	0
12045564	12045540	How to convert NUMBER(9) to String with Linq to Entity?	items = (from x in db.Table1\n         select x.ColA).ToList().Select(x => x.ToString()).toList())	0
22928456	22924581	How to get GridView values from asp:BoundField?	foreach (GridViewRow gr in GridView1.Rows)\n{\n\n   string cell_1_Value= GridView1.Rows[gr.RowIndex].Cells[0].Text; \n   string cell_2_Value= GridView1.Rows[gr.RowIndex].Cells[1].Text; \n\n}	0
9469427	9468477	Assembly Cannot be cast	public class MyOptions\n{\n  public int n;\n}\n\nstatic Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n  return Assembly.LoadFrom(@"C:\windwos\test.dll");\n}\n\nstatic void Main(string[] args)\n{\n  MyOptions ass = new MyOptions();\n  AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n  StringWriter sw = new StringWriter();\n  XmlSerializer serializer = new XmlSerializer(ass.GetType(), new Type[] { typeof(MyOptions) });\n  serializer.Serialize(sw, ass);\n  //more code writing in an xml file\n  AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;\n}	0
15532809	15532726	C# how to saving userinput in windows form	for (int i = 0; i < MusicList.Count i++)\n{\n    string sName = MusicList[i].songName;\n    string aName = MusicList[i].artistName;\n    FileSaving.WriteLine(sName + ' ' + aName);\n}	0
24822686	24822499	Best way to Convert Int[] array to string and string to int[] in .net Compact framework 2.0 through VS2005	int[] arr = new int[] { 1, 2, 3, 4 };\n\nstring[] strArr = new string[4];\n\nfor (int i = 0; i < arr.Length; i++)\n    strArr[i] = arr[i].ToString();\n\nstring newStr = String.Join(",", strArr);	0
6860257	6860060	Implementing a variation of the Flood Fill algorithm.	gameGrid.DetectNeighbours2(gameGrid.planets.Last());\n\n\n//Flood fill algorithm to detect all connected planets\n    internal void DetectNeighbours(Planet p)\n    {\n        try\n        {\n            if (p == null || p.deletable)\n                return;\n\n            p.deletable = true;\n\n            DetectNeighbours(GetTopNode(p));\n        }\n\n        catch (Exception err)\n        {\n            Debug.WriteLine(err.Message);\n        }\n    }\n\n\n    internal Planet GetTopNode(Planet b)\n    {\n        foreach (Planet gridPlanet in planets)\n        {\n            if (gridPlanet .Y == b.Y - 50)\n                return gridPlanet ;       \n        }\n\n        return null;\n    }	0
7735238	7734983	In WCF Data Services, how can I limit the entities visible to the consumer?	config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);	0
31636871	31636331	how can I access Session in preinit function in asp.net?	public partial class YOUR_ASPX: System.Web.UI.Page , IRequiresSessionState\n{\n // your preinit code\n\n}	0
12223957	12221039	How to get data from a JSON request and display in metro app	using (var wc = new WebClient())\n{\n    string json = await wc.DownloadStringTaskAsync(trendingURL);\n    dynamic obj = JsonConvert.DeserializeObject(json);\n    foreach (var item in obj)\n    {\n        Console.WriteLine("{0} - {1} - {2} - {3}", \n                    item.title, \n                    item.year, \n                    item.images.poster, \n                    item.ratings.votes);\n    }\n}	0
20935538	20935420	JSON Deserialize Issue	var o = JsonConvert.DeserializeObject<RootObject>(response);\nDatum searchResult = o.data.FirstOrDefault();\n\nif (searchResult != null)\n{\n    // awesome\n}	0
10879042	10878865	How to retrieve 0 as the first number in C#	int number = 0;\n            string strNumber = (string)cmd.ExecuteScalar();\n            if(int.TryParse(strNumber, out number))\n            {\n                // process number\n\n                // if you want some output to be formatted with leading \n                // zeros you can use PadLeft method\n                int totalNumberOfDigits = 6;\n                string strResult = number.ToString().PadLeft(totalNumberOfDigits, '0');\n            }	0
2657942	2657881	how to pass the strMessage (from codebehind to the script) to get the alert message	using Microsoft.Security.Application;\n\nnamespace RegisterClientScriptBlock\n{\n    public partial class _Default : System.Web.UI.Page\n    {\n        protected void Page_Load(object sender, EventArgs e)\n        {\n            String alertScript;\n            String inputWord;\n            String encodedWord;\n\n            encodedWord = AntiXss.JavaScriptEncode(inputWord);\n\n            alertScript = "function alertShowMessage() {";\n\n            if (checkIfWordHasBeenUsed(inputWord) == true)\n            {\n                alertScript = alertScript + "alert('You have already used the message:" + encodedWord + "');}";\n            }\n            else\n            {\n                alertScript = alertScript + "alert('You have not used the message:" + encodedWord + "');}";\n            }\n\n            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertShowMessage", alertScript, true);\n        }\n    }\n}	0
8767662	8762642	Use of SqlBulkInsert in production applications	public void Bulk(String connectionString, DataTable data, String destinationTable)\n{\n    using (SqlConnection connection = new SqlConnection(connectionString))\n    {\n        using (SqlBulkCopy bulkCopy =\n            new SqlBulkCopy\n            (\n            connection,\n            SqlBulkCopyOptions.TableLock |\n            SqlBulkCopyOptions.FireTriggers |\n            SqlBulkCopyOptions.UseInternalTransaction,\n            null\n            ))\n        {\n            bulkCopy.BatchSize = data.Rows.Count;\n            bulkCopy.DestinationTableName = String.Format("[{0}]", destinationTable);\n            connection.Open();\n            bulkCopy.WriteToServer(data);\n        }\n    }\n}	0
21846947	21821699	Identifying elements in Iframe after content change using Selenium	driver.switchTo().frame(frameid);\n       driver.findElement(By.cssSelector("input[name=\"login\"]")).click();//whatever you want to perform in frame.\n      driver.switchTo().defaultContent();\n       Thread.sleep(3000);\n      driver.switchTo().frame(frameid);\n      driver.findElement(By.cssSelector("input[name=\"login\"]")).getText();//Whar ever you want to perform.	0
19626722	19626662	Retrieving Values in a Dictionary in C#	foreach (var item in records)\n{\n    // records will have key & value\n    var arr = item.Value.ToArray();\n}\n\n\n\n      foreach (var item in records)\n        {\n            // records will have key & value\n            var key = item.key;\n            var arr = item[key].ToArray();\n        }	0
12347607	12347504	Jquery Date picker toDateTime	where (@pDate is null  or CONVERT(VARCHAR(10), Date,111) between CONVERT(VARCHAR(10), @pStartDate,111) and CONVERT(VARCHAR(10), @pEndDate,111))	0
22038173	22035915	How to specify the number of parallel tasks executed in Parallel.ForEach?	class Program\n{\n    static void Main(string[] args)\n    {\n        var task = Worker.DoWorkAsync();\n        task.Wait(); //stop and wait until our async method completed\n\n        foreach (var item in task.Result)\n        {\n            Console.WriteLine(item);\n        }\n\n        Console.ReadLine();\n    }\n}\n\nstatic class Worker\n{\n    public async static Task<IEnumerable<string>> DoWorkAsync()\n    {\n        List<string> results = new List<string>();\n\n        for (int i = 0; i < 10; i++)\n        {\n            var request = (HttpWebRequest)WebRequest.Create("http://microsoft.com");\n            using (var response = await request.GetResponseAsync())\n            {\n                results.Add(response.ContentType);\n            }\n        }\n\n        return results;\n    }\n}	0
1823718	1823624	Serializing objects into the database while maintaining flexibility	/// <summary>\n/// The data storage could look something like this\n/// create table PersistedObject (ObjectId int )\n/// create table PersistedProperty (PropertyId int , PropertyName varchar(50) )\n/// create table Data (ValueId int, PropertyId int, SerializedValue image )\n/// </summary>\ninterface IFlexiblePersistence\n{\n    object this[string propertyName] { get; set;}\n\n    void Persist();\n\n}\n\nclass Person : IFlexiblePersistence\n{\n    Dictionary<string, object> data;\n\n    public Person(int personId)\n    {\n        data = PopulatePersonData(personId);\n    }\n\n    public object this[string propertyName]\n    {\n        get { return data[propertyName]; }\n\n        set\n        {\n            data[propertyName] = value;\n            Persist();\n        }\n    }\n\n    public void Persist()\n    {\n        LoopThroughAllValuesAndSaveToDB();\n    }\n}	0
28724273	28723789	Many-to-Many Query in Entity Framework 6 without Junction Tables	int id=10;\nvar items = from s in db.Packages\n            join p in db.Platforms on s.PlatformID equals p.ID\n            from g in s.Groups\n            from c in g.Customers\n            where c.Id==id && s.Published==1\n            select new {Name=s.Name, \n                        Description=s.Description,\n                        Version= s.Version,\n                        FileName= s.Filename,\n                        PlatformName=p.Name,\n                        ReleaseNoteUrl=p.ReleaseNoteUrl};	0
14329234	14328961	Populate comboBox from listBox values in C#	private BindingList<string> bindingList;\n\nList<string> stringList = new List<string();\n//populate the list any way you want for example\nstringList.Add("Hello");\nstringList.Add("Good Morning");\n\nbindingList = new BindingList<string>(stringList);\nthis.comboBox1.DataSource = bindingList;\nthis.listBox1.DataSource = bindingList;	0
16079700	16079013	Generate a Word Document from StringBuilder	Word._Application oWord;\nWord._Document oDoc;\nobject oMissing = Type.Missing;\noWord = new Word.Application();\noWord.Visible = true;\n\n//Add Blank sheet to Word App\noDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); \n\noWord.Selection.TypeText("Write your text here");\n//FOrmatting your text\noWord.Selection.Font.Size = 8;\noWord.Selection.Font.Name = "Zurich BT";\noWord.Selection.Font.Italic = 1\noWord.Selection.Font.Bold = 1\n\noDoc.Content.Application.ActiveWindow.ActivePane.View.SeekView = //Havent tested the  \n                                                             //header and footer part\nWord.WdSeekView.wdSeekCurrentPageFooter;\noDoc.Content.Application.Selection.TypeText(?Martens?);	0
22712750	22712387	How do I use MoqSequence	int callOrder = 0;\nwriterMock.Setup(x => x.Write(expectedType)).Callback(() => Assert.That(callOrder++, Is.EqualTo(0))); \nwriterMock.Setup(x => x.Write(expectedId)).Callback(() => Assert.That(callOrder++, Is.EqualTo(1))); \nwriterMock.Setup(x => x.Write(expectedSender)).Callback(() => Assert.That(callOrder++, Is.EqualTo(2)));	0
11126398	11126375	How do I determine how big a data type is in .NET?	sizeof(T)	0
4150157	4149608	reloaded wpf window	private bool m_close = false;\n// Shadow Window.Close to make sure we bypass the Hide call in \n// the Closing event handler\npublic new void Close()\n{\n    m_close = true;\n    base.Close();\n}\nprivate void Window_Closing(object sender, CancelEventArgs e)\n{\n    // If Close() was called, close the window (instead of hiding it)\n    if (m_close == true)\n    {\n        return;\n    }\n    // Hide the window (instead of closing it)\n    e.Cancel = true;\n    this.Hide();\n}	0
7930044	7896297	Preserve white space with HtmlAgilityPack	HtmlDocument.OptionWriteEmptyNodes = true;	0
825407	825323	How to Efficiently Delete Checked Items from a TreeView?	void RemoveCheckedNodes(TreeNodeCollection nodes)\n{\n    List<TreeNode> checkedNodes = new List<TreeNode>();\n\n    foreach (TreeNode node in nodes)\n    {\n        if (node.Checked)\n        {\n            checkedNodes.Add(node);\n        }\n        else\n        {\n            RemoveCheckedNodes(nodes.ChildNodes);\n        }\n    }\n\n    foreach (TreeNode checkedNode in checkedNodes)\n    {\n        nodes.Remove(checkedNode);\n    }\n}	0
25430861	25430778	How do I print out all of the columns from a row in a database in C#	while (reader.Read())\n{\n   for (int i = 0; i < reader.FieldCount; i++)\n   {\n       Console.WriteLine("\t{0}", reader[i]);\n   }\n}	0
15992680	15992523	how to show the current build with c# or msbuild?	[assembly: AssemblyVersion("1.0.*")]	0
10529429	10529259	Return FontStyle from string name	var propertyInfo = typeof(FontStyles).GetProperty("Italic",\n                                                  BindingFlags.Static |\n                                                  BindingFlags.Public |\n                                                  BindingFlags.IgnoreCase);\nFontStyle f = (FontStyle)propertyInfo.GetValue(null, null);	0
2024810	2024757	How to solve grayish frame issue when Scaling a bitmap using GDI+	System.Drawing.Imaging.ImageAttributes Att = new System.Drawing.Imaging.ImageAttributes();\nAtt.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Clamp, System.Drawing.Color.White); \ng.DrawImage(Im, new Rectangle(0,0,Im.Width,Im.Height), 0, 0, Im.Width, Im.Height, GraphicsUnit.Pixel, Att);	0
8962208	8962152	Creating a Login Screen, WPF, how to store usernames and passwords	public static string EncodePassword(string password)\n{  byte[] bytes   = Encoding.Unicode.GetBytes(password);\n   byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);\n   return Convert.ToBase64String(inArray);\n}	0
2849068	2849039	How to change font color in .net 4 Chart	chartArea.AxisX.LabelStyle.ForeColor = ColorTranslator.FromHtml("#517985");	0
28003831	28003511	C# How to use Statements in strings to parse text	interpolate(@"'It's nice to meet you $(if (Female){ ""Miss, what's a pretty \nyoung thing like you doing out in the dessert.""} else { ""Sir, what can I \ndo for ya?""})' the man asks in a drawl.");	0
6149248	6149215	How to notify event subscriber	private EventHandler foo;\n\npublic event EventHandler Foo \n{\n    add\n    {\n        if (value != null)\n        {\n            value(this, EventArgs.Empty);\n        }\n        foo += value;\n    }\n\n    remove\n    {\n        foo -= value;\n    }\n}	0
16432275	16413479	Pics included to make my Q more clear.How to write correct command line arguments for installing SQL Server 2008 R2?	/qs /ACTION=Install /FEATURES=SQLEngine,SSMS /INSTANCENAME="Your instance name here" /SQLSVCACCOUNT="NT AUTHORITY\Network Service" /SQLSYSADMINACCOUNTS="Administrators" /AGTSVCACCOUNT="NT AUTHORITY\Network Service" /IACCEPTSQLSERVERLICENSETERMS	0
6502545	5142804	How to set Background image's Scretch and TileMode in Code behind?	var imageBrush = new ImageBrush();\nimageBrush.Stretch = Stretch.Uniform;\nStackPanel1.Background = imageBrush;	0
7944407	7944280	C# regarding a parameter and running program	static Random random = new Random();	0
12041185	12035726	Linq - Limit number of results by same value of a field	using (Entities bdd = new Entities())\n{\n    from trt in bdd.TREATMENT\n    where trt.STATE == "A" &&\n    (from trt2 in bdd.TREATMENT\n    where trt2.STATE == "A" && trt2.APPLICATION == trt.APPLICATION && trt2.ID <= trt.ID\n    select trt2).Count() <= maxPerApplication - (from appp in bdd.TREATMENT\n                                                 where appp.STATE == "R" \n                                                 && appp.APPLICATION.Equals(trt.APPLICATION) \n                                                 select appp).Count()\n    select new TreatmentDto()\n    {\n     Id = trt.ID\n    };\n\n    result = treatments.ToList();\n}	0
12203166	12203037	Converting API Example From C# To VB For DoL API	AddHandler entity.SendingRequest, AddressOf DOLDataUtil.service_SendingRequest	0
24372612	24353843	Parsing a element with name space not working xpath	XmlDocument doc = new XmlDocument();\ndoc.Load("XMLFile1.xml");\n\n// Give the namespace an alias that we will use in our XPath statement\nXmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);\nmgr.AddNamespace("a", "http://Microsoft.EnterpriseManagement.Core.Criteria/");\n\n// Find any Criteria node tagged with the "a" namespace\nXmlNode node = doc.SelectSingleNode("//a:Criteria", mgr);\n\nConsole.WriteLine(node.OuterXml);	0
24403445	24380134	Zip file from URL not valid	string fileName = "filename" + ".zip";\n\n MemoryStream stream = new MemoryStream();\n\n ZipFile zipFile = new ZipFile();     \n\n WebRequest webRequest = WebRequest.Create(myUrl);\n\n webRequest.Timeout = 1000;\n\n WebResponse webResponse = webRequest.GetResponse();\n\n using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))\n {\n     string content = reader.ReadToEnd();\n     zipFile.AddEntry("myfile.txt", content);\n }\n\n zipFile.Save(stream);\n zipFile.Dispose();\n stream.Seek(0, SeekOrigin.Begin);\n\n return File(stream, "application/zip", fileName);	0
2391333	2391295	C# Code Optimization, Profiling , Application Optimization	void MyFunction()\n{\n  CountersManager.IncrementMyFunction(1);\n\n  CountersManager.IncrementFirstDBCall(1);\n  dataAccess.FirstCall();\n  CountersManager.IncrementFirstDBCall(-1);\n\n  CountersManager.IncrementWebCall(1);\n  webRequest.MakeCall();\n  CountersManager.IncrementWebCall(-1);\n\n  someCode.. moreCode;\n\n  CountersManager.IncrementSecondDBCall(1);\n  dataAccess.SecondCall();\n  CountersManager.IncrementSecondDBCall(-1);\n\n  CountersManager.IncrementMyFunction(-1);\n}	0
22833342	22833052	Parsing with Regex	\[\s*(?<yyyy>\d+)\.(?<MM>\d+)\.(?<dd>\d+)\s+(?<hh>\d+)\:(?<mm>\d+)\:(?<ss>\d+)\s+\] System > (?<username>.+) was kicked by (?<moderatorname>\w+)	0
7736408	7736357	XML LINQ: How to select more than one item?	from item in xDoc.Descendants("Product")  \n    select new \n        { \n          Name = item.Element("Name").Value,\n          price = item.Element("Price").Value\n        };	0
16404755	16401182	SSIS Package with file throught an ActionResult	//Load your package\nPackage pckg = (Package)app.LoadPackage(SSISPackagePath, null);\n// This needs to correspond to the CM's name in the package\n// and the properties of the current CM's ConnectionString\npckg.Connections["Excel Connection Manager"].ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\folder\fileName.xls;Extended Properties=""EXCEL 8.0;HDR=YES"";";\n//Execute the package and retrieve result\nresult = pckg.Execute();	0
6225000	6206662	.Net interface with AutoCad - how to make a selection	Document doc = Application.DocumentManager.MdiActiveDocument;\nDatabase db = doc.Database;\nEditor ed = doc.Editor;\nPromptSelectionResult psr = ed.GetSelection();\nif (psr.Status != PromptStatus.OK) return;\nusing (Transaction tr = db.TransactionManager.StartTransaction())\n{\n    foreach (SelectedObject so in psr.Value)\n    {\n        var dbo = tr.GetObject(so.ObjectId, OpenMode.ForRead);\n        //...\n    }\n    tr.Commit();\n}	0
21748473	21748144	how to avoid to insert same data into database	CREATE PROCEDURE your_Proc\n(\n     @mail_id nvarchar(255),\n     ... //other parameters here\n)\nAS\nBEGIN\n      IF EXISTS(SELECT 0 FROM contact_book WHERE LOWER(mail_id) = LOWER(@mail_id))\n      BEGIN\n          SELECT "mail id exist"\n      END\n      ELSE\n      BEGIN\n          INSERT INTO contact_book ....\n          SELECT "record inserted successfully"\n      END\nEND	0
30517387	30517302	Buttons in WinForms	cb.Appearance = Appearance.Button;	0
33365100	33363641	Can I create view with di-container in custom TriggerAction in WPF and Prism?	ServiceLocator.Current.GetInstance<MyServie>();	0
19680001	19679953	how to get the Linkbutton's text to string type in it's Click event	protected void QuestionLinkButton_Click(object sender, EventArgs e)\n{\n    LinkButton btn = sender as LinkButton;\n    string LBQ = btn.Text; \n}	0
21731887	21731804	How do i post to facebook a meassage with some lines and a space/s between the lines?	private void button8_Click(object sender, EventArgs e)\n{\n    PostFacebookWall("", lineToPost + Environment.NewLine + Environment.NewLine \n                                    + "new line test");\n}	0
30999174	30998925	Can I check if action is a child action in a view?	ViewContext.IsChildAction	0
18394973	18372857	Dynamically creating App Bar in Windows Phone 8 PhoneGap app	URI currentURI = ((App)Application.Current).RootFrame.CurrentSource;	0
11439903	11439796	How can I encode two numbers in a single Integer?	both = Math.Round(num1, 2) * 10000 + Math.Round(num2, 2);	0
11462623	11462608	in C#, why do I see there's a zero stored in my int variable when I declare it, but still get an error saying I should initialize it?	int v=0	0
2686205	2684221	Creating a PDF from a RDLC Report in the Background	Warning[] warnings;\nstring[] streamids;\nstring mimeType;\nstring encoding;\nstring filenameExtension;\n\nbyte[] bytes = reportViewer.LocalReport.Render(\n    "PDF", null, out mimeType, out encoding, out filenameExtension,\n    out streamids, out warnings);\n\nusing (FileStream fs = new FileStream("output.pdf", FileMode.Create))\n{\n    fs.Write(bytes, 0, bytes.Length);\n}	0
20727825	20725640	How do I get rid of the outliers in this Point array?	var numDotsPerRow = new Dictionary<int,int>();\nvar numDotsPerColumn = new Dictionary<int,int>();\n\nforeach (var point in pointArray)\n{\n    int count;\n    numDotsPerRow.TryGetValue(point.X, out count);\n    numDotsPerRow[point.X] = count+1;\n    numDotsPerColumn.TryGetValue(point.Y, out count);\n    numDotsPerColumn[point.Y] = count+1;\n}	0
2366838	2363458	StructureMap singleton usage (A class implementing two interface)	ObjectFactory.Initialize(x =>\n{\n    x.For<IInterface1>().Singleton().Use<MyClass>();\n    x.Forward<IInterface1, IInterface2>();\n});	0
4554385	4554299	How to use lame.exe in my application?	string lameEXE = @"C:\path_of_lame\lame.exe";\nstring lameArgs = "-V2";\n\nstring wavFile = @"C:\my_wavs\input.wav";\nstring mp3File = @"C:\my_mp3s\output.mp3";\n\nProcess process = new Process();\nprocess.StartInfo = new ProcessStartInfo();\nprocess.StartInfo.FileName = lameEXE;\nprocess.StartInfo.Arguments = string.Format(\n    "{0} {1} {2}",\n    lameArgs,\n    wavFile,\n    mp3File);\n\nprocess.Start();\nprocess.WaitForExit();\n\nint exitCode = process.ExitCode;	0
6468205	6468151	Get javascript code from html file	HtmlWeb hwObject = new HtmlWeb();\nHtmlDocument htmldocObject = hwObject.Load("http://www...");\nforeach(var script in doc.DocumentNode.Descendants("script").ToArray()) \n{ \n    string s = script.InnerText;\n    // Modify s somehow\n    HtmlTextNode text = (HtmlTextNode)script.ChildNodes\n                        .Single(d => d.NodeType == HtmlNodeType.Text);\n    text.Text = s;\n}\nhtmldocObject .Save("file.htm");	0
753157	753132	How do I get the colour of a pixel at X,Y using c#?	using System;\n  using System.Drawing;\n  using System.Runtime.InteropServices;\n\n  sealed class Win32\n  {\n      [DllImport("user32.dll")]\n      static extern IntPtr GetDC(IntPtr hwnd);\n\n      [DllImport("user32.dll")]\n      static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);\n\n      [DllImport("gdi32.dll")]\n      static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);\n\n      static public System.Drawing.Color GetPixelColor(int x, int y)\n      {\n       IntPtr hdc = GetDC(IntPtr.Zero);\n       uint pixel = GetPixel(hdc, x, y);\n       ReleaseDC(IntPtr.Zero, hdc);\n       Color color = Color.FromArgb((int)(pixel & 0x000000FF),\n                    (int)(pixel & 0x0000FF00) >> 8,\n                    (int)(pixel & 0x00FF0000) >> 16);\n       return color;\n      }\n   }	0
7661208	7631922	 Generate drop down from non-direct-link database table	public class FoodViewModel\n{\n    public IEnumerable<FOOD> Foods { get; set; }\n    public IEnumerable<FOODUNIT> FoodUnits { get; set; }\n}	0
4403775	4403760	How to do this vb 2010	Dim number As Int32 = New Random().[Next]()\nConsole.WriteLine(number)\n\nDim GenerateRandom As Func(Of Int32) = Function() New Random().[Next]()\n\nConsole.WriteLine("Begin Call")\nGenerateRandom.DoAsync(Function(number) Console.WriteLine(number))\nConsole.WriteLine("End Call")	0
2170691	2170644	Linq to Xml Convert a list	string input = "<mytags><tag1>hello</tag1><tag2>hello</tag2><tag1>MissingTag</tag1><tag1>Goodbye</tag1><tag2>Goodbye</tag2></mytags>";\nvar xml = XElement.Parse(input);\nvar list = (from x in xml.Elements("tag1")\n           let next = x.NextNode as XElement\n           select new MyObject\n            {\n                Tag1 = x.Value,\n                Tag2 = (next != null && next.Name == "tag2") ? next.Value : ""\n            }).ToList();	0
8936592	8936397	how to change the grid row of the control from code behind in wpf	Grid.SetRow(txtDescription, 1);	0
17251765	17248723	Calculating Number of week with a condition	int weeks=0;\n  DateTime firstdayback = Convert.ToDateTime ("2013-06-01");\n            weeks = DateTime.Now.Subtract(firstdayback).Days / 7;\n            Console.WriteLine(weeks);	0
29609491	29609392	Dynamic HTTP Requests based off DateTime in WebAPI + AngularJS	recurring background tasks in ASP.NET	0
6844665	6831536	set the footer in place	printedby.Docking = Docking.Bottom;\ngompanytitle.Docking = Docking.Bottom;\nfootertitle.Docking = Docking.Bottom;	0
24903561	24902139	How to get Start and End date given the week number in jQuery datepicker	// Returns a Date object for Monday at the\n// start of the specified week\nfunction dateFromWeekNumber(year, week) {\n  var d = new Date(year, 0, 1);\n  var dayNum = d.getDay();\n  var diff = --week * 7;\n\n  // If 1 Jan is Friday to Sunday, go to next week\n  if (!dayNum || dayNum > 4) {\n    diff += 7;\n  }\n\n  // Add required number of days\n  d.setDate(d.getDate() - d.getDay() + ++diff);\n  return d;\n}\n\nconsole.log(dateFromWeekNumber(2014, 1));  // Mon 30 Dec 2013\nconsole.log(dateFromWeekNumber(2016, 1));  // Mon 04 Jan 2016\nconsole.log(dateFromWeekNumber(2014, 30)); // Mon 21 Jul 2014	0
3259481	3259392	Drawing Items in a Listbox	if (e is String)\n{\n    //do something..\n}\nelse if (e is Label)\n{\n    //do something..\n}	0
18227766	18227715	Get Specific number from List	for(int i=0; i<5; ++i)\n{\n  listBox3.Items.Add(Url[i]);\n}	0
21582392	21582301	How to assign an event to a button press	class Example \n{\n   public static void Main() \n   {\n      ConsoleKeyInfo cki;\n      // Prevent example from ending if CTL+C is pressed.\n      Console.TreatControlCAsInput = true;\n\n      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");\n      Console.WriteLine("Press the Escape (Esc) key to quit: \n");\n      do \n      {\n         cki = Console.ReadKey();\n         Console.Write(" --- You pressed ");\n         if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");\n         if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");\n         if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");\n         Console.WriteLine(cki.Key.ToString());\n       } while (cki.Key != ConsoleKey.Escape);\n    }\n}	0
22177093	22176962	delete all files in a web directory	System.IO.DirectoryInfo di= new DirectoryInfo(HttpContext.Current.Server.MapPath("\\MyDirectory"));\n\nforeach (FileInfo file in di.GetFiles())\n{\n  file.Delete(); \n}	0
24715523	24715209	How to set the principal in the current scenario	AppDomain.CurrentDomain.SetThreadPrincipal(authentication);	0
29240023	29239723	DotNetZip extract prevents process from accessing file	[Test]\n        public void Test2()\n        {\n            using (ZipFile zip = ZipFile.Read("D:/ArchiveTest.zip"))\n            {\n                foreach (ZipEntry entry in zip)\n                {\n                    entry.Extract("D:/ArchiveTest");\n                }\n\n                zip.Dispose();\n            }\n\n            var updateList = Directory.GetFiles("D:/ArchiveTest").Where(x => x.Contains(".UPD"));\n            foreach (string upd in updateList)\n            {\n                string[] result = File.ReadAllLines(upd);\n                int index = Array.IndexOf(result, "[Info]");\n\n                //then I do stuff with index\n            }\n        }	0
26819709	26819548	How to know which figure I clicked?	bool isClicked(float x, float y)	0
9966079	9965919	Preventing Page Review after Logout	FormsAuthentication.SignOut();\nSession.Abandon();\n\n// clear authentication cookie\nHttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");\ncookie1.Expires = DateTime.Now.AddYears(-1);\nResponse.Cookies.Add(cookie1);\n\n// clear session cookie\nHttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");\ncookie2.Expires = DateTime.Now.AddYears(-1);\nResponse.Cookies.Add(cookie2);\n\nFormsAuthentication.RedirectToLoginPage();	0
33122870	33122241	Generic Repository Inconsistent accessibility	public IGenericRepository<TEntity> Repository<TEntity>() where TEntity : class\n{\n        if (repositories.Keys.Contains(typeof(TEntity)) == true)\n        {\n            return repositories[typeof(TEntity)] as IGenericRepository<TEntity>;\n        }\n        GenericRepository<TEntity> repo = new GenericRepository<TEntity>(_context);\n        repositories.Add(typeof(TEntity), repo);\n        return repo;\n}	0
3181183	3181131	how to: make a panel resize with its form; and attach a console for output	Control.Anchor	0
4669233	4668925	Cryptographically secure XML comparator	XmlDocument doc = new XmlDocument();\n  doc.LoadXml(xml);\n  System.Security.Cryptography.Xml.Transform t = new System.Security.Cryptography.Xml.XmlDsigC14NTransform();\n  // or System.Security.Cryptography.Xml.XmlDsigExcC14NTransform\n  t.Resolver = null;\n  t.LoadInput(doc);\n  Stream stream = (Stream)t.GetOutput(typeof(Stream));\n  string canonicalXml = new StreamReader(stream).ReadToEnd();	0
14260280	14260238	Measuring time in C++ with high precision	LARGE_INTEGER freq, start, end;\nQueryPerformanceFrequency(&freq);\nQueryPerformanceCounter(&start);\n// do some long operation here\nSleep(5000);\nQueryPerformanceCounter(&end);\n// subtract before dividing to improve precision\ndouble durationInSeconds = static_cast<double>(end.QuadPart - start.QuadPart) / freq.QuadPart;	0
6657087	3502759	Weifenluo Dock Panel Suite: Float windows using their design size?	var topLeft = dockPanel1.Location;\ntopLeft.X += (dockPanel1.Size.Width / 2 - newForm.Size.Width / 2);\ntopLeft.Y += (dockPanel1.Size.Height / 2 - newForm.Size.Height / 2);\nnewForm.Show(dockPanel1, new Rectangle(topLeft, newForm.Size));	0
12665513	12665492	How do I read this xml File?	var doc = XDocument.Load(fileName);\n// This should be parameters/parameter, i follow the question with parameters/parameters\nvar par = doc.Element("parameters").Element("parameters");  \nregisterLink = par.Attribute("registerLink").Value;  // string	0
7416754	7416615	Append binding data not replace with binding data	ObservableCollection<string>_myUpdateList = new ObservableCollection<string>();	0
1714548	1681501	Changing how a telerik radgrid marks a row as "modified"	private void SaveButton_Click(object sender, EventArgs e)\n    {\n         SaveButton.Focus();\n         // Do work to save the grid's modified rows\n    }	0
582699	582680	C# setting multiple properties through a single assignment	public string PropertyA\n {\n       get { return a; }\n       set \n       {\n            a = value;\n            doStuff(); \n       }\n }	0
11621665	11621640	How to return an object value in a list that has a certain dictionary value	people.Single(x => x.RoleTypes.ContainsKey("CEO"));	0
18996388	18993417	How can I update Rally team membership?	//Get the current team memberships for a user\nvar user = restApi.GetByReference("/user/12345", "TeamMemberships");\nRequest teamMemberRequest = new Request(user["TeamMemberships"]);\nList<DynamicJsonObject> teams = new List<DynamicJsonObject>(restApi.Query(teamMemberRequest).Results.Cast<DynamicJsonObject>());\n\n//Add the new team (project)        \nDynamicJsonObject newTeam = new DynamicJsonObject();\nnewTeam["_ref"] = "/project/23456";\nteams.Add(newTeam);\n\n//Update the user\nDynamicJsonObject toUpdate = new DynamicJsonObject();\ntoUpdate["TeamMemberships"] = teams;\nrestApi.Update(user["_ref"], toUpdate);	0
16865159	16865146	get string from file path not in a path format	fullpath = fullpath.Replace(@"\\", @"\");	0
3442030	3090246	A Toolstrip that can auto size itself	m_floatForm.AutoSize = True\n  m_floatForm.AutoSizeMode = AutoSizeMode.GrowAndShrink	0
26569818	26569764	Storing XML in a nested dictionary	var dictionary =\n    xd\n        .Descendants("Pet")\n        .ToDictionary(\n            x => x.Attribute("name").Value,\n            x => x.Elements()\n                .ToDictionary(\n                    y => y.Name,\n                    y => y.Attribute("name").Value));	0
15154791	15154712	Updating table in database using string from database?	string sql = "UPDATE [Product] SET [Quantity]=[Quantity] - 1 " + " WHERE [Product Name]= '" + product + "'";	0
23474767	23474730	Best practices with oracle connection in C #	string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";\nusing(OracleConnection conn = new OracleConnection(oradb))\nusing(OracleCommand cmd = new OracleCommand())\n{\n   conn.Open();\n   cmd.Connection = conn;\n   cmd.CommandText = "select * from departments";\n   cmd.CommandType = CommandType.Text;\n   using(OracleDataReader dr = cmd.ExecuteReader())\n   {\n       dr.Read();\n       label1.Text = dr.GetString(0);\n   }\n}	0
2670019	2669943	List view new line for new values	private void displayDeliveries() \n{ \n    lstDeliveryDetails.Items.Clear(); \n    foreach (Delivery d in mainForm.myDeliveries) \n    { \n        ListViewItem item = lstDeliveryDetails.Items.Add(d.DeliveryName); \n        item.SubItems.Add(d.DeliveryAddress);  \n    } \n}	0
14080176	14080110	Show the SwitchUser Screen	using System;\nusing System.Runtime.InteropServices;\nusing System.ComponentModel;\n\nclass Program\n{\n  [DllImport("wtsapi32.dll", SetLastError = true)]\n  static extern bool WTSDisconnectSession(IntPtr hServer, int sessionId, bool bWait);\n\n  const int WTS_CURRENT_SESSION = -1;\n  static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;\n\n  static void Main(string[] args)\n  {\n    if (!WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE,\n         WTS_CURRENT_SESSION, false))\n      throw new Win32Exception();\n  }\n}	0
23143854	23143547	Getting the position of a windows application from C#	MessageBox.Show( string.Format("Left: {0}\r\nTop: {1}\r\nRight: {2}\r\nBottom: {3}", NotepadRect.Left, NotepadRect.Top, NotepadRect.Right, NotepadRect.Bottom));	0
2725106	2725072	LINQ to XML return second element	.Skip(1).First().Attribute....	0
25510121	25509756	Focus on Control	get\n{\n    if (dbLocation == null)\n    {\n        dbDialog.ShowDialog();\n        dbLocation = db.FileName;\n    }\n    return dbLocation;\n}	0
28157458	28152270	Determine screen coordinates from point in DirectX world	var viewProj = mMainCamera.View * mMainCamera.Projection;\nvar vp = mDevice.ImmediateContext.Rasterizer.GetViewports()[0];\nvar screenCoords = Vector3.Project(worldSpaceCoordinates, vp.X, vp.Y, vp.Width, vp.Height, vp.MinZ, vp.MaxZ, viewProj);	0
11162112	11161569	Array of different generics	public MyGeneric<T2> ToOtherType<T2>()\n{\n    if (typeof(T2).IsAssignableFrom(typeof(T)))\n    {\n        // todo: get the object\n        return null;\n    }\n    else\n        throw new ArgumentException();\n}\n\n        new MyGeneric<Dog>().ToOtherType<Animal>(),\n        new MyInheritedGeneric<Cat>().ToOtherType<Animal>()	0
1286573	1286572	Compare two datetimes - without hour and second	DateTime.Now.Date	0
4665541	4665530	C# polymorphism with cloning	public abstract class Loot : ICloneable\n{\n    public virtual object Clone()\n    {\n        Type type = this.GetType();\n        Loot newLoot = (Loot) Activator.CreateInstance(type);\n        //do copying here\n        return newLoot;\n    }\n}	0
7435332	7435036	Ordering list elements with regex in C#	var input = "BLOCK\r\n    LIST1 Lorem ipsum dolor sit amet ...";\n\nvar levels = new List<string> { "BLOCK", "LIST1", "LIST2", "LIST3" };\nvar counter = levels.ToDictionary(level => level, level => 0);\n\n// Replace each key word with incremented counter,\n// while resetting deeper levels to 0.\nvar result = Regex.Replace(input, string.Join("|", levels), m =>\n{\n    for (int i = levels.IndexOf(m.Value) + 1; i < levels.Count; i++)\n    {\n        counter[levels[i]] = 0;\n    }\n    return GetLevelToken(m.Value, ++counter[m.Value]);\n});\n\nprivate static string GetLevelToken(string token, int index)\n{\n    switch (token)\n    {\n        case "BLOCK":\n            return index.ToString() + ".";\n        case "LIST1":\n            return index.ToString() + ".";\n        case "LIST2":\n            return ((char)('A' + index - 1)).ToString();\n    }\n    return "";\n}	0
9535671	9535302	How to insert TextBox into Grid when Window is loaded in C# WPF application	grdAdtn.Children.Add(fields[i,j]);  \nGrid.SetColumn(fields[i,j], i);  \nGrid.SetRow(fields[i,j], j);	0
15873403	15873270	In WPF/MVVM, how to implement the "Select All" function in a perfect way	public bool? SelectedAll\n{\n    get { return this.Get<bool?>("SelectedAll"); }\n    set \n    {\n        if(Equals(SelectedAll, value) == true)\n            return;\n        this.Set<bool?>("SelectedAll", value);\n        OnSelectedAllChanged(value);\n    }\n}\n\nprivate void SelectedAllChanged(bool? input)\n{\n    //Stuff\n}	0
8770292	8770234	Releasing access to files	using System.IO;\n\nclass Program\n{\n    static void Main()\n    {\n          using (StreamWriter writer = new StreamWriter("important.txt"))\n          {\n                writer.Write("Word ");\n                writer.WriteLine("word 2");\n                writer.WriteLine("Line");\n          }\n    }\n}	0
10669397	10669262	Using a stopwatch to benchmark application usage	// Declare singleton wrapper of a stopwatch, which instantiates stopwatch\n// on construction\npublic class StopwatchProxy \n{\n    private Stopwatch _stopwatch;\n    private static readonly StopwatchProxy _stopwatchProxy = new StopwatchProxy();\n\n    private StopwatchProxy()\n    {\n        _stopwatch = new Stopwatch();\n    }\n\n    public Stopwatch Stopwatch { get { return _stopwatch; } } \n\n    public static StopwatchProxy Instance\n    { \n        get { return _stopwatchProxy; }\n    }\n}\n\n// Use singleton\nclass Foo\n{\n    void Foo()\n    {\n        // Stopwatch instance here\n        StopwatchProxy.Instance.Stopwatch.Start();\n    }\n}\n\nclass Bar\n{\n    void Bar()\n    {\n        // Is the same instance as here\n        StopwatchProxy.Instance.Stopwatch.Stop();\n    }\n}	0
10590279	10589940	Tab delimited txt file reading int value from string array	int parsedNumber;\n userWorkload.contactHours = int.TryParse(arrColumns[9], out parsedNumber) ? parsedNumber : -1;	0
12306429	12306320	Get Associated Pattern String from a CurrencyNegativePattern	string[] patternStrings = { "($n)", "-$n", "$-n", "$n-", "(n$)", \n                            "-n$", "n-$", "n$-", "-n $", "-$ n",\n                            "n $-", "$ n-", "$ -n", "n- $", "($ n)",\n                            "(n $)" };    \n\nint GetNegativeAssociatedPattern(int index)\n{\n    return patternStrings[index];\n}	0
6114615	6114519	How to create method interface with variable parameters / different method signatures?	public interface IViewModel\n{\n    //...\n    void ResetReferences(IResetValues vals); \n}	0
20923023	20922721	How can I bind to the property of a class from the codebehind?	foreach (var Stats in player){\nvar columnHeaderScore = new TextBlock\n{\n    Style = Application.Current.Resources["Column_Value_Large"] as Style,\n};\ncolumnHeaderScore.SetBinding(TextBlock.TextProperty, new Binding\n{\n    Source = Stats.Scores.Team,\n});\ncolumnHeaderStackPanel.Children.Add(columnHeaderScore);	0
22684041	22683579	Looping from a position in array +2 a certain amount of times, getting those values and display (later to plot graph)	int of2 = 502;\nint of1 = 254;\nint of3 = 750;\n\nfor (int i = 1; i < 100; i++) \n{\n    float f1 =  Decode(Rec, of1) / (float)100;\n    float f2 =  Decode(Rec, of2) / (float)100;\n    float f3 =  Decode(Rec, of3);\n    of1 +=2;\n    of2 +=2;\n    of3 +=2;\n\n}	0
942077	942039	Custom Linq Ordering	//Creating a dictionary with the custom order\nvar order = "MSHAP";\nvar orderDict = order.Select((c,i)=>new {Letter=c, Order=i})\n                     .ToDictionary(o => o.Letter, o => o.Order);\n\nvar list = new List<string>{"A.ext", "H.ext", "M.ext", "P.ext", "S.ext"};\n\n//Ordering by the custom criteria\nvar result = list.OrderBy(item => orderDict[item[0]]);	0
4657106	4656045	How to Check the CheckBox in a GridView based on Condition?	DR["IsFixed_f"] = radiobuttonlist.SelectedItem.Value == "Fixed Length" ?true : false;	0
13675877	13675769	How can I add the registry key	Registry.SetValue(@"HKLM\Software\Business Objects\Suite 11.5\Components\DHTMLViewer", "EncodeHTMLForSingleLineFieldObjects", "my value");\n\nvar value = Registry.GetValue(@"HKLM\Software\Business Objects\Suite 11.5\Components\DHTMLViewer", "EncodeHTMLForSingleLineFieldObjects", null);	0
16167704	16165675	Download a Word editable document from an aspx page	Response.AddHeader("Content-Type", "application/msword");	0
23899208	23899081	How to compare 2 images and get percentage size difference	Image imageA = new System.Drawing.Image("ImageA.png");\nImage imageB = new System.Drawing.Image("ImageB.png");\n\ndouble imageASize = imageA.Size.Height * imageA.Size.Width;\ndouble imageBSize = imageB.Size.Height * imageB.Size.Width;\n\nstring ratio = string.Format("Image B is {0}% of the size of image A", \n  ((imageBSize / imageASize)*100).ToString("#0"));	0
5997619	5997570	How to convert DateTime to Eastern Time	var timeUtc = DateTime.UtcNow;\nTimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");\nDateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);	0
7990947	7990920	How can I remove some characters from a C# string?	var ip= new Uri("http://127.0.0.1:96/Cambia3");\nvar withoutPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);	0
20304292	20304186	Populate a text box with todays date but don't want that date to be posted when I search	protected void Page_Load(object sender, EventArgs e)\n{\n    If(!Page.IsPostback)\n    {\n        TextBox1.Text = DateTime.Today.ToShortDateString();\n        TextBox2.Text = DateTime.Today.ToShortDateString();\n    }\n\n}	0
16952647	16952465	Trouble displaying an error when custom value is entered in a textbox	//Get the values\n    if (rblYears.SelectedIndex == 0)\n        years = 15;\n    else if (rblYears.SelectedIndex == 1)\n        years = 30;\n    else\n    {\n        //Display Error if custom duration is entered\n        if (!double.TryParse(txtYears.Text, out years))\n        {\n            error = true;\n            lblResult.Text = "The years must be a numeric value!";\n        }\n    }	0
591734	589268	How to make my Windows Form app snap to screen edges?	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n    }\n    private const int SnapDist = 100;\n    private bool DoSnap(int pos, int edge) {\n      int delta = pos - edge;\n      return delta > 0 && delta <= SnapDist;\n    }\n    protected override void  OnResizeEnd(EventArgs e) {\n      base.OnResizeEnd(e);\n      Screen scn = Screen.FromPoint(this.Location);\n      if (DoSnap(this.Left, scn.WorkingArea.Left)) this.Left= scn.WorkingArea.Left;\n      if (DoSnap(this.Top, scn.WorkingArea.Top)) this.Top = scn.WorkingArea.Top;\n      if (DoSnap(scn.WorkingArea.Right, this.Right)) this.Left = scn.WorkingArea.Right - this.Width;\n      if (DoSnap(scn.WorkingArea.Bottom, this.Bottom)) this.Top = scn.WorkingArea.Bottom - this.Height;\n    }\n  }	0
10576221	10576190	InputeState method parameters	out PlayerIndex playerIndex	0
1862025	1861166	How to add button to textbox?	[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic Button Button {\n    //...\n}	0
2726317	2726296	Playing with bytes...need to convert from java to C#	protected static int putLong(byte [] b, int off, long val) {\n    b[off + 7] = (byte) (val >> 0);\n    b[off + 6] = (byte) (val >> 8);\n    b[off + 5] = (byte) (val >> 16);\n    b[off + 4] = (byte) (val >> 24);\n    b[off + 3] = (byte) (val >> 32);\n    b[off + 2] = (byte) (val >> 40);\n    b[off + 1] = (byte) (val >> 48);\n    b[off + 0] = (byte) (val >> 56);\n    return off + 8;\n}	0
29203333	29203189	How to Selectively Disable Sphere Colliders?	other.enabled = false;	0
19744220	19731023	Data structure for Rush Hour solver taboo list	public override int GetHashCode()\n{\n    int hash = 0;\n    int mul = 1;\n    foreach (Car c in Cars.Values)\n    {\n        hash += (c.P1.X + c.P1.Y * W) * mul;\n        mul += W * H;\n    }\n    return hash;\n}	0
11146242	11145313	in C# code (WPF project) can I raise an event at a specific point in a storyboard	private Storyboard stb = new Storyboard();\nprivate TimeSpan tsp = new TimeSpan();\n\npublic MainWindow()\n{\n    InitializeComponent();\n    stb.CurrentTimeInvalidated += new EventHandler(doSomething);            \n}\n\nprivate void doSomething(Object sender, EventArgs e)\n{\n    Clock storyboardClock = (Clock)sender;\n        // or whatever other logic you want\n    if (storyboardClock.CurrentTime.Value.Seconds % 2 == 0 && \n       Math.Abs((storyboardClock.CurrentTime.Value - tsp).TotalSeconds) >= 2)\n    {\n        // or something like this...\n        tsp = storyboardClock.CurrentTime.Value\n         - new TimeSpan(0,0,0,0,storyboardClock.CurrentTime.Value.Milliseconds);\n        // do something\n    }\n}	0
14919395	14918992	How to access controls inside repeater?	// another way to search for asp elements on page\n\n\n public static void GetAllControls<T>(this Control control, IList<T> list) where T : Control\n        {\n            foreach (Control c in control.Controls)\n            {\n                if (c != null && c is T)\n                    list.Add(c as T);\n                if (c.HasControls())\n                    GetAllControls<T>(c, list);\n            }\n        }	0
21546944	21544634	How to scale a sprite(2D) using a matrix	ScalingFactor = new Vector3(widthScaling, heightScaling, 1);\nScale = Matrix.CreateScale(ScalingFactor);\nspriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null,null, Scale);	0
26089339	26075505	Put all the cells of selected row of a DataGrid in Edit Mode in WPF	BeginEdit()	0
12938910	12938713	How to select random number	public double GetRandomNumber()\n{ \n    //Between 0 and 1\n    Random random = new Random();\n    double randomNumber = random.NextDouble();\n\n    //Between -0.5 and 0.5;\n    randomNumber -= 0.5;\n\n    //Between -5.0 and 5.0;\n    randomNumber *= 10.0;\n\n    //Between [-15.0, -10.0] or [10.0, 15.0]\n    randomNumber += Math.Sign(randomNumber) * 10.0;\n\n    return randomNumber;\n}	0
24456989	24456903	Parsing XML file in C#	var xml = XDocument.Load("your xml string");\nforeach (var day in xml.Descendants("day"))\n{\n    var pChildren = day.Descendants("p").ToList();\n    var aretThereMorePs = pChildren.Count() > 1;\n    foreach (var p in pChildren)\n    {\n        var shortVal = (string)p.Element("short");\n        //etc\n    }\n}	0
8744244	8744211	Where does the returned value from e.g. a method call go if not filled into a declared variable of expected type?	IL_000A:  call        System.Math.Round\nIL_000F:  pop	0
68036	67492	What is the simplest way to initialize an Array of N numbers following a simple pattern?	var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9);	0
2989038	2989010	How can you start a process from asp.net without interfering with the website?	process.WaitForExit();	0
722012	721870	How can I get generic Type from string representation	Type.GetType("System.Collections.Generic.IEnumerable`1[System.String]");	0
11607791	11607722	how to get only active sheet name from excel file using c#?	WorkSheet sheet = (WorkSheet)_application.activesheet;\n\nstring name = sheet.Name;	0
10713763	10713597	DateTime issue in vb.net regarding automatic scheduling	If jb.ScheduledStartTime.Value.ToString("MM/dd/yyyy HH:mm") =\n    Now().ToString("MM/dd/yyyy HH:mm") Then\n                        'Do some work here.\n End If	0
6765566	6765376	Why my grid view doesn't sort with data table as a data source	if (sortExpression != null && sortExpression.Length > 0) \n{\n    table.DefaultView.Sort = sortExpression + " " + sortOrder;\n}	0
21331699	21331466	implementing server-side regex validation from client-side regex	public bool MadeIt(string TheCandidateString) \n{\n    string regex= @"yourRegex";\n    var match = Regex.Match(TheCandidateString, regex, RegexOptions.IgnoreCase);\n    return match.Success;\n}	0
8389566	1405865	Filetransfer in remoting	static int CHUNK_SIZE = 4096;\n\n// open the file\nFileStream stream = File.OpenRead("path\to\file");\n\n// send by chunks\nbyte[] data = new byte[CHUNK_SIZE];\nint numBytesRead = CHUNK_SIZE;\nwhile ((numBytesRead = stream.Read(data, 0, CHUNK_SIZE)) > 0)\n{\n    // resize the array if we read less than requested\n    if (numBytesRead < CHUNK_SIZE)\n        Array.Resize(data, numBytesRead);\n\n    // pass the chunk to the server\n    server.GiveNextChunk(data);\n    // re-init the array so it's back to the original size and cleared out.\n    data = new byte[CHUNK_SIZE];\n}\n\n// an example of how to let the server know the file is done so it can close\n// the receiving stream on its end.\nserver.GiveNextChunk(null);\n\n// close our stream too\nstream.Close();	0
5004869	5004688	Get attribute and value from generic class	var props = typeof(IReadOnlyMappingManager).GetProperties();\nforeach (var p in props)\n    var value = p.GetValue(mappingManager)	0
12944038	12943880	Regular Expression \d matches with multiple numbers	Regex myRegex = new Regex(@"^\d$");	0
33670719	33669218	Append IBuffer to byte[]	byte[] data;\nIInputStream inputStream = await response.Content.ReadAsInputStreamAsync();\ndata = new byte[inputStream .Length];\ninputStream.Read(data, 0, (int)inputStream.Length);\n\n//Save the file here (data)	0
2293667	2293290	Stopping Application Loop in secondary AppDomain	AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;\n        Application.ThreadException += ApplicationThreadException;	0
31190690	31188479	Converting a VideoFrame to a byte array	CopyToBuffer()	0
17730696	17629511	How to disable a div code behind in C#?	Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenNewWindow", "<script type='text/javascript'>$(function() { $('#MainDiv').dialog('open'); });$('.second-div-class').show();</script>");	0
18409948	18409889	How do I ensure that all controllers in an asp.net web-api service are configured correctly _in a single test class_?	var myControllers = Assembly.Load(yourAssemblyName)\n    .GetTypes()\n    .Where(t => typeof(t).IsAssignableFrom(ApiController))\n    .ToList();	0
5043891	935599	How to center a WPF app on screen?	WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;	0
4653031	4562442	ASMX Web Service Problem Communicating with Windows Service In a Separate Thread	[WebMethod]\npublic void Fnc()\n{\n    ...\n    ...\n    System.Security.Principal.WindowsIdentity wi =    System.Security.Principal.WindowsIdentity.GetCurrent();\n    System.Threading.Thread postJobThread = new Thread(PostJobThread);\n    postJobThread.Start(wi);\n    ...\n}\n\n...\n\nprivate void PostJobThread(object ob)\n{\n    System.Security.Principal.WindowsIdentity wi = (System.Security.Principal.WindowsIdentity)ob;\n    System.Security.Principal.WindowsImpersonationContext ctx = wi.Impersonate();\n\n    ...\n    // Do some job which couldn't be done in this thread\n    ...\n    // OK, job is finished\n    if(ctx != null)\n    ctx.Undo();\n}	0
33920285	33920222	In C#, what is the recommended way to cast a List of Interface to a list of objects?	var allCars = allVehicles.Cast<Car>();	0
27819373	27819111	How do I replace part of a string?	str1 = Regex.Replace(str1, @"\<tag.*?\>", "<tag>");	0
5440034	5427869	How to create a one-to-one mapping in NHibernate using Mapping Attributes	[OneToOne(Cascade="all-delete-orphan", ForeignKey="none", PropertyRef="Order", Lazy=Laziness.Proxy)]        \n    public Reservation Reservation\n    {\n        get;\n        private set;\n    }	0
7413775	7413029	Is there a way for ignoring all xml parsing exceptions?	using (StreamReader reader = new StreamReader("myfile.xml", Encoding.Unicode))\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load(reader);\n}	0
25435708	17065943	How to set reminding time for appointment to NONE?	ReminderIsSetSpecified = true;\nReminderIsSet = false;	0
9843193	9843116	Difficulty Establishing Connection With a Server in C# using TcpClient and Working with NetworkStreams	writer.WriteLine("0");\nwriter.Flush();\nreturn reader.ReadLine();	0
27429706	27429691	C# WPF Visibility of a TextBox in window constructor?	InitializeComponent()	0
24292195	24291990	Insert rows automatically	INSERT INTO Table3 (CustomerID, StaffID)\nselect CustomerID, @StaffId from Table1\nwhere Zipcode = @zipcode\n    and NOT EXISTS(select StaffID from Table3 where StaffID = @staffId)	0
4855966	4855766	how to use c# struct from f#	let mutable someStruct = CallSomething()\nsomeStruct.Field1 <- 42\n// etc.	0
22971348	22971269	Closing an open excel workbook in C#	Excel.Workbook wb = null;\ntry\n{\n    wb = exApp.Workbooks.Open(@file);\n}\ncatch (Exception)\n{\n    if (wb != null) wb.Close(true);\n}	0
16358368	16356348	Second eventhandler won't trigger from button	protected void Page_Load(object sender, EventArgs e)\n{\n    ImageButton btn = new ImageButton();\n    btn.Command += btnOne_Click;\n    form1.Controls.Add(btn);\n\n    ImageButton btn2 = new ImageButton();\n    btn2.Command += btnTwo_Click;\n    btn2.Visible = false;\n    form1.Controls.Add(btn2);\n}\n\nvoid btnOne_Click(object sender, EventArgs e)\n{\n    // Your second button \n    form1.Controls[2].Visible = true;\n}\n\nvoid btnTwo_Click(object sender, EventArgs e)\n{\n    ImageButton btn2 = (ImageButton)sender;\n    // Do something\n}	0
11363178	11362938	Make transparent background of application window	this.BackColor = System.Drawing.Color.Lime;\nthis.TransparencyKey = System.Drawing.Color.Lime;	0
26334096	26333548	Converting IsClosedTypeOf from autofac to simple.injector	var allQueryTypes =\n    from assembly in AppDomain.CurrentDomain.GetAssemblies()\n    from type in assembly.GetTypes()\n    where !type.IsAbstract && !type.IsGenericTypeDefinition\n    let queryInterfaces =\n        from iface in type.GetInterfaces()\n        where iface.IsGenericType\n        where iface.GetGenericTypeDefinition() == typeof(IQuery<>)\n        select iface\n    where queryInterfaces.Any()\n    select type;	0
5847559	2184191	SOAP , getting progress of the uploaded Request while its uploading c#	long buffer = 4096;\nStream stm = request.GetRequestStream();\nwhile (remainingOfChunkWithReq != 0)\n{\n  stm.Write(buffer, 0, bytesRead);\n  remainingOfChunkWithReq = remainingOfChunkWithReq - bytesRead;\n  bytesRead = memoryStream.Read(buffer, 0, bytesSize);\n  //Send Progress\n}	0
30130914	26928403	Reflections for ReGIS graphics screen scraping in C# .NET API	Reflection4.Session session = (Marshal.GetActiveObject("Reflection4.Session.8") as Reflection4.Session);	0
29609939	29597018	How to access values in XmlElementAttributte in .NET	var myData = new data();\n        //populate the data object via your webservice call.\n\n        if (myData.Items != null && myData.Items.Length > 0)\n        {\n            var currentData = from c in myData.Items where c.GetType() == typeof(ConsoleApplication3.data.dataCurrentRow) select c as ConsoleApplication3.data.dataCurrentRow ;\n\n            if (currentData != null && currentData.Count() > 0)\n            {\n                foreach (var row in currentData)\n                {\n                    if(row != null && row.columnValue != null)\n                        Console.WriteLine(row.columnValue);\n                }\n            }\n        }	0
648566	648509	how do I display time in a windows forms dataGridView bound to a datatable	public Form1()\n{\n    InitializeComponent();\n\n    dataGridView1.DataSource = new List<MyObject>\n    {\n        new MyObject{ MyDateTime= DateTime.Now }\n    };\n\n    dataGridView1.Columns["MyDateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";\n}\n\npublic class MyObject\n{\n    public DateTime MyDateTime { get; set; }\n}	0
32301311	32300849	I am trying to make a very simple program that converts decimal to binaries but I need to write them reversed	static void Main()\n{\n    int n = int.Parse(Console.ReadLine()); //input.\n\n    // Use a string to store the values before reverting.\n    string result = "";\n\n    // If you have performance issues, use a StringBuilder instead of string.\n    StringBuilder strBuilder = new StringBuilder();\n\n    while (n >= 1) // it stops if there is no number to divide.\n    {\n        int digit = n % 2; // this shows the digit.\n        result += digit; // string approach\n        strBuilder.Append(digit); // StringBuilder approach\n        n = n / 2; // for calculating another digit.\n    }\n\n    // Now you will have result == strBuilder.ToString()\n    // from this point you can use which you prefer (I use result in this example)\n\n    // OPTION 1: Use Reverse() extension method and then convert to a printable array.\n    Console.WriteLine(result.Reverse().ToArray());\n\n    // OPTION 2: Print the string backwards.\n    for (int i = result.Length - 1; i >= 0; i--)\n        Console.Write(result[i]);\n}	0
33850869	33850607	Count number of occurrences of two words in a string	string s = "on top on bottom on side Works this Magic door";\nRegex r = new Regex(@"\bon\W+(?:\w+\W+){0,4}side\b");\nint output = 0;\nint start = 0;\nwhile (start < s.Length)\n{\n    Match m = r.Match(s, start);\n    if (!m.Success) { break; }\n    Console.WriteLine(m.Value);\n    output++;\n    start = m.Index + 1;\n}\nConsole.WriteLine(output);	0
4642029	4641505	Entity Framework CTP5, Code-First. Help creating reference tables via object model	protected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<Model>().HasMany(o => o.Metals).WithMany();\n}	0
7825440	7824816	asp.net custom basepage has a public property for a repeater,prevent designer from adding protected variable for that repeater?	//MobileFunnelPage.cs  \npublic abstract class MobileFunnelPage : Page  \n{  \n    public abstract Repeater MyRepeater { get; set; }  \n}\n\n//ConcreteMobileFunnelPage.aspx.cs  \npublic class ConcreteMobileFunnelPage : MobileFunnelPage  \n{  \n    public override Repeater MyRepeater {\n        get {\n           return myRepeater;\n        }\n        set {\n           myRepeater = value;\n        }\n    }\n}	0
12520382	12519290	Downloading Files Using FTPWebRequest	private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)\n    {\n        int bytesRead = 0;\n        byte[] buffer = new byte[2048];\n\n        FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);\n        request.Method = WebRequestMethods.Ftp.DownloadFile;\n\n        Stream reader = request.GetResponse().GetResponseStream();\n        FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);\n\n        while (true)\n        {\n            bytesRead = reader.Read(buffer, 0, buffer.Length);\n\n            if (bytesRead == 0)\n                break;\n\n            fileStream.Write(buffer, 0, bytesRead);\n        }\n        fileStream.Close();       \n    }	0
31050459	31050340	how to change align of combobox item to right?	HorizontalContentAlignment="Right"	0
25653490	25653432	how to concatenate a string with a double in a propertygrid view ? C#	double v = 10;\nstring s = v.ToString(); // "10"\nstring f = string.Format("{0:0.00} cm", v); // "10.00 cm"	0
28796980	28796016	Not duplicating the data into a table when it's inserted	string insertString = "INSERT INTO TabelaUtilizatori (name, password) VALUES('"+UserID+"', '"+UserPas+"')";\n        string selectString = "SELECT COUNT(*) FROM TabelaUtilizatori where name=" + "'" + UserID + "'";\n        if (this.OpenConnection() == true)\n        {\n            MySqlCommand cmd = new MySqlCommand(selectString, connection);\n            int Result = 0;\n            Result = Convert.ToInt32(cmd.ExecuteScalar());\n            if (Result == 1)\n            {\n                MessageBox.Show("Username Already Exists");\n                this.CloseConnection();\n            }\n            else{\n              MySqlCommand cmdInsert = new MySqlCommand(insertString, connection);\n            cmdInsert.ExecuteNonQuery();\n            this.CloseConnection();\n            MessageBox.Show("Inregistration Sucessful");\n            }\n\n        }	0
1099292	1099266	c# assign 1 dimensional array to 2 dimensional array syntax	// create array of arrays\nobject[][] tableOfObject = new object[10][];\n// create arrays to put in the array of arrays\nfor (int i = 0; i < 10; i++) tableOfObject[i] = new object[10];\n\n// get row as array\nobject[] rowOfObject = GetRow();\n// put array in array of arrays\ntableOfObjects[0] = rowOfObjects;	0
1422544	1422470	How to produce multiple items in Linq to XML enumerator?	var category = xd.Descendants("PrimaryCategory")\n                 .Where(c => (int)c.Element("PrimaryCategoryID") == 3)\n                 .Single(); // Could use `FirstOrDefault` if there could be none\n\nvar query = from list in category.Elements("CategoryList")\n            select new { Name = list.Element("CategoryName").Value,\n                         Url = list.Element("CategoryURL").Value };	0
2057031	2056777	How to stop XmlSerializer from adding newlines to blank elements	if (data.Length == 0) newchild.IsEmpty = true;\n            else newchild.InnerText = data;	0
13310567	12921446	Ninject - Different Solution Configurations	#if DEBUG\n        kernel.Bind<IMyService>().To<MyServiceMock>();\n#else\n        kernel.Bind<IMyService>().To<MyService>();\n#endif	0
26013801	26013168	Convert excel format to C# TimeStamp like excel do so	var timeStamp = "1900-01-02 13:20:04";\nvar date = DateTime.Parse(timeStamp);\nvar stamp = date.Subtract(new DateTime(1900, 1, 1));\nvar result = string.Format("{0}:{1:00}:{2:00}", 24 + stamp.Days * 24 + stamp.Hours, stamp.Minutes, stamp.Seconds);	0
11537486	11537416	How to get this binding for item instead of TreeViewItem?	Binding="{Binding Path=DataContext.IsDefined, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"	0
33645493	33637875	Getting the first 5 links of a Google search	IWebElement searchInput = Driver.FindElement(By.Id("lst-ib"));\nsearchInput.SendKeys(command);\nsearchInput.SendKeys(Keys.Enter);\nWebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));\nBy linkLocator = By.CssSelector("cite._Rm");\nwait.Until(ExpectedConditions.ElementToBeClickable(linkLocator));\nIReadOnlyCollection<IWebElement> links = Driver.FindElements(linkLocator);\nforeach (IWebElement link in links)\n{\n    Console.WriteLine(link.Text);\n}	0
32888768	32888150	Serialise list of C# custom objects	var userList = JArray.Parse(json)\n    .Select(t => new User()\n    {\n        id = int.Parse(t["id"].ToString()),\n        displayName = t["attr"]["display_name"].ToString(),\n        email = t["attr"]["email"].ToString(),\n        total_points = int.Parse(t["attr"]["total_points"].ToString()),\n        total_values = float.Parse(t["attr"]["total_values"].ToString()),\n    }).ToList();	0
27187216	27187061	Linq to get a combined list out of lists C#	var orders = FruitCategories.SelectMany(fc => fc.Fruits).SelectMany(f => f.Order);\n var distinctOrders = orders.GroupBy(o => o.Id).Select(og => og.First());	0
12271328	12271066	Find Xml attribute by value, and change its other value	XmlDocument doc = new XmlDocument();\ndoc.Load("att.xml");\nforeach(XmlNode item in doc.SelectNodes("//item"))\n    comboBox1.Items.Add(item.Attributes["name"].Value);\n\n\nvoid button3_Click(object sender, NotifyArgs e)\n{\n    XmlNode item = doc.SelectSingleNode("//item[@name='" + comboBox1.Text + "']");\n    if (item == null) return;\n    item.Attributes["name"].Value = textBox1.Text;\n    ...\n    doc.Save("att.xml");\n}	0
24166174	24160932	How to use BeforeSaveEntitiesDelegate and BeforeSaveEntityDelegate of web api context provider	BeforeSaveEntity is called once for each entity before it is saved.	0
15653626	15653472	How to Convert ListView to Datatable in WPF?	// Create the `DataTable` structure according to your data source\nDataTable table = new DataTable();\ntable.Columns.Add("FileNumber", typeof(int));\ntable.Columns.Add("ShiftDate", typeof(DateTime));\ntable.Columns.Add("TimeCreated", typeof(DateTime));\ntable.Columns.Add("Remarks", typeof(string));\n\n// Iterate through data source object and fill the table\nforeach (var item in CollectionUserData)\n{\n    table.Rows.Add(item.FileNumber, item.ShiftDate, item.TimeCreated, item.Remarks);\n}	0
7956277	7956231	How to fetch entity model connection string?	private string GetADOConnectionString()\n{\n    var db = new DataBaseEntities();\n\n    EntityConnection ec = (EntityConnection)db.Connection;\n\n    return ec.StoreConnection.ConnectionString;\n}	0
6344195	6344152	How to set css properties to dynamically created table?	HtmlTable tbl = new HtmlTable();\ntbl.Attributes.Add("class","ClassName");	0
2760520	2760197	String Parsing in C#	var input = "(params (abc 1.3)(sdc 2.0)(www 3.05)....)";\nvar tokens = input.Split('(');\nvar typeName = tokens[0];\n//you'll need more than the type name (assembly/namespace) so I'll leave that to you\nType t = getStructFromType(typeName);\nvar obj = TypeDescriptor.CreateInstance(null, t, null, null);\nfor(var i = 1;i<tokens.Length;i++)\n{\n    var innerTokens = tokens[i].Trim(' ', ')').Split(' ');\n    var fieldName = innerTokens[0];\n    var value = Convert.ToDouble(innerTokens[1]);\n    var field = t.GetField(fieldName);\n    field.SetValue(obj, value);\n}	0
12294815	12294717	How do I call a method from SessionSwitch event in windows application using c#?	SystemEvents.SessionSwitch += HandleSessionSwitch;\n\n...\n\nprivate static void HandleSessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)\n{\n    // do something\n}	0
21563501	21563320	why identity number in ef jump to a big number?	SET IDENTITY_INSERT ON	0
18649034	18648976	return json object as a string in asp.net MVC	success: function (result) { alert(result.FirstName);}	0
21505782	21505685	Wait 500ms for user input with ability to cancel or restart	private CancellationTokenSource tokenSource;\n\nprivate async void button1_MouseEnter(object sender, EventArgs e)\n{\n    if (tokenSource != null)\n        tokenSource.Cancel();\n\n    tokenSource = new CancellationTokenSource();\n    try\n    {\n        await Task.Delay(500, tokenSource.Token);\n        if (!tokenSource.IsCancellationRequested)\n        {\n            //\n        }\n    }\n    catch (TaskCanceledException ex) { }\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    tokenSource.Cancel();\n}	0
6485317	6485300	How to terminate an asynchronous function in C#	webClient.CancelAsync();	0
12302117	12299859	Problems using ImageHelper to resize images on OpenNetCF with HTC T3333	IBitmapImage imageBitmap;\nImageInfo imageInfo;\nIImage image;\n\nvar imageFactory = new ImagingFactoryClass();\nimageFactory.CreateImageFromStream(new StreamOnFile(fileStream), out image);\nimage.GetImageInfo(out imageInfo);\n\n//verify we're a CF-supported image format\nif (imageInfo.PixelFormat != PixelFormat.Format16bppRgb555 \n    && imageInfo.PixelFormat != PixelFormat.Format16bppRgb565 \n    && imageInfo.PixelFormat != PixelFormat.Format24bppRgb \n    && imageInfo.PixelFormat != PixelFormat.Format32bppRgb)\n{\n    imageInfo.PixelFormat = PixelFormat.Format24bppRgb; \n}\n\nimageFactory.CreateBitmapFromImage(\n             image,  \n             (uint)width, \n             (uint)height, \n             imageInfo.PixelFormat, \n             InterpolationHint.InterpolationHintDefault, \n             out imageBitmap);\n\nvar bmp = ImageUtils.IBitmapImageToBitmap(imageBitmap);	0
11916305	11916256	Uploading a zip file to a database	var stream = new System.IO.MemoryStream();\n\nusing (ZipFile 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(stream);\n}\n\nbyte[] data = stream.ToArray();	0
4716993	4716950	compiling a visual studio solution file	Class Library	0
14339819	14339577	Bitmap XML Serialization	public byte[] MyImageBytes {\n    get {\n       ImageConverter converter = new ImageConverter();\n       return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));\n    }\n}	0
34312325	34309955	Own implementation of ICollection<T> in Entity Framework possible?	ICollection<T>	0
23663627	23663436	Unable to change text of textblock in Windows Phone 8.0	using System.Timers;\n\nclass myclass\n{\n    System.Timers.Timer timer;\n\n    public void initialise()\n    {\n        timer = new System.Timers.Timer(10000);\n        timer += new ElapsedEventHandler(_timer_Elapsed);\n    }\n\n    void _timer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n    timeHours.Text = DateTime.Now.Hour.ToString();\n    }\n}	0
13084869	13084503	Deserialize object from JSON Api WinRT	public static async Task<string> GetJsonString()\n{\n    HttpClient client = new HttpClient();\n    string url = @"https://api.stackexchange.com/2.1/answers?fromdate=1349913600&order=desc&min=20&sort=votes&site=stackoverflow";\n    HttpResponseMessage response = await client.GetAsync(url);\n\n    byte[] buf = await response.Content.ReadAsByteArrayAsync();\n    GZipStream zipStream = new GZipStream(new MemoryStream(buf), CompressionMode.Decompress);\n    StreamReader reader = new StreamReader(zipStream);\n    return reader.ReadToEnd();\n}	0
4068402	4068360	c# warning - Mark assemblies with NeutralResourcesLanguageAttribute	[assembly: NeutralResourcesLanguage("en")]	0
34010671	34010630	How to add my variable every time	internal static Beer Beer\n        {\n            get { return beer; }\n            set \n            { \n                beersList.Add(value);\n                beer = value; \n            }\n        }	0
33639386	33639006	Getting the first unused Id from a table?	SELECT\n    min(RN) AS FirstAvailableID\nFROM (\n    SELECT\n        row_number() OVER (ORDER BY Id) AS RN,\n        Id\n    FROM\n        YourTable\n    ) x\nWHERE\n    RN <> Id	0
12857782	12508019	Blur images shown in listview	Bitmap bmp = new Bitmap(64, 64);\nGraphics grfx = Graphics.FromImage(bmp);\n\ngrfx.DrawImage(\n    myImage,\n    (bmp.Width - myImage.Width) / 2,\n    (bmp.Height - myImage.Height) / 2);\n\nlistView.Items[0].Image = bmp;	0
1521236	1521157	Drawing vertically stacked text in WinForms	protected override void OnPaint(PaintEventArgs e)\n    {\n        float x = 10.0F;\n        float y = 10.0F;\n\n        string drawString = "123";\n\n        using(SolidBrush brush = new SolidBrush(Color.Black))\n        using (Font drawFont = new Font("Arial", 16))\n        {\n            foreach (char c in drawString.ToCharArray())\n            {\n                PointF p = new PointF(x, y);\n                e.Graphics.DrawString(c.ToString(), drawFont, brush, p);\n\n                y += drawFont.Height;\n            }\n        }\n        base.OnPaint(e);\n    }	0
9491196	9488704	Background keyboard shortcuts that do not propagate to windows	return CallNextHookEx(Hook, Code, wParam, ref lParam);	0
31941210	31941167	display byte[] array variable in textbox (as is)	textBox1.Text = String.Join(",", buf);	0
7690730	7690481	Linq: Count Groups of Rows Including 0 For Missing Rows	var firstDate = data.Min(d => d.Date).AddDays(-1);\nvar lastDate = data.Max(d => d.Date).AddDays(1);\n\nfor (var date = firstDate; date <= lastDate; date = date.AddDays(1))\n    if (!data.Exists(d => d.Date == date))\n        data.Add(new { Date = date, Count = 0 });\n\ndata = data.OrderBy(d => d.Date);\n// do something with data	0
7401886	7401786	How do I get an DataTable from IDataReader?	// Load the data into the existing DataSet. \n    DataTableReader reader = GetReader();\n    dataSet.Load(reader, LoadOption.OverwriteChanges,\n    customerTable, productTable); \n\n    // Load the data into the DataTable.\n    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);\n    DataTable dt = new DataTable();\n    dt.Load(dr);	0
867100	866487	How to retrieve info on a loaded assembly at runtime? (c# , .NET)	var names = Assembly.GetExecutingAssembly().GetReferencedAssemblies();	0
2423607	2423584	Deleting an Image that has been used by a WPF control	BitmapImage bi = new BitmapImage();\nbi.BeginInit();\nbi.DecodePixelWidth = 30;\nbi.StreamSource = byteStream;\nbi.EndInit();	0
22371588	22371480	refresh form1 gridview from form2 after inserting the rows	GridView1.DataBind();	0
21524390	21524207	Accessing elements of Unity (.config) file via XElement	XElement root = XElement.Load(new XmlTextReader(@"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config");\n\nif(root != null)\n{\n    XNamespace ns = "http://schemas.microsoft.com/practices/2010/unity";\n\n    var registers = root\n        .Element(ns + "unity")\n        .Element(ns + "container")\n        .Descendants(ns + "register");\n\n    var tipList = registers.Select(x => x.Attribute("type").Value);\n    var mapToList = registers.Select(x => x.Attribute("mapTo").Value);\n}	0
7872412	7870492	How to Filter by Id	RAMDirectory dir = new RAMDirectory();\nIndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true);\nfor (int i = 0; i < 20; i++)\n{\n    Document doc = new Document();\n    doc.Add(new Field("field1", "some text " + i.ToString(), Field.Store.YES, Field.Index.ANALYZED));\n    doc.Add(new Field("ID", i.ToString(), Field.Store.YES, Field.Index.ANALYZED));\n    writer.AddDocument(doc);\n}\nwriter.Close();\n\nIndexReader reader = IndexReader.Open(dir);\n\nLucene.Net.Search.Similar.MoreLikeThisQuery mltq = new Lucene.Net.Search.Similar.MoreLikeThisQuery("text", new string[] { "field1" }, new WhitespaceAnalyzer());\n\nBooleanQuery bq = new BooleanQuery();\nbq.Add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);\nbq.Add(new TermQuery(new Term("ID","15")),BooleanClause.Occur.MUST_NOT);\nFilter filter = new CachingWrapperFilter(new QueryWrapperFilter(bq));\n\nTopDocs td =  new IndexSearcher(reader).Search(mltq, filter, 100);\nDebug.Assert(td.TotalHits == 19);\n\nreader.Close();	0
9261652	9260234	Linq to entity: How to groupby date part of datetime	int recordsPerPage = 10, currentIndex = 0;\nvar groupQuery =\n    myDC.Flights.\n    GroupBy(f => EntityFunctions.TruncateTime(f.Arrival)).\n    Skip(recordsPerPage * currentIndex).\n    Take(recordsPerPage);	0
28593617	28588937	Upload a file to a server using ASP.NET and C#	public void ProcessRequest(HttpContext context)\n {\n    context.Response.ContentType = "text/plain";\n    HttpPostedFile postedFile = context.Request.Files["Filedata"];\n    string filename = postedFile.FileName;\n    var Extension = filename.Substring(filename.LastIndexOf('.') \n    + 1).ToLower();\n\n    string savepath =HttpContext.Current.Server.MapPath("/images/profile/");\n\n    postedFile.SaveAs(savepath + @"\" + user.uid + filename);\n }	0
7349579	7349497	Help convert SQL statement to LINQ Lambda (need help with group by and sum)	var q = context.TableName\n           .GroupBy(x => x.Date)\n           .Select(g => new { \n               Date = g.Key,\n               Counted = g.Sum(x => x.Counted), \n               Time = g.Sum(x => x.Time)\n           });	0
14994051	14994024	How to make C# login to website	string string loginData = "username=***&passowrd=***&next=/hurt/";\n\nWebClient wc = new WebClient();\n\nwc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");\nwc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");\nwc.Headers.Add("Accept-Encoding", "identity");\nwc.Headers.Add("Accept-Language", "en-US,en;q=0.8");\nwc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");\nwc.Headers.Add("ContentType", "application/x-www-form-urlencoded");\nstring response = wc.UploadString("http://xyz.com/accounts/login/", "POST", loginData);	0
5376921	5376883	How to unit-test that the logger was called with the correct localizable, formatted string?	params object[] args	0
31469828	31469759	Getting JSON data member from class	public class Issue\n{                          \n    public string key { get; set; }\n}\n\n\npublic class search\n{\n    public IList<Issue> issues { get; set; }\n}\n\nprivate static void Main(string[] args) {\n\n    search s = new search();\n\n    s.issues.Add(new Issue()); // YOU HAVE THREE ISSUES\n    s.issues.Add(new Issue());\n    s.issues.Add(new Issue());\n\n\n    var x=s.issues[0].key; // YOU ACCESS 1st one\n    x = s.issues[2].key; // YOU ACCESS 3rd one (zero based)\n\n\n}	0
13561624	13561606	How can I change the first two characters of a string to "01" with C#?	var res = "01" + abc.Substring(2);	0
4493724	4493640	WebBrowser Control - Prevent Right-Click	webBrowser1.IsWebBrowserContextMenuEnabled = false;\n        webBrowser1.AllowWebBrowserDrop = false;	0
7200330	7200259	Fetching a segment of the URL in the address bar	var lastSegment = url\n    .Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)\n    .ToList()\n    .Last();	0
25203891	25203747	How can I manipulate DataGrid values when testing with TestStack.White?	distributionGrid.Rows[0].Cells[0].Value = firstName;	0
4819168	4818745	How can I tell the compiler to ignore a method in stack traces in c#?	System.NotImplementedException: The method or operation is not implemented.\n   at ConsoleApplication1.Program.ThrowMe() in C:\Users\hpassant\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 9\n   at ConsoleApplication1.Program.Main(String[] args) in C:\Users\hpassant\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 17	0
31827646	31827583	C# parse Collection of items returned from PowerShell Command	var principalNames = (List<string>)xx.Properties["ServicePrincipalNames"].Value;\nforeach(var principalName in principalNames) {...}	0
24394325	24041372	Windows 8 start screen tile, based on desktop shortcut	function GetPropertyKeyCanonicalName(const AKey: TPropertyKey): UnicodeString;\nvar\n  PropertySystem: IPropertySystem;\n  PropertyDescription: IPropertyDescription;\n  N: PWideChar;\nbegin\n  Result := '';\n  if Succeeded(CoCreateInstance(CLSID_IPropertySystem, nil, CLSCTX_INPROC_SERVER, IPropertySystem, PropertySystem)) then\n    try\n      if Succeeded(PropertySystem.GetPropertyDescription(AKey, IPropertyDescription, PropertyDescription)) then\n        try\n          if Succeeded(PropertyDescription.GetCanonicalName(N)) then\n            try\n              Result := N\n            finally\n              CoTaskMemFree(N);\n            end;\n        finally\n          PropertyDescription := nil;\n        end;\n    finally\n      PropertySystem := nil;\n    end;\nend;	0
25145116	25144054	How to get app version in Windows Universal App?	string appVersion = string.Format("Version: {0}.{1}.{2}.{3}",                          \n                    Package.Current.Id.Version.Major, \n                    Package.Current.Id.Version.Minor, \n                    Package.Current.Id.Version.Build,\n                    Package.Current.Id.Version.Revision);	0
4153050	4152834	Providing links to page sections via textblocks or similar in WPF?	FrameworkElement.BringIntoView	0
5349156	5348073	How to get Primary and foreign Key details from MS Access database	1. SELECT * FROM ALL_CONS_COLUMNS A \n      JOIN ALL_CONSTRAINTS C ON A.CONSTRAINT_NAME = C.CONSTRAINT_NAME \n      WHERE C.TABLE_NAME = <your table> AND C.CONSTRAINT_TYPE = 'P'\n   2.  SELECT * FROM ALL_CONS_COLUMNS A \n       JOIN ALL_CONSTRAINTS C  ON A.CONSTRAINT_NAME = C.CONSTRAINT_NAME \n       WHERE C.TABLE_NAME = <your table> AND C.CONSTRAINT_TYPE = 'R'	0
32637630	32637348	TimeSpan or DateTime for hour and minute as parameters to parse into Ticks	var ticks = new TimeSpan(hours, minutes, 0).Ticks;	0
9575559	9575522	Regex string for sample strings	string pattern = @"^(?<text>.+?)(\((?<count>\d+)\))?$";\nMatch m = Regex.Match(line, pattern);\ncount = 0;\ntext = "";\nif (m.Success)\n{\n    text = m.Groups["text"].Value.Trim();\n\n    if(m.Groups["count"].Success) {\n        int.TryParse(m.Groups["count"].Value, out count);\n    }\n}	0
15108571	15108525	Handle Open Square Bracket in NHibernate query for SQL Server	query.SetAnsiString("text", "%" + filter.Text.Replace("[", "[[]") + "%");	0
30108609	30108366	Oxyplot Model Handle Key Press	this.Model.KeyDown += ModelOnKeyDown;\n\nprivate void ModelOnKeyDown(object sender, OxyKeyEventArgs e)\n{\n     if (e.Key == OxyKey.Up)\n     {\n        // Do Some Stuff\n     }\n     else if (e.Key == OxyKey.Down)\n     {\n         // Do Some Stuff\n     }\n }	0
18626631	18479826	How to Change the Color of Application Bar Buttons when Pressed	ApplicationBar.Foreground = new SolidColorBrush(Color.FromArgb(255, 254, 254, 254));	0
27128574	27127403	Get and Set XML elements with Namespaces	string xml = "<Root><Options></Options></Root>";\n\nvar xdocs = XDocument.Parse(xml);\n\nxdocs.Descendants().Where(q => q.Name == "Options").FirstOrDefault().Value = "FoundIt";	0
16832608	16831790	Get Thumbnail from a smooth streaming file (.ism)	var panelPoint = this.MyPanel.PointToScreen(new Point(this.MyPanel.ClientRectangle.X, this.MyPanel.ClientRectangle.Y));\n        using (var bitmap = new Bitmap(320, 240))\n        {\n            using (var graphics = Graphics.FromImage(bitmap))\n            {\n                graphics.CopyFromScreen(320, Point.Empty, new Size(320, 240));\n            }\n\n            if (SimpleIoc.Default.ContainsCreated<ICommonApplicationData>())\n            {\n                var imageGuidName = Guid.NewGuid();\n                fileName = Path.Combine("C:\", "TestFolder", imageGuidName + ".jpg");\n                bitmap.Save(fileName, ImageFormat.Jpeg);\n                var tempBitmapImage = new BitmapImage();\n                tempBitmapImage.BeginInit();\n                tempBitmapImage.UriSource = new Uri(fileName);\n                tempBitmapImage.EndInit();\n                image.Source = tempBitmapImage;\n            }\n        }	0
10558736	3627658	Changing font (Trebuchet MS, Calibari) in Excel programmatically C#	//Declare Excel Interop variables\n    Microsoft.Office.Interop.Excel.Application xlApp;\n    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;\n    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;\n\n    //Initialize variables\n    xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();\n    xlWorkBook = xlApp.Workbooks.Add(misValue);\n    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n\n    //Set global attributes\n    xlApp.StandardFont = "Arial Narrow";\n    xlApp.StandardFontSize = 10;	0
19561538	19561521	How to format SQL query without using string +	string query= @"SELECT *  \n                  FROM product p \n                  JOIN order   o ON p.productID = o.productID";	0
1317191	1317177	Jquery/javascript datetime	getDateFromFormat()	0
22721799	22721681	Create input table parameter for calling oracle stored procedure in C#	System.Data.OracleClient	0
20634935	20634723	How to select multiple items in multilistpicker windows phone 8	listpicker.SelectedItems = List<your selected items>;	0
16244723	16244310	Partial String in array of strings	string [] arr = {"ABC_DEF_GHIJ", "XYZ_UVW_RST"};\n        for (int i = 0; i < arr.Length; i++)\n            if (arr[i].Contains("ABC_DEF"))\n                return i; // or return arr[i]	0
4141425	4141405	Read a file that was created	string[] lines = File.ReadAllLines("filename.txt");\nlabel6.Text = String.Join(Environment.NewLine, lines);	0
13566453	13566302	Download large file in small chunks in C#	int read;\ndo\n{\n    read = responseStream.Read(bytesInStream, 0, (int)bytesInStream.Length);\n    if (read > 0)\n        fileStream.Write(bytesInStream, 0, read);\n}\nwhile(read > 0);	0
25453622	25453600	How can I create a for loop that uses base 16?	for(int i = 0; i < 0xFFFF; i++)\n{\n    // do work\n}	0
12743491	12742824	Set header in Excel for worksheet 2	Excel.Range headerRange = xlWorkSheet1.get_Range("A1", "V1");\nheaderRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;\nheaderRange.Value = "Header text 1";\n\nheaderRange = xlWorkSheet2.get_Range("A1", "V1");\nheaderRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;\nheaderRange.Value = "Header text 2";	0
10007910	10007762	Hook a custom function for label's click event	List<int> _list1 = new List<int>(); //1, 2, 3, 4, 5\n\nforeach (var item in _list1)\n{\n    // take copy of loop variable to avoid closing over the loop variable\n    int i = item; \n    Label lb = new Label { Text = item.ToString() };\n    lb.Click += (x,y) => CustomFunction(i);\n}\n\nvoid CustomFunction(int item)\n{\n}	0
20803966	20803529	how do i get a game object to apply changes to a prefab in script	public static Material BallMaterial = null;   // or you can assign a Material that will act as InitialState	0
31258055	31257654	populating a dictionary of objects, from objects written separately in a file C#	WriteToBinaryFile(file, dict, false)	0
33521456	33521368	How to execute a stored Procedure in a webApi using EntityFramework with a single input parameter	public IEnumerable<StudentDetailss_result> GetStudentDetails(string routeId)\n{\n    using(var ctx = new YourContextHere())\n    {\n        var result = ctx.StudentDetailss(routeId);\n        return result.ToList();\n    }\n}	0
31767323	31767071	Get object from IHttpActionResult response c#	var blob = JsonConvert.DeserializeObject<BlobUploadModel>(responseBody);	0
23688665	23687420	Required Byte[] on View Model	if (fthumbnail == null || fthumbnail == null)\n{\n    ModelState.AddModelError("_FORM", "Your little error message to the user.");\n    return View(classdetail);\n}	0
8491418	8490736	How to check in for a value in DB through jquery	public string GetValueFromDB()\n    {\n        if(value is there)\n          return "your result"; \n        return "emptystring";\n    }	0
1362097	1361695	How to Access attachments from Notes mail?	NotesRichTextItem rtitem = doc.GetFirstItem("name")\nif ( rtitem.Type = 1) {\n  foreach (NotesEmbeddedObject o in rtitem.EmbeddedObjects) {\n    if ( o.Type = 1454 ) {\n      o.ExtractFile( "c:\samples\" & o.Source )\n    }\n  }\n}	0
27562672	27562002	Implementing the Right GUI Behavior for Form_Find	Form f1;\nvoid Main()\n{\n    f1 = new Form();\n    TextBox t1 = new TextBox();\n    t1.Location = new Point(0,0);\n    TextBox t2 = new TextBox();\n    t2.Location = new Point(0,30);\n    f1.Controls.AddRange(new Control[] {t1,t2});\n    f1.Deactivate += onDeactive;\n    f1.Show();\n\n    Form f2 = new Form();\n    Button b = new Button();\n    b.Click += bClick;\n    f2.Controls.Add(b);\n\n    // This line pass the F1 form\n    // as owner of F2 establishing the \n    // correct parent/child behavior\n    f2.Show(f1);\n}\n\nvoid bClick(object sender, EventArgs e)\n{\n    Console.WriteLine("Clicked");\n    f1.ActiveControl.Text = DateTime.Now.ToString("hh:mm:ss");\n}\nvoid onDeactive(object sender, EventArgs e)\n{\n    Console.WriteLine("Main Deactivated");\n}	0
11207457	11207297	How to make the header font bold while exporting dataset to excel?	dataExportExcel.HeaderStyle.Font.Bold=true;	0
753261	753247	How to form this Regex	(?<!r)-	0
19329623	19329351	Delete file using querystring and name from database	protected void Page_Load(object sender, EventArgs e)\n{\n    ....\n\n    if (reader.Read())\n    {\n        billedeID.Text = reader["Id"].ToString();\n        billedenavn.Text = reader["imgnavn"].ToString();\n        ViewState["imgnavn"] = reader["imgnavn"].ToString();\n    }\n\n    ....\n}\n\nprotected void sletBtn_Click(object sender, EventArgs e)\n{\n    try\n    {\n\n        string imageName = ViewState["imgnavn"].ToString();    \n\n        // slet Originalfilen i image/upload/Original/ mappen\n        File.Delete(Server.MapPath("~/upload/originals/" + imageName));\n\n        // Slet Thumbsfilen i /Images/Upload/Thumbs/\n        File.Delete(Server.MapPath("~/upload/thumbs/" + imageName));\n\n        // Slet Resized_Original i /Images/Upload/Resized_Original/ mappen\n        File.Delete(Server.MapPath("~/upload/originalsResized/" + imageName));\n\n        ...\n    }\n\n    ...\n}	0
5198907	5198802	how to copy all *.bak files from Directory A to Directory B?	string dirA = @"C:\";\nstring dirB = @"D:\";\n\nstring[] files = System.IO.Directory.GetFiles(dirA);\n\nforeach (string s in files) {\n    if (System.IO.Path.GetExtension(s).equals("bak")) {\n        System.IO.File.Copy(s, System.IO.Path.Combine(targetPath, fileName), true);\n    }\n}	0
33756545	33756257	Simple Injector - Inject specific implementation of interface to specific controller	container.RegisterConditional<ITeamRespository, SoccerRepository>(\n    c => c.Consumer.ImplementationType == typeof(SoccerController));\n\ncontainer.RegisterConditional<ITeamRespository, FallbackRepository>(c => !c.Handled);	0
11068310	11067653	Measurement unit conversion + data binding	private float _celsius;\n\npublic float Fahrenheit {\n    get { return _celsius * 1.8f + 32.0f }\n    set \n    { \n        float cels = (((value - 32.0f) * 5.0f) / 9.0f);\n        if (cels != _celsius)\n        {\n            _celsius = cels;\n            TempPropertiesChanged();\n        }\n    }\n}\n\npublic float Celsius\n{\n    get { return _celsius; }\n    set\n    {\n        if (value != _celsius)\n        {\n            _celsius = value;\n            TempPropertiesChanged();\n        }\n    }\n}\n\nprivate void TempPropertiesChanged()\n{\n   OnPropertyChanged("Fahrenheit");\n   OnPropertyChanged("Celsius");\n}	0
8721307	8721265	HelloWorld Multithreaded C# app	using System;\nusing System.Threading;\n\n\npublic class ThreadTest {\n\n    public static void Main () {\n\n        Thread t=new Thread(WriteString);\n        t.Start("y");\n        Thread u=new Thread(WriteString);\n        u.Start("x");\n\n        t.Join();\n        u.Join();\n\n    }\n\n    public static void WriteString (Object o) {\n\n        for (Int32 i=0;i<1000;++i) Console.Write((String)o);\n\n    }\n\n}	0
22998895	22995036	How to use automapper with complex types	Mapper.CreateMap<string, ModelProperty<string>>()\n    .ConvertUsing(src => new ModelProperty<string> { Value = src });	0
14877170	14876899	Gridcontrol return value	public static class MyClass\n{\n    public static object myValue;\n}\n\n\nprivate void label14_Click(object sender, EventArgs e)\n{\n    frmSelectInvoice selectInvoice = new frmSelectInvoice();\n    selectInvoice.ShowDialog();  \n    //Get value before close\n    object value = MyClass.myValue;\n}\n\n\n\npublic partial class frmSelectInvoice : DevExpress.XtraEditors.XtraForm\n{\n    public ValinorEntities valinor;\n    public BindingSource src;\n\n    public frmSelectInvoice()\n    {\n        InitializeComponent();\n\n        using (this.valinor = new ValinorEntities())\n        {\n            this.valinor = new ValinorEntities();\n            this.src = new BindingSource(valinor.invoices_head, null);\n            gridControl1.DataSource = src;\n            src.DataSource = valinor.invoices_head;\n        }\n    }\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    //Set value after close\n    MyClass.myValue = "value";\n    this.Close();       \n}	0
14736975	14736789	Oracle MERGE from external data source	merge into target_table t\nusing load_table l on (t.key = l.key) -- brackets are mandatory\nwhen matched then update\nset t.col = l.col\n,   t.col2 = l.col2\n,   t.col3 = l.col3\nwhen not matched then insert\n(t.key, t.col, t.col2, t.col3)\nvalues\n(l.key, l.col, l.col2, l.col3)	0
23192875	23192352	Comparing user Input to data in comma-delimited file and return data from file if matches input	public string MatchedName(string input)\n{\n    const int nameColumnIndex = 0;\n    const string matchFile = @"C:\matchedfile.txt";\n\n    string normalizedInput = RemoveCharTab(input);\n\n    string[] names = File.ReadAllLines(matchFile)\n                         .Select(l => l.Split(',')[nameColumnIndex])\n                         .Select(s => s.Trim())\n                         .ToArray();\n    return names.FirstOrDefault(n => string.Equals(RemoveCharTab(n), normalizedInput)) ?? input;\n}	0
25908410	25886800	Setting WPF Delay from code in MVVM	public class QuestionTextViewModel : QuestionItemViewModel\n{\n    private Timer Timer { get; set; }\n\n    public QuestionTextViewModel(IEventAggregator eventAggregator, TransactionDetail transactionDetail)\n        : base(transactionDetail)\n    {\n        _eventAggregator = eventAggregator;\n        TransactionDetailId = transactionDetail.TransactionDetailId;\n        this.Timer = new Timer(1500) {AutoReset = false};\n        this.Timer.Elapsed += TextValueTimer_Elapsed;\n    }\n\n    public string TextValue\n    {\n        get { return _textValue; }\n        set\n        {\n            _textValue = value;\n            this.Timer.Stop();\n            this.Timer.Start();\n        }\n    }\n\n    private void TextValueTimer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        NotifyOfPropertyChange(() => TextValue);\n    }\n}	0
6859646	6859574	Microsoft Office Interop Excel - Specify name of Excel file	_book.SaveAs(outputPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, \n                            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);	0
4399065	4398976	how to typecast the value of gridviewrow.cells[i] value into int32?	int myVal = Int32.Parse(GridViewRow.Cells[i].Text);	0
14283553	14276780	Disable-Mailbox cmdlet from C#	powerShell.Streams.Error	0
1970750	1970738	Convert System.Array to string[]	string[] foo = someObjectArray.OfType<object>().Select(o => o.ToString()).ToArray();	0
17572282	17572213	Replace foreach loop with linq	mpwrapper.parser.Discoveries.ToList().ForEach(s => { solution.AddFile("Discoveries", s.DisplayStringName + ".mpx", s); });	0
18483383	18481665	Store values in C# and populate in Javascript	sb.Append("var obj = {text:'" + Engine[i][0] + "',"  + "value:" + Engine[i][1] +"};");	0
24998029	24997936	Selenium Webdriver/ C# - how to confirm page load after clicking?	wait.Until(ExpectedConditions.ElementExists(locator));\nwait.Until(ExpectedConditions.ElementIsVisible(locator));	0
10692368	10683366	Set Display Text Of ComboBox In Datagridview	dgv_col.DataPropertyName="name"\ndgv_col.DisplayMember="name"\ndgv_col.ValueMember="id"	0
25998772	25761783	Horizontal Lines appearing in ContentDialog view	_contentDialog = new ContentDialog();\n        _contentDialog.Background = new SolidColorBrush(Colors.Transparent);	0
5031537	5031274	Does IDbCommand get disposed from within a class that implements IDisposable?	public int CreateFoo()\n{\n    using (var cn = new MySqlConnection(connString))\n    {\n        // Notice that the cmd here is not wrapped in a using or try-finally.\n        using (IDbCommand cmd = CreateCommand("create foo with sql", cn))\n        {\n            cn.Open();\n            return int.Parse(cmd.ExecuteScalar().ToString());\n        }\n     }\n}	0
29326908	29326759	Access to Internet in Background	BackgroundTaskDeferral _deferral;\n\npublic async void Run(IBackgroundTaskInstance taskInstance)\n{\n    _deferral = taskInstance.GetDeferral();\n    // your async code\n    _deferral.Complete();\n}	0
26887855	25458678	Consuming user profile properties in Master Pages	{\n        string firstname;\n\n        ApplicationDbContext db = new ApplicationDbContext();\n        UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);\n        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);\n\n        ApplicationUser user = userManager.FindByName(HttpContext.Current.User.Identity.Name);\n\n        firstname = user.FirstName;                              \n\n\n        return firstname;\n    }	0
13874838	13874808	How to Thread.Sleep in BeginInvoke	Thread t1 = new Thread(new ThreadStart(\ndelegate()\n{\n    for (int i = 1; i < 11; i++)\n    {\n    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n        new Action(delegate()\n            {                        \n                    mytxt1.Text = "Counter is: " + i.ToString();                           \n\n            }));\n     Thread.Sleep(1000);\n     }             \n}));\nt1.Start();	0
19565758	19565589	Getting error while converting a string to datetime format in c#	string formatDB ="YYYY/MM/dd";\nDateTime.Now.ToString(formatDB);	0
12185472	12185053	What's the best practice in executing a stored procedure with multiple parameters using MVC3?	var column = "Name";\nvar value = "Marvin";\nvar query = DbCtx.MyEntity.Where("{0} == @1", columnName, value);	0
17155113	17155076	Lambda to extract some integers?	List<int> A = ServiceItems.First().\n    ServiceItemDetails.Select(x => x.Numbers).ToList();	0
26941610	26941573	How to change the properties of a textbox in C#?	textBox1.TextAlign = HorizontalAlignment.Center;\ntextBox1.TextAlign = HorizontalAlignment.Right;\ntextBox1.TextAlign = HorizontalAlignment.Left;	0
11204276	11204209	Winforms SQL Database App - How to group database transactions	try\n{\n    // Encapsulate your data access code in this using\n    using (TransactionScope scope = new TransactionScope())\n    {\n\n\n        .....\n\n        scope.Completed();\n    }\n}	0
14621929	14614809	Refresh converted bindings in WPF ListView	ICollectionView view = CollectionViewSource.GetDefaultView(MyListView.ItemsSource);\nview.Refresh();	0
3480534	3480498	best way to find webcontrols quickly	TextBox ControlId = (TextBox) FindControl("ControlId")	0
19670971	19591157	GetVstoObject fails with AccessViolationException	public Microsoft.Office.Tools.Excel.Workbook CurrentWorkbook\n{\n  get\n  {\n    return GetVSTOWorkbookByInteropWorkbook(Globals.ThisAddIn.Application.ActiveWorkbook);\n  }\n}\n\n[HandleProcessCorruptedStateExceptions]\npublic static ExcelVSTO.Workbook GetVSTOWorkbookByInteropWorkbook(ExcelInterop.Workbook workbook)\n{\n    if (workbook == null) return null;\n\n    try\n    {\n        return Globals.Factory.GetVstoObject(workbook);\n    }\n    //This also catches unhandled "AccessViolationException" in the VSTO layer because \n    //we have decorated the method by the annotation [HandleProcessCorruptedStateExceptions].\n    catch (AccessViolationException ex)\n    {\n        //Handle exception...\n    }\n}	0
2613471	2613384	How to use Linq to select and group complex child object from a parents list	var query = orderList.SelectMany( o => o.OrderLineList )\n                        // results in IEnumerable<OrderProductVariant>\n                      .Select( opv => opv.ProductVariant )\n                      .Select( pv => p.Product )\n                      .GroupBy( p => p )\n                      .Select( g => new {\n                                    Product = g.Key,\n                                    Count = g.Count()\n                       });	0
2242607	2242564	File count from a folder	System.IO.Directory myDir = GetMyDirectoryForTheExample();\nint count = myDir.GetFiles().Length;	0
10832941	10832567	Convert integer number to three digit	int X = 9;\n\nstring PaddedResult = X.ToString().PadLeft (3, '0'); // results in 009	0
12871432	12871087	Convert WGS84(Degrees, Minutes, seconds) To Decimal Degrees	public decimal DmsToDD(double d, double m = 0, double s = 0)\n{\n    return Convert.ToDecimal((d + (m/60) + (s/3600))*(d < 0 ? -1 : 1));\n}	0
9051225	9051220	How to match a string pattern like AB12 with c# Regex	[A-Za-z]{1,3}[1-9]\d*	0
2736917	2736846	Detecting webhost server	string serverName = Request.ServerVariables["SERVER_NAME"];\nstring httpHost = Request.ServerVariables["HTTP_HOST"];	0
4650961	4650899	How to count number of XML nodes that contain specific value	XmlDocument readDoc = new XmlDocument();\nreadDoc.Load(MapPath("Results.xml"));\nint count = readDoc.SelectNodes("root/User").Count;\nlblResults.Text = count.ToString();\nint NoCount = readDoc.SelectNodes("JSEnabled[. = \"No\"]").Count;	0
10602574	9986292	How to force validation errors update on View from ViewModel using IDataErrorInfo?	myControl.GetBindingExpression(ControlType.ControlProperty).UpdateSource();	0
10835252	10835215	How can I cast object dynamically?	private dynamic obj;	0
25638794	25638084	How to disable page animation while loading in WP 8.1?	public MyPage()\n{\n    this.InitializeComponent();\n    Frame myFrame =(Frame)Window.Current.Content;\n    myFrame.ContentTransitions = null;\n}	0
22516932	22516870	Calculating decimal property total of a generic list	var totalValue = lstParts.Sum(x => x.PartStockAvailable * x.mPartPrice);	0
6170804	6170438	Resize embedded user controls in a panel C#	this.Dock = DockStyle.Fill;	0
22175471	22175376	How to convert enum to list with where statement	List<string> list = Enum.GetValues(typeof(Statement))\n                        .Cast<Statement>()\n                        .Where(r=> (int) r != 1)\n                        .Select(t=> t.ToString())\n                        .ToList();	0
16551604	16551415	Dynamic-length array using Singleton	public class mySingleton\n{\n    private static int _dataSize;    // you might want to set this to some sensible default\n    public static int DataSize \n    { \n        get { return _dataSize; }\n        set \n        { \n            _dataSize = value;\n            _dataSet = null;        // changing the size will implicitly clear the array - but you could write code to resize if you really wanted to\n        }\n    }\n    private static double[] _dataSet;\n    public static double[] DataSet \n    { \n        get \n        {\n            if (_dataSet == null) \n            {\n                _dataSet = new double[_dataSize];\n            }\n            return _dataSet;\n        }\n        // you can include a setter if you want to let the consumer set the dataset directly - in which case it should update the _dataSize field.\n    }               \n}	0
19874075	19873761	c# reflection parameter count mismatch	internal SearchResult(System.Net.NetworkCredential parentCredentials,\n                         System.DirectoryServices.AuthenticationTypes parentAuthenticationType);	0
12149172	12148552	how to turn ExpressionStatementSyntax into ParenthesizedExpressionSyntax (put parentheses around expression)	using System;\nusing System.Linq;\nusing Roslyn.Compilers;\nusing Roslyn.Compilers.CSharp;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var oldRootNode = Syntax.ParseCompilationUnit(\n            "class C { void M() { \"\".GetType(); } }");\n        var oldStatementNode = oldRootNode.DescendantNodes().OfType<ExpressionStatementSyntax>().First();\n        var oldExpressionNode = oldStatementNode.Expression;\n        var newExpressionNode = Syntax.ParenthesizedExpression(oldExpressionNode);\n        var newRootNode = oldRootNode.ReplaceNode(oldExpressionNode, newExpressionNode);\n        Console.WriteLine(oldRootNode.ToString());\n        Console.WriteLine(newRootNode.ToString());\n    }\n}	0
32876410	32876357	Counting the total XML-files in a directory	namespace Jobbuppgift1\n{\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    string path1 = "c:\\Jobbuppg";//this or line below\n    string path1 = @"c:\Jobbuppg";//this or line above\n\n    private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        int fileCount = Directory.GetFiles(path1, "*.xml", SearchOption.AllDirectories).Length;\n        textBox1.Text = fileCount.ToString();\n    }\n}	0
32779990	32762553	Links does not open my page in my masterpage's contentPlaceHolder but in a new tab	string target="_Blank";	0
28447526	28447461	Creating a list with values directly inside function parameters	MyFunction(new List<float> { 3.0f, 4.0f });	0
14185049	14184191	Finding fastest path at additional condition	src/solver.py	0
16975882	16330792	C# Linq To Excel Getting Table Data Not Starting In The First Row	var details = from c in excel.WorksheetRange<ContributionScheduleExcelFormat>("A3", "G16000") select c;	0
20555003	20554812	Showing every element in an IEnumberable HtmlElement collection	private static void PrintObject(IEnumerable<HtmlElement> propertyElements)\n{\n    Console.WriteLine("---------------------------------");\n    foreach (HtmlElement element in propertyElements)\n    {\n        Console.WriteLine(element.OuterHtml);\n        //or\n        Console.WriteLine(element.Name);\n        //or\n        Console.WriteLine(element.InnerHtml);\n        //or\n        Console.WriteLine(element.TagName);\n    }\n    Console.WriteLine("---------------------------------");\n}	0
21602440	21601981	Extract info from mail using regex	var fromAddress = new string(msg.SkipWhile(c => c != '<').Skip(1).TakeWhile(c => c != '>').ToArray());\n\nvar toAddress = new string(msg.Substring(msg.IndexOf("To")).SkipWhile(c => c != '<').Skip(1).TakeWhile(c => c != '>').ToArray());\n\nvar subject = new string(msg.Substring(msg.IndexOf("Subject")).SkipWhile(c => c != ' ').Skip(1).TakeWhile(c => c != 'T').ToArray());	0
25560948	25559897	Serialize/Deserialize a dynamic object	public static bool Save(Animal animal)\n    {\n        var lListOfAnimals = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()\n                         from lType in lAssembly.GetTypes()\n                         where typeof(Animal).IsAssignableFrom(lType)\n                         select lType).ToArray();\n\n        System.Xml.Serialization.XmlSerializer ListSer = new System.Xml.Serialization.XmlSerializer(typeof(Animal), lListOfAnimals);	0
32398264	32398016	Prevent DateTimePicker2 to go under the date set by DateTimePicker1	private void dtpFromDate_ValueChanged(object sender, EventArgs e)\n    {\n        //Set the min date of the to date when the from date is changed\n        dtpToDate.MinDate = dtpFromDate.Value;\n    }\n\n    private void dtpToDate_ValueChanged(object sender, EventArgs e)\n    {\n        //set the to date to the date selected, or the 'from' date if the 'to' date is lower\n        //(if this) ? (then this) : (otherwise this)\n        dtpToDate.Value = dtpToDate.Value < dtpFromDate.Value ? dtpFromDate.Value : dtpToDate.Value;\n    }	0
3233882	3233869	Storing a Function to Run Later	private void Test(object bar)\n{\n    // Using lambda expression that captures parameters\n    Action forLater = () => foo(bar);\n    // Using method group directly\n    Action<object> forLaterToo = foo;\n    // later\n    forLater();\n    forLaterToo(bar);\n}\n\nprivate void foo(object bar)\n{\n    //...\n}	0
24641680	24639255	Dynamically Creating a popup window without jquery	ClientScript.RegisterStartupScript(GetType(), "failed", string.Format("alert({0});", AntiXss.JavaScriptEncode(error)), true);	0
30728025	30727971	Custom Exception: customize message before call the base constructor	public class ThirdPartyServiceException : System.Exception\n{\n    public ThirdPartyServiceException(string code, string message, string description, Exception innerException)\n    :base(string.format("Error: {0} - {1} | {2}", code, message, description), innerException) \n    {        \n    }\n}	0
24160398	24160356	Windows Store App - XAML - C# - Access ThemeResource in code	Application.Current.Resources[ "MyColour" ] as SolidColorBrush	0
17168999	17168961	How do I escape " in verbatim string?	string s2 = @"This is \t a ""verbatim"" string";	0
15805716	15805688	how to prevent disabled checkboxes of gridview from getting checked when select all checkbox is clicked?	if (objRef.checked && !inputList[i].disabled) {\n           inputList[i].checked = true;\n }\n else {\n       inputList[i].checked = false;\n }	0
29352746	29305189	Deserialize JSON with RESTSharp C#	public class Event\n{\n    public int id { get; set; }\n    public string name { get; set; }\n    public string datefrom { get; set; }\n    public string timeto { get; set; }\n    public string price { get; set; }\n    public string imagen { get; set; }\n    public string desc { get; set; }\n    public string info { get; set; }\n    public int user { get; set; }\n    public int place { get; set; }\n    public string dateto { get; set; }\n    public List<object> Eventcategories { get; set; }\n}\n\npublic class EventResponse\n{\n    public List<Event> Events { get; set; }\n}	0
516817	516794	How to run a sp from a C# code?	public int Insert(Person person)\n{\nSqlConnection conn = new SqlConnection(connStr);\nconn.Open();\nSqlCommand dCmd = new SqlCommand("InsertData", conn);\ndCmd.CommandType = CommandType.StoredProcedure;\ntry\n{\ndCmd.Parameters.AddWithValue("@firstName", person.FirstName);\ndCmd.Parameters.AddWithValue("@lastName", person.LastName);\ndCmd.Parameters.AddWithValue("@age", person.Age);\nreturn dCmd.ExecuteNonQuery();\n}\ncatch\n{\nthrow;\n}\nfinally\n{\ndCmd.Dispose();\nconn.Close();\nconn.Dispose();\n}\n}	0
9648414	9648381	How to prevent manual input into a ComboBox in C#	this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;	0
20108098	20108066	write binary file to docx file	File.WriteAllBytes(@"C:\temp\myfile.docx", res);	0
24859935	24859602	Automatic serialwise string generator followed by integer	void emp_id_generator(DataGridView dataGridView1)\n        {\n          if (dataGridView1 != null)\n           {\n                    int j = 6;  //this is what i want to increment\n             for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)\n             {\n                    Label l = new Label();\n                    l.Text = "EmpID" + (j);\n                    dataGridView1.Rows[count].Cells[0].Value = l.Text;\n                     j=j+1;\n             }\n          }\n        }	0
22026290	22025331	How to redirect user to paypal with parameters from c#	protected void BuyButton_Click(object sender, EventArgs e)\n{\n   string url = TestMode ? \n      "https://www.sandbox.paypal.com/us/cgi-bin/webscr" : \n      "https://www.paypal.com/us/cgi-bin/webscr";\n\n   var builder = new StringBuilder();\n   builder.Append(url);\n   builder.AppendFormat("?cmd=_xclick&business={0}", HttpUtility.UrlEncode(Email));\n   builder.Append("&lc=US&no_note=0&currency_code=USD");\n   builder.AppendFormat("&item_name={0}", HttpUtility.UrlEncode(ItemName));\n   builder.AppendFormat("&invoice={0}", TransactionId);\n   builder.AppendFormat("&amount={0}", Amount);\n   builder.AppendFormat("&return={0}", HttpUtility.UrlEncode(ReturnUrl));\n   builder.AppendFormat("&cancel_return={0}", HttpUtility.UrlEncode(CancelUrl));\n   builder.AppendFormat("&undefined_quantity={0}", Quantity);\n   builder.AppendFormat("&item_number={0}", HttpUtility.UrlEncode(ItemNumber));\n\n   Response.Redirect(builder.ToString());\n}	0
2776240	2776225	SQL Server: position based on marks	SELECT\n    StudentId,\n    StudentName,\n    Marks,\n    RANK() OVER (ORDER BY Marks DESC) AS Position\nFROM Student	0
2994562	2994539	how can i loop through all of the columns of the OracleDataReader	Dictionary<string, string> fields = new Dictionary<string, string>();\nOracleDataReader reader = command.ExecuteReader();\n\nif( reader.HasRows )\n{\n    for( int index = 0; index < reader.FieldCount; index ++ )\n    {\n        fields[ reader.GetName( index ) ] = reader.GetString( index );\n    }    \n}	0
16715864	16715260	Using of ashx to populate div with html	public class CustomFormHandler : IHttpHandler {\n    public void ProcessRequest (HttpContext context) {\n\n        context.Response.ContentType = "text/html";\n        context.Response.Write("<p>my html</p>");\n    }\n    public bool IsReusable {\n        get {\n            return false;\n        }\n    }\n}	0
23459799	23459380	CodeFirst, model property always null on fetch	//public MediaCategory MediaCategory { get; set; }\n  public virtual MediaCategory MediaCategory { get; set; }	0
33547110	33546380	Accessing elements in a dynamic object in C#	var myClass = new MyClass();\nvar stuff = myClass.myMethod();\nvar dynamicType = (TypeInfo)stuff.GetType();\n\nvar dataProperty = dynamicType.GetProperty("data");\nvar data = (IEnumerable)dataProperty.GetValue(stuff);\n\nvar result = new List<string>();\nType itemType = null;\nPropertyInfo myProperty = null;\nforeach(var item in data){\n    if(itemType == null){\n        itemType = item.GetType();\n        myProperty = itemType.GetProperty("myString");\n    }\n\n    var content = (string)myProperty.GetValue(item);\n    result.Add(content);\n}	0
20127233	20127150	Attribute to ignore method in debugging -	using System.Diagnostics\n\n...\n\n[DebuggerStepThrough]\npublic void MyMethod() {\n    ...	0
33846909	33846889	C# Join Strings of two arrays	var joined = array1.Zip(array2, (first, second) => first + " " + second);	0
21647813	21647711	Check for response every 100ms	check()	0
757810	751325	How to create a WPF UserControl with NAMED content	protected override void OnInitialized(EventArgs e)\n    {\n        base.OnInitialized(e);\n\n        var grid = new Grid();\n        var content = new ContentPresenter\n                          {\n                              Content = Content\n                          };\n\n        var userControl = new UserControlDefinedInXAML();\n        userControl.aStackPanel.Children.Add(content);\n\n        grid.Children.Add(userControl);\n        Content = grid;           \n    }	0
34144138	34140309	Set-Execution Policy from process	using (PowerShell PowerShellInstance = PowerShell.Create())\n{\n    string script = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy"; // the second command to know the ExecutionPolicy level\n    PowerShellInstance.AddScript(script);\n    var someResult = PowerShellInstance.Invoke();\n    something.ToList().ForEach(c => Console.WriteLine(c.ToString()));\n    Console.ReadLine();\n}	0
4304379	4304333	C# XmlDocument for small XML files - weight / performance	var xmlData = XDocument.Load(filename);\n  var tags = xmlData.Descendants("TAG");\n  foreach(var tag in tags) ...	0
13440915	13440898	insert rows into table with cursor or C# code	Insert Into Table1\n  (col1, col2)\nSelect Top 10\n  col1, col2\nFrom\n  Table2\nOrder By\n  NewID()	0
24222289	24222218	How to set radcombobox selected value from database?	RadComboBoxItem item = RadComboBox1.FindItemByText("Thomas Hardy");\nitem.Selected = true;\n\nint index = RadComboBox1.FindItemIndexByValue("2");\nRadComboBox1.SelectedIndex = index;\n\n//In your case value will be ContactID\nRadComboBox1.SelectedValue = value;	0
29059955	29059482	How do I stop the animated movement of an object at the edge of the window?	public Form1()\n    {\n        InitializeComponent();\n        Timer timer = new Timer();\n        timer.Interval = 12;\n        timer.Tick += timer_Tick;\n        timer.Start();\n    }\n    int difference = 5;\n    void timer_Tick(object sender, EventArgs e)\n    {\n        if (pictureBox1.Left  < 0 || pictureBox1.Left + pictureBox1.Width > this.Width) difference = -difference;\n        pictureBox1.Left += difference;\n    }	0
16481471	16467574	How to make a BaseUserControl meant for inheritance	//Base class\nusing System.Windows.Controls;\nnamespace Controls\n{\n    public class BaseUserControl: UserControl\n    {\n        protected string getText()\n        {\n            return "Hello World";\n        }\n    }\n} \n\n//Sub class\n<Controls:BaseUserControl x:Class="MyNameSpace.MyUserControl"\n         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n         xmlns:Controls="clr-namespace:Controls;assembly=MyAssembly">\n</Controls:BaseUserControl>\n\nusing Controls;\npublic partial class MyUserControl : BaseUserControl\n{\n    public MyUserControl ()\n    {\n        var baseText = getText();\n    }\n}	0
25573718	25573653	Initialize BitArray from integer	var b = new BitArray(BitConverter.GetBytes(0xfa2));\n    for (int i = b.Count-1; i >= 0; i--)\n    {\n        char c = b[i] ? '1' : '0';\n        Console.Write(c);\n    }\n    Console.WriteLine();	0
2764010	2763995	Regex for Username?	"^[a-zA-Z0-9]+$"	0
4184814	4184698	Unable to Copy datacolumn from one data table to another	DataTable dt1 = new DataTable();\nDataTable dt2 = new DataTable();\n\ndt2.Columns.Add("ColumnA", dt1.Columns["ColumnA"].DataType);\n\nfor (int i = 0; i < dt1.Rows.Count; i++)\n{\n    dt2.Rows[i]["ColumnA"] = dt1.Rows[i]["ColumnA"];\n}	0
6568262	6568145	Linq to XML Remove multiple returns	documentClass.Descendants("ValidationPluginAssociation")\n             .Attributes("CustomStorageString").First().Value	0
9360800	9360706	Do the Scrolling in Client Brower Window	function pageScroll() {\n         window.scrollBy(0,50); // horizontal and vertical scroll increments\n         var control = document.getElementById("yourControlName");\n         if( control != null ){control.focus();\n}	0
7424436	7424287	Download dynamically generated image from ASP.NET website	Content-Disposition	0
32868834	32868797	migrating to dbcontext LINQ where clause string parameter	var query = db.Inventory.Where(x => states.Contains(x.IdState));	0
4174761	4174154	Getting rounded value from a double result	int wholeNumber; //for getting the left part of the number\nint decimalPartTwoPlaces; //for assigning the right part to two characters\ndouble pi = 3.14159265d;\n\nwholeNumber = Math.Round(pi);\ndecimalPartTwoPlaces = Math.Round( ( pi - (double)wholeNumber ) * 100 ); // cast so it doesn't try and truncate the pi part	0
14740576	14733982	How to get wkhtmltopdf logging info in C#?	String output =string.Format("STD: {0}\nErr: {1}", p.StandardOutput.ReadToEnd(),\n                p.StandardError.ReadToEnd());	0
13032053	13031971	Open IE page through client side	window.print();	0
46378	46282	How do I create an XmlNode from a call to XmlSerializer.Serialize?	XmlSerializer xs = new XmlSerializer(typeof(MyConfig));\nStringWriter xout = new StringWriter();\nxs.Serialize(xout, myConfig);\nXmlDocument x = new XmlDocument();\nx.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>");	0
17973867	17973501	How to create multiple threads from an application and do not listen to their response?	Task t = Task.Run(() => ProcessMessage(message));	0
9650365	9650289	IP and Location information	public static GeoLocation HostIpToPlaceName(string ip)\n    {\n        string url = "http://api.ipinfodb.com/v2/ip_query.php?key={enterAPIKeyHere}&ip={0}&timezone=false";\n        url = String.Format(url, ip);\n\n        var result = XDocument.Load(url);\n\n        var location = (from x in result.Descendants("Response")\n                        select new GeoLocation\n                        {\n                            City = (string)x.Element("City"),\n                            Region = (string)x.Element("RegionName"),\n                            CountryId = (string)x.Element("CountryName")\n                        }).First();\n\n        return location;\n    }	0
10286593	10254373	Linq Group (multiple) on XML Data	var expr = from d in xmlDoc.Descendants("ROW")\n                        group d by new\n                        {\n                           ParentDir = d.Element("PARENT_DIR").Value,\n                           Dir = d.Element("DIR").Value,\n\n                        } into gDir\n                        select new\n                        {\n                           GroupKey = gDir.Key,\n                           Data = from z in gDir\n                                  select new { FileName = z.Element("FILE_NAME").Value }\n\n                        };\n\nforeach (var g in expr)\n{\n   Console.WriteLine("{0}\t\t", g.GroupKey.ParentDir, g.GroupKey.Dir);\n\n   foreach (var n in g.Data)\n               Console.WriteLine("\t\t{0}", n.FileName);\n}	0
7796512	7796420	Pattern to avoid nested try catch blocks?	Func<double>[] calcs = { calc1, calc2, calc3 };\n\nforeach(var calc in calcs)\n{\n   try { return calc(); }\n   catch (CalcException){  }\n} \n\nthrow new NoCalcsWorkedException();	0
3713574	3713483	Getting Sharp Architecture template to work with Visual Studio 2010	devenv /installvstemplates	0
23492142	23491516	Sort a DateTime Column with a Calendar	DATEDIFF(DAY, date1, date2) = 0	0
3043453	3043317	can i fetch the xaml button style on my dynamic button?	myDynamicButton.Style = (Style)myWindow.FindResource("myButtonStyle");	0
1717338	1530995	Can you programatically execute 'Run Custom Tool' on a ProjectItem in C#?	DTE.ExecuteCommand("Project.RunCustomTool")	0
21063607	21063443	Remove specific line in a csv file defined by the string in selected item in listbox - winforms c#	string playerStats = "D:\\playerStats.csv";\n    string lineToDelete = listBox1.SelectedItem.ToString();\n\n    if (File.Exists(playerStats))\n    {\n        string[] lines = File.ReadAllLines(playerStats);\n\n        using (StreamWriter sw = new StreamWriter(playerStats, false))\n        {\n            foreach (var line in lines)\n            {\n                string[] parts = line.Split(',');\n                if (parts[0] != lineToDelete)\n                {\n                    sw.WriteLine(line);\n                }\n                else\n                {\n                    MessageBox.Show("Player: " + lineToDelete + "Has been deleted");\n                }\n            }\n        }\n    }\n    else\n    {\n        MessageBox.Show("playerStats.csv does not exist, Check Filepath");\n    }	0
694705	561029	Scroll a WPF FlowDocumentScrollViewer from code?	public static ScrollViewer FindScrollViewer(this FlowDocumentScrollViewer flowDocumentScrollViewer)\n{\n    if (VisualTreeHelper.GetChildrenCount(flowDocumentScrollViewer) == 0)\n    {\n        return null;\n    }\n\n    // Border is the first child of first child of a ScrolldocumentViewer\n    DependencyObject firstChild = VisualTreeHelper.GetChild(flowDocumentScrollViewer, 0);\n    if (firstChild == null)\n    {\n        return null;\n    }\n\n    Decorator border = VisualTreeHelper.GetChild(firstChild, 0) as Decorator;\n\n    if (border == null)\n    {\n        return null;\n    }\n\n    return border.Child as ScrollViewer;\n}	0
31169633	31169565	Prefixing a property with base class	interface IControl\n{\n    void Paint();\n}\ninterface ISurface\n{\n    void Paint();\n}\n\npublic class SampleClass : IControl, ISurface\n{\n    void IControl.Paint()\n    {\n        System.Console.WriteLine("IControl.Paint");\n    }\n    void ISurface.Paint()\n    {\n        System.Console.WriteLine("ISurface.Paint");\n    }\n}	0
8549741	8548482	Recursive validation using annotations and IValidatableObject	[CustomValidation(typeof(Customer), "ValidateRelatedObject")]\npublic CustomerDetails Details\n{\n    get;\n    private set;\n}\n\npublic static ValidationResult ValidateRelatedObject(object value, ValidationContext context)\n{\n    var context = new ValidationContext(value, validationContext.ServiceContainer, validationContext.Items);\n    var results = new List<ValidationResult>();\n    Validator.TryValidateObject(value, context, results);\n\n    // TODO: Wrap or parse multiple ValidationResult's into one ValidationResult\n\n    return result;\n\n}	0
2415268	2415022	NullReferenceException while working with ObjectBuilder in implementing MVP pattern 	protected override void OnPreInit(EventArgs e)\n{\n    ObjectFactory.BuildUp(this);\n    base.OnPreInit(e);\n}	0
26214458	26214268	How to remove comma separated duplicated string values and get last two values	string str = "2,4,3,12,25,2,4,3,6,2,2,2";\nList<string> uniques = str.Split(',').Reverse().Distinct().Take(2).Reverse().ToList();\nstring newStr = string.Join(",", uniques);\nConsole.WriteLine(newStr);	0
26967440	26962526	How to check user role in a resource server when using Thinktecture.IdentityServer.v3	JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None;	0
25640797	25640683	How do you include a linebreak taken from a textarea in a paragraph?	string text = textFromDatabase.Replace(Environment.NewLine, "<br />");	0
20394400	20356258	OdataController query plan not optimal because of DTO mapping	public virtual IQueryable<TDTO> Get(ODataQueryOptions queryOptions)\n        {\n            if (queryOptions.SelectExpand == null)\n            {\n                var selectOption = new SelectExpandQueryOption("Id,Name", string.Empty, queryOptions.Context);\n                Request.SetSelectExpandClause(selectOption.SelectExpandClause);\n            }\n\n            return (from m in Context.Get<MainDalObject>()\n    select new MainObject \n    {\n       Id = m.Id,\n       Name = m.Description,\n       Subs = m.Subs.Select(s => new SubObject \n       {\n          Id = s.Id,\n          Name = s.Name\n       }\n    });\n}	0
26516773	26516301	Regex for a TextBox	int intInTheBox;\n        if (int.TryParse(textBox_Gen_Offset.Text, out intInTheBox))\n        {\n            //Do stuff if it's an int\n        }\n\n        double doubleInTheBox;\n        if (double.TryParse(textBox_Gen_Offset.Text, out doubleInTheBox))\n        {\n            //Do stuff if it's a double\n        }	0
4369589	4368543	Validating decimal in C# for storage in SQL Server	public static bool WillItTruncate(double dNumber, int precision, int scale) {\n        string[] dString = dNumber.ToString("#.#", CultureInfo.InvariantCulture).Split('.');\n        return (dString[0].Length > (precision - scale) || dString.Length>1?dString[1].Length > scale:true);\n    }	0
18343943	18343375	Set Button shortcut Without Command?	Keys lastkey = Keys.None;\n    Button b = new Button();\n    private void KeyPress(object sender, KeyEventArgs e)\n    {\n        if (lastkey == Keys.Control)\n        {\n            //Do some stuff\n            b.PerformClick();\n        }\n        if (e.KeyCode == Keys.Control)\n            lastkey = Keys.Control;\n        else\n            lastkey = e.KeyCode;\n    }	0
7322407	7322118	Accessing a Graphics object from a different class	private void panel1_Paint(object sender, PaintEventArgs e)\n{\n  RectMaker rect_Maker = new RectMaker();\n  rect_Maker.Draw(e.Graphics);\n}	0
13986945	13986454	saving get data to a local variable	Session.AddItem	0
21985000	21984776	disable right click on datagrid while in edit mode	private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        e.Control.ContextMenuStrip = myContextMenuStrip;\n    }	0
33469858	33464573	Is it possible to use a dash character in variable name .net Web API?	[JsonProperty(PropertyName = "err-code")]	0
4118170	4118038	Fluent NHibernate cascading delete convention for aggregate roots	IAutomappingOverride<Application>	0
34013136	34013073	Variables values remain saved after closing and opening the same page	public MyObject {\n  get { return (MyObject)Session["MyObject_key"]; }\n  set { Session["MyObject_key"] = value; }\n}	0
4273727	4273699	How to read a large (1 GB) txt file in .NET?	StreamReader.ReadLine	0
13342624	13342581	Get CultureInfo by culture English name	var names = CultureInfo.GetCultures(CultureTypes.AllCultures).ToLookup(x => x.EnglishName);\nnames["English"].FirstOrDefault();	0
4453445	4453414	Does anyone know a translation into VB for the below code?	Dim customers = (From c In xDoc.Descendants("customer")Order By c.Attribute("CustomerID").Value\n Select New Customer() With { _\n  .ID = c.Attribute("CustomerID").Value, _\n  .CompanyName = c.Attribute("CompanyName").Value, _\n  .ContactName = c.Attribute("ContactName").Value, _\n  .ContactTitle = c.Attribute("ContactTitle").Value, _\n  .Address = c.Attribute("Address").Value, _\n  .City = c.Attribute("City").Value, _\n  .State = c.Attribute("State").Value, _\n  .ZIPCode = c.Attribute("ZIPCode").Value, _\n  .Phone = c.Attribute("Phone").Value _\n}).ToList()	0
7391648	7391613	C# - Open a file with the associated program without invoking the command line	Process.Start(filePath)	0
2179327	2173063	Drawing Collision on Screen	plane A     |    plane B\n            |\n           / \\n          /   \\n         /     \\n________/       \\n        |        \\n        |         \\nplane C | plane D  \\n\n        vs.\n\nplane A |    plane B\n        |\n        |\n________|\n         \\n          \\n          |\\n          | \\n          |  \\n          |   \\n          |    \\n          |     \\n          |      \\n          |       \\n          |        \\nplane C   | plane D \	0
27319911	27319351	How to draw a stripline diagonally using MSChart?	// we create a general LineAnnotation, ie not Vertical or Horizontal:\nLineAnnotation lan = new LineAnnotation();\n\n// we use Axis scaling, not chart scaling\nlan.IsSizeAlwaysRelative = false;\n\nlan.LineColor = Color.Yellow;\nlan.LineWidth = 5;\n\n// the coordinates of the starting point in axis measurement\nlan.X = 3.5d;\nlan.Y = 0d;\n// the size: \nlan.Width = -3.5d;\nlan.Height = 5.5d;\n\n// looks like we need an anchor point, no matter which..\nlan.AnchorDataPoint = yourSeries.Points[0];\n\n// now we can add the LineAnnotation;\nchart1.Annotations.Add(lan);	0
4923658	4923486	How do I paint a ball moving in a panel using WinForms?	List<Ball>	0
25150738	25147811	Backgroundworker doesn't update progress bar in separate window	DoWork()	0
5444803	5444585	Automaper how to map this?	Mapper.CreateMap<Task,TaskTableViewModel>()\n             .ForMember(dest => dest.CourseCoursePermissionsBackgroundColor,\n                         opt => opt.MapFrom(src=>src.Course.CoursePermissions[0].BackgroundColor));	0
10609506	10602264	Using Moq to verify calls are made in the correct order	int callOrder = 0;\nwriterMock.Setup(x => x.Write(expectedType)).Callback(() => Assert.That(callOrder++, Is.EqualTo(0)));\nwriterMock.Setup(x => x.Write(expectedId)).Callback(() => Assert.That(callOrder++, Is.EqualTo(1)));\nwriterMock.Setup(x => x.Write(expectedSender)).Callback(() => Assert.That(callOrder++, Is.EqualTo(2)));	0
973733	973721	C# - Detecting if the SHIFT key is held when opening a context menu	if (Control.ModifierKeys == Keys.Shift ) { \n  ...\n}	0
21105737	21104392	How do I download a certificate from an endpoint with .Net?	ServicePointManager.FindServicePoint(Uri)	0
3566138	3559760	Trouble with FindControl and dynamicly created controls	public static Control FindControl(Control parent, string id)\n    {\n        foreach (Control control in parent.Controls)\n        {\n            if (control.ID == id)\n            {\n                return control;\n            }\n            var childResult = FindControl(control, id);\n            if (childResult != null)\n            {\n                return childResult;\n            }\n        }\n        return null;\n    }	0
17268132	17268037	How to do a pause in C# for Windows Phone 8 using Windows Phone App	private bool _paused = false;\n\nprivate void OnUpdate(object sender, object e)\n{\n    if (_paused)\n    {\n       return;\n    }\n    ...\n}\n\nprivate void btnPause_Click(object sender, RoutedEventArgs e)\n{\n    _paused != _paused;\n}	0
1283249	1283245	Can you change a setting in the Foo.settings file at run-time?	public void VerifyIfFirstTimeRun()\n{\n    if (Properties.Settings.Default.FirstTimeUse == true)\n    {\n        //Do something here.\n\n        //Change first time usage Bool to false\n        Properties.Settings.Default.FirstTimeUse = false;\n\n        //Save your changes, and you're done!\n        Properties.Settings.Default.Save();\n    }                        \n}	0
33106729	33105307	Changing System Tray Icon Image	notifyIcon.Icon = new Icon(this.GetType(), "red.ico");	0
2289617	2289566	How to join two collections by index in LINQ	var values = { "1", "hello", "true" };\nvar types = { typeof(int), typeof(string), typeof(bool) };\nvar objects = values.Zip(types, (val, type) => Convert.ChangeType(val, type));	0
11725793	11725634	Datatable as datasource in ReportViewer	ReportDataSource source = new ReportDataSource("DataTable1", dt);	0
33941333	33939862	Command to copy a file to another, user-chosen directory?	protected void Button3_Click(object sender, EventArgs e)\n        {\n            string fileToCopy = @"e:\TestFile.pdf"; \n            string destinationDirectoryTemplate = TextBox1.Text;\n            var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);\n            var di = new DirectoryInfo(dirPath);\n            if (!di.Exists) \n            { di.Create(); } \n            var fileName = Path.GetFileNameWithoutExtension(fileToCopy);\n            var extn = Path.GetExtension(fileToCopy);\n\n            var finalname = fileName + " " + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + extn;\n            var targetFilePath = Path.Combine(dirPath, finalname);\n            File.Copy(fileToCopy, targetFilePath);\n        }	0
1853214	934956	how to use foreach in linq	xml.Elements().ToList().ForEach(ele => DoSomething(ele));	0
24273361	24272891	get URL from web page button click	private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n    {\n        if (e.Url.AbsoluteUri.Contains("something")) {\n            //stais in the current page\n            e.Cancel = true;\n\n            //aditionally you can navigate to another URL (though it will fire this event again)\n            webBrowser1.Navigate(e.Url.AbsoluteUri.Replace("something", "empty"));\n\n        } else {\n            //continue\n        }\n    }	0
7345694	7345444	Finding users' HOMEPATHs from a service	String PersonalFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);	0
22582515	22570877	How to link a GUI Texture button to a script in Unity3d	if(GUI.Button(Rect(Screen.width*.85,Screen.height*0,width,width),Resources.Load("pause") as Texture))\n{\n\n//Button press action\n}	0
33997040	33873442	Retrieve process- or thread-id of global keypress using SetWindowsHookEx	public partial class Form1 : Form \n{\n    [DllImport("user32.dll")]\n    static extern IntPtr GetForegroundWindow();\n\n    [DllImport("user32.dll")]\n    static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);\n\n    Process process;\n\n    public Form1() \n    {\n        process = Process.GetProcesses()\n            .Where(x => x.ProcessName == "MyProcessName")\n            .FirstOrDefault();\n\n        //init global keypress as needed\n    }\n\n    void gkh_KeyUp(object sender, KeyEventArgs e)\n    {\n        IntPtr handle = GetForegroundWindow();\n        uint processID = GetWindowThreadProcessId(handle, IntPtr.Zero);\n        if (p2.Threads.OfType<ProcessThread>().Any(x => x.Id == Convert.ToInt32(processID)))\n        {\n            //keypress in MyProcessName\n        }\n        e.Handled = true;\n    }	0
1180472	1180344	Most efficient way to implement preemptive waiting queue?	public static IList<Item> _list;\n\npublic void DoSomething()\n{\n    while (true)\n    {\n        DateTime minDate = DateTime.MaxValue;\n\n        for (int i = 0; i < _list.Count; i++)\n        {\n            DateTime nextExecution = _list[i].LastUpdate.AddMinutes(_list[i].Time);\n\n            if (nextExecution <= DateTime.Now)\n            {\n                var item = DoWork(_list[i].Url);\n                _list[i].LastUpdate = item.LastUpdate;\n                nextExecution = _list[i].LastUpdate.AddMinutes(_list[i].Time);\n                Console.WriteLine(item.Title + " @ " + item.LastUpdate + "; i = " + i);\n            }\n\n            if (nextExecution < minDate)\n                minDate = nextExecution;\n        }\n\n        TimeSpan timeToSleep = minDate.Subtract(DateTime.Now));\n\n        if (timeToSleep.TotalMilliseconds > 0)\n        {\n            Console.WriteLine("Sleeping until: " + minDate);\n            System.Threading.Thread.Sleep(timeToSleep);\n        }\n    }\n}	0
7524099	7524057	How do I change the full background color of the console window in C#?	Console.ForegroundColor = ConsoleColor.Red;\nConsole.BackgroundColor = ConsoleColor.Green;\n\nConsole.Clear();\n\nConsole.WriteLine("Hello World");\n\nConsole.ReadLine();	0
3987215	3987028	How to check if a scroll is currently visible in WPF DataGrid?	ScrollViewer scrollview = FindVisualChild<ScrollViewer>(dataGrid);\nVisibility verticalVisibility = scrollview.ComputedVerticalScrollBarVisibility;\nVisibility horizontalVisibility = scrollview.ComputedHorizontalScrollBarVisibility;	0
18728462	18728406	Add an EXE file to a project, so that it will be copied to the Bin/Debug folder just like a DLL?	copy if newer	0
3438316	3438296	Is there a simple way to create an initialized array?	return Enumerable.Repeat(1, 24).ToArray();	0
11280587	11280380	Correct approach to make a ListBox Page Navigation using MVVM on Windows Phone	private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        // If selected index is -1 (no selection) do nothing\n        if (MainListBox.SelectedIndex == -1)\n            return;\n\n        // Navigate to the new page\n        NavigationService.Navigate(new Uri("/Views/detailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));\n\n        // Reset selected index to -1 (no selection)\n        MainListBox.SelectedIndex = -1;\n    }	0
29143319	27651342	Failed to add reference to 'System.Net.Http'. Please make sure that it is in the Global Assembly Cache	System.Net.Http	0
4315669	4315009	SQL export to ListView using C#	foreach (DataRow row in poplb6ds.Tables[0].Rows) {\n    ListViewItem item = new ListViewItem(row["Pro"].ToString());\n    item.SubItems.Add(row["size"].ToString());\n    item.SubItems.Add(row["Date"].ToString());\n    listView1.Items.Add(item);\n}	0
8244213	8228262	Create Outlook MailItem and save as draft for other user	Dim omApp As New Outlook.Application\n\n    Dim omNamespace As Outlook.NameSpace = omApp.GetNamespace("MAPI")\n\n    Dim omUser As Outlook.Recipient = omNamespace.CreateRecipient("otheruser@mail.com")\n    omUser.Resolve()\n    If Not omUser.Resolved Then\n        MsgBox("Could not login.")\n    End If\n\n    Dim omDrafts As Outlook.MAPIFolder = omNamespace.GetSharedDefaultFolder(omUser, Outlook.OlDefaultFolders.olFolderDrafts)\n    Dim omMailItem As Outlook.MailItem = CType(omDrafts.Items.Add, Outlook.MailItem)\n\n    With omMailItem\n        .SentOnBehalfOfName = "otheruser@mail.com"\n        .To = "bill@gates.com"\n        .Subject = "Test"\n        .Body = "Test email"\n        .Save()\n\n        .Move(omDrafts)\n\n    End With	0
33865976	33865192	How to determine in which scope is a value in an array?	string GetPrize(int cId, decimal amount)\n    {\n        foreach (var campaignPrize in db.CampaignPrizes.Where(c => c.CampaignId == cId).OrderByDescending(x => x.MinimumAmount))\n        {\n            if (amount > campaignPrize.MinimumAmount)\n            {\n                return campaignPrize.Prize;\n            }\n        }\n\n        return "No Gift"; // lesser than or equal to lowest MinimumAmount\n    }	0
4849356	4849332	how to specify the connection string if the excel file name contains white space?using c#	string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"D:\\data\\Proj_Resource Details 20110118.xlsx\";Extended Properties=Excel 12.0";	0
20317957	20317922	Grab next item in a list based on a field with LINQ	var person = \n   r.SkipWhile(e => e.Name != "Bob Smith") // skip people until Bob Smith\n    .Skip(1) // go to next person\n    .SkipWhile(e => e.Status != "yes") // skip until status equal 'yes'\n    .FirstOrDefault(); // get first person, if any\n\nif (person == null)\n    person = r.TakeWhile(e => e.Name != "Bob Smith")\n              .FirstOrDefault(e => e.Status != "yes");	0
14129195	14128321	How to develop MS Outlook plug-in in VS 2010?	private void ThisAddIn_Startup(object sender, System.EventArgs e)\n    {\n        System.Windows.Forms.MessageBox.Show("Outlook starting up...");\n    }	0
10045422	10044938	CommandBarButton click event for several buttons	vsoButtonX1.Tag = "1";\nvsoButtonX2.Tag = "2";	0
10061396	10061286	2-Dimension array of List in C#?	List<string>[,] strings = new List<string>[2, 2];\nstrings[0, 0] = new List<string> { "One" };\nstrings[0, 1] = new List<string> { "Two" };\nstrings[1, 0] = new List<string> { "Three" };\nstrings[1, 1] = new List<string> { "Four" };	0
2158951	2158888	Determining which object was selected using a listbox	public class Person\n{\n    public string FirstName { get; set; }\n    public string Surname { get; set; }\n}\n\nvar people = new[]\n{\n    new Person{FirstName = "Peter", Surname = "Pan"}, \n    new Person{FirstName = "Simon", Surname = "Cowell"}\n};\n\nvar listbox = new ListBox\n{\n  DisplayMember = "FirstName",\n  ValueMember = "FirstName",\n\n  DataSource = people\n};\n\nvar person = listbox.SelectedItem as Person;	0
2300246	2300156	Problem converting a GMT date to local time using C#?	DateTime parsedStartTime = DateTime.SpecifyKind(\n    DateTime.Parse(starttime),\n    DateTimeKind.Utc);\n\nDateTime localStartTime = parsedStartTime.DateToLocalTime();	0
26978466	26977893	How to clear selected elements from array	static void ProcessDelete( Int32[] playerNumbers, String[] playerLastName,  Int32[] playerPoints, Int32 playerIndex)\n{\n  playerNumbers[playerIndex] = 0;\n  playerLastName[playerIndex] = " ";\n  playerPoints[playerIndex] = 0;\n}	0
24390285	24387432	Access profiles using attributes	public static void RegisterGlobalFilters(GlobalFilterCollection filters)\n    {\n        if (filters != null)\n        {\n            filters.Add(new CustomAuthorizeAttribute());\n        }\n    }\n\n\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\npublic sealed class CustomAuthorizeAttribute : AuthorizeAttribute\n{\n    protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        //your code here\n    }	0
16467586	16467412	Identify Duplicate Nodes in XML Using XPath	var dubs = XDocument.Parse(xml)\n            .Descendants("group")\n            .GroupBy(g => (string)g.Attribute("name"))\n            .Where(g => g.Count() > 1)\n            .Select(g => g.Key);	0
11510088	11509679	Parsing user input from a console as commandline arguments in c#	static void Main(string[] args)\n{\n    Console.WriteLine("Input please:");\n    string input = Console.ReadLine();\n    // Parse input with Regex (This splits based on spaces, but ignores quotes)\n    Regex regex = new Regex(@"\w+|""[\w\s]*""");\n}	0
22123944	22123368	How to set Cell value of DataGridViewRow by column name?	//Create the new row first and get the index of the new row\nint rowIndex = this.dataGridView1.Rows.Add();\n\n//Obtain a reference to the newly created DataGridViewRow \nvar row = this.dataGridView1.Rows[rowIndex];\n\n//Now this won't fail since the row and columns exist \nrow.Cells["code"].Value = product.Id;\nrow.Cells["description"].Value = product.Description;	0
29765269	29764493	RouteUrl with querystring - with duplicate keys	string _rawstring = context.HttpContext.Request.RawUrl;\nint _f;\n_f = _rawstring.IndexOf('?');\nstring _resultString = _rawstring.SubString(_f, _rawstring.Length);	0
3775263	3769570	Could I get the decrypted password in membership from database?	MembershipUser user = Membership.GetUser(userId);\nuser.ChangePassword(user.GetPassword(), newpw);	0
17176854	17176617	inserting xml element into multiple nodes	XmlNodeList nodes = xDoc.DocumentElement.SelectNodes("Uic");\nforeach(XmlNode node in nodes) {\n   XmlElement element = xDoc.CreateElement("SomeElement");\n   element.InnerText = "anything";\n   node.ParentNode.AppendChild(element);\n}	0
28145964	28145757	I need a program to display user input digit and sum of those digits	static void Main()\n{\n     Console.WriteLine("Enter a Number : ");\n\n     string input = Console.ReadLine();\n     int num, sum = 0;\n\n     if (int.TryParse(input, out num))\n     {\n         for (; num > 0; num = num / 10)\n         {\n             sum = sum + num % 10;\n         }\n\n         Console.WriteLine("The sum of the digits in the number: {0} is {1}", input, sum);\n     }\n     else { Console.WriteLine("Invalid number format."); }\n\n     Console.ReadKey();\n }	0
7984304	7983767	Valid return value becomes null in receiver in C#	class IntPoint {\n    public int X { get; set; }\n    public int Y { get; set; }\n\n    public IntPoint(int X, int Y) {\n        this.X = X;\n        this.Y = Y;\n    }\n\n    public override bool Equals(object obj)\n    {\n        if (obj is IntPoint) return Equals(obj as IntPoint);\n        return base.Equals(obj);\n    }\n\n    public bool Equals(IntPoint anotherPoint) {\n        return ((anotherPoint.X == X) && (anotherPoint.Y == Y));\n    }\n}	0
1573376	1508570	read string from .resx file in C#	// Create a resource manager to retrieve resources.\nResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());\n\n// Retrieve the value of the string resource named "welcome".\n// The resource manager will retrieve the value of the  \n// localized resource using the caller's current culture setting.\nString str = rm.GetString("welcome");	0
19903290	19902869	c# deleting whole row in access database	using (var myConnection = new OleDbConnection(myConnectionString))\nusing (var myCommand = myConnection.CreateCommand())\n{\n    var idParam = new OleDbParameter("@id", Izbor.SelectedValue);\n\n    myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = @id";\n    myCommand.Parameters.Add(idParam);\n\n    myConnection.Open();\n    myCommand.ExecuteNonQuery();\n}	0
12097299	12096905	Printing the currently active window in landscape mode	PrintForm p = new PrintForm(this);\np.PrinterSettings.DefaultPageSettings.Landscape = true;\np.Print();	0
25186739	25186532	Passing Zipcode + 4 in query string	string sZip = zip.ToString();\nsZip = sZip + "-1234";	0
9441553	9441505	How to detect specific Keys pressed in a text box	private void textBox_KeyPress(object sender, KeyPressEventArgs e)\n    {\n\n                if (e.KeyChar == '%')\n                {\n                    //your further code ...\n                }\n    }	0
12727753	12727491	Programmatically set TextBlock Foreground Color	textBlock.Foreground = new SolidColorBrush(Colors.White);	0
7740332	7740304	Redirect and pass a value from server side in asp.net	Response.Redirect(string.Format("ResponseMetric.aspx?MsgID={0}", msgid));	0
8776516	8732472	Sum value from gridview cells and display it using label	int totalMarks=0;\n\n        foreach (GridViewRow row in GridView1.Rows)\n        {\n\n                total = Convert.ToInt32(row.Cells[3].Text);\n\n               totalMarks = totalMarks + total;\n\n\n\n        }\n\n\n\n        totalMarks Label.Text = Convert.ToString(totalMarks );	0
10830967	10767366	Pass parameters from ConfirmNavigationRequest to NavigationService in Prism	navigationResult.Context.Parameters["Count"];	0
28131738	28131704	Query a list of objects that contains any string	myObject.Where(o => words.Any(o.SearchString.Contains))	0
699103	698705	How to find the nested Asp:GridView within the following code?	protected void gvMaster_RowCreated(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow) {\n        GridView gv = (GridView)e.Row.FindControl("gvDetails");\n    }\n}	0
10928799	10928455	Accept an untrusted certificate by default to connect with SSL for Windows Phone	TrustedRootCertificateInstaller.cs	0
15269152	15269082	using regular expression to match the last word of a substring	string s = "^.* ([^ ]+) for a long time\\.$";\n\nRegex r = new Regex(s);\nMatch m = r.Match("The old man walks today for a long time.");\nif(m.Success)\n{\n    Console.WriteLine(m.Groups[1].Value);\n}	0
21467420	21466214	MigraDoc: Centering a watermark on both landscape and portrait pages	myImage = section.Headers.EvenPage.AddImage("C:\\myImage.png");\n\n    myImage.Height = "4.5cm";\n    myImage.LockAspectRatio = true;\n    myImage.Top = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;\n    myImage.Left = MigraDoc.DocumentObjectModel.Shapes.ShapePosition.Center;\n    myImage.RelativeHorizontal = MigraDoc.DocumentObjectModel.Shapes.RelativeHorizontal.Margin;\n    myImage.RelativeVertical = MigraDoc.DocumentObjectModel.Shapes.RelativeVertical.Margin;	0
21386496	21386391	Open and Close the same window on the same button click	private xamlHelp help = null;\nprivate void btnHelp_Click(object sender, RoutedEventArgs e)\n{\n    if (help != null)\n    {\n        help.Close();\n        help = null;\n    }\n    else\n    {\n        help = new xamlHelp();\n        help.Show();\n    }\n}	0
4945451	4945430	Change Windows 7 Serial Number	Process.Start	0
8679225	8564761	C# deserialization of System.Type throws for a type from a loaded assembly	AppDomain current = AppDomain.CurrentDomain;\ncurrent.AssemblyResolve += new ResolveEventHandler(HandleAssemblyResolve);\n\nstatic Assembly HandleAssemblyResolve(object sender, ResolveEventArgs args)\n{\n    /* Load the assembly specified in 'args' here and return it, \n       if the assembly is already loaded you can return it here */\n}	0
1682765	1682484	Explicit implementation of interface's GetEnumerator causes stack overflow	public class Things : List<Thing>, IThings\n    {\n        IEnumerator<IThing> IEnumerable<IThing>.GetEnumerator()\n        {\n            foreach (Thing t in this)\n            {\n                yield return t;\n            }\n        }\n    }	0
28618619	28618476	How to deserialize json object into class	[JsonObject(MemberSerialization.OptIn)]\npublic class User\n{\n     [JsonProperty("initials")]\n     public string Initials { get; set; }\n\n     [JsonProperty("name")]\n     public string Name { get; set; }\n\n     [JsonProperty("companies")]\n     public string[] Companies { get; set; }\n\n     [JsonProperty("responseMessage")]\n     public string ResponseMessage { get; set; }\n}\n\n[JsonObject(MemberSerialization.OptIn)]\npublic class ResponseData\n{\n     [JsonProperty("user")]\n     public User User { get; set; }\n\n     [JsonProperty("employee")]\n     public string Employee { get; set; }\n}	0
11312180	11311883	How to change a method from string result without a IF	var button = repo.TiTouchScreenApp.ToolbarListBox.Buttons.Where(b => b.Name == deviceName).FirstOrDefault();\n\nif(button != null)\n{\n  button.DoubleClick();\n}	0
17068799	17068300	Populating a listview with checkboxes from a XAML file	SaltWater = x.Descendants("SaltWater").First().Value	0
616825	616808	Exposing WCF subclasses based on an abstract class	public static void RunService()\n{\n        Type t = typeof(Child);\n        ServiceHost svcHost = new ServiceHost(t, new Uri("http://localhost:8001/People"));\n        svcHost.AddServiceEndpoint(typeof(IWcfClass), new BasicHttpBinding(), "Basic");\n        svcHost.Open();\n}	0
11135631	10641889	How do I stop my controls from generating resource files for my data lists?	[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic List<Job> Jobs {\n   get { return _jobs; }\n   set { _jobs = value; }\n}	0
19858014	19857486	How can I parse this DateTime? (T & Z)	string dateString = "2013-11-08T10:00:04.000Z";\nDateTime convertedDate = DateTime.Parse(dateString);\nConsole.WriteLine("Converted {0} to {1} time {2}", \n                           dateString, \n                           convertedDate.Kind.ToString(), \n                           convertedDate);	0
12824452	12824156	How do you iterate over an arbitrary number of lists, including every permutation?	static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) \n{ \n  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; \n  return sequences.Aggregate( \n    emptyProduct, \n    (accumulator, sequence) => \n      from accseq in accumulator \n      from item in sequence \n      select accseq.Concat(new[] {item})); \n}	0
23974399	23974327	listbox selectedindex only selecting last element	foreach (ClasaAutor autor in listaAutoriPublicatie)\n{\n    foreach (ListItem item in list.Items)\n    {\n        if (item.Value == autor.GuidAutor.ToString())\n            item.Selected = true;\n    }\n}	0
3700422	3700370	Working with enums(constructing a list)	[Flags]\npublic enum ParentDepartments\n{\n    None = 0x0,\n    Electrical = 0x1,\n    Mechanical = 0x2,\n    Biology = 0x4,\n}\n\npublic static ParentDepartments GetParentDepartments(Course course)\n{\n    var departments = ParentDepartments.None;\n\n    if (course.ElectricalStudents.Any())\n        departments |= ParentDepartments.Electrical;\n\n    if (course.ComputerStudents.Any())\n        departments |= ParentDepartments.Electrical;\n\n    if (course.MechanicalStudents.Any())\n        departments |= ParentDepartments.Mechanical;\n\n    if (course.BioengineeringStudents.Any())\n        departments |= ParentDepartments.Biology;\n\n    return departments;\n}	0
7544030	7543885	IIS CPU goes bezerk after updating web.config in a C# application with a Singleton with a thread	private void StartThread()\n{\n    do\n    {\n        try\n        {\n            //do some work with HTTP requests\n            Thread.Sleep(1000 * 2);\n        }\n        catch (Exception e)\n        {\n            //The recursive call here is suspect\n            //at the very least find a way to prevent infinite recursion\n            //--or rethink this strategy\n            this.StartThread();\n        }\n    } while (this.status == START);\n}	0
18378310	18377894	c# Accessing MasterPage elements from Child Page	public void master_Page_PreLoad(object sender, EventArgs e)	0
24782326	24781892	How to read dynamic returned JSON string in c#?	private string GetKeyValuePairs(string jsonString)\n    {\n        var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);\n        string sdict = string.Empty;\n        foreach (string key in resDict.Keys)\n        {\n            sdict += "<br/> " + key + " : " + (resDict[key].GetType() == typeof(JObject) ? GetKeyValuePairs(resDict[key].ToString()) : resDict[key].ToString());\n        }\n        return sdict;\n    }	0
23422575	23422480	How to disable download option of pdf file in c# ?	Google Document Viewer	0
7509844	7509798	how to arrange downloaded information to fit into rows?	while (SQLRD.Read())\n{\n     data += SQLRD[0].ToString() + ",";\n                   //              ^^^ note the change from '\n' to ','\n     data += SQLRD[1].ToString() + ",";\n     data += SQLRD[2].ToString() + ",";\n     ...\n     data += SQLRD[7].ToString(); // final column doesn't need a ','\n     data += "\n"; // final line separator for the entire row\n}	0
12054532	12048586	How to give/add parent node for set of nodes in xmlDocument using vb.net or C#	Dim doc As New XmlDocument()\ndoc.Load(xmlFilePath)\nDim bookToModify As XmlNode = doc.SelectSingleNode("/books")\nDim author As XmlNode = doc.CreateElement("author")\nbookToModify.AppendChild(author)\nFor Each node As XmlNode In bookToModify.SelectNodes("surname | givenname")\n    node.ParentNode.RemoveChild(node)\n    author.AppendChild(node)\nNext	0
1787960	1786529	Validate 2 lists using FluentValidation	RuleFor(f => f.Names).Must((f, d) =>\n            {\n                for (int i = 0; i < d.Count; i++)\n                {\n                    if ((String.IsNullOrEmpty(d[i]) &&\n                         !String.IsNullOrEmpty(f.URLs[i])))\n                        return false;\n                }\n\n                return true;\n            })\n            .WithMessage("Names cannot be empty.");\n\n            RuleFor(f => f.URLs).Must((f, u) =>\n            {\n                for (int i = 0; i < u.Count; i++)\n                {\n                    if ((String.IsNullOrEmpty(u[i]) &&\n                         !String.IsNullOrEmpty(f.Names[i])))\n                        return false;\n                }\n\n                return true;\n            })\n            .WithMessage("URLs cannot be empty.");	0
19564094	19563753	Windows Phone IsolatedStorage	public async void btnDownload2_Click()\n{\n  try\n  {\n    var httpClient = new HttpClient();\n    var response = await httpClient.GetAsync(new Uri("http://somelink/video/nameOfFile.mp4"), HttpCompletionOption.ResponseHeadersRead);\n\n    response.EnsureSuccessStatusCode();\n\n    using(var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n      bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);\n\n      string VideoFile = "PlayFile.wmv";\n      using(var isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile))\n      {\n        using(var stm = await response.Content.ReadAsStreamAsync())\n        {\n          stm.CopyTo(isolatedStorageFileStream);\n        }\n      }\n    }\n  }\n  catch(Exception)\n  {\n    // TODO: add error handling\n  }\n}	0
3416968	3416899	C# Create HTML unordered list from List using Recursion	public static bool WriteMenu(List<Page> pages, int parentId, int indent)\n{\n    string padding = new string(' ', indent * 8);\n    bool writtenAny = false;\n    foreach (var page in pages.Where(p => p.ParentPageId == parentId))\n    {\n        if (!writtenAny)\n        {                \n            Console.WriteLine();\n            Console.WriteLine(padding + "<ul>");\n            writtenAny = true;\n        }\n        Console.Write(padding + "    <li>{0}", page.PageId);\n        if (WriteMenu(pages, page.PageId, indent + 1))\n        {\n            Console.WriteLine(padding + "    </li>");                \n        }\n        else\n        {\n            Console.WriteLine("</li>");\n        }\n    }        \n    if (writtenAny)\n    {\n        Console.WriteLine(padding + "</ul>");\n    }\n    return writtenAny;\n}    \n...\nWriteMenu(pages, 0, 0);	0
6030696	6030576	How to make gridview searchable?	DataView dvData = new DataView(dtData);\ndvData.RowFilter = "[ColumnName]=[Condition, this will be your dropdown value]";\ngv.DataSource = dvData;\ngv.DataBind();	0
6467737	6467711	Substring a string from the end of the string	string str = "Hello Marco !";\n        str = str.Substring(0, str.Length - 2);	0
20958776	20947217	Generate CSS from LESS on windows azure worker role	// File path.\n        var lessCompilerPath = "...\\lessc.wsf";\n        var lessPath = "site.less");\n        var cssPath = "site.css");\n\n        // Compile.\n        var process = new Process\n        {\n            StartInfo = new ProcessStartInfo("cscript")\n            {\n                WindowStyle = ProcessWindowStyle.Hidden,\n                CreateNoWindow = true,\n                Arguments = "//nologo \"" + lessCompilerPath + "\" \"" + lessPath + "\" \"" + cssPath + "\" -filenames",\n                UseShellExecute = false,\n                RedirectStandardError = true,\n                RedirectStandardOutput = true\n            }\n        };\n        process.Start();\n        process.WaitForExit();\n\n        // Error.\n        if (process.ExitCode != 0)\n        {\n            throw new InvalidOperationException(process.StandardError.ReadToEnd());\n        }	0
15163494	15141157	Format Font Inside Table OpenXML C#	Text heading_text = new Text("Company Name");\n\n////create the run\nRun runHeaderRun = new Run();\n\n////append the run properties and text to the run\nrunHeaderRun.Append(runHeader);\nrunHeaderRun.Append(heading_text);\n\n////append the run to the paragraph\nparaHeader.Append(runHeaderRun);\n\ntc.Append(paraHeader);	0
8669360	8631088	Windows 8 - BeginAnimation?	var storyboard = new Storyboard();\n\nvar opacityAnimation = new DoubleAnimation { \n    From = 0,\n    To = 1,\n    Duration = DurationHelper.FromTimeSpan(TimeSpan.FromSeconds(1)),\n};\nstoryboard.Children.Add(opacityAnimation);\n\nStoryboard.SetTargetProperty(opacityAnimation, "Opacity");\nStoryboard.SetTarget(storyboard, myObject);\n\nstoryboard.Begin();	0
13645733	13645207	Converting the value of a string to a variable of KeyValuePair<TKey,TValue>	Dictionary<int, bool> AntennaIsEnabled = new Dictionary<int, bool>();\nforeach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )\n{\n  var selectedReader = reader;\n\n  //From your example\n  AntennaIsEnabled.Add(1, selectedReader.Value.Antenna1IsEnabled);\n  AntennaIsEnabled.Add(2, selectedReader.Value.Antenna2IsEnabled);\n  AntennaIsEnabled.Add(3, selectedReader.Value.Antenna3IsEnabled);\n  AntennaIsEnabled.Add(4, selectedReader.Value.Antenna4IsEnabled);\n}	0
15768518	15767596	Insert into multiple tables using ado.net entity object	Student student = new Student();\n...\nStandard standard = new Standard();\nstandard.Student = student;\n\n/* Commit it */	0
24673811	24673395	Html page parsing using Html Agility Pack	Regex reg1 = new Regex(@"(\d* (out of) \d*)");\n    for (int i = 0; i < number; i++)\n    {\n      Console.WriteLine("the heading of the movie is {0}", header[i].InnerHtml);\n      Match m = reg1.Match(header[i].InnerHtml);\n\n      if (!m.Success)\n      {\n          return;\n      }\n      else\n      {\n          Regex reg2 = new Regex(@"\d+");\n          m = reg2.Match(m.Value);\n          string str1 = m.Value;\n          string str2 = m.NextMatch().Value;\n\n          if (!Int32.TryParse(str1, out index1))\n          {\n              return;\n          }\n          if (!Int32.TryParse(str2, out index2))\n          {\n              return;\n          }\n          Console.WriteLine("index1 = {0}", index1);\n          Console.WriteLine("index2 = {0}", index2);\n      }\n    }	0
12706232	12706171	Best way for set date creation of file, which downloaded by filestream	File.SetCreationTime(fileName, fileDateTime);	0
11606814	11534878	How to DrawImage without gradation	g.DrawImage(Resources.Resource.RingBinderTop, new Rectangle((this.Size.Width - 49) / 2, 9, 49, 11));\n    g.DrawImage(Resources.Resource.RingBinder, new Rectangle((this.Size.Width - 49) / 2, 20, 49, this.Size.Height - 33));\n    g.FillRectangle(new TextureBrush(Resources.Resource.RingBinderBottom), new Rectangle((this.Size.Width - 49) / 2, this.Size.Height - 20, 49, 11));	0
18595497	18595266	Accessing the properties from a known view his viewmodel	CommandParameter="{Binding ElementName=timePicker, Path=DataContext.ValidTime}"	0
9013800	9013730	Remove duplicates in a list (c#)	// If Equals() returns true for a pair of objects \n// then GetHashCode() must return the same value for these objects.\n\npublic int GetHashCode(Product product)\n{\n    //Check whether the object is null\n    if (Object.ReferenceEquals(product, null)) return 0;\n\n    //Get hash code for the Name field if it is not null.\n    int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();\n\n    //Get hash code for the Code field.\n    int hashProductCode = product.Code.GetHashCode();\n\n    //Calculate the hash code for the product.\n    return hashProductName ^ hashProductCode;\n}	0
5171137	5170716	Loop through all cells in a Excel Column to the end	int i = 0;\n\nwhile (target_range.Offset(i, 0).Value != "")\n{\n    i++;\n}	0
27042713	27042602	Running C# Executable From Iron Python	import clr\nclr.AddReference('MyAssemblyWhichContainsForm.dll')\nimport MyForm\nobj = MyForm("form title")\nobj.Show()	0
21182617	21182555	Converting c# to VB.NET for my windows phone app	AddHandler AccessTokenQuery.QueryResponse, AddressOf AccessTokenQuery_QueryResponse	0
4930045	4928441	Extracting Additional Metadata from a PDF using iTextSharp	PdfReader reader = new PdfReader(YOUR_PDF);\nbyte[] b = reader.Metadata;\nif (b != null) {\n  string xml = new UTF8Encoding().GetString(b);\n}	0
13807720	13807546	Cannot get XPath to work with unnamed namespace	XmlNamespaceManager ns = new XmlNamespaceManager(cd.NameTable);\n        ns.AddNamespace("sp", "http://schemas.xmlsoap.org/soap/envelope/");\n        ns.AddNamespace("sc", "http://sitecore.net/visual/");\n        XmlNode sitecoreRoot = cd.SelectSingleNode("//sp:Envelope/sp:Body/sc:GetXMLResponse/sc:GetXMLResult/sitecore/status", ns);\nvar status = sitecoreRoot.InnerText;	0
31318006	31317693	Foreach keeps looping	Program.AnimalInfo.Info_ID_ListBox.Items.Clear();\n_dataTable.Clear();	0
8539864	8539414	Issues with IE6 panels in asp.net application?	* html div#division { \n   height: expression( this.scrollHeight > 332 ? "333px" : "auto" ); /* sets max-height for IE */\n}\n\ndiv#division {\n   max-height: 333px; /* sets max-height value for all standards-compliant browsers */\n}	0
4184009	4183092	Constructing Dynamic LINQ queries with all properties of an object	public static void CheckMyEntity(IQueryable<ABCEty> _allABCs, MyEntity _myEntity)\n{\n    foreach (var propertyInfo in _myEntity.GetType().GetProperties())\n    {\n        if (!String.IsNullOrEmpty(propertyInfo.GetValue(_myEntity, null).ToString()))\n        {\n            //access to modified closure\n            PropertyInfo info = propertyInfo;\n            _allABCs = _allABCs.Where(temp => temp.ABCMyEntitys.All(GenerateLambda(_myEntity, info)));\n        }\n    }\n    var result = _allABCs.ToList();\n}\n\nprivate static Func<MyEntity, bool> GenerateLambda(MyEntity _myEntity, PropertyInfo propertyInfo)\n{\n    var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");\n    var property = Expression.Property(instance, propertyInfo);\n    var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null));\n    var equalityCheck = Expression.Equal(property, propertyValue);\n    return Expression.Lambda<Func<MyEntity, bool>>(equalityCheck, instance).Compile();\n}	0
5142438	5140744	c# cancel application from closing if hidden form has unsaved changes	Stack<Form> stack = new Stack<Form>();\n            foreach (Form f in Forms)\n            {\n                if (f is Menu)\n                {\n                    //do nothing\n                }\n                else\n                {\n                    if (!f.IsDisposed)\n                    {\n\n\n                        stack.Push(f);\n                    }\n\n                }\n\n            }\n            for (int i = 0; i < stack.Count; i++)\n            {\n                Form temp = stack.Pop();\n                temp.Close();\n            }	0
7125329	7125050	Change the encoding to UTF-8 on a stream (MemoryMappedViewStream)	static void Main(string[] args)\n{\n  using (var file = MemoryMappedFile.CreateFromFile(@"d:\temp\temp.xml", FileMode.Open,  "MyMemMapFile"))\n  {\n     using (MemoryMappedViewStream stream = file.CreateViewStream())\n    {\n        Read(stream);\n    }\n   }\n}\n\nstatic void Read(Stream stream)\n{\n  using (XmlReader reader = XmlReader.Create(new StreamReader(stream, Encoding.UTF8)))\n  {\n     reader.MoveToContent();\n\n    while (reader.Read())\n    {\n    }\n }\n}	0
14828119	14828049	Disable a button in c# under a condition	private void button5_Click(object sender, EventArgs e)\n    {\n        //Agregar\n        arreglo.Add(textBox1.Text.ToString());\n        if (arreglo.Count > 10)\n        {\n            button5.Enabled = false;\n        }\n        this.textBox1.Clear();\n        this.textBox1.Focus();\n    }	0
2617434	2617425	How to POST using WebRequest?	var request = WebRequest.Create("http://www.example.com");\nrequest.Method = "POST";\nrequest.ContentType = "application/x-www-form-urlencoded";\nusing (var writer = new StreamWriter(request.GetRequestStream()))\n{\n    // write to the body of the POST request\n    writer.Write("param1=value1&param2=value2");\n}	0
4046287	4046117	Can automapper be told that a property is ok to be left blank?	Mapper.CreateMap<Src, Dest>()\n    .ForMember(d => d.MyCustomUnmappedProperty, o => o.Ignore());	0
3880494	3880475	split string with more than one Char in C#	string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";\nstring[] stringSeparators = new string[] {"[stop]"};\n\n// Split a string delimited by another string and return all elements.\nstring[] result = source.Split(stringSeparators, StringSplitOptions.None);	0
23135472	20976777	Refresh a web page programmatically	private void RefreshPage()\n{\n    int count = 0;\n    IntPtr[] explorerHandle = new IntPtr[4] { \n        FindWindow(null, "DashBoard - Google Chrome"), \n        FindWindow(null, "DashBoard - Internet Explorer"),\n        FindWindow(null, "DashBoard - Opera"), \n        FindWindow(null, "DashBoard - Firefox")\n    };\n\n    foreach (IntPtr value in explorerHandle)\n    {\n        if (value != IntPtr.Zero)\n        {\n            count++;\n            SetForegroundWindow(value);\n            SendKeys.Send("{F5}");\n        }\n    }\n    if(count == 0)\n        System.Diagnostics.Process.Start("http://localhost:9000/DashBoard.html");\n}	0
3591175	3591089	String immutability in C#	void Frob(Bar bar)\n{\n    if (!IsSafe(bar)) throw something;\n    DoSomethingDangerous(bar);\n}	0
17223508	17223459	How to parse a message from a text file with c# that spans multiple lines?	2013-06-19	0
30191228	22118123	Windows Phone 8 HttpClient Get method returns strange results	client.DefaultRequestHeaders.IfModifiedSince	0
821239	820895	WPF WYSIWYG Editor	public MyControl()\n{\n    InitializeComponent();\n\n    editor.Navigated += new NavigatedEventHandler(editor_Navigated);\n    editor.NavigateToString("<html><body></body></html>");\n}\n\nvoid editor_Navigated(object sender, NavigationEventArgs e)\n{\n    var doc = editor.Document as IHTMLDocument2;\n\n    if (doc != null)\n        doc.designMode = "On";\n}	0
3099765	3099689	How to search for any text in List<String>	string serachKeyword ="o";\n\nList<string> states = new List<string>();\nstates.Add("Frederick");\nstates.Add("Germantown");\nstates.Add("Arlington");\nstates.Add("Burbank");\nstates.Add("Newton");\nstates.Add("Watertown");\nstates.Add("Pasadena");\nstates.Add("Maryland");\nstates.Add("Virginia");\nstates.Add("California");\nstates.Add("Nevada");\nstates.Add("Ohio");\n\nList<string> searchResults = states.FindAll(s => s.Contains(serachKeyword));	0
31096667	31095937	phrase text too big for one page	pdfTable.SplitLate = false;	0
19544284	19501245	Inject NServiceBus with Ninject in WebApi App	Configure.Serialization.Xml();\n      Configure.Transactions.Disable();\n      Configure.With()\n      .NinjectBuilder(kernel)\n      .UseTransport<Msmq>()\n      .UnicastBus()\n      .SendOnly();	0
26678214	26674330	Can't capture traffic with FiddlerCore with mobile user-agent in a Windows service	chrome.exe --proxy-server=127.0.0.1:8888	0
714104	714091	Client/Server both give up after 1 connection	private void ListenForClients()\n{\n    while(true)\n    {\n        TcpClient client = listener.AcceptTcpClient();\n        new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client);\n    }\n}	0
21956156	21956116	How can I aggregate a list of string in a Linq query?	OrderNumbers = string.Join("", r.Processes.Select(p=>p.OrderNumber)),	0
4817288	4817173	How can I programatically determine which application is locking a file?	try\n {\n    using (Stream stream = new FileStream("MyFilename.txt"))\n   {\n   }\n } catch {\n   //check here why it failed and ask user to retry if the file is in use.\n}	0
2759029	2758336	Find a part of UNC path and put in a variable?	Uri uri = new Uri(@"\\ourfileserver\remoteuploads\countyfoldername\personfoldername");\n    Console.WriteLine(uri.Segments[3]); // personfoldername\n    Console.ReadLine();	0
21042980	21042811	Replace characters === either side of text with html tags	var yourstring = "===20th and 21st centuries===";\nvar regex = new Regex(Regex.Escape("==="));\n// The last 1 tells to replace only the first occurence of the Escape\nyourstring = regex.Replace(yourstring, "</p><p class=\"strong\">", 1);\nyourstring = regex.Replace(yourstring, "<p>", 1);	0
15873835	15873760	How to send the value to textbox programatically?	int CurrentIndex;\n        private void textNumber_Click(object sender, EventArgs e)\n        {\n            CurrentIndex = textNumber.SelectionStart;\n        }\n\n        private void Key_Click(object sender, EventArgs e)\n        {\n            textNumber.Text = textNumber.Text.Insert(CurrentIndex, "_");\n        }	0
26405295	26404679	Parallel loops running at different intervals	private System.Timers.Timer _timer;\nprivate int _delaySeconds = 5;\n\nvoid Main()\n{\n    // timer prevents threads from overlapping modify with care\n    _timer = new System.Timers.Timer();\n    _timer.Interval = _delaySeconds*1000;\n    _timer.AutoReset = true;        // important to prevent overlap\n    _timer.Elapsed += OnProcess;\n\n    _timer.Start();\n}\n\nprivate void OnProcess(object sender, System.Timers.ElapsedEventArgs args)\n{\n    // timer prevents from thread overlapping modify with care\n    _timer.Stop();\n\n    // do work\n    Debug.WriteLine("Processing on thread. [{0}]", Thread.CurrentThread.ManagedThreadId).Dump("this");\n\n    // setting the interval resets the timer\n    _timer.Interval = _delaySeconds*1000;\n    _timer.Start();\n}	0
16362674	16362184	Cannot serialize the derived property to JSON in Web API	[TestClass]\npublic class UnitTest8\n{\n    [TestMethod]\n    public void TestJasonFileFolder()\n    {\n        var folder = new FileFolder();\n        folder.Folder = new FileFolder { Name = "Parent" };\n        folder.Name = "Something";\n\n        var document = new Document { Folder = folder, Id = 1 };\n\n        var test = JsonConvert.SerializeObject(document);\n        Assert.IsNotNull(test);\n    }\n}\n\npublic class Document\n{\n    public int Id { get; set; }\n    public FileFolder Folder { get; set; }\n    public FileFolder FolderParent\n    {\n        get\n        {\n            return this.Folder.Folder;\n        }\n    }\n}\n\npublic class FileFolder\n{\n    public string Name { get; set; }\n    public FileFolder Folder { get; set; }\n}	0
26583039	26582831	Get a part of string	bool isNumeric = Regex.IsMatch(getucoid, @"^\d+$");	0
503359	503263	How to determine if a type implements a specific generic interface type	bool isBar = foo.GetType().GetInterfaces().Any(x =>\n  x.IsGenericType &&\n  x.GetGenericTypeDefinition() == typeof(IBar<>));	0
6822552	6822175	MSChart Custom Y Axis Value Range	chart1.ChartAreas[0].AxisY.CustomLabels.Add(0, 1, "LOW"); \n// it means: on Y range = [0, 1] show the label "LOW" ...\n\nchart1.ChartAreas[0].AxisY.CustomLabels.Add(2, 3, "MEDIUM");\nchart1.ChartAreas[0].AxisY.CustomLabels.Add(3, 4, "HIGH");	0
27362206	27325678	Include image from website in mailitem.HTMLBody	void OutlookApplication_ItemSend(object Item, ref bool Cancel)\n    {\n\n        if (Item is Outlook.MailItem)\n        {\n            Outlook.Inspector currInspector;\n            currInspector = outlookApplication.ActiveInspector();\n            Outlook.MailItem oldMailItem = (Outlook.MailItem)Item;\n            Outlook.MailItem mailItem = oldMailItem.Copy();\n            string image = "<img src='http://someserver.com/attach.jpg' width=\"1\" height=\"1\" alt=\"\" />";\n            string body = mailItem.HTMLBody;\n\n            body = body.Replace("</body>", image+"</body>");\n\n            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;\n            mailItem.HTMLBody = body;\n\n            mailItem.Send();\n            Cancel = true;\n            currInspector.Close(Outlook.OlInspectorClose.olDiscard);\n        }\n    }	0
8795483	7921833	Custom functions unavailable from BrowserInteropHelper.HostScript in an XBAP	BrowserInteropHelper.HostScript	0
27336918	27336890	Select from list 2 fields and join them as string	String.Join(", ", list.Select(p => String.Format("{0}({1})", p.Name, p.Quantity)))	0
713283	713277	find the hwnd of a window which user selects, through c#	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\npublic class MainClass\n\n    // Declare external functions.\n    [DllImport("user32.dll")]\n    private static extern IntPtr GetForegroundWindow();\n\n    [DllImport("user32.dll")]\n    private static extern int GetWindowText(IntPtr hWnd,\n                                            StringBuilder text,\n                                            int count);\n\n    public static void Main() {\n        int chars = 256;\n        StringBuilder buff = new StringBuilder(chars);\n\n        // Obtain the handle of the active window.\n        IntPtr handle = GetForegroundWindow();\n\n        // Update the controls.\n        if (GetWindowText(handle, buff, chars) > 0)\n        {\n            Console.WriteLine(buff.ToString());\n            Console.WriteLine(handle.ToString());\n        }\n    }\n}	0
4780552	4780138	Browse Secure Web pages in wpf web browser control	WebClient client = new WebClient();\nbyte[] dataBuffer = client.DownloadData("https://www.gmail.com");\nstring data = Encoding.ASCII.GetString(dataBuffer);\nwebBrowser.NavigateToString(data);	0
1874184	1874132	How to remove all comment tags from XmlDocument	XmlReaderSettings settings = new XmlReaderSettings();\nsettings.IgnoreComments = true;\nXmlReader reader = XmlReader.Create("...", settings);\nxmlDoc.Load(reader);	0
16846727	16846523	Getting filenames without extensions except for duplicates	Directory.GetFiles(folderName)\n.Where(f => !f.EndsWith(".blah"))\n.Select (f => new FileInfo(f))\n.Select(f => new { NoExt = Path.GetFileNameWithoutExtension(f.Name),  f.Name})\n.GroupBy (f => f.NoExt)\n.SelectMany(g => g.Count() > 1 ? g.Select(f => f.Name) \n                               : g.Select (f => f.NoExt))	0
6216495	6216367	Copying from one stream to another?	public static void WriteTo(Stream sourceStream, Stream targetStream)\n{\n       byte[] buffer = new byte[0x10000];\n       int n;\n       while ((n = sourceStream.Read(buffer, 0, buffer.Length)) != 0)\n           targetStream.Write(buffer, 0, n);\n}	0
1669412	1667744	How do you end an Application from a Web Method within a Web Service?	Session.Contents.Abandon();	0
19308313	19304207	Event from external callback	class Transmitter\n{\n    LibWrapper lib = new LibWrapper();\n    private AutoResetEvent evt = new AutoResetEvent(false);\n    byte[] data;\n\n    public void OnDataSendingDone(UInt32 handle)\n    {\n        evt.Set();\n    }\n\n    public void TransmitData()\n    {\n        // here: sequential data transmission   \n        foreach (byte b in data)\n        {\n            lib.SendByte(b);\n            if (!evt.WaitOne(15000)) // or whatever timeout makes sense\n                throw new Exception("timed out");\n        }\n    }\n}	0
7233466	7233437	How to redirect to a different page from a javascript alert box in a .net application?	String csScriptText = "alert(' settings have been saved ');document.location='http://.../newurl.htm'";	0
33701776	33701552	Connecting to a database based on a course I follow	using (var command = DbProviderFactories.GetFactory(provider).CreateCommand()) // here you've created the command
\n            {
\n                if (command == null) return null;
\n
\n                command.CommandType = CommandType.Text;
\n                command.Connection = connection;
\n                command.CommandText = "SELECT * FROM Continent";
\n
\n                using (var reader = command.ExecuteReader()) //Here you're reading what the command returned.
\n                    while (reader.Read())
\n                        continents.Add(new Continent(reader["Code"].ToString(), reader["EnglishName"].ToString()));
\n            }	0
32475015	32474210	Serialization of derived FixedDocument	internal bool IsSerializedObjectTypeSupported(object serializedObject)\n{\n  bool flag = false;\n  Type type = serializedObject.GetType();\n  if (this._isBatchMode)\n  {\n    if (typeof (Visual).IsAssignableFrom(type) && type != typeof (FixedPage))\n      flag = true;\n  }\n  else if (type == typeof (FixedDocumentSequence) || type == typeof (FixedDocument) || (type == typeof (FixedPage) || typeof (Visual).IsAssignableFrom(type)) || typeof (DocumentPaginator).IsAssignableFrom(type))\n    flag = true;\n  return flag;\n}	0
1047680	1047531	Splitting Comma Separated Values (CSV)	using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace CSV\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            string csv = "user1, user2, user3,user4,user5";\n\n            string[] split = csv.Split(new char[] {',',' '});\n            foreach(string s in split)\n            {\n                if (s.Trim() != "")\n                    Console.WriteLine(s);\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
7444458	7444371	Closure in predicates with delegates unknown at compile-time	public List<Person> getPeopleFromClassLowerThanLimit(int classId, int height)\n{\n    Database db = new Database();\n    return db.Persons.Where(p => isLowerThan(p, classId, height)).ToList();\n}\n\nprivate bool isLowerThan(Person person, int classId, int height)\n{\n\n}	0
2987950	2987521	Dynamic control click event not firing properly	Visible = false	0
5736829	5736701	Bind data to repeater on button click from user control in another repeater	repeater.ItemCreated += new ItemCreatedEventHandler()	0
22308727	22291282	Using SendInput to send unicode characters beyond U+FFFF	public static void SendCharUnicode(int utf32)\n{\n    string unicodeString = Char.ConvertFromUtf32(utf32);\n    Win32.INPUT[] input = new Win32.INPUT[unicodeString.Length];\n\n    for (int i = 0; i < input.Length; i++)\n    {\n        input[i] = new Win32.INPUT();\n        input[i].type = Win32.INPUT_KEYBOARD;\n        input[i].ki.wVk = 0;\n        input[i].ki.wScan = (short)unicodeString[i];\n        input[i].ki.time = 0;\n        input[i].ki.dwFlags = Win32.KEYEVENTF_UNICODE;\n        input[i].ki.dwExtraInfo = IntPtr.Zero;\n    }\n\n    Win32.SendInput((uint)input.Length, input, Marshal.SizeOf(typeof(Win32.INPUT)));\n}	0
17589121	17588971	Comma separated values from SQL, getting distinct values and their count	var groupedResults = results.SelectMany(v => v.Split(','))\n                        .GroupBy(n => n)\n                        .Select((item, index) => \n                                 new {\n                                    name = String.Format("{0}) {1}", index+1, item.Key),\n                                    count = item.Count()\n                                 })\n                        .ToList();	0
18348076	18347245	Parsing JSON result from web link	var json = @"{'Warranty':[{'EndDate':'ValueIWant','ServiceLevelDescription':'ValueIWant'}]}";\n\nvar j = JObject.Parse(json);\n\nforeach(var o in j["Warranty"])\n{\n    Console.WriteLine("Warranty end date: {0}", (string)o["EndDate"]);\n    Console.WriteLine("Warranty service level description: {0}", (string)o["ServiceLevelDescription"]);\n}	0
32824285	32824125	Check union of delimited strings for duplicates	items\n    .Select(x=>x.Split(',').Select(y=>y.Trim()).ElementAt(0))\n    .Any(x=>x == newfilename);	0
8305745	8305712	How do I combine the contents of two lists?	int[] combinedWithoutDups = oldItemarry1.Union(newItemarry1).ToArray();	0
29412345	29412083	Getting all entry Elements within a Namespace from XML using XPath	var nsm = new XmlNamespaceManager(rssXmlDoc.NameTable);\nnsm.AddNamespace("atom", "http://www.w3.org/2005/Atom");\n\nvar entries = rssXmlDoc.SelectNodes("/atom:feed/atom:entry", nsm);	0
19229408	19229129	Often used LINQ returned from method	var expression = GetFilteredEntity();\ndb.ParentEntities.Where(entity => entity.MyEntities.Where(expression ));	0
13166015	11667162	Set range for values for graph axes using DynamicDataDisplay	var axis = (DateTimeAxis)productPlot.MainHorizontalAxis;\ndouble yMin = 0;\ndouble yMax = 100;       \nRect domainRect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin);\n//xMin and xMax are left to your discretion based on your DateTimeAxis\n\nplotter.ViewPort.Domain = domainRect;	0
24450341	24449299	Encode error in while showing data	"s/\/\\/g"	0
18814445	18814350	Find control by id in a UserControl structure	private Control FindControlRecursive(Control root, string id)\n{\n    if (root.ID == id)\n        return root;\n\n    foreach (Control control in root.Controls)\n    {\n        Control found = RecursiveFindControl(control, id);\n        if (found != null)\n            return found;\n    }\n\n    return null;\n}	0
14134335	14134021	How to loop usercontrol	private const int gap = 20;\nprivate int count = 0;\nprivate void button1_Click(object sender, EventArgs e)\n{\n    var add = new UserControl1();\n    add.Top = count * (add.Height + gap);\n    show_pnl.Controls.Add(add);\n    count++;\n}	0
2988794	2988786	how do you add a condition to a lambda expression	return MyArray.Where(r => r.CanDrive).Sum(r => r.Trips);	0
1956632	1939774	How to get the value of abstract property in xsd file	XmlSchemaComplexType.IsAbstract	0
13872457	13871286	Posting Soap XML in Windows 8 Metro App - Errors	req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/soap+xml;charset=UTF-8");	0
29223779	29223649	Amazon S3 server side encryption	TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest\n{\n    BucketName = existingBucketName,\n    FilePath = filePath,\n    StorageClass = S3StorageClass.ReducedRedundancy,\n    PartSize = 6291456, // 6 MB.\n    Key = keyName,\n    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256\n};\nfileTransferUtility.UploadAsync(fileTransferUtilityRequest, someCancelToken);	0
4747416	4741726	Silverlight 3 Button - Text + Image Alignment Problems	button.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;	0
12628205	12628169	How can I convert a null value to string.empty before it has a chance to throw an exception?	object cellValue = \n    dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value;\nprevValue = cellValue == null ? string.Empty : cellValue.ToString()	0
1407314	1400916	Microsoft Solver Foundation Services declarative syntax	SolverContext context = SolverContext.GetContext();\nModel model = context.CreateModel();\n\nDecision[] slot = new Decision[10];\n\nfor (int i = 0; i < slot.Length; i++)\n{\n    slot[i]  = new Decision(Domain.IntegerRange(1, 5), "slot" + i.ToString());\n    model.AddDecision(slot[i]);\n    if (i > 0) model.AddConstraint("neighbors not equal", slot[i-1] != slot[i]);\n}\n\nmodel.AddConstraint("sum", Model.Sum(slot) > 20);\n\nSolution solution = context.Solve();	0
7476353	7446478	Changing the value in a drop down list Excel C#	using Excel = Microsoft.Office.Interop.Excel;\n\n  public virtual Object ActiveSheet { get; set; }\n\n  private void button15_Click(object sender, EventArgs e)\n    {\n        //Gets ActiveSheet to Modify\n        Excel.Application oXL;\n        Excel.Workbook oWB;\n        Excel.Worksheet oSheet;\n\n        //Start Excel and get Application object.\n        oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); \n        oXL.Visible = true;\n        oWB = (Excel.Workbook)oXL.ActiveWorkbook; \n        oSheet = (Excel.Worksheet)oWB.ActiveSheet;\n\n        //Generate Linear Guide Supports using Design Table in Solidworks\n        if (comboBox1.Text == "0")//no external rails\n        {\n            oSheet.Cells[6, 4] = "0"; //Change Value in Cell in Excel Cell Location [y-axis, x-axis]\n        }\n        //Quit Excel\n        oXL.Quit();\n    }	0
31409842	31409678	Log to database with EF Code First	Pooling=false	0
24957462	24956284	Umbraco how to use image property id to get URL	var bannerId = Umbraco.Media(banner.image); //banner.image is the property id.\n var bannerUrl = bannerId.Url;	0
25991525	25991430	VS2013 - Moving a simple Breakpoint	Debug / Exceptions ...	0
31018720	31018590	Pairing Values from List in C#?	string[] array = {"A", "B", "C", "D"};\n    var pairs = new List<string[]>();\n    for (int i = 0; i < array.Length; i++)\n    {\n        for (int j = i + 1; j < array.Length; j++)\n        {\n            pairs.Add(new []\n            {\n                array[i],\n                new string(array[j].ToCharArray().Except(array[i].ToCharArray()).ToArray<char>())\n            });\n        }\n    }\n\n    /*output of pairs\n    A, B\n    A, C\n    A, D\n    B, C\n    B, D\n    C, D\n    */	0
12507824	12507162	Get column name from Linq to Sql Entity	var column = typeof(Person).GetProperty("FirstName")\n    .GetCustomAttribute(typeof(ColumnAttribute, false)\n        as ColumnAttribute;\n\nvar name = column.Name;	0
512711	512651	How is Java's notion of static different from C#'s?	// My naive C# attempt:P\n\npublic class Property \n{\n\n    public static void main( String []args ) \n    {\n         Property p = Property.buildFrom( new Builder("title").Area("area").Etc() )\n    }\n    public static Property buildFrom( Builder builder ) \n    {\n        return new Propert( builder );\n    }\n\n    private Property ( Builder builder ) \n    {\n        this.area = builder.area;\n        this.title = builder.title;\n        // etc. \n    }\n}\npublic class Builder \n{\n    public Builder ( String t ) \n    {\n       this.title = t;\n    }\n\n    public Builder Area( String area )\n    {\n       this.area = area;\n       return this;\n    }\n    // etc. \n}	0
32601358	32600926	How do I stop text expanding horizontally in RDLC?	Can Grow	0
21009772	21009624	Reasons of working slowly and solution of that	System.Windows.Forms.WebBrowser	0
11213220	11213091	Inserting into database from textbox in C# using parameters	string connectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated  Security=True;User Instance=True";\n\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n\n    using (SqlCommand insertCommand = connection.CreateCommand())\n\n        {\n            insertCommand.CommandText = "INSERT INTO address(name,age,city) VALUES (@na,@ag,@ci)";\n            insertCommand.Parameters.Add("@na", na);\n            insertCommand.Parameters.Add("@ag", ag);\n            insertCommand.Parameters.Add("@ci", ci);\n\n\n            insertCommand.Connection.Open();\n            insertCommand.ExecuteNonQuery();\n\n\n        }\n}	0
32895460	32849500	Console hosted WCF data service with transport security running but not found by clients	netsh http add sslcert ipport=0.0.0.0:8900 appid={cc57b9c6bbd7-468d-81be-779e6a74099e} certhash=a36f22858609f04b123cea1810c7146332f8a06e	0
22444096	22443752	How to extract a folder from zip file using SharpZipLib?	using System;\nusing ICSharpCode.SharpZipLib.Zip;\n\nvar zipFileName = @"T:\Temp\Libs\SharpZipLib_0860_Bin.zip";\nvar targetDir = @"T:\Temp\Libs\unpack";\nFastZip fastZip = new FastZip();\nstring fileFilter = null;\n\n// Will always overwrite if target filenames already exist\nfastZip.ExtractZip(zipFileName, targetDir, fileFilter);	0
30097143	30096783	Word translator from XML file	node.Attributes["id"].Value	0
1058850	1058783	Regular expression to find and remove duplicate words	var words = new HashSet<string>();\nstring text = "I like the environment. The environment is good.";\ntext = Regex.Replace(text, "\\w+", m =>\n                     words.Add(m.Value.ToUpperInvariant())\n                         ? m.Value\n                         : String.Empty);	0
3007178	3006985	C#: How to bind HashTable to a ComboBox via Enum as a key?	comboResult.SelectedValue = m_defaultResult;	0
31532795	31532302	Browsing gataGridView using entity framework	dataGridView1.DataSource = yourListOfPocos.Where(a => a.Name == searchString).ToList();	0
14897013	14896630	Stretch and center a popup in Metro apps	//Here is where I get a bit tricky.  You see namePromptPopup.ActualWidth will show\n//the full screen width, and not the actual width of the popup, and namePromptPopup.Width\n//will show 0 at this point.  So we needed to calculate the actual\n//display width.  I do this by using a calculation that determines the\n//scaling percentage from the height, and then calculates that against my\n//original width coding.\nnamePromptPopup.HorizontalOffset = (currentWindow.Bounds.Width / 2) - (400 / 2);\nnamePromptPopup.VerticalOffset = (currentWindow.Bounds.Height / 2) - (150 / 2);	0
5955496	5955459	How to use properties to expose a private array as read-only?	class MyClass {\n    public int[] MyValues { get; protected set; }\n\n    public MyClass() {\n        MyValues = new [] {1, 2, 3, 4, 5};\n    }\n\n    public void foo {\n        foreach (int i in MyValues) {\n            Trace.WriteLine(i.ToString());\n        }\n    }\n}\n\nMyOtherClass {\n    MyClass myClass;\n\n    // ...\n    void bar {\n        // You can access the MyClass values in read outside of MyClass, \n        // because of the public property, but not in write because \n        // of the protected setter.\n        foreach (int i in myClass.MyValues) {\n            Trace.WriteLine(i.ToString());\n        }\n    }\n}	0
33625317	33620658	Download an image generated dynamically rather than display in browser	[AllowAnonymous]\npublic FileResult URLToImage(string url)\n{\n    // In some cases you might want to pull completely different URL that is not related to your application.\n    // You can do that by specifying full URL.\n    UrlAsImage urlImg = new UrlAsImage(url)\n    {\n        FileName = Guid.NewGuid().ToString() + ".jpg",\n        PageHeight = 630,\n        PageWidth = 1200\n    };\n    Response.AddHeader("Content-Disposition", "inline; filename="+urlImg.FileName);\n    return File(urlImg.BuildFile(this.ControllerContext), "image/jpg");\n}	0
12504715	12500604	Mapping relationships to collections of abstractions in Entity Framework	public class ProductBase\n{\n    public string ProductId { get; set; }\n    public string CategoryId { get; set; }\n}\n\npublic class CategoryBase\n{\n    public string CategoryId { get; set; }\n    public virtual ICollection<ProductBase> Products { get; set; }\n}\n\npublic class DerivedProduct : ProductBase\n{\n}\n\npublic class DerivedCategory : CategoryBase\n{\n}	0
14066943	14058485	C# ODATA , Expand N Level with sub-entities	URI = "mebs_schedule({0})?$expand=mebs_ingesta/mebs_videoitem,mebs_ingesta/mebs_ingestadetails,mebs_ingesta/mebs_channel/mebs_channeltuning"	0
11967649	11967495	Count the occurrence of strings in an array	Dictionary<string, int> dictionary = new Dictionary<string, int>();\n    foreach (string word in words)\n    {\n        if (dictionary.ContainsKey(word))\n        {\n            dictionary[word] += 1; \n        }\n        else\n        {\n            dictionary.Add(word,1);\n        }\n    }	0
555067	555022	Silverlight InitParams where value has a comma	key1=value1,key2=two|values	0
33146518	33141963	Create DTO by joining EF entity with another object in LINQ	public IEnumerable<DTO> GetDtos(IQueryable<OtherObject> otherObjects) \n{\n   var ids = otherObjects.Select(x => x.SomeId);\n   return _someRepository.GetAll()\n          .Where(x => ids.Contains(x.SomeId)\n          .ToList()\n          .Select(x =>\n                 new DTO()\n                 {\n                    EntityProperty1 = x.EntityProperty1,\n                    EntityProperty2 = x.EntityProperty2, \n                    EntityProperty3 = x.EntityProperty3,\n                    OtherObjectEntity1 = otherObjects.FirstOrDefault(p => p.SomeId == x.SomeId).OtherObjectEntity1\n                 };\n}	0
25304509	22978754	Send SqlParameter to Dapper	var args = new DynamicParameters(new {});\nparameters.ForEach(p => args.Add(p.ParameterName, p.Value));\nconn.Query<TModel>(sql, args );	0
26003936	26003751	Passing variable double[]	class X\n{\n    double[] value1;\n    double[] value2;\n\n    protected void btn1_Click(object sender, EventArgs e)\n    {\n        double[] val1 = {...};\n        value1 = val1;\n        double[] val2 = {...};\n        value2 = val2;\n    }\n}	0
6977818	6962621	Decouple connection string from Backend code	private string GetWebConfigConnection()\n    {\n\n        string conString = string.Empty;\n        System.Configuration.Configuration rootWebConfig =\n            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/WebSite21"); // give your web site name here\n\n        System.Configuration.ConnectionStringSettings connString;\n        if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)\n        {\n            connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MainConnStr"]; // give your connection string name here\n            if (connString != null)\n                conString=  connString.ConnectionString;\n        }\n\n        return conString;\n    }	0
5497060	5496969	Outlook 2007/2010 context menu item picture	contextButton.Style=MsoButtonStyle.msoButtonIconAndCaption	0
29477851	29477498	Get File Extension of File Dropped Onto Windows Form	private void Form1_DragEnter(object sender, DragEventArgs e) {\n        if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;\n        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n        foreach (var file in files) {\n            var ext = System.IO.Path.GetExtension(file);\n            if (ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase) ||\n                ext.Equals(".txt",  StringComparison.CurrentCultureIgnoreCase)) {\n                e.Effect = DragDropEffects.Copy;\n                return;\n            }\n        }\n    }	0
34026815	34025603	Map values from parent class	var retModel = new ChildItemDTO();\n       ParentItemDTO.Map(model, retModel);\n       // map child-specific fields here	0
3290419	3289450	Getting nested data out of JSON in C#	dynamic jsonData = jsonObject;\nint workflowNum = jsonData.SecondPerson[0].workflow;	0
16579241	16564561	A pop-up element containing a web-view with video	Popup popup = new Popup();\n\n        Grid panel = new Grid();\n\n        panel.Height = 250;\n        panel.Width = 250;\n\n        panel.Transitions = new TransitionCollection();\n        panel.Transitions.Add(new PopupThemeTransition());\n        WebView web = new WebView();\n        //web.HorizontalAlignment = HorizontalAlignment.Center;\n        //web.VerticalAlignment = VerticalAlignment.Center;\n        web.Navigate(item.PlayerUri);\n        popup.Child = panel;\n        panel.Children.Add(web);\n        popup.HorizontalAlignment = HorizontalAlignment.Center;\n        popup.VerticalAlignment = VerticalAlignment.Center;\n\n\n        popup.HorizontalOffset = (Window.Current.Bounds.Width / 2 - panel.Width / 2);\n        popup.VerticalOffset = (Window.Current.Bounds.Height / 2 - panel.Height / 2);\n\n        popup.IsOpen = true;\n        UpdateLayout();	0
1612705	1610666	Area constraint blows up my physics simulation if a body slams into it too fast	if (!atom.IsStatic)\n{\n    if (atom.Position.X - atom.Radius < _min.X && atom.Velocity.X < 0)\n    {\n        atom.ReverseVelocityDirection(true, false);\n    }\n    if (atom.Position.X + atom.Radius > _max.X && atom.Velocity.X > 0)\n    {\n        atom.ReverseVelocityDirection(true, false);\n    }\n    if (atom.Position.Y - atom.Radius < _min.Y && atom.Velocity.Y < 0)\n    {\n        atom.ReverseVelocityDirection(false, true);\n    }\n    if (atom.Position.Y + atom.Radius > _max.Y && atom.Velocity.Y > 0)\n    {\n        atom.ReverseVelocityDirection(false, true);\n    }\n}	0
21578366	21575264	Search by category Exchange Server EWS	ExchangeService service = GetService(); \n\nvar iv = new ItemView(1000);\nstring aqs = "System.Category:Processed";\nFindItemsResults<Item> searchResult = null;\ndo\n{\n    searchResult = service.FindItems(WellKnownFolderName.Inbox, aqs, iv);\n    foreach (var item in searchResult.Items)\n    {\n        Console.WriteLine(item.Subject);\n    }\n    iv.Offset += searchResult.Items.Count;\n} while (searchResult.MoreAvailable == true);	0
24142823	24142655	MVVM Pattern in Master-Detail when editing details	public ItemType SelectedItem\n{\n    get { return _selectedItem; }\n    set\n    {\n        _selectedItem = value;\n        // your logic here\n    }\n}	0
22145964	22145545	How To Set Time Interval using SQL server	declare @Start time\ndeclare @end time\ndeclare @request int\n\nset @Start = '08:00:00'\nset @end = '16:00:00'\nset @request = 1\n\n;with Dates as (\n    select @request as reqId,@Start as reqDate\n    union all\n    select reqId+1,DATEADD(MINUTE,10,reqDate) from Dates\n    where reqDate < @end\n)\nselect reqId,convert(varchar(8),reqDate,100)+'-'+convert(varchar(8),DATEADD(MINUTE,10,reqDate),100) "Time Interval" from Dates	0
34133666	34133548	Show ButtonField of gridview dynamically	if(IsExpert || IsAgent)\n    GridView1.Columns[9].Visible=true;\n else\n    GridView1.Columns[9].Visible=false;	0
26786229	26714646	How to change a JS GameObject using C#?	GameObject temp = GameObject.Find ("player(Clone)/LocalSHIP");
\nGameObject.Find("gameMgr").GetComponent<radarScript>().Transforms[0] = temp.transform;	0
34439849	34439737	How to pass email address in the format test@test1.com in an update query to the Access DB	string em = "test@" + comId + ".com";\n  string cmd = "UPDATE tblWebUsers SET Email ='"+ em +"' WHERE CustRole = 'SuperAdmin'";\n  OleDbCommand cmdv3 = new OleDbCommand(cmd, con);\n  cmdv3.ExecuteNonQuery();	0
16450529	16450500	Recursively checking for a duplicate random number in a database	public int GenerateNumber()\n{\n    Random r = new Randon();\n    int num = r.Next(1000);\n\n    while(num is in database)\n    {\n        num = r.Next(1000);\n    }\n\n    return num;\n}	0
27016715	27016582	Get concrete property that implements type	var type = instance.GetType().GetProperty("Bar").GetValue(instance,null).GetType()	0
13802289	13796285	To access the button on the server side	protected void TreeList_HtmlDataCellPrepared(object sender, TreeListHtmlDataCellEventArgs e)\n{\n    int empId = (int) e.GetValue("EmpID");\n    if ("EditColumn".Equals(e.Column.FieldName) && empId == 1)\n    {\n        ASPxButton button = (ASPxButton) treeList.FindDataCellTemplateControl(e.NodeKey, e.Column, "btnSample");\n        if (button != null)\n            button.Visible = false;\n    }\n}	0
27023637	27018523	Continuously update control (listBox) from live feed (file) c#	if (this._listbox.InvokeRequired)\n            this._listbox.Invoke(new MethodInvoker(delegate\n            {\n                this._listbox.Items.Add(newItem);\n\n            }));\n        else\n            this._listbox.Items.Add(newItem);	0
34097755	34097561	How to sort an array of strings taken from textbox1 and display the change in textbox2 in C#?	string[] myArray= textBox.Text.Split(" "); \ntextBox2.Text= string.Join(" ", myArray.OrderByDescending(s => s.Length));	0
3762883	3762541	Get all base property declarations within a class hierarchy	static void GetProperties(Type type)\n    {\n        if (type.BaseType != null)\n        {\n            GetProperties(type.BaseType);\n        }\n\n        foreach (var item in type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public))\n        {\n            MethodInfo method = item.GetGetMethod();\n            MethodInfo baseMethod = method.GetBaseDefinition();\n\n            System.Diagnostics.Debug.WriteLine(string.Format("{0} {1}.{2} {3}.{4}", type.Name, method.DeclaringType.Name, method.Name, baseMethod.DeclaringType, baseMethod.Name));\n\n            if (baseMethod.DeclaringType == type)\n            {\n                Console.WriteLine("{0} {1}", type.Name, item.Name);\n            }\n        }\n    }	0
29279157	29273595	Adding a new item to SharePoint 2010 list using client OM without retrieving the whole list	var list = ctx.Web.Lists.GetByTitle(listTitle); //get List object reference (note, it is not initialized until requested from the server) \n\nvar itemCreateInfo = new ListItemCreationInformation();\nvar listItem = list.AddItem(itemCreateInfo);   \nlistItem[propertyName] = propertyValue;\nlistItem.Update();     //prepare to create new List Item\nctx.ExecuteQuery();   //submit request to the server goes here	0
10156701	10156662	Need helping converting some method from C# to VB.net (Windows Phone 7)	AddHandler Play, Sub(_, __)\n'Do something here\nEnd Sub\n\nAddHandler camRecorder.Initialized, Sub(___, ____)\n'Do something here\nEnd Sub\n\nNew Thread(Sub()\n'Do something here\nEnd Sub).Start()	0
14434450	14432134	Incorrect Log On parameters When Exporting Crystal Report Document To PDF	rep.SetDataSource(ds.Tables[0]);\n        if (ds.Tables.Count > 1)\n        {\n            if (ds.Tables[1].Rows.Count > 0)\n            {\n                rep.OpenSubreport("Subrep1").SetDataSource(ds.Tables[1]);\n            }\n\n        }\n\n\n\nrep.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "ABCDReport");	0
20671510	20671419	Grouping Strings and Adding into a list	list.Select(item => item.Split('/'))\n    .GroupBy(tokens => tokens[0], tokens => tokens[1])\n    .Select(g => new TheClass\n                     {\n                         Category = g.Key,\n                         SubCategory = g.ToList()\n                     });	0
24518556	24518497	Select section of list of custom type into new list of type double	List<double> values = SalesList.Skip(149).Take(200).Select(s => s.Value_USD).ToList()	0
16798354	16798039	Java BigInteger to byte array equivalent in .NET	sbyte[] key = BigInteger.Parse(keyString, NumberStyles.HexNumber).ToByteArray().Reverse().Select(x => (sbyte)x).ToArray();	0
27022165	27021953	how do you import a C .DLL file to a C# windows form application and call its functions that are defined in headers?	int channels = 0;\nNativeMethods.SPI_GetNumChannels(ref channels);\ntextBox1.Text = channels.ToString();	0
23009154	23008251	How to do async 'paged' processing of EF select result	public IEnumerable<ProcessQueueItem> Generate(Guid batchId)\n    {\n        var accounts = this.AccountStatusRepository.GetAccountsByBatchId(batchId.ToString());\n\n        foreach (var accountStatuse in accounts)\n        {\n            yield return accountStatuse.AsProcessQueueItem(batchId);\n        }\n    }	0
6190870	6190816	Random Pick 2 Int as an option	int RandomTolerance=random.Next(0,2)<1?5:10;	0
21042283	21042135	Adding an item to a list	class MapLocation\n    {\n        public MapLocation()\n        {\n        }\n\n        public LatLng Location {get; set;}\n        public BitmapDescriptor icon {get; set;}\n        public String Snippet {get; set;}\n        public String Title {get; set;}\n    }\n}	0
11931696	11931582	Get IP address from hostname in LAN	public static void DoGetHostAddresses(string hostname)\n{\n\n   IPAddress[] ips;\n\n    ips = Dns.GetHostAddresses(hostname);\n\n    Console.WriteLine("GetHostAddresses({0}) returns:", hostname);\n\n    foreach (IPAddress ip in ips)\n    {\n        Console.WriteLine("    {0}", ip);\n    }\n}	0
1669052	1668870	Suggest a good method for having a number with high precision in C#	System.Numerics.BigInteger	0
5542860	5541818	C# Combine JSON objects	var objects = [\n{\n    "id" : 1,\n    "firstName" : "John"\n},\n{\n    "id" : 1,\n    "firstName" : "John",\n    "lastName" : "Dow",\n    "phone" : "555-555-5555"\n},\n{\n    "id" : 1,\n    "phone" : "(555) 555-555"\n},\n{\n    "id" : 1,\n    "position" : "Peon"\n}];\n\nvar merged = _.reduce(objects, function(sum, value){ return _.extend(sum, value); }, {});\n\ngives\n\n{\n "id":1,\n "firstName":"John",\n "lastName":"Dow",\n "phone":"(555) 555-555",\n "position":"Peon"\n}	0
21600901	21553219	DevExpress XtraReports absolute value	private void xrLabel1_SummaryCalculated(object sender, TextFormatEventArgs e) {\n  xrLabel1.Text = Math.Abs(Convert.ToInt32(e.Value)).ToString();\n}	0
31427693	31426088	How can i access any key inside of json string via C#?	string json = @"...";\n\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nvar o = serializer.Deserialize<dynamic>(json);\nvar body = o["soap:Envelope"]["soap:Body"];	0
30648544	30627748	Is there any particular structure needed to run nunit-console with a list of tests in a textfile?	FULLNAMEA\nFULLNAMEB\nFULLNAMEC\n...	0
4982837	4982807	C# - Insert a variable number of spaces into a string? (Formatting an output file)	myString.PadRight(totalLength, charToInsert)	0
869924	869903	How to make this extension method compile?	public static void AsyncInvoke<T>(this Action<T> action, T param)\n{\n    action.BeginInvoke(param, asyncResult => \n    {\n        Action<T> a = (Action<T>)asyncResult.AsyncState;\n        a.EndInvoke(asyncResult);\n    }, action);\n}	0
34273064	34273020	GetOrDefault<T> without relying on InvalidCastException	where T : class	0
1432259	1432213	Copy file on a network shared drive	AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n\n// http://pinvoke.net/default.aspx/advapi32/LogonUser.html    \nIntPtr token;\nLogonUser("username", "domain", "password", LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT);\n\nWindowsIdentity identity = new WindowsIdentity(token);\n\nWindowsImpersonationContext context = identity.Impersonate();\n\ntry\n{\n    File.Copy(@"c:\temp\MyFile.txt", @"\\server\folder\Myfile.txt", true);\n}\nfinally\n{\n    context.Undo();\n}	0
19164887	19164780	make a written line editable by the user	Console.Write("Edit: _____");\nConsole.SetCursorPosition(6, Console.CursorTop);\nstring text = Console.ReadLine();	0
2657614	2657575	how to read the txt file from the database(line by line)	using (MemoryStream m = new MemoryStream(buffer))\nusing (StreamReader sr = new StreamReader(m))\n{\n    while (!sr.EndOfStream)\n    {\n        string s = sr.ReadLine();\n    }    \n}	0
32354563	32318320	Getting path of right click in unity 3D editor	AssetDatabase.GetAssetPath (Selection.activeObject)	0
33112836	33112507	IGrouping<int, Keypair> to Dictionary	Dictionary<String, int> workLoad = something.ToDictionary(x => x.Key, x => x.Value);	0
2266997	2266583	Differentiating between a Compose Inspector and a Read Inspector	Outlook.MailItem currentMail = Inspector.CurrentItem as Outlook.MailItem;\n\n        if (currentMail != null)\n        {\n            if (currentMail.Sent)\n            {\n                //Read Mode\n\n            }\n            else\n            { \n                // Compose\n            }\n\n        }	0
4818399	4818088	C#: How to add a full ContextMenu to MenuItem as a submenu	private void AddSubMenu(MenuItem item, ContextMenu contextMenu)\n{\n    item.MergeMenu(contextMenu);\n}	0
14476218	14476162	How to find the indices of items fulfilling some condition in List of int?	var indexes = mylist.Select((v, i) => new { v, i })\n                    .Where(x => x.v > 23)\n                    .Select(x => x.i);	0
11807010	11798721	RavenDB Trigger for updated index	store.Changes().ForIndex("YourIndex").Subscribe(DoSomething);	0
24741469	24726908	how to delete library file permanently on Windows Phone 8?	var listBefore = (await KnownFolders.MusicLibrary.GetFilesAsync()).ToList();\nawait listBefore.FirstOrDefault().DeleteAsync(StorageDeleteOption.PermanentDelete);\nvar listAfter = (await KnownFolders.MusicLibrary.GetFilesAsync()).ToList();	0
677589	677487	C# PInvoke Delphi dll that returns a string fails in IIS only	function StringTest(const StringOut : pchar; MaxLen: Integer) : Boolean; stdcall;\nbegin\n    StrPLCopy(StringOut, 'Test output string.', MaxLen);\n    result := true;\nend;\n\n[DllImport(@"C:\\Test\\DelphiTest.dll", CharSet = CharSet.Ansi)]\npublic static extern bool StringTest(ref string stringOut, int maxLen);	0
7060580	7056888	Change some windows username programmatically (Rename windows user)	#include <Windows.h>\n#include <LM.h>\n\n#include <stdio.h>\n\n#pragma comment(lib, "netapi32.lib")\n\nint main(int argc, char ** argv)\n{\n    USER_INFO_0 ui0;\n    NET_API_STATUS result;\n    LPWSTR command = GetCommandLineW();\n    wchar_t newname[21];\n\n    while (*command != L'*') command++;\n\n    command++;\n\n    ui0.usri0_name = newname;\n    wcscpy_s(newname, _countof(newname), L"decommiss-");\n    wcscat_s(newname, _countof(newname), command);\n\n    result = NetUserSetInfo(NULL, command, 0, (LPBYTE)&ui0, NULL);\n\n    printf("%u\n", result);\n\n    return result;\n}	0
3685981	3685932	How to filter system files in C#	MyFolderWatcher.Changed += (s, e) => {\n    if ((File.GetAttributes(e.FullPath) & FileAttributes.System) != FileAttributes.System)\n        ; // Do something\n}	0
14530855	14530811	Press on arrow keys without focusing on any control	this.ActiveControl = null;	0
1296003	1289950	Recursive Security Settings	static void Main(string[] args)\n{\n    DirectoryInfo dInfo = new DirectoryInfo(@"C:\Test\Folder");\n    DirectorySecurity dSecurity = dInfo.GetAccessControl();\n    ReplaceAllDescendantPermissionsFromObject(dInfo, dSecurity);\n}\n\nstatic void ReplaceAllDescendantPermissionsFromObject(\n    DirectoryInfo dInfo, DirectorySecurity dSecurity)\n{\n    // Copy the DirectorySecurity to the current directory\n    dInfo.SetAccessControl(dSecurity);\n\n    foreach (FileInfo fi in dInfo.GetFiles())\n    {\n        // Get the file's FileSecurity\n        var ac = fi.GetAccessControl();\n\n        // inherit from the directory\n        ac.SetAccessRuleProtection(false, false);\n\n        // apply change\n        fi.SetAccessControl(ac);\n    }\n    // Recurse into Directories\n    dInfo.GetDirectories().ToList()\n        .ForEach(d => ReplaceAllDescendantPermissionsFromObject(d, dSecurity));\n}	0
913305	902891	How can I add a state to a control in Silverlight?	[TemplateVisualState(Name = "TextBlock", GroupName = "ControlType")]\n[TemplateVisualState(Name = "TextBox", GroupName = "ControlType")]\npublic class TextBox2 : TextBox\n{\npublic TextBox2()\n{\nDefaultStyleKey = typeof (TextBox2);\nLoaded += (s, e) => UpdateVisualState(false);\n}\n\n\nprivate bool isTextBlock;\npublic bool IsTextBlock\n{\nget { return isTextBlock; }\nset\n{\nisTextBlock = value;\nUpdateVisualState(true);\n}\n}\n\npublic override void OnApplyTemplate()\n{\nbase.OnApplyTemplate();\nUpdateVisualState(false);\n}\n\n\ninternal void UpdateVisualState(bool useTransitions)\n{\nif (IsTextBlock)\n{\nVisualStateManager.GoToState(this, "TextBlock" , useTransitions);\n}\nelse\n{\nVisualStateManager.GoToState(this, "TextBox" , useTransitions);\n}\n}\n}	0
5878056	5855737	combine two expressions	public Expression<Func<IEntityPriceDefinition, bool>> IsMatchExpression(\n        long? inviterId, long? routeId, long? luggageTypeId, long additionId)\n    {\n    return x =>\n        (inviterId.HasValue || routeId.HasValue || luggageTypeId.HasValue) &&\n        (x.PriceDefinition.AdditionsPrices.Any(a => a.AdditionId == additionId)) &&\n        !(\n            (x.PriceDefinition.InviterId.HasValue && inviterId.HasValue &&\n                PriceDefinition.InviterId.Value != inviterId.Value) ||\n\n            (PriceDefinition.LuggageTypeId.HasValue && luggageTypeId.HasValue &&\n                PriceDefinition.LuggageTypeId.Value != luggageTypeId.Value) ||\n\n            (PriceDefinition.InviterId.HasValue && inviterId.HasValue &&\n                PriceDefinition.InviterId.Value != inviterId.Value)\n        );\n}	0
28348331	28340114	LibGit2Sharp get all commits since {Hash}	using (var repo = new Repository(repositoryDirectory))\n{\n    var c = repo.Lookup<Commit>(shaHashOfCommit);\n\n    // Let's only consider the refs that lead to this commit...\n    var refs = repo.Refs.ReachableFrom(new []{c});\n\n   //...and create a filter that will retrieve all the commits...\n    var cf = new CommitFilter\n    {\n        Since = refs,       // ...reachable from all those refs...\n        Until = c           // ...until this commit is met\n    };\n\n    var cs = repo.Commits.QueryBy(cf);\n\n    foreach (var co in cs)\n    {\n        Console.WriteLine("{0}: {1}", co.Id.ToString(7), co.MessageShort);\n    }       \n}	0
19616607	19608491	how to remove the Plus Sign(+) Displayed on GMap Centre Location	MainGMap.ShowCenter = false;	0
27489036	27434696	Format SSN as user types	partial void SSN_Validate(EntityValidationResultsBuilder results)\n    {\n        if (this.SSN != null)\n        {\n            if (this.SSN.Length == 9 && !this.SSN.Contains("-"))\n            {\n                this.SSN = this.SSN.Substring(0, 3) + "-" + this.SSN.Substring(3, 2) + "-" + this.SSN.Substring(5);\n            }\n\n            if(!Regex.IsMatch(this.SSN, @"^\d{3}-\d{2}-\d{4}$"))\n            {\n                results.AddPropertyError("Please enter a valid SSN (i.e. 123-45-6789).");\n            }\n        }            \n    }	0
16301342	16301090	reusing validation code for two text boxes	protected void validatePart_ServerValidate(object source, ServerValidateEventArgs args)\n{\n    args.IsValid = Part.Exists(args.Value);\n}	0
23412888	23412636	Convert string to double from combobox	DataRow selectedDataRow = ((DataRowView)cboBeverage.SelectedItem).Row;\ndouble tempPrice = Convert.ToDouble(selectedDataRow["PriceBeverage"]);\nCalculations(tempPrice);	0
9162698	9162251	How to get absolute xpath by passing the xElement name in XmlDocument or XDocument?	public static string GetPath(XElement element)\n{\n    return string.Join("/", element.AncestorsAndSelf().Reverse()\n        .Select(e =>\n            {\n                var index = GetIndex(e);\n\n                if (index == 1)\n                {\n                    return e.Name.LocalName;\n                }\n\n                return string.Format("{0}[{1}]", e.Name.LocalName, GetIndex(e));\n            }));\n\n}\n\nprivate static int GetIndex(XElement element)\n{\n    var i = 1;\n\n    if (element.Parent == null)\n    {\n        return 1;\n    }\n\n    foreach (var e in element.Parent.Elements(element.Name.LocalName))\n    {\n        if (e == element)\n        {\n            break;\n        }\n\n        i++;\n    }\n\n    return i;\n}	0
21993953	21993885	How can I make a delay inside my ?for loop??	Thread.Sleep(1)	0
31194112	31193959	How Query for contain any list	filterGroup = allGroup\n         .Where(a => subGroup.manyID.Intersect(a.manyID).Any())\n         .ToList();	0
16967286	16965915	Convert a "big" Hex number (string format) to a decimal number (string format) without BigInteger Class	static string HexToDecimal(string hex)\n{\n    List<int> dec = new List<int> { 0 };   // decimal result\n\n    foreach (char c in hex)\n    {\n        int carry = Convert.ToInt32(c.ToString(), 16);   \n            // initially holds decimal value of current hex digit;\n            // subsequently holds carry-over for multiplication\n\n        for (int i = 0; i < dec.Count; ++i)\n        {\n            int val = dec[i] * 16 + carry;\n            dec[i] = val % 10;\n            carry = val / 10;\n        }\n\n        while (carry > 0)\n        {\n            dec.Add(carry % 10);\n            carry /= 10;\n        }\n    }\n\n    var chars = dec.Select(d => (char)('0' + d));\n    var cArr = chars.Reverse().ToArray();\n    return new string(cArr);\n}	0
2671349	2554609	C# : changing listbox row color?	private void listView1_Refresh()\n{\n    for (int i = 0; i < listView1.Items.Count; i++)\n    {\n        listView1.Items[i].BackColor = Color.Red;\n        for (int j = 0; j < existingStudents.Count; j++)\n        {\n            if (listView1.Items[i].ToString().Contains(existingStudents[j]))\n            {\n                listView1.Items[i].BackColor = Color.Green;\n            }\n        }\n    }\n}	0
18387834	17883247	Magick.NET takes a long time loading PDF	using (MagickImageCollection collection = new MagickImageCollection())\n{\n  MagickReadSettings settings = new MagickReadSettings();\n  settings.FrameIndex = 0; // First page\n  settings.FrameCount = 1; // Number of pages\n\n  collection.Read("Snakeware.pdf", settings);\n}	0
19782760	19782670	Unicode characters in string	char ch1 = '\u2085';  \nchar ch2 = '\u8328';\nchar ch3 = '\u8327';\nchar ch4 = '\u8326';\nchar ch5 = '\u8325';\nConsole.WriteLine("" + ch1 + ch2 + ch3 + ch4 + ch5);	0
5419325	5419265	How do I add a WPF User Control Library using C# to a WPF window	using TechLog;\n\n ...\n\nUserControl ctrl = new UserControl();\nthis.TabItem1.Content = UserControl;	0
533888	533872	How do I get all the bottom types in an assembly?	var allTypes = assembly.GetTypes();\nvar baseTypes = allTypes.Select(type => type.BaseType);\nvar bottomTypes = allTypes.Except(baseTypes);	0
2844656	2844611	How to get all links avaliable from server on some port?	class Program\n{\n    static void Main()\n    {\n        var document = new HtmlDocument();\n        using (var client = new WebClient())\n        using (var reader = new StringReader(client.DownloadString("http://www.google.com")))\n        {\n            document.Load(reader);\n        }\n\n        var anchors = document.DocumentNode.SelectNodes("//a");\n        foreach (var anchor in anchors)\n        {\n            Console.WriteLine(anchor.Attributes["href"].Value);\n        }\n    }\n}	0
33411411	33411209	Restrict opening of duplicate dialog	MyWindow uiObj=new MyWindow();\nuiObj.Closing+={windowsOpened = false;}\nuiObj.Shown+={windowsOpened = true;}\npublic void ShowWindow(Object Obj, Object ObjThis)\n{ \nif(windowsOpened)return;\n...	0
31047472	31047182	How can i improve the performance of this LINQ?	max(id)	0
1858104	1858055	Issue with fetching value from registry	class FooBar\n{\n\n    //other code goes here\n\n    public FooBar()\n    {\n        m_wrmversion = (string)regkey.GetValue(SpoRegistry.regValue_CurrentVersion);\n    }\n}	0
8833007	8831496	How to Update/Edit Database Field with Using Entity Framework and Mapper	//this assumes that the AddressId in address is exists in the database: just attach it to the addresses set\nmobileServiceContext.Addresses.Attach(address);\n//this tells ef that the object is in a modified state\nmobileServiceContext.ObjectStateManager.ChangeObjectState(address, entityState.Modified);\n//savechanges will now update the database\nmobileServiceContext.SaveChanges();	0
1867658	1867592	C# Converting ListBox to String then Aggregate	string[] items = listBox1.Items\n            .OfType<object>()\n            .Select(item => item.ToString())\n            .ToArray();\n        string result = string.Join(",", items);	0
10162246	10162239	how can I check if a string is a positive integer?	int x;\nif (int.TryParse(str, out x) && x > 0)	0
8401660	8399759	Change all Administrators wallpaper	string adminKey = Registry.Users.GetSubKeyNames()\n                    .FirstOrDefault(key => key.StartsWith(sid.AccountDomainSid.Value) && char.IsDigit(key[key.Length - 1]));\n\nif (adminKey != null) // ...	0
2902597	2902563	Format string as date	DateTime.ParseExact("20100524", "yyyyMMdd", Thread.CurrentThread.CurrentCulture);	0
22291612	22291518	Remove the space between single characters only	res = Regex.Replace(s, @"(?<=\b\w)\s(?=\w\b)", "");	0
6321820	6321760	Add a new Trusted Location for word 2010 using VB.Net	[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Word\Security\Trusted Locations\Location0]\nAllowSubFolders (REG_DWORD) = 1\nPath (REG_SZ) "**The Path for Your Folder**"	0
32538333	32513909	Fluent Nhibernate : Map one class to two identical tables but with different table names	public class A \n{\n  public virtual Guid id;\n  public virtual string name;\n}\n\npublic class B : A { }\n\n\npublic class AMap : ClassMap<A>\n{\n  public AMap()\n  {\n    Table("Atable");\n    Id(x => x.id);\n    Map(x => x.name);\n  }\n}\n\npublic class BMap : SubclassMap<B>\n{\n  public BMap()\n  {\n    Table("Btable");\n  }\n}	0
1138180	1138166	C#.Net Getting Last day of the Previous Month from current date	DateTime now = DateTime.Now;\n\nDateTime lastDayLastMonth = new DateTime(now.Year, now.Month, 1);\nlastDayLastMonth = lastDayLastMonth.AddDays(-1);	0
30207327	29960168	Elastic Search-Search string having spaces and special characters in it using C#	IIndicesOperationResponse result = null;\n                    if (!objElasticClient.IndexExists(elastic_indexname).Exists)\n                    {\n                        result = objElasticClient.CreateIndex(elastic_indexname, c => c.AddMapping<dynamic>(m => m.Type("_default_").DynamicTemplates(t => t\n                                                    .Add(f => f.Name("string_fields").Match("*").MatchMappingType("string").Mapping(ma => ma\n                                                        .String(s => s.Index(FieldIndexOption.NotAnalyzed)))))));\n                }	0
24408120	24408077	How do I limit the number of cores used for a process?	using System;\nusing System.Diagnostics;\n\nnamespace ProcessThreadIdealProcessor\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // Make sure there is an instance of notepad running.\n            Process[] notepads = Process.GetProcessesByName("notepad");\n            if (notepads.Length == 0)\n                Process.Start("notepad");\n            ProcessThreadCollection threads;\n            //Process[] notepads; \n            // Retrieve the Notepad processes.\n            notepads = Process.GetProcessesByName("Notepad");\n            // Get the ProcessThread collection for the first instance\n            threads = notepads[0].Threads;\n            // Set the properties on the first ProcessThread in the collection\n            threads[0].IdealProcessor = 0;\n            threads[0].ProcessorAffinity = (IntPtr)1;\n        }\n    }\n}	0
30533524	30533489	c# error: is a 'field' but is used as a 'type' when trying to use while loop	private void Test()\n{\n    List<int> fib = new List<int>();\n    bool notAtLimit = true;\n\n    while (notAtLimit)\n    {\n        //code to populate list of fibonacci series\n    }\n}	0
26176255	26176213	TextBox enable to add only numbers - C#	if (e.KeyChar < '0' || e.KeyChar > '9')\n{\n     e.Handled = true;\n}	0
29326684	29322545	Application settings Windows phone 8	var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;\n\n// Create a simple setting\n\nlocalSettings.Values["exampleSetting"] = "Hello Windows";\n\n// Read data from a simple setting\n\nObject value = localSettings.Values["exampleSetting"];\n\nif (value == null)\n{\n    // No data\n}\nelse\n{\n   // Access data in value\n}\n\n   // Delete a simple setting\n\nlocalSettings.Values.Remove("exampleSetting");	0
30720271	30720194	How to link a button to outlook application and send mail c#	Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body=" + body);	0
298329	296834	Fluent NHibernate - how to map a subclass one-to-one?	// Domain classes\npublic class Animal\n{\n    public virtual int Id { get; set; }\n    public virtual string Name { get; set; }\n}\n\npublic class Cat : Animal\n{\n    public virtual int WhiskerLength { get; set; }\n    public virtual int ClawCount { get; set; }\n}\n\npublic class Dog : Animal\n{\n    public virtual int TailWagRate { get; set; }\n}\n\n\n\n// Mapping file\npublic class AnimalMap : ClassMap<Animal>\n{\n    public AnimalMap()\n    {\n        Id(x => x.Id)\n            .WithUnsavedValue(0)\n            .GeneratedBy.Native();\n\n        Map(x => x.Name);\n\n        var catMap = JoinedSubClass<Cat>("CatId", sm => sm.Map(x => x.Id));\n\n        catMap.Map(x => x.WhiskerLength)\n            .CanNotBeNull();\n        catMap.Map(x => x.ClawCount)\n            .CanNotBeNull();\n\n        JoinedSubClass<Dog>("DogId", sm => sm.Map(x => x.Id))\n            .Map(x => x.TailWagRate)\n                .CanNotBeNull();\n    }\n}	0
7071369	7071324	How to convert recursive procedure with side effects on ref param to recursive function returning a list?	public static List<XDocument> GetResources(string startURL)\n{\n    var result = new List<XDocument>();\n    var doc = XDocument.Parse(GetXml(startURL));\n    var xs = new XmlSerializer(typeof(resourceList));\n    var rdr = doc.CreateReader();\n    if (xs.CanDeserialize(rdr))\n    {\n        var rl = (resourceList)xs.Deserialize(doc.CreateReader());\n\n        foreach (var item in rl.resourceURL)\n        {\n            result.AddRange(GetResources(startURL + item.location));\n        }\n    }\n    else\n    {\n        result.Add(doc);\n    }\n    return result;\n}	0
10915306	10915220	C# saving file cuts away part of my text	using (StreamWriter wText = new StreamWriter(myStream))\n{\n  wText.Write(result.ToString());\n  //wText.Flush(); //this should not be needed because close will flush\n}	0
17155164	17154878	Windows service performs differently after reboot	Logger.Instance.Error()	0
25143717	25107904	Allow button click even if validation on another control fails	button.MouseUp += (sender, e) =>\n{\n    if (button.Parent.ContainsFocus || e.Button != MouseButtons.Left\n        || !button.ClientRectangle.Contains(e.Location))\n    {\n        return;\n    }\n    textBox.UseSystemPasswordChar = !textBox.UseSystemPasswordChar;\n};\n\nbutton.Click += delegate\n{\n    if (!button.Parent.ContainsFocus) {\n        return;\n    }\n    textBox.UseSystemPasswordChar = !textBox.UseSystemPasswordChar;\n};	0
959815	959752	Where IN clause in LINQ	dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))	0
10966611	10966599	inserting multiple values from C# into one row in a SQL table	using (SqlCommand cmd = new SqlCommand("INSERT INTO [user] (solution) VALUES (@text)", cn))\n            {\n                cmd.Parameters.AddWithValue("@text", textBox1.Text + " " + textBox2.Text + " " + textBox3.Text);\n\n                cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery() \n                MessageBox.Show("Success!");\n\n            }	0
1276792	1276763	How to get the list of key in dictionary	List<string> keyList = new List<string>(this.yourDictionary.Keys);	0
10419011	10418670	Very poor performance with a simple query in Entity Framework	List<Order> orders = myContext.Orders\n    .Include( "OrderRows.RowExtras" )\n    .Where( ... select all the orders you want, not just one at a time ... )\n    .ToList();\n\nforeach ( Order order in orders )\n{\n    ... execute your logic on the in-memory model\n}\n\nmyContext.SaveChanges();	0
15041142	15040967	The number of lambda outer subquery iteration variable evaluations	string[] colors = { "green", "brown", "blue", "red" };\n\nint count = 0;\n\nvar query =\n    from c in colors\n    where c.Length == colors.Max (c2 => \n        {\n            count.Dump();\n            count++;\n            return c2.Length;\n        }\n    )\n    select c;\n\nquery.Dump();	0
10191227	10190971	ashx handler called only once from ascx page	this.imgPhotos.ImageUrl = "~/lib/services/GetSpaceImage.ashx?param=" + DateTime.Now.Ticks.ToString();	0
27702611	27702487	Identifying if a window instance is already opened	var window = Application.Current.Windows.OfType<UserPersonalChatWindow>()\n.FirstOrDefault(x => x.StaffUserId.Content == id);	0
2385393	2385368	Filter a list of objects using LINQ	var newList = objList.Select(x => x.date1.Date)\n                     .Concat(objList.Select(x => x.date2.Date))\n                     .Distinct()\n                     .ToList();	0
5911559	5909541	How to use SqlBulkCopy with SMO and transactions	try/catch	0
5963497	5963317	Convert string to decimal with format	public decimal? CustomParse(string incomingValue)\n{\n    decimal val;\n    if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))\n        return null;\n    return val / 100;\n}	0
27814682	27771322	Local network multiplayer game with unity	void Start () {\n\n        Connect ();\n        PhotonNetwork.JoinRoom("room1");\n        //Create your player\n    }\n\nvoid Connect(){\n        PhotonNetwork.ConnectUsingSettings ("your settings");\n    }	0
2429752	2429713	Reading from excel using oledbcommand	OleDbConnection dbConnection = new OleDbConnection (@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\BAR.XLS;Extended Properties=""Excel 8.0;HDR=Yes;""");\ndbConnection.Open ();\ntry\n{\n    // Get the name of the first worksheet:\n    DataTable dbSchema = dbConnection.GetOleDbSchemaTable (OleDbSchemaGuid.Tables, null);\n    if (dbSchema == null || dbSchema.Rows.Count < 1)\n    {\n        throw new Exception ("Error: Could not determine the name of the first worksheet.");\n    }\n    string firstSheetName = dbSchema.Rows [0] ["TABLE_NAME"].ToString ();\n\n    // Now we have the table name; proceed as before:\n    OleDbCommand dbCommand = new OleDbCommand ("SELECT * FROM [" + firstSheetName + "]", dbConnection);\n    OleDbDataReader dbReader = dbCommand.ExecuteReader ();\n\n    // And so on...\n}\nfinally\n{\n    dbConnection.Close ();\n}	0
12530516	12530277	convert ienumerable<string> to xpathnodeiterator	public static XPathNodeIterator GetWordsAsXml(List<string> words)\n{\n    return umbraco.library.Split(string.Join(",", words), ",");\n}	0
865801	865774	C#: Getting the correct keys pressed from KeyEventArgs' KeyData	//asumming e is of type KeyEventArgs (such as it is \n// on a KeyDown event handler\n// ..\nbool ctrlShiftM; //will be true if Ctrl + Shit + M is pressed, false otherwise\n\nctrlShiftM = ((e.KeyCode == Keys.M) &&               // test for M pressed\n              ((e.Modifiers & Keys.Shift) != 0) &&   // test for Shift modifier\n              ((e.Modifiers & Keys.Control) != 0));  // test for Ctrl modifier\nif (ctrlShiftM == true)\n{\n    Console.WriteLine("[Ctrl] + [Shift] + M was pressed");\n}	0
9825431	9823240	How to retrieve digital signature information (name, date, ...) with ItextSharp	StringBuilder sb = new StringBuilder();\nPdfReader reader = new PdfReader(pdf);\nAcroFields af = reader.AcroFields;\nArrayList  names = af.GetSignatureNames();\nfor (int i = 0; i < names.Count; ++i) {\n  String name = (string)names[i];\n  PdfPKCS7 pk = af.VerifySignature(name);\n  sb.AppendFormat("Signature field name: {0}\n", name);\n  sb.AppendFormat("Signature signer name: {0}\n", pk.SignName);\n  sb.AppendFormat("Signature date: {0}\n", pk.SignDate);\n  sb.AppendFormat("Signature country: {0}\n",  \n    PdfPKCS7.GetSubjectFields(pk.SigningCertificate).GetField("C")\n  );\n  sb.AppendFormat("Signature organization: {0}\n",  \n    PdfPKCS7.GetSubjectFields(pk.SigningCertificate).GetField("O")\n  );\n  sb.AppendFormat("Signature unit: {0}\n",  \n    PdfPKCS7.GetSubjectFields(pk.SigningCertificate).GetField("OU")\n  );\n}	0
1919109	1911770	.Net Refactoring application to use Dependency Injection	var builder = new ContainerBuilder();\n\n// Use the most resolvable constructor\nbuilder.Register<DataSourceLoaderPlugins>().As<IDataSourceLoaderPlugins>().SingletonScoped();\n\n// Use your own instance\nbuilder.Register(new DataSourcesService("some path")).As<IDataSourcesService>().SingletonScoped();\n\n// Reference another component\nbuilder.Register(c => new ChartPlugins(c.Resolve<IDataSourcesService>(), "another path")).As<IChartPlugins>().SingletonScoped();\n\n// ...other ~10 dependencies...\n\nbuilder.Register<DataService>().SingletonScoped();\n\n// How to resolve an instance\n\nvar container = builder.Build();\n\nDataService dataService = container.Resolve<DataService>();	0
13093300	13093273	How to use the same DB for authentication and data in MVC3?	aspnet_regsql.exe	0
11425988	11425905	How to add Comma for total in the gridview footer	protected void grdList_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.Footer)\n    {\n        Label lbl = (Label)(e.Row.FindControl("lblTotal"));\n        lbl.Text = String.Format("{0:n}", Total);\n    }\n}	0
194128	194127	C# how can you get output of an other batch file?	Process myProcess = new Process();\nProcessStartInfo myProcessStartInfo = new ProcessStartInfo("YOUPROGRAM_CONSOLE.exe" );\nmyProcessStartInfo.UseShellExecute = false;\nmyProcessStartInfo.RedirectStandardOutput = true;\nmyProcess.StartInfo = myProcessStartInfo;\nmyProcess.Start();\n\nStreamReader myStreamReader = myProcess.StandardOutput;\nstring myString = myStreamReader.ReadLine();\nConsole.WriteLine(myString);\nmyProcess.Close();	0
3101353	3100909	How to pass a delegate to create an expression tree that is a MethodCallExpression	private SomeViewModel CreateViewModel(SomeDto dto, Tier t, \n    Expression<Func<string, int, ActionResult>> actionToCall)\n{\n    var methodCallExpression = (MethodCallExpression)actionToCall.Body;\n    var param = Expression.Parameter(typeof(SomeController), null);\n    return new SomeViewModel()\n    {\n        Action =\n            Expression.Lambda<Action<SomeController>>(\n                Expression.Call(\n                    param,\n                    methodCallExpression.Method,\n                    Expression.Constant(dto.Qualification.Name),\n                    Expression.Constant(t.Id)),\n                param)\n    };\n}	0
27827357	27827332	Passing a List of Strings to a where clause in a LINQ Query	.Where(x => !listProducts.Contains(x.Product))	0
18643139	18624995	MS Chart zooming with multiple chart areas	Chart.ChartArea[i].AlignWithChartArea	0
7108987	7108971	Creating DateTime in C#	var today = DateTime.Today.AddHours(16);	0
5941797	5928575	change connection string in class application at runtime?	EntityConnectionStringBuilder conn = new EntityConnectionStringBuilder();\n        conn.Metadata = @"res://*/KzDm.csdl|res://*/KzDm.ssdl|res://*/KzDm.msl";\n        conn.Provider = "System.Data.SQLite";\n        conn.ProviderConnectionString = @"data source=F:\My Own programs\KrarZara2\KZ\KZ\KrarDS.krar;Version=3;";\n        EntityConnection entity = new EntityConnection(conn.ConnectionString);\n        using (DmEnt ent = new DmEnt(entity))\n        {\n            var parcel = ent.Parcels.SingleOrDefault(d => d.id == 1);\n            var pparcc = ent.Parcels.Select(d => d.id == 2);\n            Parcel r = new Parcel();\n            r.ParcelNumber = "11ju";\n            r.Area = 8787;\n\n            ent.AddToParcels(r);\n            ent.SaveChanges();\n        }	0
1775910	1775843	How to directly access the UI thread from the BackgroundWorker thread in WPF?	Dispatcher.Invoke(new Action(() => { Button_Start.Content = i.ToString(); }));	0
22864895	22864732	Trying to convert string into double C#?	var culture = CultureInfo.GetCultureInfo("FR-fr");       \nvar qty = Convert.ToDouble("39,618840", culture);	0
338308	338274	How to get the name of the class	public class BaseEntity {\n    public string MyName() {\n        return this.GetType().Name\n    }\n}	0
12240834	12240452	How to do an update with Linq, Lambda and EF	public static void UpdateUser(User user)\n{\n      Save<User>(u => { \n         u.Attach(user); \n         u.Context.ObjectStateManager\n              .ChangeObjectState(user, System.Data.EntityState.Modified);\n         });\n}	0
1911064	1905433	Centering an pdfimportedpage in iTextSharp	Float offset = 0;\nif(importedPage.width < iTextDocument.PageSize.Width) {\n   offset = (iTextDocument.PageSize.Width - importedPage.width)/2;\n}\npdfContentByte.AddTemplate(importedPage, offset, 0);	0
9411497	9411432	Connection string for C# winapp with a SQL Server database file	Server=.\SQLExpress;AttachDbFilename=c:\pathtodb\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;	0
11017150	11015473	implementation of #define and #ifdef in MonoTouch	public const int TARGET_OS_MAC = 1; \npublic const int TARGET_OS_WIN32 = 0; \npublic const int TARGET_OS_UNIX = 0; \npublic const int TARGET_OS_EMBEDDED = 0; \npublic const int TARGET_OS_IPHONE = 1;  \npublic const int TARGET_IPHONE_SIMULATOR = 1; \n\n#if __MACH__ \n    public const int TARGET_RT_MAC_MACHO = 1; \n    public const int TARGET_RT_MAC_CFM = 0; \n#else \n    public const int TARGET_RT_MAC_MACHO = 0; \n    public const int TARGET_RT_MAC_CFM = 1; \n#endif	0
34529692	34529540	Customize an item within the CSS for a specific view	.CampoRealyOnly input[type=text], .CampoRealyOnly textarea, .CampoRealyOnly select\n{\n    border: 1px solid #888888;\n    left: 298px;\n    position: relative;\n    top: -29px;\n}	0
15158727	15158707	List<Vector3>, how get an item from it?	var item = list[index];	0
15900232	15900110	Declarations of p/invoke for file io and pseudo terminal	[DllImport("libc.so.6")]	0
9411417	9099184	Changing the PivotCache connection of an Excel spreadsheet in C#	//update the connections\n        foreach (EXCEL.WorkbookConnection connection in workbook.Connections)\n        {\n            if (connection.Type.ToString() == "xlConnectionTypeODBC")\n            {\n                connection.ODBCConnection.BackgroundQuery = false;\n                connection.ODBCConnection.Connection = ConnectionString;\n            }\n            else\n            {\n                connection.OLEDBConnection.BackgroundQuery = false;\n                connection.OLEDBConnection.Connection = ConnectionString;\n            }\n        }\n\n        //Refresh all data\n        workbook.RefreshAll();	0
26605602	26605439	Eliminate empty string values in databound combobox C#	string sName = myreader666.GetString("50079");\nif(!String.IsNullOrEmpty(sName))\n{\n  50079combobox.Items.Add(sName);\n}	0
23368490	23365534	Kendo UI Grid not displaying data, only blank rows	[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult EditingPopup_Create([DataSourceRequest] DataSourceRequest request,     ExpenseReportModel expenseReportModel, int id)	0
7856078	7856060	LINQ Queries with dynamic Order By	IQueryable<Foo> query = ...;\n\nswitch (orderByParameter)\n{\n    case "price":\n        query = query.OrderBy(x => x.Price);\n        break;\n    case "rating":\n        query = query.OrderBy(x => x.Rating);\n        break;\n    // etc\n}	0
23895570	23888260	Getting metadata from an image c#	BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.Default);	0
29233272	29233133	How to copy values from a table to another table C# SQL	INSERT INTO StdAccounts (StudentID, StudentPassword)\n  select s.StudentID, @Password FROM Students s\n  WHERE NOT EXISTS (SELECT StudentID FROM StdAccounts std\n                    WHERE s.StudentID = std.StudentID)	0
15475274	15473109	Set windows service account in config	Assembly service = Assembly.GetAssembly(typeof(ProjectInstaller));\nstring assemblyPath = service.Location;\nConfiguration config = ConfigurationManager.OpenExeConfiguration(assemblyPath);\nKeyValueConfigurationCollection mySettings = config.AppSettings.Settings;\nprocessInstaller.Account = (ServiceAccount)Enum.Parse(typeof(ServiceAccount), mySettings["Account"].Value);	0
20150960	19481291	How to enable a button only if a row is selected in DataGrid?	public event EventHandler CanExecuteChanged\n{\n    add { CommandManager.RequerySuggested += value; }\n    remove { CommandManager.RequerySuggested -= value; }\n}	0
25099696	25099690	How to declare multiple list <t> variables in one statement in c#	List<Plane> availableAircrafts = new List<Plane>(), selectedAircrafts = new List<Plane>();	0
5848621	5848520	Find two numbers which are divisible without remainder	1. Let A is greater and B is smaller\n2. Set M = (A % B)\n3. If M == 0, You're done..\n4. Else Adjust A  either by adding, A = A + B - M\n5.               or by subtracting, A = A - M	0
16426893	16422270	Lucene.net search by numeric value(as string)	RAMDirectory dir = new RAMDirectory();\nIndexWriter iw = new IndexWriter(dir, new SnowballAnalyzer(Lucene.Net.Util.Version.LUCENE_30,"English"), IndexWriter.MaxFieldLength.UNLIMITED);\n\nDocument d = new Document();\nField f = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED);\nd.Add(f);\n\nf.SetValue("He was born 1990 years");\niw.AddDocument(d);\n\niw.Commit();\nIndexReader reader = iw.GetReader();\n\nIndexSearcher searcher = new IndexSearcher(reader);\n\nQueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "text", new SnowballAnalyzer(Lucene.Net.Util.Version.LUCENE_30, "English"));\nQuery q = qp.Parse("+born +1990");\n\nTopDocs td = searcher.Search(q, null, 25);\nforeach (var sd in td.ScoreDocs)\n{\n    Console.WriteLine(searcher.Doc(sd.Doc).GetField("text").StringValue);\n}\n\nsearcher.Dispose();\nreader.Dispose();\niw.Dispose();	0
4547717	4547591	WPF Binding to variable / DependencyProperty	public string Test\n{\n    get { return (string)this.GetValue(TestProperty); }\n    set { this.SetValue(TestProperty, value); }\n}\n\npublic static readonly DependencyProperty TestProperty =\n    DependencyProperty.Register("Test",\n    typeof(string),\n    typeof(MainWindow),\n    new PropertyMetadata("CCC", TestPropertyChanged));\n\nprivate static void TestPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)\n{\n    MainWindow mainWindow = source as MainWindow;\n    string newValue = e.NewValue as string;\n    // Do additional logic\n}	0
21146665	21146594	Should I throw a KeyNotFoundException for a database lookup?	System.Data	0
13183392	13182950	DataGrid Set ReadOnly and allow scrolling?	dataGridView1.ReadOnly = true;\nvoid dataGridView1_DoubleClick(object sender, EventArgs e)\n{\n     if (dataGridView1.ReadOnly == true)\n          return;\n\n     // .. whatever code you have in your handler...\n}	0
6827674	6827594	How can I parse REST service response?	PublisherInfo pi = myServiceClient.GetPublisherInfo();	0
2326447	2326354	Need to get empty datatable in .net with database table schema	SET FMTONLY ON;\nSELECT * FROM SomeTable\nSET FMTONLY OFF;	0
8883018	8882968	How to set file type association in C#	HKCR\txtfile\shell\open\command	0
3807068	3807041	Checking status of parallel foreach loop	Interlocked.Increment()	0
6694017	6693854	One or zero to many with code first	class Person {\n  public int Id {get;set;}\n  public string Name {get;set;}\n  public Person Manager {get;set;}\n  public int? ManagerId {get;set;}\n}	0
1903724	1903173	Problem assigninging values to a struct in C++ to a structure passed from C#	private static extern int PassSomeStructs(int count, [In, Out] Box[] boxes, [In, Out] Spot[] points);	0
21885970	21882797	TFS working with IBuildController in C#	buildServer = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));\nIBuildController[] buildserverlist = buildServer.QueryBuildControllers();	0
1378800	1378550	Pattern for closing the state of a ServiceClient	try\n{\n   var host = ServiceClientFactory.CreateInstance<MySericeClient>();\n\n   ...... (use it).......\n\n   host.Close();\n}\ncatch(FaultException)\n{   \n   host.Abort();\n}\ncatch(CommunicationException)\n{\n   host.Abort();\n}	0
20182269	20179120	How to copy segment from the image?	Mat image = imread("image.jpg",CV_LOAD_IMAGE_COLOR);\nvector<Point> triangleRoi;\nMat mask;\n\n//draw your trianlge on the mask\ncv::fillConvexPoly(mask, triangleRoi, 255);\n\nMat copiedSegment;\nimage.copyTo(copiedSegment,mask);	0
1919393	1919261	Performance of Image Proxy	// GetCacheFileName -> Returns the full path of the "cached" image\n    // CreateImage -> Used to create a new image if necessary\n    string cacheFile = GetCacheFileName(param1, param2, param3, param4);\n    if (!File.Exists(cacheFile))\n    {\n        Image cacheImage = CreateImage(param1, param2, param3, param4);\n        cacheImage.Save(cacheFile, ImageFormat.Jpeg);\n    }\n\n    Response.ContentType = "image/jpeg";\n    Response.TransmitFile(cacheFile);	0
13131748	12983301	How to WebView.postUrl() in WebBrowser	HtmlElement form = webBrowser1.Document.GetElementById("FormID");\nif (form != null)\n    form.InvokeMember("submit");	0
7908692	7908650	How to get average occurrences of string in list	string most = lMyList.GroupBy(x => x)\n        .Select(g => new {Value = g.Key, Count = g.Count()})\n        .OrderByDescending(x=>x.Count).First();	0
9162037	9161696	Regex required for renaming file in C#	var fileNames = new [] {\n    "22px-Flag_Of_Sweden.svg.png"\n    ,"13px-Flag_Of_UnitedStates.svg.png"\n    ,"17px-Flag_Of_India.svg.png"\n    ,"22px-Flag_Of_Ghana.svg.png"\n    ,"asd.png"\n};\n\nvar regEx = new Regex(@"^.+Flag_Of_(?<country>.+)\.svg\.png$");\n\n\n\nforeach ( var fileName in fileNames )\n{\n    if ( regEx.IsMatch(fileName))           \n    {\n        var newFileName = regEx.Replace(fileName,"${country}.png").ToLower();\n        //File.Save(Path.Combine(root, newFileName));\n\n    }\n}	0
14343892	14267425	Extracting RGB from a pixel without color object in C#	Bitmap source = new Bitmap(image);\n\n            Rectangle rect = new Rectangle(0, 0, source.Width, source.Height);\n\n            BitmapData bmd = source.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);\n\n            int totalPixels = rect.Height * rect.Width;\n            int[] pixelData = new int[totalPixels];\n            for (int i = 0; i < totalPixels; i++)\n            {\n                byte* pixel = (byte*)bmd.Scan0;\n                pixel = pixel + (i * 4);\n\n                byte b = pixel[0];\n                byte g = pixel[1];\n                byte r = pixel[2];\n\n                int luma = (int)(r * 0.3 + g * 0.59 + b * 0.11);\n                pixelData[i] = luma;\n            }	0
15473164	15430458	Automatic page numbering	doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;\n                Object oMissing = System.Reflection.Missing.Value;\n                doc.ActiveWindow.Selection.TypeText("some text \t Page ");\n                Object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;\n                Object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;\n                doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref CurrentPage, ref oMissing, ref oMissing);\n                doc.ActiveWindow.Selection.TypeText(" of ");\n                doc.ActiveWindow.Selection.Fields.Add(doc.ActiveWindow.Selection.Range, ref TotalPages, ref oMissing, ref oMissing);	0
8946632	8942949	Ninject: How to bind interface depending on target assembly	Bind<IFoo>.To<Foo>.When(request =>\n    request.Target.Type.Assembly.FullName == "someAssembly");\nBind<IFoo>.To<Bar>.When(request =>\n    request.Target.Type.Assembly.FullName == "someOtherAssembly");	0
10189507	10189437	Match but don't include in result using regex	(?:(?:kl(?:\.)?|at)?([0-1][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?)	0
30616722	30616670	Convert a String to binary sequence in C# with zero padding when not 8 bits of char	public string GetBits(string input)\n{\n    return string.Concat(input.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));\n}	0
8063712	8063664	how to get the full querystring, or other options?	string str = Request.QueryString.ToString();	0
17945166	8723513	Custom control and required field validator	[ValidationProperty("Text")]\n   public class cusTextBox:TextBox	0
25718899	25718488	Get the values of Standard Drop Down list in controller	public ActionResult Create(FormCollection formCollection)\n{\n   foreach (var key in formCollection.Keys)\n   {\n       var value = formCollection[key.ToString()];\n       // save value\n   }\n   return RedirectToAction("Create", "Score");\n}	0
11755057	11754391	how to clear generated columns without clearing ItemTemplate fields	YourGridView.Columns[0].Visible = false;	0
22608360	22608253	Deserialization NOT from a file	using(var reader = new StringReader(dataSet.GetXml()))\n{\n   .....\n}	0
2894301	2893358	How can I improve the recursion capabilities of my ECMAScript implementation?	public object Call(object thisObject, object[] arguments)\n{\n    var lexicalEnviroment = Scope.NewDeclarativeEnviroment();\n    var variableEnviroment = Scope.NewDeclarativeEnviroment();\n    var thisBinding = thisObject ?? Engine.GlobalEnviroment.GlobalObject;\n    var newContext = new ExecutionContext(Engine, lexicalEnviroment, variableEnviroment, thisBinding);\n    var result = default(object);\n    var callArgs = default(object[]);\n\n    Engine.EnterContext(newContext);\n    while (true)\n    {\n        result = Function.Value(newContext, arguments);\n        callArgs = result as object[];\n        if (callArgs == null)\n        {\n            break;\n        }\n        for (int i = 0; i < callArgs.Length; i++)\n        {\n            callArgs[i] = Reference.GetValue(callArgs[i]);\n        }\n        arguments = callArgs;\n    }\n    Engine.LeaveContext();\n\n    return result;\n}	0
30392026	30378811	Filtering DataTable that contains objects	EnumerableRowCollection erc = dataTable.AsEnumerable().Where(dr => ((Cell)dr[columnIndex]).Value.ToString().ToLower().Contains(filter.ToLower()));	0
14901898	14899537	Round doubles operations	public static double operator *(double d1, double d2)\n{\n    double result;\n    result = Math.Round(d1 * d2, 5);\n\n    return result;\n}	0
8447515	8413327	Change nodes of treeview	int indCurr = treeView.SelectedNode.Index;\nint levelCurr = treeView.SelectedNode.Level;\nif (indCurr == 0) return;\n\nif (levelCurr == 0)\n{\n  TreeNode prevNode = treeView.Nodes[indCurr - 1];\n  prevNode.Remove();\n  treeView.Nodes.Insert(indCurr, prevNode);\n}\nelse\n{\n  TreeNode prevNode = treeView.SelectedNode.Parent.Nodes[indCurr - 1];\n  prevNode.Remove();\n  treeView.SelectedNode.Parent.Nodes.Insert(indCurr, prevNode);\n}	0
5875180	5875105	Need help figuring out NullReferenceException	link.Text = s != null ? s.app.Name : (((r.RequesteeID == myUserID) ? r.RequesterName : r.RequestedName));	0
12081882	12075686	MongoDB C# Driver - How to InsertBatch using a List of Dictionary<string, string>	collection.InsertBatch(documents.Select(d => new BsonDocument(d)));	0
33395780	33395687	Entity Framework Update without reading	context.Tasks\n    .Where(t => t.StatusId == 1)\n    .Update(t => new Task { StatusId = 2 });	0
32700682	32700186	LINQ filter nullable datetime with matching params?	int? month = 2;\nint? day = 25;\nint? century = 19; // actual century minus one\n\n// other LINQ here\n.Where(x => x.DOB == null \n    || ((month == null || x.DOB.Month = month)\n     && (day == null || x.DOB.Day = day)\n     && (century == null || x.DOB.Year / 100 == century)));	0
8236760	8236547	How to delay Silverlight's loading screen?	private void Application_Startup(object sender, StartupEventArgs e)\n{\nvar timer = new DispatcherTimer();\ntimer.Interval = TimeSpan.FromSeconds(10);\nEventHandler eh = null;\n\neh = (s, args) =>\n{\n    timer.Stop();\n    this.RootVisual = new Test();\n    timer.Tick -= eh;\n};\n\ntimer.Tick += eh;\n\ntimer.Start();\n}	0
21531056	21467836	Freeze Panes in multiple worksheets C#	worksheet.SheetView.Freeze(1,6);	0
17644157	17644111	Getting JSON instead of XML file when calling a service with WebClient	client.Headers.Add("accept", "application/xml");	0
13885374	13885285	How Destroy Sorting Of A Sorted List<string>	Random rnd = new Random();\nvar LS2 = LS1.OrderBy(_ => rnd.Next()).ToList();	0
31615294	31615141	How to delete a record in MVC without using a View?	public async Task<ActionResult> Delete(int id)\n{\n    string url = String.Format("api/user/{0}", id);\n\n    using (HttpClient client = new HttpClient())\n    {\n        client.BaseAddress = new Uri("http://localhost:49474/");\n        client.DefaultRequestHeaders.Accept.Clear();\n        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));\n\n        HttpResponseMessage response = await client.DeleteAsync(url);\n\n        return RedirectToAction("Index");\n    }\n}	0
13314740	13314617	Replace characters in between string?	static string ReplaceSpacesWithZerosExceptLeading(string s)\n{\n    return s.TrimStart(' ').Replace(' ', '0').PadLeft(s.Length);\n}	0
8533389	8533031	Change data on gridview row click	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n    {\n        int PersonID=Convert.ToInt32(dataGridView1.CurrentRow.Cells["PersonID"].ToString());\n        //Pass PersonID to Parameter and Get detail list\n\n    }	0
30319032	30318801	Set Column value Order RDLC	Sorting Tab	0
9832475	9832225	Scan table in stored procedure	var dataList = new List<object>();\n\nwhile (reader.Read()) \n{\n    var values = new object[reader.FieldCount];\n    var fieldCount = reader.GetValues(values);\n\n    dataList.AddRange(values);\n}\n\n//var arrayData = dataList.ToArray()\nvar arrayData = dataList.ConvertAll<double>(o => (double) o).ToArray();	0
33239005	33238875	Passing in dropdown as a parameter	var dropDown = Page.FindControl("myDropDown") as DropDownList;\nMyLevel myLevel = GetLevel(myValue, dropDown);	0
15661454	15661419	Validate Date format using C# 4.0	private static bool IsDate(string inputText)\n{\n    DateTime d;\n    return DateTime.TryParse(inputText, out d);\n}	0
13957089	13955478	Word 2007 Remove section break	private void RemoveAllSectionBreaks(Word.Document doc)\n{\n    Word.Sections sections = doc.Sections;\n    foreach (Word.Section section in sections)\n    {\n        section.Range.Select();\n        Word.Selection selection = doc.Application.Selection;\n        object unit = Word.WdUnits.wdCharacter;\n        object count = 1;\n        object extend = Word.WdMovementType.wdExtend;\n        selection.MoveRight(ref unit, ref count, ref oMissing);\n        selection.MoveLeft(ref unit, ref count, ref extend);\n        selection.Delete(ref unit, ref count);\n    }\n}	0
21670521	21670439	How to add month to a Datetime object?	DateTime installmentDate=Convert.toDateTime(baseDate.tostring("MM/dd/yyyy")).AddMonths(1);	0
10613599	10613292	Get unmarked data from db	DECLARE @teamName varchar(50) = 'TEAM01'\n\nSELECT * \nFROM Mails M\nLEFT OUTER JOIN MailAssignments MA ON M.msgId = MA.msgId\nWHERE MA.msgId IS NULL OR \n      (\n         MA.forTeam IS NULL AND \n         MA.notForTeam <> @teamName AND \n         MA.processedByTeam <> @teamName\n      )	0
2144464	2144370	winform application to launch and read from a file with custom extension	static class Program\n    {    \n        [STAThread]\n        static void Main()\n        {\n            string[] args = Environment.GetCommandLineArgs(); \n            string text = File.ReadAllText(args[1]);\n\n            // ...\n        }\n    }	0
1527210	1527193	Using an EventHandler to detect a variable change?	//Some code here	0
5060849	5060829	Split string by array of strings and preserve delimeters	results = results.Select((x, i) => names[i] + x).ToArray();	0
10761546	10760833	Show 3 result from each element in group by	var lastMeterReading = (from meeters in metermodel.Meeters\n                       join reading in metermodel.Readings on meeters.MeterNumber equals reading.MeterNumber\n                       where (maalers.CustNo == 6085574)\n                       orderby reading.Date descending\n                       group meeters by new { meeters.MeterNumber, reading.Consumption, reading.Date } into result\n                       from m in result\n                       select new {Key = m.Key, Info = result.OrderByDescending(r => r.Date).Take(3)})\n                       .Select(r => new \n{ Consumption = r.Consumption, No = r.MeterNumber, Date = r.Date });	0
23693950	23693209	How to get all the user's details from Active Directory using LDAP	sb.AppendLine("Email = " + de.Properties["mail"].Value.ToString());	0
18866172	18865054	How to decrypt encrypted image in memory & use in Application	public Stream DecryptFile(string encryptedImageFile){\n  byte[] ImageBytes;\n\n  ImageBytes = File.ReadAllBytes(encryptedImageFile);\n\n  for (int i = 0; i < ImageBytes.Length; i++){\n    ImageBytes[i] = (byte)(ImageBytes[i] ^ 5);\n  }\n\n  return new MemoryStream(ImageBytes);\n}	0
7529514	7527163	dropdownlist in footer row of gridview being clear on postback	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType != DataControlRowType.Footer)\n        {\n            //do the binding for the normal rows\n        }\n    }	0
20158438	20158378	How to unshare a Datagridviewrow	ThreadGrid.Rows.Remove(ThreadGrid.Rows[0]);	0
31625240	31624070	Space between character C# string	string theDate1 = dateTimePicker1.Value.ToString("ddMMyyyy");\ntheDate1 = string.Join(" ", theDate1.AsEnumerable());	0
437176	437137	Can't get values from rows/cells in GridView	row.Cells[1].Controls	0
11331300	11331072	Recommended approach to integrate applications without blocking interaction	App A -> Message1 -> AppB Inbound Queue\nApp A -> Message2 -> AppB Inbound Queue\n\n.... Later, when App B is able to do some work\n\nApp B Inbound Queue -> transaction -> Message1 -> App B \nApp B processes Message 1 -> App B Database\nApp B -> Message3 -> AppC Inbound Queue\n\n.... and so on	0
21846616	21846469	How to convert the following foreach loop to linq code format?	projectDataCandidate.ViewMaps\n    .Where(vm => !vm.IsNotTestLane)\n    .Select(this.GenerateTestView)\n    .ToList()\n    .ForEach(testView =>\n    {\n        this.SwimLaneViews.Add(testView);\n        testView.ItemsOrphaned += OnItemsOrphaned;\n    });	0
31184400	31184089	C# Populating ListBox from another Class	private void Button_Click_1(object sender, RoutedEventArgs e)\n    {\n        Program.MyCall(this);\n    }\n\npublic static void MyCall(Form form)\n    {\n        form.Logger.Items.Add("Obtaining info ....");\n    }	0
31337509	31337231	Implement Interface and accessing methods	ISecurisable shoppingCart = new shoppingCart();\nshoppingCart.Deactivate();\n\npublic interface ISecurisable\n{\n    void Deactivate();\n}\n\npublic partial class shoppingCart : ISecurisable\n{\n     public void Deactivate()\n     {\n         shoppingCartid = null;\n         IsActive = false;\n         foreach (var shoppingCartDetails in Childs)\n         {\n            shoppingCartDetails.ParentId = ParentId;\n         }\n     }\n}	0
355749	355724	Embedding a DOS console in a windows form	var processStartInfo = new ProcessStartInfo("someoldapp.exe", "-p someparameters");\n\nprocessStartInfo.UseShellExecute = false;\nprocessStartInfo.ErrorDialog = false;\n\nprocessStartInfo.RedirectStandardError = true;\nprocessStartInfo.RedirectStandardInput = true;\nprocessStartInfo.RedirectStandardOutput = true;\nprocessStartInfo.CreateNoWindow = true;\n\nProcess process = new Process();\nprocess.StartInfo = processStartInfo;\nbool processStarted = process.Start();\n\nStreamWriter inputWriter = process.StandardInput;\nStreamReader outputReader = process.StandardOutput;\nStreamReader errorReader = process.StandardError;\nprocess.WaitForExit();	0
20768918	20768427	How to Use Image as Map PushPin	// Create a small circle to mark the current location.\nmyImage = new BitmapImage(new Uri("/Assets/Tiles/Launch/map.location.png", UriKind.RelativeOrAbsolute));\nvar image = new Image();\nimage.Width = 20;\nimage.Height = 20;\nimage.Opacity = 50;\nimage.Source = myImage;\n\n// Create a MapOverlay to contain the circle.\nmyLocationOverlay = new MapOverlay();\nmyLocationOverlay.Content = image;\nmyLocationOverlay.PositionOrigin = new Point(0.5, 0.5);	0
3757264	3755081	Counting sort - implementation differences	def sort(a):\n  B = 101\n  count = [0] * B\n  for (k, v) in a:\n    count[k] += 1\n  for i in range(1, B):\n    count[i] += count[i-1]\n  b = [None] * len(a)\n  for i in range(len(a) - 1, -1, -1):\n    (k, v) = a[i]\n    count[k] -= 1\n    b[count[k]] = a[i]\n  return b    \n\n\n>>> print sort([(3,'b'),(2,'a'),(3,'l'),(1,'s'),(1,'t'),(3,'e')])\n[(1, 's'), (1, 't'), (2, 'a'), (3, 'b'), (3, 'l'), (3, 'e')]	0
21974184	21974117	How can I search for a word in my DB and replace it with its synonym	SqlCommand myCommand = new SqlCommand("select * from synreplace where word='"+words1[i]+"'", myConnection);	0
15793780	15793409	how to split a string into multiple lines if more than 37 characters are present	static string sentence(string statement)\n{\n  if (statement.Length > 37)\n  {\n    var words = statement.Split(' ');        \n    StringBuilder completedWord = new StringBuilder();\n    int charCount = 0;\n\n    if (words.Length > 1)\n    {\n      for (int i = 1; i < words.Length - 1; i++)\n      {\n        charCount += words[i].Length;\n        if (charCount >= 37)\n        {\n          completedWord.AppendLine();\n          charCount = 0;\n        }\n\n        completedWord.Append(words[i]);\n        completedWord.Append(" ");\n      }\n    }\n\n    // add the last word\n    if (completedWord.Length + words[words.Length - 1].Length >= 37)\n    {\n      completedWord.AppendLine();\n    }\n    completedWord.Append(words[words.Length - 1]);\n    return completedWord.ToString();\n  }\n  return statement;\n}	0
13520684	13503365	How to iterate on a T object to find a property?	if (this.datasource != null)\n{\n    var y = (T)this.datasource;\n\n    var propList = typeof(T).GetProperties();\n    //try to assign the prop but it might be on a child-prop.\n    try \n    {           \n        retour = DataBinder.Eval(y, propriete.Name).ToString();\n    }\n    catch \n    {\n        foreach (PropertyInfo prop in propList)\n        {\n            if ((prop.PropertyType).FullName.Contains("Env."))\n            {\n                var childPropList = prop.PropertyType.GetProperties();\n                foreach (PropertyInfo childProp in childPropList)\n                {\n                    if (((System.Reflection.MemberInfo)(childProp)).Name == propriete.Name)\n                    {\n                        var x = DataBinder.GetPropertyValue(y, prop.Name);\n                        retour = DataBinder.Eval(x, propriete.Name).ToString();\n                    }\n                }\n            }\n        }\n    }\n}	0
13154892	13154833	Windows 8 apps - EntranceThemeTransition using C#?	myStackPanel.ChildrenTransitions = new \n             TransitionCollection {new EntranceThemeTransition()};	0
22083053	22082753	StackPanel space between each item at runtime	sD.Margin = new Thickness(12,12,0,0);	0
10771004	10770912	c# xml comments for properties / assessors	/// <summary>\n    ///   Something about property.\n    /// </summary>\n    /// <remarks>\n    /// Some extra remarks that won't show up in the property's intellisense later.\n    /// </remarks>	0
3470780	3470667	Query a list for only duplicates	int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };\nvar duplicates = listOfItems\n    .GroupBy(i => i)\n    .Where(g => g.Count() > 1)\n    .Select(g => g.Key);\nforeach (var d in duplicates)\n    Console.WriteLine(d);	0
11453119	11439827	Extracting values from Initializationstring and returning as a key-value pair	using System.Linq;\nusing System.Xml.Linq;\n\nstatic class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    public static void Main ( )\n    {\n        var xDoc = XElement.Load ( "ApplicationInit.xml" );\n        var appSettingsDictionary = (xDoc.Descendants("InputElement")\n            .Select ( item => new \n                             { \n                                 Key = item.Attribute("name").Value,\n                                 Value = item.Descendants("id").First().Value \n                             }\n                    )\n                ).ToDictionary ( item => item.Key, item => item.Value );\n    }\n}	0
14836392	14821069	converting string to?	// collect relevant inputs\n            foreach (Control c in fPanelIn.Controls)\n            {\n                if (c.Tag is PropertyInfo) \n                {\n                    PropertyInfo pi = c.Tag as PropertyInfo;\n\n                    if(c.Text.Length>0)\n                    {\n                        Type ti = pi.PropertyType;\n\n                        if (ti.IsGenericType)\n                        {\n                            ti = ti.GetGenericArguments()[0];\n                        }\n                        object o = Convert.ChangeType(c.Text, ti);\n\n                        pi.SetValue(Calculator, o, null);\n\n                        //MethodInfo mi = calcType.GetMethod(ConstructMethodName(pi), new Type[] { typeof(String) });\n\n                        //mi.Invoke(Calculator, new object[] { c.Text });\n                    }\n                    else\n                    {\n                        pi.SetValue(Calculator, null, null);\n                    }\n                }\n            }	0
3282834	3282642	Scrolling panel causes controls to appear halfway down panel	int iYpos = pnlMain.AutoScrollPosition.Y	0
18475569	18475266	How to get data returned from database that contains either a date or returns nothing in to a view in .Net MVC	DateTime? lastEntryDate = null;\n        foreach (DataRow dr in ds.Tables[0].Rows)\n        {\n            lastEntryDate = (DateTime?)dr["When"];\n        }\n\n        ViewData["LastEntryDate"] = lastEntryDate;	0
4997500	4997443	Remove duplicates in multi-element string[] array?	Dictionary<string, string> addresses = new Dictionary<string, string>();\n\nforeach(string result in resultsArray)\n{\n    string splitResult[] = result.Split('|');\n\n    // check to see if address already exists, if it does, skip it.\n    if(!addresses.ContainsKey(splitResult[1]))\n    {\n        addresses.add(splitResult[1], splitResult[0]);\n    }\n}	0
29735805	29735455	Listbox deselect top item	listBoxTracks.SelectedItems.Remove(listBoxTracks.SelectedItems[0]);	0
12626312	12626258	looping through the values of an ArrayList in C#	foreach(var item in args )\n{\n  Console.WriteLine(item);\n}	0
15063745	15055257	No binding Value Property of Slider in Windows Phone 8	change Valor to a Double	0
31338086	31338007	How to exit while loop in multithread c#	if (ptr < list.Length-1)\n  {\n        ptr += 1;	0
9366657	9366548	Calculate zoom level to fit an image into a panel	var panel_ratio = targetPanel.Width / targetPanel.Height;\nvar image_ratio = image.Width / image.Height;\n\nreturn panel_ratio > image_ratio\n     ? targetPanel.Height / image.Height\n     : targetPanel.Width / image.Width\n     ;	0
22330066	22329970	How to create an Object from Generics in c#	public class GenericTest<T> where T : MyBuilder\n{\n    [TestInitialize]\n    public void Init()\n    {\n        target = (T)Activator.CreateInstance(typeof(T), new object[] { param1, param2, param3, param4 });\n    }\n}	0
4340912	4340630	How can I configure IIS 6 programmatically?	string iisPath = "IIS://localhost/W3svc/1/Root";\nDirectoryEntry IISRootEntry = new DirectoryEntry(iisPath);	0
9400308	9400071	Creating listbox items from a large string	listBox1.Items.AddRange(String.Split(...));	0
17644447	17644365	Truncating a number to specified decimal places	decimal TruncateTo100ths(decimal d)\n{\n    return Math.Truncate(d* 100) / 100;\n}\n\nTruncateTo100ths(0m);       // 0\nTruncateTo100ths(2.919m);   // 2.91\nTruncateTo100ths(2.91111m); // 2.91\nTruncateTo100ths(2.1345m);  // 2.13	0
12769459	12767563	Why is received data from the Serial Port Null?	if (connecttodevice == true)\n    {\n        DA.SetDataList(0, myReceivedLines);\n    }	0
21347268	21346879	Send Ajax call to action but how to convert given string data to something usable	string json = "profileTable%5B%5D=1&profileTable%5B%5D=2&profileTable%5B%5D=4&profileTable%5B%5D=5&profileTable%5B%5D=3&profileTable%5B%5D=6&profileTable%5B%5D=7&profileTable%5B%5D=8&profileTable%5B%5D=9&profileTable%5B%5D=10";\nvar str = json.Replace("%5B", "[").Replace("%5D", "]");\nvar strArray = str.Split('&');\n\nfor (int i = 0; i < strArray.Count(); i++)\n{\n    //get the required value from strArray\n    //Console.WriteLine(strArray[i]);\n}	0
15517412	15516747	Draw grid from code behind	private void AddGrids()\n{\n    for (int i = 0; i < 10; i++)\n    {\n        Grid grid = new Grid\n        {\n            HorizontalAlignment = HorizontalAlignment.Left,\n            VerticalAlignment = VerticalAlignment.Top,\n            Height = 100,\n            Width = 100,\n            Background = new SolidColorBrush(Color.FromArgb(255, 245, 245, 220)),\n            Margin = new Thickness("margin calculated by your algorithm")\n        };\n        LayoutRoot.Children.Add(grid);\n    }\n}	0
4956241	4955607	Possible to turn callback calls into IEnumerable	class Program\n{\n    static void Main(string[] args)\n    {\n        foreach (var x in CallBackToEnumerable<int>(Scan))\n            Console.WriteLine(x);\n    }\n\n    static IEnumerable<T> CallBackToEnumerable<T>(Action<Action<T>> functionReceivingCallback)\n    {\n        return Observable.Create<T>(o =>\n        {\n            // Schedule this onto another thread, otherwise it will block:\n            Scheduler.Later.Schedule(() =>\n            {\n                functionReceivingCallback(o.OnNext);\n                o.OnCompleted();\n            });\n\n            return () => { };\n        }).ToEnumerable();\n    }\n\n    public static void Scan(Action<int> act)\n    {\n        for (int i = 0; i < 100; i++)\n        {\n            // Delay to prove this is working asynchronously.\n            Thread.Sleep(100);\n            act(i);\n        }\n    }\n}	0
23718776	23718723	Add Int[] array into List<int[]>	collected_result.Add(result.ToArray());	0
20284708	20284568	How to format a string inside an array?	private string FormatStringByIndex(object field, int index)\n{\n    if (index > 0 && index < 3)\n        return string.Format("{0:yyyy-MM-dd HH:mm:ss.fffffff}", field);}\n    else\n        return field.ToString();\n}\n\n// ...\n\nStringBuilder sb = new StringBuilder();\nvar columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();\nsb.AppendLine(string.Join(",", columnNames));\nforeach (DataRow row in dt.Rows)\n{\n   var fields =   row.ItemArray.Select((field, index) => "\"" + FormatStringByIndex(field, index).Replace("\"", "\"\"") + "\"").ToArray();\n   sb.AppendLine(string.Join(",", fields));\n}	0
25409076	25308195	How to search characters between #, but do not use # in combination &#60 in C#	string value = "text1#text2&#60&#61#text3#56&*()_!";\nstring splitPattern = @"(?<!&)#|#(?!\d+)";\n\nList<string> values = Regex.Split(value, splitPattern).Where(s => s != String.Empty);	0
21326219	21326155	C# to VB .NET IntPtr conversion	Dim buffer As IntPtr() = New IntPtr(4) {}\n\nFor i As Int32 = 0 To 4\n    buffer(i) = Marshal.AllocHGlobal(100)\nNext\n\nFor i As Int32 = 0 To 4\n    Marshal.FreeHGlobal(buffer(i))\nNext	0
380712	380708	Shortest method to convert an array to a string in c#/LINQ	String.Join(",", arr.Select(p=>p.ToString()).ToArray())	0
20476513	20473304	HttpResponse is returning status code 400, after being set to a custom value	public bool CheckIfUserExists(string email)\n    {\n        if (email.Length > 254)\n        {                \n            throw new WebFaultException<string>("{EmailTooLong" + ":" + "Error 94043" + "}", System.Net.HttpStatusCode.BadRequest);\n        }\n        return DBUtility.CheckIfUserExists(email);\n    }	0
16039081	15984894	Serial port communication and IP address	foreach (char c in txtWrite.Text)\n{\n    serialPort1.WriteLine(c.ToString());\n    System.Threading.Thread.Sleep(100);\n\n }\n serialPort1.WriteLine("\r\n");	0
11597462	11584459	Extract literal strings from assembly	ildasm.exe /text /metadata=heaps mscorlib.dll >out.txt\n\n// User Strings\n// -------------------------------------------------------\n// 70000001 : ( 4) L"info"\n// 7000000b : ( 2) L", "\n// 70000011 : ( 5) L"value"\n// 7000001d : ( 1) L"D"\n...	0
24135114	24135014	In clause in Linq to SQL	from a in context.EH_PP_DmainComps\nwhere id.Contains(a.domainCode.ToString())\nselect new Entity.correlations(a)	0
1042098	1042087	How to select values within a provided index range from a List using LINQ	yourEnumerable.Skip(4).Take(3).Select( x=>x )\n\n(from p in intList.Skip(x).Take(n) select p).sum()	0
16943650	16943554	How to translate this line of code from C# to Visual Baisc	MapRecords.Add(New MapModal() With {.Location = New WPF.Location(47, -122), .TooltipTex = "Sample tooltiptext!"})	0
19260700	14368380	Moq to set up a function return based on called times	customerService.SetupSequence(s => s.GetCustomerName(It.IsAny<int>()))\n   .Returns("Joe")//first call\n   .Returns("Jane");//second call	0
1758243	1738498	Finding a class within list	private void BuildUpChildren(List<Node> list)\n        {\n            foreach (Node item in list)\n            {\n                List<Node> nodes = GetNodesByParent(item.Id);\n                item.Nodes.AddRange(nodes);\n                BuildUpChildren(nodes);\n            }\n}	0
22400431	22374235	Mapping entity without any key	public AMap() \n {\n    ....\n    ....\n    HasMany(a=> a.B).KeyColumn("aID").Inverse().Cascade.All();\n }\n\n public BMap()\n {\n   CompositeId()\n         .KeyProperty(b=> b.AID)\n         .KeyProperty(b=> b.Name)\n         .KeyProperty(b=> b.Year);\n   References(b=> b.A).Column("aID");\n   Map(b=> b.Name);\n   Map(b=> b.Year);\n }	0
20743181	20743119	Outlook window blocks access to Windows.Forms	oMailItem.Display(false);	0
30281369	30262068	WPF Cannot see image in runtime	Source="<dragged image path>"	0
23225956	23225231	C# - Arranging DataTable into a "|" Delimited Format With Potential Different Number Of Columns Per Record	var lines = myDataTable.AsEnumerable().GroupBy(row => //grouping Selector\n       new { id = row.id, \n       , firstName = row.firstName\n       , lastName = row.lastName\n       , dob = row.dob\n   }, (key, rows) => //result selector\n       (key.id + "|" \n         + key.firstname + "|" \n         + key.firstname + "|" \n         + key.dob + "|" \n         + string.Join("|", rows.Select(codeRow => codeRow.code))\n    )\n);	0
27976546	27976540	how to display only date from DateTime	string strDate = reader[6].ToString();\ndob_lbl.Text  =  DateTime.ParseExact(strDate, "M/dd/yyyy hh:mm:ss tt", \n                            CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");	0
5625213	5625146	Configuring the Date Popup on the WPF DatePicker Control	SelectedDate="{Binding TehDate, FallbackValue={x:Static sys:DateTime.Now}}"	0
22934565	22934540	How to read text file inside folder in c#	using System.Linq;\n\n//Get LatestFile  \nvar directory = new DirectoryInfo("c:\\Main");\nvar LatestFile = (from f in directory.GetFiles()\n             orderby f.LastWriteTime descending\n             select f).First();\n//Read contents \n string contents = File.ReadAllText(LatestFile);	0
15513861	15513713	How to write "XML doc" for declaration with multiple variables?	/// <summary>\n/// general explanation for TempAngle\n/// </summary>    \ndouble TempAngle = 1;\n\n/// <summary>\n/// general explanation for AngleCountDown \n/// </summary>\ndouble AngleCountDown = HalfSight;\n\n/// <summary>\n/// general explanation for sightanglefromcopter\n/// </summary>\ndouble SightAngleFromCopter = 0;	0
3906302	3906238	Collection of X elements, want to traverse them in groups of two (using Linq?)	public static IEnumerable<Tuple<TElement, TElement>> AsPairs<TElement>(this IEnumerable<TElement> @this)\n{\n    IEnumerator<TElement> enumerator = @this.GetEnumerator();\n\n    while (enumerator.MoveNext())\n    {\n        TElement left = enumerator.Current;\n\n        if (enumerator.MoveNext())\n        {\n            TElement right = enumerator.Current;\n\n            yield return Tuple.Create(left, right);\n        }\n        else\n        {\n            throw new ArgumentException("this", "Expected an even number of elements.");\n        }\n    }\n}\n\n...\nforeach (Tuple<TextBox, TextBox> pair = textBoxes.AsPairs())\n{\n    ...\n}	0
33990936	33990800	Japanese Character Encodeing	request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";	0
1919089	1919081	Unique set of strings in C#	HashSet<string>	0
11192063	11191955	Get ID from another table	categoryId = dc.Categories.Single(c => c.Name == p.category).Id;	0
22885046	22883543	Quickest way to open dataset, count the records and return the number to a variable	string cmdText = "SELECT COUNT(ID) FROM tblActivities WHERE [Activity] = 'Sleeping'";\nusing(SQLiteConnection con = new SQLiteConnection(cs))\nusing(SQLiteCommand cmd = new SQLiteCommand(cmdText, con))\n{\n    con.Open();\n    int count = Convert.ToInt32(cmd.ExecuteScalar());\n    Console.WriteLine("You have " + count.ToString() + " records sleeping");\n}	0
11042864	11042782	c# Regex matches too generous	bool testResult;\n\n        var testSuccess = "12345-01";\n        testResult = Regex.IsMatch(testSuccess, @"\A\d{5}-\d{2}\Z"); //is True\n\n        var testFail = "12345";\n        testResult = Regex.IsMatch(testFail, @"\A\d{5}-\d{2}\Z"); //is False	0
32991329	32990938	how to publish C# application with the access database	string sourcePath=@"C:\PROGRAM FILES\DEFAULT COMPANY NAME\SETUPER2";\nstring appDataPath= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\nstring fileName="F.MDF";\nSystem.IO.File.Copy(sourcePath+"\\"+fileName, appDataPath+"\\"+fileName ,false);	0
11849541	11585278	Get contentpresenter location (size and offset from owner)	presenter.TransformToVisual(control).Transform(new Point(0,0));	0
19565632	19565583	How to split following string?	Cookie.Split(new char[] { '=' }, 2)	0
12490956	12490689	Can I send emails without authenticating on the SMTP server?	SmtpClient mailClient = new SmtpClient("your.emailgateway.com");\nmailClient.Send(message);	0
11900516	11896159	Arrays position inside foreach	if(msg_arr[0] == "setelg") { \n//Item found or true\n } \nelse { \n//Item not found or false\n }	0
4261975	4261645	Inject property call with Mono Cecil	var module = ModuleDefinition.ReadModule ("assembly.dll");\nvar container = module.GetType ("Container");\nvar test = container.Methods.First (m => m.Name == "Test");\nvar field = container.Fields.First (f => f.Name == "DialogResult");\n\nvar il = test.Body.GetILProcessor ();\n\nvar first = test.Body.Instructions [0];\n\nil.InjectBefore (first, il.Create (OpCodes.Ldarg_0));\nil.InjectBefore (first, il.Create (OpCodes.Ldc_i4, (int) DialogResult.Ok));\nil.InjectBefore (first, il.Create (OpCodes.Stfld, field));	0
25844349	25844294	Convert List<int> to a Dictionary<int,int> using LINQ	var result = list.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count());	0
13550678	13549351	How to persist design time property changes that were made programmatically?	public class MyLabel: Label\n{\n    public string ID { get; set; }\n\n    protected override void OnCreateControl()\n    {\n        base.OnCreateControl();\n        if (this.DesignMode && string.IsNullOrEmpty(this.ID))\n        {\n            this.ID = Guid.NewGuid().ToString();\n        }\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        this.Text = this.ID;\n    }\n}	0
27324145	27317787	Get float value out from NSDictionary	float f = (metrics ["leftInset"] as NSNumber).FloatValue;	0
3714937	3714804	How to customize XML serialization output for Object?	[System.Xml.Serialization.XmlElementAttribute("files", typeof(Files))]\n[System.Xml.Serialization.XmlElementAttribute("metrics", typeof(Metrics))]\npublic object[] Items { get; set; }	0
10285452	10285243	Set Maximum DateTime on a field in MVC application via DataAnnotations	public sealed class DateEndAttribute : ValidationAttribute\n{\n    public string DateStartProperty { get; set; }\n    public override bool IsValid(object value)\n    {\n        // Get Value of the Date property\n        string dateString = HttpContext.Current.Request[YourDateProperty];\n        DateTime dateNow = DateTime.Now\n        DateTime dateProperty = DateTime.Parse(dateString);\n\n        // \n        return dateProperty < dateNow;\n    }\n}	0
24745647	24741371	How to specify subfolder of DataDirectory in C#	using (var con = new SqlCeConnection())\n    {\n        con.ConnectionString = @"Data Source = |DataDirectory|\Database\DB.sdf;Persist Security Info=False";\n        var cmd = new SqlCeCommand("SELECT * FROM TEST", con);\n        con.Open();\n        var data = new DataTable("whatever");\n        data.Load(cmd.ExecuteReader());\n        con.Close();\n    }	0
26343099	26343009	How do I call a function in C# that adds text to your existing code?	string foo = "boogie";\n\nstring path = @"C:\Users\Me\Desktop\"+foo+".xml";\n\nusing (StreamWriter fv = File.AppendText(path))\n{\n    XMLHeader(fv);\n    fv.WriteLine("HANDLINGUNIT> \r\n");\n}\n\nPrivate Void XMLHeader(StreamWriter fv)\n{\n    // *pseudocode for my question*\n    // convert this to string:\n    fv.WriteLine("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\r\n");\n    fv.WriteLine("<asx:abap xmlns:asx = \"http://www.awebsite.com\" version = \"1.0\">\r\n");\n    fv.WriteLine("<asx:values>\r\n");\n}	0
10712171	10711821	Get entity with filtered inner entities - EF	var query = from e in dbContext.Entry\n            select new { Entry = e, Related = e.Contents.Where(c => c.Value > 10) };\nreturn query.Where(p => p.Related.Count > 0).Select(p => p.Entry);	0
12075693	12075157	Unable to format Xml for Excel	Open XML SDK	0
7908482	7908343	List of Timezone ID's for use with FindTimeZoneById() in C#?	using System;\n\nnamespace TimeZoneIds\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())\n                Console.WriteLine(z.Id);\n        }\n    }\n}	0
3004953	3004786	How to maintain my data like a session variable in .NET Windows Forms?	class Program\n{\n    internal static Dictionary<string, object> GlobalVariables = new Dictionary<string, object>();\n\n    static void Main(string[] args)\n    {\n        ...\n    }\n}	0
22032491	22032030	How to combine 3 action before running loop?	var actions = new List<Action<Item, Item>>();\n\nif (!string.IsNullOrEmpty(setting_.Name))\n{\n    actions.Add((tt1, tt2) =>\n    {\n        if (tt1 != null && tt2 != null) \n            tt2.Rename(tt1, setting_.Name);\n    });\n}\n\nif (setting_.Settings != null)\n{\n    actions.Add((tt1, tt2) =>\n    {\n        if (tt1 != null && tt2 != null)\n            tt2.ChangeSettings(tt1, setting_.Settings);\n    });\n}\n\nif (setting_.Settings != null)\n{\n    actions.Add((tt1, tt2) =>\n    {\n        if (tt1 != null && tt2 != null)\n            tt2.ChangeLocation(tt1, setting_.Location);\n    });\n}\n\nforeach (var item in itemCollection)\n{\n    var tt1 = item.GetTT1();\n    var tt2 = item.GetTT2();\n    actions.ForEach(a => a(tt1, tt2));\n}	0
10836657	10836195	Ignoring invalid mail server certificates in C#	EnableSsl = false;	0
25824178	25824154	Counting number of element in array of list	List<int>[] arrList = new List<int>[3];\narrList[0] = new List<int>{1,2,3};\narrList[1] = new List<int>{1,2,3};\narrList[2] = new List<int>{1,2};\n\nint cnt = arrList.Sum(l => l.Count); // 8	0
4305146	4305129	C# Simple Regex - 32 characters, containing only 0-9 and a-f (GUID)	Regex regex = new Regex("^[0-9a-f]{32}$");\nif (regex.IsMatch(text))\n...	0
6751849	6586914	Calculate zoom level on google maps control in C#	// Set the map to call zoomMap javascriptFunction\n    GoogleMap.OnClientMapLoad = "zoomMap";\n\n    // build zoomMap javascript function. I already know what my bounds are\n    StringBuilder script = new StringBuilder();\n    script.AppendFormat("<script>").AppendLine();\n    script.Append("function zoomMap() {").AppendLine();\n    script.AppendFormat("var sw = new GLatLng({0}, {1});", minLat, minLong).AppendLine();\n    script.AppendFormat("var ne = new GLatLng({0}, {1});", maxLat, maxLong).AppendLine();\n    script.AppendFormat("var bounds = new GLatLngBounds(sw, ne);").AppendLine();\n    script.AppendFormat("var zoomLevel = GoogleMap.GMap.getBoundsZoomLevel(bounds);").AppendLine();\n    script.AppendFormat("GoogleMap.GMap.setZoom(zoomLevel);", GoogleMap.ClientID).AppendLine();\n    script.Append("}").AppendLine();\n    script.AppendFormat("</script>").AppendLine();\n\n    Page.RegisterClientScriptBlock("map", script.ToString());	0
24497446	24497309	Loading several BLOB from sql database into ListView in C#	for (int i = 0; i < dt.Rows.Count; i++)\n{\n    using (MemoryStream mStream = new MemoryStream())\n    {\n        myRow = dt.Rows[i];\n        MyData = (byte[])myRow["Picture"];\n        mStream.Write(MyData, 0, Convert.ToInt32(MyData.Length));\n        mPictures.Add(new Bitmap(mStream, false));\n    }\n}	0
24124670	24124648	Access to names of all files of directory via FileSystemWatcher	Directory.EnumerateFiles()	0
5366031	5365951	draw multiple curves in WinForms picturebox	Point[] ptarray = new Point[3];\nptarray[0] = new Point(250, 250);\nptarray[1] = new Point(300, 300);\nptarray[2] = new Point(350, 400);\n\nPen pengraph = new Pen(Color.Green, 0.75F);\ng.DrawCurve(pengraph, ptarray);\n\nPoint[] ptarray2 = new Point[3];\nptarray2[0] = new Point(100, 100);\nptarray2[1] = new Point(200, 150);\nptarray2[2] = new Point(250, 250);\n\nPen pengraph2 = new Pen(Color.Yellow, 1.25F);\ng.DrawCurve(pengraph2, ptarray2);	0
1953668	1949911	Sticking HTML formatting into System.String object in C#	foreach (var c in abbr)\n        {\n            String s = String.Format("{0} - ({1})", c.DepartmentAbbr, c.DepartmentName);\n            rcbDepartments.Items.Add(new RadComboBoxItem(s, c.DepartmentID.ToString()));\n        }\n    }\n}	0
8577102	8576613	select one value of checkboxCombobox(additional)	comboBox1.Visible = true;\nPreDefSerials.Visible = false;	0
26657400	26655734	How to Access a video gallery with windows phone 8 Silverlight?	KnownFolders.VideoLibrary.GetFilesAsync();	0
17347304	17347218	Killing a WPF application from a timer	Application.Current.Dispatcher.Invoke(new Action(() => Application.Current.Shutdown()));	0
745962	745842	String to method	using IronPython.Hosting;\n\nPythonEngine pythonEngine = new PythonEngine();\nstring script = @"import clr \n clr.AddReference(""System.Windows.Forms"") \n import System.Windows.Forms as WinForms \n WinForms.MessageBox.Show(""Hello"", ""Hello World"")";\npythonEngine.Execute(script);	0
8537351	8537182	Response.StatusDescription not being sent from JsonResult to jQuery	xhr.statusText	0
16445192	16444872	C# Make application compatible on other computers?	private void EmptyFolderContents(string folderName)\n{\n    if(Directory.Exists(folderName)\n    {\n        foreach (var folder in Directory.GetDirectories(folderName))\n        {\n            try\n            {\n                Directory.Delete(folder, true);\n            }\n            catch(Exception ex)                \n            {\n                 MessageBox.Show("Error deleting folder: " + folder+ Environment.NewLine + ex.Message);\n            }\n        }\n        foreach (var file in Directory.GetFiles(folderName))\n        {\n            try\n            {\n                File.Delete(file);\n            }\n            catch(Exception ex)\n            {\n                 MessageBox.Show("Error deleting file: " + file + Environment.NewLine + ex.Message);\n            }\n        }\n\n    }	0
3736542	3736477	How to read inputstream from HTML file type in C# ASP.NET without using ASP.NET server side control	//aspx\n<form id="form1" runat="server" enctype="multipart/form-data">\n <input type="file" id="myFile" name="myFile" />\n <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />\n</form>\n\n//c#\nprotected void btnUploadClick(object sender, EventArgs e)\n{\n    HttpPostedFile file = Request.Files["myFile"];\n    if (file != null && file.ContentLength )\n    {\n        string fname = Path.GetFileName(file.FileName);\n        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));\n    }\n}	0
10246861	10246705	read data from ODBC using DataSet	using (OdbcConnection connection = \n               new OdbcConnection(connectionString))\n    {\n        string queryString = "SELECT * FROM Members";\n        OdbcDataAdapter adapter = \n            new OdbcDataAdapter(queryString, connection);\n\n        // Open the connection and fill the DataSet.\n        try\n        {\n            connection.Open();\n            adapter.Fill(dataSet);\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }\n        // The connection is automatically closed when the\n        // code exits the using block.	0
7409569	7409457	How to sum two objects?	using System;\nusing System.Diagnostics;\n\nnamespace ConsoleApplication33 {\n  public static class Program {\n    private static void Main() {\n      var result1=DoTheCSharpOperation(Operator.Plus, 1.2, 2.4);\n      var result2=DoTheCSharpOperation(Operator.Plus, "Hello", 2.4);\n      var result3=DoTheCSharpOperation(Operator.Minus, 5, 2); \n\n      Debug.WriteLine(result1); //a double with value 3.6\n      Debug.WriteLine(result2); //a string with value "Hello2.4"\n      Debug.WriteLine(result3); //an int with value 3\n    }\n\n    public enum Operator {\n      Plus,\n      Minus\n    }\n\n    public static object DoTheCSharpOperation(Operator op, dynamic a, dynamic b) {\n      switch(op) {\n        case Operator.Plus:\n          return a+b;\n        case Operator.Minus:\n          return a-b;\n        default:\n          throw new Exception("unknown operator "+op);\n      }\n    }\n  }\n}	0
5165905	5165780	c# Regex substring after second time char appear	4TOT.*?\|.*?\|(.*?)\|	0
7423124	7423092	Create Folder o Save in Temp	string tempPath = System.IO.Path.GetTempPath();	0
8576013	8575644	How to split the string numbers and characters in asp.net	DECLARE @String VARCHAR(200)\nSET @String = '100254E'\n\nDECLARE @number INT,\n        @letter VARCHAR(5)\n\nSET @number = CAST(LEFT(@String, LEN(@String) - 1) AS INT)\nSET @letter= SUBSTRING(@String,LEN(@String), LEN(@String))\n--Check if it is Z\nIF(ASCII(@letter)=90)\nBEGIN\n    SET @number=@number+1\n    SET @letter=CHAR(65)\nEND\nELSE\nBEGIN\n    SET @letter=CHAR(ASCII(@letter)+1)\nEND\n\nSELECT CAST(@number AS VARCHAR(100))+@letter AS new\nSELECT @String AS old	0
18399949	18399889	How to call a class in c#	myPurge.TeachMeCSharp(MSDN)	0
17466694	17466539	Converting string with month that is not integer to datetime	var date = DateTime.Parse("Mar 25 2013 6:30PM");\n\n Console.WriteLine(date.ToString()); /*This will output the date in the required format */	0
1690198	1690151	how to find file size in windows-mobile?	FileInfo fi = new FileInfo(pathToMyFile);\nif(fi.Exists)\n    long sizeOfMyFile = fi.Length;	0
23722800	23722484	XPath select node in Xaml	//Load xml in XElement\nstring xml="xml";\nXElement xmlTree=XElement.Parse(xml);\n//Get required element\nXElement child = xmlTree.Element("SomeNode.AnyProperty");\n//replace it with requried element\nchild.ReplaceWith(\n    new XElement("NewChild", "new content")\n);	0
2565292	2565276	Hashtable is that fast	count()	0
16831794	16831317	C# XML deserialization XmlAttribute	public class Items1\n{\n    [XmlAttribute]\n    public string note { get; set; }\n    [XmlElement]\n    public List<item1> item1 { get; set; }\n}\n\npublic class Item2\n{\n    [XmlElement]\n    public List<item2> item2 { get; set; }\n}\n\n[XmlRootAttribute("Something", Namespace="", IsNullable=false)]\npublic class Something\n{\n   [XmlElement]\n    public Items1 items1 { get; set; }\n    [XmlElement]\n    public Item2 item2 { get; set; }\n}\n\n\nSomething objSomething = this.Something();\n\nObjectXMLSerializer<Something>.Save(objSomething, FILE_NAME);\n\nLoading the xml\n\nobjSomething = ObjectXMLSerializer<Something>.Load(FILE_NAME);	0
29936304	29936071	How to call javascript by passing multiple arguments from c#	this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx", "<script>moreFieldsEditFunction('" + extraFieldName[i] + "','" + extraFieldValue[i] + "');</script>");	0
13333425	13333211	Any way to convert C# XML Comments into C# Comment?	string content =\n@"<member name=""P:..."">\n  <summary>This is the summary.</summary>\n  <returns>This is the return info.</returns>\n  </member>";\n\nXDocument doc = XDocument.Parse(content);                        \nforeach (var member in doc.Descendants("member"))\n{\n     StringBuilder sb = new StringBuilder();\n\n     sb.AppendLine("/// <summary>");\n     sb.AppendLine("/// " + member.Descendants("summary").Select(e => e.Value).FirstOrDefault());\n     sb.AppendLine("/// </summary>");\n\n     sb.AppendLine("/// <returns>");\n     sb.AppendLine("/// " + member.Descendants("returns").Select(e => e.Value).FirstOrDefault());\n     sb.AppendLine("/// </returns>");\n\n     // sb.ToString() contains the comments for this member\n }	0
34171029	34170837	Unable to parse JSON from GET request	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Newtonsoft.Json.Linq;\n\nnamespace ConsoleApplication10\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string str = @"{\n  ""batchcomplete"": """",\n  ""query"": {\n    ""normalized"": [\n      {\n        ""from"": ""program"",\n        ""to"": ""Program""\n      }\n    ],\n    ""pages"": {\n      ""23771"": {\n        ""pageid"": 23771,\n        ""ns"": 0,\n        ""title"": ""Program"",\n        ""revisions"": [\n          {\n            ""contentformat"": ""text/x-wiki"",\n            ""contentmodel"": ""wikitext"",\n            ""*"": ""the page content is too long to reasonably post here""\n          }\n        ]\n      }\n    }\n  }\n}";\n            var json = JObject.Parse(str);\n            var pages = json["query"]["pages"].Values().First();\n\n            Console.WriteLine(pages["title"]);\n            Console.WriteLine(pages["revisions"][0]["*"]);\n        }\n    }\n}	0
15147490	15146693	Show my current cursor position as a current line and current column?	private void Key_Down(object sender, KeyEventArgs e)\n{\n    if (e.KeyData == Keys.Enter)\n    {\n        int line = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);\n        int column = richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexFromLine(line);\n\n        toolStripStatusLabel5.Text = "Line" + " " + line.ToString();\n        toolStripStatusLabel6.Text = " Column" + " " + column.ToString();\n        toolStripStatusLabel3.Text = Cursor.Position.ToString(); // where is my mouse cursor at this Time like that x and y cordinate 330,334\n        Update();\n    }\n}	0
17845713	17844409	Converting byte array to string in C#	[TestMethod]\n  public void TestBytToString()\n  {\n     byte[] bytArray = new byte[256];\n     ushort[] usArray = new ushort[256];\n     for (int i = 0; i < bytArray.Length; i++)\n     {\n        bytArray[i] = (byte)i;\n\n     }\n\n     string x = System.Text.Encoding.Default.GetString(bytArray);\n     for (int i = 0; i < x.Length; i++)\n     {\n        int y = System.Text.Encoding.Default.GetBytes(x.Substring(i, 1))[0];\n        Assert.AreEqual(i, y);\n     }\n  }	0
18102755	18102300	Mapping: Default value across databases	var db = DependencyResolver.Current.GetService<Provider>();\n\nif (db == null)\n{\n    throw new NullReferenceException("Service Provider not found.");\n}\n\nif (db is SybaseProvider)\n{\n    map.Column(c => c.Default("now(*)"));\n}\nelse // SQLite\n{\n    map.Column(c => c.Default("CURRENT_TIMESTAMP"));\n}\nmap.Generated(PropertyGeneration.Insert);\nmap.NotNullable(true);	0
8809808	8809745	Linq to file system to get last created file in each sub folders	DirectoryInfo di = new DirectoryInfo(@"C:\SomeFolder");\n\nvar recentFiles = di.GetDirectories()\n                    .Select(x=>x.EnumerateFiles()\n                                .OrderByDescending(f=> f.CreationTimeUtc)\n                                .FirstOrDefault())\n                    .Where(x=> x!=null)\n                    .Select(x=>x.FullName)\n                    .ToList();	0
32219807	32219593	Comparing the properties of two objects	void CompareCars(Car oldCar, Car newCar) \n{\n    Type type = oldCar.GetType();\n    PropertyInfo[] properties = type.GetProperties();\n\n    foreach (PropertyInfo property in properties)\n    {\n        object oldCarValue = property.GetValue(oldCar, null); \n        object newCarValue = property.GetValue(newCar, null); \n        Console.WriteLine("oldCar." + property.Name +": " + oldCarValue.toString() " -> "  + "newCar." + property.Name +": " newCarValue.toString();\n    }\n}	0
34265489	34265190	Assign dynamically Control to ActiveControl	this.ActiveControl = (PictureBox)sender;	0
32669976	32540338	Validating items in ItemsControl	NextButtonVisibility="{Binding ElementName=txtContactValue, Path=(Validation.HasError), Converter={StaticResource BooleanToVisibilitConverter}}"	0
32229823	32229433	Get XML value from xml file	var xDoc = XDocument.Parse(xmlString);\n\nXNamespace ns = "http://www.cargowise.com/Schemas/Universal/2011/11";\n\nvar value = xDoc\n    .Element(ns + "UniversalInterchange")\n    .Element(ns + "Body")\n    .Element(ns + "UniversalShipment")\n    .Element(ns + "Shipment")\n    .Element(ns + "DataContext")\n    .Element(ns + "DataTargetCollection")\n    .Element(ns + "DataTarget")\n    .Element(ns + "Type")\n    .Value;	0
13712732	3711719	how to insert a row in the middle of a google spreadsheet	function onOpen() {\n  // get active spreadsheet\n  var ss = SpreadsheetApp.getActiveSpreadsheet();\n\n  // create menu\n  var menu = [{name: "Insert row ", functionName: "insertRow"}];\n\n  // add to menu\n  ss.addMenu("Insert", menu);  \n}\n\nfunction insertRow() {\n  // get active spreadsheet\n  var ss = SpreadsheetApp.getActiveSpreadsheet();\n\n  // get first sheet\n  var sh = ss.getSheets()[0];\n\n  // determine number of rows (compensate for header)\n  var rows = sh.getMaxRows();\n\n  // insert row in the middle\n  var middle = rows/2;\n  sh.insertRows(middle);\n}	0
4099741	4099591	Split Graphic into pieces c#	pictureBox1.Invalidate();	0
16153537	16153494	Mocking generics that implement multiple interfaces	public interface ICanTestAAndB : IInterfaceA, IInterfaceB {}\n\nvar mock = new Mock<ClassA<ICanTestAAndB>>();	0
11565240	11565041	Replacing Values in CSV export	public override void WriteField( string field )\n    {\n        if (field.ToLower() == bool.TrueString.ToLower())\n             field = "1";\n        if (field.ToLower() == bool.FalseString.ToLower())\n             field = "0";\n        base.WriteField(field);\n    }	0
9838714	9805415	Return Elements that are not in the other XML	var newAddresses= Xml1.Descendants("Address").Cast<XNode>()\n                      .Except(Xml2.Descendants("Address").Cast<XNode>(), new XNodeEqualityComparer());	0
27372627	27372502	How to make a function which returns Type <T>	public static List<T> ConvertArrayListToList<T>(CollectionClass paramcollection)\n{\n    return paramcollection.Cast<T>().ToList(); \n\n}	0
845004	844995	convert a string[] to string with out using foreach	string[] text = new string[] { "asd", "123", "zxc", "456" };\n\nvar result = texts.Aggregate((total, str) => total + "," + str);	0
26761388	26761274	How to call a list thats made from an enum and bind it to a drop down list?	ddlSize.DataSource = TerritoryServices.GetSize();\nddlSize.DataTextField = "Value";\nddlSize.DataValueField = "Key";\nddlSize.DataBind();	0
13554217	13554195	Escape curly brackets around a template entry when using String.Format	string result = String.Format("products/item/{{{0}}}", itemIdPattern);	0
6661146	6661069	set html img src from byte array	Response.ContentType = "image/png";\n Response.BinaryWrite( <bytes> );	0
1024063	1024052	How to take value click gridview without js?	protected void gvDepartman_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex >=0)\n        {\n            string selectedid = (gvDepartman).DataKeys[e.Row.RowIndex].Value.ToString();\n            e.Row.Attributes["onclick"] = string.Format("location.href='Test.aspx?id={0}'", selectedid);\n        }\n    }	0
19978168	19977848	How to find the nth duplicate from an array	public static char returnSecondDuplicate(char[] arr)\n{\n    if (arr.Length == 0)\n        throw new ArgumentNullException("Empty Array passed");\n    var dictionary = new Dictionary<char, int>();\n    char firstDuplicate = '\0';\n\n    for (int i = 0; i <= arr.Length - 1; i++)\n    {\n\n        if (!dictionary.ContainsKey(arr[i]))\n        {\n            dictionary.Add(arr[i], 1);\n        }\n        else if (firstDuplicate == '\0')\n        {\n            firstDuplicate = arr[i];\n        }\n        else if(arr[i] != firstDuplicate)\n        {\n            return arr[i];\n        }\n\n    }\n\n    return '\0'; //not found\n}	0
7302010	7301953	Using struct in C# as you would in C - can you?	Marshal.Copy	0
13542726	13542683	DateTime.ParseExact throws expcetion on windows xp	dt.Rows[0]["duedate"] = DateTime.ParseExact(textBox_duedate.Text, \n                            new CultureInfo("en-US")).ToString("dd-MM-yyyy");	0
11651845	11651760	Change more then one variable in one line?	class PageLoc\n{\n    public int Header { get; set; }\n    public int Body { get; set; }\n    public int Footer { get; set; }\n\n    void MoveAll(int distance) {\n        Header += distance;\n        Body += distance;\n        Footer += distance;\n    }\n}	0
9275937	9275559	How to edit path in a Windows link file	using System;\nusing IWshRuntimeLibrary;\n\nnamespace ShortCutTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var wsh = new WshShell();\n            var shortcut = (IWshShortcut)wsh.CreateShortcut(@"C:\cmd.lnk");\n            shortcut.Description = "Shortcut for cmd.exe";\n            shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) +  @"\cmd.exe";\n            shortcut.Save();\n        }\n    }\n}	0
12703284	12701916	How to send e-mail from asp using gmail?	using System.Net.Mail;\n            using System.Net;\n            var fromAddress = new MailAddress("from@gmail.com", "From Name");\n            var toAddress = new MailAddress("to@gmail.com", "To Name");\n            const string fromPassword = "password";\n            const string subject = "test";\n            const string body = "Hey now!!";\n\n            var smtp = new SmtpClient\n            {\n                Host = "smtp.gmail.com",\n                Port = 587,\n                EnableSsl = true,\n                DeliveryMethod = SmtpDeliveryMethod.Network,\n                Credentials = new NetworkCredential(fromAddress.Address, fromPassword),\n                Timeout = 20000\n            };\n            using (var message = new MailMessage(fromAddress, toAddress)\n            {\n                Subject = subject,\n                Body = body\n            })\n            {\n                smtp.Send(message);\n            }	0
21278226	21278178	Remove seconds part from time C#	DateTime.ToShortTimeString()	0
32946702	32946439	Log4Net cannot parse xml configuration	var xmlConfig = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar + "logConfig.xml";	0
14500385	14500302	Acces mainwindow control from class	public void function(ref TextBox textBox)\n{\n  textbox.Text = string.empty;\n}	0
5093484	5093294	ObjectPool implementation deadlocks	stack.Count > 0	0
24926873	24909428	How can i get all groups of a local user using ObjectQuery?	class Program\n{\n    static ManagementScope scope =\n           new ManagementScope(\n               "\\\\ServerIP\\root\\cimv2");\n    static string username = "Test";\n\n\n    static void Main(string[] args)\n    {\n        string partComponent = "Win32_UserAccount.Domain='Domain',Name='"+username+"'";\n        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_GroupUser WHERE PartComponent = \"" + partComponent + "\"");\n        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))\n        {\n            var result = searcher.Get();\n            foreach (var envVar in result)\n            {\n                ManagementObject groupComponent = new ManagementObject("\\\\ServerIP\\root\\cimv2", envVar["GroupComponent"].ToString(), null);\n                Console.WriteLine(groupComponent["Name"]);\n            }\n        }\n        Console.ReadLine(); \n    }\n}	0
2568687	2568611	How to Create an XML Serializer for More than One Type?	XmlSerializer xs = new XmlSerializer(obj.GetType());	0
3729221	3728937	Parsing string and making list of required data	class Program\n{\n    private const string PATTERN = @".style[\d]+{[^}]*}";\n\n    private const string STYLE_STRING = @"  .right {          }      td{         }   table{          }   .style1{          }   .style2{          }   .style15{          }  .style20{        }";\n\n    static void Main(string[] args)\n    {\n        var matches = Regex.Matches(STYLE_STRING, PATTERN);\n        var styleList = new List<string>();\n\n        for (int i = 0; i < matches.Count; i++)\n        {\n            styleList.Add(matches[i].ToString());\n        }\n\n        styleList.ForEach(Console.WriteLine);\n\n        Console.ReadLine();\n    }\n}	0
21770183	21770053	How do access the attributes of a method's Parameters	[TestCase("")]\npublic void TestParameterAttribute([NotRequired]string theString)\n{\n    var method = MethodInfo.GetCurrentMethod();\n    var parameter = method.GetParameters()[0];\n    var result = false;\n\n    foreach (var attribute in parameter.GetCustomAttributes(true))\n    {\n        if (attribute.GetType() == (typeof(NotRequiredAttribute)))\n        {\n            result = true;\n        }\n    }\n\n    Assert.That(result, Is.True);\n}	0
3872138	3872084	How can I transform a List<string> into XML using Linq?	XElement xml = new XElement("Users",\n                    (from str in aList select new XElement("User", str)).ToArray());	0
6085727	6085693	How can I use a right click context menu on a DataGridView?	DataGridViewRow currentRow;\nvoid DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n{\n    if (e.RowIndex >= 0)\n        currentRow = self.Rows[e.RowIndex];\n    else\n        currentRow = null;\n}	0
31855967	31855832	How to determine if class inherits Dictionary<,>	var obj = new List<int>(); // new SerializableDictionary<string, int>();\nvar type = obj.GetType();\n\nvar dictType = typeof(SerializableDictionary<,>);\nbool b = type.IsGenericType && \n         dictType.GetGenericArguments().Length == type.GetGenericArguments().Length &&\n         type == dictType.MakeGenericType(type.GetGenericArguments());	0
3613802	3613615	How to validate X509 certificate?	X509Certificate2.Verify():	0
3247796	3247776	Coding Style - Passing method as Parameter	int i = MethodB();\nMethodA(i);	0
7919303	7919170	cell in Excel "Number stored as text"	oRng = oSheet.get_Range("C2", "C1000"); //change this range to suit your scenario\noRng.Formula = "<any formula you may be using already or skip it>";\noRng.NumberFormat = "#,##0.00";	0
9352183	9352066	Get ReturnParameter's Name property of a RuntimeMethodInfo object using Reflection (C#)	[Table(name="MyTable")]    \npublic class B : A\n    {\n\n[Key(column_name="id")]    \npublic Int32 B_ID;\n        public String B_Value;\n\n        public Int32 getID()\n        {\n            return B_ID;\n        }\n\n        public void setID(Int32 value)\n        {\n            B_ID = value;\n        }\n    }	0
29614820	29614774	Loop to write a cimma separated list of items	public static void Test()\n        {\n            for (int i = 49; i >= 1; i--)\n            {\n                Console.WriteLine(i + (i != 1 ? "," : ""));\n            }\n\n            Console.ReadLine();\n        }	0
4254881	4252421	How do I create a factory that returns different instances with different parameters?	public FailResult CreateFailResult(int failcode)\n{\n    return _kernel.Get<FailResult>(new ConstructorArgument("failCode", failcode));\n}	0
6529919	6525276	Get the body of an incoming email in an Outlook Addin	void MyApplication_NewMailEx(string anEntryID)\n{\n  Outlook.NameSpace namespace = this.GetNamespace("MAPI");  \n  Outlook.MAPIFolder folder = this.Session.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderInbox );\n  Outlook.MailItem mailItem = (Outlook.MailItem) outlookNS.GetItemFromID( anEntryID, folder.StoreID );\n\n  // ... process the mail item\n}	0
25410768	25410677	Querying for nullable relationship set of two lists	var values = A.Concat(B)\n    .Select(record => record.Value)\n    .Distinct();\n\nvar query = from value in values\n    join a in A\n    on value equals a.Value\n    into aMatches\n    join b in B\n    on value equals b.Value\n    into bMatches\n    select Tuple.Create(aMatches.FirstOrDefault(), \n        bMatches.FirstOrDefault());	0
820476	820419	How to post params from javascript to asp.net?	document.miniform.parameter1.value = yourvalue1;\ndocument.miniform.parameter1.value = yourvalue2;\ndocument.miniform.submit();	0
17277634	17277553	Metro - Detecting if Location Services is enabled	Geolocator geo=new Geolocator();\nif(PositionStatus.Disabled.Equals(geo.LocationStatus))\n    //geolocalization disabled	0
13608672	13608545	how to crop an image	Rectangle cropRect = new Rectangle(...);\nBitmap src = Image.FromFile(fileName) as Bitmap;\nBitmap target = new Bitmap(cropRect.Width, cropRect.Height);\n\n using(Graphics g = Graphics.FromImage(target))\n {\n  g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), \n                cropRect,                        \n                GraphicsUnit.Pixel);\n }	0
11148942	11148534	EF 4.3.1 How to map a sub sub class with table per type	modelBuilder.Entity<Person>().ToTable("People");\nmodelBuilder.Entity<Employee>().ToTable("Employees");	0
28678277	28678137	.Net - I want to compare a value from a TextBox with Database values	SqlCommand cmd = new SqlCommand("Select COUNT(*) from Diagnosticos Where Diagnostico_Nome=@Diagnostico_Nome", db);\ncmd.Parameters.AddWithValue("@Diagnostico_Nome", (string)source);\nvar count = (int)cmd.ExecuteScalar();\n\nif (count > 0)\n    // This exists in the DB	0
1031144	1031103	Return Bitmap to Browser dynamically	using System.Drawing;\nusing System.Drawing.Imaging;\n\npublic class MyHandler : IHttpHandler {\n\n  public void ProcessRequest(HttpContext context) {\n\n    Image img = Crop(...); // this is your crop function\n\n    // set MIME type\n    context.Response.ContentType = "image/jpeg";\n\n    // write to response stream\n    img.Save(context.Response.OutputStream, ImageFormat.Jpeg);\n\n  }\n}	0
5652574	5652515	How can I pass addition local object variable to my event handler?	hyperlinkButton.Click += (sender, e) => HandleGraphic(graphic, sender, e);	0
27460011	27459109	How can I populate a datagridview from top to bottom, left to right?	foreach (DataGridViewRow row in DataGridView.Rows)\n        {\n            foreach (DataGridViewCell cell in row.Cells)\n            {\n                //cell.\n            }\n        }	0
2369831	2369786	Creating a Generic Dictionary From a Generic List	public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{\n}	0
7805968	7805483	Using a Object property as method argument	list.OrderBy(t => t.ColumnYouWantToSortBy)	0
24247376	24247324	Saving a generic list	var json = new JavaScriptSerializer().Serialize(thing);	0
23085132	23084279	XML Syntax Highlight for WPF C#	SyntaxHighlighting="XML"	0
28449548	28447272	[Solved]How to solve WPF Popup Notify in taskbar to rightbottom of the screen in c#?	nic.Icon = new Icon(@"PATH/TO/AN/ICON.ico");	0
541893	541732	How can I sort a List<T> when the user clicks on a table header?	var serviceCalls = sc.Service.GetOpenServiceCalls("").OrderBy(call => DataBinder.Eval(call, sortBy));\nreturn serviceCalls.ToPagedList(pageIndex, 2);	0
20590450	20590434	Using LINQ to remove items from a list that do not apear in another list	public class myItem\n{\n   public int id { get; set;}\n   public String Name { get; set;}\n}\n\nvoid Main()\n{\n    //My original List\n    List<myItem> masterList = new List<myItem>() { new myItem{ id = 1, Name = "item 1"},\n                                            new myItem{id = 2, Name = "item 2"},\n                                            new myItem{id = 3, Name = "item 3"},\n                                            new myItem{id = 4, Name = "item 4"}\n                                            };\n\n    //List of ids of items I want to KEEP in my original list\n    List<int> keepList = new List<int>() {2,3}; \n\n    // what you want\n    masterList = masterList.Where(i => keepList.Contains(i.id)).ToList();\n}	0
19759228	19758741	Catching ctrl+c event in console application (multi-threaded)	static ConsoleEventDelegate handler;\nprivate delegate bool ConsoleEventDelegate(int eventType);\n[DllImport("kernel32.dll", SetLastError = true)]\nprivate static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);\n\nprivate static MyExternalProcess p1;\n\npublic static void Main()\n{\n    Console.CancelKeyPress += delegate\n    {\n        killEveryoneOnExit();\n    };\n\n    handler = new ConsoleEventDelegate(ConsoleEventCallback);\n    SetConsoleCtrlHandler(handler, true);\n\n    p1 = new MyExternalProcess();\n    p1.startProcess();\n}\n\npublic static void killEveryoneOnExit()\n{\n    p1.kill();\n}\n\nstatic bool ConsoleEventCallback(int eventType)\n{\n    if (eventType == 2)\n    {\n        killEveryoneOnExit();\n    }\n    return false;\n}	0
19769690	19769584	Running a BackgroundWorker continuously	public Test()\n    {\n        this.InitializeComponent();\n        BackgroundWorker backgroundWorker = new BackgroundWorker\n            {\n                 WorkerReportsProgress = true,\n                WorkerSupportsCancellation = true\n            };\n        backgroundWorker.DoWork += BackgroundWorkerOnDoWork;\n        backgroundWorker.ProgressChanged += BackgroundWorkerOnProgressChanged;\n    }\n\n    private void BackgroundWorkerOnProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n        object userObject = e.UserState;\n        int percentage = e.ProgressPercentage;\n    }\n\n    private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs e)\n    {\n        BackgroundWorker worker = (BackgroundWorker) sender;\n        while (!worker.CancellationPending)\n        {\n            //Do your stuff here\n            worker.ReportProgress(0, "AN OBJECT TO PASS TO THE UI-THREAD");\n        }        \n    }	0
910318	910274	How to fetch an entity with its entity-properties in nhibernate?	IList<Survey> surveys = session.CreateCriteria(typeof(Survey))\n                        .SetFetchMode("SurveyPages", FetchMode.Eager)\n                        .List<Survey>();	0
9122047	9103239	RDO Outlook Redemption access mailbox from test server	using ExWs = Microsoft.Exchange.WebServices.Data; \n\n ExWs.ExchangeService service = new \n                   ExWs.ExchangeService(ExWs.ExchangeVersion.Exchange2007_SP1);\n                    service.Credentials = new   \n                   ExWs.WebCredentials("username", "password", "domain");\n                    service.AutodiscoverUrl("name@company.com");	0
14741355	14740657	jqgrid paging repeats the same rows	var viewData = phdetail.Skip(rows*(page-1)).Take(rows).Select((p, index) \n    => new TableRow {\n        id = index + 1,\n        cell = new List<string> {\n            p.PhoneNumber,  p.UpdateDate, p.UpdateTime\n        }\n    }).ToArray();	0
2370504	2370427	iTextSharp set document landscape (horizontal) A4	iTextSharp.text.Document doc;\n\n// ...initialize 'doc'...\n\n// Set the page size\ndoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());	0
20934212	20934193	Creating an error message that reports a crash from anywhere inside an C# application	class Program\n    {\n        static void Main(string[] args)\n        {\n            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;\n\n            var thr = new Thread(() =>\n            {\n                Thread.Sleep(1000);\n                throw new Exception("Custom exception from thread");\n            });\n            thr.Start();\n            thr.Join();\n\n            Console.WriteLine("Done");\n        }\n\n        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n        {\n            //Log information from e.ExceptionObject here\n        }\n    }	0
17970434	17970181	Multiple Bitwise Flag Combos	MyFlags value = MyFlags.Flag2 | MyFlags.Flag3;\n\nMyFlags item1 = MyFlags.Flag1;\nMyFlags item2 = MyFlags.Flag1 | MyFlags.Flag3;\nMyFlags item3 = MyFlags.Flag2 | MyFlags.Flag3;\n\nbool matchItem1 = (value & item1) > 0; //false\nbool matchItem2 = (value & item2) > 0; //true\nbool matchItem3 = (value & item3) > 0; //true\n\n[Flags]\nenum MyFlags\n{\n    Flag1 = 1,\n    Flag2 = 2,\n    Flag3 = 4\n}	0
17770677	17770667	How to select multiple fields (LINQ)	var a = DF_Utilities.\n    GetAvailableTasks(empnum, 1).\n    AsEnumerable().\n    Where(p => p.Field<int>("task_code") == int.Parse(drpTasks.SelectedValue)).\n    Select(p => new \n    {\n        candNum = p.Field<int>("cand_num"),\n        dataEntry = p.Field<int>("data_entry")\n    }).\n    First();	0
33121288	33109778	Lambda expression to loop through two concurrent dictionaries	var sb_eventdata = new Dictionary<string, string>{ {"a", "a"}, {"b", "b"}};\nvar final_data = new Dictionary<string, string>{{"a", "a"}, {"b", "b"}, {"c","c"}};\n\nvar result = \n    // first loop\n    sb_eventdata.Select(s => \n        // second loop\n        final_data.Where(f => s.Value.Equals(f.Value)))\n    // flatten results (returns results from the first dictionary)\n    .SelectMany(x => x);	0
3329078	3328997	Converting a byte array to an array of primitive types with unknown type in C#	byte[] byteData = new byte[] { 0xa0, 0x14, 0x72, 0xbf, 0x72, 0x3c, 0x21 };\nType[] types = new Type[] { typeof(int), typeof(short), typeof(sbyte) };\n\nobject[] result = new object[types.Length];\nunsafe\n{\n    fixed (byte* p = byteData)\n    {\n        var localPtr = p;\n        for (int i = 0; i < types.Length; i++)\n        {\n            result[i] = Marshal.PtrToStructure((IntPtr)localPtr, types[i]);\n            localPtr += Marshal.SizeOf(types[i]);\n        }\n    }\n}	0
30718984	30718861	Selenium C#: Store element's position on graph as a variable	string position = circle.GetAttribute("cy");	0
8173471	8173410	attach word document from folder, c# mail message	string path = HttpContext.Current.Server.MapPath(@"Docs\" + companyName + ".doc");\nAttachment attachment = new Attachment(path);\nmsg.Attachments.Add(attachment);	0
1363302	1357612	How to get list of views from "mail" in Lotus Notes using .NET?	Object[] docColl = _notesDatabase.Views as Object[];\n\nforeach (Object objView in docColl) {  \n   NotesView view = objView as NotesView;\n   MessageBox.Show(view.Name);    \n}	0
20959325	20958020	Escape button on C# console application	public static void Main() \n{\n    ConsoleKeyInfo cki;\n\n    Console.WriteLine("Press the Escape (Esc) key to quit: \n");\n    do \n    {\n        cki = Console.ReadKey();\n        // do something with each key press until escape key is pressed\n    } while (cki.Key != ConsoleKey.Escape);\n}	0
7278044	7267961	HTML Agilty for WP7 - Silverlight c#	var flightTableCell =\n    doc.DocumentNode\n        .Descendants("div")\n        .FirstOrDefault(x => x.Id == "FlightInfo_FlightInfoUpdatePanel")\n        .Element("table")\n        .Element("tbody")\n        .Elements("td")\n        .FirstOrDefault(x => x.Attributes.Contains("flight"));\n\nvar value = flightTableCell.InnerText;  \nthis.textBlock1.Text = value;	0
28450769	28437348	Add Subprotocol to websocket (c#, Universal App)	var protocollist = messageWebSocket.Control.SupportedProtocols;\n   protocollist.Add("subprotocol");	0
14976428	14976155	Using SetParent freeze the parent window	Thread thread = new Thread( () =>\n{\n     var formCover = new FormCover();\n     Application.Run(formCover);\n});\nthread.ApartmentState = ApartmentState.STA;\nthread.Start();	0
30244955	30242941	How to retrieve data from an html string from a span tag by using Regular Expressions?	"<span class=\"type\">(?<Content>([^<]*))</span>"	0
21042341	21042190	Creating a new ObservableCollection using a collection of classes	var myData = myData2.Select(data2 => new MyData() { Data2 = data2 });\nvar collection = new ObservableCollection<MyData>(myData);	0
7326887	7326755	c# Try Statement issue converting from VB	for (y = 0; y <= oAddresses.address[x].LABEL.item.Length; y++)	0
31314946	31313358	Get HTML from Outlook's message editor - ControlType.Document	Outlook.MailItemClass mItem = (Outlook.MailItemClass)doc.MailEnvelope.Item;\nmItem.Subject = strSubject;\nmItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;\nmItem.HTMLBody = GetString(strBody);	0
5619330	5619290	Web user control set default value	private string _Text = "abc";\n\npublic string Text\n{\n   get { return _Text; }\n   set { _Text = value; }\n}	0
18915126	18915032	Linq: Get rows where values exists in another table	from ta in _db.TableA\nfrom t in _db.TableB on new {a=ta.ColA,b=ta.ColB} equals new{a= t.ColA,b=t.ColB} \ninto tc from tb in tc\nwhere ta.IsSelectable == true\nselect ta;	0
27315652	27313692	How to Send Multiple Email Addresses with Names in C#	// define the body of your mail\nvar message = new MailMessage\n{\n    From = new MailAddress("foo@gmail.com", "John Doe"),\n    Subject = "Please don't spam me",\n    Body = "I will be very angry if you send me spam."\n};\n\n// if you don't use gmail, then you have to specify your own settings!!!\nvar client = new SmtpClient("smtp.gmail.com", 587)\n{\n    EnableSsl = true,\n    Credentials = new NetworkCredential("foo@gmail.com", "superPassword")\n};\n\n// I skipped the creation of connection and command.\n// Don't forget to call Dispose when you finish to work with database.\nwhile (sdrReader.Read())\n{\n    var to = new MailAddress(sdrReader["EmailAddress"].ToString(),\n                             sdrReader["Name"].ToString());\n    message.To.Add(to);\n}\n\nclient.Send(message);	0
24791617	24791493	Restart a completed task	TaskStatus.RanToCompletion	0
26258529	26258280	Asp.Net MVC - returing pure ViewModel from controller action	public JsonResult GetProfileInformationViewModel(int id)\n{\n    var myProfile = GetProfile(id);\n    return new JsonResult(){ Data = myProfile };\n}	0
7551774	7551028	Windows explorer get list of selected items and pass it to another process	IContextMenu::QueryContextMenu	0
13859459	13859414	Return a File to download on LinkButton click	string pdfPath = MapPath("mypdf.pdf");\nResponse.ContentType = "Application/pdf";\nResponse.AppendHeader("content-disposition",\n        "attachment; filename=" + pdfPath );\nResponse.TransmitFile(pdfPath);\nResponse.End();	0
8996247	8995916	Subwords of a fibonacci word	//w denotes lookup word\nisSubWord(w){\n  i=0;\n  cnt=0;\n  while(i!=w.length){\n    if(f(i+cnt)==w(cnt)){\n      ++cnt;\n    }else{\n      cnt=0;\n      ++i;\n    }\n}	0
2329473	2002922	How do I copy a chart image to the clipboard using C#2010?	using (MemoryStream ms = new MemoryStream())\n{\n    chart1.SaveImage(ms, ChartImageFormat.Bmp);\n    Bitmap bm = new Bitmap(ms);\n    Clipboard.SetImage(bm);\n}	0
24453211	24430591	How to change the file extension of C# project output included in a VS Setup Project	public override void Install(IDictionary stateSaver)\n    {\n        base.Install(stateSaver);\n        var text = Context.Parameters["ScreensaverPath"];\n        var file = new FileInfo(text + "MyScreenSaver.exe");\n        if (!file.Exists)\n            return;\n        file.MoveTo(text + "MyScreenSaver.scr");\n    }\n\n    public override void Uninstall(IDictionary savedState)\n    {\n        base.Uninstall(savedState);\n        var text = Context.Parameters["ScreensaverPath"];\n        var file = new FileInfo(text + "MyScreenSaver.scr");\n        if (!file.Exists)\n            return;\n        file.MoveTo(text + "MyScreenSaver.exe");\n    }	0
7243544	7199194	How to open a picture in the viewer used by the content manager in windows mobile 6.5 using C#?	ProcessStartInfo psi = new ProcessStartInfo();\n        psi.FileName = @"\Windows\pimg.exe";\n        psi.Arguments = @"\My Documents\My Pictures\Flower.jpg";\n\n        Process.Start(psi);	0
27400502	27400250	How can I select from a SQL DB using linq and EF where ExpiryDate is 30 days to expire from today using DateDiff function	var expiryDate = DateTime.Today.AddDays(30);\nvar memberships = db.Membership.Where(m => m.ExpiryDate > expiryDate);	0
2158925	2158258	Create SqlXml object instead of string object	public static string SqlXmlFromZippedBytes(byte[] input)\n{\n    if (input == null){\n        return null;\n    }\n    using (MemoryStream inputStream = new MemoryStream(input))\n    using (DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress))\n    using (StreamReader reader = new StreamReader(gzip, System.Text.Encoding.UTF8))\n    {\n        return new SqlXml(reader); // From System.Data.SqlTypes\n    }\n}	0
4620162	4619716	how to run line by line in text file - on windows mobile?	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                    Console.WriteLine(line);\n                }\n            }	0
17008089	17008067	how to select elements that not intersec?	var result = listA.Except(listB); //maybe a .ToList() at the end,\n//or passing an IEqualityComparer<T> if you want a different equality comparison.	0
10330897	10330833	Simplified syntax to compare last element of list with element before that?	var count = list.Count; \n\nif(list[count - 1] != list[count - 2])\n{\n    //do something\n}	0
28998178	28913493	Sharepoint Client Object Model Updating Property of a only one folder	using (var ctx =  new ClientContext(webUri))\n{\n   var web = ctx.Web;\n\n   var folder = web.GetFolderByServerRelativeUrl("/site/Documents/folder/sub folder");\n   var listItem = folder.ListItemAllFields;\n   listItem["PropertyName"] = "PropertyValue";\n   listItem.Update();\n   ctx.ExecuteQuery();\n}	0
13496963	13496908	How to limit a for loop in C#	string star = "";\nfor (int i = 0; i < Model.orgInternalcontact.User.Password.Length && i < 15; i++)\n{\n     string mem = "*";\n     star = star + mem;\n}	0
8400659	8400177	XMLDataSource with filter binding to a DropDownList	/AddressTypes/AddressType[ @status = 'true' ]	0
8025740	8025717	How to save a Form using SaveFileDialog	public class Form1\n  {\n\n      private Bitmap objDrawingSurface;        \n      private Rectangle rectBounds1;\n\n      private void Button1_Click(object sender, System.EventArgs e) \n      {\n         objDrawingSurface = new Bitmap(this.Width, this.Height, Imaging.PixelFormat.Format24bppRgb);\n         rectBounds1 = new Rectangle(0, 0, this.Width, this.Height);\n         this.DrawToBitmap(objDrawingSurface, rectBounds1);\n         SaveFileDialog sfd = new SaveFileDialog();\n         sfd.Filter = "JPG Files (*.JPG) |*.JPG";\n        if ((sfd.ShowDialog == Windows.Forms.DialogResult.OK))\n        {\n            objDrawingSurface.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);\n        }\n     }\n  }	0
22862394	22853498	unable to update values in SQLite DB after importing- windows phone	int updateCount = dbConn.Execute("update resources SET isFavorite = 1,modifiedTime = DATETIME('now') WHERE resourceId =" + rid);	0
19517943	19517665	find total of matching category names	var categoryTotals = company.Saleses\n            .GroupBy (c => c.Category)\n            .Select (\n               g => \n                  new  \n                  {\n                     Category = g.Key, \n                     Total = g.Sum(s => s.Amount)\n                  }\n            );\n\nforeach(var categoryTotal in categoryTotals)\n{\n     Console.WriteLine(string.Format("Category: {0}, Total: {1}", \n         categoryTotal.Category, categoryTotal.Total.ToString()));\n}	0
1603822	1603700	XML Tags in asp:TextBox prevents other controls working?	ValidateRequest="false"	0
15636973	15636931	How to add the numbers stored in Label.Text	Label16.Text = (int.parse(Label7.Text)+int.parse(Label6.Text)).toString();	0
4563047	4563036	how to initialise a public property	public class Foo\n{\n    public Foo()\n    {\n        FromID = 1;\n    }\n\n    public int FromID { get; set; }\n}	0
18035631	18035579	How to open a link in webBrowser control in external browser?	public void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n{\n    //cancel the current event\n    e.Cancel = true;\n\n    //this opens the URL in the user's default browser\n    Process.Start(e.Url.ToString());\n}	0
17412783	17411972	How do I programatically change tab names in a WPF TabControl?	foreach(TabItem item in tabControl.Items)\n    item.Header = "blah";	0
9707976	9707724	Access<asp:FormView> field value from code behind.	var firstNameTextbox = FormViewId.FindControl("FirstName") as TextBox;\nstring myValue = firstNameTextbox.Text;	0
4457688	4457311	Creating JSON output file in C#	using System.Web.Script.Serialization; \n\npublic class Person\n{\n   public string firstName = "bp";\n   public string lastName = "581";\n}\n\npublic partial class MyPage : System.Web.UI.Page\n{\n   protected void Page_Load(object sender, EventArgs e) \n   { \n      Person p = new Person();\n      string output = JavaScriptObjectSerializer.Serialize(p);\n      Response.Write(output);\n      Response.Flush();\n      Response.End();\n   }          \n }	0
19379679	19376081	Best way to format randomly copied texts from other websites?	/( style=['"][^'"]*['"])/g	0
11353887	11353587	Textbox values into int array	int[] xMatrix = new int[6];\n    int[,] aMatrix = new int[6,6];\n\n    foreach (Control control in this.Controls) \n    { \n        if (control is TextBox) \n        { \n            string pos = control.Name.SubString(1);\n            if(control.Name.StartsWith("a"))\n            {\n                int matrixPos = Convert.ToInt32(pos) ;\n                int x = (matrixPos / 10) - 1;\n                int y = (matrixPos % 10) - 1;\n                aMatrix[x,y] = Convert.ToInt32(control.Text);\n            }\n            else if(control.Name.StartsWith("x")\n            {\n                int arrayPos = Convert.ToInt32(pos) - 1;\n                xMatrix[arrayPos] =  Convert.ToInt32(control.Text);\n            }\n        } \n    }	0
26215241	26215010	How do i use DirectoryInfo and FileInfo to get all files and add the sorted files to a List?	List<String> giffiles = Directory.GetFiles(radarImagesDirectory, "*.gif")\n                                     .Select(path => Path.GetFileName(path))\n                                     .ToList();\n\ntestfiles.AddRange(giffiles);\ntestfiles = testfiles.OrderBy(q => q).ToList();	0
8807692	8806623	InvalidOperationException when trying to delete a share	foreach(ManagementObject obj in result)\n  obj.InvokeMethod("Delete", new object[] { });	0
8001917	8001852	Removing associated entities from an EF entity	Employee\n{       \n    SomeOtherEntity SomeOtherEntityNavigation { get; set;}    \n    ICollection<Blah>  Blahs {get; set;}    \n}    \n\n//somewhere\nanEmployee.SomeOtherEntityNavigation = null;\nanEmployee.Blahs.Clear();	0
12491254	12490190	EF 5 + SQL CE 4: How to specify custom location for database file?	private MyApplicationDataContext()\n    { }\n\n    public static MyApplicationDataContext CreateInstance()\n    {\n        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n        var path = Path.Combine(directory, @"ApplicationName\MyDatabase.sdf");\n\n        // Set connection string\n        var connectionString = string.Format("Data Source={0}", path);\n        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", connectionString);\n\n        return new MyApplicationDataContext();\n    }	0
9763856	9763771	Populate an array with items from a List of objects using a loop	return products.Where(p => p.Type == theType).Select(p => p.ProductName).ToArray();	0
24894618	24894580	How do you perform an if then else statement as a concatenation?	string message = x == 1 ? "message1" : x == 2 ? "message2" : "message3"	0
15631398	15611326	How to simulate pressing f2 to make treeview node editable	public partial class Form1 : Form\n{\n    RadTreeView tree = new RadTreeView();\n\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.Controls.Add(tree);\n        tree.Size = new Size(500, 500);\n        tree.AllowEdit = true;\n\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        RadTreeNode newNode = new RadTreeNode();\n        newNode.Text = "new Cabinet";\n        tree.Nodes.Add(newNode);\n        newNode.BeginEdit();\n    }\n}	0
26144554	26144407	Order of sheets in Excel file while reading with GetOleDbSchemaTable	I am afraid that OLEDB does not preserve the sheet order as they were in Excel.	0
31398953	31398883	Return string when inside a while loop	public string functionname\n{\n    while(conditions)\n    {\n      //More Code\n      string X;\n      X = "string stuff";\n      return X;\n    }\n    return string.Empty;\n}	0
1888221	1888140	How can I tell if my controller action is being called from another controller action?	public class SomeController : Controller\n{\n    public ActionResult SomeAction()\n    {\n        // ... do stuff ...\n        TempData["SomeKey"] = "SomeController.SomeAction";\n        return RedirectToAction("SomeOtherAction", "SomeOtherController");\n    }\n}\n\npublic class SomeOtherController : Controller\n{\n    public ActionResult SomeOtherAction()\n    {\n        if (TempData.ContainsKey("SomeKey"))\n        {\n            // ... do stuff ...\n        }\n        // etc...\n    }\n}	0
10294417	10294222	Setting up Environment Variables in WCF	public static string Server {\n  get {\n#if DEBUG\n    return ConfigurationManager.AppSettings[key0];\n#else\n    return ConfigurationManager.AppSettings[key1];\n#endif\n  }\n}	0
32191358	32191146	How To Pass EF ObjectContext To Multiple Functions?	private void SaveEntity()\n{\n    using (var oContext = new MyEntities())\n    {\n        SaveEntityInfo(oContext);\n        SaveOwners(oContext);\n        SavePartners(oContext);\n        SaveOfficers(oContext);\n        SaveDirectors(oContext);\n        oContext.SaveChanges();\n    }\n}\n\n//One of multiple save methods\nprivate void SaveEntityInfo(MyEntities context)\n{\n    //Add something to context\n    //Remove something from context\n    //Update something in context\n    //But never use context.Save() here\n    //Let SaveChanges() only calls in your SaveEntity() method\n}	0
5348969	5348045	how to get parent repeater item from child repeater?	Protected Sub rptMaster_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptMaster.ItemDataBound\n    Dim drv As DataRowView = e.Item.DataItem\n    Dim rptChild As Repeater = CType(e.Item.FindControl("rptChild"), Repeater)\n    If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then\n            'Get TransactionID here from master repeater\n            Dim lblTransactionID  As Label = drv("TransactionID")\n            'bind child repeater here\n            rptChild.DataSource = GetData()\n            rptChild.DataBind()\n    End If\nEnd Sub	0
17453827	17442401	Bing maps animation translation	private void Pushpin_Click(object sender, TappedRoutedEventArgs e)\n{\n     var TappedPin = sender as Pushpin;\n     Location currentPinLocation = MapLayer.GetPosition(TappedPin);\n     Map.SetView(currentPinLocation);  \n}	0
4017372	4017348	Changing the 'Run As:' field for a scheduled task via C#	Process p = new Process();\np.StartInfo.UseShellExecute = false;\np.StartInfo.FileName = "SCHTASKS.exe";\np.StartInfo.RedirectStandardError = true;\np.StartInfo.CreateNoWindow = true;\np.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n\np.StartInfo.Arguments = String.Format(\n    "/Change /S {0} /TN {1} /RU {2}\\{3} /RP {4}",\n    MachineName,\n    ScheduledTaskName,\n    activeDirectoryDomainName,\n    userName,\n    password\n);\n\np.Start();\n// Read the error stream first and then wait.\nstring error = p.StandardError.ReadToEnd();\np.WaitForExit();\n\nif (!String.IsNullOrWhiteSpace(error))\n{\n    throw new Exception(error);\n}	0
23623958	23623820	How to Open database connection	using (var conn = new SqlConnection(@"Data Source=(LocalDb)\v11.0;AttachDBFilename='E:\TodayData\DatabaseLogin\LoginExample\LoginExample\App_Data\DatabaseLoginExample.mdf';Integrated Security=True"))	0
20133895	20116467	extract data from HTML snippet using Regex in .net language	((?<=href\=\").*?(?=\")|(?<=href\=\".*?\"\>).*?(?=\<)|(?<=\</.*?\>)[\s\S]*?(?=\<)|(?<=\<td\>).*?(?=</td\>))	0
10785880	10782818	How to add discussion board in page automatically in Sharepoint 2010?	using Microsoft.SharePoint;\nusing Microsoft.SharePoint.WebPartPages;\n\n// Get a reference to a web and a list\nSPSite site = new SPSite("http://localhost:8000");\nSPWeb web = site.OpenWeb();\nSPList list = web.Lists["Contacts"];\n\n// Instantiate the web part\nListViewWebPart wp = new ListViewWebPart();\nwp.ZoneID = "Left";\nwp.ListName = list.ID.ToString("B").ToUpper();\nwp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();\n\n// Get the web part collection\nSPWebPartCollection coll = \n    web.GetWebPartCollection("default.aspx", \n    Storage.Shared);\n\n// Add the web part\ncoll.Add(wp);	0
588839	588774	How can you remove duplicate characters in a string?	public static string RemoveDuplicates(string input)\n{\n    return new string(input.ToCharArray().Distinct().ToArray());\n}	0
24733699	24733120	AspNetMx Emaild Validation with c# asp.net	MXValidate mx = new MXValidate();\n\nstring email = "test@hotmail.com";\nMXValidateLevel level = mx.Validate( email, MXValidateLevel.Mailbox );\n\nswitch( level )\n{\ncase MXValidateLevel.NotValid:\n//bad email address, remove from email address list\nbreak;\n\ncase MXValidateLevel.Syntax:\n//the email address is syntactically correct\nbreak;\n\ncase MXValidateLevel.MXRecords:\n//mx records were found, but for some reason\n//the SMTP server couldn't be found\n//save email for checking later, and see if SMTP servers fail again\nbreak;\n\ncase MXValidateLevel.SMTP:\n//able to connect to the mail server\n//but mail server said email address was bad\n//remove from list\nbreak;\n\n\ncase MXValidateLevel.Greylisted:\n//able to connect to the mail server\n//but mail server said email address was greylisted\n//for a later time.\n//try back later\nbreak;\n\ncase MXValidateLevel.Mailbox:\n//the email address validated to the mail box `enter code here`level\n//and the mail server will accept email for that address\nbreak;\n}	0
4721525	4721436	Binding XML to Combobox	comboBox1.DataSource = obj.Descendants("manager").Select(x => new\n {\n   ManagerDesig = x.Attribute("name").Value,\n   ManagerID = x.Attribute("id").Value\n })\n.ToList();//convert to list	0
25086635	25086614	How do you derive from an Abstract Class having overloaded Constructors	public class B : A\n{\n    public B(int x, int y) : base(x , y) {}    \n    public B(int x, int y, string z) : base(x, y, z) {}\n\n    public B() : base(0, 0, "Hello!") {}\n\n    public B(int x) : this(x, 10, "Chained to B") {}\n}	0
30036021	30035641	MailMessage email via text-message fails to send	SmtpClient smtpClient = new SmtpClient("smtp.verizon.net", 465);\n\n        MailMessage MyMailMessage = new MailMessage("from@verizon.com", "to@ymail.com",\n            "write your subject Here ", "Hi,This is the test message ");\n        MyMailMessage.IsBodyHtml = false;\n        NetworkCredential mailAuthentication = new NetworkCredential("your_email@verizon.com", "password");\n\n        mailClient.EnableSsl = true;\n        mailClient.UseDefaultCredentials = false;\n        mailClient.Credentials = mailAuthentication;\n        mailClient.Send(MyMailMessage);	0
2927637	2927618	LINQ Group By to project into a non-anonymous type?	var colorDistributionSql = \n    from product in ctx.Products\n    group product by product.Color\n    into productColors\n\n    select\n       new \n    {\n       Color = productColors.Key,\n       Count = productColors.Count()\n    };\n\nvar colorDistributionList = colorDistributionSql\n      .AsEnumerable()\n      .Select(x => new ProductColour(x.Color, x.Count))\n      .ToList();	0
17794817	17794712	Going back from signed hash with RSA SignHash	Console.WriteLine(whatever)	0
2899445	2897980	Implementing sub fields in a PropertyGrid	public Form1()\n{\n    InitializeComponent();\n\n    Person x = new Person();\n    propertyGrid1.SelectedObject = x;\n}\n\npublic class Person\n{\n    public string Caption { get; set; }\n\n    [TypeConverter(typeof(ExpandableObjectConverter))]\n    public class Name\n    {\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n\n        public override string ToString()\n        {\n            return LastName + ", " + FirstName;\n        }\n    }\n\n    private Name _name = new Name();\n\n    public Name testName\n    {\n        get { return _name; }\n    }\n}	0
22427369	22427346	Group By Totals	personList.GroupBy(x => x.Country.Name)\n           .Select(x => new { CountryName = x.Key, Count = x.Count() });	0
3275967	3215824	Missing extension methods in HtmlHelper using NHaml	//public HtmlHelper Html { get; protected set; } // line 42\npublic HtmlHelper<TModel> Html { get; protected set; }\n\n//Html = new HtmlHelper( viewContext, this ); // line 37\nHtml = new HtmlHelper<TModel>( viewContext, this );	0
3203760	2948786	Calling 32-bit unmanaged DLL files from C# randomly failing	private static void AddEnvironmentPaths(string[] paths)\n{\n    string path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;\n    path += ";" + string.Join(";", paths);\n\n    Environment.SetEnvironmentVariable("PATH", path);\n}	0
10025798	10024558	How to get files from multiple directories and displaying it in a datagridview?	List<string> s1 = System.IO.Directory.GetFiles(@"C:\Documents and Settings\Administrator\Desktop\FILE\7", "*.*").ToList<string>();\ns1.AddRange(System.IO.Directory.GetFiles(@"C:\Documents and Settings\Administrator\Desktop\FILE\9", "*.*").ToList<string>());	0
5750908	5750860	VS2010 to show summary info from parent interfaces/class in IntelliSense	IMyInterface instance = new MyClass();\ninstance.MyMethod(); // shows intellisense	0
3924454	3924257	How to display enum values in datagridview column	private void Transform(DataTable table)\n    {\n        table.Columns.Add("EnumValue", typeof(SomeEnum));\n        foreach (DataRow row in table.Rows)\n        {\n            int value = (int)row[1]; //int representation of enum\n            row[2] = (SomeEnum)value;\n        }\n    }	0
30258572	30258494	FieldBuilder - Ho do you set the default value?	.method public hidebysig specialname rtspecialname \n    instance void .ctor () cil managed \n{\n    // Method begins at RVA 0x2061\n    // Code size 15 (0xf)\n    .maxstack 8\n\n    IL_0000: ldarg.0\n    IL_0001: ldc.i4.s 64\n    IL_0003: stfld int32 DynamicType1::m_number	0
31459860	31459825	negation lambda expression in c#, NOT starWith	onelist = mylist.Where(x => !x.Cod.StartsWith("A"));	0
2159220	2158343	Need Help Accessing Properties in Enclosing Class from Sub Class	public class UserFluentInterface\n            {\n                private readonly User _User;\n                private readonly Membership _Membership;\n\n                public UserFluentInterface(User User, Membership membership)\n                {\n                    _User = User;\n                    _Membership = membership;\n                }\n            }	0
6210401	6210119	Disable viewstate for all Label controls in web.config?	public class MyLabel : System.Web.UI.WebControls\n{\n  Public MyLabel() \n  {  \n    EnableViewState = false;\n  }\n}	0
5801915	5793693	Fire an event when a div changes by a javascript in a webBrowser1 in a winforms	private void timer1_Tick(object sender, EventArgs e)\n    {\n        content = webBrowser1.Document.GetElementById("speed");\n        string x = content.OuterHtml;\n        if (x != CheckString)\n        {\n            timer1.Enabled = false;\n            MessageBox.Show(x);\n\n        }\n    }	0
7603636	7603603	Draw on the screen, C#	form.TopMost=true	0
26088859	26088000	Playing Audio Files with spaces in filename	string fileIn = @"c:\Wherever\Calvin Harris - Summer.mp3";        \n\nProcessStartInfo processStartInfo = new ProcessStartInfo()\n{\n    Arguments = String.Format("\"{0}\"", fileIn),\n    FileName = VLC_EXE_PATH\n};\n\nProcess.Start(processStartInfo);	0
25760030	25759810	How to add <list> class from data row with non define property name?	public T MapObjects<T, Y>(Y item)\n        {\n            T _item = Activator.CreateInstance<T>();\n\n            foreach (PropertyInfo propertyInfo in typeof(Y).GetProperties())\n            {\n\n                if (typeof(T).GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public) != null)\n                    typeof(T).GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public).SetValue(_item, propValue);\n            }\n\n            return _item;\n        }	0
13175000	13174617	Index was outside the bounds of the array while reading from excelsheet	If(!String.IsNullOrEmpty(a)){\n    If(Char.IsLetter(a[0])){\n          Label12.Text = "CAPITAL";\n          break;\n    }\n}	0
13991851	13991806	sql in for loop	command.CommandText = "INSERT INTO Configuration (id,A, B, C, D, E, F,G) VALUES (@id, @a, @b , @c, @d, @e, @f, @g)";\n\ncommand.Parameters.Clear();\ncommand.Parameters.AddWithValue("@id", currId);	0
29376751	29376665	Cannot convert from method group to System.Func<string>	return Task.Factory.StartNew(() => this.DownloadString("http://...."));	0
26967472	26967178	Set current PC date and Time as Default in RadDatePicker	myDatePicker.SelectedDate = DateTime.Now;	0
3125617	3125600	Replicate Memcached to multiple servers	private bool CheckForDuplicatesInCache(Message theMessage)\n    {\n        var cacheClient = MemcachedClient.GetInstance("IntegrationCache");\n        var cacheClient2 = MemcachedClient.GetInstance("IntegrationCache2");\n        var messageHash = theMessage.GetHashCode();\n        if (cacheClient.Get(messageHash.ToString()).IsNotNull())\n        {\n            IntegrationContext.WriteLog("Warning: This message is a duplicate. Will Not Process.");\n            return false;\n        }\n\n        if (cacheClient2.Get(messageHash.ToString()).IsNotNull())\n        {\n            IntegrationContext.WriteLog("Warning: This message is a duplicate. Will Not Process.");\n            return false;\n        }\n\n        cacheClient.Set(messageHash.ToString(), "nothing", new TimeSpan(2, 0, 0));\n        cacheClient2.Set(messageHash.ToString(), "nothing", new TimeSpan(2, 0, 0));\n        return true;\n    }	0
25741199	25637436	Multi attach files from DB row	foreach (DataRow DRA in DTBA.Rows)\n      {\n          message.Attachments.Add(AttachmentFile(2, DRA["FILENAME"].ToString().Trim(), 0, null));\n          RecordLine("DEBUG 3.1 - " + message.Attachments.Count.ToString());\n      }	0
19515470	19515369	Discrete Sum of Func(T, TResult) with lambda expression	public static double DiscreteSum(Func<double, double> F1, double t1, double t2)\n    {\n        double s = 0;\n        for(long i = (t1<t2)?t1:t2; i < (t1<t2)?t2:t1; i++)\n        {\n            s += F1(i);\n        }\n        return s;\n    }	0
26901260	26900875	Table per Hierarchy table mapping with both shared and unshared columns	modelBuilder.Entity<Document>().Map<Licence>(map =>\n{\n    map.Property(l => l.LicenceNumber).HasColumnName("Number");\n    map.Property(l => l.ExpiryDate).HasColumnName("ExpiryDate");\n});	0
8322312	8312257	Export DataGridView Data with Images into Excel, HTML, or Word with Proper Table Formatting	if (cell.Value.GetType() == typeof(Bitmap))\n{\n    // You have to get original bitmap path here\n    string imagString = "bitmap1.bmp";\n    Excel.Range oRange = (Excel.Range)xlWorkSheet.Cells[i + 1, j + 1]; \n    float Left =(float) ((double)oRange.Left);\n    float Top =(float) ((double)oRange.Top);\n    const float ImageSize=32;\n    xlWorkSheet1.Shapes.AddPicture(imagString, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);\n    oRange.RowHeight = ImageSize + 2;\n}\nelse\n{\n    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;\n}	0
20747935	20747909	Iterate for loop after user input	.ShowDialog()	0
18934331	18933751	Open a WPF from a click button in my Outlook addin	string myWpfAppPath = "C:\somepath\someapp.exe";\nSystem.Diagnostics.Process.Start(myWpfAppPath);	0
12832352	12832321	read xml root node into datagrid and write edits back to xml file	XmlDataDocument xmlDatadoc = new XmlDataDocument();\n    xmlDatadoc.DataSet.ReadXml("abcd.xml");\n\n    DataSet ds = new DataSet("abc");\n    ds = xmlDatadoc.DataSet;\n\n    dataGrid1.DataSource = ds.Tables[0];	0
15422851	15415642	Changing static value permanently	Settings.Default["StaticValue"] = "30";\nSettings.Default.Save();	0
2863807	2785376	How to enable design support in a custom control?	using System;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Windows.Forms.Design;   // Note: add reference required\n\nnamespace WindowsFormsApplication1 {\n    [Designer(typeof(MyDesigner))]   // Note: custom designer\n    public partial class UserControl1 : UserControl {\n        public UserControl1() {\n            InitializeComponent();\n        }\n\n        // Note: property added\n        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n        public ListView Employees { get { return listView1; } }\n    }\n\n    // Note: custom designer class added\n    class MyDesigner : ControlDesigner {\n        public override void Initialize(IComponent comp) {\n            base.Initialize(comp);\n            var uc = (UserControl1)comp;\n            EnableDesignMode(uc.Employees, "Employees");\n        }\n    }\n}	0
22230721	20427088	Sitemap doesn't show as xml	var sitemap = new XDocument(\n            new XDeclaration("1.0", "utf-8", "yes"),\n            new XProcessingInstruction("xml-stylesheet",\n                "type=\"text/xsl\" href=\"" + Url.AbsoluteAction("SitemapXsl", "Default") + "\""),\n            new XElement(ns + "urlset",\n                new XAttribute(XNamespace.Xmlns + "sitemap", ns),\n                new XAttribute(XNamespace.Xmlns + "xhtml", xhtml), \n                nodeList));\n\n        Response.AddHeader("X-Robots-Tag","noindex");\n        return Content(sitemap.Declaration+"\r\n"+sitemap, "text/xml");	0
26442102	26442047	How to replace text in a sentence but avoid certain words/letters?	modifiedSentence = new Regex(string.Join("|", fullName\n    .Split(' '))).Replace(sentence, fullName, 1);\nConsole.WriteLine(modifiedSentence);	0
3569120	3569102	Using Linq, Trying to Use OrderBy on Object's Children	IQueryable<AObject> aObj = query.OrderBy(aObject =>\n    aObject.Type==i ?\n    aObject.B.Cs.Max(c => c.Ds.Max(d => d.Foo)) : \n    aObject.E.Fs.Max(f => f.Bar)\n).Skip(offset).Take(limit).AsQueryable();	0
34094089	34090919	How do I charge a stored credit card with the payflow pro API?	"string authorizationRequest = "TRXTYPE=A&ORIGID=" + payPalCollection.Get("PNREF") + "&INVNUM=ORD123456&AMT=50&COMMENT1=My Product Sale&USER=<USER>&VENDOR=<VENDOR>&PARTNER=<PARTNER>&PWD=<PASSWORD>&VERBOSITY=HIGH"	0
12895702	12895583	ASP Validation kills postback	ValidatorEnable(object,true/false)	0
7832211	7832183	how to get key from value in hash table	Hashtable clientList = new Hashtable();\n\n        foreach (DictionaryEntry dictionaryEntry in clientList)\n        {\n            // work with value.\n            Debug.Print(dictionaryEntry.Value.ToString());\n\n            // work with key.\n            Debug.Print(dictionaryEntry.Key.ToString());\n        }	0
24101614	24101547	How to hide Windows Phone 8.1 StatusBar in only landscape orientation?	void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)\n{\n    // Get the new view state\n    string CurrentViewState = ApplicationView.GetForCurrentView().Orientation.ToString();\n    var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();\n\n    if (CurrentViewState == "Portrait")\n    {\n        bottombar.Visibility = Visibility.Visible;\n        ShowStatusBar();                      \n    }\n\n    if (CurrentViewState == "Landscape")\n    {\n        bottombar.Visibility = Visibility.Collapsed;\n        HideStatusBar();\n    }\n}\n\nprivate async void ShowStatusBar()\n{\n    var statusBar = StatusBar.GetForCurrentView();\n    await statusBar.ShowAsync();\n}\n\nprivate async void HideStatusBar()\n{\n    var statusBar = StatusBar.GetForCurrentView();\n    await statusBar.HideAsync();\n}	0
19077858	19077762	MVC4 return a stored proc output with linq to sql	int? success = null;\nContext.usp_UpdateValuesInTables(Convert.ToInt32(obj.SourceClientDropDown),ref success);\nvar successCode = success; //success is the returned result.	0
11949854	11851491	ListBox knows it is in some distant ScrollViewer?	public MainWindow()\n    {\n\n        InitializeComponent();\n\n    }\n\n    public void WindowLoaded(object sender, EventArgs e) \n    {\n        listbox = new ListBox { Margin = new Thickness(10.0), MinWidth = 400, MinHeight = 400 };\n        listbox.Items.Add(new string('c', 3000));\n\n        var sv = new ScrollViewer { HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto };\n        sv.Content = listbox; // remove for test\n\n        this.Width = 600;\n        this.Height = 400;\n        this.Content = sv;\n\n    }\n\n    protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)\n    {\n\n        base.OnRenderSizeChanged(sizeInfo);\n        if (listbox != null)\n            listbox.MaxWidth = this.RenderSize.Width - (int.Parse(listbox.Margin.Right.ToString()) * 4);\n\n    }	0
18559810	18559516	ScintillaNET in WPF XAML Issues	xmlns:scintilla="clr-namespace:ScintillaNET;assembly=ScintillaNET"	0
3465014	3464415	C# Lambda to VB.Net	Public Sub Run()\n    Dim mutex = New ManualResetEvent(False)\n    Do\n        mutex.Reset()\n        listener.BeginAcceptSocket(Function(ar) AnonymousMethod1(ar, mutex), Nothing)\n        mutex.WaitOne()\n    Loop\nEnd Sub\n\nPrivate Function AnonymousMethod1(ByVal ar As Object, ByVal mutex As ManualResetEvent) As Object\n    mutex.Set()\n    processor.ProcessConnection(listener.EndAcceptSocket(ar))\n    Return Nothing\nEnd Function	0
33683397	33683263	Retrieve collection of elements whose key is less than specified value in c#	var value = 42u; //your certain value\nforeach (var m in mensajesEnviados.Where(kvp => kvp.Key < value).Select(kvp => kvp.Value))\n{\n}	0
28831823	28831696	Characters comparison in a string then return an integer value and calculate the percentage	public static double Percentage(string str1, string str2) {\n    // Handling of empty strings. No divisions by zero here!\n    if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) {\n        return 0.0;\n    }\n\n    // str2 is contained in str1\n    if (str1.Contains(str2)) {\n        return 100.0 * str2.Length / str1.Length;\n    }\n\n    // str1 is contained in str2\n    if (str2.Contains(str1)) {\n        return 100.0 * str1.Length / str2.Length;\n    }\n\n    // No matching\n    return 0.0;\n}	0
957749	957742	How to detect if my program is running in Windows?	//Declare a static Mutex in the main form or class...\nprivate static Mutex _AppMutex = new Mutex(false, "MYAPP");\n\n// Check the mutex before starting up another possible instance\n[STAThread]\nstatic void Main(string[] args) \n{\n  if (MyForm._AppMutex.WaitOne(0, false))\n  {\n    Application.Run(new MyForm());\n  }\n  else\n  {\n    MessageBox.Show("Application Already Running");\n  }\n  Application.Exit();\n}	0
12392632	12392604	Unable to read from stream in C#	sw.AutoFlush = true;\nsw.Write("A test message");	0
13922460	13920571	How do I access parameters of my POST request within a controller	public class QueryClass \n{\npublic string query { get; set; }\n}\n\npublic ResponseModel messageProcessor(QueryClass query)\n{\n  ResponseModel model=DoStuff(query.query);\n  return model;\n}	0
14887843	14796234	Connecting to Google Analytics Reporting API	string username = "youremailuser@domain.com";\n    string pass = "yourpassword";\n    string gkey = "?key=YourAPIkEY";\n\n    string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;\n    string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;\n\n    AnalyticsService service = new AnalyticsService("WebApp");\n    service.setUserCredentials(username, pass);\n\n    DataQuery query1 = new DataQuery(dataFeedUrl);\n\n\n    query1.Ids = "ga:12345678";\n    query1.Metrics = "ga:visits";\n    query1.Sort = "ga:visits";\n\n    query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd"); \n    query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");\n    query1.StartIndex = 1;        \n\n    DataFeed dataFeedVisits = service.Query(query1);\n\n    foreach (DataEntry entry in dataFeedVisits.Entries)\n    {\n        string st = entry.Title.Text;\n        string ss = entry.Metrics[0].Value;\n        visits = ss;\n    }	0
4123661	4123055	Alternative method to maximising the Console Window - C#	static void Main(string[] args) {\n        Console.BufferWidth = 100;\n        Console.SetWindowSize(Console.BufferWidth, 25);\n        Console.ReadLine();\n    }	0
15406798	15406679	checking for null in lambda expression - linq	filteredPeople = unitOfWork.PeopleRepository.Get()\n                .Where(c => (IdSearchable\n                        && c.personID != null\n                        && c.personID.ToString().Contains(param.sSearch.ToLower()))\n                    || (surnameSearchable \n                        && c.Surname != null\n                        && c.Surname.ToLower().Contains(param.sSearch.ToLower()))\n                    || (firstNameSearchable \n                        && c.FirstName != null\n                        && c.FirstName.ToLower().Contains(param.sSearch.ToLower()))\n                    || (genderSearchable \n                        && c.Gender != null\n                        && c.Gender.ToLower().Contains(param.sSearch.ToLower())));	0
29357701	29357639	Add a counter to a sql table	SELECT\n    t1.Name, t1.NameID, COUNT(*) AS Quantity\nFROM\n    Table1 t1\n        INNER JOIN Table2 t2 ON t1.NameID = t2.NameID\nGROUP BY\n    t1.Name, t1.NameID	0
7285140	6444058	MSChart: How to group RangeBar data with text labels instead of indexes?	for (int i = 0; i < timeRanges.Count; i++)\n{\n    string theLabel = timeRanges[i].ItemLabel;\n    int pointIndex = connectedTimeRangeSeries.Points.AddXY(timeRanges[i].ItemId + 1,   timeRanges[i].StartConnectionTime, timeRanges[i].StopConnectionTime);\n    connectedTimeRangeSeries.Points[pointIndex].AxisLabel = theLabel;\n}	0
4376466	4376319	Using LINQ to SQL to query a word started with something within string	' return employees where family name starts with "joe"\nquery = From emp In db.Employees _\n        Where emp.LastName.Substring(emp.LastName.LastIndexOf(" ") + 1) _\n                          .StartsWith("joe") _\n        Select emp\n\n' return employees where middle name or family name starts with "joe"\nquery = From emp In db.Employees _\n        Where emp.LastName.StartsWith("joe") _\n            OrElse emp.LastName.Contains(" joe") _\n        Select emp	0
18772284	18771677	Inserting data into gridView without using SqlDataSource and DataBind from a Sql Table	public void GetRowHeaders(GridView gridViewSample)\n{\n    string commandstr = @"SELECT a.*, b.somecolumn FROM tablea as a inner join tableb as b on b.someid= a.someid WHERE ID!=0 ORDER BY ID";\n\n    SqlCommand rowHeaderCmd = new SqlCommand(commandstr, sqlcon);\n\n    sqlcon.Open();\n    DataTable dt = new DataTable();\n    SqlDataAdapter da = new SqlDataAdapter();\n\n    da.SelectCommand = rowHeaderCmd;\n    da.Fill(dt);\n\n    gridViewSample.DataSource = dt;\n    gridviewSample.DataBind();\n\n    sqlcon.Close();\n}	0
26570892	26570731	Display PDF in WPF WebBrowser	private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n    {\n        string url = e.Url.ToString();\n        if (url.StartsWith("res://ieframe.dll/navcancl.htm") && url.EndsWith("pdf"))\n        {\n            e.Cancel = true;\n            MessageBox.Show("Cannot open PDF!");\n        }\n    }	0
3902675	3883835	Verify that a base protected method is called with Moq 3.1	class ClassIWantToTestHarness : ClassIWantToTest {\n    public string Arg1 { get; set; }\n    public string Arg2 { get; set; }\n    public int CallCount { get; set; }\n\n    protected override void SomeMethodThatsAPainForUnitTesting(var1, var2) {\n        Arg1 = var1;\n        Arg2 = var2;\n            CallCount++;\n    }\n}\n\n[Test]\npublic void ClassIWantToTest_DoesWhatItsSupposedToDo() {\n    var harness = new ClassIWantToTestHarness();\n    harness.IWantToTestThisMethod();\n    Assert.AreEqual("Whatever", harness.Arg1);\n    Assert.AreEqual("It should be", harness.Arg2);\n    Assert.IsGreaterThan(0, harness.CallCount);\n}	0
6230244	6230143	C# Split Times into Hour Blocks	var hours = new List<DateTime>();\nhours.Add(clockin);\n\nvar next = new DateTime(clockin.Year, clockin.Month, clockin.Day,\n                        clockin.Hour, 0, 0, clockin.Kind);\n\nwhile ((next = next.AddHours(1)) < clockout)\n{\n    hours.Add(next);\n}\nhours.Add(clockout);	0
14912605	14912541	how can I set my app to run at startup,when I don't know the folder in which the app might be installed?	RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\nrk.SetValue(AppName, Application.ExecutablePath.ToString());	0
21201864	21201809	How to get rid of any program's output in terminal	Process.Start(new ProcessStartInfo(arr[pos]) { WindowStyle = ProcessWindowStyle.Hidden });	0
30151831	30147848	Using switch in Kendo Grid Client Template	# if (IFlowCode == 1) {# 'A' #} else if (IFlowCode == -1) {# 'b' #} else if (IFlowCode == 0) {# 'C' #}#");	0
12228028	12228009	How to Databind a CheckBox	gymCheckBox.DataBindings.Add(new Binding("Checked", bsRooms, "Gym"));	0
12327794	12327670	C# Console Program Won't Execute from Command Prompt	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(Process.GetCurrentProcess().MainWindowHandle);\n        Console.ReadKey();\n    }\n}	0
32026271	32025958	How to draw rectangle on picture box at mouse click coordinates	int mouseX, mouseY;\n\nprivate void pbImage_MouseDown(object sender, MouseEventArgs e)\n{\n  mouseX = e.X;\n  mouseY = e.Y;\n  pbImage.Refresh();\n}\n\nprivate void pbImage_Paint(object sender, PaintEventArgs e)\n{\n  //... your other stuff\n  Rectangle rect = new Rectangle(mouseX - 100, mouseY - 100, 200, 200);\n  e.Graphics.DrawRectangle(whitePen, rect);\n}	0
11908999	11908827	Don't know how to loop through (n) number of nested objects in C#	private static string DisplayCriteria(Criteria criteriaObject)\n        {\n            string criteria = "";\n            foreach(Criteria c in criteriaObject)\n            {\n                if (c.Criteria.Count() > 0)\n                {\n                    criteria += string.Format("({0}" + System.Environment.NewLine, c.Display);\n                    criteria += string.Format("{0})" + System.Environment.NewLine, DisplayCriteria(c.Criteria));\n                }\n                else\n                {\n                    criteria += string.Format("[{0}]" + System.Environment.NewLine, c.Display);\n                }\n            }\n            return criteria;\n        }\n\n        // your code  ...\n        DisplayCriteria(rule.SearchCriteria.Criteria);\n        // your code  ...	0
23800931	23800474	C# Console Application insert row in MySQL database	static void Main() \n{\n    string cs = @"server=localhost;userid=user12;\n        password=34klq*;database=mydb";\n\n    MySqlConnection conn = null;\n\n    try \n    {\n      conn = new MySqlConnection(cs);\n      conn.Open();\n\n      string stm = "SELECT VERSION()";   \n      MySqlCommand cmd = new MySqlCommand(stm, conn);\n      string version = Convert.ToString(cmd.ExecuteScalar());\n      Console.WriteLine("MySQL version : {0}", version);\n\n    } catch (MySqlException ex) \n    {\n      Console.WriteLine("Error: {0}",  ex.ToString());\n\n    } finally \n    {\n\n      if (conn != null) \n      {\n          conn.Close();\n      }\n\n    }\n}	0
14922989	14922722	How I can deserialize python pickles in C#?	import json, pickle\n\nwith open("data.pickle", "rb") as fpick:\n    with open("data.json", "w") as fjson:\n        json.dump(pickle.load(fpick), fjson)	0
17472945	17472250	Dynamic tabs @ runtime and creating controls in it	TabPage tp = new TabPage("New Tabl Page");\n\n        TextBox t = new TextBox(); \n        t.Left = 10;\n        t.Top = 10;\n        t.Visible = true;\n        t.Width = 100;\n\n        tp.Controls.Add(t);\n\n        tabControl1.TabPages.Add(tp);	0
32872350	32872196	Unity 2D Collision Detection	void OnCollisionEnter2D(Collision2D coll) \n{\n    Vector3 collPosition = coll.transform.position;\n\n    if(collPosition.y > transform.position.y)\n    {\n        Debug.Log("The object that hit me is above me!");\n    }\n    else\n    { \n        Debug.Log("The object that hit me is below me!");\n    }\n\n    if (collPosition.x > transform.position.x)\n    {\n        Debug.Log ("The object that hit me is to my right!");\n    } \n    else \n    {\n        Debug.Log("The object that hit me is to my left!");\n    }\n}	0
27696290	27696220	Passing a dbset as a parameter to a function	private static void SetEntityPropertiesRequired<TEntity>(DbModelBuilder modelBuilder)\n{\n    //set all decimal properties in Projection Entity to be Required\n    var decimalproperties = typeof (TEntity).GetProperties()\n    ...	0
24244196	24244147	How do I count each two lines in a string?	string[] lines = combindedString.Split(new string[] { "\n", "\r\n" },\n                     StringSplitOptions.RemoveEmptyEntries);\n\nvar result = new StringBuilder();\nfor (int i = 0; i < lines.Length; i++)\n{\n    if (i % 2 == 0 && i != 0)   // i != 0 to not get blank line at the beginning\n        result.AppendLine();\n    result.AppendLine(lines[i].Trim());\n}\ncombindedString = result.ToString();	0
9161919	9161841	Select joined tables in EF	dbContext.MerchantShop\n    .Where(s => s.Campaign.Any(c => c.CampaignID == campaignID));	0
33942963	33941522	C# Read a row in a file	//Load your files in a list of strings\nIList<string> lines = File.ReadLines("\path\to\your\file.txt");\n\n//Filter the list with only the pattern you want\nvar pattern = username + "[ ]{1,}" + password;\nRegex regex = new Regex(pattern);\nIList<string> results = lines.Where(x => regex.IsMatch(x)).ToList();	0
5283442	5283313	Path to an embedded resource file	//Get the assembly.\nSystem.Reflection.Assembly CurrAssembly = System.Reflection.Assembly.LoadFrom(System.Windows.Forms.Application.ExecutablePath);\n\n//Gets the image from Images Folder.\nSystem.IO.Stream stream = CurrAssembly.GetManifestResourceStream("ImageURL");\n\nif (null != stream)\n{\n    //Fetch image from stream.\n    MyShortcut.IconLocation = System.Drawing.Image.FromStream(stream);\n}	0
10890685	10879411	Monotouch binding syntax for blocks	delegate void CaptureCallback (UIImage processedImage, NSError);\n\n  [BaseType (typeof (GPUImageVideoCamera))]\n  interface GPUImageStillCamera {\n       [Export ("capturePhotoAsJPEGProcessedUpToFilter:withCompletionHandler:")]\n       void CapturePhotoAsJpeg (GPUImageoutput finalFilter, \n                                CaptureCallback completionCallback);\n  }	0
4238926	4238888	How do I parse an unusual date string	string date ="20101121"; // 2010-11-21\nstring time ="13:11:41"; //HH:mm:ss\n\nDateTime value;\n\nif (DateTime.TryParseExact(\n    date + time,\n    "yyyyMMddHH':'mm':'ss", \n    new CultureInfo("en-US"),\n    System.Globalization.DateTimeStyles.None,\n    out value))\n{\n    Console.Write(value.ToString());\n}\nelse\n{\n    Console.Write("Date parse failed!");\n}	0
21287586	21287519	Search for specific text in list string and return whole line	Entries.Where(e=>e.Contains("fox")).FirstOrDefault()	0
12495314	12495254	Convert a html file to PDF (with inline styles)	PdfConverter pdfConverter = new PdfConverter();\n            //pdfConverter.LicenseKey = "put your license key here";\n\n            pdfConverter.PdfDocumentOptions.EmbedFonts = false;\n            pdfConverter.PdfDocumentOptions.ShowFooter = false;\n            pdfConverter.PdfDocumentOptions.ShowHeader = false;\n            pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;\n            pdfConverter.ActiveXEnabled = true;\n            pdfConverter.AvoidImageBreak = true;\n            pdfConverter.NavigationTimeout = 2147483647;\n\n            pdfConverter.ScriptsEnabled = true;\n            pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true;\n            pdfConverter.SavePdfFromUrlToFile(html file path, output file path filepath);	0
18445666	18445541	How to get random time in certain time format	int startHour = 14;\nint endHour = 23;\nint allQuarters = Enumerable.Range(0, (endHour - startHour) * 4).Count();\nTimeSpan time = TimeSpan.FromMinutes(gen.Next(allQuarters) * 15);\nstart = start + TimeSpan.FromHours(startHour) + time;	0
3247315	3246902	Is it possible to insert large amount of data using linq-to-sql?	foreach(List<Order> orderbatch in orders.Batch(100))\n{\n  db.Orders.InsertOnSubmit(orderbatch); \n  db.SubmitChanges();   \n}\n\n\npublic static IEnumerable<List<T>> Batch<T>(this IEnumerable<T> source, int batchAmount)\n{\n  List<T> result = new List<T>();\n  foreach(T t in source)\n  {\n    result.Add(t);\n    if (result.Count == batchSize)\n    {\n      yield return result;\n      result = new List<T>();\n    }\n  }\n  if (result.Any())\n  {\n    yield return result;\n  }\n}	0
12224002	12223876	Regex to get the table with cell containing specific innerHTML	/<table[^>]*>(?:.(?!<\/table>))*<td[^>]*>(?:.(?!<\/td>))*THISISIMPORTANT.*?<\/td>.*?<\/table>/	0
28172699	28172248	Is possible to pass parameter in ajax request with dynamic parameter name in asp,net?	public BoundUrl Bind(RouteValueDictionary currentValues, RouteValueDictionary values, RouteValueDictionary defaultValues, RouteValueDictionary constraints)\n{\n    ...\n    foreach (KeyValuePair<string, object> keyValuePair in values)\n    {\n        if (ParsedRoute.IsRoutePartNonEmpty(keyValuePair.Value) && !acceptedValues.ContainsKey(keyValuePair.Key))\n      acceptedValues.Add(keyValuePair.Key, keyValuePair.Value);\n    }\n    foreach (KeyValuePair<string, object> keyValuePair in currentValues)\n    {\n        string key = keyValuePair.Key;\n        if (!acceptedValues.ContainsKey(key) && ParsedRoute.GetParameterSubsegment(this.PathSegments, key) == null)\n      acceptedValues.Add(key, keyValuePair.Value);\n    }\n    ...\n}	0
26734250	26731740	Why does XmlSerializer serialize an object to a file containing zeros instead of XML?	using (Stream file = new FileStream(settingTemp, FileMode.Create,\n                                   FileAccess.Write, FileShare.None,\n                                   0x1000, FileOptions.WriteThrough))\n{\n   using (StreamWriter sw = new StreamWriter(file))\n   {\n      ...\n   }\n}	0
19937659	19933249	Parsing json string that sometimes is an array	[DataMember(Name = "description"]\nprivate object _description;\n\npublic string Description\n{\n    get\n    {\n        if (_description != null)\n        {\n            if (_description is string)\n            {\n                // Do Nothing\n                // You can remove this, just putting this here to \n                //   show conditional is implicit\n            }\n            else if (_description is string[])\n            {\n                // Join string[] using '\n\n' as the connector\n                _description = string.Join("\n\n", (string[])_description);\n            }\n        }\n\n        return _description as string;\n    }\n}	0
14632858	14632804	In a for loop is it advisable to convert the constants again and again, rather than declaring another variable before the loop starts	// Why is this the wrong type in the first place?\nvar paymentPending = Convert.ToInt32(DomainConstants.PaymentPending); \n\nforeach(var domain in someDomains.Where(sd => sd.Value != paymentPending)\n{\n   // Do something with domain	0
11120213	11120148	How to insert a string with ( ' ) in to the sql database?	using (SqlCommand myCommand = new SqlCommand(\n    "INSERT INTO table (text1, text2) VALUES (@text1, @text2)")) {\n\n    myCommand.Parameters.AddWithValue("@text1", "mother's love");\n    myCommand.Parameters.AddWithValue("@text2", "father's love");\n    //...\n\n    myConnection.Open();\n    myCommand.ExecuteNonQuery();\n    //...\n}	0
2513584	2513039	Using javascript to open a popup window	function openWindow()\n{  \n   var email = document.getElementById('<%=txtEmail.ClientID%>').value;\n   window.open('CheckEmail.aspx?email=' + email + , 'Check Email','left=100,top=100,toolbar=no,scrollbars=yes,width=680,height=350');\n   return false;\n}	0
10208081	10204529	How to get a count in the foreign key item?	banks = from bank in banks\n        join bankBranche in m_banksRepository.BankBranches on bank.Id equals bankBranche.BankId\n        where bankBranche.CityId == filter.CityId\n        select bank;	0
24504991	24504765	Converting string to Percent with 2 decimal points	string value = "24.7%".Trim();\nValue = value.Replace("%", "");\ndecimal Value = decimal.Parse(value);\nstring decimalValue = Value.ToString("0.00");\nstring actualValue=decimalValue +"%";	0
8926497	8926400	Get CultureInfo object from country name or RegionInfo object	var cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures)\n                              .Where(c => c.Name.EndsWith("CH"));	0
13166487	13166443	How to delete every 2nd character in a string?	String input = "3030313535333635";\nString result = "";\nfor(int i = 1; i < 16; i +=2 )\n{\n    result += input[i];\n}	0
2698703	2698503	How to identify a particular entity's Session Factory with Fluent NHibernate and Multiple Databases	IClassMetadata metadata = sessionfactory.GetClassMetadata(boType);	0
1981854	1981841	C#: how to get an object by the name stored in String?	Type.GetField	0
32994504	32994113	How to distinguish query parameters from path parameters	return Request.CreateResponse(HttpStatusCode.OK);	0
21545735	21545650	Function to multiply array elements	static void  letsMult(int [] myArray)\n        {  \n            int output=1;\n\n            for (int a = 0; a < myArray.Length; a++ )\n            {\n                  output=output*myArray[a];\n                  Console.WriteLine(output);\n            }    \n        }	0
204777	204505	Preserving order with LINQ	private static IEnumerable<TSource> DistinctIterator<TSource>\n      (IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)\n    {\n        Set<TSource> set = new Set<TSource>(comparer);\n        foreach (TSource element in source)\n            if (set.Add(element)) yield return element;\n    }	0
2133007	2132745	Can you access 'Service Reference' Programmatically?	IVsWCFReferenceManager referenceManager = refMgrFactory.GetReferenceManager(hierarchy);\n\n IVsWCFReferenceGroupCollection referenceGroups = referenceManager.GetReferenceGroupCollection();	0
32865363	32865082	Using standard or custom date formats	Console.WriteLine(test.ToString("%d"));\nConsole.WriteLine(test.ToString(" d"));\nConsole.WriteLine(test.ToString("d "));	0
12232163	12231552	Localizing non-breaking space in Windows 8	var loader = new Windows.ApplicationModel.Resources.ResourceLoader();\nvar str = loader.GetString('Farewell');\nvar modstring = str.Replace("&#00a0", "\x00a0");\nmyControl.Text = modstring;	0
2400723	2400524	How to get all rows but specifc columns from a DataTable?	string[] selectedColumns = new[] { "ID", "LastName" };\n\nDataTable tableWithOnlySelectedColumns =\n    new DataView(table).ToTable(false, selectedColumns);	0
18681563	18678220	DataGridView: Copy Insert specific Column to another DGV	// create a new column named Amount in your dgv at specified index (index 0 in my case)\nint newColumnIndex = 0;\ndgv2.Columns.Insert(newColumnIndex , new DataGridViewTextBoxColumn { Name = "Amount" });\n// get an index of the Amount column in your other dgv\nvar index = dgv1.Columns["Amount"].Index;\n// copy all items from dgv1 in that column to new column in dgv2\nfor (int i = 0; i < dgv1.Rows.Count; i++)\n    dgv2.Rows[i].Cells[newColumnIndex].Value = dgv1.Rows[i].Cells[index].Value;	0
2291234	2291108	What's a useful pattern for waiting for all threads to finish?	class MyClass {\n    int workToComplete; // Total number of elements\n    ManualResetEvent mre; // For waiting\n\n    void StartThreads()\n    {\n        this.workToComplete = 100;\n        mre = new ManualResetEvent(false);\n\n        int total = workToComplete;\n        for(int i=0;i<total;++i)\n        {\n             Thread thread = new Thread( new ThreadStart(this.ThreadFunction) );\n             thread.Start(); // Kick off the thread\n        }\n\n        mre.WaitOne(); // Will block until all work is done\n    }\n\n    void ThreadFunction()\n    {\n        // Do your work\n\n        if (Interlocked.Decrement(ref this.workToComplete) == 0)\n            this.mre.Set(); // Allow the main thread to continue here...\n    }\n}	0
7885122	7849256	Add a DataGridViewRow to a BindingSource	((DataTable)(bs.DataSource)).Rows.Add(RowArray);	0
15168856	15167833	datagridview AutoResizeRow function but for a single row	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\ndataGridView1.Rows[e.RowIndex].Visible = false;\n}	0
8834008	8832878	Scale on decimal number with Entity Framework	x.Days1 = Convert.ToDecimal(x.Days1.ToString("n2"));	0
4543701	4543686	how to automatically escape the path	string s = s.Replace(@"\", @"\\");	0
2192414	2192335	Is there a Ruby equivalent for the typeof reserved word in C#?	s.is_a? Thing	0
23067197	23045839	c# copy html links from webbrowser and write it in textfile	public void grabLink()\n{\n    HtmlElementCollection links = webBrowser3.Document.Links ;\n\n    using (TextWriter tw = new StreamWriter("link.tnx"))\n    {\n        foreach (HtmlElement  link in links)\n        {\n            if (link.InnerHtml.Contains("Sign Up"))\n            {\n                tw.WriteLine(link.OuterHtml);\n            }\n        }\n    }\n}	0
7039435	7039403	How to redirect route outside of a ASP.NET MVC3 controller in custom attribute?	public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)\n    {\n        // Want to redirect to route here.\n        filterContext.Result = new RedirectToRouteResult("routename", routeValues)\n\n        base.OnAuthorization(filterContext);\n    }	0
21797379	21797260	How to check two conditions in an IF statement in windows phone 7 application using c#?	if ((name.Text == String.Empty) || (name.Text == "Name"))\n        {\n            MessageBox.Show("Please Enter the name");\n            name.Focus();\n            return false;\n        }	0
21537737	21537469	How to make LEFT JOIN in Lambda LINQ expressions	order.Items\n   .GroupJoin (\n      productNonCriticalityList, \n      i => i.ProductID, \n      p => p.ProductID, \n      (i, g) => \n         new  \n         {\n            i = i, \n            g = g\n         }\n   )\n   .SelectMany (\n      temp => temp.g.DefaultIfEmpty(), \n      (temp, p) => \n         new  \n         {\n            i = temp.i, \n            p = p\n         }\n   )	0
15276786	15244950	use subfolders in homegroup	List<string> fileTypeFilter = new List<string>();\nfileTypeFilter.Add(".jpg");\nfileTypeFilter.Add(".png");\nvar queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);\n\nvar query = KnownFolders.HomeGroup.CreateFileQueryWithOptions(queryOptions);\nIReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();\nStorageFile file = fileList.FirstOrDefault(x => x.Name == "123_123.jpg");	0
9132073	9132037	How to override or create custom behavior for brackets "[]" in c#?	public class MyType {\n  public string this[int index] {\n    get { \n      switch (index) {\n        case 1: return "hello";\n        case 2: return "world";\n        default: return "not found";\n      }\n    }\n    set { ... }\n  }\n}\n\nMyType t = ...;\nConsole.WriteLine(t[0]);  // hello\nConsole.WriteLine(t[1]);  // world	0
28283990	28283889	WebDriver C# - Selecting an item from a drop down list using partial text	selectList.FindElement(By.XPath(string.Format("./option[starts-with(text(), '{0}')]", "Firstname Lastname"))).Click();	0
9363344	9301337	Collecting a list of vendors	VendorCriteria x = new VendorCriteria();\nx.IsActive.EqualValue =true ;\nVendorSummary []=wsDynamicsGP.GetVendorList(x,context);	0
19617626	19617346	View a list of objects in a crystal report within razor application	rd.SetDataSource(model);	0
8599156	8599139	initializing variables in c#	public class MyClass { \n   private int TheID {get;set;} \n   private string TheString {get;set;}\n\n   public string DoSomething(string TheString)   {\n\n   }\n  }	0
19016108	8792120	How to determine if an assembly name matches a requested, partial assembly name	AssemblyName name = new AssemblyName( args.Name );\nforeach( Assembly pluginAssembly in LoadedPluginAssemblies ) {\n  if( AssemblyName.ReferenceMatchesDefinition( name, pluginAssembly.GetName() ) ) \n    return pluginAssembly;\n}	0
33773692	33768659	How to Load all the Objects in an Array List	// -1 Indicates that you should start at the end of the list\nint index = -1; \n\nprivate void loadButton_Click(object sender, EventArgs e)\n{\n    if (members != null && members.Count > 0) // Avoid accessing if list is empty or null\n    {\n        if (index == -1)\n            index = members.Count - 1;\n\n        firstNameTxt.Text = lstMembers[index].FirstName;\n        lastNameTxt.Text = lstMembers[index].LastName;\n        userNameTxt.Text = lstMembers[index].UserName;\n        passwordTxt.Text = lstMembers[index].Password;\n        confPassTxt.Text = lstMembers[index].ConfPassword;\n        majorBox.Text = lstMembers[index].Major;\n        specialtyBox.Text = lstMembers[index].Specialty;\n\n        if (index == 0) // Reached beginning of array\n            index = -1; // Indicate that next time the last element must be accessed\n        else\n            --index;\n    }\n}	0
5395933	5395908	How to pass multiple string values to a Button click event handler in C#	string s1 = ...;\nstring s2 = ...;\nbutton.Click += (sender, e) => { MyHandler(sender, e, s1, s2); };\n\nvoid MyHandler(object sender, EventArgs e, string s1, string s2) {\n  ...\n}	0
16710475	16709148	It is possible to clear connection pool using sqlcmd utility in C# console app when run multiple SQL queries?	SqlConnection.ClearAllPools();	0
8317334	8317104	BackgroundWorker to update GUI	BackgroundWorker.RunWorkerCompleted	0
13401347	13401297	Create a new record with Entity Framework	SaveChanges()	0
25050700	25024538	Ajax tabContainer using GridView inside panel, one button outside of the tabContainer	AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)TabConAddInfo;\n        int index = container.ActiveTabIndex;\n\n        if (index == 0)\n        {\n            addSplash();\n            lblMsgAdd.Text = "Added successfully";\n        }\n        else if (index == 1)\n        {\n            addMainCat();\n            lblMsgAdd.Text = "Added successfully";\n        }\n        else if (index == 2)\n        {\n            addSubCat();\n            lblMsgAdd.Text = "Added successfully";\n        }\n        else if (index == 3)\n        {\n            addBusinessContact();\n            lblMsgAdd.Text = "Added successfully";\n        }\n        else if (index == 4)\n        {\n            addPersonContact();\n            lblMsgAdd.Text = "Added successfully";\n        }	0
26411717	26410980	C# string multi-byte c++ , gif binary data convert to png or image	byte[] image_format = my6705B.ReadBytes();\nMemoryStream ms4 = new MemoryStream(image_format);\nImage image = Image.FromStream(ms4);\nimage.Save(@"C:\Users\Administrator\Desktop\imageTest.png");	0
1402632	1402622	String from byte array doesn't get trimmed in C#?	TrimEnd(new char[] { (char)0 });	0
29929102	29926920	How to solve multiple cascade paths with entity code first	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n\n    modelBuilder.Entity<Index>()\n        .HasRequired(index => index.MetaIndex)\n        .WithMany(metaIndex => metaIndex.Indices)\n        .HasForeignKey(index => index.MetaIndexID)\n        .WillCascadeOnDelete(false);\n\n    base.OnModelCreating(modelBuilder);\n}	0
6585269	6584474	How to create an XpsDocument from byte array?	public static XpsDocument OpenXpsDocument(string url)\n{\n    var webClient = new WebClient();\n    var data = webClient.DownloadData(url);\n    var package = System.IO.Packaging.Package.Open(new MemoryStream(data));\n    var xpsDocument = new XpsDocument(package, \n                                      CompressionOption.SuperFast, \n                                      url);\n    return xpsDocument;\n}	0
19874763	19874712	Alternative to for loop to populate ddl with static items	ddlGroups.Items.AddRange(Enumerable\n    .Range(0, 85)\n    .Select(i => new ListItem() { Text = "Group " + (i + 1)} );	0
11666366	11666198	Unable to add and save data to excel when excel sheet is opened	workbook.Save();\n        applicationClass.Quit();\n        while (Marshal.ReleaseComObject(usedRange) > 0) \n        {}\n        while (Marshal.ReleaseComObject(worksheet) > 0) \n        {}\n        while (Marshal.ReleaseComObject(workbook) > 0) \n        {}\n        while (Marshal.ReleaseComObject(applicationClass) > 0) \n        {}	0
27511964	27507706	How to find a JavaScript alert that is already open with WatiN	public partial class Form1 : Form\n{\n    //\n    // Your class properites/variables\n    //\n    AlertDialogHandler dialogHandler;\n\n\n    [DllImport("User32.dll")]\n    public static extern Int32 FindWindow(String lpClassName, String lpWindowName);\n\n    //\n    // Some methods/functions declarations\n    //\n\n    public void SomeInitMethod()\n    {\n          dialogHandler = new AlertDialogHandler()\n          browse.AddDialogHandler(dialogHandler);\n    }\n\n    public void SampleMethod()\n    {\n       IntPtr hwndTmp = (IntPtr)FindWindow("#32770", "Dialog Title");\n       WatiN.Core.Native.Windows.Window popUpDialog = new Window(hwndTmp);\n       dialogHandler.HandleDialog(popUpDialog);\n       //\n       // The line above will find the OK button for you and click on it, \n       // from here you continue with the rest of your code.\n\n    }\n\n}	0
4153163	4153122	How to search in data table using LINQ?	//dt is DataTable\ndt.PrimaryKey = new DataColumn[1] { dt.Columns[0] };  // set your primary key\nDataRow dRow = dt.Rows.Find(SearchTextbox.Text);\nif (dRow != null){\n     // you've found it\n}\nelse{\n    //sorry dude\n}	0
30708648	30707142	Replace foreach to make loop into queryable	var query = from deal in context.Dealers\n            where deal.ManufacturerId == manufacturerId\n            from bodyshop in deal.Bodyshops1\n            where bodyshop.Manufacturer2Bodyshop.Select(s => s.ManufacturerId).Contains(manufacturerId)\n            let stat = bodyshop.Manufacturer2Bodyshop.FirstOrDefault(x => x.ManufacturerId == manufacturerId)\n            orderby deal.Name\n            select new DealerReport\n            {\n                Dealer = deal.Name,\n                Bodyshop = bodyshop.Name,\n                StatusShort = stat != null ? stat.ComplianceStatus : 0, // or some other default\n            };\n\nreturn query;	0
9334322	9300964	C# void equivalent for template parameters	private class SoapTask : AsyncTask{}	0
10218579	10218336	Check if a key in WPF OnKeyUp event is a special character	KeysConverter kc = new KeysConverter();\nif (!Char.IsControl(Convert.ToChar(kc.ConvertToString(e.KeyCode))))\n{\n    ...\n}	0
33951819	33951630	Add Insert new row between two existing rows in bounded DataGridView in C#	int idx = DGMaratha.CurrentCell.RowIndex;\nvar table = (DataTable)DGMaratha.DataSource;\nvar row = table.NewRow();\ntable.Rows.InsertAt(row, idx);	0
4637655	4637611	Windows Phone 7- Set an Image source to a stream in memory	var bi = new BitmapImage();\nbi.SetSource(stream);\nmyImage.Source = bi;	0
9585714	9585625	Selecting an object from a listbox quickly	currImage = objWholeLibrary.FirstOrDefault(\n    img => Path.GetFileName(img.FileName).Equals(\n        lbxImageObjects.SelectedItem.ToString())\n    );\nUpdateDisplay();	0
14684355	14644342	Providing both WS/Rest endpoints for hosted services using WCFFacility	_container.Register(\n    Component\n    .For<ISomeService>()\n    .ImplementedBy<SomeService>()\n    .AsWcfService(new RestServiceModel().Hosted())\n    .AsWcfService(new DefaultServiceModel().Hosted()\n        .PublishMetadata(mex => mex.EnableHttpGet())\n        .AddEndpoints(\n            WcfEndpoint.ForContract<ISomeService>().BoundTo(new WSHttpBinding())\n        )\n    )\n);\n\nRouteTable.Routes.Add(new ServiceRoute("v1/rest", new WindsorServiceHostFactory<RestServiceModel>(_container.Kernel), typeof(ISomeService)));\nRouteTable.Routes.Add(new ServiceRoute("v1/ws", new WindsorServiceHostFactory<DefaultServiceModel>(_container.Kernel), typeof(ISomeService)));	0
4046220	4046082	nHibernate - Iterate properties of a class to generically add parameters for stored procedure	foreach (var prop in properties)\n    {\n        query.SetParameter(prop.Name, prop.GetValue(entity, null));\n    }	0
22425454	22424801	Thread with XmlDocument as parameter	XmlDocument xmlDoc = TestController.TestFilelocation4000;\nvar t = new Thread(() => sendController.SendData2(xmlDoc));\nt.Start();	0
17484173	17484144	C# Mysql Insert Data not work	"INSERT INTO mahasiswa (name,jurusan,mail) values ('{1}','{2}','{3}')", txtnama.Text, txtjurusan.Text, txtemail.Text)";	0
18230358	18229967	c# listbox multiselect, selectedItems winforms	var list  = customListBox1.SelectedItems.Cast<string>().ToList();\nvar result = list3.Where(Srodek => list.Any(x=>x == Srodek.Srodek.category1));	0
12842646	12842394	Get the contents of all elements with the same name using XML?	XDocument doc = XDocument.Load(file.FullName);\nvar strings = doc.Descendants("container").SelectMany(x => x.Descendants("text")).ToList();\nreturn strings.Join(" \n ");	0
14142986	14142692	how to parse this comma delimited string?	var str = "'2014' , '381' , '1' , 'Eastern 10' , 'Wes 10' , '1'";\nvar parts = str.Split(new string[] { " , " }, StringSplitOptions.None);\n\nparts[0] = String.Format("'{0}{1}'", parts[0].Replace("'", ""),\n                                     parts[1].Replace("'", ""));\nstr = String.Join(" , ", parts);	0
3832528	3832512	Catch block without arg	catch\n{ \n   connection.Close(); \n   return null; \n}	0
10896311	10896265	Storing a DataTable in a Flatfile	public static void DataTableToFile(string fileLoc, DataTable dt)\n{\n    StringBuilder str = new StringBuilder();\n\n    // get the column headers\n    str.Append(String.Join(",", dt.Columns.Cast<DataColumn>()\n                                      .Select(col => col.ColumnName)) + "\r\n");\n\n    // write the data here\n    dt.Rows.Cast<DataRow>().ToList()\n           .ForEach(row => str.Append(string.Join(",", row.ItemArray) + "\r\n"));\n\n    try\n    {\n        Write(fileLoc, str.ToString());\n    }\n    catch (Exception ex)\n    {\n        //ToDO:Add error logging\n    }\n}	0
3862577	3862489	Showing all HTTP data sent in C# using HttpWebRequest	resp.Headers.AllKeys	0
25327862	25327656	Convert Excel formula to C#	string A2 = "660013103525";\n\nint intA2, div, mod, output;\nif (!int.TryParse(A2.Substring(A2.Length - 8, 8), out intA2)) \n    throw new ArgumentOutOfRangeException("A2");\n\ndiv = intA2 / 65536;\nmod = intA2 % 65536;\noutput = 100000 * div + mod;\nMessageBox.Show(output.ToString());	0
6531882	6531814	How to count the number of updated row	OleDbCommand command = new OleDbCommand("UPDATE SomeTable SET SomeColumn='SomeValue'", SomeConnection);\nint updated_records_count = command.ExecuteNonQuery();	0
13590087	13590056	More concise RegEx?	[aA\d]\d{8}	0
15930140	10123143	ASP.NET MVC 3 - Dealing with Session variables	protected void Session_Start(object sender, EventArgs e)\n{\n    if (User.Identity.IsAuthenticated)\n    {\n        Session["Name"] = client.GetName(User.Identity.Name);   \n    }\n}	0
32327642	32326249	sending email more than once at a time	string email = row["Email"].ToString();\nif(String.IsNullOrEmpty(value) || value.Trim().Length == 0)\n{\n    continue;\n}	0
3788940	3788856	To get the Form from its Processhandle	Form.FromHandle	0
12534630	12531826	Delete row from asp gridview via a LinkButton	protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)\n{\n    GridView gv = (GridView)sender;\n    switch (e.CommandName)\n    {\n        case "delete":\n            {\n                    DataTable test = RetrieveData(0, 0); // this is a function I used to get a datatable\n                    test.Rows[0].Delete();\n                    test.AcceptChanges();\n                    TargetedSpView = test.DefaultView;\n                    TBDSPCGrid.DataSource = TargetedSpView;\n                    TBDSPCGrid.DataBind();\n            }\n            break;\n}\n}	0
10955650	10955517	Get Enum Value By Description	Rule f;\n        var type = typeof(Rule);\n        foreach (var field in type.GetFields())\n        {\n            var attribute = Attribute.GetCustomAttribute(field,\n                typeof(DescriptionAttribute)) as DescriptionAttribute;\n            if (attribute != null)\n            {\n                if (attribute.Description == "description"){\n                    f = (Rule)field.GetValue(null);\n                break;}\n            }\n            else\n            {\n                if (field.Name == "description"){\n                    f = (Rule)field.GetValue(null);\n                break;}\n            }\n        }	0
592970	592864	How to copy between generic declared types with value type constraints	private Ttgt MyMethod<Tsrc,Ttgt>(Tsrc sourceObject) \n    where Tsrc:struct where  Ttgt:struct    \n{    \n    Type targetType = typeof(Ttgt);\n    TypeConverter tc = TypeDescriptor.GetConverter(targetType);\n    Ttgt returnObject = (Ttgt)tc.ConvertTo(sourceObject, targetType);\n    return returnObject;    \n}	0
8569560	8569429	LINQ query over a list of Bool+String pairs. How to join strings without foreach?	string fpoint=query.Aggregate((c, c1) => c + System.Environment.NewLine+ c1 );	0
22967134	22966838	Hide header of a section	if(Length({reportfield})=0)then true	0
9802682	9772321	Tridion 2009 TBB: How do I determine if a Page is published to particular publication target?	IList<RepositoryLocalObject> rlos = structuregroup.GetItems(pageFilter);\nList<Page> pages = new List<Page>(rlos.Count);    \nforeach (RepositoryLocalObject o in rlos)\n{  \n    Page p = (Page) o;\n    bool isPublished = false;\n    ICollection<PublishInfo> publishInfo = PublishEngine.GetPublishInfo(p);\n    foreach (PublishInfo info in publishInfo)\n    {\n        if (info.Publication.Id.ItemId == p.Id.PublicationId)\n        {\n            isPublished = true;\n        }\n    }\n\n    if(p != null && isPublished)\n    {\n        pages.Add(p);\n    }\n}	0
8113302	8113085	How to forward SOAP request in ASP.NET on IIS6?	Context.Request.InputStream.CopyTo(newRequest.GetRequestStream());	0
28457906	28456850	Asp.net Validation. Only allow user to enter specific numbers in a text box	down vote favorite\n<asp:TextBox ID="Fund9"\n    runat="server"\n    Columns="4"\n    MaxLength="3" Value="" />\n<asp:RegularExpressionValidator ID="Fund9RegularExpressionValidator"\n    runat="server"\n    ValidationExpression="^(0|100)$"\n    ErrorMessage="Fund 9 must be 0 or 100" ControlToValidate="Fund9"\n    Text="Must be 100% if selected" Display="Dynamic" />\n<asp:Button runat="server" ID="SubmitButton" Text="Submit"\n    OnClick="SubmitButton_Click" />\n\n<%-- RequiredFieldValidator is optional --%>\n<asp:RequiredFieldValidator ControlToValidate="Fund9" Text="Required"\n    ErrorMessage="Required is required." runat="Server"\n    ID="Fund9RequiredFieldValidator" Display="Dynamic" />	0
19541617	19541410	Put multiple regular expression patterns into one pattern as attribute in C#	(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\p{Nd})	0
4925454	4923846	Fast casting in C# using BitConverter, can it be any faster?	byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 ,9,10,11,12,13,14,15,16};\n\n        fixed (byte* a2rr = &arr[0])\n        {\n\n            UInt64* uint64ptr = (UInt64*) a2rr;\n            Console.WriteLine("The value is {0:X2}", (*uint64ptr & 0x0000FFFFFFFFFFFF));\n            uint64ptr = (UInt64*) ((byte*) uint64ptr+6);\n            Console.WriteLine("The value is {0:X2}", (*uint64ptr & 0x0000FFFFFFFFFFFF));\n        }	0
22020636	21946322	Post will timeout for C# Console Application but not aspx page	wr.Close()	0
16297842	16297180	Reverse stack items in the listbox WP7	listBox1.Items.Insert(0, obj1);	0
16733602	16608133	At what point do the Input Parameters of a WCF Workflow Service get instantiated/set?	this.OperationHelper.PopulateInputs(this, requestContext.Inputs);	0
6927593	6927470	Best approach to get ipv4 last octet	Console.WriteLine(IPAddress.Parse("192.168.1.33").GetAddressBytes()[3]);	0
4340966	4340770	Choice of direction in c# streams	Stream.CopyTo()	0
268223	268084	Creating a constant Dictionary in C#	switch (myString)\n{\n   case "cat": return 0;\n   case "dog": return 1;\n   case "elephant": return 3;\n}	0
17648888	17648464	display the image from remote database in windows phone 8	BitmapImage image = new BitmapImage(new Uri(file, UriKind.Absolute));	0
24540289	24540234	Initialize Point Array from String	string s = "10,10;10,20;20,20;20,10;10,10";\nvar points = s.Split(';').Select(x=>x.Split(','))\n              .Select(y=>new Point(int.Parse(y[0]),int.Parse(y[1])))\n              .ToArray();	0
13608103	13606164	Reading XML file from specified starting position	int position = 1;\nvar contacts = xdoc\n    .Descendants("Contact")\n    .Select((x, index) => new { Contact = x, Index = index })\n    .Where(x => x.Index >= position)\n    .Select(x => x.Contact);	0
19631287	19521459	Web ActiveX in C# application	[DllImport("User32.dll")]\npublic static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\nFindWindow(null, /*Here the window name*/);	0
4065119	4065086	trying to play .wav file which is in Resources folder, its there but visual studio sais it isn't!	System.Media.SoundPlayer player = new System.Media.SoundPlayer();\n        player.Stream = Properties.Resources.test;\n        player.Play();	0
956287	956220	C# Console App - OO Math/Thought Problem	enum Marks { Open, Spare, Strike };	0
11500093	11500091	dynamic button inside dynamic literal control	child controls (like button, literal, etc.),	0
18471178	18471136	bad compile constant value on dictinary string values	private Dictionary<string, char> binaryCharacterTohex = new Dictionary<string, char>\n{\n    {"0000", '0'},\n    {"0001", '1'},\n    {"0010", '2'},\n    {"0011", '3'},\n    {"0100", '4'},\n    {"0101", '5'},\n    {"0110", '6'},\n    {"0111", '7'},\n    {"1000", '8'},\n    {"1001", '9'},\n    {"1010", 'a'},\n    {"1011", 'b'},\n    {"1100", 'c'},\n    {"1101", 'd'},\n    {"1110", 'e'},\n    {"1111", 'f'}\n};	0
31543213	31384811	change with of dropdown window in a telerik RadGridView comboboxcolumn	protected override void OnLoad(EventArgs e)\n    {\n        base.OnLoad(e);\n\n        radGridView1.CellEditorInitialized += RadGridView1_CellEditorInitialized;\n    }\n\n    private void RadGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e)\n    {\n        RadDropDownListEditor editor = e.ActiveEditor as RadDropDownListEditor;\n        if (editor != null)\n        {\n            RadDropDownListEditorElement ddlElement =(RadDropDownListEditorElement ) editor.EditorElement;\n            ddlElement.DropDownMinSize = new Size(200, 300);\n        }\n    }	0
24227006	24046648	How to pass Unity Container has constructor parameter to Constructor of Controller in Web API	_serviceinstance= _unityContainer.Resolve<I1>("Class1");	0
30451080	30256007	Unity3d 5 WavePro Dynamic MeshCollider	Mesh myMesh = this.GetComponent<MeshFilter>().mesh;\nDestroyImmediate(this.GetComponent<MeshCollider>());\nvar collider = this.AddComponent<MeshCollider>();\ncollider.sharedMesh = myMesh;	0
9582979	9582826	How to use auto indexing in ACCESS database using OleDb in C# with sql commands	"INSERT INTO Item " + \n"(item_name, creator_name publishing_name, item_type, genre, year_publication) " +\n"VALUES " + \n"(@item_name, @creator_name,@publishing_name,@item_type,@genre,@year_publication);";	0
25892239	25876890	Using FileHelpers to import Excel data using MVC 5	//test is a stream here that I get using reflection\nIExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(test);\n\nDataSet result = excelReader.AsDataSet();\n\nwhile(excelReader.Read())\n{\n    //process the file\n}\n\nexcelReader.Close();	0
23593534	23593459	Get a hold of the index in a for loop	for (int i = 0; i < Model.Albums.Count; i++)\n  {\n    @Html.ActionLink("Edit Record", "Edit", new {Id=i})\n  }	0
7832668	7832602	List array duplicates with count	Dictionary<string, int> counts = array.GroupBy(x => x)\n                                      .ToDictionary(g => g.Key,\n                                                    g => g.Count());	0
23580378	23580293	Event based programming, how to respond to instance which sent request	void SomeFunc(Action a)\n{\n  // your code\n  a.Invoke();\n}	0
3898047	3896444	Castle DynamicProxy Interface Proxy Generation	var container = new WindsorContainer();\ncontainer.Register(Component.For<DynamicImplementationInterceptor>());\ncontainer.Register(Component.For<ISomething>()\n    .Interceptors(InterceptorReference.ForType<DynamicImplementationInterceptor>()).First);	0
1140153	1140076	Want a drawn circle to follow my mouse in C#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Paint(object sender, PaintEventArgs e)\n    {\n        Point local = this.PointToClient(Cursor.Position);\n        e.Graphics.DrawEllipse(Pens.Red, local.X-25, local.Y-25, 20, 20);\n    }\n\n    private void Form1_MouseMove(object sender, MouseEventArgs e)\n    {\n        Invalidate();\n    }\n}	0
11953139	11952999	Bind data from column in DataGridView control to a .NET Chart control	Chart1.Series[0].Points.DataBindY((DataView)DataGridView1.DataSource, "SignalStength");	0
22296664	22296194	Using foreach with two types of conditions in c#	var lstCombined =\n    lstRoles\n     .Zip(lstFunctions, (role, function) => new {Role = role, Function = function}).ToList();\n\nint i = 1;\n\nforeach (var item in lstCombined)\n{\n    selectListRoles.Add(new SelectListItem\n                            {\n                                Text = item.Role,\n                                Value = item.Function,\n                                Selected = (i == 0)\n                            });\n\n    i++;\n}	0
23342101	23341136	How to format enum with flags attribute as hex value?	public static string GetDescription(EnumName value)\n{\n    var enumtotal = Enum.GetValues(typeof(EnumName)).Cast<int>().Aggregate((i1, i2) => i1 | i2); //this could be buffered for performance\n    if ((enumtotal | (int)value) == enumtotal)\n        return value.ToString();\n    return ((int)value).ToString("X8");\n}	0
27650379	27650323	Fast creation of 2D array from 1D array of objects	public byte[,] allBytes()\n    {\n        int size1 = this.frameListSize;\n        int size2 = this.ySize * this.xSize;\n        byte[,] output = new byte[size1, size2];\n        Parallel.For(0, size1, (y) =>\n        {\n            byte[] bits = this.frameList[y].getBytes();\n            System.Buffer.BlockCopy(bits, 0, output, 0 + size2 * y, bits.Length);\n        });\n        return output;\n    }	0
856918	856845	How To: Best way to draw table in console app (C#)	static int tableWidth = 77;\n\nstatic void PrintLine()\n{\n    Console.WriteLine(new string('-', tableWidth));\n}\n\nstatic void PrintRow(params string[] columns)\n{\n    int width = (tableWidth - columns.Length) / columns.Length;\n    string row = "|";\n\n    foreach (string column in columns)\n    {\n        row += AlignCentre(column, width) + "|";\n    }\n\n    Console.WriteLine(row);\n}\n\nstatic string AlignCentre(string text, int width)\n{\n    text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;\n\n    if (string.IsNullOrEmpty(text))\n    {\n        return new string(' ', width);\n    }\n    else\n    {\n        return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);\n    }\n}	0
16499633	16298480	Refreshing value in a bound ComboBoxCell	row.Cells["RefFieldName"].Value = refRow.Cells["FieldName"].Value;	0
29822852	29822391	How can I modify from C# the value of an element which is define in a XAML DataTemplate?	private void MyButton_OnClick(object sender, RoutedEventArgs e)\n{\n    var alphaDataTemplate = this.Resources["AlphaDataTemplate"] as DataTemplate;\n    var label = alphaDataTemplate.FindName("LabelInDataTemplate", MyContentPresenter) as Label;\n    label.Content = "It Works";\n}	0
24485072	24424854	Save two string array values into single table using foreach	string[] func= { };\n        string[] rol= { };\n\n\n        if (!string.IsNullOrEmpty(collection["Area"]))\n            func= collection["Area"].Split(',');\n\n        if (!string.IsNullOrEmpty(collection["Role"]))\n            roles= collection["Role"].Split(',');\n\n        var lstCombined = roles.Zip(func, (role, func) => new { Role = role, Function = func }).ToList();\n\n       foreach (var pf in lstCombined)\n        {     \n                    var cpf= new prefunc\n                    {\n                        CID= candidateId,\n                        FID= Convert.ToInt32(pf .Function),\n                        RID= Convert.ToInt32(pf .Role)\n\n                    };\n\n         }	0
19989236	19520045	Executing Stored Procedure with Entity Framework	IEnumerable<ReturnType> Results = null;\n\nusing (DbContext NewContext = new PrometheusEntities())\n{\n    Results = NewContext.Database.SqlQuery<ReturnType>(query, parameters).ToList();    \n}    \nreturn Results;	0
14954812	14953655	Casting an Array Object	Array numbers = Array.CreateInstance(typeof(int), 10);\nint index = 0;\nforeach (int x in numbers)\n{\n    numbers.SetValue(index * index, index);\n    index++;\n}\nArray numberClone = (Array)numbers.Clone();	0
7298605	7200823	Enrolling a Certificate in Microsoft Certification services for a User From Java Program	keytool -genkey -keystore server-keystore.jks -alias server_alias \\n        -dname "CN=hostnameofserver,OU=orgunit" \\n        -keyalg "RSA" -sigalg "SHA1withRSA" -keysize 2048 -validity 365\n\nkeytool -export -keystore server-keystore.jks -alias server_alias -file server.crt\n\nkeytool -import -keystore client-truststore.jks -file server.crt	0
30048026	30047945	Password validation	public bool IsPasswordValid(string password)\n{\n    return password.Length >= 8 &&\n           password.Length <= 15 &&\n           password.Any(char.IsDigit) &&\n           password.Any(char.IsLetter) &&\n           (password.Any(char.IsSymbol) || password.Any(char.IsPunctuation)) ;\n}	0
32889150	32885243	Compare title on item, if it exists I want to add a new file with eg. v2 at the end	private string AppendFileNumberIfExists(SPWeb rootWeb, SPFolder folder, string file)\n    {\n        if (rootWeb.GetFile(file).Exists) \n        {\n            string fileName = Path.GetFileNameWithoutExtension(file); // The file name with no extension. \n            int fileVersionNumber = 0;\n\n            do\n            {\n                var version = "_v";\n                fileVersionNumber += 1;\n                file = SPUrlUtility.CombineUrl(folder.Url, \n                            string.Format("{0}{1}{2}{3}", \n                                            fileName,\n                                            version,\n                                            fileVersionNumber,\n                                            ".csv" ));       \n            }\n            while (rootWeb.GetFile(file).Exists); // As long as the file name exists, keep looping. \n        }\n        return file;\n }	0
10537060	10522118	PowerPoint Programming: Issues while trying to access ruler margins	Sub Levels()\n  Dim oSh as Shape\n  Dim x As Long\n\n  Set oSh = ActiveWindow.Selection.ShapeRange(1)\n\n  With oSh.TextFrame2.Ruler\n    For x = 1 to .Count\n      Debug.Print .Levels(x).FirstMargin\n      Debug.Print .Levels(x).LeftMargin\n    Next\n  End With\n\nEnd Sub	0
15064428	15063818	Composing shared parts with different export names via static properties	[Export("Type A", typeof(IMyExport))]\n    public static IMyExport ExportA\n    {\n        get\n        {\n            return new MyExport();\n        }\n    }\n\n    [Export("Type B", typeof(IMyExport))]\n    public static IMyExport ExportB\n    {\n        get\n        {\n            return new MyExport();\n        }\n    }	0
14564355	14560068	sending a tile and toast notification through at the same time?	string notificationData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +\n        "<wp:Notification xmlns:wp=\"WPNotification\">" +\n        "<wp:Toast>" +\n        "<wp:Text1>WP8 TOAST</wp:Text1>" +\n        "<wp:Text2>" + TextBoxBackContent.Text + "</wp:Text2>" +\n        "</wp:Toast>" +\n        "<wp:Notification xmlns:wp=\"WPNotification\">" +\n            "<wp:Tile>" +\n              "<wp:BackgroundImage>" + TextBoxBackgroundImage.Text + "</wp:BackgroundImage>" +\n              "<wp:Count>" + TextBoxCount.Text + "</wp:Count>" +\n              "<wp:Title>" + TextBoxTitle.Text + "</wp:Title>" +\n              "<wp:BackBackgroundImage>" + TextBoxBackBackgroundImage.Text + "</wp:BackBackgroundImage>" +\n              "<wp:BackTitle>" + TextBoxBackTitle.Text + "</wp:BackTitle>" +\n              "<wp:BackContent>" + TextBoxBackContent.Text + "</wp:BackContent>" +\n           "</wp:Tile> " +\n        "</wp:Notification>";	0
17353541	17353146	How to create a C# Console App Grid that groups CSV Entries by Lattitude and Longitude?	private static double WeirdRounding(double n)\n{\n    int temp = (int)(Math.Round(n, 3) * 1000);\n    return temp % 2 == 0 ? (double)temp / 1000 : ((double)temp + 1) / 1000;\n}	0
12883183	12883173	How can I check to see if a C# string array contains a value	bool x = a.Contains("c");	0
24249379	24249335	How to find physical path inside of a C# .NET integration test at runtime?	var codebase = Assembly.GetExecutingAssembly().CodeBase;\nvar pathUrlToDllDirectory = Path.GetDirectoryName(codebase);\nvar pathToDllDirectory = new Uri(pathUrlToDllDirectory).LocalPath;	0
154496	153748	How to inject Javascript in WebBrowser control?	HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\nHtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\nIHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\nelement.text = "function sayHello() { alert('hello') }";\nhead.AppendChild(scriptEl);\nwebBrowser1.Document.InvokeScript("sayHello");	0
5954155	5953978	Waiting for event silence	AutoResetEvent resetTimer = new AutoResetEvent(false);\n\n        ...\n\n        private void TimerJob()\n        {\n            ...\n\n            // The thread will sleep and loop until \n            // 2 seconds elapse without directory changes \n            while (resetTimer.WaitOne(2000)) {}\n\n            ...\n        }\n\n        private void ResetTimer()\n        {\n            resetTimer.Set();\n        }	0
18856683	18856630	write and read from byte stream	new MemoryStream()	0
13871634	13871385	search files with date pattern names in c# based on date range	DateTime startDate = DateTime.Now;\n        DateTime endDate = DateTime.Now;\n\n        var myFiles = new DirectoryInfo(location).EnumerateFiles()\n            .Where(f => DateTime.Parse(System.IO.Path.GetFileNameWithoutExtension(f.Name).Replace("Prefix", "")) >= startDate\n            && DateTime.Parse(System.IO.Path.GetFileNameWithoutExtension(f.Name).Replace("Prefix", "")) <= endDate);	0
9239945	9239910	A performant way to read the last line of a file in C#	FileStream  fileStream = new FileStream(fileName, FileMode.Open)\n// Set the stream position to the end of the file.\nfileStream.Seek(0, SeekOrigin.End);	0
8079613	8079325	How to read HardDisk Temperature?	//S.M.A.R.T.  Temperature attritube\n\nconst byte TEMPERATURE_ATTRIBUTE = 194;\npublic List GetDriveTemp()\n{\n    List retval = new List();\n    try\n    {\n        ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData");\n                //loop through all the hard disks\n        foreach (ManagementObject queryObj in searcher.Get())\n        {\n            byte[] arrVendorSpecific = (byte[])queryObj.GetPropertyValue("VendorSpecific");\n            //Find the temperature attribute\n                        int tempIndex = Array.IndexOf(arrVendorSpecific, TEMPERATURE_ATTRIBUTE);\n            retval.Add(arrVendorSpecific[tempIndex + 5]);\n        }\n    }\n    catch (ManagementException err)\n    {\n        Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);\n    }\n    return retval;\n}	0
26381136	26381006	Run chrome in minimized mode	private const int SW_SHOWMINIMIZED = 2;\n\n[DllImport("user32.dll")]\nprivate static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);\n\nprivate void hideChrome()\n{\n    Process proc;\n    foreach (Process process in Process.GetProcesses())\n    {\n        if (process.ProcessName.Equals("chrome"))\n            proc = process;\n    }\n\n    IntPtr hWnd = proc.MainWindowHandle;\n    if (!hWnd.Equals(IntPtr.Zero))\n    {\n        ShowWindowAsync(hWnd, SW_SHOWMINIMIZED);\n    }\n}	0
23866677	23865511	contrast with color matrix	c = 1+ value;	0
4458259	4458210	Can't start powerpoint from start menu shortcut in c#	Process.Start(shortcutPath);	0
3517950	3517767	WinForms MouseEventHandler on listBox syntax	private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        //<============================================================================\n        //  Update image preview when file is selected from listBox1  \n        //<============================================================================\n\n        // BitmapImage.UriSource must be in a BeginInit/EndInit block\n        BitmapImage myBitmapImage = new BitmapImage();\n        string curItem = destinationFolder + "\\" + listBox1.SelectedItem.ToString();\n\n        myBitmapImage.BeginInit();\n        myBitmapImage.UriSource = new Uri(@curItem);\n        myBitmapImage.DecodePixelWidth = 200;\n        myBitmapImage.EndInit();\n        uploadImage.Source = myBitmapImage;\n    }	0
8099890	8099704	How is AttributeUsageAtribute implemented?	var attributes = typeof(A).GetCustomAttributes(A.GetDerivedFromAOnlyAttributeType(), false);\n// using an attribute outside the A class\n\nclass A {\n    protected class DerivedFromAOnlyAttribute : Attribute { }\n    public static Type GetDerivedFromAOnlyAttributeType() {\n        return typeof(DerivedFromAOnlyAttribute);\n    }\n}\n[A.DerivedFromAOnly] //ok\nclass B : A {\n}\n[A.DerivedFromAOnly] //error\nclass C { \n}	0
32523439	32456824	Failed to load resource (CSS,JS and picture files) after updating ASP.NET 5 from Beta6 to Beta7	public void Configure(IApplicationBuilder app)\n    {\n        app.UseMvc(routes =>\n                   {\n                       routes.MapRoute(\n                           name: "DefaultController",\n                           template: "{controller=Home}/{action=Index}/{id?}"\n                           );\n                   });\n\n        app.RunIISPipeline(); //New\n    }	0
11157248	11157136	Removing DIV from a text file if it contains a certain classname	XElement root = XElement.Load(file); // or .Parse(string);\nXElement div = root.XPathElement("//div[@class={0}]", "feedflare");\ndiv.Remove();\nroot.Save(file); // or string = root.ToString();	0
4291679	4291609	How to deal with dates in Linq Query?	var searchSchedules =\n    from searchSchedule in db.SearchSchedules\n    where searchSchedule.Active.Value &&\n            ((DateTime.UtcNow - searchSchedule.LastChecked.Value).Minutes >= searchSchedule.CheckFrequencyMinutes) &&\n          searchSchedule.PublishingConfigurationId == pubConfig.Id\n          select searchSchedule;	0
20032535	20031912	Getting multiply results via linq	var urls = (from item in youtube.Element("{http://www.w3.org/2005/Atom}feed").Descendants("{http://www.w3.org/2005/Atom}entry")\n                select new\n                {\n                    soundName = item.Element("{http://www.w3.org/2005/Atom}title").ToString(),\n                    url = item.Element("{http://www.w3.org/2005/Atom}id").ToString(),\n                });	0
12583286	12583030	reading File with FileStream	System.Windows.Forms.Application.StartupPath	0
2404661	2404629	get all the elements that have a particular element name	static void Main(string[] args)\n{\n    var g = XDocument.Parse("<nodes><skus><sku>abc</sku><sku>def123</sku></skus></nodes>");\n    var t = from e in g.Descendants("sku")\n    select e;\n}	0
27720616	27719380	extract specific data from HTML -CDATA- pattern in C#	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
\nstring a = "<![CDATA[<div><b>ID:</b> 40</div><div><b>Name:</b> John</div>]]>";
\ndoc.LoadHtml(Regex.Match(Regex.Match(a, @"\[([^)]*)\]").Groups[1].Value, @"\[([^)]*)\]").Groups[1].Value);
\nvar divs = doc.DocumentNode.SelectNodes("//div");
\nstring ID = divs[0].InnerText.Split(':')[1];
\nstring Name = divs[1].InnerText.Split(':')[1];	0
10442986	10442465	how to download file from webserver when url contains only file ID	public ActionResult clipstore(string id)\n    {\n        var path = GetFilePathByID(id);\n\n        StreamReader reader = new StreamReader(path);\n\n        var fileBytes = System.IO.File.ReadAllBytes(path);            \n\n        FileContentResult file = File(fileBytes, "image/png");\n\n        return file;\n    }	0
21146318	21146249	Parsing JSON using Newtonsoft.JSON	var resultsJSON = JsonConvert.DeserializeObject<List<AnnouncementListObject>>(json); //line1	0
6438868	6438697	log4net set from an external config file not working	log4net.Config.XmlConfigurator	0
3502412	3502360	how to do string manipulation in c#	string s = "Explosive;a dynamic person";\nvar separatorIndex = s.IndexOf(";");\nif (separatorIndex != -1 && separatorIndex < s.Length + 1)\n    s = s.Substring(0, separatorIndex + 1) + s.Substring(separatorIndex + 1, 1).ToUpper() + s.Substring(separatorIndex + 2);\n\nConsole.WriteLine(s);	0
33589598	33589499	Linq SQL datetime invocation error on app close	namespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n            this.FormClosing += formClosing;\n        }\n\n        private void formClosing(object sender, FormClosingEventArgs e)\n        {\n            comboBox1.SelectedIndexChanged -= comboBox1SelectedIndexChanged;\n        }\n\n        private void comboBox1SelectedIndexChanged(object sender, EventArgs e)\n        {\n            // your code\n        }\n    }\n}	0
33009020	33008731	Building dynamic Regex in C#	var escapedSymbol = Regex.Escape(symbol);\nRegex regex = new Regex(@"(^" + "/(" + escapedSymbol  + @" \(\d+\)$)|" + escapedSymbol );	0
27984449	27983749	Convert Isolated PDF File to HEX String in Silverlight Windows Phone 8.1	StorageFolder sFolder = Windows.Storage.ApplicationData.Current.LocalFolder;\nStorageFile sFile = await sFolder.GetFileAsync("PDF.pdf");\nvar sFileOut = await sFile.OpenReadAsync();\nStream sFileOutStream = sFileOut.AsStream();\nMemoryStream ms = new MemoryStream();\nawait sFileOutStream.CopyToAsync(ms);\nbyte[] sFileOutStreamByte = ms.ToArray();\nstring hexString = BitConverter.ToString(sFileOutStreamByte);	0
26659288	26645110	Save PDF to file	//We need a StorageFile to save into.\nStorageFile saveFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("safedPdf.png",CreationCollisionOption.GenerateUniqueName);\n\nusing (var saveStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))\n{\n    await page.RenderToStreamAsync(saveStream);\n}	0
20267886	20267755	how to get aiff file bit rate c#	var bitRate = ddf.WaveFormat.AverageBytesPerSecond * 8;	0
20086607	20086486	Store methods in arrays	Action[] actions = new Action[2]; // create an array of actions, with 1 action for each button\nactions[0] = start;\nactions[1] = options;\n\n...\n\nfor(var i = 0; i < buttons.Length; i++)\n{\n    if(buttons[i].isClicked)\n        actions[i]();\n}	0
9465775	9465661	Local variables in Runtime Compiled Expressions	foreach (var childt in itemt.ItemTemplates)\n{                 \n       var naam = childt.Naam;\n       columns.Add(new ColumnInfo<Item>(model => \n             level(model).GetV(naam, model.Taal) + naam,\n             naam,\n             new TextPropertyRenderer(), \n             editable));\n\n}	0
26155672	26141176	How to get the text out from a dynamically added textbox in asp.net?	Table[] T = new Table[] { Table1, Table2, Table3, Table4, Table5, Table6, Table7, Table8, Table9, Table10 };\n        foreach (Table t in T)\n        {\n            t.Visible = false;\n        }\n        for (int i = 0; i < ddlServer.SelectedIndex; i++)\n        {\n            T[i].Visible = true;\n        }	0
6664584	6664562	Removing all but one item from Controls	for(int i = this.Controls.Count - 1; i >= 0; i--)\n{\n    if (this.Controls[i] is Label && this.Controls[i].ID != "error")\n    {\n        this.Controls.Remove(this.Controls[i]);\n    }\n}	0
11184742	11184718	How to get TimeSpan from DateTime	TimeSpan timeOfDay = startTime.TimeOfDay;\nDateTime fullStartDateTime = startDate.Add(timeOfDay);	0
3072728	3072704	Regex group capturing problem	(?<front>.*<img.*src="http://images.domain.com/Images/)(?<imgName>[^"]*)"(?<end>.*)	0
24908328	24899948	Netstat focus on (find port)	var ip =  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();\n\nforeach(var tcp in ip.GetActiveTcpConnections())\n{\n        if (tcp.LocalEndPoint.Port == number \n         || tcp.RemoteEndPoint.Port == number)\n        {\n           Logs.Write(\n                String.Format(\n                   "{0} : {1}", \n                   tcp.LocalEndPoint.Address, \n                   tcp.RemoteEndPoint.Address));\n        }\n}	0
8803738	8803689	Find a specific string within another string without getting similar results	\\par\b	0
26021564	25708896	How to define the Window Class Name for a C# Windows Form?	private string GetFullClassName(string className)	0
26023497	26023453	Formatting data in a textbox in C#	string.Format("{0:00.00}", ddlCIT.SelectedValue);	0
17191734	17190794	remove item from 2 dimensional Array XNA?	List<Bricks> bricks;\n\npublic void loadBricks(Texture2D b, int x, int y)\n{\n    bricks = new List<Bricks>();\n    for(int i = 0; i < (x * y); i++)\n        bricks.Add(new Brick(b, new Rectangle(b.Width * i / x, b.Height * (i % y), b.Width - 2, b.Height), i % y));\n}	0
16577299	16577194	HOW TO: Insert checked checkboxes into mysql using C#	(CheckBox.Checked).ToString()	0
2910092	2910048	Drop Item into Specific Index in ListView in WPF C#	ObservableCollection<FileInfo>	0
16582745	16581462	How to create object more than once with dependency injection	public class DetailFrm\n{\n    private readonly Func<ListFrm> _listFrmInstance;\n\n    public DetailFrm(Func<ListFrm> listFrmInstance)\n    {\n        _listFrmInstance = listFrmInstance;\n    }\n\n    private SelectButton OnClick(object sender, EventArgs e)\n    {\n        using(var listFrm = _listFrmInstance())\n        {\n            listFrm.ShowDialog();\n\n            // Do detail data filling here\n        }\n    }\n}	0
32715216	32709383	How to draw in Windows Phone 8.1 on WriteableBitmap?	using (writeableBmp.GetBitmapContext()) \n{\n   writeableBmp.Clear();\n   writeableBmp.DrawLine(0, 0, (int)pnt.X, (int)pnt.Y, Colors.White);   \n} // Invalidates on exit of using block	0
25266998	25266533	How would you write a method that takes a parameter like [ModelBinder(typeof(GeoPointModelBinder))] GeoPoint location	using System;\nusing System.Reflection;\n\nnamespace Test081204\n{\n    [AttributeUsage(AttributeTargets.Parameter)]\n    public class SomeCoolAttribute : System.Attribute\n    {\n        public readonly int Val;\n\n        public SomeCoolAttribute(int val)\n        {\n            Val = val;\n        }\n    }\n\n    class Test\n    {\n        public void Run([SomeCool(123)] string value)\n        {\n            // Prints "In Run: test123"\n            Console.WriteLine("In Run: " + value);\n        }\n    }\n\n    class Program\n    {\n        public static void Main()\n        {\n            var parameters = typeof(Test).GetMethod("Run").GetParameters();\n            var attr = parameters[0].GetCustomAttribute(typeof(SomeCoolAttribute)) as SomeCoolAttribute;\n\n            // Prints "123"\n            Console.WriteLine("In Main: " + attr.Val);\n\n            new Test().Run("test" + attr.Val.ToString());\n        }\n    }\n}	0
5613561	5613497	a little help instancing a wcf object, events don't work	ServerClass myServer = new ServerClass();	0
20923249	20922659	nested gridview row values	GridView Gridview2 = (GridView)GridView1.Rows[1].FindControl("GridView2");	0
734031	734005	Is it possible to Shut down a 'remote PC' programatically through .net application?	System.Diagnostics.Process proc = new System.Diagnostics.Process();\nproc.EnableRaisingEvents=false;\nproc.StartInfo.FileName = "shutdown.exe";\nproc.StartInfo.Arguments = @"\\computername /t:120 ""The computer is shutting down"" /y /c";\nproc.Start();	0
4902183	4790498	How do you add a list of bsondocuments as an element of a bsondocument	var document = new BsonDocument {\n            { "name", "John Doe" },\n            { "classes", new BsonArray {\n                new BsonDocument("classname", "Class1"),\n                new BsonDocument("classname", "Class2")\n            }}\n        };\n        var json = document.ToJson();	0
9591393	9591213	How to get Tracelistnername from app.config	foreach (TraceListener listener in System.Diagnostics.Trace.Listeners)\n{\n    Console.WriteLine(listener.Name);\n}	0
5309015	5308961	HLSL - Combining textures	AlphaSourceBlend = SrcAlpha\nAlphaDestinationBlend = InvSrcAlpha	0
31400431	31399293	Multiplying a matrix by a vector of scalars in parallel C#	var results = new ConcurrentDictionary<string, int[]>();\n\nParallel.ForEach(ret, pair =>\n{\n      var srcArr = pair.Value;\n      var arr = new int[srcArr.Length];\n      var multBy = multipliers[pair.Key];\n\n      for (var i = 0; i < srcArr.Length; i++)\n      {\n           var d = srcArr[i] * multBy;\n\n           arr[i] = d;\n      }\n      results[pair.Key] = arr;\n});	0
30587402	30571235	second parameter interfering with generic handler	string schemeCode = context.Request.QueryString["schemeCode"].ToString();\n    string version = context.Request.QueryString["Version"].ToString();	0
11294115	11293859	Can I assign a method to multiple Form-based Events?	public Form1() {\n        InitializeComponent();\n        Application.Idle += UpdateTextLabel;\n        this.FormClosed += delegate { Application.Idle -= UpdateTextLabel; };\n    }\n\n    void UpdateTextLabel(object sender, EventArgs e) {\n        // etc..\n    }	0
31834598	31828509	How to hide row in GridView if certain column is empty?	void gv_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            JobPieceSerialNo item = e.Row.DataItem as JobPieceSerialNo;\n            if (item != null)\n            {\n                if (string.IsNullOrEmpty(item.Reason))\n                {\n                    e.Row.Visible = false;\n                }\n            }\n        }\n    }	0
6077060	6077031	c# comparing arrays	var idsWithoutObjects = ids.Except(x.Select(item => item.id));	0
6249049	6248926	LINQ-to-SQL - 'Sum' inside a select new	var data = dc.Deliveries.Where(d => d.TripDate == DateTime.Now)\nvar rateSum = data.Sum(d => d.Rate);\nvar additionalCharges = data.Sum(d => d.AdditionalCharges);	0
27064556	27064050	Retrieve all rows from all database tables with "Where" condition	CREATE PROCEDURE usp_BulkTableOpenReport \nAS\nBEGIN\n\n    DECLARE @TBLS AS TABLE (REF INT IDENTITY (0,1), TABLENAME NVARCHAR(100), TABLEID BIGINT);\n    DECLARE @TBL AS NVARCHAR(100);\n    DECLARE @TBLID AS BIGINT;\n    DECLARE @SQL AS NVARCHAR(MAX);\n    DECLARE @I INT = 0;\n    DECLARE @M INT = 0;\n    DECLARE @V INT = 0\n\n    INSERT INTO @TBLS(TABLENAME,TABLEID)\n    SELECT NAME,OBJECT_ID FROM sys.tables\n\n    SELECT @M = MAX(REF) FROM @TBLS\n\n    WHILE @I <= @M\n    BEGIN\n        SELECT @TBL = TABLENAME, @TBLID= TABLEID FROM @TBLS WHERE REF = @I \n        /* CHECK TO MAKE INSURE THAT A FLD CALLED [OPEN] EXIST. */\n        SELECT @V = COUNT(*) FROM SYS.columns WHERE name = 'OPEN' AND  OBJECT_ID = @TBLID\n        IF @V != 0 \n        BEGIN\n            SET @SQL = 'SELECT * FROM [' + @TBL + '] WHERE [OPEN] = 1'\n            EXEC SP_EXECUTESQL @SQL\n        END;\n        SET @I = @I + 1\n    END; \nEND\nGO	0
22328526	22326232	Windows Phone 8 Logging	System.Diagnostics.Debug.WriteLine("Print something");	0
25875607	25739576	Copying application files with visual studio for debugging	Debugger.Launch();	0
6355920	6355911	Avoid confirmation box in MsiExec uninstall	msiexec /quiet	0
3318458	3318443	How can i access a server side control from asp.net code behind file using reflection?	foreach(var id in enabledTabs.Split(','))\n{\n    PlaceHolder control = (PlaceHolder)this.FindControl("tab_"+id));\n    control.Visible = true;\n}	0
27056312	27056191	JSON data in PUT request in C#	var serializer = new JavaScriptSerializer();\n        string json =\n            serializer.Serialize(\n                new\n                    {\n                        main = new\n                                   {\n                                       reg_FirstName = "Bob", \n                                       reg_LastName = "The Guy"\n                                   },\n                        others = new[]\n                                     {\n                                         new { reg_FirstName = "Bob", reg_LastName = "The Guy" }, \n                                         new { reg_FirstName = "Bob", reg_LastName = "The Guy" }\n                                     }\n                    });	0
6870388	6870253	LINQ search for a given string value within a node	public string GetDestination(string categoryName, XDocument xDoc)\n{\n\n     var query = (from x in xDoc.Descendants("DocumetentCategory")\n                  where ((string)x.Element("CategoryName")).Contains(categoryName)\n                  select (string)x.Element("DestinationDocumentLibrary")).SingleOrDefault();\n\n     return (string)query;\n}	0
3918194	3918021	c# reorganize controls in a FlowLayoutPanel	FlowLayoutPanel.SetChildIndex()	0
27146902	27146424	Prevent app has closed screen when killing a process	Process.Start("taskkill", "/F /IM [taskname].exe");	0
10074694	10074482	How to create a "sharp" gradient in Windows Forms?	private void pictureBox1_Paint(object sender, PaintEventArgs e)\n    {\n        int k = 20;\n        Color mycolor = new Color();\n        for (int i = 0; i < 10; i++)\n        {\n            mycolor = Color.FromArgb(i * k, i * k, i * k);\n            SolidBrush mybrash = new SolidBrush(mycolor);\n            e.Graphics.FillRectangle((Brush)mybrash, 0 + i * k, 0, k, k);\n        }\n    }	0
13587908	13565720	Highlight the null value cells in RadGridView C#	private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)\n{\n    if (e.RowIndex != -1)\n    {\n        if (e.CellElement.Value != null && e.CellElement.Value.ToString() == "")\n        {                    \n            radGridView1.Rows[e.CellElement.RowIndex].Cells[e.CellElement.ColumnIndex].Style.BackColor = Color.Red;\n            radGridView1.Rows[e.CellElement.RowIndex].Cells[e.CellElement.ColumnIndex].Style.CustomizeFill = true;\n        }\n\n    }\n}	0
32710789	32709564	C# WPF - how to prevent image to be dragged outside canvas	double canvasSize = 800;\n\ndouble newLeft = Canvas.GetLeft(draggedImage) + offset.X;\ndouble newTop = Canvas.GetTop(draggedImage) + offset.Y;\n\nif (newLeft < 0)\n    newLeft = 0;\nelse if (newLeft + draggedImage.ActualWidth > canvasSize)\n    newLeft = canvasSize - draggedImage.ActualWidth;\n\nif (newTop < 0)\n    newTop = 0;\nelse if (newTop + draggedImage.ActualHeight > canvasSize)\n    newTop = canvasSize - draggedImage.ActualHeight;\n\nCanvas.SetLeft(draggedImage, newLeft);\nCanvas.SetTop(draggedImage, newTop);	0
6726706	6720294	WPF: Close a secondary window when application shutdown without "programmer" intervention	Application.Current.MainWindow.Closed += new EventHandler(MainWindow_Closed);\n\nstatic void MainWindow_Closed(object sender, EventArgs e)\n{\n    Dispose();\n}	0
12890151	12890138	How to use PrincipalContext with MVC Web Application	System.DirectoryServices.AccountManagement.dll	0
11326309	11326142	How do I use try-catch correctly in simple methods?	public static int[] GetIntArrayFromStringArray(string[] stringArray)\n    {\n        if (stringArray == null)\n        {\n            throw new ArgumentNullException("stringArray");\n        }\n\n        int count = stringArray.Length;\n        int[] ints = new int[count];\n        for (int i = 0; i < count; i++)\n        {\n            int intValue;\n            ints[i] = int.TryParse(stringArray[i], out intValue) ? intValue : 0;\n        }\n        return ints;\n    }	0
29118488	29118019	c# regex everything after n-th occurence of capital letter	var name = Regex.Replace("NameSurname", @"^(\w)[^A-Z]*(.*)", "$1$2")	0
22894525	22894372	Reading XML with a colon (:)	XmlNodeList videos = doc.GetElementsByTagName("entry");\n\nforeach (XmlNode video in videos)\n{\n    string videoId = video["id"].InnerText.Replace("http://gdata.youtube.com/feeds/api/videos/", String.Empty);\n    string author = video["author"]["name"].InnerText;\n    string views = video["yt:statistics"].Attributes["viewCount"].Value;\n\n    Console.WriteLine(videoId);\n    Console.WriteLine(author);\n    Console.WriteLine(views);\n}	0
20816556	20816383	Await a button click	Message Dialog	0
8711667	8711522	Calculating the number of bits in a Subnet Mask in C#	string mask = "255.255.128.0";\nint totalBits = 0;\nforeach (string octet in mask.Split('.'))\n{\n    byte octetByte = byte.Parse(octet);\n    while (octetByte != 0)\n    {\n        totalBits += octetByte & 1;     // logical AND on the LSB\n        octetByte >>= 1;            // do a bitwise shift to the right to create a new LSB\n    }                \n}\nConsole.WriteLine(totalBits);	0
2637791	2637697	Sending UDP Packet in C#	Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,\nProtocolType.Udp);\n\nIPAddress serverAddr = IPAddress.Parse("192.168.2.255");\n\nIPEndPoint endPoint = new IPEndPoint(serverAddr, 11000);\n\nstring text = "Hello";\nbyte[] send_buffer = Encoding.ASCII.GetBytes(text );\n\nsock.SendTo(send_buffer , endPoint);	0
4658400	4658388	how to ignore { character?	String.Format(CultureInfo.InvariantCulture, @"\n    function(s, e) {{\n        {0}.PerformCallback(MyObject.GetSelectedItem().value);\n    }}", getClientName);	0
10900084	10900021	Test whether an object implements a generic interface for any generic type	return type.GetInterfaces()\n           .Where(t => t.IsGenericType)\n           .Select(t => t.GetGenericTypeDefinition())\n           .Any(t => t.Equals(typeof(IDictionary<,>)));	0
22699387	22699293	How to ORDER BY in this SQL	sqlSEQ = "SELECT ROW_NUMBER() OVER(ORDER BY ID_KEY DESC) AS RN,* From(Select distinct f.FACILITY_NAME, ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX], [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI], [PHYSICIAN], [COST], [QUANTITY], [MEDICATION], A.[NDC], " +\n                    " case when COST > 0 then (COST / DAYSUPPLY) * 30 else 0 end [30DayCost] , [PATIENTNAME], [ROUTEOFADMIN], [INVOICECAT], [COPAY], [BRAND], [VER], [SKILLLEVEL], [STAT] STATUS, [LASTTASKDATE],SEQNO,B.[SUBST_INSTRUCTIONS] , f.FACILITY_ID " +\n                    " FROM [VBM].[T_CHARGES] A LEFT OUTER JOIN [OGEN].[NDC_M_FORMULARY] B ON A.[SEQNO] = B.[SEQ_NO]   Left Outer Join VBM.FACILITY f on A.FACILITYNPI = f.FACILITY_NPI  " +\n                    " Where [STAT] not in (3, 4, 5) " +\n\n                    " AND [VER] <> 'T1'  " +\n                    sqlWhere + " AND f.FACILITY_ID IN (" + selected + ")"\n+ " ORDER BY [PATIENTNAME]";	0
28880367	28830743	Open Excel, Parse Data?	var path = string.Format(@"C:\Users\jlambert\Desktop\encryptedSSNs.xlsx");\n        var connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";\n\n\n        var adapter = new OleDbDataAdapter("SELECT * FROM [sheetName$]", connStr);\n        var ds = new DataSet();\n\n        adapter.Fill(ds, "anyNameHere");\n\n        var data = ds.Tables["anyNameHere"].AsEnumerable();\n\n        var query = data.Where(x => x.Field<string>("MRN") != string.Empty).Select(x =>\n            new \n            {\n                mrn = x.Field<string>("MRN"),\n                ssn = x.Field<string>("ssn"),\n            });\n\n        foreach (var q in query)\n        {\n            Console.WriteLine(q);    \n        }\n        Console.ReadLine();	0
9110799	9110676	Remove a property/column from a generic list	List<myClass> list = ...;\nvar reducedList = list.Select(e => new {e.id, e.name, e.status}).ToList();\n// note: call to ToList() is optional\n\nforeach (var item in reducedList)\n{\n    Console.WriteLine(item.id + " " + item.name + " " + item.status);\n    //note: item does not have a property "sDate"\n}	0
9654003	9653589	How to determine if a printer exist?	System.Windows.Forms.PrintDialog dlg=new PrintDialog();\nif(dlg.PrinterSettings.IsValid)\n      MessageBox.Show("Printer Exist: "+ dlg.PrinterSettings.PrinterName);\nelse\n      MessageBox.Show("Printer Does Not Exist");	0
29471648	29285672	DataTable losing its values when applying filter	var newDataTable = cachedDataTable.Clone();\n            var filteredRows = cachedDataTable.Select("[Status Type]='test'");\n            foreach (DataRow row in filteredRows)\n            {\n                newDataTable.ImportRow(row);\n            }	0
24087413	24087389	Decimal to money string with 3 decimals?	MyMoneyField.ToString("C3", new CultureInfo("en-US");	0
9159690	9153877	How can I extract text visible on a page from its html source?	string StripHTML(string htmlStr)\n{\n    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n    doc.LoadHtml(htmlStr);\n    var root = doc.DocumentNode;\n    string s = "";\n    foreach (var node in root.DescendantNodesAndSelf())\n    {\n        if (!node.HasChildNodes)\n        {\n            string text = node.InnerText;\n            if (!string.IsNullOrEmpty(text))\n            s += text.Trim() + " ";                     \n        }\n    }\n    return s.Trim();\n}	0
10294397	10294302	How to merge two Task results in a third task?	class Step1Result {}\nclass Step2AResult\n{\n    public Step2AResult(Step1Result result) {}\n}\nclass Step2BResult\n{\n    public Step2BResult(Step1Result result) {}\n}\nclass FinalResult \n{\n    public FinalResult(Step2AResult step2AResult, Step2BResult step2BResult) {}\n}\n\n    public Task<FinalResult> RunStepsAsync()\n    {\n        var task1 = Task<Step1Result>.Factory.StartNew(() => new Step1Result());\n\n        // Use the result of step 1 in steps 2A and 2B\n        var task2A = task1.ContinueWith(t1 => new Step2AResult(t1.Result));\n        var task2B = task1.ContinueWith(t1 => new Step2BResult(t1.Result));\n\n        // Now merge the results of steps 2A and 2B in step 3\n        return Task <FinalResult>\n            .Factory\n            .ContinueWhenAll(new Task[] { task2A, task2B }, tasks => new FinalResult(task2A.Result, task2B.Result));\n    }	0
7566998	7566939	How to make a reference to a struct in C#	void method(ref MyStruct param)\n{\n}	0
23520452	23520195	Datagridview how to cast selected row to custom object	var pilots = new List<Pilots>(grid.SelectedRows.Count);\n\nfor(int index = 0; index < grid.SelectedRows.Count; index++)\n{\n   var selectedRow = grid.SelectedRows[index];\n   var pilot = (Pilots)selectedRow.DataBoundItem;\n\n   pilots.Add(pilot);\n}	0
16185057	16184280	Is it possible to change a url column in a GridView (HyperLink or HyperLinkField) to a normal text?	private void RemoveLinks(Control grdView)\n    {\n        LinkButton lb = new LinkButton();\n        Literal l = new Literal();\n\n        for (int i = 0; i < grdView.Controls.Count; i++)\n        {\n            if (grdView.Controls[i].GetType() == typeof(LinkButton))  // or hyperlink\n            {\n                l.Text = (grdView.Controls[i] as LinkButton).Text;\n                grdView.Controls.Remove(grdView.Controls[i]);\n                grdView.Controls.AddAt(i, l);\n            }\n            if (grdView.Controls[i].HasControls())\n            {\n                RemoveLinks(grdView.Controls[i]);\n            }\n        }        \n    }	0
2904279	2903172	indicate truncation in ToolTipStatusLabel automatically	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\n[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.StatusStrip)]\npublic class SpringLabel : ToolStripStatusLabel {\n    public SpringLabel() {\n        this.Spring = true;\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        var flags = TextFormatFlags.Left | TextFormatFlags.EndEllipsis;\n        var bounds = new Rectangle(0, 0, this.Bounds.Width, this.Bounds.Height);\n        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, bounds, this.ForeColor, flags);\n    }\n}	0
11750553	11750423	Print option with page range not setting correctly	PrinterSettings.PrintRange = PrintRange.SomePages	0
7959928	7959903	Reading from an Access Database c#	lblist.Items.Clear();\nrdr = cmd.ExecuteReader();\nwhile (rdr.Read())\n{\n    //lblist.Text += (string)rdr["GroupName"];\n    lblist.Items.Add((string)rdr["GroupName"]);\n}	0
7487075	7487007	How can I enumerate through a folder to get all file names in an ASP.NET MVC website?	string[] files = Directory.GetFiles(Server.MapPath(path), "*.png");	0
9958857	9958732	How to flatten entities for display in a table	var result = ctx.Persons\n.Select(x => \nnew {PersonID = x.PersonID, \n     Name = x.Name,\n     Title = x.Title,\n     PrimaryContact = x.PersonContacts.FirstOrDefault(y => y.IsDefault == true).Select(t => t.ContactText),\n     MobileNumber = x.PersonContacts.FirstOrDefault(z => z.ContactType.TypeString =="Mobile").Select(q => q.ContactText)\n     }).ToList();	0
2067446	2066615	Manually instantiate a Controller instance from an arbitrary URL?	string url = "~/Account/LogOn";  //trying to create Account controller in default MVC app\n\nRouteCollection rc = new RouteCollection();\nMvcApplication.RegisterRoutes(rc);\nSystem.Web.Routing.RouteData rd = new RouteData();\nvar mockHttpContext = new Moq.Mock<HttpContextBase>();\nvar mockRequest = new Moq.Mock<HttpRequestBase>();\nmockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);\nmockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);\n\nRouteData routeData = rc.GetRouteData(mockHttpContext.Object);\n\nstring controllerName = routeData.Values["controller"].ToString();\n\nIControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();\nIController controller = factory.CreateController(this.ControllerContext.RequestContext, controllerName);	0
33056634	33056540	How to access data json.net array in c#	using System;\nusing System.Collections.Generic;\nusing Newtonsoft.Json;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string json2 = @"[{\n     'Email': 'james@example.com',\n      'Active': true,\n      'CreatedDate': '2013-01-20T00:00:00Z',\n      'Roles': [\n        'User',\n        'Admin']\n    },\n    {\n     'Email': 'james@example.com2',\n      'Active': true,\n      'CreatedDate': '2013-01-20T00:00:00Z',\n      'Roles': [\n        'Userz',\n        'Adminz'\n      ]\n    }]";\n\n    List<Account> account = new List<Account>();\n    account.AddRange(JsonConvert.DeserializeObject<List<Account>>(json2));\n\n\n    // james@example.com\n    Console.Write(account[0].Email);\n    }\n}\n\npublic class Account\n{\n    public string Email { get; set; }\n    public bool Active { get; set; }\n    public DateTime CreatedDate { get; set; }\n    public IList<string> Roles { get; set; }\n}	0
23380916	23357864	Lost end of the string	Encoding.UTF8.GetString(connection.Buffer,0 , bufferLength);	0
1588772	1588283	How can I lock the screen using C#?	formName.WindowState = FormWindowState.Maximized; \nformName.FormBorderStyle = FormBorderStyle.None; \nformName.Opacity = 0.70; \nformName.TopMost = true;	0
33602653	33601795	How do edit controls that were created in C# during runtime?	private List<TextBox> dynamicGroupEdits = new List<TextBox>();\n\nprivate void AddNewButton_Click(object sender, RoutedEventArgs e)\n{\n    ...\n    dynamicGroupEdits.Add(GroupEdit);\n\n    GroupEdit.Tag = dynamicGroupEdits.Count;\n    GroupPanel.Tag = GroupEdit.Tag;\n    GroupTextBox.Tag = GroupEdit.Tag;\n    ...\n}\n\nprivate void GroupEdit_Click(object sender,RoutedEventArgs e)\n{\n    ...\n    tag = GroupEdit1.Tag;\n    // Loop through all child controls and set visibility according to tag\n    for each (var c in LogicalTreeHelper.GetChildren(GroupEdit1.Parent)\n    {\n        if(c is TextBox && c.Tag == tag) \n            c.Visible =Visibility.Visible;\n        else if(c is TextBlock && c.Tag == tag) \n            c.Visibility = Visibility.Collapsed;\n     }\n}	0
1341795	1302237	Marshalling CodeElements to an IntPtr in C#	[DllImport("CodeMethodsToString.dll")]\n[return: MarshalAs(UnmanagedType.BStr)]\nprivate static extern string CodeMethodsToString(IntPtr functionObject);\n\npublic static void CodeMethodsToXML(XmlElement parent, CodeElements elements)\n{\n   GCHandle pin;\n   try\n   {\n      pin = GcHandle.Alloc(elements, GCHandleType.Pinned);\n      string methods = CodeMethodsToString(pin.AddrOfPinnedObject());\n    }\n    finally\n    {\n       pin.Free();\n    }\n}	0
4206984	4206509	Fluent Nhibernate HasManyToMany both sides with noop map	HasManyToMany(x => x.SomeCollection).Table("MappingTable").ParentKeyColumn("ParentKey").ChildKeyColumn("ChildKey").Cascade.AllDeleteOrphan();	0
14821708	14821669	Table column make enum and return values as strings	using (SMEntities db = new SMEntities())\n    {\n        User user = db.Users.First(x => x.Username == username);\n        return user.Roles.Select(r => r.Type).ToArray();\n    }	0
18957923	18957852	Calculating distances in MySQL and displaying the distance between them in .NET	Items.Add(new {\n    Name = reader["Name"].ToString(),\n    Latitude = reader["Latitude"].ToString(),\n    Longitude = reader["Longitude"].ToString(),\n    Distance = reader["distance"]\n});	0
13042498	13042318	Ray intersection with 3D quads in XNA?	public Plane (\n     Vector3 point1,\n     Vector3 point2,\n     Vector3 point3\n)	0
24459378	24459377	In WinRT, how to Reflect for Properties that implement an Interface?	using System.Reflection;\n\n/// <summary>Finds properties that implement a type</summary>\n/// <param name="parent">The parent type</param>\n/// <param name="type">The filter type</param>\n/// <returns>Enumerable of PropertyInfo</returns>\nIEnumerable<PropertyInfo> Properties(Type parent, Type type)\n{\n    var typeinfo = type.GetTypeInfo();\n    var properties = parent.GetRuntimeProperties();\n    foreach (PropertyInfo property in properties)\n    {\n        var propertytypeinfo = property.PropertyType.GetTypeInfo();\n        if (typeinfo.IsAssignableFrom(propertytypeinfo))\n            yield return property;\n    }\n}	0
15526463	15526188	C# expressions syntax shorthand	string myMethod() { return DateTime.Now.ToString(); }	0
16722995	16664712	How to show image in DotNetNuke custom module?	private string GetPath(int fileId)\n{\n    StringBuilder sb = new StringBuilder("/Portals/");\n\n    IFileInfo fi = FileManager.Instance.GetFile(fileId);\n    sb.Append(fi.PortalId);\n    sb.Append("/");\n    sb.Append(fi.RelativePath);\n\n    return sb.ToString();\n}	0
31499716	31499594	checking two lists contains same property values	var accessedTopicsByCode = topicsB.ToDictionary(x => x.TopicCode);\nforeach (var t in topicsA)\n{\n    if (accessedTopicsByCode.ContainsKey(t.TopicCode))\n    {\n        t.TopicAccessed = true;\n    }\n}	0
15257812	15257718	Page functions for JavaScript Parameters?	numberOfWeeks: <% =GetNumWeeks() %>	0
3918278	3918135	How can i add a data object of a class array to a drop down list?	ddl_traders.DateSource = traders;\n    ddl_traders.DataTextField = "FirstName";\n    ddl_traders.DateValueField= "login";\n    ddl_traders.DataBind();	0
29391386	29125460	How to prevent StackOverflowException when reusing a callback in a callback?	void OnCacheItemRemoved( string key, object value, CacheItemRemovedReason reason )\n    {\n\n        if ( reason != CacheItemRemovedReason.Expired )\n        {\n            return;\n        }	0
8712743	8712411	c# XML Parsing seperating innerxml from innertext	class Program\n    {   \n        static void Main(string[] args)\n        {\n          string xml = @"<Woods><Wood><ID>1</ID><Name>Hickory</Name><Weight>3</Weight><Thickness>4</Thickness><Density>5</Density><Purity>6</Purity><Age>7</Age></Wood><Wood><ID>2</ID><Name>Soft Maple</Name><Weight>3</Weight><Thickness>4</Thickness><Density>5</Density><Purity>6</Purity><Age>7</Age></Wood><Wood><ID>3</ID><Name>Red Oak</Name><Weight>3</Weight><Thickness>4</Thickness><Density>5</Density><Purity>6</Purity><Age>7</Age></Wood></Woods>";\n\n           XDocument doc = XDocument.Parse(xml);\n           //Get your wood nodes and values in a list \n           List<Tuple<string,string>> list = doc.Descendants().Select(a=> new Tuple<string,string>(a.Name.LocalName,a.Value)).ToList();\n\n           // display the list\n           list.All(a => { Console.WriteLine(string.Format("Node name {0} , Node Value {1}", a.Item1, a.Item2)); return true; });\n           Console.Read();\n        }\n    }	0
9968210	9964562	Given a CloudTableQuery / DataServiceQuery, return associated TableServiceContext	using System;\nusing System.Linq;\nusing System.Reflection;\n\nusing Microsoft.WindowsAzure.StorageClient;\n\npublic static class DataServiceQueryExtensions\n{\n    public static TableServiceContext GetTableServiceContext<TType>(this IQueryable<TType> query)\n    {\n        var contextField = query.Provider.GetType().GetField("Context", (BindingFlags.Instance | BindingFlags.NonPublic));\n        if (contextField == null)\n            return null;\n        else\n            return contextField.GetValue(query.Provider) as TableServiceContext;\n    }\n}	0
18979591	18979039	.net - How to add controls dynamically?	private int controlCount\n{\n    get \n    {\n        int val = 0;\n        try\n        {\n            val = (int)Page.ViewState["ControlCount"];\n        }\n        catch(Exception e)\n        {\n            // handle exception, if required.\n        }\n        return val;\n    }\n    set { Page.ViewState["ControlCount"] = value; }\n}\nprotected void addnewtext_Click(object sender, EventArgs e)\n{\n    int i = controlCount++;\n    for (int j = 0; j <= i; j++)\n    {\n        AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");\n        placeHolder.Controls.Add(ac);\n        placeHolder.Controls.Add(new LiteralControl("<BR>"));\n    }\n}	0
23835903	23835828	Add CSV Connection to Excel with c#	string strFileName = textpath + "\\filename.csv";\nOleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) +"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");\nconn.Open();\nOleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);\nDataSet ds = new DataSet("Temp");\nadapter.Fill(ds);\nDataTable tb = ds.Tables[0];	0
13952206	13943607	Populating the data attribute of an object tag in Chrome with an ASP.NET MVC action that serves a PDF file result	var doc = ...\nvar contentDisposition = new ContentDisposition\n{\n    FileName = doc.FileName,\n    Inline = true\n};\n\nResponse.AppendHeader("Content-Disposition", contentDisposition.ToString());\n\nreturn File(doc.Path, MediaTypeNames.Application.Pdf);	0
30651910	30651831	Integrating a running clock in my program C#	System.Windows.Forms.Timer t = null;\nprivate void StartTimer()\n{\n    t = new System.Windows.Forms.Timer();\n    t.Interval = 1000;\n    t.Tick += new EventHandler(t_Tick);\n    t.Enabled = true;\n}\n\nvoid t_Tick(object sender, EventArgs e)\n{\n    lblTime.Text = DateTime.Now.ToString();\n}	0
10930999	10930965	How to Set Master Page dynamically?	void Page_PreInit(Object sender, EventArgs e)\n{\n    this.MasterPageFile = "~/MyMaster.master";\n}	0
21504140	21503814	dynamically add html and data from database (using LINQ)	//Move this outside of the for-loop\nDataClassesDataContext tb = new DataClassesDataContext();\nfor (int i = 0; i < dv; i++)\n    {\n\n        var ctitle = (from cat in tb.dml_np_Categories\n                      where cat.Pk_Category_Id == (i+1)\n                      select cat.Category_Title).First();\n\n        HtmlGenericControl adddiv = new HtmlGenericControl("div");\n        adddiv.Attributes.Add("class", "category");\n        HtmlGenericControl addh3 = new HtmlGenericControl("h3");\n        addh3.Attributes.Add("class", "h3");\n        addh3.InnerText = ctitle.ToString();\n\n        catblock.Controls.Add(adddiv);\n        adddiv.Controls.Add(addh3);\n}	0
30905187	30854457	Crystal Report Prompts for variables issue in c#	Customer_List1.Database.Tables["Customer_List"].SetDataSource((DataTable)dt);\ncrv_customer_list.ReportSource = Customer_List1;\nCustomer_List1.SetParameterValue("IsSubs", subs);    \ncrv_customer_list.Refresh();	0
12150177	12150008	Add TextBox.Text to a list using a for loop	var amtBoxes = new TextBox[] { amtBox0, amtBox1, .... };\nfor (int i = 0; i <= amt.Count(); i++)\n{\n    amt[i] = int.Parse(amtBoxes[i].Text);\n}	0
13082908	13082633	How decompress zip with a password in windows 8	SharpZipLibZip.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();\nzip.Password = "password";\nzip.CreateZip(zipfilename, "temp\\", true, null, null);	0
8302913	8301396	Parsing HTML using HTMLAgilityPack	HtmlNodeCollection tl = document.DocumentNode.SelectNodes("//p[not(@*)]");\nforeach (HtmlAgilityPack.HtmlNode node in tl)\n{\n    Console.WriteLine(node.InnerText.Trim());\n}	0
14206534	14203333	Sync mouseclicks between controls	const int WM_LBUTTONDOWN = 0x201;\n\nswitch( message.Msg ) \n{\n    case WM_LBUTTONDOWN:\n        Int16 x = (Int16)message.LParam;\n        Int16 y = (Int16)((int)message.LParam >> 16);\n\n        //Getting the control at the correct position\n        Control control = m_TableControl.GetControlFromPosition(0, (y / 16));\n\n        if (control != null)\n            m_TableControl.Refresh();\n\n        TreeNode node = this.GetNodeAt(x, y);\n        this.SelectedNode = node;\n        break;\n}	0
19389732	19389495	How to get text contained between brackets with regular expression?	Regex regexObj = new Regex(\n    @"\{\{            # Match {{\n    (?>               # Then either match (possessively):\n     (?:              #  the following group which matches\n      (?!\{\{|\}\})   #  (but only if we're not at the start of {{ or }})\n      .               #  any character\n     )+               #  once or more\n    |                 # or\n     \{\{ (?<Depth>)  #  {{ (and increase the braces counter)\n    |                 # or\n     \}\} (?<-Depth>) #  }} (and decrease the braces counter).\n    )*                # Repeat as needed.\n    (?(Depth)(?!))    # Assert that the braces counter is at zero.\n    \}}               # Then match a closing parenthesis.", \n    RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);	0
9206504	9206451	how to solve OutOfMemoryException in c#	using (var image = ...new instance created...)\n{\n    // ...do stuff...\n}	0
6792950	6767847	comparing two List<>	List<Employee> found = EmployeeListFromDB.FindAll(a=>!selectedEmployee.Exists(b=>a.Id == b.Id));	0
7494912	7494842	Get data for XmlDocument in C#	StringWriter sw = new StringWriter();\nXmlTextWriter tx = new XmlTextWriter(sw);\nACTGraphicalXMLDoc.WriteTo(tx);\nsw.ToString();	0
6879700	6879805	How do I read the contents of an XML element using C#?	XDocument xdoc = XDocument.Load("file.xml"));\nvar elm = from element in xdoc.Descendants("element")\n           select new { \n               attribute = element.Attribute("attribute").Value,\n           };	0
15013610	15013512	Removing an item from a list c#	if (li.Text == current[i].uname)\n        {\n            current.RemoveAt(i);\n            break;\n        }	0
19275361	19275147	Issue with a DLL reading a ConfigurationSection when called through Service Reference	Configuration config;\nExeConfigurationFileMap ecfm = new ExeConfigurationFileMap();\necfm.ExeConfigFilename = <your_config_file_path>;\n\nconfig = ConfigurationManager.OpenMappedExeConfiguration(ecfm, ConfigurationUserLevel.None);\nvar mySection = (BusinessConfigurationSection)config.GetSection("GroupName/SectionName");	0
3393076	3393043	Capturing cookie responses in C#	Set-Cookie	0
5252166	5251980	NHibernate QueryOver - Date Comparison expression	.Where(r => r.DateColumn <= myDate)	0
4034869	4034805	Querying Entity Data Model from C# code	myEntities.CalculateCustomerInvoices();	0
3154903	3154880	Group and aggregate a list of objects	var query =\n    from row in rows\n    group row by new { row.Field1, row.Field2 } into g\n    select new RowClass\n    {\n        Field1 = g.Key.Field1,\n        Field2 = g.Key.Field2,\n        Field3 = g.Aggregate(\n                    new StringBuilder(), \n                    (sb, grp_row) => sb.Append(grp_row.Field3))\n                  .ToString()\n    }	0
22472491	22472423	ListView doesn't show up at all	yourFormName.Controls.Add(auftraegeView );	0
23254433	23254227	How Do I Populate Text Boxes With Sql Database Data Using One Combo Box	private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)\n{\n      string connectionString =\n          ZimbFootball.Properties.Settings.Default.Football2ConnectionString;\n      using (SqlConnection connection = new SqlConnection (connectionString))\n      using (SqlCommand command = new SqlCommand(\n                    "SELECT * From Add_Players WHERE Player_ID =@id", connection))\n      {\n          connection.Open();\n          command.Parameters.AddWithValue("@id", comboEditPlayer.Text);\n          using(SqlDataReader myReader = command.ExecuteReader())\n          {\n              while (myReader.Read())\n              {\n                    comboEditPlayerPos.Items.Add(myReader[1]);\n                    txtEditPlayerName.Text = myReader[2].ToString();\n                    txtEditPlayerSecond.Text = myReader[3].ToString();\n                    comboEditPlayerStatus.Items.Add(myReader[4]);\n              }\n          }\n       }\n }	0
22440146	22439923	How to delete row in DataTable	foreach(DataRow row in dt.Rows)\n     {\n      if (row["ProductID"].ToString().Equals(txtBarcode.Text.Trim()))\n      {\n        row.Delete();\n        txtBarcode.Clear();\n\n      }\n     }\n   dt.AcceptChanges();	0
16550297	16550226	how to set sqldatasource default value from database in c#?	SqlDataSource4.SelectParameters.Add("@Vehicle", "Vehicle Value");	0
29114849	28951700	C# How to change background color of root layout in Windows Phone 8 WinRT	if (rootFrame == null)\n{\n// Create a Frame to act as the navigation context and navigate to the first page\nrootFrame = new Frame();\n\nSolidColorBrush color = new SolidColorBrush();\ncolor.Color = (Windows.UI.ColorHelper.FromArgb(0xFF, 44, 50, 50));\nrootFrame.Background = color;	0
21840221	21840165	Check if variable values are close to each other	// Get the difference\nint d = test - test1;\n\n// Test the range\nif (-5 <= d && d <= 5)\n{\n    // Within range.\n}\nelse\n{\n    // Not within range\n}	0
22538239	22538059	Text box to accept only number in C#	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (!char.IsControl(e.KeyChar) \n        && !char.IsDigit(e.KeyChar) \n        && e.KeyChar != '.')\n    {\n        e.Handled = true;\n    }\n\n    // only allow one decimal point\n    if (e.KeyChar == '.' \n        && (sender as TextBox).Text.IndexOf('.') > -1)\n    {\n        e.Handled = true;\n    }\n}	0
34088914	34088748	Regex pattern single and multiple instance of same character	string clean = Regex.Replace(@"grey 1.25-2.50mm \ ----", @"([^\w./\s-]+|-{2,})", "")	0
17981964	17981483	AJAX Control Toolkit TabContainer Throws Specified Argument Out of Range of Valid Values	TabContainer1.ActiveTabIndex=0;	0
7845598	7845494	Generate LINQ or Lambda Expression for Multiple columns based on the user selection of checkboxes	var students = <your list of students>.AsQueryable();\n\nif ( chkStudentId.checked)\n{\n    students = students.Where(s => s.StudentId == c.StudentId);\n}\n\nif (chkStudentType.checked))\n{\n    students = students.Where(s => s.StudentType== h.StudentType);\n}	0
4495388	4494443	Serialize as object using json.net	// This is equivalent to defining window.clickEventHandler or\n//  window['clickEventHandler'] as a function variable.\nfunction clickEventHander() {\n  // Magic.\n}\n\n// Valid JSON, using strings to reference the handler's name.\nvar json = '{"onClickHandler": "clickEventHandler"}'\n\n// You might be using eval() or a framework for this currently.\nvar handlerMappings = JSON.parse(json);\n\nwindow[handlerMappings.onClickHandler]();	0
4601337	4601269	How to enable form button after process has exited?	private void SetText(string text)\n    {\n        // InvokeRequired required compares the thread ID of the\n        // calling thread to the thread ID of the creating thread.\n        // If these threads are different, it returns true.\n        if (this.textBox1.InvokeRequired)\n        {   \n            SetTextCallback d = new SetTextCallback(SetText);\n            this.Invoke(d, new object[] { text });\n        }\n        else\n        {\n            this.textBox1.Text = text;\n        }\n    }	0
22968850	19913792	SharpSVN: Unable to connect to a repository at URL | Access Forbidden	client.Authentication.ForceCredentials("login", "pswd");	0
19493744	19493651	Get fields and values from an object by reflection in C#	Dictionary<string, string> listField =\nmembership.GetType()\n         .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) // <-- specify that you want instance fields\n         .ToDictionary(f => f.Name,\n                       f => (string)f.GetValue(membership)); // <-- IMPORTANT, \n                       // you need to specify an instance to get a value from a non-static field	0
4618249	4611985	Nservice bus - replying to message after publish	Bus.Send<IRequestDataMessage>(m =>\n            {\n                m.DataId = g;\n                m.String = "<node>it's my \"node\" & i like it<node>";\n            })\n                .Register(i => Console.Out.WriteLine(\n                                   "Response with header 'Test' = {0}, 1 = {1}, 2 = {2}.",\n                                   Bus.CurrentMessageContext.Headers["Test"],\n                                   Bus.CurrentMessageContext.Headers["1"],\n                                   Bus.CurrentMessageContext.Headers["2"]));	0
6088133	6088104	How to split a string into two parts using a character separator in c#?	string[] words = myString.Split(new char[]{' '}, 2);	0
27413734	27412932	How to access programmatically the associated dataType of a DataTemplate?	var key = new System.Windows.DataTemplateKey(typeof(ProductsViewModel));\n        var dataTemplate = (DataTemplate)this.FindResource(key);\n\n        var tc = dataTemplate.LoadContent().GetType();\n        var instance = Activator.CreateInstance(tc);	0
9099185	9099157	Nullable DateTime and the Database	using (SqlCommand command = new SqlCommand(updateSql, db))\n{\n    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;\n}	0
435695	435676	How to add data to a new formed column	for int i=0; i<ds.tables[0].Rows.Count; i++)\n{\n    ds.tables[0].Rows[i]["Count"] = "4";\n}	0
27347547	27347443	connection string in visual studio community edition	string constr = @"data source=(LocalDB)\v11.0;\n                  AttachDBFileName=C:\Users\leon3\Documents\Visual Studio 2013\Projects\WindowsApplication1\WindowsApplication1\sqlserver.mdf;\n                  integrated security=True;connect timeout=30";	0
5880305	5880260	Binary sequence of a Image --> BMP etc	public void ImageToBytes(Image image, ImageFormat format)\n{\n  var stream = new MemoryStream();\n  image.Save(stream, format);\n  return stream.ToArray();\n}	0
5779664	5776327	HTML Agility Pack Parsing With Upper & Lower Case Tags?	"//body"	0
3059541	3059454	Adding roles from a DB Table	Create Table Roles\n(\nRoleId int identity(1,1) Not Null,\nRoleName varchar(50) not null\n)	0
33690338	33672643	Invalid length for a Base-64 char array error in c#	Decrypt(Request.QueryString["UserNumber"].ToString().Replace(" ", "+"))	0
13252506	13252361	getting selected index of listbox(c#)	GetSelectedIndices()	0
4580843	4577141	Move window without border	public const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HT_CAPTION = 0x2;\n\n[DllImportAttribute("user32.dll")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n[DllImportAttribute("user32.dll")]\npublic static extern bool ReleaseCapture();\n\nprivate void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)\n{     \n    if (e.Button == MouseButtons.Left)\n    {\n        ReleaseCapture();\n        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);\n    }\n}	0
12029117	12029023	How do I combine these three sets of code	private void uxRadioButton_CheckedChanged(object sender, EventArgs e) \n{ \n     radioButtonCode((RadioButton)sender);\n}\n\npublic void radioButtonCode(RadioButton myRadio)\n{\n    if (myRadio.Checked == true)\n    {\n        int guySelected = getGuySelectedIndex(myRadio);\n        uxPersonBettingLabel.Text = Guys[guySelected].Name;\n        uxBetNumericUpDown.Maximum = Guys[guySelected].Cash;\n    }\n}\n\npublic int getGuySelectedIndex(RadioButton myRadio)\n{\n    int index = 0;\n    if (myRadio == this.uxRajRadioButton) index = 0;\n    else if (myRadio == this.uxPaulRadioButton) index = 1;\n    else if (myRadio == this.uxMikeRadioButton) index = 2;\n    return index;\n}	0
3614701	3614664	Find out deselected item in a CheckBoxList ASP.NET	int myValue = 0;\n\nforeach(ListItem item in cbl.Items)\n{\n    if(item.Selected) myValue += int.Parse(item.Value);\n}	0
14157170	14036861	how to Remove item from one Listbox and add into another Listbox?	List<object> _selecteditems = new List<object>();\nforeach (var item in lstBox1.SelectedItems)\n{\n    _selecteditems.Add(item);\n}\nforeach (var item in _selecteditems)\n{\n  DataRow dr = dtSelctedDest.NewRow();\n  dr[0] = ((DataRowView)item).Row[0].ToString();\n  dr[1] = ((DataRowView)item).Row[1].ToString();\n  dtSelctedItem.Rows.Add(dr);\n  dtAllItem.Rows.Remove(dtAllItem.Rows.Remove.Select(string.Format("ID='{0}'", ((DataRowView)item).Row[0].ToString()))[0]);\n }\n lstBox1.DataContext = dtAllItem;\n lstBox2.DataContext = dtSelctedItem;	0
25644118	25557261	WCF SOAP call with both username token and client certificate	var b = new CustomBinding();\n        var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10);\n        sec.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());\n        sec.MessageSecurityVersion =\n            MessageSecurityVersion.\n                WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;\n        sec.IncludeTimestamp = false;\n        sec.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;\n\n        b.Elements.Add(sec);\n        b.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));\n        b.Elements.Add(new HttpsTransportBindingElement());	0
34503953	34503908	How to check any .txt file exists in a folder?	DirectoryInfo dir = new DirectoryInfo(@"c:\Directory");\nFileInfo[] TXTFiles = dir.GetFiles("*.txt");\nif (TXTFiles.Length == 0)\n{\n    //No files present\n}\nforeach (var file in TXTFiles)\n{\n    if(file.Exists)\n    {\n         //.txt File exists \n    }\n}	0
15551782	15551692	mixed up attributes and elements in xml	new XElement("PipeId",                       // Name of the element\n    new XAttribute("pid", "4598702C-691E"),  // Attribute of the element\n    "testvalue")                             // Text content of the element	0
18443558	18440191	How can I trigger dropdown while viewing asp.net page	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack)\n    {\n       LoadCountriesInDropDown(ddlCountry);\n       ddlCountry.SelectedValue = "5" //For eg:\n       LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue);  // selected country value was set here as 5\n       ddlCountry_SelectedIndexChanged(null, null);\n    }\n}\nprotected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if(ddlCountry.SelectedItem.Text == "Select")\n    {\n        ddlCity.Items.Clear();\n    }\n    else\n    {\n        LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue);\n    }\n\n}	0
3717725	3717690	generate a XML-File and display it in XML-format	Response.CompleteRequest()	0
2255460	2255431	How To Add A Calculated Column to A Data-Bound Listview?	oCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(oCollection_CollectionChanged);\n\nprivate void oCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n{\n    CalculatedBalance();\n}	0
25358918	25301044	WatiN C# selecting item from a HTML generated list	browserInstance.FindElement(By.Id("BirthMonth")).Click();\nSystem.Threading.Thread.Sleep(1000);\nSystem.Collections.ObjectModel.ReadOnlyCollection<IWebElement> months = browserInstance.FindElement(By.ClassName("goog-menu-vertical")).FindElements(By.ClassName("goog-menuitem-content"));\nmonths[new Random().Next(0, 11)].Click();\nSystem.Threading.Thread.Sleep(1000);	0
4935580	4935452	ASP.Net re-direct from URL after authentication	FormsAuthentication.RedirectFromLoginPage()	0
11012442	11011997	How to create a 'style master' winforms control	public class MasterDataGridView: System.Windows.Forms.DataGridView\n{\n    public MasterDataGridView()\n    {\n        BackColor = Color.Yellow;\n        // define other behaviours\n    }\n}\n\npublic class OrdersDataGridView : MasterDataGridView\n{\n   // data binding, column addition etc can be handle in respective grid views\n}\n\n\npublic class ReportsDataGridView : MasterDataGridView\n{\n}	0
28636249	28636224	How do I find multiple non-greedy instances of a Regex?	var r = new Regex( "\\{\\{(.+?):{3}([^}]+)\\}\\}" );	0
1669341	1669318	Override standard close (X) button in a Windows Form	protected override void OnFormClosing(FormClosingEventArgs e)\n{\n    base.OnFormClosing(e);\n\n    if (e.CloseReason == CloseReason.WindowsShutDown) return;\n\n    // Confirm user wants to close\n    switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))\n    {\n    case DialogResult.No:\n        e.Cancel = true;\n        break;\n    default:\n        break;\n    }        \n}	0
17338400	17338285	Several applications needs to access "a central server-program"	public class MyController\n{\n    [HttpPost]\n    public ActionResult MakeAnInvoice(Order theOrderObject)\n    {\n        // Do your invoice making magic\n    }   \n}	0
4796471	4796423	C# MySQL claims a field is too long	MySqlCommand insertCom = new MySqlCommand("INSERT INTO patients(" +\n            "last_name, first_name, sex, birth) VALUES" + \n            "(@lastName, @firstName, @sex, @birthDate)",\n            connection);	0
2197403	2196945	Running multiple threads, starting new one as another finishes	var semaphores = new List<AutoResetEvent>();\n        foreach (String fileName in filesToConvert)\n        {\n            String file = fileName;\n            AutoResetEvent[] array;\n            lock (semaphores)\n            {\n                array = semaphores.ToArray();\n            }\n            if (array.Count() >= 10)\n            {\n                WaitHandle.WaitAny(array);\n            }\n\n            var semaphore = new AutoResetEvent(false);\n            lock (semaphores)\n            {\n                semaphores.Add(semaphore);\n            }\n            ThreadPool.QueueUserWorkItem(\n              delegate\n              {\n                  Convert(file);\n                  lock (semaphores)\n                  {\n                      semaphores.Remove(semaphore);\n                  }\n                  semaphore.Set();\n              }, null);\n        }	0
4746592	1406499	Xml query in LinqToSql	var db = new MyDataContext();\nvar query = from x in db.MyTable \n            where db.XmlGetElementValue(x.XmlColName, "ElementX") == "somevalue" \n            select x;	0
13174302	13173384	Generic constraint for COM object	Marshal.IsComObject	0
8791485	8765335	Is it bad Ju-ju that the port is still being listened to after my app shuts down?	if (bThisInstanceFunctionsAsServer)\n        {\n            var serverThread = new Thread(Server);\n            serverThread.IsBackground = true; // Make sure the server thread doesn't keep the app running in the background\n            serverThread.Start();       // Run server method concurrently.\n            Thread.Sleep(500);                // Give server time to start.\n        }	0
2576703	2576640	How can I create a MethodInfo from an Action delegate	MethodInfo GetMI(Action a)\n{\n    return a.Method;\n}	0
24885393	24882902	MongoDb: documents with variable structure using and C#	Get["/api/docs/{category}"] = _ =>\n{\n   var filterValue = _.category;\n   //Search the DB for one record where the category property matches the filterValue\n   var item = database.GetCollection("docs").FindOne(Query.EQ("category", filterValue))\n   var json = item.ToJson();\n\n   var jsonBytes = Encoding.UTF8.GetBytes(json );\n   return new Response\n   {\n      ContentType = "application/json",\n      Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length)\n   };\n};	0
14301159	14301022	Async Tcp Server I just can get one client	static void callbake(IAsyncResult ar)\n{\n    // call BeginAcceptTcpClient here so that it's called everytime a connection is accepted\n    TcpListener listener = (TcpListener)ar.AsyncState;\n    listener.BeginAcceptTcpClient(new AsyncCallback(callbake), listener);\n\n    TcpClient clienter = listener.EndAcceptTcpClient(ar);\n    Console.WriteLine("---client connect {0}<--{1} ---", clienter.Client.LocalEndPoint, clienter.Client.RemoteEndPoint);\n}	0
13768835	13768683	C# How to retrieve an original string from the UTF-8 string?	Uri.UnescapeDataString(HttpUtility.UrlDecode("??y"));	0
31008960	30883768	Finding Depth value for Color Pixels in Kinect	ushort[] depthData = ... // Data from the Depth Frame\nDepthSpacePoint[] result = new DepthSpacePoint[512 * 424];\n\n_sensor.CoordinateMapper.MapColorFrameToDepthSpace(depthData, result);	0
13557001	13556924	Issues with server-side prepared statements in MySQL Connector/ODBC 5.2.2	no_ssps=1	0
8541599	8539753	deserializing json object with nested lists	public class MyObjectConvert : JavaScriptConverter {\n\n  public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(MyObjectConvert) }; }  \n\n  public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {\n\n    int TheID;\n    MyObject TheObject = new MyObject();\n\n    int.TryParse(serializer.ConvertToType<string>(dictionary["TheID"]), out TheID))\n    TheObject.ID = TheID;\n\n    if (dictionary.ContainsKey("ListOfMyNestedObject1"))\n    {\n      serializer.RegisterConverters(new JavaScriptConverter[] { new MyNestedObject1Convert() });\n      var TheList = serializer.ConvertToType<List<MyNestedObject1>>(dictionary["ListOfMyNestedObject1"]);\n      TheObject.ListOfMyNestedObject1 = TheList\n    }\n\n    return TheObject;\n    }\n}	0
1176347	1176276	How do I improve the performance of code using DateTime.ToString?	public static string FormatDateTime(DateTime dt)\n{\n    char[] chars = new char[21];\n    Write2Chars(chars, 0, dt.Day);\n    chars[2] = '.';\n    Write2Chars(chars, 3, dt.Month);\n    chars[5] = '.';\n    Write2Chars(chars, 6, dt.Year % 100);\n    chars[8] = ' ';\n    Write2Chars(chars, 9, dt.Hour);\n    chars[11] = ' ';\n    Write2Chars(chars, 12, dt.Minute);\n    chars[14] = ' ';\n    Write2Chars(chars, 15, dt.Second);\n    chars[17] = ' ';\n    Write2Chars(chars, 18, dt.Millisecond / 10);\n    chars[20] = Digit(dt.Millisecond % 10);\n\n    return new string(chars);\n}\n\nprivate static void Write2Chars(char[] chars, int offset, int value)\n{\n    chars[offset] = Digit(value / 10);\n    chars[offset+1] = Digit(value % 10);\n}\n\nprivate static char Digit(int value)\n{\n    return (char) (value + '0');\n}	0
26021260	25939660	Can't find panel control inside formview Edit mode with Gridview event	protected void fvWasteCollected_DataBound(object sender, EventArgs e)\n    {\n        FormView formview = fvWasteCollected;\n        FormViewRow row = fvWasteCollected.Row;\n        DataRowView rowview = (DataRowView)fvWasteCollected.DataItem;\n        Panel pnlOtherContractor = (Panel)fvWasteCollected.FindControl("pnlOtherContractor2");\n\n        if (fvWasteCollected.CurrentMode == FormViewMode.Edit)\n        {\n            var s_contractorId = rowview["MRWContractorId"].ToString();\n            if (s_contractorId == "0")\n            {\n                pnlOtherContractor.Visible = true;\n            }\n            else\n            {\n                pnlOtherContractor.Visible = false;\n            }\n        }\n\n    }	0
4108355	4108290	c# looping through datatable, changing data	foreach (DataRow row in MyDataTable.Rows)\n{\n row["columnNameHere" Or index] = value;\n}	0
19962470	19962388	Enable postsharp in production	if (ConfigurationManager.AppSettings["YourSetting"] == "some_value")\n{\n    args.FlowBehavior = FlowBehavior.Default;\n    return;\n}	0
23447693	23404251	Update all cells of a datatable in one go in c#	var now = DateTime.Now;\nforeach(DataRow dr in oDT.Rows)\n{\n    dr["ModifiedOn"] = now;\n}	0
7744365	7744357	Linq-to-SQL - take not working	var members = (from member in db.Stops_edited_smalls\n              where Math.Abs(Convert.ToDouble(member.Latitude)\n                  - curLatitutde) < 0.05\n              && Math.Abs(Convert.ToDouble(member.Longitude)\n                  - curLongitude) < 0.05\n              select member).Take(25);	0
32100119	32100024	Saving Specific line of richTextBox in a Variable C#	int charNum = richTextBox1.Find(find);\nif (charNum > -1) {\n  lineText = richTextBox1.Lines[richTextBox1.GetLineFromCharIndex(charNum)];\n}	0
34496304	34495910	How to get back the focus on popup, after loosing it in WPF?	private void Popup_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n{\n    this.Focus();\n}	0
27729294	27729274	how return an IEnumrable<> of my customized model?	public static IEnumerable<AttachLabel> GetAttachLabel()\n{\n    Entities db = new Entities();\n\n    return from item in db.tblAttachLabels select new AttachLabel()\n    {\n        ID = item.ID,\n        Text = item.Text\n    };\n}	0
14487380	13869024	Cursor lines in chart	private void chData_MouseMove(object sender, MouseEventArgs e)\n{\n    Point mousePoint = new Point(e.X, e.Y);\n\n    Chart.ChartAreas[0].CursorX.SetCursorPixelPosition(mousePoint, true);\n    Chart.ChartAreas[0].CursorY.SetCursorPixelPosition(mousePoint, true);\n\n    // ...\n}	0
32849142	32848888	How to only allow single words to be input using console.readline() in c#?	string word;\ndo\n{\n    Console.WriteLine("Enter a word to encode");\n    word = Console.ReadLine();\n} while (word.Contains(' '));\nvar encodedMessage = word.Substring(1) + word[0]  + "ay";\nConsole.WriteLine("Your string encodes to backslang as " + encodedMessage);	0
21197458	21197405	C# Password generator, generate more than one password	for (; totalPasswords > 0; totalPasswords--)\n{\n    for (var i = length; i > 0; i--)\n    {\n        sw.Write(minatecken[rnd.Next(0, 62)]);\n    }\n    richTextBoxPasswords.Text += sw + "\n";\n}	0
10017105	10017066	Entire web page source code appended to end of XML document	Response.CompleteRequest()	0
32871710	32358581	ElasticSearch: Querying a field that's an array of objects	.Term("person.name", "john")	0
20417146	20416231	if text box array how to add to listbox	int seatnum = int.Parse(textBox1.Text);\n         Seat = new int[15];\n        if (textBox1.Text != "")\n        {\n            Seat[seatnum - 1] = seatnum;\n        }\n        for (int i = 0; i < 15; i++)\n        {\n            if (Seat[i] != 0)\n            {\n                listBox1.Items.Add(textBox1.Text);\n            }\n        }	0
10276552	10275820	Get ElapsedTime From Trace	using (Tracer tracer = new Tracer("General"))\n{\n    FieldInfo fieldInfo = typeof(Tracer).GetField("stopwatch", BindingFlags.NonPublic | BindingFlags.Instance);\n    var sw = fieldInfo.GetValue(tracer) as Stopwatch;\n    Console.WriteLine(sw.ElapsedMilliseconds);\n}	0
22803389	22802369	How to pass mulitple querystring value in MVC 4	return RedirectToAction("Action","Controller", new {id=1,name="test",......})	0
6873489	6873306	C++ to C# Marshaling	int size = sizeof(int) * tempData.Length;\nIntPtr ptrData = Marshal.AllocHGlobal(size);\nMarshal.Copy(tempData, 0, ptrData, size);	0
2458328	2443554	Way to know if two partitions are in one physical hard disk without WMI?	var x = from di in DriveInfo.GetDrives()\n        where (di.DriveType == DriveType.Fixed)\n        select di;\n\nforeach (DriveInfo di in x)\n{\n    // Call DeviceIoControl() using the partition name from di.Name and the IOCTL_STORAGE_GET_DEVICE_NUMBER  control code to retrieve the physical disk\n}	0
26814907	26797199	Log execution of Quartz.Net jobs in a custom format	quartz.plugin.triggHistory.jobToBeFiredMessage = *** Job {1}.{0} fired (by trigger {4}.{3}) at: {2:HH:mm:ss MM/dd/yyyy}\nquartz.plugin.triggHistory.jobSuccessMessage = *** Job {1}.{0} execution complete at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}\nquartz.plugin.triggHistory.jobFailedMessage = *** Job {1}.{0} execution failed at {2:HH:mm:ss MM/dd/yyyy} and reports: {8}	0
23964445	23963619	How to search through XML to find bad nodes	var errors = new List<string>();\nvar schemaSet = new XmlSchemaSet();\nschemaSet.Add("", XmlReader.Create(new StringReader(Properties.Resources.NameOfXSDResource)));\ndocument.Validate(schemaSet, (sender, args) =>\n    {\n        errors.Add(args.Message);\n    }\n);	0
16552702	16552634	How to get linq to transform data from one form to another	var data = paymentHeaders.GroupBy(x => x.Payee)\n               .Select(g => new { Payee = g.Key, Headers = g.ToList() })\n               .ToList();\n\nforeach(var d in data)\n{\n   Console.WriteLine("Payee {0} has {1} headers", d.Payee, d.Headers.Count);\n}	0
12870792	12870526	Data list item data bound not working properly	If e.Item.ItemType = ListItemType.Item Or _\n             e.Item.ItemType = ListItemType.AlternatingItem Then\n\n//Your Code Here\n\nEnd If	0
1939456	1939443	Defining two dimensional Dynamic Array with different types	public class MyClass\n{\n    public string ControlName {get;set;}\n    public bool MyBooleanValue {get;set;}\n}\n\npublic MyClass[] myValues=new MyClass[numberOfItems];	0
615314	615310	How do you return a copy of original List<T> from Func<T, TResult>?	foreach (var nodeId in _AuthenticatedNodes.Keys.ToList())\n    ...	0
2235623	2235571	How to extract the most common YEAR from an array of DateTime objects using LINQ	int commonYear = dates.GroupBy(date => date.Year)\n                      .OrderByDescending(g => g.Count())\n                      .First().Key;	0
13745476	13745433	connected host has failed to respond, timeout expired	Command.CommandTimeout = 300;	0
20517110	20516835	Is there a COM type library for Windows Core Audio	namespace NAudio.CoreAudioApi.Interfaces\n{\n    /// <summary>\n    /// n.b. WORK IN PROGRESS - this code will probably do nothing but crash at the moment\n    /// Defined in AudioClient.h\n    /// </summary>\n    [Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"), \n        InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n    internal interface IAudioClient\n    {\n        [PreserveSig]\n        int Initialize(AudioClientShareMode shareMode,\n            AudioClientStreamFlags StreamFlags,\n            long hnsBufferDuration, // REFERENCE_TIME\n            long hnsPeriodicity, // REFERENCE_TIME\n            [In] WaveFormat pFormat,\n            [In] ref Guid AudioSessionGuid);	0
7996590	7996425	C# - Convert Jpg to Png with index transparency	Bitmap b = Image.FromFile(/*Image*/);\nb.MakeTransparent(Color.White);\ng.DrawImage(b, new Point(0, 0));	0
9420312	9420177	I have data in my dataset, but it's not showing up in my reportviewer?	ASP.NET controls require you to execute the DataBind method on the control to indicate\nthat the data is ready to be rendered. If you don???t execute the DataBind method, the control won???t render. When executing the DataBind method on a control, the control is obliged to call the DataBind method on its child controls. This means that you can execute the DataBind method on the Web form, and it will call the DataBind method on all its controls	0
19033877	19033823	Multidimensional arrays in C# parametrized on dimensions	System.Array.CreateInstance(Type, params int[])	0
26742039	26742007	How do I get request parameters in ASP.NET MVC	string strParam = HttpContext.Current.Request["someParameter"];	0
17839090	17680454	Getting the same BLOB in C# that i get with AppendChunk in VB6	private void AddDocument(string photoFilePath)\n    {\n        //GetFileStream() is a custom function that converts the doc into a stream\n        byte[] photo = GetFileStream(photoFilePath);\n        var conn = new SqlConnection(@"ConnectionString here");\n        var updPhoto = new SqlCommand("UPDATE DT_Document "\n                   + "SET DocumentData = @Photo WHERE Id=399", conn);\n        updPhoto.Parameters.Add("@Photo", SqlDbType.Image, photo.Length).Value = photo;\n        conn.Open();\n        updPhoto.ExecuteNonQuery();\n        conn.Close();\n    }	0
1349448	1349364	Rhino Mocks - Set a property if a method is called	callMonitor.Expect(x => x.HangUp())\n.WhenCalled(invocation => callMonitor.InCall = false);	0
20628129	20627474	How to Integrate Autofac and Log4Net with ASP.NET Web API 2 Application	IocContainer container = // code to create your container\nGlobalConfiguration.Configuration.DependencyResolver = \n    new AutofacWebApiDependencyResolver(container);	0
12732173	12732133	Shortening of multiple filenames' which are chosen by user through dialogBox	filesRepNames = dialF.FileNames.Select(p => Path.GetFileName(p))\n                                .ToList();	0
27098293	26751674	How to create a text file name with textbox value?	private void button2_Click(object sender, EventArgs e)\n    {\n        button2.Text = "SAVE";      \n        var files = Directory.GetFiles(@"C:\\Users\\Apple\\Desktop\\proj").Length;\n        string fileName = textBox1.Text.Substring(0, 3) + -+ ++files + ".txt";\n        string path2 = Path.GetFullPath("C:\\Users\\Apple\\Desktop\\proj");\n        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\n        string var = Path.Combine(docPath, path2);\n        string var1 = Path.Combine(var, fileName);\n        using (StreamWriter writer = new StreamWriter(var1))\n        {\n            string var6 = textBox1.Text;\n            string var7 = "                 ";\n            string var8 = textBox2.Text;\n\n            string var9 = string.Concat(var6, var7, var8);\n            writer.WriteLine(var9);\n\n        }\n\n        MessageBox.Show("File created");	0
27152205	27151963	C# Trying to serialize an ArrayList into an XML file	public class ClientInfo // you meant "class" right? since that clearly isn't a "value"\n{\n    public string Name {get;set;} // use a property; don't use a name prefix\n    public string Password {get;set;} // please tell me you aren't storing passwords\n}\n\nList<ClientInfo> clientList = new List<ClientInfo>(); // typed list\n\npublic static void Serialize(List<ClientInfo> input) // typed list\n{\n    if(input == null) throw new ArgumentNullException("input");\n    XmlSerializer serializer = new XmlSerializer(typeof(List<ClientInfo>));\n    using(TextWriter sw = new StreamWriter("users.txt")) // because: IDisposable\n    {\n        serializer.Serialize(sw, input);\n        sw.Close();\n    }\n}	0
23275332	23253881	EntityFramework Multiple NavigationProperties to the same table	public partial class TableA\n{\n    public static readonly TableB DefaultTableBValue = new TableB(null);\n\n    public TableA()\n    {\n        this.First = TableA.DefaultTableBValue;\n        this.Second = TableA.DefaultTableBValue;\n        this.Third = TableA.DefaultTableBValue;\n    }\n}\n\npublic partial class TableB\n{\n    public TableB(string value)\n    {\n        this.Value = value;\n    }\n}	0
2257333	2243547	How to read text that is present in text box of MS word document?	Dim Doc As Document\nDim Range As Range\n\n' Load document\n\nSet Range = Doc.StoryRanges(wdTextFrameStory)\nDo Until Range Is Nothing\n    ' Do something with Range.Text\n    Set Range = Range.NextStoryRange\nLoop	0
9035023	9034721	Handling multiple requests with C# HttpListener	private void CreateLListener() {\n    //....\n    while(true) {\n        ThreadPool.QueueUserWorkItem(Process, listener.GetContext());    \n    }\n}\nvoid Process(object o) {\n    var context = o as HttpListenerContext;\n    // process request and make response\n}	0
33146593	33146505	ListBox mulitple Selection get all selected values	var lst = listBox1.SelectedItems.Cast<DataRowView>();\nforeach (var item in lst)\n{\n     MessageBox.Show(item.Row[0].ToString());// Or Row[1]...\n}	0
4889513	4889298	COM interop: How can I get the CCW from an LPDISPATCH?	Type type = Type.GetTypeFromProgID("WinFax.Attachments");\n    if (type == null)\n          throw new ArgumentException("WinFax Pro is not installed.");\n    Object comObject = Activator.CreateInstance(type);  \n    Object o2 = type.InvokeMember("MethodReturnsLpdispatch",\n                                     BindingFlags.InvokeMethod,\n                                     null,\n                                     comObject,\n                                     null);\n    Type t2 = Type.GetTypeFromProgID("WinFax.Attachment"); // different ProgId !!\n    Object x = t2.InvokeMember("MethodOnSecondComObject",  \n                                     BindingFlags.InvokeMethod,\n                                     null,\n                                     o2,\n                                     null);	0
15528704	15528599	C# - List all .aspx pages in a domain	wget --recursive --http-user=user --http-password=password --accept=.aspx www.hostname.com	0
22137952	22134375	How can I declare and set Cursor in Android written by C#	var cursor = context.ContentResolver.Query(\n            MediaStore.Audio.Media.ExternalContentUri,\n            new string[] \n            { \n                /* insert fields here */ \n            }, \n            "1=1",\n            null, \n            null);	0
19599850	19599812	Issue with joining tables in LINQ when needing a left outer join type	from cn in Clients_Network\njoin c in Clients on cn.networkClientID equals c.networkClientID into g\nfrom cc in g.DefaultIfEmpty()\nselect new { cn, cc }	0
8478957	8478939	Attached Properties Add With Code	OwningClass.SetPropertyName(someInstance, someValue);	0
21035878	21035849	ASP.NET Web API POST parameter is null	public class PlayerEntry\n{\n    public string userID { get; set; }\n    public string userName { get; set; }\n    public int userProgress { get; set; }\n}	0
66595	66475	How can I get Column number of the cursor in a TextBox in C#?	int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);\nint column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);	0
1299831	1299727	How do you declare a by-reference parameter variable for use in a Linq query?	var qry = from mc in MyClasses.FunctThatReturnsAnIEnumerable()\n          let result = mc.MyMethod() //this returns the struct\n          select new {mc, result.BoolVal, result.DateVal};	0
5246418	5246343	Regular expression for validating phone	"^[0-9]+(-[0-9]+)*$"	0
1885519	1885490	C# file input from text file	public void Numbers(string filename)\n    {\n        List<float> myList = new List<float>();     \n\n        string input;\n\n        if (System.IO.File.Exists(filename) == true)\n        {\n            System.IO.StreamReader objectReader;\n            objectReader = new System.IO.StreamReader(filename);\n            while ((input = objectReader.ReadLine()) != null)\n            {\n                Single output;\n                if (Single.TryParse(input, out output ))\n                {\n                    myList.Add(output);\n                }\n                else\n                {\n                   // Huh? Should this happen, maybe some logging can go here to track down why you couldn't just use the .Convert()\n                }\n            }\n            objectReader.Close();\n\n        }\n        else\n        {\n            MessageBox.Show("No Such File" + filename);\n        }\n    }	0
26638923	26623145	Exception: EOF in Header occuring while extracting zip from isolated storage	Stream.Position =0;	0
6477569	6477564	C# - How to clear a ListBox's values	listBox.Items.Clear();	0
10497864	10497727	Get rectangle bounds from string	RectangleConverter r = new RectangleConverter();\n\nvar rectangleAsString= r.ConvertToString(this.DesktopBounds);\n\nvar rectangle = (Rectangle)r.ConvertFromString(rectangleAsString);	0
2736822	2736303	Uploading file with metadata	SPFile file = myfolder.Files.Add(System.IO.Path.GetFileName(document.PostedFile.FileName);\nSPListItem item = file.Item;\nitem["My Field"] = "Some value for your field";\nitem.Update()	0
33670330	33669666	formatting of text in p tag not formatting?	white-space: pre-line	0
31570575	31570411	How do I create a static "header" in the Console C#?	Console.SetCursorPosition	0
21396178	21396043	Select with NOT IN with entity framework	var friendIds = db.users_friends.Where(f => f.userid == 1).Select(f => f.friendid);\nvar friends = db.Friends.Where(f => !friendIds.Contains(f.Id) &&\n                                      (f.Alias.Contains(query) ||       \n                                      f.FirstName.Contains(query) || \n                                        f.LastName.Contains(query)))\n                         .Select(f => new FriendModel() { ... })\n                         .OrderBy(f => f.Alias)\n                         .ToList();	0
1363775	1363748	Passing Args from Method to Click Event Method in C#	private void btnViewFile_Click(object sender, EventArgs e) \n{               \n    lblOutputPath.Text = GetFileNames().ToString();    \n}    \n\nprivate StringBuilder GetFileNames() \n{        \n    StringBuilder sb = new StringBuilder();        \n    string[] fileNames = Directory.GetFiles(Dir);        \n    foreach (string s in fileNames)            \n        sb.Append(s);        \n    return sb;    \n}	0
2300731	2300726	How to exit a process from Window Service in C#	Process.CloseMainWindow()	0
9740783	9740719	Writing a value into a struct var member with reflection do not works but it does for classes	object obj = instance; // box\nblah.SetValue(obj, value); // mutate inside box\ninstance = (YourType)obj; // unbox	0
5173091	5173062	What is a fastest way to do search through xml	XDocument doc = XDocument.Load("myfile.xml");\nvar addresses = from address in doc.Root.Elements("address")\n                where address.Element("firstName").Value.Contains("er")\n                select address;	0
18551453	18551222	Combine multiple interfaces into one at runtime in C#	public interface A\n{\n    void DoA();\n}\n\npublic interface B\n{\n    void DoB();\n}\n\npublic class IInterceptorX : IInterceptor\n{\n    public void Intercept(IInvocation invocation)\n    {\n        Console.WriteLine(invocation.Method.Name + " is beign invoked");\n    }\n}\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var generator = new ProxyGenerator();\n\n        dynamic newObject = generator.CreateInterfaceProxyWithoutTarget(typeof(A), new Type[] { typeof(B) }, new IInterceptorX());\n\n        Console.WriteLine(newObject is A); // True\n\n        Console.WriteLine(newObject is B); // True\n\n        newObject.DoA(); // DoA is being invoked\n    }\n}	0
21364086	21352549	changing an element of project file by xml means	XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";\n    var outputNodes = xDoc.Root.Descendants(ns + "OutputPath");	0
5988768	5988523	Loop week based on culture info	DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;\n        for (int dayIndex = 0; dayIndex < 7; dayIndex++)\n        {\n            var currentDay = (DayOfWeek) (((int) firstDay + dayIndex) % 7);\n\n            // Output the day\n            Console.WriteLine(dayIndex + " " + currentDay);\n        }	0
29942256	29941787	Reverse a multidimensional array 4 times	var result = ArrayReflection(scoreBoard);       \n\npublic static T[,] ArrayReflection<T>(T[,] arr)\n{\n    // number of rows in array\n    int m = arr.GetLength(0);\n    // number of columns in array\n    int n = arr.GetLength(1);\n    var res = new T[m*2, n*2];\n\n    for(int r=0; r<m; r++)\n        for(int c=0; c<n; c++)\n    {\n        res[r,c] = arr[r,c];\n        res[r,n + c] = arr[r, n - c - 1];\n        res[r + m,c] = arr[m - r - 1, c];\n        res[r+m,n+c] = arr[m - r - 1, n - c - 1];   \n    }\n\n    return res;     \n}	0
796776	796654	How can I prevent the keydown event of a form in C# from firing more than once?	namespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        private bool _keyHeld;\n        public Form1()\n        {\n            InitializeComponent();\n            this.KeyUp += new KeyEventHandler(Form1_KeyUp);\n            this.KeyDown += new KeyEventHandler(Form1_KeyDown);\n            this._keyHeld = false;\n        }\n\n        void Form1_KeyUp(object sender, KeyEventArgs e)\n        {\n            this._keyHeld = false;\n        }\n\n        void Form1_KeyDown(object sender, KeyEventArgs e)\n        {\n            if (!this._keyHeld)\n            {\n                this._keyHeld = true;\n                if (this.BackColor == Control.DefaultBackColor)\n                {\n                    this.BackColor = Color.Red;\n                }\n                else\n                {\n                    this.BackColor = Control.DefaultBackColor;\n                }\n            }\n            else\n            {\n                e.Handled = true;\n            }\n        }\n    }   \n}	0
6299481	6296839	How to calculate changes of nullable numbers with Linq	static IEnumerable<double?> GetChanges(IEnumerable<double?> x)\n{\n    double? previous = x.First();\n    return x.Skip(1).Select(d =>\n              { double? result = d - previous; previous = d; return result; });\n}	0
14205210	14203730	Open browser only if page not displayed	SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();\n\nstring filename;\n\nforeach (SHDocVw.InternetExplorer ie in shellWindows)\n{\n    filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();\n\n    if (filename.Equals("iexplore"))\n    {\n        try\n        {\n            Uri test = new Uri(ie.LocationURL);\n        }\n        catch\n        {\n\n        }\n    }\n}	0
9155746	9155640	failed to call event from gridview linkbutton	protected void grdvResults_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.DataItem != null)\n        {\n           ((LinkButton)e.Row.FindControl("lnkname")).PostBackUrl = "~/somewhere/" + Session["path"].ToString();\n        }\n    }	0
8246053	8245926	The current SynchronizationContext may not be used as a TaskScheduler	[SetUp]\npublic void TestSetUp()\n{\n  SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());\n}	0
12429256	12429131	Use DateTime Format Strings in a Custom DateTimePickerFormat	picker.CustomFormat = DateTimeFormatInfo.ShortDatePattern +  DateTimeFormatInfo.LongTimePattern	0
8013888	8013745	C# mysql Execute Reader with parameters Input string was not in a correct format	MySqlCommand cmd = new MySqlCommand("Select * from login where username=?username and password=?password", cn);\n\ncmd.Parameters.Add("?username", OdbcType.VarChar);\ncmd.Parameters["?username"].Value = this.Login1.UserName;\n\n...	0
16960991	16960112	Deserialize a json object with an array fails with Default constructor not found for type System.String[]	public List<string> ParentProductIds {\n    get;\n    set;	0
6131419	6100703	C# Facebook SDK Authorization Flow- how to redirect back to page?	[CanvasAuthorize(ReturnUrlPath="enter-url-here")]	0
17055094	17054989	All Common Substrings Between Two Strings	public static string [] CommonString(string left, string right)\n    {\n        List<string> result = new List<string>();\n        string [] rightArray = right.Split();\n        string [] leftArray = left.Split();\n\n        result.AddRange(rightArray.Where(r => leftArray.Any(l => l.StartsWith(r))));\n\n        // must check other way in case left array contains smaller words than right array\n        result.AddRange(leftArray.Where(l => rightArray.Any(r => r.StartsWith(l))));\n\n        return result.Distinct().ToArray();\n    }	0
1466655	1466487	How to check name of Domino Server to which lotus notes is configured? using C#	Domino.NotesSessionClass _lotesNotesSession = new Domino.NotesSessionClass();\n//Initializing Lotus Notes Session\n_lotesNotesSession.Initialize( "my_password" );\nDomino.NotesDatabase _serverDatabase = _lotesNotesSession.GetDatabase( "some_server", "names.nsf", false );\nif (_serverDatabase == null){\n   System.Console.Writeline("Can not connect to server.");\n}	0
9011601	9010414	double multidimensional array,in c++, the best way	class StateSymbols\n{\npublic:\n    StateSymbols(unsigned int states, unsigned int symbols) :\n    m_states(states),\n    m_stateSymbols(states * symbols)\n    {\n    }\n\n    double get(unsigned int state, unsigned int symbol) const\n    {\n        return m_stateSymbols[(m_states * symbol) + state];\n    }\n\nprivate:\n    const unsigned int m_states;\n    std::vector<double> m_stateSymbols; \n};	0
23780756	23780605	How implement Pell number calculation in c#	return 2 * calcPell(input - 1) + calcPell(input -2);	0
1636596	1636464	Need help turning this LINQ expression into LINQ statement	var pubBooks =\n            SampleData.Publishers.GroupJoin(\n                SampleData.Books,\n                pub => pub.Name,\n                book => book.Publisher.Name,\n                (pub, pubbks) => new\n                                     {\n                                         Publisher = pub.Name,\n                                         Books =\n                                     from b in pubbks\n                                     select b.Title\n                                     });	0
26098063	26097800	How to write PNG file in c#	//Read All Bytes\nbyte[] fileBytes = File.ReadAllBytes(openFileDialog1.FileName.ToString());\n\n//Data that needs to added, converted to bytes, Better off making a function for this\nString str = "Data to be added";\nbyte[] newBytes = new byte[str.Length * sizeof(char)];\nSystem.Buffer.BlockCopy(str.ToCharArray(), 0, newBytes, 0, newBytes.Length);\n\n//Add the two byte arrays, the file bytes, the new data bytes\nbyte[] fileBytesWithAddedData = new byte[ fileBytes.Length + newBytes.Length ];\nSystem.Buffer.BlockCopy(fileBytes, 0, fileBytesWithAddedData, 0, fileBytes.Length);\nSystem.Buffer.BlockCopy( newBytes, 0, fileBytesWithAddedData, fileBytes.Length, newBytes.Length );\n\n//Write to new file\nFile.WriteAllBytes(@"D:\result.png", fileBytesWithAddedData);	0
28378702	28378669	How do I include a timer in a universal windows app with c#	Windows.UI.Xaml	0
13332989	13332527	How to display List<> items in a DataGrid cell?	public Recipient Recipient\n{\n    get { return _Recipient; }\n    set\n    {\n        _Recipient = value;\n        NotifyPropertyChanged("Recipient");\n        NotifyPropertyChanged("MailingList");\n    }\n} private Recipient _Recipient\n\npublic EntityCollection<MailingList> MailingList\n{\n    get { return _MailingList; }\n    set\n    {\n        _MailingList= value;\n        NotifyPropertyChanged("MailingList");\n    }\n} private EntityCollection<MailingList> _MailingList	0
27181613	27140288	How to draw at top left of metaFile	var img = new Metafile(path, g.GetHdc(), new Rectangle(0, 0, 101, 101), MetafileFrameUnit.Pixel);	0
25120556	25119984	update a table view with new data on click of a button	Submit.TouchUpInside += (object sender, EventArgs e) => {\n    CLGeocoder latlng = new CLGeocoder ();\n    latlng.GeocodeAddress (Ziptext.Text, HandleCLGeocodeCompletionHandler);\n\n     // add code here to update the SpecAdresses list with the data you want to display\n\n    Zipcode.ReloadData() // refresh the table\n};	0
13165678	13165625	Efficient way to determine highest value (with or without offset)	float highestRawVal = float.MinVal;\nfloat offset_ForHighestRawVal = float.MinVal;\nfor(...)\n{\n    float rawValue;\n    float offset;\n    sortedList.Add(rawValue + offset, index);\n    if(highestRawVal < rawVal)\n    {\n        highestRawVal = rawValue;\n        offset_ForHighestRawVal = offset;\n    }\n}\n\nif (highestRawVal + offset_ForHighestRawVal == sortedList[0])\n    Console.WriteLine("They Match");	0
3920589	3920391	Prism v4 Loading modules on demand with DirectoryModuleCatalog	[Module(ModuleName = "MyModule", OnDemand = true)]\npublic class MyModule : IModule\n{\n   ...\n}	0
22329494	22302329	Accessing Controls in a Thread in Windows CE C# Program	delegate void SetTextCallback(string text);\n    public void addLog(string text)\n    {\n        // InvokeRequired required compares the thread ID of the\n        // calling thread to the thread ID of the creating thread.\n        // If these threads are different, it returns true.\n        if (this.txtLog.InvokeRequired)\n        {\n            SetTextCallback d = new SetTextCallback(addLog);\n            this.Invoke(d, new object[] { text });\n        }\n        else\n        {\n            txtLog.Text += text + "\r\n";\n            //scroll to updated text\n            txtLog.SelectionLength = 0;\n            txtLog.SelectionStart = txtLog.Text.Length - 1;\n            txtLog.ScrollToCaret();\n        }\n    }	0
17185716	17185507	Html Agility Pack: Get an HTML document from an Internet resource and saves it to the specified file	const string url = "http://google.com";\n\nHtmlWeb page = new HtmlWeb();\nHtmlDocument document = page.Load(url);\npage.Get(url, "/");\ndocument.Save("out.html");	0
31354230	31354077	C# Adding an array of RichTextBoxes to an array of TabPages in a for loop	public partial class Form1 : Form\n{\n    public static TabPage[] TabPages = new TabPage[20];\n    public static RichTextBox[] TextBoxes = new RichTextBox[20];\n    public Form1()\n    {\n        InitializeComponent();\n\n        tabControl1.TabPages.Clear();\n        for (int x = 0; x < 19; x++)\n        {\n            TabPages[x] = new TabPage();\n\n            TabPages[x].Controls.Add(TextBoxes[x]);    //ERROR HERE\n            //Object reference not set to an instance of an object.\n            tabControl1.TabPages.Add(TabPages[x]);\n        }\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n    }\n}	0
13821215	13821127	Linq Query to Compare with List of string values	var model = (from xx in Db.ItemWeedLogs\n                     where uids.Contains(xx.ItemNo)\n                     select xx).ToList();	0
10118384	10104444	encapsulation of a sub-namespace in c#	// what you have now:\nnamespace DAL.SQLServerDal\n{\n    public class A {}\n    public class B {}\n}\n\n// in other assembly\nusing DAL.SQLServerDal ; // ok\nnew A () ; // ok\n\n// with internal classes:\nnamespace DAL.SQLServerDal\n{\n    internal class A {}\n    internal class B {}\n}\n\n// in other assembly\nusing DAL.SQLServerDal ; // ok\nnew A () ;               // error: A is inaccessible due to protection level\n\n// what I propose:\nnamespace DAL\n{\n    internal static class SQLServerDal\n    {\n        public class A {}\n        public class B {}\n    }\n}\n\n// in other assembly\nusing DAL.SQLServerDal ; // error: namespace DAL.SQLServerDal does not exist	0
6722436	6722367	Where is the most convenient place to validate a property length of a saveable object?	var ctx = new ValidationContext(obj, null, null);\nValidator.ValidateObject(obj, ctx);	0
2823866	2823200	Make square image	public static Image PadImage(Image originalImage)\n{\n    int largestDimension = Math.Max(originalImage.Height, originalImage.Width);\n    Size squareSize = new Size(largestDimension, largestDimension);\n    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);\n    using (Graphics graphics = Graphics.FromImage(squareImage))\n    {\n        graphics.FillRectangle(Brushes.White, 0, 0, squareSize.Width, squareSize.Height);\n        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;\n        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;\n\n        graphics.DrawImage(originalImage, (squareSize.Width / 2) - (originalImage.Width / 2), (squareSize.Height / 2) - (originalImage.Height / 2), originalImage.Width, originalImage.Height);\n    }\n    return squareImage;\n}	0
5895560	5895209	How to change UIButton HighLight Color using Monotouch?	btn.SetImage(UIImage.FromBundle("Images/btnHighlighted.png"), UIControlState.Highlighted);	0
2607715	2607508	How to control docking order in WinForms	myControl.SendToBack();\nmyControl.BringToFront();	0
3478316	3477971	Is there a way to setup a Func with a generic object parameter?	converters.Add( typeof( StampAnnotation ), \n    tool => ToTextStampAnnotationMark( (StampAnnotation)tool );	0
3249269	3249205	How to Clicking "X" in Form, will not close it but hide it	Private CloseAllowed As Boolean\n\n    Protected Overrides Sub OnFormClosing(ByVal e As System.Windows.Forms.FormClosingEventArgs)\n        If Not CloseAllowed And e.CloseReason = CloseReason.UserClosing Then\n            Me.Hide()\n            e.Cancel = True\n        End If\n        MyBase.OnFormClosing(e)\n    End Sub\n\n    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click\n        CloseAllowed = True\n        Me.Close()\n    End Sub	0
30763610	30742268	Dynamic queryable parameter to database interface	ParameterExpression numParam = Expression.Parameter(typeof(int), "num");\nConstantExpression five = Expression.Constant(5, typeof(int));\nBinaryExpression numLessThanFive = Expression.LessThan(numParam, five);\nExpression<Func<int, bool>> lambda1 = Expression.Lambda<Func<int, bool>>(numLessThanFive, new ParameterExpression[] { numParam });	0
9264304	9263965	How to calculate font size of TextBlock to fill in Canvas?	double h = canvas1.Height / 2; \n\n foreach (var item in textBlocks)\n {\n    if (item is TextBlock)\n    {\n         (item as TextBlock).FontSize = h;\n    }\n }	0
34141079	34141005	How do I get two numbers between two words (C#)	Building(\d+)Floor(\d+)	0
26496855	26494050	EF get list of records in runtime from Type	public static void loopAllEntities(DbContext dbContext)\n    {\n        List<Type> modelListSorted = ModelHelper.ModelListSorted();\n\n        foreach (Type type in modelListSorted) \n        {\n            var records = dbContext.Set(type);\n            // do something with the set here\n        }\n    }	0
7154409	7154389	how to construct a list using Linq, while doing something else?	var c = a.Sum();\nvar b = a.ToList();\nforeach(var item in a)\n{\n    DoSomething();\n}	0
21890373	21888397	compare model value in controller with database value	var origTeacherAttr = db.TeacherAttrs.Find(ta.ID);\n\nif(origTeacherAttr.DMTeacherAttr==ta.DMTeacherAttr)\n{\n//Do something\n}	0
17998100	17998003	Can't read from database using Entity Framework 5	using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\stephen.carmody\Desktop\NewText.txt", true))\n    {\n        foreach (var row in query)\n        {\n            file.WriteLine("{0} | {1} | {2} | {3} | {4} | {5}",\n                row.STRATRULEKEY,\n                row.CODETYPE, \n                row.CODEVALUE, \n                row.SYSTEMID, \n                row.CODESETKEY, \n                row.PAYMENTYEAR);\n        }\n    }	0
9053785	9053764	MVVM INotifyPropertyChanged conflict with base class PropertyChange	protected virtual void RaisePropertyChanged(string propertyName);	0
33255939	33254678	How to clone and remove unselected rows in DataGridView?	'CLONE COLUMNS ONLY'\nDim dgv As New DataGridView\nFor Each dgvCol As DataGridViewColumn In CtrlDataGridView1.Columns\n    dgv.Columns.Add(New DataGridViewColumn(dgvCol.CellTemplate))\nNext\n\n'COPY SELECTED / UNSELECTED ROWS AS PER YOUR REQUIREMENT'\nFor Each dr As DataGridViewRow In CtrlDataGridView1.Rows\n    If dr.Selected Then\n    'OR If Not dr.Selected Then'\n        dgv.Rows.Add(dr.Clone)\n    End If\nNext	0
31722359	31708356	icsharpcode SharpZipLib is not setting password correctly on zip file	file.Password = password;\n\nfile.UseZip64 = UseZip64.On;\n\nfile.CommitUpdate();\nfile.Close();	0
1536740	1536722	How to Create a search function with nhibernate, linq?	var query==...\nif (filter.Name.Length>0)\n   query=query.Where(name=...)\nif (filter.Email.Length>0)\n   query=query.Where(email=...)	0
2589176	2589150	C# Implementing a custom stream writer-esque class	public sealed class StreamManipulator\n{\n    private readonly Stream _backingStream;\n\n    public StreamManipulator(Stream backingStream)\n    {\n        _backingStream = backingStream;\n    }\n\n    public void Write(string text)\n    {\n        var buffer = Encoding.UTF8.GetBytes(text);\n        _backingStream.Write(buffer, 0, buffer.Length);        \n    }\n}	0
13681005	13680039	Sorting results that have been posted by another view	[HttpPost]\npublic ActionResult Index(String carMake, String carModel)\n{\n   //Redirect to SearchResults. You can do this from client as well.\n   return RedirectToAction("SearchResult",  \n                new { make = carMake, model = carModel });\n}\n\n//Add your filter and order code here\npublic ActionResult SearchResult(String make, String model)\n{\n     var cars = from d in db.Cars\n                select d;\n\n    if (!String.IsNullOrEmpty(make))\n    {\n        if (!carMake.Equals("All Makes"))\n        {\n            cars = cars.Where(x => x.Make == make);\n        }\n    }\n\n    if (!String.IsNullOrEmpty(model))\n    {\n        if (!carModel.Equals("All Models"))\n        {\n            cars = cars.Where(x => x.Model == model);\n        }\n    }\n\n    cars = cars.OrderBy(x => x.Make);\n    return View(cars);\n}	0
14025817	14025725	Toggle visibility of listbox with a button?	private void button3_Click(object sender, RoutedEventArgs e)\n{\n\n    if (listbox1.Visibility == Visibility.Collapsed) \n    {\n        listbox1.Visibility = Visibility.Visible ;\n    }\n    else\n        listbox1.Visibility = Visibility.Collapsed;\n}	0
10950771	10948862	change dataset table adapter connection string at run time	class Program\n{\n    static void Main(string[] args)\n    {\n        //Application Properties can not change. They are read only\n        //Properties.Settings.Default.testConnectionStringApplication \n        //    = String.Format("server={0};Port={1}; database={2};User Id={3};password={4}", "172.23.2.32", "3306", "hrm", "root", "test123");\n\n        //User Properties can change\n        Properties.Settings.Default.testConnectionStringUser\n            = String.Format("server={0};Port={1}; database={2};User Id={3};password={4}", "172.23.2.32", "3306", "hrm", "root", "test123");\n\n        //Call Save to persist the settings. \n        Properties.Settings.Default.Save();\n\n        Console.WriteLine(Properties.Settings.Default.testConnectionStringUser);\n        Console.ReadLine(); \n    }\n}	0
2987033	2986999	Accessing object properties from a treenode that's associated with it?	var valueA = ((object1Type)node1.tag).valueA;	0
14519640	14519221	Caching in .Net Windows application	using System.Runtime.Caching;\n\n private static MemoryCache cache = MemoryCache.Default;	0
11209335	11195979	Calling a WCF method from a WPF client does nothing	Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new System.Action(() => { /* send report code */ }));	0
1204866	285323	Best practice: How to expose a read-only ICollection	public IEnumerable<Foose> GetFooseList() {\n   foreach(var foos in Collection) {\n     yield return foos.Clone();\n   }\n}	0
33022800	33021755	Split and add space	var text = "a1000b2000.00c3000s321a";\n\nvar pattern = @"(?<Section>[a-z])(?<Numbers>[\d.]*)";\n\nvar entities =\n         Regex.Matches(text, pattern)\n              .OfType<Match>()\n              .Select((mt, index) => new\n                {\n                    Index   = index,\n                    Section = mt.Groups["Section"].Value,\n                    Value   = mt.Groups["Numbers"].Value,\n                });	0
29207255	24324987	How to make Ajax timer decrement properly in asp.net?	// Add the ScriptManager and Timer Control.\n\n<div>\n<asp:ScriptManager ID= "SM1" runat="server"></asp:ScriptManager>\n<asp:Timer ID="timer1" runat="server" \nInterval="1000" OnTick="timer1_tick"></asp:Timer>\n</div>\n//   Add the update panel, \n//a label to show the time remaining and the AsyncPostBackTrigger.   \n<div>\n<asp:UpdatePanel id="updPnl" \nrunat="server" UpdateMode="Conditional">\n<ContentTemplate>\n<asp:Label ID="lblTimer" runat="server"></asp:Label>\n</ContentTemplate>\n<Triggers>\n<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />\n</Triggers>\n</asp:UpdatePanel>\n</div>	0
9284643	9284610	Is this the best way to determine that a List of ints contains a 0?	if (ALogMsgTypeIntArray.Contains(0))\n{\n    MessageBox.Show("0 exists");\n}	0
5934357	5934008	xml serialization and encoding	var settings = new XmlWriterSettings\n{\n    Encoding = Encoding.GetEncoding(1252)\n};\n\nusing (var buffer = new MemoryStream())\n{\n    using (var writer = XmlWriter.Create(buffer, settings))\n    {\n        writer.WriteRaw("<sample></sample>");\n    }\n\n    buffer.Position = 0;\n\n    using (var reader = new StreamReader(buffer))\n    {\n        Console.WriteLine(reader.ReadToEnd());\n        Console.Read();\n    }\n}	0
11112975	10732677	How to indent particular row in datagridview	protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)\n{   \nif (e.Row.RowType == DataControlRowType.DataRow)\n{\n     if (e.Row.Cells[0].Text.IndexOf('Child') > 0){\n           e.Row.Cells[0].Style.Add("padding-left", "16px");\n     }\n}\n}	0
31252717	31252677	c# putting inputs into next array elements automatically	private int indexValue; // defines a field to keep the current index\n\nprivate void btnAdd_Click(object sender, EventArgs e)\n{\n    array[indexValue++] = TextBox1.Text; // assigns the value entered by the user to the array on the next position\n}	0
18613358	18609148	Can I rename a table without breaking the final-release?	CREATE VIEW [OldTableName] AS SELECT * FROM [NewTableName];	0
2878619	2878265	Multiple Instances of a single MEF DLL	public class Logger : ILogger\n{\n    public Logger(IFoo foo) { }\n    // ...\n}\n\n[Export(typeof(ILoggerFactory))]\npublic class LoggerFactory : ILoggerFactory\n{\n    [Import]\n    public IFoo Foo { get; set; }\n\n    public ILogger CreateLogger()\n    {\n        return new Logger(Foo);\n    }\n}	0
6808051	6808029	Open image in Windows Photo Viewer	Process photoViewer = new Process();\nphotoViewer.StartInfo.FileName = @"The photo viewer file path";\nphotoViewer.StartInfo.Arguments = @"Your image file path";\nphotoViewer.Start();	0
3542094	3542061	How do I stop a thread when my winform application closes	static bool isCancellationRequested = false;\nstatic object gate = new object();\n\n// request cancellation\nlock (gate)\n{\n    isCancellationRequested = true;\n}\n\n// thread\nfor (int i = 0; i < 100000; i++)\n{\n    // simulating work\n    Thread.SpinWait(5000000);\n\n    lock (gate)\n    {\n        if (isCancellationRequested)\n        {\n            // perform cleanup if necessary\n            //...\n            // terminate the operation\n            break;\n        }\n    }\n}	0
5815627	5802526	How to get anonymous profile for not current user?	user = Membership.GetUser(new Guid(item["UserID"].ToString()));\nif (user == null)\n{\n        // anonymous profile\n        profil = (ProfileCommon)ProfileBase.Create(item["UserID"].ToString());\n}\nelse\n{\n        // hey! I know you!\n        profil = (ProfileCommon)ProfileBase.Create(user.UserName);\n}	0
5431416	5431277	Formatting TextboxFor content 	Html.TextBox("MyValue",String.Format('<your format>',Model.MyClass.MyValue))	0
4448088	4447982	Abstract getter with concrete setter in C#	// implementor MUST override\n protected abstract object IndexerGet(int index);\n\n // implementor can override if he wants..\n protected virtual void IndexerSet(int index, object value) \n {\n   throw new NotSupportedException("The collection is read-only.");\n }\n\n public object this[int index] {\n   get {\n     return IndexerGet(index);\n   }\n   set {\n     IndexerSet(index, value);\n   }\n }	0
4207922	4207867	How to parse an C# assembly and extract every method	var assembly = Assembly.GetExecutingAssembly();\n    var names = (from type in assembly.GetTypes()\n                 from method in type.GetMethods(\n                   BindingFlags.Public | BindingFlags.NonPublic |\n                   BindingFlags.Instance | BindingFlags.Static)\n                 select type.FullName + ":" + method.Name).Distinct().ToList();	0
1762335	1762311	In C# , How can i create a System.Drawing.Color object using a hex value?	string hexValue = "#000000"; // You do need the hash\nColor colour = System.Drawing.ColorTranslator.FromHtml(hexValue); // Yippee	0
27656360	27656229	How to index and get a value	string[] arr = (object)key as string[];\nif(arr != null)\n{\n    int length = arr.Length;\n    //more code\n}	0
809667	809262	How to programatically modify assemblyBinding in app.config?	private void SetRuntimeBinding(string path, string value)\n    {\n        XmlDocument doc = new XmlDocument();\n\n        try\n        {\n            doc.Load(Path.Combine(path, "MyApp.exe.config"));\n        }\n        catch (FileNotFoundException)\n        {\n            return;\n        }\n\n        XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);\n        manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1");\n\n        XmlNode root = doc.DocumentElement;\n\n        XmlNode node = root.SelectSingleNode("//bindings:bindingRedirect", manager);\n\n        if (node == null)\n        {\n            throw (new Exception("Invalid Configuration File"));\n        }\n\n        node = node.SelectSingleNode("@newVersion");\n\n        if (node == null)\n        {\n            throw (new Exception("Invalid Configuration File"));\n        }\n\n        node.Value = value;\n\n        doc.Save(Path.Combine(path, "MyApp.exe.config"));\n    }	0
16698469	16680662	Multiple pivottable creation using EPPlus	CreatePivotTable("Pivot1", "Pivot1", rng1);\n    Save();\n    CreatePivotTable("Pivot2", "Pivot2", rng2);\n\n    private void Save()\n    {\n        m_writer.Save();\n        m_writer.OpenWorkbook ();\n    }	0
4551357	4550284	C# - Passing focus to a tabcontrol/page and not being able to mousewheel scroll	private void setFocusToPage(TabPage page) {\n        var ctl = page.Controls.Count > 0 ? page.Controls[0] : page;\n        this.BeginInvoke((MethodInvoker)delegate { ctl.Focus(); });\n    }	0
22912088	22912021	Exception at initialization of DateTime	public ActionResult ForFahrzeug(DateTime? initDat = null, ...\n {\n }	0
30066677	30066482	How can I properly overload a WebAPI 2 Controller with multiple collection parameters?	public IEnumerable<StockDataItem> Get([FromUri] string[] symbols, DateTime? time) {\n    // Return stock data at a specific time for the provided symbols\n}	0
6343434	6342291	How to assign a row collection (obtained by a linq query) to a datatable without using a loop?	// Create a DataTable from Linq query.       \n\n             IEnumerable<DataRow> query = from row in CSVDataTable.AsEnumerable()\n                                            where CSVDataTable.Columns.Cast<DataColumn>().Any(col => !row.IsNull(col))\n                                            select row; //returns IEnumerable<DataRow>\n\n             DataTable CSVDataTableWithoutEmptyRow = query.CopyToDataTable<DataRow>();	0
25363292	25363207	How can i parse oracle tnsname values in c#?	var host = new Regex("HOST=(?<host>([a-z0-9]+))").Match("<add name='F8CONNECTION' connectionString='Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhawd1221ost)(PORT=1521))(CONNECT_DATA=(SID=PROD)));User Id=$USERNAME;Password=$PASSWORD' providerName='ORACLE' />").Groups["host"].Value;	0
5145035	5144922	How do I search for a specific value in a generic List in C#?	public class MyGenericClass<T> where T : IComparable \n   {\n    T[] Data;\n\n    public void AddData(T[] values) \n    {\n        Data = values;\n\n        var list = Data.ToList();\n        object compareWith = new object();\n        compareWith = 3;\n\n\n        int count = list.Where(a=>a.CompareTo(compareWith) == 0).Count();\n\n    }\n  }	0
8983997	8787323	How to maintain formatting of cells when copying cells from Excel to Word	wordDoc.Tables.Add(b.Range,newsheet.UsedRange.Rows.Count,newsheet.UsedRange.Columns.Count);\nMicrosoft.Office.Interop.Word.Table table = b.Range.Tables[1];\nnewsheet.UsedRange.Copy();\ntable.Range.Select(); \nwordApp.Selection.Paste();	0
410778	410692	Can I initialize a const string from a const char in C#?	private static readonly EscapeString = EscapeChar.ToString();	0
22085142	22084969	BackgroundWorker WPF difficulties with Progress Bar	private readonly BackgroundWorker worker\n    = new BackgroundWorker { WorkerReportsProgress = true };\n\npublic MainWindow()\n{\n    InitializeComponent();\n\n    worker.DoWork += worker_DoWork;\n    worker.ProgressChanged += worker_ProgressChanged;\n}\n\nprivate void worker_DoWork(object sender, DoWorkEventArgs doWorkEventArgs)\n{\n    // Do some long process, break it up into a loop so you can periodically\n    //  call worker.ReportProgress()\n\n    worker.ReportProgress(i);  // Pass back some meaningful value\n}\n\nprivate void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    prgBar.Value = Math.Min(e.ProgressPercentage, 100);\n}	0
19268922	19268095	Xamarin iOS Navigate to Settings	UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString))	0
9672932	9672780	Importing XML Data From XML File To SQL Database	Declare @xml XML\n\nSelect  @xml  = \nCONVERT(XML,bulkcolumn,2) FROM OPENROWSET(BULK 'filePath\fileName.xml',SINGLE_BLOB) AS X\n\nSET ARITHABORT ON\n\nInsert into [YourTableName] \n        (\n            City,County,AreaCode,Founded,CityWebSite,[Population],Zipcode,ZipcodeMax\n        )\n\n    Select \n        P.value('City[1]','VARCHAR(100)') AS City,\n        P.value('County[1]','VARCHAR(100)') AS County,\n        P.value('AreaCode[1]','VARCHAR(100)') AS AreaCode,\n        P.value('Founded[1]','VARCHAR(100)') AS Founded,\n        P.value('CityWebSite[1]','VARCHAR(100)') AS CityWebSite,\n        P.value('Population[1]','VARCHAR(100)') AS Population,\n        P.value('Zipcode[1]','VARCHAR(100)') AS Zipcode,\n        P.value('ZipcodeMax[1]','VARCHAR(100)') AS ZipcodeMax,\n\n    From @xml.nodes('/dataroot/CityData') PropertyFeed(P)	0
2584272	2584206	Adding behaviour to a set of classes	accept(Visitor v)	0
11804738	11803167	api to check for project variables and reference paths in a project file	Dictionary<string, string> globalProperties = new Dictionary<string, string>();\n\n    globalProperties.Add("Configuraion", "Debug");\n    globalProperties.Add("Platform", "AnyCPU");\n\n    ProjectCollection pc = new ProjectCollection(globalProperties);\n\n    Project sln = pc.LoadProject(@"my_directory\My_solution_name.sln.metaproj", "4.0");\n\n    foreach (ProjectItem pi in sln.Items)\n    {\n        if (pi.ItemType == "ProjectReference")\n        {\n            Project p = pc.LoadProject(pi.EvaluatedInclude);\n            ProjectProperty pp = p.GetProperty("OutputPath");\n            if (pp != null)\n            {\n                Console.WriteLine("Project=" + pi.EvaluatedInclude + " OutputPath=" + pp.EvaluatedValue);\n            }\n        }\n    }	0
5114538	5114389	How make sure Aero effect is enabled?	[DllImport("dwmapi.dll", PreserveSig = false)]\npublic static extern bool DwmIsCompositionEnabled();\n\n// Check to see if composition is Enabled\nif (Environment.OSVersion.Version.Major >= 6 && DwmIsCompositionEnabled())\n{\n    // enable glass rendering\n}\nelse\n{\n    // fallback rendering\n}	0
4862992	4862709	MVVM separation of Data Access from ViewModel	public class DataLayer\n    {\n        public ObservableCollection<ContactModel> GetContacts()\n        {\n            var tList = new ObservableCollection<ContactModel>();\n\n            //load from db into tList\n\n            return tList;\n        }\n    }\n\n    public class ContactModel\n    {\n        public int ContactListID { get; set; }\n        public string ContactListName { get; set; }\n        public ObservableCollection<AggregatedLabelModel> AggLabels { get; set; }\n    }\n\n    public class ContactsViewModel\n    {\n        public ObservableCollection<ContactModel> ListOfContacts;\n\n        public ContactsViewModel()\n        {\n            var dl = new DataLayer();\n            ListOfContacts = dl.GetContacts();\n        }\n    }	0
14319971	14319763	Query the Unioned Results of Multiple Tables With Entity Framework	var query =\n    context.SetOne.Select(x => new { Key = x.ID })\n        .Union(context.SetTwo.Select(x => new { Key = x.AnotherKey }))\n        .Union(context.SetThree.Select(x => new { Key = 5 }));	0
19361391	14057105	update element of list of Complex object with linq	// You didn't confuse == vs = did you?\n// Single also helps us debug and ensure we're only getting one result\nvar itemToUpdate = listOfAccessModuleInfo.Where(x => x.AccessModuleId == 4).Single();\nitemToUpdate.ListOfAccessRole.ForEach(x => x.AccessRoleValue = newValue);	0
32824436	32822955	Keeping connection alive in the right way from c# client	hubConnection.Closed += () => {\n            connected = false;\n            while (!connected)\n            {\n                System.Threading.Thread.Sleep(2000);\n                hubConnection = new HubConnection("http://localhost:8080/signalr", "source=" + feed, useDefaultUrl: false);\n                priceProxy = hubConnection.CreateHubProxy("UTHub");\n                hubConnection.Start().Wait();\n                connected = true;\n            }\n        };	0
6173900	6173456	Get DateTime Difference in a Array	DateTime start = Convert.ToDateTime("04/30/2011");\n            DateTime end = Convert.ToDateTime("05/30/2011");\n            List<DateTime> dateArray = new List<DateTime>();\n            while (end > start.AddDays(1))\n            {\n               end= end.AddDays(-1);\n               dateArray.Add(end);\n            }\n            DateTime[] array = dateArray.ToArray();	0
17905163	17904184	Using taglib to display the cover art in a Image box in WPF	// Load you image data in MemoryStream\nTagLib.IPicture pic = f.Tag.Pictures[0];\nMemoryStream ms = new MemoryStream(pic.Data.Data);\nms.Seek(0, SeekOrigin.Begin);\n\n// ImageSource for System.Windows.Controls.Image\nBitmapImage bitmap= new BitmapImage();\nbitmap.BeginInit();\nbitmap.StreamSource = ms;\nbitmap.EndInit();\n\n// Create a System.Windows.Controls.Image control\nSystem.Windows.Controls.Image img = new System.Windows.Controls.Image();\nimg.Source = bitmap;	0
16056402	16056294	SQLite, insert variable in my table (c# console app)	command2.CommandText = "INSERT INTO User (name) VALUES(@param1)";\ncommand2.CommandType = CommandType.Text;\ncommand2.Parameters.Add(new SQLiteParameter("@param1", TheName));	0
32826391	32825990	Mocking a method to return for some parameters and throws exception for all other parameters	mock.Setup(t => t.GetRecord(It.IsAny<Guid>())).Throws(new MyException());\nmock.Setup(t => t.GetRecord(id)).Returns(record1);\nmock.Setup(t => t.GetRecord(id2)).Returns(record2);\nmock.Setup(t => t.GetRecord(id3)).Returns(record3);	0
1698755	1698684	Check if property is null in lambda expression	list.Where(r => r.Properties["RS_Partner_Type"] != null && r.Properties["RS_Title"] != null)\n    .OrderByDescending(r => r.Properties["RS_Partner Type"].ToString())\n    .ThenBy(r => r.Properties["RS_Title"].ToString());	0
17343881	17342074	How to pass a string to vc++ dll from a csharp programme	[DllImport("ConsoleApplication2.dll", CallingConvention=CallingConvention.Cdecl)]\npublic static extern int main_c([MarshalAs(UnmanagedType.LPStr)] String IpAddr, int port);	0
24969856	24969745	Dependency Injection with priority and generics in Unity	container.RegisterType(typeof(IRepository<>), typeof(GenericRepository<>));\n\n// Override multiple specific implementations (I image batch registration here)\ncontainer.RegisterType(typeof(IRepository<Order>), typeof(OrderRepository));\ncontainer.RegisterType(typeof(IRepository<Customer>), typeof(CustomerRepository));	0
30366794	30366693	Implementing async version of a sync method: How to return Task<int> which is constant 1?	return Task.FromResult(1);	0
5548425	5539114	Getting Grid cell information on Left Mouse Button Down	double rowheigth = 0, columnlength = 0;\nint row = 0, column = 0;\nif (pos.X > this.TheGrid.ColumnDefinitions[0].ActualWidth && pos.Y > this.TheGrid.RowDefinitions[0].ActualHeight)\n{\n    while (rowheigth + this.TheGrid.RowDefinitions[row].ActualHeight < pos.Y)\n    {\n        rowheigth += this.TheGrid.RowDefinitions[row].ActualHeight;\n        row++;\n    }\n    while (columnlength + this.TheGrid.ColumnDefinitions[column].ActualWidth < pos.X)\n    {\n        columnlength += this.TheGrid.ColumnDefinitions[column].ActualWidth;\n        column++;\n    }\n}	0
11790778	11517268	Reading each row from text file into an array of doubles or integer using C#	private void ReadFile()\n    {\n        var lines = File.ReadLines("Data.csv");\n        var numbers = new List<List<double>>();\n        var separators = new[] { ',', ' ' };\n        /*System.Threading.Tasks.*/\n        Parallel.ForEach(lines, line =>\n        {\n            var list = new List<double>();\n            foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))\n            {\n                double i;\n\n                if (double.TryParse(s, out i))\n                {\n                    list.Add(i);\n                }\n            }\n\n            lock (numbers)\n            {\n                numbers.Add(list);\n            }\n        });	0
21425567	21425155	NHibernate criteria to count unique visits	Projections.GroupProperty("CityID")	0
31562649	31561735	AvalonEdit : How to modify the xshd file to change elements atrribute	XDocument doc = XDocument.Load("file.xml");\nXNamespace ns = "http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008";\nvar element = doc.Descendants(ns + "Color").First(x => x.Attribute("name").Value == "String");\nelement.SetAttributeValue("foreground", "VALUECOLOR");\ndoc.Save("file.xml");	0
33478547	33444904	Comparing a DateTimeOffSet From DataBase to Current Value	public ActionResult Index()\n{\n    DateTimeOffset currentDate = DateTimeOffset.Now.AddDays(-1);\n    IQueryable<Event> events = db.Events.Where(x => currentDate > x.EventTime);\n\n    foreach(var e in events){ \n    {\n        db.Events.Remove(e);\n    }\n    db.SaveChanges()\n\n    return View(db.Events.ToList());\n}	0
3997824	3997743	How to get a datatable from a listbox	protected override Page_Load(object sender, EventArgs e)\n{\n    if( !IsPostBack)\n    {\n        DataTable tbl = GetData();\n        lstData.DataSource = tbl;\n        lstData.DataBind();\n\n        // store in viewstate\n        ViewState["data"] = tbl;\n    }\n}\n\nprotected void btnSave_Click(object sender, EventArgs e)\n{\n    DataTable tbl = (DataTable)ViewState["data"];\n}	0
662116	662085	get an html element top and left properties data	Element = <however your get your element>;\n\n//--- Determine real element size and position relative to the main page.\nint ElementLeft = Element.offsetLeft;\nint ElementTop = Element.offsetTop;\nmshtml.IHTMLElement TmpElem = Element.offsetParent;\nwhile (TmpElem != null)\n{\n     ElementLeft = ElementLeft + TmpElem.offsetLeft;\n     ElementTop = ElementTop + TmpElem.offsetTop;\n     TmpElem = TmpElem.offsetParent;\n}	0
1683406	1683203	Emulating Value Type Polymorphism in C Sharp	IPrincipal.IsInRole	0
18455151	18258324	How to resize byte[] while keeping proportions?	using (var ms = new MemoryStream(data))\n{\n    var image = Image.FromStream(ms);\n\n    var ratioX = (double)150 / image.Width;\n    var ratioY = (double)50 / image.Height;\n    var ratio = Math.Min(ratioX, ratioY);\n\n    var width = (int)(image.Width * ratio);\n    var height = (int)(image.Height * ratio);\n\n    var newImage = new Bitmap(width, height);\n    Graphics.FromImage(newImage).DrawImage(image, 0, 0, width, height);\n    Bitmap bmp = new Bitmap(newImage);\n\n    ImageConverter converter = new ImageConverter();\n\n    data = (byte[])converter.ConvertTo(bmp, typeof(byte[]));\n\n    return "data:image/*;base64," + Convert.ToBase64String(data);\n}	0
2508982	2508963	Error converting datetime to string	txtStartDate.Text = rdrGetUserInfo.IsDBNull(14) ? String.Empty : Convert.ToString(rdrGetUserInfo.GetDateTime(14).ToString());	0
5412419	5412397	How to determine if a string contains any matches of a list of strings	Vehicles.Where(v => listOfStrings.Contains(v.Name))	0
14242855	14242782	Select in the grid a recently added name	var recentlyAddedEmployer= employerManager	0
19126670	19126659	Customise SystemTray Windows Phone 8?	shell:SystemTray.IsVisible="true"\nshell:SystemTray.BackgroundColor="Transparent"\nshell:SystemTray.Opacity="0.0"	0
31619734	31618317	Extra field in junction table with DataAnotations in EntityFramework	public class A\n{\n   public int Id{get;set;}\n   //...\n   public virtual ICollection<AB> ABs{get;set;}\n}\n\npublic class B\n{\n   public int Id{get;set;}\n   //...\n public virtual ICollection<AB> ABs{get;set;}\n}\n\npublic class AB\n{\n   [Key,ForeignKey("A"),Column(Order=1)]\n   public int AId{get;set;}\n\n   [Key,ForeignKey("B"),Column(Order=2)]\n   public int BId{get;set;}\n\n   public virtual A A{get;set;}\n   public virtual B B{get;set;}\n\n   //Add here the extra column(s)\n}	0
12489145	12489011	How can I unblock a file using C#?	new FileStream("myFile.dat", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);	0
29690080	29689680	Simple socket server in C# unexpectedly closes connection when trying to write data to client	GET /chat HTTP/1.1\n    Host: server.example.com\n    Upgrade: websocket\n    Connection: Upgrade\n    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\n    Origin: http://example.com\n    Sec-WebSocket-Protocol: chat, superchat\n    Sec-WebSocket-Version: 13	0
16129633	16128664	A referential integrity constraint violation occurred	mMaMDBEntities.Entry<MamConfiguration>(item).State = System.Data.EntityState.Modified;	0
1318931	1318906	How do I use a shape to define a clipping region?	GraphicsPath gpath new GraphicsPath();\ngpath.AddPie(rect, startAngle, sweepAngle);\ngpath.CloseFigure();\nthis.Region = new Region(gpath);	0
18981521	18981210	Im getting ArgumentOutOfRange exception when trying to color text in a listBox why?	if (data.Count > e.Index)\n{\n    if (data[e.Index].Contains(strMid))\n    {\n        int index = data[e.Index].IndexOf(strMid);\n        strLeft = data[e.Index].Substring(0, index);\n        strRight = data[e.Index].Substring(index + strMid.Length);\n    }\n\n}	0
9891305	9890623	How to show a child window on its parent?	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        ChildWin childwindow = new ChildWin();\n        childwindow.Owner = this;\n        ChildWin.ShowInTaskbar = false;\n        childwindow.ShowDialog();\n    }	0
5559195	5559123	programmatically add private queues in MSMQ	using System.Messaging;\n\n//...\n\nvoid CreateQueue(string qname) {\n   if (!MessageQueue.Exists(qname)) MessageQueue.Create(qname);\n}	0
32529889	32529663	C# Get child window titles of my process	FormCollection forms = Application.OpenForms;\nList<string> titleList = new List<string>();\nforeach (var item in forms)\n{\n    Form form = item as Form;\n    if (form == null || form.Equals(this))\n        continue;\n    else\n        titleList.Add(form.Text);\n}	0
13784531	13784432	How can I trim the fat from this SQLite operation?	public async Task<List<String>> SelectDistinctGroupNames()\n{\n    var db = new SQLiteAsyncConnection(SQLitePath);\n    var groupNames = await db.QueryAsync<string>("SELECT DISTINCT GroupName FROM SOs_Locations");\n    return groupNames.ToList();\n}	0
19258237	19258130	getting data from a class object	private  Student NewStudent { get; set; }\n\nprivate void btnset_Click(object sender, RoutedEventArgs e)\n{\n    NewStudent = new Student();\n    NewStudent.Forename = txtforename.Text;\n    NewStudent.Surname = txtsurname.Text;\n    NewStudent.Course = txtcourse.Text;\n    NewStudent.DoB = txtdob.Text;\n    NewStudent.Matriculation = int.Parse(txtmatric.Text);\n    NewStudent.YearM = int.Parse(txtyearm.Text);\n}	0
15839388	15811202	Rest Sharp - 406 Error - No match for accept header	"application/json","application/xml","text/json","text/x-json","text/javascript","text/xml"	0
4438568	4430785	How do you exclude a property in a persistent object in db4o using C#?	class Item\n{\n    [Transient] \n    private int serviceLength; \n\n    public int ServiceLength\n    {\n       get { return serviceLength; } \n       set { serviceLength = value; } \n    }\n}	0
3437644	3437620	C#: How set "on row command" event handler of a gridview dynamically?	gridView.RowCommand -= MyOldRowCommandHandler;\ngridView.RowCommand += MyNewRowCommandHandler;	0
217509	217353	Retrieving Selected Text from Webbrowser control in .net(C#)	using mshtml;\n\n...\n\n    IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2;\n\n    IHTMLSelectionObject currentSelection= htmlDocument.selection;\n\n    if (currentSelection!=null) \n    {\n        IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange;\n\n        if (range != null)\n        {\n            MessageBox.Show(range.text);\n        }\n    }	0
27557870	27557820	Passing a button to an event handler	void ButtonClicked(object sender, EventArgs e)\n{\n    Button button = sender as Button;\n    if (button != null)\n    {\n        button.Text = "changed";\n    }\n}	0
28716972	28716884	generate 200 numbers with an operator c#	string[] operands = new[] {"+", "-", "*", "/"};\n      Random random = new Random();\n      List<string> results = new List<string>();\n      for (int i = 0; i < 200; i++)\n      {\n        int firstNum = random.Next(0, 500);\n        int secondNum = random.Next(0, 500);\n\n        string operand = operands[random.Next(0, 3)];\n        results.Add(string.Format("{0}{1}{2}", firstNum, operand, secondNum));\n      }	0
1626140	1626083	Open file read-only	var attributes = File.GetAttributes(path);\n\nFile.SetAttributes(filePath, attributes | FileAttributes.ReadOnly);\n\nSystem.IO.Diagnostics.Process.Start(fileName);\n\nFile.SetAttributes(filePath, attributes);	0
17221588	17221533	Parsing JSON POST request C#	string postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();	0
2875152	2874680	XmlSerializer - Deserialize different elements as collection of same element	class Program\n{\n    static void Main(string[] args)\n    {\n        XDocument doc = XDocument.Load(@".\Resources\Sample.xml");\n\n        var columns = from column in doc.Descendants("COLUMNS").Descendants()\n                      select new Column(column.Name.LocalName, int.Parse(column.Attribute("WIDTH").Value));\n\n        foreach (var column in columns)\n            Console.WriteLine(column.Name + " | " + column.Width);\n    }\n\n    class Column\n    {\n        public string Name { get; set; }\n        public int Width { get; set; }\n\n        public Column(string name, int width)\n        {\n            this.Name = name;\n            this.Width = width;\n        }\n    }\n}	0
11750385	11750318	Using Entity Framework 4 how to filter referenced Entity Collection	var vcontact = from c in context.Contacts\n               orderby c.LastName\n               where c.Addresses.Any(a => a.City == "Toronto")\n               select new Contact\n               {\n                   LastName = c.LastName;\n                   // map all remaining properties of Contact\n                   Addresses = c.Addresses.Where(a => a.City == "Toronto")\n               };	0
11491310	11491286	how to get data from two table in the grid by using stored procedure in c#	SqlDataReader myReader = testCMD.ExecuteReader();\nwhile (myReader.Read())\n { \n  //\n } \nmyReader.NextResult();\nwhile (myReader.Read())\n { \n  //\n }	0
21967296	21967246	ListView: getting an actual item object from ListViewItem	public class MyListView : ListView\n{\n        protected override DependencyObject GetContainerForItemOverride()\n        {\n            return new ProblemsListItem();\n        }\n}	0
26611046	26610203	How should a controller be excluded on publish?	#if !DEBUG\nroutes.IgnoreRoute("UnitTest/{*pathInfo}")\n#endif	0
32558186	32558032	Custom date format in Excel for zero	dataRange.NumberFormat = "m/d/yyyy;;#0";	0
2389766	2389737	How to write regex that searches for a dynamic amount of pairs?	string txt = "Lore ipsum {{abc|prop1=\"asd\";prop2=\"bcd\";prop3=\"bbb\";}} asd lore ipsum";            \n        Regex r = new Regex("{{(?<single>([a-z0-9]*))\\|((?<pair>((?<key>([a-z0-9]*))=\"(?<value>([a-z0-9]*))\";))*)}}", RegexOptions.Singleline | RegexOptions.IgnoreCase);\n        Match m = r.Match(txt);            \n        if (m.Success)\n        {\n            Console.WriteLine(m.Groups["single"].Value);\n            foreach (Capture cap in m.Groups["pair"].Captures)\n            {\n                Console.WriteLine(cap.Value);                    \n            }\n            foreach (Capture cap in m.Groups["key"].Captures)\n            {\n                Console.WriteLine(cap.Value);\n            }\n            foreach (Capture cap in m.Groups["value"].Captures)\n            {\n                Console.WriteLine(cap.Value);\n            }\n        }	0
8737342	8708829	debugging a HTTP Handler	You will need to go to Start -> Microsoft Visual Studio 2005 -> Visual Studio Tools -> Visual Studio 2005 Command Prompt. On the prompt write down this command:\naspnet_regiis -r\nThe above command will register dot net with IIS and now the button will also be enabled.	0
6074979	6074938	C# proper way to loop through a float	double y;\nfor(double x=3.3454; x<20.3458; x += .1) {\n    y = Math.Exp(-0.04D * Math.Pow((x- 13.25D), 2D)) * 300;\n    // do something with y\n}	0
16111436	16111366	How do I delete a row from a Microsoft Access table using c#	string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" +  textBox1.Text + "'";	0
9553005	9552909	How to order and groupby while maintaining list order using Linq	var result = people.Select((person,index)=>new{person,index})\n      .OrderBy(pair => pair.person.ID)\n      .ThenBy(pair => pair.index)\n      .Select(pair => pair.person)\n      .ToArray();	0
14830614	14806270	not able get message in chat application when successfully logs in	public void AddCustomer(string sUser)\n        {\n            string cAddText = "<STRONG>" + sUser + "</STRONG>";\n            if (CheckUser(sUser)==false)\n            {\n                cArray.Add(cAddText);\n            }\n\n            if (cArray.Count > 200)\n            {\n                cArray.RemoveRange(0, 10);\n            }\n        }	0
33068318	33068283	Adding a zero and decimal place to int	decimal dec = (decimal)number / 100;	0
22246572	22243465	Ajax postback not working for a page inside a directory?	[System.Web.Services.WebMethod]\npublic static string mymethod()\n{\n    //do something\n}	0
18072678	18071587	getting the full filenames from all top directory files in a specific directory and suppressing the occuring error	private void button1_Click(object sender, EventArgs e)\n    {\n        string folder = @"C:\windows\prefetch";\n        string filemask = @"*.pf";\n        string[] filelist = Directory.GetFiles(folder, (filemask));\n\n        //now use filelist[i] for any operations. \n    }	0
26024047	26023954	Can a filter access properties from my BaseController?	if (filterContext.Controller is BaseController)\n{\n    BaseController ctr = (BaseController)filterContext.Controller;\n    if (ctr.User.IsAdmin)\n    {....}\n}	0
6096113	6096051	How to get number of words on a web page?	//text()	0
32865636	32858415	NoLock in Entity Framework	public async Task<KeyValuePair<String, List<BE_Category>>> CategoryList(BE_Category obj)\n{\n    try\n    {\n        using (var categoryContext = new ModelGeneration())\n        {\n            using (var dbContextTransaction = categoryContext\n                      .Database\n                      .BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))\n            {\n                categoryContext.Configuration.ProxyCreationEnabled = false;\n\n                //Code\n\n                dbContextTransaction.Commit();\n\n                return new KeyValuePair<String, List<BE_Category>>("", data);\n            }\n        }\n    }\n    catch (Exception ex)\n    {\n        return new KeyValuePair<String, List<BE_Category>>(ex.Message, null);\n    }\n}	0
1201220	1201138	Windows Service looping - How To?	Private myThreadingTimer As System.Threading.Timer\n    Private blnCurrentlyRunning As Boolean = False\n\n    Protected Overrides Sub OnStart(ByVal args() As String)\n       Dim myTimerCallback As New TimerCallback(AddressOf OnTimedEvent)\n       myThreadingTimer = New System.Threading.Timer(myTimerCallback, Nothing, 1000, 1000)\n    End Sub\n\n    Private Sub OnTimedEvent(ByVal state As Object)\n        If Date.Now.Second = 1 Or Date.Now.Second = 15 Or Date.Now.Second = 30 Or Date.Now.Second = 45 Then\n            If Not blnCurrentlyRunning Then\n                blnCurrentlyRunning = True\n\n                Dim myNewThread As New Thread(New ThreadStart(AddressOf MyFunctionIWantToCall))\n                myNewThread.Start()\n            End If\n        End If\n    End Sub\n\nPublic Sub MyFunctionIWantToCall()\n   Try\n       'Do Something\n   Catch ex As Exception\n   Finally\n       blnCurrentlyRunning = False\n   End Try\nEnd Sub	0
298392	289512	How to define a default constructor by code using StructureMap?	ForRequestedType<MyDataContext>().TheDefault.\nIs.ConstructedBy(() => new MyDataContext());	0
10005447	10005418	Finding Week, using current date ? In C#?	using System;\nusing System.Globalization;\n\npublic class Example\n{\n   public static void Main()\n   {\n      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;\n      DateTime date1 = new DateTime(2011, 1, 1);\n      Calendar cal = dfi.Calendar;\n\n      Console.WriteLine("{0:d}: Week {1} ({2})", date1, \n                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, \n                                          dfi.FirstDayOfWeek),\n                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));       \n   }\n}\n// The example displays the following output:\n//       1/1/2011: Week 1 (GregorianCalendar)	0
17974177	17829540	Glimpse is breaking signalr on mono	web.config	0
27683424	27648888	How to save SpeechSynthesisStream as audio in local storage of Windows Phone 8.1	var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();\n\n        SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");\n\n        using (var reader = new DataReader(stream))\n        {\n            await reader.LoadAsync((uint)stream.Size);\n            IBuffer buffer = reader.ReadBuffer((uint)stream.Size);\n            await FileIO.WriteBufferAsync(outputFile, buffer);\n        }	0
8916229	8916184	How to set WPF Combobox SelectedValue by code behind based on the custom class?	// Get first element with proper name from the bound source\ncmdLanguages.SelectedValue = languages.FirstOrDefault(l => l.EnglishName == "Spanish");	0
32103446	32036040	How to Get the content of html tag in c#	dynamic document = webControl1.ExecuteJavascriptWithResult("document");\nvar p = document.getElementsByTagName("p");\n  for (int i = 0; i < p.length; i++)\n            {\n                MessageBox.Show(p[i].innerText) ;\n\n            }	0
20664177	20661811	How does Rx behave when stream of data comes faster than Subscribers can consume?	Observable.Synchronize()	0
16998801	16998748	Copy protected field in subclass constructor	class Connection\n{\n    // internal details of the connection; should not be public.\n    protected object _client;\n\n    // base class constructor\n    public Connection(object client) { _client = client; }\n\n    // copying constructor\n    public Connection(Connection other) : this(other._client) { }\n}\n\nclass AuthenticatedConnection : Connection\n{\n    // broken constructor?\n    public AuthenticatedConnection(string token, Connection connection)\n        : base(connection)\n    {\n        // use token etc\n    }\n}	0
18423609	18423527	How to compare time in c#?	System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();\n\n    void CreateTimer()\n    {\n        _timer = new System.Windows.Forms.Timer();\n        _timer.Tick += new EventHandler(_timer_Tick);\n        _timer.Interval = 5000;\n        _timer.Enabled = true;\n    }\n\n    void _timer_Tick(object sender, EventArgs e)\n    {\n        // do something.\n    }	0
31146226	31146152	Using Decimals in C#	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    decimal x = 0;\n    if (decimal.TryParse(textBox1.Text, out x))\n    {\n        var y = 1000000.0M;\n        var answer = x * y;\n\n        displayLabel2.Text = answer.ToString();\n    }\n    else\n    {\n        displayLabel2.Text = "error";\n    }\n}	0
27121353	27120916	How to find the installed location of a software with Registry using C#	RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"your path here", false);	0
30755446	30755350	OrderBy numbers that are strings (cannot convert to int)	var sorted = list\n    .Select(x => new\n    {\n        Splited = x.Split(),\n        Raw = x\n    }) //split the string and keep the raw value\n    .Select(x => new\n    {\n        Count = int.Parse(x.Splited[0]), // extract the number \n        Raw = x.Raw\n    })\n    .OrderBy(x => x.Count) //order by that number\n    .Select(x => x.Raw); //select raw value	0
12985148	11489234	Get current generated html while debugging mvc3 view	((System.Web.Mvc.WebViewPage)(this)).ViewContext.Writer	0
2072016	2071974	Get average value from double[] between two indices	var values = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };\nvar average = values.Skip(2).Take(5).Average();	0
9804012	9803786	How to pass a parameter to TeamCity Test Runner?	Rule:\n+: SolutionName\Tests\ConfigFiles\Dev\App.config=>SolutionName\Tests\App.config	0
26073306	26072303	how to pass dynamic value with in sql query	string st = ("select  receipt_no, name, rupees, pay_by, date from receipt_info where receipt_no =" + i);	0
22070626	22070353	How to serialize partial classes with WebAPI and Linq	public partial class Category\n{\n    [DataMember]\n    public string CoverImageUrl { get; set; }\n}	0
12532586	12532524	Process a list with a nested loop using PLINQ	measures = this.results\n        .AsParallel()\n        .SelectMany(result => result.Item2.Select(destination =>\n            new Tuple<int, object, object>(\n                result.Item1,\n                destination.Message,\n                destination.DestinationName)).ToList()).ToList();	0
24159882	24139583	Read Value of Arbitrary Type From Byte Array	public object GetValueByType(Type typeOfReturnedValue, int offsetInDataSection)\n    {\n        GCHandle handle = GCHandle.Alloc(this.byteArray, GCHandleType.Pinned);\n        int offset = <some desired offset>;\n        IntPtr addressInPinnedObject = (handle.AddrOfPinnedObject() + offset);\n        object returnedObject = Marshal.PtrToStructure(addressInPinnedObject, typeOfReturnedValue);\n        handle.Free();\n        return returnedObject;\n    }	0
18915639	18914916	Extract SQL 'print' messages from LINQ ExecuteMethodCall	SqlConnection conn = (SqlConnection)context.Database.Connection;\nconn.Open();\nconn.InfoMessage += (s, e) => Console.WriteLine(e.Message);	0
9887283	9887260	Assign Method to Action<string>	Logic.DisplayData = MainForm.AddToList;	0
7977907	7977778	Open a link with different browsers	System.Diagnostics.Process.Start("browserChoice.exe", "http://stackoverflow.com"	0
18939820	18939390	How to read struct items one by one in c#?	GoldAverage Gold = new GoldAverage();\n    StringBuilder sb = new StringBuilder();\n    foreach (var field in typeof(GoldAverage).GetFields())\n    {\n        sb.append(field.Name.ToString() + " : " + field.GetValue(Gold).ToString() + " | ");	0
17098537	16991954	How do I create a 3 week rotating schedule from SQL data? - EDITED	WHERE [WeekNum] = (DATEPART(WEEK, GETDATE()) % 3) + 1 AND [DayNum] = DATEPART(DW, GETDATE())	0
26065266	26043407	ServiceStack ArgumentException Mapping Dto to Domain Model	PclExport.Instance.SupportsExpression = false;	0
1853807	1853777	How to get unique entries of products in a List<Order> with LINQ	var products = orders.SelectMany(o => o.OrderRows)\n                     .Select(r => r.ProductId)\n                     .Distinct();	0
5738579	5703712	how should I convert VAriant from C++ in C#	string[] listaF = new string[infoList.GetCount()];	0
3575169	3575085	Scroll to bottom on new item. My method freezes scrollbar	INotifyCollectionChanged collection = logListView.Items;\ncollection.CollectionChanged += collection_CollectionChanged;	0
15913725	15913654	Parse various formatted string to time	string myTime = "5:00AM";\nDateTime dt = DateTime.Now;\nDateTime.TryParse(ss, out dt);	0
21203281	21203004	Generic Interface inheriting Non-Generic One C#	public abstract class AbstractBlockRule\n{\n    public long Id{get;set;}\n    public abstract List<IRestriction> Restrictions { get; set; }\n}\n\npublic interface IRestriction\n{\n    object Limit { get; }\n}\n\npublic interface IRestriction<T> : IRestriction \n    where T:struct\n{\n    // hide IRestriction.Limit\n    new T Limit {get;} \n}\n\npublic abstract class RestrictionBase<T> : IRestriction<T>\n    where T:struct\n{\n    // explicit implementation\n    object IRestriction.Limit\n    {\n        get { return Limit; }\n    }\n\n    // override when required\n    public virtual T Limit { get; set; }\n}\n\npublic class TimeRestriction : RestrictionBase<TimeSpan>\n{\n}\n\npublic class AgeRestriction : RestrictionBase<TimeSpan>\n{\n}\n\npublic class BlockRule : AbstractBlockRule\n{\n    public override List<IRestriction> Restrictions { get; set; }\n}	0
24052627	23701253	Convert an asp.net c# webservice datetime value to Date object in android(Java)	Scanner in = new Scanner(obj.getString("CreationTime")).useDelimiter("[^0-9]+");\nLong createdate = in.nextLong();	0
10728636	10728602	Turning a single quote into an escaped single quote within a string	s = s.Replace("'", @"\'");	0
34496808	34495958	generics casting - it's not able to cast from GClass<string> to GClass<T>	switch (to)\n    {\n        case "x":\n            result = this.dialogX() as GClass<T>;\n            break;\n        case "y":\n            result = this.dialogY() as GClass<T>;\n            break;\n    }	0
29602581	20067548	Common Library in Sandbox Solution SharePoint 2013	[assembly: AllowPartiallyTrustedCallers]	0
21866385	21865774	Is there a way to merge two IObservables such that if B finishes before A, it halts the result (but not vice-versa)?	var combined = A.TakeUntil(B).Merge(B);	0
1681085	1681065	Equivalent of += for prefixing	x = "prefix" + x;	0
19039802	19039415	Specflow reusing When declared in feature file with C# file	Scenario: demo\nGiven ...\nWhen do something\n\n[Binding]\npublic class Demo{\n\n [When(@"do something"), Scope(Scenario = "demo")]\n public void DoSomething(){\n  {  }\n}\n\nScenario: demo 2\nGiven ...\nWhen do something\n...\n\n[Binding}\npublic class Demo2{\n\n [When(@"do something"), Scope(Scenario = "demo 2"))]\n public void DoSomething(){\n {  }\n\n}	0
10534072	10533848	Write Access records into a SQL table using C# SqlConnection	bulkCopy.ColumnMappings.Add("A", "A");\nbulkCopy.ColumnMappings.Add("B", "B");\nbulkCopy.ColumnMappings.Add("C", "C");	0
4650090	4649989	Reading a *.CSPROJ file in C#	XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);\nmgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");\n\nforeach (XmlNode item in xmldoc.SelectNodes("//x:ProjectGuid", mgr))\n{\n    string test = item.InnerText.ToString();\n}	0
23624052	23623696	Timer for a for loop	private void timer_Tick(object sender, EventArgs e)\n{\n     var timer = (Timer)sender;\n     timer.Stop();\n\n     //you should check how many time's you have fired and decide whether to keep going here.\n\n\n     timer.Interval = valueTimer.Next(10, 100);\n     timer.Start();\n}\n\n\nprivate void btnRun_Click(object sender, EventArgs e)\n{\n    timer.Interval = valueTimer.Next(10, 100);\n    timer1.Start();\n}	0
26127500	26127402	Prevent application from closing	Application.Run	0
14124417	14124296	String List Serializer	public class NewCVXml : IXmlSerializable {\n\n    public List<string> FieldFirst { get; set; }\n    public List<string> FieldSecond { get; set; }\n    public List<string> FieldThird { get; set; }\n\n    public void WriteXml (XmlWriter writer)\n    {\n        // Custom Serialization Here\n    }\n\n    public void ReadXml (XmlReader reader)\n    {\n        // Custom Deserialization Here\n    }\n\n    public XmlSchema GetSchema()\n    {\n        return(null);\n    }\n\n}	0
1173266	1173241	How can Replace infinite loop?	String c = Regex.Replace(b, "\n\n+", "\n");	0
32598965	32598809	how to compare values of a datatable from two datatable and subtract them	if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))\n {\n     rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString())\n }	0
1156381	1121411	Parsing HTML and pulling down a drop down	What color is your favorite?: <br/>\n<form method="post" action="post.php">\n        <select name="color">\n            <option>AliceBlue</option>\n            <option>AntiqueWhite</option>\n            <option>Aqua</option>\n        </select><br/>\n        <input type="submit" value="Submit"/>\n</form>	0
10297152	10297047	Matching plurals using regex in C#	/(?<![aei])([ie][d])(?=[^a-zA-Z])|(?<=[ertkgwmnl])s(?=[^a-zA-Z])/g	0
13755972	13755399	Relative path to current directory in code-behind isn't consistent	string paths = " Runtime Path "  + System.Reflection.Assembly.GetExecutingAssembly().Location + "<br>" +\n            " Using Root " + new DirectoryInfo("./").FullName + "<br>" +\n            " Appdomain " + Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) + "<br>" +\n            " Environment " + System.Environment.CurrentDirectory;	0
28150729	28147461	Table border lines showing over panels ASP NET	#Panel1 {\n    background-color:#ffffff;\n    z-index:9999;\n}	0
7865037	7864953	How to get resource from ninject without using constructor pattern in mvc3	public class HomeController : Controller\n{\n    private IHelloService _service;\n\n    /*\n          No default constructor\n    */\n\n    public string Index()\n    {\n        _service= DependencyResolver.Current.GetService<IHelloService>();\n        return _service.GetGreeting();\n    }\n}	0
33296013	33295958	How to restore databse SQL 2008 in C#?	string stringquery = @"USE master BACKUP DATABASE [TEST] TO DISK='D:\ABC.BAK'";	0
33662556	33662445	How can I cascade the location where new windows are opened up?	var v = new View()\n{\n    Owner = this\n};\nvar ownedWindows = OwnedWindows.Cast<Window>().Where(w => w.IsVisible).ToList();\nif (!ownedWindows.Any())\n{\n    v.WindowStartupLocation = WindowStartupLocation.CenterScreen;\n}\nelse\n{\n    v.WindowStartupLocation = WindowStartupLocation.Manual;\n    v.Left = ownedWindows.Max(w => w.Left) + 20;\n    v.Top = ownedWindows.Max(w => w.Top) + 20;\n}\nv.Show();	0
6943445	6943303	Show progress only if a background operation is long	private ManualResetEvent _finishLoadingNotifier = new ManualResetEvent(false);\n\nprivate const int ShowProgressTimeOut = 1000 * 3;//3 seconds\n\n\nprivate void YourLongOperation()\n{\n    ....\n\n    _finishLoadingNotifier.Set();//after finish your work\n}\n\nprivate void StartProgressIfNeededThread()\n{\n    int result = WaitHandle.WaitAny(new WaitHandle[] { _finishLoadingNotifier }, ShowProgressTimeOut);\n\n    if (result > 1)\n    {\n        //show the progress bar.\n    } \n}	0
9973699	9902758	Filesystemwatcher double entries	public void OnChanged(object source, FileSystemEventArgs e)\n{\n    try\n    {\n        watcher.EnableRaisingEvents = false;\n        FileInfo objFileInfo = new FileInfo(e.FullPath);\n        if (!objFileInfo.Exists) return;\n        System.Threading.Thread.Sleep(5000);\n\n        FileInfo fileinformatie = new FileInfo(e.FullPath);\n        string strCreateTime = fileinformatie.CreationTime.ToString();\n        string strCreateDate = fileinformatie.CreationTime.ToString();\n\n        //Ignore this, only for my file information.\n        strCreateTime = strCreateTime.Remove(strCreateTime.LastIndexOf(" "));\n        strCreateDate = strCreateDate.Remove(0,strCreateDate.LastIndexOf(" "));\n\n        ProcessAllFiles(e.FullPath, strCreateTime, strCreateDate);\n    }\n    catch (Exception ex)\n    {\n        ToolLabel.Text = ex.Message.ToString();\n    }\n    finally\n    {\n        watcher.EnableRaisingEvents = true;\n    }\n}	0
21200890	21200212	ASP C#: How to get a table row from a control inside a cell	protected void Page_Load(object sender, EventArgs e)\n{\n        for (int i = 0; i < 3; i++)\n        {\n            TableCell cell_name = new TableCell();\n            cell_name.Text = "Some name";\n\n            TableCell cell_active = new TableCell();\n            CheckBox checkbox = new CheckBox();\n            cell_active.Controls.Add(checkbox);\n\n            TableCell cell_actions = new TableCell();\n            ImageButton button = new ImageButton();\n            button.CommandArgument=i.ToString();\n            button.Click += RowClick;\n            cell_actions.Controls.Add(button);\n\n            TableRow row = new TableRow();\n            row.Cells.Add(cell_name);\n            row.Cells.Add(cell_active);\n            row.Cells.Add(cell_actions);\n\n            table1.Rows.Add(row);\n        }\n}\nprotected void RowClick(object sender, EventArgs e)\n{\n        int rowIndex =int.Parse( ((ImageButton)sender).CommandArgument);\n        Response.Write("RowIndex = " + rowIndex);\n}	0
12747684	12747533	How to get the number of pages inside each pdf document inside a directory	using System;\nusing iTextSharp.text.pdf;\nusing System.IO;\n\nnamespace ConsoleApplication2\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int PgCount = 0;\n            string[] PdfFiles = Directory.GetFiles(@"C:\MyFolder\", "*.pdf");\n            Console.WriteLine("{0} PDF Files in directory", PdfFiles.Length.ToString());\n            for (int i = 0; i < PdfFiles.Length; i++)\n            {\n                PgCount = GetNumberOfPages(PdfFiles[i]);\n                Console.WriteLine("{0} File has {1} pages", PdfFiles[i], PgCount.ToString());\n            }\n            Console.ReadLine();\n        }\n\n        static int GetNumberOfPages(String FilePath)\n        {\n            PdfReader pdfReader = new PdfReader(FilePath); \n            return pdfReader.NumberOfPages; \n        }\n    }\n}	0
27090414	27087390	Texture2D to front	SpriteBatch.Draw()	0
12260126	12120630	How do I identify my server name for server authentication by client in c#	X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadOnly);\nvar certificates = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "CN=localhost", false);\nstore.Close();\n\nif (certificates.Count == 0)\n{\n    Console.WriteLine("Server certificate not found...");\n    return;\n}\nelse\n{\n    serverCertificate = certificates[0];\n}	0
4564761	4517460	How to execute custom JavaScript in WebBrowser control?	HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\n    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n    element.text = "function sayHello() { alert('hello') }";\n    head.AppendChild(scriptEl);\n    webBrowser1.Document.InvokeScript("sayHello");	0
13761279	13761181	Tahoma font rendering on Windows 8	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        var s = "Hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";\n        e.Graphics.DrawString(s, this.Font, Brushes.Black, 0, 0);\n        TextRenderer.DrawText(e.Graphics, s, this.Font, new Point(0, this.Font.Height), Color.Black);\n        base.OnPaint(e);\n    }\n}	0
9140079	9126076	How can I calculate the width of a string in Metro (without displaying it)?	// Setup the TextBlock with *everything* that affects how it \n// will be drawn (this is not a complete example)\nTextBlock^ tb = ref new TextBlock; \ntb->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Top; \ntb->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; \ntb->Height = in_height; \ntb->Text = text;\n\n// Be sure to tell Measure() the correct dimensions that the TextBox \n// have to draw in!\ntb->Measure(SizeHelper::FromDimensions(Parent->Width,Parent->Height)); \ntext_width = tb->DesiredSize.Width;	0
13845794	13819685	Connecting MS Access database when another application using the same MS Acess File	conn.ConnectionString = "FIL=MS Access;DSN=your_dsn_name";	0
30683531	30683402	C# code to retrieve xml data	using (WebClient client = new WebClient())\n{\n    client.Headers.Add("Accept-Language", " en-US");\n    client.Headers.Add("Accept", "application/xml");\n    client.Headers.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");\n\n    XDocument xml = XDocument.Parse(client.DownloadString("http://api.arbetsformedlingen.se/af/v0/platsannonser/matchning?lanid=1&kommunid=180&yrkesid=2419&1&antalrader=10000"));\n}	0
2715730	2714360	How to access a silverlight control's properties and methods from an aspx page?	[ScriptableMember]\npublic int GetValueFromSilverlight()\n{\n    // lame example\n    return int.Parse(textBox.Value);\n}	0
1646504	1646484	Parse string with regex	string input = "a3:S8:[gmpage]S17:Head GM NecrocideS12:test [15158]";\nstring output = Regex.Replace(myString, "NecrocideS\d\d:", "Necrocide:");	0
7847797	7847729	How to query using criteria to obtain all objects whose propriety is different than any string value in a list?	ActiveRecordMediator<Person>.FindAll(Expression.Not(Expression.In("Name", names)))	0
18827349	18826508	How to get start and end date	DateTime lastWeekSaturday = DateTime.Now.AddDays(-2);\nDateTime thisWeekFriday = DateTime.Now.AddDays(4);	0
32941588	32941532	Populating a combobox with c# using MVVM paradigm	public long ugp_id { get; set; }\npublic String groupName { get; set; }	0
5207100	5206949	How to find a Windows Forms Application's Product Code?	"ProductCode" = "8:{GUID}"	0
4572782	4565375	Parsing a torrent info from multiple trackers and storing in a database	announce-list	0
22276607	22275328	WPF ObservableCollection : possible to modify one particular property on all items at once?	foreach(var zone in zones.Where(z => z.IsFiltered))\n{\n     zone.IsFiltered = false;\n}	0
6039512	6039501	c#: how to set combobox valuemember from linq query	var qaNames = (\n    from a in db.LUT_Employees\n    where a.position == "Supervisor" && a.department == "Quality Assurance"\n    select new { a.ID, Names = a.lastName + ", " + a.firstName })\n    .ToList();\n\ncboQASupervisor.DataSource = qaNames;\ncboQASupervisor.DisplayMember = "Names";\ncboQASupervisor.ValueMember = "ID";	0
4959716	4959509	Accessing a UserControl from different Usercontrol	this.Parent.FindControl("UsrCtrl2Name")	0
18899230	18899172	How do I find out the value of these dwFlags constants?	[Flags()]\npublic enum ChangeDisplaySettingsFlags : uint\n{\n    CDS_NONE = 0,\n    CDS_UPDATEREGISTRY = 0x00000001,\n    CDS_TEST = 0x00000002,\n    CDS_FULLSCREEN = 0x00000004,\n    CDS_GLOBAL = 0x00000008,\n    CDS_SET_PRIMARY = 0x00000010,\n    CDS_VIDEOPARAMETERS = 0x00000020,\n    CDS_ENABLE_UNSAFE_MODES = 0x00000100,\n    CDS_DISABLE_UNSAFE_MODES = 0x00000200,\n    CDS_RESET = 0x40000000,\n    CDS_RESET_EX = 0x20000000,\n    CDS_NORESET = 0x10000000\n}\n\n[DllImport("user32.dll")]\npublic static extern DISP_CHANGE ChangeDisplaySettings(ref DEVMODE devMode, ChangeDisplaySettingsFlags flags);	0
11583063	11523934	DocumentFormat.OpenXml - how can I find an element's opacity	using DocumentFormat.OpenXml.Packaging;\nusing System;\nusing System.Linq;\nusing DRAW = DocumentFormat.OpenXml.Drawing;\nusing DocumentFormat.OpenXml.Presentation;\n\n.....\n\nusing (PresentationDocument outputDocument = PresentationDocument.Open(@"C:\Users\YN\Desktop\80.pptx", true))\n{\n\n    Slide slide = outputDocument.PresentationPart.SlideParts.First<SlidePart>().Slide;\n    CommonSlideData csd = slide.GetFirstChild<CommonSlideData>();\n    ShapeTree st = csd.GetFirstChild<ShapeTree>();\n    Shape s = st.GetFirstChild<Shape>();\n    ShapeProperties sp = s.GetFirstChild<ShapeProperties>();\n    DRAW.SolidFill sf = sp.GetFirstChild<DRAW.SolidFill>();\n    DRAW.SchemeColor sc = sf.GetFirstChild<DRAW.SchemeColor>();\n    DRAW.Alpha a = sc.GetFirstChild<DRAW.Alpha>();\n    Console.WriteLine((int)a.Val);\n\n}	0
6018809	6018756	howto delete rows from DataTable in C# with a filter?	public void DeleteOldById(DataTable table, int id)\n{\n      var rows = table.Rows.Cast<DataRow>().Where(x => (int)x["ID"] == id);\n      DateTime specifyDate = rows.Max(x => (DateTime)x["Date"])\n\n      rows.Where(x =>(DateTime)x["Date"] < specifyDate).ToList().\n           ForEach(x => x.Delete());\n}\n\n\npublic void DeleteAllOldRows(DataTable table)\n{\n     var ids = table.Rows.Cast<DataRow>().Select(x => (int)x["ID"]).Distinct();\n     foreach(int id in ids)\n        DeleteOldById(table,id);\n}	0
24782689	24781822	How to check existing record field and compare with post data before change ?	//don't get this object from database \n//PurchaseMaster pm = db.PurchaseMasters.Find(myId); \n\nif (db.PurchaseMasters.Any(x  =>x.Id == myId && x.OrderStatus != "Received") {\n   // Do your stuff\n}	0
1701807	1701788	How to convert string[] to ArrayList?	string[] myStringArray = new string[2];\nmyStringArray[0] = "G";\nmyStringArray[1] = "L";\n\nArrayList myArrayList = new ArrayList();\nmyArrayList.AddRange(myStringArray);	0
4915437	4914999	Marshaling unmanaged char** to managed string[]	int count = 10;\nint maxLen = 25;\nIntPtr[] buffer = new IntPtr[count];\n\nfor (int i = 0; i < count; i++)\n    buffer[i] = Marshal.AllocHGlobal(maxLen);\n\nTestArray(buffer, count, maxLen);\n\nstring[] output = new string[count];\nfor (int i = 0; i < count; i++)\n{\n    output[i] = Marshal.PtrToStringAnsi(buffer[i]);\n    Marshal.FreeHGlobal(buffer[i]);\n}	0
3309107	3308718	Persist List<int> through App Shutdowns	public void Serialize(List<int> list, string filePath)\n{\n  using (Stream stream = File.OpenWrite(filePath))\n  {\n    var formatter = new BinaryFormatter();\n    formatter.Serialize(stream, list);\n  }\n}\n\npublic List<int> Deserialize(string filePath)\n{\n  using (Stream stream = File.OpenRead(filePath)\n  {\n    var formatter = new BinaryFormatter();\n    return (List<int>)formatter.Deserialize(stream);\n  }\n}	0
21627971	21627648	How to import MDB file, read and save in SQL	if (reader.HasRows)\n{\n    while (reader.Read())\n    {\n        sqlComm.Parameters.AddWithValue("@CODIGO", reader[0]);\n        sqlComm.Parameters.AddWithValue("@NF_CONTA", reader[1]);\n        sqlComm.Parameters.AddWithValue("@TEXTO", reader[2]);\n        sqlComm.ExecuteNonQuery();\n    }\n}	0
12571478	12571224	Find and replace dynamic values via for loop	List<string> keys = new List<string>() { "name", "age", "param3" };\n    string url = "http://www.test.com/test.aspx?testinfo=&|&;";\n    Regex reg = new Regex("&");\n    int count = url.Count(p => p == '&');\n\n    for (int i = 0; i < count; i++)\n    {\n        if (i >= keys.Count)\n            break;\n        url = reg.Replace(url, keys[i], 1);\n    }	0
27644495	27644368	How to get progress of ZipFile.Read()	ReadOptions myReadOptions = new ReadOptions { ReadProgress = ExtractProgressHandler };\nusing (ZipFile zip = ZipFile.Read(FileName, myReadOptions))\n{\n    zip.ExtractProgress += ExtractProgressHandler;    \n    zip.ExtractAll(AppDomain.CurrentDomain.BaseDirectory + "\\Library\\" + zip.Comment,ExtractExistingFileAction.OverwriteSilently);               \n}	0
13608765	13608437	XML Stream returning zero rows	DataTable xmlComments = new DataTable();\n\nxmlComments.TableName = "item"; //<---- Added\nxmlComments.Columns.Add("User", typeof(string));\nxmlComments.Columns.Add("Date", typeof(string)); //<---- Type changed\nxmlComments.Columns.Add("Comment", typeof(string));\nxmlComments.Columns.Add("Restricted", typeof(string)); //<---- Column name changed\n\nxmlComments.ReadXml(xmlStream);	0
16086132	16085754	How to add hyperlinks into Word docx using open XML?	using (WordprocessingDocument doc = WordprocessingDocument.Open("", true))\n{\n    doc.MainDocumentPart.Document.Body.AppendChild(\n        new Paragraph(\n            new Hyperlink(new Run(new Text("Click here")))\n            {\n                 Anchor = "Description",\n                 DocLocation = "location",\n             }\n        )\n    );\n\n    doc.MainDocumentPart.Document.Save();\n\n}	0
5432324	5432130	Binding to a property in a UserControl	public static DependencyProperty EditorTextProperty = DependencyProperty.Register("ExpressionText", typeof(string), typeof(MyUserControl),\n          new PropertyMetadata(new PropertyChangedCallback((s, e) =>\n          { })));\npublic string ExpressionText\n{\n    get\n    {\n        return (string)base.GetValue(EditorTextProperty);\n    }\n    set\n    {\n        base.SetValue(EditorTextProperty, value);\n    }\n}	0
5750175	5749826	Need to get the "PRINT" value in C#	SqlConnection.InfoMessage	0
4189333	4189297	converting string to uint	UInt32 x = Convert.ToUInt32(location_txtbox.Text, 16);	0
15540879	15540818	summary of the gridview	decimal totalPrice = 0M;\nint totalItems = 0;\nprotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n  {\n    ...\n\n   }	0
6136119	6135903	How can 'Group By' on a ultrawingrid column?	private void SwitchGroupByFor(string key) //key stands for the ultragridcolumn key\n    {\n        var band = grid.DisplayLayout.Bands[0];\n        var sortedColumns = band.SortedColumns;\n\n        sortedColumns.Add(key, false, true); //last flag indicates is a group by column\n    }	0
14037211	14036854	Can't convert a variable to Guid	Guid guid = new Guid(Periodid);	0
24049600	24029694	Convert Nested for loops into Linq	var messageCodesQuery =\n    from newMessageCode in newDiffMsgCodeCollection\n    from oldMessageCode in oldDiffMsgCodeCollection\n    where newMessageCode.MessageCode == oldMessageCode.MessageCode\n    select new MessageCodes()\n    {\n        MessageCode = newMessageCode.MessageCode,\n        LangCollection = (\n            from newLangNode in newMessageCode.LangCollection\n            from oldLangNode in oldMessageCode.LangCollection\n            let newCode = newLangNode.Key.Trim().ToLower()\n            let oldCode = oldLangNode.Key.Trim().ToLower()\n            where newCode == oldCode\n            where newLangNode.Value != oldLangNode.Value\n            select new { newCode, oldCode }\n        ).ToDictionary(x => x.newCode, x => x.oldCode)\n    };	0
28750354	28750101	Populating textboxes and labels from with specific variables from Listbox or List<T>	if (queryResult.size > 0)\n{               \n    for (int i = 0; i < queryResult.size; i++)\n    {                    \n         User user = (User)queryResult.records[i];\n          id = user.Id;\n          firstName = user.FirstName;\n          lastName = user.LastName;\n          role = user.UserRole.Name;\n          string[] uSers = { id, firstName, lastName, role };\n         listEdit.AddRange(uSers);\n         // adds Items in uSers to lstEditUser\n         lstEditUser.Items.Add(string.Format("{0}  {1} {2}   {3}", uSers));      \n         lstDeleteUser.Items.Add(string.Format("{0}  {1} {2}       {3}",uSers));     \n    }\nlstEditUser.SelectedIndexChanged += SelectNewUser;\nlstEditUser.SelectedIndex = 0;\n    MessageBox.Show("The query result has found " + queryResult.size  + " users.");\n\n}\n\nprivate void SelectNewUser (object sender, EventArgs e)\n{\n    int idx = lstEditUser.SelectedIndex;\n    if (idx < 0)\n        return;\n    lblUserID.Text = listEdit[idx*4];\n}	0
4143275	4143158	C# regular expression to find custom markers and take content	Regex theRegex = new Regex(@"\[MM\](\d+)\[/MM\]");\ntext = theRegex.Replace(text, delegate(Match thisMatch)\n{\n\n    int mmLength = Convert.ToInt32(thisMatch.Groups[1].Value);\n    int cmLength = mmLength / 10;\n    return cmLength.ToString() + "cm";\n});	0
22479340	22479061	Filling a DataTable from a List	table.Columns.Add(prod, typeof(Product));	0
9640068	9640023	How to check if a file has been modified in c#	using (var md5 = new MD5CryptoServiceProvider())\n        {\n            var buffer = md5.ComputeHash(File.ReadAllBytes(filename));\n            var sb = new StringBuilder();\n            for (var i = 0; i < buffer.Length; i++)\n            {\n                sb.Append(buffer[i].ToString("x2"));\n            }\n            return sb.ToString();\n        }	0
22777935	22777669	Find out the members of Subgroup using C#	if (gp != null) // gp is your instance of GroupPrincipal \n{\n  foreach (Principal p in gp .GetMembers(recursive: true))\n  {\n    Console.WriteLine(p.Name);\n  }\n  gp .Dispose();\n}	0
2584644	2584628	How to Load type from string directly into linq expression in C#?	Type.GetType	0
26670098	26668393	Setting the FillColor of MS Excel Cell using NumberFormat	.NumberFormat	0
1630209	1630183	GetHashCode for a Class with a List Object	override int GetHashCode()\n{\n  return Edges.Distinct().Aggregate(0, (x,y) =>x.GetHashCode() ^ y.GetHashCode());\n}	0
25363562	25329323	Using textures in wpf 3D	points: 0,0,0    0,0,1    1,0,0    1,0,1      0,1,0     0,1,1\n\nindices: 0 2 1   2 3 1   0 1 4   1 4 3\n\ntexture coordinates: 0,1 0,0 1,1 1,0 1,1 1,0\n\nexample how i fixed:\n\npoints: 0,0,0    0,0,1    1,0,0    1,0,1    0,0,0    0,0,1    0,1,0     0,1,1\n\nindices: 0 2 1   2 3 1    4 5 6   7 6 4\n\ntexture coordinates: 0,1 0,0 1,1 1,0    1,1 1,0  0,1 0,0	0
3205346	982481	Trying to Build and Publish Asp.net website from command line using aspnet_compiler	aspnet_compiler -v/WebsiteOne -p c:\projects\Website1 -f c:\Inetpub\wwwroot\WebsiteOne	0
9125045	9125005	how to read an html file and replace with our characters	String s = s.Replace("XXXXX", "23453");	0
8491548	8491469	Inserting a special character at the proper place in a string using C#	int pos1 = text.IndexOf('-');    \nint pos2 = text.IndexOf(' ', pos1);    \nstring result = text.Insert(pos2+1, "#");	0
22846287	22840457	Set search textbox above datagridviewcolomns	protected override void OnLoad(EventArgs e) {\n  base.OnLoad(e);\n  fillPanelWithSearch();\n}	0
21379975	21379521	Func delegate used as a parameter	new Func<BusinessMetadataQueryDataContract,\n            AsyncCallback,\n            object,\n            IAsyncResult>(\n   this.Channel.BeginBusinessMetadataGet)	0
34187818	34187357	Manipulating index values of array property get/set	class DongeonFloor\n{\n    private room[,] room=new room[rows,columns];\n    public Room this[int i,int j] {\n    get\n    {\n        return room[i+1,j+1]; //modify for whatever the offset is \n    }\n    private set{\n        room[i-1,j-1]=value;\n    }\n\n\n}	0
6287562	6285889	Button inside RowDetailsTemplate in DataGrid - how to know which row clicked on?	var myObject = (sender as FrameworkElement).DataContext as MyObject;	0
3617628	3617533	Error with calling stored procedure from C#	using (SqlConnection connection = new SqlConnection(connectionString))\nusing (SqlComamnd command = connection.CreateCommand())\n{\n    command.CommandText = commandText;\n    command.CommandType = CommandType.StoredProcedure;\n\n    command.Parameters.Add("@lat1", SqlDbType.Float,50, lat1).Value = lat1;\n    command.Parameters.Add("@lng1", SqlDbType.Float,50, lng1).Value = lng1;\n    command.Parameters.Add("@radius1", SqlDbType.Int,10, radius1).Value = radius1;\n    command.Parameters.Add("@streetname", SqlDbType.VarChar, 50, streetname).Value = streetname;\n    command.Parameters.Add("@keyword1", SqlDbType.VarChar, 50, keyword1).Value = keyword1;\n\n    connection .Open();\n    DataSet ds = new DataSet();\n    using (SqlDataAdapter adapter = neq SqlDataAdapter(command))\n    {\n        adapter.Fill(ds);                \n    }\n}	0
3588492	3588467	How to detect a C++ identifier string?	"^[a-zA-Z_][a-zA-Z0-9_]*$"	0
24422752	24406401	Xamarin SetError validation on EditText	if (IsValidEmail(e.Text.ToString()))\n{\n    //change icon to green\n    emailEditText.SetCompoundDrawablesWithIntrinsicBounds(0, 0, Resource.Drawable.correctIcon, 0);\n}\nelse\n{\n    //change icon to red\n    emailEditText.SetCompoundDrawablesWithIntrinsicBounds(0, 0, Resource.Drawable.errorIcon, 0);\n}	0
5716031	5714657	How to insert non repeted values when i click previous button in asp.net	SqlCommand cmd = new SqlCommand("SELECT Count(*)from Sel_Ans WHERE Quid=" + a[Convert.ToInt32(Session["Counter"]) - 1] + "", sqlconn);\n\n            sqlconn.Open();\n            int result = cmd.ExecuteScalar();\n            if (result != 0)	0
23931749	23931690	WCF: Is it good practice to send null response from Server	return new Product[]	0
14313563	14293228	How to encrypt files using EFS with vbscript?	WshShell sh1 = new WshShell(); \nvar retval = sh1.Run("CIPHER /E /S:" & strDir, 0, True);	0
21639390	21639194	loop in xml and delete some values	var xDoc = XDocument.Load(filename); //XDocument.Parse(xmlstring);\n\nxDoc.Descendants()\n    .SelectMany(d => d.Attributes())\n    .Where(a => a.Name == "Att1" || a.Name == "Att2")\n    .ToList()\n    .ForEach(x => x.Remove());\n\nvar newXml = xDoc.ToString(); //xDoc.Save(filename);	0
23267487	23266797	Creating nested objects from JSON	public class Scheduling\n{\n    public DateTime date { get; set; }\n    public string description { get; set; }\n}\n\npublic class RootObject\n{\n    public string to { get; set; }\n    public Scheduling scheduling { get; set; }\n    public string id { get; set; }\n}	0
32090671	32090207	Foreign Key with Fluent API - Code First	modelBuilder.Entity<UserProduct>()\n            .HasRequired(x => x.User) \n            .WithMany(u => u.Orders) \n            .HasForeignKey(x => x.OrderId);	0
6600664	6600070	How to get all records for the entire day?	DateTime userDayStart = TimeZoneInfo.ConvertTimeFromUtc(\n    DateTime.UtcNow,\n    usersTimeZone\n).Date;\n\nDateTime utcStart = TimeZoneInfo.ConvertTimeToUtc(\n    userDayStart,\n    usersTimeZone\n);\n\nDateTime utcEnd = TimeZoneInfo.ConvertTimeToUtc(\n    userDayStart.AddDays(1),\n    usersTimeZone\n);	0
27573287	27573168	How to click this Frame Name in selenium c#	driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@name,'fancybox-frame')]")));	0
23780275	23780084	Use WillCascadeOnDelete	obj1.Children = obj2, obj3\nobj2.Children = obj4, obj5\nobj5.Children = obj1, someOtherObjs\n\ndeleting obj1 -----------<-----------\n    should delete obj2              |\n        should delete obj5          |\n            should delete obj1 -->---	0
10538858	10538737	How to get all Images src's of some html	foreach (Match m in Regex.Matches(sometext, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))\n{\n    string src = m.Groups[1].Value;\n    // add src to some array\n}	0
11413061	11412853	Splitting text from text file in c#	var keyValue = new Dictionary<string, string>();\nforeach (var lineItem in System.IO.File.ReadAllLines(@"C:\Users\Kane\Desktop\yourFile.txt").Where(x => x.Contains(": ")))\n{\n    var splitPosition = lineItem.IndexOf(": ", System.StringComparison.OrdinalIgnoreCase);\n    var key = lineItem.Substring(0, splitPosition);\n    var value = lineItem.Substring(splitPosition + 1);\n\n    // add in functions for checking null\n    // add in functions for trimming\n    // add in special cases for \n    keyValue.Add(key, value);\n}	0
14041328	14041286	Regex pattern allowing alphabets, numbers, decimals, spaces and underscore	'[a-zA-Z0-9_. ,]*'	0
17056518	17054736	Using Entity Framework, return all rows with date port of DateTime column equal to today	DateTime today = DateTime.Today;                    // earliest time today \n            DateTime tomorrow = DateTime.Today.AddDays(1);      // earliest time tomorrow\n\n            var q = db.Objects\n                        .Where(x => x.Time >= today)\n                        .Where(x => x.Time < tomorrow);	0
19628250	19581889	Changing from xaml design into C# coding	void SearchPeers()\n {\n     List<string> name = new List<string>();\n     var peers = await PeerFinder.FindAllPeersAsync();\n     for(int i=0;i<peers.Count;i++)\n     {\n       string peerName = peers.DisplayName;\n       name.Add(peerName);\n     }\n }	0
12770399	12770251	ServiceStack Redis how to implement paging	var redisAnswers = Redis.As<Answer>();\n\nredisAnswers.StoreAll(q1Answers);\nq1Answers.ForEach(redisAnswers.AddToRecentsList); //Adds to the Recents List\n\nvar latest3Answers = redisAnswers.GetLatestFromRecentsList(0, 3);\n\nvar i = q1Answers.Count;\nvar expectedAnswers = new List<Answer>\n{\n    q1Answers[--i], q1Answers[--i], q1Answers[--i],\n};\n\nAssert.That(expectedAnswers.EquivalentTo(latest3Answers));	0
29116460	29116261	Anonymous methods and with some constant arguments	VAR3 = (x)=>FUNC2(x,8);	0
1874591	1874385	How to create a full screen application in Win CE 6.0 using .NET Compact Framework 3.5?	HWND hwndTaskbar = ::FindWindow(_T("HHTaskBar"), NULL); \n::ShowWindow(hwndTaskbar, SW_HIDE);	0
1515810	1471127	How to flush pending FileSystemWatcher events?	while (true)\n{\n    WaitForChangedResult res = watcher.WaitForChanged(WatcherChangeTypes.All, 1);\n    if (res.TimedOut)\n         break;\n}	0
6555619	6550854	How to detect Copy event of WebBrowser control?	private void myBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    myBrowser1.Document.GetElementsByTagName("body")[0].AttachEventHandler("oncopy", SayHello);\n}\n\npublic void SayHello(object obj,EventArgs e)\n{\n    MessageBox.Show("Hello"); //Do your stuff here.\n}	0
29539445	29539332	How to get size of a file using C#?	System.IO.FileInfo fi = new System.IO.FileInfo(@"c:\temp\" + newFile + "__" + fileName);\nlong fileSizeInBytes = fi.Length; //size in Bytes	0
6496818	6496414	How To Handle Image as Background to CAD Application	private static Bitmap Resample(Image img, Size size) {\n        var bmp = new Bitmap(size.Width, size.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);\n        using (var gr = Graphics.FromImage(bmp)) {\n            gr.DrawImage(img, new Rectangle(Point.Empty, size));\n        }\n        return bmp;\n    }	0
13663977	13663562	Benchmark inconsistent results	GC.Collect	0
34306873	34305630	REST web method in fiddler parameter is null	[WebInvoke(RequestFormat = WebMessageFormat.Json)]\nList<string> getPackPreviews(PackFilter filter){}	0
995221	995142	combining lambda expressions to property paths	Expression.Invoke	0
425847	259364	How do I configure Emacs speedbar for C# mode?	(speedbar-add-supported-extension ".cs")\n   (add-to-list 'speedbar-fetch-etags-parse-list\n        '("\\.cs" . speedbar-parse-c-or-c++tag))	0
8619663	8619520	C# regex - not matching my string	if ( !Regex.IsMatch( text , @"\b" + mm + @"\b:" , RegexOptions.Multiline ) )	0
30795609	30794697	Bind grid view data from existing code, current date	string connetionString = null;\nSqlConnection connection;\nSqlCommand command;\nstring sql = null;\n\nconnetionString = "Data Source=AXSQL;Initial Catalog=UniKL;User ID=aten;Password=pass@WORD1";\nsql = "Select * FROM [UniKL].[dbo].[BudgetPlanning_Transaction] WHERE [SubmmitedDateTime] = cast(getdate() as date)";\n\n//GridView1.DataBind();\n\nconnection = new SqlConnection(connetionString);\nconnection.Open();\ncommand = new SqlCommand(sql, connection);\n\n//Get data into a reader\nSqlDataReader sr = command.ExecuteReader();\n//command.ExecuteNonQuery();\n\n//Set the datasource of GridView1\nGridView1.DataSource = sr;\nGridView1.DataBind();\n\n\ncommand.Dispose();\nconnection.Close();	0
19425607	19424526	Compare a byte[] or a Base64String to a T-SQL timestamp	-- Convert Base64 value to varbinary \nselect cast ('AAAAAA1iUFw=' as varbinary(20))	0
32026347	32026319	Load a web page to send data	var fullUrl = url + info;\nvar conent = new System.Net.WebClient().DownloadString(fullUrl);	0
13321786	13321716	Is there anything that reduces the Olson time zone list into a readable format for the UI (like Google Calendar does)?	zone.tab	0
25814532	25814446	How do i make like a switch when pressing on keys in the keybaord?	void gkh_KeyDown(object sender, KeyEventArgs e)\n{\n  if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == System.Windows.Forms.Keys.O)\n    cbDrawOverlay.Checked = !cbDrawOverlay.Checked;\n}	0
15165466	15098045	Inserting text with SendMessage	[DllImport("user32.dll", CharSet = CharSet.Auto)]\nstatic extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n//...\nIntPtr boo = new IntPtr(1);\nSendMessage(handle, EM_SETMODIFY, boo, IntPtr.Zero);	0
13452030	13451929	Create a Dictionary using Linq	XDocument xDoc = XDocument.Parse(xml);\nvar dict = xDoc.Descendants("student")\n                .ToDictionary(x => x.Attribute("name").Value, \n                              x => new Info{ \n                                  Addr=x.Attribute("address").Value,\n                                  Avg = x.Attribute("avg").Value });\n\n\nvar cDict = new ConcurrentDictionary<string, Info>(dict);	0
20423915	20423862	Closing the tab in browser after calling a ashx handler	r.Write("<script type='text/javascript'>alert('brak dokumentu w bazie');window.close();</script>");	0
4019982	4008361	Gtk#: How to convert a Gtk.Image in a Gdk one?	public static void ShowImage(Gdk.Window w, Gtk.Image image)\n{\n    w.DrawImage( Style.ForegroundGC( StateType.Normal ),\n                     image.ImageProp,             // TRY THIS                              \n                     0, 0, image.Pixbuf.Width, image.Pixbuf.Height,\n                     image.Pixbuf.Width, image.Pixbuf.Height\n    );\n}	0
12040698	12040239	Save Email Upon Send in Outlook Add-In	private void saveEmail(object Item, ref bool Cancel)\n{\n         var msg = Item as Outlook.MailItem;\n         msg.SaveAs(yourPath, Outlook.OlSaveAsType.olMSG);\n}	0
22920426	22901251	Group By Query with Entity Framework	var query = dbContext.Category.Select(u => new \n{ \n    Cat = u, \n    MovementCount = u.Movement.Count() \n})\n.ToList()\n.OrderByDescending(u => u.MovementCount)\n.Select(u => u.Cat)\n.ToList();	0
2078926	2078914	Creating a Generic<T> type instance with a variable containing the Type	var genericListType = typeof(List<>);\nvar specificListType = genericListType.MakeGenericType(typeof(double));\nvar list = Activator.CreateInstance(specificListType);	0
34092729	34091964	How to define EF Many To Many Relationship in type that has other relationships to the same other type	modelBuilder.Entity<TypeA>().HasMany<TypeB>(i => i.Bees).WithMany();\nmodelBuilder.Entity<TypeB>().HasMany<TypeA>(i => i.Aaas).WithMany();	0
7125203	7125178	Comparing contents of a List<int> to find matches	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);	0
24803707	24803177	How can I deserialize an XML - Windows Phone	[XmlRoot("root")]\npublic class Destinataires\n{\n    [XmlArray("Destinataires")]\n    [XmlArrayItem("Destinataire")]\n    public ObservableCollection<XML_Arret> Collection { get; set; }\n}	0
28574089	28574027	What's the syntax for writing to files with SaveFileDialog	using (var myStream = saveFileDialog1.OpenFile())\nusing (var writer = new StreamWriter(myStream))\n{\n    writer.WriteLine("File content goes here");\n}	0
23566615	23558363	Rename multiple variables in 1 click	Renamer.RenameSymbolAsync()	0
18886369	18885416	How to set selected index on listbox selection	Item found = itemList.Find(x => x.Name == (string)itemListBox.SelectedItem);\n        if (found != null)\n        {\n            nameText.Text = found.Name;\n            priceText.Text = Convert.ToString(found.Price);\n            urlText.Text = found.URL;\n        }	0
508641	508213	Is there a way to dynamically execute a string in .net, similar to eval() in javascript or dynamic sql in sql?	class MyDynamicEvalClass\n  def eval(someString,transformString)\n    eval(someString,transformString)\n  end\nend	0
10744043	10339877	ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient	using (var client = new HttpClient())\n{\n    using (var content = new MultipartFormDataContent())\n    {\n        var values = new[]\n        {\n            new KeyValuePair<string, string>("Foo", "Bar"),\n            new KeyValuePair<string, string>("More", "Less"),\n        };\n\n        foreach (var keyValuePair in values)\n        {\n            content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);\n        }\n\n        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));\n        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")\n        {\n            FileName = "Foo.txt"\n        };\n        content.Add(fileContent);\n\n        var requestUri = "/api/action";\n        var result = client.PostAsync(requestUri, content).Result;\n    }\n}	0
10253923	10253841	C# Unit testing, using XML from a zip file	ZipInputStream zip = new ZipInputStream(new MemoryStream(Properties.Resources.scripts));\nwhile (zip.GetNextEntry() != null)\n{\n  MemoryStream data = new MemoryStream();\n  zip.CopyTo(data);\n  data.Position = 0;\n  string scriptContents = new StreamReader(data).ReadToEnd();\n  /// do something with scriptContents variable\n}	0
1674182	1674160	Converting little endian to int	int GetBigEndianIntegerFromByteArray(byte[] data, int startIndex) {\n    return (data[startIndex] << 24)\n         | (data[startIndex + 1] << 16)\n         | (data[startIndex + 2] << 8)\n         | data[startIndex + 3];\n}\n\nint GetLittleEndianIntegerFromByteArray(byte[] data, int startIndex) {\n    return (data[startIndex + 3] << 24)\n         | (data[startIndex + 2] << 16)\n         | (data[startIndex + 1] << 8)\n         | data[startIndex];\n}	0
3325796	3325326	Using a C# regex to parse a domain name?	Uri uri = new Uri("http://www.google.com/search?q=439489");\n            string url = uri.Host.ToString();\n            return url;	0
9951358	9951343	FormatException while converting string to DateTime	"dd/MM/yyyy hh:mm:ss"	0
16882313	16882292	Read regiondata as rectangles	RectangleF[] rects = region.GetRegionScans(new Matrix());	0
21189085	21188868	Adding properties to a bitmap object that's created by calling another method within a constructor	public Bitmap overlayBitmap\n{\n    get\n    {\n        // Build bitmap overlay\n        return overlayBitmapOutput;\n    }\n...\n}	0
15787049	15786958	Change all keys in a Dictionary	Dictionary<DateTime, bool> dates = new Dictionary<DateTime, bool>()\n{\n    {\n        DateTime.Now, true\n    }\n};\n\nvar modifiedDic = dates.ToDictionary(z => z.Key.AddDays(-1), z => z.Value);	0
312196	311250	DropDownList.SelectedValue changes (as a child control in a FormView) aren't sticking	protected void FrmAdd_DataBound(object sender, EventArgs e)\n{\n    // This is the same code as before, but done in the FormView's DataBound event.\n    ((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =\n    ((Guid)Membership.GetUser().ProviderUserKey).ToString();\n}	0
32551860	32551502	How to return to main menu with many menu inside?	static void Main(string[] args)   \n  {\n      int choice = 0;\n      while (choice != 3)\n      {\n           Console.WriteLine("Main Menu");\n           Console.WriteLine("Rent=1");\n           Console.WriteLine("Return=2");\n           Console.WriteLine("Exit=3)");\n           choice = GetUserChoice("What is your choice?", choice);\n           if (choice == 1)\n           {\n              //when complete all thing in choice 1\n              choice = GetUserChoice("Do you want to start over?(Y=1,N=3)", choice);\n           }\n           else if(choice == 2)\n           {\n               //when complete all thing in choice 2\n               choice = GetUserChoice("Do you want to start over?(Y=1,N=3)", choice);\n           }\n       }\n   }\n\n   private static int GetUserChoice(string question, int choice)\n   {\n       Console.WriteLine(question);\n       return  Convert.ToInt32(Console.ReadLine());\n   }	0
5968014	5955519	How do you resolve a Ninject dependency in the global file in ASP.NET?	[Inject]\npublic IErrorLogEntryController ErrorLogEntryController { get; set; }	0
3967133	3967083	Split 8 bit byte	public class FoutBitsArrayEnumerator : IEnumeable<byte>\n{\n  FoutBitsArrayEnumerator(byte[] array)\n  {\n    this.array = array;\n  }\n  public IEnumerator<byte> GetEnumerator\n  {\n    foreach (byte i in array)\n    {\n        yield return i & 15;\n        yield return (i >> 4) & 15;\n    }\n  }\n\n  byte[] array;\n}	0
11630020	11629914	How to add new string to Registry Entry of type REG_MULTI_SZ?	key.SetValue("MultipleStringValue", new string[] {"One", "Two", "Three"});	0
30471937	30471903	Range Attribute for Dates	[RangeDate(ErrorMessage = "Value for {0} must be between {1:dd/MM/yyyy} and {2:dd/MM/yyyy}")]\npublic DateTime anyDate { get; set; }	0
3378328	3378291	Duplicates in Listbox when displaying items from a List<T>. Please help!	public void UpdateEmployeeList()\n{\n    lstResults.Items.Clear();\n    foreach (Employees values in employeeRegistry.employeerList)\n    {\n       lstResults.Items.Add(values);\n    }\n}	0
11540039	11518625	How to bind data from BitmapData to WPF Image Control?	[ValueConversion(typeof(BitmapData), typeof(ImageSource))]\npublic class BitmapDataConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        BitmapData data = (BitmapData)value;\n        WriteableBitmap bmp = new WriteableBitmap(\n            data.Width, data.Height,\n            96, 96,\n            PixelFormats.Bgr24,\n            null);\n        int len = data.Height * data.Stride;\n        bmp.WritePixels(new System.Windows.Int32Rect(0, 0, data.Width, data.Height), data.Scan0, len, data.Stride, 0, 0);\n        return bmp;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new NotSupportedException();\n    }\n}	0
26259307	26250966	NServiceBus 5 with RabbitMQ defining an EndpointName with single broker queue	configuration.UseTransport<RabbitMQTransport>()\n.DisableCallbackReceiver();	0
12519430	12519144	C# Button with Text and Down Arrow	Button1.Text = "Details " + char.ConvertFromUtf32(8595);	0
12956073	12955766	How do I define a DataRelation between a DataSet's DataTables on multiple columns?	DataSet dsMain = new DataSet();\nDataRelation newRelation = new DataRelation("processData",\n    new DataColumn[] { dtNames.Columns["EmpName"], dtNames.Columns["EmpRole"] },\n    new DataColumn[] {dtDetails.Columns["EmpName"], dtDetails.Columns["EmpRole"]}\n);\ndsMain.Relations.Add(newRelation);	0
33537046	33536654	Implementing close_far solution logic	public static bool Foo(int a, int b, int c)\n{\n    var x = Math.Abs(a-b);\n    var z = Math.Abs(c-a);\n\n    var close = x>z?c:b;\n    var far = x>z?b:c;\n\n    return Math.Abs(close-a)<=1 \n            && Math.Abs(far-a)>=2 \n            && Math.Abs(far-close)>=2;\n}	0
11599660	11599647	Next letters as against a char variable	textbox1.Text = ((char)(((int)c) + 2)).ToString();	0
16308900	16308761	How do I get Entity Framework 5 to update stale data	dbContext.Entry(entity).Reload();	0
10670423	10670149	How do I make a ListBox refresh the text?	private void btnUpdate_Click(object sender, EventArgs e)\n        {\n            Employee selectedEmployee = (Employee)lstEmployees.SelectedItem;\n            selectedEmployee.Name = "Joseph";\n            if (selectedEmployee != null)\n            {\n                _employees[selectedEmployee.Id] =selectedEmployee;\n            }\n        }	0
10607058	10584425	FluentMongo LINQ: How to query a sublist of a class	col.AsQueryable().Where(x => x.Any(y => y.Age < 40));	0
18716945	18716845	Add string to List<string>	public string SplitName(string text)\n{\n    string forename;\n    string middlename;\n    string surname;\n\n    var name = text.Split(' ');\n\n    if (name != null)\n    {\n        if (name.Length > 2)\n        {\n            forename = name[0];\n            surname = name[name.Length - 1];\n\n            middlename = string.Join(" ", name, 1, name.Length - 2);\n\n            text = string.Format("{0} {1} {2}", forename, middlename, surname);\n        }\n    }\n    else\n    {\n        text = "INVALID";\n    }\n\n    return text;\n}	0
14103967	14103899	Do I need to use a BaseClass for this scenario?	base class	0
22431079	22431047	Browse Network UNC path	Type type = oFolderBrowserDialog.GetType();\n                                         ^^^^^	0
7837132	7837082	update values in IQueryable doesn't save to database	foreach( var record in dinner.GetRecords(id).Where(d=>d.Year == Yearpassed))\n{\n   record.Year='2000';\n}\ndinner.Save();	0
28062857	28062654	Fill Datagridview rows from Datatable according to a DatagridviewComboboxCell value	if (cb.SelectedValue != null)	0
25166526	25162800	Numbers appear in scientifically notation in excel when data is exported from C# application	...\nxlWorkSheet.Cells[i + 1, j + 1].NumberFormat = "@";\nxlWorkSheet.Cells[i + 1, j + 1] = cell.Value\n...	0
6903367	6903256	How to programmatically check C++ DLL files and C# DLL files for references to debug DLLS to automate a testing procedure	[DllImport("kernel32.dll")]\nstatic extern IntPtr LoadLibrary(string dllToLoad);\n\n[DllImport("kernel32.dll")]\nstatic extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);\nconst UInt32 DONT_RESOLVE_DLL_REFERENCES = 0x00000001;\nconst UInt32 LOAD_LIBRARY_AS_DATAFILE = 0x00000002;\nconst UInt32 LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008;\n\n[DllImport("kernel32.dll")]\nstatic extern bool FreeLibrary(IntPtr hModule);\n\n[DllImport("kernel32.dll")]\nstatic extern UInt32 GetLastError();\n\nvoid CheckUnmanagedDll(string DllName)\n{\n    IntPtr hModule = LoadLibrary(DllName);\n    if (hModule.Equals(IntPtr.Zero))\n        MessageBox.Show("Can't find " + DllName);\n     FreeLibrary(hModule);\n }	0
18773822	18764080	Creating a dynamic query using IQueryable	var keywords=new List<string>(){ "Test1","Test2" };\n\nvar predicate = PredicateBuilder.False<QuestionsMetaDatas>();\n\nforeach (var key in keywords)\n{\n  predicate = predicate.Or (a => a.Text.Contains (key));\n}\n\nvar query = context.QuestionsMetaDatas.AsQueryable().Where(predicate);	0
5806603	5806242	Define foreground color of a itextsharp table cell	var FontColour = new BaseColor(31, 73, 125);\n    var MyFont = FontFactory.GetFont("Times New Roman", 11, FontColour );\n    table.AddCell(new Paragraph("My Text", MyFont));	0
2759478	1483701	MSI Log Debug Log Sink	using (Msi.Install msi = Msi.CustomActionHandle(_msiHandle))\n {\n     using (Msi.Record record = new Msi.Record(100))\n     {\n         record.SetString(0, "LOG: [1]");\n         record.SetString(1, entry.Message);\n         msi.ProcessMessage(Msi.InstallMessage.Info, record);\n     }\n }	0
5275438	5275366	Combine two generic lists of different types	List<BillDetails> billDetails = new List<BillDetails>();\n    List<Header> headers =new List<Header>();\n\n    var results = billDetails.Zip(headers, (details, header) => \n                                  new { details.chargecategory, details.materialcode, header.chargecode, header.customername })\n                             .ToList();	0
10400251	10400213	Using LINQ to read key value pair from configuration file	var result = File.ReadLines(pathToFile)\n                 .Select(line => line.Split(new[] { '=' }, 2))\n                 .Where(split => split.Length == 2)\n                 .ToDictionary(split => split[0], split => split[1]);	0
33881048	33880863	GroupBy multiple columns in Linq with Take()	var results = context.Entries\n    .Include(x => x.Contract)\n    .GroupBy(t=>t.Contract)\n    .Select(t=>new{\n        Contract=t.Key,\n        Years=t.GroupBy(s=>s.Year)\n            .Select(s=>new{\n               Year=s.Key,\n               Count=s.Count()\n            })\n        })\n     .Take(5);	0
1744457	1744429	Loop through controls in TabControl	TabPage page = aTabControl.SelectedTab;\n\n        var controls = page.Controls;\n\n        foreach (var control in controls)\n        {\n            //do stuff\n        }	0
26158410	26157475	Use of HttpListener	public static void Main(string[] args)\n{\n    HttpListener(new[] { "http://localhost/" });\n}	0
9036825	9033815	Message submission rate for this client has exceeded the configured limit?	SmtpMail.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;	0
16348798	16348650	Global Project Static Variables	/src\n    FooApp.sln                       -- solution file\n    /apps                            -- folder for apps\n        /FooApp.Core                 -- core project\n        /FooApp.Drawing1             -- project that references core\n        /FooApp.Drawing2             -- project that references core    \n    /tests                           -- tests\n        /FooApp.Core.Test\n        /FooApp.Drawing1.Test\n        /FooApp.Drawing2.Test	0
18467130	17962331	How to set certificate friendly name	Certificate.FriendlyName = "New Friendly Name";\nvar store = new X509Store("My");\nstore.Open(OpenFlags.ReadWrite);\nstore.Add(Certificate);	0
26457034	26432771	C# - Get NamedRanges of a particular sheet in Excel using Oledb	/// <summary>\n    /// The procedure examines the workbook that you specify, \n    /// looking for the part that contains defined names. \n    /// If it exists, the procedure iterates through all the \n    /// contents of the part, adding the name and value for \n    /// each defined name to the returned dictionary\n    /// </summary>\n    public static IDictionary<String, String> XLGetDefinedNames(String fileName)\n    {\n      var returnValue = new Dictionary<String, String>();\n      //\n      using (SpreadsheetDocument document = \n          SpreadsheetDocument.Open(fileName, false))\n      {\n        var wbPart = document.WorkbookPart;\n        //\n        DefinedNames definedNames = wbPart.Workbook.DefinedNames;\n        if (definedNames != null)\n        {\n          foreach (DefinedName dn in definedNames)\n            returnValue.Add(dn.Name.Value, dn.Text);\n        }\n      }\n      //\n      return returnValue;\n    }	0
4605344	4605283	check for an particular column name in datatable	foreach (DataColumn dc in dtNewTable.Columns) \n{\n      if(dc.ColumnName == "MONTH")\n      {\n           dc.DataType = typeof(string);\n      }\n}	0
11861301	11861118	How to handle the connection string in an external dll?	public static int Is_Valid_User(string p_u, string p_p, string connectionString)	0
1230253	1230223	Is it possible to raise an event on an object, from outside that object, without a custom function	EventArgs e = new EventArgs(myClassInstance);  // Create appropriate EventArgs\n\nMulticastDelegate eventDelagate = \n    this.GetType().GetField(theEventName + "Event",\n    System.Reflection.BindingFlags.Instance | \n    System.Reflection.BindingFlags.NonPublic).GetValue(myClassInstance) as MulticastDelegate;\n\nDelegate[] delegates = eventDelagate.GetInvocationList();\nforeach (Delegate del in delegates) {  \n      del.Method.Invoke(del.Target, new object[] { myClassInstance, e }); \n}	0
10441694	10441000	How to programmatically set the ForeColor of a label to its default?	if (lblExample.ForeColor != System.Drawing.Color.Red)\n{\n    lblExample.ForeColor = System.Drawing.Color.Red;\n}\nelse\n{\n    lblExample.ForeColor = new System.Drawing.Color();\n}	0
2520032	2519993	C# Loading a xml file from the current directory?	string fileName = Path.Combine(Application.StartupPath, "config.xml");	0
2867236	2867196	How can I make this simple C# generics factory work?	public class FactoryMap { \n  private Dictionary<Type,object> _map = new Dictionary<Type,object>();\n  public void Add<T>(IFactory<T> factory) {\n    _map[typeof(T)] = factory;\n  }\n  public IFactory<T> Get<T>() {\n    return (IFactory<T>)_map[typeof(T)];\n  }\n}	0
18034553	18034468	Syntax error in insert into statement in C# links to MS Access By ADO.NET	cmd.CommandText = "INSERT INTO Libarary ( ISBN, [Name], Gategory, Author, Cost, [Date]) " + \n                  "VALUES ( @ISBN, @Name, @Gategory, @Author, @Cost, @Date) ";	0
2948113	2948070	How to Open a Directory Sorted by Date?	static void Main(string[] args)\n{\n    var files = Directory.GetFiles(@"d:\", "*").OrderByDescending(d => new FileInfo(d).LastWriteTime);\n    foreach(var directory in files)\n    {\n        Console.WriteLine(directory);\n    }\n\n    Console.ReadLine();\n}	0
20136384	20136325	Converting variable to time (mm ss)	TimeSpan time = TimeSpan.FromSeconds(audio.Duration);\n\nDurationLabel.Text = String.Format("{0:D2}:{1:D2}:{2:D2}", \n                    (int)time.TotalHours,\n                    time.Minutes,\n                    time.Seconds);	0
22474802	22474309	Create a general "skeleton" from a c# project	File>Export Template	0
26906572	26905617	Convert IEnumerable string array to datatable	const char Delimiter = '|';\n\nvar dt = new DataTable;\nusing (var m = File.ReadLines(filePath).GetEnumerator())\n{\n    m.MoveNext();\n    foreach (var name in m.Current.Split(Delimiter))\n    {\n        dt.Columns.Add(name);\n    }\n\n    while (m.MoveNext())\n    {\n        dt.Rows.Add(m.Current.Split(Delimiter));\n    }\n}	0
24798606	24798605	DataGridView Removed rows cells still show up in code, even though removed from Grid	DataView.Refresh();	0
16502308	16502180	Restart a Running Thread	private static void playWav(object sender, EventArgs e) {\n    //Reference to Thread\n    thread = new Thread(playWavThread);\n    thread.IsBackground = true;\n    thread.Start();\n}	0
6612173	6611924	creating a "join" to update one XElement from another XElement	foreach (XElement task in XTasks.Elements())\n {\n     XElement userNode = XUsers.Elements().Where(\n        e => e.Attribute("id").Value == task.Attribute("ownerId").Value).FirstOrDefault();\n     if (userNode != null)\n     {\n        task.Attribute("ownerName").SetValue(userNode.name);\n     }\n }	0
29710847	29710597	Get nested properties values	public static void Main(string[] args)\n{\n  var a = new A()\n  {\n    X1 = 1,\n    X2 = "2",\n    X3 = new List<B> { new B { Y1 = 5, Y2 = 7 } }\n  };\n\n  PrintProperties(a);\n}\n\nprivate static void PrintProperties(object obj)\n{\n  foreach (var prop in obj.GetType().GetProperties())\n  {\n    var propertyType = prop.PropertyType;\n    var value = prop.GetValue(obj);\n\n    Console.WriteLine("{0} = {1} [{2}]", prop.Name, value, propertyType);\n\n    if (typeof(IList).IsAssignableFrom(propertyType))\n    {\n      var list = (IList)value;\n\n      foreach (var entry in list)\n      {\n        PrintProperties(entry);\n      }\n    }\n    else\n    {\n      if (prop.PropertyType.Namespace != "System")\n      {\n        PrintProperties(value);\n      }\n    }\n  }\n}	0
32129828	32129759	Display a Sequence in a Console in C#	var flipValues = List<int>();\nfor (int i = 1; i <= 7; i++)\n{\n   int coin1 = RandomFlip(); //1 head 2 tails\n   int coin2 = RandomFlip();\n   if(coin1 == coin2)\n   {\n       flipValues.Add(coin1);\n   }\n}\n\nConsole.Write(string.Join(", ", flipValues.Select(f => f.ToString());	0
15014429	15014294	Json.Net parsing datetime value error	String MyJson = "{MyDate   : \"2013-02-21T22:23:57.118Z\" }";\nvar x = Newtonsoft.Json.Linq.JObject.Parse(MyJson);	0
26714213	26711828	How to get all merge fields of word document using open xml sdk	foreach (var header in doc.MainDocumentPart.HeaderParts)\n            foreach (var cc in header.RootElement.Descendants<FieldCode>())\n                //DO CODE\nforeach (var footer in doc.MainDocumentPart.FooterParts)\n           foreach (var cc in footer.RootElement.Descendants<FieldCode>())\n                //DO CODE	0
18193854	18193794	String as Indexer in C#	Dictionary<string, object> dict = new Dictionary<string, object>();\ndict["hello"] = "world";	0
7635423	7630654	C# reading from text file (which has different data types) to get sum of numerical values	using System;\nusing System.IO;\nusing System.Linq;\n\nclass Sample {\n    static void Main(){\n        string[] data = File.ReadAllLines("data.txt");\n        double sum = data.Select( x => {double v ;Double.TryParse(x, out v);return v;}).Sum();\n        Console.WriteLine("sum:{0}", sum);\n    }\n}	0
26548206	26494350	Method of a ATL/COM object : calling it in VBA for excel versus calling it in c#	MyVARIANT_TESTLib.TheATLObject TheATLObj = new MyVARIANT_TESTLib.TheATLObject();\ndouble TheDouble = 2.0;\nobject[,] TheMatrix = { { -3.0, 3.0, 2.0, 1.0 } };\nobject thevariant = new object();\nthevariant = TheMatrix ;\nTheATLObj.MULT(TheDouble, ref thevariant); // ref is crucial here	0
4202320	4202277	How can I apply a CSS class to HtmlTableCell?	myTableCell.Attributes.Add("class", "whatever");	0
2154033	2152934	Factory pattern with external dependency	class Foo {\n} \n\nclass Boo {\n  public Boo(Foo foo) {}\n}\n\nstatic class BooFactory {\n  public static Boo CreateBoo(Foo foo) {\n     return new Boo(foo);\n  }\n}	0
33030261	33027107	Image control ActualWidth correct only after second load - Image Cropper	this.UpdateLayout();	0
1251632	1251621	Get click event on a menuitem with subitems (C#)	MenuItem.Click	0
22496426	22473528	Find bounding box for contours	Image<Gray, Byte> canny = new Image<Gray, byte>(grayImage.Size);\n     using (MemStorage storage = new MemStorage())\n     for (Contour<Point> contours =grayImage.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_TREE, storage); contours != null; contours = contours.HNext)\n     {\n         //Contour<Point> currentContour = contours.ApproxPoly(contours.Perimeter * 0.05, storage);\n         CvInvoke.cvDrawContours(canny, contours, new MCvScalar(255), new MCvScalar(255), -1, 1, Emgu.CV.CvEnum.LINE_TYPE.EIGHT_CONNECTED, new Point(0, 0));\n     }\nusing (MemStorage store = new MemStorage())\n         for (Contour<Point> contours1= grayImage.FindContours(Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE, Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_TREE, store); contours1 != null; contours1 = contours1.HNext)\n         {\n             Rectangle r = CvInvoke.cvBoundingRect(contours1, 1);\n             canny.Draw(r, new Gray(255), 1);\n         }	0
217207	217187	Storing C# data structure into a SQL database	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.Serialization;\nusing System.IO;\n\nnamespace SerializeThingy\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            List<string> myList = new List<string>();\n            myList.Add("One");\n            myList.Add("Two");\n            myList.Add("Three");\n            NetDataContractSerializer serializer = new NetDataContractSerializer();\n            MemoryStream stream = new MemoryStream();\n            serializer.Serialize(stream, myList);\n            stream.Position = 0;\n            Console.WriteLine(ASCIIEncoding.ASCII.GetString(stream.ToArray()));\n            List<string> myList2 = (List<string>)serializer.Deserialize(stream);\n            Console.WriteLine(myList2[0]);\n            Console.ReadKey();\n        }\n    }\n}	0
16293364	16288495	how can I save GridView rows and call them same after Postback?	protected void Page_Load(object sender, EventArgs e)\n        {\n            if (!Page.IsPostBack)\n            {\n             // Initially bind your grid view like\n                GridView1.DataSource = "DataSource";\n                GridView1.DataBind();\n            }\n        }	0
20367865	20367842	need string name, why showing integer Value?	SqlCommand cmd = new SqlCommand("SELECT gname FROM tblNewgroup WHERE gno=@gno", con);	0
28781811	28781658	How to clear textbox when all checkboxes are unchecked in DataGridView C#	bool shouldClearTextBox = true;\n  foreach (DataGridViewRow Row in data.Rows)\n  {\n    object cell = Row.Cells[5].EditedFormattedValue;\n    // If the particular checkbox isn't cleared, shouldClearTextBox is set to false\n    shouldClearTextBox &= !Convert.ToBoolean(cell);\n  }\n  if (shouldClearTextBox)\n    textBox1.Clear();	0
17696870	17696745	Using SelectSingleNode with XPath returns NULL	xmlns="http://schemas.microsoft.com/developer/msbuild/2003"	0
25967364	25967229	Display image in label	protected void Page_Load(object sender, EventArgs e)\n{\n       if (!Page.IsPostBack)\n{\n        string image;\n        Advertisement Ad= BusinessLogic.getAd(8);\n\n        image = Ad.getImage();\n\n ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('"+image+"');", true);\n// it will alert image path\n    lblImage.Text = "<img alt='' src='"+image+"' />"; \n}\n    }	0
12523858	12523384	Range Validator in Excel with custom message text	Validation.ErrorTitle	0
19248636	19248344	Run Stored Procedure with table data as parameter	DECLARE @uniqueId int\nDECLARE @TEMP TABLE (uniqueId int)\n-- Insert into the temporary table a list of the records to be updated\nINSERT INTO @TEMP (uniqueId) SELECT uniqueId FROM myTable\n\n-- Start looping through the records\nWHILE EXISTS (SELECT * FROM @TEMP)\nBEGIN\n-- Grab the first record out\nSELECT Top 1 @uniqueId = uniqueId FROM @TEMP\nPRINT 'Working on @uniqueId = ' + CAST(@uniqueId as varchar(100))\n-- Perform some update on the record\nEXEC proc_run @uniqueId\n-- Drop the record so we can move onto the next one\nDELETE FROM @TEMP WHERE uniqueId = @uniqueId\nEND	0
1067685	1067373	Is there a way to specify the application icon for a ClickOnce application manifest using Mage/MageUI?	mage -New Application -ToFile MyApplication.exe.manifest -Name "My Application" -Version 1.0.0.0 -FromDirectory bin -IconFile ApplicationIcon.ico	0
718159	718147	Writing custom indexer for generic dictionary with enumeration as its key	Dictionary<YourEnum, int> dic = new Dictionary<YourEnum, int>();\n\ndic.ElementAt(index);	0
13099702	13099663	Not printing duplicate values using view in entity model	the correct result should be:\n\nA, 1\nA, 2\nB, 4\nB, 6\nB, 7\nC, 5\n\n\nThe actual result in code with Entity Framework would become:\n\n\nA, 1\nA, 1\nB, 4\nB, 4\nB, 4\nC, 5	0
21019094	21019002	Windows phone getting nearby latitude and longitude within 6 Kilometer based on my lat and long	double distance = myLocation.GetDistanceTo(yourLocation); // metres	0
29615672	29590369	How to clear MemoryTarget Logs in NLog?	MemoryTarget.Logs.Clear();	0
10729091	10728059	Can I save changed information in datagridview at runtime?	dataGridView1.Rows.RemoveAt(2);\nds.Tables["[Sheet1$]"].Rows[2].Delete();	0
30591186	30591114	Cancel some keyboard events on a control	public void Test()\n    {\n        DataGridView view = new DataGridView();\n\n        view.KeyDown += view_KeyDown;\n    }\n\n    void view_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.KeyCode == Keys.Enter /* && some other conditions */)\n        {\n            //Do some custom logic\n            e.Handled = true; //Cencel event. Avoid any other processing. Like the button was never pressed.\n        }\n    }	0
2588032	2587969	More efficient method for grabbing all child units	DECLARE @Table TABLE(\n        ID INT,\n        Val VARCHAR(10),\n        ParentID INT\n)\n\nINSERT INTO @Table SELECT 1, 'A', NULL\nINSERT INTO @Table SELECT 2, 'B', NULL\nINSERT INTO @Table SELECT 3, 'C', 1\nINSERT INTO @Table SELECT 4, 'D', 1\nINSERT INTO @Table SELECT 5, 'E', 4\nINSERT INTO @Table SELECT 5, 'F', 2\n\n;WITh Parents AS (\n    SELECT  *,\n            CAST(Val + '/'  AS VARCHAR(100))PathVal\n    FROm    @Table\n    WHERE   ParentID IS NULL\n    UNION ALL\n    SELECT  t.*,\n            CAST(p.PathVal + t.Val + '/' AS VARCHAR(100))\n    FROM    @Table t INNER JOIN \n            Parents p ON t.ParentID = p.ID\n)\nSELECT  *\nFROM    Parents	0
9465349	9465334	how to find the number of bytes in a file?	FileStream.Length	0
10804879	10804130	how to access all of the contents of a DICOM sequence using clearcanvas	void Dump(DicomAttributeCollection collection, string prefix, StringBuilder sb)\n    {     \n        foreach (DicomAttribute attribute in collection)\n        {\n            var attribSQ = attribute as DicomAttributeSQ;\n            if (attribSQ != null)\n            {                    \n                for (int i=0; i< attribSQ.Count; i++) \n                {\n                    sb.AppendLine(prefix + "SQ Item: " + attribSQ.ToString());\n\n                    DicomSequenceItem sqItem = attribSQ[i];\n                    Dump(sqItem, prefix + "\t", sb);\n                }\n            }\n            else\n            {\n                sb.AppendLine(prefix + attribute.ToString());\n            }\n        }\n    }	0
1083693	1083637	Invoking the click method of a button programmatically	PerformClick()	0
16126121	16121088	CrmEntityDataSource To CodeBehind Datareader	IEnumerator e = dataSource.GetEnumerator();\nwhile (e.MoveNext())\n{\n    object dataobject = e.Current;\n}	0
10317801	10169872	How to build a hierarchical tree using EF and LINQ	ICollection<object> treeList = <dbcontent>.<entity>.All().ToList();\ntreeList = treeList.Where(o => o.ParentId == 0).ToList();	0
12841480	12841438	Remove enclosing brackets from a string in c#	if (s.Length > 2) {\n    s = s.Substring(1, s.Length-2);\n}	0
26991366	26970104	c# MS chart get scrollbar value	private void chart1_AxisViewChanged(object sender, ViewEventArgs e)\n    {\n        if (!allowReadData)\n            allowReadData = true;\n    }\n\nprivate void timer4_Tick(object sender, EventArgs e)\n    {\n        if (allowReadData && MouseButtons != MouseButtons.Left)\n        {\n            allowReadData = false;\n            double xMin = chart1.ChartAreas[0].AxisX.ScaleView.ViewMinimum;\n            double xMax = chart1.ChartAreas[0].AxisX.ScaleView.ViewMaximum;\n            MessageBox.Show("Minimum: " + xMin+"\nMaximum: "+xMax);\n        }\n    }	0
26383371	26382816	Group By from DataTable using linq	var query = \n    data.GroupBy(d => d.ID)\n        .OrderBy(g => g.Key)\n        .SelectMany(g => (new[] {new {\n                                      g.First().ID, \n                                      g.First().Name, \n                                      g.First().Price}})\n                         .Concat(g.Skip(1).Select(i => new {\n                                                            ID = (string)null, \n                                                            i.Name, \n                                                            i.Price})));	0
26419517	20374455	A failing minimal example of executing JS in Win 8.1 Chakra with C#	[DllImport("jscript9.dll", CharSet = CharSet.Unicode)]	0
10957895	10957854	How to generate random color?	// Store these as static variables; they will never be changing\nString[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));\nint numColors = colorNames.Length;\n\n// ...\n\nRandom rand = new Random(); // No need to create a new one for each iteration.\nstring[] x = new string[] { "", "", "" };\nwhile(true) // This should probably be based on some condition, rather than 'true'\n{\n    // Get random ConsoleColor string\n    string colorName = colorNames[rand.Next(numColors)];\n    // Get ConsoleColor from string name\n    ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);\n\n    // Assuming you want to set the Foreground here, not the Background\n    Console.ForegroundColor = color;\n\n    Console.WriteLine((x[rand.Next(x.Length)]));\n    Thread.Sleep(100);\n}	0
3214689	3214351	How to dock a windows form in C#?	this.DesktopLocation = new Point((Screen.PrimaryScreen.Bounds.Width / 2 - 420), 0);	0
29549038	29548356	Populating a treeview with files in ASP.NET C#	private void PopulateTree()\n{\n    var rootFolder = new DirectoryInfo(@"C:\inetpub\wwwroot\yourwebproject");\n    var root = AddNodeAndDescendents(rootFolder);\n    TreeView1.Nodes.Add(root);\n}\n\nprivate TreeNode AddNodeAndDescendents(DirectoryInfo folder)\n{        \n    var node = new TreeNode(folder.Name, folder.Name);\n\n    var subFolders = folder.GetDirectories();\n\n    foreach (DirectoryInfo subFolder in subFolders)\n    {\n        var child = AddNodeAndDescendents(subFolder);\n        node.ChildNodes.Add(child);\n    }\n\n    foreach (FileInfo file in folder.GetFiles("*.bch"))\n    {\n        var tn = new TreeNode(file.Name, file.FullName);\n        node.ChildNodes.Add(tn);\n    }\n    return node;\n}	0
8462952	8462844	how to catch an unhandled exception in windows phone 7 application?	// Code to execute on Unhandled Exceptions\nprivate void Application_UnhandledException(object sender,ApplicationUnhandledExceptionEventArgs e)\n{\n    if (e.ExceptionObject is QuitException)\n        return;\n\n    if (System.Diagnostics.Debugger.IsAttached)\n    {\n        // An unhandled exception has occurred; break into the debugger\n        System.Diagnostics.Debugger.Break();\n    }\n\n    //MessageBox.Show(e.ExceptionObject.ToString(), "Unexpected error", MessageBoxButton.OK);\n\n    var errorWin = new ErrorWindow(e.ExceptionObject, "An unexpected error has occurred. Please click Send to report the error details.")\n                       {Title = "Unexpected Error"};\n    errorWin.Show();\n    //((PhoneApplicationFrame) RootVisual).Source = new Uri("/Views/ErrorWindow.xaml", UriKind.Relative);\n\n    e.Handled = true;\n}\n\nprivate class QuitException : Exception { }\n\npublic static void Quit()\n{\n    throw new QuitException();\n}	0
34396936	34396609	Optimize EF query using Any instead of contains	var navFilters = db.NavFilters.Where(finalExpression);\n\nvar thereIsAny = (from x in navFilters\n                  join n in db.NavItemsFilters on x.ItemID equals n.ItemID \n                  where n.Promo != string.Empty && x.Attribute1 == e.Attribute && x.Link == link && x.SubLink == subLink\n                  ).Any();	0
25353140	25347004	Set media files Title and Album in Background Audio in Windows Phone 8.1 Store apps	systemmediatransportcontrol.DisplayUpdater.MusicProperties.Title = "My lovely track";\nsystemmediatransportcontrol.DisplayUpdater.MusicProperties.Artist = "An awesome artist";\nsystemmediatransportcontrol.DisplayUpdater.Update();	0
10224248	10223673	Displaying a local PDF file in WPF with WebBrowser-Control	webBrowser.Navigate("file:///" + url);	0
2832192	2832174	Class inheriting from several Interfaces having same method signature	class ABC: I1,I2, I3\n{\n    void I1.XYZ() { /* .... */ }\n    void I2.XYZ() { /* .... */ }\n    void I3.XYZ() { /* .... */ }\n}\n\nABC abc = new ABC();\n((I1) abc).XYZ(); // calls the I1 version\n((I2) abc).XYZ(); // calls the I2 version	0
16614291	16612871	C# EF5 Database first Data Annotations for removing non-numbers from a phone number field	phone == null ? string.Empty : new string((phone).Where(c => char.IsNumber(c)).ToArray());	0
3009245	3009168	String help! Process isn't starting, probably because the argument string is kind of messed up	Clipboard.SetText(executionstring);	0
23808008	23686158	JumpList in C# application (recent files)	private void ReportUsage()\n\n   {\n\n       XmlDocument myXml = new XmlDocument();\n\n       myXml.Load(historyXml);\n\n       string list = historyXml;\n\n       jumpList.ClearAllUserTasks();\n\n       foreach (XmlElement el in myXml.DocumentElement.ChildNodes)\n\n       {\n\n           string s = el.GetAttribute("url");\n\n           JumpListLink jll = new JumpListLink(Assembly.GetEntryAssembly().Location, s);\n\n           jll.IconReference = new IconReference(Path.Combine("C:\\Program Files\\ACS Digital Media\\TOC WPF Browser\\Icon1.ico"), 0);\n\n           jll.Arguments = el.GetAttribute("url");\n\n           jumpList.AddUserTasks(jll);\n\n       }\n\n       jumpList.Refresh();\n\n   }	0
17855031	17854879	Set default text in textBox on button click	this.textBox1.Text = textBox1.Text;\n this.textBox2.Text = textBox2.Text;\n this.textBox3.Text = textBox3.Text;\n this.textBox4.Text = textBox4.Text;	0
25801688	25801075	Timing control in C# Socket Programming	static void Main()\n{\n    // Create a timer with a one second interval.\n    aTimer = new System.Timers.Timer(1000);\n\n    // Hook up the Elapsed event for the timer. \n    aTimer.Elapsed += SendRequest;\n    aTimer.Enabled = true;\n}\n\nprivate static void SendRequest(Object source, ElapsedEventArgs e)\n{\n    // maybe end existing request if not completed?\n    // send next request\n}	0
12515175	12500530	Getting a Byte Array from the audio file saved by Media.RecordSoundAction	public String GetRealPathFromUri(Uri contentUri){\n        String[] proj = {MediaStore.Audio.AudioColumns.Data};\n        ICursor cursor = ManagedQuery(contentUri, proj, null, null, null);\n        int column_index = cursor.GetColumnIndex(MediaStore.Audio.AudioColumns.Data);\n        cursor.MoveToFirst();\n        return cursor.GetString(column_index);\n    }\n\nvar responseRealPath = GetRealPathFromUri(responseUri);\nvar getBytes = System.IO.File.ReadAllBytes(responseRealPath);\nvar responseBase = Convert.ToBase64String(getBytes);	0
25152009	25151851	Progress bar in wpf c#	public void ExtractFiles()\n{\n     var total = d.GetFiles("*.").count();\n     var progressChange =  100/total;\n\n    foreach (var file in d.GetFiles("*."))\n    {\n        if (!Directory.Exists(targetPath))\n            Directory.CreateDirectory(targetPath);\n\n        if (!File.Exists(targetPath + file.Name))\n        {\n            Directory.Move(file.FullName, targetPath + file.Name);\n        }\n        else\n        {\n            File.Delete(targetPath + file.Name);\n            Directory.Move(file.FullName, targetPath + file.Name);\n        }\n        pb.Value += progressChange;\n    }\n}	0
24408849	24408416	Alphabetical order does not compare from left to right?	string[] strings = { "-1", "1", "10", "-10", "a", "ba","-a" };      \nArray.Sort(strings,StringComparer.Ordinal );\nConsole.WriteLine(string.Join(",", strings));\n// prints: -1,-10,-a,1,10,a,ba	0
9998692	9998655	Group objects with matching properties into Lists	var groups = list.GroupBy(x => new { x.code1, x.code2 });\n\n// Example of iterating...\nforeach (var group in groups)\n{\n    Console.WriteLine("{0} / {1}:", group.Key.code1, group.Key.code2);\n    foreach (var item in group)\n    {\n        Console.WriteLine("  {0} ({1})", item.id, item.name);\n    }\n}	0
2311143	2299601	How can I Access ASP.Net Wizard Finish Button in Code?	Button b = (Button)wCheckout.FindControl("FinishNavigationTemplateContainerID").FindControl("FinishButton");	0
11837518	11837440	How to dynamically add any number of images to web form where the source string is in a database?	.aspx\n\n<asp:SqlDataSource id="SqlDataSource1"\n      runat="server"\n      ConnectionString="<%$ ConnectionStrings:MyConnString%>"\n      SelectCommand="SELECT * FROM Table">\n  </asp:SqlDataSource>\n\n<asp:ListView ID="lvImages" runat="server" DataSource="SqlDataSource1">\n   <ItemTemplate>\n       <asp:Image ID="imgListImage" runat="server" ImageUrl='<%# Eval("Folder") %>' />\n   </ItemTemplate>\n</asp:ListView>	0
27785496	27785284	Prepending information in a text file	var path = @"C:\Users\User\Desktop\New folder\DHStest.txt";\n\nvar lines = File.ReadAllLines(path);\nFile.WriteAllLines(path, lines.Select(x => x.PadLeft(31, '0')));	0
11151186	11150912	Bind and access checkbox value within a gridview	You can try this one...\n\nBind id to lable instead of to checkbox as below.\n\n<asp:TemplateField>     \n<ItemTemplate>       \n<asp:CheckBox ID="chkSelItem" runat="server" />     \n\n<asp:Label ID="lblSelectedItem" value=<%# Eval("Key.Id")) %> visible="False"/>\n</ItemTemplate> </asp:TemplateField>\n\n\n\nIn codebehind try this\n\nforeach (GridViewRow row in gridDepartments.Rows)         \n{             \n      CheckBox chkSelItem = (CheckBox)row.FindControl("chkSelItem");\n       Label lblSelectedItem= (Label)row.FindControl("lblSelectedItem");\n\n      if (chkSelItem.Checked) \n      {\n                 int departmentId = int.Parse(lblSelectedItem.Text); \n      }\n} \n\n\n\nHope this is what u want...	0
6594104	6137542	C# Lost Focus without using control event	foreach (Control uie in FindInLogicalTreeDown(this, typeof(TextBox))) AssignEvents(uie);\n\n    private static IEnumerable<DependencyObject> FindInLogicalTreeDown(DependencyObject obj, Type type)\n    {\n        if (obj != null)\n        {\n            if (obj.GetType() == type) { yield return obj; }\n            foreach (object child in LogicalTreeHelper.GetChildren(obj)) \n                if (typeof(DependencyObject).IsAssignableFrom(child.GetType()))\n                    foreach (var nobj in FindInLogicalTreeDown((DependencyObject)child, type)) yield return nobj;\n        }\n        yield break;\n    }\n\n    void AssignEvents(Control element)\n    {\n        element.GotMouseCapture += new MouseEventHandler(Component_GotFocus);\n    }\n\n    public Control LastFocus { get; set; }\n    public void Component_GotFocus(object sender, RoutedEventArgs e)\n    {\n        LastFocus = (Control)sender;\n        if (LastFocus.GetType() == typeof(TextBox)) { KeyboardVisible = true; }\n    }	0
15817573	15817220	C#: Create click event for DataGridView column heading	dataCapPlan.ColumnHeaderMouseClick +=new DataGridViewCellMouseEventHandler(dataCapPlan_ColumnHeaderMouseClick);	0
11716730	11691230	How to retrieve the CaretPosition from the WPF RichTextBox during GotFocus?	private void RichTextBox_GotFocus(object sender, RoutedEventArgs e)\n{\n    Dispatcher.BeginInvoke(new Action(UpdateTextBoxCaretPosition));\n}\n\nvoid UpdateTextBoxCaretPosition()\n{\n    var textRange = new TextRange(rtfBox.Document.ContentStart, rtfBox.CaretPosition);\n    plainTextBox.Focus();\n    plainTextBox.CaretIndex = textRange.Text.Length;\n}	0
9860451	9860396	On edit event how insert a value into the database in the same row as in the gridview?	protected void GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e)\n{   \n   GridViewRow row = ((GridView)sender).Rows[e.RowIndex];\n   DropDownList ddl =  (DropDownList)row.FindControl("DdlChoose");\n   bool yes = ddl.SelectedValue == "Yes";\n   SaveData(params); // pseudo-code \n}	0
27746780	27741659	Composing expression trees for composite DTO	private static readonly Expression<Func<DaoMailing, DaoTemplate, DaoSender, Mailing>> ToMailingFull =\n        (Expression<Func<DaoMailing, DaoTemplate, DaoSender, Mailing>>)Expression.Lambda(\n            Expression.MemberInit(\n                Expression.New(typeof(Mailing).GetConstructor(Type.EmptyTypes)),\n                (ToMailingShort.Body as MemberInitExpression).Bindings\n                    .Concat(new List<MemberBinding>{\n                        Expression.MemberBind(typeof(Mailing).GetProperty("Sender"), (ToSender.Body as MemberInitExpression).Bindings),\n                        Expression.MemberBind(typeof(Mailing).GetProperty("Template"), (ToTemplate.Body as MemberInitExpression).Bindings)\n                    })\n            ),\n            ToMailingShort.Parameters[0],\n            ToTemplate.Parameters[0],\n            ToSender.Parameters[0]\n        );	0
3204087	3203938	Arrange buttons in a grid with WPF	.Stretch	0
22976317	22969452	How can I stop a method's execution using PostSharp?	public class CacheThisMethod : OnMethodBoundaryAspect\n{\n        public override void OnEntry(MethodExecutionArgs args)\n        {\n           if (isCached( args.Method.name)\n               {\n                args.MethodExecutionTag =  getReturnValue(args.Method.name)\n                OnExit(args);\n               }\n           else\n               {\n                //continue\n               }\n        }\n        public override void OnExit(MethodExecutionArgs args)\n        {\n           //args.Method.ReturnValue = args.MethodExecutionTag;\n            args.ReturnValue = args.MethodExecutionTag;\n            args.FlowBehavior = FlowBehavior.Return;\n        }\n}	0
23490647	23490510	How to update foreign key using entitystate.modified?	db.Materials.Attach(material);\ndb.Entry(material).State = EntityState.Modified;\ndb.SaveChanges();	0
33581159	33580993	Add Pushpin to MapControl in UWP	// get position\nGeopoint myPoint = new Geopoint(new BasicGeoposition() { Latitude = 51, Longitude = 0 });\n//create POI\nMapIcon myPOI = new MapIcon { Location = myPoint, NormalizedAnchorPoint = new Point(0.5, 1.0), Title = "My position", ZIndex = 0 };\n// add to map and center it\nmyMap.MapElements.Add(myPOI);\nmyMap.Center = myPoint;\nmyMap.ZoomLevel = 10;	0
29496755	29496538	Retrieve multiple values from XML in C#	var answers = doc.SelectNodes("//x:fv", nsmgr);\n\nif (answers == null)\n    return;\n\nforeach (var item in answers)\n{\n     var result = ((XmlNode)item).InnerXml;\n}	0
11591200	11591023	Is there a setting that is preventing the unhandled exception dialog from displaying in apps that I compile?	[STAThread]\n    static void Main() {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);\n        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;\n        Application.Run(new Form1());\n    }\n\n    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {\n        // TODO: improve logging and reporting\n        MessageBox.Show(e.ExceptionObject.ToString());\n        Environment.Exit(-1);\n    }	0
21155779	21155220	CONVERT date format from mm-dd-yyyy to dd-mmm-yyyy in c#	String MyString = "12-30-2014"; // get value from text field\n        DateTime MyDateTime = new DateTime();\n        MyDateTime = DateTime.ParseExact(MyString, "MM-dd-yyyy",null);\n        String MyString_new = MyDateTime.ToString("dd-MM-yyyy"); //add MyString_new to    oracle.	0
1162291	1162262	How can I simulate a C++ union in C#?	[StructLayout(LayoutKind.Explicit)]\nstruct STRUCT\n{\n    [FieldOffset(0)]\n    public Int64 fieldTotal;\n\n    [FieldOffset(0)]\n    public Int32 fieldFirst;\n\n    [FieldOffset(4)]\n    public Int32 fieldSecond;\n}	0
1710125	1707531	Get max + min in one line with linq	public class TimetableWithMaxMin\n{\n    public Timetable Timetable { get; set; }\n    public DateTime Max { get; set; }\n    public DateTime Min { get; set; }\n}\n\npublic IQueryable<TimetableWithMaxMin> GetTimetables()\n{\n    return from t in _entities.Timetables\n           select new TimetableWithMaxMin\n           {\n               Timetable = t,\n               Max = _entities.Timetables.Max(t => t.StartTime),\n               Min = _entities.Timetables.Min(t => t.StartTime)\n           };\n}	0
10511728	10507939	 How can I get customErrors' defaultRedirect value from code?	CustomErrorsSection customErrorsSection = (CustomErrorsSection) ConfigurationManager.GetSection("system.web/customErrors");\n        string defaultRedirect = customErrorsSection.DefaultRedirect;	0
30963907	30919140	unable to change a label text from NetworkAddressChangedEventHandler c#	this.Invoke((MethodInvoker)delegate\n        {\n                 //your code here\n        });	0
28354067	28351979	Executing F# Source from C#	using FSharp.Compiler.CodeDom;\nusing System.CodeDom;\nvar codeString = "let add x y = x + y";\nvar provider = new FSharp.Compiler.CodeDom.FSharpCodeProvider();\nEnvironment.CurrentDirectory.Dump("exe is going here"); // diagnostic helper\nvar targetFile = "FSFoo.exe";\nprovider .CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters(){ OutputAssembly= targetFile, GenerateExecutable=true }, new []{codeString}).Dump(); // .Dump is just for diagnostics, remove if you aren't running this in linqpad\nif(!System.IO.File.Exists(targetFile)){\n    throw new FileNotFoundException("Could not find compiled exe",targetFile);\n}\n\nSystem.IO.Directory.GetFiles(Environment.CurrentDirectory,"FSFoo.exe").Dump();// .Dump is just for diagnostics, remove if you aren't running this in linqpad	0
23898114	23898055	Getting data from each row in a SQL Server CE database	cmd.ExecuteNonQuery();	0
32636959	32635732	How to initialize an array of object using a constructor with arguments?	public class EquationGenerator \n        {\n            EquationTerm[] LeftTerms;\n            EquationTerm[] RightTerms;\n\n            void Start()\n            {\n                //Initialize both side with a random number of terms\n                LeftTerms = InitializeArray(Random.Range(1, 6));\n                RightTerms = InitializeArray(Random.Range(1, 6));\n            }\n\n            EquationTerm[] InitializeArray(int length)\n            {\n\n                EquationTerm[] array = new EquationTerm[length];\n                array[0] = new EquationTerm(Random.Range(1, 10));\n                for (int i = 1; i < length; ++i)\n                {\n                    array[i] = new EquationTerm(Random.Range(1, 10), Random.Range(1, 5), true);\n                }\n\n                return array;\n            }\n        }	0
12239242	12239214	Duplicate a Random Number function from JS to C#	Random random = new Random();\n\n long r = (long)(random.NextDouble() * 10000000000000);	0
11948370	11885054	How to get table name for a simple bag?	var metaData = sf.GetClassMetadata("containingType");\nvar c = (CollectionType)metaData.PropertyTypes[Array.IndexOf(metaData.PropertyNames, "collectionPropertyName")];\nvar tablename = c.GetAssociatedJoinable((ISessionFactoryImplementor)sf).TableName;	0
22246242	22224420	Xamarin Android deserialize local json file	string response;\n\nStreamReader strm = new StreamReader (Assets.Open ("form.json"));\nresponse = strm.ReadToEnd ();\n\nList<Vraag> vragen = JsonConvert.DeserializeObject<List<Vraag>>(response);\n\nforeach(Vraag vraag in vragen)\n{\n    if (vraag.type == "textField") {\n        var editText  = new EditText (this);\n        editText.Text = "Dit is vraag: " + vraag.id + ".";\n        editText.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,ViewGroup.LayoutParams.WrapContent);\n        layout.AddView (editText);\n    }\n}	0
4437896	4162158	ASP.NET Agility Pack | How to parse a web page. that is taking post parameters?	BrowserSession b = new BrowserSession();\nb.Get("http://www.skyline-eng.com/");\nb.FormElements["navigationTypeID"] = rblCategory.SelectedItem.Value;\nb.FormElements["navigationSeriesID"] = boxItem.Value;\nHtmlDocument docSkyLine = b.Post("http://www.skyline-eng.com/");	0
29122610	29122534	How to get class property name with spaces?	foreach (var fieldName in trimedNames)\n{\n    var fieldNameWithSpaces = Regex.Replace(fieldName, "(\\B[A-Z])", " $1");\n\n    // you can use fieldNameWithSpaces here...\n}	0
21724621	21724448	How to manage Label in c#	if ((string.IsNullOrEmpty(TbTcNo.Text) || string.IsNullOrWhiteSpace(TbTcNo.Text)))\n        {\n            warningcase = 1;\n            TextLabelManagement(warningcase);                              \n        }\n        if ((string.IsNullOrEmpty(TbId.Text) || string.IsNullOrWhiteSpace(TbId.Text)))\n        {\n            warningcase = 2;\n            TextLabelManagement(warningcase);               \n        }\n         if ((string.IsNullOrEmpty(TbName.Text) || string.IsNullOrWhiteSpace(TbName.Text)))\n        {\n            warningcase = 3;\n            TextLabelManagement(warningcase);      \n        }	0
723219	723211	Quick way to create a list of values in C#?	var list = new List<string> { "test1", "test2", "test3" };	0
4616709	4616685	how to generate a random string, and specify the length you want, or better generate unique string on specification you want	private static void Main()\n{\n    const string AllowedChars =\n        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";\n    Random rng = new Random();\n\n    foreach (var randomString in RandomStrings(AllowedChars, 1, 16, 25, rng))\n    {\n        Console.WriteLine(randomString);\n    }\n\n    Console.ReadLine();\n}\n\nprivate static IEnumerable<string> RandomStrings(\n    string allowedChars,\n    int minLength,\n    int maxLength,\n    int count,\n    Random rng)\n{\n    char[] chars = new char[maxLength];\n    int setLength = allowedChars.Length;\n\n    while (count-- > 0)\n    {\n        int length = rng.Next(minLength, maxLength + 1);\n\n        for (int i = 0; i < length; ++i)\n        {\n            chars[i] = allowedChars[rng.Next(setLength)];\n        }\n\n        yield return new string(chars, 0, length);\n    }\n}	0
16627114	16626700	C# How to make Stack function like List?	private Stack<Gem> gems = new Stack<Gem>();\nprivate Stack<Enemy> enemies = new Stack<Enemy>();\n\n/// <summary>\n/// Animates each gem and checks to allows the player to collect them.\n/// </summary>\nprivate void UpdateGems(GameTime gameTime)\n{\n    var newGems = new Stack<Gem>(this.gems.Count);\n\n    while (this.gems.Count > 0)    \n    {\n        var gem = this.gems.Pop();\n        gem.Update(gameTime);\n\n        if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))\n        {\n            OnGemCollected(gem, Player);\n        }\n        else\n        {\n            newGems.Push(gem);\n        }\n    }\n\n    this.gems = newGems;\n}	0
643806	643774	How to fix this SocketException	socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);	0
14042772	14042685	newbie with dapper and c#	using ...;\nusing Dapper;\nusing ...;	0
29468771	29467348	How to set mouse position without importing user32.dll in wpf	System.Windows.Forms.Cursor.Position = new System.Drawing.Point(0, 0);	0
22471807	22471743	Send Email without attachments	if(File.Exists("screenshot.png"))\n{\n   System.Net.Mail.Attachment attachment;\n   attachment = new System.Net.Mail.Attachment("screenshot.png");\n   msg.Attachments.Add(attachment);\n}	0
23259932	23259913	Format String for SQL Entry	var date = DateTime.Parse(theString);\nSqlCommand cmd = new SqlCommand("insert into xxx (theDateField) values(@param1)", con);\ncmd.Parameters.AddWithValue("param1", date);\n\n//execute your query and do what even you want.	0
19650874	19583049	Single dll for Windows 8 and Windows 8.1	Type tp = Type.GetType("Windows.System.UserProfile.AdvertisingManager, Windows.System, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime");\n        if (tp != null)\n        {\n            PropertyInfo properties = tp.GetRuntimeProperty("AdvertisingId");\n            if (properties != null)\n            {\n                string deviceId = (string)properties.GetValue(null);\n            }\n        }	0
2116555	2116511	SQLite injection with list of strings	using (var conn = new SQLiteconnection(connectionString))\nusing (var command = conn.CreateCommand())\n{\n    conn.Open();\n    command.CommandText = "select name from persons where id = @id";\n    command.Parameters.AddWithValue("@id", 5);\n    using (var reader = command.ExecuteReader())\n    {\n        while (reader.Read())\n        {\n\n        }\n    }\n}	0
13274490	13247404	Get Value of a colum from GridView Windows Mobile 6.0	int rowIndex = dgridShipmentItemTypes.CurrentCell.RowNumber;\nint nIndex = 0; // Whatever your column index is.\nobject obj = dgridShipmentItemTypes[rowIndex, nIndex];\nif ((obj != null) && (obj != DBNull.Value)) {\n  // do something with it\n}	0
14333683	14333582	Merging two tables using datasets and display in gridview	setOleDb.Tables[0].PrimaryKey = setOleDb.Tables[0].Columns["CODE"];	0
10553349	10553323	checkedListBox alllowing only one item to be checked	private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {\n      for (int ix = 0; ix < checkedListBox1.Items.Count; ++ix)\n        if (ix != e.Index) checkedListBox1.SetItemChecked(ix, false);\n    }	0
4330174	4329652	background color not changing in circular application	myComponent.Invalidate();	0
5195807	5195692	Is there a way to delete a character that has just been written using Console.WriteLine?	Console.Write("Abc");\n    Console.Write("\b");\n    Console.Write("Def");	0
22963545	22963267	how to pass default image from images folder if no if no items found in asp.net 3.5	if (item != null)\n            {\n                imageData = item.Image.ToArray();\n                context.Response.ContentType = "image/jpeg";\n                context.Response.BinaryWrite(imageData);\n            }\n            else\n            {\n                //get images from images named folder and parse it to byte array\n             imageData =System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Images/DefaultImage.jpg"));\n\n            context.Response.ContentType = "image/jpeg";\n            context.Response.BinaryWrite(imageData);\n            }	0
22987229	22975448	Get IdentityDbContext during ValidateClientAuthentication in my custom OAuthAuthorizationServerProvider	ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();\nApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();	0
1592129	179254	Reloading configuration without restarting application using ConfigurationManager.RefreshSection	ConfigurationManager.RefreshSection("appSettings");	0
19654200	19640583	DevExpress - Formating the string of the expression in Style Format Condition	// just sample data\ngridControl1.DataSource = new List<DataObj> { \n    new DataObj() { RValue = 0.2 }, \n    new DataObj() { RValue = 0.21 },  // !!! Orange\n    new DataObj() { RValue = 0.201 }, // !!! Orange\n    new DataObj() { RValue = 0.2001 },\n    new DataObj() { RValue = 0.20001 },  \n};\ngridView1.PopulateColumns();\n\n//...\nvar condExpression = new StyleFormatCondition(FormatConditionEnum.Expression);\ncondExpression.Column = gridView1.Columns["RValue"];\ncondExpression.Appearance.BackColor = Color.OrangeRed;\ncondExpression.Appearance.Options.UseBackColor = true;\ncondExpression.Expression = String.Format("Abs([RValue] - {0} - {1}) > {2}", 0.1, 0.1, EPSILON);\ngridView1.FormatConditions.Add(condExpression);\n\n//...\nclass DataObj {\n    public double RValue { get; set; }\n}	0
9987380	9987327	date comparison in where condition in c# with oledb database	string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between #" + dt_start + "# and #" + dt_end + "#";	0
13902141	13902069	CheckBox inside a listbox in windows form	private void Form1_Load(object sender, EventArgs e)\n    {\n        var items = checkedListBox1.Items;\n        items.Add("Perls");\n        items.Add("Checked", true);\n    }	0
18718430	18718298	How to remove object with specific name from ArrayList	arrayList = arrayList.Where(x=>x.Name != "button1").ToList();	0
17522944	17522062	How can I get Session.SessionID from my MVC-Framework in unit tests?	var contextMock = new Mock<ControllerContext>();\nvar mockHttpContext = new Mock<HttpContextBase>();\nvar session = new Mock<HttpSessionStateBase>();\nmockHttpContext.Setup(h => h.Session).Returns(session.Object);\ncontextMock.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);	0
17965298	17941668	Counting strings row wise in Crystal report	EvaluateAfter({@a});\nEvaluateAfter({@a 2});\nEvaluateAfter({@a 3});\n\n\n    Local StringVar a;\n    Local StringVar a1;\n    Local StringVar a2;\n    Local NumberVar i;\n    Local NumberVar j;\n    Local StringVar array x;\n    a:={@a};\n    a1:={@a 2};\n    a2:={@a 3};\n    x:=[a,a1,a2];\n    j:=0;\n    for i:=1 to Count(x) do\n    (\n    if x[i]="A"\n    Then j:=j+1;\n    );\n    j	0
17031865	17030821	Replace a type in an expression tree	// Example use: return entities.Entities.Where(ExpressionTransformer<IEntity,Entity>.Transform(filter));\ninternal static class ExpressionTransformer<TFrom, TTo> where TTo : TFrom\n{\n    public class Visitor : ExpressionVisitor\n    {\n        private ParameterExpression _parameter;\n\n        public Visitor(ParameterExpression parameter)\n        {\n            _parameter = parameter;\n        }\n\n        protected override Expression VisitParameter(ParameterExpression node)\n        {\n            return _parameter;\n        }\n    }\n\n    public static Expression<Func<TTo, bool>> Tranform(Expression<Func<TFrom, bool>> expression)\n    {\n        ParameterExpression parameter = Expression.Parameter(typeof(TTo));\n        Expression body = new Visitor(parameter).Visit(expression.Body);\n        return Expression.Lambda<Func<TTo, bool>>(body, parameter);\n    }\n}	0
21432675	21432243	Use for loop when writing a XML file with LINQ	XDocument document = new XDocument(\n   new XDeclaration("1.0", "utf-8", "yes"),\n   new XElement("alegeri",\n       Enumerable.Range(1,2).Select(i => \n         new XElement("tur",\n           new XElement("nrtur", i),\n             candTur1.Select((s, index) =>                \n                new XElement("candidat",\n                new XElement("nume", candTur1[index]),\n                new XElement("voturi",votTur1[index] ),\n                new XElement("procent",((votTur1[index] * 100) / votanti)) ))))));	0
18826744	18825609	Post data to server in windows store app	using System.Net.Http;\n\nprotected async override void OnNavigatedTo(NavigationEventArgs e)\n{\n    var data = new List<KeyValuePair<string, string>>\n    {\n        new KeyValuePair<string, string>("key_1", "value_1"),\n        new KeyValuePair<string, string>("key_2", "value_1")\n    };\n\n    await PostKeyValueData(data);\n}\n\nprivate async Task PostKeyValueData(List<KeyValuePair<string, string>> values)\n{\n    var httpClient = new HttpClient();\n    var response = await httpClient.PostAsync("http://50.16.234.220/helloapp/api/public/", new FormUrlEncodedContent(values));\n    var responseString = await response.Content.ReadAsStringAsync();\n}	0
24125020	24083576	Switch Languages/Words/Terms in a single application deployed to multiple sites	Text.xml becomes\nText.Debug.xml and\nText.Release.xml	0
23579425	23520521	Problems binding a DataGrid with an Observable Collection that receive null parameters in WPF	if(MyProperty == null)\n{ \n    MyProperty = string.Empty;\n]	0
8443803	8442875	EF CF m-to-n relationship via data annotations	[Table("Foo")]\npublic class Foo {\n    [Key]\n    public Int32 FooId { get; set; }\n    public String FooName { get; set; }\n    [InverseAttribute("Foos")]\n    public ICollection<Bar> Bars { get; set; }\n}\n\n[Table("Bar")]\npublic class Bar { \n    [Key]\n    public Int32 BarId { get; set; }\n    public String BarName { get; set; }\n    [InverseAttribute("Bars")]\n    public ICollection<Foo> Foos { get; set; }\n}	0
23815939	23815705	Getting the MAX of several SUMs with LINQ	IEnumerable<UserActivity> UserActivities = LoadUserActivities();\nint maxTotalPointsActivityId = \n    UserActivities\n    .GroupBy(ua => ua.ActivityId)\n    .OrderByDescending(uaGp => uaGp.Sum(ua => ua.Points))\n    .First()\n    .Key;	0
9412925	9412705	Pass arguments to a server side CustomValidator	CustomValidator cvalid = (CustomValidator)source;\nGridViewRow gv = cvalid.NamingContainer;\nint index = gv.RowIndex;	0
18321912	18321561	Is it possible to make a list of generics that return a specific data type?	var l = new List<Union3<string, DateTime, int>>  {\n            new Union3<string, DateTime, int>(DateTime.Now),\n            new Union3<string, DateTime, int>(42),\n            new Union3<string, DateTime, int>("test"),\n            new Union3<string, DateTime, int>("one more test")\n    };\n\n        foreach (Union3<string, DateTime, int> union in l)\n        {\n            string value = union.Match(\n                str => str,\n                dt => dt.ToString("yyyy-MM-dd"),\n                i => i.ToString());\n\n            Console.WriteLine("Matched union with value '{0}'", value);\n        }	0
7513331	7513260	Generating a non-guid unique key outside of a database	public static class MD5Gen\n    {\n        static MD5 hash = MD5.Create();\n        public static string Encode(string toEncode)\n        { \n            return Convert.ToBase64String(\n            hash.ComputeHash(Encoding.UTF8.GetBytes(toEncode)));\n        }\n    }	0
30293706	30292418	How to use bundle transformer to Minify CSS or JS	BundleTable.EnableOptimizations = true;	0
20577851	20328783	How to create Windows Azure Media Services Access Policy without Duration or with a longer validity?	_mediaContext.AccessPolicies.CreateAsync("TimeSpan.MaxValue readonly policy", TimeSpan.MaxValue, AccessPermissions.Read);	0
13052331	13052251	Sort array of string 00:00:00	string[] array = new string[] { "00:03:00", "00:00:00" };\nArray.Sort(array);	0
8673353	8673259	How to filter LINQ to SQL result by xref table property	public static IQueryable<TblProjCd> ByEmployeeId(this IQueryable<TblProjCd> qry, int employeeId)\n{\n    //Return the filtered IQueryable object\n    return from q in qry\n           where q.TblEmployee.Any(p => p.EmployeeId == employeeId)\n           select q;\n}	0
20000303	19543032	How to force ChangeTracker to reset current object state to Unchanged without abandoning changes	if(context.Entry(o).State == EntityState.Unchanged)\n                {\n                    context.Entry(o).State = EntityState.Modified;\n                }	0
1491558	1491550	Converting from string bits to byte or hex	string binaryText = "1101000";\nint value1 = Convert.ToInt32(binaryText, 2) // 104\nbyte value2 = Convert.ToByte(binaryText, 2); // 104	0
33493031	33492785	inserting table values from one table to another	protected void Button2_Click1(object sender, EventArgs e)\n{\nString str1 = "insert into table2(Code,Qty,UPrice,Total,Num) select Code,Qty,UPrice,Total,'"+TextBox1.Text+"' from table1 ;";    \nSqlCommand cmd = new SqlCommand(str1, con);\ncon.Open();\nSqlDataAdapter da1 = new SqlDataAdapter();\nda1.SelectCommand = cmd;\nDataSet ds1 = new DataSet();\nda1.Fill(ds1);\nGridView1.DataSource = ds1;\ncon.Close();\n}	0
6511274	6511155	how to get current month Weekends list of calender control in asp.net using c#	var startDate = DateTime.Now;\nvar first = new DateTime(startDate.Year, startDate.Month, 1);\nList<DateTime> weekends = new List<DateTime>();\nfor (int i = 0; i <= DateTime.DaysInMonth(startDate.Year, startDate.Month); i++)\n{\n    var nextDay = first.AddDays(i);\n    if (nextDay.DayOfWeek == DayOfWeek.Saturday || nextDay.DayOfWeek == DayOfWeek.Sunday)\n    {\n        weekends.Add(nextDay);\n    }\n}	0
2961778	2961534	How to prevent Windows Forms designer from generating default value assignments for properties?	[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n    public Image Aardvark { get; set; }	0
2608809	1800415	CommandBinding Ctrl + Spacebar	public Window1()\n    {\n        InitializeComponent();\n        ApplicationCommands.Find.InputGestures.Add(new KeyGesture(Key.Space, ModifierKeys.Control));\n        CommandBinding commandBinding = new CommandBinding(ApplicationCommands.Find, myCommandHandler);\n        this.CommandBindings.Add(commandBinding);\n    }\n\n    private void myCommandHandler(object sender, ExecutedRoutedEventArgs args)\n    {\n        MessageBox.Show("Command invoked!");\n    }	0
13424468	13415777	Disable Right-Click for ContextMenuStrip in DataGridView	private MouseButtons e_Button = new MouseButtons();\n    private void dgv1_MouseDown(object sender, MouseEventArgs e)\n    {\n        e_Button = e.Button;\n    }\n\n    private void cms1_Opening(object sender, CancelEventArgs e)\n    {\n        if (e_Button == System.Windows.Forms.MouseButtons.Right)\n            e.Cancel = true;\n    }	0
604042	44980	How can I programmatically determine if my workstation is locked?	Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);\n\n    void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)\n    {\n        if (e.Reason == SessionSwitchReason.SessionLock)\n        { \n            //I left my desk\n        }\n        else if (e.Reason == SessionSwitchReason.SessionUnlock)\n        { \n            //I returned to my desk\n        }\n    }	0
2273148	2273101	NULLs in string array	string[] items = new string[] { "", "-2", "3", null, "-4", "+5", null, "66" };\n\nitems = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();	0
9731881	9731846	Extract Values from DateTime	int hrs24 = dt.Hour;\nint hrs12 = hrs24 > 12 ? hrs24 - 12 : (hrs24 == 0 ? 12 : hrs24);	0
868283	867656	Fading out a wpf window on close	private bool closeStoryBoardCompleted = false;\n\nprivate void Window_Closing(object sender, CancelEventArgs e)\n{\n    if (!closeStoryBoardCompleted)\n    {\n        closeStoryBoard.Begin();\n        e.Cancel = true;\n    }\n}\n\nprivate void closeStoryBoard_Completed(object sender, EventArgs e)\n{\n    closeStoryBoardCompleted = true;\n    this.Close();\n}	0
11247565	11247528	Getting request type from ActionResult	context.HttpContext.Request.HttpMethod	0
6714192	6713835	How do I return a Powershell DataTable object from C# app code?	System.Management.Automation.PowerShell.Create().AddScript(...).Invoke<DataTable>	0
8866255	8866169	C# get notified when another process makes changes to a textfile	string fileToWatch = @"C:\MyFile.txt";\nfileSystemWatcher = new FileSystemWatcher(fileToWatch);\n\nvoid fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)\n{\n    Debug.WriteLine(e.Name +  " has changed");\n}	0
11849973	11849930	If statements for Checkboxes	if (checkbox1.Checked && !checkbox2.Checked)\n{\n\n}\nelse if (!checkbox1.Checked && checkbox2.Checked)\n{\n\n}	0
7900531	7900482	Similar to alt tag in WinForms controls	ToolTip tooltip = new ToolTip();\ntooltip.SetToolTip(checkBox, "A tooltip on my checkBox");\ntooltip.SetToolTip(button, "A tooltip on my button");	0
29206678	29206092	Populate combobox with content from comma separated textfile - based on selection of another combobox	foreach (var line in lineOfContents)\n  {\n        string[] tokens = line.Split(',');\n        if (tokens[0] == combobox1_SelectedValue)\n        {\n            comboBox2.Items.Add(tokens[1]);\n        }   \n   }	0
24056533	24018457	Get currentPositionTimecode from a video file .wmv using WMPLib	using WMPLib;\n\npublic partial class MainWindow : Window\n{\n    private string _Timecode;\n     WindowsMediaPlayerClass _Wmp =  new WindowsMediaPlayerClass{volume = 0};\n    public MainWindow()\n    {\n        InitializeComponent();\n        _Wmp.MediaChange += WmpOnMediaChange;\n    }\n\n    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)\n    {\n        MessageBox.Show(_Timecode);\n    }\n\n    private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)\n    {\n        const string filename = @"C:\Users\Public\Videos\Toto.wmv";\n        _Wmp.URL = filename;\n    }\n\n    private void WmpOnMediaChange(object item)\n    {\n        _Wmp.MediaChange -= WmpOnMediaChange;\n        _Wmp.controls.pause();\n        _Wmp.controls.currentPosition = 0 ;\n        _Timecode = ((IWMPControls3) _Wmp.controls).currentPositionTimecode;\n        _Wmp.close();\n        _Wmp = null;\n    }\n}	0
3708707	3708663	My C# app is locking a file, how I can find where it does it?	using(var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))\n{\n//Your code goes here.\n}	0
13126419	13126308	How can I decouple the EF POCO from the generic IRepository in this pattern?	EmployeeDTO FindEmployeeByName(string name)\n{\n    return Mapper.Map<EmployeeDTO>(dbSet.Where(o=>o.name.Contains(name)).FirstOfDefault());\n}	0
6570464	6570187	Create one image from various image files	using (Graphics grfx = Graphics.FromImage(image))\n{\ngrfx.DrawImage(newImage, x, y)\n}	0
25738947	25737412	How to add definiton for xsi namespace with saxon .NET api	Processor xmlProcessor = new Processor();\n    DocumentBuilder builder = xmlProcessor.NewDocumentBuilder();\n    XdmNode xdmNode = builder.Build(xmlDocument);\n    XPathCompiler compiler = xmlProcessor.NewXPathCompiler();\n    compiler.DeclareNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");	0
9820272	9820165	Convert hexadecimal string to its numerical values in C#	string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";\nstring[] hexValuesSplit = hexValues.Split(' ');\nforeach (String hex in hexValuesSplit)\n{\n    // Convert the number expressed in base-16 to an integer.\n    int value = Convert.ToInt32(hex, 16);\n    // Get the character corresponding to the integral value.\n    string stringValue = Char.ConvertFromUtf32(value);\n    char charValue = (char)value;\n    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",\n                    hex, value, stringValue, charValue);\n}	0
27318960	27317899	Getting HRESULT E_FAIL error if copy a big file in Windows Runtime	var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;\nvar file = await folder.GetFileAsync("largeFile.txt");\n\nStorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;\n\n// Exception\nif (file != null)\n{\n    StorageFile copiedFile = await file.CopyAsync(tempFolder, "copied.txt", NameCollisionOption.GenerateUniqueName);\n}\n\n\n// Setting the internal buffer to 1024 \n// Be aware- from MSDN: However, this buffer is allocated on the large object heap \n// and could potentially degrade garbage collection performance. \n// You should only use large buffer sizes if it will noticeably improve the performance of your app.\nvar newFile = await CreateNewFileAsync();\n\nusing (Stream ss = await file.OpenStreamForReadAsync())\nusing (Stream sd = await newFile.OpenStreamForWriteAsync())\n{\n    await ss.CopyToAsync(sd, 1024);\n    var fileProps = await file.GetBasicPropertiesAsync();\n    var size = fileProps.Size;\n}	0
31590070	31589995	Is it possible to create a shortcut for removing unused usings into a class?	Edit.RemoveUnusedUsings	0
8946937	8946846	Converting a byte array to PNG/JPG	byte[] bitmap = GetYourImage();\n\nusing(Image image = Image.FromStream(new MemoryStream(bitmap)))\n{\n    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png\n}	0
14769856	14769533	Disable all stylecop warnings for a specific C# class	public class OuterClass\n{\n    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "*")]\n    public class InnerClass\n    {\n        public void MyUndocumentedMethod\n        {\n        }\n    }\n}	0
20136323	20136252	Cannot Convert From List<T> to List<T>	public interface IRepository<T> where T : class\n{\n    void DeserializeJSON();\n}\n\npublic class Repository<T> : IRepository<T> where T : class\n{\n    private string data;\n    private List<T> entities;\n\n    public void DeserializeJSON()\n    {\n                   // Cannot implicitly convert type\n        entities = JsonConvert.DeserializeObject<List<T>>(data);\n    }\n}	0
1434103	1434062	Design Pattern to Handle Grouping Similar Entities Together	interface ParticipatorWrapper{\n    public void doSomething();\n}\n\nclass CustomerWrapper implements ParticipatorWrapper{\n    Customer customer;\n    public void doSomething(){\n       //do something with the customer\n    }\n}\n\nclass SaleREpresentativeWrapper implements ParticipatorWrapper{\n    SaleRepresentative salesRepresentative;\n    public void doSomething(){\n       //do something with the salesRepresentative\n    }\n\n}\n\nclass ClientOfWrapper{\n    public void mymethod(){\n         ParticipatorWrapper p = new ParticipatorWrapper(new Customer());\n         p.doSomething();\n   }\n}	0
3157088	3156893	Access MySettings from other Project in Solution	Public NotInheritable Class Helper\n   Private Sub New()\n   End Sub\n\n   Public Shared Function getAppSetting(ByVal key As String) As String\n       Dim returnValue As Object = My.Settings(key)\n       If returnValue Is Nothing Then\n           Return String.Empty\n       Else\n           Return returnValue.ToString\n       End If\n   End Function\nEnd Class	0
1689051	1687207	how to find the sqlserver name(data source) used by sharepoint?	public String GetSharePointSQLServerName()\n    {\n        String sServerName = "notFound";\n        foreach (var item in SPFarm.Local.Servers)\n        {\n            foreach (var svc in item.ServiceInstances)\n            {\n                 if (svc is SPDatabaseServiceInstance)\n                {\n                    SPDatabaseServiceInstance s = svc as SPDatabaseServiceInstance;                        \n                    sServerName = item.DisplayName+"\\"+s.Instance;\n                }\n            }             \n        }\n        return sServerName;\n    }	0
9295315	9295157	How can I prevent a third party from calling certain methods?	public partial class MyClass\n    {\n        public void NonSensitive(){}\n    }\n\n    #if INTERNAL_BUILD\n    public partial class MyClass\n    {\n        public void Sensitive(){}\n    }\n    #endif	0
12116776	12116576	Deserialize XML file	while(rdr.Read())\n  if(rdr.NodeType == XmlNodeType.Element)\n    switch(rdr.LocalName)\n    {\n      case "strFolder1":\n        strFolder1 = rdr.ReadContentAsString();\n        break;\n      case "strFolder2":\n        strFolder2 = rdr.ReadContentAsString();\n        break;\n      case "strTabName":\n        strTabName = rdr.ReadContentAsString();\n        break;\n      case "strTabText":\n        strTabText = rdr.ReadContentAsString();\n        break;\n    }	0
23519810	23517911	Checkout a dwg file using Vault Api	private static void downloadFile (VDF.Vault.Currency.Connections.Connection connection, \n        VDF.Vault.Currency.Entities.FileIteration file, string folderPath)\n    {\n        var settings = new VDF.Vault.Settings.AcquireFilesSettings(connection);\n        settings.AddEntityToAcquire(file);\n        settings.DefaultAcquisitionOption = VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Checkout |\n                                            VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download;\n\n        settings.LocalPath = new VDF.Currency.FolderPathAbsolute(folderPath);\n\n        connection.FileManager.AcquireFiles(settings);\n    }	0
19935940	19935180	ASP.NET manually update updatepanel to show feedback in long function	private static String infoMessages = "", errorMessages = "";\npublic void setFeedback(String message, bool info)\n{\n    if (info)\n    {\n        if (!infoCell.Visible)\n        {\n            errorCell.Visible = false;\n            infoCell.Visible = true;\n        }\n        infoMessages += String.Format("- {0}<br />", message);\n        lblInfo.Text += infoMessages;\n    }\n    else\n    {\n        if (!errorCell.Visible)\n        {\n            infoCell.Visible = false;\n            errorCell.Visible = true;\n        }\n        errorMessages += String.Format("- {0}<br />", message);\n        lblError.Text += errorMessages;\n    }\n}	0
12107663	12106766	Binding to an ICollectionView converted to a dictionary	var referenceCopy = Items;\nItems = null;//make sure INotifyPropertyCHanged is fired.\nItems = referenceCopy; //converter should be called again.	0
22866278	22865280	Regular Expressions - Datetime	\d{1,2}:\d{2}\s*[AP]M	0
31273090	31272847	How to write .csv from request stream	var fileStream = File.Create(fileNamePath);\n\nuploadFileStream.copyTo(fileStream);	0
31769546	31769505	[C#]Creating a file with FileStream returns an InvalidOperationException	string directory = @"C:\Users\PC-User\Documents\Link" + newURL.name + ".xml";\n    await Task.Run(()=>\n    {\n        Task.Yield();\n        using (var file = File.Create(directory))\n        {\n            xml.Serialize(file, url);\n        }\n    });	0
10136112	10126744	Is there a way to assign a ContextMenuStrip to a ListViewItem?	private void listView1_MouseDown(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        var hitTestInfo = listView1.HitTest(e.X, e.Y);\n        if (hitTestInfo.Item != null)\n        {\n            var loc = e.Location;\n            loc.Offset(listView1.Location);\n\n            // Adjust context menu (or it's contents) based on hitTestInfo details\n            this.contextMenuStrip2.Show(this, loc);\n        }\n    }\n}	0
19636811	19636536	c# console stick inside winform	public class ConsoleHelper\n{\n    /// <summary>\n    /// Allocates a new console for current process.\n    /// </summary>\n    [DllImport("kernel32.dll")]\n    public static extern Boolean AllocConsole();\n\n    /// <summary>\n    /// Frees the console.\n    /// </summary>\n    [DllImport("kernel32.dll")]\n    public static extern Boolean FreeConsole();\n}	0
22610391	22610189	Randomizing Numbers without repeating it in C#	Random r = new Random();\nvar numbers = Enumerable.Range(1,9) // create a sequence of the integers 1 through 9\n    .OrderBy(x => r.Next()) // randomize the order\n    .ToArray(); // turn the sequence into an array.\n\n// assign the numbers to the labels\nlabel1.Text = numbers[0];\n...\nlabel9.Text = numbers[8];	0
16957359	16956578	Search in specific column in ListView	foreach (ListViewItem lvi in listView1.Items)\n  if (lvi.SubItems[1].Text=="Text for search")\n     MessageBox.Show("!!!!!!!");	0
1818164	1818147	Help parsing GML data using C# Linq to XML	using System;\nusing System.Linq;\nusing System.Xml.Linq;\n\nclass Test\n{\n    static void Main()\n    {\n        XDocument doc = XDocument.Load("test.xml");\n        XNamespace gml = "http://www.opengis.net/gml";\n\n        var query = doc.Descendants(gml + "coord")\n            .Select(e => new { X = (decimal) e.Element(gml + "X"),\n                               Y = (decimal) e.Element(gml + "Y") });\n\n        foreach (var c in query)\n        {\n            Console.WriteLine(c);\n        }\n    }\n}	0
28171155	28171106	how can I make unconditional assert	Assert.Fail("Some message");	0
2523444	2521850	Changing DBML, how to change SQL database?	-- Update to version 2\nalter table [MyTable] add newColumn int null\nGO\nupdate [MyTable] set [newColumn] = 0\nGO\nalter table [MyTable] change newColumn int not null\nGO\nalter procedure spGetDBVersion\nas\nbegin\n    select 2 as CurrentVersion\nend	0
10795506	10795480	How to execute a stored procedure via odbc using c#?	using (OdbcConnection connection = new OdbcConnection(connectionString))\nusing (OdbcCommand command = connection.CreateCommand())\n{\n    command.CommandText = commandText //your store procedure name;\n    command.CommandType = CommandType.StoredProcedure;\n\n    command.Paremeters.Add("@yourParameter", OdbcType.NChar, 50).Value = yourParameter\n\n    DataTable dataTable = new DataTable();\n\n    connection.Open();    \n    using (OdbcDataAdapter adapter = new OdbcDataAdapter(command))\n    {\n        adapter.Fill(dataTable);\n    }\n}	0
11635995	11493829	Multidimensional array access performance in C#	b = a[3, 5];\n00000026  mov         eax,3 \n0000002b  lea         edx,[eax+2] \n0000002e  sub         eax,dword ptr [ecx+10h] \n00000031  cmp         eax,dword ptr [ecx+8] \n00000034  jae         0000010B \n0000003a  sub         edx,dword ptr [ecx+14h] \n0000003d  cmp         edx,dword ptr [ecx+0Ch] \n00000040  jae         0000010B \n00000046  imul        eax,dword ptr [ecx+0Ch] \n0000004a  add         eax,edx \n0000004c  mov         edi,dword ptr [ecx+eax*4+18h]	0
1598795	1598780	C# - Pass string to textbox in web page using the webbrowser control	HtmlDocument doc = this.webBrowser1.Document;\ndoc.GetElementById("myId").SetAttribute("Value", "someValue");	0
6219006	6218976	How to insert a new record with LinqToSql?	yourDatacontext.yourlinqClass.InsertOnSubmit(new yourlinqClass());\n\nyourDatacontext.SubmitChanges();	0
18989099	18988610	Converting numbers as Facebook Like Counter	object[][] list = {\n                              new object[] {"B", 1000000000}, \n                              new object[] {"M", 1000000}, \n                              new object[] {"T", 1000}\n                              };\n\n            long num = 123412456255; // Here should be the number of facebook likes\n            string returned_string = "";\n            foreach (object[] a in list) {\n                if (num / Convert.ToInt64(a[1]) >= 1) {\n                    returned_string += Convert.ToInt64(num / Convert.ToInt64(a[1])).ToString() + a[0] + " ";\n                    num -= Convert.ToInt64(num / Convert.ToInt64(a[1])) * Convert.ToInt64(a[1]);\n                }\n            } Console.WriteLine(returned_string);	0
5822370	5822333	Dictionary array to flat list	idList = deserializedJSON.Select(d => decimal.Parse(d["Id"]))\n                         .ToList();	0
6525946	6525845	Process boolean phrase with Regex	"\\b(and|or|not|near)\\b|\""	0
30089689	30075498	Extract full XML tree out of part of ID	using System;
\nusing System.Collections.Generic;
\nusing System.Linq;
\nusing System.Text;
\nusing System.Xml;
\nusing System.Xml.Linq;
\n
\nnamespace ConsoleApplication1
\n{
\n    class Program
\n    {
\n        const string FILENAME = @"c:\temp\test.xml";
\n        static void Main(string[] args)
\n        {
\n            XDocument doc = XDocument.Load(FILENAME);
\n            var results = doc.Root.Elements()
\n                .Where(x => x.Attribute("id").Value.EndsWith("ID1000"));
\n        }
\n    }
\n}???	0
28330416	28254275	Windows Phone 8.1: Save list in app settings/storage	private async void OnSuspending(object sender, SuspendingEventArgs e)\n    {\n        var deferral = e.SuspendingOperation.GetDeferral();\n\n\n        await SaveAppSettingsAsync();\n\n\n        deferral.Complete();\n    }\n\nprivate async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)\n    {\n        Frame rootFrame = Window.Current.Content as Frame;\n        if (rootFrame != null)\n        {\n            e.Handled = true;\n            if (rootFrame.CurrentSourcePageType == typeof(MainPage))\n            {\n                await SaveAppSettingsAsync();\n\n                this.Exit();\n            }\n            else if (rootFrame.CanGoBack)\n                rootFrame.GoBack();\n        }\n    }	0
7659852	7482269	set a datavalue of a detailsView ' field programmatically	protected void UpdateDataSource(object sender, EntityDataSourceChangingEventArgs e)\n{\n    if (!gruppoAdmin.Contains("SPGAdmins"))\n    {\n        SalesPortalModel.PianificazioneIncontri pianificazione = e.Entity as SalesPortalModel.PianificazioneIncontri;\n        int idCommerciale = (from a in entity.Commerciali where a.Nome == Context.User.Identity.Name select a.IDCommerciale).First();\n        pianificazione.IDCommerciale = idCommerciale;\n        detailsView1.Rows[1].Visible = false;\n    }\n\n}	0
2993801	2993761	Excel Automation From .NET - creating a new worksheet	Worksheet workSheet = (Worksheet)newWorkbook.Sheets.Add\n                (\n                    existingWorksheet, // before\n                    System.Reflection.Missing.Value,\n                    System.Reflection.Missing.Value, // 1,\n                    System.Reflection.Missing.Value //XlSheetType.xlWorksheet\n                );	0
2354713	2354662	Casting xml to inherited class	using System;\nusing System.IO;\nusing System.Xml.Serialization;\n\n[XmlRoot("ClassA")]\npublic class ClassA {\n    [XmlElement]\n    public String TextA {\n        get;\n        set;\n    }\n}\n\n[XmlRoot("ClassA")] // note that the two are the same\npublic class ClassB : ClassA {\n    [XmlElement]\n    public String TextB {\n        get;\n        set;\n    }\n\n}\n\nclass Program {\n    static void Main(string[] args) {\n\n        // create a ClassA object and serialize it\n        ClassA a = new ClassA();\n        a.TextA = "some text";\n\n        // serialize\n        XmlSerializer xsa = new XmlSerializer(typeof(ClassA));\n        StringWriter sw = new StringWriter();\n        xsa.Serialize(sw, a);\n\n        // deserialize to a ClassB object\n        XmlSerializer xsb = new XmlSerializer(typeof(ClassB));\n        StringReader sr = new StringReader(sw.GetStringBuilder().ToString());\n        ClassB b = (ClassB)xsb.Deserialize(sr);\n\n    }\n}	0
5495888	5495632	How to use webbrowser control to turn the div visibility into visible?	yourWebBrowserControl.Document.All["YourButton"].InvokeMember("click");	0
7599922	6601277	Troubles with setting ToolTip duration programmatically	// selectedPart will be null if no part is selected\nif(selectedPart != null && prevSelectedPart != selectedPart)\n{\n    toolTip.IsOpen = false;\n    host.ToolTip = toolTip;\n    toolTip.IsOpen = true;\n}\nelse if (prevSelectedPart == selectedPart  && prevSelectedPart != null)\n{\n    toolTip.IsOpen = true;\n}\nelse\n    toolTip.IsOpen = false;	0
7634999	7634205	DocX with filestream doesn't save	public ActionResult CVToWord(int id) \n        {\n            var CV = CVDAO.CV.Single(cv => cv.id == id);\n            var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx";\n\n            using (DocX doc = DocX.Create(filename)) \n            {\n                Paragraph title = doc.InsertParagraph();\n                title.Append(CV.firstname + " " + CV.name);\n                doc.Save();\n            }\n\n            System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);\n            return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);\n        }	0
4911158	4909067	MEF with ImportMany and ExportMetadata	public interface IMapMetaData\n{\n    int ID { get; }\n}	0
26353782	26353659	Regarding share link task in wp8	ShareLinkTask shareLinkTask = new ShareLinkTask();\nshareLinkTask.Title = "Code Samples";\nshareLinkTask.LinkUri = new Uri("http://code.msdn.com/wpapps", UriKind.Absolute);\nshareLinkTask.Message = "Here are some great code samples for Windows Phone.";\nshareLinkTask.Show();	0
34516976	34516784	Issues with file splitting with c#	i % numberOfRows	0
20416455	20415720	how do I hide email information in a .net application	System.Security.Cryptography	0
4240336	4239684	System.Configuration in a custom installer class	System.Configuration.dll	0
2118646	2118642	C# Regex quick help	var lines = File.ReadAllLines(originalPath);\nFile.WriteAllLines(newPath, lines\n    .Select(l => Regex.Match(l, @"\d+").Value).ToArray());	0
7976591	7976348	How to get absolute path for file download from another drive?	public class MyHandler :\n    IHttpHandler\n{\n    public void ProcessRequest(HttpContext context)\n    {\n        var fileName = Request[@"fn"];\n        var filePath = Path.Combine(@"C:\My\Fixed\File\Path", fileName );\n\n        Response.ContentType = @"application/pdf";\n\n        Response.AddHeader(\n            @"Content-Disposition", \n            @"attachment; filename=" + Path.GetFileName(filePath));\n        Response.AddHeader(\n            @"Content-Length",\n            new FileInfo(filePath).Length );\n\n        Response.WriteFile(filePath);\n        Response.End();\n    }\n\n    public bool IsReusable\n    {\n        get { return false; }\n    }\n}	0
1288845	1288652	validate string - only specific language characters	string str = "this text has arabic characters";\nbool hasArabicCharacters = str.Any(c => c >= 0xFB50 && c <= 0xFEFC);	0
3087299	3087102	Help with sql to linq conversion	var maxId = (from e in email_log\n             where e.as_at_date < new DateTime(2010, 06, 18)\n             group e by e.template_id into grouped\n             select grouped.Max(a => a.id)).First();\n\nvar selectedEmailLog = from e in email_log\n                       where e.id == maxId\n                       select new\n                       {\n                           email_id = e.id,\n                           e.sent_at,\n                           e.sent_by,\n                           e.template_id,\n                       };\n\nvar seletedRows = from t in email_templates\n                  join l in selectedEmailLog \n                    on t.id equals l.template_id into tls\n                  from tl in tls\n                  select new\n                  {\n                      t.id,\n                      tl.email_id,\n                      tl.sent_at,\n                      tl.sent_by,\n                  };	0
34315320	34304258	How do I set the contents of an ASPxImageZoom control?	protected void Page_Load(object sender, EventArgs e)\n{\n    string filePath = Server.MapPath("~/Images/41LR9-Q2W-L._AC_UX500_SY400_.jpg");\n    if (File.Exists(filePath))\n    {\n        Byte[] bytes = File.ReadAllBytes(filePath);\n        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);\n        ASPxImageZoom1.ImageUrl = "data:image/png;base64," + base64String;    \n    }            \n}	0
27506092	27501182	Add subtotals to Gridview & percentage difference	sum(table_a.col1) + sum(table_b.coly) as SubTotal	0
13207812	13207303	filter dataset based on the selected values in ComboBox	dgvMain.DataSource = null;\ndsMainDoctors.Tables[0].DefaultView.RowFilter = "Name = '" + cmbDoctorName.Text + "'";\ndgvMain.DataSource = dsMainDoctors.Tables[0].DefaultView;	0
6882859	6882792	public string blaBla { get; set; } in python	class Foo(object):\n   def __init__(self):\n      self._x = 0\n\n   def _get_x(self):\n      return self._x\n\n   def _set_x(self, x):\n      self._x = x\n\n   def _del_x(self):\n      del self._x\n\n   x = property(_get_x, _set_x, _del_x, "the x property")	0
9773823	9772912	Select next Item in Listview on Repeatbutton Click	ListBox1.SelectedIndex += 1; // increase\n\n        ListBox1.SelectedIndex -= 1;  //decrease	0
9942853	9942252	Get path to Silverlight ClientBin directory	string pathToClientBin = HostingEnvironment.MapPath("~/ClientBin");	0
7402826	7391836	Trying to get debugging output from Mono NUnit tests	mono --debug /opt/mono-2.10/lib/mono/4.0/nunit-console.exe Test.dll -config=Debug	0
15356939	15312066	Contact from join in EF	// db first\n        using (var db = new SO15312066Entities())\n        {\n            // iterate over table 1, with join values from 2\n            var query = db.Table1.Include("Table2");\n\n            foreach (var item in query)\n            {\n                Console.WriteLine("{0}:{1}", item.Id, string.Join(";", item.Table2.Select(x => x.Name).ToList()));\n            }\n        }\n\n        //output\n        //1:SomeText1;SomeText2\n        //2:SomeText3	0
4820649	4820515	How to open a form on a separate thread due to language requirements	Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-ca");	0
18103245	17971915	How to render Path geometry without Window Handle using Windows Store C++	ID2D1Factory *pFactory=nullptr;\n d2dDevice->GetFactory(&pFactory);\n ID2D1GeometrySink *pSink = NULL;\n ID2D1PathGeometry *pPathGeometry=NULL;\n // Create a path geometry.\n HRESULT hr = pFactory->CreatePathGeometry(&pPathGeometry);	0
29008131	29008038	Cant go deeper than root, LINQ to (Funds)XML, C#	roots.Descendants()	0
24996592	24904793	How to prevent non-mobile views from using the mobile layout in .Net MVC5?	_Layout.DesktopForMobile.cshtml	0
5899948	5899332	Is there a .NET method to grab the data source for an entity framework connection string?	EntityContextName context = new EntityContextName();\nstring datasourceName = context.Connection.DataSource;	0
1347983	1347936	Indentifying a custom indexer using reflection in C#	foreach (PropertyInfo pi in typeof(MyClass).GetProperties())\n{\n    if (pi.GetIndexParameters().Length > 0)\n    {\n       // Indexed property...\n    }\n}	0
23913238	23866401	Serialize DTO based on authentication	To conditionally serialize a property add a boolean method with the same name as \nthe property and then prefixed the method name with ShouldSerialize. \nThe result of the method determines whether the property is serialized. \nIf the method returns true then the property will be serialized, if it returns false\nand the property will be skipped.	0
9416059	9405659	How to get the view from a region in PRISM?	_regionManager.Regions["TopLeftRegion"].Add(new View1(),"ViewB");\n\nvar view = _regionManager.Regions["TopLeftRegion"].GetView("ViewB");	0
5961236	5960636	LINQ to SQL running direct SQL for a scalar value	var numberOfDays = db.ExecuteQuery<int>(str).FirstOrDefault();	0
27371216	27336204	Create contact group in EWS in contact folder other than WellKnownFolderName.Contact	FolderView cfv = new FolderView(1000);\n        cfv.Traversal = FolderTraversal.Shallow;\n        SearchFilter cfFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName,"OtherContacts");\n        FolderId cntfld = new FolderId(WellKnownFolderName.Contacts, "mailbox@domain.com");\n        FindFoldersResults ffcResult = service.FindFolders(cntfld, cfFilter, cfv);\n        if (ffcResult.Folders.Count == 1) {\n            ContactGroup cg = new ContactGroup(service);\n            cg.DisplayName = "TestCg";\n            cg.Save(ffcResult.Folders[0].Id);\n        }	0
28461453	28461235	Search for X amount of occurences within 24-hour Period	string reason = "???";\n\nvar query = \n    events.Where(ev => ev.Reason = reason)\n          .Select(ev => events.Where(ev2 => ev.Reason = reason &&\n                                            (ev.timestamp >= ev2.timestamp) &&\n                                            (ev.timestamp - ev2.timestamp).TotalHours <= 24))\n          .Where(g => g.Count() >= 10);	0
14734769	14734509	Using XmlDocument() with Nodes that have xmlns attributes?	XDocument xdoc = XDocument.Load("test.xml");\nXNamespace ns = "http://private.com";\nvar entries = xdoc.Descendants("Logs")\n                  .Elements(ns + "LogEntry")\n                  .Select(e => new {\n                      Date = (DateTime)e.Element(ns + "DateTime"),\n                      Sequence = (int)e.Element(ns + "Sequence"),\n                      AppID = (string)e.Element(ns + "AppID")\n                  }).ToList();   \n\nConsole.WriteLine("Entries count = {0}", entries.Count);    \n\nforeach (var entry in entries)\n{\n    Console.WriteLine("{0}\t{1} {2}", \n                      entry.Date, entry.Sequence, entry.AppID);\n}	0
19333832	19333648	Start a Task without waiting	public class HomeController : Controller\n{\n  public ActionResult Index()\n  {\n    ViewData["Message"] = "Welcome to ASP.NET MVC!";\n\n    Task.Run(()=> DoSomeAsyncStuff());\n\n    return View();\n  }\n\n  private async void DoSomeAsyncStuff()\n  {\n\n  }\n}	0
3990231	3990198	opening pdf file in console app	byte[] buffer = GetPdfData();\n\n// save to temp file\nstring path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()+".pdf");\nFile.WriteAllBytes(path, buffer);\n\n// open in default PDF application\nProcess process = Process.Start(path);\nprocess.WaitForExit();\n\n// clean up temp file\nFile.Delete(path);	0
11347516	11347343	Binding a DropDownList without a SqlDataSource in a Gridview	Dictionary<string, string> items= new Dictionary<string, string>();\nitems.Add("-1","-Select-");\nitems.Add("Test1", "Test1");\nitems.Add("Test2", "Test2");\nddl.DataSource = items;\nddl.DataValueField = "Key";\nddl.DataTextField = "Value";\nddl.DataBind();	0
15637196	15637106	How can I compare two lists using c#, and if I found same item in both list[No Duplication] add log	var commonElements = A.Intersect(B); \nforeach(var element in commonElements)\n{\n     //your processing.\n}	0
19954328	19764773	Get underlying Socket for HttpRequest	private void HandleAsyncConnection(IAsyncResult result)\n{\n  // Accept connection \n  TcpListener listener = (TcpListener)result.AsyncState;\n  TcpClient client = listener.EndAcceptTcpClient(result);\n  client.Client.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.TypeOfService);\n  ...\n  // and then I do a redirect in HTTP\n}	0
8657042	8657016	Add additional data to Linq to SQL result	ddlDomain.Items.Add(new ListItem() { Text = "All Url" });\nddlDomain.AppendDataBoundItems = true;\nddlDomain.DataSource = results;\nddlDomain.DataBind();	0
31423506	31423091	How to create backup of ms access in folder?	using System;\nusing System.IO;\n\npublic class Program\n{\n    public static void Main()\n    {\n\n        string baseDirectory = "C:\\Insert\\Your\\Base\\Directory";\n        string mdbSourceFilePath = "C:\\Directory\\Of\\mdb\\MyAccessDb.accdb";\n        string mdbTargetFileName = "MyAccessDb.bk";\n\n        string fullDirectory = Path.Combine(baseDirectory, DateTime.Today.ToString("dddd"));\n        if (!Directory.Exists(baseDirectory))\n            Directory.CreateDirectory(baseDirectory);\n        if (!Directory.Exists(fullDirectory))\n            Directory.CreateDirectory(fullDirectory);\n\n        string mdbTargetFilePath = Path.Combine(fullDirectory, mdbTargetFileName);\n\n        File.Copy(mdbSourceFilePath, mdbTargetFilePath);\n\n\n    }\n\n\n}	0
14742436	14742173	REGEX character Set substitution	var fromCharacters = "abcdefghijklmnopqrstuvwxyz";\nvar toCharacters = "12345678901234567890123456";\n\nvar myString = "bag";\n\nvar sb = new StringBuilder(myString.Length);\nfor (int i = 0; i < myString.Length; ++i)\n{\n    sb.Append(toCharacters[fromCharacters.IndexOf(myString[i])]);\n}\n\nsb.ToString().Dump();	0
14636598	14635642	Add Indexed (Duplicated OK) to access database C#	CREATE INDEX idx_columnName ON table(columnName) WITH IGNORE NULL	0
8828130	8826606	Disable Suspend in Window CE	private static void DoAutoResetEvent()\n    {\n        string eventString = "PowerManager/ReloadActivityTimeouts";\n\n        IntPtr newHandle = CreateEvent(IntPtr.Zero, false, false, eventString);\n        EventModify(newHandle, (int)EventFlags.EVENT_SET);\n        CloseHandle(newHandle);\n    }\n\n    private enum EventFlags\n    {\n        EVENT_PULSE = 1,\n        EVENT_RESET = 2,\n        EVENT_SET = 3\n    }\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    private static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);\n\n    [DllImport("coredll")]\n    static extern bool EventModify(IntPtr hEvent, int func);\n\n    [DllImport("coredll.dll", SetLastError = true)]\n    private static extern bool CloseHandle(IntPtr hObject);	0
2869798	2869764	ASPxGridView -- How to simply add example values with only a DataSource property?	public class Item\n{\n  public string Name { get; set; }\n  public int Count { get; set; }\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n  GridView1.DataSource = new Item[] { new Item { Name = "2", Count = 2 }, new Item { Name = "3", Count = 3 }, };\n  GridView1.DataBind();\n}\n\n\n<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" Width="100%" AutoGenerateColumns="False" >\n     <Columns>\n         <dxwgv:GridViewDataTextColumn Caption="Name" FieldName="Name" ReadOnly="True">\n         </dxwgv:GridViewDataTextColumn>\n         <dxwgv:GridViewDataTextColumn Caption="Count" FieldName="Count" ReadOnly="True" >\n         </dxwgv:GridViewDataTextColumn>\n     </Columns>\n     </dxwgv:ASPxGridView>	0
7147228	7147128	Changing LINQ-to-SQL connection string at runtime	DataContext context = new DataContext ("cxstring");	0
7689594	7689571	There is any way to force Take linq method to get less than count if there are no enough elements?	Enumerable.Take	0
6327197	6327154	Moving files from PC to MAC	**SYSTEM.IO**	0
24475023	24474888	different presentation of a float number in DB and webform	//point = arg.Point.ToString()\n   point = arg.Point.ToString("0.0", CultureInfo.InvariantCulture)    // always 1 decimal digit\n   point = arg.Point.ToString("#.##", CultureInfo.InvariantCulture)   // at most 2	0
32713837	32713431	Incorrect number of arguments supplied for call to method 'Boolean Equals	(from l in context.Languages\njoin t in context.Translations on l.ISO639_ISO3166 equals t.ISO639_ISO3166).AsEnumerable()\n.Where(l => string.Equals(l.ApplicationName, applicationName, StringComparison.InvariantCultureIgnoreCase))\n.Select(new Translation\n              {\n                  Key = t.Key,\n                  Text = t.Text\n              }).ToListAsync();	0
5297315	5297170	how to determine whether app.config file exists	if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["dummyflag"]))\n{\n  //config file doesn't exist..\n}	0
31527198	31526955	Windows Phone Launch App with Voice Commands in Cortana	Windows.Phone.Speech.VoiceCommands	0
28312488	28312144	static From and To methods vs implicit and explicit Casting methods	1/2 < 1/10f	0
23406108	23405867	How to check if button from user control was clicked?	protected void btnTest_Click(object sender, Eventargs e)\n{\n   //do something\n}	0
29771653	29771546	How to use vbKeySpace in C#?	if(intCharASCII == 32)\n  {\n     strEncodedStr = strEncodedStr + "+";\n  }	0
21427166	21427116	Getting sublist from a list in Linq	ListA.Where(x => x.Rank == 1)\n     .Select(x => new {\n         Max = x.Max,\n         Min = x.Min\n     })\n     .ToList();	0
1539901	1539806	read XML using LINQ	XDocument loaded = XDocument.Load(@"C:\data.xml");\nvar q = from c in loaded.Descendants("DATA")\n        select new \n        {\n            MsgId = (int)c.Attribute("msgid"),\n            MsgTime = (DateTime)c.Attribute("msgtime"),\n            PtpPercentage = (int)c.Element("PTP").Attribute("percentage")\n            ContUrls = from i in c.Element("CHAS1")\n                                  .Element("CONT1")\n                                  .Descendants("Image")\n                       where (string)i.Attribute("type") == "RIGHT"\n                       select (string)i.Attribute("url");\n        };	0
17325827	17325788	Get Windows user C#	Environment.UserName	0
20459726	20459605	Display FigCaption from Media library	var field = media.InnerItem.Fields["Copyright"]	0
3971304	3971258	c# win application	List<Button>	0
12895261	12895092	Disable and hide a TabPage	tabPage1.Enabled = false; // this disables the controls on it\n        tabPage1.Visible = false; // this hides the controls on it.	0
32965082	32964942	Authentication based on roles	cmd.ExecuteNonQuery();	0
8067595	8066976	SSAS / MDX / ADOMD.NET - Retrieve last updated date from a cube	Set objRst = objConnection.OpenSchema(32, Array(strCatalog, vbNullString, strCube))\ndtLast = objRs("LAST_DATA_UPDATE")	0
2953108	2953064	Best options for image resizing	public Bitmap Resize(Bitmap originalImage, int newWidth)\n{\n    int newHeight = (int)Math.Round(originalImage.Height * (decimal)newWidth / originalImage.Width, 0);\n    var destination = new Bitmap(newWidth, newHeight);\n    using (Graphics g = Graphics.FromImage(destination))\n    {\n        g.SmoothingMode = SmoothingMode.AntiAlias;\n        g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n        g.PixelOffsetMode = PixelOffsetMode.HighQuality;\n        g.DrawImage(originalImage, 0, 0, newWidth, newHeight);\n    }\n    return destination;\n}	0
2382254	2382233	passing a string parameter when calling a method in asp.net	ToolTip='<%# getToolTip(getProductIdNoutatiFeatured(),\n                        "imgBtnWishSubcategory2Featured")%>'/>	0
1454117	1454076	C#- problem with splitting string	SortedList<int, string> list = new SortedList<int, string>();\n            string[] seperator = new string[9];\n            seperator[0] = "*";  //is the client\n            seperator[1] = "/";  //is the name of company\n            seperator[2] = "(";     //name of the market    \n            seperator[5] = ":";    //ID\n            seperator[6] = "?";    //orderType\n            seperator[3] = "!@";   //realtive Time\n            seperator[4] = "!+";   //\n            seperator[7] = "+";    //quantity\n            seperator[8] = "@";//price\n            string val = "*A/AB(M!@12:6?SIMPLE!+5+2";\n\n            for (int iSep = 0; iSep < seperator.Length; iSep++)\n                list.Add(val.IndexOf(seperator[iSep]), val);	0
30705980	30705526	Gridview row count with condition	dataGridView1.DataSource = ds.Tables[0];\n    lbltotalfemale.Text = ds.Tables[0].Select("Gender='female'")\n                                      .Count().ToString();\n    lbltotalmale.Text = ds.Tables[0].Select("Gender='male'")\n                                    .Count().ToString();	0
26570347	26570226	Initializing a new vector3 with field values instead of literals	class MyClass\n{\n    private float crest1 = 14;\n    private float starter = 3;\n    private Vector3 L1;\n\n    public MyClass()\n    {\n        L1 = new Vector3(crest1, starter, crest1);\n    }\n}	0
1635048	1634795	Matrix Multiplication To Rotate An Image In C#	// create filter - rotate for 30 degrees keeping original image size\nRotateBicubic filter = new RotateBicubic( 30, true );\n// apply the filter\nBitmap newImage = filter.Apply( image );	0
26848351	26848187	How do I make the cursor to go back to RichTextBox after clicking a button?	private void button2_Click(object sender, EventArgs e)\n    {\n        richTextBox1.Focus();\n        richTextBox1.Select(lastPosition, 0);\n    }	0
33639755	33598370	Associate Contacts to Products/Contracts - Dynamics CRM	// Create an object that defines the relationship between the contact and contract.\nRelationship relationship = new Relationship("contract_customer_contacts");\n\n//Set up the EntityReferenceCollection that you are associating the contact to\nEntityReferenceCollection contractRefs = new EntityReferenceCollection().Add(\n    new EntityReference(Contract.EntityLogicalName, _contractId));\n\n//Associate the contact with the contract(s).\n_service.Associate(Contact.EntityLogicalName, _contactId, relationship,\ncontractRefs);	0
18754763	18719772	Run element text property is not set after navigating back from another frame	TextBlock txtBlockObject = (TextBlock)lstTabs.FindName("tabMessage");\n txtBlockObject.Inlines.Remove(runElementObj);\n runElementObj = null;\n // Create a new instance of run element and add it to the text block\n runElementObj = new Run();\n runElementObj.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);\n runElementObj.FontWeight = FontWeights.ExtraBold;\n txtBlockObject.Inlines.Add(runElementObj);	0
25162497	25162299	How can I order a column in Linq where that column is a string?	dict.Add(0, x => x.seleccionado);\ndict.Add(1, x => x.IdPedido);\n\n// etc.	0
33782561	33781709	Convert value stored as hex to date	2015-08-04 - **94** days = 2015-05-02\n2015-07-16 - **75** days = 2015-05-02\n2015-08-07 - **97** days = 2015-05-02	0
23544940	23543905	Making a .Net service configurable	SectionInformation.ProtectSection	0
24214208	24213616	Search with date only	var date = Convert.ToDateTime(search).Date;\nvar nextDay = date.AddDays(1);\nreturn View(db.newsletter\n    .Where(x => x.issuetime >= date && x.issuetime < nextDay)\n    .ToList());	0
2497418	2490496	Most efficient way to combine two objects in C#	private string Combine(string o1, string o2) { return o1 + o2; }\n    private string Combine(string o1, int o2) { return o1 + o2; }\n    private string Combine(string o1, float o2) { return o1 + o2; }\n    private string Combine(float o1, string o2) { return o1 + o2; }\n    private float Combine(float o1, int o2) { return o1 + o2; }\n    private float Combine(float o1, float o2) { return o1 + o2; }\n    private string Combine(int o1, string o2) { return o1 + o2; }\n    private float Combine(int o1, float o2) { return o1 + o2; }\n    private int Combine(int o1, int o2) { return o1 + o2; }	0
21248448	21247533	Individualize MarkerSize for each point in series based on axis values c#	static int CalcualteMarkerPixelSize(double diameterOnXAxis, Chart chart)\n{\n    double innerWidthScale = chart.ChartAreas[0].AxisX.Maximum - chart.ChartAreas[0].AxisX.Minimum;\n    float innerWidthPct = chart.ChartAreas[0].InnerPlotPosition.Width / 100;\n    float innerWidthPixels = chart.Width*innerWidthPct;\n    return (int) (diameterOnXAxis/innerWidthScale*innerWidthPixels);\n}	0
18488626	18403687	MSMQ custom message format	Message.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(string i want to put as Body))	0
4330067	4329939	Get SQL INSERT OUTPUT value in c#	OUTPUT INSERTED.*	0
29742723	29742251	How to write this XAML Storyboard in Code behind?	DoubleAnimation animation = new DoubleAnimation(100,0, new Duration(TimeSpan.FromMilliseconds(800)));\nContentGrid.BeginAnimation(HeightProperty, animation);	0
29469058	29441340	Ninject Binding By Parameter Name	_kernel.Bind<ITemplateProvider>().To<MessageTemplateProvider>().When(a => a.Target.Name == "msgTemplate");\n_kernel.Bind<ITemplateProvider>().To<MailTemplateProvider>().When(a => a.Target.Name == "mailTemplate");	0
3428942	3428916	Is there a shortcut to binary-serialize every property in an object?	MyObject obj = new MyObject();\nobj.n1 = 1;\nobj.n2 = 24;\nobj.str = "Some String";\nIFormatter formatter = new BinaryFormatter();\nStream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);\nformatter.Serialize(stream, obj);\nstream.Close();	0
30627139	30626864	Unit Testing - best practice for multiple runs	[TestMethod]\npublic void TestA()\n{\n  var result = TestI32(arg1, arg2);\n  Assert.IsTrue(result); // or whatever your assertion is.\n}\n\n[TestMethod]\npublic void TestB()\n{\n  var result = TestI32(arg3, arg4);\n  Assert.IsFalse(result); // or whatever your assertion is.\n}	0
5246704	5246680	Syntax help required	CollectionView.Filter = m => \n    ((Customer)m).DateAdded == DateTime.Parse(_filterDate);	0
1061342	1061334	Possible Loss of Fraction	double returnValue = (myObject.Value / 10.0);	0
26287374	26285503	Cron expression validator	CronExpression.ValidateExpression	0
31721003	31720485	List all days of a month ASP.NET C#	List<DateTime> daysOfMonth = Enumerable.Range(1, DateTime.DaysInMonth(year, month))  // Days: 1, 2 ... 31 etc.\n                             .Select(day => new DateTime(year, month, day)) // Map each day to a date\n                             .ToList();	0
33451535	33451417	Find index of an array in List of arrays in C#	var myArr = new int[] { 2, 1 };\nList<int[]> ListOfArrays = new List<int[]>();\nListOfArrays.Add(new int[] { 1, 1 });\nListOfArrays.Add(new int[] { 4, 1 });\nListOfArrays.Add(new int[] { 1, 1 });\nListOfArrays.Add(new int[] { 2, 1 });\n\nint index = ListOfArrays.FindIndex(l => Enumerable.SequenceEqual(myArr, l));	0
23089401	23088627	Adding a condition in a LINQ statement	private string GetErrorCodeLogLabel(ErrorCode code)\n        {\n            if(code == ErrorCode.Error /* || .. other errors*/)\n                return "Error";\n            else if (code == ErrorCode.Warning /* || .. other warnings*/)\n                return "Warning";\n\n            throw new NotImplementedException(code);\n        }\n\n        var errors = errorList.\n            Select((e, i) => string.Format("{0} occured #{1}: {2} (Error code = {3}).", GetErrorCodeLogLabel(e.ErrorCode), i + 1, e.Message, e.ErrorCode)).\n            ToArray();	0
1205395	1205376	How can I convert this C# 2 delegate example to C# 3 lambda syntax?	_worker.DoWork += (s, args) => {body of method};	0
34297211	34296273	Reordering tabpages in c# with a for loop	for (int i = 0; i < 8; ++i) {\n  TabPage tp = tabControl1.TabPages[22];\n  tabControl1.TabPages.RemoveAt(22);\n  tabControl1.TabPages.Insert(5, tp);\n}	0
6692707	6692611	How to change DateTimeFormatInfo.CurrentInfo AbbreviatedDayNames collection	CultureInfo cinfo = CultureInfo.CreateSpecificCulture("en-EN");\ncinfo.DateTimeFormat.AbbreviatedDayNames = new string[]{"Suns","Mon","Tues", "Weds","Thursday","Fries","Sats"};	0
4326026	4325620	Draw image with rounded corners, border and gradient fill in C#	GraphicsPath gp = new GraphicsPath();\n    gp.AddLine(new Point(10, 10), new Point(75, 10));\n    gp.AddArc(50, 10, 50, 50, 270, 90);\n    gp.AddLine(new Point(100, 35), new Point(100, 100));\n    gp.AddArc(80, 90, 20, 20, 0, 90);\n    gp.AddLine(new Point(90, 110), new Point(10, 110));\n    gp.AddLine(new Point(10, 110), new Point(10, 10));\n    Bitmap bm = new Bitmap(110, 120);\n    LinearGradientBrush brush = new LinearGradientBrush(new Point(0, 0), new Point(100, 110), Color.Red, Color.Yellow);\n    using (Graphics g = Graphics.FromImage(bm))\n    {\n        g.FillPath(brush, gp);\n        g.DrawPath(new Pen(Color.Black, 1), gp);\n        g.Save();\n    }\n    bm.Save(@"c:\bitmap.bmp");	0
12109186	12091375	How to get a PropertyGrid's cell value (c#)?	private void button1_Click(object sender, EventArgs e)\n{\n    GridItem gi = propertyGrid1.SelectedGridItem;\n    while (gi.Parent != null)\n    {\n        gi = gi.Parent;\n    }\n    foreach (GridItem item in gi.GridItems)\n    {\n        ParseGridItems(item); //recursive\n    }\n}\n\nprivate void ParseGridItems(GridItem gi)\n{\n    if (gi.GridItemType == GridItemType.Category)\n    {\n        foreach (GridItem item in gi.GridItems)\n        {\n            ParseGridItems(item);\n        }\n    }\n    textBox1.Text += "Lable : "+gi.Label + "\r\n";\n    if(gi.Value != null)\n        textBox1.Text += "Value : " + gi.Value.ToString() + "\r\n";\n}	0
11541950	11541600	c# reflection finding overloaded method wr to inheritance	var method = typeof(SomeClass).GetMethod("method", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(UserClass) },null);	0
3046467	3046193	How do I properly Load a Workflow after Pausing/Persisting it?	workflow = new WorkflowApplication(myActivity);\nworkflow.InstanceStore = wfStore;\nworkflow.Load(LastWfGuid);	0
32581529	32579743	Multiple Instances of Word Document Ribbon button disable in Word Addin Project	private void MyAddin_Startup(object sender, System.EventArgs a)\n{\n    this.Application.DocumentChange += new ApplicationEvents4_DocumentChangeEventHandler(Application_DocumentChange);\n}\n\nprivate void Application_DocumentChange()\n{\n    bool enableButton = false;\n    if(yourdocument)   // put something here that checks the document you want the button to be enable in\n    { \n        enableButton = true;\n    }\n    CustomRibbon ribbon = Globals.Ribbons.CustomRibbon;\n    ribbon.button.Enabled = enableButton;\n}	0
8558224	8558194	get string combination probability from 3 list of strings in c#	ICollection<String> result = new List<String>();\n\nforeach (String region in list1)\n{\n    foreach (String state in list2)\n    {\n        foreach (String lang in list3)\n        {\n            result.Add(String.Format("{0}/{1}/{2}", region, state, lang));\n        }\n    }\n}\n\n// Use result...	0
14020495	14020476	How to use DialogResult with javascript or jQuery?	var r = confirm("Press a button");\nif (r == true) {\n    alert("You pressed OK!");\n}\nelse {\n    alert("You pressed Cancel!");\n}???	0
28828731	28828365	how to select list of another list in EF	var st = students.SelectMany (s => s).Where(s=>s.Grade>15).ToList();	0
19805859	19805836	Command Pattern with responsible commands	ICommandResponse Execute(object params)	0
17154024	17153976	Must a ReadOnlyCollection<T> be immutable	ReadOnlyCollection<T>	0
18342275	18341902	Merging few lists into one using linq	Enumerable.Range(0, Some2dList.FirstOrDefault().Count)\n   .Select(columnIndex => \n       Some2dList.Max(row => row[columnIndex]))\n   .ToList();	0
10938378	10936266	How to break apart a URI in WP7?	public static class UriExtensions\n    {\n        private static readonly Regex QueryStringRegex = new Regex(@"[\?&](?<name>[^&=]+)=(?<value>[^&=]+)");\n\n        public static IEnumerable<KeyValuePair<string, string>> ParseQueryString(this Uri uri)\n        {\n            if (uri == null)\n                throw new ArgumentException("uri");\n\n            var matches = QueryStringRegex.Matches(uri.OriginalString);\n            for (var i = 0; i < matches.Count; i++)\n            {\n                var match = matches[i];\n                yield return new KeyValuePair<string, string>(match.Groups["name"].Value, match.Groups["value"].Value);\n            }\n        }\n    }	0
12491163	12490441	Generic regex to get iOS version, all iOS devices	(i[PSa-z\s]+);.*?CPU\s([OSPa-z\s]+(?:([\d_]+)|;))	0
21641802	21637556	DateTime.TryParse cannot parse DateTime.MinValue	private bool TryParseIso8601(string s, out DateTime result)\n{\n    if (!string.IsNullOrEmpty(s))\n    {\n        string format = s.EndsWith("Z") ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:sszzz";\n        return DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result);\n    }\n\n    result = new DateTime(0L, DateTimeKind.Utc);\n    return false;\n}	0
3149244	3149184	Can i use interfaces or polymorphism to deserialise two different xml files into one object type?	public interface IMessageReader()\n{\n    ONIXMessage Read(string xml);\n}\n\npublic static class ONIXMessageFactory\n{\n    private static IList<IMessageReader> readers = new List<IMessageReader>();\n\n    public static ONIXMessage CreateMessage(string xml)\n    {\n      var reader = GetReader(xml);\n      return reader.Read(xml);\n    }\n\n    public static IMessageReader GetReader(string xml)\n    {\n      // Somehow identify which reader would be required.\n    }\n}	0
4492628	4492587	Proper error handling with windows service that loads external assembly/dll	try\n{\n\n}\ncatch(Exception ex)\n{\n\n}\ncatch\n{\n}\nfinally\n{\n}	0
7420638	7420452	WP7 - set ListBoxItem.IsSelected to true from c#	// to add\nlistBox.SelectedItems.Add( someItem );\n\n// to remove\nlistBox.SelectedItems.Remove( someItem );\n\n// to clear\nlistBox.SelectedItems.Clear();	0
2104742	2104449	Replacing parameters in a lambda expression	public static void Main()\n{\n    String thing = "test";\n\n    Expression<Action<String>> expression = c => c.ToUpper();\n    Delegate del = expression.Compile();\n    del.DynamicInvoke(thing);\n\n    Dictionary<String, Delegate> cache = new Dictionary<String, Delegate>();\n    cache.Add(GenerateKey(expression), del);\n\n    Expression<Action<String>> expression1 = d => d.ToUpper();\n    var test = cache.ContainsKey(GenerateKey(expression1));\n    Console.WriteLine(test);\n\n}\n\npublic static string GenerateKey(Expression<Action<String>> expr)\n{\n    ParameterExpression newParam = Expression.Parameter(expr.Parameters[0].Type);\n    Expression newExprBody = Expression.Call(newParam, ((MethodCallExpression)expr.Body).Method);\n    Expression<Action<String>> newExpr = Expression.Lambda<Action<String>>(newExprBody, newParam);\n    return newExpr.ToString();\n}	0
32879882	32879827	Adding from one table and Update the other table	cmd.Parameters.AddWithValue("@ProductID", name);\n        cmd.Parameters.AddWithValue("@ProdCatID", DBNull.Value);\n        cmd.Parameters.AddWithValue("@SupplierName", txtSupplier.Text);\n        cmd.Parameters.AddWithValue("@Quantity", delivered);\n        cmd.Parameters.AddWithValue("@CriticalLevel", DBNull.Value);\n        cmd.Parameters.AddWithValue("@Price", DBNull.Value);\n        cmd.Parameters.AddWithValue("@Status", DBNull.Value);\n        cmd.Parameters.AddWithValue("@DateAdded", DateTime.Now);\n        cmd.Parameters.AddWithValue("@DateModified", DateTime.Now);\ncmd.ExecuteNonQuery();\n\ncmd = new SqlCommand();\ncmd.Connection = con;\n\n\n\ncmd.CommandText = "UPDATE PurchaseOrder SET POStatus=@POStatus WHERE PONo=@PONo";\ncmd.Parameters.AddWithValue("@POStatus", status);\ncmd.Parameters.AddWithValue("@PONo", txtPONo.Text);\ncmd.ExecuteNonQuery();	0
4688742	4688725	How to handle Textbox leave event for only once	txtNoOfAddenda.Leave -= txtNoOfAddenda_Leave;	0
10813277	10813249	Maintain variable value in method and caller method	private void method()\n{\n    int a = 10;\n    function(ref a);\n}\n\nprivate void function(ref int a)\n{\n    //do work and change value of a\n}	0
1537752	1537631	Unity and WCF Library: Where to load unity in a wcf library?	public static class ApplicationStart\n{\n    public static void AppInitialize()\n    {\n        // Initialise IoC container\n    }\n}	0
33791274	23041034	Can't see the table created with EF and code-first in Azure	public MyDbContext() : base("MyDbContext") {}\n\n<connectionStrings>\n<add name="MyDbContext" providerName="System.Data.SqlClient" connectionString="Server=tcp:servername.domain.win.net,1433;Database=MyDb;User ID=appuser@servername;Password=password;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"/>\n</connectionStrings>	0
1537764	1537731	Version number of a dll in .NET	string fileVersion = FileVersionInfo.GetVersionInfo(file).FileVersion;\nstring productVersion = FileVersionInfo.GetVersionInfo(file).ProductVersion;	0
12943883	12823305	How get the default Sharepoint AlertTemplates	SPAlertTemplateCollection atc = new SPAlertTemplateCollection((SPWebService)site.WebApplication.Parent);\n     SPAlertTemplate newTemplate = atc["SPAlertTemplateType.GenericList"];	0
18607739	18607625	Restrict visibility of classes by specific assembly	[assembly: InternalsVisibleTo("YourTestProject")]	0
2583713	2583565	delay ring between two font style changing	public static class LabelExtensions\n{\n    public static Label BlinkText(this Label label, int duration)\n    {\n        Timer timer = new Timer();\n\n        timer.Interval = duration;\n        timer.Tick += (sender, e) =>\n            {\n                timer.Stop();\n                label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold);\n            };\n\n        label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold);\n        timer.Start();\n\n        return label;\n    }\n}	0
4199337	4198692	Using MemoryMappedFile and FileSystemWatcher to detect new entries to logfile	FileStream fileStream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);	0
14113996	14113817	Match a string with regular expression, starting and ending with specific strings and not containing in between	aa(?!.*aa).*\.	0
31997850	31997707	Rounding value to nearest power of two	int ToNearest(int x)\n{\n  int next = ToNextNearest(x);\n  int prev = next >> 1;\n  return next - x < x - prev ? next : prev;\n}	0
683991	683896	Any way to create a hidden main window in C#?	Form f = new Form1();\n        f.FormBorderStyle = FormBorderStyle.FixedToolWindow;\n        f.ShowInTaskbar = false;\n        f.StartPosition = FormStartPosition.Manual;\n        f.Location = new System.Drawing.Point(-2000, -2000);\n        f.Size = new System.Drawing.Size(1, 1);\n        Application.Run(f);	0
7027267	7027112	How can I terminate a stored procedure?	BEGIN TRY\n\n  BEGIN\n    SELECT @temp = COUNT(*) FROM dbo.Users WHERE ManagerID = @original_UserID\n  END\n\n  BEGIN\n   IF(@temp>0)\n     RAISERROR ('This user is manager of other user',\n                16, -- Severity.\n                1 -- State.\n                );\n                //Error occurred / jump to the catch block\n  END\n\n  BEGIN\n    SELECT @temp = COUNT(*) FROM dbo.Project WHERE ProjectManagerID = @original_UserID\n  END\n\nEND TRY\nBEGIN CATCH\n  ...\nEND CATCH	0
12576362	12576351	I am trying to understand what is happening in this variable assignment	if( forward.Data.Key >= key ) {\n    num = 1;\n}\nelse {\n    num = 0;\n}	0
1968098	1967915	How to make ScrollViewer automatic	scrollViewer.UpdateLayout();\nscrollViewer.ScrollToVerticalOffset(txtBlock.ActualHeight);	0
31925820	31925731	Disable checkbox column based on user authorization	protected void grdchkbox_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n        CheckBox chkbox1 = (e.Row.FindControl("Checkbox1") as CheckBox);\n        //we check to see if we already have the users status saved in session\n        var isUser = HttpContext.Current.Session["IsGeneralUser"];\n        //if we dont, we run the IsGeneralUser method and save the result in session\n        if(isUser == null)\n        {\n            isUser = IsGeneralUser(empid);\n            HttpContext.Current.Session.Add("IsGeneralUser", isUser);\n        }\n        if (Convert.ToBoolean(isUser))\n        {\n            chkbox1.Enabled = false;\n        }\n    }\n}	0
20167467	20167448	Find type from Assembly that implements particular interface	foreach (Type type in customAssembly )\n    {\n       if (type.GetInterface("IPlugin") == typeof(IPlugin))\n       {\n         IPlugin plugin = Activator.CreateInstance(type) as IPlugin;                      \n        }\n    }	0
17373957	17372268	Inject EventAggregator into ViewModel with Caliburn Micro	var svm = new SomeViewModel(?)	0
2931974	2931917	using a List<Article> that is ordered, I want to get next/previous urls	var foundIndex = articles.FindIndex(a => a.Url == "myUrl");\nvar previousUrl = (foundIndex > 0 ? articles[foundIndex - 1].Url : null);\nvar  nextUrl = (foundIndex < articles.Count-1 ? articles[foundIndex + 1].Url : null);	0
21610084	21606044	Validate user details	if (!_userRepo.Validate(userName, password))\n            {\n                return null;\n            }	0
17519494	17519419	TextBox DateTime format	private void Form1_Load(object sender, EventArgs e)\n{\n   maskedTextBox1.Mask = "00.00.0000";\n}	0
20523370	20263547	Prevent winforms control from becoming visible when dynamically adding to Controls collection	protected override void OnShown(EventArgs e)\n{\n    //trigger the OnLoad event of myControl - this does NOT cause it to appear\n    //over the loading Panel\n    myControl.Visible = true;\n    myControl.Visible = false;  //set it back to hidden\n\n    //now add the control to the Controls collection - this now does NOT trigger the\n    //change to Visible, therefore leaving it hidden\n    Controls.Add(myControl);\n\n    //finally, set it to Visible to actually show it\n    myControl.Visible = true;\n\n    base.OnShown(e);\n}	0
28051585	28031435	Office 365 send email with attachment using OutlookServicesClient	// Save to Drafts folder\nawait outlook.Me.AddMessageAsync(m);\n\nforeach (var attach in me.Attachments)\n{\n    var file = attach.File;\n    var fileversion = file.GetVersion(attach.Version);\n    string fullpath = LibraryServiceImpl.GetFullNameInArchive(fileversion);\n    var mattach = new FileAttachment { Name = file.Name, ContentId = attach.ContentId, ContentLocation = fullpath, ContentType = GraphicUtils.DetermineMime(Path.GetExtension(fullpath)) };\n    if (file.Name.MissingText())\n        mattach.Name = attach.ContentId + fileversion.FileExtension;\n    m.Attachments.Add(mattach);\n}\n\n// Update with attachments\nawait m.UpdateAsync();\n// Send the message\nawait m.SendAsync();	0
32618125	32617991	Filter result is filtering with a byte and not with an integer value using reflection	dropDown.DataSource = typeMethod.Invoke(clase, new object[] { (byte)filter });	0
14682540	14682488	Get node by text from xml	var doc = XDocument.Load(path); // or .Parse(str)\nvar r = from e in doc.Element("NewDataSet") // root\n                     .Elements() // first level child nodes\n        // where e.Name.StartsWith("Table")\n        select e;	0
11541900	11501294	Serialize object to XML	namespace System.Xml.Serialization {\n    public static class XmlSerializationExtensions {\n        public static readonly XmlSerializerNamespaces EmptyXmlSerializerNamespace = new XmlSerializerNamespaces(\n            new XmlQualifiedName[] {\n                new XmlQualifiedName("") } );\n\n        public static void WriteElementObject( this XmlWriter writer, string localName, object o ) {\n            writer.WriteStartElement( localName );\n            XmlSerializer xs = new XmlSerializer( o.GetType() );\n            xs.Serialize( writer, o, EmptyXmlSerializerNamespace );\n            writer.WriteEndElement();\n        }\n\n        public static T ReadElementObject< T >( this XmlReader reader ) {\n            XmlSerializer xs = new XmlSerializer( typeof( T ) );\n            reader.ReadStartElement();\n            T retval = (T)xs.Deserialize( reader );\n            reader.ReadEndElement();\n            return retval;\n        }\n    }\n}	0
14705382	14700459	Update entity framework 5, one to one relationship	using (var context = new BenzineFleetContext())\n{\n    var card = context.Cards.First(c => c.Number == "123456");\n\n    var customer = new Customer { Name = "Rayz", Card = card };\n    card.Customer = customer;\n    context.SaveChanges();\n}	0
11393431	11389880	How to get the accurate total visitors count in ASP.NET	Dictionary<string, DateTime>	0
6765524	6764883	Programatically checkout a file in TFS 2010	GetStatus status = workspace.Get(new GetRequest("FilePath", RecursionType.None, VersionSpec.Latest),GetOptions.Overwrite);\nworkspace.PendEdit("FilePath");	0
3153268	3153217	C#: Enums in Interfaces	T : struct	0
24211919	24211837	Design pattern to use for read only operations by stored procedures?	public override List<AdminUser> GetAll() {\n        using (var context = new Scope_v5Entities()) \n            return context.getAllAdmin().ToList();\n    }	0
12323520	12323298	DataGridView ComboBox column selection changed event	private void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n    if(((DataGridView)sender).CurrentCell.ColumnIndex == 0) //Assuming 0 is the index of the ComboBox Column you want to show\n    {\n        ComboBox cb = e.Control as ComboBox;\n        if (cb!=null)\n        {\n            cb.SelectionChangeCommitted -= new EventHandler(cb_SelectedIndexChanged);\n            // now attach the event handler\n            cb.SelectionChangeCommitted += new EventHandler(cb_SelectedIndexChanged);\n        }\n    }\n}	0
13827107	13827067	Get first KeyValuePair in a dictionary that has a specific value	d[d.FirstOrDefault(x => string.IsNullOrEmpty(x.Value)).Key] = "My String";	0
15811446	15811164	How to use XmlTextWriter Element?	myXmlTextWriter2.WriteStartElement("Account");\nmyXmlTextWriter2.WriteAttributeString("nr", AccountNumber.ToString());\nmyXmlTextWriter2.WriteAttributeString("name", Name);\n\ndouble summ=0;\nforeach (AccountRecord ar in kp)\n{\n myXmlTextWriter2.WriteStartElement("Accounting");\n myXmlTextWriter2.WriteElementString("income", ar.Amount.ToString());\n myXmlTextWriter2.WriteEndElement();\n summ += ar.Amount;\n }\n\nmyXmlTextWriter2.WriteElementString("summincome", summ.ToString());\nmyXmlTextWriter2.WriteEndElement();	0
22574942	22571124	Dynamically add cells to table with fixed number of columns in ASP.net	// Suppose you want to add 10 rows\n    int totalRows = 10;\n    int totalColumns = 5;\n\n    for (int r = 0; r <= totalRows; r++)\n    {\n        TableRow tableRow = new TableRow();\n        for (int c = 0; c <= totalColumns; c++)\n        {\n            TableCell cell = new TableCell();\n            TextBox txtBox = new TextBox();\n            txtBox.Text = "Row: " + r + ", Col:" + c;\n            cell.Controls.Add(txtBox);\n            //Add the cell to the current row.\n            tableRow.Cells.Add(cell);\n\n            if (c==5)\n            {\n                // This is the final column, add the row\n                table.Rows.Add(tableRow);\n            }\n        }\n    }	0
25175105	25174974	Cast a Task<T> to a T	// Signature specifies Task<TResult>\n async Task<int> TaskOfTResult_MethodAsync()\n {\n     int hours;\n     // . . .\n     // Return statement specifies an integer result.\n     return hours;\n }\n\n // Calls to TaskOfTResult_MethodAsync\n Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();\n int intResult = await returnedTaskTResult;\n // or, in a single statement\n int intResult = await TaskOfTResult_MethodAsync();	0
20748026	20747890	How to Join 2 tables using lambda expression	from Fc in CoachingDef.FormCategory\njoin Ef in CoachingLang.ExpandedForm on Fc.FormID equals Ef.FormId \njoin Ec in CoachingLang.ExpandedCategory on Fc.CategoryID equals Ec.CategoryId\nwhere Ef.DictionaryId = -2147483645 && Ef.PropertyId = -2147483647\n&& Ec.DictionaryId = -2147483645 && Ec.PropertyId = -2147483647\n\nselect new {Translation = Ef.Translation +' - '+ Ec.Translation, \n    Fc.FormCategoryID, Ef.FormId,Ef.Translation, \n    Ec.CategoryId, Ec.Translation}	0
23823211	23822964	skipping string having angle brackets <*> in Regex	var cleanedString = Regex.Replace("<DOC NO> How are you <DOC NO/>", "<.*?>", "");	0
6928343	6927904	How do you Response.Redirect to another website with the same name, but with different port?	Response.Redirect(\n  "http://" + Request.Url.Host + ":90" + \n  Request.ApplicationPath + "/login.aspx");	0
33282744	33282656	Using Elvis operator in combination with string.Equals	if (data.val?.ToLower().Equals("x") ?? false) { }	0
13764847	13764027	Dynamically create Pivot item and add stack panel dynamically?	void ws_getMenuCompleted(object sender, getMenuCompletedEventArgs e)\n        {\n            PivotItem pvt;\n            for (int i = 0; i < e.Result.menu.Length; i++)\n            {\n                pvt = new PivotItem();\n                pvt.Header = e.Result.menu[i].name.ToLower();\n                var stack = new StackPanel();\n                pvt.Content = stack;\n                pvtRestaurante.Items.Add(pvt);\n                pvt = null;\n            }\n}	0
4401653	4401495	Insert data into text file	copy one.txt + two.txt three.txt	0
12175987	12175932	Initializing stored procedure output parameter	ParameterDirection.InputOutput	0
17908320	17908054	Lambda Expression if-else statement in where clauses	.Where(u => (userField == "ID" && u.Id == searchText)\n       || (userField == "Name" && u.Name == searchText)\n       || (userField == "Email" && u.Email == searchText)\n       )	0
20080525	20080461	How to make returned value of Button to "OK"	this.DialogResult = DialogResult.OK;\nthis.Close();	0
8761101	8761041	Messagebox button text	Win32.SetWindowText()	0
11385522	11380353	Box API v2 creating folder with cyrillic letters in it's name	public static Task<string> Post(string url, string data, string authToken) {\n    var client = new WebClient { Encoding = Encoding.UTF8 };\n    client.Headers.Add("Content-Type:application/x-www-form-urlencoded");\n    client.Headers.Add(AuthHeader(authToken));\n    return client.UploadStringTaskAsync(new Uri(url), "POST", data);\n}	0
20422557	20422488	How can i append a Where String in to Linq?	var query = from type in db.TempR_ThermometerType\n            select type;\n\nif (groupId >= 0)\n{\n    query = query.Where(type => type.GroupID == groupId);\n}\nif (siteId >= 0)\n{\n    query = query.Where(type => type.SiteID == siteId);\n}\n\n...\n\nreturn query.ToList();	0
15238690	15237942	Json response to class mapping Restsharp deserializing	public class Pothole\n{\n    public string id { get; set; }\n    public string latitude { get; set; }\n    public string longitude { get; set; }\n    public string rating { get; set; }\n    public string streetid { get; set; }\n    public string username { get; set; }\n    public string verified { get; set; }\n}	0
17412315	17412239	Keeping track of number of button clicks	if (!this.IsPostBack) { Session["RetryCount"] = 1; }\nelse\n{\n    int retryCount = (int)Session["RetryCount"];\n    if (retryCount == 3) { // do something because it's bad }\n    else { retryCount++; Session["RetryCount"] = retryCount; }\n}	0
2885163	2885123	How can I show characters for an ASP.net password textbox control after assigning its .Text property?	TextBox myTextBox = (TextBox)ControlTextBox;\nstring pwVal = myTextBox.Text;\nmyTextBox.Attributes.Add("value", "*******");	0
9165232	9165184	Storyboard TargetName WPF	ControlTemplate.Triggers	0
11290964	11290824	How to create a log file that logs the detail of each file copied in C#?	string saveTo1 = savePath + @"\" + filename[i];\nbyte[] buffer = new byte[32768];\ntry\n{\n            using (Stream input = getResponse.GetResponseStream())\n            {\n                using (FileStream output = new FileStream(saveTo1, FileMode.OpenOrCreate))\n                {\n                    int bytesRead;\n\n                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)\n                    {\n                        output.Write(buffer, 0, bytesRead);\n                    }\n                    output.Close();\n                }\n            }\n    //logging good news and info\n    MyLogManager("Good news", FileDetails);\n}\ncatch(Exception ex)\n{\n    //logging bad news and exceptions info\n    MyLogManager("Bad news", ExceptionDetails);\n}	0
3640268	3640128	Simulating a Backspace button press in c# with a null ActiveSource	else\n{\n    //Hacky?  Perhaps... but it works.\n    PresentationSource source = PresentationSource.FromVisual(this);\n    KeyEventArgs ke = new KeyEventArgs(\n                        Keyboard.PrimaryDevice,\n                        source,\n                        0,\n                        System.Windows.Input.Key.Back);\n    ke.RoutedEvent = UIElement.KeyDownEvent;\n    System.Windows.Input.InputManager.Current.ProcessInput(ke);\n}	0
34152834	34149405	How to play an internal sound with BackgroundMediaPlayer from my Universal Windows App	BackgroundMediaPlayer.Current.SetUriSource(new Uri("ms-winsoundevent:Notification.Looping.Alarm10"));\nBackgroundMediaPlayer.Current.Play();	0
11876037	11875889	EF repository Query method, how to mention other entity in expression?	Repository.Query(level => level.Title.Entity.EntityId == selectedId);	0
10789437	10788957	Fullscreen app in wince 6.0 c#	myForm.Width = Screen.PrimaryScreen.Bounds.Width;\nmyForm.Height = Screen.PrimaryScreen.Bounds.Height;\nmyForm.Left = 0;\nmyForm.Top = 0;	0
714216	714155	Passing objects as parameters to ActionResult methods in ASP .Net MVC from desktop client	var toWrite = DateTime.Now;\nstring url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile");\nurl = string.Concat(url, "?date=", toWrite.ToString("s"));	0
29249712	29231525	Google Chart to draw linechart	public class Col\n    {\n        public string id { get; set; }\n        public string label { get; set; }\n        public string pattern { get; set; }\n        public string type { get; set; }\n    }\n\n    public class C\n    {\n        public object v { get; set; }\n    }\n\n    public class Row\n    {\n        public List<C> c { get; set; }\n    }\n\n    public class RootObject\n    {\n        public List<Col> cols { get; set; }\n        public List<Row> rows { get; set; }\n    }	0
9281181	9280916	BCrypt Hashed Password Truncated in The Database	using (SqlConnection con = new SqlConnection("Your Connection String"))\n{\n    using (SqlCommand cmd = new SqlCommand("Your Stored Procedure Name", con))\n    {\n        SqlParameter param = new SqlParameter();\n        param.ParameterName = "Parameter Name";\n        param.Value = "Value";\n        param.SqlDbType = SqlDbType.VarChar;\n        param.Direction = ParameterDirection.Input;\n        cmd.Parameters.Add(param);\n        cmd.ExecuteNonQuery();\n    }\n}	0
8767031	8766974	Check JSON and XML is valid? c#	var serializer = new JavaScriptSerializer();\nvar result = serializer.Deserialize<Dictionary<string, object>>(json);	0
15465123	15465095	Letter replacement in string	foreach(char c in key){    \n    if(c==letter1){\n        newKey.Append(letter2);\n    }else if(c==letter2){\n        newKey.Append(letter1);\n    }else{\n        newKey.Append(c);\n    }\n}	0
10604266	10604210	Skipping locked section already in use	// Assuming this uses calls from multiple threads, I used volatile.\nvolatile bool executed = false;\nobject lockExcecuted = new object();\n\nvoid DoSomething()\n{\n    lock (lockExecuted)\n    {\n        if (executed) return;\n        executed = true;\n    }\n    // do something\n}	0
18301173	18301139	How to access different property value in derived class	public class ViewModelBase \n{\n    private string _aProperty = "A";\n    public virtual string AProperty \n    {\n        get { return _aProperty; }\n    }\n\n    public void DoSomething() \n    {\n        Console.WriteLine(AProperty);\n    }\n}\n\npublic class DerivedViewModel : ViewModelBase \n{\n    private string _bProperty = "B";\n    public override string AProperty \n    {\n        get { return _bProperty; }\n    } \n}\n\nDerivedViewModel dr = new DerivedViewModel();\ndr.DoSomething();//Prints B	0
14219797	14218443	Working with both landscape and portrait document	Document doc = new Document();\n            PdfCopy copy = new PdfCopy(doc, new FileStream(destination, FileMode.Create));\n            doc.Open();\n\n            foreach (Page page in pages) {\n                doc.NewPage();\n                copy.AddPage(copy.GetImportedPage(reader, page.Number));\n            }	0
17563813	17563729	Append Textbox value to a string	oOutputFile.FileName = "F:\inventor\Proof Of Con\Rim\Document\Rim_Update" & textbox1.Value & ".dwf"	0
17322014	17321948	Is there a RangeAttribute for DateTime?	public class CustomDateAttribute : RangeAttribute\n{\n  public CustomDateAttribute()\n    : base(typeof(DateTime), \n            DateTime.Now.AddYears(-6).ToShortDateString(),\n            DateTime.Now.ToShortDateString()) \n  { } \n}	0
6431181	6410431	Outputcache attribute on clientside with partial pages'	[OutputCache(Duration=7200, VaryByParam="*")]  \npublic PartialViewResult Menu(int userId)\n{\n   ...\n}	0
56533	56521	Windows Forms Designer upset by a control with a nullable property	[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]	0
2597681	2597648	How to add member variable to an interface in c#	public interface IBase {\n  void AddData();\n  void DeleteData();\n}\n\npublic abstract class AbstractBase : IBase {\n  string ErrorMessage;\n  public abstract void AddData();\n  public abstract void DeleteData();\n}	0
1818926	1818848	How to empty the cells of a DataGridView in C#?	for (int i = 0; i < dgUsers.Columns.Count ;i++ )\n      {\n          for (int j = 0; j < dgUsers.Rows.Count; j++)\n          {\n               dgUsers.Rows[j].Cells[i].Value = "";\n          }\n      }	0
21509841	21509753	Using a calculated value in the OrderBy clause with EF	EntityFunctions.DiffDays(todaysDate, x.Created)	0
10820828	10820500	Timing a gridView Update in C#	if(!IsPostBack)\n    {\n      // only then bind your grid View...\n    }	0
12470013	12420045	Passing C-style arrays of structs/records from delphi 5 to C# via COM	// C# interop method.\nvoid DoFoo(byte[] myStructs); \n\n// Delphi SafeArray creation\nsize := fooNumber* sizeof(Foo);\narrayBounds.lLbound :=  0;\narrayBounds.cElements := size;\nsafeArray := SafeArrayCreate( varByte, 1, arrayBounds );\nSafeArrayLock(safeArray);\nMove(pointerToFooArray^, safeArray.pvData^, size);\nSafeArrayUnlock(safeArray);\nauroraDiagnostics.DoFoo(safeArray);	0
2913348	2913287	Comparing Arrays using LINQ in C#	string[] a = { "a", "b" };\nstring[] b = { "a", "b" };\n\nreturn (a.Length == b.Length && a.Intersect(b).Count() == a.Length);	0
343552	343457	Converting string from memorystream to binary[] contains leading crap	"<foo>"	0
3656408	3656100	max row=16,777,216 , Can't find the max columns in Datatable	DataTable dt = new DataTable();\ntry\n{\n    for(int i = 0;i<1000000000000;i++)\n        dt.Columns.Add(i.ToString)\n}\ncatch(Exception ex)\n{\n    //Some limit exception!\n}	0
30214748	30214283	How to use Web Browser Control in for loop?	int count = 3910001;//that's your number\nprivate void webBrowser1_DocumentCompleted(object sender,\n    WebBrowserDocumentCompletedEventArgs e)\n{\n    HtmlElement form = webBrowser1.Document.GetElementById("form1");\n    webBrowser1.Document.GetElementById("RollNo").SetAttribute("value", "100");\n    HtmlElement btn = webBrowser1.Document.GetElementById("Submit");\n    btn.InvokeMember("click");\n\n    ++count;\n    if(count<391537)//that's your Number too, but it does not make sense, Count is always smaller than 391537\n        webBrowser1.Navigate(url);\n}	0
26631896	26631822	Get data from Access database present on a different server	Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source="\\server\share\Filename.accdb";Mode=Share Deny None	0
14701302	14701209	Set window's default location on a user screen	this.StartPosition = FormStartPosition.Manual;\nthis.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width,\n                          Screen.PrimaryScreen.WorkingArea.Height - this.Height);	0
23926253	23926141	Windows service scheduling to run daily once a day at 6:00 AM	ServiceTimer = new System.Timers.Timer();\nServiceTimer.Enabled = true;\nServiceTimer.Interval = 60000 * Interval;\nServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(your function);	0
9384484	9384458	c# show only Month / Day	item.ActDate.ToString("MM/dd")	0
1073491	1073480	C#: Custom casting to a value type	public class Foo\n    {\n        public Foo( double d )\n        {\n            this.X = d;\n        }\n\n        public double X\n        {\n            get;\n            private set;\n        }\n\n\n        public static implicit operator Foo( double d )\n        {\n            return new Foo (d);\n        }\n\n        public static explicit operator double( Foo f )\n        {\n            return f.X;\n        }\n\n    }	0
20993732	20883282	How come I suddenly start receiving OAuthException when posting to facebook page using facebook c# SDK	dynamic result = fb.Post(PageId + "/feed", new\n                {\n                    access_token = AccessToken,\n                    link = url,\n                    message = message\n                });	0
9982684	9981942	How to display ? in PDF using iTextSharp?	Phrase phrase = new Phrase("A check mark: ");   \nFont zapfdingbats = new Font(Font.FontFamily.ZAPFDINGBATS);\nphrase.Add(new Chunk("\u0033", zapfdingbats));\nphrase.Add(" and more text");\ndocument.Add(phrase);	0
30353542	30342291	How to send messages from server to a specific client	_clientsocket.Send(...);	0
27010444	27009149	validating password with uppercase and lowercase	SqlCommand cmd = new SqlCommand ("select COUNT(*) from UserTable where (CAST(User_Name as varbinary(50))=cast('"+ Login.UserName_value+"' as varbinary))  and (CAST(User_Password as varbinary(50))=cast('"+Login.UserPassword_value+"' as varbinary)),con);\ncon.Open();\nstring str = cmd.ExecuteScalar().ToString();\ncon.Close();\nreturn str;	0
11479031	11478917	Programmatically Adding Permissions to a Folder	var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); \n\nSecurity.AddAccessRule(\n   new FileSystemAccessRule(\n       sid,\n       FileSystemRights.Modify,\n       InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n       PropagationFlags.None,\n       AccessControlType.Allow));	0
18318074	18316793	Populate combobox from datatable	private void FillComboFromColumnIndex(int columnIndex){\n  yourDataTable.AsEnumerable()\n               .Select(r=>r[columnIndex])\n               .Where(x=>x != null)\n               .Distinct().ToList()\n               .ForEach(x=>yourComboBox.Items.Add(x));\n}\n//To add all the items in column at index 1, do this\nFillComboFromColumnIndex(1);	0
27773361	27773236	how to get connection string from app config in c#	SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);	0
925274	925244	Specifying instance for registration of a component with Castle Windsor	container.Register(Component.For<T>().Instance(myT));	0
16391171	16390939	Finding the distance of a point from a triangle in 3d space	[ 30 35 21 ]\nA = [ 24 13 29 ]\n    [ 22 19 85 ]	0
8382902	8382834	How to remove an xml element from file?	string xmlInput = @"<Snippets>\n <Snippet name=""abc"">\n   <SnippetCode>\n   code goes here\n   </SnippetCode>\n </Snippet>\n\n <Snippet name=""def"">\n   <SnippetCode>\n   code goes here\n   </SnippetCode>\n </Snippet>\n</Snippets>";\n\n// create the XML, load the contents\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xmlInput);\n\n// find a node - here the one with name='abc'\nXmlNode node = doc.SelectSingleNode("/Snippets/Snippet[@name='abc']");\n\n// if found....\nif (node != null)\n{\n   // get its parent node\n   XmlNode parent = node.ParentNode;\n\n   // remove the child node\n   parent.RemoveChild(node);\n\n   // verify the new XML structure\n   string newXML = doc.OuterXml;\n\n   // save to file or whatever....\n   doc.Save(@"C:\temp\new.xml");\n}	0
32039656	32039566	More than 2 Models in a ModelView with a twist	public List<Comment> Comments\n{\n    get\n    {\n        return _ticket.Comments.AsReadOnly();\n    }\n}	0
9366708	9366690	Divide a string at first space	var s = "!say this is a test";\nvar commands = s.Split (' ', 2);\n\nvar command = commands[0];  // !say\nvar text = commands[1];     // this is a test	0
4373790	4373669	how to properly populate DataSet twice (after empty set)	using (SqlConnection dbSqlConnection = new SqlConnection(connStr))\n{\n    //do things\n}//the connection will be disposed automatically here	0
11228124	11228069	VS2008 Build Error with xcopy	xcopy\n   "C:\Subversion Code\Subversion\Mrw\trunk\MrwMeasureApp\MrwReports"\n   "C:\Subversion Code\Subversion\Mrw\trunk\MrwMeasureApp\bin\Debug\MrwReports\"\n   /Y	0
2775679	2775665	Binary data instead of actual image in C#	byte[] bytes;\nusing (var stream = new MemoryStream())\n{\n    Code39 code = new Code39("10090");\n    code.Paint().Save(stream, ImageFormat.Png);\n    bytes = stream.ToArray();\n}	0
2092036	2091988	How do I update an ObservableCollection via a worker thread?	public static void AddOnUI<T>(this ICollection<T> collection, T item) {\n    Action<T> addMethod = collection.Add;\n    Application.Current.Dispatcher.BeginInvoke( addMethod, item );\n}\n\n...\n\nb_subcollection.AddOnUI(new B());	0
10938024	10937860	Remove all objects matching a condition	List<LabEntity> selected = originalSettings.SelectedInstanceLabs;\n        List<LabEntity> available = Presenter.GetLabs(dateRange);\n        if (!firstLoad)\n        {\n            //Remove selected labs\n            available = available.Except<LabEntity>(selected).ToList();\n        }	0
20194131	20193955	How to design the grid view with multiple row in on row template	protected void Page_Load(object sender, EventArgs e)    {\n        if (!IsPostBack)\n        {\n            DataSet ds = BOL.GetFilesFromCart();\n            GridView1.DataSource = ds;\n            GridView1.DataBind();\n        }\n    }\n\n    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            GridView gv = (GridView)e.Row.FindControl("GridView2");\n            DataSet ds1 = BOL.GetPrintSize();\n            ImageButton ib = (ImageButton)e.Row.FindControl("ImageButton1");\n            gv.DataSource = ds1;\n            gv.DataBind();\n        }\n    }	0
462301	462270	Get File Icon used by Shell	Imports System.Drawing\nModule Module1\n\n    Sub Main()    \n        Dim filePath As String =  "C:\myfile.exe"  \n        Dim TheIcon As Icon = IconFromFilePath(filePath)  \n\n        If TheIcon IsNot Nothing Then    \n            ''#Save it to disk, or do whatever you want with it.\n            Using stream As New System.IO.FileStream("c:\myfile.ico", IO.FileMode.CreateNew)\n                TheIcon.Save(stream)          \n            End Using\n        End If\n    End Sub\n\n    Public Function IconFromFilePath(filePath As String) As Icon\n        Dim result As Icon = Nothing\n        Try\n            result = Icon.ExtractAssociatedIcon(filePath)\n        Catch ''# swallow and return nothing. You could supply a default Icon here as well\n        End Try\n        Return result\n    End Function\nEnd Module	0
2517404	2517369	this keyword as a property	class MyClass\n{\n    Dictionary<string, MyType> collection;\n    public MyType this[string name]\n    {\n        get { return collection[name]; }\n        set { collection[name] = value; }\n    }\n}\n\n// Getting data from indexer.\nMyClass myClass = ...\nMyType myType = myClass["myKey"];\n\n// Setting data with indexer.\nMyType anotherMyType = ...\nmyClass["myAnotherKey"] = anotherMyType;	0
8308974	8308823	How can I use group in a LINQ expressions to group substrings of a field?	new [] { \n    "010000100001", "010000100001", "010000100001", "010000100002",\n    "010000100002", "010000100002", "010000200003", "010000200003",\n    "020000300004", "020000300005" }\n.GroupBy(s => new {\n          Subject = s.Substring(0,2),\n          Chapter = s.Substring(2,6),\n          Book    = s.Substring(8) });	0
4519037	4518940	Add UserControl to page From another class	namespace Program  \n{  \n    public class MyClass  \n    {  \n         public static void Calling(Page page)  \n         {  \n            ContentPlaceHolder cph = page.Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;\n            if (cph == null)\n            {\n                  return;\n            }\n\n            PlaceHolder ph = cph.FindControl("PlaceHolder1") as PlaceHolder;\n            if (ph != null)\n            {\n                ph.Controls.Add(new TextBox());\n            }\n         }  \n    }  \n}	0
8817720	8817674	How would you write this in VB.net? I don't get index++	Dim index As Integer = 0\nFor Each prop As [String] In props.Keys\n    index = index +1\n    pSpec.pathSet(index) = prop\nNext\npSpecs.Add(pSpec)	0
2551304	2551282	C# - Using a copy of Session-stored variables instead of reference	DataTable dtTable = ((DataTable)Session["someSessionKey"]).Copy();	0
30571949	30571925	Declare Generic static method in C#	public static class MyExtensions\n{\n  public static T ConvertToT<T, P>(this P ob)\n    where T : class\n    where P : class\n  {\n    // ...\n  }\n}	0
33828376	33828287	C# self reference a method	void SelfRef(string _Input){\n    while(true)\n    {\n        if (_Input == "route1"){\n\n            _Input = "route2"\n            continue;\n\n        }else if (_Input == "route2"){\n\n            //route2 ends\n            break;\n        }\n        //break?\n    }\n}	0
24559027	24558166	Extracting Username and Password from raw URL	Uri uri = new Uri("http://bookReport/request.aspx?user=abc&password=password&request=1&option=yes");        \n    var qs = HttpUtility.ParseQueryString(uri.Query);	0
4510432	4510400	Linq Reverse -does it leave the variable changed or make a copy	Enumerable.Reverse	0
4176759	4176749	C# extension method, get rid of ref keyword	currentList.Insert(0, itemValue);	0
4733597	4733501	ClickOnce deployed application registry persmission issue	Process.Start(\n       new ProcessStartInfo\n       {\n           Verb = "runas",\n           FileName = typeof(SomeClassInOtherAssembly).Assembly.Location,\n           UseShellExecute = true,\n           CreateNoWindow = true // Optional....\n       }).WaitForExit();	0
14229047	14228980	C# EF Deep Lambda Distinct Count Query	project.ProjectDoc\n        .SelectMany(c => c.Comment.Select(i => i.UserID))\n        .Distinct()\n        .Count()	0
8093307	8092421	set tooltip for a control inside dataRepeater	if (tt.GetToolTip((PictureBox)sender)==string.Empty)\n    tt.SetToolTip((PictureBox)sender, "Delete This Entry");	0
2535333	2535086	UniqueConstraint in EmbeddedConfiguration	// Initialize Indexes\ndbConfig.Common.ObjectClass(typeof(DAObs.Environment))\n    .ObjectField("<Key>k__BackingField").Indexed(true);\ndbConfig.Common.Add(new Db4objects.Db4o.Constraints.\n    UniqueFieldValueConstraint(typeof(DAObs.Environment), "<Key>k__BackingField"));	0
31679289	31679035	Json Webrequest To C# Object	var url = JsonBaseuri + IDInput.Text;\nvar wc = new WebClient {Proxy = null};\nvar json = wc.DownloadString(url);\nvar responseModel = JsonConvert.DeserializeObject<InventoryJsonData>(json);\nvar price = responseModel.RootObject.Price;	0
21509519	21497902	NHibernate QueryOver query subclass from base	mutable=false	0
3723984	3716770	Setters in Domain Model	public void ChangeAddress(Address address)\n{\n   //Consistency rules are here\n   _address = address;\n}	0
11420651	11420611	Loading Array of Images	Project\bin\Debug	0
11853493	11846807	Allow non 0 uint for textbox in xaml - WPF 	public static readonly DependencyProperty dp =\n    DependencyProperty.Register(\n        "result", typeof( uint ), typeof( ui ),\n        new FrameworkPropertyMetadata(\n            ( uint )100, \n            null,\n            new CoerceValueCallback( ResultCoerceValue )\n        )\n    );\n\n\nprivate static object ResultCoerceValue \n    (DependencyObject depObj, object baseValue)\n{\n    uint coercedValue = (uint)baseValue;\n\n    if ((uint)baseValue == 0)\n        coercedValue = 1; // might be able to set to null...but not sure on that.\n\n    return coercedValue;\n}	0
31772196	31771517	Create WriteableBitmap in windows phone app 8.1?	WritableBitmapEx.WinRT.dll	0
22509058	22449063	how to access the control within a control in tablelayout	if (myCellControl is Container)\n{\n   Container tmp = myCellControl as Container;\n   //after this point, you can reference the controls/properties of your\n   //Container class/control using tmp... see example below as i do not know\n   //what your Container control exposes as far as properties are concerned.\n   Adapter.insertposition(RackID, row, col, tmp.ChannelValue, "Ready");\n}	0
10322374	9353583	Audio/Video Playback with seeking in XNA	Microsoft.DirectX.AudioVideoPlayback.Video	0
5460717	5460689	How can I access unknown typed object's property names	var properties = obj.GetType().GetProperties();	0
18320380	18320309	Retrieving value from database and set dropdown selected item	try //Try block for opening, querying and displaying pulled data\n        {\n            SqlConnection sqlConn = new SqlConnection("ConnString"); //Connection String\n            sqlConn.Open();\n            using (SqlDataAdapter dataadapter = new SqlDataAdapter("Select * from Test_Names", sqlConn))\n            {\n                var table = new DataTable();\n                a.Fill(table);           \n                comboBox1.DataSource = t;       \n                comboBox1.DisplayMember = "FirstName"; //name of Column/DisplayName\n                comboBox1.ValueMember = "Firstname"; //Name of Column/Value          \n             }                                    \n         }\n        sqlConn.Close(); //Close Conn\n        catch (Exception ex)\n        {\n        //handle errors\n        } //End Try Catch for SQL Operations	0
4520908	4520876	Counting the Frequency of Specific Words in Text File	var dict = new Dictionary<string, int>();\n\nforeach (var word in file)\n  if (dict.ContainsKey(word))\n    dict[word]++;\n  else\n    dict[word] = 1;	0
18567471	18567388	c# Is there a beter way to validate user input	class VendorViewModel\n{\n    [Required]\n    public string Name { get; set; }\n\n    public string Website { get; set; }\n\n    [Regex("regex for email")]\n    public string Email { get; set; }\n\n    [MaxLength(160)]\n    public string Address { get; set; }\n}	0
1642290	1642280	JPG to PDF Convertor in C#	public static void ImagesToPdf(string[] imagepaths, string pdfpath)\n{\n    using(var doc = new iTextSharp.text.Document())\n    {\n        iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));\n        doc.Open();\n        foreach (var item in imagepaths)\n        {\n            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);\n            doc.Add(image);\n        }\n    }\n}	0
13363120	13362938	Consume WCF service from PHP with .NET parameter	Reference.cs	0
11622712	11622456	calling controls in Parent window	var mainWindow = Application.Current.Windows.OfType<MainWindowForm>()\n                                            .FirstOrDefault();\n\nif (mainWindow != null)\n{\n   //Visibility stuff goes here\n}	0
7834783	7834604	Zed-Graph Set scale to default programmatically	_scale._minAuto = true;\n_scale._maxAuto = true;\n_scale._majorStepAuto = true;\n_scale._minorStepAuto = true;\n_crossAuto = true;\n_scale._magAuto = true;\n_scale._formatAuto = true;	0
27998070	27998006	Minimize / Transform string without losing data	using (SHA1Managed sha1 = new SHA1Managed())\n{\n    var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(mystring));\n    return Convert.ToBase64String(hash);\n}	0
3025287	3025010	How can I invoke linux programs from C#/Mono?	var psi = new Process.StartInfo ("gcc", "-gcc -arguments") {\n    RedirectStandardError = true,\n    RedirectStandardOutput = true,\n    UseShellExecute = false,\n};\nvar error  = new System.Text.StringBuilder ();\nvar output = new System.Text.StringBuilder ();\n\nvar p = Process.Start (psi);\np.EnableRaisingEvents = true;\np.OutputDataReceived +=\n    (object s, DataReceivedEventArgs e) => output.Append (e.Data);\np.ErrorDataReceived  +=\n    (object s, DataReceivedEventArgs e) => output.Append (e.Data);\n\np.WaitForExit ();	0
31930352	31929813	How to store a list of files from disk into an array in C# ASP.NET?	Public class Resource\n{\n    Public string URL {get; set;}\n    Public string Name {get;set;}\n}	0
22684642	22683618	When I add google+ button to my website, how can I be aware that `access_token` expired?	result = makeApiRequest();\nif (result.status == 401) {\n    refreshToken();\n    result = makeApiRequest();\n}	0
22789738	22789554	Use Response.Redirect to open pdf in browser	Content-Disposition: inline; doc.pdf	0
1406218	1406083	Two dimensional array slice in C#	public static IEnumerable<T> SliceRow<T>(this T[,] array, int row)\n{\n    for (var i = 0; i < array.GetLength(0); i++)\n    {\n        yield return array[i, row];\n    }\n}\n\ndouble[,] prices = ...;\n\ndouble[] secondRow = prices.SliceRow(1).ToArray();	0
16402321	16402173	How to draw a Horizontal line using Highcharts DotNet C#	.SetYAxis(new YAxis\n                  {\n                      Title = new XAxisTitle { Text = "" },\n                      PlotLines = new[]\n                                  {\n                      new XAxisPlotLines\n                       {\n                        value : 0,\n                        color : 'green',\n                        dashStyle : 'shortdash',\n                        width : 2,\n                        label : {\n                        text : ''\n                                 }\n                          }\n                       new XAxisPlotLines\n                                      {\n                        value : 250,\n                        color : 'red',\n                        dashStyle : 'shortdash',\n                        width : 2,\n                        label : {\n                         text : ''\n                                       }\n                                      }\n                                  }\n                  })	0
19874192	19874160	Convert video file to binary file - and then convert binary file to video file	var bytes = File.ReadAllBytes(pathToFile)	0
22926445	22926306	Replace a word from a specific line in a text file	var path = @"c:\temp\test.txt";\nvar originalLines = File.ReadAllLines(path);\n\nvar updatedLines = new List<string>();\nforeach (var line in originalLines)\n{\n    string[] infos = line.Split(',');\n    if (infos[0] == "user2")\n    {\n        // update value\n        infos[1] = (int.Parse(infos[1]) + 1).ToString();\n    }\n\n    updatedLines.Add(string.Join(",", infos));\n}\n\nFile.WriteAllLines(path, updatedLines);	0
7018815	7018003	Loop through a table in a CLR UDF C#	int count;\nusing (SqlCommand cmdCount = conn.CreateCommand())\n{\n    cmdCount.CommandText = "SELECT COUNT(*) FROM [MyTable]";\n    count = (int)cmdCount.ExecuteScalar();\n}\n\n// knowing the number of rows we can efficiently allocate the array\ndouble[] values = new double[count];\n\nusing (SqlCommand cmdLoad = conn.CreateCommand())\n{\n    cmdLoad.CommandText = "SELECT * FROM [MyTable]";\n\n    using(SqlDataReader reader = cmdLoad.ExecuteReader())\n    {\n        int col = reader.GetOrdinal("MyColumnName");\n        for(int i = 0; i < count && reader.Read(); i++)\n        {\n            values[i] = reader.GetDouble(col);\n        }\n    }\n}\n\n// do more processing on values[] here	0
24753429	24753297	Combobox value null on first launch	string st = PrCombo.SelectedItem.ToString();	0
11070173	11070154	build html from server side c#	string html="";\nstring param="Test Value";\nhtml+="<a href=\"#\" onclick=\""+"doSomething('"+param+"')\">Test</a>";	0
27213392	27213268	Linq, Joining a list to last item in another list	var usersActivity =\n    from user in Users\n    join activity in Activities on user.Id equals activity.UserId\n    group activity by user into UserActivities\n    select new\n    {\n        activity = UserActivities.OrderByDescending(g => g.DateTime).First(),\n        user = UserActivities.Key\n    };	0
3427054	3427030	Retrieve All Children From Parent[]	parents.SelectMany(p => p.Children).ToArray()	0
7597680	7596447	NUnit: SetUp and TearDown for each test in a test fixture across multiple Fixtures	public class BaseTest \n{\n[SetUp] \npublic void SetUp()\n{ \n    //Do generic Stuff \n}\n\n[TearDown] \npublic void TearDown()\n{\n  // Do generic stuff \n}\n\n\n\n[TestFixture]\npublic class TestClass : BaseTest\n{\n [SetUp] \npublic void SetUp()\n{ \n    //Do Stuff \n}\n\n[TearDown] \npublic void TearDown()\n{\n  // Do stuff \n}	0
15360913	15360642	Get the logged in user in Windows Forms using MS Access	Form2 objForm2=new Form2(String userid)\nobjForm2.ShowDialog();	0
23461883	23461760	IObservable sequence from *Async method	public static IObservable<Boo> OGetBoos(IReadOnlyCollection<Foo> foos)\n{\n    var query =\n        from f in foos.ToObservable()\n        from b in ConvertFooToBooAsync(f).ToObservable()\n        select b;\n\n    return query;\n}	0
158035	133194	Embedded Outlook View Control	session.AddStore("C:\\test.pst"); // loads existing or creates a new one, if there is none.\nstorage = session.Folders.GetLast(); // grabs root folder of the new fileStorage.\n\nif (storage.Name != storageName) // if fileStorage is brand new, it has default name.\n{\n      storage.Name = "Documents";\n      session.RemoveStore(storage); // to apply new fileStorage name, it have to be removed and added again.\n      session.AddStore(storagePath);\n }	0
20634444	20634406	linq sorted string in array by sub string	var res = new string[] { "1, Mark, 250", "4, Ostin, 150", "2, Rick K., 12", "11,Robert,1" };\n\n\n var sortByBonus = res.OrderBy(i => int.Parse(i.Split(',').Last())).ToArray();\n var sortById = res.OrderBy(i => int.Parse(i.Split(',').First())).ToArray();	0
14809206	14806895	Reading a DOCX file from stream	// First file\nvar xmlStream = System.Web.HttpContext.Current.Request.Files[0].InputStream;\nvar xmlDocument = new XmlDocument();\nxmlDocument.Load(xmlStream);\n\n// The same code for the second file processing.\n// Second file\nvar wordDocStream = System.Web.HttpContext.Current.Request.Files[1].InputStream;\nvar wordXmlDocument = new XmlDocument();\nwordXmlDocument.Load(wordDocStream);	0
13020256	13020202	Passing a model object to a RedirectToAction without polluting the URL?	[HttpPost]\npublic ActionResult Index(ContactModel model)\n{\n  if (ModelState.IsValid)\n  {\n    // Send email using Model information.\n    TempData["model"] = model;\n    return RedirectToAction("Gracias");\n  }\n\n  return View(model);\n}\n\npublic ActionResult Gracias()\n{\n  ContactModel model = (ContactModel)TempData["model"];\n  return View(model);\n}	0
8917969	8917896	locking a property after it's set	public class MyClass\n{\n    private bool myPropSet = false;\n\n    private int myProp;\n    public int MyProp\n    {\n        get\n        {\n            return myProp;\n        }\n        set\n        {\n            if (!myPropSet)\n            {\n                myPropSet = true;\n                myProp = value;\n            }\n        }\n    }	0
8994355	8994178	Cascading extension methods for multiple interfaces?	public static class Helper\n{\n    public static void ToEntity(this MeetingDto source)\n    {\n        Console.WriteLine ("MeetingDto.ToEntity");\n        //Do Stuff\n        (source as IDocumentDto).ToEntity();\n    }\n\n    public static void ToEntity(this ContactDto source)\n    {\n        Console.WriteLine ("ContactDto.ToEntity");\n        //Do Stuff\n        (source as IBaseDto).ToEntity();\n    }\n\n    public static void ToEntity(this IDocumentDto source)\n    {\n        Console.WriteLine ("IDocumentDto.ToEntity");\n        //Do Stuff\n        foreach (var element in source.Subscriptions)\n        {\n            element.ToEntity();\n        }\n    }\n\n    public static void ToEntity(this IBaseDto source)\n    {\n        Console.WriteLine ("IBaseDto.ToEntity");\n        //Do Stuff        \n    }\n}	0
18566681	18566612	My random number generator does not create a new value in my loop C#	private Random random = new Random();\nconst int minimumNumber = -9;\nconst int maximumNumber = 15;\npublic int GenerateRandomNumber()\n{        \n    var randomNumber = random.Next(minimumNumber, maximumNumber);\n    return randomNumber;\n}	0
6600853	6600713	Load selective XML data into Dataset using C#	var doc = XDocument.Load(fileName);\nvar lst = doc\n       .Descendants("summary")   // don't care where summary is\n       .Elements("account ")     // direct child of <summary>\n       .Select(x => new \n       {\n          number = x.Attribute("number").Value,\n          ...\n       });\n\nforeach(var account in lst) \n{\n  .... // add to DataSet\n}	0
7866927	7866907	How can I use c# to send a tweet?	[twitter]	0
3460000	3415550	How do I pass a list from aspx to javascript?	success: function(data) {\n        var loopList = data.message.NewList;\n        for (var i = 0; i < loopList.length; i++) {\n            addRecentData(loopList[i]);\n        }\n    },\n});\nfunction addRecentData(data) {\n    ....\n}	0
6654871	6654540	Update database bit value	static void UpdateCheckedState(bool state) {\n    string connectionstring = "<yourconnectionstring>";\n    using (SqlConnection connection = new SqlConnection(connectionstring)) {\n        try {\n            connection.Open();\n        }\n        catch (System.Data.SqlClient.SqlException ex) {\n            // Handle exception\n        }\n        string updateCommandText = "UPDATE Settings SET Value = @state WHERE Name = 'CheckboxState'";\n        using (SqlCommand updateCommand = new SqlCommand(updateCommandText, connection)) {\n            SqlParameter stateParameter = new SqlParameter("state", state);\n            updateCommand.Parameters.Add(stateParameter);\n            try {\n                updateCommand.ExecuteNonQuery();\n            }\n            catch (System.Data.SqlClient.SqlException ex) {\n                // Handle exception\n            }\n        }\n    }\n}	0
12527341	12517324	action controller asp.net	using (NHibernate.ISession nhSession = User.OpenSession())\nusing (var trans = nhSession.BeginTransaction())\n{\n    User u = nhSession.Get<User>(id);\n\n    // Now update non-identifier fields as you wish.\n\n    // Since the instance is already known by NH, the following\n    // is enough (with default NH settings) to persist the changes.\n    trans.Commit();\n}\n\nreturn true;	0
12309941	12309896	Copy to clipboard with masked textbox	masked.TextMaskFormat=MaskFormat.ExcludePromptAndLiterals	0
6210055	6210027	Calling stored procedure with return value	using (SqlConnection conn = new SqlConnection(getConnectionString()))\nusing (SqlCommand cmd = conn.CreateCommand())\n{\n    cmd.CommandText = parameterStatement.getQuery();\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");\n\n    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);\n    returnParameter.Direction = ParameterDirection.ReturnValue;\n\n    conn.Open();\n    cmd.ExecuteNonQuery();\n    var result = returnParameter.Value;\n}	0
26833502	26833205	How to place gameobject to mouse position	Vector3 a = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));\n\na.Set(a.x, a.y, myGameObject.transform.position.z);\n\nmyGameObject.transform.position = Vector3.Lerp(myGameObject.transform.position, a, 0.01f);	0
18367024	18341838	Reportviewer shows blank page after adding some code	public void InsertLineBreaks(List<LineChart> inputList, int sampleInterval)\n{\n    List<LineChart> breaklinesList = new List<LineChart> { };\n    for (int i = 1; i <= inputList.Count; i++)\n    {\n        if ((inputList[i].X - inputList[i - 1].X).TotalMinutes > sampleInterval)\n        {\n            LineChart breakline = inputList[i];\n            breakline.BreakLine = 1;\n            breaklinesList.Add(breakline);\n        }\n\n    }\n inputList.AddRange(breaklinesList);\n\n}	0
20075064	20059166	Applying a snapshot in Hyper-V WMI V2 from C#	ManagementBaseObject inParams = null;\n\ninParams = PrivateLateBoundObject.GetMethodParameters("ApplySnapshot");\ninParams["Snapshot"] = ((System.Management.ManagementPath)(Snapshot)).Path;\n\nManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ApplySnapshot", inParams, null);\n\n// i left this as i assume this is vs generated though this isn't how i would normally\n// get my jobs back.\nJob = ((ManagementPath)(outParams.Properties["Job"].Value));\n\nreturn Convert.ToUInt32(outParams.Properties["ReturnValue"].Value);	0
6098297	6098263	C# split first two in string, then keep all the rest together	string myString = "2008 apple micro pc computer";\nstring[] parts = myString.Split(new char[] { ' ' }, 3);	0
16747849	16747829	Replace chars order in string C#	var registerDate = "25-5-2013";\nregisterDate = String.Join("-", registerDate.Split('-').Reverse());	0
10101069	10100956	How do I convert from an unmanaged C++ dll char** to a C# string and back	[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]\nstatic extern int SomeDLLMethod(ref IntPtr data, ref int count);\n.....\nIntPtr data;\nint count;\nint retval = SomeDLLMethod(ref data, ref count);\nstring str = Marshal.PtrToStringAnsi(data, count);	0
17328640	17328339	cast string to enum	(eOrderType) Enum.Parse(typeof(eOrderType ),ds.Tables[0].Rows[0]["OrderType"]);	0
34042761	34032714	How to get all valid fields for WIQL query using TFS API C#?	witadmin listfields /collection:http://????:8080/tfs/DefaultCollection	0
9456858	9456667	How can one ComboBox's items be determined by another ComboBox's selected item?	Private Sub ComboBoxClients_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripComboBoxClients.TextChanged\n    If (Me.InitiallyLoaded) Then\n        LoadData()\n    End If\nend sub	0
10576574	10575843	How do LINQ expressions work with Stored Procedures?	repository.Find(...)	0
31208205	31207739	I need to embed an Excel file in a webpage	iframe {\n  -moz-transform: scale(0.25, 0.25); \n  -webkit-transform: scale(0.25, 0.25); \n  -o-transform: scale(0.25, 0.25);\n  -ms-transform: scale(0.25, 0.25);\n  transform: scale(0.25, 0.25); \n  -moz-transform-origin: top left;\n  -webkit-transform-origin: top left;\n  -o-transform-origin: top left;\n  -ms-transform-origin: top left;\n  transform-origin: top left;\n}	0
15698207	15696812	How to set relative path to Images directory inside C# project?	var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);\n\n            var logoimage = Path.Combine(outPutDirectory, "Images\\logo.png");\n\n            string relLogo = new Uri(logoimage).LocalPath;\n\n            var logoImage = new LinkedResource(relLogo)	0
5092722	5090392	WPF Tab Control Prevent Tab Change	private void tabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)\n    {\n        if (e.OriginalSource == tabControl)\n        {\n            if (EditMode == TEditMode.emBrowse)\n            {\n                _TabItemIndex = tabControl.SelectedIndex;\n            }\n            else if (tabControl.SelectedIndex != _TabItemIndex) \n            {\n                e.Handled = true;\n\n                tabControl.SelectedIndex = _TabItemIndex;\n\n                MessageBox.Show("Please Save or Cancel your work first.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);\n            }\n\n        }\n    }	0
32315290	32315183	Sending to multiple e-mail adresses	using System.Net;\nusing System.Net.Mail;\n\nvar fromAddress = new MailAddress("from@gmail.com", "From Name");\nconst string fromPassword = "fromPassword";\nconst string subject = "Subject";\nconst string 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()\n{\n    From = fromAddress,\n    Subject = subject,\n    Body = body\n})\n{\n    message.To.Add(new MailAddress("recipient1@example.com", "Name"));\n    message.To.Add(new MailAddress("recipient2@example.com", "Name"));\n    smtp.Send(message);\n}	0
12951435	12943740	Treating strings for insertion into XElement	static Lazy<Regex> ControlChars = new Lazy<Regex>(() => new Regex("[\x00-\x1f]", RegexOptions.Compiled));\n\n    private static string FixData_Replace(Match match)\n    {\n        if ((match.Value.Equals("\t")) || (match.Value.Equals("\n")) || (match.Value.Equals("\r")))\n            return match.Value;\n\n        return "&#" + ((int)match.Value[0]).ToString("X4") + ";";\n    }\n\n    public static string Fix(object data, MatchEvaluator replacer = null)\n    {\n        if (data == null) return null;\n        string fixed_data;\n        if (replacer != null) fixed_data = ControlChars.Value.Replace(data.ToString(), replacer);\n        else fixed_data = ControlChars.Value.Replace(data.ToString(), FixData_Replace);\n        return fixed_data;\n    }	0
21219087	21218896	Do something if certain process is running without timer	var process = Process.GetProcessesByName("notepad").FirstOrDefault();\nif (process == null)\n{\n    MessageBox.Show("process is not running");\n}\nelse\n{\n    process.EnableRaisingEvents = true;\n    process.Exited += (sender, args) =>\n        {\n            MessageBox.Show("process exited");\n        };\n}	0
11636956	11636905	How to invoke a function with type?	Type typeDefinition = typeof(MyObject<>);\nType constructedType = typeDefinition.MakeGenericType(t);\nMethodInfo method = constructedType.GetMethod("MyFunction");\nmethod.Invoke(null, null);	0
14827026	14826192	Find object below the Character Controller	using UnityEngine;\nusing System.Collections;\n\npublic class GetFloorName : MonoBehaviour \n{\n    public string NameOfRaycastHitObject;\n\n    void Update () \n    {\n        RaycastHit hitInfo;\n        int layerMask = ~(1 << LayerMask.NameToLayer("Player"));\n        float distance = 100f;\n\n        if (Physics.Raycast(transform.position, Vector3.down, out hitInfo, distance, layerMask))\n        {\n            NameOfRaycastHitObject = hitInfo.collider.name;\n        }\n    }\n}	0
33068640	33068555	How to define value for C# preprocessor symbol?	#defines	0
25120679	25120630	MSTest: How to assert positive if one of 3 asserts are valid?	Assert.IsTrue(\n    result.fieldA.StartsWith(astring) || \n    result.fieldB.StartsWith(astring) ||\n    result.fieldC.StartsWith(astring)\n);	0
10079271	10079222	load text property of label from datatable	lblagreeamount.Text = dt.Row[0]["amount"].ToString();	0
6565902	5548702	invoke button submit using webkitbrowser	.submit()	0
9901355	9901320	Need advice on how to best deal with the storing/unboxing of different types in a list and what is more optimal in my case	public interface IPricedItem\n{\n    double Price { get; }\n}\n\nclass Product : IPricedItem { ... }\nclass ProductCombo : IPricedItem { ... }\n\npublic class Whatever\n{\n    public List<IPricedItem> StoreItems { get; set; }\n}	0
24221982	24221749	Get Total Count and Page Rows in same database trip when using Entity Framework	var results = (from c in e.Customers\n               where m.Name.Contains(name)\n               select new { c.CustomerId, c.NAME, c.CITY, c.STATE, c.COUNTRY })\n              .Distinct()\n              .OrderBy(s => s.NAME)\n              .ThenBy(s => s.CITY)\n              .ThenBy(s => s.CustomerId)\n              .ToList();\ntotalCount = results.Count;\nreturn results.Skip(skipCount).Take(pageSize).ToList();	0
8015902	8015863	Dynamically Creating Multiple controls which use a common handler	protected void chkDynamic_CheckedChanged(object sender, EventArgs e)\n{\n    if (((CheckBox)sender).Checked)\n        Response.Write( "you checked the checkbox");\n    else \n        Response.Write("checkbox is not checked");\n}	0
11336809	11331475	Adding registries to Container after initialization	Container.Configure()	0
7454247	7454106	Windows service couldnt get screenshot in windows 7	CreateProcessAsUser()	0
4017650	4017593	Linq join, group, count where count greater than value	var qryGeoApppendCount =\n              (from a in append\n              join g in geo\n              on a.Field<string>("RNO")\n              equals g.Field<string>("RNO")\n              group g by g.Field<int>("DSCID") into appendGeo\n              select new\n              {\n                DscId = appendGeo.Key,\n                DscIdCount = appendGeo.Count()\n              })\n              .Where(a => a.DscIdCount > 1);	0
10753892	10753577	How to get a cell value buttonclick in DataGrid C#	private void dgv_buttonCol(object sender, DataGridViewCellEventArgs e)\n{\n        if (e.ColumnIndex != 4) // Change to the index of your button column\n        {\n             return;\n        }\n\n        if (e.RowIndex > -1)\n        {\n            string name = Convert.ToString(dgv.Rows[e.RowIndex].Cells[2].Value);\n            ShowRichMessageBox("Code", name);\n        }\n}	0
21281386	21281361	How to convert foreach loop to lambda expression	btnshowname.Visible = MyString.Any(s => s == "MyName");	0
26717586	24828812	Run task on background but return response to client in ASP MVC web application	// ...main thread is working here\n    //put a call to stored procedure on a separate thread\n    Thread t = new Thread(()=> {\n       //call stored procedure which will run longer time since it calls another remote stored procedure and\n       //waits until it's done processing\n    }).Start();\n\n   // ...main thread continue to work here and finishes the request so it looks for user as the response is coming right away, all other stuff is being processed on that new thread so user even doesn't suspect	0
5119111	5118868	How to Deserialize this Xml file?	public class SomeObject\n{\n    public List<Layer> Layers { get; set; }\n}\n\npublic class Layer\n{\n    [XmlAttribute]\n    public int Id { get; set; }\n\n    [XmlElement("RowInfo")]\n    public List<RowInfo> RowInfos { get; set; }\n}\n\npublic class RowInfo\n{\n    [XmlText]\n    public string Info { get; set; } // you'll need to parse the list of ints manually\n}	0
17992982	17988751	Implementing pinch zoom behavior on an image inside a data template	xmlns:Behaviors="clr-namespace:NAMESPACE;assembly=ASSEMBLY"	0
1522806	1522786	Is there some library to create object instances with dummy data in their properties?	var products = Builder<Product>.CreateListOfSize(100)\n                 .WhereTheFirst(10)\n                     .Have(x => x.QuantityInStock = Generate.RandomInt(1, 2000))\n                 .List;	0
10078378	10077699	Pattern for executing common code before a property is accessed	public enum XmlFile{\n    File1,\n    File2\n};\n\npublic static class TestFiles{\n    const string RelativeDirectory = @"TestData";\n    const string XmlExtension = @"xml";\n    static string RootPath {\n        get\n        {\n            return Some_DirectoryName_Determined_At_Run_Time_Returned_BySomeOtherModule();\n        }\n    }\n\n    //overload as necessary for other extensions or pass it as an additional parameter\n    public static string GetFullPath(XmlFile file){\n        return string.Format(@"{0}{1}\{2}.{3}", RootPath, RelativeDirectory, file, XmlExtension);\n    }\n}	0
22302370	22301868	Need to store multiple values seperated by comma(,) in single column	string sql = ("UPDATE  History set RegID_UserProfile=RegID_UserProfile + ',' + '" + Request.QueryString["id"].ToString() + "' WHERE UserName='" + Name + "' and LoginTime='" + time + "'");	0
8493836	8493535	How best to turn a JArray of type Type into an array of Types?	int[] items = myJArray.Select(jv => (int)jv).ToArray();	0
18802884	18802568	using HtmlAgilityPack	var nufus = doc.DocumentNode.SelectNodes("//table[@class='belediyeler']/tr")\n            .Skip(1)\n            .Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())\n            .Select(td => new { Yil = td[0], Toplam = td[1], Kadin = td[2], Erkek = td[3] })\n            .ToList();\n\ndataGridView1.DataSource = nufus;	0
4569916	4569862	how to get a list of recent documents in windows 7?	string path = Environment.GetFolderPath(Environment.SpecialFolder.Recent);\nvar files = Directory.EnumerateFiles(path);	0
18144791	18142331	Sharepoint OData query fails to compile with Where clause	query = oDataService.Tickets.Where(d => d.Created == dateStarted) as DataServiceQuery<TicketsItem>	0
18242538	18242320	Ignore a property during xml serialization but not during deserialization	XmlAttributeOverrides overrides = new XmlAttributeOverrides();\nXmlAttributes attribs = new XmlAttributes();\nattribs.XmlIgnore = true;\nattribs.XmlElements.Add(new XmlElementAttribute("YourElementName"));\noverrides.Add(typeof(YourClass), "YourElementName", attribs);\n\nXmlSerializer ser = new XmlSerializer(typeof(YourClass), overrides);\nser.Serialize(...	0
29497223	29482082	How to Define a PDF Outline Using MigraDoc	var document = new Document();\n// Populate the MigraDoc document here\n...\n\n// Render the document\nvar renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always)\n{\n    Document = document\n};\nrenderer.RenderDocument();\n\n// Create the custom outline\nvar pdfSharpDoc = renderer.PdfDocument;\nvar rootEntry = pdfSharpDoc.Outlines.Add(\n    "Level 1 Header", pdfSharpDoc.Pages[0]);\nrootEntry.Outlines.Add("Level 2 Header", pdfSharpDoc.Pages[1]);\n\n// Etc.\n\n// Save the document\npdfSharpDoc.Save(outputStream);	0
2646944	2646825	Launching default browser with html from file, then jump to specific anchor	string Anchor = String.Format("\"file:///{0}/site.html#Anchor\"", Environment.CurrentDirectory.ToString().Replace("\\", "/"));\nSystem.Diagnostics.Process.Start(Anchor);	0
14772284	14770361	Convert REST content to comma seperated string	string c = product["children"].ToString();\n\nforeach (Match m in Regex.Matches(c, "(?<=\")[\\w]+(?!=\")"))\n{\n    string children = m.Value + ",";\n}	0
14539710	14538924	Encryption of Data that should be stored in a Database. And understanding the concept of the "key" used,	web.config	0
4054082	4054075	How to make a deep copy of an array in C#?	int[,] originalValues = (int[,])this.Metrics.Clone();	0
13504092	13504067	Windows Desktop Size changed event?	SystemEvents.DisplaySettingsChanged	0
24569959	24568341	how to know that a mailitem has arrived in the folder	private Items _inboxItems;\n\nprivate void ThisAddIn_Startup(object sender, System.EventArgs e)\n{\n    MAPIFolder inboxFolder = Application.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);\n    _inboxItems = inboxFolder.Items;\n\n    _inboxItems.ItemAdd += InboxItems_ItemAdd;\n\n    Marshal.ReleaseComObject(inboxFolder);\n}\n\nprivate void ThisAddIn_Shutdown(object sender, System.EventArgs e)\n{\n    Marshal.ReleaseComObject(_inboxItems);\n}\n\nprivate void InboxItems_ItemAdd(object item)\n{    \n    if (item is MailItem)\n    {\n        // Add your code here        \n    }\n}	0
28769187	28767487	ServiceStack Funq Container setting public Members to null	container.Register<IDependency>(c => new Dependency(c.Resolve<IFoo>()) {\n        Bar = c.Resolve<IBar>()\n    })	0
20939895	20939170	Flat Roulette with random number: get interval where random belongs to	class Program\n{\n    static void Main(string[] args)\n    {\n        var random = new Random();\n        int[] roulette = { 0, 21, 29, 0, 50 };\n\n        var cumulated = roulette.CumulativeSum().Select((i, index) => new { i, index });\n        var randomNumber = random.Next(0, 100);\n        var matchIndex = cumulated.First(j => j.i > randomNumber).index;\n\n        Console.WriteLine(roulette[matchIndex]);\n    }\n}\n\npublic static class SumExtensions\n{\n    public static IEnumerable<int> CumulativeSum(this IEnumerable<int> sequence)\n    {\n        int sum = 0;\n        foreach (var item in sequence)\n        {\n            sum += item;\n            yield return sum;\n        }\n    }\n}	0
26335705	26333719	Checking if a string contains words in a specific order	class Program\n    {\n        static void Main(string[] args)\n        {\n            List<string> list = new List<string>();\n            list.Add("Bill cat had");\n            list.Add("Bill had a cat");\n            list.Add("Bill had cat");\n            list.Add("Cat had Bill");\n            Regex rex = new Regex(@"((Bill)).*((had)).*((cat))");\n\n            foreach (string str in list)\n            {\n                if (rex.IsMatch(str))\n                {\n                    Console.WriteLine(str);\n                }\n            }\n            Console.ReadLine();\n        }\n    }	0
6795931	6795903	C# WPF, Date Picker. Only following days	yourDatePickersName.DisplayDateStart = DateTime.Today;	0
4791224	4791202	Most efficient way to reverse the order of a BitArray?	public void Reverse(BitArray array)\n{\n    int length = array.Length;\n    int mid = (length / 2);\n\n    for (int i = 0; i < mid; i++)\n    {\n        bool bit = array[i];\n        array[i] = array[length - i - 1];\n        array[length - i - 1] = bit;\n    }    \n}	0
32970603	32970194	Get character position in StringBuilder when using contains	if (returnCode != null && returnCode.Length > 1 && returnCode[1] == '0') // no need to check for null if you are sure it's not null	0
30595051	30594948	Implementing a Command Design Pattern with static methods C#	public class SomeClass\n{\n    public static CreateCommand(SomeType state, SomeEventHandler eventHandler)\n    {\n        eventHandler += (s, e) => MyDelegate(state, s, e);\n    }\n\n    private static void MyDelegate(SomeType state, object sender, EventArgs e)\n    {\n        // do something with state, when the event is fired.\n    }\n}	0
28851558	28849144	Excel Sheet copy from gridview in formated excel file	// Load the existing Excel file\nExcelDocument workbook = new ExcelDocument();\nworkbook.easy_LoadXLSFile(pathToExistingExcel);\n\n// Get the first sheet\nExcelWorksheet sheet = (ExcelWorksheet)workbook.easy_getSheetAt(0);\n\n// Create a dataset that keeps the gridview datatable\nDataSet dataSet = new DataSet();\ndataSet.Tables.Add((DataTable)gridView.DataSource);\n\n// Insert gridview data into sheet\nsheet.easy_insertDataSet(dataset, false);\n\n// Choose a name for the xls file \nstring fileName = "Excel.xls";\nResponse.Clear();\nResponse.Buffer = true;\nResponse.AddHeader("content-disposition", "attachment;filename=" + fileName);\nResponse.ContentType = "application/vnd.ms-excel";\n\n// Export new Excel file and prompt the "Open or Save Dialog Box"\nworkbook.easy_WriteXLSFile(Response.OutputStream);	0
17664382	17660767	Azure Storage Table query by DateTime not returning any results	where g.PartitionKey.Equals(time.ToString("yyyyMMddHHmm"))	0
25309857	25309642	Ordered grouping without Dictionary	List<List<Trip>> tripsByMine2 = trips.GroupBy(x => x.demand.Mine)\n    .Select(x => x.ToList())\n     .OrderByDescending(x => x.Count)\n     .ToList();	0
28549602	28549530	Trying to understand the signature of a C# method	dh.Calculate<Byte>(new Image<Gray, Byte>[] { img[0] }, false, null);	0
359984	359894	How to create byte array from HttpPostedFile	byte[] fileData = null;\nusing (var binaryReader = new BinaryReader(Request.Files[0].InputStream))\n{\n    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);\n}	0
29023537	29003887	How to get all users that belong in an AppRole using Azure Active Directory Graph API	await client.ServicePrincipals\n    .GetByObjectId(servicePrincipalObjectId)\n    .AppRoleAssignedTo\n    .ExecuteAsync()	0
12476420	12475619	How to use function max for auto number?	public int Autogenerate()\n{\n    con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Directory.GetCurrentDirectory() + "/CleaningTroopers.mdb");\n    con.Open();\n    string str4 = "select iif(isnull(max(uom_code)),1000,max(uom_code)+1) from uom_master ";\n    cmd = new OleDbCommand(str4, con);\n    OleDbDataAdapter da = new OleDbDataAdapter(cmd);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n    return Convert.ToInt32(dt.Rows[0][0]);\n    con.Close();\n}	0
11165575	11159863	Add text to ZedGraph outside the graph area	private void Form1_Load(object sender, EventArgs e)\n{\n    GraphPane pane = zedGraphControl1.GraphPane;\n    pane.Chart.Rect = new RectangleF(10, 10, 500, 200);\n    TextObj testObj = new TextObj("X Axis Additional Text", 0.6, -0.3);\n    pane.GraphObjList.Add(testObj);\n    zedGraphControl1.Refresh();\n }	0
11891187	11879833	Showing Nothing in created PDF using iTextSharp?	System.Text.StringBuilder store = new System.Text.StringBuilder();\nstring line;\n\n     while ((line = htmlReader.ReadLine()) != null)\n     {\n       store.Append(line + Environment.NewLine);\n     }\n\nstring html = store.ToString();\nFileStream stream = new FileStream(newFileName, FileMode.Create, FileAccess.Write);\nDocument document = new Document(PageSize.LETTER, 15, 15, 35, 25);\nPdfWriter writer = PdfWriter.GetInstance(document, stream);\ndocument.Open();\nSystem.Collections.Generic.List<IElement> htmlarraylist = new List<IElement>(HTMLWorker.ParseToList(new StringReader(html), new StyleSheet()));\n\n     foreach (IElement element in htmlarraylist)\n     {\n        document.Add(element);\n     }\n\ndocument.Close();	0
30047460	30046955	Override Values in Insertion in Nested Dictionary in C#	if (!outerDictionary.ContainsKey(senderID))\n{\n    outerDictionary[senderID] = new Dictionary<int, string>();\n}\nouterDictionary[senderID][numMessages] = txtSendMessage.Text;	0
11284740	11284695	C# Console program that contains a constant static field to display text in the output main method	GirlScout.scoutName = Console.ReadLine();	0
22877633	22877148	Adding data to pdf file in c# using iTextSharp	Chunk ch= new Chunk("Here is your data");\nPhrase ph = new Phrase(beginning);\nParagraph p = new Paragraph();\np.Add(ph);\ndocument.Add(p);//this line must be added before you add table to document.	0
14104696	14104138	Manage ASP.NET session timeout for a single key	[Serializable]\npublic class SessionUser\n{\n    public User User { get; set; }\n    public DateTime Expires { get; set; }\n}\n\n[Serializable]\npublic class SessionRedirectUrl\n{\n    public Uri RedirectUrl { get; set; }\n    public DateTime Expires { get; set; }\n}	0
6508776	6508653	Manipulating a control in a child from the parent page	public bool ShowCreditCardButton\n{\n   get { return CreditCardButton.Visable; }\n   set { CreditCardButton.Visable = value; }\n}	0
818938	818909	Uploading a text file in ASP.NET	StreamReader reader = new StreamReader(fileUpload1.FileContent);\nstring text = reader.ReadToEnd();	0
25274816	25274639	Linq select one from groupby, take null or empty unless there is a number 1	students.GroupBy(s => s.Id).Select(s => s.OrderBy(p => p.Order ?? 9999)).Select(s => s.First()).ToList();	0
15493693	15481187	Handling alert after action chain in IE, webdriver	InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions\n{\n   EnableNativeEvents = true\n};\nIWebDriver driver = new InternetExplorerDriver(internetExplorerOptions);	0
4840242	4840231	How to render a self closing tag using TagBuilder?	canonical.ToString(TagRenderMode.SelfClosing);	0
25716986	25706708	TPL Dataflow Blocks using LinkTo Predicate	MainBlock.Completion.ContinueWith(t =>\n{\nBlock1.Complete();\nBlock2.Complete();\nBlock3.Complete();\n});\n\nTask.WhenAll(Block1.Completion, Block2.Completion, Block3.Completion)\n.ContinueWith(t =>\n{\n    EndBlock.Complete();\n});	0
12331934	12231144	How to tooltip the headers of the GridView using the list of items in ListBox	protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.Header)\n    {\n        for (int i = 1; i < GridView2.Columns.Count; i++)\n        {\n            String header = GridView2.Columns[i].HeaderText; \n\n            if (header.Length != 0)\n            {\n               e.Row.Cells[i+1].ToolTip = ListBox4.Items[i].ToString().Trim();\n            }\n        }\n    }\n}	0
16490034	16473188	Extracting the contents of a zipped tab delimited file from a byte array	Stream stream = new MemoryStream(file); // file as your byte[]\n    using (ZipArchive archive = new ZipArchive(stream))\n    {\n        foreach (ZipArchiveEntry entry in archive.Entries)\n        {\n            if (entry.FullName.EndsWith(".tsv", StringComparison.OrdinalIgnoreCase))\n            {\n                using (stream = entry.Open())\n                using (var reader = new StreamReader(stream)) {\n                        string output = reader.ReadToEnd();\n            }\n        }       \n    }	0
29202304	29202209	Execute IQueryable after it's being done building	return fetchedWorkflowLogs.ToList()	0
19320318	19320073	Different CSV files based on value	var adLines = new List<string>();\nvar bcLines = new List<string>();\nvar unknownLines = new List<string>();\nvar adList = new[]{"A", "D"};\nvar bcList = new[]{"B", "C"};\nusing(var debtors = new StreamReader(@"C:\CSV\Debtors.csv"))\n{\n    string line = null;\n    while((line = debtors.ReadLine()) != null)\n    {\n        string[] columns = line.Split(';'); // you should check if columns.Length is correct\n        string lastColumn = columns.Last().Trim();\n        if(adList.Contains(lastColumn, StringComparer.CurrentCultureIgnoreCase))\n            adLines.Add(line);\n        else if(bcList.Contains(lastColumn, StringComparer.CurrentCultureIgnoreCase))\n            bcLines.Add(line);\n        else\n            unknownLines.Add(line);\n    }\n}\nFile.WriteAllLines(@"C:\CSV\DebtorsSystemen.csv", adLines);\nFile.WriteAllLines(@"C:\CSV\DebtorsHolding.csv", bcLines);	0
7430943	7430862	Linq to xml using ASP.Net	var results = doc.Descendants("Order")\n                 .Where(o => o.Attribute("OrderNumber").Value == "SO43659")\n                 .FirstOrDefault();\n\nforeach (var r in results.Elements("LineItem"))\n{\n    ListBox1.Items.Add(new ListItem(r.ToString()));\n}	0
6207807	6198678	Make folders nodes in TreeView, and move nodes between them	protected void Populate(TreeNode parentNode, DirectoryInfo directory)\n{\n    foreach (DirectoryInfo dir in directory.GetDirectories())\n    {\n        TreeNode node = parentNode.Nodes[dir.Name] \n            ?? parentNode.Nodes.Add(dir.Name, dir.Name);\n        node.Tag = dir;\n        // node.ContextMenuStrip = cmenu;\n        Populate(node, dir);\n    }\n}	0
33224953	33224768	Output numbers separated by commas	Console.Write("1");\nfor (int number = 2; number <= 9; number++)\n  Console.Write(", {0}", number);	0
26056029	26055855	Navigating to phone settings	using Microsoft.Phone.Tasks; \n\nConnectionSettingsTask task = new ConnectionSettingsTask(); \ntask.ConnectionSettingsType = ConnectionSettingsType.WiFi;\n    task.Show();	0
31156269	31155565	Get child node attribute value based on parent node attribute value	XNamespace ns = XNamespace.Get("http://test.net/schema/session/1.0");\n\nIEnumerable<XElement> failures =\n    doc\n        .Descendants(ns + "download")\n        .Concat(doc.Descendants(ns + "upload"))\n        .Elements(ns + "result")\n        .Elements(ns + "message")\n        .Where(e => e.Parent.Attributes("success").Any(a => !(bool)a));	0
34341147	34340802	C# Read XmlElement from a Text file	XmlDocument xml = new XmlDocument ();\nxml.InnerXml = @"<Data a=\"a\" b=\"b\" c=\"c\" d=\"d\"><Date runDt=\"01-01-1900\" /></Data>";\nConsole.WriteLine (xml.ChildNodes [0].Attributes [0].InnerText);	0
8579435	8579034	Managing internal changes when deploying update for Windows Phone	var currentDbVersion = GetDbVersion();\nwhile(currentDbVersion < currentCodeVersion)\n{\n    switch(currentDbVersion)\n    {\n        case 1.2:\n            RunUpgradeFrom12to13();\n            break;\n        case 1.3:\n            RunUpgradeFrom12to13();\n            break;\n        default:\n            break;\n    }\n    currentDbVersion = GetDbVersion();\n}	0
1723905	1723884	LInq update is also inserting unwanted rows	DataContext.GetChanges()	0
23916924	23889993	Data format for generating table with json mvc ASP.NET	var dataResult = new List<List<sometypewhichhasallofthosejsobproperties>>();	0
31755537	31688080	French Characters in SQL Text field to UTF - 8	Encoding wind1252 = Encoding.GetEncoding(1252);\nEncoding utf8 = Encoding.UTF8;\nbyte[] wind125Bytes = wind1252.GetBytes(input);\nbyte[] data = Encoding.Convert(wind1252, utf8, wind125Bytes);	0
13116958	13116870	How do I search for a folder in a folder in c#?	Directory.Exists(currentPath + @"\Database")	0
25990562	25960918	How to click buttons/links which are in iframe? (GeckoFx)	string content = null;\nvar iframe = browser.Document.GetElementsByTagName("iframe").FirstOrDefault() as Gecko.DOM.GeckoIFrameElement;\nif (iframe != null)\n{\n    var html = iframe.ContentDocument.DocumentElement as GeckoHtmlElement;\n    if (html != null)\n        content = html.OuterHtml;\n\n    textBox1.Text = content;\n\n    GeckoElementCollection elements = iframe.ContentDocument.GetElementsByName("username");\n    foreach (var element in elements)\n    {\n        GeckoInputElement input = (GeckoInputElement)element;\n        input.Value = "Auto filled!";\n    }\n}	0
11149569	11149556	App.Config change value	string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          \nstring configFile = System.IO.Path.Combine(appPath, "App.config");\nExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         \nconfigFileMap.ExeConfigFilename = configFile;          \nSystem.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);\n\nconfig.AppSettings.Settings["YourThing"].Value = "New Value"; \nconfig.Save();	0
29303761	29303440	Connecting to a Database through a separate form C#	using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;", con))\n{\n  ...\n}	0
21147956	21025648	How to group near coordinates	var rand = new Random();\nvar threshold = 1;\nvar points = new List<PointF>();\n\nfor (int i = 0; i < 20; i++)\n{\n    points.Add(new PointF((float) rand.NextDouble()*10, (float) rand.NextDouble()*10));\n}\n\nConsole.WriteLine(points.Count);\n\nfor (int i = 0; i < points.Count(); i++)\n{\n    for (int j = i + 1; j < points.Count(); )\n    {\n        var pointHere = points[i];\n        var pointThere = points[j];\n\n        var vectorX = pointThere.X - pointHere.X;\n        var vectorY = pointThere.Y - pointHere.Y;\n\n        var length = Math.Sqrt(Math.Pow(vectorX, 2) + Math.Pow(vectorY, 2));\n\n        if (length <= threshold)\n        {\n            points.RemoveAt(j);\n        }\n        else\n        {\n            j += 1;\n        }\n    }\n}\n\nConsole.WriteLine(points.Count);	0
1787041	1786993	Dealing with Tokens	public void GetToken(int t)\n{\n    numTokens -= t;\n}	0
19293421	19293040	Insert text in a text file at specific position	string FilePath = @"C:\test.txt";\n\n        var text = new StringBuilder();\n\n        foreach (string s in File.ReadAllLines(FilePath))\n        {\n            text.AppendLine(s.Replace("here", "here ADDED TEXT"));\n        }\n\n        using (var file = new StreamWriter(File.Create(FilePath)))\n        {\n            file.Write(text.ToString());\n        }	0
1380032	1379720	Custom Sorting on a DataGridView	private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)\n    {\n        string cell1, cell2;\n\n        if (e.Column == "Your_Column")\n        {\n            if (e.CellValue1 == null) cell1 = "";\n            else cell1 = e.CellValue1.ToString();\n\n            if (e.CellValue2 == null) cell2 = "";\n            else cell2 = e.CellValue2.ToString();\n\n            if (cell1 == "Account Manager") { e.SortResult = -1; e.Handled = true; }\n            else\n            {\n                if (cell2 == "Account Manager") { e.SortResult = 1; e.Handled = true; }\n                else\n                {\n                    if (cell1 == "Assistant Account Manager") { e.SortResult = -1; e.Handled = true; }\n                    else\n                    {\n                        if (cell2 == "Assistant Account Manager") { e.SortResult = 1; e.Handled = true; }\n                    }\n                }\n            }\n        }\n    }	0
1757868	1755864	Automapper, generics, dto funtimes	MethodInfo createMap = createMapInfo.MakeGenericMethod(new Type[] { typeof(MainInvoiceDataSums), generetedType });	0
7737477	7737461	how to get only file names from the directory ,not the entire path	string filenameWithoutPath = Path.GetFileName(filename);	0
10855293	10855232	How to pass parameters to an ajax call	MyTest.init = function() {\n    var params = new Hash();\n    params.set("blank", "blank");\n    new Ajax.Request('/Test.asmx/CreateClients', {\n        method: 'post',\n        data: {Name:"name", Notes:"Notes"},\n        onSuccess: attachCallback(this, "Yay"),\n        onFailure: attachCallback(this, "Nay"),\n        onException: attachCallback(this, "Nay"),\n        parameters: params\n    });\n}	0
24108057	24108005	Convert hex string to byte array	public static byte[] StringToByteArray(string hex) \n{\n    if((hex.Length % 2) != 0)\n        hex = "0" + hex;\n\n    return Enumerable.Range(0, hex.Length)\n                     .Where(x => x % 2 == 0)\n                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))\n                     .ToArray();\n}	0
16679610	16678736	Limit the Properties Bound to DataGrid in WPF using MVVM	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        this.DataContext = new TypedListObservableCollection<Foo>();\n\n        InitializeComponent();\n    }\n}\n\npublic class TypedListObservableCollection<T> : ObservableCollection<T>\n    , ITypedList\n{\n    public TypedListObservableCollection()\n    {\n    }\n\n    PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)\n    {\n        return TypeDescriptor.GetProperties(typeof(T), new Attribute[] { BrowsableAttribute.Yes });\n    }\n\n    string ITypedList.GetListName(PropertyDescriptor[] listAccessors)\n    {\n        return typeof(T).Name;\n    }\n}\n\npublic class Foo\n{\n    public string Name\n    {\n        get;\n        set;\n    }\n\n    [Browsable(false)]\n    public bool IsSelected\n    {\n        get;\n        set;\n    }\n}	0
13737607	13737236	How to cast to a control found on the page	PropertyInfo.SetValue	0
14086215	14085856	RichTextBox select par of text	string text = "abc /*defg*/ hij /*klm*/ xyz";\nrichTextBox1.Text = text;\n\nRegex.Matches(text, @"\/\*(.*?)\*\/",RegexOptions.Singleline).Cast<Match>()\n        .ToList()\n        .ForEach(m =>\n        {\n            richTextBox1.Select(m.Index, m.Value.Length);\n            richTextBox1.SelectionColor = Color.Blue;\n            //or \n            //richTextBox1.Select(m.Groups[1].Index, m.Groups[1].Value.Length);\n            //richTextBox1.SelectionColor = Color.Blue;\n        });	0
10620662	10620534	Updating an Entity Framework entity mapped to a view	[DatabaseGenerated(DatabaseGeneratedOption.Computed)]	0
27379253	27379036	C# XDocument: Find Attribute by another Attribute	XElement item = xdoc.Root.Elements("item").FirstOrDefault(i => (string)i.Attribute("att") == "102");\nif (item != null) \n{ \n  string s = (string)item.Attribute("some");\n}\nelse\n{\n  // treat case that no matching item was found\n}	0
30293684	30292821	Limit navigation property to parent items with entity framework	public ICollection<Item> ItemsWithoutParent {\n    get {\n        return this.Items.Where(i => !i.ParentId.HasValue);\n    }\n}	0
3383452	3383397	How can I pass a variable number of named parameters to a method?	using System;\n\nnamespace ConsoleApplication5\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ParamsTest(new { A = "a", B = "b"});\n        }\n\n        public static void ParamsTest(object o)\n        {\n            if (o == null)\n            {\n                throw new ArgumentNullException();\n            }\n            var t = o.GetType();\n            var aValue = t.GetProperty("A").GetValue(o, null);\n            var bValue = t.GetProperty("B").GetValue(o, null);\n        }\n    }\n}	0
4357347	4357289	Custom user control not appearing in WPF window?	TimeoutPanel tp = new TimeoutPanel(this);\nmyGrid.Children.Add(tp);	0
18340608	18340419	Upload JSON File and Parse	using System.Web.Script.Serialization;\n\n[HttpPost]\npublic ActionResult Index(HttpPostedFileBase file)\n{\n    if (file.ContentLength > 0)\n    {\n        // get contents to string\n        string str = (new StreamReader(file.InputStream)).ReadToEnd();\n\n        // deserializes string into object\n        JavaScriptSerializer jss = new JavaScriptSerializer();\n        var d = jss.Deserialize<dynamic>(str);\n\n        // once it's an object, you can use do with it whatever you want\n    }\n}	0
15053637	15050982	Stream image to file from SavePicker in Windows 8	await current_photo.CopyAndReplaceAsync(file);	0
2462771	2424329	WPF ComboBox IsSynchronised Default Value	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        Supplier.Text = null;\n    }	0
23382672	23382605	Creating specific lambda expression	var item = stockList.FirstOrDefault(i => i == order.OrderItem);\n if (item != null)\n {\n     item.ChangeStock(order.NumberOfItems);    \n }	0
9117370	9117221	Retrieving the highest column value	long version = DbContext.ElectronicSignatureTypes\n                .Where(est => est.Entity.Name == entity)\n                .Max(est => est.Version);	0
14787528	14787499	How to deserialize a file received from the network	public static T BinaryDeserializeObject<T>(byte[] serializedType)\n    {\n        if (serializedType == null)\n            throw new ArgumentNullException("serializedType");\n\n        if (serializedType.Length.Equals(0))\n            throw new ArgumentException("byte array cannot be empty"));\n\n        T deserializedObject;\n\n        using (MemoryStream memoryStream = new MemoryStream(serializedType))\n        {\n            BinaryFormatter deserializer = new BinaryFormatter();\n            deserializedObject = (T)deserializer.Deserialize(memoryStream);\n        }\n\n        return deserializedObject;\n    }	0
2200948	2200174	How to detemine if the ADS account password needs to be reset at first login	usr.Properties["pwdLastSet"].Value = -1; // To turn on, set this value to 0.\nusr.CommitChanges();	0
7467653	7443781	How to convert string formula to a mathematical formula in C#	// Define the context of our expression\nExpressionContext context = new ExpressionContext();\n// Allow the expression to use all static public methods of System.Math\ncontext.Imports.AddType(typeof(Math));\n// Define an int variable\ncontext.Variables["a"] = 100;\n// Create a dynamic expression that evaluates to an Object\nIDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");\n// Evaluate the expressions\ndouble result = (double)eDynamic.Evaluate();	0
27462074	27404639	Search each element in string array for multiple terms using RavenDB and lucene	from doc in docs\nfrom text in doc.Tests\nselect new { Text = text }	0
33775632	33775070	C# CodeDom: Custom class as parameter in string code	string expression = @"using System;  \nnamespace MyNamespace {\n    public class MyClass {\n        public static int DoStuff(CustomClass myCustomClass) {\n            return myCustomClass.X + myCustomClass.Y;\n        }\n    }\n\n    public class CustomClass\n    {\n        public int X;\n        public int Y;\n        public CustomClass(int x, int y) { X = x; Y = y; }\n    }\n}";\n\nCSharpCodeProvider provider = new CSharpCodeProvider();\nCompilerParameters assemblies = new CompilerParameters(new string[] { "System.dll" });\nCompilerResults results = provider.CompileAssemblyFromSource(assemblies, expression);\nType temporaryClass = results.CompiledAssembly.GetType("MyNamespace.MyClass");\nType parClass = results.CompiledAssembly.GetType("MyNamespace.CustomClass");\nMethodInfo temporaryFunction = temporaryClass.GetMethod("DoStuff");\nobject mc = parClass.GetConstructor(new Type[] { typeof(int), typeof(int) }).Invoke(new object[]{1,2});\nobject result = temporaryFunction.Invoke(null, new object[] { mc });	0
12853179	12817510	How to Store SelectedRow.Cell[0] value in a session when CommandField is "Select" in a GridView	protected void GVNatureOFWork_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        int index = GVNatureOFWork.SelectedIndex;\n        string natureofwrkid = GVNatureOFWork.DataKeys[index].Value.ToString();\n        Session["NOWID"] = natureofwrkid;\n        lblDisplayNOWID.Text = natureofwrkid;\n        BindRegionProjectInfoGrid();\n\n    }	0
18234859	18234802	I need to use XmlDocument object instead read xml file from drive	XmlDocument doc = new XmlDocument();\nClassFromXsd obj = null;\nusing (var s = new MemoryStream())\n{\n    doc.Save(s);\n    var ser = new XmlSerializer(typeof (ClassFromXsd));\n    s.Seek(0, SeekOrigin.Begin);\n    obj = (ClassFromXsd)ser.Deserialize(s);\n}	0
3206434	3206379	disable a checkbox in gridview	void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e) {\n    if (e.Row.RowType == DataControlRowType.DataRow) {\n        MyObject myObj = (myObj)e.Row.DataItem;\n        if (myObj.flag) {\n            CheckBox cb = (CheckBox)e.Row.FindControl("myCheckBox");\n            cb.Enabled=false;\n        }\n    }\n}	0
17484523	17477355	Backup SQL Server database from windows form application by a button click	private void button_backup_Click(object sender, EventArgs e)\n        {\n            //con is the connection string\n            con.Open();\n            string str = "USE TestDB;";\n            string str1="BACKUP DATABASE TestDB TO DISK = 'E:\\backupfile.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";\n            SqlCommand cmd1 = new SqlCommand(str, con);\n            SqlCommand cmd2 = new SqlCommand(str1, con);\n            cmd1.ExecuteNonQuery();\n            cmd2.ExecuteNonQuery();\n            MessageBox.Show("success");\n            con.Close();\n        }	0
1594886	1567026	redirect user after inactivity, but keep session alive	function timer() \n{\n    time1 = window.setTimeout('redirect();', 300000);\n}\n\nfunction redirect() \n{\n   window.location = "XXX.aspx";\n}\n\nfunction detime() \n{\n    if (time1 !=null) {\n        window.clearTimeout(time1);\n        time1 = null;\n    }\ntimer()\n}	0
14719688	14719112	How can I have a nullable enum serialized to an attribute	public enum _RESIDENCEBorrowerResidencyType\n{\n    [XmlEnum(Name="")]\n    Default = 0,\n\n    Current,\n    Prior	0
2772270	2745268	How to use Tor control protocol in C#?	public static string MakeTcpRequest(string message, TcpClient client, bool readToEnd)\n{\n    client.ReceiveTimeout = 20000;\n    client.SendTimeout = 20000;\n    string proxyResponse = string.Empty;\n\n    try\n    {\n        // Send message\n        using (StreamWriter streamWriter = new StreamWriter(client.GetStream()))\n        {\n            streamWriter.Write(message);\n            streamWriter.Flush();\n        }\n\n        // Read response\n        using (StreamReader streamReader = new StreamReader(client.GetStream()))\n        {\n            proxyResponse = readToEnd ? streamReader.ReadToEnd() : streamReader.ReadLine();\n        }\n    }\n    catch (Exception ex)\n    {\n        throw ex;\n    }\n\n    return proxyResponse;\n}	0
16125780	16125721	How do you clear a WPF RichTextBox?	richTextBox.Document.Blocks.Clear();	0
2478532	2478495	Check the status of an application pool (IIS 6) with C#	protected void status()\n    {\n        string appPoolName = "dev.somesite.com";\n        string appPoolPath = @"IIS://" + System.Environment.MachineName + "/W3SVC/AppPools/" + appPoolName;\n        int intStatus = 0;\n        try\n        {\n            DirectoryEntry w3svc = new DirectoryEntry(appPoolPath);\n            intStatus = (int)w3svc.InvokeGet("AppPoolState");\n            switch (intStatus)\n            {\n                case 2:\n                    lblStatus.Text = "Running";\n                    break;\n                case 4:\n                    lblStatus.Text = "Stopped";\n                    break;\n                default:\n                    lblStatus.Text = "Unknown";\n                    break;\n            }\n        }	0
25523892	25523360	Enity Framework migrations - Multiplicity is not valid in Role	[Key, ForeignKey("CmsMember")]\npublic int nodeId { get; set; }	0
7095167	7095104	How to confirm that mail has been delivered or not?	smtp.Send()	0
6669903	6669811	Recreating a solution	#if some_condition/.../#endif	0
32403396	32402554	How to populate checkbox ID based on the SQL Server column name it represents	for (int i = 0; i < sdr.FieldCount; i++)\n    {\n        bool val = Convert.ToBoolean(dr[i]);\n        string colName = sdr.GetName(i);\n        if (colName != "Name" && val)\n        {\n            CheckBox myChkBox = (CheckBox)Page.FindControl(colName);\n            myChkBox.checked = val;\n\n        }\n    }	0
12598739	12598227	structure of arrays	public static void SendCmdWithData(int IntCode, Hashtable Htbl)\n        {\n            DatawithCommandCode[] arrData = new DatawithCommandCode[Htbl.Count];\n            try\n            {\n                int i = 0;\n                foreach (System.Collections.DictionaryEntry element in Htbl)\n                {\n                    DatawithCommandCode tempData = new DatawithCommandCode();\n                    tempData.CmdCode = Convert.ToInt32(element.Key);\n                    tempData.Value = Convert.ToInt32(element.Value);\n                    arrData[i++] = tempData;\n                }\n            }\n            catch (Exception) { }\n        }	0
23714894	23714657	How to make a List of interfaces to perform a action	public void Dispose()\n{\n   TellMinionsTo(minion=>minion.Dispose());\n}    \n\n\nprivate void TellMinionsTo(Action<ManagableClass> doSomething)\n{\n    foreach (ManagableClass minion in minions)\n    {\n         doSomething(minion);\n    }\n}	0
8667689	8608201	Make C# save a 16-bit bitmap without bitfields compression	EncoderParameters codecParams = new EncoderParameters(1);\ncodecParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L); \nb.Save(outputFilename, myImageCodecInfo, codecparams );	0
30265698	30265629	C# How do I stop code from looping during collection serialization causing a stackoverflow?	public Section this[int index]\n{            \n    get {\n        return (Section)base[index]; //loops here with index always [0]\n    }\n    set {\n        base[index] = value;\n    }\n}	0
1194740	1194675	C# and XPath - how to query	XmlNamespaceManager nsmgr = new XmlNamespaceManager(_xmlArticlesDocument.NameTable);\n nsmgr.AddNamespace("a", "the-namespace-in-them-xmlns-attribute");\n XmlNode page = _xmlArticlesDocument.SelectSingleNode(String.Format("//a:page[id={0}]", id), nsmgr);	0
6722430	6722418	C# : how can i switch between my two network interface	Socket.Bind	0
28995460	28822211	How To Draw A Frustum in OpenGL	Vector3 IntersectionPoint(ref Plane a, ref Plane b, ref Plane c)\n{\n    // Formula used\n    //                d1 ( N2 * N3 ) + d2 ( N3 * N1 ) + d3 ( N1 * N2 )\n    //P =   ---------------------------------------------------------------------\n    //                             N1 . ( N2 * N3 )\n    //\n    // Note: N refers to the normal, d refers to the displacement. '.' means dot product. '*' means cross product\n\n    Vector3 v1, v2, v3;\n    float f = -Vector3.Dot(a.Normal, Vector3.Cross(b.Normal, c.Normal));\n\n    v1 = (a.D * (Vector3.Cross(b.Normal, c.Normal)));\n    v2 = (b.D * (Vector3.Cross(c.Normal, a.Normal)));\n    v3 = (c.D * (Vector3.Cross(a.Normal, b.Normal)));\n\n    Vector3 vec = new Vector3(v1.X + v2.X + v3.X, v1.Y + v2.Y + v3.Y, v1.Z + v2.Z + v3.Z);\n    return vec / f;\n}	0
21075461	21074898	How can I convert using statement in vb syntax	Using sqlConnection As SqlConnection = New SqlConnection(Utilities.ConnectionString)\n\n        End Using	0
11862539	11862252	Drawn line isn't shown on a combobox	public Form1() \n{\n  InitializeComponent();\n  comboBox1.DrawMode = DrawMode.OwnerDrawFixed;\n  comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);\n}\n\nvoid comboBox1_DrawItem(object sender, DrawItemEventArgs e) {\n  e.DrawBackground();\n  e.Graphics.DrawLine(Pens.Black, new Point(e.Bounds.Left, e.Bounds.Bottom-1),\n    new Point(e.Bounds.Right, e.Bounds.Bottom-1));\n  TextRenderer.DrawText(e.Graphics, comboBox1.Items[e.Index].ToString(), \n    comboBox1.Font, e.Bounds, comboBox1.ForeColor, TextFormatFlags.Left);\n  e.DrawFocusRectangle();\n}	0
14651465	14651416	modifying a string variable	var query = "select col1, col2 from tab1 inner join (select col3, col4 from tab2)";\nvar regex = new Regex("select");\nquery= regex.Replace(query, "Select TOP 100", 1);	0
9502665	9502581	Sorting entries inside a ListView	public virtual void Sort(\n    string sortExpression,\n    SortDirection sortDirection\n)	0
22919915	22919857	How To remove the http://www from the any given url in c#	var url = "http://www.stackoverflow.com/questions/ask";\nurl = url.Replace("http://","").Replace("www.","")	0
2734679	2734640	How to get the row and column of button clicked, in the grid event handler?	UIelement element = (UIelement) Grid.InputHitTest(e.GetPosition(Grid));\nrow= Grid.GetRow(element);	0
32374507	32143745	WPF BitmapImage sliced in two	using(var ms = new MemoryStream(bytes))\n{\n     var decoder = new BmpBitmapDecoder(ms, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);\n     return new WriteableBitmap(decoder.Frames.FirstOrDefault());\n}	0
3376729	3376353	c# asp.net , add custom control	ArticleUserControl myControl = (ArticleUserControl)LoadControl("~/PathToUc/MyControl.ascx");\nmyControl.datasource = item;\nphControl.Controls.Add(myControl);	0
17296627	17294422	AdornerLayer.GetAdornerLayer() return NULL for all controls in a Panel	Content.UpdateLayout();	0
11133681	11133541	Sitecore Creating Item with Fields[] Included	Item newItem = parent.Add(itemName, template);\n    newItem.Editing.BeginEdit();\n    newItem.Fields["fieldName"].Value = "fieldValue";\n    newItem.Editing.EndEdit();	0
11107488	11107465	Getting only hour/minute of datetime	var src = DateTime.Now;\nvar hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);	0
11687104	11686988	How to append '/' to URL if the user removes '/' from url in ASP.NET MVC 4	public class UrlMessingModule : IHttpModule\n{\n    public void Init(HttpApplication context)\n    {\n        context.BeginRequest += Application_BeginRequest;\n    }\n\n    public void Dispose() { }\n\n    protected void Application_BeginRequest(object sender, EventArgs e)\n    {\n        var application = (HttpApplication) sender;\n        var request = application.Request;\n        var response = application.Response;\n\n        var url = request.Url.AbsolutePath;\n\n        if (url.Length > 1 && !url.EndsWith("/"))\n        {\n            response.Clear();\n            response.Status = "301 Moved Permanently";\n            response.StatusCode = (int)HttpStatusCode.MovedPermanently;\n            response.AddHeader("Location", url + "/");\n            response.End();\n        }\n\n    }\n}	0
16476253	16476061	Login control using fluent nhibernate	using NHibernate.Linq;\n\npublic ISession DbSession { get; set; } // set on each Beginrequest with ISessionFactory.OpenSession();\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    var registrations = DbSession.Query<Registration>()\n        .Where(registration => registration.Name == txt_name.Text)\n        .ToList();\n\n    if (registrations.Count == 0 || registrations[0].Password != txt_pass.Text)\n    {\n        label4.Text ="Invalid Username/Password";\n    }\n    else\n    {\n        Session["new"] = txt_name.Text;\n        Response.Redirect("logout.aspx");\n    }\n}	0
23977390	23977347	How can I get the file name of currently running process?	foreach (Process in Process.GetProcesses())\n{\n    string filePath = process.Modules[0].FileName;\n    Icon fileIcon = Icon.ExtractAssociatedIcon(filePath);\n\n    ...\n}	0
20743713	20743685	Select Single node using child node containing specific innertext. XMLDocument	string ItemCode="8901786409990 ";\n XmlNode node = doc.SelectSingleNode("/*/b:Product[contains(b:Barcode,'" + Itemcode1 + "')]");	0
1879161	1879152	String comparing in c#	if (string1.Contains(string2)) {\n    //Your code here\n}	0
8103165	8103021	Read file from blob url container	WebClient client = new WebClient();\nstring fileString = client.DownloadString(new uri(http://.....)));	0
18034054	18033981	Get value between a range of two values from percentage	int Range1Min = 5, Range1Max=90, Range1SelectedValue = 40;\n int Range2Min = 6, Range2Max=80;\n decimal range1Percent = (Range1SelectedValue-Range1Min ) / (Range1Max-Range1Min) * 100.0\n decimal range2NewValue = (Range2Max - Range2Min) * range1Percent  / 100 + Range2Min;	0
11425590	11424716	Cannot access asp.net changepassword controls in codebehind	TextBox password = ChangePassword1.Controls[0].FindControl("CurrentPassword") as TextBox;\n  Label passwordLabel = ChangePassword1.Controls[0].FindControl("CurrentPasswordLabel") as Label;	0
8080859	8080716	Fluent NHibernate - Mapping List<decimal> to ordered child table	HasMany(x => x.DecimalList)\n...\n.AsList(x => x.WithColumn("ListPosition")	0
11630894	11630799	Prevent word from opening when opening a document	private void OpenWord(string path)\n{\nApplication word = new Application();\nFileInfo fileInfo = (FileInfo)file;\n\nobject filename = fileInfo.FullName;\nobject confirmConversion = false;\nobject readOnly = true;\nobject visible = false;\nobject skipEncodingDialog = true;\nobject save = false;\n\nword.Visible = false;\n\nDocument srcDoc = word.Documents.Open(ref path, ref confirmConversion, ref readOnly, ref missing,\n    ref missing, ref missing, ref missing, ref missing,\n    ref missing, ref missing, ref missing, ref visible,\n    ref missing, ref missing, ref skipEncodingDialog, ref missing);\n}	0
7123304	7123196	How to check, programatically, if MS Excel exists on a pc?	Type officeType = Type.GetTypeFromProgID("Excel.Application");\nif (officeType == null)\n{\n     //no Excel installed\n}\nelse\n{\n     //Excel installed\n}	0
23500727	23408337	Determine the load context of an assembly	private static bool DoesAssemblyMatchLoad(Assembly assemblyToTest)\n{\n    try\n    {\n        var loadedAssembly = Assembly.Load(assemblyToTest.FullName);\n        return assemblyToTest.CodeBase == loadedAssembly.CodeBase;\n    }\n    catch (FileNotFoundException)\n    {\n        return false;\n    }\n}	0
27863562	27863510	Getting individual string length in an array	int[] GetLengths(string[] array)\n    {\n       int[] structure = new int[array.Length];\n       for(int i = 0;i < array.Length;i++)\n        {\n           int length = array[i].Length;\n           structure[i] = length;\n        }\n        return structure;\n    }	0
13254019	13253671	Reading XML dynamically using LINQ	var testlinq = XElement.Load(sr);   \nvar test = testlinq.Descendants("Alumno")\n                   .Select(x => x.Descendants()\n                                 .ToDictionary(y => y.Name, y => y.Value )\n                   ).ToList();	0
281631	267124	UpdatePanel Slowness in IE	// In your aspx.cs define the server-side method marked with the \n// WebMethod attribute and it must be public static.\n[WebMethod]\npublic static string HelloWorld(string name)\n{\n  return "Hello World - by " + name;\n}\n\n// Call the method via javascript\nPageMethods.HelloWorld("Jimmy", callbackMethod, failMethod);	0
9296199	9295128	How can I share a link from Facebook pages that I admin using Facebook C# SDK?	facebookclient.Post("me/feed",parameters);	0
6153664	6153263	Relationships in Habanero	if (!HasReverseRelationship(relationshipDef)) return;\n\n        string reverseRelationshipName = relationshipDef.ReverseRelationshipName;\n        if (!relatedClassDef.RelationshipDefCol.Contains(reverseRelationshipName))\n        {\n            throw new InvalidXmlDefinitionException\n                (string.Format\n                     ("The relationship '{0}' could not be loaded for because the reverse relationship '{1}' defined for class '{2}' is not defined as a relationship for class '{2}'. Please check your ClassDefs.xml or fix in Firestarter.",\n                      relationshipDef.RelationshipName, reverseRelationshipName, relatedClassDef.ClassNameFull));\n        }\n\n        var reverseRelationshipDef = relatedClassDef.RelationshipDefCol[reverseRelationshipName];	0
11326404	11326284	Regex - is it possible to find overlaping groups?	Regex regexObj = new Regex(@"(?=(\d{4}\s\d{4}\s\d{4}))");\nMatch matchResult = regexObj.Match(subjectString);\nwhile (matchResult.Success) {\n    resultList.Add(matchResult.Groups[1].Value);\n    matchResult = matchResult.NextMatch();\n}	0
31326693	31326451	Replacing Regex matches using lambda expression	string input="abc123def";\nvar output = Regex.Replace(input, @"\d", m=>(m.Value[0]-'0'+ 5).ToString());\nConsole.WriteLine(output);	0
8929562	8919153	How to dynamically create a Func<T> when T is unknown in C#	public TOutput HandleTask<TTaskInput, TOutput>(TTaskInput task)	0
16195632	16195603	Multiline string with added text from variables	string pattern = @"this is a multiline text\nthis is {0}\nthis is {1}\nthis is {2}";\n\nstring result = string.Format(pattern, a1, a2, a3);	0
3656082	3655962	Locking a xml file(located in a server) when the same application(from 2 different computers) is trying to write into it	using (FileStream file = File.Open("c:\\yourpath\\file.xml", FileMode.Create, FileAccess.Write))\n{\n... // Here the file is locked\n}	0
15254644	15254421	Mapping tables using Entity Data Model	public class MyContext : DbContext\n{\n    public DbSet<MyEntity> MyEntities { get; set; }\n    public DbSet<MyCoolEntity> MyCoolEntities { get; set; }\n    /* ... */\n}	0
652072	651948	How to Unit Test an Implementation of IDictionary	void Test_IDictionary_Add(IDictionary a, IDictionary b)\n{\n    string key = "Key1", badKey = 87;\n    int value = 9, badValue = "Horse";\n\n    a.Add(key, value);\n    b.Add(key, value);\n\n    Assert.That(a.Count, Is.EqualTo(b.Count));\n    Assert.That(a.Contains(key), Is.EqualTo(b.Contains(key)));\n    Assert.That(a.Contains(key), Is.EqualTo(a.ContainsKey(key)));\n    Assert.That(a.ContainsKey(key), Is.EqualTo(b.ContainsKey(key)));\n    Assert.That(a.ContainsValue(value), Is.EqualTo(b.ContainsValue(value)));\n    Assert.That(a.Contains(badKey), Is.EqualTo(b.Contains(badKey)));\n    Assert.That(a.ContainsValue(badValue), Is.EqualTo(b.ContainsValue(badValue)));\n    // ... and so on and so forth\n}\n\n[Test]\nvoid MyDictionary_Add()\n{\n    Test_IDictionary_Add(new MyDictionary(), new Hashtable());\n}	0
2337496	2337245	Unit Testing an Event Firing From a Thread	public void CheckFinishedEventFiresTest() {\n        var threadTest = new ThreadRunner();\n        var finished = new ManualResetEvent(false);\n        threadTest.Finished += delegate(object sender, EventArgs e) {\n            finished.Set();\n        };\n        threadTest.StartThreadTest();\n        threadTest.FinishThreadTest();\n        Assert.IsTrue(finished.WaitOne(1000));\n    }	0
14626267	14626171	sql query to grab data from database	SqlCommand cmd = new SqlCommand(@"\nIF NOT EXISTS(SELECT english from dic where english=@e_word)\nInsert INTO dic (english, bangla) VALUES(@e_word,@b_word)\nelse UPDATE dic SET bangla=@b_word WHERE english=@e_word",con);   \n\ncmd.Parameters.AddWithValue("e_word", e_word);   \ncmd.Parameters.AddWithValue("b_word", b_word);\ncmd.ExecuteNonQuery();	0
6717598	6717529	How to convert a color (in RGB mode) to transparent color for PNG using C#?	Bitmap bmp = new Bitmap(_jpegFilePath);\nbmp.MakeTransparent(Color.FromArgb(254,242,211));\nbmp.Save(_pngFilePath);	0
27488704	27488584	How to retain previous graphics in paint event?	// Your painting class. Only contains X and Y but could easily be expanded\n    // to contain color and size info as well as drawing object type.\n    class MyPaintingObject\n    {\n        public int X { get; set; }\n        public int Y { get; set; }\n    }\n\n    // The class-level collection of painting objects to repaint with each invalidate call\n    private List<MyPaintingObject> _paintingObjects = new List<MyPaintingObject>();\n\n    // The UI which adds a new drawing object and calls invalidate\n    private void button1_Click(object sender, EventArgs e)\n    {\n        // Hardcoded values 10 & 15 - replace with user-entered data\n        _paintingObjects.Add(new MyPaintingObject{X=10, Y=15});\n        panel1.Invalidate();\n    }\n\n    private void panel1_Paint(object sender, PaintEventArgs e)\n    {\n        // loop through List<> and paint each object\n        foreach (var mpo in _paintingObjects)\n            e.Graphics.FillEllipse(Brushes.Red, mpo.X, mpo.Y, 20, 20);\n    }	0
23109614	23108915	Threading in C# method with parameter using same variable	// send request\nforeach (string host in hosts)\n    pinger(host);\n\n// async function\nasync void pinger(string host)\n{\n    var ping = new System.Net.NetworkInformation.Ping();\n    bool bResp;\n\n    try\n    {\n        var result = await ping.SendPingAsync(host, 4000);\n        bResp = result.Status == System.Net.NetworkInformation.IPStatus.Success;\n    }\n    catch { bResp = false; }\n\n    txt_result.Text += bResp.ToString() + Environment.NewLine;\n}	0
15509429	15508944	MDS 2012 List members of Product Entity in WCF	foreach(var member in members)\n{\n    Console.WriteLine(member.MemberId.Id);\n    foreach(var attribute in member.Attributes)\n    {\n        Console.WriteLine("Attribute: {0},\tValue: {1}", attribute.Identifier.Name, attribute.Value);\n    }\n}	0
19567712	19567455	Returned JSON string from JavaScriptSerializer	protected internal JsonResult Json(object data, JsonRequestBehavior behavior)\n{\n  return this.Json(data, (string) null, (Encoding) null, behavior);\n}	0
9310343	9309390	how to cast this string list to an object	string myObjectString = "MyObject, SetWidth, int, 10, 0, 1";\n        var info = myObjectString.Split(',');\n\n        string objectName = info[0].Trim();\n        string propertyName = info[1].Trim();\n        string defaultValue = info[3].Trim();\n\n        //find the type\n        Type objectType = Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.Name.EndsWith(objectName)).Single();//might want to redirect to proper assembly\n\n        //create an instance\n        object theObject = Activator.CreateInstance(objectType);\n\n        //set the property\n        PropertyInfo pi = objectType.GetProperty(propertyName);\n        object valueToBeSet = Convert.ChangeType(defaultValue, pi.PropertyType);\n        pi.SetValue(theObject, valueToBeSet, null);\n\n        return theObject;	0
27458354	27458124	When do you use scope without a statement in C#?	int a = 10;\nswitch(a)\n{\n    case 1:\n    {\n        int b = 10;\n        break;\n    }\n\n    case 2:\n    {\n        int b = 10;\n        break;\n    }\n}	0
16656951	16656409	Show button when parent cursor in parent control	if (!this.RectangleToScreen(ClientRectangle).Contains(Cursor.Position))\n                button1.Visible = false;	0
23093753	23092523	Programmatically Build Access Query	var dbe = new DBEngine();\n        var db = dbe.OpenDatabase(@"c:\path\to\your\youraccessdatabase.accdb");\n\n        // loop over tables\n        foreach (TableDef t in db.TableDefs)\n        {\n            // create a querydef\n            var qd = new QueryDef();\n            qd.Name = String.Format("Count for {0}", t.Name);\n            qd.SQL = String.Format("SELECT count(*) FROM {0}", t.Name);\n\n            //append the querydef (it will be parsed!)\n            // might throw if sql is incorrect\n            db.QueryDefs.Append(qd);\n        }\n\n        db.Close();	0
3484719	3484672	How is a stored procedure processed by Sql Server and .Net	INSERT INTO <table> EXEC sp_test	0
3834160	3834106	How do I set a constraint for unique values in a C#.NET dataset table column?	private void AddConstraint(DataTable table)\n{\n    UniqueConstraint uniqueConstraint;\n    // Assuming a column named "UniqueColumn" exists, and \n    // its Unique property is true.\n    uniqueConstraint = new UniqueConstraint(\n        table.Columns["UniqueColumn"]);\n    table.Constraints.Add(uniqueConstraint);\n}	0
2454398	2454390	How to add attributes to an element using LINQ, C#?	xElement.Add(new XAttribute("Foo", "Bar"));	0
24337029	24336950	how to retrieve back values from an ORed flag	bool b = (value & GENERIC_READ) != 0;	0
12209156	12208693	How to display a DataGridViewComboBoxColumn without a combobox?	flat appearance	0
10625494	10625194	How to save a game state?	// somehow convert your game state into a serializable object graph\nvar saveState = gameState.Save();\n\n// use json.net to convert that to a string\nstring json = JsonConvert.SerializeObject(saveState, Formatting.Indented);\n\n// save that string to the file system using whatever is available to you.\nfileSystemService.WriteAllText("Saves\game1.json", json);	0
2059873	2059841	How to use LINQ to filter a list of items in another list and not in a third	var classAListFiltered = from classA in GetClassAList()\nwhere (from classB in classBList select classB.ClassAID).Contains(classA.ID)....	0
27069954	27069793	How to pick one random string from given strings?	List<String[]> quests = new ArrayList<String[]>();\nquests.add(0, new string[]{"You","Are","How","Hello"});\nquests.add(1, new string[]{"Hey","Hi","Why","Yes"});\nquests.add(2, new string[]{"Here","Answer","One","Pick"});\nint x = new Random().nextInt((2 - 0) + 1);\nSystem.out.println(quests.get(x).toString());	0
23933	11288	WPF - Sorting a composite collection	class MyCompositeObject\n{\n    DateTime    CreatedDate;\n    string      SomeAttribute;\n    Object      Obj1;\n{\nclass MyCompositeObjects : List<MyCompositeObject> { }	0
26450339	26450270	How to get buttons with specifications from an array list	var greenbtns = (from m in RightArr where m.BackColor == Color.Green select m).ToList();\nif (greenbtns.Count >= 4) {\n    MessageBox.Show("There are 4 green buttons");\n}	0
32984239	32984115	How do I make a loop that prompts the user to enter data every time they enter an invalid data type?	bool repeat = true;\nvar dblMilesMon = (double)0;\ndo \n{\n    Console.WriteLine("Enter value for Monday : ");\n    var strMilesMon = Console.ReadLine();\n    if (!double.TryParse(strMilesMon, out dblMilesMon)) \n        Console.WriteLine("You entered an invalid number - please enter a numeric value.")          \n    else\n        repeat = false; \n}while (repeat);\n\n//do something with dblMilesMon	0
20998809	20940475	Create SVG using C# by overlaying one SVG icon onto another	var icon = SvgDocument.Open(...);\nvar overlayIcon = SvgDocument.Open(...);\n\nvar overlayed = new SvgDocument();\n\noverlayed.Children.Add(icon);\noverlayed.Children.Add(overlayIcon);\n\noverlayed.Write(...); // saving	0
3655891	3655738	How to get country name	var regex = new System.Text.RegularExpressions.Regex(@"([\w+\s*\.*]+\))");\n        foreach (var item in CultureInfo.GetCultures(CultureTypes.SpecificCultures))\n        {\n            var match = regex.Match(item.DisplayName);\n            string countryName = match.Value.Length == 0 ? "NA" : match.Value.Substring(0, match.Value.Length - 1);\n            Console.WriteLine(countryName);\n        }	0
9335902	9335756	Selecting namespaced XML node attributes with namespace alias instead of URI on an XElement	XNamespace skos = XNamespace.Get("http://www.w3.org/2004/02/skos/core#");\nXNamespace geo = XNamespace.Get("http://www.geonames.org/ontology#");\nXNamespace rdfs = XNamespace.Get("http://www.w3.org/2000/01/rdf-schema#");\n\nXDocument rdf = XDocument.Load(new StringReader(xmlstr));\nforeach(var country in rdf.Descendants(geo + "Country"))\n{\n    Console.WriteLine(\n        country.Attribute(skos + "notation").Value + " "  + \n        country.Attribute(rdfs + "label").Value );\n}	0
22999111	10845820	Check the length of integer variable	public static int IntLength(int i)\n{\n  if (i < 0)\n    throw new ArgumentOutOfRangeException();\n  if (i == 0)\n    return 1;\n  return (int)Math.Floor(Math.Log10(i)) + 1;\n}	0
10640136	10624077	Pass array from javascript to C# in Metro app	public sealed class MyClass {\n    public static string Foo(IEnumerable<string> strings) {\n        // do stuff...\n    }\n}	0
22200131	22199913	Linq - choosing item or a default from a list	ILookup<string, T> _lookup = metadata\n    .Where(z => (z.LanguageCode == DisplayLanguage) || (z.LanguageCode == DefaultLanguage))\n    .OrderBy(x => (x.LanguageCode == DisplayLanguage) ? 0 : 1)\n    .GroupBy(x => x.MetaTag)\n    .ToDictionary(x => x.ToLower(), y => y.First());	0
18785059	18784880	delete all files of specific pattern without deleting the presently using file	var files = dir.GetFiles(temp_file_format).OrderByDescending(f=>f.CreationTime).Skip(1).ToList();\n\nfor( int i=0; i< files.Count; i++)\n   files[i].Delete();	0
3730730	3730630	Send Message to remote PC in local network	NET SEND	0
3477821	3477735	Convert DateTime to string format("yyyyMMdd")	DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", \n                                  CultureInfo.InvariantCulture);\ndt.ToString("yyyyMMdd");	0
27881757	27881069	RangeAttribute with Enum	isValid = Validator.TryValidateObject(this, validationContext, results, true);	0
168221	168169	public variables vs private variables with accessors	public string Name { get; set; }	0
25101585	25101543	How to properly create an EF One-to-Zero-or-One relationship with navigation properties on both ends?	public class Lead {\n    public int Id { get; set; }\n    public virtual Work Work { get; set; }\n}\n\npublic class Work {\n    [Key, ForeignKey("Lead")]\n    public int Id { get; set; }\n    public virtual Lead Lead { get; set; }\n}	0
12845582	12845433	Foreach to calculate multiple arrays	static void Main(string[] args) {\n        Console.WriteLine("Enter your Card Number");\n\n        char[] card = Console.ReadLine().ToCharArray();\n\n        int[] card_m = { 1, 2 };\n\n        for (int idx = 0; idx < card.Length; idx++) {\n            int number = (int) char.GetNumericValue(card[idx]);\n            Console.WriteLine("Converted Number: {0}", number);\n\n            // pull the multiplier from the card_m array\n            int m = card_m[idx % card_m.Length];\n\n            Console.WriteLine("Card Number Multiplier: {0}", m);\n        }\n\n        Console.Read();\n    }	0
15005775	15005248	Passing Custom Object to DLL via Method Call	void Method1()\n    {\n\n\n        var tableVars = new Dictionary<string, dynamic>();\n\n        dynamic sampleObject = new ExpandoObject();\n        sampleObject.Name = "Count";\n        sampleObject.Type = "Int32";\n        sampleObject.Value = "4";\n        sampleObject.Default = "0";\n\n        tableVars.Add("Sample", sampleObject);\n\n        Insert("TableName", tableVars, "Connection");\n\n\n    }\n\n    string Insert(string table, Dictionary<string, dynamic> tableVars, string connection)\n    {\n\n        foreach (var v in tableVars)\n        {\n            Console.Write("Name is: ");\n\n            Console.WriteLine(v.Value.Name);\n\n        }\n\n        return "";\n    }	0
2405352	2405261	How to clip a rectangle from a tiff?	public static Bitmap CropImage(Image source, Rectangle crop) {\n        var bmp = new Bitmap(crop.Width, crop.Height);\n        using (var gr = Graphics.FromImage(bmp)) {\n            gr.DrawImage(source, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);\n        }\n        return bmp;\n    }	0
2428596	2428554	Trying to get all elements after first match using linq	var elementsAfterFirstNonDash = arr.SkipWhile(i => i[0] != '-').Skip(1);	0
2963192	2963176	Problem using Add key value in app.config of c# windows application	& = &amp;	0
6588061	4159149	How do I load an Enterprise Library Configuration from a string	string loggingConfigSetting = GetSetting("LoggingConfiguration");\n\nstring tempConfigPath = Path.GetTempFileName();\nFile.AppendAllText(tempConfigPath, loggingConfigSetting);\n\nFileConfigurationSource configSource = new FileConfigurationSource(tempConfigPath);\nLogWriterFactory logFactory = new LogWriterFactory(configSource);\nwriter = logFactory.Create();	0
34414604	34390405	textbox not updating its value from viewmodel	public class BuddyChatViewModel : INotifyPropertyChanged, BaseViewModel\n{\nprivate string chat;\npublic string Chat\n{\n    get { return chat; }\n    set\n    {\n        chat = value;\n        NotifyPropertyChanged("Chat");\n    }\n}   \n\n\n//INotifyPropertyChanged Members\n\npublic event PropertyChangedEventHandler PropertyChanged;\nprivate void NotifyPropertyChanged(String info)\n{\n    if (PropertyChanged != null)\n    {\n        PropertyChanged(this, new PropertyChangedEventArgs(info));\n    }\n}\n\n}	0
31435941	31435516	C# - Use a referenced library from an included project	string wrapperMethod() {\n    return libraryMethod();\n}	0
24539645	24539606	AutoMapping Array to a List	CreateMap<A,B>()\n    .ForMember(d => d.array, opts => opts.MapFrom(s => s.list.ToArray());	0
14831601	14811820	How to implement dialog architecture in MVVM	public interface IDialogService\n{\n    void    RegisterDialog  (string dialogID, Type type);\n    bool?   ShowDialog      (string dialogID);\n}\npublic class DialogService : IDialogService\n{\n    private IUnityContainer       m_unityContainer;\n    private DialogServiceRegistry m_dialogServiceRegistry;\n\n    public DialogService(IUnityContainer unityContainer)\n    {\n        m_unityContainer = unityContainer;\n        m_dialogServiceRegistry = new DialogServiceRegistry();\n    }\n    public void RegisterDialog(string dialogID, Type type)\n    {\n        m_dialogServiceRegistry.RegisterDialog(dialogID, type);\n    }\n\n    public bool? ShowDialog(string dialogID)\n    {\n        Type type = m_dialogServiceRegistry[dialogID];\n        Window window  = m_unityContainer.Resolve(type) as Window;\n        bool? dialogResult = window.ShowDialog();\n\n        return dialogResult;\n    }	0
20779718	20779668	How to read this type ofJson	public class AnswerObj{\n\n       public string Answer{get;set;}\n\n    }\n\n    public class QuestionObj{\n\n       public string Question {get;set;}\n\n       public int CorrectAnswer {get;set;}\n\n       public List<AnswerObj> Answers {get;set;}\n    }\n\n    public class QuestionsRepository\n    {\n       public List<QuestionObj> Questions {get;set;}\n    }\n\n    //Here is the code for reading your JSON\n    string json = "Your_JSON_COMES_HERE as a string"\n\n    QuestionsRepository questions = JsonConvert.DeserializeObject<QuestionsRepository>(json);	0
7216950	7216883	Linq query - find strings based upon first letter b/w two ranges	var countryAG = from elements in countryList\n                where elements[0] >= 'A' && elements[0] <= 'H'\n                select elements;	0
230742	230736	Can C# generics have a specific base type?	public interface IGenericFace<T> where T : SomeBaseClass	0
9040126	9039872	Using "if" statement to remove min/max user input data	int[] n = { 4, 7, 29, 3, 87 };\nint max = 0;\nint min = int.MaxValue;\ndouble avg = 0;\n\nforeach (int i in n)\n{\n    if (i > max)\n        max = i;\n\n    if (i < min)\n       min = i;\n\n   avg += i;\n}\n\navg = avg / n.Count - 2;	0
32025808	32024990	Find nested repeater on OnCommand event	protected void Page_Load(object sender, EventArgs e)\n    {\n        Rep1.DataSource = new string[] { "Test" };\n        Rep1.DataBind();\n    }\n    protected void Rep1_ItemCreated(object sender, RepeaterItemEventArgs e)\n    {\n        Repeater Rep2 = e.Item.FindControl("Rep2") as Repeater;\n        Rep2.ItemCreated += Rep2_ItemCreated;\n        Rep2.DataSource = new string[] { "Test" };\n        Rep2.DataBind();\n    }\n    protected void Rep2_ItemCreated(object sender, RepeaterItemEventArgs e)\n    {\n        Repeater Rep3 = e.Item.FindControl("Rep3") as Repeater;\n        Rep3.DataSource = new string[] { "Test" };\n        Rep3.DataBind();\n    }\n    protected void LinkButtonSave_OnCommand(object sender, CommandEventArgs e)\n    {\n        LinkButton LinkButtonSave = (LinkButton)sender;\n\n        // Here is the found repeater. The first parent returns the FooterTemplate\n        Repeater Rep3 = LinkButtonSave.Parent.Parent as Repeater;\n    }	0
26815175	26814408	I have a complex puzzle regarding serialization of data	var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n        var ms = new System.IO.MemoryStream();\n        bf.Serialize(ms, DateTime.Now);\n        bf.Serialize(ms, "hello world");\n        var str = Convert.ToBase64String(ms.ToArray());\n\n        ms = new System.IO.MemoryStream(Convert.FromBase64String(str));\n        var obj1 = (DateTime)bf.Deserialize(ms);\n        var obj2 = (string)bf.Deserialize(ms);\n\n        Console.WriteLine(obj1);\n        Console.WriteLine(obj2);	0
4699427	4699375	HTTP verb POST used to access path '/' is not allowed in Facebook app	POST for canvas	0
12753802	12753762	Linq syntax for OrderBy with custom Comparer<T>	IComparer<T>	0
13344603	13344276	String.Format anomaly	var x = 100m;\nvar y = x * 1.00m;\n\nstring s1 = string.Format("{0}", x); // "100"\nstring s2 = string.Format("{0}", y); // "100.00"	0
16370491	16370465	how to show alert box after successful insert using C#	ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);	0
28608631	28608356	File method with removing lines	public static void changeFile(string InputPath,string OutputPath)\n    {\n\n            List<string> OUTPUT = new List<string>();\n            StreamReader sr = new StreamReader(InputPath);\n            while (!sr.EndOfStream)\n            {\n                OUTPUT.Add(sr.ReadLine());\n            }\n            sr.Close();\n            StreamWriter fs = new StreamWriter(OutputPath);\n            string output = "";\n\n            foreach (string line in OUTPUT)\n            {\n                output += line + " ";\n            }\n            fs.WriteLine(output);\n            fs.Close();\n}	0
9918269	9918204	Displaying list of files and subfolders in datagridview?	Directory.GetFiles(@"C:\Documents and Settings\Administrator\Desktop\FILE",\n                   "*",\n                   SearchOption.AllDirectories)	0
10693224	10692850	Remove Duplicate item from list based on condition	var result = items\n    .GroupBy(item => item.Name)\n    .SelectMany(g => g.Count() > 1 ? g.Where(x => x.Price != 500) : g);	0
6913150	6907103	How to create a dynamic 'contains or LIKE' Expression to be used with Linq against OData service	IQueryable<string> source = new List<string>().AsQueryable();\nIQueryable<string> result = from item in source where item.Contains("John") select item;\nConsole.WriteLine(result.Expression.ToString());	0
34489074	34487976	Load scene using canvas button	public void LoadScene2()\n{\n    SceneManager.LoadScene ("Scene2");\n}	0
29866893	29866683	I am trying to add user input from the second form with title, description to my Data array but can't	add_item[1] = new Data(5,"title", "description", new DateTime(2015, 4, 25), "desc2",3);	0
24056391	24056157	how to split this label to get the specific value	String temp = "Last login: Thu Jun 5 08:20:35 2014 from .** /*/*-..****.**///*-****.**.*/****/*/***status Virtual server [...] is UP. *: 337 bananas left ****(s)******: 229 bananas eaten(s) ** *. [* ] ???";\n    String[] arr = temp.Split(new String[]{"*:"}, StringSplitOptions.RemoveEmptyEntries);\n    String numOne = arr[1].Split(new String[]{" "}, StringSplitOptions.RemoveEmptyEntries)[0];\n    String numTwo = arr[2].Split(new String[]{" "}, StringSplitOptions.RemoveEmptyEntries)[0];\n    String tmp = "";	0
29403150	29402911	Storing fields from a database in an array c#	string[] tasks;\n        string sql = "SELECT [Task Name] FROM Tasks";\n        using (OleDbCommand cmd = new OleDbCommand(sql, conn))\n        {\n            using (OleDbDataReader dataReader = cmd.ExecuteReader())\n            {\n                List<object[]> list = new List<object[]>();\n                if (dataReader.HasRows)\n                {\n                    while (dataReader.Read())\n                    {\n                        object[] oarray = new object[dataReader.FieldCount];\n                        list.Add(oarray);\n                        for (int i = 1; i <= dataReader.FieldCount; i++)\n                        {\n                            oarray[i] = dataReader[i];\n                        }\n                    }\n                }\n            }\n        }	0
31440542	31439718	Reading a csv file and storing the data in a 2-D object array	public class PriceAndDate\n{\n    public DateTime Date {get;set;}\n    public Decimal Price {get;set;}\n}\n\nList<PriceAndDate> priceAndDate = new List<PriceAndDate>();	0
32464244	32463844	Open a .rtf file in a RichTextBox from a TreeView populated with .rtf files	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n    TreeNode tn=e.Node;\n    string loc = currentLocation + "\\" + tn.Text+ ".rtf";\n    richTextBox1.LoadFile(loc);\n}	0
5979062	5978928	POST json with  Rest APi using webReuest from WP7	sw.Write(data);	0
12822659	11778349	Launch IOS Bar Code Scanner From Web Link	window.addEventListener("storage", onStorageChanged, false);\nfunction onStorageChanged(e)\n{\n    if(/*check for appropriate key-value*/)\n    {\n         window.Close();       \n    }\n}	0
22691580	22691307	How to return multiple tables with one method?	public DataTable[] MultipleMethod(args)\n{\n    List<DataTable> list = new List<DataTable>();\n\n    // Load first DataTable\n    DataTable dt = ...\n    list.Add(dt);  // Add the DataTable to the list of tables\n\n    // Load second DataTable\n    dt = ...\n    list.Add(dt);  // Add the DataTable to the list of tables\n\n    // Load another DataTable\n    dt = ...\n    list.Add(dt);  // Add the DataTable to the list of tables\n\n    return list.ToArray();  // Return an array of tables (can return the list if that is the return type)\n}	0
28518219	28255815	Selenium and PhantomJS takes 30 seconds to open each link	var phantomJSDriverService = PhantomJSDriverService.CreateDefaultService();\n        IWebDriver browser = new PhantomJSDriver(phantomJSDriverService);\n        browser.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));	0
30027419	30026610	Removing an item from itemsource for UI only	private static readonly string[] exclude =\n    new string[] { "None", "NONE", "Na", "NA" };\n\npublic override object ProvideValue(IServiceProvider serviceProvider)\n{\n    return Enum.GetValues(_enumType).Cast<object>()\n        .Where(e => !exclude.Contains(e.ToString())).ToList();\n}	0
7629899	7520681	Is there a way to get a custom control to display the correct language in the VS Editor when a different language is selected	protected override void OnPaint(PaintEventArgs pevent)\n    {\n        base.OnPaint(pevent);\n        this.Text = CustomGlobalResources.GetItem(this.Tag.ToString());\n    }	0
7458905	7454589	No session bound to the current context	public class SessionFactory\n{\n    protected static ISessionFactory sessionFactory;\n    private static ILog log = LogManager.GetLogger(typeof(SessionFactory));\n\n    //Several functions omitted for brevity\n\n    public static ISession GetCurrentSession()\n    {\n        if(!CurrentSessionContext.HasBind(GetSessionFactory()))\n            CurrentSessionContext.Bind(GetSessionFactory().OpenSession());\n\n        return GetSessionFactory().GetCurrentSession();\n    }\n\n    public static void DisposeCurrentSession()\n    {\n        ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory());\n\n        currentSession.Close();\n        currentSession.Dispose();\n    }\n}	0
7420437	7420381	Dictionary<char, char> to map an alphabet -- with unique keys & values	Shuffle(sequence1)\nShuffle(sequence2)\n\nfor index 0 to 25\n    dictionary add sequence1[index], sequence2[index]	0
148688	148669	Local variables with Delegates	class Foo {\n  public string currentValue; // yes, it is a field\n\n  public void SomeMethod(object sender, EventArgs e) {\n    Response.Write(currentValue);\n  }\n}\n...\npublic Page_Index() {\n  Foo foo = new Foo();\n  foo.currentValue = "This is the FIRST value";\n  this.Load += foo.SomeMethod;\n\n  foo.currentValue = "This is the MODIFIED value";\n}	0
13986433	13984498	Mapping JSON data to model and back in MVC 4	public class Comment\n{\n    [Key]\n    public int CommentID { get; set; }\n    public int ProjectDocID { get; set; }\n    public int UserID { get; set; }\n    public string text { get; set; }\n    public string quote { get; set; }\n    public DateTime DateCreated { get; set; }\n\n    public virtual ICollection<CommentVote> CommentVote { get; set; }\n    public virtual ICollection<CommentReply> CommentReply { get; set; }\n    public ProjectDoc ProjectDoc { get; set; }\n    public virtual User User { get; set; }\n    public List<ranges> ranges { get; set; }\n}\npublic class ranges {\n    public int ID { get; set; }\n    public string start { get; set; }\n    public string end { get; set; }\n    public string startOffset { get; set; }\n    public string endOffset { get; set; }\n\n\n}	0
18508689	18508384	Create List from a String with multiple unnecessary characters	using Newtonsoft.Json.Linq;\n\nstring json = @"\n    {""0"":{""title"":""iPhone""},""1"":{""title"":""iPod""},""2"":{""title"":""iPad""},""length"":3,""prevObject"":{""0"":{},""1"":{},""2"":{},""length"":3,""prevObject"":{""0"":{},""length"":1,""context"":{""location"":{},""jQuery18308480830912211994"":1},""selector"":""#mycart""},""context"":{""location"":{},""jQuery18308480830912211994"":1},""selector"":""#mycart li""},""context"":{""location"":{},""jQuery18308480830912211994"":1}}\n";\n\nJObject obj = JObject.Parse(json);\n\nint length = (int)obj.GetValue("length");\nvar titles = new List<string>();\nfor (int i = 0; i < length; i++)\n{\n    JObject item = (JObject) obj.GetValue(i.ToString());\n    titles.Add((string) item.GetValue("title"));\n}	0
6612317	6612068	Delete database table with column of datatype Image	[Column(Storage="_myColumn", DbType="VarBinary", UpdateCheck=UpdateCheck.Never)]\npublic string myColumn\n{\n...\n}	0
1394075	1393982	Strip everything but text from html	static void Main()\n{\n    HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml(@"&#xD;&#xA;      <p>&#xD;&#xA;      <strong>text text. more text</strong>&#xD;&#xA;      <a href=""http://blabla>blabla</a> even more text...");\n    string s = doc.DocumentNode.InnerText;\n    // s is: &#xD;&#xA;      &#xD;&#xA;      text text. more text&#xD;&#xA;     \n}	0
24484104	24483866	Retrieving a image from database to asp.net page using c#	public ActionResult GetAvatar(int id) {\n    using (var dbContainer = new MainDBContainer()) {\n        return File(dbContainer.UserSet.First(p => p.Id == id).Image.Image,"image/png");\n    }\n}	0
20890636	20868181	Linq join on multiple tables with null values	var dset = from s in db.ZIPCODEs\n           join u in db.COUNTRies on s.COUNTRYCODE equals u.COUNTRYCODE into ulist from u in ulist.DefaultIfEmpty()\n           join w in db.REGIONS on s.REGIONCODE equals w.REGIONCODE into wlist from w in wlist.DefaultIfEmpty()      \n           join v in db.STATES on s.STATECODE equals v.STATECODE into vlist from v in vlist.DefaultIfEmpty()                          \n           select new ZIPCODEListViewModel\n          {\n            ID = s.ID,\n            ZIPCODE1 = s.ZIPCODE1,\n            DESCRIPTION = s.DESCRIPTION,\n            STATECODE = s.STATECODE,\n            COUNTRYCODE = s.COUNTRYCODE,\n            REGIONCODE = s.REGIONCODE,\n            COUNTRYNAME =u.DESCRIPTION,\n            STATENAME = v.DESCRIPTION,\n            REGIONNAME = w.DESCRIPTION\n        };	0
19168561	18286148	Aforge, converting pixel data to UnmanagedImage	unsafe\n    {\n        byte* dst = (byte*)data.Scan0.ToPointer();\n\n\n        for (int y = 0; y < Height; y++)\n        {\n            for (int x = 0; x < Width; x++, src++, dst += pixelSize)\n            {\n                dst[RGB.A] = input[src].A;\n                dst[RGB.R] = input[src].R;\n                dst[RGB.G] = input[src].G;\n                dst[RGB.B] = input[src].B;\n            }\n\n            dst += offset;\n        }\n    }	0
1525141	1525096	Translating a MethodInfo object obtained from an interface type, to the corresponding MethodInfo object on an implementing type in C#?	Type.GetInterfaceMap	0
20613677	20611632	How can I get ASP Application variables with C# HttpRequest?	if session("isLoggedInOrSomething") = true then\n    if request.form("act") = "gimmeAppVar" then\n        response.write application( request.form("requestedAppVar") )\n    end if\nend if	0
27983774	27648573	Download file from a shared folder on network	\\\\server\\somefolder\\somefolder\\file.txt	0
19541079	19541046	Best way to do a multithread foreach loop	Parallel.ForEach(GetAllUsers(), user=>\n{\n  SendMail(user.Email);\n});	0
15811680	15811626	How to represent comma's in string?	value = 1234567890;\nConsole.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture)); \n// Displays 1,234,567,890	0
2911492	2911186	How to add items to a list in Rhino Mocks	myMock.Stub(methodInv => methodInv.MyMethod(new List<Foo>()).IgnoreArguments()\n    .WhenCalled(invocation => (invocation.Arguments[0] as IList<foo>).Add(new Foo());	0
5874254	5874219	Prevent failed Insert from claiming next Identity value	CREATE TABLE test(id INT IDENTITY, bla INT)\n\nINSERT test VALUES(1)\nINSERT test VALUES('b') --fails\n\n\nDBCC CHECKIDENT(test,RESEED,1) --RESEED table\nINSERT test VALUES(1)\nSELECT * FROM test\n\nDROP TABLE test	0
16544523	16543871	Skip validation with controlbox[X] of winform?	protected override void WndProc(ref Message m) {\n        // Intercept WM_SYSCOMMAND, SC_CLOSE\n        if (m.Msg == 0x112 && (m.WParam.ToInt32() & 0xfff0) == 0xf060) this.AutoValidate = AutoValidate.Disable;\n        base.WndProc(ref m);\n    }	0
12656341	12655738	c# opening a compress file into a program	static class Program\n{\n    [STAThread]\n    static void Main(string[] args)\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Form1 form = new Form1(args);\n        Application.Run(form);\n    }\n}	0
31675107	31674085	Linq to populate values of a class	Func<byte[], IEnumerable<Cell>, Row> create =\n    (k, cs) =>\n    {\n        CellSet.Row row = new CellSet.Row { key = k };\n        row.values.AddRange(cs);\n        return row;\n    };\n\nvar result =\n(\n    from a in firstrow\n    let valuesset = a.Split(',')\n    from l in valuesset\n    select create(\n        Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()),\n        new [] { value12 })\n).ToList();	0
9177377	2892910	Problems with Json Serialize Dictionary<Enum, Int32>	Dictionary<TestEnum, Int32> data = new Dictionary<TestEnum, Int32>();\n\ndata.Add(TestEnum.A, 1);\ndata.Add(TestEnum.B, 2);\ndata.Add(TestEnum.C, 3);\n\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nDictionary<string, Int32> dataToSerialize = data.Keys.ToDictionary(p => p.ToString(), p => data[p]);\nstring dataSerialized = serializer.Serialize(dataToSerialize);	0
21301702	21298074	how to string.format multiple column names with X length of column in C# SQL query	var query = "SELECT " +string.Join(",", requestedColumns) + " WHERE id=@id LIMIT 1";	0
5987089	5987051	List View Sliding Window	IEnumerable<double> GetWindow(List<double> lst, int index, int windowSize) {\n    if(index >= lst.Length){\n        // Throw proper exception\n    }\n    return lst.Skip(index-windowSize).Take(Math.Min(index,windowSize));\n}	0
22381533	22381174	How to redirect user after login using role management in asp.net?	if(string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))\n{\n    FormsAuthentication.SetAuthCookie(tbUserName.Text, false);\n\n    if (HttpContext.Current.User.IsInRole(ADMIN))\n    {\n        Response.Redirect(ADMIN_URL, true);\n    }\n    else if (HttpContext.Current.User.IsInRole(USER))\n    {\n        Response.Redirect(USER_URL, true);\n    }\n    else if (HttpContext.Current.User.IsInRole(DEALER))\n    {\n        Response.Redirect(DEALER_URL, true);\n    }\n    else if (HttpContext.Current.User.IsInRole(OPERATOR))\n    {\n        Response.Redirect(OPERATOR_URL, true);\n    }\n    else\n    {\n        Response.Redirect(SOME_DEFAULT_URL, true);\n    }\n}\nelse\n{\n    FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);\n}	0
7409297	7409256	Can one force a custom compiler error in c#?	if (...)\n    thingy.BeginTransaction();\nthingy.NonTransactionalMethod();	0
12227545	12227520	WebBrowser Control c#: finding particular link and "clicking" it programmatically?	if ((link.InnerText != null) && (link.InnerText.Equals("My Assigned")) )\n        link.InvokeMember("Click");	0
1038531	1038431	How to clean HTML tags using C#	HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml(html);\n    string s = doc.DocumentNode.SelectSingleNode("//body").InnerText;	0
17636396	17636266	C# MySQL retrieving a value from a column matching another	MySqlConnection sqlConn = new MySqlConnection();\n    MySqlCommand sqlCmd = new MySqlCommand();\n    string sSql = "SELECT id FROM caregiverdatabse WHERE name Like '%" + caregiverNameDisp.Text + "%'";\n    sqlConn.ConnectionString = "Server=" + server + ";" + "Port=" + port + ";" + "Database=" + database + ";" + "Uid=" + uid + ";" + "Password=" + password + ";";\n    sqlCmd.CommandText = sSql;\n    sqlCmd.CommandType = CommandType.Text;\n    sqlConn.Open();\n    sqlCmd.Connection = sqlConn;\n    MySqlDataReader reader = sqlCmd.ExecuteReader();\n    List<string> results = new List<string>();\n\n    while (reader.Read())\n    {\n\n        results.Add((reader["id"].ToString());\n\n    }\n\n    reader.Close();\n    sqlConn.Close();	0
6654520	6654388	Adding textboxes to a panel without space between them	flowLayoutPanel1.Controls.Add(mytextbox1);	0
34005016	34004913	Delete Folder If Only Contains Text File	public static void processDirectory(string startLocation)\n{\n    foreach (var directory in Directory.GetDirectories(startLocation))\n    {\n        processDirectory(directory);\n        var aFiles = Directory.GetFiles(directory);\n        var noFiles = aFiles.Length == 0 || (aFiles.Length == 1 && aFiles.Count(file => Path.GetExtension(file) == ".txt") == 1);\n        if (noFiles && Directory.GetDirectories(directory).Length == 0)\n        {\n            Directory.Delete(directory, true);\n        }\n    }           \n}	0
2343132	2343086	How to implement string(xml) to memorystream to file in C#?	string xml;\n\nMemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(xml));\n\nms.DuStuf();\n\nfileStream.Write(ms.GetBuffer(), 0, xml.Length);	0
1695366	1695360	Getting the value of an int array at an index in c#	locX[Ind]	0
19015482	18989773	WCF Client for web service with WS-Security, signed headers, authentication tokens and encryption of body	var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10);\n            sec.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());\n            sec.MessageSecurityVersion =\n                MessageSecurityVersion.\n                    WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;\n            sec.IncludeTimestamp = false;\n            sec.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;\n\n            b.Elements.Add(sec);\n            b.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));\n            b.Elements.Add(new HttpsTransportBindingElement());	0
20465026	20464882	How to Display only DatePart in Wpf DateTimepicker?	{Binding DateTimeProperty, StringFormat={}{0:dd/MM/yyyy}"	0
25580726	25580630	Infinite while loop in Windows Service	private const string Query = "SELECT * FROM 'reportsetting` order by SendingTime;"\n\nprotected override void OnStart(string[] args)\n{\n    _timer = new Timer(40 * 1000); // every 40 seconds\n    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n    _timer.Start(); // <- important\n}\n\nprivate void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n    MySqlConnection con = new MySqlConnection(conn);\n    MySqlCommand comm = new MySqlCommand(Query, con);\n    con.Open();\n    MySqlDataReader dr = comm.ExecuteReader();\n    while (dr.Read())\n    {\n\n        time = dr["SendingTime"].ToString();\n\n        if ((str = DateTime.Now.ToString("HH:mm")).Equals(time))\n        {\n\n            //Execute Function and send reports based on the data from the database.\n\n            Thread thread = new Thread(sendReports);\n            thread.Start();\n        }\n    }\n}	0
27487367	27486962	How to get Excel XValue of a Chart in C#	var chart = chartObj.Chart as Excel.Chart;\nvar s = chart.SeriesCollection(1) as Excel.Series;\n\nvar xValues = (s.XValues as object) as Array;\n\nforeach (var xVal in xValues)\n{\n    MessageBox.Show(xVal.ToString());\n}	0
28029818	22426715	How can I return differences between versions and access properties that changed?	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(DownloadedPageContent);\n\nHtmlNodeCollection n = doc.DocumentNode.SelectNodes("//tr[@id='vv" + VersionId + FieldName +"']/td");\n\nString value = n[1].InnerText.Trim();	0
21290177	21289812	List of public Properties and their values	class Program\n{\n    static void Main(string[] args)\n    {\n        var myClass = new MyClass()\n        {\n            Number = 1,\n            String = "test"\n        };\n\n        var properties = myClass.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n        foreach (var property in properties)\n        {\n            var columnName = property.Name;\n            var value = myClass.GetType().GetProperty(columnName).GetValue(myClass, null);\n\n            Console.WriteLine(string.Format("{0} - {1}", columnName, value));\n        }\n        Console.ReadKey();\n    }\n}\n\npublic class MyClass\n{\n    public int Number { get; set; }\n    public string String { get; set; }\n}	0
24208045	24207950	Grab the part after '\' using a regex	userName.Substring(userName.IndexOf('\\')+1)	0
1685861	1685821	How to find out if an MSI I just installed requested a windows reboot?	HKLM\System\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations	0
15843618	15842892	AspNet Membership - Centralizing Logins	// ValidateUser method doesn't take any additional parameter\npublic bool ValidateUser(string username, string password)	0
18757750	18735476	How to dynamically add buttons to ListBox - WFP - C#	private Boolean addNewListBox(ListBox targetElement, int indexOfElement)\n    {\n        ListBox elementListBox = new ListBox();\n\n        elementListBox.Name = "elementListBox" + indexOfElement;\n        elementListBox.VerticalAlignment = VerticalAlignment.Top;\n\n        targetElement.Items.Remove(addFloor);\n        targetElement.Items.Add(elementListBox);\n        elementListBox.Items.Add(putElements("TEST", index));\n        targetElement.Items.Add(addFloor);\n        return true;\n    }\npublic object putElements(string nameOfElement, int indexOfElement)\n    {\n        if (nameOfElement.Contains("TEST"))\n        {\n            Button floorButton = new Button();\n\n            floorButton.Name = "floorButton" + indexOfElement;\n            floorButton.Content = "floorButton" + indexOfElement;\n            floorButton.Height = 60;\n            floorButton.Width = 87;\n            floorButton.Margin = new Thickness(0, 2, 0, 0);\n\n            return floorButton;\n        }\n    }	0
24459889	24441119	Asp.Net ListView Grouping - How to order data inside groups?	DataSource='<%# ((Customers)Container.DataItem).Orders.OrderBy(p => p.OrderName) %>'	0
4454005	4450571	Using ValidationGroup with Sharepoint EditorPart	string _errorText;\n\npublic override bool ApplyChanges()\n{\n\n\n if (System.Text.RegularExpressions.Regex.IsMatch(validTb.Text, myRegExp))\n            {\n        //write you code here in case of valid input\n                return true;\n            }\n            else\n            {\n        _errorMessage = "Not A valid String";\n                return false; \n            }\n\n}\n\nprotected override OnPreRender(EventArgs e)\n{\n  if (!string.IsNullOrEmpty(_errorText))\n  {\n    this.Zone.ErrorText =  _errorText;\n  }      \n  base.OnPreRender(e);\n}	0
23353360	23353285	How do I create a dynamic selection on a linq query with an Expression	(f, l) => \n{ \n    var compiled = l.IdToMapOn.Compile();\n    return f.RecordCollection.Select(compiled.Invoke);\n}	0
228597	228559	how to uppercase date and month first letter of ToLongDateString() result in es-mx Culture?	string[] newNames = { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" };\n        Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames;	0
10279327	10279297	Creating a file system path branch in C#	System.IO.Directory.CreateDirectory(@"C:\A\B\C\D\")	0
3235446	3235403	How to replace upper case with lower case using regex?	String s = "NotImplementedException";\ns = Regex.Replace(s, @"\B[A-Z]", m => " " + m.ToString().ToLower());\n// s = "Not implemented exception"	0
7341491	7341351	Get the current index of a ComboBox?	private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)\n{\n    currentMyComboBoxIndex = myComboBox.SelectedIndex;\n}	0
14134321	14131063	How to Update an Existing Data Structure When We need to Maintain Legacy Support?	[Serializable]\npublic class Data\n{\n    public string Field1 {get; set;}\n}\n\n[Serializable]\npublic class Data2\n{\n    public Data2() { _version1 = new Data();}\n\n    [NonSerialized]\n    private Data _version1; \n    public string Field1 \n    { \n        get { return _version1.Field1;} \n        set { _version1.Field1 = value;}\n    }\n    public int Field2 {get; set;}\n}\n\n[Serializable]\npublic class Data3\n{\n    public Data3() { _version2 = new Data2();}\n\n    [NonSerialized]\n    private Data2 _version2;\n    public string Field1 \n    { \n        get { return _version2.Field1;} \n        set { _version2.Field1 = value;}\n    }\n    public int Field2 \n    { \n        get { return _version2.Field2;} \n        set { _version2.Field2 = value;}\n    }\n    public double Field3 {get; set;}    \n}	0
4352629	4352590	create a transaction for MS Access in c#	using (var transaction = cn.BeginTransaction()) {\n  //Do Stuff here using the connection\n  transaction.Commit();\n}	0
7298249	7298210	How to return a new object of a concrete type using LINQ/Linq2E?	var tempAccounts = from i in db.IRSBASEFLs\n                   join vr in db.VSARules on i.VSACode equals vr.VSACode into rules\n                   from rule in rules.DefaultIfEmpty()\n                   select new { VarI = i, Rule = rule, Liquidity = RuleType.Liquidity};\n\nvar accounts = tempAccounts.Select(x => new ImporterAccount(x.VarI, x.rule, x.Liquidity));	0
23880063	23879975	Checkboxlist multiple value select and display in gridview in asp.net	SqlCommand cmd = new SqlCommand(str, con);\ncommand.Parameters.Add(new SqlParameter("@textInput", 0));\n\n for (int d = 0; d < YrStrList.Count; d++)\n    {\n string text;\n        text = YrStrList[d];\ncommand.Parameters["@textInput"].Value = text ;\n...\n}	0
3831210	3830838	Silverlight: Give focus to a parent ListBox item when clicking a child button	ManageImageList.SelectedItem = ((Button)sender).DataContext;	0
26779350	26778892	Populating combobox from app settings	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    textBox3.Text = appStgs[comboBox1.Text];\n}	0
20007312	20007163	Wait a few microseconds and update the screen	Task.StartNew(BackgroundLabelToggle, Label[] {  lblIF, lblID });\n\nprivate static void BackgroundLabelToggle(Label[] labels)\n{\n   var a = labels[0];\n   var b = labels[1];\n\n   a.Invoke(LabelUpdater, a); //to bold\n   Thread.Sleep(500);\n   a.Invoke(LabelUpdater, a); //to regular again\n   b.Invoke(LabelUpdater, b); //to bold\n   Thread.Sleep(500);\n   b.Invoke(LabelUpdater, b); //to regular again\n}	0
9725261	9724953	How to search a tree for a specific node class	List<Node> nodes = new List<Node>();\nnodes.add( rootnode )\n\nfor (int i=0; i < nodes.count; i++)\n{\n\nNode currentNode = nodes[i];\n\n//do the processing to check here\n\nnodes.add(currentNode.children) //not 100% sure how to do this, but you get the idea\n\n}	0
30219648	30219059	How to save values in array with for each?	List<List<object>> results = new List<List<object>>();\n            liveMatches.ForEach(match => results.Add( new object[] {\n               match.Id.ToString(),\n               match.Name,\n               match.Country,\n               match.Historical_Data,\n               match.Fixtures,\n               match.Livescore,\n               match.NumberOfMatches,\n               match.LatestMatchResult\n            }));	0
22991682	22980684	How can I parse a date string containing "17th" or similar suffixes?	Dim formats() As String = {"dd MMMM yyyy", "dd\s\t MMMM yyyy", "dd\t\h MMMM yyyy"}\n\n    d = DateTime.ParseExact(s, formats, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)	0
21714334	21710296	MEF with extra DLLs	AppDomain.AssemblyResolve	0
33869728	33834764	How to convert ticks from java to DateTime c# with time zone	var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1448013624577 / 1000d);\n\nvar dof = new DateTimeOffset(dt, new TimeSpan(0));\n\nvar dtGmt = dof.ToLocalTime().DateTime;	0
6171223	6168799	Is there a way to access the columns in a Dapper FastExpando via string or index?	var sql = "select 1 A, 'two' B";\nvar row = (IDictionary<string, object>)connection.Query(sql).First();\nrow["A"].IsEqualTo(1);\nrow["B"].IsEqualTo("two");	0
31615521	31615492	EF Data annotations Regular expression	[RegularExpression(@"^\d{5}-[a-zA-Z]\d$")]	0
32366434	32366227	RegEx validation for monetary value in c#	var culture = CultureInfo.CreateSpecificCulture("en-US");\ndecimal currency;\nif (Decimal.TryParse(textBox1.text, NumberStyles.Currency, culture, out currency))\n{\n   // Its a valid currency value\n}\nelse {\n  // NOt a valid currency.\n  MessageBox.Show("Please enter a valid currency.");\n}	0
10439027	10439001	Reading UInt16 numbers only binary file	byte[] data;\nint size;\nusing (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))\n{\n    size = (int) stream.Length;\n    data = new byte[size];\n    stream.Read(data, 0, size);\n}\n\nuint[] uintData = new unit[size / 2];\nusing (var memoryStream = new MemoryStream(data))\nusing (var reader = new BinaryReader(memoryStream))\n    for (int i = 0; i < size / 2; i++)\n        uintData[i] = reader.ReadUInt16();\n\n// Done.	0
5705161	5704887	Collating a Collection from Multiple Unknown Objects	public static IEnumerable<Page> GetDescendantsAndSelf(this IPages root)\n{\n  if(root == null)\n    yield break;  // the Page doesn't implement IPages\n  if(root is Page)  // the IPages is actually a Page\n    yield return root as Page;\n  // go through each child\n  // call this method recursively and return the result\n  foreach(var child in root.Pages)\n    foreach(var page in child.GetDescendantsAndSelf())\n      yield return page;\n}	0
16742124	16741953	Sendind mail to a database list	Sqldatareader rdr = sqlcommand_variable.ExecuteReader();\nWhile (rdr.read()) {\n    mail.To.Add(new MailAddress(rdr['firstname'] + "." + rdr['lastname'] + "@domain.com"));\n}	0
25711597	25711456	atomic operations on a file from different processes	const int MAX_RETRY = 50;\nconst int DELAY_MS = 200;\nbool Success = false;\nint Retry = 0;\n\n// Will return an existing mutex if one with the same name already exists\nMutex mutex = new Mutex(false, "MutexName"); \nmutex.WaitOne();\n\ntry\n{\n    while (!Success && Retry < MAX_RETRY)\n    {\n        using (StreamWriter Wr = new StreamWriter(ConfPath))\n        {\n            Wr.WriteLine("My content");\n        }\n        Success = true;\n    }\n}\ncatch (IOException)\n{\n  Thread.Sleep(DELAY_MS);\n  Retry++;\n}\nfinally\n{\n    mutex.ReleaseMutex();\n}	0
33198914	33198805	datagridview cellvaluedchanged event reuse it in other datagridview	dgvPrelimLec.CellValueChanged += dgvPrelim_CellValueChanged;\ndgvMidterm.CellValueChanged += dgvPrelim_CellValueChanged;\ndgvPrefinal .CellValueChanged += dgvPrelim_CellValueChanged;\ndgvFinal.CellValueChanged += dgvPrelim_CellValueChanged;\n\n\n\nprivate void dgvPrelim_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n    {\n        DataGridView dvg = (DataGridView)sender;\n\n        .....\n    }	0
784540	784533	Reverse that Math function	Func_4()	0
13424327	13389516	Tweetsharp: Retrieve list of tweets from a specific user	var service = new TwitterService(ConsumerKey, ConsumerSecret);\nservice.AuthenticateWith(AccessToken, AccessTokenSecret);\nvar currentTweets = service.ListTweetsOnSpecifiedUserTimeline(screenName:"screen name", page:1, count:100);	0
12324888	12317391	How to force BundleCollection to flush cached script bundles in MVC4	Context.Cache["System.Web.Optimization.Bundle:~/bundles/jquery"]	0
21088059	21087690	Updating data in to a Excel sheet using c#	Provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\abc1.xlsx';Extended Properties="Excel 12.0 Xml;HDR=YES";	0
13072596	13070841	How to get specific text value from a textbox based upon the mouse position	private void txtHoverWord_MouseMove(object sender, MouseEventArgs e)\n{\n    if (!(sender is TextBox)) return;\n    var targetTextBox = sender as TextBox;\n    if(targetTextBox.TextLength < 1) return;\n\n    var currentTextIndex = targetTextBox.GetCharIndexFromPosition(e.Location);\n\n    var wordRegex = new Regex(@"(\w+)");\n    var words = wordRegex.Matches(targetTextBox.Text);\n    if(words.Count < 1) return;\n\n    var currentWord = string.Empty;\n    for (var i = words.Count - 1; i >= 0; i--)\n    {\n        if (words[i].Index <= currentTextIndex)\n        {\n            currentWord = words[i].Value;\n            break;\n        }\n    }\n    if(currentWord == string.Empty) return;\n    toolTip.SetToolTip(targetTextBox, currentWord);\n}	0
11734541	11646619	C#: A function that will auto adjust fonts base on the control size at runtime?	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        label1.AutoSize = false;\n        label1.Size = new Size(100, 60);\n        label1.Text = "Autosize this";\n        label1.Anchor = AnchorStyles.Left | AnchorStyles.Right;\n        label1.Resize += new EventHandler(label1_Resize);\n    }\n\n    void label1_Resize(object sender, EventArgs e) {\n        using (var gr = label1.CreateGraphics()) {\n            Font font = label1.Font;\n            for (int size = (int)(label1.Height * 72 / gr.DpiY); size >= 8; --size) {\n                font = new Font(label1.Font.FontFamily, size, label1.Font.Style);\n                if (TextRenderer.MeasureText(label1.Text, font).Width <= label1.ClientSize.Width) break;\n            }\n            label1.Font = font;\n        }\n    }\n\n    protected override void OnLoad(EventArgs e) {\n        label1_Resize(this, EventArgs.Empty);\n        base.OnLoad(e);\n    }\n}	0
2056707	2056620	How to Convert MonthCalendar to Bitmap in Windows Forms?	Bitmap bmp = new Bitmap(monthCalendar1.Width, monthCalendar1.Height);\n  Rectangle rc = new Rectangle(Point.Empty, bmp.Size);\n  monthCalendar1.DrawToBitmap(bmp, rc);	0
12767272	12766100	Neo4jClient get all nodes of a specific type connected to root node	var results = new CypherFluentQuery(_client)\n           .Start("n", _client.RootNode)\n           .Match(string.Format("(n)-[:{0}]-(x)", UserBelongsTo.TypeKey))\n           .Return<Node<User>>("x")\n           .Results;	0
14155728	14143683	Disable WPF buttons during longer running process, the MVVM way	//Declare a new BackgroundWorker\n            BackgroundWorker worker = new BackgroundWorker();\n            worker.DoWork += (o, ea) =>\n            {\n                try\n                {\n                    // Call your device\n\n                    // If ou need to interact with the main thread\n                   Application.Current.Dispatcher.Invoke(new Action(() => //your action));\n                }\n                catch (Exception exp)\n                {\n                }\n            };\n\n            //This event is raise on DoWork complete\n            worker.RunWorkerCompleted += (o, ea) =>\n            {\n                //Work to do after the long process\n                disableGui = false;\n            };\n\n            disableGui = true;\n            //Launch you worker\n            worker.RunWorkerAsync();	0
7564924	7564906	Convert double to fraction as string in C#	using System.IO;\nusing System;\nusing Mehroz;\n\nclass Program\n{\n    static void Main()\n    {\n        double d = .5;\n        string str = new Fraction(d).ToString();\n\n        Console.WriteLine(str);\n    }\n}	0
18560793	18560745	C# Object initializer without default constructor	Foo f = new Foo { Data = 10 };  // What you want (object initializer syntax)\nFoo f = new Foo ( Data : 10 );  // What you can get (constructor syntax)	0
24055887	24055734	Passing routed value to View from Action	return RedirectToAction("List", new { Id = id});	0
3817526	3817477	simultaneous read-write a file in C#	string test = "foo.txt";\n\nvar oStream = new FileStream(test, FileMode.Append, FileAccess.Write, FileShare.Read); \nvar iStream = new FileStream(test, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); \n\nvar sw = new System.IO.StreamWriter(oStream);\nvar sr = new System.IO.StreamReader(iStream); \nvar res = sr.ReadLine(); \nres = sr.ReadLine();\nsw.WriteLine("g"); \nsw.Flush(); \nres = sr.ReadLine();\nres = sr.ReadLine();\nsw.WriteLine("h"); sw.Flush();\nsw.WriteLine("i"); sw.Flush(); \nsw.WriteLine("j"); sw.Flush(); \nsw.WriteLine("k"); sw.Flush(); \nres = sr.ReadLine(); \nres = sr.ReadLine(); \nres = sr.ReadLine();\nres = sr.ReadLine();\nres = sr.ReadLine();\nres = sr.ReadLine();	0
27183898	27183846	Remove selected item from a list	if(listBox.SelectedIndex >= 0 && listBox.SelectedIndex < _List.Count)\n    _List.Items.RemoveAt(listBox.SelectedIndex);	0
19449815	19449752	How to select all columns plus a custom one from table by using EF LINQ?	var initme = (from c in Repo.T_Users\n                          orderby c.BE_Name\n\n                          select new\n            {\n                 test =  "abc",\n                 c1 = c.col_1, \n                 c2 = c.col_2,\n                 ... \n            }	0
24057764	24057601	Casting a Generic Type in implemented abstract class	public abstract class TestAbstractClass<T>\n{\n    protected virtual void Method(ref IQueryable<T> query)\n    {\n    }\n}\n\nclass TestA : TestAbstractClass<Person>\n{\n    protected override void Method(ref IQueryable<Person> query)\n    {\n        var q = query.OrderBy(p => p.Forename);\n    }\n}	0
5131017	5130937	How to bind to page property in silverlight?	this.DataContext = this;	0
20292511	20292479	String 'Input string was not in a correct format' exception on JSON string	string.Format("{ a: {0} }", 2); // throws exception\nstring.Format("{{ a: {0} }}", 2); // returns the string "{ a: 2 }"	0
29853311	29850634	Trying to move an object in a matrix using line drawing algorithm	// assume dx>0, dy>0\nint linearMod28 = (dx + 3*dy) % 28; // 0 through 27\nint pseudorandomMod29 = (1 << linearMod28) % 29; // 1 through 28\ndouble threshold = pseudorandomMod29/29.0; // 1/29 through 28/29\nif (dx/(double)(dx+dy) < threshold)\n    // take a step in the x direction\nelse\n    // take a step in the y direction	0
22835724	22835611	how to validate with minor fixes only	public string ValidateInputString(string input)\n{\n   // Your Logic Here\n   return responseString;\n}	0
12919750	12919539	Finding a Path through a Multidimensional Array	[Flags]\npublic enum TileDescription\n{ \n    Walkable,\n    Trap,\n    Altar,\n    Door\n}	0
12059058	12054918	How to pan Image inside PictureBox	private Point startingPoint = Point.Empty;\nprivate Point movingPoint = Point.Empty;\nprivate bool panning = false;\n\nvoid pictureBox1_MouseDown(object sender, MouseEventArgs e) {\n  panning = true;\n  startingPoint = new Point(e.Location.X - movingPoint.X,\n                            e.Location.Y - movingPoint.Y);\n}\n\nvoid pictureBox1_MouseUp(object sender, MouseEventArgs e) {\n  panning = false;\n}\n\nvoid pictureBox1_MouseMove(object sender, MouseEventArgs e) {\n  if (panning) {\n    movingPoint = new Point(e.Location.X - startingPoint.X, \n                            e.Location.Y - startingPoint.Y);\n    pictureBox1.Invalidate();\n  }\n}\n\nvoid pictureBox1_Paint(object sender, PaintEventArgs e) {\n  e.Graphics.Clear(Color.White);\n  e.Graphics.DrawImage(Image, movingPoint);\n}	0
617433	617424	How to find the top several values from an array?	proc top_k (array<n>, heap<k>)\nheap <- array<1..k-1>\nfor each (array<k..n-1>) \n  if array[i] > heap.min\n     heap.erase(heap.min)\n     heap.insert(array[i])\n  end if\nend for	0
11706875	11706830	Is there a more efficient alternative to the switch statement for variables that rarely change in gameloops	var choices = new Dictionary<ChoiceType, Func<ChoiceResult> > (); \n...\n\npublic ChoiceResult HereWasSwitch(ChoiceType myChoice)\n{\n  return choices[myChoice]();\n}	0
5357168	4612255	Regarding IE9 WebBrowser control	Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]\n"contoso.exe"=dword:00002328	0
9464692	9464359	Add strings to listbox in WPF using C# in a thread	public void ProcessFile(string path)\n{\n    myListBox.Items.Add(path);\n    myListBox.ScrollIntoView(myListBox.Items[myListBox.Items.Count-1]);\n    Dispatcher.Invoke(new Action(delegate { }), DispatcherPriority.Background);\n}	0
5143314	5140569	Repeat header row after each row dynamically	protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        GridViewRow row = new GridViewRow(e.Row.RowIndex, 0, DataControlRowType.Header, DataControlRowState.Normal);\n\n        TableCell cell = new TableCell();\n        cell.Controls.Add(new Label { Text = "Header" }); //as needed\n\n        row.Cells.Add(cell);\n\n        Table tbl = (e.Row.Parent as Table);\n\n        tbl.Controls.AddAt(e.Row.RowIndex * 2 + 1, row);            \n    }\n}	0
11032569	11032399	How to get CultureInfo from client machine?	Thread.CurrentThread.CurrentCulture = new CultureInfo(Request.UserLanguages[1]);	0
30693024	30692713	Transferring values from one form to another	public FrmRedirect(string name)\n{\n     lblTitle.Text = "Thank you for logging in " + name;\n}	0
26642301	26641979	how to read an highlighting and specific word in a textbox?	voice.SpeakAsync(richTextBox1.SelectedText);	0
24294009	24293920	Insert ID into SQL from C# Combo box	App.SelectedValue	0
31591184	31589900	OData, method get with key not found	Get([FromODataUri] int key)	0
4155629	4155506	Need a good way to store Name value pairs	public static class MyRequestStatus\n{\n    public const string Accepted = "ACC",\n                        Rejected = "REJ";\n}	0
26300090	26273276	Embeded MS Word in C# application	IntPtr FileMenuHandle = (IntPtr)0;\nprivate void Timer_Tick(object sender, EventArgs e)\n{\n    IntPtr tmpHndl = FindWindowEx(MainForm.Handle, IntPtr.Zero, "FullPageUIHost", null);\n    if (tmpHndl != IntPtr.Zero && FileMenuHandle == IntPtr.Zero)\n    {\n        FileMenuHandle = tmpHndl;\n        SetParent(FileMenuHandle, Panel.Handle);\n        MoveWindow(FileMenuHandle, 0, 0, Panel.Width, panel.Height, false);\n    }\n    else if (tmpHndl == IntPtr.Zero && FileMenuHandle != IntPtr.Zero)\n        FileMenuHandle = IntPtr.Zero;\n}	0
23021245	23020932	Pinging several servers in the same time	foreach(string element in ids)\n{\n   int id = Int32.Parse(element);\n   ListViewItem item = new ListViewItem(name[id]);\n   item.SubItems.Add(ip[id]);\n   Ping pingsv = new Ping();\n   pingsv.PingCompleted += pingsv_PingCompleted;\n\n   pingsv.SendAsync(IPAddress, 500, id);\n\n}\n\n[... somewhere else in the same class ...]\n\nvoid pingsv_PingCompleted(object sender, PingCompletedEventArgs e)\n{\n      long pingtime = e.Reply.RoundtripTime;\n      // do something with pingtime...\n\n      // id has been saved to UserState (see above)\n      string id = (string)e.UserState;\n\n      // do something with id...\n\n}	0
22278886	22278821	How to deactivate all children in Unity?	//Assuming parent is the parent game object\nfor(int i=0; i< parent.transform.childCount; i++)\n{\n    var child = parent.transform.GetChild(i).gameObject;\n    if(child != null)\n        child.setActive(false);\n}	0
12276190	12259857	Filtering an ObjectQuery<T> dynamically on DateTime	Where("SqlServer.datediff('DAY'," + dateColumn + ", @p{1}) = 0")	0
22221011	22220875	Alert on button click	if (String.IsNullOrWhiteSpace(txt1.Text) || String.IsNullOrWhiteSpace(txt2.Text) || String.IsNullOrWhiteSpace(txt3.Text) || String.IsNullOrWhiteSpace(txt4.Text))\n{\n    string message = "Please enter values";\n    string script = String.Format("alert('{0}');", message);\n    this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "msgbox", script, true);\n    return;\n}	0
26245733	26245682	Getting Excel to shutdown after interop	app.Quit();	0
29292064	29292034	DataTable binding to DataGrid WPF	Binding="{Binding Description}"	0
23590125	23590075	How can i save UI Element as a image in Windows Phone 8?	var writeableBitmap = new WriteableBitmap((int)YourLongListSelector.RenderSize.Width, (int)LongListSelector.RenderSize.Height);\n\nwriteableBitmap.Render(YourLongListSelector, new ScaleTransform() { ScaleX = 1, ScaleY = 1 });\nwriteableBitmap.Invalidate();\n\nimage.Source = writeableBitmap;	0
17187053	17185560	Binding two combo boxes to the same data source,that each combo will have individual behaviour	Dictionary<string,string> dict = new Dictionary<string, string>();\ndict.Add("S1", "Sample1");\ndict.Add("S2", "Sample2");\ndict.Add("S3", "Sample3");\ndict.Add("S4", "Sample4");\n\ncomboBox1.DataSource = new BindingSource(dict, null);\ncomboBox1.DisplayMember = "value";\ncomboBox1.ValueMember = "key";\n\ncomboBox2.DataSource = new BindingSource(dict, null);\ncomboBox2.DisplayMember = "value";\ncomboBox2.ValueMember = "key";	0
30136371	30136116	How to pass values to a referenced project?	public class c1 {\n    public void m1() {\n        int someValue = 1;\n        c2 ic2 = new c2();\n        c2.m2(someValue);\n    }\n}\n\n// In project 2\npublic class c2 {\n    public void m2(int passedValue) {\n        // do something with the value\n    }\n}	0
3445849	3445818	how to insert this text in mysql	sql.command.Parameters.AddWithValue("?UserName", username);\nsql.command.Parameters.AddWithValue("?Password", password);\nsql.command.CommandText = "SELECT * FROM `users` WHERE `username`=?UserName\n  AND `password`=?Password LIMIT 1";	0
8290817	8290777	Asp.Net Returning Custom Object in json	namespace UserSite //Classes For my site\n{\n    namespace General\n    {\n        public class CodeWithMessage\n        {         \n            public int Code { get; set; }\n            public string Message { get; set; }\n        }\n     }\n}\n\n..............\n//usage\nCodeWithMessage CWM = new CodeWithMessage();\nCWM.Message = "That url Is In Use";\nCWM.Code = 0;\nreturn CWM;	0
23688029	23685375	Subquery with Entity Framework	var accountBalance = context\n    .AccountBalanceByDate\n    .Where(a => \n        a.Date == context.AccountBalanceByDate\n             .Where(b => b.AccountId == a.AccountId && b.Date < date).Max(b => b.Date));	0
12347473	12347327	Developing with twitter API	Console.WriteLine()	0
2836750	2836674	Determine if a server is listening on a given port	using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n{\n    try\n    {\n        socket.Connect(host, port);\n    }\n    catch (SocketException ex)\n    {\n        if (ex.SocketErrorCode == SocketError.ConnectionRefused) \n        {\n            // ...\n        }\n    }\n}	0
10451126	10435032	Setting Width on a Column Series: Using dotNetCharting	series["PixelPointWidth"] = "your value for width";	0
15502373	15480161	Printing 4 similar images to one document c#	Image labelImage = new Bitmap(419 * ((int)e.Graphics.DpiX / 100), 581 * ((int)e.Graphics.DpiX / 100), e.Graphics);	0
13102728	13102647	How to get the most recent National Weather Service radar images?	WebClient wc = new WebClient();\nvar page = wc.DownloadString("http://radar.weather.gov/ridge/RadarImg/NCR/OKX/?C=M;O=D");\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(page);\n\nvar imageLink = doc.DocumentNode.SelectNodes("//td/a[@href]")\n                    .Select(a=>a.Attributes["href"].Value)\n                    .OrderByDescending(a=>a)\n                    .First();	0
1224776	1224450	Is it possible to use a Strategy pattern for data structure with no common ancestor?	TResult Populate(string data);	0
13159415	13159341	Cut a text on a string when '.' is found in the text	Stringvariabel.Substring(0, Stringvariabel.IndexOf('.') + 1);	0
12996723	12996711	How to send web requests parallely using C#.	Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());	0
2585151	2575297	LINQ - How to change value in select or foreach loop?	IQueryable items = from rr in _dt.AllItems\n               where rr.ID == ItemID\n               select new {\n                   rr.Item,\n                   SecondItem = rr.SecondItem.Value ? "On" : "Off"\n               };	0
26892921	26890160	Calculate rotation acording to drag of one edge	dx0 = x0-cx\ndy0 = y0-cy\ndx1 = x1-cx\ndy1 = y1-cy\nRotationAngle = Math.Atan2(dx0 * dy1 - dx1 * dy0, dx0 * dx1 + dy0 * dy1)	0
33915782	33914945	Tree of objects	// Convert the flat list into a hash table with the ID\n    // of the element as the key\n    var dict = allCategories.ToDictionary (i => i.Id);\n\n    // Group categories by the parent id\n    var parentGrouping = allCategories.Where(c => c.IdCategoriaPai != null).GroupBy(c => c.ParentId);\n\n    // Since we group the items by parent id, we can find\n    // the parent by id in the dictionary and add the children\n    // that have that particular id.\n    foreach(var groupItem in parentGrouping)\n        if(groupItem.Key != null)\n            dict[(int)groupItem.Key].children.AddRange(groupItem);\n\n    // Get the root elements.\n    var hierarchicalCategories = allCategories.Where(item => item.IdCategoriaPai == null);\n\n    // Do what you need to do here.	0
1242041	1237621	WCF service with XML based storage. Concurrency issues?	//when a new userfile is added, create a new sync object\nfileLockDictionary.Add("user1file.xml",new object());\n\n//when updating a file\nlock(fileLockDictionary["user1file.xml"])\n{\n   //update file.\n}	0
18279188	18275984	Dependency Injection with MVVM and Child Windows	public TypeDetailsViewModel(ISomeService someService)\n{\n     TypeDetail GetDetailsCommand(int id)\n     {\n        ...\n     }\n}	0
13136180	13121587	OpenXML spacing troubles	DocumentFormat.OpenXml.Wordprocessing.TableStyle tableStyle2 = new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" };	0
5921176	5921145	How do you deal with object type switching?	//pseudo code\nhandlers.put(typeof(int), delegate(object value) { return something.GetInt32(value); });\n\n//like this\nvar handler = handlers[type];\nhandler.Invoke(val);	0
29110196	29088425	How to change DevExpress GridControl default theme in WPF control which is used in MFC	ThemeManager.SetThemeName(this, ?Office2007Blue?);	0
25146028	25145775	Task Parallel Library - running dependent tasks	......\n        tasks.Add(compute);\n        compute.ContinueWith(c=>\n        {\n            if(c.Result.Status.ToLower() == "success")\n            Dispatcher.Invoke(()=>WMIHelper.GetUptime(compute.Result.ComputerName));\n        });	0
1166350	1166314	Marshaling from C# to C++	[DllImport("lib.dll")]\npublic static extern int FunctionName(IntPtr somevariable, ushort var1, byte var2, byte var3, byte var4, [MarshalAs(UnmanagedType.LPWStr), In] string str1, [MarshalAs(UnmanagedType.LPWStr), In] string str2);	0
19633924	19633514	C# WebApi only accepts one date field per model	Id=4&Name=Tester+2&DateEnd=2013-01-10&DateStart=2013-12-31&Enabled=true	0
5595325	5593122	How to show exception in Visual Studio for SQL CE?	...\n}\ncatch (Exception ex)\n{\n    if (ex.InnerException != null)\n        Console.WriteLine(ex.InnerException.ToString());\n    else\n        Console.WriteLine("No Inner Exception");\n}	0
5843923	5839896	Simple Examples of joining 2 and 3 table using lambda expression	var list = dc.Orders.\n                Join(dc.Order_Details,\n                o => o.OrderID, od => od.OrderID,\n                (o, od) => new\n                {\n                    OrderID = o.OrderID,\n                    OrderDate = o.OrderDate,\n                    ShipName = o.ShipName,\n                    Quantity = od.Quantity,\n                    UnitPrice = od.UnitPrice,\n                    ProductID = od.ProductID\n                }).Join(dc.Products,\n                        a => a.ProductID, p => p.ProductID,\n                        (a, p) => new\n                        {\n                            OrderID = a.OrderID,\n                            OrderDate = a.OrderDate,\n                            ShipName = a.ShipName,\n                            Quantity = a.Quantity,\n                            UnitPrice = a.UnitPrice,\n                            ProductName = p.ProductName\n                        });	0
5748988	5748929	Converting list of bools to a single uint	bool[] boolValues = Enumerable.Repeat(true, 16).ToArray(); //test\nuint intValue = 0;\nfor (int i = 0; i < boolValues.Length; i++)\n{\n    if (boolValues[i])\n        intValue += (uint)(1 << i);\n}	0
9623841	9622889	How to speed up my color thresholding in C#	double satMin2 = satMin*satMin;\ndouble satMax2 = satMax*satMax;\n// ...\nsat2 = g*g + r*r;\n\n//conditions to set pixel black or white\nif ((angle >= angleMin && angle <= angleMax) && (sat2 >= satMin2 && sat <= satMax2))	0
12860215	12859094	How to get the instance of a button that is inside a DataGridView cell?	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        Int32 id = (Int32)dataGridView1[0, e.RowIndex].Value;\n        if (e.RowIndex < 0 || e.ColumnIndex != dataGridView1.Columns["NewDate"].Index)\n        {\n            if (e.RowIndex < 0 || e.ColumnIndex != dataGridView1.Columns["Delete"].Index) return;\n            else\n            {\n\n            }\n        }\n        else\n        {\n            Rectangle rect = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);\n            panel2.Location=new Point(rect.X,rect.Y);\n\n        }\n\n    }	0
3890537	3889287	How to add a jscript or html item template via an add-in in visual studio	string Solution2.GetProjectItemTemplate(string TemplateName, string Language)	0
6810782	6810360	Castly Dynamic Proxy - Get the target method's return value	invocation.Proceed();\n\nvar returnValue = invocation.ReturnValue;	0
22048120	22047436	How to draw on a picturebox and save it in Winforms C#?	pictureBox1.Invalidate();	0
20218462	20218374	C# - Fix linklabel hand-cursor	public class MyLinkLabel : LinkLabel\n{\n    protected override void OnMouseEnter(EventArgs e)\n    {\n        base.OnMouseEnter(e);\n        OverrideCursor = Cursors.Cross;\n    }\n\n    protected override void OnMouseLeave(EventArgs e)\n    {\n        base.OnMouseLeave(e);\n        OverrideCursor = null;\n    }\n\n    protected override void OnMouseMove(MouseEventArgs e)\n    {\n        base.OnMouseMove(e);\n        OverrideCursor = Cursors.Cross;\n    }\n}	0
2458867	2458847	how to serialize a DataTable to json or xml	DataTable myTable = new DataTable();\nmyTable.WriteXml(@"c:\myfile");	0
17306139	17306038	How would you detect the current browser in an Api Controller?	var userAgent = HttpContext.Current.Request.UserAgent;\n        userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };\n        var factory = new BrowserCapabilitiesFactory();\n        factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);\n\n        //Set User browser Properties\n        BrowserBrand = userBrowser.Browser;\n        BrowserVersion = userBrowser.Version;	0
12251167	12215255	how to get/set value from Com interop object using dynamic by property name string	var wrapped = ObjectAccessor.Create(obj); \nvar result = wrapped[somePropertyName];	0
12472826	12472356	How to prevent usercontrol fill option from extending too far	logicForm.BringToFront();	0
23543088	23542971	how do to deploy a c# M.S. access database application	#if DEBUG    \n      'Your connection string\n    #else\n      'Live connection string\n    #endif	0
19009494	19009351	My PDF's are opening in Adobe but not through my browser	byte[] fileContents = System.IO.File.ReadAllBytes(Server.MapPath("~/" + pathToFile));\nResponse.ContentType = "application/pdf";\nResponse.AddHeader("content-disposition", "attachment;filename=" + filename);\nResponse.OutputStream.Write(fileContents, 0, fileContents.Length);	0
12406735	12406708	exclude a class from a used namespace	using Action = MyNamespace.Action	0
22410879	22410511	Deserialize partial JSON	var response = JsonConvert.DeserializeObject<JObject>(responseStr);\nvar dataResult = (string)response["GetDataResult"];\nvar cityData = JsonConvert.DeserializeObject<CityData>(dataResult);	0
33577949	33577890	Create a list of sequential numbers excluding one number	Enumerable.Range(a, n + 1)\n          .Where(i => i != x)\n          .Take(n);	0
6194984	6194932	How to fire an asynchronous task, but wait for all callbacks before returning ActionResult?	public ActionResult ChangeProfilePicture()\n{\n   var fileUpload = Request.Files[0];\n   var threads = new Thread[3];\n   threads[0] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Original));\n   threads[1] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Profile));\n   threads[2] = new Thread(()=>ResizeAndUpload(fileUpload.InputStream, Size.Thumb));\n\n   threads[0].Start();\n   threads[1].Start();\n   threads[2].Start();\n\n   threads[0].Join();\n   threads[1].Join();\n   threads[2].Join();\n\n   return Content("Success", "text/plain");   \n}	0
20066045	20037629	How to refresh by pulling down the items?	ScrollViewer.ManipulationMode ="Control"	0
20468476	20468381	How to make button text bold?	var b = new Button()\n{\n    Location = new Point(x * 30, y * 30),\n    Width = 30,\n    Height = 30,\n    Tag = new Point(y, x), // game location x, y\n    BackColor = Color.SkyBlue,\n    Font = new Font("Tahoma", 8.25F, FontStyle.Bold)\n};	0
12682026	12630566	Parsing through Arabic / RTL text from left to right	static void Main(string[] args) {\n    string s = "Test:?????;\u200E?????;a;b";\n    string[] spl = s.Split(';');\n}	0
12904478	12904395	Un-escape HTML string in Windows 8 metro application	System.Net.WebUtility.HtmlDecode	0
22211147	22210971	How to override a getter-only property with a setter in C#?	D d = new D();\n        d.X = 2;\n        B b = d as B;\n\n        Assert.AreEqual(2, b.X);	0
19157328	19157284	Convert double to string (C#)	String.Format("{0:D8}", (int)(12.45 * 100));	0
3956219	3955968	Help in parsing XML, simple string - but I can't seem to parse it	using System;\nusing System.Xml;\n\nnamespace XMLTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            XmlDocument doc = new XmlDocument();\n             XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);\n            namespaces.AddNamespace("ns1", "jabber:client");\n            namespaces.AddNamespace("ns2", "http://jabber.org/protocol/pubsub");\n            doc.Load("xmltest.xml");\n\n            XmlNode iqNode = doc.SelectSingleNode("/ns1:iq", namespaces);\n            string ID = iqNode.Attributes["id"].Value;\n            Console.WriteLine(ID);\n\n            XmlNode subscriptionNode = doc.SelectSingleNode("/ns1:iq/ns2:pubsub/ns2:subscription", namespaces);\n            string subID = subscriptionNode.Attributes["subid"].Value;\n            Console.WriteLine(subID);\n\n            Console.ReadLine();\n        }\n    }\n}	0
10175476	10175161	Use Socket for received File in windows phone	// Data has now been sent and received from the server. \n        // Disconnect from the server\n        socket = e.UserToken as Socket;\n        socket.Shutdown(SocketShutdown.Send);\n        socket.Close();	0
27911657	27871750	importing an MDF from another machine	Data Source=.\SQLEXPRESS	0
14137064	14136956	String formatting as per current locale	string sTemp = "10.12;12.13;15.345";\nstring[] splitted = sTemp.Split(';');\nIEnumerable<float> floats = splitted.Select(s => float.Parse(s, System.Globalization.CultureInfo.InvariantCulture));\n\nstring localized = floats.Select(f => f.ToString()).Aggregate((current, next) => current + ";" + next);	0
14906592	14906555	Save edited XML Document to any location?	SaveFileDialog saveFileDialog = new SaveFileDialog();\nsaveFileDialog.Filter = "Xml (*.xml)|*.xml";\nif (saveFileDialog.ShowDialog().Value)\n{\n    doc.Save(saveFileDialog.FileName);\n}	0
16843447	16843185	Sending xml using Apache HttpComponents	File file = new File("somefile.xml");\nFileEntity entity = new FileEntity(file, ContentType.create("application/xml", "UTF-8"));	0
30760278	30753752	How to be sure Outlook application has been loaded completely (application.StartUp event)	olApp = new Outlook.Application();\nOutlook.Namespace ns = olApp.GetNamespace("MAPI");\nns.Logon();	0
13787927	13787878	How to get top 5 repeated Regex.Matches in C#?	var topMatches = Regex.Matches(stringToCheck, RegExPattern)\n    .Cast<Match>()\n    .GroupBy(m => m.Value)\n    .Select(m => new{ Colour = m.Key, Count = m.Count() })\n    .OrderByDescending(g => g.Count)\n    .Take(5)\n    .ToList();	0
16883057	16876446	How to programatically change the visual state in silverlight	VisualStateManager.GoToState	0
16748110	16748055	Any better way of accessing values from database-LinqToSql	return (from user in dB.Users\n             where {your test}\n             select user).ToList();	0
7278869	7278775	How can I check, then change, the value in a datatable cell?	if (transformerDT.Rows[0][6].ToString() == "0002") {\n    transformerDT.Rows[0][6] = "Conventional";\n}	0
9814828	9814660	Return best fit item from collection in C# 3.5 in just a line or two	MaxBy()	0
16254155	16242975	How can I log someone into DotNetNuke without knowing their DotNetNuke password in an SSO scenario?	UserController.GetUserByName	0
26742591	26742262	How to use Fluent API to map foreign key	[Column("JobTESPM_EmployeeID")]\npublic int? JobTESPMId { get; set; }\n[ForeignKey("JobTESPMId")]\npublic virtual Employee JobTESPM { get; set; }	0
21540511	21372530	c# How to encode int array to TIFF image?	if (!System.IO.File.Exists(pathString))\n                {\n                    System.Windows.Media.PixelFormat pf = System.Windows.Media.PixelFormats.Gray16;\n                    int stride = newImage.imageWidth * 2;\n                    BitmapPalette pallet = BitmapPalettes.Gray16;\n                    double dpix = 216;\n                    double dpiy = 163;\n                    BitmapSource bmpSource = BitmapSource.Create(imageWidth, imageHeight, dpix, dpiy, pf, pallet, intArray, stride);\n                    using (FileStream fs = new FileStream(pathString, FileMode.Create))\n                    {\n                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();\n                        encoder.Compression = TiffCompressOption.None;\n                        encoder.Frames.Add(BitmapFrame.Create(bmpSource));\n                        encoder.Save(fs);\n                    }\n\n                }	0
16005054	15982323	COSM Trigger extracting JSON values using C# from an HTTP Post	[OperationContract]  \n[WebInvoke(Method = "POST",  \nBodyStyle = WebMessageBodyStyle.WrappedRequest,  \nUriTemplate = "cosm")]  \nstring cosmStream(Stream body);	0
1862226	1862163	Migrating from .net to Sharepoint	Microsoft.Sharepoint	0
13885279	13885195	How to select data from table selected in dropdownlist?	protected void Button1_Click(object sender, EventArgs e)\n{\n    OleDbConnection con= new OleDbConnection(connectionString);\n\n    SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT * FROM {0}",DropDownList1.SelectedValue), con);\n    DataSet ds = new DataSet();\n    da.MissingSchemaAction = MissingSchemaAction.AddWithKey;\n    da.Fill(ds);\n\n    GridView1.DataSource = ds.Tables[0];\n    GridView1.DataBind();\n    con.Close();\n}	0
14858275	14857977	Posting Array using JSON & JQuery to a C# Web Api back end	content-type :application/json	0
15722518	15722455	Read text file from C# Resources	string resource_data = Properties.Resources.test;\nList<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();	0
20527150	20527090	Starting tasks in a dynamic way	var list = new List<SomeClass>();\nParallel.ForEach(list, instance =>\n{\n    instance.Process();\n});	0
7270267	7269958	Capturing sound from TV Card with C#	var windowInteropHelper = new WindowInteropHelper(this);\nsoundDevice = new DS.Device();\nsoundDevice.SetCooperativeLevel(windowInteropHelper.Handle, CooperativeLevel.Priority);	0
20752165	20752118	Programmatically setting button image	// Give the button a flat appearance.\n    button1.FlatStyle = FlatStyle.Flat;	0
28035676	28035453	How can I merge 2 zip files into 1?	public ZipArchive Merge(List<ZipArchive> archives)\n    {\n        if (archives == null) throw new ArgumentNullException("archives");\n        if (archives.Count == 1) return archives.Single();\n\n        using (var memoryStream = new MemoryStream())\n        {\n            using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))\n            {\n                foreach (var zipArchive in archives)\n                {\n                    foreach (var zipArchiveEntry in zipArchive.Entries)\n                    {\n                        var file = archive.CreateEntry(zipArchiveEntry.FullName);\n\n                        using (var entryStream = file.Open()) {\n                            using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(zipArchiveEntry.Open()); }\n                        }\n                    }\n                }\n\n                return archive;\n            }\n        }\n    }	0
19153377	19153306	how to bind more than one dropdownlist without refreshing?	protected void Page_Load(object sender, EventArgs e)\n{\n  if(!IsPostBack)\n {\n\n    bindbranches();\n    bindbranches1();\n  }\n}	0
931418	918776	How do you make methods relying on extension methods testable?	[TestMethod]\npublic void SelectReturnsNullOnNullBuildAgents()\n{\n    Mocks = new MockRepository();\n    IBuildServer buildServer = Mocks.CreateMock<IBuildServer>();\n\n    BuildAgent agent = new BuildAgent { ... }; // Create an agent\n    BuildAgentSelector buildAgentSelector = new BuildAgentSelector();\n    using (Mocks.Record())\n    {\n        Expect.Call(buildServer.CreateBuildAgentSpec(TeamProjectName)).Return(new List<BuildAgent> { agent });\n    }\n\n    using (Mocks.Playback())\n    {\n        BuildAgent buildAgent = buildAgentSelector.Select(buildServer, TeamProjectName);\n\n        Assert.IsNull(buildAgent);\n    }\n}	0
17994818	17994776	website uploads on page refresh	Response.Redirect("~/path/to/your/file.aspx");	0
3768188	3768083	Closing one application from another in c# .net	Process []GetPArry = Process.GetProcesses();\nforeach(Process testProcess in GetPArry)\n{\n    string ProcessName = testProcess .ProcessName;\n\n    ProcessName  = ProcessName .ToLower();\n    if (ProcessName.CompareTo("winword") == 0)\n        testProcess.Kill();\n}	0
3638833	3638712	How to get a file and move it out of the isolated storage?	using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())\n{\n    //write sample file\n    using (Stream fs = new IsolatedStorageFileStream("test.txt", FileMode.Create, store))\n    {\n        StreamWriter w = new StreamWriter(fs);\n        w.WriteLine("test");\n        w.Flush();\n    }\n\n    //the following line will crash...\n    //store.CopyFile("test.txt", @"c:\test2.txt");\n\n    //open the file backup, read its contents, write them back out to \n    //your new file.\n    using (IsolatedStorageFileStream ifs = store.OpenFile("test.txt", FileMode.Open))\n    {\n        StreamReader reader = new StreamReader(ifs);\n        string contents = reader.ReadToEnd();\n        using (StreamWriter sw = new StreamWriter("nonisostorage.txt"))\n        {\n            sw.Write(contents);\n        }\n    }\n}	0
24249235	24218672	Insert 2D array into excel in C# WPF	xlApp = new Excel.Application();\n\n        xlWorkBook = xlApp.Workbooks.Open(ExcelFile);\n        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n\n        Excel.Range firstCell = xlWorkSheet.get_Range("A1", Type.Missing);\n\n        Excel.Range lastCell = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);\n\n\n        Excel.Range worksheetCells = xlWorkSheet.get_Range(firstCell, lastCell);\n\n        int rowCount = worksheetCells.Rows.Count;\n        int colCount = worksheetCells.Columns.Count;\n\n         object[,] cellFormulas = new String[rowCount, colCount];\n\n         cellFormulas = worksheetCells.Formula as object[,];\n\n       //  String[][] ResultMatrix = new String[rowCount][];\n\n\n\n        xlWorkBook.Close(true, misValue, misValue);\n        xlApp.Workbooks.Close();'	0
29095937	29029521	webpart value gone after page reload	SPWeb web = SPContext.Current.Web;\n                SPFile file = web.GetFile(<PageURL>);\n                SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);                \n                web.AllowUnsafeUpdates = true;\n                CustomWebPart webPart = (CustomWebPart)manager.WebParts[this.ID];\n  //saved condition is my properties, u can find it from my questions above\n                webPart.SavedCondition = "Something"; \n                manager.SaveChanges(webPart);\n                web.AllowUnsafeUpdates = false;	0
30953970	30953908	Lambda expression to check if value is null or equals	FilteredResult = db.Stocks.where(m => (m.PaperType == PaperType || !PaperType.HasValue)\n                                   && (m.PaperGram == PaperGram || !PaperGram.HasValue) \n                                   && (m.Brand     == Brand     || !Brand.HasValue));	0
1703692	1703528	Merging an XML file with a list of changes	XmlDocument main = new XmlDocument();\nmain.Load( "main.xml" );\n\nXmlDocument changes = new XmlDocument();\nchanges.Load( "changes.xml" );\n\nforeach ( XmlNode mainNode in main.SelectNodes( "preset/var" ) )\n{\n    string mainId = mainNode.Attributes[ "id" ].Value;\n    string mainOpt = mainNode.Attributes[ "opt" ].Value;\n\n    foreach ( XmlNode changeNode in changes.SelectNodes( "preset/var" ) )\n    {\n        if ( mainId == changeNode.Attributes[ "id" ].Value &&\n            mainOpt == changeNode.Attributes[ "opt" ].Value )\n        {\n            mainNode.Attributes[ "val" ].Value = changeNode.Attributes[ "val" ].Value;\n        }\n    }\n}\n\n// save the updated main document\nmain.Save( "updated_main.xml" );	0
13241517	13231913	How do I call a specific Method from a Python Script in C#?	var pySrc =\n@"def CalcAdd(Numb1, Numb2):\n    return Numb1 + Numb2";\n\n// host python and execute script\nvar engine = IronPython.Hosting.Python.CreateEngine();\nvar scope = engine.CreateScope();\nengine.Execute(pySrc, scope);\n\n// get function and dynamically invoke\nvar calcAdd = scope.GetVariable("CalcAdd");\nvar result = calcAdd(34, 8); // returns 42 (Int32)\n\n// get function with a strongly typed signature\nvar calcAddTyped = scope.GetVariable<Func<decimal, decimal, decimal>>("CalcAdd");\nvar resultTyped = calcAddTyped(5, 7); // returns 12m	0
3080867	3080854	Format Exception- DateTime and hours	DateTime test= DateTime.Now;\nConsole.WriteLine(test.ToString("{0:%h}")); // From the document, adds precision\nConsole.WriteLine(test.ToString("%h")); // Will also work	0
6167016	6166992	How to parse multiple single xml elements in .Net C#	string xml = "<root>...</root>";\nXDocument doc = XDocument.Parse(xml); // Use .Load() if loading from a file\nString status = doc.Root.Element("status").Value;\nIEnumerable<string> personNames = doc.Root.Descendants("person").Select(x => x.Element("name").Value);	0
21097438	21096523	Xamarin Pass Data Between Activity	homeButton.Click += delegate {\n    var second = new Intent(this, typeof(SecondPage));\n    second.PutExtra("reg", "qwe");\n    StartActivity (second);\n    }	0
31710174	31710004	c# sort hand of playing cards	var sorted = hand\n    .GroupBy(l => l.Suit)\n    .OrderByDescending(g => g.Count())\n    .SelectMany(g => g.OrderByDescending(c => c.Value));	0
12525343	12521883	Displaying JSON data using RestSharp	restClient.ExecuteAsync<Entry>(request, response =>\n    {\n        //Supply your JSON data to a callback\n        Callback(response.Data);\n    });\n\npublic void Callback(string jsonResponse)\n{\n    var responseList = JsonConvert.DeserializeObject<RootObject>(jsonResponse);\n    //Assuming you have properly setup binding properties for Listbox, databind listbox here\n    YourListBox.ItemsSource = responseList.entries;\n}	0
14158202	14140617	Update and Add Child Rows at same time with Entity Framework	public void EditReport(Inspection obj)\n{\n    var inspection = new tbl_inspection\n    {\n        id_inspection = obj.ID,\n        code = obj.Code       \n    };\n\n    foreach (var roll in obj.Rolls)\n    {                    \n        var rollStub = new tbl_inspection_roll\n        {\n            id_inspection_roll = roll.ID,\n            id_inspection = obj.ID,\n            description = roll.Description\n        };\n\n        container.tbl_inspection_roll.Attach(roll);\n        container.ObjectStateManager.ChangeObjectState(roll, (roll.id_inspection_roll == 0) ? EntityState.Added : EntityState.Modified);\n    }\n\n    container.tbl_inspection.Attach(inspection);\n    container.ObjectStateManager.ChangeObjectState(inspection, EntityState.Modified);\n\n    container.SaveChanges();\n}	0
28644433	28644376	How do I get information from a text box sent to my email? (C#, Visual studio 2013)	// Attach the btnSend click event where it is created or before it suites better in you code.\nbtnsend.Click += btnsend_Click;\n\n        void btnsend_Click(object sender, RoutedEventArgs e)\n        {\n            MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");\n            SmtpClient client = new SmtpClient();\n            client.Port = 25;\n            client.DeliveryMethod = SmtpDeliveryMethod.Network;\n            client.UseDefaultCredentials = false;\n            client.Host = "smtp.google.com";\n            mail.To.Add("reciever@example.com");\n            mail.Subject = textbox1.Text;\n            mail.Body = textbox2.Text;\n            client.Send(mail);\n        }	0
30984762	30983567	How can i put formclosing event in Button	private bool btnClicked = false;\npublic void btnChallenge_Click(object sender, EventArgs e)\n{\n     btnClicked = true;\n}\n\nprivate void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n    if(btnClicked)\n    {\n        e.Cancel=true;\n    }\n\n}	0
29131767	29129701	Initialising a user control in code behind not working - MVVM WPF	public MainView(IMainViewModel mainViewModel)\n{\n    InitializeComponent();\n\n    DataContext = mainViewModel;\n    SomeViewUc.DataContext = new SomeViewModel(mainViewModel); \n}	0
6170934	6170566	C# Getting the window with focus?	GUITHREADINFO.hwndFocus	0
30594704	30593869	Deserializing Json String into multiple Object types	var j = JArray.Parse(data);\nTeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());\nMobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());	0
5583144	5583095	Sorting Column By DateTime Value Not String Value?	try {\n    DateTime dateX = Convert.ToDateTime(listviewX.SubItems[ColumnToSort].Text);\n    DateTime dateY = Convert.ToDateTime(listviewY.SubItems[ColumnToSort].Text);\n    compareResult = ObjectCompare.Compare(dateX, dateY);\n}\ncatch {\n    compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);\n}	0
20122370	20121593	How to check whether a multi line string contains in a text file using c#?	string scriptToFind = ...\nstring fileToSearchText = ...\n\nstring patternToFind = Regex.Replace(@patternToFind, @"(\*|\.|\\|\(|\)|\[|\]|\{|\}|\+)",@"\$1"); // those aren't all special regex characters that need to be escaped\npatternToFind = Regex.Replace(@scriptToFind, @"\s+",@"\s*");\n\nbool isMatch = Regex.IsMatch(@fileToSearchText,@patternToFind);	0
2892695	2892603	How to parse DateTime in this format? "Sun May 23 22:00:00 UTC+0300 2010"	DateTime dt = DateTime.ParseExact(s,"ddd MMM dd HH:mm:ss UTCzzzz yyyy", System.Globalization.CultureInfo.InvariantCulture);	0
11379993	11379963	linq-to-sql getting state of value at a certain date	// var date = DateTime.Now.Subtract(TimeSpan.FromMonths(1));\nvar state = MyDC.StateTable.Where(xx => date >= xx.Date)\n                           .OrderBy(xx => xx.Date)\n                           .First()\n                           .State;	0
5122425	5122306	How do I run a Console Application, capture the output and display it in a Literal?	ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe");\npInfo.FileName = exePath;\npInfo.WorkingDirectory = new FileInfo(exePath).DirectoryName;\npInfo.Arguments = args;\npInfo.CreateNoWindow = false;\npInfo.UseShellExecute = false;\npInfo.WindowStyle = ProcessWindowStyle.Normal;\npInfo.RedirectStandardOutput = true;\nProcess p = Process.Start(pInfo);\np.OutputDataReceived += p_OutputDataReceived;\np.BeginOutputReadLine();\np.WaitForExit();\n// set status based on return code.\nif (p.ExitCode == 0) this.Status = StatusEnum.CompletedSuccess;\n   else this.Status = StatusEnum.CompletedFailure;	0
24042411	24011906	Instance of a class in Create method of JobBuilder in quartz.net	public static class HelloFactory\n{\n\n    public Type GetHelloType(HelloEnum theEnum)\n    {\n        Type type;\n        switch (theEnum)\n        {\n            case HelloEnum.Type1:\n                type = typeof(Hello1);\n                break;\n            case HelloEnum.Type2: job = typeof(Hello2);\n                break;\n        }\n\n    }\n}	0
11232031	11231990	Counting sublists of a list in C#	listholder.Count()	0
11062147	11062065	How can we take a short string from a long string in asp.net mvc3 using LINQ?	public string ProductDescription { get; set; }\n\n    public string ShortDescription\n    {\n        get\n        {\n            var text = ProductDescription;\n            if (text.Length > 21)\n            {\n                text = text.Remove(19);\n                text += "..";\n            }\n            return text ;\n        }\n    }	0
23897929	23897482	Get SQL print messages from stored proc	private static void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)\n    {\n        if (e.Errors != null)\n        {\n            for (int i = 0; i < e.Errors.Count; i++)\n            {\n                sqlMessages.AppendLine(e.Errors[i].Message);\n            }\n        }\n    }	0
1725760	1725155	Reading RSS feed with Linq-to-XML and C# - how to decode CDATA section?	"&#246;"	0
11320295	11320240	Send HTTP Request via ASP.NET C#	var response = request.GetResponse() as HttpWebResponse;	0
32245516	32245448	How to remove duplicates while exporting from different excel files to database	insert into tartget_table(col_list)\nselect t1.col_list from staging as t1 where not exists\n(select * from target_table as t2 where t1.keycol=t2.keycol)	0
28174898	28174821	Round numbers to next int, hundred and thousand in c#	double number = 1551;\nif (number >= 0 && number <= 100)\n{\n    number = Math.Round(number);\n}\nelse if (number > 100 && number <= 10000)\n{\n    number = Math.Round(number / 100) * 100;\n}\nelse if (number > 10000)\n{\n    number = Math.Round(number / 1000) * 1000;\n}\n\nConsole.WriteLine(number);	0
15366161	15365858	Need Help - Dynamic Click EventHandler with custom arguments - Lambda Expression	awardButton.Click += (sender, e) => PreviewAward(sender, e, dtAward.Rows[0]["iconImage"].ToString());	0
542663	542645	Eval stacktrace with formatting	String htmlMessage = e.Message.Replace("\n", "<br/>");	0
27135977	27135935	How to use less arguments for methods	public class ProductArgs\n{\n    public int? ProductID { get; set; }\n    public string Name { get; set; }\n    public string Color { get; set; }\n    public bool? MakeFlag { get; set; }\n}\n\npublic List GET_Product(ProductArgs p){ ... }	0
5174459	5174423	Getting 'basic' datatype rather than weird nullable one, via reflection in c#	private static Type GetCoreType(Type type)\n{\n    if (type.IsGenericType &&\n        type.GetGenericTypeDefinition() == typeof(Nullable<>))\n        return Nullable.GetUnderlyingType(type);\n    else\n        return type;\n}	0
15782447	15782314	restrict opening window B when window A is open	menuItem1.Enabled = false;	0
12238052	12238027	How to sort two separate lists alphabetically without intermediate object?	interface ISortableItem\n{\n  string Name { get; }\n}	0
4623478	4623360	Initialize list from array using a initializer list	using System.Linq;\n\n\npublic class Derived : Base\n{\n    public Derived()\n        : base(new List<SomeEnum>(Enum.GetValues(typeof(SomeEnum)).OfType<SomeEnum>()))\n    {\n    }\n}	0
22992408	22992148	How to match all objects from two lists into pairs of two based on proximity of DateTime values	//just some objects for me to play with\nvar requests =  Enumerable.Range(1).Select(i => new { Time = DateTime.Now, Method = "blah" }).ToList();\nvar responses =  Enumerable.Range(1).Select(i => new { Time = DateTime.Now, Method = "blah" }).ToList();\n\nforeach (var req in requests)\n{\n    //In all of the responses - find the one that happened soonest after the request (with the same method name)\n    var closestResponse = responses\n        .Where(resp => resp.Method == req.Method)\n        .OrderBy(resp => resp.Time - req.Time)\n        .FirstOrDefault();\n\n    //No more responses - exit\n    if(closestResponse == null)\n        break;\n\n    responses.Remove(closestResponse);\n\n    //make new call pair, with the closest rseponse\n}	0
513325	513276	How to display the same control on two different tabs?	listBox1.Parent = tabControl1.TabPages[1];	0
14756965	14748678	Call Javascript function with parameters from C# Page .aspx	public partial class Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        ClientScript.RegisterClientScriptBlock(this.GetType(), \n                "openTicketsScript", string.Format("openticketPageLoad({0});", Request.QueryString["ID"]), true);\n    }\n}	0
28182355	28182266	C# how to get hours and minutes from decimal value	time.Minutes == 47\ntime.Days == 4\ntime.TotalHours == 98.785	0
1204443	1204437	c# default parameters	void cookEgg(bool hardBoiled) { ... }\nvoid cookEgg() { cookEgg(true); }	0
11532176	11511550	Verifying many properties cleanly [separately outside of single verify call] of an argument passed to Mock?	protected static LayoutENT.Theme savedTheme;\n// Arrange\nthemeParam = null;\nsaveThemeAS.Setup(service => service.Execute(FakeUserID, It.Is<LayoutENT.Theme>)\n    .Callback<layoutENT.Theme>(p =>  savedTheme = p);\n\n// Act\n// Calls the subject under test\n\n// Assert\nAssert.IsNotNull(savedTheme); \nAssert.AreEqual(FakeCopiedThemeName, savedTheme.Name); \nAssert.AreEqual(0, savedTheme.ThemeID)	0
11431276	11431044	Showing report in Report Viewer based on conditions?	ReportDataSource rds0 = new ReportDataSource("DataSetNameDefinedInReport", data);\nthis.reportViewer1.LocalReport.ReportPath = @"Reportname.rdlc";\nthis.reportViewer1.LocalReport.DataSources.Add(rds0);\n//show report!\nthis.reportViewer1.RefreshReport();	0
13211276	13211012	getting a "default" concrete class that implements an interface	var defaultTypeFor = new Dictionary<Type, Type>();\ndefaultTypeFor[typeof(IList<>)] = typeof(List<>);\n...\nvar type = property.PropertyType;\nif (type.IsInterface) {\n    // TODO: Throw an exception if the type doesn't exist in the dictionary\n    if (type.IsGenericType) {\n        type = defaultTypeFor[property.PropertyType.GetGenericTypeDefinition()];\n        type = type.MakeGenericType(property.PropertyType.GetGenericArguments());\n    }\n    else {\n        type = defaultTypeFor[property.PropertyType];\n    }\n}\ntheList = Activator.CreateInstance(type);	0
320670	320645	Check status of process	using System;\nusing System.Diagnostics;\n\nnamespace ProcessStatus\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Process[] processes = Process.GetProcesses();\n\n            foreach (Process process in processes)\n            {\n                Console.WriteLine("Process Name: {0}, Responding: {1}", process.ProcessName, process.Responding);\n            }\n\n            Console.Write("press enter");\n            Console.ReadLine();\n        }\n    }\n}	0
34225702	34183891	how to embed an external javascript file to a c# selenium test unit?	using System.IO;\n\n\nIJavaScriptExecutor selenium = _driver as IJavaScriptExecutor;\nstring path = @"Path to your file";\nstring jsFileContent = File.ReadAllText(path);\nselenium.ExecuteScript (jsFileContent);	0
30098358	30097367	XML Outputs in Visual C#	[XmlRoot("root")]
\n    public class Root
\n    {
\n        [XmlElement("element")]
\n        public List<Element> elements {get;set;}
\n    }	0
12128040	12126612	Manipulate ListView from inside a background worker	private void bParsePosts_Click(object sender, EventArgs e)\n{\n    parseWorker.WorkerReportsProgress = true;\n    parseWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);\n    parseWorker.RunWorkerAsync();\n}\n\nprivate void parseWorker_DoWork(object sender, DoWorkEventArgs e)\n{\n    // Loop through each item\n    for (int i = 0; i < lvPostQueue.Items.Count; i++)\n    {\n        string title = lvPostQueue.Items[i].SubItems[0].ToString();\n        string category = lvPostQueue.Items[i].SubItems[1].ToString();\n        string url = lvPostQueue.Items[i].SubItems[2].ToString();\n\n        parseWorker.ReportProgress(i * 100 / lvPostQueue.Items.Count, i);\n    }\n}\n\nvoid worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    var i = (int)e.UserState;\n    lvPostQueue.Items[i].SubItems[3].Text = "Done";\n}	0
30846867	30833377	Receiving strangers strings in target window from PostMessage api	//   PostMessage(WindowHandle, WM_KEYDOWN, val, new IntPtr(0));\n                PostMessage(WindowHandle, WM_CHAR, val, new IntPtr(0));\n            //    PostMessage(WindowHandle, WM_KEYUP, val, new IntPtr(0));	0
32605288	32605081	How to generate object from xml steam using xsd?	XmlSerializer serializer = new XmlSerializer(typeof(YourXsdClass));\nusing (someReader = YourXmlReader)\n{\n    StepList result = (YourXsdClass)serializer.Deserialize(reader);\n}	0
27326338	27301498	Generate XML File From Generated Object	xsd.exe	0
2222488	2219930	Pattern to map Generic Data Structure to a Specific Data Structure	public class NodeFu {\n\n    private Node node;\n\n    public NodeFu(Node node){\n        this.node = node;\n        // perhaps traverse and validate node data here\n    }\n\n    public String getNodeAttribute(String attrName){\n        // pardon the offense, Demeter, only for demonstration...\n        return node.getAttributes().getNamedItem(attrName).toString();\n    }\n\n    public void setNodeAttribute(String attrName, attrValue){\n        node.setAttributeValue(attrName, attrValue);\n    }\n\n    public ArrayList<NodeFu> getChildren(){\n        ArrayList<NodeFu> children = new ArrayList<NodeFu>();\n        for (Node childNode : node.getChildNodes()){\n            children.add(new NodeFu(childNode));\n        }\n        return children;\n    }\n}	0
22220097	22218001	ASP MVC4 + NHibernate objects in Session	var userId = Convert.ToInt32(ModelState["User"].Value.AttemptedValue);\nUser usr = _userRepository.GetById(userId);\nNHibernateUtil.Initialize(usr.Customer);\nSession["user"] = usr;	0
13592445	13592064	Get user group in Membership.ValidateUser	string userName = "someuser";\n        string password = "";\n        MembershipUser user = null;\n        if (Membership.ValidateUser(userName,password))\n        {\n            user = Membership.GetUser(userName);\n        }	0
10603569	10603269	xml to treeview using dataset	SearchString = [String].Format("//Id[.=""{0}""]/..", Row("ParentId").ToString())	0
9377714	9377635	Create Expression from Func	Func<int> func = () => 1;\nExpression<Func<int>> expression = Expression.Lambda<Func<int>>(Expression.Call(func.Method));	0
16489820	16285311	Plugin Framework for Win-Rt	Type driverType = Type.GetType(string.Format("Win8App.RDriver.Drivers.{0}", driver));\nif (driverType != null)\n{\n    return (IDriver)Activator.CreateInstance(driverType);\n}\nlog.Error(string.Format("Could not load driver Win8App.RDriver.Drivers.{0}", driver));\nreturn null;	0
7022474	6952014	Silverlight: Get RowGroupHeader value in DataGridRowGroupHeader event	private void TaskDataGrid_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e)\n{\n\n     var RowGroupHeader = (e.RowGroupHeader.DataContext as CollectionViewGroup);\n\n                if (RowGroupHeader != null && RowGroupHeader.Items.Count != 0)\n                {\n\n                        MasterTask task = RowGroupHeader.Items[0] as MasterTask;\n                        if (task != null && task.SubCategoryName == null)\n                            e.RowGroupHeader.Height = 0;\n\n\n               }\n }	0
3506364	3505486	How can I setup default actions for a rhino mocked interface in a setup method, which can be overridden for specific behavior in a test method?	someOptions.Stub(o => o.Something).Return("default");\nsomeOptions.Stub(o => o.Something).Return("override");	0
30491864	30491553	Placing Hyperlinks in DataGrid	row[3] = "<a href='" + row[3] + "/rev/" + row[1] + "'>" + "test" + "</a>";	0
8535117	8535018	Entity Framework - Combining data on two rows	var firstnames = from user in context.Users\n                 where user.PropertyType == 1\n                 select new { Id = user.UserID,\n                              Firstname = user.PropertyValue };\n\nvar lastnames = from user in context.Users\n                where user.PropertyType == 2\n                select new { Id = user.UserID,\n                             Lastname = user.PropertyValue };\n\nvar users = from fn in firstnames\n            join ln in lastnames on fn.Id equals ln.Id\n            select new { Id = fn.Id,\n                         Firstname = fn.Firstname,\n                         Lastname = ln.Lastname };\n\nvar query = from order in context.Orders\n            join user in users on order.UserID equals user.Id\n            select new { /*what you need to select*/ };	0
25275272	25267005	Remove row from chart range using office interop	chart.Chart.SeriesCollection(4).Delete();	0
15088009	15087799	Fetching string from webpage into C# Form application	using (var client = new WebClient())\n{\n    string result = client.DownloadString("http://www.test.com");\n    // TODO: do something with the downloaded result from the remote\n}	0
8937428	8937290	lambda expressions c#	static Func<T, T> Compose<T>(params Func<T, T>[] ff)\n{\n  Func<T, T> id = x => x;\n\n  foreach (var f in ff)\n  {\n    var i = f;\n    var idd = id;\n    id = x => i(idd(x));\n  }\n\n  return id;\n}	0
6795659	6795649	C# - How can I pass a reference to a function that requires an out variable?	delegate ICollection<string> MyFunc(string x, out int y);	0
14131382	14131357	Add multiple labels to a panel	var range = Enumerable.Range(1, 90);\nvar vartable = new Dictionary<string, Label>();\nforeach (int i in range)\n{\n    var num = i.ToString();\n    var label = new Label { Text = num };\n    vartable[num] = label;\n    panel1.Controls.Add(label);\n}	0
14123976	14105049	Windows Directory Size Differences Between Applications	[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]\ninternal static extern SafeFindHandle FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData)	0
29231796	29229904	How to find specific sql query in a c# project	ctrl+shift+f	0
27029147	27022216	Not getting a result with single sign on to Goodreads on Windows 8.1	string goodreadsURL =\n    "https://www.goodreads.com/oauth/authorize?oauth_token=" + Properties.OAuth_token;\n\nUri sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();\nstring callbackURL = sid.ToString();\n\nvar startUri =\n    new Uri(goodreadsURL + "&oauth_callback=" + Uri.EscapeDataString(callbackURL));\n\nWebAuthenticationResult result =\n    await WebAuthenticationBroker.AuthenticateAsync(\n        WebAuthenticationOptions.None,\n        startUri,\n        new Uri(callbackURL));\n\nif (result.ResponseStatus == WebAuthenticationStatus.Success &&\n    !result.ResponseData.Contains("&error="))\n{\n    [...]\n}	0
30943933	30943838	Return list of string	return fatcaQuestionaires.Select(x => x.Questionaire).ToList();	0
14221057	14220611	System::IntPtr to int* in C++/CLI	doSomething(reinterpret_cast<int*>(itn.ToPointer()), size);	0
11145105	11145053	Can't find how to use HttpContent	System.Net.Http	0
5409969	5409890	Formatting a string using values from a generic list by LINQ	string retrieveSectors =\n        string.Format(\n        "sectors {0} -",\n        sectors.Select(s => s.Replace("sector ", "").Replace("|", ""))\n            .OrderBy(s => s)\n            .Aggregate((a, b) => string.Format("{0} & {1}", a, b))\n        );	0
30584954	30584910	Opening Windows Form app from .bat file places it behind Windows Explorer	this.Show();\nthis.WindowState = FormWindowState.Normal;\nthis.BringToFront();\nthis.Activate();	0
9597496	9597430	Http Module to change culture has no effect	System.Threading.Thread.CurrentThread.CurrentUICulture = currentCulture;	0
9832136	9830755	How to design a comment system using Entity Framework?	public interface ICommentable {\n // basically a marker interface like Serializable\n}\n\npublic class Picture : ICommentable {\n // etc\n}\n\npublic class Comment {\n // etc\n public ICommentable _commentAttachedTo;\n}	0
155787	155685	I need a LINQ expression to find an XElement where the element name and attributes match an input node	public static void ReplaceOrAdd(this XElement source, XElement node)\n { var q = from x in source.Elements()\n           where    x.Name == node.Name\n                 && x.Attributes().All\n                                  (a =>node.Attributes().Any\n                                  (b =>a.Name==b.Name && a.Value==b.Value))\n           select x;\n\n   var n = q.LastOrDefault();\n\n   if (n == null) source.Add(node);\n   else n.ReplaceWith(node);                                              \n }\n\nvar root   =XElement.Parse(data);\nvar newElem=XElement.Parse("<thing2 a1=\"a\" a2=\"b\">new value</thing2>");\n\nroot.ReplaceOrAdd(newElem);	0
10613898	10607909	Chosing datagrid event	e.Handled=true	0
13435193	13434697	How to Navigate to another Page After running an Animation	private void Button1_Click(object sender, RoutedEventArgs e)\n    {\n        myAnimation.Begin();\n        myAnimation.Completed += (s,ev)=>\n          {\n           NavigationService.Navigate(new Uri("/nextPage.xaml?id=Button1",UriKind.Relative));\n          };\n\n    }	0
7311115	7310896	ASP.NET WebForms - Calling Multiple API's and show result to user	public interface IResultsStrategy {\n    RateResults GetRateResults(SiteInfo site);\n}\n\npublic class SpecificSiteStrategy {\n    public RateResults GetRateResults(SiteInfo site) {\n        //access the service through WCF, or whatever makes the most sense\n        //create a new RateResults object, and fill it with the appropriate data\n    }\n}\n\npublic class AnotherSiteStrategy {\n    public RateResults GetRateResults(SiteInfo site) {\n        //access the service through a web request, or whatever makes the most sense\n        //create a new RateResults object, and fill it with the appropriate data\n    }\n}\n\npublic class RateFetcher {\n    public IEnumerable<RateResults> GetRates() {\n        var rateResults = new List<RateResults();\n        foreach(SiteInfo site in SitesToFetch) {\n            IResultsStrategy strategy = GetStrategy(site);\n            rateResults.Add(strategy.GetRateResults(site));\n        }\n        return rateResults;\n    }\n}	0
25156168	25012346	Kendo Grid Filter not working properly for date column	[DataType(DataType.Date)]\npublic DateTime? UpdatedOrderedDateReadOnly \n{ \n    get\n    {\n        if (OrderedDate != null)\n        {\n            return (Convert.ToDateTime(OrderedDate).Date);\n        }\n        return null;\n    }\n}	0
2580952	2580642	How to avoid beep sound of DateTimePicker	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n      dateTimePicker1.KeyDown += squelchBeep;\n    }\n    private void squelchBeep(object sender, KeyEventArgs e) {\n      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Escape) e.SuppressKeyPress = true;\n    }\n  }	0
2447912	2447176	XmlDocument OuterXml pretty printed	using System.Xml.Linq;\nXDocument xDoc = XDocument.Load(@".....\test.xml");\nstring xDocString = xDoc.ToString(SaveOptions.None);	0
8839351	8838417	How to get a flattened list from nested class List<T>?	public IEnumerable<Person> Find(IEnumerable<Person> input, Func<Person, bool> predicate) {\n    return input.Select(p => \n        {\n            var thisLevel = new List<Person>();\n            if(predicate(p))\n                thisLevel.Add(p);\n\n            return thisLevel.Union(Find(p.People ?? new List<Person>(), predicate));\n        }\n    ).SelectMany(p => p);\n}	0
12641729	12640724	Fade video in a MediaElement in WPF	mediaElement.BeginAnimation(\n    UIElement.OpacityProperty,\n    new DoubleAnimation(0d, 1d, TimeSpan.FromSeconds(1d)));	0
3697966	3697517	How to handle KeyEvents in a DataGridViewCell?	private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n  DataGridViewTextBoxEditingControl tb =(DataGridViewTextBoxEditingControl)e.Control;\n  tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);\n\n  e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);\n}\n\n\nprivate void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)\n{\n  //when i press enter,bellow code never run?\n  if (e.KeyChar==(char)Keys.Enter)\n  {\n    MessageBox.Show("You press Enter");\n  }\n}	0
22693836	22693604	C# Regex to parse HTML string and add ids into each header tag?	Regex.Replace("<h2>XYZ</h2>", "<h2>(?<innerText>[^<]*)</h2>", x => string.Format("<h2 id=\"{0}\">{0}</h2>", x.Groups["innerText"]))	0
16365417	16365294	Passing in an object as an out parameter	void FindingObjectType(String str)\n{\n    Object obj;\n    if(isValid(str, out obj)\n         //process\n}	0
7981624	7981517	Pass a parameter to SQL server SP with quotes	using (SqlCommand cmd = new SqlCommand("SomeProcedure", connection) {\n  cmd.Parameters.Add("@Id", SqlDbType.Int).Value = 42;\n  cmd.Parameters.Add("@Text", SqlDbType.Varchar, 50).Value = "A string value";\n  cmd.ExecuteNonQuery();\n}	0
6045667	6045161	How to find out which DataGridView rows are currently onscreen?	public void GetVisibleCells(DataGridView dgv)\n    {\n        var vivibleRowsCount = dgv.DisplayedRowCount(true);\n        var firstDisplayedRowIndex = dgv.FirstDisplayedCell.RowIndex;\n        var lastvibileRowIndex = (firstDisplayedRowIndex + vivibleRowsCount) - 1;\n        for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvibileRowIndex; rowIndex++)\n        {\n            var cells = dgv.Rows[rowIndex].Cells;\n            foreach (DataGridViewCell cell in cells)\n            {\n                if (cell.Displayed)\n                {\n                    // This cell is visible...\n                    // Your code goes here...\n                }\n            }\n        }\n    }	0
24125932	24125812	select all xml child nodes that start with a string	var xDoc = XDocument.Parse(xmlstring);\nvar stores = xDoc.Descendants()\n            .Where(d => d.Name.LocalName.StartsWith("Store"))\n            .ToList();	0
11368421	11368378	Insert rows to DataTable from SQL table	DataTable dttemp = new DataTable();\n\ndataAdapter.Fill(dtTemp);\n\noriginaldatatable.Merge(dtTemp);	0
15362236	15362071	How to convert this LINQ query from methods form to fluent syntax?	( \n from item in items\n select (from fieldName in fieldsNames\n         select item.FieldValues[fieldName]).ToList()\n).ToList();	0
17481668	17481615	Save image to folder and image path to database	if(!Directory.Exists(Application.StartupPath + @"\Photos"))\n         Directory.CreateDirectory(Application.StartupPath + @"\Photos");	0
11375515	11375196	How can I cast to IEnumerable<Guid> in simple.data?	var db = Database.Open();\nIEnumerable<Guid> recetas = db.Factura\n    .All()\n    .Where(db.Factura.ObraSocialPlan_id == obraSocialPlanId)\n    .Select(db.Factura.Id)\n    .ToScalarList<Guid>();	0
13981653	13981596	Declaring interface on abstract base class	public interface IExample\n{\n    string Word { get; set; }\n    void DoIt();\n}\n\npublic abstract class ExampleClass : IExample\n{\n   public string Word { get; set; }\n   public abstract void DoIt();\n}	0
14911565	14911315	Singular Value Decomposition - Social Network Analysis	svdOut* =\n| 1.61803  0        0  0  0 | \n| 0        1.41421  0  0  0 | \n| 0        0        0  0  0 |\n| 0        0        0  0  0 |\n| 0        0        0  0  0 |	0
29403717	29402914	Setting optional values using NDesk.Options	{ "r|repeat:", \n       "the number of {TIMES} to repeat the greeting.\n" + \n          "this must be an integer.",\n        (int v) => repeat = (v != null ? v : 1) },	0
18864745	18864692	How to write a linq statement to check if a record exists then make changes to it?	ButtonColor = cn.OrderDressings\n                .Any(x=>x.OrderID == OrderID &&\n                        x.OrderItemID == ProductID) ? ButtonColor.Green : ButtonColor.Red;	0
6113305	6035604	Generate script from database in c#	Information_Schema.TABLES\nInformation_Schema.COLUMNS\nInformation_Schema.REFERENTIAL_CONSTRAINTS\nInformation_Schema.TABLE_CONSTRAINTS \nInformation_Schema.KEY_COLUMN_USAGE	0
22277011	22276691	Win32 api - how to check if a specified handle is a window? (and isn't a control inside a window)	if (GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD) {\n    // window is a child window\n} else {\n    // window is a top-level window\n}	0
7120486	7117877	how to access romote windows service with Related ObjectQuery	ManagementObjectSearcher moSearcher = new ManagementObjectSearcher();\n            moSearcher.Scope = managementScope;\n            moSearcher.Query = new ObjectQuery("SELECT * FROM win32_Service WHERE Name ='KanAktarim'");\n            ManagementObjectCollection mbCollection = moSearcher.Get();\n\n            foreach (ManagementObject oReturn in mbCollection)\n            {\n                ManagementBaseObject outParams = oReturn.InvokeMethod("StartService", null, null);\n                ManagementBaseObject outParams = oReturn.InvokeMethod("StopService", null, null);\n                string a = outParams["ReturnValue"].ToString();\n\n                string state = oReturn.Properties["State"].Value.ToString().Trim();\n            }	0
1271093	1270553	How to get my .net dll to be referenced in vba/com?	using ...;\n\nnamespace SomeCOMTool\n{\n    [ClassInterface(ClassInterfaceType.AutoDual)]\n    [ProgId("MyCOMTool")]\n    [ComVisible(true)]\n    [Guid("your-guid-here without curly brackets!")]\n    public class MyCOMTool\n    {\n        /// <summary>\n        /// Empty constructor used by Navision to create a new instance of the control.\n        /// </summary>\n        public MyCOMTool()\n        {\n        }\n\n        [DispId(101)]\n        public bool DoSomething(string input, ref string output)\n        {\n        }\n    }\n}	0
30252187	30251785	Want to populate a combobox with two related tables in access	OleDbCommand cmd = new OleDbCommand("SELECT Table1.Cd_AtributosNormais as Cd_AtributosNormais, Table2.Nm_Atr as Nm_Atr FROM Table1 Left outer join Table2 on Table1.Cd_AtributosNormais = Table2.Cd_AtributosNormais", cn);\n            OleDbDataReader reader = cmd.ExecuteReader();\n            DataTable table = new DataTable();\n            table.Load(reader);\n            DataRow row = table.NewRow();\n            row["Nm_Atr"] = "";\n            table.Rows.InsertAt(row, 0);\n\n            this.btCmbAtkBaAtr1.DataContext = table.DefaultView;\n            this.btCmbAtkBaAtr1.DisplayMemberPath = "Nm_Atr";\n            this.btCmbAtkBaAtr1.SelectedValuePath = "Cd_AtributosNormais";\n            cmd.ExecuteNonQuery();\n            reader.Close();\n            reader.Dispose();\n        }\n        catch(Exception ex)\n        {\n            MessageBox.Show(ex.Message);\n        }\n        finally\n        {\n            cn.Close();\n            cn.Dispose();\n        }	0
1607457	1607433	Application.StartupPath contains spaces	var pathJava = "\""+ Application.StartupPath + "\\pathToJavaApp\\javaApp.jar" + "\"";	0
19416137	19415823	XML to database and vice-versa	IEnumerable<XElement> items = d.Descendants("level").Elements();\nstring names = string.Empty;\nstring values = string.Empty;\nforeach (XElement item in items)\n{\n    names += item.Name + ",";\n    values += "@" + item.Name + ",";\n    IDbDataParameter parameter = datacommand1.CreateParameter();\n    parameter.ParameterName = "@" + item.Name;\n    parameter.DbType = DbType.String;\n    parameter.Value = item.Value;\n    datacommand1.Parameters.Add(parameter);\n}\ndatacommand1.CommandText = "INSERT INTO MyTable (" + names.Substring(names.Length - 1) + ") VALUES (" + values.Substring(values.Length - 1) + ");";\ndatacommand1.ExecuteNonQuery();	0
26205950	26205910	How to print word document after edit it	ProcessStartInfo info = new ProcessStartInfo(saveFileDialog1.FileName);\ninfo.Verb = "Print";\ninfo.CreateNoWindow = true;\ninfo.WindowStyle = ProcessWindowStyle.Hidden;\nProcess.Start(info);	0
11649062	11648376	ASP.NET Wizard get Value of Textbox	if(!Page.IsPostBack)\nTextBox1.Text = Initialvalue;	0
6581724	6581632	How to use Flags attribute?	[Flags] \npublic enum ItemTags \n{ \n  Default =0,\n  Browsable = 2, \n  IsInMenu = 4,\n  All = 6 // Browsable / IsInMenu\n}	0
24282060	24280902	c# bit shift task with integers	/// <summary>\n/// Convert an Int32 value into its binary string representation.\n/// </summary>\n/// <param name="value">The Int32 to convert.</param>\n/// <returns>The binary string representation for an Int32 value.</returns>\npublic String ConvertInt32ToBinaryString(Int32 value)\n{\n        String pout = "";    \n        int mask = 1 << 31;\n\n        for (int n = 1; n <= 32; n++)\n        {\n            pout += (value & mask) == 0 ? "0" : "1";\n            value <<= 1;\n            if (n % 4 == 0)\n            {pout += " ";}\n        }\n\n        return pout;\n}	0
11517973	11517927	how to create a many to many linq query in c#?	List<Class1> classOneList = ...\nList<Class2> classTwoList = ...\n\nvar items = classOneList.Where(c1 => c1.Id == 1)\n                        .Where(c1 => !c1.Class2Collection.Any(c2 => c2.Id == 2));	0
20797351	20797152	Wrong in convert four byte to integer then display in textbox	byte[] bb = new byte[4] { 64, 1, 0, 0 }; \ntextBox1.Text = BitConverter.ToInt32(bb, 0).ToString();	0
15584141	15493641	How can I load a property of a navigational property?	var selectedTeacher = from t in selectTemp where t.InstructorFullName == teacher select t;\n\n\n            viewModel.Enrollments = selectedTeacher;	0
8028832	8028814	Get XElement.Value on multiple elements by element name	return new string[] {\n    xe.Element("name").Value,\n    xe.Element("version").Value,\n    xe.Element("beta").Value\n};	0
27519635	27519396	How to query database using LINQ to bring data from database based on array of months in ASP.Net MVC 5?	int[] months = { 1, 2, 3 };\nvar query=  db.TheMonthlyDelivery.Where(x => months.Contains(x.Date.Month));	0
4990536	4988436	MongoDB GridFs with C#, how to store files such as images?	var server = MongoServer.Create("mongodb://localhost:27020");\n var database = server.GetDatabase("tesdb");\n\n var fileName = "D:\\Untitled.png";\n var newFileName = "D:\\new_Untitled.png";\n using (var fs = new FileStream(fileName, FileMode.Open))\n {\n    var gridFsInfo = database.GridFS.Upload(fs, fileName);\n    var fileId = gridFsInfo.Id;\n\n    ObjectId oid= new ObjectId(fileId);\n    var file = database.GridFS.FindOne(Query.EQ("_id", oid));\n\n    using (var stream = file.OpenRead())\n    {\n       var bytes = new byte[stream.Length];\n       stream.Read(bytes, 0, (int)stream.Length);\n       using(var newFs = new FileStream(newFileName, FileMode.Create))\n       {\n         newFs.Write(bytes, 0, bytes.Length);\n       } \n    }\n }	0
18655895	18655685	Telerik grid selection with a Button - MVVM	CommandParamter="{Binding}"	0
27469109	27468954	Change button color for a short period of time from its last click c# WPF	public partial class MainWindow : Window\n    {\n        private Timer timer;\n        public MainWindow()\n        {\n            InitializeComponent();\n            timer = new Timer{Interval = 5000};\n        }\n\n        private void Button_Click(object sender, RoutedEventArgs e)\n        {               \n            timer.Elapsed += HandleTimerTick;\n            myButton.Background = new SolidColorBrush(Colors.LightGreen);\n            timer.Stop();\n            timer.Start();\n        }\n\n        private void HandleTimerTick(object sender, EventArgs e)\n        {\n            Timer timer = (Timer)sender;\n            timer.Stop();\n            myButton.Dispatcher.BeginInvoke((Action)delegate()\n            {\n                myButton.Background = new SolidColorBrush(Colors.Red);\n            });\n        }\n    }	0
29532815	29520318	IsMouseCaptured turns to False	/// <summary>\n    /// Handles pressing Mouse Button over the Control.\n    /// </summary>\n    private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        this.startPoint = e.GetPosition(base.AssociatedObject);\n        base.AssociatedObject.CaptureMouse();\n        e.Handled = true;\n    }	0
4500929	4437338	Reading an xml / incorporating it in to a project - C#	doc.Load(Path.Combine("MyFolder", filename));	0
13017932	13015364	Logging number of rows transfered using script task without using SSIS logging	MasterPackage.dtsx\n                 |             |\n                 |             |\n PackageHandler.dtsx         PackageHandler.dtsx\n        |                           |\n        |                           |\n ChildPackage_1.dtsx         ChildPackage_2.dtsx	0
25155965	25155883	Get App Version Number	string Version = XDocument.Load("WMAppManifest.xml")\n                    .Root.Element("App").Attribute("Version").Value;	0
3770692	3770427	How do I tell my webpage to use a specific UI Culture?	System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");\nSystem.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");	0
7006234	6994566	how to enter the string value in a particular cell of DataGrid in WPF	void OurGrdEditEnding(object sender, DataGridRowEditEndingEventArgs e)\n {\n\n       DataRowView dRowView = e.Row.Item as DataRowView;\n       string sName = dRowView.Row["columnName"].ToString();\n }	0
15512604	15512558	c#.net MS Access database without Access installed	var connection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BC207\test.accdb")	0
15098326	15098143	Using NavigationWindow with Pages	NavigationSerivce.Navigate(App.Page2);	0
29871694	29870598	convert a bitmapImage to byte array for windows store	Async Function bitmapTObyte(ByVal bitmapimage1 As StorageFile) As Task(Of Byte())\n    Dim fileBytes As Byte() = Nothing\n    Using stream As IRandomAccessStreamWithContentType = Await bitmapimage1.OpenReadAsync()\n        fileBytes = New Byte(stream.Size - 1) {}\n        Using reader As New DataReader(stream)\n            Await reader.LoadAsync(CUInt(stream.Size))\n            reader.ReadBytes(fileBytes)\n            Return fileBytes\n        End Using\n    End Using	0
10468360	10331132	While creating charts in hidden Word2010, Excel opens. How to disable this? 	Word.InlineShape wrdInlineShape = doc.InlineShapes.AddOLEObject(classtype, Range: shapeBookMark.Range);\nExcel.Application xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");\nxlApp.Visible = false;\n\nif (wrdInlineShape.OLEFormat.ProgID == classtype)\n{\n    // etc...	0
16103750	16103653	C# Local SQL rows returned if statement	using(SqlCeConnection connection = new SqlCeConnection(.....)) \n{\n     connection.Open();\n     string sqlText = "SELECT Count(*) FROM Technician WHERE Name = @name AND Password=@pwd"\n     SqlCeCommand command = new SqlCeCommand(sqlText, connection);\n     command.Parameters.AddWithValue("@name", txt_username.Text);\n     command.Parameters.AddWithValue("@pwd", txt_password.Text);\n     int result = (int)command.ExecuteScalar();\n     if (result > 0)\n     {\n          MessageBox.Show("Login Successful");\n          System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(MainMenuForm));\n          t.Start();\n          this.Close();\n     }\n     else\n     {\n           MessageBox.Show("Login Unsuccessful");\n           return;\n     }\n }	0
11572002	11571933	How can quickly add two bytes into a bytes array?	Array.Copy	0
5739139	5739095	Null reference exception on column click in datagridview	void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)\n    {\n        var index = e.RowIndex;\n    }	0
19116542	19112965	How to retrieve name of a generic method, including generic types names	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        Load(new Repository<int>());\n        Load(new Repository<string>());\n        Console.ReadLine();\n    }\n\n    class Repository<T> { }\n\n    static List<T> Load<T>(Repository<T> repository)\n    {\n        Console.WriteLine("Debug: List<{1}> Load<{1}>({0}<{1}> repository)", typeof(Repository<T>).Name, typeof(Repository<T>).GenericTypeArguments.First());\n        return default(List<T>);\n    }\n}	0
27623959	27622863	How to Speech.Remove everything but a key word	string[] allowedWords = { "what", "are", "dogs" };\n\nvar speech = "Can you tell me what are dogs?";\n\nvar words = speech.split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nvar cleanSpeech = "";\n\nRegex rgx = new Regex("[^a-zA-Z0-9]");\n\nforeach(var word in words)\n{\n    var cleanWord = rgx.Replace(word , "").ToLower();\n\n    if(allowedWords.Contains(cleanWord))\n       cleanSpeech += word + " ";\n}\n\ncleanSpeech.Trim();	0
2441415	2441405	Converting 8 digit number to DateTime Type	CultureInfo provider = CultureInfo.InvariantCulture;\nstring dateString = "08082010";\nstring format = "MMddyyyy";\nDateTime result = DateTime.ParseExact(dateString, format, provider);	0
567632	567590	Asp.Net Absolute Path of a URL	// Gets the base url in the following format: \n// "http(s)://domain(:port)/AppPath"\nHttpContext.Current.Request.Url.Scheme \n    + "://"\n    + HttpContext.Current.Request.Url.Authority \n    + HttpContext.Current.Request.ApplicationPath;	0
1465390	826851	Dynamic map layer with Mapserver's C# MapScript	myLayer.type = OSGeo.MapServer.MS_LAYER_TYPE.MS_LAYER_LINE;\nmyLayer.status = 1;\nmyLayer.symbolscaledenom = 1; \n\n// Create a mapping class\nOSGeo.MapServer.classObj myClass = new OSGeo.MapServer.classObj(myLayer);\n\n// Create a style\nOSGeo.MapServer.styleObj style = new OSGeo.MapServer.styleObj(myClass);\n\n// unitColor = new Color(12, 34, 56);\nint red = Convert.ToInt32(unitColor.R);\nint green = Convert.ToInt32(unitColor.G);\nint blue = Convert.ToInt32(unitColor.B);\n\nstyle.color.setRGB(red, green, blue);\n\nstyle.outlinecolor.setRGB(255, 255, 255);\n//style.symbol = _map.symbolset.index("circle");  // Here '_map' is an instance of mapObj, this line is not strictly necessary \n\nstyle.size = 10;\nstyle.minsize = 3; // Change this to your needs	0
3906395	3906260	How can I convert a JPEG image to a PNG one with transparent background?	using (Image img = Image.FromFile(filename))\nusing (Bitmap bmp = new Bitmap(img))\n{\n    for (int x = 0; x < img.Width; x++)\n    {\n        for (int y = 0; y < img.Height; y++)\n        {\n            Color c = bmp.GetPixel(x, y);\n            if (c.R == 255 && c.G == 255 && c.B == 255)\n                bmp.SetPixel(x, y, Color.FromArgb(0));\n        }\n    }\n    bmp.Save("out.png", ImageFormat.Png);\n}	0
15091121	15091094	Removing empty bytes from List<byte>	myList.RemoveAll(b => b == 0);	0
4789272	4788157	Fluent NHibernate mapping for read only properties	PropertyInfo.CanWrite	0
23034496	23005404	Service Stack Kill a HTTP request in filter	this.RequestFilters.Add((req, res, requestDto) =>\n{                \n    var access_token = req.Headers.GetValues("token");\n    if(access_token == null || String.IsNullOrEmpty(access_token[0]))\n    {\n        throw new UnauthorizedAccessException();\n    }	0
4664990	4663818	How can a winforms application accept user input without having focus?	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        this.TopMost = true;\n    }\n    protected override CreateParams CreateParams {\n        get {\n            var cp = base.CreateParams;\n            cp.ExStyle |= 0x08000000; // Turn on WS_EX_NOACTIVATE;\n            return cp;\n        }\n    }\n}	0
1060454	1060442	png to bmp	Image Dummy = Image.FromFile("image.png");\nDummy.Save("image.bmp", ImageFormat.Bmp);	0
17161990	17161897	c# How to write to a ini file	public class IniFile\n  {\n    public string path;\n\n    [DllImport("kernel32")]\n    private static extern long WritePrivateProfileString(string section,\n      string key,string val,string filePath);\n\n    [DllImport("kernel32")]\n    private static extern int GetPrivateProfileString(string section,\n      string key,string def, StringBuilder retVal,\n      int size,string filePath);\n\n    public IniFile(string INIPath)\n    {\n      path = INIPath;\n    }\n\n    public void IniWriteValue(string Section,string Key,string Value)\n    {\n      WritePrivateProfileString(Section,Key,Value,this.path);\n    }\n\n    public string IniReadValue(string Section,string Key)\n    {\n      StringBuilder temp = new StringBuilder(255);\n      int i = GetPrivateProfileString(Section,Key,"",temp,255, this.path);\n      return temp.ToString();\n    }\n  }	0
17497489	17479107	Cannot set Opacity property on ScatterViewItem after an animation has been performed	public void HideShape()\n{\n    if (this.TangibleShape != null)\n    {\n        DoubleAnimation animation = new DoubleAnimation();\n        animation.From = 1.0;\n        animation.To = 0.0;\n        animation.AutoReverse = false;\n        animation.Duration = TimeSpan.FromSeconds(1.5);\n        animation.FillBehavior = FillBehavior.Stop; // needed\n\n        Storyboard s = new Storyboard();\n        s.Children.Add(animation);\n\n        Storyboard.SetTarget(animation, this.TangibleShape.Shape);\n        Storyboard.SetTargetProperty(animation, new PropertyPath(ScatterViewItem.OpacityProperty));\n\n        s.Completed += delegate(object sender, EventArgs e)\n        {\n            // call UIElementManager to finally hide the element\n            UIElementManager.GetInstance().Hide(this.TangibleShape);\n            this.TangibleShape.Shape.Opacity = 0.0; // otherwise Opacity will be reset to 1\n        };\n        s.Begin(this.TangibleShape.Shape); // moved to the end\n    }\n}	0
1796877	1796873	how to save Web C# Bitmap object to Server disk	Bitmap.Save	0
32173630	32173255	Unable to connect to the remote server with hotmail	smtpClient.Port = 587;\n smtpClient.EnableSsl = true;	0
26747279	26746893	Can I select a div by value in HtmlAgilityPack?	//div[contains(.,'foo:')]	0
18727646	18727548	Normalize xml data to object linq to xml	from planInfo in root.Descendants("plan")\ngroup planInfo by (string)planInfo.Element("plantitle") into g\nselect new QuotePlanMbp {\n   Name = g.Key,\n   QuoteTerms = \n      (from planTerm in g\n       let months = (int?)planTerm.Element("plancoveredterm")\n       select new QuoteTermMbp {\n           TermMonths = months.GetValueOrDefault(),\n           TermMiles = (int)((int?)planTerm.Element("plancoveredmiles") ?? 0),\n           TermCost = ((int?)planTerm.Element("plancost")).GetValueOrDefault()\n       }).ToList<QuoteTermMbp>()\n};	0
15217387	15216835	File Download from Ftp server with case insencitive match c#	FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");\nrequest.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");\nrequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;\n\nusing(var response = (FtpWebResponse)request.GetResponse())\n  using(var responseStream = response.GetResponseStream())\n    using(var reader =  new StreamReader(responseStream))\n    {\n      Console.WriteLine(reader.ReadToEnd());\n    }	0
21845763	21845486	How to prevent parent window from going into background after child is closed?	Topmost=true	0
10674208	10674027	Outlook C# - How do I determine if user replied to a message?	string SchemaTransportHeader = @"http://schemas.microsoft.com/mapi/proptag/0x10820040";\n\nstring repliedOn =  oMailItem.PropertyAccessor.GetProperty(SchemaTransportHeader).ToString();	0
4097959	4097896	c# datagridview datasource	this.Controls.Add(dgv);\nMessageBox.Show(dgv.Rows.Count.ToString());	0
15280919	15280721	C# callback from C++ gives access violation	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]\npublic delegate void InstallStatusDel([MarshalAs(UnmanagedType.LPStr)]string Mesg, int Status);	0
19465729	19464532	Difficulties with dynamically identifying enum member	public enum Levels\n{\n    LevelState1 = 1,\n    LevelState2 = 2,\n    LevelState3 = 3\n}\nprivate Levels currentLevel;\npublic void ChooseLevel(int state)\n{\n    currentLevel = (Levels)state; // casting to enum from int\n    // process level or whatever here\n}\n\n//The variable CurrentLevel is an integer\nChooseLevel(game1.CurrentLevel);	0
14499215	14499195	Dynamic Control names in C#	var studentControls = new List<Control>();\nstudentControls.Add(student1); \nstudentControls.Add(student2);\n...\nfor (int i = 0; i < students.Length; i++)\n{\n    studentControls[i].Text = students[i];\n}	0
6128745	6127259	using .NET resources without building	ResourceManager.CreateFileBasedResourceManager	0
8443400	8442223	How to activate Developer tab in Powerpoint 2010 programmatically?	HKCU\Software\Microsoft\Office\14.0\PowerPoint\Options\DeveloperTools = 1	0
2934125	2927834	Get a list of documents from Mongo DB	var mongo = new Mongo();\nvar queryable = mongo["db"]["collection"].AsQueryable();\nvar in = from d in queryable where d.Key("foo").In("bar", "baz") select d;	0
20573128	20572596	Get instance of a class using generics	class MoveUnitVisualPlayerCommand: IVisualPlayerCommand, IPlayerCommand {} \nservices = new Dictionary<object, object>();\nthis.services.Add(typeof(IPlayerCommand ), new MoveUnitVisualPlayerCommand());	0
18644452	18644402	Going to a specific page number in a GridView paging feature	protected void btnGo_Click(object sender, EventArgs e)\n    {\n        GridView1.PageIndex = Convert.ToInt16(txtGoToPage.Text) -1; //since PageIndex starts from 0 by default.\n        txtGoToPage.Text = "";\n        GridView1.DataBind()\n    }	0
4569248	4569205	LINQ: Get the data from the Dictionary in c#	var result = l_dictRawData.Where(pair => pair.Value.SequenceEqual(l_lstInput))\n                          .Select(pair => pair.Key)\n                          .FirstOrDefault();	0
10320223	10320090	C# - Parse Year/Month from multiple files, run program and create new file in subfolders (year/month)	String filename = "2012-4-24.log";\n  String file = Path.GetFileNameWithoutExtension(filename);\n  String[] parts = file.Split('-');\n  if (parts.Length == 3)\n  {\n    String year = parts[0];\n    String month = parts[1];\n    String day = parts[2];\n\n    Console.WriteLine(string.Format("year:{0} - month:{1} - day:{2}", year, month, day));\n  }	0
912968	912948	SqlDataReader - How to convert the current row to a dictionary	// Need to read the row in, usually in a while ( opReader.Read ) {} loop...\nopReader.Read();\n\n// Convert current row into a dictionary\nDictionary<string, object> dict = new Dictionary<string, object>();\nfor( int lp = 0 ; lp < opReader.FieldCount ; lp++ ) {\n    dict.Add(opReader.GetName(lp), opReader.GetValue(lp));\n}	0
15458236	15458200	How to go from one exception handler to another?	Exception ex = null;\ntry\n{\n    //Do work\n}\ncatch (SqlException sqlEx)\n{\n    ex = sqlEx;\n    if (ex.Number == -2)\n    {\n       //..\n    }\n    else\n    {\n        //..\n    }\n}\ncatch (Exception generalEx)\n{\n  ex = generalEx;\n}\nfinally()\n{\n  if (ex != null) debugLogGeneralException(ex);\n}	0
14483264	14468985	Getting the friendly name for a Process after starting it	var startInfo = new ProcessStartInfo { FileName = "notepad.exe" };\nvar process = new Process();\nprocess.StartInfo = startInfo;\nprocess.Start();\nvar friendlyName = Path.GetFileNameWithoutExtension(startInfo.FileName);	0
11127611	11127475	SelectedIndices Changed Listbox	foreach (var item in listBox1.SelectedItems)\n{\n    if ((item as Curve).newName == null)\n    {\n        int index = listBox1.SelectedItems.IndexOf(item);\n        listBox1.SetSelected(index, false);\n    }\n}	0
14056998	14056766	Keeping HTTP Basic Authentification alive while being redirected	CredentialCache myCache = new CredentialCache();\n\nmyCache.Add(\nnew Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));\nreq.Credentials = myCache;	0
21414043	21413777	Locking async method in windows phone 7	return _navigateToDropBoxUploadCommand = _navigateToDropBoxUploadCommand ?? new RelayCommand(\n    async () =>\n    {\n        myButton.IsEnabled = false;\n        await UploadDataToDropbox("sandbox");\n        myButton.IsEnabled = true;\n    });	0
17154708	17154626	Concurent foreach iteration of two list strings	for (int i = 0; i < alpha.Count; i++)\n    {\n        var itemAlpha = alpha[i] // <= your object of list alpha\n        var itemBeta = beta[i] // <= your object of list beta\n        //write your code here\n    }	0
22323848	22321771	Convert string to a UI element name - Win 8	var ach = (CheckBox)this.FindName(arr[0]);	0
16672853	16672803	Formatting plain text in C#	"Hello World! \r\n" + someStringVar + "\t Goodbye!"	0
18746198	18746121	write values in a .txt file in C#	string name;\nint number1,number2;\n// Read name, number1, number2 from Console\n//.....\n//.....\n\n//Saving in a file:\nstring outputFileName = @"c:\myfile.txt"\nStreamWriter sw = new StreamWriter(outputFileName);\nsw.WriteLine(string.Format("{0},{1},{2}",name,number1,number2));\nsw.Close();	0
3965333	3965304	Disable sorting when clicking DataGridView column header	protected override void OnColumnAdded(DataGridViewColumnEventArgs e)\n    {\n        base.OnColumnAdded(e);\n        e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;\n    }	0
30460799	30460749	Using default generic values in C#	public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql)\n{\n  IEnumerable<T> results = Enumerable.Empty<T>();\n  using (var database = new SqlConnection("[ConnectionString]"))\n  {\n    database.Open();\n    results = await database.QueryAsync<T>(sql);                        \n  }\n  return results;\n}	0
28171820	28171394	how to draw captcha image from other web site	string responseString = null;\nusing(StreamReader reader = new StreamReader(response.GetResponseStream())\n{\n    responseString = reader.ReadToEnd();\n    // ...\n}	0
3343769	199761	How can you use optional parameters in C#?	public void SomeMethod(int a, int b = 0)\n{\n   //some code\n}	0
4986573	4986563	How to read a method body with reflection	MethodInfo.GetMethodBody	0
3493648	3493618	can someone explain this to me	ScheduleTimes \n===============\nScheduleTimesID  <-- PK\nStartDate\nStopDate\n\nScheduleUsers\n===============\nScheduleUsersID  <-- PK\nUserID           <-- FK to Users table\nScheduleTimesID  <-- FK to ScheduleTimes table\n\nUsers\n=======\nUserID           <-- PK\nUsername\n...	0
19905065	19854253	Sum up column values in datagrid based on the value of another column in c# windows	double sumP = 0;\ndouble sumF = 0;\n\nfor (int i = 6; i < dataGridView1.Rows.Count-1; ++i)\n{\n    if (dataGridView1.Rows[i].Cells[6].Value.Equals("P"))\n    {\n        sumP += Convert.ToDouble(dataGridView1.Rows[i].Cells[9].Value);\n    }\n    else if (dataGridView1.Rows[i].Cells[6].Value.Equals("F"))\n    {\n        sumF += Convert.ToDouble(dataGridView1.Rows[i].Cells[9].Value);\n    }\n}\n\nIf(sumF>sumP)\n{\n    Label2.text="Fail";\n}\nelse\n{\n    label2.text="Pass";\n}	0
6125443	6125406	General Lambda syntax question	List<object> values = new List<object>();\n        values.ForEach(value =>\n                           {\n                               System.Diagnostics.Debug.WriteLine(value.ToString());\n                               System.Diagnostics.Debug.WriteLine("Some other action");\n                           }\n\n            );	0
15896405	15896244	Apply style and template controls in c# WPF XAML	window.resources	0
34210521	34209825	How to combine multiple lists and use as a GridView datasource	List<dynamic> lstName = new List<dynamic>();\n        List<dynamic> lstCMSID = new List<dynamic>();\n        List<dynamic> lstSpecialtyPhys = new List<dynamic>();\n\n        lstName.Add("John Doe");\n        lstCMSID.Add("56");\n        lstSpecialtyPhys.Add("90");\n\n        lstName.Add("James Coon");\n        lstCMSID.Add("34");\n        lstSpecialtyPhys.Add("24");\n\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Name");\n        dt.Columns.Add("Number");\n        dt.Columns.Add("Value");\n\n        for (int i = 0; i < lstName.Count; i++)\n        {\n            dt.Rows.Add(lstName[i], lstCMSID[i], lstSpecialtyPhys[i]);\n        }\n\n        gvSP.DataSource = dt;\n        gvSP.DataBind();	0
22937076	22937049	Dictionary with multiple values for each key?	Dictionary<string,List<Order>>	0
15496737	15496157	How to process text from textbox/richtext box in C# using regular expression and more	List<string> myList1 = new List<string>();\n        List<string> myList2 = new List<string>();\n\n        string rawInput = txtInput.Text;            \n\n        foreach (string line in txtInput.Lines)\n        {\n            string firstPortion = "";\n            string secondPortion = "";\n\n            string[] splitInput = Regex.Split(line, ("\\s+"));\n            firstPortion = splitInput[0];\n            secondPortion = splitInput[1];\n\n            myList1.Add(firstPortion);\n            myList2.Add(secondPortion);\n\n            txtOutPut.Text = "modified " + myList1.LastOrDefault() + "  " + myList2.LastOrDefault() + "\r\n";\n        }	0
31175621	31158535	Need class for custom config in app.config of collection refering another	class Program\n{\n    static void Main(string[] args)\n    {\n        List<Activity> activities = new List<Activity>();\n    }\n}\n\npublic class Activity\n{\n    public string Name { get; set; }\n    List<Task> Tasks { get; set; }\n}\n\npublic class Task\n{\n    public string Name { get; set; }\n    public string Type { get; set; }\n    public Priority Priority { get; set; }\n}\n\npublic class Priority\n{\n    public string Name { get; set; }//--or however you want to structure this class, this could also be an enum\n}	0
1784599	1784564	display number with commas and decimal points	Label9.Text = sisRatio.ToString("#,##0.##");	0
31264014	31241240	How to open a link in a native browser from CefSharp 3	bool IRequestHandler.OnBeforeBrowse(IWebBrowser browserControl,\n IBrowser browser, IFrame frame, IRequest request, bool isRedirect)\n         {\n             // If the url is Google open Default browser\n             if (request.Url.Equals("http://google.com/"))\n             {\n                 // Open Google in Default browser \n                 System.Diagnostics.Process.Start("http://google.com/");\n                 return true;\n             }else\n             {\n                 // Url except Google open in CefSharp's Chromium browser\n                 return false;\n             }\n         }	0
21482995	21465624	Setting MIDI Tempo in a MIDI file with NAudio	var evt = new TempoEvent(midiTempo, 0)	0
12694916	12694879	How can I pull in all xml nodes that are one of two types of nodes with Linq-to-xml?	contentDiv.Parent.Parent.Parent.Parent.Parent.Elements()\n          .Where(x => x.Name.LocalName == "p" || x.Name.LocalName == "ul")\n          .ToList();	0
33020545	33014878	C# sha256 into PHP	base64_encode(hash('sha256', 'rosnicka'.base64_decode('zxwqTy+XjaY='), true));	0
23081700	23080362	calling async methods from sync service layer boundary	public void ProcessOrder()\n{\n    // other stuff...\n\n    // initiate the IO-bound operation\n    var task = _publisher.PublishAsync(new ItemOrderedEvent() {});\n    {\n        MessageId = Guid.NewGuid(),\n        IsDurable = true,\n    }); // do not call .Wait() here\n\n    // do your work\n    for (var i = i; i < 100; i++)\n        DoWorkItem(i);\n\n    // work is done, wait for the result of the IO-bound operation\n    task.Wait(); \n}	0
1112856	1112842	How do i convert hexadecimal value from string to int?	using System;\nusing System.Globalization;\n\npublic class StrToInt {\n    public static void Main(string[] args) {\n        string val = "FF";\n        int num = Int32.Parse(val, NumberStyles.AllowHexSpecifier);\n        Console.WriteLine(num);\n    }\n}	0
12610761	12610618	c# - How to split a string	string s = "The Electors shall meet in their respective states to vote by ballot for President and Vice-President.";\n\nstring sSub = s.Substring(0,60);  //first 60 letters\n\nstring sSubSub = sSub.Substring(0,30);  //at most 30 per string\n\nint index = sSubSub.LastIndexOf(' '); //finds the last space\n\nstring firstString = sSub.Substring(0,index); //first string is up until that space of t he 60-letter string\n\nstring secondSTring = sSub.Substring(index + 1, 30); //second string is the first 30 letters of the rest of the 60-letter string	0
7783775	7783682	getting a specific field values from lucene	Term curTerm = iReader.Term();\nbool hasNext = true;\nwhile (curTerm != null && hasNext)\n{\n    //do whatever you need with the current term....\n    hasNext = iReader.Next();\n    curTerm = iReader.Term();\n}	0
4351866	4351758	Reading struct from NameValueCollection	var contact = (ContactVariable)Context.Request.Params[str];	0
32406824	32406598	Paging a Gridview with Linq	// Paginate //\n    Employees = Employees.Take(11).Skip(0);	0
5749290	5749086	Is there a way to find out how much space in isolated storage you app is using on WP7?	IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();\nlong usedBytes = isf.Quota - isf.AvailableFreeSpace;	0
29640322	29639901	SQL Request with Timestamp	// Somewhere in your class declaration:\n// Fixed parameterized query text as a constant.\nprivate const string TimeRangeQuerySQL = \n    "SELECT COUNT(TimeStamp) FROM net WHERE Timestamp BETWEEN @starttime AND @endtime";\n\n// ...\nvar cmd = new SqlCommand(TimeRangeQuerySQL, sqlCon);\ncmd.Parameters.Add("@starttime", SqlDbType.DateTime).Value = Starttime;\ncmd.Parameters.Add("@endtime", SqlDbType.DateTime).Value = Endtime;\n\nvar reader = sqlCmd.ExecuteReader();\n\n// ...	0
476520	476485	Problem applying texture to square in OpenGL	glEnable( GL_TEXTURE_2D );	0
17379665	17379482	Get values between curly braces c#	s.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)	0
6896452	6894100	How to use the derived type in a generic collection from an abstract class (C#)?	public class MyCollection<T> where T : MyItemBase<T>\n{\n    public void Call(MyItemBase<T> item) { }\n}\n\npublic abstract class MyItemBase<T> where T : MyItemBase<T>\n{\n    protected MyCollection<T> _collection;\n\n    protected MyItemBase(MyCollection<T> collection)\n    {\n        _collection = collection;\n    }\n\n    public void DoSomething()\n    {\n        _collection.Call(this);\n    }\n}\n\npublic class MyItem : MyItemBase<MyItem>\n{\n    public MyItem(MyCollection<MyItem> Collection)\n        : base(Collection)\n    {\n    }\n}	0
12819941	12819855	How to Enable/Disable a button in VB.Net depending on value?	Private Sub Class_1_loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded\nIf dzien = 0 Then\n   Button2.Enabled = False\nElse \n   Button2.Enabled = True\nEnd Sub	0
14114751	14114509	Converting an array of 2 consecutive bytes to integers faster	byte[] b = new byte[]{1, 2, 3, 4};\nshort[] s = new short[2]; // 4 bytes long\nBuffer.BlockCopy(b, 0, s, 0, 4);	0
21267030	21173084	How to set up .net teradata connection in c#?	TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();\nconnectionStringBuilder.DataSource = "x";\nconnectionStringBuilder.Database = "DATABASENAME";\nconnectionStringBuilder.UserId = "y";\nconnectionStringBuilder.Password = "z";\nconnectionStringBuilder.AuthenticationMechanism = "LDAP";\n\nusing (TdConnection cn = new TdConnection())\n{\n    cn.ConnectionString = connectionStringBuilder.ConnectionString;\n    cn.Open();\n\n    TdCommand cmd = cn.CreateCommand();\n    cmd.CommandText = "SELECT DATE";\n\n    using (TdDataReader reader = cmd.ExecuteReader())\n    {\n        reader.Read();\n        DateTime date = reader.GetDate(0);\n        Console.WriteLine("Teradata Database DATE is {0}", date);\n    }\n}	0
21383146	21383045	convert string to datetime with form yyyy-MM-dd HH:mm:ss in C#	DateTime date = DateTime.ParseExact("2010-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);\nstring formattedDate = date.ToString("yyyy-MM-dd HH:mm:ss")\nConsole.WriteLine(formattedDate);	0
18945958	18945957	Unable To set row visible false of a datagridview	CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[MyGrid.DataSource];\n    currencyManager1.SuspendBinding();\n    MyGrid.Rows[5].Visible = false;\n    currencyManager1.ResumeBinding();	0
12298721	12298515	Best format for lossless image compression in C#	JPEG 2000R  JPEG-LS L-JPEG  PNG \nbike    1.77        1.84    1.61    1.66\ncafe    1.49        1.57    1.36    1.44\ncmpnd1  3.77        6.44    3.23    6.02\nchart   2.60        2.82    2.00    2.41\naerial2 1.47        1.51    1.43    1.48\ntarget  3.76        3.66    2.59    8.70\nus      2.63        3.04    2.41    2.94\naverage 2.50        2.98    2.09    3.52	0
19383044	18929792	How to handle this code in Many-One in linq	var result = from item in db.Table1\n                           .Include(a=> a.Table2)\n                   select new { item};	0
15123239	15121983	How can I get the information from the details tab of the file properties dialog in Windows?	var image = System.Drawing.Image.FromFile(@"C:\your\image\here");\n\n        foreach (var a in image.PropertyItems)\n        {\n            dynamic value;\n\n            switch (a.Type)\n                {\n                case 2:\n                    value = Encoding.ASCII.GetString(a.Value);\n                    break;\n                case 3:\n                    value = BitConverter.ToInt16(a.Value, 0);\n                    break;\n                case 4:\n                    value = BitConverter.ToInt32(a.Value, 0);\n                    break;\n                default:\n                    value = "NaN";\n                    break;\n                }\n\n            Console.WriteLine("Type: {0} \r\n Value: {1}", a.Type, value);\n        }	0
16844105	16843993	What is the best way for the layout to extract data from a page?	public class ParentViewModel\n{\n      public string SomeSharedField { get; set; }\n}\n\npublic class ChildViewModel : ParentViewModel\n{\n      public string SomeFieldJustForChild { get; set; }\n}	0
6289134	5851229	How to check in sharepoint if user is authenticated by Claims?	SPClaimProviderManager.IsEncodedClaim(SPContext.Current.Web.CurrentUser.LoginName)	0
27010523	27010522	SerializationBinder to ignore unknown types from foreign assembly	sealed class MyAsemblyBinder : System.Runtime.Serialization.SerializationBinder\n    {\n        public override Type BindToType(string assemblyName, string typeName)\n        {\n            string myAsm = System.Reflection.Assembly.GetExecutingAssembly().FullName;\n\n            Type foundType = Type.GetType(String.Format("{0}, {1}", typeName, myAsm));\n\n            if (foundType == null)\n                foundType = typeof(Object);\n\n            return foundType;\n        }\n    }	0
22409377	22382135	db4o: How to retrieve objects from DB without having the original class in c#?	IQuery query = container.Query();\nIEnumerable allObjects = query.Execute();\n\nforeach(Object item : allObjects){\n\n    GenericObject dbObject = (GenericObject)item; // Note: If db4o finds actuall class, it will be the right class, otherwise GenericObject. You may need to do some checks and casts\n    dbObject.GetGenericClass().GetDeclaredFields(); // Find out fields\n    object fieldData = dbObject.Get(0); // Get the field at index 0. The GetDeclaredFields() tells you which field is at which index\n}	0
26148501	26134726	LINQ query to update property of a list	(from s in List select s).ToList().ForEach((s) =>\n    {\n        s.IsActive = false;\n        if(s.TestList != null) //This check of TestList was missing\n            (from t in s.TestList where t != null select t).ToList().ForEach((t) =>\n                        {\n                                    t.IsActive = false;\n                        });\n    });	0
3320667	3320641	How to compile just one file in c#?	#include	0
21282709	21282593	add click event to many control	private void Form1_Load(object sender, EventArgs e)\n{\n    panel1.Controls.OfType<Label>().ToList().ForEach(l => l.Click += label_Click);\n}\n\nprivate void label_Click(object sender, EventArgs e)\n{\n    ChangeToTextbox(sender);\n}	0
30322220	30242861	How to change all imageTag src path in CsQuery	CQ HtmlContainingImg = html;\n    foreach (var img in HtmlContainingImg["IMG"])\n       {\n         string imgsrc = img.Attributes["src"];\n         if (!IsAbsoluteUrl(imgsrc))\n           {\n  img.Attributes["src"]= Setting.FelApplicationPath + Setting.folderPath + imgsrc;\n             }\n       }\n html=  HtmlContainingImg.Render(); // I was missing this line	0
5261614	5239832	Insert an image into RTF document in C#	internal void InsertImage(Image img)\n{\n    IDataObject obj = Clipboard.GetDataObject();\n    Clipboard.Clear();\n\n    Clipboard.SetImage(img);\n    this.Paste();\n\n    Clipboard.Clear();\n    Clipboard.SetDataObject(obj);\n}	0
13332669	13332548	XML parsing C# using LINQ	var houses = from house in document.Descendants("house")\n                select new RowData\n                {\n                    number = (int)house.Attribute("nbr"),\n                    city = (string)house.Attribute("city"),\n                    owner = (string)house.Attribute("owner")\n                };	0
12980007	12961715	Serializing a composite id into binary	public sealed class Id\n{\n    public int p0 { get; set; }\n    public byte[] p1to7 { get; set; }\n}	0
5601395	5601269	Non-invocable member cannot be used like a method	strTomorrow = DateTime.Today.AddDays(1).ToString("yyyyMMdd");	0
9937774	9937405	Findings the Unmatched Strings	var vardiff =( a.Split(new char[] { ' ' }).Except(b.Split(new char[] { ' ' }))).ToList<string>();\n        var vardiff1 = (b.Split(new char[] { ' ' }).Except(a.Split(new char[] { ' ' }))).ToList<string>();	0
20133391	20133108	How to set number of items in owner-drawn listbox	listVersions.DataSource = entries	0
23524652	23524335	RedirectToAction with Parameters?	routeValues: new { langId = id};	0
4086232	4086141	Modifying a Dictionary	Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();\n        dic.Add("k1", new List<string>() { "1", "2", "3", "4", "5" });\n        dic.Add("k2", new List<string>() { "7", "8" });\n        dic.Add("k3", new List<string>());\n\n        var max = dic.Max(x => x.Value.Count);\n        dic.ToDictionary(\n            kvp => kvp.Key,\n            kvp =>\n            {\n                if (kvp.Value.Count < max)\n                {\n                    var cnt = kvp.Value.Count;\n                    for (int i = 0; i < max - cnt; i++)\n                        kvp.Value.Add("");\n                }\n                return kvp.Value;\n            }).ToList();	0
827653	827644	How do I share IDisposable resources within a class?	using (SQLiteConnection sqlite_conn = new SQLiteConnection(connectionString))\nusing (SQLiteCommand sqlite_cmd = new SQLiteCommand())\n{\n    sqlite_conn.Open();\n\n    sqlite_cmd.Connection = sqlite_conn;\n    sqlite_cmd.CommandText = "INSERT INTO SOMETHING SOMETHING;";\n    sqlite_cmd.ExecuteNonQuery();\n} // no need to call .Close(): IDisposable normally handles it for you	0
12067596	12067520	vs2010 web application package deploy.cmd - specify application pool	msdeploy.exe \n  -verb:sync -source:appHostConfig="Default Web Site" \n  -enableLink:AppPoolExtension \n  -dest:package=site.zip \n  -declareParam:name="Application Pool",\n       defaultValue="Default Web Site",\n       description="Application pool for this site",\n       kind=DeploymentObjectAttribute,\n       scope=appHostConfig,\n       match="application/@applicationPool	0
30849312	30849073	Getting 302 response headers from Ajax.BeginForm?	return new JsonResult { \n     JsonRequestBehavior = JsonRequestBehavior.AllowGet,\n     Data = new { Location = Url.Action("ActionName") }};	0
24684125	24678191	How to get the resolution of screen (width and height) in Windows Phone 8.1?	Window.Current.Bounds	0
11902288	11881484	ItemAdded how to detect if the item being added is the documentset itself or a file into the document library	string contentTypeName = properties.ListItem.ContentType.Name;\n            if (contentTypeName == "contentypename")\n            {	0
13255670	13255599	How to get location of current culture's satellite assembly?	var subfolder = System.Threading.Thread.CurrentUICulture.Name;	0
23267322	23266687	ASP.NET Web API multiple post messages single controller or action	public HttpResponseMessage Post([FromBody]XElement xmlbody) { \n    // Process the xmlbody \n    return new HttpResponseMessage(HttpStatusCode.Created); \n}	0
21405802	21405640	Reading values from a string into an array in c#	var polygons = JsonConvert.DeserializeObject<List<List<Point>>>(polys);\n\n// polygons is a List<List<Point>>\n\nforeach (var polygon in polygons)\n{\n    // polygon is a List<Point>\n}	0
26896824	26896449	Failing to retrieve the third td nodes in an html list	var result = doc.DocumentNode.SelectNodes("//ul[@id='features']/li/*//td[last()]")\n                .Select(td => td.InnerText)\n                .ToList();	0
22721296	22721050	What's the best way to split a list of strings to match first and last letters?	int min = 5;\n int max = 7;\n var results = str.Split()\n                     .Where(s => s.Length >= min && s.Length <= max)\n                     .GroupBy(s => new { First = s.First(), Last = s.Last()});	0
11264627	11262770	How to share attributes between properties of different classes	public abstract class ElementBase\n{\n}\n\npublic class ElementOne : ElementBase\n{\n}\n\npublic class ElementTwo : ElementBase\n{\n    public SubElementList SubElements { get; set; }\n}\n\npublic class SubElementList\n{\n    [XmlElement("element-one", typeof(ElementOne))]\n    [XmlElement("element-two", typeof(ElementTwo))]\n    public ElementBase[] Items { get; set; }\n}\n\n[XmlRoot("root-element")]\npublic class RootElement\n{\n    public SubElementList SubElements { get; set; }\n}	0
27679322	27678935	how to prepare a string to be inserted into MySQL e.g. add backslash	MySql.Data.MySqlClient.MySqlHelper.EscapeString()	0
11760317	11760080	Group items by total amount	class Less7Holder\n{\n   public List<int> g = new List<int>();\n   public int mySum = 0;\n}\n\nvoid Main()\n{\n    List<int> nu = new List<int>();\n    nu.Add(2);\n    nu.Add(1);\n    nu.Add(3);\n    nu.Add(5);\n    nu.Add(2);\n    nu.Add(1);\n    nu.Add(1);\n    nu.Add(3);\n\n    var result  = nu .Aggregate(\n       new LinkedList<Less7Holder>(),\n       (holder,inItem) => \n       {\n          if ((holder.Last == null) || (holder.Last.Value.mySum + inItem >= 7))\n          {\n            Less7Holder t = new Less7Holder();\n            t.g.Add(inItem);\n            t.mySum = inItem;\n            holder.AddLast(t);\n          }\n          else\n          {\n            holder.Last.Value.g.Add(inItem);\n            holder.Last.Value.mySum += inItem;\n          }\n          return holder;\n       },\n       (holder) => { return holder.Select((h) => h.g );} );\n\n   result.Dump();\n\n}	0
11907244	11906976	how to create text image on the fly and embed it with email	//... other System.Net.Mail.MailMessage creation code\n// CustomerSignature is a byte array containing the image\nSystem.IO.MemoryStream ms = new System.IO.MemoryStream(CustomerSignature);\nSystem.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();\ncontentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;\ncontentType.Name = "signature.jpg";\nSystem.Net.Mail.Attachment imageAttachment = new System.Net.Mail.Attachment(ms, contentType);\nmailMessage.Attachments.Add(imageAttachment);\nSystem.Net.Mail.LinkedResource signature = new System.Net.Mail.LinkedResource(ms, "image/jpeg");\nsignature.ContentId = "CustomerSignature";\nSystem.Net.Mail.AlternateView aView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailMessage.Body, new System.Net.Mime.ContentType("text/html"));\naView.LinkedResources.Add(signature);\nmailMessage.AlternateViews.Add(aView);	0
8182316	8182188	Interfaces with protobuf-net and C#	[ProtoContract]\nclass Wrapper\n{\n    [ProtoMember(1)]\n    public ILesson5TestInteface1 Content { get; set; }\n}\nstatic class Program\n{\n    static void Main()\n    {\n        Wrapper obj = new Wrapper\n        {\n            Content = new Lesson5TestClass2()\n        }, clone;\n        using(var ms = new MemoryStream())\n        {\n            Serializer.Serialize(ms, obj);\n            ms.Position = 0;\n            clone = Serializer.Deserialize<Wrapper>(ms);\n        }\n        // here clone.Content *is* a Lesson5TestClass2 instance\n    }\n}	0
3047333	2973240	Custom control doesn't fire validation	PostBackOptions options = new PostBackOptions(this);\noptions.PerformValidation = true;\noptions.RequiresJavaScriptProtocol = true;\n\nstring postback = string.IsNullOrEmpty(OnClientClick) ? this.Page.ClientScript.GetPostBackEventReference(options) : OnClientClick;	0
22500484	22500128	Common Elements Sequence	int[] righttarray = new int[] { 6, 3, 8, 1, 5, 3 };\nint[] leftarray = new int[] { 1, 3 };\n\nif (righttarray.Length < leftarray.Length)\n{\n    var result = righttarray.Where((x, i) => righttarray[i] == leftarray[i]);\n}\nelse\n{\n    var result = leftarray.Where((x, i) => leftarray[i] == righttarray[i]);\n}	0
12371285	12371212	Mail dosen't work with multiple to addresss	MailMessage message = new MailMessage();\nmessage.To.Add("sillyjoe@stackoverflow.com");	0
25116718	25113718	Unable to load ViewController from tableview RowSelected in xamarin	// in your controller, when you assign the source\nthis.TableView.Source = new MyTableViewSource(this);\n\n// in your source, keep a class level ref to the parent\nMyTableViewController _parent;\n\n// your Source's constructor\npublic MyTableViewSource(MyTableViewController parent) {\n  _parent = parent;\n}\n\n// finally, in your RowSelected use the _parent reference to access the Nav controller\nvar detailController = new DetailViewController ();\n_parent.NavigationController.PushViewController(detailController, true);	0
5689029	5689013	How do I start external Applications in C# WPF?	Process.Start("path/to/your/file")	0
32972349	32659063	Swashbuckle: Swagger UI: Custom API Action	[HttpPost]	0
18382803	18381817	Optional parameters ?must be a compile-time constant?	literal double Invalid = -1;	0
15255063	15254990	Loading raw data into a Bitmap - what have I done wrong?	for(int i = 0; i < bmp.Height; i++) {\n    Marshal.Copy(data, \n        i * bmp.Height,\n        bmpData.Scan0 + i * bmpData.Stride,\n        bmp.Width * 3);\n}	0
1801268	1801264	Centralised settings in C# for multiple programs	string appData = Environment.GetFolderPath(\n    Environment.SpecialFolder.LocalApplicationData));\nstring folder = "MyApplicationName";\nstring fileName = "settings.xml";\nstring path = Path.Combine(Path.Combine(appData, folder), fileName);	0
30390819	30296073	How to run a command tool exe in C# web application?	using System.Diagnostics;\n\nProcess p = new Process();\np.StartInfo.FileName = @"D:\Executable\Projects\MMF\gm1.3.5\gm.exe";\np.StartInfo.Arguments = "convert -define dpx:colorspace=rgb -define tiff:bits-per-sample=16 \"C:\\Documents and Settings\\software\\Desktop\\DPX_Test\\3.dpx\" \"C:\\TEMP_21May2015103216\\3.tiff\"";\np.Start();                \np.WaitForExit();	0
496966	496922	Can I force svcutil.exe to generate data contracts for a WCF service?	[KnownType(typeof(Bar))]\n[DataContract]\npublic class Foo { }	0
16283459	16283374	In EF 4.1 is it possible to set a field to null with a stub entity?	ctx.Entry(myEntity).Property(e => e.myNullableField).IsModified = true;	0
5633367	5434049	Disable ListBoxItem based on the DataContext of another element in the window	var lbi = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(member);	0
22406117	22406000	Find the closest datetime to desired datetime and loop through list in reverse	// quotes is the list of ProviderQuotes\n// reference is the DateTime being used for comparison\nIEnumerable<ProviderQuote> toUse = quotes.TakeWhile(q => q.TimeStamp <= reference)\n                                         .Reverse();\nforeach (ProviderQuote item in toUse)\n{\n    // do something with item\n}	0
9380782	9380723	Struct - changing values fastest as possible	point.X = 7;\npoint.Y = 7;	0
17633178	17633092	Changing color of grid in C# (Windows Phone 8)	public MainPage()\n        {\n            colorPlace.Background = new SolidColorBrush(Color.FromArgb(255, 100, 100, 100));\n            InitializeComponent();    \n        }	0
32849381	32378978	How to identify Property Custom Type in Listener?	...\nif (Persistor.PropertyTypes[i] is CustomType && (Persistor.PropertyTypes[i] as CustomType).UserType is MyUserType)\n    return "Encrypted";\n...	0
7402728	7402685	Sorting the grid view in asp.net	string MysqlStatement = "SELECT MsgID, MsgText, Title, RespondBy, ExpiresBy, OwnerName, Status FROM tbl_message WHERE tbl_user_tbl_organisation_OrganisationID = @Value1 order by MsgID desc";	0
5297583	5297485	Problem checking if any words in a list contain a partial string .net	Request.Params.AllKeys.Any(l => !String.IsNullOrEmpty(l) &&\n                           l.Contains("stringImLookingFor"));	0
23407411	23407237	How to solve encoding issue while getting a page's source code?	HtmlWeb htmlWeb = new HtmlWeb() { \n  AutoDetectEncoding = false, \n  OverrideEncoding = Encoding.GetEncoding("iso-8859-2") \n};	0
11867787	11867659	Add node and elements in xml using C#/Linq	XmlDocument xDoc = new XmlDocument();\n        xDoc.Load("filename.xml");\n\n        foreach (XmlNode xNode in xDoc.SelectNodes("//FeaturedProduct"))\n        {\n            XmlElement newElement = xDoc.CreateElement("newElementName");\n            XmlAttribute newAttribute = xDoc.CreateAttribute("AttributeName");\n            newAttribute.Value = "attributeValue";\n            newElement.Attributes.Append(newAttribute);\n\n            xNode.AppendChild(newElement);\n            xNode.InnerText = "myInnerText";\n        }	0
6238114	6238099	Program Execution + Parameters from a form in C#	Process.Start("nan.exe", @"c:\windows\system32");	0
648573	648555	Is there a good way to use Console.ReadKey for choosing between values without doing a lot of conversion between types?	if char.IsDigit(convertedchoice)\n{\n  int result = convertedchoice - '0';    // char1 - char2 = int, in this case in 0..9\n  return result;\n}\nelse ...	0
24272167	24272007	Data structure for infinite loop	public static IEnumerable<T> LoopForever<T>(this IEnumerable<T> source)\n{\n    while (true)\n        foreach (var item in source)\n            yield return item;\n}	0
29143049	29142898	How to print 0x00000001 from 1	int x = 1;\nConsole.WriteLine(x.ToString("X8"));	0
7464499	7464448	How to read/write on console at the same time using threads	Console.ReadKey()	0
22029335	22029042	updating variable from inside a loop?	List<int[]> theList = new List<int[]>();\ntheList.Add(code);	0
11597936	11597846	Dynamically change properties	public void ChangeIt(string ctrlName, string typ, string prop, string value) {\n     object obj = App.Current.MainWindow.FindName(ctrlName);\n     obj.GetType().GetProperty(prop).SetValue(obj, value);\n}	0
10616194	10615895	convert string array of byte values to a byte array	ToString("x")	0
23866150	23866092	String with strange format to array	string s = "[\"default\",\"direct\"]";\nstring[] result = JsonConvert.DeserializeObject<string[]>(s);	0
17968642	17859888	Retrieving images from ssms Database using relative path and showing image in picture box in C# visual studio 2012?	txtbEOname.Text = (String)PEO.Rows[cmbEOselect.SelectedIndex]["Name"];\n            String folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) +   @"" + PEO.Rows[cmbEOselect.SelectedIndex]["IMAGE"];\n            pBoxOils.Load(folder);	0
28326029	28325606	how to override built in event handler in WPF c#	class TextBoxEx : TextBox\n{\n    protected override void OnTouchUp(System.Windows.Input.TouchEventArgs e)\n    {\n        base.OnTouchUp(e);\n    }\n\n    protected override void OnTouchDown(System.Windows.Input.TouchEventArgs e)\n    {\n       base.OnTouchDown(e);\n    }\n}	0
22006336	22006291	How to Remove TopMost element From ArrayList in C#	ArrayList list = ???\n\n// remove the last item\nlist.RemoveAt(list.Count - 1);	0
8523485	8502849	Generic Cast xAttribute to bool	public static bool TryGetValueFromAttribute<T>(this XElement element, String attName, out T output, T defaultValue)\n    {\n        var xAttribute = element.Attribute(attName);\n        if (xAttribute == null)\n        {\n            output = defaultValue;\n            return false;\n        }\n\n        if(typeof(T) == typeof(bool))\n        {\n            object value = XmlConvert.ToBoolean(xAttribute.Value);\n            output = (T) value;\n\n            return true;\n        }\n\n        output = (T)Convert.ChangeType(xAttribute.Value, typeof(T));\n        return true;\n    }	0
22842888	22841915	How to implement USING statement (disposal) in HttpWebRequest?	using() {}	0
31841250	31832579	Masterpage method returns null when firing a button event in a derived page	frmInviteUser.Action = Request.RawUrl;	0
9378903	9378808	How to filter a DataTable by values not contained in an array?	var filtered = (from row in tbl.AsEnumerable()\n               where row.Field<int>("emp_num")==yourNum\n               && !process.Contains(row.Field<int>("process_id"))\n               select row).CopyToDataTable();	0
15744112	15743931	Can i group a text file with Regex based on line patterns	string[] lines = System.IO.File.ReadAllLines("your taext file");\n\n       var Groups =( \n                from w in lines \n                group w by w[0] into g \n                select new { FirstLetterLine = g.Key, Lins = g });	0
17745516	17745112	How to convert database results to Dictionary<int, List<decimal>>	Dictionary<int, List<Decimal>> result = new Dictionary<int, List<Decimal>>();\n\n  using (var reader = cmd.ExecuteReader()) {\n    while (reader.Read()) {\n      int id = int.Parse(reader["ID"].ToString());\n      Decimal price = Decimal.Parse(reader["PRICE"].ToString());\n\n      List<Decimal> list;\n\n      if (result.TryGetValue(id, out list))    \n        list.Add(price);\n      else \n        result.Add(id, new List<Decimal> {price});\n    }\n  }	0
29831644	29831569	how to avoid 01-01-1900 in the text box after update statement in asp.net	if(string.IsNullOrEmpty(txtDay1Date2.Text))\n   cmd2.Parameters.AddWithValue("@Day2Date", SqlDbType.VarChar).Value = txtDay1Date2.Text;\nelse\n   cmd2.Parameters.AddWithValue("@Day2Date", SqlDbType.VarChar).Value = DBNull.Value;	0
16354638	10303345	How to force eager load at runtime?	session.QueryOver<MasterEnt>()\n   .Where(x => x.Id == 2)\n   .Fetch(x => x.DetailEntList)\n   .Eager().List();	0
23758711	23758551	How to make a class public and it's constraint less accessible	public class SingletonIntializer<T>\n{\n    public T GetInstance(params object[] @params)\n    {\n        if (!SingletonContainer.ContainsType(typeof(T)))\n        {\n            SingletonContainer.CreateInstance(typeof(T), @params);\n        }\n\n        return (T)SingletonContainer.GetInstance(typeof(T));\n    }\n}\n\ninternal static class SingletonContainer\n{\n    private static Dictionary<Type, object> internalContainer = new Dictionary<Type, object>();\n\n    public static bool ContainsType(Type type)\n    {\n        return internalContainer.ContainsKey(type);\n    }\n\n    public static bool CreateInstance(Type type, object[] @params)\n    {   \n        if (ContainsType(type))\n        {\n            return false;\n        }\n\n        internalContainer[type] = Activator.CreateInstance(type, @params);\n        return true;\n    }\n\n    public static object GetInstance(Type type)\n    {\n        if (!ContainsType(type))\n        {\n            return null;\n        }\n\n        return internalContainer[type];\n    }\n}	0
21589321	21587954	Input string was not in a correct format error using C#	if (string.IsNullOrEmpty(Hours.Text))\n                    cmd.Parameters.AddWithValue("@HOURS", DBNull.Value);\n                else\n                    cmd.Parameters.AddWithValue("@HOURS", decimal.Parse(Hours.Text));	0
14320742	14320564	Allowing paging for gridview	protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)	0
18327223	18274181	How to: Drag and Drop movement in Windows 8 apps?	translation.X = e.Delta.Translation.X;\ntranslation.Y = e.Delta.Translation.Y\n\n// Since we are checking the left point subtract your shapes width from the canvas right\n// bounds.  If X is greater than this set it instead to that maximum bound.\nif (translation.X > (canvasright - shape.Width))\n    translation.X = canvasright - shape.Width;\n\n/// Same for top.  If Y is less than the canvas top set it instead right at the boundary.\nif (translation.Y < canvastop)\n    translation.Y = canvastop;\n\n// Do the same for bottom and left	0
20431994	20431529	Convert list to dictionary	List<Thing> things = new List<Thing>();\nDictionary<Thing, Thing> dictionary = new Dictionary<Thing,Thing>();\n\nvar keys = from thing in things\n           where thing.Unconfigured\n           select thing;\n\nvar values = from thing in things\n             where !thing.Unconfigured\n             select thing;\n\nforeach (Thing key in keys)\n{\n    var value = (from thing in values\n                 where thing.ParentKey == key.ParentKey &&\n                       thing.Position == key.Position\n                 select thing).FirstOrDefault();\n    dictionary.Add(key, value);\n}	0
23465883	23465839	How to write response of streamReader into textfile in c#	using(var textFileWriter = new StreamWriter("textFile.txt"))\n{\n    var streamReader = new StreamReader(client.GetStream());\n    var serverResponse = streamReader.ReadLine();\n\n    textFileWriter.WriteLine(serverResponse);\n}	0
5536539	5536464	how to create my own event in c#?	int nClicks;\nevent EventHandler TrippleClick;\n\npublic Form1()\n{\n    InitializeComponent();\n    this.button1.Click += new System.EventHandler(this.button1_Click);\n    nClicks = 0;\n    TrippleClick = new EventHandler(OnTrippleClick);\n}\n\nvoid OnTrippleClick(object sender, EventArgs e)\n{\n    MessageBox.Show("Tripple click");\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    nClicks++;\n    if (nClicks == 3)\n    {\n        TrippleClick(sender, e);\n        nClicks = 0;\n    }\n}	0
7895528	7895505	Using sizeof a Managed Structure in C#	Marshal.SizeOf	0
14008258	14008211	Good way to upload a file and get a string response from Client App to Microsoft Stack?	[HttpPost]    \npublic ActionResult Upload(string fileName)\n{\n\n------------\n//your code ...\n\nreturn Json(new{resultString="Uploaded Successfully."});\n}	0
16588512	16579502	How to populate related lookup field CRM 2011	public void Execute(IServiceProvider serviceProvider)\n{\n    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));\n    var service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(context.UserId);\n\n    var originalContact = context.InputParameters["Target"] as Entity;\n    var newContact = new Entity("new_historicalcontact");\n    if (originalContact.Contains("firstname"))\n    {\n        newContact.Add("new_firstname", orginalContact["firstname"]);\n    }\n    if (originalContact.Contains("emailaddress1"))\n    {\n        newContact.Add("new_emailaddress1", orginalContact["emailaddress1"]);\n    }\n    if (originalContact.Contains("parentcustomerid"))\n    {\n        newContact.Add("new_parentcustomerid", orginalContact["parentcustomerid"]);\n    }\n\n    //etc etc for other properties\n    service.Create(newContact);\n}	0
22595577	22595447	Can I call a derived method from base class?	public abstract class EmailTemplates\n{\n    protected void BuildBody()\n    {\n        ReplaceVariables();\n    }\n    protected virtual string ReplaceVariables()\n    {\n        //code\n    }\n}\n\npublic abstract class CustomerEmailTemplates : EmailTemplates\n{\n    protected override string ReplaceVariables()\n    {\n        //code\n        base.ReplaceVariables();\n    }\n}\n\npublic class OrderEmailTemplates : CustomerEmailTemplates\n{\n    protected override string ReplaceVariables()\n    {\n        //code\n        base.ReplaceVariables();\n    }\n}	0
10368224	10368111	Encode a RSA public key to DER format	using Org.BouncyCastle.X509;\nusing Org.BouncyCastle.Security;\nusing Org.BouncyCastle.Crypto;\nusing Org.BouncyCastle.Crypto.Generators;\nusing Org.BouncyCastle.Crypto.Parameters;\n\n...\n\nvar generator = new RsaKeyPairGenerator ();\ngenerator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));\nvar keyPair = generator.GenerateKeyPair ();\nRsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;\nvar info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo (keyParam);\nRsaBytes = info.GetEncoded ();	0
2114787	2114731	Whats the deal with a performance counter Parent?	\\Computer\PerfObject(ParentInstance/ObjectInstance#InstanceIndex)\Counter	0
9894890	9894753	Having trouble changing from One Line Text Box to Multiple Line Text Box	function checkForSemiColon(e){\n    var watchedkey = e.keyCode? e.keyCode : e.charCode\n    if(watchedkey = 186).....\n    }	0
26489770	26489753	Is there any function that performs both tasks Ceiling and Floor itself?	Math.Round()	0
5359103	5358495	Windows Phone 7: Making ListBox items change dynamically	private Visibility _longDescriptionVisibility;\npublic Visibility LongDescriptionVisibility\n{\n    get { return _longDescriptionVisibility; }\n    set\n    {\n        _longDescriptionVisibility = value;\n        NotifyPropertyChanged("LongDescriptionVisibility");\n    }\n}	0
14625466	14625427	C# time delay on application	await Task.Delay(5000)	0
6002694	6002605	regex embedded {{ matching	result = Regex.Match(subject,\n    @"\{                   # opening {\n        (?>                # now match...\n           [^{}]+          # any characters except braces\n        |                  # or\n           \{  (?<DEPTH>)  # a {, increasing the depth counter\n        |                  # or\n           \}  (?<-DEPTH>) # a }, decreasing the depth counter\n        )*                 # any number of times\n        (?(DEPTH)(?!))     # until the depth counter is zero again\n      \}                   # then match the closing }",\n    RegexOptions.IgnorePatternWhitespace).Value;	0
4305374	4304385	Dynamic addition of control in C#	Panel.Height = Unit.Point(30 + Convert.ToInt32((Unit)Panel.Height));	0
29419098	29418873	Converting multiple if-else logic to for loop	for (int i = 2; ; i += 2)\n    {\n        if (a > i && a < i + 2)\n        {\n            //Do your thing\n            break;\n        }\n    }	0
19228433	19225298	Cut String on first blank (space) with C#	var psRowElements = pslistArray[i].Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);	0
30973034	30971706	Multiple Threads searching on same folder at same time	fileNames.AsParallel().ForAll(str =>\n            {\n                var files = Directory.GetFiles(folderToCheckForFileName, str, SearchOption.AllDirectories);\n                files.AsParallel().ForAll(file =>\n                {\n                    if (!string.IsNullOrEmpty(file))\n                    {\n                        string combinedPath = Path.Combine(newTargetDirectory, Path.GetFileName(file));\n                        if (!File.Exists(combinedPath))\n                        {\n                            File.Copy(file, combinedPath);\n                        }\n                    }\n                });\n            });	0
7113698	7113667	Creating dynamic SQL DbParameter values	DbCommand dbCommand = SqlDb.GetStoredProcCommand(uspCommand);\n\nforeach(String param in MyParameters)\n{\n   DbParameter ProcessedFileName = dbCommand.CreateParameter();\n   ProcessedFileName.DbType = DbType.String;\n   ProcessedFileName.ParameterName = param;\n   ProcessedFileName.Value = pstrProcessedFileName;\n   dbCommand.Parameters.Add(ProcessedFileName);\n}	0
1588139	1588135	Is there an easier way of passing a group of variables as an array	public static void Write(params string[] stringsToWrite) {\n    ...    \n\n    foreach (string stringToWrite in stringsToWrite) {\n        writer.Write(" " + stringToWrite + " ");\n    }\n\n    ...\n}	0
29605318	29604367	datagridview to crystal report in asp.net website	GridView1.DataSource = dt;\nGridView1.DataBind();\n\nReportDocument rptDoc = new ReportDocument();\nrptDoc.Load(Server.MapPath("../blockreport.rpt"));//rpt file path\n\nDataSet ds = new DataSet();\nds.Tables.Add(dt);//your datatable\n\nrptDoc.SetDataSource(ds);\nCrystalReportViewer1.ReportSource = rptDoc;	0
15409562	15409501	Make wpf UI responsive when button click is performed	Thread t = new Thread(() => WorkerMethod());\nt.Start();	0
10394897	10336580	Windows Shell Extension dll and Winform process	void OnVerbDisplayFileName(IntPtr hWnd)\n    {\n        string file = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;\n        string executableName = file.Substring(0, file.LastIndexOf("/"));\n        executableName += "/MyApp.exe";\n\n        Process gui = new Process();\n\n        gui.StartInfo.FileName = executableName;\n        gui.StartInfo.Arguments = selectedFiles.JoinFileNames(" ");\n\n        gui.Start();\n    }	0
15763489	15735184	Fill DataSet from OleDbDataAdapter	FileStream stream = File.Open(strNewPath , FileMode.Open, FileAccess.Read);            \n        //1. Reading from a binary Excel file ('97-2003 format; *.xls)\n        //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);\n        //...\n        //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)\n        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);;                      \n        excelReader.IsFirstRowAsColumnNames = true;\n        DataSet result = excelReader.AsDataSet();	0
10280190	10278668	Need to extract fields from a string in C#	Regex regex = new Regex("(?<name>(\\S*))(\\s*)(?<date>((\\S*)\\s(\\S*)))(\\s*)(?<number>(\\d*))");\n            Match match = regex.Match(yourString);\n            if (match.Success)\n            {\n                string name = match.Groups["name"].Value;\n                string date = match.Groups["date"].Value;\n                string number = match.Groups["number"].Value;\n            }	0
33821052	33820381	Unity3D UI Text string from json not correctly showing	textAZ = jsonObject.GetString("haqqinda_az").ToString();\ntextAZ = textAZ.Replace("\\n","\n").Replace("\\r","\r");\naboutText.text = textAZ;	0
13064318	13063946	Find grid control inside grid without its rowbound event	foreach (GridViewRow row in gv.Rows)\n    {\n        TextBox txt = row.Cells[0].Controls[0].FindControl("TextBox1") as TextBox;\n        string value = txt.Text;\n        Response.Write(value);\n    }	0
24666667	24666644	Putting manually created buttons into an array	List<Button> panelButtonList = this.YourPanel.Controls.OfType<Button>().ToList();	0
11247302	11213575	Find version changes in an EF object	public ActionResult IsChanged(string fieldName, int parentID)\n{\n    using (MyEntities _db = new MyEntities())\n    {\n        bool isChanged = false; \n\n            string[] aName = fieldName.Split('.');\n\n            string strTableName = aName[0];\n            string strFieldName = aName[1];\n\n            string strQuery = String.Format("select distinct {0} from {1} where parentID = {2}", strFieldName, strTableName, parentID);\n\n            isChanged = _db.ExecuteStoreQuery<dynamic>(strQuery).Count() > 1;\n\n            return Json(isChanged, JsonRequestBehavior.AllowGet);\n    }\n}	0
6937351	6937295	How to serialize a .NET object and assign to a string variable?	XmlSerializer ser = new XmlSerializer(typeof(Test));\nTest t = new Test() { Id = 1 };\n\nMemoryStream ms = new MemoryStream();\nser.Serialize(ms, t);\nms.Position = 0;\n\nStreamReader r = new StreamReader(ms);\nstring res = r.ReadToEnd();	0
18181126	18180472	Retrieve child node value	XDocument DocumentObject = XDocument.Load(yourxml); \n  IEnumerable<XElement> Tax= from TaxInfo in DocumentObject.Descendants("Tax") select  TaxInfo;\n\n            foreach (var t in Tax)\n            {\n                TaxType = (string)t.Element("TaxType");\n\n            }	0
457747	457677	TabControl Context Menu	public Form1()\n{\n    InitializeComponent();\n    this.tabControl1.MouseClick += new MouseEventHandler(tabControl1_MouseClick);\n}\n\nprivate void tabControl1_MouseClick(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        this.contextMenuStrip1.Show(this.tabControl1, e.Location);\n    }\n\n\n}	0
11905260	11904743	how to define a Global Structure in C#?	public class MyObject\n{\n    public int Value;\n}\n\npublic static void Main(string[] args)\n{\n    MyObject obj = new MyObject();\n\n    obj.Value = 42;\n\n    PrintObject(obj);\n\n    Console.WriteLine("Press any key to exit...");\n    Console.ReadKey(true);\n}\n\npublic static void PrintObject(MyObject obj)\n{\n    Console.WriteLine(obj.Value);\n}	0
25493356	25493303	generic Func with parameter	Func<Task<string>> action = ()=> myApiClient.Action(parameter1, parameter2)	0
11742390	11705223	Multiple relationships between two models	[ForeignKey("FarmID")]\npublic virtual Farm Farm { get; set; }	0
30297127	30297072	How to get the Winform program run time?	using System.Diagnostics.Stopwatch\nclass Program\n{\n    static void Main()\n    {\n    // Create new stopwatch\n    Stopwatch stopwatch = new Stopwatch();\n\n    // Begin timing\n    stopwatch.Start();\n\n    // Do something     \n\n    // Stop timing\n    stopwatch.Stop();\n\n    // Write result\n    Console.WriteLine("Time elapsed: {0}",\n        stopwatch.Elapsed);\n    }\n}	0
21797516	21797423	How to get the boundaries of an area after scale/translate	// Return the general transform for the specified visual object.\nGeneralTransform generalTransform1 = myStackPanel.TransformToVisual(myTextBlock);\n\n// Retrieve the point value relative to the child.\nPoint currentPoint = generalTransform1.Transform(new Point(0, 0));	0
479664	22322	How to late bind 32bit/64 bit libs at runtime	static void Main(String[] argv)\n  {\n     // Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit\n     // sub-directories.\n\n     AppDomainSetup objADS = new AppDomainSetup();\n\n     System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n     switch (System.IntPtr.Size)\n     {\n        case (4): assemblyDir += "\\win32\\";\n           break;\n        case (8): assemblyDir += "\\x64\\";\n           break;\n     }\n\n     objADS.ApplicationBase = assemblyDir;\n\n     // We set the PrivateBinPath to the application directory, so that we can still\n     // load the platform neutral assemblies from the app directory.\n     objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n\n     AppDomain objAD = AppDomain.CreateDomain("", null, objADS);\n     if (argv.Length > 0)\n        objAD.ExecuteAssembly(argv[0]);\n     else\n        objAD.ExecuteAssembly("MyApplication.exe");\n\n     AppDomain.Unload(objAD);\n\n  }	0
24228518	24018507	OpenTK: Detect display's DPI	// game is derived from GameWindow and screenSize\n// is given as a parameter for its constructor.\nvar scale = game.Width / (float)screenSize.X;	0
8988183	8988147	Match everything before a specific word in a multiline string	resultString = Regex.Replace(subjectString, \n    @"\A             # Start of string\n    (?:              # Match...\n     (?!""giraffe"") #  (unless we're at the start of the string ""giraffe"")\n    .                #  any character (including newlines)\n    )*               # zero or more times", \n    "", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);	0
2462594	2462552	Get all attribute values of given tag with Html Agility Pack	var nodes = sourceDocument.DocumentNode.SelectNodes("//span[@id]");\nList<string> ids = new List<string>(nodes.Count);\n\nif(nodes != null)\n{\n    foreach(var node in nodes)\n    {\n        if(node.Id != null)\n        ids.Add(node.Id);\n    }\n}\n\nreturn ids;	0
25719001	25621972	Format condition by expression EPPlus	ExcelPackage pck = new ExcelPackage();\n            var ws = pck.Workbook.Worksheets.Add("Sample1");\n            var _formatRangeAddress = new ExcelAddress("H16:K31,H33:K44,H46:K57,H59:K69,H71:K73");\n            string _statement = "AND(COUNTA(H16:H16)<2,COUNTA(H16:K16)>0)";\n            var _cond4 = ws.ConditionalFormatting.AddExpression(_formatRangeAddress);\n            _cond4.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;\n            _cond4.Style.Fill.BackgroundColor.Color = Color.Green;\n            _cond4.Formula = _statement;\n            pck.SaveAs(Response.OutputStream);\n            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n            Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");	0
13353697	13353628	Parsing Visual Studio Project File as XML	XNamespace msbuildNs = "http://schemas.microsoft.com/developer/msbuild/2003"\nXElement subElement = element.Element(msbuildNs + binder.Name);	0
31679877	31679681	Manipulating a list of data while keeping a history of all items	WHERE DELETED = 0	0
11822172	11821644	How can I compare each element of a list with itself only once	string[] textlist = {"a", "b", "c"};\nvar intersecting = from aIndex in Enumerable.Range(0, textlist.Count())\n                   from b in textlist.Skip(aIndex + 1)\n                   let a = textlist.ElementAt(aIndex)\n                   where a != b && a.SomeCondition(b)\n                   select new\n                   {\n                       object1 = a,\n                       object2 = b\n                   };	0
11466167	10948219	Make Linq to Sql generate T-SQL with ISNULL instead of COALESCE	DataContext.ExecuteQuery<TResult>	0
3838868	3838797	Using Linq2SQL to return Parent Table Data, but sorted by Child Table Data	var results = \n    from p in parent\n    join c in (from c2 in child orderby c2.Date descending select c2)\n    on p.Id equals c.ParentId into childGroup\n    select new { ParentId=p.Id, ParentDate=p.Date, ChildDate=childGroup.First().Date };	0
23926044	23925793	Convert String dateTime of javascript to DateTime C#	var Date = "Tue May 13 2014 00:00:00 GMT+0700";\nvar FormattedDate = DateTime.ParseExact(Date,"ddd MMM dd yyyy HH:mm:ss \n'GMT'zzz",System.Globalization.CultureInfo.InvariantCulture);	0
25270458	25269824	How can I create an instance of a derived class from an instance of a base class and include private fields?	class Identity\n{\n    private int x;\n    public Identity(Identity that)\n    {\n        this.x = that.x;\n    }\n}\n\nclass OrgnaizationIdentity : Identity \n{\n    public OrgnaizationIdentity(Identity that) : base(that) { ... }\n}	0
15398763	15398730	How can I get a percent accuracy match when comparing two strings of an address?	percent = (largerString.Length - editDistance) / largerString.Length	0
2686581	2686533	Is there a way to create a SyndicationFeed from a String?	TextReader tr = new StringReader(xmlString);\nXmlReader xmlReader = XmlReader.Create(tr);\nSyndicationFeed feed = SyndicationFeed.Load(xmlReader);	0
4788570	4788386	Extracting a specific folder from a zip using DotNetZip	public void ExtractFiles(string fileName, string outputDirectory)\n          {\n                using (ZipFile zip1 = ZipFile.Read(fileName))\n                {\n                    var selection = (from e in zip1.Entries\n                                     where (e.FileName).StartsWith("CSS/")\n                                     select e);\n\n\n                    Directory.CreateDirectory(outputDirectory);\n\n                    foreach (var e in selection)\n                    {                            \n                        e.Extract(outputDirectory);        \n                    }\n                }\n         }	0
11960346	11959857	Trying to make update to WebSphere MQ Queue atomic	// Specify the message options\nMQPutMessageOptions pmo = new MQPutMessageOptions();\n\n// MQC.MQPMO_SYNCPOINT = provide transaction support for the Put.\npmo.Options = MQC.MQPMO_SYNCPOINT;\nCommittableTransaction transScope = new CommittableTransaction();\nCommittableTransaction.Current = transScope;    \n\ntry\n{                            \n    foreach (string agentItem in qSqlContents.Values)\n    {\n        // Define a WebSphere MQ message, writing some text in UTF format\n        MQMessage mqMessage = new MQMessage();\n        mqMessage.Write(StrToByteArray(agentItem));\n\n        // Put the message on the queue\n        _outputQueue.Put(mqMessage, pmo);\n    }                       \n}\ncatch (Exception)\n{\n    transScope.Rollback();                        \n}\nfinally\n{\n    _outputQueue.close();\n    transScope.Commit(); \n    transScope.Dispose();                       \n}	0
24524089	24518262	Click Image which then directs to a url in IE	private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n        {\n            WebBrowserTask BrowserTask = new WebBrowserTask();\n            BrowserTask.Uri = new Uri("http://www.google.com",UriKind.Absolute);\n            BrowserTask.Show();\n        }	0
3937208	3937188	3rd Party dll in Silverlight application	Print()	0
29593594	29593569	how to write data to mysql database and ignore a column using c#	DBConnectMySQL.DBCommand.CommandText = "INSERT INTO tbCard(id, Phone, username) VALUES (@id,@Phone, @username)";\n\nDBConnectMySQL.DBCommand.Parameters.AddWithValue("@id", "");\nDBConnectMySQL.DBCommand.Parameters.AddWithValue("@Phone", number);\nDBConnectMySQL.DBCommand.Parameters.AddWithValue("@username", UserName);	0
19725618	19725543	add test to splint method	if (item.CalcInsor_Desc != null)\n{\n    string[] CalcInsor_Desc = item.CalcInsor_Desc.ToString().Split('.');\n        if (CalcInsor_Desc.Length >= 2)\n        {\n             schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];\n             schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];\n        }\n}	0
21407088	21338556	Showing Prism modules inside Prism Module	[Module(ModuleName = "TestModule", OnDemand = false)]\n[ModuleDependency("ModuleDockModule")]\npublic class TestModuleModule : IModule\n{ ...	0
15031596	15026300	How to find where a line is wrapped in a dataGridView cell?	string testLength = "1";\n    private void DataSheets_Load(object sender, EventArgs e) //DataGridView, 2 columns\n    {\n        clmData.DefaultCellStyle.WrapMode = DataGridViewTriState.True;\n        Data.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;\n        Data.DefaultCellStyle.Font = new Font("Courier", 8);\n        RunWidth();\n    }\n\n    void RunWidth()\n    {\n        int l1 = len(testLength);\n        int l2 = len(testLength + testLength);\n        int perChar = l2 - l1;\n        int pad = l1 - perChar;\n        int s7 = pad + (perChar * 75);\n        int s5 = pad + (perChar * 50);\n        Data.Columns[0].Width = s7;\n        Data.Columns[1].Width = s5;\n    }\n    public int len(string text)\n    {\n        Size te = TextRenderer.MeasureText(text, new Font("Courier", 8));\n        return te.Width;\n    }	0
14337190	14336797	compare values in datatable, change it if they are the same	var invalidGroups = DT.AsEnumerable()\n    .GroupBy(r => r.Field<string>("name"))\n    .Where(g => g.Count() > 1)\n    .Select(g => new { Name = g.Key, FirstRow = g.First(), Group = g })\n    .Select(x => new { x.Name, x.FirstRow, x.Group, FirstSum = x.FirstRow.Field<int>("Bit") + x.FirstRow.Field<int>("Size") })\n    .Where(x => x.Group.Any(r => x.FirstSum < r.Field<int>("Bit") + r.Field<int>("Size")));\nforeach (var x in invalidGroups)\n{\n    string name = x.Name;\n    DataRow referenceRow = x.FirstRow;\n    var invalidRows = x.Group\n        .Where(r => x.FirstSum < r.Field<int>("Bit") + r.Field<int>("Size"));\n    foreach (DataRow r in invalidRows)\n    {\n        int sum = r.Field<int>("Bit") + r.Field<int>("Size"); // 12 instead of 11\n        r.SetField("Bit", referenceRow.Field<int>("Bit"));\n        r.SetField("Size", referenceRow.Field<int>("Size"));\n    }\n}	0
12462314	12462100	Default value for Required fields in Entity Framework migrations?	AlterColumn("dbo.Movies", "Director", c => c.String(nullable: false, defaultValueSql: "John Doe"));	0
614350	614336	Check if a server is available	using System.Net.NetworkInformation;\nvar ping = new Ping();\nvar reply = ping.Send("google.com", 60 * 1000); // 1 minute time out (in ms)\n// or...\nreply = ping.Send(new IPAddress(new byte[]{127,0,0,1}), 3000);	0
24588314	24588296	Crystal Reports parameters c#	ReportDocument DocumentObjReport = new ReportDocument();\n\n    DocumentObjReport.SetParameterValue("ParameterName",YourParameterValue);	0
7305609	7280580	How to check if a font supports an specific style	private bool SupportStrikeout(Font font)\n    {\n        try\n        {\n            using (Font strikeout = new Font(font, FontStyle.Strikeout))\n            {\n                return true;\n            }\n        }\n        catch (ArgumentException)\n        {\n            return false;\n        }\n    }	0
19697589	19697183	How to retrieve specific text from the given string in the c#	namespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string[] strArray = new string[50];\n            string str = "SampleText<b>Billgates</b><p>This is Para</p><b>SteveJobs</b>ThisisEnd";\n\n            Regex expression = new Regex(@"\<b\>(.*?)\</b\>");\n\n            for (int i = 0; i < expression.Matches(str).Count; ++i)\n            {\n                string value = expression.Matches(str)[i].ToString();\n\n                value = value.Replace("<b>", "");\n                value = value.Replace("</b>", "");\n                strArray[i] = value;\n            }\n\n            Console.WriteLine(strArray[0]);\n            Console.WriteLine(strArray[1]);\n\n            Console.ReadLine();\n        }\n    }\n}	0
8361211	8358613	Clean Design to Handle Multiple Result Sets from IDataReader	while (dr.Read())\n    {\n        var sdr = new SafeDataReader(dr);\n        memberModel.ClientId = sdr.GetInt64("ClientId");\n        memberModel.Id = sdr.GetInt64("EntityId");\n        memberModel.Name = sdr.GetString("EntityName");\n    }\n    if (dr.NextResult())\n    {\n        while (dr.Read())\n        {\n            AddAttribute(memberModel, new SafeDataReader(dr));\n        }\n    }\n    if (dr.NextResult())\n    {\n        while (dr.Read())\n        {\n            AddAlternateId(memberModel, new SafeDataReader(dr));\n        }\n    }	0
2634888	2634865	Using Progressbar in c# windows application	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
29245223	29245131	I have two combo Boxes where I want users to calculate a total time for a process	string format = "hh:mm"\nDateTime dateTime = DateTime.ParseExact(comboBox.Text, format, CultureInfo.InvariantCulture);	0
2252395	2252379	declare an array in a for	foreach (string j in new string[] {"1","1"})\n{\n\n}	0
4936382	4936300	WPF Datagrid editable template column	CanUserAddRows="false"	0
13643610	13643486	Adding an element to this xml structure	string xml = "<root><element1>innertext</element1><element2>innertext</element2><element3><child1>innertext</child1></element3></root>";\n\n var doc = XDocument.Parse(xml); //use XDocument.Load("filepath"); in case if your xml is in a file.\n\n var el3 = doc.Descendants("element3").FirstOrDefault();\n\n el3.Add(new XElement("child2", "innertext"));	0
13160505	13160257	Getting element of enum in array	int oi, ii;\nfor (oi = 0; oi <= cells.GetUpperBound(0); ++oi)\n{\n    for (ii = 0; ii <= cells.GetUpperBound(1); ++ii)\n    {\n        System.Diagnostics.Debug.WriteLine(\n            "Checking: " + oi + "," + ii + " : " + cells[oi, ii].ToString()\n        );\n    }\n}	0
14380569	14347717	Use a string to determine table to query	dynamic test = t.InvokeMember(table,\n                        BindingFlags.DeclaredOnly |\n                        BindingFlags.Public | BindingFlags.NonPublic |\n                        BindingFlags.Instance | BindingFlags.GetProperty, null, context, new object[0]);\n\n            ((IQueryable)test).AsQueryable().Where(condition).Load();\n            results.ItemsSource = test.Local;	0
12394475	12393903	Issues getting return confirm to fire before button click event	OnClientClicking="function (sender, args){args.set_cancel(!window.confirm('Are you sure you want to delete this account?'));}"	0
12032939	12032905	Problems with mouseclick event on image over a rectangle in WPF app	image.IsHitTestVisible = false;	0
5090853	5090803	Get object associated with selected rows in DataGridView	DataGridViewSelectedRowCollection rows = MyDataGridView.SelectedRows;\nforeach (DataGridViewRow row in rows)\n{\n   DataRow myRow = (row.DataBoundItem as DataRowView).Row;\n   // Do something with your DataRow\n}	0
26359109	26358811	How to get a date in a link? MVC 5	DateTime.Now.Ticks	0
9787389	9787250	How do I dynamically set source of an IFrame?	// (Add inside script element in head of page html)\n\nwindow.onload = function() {\n    document.getElementById('<id of input>').onchange = function() {\n        changeFrameUrl();\n    }\n};\n\nfunction changeFrameUrl() {\n        var inputVal = document.getElementById('<id of input>').value;\n        document.getElementById('<id of iframe>').src = inputVal;\n}	0
22630680	22630455	Register Enumeration with Castle Windsor	// declare the enum\npublic enum StopCode\n{\n    StartProd,\n    BeaOmstilling,\n    FlexOmstilling,\n    PlaStop,\n}\n\n// and declare an interface that translates this enum to values\npublic interface StopCodeConverter\n{\n    int convertFrom(StopCode code);\n}\n\n// then your components\npublic class EnglishStopCodeConverter\n{\n    public int convertFrom(StopCode code) { /* do your translation */ return  0;}\n}\n\npublic class SpanishStopCodeConverter\n{\n    public int convertFrom(StopCode code) { /* hace su translaci??n */ return  0;}\n}	0
23376031	23375243	Access ASP.NET control in parent GridView in from OnRowDataBound event in child GridView	protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        var gvChild = sender as GridView;    \n        var hfAppID = gvChild.Parent.FindControl("hfAppID") as HiddenField;\n        var id = hfAppID.Value;\n    }\n}	0
12943644	12942644	How to call a WebAPI from Windows Service	// Create an HttpClient instance\nHttpClient client = new HttpClient();\nclient.BaseAddress = new Uri("http://localhost:8888/");\n\n// Usage\nHttpResponseMessage response = client.GetAsync("api/importresults/1").Result;\nif (response.IsSuccessStatusCode)\n{\n    var dto = response.Content.ReadAsAsync<ImportResultDTO>().Result;\n}\nelse\n{\n    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);\n}	0
11863440	11863234	How to download a xml content in a xml file	public FileResult Download(string id)\n{  \n    var model = service.GetAllDefinitions().First(x => x.ID == id);\n    var definitionDetails = new StatisticDefinitionModel(model);\n    string xmlString = definitionDetails.ToXml;\n    string fileName = definitionDetails.Name + ".xml";\n\n\n    return File(Encoding.UTF8.GetBytes(xmlString), "application/xml", fileName);\n}	0
14480011	14465230	Extract files from a zip into a jar archive	if (Directory.Exists(temp))\n    {\n        Directory.Delete(temp, true);\n        Directory.CreateDirectory(temp);\n    }\n    using (ZipFile jar = ZipFile.Read(appdata + "\\.minecraft\\bin\\minecraft.jar"))\n    {\n        using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n        {\n            zip.ExtractAll(temp, ExtractExistingFileAction.OverwriteSilently);\n        }\n        foreach (string file in Directory.GetFiles(temp))\n        {\n            if (jar.ContainsEntry(file))\n            {\n                jar.RemoveEntry(file);\n            }\n            jar.AddFile(file, "\\");\n        }\n        jar.Save();\n        MessageBox.Show("Entpacken der Dateien abgeschlossen!");\n        label1.Text = "Entpacken abgeschlossen!";Solved the problem with this code(thanks to GemHunter1 :D ):	0
28889757	28887795	Add javascript to pdf file using iTextSharp	var pdfLocalFilePath = Server.MapPath("~/sourceFile.pdf");\nvar outputLocalFilePath = Server.MapPath("~/outputFile.pdf");\nusing (var outputStream = new FileStream(outputLocalFilePath, FileMode.CreateNew))\n{\n    AddPrintFunction(pdfLocalFilePath, outputStream);\n    outputStream.Flush();\n}	0
12263686	12263315	Default MongoDB serialization of public properties	public List<Release> Releases\n{\n    get\n    {\n        return new List<Release>(releases); //I can protect 'releases' when reading by passing a copy of it\n    }\n    protected set\n    {\n        releases = value; //BUT how can I protect release when writing?\n    }\n}	0
17212138	17210373	How to set Validation for a cell in Excel created using NPOI	var markConstraint = DVConstraint.CreateExplicitListConstraint(new string[]{"1","2","3"});\n    var markColumn = new CellRangeAddressList(1, 5, 1, 1);\n    var markdv = new HSSFDataValidation(markColumn, markConstraint);\n    markdv.EmptyCellAllowed = true;\n    markdv.CreateErrorBox("Wrong Value", "Please Enter a correct value");\n    sheet.AddValidationData(markdv);	0
20399560	20399493	how compare two int[] array for update and merge the difference?	//Here   is a sample on  how you can achieve this  \n\n static void Main(string[] args)\n    {\n       //Two list [source , compare ]\n    int[] ListSource = new int[]{ 4,8,12,20,24,32 } ;\n    int[] ListToCompare = new int[] { 3, 8, 16, 16, 20, 24, 28, 32,36 };\n\n\n        var res = ListToCompare.Except(ListSource);\n        var NewListSource = ListSource.ToList();\n        NewListSource.AddRange(res);\n       ListSource = NewListSource.OrderBy(x=>x).ToArray();  \n\n\n\n\n        //And finally my Listsou\n    }\n}	0
16857021	16855010	Get cyrrency symbol while current culture is another than control's one	String language = "FR-fr"; // <- France (culture or region ISO code)\n  String currecySymbol = new RegionInfo(language).CurrencySymbol; // <- should return Euro currency symbol ???	0
7319140	7318911	Problem URLDecoding string from ASP to ASP.Net (international characters)	string str = @"%A0%A01stk.+%D8repynt+%3Cbr%3E%A0%A01stk.+Slipsn%E5l+%3Cbr%3E%3Cp%3E+Total+pris%3A+300";\n        string decoded = System.Web.HttpUtility.UrlDecode(str, System.Text.Encoding.GetEncoding("ISO-8859-1"))	0
22045132	22044362	What is the best way to avoid sending too much data in JSON to a Telerik Grid when using Ajax binding?	public class ClientModel\n{\n    public int ClientId {get; set; }\n    public string Name { get; set; }\n    public string Address { get; set; }\n}\n\nvar model = from c in clients\n            select new ClientModel {\n               ...\n            };\n\nreturn View(new GridModel(model));	0
28818708	28818512	Registering same singleton for multiple interfaces in IOC	ThemeService singletonService = null;\nprivate ThemeService GetThemeService() \n{\n    if (singletonService == null) \n    {\n        singletonService = new ThemeService(Mvx.Resolve<IMvxJsonConverter>(), Mvx.Resolve<IMvxResourceLoader>());\n    }\n    return singletonService;\n}\n\nprotected override void InitializeFirstChance()\n{\n    Mvx.RegisterSingleton<IDroidThemeService>(GetThemeService);\n    Mvx.RegisterSingleton<IThemeService>(GetThemeService);\n\n    base.InitializeFirstChance();\n}	0
21229983	21229747	Waiting for responses to asynchronous HTTP requests without async/await	var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();\nTask.Factory.ContinueWhenAll(runningTasks.ToArray(), antecedents =>\n{\n    webBrowser1.DocumentText = ...//This runs in UI thread\n},CancellationToken.None, TaskContinuationOptions.None,uiTaskScheduler );	0
12415776	12415083	MigraDoc - Bold certain text in a paragraph	var paragraph = section.AddParagraph("This text"); \n\nparagraph.AddFormattedText("Text in Bold Style", TextFormat.Bold);	0
27274003	27273248	Deserializing with xsd.exe - how to deserialize to objects, not to DataSet?	xsd room.xml\nxsd room.xsd /classes	0
22118666	22118546	Correcting whitespace count using Regex	input = Regex.Replace(input, "\\s*\\|\\s*", " | ");	0
16491463	16491423	Linq query with select needed to get specific properties from a list	EtchVectors = vio.Shapes.Select( s => s.Formatted );	0
22965056	22964459	Moving values from optional ordered text boxes if any before are empty	string Temp="";\nif(txt1.Text!="")\n    Temp=Temp+txt1.Text+"^";\nif(txt2.Text!="")\n    Temp=Temp+txt2.Text+"^";\nif(txt3.Text!="")\n    Temp=Temp+txt3.Text+"^";\nif(txt4.Text!="")\n    Temp=Temp+txt4.Text+"^";\nif(txt5.Text!="")\n    Temp=Temp+txt5.Text+"^";\nif(txt6.Text!="")\n    Temp=Temp+txt6.Text+"^";\nTemp=Temp+"^^^^^^";\nstring Parts[] = Temp.Split('^');\ntxt1.Text=Parts[0];\ntxt2.Text=Parts[1];\ntxt3.Text=Parts[2];\ntxt4.Text=Parts[3];\ntxt5.Text=Parts[4];\ntxt6.Text=Parts[5];	0
12127754	12127706	Im parsing some text from xml file how can i parse also the names?	e.Element("From").Element("User").Attribute("FriendlyName").Value.ToString()	0
31726429	31725400	How to get the registered user control to code behind in c#?	public partial class SideControl : System.Web.UI.UserControl\n{\n    // your code...\n}	0
9550461	9550414	Show listbox in datagridview	this.Controls.Add(lb);	0
7514948	7514861	Looking for regex to split on the string on upper case basis	var subjectString = "DisclosureOfComparativeInformation";\nvar resultString = Regex.Replace(subjectString, "([a-z])([A-Z])", "$1 $2");	0
32872014	32871925	Constructor with unknown argument	public class User\n{\n    public User(int userId)\n    {\n        // Do stuff\n    }\n}\n\npublic class Employee : User\n{\n    public Employee(int employeeId) : base(GetUserId(employeeId))\n    {\n\n    }\n\n    public static int GetUserId(int employeeId)\n    {           \n        return employeeId - 5;\n    }\n}	0
680971	680960	Different format for whole numbers and decimal	if (Math.Floor(d) == d)\n    return d.ToString("0");\nelse\n    return d.ToString();	0
801894	798494	How do I print from the wpf WebBrowser available in .net 3.5 SP1?	mshtml.IHTMLDocument2 doc = webBrowser.Document as mshtml.IHTMLDocument2;\n    doc.execCommand("Print", true, null);	0
17603965	17591274	how to apply Font.WeightBold for only one ListBoxitem in ListBox	private void MakeBold()\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            TextBlock s = new TextBlock();\n            s.Text = "Testing" + i;\n            if (i == 3)\n                s.FontWeight = FontWeights.Heavy;\n            lstbx.Items.Add(s);\n        }\n    }	0
22923726	22888574	How to get AuthorityKeyIdentifier from Certificate	KeyIdentifier ::= OCTET STRING	0
5648389	5648339	Deleting specific rows from DataTable	for(int i = dtPerson.Rows.Count-1; i >= 0; i--)\n{\n    DataRow dr = dtPerson.Rows[i];\n    if (dr["name"] == "Joe")\n        dr.Delete();\n}	0
4649532	4645958	Removing a default instance type from StructureMap at runtime	var container = new Container(x =>\n{         \n  x.InstanceOf<IDateAdjuster>().Is.Conditional(o =>\n  {                 \n    o.If(c => c.GetInstance<IUserSettings>()\n     .UseTestDateAdjuster).ThenIt.Is.OfConcreteType<DateAdjusterForTest>();\n\n    o.TheDefault.Is.OfConcreteType<DateAdjuster>();\n  });\n});	0
25501271	25397658	How can I get MICR string from scanner by using TWAIN driver	public string GetExtendedImageInfo()\n    {\n        TwRC rc;\n        TwExtImageInfo exinf = new TwExtImageInfo();\n\n        exinf.NumInfos = 1;\n        exinf.Info = new TwInfo();\n        exinf.Info.InfoID = (short)TwEI.BARCODETEXT;\n\n        rc = DSexfer(appid, srcds, TwDG.Image, TwDAT.ExtImageInfo, TwMSG.Get, exinf);\n\n        StringBuilder strItem = new StringBuilder(255);\n        IntPtr itemPtr = new IntPtr(exinf.Info.Item);\n        IntPtr dataPtr = GlobalLock(itemPtr);\n        string str = Marshal.PtrToStringAnsi(dataPtr);\n        GlobalUnlock(itemPtr);\n        GlobalFree(itemPtr);\n\n        return str;\n    }	0
13903541	13903164	How to generate a file with all possible 12 character letter/number combinations?	var alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";\n\nvar query = from a in alphabet\n            from b in alphabet\n            from c in alphabet\n            from d in alphabet\n            from e in alphabet\n            from f in alphabet\n            from g in alphabet\n            from h in alphabet\n            from i in alphabet\n            from j in alphabet\n            from k in alphabet\n            from l in alphabet\n\n            select "" + a + b + c + d + e + f + g + h + i + j + k + l;\n\nforeach (var item in query)\n{\n    Console.WriteLine(item);\n}	0
10418110	10417999	How to pass singleton as generic type parameter?	public interface IEdge<TPoint>...\n\nclass MyEdge : IEdge<MyPoint>\n{\n   IEdgeFactory<MyPoint> factory;\n   public MyEdge(IEdgeFactory<MyPoint> factory)\n   {\n      this.factory = factory;\n   }\n}	0
7291551	7290997	LINQ: Chain ID's from one row to another	List<int> GetParentHierarchy(int startingId)\n{\n  List<int> hierarchy = new List<int> { startingId };\n  using(Connection db = new Connection()) //change to your context\n  {      \n      int parentId = startingId;\n      while(true)\n      {\n         var foo = db.Foo(x => x.Id == parentId).SingleOrDefault(); \n         if(foo == null)\n           break;\n         parentId = foo.ParentId;\n         hierarchy.Add(foo.Id);\n         if(foo.BaseParentID == 0)\n           break;\n      }\n  }\n\n  return hierarchy;\n\n}	0
33099082	33098702	Limit no of items in autocomplete textbox in asp.net C#	public static List<string> GetNames(string prefixText, int count)	0
27565518	27565388	C# Fetch certain email with subject	using(Pop3Client client = new Pop3Client())\n{\n    client.Connect(hotmailHostName, pop3Port, useSsl);\n    client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword);\n\n    // And here you can use the client.GetMessage() method to get a desired message. \n    // You can iterate all the messages and check properties on each of them. \n}	0
16484470	16484058	how to retrieve data from helper class property using Linq query C#	var session = SessionManager.GetCurrentSession();\n\nvar data2 = session.Query<CPayment>().Select(row => new CPaymentModel()\n{\n    CardNo = row.CardNo,\n    Product = row.ProductDetails.Product,\n    Subproduct = row.ProductDetails.Subproduct,\n    FileDate = row.FileDate,\n    Transaction =new TransactionHelper()\n    {\n        TransCode = row.Transaction.TransCode;\n        TransDate = row.Transaction.TransDate\n    }\n}).ToList<CPaymentModel>();\nvar list = data2.ToDataSourceResult(dsRequest);	0
18487388	18487258	Regular expression for multiple email destinations delimited by semicolon	foreach (var email in emailList.Split(new char[] { ';' },\n    StringSplitOptions.RemoveEmptyEntries))\n{\n    // validate email\n}	0
2440083	2440010	Access denied at webservice	NT AUTHORITY\NETWORK SERVICE	0
11034584	10707993	Getting the HTML content of the current page with databound controls	protected void ConvertRepeaterToPDF_click(object sender, EventArgs e)\n{\n    // handle the PreRender complete method\n    Page.PreRenderComplete += new EventHandler(Page_OnPreRenderComplete);\n}	0
585633	585543	Why does this string initialization in an if statement prevent me from printing?	if (nom == "1")\n{\n    nom +=1;\n    ou = nom;\n} else \n{\n    ou = "blank value";\n}	0
7344137	7344120	DateTime FormatException error	DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);	0
3986872	3985576	DevExpress Wizard Control - how to un - dock?	public override DockStyle Dock {\n        get { return base.Dock; }\n        set { base.Dock = DockStyle.Fill; }\n    }	0
28989772	28989184	How to make two threads in C# wpf application	public void doAsync(){\n   var list = new List<ofSomething>();\n   Task.Factory.StartNew(()=>{\n        //You are now in a new thread, just do your stuff here.\n        var somerange = GetSomeRange();\n        list.AddRange(somerange);\n   }).Continue((p)=>{\n       //you are now on GUI thread send event or return the list.\n       //I personally like to send events.\n       if(PostDataReady != null) PostDataReady(list);\n   });\n\n}	0
14223837	14223346	fast and memory-efficient way of converting byte[] to arrays of primitives	unsafe public void Convert(void* b)\n    {\n        int i;\n\n        double* asDouble = (double*)b;\n        double sum1 = 0.0;\n        for (i = 0; i < 100; i++, asDouble++)\n            sum1 += *asDouble;\n\n        int* asInt = (int*)asDouble;\n        int sum2 = 0;\n        for (i = 0; i < 100; i++, asInt++)\n            sum2 += *asInt;\n    }\n\n    public unsafe void SomeThing()\n    {\n        byte[] rawbytes = new byte[44000];\n\n        // Fill the "rawbytes" array somehow\n\n        fixed (byte* ptr = rawbytes)\n        {\n            Convert(ptr);\n        }\n    }	0
241946	241790	Best way to access user/site settings	#region Data Access\n\nprivate string GetSettingsFromDb(string settingName)\n{\nreturn "";\n}\nprivate Dictionary<string,string> GetSettingsFromDb()\n{\nreturn new Dictionary<string, string>();\n}\n\n#endregion\n\nprivate const string KEY_SETTING1 = "Setting1";\npublic string Setting1\n{\nget\n{\nif (Cache.Get(KEY_SETTING1) != null)\nreturn Cache.Get(KEY_SETTING1).ToString();\n\nSetting1 = GetSettingsFromDb(KEY_SETTING1);\n\nreturn Setting1;\n\n} \nset\n{\nCache.Remove(KEY_SETTING1);\nCache.Insert(KEY_SETTING1, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(2));\n}\n}\n\nprivate Cache Cache { get { return HttpContext.Current.Cache; } }	0
8613730	8610982	monodroid - default new untouched template project cannot run in android emulator	obj\Debug\android\AndroidManifest.xml:2: Tag <manifest> attribute package has invalid character '-'.\nobj\Debug\android\AndroidManifest.xml:14: Tag <category> attribute name has invalid character '-'.	0
4096519	4078362	DataColumn.ExtendedProperties Data to GridView	protected void gridView_rowDataBound(object sender, GridViewRowEventArgs e)\n{\n    switch (e.Row.RowType)\n    {\n        case DataControlRowType.Header:\n            foreach (DataColumn col in myDataTable.Columns)\n            {\n                if (col.ExtendedProperties["error"] != null)\n                {\n                    e.Row.Cells[col.Ordinal].CssClass = "error-cell";\n                    e.Row.Cells[col.Ordinal].ToolTip = col.ExtendedProperties["error"].ToString();\n                }\n            }                 \n            break;\n        case DataControlRowType.DataRow:\n\n            break;\n    }\n}	0
15701524	15701344	C# Addition of two 2-Dimensional Arrays	static void Main()\n{\n    // Your code\n\n    int[,] result = new int[row, col];\n\n    for (int i = 0; i < row; i++)\n    {\n        for (int j = 0; j < col; j++)\n        {\n            result [i, j] = a[i,j] + b[i,j];\n\n            Console.Write(result[i, j] + " ");\n        }\n\n        Console.WriteLine();\n    }\n}	0
22228159	22227804	Build visual studio solution from code	string projectFilePath = Path.Combine(@"c:\solutions\App\app.sln");\n\nProjectCollection pc = new ProjectCollection();\n\n// THERE ARE A LOT OF PROPERTIES HERE, THESE MAP TO THE MSBUILD CLI PROPERTIES\nDictionary<string, string> globalProperty = new Dictionary<string, string>();\nglobalProperty.Add("OutputPath", @"c:\temp");\n\nBuildParameters bp = new BuildParameters(pc);\nBuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0", new string[] { "Build" }, null);\n// THIS IS WHERE THE MAGIC HAPPENS - IN PROCESS MSBUILD\nBuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);\n// A SIMPLE WAY TO CHECK THE RESULT\nif (buildResult.OverallResult == BuildResultCode.Success)\n{              \n    //...\n}	0
18502105	18502053	Attribute that returns a single object from a List inside the same class	using System.Linq;\n\n    return CourseStatusList.OrderByDescending(s => s.InsertDate)\n                           .FirstOrDefault();	0
20682507	20682317	How to get the position of the paticular cell that the user click on in tablelayout in c#	You can get the location like this\n\n  private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)\n    {\n        int row = 0;\n        int verticalOffset = 0;\n        foreach (int h in tableLayoutPanel1.GetRowHeights())\n        {\n            int column = 0;\n            int horizontalOffset = 0;\n            foreach(int w in tableLayoutPanel1.GetColumnWidths())\n            {\n                Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);\n                if(rectangle.Contains(e.Location))\n                {\n                    Trace.WriteLine(String.Format("row {0}, column {1} was clicked", row, column));\n                    return;\n                }\n                horizontalOffset += w;\n                column++;\n            }\n            verticalOffset += h;\n            row++;\n        }\n    }	0
17020614	17020303	WPF delay a function that fills a table	private async void myFunc()\n{\n    while (SOME_CONDITION) {\n        await Task.Delay(X_MS);\n        this.myTable.RowGroups[0].Rows[SOME_ROW].Cells[SOME_COLUMN].Background = Brushes.Blue;\n    }\n}	0
5136009	5135971	regexp match in specific word in a sentence	string pattern = @"(\S+\s){5}\S*?h3\.asp";	0
8447052	8446977	How to map a property as NOT a column in EF 4.1	modelBuilder.Entity<classParty>().Ignore(x => x.ArrivedCount);	0
22640684	22638778	Avoid using the JsonIgnore attribute in a domain model	[DataContract]\npublic class Computer\n{\n  // included in JSON\n  [DataMember]\n  public string Name { get; set; }\n  [DataMember]\n  public decimal SalePrice { get; set; }\n\n  // ignored\n  public string Manufacture { get; set; }\n  public int StockCount { get; set; }\n  public decimal WholeSalePrice { get; set; }\n  public DateTime NextShipmentDate { get; set; }\n}	0
28823859	28823765	Serialization/Deserialization with prototype objects	JObject o1 = JObject.Parse(@"{\n  'FirstName': 'John',\n  'LastName': 'Smith',\n  'Enabled': false,\n  'Roles': [ 'User' ]\n}");\nJObject o2 = JObject.Parse(@"{\n  'Enabled': true,\n  'Roles': [ 'User', 'Admin' ]\n}");\n\no1.Merge(o2, new JsonMergeSettings\n{\n    // union array values together to avoid duplicates\n    MergeArrayHandling = MergeArrayHandling.Union\n});\n\nstring json = o1.ToString();\n// {\n//   "FirstName": "John",\n//   "LastName": "Smith",\n//   "Enabled": true,\n//   "Roles": [\n//     "User",\n//     "Admin"\n//   ]\n// }	0
17308231	17308103	how to set the OnSelectedIndexChanged in C# codebehind instead of ASP.net	makeControl.getlistbox().OnSelectedIndexChanged += this.Index_Changed\n\nvoid Index_Changed(Object sender, EventArgs e) {\n    // whatever you need to do on the event\n}	0
32161719	32161647	How to handle unescaped quote characters in XML attribute value?	"Thank you for your order! The order is currently being reviewed by a moderator. A moderator will contact you with a ("Quote") when the review is complete."	0
8836145	8835018	How the CLR locates pdb symbol files	using System;\nusing System.Runtime.CompilerServices;\nusing System.Reflection;\nusing System.IO;\n\nclass Program {\n    static void Main(string[] args) {\n        var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);\n        path = Path.Combine(path, "symbols");\n        Environment.SetEnvironmentVariable("_NT_SYMBOL_PATH", path);\n        try {\n            Kaboom();\n        }\n        catch (Exception ex) {\n            Console.WriteLine(ex.ToString());\n        }\n        Console.ReadLine();\n    }\n    [MethodImpl(MethodImplOptions.NoInlining)]\n    static void Kaboom() {\n        throw new Exception("test");\n    }\n}	0
30720135	30720010	How can I save values from a textbox (input == text) as Currency values in Sharepoint?	//assumes input has been validated\nspli["Airfare"] = double.Parse(boxAirfare.Text);	0
2214680	2214616	How do I build C# asp.net ajax wizard (or rather convert a PlaceHolder based wizard)	display: none	0
2848778	2848658	what is the most elegant way of showing first week in a month	public static IEnumerable<DateTime> GetFirstWeek(int year, int month) {\n    DateTime firstDay = new DateTime(year, month, 1);\n    firstDay = firstDay.AddDays(-(int) firstDay.DayOfWeek);\n    for (int i = 0; i < 7; ++i)\n        yield return firstDay.AddDays(i);\n}	0
23797061	23761015	Tools for form authentication in web application on the basis of user role in asp.net	if (User.IsInRole("admins")) {\n    //display the admin menu\n} else {\n    //display the non-admin menu\n}	0
13231080	13231032	Delete multiple rows with Entity Framework 5	context.Database.ExecuteSqlCommand\n     ("DELETE [MYSCHEMA].TABLE1 Where TABLE2_Id = 5");	0
11039969	11039755	How do I open a picture after creating it in C#?	var myBitmap = Bitmap.FromFile("c:\somefile.bmp");	0
7581121	7580998	Issue with radio buttons while firing Validations	protected void RadioButton1_CheckedChanged(object sender, EventArgs e)\n{\n    TextBox1.Enabled = RequiredFieldValidator1.Enabled = true;\n}\n\nprotected void RadioButton2_CheckedChanged(object sender, EventArgs e)\n{\n    TextBox1.Enabled = RequiredFieldValidator1.Enabled = false;\n}	0
18134268	18134050	Kill a process that use a certain image path	var imagePath = @"C:\applicationfolder";\nvar processes = Process.GetProcesses()\n                .Where(p => p.MainModule.FileName.StartsWith(imagePath, true, CultureInfo.InvariantCulture));\nforeach (var proc in processes)\n{\n    proc.Kill();\n}	0
19018436	19018368	Webrowser manipulate HTML Table	HtmlElementCollection inputHtmlCollection = Document.GetElementsByTagName("input");\n foreach (HtmlElement anInputElement in inputHtmlCollection)\n{\n                    if (anInputElement.Name.Equals("portal_id"))\n                    {\n                        anInputElement.SetAttribute("VALUE", Properties.Settings.Default.sharepoint_user);\n                    }\n                    if (anInputElement.Name.Equals("password"))\n                    {\n                        anInputElement.SetAttribute("VALUE",  roperties.Settings.Default.sharepoint_pw);\n                    }\n}	0
8691937	8691786	CollectionViewSource Sorting Dynamically	var properties = new List<string>();\n\n        foreach (var info in typeof(Car).GetProperties())\n        {\n            properties.Add(info.Name);\n        }\n        cbxSortPrimary.ItemsSource = properties;	0
390503	390491	How to add item to the beginning of List<T>?	ti.Insert(0, initialItem);	0
24862797	24808014	Convert base64 encoding to pdf	byte[] sPDFDecoded = Convert.FromBase64String(base64BinaryStr);\n\n\n            File.WriteAllBytes(@"c:\Users\u316383\Documents\pdf8.jpg", sPDFDecoded);	0
10882120	10877631	Getting Geometry length	public static double GetLength(this Geometry geo)\n    {\n        PathGeometry path = geo.GetFlattenedPathGeometry();\n\n        double length = 0.0;\n\n        foreach (PathFigure pf in path.Figures)\n        {\n            Point start = pf.StartPoint;\n\n            foreach (PolyLineSegment seg in pf.Segments)\n            {\n                foreach (Point point in seg.Points)\n                {\n                    length += Distance(start, point);\n                    start = point;\n                }\n            }\n        }\n\n        return length;\n    }\n\n    private static double Distance(Point p1, Point p2)\n    {\n        return Math.Sqrt(Math.Pow(p1.X - p2.X,2) + Math.Pow(p1.Y - p2.Y,2));\n    }	0
22079150	22078774	Calling async method from webservice	GetIbuttonDataInput input = new GetIbuttonDataInput {ibuttonId ="x", testerName ="me"};\ngetIbuttonDataResponse x = await getIbuttonDataAsync(input);	0
33071555	33071498	Naming an object that is an attribute of another object with the same getter/setter as Object Type	class Foo\n{\n   Bar Bar {get; set; }\n}	0
27981713	27981491	Get % of Each item from List<ListItem>	namespace ConsoleApplication\n{\n    public class Test\n    {\n        public string name { get; set; }\n        public int count { get; set; }\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n                List<Test> testList = new List<Test>();\n                testList.Add(new Test { name = "yes", count = 1 });\n                testList.Add(new Test { name = "no", count = 0 });\n                testList.Add(new Test { name = "can't say", count = 3 });\n\n\n                var totalCount = testList.Sum(c => c.count);\n\n                foreach(var item in testList)\n                {\n                    Console.WriteLine(string.Format("{0} {1}", (decimal)item.count / totalCount * 100, item.name));\n                }\n\n                Console.ReadKey();\n        }\n    }\n}	0
3142157	3142088	How to get the MAC address prior to connection?	internal static string GetMAC(string ip)\n    {\n        IPAddress dst = IPAddress.Parse(ip); // the destination IP address Note:Can Someone give the code to get the IP address of the server\n\n        byte[] macAddr = new byte[6];\n        uint macAddrLen = (uint)macAddr.Length;\n        if (SendARP((int)dst.Address, 0, macAddr, ref macAddrLen) != 0)\n            throw new InvalidOperationException("SendARP failed.");\n\n        string[] str = new string[(int)macAddrLen];\n        for (int i = 0; i < macAddrLen; i++)\n            str[i] = macAddr[i].ToString("x2");\n        return string.Join(":", str);\n        //Console.WriteLine(string.Join(":", str));\n    }	0
10472598	10471428	split string to string biulder with removing all words match the pattern	using System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string value = "one or:another{3}";\n        Regex exclude = new Regex(@"\d|\s|/|-", RegexOptions.Compiled);\n        string final = string.Join(" ",\n            (from s in Regex.Split(value, "([ \\t{}():;.,?\"\n])")\n                where s.Length > 2 && !exclude.IsMatch(s)\n                select s.Replace("??","?")).ToArray());\n\n        // to get the List<string> instead:\n        List<string> l = (from s in Regex.Split(value, "([ \\t{}():;.,?\"\n])")\n            where s.Length > 2 && !exclude.IsMatch(s)\n            select s.Replace("??","?")).ToList();\n    }\n}	0
4224709	4224654	dependency injection into a set of classes	public interface IDependency\n{\n}\n\npublic abstract class A\n{\n    protected IDependency _dep;\n\n    protected A(IDependency dep)\n    {\n        _dep = dep;\n    }\n}\n\npublic class B : A\n{\n    public B(IDependency dep) : base(dep)\n\n    {\n    }\n}	0
17808481	17808427	Remove specific symbol from string	string newString = originalString.Trim(new[] {'{', '}'});	0
16873963	16873927	Remove duplicate values in collection	mydIds = mydIds.Distinct().ToList();	0
26339133	26339099	Is there a one line way I can find the length of the longest of two C# strings?	Math.Max(c==null?0:c.Length, r==null?0:r.Length)	0
16573149	14710968	How can I set the calendar property on my MSProject project?	app.ProjectSummaryInfo(\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing,\n                       "Noche",\n                       Type.Missing,\n                       Type.Missing,\n                       Type.Missing);	0
15401554	15401531	EntityFramework Rollback All Transactions if One Object Fails	_dbContext.Table1.AddObject(object1);\n_dbContext.Table2.AddObject(object2);\n_dbContext.Table3.AddObject(object3);\n_dbContext.Table4.AddObject(object4);\n_dbContext.Table5.AddObject(object5);\n_dbContext.SaveChanges(); // if fails will roll back all objects	0
12851753	12851433	Regex group string replace issue	var regex = new Regex(@"\bA\b|\bB\b")	0
12543570	12543534	How to know current new object's ID in advance, before saving?	//don't save the image yet, or save it in a temporary location\ndb.Products.AddObject( product );\ndb.SaveChanges();\nproduct.ImagePath = //path including product.Id\n//save or move image to product.ImagePath\ndb.SaveChanges();	0
30164061	30163737	Drop down values are not getting listed in combobox in winform	this.Refresh()	0
18387554	18387189	C# lambda group query with two parameters?	var carTurns = new[] { ct1, ct2, ct3, ct4 };\nvar groupedCarTurns = carTurns.GroupBy(ct => ct.Car);\nvar oneSideCount = groupedCarTurns.Count(group =>\n    group.All(ct => ct.Turn == right) ||\n    group.All(ct => ct.Turn == left);\nvar bothSides = groupedCarTurns.Count(group =>\n    group.Any(ct => ct.Turn == right) &&\n    group.Any(ct => ct.Turn == left);	0
11225109	11225004	To display Text On Notify Icon Mouse Over	public string Text { get; set; }	0
13997194	13995529	Implement List treenode for extjs tree	comd.CommandText = "SELECT * FROM MyTable";\n\ncon.Open();\nSqlDataReader reader = comd.ExecuteReader();\nwhile (reader.Read())\n{\n    City myData = new City();\n    myData.State = reader["State"].ToString().Trim();\n    myData.Cities = reader["Cities"].ToString().Trim();\n    giveData.Add(myData);\n}  \nint count = 1;\nDictionary<string, TreeNode> result = new Dictionary<string, TreeNode>();\nforeach (City myData in giveData) \n{\n    if (result.ContainsKey(myData.State ))\n    {\n        result[myData.State].children.Add(new TreeNode() {\n            id = count++,\n            name = myData.Cities,\n            leaf = true\n        });\n    }\n    else\n    {\n        result.add(giveData.State, new TreeNode() {\n            id = count++,\n            name = myData.State,\n            leaf = false,\n            children = new List<TreeNode>()\n        });\n    }\n}\n\nreturn JsonConvert.SerializeObject(result.Values);	0
32819128	32815565	How do I generate the shortest database identifier names from a number?	public static String intToDatabaseIdentifier(int number)\n    {\n        const string abcFirst = "abcdefghijklmnopqrstuvwxyz";\n        const string abcFull = "abcdefghijklmnopqrstuvwxyz0123456789";\n        if (number < 0 || number > 1000000)\n            throw new ArgumentOutOfRangeException("number");\n        var stack = new Stack<char>();\n        //Get first symbol. We will later reverse string. So last - will be first. \n        stack.Push(abcFirst[number % abcFirst.Length]);\n        number = number / abcFirst.Length;\n        //Collect remaining part\n        while (number > 0)\n        {\n            int index = (number - 1) % abcFull.Length;\n            stack.Push(abcFull[index]);\n            number = (number - index) / abcFull.Length;\n        }\n        //Reversing to guarantee first non numeric.\n        return new String(stack.Reverse().ToArray());\n    }	0
7607106	7607035	Duplicates in results from .ToArray in LinQ query	string[][] results = query.Distinct().ToArray();	0
23957164	23957027	Best way to implement a generic method in a type generic/agnostic way	private readonly Dictionary<Type, Delegate> obfuscators =\n    new Dictionary<Type, Delegate>;\n\n// Alternatively, register appropriate obfuscators on construction.\npublic void RegisterConverter<T>(Func<T, T> obfuscator)\n{\n    obfuscators[typeof(T)] = obfuscator;\n}\n\npublic T Obfuscate<T>(T value)\n{\n    Delegate obfuscator;\n    if (obfuscators.TryGetValue(typeof(T), out obfuscator)\n    {\n        // We know it'll be the right type...\n        var realObfuscator = (Func<T, T>) obfuscator;\n        return realObfuscator(value);\n    }\n    // ??? Throw exception? Return the original value?\n}	0
33760686	33746435	How to query a Foxpro .DBF file with .NDX index file using the OLEDB driver in C#	string myCommand = @"Use ('P:\Test\DSPC-1') alias myData\nSet Index To ('P:\Test\DSPC-1_Custom.NDX')\nselect * from myData ;\n  where dp_file = '860003' ;\n  into cursor crsResult ;\n  nofilter\nSetResultset('crsResult')";\n\nDataTable resultTable = new DataTable();\nusing (oleDbConnection = new OleDbConnection(@"Provider=VFPOLEDB;Data Source=P:\Test"))\n{\n  oleDbConnection.Open();\n  OleDbCommand command = new OleDbCommand("ExecScript", oleDbConnection);\n  command.CommandType = CommandType.StoredProcedure;\n  command.Parameters.AddWithValue("code", myCommand);\n\n  resultTable.Load(cmd.ExecuteReader());\n  oleDbConnection.Close();\n}	0
18171029	18170985	Null value in a parameter varbinary datatype	cmd.Parameters.Add( "@Image", SqlDbType.VarBinary, -1 );\n\ncmd.Parameters["@Image"].Value = DBNull.Value;	0
27428288	27426124	Problems with mapping relationship in EF	public class CameraDisplayMap {\n    public int Id { get; set; } //primary key\n\n    public int? SetupGroupId { get; set; }       //foreign key to [SetupGroup]\n    public int? CameraId { get; set; }           //foreign key to [Camera]\n    public int? DisplayId Displays { get; set; } //foreign key to [Display]\n\n    public virtual SetupGroup SetupGroups { get; set; }\n    public virtual Camera Cameras { get; set; }\n    public virtual Display Displays { get; set; }\n}	0
19283377	19283287	Equivalent of (IntPtr)1 in VBNET?	SendMessage(hText, WM_SETFONT, mFont.ToHfont(), New IntPtr(1))	0
1200999	1199519	How to add custom properties to a custom webcontrol	public class MyCustomGrid : GridView\n{\n  [...]\n  private MyCustomSettings customSettings;\n  [PersistenceMode(PersistenceMode.InnerProperty),DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n  public MyCustomSettings CustomSettings\n        {\n            get { return customSettings; }\n        }\n  [...]\n}\n\n[TypeConverter(typeof(MyCustomSettings))]\npublic class MyCustomSettings \n{\n  private string cssClass = "default";\n  public string CssClass\n  {\n    get { return cssClass; }\n    set { cssClass = value; }\n  }\n}	0
2127176	2127128	how to update a cell in DataGrid which is binded with string[][] array	dataGrid.ItemSource	0
32394975	32394797	How do I create a method for changing forms easily?	ShowDialog();\nClose();	0
30397740	30372003	How to retrieve the check state of CheckBox from database while the CheckBox control is on the DataRepeater	foreach ( DataRepeaterItem rowItem in dataRepeater1.Controls )\n    {\n        if (((Label)rowItem.Controls["stateLabel1"]).Text == "1") \n        { \n            ((CheckBox)rowItem.Controls["checkBox1"]).Checked = true; \n        } \n        else \n        { \n            ((CheckBox)rowItem.Controls["checkBox1"]).Checked = false; \n        } \n    }	0
9328208	9328139	Alternative Data Structure to DataTable	List<object[]>	0
13492624	13492562	How can I get row and column id of an Excel sheet in my winform application	Excel.Range range = (Excel.Range)CurrentWorksheetObject.Cells[row, col];\n   string cellAddress = range.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);	0
8929807	8929778	Cant find the right syntax?	public static void CopyProperties<T1, T2>(T1 objA, T2 objB) \n    where T1 : new()\n    where T2 : new()\n{\n}	0
14878255	14758915	Get All Processes With Their Corresponding App Domains	CorPublish cp = new CorPublish();\nforeach (CorPublishProcess process in cp.EnumProcesses())\n            {\n                    foreach (CorPublishAppDomain appDomain in process.EnumAppDomains())\n                    {\n\n                    }\n                }	0
4665633	4665613	PageIndexChanging in GridView in ASP.NET	protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    FillGrid();\n    grdView.PageIndex = e.NewPageIndex;\n    grdView.DataBind();\n}	0
7099807	7099741	C# list sort by two columns	result.Sort((x,y) => x.CheckedIn==y.CheckedIn ? \n  string.Compare(x.LastName, y.LastName) : \n  (x.CheckedIn ? -1 : 1) );	0
7801554	7801361	Multithreading in Sqlite	int sqlite3_errcode(sqlite3 *db); \nconst char *sqlite3_errmsg(sqlite3*);	0
3556581	3556535	Object Arrays in Console Application	static void Main() \n    { \n        User[] users = new User[2];\n\n        for (int i=0;i<users.Length; i++) \n        {  \n            users[i] = new User();\n            InputUser(users[i]);  \n        }            \n    }	0
29351554	29350012	MVC route matching routes that aren't valid	// Default Route\n routes.MapRoute(\n   name: "Default",\n   url: "{controller}/{action}/{id}",\n   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, \n   namespaces: new string[] { "DMP.Core.Web.Controllers" }\n        ).DataTokens["UseNamespaceFallback"] = false;	0
20614228	20560522	Print preview issue in Steema Teechart with graphics3d	private void InitializeChart()\n{\n  tChart1.Graphics3D = new Graphics3DDirect2D(tChart1.Chart);\n  tChart1.Aspect.View3D = false;\n  FastLine series = new FastLine(tChart1.Chart);\n  series.FillSampleValues(1000);\n\n}\n\nTChart tChart2;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n  if(tChart2 == null) tChart2 = new TChart();\n\n  MemoryStream ms = new MemoryStream();\n  tChart1.Export.Template.Save(ms);\n  ms.Position = 0;\n  tChart2.Import.Template.Load(ms);\n\n  tChart2.Export.Image.PNG.Width = tChart1.Width;\n  tChart2.Export.Image.PNG.Height = tChart1.Height;\n  tChart2.Export.Image.PNG.Save(@"C:\tmp\direct2d.png");\n}	0
20225100	20225044	How do i concatenate a variable to a SqlCeCommand?	SqlCeCommand command = new SqlCeCommand("SELECT * FROM Movie WHERE Genre = @genre", connection);\ncommand.Parameters.AddWithValue("@genre", genre);	0
11071574	11071555	Date in c# xml parsing	private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, \n                                                      DateTimeKind.Utc);\n\npublic static DateTime UnixTimeToDateTime(string text)\n{\n    double seconds = double.Parse(text, CultureInfo.InvariantCulture);\n    return Epoch.AddSeconds(seconds);\n}	0
20403691	20403217	fill object from a returned dataset in C#	using (DbDataReader reader = command.ExecuteReader()) {\n  while (reader.Read()) {\n    PaymentAccDetails pad = new PaymentAccDetails();\n    pad.PaymentRef = reader.GetString(0);\n    [fill other properties]\n    [add to list]\n  }\n}	0
23037194	23024105	ComboBox DropDownList searching for text	private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    SortedDictionary<int, ListInfo> dict = new SortedDictionary<int, ListInfo>();\n\n    int found = -1;\n    int current = comboBox1.SelectedIndex;\n\n    // collect all items that match:\n    for (int i = 0; i < comboBox1.Items.Count; i++)\n        if (((ListInfo)comboBox1.Items[i]).Name.ToLower().IndexOf(e.KeyChar.ToString().ToLower()) >= 0)\n        // case sensitive version:\n        // if (((ListInfo)comboBox1.Items[i]).Name.IndexOf(e.KeyChar.ToString()) >= 0)\n                dict.Add(i, (ListInfo)comboBox1.Items[i]);\n\n    // find the one after the current position:\n    foreach (KeyValuePair<int, ListInfo> kv in dict)\n             if (kv.Key > current) { found = kv.Key; break; }\n\n    // or take the first one:\n    if (dict.Keys.Count > 0 && found < 0) found = dict.Keys.First();\n\n    if (found >= 0) comboBox1.SelectedIndex = found;\n\n    e.Handled = true;\n\n}	0
6490242	6490170	Getting screenshots of web pages	System.Windows.Forms.WebBrowser	0
30420034	30419941	Does a primitive type get boxed when declared as a dynamic	Func<string, object>	0
4638436	4638427	How to close a webform IN C# LANGUAGE?	window.close	0
7763743	7763687	Advanced C# pattern search in long string (100-25000 char)	Dictionary<string, int>	0
13073483	13073420	how to get the return value from a JS dialog box in asp.net without tying it to a button	__doPostBack(control, arg);	0
24816591	24816563	Replace substring inside a string with a new GUID for each substring found	var result = Regex.Replace(text, "<p>", _ => \n       "<p data-paragraph-id=" + Guid.NewGuid().ToString() + ">");	0
32824241	32823962	Extract a text from a file c#	string prefix = "Message=";\n        string postfix = "Message=END";\n\n        var text = File.ReadAllText("a.txt");\n        var messageStart = text.IndexOf(prefix) + prefix.Length;\n        var messageStop = text.IndexOf(postfix);\n        var result = text.Substring(messageStart, messageStop - messageStart);	0
8604770	8604607	Do EntityObjects have a PropertyChanged event that allows me to access OldValue and NewValue?	public global::System.String Property\n    {\n        get\n        {\n            return _Property;\n        }\n        set\n        {\n            OnPropertyChanging(value);\n            ReportPropertyChanging("Property");\n            _Property = StructuralObject.SetValidValue(value, false);\n            ReportPropertyChanged("Property");\n            OnPropertyChanged();\n        }\n    }\n\n    private global::System.String _Property;\n    partial void OnPropertyChanging(global::System.String value);\n    partial void OnPropertyChanged();	0
19097925	19097836	How to convert Linq expression with multiple joins into method syntax OR retrieve select index?	var query = //your original query goes here\n\nvar finalQuery = query.AsEnumerable()\n    .Select((answer, index) => new\n        {\n            answer.SubmissionId,\n            answer.Answer,\n            Code = index,\n        });	0
10611730	10611615	Checking textbox for valid input in a loop or try catch c#	int number;\nif(string.IsNullOrEmpty(guessInput.Text))\n{\n  MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);\n  return;\n}\nif(Int32.TryParse(guessInput.Text, out number))\n{\n  guessInt = number; \n}else\n{\n  MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values",      MessageBoxButtons.OK, MessageBoxIcon.Error);\n   guessInput.Text = "";\n   return;\n}\n\n\n// when come to here you have guessInt, process it \n\n   guess.Enabled = false;\n    next_Guess.Enabled = true;\n\n    if (guessInt == randomArray[x])\n    {\n        result.Text = ("You Win! The correct number was " + randomArray[x]);\n        right += 1;\n        correctAnswers.Text = right.ToString();\n\n    }\n    else\n    {\n        result.Text = ("Sorry you lose, the number is " + randomArray[x]);\n        wrong += 1;\n        incorrectAnswers.Text = wrong.ToString();\n\n    }\n\n    hintLabel.Enabled = false;\n    x++;	0
32488635	32488085	C# Dictionary As Application Cache	public Dictionary<string, List<ParameterValues>> LoadParameterCache2()\n{\n    List<KeyValuePair<string, ParameterValues>> dataValues = new List<KeyValuePair<string, ParameterValues>>();\n\n    // Your code to produce the DataReader\n    DataTableReader rdr = GetDataReader();\n\n    while (rdr.Read())\n    {\n        ParameterValues cacheObj = new ParameterValues();\n        cacheObj.ParameterKey = (string)rdr["PARAMETER_KEY"];\n        cacheObj.ParameterValue = (string)rdr["PARAMETER_VALUE"];\n\n        KeyValuePair<string, ParameterValues> dataValue = new KeyValuePair<string, ParameterValues>((string)rdr["GROUP_CODE"], cacheObj);\n\n        dataValues.Add(dataValue);\n    }\n\n    Dictionary<string, List<ParameterValues>> objList = dataValues.GroupBy(d => d.Key).ToDictionary(k => k.Key, v => v.Select(i => i.Value).ToList());\n\n    return objList;\n}	0
29834253	29834223	LINQ to JSON - Select Individual properties belong to a navigational property	var nodes = await dbContext.MonProfiles.Include(x => x.Nodes).\n        Where(x => x.Id == profileId).\n        SelectMany(x => x.Nodes.\n            Select(y => new { y.NodeNativeId, y.NodeClassId, y.NodeName, y.NodeClass.ClassName })).\n            ToListAsync();	0
20431739	20431580	How can I simplify my codeblock?	try\n        {\n            HttpWebRequest _request = _httpUrl;\n            _request.Method = "GET";\n\n            if (_httpProxy != null)\n            {\n                _request.Proxy = _httpProxy;\n                proxymessage = "with Proxy";\n            }\n            else\n                proxymessage = "without Proxy";\n\n            _response = (HttpWebResponse)_request.GetResponse();\n            _strBuilderVerbose.Append(String.Format("HttpWebRequest {0} was successful",proxymessage));\n            return true;\n        }\n        catch (WebException e)\n        {\n            _strBuilderVerbose.Append(String.Format("Catch 'WebException e' {0} was called",proxymessage));\n            if (e.Status == WebExceptionStatus.ProtocolError) _response = (HttpWebResponse)e.Response;\n            else return false;\n        }\n        catch (Exception)\n        {\n            if (_response != null) _response.Close();\n            return false;\n        }\n\n        return true;\n    }	0
20664211	20663630	EF 6: The result of a query cannot be enumerated more than once	Func<Trade, bool> filter1 = t => t.A > 10;\n Func<Trade, bool> filter2 = t => t => t.B > 10;\n Func<Trade, bool> compositeFilter = t => filter1(t) && filter2(t);\n\n int totalCount = _db.Trades.Count(filter1);\n int totalCountAfterAdditionalFilter  = _db.Trades.Count(compositeFilter);\n\n //Need more?\n compositeFilter = t => compositeFilter(t) && t.C > 100;\n int totalAfterMoreFilters = _db.Trades.Count(compositeFilter);	0
2182023	2180363	MSTest with Moq - DAL setup	[TestMethod]\npublic void GetNotifications_PassedNullFoo_ReturnsData()\n{\n     //Arrange\n     Mock<IDatabase> mockDB = new Mock<IDatabase>();\n     mockDB.Setup(db => db.ExecuteDataSet()).Returns(new DataSet() ... );\n\n     //Act\n     FooClass target = new fooClass();\n     var result = target.GetNotifications(null, "Foo2", mockDB.Object);\n\n     //Assert\n     Assert.IsTrue(result.DataSet.Rows.Count > 0);\n}	0
28894361	28894110	How to count occurences of an int in an array?	int[] a = new int[] \n   { 2, 3, 4, 3, 4, 2, 4, 2, 4 };\n\n  // I'd rather not used array, as you suggested, but dictionary \n  Dictionary<int, int> b = a\n    .GroupBy(item => item)\n    .ToDictionary(item => item.Key, item => item.Count());\n\n ...\n\nthe outcome is\n\n  b[2] == 3;\n  b[3] == 2;\n  b[4] == 4;	0
11561607	11561544	NullReferenceException was unhandled in c# array	ArrayList list = read();\nint N = Values.N;\nstring pt = Values.PlainText;\nMessageBox.Show(""+pt.Length+" "+pt[0]);\nint count = 0;\nchar[][][] array = new char[6][][];\nfor(int i=0;i<6;i++)\n{\n    for(int j=0;j<N;j++)\n    {\n        array[i] = new char[N][]; // <---- Note\n        for(int k=0;k<N;k++)\n        {\n            array[i][j] = new char[N]; // <---- Note\n            if (count < pt.Length)\n            {\n                array[i][j][k] = 'r';\n                //array[i][j][k] = pt[count];\n                //count++;\n            }\n            else\n            {\n                array[i][j][k] = 'x';\n            }\n        }\n    }\n}	0
32697194	32696586	Pass arguments from aspx to user control code behind	var myDefault = (MyDefaultPage) this.Page();\n    string discount = myDefault.strDiscount	0
22357054	22338924	Rackspace cloud files REST api inexplicably getting bad request response	request.AddParameter("application/json", serText, ParameterType.RequestBody);	0
26513100	26511214	How to limit a textbox to only numbers and a single decimal point on key press event?	private void txtPurchasePrice_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&\n        (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
22529572	22529331	How do I match a string in a list to a word in a sentence?	var match = browserList.Where(sentence.Contains).FirstOrDefault() ??\n            mediaPlayerList.Where(sentence.Contains).FirstOrDefault();	0
22996594	22996535	Using auto increment column	String insertString = @"INSERT INTO coupons(title, description, imagepath, couponpath, barcodepath, downloadedon, redeemedon, starttime, endtime, status, statustext)\nVALUES(@title, @description, @imagepath, @couponpath, @barcodepath, @downloadedon, @redeemedon, @starttime, @endtime, @status, @statustext)";	0
11715705	11715533	reading xml file using xmlreader	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\n\nnamespace XmlReading\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            //Create an instance of the XmlTextReader and call Read method to read the file            \n            XmlTextReader textReader = new XmlTextReader("D:\\myxml.xml");\n            textReader.Read();\n\n            XmlDocument xmlDoc = new XmlDocument();\n            xmlDoc.Load(textReader);\n\n            XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");\n            XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");\n            for (int i = 0; i < BCode.Count; i++)\n            {\n                if (BCode[i].InnerText == "001")\n                    Console.WriteLine(BName[i].InnerText);                \n            }\n\n            Console.ReadLine();\n        }\n    }\n}	0
765238	765225	How to get the Handle of the form with get{set?	public int GetHandle\n    {\n        get\n        {\n            if (this.InvokeRequired)\n            {\n                return (int)this.Invoke((GetHandleDelegate)delegate\n                {\n                    return this.Handle.ToInt32();\n                });\n            }\n            return this.Handle.ToInt32();\n        }\n    }\nprivate delegate int GetHandleDelegate();	0
26521478	26502377	Moving Email Attachment to another folder in Outlook	foreach (Attachment Attach in EWSItem.Attachments)\n        {\n            if (Attach is ItemAttachment)\n            {\n                PropertySet psProp = new PropertySet(BasePropertySet.FirstClassProperties);\n                psProp.Add(ItemSchema.MimeContent);\n                ((ItemAttachment)Attach).Load(psProp);\n                if (((ItemAttachment)Attach).Item.MimeContent != null)\n                {\n                    EmailMessage NewMessage = new EmailMessage(service);\n                    NewMessage.MimeContent = ((ItemAttachment)Attach).Item.MimeContent;\n                    NewMessage.SetExtendedProperty(new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer), "1");\n                    NewMessage.Save(folderItemToMove.Id);\n                }\n            }\n        }	0
12864655	12786073	How to send keys to the website using their element IDs in C# ASP.Net?	protected void Button1_Click(object sender, EventArgs e)         \n{\n    IWebDriver driver = \n        new InternetExplorerDriver(@"C:\.....\IEDriverServer_Win32_2.25.2"); \n\n    driver.Navigate().GoToUrl("https://website.com/login.asp");\n\n    // Find the text input element by its name\n    // username\n\n    IWebElement name_ID = driver.FindElement(By.Name("name_ID"));\n    name_ID.SendKeys("xyzw");\n\n    // password\n    IWebElement pwd_PW = driver.FindElement(By.Name("pwd_PW"));\n    pwd_PW.SendKeys("fasdfasfdasdf");\n\n    // submit login form\n    IWebElement sSubmit = driver.FindElement(By.Name("submit"));\n    submit.Submit();\n    System.Threading.Thread.Sleep(5000);\n    driver.Quit();\n}	0
24009219	24008924	Unable to insert current_timestamp in MySQL using c# Stored Procedure	command.Parameters.Add(new MySqlParameter("@Created_Date", MySqlDbType.Timestamp)).Value = DateTime.Now;	0
25455145	25455017	How to access existing NLog MemoryTarget	var target =(MemoryTarget)LogManager.Configuration.FindTargetByName("MemLogger");\n\nforeach (string log in target.Logs)\n{\n    var parts = log.Split('|');\n    var date = parts[0].Replace("TimeStamp:[", "").TrimEnd(']');\n    var message = parts[1];\n    var type = parts[2];\n    //...\n}	0
13376119	13375950	Changing base class for WPF page code behind	public partial class MainWindow \n{\n    public MainWindow()\n    {\n        InitializeComponent();\n\n    }\n}\n\npublic class CustomPage : Window\n{\n    public string PageProperty { get; set; }\n}\n\n<myWindow:CustomPage x:Class="WpfApplication4.MainWindow"\n    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n    xmlns:myWindow="clr-namespace:WpfApplication4"\n    Title="MainWindow" Height="800" Width="800">\n<Grid>\n</Grid>\n</myWindow:CustomPage>	0
26093150	26093097	How to access a Control variable by a string?	Random rnd = new Random();\nint x= rnd.Next(1, 10);\nstring ime = "pictureBox" + x.ToString();\n((PictureBox)frm.Controls.Find(ime ,true)[0]).BackColor = Color.CornflowerBlue;	0
22006274	21930704	How to get Whats New field value from TFS	if ((f.Name.Equals(Consts.WHATS_NEW) && f.Value != null))\n                    this.WhatsNew = (String)f.Value;	0
9172542	9172112	Checkbox inside a datatable	DataTable dt = new DataTable();\n    dt.Columns.Add(new DataColumn("Action", typeof(bool)));            \n    dt.Rows.Add(0);\n    dt.Rows.Add(1);\n    GridView1.DataSource = dt;\n    GridView1.DataBind();	0
16827141	16827123	Adding String to a List - Quicker way?	var apptList = appointments.Select(a => a.Subject).ToList();	0
20704588	20694575	Handle exception from nHibernate EnumStringType when enum values don't match string values	public class MyEnumType : EnumMappingBase\n{\n    public MyEnumType()\n        : base(typeof(MyEnum))\n    {}\n\n    public override object GetInstance(object code)\n    {\n        // Set the desired default value\n        MyEnum instanceValue = MyEnum.Enum1;\n        Enum.TryParse(code, true, out instanceValue);\n\n        return instanceValue;    \n    }\n}	0
33739230	33738998	Comparing the properties of 2 objects with the same interface	bool IsEqual(IPropertyComparer o1, IPropertyComparer o2)\n{\n    var props = typeof(IPropertyComparer).GetProperties();\n\n    foreach(var prop in props)\n    {\n        var v1 = prop.GetValue(o1);\n        var v2 = prop.GetValue(o2);\n\n        if(v1 == null)\n        {\n            if(v2 != null) return false;\n        }\n        else\n        {\n            if(!v1.Equals(v2)) return false;\n        }\n    }\n\n    return true;\n}	0
6667751	6667621	How to reference all instances of a generic class?	interface ISomeClass\n{\n    bool IsActive {get;}\n}\n\npublic abstract SomeClass<T> : ISomeClass where T : SomeInterface\n{\n    public bool DoSomethingsWithT(T theItem)\n    {\n        //doStuff!!!\n    }\n\n    public virtual bool IsActive\n    {\n       get { return true; }  \n    }\n}\n\npublic bool SomeMethod(object item)\n{\n    var something = item as ISomeClass;\n\n    return something.IsActive;\n}	0
7493318	7493117	Code to parse text within files slows to a halt c#	Regex exp = new Regex(@"dojo\.require\([""'][\w\.]+[""']\)", RegexOptions.IgnoreCase | RegexOptions.Compiled);	0
4000786	4000708	DataGridView with CheckBox cell problem	void dataGridView1_CurrentCellDirtyStateChanged(object sender,\n    EventArgs e)\n{\n    if (dataGridView1.IsCurrentCellDirty)\n    {\n        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n    }\n}	0
33975713	33975579	How to match user credentials against text file contents in C#	protected void login(string command, string param1, string param2) // string command "login" string username, string password\n{\n    if (command == "login")\n    {\n        var logins = File.ReadAllLines(@"C:\\Files\\accounts.txt");\n        if (logins.Any(l => l == string.Format("{0} {1}", param1, param2)))\n            Console.WriteLine("login {0} successful", param1);\n        else\n        {\n            //log audit details\n            Console.WriteLine("invaild username/password");\n        }\n    }\n}	0
13267115	13267055	How can I convert formatted string to int (if I know format) in C#?	mytext = System.Text.RegularExpressions.Regex.Replace(mytext.Name, "[^.0-9]", "");	0
609529	609501	Generating a Random Decimal in C#	/// <summary>\n/// Returns an Int32 with a random value across the entire range of\n/// possible values.\n/// </summary>\npublic static int NextInt32(this Random rng)\n{\n     unchecked\n     {\n         int firstBits = rng.Next(0, 1 << 4) << 28;\n         int lastBits = rng.Next(0, 1 << 28);\n         return firstBits | lastBits;\n     }\n}\n\npublic static decimal NextDecimal(this Random rng)\n{\n     byte scale = (byte) rng.Next(29);\n     bool sign = rng.Next(2) == 1;\n     return new decimal(rng.NextInt32(), \n                        rng.NextInt32(),\n                        rng.NextInt32(),\n                        sign,\n                        scale);\n}	0
1507303	1507266	C# loopless way to split string into multidimensional array or jagged array	String s = "1:2;1:3;1:4";\nString[][] f = s.Split( ';' ).Select( t => t.Split( ':' ) ).ToArray();	0
8583893	8583808	Convert code from Windows Form Application to WPF?	private void BoxChatAreaKeyPress(object sender, KeyEventArgs e)\n{\n    var xBox = (RichTextBox)sender;\n\n    // Setting a limit so the user cannot type more than 4000 characters at once\n    var textRange = new TextRange(xBox.Document.ContentStart, xBox.Document.ContentEnd);\n    var textLen = textRange.Text.Trim();\n\n    if (textLen.Length <= 4000)\n    {\n        if ((textLen.Length > 1) && (e.Key == Key.Enter))\n        {\n            WriteMessage(xBox);\n        }\n    }\n    else\n    {\n        e.Handled = true;\n    }\n}	0
27553280	27553205	Opening a MongoDB GridFS by name with C# Driver	var url = new MongoUrl("mongodb://localhost");\nvar Client = new MongoClient(url);\nvar Server = Client.GetServer();\nvar Database = Server.GetDatabase("test");\nvar collection = Database.GetCollection("test");\n\nvar set = new MongoGridFSSettings {UpdateMD5 = true, ChunkSize = 512*1024, VerifyMD5 = false};\n\n// you can set the name here\nset.Root = "mycol";\nvar grid = Database.GetGridFS(set);\n\n// Upload\ngrid.Upload(@"C:\Users\Hamid\Desktop\sample.txt", "remote");\n\n// Download\ngrid.Download(@"C:\Users\Hamid\Desktop\sample2.txt", "remote");	0
18766662	18765730	Photo orientation after save VideoBrush to Image	captureDevice.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation,\n                                  cameraViewTransform.YourOrientation);	0
21635001	21634980	c# finding file in directories	Directory.GetFiles(@"c:\plugins\", "plugin.json", SearchOption.AllDirectories);	0
33110293	33109095	Horizontal Listbox	listView1.View = View.Tile;\nlistView1.Alignment = ListViewAlignment.Left;\nlistView1.OwnerDraw = true;\nlistView1.DrawItem += listView1_DrawItem;\nlistView1.TileSize = new Size(48,\n  listView1.ClientSize.Height - (SystemInformation.HorizontalScrollBarHeight + 4));\nfor (int i = 0; i < 25; ++i) {\n  listView1.Items.Add(new ListViewItem(i.ToString()));\n}\n\nvoid listView1_DrawItem(object sender, DrawListViewItemEventArgs e) {\n  Color textColor = Color.Black;\n  if ((e.State & ListViewItemStates.Selected) != 0) {\n    e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);\n    textColor = SystemColors.HighlightText;\n  } else {\n    e.Graphics.FillRectangle(Brushes.White, e.Bounds);\n  }\n  e.Graphics.DrawRectangle(Pens.DarkGray, e.Bounds);\n\n  TextRenderer.DrawText(e.Graphics, e.Item.Text, listView1.Font, e.Bounds,\n                        textColor, Color.Empty,\n                        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n}	0
18906661	18906629	Insert sound and image on messagebox in maze	public void playSound(int deviceNumber)\n{\n    disposeWave();// stop previous sounds before starting\n    waveReader = new NAudio.Wave.WaveFileReader(fileName);\n    var waveOut = new NAudio.Wave.WaveOut();\n    waveOut.DeviceNumber = deviceNumber;\n    output = waveOut;\n    output.Init(waveReader);\n    output.Play();}	0
10884164	10852899	WebformsMVP Implement a Ninject IPresenterFactory	IPresenter Create(Type presenterType, Type viewType, IView viewInstance);	0
820971	820832	Replacing images with same names in folders	images/Image123.jpg?version=42	0
28459499	28453715	date filter using elasticsearch, using nest c#	DateTime date;\nDateTime.TryParse(filter.SearchText, out date);\ndate = date.Date.AddDays(1); // date = floor(date) + 1 day\nstring dateString = date.ToString("MM/dd/yyyy");\nquery = filterDesc.And(filterDesc.Range(n =>n.GreaterOrEquals(dateString).OnField(searchFields[filter.Field])));	0
10373587	10373259	Windows 8: how to add user control with C# code	MyUserControl myControl = new MyUserControl();\nmyPanel.Children.Add(myControl);	0
17801161	17801083	how to reduce the code with this enum lists	var invalidComparisons = new string[][] {\n        new[] { ValidationFields.FO.ToString(), ValidationTypes.P.ToString() },\n        new[] { ValidationFields.FW.ToString(), ValidationTypes.P.ToString() },\n        new[] { ValidationFields.UF.ToString(), ValidationTypes.O.ToString() },\n        new[] { ValidationTypes.O.ToString(), ValidationTypes.P.ToString() },\n        new[] { ValidationTypes.W.ToString(), ValidationTypes.P.ToString() },\n        new[] { ValidationTypes.P.ToString(), ValidationTypes.C.ToString() },\n        new[] { ValidationTypes.C.ToString(), ValidationTypes.U.ToString() },\n};\n\nif (invalidComparisons.Any(x => CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), x[0], x[1]))\n{\n    BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";\n    args.IsValid = false;\n}	0
5587665	5587604	C# Screen Capture in Parallel?	public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)	0
2907475	2907290	In Windows Vista and 7, I can't access the %DEFAULTUSERPROFILE% system variable - it shows as not found	public static string GetDefaultUserProfilePath() {\n    string path = System.Environment.GetEnvironmentVariable("DEFAULTUSERPROFILE") ?? string.Empty;\n    if (path.Length == 0) {\n        using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList")) {\n            path = (string)key.GetValue("Default", string.Empty);\n        }\n    }\n    return path;\n}	0
25928485	25916423	Compare n number of lists and return matching objects in c#	List<Card> results = new List<Card>(allMatches.FirstOrDefault ());\n\n        for (int i = 1; i < allMatches.Count (); i++) {\n            List<Card> other = allMatches [i];\n\n            List<Card> toRemove = new List<Card> ();\n            foreach(Card e in results) {\n\n            //This comparison can be interpreted as other.Contains(e)\n                if (other.Any(b => b.ID == e.ID)) {\n                    continue;\n                }\n                toRemove.Add (e);\n            }\n\n            foreach (Card e in toRemove) {\n                results.Remove (e);\n            }\n        }	0
22104538	22104490	Assigning different variables with similar name in a loop	List<TextBox> textBoxes = new List<TextBox>();\ntextBoxes.Add(textBox1);\ntextBoxes.Add(textBox2);\ntextBoxes.Add(textBox3);\n// etc.\n\nfor (int i = 0; i < textBoxes.Count; ++i)\n{\n    textBoxes[i].Text = "Stackoverflow" + (i + 1).ToString();\n}	0
1464612	1464519	retrieve column data in ListView multiple column c#	listView1.SelectedItems[N].SubItems[X].Text;	0
25304883	25304549	Bind checkbox with Images and Dropdownlist in Grid view	Dim cbSelect As CheckBox, imgToInsert As Image, ddlStatus As DropDownList\nFor Each r As GridViewRow In gvDetails.Rows\n    cbSelect = r.Cells(0).FindControl("CheckBox2")\n\n    If cbSelect.Checked Then\n        imgToInsert = r.Cells(1).FindControl("imgPreview")\n        ddlStatus = r.Cells(2).FindControl("dpdListEstatus")\n\n        'Insert statement goes here...\n    End If\nNext r	0
17464734	17464668	Delete rows that contains null value from dataTable	public static void RemoveNullColumnFromDataTable(DataTable dt)\n{\n    for (int i = dt.Rows.Count - 1; i >= 0; i--)\n    {\n        if (dt.Rows[i][1] == DBNull.Value)\n            dt.Rows[i].Delete();\n    }\n    dt.AcceptChanges();\n}	0
10420462	10409499	how to set applicationbar opacity from code behind	(ApplicationBar as ApplicationBar).Opacity = num;	0
24250683	22958965	VS Application Insights for a Web App deployed to multiple environments	appInsights.start("@ServerAnalytics.ApplicationInsightsId");	0
26630614	26629852	Is there a clean way for checking a cancellation request in BackgroundWorker without re-typing the same code over and over again?	void worker_DoWork(object sender, DoWorkEventArgs e)\n{\n    List<Action> delegates = new List<Action>();\n    delegates.add(some_time_consuming_task);\n    delegates.add(another_time_consuming_task);\n\n    BackgroundWorker w = sender as BackgroundWorker;    \n    while(!w.CancellationPending && delegate.Count!=0)\n    {\n        delegates[0]();\n        delegates.remove(0);\n    }\n\n    if(w.CancellationPending)\n        e.Cancel = true;\n}	0
8062240	8061812	Using autofac with moq	var AppContainer = ApplicationContainer.GetApplicationContainer();\n  var studyLoaderMock = new Mock<IStudyLoader>().Object;\n  cb.RegisterInstance(studyLoaderMock).As<IStudyLoader>();\n  cb.Update(AppContainer);	0
12222642	12222100	copy asp control	using System.Text;\nusing System.IO;\nusing System.Web.UI;\n\npublic string RenderControl(Control ctrl)\n{\n    StringBuilder sb = new StringBuilder();\n    StringWriter tw = new StringWriter(sb);\n    HtmlTextWriter hw = new HtmlTextWriter(tw);\n\n    ctrl.RenderControl(hw);\n    return sb.ToString();\n}	0
2155211	2155155	How to get the next text of an XML node, with C#?	document.SelectSingleNode("/skin/color[classname='.depth1']/colorcode").InnerText	0
6801023	6800972	how can i modify a value in list<t>?	PhraseInfo pi = posesBracket[0];\npi.Start = 10;\nposesBracket[0] = pi;	0
3497112	3496527	how to set the log file path of the SSIS package programmatically	Application app = new Application();\nPackage p = app.LoadPackage(@"C:\PathToPackage", null);\n\n// LogFileConnection is an existing connection to a log file.\nConnectionManager c = p.Connections["LogFileConnection"] as ConnectionManager;\nif (c != null)\n    c.ConnectionString = @"C:\SomePathToLogFile"; // Change the file path\n\np.Execute(); //You should now see events logged to the new file path	0
29925046	29923280	How to override get accessor of a dynamic object's property	dynamic person = new GetterExpando();\nperson.Name = "Matt";\nperson.Surname = "Smith";\nperson.FullName = new GetterExpando.Getter(x => x.Name + " " + x.Surname);\n\nConsole.WriteLine(person.FullName);  // Matt Smith\n\n// ...\n\npublic sealed class GetterExpando : DynamicObject\n{\n    private readonly Dictionary<string, object> _data = new Dictionary<string, object>();\n\n    public override bool TrySetMember(SetMemberBinder binder, object value)\n    {\n        _data[binder.Name] = value;\n        return true;\n    }\n\n    public override bool TryGetMember(GetMemberBinder binder, out object result)\n    {\n        object value;\n        if (_data.TryGetValue(binder.Name, out value))\n        {\n            var getter = value as Getter;\n            result = (getter == null) ? value : getter(this);\n            return true;\n        }\n        return base.TryGetMember(binder, out result);\n    }\n\n    public delegate object Getter(dynamic target);\n}	0
16022617	16022566	Issue with converting string to int	num1 = Char.GetNumericValue(date1[0]);\nnum2 = Char.GetNumericValue(date1[1]);\nnum3 = Char.GetNumericValue(date1[2]);\nnum4 = Char.GetNumericValue(date1[3]);	0
23060554	23058902	How to hide audio file inside image	byte[] bytes = System.IO.File.ReadAllBytes("myAudioFile.mp3");	0
9794386	9794282	c# Textbox filling with dataset from MYsql?	textBox5.Text = DS.Tables[0].Rows[0][0].ToString();	0
17075877	17075610	How do I consume C# WCF Service with JSON for development and debugging?	[WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]	0
28771146	28765224	Inserting object into embedded document	var query = Query<PlayList>.EQ(e => e.Id, playListId);\nvar update = Update<PlayList>.Push(e => e.UrlList, url);\n\ncollection.Update(query, update);	0
18099161	18098717	How to determine if an object inherits from an abstract generic class	Type type2 = type; // type is your type, like typeof(ClassA)\n\nwhile (type2 != null)\n{\n    if (type2.IsGenericType && \n        type2.GetGenericTypeDefinition() == typeof(SuperClass<>))\n    {\n        // found\n    }\n\n    type2 = type2.BaseType;\n}	0
2515787	2514712	WPF: Displaying two windows simultaneously (extended desktop) in full screen	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n\n        foreach (var screen in System.Windows.Forms.Screen.AllScreens)\n        {\n            var window = new Window1\n            {\n                WindowStartupLocation = WindowStartupLocation.Manual,\n                WindowState = WindowState.Maximized,\n                WindowStyle = WindowStyle.None,\n                Title = screen.DeviceName,\n                Width = screen.Bounds.Width,\n                Height = screen.Bounds.Height,\n                Left = screen.Bounds.Left,\n                Top = screen.Bounds.Top,\n            };\n            window.Show();\n        }\n    }\n}	0
31558234	31558036	specific dates in DatePicker	inp.datepicker({\n    dateFormat: dateFormat,\n    changeMonth: true,\n    beforeShowDay: function(date){\n        var arr = ["2013-03-14", "2013-03-15", "2013-03-16"] ; // Should be your json array of dates coming from server\n        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);\n        return [ array.indexOf(string) == -1 ]\n    },\n    changeYear: false,\n    showWeek: true,\n    firstDay: 1,\n    yearRange: "c-100:c+15",\n    showOn: inp.hasClass("ui-date-picker-onfocus") ? "focus" : "button"\n})	0
6599561	4425011	How to play local mp3 files with MediaElement	mediaElement1.Source = new Uri("D://ExamplePath//myVideoFile.avi");	0
28241504	28198391	How to manipulate webpage by weBrowser control after JS is executed?	var elements=document.getElementsByClassName('vote-up');\nfor (index = 0; index < elements.length; index++) {elements[index].click();}	0
17357126	17357109	How to get the root directory	string rootPath = Path.GetPathRoot(filename);	0
16373933	16373891	How can I change a WebBrowser URL with a button?	newsfeedbox.Navigate("http://youtube.com");	0
28508516	28508481	How to prevent direct access to the variable in a class?	public class SomeBaseClass {\n    private int _x;\n    public int X { get { return _x; } set { _x = value; } }\n}\n\npublic class DerivedClass : SomeBaseClass {\n    void DoSomething() {\n        // Does not have access to _x\n    }\n}	0
22256291	22256128	how to synchronize read and write	public partial class Form1 : Form\n{\n    private Thread _thread = null;\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        ParameterizedThreadStart pts = new ParameterizedThreadStart(RunPreUp);\n\n        _thread = new Thread(pts);\n\n        _thread.Start("script");\n    }\n\n    private void RunPreUp(object param)\n    {\n        string parameter = param as string;\n\n        // do work.\n\n        string result = "here is a result";\n\n        richTextBox1.Invoke((MethodInvoker)delegate\n        {\n            richTextBox1.Text = result;\n        });\n\n        Thread.CurrentThread.Abort();\n    }\n}	0
14705736	14705672	Search in IQueryable<T>	if (!UserList.Any(x => x.Type == (int)UserType.SuperUser))\n{\n    AesCrypto aesCrypto = new AesCrypto();\n    user newuser = new user();\n    newuser.username = DEFAULT_SUPER_USER_NAME;\n    newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);\n    newuser.type = (int)UserType.SuperUser;\n    newuser.create_date = DateTime.Now;\n    newuser.last_login = newuser.create_date;\n    newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;\n    newuser.login_count = 1;\n\n    DatabaseContext.Users.Add(newuser);\n    if (!DatabaseContext.Save())\n        return false;\n}	0
33665225	33623632	ReportAvOnComRelease was detected	Public Sub closeform()\n        Me.Close()\n    End Sub	0
23696605	23696101	umbraco 7: get property value	item.NameofYourPropertyAlias	0
19477553	19476010	Wait for Geocoordinatewatcher finish before continue with execution	var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);\nwatcher.MovementThreshold = 0.5;	0
2390499	2390084	C# Linq question: How to identify and count items in a set	static IQueryable<IGrouping<TKey, TSource>> GroupWithinDates<TSource, TKey>(\n    this IQueryable<TSource> source,\n    Expression<Func<TSource, TKey>> keySelector,\n    Expression<Func<TSource, DateTime>> dateSelector,\n    DateTime startDate,\n    DateTime endDate\n)\n{\n    return source\n        .Where(item => dateSelector(item) >= startDate\n                       && dateSelector(item) < endDate)\n        .GroupBy(keySelector)\n}\n\n// Usage after setting startDate and endDate\nvar groups = mytable.GroupWithinDates(\n               A => A.name, A => A.when, startDate, endDate)\n// You can then transform to Name and Count\nvar groupCounts = groups.Select(g => new {Name = g.Key, Count = g.Count()};	0
12955171	12816291	On Udp -Level :"Only one usage of each socket address is normally permitted"	IPEndPoint(IPAddress.Any, receivePort);	0
30448966	30448830	How to properly align a 5x10 2-d array with random data in console?	static void Main()\n{\n    const int ROWS = 10;\n    const int COLS = 5;\n    const int MAX = 100;\n    int[,] numbers = new int[10, 5];\n\n    Random rand = new Random();\n\n    for (int i = 0 ; i< ROWS; ++i)\n    {\n        for (int j = 0; j < COLS; ++j)\n        {\n            numbers[i, j] = rand.Next(0, 101);\n            Console.Write(" {0, 5}", numbers[i, j]);\n        }\n        Console.WriteLine("");\n    }\n}	0
33346477	33283721	C# Recursivly populate treeview from paths in registry	try\n        {\n            TreeNode rootNode;\n            NodeInfo nInfo;\n\n            string[] paths = Global.GetPaths();\n            for (int i = 0; i < paths.Length; i++)\n            {\n                string path = paths[i];\n                DirectoryInfo info = new DirectoryInfo(path);\n                if (info.Exists)\n                {\n                    rootNode = new TreeNode(info.Name, 3, 3);\n                    rootNode.Name = info.Name;\n\n                    nInfo = new NodeInfo(NodeInfo.Types.Root, info.FullName);\n                    rootNode.Tag = nInfo;\n\n                    GetDirectories(info, rootNode);\n                    treeView1.Nodes.Add(rootNode);\n                    treeView1.SelectedNode = rootNode;\n                }\n            }\n\n        }\n\n        catch (Exception ex)\n        {\n            //.....\n            Logic.Log.write("ERROR PopulateTreeView -" + ex.Message);\n        }	0
17232460	17145492	how to mute barcode2 scan in C#	Barcode2.Config.Scanner.Set();	0
13553021	13552842	How Access A Server-Side div In Code Behind (Inside Content Page)	HtmlGenericControl myDiv = (HtmlGenericControl)MyDiv;\nmyDiv.Style.Add("Display", "none");	0
16393252	16393161	How to set dropdown list value and item as database table value in edit?	use selectedvalue property\n\nwhile (reader.Read())\n{\n    ddCustomerName.SelectedValue= reader["CustomerId"].ToString();\n    txtPickupLocation.Text = reader["Location"].ToString();\n}	0
16406143	16405841	Pathing around a centerposition, how can I skip the line from center?	new Point(x + tileXDelta / 2, y + tileRadius / 2)	0
26222562	26220358	How to iterate through nested properties of an object	var myType = typeof(Custom1);\n            ReadPropertiesRecursive(myType);\n\n\nprivate static void ReadPropertiesRecursive(Type type)\n        {\n            foreach (PropertyInfo property in type.GetProperties())\n            {\n                if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))\n                {\n                    Console.WriteLine("test");\n                }\n                if (property.PropertyType.IsClass)\n                {\n                    ReadPropertiesRecursive(property.PropertyType);\n                }\n            }\n        }	0
8145622	8140665	How can I retrieve the SQL SELECT statement used in an Crystal Report?	public string getCommandText(ReportDocument rd)\n{\n    if (!rd.IsLoaded)\n        throw new ArgumentException("Please ensure that the reportDocument has been loaded before being passed to getCommandText");\n    PropertyInfo pi = rd.Database.Tables.GetType().GetProperty("RasTables", BindingFlags.NonPublic | BindingFlags.Instance);\n    return ((dynamic)pi.GetValue(rd.Database.Tables, pi.GetIndexParameters()))[0].CommandText;\n}	0
34500158	34500076	Delete a file that was created via background worker in c#?	bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){\n    if(e.Cancelled) {\n        File.Delete(_output);\n        ((MainWindow)Application.Current.MainWindow).DisplayAlert("Split has been cancelled");\n        ProgressBar.Value = 0;\n    }\n    // TODO: handle your other, non-cancel scenarios\n}	0
25627173	25627068	how to get the indices with a specific text from List?	List<Int32> indexes = new List<Int32>();\nbool wasValid = false;  // flag if previous item was valid\nfor (int i = 0; i < myArray.Count; i++)\n    {\n        if (IsValidText(myArray[i]))\n        {\n            if (!wasValid) // previous item was not valid\n                indexes.Add(i);  // note fix to keep as 0-based index \n            wasValid = true;\n        }   \n        else\n        {\n            wasValid = false;  // for next loop\n        }\n    }	0
29099538	29099469	How can I save multiline text from a multiline textbox into database in ASP.NET?	text.Replace("\n","<br/>")	0
20918261	20917251	Linq SelectMany With Null Child	var vs = result.Select(x => new MenuDetailsViewModel\n{\n    MenuId = x.MenuId,\n    DisplayText = x.DisplayText,\n    MenuOrder = x.MenuOrder,\n    HasKids = x.HasKids,\n    MenuStatus = x.MenuStatus,\n    AccessRuleLists = x.AccessRules == null ? null : x.AccessRules.\n        Select(c => new AccessRulesList\n        {\n            Id = c.Id,\n            MenuId = c.Menu.MenuId,\n            RoleId = c.Roles.RoleId,\n            CanCreate = c.CanCreate,\n            CanUpdate = c.CanUpdate,\n            CanDelete = c.CanDelete\n        }).ToList()\n}).SingleOrDefault();	0
24169212	24168723	How to tell if a type inherits from another type not including any generic type parameters?	Console.WriteLine(myClientType.BaseType.GetGenericTypeDefinition() \n  == typeof(ClientBase<>));	0
23491381	23491088	Split String between 2 substrings without removing delimiters	string mailstring = "<Canvas Background='#FF00FFFF' Name='Page_1' Width='1200' Height='900' ><TextBlock Name='PageTitle' /></Canvas><Canvas Background='#FF00FFFF' Name='Page_2' Width='1200' Height='900'<TextBlock Name='PageTitle' /></Canvas>";\n            string splitor = "</Canvas>";\n            string[] substrings = mailstring.Split(new string[] { splitor }, StringSplitOptions.None);\n            string part1 = substrings[0] + splitor;\n            string part2 = substrings[1] + splitor;	0
3374109	3374040	Split large file into smaller files by number of lines in C#?	using (System.IO.StreamReader sr = new System.IO.StreamReader("path"))\n{\n    int fileNumber = 0;\n\n    while (!sr.EndOfStream)\n    {\n        int count = 0;\n\n        using (System.IO.StreamWriter sw = new System.IO.StreamWriter("other path" + ++fileNumber))\n        {\n            sw.AutoFlush = true;\n\n            while (!sr.EndOfStream && ++count < 20000)\n            {\n                sw.WriteLine(sr.ReadLine());\n            }\n        }\n    }\n}	0
9199767	9199268	ORDER on an INSERT TO	DataView d = null;//Load from Excel\n   var rows = (from DataRowView rowView in d select rowView.Row).ToList();\n   foreach (DataRow dataRow in rows.OrderByDescending(r=>(int)r["notes"]))\n   {\n      //Insert code here that you already have\n   }	0
22563762	22563625	Checking if an integer dataset value return dbnull value	if (loanAppDetails[0].datNewClient != DBNull.Value)	0
17373681	17373548	Could not find a part of the path using File.Copy(source,destination,true) in C# console app	Extra6DestPath = @"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"	0
20887927	14256283	Show tooltip only on the datapoint for line graph in MSCHART	public void Form1()\n{\n   //Add a handler for the GetToolTipText event\n   chart1.GetToolTipText += new EventHandler<ToolTipEventArgs>(chart1_GetToolTipText);\n}\n\nprivate void chart1_GetToolTipText(object sender, ToolTipEventArgs e)\n{\n   //Check selected chart element is a data point and set tooltip text\n   if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)\n   {   \n      //Get selected data point\n      DataPoint dataPoint = (DataPoint)e.HitTestResult.Object;\n\n      //Is it my datapoint?\n      if (dataPoint == myDataPoint)\n      {\n         //Yes, set text\n         e.Text = "My data point value " + dataPoint.XValue.ToString() + dataPoint.YValues[0].ToString();\n      }\n      else\n      {\n         //No, void string\n         e.Text = "";\n      }\n   }\n}	0
6194572	6194477	How can I migrate a temp table using LINQ to SQL?	// migrate temp profile(s)...\nvar tempProfiles = from ct in db.contact_temps\n                             where ct.SessionKey == contact.Profile.SessionId\n                             select ct;\n\nforeach (var c in tempProfiles)\n{\n    Contact newC = new Contact();\n    newC.Name = c.Name;\n    // copy other values\n\n    db.contacts.InsertOnSubmit(newC);\n}\n\n// WAIT! do it at once in a single TX => avoid db.SubmitChanges() here.\n\n db.contact_temps.DeleteAllOnSubmit(tempProfiles);\n\n // Both sets of changes in one Tx.\n db.SubmitChanges();	0
12191765	12185583	Building a canvas template in WP7	object myDataObject = DataContext;\nBinding myBinding = new Binding();\nmyBinding.Source = myDataObject;\nmyBinding.Path="."; // not sure if required\nnewBlock.SetBinding(TextBlock.TextProperty, myBinding);	0
11238275	11238111	How to read a specific line of a RSS feed in visual C#	var rss = XDocument.Load("your rss file");\n    var items = (from c in rss.Descendants("item") select new{\n                 Title  = (string)c.Element("description")      \n                }).ToList();\n\n// first description \n\n    string firstitem= items[0].Title.ToString();	0
10488802	10488702	How to make this class deserializable	[XmlRoot("Pools")]\npublic class Pools : List<Pool> {\n   // etc...\n}	0
23261755	23261127	Dropdown comboboxcell on button click	gvTeam2.CurrentCell = gvTeam2[4, 0];\ngvTeam2.BeginEdit(false);\ngvTeam2.EditingControl as DataGridViewComboBoxEditingControl).DroppedDown = true;	0
1737094	1737088	Winforms : avoid freeze application	private void button1_Click(object sender, EventArgs e)\n{\n    var worker = new BackgroundWorker();\n    worker.DoWork += (s, args) =>\n    {\n        // Here you perform the operation and report progress:\n        int percentProgress = ...\n        string currentFilename = ...\n        ((BackgroundWorker)s).ReportProgress(percentProgress, currentFilename);\n        // Remark: Don't modify the GUI here because this runs on a different thread\n    };\n    worker.ProgressChanged += (s, args) =>\n    {\n        var currentFilename = (string)args.UserState;\n        // TODO: show the current filename somewhere on the UI and update progress\n        progressBar1.Value = args.ProgressPercentage;\n    };\n    worker.RunWorkerCompleted += (s, args) =>\n    {\n        // Remark: This runs when the DoWork method completes or throws an exception\n        // If args.Error != null report to user that something went wrong\n        progressBar1.Value = 0;\n    };\n    worker.RunWorkerAsync();\n}	0
13901775	13901752	When edit data should id of data be stored in session	an example	0
23282468	23281159	How to get ID against selected value of Dropdownlist C#	string Id = DropDwonList.SelectedValue;\n\n        using (SqlConnection sql = new SqlConnection("Your connection string"))\n        {\n            SqlCommand cmd = new SqlCommand();\n            string query = @"INSERT INTO TABLE2(Column1)\n                               VALUES(" + Id + ")";\n            cmd.CommandText = query;\n            cmd.CommandType = CommandType.Text;\n            cmd.Connection = sql;\n            sql.Open();\n            cmd.ExecuteNonQuery();\n            sql.Close();\n        }	0
19531066	19531041	c# displaying something in a listbox through a button based on info in a textbox	if (codeTXT.Text == "1432")	0
14654535	14612296	Efficient way to "apply to all" with EF	List<int> InDB = _db.Comments           \n    .Where(r => model.ids.Contains(r.id))\n    .Select(r => r.id)\n    .ToList();\n\nList<int> diff = model.ids.Except(InDB).ToList();\n//Loop through items to ADD\nforeach (int i in diff)\n{\n    Comment comment = new Comment { Text = model.Text, id = i };\n    _db.Comments.Add(comment);\n}\n//Loop through items to edit\nforeach (int i in InDB)\n{\n    Comment comment = new Comment { Text = model.Text, id = i };\n    _db.Entry(comment).State = EntityState.Modified;\n}	0
32422311	32422267	C# - how to filter the DataGridView using ComboBox	DataTable dt = new DataTable();\n\nprivate void cboFilter_SelectedIndexChanged(object sender, EventArgs e)\n{\n    DataView dv = dt.DefaultView;\n    dv.RowFilter = string.Format("TRANSACTYPE  LIKE '%{0}%'", cboFilter.SelectedItem.ToString());\n    dataGridView1.DataSource = dv;\n}	0
15217363	15216803	How to create self expiring files	1 day, 2 hour, or whatever	0
5529464	5529404	How to make attached property react to children collection change?	public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)\n{\n    var panel = sender as Panel;\n    panel.Loaded += ...\n}	0
18567991	18567891	Reading Data from file into 1D array C#	string[] arrText;\nstring lineThreeHundred;\n\narrText = File.ReadAllLines("c:\test.txt");\nint counter = 0;\nList<Country> contries = new List<Country>();\n\nwhile(counter < arrText.Length)\n{\n   Country curr =new Country();\n   curr.country = arrText[counter];\n   curr.capital = arrText[counter + 1];\n   int.TryParse(arrText[counter + 2], out curr.area);\n   int.TryParse(arrText[counter + 3], out curr.population);\n   counter += 4;\n}	0
10997723	10997458	protecting files for download just for user that has credit in his/her acount?	public class CustomImageHandler : IHttpHandler\n{\n        public void ProcessRequest(HttpContext context)\n        {\n            //Get file name from query string and check balance for that file extension... read the file into aStream\n\n            context.Response.Clear();\n            context.Response.ContentType = "image/...";\n            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", GetTheFileName()));\n            context.Response.BinaryWrite(aStream.ToArray());\n        }\n}	0
7310401	7309086	Rotate a BitmapImage	var transformBitmap = (TransformedBitmap)image1.Source;\nRotateTransform rotateTransform = (RotateTransform)(transformBitmap.Transform);\nrotateTransform.Angle += 90;\nimage1.Source = transformBitmap.Clone();	0
20982216	20981816	How can I put a shader over my UI	private void button2_Click(object sender, EventArgs e)\n    {\n        this.Enabled = false;\n    }	0
26088031	26087327	C# Console application, How to calculate Mobile Bill for any duration?	decimal bill = 0;            \n\nDateTime startTime = DateTime.Now;\nDateTime endTime = DateTime.Now.AddHours(2.5);\nDateTime timeNow = startTime;\n\nwhile (timeNow <= endTime)\n{                \n    decimal rate = (timeNow.Hour >= 12 && timeNow.Hour <= 24) ? 2 : 1;                \n    bill = bill + rate;\n    Console.WriteLine("{0:HH:mm}, rate: ${1:#,0.00}, bill: ${2:#,0.00}", timeNow, rate, bill);\n    timeNow = timeNow.AddMinutes(1);\n}\n\nConsole.WriteLine("Bill: {0:HH:mm} to {1:HH:mm}, {2:#,0} mins, ${3:#,0.00}", startTime, endTime, (endTime - startTime).TotalMinutes, bill);\n\nConsole.ReadLine();	0
6381285	6381257	Regular Expression to check a string with special characters	Regex isString = new Regex("^['][a-zA-Z]*[']|[\"][a-zA-Z]*[\"]|[a-zA-Z]*$");	0
16681032	16680984	How to replace > 1 tokens on a string?	string fileContent = File.ReadAllText(path);\nfileContent = Regex.Replace(fileContent, pattern1, replacement1);\n...\nfileContent = Regex.Replace(fileContent, patternN, replacementN);	0
16208131	16208081	Comma separated string to linebreak	public static string getcolours()\n{\n    List<string> colours = new List<string>();\n    DBClass db = new DBClass();\n    DataTable allcolours = new DataTable();\n    allcolours = db.GetTableSP("kt_getcolors");\n    for (int i = 0; i < allcolours.Rows.Count; i++)\n    {\n        string s = allcolours.Rows[i].ItemArray[0].ToString();\n        string missingpath = "images/color/" + s + ".jpg";\n        if (!FileExists(missingpath))\n        {\n            colours.Add(s);\n        }\n    }\n    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"F:\test.txt", true))\n    {\n        foreach(string color in colours)\n        {\n            file.WriteLine(color);\n        }\n    }\n    return string.Join("\n", colours);;\n}	0
9507278	9506740	JQuery Mobile Rendering Hierarchies of Elements	data-role="none"	0
3850254	3846716	Method cannot be translated into a store expression	public IQueryable<Models.Estate> GetEstates()\n{\n    return from e in entity.Estates.AsEnumerable()\n       let AllCommFeat = from f in entity.CommunityFeatures\n                         select new CommunityFeatures {\n                             Name = f.CommunityFeature1,\n                             CommunityFeatureId = f.CommunityFeatureId\n                         },\n       let AllHomeFeat = from f in entity.HomeFeatures\n                         select new HomeFeatures() {\n                             Name = f.HomeFeature1,\n                             HomeFeatureId = f.HomeFeatureId\n                         },\n       select new Models.Estate {\n            EstateId = e.EstateId,\n            AllHomeFeatures = new LazyList<HomeFeatures>(AllHomeFeat),\n            AllCommunityFeatures = new LazyList<CommunityFeatures>(AllCommFeat)\n       };\n}	0
5676899	5676847	Communication between two different applications	using (NamedPipeServerStream pipeServer =\n    new NamedPipeServerStream("testpipe", PipeDirection.Out))\n{\n    Console.WriteLine("NamedPipeServerStream object created.");\n\n    // Wait for a client to connect\n    Console.Write("Waiting for client connection...");\n    pipeServer.WaitForConnection();\n\n    Console.WriteLine("Client connected.");\n    try\n    {\n        // Read user input and send that to the client process.\n        using (StreamWriter sw = new StreamWriter(pipeServer))\n        {\n            sw.AutoFlush = true;\n            Console.Write("Enter text: ");\n            sw.WriteLine(Console.ReadLine());\n        }\n    }\n    // Catch the IOException that is raised if the pipe is broken\n    // or disconnected.\n    catch (IOException e)\n    {\n        Console.WriteLine("ERROR: {0}", e.Message);\n    }\n}	0
7198850	7198724	Sorting a Dictionary by value which is an object with a DateTime	public void List( Dictionary<string,DateTime> dict )\n{\n  int i = 0 ;\n  foreach( KeyValuePair<string,DateTime> entry in dict.OrderBy( x => x.Value ).ThenByDescending( x => x.Key ) )\n  {\n    Console.WriteLine( "{0}. Key={1}, Value={2}" , ++i , entry.Key , entry.Value ) ;\n  }\n  Console.WriteLine( "The dictionary contained a total of {0} entries." , i ) ;\n}	0
20708129	20686960	Concatenation in a linq statement	var results1 = from table1 in data2.AsEnumerable()\n                       select new\n                       {\n                           A_M = table1["ANo"] + "\" + table1["MatterNo"],\n                           ANo = table1["ANo"],\n                           c1 = table1["c1"].Equals(DBNull.Value) ? 0 : Convert.ToInt32(table1["c1"]),\n                           //Case_Status = Convert.ToString(table1["Case_ Status"])\n                       };\n        var results = from table1 in results1\n                      join table2 in data1.AsEnumerable()\n                      on table1.A_M equals (string)table2["File_Code"]\n                      where table1.c1 != 0\n                      && (string)table2["Case_Status"] == "Open"\n                      orderby table1.ANo\n                      select new\n                      {\n                          cCode = table2["acAccountCode"],\n                          ANo = table1.ANo,\n                          c1 = table1.c1\n                      };	0
13493689	13490374	How to perform raw SQLite query through SQLiteAsyncConnection	SQLiteAsyncConnection conn = new SQLiteAsyncConnection(DATABASE_NAME);\nint profileCount = await conn.ExecuteScalarAsync<int>("select count(*) from " + PROFILE_TABLE);	0
13735167	13732211	Dynamically change a button image according to database information	public void checkSuites()\n    {\n        Dictionary<int, Control> btnList = new Dictionary<int, Control>();\n        btnList.Add(1, suite1);\n        btnList.Add(2, suite2);\n        btnList.Add(3, suite3);\n        btnList.Add(4, suite4);\n        btnList.Add(5, suite5);\n        SqlCeCommand checkSuite = new SqlCeCommand("SELECT * FROM RentSessionLog WHERE State='0'", mainConnection);\n\n        SqlCeDataReader readSuite = checkSuite.ExecuteReader();\n        while (readSuite.Read())\n        {\n            int suiteIndex = Convert.ToInt32(readSuite["SuiteNum"]);\n            string suitePath = "suite" + suiteIndex;\n            foreach (Button key in btnList.Values)\n            {\n                if (key.Name == suitePath)\n                {\n                 key.Image = NewSoftware.Properties.Resources.busySuiteImg;\n                }\n            }\n\n            }\n\n\n    }	0
16303105	16302494	How to add update parameter to SQLDataSource in c#	using (SqlConnection connection = new SqlConnection(ConnectionString())\n  using (SqlCommand cmd = new SqlCommand(updateStatement, connection)) {\n    connection.Open();\n    cmd.Parameters.Add(new SqlParameter("@Name", userName));\n    cmd.Parameters.Add(new SqlParameter("@city", city));\n    cmd.Parameters.Add(new SqlParameter("@UserId", userID));\n    cmd.ExecuteNonQuery();\n  }	0
3207639	3207585	how to isolated string that contain TAB?	return thatString.Split("\t");	0
792690	792649	How can I get the filename of a Word document from C#?	((Microsoft.Office.Tools.Word.Document)(this)).FullName	0
12224063	12224044	How to copy included file programatically	File.WriteAllBytes("destination path", Properties.Resources.YourResourceName);	0
28801256	28800403	Trick in C# with lambda and event	Func<EventHandler, Button> newButtonWithClick = h =>\n{\n    Button b = new Button();\n    b.Click += h;\n    return b;\n};\n\nButton button = newButtonWithClick((sender, e) => MessageBox.Show("hello"));	0
23420886	23419747	Array mismatch on Deserialization with protobuf-net	// configure the model; SupportNull is not currently available\n// on the attributes, so need to tweak the model a little\nRuntimeTypeModel.Default.Add(typeof(SerializableFactors), true)[1].SupportNull = true;\n\nif (File.Exists("factors.bin"))\n{\n   using (FileStream file = File.OpenRead("factors.bin"))\n   {\n      _factors = Serializer.Deserialize<SerializableFactors>(file);\n   }\n}\nelse\n{\n   _factors = new SerializableFactors();\n   _factors.CaF = new double?[24];\n   _factors.CaF[8] = 7.5;\n   _factors.CaF[12] = 1;\n   _factors.CaF[18] = 1.5;\n   _factors.CoF = new byte?[24];\n   _factors.CoF[8] = 15;\n   _factors.CoF[12] = 45;\n   _factors.CoF[18] = 25;\n   using (FileStream file = File.Create("factors.bin"))\n   {\n     Serializer.Serialize(file, _factors);\n   }\n}	0
1789263	1789243	Highlight Color for particular cells in DataGridView	foreach (DataGridViewRow row in dataGridView.Rows)\n{\n    if (row.Cells[0].Value.ToString() == "someVal")\n    {\n        row.DefaultCellStyle.BackColor = Color.Tomato;\n    }\n}	0
24957498	24957446	Where do I put a piece of code that I want to run right before a multi-form Windows form app exits? (no matter how the program exits)	static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n\n        //** this code will not be reached until form1 closes.\n        bool blah = true;\n        doWhatEver(blah);\n    }	0
11762881	11762597	Can a SWITCH CASE statement get too big?	if value < 50\n  switch\n    ...\n  end\nelse if value < 100\n  switch\n    ...\n  end\nelse\n  ...\nend	0
29750304	29750091	Passing a parameter to a getter/setter	public class Job\n{\n    private DateTime fromDate;\n\n    public Job(DateTime fromDate)\n    {             \n        Reports = new List<Report>();\n        this.fromDate = fromDate;\n    }\n    ...\n    public decimal AverageReportTurnaround\n    {\n        get\n        {\n            DateTime reportdate = Reports.Where(x => x.DateCompleted > this.fromDate)\n                .Select(x=> x.DateCompleted).FirstOrDefault();\n            return (reportdate - AppointmentDate).Value.Days;\n\n        }\n    }\n}	0
16669301	16668599	how to show the following output in wpf datagrid depending on a condition	var duration_query = this.db.Events\n                       .Where(p => ID.Contains(p.ServerID) &&\n                       p.Type == "Complete" && \n                      // fromDP and toDP are name of DataPicker control\n                       (p.Date >= fromDP.SelectedDate.Value && \n                        p.Date <= toDP.SelectedDate.Value))\n                       .GroupBy(p => (((int)(p.Duration / 10)) + 1)*10)\n                       .Select(g => new\n                       {\n                       Duration = g.Key,\n                       serverID = g.Count()\n                       })\n                       .OrderBy(x => x.Duration).ToList();\n\n  dgProcessingTime.ItemsSource = duration_query.ToList();	0
2287429	2287399	Encode object to JSON	var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();\n            string json = jsonSerializer.Serialize(yourCustomObject);	0
10019088	10019044	Returning multiple objects with a JSON result	return Json ( Enumerable.Range(0, 10).Select(i => new { Name = "N" + i, Price = i });	0
23650421	23650260	How async Socket.EndReceive know the number of bytes it read? And how does async socket finish reading?	private enum State\n{\n   MessageLength\n   MessageData\n}\n\nprivate State _state;\nprivate void OnEndReceive(IAsyncCallback ia)\n{\n    int bytesRead = _socket.EndReceive(ia);\n\n\n    if (_state == MessageLength) \n    {\n        // read and store the message length byte\n    }\n    else if (_state == State.MessageData)\n    {\n        // read message data up to the number of bytes received .\n        // if there's data left to be read for the current message, read it.\n        // if more bytes have been received than there is message data, it means there's a \n        // new message already waiting\n    }\n\n}	0
2613997	2613892	Trying to suppress StyleCop message SA1513:ClosingCurlyBracketMustBeFollowedByBlankLine	[SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules",\n                     "SA1600:ElementsMustBeDocumented",\n                     Justification = "Reviewed. Suppression is OK here.")]	0
31098554	31093660	Linq to SQL Format Date time in One Take	var baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\nproduction_cycles = from p in db.ProductionCycles\n    where p.IsRunning == true\n    select new Rest.ProductionCycle\n    {\n        id = p.ID,\n        name = p.Name,\n        created = p.Created,\n        steps = from s in p.Logs\n            where user_permissions.Contains(s.Permission.ID)\n            orderby s.ID ascending\n            select new Rest.Step\n            {\n                created = s.Created,\n                created_label = DbFunctions.DiffHours(baseDate, s.Created).ToString + ":" + DbFunctions.DiffMinutes(baseDate, s.Created).ToString + ":" +DbFunctions.DiffSeconds(baseDate, s.Created).ToString\n\n                ////// the rest as usual\n\n            },\n    };	0
3996605	3996547	From HWND to control	Control.FromHandle(myIntPtr);	0
6288013	6287962	How to convert un-reference-type Object to actual object	Assembly assembly = Assembly.LoadFrom("lib.dll");\nType attributeType = assembly.GetType("Lib.MarkAttribute");\nType dataType = assembly.GetType("Lib.Data");\nAttribute attribute = Attribute.GetCustomAttribute(dataType, attributeType);\nif( attribute != null )\n{\n    string a = (string)attributeType.GetProperty("A").GetValue(attribute, null);\n    string b = (string)attributeType.GetProperty("B").GetValue(attribute, null);\n    // Do something with A and B\n}	0
15434320	15407313	Parsing text with linq	foreach (string line in lines)\n        {\n            var words = line.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\n            foreach(string w in words)\n                Console.Write("{0,6}", w);\n\n            // filling out\n            for (int i = words.Length; i < 8; i++)\n                Console.Write("{0,6}", "0.");\n\n            Console.WriteLine();\n        }	0
14056507	14052929	Cyrillic letters GET request in REST web service	PropertyInfo[] inf = WebOperationContext.Current.IncomingRequest.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);\n                HttpRequestMessageProperty val = (HttpRequestMessageProperty)inf[0].GetValue(WebOperationContext.Current.IncomingRequest, null);\n                string paramString = HttpUtility.UrlDecode(val.QueryString, Encoding.GetEncoding(1251));\n                Uri address = new Uri("http://server.ru/services/service.svc/reg?" + paramString);\n\n                p1 = HttpUtility.ParseQueryString(address.Query).Get("p1");\n                p2 = HttpUtility.ParseQueryString(address.Query).Get("p2");\n                p3 = HttpUtility.ParseQueryString(address.Query).Get("p3");\n                ...	0
11726019	11725857	How do you check if a string exist in a constant	void Main()\n{\n  // make sure that we only take public static const\n  string phrase = "companyA";\n  var fields = typeof(Supplier).GetFields(BindingFlags.Static | BindingFlags.Public).Where(i => i.IsLiteral);\n  foreach (FieldInfo field in fields)\n  {\n    string val = field.GetRawConstantValue().ToString();\n    string msg = string.Format("is '{0}' equal to '{1}' => {2}", val, phrase, val == phrase);\n    Console.WriteLine(msg);\n  }\n}\n\n// Define other methods and classes here\npublic struct Supplier {\n    public const string\n        NA = "N/A",\n        companyA = "companyA",\n        companyB = "companyB";\n};	0
1780793	1780671	C#: Accessing and Modifying Values in a WebBrowser Control	[Test] \npublic void SearchForWatiNOnGoogle()\n{\n using (IE ie = new IE("http://www.google.com"))\n {\n  ie.TextField(Find.ByName("q")).TypeText("WatiN");\n  ie.Button(Find.ByName("btnG")).Click();\n\n  Assert.IsTrue(ie.ContainsText("WatiN"));\n }\n}	0
24454708	24451786	Create proxy with signalR	Connection = new HubConnection(GetUrl());\n        var hubProxy = ((HubConnection) Connection).CreateHubProxy("YourHubName");	0
23913064	23912108	Declaring array of byte as public member	public interface class IStatusListener\n{\n   void OnNewData(Platform::Array<byte>^* data);\n};	0
2532551	2532531	Creating a database using Connector/NET Programming?	conn.Open();\ns0 = "CREATE DATABASE IF NOT EXISTS `hello`;";\ncmd = new MySqlCommand(s0, conn);\ncmd.ExecuteNonQuery();\nconn.Close();	0
6862788	6862684	Converting from Decimal degrees to Degrees Minutes Seconds tenths.	double decimal_degrees; \n\n// set decimal_degrees value here\n\ndouble minutes = (decimal_degrees - Math.Floor(decimal_degrees)) * 60.0; \ndouble seconds = (minutes - Math.Floor(minutes)) * 60.0;\ndouble tenths = (seconds - Math.Floor(seconds)) * 10.0;\n// get rid of fractional part\nminutes = Math.Floor(minutes);\nseconds = Math.Floor(seconds);\ntenths = Math.Floor(tenths);	0
29818590	29818333	Modify multiple string fields	class SearchCriteria\n{\n    private string _Name;\n    public string Name\n    {\n        get { return _Name; }\n        set { _Name = value == null ? null : value.Trim(); }\n    }\n\n    private string _Email;\n    public string Email\n    {\n        get { return _Email; }\n        set { _Email = value == null ? null : value.Trim(); }\n\n    }\n\n    private string _Company;\n    public string Company\n    {\n        get { return _Company; }\n        set { _Company = value == null ? null : value.Trim(); }\n\n    }\n\n    // ... around 20 fields follow\n}	0
1134696	1134671	How can I safely convert a byte array into a string and back?	string base64 = Convert.ToBase64String(bytes);\nbyte[] bytes = Convert.FromBase64String(base64);	0
887403	887377	How do I get a list of all the printable characters in C#?	List<Char> printableChars = new List<char>();\nfor (int i = char.MinValue; i <= char.MaxValue; i++)\n{\n    char c = Convert.ToChar(i);\n    if (!char.IsControl(c))\n    {\n        printableChars.Add(c);\n    }\n}	0
9305304	9280279	Serial port running on a thread using MVP	void someEvent_Handler(object sender, SomeEventEventArgs e)\n{\n    if (this.Dispatcher.CheckAccess())\n    {\n        // do work on UI thread\n    }\n    else\n    {\n        // or BeginInvoke()\n        this.Dispatcher.Invoke(new Action(someEvent_Handler), \n            sender, e);\n    }\n}	0
23243534	23243444	Android play sound of resource	AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");\nplayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());	0
6117158	6116895	Using LINQ2SQL Efficiently	protected void MyFunction()\n{\n    using(MyDataContext db = new MyDataContext())\n    {\n         // uncomment the following line for read only queries\n         // db.ObjectTrackingEnabled = false;\n         // implementation here\n    }\n}	0
6981868	6981799	ASP:Login Control - Changing authentication method	asp:Login	0
26623376	26623214	How to hide particular menu items from master page based on login type?	var menu = Page.Master.FindControl("Menu1") as Menu;\nif(UserStatus != "Admin")\n{\n Menu1.Items.Remove(Menu1.FindItem("INSPECTION"));\n Menu1.Items.Remove(Menu1.FindItem("WORK"));\n}	0
21047653	21047456	how to open a pop up window to a link in gridview	function SetMouseDown(element) {\n    var r = confirm('Are you sure?');\n    var url = window.location.pathname;\n    var pathArray = url.split('/');\n    var host = pathArray[1];\n    var newHost = '/About.aspx';\n\n    if (r == true) {\n        //window.location = host + newHost;\n\n        window.open(host + newHost,'name','width=200,height=200');\n    }\n    else {\n        alert('it didnt work');\n    }\n    return false;\n}	0
22977254	22770930	WAAD Single Sign-on for existing application	[Authorize]	0
10673166	10672897	How to return another value from method in "third party" lib?	Task<string>[] tableOfWebClientTasks = new Task<string>[taskCount];\nvar taskIdToUrl = new Dictionary<int,string>();\n\nfor (int i = 0; i < taskCount; i++)\n{\n    var url = allUrls[count - i - 1];\n    var task = new WebClient().DownloadStringTask(url);\n    tableOfWebClientTasks[i] = task;\n    taskIdToUrl.Add(task.Id, url);\n}\n\nTaskFactory.ContinueWhenAll(tableOfWebClientTasks, tasks =>\n{\n    Parallel.ForEach(tasks, task =>\n    {\n        // To get the url just do:\n        var url = taskIdToUrl[task.Id];\n    });\n});	0
29163788	29162162	Json DeserializeObject with whitespace in Resource Objects	public class Rootobject\n{\n    public Resultslist[] resultsList { get; set; }\n}\n\npublic class Resultslist\n{\n    public int id { get; set; }\n    [JsonProperty("last event")]\n    public string lastevent { get; set; }\n    [JsonProperty("use id")]\n    public string useid { get; set; }\n    [JsonProperty("user status")]\n    public string userstatus { get; set; }\n\n}	0
13087388	13086995	How can I do a threaded Client socket	string data = "Some_Comand";\n        byte[] b = Encoding.ASCII.GetBytes(data);\n        byte[] buffer = new byte[1024];\n        var client = new TcpClient();\n        var serverEndPoint = new IPEndPoint(IPAddress.Parse("ip"), 8010);\n        client.Connect(serverEndPoint);\n        var clientStream = client.GetStream();\n        clientStream.Write(b, 0, b.Length);\n        Socket s = client.Client;\n        byte[] receiveData = new byte[200];\n        s.Receive(receiveData);\n        Debug.WriteLine(Encoding.ASCII.GetString(receiveData));	0
32430246	32430126	Truncate/Convert Datacolumn Dates. C# Console App	DateTimeFormatInfo myDTFI = new CultureInfo( "en-US", false ).DateTimeFormat;\nDateTime myDT = new DateTime(ID);\ndcUnits.Expression = string.Format\n("SUBSTRING({0}, 1, 1)+''+{1}+''+{2}", "BRANCH", "TYPE", myDT.ToString("y", myDTFI));	0
6055422	6055038	How to clone Control event handlers at run time?	var eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);\nvar eventHandlerList = eventsField.GetValue(button1);\neventsField.SetValue(button2, eventHandlerList);	0
13858323	13858109	How to delete a node from a xml c#?	var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(filename)\n\nxDoc.Descendants("Person")\n    .Select(x => x.Attribute("Manager_Id"))\n    .Where(x => x!=null)\n    .ToList().ForEach(a => a.Remove());\n\nvar newxml = xDoc.ToString(); //xDoc.Save(fileName);	0
4794810	4794739	Check box inside a gridview	GridViewRow gridRow = ((sender as CheckBox).Parent).Parent as GridViewRow;\n        int currentRowIndex = gridRow.RowIndex;	0
10618214	10618120	Leave object in cache unchanged	XDocument cachedDocument = ... get it from the cache ...\nXDocument clone = new XDocument(cachedDocument);\n... modify the clone	0
7416724	7415906	How to add Save file Dialog Box using C#	private void Save_As_Click(object sender, EventArgs e)\n{\n  SaveFileDialog _SD = new SaveFileDialog(); \n  _SD.Filter = "Text File (*.txt)|*.txt|Show All Files (*.*)|*.*";\n  _SD.FileName = "Untitled"; \n  _SD.Title = "Save As";\n  if (__SD.ShowDialog() == DialogResult.OK)\n  {\n   RTBox1.SaveFile(__SD.FileName, RichTextBoxStreamType.UnicodePlainText);\n  }\n}	0
20581736	20581605	Use HtmlAgilityPack to determine if string contains ONLY tags from list of allowed tags	var allowedTags = new List<string> { "html", "head", "body", "div" };\n\nbool containsOnlyAllowedTags =\n         doc.DocumentNode\n            .Descendants()\n            .Where(n => n.NodeType == HtmlNodeType.Element)\n            .All(n => allowedTags.Contains(n.Name));	0
5230016	5229993	How to get the data from list without using iterator in c#	List<string> myList = new List<string>();\nmyList.Add("string 1");\nmyList.Add("String 2");\n\nConsole.WriteLine(myList[0]); // string 1\nConsole.WriteLine(myList[1]); // String 2	0
10854440	10854245	Is a process running on a remote machine?	Console.WriteLine(process["Name"]);	0
1855897	1855885	How do I get \0 off my string from C++ when read in C#	string sFixedUrl = "hello\0\0".Trim('\0');	0
4345714	4345666	Hiding a form and showing another when a button is clicked in a Windows Forms application	private void button1_Click_1(object sender, EventArgs e)  \n{  \n    if (richTextBox1.Text != null)  \n    {  \n        this.Visible=false;\n        Form2 form2 = new Form2();\n        form2.show();\n    }  \n    else MessageBox.Show("Insert Attributes First !");  \n\n}	0
27121745	27120723	Changing ~280 controls from visible=true to visible=false takes about 8-9 seconds (too long)	cPanel.SuspendLayout();\n                foreach (KeyValuePair<Control, bool> i in ItemControlUpdates)\n                {\n                    i.Key.Visible = i.Value;\n                }\n                cPanel.ResumeLayout();	0
33353429	33353249	How do I grab only the latest Invoice Number	SELECT\n  InvoiceNumber + MAX(InvoiceString) As strInvoiceNo    \nFROM\n(\n   SELECT\n       dbo.fnNumbersFromStr(strInvoiceNo) AS [InvoiceNumber],\n       dbo.fnStringFromNum(strInvoiceNo) AS [InvoiceString]\n   FROM @TempTable\n) As tbl\nGROUP BY InvoiceNumber	0
8617108	8591920	How to Assert that an Event Has been Subscribed To with FakeItEasy?	public interface IHaveAnEvent\n{\n    event EventHandler MyEvent;\n}\n\n// In your test...\nvar fake = A.Fake<IHaveAnEvent>();\n\nvar handler = new EventHandler((s, e) => { });\n\nfake.MyEvent += handler;\n\nA.CallTo(fake).Where(x => x.Method.Name.Equals("add_MyEvent")).WhenArgumentsMatch(x => x.Get<EventHandler>(0).Equals(handler)).MustHaveHappened();	0
25361892	25361864	Pass multiple types of data arrays through method c#	public void loopThrough<T>(T[] arr)\n{\n    for (int x = 0; x < arr.Length; x++)\n    {\n        T t = arr[x];\n    }\n}	0
11780391	11775741	ActiveMQ - CreateSession failover timeout after a connection is resumed	private void OnConnectionResumed()\n{\n    Task.Factory.StartNew(() =>\n        {\n            var session = connection.CreateSession();\n\n            ...\n        });\n}	0
24183025	24182893	How to Write a extension method that I can use over string and int both?	public static string ToCommaList<T>(this IEnumerable<T> val)\n{\n    if (!val.Any())\n        return string.Empty;\n\n    return String.Join(",", val);\n}	0
12008009	12007743	Searching for special characters on a DataVew RowFilter	CheckValue("fefe[][]12#");\nCheckValue("abvds");\nCheckValue("#");\nCheckValue(@"[][][][][]\\\\\][]");\nCheckValue("^^^efewfew[[]");\n\npublic static string CheckValue(string value)\n{\n    StringBuilder sBuilder = new StringBuilder(value);\n\n    string pattern = @"([-\]\[<>\?\*\\\""/\|\~\(\)\#/=><+\%&\^\'])";\n\n    Regex expression = new Regex(pattern);\n\n    if (expression.IsMatch(value))\n    {\n        sBuilder.Replace(@"\", @"\\");\n        sBuilder.Replace("]", @"\]");\n        sBuilder.Insert(0, "[");\n        sBuilder.Append("]");\n    }\n    return sBuilder.ToString();\n}	0
8587130	8587109	Chaining methods with &&	return method1() && method2() && method3();	0
11426977	11426641	Connection string of SQL Server 2008 R2 silent install	string connectionstring ="datasource = .; Initial Catalog = |DataDirectory|\DBName.mdb;Integrated Security=SSPI	0
10040489	10039427	How to determine if a customAttribute from a class is equals to another?	public class ResponseAttribute : Attribute { \n  public string PropertyName { get; set }\n}\n\n[ResponseAttribute ("CustomResponse")}\npublic class Question1 {\n   public string CustomResponse;\n}\n\nvia reflection\nforeach(var question in questions) {\n   var responseAttr = (ResponseAttribute) question.GetType().GetCustomAttributes(typeof(ResponseAttribute));\n\nvar questionResponse= question.GetType().GetProperty(responseAttr.PropertyName,question,null);\n}	0
7083351	7083160	WPF DataGrid DataContext extremely slow	ObservableCollection<User> Users { get; set; }\n\nvoid LoadUsers()\n{\n    int _Size = 2;\n    int _Page = 0;\n    using (System.ComponentModel.BackgroundWorker _Worker\n        = new System.ComponentModel.BackgroundWorker())\n    {\n        _Worker.WorkerReportsProgress = true;\n        _Worker.DoWork += (s, arg) =>\n        {\n            List<User> _Data = null;\n            while (_Data == null || _Data.Any())\n            {\n                _Data = GetData(_Size, _Page++);\n                _Worker.ReportProgress(_Page, _Data);\n            }\n        };\n        _Worker.ProgressChanged += (s, e) =>\n        {\n            List<User> _Data = null;\n            _Data = e.UserState as List<User>;\n            _Data.ForEach(x => Users.Add(x));\n        };\n        _Worker.RunWorkerAsync();\n    }\n}\n\nList<User> GetData(int size, int page)\n{\n    // never return null\n    return m_Context.Users.Take(size).Skip(page).ToList();\n}	0
14186191	14186162	update gridview on a button click using update panel in asp.net	GridView1.DataBind();	0
31133529	31133254	How to use switch case in for loop?	var message = string.Format("{0} is selected.", ((MenuItem) e.Source).Header);\n// Do something with message	0
21736104	21736014	Is it possible to use a C Sharp console as an external console for an executable run through the program?	//\n// Setup the process with the ProcessStartInfo class.\n//\nProcessStartInfo start = new ProcessStartInfo();\nstart.FileName = @"C:\7za.exe"; // Specify exe name.\nstart.UseShellExecute = false;\nstart.RedirectStandardOutput = true;\n//\n// Start the process.\n//\nusing (Process process = Process.Start(start))\n{\n    //\n    // Read in all the text from the process with the StreamReader.\n    //\n    using (StreamReader reader = process.StandardOutput)\n    {\n    string result = reader.ReadToEnd();\n    Console.Write(result);\n    }\n}	0
17024618	17024459	Group list by element number	int i = 0;\nreturn items.GroupBy(x => i++ % 10);	0
5233992	5233449	Determine if a reflected property can be assigned a given value	public static bool IsAssignable(PropertyInfo property, object value)\n{\n    if (value == null && property.PropertyType.IsValueType && Nullable.GetUnderlyingType(property.PropertyType) == null)\n        return false;\n    if (value != null && !property.PropertyType.IsAssignableFrom(value.GetType()))\n        return false;\n    return true;\n}	0
1056481	1056317	How many characters to create a byte array for my AES method?	string plain_text = "Cool this works";\nbyte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n                                           0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};\nbyte[] key = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n                                           0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };\nbyte[] encrytped_text = encryptStringToBytes_AES(plain_text, key, iv);\nstring plain_text_again = decryptStringFromBytes_AES(encrypted_text, key, iv);	0
33729821	33729583	How to sort xml data in c# to get specific data according to value of a element	XElement root = XElement.Load("abc.xml"); //Load the xml in memory \n\nroot.Elements("CruiseProduct") //Search the details\n.Where(x => x.Element("Location")!=null && x.Element("Location").Value == "LUX");//Filter the details based on your criteria.	0
26545113	26544946	How to implement java Overriding on Instantiation in C#?	public class CommandQueued\n    {\n        protected virtual void onHandleCommandMessage(Message msg)\n        {\n            //onConferenceEvent(msg);\n        }\n    }\n\n    public class DerivedCommandQueue : CommandQueued\n    {\n        protected override void onHandleCommandMessage(Message msg)\n        {\n            //..\n        }\n    }	0
5122628	5122475	C# - How to get complement of two lists without identifiers	var listA = new List<Int32> {1, 2, 2, 3, 5, 8, 8, 8};\nvar listB = new List<Int32> {1, 3, 5, 8};\nvar listResult = new List<Int32>(listA);\n\nforeach(var itemB in listB)\n{\n    listResult.Remove(itemB);\n}	0
31806960	31804925	Update field in array mongodb c# driver	Builders<Person>.Update.Set(x => x.Pets[-1].Name, "Fluffencutters")	0
15595515	15595476	Refactor the foreach loop with continue in it?	if (!something) \n{\n  DoFirstThing();\n  if (!otherthing)\n  {\n     DoSechondThing();\n  }\n} \n//continue implicitly happens here anyway.	0
304376	304361	Visual Studio Extensibility, How do you enumerate the projects in a solution?	static public IEnumerable<IVsProject> LoadedProjects\n    {\n        get\n        {\n            var solution = _serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;\n            if (solution == null)\n            {\n                Debug.Fail("Failed to get SVsSolution service.");\n                yield break;\n            }\n\n            IEnumHierarchies enumerator = null;\n            Guid guid = Guid.Empty;\n            solution.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, ref guid, out enumerator);\n            IVsHierarchy[] hierarchy = new IVsHierarchy[1] { null };\n            uint fetched = 0;\n            for (enumerator.Reset(); enumerator.Next(1, hierarchy, out fetched) == VSConstants.S_OK && fetched == 1; /*nothing*/)\n            {\n                yield return (IVsProject)hierarchy[0];\n            }\n        }\n    }	0
5953732	5948693	Linq issue select Sum of one column minus another from different table	var query = from stk in V_InStock\n            group stk by stk.PartNo into stkg\n            where stkg.Key == '100-25897'\n            select new\n            {\n              ModulePartNo = stkg.Key,\n              Available = stkg.Sum(s => s.Delivered) - stkg.Sum(s => s.Allocated)\n            }	0
8798840	8798806	How to split using multiple characters?	string[] delim = new string[] {"$%$"};\n\nstring[] allSettings = lastUsed.Text.Split(delim, StringSplitOptions.None);	0
26472852	26472733	WPF - Display Concatenated String in the ComboBox Items	var customersList = (from c in context.Customers\n                                where c.IsDeleted == false\n                                select new\n                                {\n                                    Name = c.FirstName + " " + c.LastName,\n                                    c.CustomerId\n                                }).ToList();\n\n     cmbCustomer.ItemsSource = customersList;\n     cmbCustomer.DisplayMemberPath = "Name";\n     cmbCustomer.SelectedValuePath = "CustomerId";	0
3086350	3086315	Scaling a Control's Font in C# .Net	myControl.Font = new Font(myControl.Font, \n    myControl.Font.Style | FontStyle.Bold);	0
11366509	11366409	Locating XML node by child node value inside of it, and changing another value	// Given:\n//   var xdoc = XDocument.Load(...);\n//   string applianceName = "Toaster";\n\n// Find the appliance node who has a sub-element <Name> matching the appliance\nvar app = xdoc.Root\n              .Descendants("Appliance")\n              .SingleOrDefault(e => (string)e.Element("Name") == applianceName);\n\n// If we've found one and it matches, make a change\nif (app != null)\n{\n    if (((string)app.Element("Model")).StartsWith("B8d-k30"))\n    {\n        app.Element("Model").Value = "B8d-k30 Mark II";\n    }\n}\n\nxdoc.Save(@"output.xml"); // save changes back to the document	0
24976974	24976927	Parse Abnormal Date Run to List<DateTime>	var input = "Jul 23, 30 , Aug 06, 13, 20, 27";\nvar dates = \n    (from Match m in Regex.Matches(input, @"(\w+)(?:[\s,]+(\d+))+")\n     from Capture c in m.Groups[2].Captures\n     let str = m.Groups[1].Value + " " + c.Value\n     select DateTime.ParseExact(str, "MMM dd", null))\n    .ToList();	0
3746910	3746331	How can I convert an int to byte array without the 0x00 bytes?	static byte[] VlqEncode(int value)\n    {\n        uint uvalue = (uint)value;\n        if (uvalue < 128) return new byte[] { (byte)uvalue }; // simplest case\n        // calculate length of buffer required\n        int len = 0;            \n        do {\n            len++;\n            uvalue >>= 7;\n        } while (uvalue != 0);\n        // encode (this is untested, following the VQL/Midi/protobuf confusion)\n        uvalue = (uint)value;\n        byte[] buffer = new byte[len];\n        for (int offset = len - 1; offset >= 0; offset--)\n        {\n            buffer[offset] = (byte)(128 | (uvalue & 127)); // only the last 7 bits\n            uvalue >>= 7;\n        }\n        buffer[len - 1] &= 127;\n        return buffer;\n    }	0
28104285	28104115	Excel Persistent Window	frm.ShowDialog();	0
17513482	17512430	What to do with a worker thread in the OnStop method in a basic Windows service?	protected override void OnStop()\n{\n   // flag to tell the worker process to stop\n   serviceStopped = true;\n\n   // give it a little time to finish any pending work\n   workerThread.Join(new TimeSpan(0,2,0));\n}	0
29985488	29922761	Persistent AuthCookie is set but being redirected to login	//this line is NOT ENOUGH for "remember me" to work!!!\nFormsAuthentication.SetAuthCookie(userName, true); //DOESN'T WORK!\n\n//###########\n\n//you have to save the "remember me" info inside the auth-ticket as well\n//like this:\n\nDateTime expires = DateTime.Now.AddDays(20); //remember for 20 days\n\n//create the auth ticket\nFormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,\n    userName,\n    DateTime.Now,\n    expires, // value of time out property\n    true, // Value of IsPersistent property!!!\n    String.Empty,\n    FormsAuthentication.FormsCookiePath);\n\n//now encrypt the auth-ticket\nstring encryptedTicket = FormsAuthentication.Encrypt(ticket);\n\n//now save the ticket to a cookie\nHttpCookie authCookie = new HttpCookie(\n            FormsAuthentication.FormsCookieName,\n            encryptedTicket);\nauthCookie.Expires = expires;\n\n//feed the cookie to the browser\nHttpContext.Current.Response.Cookies.Add(authCookie);	0
1606748	1606640	User control page_load event invoked before the Button click event of the aspx page	//MyPage.aspx\nvoid Button_OnClick(object sender, EventArgs e)\n{\nMyUserControl.DataBind(MyTextBox.Text);\n}\n\n//MyUserControl.ascx\npublic void DataBind(string value)\n{\nUpdateView(value);\n}	0
16550949	16550511	How to resize PDF Document to fit a Bitmap	oPage.Width = ...\noPage.Height = ...	0
29356748	29352110	Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''	{\n  "player_name": "Test",\n  "player_location": "EUW",\n  "player_wins":10,\n  "player_draws":10,\n  "player_losses":15,\n  "player_points":20\n}	0
2684498	2684261	How to convert a number to a range of prices	int getPrice(int n)\n{\n    if (n >= 1 && n <= 10) return 50 * n;\n    if (n >= 11 && n <= 20) return 40 * n;\n    if (n >= 21 && n <= 30) return 30 * n;\n    if (n >= 31 && n <= 50) return 20 * n;\n    throw new Exception("Impossible");\n}\n\nint minimizePrice(int n)\n{\n    int[] minimumPrice = new int[n + 1];\n    for (int i = 1; i <= n; ++i)\n    {\n        minimumPrice[i] = int.MaxValue;\n        for (int j = Math.Max(0, i - 50); j < i; ++j)\n        {\n            minimumPrice[i] = Math.Min(minimumPrice[i],\n                minimumPrice[j] + getPrice(i - j));\n        }\n    }\n    return minimumPrice[n];\n}	0
2037061	2035154	In Visual Studio how can I load a .png image from the project Resources folder?	private void menuItemPosition1_Click(object sender, EventArgs e)\n    {\n        Graphics graphicsCanvas = this.pictureBoxBoard.CreateGraphics();\n        graphicsCanvas.DrawImage(global::StrikeOutMobile.Properties.Resources.counter_square_blue, 60, 60);\n\n    }\n\n    private void pictureBoxBoard_Paint(object sender, PaintEventArgs e)\n    {\n\n    }	0
8788916	8788835	How to get the value from dropdown in asp.net	ddBanner.selectedItem.Text	0
21608390	21608308	Calculate the sum of all odd, random numbers in a range	int sum = 0;\nfor (int X = 1; X <= 20; X++)\n{\n    int y = rnd.Next(1, 10);\n    if (y % 2 == 1)\n    {\n        sum += y; // sum = sum + y;\n    }\n\n    Console.WriteLine("{0}", y);\n}\n\nConsole.WriteLine("sum: {0}", sum);	0
1358145	1358111	How can I set the exact height of a listbox in Windows Forms (C#)?	listbox1.IntegralHeight=false;\nlistbox1.Height=some_int_number;	0
2514514	2514463	How to format this string in c#	public String formatAllowed(String allowedFormats)\n{\n    String[] formats = allowedFormats.Split('|');\n\n    if (formats.Length == 1)\n        return formats[0];\n\n    StringBuilder sb = new StringBuilder(formats[0]);\n\n    for (int i = 1; i < formats.Length - 1; i++)\n    {   \n        sb.AppendFormat(",\"{0}\"", formats[i]);\n    }\n\n    sb.AppendFormat(" and \"{0}\"", formats[formats.Length - 1]);\n\n    return sb.ToString();\n}	0
16936039	16935700	How to add an HyperLink field by code but with an image instead of a text?	bCSLink .Text = @"<img src='"+ResolveUrl("Path of Image of Delete Icon")+"' /> ";	0
7701317	7701151	Date comparison - How to check if 20 minutes have passed?	start.AddMinutes(20) > DateTime.UtcNow	0
3269689	3269679	Abstract class' constructor asks for a return type	protected BaseSqlRepository(EvalgridEntities db)\n{\n    this.DataContext = db;\n}	0
20806534	20806383	Search value from more xml attributes	var strings = searchString.Split(' ');	0
13983979	13983781	How to setup so I can set a breakpoint in ASP.NET MVC 4 source?	SkipStrongNames -e	0
30311708	30310742	Flickering Tab Control with MouseMove Determining What To Draw	private void tabControl_MouseMove(object sender, MouseEventArgs e) {\n  TabControl tc = sender as TabControl;\n  for (int i = 0; i < tc.TabPages.Count; i++) {\n    Rectangle r = tc.GetTabRect(i);\n    Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);\n    if (closeButton.Contains(e.Location)) {\n      if (mousedOver != i) {\n        mousedOver = i;\n        tc.Invalidate(r);\n      }\n    } else if (mousedOver == i) {\n      int oldMouse = mousedOver;\n      mousedOver = -1;\n      tc.Invalidate(tc.GetTabRect(oldMouse));\n    }\n  }\n}	0
11561044	11560921	LINQ query to match multiple words	var suggestions = (from a in query\n                   where searchstrings.All(word => a.ToLower().Contains(word.ToLower()))\n                   select a);	0
7701070	7699972	How to decode a JSON string using C#?	var data = new Dictionary<string, string>();\ndata.Add("foo", "baa"); \n\nJavaScriptSerializer ser = new JavaScriptSerializer();\nvar JSONString = ser.Serialize(data); //JSON encoded\n\nvar JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded\nConsole.Write(JSONObj["foo"]); //prints: baa	0
525372	525364	How to download a file from a website in C#	using System.Net;\n//...\nWebClient Client = new WebClient ();\nClient.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");	0
25922651	25921074	Random 2-D array with LINQ c#	var r = new Random();\n   var result = Enumerable.Range(0, 10).Select(x => \n                   Enumerable.Range(0, 10).Select(y => r.Next()).ToArray())\n               .ToArray();	0
24011572	24011134	How to overwrite the implementation of a property created automatically in a partial class (T4 EF)?	//in generated partial\npublic DateTime DateCreatedDB { get; set; }\n\n//in second file that contains your partial of that class \npublic DateTime DateCreated\n{\n     get { // return converted DateCreatedDB }\n     set { // set DateCreatedDB to unconveted value }\n}	0
19246636	19246581	Find all filenames that contain whitespace	List<string> filenames = ...\nList<string> filenamesWithSpaces = filenames.Where(f => f.Contains(" ")).ToList();	0
29624784	29624730	Regex Arabic Vocalization Matching	var inp1 = "?????????? ???????? ???? ???????:?????????: ????? ?????? ??????????? ?????????????? ???? ???????? ?????????? ??????????? ??????????.";\nvar t2 = Regex.Matches(inp1, "[\u064B-\u0652]", RegexOptions.RightToLeft);	0
9296974	9296906	Passing values from a class to a method of another class	protected void Btnsearch_Click(object sender, EventArgs e)\n{\n    Session["moviename"] = TextBox3.Text;\n    Session["language"] = DropDownList1.Text;\n    Response.Redirect("SearchResults.aspx");        \n}	0
27558228	27558099	Linq syntax for a nested join query	var usedIngredients =\n    (from recipe in this.Recipes\n    from ingredient in recipe.ingredients\n    select ingredient).Distinct().ToList();	0
1073625	1073594	c# datagridview order rows?	this.dataGridView1.Sort(dataGridView1.Columns["DateTime"], ListSortDirection.Ascending);	0
13985536	13977749	DevExpress.XtraEditors.DateEdit set datetime value	// 31, 2012, December, 23:59:59\ndateEdit1.EditValue = new System.DateTime(2012, 12, 31, 23, 59, 59);\ndateEdit1.Properties.Mask.EditMask = "dd, yyyy, MMMM, HH:mm:ss";\ndateEdit1.Properties.Mask.UseMaskAsDisplayFormat = true;	0
16442718	10690771	Include a filtered set of records	var results = (from c in _context.properties\n               where c.Characteristics.Any(c=>c.cat_cd == "DD") select c);	0
21881449	21881258	How to insert Xml element at a specific location using LINQ?	doc.XPathSelectElement("A/B/C[last()]").AddAfterSelf(new XElement("D", new XAttribute("name","New Tag"),new XElement("E")));	0
22653052	22652665	replacement for static variable	public static List<UserMenu> UserMenus\n    {\n        set\n        {\n            Session["UserMenus"] = value;\n        }\n        get\n        {\n            return Session["UserMenus"] == null ? new List<UserMenu>() : (List<UserMenu>) Session["UserMenus"];\n        }\n    }	0
1472932	1238498	In C# Get All the .nsf files(Notes Database) from \data\notes directory and populate it in a Listbox	NotesSession s = new Domino.NotesSessionClass();\ns.Initialize("MyPassword");\nNotesDbDirectory d = s.GetDbDirectory ("MyServer");\nNotesDatabase db = d.GetFirstDatabase();\n...\n\n// loop over all DB's\nString sPath = db.filePath;\n...\ndb = d.getNextDatabase (db);\n...	0
17692824	17690750	Conversion from ReadOnlyObservableCollection to List<MyClass>	public object Convert(object values, Type targetType, object param, CultureInfo culture) {\n    var source = (ReadOnlyObservableCollection<object>) values;\n    List<MyClass> list = source.OfType<MyClass>().ToList();\n    ...\n}	0
15938336	15938171	Regex replace a pattern with another pattern	string s = "fsdfs [b]abc[/b] dddfs [b]abc[/b] fdsfdsfs [b]abcfsdfs";\nstring result = Regex.Replace(s, @"\[b\](.*?)\[/b\]", @"<strong>$1</strong>");	0
4710714	4710696	C# run application	System.Diagnostics.Process process = new System.Diagnostics.Process();\n//process.StartInfo.FileName = @"C:\WINDOWS\system32\iisreset.exe";\nprocess.StartInfo.FileName = "cmd";\nprocess.StartInfo.Arguments = "/C iisreset /STOP";\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.RedirectStandardError = true;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.Start();\nprocess.WaitForExit();	0
3780113	3780005	Function to generate alpha numeric sequence number based on input number	int value = 12345;\n\nstring alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";\n\nvar stack = new Stack<char>();\nwhile (value > 0)\n{\n     stack.Push(alphabet[value % alphabet.Length]);\n     value /= alphabet.Length;\n}\nstring output = new string(stack.ToArray()).PadLeft(6, '0');	0
4868747	4866987	How to recursively delete a folder with the files within using FtpClient?	WebRequestMethods.Ftp.UploadFile	0
10151748	10145247	How Can I Check That A File Is A Valid XPS File With C#?	using System;\nusing System.IO;\nusing System.Windows.Xps.Packaging;\n\nclass Tester\n{\n    public static bool IsXps(string filename)\n    {\n        try\n        {\n            XpsDocument x = new XpsDocument(filename, FileAccess.Read);\n\n            IXpsFixedDocumentSequenceReader fdsr = x.FixedDocumentSequenceReader;\n\n            // Needed to actually try to find the FixedDocumentSequence\n            Uri uri = fdsr.Uri;\n\n            return true;\n        }\n        catch (Exception)\n        {\n        }\n\n        return false;\n    }\n}	0
24577101	24577009	how to create a timer that displays an image for a second c#	DispatcherTimer dispatcherTimer = new DispatcherTimer();\ndispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);\ndispatcherTimer.Interval = new TimeSpan(0, 0, 3);   //fire after 3 seconds\n\n...\n\nprivate void ShowMyImage()\n{\n    // logic to show your image\n    dispatcherTimer.Start();\n}\n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n    // logic to hide your image\n    dispatcherTimer.Stop();\n}	0
593223	593205	action delegate with zero parameters	System.Core	0
15633208	15633167	Image to InsertImage	byte[] srcStream = (byte[])src;\n\nStream stream = new MemoryStream(srcStream);\n\nImage img = Image.FromStream(stream);	0
4427599	4427523	how to connect to access 2007 with c#	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Jet OLEDB:Database Password=MyDbPassword;	0
10624420	10622200	How to programmatically group (shift select) sheets in Excel	String[] sheetsToBeSelected = {"Sheet3","Sheet1","Sheet2"}; //Note, Sheet3 is the first item in this array\nexcel.Workbook workbook = ExcelApp.ActiveWorkbook; //get your Excel application however you want\nexcel.Sheets worksheets = workbook.Worksheets; //get all the sheets in this workbook\n\n//This gets a collection of the sheets specified and ordered by the array of names passed in. \n//Just call select on this collection, and the first sheet in the collection becomes the active sheet!\n((excel.Sheets)worksheets.get_Item(sheetsToBeSelected)).Select();	0
2207542	2105584	From a UITypeEditor, retreive an attribute applied to the parent of a property in .net	DirectCast(context, GridItem).Parent.PropertyDescriptor.Attributes.	0
30134672	30134349	Adding force to one object adds force to all objects with script attached	} else if (Input.GetMouseButton (0) == true) {\n    ray = Camera.main.ScreenPointToRay (Input.mousePosition);\n\n    if (Physics.Raycast (ray, out hit)) {\n        print (hit.collider.gameObject.name);\n\n        // If this is the clicked object\n        if(hit.collider.gameObject == gameObject){\n            Vector3 mousePosition = Input.mousePosition;\n            Rigidbody rigidbody = GetComponent<Rigidbody> ();\n\n            if (lastMousePosition.y > mousePosition.y){\n                rigidbody.AddForce (0, -Input.mousePosition.y, 0);\n            }else if (lastMousePosition.y == mousePosition.y){\n                rigidbody.AddForce (0, 0, 0);\n            }else{\n                rigidbody.AddForce (0, Input.mousePosition.y, 0);\n            }\n        }\n        lastMousePosition = mousePosition;\n    }\n} else if ...	0
21990451	21990049	How to log SOAP envelope from C# web service call?	ws.Proxy = new System.Net.WebProxy("localhost", 8888);	0
31281248	30926736	Parallel.ForEach loop is performing like a serial loop	// collect all of the IDs\nvar itemIDs = Store.Query(query).Cast<WorkItem>().Select(wi = wi.Id).ToArray();\n\nIWorkItemData[] workitems = new IWorkItemData[itemIDs.Length];\n\n// then go through the list, get the complete workitem, create the wrapper,\n// and finally add it to the collection\nSystem.Threading.Tasks.Parallel.For(0, itemIDs.Length, i =>\n{\n    var workItem = Store.GetWorkItem(itemIDs[i]);\n    var item = new TFSWorkItemData(workItem);\n    workitems[i] = item;\n});	0
20629948	20606473	Cannot use cvDilate with some structure element	//Create a grayscale image\n       Image<Gray, Byte> img = new Image<Gray, byte>(400, 400);\n       // Fill image with random values\n       img.SetRandUniform(new MCvScalar(), new MCvScalar(255));\n       // Create and initialize histogram\n       ImageViewer.Show(img);\n       //Create structuring element\n       int[,] tempStructure = { { 1, 1, 1 } };\n       StructuringElementEx element = new StructuringElementEx(tempStructure, 1, 0);\n       //Apply dilation using element\n       CvInvoke.cvDilate(img, img, element, 2);\n       ImageViewer.Show(img);	0
14466634	14466495	Need a linq to objects query for a nested collection	var itineraryItems = _Result.resourceSets\n                            .SelectMany(rs => rs.resources)\n                            .SelectMany(res => res.routeLegs)\n                            .SelectMany(rl => rl.itineraryItems);\n\nforeach(var item in itineraryItems)\n    sb.Append(ii.instruction.ToString());	0
11972301	11965891	WebBrowser opens link in IE instead of Default Browser?	browser.Navigating +=	0
3851832	3851817	How to you kill a windows form program other than using x	Application.Exit()	0
14483208	14483141	Entity Framework Query filters implementation for best perfomance	lista_cheques = db.Cheque.Include("Operacion").Include("Cliente").Where(x => x.fecha_deposito == fecha).ToList();\nlista_cheques = lista_cheques.Where(x => x.banco.id_banco = banco).ToList();\nlista_cheques = lista_cheques.Where(x => x.Operacion.Cliente.id_cliente = id_cliente).ToList();	0
16753186	16750213	DateTime Relative conversion issue	using System;\nusing NodaTime;\n\nclass Test\n{\n    static void Main()\n    {\n        LocalDate start = new LocalDate(2013, 3, 3);\n        LocalDate end = new LocalDate(2013, 5, 25);\n\n        // Defaults to years, months and days - but you can change\n        // that by specifying a PeriodUnits value.\n        Period period = Period.Between(start, end);\n        Console.WriteLine("{0} years, {1} months, {2} days",\n                          period.Years, period.Months, period.Days);\n    }\n}	0
9264450	9264262	Replacing bad characters of a String with bad characters	StringBuilder sb = new StringBuilder();\nforeach (char c in str.ToCharArray()) {\n    if (c == '[' || c == ']') {\n        sb.Append('[' + c + ']');\n    }\n    else {\n        sb.Append(c);\n    }\n}\nstring result = sb.ToString();	0
1328976	1328944	Limit Character count in c# String	public static string trimIt(string s)\n{\n   if(s == null)\n       return string.Empty;\n\n   int count = Math.Min(s.Length, 250);\n   return s.Substring(0, count);\n}	0
12986901	12980379	Setting a fixed GridView width on the first column in WPF	DataGrid.Columns[0].Width = 150;	0
16443335	16439191	Missing action in content-type of WCF SOAP call HTTP header	var serviceBinding = new WSHttpBinding("vz801802Soap12");	0
5023543	5023081	Find all subsets of a list	string set = "abcde";\n\n        // Init list\n        List<string> subsets = new List<string>();\n\n        // Loop over individual elements\n        for (int i = 1; i < set.Length; i++)\n        {\n            subsets.Add(set[i - 1].ToString());\n\n            List<string> newSubsets = new List<string>();\n\n            // Loop over existing subsets\n            for (int j = 0; j < subsets.Count; j++)\n            {\n                string newSubset = subsets[j] + set[i];\n                newSubsets.Add(newSubset);\n            }\n\n            subsets.AddRange(newSubsets);\n        }\n\n        // Add in the last element\n        subsets.Add(set[set.Length - 1].ToString());\n        subsets.Sort();\n\n        Console.WriteLine(string.Join(Environment.NewLine, subsets));	0
18270901	18268870	LINQ to XML query returning wrong data	var xDoc = XDocument.Load(@"C:\TEST\TEST.XML");\n\nvar depts = from e in xDoc.Descendants("Department")\n            where e.Element("id").Value.Equals("001")\n            select e;\n\nvar sections = from e in depts.Descendants("Section")\n            where e.Element("SectionId").Value.Equals("001001")\n            select e;\n\nvar rooms = (from e in sections.Descendants("Room")\n            select new //Room \n            {\n                ID = (string)e.Element("RoomID"),\n                Owner = (string)e.Element("Owner")\n            }).ToList();	0
1302912	1293599	Mapping CLR Parameter Data	public sealed class SqlServerTypeDescription\n{\n    // for sql text construction\n    public readonly string SqlServerName;\n    // for code construction\n    public readonly SqlDbType SqlDbType;\n    // for code construction\n    public readonly Type ClrType;\n\n    // constructor etc.\n}	0
11789369	11788981	C# How do I use Directory.GetFiles() to get files that have the same order as in Windows explorer?	HKCU\Software\Microsoft\Windows\Shell\BagMRU\nHKCU\Software\Microsoft\Windows\Shell\Bags	0
5712655	5712509	How can I dynamically add colums and rows to an empty dataset?	DataRow dr;        \n\nfor (int i = 0; i < chkcnt; i++)\n        {\n            dr = local_ds2.Tables["ACHFile"].NewRow();\n            dr["EmpID"] = EmpID[i];\n            dr["Name"] = Empname[i];\n            dr["BankRoutingNumber"] = BnkRoutingNumber[i];\n            dr["BankAccount"] = BnkAccount[i];\n            dr["BankAccountTypeID"] = AchDB.strBankTypeID[i];\n            dr["Amount"] = AchDB.Amount1[i];\n            if (AchDB.strBankTypeID[i].ToString() == "D")\n                strBankAccntType = "BankAccountTypeID='" + AchDB.strBankTypeID[i].ToString() + "'";\n            local_ds2.Tables["ACHFile"].Rows.Add(dr);\n        }	0
8839308	8839040	custom format for decimal c#	String.Format("{0:0000000000}", (value * 100));	0
2518312	2518269	Switch statement - variable "case"?	string s = ScoreOption.ToUpper().Trim();\nswitch(s)\n{\n    case "A":\n\n        ....\n\n        break;\n    case "B":\n\n        ....\n\n        break;\n    default:\n        if (s.StartsWith("T_"))\n        {\n        ....\n        }                       \n        break;\n\n}	0
5332037	5331842	How likely is it to get a HashCode collision with this hashcode function?	import random\n\ndef hash(key):\n    hashKey = 0\n    hashKey += 2047 * key[0]\n    hashKey += 8191 * key[1]\n    hashKey += 32767 * key[2]\n    hashKey += 131071 * key[3]\n    return hashKey\n\nseen = set()\ncollisions = 0\nfor i in range(0,10000000):\n    x = hash([random.randint(0,1000000), random.randint(0,10000), random.randint(0,1000), random.randint(0,1000)])\n    if x in seen:\n        collisions += 1\n    else:\n        seen.add(x)\n\nprint collisions	0
20265532	20225015	WinStore/WinPhone - how can I get runtime Assembly type for assembly I cannot reference at design time	var assemblyName = new AssemblyName() {Name = "YouAssemblyNameWithoutExtension"};\nvar assembly = Assembly.Load(assemblyName);	0
22551774	22551575	How to write txt file in windows app store?	string text = "Hello, world";\n\nStorageFolder folder = ApplicationData.Current.LocalFolder;\nStorageFile file = await folder.CreateFileAsync("data.txt");\n\nif (file != null)\n{\n    await FileIO.WriteTextAsync(file, text);\n}	0
23662086	23661754	Converting image into CvMat in OpenCV for training neural network	trainMAt = Cv.CreateMat(10, inp_layer_size, MatrixType.F32C1);\nresponses = Cv.CreateMat(10, 1, MatrixType.F32C1); // 10 labels for 10 samples	0
10930467	10929215	Check if an array is a sub array with recursion 	public static bool FindSequence(char[] findIn, char[] toFind)\n    {\n        return FindSequence(findIn, toFind, 0, 0);\n    }\n\n    private static bool FindSequence(char[] findIn, char[] toFind, int posInFindIn, int posInToFind)\n    {\n        if (findIn.Length - posInFindIn < toFind.Length - posInToFind)\n            return false;\n        if (findIn[posInFindIn] == toFind[posInToFind])\n        {\n            if (posInToFind == toFind.Length - 1)\n                return true;\n            else\n                if (FindSequence(findIn, toFind, posInFindIn + 1, posInToFind + 1))\n                    return true;\n        }\n        return FindSequence(findIn, toFind, posInFindIn + 1, 0);\n    }	0
16634125	16634059	get a word after specific word/character from .txt file	var dict = File.ReadLines(filename)\n                    .Select(line => line.Split('='))\n                    .Where(parts => parts.Length>1)\n                    .ToDictionary(x=>x[0].Trim(), x=>x[1].Trim());\n\nConsole.WriteLine(dict["andrea"]);	0
33638125	33637315	select 2 columns from table where columns from comboboxes	using (SqlDataReader read1 = com.ExecuteReader())\n                {\n                    while (read1.Read())\n                    {\n                        ListViewItem parent = listView1.Items.Add(read1[0].ToString());\n                        parent.SubItems.Add(read1[1].ToString());\n                    }\n                }	0
1723661	1723625	Setting the Page-Title in .Net using C# from a Class	var page = (Page)HttpContext.Current.Handler;\npage.Title = "someTitle";	0
11565273	11564109	How to create a control properly from other thread (.net compact framework), with no reference to other control?	class Foo\n{\n    private Control m_invoker;\n\n    public Foo()\n        : this(null)\n    {\n    }\n\n    public Foo(Control invoker)\n    {\n        if (invoker == null)\n        {\n            // assume we are created on the UI thread, \n            // if not bad things will ensue\n            m_invoker = new Control();\n        }\n        else\n        {\n            m_invoker = invoker;\n        }\n    }\n\n    public void Bar()\n    {\n        m_invoker.Invoke(new Action(delegate\n        {\n            // do my UI-context stuff here\n        }));\n    }\n}	0
29104924	28987632	How to check in ReportViewer if a report exists to prevent rsItemNotFound?	try\n{\n    var requestedParameters = MyReportViewer.ServerReport.GetParameters();\n\n    var filledParameters = GetFilledParameters(requestedParameters);\n\n    MyReportViewer.ServerReport.SetParameters(requestedParameters);\n    MyReportViewer.ServerReport.Refresh();\n}\ncatch (ReportServerException exception)\n{\n    if (!exception.Message.Contains("rsItemNotFound"))\n    {\n        throw;\n    }\n    // Else... ReportViewer will show "rsItemNotFound" error. \n    // Or you can do something fancy in your app here, I suppose :-)\n}	0
24054012	24053791	How to get the value of selected row from PostgreSQL in C#?	public void myMethod()\n{\n    this.OpenConn(); //opens the connection\n\n    string sql = "SELECT id FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'customers' ORDER BY id DESC, LIMIT 1";\n\n    using (NpgsqlCommand command = new NpgsqlCommand(sql, conn))\n    {\n        int val;\n        NpgsqlDataReader reader = command.ExecuteReader();\n        while(reader.Read()){\n           val = Int32.Parse(reader[0].ToString());\n           //do whatever you like\n        }\n\n        this.CloseConn(); //close the current connection\n    }\n}	0
29665670	29665518	How to set content type to html and plain text	using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT)) \n{\n    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("fromfield@example.com",\n                                          "tofield@example.com",\n                                          "subject",\n                                          "<i><strong>body</strong></i>");\n    message.IsBodyHtml = true;\n    client.Send(message);\n}	0
10217330	10217286	Silverlight - Width of a Textblock	TextBlock.ActualWidth	0
4546412	4546381	Enumerate and copy properties from one object to another object of same type	private object CloneObject(object o)\n{\n    Type t = o.GetType();\n    PropertyInfo[] properties = t.GetProperties();\n\n    Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, \n        null, o, null);\n\n    foreach (PropertyInfo pi in properties)\n    {\n        if (pi.CanWrite)\n        {\n            pi.SetValue(p, pi.GetValue(o, null), null);\n        }\n    }\n\n    return p;\n}	0
13374491	13374454	Declare and assign multiple string variables at the same time	string Camnr, Klantnr, Ordernr, Bonnr, Volgnr;// and so on.\nCamnr = Klantnr = Ordernr = Bonnr = Volgnr = string.Empty;	0
1153028	1152960	Overridable Methods In Constructors -Help to Fix	private string _description;\npublic Region(string description)\n{\n    Check.Require(!string.IsNullOrEmpty(description));\n    _description = description;\n}\n\nprotected Region()\n{\n}\n\n[DomainSignature]\npublic virtual string Description {\n    get {return _description;} \n    set {_description = value;}\n}	0
9488679	9484700	How to edit the ApplicationSettings section of app.config in WPF application	public void WriteLocalValue(string localKey, string curValue) \n{ \n    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); \n    KeyValueConfigurationElement k = config.AppSettings.Settings[localKey]; \n    if (k == null) \n        config.AppSettings.Settings.Add(localKey, curValue); \n    else \n        k.Value = curValue; \n    config.Save(); \n} \n\npublic string ReadLocalValue(string localKey, string defValue) \n{ \n    string v = defValue; \n    try \n    { \n        Configuration config = ConfigurationManager.OpenExeConfiguration( Application.ExecutablePath); \n        KeyValueConfigurationElement k = config.AppSettings.Settings[localKey]; \n        if (k != null) v = (k.Value == null ? defValue : k.Value); \n            return v; \n    } \n    catch { return defValue; } \n}	0
1540826	1540714	Wire _KeyDown event of textbox to a _click event of button control	private void txtWO_KeyUp(object sender, KeyEventArgs e)    {        \n    if (e.KeyCode == Keys.Enter)        {            \n         btnFill_Click();\n    }    \n}	0
12318379	12041673	C# Excel interop sort range so blank cells go to last and cells with data go up	var sortedDataGroup = datagroup.OrderBy(row =>\n{\n    var wrapper = new DataRowWrapper(row, type);\n\n    if (wrapper.Incasari != null)\n        return wrapper.ContCor.ToLower();\n    else\n        return "A"; // Capital letters are after lower case letters\n});	0
15579085	15578911	Conditional statements and how to increment a variable	else\n    {\n        substitutions = d[i - 1, j - 1] + 1;\n        insertions =  Math.Min(d[i, j - 1] + 1, substitutions);\n        deletion = Math.Min(d[i - 1, j] + 1, insertions);\n        d[i, j] = deletion;\n\n        if (/* whatever */)\n            counter++;\n    }	0
6742096	6741883	C# Convert int to currency string with decimal places	int originalValue = 80;\n    string yourValue = (originalValue / 100m).ToString("C2");	0
11389697	11388227	Fluent NHibernate Dictionary<string, Entity> using 3 Tables	public virtual IDictionary<Column, Cell> Cells { get; private set; }\n\nHasMany(m => m.Cells)\n    .Table("Cells")\n    .KeyColumn("Row_Id")\n    .AsEntityMap("Column_id")\n    .Inverse().Cascade.All();	0
11011182	11011128	How can I sort on multiple fields with LINQ?	.OrderByDescending(item => item.RowKey.Substring(0,4))\n.ThenBy(item => item.ShortTitle)	0
3718222	3718174	How to make an Encode function based on this Decode function?	byte Encode(byte EncodedByte) \n{ \n    EncodedByte = (byte)((EncodedByte << 4) | (EncodedByte >> 4)); \n    EncodedByte ^= (byte)194; \n    return EncodedByte; \n}	0
12081731	12081391	Modify property values for Debug and Release Configuration without defining respective dictionaries	var project = ProjectRootElement.Open(fileName);\nproject.PropertyGroups.Where(x => x.Condition.Contains("x86") || \n                                  x.Condition.Contains("AnyCPU"))\n    .ToList().ForEach(x => x.AddProperty("WarningLevel", "4"));	0
10377562	10377536	Selecting items from generic list based on true condition from another list	var results = listData.Where((item, index) => listFilter[index] == 1);	0
30787553	30629616	How to get all sections of a specific type	var config = HostingEnvironment.IsHosted\n    ? WebConfigurationManager.OpenWebConfiguration(null) // Web app.\n    : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Desktop app.	0
12395050	12395006	How do I do multiple replaces on a string at the same time?	string finalString = Properties.Settings.Default.ConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");	0
25068308	25068092	Download pdf file with incrementing filename	const string BASE_URL ="http://www.website.com/";\n    const string FILE_NAME = "newsletter{0}of{1}.pdf";\n\n    var stringLastNumber = File.ReadAllText("lastnumber.txt");\n    var lastNumber = Convert.ToInt32(stringLastNumber);\n\n    var thisFileName = String.Format(FILE_NAME, lastNumber++, DateTime.Now.Year);\n    var uri = new Uri(String.Concat(BASE_URL, thisFileName));\n\n    File.WriteAllText("lastnumber.txt", lastNumber.ToString());\n\n    using (var client = new WebClient())\n    {\n        client.DownloadFile(uri, thisFileName);\n    }	0
16173677	16171165	Global appBar, add other buttons to this appbar for a specific page	protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)\n{\n    ApplicationBar.Buttons.Remove(appBarButtonTagPlace);\n    base.OnNavigatedFrom(e);\n}	0
11809259	11809219	How to change where UnauthorizedAccessException redirects to in ASP.Net	try\n        {\n            // code here\n        }\n        catch (UnauthorizedAccessException)\n        {\n            Response.Redirect(errorPageUrl, false);\n        }\n        catch (Exception)\n        {\n            Response.Redirect(loginPageUrl, false);\n        }	0
13920257	13920181	How to ensure a certain method doesn't get executed if some other method is running?	static object _syncRoot = new object();\npublic int getCurrentValue(int valueID)\n{\n    lock(_syncRoot)\n    {\n        value = // read value from DB\n    }\n}\n\npublic void updateValues(int componentID)\n{\n    lock(_syncRoot)\n    {\n        // update values in DB\n    }\n}	0
33695423	33692732	How a Rect object able to intersectwidth Rectangle object? (in WPF, C#)	rct.IntersectsWith(new Rect(rctn.Margin.Left, rctn.Margin.Top, rctn.Width, rctn.Height));	0
1027631	1027605	Setting default fonts in C#	private void Form1_Load(object sender, EventArgs e)\n{\n   this.Font = font_from_settings;\n}	0
32135560	32135421	Index was outside the bounds of array at trimmed text	private void button1_Click(object sender, EventArgs e)\n{\n    if (textBox1.Text.Length != 0)\n    {\n        var numePrenume = textBox1.Text.Trim().Split(' ');\n        var nume = numePrenume[0];\n\n        if(numePrenume.Length >= 1) \n        {\n            var prenume = numePrenume[1];\n        }\n\n        if (nume.Length > 0 || prenume.Length > 0)\n        {\n            var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";\n            using (var conn = new SqlCeConnection(connString))\n            {\n            }\n        }\n        //some code\n    }	0
7291243	7291218	calculating factorials in C#	static void Main(string[] args)\n{\nConsole.WriteLine("Input a value n");\nstring number = Console.ReadLine(); // read number\nint n = Convert.ToInt32(number); // converting to int\n\nConsole.WriteLine("Do you want to calculate factorial or sum");\nConsole.WriteLine("Enter F or S");\nstring choose = Console.ReadLine(); // F or S\n\nint result = -1; // to view later\n\nif (choose == "f" || choose == "F")\n{\n result = 1;\n for (int i = n; i >= 1; i--) // loop for calculating factorial\n   result *= i;\n}\nelse if (choose == "s" || choose == "S")\n{\n result = 0;\n for (int i = n; i >= 1; i--) // loop for calculating sum\n   result += i;\n}\n\nConsole.WriteLine(result); // printing answer\n\nConsole.WriteLine("Press any key to close...");\nConsole.ReadLine();\n}	0
16254337	16253486	How can test if an image is onto another in WPF?	VisualTreeHelper.HitTest(...)	0
6743674	6743644	How to change the mouse cursor into a custom one when working with Windows Forms applications?	Cursor myCursor = new Cursor("myCursor.cur");\nmyControl.Cursor = myCursor;	0
22182466	22182387	Dataset, For Loop to return row value for match	if (txtfname.Text == (string) ds.Tables[0].Rows[i]["first_name"])	0
11263780	11263754	GridView removes a row	myReader.Read();	0
19987806	19964733	NInjecting into a asp.net website httphandler	public class MyHandler : Ninject.Web.HttpHandlerBase\n{\n    [Inject]\n    public IHelloService HelloService { get; set; }\n\n    protected override void DoProcessRequest(HttpContext context)\n    {\n        context.Response.Write(HelloService.Hello());\n    }\n\n    public override bool IsReusable { get { return true; } }\n}	0
4522141	4522128	Using the same lock for muliple methods	private static object sharedInstance;\npublic static object SharedInstance\n{\n     get\n     {\n          if (sharedInstance == null)\n              Interlocked.CompareExchange(ref sharedInstance, new object(), null);\n          return sharedInstance;\n     }\n}	0
25410898	25410805	How to get values out of a Background Worker's event args?	List<long?> docRefIds = new List<long?>();	0
25932979	25932873	Add a ListViewItem to multiple groups	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));\nfor (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}	0
13063542	13062716	Repeater Control : Move individual item	var topItmes = new List<ChallengeList>();\nvar otherItmes = new List<ChallengeList>();\n\nforeach (var item in challenge)\n{\n    if(/*item needs to be on top*/)\n    {\n        topItmes.Add(item);\n    }\n    else\n    {\n        otherItmes.Add(item);\n    }\n}\n\ntopItmes.AddRange(otherItmes);	0
2680598	2680595	how to calculate the 4 days before date of the target date	var dt = new DateTime(2010, 5, 2);\nvar fourDaysBefore = dt.AddDays(-4);	0
7675241	7675205	How to Create a Read-Only Object Property in C#?	public class Product\n{\n    private Product(){}\n\n    public string Name { get; private set; }\n\n    public static Product Create(string name)\n    {\n        return new Product { Name = name };\n    }\n}	0
11015409	11015157	How Do I Redirect Output From Powershell	Process.StandardOutput	0
2153925	2153895	Shuffle lines in a file in .NET	var lines = File.ReadAllLines("test.txt");\nvar rnd = new Random();\nlines = lines.OrderBy(line => rnd.Next()).ToArray();\nFile.WriteAllLines("test.txt", lines);	0
23614256	23614159	How to assign values to instances of type T?	public abstract class DataFileBase<T>\n{\n    protected abstract T BuildInstance(string[] tokens);\n}\n\npublic AccountDataFile : DataFileBase<AccountDataFile.Account>\n{\n    protected override Account BuildInstance(string[] tokens)\n    {\n        var account = new Account();\n        account.Name = tokens[0]; // or whatever\n\n        return account;\n    }\n}	0
26827053	26827011	Update all links in Excel file	Sub HyperLinkChange()\n   Dim oldtext As String\n   Dim newtext As String\n   Dim h As Hyperlink\n\n   oldtext = "F:\"\n   newtext = "G:\"\n       For Each h In ActiveSheet.Hyperlinks\n       x = InStr(1, h.Address, oldtext)\n       If x > 0 Then\n           h.Address = Application.WorksheetFunction. _\n           Substitute(h.Address, oldtext, newtext)\n       End If\n       Next\nEnd Sub	0
3791450	3787283	how can i get the radio button inside a Wpf item template column	Radiobutton.IsChecked	0
4775831	4775624	How to write a unit test for thread unsafe collection	ICollection<T>	0
25808345	25807592	How to select data based on what a user has access to using Entity Framework	var userId = ..; // provides the user id\nDatas = c.Datas.Where(d => \n    !d.Deleted \n    && DatabaseContext.UserDatas.Any(ud => \n        ud.DataId == d.DataId && ud.Id == userId).ToList()\n)	0
16644674	16643137	retrieve data from access database	// note the ID=?\nmyCommand.CommandText = "SELECT ImageName AS 'ImageName', ImagePath AS 'Path' FROM [AImages]  WHERE ID=?";\nmyCommand.CommandType = CommandType.Text;\n\n// now a parameter\nvar pId = new OleDbParameter {Value = _ID};\nmyCommand.Parameters.Add(pId);	0
2095371	2095313	Best way of validating/creating a number only text-box?	isNaN()	0
569211	568941	How do I get a control which looks like a TabControl with no tabs?	protected override void OnPaintBackground(PaintEventArgs e)\n{\n    if (TabRenderer.IsSupported && Application.RenderWithVisualStyles)\n    {\n        TabRenderer.DrawTabPage(pe.Graphics, this.ClientRectangle);\n    }\n    else\n    {\n        base.OnPaintBackground(pe);\n        ControlPaint.DrawBorder3D(pe.Graphics, this.ClientRectangle, Border3DStyle.Raised);\n    }\n}	0
24166474	24166340	Set up a socket server	private Socket m_ServerSocket;\n\n...\n\npublic TcpListener(IPEndPoint localEP)\n{\n  if (Logging.On)\n    Logging.Enter(Logging.Sockets, (object) this, "TcpListener", (object) localEP);\n  if (localEP == null)\n    throw new ArgumentNullException("localEP");\n  this.m_ServerSocketEP = localEP;\n  this.m_ServerSocket = new Socket(this.m_ServerSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);\n  if (!Logging.On)\n    return;\n  Logging.Exit(Logging.Sockets, (object) this, "TcpListener", (string) null);\n}	0
28436021	16622895	Get Type from Fully qualified name only in Windows Store App	var filename = file.Name.Substring(0, file.Name.Length - file.FileType.Length);\n\nAssemblyName name = new AssemblyName() { Name = filename };\nAssembly asm = Assembly.Load(name);	0
15843627	15843428	Trying to parse xml in Windows Phone 7.8 app but getting null value?	XNamespace ns = "urn:types.partner.api.shopping.com";\nXDocument xDoc = new XDocument();\nxDoc = XDocument.Parse(data);\nvar xEle = xDoc.Root.Descendants(ns + "categories");	0
25979636	25451429	Read protobuff text file using protobuff-csharp port	using (TextReader inputStream = new StreamReader(new FileStream(@"C:\PersonDirectory.txt", FileMode.Open, FileAccess.Read), Encoding.ASCII))\n{\n                PersonDir.Builder personDirBuilder = PersonDir.CreateBuilder();\n                TextFormat.Merge(inputStream, personDirBuilder);\n                PersonDir pd = personDirBuilder.Build();\n}	0
28278919	28278846	how to auto increment the number to increment by 1 after saving	int versionNumber = 1000;\n\npublic void versionIncrement()\n{\n    versionNumber++;\n    lblOutput.Text = versionNumber.ToString();\n    lblOutput.Visible = true;\n}	0
1546687	1546614	Logging in with a ReturnUrl pointing to a POST action: FAIL!	[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult SomeFormAction()\n{ \n    //redirect them back to the original form GET here \n    RedirectToAction(stuffhere);\n}\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult SomeFormAction(FormCollection collection)\n{ \n    //this is your original POST \n}	0
7986418	7986331	Binding between controls in a template	IsOpen="{Binding ElementName=Bd, Path=IsChecked}"	0
6306922	6287579	How do I get posted data in MVC Action?	public ActionResult BuildPreview(string hwid, string label, string localization)\n         {\n             StreamReader streamReader = new StreamReader(Request.InputStream);\n             XmlDocument xmlDocument = new XmlDocument();\n             xmlDocument.LoadXml(streamReader.ReadToEnd());\n               ... \n\n }	0
2651460	2651423	Listview : How do I get RowHeader	public void InitializeListView()\n{\nColumnHeader header1 = this.listView1.InsertColumn(0, "Name", 10*listView1.Font.SizeInPoints.ToInt32() , HorizontalAlignment.Center);\nColumnHeader header2 = this.listView1.InsertColumn(1, "E-mail", 20*listView1.Font.SizeInPoints.ToInt32(), HorizontalAlignment.Center);\nColumnHeader header3 = this.listView1.InsertColumn(2, "Phone", 20*listView1.Font.SizeInPoints.ToInt32(), HorizontalAlignment.Center );\n}	0
19998259	19998062	Adding parameters in stored procedure using c#	int control = 5;\nstring colPrefix = "@COL";\nvar sql = new StringBuilder("sp_INSERT ").Append(colPrefix).Append(control);\n// note first item has different format due to comma\nfor(int i = control - 1; i > 0; i--)\n{\n    sql.Append(", ").Append(colPrefix).Append(i);\n}\nsql.Append(';');\nstring s = sql.ToString();	0
24647909	24633306	Excel cell format issue	Excel.Range oRange = objWorksheet.get_Range("A1:C10");\nforeach(Excel.Range cell in oRange.Cells)\n{\n    cell.Formula = cell.Formula\n}	0
26976424	26975946	detecting usb-device insertion and removal in c#	GUIobject.Dispatcher.BeginInvoke(\n        (Action)(() => { string value = myTextBox.Text; }));	0
30673207	30673151	Regex replace string, but only if non-whitespace before the string	(?<=\w)-           // (?<=\w)[dash][space]	0
14723682	14707524	Reading a posted XML file in a c# webservice	[WebMethod]\npublic string sendXliff()\n{\n    XmlDocument xmldoc = new XmlDocument();\n    //if (Request.InputStream != null)\n    if(HttpContext.Current.Request.InputStream!=null)\n    {\n\n        StreamReader stream = new StreamReader(HttpContext.Current.Request.InputStream);\n        string xmls = stream.ReadToEnd();  // added to view content of input stream\n        //XDocument xmlInput = XDocument.Parse(xmls);\n        xmldoc.LoadXml(xmls);\n        XmlReaderSettings settings = new XmlReaderSettings();\n        settings.Schemas.Add(null, "XSD LOCATION");\n        settings.ValidationType = ValidationType.Schema;\n        XmlReader rdr = XmlReader.Create(new StringReader(xmldoc.InnerXml), settings);\n        while (rdr.Read()) { }\n    }\n    try\n    {\n        XmlNodeList xmlnode = xmldoc.GetElementsByTagName("ID");\n        var sid = xmlnode[0].FirstChild.Value;\n    }\n    catch (Exception ex)\n    {\n    }\n\n    return "OK";\n}	0
3676491	3676448	Adding a derived interface to generic interface	interface IFinder<out T> ...	0
24586890	24586690	Parse Json Object in asp.net	Product product = new Product();\n\nproduct.Name = "Apple";\nproduct.ExpiryDate = new DateTime(2008, 12, 28);\nproduct.Price = 3.99M;\nproduct.Sizes = new string[] { "Small", "Medium", "Large" };\n\nstring output = JsonConvert.SerializeObject(product);\n//{\n//  "Name": "Apple",\n//  "ExpiryDate": "2008-12-28T00:00:00",\n//  "Price": 3.99,\n//  "Sizes": [\n//    "Small",\n//    "Medium",\n//    "Large"\n//  ]\n//}\n\nProduct deserializedProduct = JsonConvert.DeserializeObject<Product>(output);	0
17656648	17653820	Can't Retrieve Values of XML Elements using XElement	xdoc.Element(XName.Get("CODELIST", dns.NamespaceName)).Element(XName.Get("CODELIST_NAME", dns.NamespaceName)).Value,	0
9294431	9294406	Combine two datetime variables into one	newDateTime = date.Date + time.TimeOfDay;	0
4763513	4763124	Need to change selected item in dropdown list when selected item in another dropdown list changes	foreach (AppTable table in appTableList)\n        {\n            if (!cbxUpdateAppType.Items.Contains(table.Type))\n                cbxUpdateAppType.Items.Add(table.Type);\n        }	0
21205533	21205491	Is there a way to clear a TextBox's text without TextChanged firing?	if (txtMyOtherText.Text == string.Empty)\n{\n    MessageBox.Show("The other text field should not be empty.");\n    txtMyText.TextChanged -= textMyText_TextChanged;\n    txtMyText.Clear(); \n    txtMyText.TextChanged += textMyText_TextChanged;\n    return;\n}	0
28587425	28586155	How to get values from a one to many table column without foreign key included in EF model	var t2 = db.t2s.Find(t2ID);\nvar t1s = db.t1s.Where(m => m.t2NavProperty == t2);	0
1188539	1188510	Delete node range in xml document	int trimFeeds = 20;\n\nXmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(MapPath("rss.xml"));\n\nXmlNodeList nodeList = xmlDoc.SelectNodes(string.Format("rss/channel/item[position() > {0}]", trimFeeds));\n\nforeach (XmlNode node in nodeList)\n{\n    node.ParentNode.RemoveChild(node);\n}\nxmlDoc .Save(MapPath("rss.xml"));	0
3463928	3463911	Grab data from table, join string from two columns, display in MVC selectList	var v = dc.threecolumntable.Select(x => new {DataValue = x.id, DataText = x.text1 + ", " + x.text2 })	0
1368857	1368640	XDocument/Linq concatenate attribute values as comma separated list	String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());	0
25573229	25569773	.NET 3.5 how can I decompress a ZIP file with DotNetZip to a specified location	private void UnZip(string filePath, string targetPath)\n{\n    if (String.IsNullOrWhiteSpace(filePath) || String.IsNullOrWhiteSpace(targetPath))\n    {\n        throw new ArgumentException("Arguments cannot be null or empty.");\n    }\n\n    using (ZipFile zf = ZipFile.Read(filePath))\n    {\n        foreach (var entry in zf)\n        {\n            entry.Extract(targetPath, ExtractExistingFileAction.OverwriteSilently);\n        }\n    }\n}	0
29948592	29922868	OCR multiple images into one PDF	//... declare variables \nNSOCRLib.NSOCRClass NsOCR = new NSOCRLib.NSOCRClass();\nNsOCR.Engine_InitializeAdvanced(out CfgObj, out OcrObj, out ImgObj); \nNsOCR.Svr_Create(CfgObj, TNSOCR.SVR_FORMAT_PDF, out SvrObj); //create Saver object, output format is PDF\nfor (i = 0; i < ImageCnt; i++)\n{\n   NsOCR.Img_LoadFile(ImgObj, ImageFiles[i]);\n   NsOCR.Img_OCR(ImgObj, TNSOCR.OCRSTEP_FIRST, TNSOCR.OCRSTEP_LAST, TNSOCR.OCRFLAG_NONE);\n   NsOCR.Svr_AddPage(SvrObj, ImgObj, TNSOCR.FMT_EXACTCOPY);\n}\nNsOCR.Svr_SaveToFile(SvrObj, "c:\\PDF.pdf");	0
17903694	17902672	Append XML using WCF	xmlDoc.Save("c:\\User.xml")	0
1152823	1152768	WPF: Asynchronous progress bar	pb.Dispatcher.Invoke(\n                  System.Windows.Threading.DispatcherPriority.Normal,\n                  new Action(\n                    delegate()\n                    {\n\n                        if (pb.Value >= 200)\n                            pb.Value = 0;\n\n                        pb.Value += 10;\n                    }\n                ));	0
29434749	29434653	Is there a way to prevent a part of a string to be printed out?	public class MySpecialString\n{\n    private string _userEntered;\n\n    public string VisibleText \n    {   \n       get\n       {\n         return _userEntered;\n       }\n       set\n       {\n          _userEntered = value;\n           //set your added text  value here...\n          AddedText = "&123";  //example\n       }\n     }\n    public string AddedText {get; private set; }\n\n    public override string ToString()\n    {\n      return VisibleText;\n    }\n }	0
15297582	15297192	Creating a multiple-level MemberExpression	var parameter = Expression.Parameter(entityType, "entity");\n\n   // Expression: "entity.Property"\n   var property = Expression.Property(parameter, propertyName);\n   var subProperty = Expression.Property(property, subPropertyName);	0
8320749	8320729	equivalent to title attribute of anchor html tag in comobobox	ToolTip T = new ToolTip();\nT.SetToolTip(yourComboBox, "The title...");	0
21843253	21842551	ICollection in interface with another interface as the type	public interface IMembershipPrincipal<T> where T:IEmail\n{\n    int ID { get; set; }\n    string UserName { get; set; }\n    ICollection<T> Emails { get; set; }\n}\n\npublic interface IEmail\n{\n    string Address { get; set; }\n    int UserID { get; set; }\n}\n\npublic class User : IMembershipPrincipal<Email>\n{\n    [Key]\n    public int ID { get; set; }\n    public string UserName { get; set; }\n    public virtual ICollection<Email> Emails { get; set; }\n}\n\npublic class Email : IEmail\n{\n    [Key]\n    public string Address { get; set; }\n    public int UserID { get; set; }\n}	0
17916412	17916183	Handle click on a sub-item of ListView	private void listView_Click(object sender, EventArgs e)\n{\n    Point mousePos = listView.PointToClient(Control.MousePosition);\n    ListViewHitTestInfo hitTest = listView.HitTest(mousePos);\n    int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);\n}	0
4530840	4530603	How can I format the string `00:00:30:00` to TimeSpan?	public static bool TryParseTime(string txt, string fmt, out TimeSpan ts) {\n        DateTime dt;\n        bool ok = DateTime.TryParseExact(txt, fmt, null, \n            System.Globalization.DateTimeStyles.NoCurrentDateDefault, out dt);\n        ts = new TimeSpan(ok ? dt.Ticks : 0);\n        return ok;\n    }	0
6795748	6794882	How to convert multiple SQL LEFT JOIN statement with where clause to LINQ	const string con1 = "abc";\nconst string con2 = "xyz";\nvar query =\n    from ve in valuationEventPit\n    join fsn in finStatNew on ve.EntityId equals fsn.EntityID\n    join fso in finStatOld on ve.EntityId equals fso.EntityID\n    let FinStatNew = fsn.FinanceStat\n    let FinStatOld = fso.FinanceStat\n    where FinStatNew != FinStatOld && FinStatOld != null\n       && new[]{con1,con2}.All(con => !FinStatNew.Contains(con))\n    select new { ve.EntityId, FinStatNew, FinStatOld };	0
714543	714507	How do I programatically change printer settings with the WebBrowser control?	using System.Management\n\npublic static bool SetDefaultPrinter(string defaultPrinter)\n{\n    using (ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"))\n    {\n        using (ManagementObjectCollection objectCollection = objectSearcher.Get())\n        {\n            foreach (ManagementObject mo in objectCollection)\n            {\n                if (string.Compare(mo["Name"].ToString(), defaultPrinter, true) == 0)\n                {\n                    mo.InvokeMethod("SetDefaultPrinter", null, null);\n                    return true;\n                }\n            }\n        }\n    }\n}	0
719589	719502	How can I convert bits to bytes?	bytes[byteIndex] |= (byte)(1 << (7-bitIndex));	0
16894191	16893952	Localization with parameters of output message C#	string.Format(yourResources.WhateverNameYouUsed, opId);	0
32229160	32224337	SSIS Custom transformation recieve variable	var dimSrcId ="";\n\nIDTSVariables100 variables = null;\n\nthis.VariableDispenser.LockForRead("User::dimSrcId");\n\nthis.VariableDispenser.GetVariables(out variables);\n\ndimSrcId = variables["User::dimSrcId"].Value.ToString();\n\nvariables.Unlock();	0
9312509	6499861	Communicating with a socket.io server via c#	socket.On("news", (data) =>    {\nConsole.WriteLine(data);\n});	0
21539357	21531520	Disable version check for specific property in Sitecore glass mapper	public class MyCrazyType : SitecoreFieldTypeMapper\n{\n    public override object GetFieldValue(string fieldValue, Mapper.Sc.Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context)\n    {\n        using (new VersionCountDisabler())\n        {\n            return base.GetFieldValue(fieldValue, config, context);\n        }\n    }\n\n    public override bool CanHandle(Mapper.Configuration.AbstractPropertyConfiguration configuration, Context context)\n    {\n        //this will mean this handle only works for this type\n        return configuration.PropertyInfo.PropertyType == typeof (ServiceMapping);\n    }\n\n}	0
21429214	21429079	Can not insert data ino table	insert into info(c_name,c_address, machine, s_version, email,i_date,due_date)	0
8402301	8402285	How do I get the first value from this collection using Linq to Entities?	userGroups.FirstOrDefault();	0
2283216	2283001	C# pattern matching	private string AddSpan(string originalString, int[] location, string color)\n    {\n        string old = originalString.Substring(location[0], location[1]);\n        string newStr = string.Format("<span id= '{0}' color='{1}'>", "idUWant", color);\n        originalString = originalString.Replace(old, newStr);\n        return originalString ; \n    }	0
33083303	33050521	Rackspace Cloud Files Get Objects In Container C#	using System;\nusing net.openstack.Core.Domain;\nusing net.openstack.Providers.Rackspace;\n\nnamespace ListCloudFiles\n{\n    class Program\n    {\n        static void Main()\n        {\n            var region = "DFW";\n            var identity = new CloudIdentity\n            {\n                Username = "username",\n                APIKey = "apikey"\n            };\n\n            var cloudFilesProvider = new CloudFilesProvider(identity);\n\n            foreach (Container container in cloudFilesProvider.ListContainers(region: region))\n            {\n                Console.WriteLine(container.Name);\n\n                foreach (ContainerObject obj in cloudFilesProvider.ListObjects(container.Name, region: region))\n                {\n                    Console.WriteLine(" * " + obj.Name);\n                }\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
6766174	6765991	Remove Read-Only Attribute On FOLDER On A Network Share	attrib -r	0
13780780	13780654	Extract all strings between two strings	private static List<string> ExtractFromString(\n    string text, string startString, string endString)\n{            \n    List<string> matched = new List<string>();\n    int indexStart = 0, indexEnd=0;\n    bool exit = false;\n    while(!exit)\n    {\n        indexStart = text.IndexOf(startString);\n        indexEnd = text.IndexOf(endString);\n        if (indexStart != -1 && indexEnd != -1)\n        {\n            matched.Add(text.Substring(indexStart + startString.Length, \n                indexEnd - indexStart - startString.Length));\n            text = text.Substring(indexEnd + endString.Length);\n        }\n        else\n            exit = true;\n    }\n    return matched;\n}	0
2215190	2215162	Reading a line in c# without trimming the line delimiter character	public IEnumerable<int> GetLineStartIndices(string s)\n{\n    yield return 0;\n    byte[] chars = Encoding.UTF8.GetBytes(s);\n    using (MemoryStream stream = new MemoryStream(chars))\n    {\n        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))\n        {\n            while (reader.ReadLine() != null)\n            {\n                yield return stream.Position;\n            }\n        }\n    }\n}	0
33915212	33914126	How to grab Checkbox values in an WebApp	foreach(var m in model.Merchants)\n{\n    if(m.IsSelected)\n    {\n        //execute code for this checkbox being checked\n    } \n}	0
10135814	10133051	Lambda expression and join	var ids = ids.Select(m => m.Ip).ToList();\n\nvar query = follows.Where(i => i.EUser.EProviders.Any(m => m.ProviderType ==EProvider.EnumProviderType.Facebook && ids.Contains(m.Ip)));	0
13438078	13437889	Showing a Context Menu for an item in a ListView	private void listView1_MouseClick(object sender, MouseEventArgs e)\n{            \n    if (e.Button == MouseButtons.Right)\n    {\n        if (listView1.FocusedItem.Bounds.Contains(e.Location) == true)\n        {\n            contextMenuStrip1.Show(Cursor.Position);\n        }\n    } \n}	0
11943935	11943898	While downloading some content from a website after few times i got exception webexception 502 Bad gateway what could make that?	10.5.3 502 Bad Gateway\n\nThe server, while acting as a gateway or proxy, received an invalid response from the \nupstream server it accessed in attempting to fulfill the request.	0
26916653	26916420	Trouble converting dynamic variable to class	url: '/Home/getNewPrice',\n data: modelData\n\npublic JsonResult getNewPrice(modelData dropdownValue)\n{\n    //...\n    return Json(new { currentPrice = currentPrice }, JsonRequestBehavior.AllowGet);\n}\n\ndocument.getElementById('priceLabel').innerHTML = data.currentPrice;	0
33714850	33714849	ObjectContext with Entity Framework 6 inserting duplicates on existing related entities	if (model.Incident != null)\n{\n    DbContext dbContext = new DbContext(context, true);\n    dbContext.Entry(model.Incident).State = EntityState.Unchanged;\n}	0
15526376	15526202	Getting hours occupied in a day	if (StartDate.Date == EndDate.Date) { return Hours; }\nelse if (EndDate.Date != CurrentDay.Date) { return DayHours; }\nelse if (StartDate.Date <= CurrentDate.Date && EndDate.Date > CurrentDate.Date) { return Hours % DayHours; }\nelse return 0;	0
31319601	31171081	How do I find a customer's files using SuiteTalk?	CustomerSearchAdvanced attachSearch = new CustomerSearchAdvanced();\n\nSearchColumnStringField[] stringcols = new SearchColumnStringField[1];\nstringcols[0] = new SearchColumnStringField();\n\nSearchColumnStringField[] stringcols = new SearchColumnStringField[1];\nstringcols[0] = new SearchColumnStringField();\n\nattachSearch.columns = new CustomerSearchRow();\nattachSearch.columns.fileJoin = new FileSearchRowBasic();\nattachSearch.columns.fileJoin.internalId = selcols;\nattachSearch.columns.fileJoin.description = stringcols;\nattachSearch.columns.fileJoin.name = stringcols;	0
16245700	16240767	CRM 2011 One Plugin for Multiple Entities	var newTask = new Entity("Task");\nnewTask.Attributes.Add("subject", "foo");\n// etc etc for other common properties\nif (context.PrimaryEntityName.Equals("new_entitya"))\n{\n    newTask.Attributes.Add("new_optionset", valueA);\n}\nelse\n{\n    newTask.Attributes.Add("new_optionset", valueB);\n}	0
7732334	7732324	load a datatable to an existing table in dataset	myDataSet.Tables["sale_info"].Merge(my_table)	0
19215154	19215142	Distance Converter for inches, feet, and yards in C#	distanceOutput.Text = toDistance.ToString();	0
5235193	5235153	How to implement logic at "masterpage" level	Html.Action	0
33443866	33443676	Removing a key/value pair from a ConcurrentDictionary given a value	var itemsToRemove = dictionary.Where(kvp => kvp.Value.Equals(token));\nforeach (var item in itemsToRemove)\n   dictionary.TryRemove(item.Key, out token);	0
19992458	19897016	Getting Posts from Facebook page with specified fields	var client = new FacebookClient(accessToken);\nvar query = string.Format(@"{{ \n""posts"":""SELECT post_id, actor_id, attachment, permalink, app_data, type, likes.count,comments.count,message,source_id ,updated_time,created_time FROM stream WHERE source_id = {0} and updated_time > {1} and type > 0 LIMIT 100"", \n""photo_posts"":""SELECT photo_id, src, width, height FROM photo_src WHERE photo_id in (SELECT attachment.media.photo.fbid FROM #posts where type=247) and width > 300 and width < 500 order by width desc""}}",  userId, LongExtensions.DateTimeToUnixTimestamp(expirationDate.DateTime));\n\ndynamic parameters = new ExpandoObject();\nparameters.q = query;\n\nIList<dynamic> postsRaw = ObjectExtensions.ToData(this.client.Get("fql", parameters));	0
31793958	31793308	EF - A proper way to search several items in database	var matchingIds = from r in db.Rights\n                  where inputRightIds.Contains(r.Id)\n                  select r.Id;\n\nforeach(var id in matchingIds)\n{\n    // Do something\n}	0
25642186	25642160	How can i delete all the files in all directories?	foreach(var file in Files)\n     File.Delete(file);	0
2963607	2963593	Automatically display keyboard in Windows Mobile	InputPanel.Enabled = True	0
30685778	30685711	Using reflection to get attribute names in struct returns value__	var t = typeof(ItemTypes).GetFields().Where(k => k.IsLiteral == true);	0
2403361	2403348	How can I know if an SQLexception was thrown because of foreign key violation?	try\n{\n    # SQL Stuff\n}\ncatch (SqlException ex)\n{\n    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error\n    {\n        switch (ex.Errors[0].Number)\n        {\n            case 547: // Foreign Key violation\n                throw new InvalidOperationException("Some helpful description", ex);\n                break;\n            case 2601: // Primary key violation\n                throw new DuplicateRecordException("Some other helpful description", ex);\n                break;\n            default:\n                throw new DataAccessException(ex);\n        }\n    }\n\n}	0
19553210	19553003	Need a Regular Expression to validate a hostname and port to be used with TcpClient.Connect()	public static bool IsValidHostAddress(string hostAddress)\n{\n    const string Pattern =  @"^(([0-9]{1,3}.){3}([0-9]{1,3})|localhost):\d+$";\n\n    var regex = new Regex(Pattern, RegexOptions.Compiled);\n    return regex.Match(hostAddress).Success;\n}	0
22193107	22192820	WPF fade in animation disapears after finish	IconGlass.Visibility = Visibility.Visible;	0
24381878	24381648	How to force WebClient to DownloadStringAsync every time on app launch	wc.Headers[ HttpRequestHeader.IfModifiedSince ] = "Sat, 29 Oct 1994 19:43:31 GMT";	0
23996386	23996324	Convert array of string to array of double	File.ReadLines("decimal list.txt")\n    .Select(l => Convert.ToDouble(l))\n    .ToArray();	0
31063137	31062831	How to draw solid strings to a bitmap	grp.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;	0
7600041	7599935	Clearing items in Combobox if user selection changed	private void PopulateDatabases(string serverName)\n{\n        //populate Databases\n        //.. your code here ...\n\n        //clear the list\n        DatabasenamesList.Items.Clear();\n        foreach (var database in Databases)\n        {\n            DatabasenamesList_combobox.Items.Add(database);\n        }\n\n}	0
2286300	2284184	Entity Framework - How do I join tables on non-primary key columns in secondary tables?	from f in ctx.Foo\njoin b in ctx.Bar on f.DbValue equals b.DbValue\nselect new {f,b}	0
1747767	1747729	How to convert non-Exponential numbers to Exponential number in c#	number.ToString("E")	0
13377245	13376698	Most effective search algorithm to find multiple incorrect values in an array	// Remove this, if you want all matches\nbool found = false;\n\nfor (int start = 0; start < a.count; start++)\n{\n      // Maybe you need end = start + 1, not sure\n    for (int end = start; end < a.count; end++)\n    {\n        if (AreSumsEqual(start, end)\n        {\n            // Found! Let's break to avoid useless iterations,\n            // if we only want one match.\n            found = true;\n            break;\n        }\n    }\n\n    if (found)\n    {\n        break;\n    }   \n}	0
10329238	10329010	C# : How to resize image proportionately with max height	public static Image ScaleImage(Image image, int maxHeight) \n{ \n    var ratio = (double)maxHeight / image.Height; \n\n    var newWidth = (int)(image.Width * ratio); \n    var newHeight = (int)(image.Height * ratio); \n\n    var newImage = new Bitmap(newWidth, newHeight); \n    using (var g = Graphics.FromImage(newImage))\n    {\n        g.DrawImage(image, 0, 0, newWidth, newHeight); \n    }\n    return newImage; \n}	0
20422895	20422863	How to use for loop instead of foreach loop	for(int i = 0; i < Request.Form.Keys.Count; i++)\n{\n    string key = Request.Form.Keys[i];\n    string value = Request.Form[key];\n}	0
26662211	26660020	Xamarin ActionBar button items hidden	app:showAsAction="always"	0
14304441	14304432	How get positions of array without repeating positions?	var indexes = Enumerable.Range(0, caminohormiga.Length).ToArray();\n// Run Fisher-Yates algorithm on indexes\n...\nforeach (var i in indexes) {\n    var randomNoRepeat = caminohormiga[i];\n    ...\n}	0
18087639	18087566	C#: How to save a dictionary to a text file?	var binaryFormatter = new BinaryFormatter();\nbinaryFormatter.Serialize(fileStream, dict);	0
22958972	22956218	How can I animate the process of word reconstruction using WPF?	string a = "Hello World!";\nchar[] b = a.ToCharArray();\nfor (int i = 0; i < b.Length; i++)\n{\n   textblock1.Text+=a[i];\n   Thread.Sleep(100);\n}	0
30393954	30393101	Instantiating Wrapper objects in a generic method	public IList<IWrapped<Entity1>> GetAllEntity1()\n{\n    return GetAll<Entity1>.Select(e => new Entity1Wrapper(e)).ToList();\n}\n\npublic IList<IWrapped<Entity2>> GetAllEntity2()\n{\n    return GetAll<Entity1>.Select(e => new Entity2Wrapper(e)).ToList();\n}\n\n//...\n\nprivate IList<T> GetAll<T>()\n{\n    //Get IList<T> entityList by querying\n    return entityList;\n}	0
834765	706142	Obtain values from current row when databinding	private void Detail_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) {\n    if (string.IsNullOrEmpty(GetCurrentColumnValue("BarcodeColumnName"))) {\n        barcode.Visible = false;\n        lblWarning.Visible = true;\n    } else {\n        barcode.Visible = true;\n        lblWarning.Visible = false;\n    }\n}	0
6637986	6637807	Get index of a specific item from list containing possible duplicates	public static class ListExtension\n{\n    public static int GetIndex<T>(this List<T> list, T value, int skipMatches = 1)\n    {\n        for (int i = 0; i < list.Count; i++)\n            if (list[i].Equals(value))\n            {\n                skipMatches--;\n                if (skipMatches == 0)\n                    return i;\n            }\n        return -1;\n    }\n}\n\nList<int> list = new List<int>();\nlist.Add(3);\nlist.Add(4);\nlist.Add(5);\nlist.Add(4);\nint secondFour = (int)list.GetIndex(4, 2);	0
3386272	3386258	parsing a given path in c#	string dir = System.IO.Path.GetDirectoryName(myPath);	0
22906571	22658930	Add WSID in EF connectionstring	public partial class MyObjectEntities : DbContext\n{\n    public MyObjectEntities(string connectionString)\n        : base(connectionString)\n    {\n    }\n}	0
2976491	2976473	How to test if a DataSet is empty?	if (ds.Tables[0].Rows.Count == 0)\n{\n    //\n}	0
14442302	14441527	Make a WPF Scroll Viewer scroll regardless of mouse position	private void Window_PreviewMouseWheel(object sender, MouseWheelEventArgs e)\n{\n    if (!e.Handled)\n    {       \n        e.Handled = true;\n        var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);\n        eventArg.RoutedEvent = MouseWheelEvent;\n        eventArg.Source = sender;\n        MyTabControl.RaiseEvent(eventArg);\n    }\n}	0
26111536	26093236	Unable to update value to XML file in Windows Phone 8	stream.SetLength(xdoc.ToString().Length);	0
11428366	11413352	FluentCassandra selecting timestamp range with CQL	var start = (FilterStartTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalMilliseconds;\nvar end = (FilterEndTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalMilliseconds;	0
8055726	8055046	Using XmlReader to Read XML	//Enums/Enum_Entry[@EnumID=1]	0
8966279	8966003	Casting IIdentity to IMyIdentity with extra properties	public virtual IMyIdentity GetCurrentUserIdentity(bool ignoreXyz)\n{\n    if (_userProfile != null && _userProfile.IsAnonymous && (ignoreXyz || _userProfile.PointId > 0))\n    {\n        return new UserIdentity\n                   {\n                       Name = _userProfile.UserName,\n                       IsAuthenticated = true,\n                       AuthenticationType = UserIdentity.AUTHENTICATION_ANONYMOUS\n                   };\n    }\n    else\n    {\n        return new UserIdentity\n                   {\n                       Name = HttpContext.Current.User.Identity.UserName,\n                       IsAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated,\n                       AuthenticationType = HttpContext.Current.User.Identity.AuthenticationType\n                   };                           \n    }\n}	0
10459016	10434658	How to open process within Windows form	private void toolStripButton1_Click(object sender, EventArgs e)\n{\n  ProcessStartInfo info = new ProcessStartInfo();\n  info.FileName = "notepad";\n  info.UseShellExecute = true;\n  var process = Process.Start(info);\n\n  Thread.Sleep(2000);\n\n  SetParent(process.MainWindowHandle, this.Handle);\n}	0
26370196	26128732	Inherit XMLType of base class	[Serializable]\n[XmlType("Base")]\n[XmlInclude(typeof(InheritedClass1))] //Missing This line! \npublic class Base\n{\n     [XmlElement(ElementName = "IdBase")]\n     public int IdBase { get; set; }\n     ...\n}	0
11203062	11202673	Converting String To Float in C#	float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);	0
17210492	17210463	How shorten if something is null comprobation	Action<GrafBase> setVisibleIfNotNull = delegate(GrafBase graf)\n{\n    if (graf != null)\n        graf.IsVisible = true;\n};\nsetVisibleIfNotNull(item.Graf);\nsetVisibleIfNotNull(item.GrafReal);\nsetVisibleIfNotNull(item.GrafIm);	0
3208199	3208036	Linq-to-SQL Help - Selecting Duplicate Rows	var duplicatedSubscribers= \n    from s in subscribers \n    where s.subscribedTo == s.subscriber \n    group s by s.subscriber into g \n    where g.Count() > 1 \n    select new { subscriber = g.Key, Count = g.Count() };	0
16256348	16256315	How can I get data from server located .txt file or .php file	var client = new System.Net.WebClient();\nstring data = client.DownloadString("http://mysite.com/test.txt");	0
28292817	21853227	calender extender not showing full in div	calender= positon:absolute	0
8834603	8834562	ASP.NET download menu from a link	public class Download : IHttpHandler {\n    public void ProcessRequest (HttpContext context) {\n        string filename = context.Request.QueryString["file"];\n        string file = context.Server.MapPath(filename);\n        context.Response.ContentType = "application/octet-stream";\n        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));\n        try\n        {\n            context.Response.TransmitFile(file);\n        }\n        catch (Exception ex)\n        {\n            SendFailedDownload(filename, context);\n        }\n        finally\n        {\n        }\n    }\n}	0
18690785	18690293	Override abstract method, but keep method abstract?	public abstract class ComponentController\n{\n    protected abstract void CreateCustomColumnsCore();\n}\n\npublic abstract class ClientComponentController : ComponentController\n{\n    protected override void CreateCustomColumnsCore()\n    {\n        // your code here\n\n        CreateCustomColumns();  // call users' implementation\n    }\n\n    public abstract void CreateCustomColumns();\n}\n\npublic class ClientInvoicesComponentController: ClientComponentController\n{\n    public override void CreateCustomColumns()\n    {\n        // user must implement this method.\n    }\n}	0
21009068	21005331	How to unit test async methods of Entity Framework with a multiple clauses	public class TestDbAsyncEnumerable<T> \n    : EnumerableQuery<T>, IDbAsyncEnumerable<T>, IQueryable	0
15834827	15834764	Linq take 3 records from each category	var result = data.GroupBy(x => x.Category)\n                 .SelectMany(x => x.Take(3));	0
19210218	19209343	using c# in unity3D to open a window once the user clicked on a specific object	using UnityEngine;\nusing System.Collections;\n\npublic class OnClick : MonoBehaviour {\n\n    // Use this for initialization\n    private bool PopUp;\n    public string Info;\n\n    void OnMouseDown()\n    {\n        PopUp = true;\n    }\n\n    void DrawInfo()\n    {\n        Rect rect = new Rect (20,20, 300, 200);\n        Rect close = new Rect (300,20,20,20);\n        if (PopUp)\n        {\n            GUI.Box(rect, Info);\n            if (GUI.Button(close,"X"))\n            {\n                PopUp = false;\n            }\n        }\n    }\n\n    void OnGUI()\n    {\n        DrawInfo();\n    }\n}	0
13639601	13639438	How to show the progress bar when i am uploading a excel sheet using C#?	ProgressBar.Value	0
12426638	12426341	Convert a C# string array to a dictionary	var q = a.Zip(a.Skip(1), (Key, Value) => new { Key, Value })\n             .Where((pair,index) => index % 2 == 0)\n             .ToDictionary(pair => pair.Key, pair => pair.Value);	0
9303629	9303257	How to decode a Unicode character in a string	System.Text.RegularExpressions.Regex.Unescape("Sch\u00f6nen");	0
8376212	8376190	Linq to XML - Deserialize to Object	List<Order> myOrders = (from order in xdoc.Descendants("Order")\n                        select new Order {\n                        OrderNumber = order.Element("OrderNumber").Value,\n                        OrderDate = order.Element("OrderDate").Value,\n                        OrderTotal = order.Element("OrderTotal").Value\n                        }).ToList();	0
23575299	23573643	Which communication protocol to use in a ServiceStack multi-tier architecture	//fire off to 2 async requests simultaneously...\nvar task1 = client.GetAsync(new Request1 { ... });\nvar task2 = client.GetAsync(new Request2 { ... });\n\n//additional processing if any...\n\n//Continue when first response is received\nvar response1 = await task1;\n\n//Continue after 2nd response, if it arrived before task1, call returns instantly\nvar response2 = await task1;	0
29706607	29705261	Display list of events grouped by day of the week	StringBuilder el = new StringBuilder();\nusing (SqlConnection conn = new SqlConnection(connString)) {\n  SqlCommand cmd = new SqlCommand(@"\n              select * from Event \n              WHERE DATEDIFF(d, getdate(), StartDate) BETWEEN 0 and 6\n              order by StartDate", conn);\n  conn.Open();\n  SqlDataReader rdr = cmd.ExecuteReader();\n\n  if (rdr.HasRows) {\n    rdr.Read();\n    System.DayOfWeek lastDayProcessed = (DateTime)rdr["StartDate"]).DayOfWeek;\n    el.AppendLine("<strong>" + lastDayProcessed + "</strong> -");\n    el.Append(" " + rdr["Title"].ToString());\n\n    while (rdr.Read()) {\n      if (((DateTime)rdr["StartDate"]).DayOfWeek != lastDayProcessed) {\n        // print the Day heading whenever the day changes\n        el.AppendLine("<br />");\n        lastDayProcessed = ((DateTime)rdr["StartDate"]).DayOfWeek;\n        el.AppendLine("<strong>" + lastDayProcessed + "</strong> -");\n      }\n      el.Append(" " + rdr["Title"].ToString());\n    }\n  }\n  rdr.Close();\n}	0
3649836	3649804	Converting flat data from sql to List<Item>	var idLookup = new Dictionary<int, Item>();\nvar roots = new List<Item>();\nforeach([row]) {\n    Item newRow = [read basic row];\n    int? parentId = [read parentid]\n    Item parent;\n    if(parentId != null && idLookup.TryGetValue(parentId.Value, out parent)) {\n        parent.Items.Add(newRow);\n    } else {\n        roots.Add(newRow);\n    }\n    idLookup.Add(newRow.Id, newRow);\n}	0
16752389	16752224	Focus when double click on Notify Icon	private void noi_MouseDoubleClick(object sender, MouseEventArgs e)\n{\n    Activate();\n}	0
5681771	5681579	How can I retrieve the text from a specific element of this XML?	XDocument doc = XDocument.Parse(yourString);\n\nstring url = (from x in doc.Descendants("url") select x.Value).FirstOrDefault();	0
28097105	28097069	Dictionary - Getting the next element of a known element	Dictionary.Values	0
1806018	1806005	Programmatically adding buttons - Problem with subscription to a mouse event	foreach (var module in modules)\n{\n    var theModule = module;  // local variable\n    var btn = new Button();\n    btn.SetResourceReference(Control.TemplateProperty, "SideMenuButton");\n    btn.Content = theModule.Title;  // *** use local variable\n    btn.MouseEnter += (s, e) => { ShowInfo(theModule.Description); };  // *** use local variable\n    btn.MouseLeave += (s, e) => { HideInfo(); };\n    ModuleButtons.Children.Add(btn);\n}	0
10998616	10981210	Disable outlook 2003 toast notification programmatically?	using Microsoft.Win32;\n\n//this will create the subkey or if it already exists will just get the location. there is //no getsubkey in the registryclass\n\nRegistryKey rkRegOutlookPreferences = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Office\11.0\Outlook\Preferences");\n\n//this will add in or change a value in that subkey\n\nrkRegOutlookPreferences.SetValue("NewmailDesktopAlerts", "0", RegistryValueKind.DWord);\n\n//there is also getValue; this will return a null if the value doesnt exist\n\nrkRegOutlookPreferences.GetValue("NewmailDesktopAlerts")\n\n//and deleting \n\nrkRegOutlookPreferences.DeleteValue("NewmailDesktopAlerts");	0
2480120	2479861	.net XML serialization: how to specify an array's root element and child element names	public class MyClass\n{\n    public string Name {get;set;}\n    [XmlArray("ItemValues")]\n    [XmlArrayItem("ItemValue")]\n    public Items MyItems {get;set;}\n}	0
1117986	1117961	C#: How to use a Type Converter to localize enums	var foo = TypeDescriptor.GetConverter(typeof(T));\nvar mystring = foo.ConvertToString(myObject));	0
12852180	12851741	How to give button click event automatically	button1.PerformClick();	0
27297012	27271468	How to use ttl in elasticsearch bulk api (NEST)	desc.Index<Person>(i => i\n    .Document(p)\n    .Ttl(p.Age > 50 ? "1M" : "6M")\n);	0
24022263	24022047	How to specify two navigation properties from entity X to the same target entity, Y?	public class Instructor\n{\n  public InstructorTypesEnum Type { get; set; }\n\n  [InverseProperty("Instructors")]\n  public virtual ICollection<Course> Courses { get; set; }\n\n  [InverseProperty("Coinstructors")]\n  public virtual ICollection<Course> CoInstructingCourses { get; set; }\n}	0
17270127	17270045	How to Sort this String in Ascending Alphanumeric	var strTest = new List<string> { "B1", "B2", "B3", "B10" };\n    strTest.Sort((s1, s2) => \n    {\n        string pattern = "([A-Za-z])([0-9]+)";\n        string h1 = Regex.Match(s1, pattern).Groups[1].Value;\n        string h2 = Regex.Match(s2, pattern).Groups[1].Value;\n        if (h1 != h2)\n            return h1.CompareTo(h2);\n        string t1 = Regex.Match(s1, pattern).Groups[2].Value;\n        string t2 = Regex.Match(s2, pattern).Groups[2].Value;\n        return int.Parse(t1).CompareTo(int.Parse(t2));\n    });	0
30976680	30976342	how can I add a column to IQueryable object and modify its values	public class MyLovelyClass\n{\n    public Int32 Number { get; set; }\n    public bool Selection { get; set; }\n}\n\nvar packs = from r in new XPQuery<Roll>(session)\n            select new MyLovelyClass()\n            {\n               Number = r.number                \n            };\ngcPack.DataSource = packs;	0
30367601	24366562	c# X509Certificate2 add certificate how mark as exportable	X509Certificate2 certificate = new X509Certificate2(path, "password", X509KeyStorageFlags.Exportable);	0
18916557	18915735	How to Trigger Datagridview.cellValidating manually?	BeginEdit();\n DataGridViewCell currentCell = GrdDetails.CurrentRow.Cells("Prod_code");\n EndEdit();\n CurrentCell = null;\n CurrentCell = currentCell;	0
18953685	18953493	Saving data from multiple tabs in a tab control	// this is the base class for tab view models\npublic class DocumentViewModel\n{\n    public void SaveChanges() {}\n}\n\n// this is the view model for tab container\npublic class EditorViewModel\n{\n    private SaveChanges()\n    {\n        foreach (var document in OpenedDocuments)\n        {\n            document.SaveChanges();\n        }        \n    }\n\n    public EditorViewModel()\n    {\n        SaveCommand = new RelayCommand(SaveChanges);\n    }\n\n    // this is your tabs\n    public ObservableCollection<DocumentViewModel> OpenedDocuments { get; private set; }\n\n    public ICommand SaveChangesCommand { get; private set; }\n}	0
3044865	3044833	Can't get a return value from a foreach loop inside a method	else\n    {\n        string value = get_nodes_value(arg_node.ChildNodes, node_name);\n        if (value != "")\n            return value;\n    }	0
32037956	32036468	How to prevent application shutdown on close window?	ShutdownMode="OnExplicitShutdown"	0
26810658	26805755	Sending a bitmapData over network - as3	var byteArray:ByteArray = new ByteArray();\nmyBitmapData.encode(new Rectangle(0,0,640,480), new flash.display.PNGEncoderOptions(), byteArray); \nvar encoder:Base64Encoder = new Base64Encoder();\nencoder.encodeBytes(byteArray);\n\nNetwork.OpenNetworkToken("ADDIMAGE" + "|" + filename + "|" + encoder.toString());	0
24290366	24289947	Error in Coloring Datagridview Row in c#	private void dataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (e.RowIndex != -1)\n    {\n        if (dataGridView2.Rows[e.RowIndex].Cells[7].Value.ToString() == "Error")\n        {\n            e.CellStyle.BackColor = Color.Red;\n        }\n        else if (dataGridView2.Rows[e.RowIndex].Cells[7].Value.ToString() == "NoError")\n        {\n             e.CellStyle.BackColor = Color.Green;\n        }\n    }\n}	0
3692259	3692246	After making a hex mask CTRL+C and CTRL+V is not allowed	private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {\n        bool ok = e.KeyChar == 8;  // Backspace\n        if ("0123456789ABCDEF".Contains(char.ToUpper(e.KeyChar))) ok = true;\n        if (!ok) e.Handled = true;\n    }\n\n    private void textBox1_Validating(object sender, CancelEventArgs e) {\n        int value;\n        if (textBox1.Text.Length > 0) {\n            if (!int.TryParse(this.textBox1.Text, System.Globalization.NumberStyles.HexNumber, null, out value)) {\n                this.textBox1.SelectAll();\n                e.Cancel = true;\n            }\n            else {\n                textBox1.Text = value.ToString("X8");\n            }\n        }\n    }	0
6329531	5994052	DevExpress XtraTreeList Disable Node Editing	foreach(TreeListColumn  col in treeList.Columns)\n{\n   col.OptionsColumn.AllowEdit = false;\n   col.OptionsColumn.ReadOnly = true;\n}	0
16058101	15656774	How to display an image like popup from View	QRCodeEncoder encoder = new QRCodeEncoder();\nBitmap img = encoder.Encode(qrcode);\nstring path = Server.MapPath(@"/Images/QRCode.jpg");        \nimg.Save(path, ImageFormat.Jpeg);        \nreturn base.File(path,"image/jpeg","QRCode.jpg");	0
29751666	29751517	Attach a sql column value to the file name of a file that was written from another columns contents obtained from the same dataset	foreach (DataTable aDataTable in aDataSet.Tables)\n    {\n        for (int i = 0; i < aDataTable.Rows.Count; i++)\n        {\n          rtf = aDataTable.Rows[i]["interpretation_text_rtf"].ToString();\n          version = aDataTable.Rows[i]["version"].ToString();\n          File.WriteAllText(mPath + rtfFile + i + version +".rtf", rtf);\n        }\n    }	0
33608960	33608483	abstract class with multiple constructors in C#	public abstract class Command\n{\n    public Command() { }\n    public Command(string str)\n    {\n        FromString(str);\n    }\n    public abstract override string ToString();\n    public abstract void FromString(string str);\n}\npublic class NetCommand : Command\n{\n    public string details;\n    public NetCommand() {}\n    public NetCommand(string str) : base(str) { }\n    public override string ToString() { return details; }\n    public override void FromString(string str) { details = str; }\n}	0
8656093	8655980	How to receive a file over TCP which was sent using socket.FileSend Method	class Program\n{\n    static void Main()\n    {\n        var listener = new TcpListener(IPAddress.Loopback, 11000);\n        listener.Start();\n        while (true)\n        {\n            using (var client = listener.AcceptTcpClient())\n            using (var stream = client.GetStream())\n            using (var output = File.Create("result.dat"))\n            {\n                Console.WriteLine("Client connected. Starting to receive the file");\n\n                // read the file in chunks of 1KB\n                var buffer = new byte[1024];\n                int bytesRead;\n                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)\n                {\n                    output.Write(buffer, 0, bytesRead);\n                }\n            }\n        }\n\n    }\n}	0
17263584	17262860	List Disk Drives with their Driver in C#	private static string GetRealPath(string path)\n{\n\n   string realPath = path;\n   StringBuilder pathInformation = new StringBuilder(250);\n   string driveLetter = Path.GetPathRoot(realPath).Replace("\\", "");\n   QueryDosDevice(driveLetter, pathInformation, 250);\n\n   // If drive is substed, the result will be in the format of "\??\C:\RealPath\".\n\n      // Strip the \??\ prefix.\n      string realRoot = pathInformation.ToString().Remove(0, 4);\n\n      //Combine the paths.\n      realPath = Path.Combine(realRoot, realPath.Replace(Path.GetPathRoot(realPath), ""));\n\n\nreturn realPath;\n}\n\n\n[DllImport("kernel32.dll")]\nstatic extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);	0
2074341	2064143	Send MIME-encoded file as e-mail in C#	using Rebex.Net; // Smtp class\nusing Rebex.Mail; // contains the MailMessage and other classes \n\n// create an instance of MailMessage \nMailMessage message = new MailMessage();\n\n// load the message from a local disk file \nmessage.Load("c:\\message.eml");\n\nSmtp.Send(message, "smtp.example.org");	0
3846577	3846561	Command Line Parameters	foreach (string arg in Environment.GetCommandLineArgs())\n{\n    Console.WriteLine(arg);\n}	0
11560411	11560358	Modifying items in dictionary without affecting the original object	Dictionary<int, int> test2 = new Dictionary<int, int>(test);	0
2159152	2159091	Parsing of string for SQL DataType	string input = @"\n    Int NOT NULL\n    Int\n    VarChar(255)\n    VarChar(255) NOT NULL\n    Bit";\nforeach (Match m in Regex.Matches(input,\n    @"^\s*(?<datatype>\w+)(?:\((?<length>\d+)\))?(?<nullable> (?:NOT )?NULL)?",\n    RegexOptions.ECMAScript | RegexOptions.Multiline))\n{\n    Console.WriteLine(m.Groups[0].Value.Trim());\n    Console.WriteLine("\tdatatype: {0}", m.Groups["datatype"].Value);\n    Console.WriteLine("\tlength  : {0}", m.Groups["length"  ].Value);\n    Console.WriteLine("\tnullable: {0}", m.Groups["nullable"].Value);\n}	0
5891695	5891687	ASP.NET declaring array of Controls in CodeBehind not working	class MyPage : Page {\n\n    DropDownList[] dls;\n\n    protected void Page_Init(object sender, EventArgs e)\n    {\n        dls = new []{ Dl1, Dl2, Dl3 };\n    }\n    ...\n\n}	0
11953709	11953689	Converting DateTime to DateTime? causing error in asp.net	tboxDateOfBirth.Text = oCust.custDOB.HasValue? oCust.custDOB.Value.ToShortDateString() : string.Empty;	0
18232222	18231705	Adding Grids In codeBehind	Grid.SetRow(button, 1);\nGrid.SetColumn(button, 1);\nGrid.SetRowSpan(button, 2);\nGrid.SetColumnSpan(button, 2);\n\nmyGrid.ColumnDefinitions.Add(new ColumnDefinition());\nmyGrid.RowDefinitions.Add(new RowDefinition());	0
19243973	19243444	Passing a value on SelectedIndexChange	protected void ddlCompanyList_SelectedIndexChanged(object sender, EventArgs e)\n{\n    DropDownList ddl = sender as DropDownList;\n    string RSReportLinkID = ddl.SelectedValue;\n}	0
29550585	29550413	How to use view models for windows inside a DLL	public MyNamespace()\n {\n     InitializeComponents();\n     this.DataContext = new VmLocator();\n }	0
5016314	5012307	Convert Audio samples from bytes to complex numbers?	byte[] data = yourByteArray;\ndouble[] x = new double[data.Length];\nfor (int i = 0; i < x.Length; i++)\n{\n    x[i] = data[i] / 32768.0;\n}\nComplexNumber[] data = new ComplexNumber[length];\nfor (int i = 0; i < x.Length; i++)\n{\n    data[j] = new ComplexNumber(x[i]);\n}	0
24141785	24141692	Convert a foreach loop to LINQ	linesPassingThroughBeamEndsInYDirection.AddRange(\n   ModelBeams.SelectMany(beam => new [] {\n                                         beam.ConnectivityLine.I.Y, \n                                         beam.ConnectivityLine.J.Y}\n                        ));	0
3082816	3080619	SQLite Used to Populate a ListView in WPF C#	SQLiteConnection sql_con = new SQLiteConnection("data source=YOUR DATA SOURCE");\nsql_con.Open();\nSQLiteCommand sql_cmd = sql_con.CreateCommand();\nsql_cmd.CommandText = "SELECT * FROM table_name";\nSQLiteDataAdapter DB = new SQLiteDataAdapter(sql_cmd.CommandText, sql_con);\nDataSet DS = new DataSet();\nDB.Fill(DS);\nYourListView.DataContext = DS.Tables[0].DefaultView;	0
738219	724644	WindowsMobile: Application Exits after handling Exception from DialogForm	try {\n  // show Dialog that Throws\n}\ncatch (Exception ex) {\n  label1.Text = ex.Message;\n  Application.DoEvents();  // this solves it\n}	0
24021232	24020489	How not to continue a cancelled task?	// ContinueWith([NotNull] Action<Task> continuationAction)\n// WriteLine([NotNull] string format, object arg0)\n.ContinueWith(t => Console.WriteLine("Should not be executed. Task status = " + t.Status, TaskContinuationOptions.NotOnCanceled));\n\n// ContinueWith([NotNull] Action<Task> continuationAction, TaskContinuationOptions continuationOptions)\n// WriteLine(string value) \n.ContinueWith(t => Console.WriteLine("Should not be executed. Task status = " + t.Status), TaskContinuationOptions.NotOnCanceled);	0
3088331	3087934	Custom 400 redirect based on MVC Controller	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]\npublic class CustomAuthorizeAttribute : AuthorizeAttribute\n{\n    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n    {\n        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;\n        var actionName = filterContext.ActionDescriptor.ActionName;\n        // TODO: Now that you know the controller name and the action name\n        // act accordingly or call the base method\n    }\n}	0
12257718	12257417	How to display the result of adding two counters in sharepoint 2010 webpart?	c = a + b;\nLiteralControl totals = new LiteralControl(c.ToString());\nthis.Controls.Add(totals);	0
8533489	7048511	Mocking classes that implement IQueryable with Moq	public static class MockExtensions\n{\n    public static void SetupIQueryable<T>(this Mock<T> mock, IQueryable queryable)\n        where T: class, IQueryable\n    {\n        mock.Setup(r => r.GetEnumerator()).Returns(queryable.GetEnumerator());\n        mock.Setup(r => r.Provider).Returns(queryable.Provider);\n        mock.Setup(r => r.ElementType).Returns(queryable.ElementType);\n        mock.Setup(r => r.Expression).Returns(queryable.Expression);\n    }\n}	0
12876097	12876056	How do I detect if no selected item on ComboBox is chosen?	if( ComboBox.SelectedItem == null ) {\n   // do something\n}	0
5913514	5909957	facebook sdk invite friends to application	FB.init({ \n  appId:'YOUR_APP_ID', cookie:true, \n  status:true, xfbml:true \n});\n\nFB.ui({ method: 'apprequests', \n  message: 'Here is a new Requests dialog...'});	0
16934749	16800396	Interpret/parse Javascript Variables in c# with JInt or similar	ScriptEngine engine = new ScriptEngine();\n\nobject result = engine.Evaluate(scriptString);\n\nvar json = Jurassic.Library.JSONObject.Stringify(engine, result);	0
25270373	25260647	How to continuously bind to Chart	public partial class MyForm : Form\n{\n    Model _Model = new Model();\n\n    public MyForm()\n    {\n        InitializeComponent();\n\n        MyChart.Series.First().XValueMember = "X";\n        MyChart.Series.First().YValueMembers = "Y";\n\n        MyChart.DataSource = _Model.DoubleList;\n    }\n\n    private void button1_Click( object sender, EventArgs e )\n    {\n        _Model.UpdateModel( 4.0, 5.0, 6.0, 7.0 );\n        MyChart.DataBind();\n    }\n}	0
20729987	20729592	Change background color of all text boxes in single click function in Windows Phone 8	foreach (var elem in container.Children)\n{\n    if (elem is TextBox)\n    {\n        (elem as TextBox).Background = new SolidColorBrush(Colors.Red); \n    }\n}	0
1867510	1867498	Limit collection by enum using lambda	MyEnum type = MyEnum.ValueIWant;\nvar filtered = items.Where(p => p.Type == type);	0
4880695	4880012	Programtically Install Driver For MySQL Database	msiexec /package conector-net.msi /quiet	0
494402	122749	How to get rid of the "Console Root" node in a MMC 3.0 snapin?	New Window from Here	0
16358684	16358602	How to convert an object to a 2 dimension branched string array	object b;\nexample[,] r = (example[,])b;	0
20103391	20103127	Make property in parent object visible to any of its contained objects	public interface IInjectable {\n  ICancelStatus Status { get; }\n}\npublic interface ICancelStatus {\n  bool CancellationRequested { get; }\n}\npublic class CalculationManager {\n  private IInjectable _injectable;\n  private SubCalculation _sub;\n  public CalculationManager(IInjectable injectable) {\n    _injectable = injectable;\n    _sub = new SubCalculation(injectable);\n  }\n  public void Execute() {}\n}\npublic class SubCalculation {\n  private IInjectable _injectable;\n  public SubCalculation(IInjectable injectable) {\n    _injectable = injectable;\n  }\n}\nprivate class CancelStatus : ICancelStatus {\n  public bool CancellationRequested { get; set;}\n}\n\nvar status = new CancelStatus();\nvar manager = new CalculationManager(status);\nmanager.Execute();\n\n// once you set status.CancellationRequested it will be immediatly visible to all\n// classes into which you've injected the IInjectable instance	0
14698563	14698517	Downloading Variable FileNames with C# and RegEx	var client = new WebClient();\nvar r = new Regex("setup(.*?)exe");\nvar matches =\n  r.Matches(client.DownloadString(@"http://devbuilds.kaspersky-labs.com/devbuilds/AVPTool/avptool11/"));\nvar latest = matches.Cast<object>().ToList()\n             .Select(o => o.ToString())\n             .OrderByDescending(s => s)\n             .FirstOrDefault();	0
30045744	30045274	Get argument from registry C#	registryKey.SetValue("MobiCheckerTest", "\"" + Application.ExecutablePath + "\" autostart");	0
8148389	8148327	Clear current attachment's data and input new data everytime I send email	StreamWriter sw = new StreamWriter("Test.html", false, Encoding.UTF8);	0
33105637	33105372	Find lines that contains a specific string and randomly pick one in c#	string[] responseLines = System.IO.File.ReadAllLines(@"responses.txt");\nList<string> helloStrings = responseLines.Where<string>(str => str.StartsWith("[hello]")).Select(str => str.Replace("[hello]", "")).ToList<string>();\nList<string> goodByeStrings = responseLines.Where<string>(str => str.StartsWith("[goodbye]")).Select(str => str.Replace("[goodbye]", "")).ToList<string>();	0
13615275	13615019	Remove xmlns attribute with namespace prefix	xml.Attribute(XNamespace.Get("http://www.w3.org/2000/xmlns/") + "rd").Remove()	0
2284943	2284938	Are all disposable objects instantiated within a using block disposed?	[Test]\npublic void TestUsing()\n{\n    bool innerDisposed = false;\n    using (var conn = new SqlConnection())\n    {\n        var conn2 = new SqlConnection();\n        conn2.Disposed += (sender, e) => { innerDisposed = true; };\n    }\n\n    Assert.False(innerDisposed); // not disposed\n}\n\n[Test]\npublic void TestUsing2()\n{\n    bool innerDisposed = false;\n    using (SqlConnection conn = new SqlConnection(), conn2 = new SqlConnection())\n    {\n        conn2.Disposed += (sender, e) => { innerDisposed = true; };\n    }\n    Assert.True(innerDisposed); // disposed, of course\n}	0
31189617	31188876	String Approximation	var list = new[]\n    {\n        "0509000004", "0509000005", "0509000006", "0510000003", \n        "0311100000004000", "0311100000004020",\n        "063050000100", "06308C000400"\n    };\n\n\nvar results = new List<string>();\n\nList<Tuple<string, string>> regexes = new List<Tuple<string, string>>{\n    new Tuple<string, string>( "^0(5)(?:0(\\d)|(\\d{1,2}))0*(\\d*)", "$1$2$3$4"),\n    new Tuple<string, string>( "^(03111)(0+)([4]\\d{2})0$", "099$1$2$3"),\n};\n\nforeach (var number in list)\n{\n    foreach (var regex in regexes)\n    {\n        if (Regex.IsMatch(number, regex.Item1))\n        {\n            results.Add(Regex.Replace(number, regex.Item1, regex.Item2));\n            break;\n        }\n    }\n}	0
2204722	2204262	Asp.Net Mvc - Switch from Server to Ajax	public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)\n{\n    //you might have to customize this bit\n    if (controllerContext.HttpContext.Request.IsAjaxRequest())\n        return base.FindView(controllerContext, viewName, "Modal", useCache);\n\n    return base.FindView(controllerContext, viewName, "Site", useCache);\n}	0
31871776	31871607	how to access field values in a Item using sitecore Xpath Query	Item[] items = Sitecore.Context.Database.SelectItems(xpath);\n\nforeach(Item item in items )\n{\nvar richtextfield = item["field"]\n...\n\n}	0
5002291	5001863	Cache compile from Expression<Func<T>>	internal static class ExpressionCache<T>\n{\n    private static readonly Dictionary<Expression<Func<T>, Func<T>> Cache = new Dictionary<Expression<Func<T>, Func<T>>();\n\n    public static Func<T> CachedCompile(Expression<Func<T>> targetSelector)\n    {\n        Func<T> cachedFunc;\n        if (!Cache.TryGetValue(targetSelector, out cachedFunc))\n        {\n            cachedFunc = targetSelector.Compile();\n            Cache[targetSelector] = cachedFunc;\n        }\n\n        return cachedFunc;\n    }\n}	0
6371344	6371042	Refactoring Database with EntityFramework from code	var ctx = new FooStoreEntities();\nctx.Database.Initialize(true);	0
9386701	9386672	Finding the number of places after the decimal point of a Double	4.556499999999999772626324556767940521240234375	0
4818041	4817012	All Data have checkbox on Gridview for Delete	protected void btnDelete_Click(object sender, EventArgs e)\n{\n//Create String Collection to store \n//IDs of records to be deleted \n  StringCollection idCollection = new StringCollection();\n  string strID = string.Empty;\n\n  //Loop through GridView rows to find checked rows \n   for (int i = 0; i < GridView1.Rows.Count; i++)\n   {\n    CheckBox chkDelete = (CheckBox)\n       GridView1.Rows[i].Cells[0].FindControl("chkSelect");\n            if (chkDelete != null)\n            {\n                if (chkDelete.Checked)\n                {\n                 strID = GridView1.Rows[i].Cells[1].Text;\n                 idCollection.Add(strID);\n                }\n            }\n        }\n\n        //Call the method to Delete records \n        DeleteMultipleRecords(idCollection);\n\n        // rebind the GridView\n        GridView1.DataBind();\n    }	0
23997899	23997789	How do I remove version number from file path? - Winforms c#	get\n{\n    var dir = Directory.GetParent(Application.UserAppDataPath);\n    return Path.Combine(dir.FullName, "FileName.xml");\n}	0
5407645	5407440	Display all messageHeader's values	for (int i = 0; i < OperationContext.Current.IncomingMessageHeaders.Count; ++i)\n{\n    MessageHeaderInfo h = OperationContext.Current.IncomingMessageHeaders[i];\n    // for any reference parameters with the correct name & namespace\n    if (h.IsReferenceParameter && \n        h.Name == IDName && \n        h.Namespace == IDNamespace) \n    {\n        // read the value of that header\n        XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(i);\n        id = xr.ReadElementContentAsString();\n    }\n}	0
24568293	24562995	How to Rotate Shapes in C#	CompositeTransform co = new CompositeTransform();\n                    co.Rotation = -90;\n                    btn.RenderTransform = co;	0
9343411	9342816	make 24 bit color bitmap save in normal brightness level	void Main()\n    {\n        int rows = 100;\n        int columns = 100;\n\n        var random = new Random(DateTime.Now.Ticks.GetHashCode());\n\n        byte[] bytes = Enumerable\n            .Range(0, columns * rows)\n\n            // White\n            .SelectMany(i => new[] { (byte)0xFF, (byte)0xFF, (byte)0xFF, } )\n\n            // Random\n            /*.SelectMany(i => \n                {\n                    byte[] buffer = new byte[3];\n                    random.NextBytes(buffer);\n                    return buffer; \n                })*/\n\n            .ToArray();\n\n        using (var bm = Plot24(ref bytes, columns))\n        {\n            bm.Save(@"c:\test.bmp", ImageFormat.Bmp);\n        }\n    }\n\n    public static Bitmap Plot24(ref byte[] bufferArray, int columns)\n    {\n        int position = 0;      \n        int lengthOfBufferArray = bufferArray.Length;\n\n        int rows = (int)Math.Ceiling((double)lengthOfBufferArray / (3*columns) );\n        // ... the rest of your code is just fine	0
17722795	17721671	Looping to add to datagridview ends in out of range	List<int> list1 = new List<int>() { 1, 2, 3, 4 };\n            List<string> list2 = new List<string>() { "a", "b", "c", "d", "e" };\n            dataGridView1.AllowUserToAddRows = true;\n            dataGridView1.AutoGenerateColumns = false;\n            int myRow = -1;\n            int myCell = -1;\n            foreach (var i in list1)\n            {\n                myRow = myRow + 1;\n                foreach (var d in list2)\n                {\n                    myCell = myCell + 1;\n                    if(dataGridView1.Rows.Count==1)\n                        dataGridView1.Rows.Add(list1.Count);\n                    dataGridView1.Rows[myRow].Cells[myCell].Value = i + "and" + d;\n                }\n                myCell = -1;\n            }	0
321404	321370	How can I convert a hex string to a byte array?	public static byte[] StringToByteArray(string hex) {\n    return Enumerable.Range(0, hex.Length)\n                     .Where(x => x % 2 == 0)\n                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))\n                     .ToArray();\n}	0
16014926	16014839	PDF official paper format	Document doc = new Document(PageSize.A4);	0
9983690	9982014	How to prevent VS to set to 32ARGB the Bitmap from a 8 bpp original image	using System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.IO;\n...\n        Stream stream = new MemoryStream(Properties.Resources.marble8);\n        PngBitmapDecoder decoder = new PngBitmapDecoder(stream, \n            BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n        BitmapSource bitmapSource = decoder.Frames[0];	0
20990961	20990816	How to fix the width for each column in GridView?	we show only that long string which can be accommodated in column and then add "..." (only if string is more than what is showing) and then add a tooltip to show the full string.	0
8971684	8971492	How to remove special characters along with <br>	string str = Regex.Replace(abc, "[^(a-z)]|[^(A-Z)]|[\\)]", string.Empty);	0
14280153	14279665	How to deserialize to property by attribute name and inner xml	public class Employee\n{\n    [XmlAttribute("id")]\n    public string Id { get; set; }\n\n    [XmlElement("field")]\n    public List<Field> Fields { get; set; }\n\n    public string DisplayName \n    { \n        get \n        {\n            return Fields.Where(i => i.Id == "displayName").FirstOrDefault().Value;\n        } \n    }\n\n    public string Email\n    {\n        get\n        {\n            return Fields.Where(i => i.Id == "email").FirstOrDefault().Value;\n        }\n    }\n}\n\npublic class Field\n{\n    [XmlAttribute("id")]\n    public string Id { get; set; }\n\n    [XmlText]\n    public string Value { get; set; }\n}	0
20211581	20127256	Fetch group name with linq from regex matches	var source = "select * from people where id > 10";\n\nvar re = new Regex(@"\n    (?:\n    (?<reserved>select|from|where|and|or|null|is|not)|\n    (?<string>'[^']*')|\n    (?<number>\d+)|\n    (?<identifier>[a-z][a-z_0-9]+|\[[^\]]+\])|\n    (?:\s+)|\n    (?<operator><=|>=|<>|!=|\+|=|\(|\)|<|>|\*|,|.)|\n    (?<other>.*)\n    )+\n    ", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Compiled);\n\n(\n    from name \n    in re.GetGroupNames() \n    select new {name = name, captures = re.Match(source).Groups[name].Captures}\n)\n.Where (r => r.name != "0")\n.SelectMany (r => (\n    from Capture c \n    in r.captures \n    where c.Length > 0\n    select new {Type = r.name, Index = c.Index, Length = c.Length, Value = c.Value}\n    )\n).OrderBy (r => r.Index).ToList().Dump();	0
802494	802322	Wpf DataGrid : changing the XML field binding at runtime	public void ChangeColumnDefinitions ( IEnumerable<XmlGridColumnDefinition> columns )\n{\n    this.datagrid.Columns.Clear ();\n\n    foreach ( var column in columns )\n    {\n            DataGridTextColumn coldef = new DataGridTextColumn\n            {\n                    Header = column.Heading,\n                    Binding = new Binding ( string.Format ( "Element[{0}].Value", column.FieldName ) )\n            };\n\n            this.datagrid.Columns.Add ( coldef );\n    }\n}	0
30348440	30348225	Pass variable with onclick method in asp.net	protected void Page_Load(object sender, EventArgs e)\n        {\n            Button btn = new Button();\n            btn.Click += btn_Click;\n            btn.CommandArgument = "12"; //<-- you can pass argument like this\n            divUserUploadedList.Controls.Add(btn);\n\n        }\n\n        void btn_Click(object sender, EventArgs e)\n        {\n            Button btn = sender as Button;\n            string value = btn.CommandArgument;\n        }	0
1440911	1440884	PropertyGrid - Custom property names?	using System.ComponentModel;\n\n[Category("Test")]\n[DisplayName("Test Property")]\n[Description("This is the description that shows up")]\npublic string TestProperty {get;set;}	0
28874115	28852079	Autosize of TextFrame for a specific table cell in PowerPoint presentation programmatically	oShape.Table.Columns._Index(2).Width = 12;	0
20458163	20458116	Date will not go to Mysql database c#	da.InsertCommand.Parameters.Add("@Age", MySqlDbType.Int16).Value = Convert.ToInt32(petAge.Text);\nda.InsertCommand.Parameters.Add("@Bills", MySqlDbType.Int16).Value = Convert.ToInt32(petVet.Text);\nda.InsertCommand.Parameters.Add("@FoodCost", MySqlDbType.Int16).Value = Convert.ToInt32(petFood.Text);\nda.InsertCommand.Parameters.Add("@Weight", MySqlDbType.Int16).Value = Convert.ToInt32(petWeight.Text);\nda.InsertCommand.Parameters.Add("@DateAdopted", MySqlDbType.Int16).Value =Convert.ToInt32( petRescued.Text);\n\nda.InsertCommand.Parameters.AddWithValue("@species",petSpecies.SelectedValue);\nda.InsertCommand.Parameters.AddWithValue("@breed",petsBreed.SelectedValue);	0
15833451	15832944	exclude a part of an image by taking color	Bitmap.MakeTransparent()	0
18388583	18388452	Unable to access a file that was just created	if(!File.Exists(FilePath)){\n    File.Create(FilePath).Close();}\n    File.WriteAllText(FileText);	0
3345576	3345553	How do you convert 3 bytes into a 24 bit number in C#?	var num = data[0] + (data[1] << 8) + (data[2] << 16);	0
26466657	26466485	generic parameterised sql query with dapper	var list = conn.Query<T>(sproc, objectParams, commandType: CommandType.StoredProcedure);\n\nvar list = conn.Query<T>(sqlString, objectParams, commandType: CommandType.Text);	0
24029800	24029615	How can i manipulate the Font Properties in c# on a run time	Title title = Chart1.Titles.Add("Test");\n   title.Font = new System.Drawing.Font("Arial", 16, FontStyle.Bold);\n   title.ForeColor = System.Drawing.Color.FromArgb(0, 0, 205);	0
2711420	2711357	How to get last Friday of month(s) using .NET	List<DateTime> lastFridays = (from day in fridays\n                              where day.AddDays(7).Month != day.Month\n                              select day).ToList<DateTime>();	0
14587783	14586782	Dynamically creating WPF controls from XML and stacking them	public enum TestInput\n{\n    None,\n    Bool,\n    Text\n}\n\npublic abstract class TestRunnerBase\n{\n    public abstract TestInput TestInput { get; }\n    public bool BoolInput { get; set; }\n    public string TextInput { get; set; }\n    public abstract bool CanRun()\n    public abstract void Run();\n}\n\npublic class MainViewModel\n{\n    List<TestRunnerBase> Steps = new List<TestRunnerBase>();\n    public TestRunnerBase CurrentStep {get;set;};\n\n    public MainViewModel()\n    {\n        //loads the Steps\n        CurrentStep = Steps\n    }\n\n    public Command RunStepCommand\n    {\n        if (CurrentStep.CanRun())\n        {\n            CurrentStep.Run();\n            CurrentStep = Steps.Next(); //you get the idea\n        }\n    }\n}	0
873227	873222	Listbox data	listBox.Append(String.Replace("\r\n", ""));	0
2948745	2948722	Where will the file without path get created in client system	String[] lines = { "LAST MESSAGE", "101" };\nString fileName = Path.combine(System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory,"MPP_Config.txt");\nFile.WriteAllLines(fileName, lines);	0
10823970	10821556	How to arrange Thumbs with a Line in a WPF custom Adorner	protected override Size ArrangeOverride(Size finalSize)\n{\n    selectedLine = AdornedElement as Line;\n\n    double left = Math.Min(selectedLine.X1, selectedLine.X2);\n    double top = Math.Min(selectedLine.Y1, selectedLine.Y2);\n\n    var startRect = new Rect(selectedLine.X1 - (startThumb.Width / 2), selectedLine.Y1 - (startThumb.Width / 2), startThumb.Width, startThumb.Height);\n    startThumb.Arrange(startRect);\n\n    var endRect = new Rect(selectedLine.X2 - (endThumb.Width / 2), selectedLine.Y2 - (endThumb.Height / 2), endThumb.Width, endThumb.Height);\n    endThumb.Arrange(endRect);\n\n    return finalSize;\n}	0
11419920	11419635	Iterate through GridView Row with Labels	public static List<Label> FindLabelRecursive(Control root)\n{\n    List<Label> labels = new List<Label>();\n    if (root is Label)\n    {\n        labels.Add(root as Label);\n        return labels;\n    }\n\n    foreach(Control c in root.Controls)\n    {\n        if (c is Label)\n        {\n            labels.Add(c);\n        }\n        else\n        {\n            List<Label> childLabels = FindLabelRecursive(c);\n            labels.AddRange(childLabels);\n        }\n    }\n\n    return labels;\n}	0
10261639	10261607	Find a child node and get the value of it using a variable. Windows phone	var doc =\n            XDocument.Parse(\n                "<ArrayOfStop><Stop><StopName>Rajdutt Restaurant</StopName><route_stop /><route_stop_stop /><route_stop_timetable_stop /><stopId>6400</stopId></Stop><Stop><StopName>Cysleys Farm (by request only)</StopName><route_stop /><route_stop_stop /><route_stop_timetable_stop /><stopId>6401</stopId></Stop></ArrayOfStop>");\n\n        var list = (from item in doc.Descendants("Stop")\n                    where (string) item.Element("StopName") == "Cysleys Farm (by request only)"\n                    select (string)item.Element("stopId")).ToList();	0
9700236	9699357	How to pass system date and time to SQL Server database	using(SqlCommand newCmd = conn.CreateCommand())\n    {\n      newCmd.Connection = conn;\n      newCmd.CommandType = CommandType.Text;\n\n      DateTime now = DateTime.Now;\n      newCmd.CommandText = "INSERT INTO Candidates_ElecCenter(Cand_ID,Party_ID,Name,NIC,DistrictID,seat,year,Candidate_Type) VALUES (@Cand_ID,@Party_ID,@Name,@NIC,@DistrictID,@seat,@year,@Candidate_Type)";\n\n      newCmd.Parameters.AddWithValue("@Cand_ID", p);\n      newCmd.Parameters.AddWithValue("@Party_ID", p_2);\n      newCmd.Parameters.AddWithValue("@Name", p_3);\n      newCmd.Parameters.AddWithValue("@NIC", p_4);\n      newCmd.Parameters.AddWithValue("@DistrictID", p_5);\n      newCmd.Parameters.AddWithValue("@seat", p_6);\n      newCmd.Parameters.AddWithValue("@year", now);\n      newCmd.Parameters.AddWithValue("@Candidate_Type", sts);\n\n      newCmd.ExecuteNonQuery();\n    }	0
22782684	22782383	How can i get access to a tree view which is placed in a tab contol in c#	treeView1 = new TreeView()	0
8864574	8864408	Failed to save changes with EF DbContext	Patient.FirstVisit	0
12621922	12621256	Connect to open LDAP over ssl	connection.SessionOptions.VerifyServerCertificate =\n                new VerifyServerCertificateCallback((con, cer) => true);	0
9135884	9135825	SKIP reading first 150 row from flat file	using (StreamReader stream = new StreamReader(FileInfo.FullName)) \n{ \n    string line; \n    int i = 0;\n    while(!stream.EndOfStream) \n    { \n         i++;\n         line = stream.ReadLine();\n         if ( i <= 150 ) continue;\n\n         // Do something with the line. \n    }  \n}	0
18385147	18385100	How to get keys and values from a dictionary	Dictionary<DateTime, List<Double>> map;\nforeach (var pair in map) {\n  DateTime dt = pair.Key;\n  foreach (double value in pair.Value) {\n    // Now you have the DateTime and Double values\n  }\n}	0
12808196	12808160	C# How to upload file by http?	var client = new System.Net.WebClient();\nclient.UploadFile(address, filename);	0
13400150	13400066	Casting with a variable Type	var obj = Convert.ChangeType(d, items[items.Count() - 1].GetType());	0
10976461	10976367	How to call a webservice that wasn't developed in .NET	private const string BASE_URL = "http://www.earthtools.org/timezone";\nprivate const string REQUEST_URL_FORMAT = "{0}/{1}/{2}";\n\npublic timezone GetTimeZone(double latitude, double longitude)\n{\n    var uriString = String.Format(REQUEST_URL_FORMAT, BASE_URL, latitude, longitude);\n    var requestUri = new Uri(uriString);\n\n    var request = WebRequest.Create(requestUri);\n    using (var response = request.GetResponse())\n    {\n        using (var responseStream = response.GetResponseStream())\n        {\n            var ser = new XmlSerializer(typeof (timezone));\n            var result = (timezone) ser.Deserialize(responseStream);\n            return result;\n        }\n    }\n}	0
19786480	19786330	Get the files information	private void CalculateFiles()\n{\n    var builder = new StringBuilder();\n    var fileGroupByExtension = new DirectoryInfo(this.DirectoryPath)\n                                    .GetFiles(SearchPattern,SearchOption.AllDirectories)\n                                    .GroupBy(file => file.Extension)\n                                    .OrderBy(grp => grp.Key);\n    foreach (var grp in fileGroupByExtension)\n    {\n        var extension = grp.Key;\n        builder.Append(extension);\n        builder.Append(":");\n        builder.AppendLine();\n        foreach (var file in grp.OrderBy(file => file.Name))\n        {\n            builder.Append(file.Name);\n            builder.Append(" ....... ");\n            builder.Append(file.Length / 1000);\n            builder.Append("KB");\n            builder.AppendLine();\n        }\n    }\n    Console.Write(builder.ToString());\n}	0
10919062	10918849	Reading a deep level xml tag with C#	var d = (from s in myXel.Descendants("Dia") \n                 where s.Attribute("id").Value == dia.ToString()\n             select s).FirstOrDefault();\n\nvar rest = d.Descendants("Restriccion").ToList();	0
16638031	16626465	How do I show, then hide the AppBar after a page loads?	private async void DelayedAppBarHide()\n    {\n        await Task.Delay(1000);\n        this.TopAppBar.IsOpen = true;\n        await Task.Delay(3000);\n        this.TopAppBar.IsOpen = false;\n\n    }	0
15992949	15992292	Is the current page the child of a directory	var pageUri  = new Uri("http://www.domain.com/directory/page.aspx");\nvar pageName = pageUri.Segments[pageUri.Segments.Length - 1];	0
30165354	30165019	c# write xml muitiable atrrtibutes	XDocument doc = new XDocument(\n    new XElement("Project ",\n        new XAttribute("Title", "old one"),\n        new XAttribute("Version", "1.5.1.0"),\n        new XAttribute("Author", ""),\n        new XAttribute("EmphasisColor1Label", ""),\n        new XAttribute("EmphasisColor1", "#000000"),\n        new XAttribute("EmphasisStyle1", "")\n    )\n);\ndoc.Save("Project.xml");	0
4717826	4717470	MEF WPF application with separate assemblies and loading controls	public IExtDialogFactory ExtDialogFactory { get; set; }\n\npublic interface IExtDialogFactory\n{\n    UserControl CreateDialog(); \n}	0
15368119	15368036	Understanding datetime conversion	string sql = "SELECT * FROM tableX WHERE memberJoined between @startDate AND @endDate";\nSqlCommand command = new SqlCommand(sql);\nSqlParameter startParam = command.Parameters.Add("@startDate", System.Data.SqlDbType.DateTime);\nstartParameter.Value = //Some date time object\nSqlParameter endParam = command.Parameters.Add("@startDate", System.Data.SqlDbType.DateTime);\nendParameter.Value = //Some date time object	0
16111156	16111009	(C#) Reading a part of a line	using System;\nusing System.IO;\n\nclass Test\n{\n    public static void Main()\n    {\n            try\n            {\n                using (StreamReader sr = new StreamReader("TestFile.txt"))\n                {\n                    while (!sr.EndOfStream)\n                    {\n                        String line = sr.ReadLine();\n                        if (line != null && line.Contains(":"))\n                            Console.WriteLine(line.Split(':')[1]);\n                    }\n                }\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine("The file could not be read:");\n                Console.WriteLine(e.Message);\n            }\n    }\n}	0
21921534	21921264	Unit testing - database data	interface DataSource {\n   List<String> GetData();\n}\n\nclass Manipulator {\n private DataSource _source;\n\n public Manipulator(){ }\n\n public Manipulator(DataSource d) { _source = d; }\n\n pubic void ManipulateData(){\n    var data = _source.GetData();\n\n    // Do something with the data\n }\n}	0
3717196	3717121	How to create a XML with a Specific Encoding using XSLT and XMLWRITER	using (XmlReader xReader = XmlReader.Create("Source.xml"))\nusing (XmlWriter xWriter = XmlWriter.Create("Target.xml", xwrSettings)) {\n    xslt.Transform(xReader, xWriter);\n}\n// your file is now written	0
19478652	15475183	Decorating an enum on the EF object model with a Description attribute?	public static string Description(this PrivacyLevel level) {\n  switch (level) {\n    case PrivacyLevel.Public:\n      return Resources.PrivacyPublic;\n    case PrivacyLevel.FriendsOnly:\n      return Resources.PrivacyFriendsOnly;\n    case PrivacyLevel.Private:\n      return Resources.PrivacyPrivate;\n    default:\n      throw new ArgumentOutOfRangeException("level");\n  }\n}	0
13348943	13316412	read column names from sqlite table windows 8 app	// read column names\n           var query = await db.QueryAsync<table_info_record>("PRAGMA table_info(MY_TABLE_NAME_HERE)");\n\n            foreach (var item in query)\n            {\n                Debug.WriteLine(string.Format("{0}", item.name) + " is a column.");\n            }	0
23178301	23108505	How to resolve InstancePerHttpRequest?	using Autofac.Integration.Mvc;	0
30907485	30907334	Find a fixed length string with specific string part in C#	List<string> sList = new List<string>(){"AB012345",\n            "AB12345",\n            "AB123456",\n            "AB1234567",\n            "AB98765",\n            "AB987654"};\n\nvar qry = sList.Where(s=>Regex.Match(s, @"^AB\d{6}$").Success);	0
14354451	14354324	Get the value of each field that updated in updating operation	FOR UPDATE TRIGGER	0
13824374	13822925	Custom ComboBox Column for DataGridView	private void dgTest_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n        {\n            if (dgTest.CurrentCell.ColumnIndex == 0) // Which column ever is your DataGridComboBoxColumn\n            {\n                // This line will enable you to use the DataDridViewCOmboBox like your\n                // Custom ComboBox.\n                CustomComboBox combo = e.Control as CUstomComboBox;\n\n            }\n        }	0
12812476	12812381	Reading specific text from XML files	XElement doc = XElement.Load(fi.FullName);\n\n//count of specific XML tags\nint XmlTagCount=doc.Descendants().Elements(txtSearchTag.Text).Count();\n\n//count particular text\n\nint particularTextCount=doc.Descendants().Elements().Where(x=>x.Value=="text2search").Count();	0
25127804	25124552	Replace default IdentityDbContext with existing database information	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    base.OnModelCreating(modelBuilder);\n\n    var user = modelBuilder.Entity<IdentityUser>().HasKey(u => u.Id).ToTable("User", "Users"); //Specify our our own table names instead of the defaults\n\n    user.Property(iu => iu.Id).HasColumnName("Id");\n    user.Property(iu => iu.UserName).HasColumnName("UserName");\n    user.Property(iu => iu.Email).HasColumnName("EmailAddress").HasMaxLength(254).IsRequired();\n    user.Property(iu => iu.IsConfirmed).HasColumnName("EmailConfirmed");\n    user.Property(iu => iu.PasswordHash).HasColumnName("PasswordHash");\n    user.Property(iu => iu.SecurityStamp).HasColumnName("SecurityStamp");\n\n    user.HasMany(u => u.Roles).WithRequired().HasForeignKey(ur => ur.UserId);\n    user.HasMany(u => u.Claims).WithRequired().HasForeignKey(uc => uc.UserId);\n    user.HasMany(u => u.Logins).WithRequired().HasForeignKey(ul => ul.UserId);\n    user.Property(u => u.UserName).IsRequired();\n...	0
8285774	8285609	name of assoc-diff in C#	var results = list1.GroupBy(p => p).Select(p => new { item = p.Key, count = p.Count() })\n                .Concat(list2.GroupBy(p => p).Select(p => new { item = p.Key, count = -p.Count() }))\n                .GroupBy(p => p.item).Select(p => new { item = p.Key, count = p.Sum(q => q.count) })\n                .Where(p => p.count > 0)\n                .SelectMany(p => Enumerable.Repeat(p.item, p.count));	0
4097728	4097682	c# use reflection to get a private member variable from a derived class	// _commandCollection is an instance, private member\nBindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;\n\n// Retrieve a FieldInfo instance corresponding to the field\nFieldInfo field = GetType().GetField("_commandCollection", flags);\n\n// Retrieve the value of the field, and cast as necessary\nIDbCommand[] cc =(IDbCommand[])field.GetValue(this);	0
4236978	4236195	Tutorial to create PieChart with compact framework	System.Drawing	0
7870598	7870583	how can you format just the time of a DateTime object in C#	yourDateTimeVariable.ToString("h:mm tt");	0
10227262	10226975	Enumerate over time zones on a Windows Mobile device	var col = new TimeZoneCollection();\ncol.Initialize();\n\nforeach (var timeZone in col)\n{\n  string name = timeZone.DisplayName;\n  // ...\n}	0
3213870	3213819	String woes in C# - having a . next to a "	string text = String.Format("<a href='http://raustdsx0700.real.local:7782/analytics/saw.dll?PortalPages&PortalPath={0}&Page={1}&P0=1&P1=eq&P2=Project.\"Project Name\"'' target='_blank'>{1}</a><br/><br/>",dashboardURL,reportName);	0
15367664	15367615	Find max and min DateTime in Linq group	var tsHeadg = \n    (from h in tsHead\n     group h by h.Index into g //Pull out the unique indexes\n     let f = g.FirstOrDefault() \n     where f != null\n     select new\n     {\n         f.Index,\n         f.TimeSheetCategory,\n         f.Date,\n         f.EmployeeNo,\n         f.Factory,\n         MinDate = g.Min(c => c.StartTime),\n         MaxDate = g.Max(c => c.FinishTime),\n     });	0
3623109	3623066	C#: How to detect which textbox value is equal to, or the closest to zero of a group of textboxes/values?	Func<string, bool> isDecimal = s => { decimal temp; return decimal.TryParse(s, out temp);};\nTextBox closestToZero =\n    (from tb in this.Controls.OfType<TextBox>()\n        where isDecimal(tb.Text)\n        orderby Math.Abs(decimal.Parse(tb.Text))\n        select tb)\n        .FirstOrDefault();\n\nif (closestToZero != null)\n    MessageBox.Show(closestToZero.Text);	0
19797536	19797408	Sorting rows in datatable	var sortedTableQuery = table.OrderBy(r => r["NomArtiste"].ToString() == lastName ? 0 : 1).ThenBy(r => r["PrenomArtiste"].ToString() == firstName ? 0 : 1).ThenBy(r => r["NomArtiste"].ToString()).ThenBy(r => r["PrenomArtiste"].ToString());\nvar a = sortedTableQuery.ToArray();	0
14098368	14051948	How to display Error message into chart in asp chart controls	protected void ChartExample_DataBound(object sender, EventArgs e)\n{\n    // If there is no data in the series, show a text annotation\n    if(ChartExample.Series[0].Points.Count == 0)\n    {\n        System.Web.UI.DataVisualization.Charting.TextAnnotation annotation = \n            new System.Web.UI.DataVisualization.Charting.TextAnnotation();\n        annotation.Text = "No data for this period";\n        annotation.X = 5;\n        annotation.Y = 5;\n        annotation.Font = new System.Drawing.Font("Arial", 12);\n        annotation.ForeColor = System.Drawing.Color.Red;\n        ChartExample.Annotations.Add(annotation);\n    }\n}	0
31191218	31190540	Winform repaint at 5 seconds	void timer_Tick(object sender, EventArgs e)\n{\n     this.invalidate();\n}	0
11815619	11815599	Format any number to three digits?	int iVal = 1;\n\niVal.ToString("D3")); // = "001"	0
4026470	4026268	date difference in EF4	var before = DateTime.Now.AddDays(-90);\nvar persons = context.Persons.Where(x => x.CreateDT > before);	0
16841396	16803099	Facebook SDK for .NET - Search keywords in public posts	var client = new FacebookClient();\n            string searchKeyword = keyWord;\n            dynamic result = client.Get("/search?q=" + searchKeyword + "&type=post");	0
26183017	26182859	Parsing a SQL Server query without executing the query against a database connection	Microsoft.SqlServer.Management.SqlParser.Parser.Parse()	0
16207355	16146423	Dynamic Data IObjectContextAdapter missing reference	using System.Data.Entity.Infrastructure;	0
33213260	33213182	Fluent nhibernate map multiple tables	public UserEntityMap : ClassMap<UserEntity>\n{\n   //Other properties\n   HasMany(x => x.Addresses)\n       .KeyColumn("User_id").Fetch.Join()\n       .BatchSize(100);\n   HasMany(x => x.Roles)\n       .KeyColumn("User_id").Fetch.Join()\n       .BatchSize(100);\n}	0
13541763	13541618	parameterized strategy pattern in MEF	interface IAlgorithm\n{\n    string AlgorithmName {get;}\n    void Execute(string paramA, int paramB);\n}\n\nalgorithm.Execute(stringParam, intParam);	0
23082351	23082263	Getting a list of files in order of the last 10 characters	.OrderBy(f => f.FullName.Substring(f.FullName.Length - 10, 8));	0
20242199	20241732	C# SQL string formatting	SqlConnection conn = new SqlConnection("YourConnectionString");\nSqlCommand cmd = new SqlCommand(@"select * from Users where role='member' and\nSUBSTRinG(lname, 1, 1) = @query ORDER BY lname ASC");\n\ncmd.Parameters.AddWithValue("@query", querystring);\n\nDataTable resultTable = new DataTable();\n\ntry\n{\n  SqlDataAdapter da = new SqlDataAdapter(cmd);\n  da.Fill(resultTable);\n} finally {\n  if (conn.State != ConnectionState.Closed) conn.Close();\n}\n\nConsole.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));	0
11512973	11214033	Move a button's location after it is already drawn	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;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n\n            button1.Location = new Point(40, 40);\n        }\n    }\n}	0
10018103	10017967	Wpf change application variable	Resources["Item1"] = "This is a test";\n    String t = (string)this.TryFindResource("Item1");\n    MessageBox.Show(t);	0
10373140	10373064	sync custom control and richtextbox C#	class HexBox : UserControl{\n\n   // .. \n}\n\npublic class MyForm :Form{\n  public MyForm(){\n    HexBox hexBox = new HexBox();\n    Controls.Add(hexBox);\n    hexBox.MouseDown += (sender, args) =>{\n       // call your scroll to function \n    };\n\n    InitializeComponent();\n\n  }\n}	0
4147132	4146877	How do I get an IL bytearray from a DynamicMethod?	using System.Linq.Expressions;\nusing System.Reflection;\nusing System.Reflection.Emit;\n...\n\n        var mtype = compiled.Method.GetType();\n        var fiOwner = mtype.GetField("m_owner", BindingFlags.Instance | BindingFlags.NonPublic);\n        var dynMethod = fiOwner.GetValue(compiled.Method) as DynamicMethod;\n        var ilgen = dynMethod.GetILGenerator();\n        var fiBytes = ilgen.GetType().GetField("m_ILStream", BindingFlags.Instance | BindingFlags.NonPublic);\n        var fiLength = ilgen.GetType().GetField("m_length", BindingFlags.Instance | BindingFlags.NonPublic);\n        byte[] il = fiBytes.GetValue(ilgen) as byte[];\n        int cnt = (int)fiLength.GetValue(ilgen);\n        // Dump <cnt> bytes from <il>\n        //...	0
24076034	24075892	How to bind a request model in WebAPI GET request with route attribute?	[Route("{UserId}/{Category}/books/{BookType}/{Page}")]\n            [HttpGet]\n            [RequestAuthorization]\n             public Response Get(([FromUri] BookbRequestModel book )\n            {          \n                var books= this.contentService.GetUserItems(book.UserId,book.Category,book.BookType,book.Page)\n                return new Response() { Status = ApiStatusCode.Ok, Books = books};\n            }	0
7972185	7969063	Get EXIF tags in Windows Phone 7	Artist  ""\nCopyright   null\nDateTime    "2011:11:01 20:50:07"\nDescription null\nExposureTime    0.0\nFileName    "\\Applications\\Data\\[GUID]\\Data\\PlatformData\\CameraCapture-[GUID].jpg.jpg"\nFileSize    789355\nFlash   No\nFNumber 0.0\nGpsLatitude {double[3]}\nGpsLatitudeRef  Unknown\nGpsLongitude    {double[3]}\nGpsLongitudeRef Unknown\nHeight  1944\nIsColor true\nIsValid true\nLoadTime    {00:00:00.1340000}\nMake    "HTC"\nModel   "7 Trophy"\nOrientation TopRight\nResolutionUnit  Inch\nSoftware    "Windows Phone 7.5"\nThumbnailData   {byte[14913]}\nThumbnailOffset 518\nThumbnailSize   14913\nUserComment null\nWidth   2592\nXResolution 72.0\nYResolution 72.0	0
33767596	33756767	Entity Framework updating many to many	public virtual void Update(T entity)\n        {\n            DbEntityEntry dbEntityEntry = DbContext.Entry(entity);\n\n            if (dbEntityEntry.State == EntityState.Detached)\n            {\n                var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);//assuming Id is the key column\n                var set = DbContext.Set<T>();\n                T attachedEntity = set.Find(pkey);\n                if (attachedEntity != null)\n                {\n                    var attachedEntry = DbContext.Entry(attachedEntity);\n                    attachedEntry.CurrentValues.SetValues(entity);\n                }                    \n            }                \n        }	0
31189509	31189352	How to merge values of rows from a multiple column list in c#?	var resultsById = new Dictionary<string, ResultClass>();\n\nforeach (DataRow row in dt.Rows)\n{\n    var id = row["emplid"].ToString().Trim();\n\n    ResultClass result;\n\n    if (!resultsById.TryGetValue(id, out result))\n    {\n        result = new ResultClass\n        {\n            employeeId = id\n        };\n        resultsById.Add(id, result);\n    }\n\n    if (row["selectedId"] != DBNull.Value)\n    {\n        result.isCheckbox1 |= (int) row["selectedId"] == 1;\n        result.isCheckbox2 |= (int) row["selectedId"] == 2;\n    }            \n}\n\nreturn resultsById.Values;	0
32419677	32418982	WPF - how to do binding the right way for a particular scenario?	INotifyPropertyChanged.PropertyChanged	0
19735975	19735459	How to merge files to single executable or decrease the number of distributed files	public partial class App : Application\n{\n    public App()\n    {\n        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n    }\n    static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n    {\n        var dllName = new AssemblyName(args.Name).Name + ".dll";\n        var execAsm = Assembly.GetExecutingAssembly();\n        var resourceName = execAsm.GetManifestResourceNames().FirstOrDefault(s => s.EndsWith(dllName));\n        if (resourceName == null) return null;\n        using (var stream = execAsm.GetManifestResourceStream(resourceName))\n        {\n            var assbebmlyBytes = new byte[stream.Length];\n            stream.Read(assbebmlyBytes, 0, assbebmlyBytes.Length);\n            return Assembly.Load(assbebmlyBytes);\n        }\n\n    }\n}	0
2872673	2872653	troubles creating a List of doubles from a list of objects	var tmp = from n in e.Result select new{Value = Convert.ToDouble ( n.Sales) };	0
24065091	23999052	Convert decimal to 10-digit number	int wholeVal = (int)amount;  //"amount" is a double & the original value from the textbox.  Counvert it to an int\nint wholeValLength = wholeVal.ToString().Replace(",", "").Length;  //get the length of int\nstring calculation = "1";  //number to calculate begins with 1\nfor (int i = wholeValLength; i < 10; ++i)\n{\n     //add zeros to the calculation value\n     calculation += "0";  \n}\ndouble dblCalculation = Convert.ToDouble(calculation);  \nledgerAmount = amount * dblCalculation;  //perform calculation	0
23512451	23512393	QueryString - Display all entries when parameter isn't specified	...    \nselectcommand="SELECT uname, uimg\n                FROM games \n                INNER JOIN categories_games\n                ON games.uid = categories_games.uid\n                INNER JOIN consoles_games\n                ON games.uid = consoles_games.uid\n                WHERE consoleid = 2\n                AND (categoryid = @categoryid OR @categoryid IS NULL)"\n\nCancelSelectOnNullParameter="false">	0
18220967	18220787	Deleting xml:base attribute from an XDocument	currentDoc.Root.Attributes(XNamespace.Xml + "base").Remove();	0
28904098	28903493	Use lambda expression to retrieve object array a field collection	List<int> result = myList.Select(x=>x.fld1).ToList();	0
14339682	14339394	How to refresh a datagrid Items automatically when the ItemsSource is updated on the sql server	// Background timer used to refresh...\nprivate DispatcherTimer _timer = null;\n\npublic MainViewModel()\n{\n    // Do initial load\n    initializeload();\n\n    // Start the timer to refresh every 100ms thereafter (change as required)\n    _timer = new DispatcherTimer();\n    _timer.Tick += Each_Tick;\n    _timer.Interval = new TimeSpan(0, 0, 0, 0, 100);\n    _timer.Start(); \n}\n\n// Raised every time the timer goes off\nprivate void Each_Tick(object o, EventArgs sender)\n{\n    // Refresh from database etc ...\n    initializeload();\n\n    // Anything else you need ...\n}\n\nprivate void initializeload()\n{\n    // Your existing code here ...\n}	0
22242083	22241467	Using a custom authorization attribute within a function	if(User.IsInRole(oRoles.PageAdmin) || User.IsInRole(oRoles.Super))\n  return RedirectToAction("Admin","PageEditor");	0
24359793	24359275	read corrupt excell-file with NPOI	private static void HTMLtoExcel(string fileName) //atm, reads the first cell value.\n{\n    string text = File.ReadAllText(fileName);\n    DataTable dt = new DataTable();\n    string insert;\n    int start = text.IndexOf("<td>");\n    int stop = text.IndexOf("</td>");\n    insert = text.Substring(start, stop - start);\n    insert = insert.Remove(0, 4);\n    Console.WriteLine(insert);\n}	0
8189391	8189359	How to access ENUM which is declared in a separate class - C#	EmployeeFactory.EmployeeType.ProgrammerType	0
21247681	21246861	how to get value of dropdownlist of a gridview?	protected void DropDownList1_onload(object sender, EventArgs e)\n{\n    //SAVE SELECTED\n    string selected = "";\n    if(DropDownList1.Items.Count > 0 && DropDownList1.SelectedIndex != 0)\n    {\n         selected = DropDownList1.SelectedValue;\n     }\n    //UPDATE\n    SqlConnection cn = new System.Data.SqlClient.SqlConnection("Data Source=CHANGEME1;Initial Catalog=Reflection;Integrated Security=True");\n    SqlDataAdapter da = new SqlDataAdapter("select salary from employee", cn);\n    DataSet ds = new DataSet();\n    var ddl = (DropDownList)sender;\n    da.Fill(ds);\n    cn.Close();\n    ddl.DataSource = ds;\n    ddl.DataTextField = "salary";\n    ddl.DataValueField = "salary";\n    ddl.DataBind();\n    ddl.Items.Insert(0, new ListItem("--Select--", "0"));\n    //RESELECT\n    if(!String.IsNullOrEmpty(selected))\n    {\n         DropDownList1.SelectedValue = selected;\n    }\n}	0
24482897	24482853	how to Copy listView selected items into an array	var myList = new List<string>();\nforeach(ListViewItem Item in ListView.SelectedItems)\n{\n   myList.add(Item.Text.ToString());\n}\nvar myArray = myList.ToArray();	0
10568853	10206615	ServiceNow XML Web Service - node naming	/xml/incident[sys_id='my GUID']	0
609842	595640	VS2005: How to automatically generate a build number with date?	case IncrementMethod.YearAndDay:\n{\n    DateTime dDate = DateTime.Now;\n    long buildNumber = dDate.Year % 2000 * 1000;\n    buildNumber += dDate.DayOfYear;\n    string newVersionNumber = buildNumber.ToString();\n    Log.LogMessage(MessageImportance.Low, logMessage, newVersionNumber);\n    return newVersionNumber;\n}	0
24949512	24819752	Export(backup) website\app using msdeploy api c#	var deployBaseOptions = new DeploymentBaseOptions\n{\n    ComputerName = @"https://WIN-CCCCWWWWXXX:8172/msdeploy.axd",\n    UserName = @"WIN-CCCCWWWWXXX\User",\n    Password = "123456",\n    AuthenticationType = "Basic"\n};\n\n// Allow sertification\nServicePointManager.ServerCertificateValidationCallback = (s, c, chain, err) => true;\n\nvar providerOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.IisApp)\n{\n    Path = "MyWebSite"\n};\n\nvar deploymentObject = DeploymentManager.CreateObject(providerOptions, deployBaseOptions);\ndeploymentObject.SyncTo(DeploymentWellKnownProvider.Package, "C:\\backup_app.zip", \n               deployBaseOptions, new DeploymentSyncOptions());	0
18268737	18267392	Get hidden value from wpf datagrid	if (dgUserEnroll.SelectedItem != null)\n{\n  var data = (User)dgUserEnroll.SelectedItem;\n  var userID = data.UserId;\n }	0
9959555	9959535	Reading Numbers From Text	string outputDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\nstring fileName = Path.Combine(outputDirectory, "numbers.txt");\nstring numbers = File.ReadAllText(fileName);	0
33110232	30273731	C# Can I take screenshot of everything below active window	CopyFromScreenAtDepth()	0
6439908	6439826	How to close Find window in a webbrowser control	webBrowser1.Select();\n        SendKeys.Send("^f");\n        SendKeys.Send("{ESCAPE}");	0
19905857	19877803	Win 8.1 ScrollViewer issues with a GridView	FrameworkElement focusedElement = FocusManager.GetFocusedElement() as FrameworkElement;\n        GeneralTransform focusedVisualTransform = parent.TransformToVisual(_scrollViewer);\n\nApplyHorizontalScrolling(focusedElement, focusedVisualTransform);\n\n  private void ApplyHorizontalScrolling(FrameworkElement focusedElement, GeneralTransform focusedVisualTransform)\n    {\n        Rect rectangle = focusedVisualTransform.TransformBounds(new Rect(new Point(focusedElement.Margin.Left, focusedElement.Margin.Top), focusedElement.RenderSize));\n        double horizontalOffset = _scrollViewer.HorizontalOffset + (rectangle.Left);\n        _scrollViewer.ChangeView(horizontalOffset, 0, _scrollViewer.ZoomFactor);\n    }	0
26201969	26201952	selecting distinct elements from two lists using LINQ?	lst1.AddRange(lst2);\nList<int> lst3  = lst1.Distinct().ToList();	0
6811895	6811834	Table with 2 foreign keys entity framework	User user = context.Users.Where(u => u.Id == 1);\nProduct product = context.Products.Where(p => p.Id == 1);\nuser.Products.Add(product);\ncontext.SaveChanges();	0
14787373	14787189	How to show error message on client side when press delete button without selecting checkbox	protected void Button2_Click(object sender, EventArgs e)\n {\n    var dt = (DataTable)ViewState["CurrentData"];\n\n    if (dt == null)\n    {\n        return;\n    }\n\n    foreach (GridViewRow row in GridView1.Rows)\n    {\n        CheckBox cb = (CheckBox)row.FindControl("CheckBox2");\n        if (cb != null && cb.Checked)\n        {\n            Label1.Visible = false;\n            dt.Rows.RemoveAt(row.RowIndex);\n            GridView1.DataSource = dt;\n            GridView1.DataBind();\n\n            GridView2.DataSource = dt;\n            GridView2.DataBind();\n\n            ViewState["CurrentData"] = dt;\n        }\n        else if (cb.Checked == false)\n        {\n            Label1.Visible = true;\n        }\n    }\n\n}	0
8445143	8445096	Translating 'New' arrays from VB.Net to C#	// Typed implicitly (type inferred by compiler).\nClients.Applicants = new[] { new Applicant(), ... };\n\n// Typed explicitly.\nClients.Applicants = new Applicant[] { new Applicant(), ... };	0
12001844	12001450	How can we integrate our windows Phone 7 apps for posting data on Google Plus Wall?	Note: The Google+ API currently provides read-only access to public data.\nAll API calls require either an OAuth 2.0 token or an API key.	0
14208370	14207467	How to read width and height of PICT image files?	[Platform Header] - 512 byte\n[File Size] - short\n[Image Top Left x] - short\n[Image Top Left y] - short\n[Image Bottom Right x] - short\n[Image Bottom Right y] - short	0
5302529	5302496	How can I get the main form of a .NET 4 application to come to the front?	Form frm = null\nprivate void button1_Click(object sender, EventArgs e)\n        {\n            frm = new Form2();\n            frm.Show();\n        }\n\n// Minimize issue is handled\n    private void Form1_Resize(object sender, EventArgs e)\n            {\n                if (this.WindowState == FormWindowState.Minimized)\n                {\n                    frm.WindowState = this.WindowState;\n                }\n            }	0
12713312	12712761	Deserializaion from Xml in C#	List<row1> row1 = xDoc.Descendants("row1")\n                .Select(x => new row1() { ing = x.Element("ing").Value })\n                .ToList();\n\nList<row> row = xDoc.Descendants("row")\n                    .Select(x => new row() { \n                        name = x.Element("name").Value,\n                        ID = x.Element("ID").Value \n                    })\n                    .ToList();	0
3819468	3819451	Unit Testing - How to Compare Two Paged Collections To Assert All Items Different?	Assert.IsFalse(postsPageOne.Intersect(postsPageTwo).Any());	0
11223688	11223664	How can I get the namespace from a generic type?	typeof(T).FullName	0
29917352	29916820	Implicit conversion from lambda expression to user-defined type	var func = (i, j) => i + j;	0
4604631	4604461	c# DateTime to Add/Subtract Working Days	public static class DateTimeExtensions\n{\n    public static DateTime AddWorkdays(this DateTime originalDate, int workDays)\n    {\n        DateTime tmpDate = originalDate;\n        while (workDays > 0)\n        {\n            tmpDate = tmpDate.AddDays(1);\n            if (tmpDate.DayOfWeek < DayOfWeek.Saturday && \n                tmpDate.DayOfWeek > DayOfWeek.Sunday &&\n                !tmpDate.IsHoliday())\n                workDays--;\n        }\n        return tmpDate;\n    }\n\n    public static bool IsHoliday(this DateTime originalDate)\n    {\n        // INSERT YOUR HOlIDAY-CODE HERE!\n        return false;\n    }\n}	0
30164396	30160255	log4net cross platform XML config	XmlConfigurator.Configure();\nif (Environment.OSVersion.Platform == PlatformID.Unix){\n        var repository = LogManager.GetRepository() as Hierarchy;\n        if (repository != null)\n        {\n            var appenders = repository.GetAppenders();\n            if (appenders != null)\n            {\n                foreach (var appender in appenders)\n                {\n                    if (appender is FileAppender)\n                    {\n                        var fileLogAppender = appender as FileAppender;\n                        fileLogAppender.File = fileLogAppender.File.Replace (@"\", Path.DirectorySeparatorChar.ToString ());\n                        fileLogAppender.ActivateOptions ();\n                    }\n                }\n            }\n        }\n}	0
6393248	6393040	How do I change what appears when right clicking in a rich text box in C#?	ContextMenu contextMenu = \n        new System.Windows.Forms.ContextMenu (\n           new [] {\n             new MenuItem ("Entry1", ContextMenuItem_Click),\n             new MenuItem ("Copy", ContextMenuItem_Click)\n           });\n     RichTextBox rtb = \n       new RichTextBox\n         {\n            Size = ClientSize,\n            Parent = this,\n            ContextMenu = contextMenu\n         };	0
33495255	33494005	asp:CheckBoxList with parents	treeView.CheckBoxes = true	0
11831106	11831043	Including library while accessing complier via console interface	/r:System.Numerics.dll	0
8414517	8413922	Programmatically determining Mono runtime version	Type type = Type.GetType("Mono.Runtime");\nif (type != null)\n{\n    MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);\n    if (displayName != null)\n        Console.WriteLine(displayName.Invoke(null, null));\n}	0
21732232	21732128	Is there a way to organise an IEnumerable into batches in column-major format using Linq?	int[] arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };\nint i=0;\nvar result = arr.GroupBy(x => i++ % 3).Select(g => g.ToList()).ToList();	0
23447715	23447551	how to obtain access to the (child) controls in webusercontrol	public string TextboxValue\n{\n    get { return txtMyText.Text; }\n    set { txtMyText.Text= value; }\n}	0
2196616	2196602	regex for formatting words	Regex.Replace(inputString, "(?=Address2=|State=)", "&");	0
26612352	25313959	Windows Phone 8 Stop bing from opening when searching bing in webbrowser	Browser.Navigate(new Uri("http://www.bing.com/search?q=" + "hello", UriKind.Absolute));	0
2826016	2825528	Removing the Title bar of external application using c#	//Get current style\nlCurStyle = GetWindowLong(hwnd, GWL_STYLE)\n\n//remove titlebar elements\nlCurStyle = lCurStyle And Not WS_CAPTION\nlCurStyle = lCurStyle And Not WS_SYSMENU\nlCurStyle = lCurStyle And Not WS_THICKFRAME\nlCurStyle = lCurStyle And Not WS_MINIMIZE\nlCurStyle = lCurStyle And Not WS_MAXIMIZEBOX\n\n//apply new style\nSetWindowLong hwnd, GWL_STYLE, lCurStyle\n\n//reapply a 3d border\nlCurStyle = GetWindowLong(hwnd, GWL_EXSTYLE)\n\nSetWindowLong hwnd, GWL_EXSTYLE, lCurStyle Or WS_EX_DLGMODALFRAME\n\n//redraw\nSetWindowPos hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE Or SWP_FRAMECHANGED	0
7556212	7556171	How to get Number Of Lines without Reading File To End	int count = File.ReadLines(path).Count();	0
13215683	13215574	How can I clear a TextBox?	MessageBox.Text = SenderBox.Text;\nSenderBox.Text = "cleared";	0
33285009	33284556	How to use regular expression with a string array	foreach ( string ex in ar)\n        {\n            if (Regex.IsMatch(txtbox.Text, @"^(www\.)([\w]+)\.(" + ex + ")$"))\n            {\n                lbl.Text = "True";\n                return;\n            }\n            else\n            {\n                lbl.Text = "False";\n            }\n        }	0
29411201	29409636	Working with multiple gameobjects	private void Button1_Click()\n{\n    var toActivate = new[] { 3, 7, 8 };\n    ActivateGameObjects(toActivate);\n}\n\nprivate void Button2_Click()\n{\n    var toActivate = new[] { 0, 7 };\n    ActivateGameObjects(toActivate);\n}\n\nprivate void ActivateGameObjects(int[] toActivate)\n{\n    for (int i = 0; i < gameobjects.Length; i++)\n    {\n        gameobjects[i].SetActive(toActivate.Contains(i));\n    }\n}	0
9010042	9009871	Find Credit Card Number in XML?	(\d{16}|\d{15}|\d{13})	0
12891575	12891253	Set maximum row height in generated excel document	Microsoft.Office.Tools.Excel.NamedRange setColumnRowRange;\n    private void SetColumnAndRowSizes()\n    {\n        setColumnRowRange = this.Controls.AddNamedRange(\n            this.Range["C3", "E6"], "setColumnRowRange");\n        this.setColumnRowRange.ColumnWidth = 20;\n        this.setColumnRowRange.RowHeight = 25;\n        setColumnRowRange.Select();\n    }	0
27041082	21996193	Changing conventions with FluentMigrator	public abstract class BaseMigration : Migration\n{\n    // Update conventions for up migration\n    public override void GetUpExpressions(IMigrationContext context)\n    {\n        this.UpdateConventions(context);\n        base.GetUpExpressions(context);\n    }\n\n    // Update conventions for down migration\n    public override void GetDownExpressions(IMigrationContext context)\n    {\n        this.UpdateConventions(context);\n        base.GetDownExpressions(context);\n    }\n\n    // Change the conventions\n    public void UpdateConventions(IMigrationContext context)\n    {\n        var conventions = ((MigrationConventions)context.Conventions);\n        conventions.GetIndexName = index => DefaultMigrationConventions.GetIndexName(index).Replace("IX_", "uidx_");\n    }\n}	0
34010432	34010327	Only Half of a Deck of Cards Being Created	private void buttonDeal_Click(object sender, EventArgs e)\n{\n    Card card = deck.DealCard();\n    deck.DealCard(); // error here. Duplicated line\n    labelOutput.Text = card.ToString();\n}	0
31086802	31086736	Best way to read yahoo IMAP emails using with C#	var client = new ImapX.ImapClient("imap.gmail.com", 993, true);\nclient.Connection();\nclient.LogIn(userName, userPassword);\nvar messages = client.Folders["INBOX"].Search("ALL", true);	0
2150376	2150362	Seemingly simple LINQ query is throwing me off. I want all items in array A unless it exists in array B	surveyorsInState.Except(currentSurveyors)	0
23284233	23284153	trying to create a extension method to convert from string to decimal	return (decimal)(retval / Math.Pow(10, numberofdecimalplaces));	0
13761827	13761675	Creating a copy of a workbook using open XML	using System.IO;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main()\n        {\n            File.Copy(@"C:\whatever\original.xlsx", @"C:\whatever\new.xlsx");\n        }\n    }\n}	0
8728410	8720023	facebook c# sdk getting started	var fb = new FacebookClient(AccessToken);\n                        dynamic parameters = new ExpandoObject();\n                        parameters.message = FacebookString;\n                        dynamic result = fb.Post("me/feed", parameters);\n                        var id = result.id;	0
25393894	25393823	Remove Item From Object SubList (LINQ)	var branchToRemove = _libraryService.GetLibrary(id);\n// .Single() will throw an exception unless there is one and only one match.\nvar consortRemove = userConsortia.Single(\n    c => c.Branches.Any(\n        b => string.Equals(b.LibraryId, id, StringComparison.OrdinalIgnoreCase));\n// remove the consortia\nuserConsortia.Remove(consortRemove);	0
12800616	12800052	how to Send Bulk Mail using Amazon webservices?	AmazonSimpleEmailServiceConfig amConfig = new AmazonSimpleEmailServiceConfig();\namConfig.UseSecureStringForAwsSecretKey = false;\nAmazonSimpleEmailServiceClient amzClient = new    \n    AmazonSimpleEmailServiceClient(ConfigurationManager.AppSettings["AKID"].ToString(),     \n    ConfigurationManager.AppSettings["Secret"].ToString(), amConfig);	0
25313678	25310736	How can I access a property from an ActionFilterAttribute in my ApiController?	[CustomActionFilter]\npublic class MyController : ApiController {\n    public ActionResult MyAction() {\n        var myAttribute = ControllerContext\n                          .ControllerDescriptor\n                          .GetCustomAttributes<CustomActionFilter>()\n                          .Single();\n        var success = myAttribute.success;\n    }\n}	0
21033070	21032861	Recursive Folder creation	static void Main(string[] args) {\n        CreateFolders(3, "c:\\temp\\temp");\n    }\n\n    static void CreateFolders(int depth, string path) {\n        if (depth <= 0) return;\n        for (int ix = 0; ix <= 10; ++ix) {\n            var dir = Path.Combine(path, ix.ToString());\n            System.IO.Directory.CreateDirectory(dir);\n            CreateFolders(depth - 1, dir);\n        }\n    }	0
17854308	17854165	Compare two lists of strings of varying length for difference based on content, not length	imported.Except(existing).Any();	0
6787146	6786758	When filling a combobox with data from a datatable, is there a way to 'get to' the other 'members' of the datatable?	var row = (DataRowView)cboCompany.SelectedItem;\n\nvar value = row["{column name}"];	0
24419854	24390741	Retrieve Values from Dictionary with Multiple Keys Using Only Each Key	public class MultiKeyDictionary : Dictionary<EntityID, string>\n{\n    private Dictionary<string, EntityID> _handleLookup = new Dictionary<string, EntityID>();\n    public Dictionary<string, EntityID> HandleLookup\n    {\n        get { return _handleLookup; }\n        set { _handleLookup = value; }\n    }\n\n    public string this[string handle]\n    {\n        get\n        {\n            EntityID id = this.HandleLookup[handle];\n            return base[id];\n        }\n    }\n\n    public void Add(EntityID id, string handle, string value)\n    {\n        base.Add(id, value);\n        this.HandleLookup.Add(handle, id);\n    }\n}	0
11121590	11120112	Setting the namespace during a parse	foreach (XElement ce in e.DescendantsAndSelf())\n     ce.Name = xs + ce.Name.LocalName;	0
14404880	14404670	A control disappears from parent UserControl after UserControl's OnRepaint event	protected override void OnResize(EventArgs e) {\n  btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA);\n}	0
18257456	18257231	Storing integers from Console to an array	Console.Writeline("Enter the number of numbers to add: ");\n//Yes, I know you should actually do validation here\nvar numOfNumbersToAdd = int.Parse(Console.Readline());\n\nint value;\nint[] arrayValues = new int[numOfNumbersToAdd];\nfor(int i = 0; i < numOfNumbersToAdd; i++)\n{\n    Console.Writeline("Please enter a value: ");\n    //Primed read\n    var isValidValue = int.TryParse(Console.Readline(), out value);\n    while(!isValidValue) //Loop until you get a value\n    {\n        Console.WriteLine("Invalid value, please try again: "); //Tell the user why they are entering a value again...\n        isValidValue = int.TryParse(Console.Readline(), out value);\n    }\n    arrayValues[i] = value; //store the value in the array\n}\n//I would much rather do this with LINQ and Lists, but the question asked for arrays.\nvar sum = 0;\nforeach(var v in arrayValues)\n{\n    sum += v;\n}\nConsole.Writeline("Sum {0}", sum);	0
31485083	31484948	Include Chromdriver In Your Application	System.Reflection.Assembly.GetExecutingAssembly().Location	0
13235136	13235089	C# Application with Numerous Errors	case "-e":\n        encrypt(args);\n        break;	0
30452876	30452726	Change the fore color of gridview row base on row text	if (lblremark.Text.Trim().ToLower().Equals("correct"))	0
20391788	20391719	Get the value of a BoundField from a DetailsView	string sOrderNumber = Order_DetailsView.Rows[0].Cells[0].Text.ToString();\nint orderNumber = Int32.Parse(sOrderNumber);	0
31136935	31136682	Multiple INSERT in one query using MySqlCommand	string cmd = "INSERT INTO " + Tables.Lux() + " VALUES ";\nint counter = 0;\n\nforeach (Element e in list) \n{\n    sql += "(NULL, @Position" + counter + ", @Mode" + counter + ", @Timer" + counter + "),";\n    command.Parameters.Add(new MySqlParameter("Position" + counter, e.Position));\n    command.Parameters.Add(new MySqlParameter("Mode" + counter, e.Mode));\n    command.Parameters.Add(new MySqlParameter("Timer" + counter, e.Timer));\n    counter++;\n}\n\ncommand.CommandText = sql.Substring(0, sql.Length-1); //Remove ',' at the end	0
22747634	22747574	How to cancel linkButton_Click() Event	if(cnt ==1) \n{\n   return;\n}	0
16832096	16809875	Full outer join, on 2 data tables, with a list of columns	var commonColumns = dt1.Columns.OfType<DataColumn>().Intersect(dt2.Columns.OfType<DataColumn>(), new DataColumnComparer());\n        DataTable result = new DataTable();\n\n        dt1.PrimaryKey = commonColumns.ToArray();\n\n        result.Merge(dt1, false, MissingSchemaAction.AddWithKey);\n        result.Merge(dt2, false, MissingSchemaAction.AddWithKey);	0
5397854	5397810	How to get the instance reference of the ViewModel, created by MEF container?	var vm = DataContext as MyModuleViewModel;	0
609544	609533	How do you open the event log programatically?	var log = EventLog.GetEventLogs().Where(x => x == "Application").First();\nforeach (var entry in log.Entries) {\n  // Do something with the entry\n}	0
17391708	17391645	How to swap two variable values?	if (sH > fH) {\n  double temp = sH;\n  sH = fH;\n  fH = temp;\n}	0
7713780	180030	How can I find out when a picture was actually taken in C# running on Vista?	//we init this once so that if the function is repeatedly called\n    //it isn't stressing the garbage man\n    private static Regex r = new Regex(":");\n\n    //retrieves the datetime WITHOUT loading the whole image\n    public static DateTime GetDateTakenFromImage(string path)\n    {\n        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n        using (Image myImage = Image.FromStream(fs, false, false))\n        {\n            PropertyItem propItem = myImage.GetPropertyItem(36867);\n            string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);\n            return DateTime.Parse(dateTaken);\n        }\n    }	0
19609482	19608834	how to store id and name in datagridview combox column	public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        for (int i = 0; i < 10; i++)\n        {\n            ComboboxItem item = new ComboboxItem("John", i);\n            comboBox1.Items.Add(item);\n\n\n\n        }\n        comboBox1.DisplayMember = "Name";\n    }\n\n    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        ComboboxItem item = (ComboboxItem)comboBox1.SelectedItem;\n        MessageBox.Show(item.ID.ToString());\n    }	0
9432201	9431949	Changing the Format of XML	using System.Linq;\nusing System.Xml.Linq;\n\nvar indoc = XDocument.Load("c:\\test.xml");   \nvar outdoc = new XDocument(\n              new XElement("Root", \n                indoc.Descendants("Root")\n                     .Descendants("Username")\n                     .Elements()\n                     .Select(n => n.Value)\n                     .Select(i => new XElement("Username", i))));\n\n// TODO: Save doc using doc.WriteTo(xmlWriter) to the file	0
1672904	1672893	C# : How to get number of days from an object of DateTime	int noOfDays = DateTime.DaysInMonth(objDate.Year, objDate.Month);	0
7020091	7019877	ScrollableControl scroll bars always return to zero	public partial class UserControl1 : UserControl {\n    public UserControl1() {\n        InitializeComponent();\n        this.SetStyle(ControlStyles.ResizeRedraw, true);\n        this.AutoScroll = true;\n        this.AutoScrollMinSize = new Size(1000, 0);\n    }\n    protected override void OnScroll(ScrollEventArgs se) {\n        base.OnScroll(se);\n        this.Invalidate();\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);\n        e.Graphics.DrawLine(Pens.Black, 0, 0, 1000, this.ClientSize.Height);\n        base.OnPaint(e);\n    }\n}	0
17897387	17897305	How can i use white spaces in bindingsource.filter?	bindingsource1.Filter="[Phone Number] = 123";	0
8349933	8349864	How can I convert string to time object for calculation	TimeSpan start = new TimeSpan(42); // 42 ticks\nTimeSpan end = new TimeSpan(420000000);\nTimeSpan diff = end.Subtract(start);\nstring ms = diff.Milliseconds.ToString();\nstring sec = ((int)diff.TotalSeconds).ToString();\nConsole.WriteLine(sec + ":" + ms);	0
22015406	22015050	Loop through subitems in menustrip	var exportMenu=allItems.FirstOrDefault(t=>t.Text=="Export");\nif(exportMenu!=null)\n{\n    foreach(ToolStripItem item in exportMenu.DropDownItems) // here i changed the var item to ToolStripItem\n    {\n         if(item.Text=="Word") // as you mentioned in the requirements\n              item.Visible=false; // or any variable that will set the visibility of the item\n    }\n}	0
26326376	26325470	How do I import .dll library from subfolder in C#	string saveCurDir = Directory.GetCurrentDirectory();\nDirectory.SetCurrentDirectory(Path.Combine(Application.StartupPath, "plugins"));\n\nIntPtr iq_dll = LoadLibrary("IQPokyd.dll");\n\nDirectory.SetCurrentDirectory(saveCurDir);	0
11253690	11253634	Limit my description field to 300 words	searchResults.DataSource = from r in response.Results\n                           select new\n                           {\n                               Title = r[SearchContentProperty.Title],\n                               Summary = r[SearchContentProperty.HighlightedSummary],\n                               Id = r[SearchContentProperty.Id] * 10,\n                               Quicklink = r[SearchContentProperty.QuickLink],\n                               Description = r[SearchContentProperty.Description].ToString().Split(' ').Take(300).Aggregate((a, b) => a + " " + b);\n                           };	0
30593288	30567843	Is it possible to create a signed email with an opaque signature using MimeKit?	var signer = new CmsSigner(certificate, key);\nsigner.DigestAlgorithm = DigestAlgorithm.Sha1;\n\nmessage.Body = ApplicationPkcs7Mime.Sign(ctx, signer, messageContent);	0
7427436	7427395	Run the Console Application as service	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.ServiceProcess;\nusing System.Text;\n\nnamespace MyWindowsService\n{\n    public partial class Service1 : ServiceBase\n    {\n        public Service1()\n        {\n            InitializeComponent();\n        }\n\n        protected override void OnStart(string[] args)\n        {\n        }\n\n        protected override void OnStop()\n        {\n        }\n    }\n}	0
19198774	19198710	How do I read the names of files in a directory into an array?	Directory.GetFiles(@"C:\MergeMe\*.txt")	0
31616765	31615737	Replace character references for invalid XML characters	public string ReplaceXMLEncodedCharacters(string input)\n{\n    const string pattern = @"&#(x?)([A-Fa-f0-9]+);";\n    MatchCollection matches = Regex.Matches(input, pattern);\n    int offset = 0;\n    foreach (Match match in matches)\n    {\n        int charCode = 0;\n        if (string.IsNullOrEmpty(match.Groups[1].Value))\n            charCode = int.Parse(match.Groups[2].Value);\n        else\n            charCode = int.Parse(match.Groups[2].Value, System.Globalization.NumberStyles.HexNumber);\n        char character = (char)charCode;\n        input = input.Remove(match.Index - offset, match.Length).Insert(match.Index - offset, character.ToString());\n        offset += match.Length - 1;\n    }\n    return input;\n}	0
16809359	16808309	Calculation algorithm for Dates	DateTime invoiceStart = StartInStorageDate.AddDays(5);\nDateTime invoiceEnd = InvoiceDate < EndOfStorageDate ? InvoiceDate : EndOfStorageDate; \n\ndouble billedDays = Math.Max(0, (invoiceEnd - invoiceStart).TotalDays);	0
31820994	31820943	How to run PowerShell script in C# from relative path?	using (PowerShell pshell = PowerShell.Create())\n    {\n        string path=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n        pshell.AddScript( path+"\\psScript.ps1" );\n        pshell.Invoke();\n    }	0
1008567	1008551	HtmlTextWriter to String - Am I overlooking something?	protected override void RenderContents(HtmlTextWriter output)  \n{  \n   StringBuilder sb = new StringBuilder();  \n   HtmlTextWriter htw = new HtmlTextWriter(new System.IO.StringWriter(sb,   \n   System.Globalization.CultureInfo.InvariantCulture));  \n   foreach (Control ctrl in Controls)  \n   {  \n      ctrl.RenderControl(htw);  \n   }  \n  string strContents = sb.ToString();	0
31405147	31404075	ComboBox items are just a path	drpdefContVal.DisplayMember = "dbTitle";	0
8137028	8135968	Is it a good practice to do following idea based on ListView?	public class TestData:  INotifyPropertyChanged\n{\nprivate string _name;\npublic string Name\n{\n    get { return _name; }\n    set\n    {\n        _name = value;\n        this.NotifyPropertyChanged("Name");\n    }\n}\n\n// I only included one property for simplicity.  You of course will need to do this\n// for every property in the test model\n\npublic event PropertyChangedEventHandler PropertyChanged;\n\nprivate void NotifyPropertyChanged(string name)\n{\n    if (PropertyChanged != null)\n    {\n        PropertyChanged(this, new PropertyChangedEventArgs(name));\n    }\n}	0
2737505	2732629	Print content of a javascript tabcontrol: Gridviews	function doPrintPage()\n{\n\nmyWindow = window.open('', '', 'titlebar=yes,menubar=yes,status=yes,scrollbars=yes,width=800,height=600');\n\nmyWindow.document.open();\nmyWindow.document.write("</br>");\nmyWindow.document.write("<h2>Results</h2>");\nmyWindow.document.write(document.getElementById('tab1').innerHTML);\nmyWindow.document.write("</br>");\nmyWindow.document.write("<h2>Tree</h2>");\nmyWindow.document.write(document.getElementById('tab2').innerHTML);\nmyWindow.document.write("</br>");\nmyWindow.document.write("<h2>Open</h2>");\nmyWindow.document.write(document.getElementById('tab3').innerHTML);\nmyWindow.document.write("</br>");\nmyWindow.document.write("<h2>Free</h2>");\nmyWindow.document.write(document.getElementById('tab4').innerHTML);\n\nmyWindow.document.close();\n\nmyWindow.focus();\n\n//myWindow.print();\n\n//myWindow.close();\n\nreturn true;\n\n}	0
11411920	11396189	Declare C function with char* parameter in c#	[DllImport("DEMO.dll",\n        SetLastError = true,\n        CallingConvention = CallingConvention.Cdecl)]\n    public extern static byte GetVersion(\n        [MarshalAs(UnmanagedType.LPStr)] StringBuilder versionBuffer,\n        [MarshalAs(UnmanagedType.LPWStr)] StringBuilder versionLengthBuffer);	0
10313594	10313445	using statement for  SQL command	int rowCount = conn.Query<int>(query, new {p_DateFrom = datefrom}).Single();	0
24518381	24516321	Match a string against an easy pattern	private bool TestMethod()\n{\n    const string textPattern = "X###";\n    string text = textBox1.Text;\n    bool match = true;\n\n    if (text.Length == textPattern.Length)\n    {\n        char[] chrStr = text.ToCharArray();\n        char[] chrPattern = textPattern.ToCharArray();\n        int length = text.Length;\n\n        for (int i = 0; i < length; i++)\n        {\n            if (chrPattern[i] != '#')\n            {\n                if (chrPattern[i] != chrStr[i])\n                {\n                    return false;\n                }\n            }\n        }\n    }\n    else\n    {\n        return false;\n    }\n    return match;\n}	0
10888461	10888449	Is it possible to convert a C# string to a SqlChars?	new SqlChars(new SqlString(text));	0
5748485	5748363	Linq to create a csv string for some values stored in an array of object using c#	var accounts = from a in accountList\n               where (a.acctnbr.StartsWith("L") || a.acctnbr.StartsWith("P")) \n                  && (a.acctnbr.Length == 6)\n               select a.acctnbr;\n\nvar csv = String.Join("," accounts.ToArray());	0
19528434	19527600	Set a list to method return value but cant use the method	public class Game1 : Microsoft.Xna.Framework.Game\n{\n    GraphicsDeviceManager graphics;\n    public static SpriteBatch spriteBatch;\n\n    // ...\n\n    // Class initialization\n    private Map map = new Map() { Width = 10, Height = 10, TileWidth = 16, TileHeight = 16 };\n\n    // Variable declaration\n    List<Vector2> blockPos = new List<Vector2>();\n\n    Texture2D dirtTex;\n\n    /// <summary>\n    /// LoadContent will be called once per game and is the place to load\n    /// all of your content.\n    /// </summary>\n    protected override void LoadContent()\n    {\n        // Create a new SpriteBatch, which can be used to draw textures.\n        spriteBatch = new SpriteBatch(GraphicsDevice);\n\n        dirtTex = Content.Load<Texture2D>("dirt");\n\n        blockPos = map.generateMap();\n    }\n\n    // ...\n}	0
16773495	16773449	how to pass Sql parameter	cmd.CommandType = CommandType.StoredProcedure;	0
13244058	13244040	Show an attachment in form	MailMessage mail = new MailMessage();\nSmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");\nmail.From = new MailAddress("your mail@gmail.com");\nmail.To.Add("to_mail@gmail.com");\nmail.Subject = "Test Mail";\nmail.Body = "mail with attachment";\n\nSystem.Net.Mail.Attachment attachment;\nattachment = new System.Net.Mail.Attachment("c:/textfile.txt");\nmail.Attachments.Add(attachment);\n\nSmtpServer.Port = 587;\nSmtpServer.Credentials = new System.Net.NetworkCredential("id", "password");\nSmtpServer.EnableSsl = true;\n\nSmtpServer.Send(mail);	0
34037588	34037467	ListView scroll to bottom as all binding data loaded	myList.ScrollIntoView(myList.Items[myList.Items.Count - 1])	0
31574782	31574507	How to get passed System.UnauthorizedAccessException when writing to a file in Application.StartUpPath?	string fileName = "myFile.txt";\nstring fileLocation = Path.Combine(Application.StartupPath, fileName);\nif(!File.Exists(fileLocation))\n{ File.Create(fileLocation); }	0
18918305	18918100	Displaying data in console window from database	using (SqlConnection connection = new SqlConnection(YOURCONNECTIONSTRING))\n        {\n            connection.Open();\n            using (SqlCommand command = new SqlCommand("SELECT * FROM Employees", connection))\n            {\n                using (SqlDataReader reader = command.ExecuteReader())\n                {\n                    while (reader.Read())\n                    {\n                        for (int i = 0; i < reader.FieldCount; i++)\n                        {\n                            Console.WriteLine(reader.GetValue(i));\n                        }\n                        Console.WriteLine();\n                    }\n                }\n            }\n        }	0
26599760	26599634	Lazy Evaluation in a Setter	public class SetVariable\n{\n    Creature ObjectToSet { get; set; }\n    Action<Creature, Creature> SetterAction { get; set; }\n\n    public SetVariable(Creature objectToSet, Action<Creature, Creature> setterAction)\n    {\n        this.ObjectToSet = objectToSet;\n        this.SetterAction = setterAction;\n    }\n\n    public Act(Creature parent)\n    {\n        this.SetterAction(parent, this.ObjectToSet);\n        //the setter action would be defined as (when instantiating this object):\n        //SetVariable mySet = new SetVariable(null, (target, val) => target.PropertyName = val);\n        //it will set the PropertyName property of the target object to val (in this case val=null).\n    }\n}	0
4227131	4226763	How do I AssertWasCalled a generic method with three different types using RhinoMocks?	[Subject("Test")]\npublic class When_something_happens_with_constraint\n{\n    static IRepository repo;\n    static TestController controller;\n    static ActionResult result;\n\n    Establish context = () =>\n    {\n        repo = MockRepository.GenerateMock<IRepository>();\n        controller = new TestController(repo);\n    };\n\n    //post data to a controller\n    Because of = () => result = controller.SaveAction(new SomethingModel() { Name = "test", Description = "test" });\n\n    //controller constructs its own something using the data posted, then saves it. I want to make sure three calls were made.  \n    It Should_save_something = () => repo.AssertWasCalled(o => o.Save(Arg<Something>.Is.Anything));\n    It Should_save_something_else = () => repo.AssertWasCalled(o => o.Save(Arg<SomethingElse>.Is.Anything));\n    It Should_save_another_one = () => repo.AssertWasCalled(o => o.Save(Arg<AnotherOne>.Is.Anything));\n}	0
6925637	6925464	Performance tuning powershell text processing	Add-Type	0
22989826	22988856	Allocation of value types	x[i++] = v();	0
24617838	24617090	Dynamic html table in c# with href as edit	foreach (DataRow myRow in dt.Rows)\n{            \n    strBuilder.Append("<tr align='left' valign='top'>");\n\n    //col[0] as link\n    strBuilder.Append("<td align='left' valign='top'><a href="+ myRow[0].ToString()+">Edit</a></td>");\n\n    foreach (DataColumn myColumn in dt.Columns.Skip(1)) //skip first, render rest\n    {\n        strBuilder.Append("<td align='left' valign='top'>");\n        strBuilder.Append(myRow[myColumn.ColumnName].ToString());\n        strBuilder.Append("</td>");\n    }\n\n    strBuilder.Append("</tr>");\n}	0
2957396	2956670	Setting the cores to use in Parallelism	using System;\nusing System.Threading.Tasks;\n\nclass Program {\n  static void Main(string[] args) {\n    var options = new ParallelOptions();\n    options.MaxDegreeOfParallelism = 2;\n    Parallel.For(0, 100, options, (ix) => {\n      //..\n    });\n  }\n}	0
4946698	4946537	dynamicaly add menu itmes to asp:Menu	Menu1.Items.Add(new MenuItem("Text", "Value"));	0
26771547	26762176	How to add a list picker on Textblock tap event in Wp8?	private void tb_Tap(object sender, System.Windows.Input.GestureEventArgs e)
\n        {
\n            ListPicker lp = new ListPicker();
\n            lp.Background = new SolidColorBrush(Colors.Blue);
\n            lp.Height = 500;
\n            LayoutRoot.Children.Add(lp);
\n        }	0
11973125	11972673	How to get a e.CommandArgument from a row in a gridview while using a dropdownlist inside it in asp.net c#?	protected void dpdListEstado_SelectedIndexChanged(object sender, EventArgs e)\n{\n    GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);   \n    MeaningfulNameHere(int.Parse(grdvEventosVendedor.DataKeys[gvr.RowIndex]),"Estado");\n}\n\nprotected void grdvEventosVendedor_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n    MeaningfulNameHere(int.Parse(e.CommandArgument.ToString()),e.CommandName);\n}\n\nprivate void MeaningfulNameHere(int id, string commandName)\n{\n\n\n    if (commandName == "Edicion")\n    {\n        //Some Code\n    }\n\n    else if (commandName == "Borrar")\n    {\n       //More Code\n    }\n\n    else if (commandName == "CRM")\n    {\n        //Even More Code\n    }\n\n    else if (commandName == "VerMas")\n    {\n        //....\n    }\n\n    else if (commandName == "Estado")\n    {\n\n    }\n}	0
20592322	20592212	How to draw simple Graphics	private void DrawIt()\n    {\n        System.Drawing.Graphics graphics = this.CreateGraphics();\n        System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(\n           50, 50, 150, 150);\n        graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);\n        graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);\n        this.Update();\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        DrawIt();\n        base.OnPaint(e);\n\n    }\n\n    private void MainWindow_Paint(object sender, PaintEventArgs e)\n    {\n        //DrawIt();\n    }	0
22601320	22599902	WPF TwoWay Binding change value in PropertyChanged	private static void LoadTriggerPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)\n{\n    if ((bool)e.NewValue)\n    {\n        //run "async" on the same UI thread:\n        Dispatcher.BeginInvoke(((UC)source).LoadLayout);\n    }\n}	0
32850756	32832512	EPPlus - Get file name from worksheet	//Get the package containing this workbook.\npublic ExcelPackage Package { get { return _package; } }\n//Get the name of the file of this workbook.\npublic String Name { get { return _package.File.Name; } }	0
12420637	12420575	Read all methode attributes using reflection in C#	Attribute[] attributes = Attribute.GetCustomAttributes\n              (methodInfo, typeof (fieldAttribute), false);	0
13933266	13933120	How to get all control list of the Form in c#?	public IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)\n{\n    List<Control> controls = new List<Control>();\n\n    foreach(Control child in parent.Controls)\n    {\n        controls.AddRange(GetSelfAndChildrenRecursive(child));\n    }\n\n    controls.Add(parent);\n\n    return controls;\n}\n\nvar result = GetSelfAndChildrenRecursive(topLevelControl)	0
15861747	15861665	How to get dynamically added UI element from C#	object findRect = Container.FindName("field_1_1");\nif (findRect is Rectangle)\n{        \n    Rectangle rect = findRect as Rectangle;\n    //change rect properties\n}	0
23992188	23827718	Binding Failure in WPF using MVVM	public static readonly DependencyProperty SelectionLengthProperty =\n     DependencyProperty.Register("SelectionLength", typeof(int), typeof(MvvmTextEditor),\n     new PropertyMetadata((obj, args) =>\n         {\n             MvvmTextEditor target = (MvvmTextEditor)obj;\n             if (target.SelectionLength != (int)args.NewValue)\n             {\n                 target.SelectionLength = (int)args.NewValue;\n                 target.Select(target.SelectionStart, (int)args.NewValue);\n             }\n         }));\n\npublic new int SelectionLength\n{\n    get { return base.SelectionLength; }\n    //get { return (int)GetValue(SelectionLengthProperty); }\n    set { SetValue(SelectionLengthProperty, value); }\n}	0
27427551	27426530	How can i add context menu for each item on listView1 and treeView1 when doing mouse right click on item?	TreeNode tn = treeView1.GetNodeAt( e.X, e.Y );\n\nif( tn != null )\n{\n  if( tn.Name == "FileName") {\n\n  }\n}	0
13898079	13897918	How can I get the current directory in PowerShell cmdlet?	this.SessionState.Path.CurrentFileSystemLocation	0
33296578	33296504	Display Double value in a label	you need to convert your val2 to double:\nprivate double val1;\nprivate int val2 =9;\nprivate void displayValue()\n{\n    val1 = ((double)val2/100);\n    text1.Text = val1.ToString("0.000");\n}	0
20809438	19686571	How to extend Ellipse class in WPF	class WeightedEllipse\n{\npublic Ellipse ellipse;\npublic double weight;\n\npublic WeightedEllipse(double weight)\n    {\n      this.ellipse=new Ellipse();\n      this.weight=weight;\n    }\n}	0
31159923	31158264	How to filter number and date in GridView using RowFilter?	string colname = ListBox1.SelectedItem.Text;\n        string value = textBox1.Text;\n        if (colname != null && dt.Columns[colname] != null)\n        {\n            if ("Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(dt.Columns[colname].DataType.Name + ","))\n            {\n                dv.RowFilter = colname + "=" + value;\n            }\n            else if (dt.Columns[colname].DataType == typeof(string))\n            {\n                dv.RowFilter = string.Format(colname + " LIKE '%{0}%'", value);\n            }\n            else if (dt.Columns[colname].DataType == typeof(DateTime))\n            {\n                dv.RowFilter = colname + " = #" + value + "#";\n            }\n        }	0
8977915	8977877	Bold text in strings	user.Name	0
7440546	7440525	How to create a custom exception in c#	void UpdateDatabase()\n{\n//...\n        try \n            { \n\n            } \n               // Your checks to identify - type of exception\n               // ...\n              // .net exception\n              // Throw your custom exception in the appropriate block - \n              // throw new DatabaseException();\n            catch (OutOfMemoryException ex1) \n            { \n\n            }\n            catch (InvalidDataException ex2) \n            { \n\n            }\n            // Generic exception\n            catch (Exception ex3) \n            { \n                // throw new DatabaseException();\n            } \n//....\n}\n\n// Method calling UpdateDatabase need to handle Custom exception\nvoid CallUpdateDatabase()\n{\n try\n  {\n    UpdateDatabase();\n  }\n  catch(DatabaseException dbEx)\n  {\n    // Handle your custom exception\n  }\n}	0
13966326	13966285	Create comma separated string from portion of strings in C# List	var nameList = myList.Select(x=>x.Name).ToList();	0
11292075	11291979	C# Listbox Passing Strings	private void button_Click(object sender, EventArgs e)\n{ \n    Form1 frm = new Form1(); \n    frm.AddItemToListBox(txtBox1.Text,txtBox2.Text); \n    frm.Show();\n}	0
4453865	4453535	How do I redirect a console program's output to a text box in a thread safe way?	proc.WaitForExit();	0
27845777	27845710	How do i convert Strings.Format from vb to c#	string formatted = (ID*100.0/65535).ToString("f1") + "%";	0
12819217	12817939	Using same transaction in workflow	instance.Start()	0
32077725	32035320	How to scan two images for differences?	private static void ProcessImages()\n{\n    (* load images *)\n    var img1 = AForge.Imaging.Image.FromFile(@"compare1.jpg");\n    var img2 = AForge.Imaging.Image.FromFile(@"compare2.jpg");\n\n    (* calculate absolute difference *)\n    var difference = new AForge.Imaging.Filters.ThresholdedDifference(15)\n        {OverlayImage = img1}\n        .Apply(img2);\n\n    (* create and initialize the blob counter *)\n    var bc = new AForge.Imaging.BlobCounter();\n    bc.FilterBlobs = true;\n    bc.MinWidth = 5;\n    bc.MinHeight = 5;\n\n    (* find blobs *)\n    bc.ProcessImage(difference);\n\n    (* draw result *)\n    BitmapData data = img2.LockBits(\n       new Rectangle(0, 0, img2.Width, img2.Height),\n          ImageLockMode.ReadWrite, img2.PixelFormat);\n\n    foreach (var rc in bc.GetObjectsRectangles())\n        AForge.Imaging.Drawing.FillRectangle(data, rc, Color.FromArgb(128,Color.Red));\n\n    img2.UnlockBits(data);\n    img2.Save(@"compareResult.jpg");\n}	0
24274813	24253770	Self-Hosted SignalR app refusing CORS requests	public class AdminHub : Hub\n    {\n        private readonly IMyService _myService;\n\n        public AdminHub(IMyService myService)\n        {\n            _myService= myService;\n            _myService.OnProcessingUpdate += (sender, args) => UpdateProcessingStatus();\n        }\n\n        public void UpdateProcessingStatus()\n        {\n            Clients.All.updateProcessing(_myService.IsProcessing);\n        }\n\n        public void GetProcessingStatus()\n        {\n            Clients.Caller.updateProcessing(_myService.IsProcessing);\n        }\n\n        public void StartProcessing()\n        {\n            _myService.Process();\n        }\n    }	0
6228441	6207971	How to use xmlschemaset and xmlreader.create to validate xml against an xsd schema	// New Validation Xml.\n            string xsd_file = filename.Substring(0, filename.Length - 3) + "xsd";\n            XmlSchema xsd = new XmlSchema();\n            xsd.SourceUri = xsd_file;\n\n            XmlSchemaSet ss = new XmlSchemaSet();\n            ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n            ss.Add(null, xsd_file);\n            if (ss.Count > 0)\n            {\n                XmlReaderSettings settings = new XmlReaderSettings();\n                settings.ValidationType = ValidationType.Schema;\n                settings.Schemas.Add(ss);\n                settings.Schemas.Compile();\n                settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);\n                XmlTextReader r = new XmlTextReader(filename2);\n                using (XmlReader reader = XmlReader.Create(r, settings))\n                {\n                    while (reader.Read())\n                    {\n                    }\n                }\n            }	0
34059014	34024521	Adding buttons to WPF from ObservableCollection using MVVM pattern	ItemsSource="{Binding Path=DataContext.TabContents, \n              RelativeSource={RelativeSource AncestorLevel=1, \n              AncestorType={x:Type Window}, Mode=FindAncestor}}"	0
13826475	13802849	Remove Domain User from Local Groups	using (PrincipalContext localContext = new PrincipalContext(ContextType.Machine))\n            {\n                try\n                {\n                    foreach (string g in groups)\n                    {\n                        using (GroupPrincipal localGroup = GroupPrincipal.FindByIdentity(localContext, IdentityType.Name, g))\n                        {\n                            foreach (Principal groupUser in localGroup.GetMembers().Where(groupUser => user.Name.Equals(groupUser.Name)))\n                            {\n                                localGroup.Members.Remove(groupUser);\n                                localGroup.Save();\n                            }\n                        }\n                    }\n                }	0
1687862	1687812	ASP.NET MVC: is it a good idea to return a File result from a byte[]?	memoryStream.Position = 0;	0
26917431	26916643	Regex match multiple substrings inside a string	string input = @"This combination of plain text and <c=@flavor> colored text<c> is valid. <c=@warning>Multiple tags are also valid.<c>";\n\nvar matches = Regex.Matches(input, @"<c=@(.+?)>(.+?)<c>")\n                .Cast<Match>()\n                .Select(m => new\n                {\n                    Name = m.Groups[1].Value,\n                    Value = m.Groups[2].Value\n                })\n                .ToList();	0
22115931	22114729	System.InvalidCastException trying to build a COM client and a COM server in C#	Tlbexp.exe	0
8517617	8517260	Resolving relative path with wildcard in C#	// input\nstring rootDir = @"c:\foo\bar"; \nstring originalPattern = @"..\blah\*.cpp";\n\n// Get directory and file parts of complete relative pattern\nstring pattern = Path.GetFileName (originalPattern); \nstring relDir = originalPattern.Substring ( 0, originalPattern.Length - pattern.Length );\n// Get absolute path (root+relative)\nstring absPath = Path.GetFullPath ( Path.Combine ( rootDir ,relDir ) );\n\n// Search files mathing the pattern\nstring[] files = Directory.GetFiles ( absPath, pattern, SearchOption.TopDirectoryOnly );	0
21755350	21754365	Inline if-else statement with multiple choices	public enum Direction\n{\n   Left = -90,\n   Right = 90,\n   Forward =0,\n   Back = 180\n}\n\nprivate void Move(Direction direction) \n{\n   transform.Rotate(0,(int)direction,0);\n   transform.Translate(Vector3.forward, Space.Self);\n}	0
14032559	14032515	How to get the amount of memory used by an application	long memory = GC.GetTotalMemory(true);	0
14613777	14610664	Prevent Web API method from being called	config.Routes.MapHttpRoute(\n    name: "GetUsers",\n    routeTemplate: "api/users/{id}",\n    defaults: new { controller = "Users", action = "GetUser" }\n);	0
25467905	25467800	Listview virtualmode not able to add items dynamically	private void listviewGames_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)\n{\n    if (listGames[1].Count < 1) return;\n\n\n    ListViewItem lvi = new ListViewItem();\n\n    lvi.Text = listGames[1][e.ItemIndex];\n\n    e.Item = lvi;\n\n}	0
22784407	22774208	How to initalize a set of random image files in c# and bind them randomly in XAML	var imageName = "Question1" + "_" + randomNumber + ".jpg";	0
3059348	3059336	DataContext to DB	var(dc = new MyDataContext()) {\n    dc.CreateDatabase();\n}	0
7625426	7625421	minimize app to system tray	private void frmMain_Resize(object sender, EventArgs e)\n{\n    if (FormWindowState.Minimized == this.WindowState)\n    {\n       mynotifyicon.Visible = true;\n       mynotifyicon.ShowBalloonTip(500);\n       this.Hide();\n    }\n\n    else if (FormWindowState.Normal == this.WindowState)\n    {\n       mynotifyicon.Visible = false;\n    }\n}	0
6726362	6726273	How to simulate daylight saving time transition in a unit test?	var dayLightChangeEnd = TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year).End.ToUniversalTime();\nvar stillInDaylightSavingTime = dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(62)).ToLocalTime();\nConsole.WriteLine(stillInDaylightSavingTime);\nConsole.WriteLine(stillInDaylightSavingTime.IsDaylightSavingTime());\nvar noDaylightSavingTimeAnymore = dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(2)).ToLocalTime();\nConsole.WriteLine(noDaylightSavingTimeAnymore);\nConsole.WriteLine(noDaylightSavingTimeAnymore.IsDaylightSavingTime());	0
3190733	3190693	I want to create an access database populated with data from xml file	DataSet ds = new DataSet();\nds.ReadXml(filename);\n\nforeach(DataTable table in ds.Tables) {\n\n    //Create table\n\n    foreach(DataRow row in table.Rows) {\n        //Insert rows\n    }\n}	0
23599265	23599150	How to extend a class's functionality?	public interface IPlayer\n{\n  string Name {get;}\n  string Id {get;}\n}\n\npublic class Player: IPlayer\n{\n    public string Id {get; private set;}\n    public string Name {get; private set;}\n    Player (string name, string id)\n    {\n        Name = name;\n        Id = id;\n    }\n}\n\npublic class ExtendedPlayer: IPlayer\n{\n    private IPlayer  _player;\n    public string Id {get { return _player.Id; }}\n    public string Name {get { return _player.Name + ", " + Color; }}\n    public string Color{ {get;set;}\n    Player (IPlayer player, string color)\n    {\n        _player = player;\n        Color = color;\n    }\n}\n\nIPlayer player = new Player("12", "Video player");\nplayer = new ExtendedPlayer(player, "red");\nConsole.WriteLine(player.Id);                      // prints 12\nConsole.WriteLine(player.Name);                    // prints Video player, red\nConsole.WriteLine(((ExtendedPlayer)player).Color); // prints red	0
2517459	2517421	check a string if have a word	bool contains = str.ToLower().Contains("wordtofind")	0
1829018	1828971	Capturing the first match with regex (C#)	\d(?<name>[^\d]+)\d	0
33944741	33934833	c# code to set cursor position in outlook word editor	wordApplication.Selection.Start = 1000\n\n wordApplication.Selection.End = 1000	0
4469128	4469097	How do I generate test data?	object classObject;\nPropertyInfo[] propertyInfos;\npropertyInfos = typeof(classObject).GetProperties(BindingFlags.Public | BindingFlags.Static);\nforeach (PropertyInfo propertyInfo in propertyInfos)\n{\n     propertyInfo.SetValue(classObject, value, null)\n}	0
19094382	19091464	Sql transaction rollback from other form	class MainForm()\n{\n    private TransactionScope _scope;\n    public void SaveButton_Click()\n    {\n        _scope.Complete();\n        Close();\n    }\n    public MainForm()\n    {\n        _scope = new TransactionScope();\n    }\n    ~MainForm()\n    {\n        _scope.Dispose();\n    }\n}	0
26581828	26554041	InnerHtml in c#	protected void hiddentoggletofrenchBackend(object sender, DirectEventArgs e)\n{\n    this.StatusPreview.InnerHtml = "aaaaa";\n    this.StatusPreview.Update();\n}	0
26145140	26144137	C# - Adding multiple Excel formatted tables	_worksheet.ListObjects.AddEx(XlListObjectSourceType.xlSrcRange, range, misValue, Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes, misValue).Name = "MyTableStyle";\n    _worksheet.ListObjects.get_Item("MyTableStyle").TableStyle = "TableStyleLight9";	0
4919507	4794917	Best way to display a group/selection of radiobuttons from the choice of a single radiobutton?	if (wd.AppTher == true) \n  { wd.AppTherRea = 0; }	0
8417122	8417074	How to group IList<T> using LINQ?	var query = from product in context.Products\n                        where product.ProductCategory_Id == productcatid\n                        group product by prodyct.Attribute_1 into g\n                        select new { Attribute_1 = g.Key, Products = g };	0
19958917	19958853	Turn a dynamic DataTable into a List<Dictionary<string,string>>	// Iterate through the rows...\ntable.AsEnumerable().Select(\n    // ...then iterate through the columns...\n    row => table.Columns.Cast<DataColumn>().ToDictionary(\n        // ...and find the key value pairs for the dictionary\n        column => column.ColumnName,    // Key\n        column => row[column] as string // Value\n    )\n)	0
19494580	19494520	DateTime.ParseExact fails	string dateToCheck = "2013-10-20 00:00";	0
19121867	19105018	change databound listbox to longlistselector	private void LongListSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    var myObj = AccountsList.SelectedItem as MyObject;\n    if(myObj == null) return;\n\n    var accountNum = myObj.AccountNumber;\n    NavigationService.Navigate(new Uri(string.Format("/ViewAccount.xaml?parameter={0}&action={1}", accountNum, "View"), UriKind.Relative));\n\n    // set the selectedItem to null so the page can be navigated to again \n    // If the user taps the same item\n    AccountsList.SelectedItem = null;\n}	0
13515421	13515380	C# loop statements, help needed for a newbie	double price = 0.5 * DistanceInMile + ((int)(DistanceInMile /1000)) *30;	0
15422625	15418416	mvc3 moq mvccontrib how to moq useragent?	public static RouteController GetRouteController(string useragent)\n        {\n            var controller = new RouteController();\n            var builder = new TestControllerBuilder();\n\n            builder.InitializeController(controller);\n            //mock out the useragent string\n            controller.HttpContext.Request.Stub(r => r.UserAgent).Return(useragent);\n            return controller;\n        }	0
21132379	21132093	How to see if HttpClient connects to offline website	// Create an HttpClient and set the timeout for requests\nHttpClient client = new HttpClient();\nclient.Timeout = TimeSpan.FromSeconds(10);\n\n// Issue a request\nclient.GetAsync(_address).ContinueWith(\n    getTask =>\n     {\n            if (getTask.IsCanceled)\n            {\n              Console.WriteLine("Request was canceled");\n            }\n            else if (getTask.IsFaulted)\n            {\n               Console.WriteLine("Request failed: {0}", getTask.Exception);\n            }\n            else\n            {\n               HttpResponseMessage response = getTask.Result;\n               Console.WriteLine("Request completed with status code {0}", response.StatusCode);\n            }\n    });	0
21443522	21443418	How to make the columns in a ListView expand dynamically?	header.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);	0
18879444	18879031	How to save value for key in *config file	Configuration config = ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);\nconfig.AppSettings.Settings["Volume"].Value = "10";\nconfig.Save(ConfigurationSaveMode.Modified);	0
33495882	33495731	getting timeout when sending a mail in cshtml	SmtpClient client = new SmtpClient();\nclient.Host = "smtp.gmail.com";\nclient.Port = 587;\nclient.EnableSsl = true; //ssl is required\nclient.DeliveryMethod = SmtpDeliveryMethod.Network;\nclient.UseDefaultCredentials = false;\nclient.Credentials = new NetworkCredential("your-email@gmail.com", "YourPassword");\nclient.Timeout = 20000; //increase the timeout	0
5196609	5194900	Help with QueryOver and WhereExists	Person personAlias = null;\n\nIList<Person> persons = \n        session.QueryOver<Person>(() => personAlias).WithSubquery\n          .WhereExists(QueryOver.Of<Cat>()\n             .Where(c => c.Age > 5)\n             .And(c => c.Owner.Id == personAlias.Id)\n             .Select(c => c.Owner))\n          .List<Person>();	0
27291511	27291439	How to sort an ObservableCollection<KeyValuePair<int, string>	TestList.OrderBy(p => p.Key)	0
13579749	13578192	Insert date-time from c# in sql server without parametrized query's	var expires = dtpExpires.Enabled ? "'" + tpExpires.Value.ToString() + "'" : "null";\n\n  string query = "INSERT INTO route (expires) Values (CONVERT(datetime, " + expires + "))";	0
10943279	10942957	programmatically change mysql connection string using c#	ConnectionStringSettings settings =\n    ConfigurationManager.ConnectionStrings["Punch_Uploader.Properties.Settings.testConnectionString"];\n\nstring connectString = settings.ConnectionString;    \n\nSqlConnectionStringBuilder builder =\n        new SqlConnectionStringBuilder(connectString);\n\nbuilder.DataSource = "172.23.2.52:3306";\nbuilder.InitialCatalog = "test";\nbuilder.UserID = "root";\nbuilder.Password = "test123";	0
5579812	5579774	Count number of Exceedence in a series	bool isAbove = false;\n        int count = yourList.Count(x =>\n        {\n            if (x > 1.5 && !isAbove)\n            {\n                isAbove = true;\n                return true;\n            }\n            else if (x < 1.5)\n            {\n                isAbove = false;\n            }\n            return false;\n        });	0
13031382	13028375	How to get one row from 1st table and others from 2nd table	public class Shop\n{\n   /// Shop Object\n   public string Shop { get; set; }\n   public List<Item> Items { get; set; }\n}\n\npublic class Item\n{\n   ///Items Object\n   public string Name { get; set; }\n   public string Picture { get; set; }\n}\n\n\npublic List<Item> ItemsList(int id)\n{\n   var item = from i in DB.Items\n   where i.ShopId == id\n   select new ShopItem\n   {\n      Name = i.Name,\n      Picture = i.ItemPictures\n   };\n  return item.ToList();\n}\n\n\npublic List<Shop> ShopItems(int ShopId)\n{\n   var Shopitms = from shop in DB.Shops\n   where shop.Id == ShopId && shop.IsActive == true && shop.IsDeleted == false\n   select new Shop\n   {\n      Shop = shop.Name,\n      Items = ItemsList(shop.Id)\n   }\nreturn ShopItms.ToList();\n}	0
19848879	19848804	Using FindAll instead of Find	var sought = txtCity.Text.Split(',')[0];\nstring.Join(",", cities.FindAll( s => s.Name == sought ).Select(zi => zi.ZipCode.ToString()));	0
11157283	11157058	How to find default property values of a control at runtime in C#	public static object GetDefaultPropertyValue(Type type, string propertyName)\n{\n        if (type.GetConstructor(new Type[] { }) == null)\n            throw new Exception(type + " doesn't have a default constructor, so there is no default instance to get a default property value from.");\n        var obj = Activator.CreateInstance(type);\n        return type.GetProperty(propertyName).GetValue(obj, new object[] { });\n}	0
16360479	16360279	Separating the column values of DataTable using LINQ	var newRows = dt.AsEnumerable()\n                .SelectMany(r => r.Field<string>("EHobbies")\n                                  .Split(',')\n                                  .Select(x => new { No = r.Field<int>("Eno"),\n                                                     Hobbies = x,\n                                                     Sal = r.Field<int>("Esal") }\n                                         )\n                           );\n\nDataTable result = new DataTable("EmployeeTable");\nresult.Columns.Add("Eno", typeof(int));\nresult.Columns.Add("EHobbies", typeof(string));\nresult.Columns.Add("Esal", typeof(int));\n\nforeach(var newRow in newRows)\n    result.Rows.Add(newRow.No, newRow.Hobbies, newRow.Sal);	0
30568149	30568050	c# Save Streamwriter after every 200 Cycles without Closing	System.IO.StreamWriter file = new System.IO.StreamWriter(path);\nint counter = 0;\nwhile(something_is_happening && my_flag_is_true)\n{\n    file.WriteLine(some_text_goes_Inside);\n    counter++;\n    if(counter < 200) continue;\n    file.Flush();\n    counter = 0;\n}\nfile.Close();	0
5902025	5901544	How do you remove rows from an Oracle table based on the maximum date in the table using delete?	DELETE FROM <yourtable> \n  WHERE <yourdatefield> < (SELECT Max(<yourdatefield>) FROM <yourtable>)	0
10250984	10250844	Map two string arrays without a switch	string result = "[placeholder2] Hello my name is [placeholder1]";\nvar placeHolders = new Dictionary<string, string>() { \n    { "placeholder1", "placeholderValue1" }, \n    { "placeholder2", "placeholderValue2" } \n};\n\nvar newResult =  Regex.Replace(result,@"\[(.+?)\]",m=>placeHolders[m.Groups[1].Value]);	0
18320253	18315580	How to get the friends activities using twitter api?	Console.WriteLine("\nStreamed Content: \n");\n        int count = 0;\n\n        (from strm in twitterCtx.UserStream\n         where strm.Type == UserStreamType.Site &&\n               strm.Follow == "15411837,16761255"\n         select strm)\n        .StreamingCallback(strm =>\n        {\n            Console.WriteLine(strm.Content + "\n");\n\n            if (count++ >= 10)\n            {\n                strm.CloseStream();\n            }\n        })\n        .SingleOrDefault();	0
2144172	2144154	How can I send ctrl+x with Sendkeys?	SendKeys.Send("^X")	0
12977218	12977046	Finding out which item the mouse is over in a list view while using itemssource	private ListViewItem FindListViewItem(DragEventArgs e)\n{\n    var visualHitTest = VisualTreeHelper.HitTest(_listView, e.GetPosition(_listView)).VisualHit;\n\n    ListViewItem listViewItem = null;\n\n    while (visualHitTest != null)\n    {\n        if (visualHitTest is ListViewItem)\n        {\n            listViewItem = visualHitTest as ListViewItem;\n\n            break;\n        }\n        else if (visualHitTest == _listView)\n        {\n            Console.WriteLine("Found ListView instance");\n            return null;\n        }\n\n        visualHitTest = VisualTreeHelper.GetParent(visualHitTest);\n    }\n\n    return listViewItem;\n}	0
18029707	18028786	Having a plugin interface with a value that's only available to the program and not the plugin itself	class PluginWithMetaData\n{\n  public PluginWithMetaData(Foo plugin)\n  {\n     Plugin = plugin;\n     MD5 = PluginFunctions.GetMD5(plugin);\n  }\n\n  public Foo Plugin { get; private set; }\n  public string MD5 { get; private set; } \n}	0
8106868	8106824	C# Pass string to method from foreach loop	private void updatedatabase( String url ) {\n    MessageBox.Show( url );\n}	0
2299195	2281930	WPF - Get the angle in degrees of a Vector3D as viewed from above	var axisZ = new Vector3D(0, 0, 1);\nvar angleZ = Vector3D.AngleBetween(axisZ, my3DObject.FrontDirection);\ndouble currentRotation = my3DObject.FrontDirection.X >= 0 ? angleZ : 360 - angleZ;	0
31578514	31578289	Strip seconds from datetime	DateTime dt = DateTime.Now;\ndt = dt.AddSeconds(-dt.Second);	0
6161280	6161254	Add comma to numbers every three digits using C#	double a = 1.5;\nInteraction.MsgBox(string.Format("{0:#,###0.#}", a));	0
17868178	17868003	How can I generate the list of number adding 5 to starting number?	class Program\n{\n    static void Main(string[] args)\n    {\n\n        List<int> numList = new List<int> { 3 };\n\n        for (int i = 0; i < 100; i++)\n        {\n            Console.WriteLine(numList[i]);\n            numList.Add(numList[i] + 5);\n        }\n        Console.Read();\n\n    }\n}	0
20548740	20534714	MethodAccessException for StreamReader in XNA Windows Phone App	StreamReader reader;\n\nprotected void LoadContent()\n{ \n  var stream = TitleContainer.OpenStream("map.txt");\n  reader = new StreamReader(stream);\n}	0
28508800	28507336	NUnit keeps running the wrong version of a .dll	configfile="Hl7ic.Engine.Test.dll.config"	0
16398156	16145187	How to open a page in a new window or tab from code-behind	string redirect = "<script>window.open('http://www.google.com');</script>"; \nResponse.Write(redirect);	0
24988778	24988746	Generating new random number onclick	protected void submitAnswerButton_Click(object sender, EventArgs e)\n    {\n        answerStatus.Visible = true;\n\n        int counter = 0;\n        int answer = randomNumber1 + randomNumber2;\n        if (mathAnswerTextBox.Text == answer.ToString())\n        {\n            answerStatus.Text = "Correct!";\n            randomNumber1 = random.Next(2, 22);\n            randomNumber2 = random.Next(2, 222);\n             num1Label.Text = Convert.ToString(randomNumber1);//add this line \n             num2Label.Text = Convert.ToString(randomNumber2); //and this line\n            num1Label.Visible = true;\n            num2Label.Visible = true;\n        }	0
6384525	6384451	how to generate random number which is combination of letters as well as digit?	Guid.NewGuid().ToString('N').SubString(0, [required length])	0
30886483	30866324	Problems to deserialize JSON data to IDbSet<T>	public class PersonContext\n{\n   public List<Person> Persons { get; set; }\n}	0
22140820	22140103	Chart Control customlabel aligment	area.AxisX.LabelAutoFitStyle = System.Web.UI.DataVisualization.Charting.LabelAutoFitStyles.None;	0
31036	31031	What's the best way to allow a user to browse for a file in C#?	using (OpenFileDialog dlg = new OpenFileDialog())\n{\n    dlg.Title = "Select a file";\n    if (dlg.ShowDialog()== DialogResult.OK)\n    {\n        //do something with dlg.FileName  \n    }\n}	0
20486570	20486559	Get a list of files in a directory in descending order by creation date using C#	DirectoryInfo dir = new DirectoryInfo (folderpath);\n\nFileInfo[] files = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();	0
4453067	4444421	Convert a Byte array to Image in c# after modifying the array	for (int i = 0; i < img.Length; i++)\n        {\n            if (i < 54)\n            {\n                //copy the first 54 bytes from the header\n                _cyph[i] = img[i];\n            }else{\n                //encrypt all the other bytes\n                _cyph[i] = encrypt(img[i]);\n            }\n        }	0
28050206	28050189	C# arrays use of unassigned local variable	int[] x = new int[4];	0
912406	912373	.net console app stop responding when printing out lots of chars in a row	using System;\n\nclass Test\n{   \n    static void Main(string[] args)\n    {\n        int i=32;\n        while (true)\n        {\n            Console.Write((char)i);\n            i++;\n            if (i == 127)\n            {\n                i = 32;\n            }\n        }\n    }\n}	0
10131691	10131641	Sorting Nearest Numbers by using array	var result = array.OrderBy(i => Math.Abs(i - value))\n             .ThenBy(i => i < value)\n             .ToArray();	0
522195	522080	DataGridView Autogeneratecolumns as TextBox instead of label	Public Class MyGrid\nInherits GridView\n\n\nPrivate Sub MyGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Me.RowDataBound\n  If Me.AutoGenerateColumns = True Then\n    If e.Row.RowType = DataControlRowType.DataRow Then\n        For Each c As TableCell In e.Row.Cells\n            Dim tb As New TextBox()\n            tb.Text = c.Text\n            c.Controls.Clear()\n            c.Controls.Add(tb)\n        Next\n    End If\n    End If\nEnd Sub	0
18245291	18244849	How can I convert a C# multidimensional List to VB.Net	Dim list As List(Of Integer()) = New List(Of Integer())()\n        list.Add(New Integer()() = { Class1.mStartPoint, Class1.mEndPoint })\n        For i As Integer = CInt(list(Class1.mColumnPoint).GetValue(0))To CInt(list(Class1.mColumnPoint).GetValue(1)) - 1\n        Next	0
20525550	20525188	5 Day Forecast using Nodes	var fiveDays = channel.SelectSingleNode("item").SelectNodes("yweather:forecast", manager);\nforeach (XmlNode node in fiveDays)\n{\n    var text = node.Attributes["text"].Value;\n    var high = node.Attributes["high"].Value;\n    var low = node.Attributes["low"].Value;\n}	0
30754085	30753114	How to close a file handle which came from a parent process C#	Environment.CurrentDirectory	0
2879413	2879410	How to Get handle of a window and disable the Keyboard inputs using c#?	GetForegroundWindow()	0
8113309	8113251	How to draw characters to a Texture2D?	PresentationParameters pp = graphicsDevice.PresentationParameters;\nbyte width = 20, height = 20; // for example\n\n// pp.BackBufferWidth, pp.BackBufferHeight // for auto x and y sizes\nRenderTarget2D render_target = new RenderTarget2D(graphicsDevice,\nwidth, height, false, pp.BackBufferFormat, pp.DepthStencilFormat,\npp.MultiSampleCount, RenderTargetUsage.DiscardContents);\n\ngraphicsDevice.SetRenderTarget(render_target);\ngraphicsDevice.Clear(...); // possibly optional\nspriteBatch.Begin();\n// draw to the spriteBatch\nspriteBatch.End();\ngraphicsDevice.SetRenderTarget(null); // Otherwise the SpriteBatch can't\n// be used as a texture, this may also need to be done before using the\n// SpriteBatch normally again to render to the screen.\n\n// render_target can now be used as a Texture2D	0
17855800	17855707	Password requirement not same as email regex c#	[NotEqualTo("EmailAddress", ErrorMessage="Passwords must be different that EmailAddress")]\npublic string Password{ get; set; }	0
25938025	25937687	Select a single element that occurs in two lists	var namesToMatch = GetIdentityNamePatterns(type);\n\nvar property = entityProperties\n    .FirstOrDefault(p => namesToMatch.Any(n => x => x.Name.Equals(n)));	0
34335990	34335090	Serializing DataTable in C# uses a lot of memory - how to improve this	List<T>	0
18458375	18457955	Wait for other transaction to commit/rollback before beginning another transaction?	cmd.Connection.BeginTransaction(IsolationLevel.ReadCommitted);	0
22563215	22562893	How to enable and disable context menu items on specific tree nodes using C#	private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n    {\n        if (e.Node.Name.Equals("Node1"))\n        {\n            DisableHide(true);\n        }\n        else\n        {\n            DisableHide(false);\n        }\n    }\n\n    private void DisableHide(bool state)\n    {\n        menuItem1.Enabled = state;\n    }	0
32213349	32212965	C# DataGridView, column multiplier format	private void dataGridView1_CellFormatting(object sender,\n    DataGridViewCellFormattingEventArgs e)\n    {\n        if (e.ColumnIndex == 0)\n        {\n            e.Value = Convert.ToInt32(e.Value.ToString()) * 2000 // apply     formating here\n            e.FormattingApplied = true;\n        }\n        //repeat for additional columns\n     }	0
4360543	4358696	How to get the contents of a HTML element using HtmlAgilityPack in C#?	public static string GetComments(string html)\n{\n    HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml(html);\n    string s = "";\n    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//ol"))\n    {\n        s += node.OuterHtml;\n    }\n\n    return s;\n}	0
21706700	21706156	.net webapi filepath as parameter	"api/{controller}/download/{*fileName}"	0
8054653	8054351	Multiple entities sharing the same role relationship table	static class RoleBuilder {\n    static IEnumerable<Role> Fetch<T>(int id) {\n        switch(typeof(T)) { ... }\n    }\n\n    static bool Save<T>(IEnumerable<Role> roles, int id) {\n        switch(typeof(T)) { ... }\n    }\n}	0
1423737	1422936	In LINQ to objects, how to set an object property to null if it equals "folder"?	items\n  .Where(i => i.FileExtension == "folder")\n  .ToList()\n  .ForEach(i => i.FileExtension = null);	0
5308376	5308208	Fire and Forget Sql Server Stored Procedure from C#	string sql = "EXEC dbo.sp_start_job 'THE NAME OF YOUR JOB'";	0
30527872	30517399	Inserting XML to XMLDocument	XmlDocumentFragment xmlfrag = xmlRequest.CreateDocumentFragment();\nxmlfrag.InnerXml = xmlSubjects ;\nxmlRequest.DocumentElement.InsertAfter(xmlfrag,xmlRequest.DocumentElement.FirstChild);	0
15701144	15699135	How to merge two adjacent XML elements having same class?	//elem is an XElement containing the XML\nvar duplicateRanges = (\n    from head in elem.Elements()\n    let currentClass = (string)head.Attribute("class")\n    let others = head.ElementsAfterSelf().TakeWhile(next => {\n        if (next.NodesBeforeSelf().LastOrDefault().NodeType == XmlNodeType.Text) { return false; }\n        return (string)next.Attribute("class") == currentClass;\n    })\n    where others.Any()\n    select new {\n        head,\n        others\n    }).ToList();\nforeach (var range in duplicateRanges) {\n    range.head.Value=(string)range.head + String.Join("", from o in range.others select (string)o);\n    foreach (var other in range.others) {\n        other.Remove();\n    }\n}	0
23019634	22995814	Getting Additional Data from SOAP response	[SoapDocumentMethod( "&&&", RequestElementName = "SubscriptionQueryRequest", RequestNamespace = "&&&", ResponseNamespace = "&&&", Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Wrapped )]\n[return: XmlAnyElement]\npublic List<XmlNode> SubscriptionQuery(string SubscriberId, int SortType, bool SortDescending, string Service, string ReferenceID, string SubscriptionName, int StartingSequence, int ResultCount )\n{\n    object[] results = this.Invoke( "SubscriptionQuery", new object[] {\n            SubscriberId, \n            SortType, \n            SortDescending,\n            Service,\n            ReferenceID,\n            SubscriptionName, \n            StartingSequence,\n            ResultCount\n    } );\n    return ( (List<XmlNode>)( results[0] ) );\n}	0
3439046	3438617	Problem with sorting jagged array	public int Compare(object x,object y)\n{\n    // changed code\n    if (x == null && y == null)\n        return 0;\n    if (x == null)\n        return 1;\n    if (y == null)\n        return -1;\n    // end of changed code\n    int[][] arrayA = (int[][])x;\n    int[][] arrayB = (int[][])y;\n\n     int resultA = arrayA[1].Sum();\n     int resultB = arrayB[1].Sum();\n\n    return resultA.CompareTo(resultB);          \n}	0
679755	679740	Fastest way to format a phone number in C#?	String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))\n\nWill result in (123) 456-7890 x 123	0
30579817	30577738	How to define many to many with attributes in Entity Framework	public class EmployeeCar {\n    [Key, Column(Order = 0)]\n    public int CarId { get; set; }\n    [Key, Column(Order = 1)]\n    public int EmployeeId { get; set; }\n\n    public virtual Car Car { get; set; }\n    public virtual Employee Employee { get; set; }\n\n    public DateTime DateFrom{ get; set; }\n    public DateTime DateTo { get; set; }\n}	0
19792893	19792351	How to access another variable C#	public class AmmoCounter : MonoBehaviour {\n\n    public int ammo;\n    private Pistol _pistol = GetComponentInChildren<Pistol>();     \n\n    void Update () {\n        ammo = _pistol.ammoMagazine;\n        guiText.text = "Pistol: " + ammo + "/7";\n    }\n}	0
5030444	5030397	Splitting a collection with LINQ	var grouped = groups.GroupBy(g => g.Group);	0
14129566	14129545	Creating a select list from an array	model.month = months\n    .Select((r,index) => new SelectListItem{Text = r, Value = index.ToString()});	0
16038225	16014079	Delete all rows in sharepoint list using Client Context and CAML Query	ListItemCollection listItems = oList.GetItems(CamlQuery.CreateAllItemsQuery());\n                    clientContext.Load(listItems,\n                                      eachItem => eachItem.Include(\n                                      item => item,\n                                      item => item["ID"]));\n                    clientContext.ExecuteQuery();\n\n                    var totalListItems = listItems.Count;\n                    Console.WriteLine("Deletion in " + currentListName + "list:");\n                    if (totalListItems > 0)\n                    {\n                       for (var counter = totalListItems - 1; counter > -1; counter--)\n                       {\n                           listItems[counter].DeleteObject();\n                           clientContext.ExecuteQuery();\n                           Console.WriteLine("Row: " + counter + " Item Deleted");\n                       }\n\n                    }	0
10412559	10411520	Export Grid view to excel and save excel file to folder	private void ExportGridView()\n{\n    System.IO.StringWriter sw = new System.IO.StringWriter();\n    System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);\n\n    // Render grid view control.\n    gvFiles.RenderControl(htw);\n\n    // Write the rendered content to a file.\n    string renderedGridView = sw.ToString();\n    System.IO.File.WriteAllText(@"C:\Path\On\Server\ExportedFile.xlsx", renderedGridView);\n}	0
6973253	6972997	String was not recognized as a valid DateTime, asp.net	[TypeLibraryTimeStampAttribute]	0
18803885	18801296	Can a constructor be pre-empted?	class BoxedInt2\n{\n  public readonly int _value = 42;\n  void PrintValue()\n  {\n    Console.WriteLine(_value);\n  }\n}\n\nclass Tester\n{\n  BoxedInt2 _box = null;\n  public void Set() {\n    _box = new BoxedInt2();\n  }\n  public void Print() {\n    var b = _box;\n    if (b != null) b.PrintValue();\n  }\n}	0
17757785	17757304	Build USPS web service request	XDocument requestXml = new XDocument(\n    new XElement("CityStateLookupRequest",\n        new XAttribute("USERID", userID),\n        new XElement("ZipCode",\n            new XAttribute("ID", "0"),\n            new XElement("ZIP5", zip5)));\nvar requestUrl = new UriBuilder("http://production.shippingapis.com/ShippingAPITest.dll");\nrequestUrl.Query = "API=CityStateLookup&XML=" + requestXml.ToString();\nvar request = WebRequest.Create(requestUrl.Uri);	0
10410475	10410002	Winforms MDI distortion of labels	private Color myColor = Color.FromArgb(104, 195, 198);\nprotected override void OnPaint(PaintEventArgs e)\n{\n    ControlPaint.DrawBorder(e.Graphics, ClientRectangle, myColor, ButtonBorderStyle.Solid);\n    base.OnPaint(e);\n}	0
2047114	2047022	How to substitute place holders in a string with values	string command = "%ans[1]%*100/%ans[0]%";\nstring[] array = new string[] { "test1", "test2" };\nfor (int iReplace = 0; iReplace < array.Length; iReplace++)\n    command = command.Replace(String.Format("%ans[{0}]%", iReplace), array[iReplace]);	0
31965355	31942645	Where to configure FAKE to use C# 6 compiler (instead of C# 5) when building?	Microsoft.Net.Compilers	0
935912	935894	TDD - Want to test my Service Layer with a fake Repository, but how?	public class RegistrationService: IRegistrationService\n{\n    public RegistrationService(IRepository<User> userRepo)\n    {\n        m_userRepo = userRepo;\n    }\n\n    private IRepository<User> m_userRepo;\n\n    public void Register(User user)\n    {\n        // add user, etc with m_userRepo\n    }\n}	0
12749825	12749259	A unique ID for a poll response	Guid.NewGuid()	0
33106462	33105825	Accessing USB Drives from 'Computer'	File.CopyTo(CopyToDrive + File.Name, false);	0
11010494	10910047	how to create a custom JSON in C# and what should the return value be?	[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n    [WebMethod]\n    public List<StandortHelper.REGION> LAND()\n    {\n        return StandortHelper.LAND();\n    }	0
16719147	16719071	Moving in text file with C#	var text = File.ReadAllLines("path"); //read all lines into an array\nvar foundFirstTime = false;\nfor (int i = 0; i < text.Length; i++)\n{\n    //Find the word the first time\n    if(!foundFirstTime && text[i].Contains("word"))\n    {\n        //Skip 3 lines - and continue\n        i = Math.Min(i+3, text.Length-1);\n        foundFirstTime = true;\n    }\n\n    if(foundFirstTime && text[i].Contains("word"))\n    {\n        //Do whatever!\n    }\n}	0
7586543	7584932	How to send my program to background while a certain process is running	private void button1_Click(object sender, EventArgs e) {\n        var prc = new Process();\n        prc.EnableRaisingEvents = true;\n        prc.Exited += processExited;\n        prc.StartInfo = new ProcessStartInfo("notepad.exe");\n        prc.Start();\n        this.Hide();\n    }\n\n    private void processExited(object sender, EventArgs e) {\n        this.BeginInvoke(new Action(() => {\n            this.Show();\n            this.BringToFront();\n        }));\n    }	0
11296898	11296569	Using UserPrincipal to check if local admin	foreach (Principal p in usr.GetAuthorizationGroups())\n{\n    if (p.ToString() == "Administrators")\n    {\n        result = true;\n    }\n}	0
14415107	14414891	Defining and extracting variable in Reguar Expression	Match match = Regex.Match("aaa 113", @"(?<word>\w*)(?<space>\s+)(?<num>\d+)");\nstring words = match.Groups["word"].Value;              //"aaa"\nstring spaces = match.Groups["space"].Value;            //" "\nstring nums = match.Groups["num"].Value;                //"113"	0
32451600	32451507	Can I use Store procedure without EF in .Net, If yes then How?	SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");\n    SqlCommand cmd = new SqlCommand();\n    SqlDataReader reader;\n\n    cmd.CommandText = "StoredProcedureName";\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.Connection = sqlConnection1;\n    //If your procedure has parameters you can add parameters too\n    //cmd.Parameters.AddWithValue("parameter", "value");\n\n\n    sqlConnection1.Open();\n\n    reader = cmd.ExecuteReader();\n    // Data is accessible through the DataReader object here.\n\n    sqlConnection1.Close();	0
21303798	21303166	Show a message box after usercontrol fully displayed	public partial class SelectAccounts : UserControl\n    {\n        bool _Shown = false;\n        private void SelectAccounts_Paint(object sender, PaintEventArgs e)\n        {\n            if (!this._Shown)\n            {\n                this._Shown = true;\n                MessageBox.Show("something");\n            }\n        }\n    }	0
31351635	31351424	Get files without looking at a specific directory or looking two levels down	var list = Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly).\n    SelectMany(sampleDir => Directory.EnumerateDirectories(sampleDir, "*", SearchOption.TopDirectoryOnly)).\n    SelectMany(textdir => Directory.EnumerateFiles(textdir, "grouptest.log", SearchOption.TopDirectoryOnly));	0
23750380	23750256	Split an interface into two new interfaces without breaking the client code?	[Obsolete]\ninterface IFileReader {...}\n\nclass MySuperReader : IFileReader, IExcelFileReader, IExcelFileReader\n{\n   void ReadExcelFile(string filePath) {...}\n   void ReadXMLFile(string filePath) {...}\n   void WriteExcelFile() {...}\n   void WriteXMLFile() {...}\n}	0
12219906	12218780	C# method parameter as array with specific size and index names?	/// <summary>\n/// Summary of the method, which is seperated nicely from below in tool tip\n/// </summary>\n/// <param name="parameters">\n/// (\n/// <c>String </c><param name="paramOne" />, \n/// <c>Int </c><param name="paramTwo" /> \n/// )\n/// </param>	0
30920106	30920040	Convert SQL to linq statement	var result =(from a in _applicationRepository.GetList(a => a.ID == applicationId)\n                      from r in _roleRepository.GetList(r => r.ApplicationId == a.ID && r.Name == rolename)\n                      from au in _authorizationRepository.GetList(au => au.ApplicationId == a.ID && r.ID == au.RoleId)\n                      from u in _userRepository.GetList(u => u.ID == au.UserId && u.UserPrincipalName == username)\n                      where a.EnableApplication == true && a.EnableAuthorization == true && a.EnableRoles == true && a.ID == applicationId\n                      //select 1, or a, or anything, it doesn't really mind\n                      select 1).Any();	0
12150964	12150758	Send Windows key keypress into application	[DllImport("user32.dll")]\nprivate static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);\n[DllImport("user32.dll")]\nprivate static extern bool UnregisterHotKey(IntPtr hWnd, int id);\n\npublic const int MOD_WIN = 0x00000008;\npublic const int KEY_W = 0x00000057\n\npublic static void RegisterKeys()\n{\n    RegisterHotKey((IntPtr)this.Handle, 1, MOD_WIN, KEY_W);\n}\n\nprotected override void WndProc(ref Message m)\n{\n    base.WndProc(ref m);\n\n    if (m.Msg == 0x0312)\n        this.Visible = !this.Visible;\n}	0
28102334	28102280	Changing text of buttons to sequential number 0-9	if (item is Button)\n{\n    ((Button)item).Text = i.ToString();\n    i++;\n}	0
25268612	24377066	Parse uploaded file, then save file contents to database and display to screen(webpage)	public ActionResult Upload(HttpPostedFileBase File )\n    {\n\n        // Verify that the user selected a file\n        if (File != null && File.ContentLength > 0)\n        {\n\n            StreamReader csvReader = new StreamReader(File.InputStream);\n            {\n                string inputLine = "";\n                while ((inputLine = csvReader.ReadLine()) != null)\n                {\n                    string[] values = inputLine.Split(new Char[] { ',' });\n                    Movie movie = new Movie();\n                    movie.Title = values[0];\n                    movie.ReleaseDate = DateTime.Parse(values[1]);\n                    movie.Genre = values[2];\n                    movie.Price = Decimal.Parse(values[3]);\n                    db.Movies.Add(movie);\n                    db.SaveChanges();\n                }\n                csvReader.Close();\n              }\n        }\n       // redirect back to the index action to show the form once again\n        return RedirectToAction("Index");\n    }	0
3634208	3634093	Changing language/culture in a MySQL/Dblinq project	calendar = Calendar.findById(1);\nprint calendar.event_date.toString("%d/%m/%Y"); # <- prints 03/10/2010	0
23696963	23681377	How to get folder path of Installed application, from Visual Studio 2012	StringBuilder sb = new StringBuilder();\nsb.Append(Environment.GetFolderPath(Environment.SpecialFolder.Programs));\nsb.Append("\\");\n//publisher name is OneApp\nsb.Append("OneApp");\nsb.Append("\\");\n//product name is OneApp\nsb.Append("OneApp.appref-ms");\nstring shortcutPath = sb.ToString();\nConsole.WriteLine(shortcutPath);\n\n//Start the One App installed application from shortcut\nSystem.Diagnostics.Process.Start(shortcutPath);	0
2294199	2294180	Sort items in datatable	DataTable dt; //comes from somewhere...\nDataView dv = new DataView(dt)\ndv.Sort = "Name ASC";\nforeach(DataRowView drv in dv)\n    //....	0
11037629	11037349	Open pdf from hyperlink in gridview	protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n\n if (e.Row.RowType == DataControlRowType.DataRow)\n     {\n            DataRow row = ((System.Data.DataRowView)e.Row.DataItem).Row;\n            HyperLink hlink = e.Row.FindControl("HL") as HyperLink;\n            if (hlink!=null)\n            {\n                string url = string.Format("~/Docs/{0}",row["FileName"]);\n                hlink.NavigateUrl = url;\n                hlink.Text = "Read";\n            }\n     } \n}	0
7706643	7689935	Save Image From Webrequest in C#	protected void Page_Load(object sender, EventArgs e)\n    {\n        string strFile = DateTime.Now.ToString("dd_MMM_yymmss") + ".jpg";\n      FileStream log = new FileStream(Server.MapPath(strFile),\n       FileMode.OpenOrCreate);\n        byte[] buffer = new byte[1024];\n        int c;\n        while ((c = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)\n        {\n            log.Write(buffer, 0, c);\n        }\n       //Write jpg filename to be picked up by regex and displayed on flash html page.\n        Response.Write(strFile);\n        log.Close();\n\n    }	0
9485522	9477158	Metro Application How to Read XML API?	private async void Button_Click(object sender, RoutedEventArgs e)\n        {\n            string UrlString = "http://v1.sidebuy.com/api/get/73d296a50d3b824ca08a8b27168f3b85/?city=nashville&format=xml";\n            var xmlDocument = await XmlDocument.LoadFromUriAsync(UrlString);\n\n            //read from xmlDocument for your values.\n         }	0
2502523	2496814	Disable selecting in WPF DataGrid	dgGrid.UnselectAll();	0
30100332	30100141	How to pass derived type to abstract class with singleton	public class DerivedService<T> : Service<T> where T : DerivedService<T>, new\n{\n    { ... } \n}	0
8349935	8349782	Concatting Lines into List of strings	var units = new Regex("UNIT, PARTS",RegexOptions.Multiline)\n          .Split(myString)\n           .Where(c=> !string.IsNullOrEmpty(c)).ToArray();	0
4893199	4893147	Slicing a FormCollection by keys that start with a certain string	var appSettings = formCollection.AllKeys\n    .Where(k => k.StartsWith("AppSettings."))\n    .ToDictionary(k => k, k => formCollection[k]);	0
21474156	21473720	How to edit/update in dynamic table	static void Main(string[] args)\n{\n    DataTable dt = GetTable();\n\n    DataRow[] dr = dt.Select("ID=2 and F_Name='raj'");\n    if (dr !=null)\n    {\n        foreach (var item in dr)\n        {\n            item["F_name"] = "rajan";\n        }\n    }\n\n}\n\nstatic DataTable GetTable()\n{\n    DataTable dt = new DataTable();\n    dt.Columns.Add("ID");\n    dt.Columns.Add("F_name");\n    dt.Columns.Add("L_name");\n\n    dt.Rows.Add("1", "mit", "jain");          \n    dt.Rows.Add("2", "raj", "patel");\n    dt.Rows.Add("3", "anki", "patel");\n    dt.Rows.Add("4", "alpa", "dumadiya");\n\n    return dt;\n}	0
608321	608274	Finding Node of Matching Raw Html in an HtmlAgility HtmlDocument	HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("YOUR_TAG_SELECTOR");\n\n            if (nodes != null)\n            {\n                foreach (HtmlNode node in nodes)\n                {\n                    if (node.InnerHtml.ToLower().Trim() == "YOUR_MATCH")\n                    {\n                        //success routine\n                        break;\n                    }\n                }\n            }	0
16058818	16058509	How do I open a docx for writing?	Word._Application oWord;\nWord._Document oDoc;\nobject oMissing = Type.Missing;\noWord = new Word.Application();\noWord.Visible = true;\n\n//Add Blank sheet to Word App\noDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); \n\noWord.Selection.TypeText("Write your text here");	0
29670015	29668988	Is it possible to send HEAD request with RestSharp?	restRequest.Parameters.Clear();\nrestRequest.AddHeader("Accept", "*/*");	0
2338473	2337629	Getting Application Path - WPF versus Windows Service	private string GetExeDir()\n    {\n        System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();\n        string codeBase = System.IO.Path.GetDirectoryName(ass.CodeBase);\n        System.Uri uri = new Uri(codeBase);\n        return uri.LocalPath;\n    }	0
9093011	8882512	Halftone effect in with gdi+	using (var g = Graphics.FromImage(bmpPattern))\n        {\n            g.Clear(Color.Black);\n            g.SmoothingMode = SmoothingMode.HighQuality;\n            for (var y = 0; y < bmp.Height; y += 10)\n                for (var x = 0; x < bmp.Width ; x += 6)\n                {\n                    g.FillEllipse(Brushes.White, x, y, 4, 4);\n                    g.FillEllipse(Brushes.White, x + 3, y + 5, 4, 4);\n                }\n        }	0
7238591	2416463	C# DataSet To Xml, Node Rename	ds.DataSetName = "ROWS";\nds.Tables[0].TableName = "ROW";\nds.WriteXml(myXmlWriter);\nmyXmlWriter.Close();	0
16726216	16725866	Foreach loop for three List<string>	public string saveEachTask(string imageData, string desc, string tid)\n{\n  var imglist = imageData.Split(',').ToList();\n  var desclist = desc.Split(',').ToList();\n  var idlist = tid.Split(',').ToList();\n\n  int maxLength = Math.Max(imglist.Count, Math.Max(desclist.Count, idlist.Count));\n\n  for (int i = 0; i < maxLength; ++i)\n  {\n    string imgItem = (i < imglist.Count ? imglist[i] : null);\n    string descItem = (i < desclist.Count ? desclist[i] : null);\n    string idItem = (i < idlist.Count ? idlist[i] : null);\n\n    // TODO: Process imgItem, descItem, idItem\n  }\n\n  return "Saved Succesfully";\n}	0
3723822	3723789	How to convert .NET Trackbar control integer value to floating-point percentage	int trackBarValue = trackBar.Value;\n  float percentage = trackBarValue / 100.0;	0
12154324	12154255	Getting the Value of a Method name itSelf into a string	System.Reflection.MethodBase.GetCurrentMethod().Name;	0
7072436	7072389	Linq to Entity Framework m2m query with simple string constraint	var shirtsOfAParticularType = db.Shirts.Where(shirt => shirt.Types.Any(type => type.TypeName == "someTypeName")).ToList();	0
24096033	24096018	Access a button using its string name and change its back color	oleDbConnection.Open();\nOleDbCommand command = new OleDbCommand("SELECT * FROM CUSTOMER WHERE FLIGHTNO = '" + variables.depFlightNo + "'", oleDbConnection);\n\nOleDbDataReader reader = command.ExecuteReader();\nwhile (reader.Read())\n    {\n        string seat = reader[3].ToString();\n        foreach (Button s in this.Controls) \n//if the controls are in different place\n//like panel or groupbox change "this.Controls" to "groupBox.Controls"\n        {\n           if (s.Name == seat)\n           {\n              s.BackColor = Color.Yellow;\n           }\n        }\n\n    }\n    reader.Close();	0
24793196	24793122	Read String From Text file and use it as a TimeSpan	var startLine = lines[0].Split(',');\nvar endLine = lines[1].Split(',');\n\nvar startHour = int.Parse(startLine[0]);\nvar startMin = int.Parse(startLine[1]);\nvar startSec = int.Parse(startLine[2]);\n\nvar endHour = int.Parse(endLine[0]);\nvar endMin = int.Parse(endLine[1]);\nvar endSec = int.Parse(endLine[2]);\n\nTimeSpan start = new TimeSpan(startHour, startMin , startSec);\nTimeSpan end = new TimeSpan(endHour, endMin, endSec);	0
8329998	8327086	WPF DataGrid double click via commands + INotifyPropertyChanged?	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"\n...\n<DataGrid SelectedItem={Binding MySelectedItem, Mode=TwoWay}>\n  <i:Interaction.Triggers>\n    <i:EventTrigger EventName="MouseDoubleClick">\n        <i:InvokeCommandAction Command="{Binding YourCommand}" />\n    </i:EventTrigger>\n  </i:Interaction.Triggers>\n</DataGrid>	0
22594619	22594535	Strip out Unknown characters out of string	output = Regex.Replace(output, @"[^\u0020-\u007F]", String.Empty);	0
14772312	14772135	Open Gl Tao Framework rotating an group of object around their axes	Gl.glTranslatef(0, 0, zoom);\nGl.glRotatef(rotate, 0, 1, 0);	0
4302150	4302025	How to loop through the values of a particular column in datatable?	}\n    static void Main(string[] args)\n    {\n\n        foreach (DataRow row in GetDataTable().Rows)\n        {\n\n            object cellData = row["Column 1"];\n            Console.WriteLine(cellData);\n\n        }\n\n\n    }\n}	0
22470602	22453731	how to update redis list in C#	var lstTemp = redisUsers.Lists["Order_Cash|123|1"].ToList();\n\nforeach(var item in lstTemp){\n\n// Update here\n}	0
11438588	11436948	MonthCalendar BoldedDates causes Beep with DateChanged Event	private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) {\n        this.BeginInvoke(new Action(() => {\n            DateTime[] dteBolded = { new DateTime(2012, 9, 28, 0, 0, 0), new DateTime(2012, 9, 21, 0, 0, 0) };\n\n            this.monthCalendar1.RemoveAllBoldedDates();\n            this.monthCalendar1.BoldedDates = dteBolded;\n        }));\n    }	0
3964962	3964942	How to access resource file in C#?	var zipFile = MyNamespace.Properties.Resources.My_Zip_File;	0
27565599	15921013	Checking if SMS message is in standard GSM alphabet	public static bool IsUnicodeSms(this string message)\n{\n    var strMap = new Regex(@"^[@?$???????????_????!""#%&'()*+,-./0123456789:;<=>? ?ABCDEFGHIJKLMNOPQRSTUVWXYZ??????abcdefghijklmnopqrstuvwxyz?????^{}\[~]|?]+$");\n    return !strMap.IsMatch(message);\n}	0
9683420	9683051	Setting a relation without fetching the object with NHibernate	ISession.Load	0
794801	787610	How do you copy a file into SharePoint using a WebService?	WebRequest request = WebRequest.Create(?http://webserver/site/Doclib/UploadedDocument.xml?);\nrequest.Credentials = CredentialCache.DefaultCredentials;\nrequest.Method = "PUT";\nbyte[] buffer = new byte[1024];\nusing (Stream stream = request.GetRequestStream())\n{\n    using (MemoryStream memoryStream = new MemoryStream())\n    {\n        dataFile.MMRXmlData.Save(memoryStream);\n        memoryStream.Seek(0, SeekOrigin.Begin);\n        for (int i = memoryStream.Read(buffer, 0, buffer.Length); i > 0;\n            i = memoryStream.Read(buffer, 0, buffer.Length))\n        {\n            stream.Write(buffer, 0, i);\n        }\n    }\n}\n\nWebResponse response = request.GetResponse();\nresponse.Close();	0
29624527	29624264	Execute code with Application Pool load	using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        public class NewConfigClass\n        {\n            public string MyConfigParameter {get;set;}\n        }\n\n        public class LegacyNeedsConfig\n        {\n            public string ConfigurableSetting {get;set;}\n            public LegacyNeedsConfig(NewConfigClass config)\n            {\n                this.ConfigurableSetting = config.MyConfigParameter;\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            NewConfigClass config = new NewConfigClass();\n            config.MyConfigParameter = "hello world"; //read from web or app config\n\n            LegacyNeedsConfig legacy = new LegacyNeedsConfig(config);\n\n            Console.WriteLine(legacy.ConfigurableSetting);\n        }\n\n    }\n}	0
27128348	27125494	Get index of selected row in filtered DataGrid	// dgDocRow is DataGrid\nBindingManagerBase bm = this.dgDocRow.BindingContext[this.dgDocRow.DataSource, this.dgDocRow.DataMember];\nDataRow dr = ((DataRowView)bm.Current).Row;	0
5705854	5705794	How can I use a perfomance counter for my process? C#	var stopwatch = new System.Diagnostics.Stopwatch();\n      stopwatch.Start();\n      ... do work here\n      stopwatch.Stop();\n      TimeSpan ts = stopwatch.Elapsed;\n      Console.WriteLine("  Elapsed {0:N2}", ts.TotalSeconds);	0
32816376	32816321	How to find count of unselected items in a Checkboxlist in C#	var count = this.MyCheckboxlist.Items.Cast<ListItem>().Count(li => li.Selected == false)	0
2909563	2909542	extract from database if key contatin string in SQL 2008using c#	string sqlQuery = "SELECT imagelink FROM Dataimages where (imagename like '%" + keywords + "%')"	0
16319417	16317510	How to programmatically change Windows update option?	// using WUApiLib;\nAutomaticUpdatesClass auc = new AutomaticUpdatesClass();\nauc.Settings.NotificationLevel = AutomaticUpdatesNotificationLevel.aunlNotifyBeforeInstallation;\nauc.Settings.Save();	0
31819690	31819582	How do I refresh DataGridView?	private void Form1_Load(object sender, EventArgs e)\n{\n    RefreshGrid();\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    RefreshGrid();\n}\n\nvoid RefreshGrid()\n{\n    connection.Open();\n\n    OleDbCommand command = new OleDbCommand();\n    command.Connection = connection;\n    string query = "select * from Customer";\n    command.CommandText = query;\n\n    OleDbDataAdapter DA = new OleDbDataAdapter(command);\n    DT = new DataTable();\n    DA.Fill(DT);\n    dataGridView1.DataSource = DT;\n\n    connection.Close();\n}	0
27365292	27362814	Data List Control text Search	void CustomerIndicators_ItemDataBound (Object sender, DataListItemEventArgs e)\n  {\n\n if (e.Item.ItemType == ListItemType.Item || \n     e.Item.ItemType == ListItemType.AlternatingItem)\n {\n    Label CustomerTypeLabel = (Label)e.Item.FindControl("Label1");\n\n    DataRowView drv= ((DataRowView)e.Item.DataItem).ToString();\n    string CustomerType = drv.Row["CustomerType"].ToString();\n\n    switch(CustomerType){\n    case "R":\n    case "P":\n    case "Y":\n          CustomerTypeLabel.Font.Bold = true;\n          break;\n\n    }\n\n }	0
7777823	7777765	Dynamic where clause in dapper	and c.Name = @name	0
25644175	25644072	Casting a LINQ date to a DateTime in C#?	IEnumerable<Guid> uids = xml.Descendants("Photo")\n   .Where(e => XmlConvert.ToDateTime(e.Element("Date").Value, XmlDateTimeSerializationMode.Utc) < DateTime.Now.AddMonths(-6))\n       .Select(e => Guid.Parse(e.Attribute("UID").Value))\n       .ToList();	0
24322715	24322510	How do I find the 2D point given a start point a angle and a distance	Vector2 shotStartPos = transform.TransformPoint(positionOnShip);	0
26007153	26006522	How to Serialize to a "Collection with an Attribute" Using the XML Serializer	[XmlElement(ElementName = "Listing")]\npublic ClassificationWrapper classificationWrapper { get; set; }\n\npublic class ClassificationWrapper\n{\n    [XmlAttribute("reference")]\n        public string ref= "MyReference";\n\n        [XmlElement("Classification", typeof(Classification))]\n        public List<Classification> classifications { get; set; }\n\npublic ClassificationWrapper() { this.classifications = new List<Classification>(); }\n}\npublic class Classification\n{\n       [XmlAttribute("Name")]\n       public string name { get; set; }\n\n       [XmlText]\n       public string Value { get; set; }\n}	0
12670154	12670092	Fix a Split Container Control in Windows Forms	MySplitContainer.IsSplitterFixed = true;	0
18002341	18001778	Filter a list based on many parameters and gather the result in another list	var filteredCards =\n    from card in mListCards\n    where _color == "ALL" || card.mCardColor == _color\n    where _type == "ALL" || card.mCardType == _type\n    where _rarity == "ALL" || card.mCardRarity == _rarity\n    select card;	0
15693225	15693188	Rx extension to keep generating events for N seconds?	// This will generate events repeatedly\nvar interval = Observable.Interval(...);\n\n// This will generate one event in N seconds\nvar timer = Observable.Timer(TimeSpan.FromSeconds(N));\n\n// This will combine the two, so that the interval stops when the timer\n// fires\nvar joined = interval.TakeUntil(timer);	0
23854623	23806292	Howto enable the expand button in a devexpress Treelist	treeList1.OptionsView.ShowRoot = true;	0
14979071	14978833	How to change BorderBrush colour to default	txtValue1.ClearValue(Border.BorderBrushProperty);	0
20235127	20234688	How to bind XML file to List<MyClass>?	XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));\n\nusing(FileStream stream = File.OpenWrite("filename"))\n{\n    List<MyClass> list = new List<MyClass>();\n    serializer.Serialize(stream, list);\n}\n\nusing(FileStream stream = File.OpenRead("filename"))\n{\n    List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);\n}	0
3465583	3449444	MEF - How can i use an ExportProvider to select just one Export	var catalog = new AggregateCatalog(); \ncatalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory)); \nvar defaults = new CatalogExportProvider(new TypeCatalog(typeof(Service2))); \nvar container = new CompositionContainer(catalog, defaults); \ndefaults.SourceProvider = container;	0
24416620	24415650	moving rectangles one by one	if ((mouse.X >= drawRectangle.X && mouse.X <= drawRectangle.X + currentCharacter.Width\n           && mouse.Y >= drawRectangle.Y && mouse.Y <= drawRectangle.Y + currentCharacter.Height)	0
10587455	10513812	Show values of WebService tables in message box	foreach (XElement nod in resultElements.Elements(@"studentPunishmentsTable"))\n{\n        s.penalty = nod.Element("penalty").Value;\n        Console.WriteLine(s.penalty);     //MessageBox.Show(s.penalty);\n}	0
29546055	29545949	How to create an object and use it into other methods of a class in C#	class One {\n//code\n}\n\nclass Two {\n One one; //instance variable accessible in entire class, not initialized\n One oneInitialized = new One(); //this one is initialized\n Two() { //this is a constructor\n  one = new One(); //initializes the object 'one' that is declared above\n }\n someMethod() {\n  One secondOne = new One(); //can only be used inside this method\n }\n //use object 'one' anywhere;\n}	0
30911900	30911543	get the value in ListItem	foreach (var item in ctl.Items) \n{\n    var value = item.Value;\n}	0
18994445	18994366	How to resolve error with equally named types in method parameters?	public static RectangleNineSides GetRectangleSide(System.Drawing.Rectangle rect, \n                                                  System.Drawing.Point p)\npublic static RectangleNineSides GetXnaRectangleSide(Microsoft.Xna.Framework.Rectangle rect, \n                                                  Microsoft.Xna.Framework.Point p)	0
693707	560076	Saving an ArrayList of custom objects to user settings	[XmlArray("Items")]\n [XmlArrayItem("A.Thing",typeof(Thing))]\n [XmlArrayItem("A.Different.Thing",typeof(Whatzit))]\n public System.Collections.ArrayList List;	0
19928250	19928144	Comparing two lists and getting higher values	var sellMax = _sellOrder.Max(y => y.Price);\nvar t = _buyOrder.Where(x => x.Price > sellMax);	0
598457	598447	How to disable editing of elements in combobox for c#?	comboBox.DropDownStyle = ComboBoxStyle.DropDownList;	0
12909771	12909701	How to replace the alert message box with RadWindow	protected void Button1_Click(object sender, EventArgs e)\n  {\n      RadWindowManager windowManager = \n               FindControl(this, "WindowManager") as RadWindowManager;\n   windowManager.RadAlert("MessageText", 400, null, "title", null);                   \n  }	0
3400573	3400560	DateTime Convert from int to Month Name in C#, Silverlight	DateTime.Now.ToString("MMMM")	0
9472269	9469406	Making the user scroll all the XtraGridControl o a GridControl	void Main()\n{\n    new MyForm().Show();\n}\n\npublic class MyForm : Form\n{\n    public MyForm()\n    {\n        var grid = new GridControl();\n        var gridview = new DevExpress.XtraGrid.Views.Grid.GridView(grid);\n        var button = new Button { Enabled = false, Text = "Next", Dock= DockStyle.Bottom };\n\n        gridview.TopRowChanged += (o, e) => \n        {\n            int bottomRowIndex = gridview.TopRowIndex + ((GridViewInfo)gridview.GetViewInfo()).RowsInfo.Count;\n            if (bottomRowIndex == gridview.RowCount)\n            {\n                button.Enabled = true;\n            }\n        };\n\n        grid.MainView = gridview;\n        grid.DataSource = new [] {9,8,7,6,5,4,3,2,1};\n\n        Controls.Add(grid);\n        Controls.Add(button);\n    }\n}	0
19719504	19719486	How to make a class interface Require an implementation of IEnumerable	public interface IGroupNode : ISceneNode, IEnumerable	0
6409190	6408423	asynchronous console output to a textblock	private static void runantc_OutputDataReceived (object sendingProcess, DataReceivedEventArgs outLine)\n{\n    YourControl.Dispatcher.BeginInvoke(new Action(() => { YourControl.Text += outLine.Data; }), null);\n}	0
11878183	11877876	How to work with libraries that don't support unicode characters	obj_ptr* loadObjFromUnicodePath(path)\n{\n//create tmp ASCII named symlink to file at arg(path).\n//call load API of irrKlang on symlink.\n//delete tmp symlink, return object.\n}	0
988355	988353	Format .NET DateTime "Day" with no leading zero	string result = myDate.ToString("%d");	0
1753978	1753920	How do I write a generic method that takes different types as parameters?	public static void AddRange<A,B>(\n  this ICollection<A> collection, \n  IEnumerable<B> list)\n    where B: A\n{\n    foreach (var item in list)\n    {\n        collection.Add(item);\n    }\n}	0
12877891	12871086	Serialize class with BsonDocument via JSON.NET or XML Serializer	public class Report\n{ \n     [BsonId, JsonIgnore]\n     public ObjectId _id { get; set; }\n\n     public string name { get; set; }\n\n     [JsonIgnore]\n     private BsonDocument layout { get; set; }\n\n     [BsonIgnore]\n     [JsonProperty(PropertyName = "layout")]\n     public string layout2JSON\n     { \n         get { return layout.ToJson(); }\n     }\n}	0
4790155	4790096	Setting initial value for DataType.DateTime in model	Nullable<DateTime>	0
25102695	25102613	How to read a text file line by line subsequently followed by button click	public class TextReader : Form\n{\n    string[] lines;\n    int currentIndex = 0;\n    public TextReader ()\n    {\n        InitializeComponent();\n        lines = File.ReadAllLines("C:\\myTextFile.txt"); \n    }\n\n    public void Button_Click(object sender, EventArgs e)\n    {\n        TextBox1.Text = lines[currentIndex];\n        currentIndex++;\n    }\n}	0
12485865	12485811	Double regex necessary?	\bhttp:\/\/(\b\w*[a-z0-9]\.)?\w*[a-z0-9]\.\w*[a-z0-9]	0
2920488	2920475	Updating an image's ImageUrl within a Repeater	// Get control from <HeaderTemplate>\nImage imgTypeControl = (Image)myRepeater.Controls[0].Controls[0].FindControl("imgType");\n\n// Get control from <FooterTemplate>\nImage imgTypeControl = (Image)myRepeater.Controls[myRepeater-Controls.Count - 1].Controls[0].FindControl("imgType");	0
32406223	32404017	WPF How to get current edited content in datagrid?	XDG.CommitEdit();	0
32587524	32587219	Linq to XML casting XML file to custom object	var results = document.Descendants("row")\n    .Select(row=>row.Elements("FIELD").ToDictionary(x=>x.Attribute("NAME").Value, x=>x.Value))\n    .Select(d=>new Address \n       {                    \n        AccountRef = d["AccountRef"],\n        AddressLine1 = d["AddressLine1"],\n        AddressLine2 = d["AddressLine2"],\n       });	0
27207330	27207125	How to divide Vector2 to Vector2 Arrays?	// For N waypoints between a start and end, we need N+1 segments\n\nsegments = WaypointAmount + 1;\nxSeg = (end.x - start.x) / segments;\nySeg = (end.y - start.y) / segments;\n\n// even though we have N+1 segments, adding the last segment would take\n// us to the endpoint, not another waypoint, so stop when we have all\n// our waypoints\nfor(var i = 1; i<=waypoints, i++)\n{\n    points.Add(new WayPoint { \n        WaypointId = i, \n        Vector2 = new Vector2(  \n                            x = start.x+(xSeg*i),\n                            y = start.y+(ySeg*i)});\n}	0
32804363	32804333	SQL Server stored procedure with 2 input parameters and 8 output parameters	declare @L1R nchar(10) output	0
34327138	34326997	Calculate Last Day of the Next Month	DateTime reference = DateTime.Now;\nDateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);\nDateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);\nDateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);\nDateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);	0
5244423	5244348	Generate pdf file after retrieving the information	protected void btnExportPdf_Click(object sender, EventArgs e)\n{\n    Response.ContentType = "application/pdf";\n    Response.AddHeader("content-disposition", "attachment;filename=BusinessUnit.pdf");\n    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);\n    StringWriter sw = new StringWriter();\n    HtmlTextWriter hw = new HtmlTextWriter(sw);\n    GridView grd = new GridView();\n    grd.DataSource = yourdatatable.DefaultView//get data from DB in Datatable\n    grd.DataBind();\n    grd.RenderControl(hw);\n    StringReader sr = new StringReader(sw.ToString());\n    Document pdfDoc = new Document(PageSize.A2, 8f, 8f, 8f, 8f);\n    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);\n    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);\n    pdfDoc.Open();\n    htmlparser.Parse(sr);\n    pdfDoc.Close();\n    Response.Write(pdfDoc);\n    Response.End();\n}	0
22284762	22284650	How to extract key value pair from a Url	string[] array = inputString.Split(new [] {"&user_id="}, StringSplitOptions.None);\nstring id = array[1];	0
16171242	16170560	C# Windows Form App With Ms Access Failed to Insert Data	string insertString = string.Format(CultureInfo.InvariantCulture, "INSERT INTO tb_reg VALUES ('{0}', '{1}', '{2}', {3})", idCard, name, dateBirth, blood_type); \nOleDbCommand cmd = new OleDbCommand(insertString, new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Data/db_klinik.mdb"));\ncmd.Connection.Open();\n\nint numberAdded = cmd.ExecuteNonQuery();\n\nif (numberAdded < 1)\n{\n     //do something, the data was not added\n}\nelse\n{\n     //be happy :)\n}\ncmd.Connection.Close();	0
19427634	19418226	Construct a string/list based on two list	var items = new List<string>(parentList.Count);\nforeach (var p in parentList)\n{\n    var fields = p.Fields.Split(',');\n    var childData = childList.Where(x => x.ParentId == p.Id).ToList();\n    for (int i = 0; i <= fields.Length-1; i++)\n    {\n        var mappingField = childData.SingleOrDefault(x => x.FieldIndex == i).Select(x => x.mappingField);\n        fields[i] = mappingField ?? "$";\n    }\n    items.Add(String.Join("|", fields));\n}	0
30061261	29826206	Determine best size for images in an given space	public void SetObjectSize()\n        {\n            int objectSize = 0;\n            for (int objectsPerRow = 1; objectsPerRow <= objects.Count ; objectsPerRow++)\n            {\n                int rows =(int)Math.Ceiling(((double)objects.Count) / objectsPerRow);\n                int horizontalSize = (this.size.Height - (rows * spacing + spacing)) / rows;\n                int verticalSize = (this.size.Width - (objectsPerRow * spacing + spacing)) / objectsPerRow;\n                int newSize = horizontalSize < verticalSize ? horizontalSize : verticalSize ;\n                if (newSize > objectSize)\n                {\n                    this.rows = rows;\n                    this.objectsPerRow = objectsPerRow ;\n                    objectSize = newSize;\n                }\n            }\n         }	0
30947610	30946835	WPF: Programatically adding a ContextMenu to a DataGrid column header	//...\n\n    DataGridTextColumn col = new DataGridTextColumn();\n\n    //...\n\n    TextBlock txt = new TextBlock() { Text = AllColumnDisplayNames[i] };\n    txt.ContextMenu = new ContextMenu(); // Build your context menu here.\n\n    col.Header = txt;\n\n    //...	0
22347071	22346535	For each loop not reading the first row in the gridview	protected void gvDepartments_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    // Empty the string variable\n    myDeptResponseCount = "";\n    // Iterate though the gridView to get Dept names and response count values\n\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        // the actual way to get your row index            \n        int rowIndex = e.Row.RowIndex;\n\n        //Label respCount = dept.FindControl("lblResponses"+ dID) as Label;\n        Label lblResponses = (Label)e.Row.FindControl("lblResponses" + dID);\n\n        deptName = e.Row.Cells[1].Text.ToString();\n\n        // get the responseCount for each of the departments\n        myDeptResponseCount = getDepartmentResponseCount.ResponseCount(deptName);\n\n        //lblResponses.Text = myResponseCount;\n        deptCount.Add(deptName);\n    }\n\n    //dID++;\n    deptNameCount.Add(deptName);\n}	0
2464605	2464590	How do I remove the resize gripper image from a StatusStrip control in C#?	StatusStrip.SizingGrip = false;	0
30128201	30127966	how Weka calculates Sigmoid function c#	if (value < -45) {\n  value = 0;\n}\nelse if (value > 45) {\n  value = 1;\n}\nelse {\n  value = 1 / (1 + Math.exp(-value));\n}  \nreturn value;	0
6831625	6827024	find the region part of live using c#	try\n{\n  var pos = e.Location;\n  var results = kpiChartControl.HitTest(pos.X, pos.Y, false, ChartElementType.DataPoint);\n  foreach (var result in results)\n  {\n    if (result.ChartElementType == ChartElementType.DataPoint)\n    {\n      if (result.Series.Points[result.PointIndex].AxisLabel == "Live")\n      {\n        Console.WriteLine("success?");\n      }\n    }\n  }  \n}	0
33886342	33886205	OpenXml DataValidation set predefined List for columns	DataValidation dataValidation = new DataValidation\n{\n    Type = DataValidationValues.List,\n    AllowBlank = true,\n    SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },\n    Formula1 = new Formula1("\"True,False\"") // escape double quotes, this is what I was missing\n};\n\nDataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet\nif (dvs != null)\n{\n    dvs.Count = dvs.Count + 1;\n    dvs.Append(dataValidation);\n}\nelse\n{\n    DataValidations newDVs = new DataValidations();\n    newDVs.Append(dataValidation);\n    newDVs.Count = 1;\n    worksheet.Append(newDVs);\n}	0
2169083	2132705	StructureMap: How to set lifecycle on types connected with ConnectImplementationsToTypesClosing	Scan(scanner =>\n{\n   scanner.AssemblyContainingType<EmailValidation>();\n   scanner.ConnectImplementationsToTypesClosing(typeof(IValidation<>))\n          .OnAddedPluginTypes(t => t.Singleton());\n});	0
26076635	26076540	Trying to encrypt a random key for password reset functionality	byte[] bytes = new byte[8];\nusing (var rng = RandomNumberGenerator.Create())\n{\n    rng.GetBytes(bytes);\n}\nstring key = string.Join("", bytes.Select(b => b.ToString("X2")));	0
1305159	1304949	List all performance counters for a category	public void ListCounters(string categoryName)\n{\n    PerformanceCounterCategory category = PerformanceCounterCategory.GetCategories().First(c => c.CategoryName == categoryName);\n    Console.WriteLine("{0} [{1}]", category.CategoryName, category.CategoryType);\n\n    string[] instanceNames = category.GetInstanceNames();\n\n    if (instanceNames.Length > 0)\n    {\n        // MultiInstance categories\n        foreach (string instanceName in instanceNames)\n        {\n            ListInstances(category, instanceName);\n        }\n    }\n    else\n    {\n        // SingleInstance categories\n        ListInstances(category, string.Empty);\n    }\n}\n\nprivate static void ListInstances(PerformanceCounterCategory category, string instanceName)\n{\n    Console.WriteLine("    {0}", instanceName);\n    PerformanceCounter[] counters = category.GetCounters(instanceName);\n\n    foreach (PerformanceCounter counter in counters)\n    {\n        Console.WriteLine("        {0}", counter.CounterName);\n    }\n}	0
31484378	31284331	How to fetch current location of device when App is launched first time in windows 8.1 using c#?	public async void MyLocationFinder()\n    {\n        Geolocator MyGeolocator = new Geolocator();\n        MyGeolocator.DesiredAccuracyInMeters = 50;\n        try\n        {\n            Geoposition MyGeoposition = await MyGeolocator.GetGeopositionAsync(\n               maximumAge: TimeSpan.FromMinutes(5),\n               timeout: TimeSpan.FromSeconds(10) );\n            LatitudeTextBlock.Text = MyGeoposition.Coordinate.Latitude.ToString("0.00");\n            LongitudeTextBlock.Text = MyGeoposition.Coordinate.Longitude.ToString("0.00");\n        }\n        catch (UnauthorizedAccessException)\n        {\n            //The app doesn't has the right capability or the location master switch is off\n            StatusTextBlock.Text = "Location is Disabled in phone storage.";\n        }\n    }	0
27059372	27058575	How to execute several commands in cmd one after the another in C#?	var p = new Process\n{\n    StartInfo = new ProcessStartInfo(@"cmd", @"/c ..\xxx.cmd ") // The required command to be executed\n    {\n        UseShellExecute = false,\n        CreateNoWindow = true,\n        RedirectStandardError = true,\n        RedirectStandardOutput = true,\n        WorkingDirectory = Path.GetFullPath(@"Sample\SampleExecutionFolder"), //Mention the working directory of the cmd execution\n    },\n    EnableRaisingEvents = true,\n};\n\np.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data); //Get the output from here\np.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data); // and error information from here\np.Start();\np.BeginErrorReadLine();\np.BeginOutputReadLine();\nvar processTaskCompletionSource = new TaskCompletionSource<int>();\np.EnableRaisingEvents = true;\np.Exited += (s, e) =>\n    {\n        p.WaitForExit();\n        processTaskCompletionSource.TrySetResult(p.ExitCode);\n    };	0
11095032	11094943	Efficiently populating an ASP.Net Calendar control	foreach (CalendarEvent x in CalendarEventManager.GetForDate(e.Day.Date))\n{\n    //logic to extract the data from x, and modify the e.Cell to display that data\n}	0
3323405	3323113	datetime to string with time zone	var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);\n        string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");\n        Console.WriteLine(s);	0
4451582	4451560	with LINQ, how to transfer a List<List<string>> to List<string>?	List<string> results = original.SelectMany(x => x).ToList();	0
33544400	33515906	Overriding mvvmcross View locator	protected override System.Reflection.Assembly[] GetViewModelAssemblies()\n    {\n      //  return base.GetViewModelAssemblies();\n\n        var result = base.GetViewModelAssemblies();\n        var assemblyList = result.ToList();\n\n        var assemblyType = typeof(SBG.NBOL.StartupModule.ViewModels.LogonViewModel);\n        assemblyList.Add(assemblyType.GetTypeInfo().Assembly);\n        return assemblyList.ToArray();\n    }	0
14499966	14499903	C# Regex to get ID value from HTML	string regex=@"esc_my_nucleus"":""(\d+)";\nstring val=Regex.Match(input,regex,RegexOptions.Ignorecase).Groups[1].Value;	0
34293668	34293325	Replace & character in a string	string name = gResults[i].Replace("&&type=unique","");	0
6739433	6737885	How do you change the color of the WPF treeview arrow?	Default WPF Themes	0
30890411	30869122	How to Order By list inside list using LINQ in C#	var result = MyList.OrderBy(x => x.SortKey).ToList();\n                foreach (var item in model)\n                {\n                   item.Group2 = item.Categories.OrderBy(x => x.SortKey).ToList();\n                }	0
20265160	20264885	Custom Data Validation. First input field must be lower than Second input field	public class Schedule\n{\n    ...\n    public int BeginWork { get; set; }\n    public int EndWork { get; set; }\n\n\n\n     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n     {\n         if (BeginWork >= EndWork )\n         {\n            yield return new ValidationResult("The end work needs to be later than the begin work");\n         }\n     }\n\n}	0
3273753	3273747	How do you get a month name from an integer value?	// using the current culture - returns "July" for me\nstring x = DateTimeFormatInfo.CurrentInfo.GetMonthName(7);\n\n// using a specific culture - returns "juillet"\nstring y = CultureInfo.GetCultureInfo("fr-FR").DateTimeFormat.GetMonthName(7);	0
3084053	3084047	how to pass a converter (constraints not applicable for generic arguments)	class Test \n{ \n   public void Foo<Tout>(string val, Converter<string, Tout> conv) \n   { \n      myObj = conv(val); \n   } \n}	0
23387922	23386607	Datagrid cell font colour is changing the entire row	SelectionUnit="Cell"	0
4379462	4378984	Latitude and Longitude keep changing every time I convert from Degrees Minutes Seconds to Decimal Degrees in c#	double Minutes(double decimalDegrees)\n{\n  //Get hours\n  double h = Math.Truncate(lat);\n  //Get minutes + seconds\n  double x = (Math.Abs(h - Math.Round(lat, 12)) * 60.0);\n  //Everything after the decimal is seconds\n  double min = Math.Truncate(x);\n  return min;\n}	0
15907722	15907543	How can I do a linq to XML statement inside another one?	var toplevel = doc.Root.Elements().Select(settingElement => new Setting\n                {\n                    Type = settingElement.Name.LocalName,\n                    SettingItems = settingElement.Elements("Item").Select(itemElement => new SettingItem\n                        {\n                            Name = itemElement.Attribute("name").Value,\n                            Value = itemElement.Attribute("value").Value,\n                        })\n                }).ToList();	0
18948188	18948116	finding nested span and <dt> with XPath in HTML	var bonusPool = doc.DocumentNode\n                .SelectNodes("//div[@class='span3 ranks']/dl[@class='dl-horizontal']//dd")\n                .Last()\n                .InnerText.Trim();\n\nvar regionRank = doc.DocumentNode\n                .SelectNodes("//div[@class='span3 ranks']/dl[@class='dl-horizontal']/dd[2]/span")\n                .Select(x => x.InnerText)\n                .ToArray();\n\n\nvar lastGame = doc.DocumentNode\n                .SelectSingleNode("//div[@class='span3 ext-stats']/dl[@class='dl-horizontal']/dd[2]")\n                .InnerText;\n\nvar lastUpdate = doc.DocumentNode\n                .SelectSingleNode("//div[@class='span3 ext-stats']/dl[@class='dl-horizontal']/dd[3]")\n                .InnerText;	0
17130481	17120932	When attach a file to JIRA issue attachment using HTTPClient Post method, JIRA return JSON object is "[]"	var filename = "C:\\Users\\XXXX\\Desktop\\Sample.xlsx";\nvar file_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\nvar filecontent = new ByteArrayContent(System.IO.File.ReadAllBytes(filename));\nvar content = new MultipartContent("form-data", "AAAA");\n\ncontent.Headers.Add("X-Atlassian-Token", "nocheck");\ncontent.Headers.Add("charset", "UTF-8");\n\nfilecontent.Headers.ContentDisposition = \n    new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") {\n        Name="\"file\"",\n        FileName = "Attachment.xlsx"\n    };\n\nfilecontent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file_type);\ncontent.Add(filecontent);	0
20851646	20851612	Detect Missing Dll in own folder	try-catch	0
21132674	21132596	how to import data from mysql database to datagridview	string connectionString = ""; //Set your MySQL connection string here.\nstring query =""; // set query to fetch data "Select * from  tabelname"; \nusing(MySqlConnection conn = new MySqlConnection(connStr))\n{\n    using(MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))\n    {\n        DataSet ds = new DataSet();\n        adapter.Fill(ds);\n        DataGridView1.DataSource= ds.Tables[0];\n    }\n}	0
6797010	6752520	C# Graphics.DrawString RectangleF Auto-Height: How to find that height?	private void panel1_Paint(object sender, PaintEventArgs e)\n{\n  string header2 = "This is a much, much longer Header";\n  string description = "This is a description of the header.";\n\n  RectangleF header2Rect = new RectangleF();\n  using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Bold))\n  {\n    header2Rect.Location = new Point(30, 105);\n    header2Rect.Size = new Size(600, ((int)e.Graphics.MeasureString(header2, useFont, 600, StringFormat.GenericTypographic).Height));\n    e.Graphics.DrawString(header2, useFont, Brushes.Black, header2Rect);\n  }\n\n  RectangleF descrRect = new RectangleF();\n  using (Font useFont = new Font("Gotham Medium", 28, FontStyle.Italic))\n  {\n    descrRect.Location = new Point(30, (int)header2Rect.Bottom);\n    descrRect.Size = new Size(600, ((int)e.Graphics.MeasureString(description, useFont, 600, StringFormat.GenericTypographic).Height));\n    e.Graphics.DrawString(description.ToLower(), useFont, SystemBrushes.WindowText, descrRect);\n  }\n\n}	0
986666	982261	Bind nullable DateTime to MaskedTextBox	public static void FormatDate(MaskedTextBox c) {\n    c.DataBindings[0].Format += new ConvertEventHandler(Date_Format);\n    c.DataBindings[0].Parse += new ConvertEventHandler(Date_Parse);\n}\n\nprivate static void Date_Format(object sender, ConvertEventArgs e) {\n    if (e.Value == null)\n        e.Value = "";\n    else\n        e.Value = ((DateTime)e.Value).ToString("MM/dd/yyyy");\n}\n\nstatic void Date_Parse(object sender, ConvertEventArgs e) {\n    if (e.Value.ToString() == "  /  /")\n        e.Value = null;\n}	0
19259153	19258810	XMLDocument.Save adds return carriages to XML when elements are blank	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(@"C:\test.xml");\n\n//Save the xml and then cleanup\nXmlWriterSettings settings = new XmlWriterSettings { Indent = true };\nXmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings);\nxmlDoc.Save(writer);	0
29038679	29036409	Create a screenshot of a WPF control in a background thread	public MainWindow()\n    {\n        InitializeComponent();\n\n        var thread = new Thread(CreateScreenshot);\n        thread.SetApartmentState(ApartmentState.STA);\n        thread.Start();\n    }\n\n    private void CreateScreenshot()\n    {\n        Canvas c = new Canvas { Width = 100, Height = 100 };\n        c.Children.Add(new Rectangle { Height = 100, Width = 100, Fill = new SolidColorBrush(Colors.Red) });\n\n        var bitmap = new RenderTargetBitmap((int)c.Width, (int)c.Height, 120, 120, PixelFormats.Default);\n        c.Measure(new Size((int)c.Width, (int)c.Height));\n        c.Arrange(new Rect(new Size((int)c.ActualWidth, (int)c.ActualHeight)));\n        bitmap.Render(c);\n\n        var png = new PngBitmapEncoder();\n        png.Frames.Add(BitmapFrame.Create(bitmap));\n\n        using (Stream stm = File.Create("c:\\temp\\test.png"))\n        {\n            png.Save(stm);\n        }\n\n    }	0
28503852	28503566	Outlook COM: Invoke OpenSharedItem via late binding	namespaceObjType.InvokeMember("OpenSharedObject", System.Reflection.BindingFlags.InvokeMethod, null, namespaceObj, new object[] { temporaryFileName });	0
8368161	8305020	Windows phone 7 Toast notification with app in foreground	string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +\n        "<wp:Notification xmlns:wp=\"WPNotification\">" +\n           "<wp:Toast>" +\n              "<wp:Text1>" + title + "</wp:Text1>" +\n              "<wp:Text2>" + message + "</wp:Text2>" +\n           "</wp:Toast>" +\n        "</wp:Notification>";	0
4961371	4961165	Access MSAccess Properties without actually opening the Database	m_oEngine = New DAO.DBEngine\n\nm_oEngine.SystemDB = sWorkgroupFile\n\nm_oWorkspace = m_oEngine.CreateWorkspace("My Workspace", sUserName, sPassword, DAO.WorkspaceTypeEnum.dbUseJet)\n\nm_oDatabase = m_oWorkspace.OpenDatabase(sDatabaseFile, bExclusive, bReadOnly)  ' Note DAO docs say the second parameter is for Exclusive	0
2839088	2838896	Any way to avoid creating a huge C# COM interface wrapper when only a few methods needed?	[ComImport, Guid("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\ninterface IUIAutomation\n{\n    void CompareElements();\n    void CompareRuntimeIds();\n    void GetRootElement();\n    // 50 or so other methods...\n    // ... define only the signatures for the ones you actually need\n}	0
14460002	14434364	Convert postscript to jpeg	PDFPrinter.WGhostScript gs = new PDFPrinter.WGhostScript();\n            gs.AddParam("-q");\n            gs.AddParam("-dNOPAUSE");\n            gs.AddParam("-dBATCH");\n            gs.AddParam("-sDEVICE=jpeg");\n            gs.AddParam(@"-sOutputFile=<full oytput file path>%i.jpg");\n            gs.AddParam(<psFilePath>);	0
22658817	22655249	How to bind a Dataset to CrystalReport in C#	testdbDataSet ds = new testdbDataSet();\n\n    //FETCH FROM ANYWHERE TO a DataTable\n    DataTable _DtFrmDBPrd = new DataTable();\n    DataTable _DtFrmDBRgn = new DataTable();\n\n    _DtFrmDBPrd = GetDataFrmDBPrd();//Filling the DataTable From DB or any where..\n    _DtFrmDBRgn = GetDataFrmDBRgn();\n\n    ds.Products.Merge(_DtFrmDBPrd);//Both the Data Table should have the same column name and Data Type\n    ds.Region.Merge(_DtFrmDBRgn);\n\n    ReportDocument reportDoc = new ReportDocument();\n    reportDoc.FileName = "CrystalReport1.rpt";\n    reportDoc.SetDataSource(ds);\n\n    crystalReportViewer1.ReportSource = reportDoc;\n    crystalReportViewer1.Show();	0
170094	170051	How would you simply Monitor.TryEnter	public bool TryEnter(object lockObject, Action work) \n{\n    if (Monitor.TryEnter(lockObject)) \n    {\n       try \n       {\n          work();\n       }\n       finally \n       {\n           Monitor.Exit(lockObject);\n       }        \n       return true;\n     }\n\n     return false;\n}	0
16450572	16450362	at a specific startindex check for space if any is found remove that specific space the text after it and add "..."	public static string TrimLength(string text, int maxLength)\n{\n    if (text.Length > maxLength)\n    {\n        maxLength -= "...".Length;\n        maxLength = text.Length < maxLength ? text.Length : maxLength;\n        bool isLastSpace = text[maxLength] == ' ';\n        string part = text.Substring(0, maxLength);\n        if (isLastSpace)\n            return part + "...";\n        int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');\n        if (lastSpaceIndexBeforeMax == -1)\n            return part + "...";\n        else\n            return text.Substring(0, lastSpaceIndexBeforeMax) + "...";\n    }\n    else\n        return text;\n}	0
15936272	15936180	Getting content/message from HttpResponseMessage	Stream receiveStream = response.GetResponseStream ();\nStreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);\ntxtBlock.Text = readStream.ReadToEnd();	0
3417577	3417383	place a form with Opacity over a main form with datagridview winform	OverlayForm form = new OverlayForm();\n     form.Show(this);	0
7013396	7013162	Writing To Existing XML FILE	XDocument doc = XDocument.Load("your.xml");\nXElement item = new XElement(WhereDoCopy ,\n                new XAttribute("Path", "C:\Users\USER\Desktop\jobs2"));\ndoc.Root.Add(item);	0
28714658	28699544	c# pdf How to set textfield label with iText	PdfReader reader = new PdfReader(SOURCE); \nPdfStamper stamper = new PdfStamper(reader, TARGET); \n\nTextField tf = new TextField(stamper.getWriter(), new Rectangle(300, 400, 500, 420), "UserName");\nstamper.addAnnotation(tf.getTextField(), 1);\n\nPdfContentByte overContent = stamper.getOverContent(1);\nBaseFont baseFont = BaseFont.createFont();\noverContent.setFontAndSize(baseFont, 12);\noverContent.beginText();\noverContent.showTextAligned(PdfContentByte.ALIGN_RIGHT, "User Name:", 300, 405, 0);\noverContent.endText();\n\nstamper.close ();	0
1357334	1357326	Save file from Database image field	sender.Response.Clear();\nsender.Response.ContentType = uf.FileType; // the binary data\nsender.Response.AddHeader("Content-Disposition", "attachment; filename="\n         + uf.FileName);\nsender.Response.BinaryWrite(uf.FileData);\nsender.Response.Close();	0
26869940	26869520	How do I search for the exact phrase?	parser.Parse("\"" + searchString + "\"");	0
6498920	6498829	Cant parse domain into IP in C#?	IPAddress ipAddress;\nif (!IPAddress.TryParse (txtBoxIP.Text, out ipAddress))\n   ipAddress = Dns.GetHostEntry (txtBoxIP.Text).AddressList[0];\nserverEndPoint = new IPEndPoint(ipAddress, MainForm.port)	0
1731225	1731207	C# Array of objects	address[] _address = new address[1];\n_address[0] = new address();\n_address[0].city = _q.LocationA.City;\n_address[0].state = _q.LocationA.State;\n_address[0].street = _q.LocationA.Address;\n_address[0].zipCode = _q.LocationA.Zip;\n\nrequest _req = new request();\n_req.addresses = _address;	0
10708147	10707881	How get reflection info of a class loaded in the main assembly	Type myType1 = Type.GetType("MyType, MyNameSpace", true, true);	0
16015930	16015806	filter on multiple rows	view.RowFilter = "Type like '%" + txt_voertuig1.Text + "%' AND Omschrijving like '%" + txt_fout1.Text + "%'";	0
25853186	25845229	Call external application from Unity mobile application	void SMS(long number, string message) {\n    string separator=(Application.platform == RuntimePlatform.IPhonePlayer)?";":"?";\n    Application.openURL(string.Format("sms:{0}{1}body={2}", number, separator, WWW.EscapeURL(message)));\n}	0
19272966	19272827	How can I write a strings to file with linebreaks inbetween?	TextWriter w_Test = new StreamWriter(file_test);\nforeach (string results in searchResults)\n{\n    int noLinesOutput = 0;\n    w_Test.WriteLine(Path.GetFileNameWithoutExtension(results));\n    noLinesOutput++;\n    var list1 = File.ReadAllLines(results).Skip(10);\n    foreach (string listResult in list1)\n    {\n        w_Test.WriteLine(listResult);\n        noLinesOutput++;\n    }\n    for ( int i = 20; i > noLinesOutput; i-- )\n        w_Test.WriteLine();\n}\nw_Test.Close();	0
5899599	5899561	DirectoryInfo GetFiles TOP number	var d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/xml"));\nvar files = d.GetFiles("*.xml").OrderByDescending(fi=>fi.LastWriteTime).Take(10);	0
16072785	14046830	DataGridView - Use DataPropertyName to show child element property	public class FormulariosENT {\n\n    #region PROPERTIES\n\n    public int IdFromulario { get; set; }\n    public string DescripcionFormulario { get; set; }\n\n    #endregion\n\n    #region PUBLIC METHODS\n    public override string ToString() {\n\n        return DescripcionFormulario;\n    }	0
14930044	14929760	Convert resource to byte[]	var info = Application.GetResourceStream(uri);\nvar memoryStream = new MemoryStream();\ninfo.Stream.CopyTo(memoryStream);\nreturn memoryStream.ToArray();	0
11377544	11377510	How to disable [RequireHttps] for all methods during debugging?	#if RELEASE\n    [RequireHttps]\n#endif\nvoid methodHere()\n{\n...\n}	0
5664811	5664349	How read files making a filter?	var fileList = (new DirectoryInfo(filePath)).GetFiles().Where(a => Regex.IsMatch(a.Name, "^[^7]*7.jpg$")).ToList();	0
23929530	23929495	Adding additional linq where clauses based on variables	if (courseID > 0)\n{\n    allFeedback = allFeedback.Where(f => f.CourseBooking.CourseID == courseID);\n}\n\nif (facilitatorID == 0)\n{\n    allFeedback = allFeedback.Where(f => f.CourseBooking.FacilitatorID == null);\n}\nelse if (facilitatorID > 0)\n{\n    allFeedback = allFeedback.Where(f => f.CourseBooking.FacilitatorID == facilitatorID);\n}	0
218141	218133	C# BinaryFormatter - How can I find out the class of the binary data?	object result = formatter.Deserialize(stream); \nType t = result.GetType();	0
5974656	5974554	EF Code First - how to set identity seed?	DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)	0
15851304	15850924	Button in ListView item - change item on click	var element = sender as FrameworkElement;\nDebug.Assert(element != null, "element != null");\nvar context = element.DataContext as MyDataModel;\nDebug.Assert(context != null, "context != null");	0
20112437	20112369	C# - Loop foreach until true	IntPtr hWnd = IntPtr.Zero;\nbool isFound = false;\nwhile(!isFound)\n{\n  foreach (Process procList in Process.GetProcess())\n  {\n    if (procList.MainWindowTitle.Contains("SAP Logon"))\n    {\n        isFound = true;\n        hWnd = procList.MainWindowHandle;\n    }\n  }\n  Thread.Sleep(100); // You may or may not want this\n}\nShowWindow(hWnd, 0);	0
5604940	5604767	GridView selects wrong row for editing	if (TextBoxSearchArticle.Text != ""){\n        LinqDataSourceAdminArticles.Where = "Title.Contains(" + "\"" + TextBoxSearchArticle.Text + "\")";\n        LinqDataSourceAdminArticles.DataBind();\n\n    LinqDataSourceAdminArticles.DataBind();}	0
20875474	20874808	Windows Phone - Audio Endpoint Device	AudioRoutingManager.GetDefault().AudioEndpointChanged += AudioEndpointChanged;\n\npublic void AudioEndpointChanged(AudioRoutingManager sender, object args) \n{\n  var AudioEndPoint = sender.GetAudioEndpoint();\n  switch (AudioEndPoint)\n  {\n     case AudioRoutingEndpoint.WiredHeadset:\n          MessageBox.Show("Headset connected");\n          break;\n  }\n}	0
13305597	13305517	Creating a startup folder shorcut with a ClickOnce application?	// The path to the key where Windows looks for startup applications\nRegistryKey rk = Registry.CurrentUser.OpenSubKey(\n                    @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);\n\n//Path to launch shortcut\nstring startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs) \n                   + @"\YourPublisher\YourSuite\YourProduct";\n\nrk.SetValue("YourProduct", startPath);	0
23544395	23544338	How to return an existing view from a new action in ASP.NET MVC 4?	public ActionResult someAction()\n{\n     return View("Index"); \n}	0
18938668	18938646	Getting multiple malformed cookies via c#	var request = WebRequest.Create(resourceUrl) as HttpWebRequest;\nrequest.Method = "GET";\nrequest.CookieContainer = new CookieContainer(); // <-- Add this\n\nvar response = request.GetResponse() as HttpWebResponse;\nvar cookiesCount = response.Cookies.Count;	0
11260396	11260289	LINQ Getting Distinct Data and looping through to get related data	//List<Item> webservice = list with items from your webservice\nvar result = (from i in items\n              group i by i.GroupName into groups\n              select new Group()\n              {\n                  GroupName = groups.Key,\n                  Items = groups.Select(g => g.ItemName).ToList()\n              }).ToList();	0
33575222	33562660	UITableView within a UITableViewCell events missing	public PlanningGwWrapperCell(IntPtr handle)\n        : base(handle)\n    {\n        ...\n\n        ContentView.AddSubview(new UILayoutHost(_header));\n        ContentView.AddSubview(_playersTable);\n\n        InitializeBindings();\n\n        _playersTable.ReloadData();\n    }\n\n    public override void LayoutSubviews()\n    {\n        base.LayoutSubviews();\n\n        _playersTable.Frame = new CGRect(0, Dimens.TableRowHeight, ContentView.Bounds.Width, Dimens.TableRowHeight);\n        _header.LayoutParameters = new LayoutParameters(ContentView.Bounds.Width, Dimens.TableRowHeight);\n    }	0
32923657	32923265	How To Add ImageTools GIF To Grid in Windows Phone 8 Silverlight	Decoders.AddDecoder<GifDecoder>();\nExtendedImage eAt = new ExtendedImage();\neAt.UriSource = new Uri(@"/medias/at.gif", UriKind.RelativeOrAbsolute);\neAt.LoadingCompleted += new EventHandler((ss, ee) =>\n{\n    Dispatcher.BeginInvoke(() =>\n    {\n        Image img = new Image();\n        img.Source = eAt.ToBitmap();\n        grd.Children.Add(img);\n    });\n});	0
11872465	11860197	Prevent HTMLAgilityPack from connecting words when using InnerText	const string html = @"<span>?stanbul</span><ul><li><a href=""i1.htm"">Adana</a></li>";\nvar doc = new HtmlDocument();\ndoc.LoadHtml(html);\nstring result = string.Join(" ", doc.DocumentNode.Descendants()\n  .Where(n => !n.HasChildNodes && !string.IsNullOrWhiteSpace(n.InnerText))\n  .Select(n => n.InnerText));\nConsole.WriteLine(result); // prints "?stanbul Adana"	0
17898331	17898206	How can I include a field from an included table in my LINQ expression?	var topics = new System.Collections.Generic.List<Topic>();\nvar subTopics = new System.Collections.Generic.List<SubTopic>();\nint topicId = 23984;\nvar details = from subtopic in subTopics\n    where subtopic.TopicId == topicId\n    join topic in topics on subtopic.TopicId equals topic.TopicId\n    select new TopicSubTopic()\n    {\n        TopicId = topic.TopicId,\n        SubTopicId = subtopic.SubTopicId,\n        TopicName = topic.Name,\n        SubtopicName = subtopic.Name\n    };	0
25978010	25977829	Return F# Interface from C# Method	public class Derp\n{\n    class Test<T> : TestUtil.ITest<T, T>\n    {\n        public string Name(T[] input, T[] iters) \n        {\n            return "asdf";\n        }\n        public void Run(T[] input, T[] iters)\n        {\n             run(input, iters);\n        }\n        public void Dispose() {}\n    }\n\n    public TestUtil.ITest<T, T> Foo<T>(T x)\n    {\n         //stuff\n         return new Test<T>();\n    }\n}	0
7836378	7836366	Is it good idea to remove dash from a GUID?	public Guid(int a, short b, short c, byte[] d);\npublic Guid(int a, short b, short c, byte d, \n            byte e, byte f, byte g, byte h, \n            byte i, byte\npublic Guid(uint a, ushort b, ushort c, byte d, \n            byte e, byte f, byte g, byte h, \n            byte i, byte j, byte k);	0
4323918	4323874	Can we split the Filepath from the last folder in C#?	string path = @"D:\TEST_SOURCE\CV\SOURCE CODE\ARMY.Data\ProceduresALL\ISample.cs";\n\n//ISample.cs\nPath.GetFileName(path);\n\n//D:\TEST_SOURCE\CV\SOURCE CODE\ARMY.Data\ProceduresALL\nPath.GetDirectoryName(path);\n\n//ProceduresALL\nPath.GetDirectoryName(path).Split(Path.DirectorySeparatorChar).Last();	0
19860139	19859960	Numbers cube, each row rotated to left by one	Console.WriteLine("Please write a Number: ");\nConsole.Write("Number: ");\nint num = int.Parse(Console.ReadLine());\nfor (int i = 0; i <= num; i++)\n{\n    for (int j = num - i; j >= 0; j--)\n    {\n        Console.Write(j);\n    }\n    for (int j = num; j > num - i; j--)\n    {\n        Console.Write(j);\n    }\n    Console.WriteLine();\n}\nConsole.ReadLine();	0
28122807	28122760	need to replace a character "?" in a C# string	lbl.Text = str.Replace("\u2015", "");	0
8431664	8431538	Using a Details View, is there any way during Page_Load (or anywhere) to only display non-null fields?	int? productId	0
1470824	1470564	C#/WPF: DataGrid - Last Row / Footer Row possible?	public class MyCollectionViewModel : ObservableCollection<SomeObject>\n    {\n        private readonly SomeObject _totalRow;\n\n        public MyCollectionViewModel ()\n        {\n            _totalRow = new SomeObject() { IsTotalRow = true; };\n            base.Add(_totalRow );\n        }\n\n        public new void Add(SomeObject item)\n        {\n            int i = base.Count -1;\n            base.InsertItem(i, item);\n        }\n    }	0
17848667	17848647	How do i copy a file name with any extention?	string sourceDirectory = @"D:\";\nstring destinationDirectory = @"D:\Test";\nList<string> fileNames = new List<string>(Directory.GetFiles(sourceDirectory, "hosts*.*"));\n\nfor (int iFile = 0; iFile < fileNames.Count; iFile++)\n{\n    string fileName = fileNames[iFile];\n    File.Copy(fileName, Path.Combine(destinationDirectory,Path.GetFileName(fileName)));\n}	0
31953366	31951572	Integrating REST Web API App with SignalR?	[Authorize]\npublic class MessageHub : Hub\n{\n}\n\npublic static class MessageHubHelper\n{\n    private static readonly IHubContext _hubContext =\n        GlobalHost.ConnectionManager.GetHubContext<MessageHub>();\n\n    public static IHubContext Context\n    {\n        get { return _hubContext; }\n    }\n\n    public static void Send(User user, Message message)\n    {\n        _hubContext.Clients.User(GetUserId(user)).Send(message);\n    }\n\n    public static void DoSomethingElse(User user, Message message)\n    {\n        _hubContext.Clients.User(GetUserId(user)).DoSomethingElse(message);\n    }\n\n    private static string GetUserId(User user)\n    {\n        return user.IdentityUser.UserName;\n    }\n}	0
17731203	17730716	LINQ to SQL - Join, Group, and Sum	var query = from p in db.POOL_SIE_SUPPORTs\n            join c in db.ACCTs on p.ACCT_ID equals c.ACCT_ID\n            where arr.Contains(p.ACCT_ID) && p.POOL_NO == 23 && p.FY_CD == "2013" && p.PD_NO == 12\n            group p by new { p.ACCT_ID, p.ACCT_NAME } into s\n            select new\n            {\n                Account = s.Key.ACCT_ID,\n                AccountName = s.Key.ACCT_NAME, \n                CTDActual = string.Format("{0:C}", s.Sum(y => y.CUR_AMT)),\n                CTDBudget = string.Format("{0:C}", s.Sum(y => y.CUR_BUD_AMT)),\n                YTDActual = string.Format("{0:C}", s.Sum(y => y.YTD_AMT)),\n                YTDBudget = string.Format("{0:C}", s.Sum(y => y.YTD_BUD_AMT))\n           };	0
10133080	10133028	How can I put a muzzle on the ErrorProvider component?	private void buttonCancel_Click(object sender, EventArgs e)\n{\n    foreach (Control ctrl in this.Controls)\n    {\n        formValidation.SetError(ctrl, string.Empty);\n    }\n    Close();\n}	0
14212486	14212419	How to send data from android to SQL Server 2008?	String url = "your_webservice_URL";\n\n try \n {\n    HttpPost loginHttpPost   = new HttpPost(url); \n    HttpContext localContext = new BasicHttpContext();          \n\n    MultipartEntity multipartContent = new MultipartEntity();\n    multipartContent.addPart("parameter1", new StringBody(value1));\n    multipartContent.addPart("parameter2", new StringBody(value2));\n    loginHttpPost.setEntity(multipartContent);\n\n    HttpClient objHttpClient = new DefaultHttpClient();\n    HttpResponse response = objHttpClient.execute(loginHttpPost,localContext);\n } \n catch (IOException e) {\n     e.printStackTrace();}	0
19018247	17801844	Generating Table in Telerik Report Viewer Programmatically	TableGroup tableGroupColumn = new TableGroup();\n//add this :\ntableGroupColumn.Name = i.ToString();	0
7340625	7340531	Exception The string '' is not a valid AllXsd value. when trying to get a DataSet from an XML string via ReadXML	MyDataSet.ReadXml(MyXMLStringReader, XmlReadMode.InferSchema);	0
8319748	8319724	Consuming an Array returned from a Method	public string[]arrayFucntion()\n\nvoid consumeFunction()\n{\n  var x = arrayFucntion();\n  for (int i=0; i<x.Lenght; i++)\n  {       \n    x[i]...\n  }\n}	0
18727653	18723932	Registering a class from an unreferenced assembly with castle windsor	container.Register(\nClasses\n    .FromAssemblyNamed("MyProject.Web").Where(t => t.FullName == "MyProject.Web.Modules.AuthenticationModule").\n    .BasedOn<IBaseHttpModule>()\n    .LifestylePerWebRequest()	0
17438462	17315743	How to count the items within Bulleted list VSTO Word 2007	Word.Document dc = Globals.ThisAddIn.Application.ActiveDocument;\nint count = dc.Lists[1].ListParagraphs.Count;	0
33457721	33457668	Sending mail from C# application	client.Credentials = new NetworkCredential("From@gmail.com", "Generated Password");	0
25017302	25016608	C# Create given number of part arrays from large array	public static IEnumerable<IEnumerable<T>> Partition<T>(IEnumerable<T> items, Int32 number)\n{\n  IEnumerable<T> list = items.ToList();\n  var partitions = new List<IEnumerable<T>>(number);\n  var size = list.Count() / number;\n  var extra = list.Count() - size * number;\n\n  for (int i = extra; i < number; ++i)\n  {\n    partitions.Add(list.Take(size).ToList());\n    list = list.Skip(size);\n  }\n  for (int i = 0; i < extra; ++i)\n  {\n    partitions.Add(list.Take(size + 1).ToList());\n    list = list.Skip(size + 1);\n  }\n  return partitions;\n}	0
24164113	24163955	PostgreSQL DSN Connection string in C#	// PostgeSQL-style connection string\n   string connstring = String.Format("Server={0};Port={1};" + \n                    "User Id={2};Password={3};Database={4};",\n                    tbHost.Text, tbPort.Text, tbUser.Text, \n                    tbPass.Text, tbDataBaseName.Text );\n                // Making connection with Npgsql provider\n   NpgsqlConnection conn = new NpgsqlConnection(connstring);\n   conn.Open();\n   // quite complex sql statement\n   string sql = "SELECT * FROM simple_table";\n   // data adapter making request from our connection\n   NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);	0
8021191	8021114	How to set a page title for an ashx file?	this.Context.Response.ClearContent();\nthis.Context.Response.ClearHeaders();\nthis.Context.Response.ContentType = "application/pdf";\nthis.Context.Response.AddHeader("Content-Disposition", "inline; filename=mytest.pdf");\nthis.Context.Response.TransmitFile(sLocalFileName);\nthis.Context.Response.Flush();	0
1632460	1632442	Where are LINQ assemblies located in Windows XP?	%WINDIR%	0
22045007	21185967	SDL 2 C# - Opening a joystick device	[STAThread]\nstatic void Main(string[] args){ ... }	0
9041004	9040887	Developing independently from UI framework	abstract class AbstractControl { }\n\nclass WinFormsControl : AbstractControl { }\n\nclass WpfControl : AbstractControl { }\n\ninterface IClientView\n{\n   AbstractControl SelfControl { get; }\n}	0
20348913	20346219	How to show toast after performing some functionality in windows phone 8	ToastPrompt toast = new ToastPrompt();\ntoast.Title = "Your app title";\ntoast.Message = "Record saved.";\ntoast.TextOrientation = Orientation.Horizontal;\ntoast.MillisecondsUntilHidden = 2000;\ntoast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));\n\ntoast.Show();	0
13171328	13171298	Unable to catch the Dropdown selected value in a textbox inside a repeater	protected virtual void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)\n{\n    DropDownList MyList = (DropDownList)e.Item.FindControl("ddl");\n    MyList.SelectedIndexChanged += ddl_SelectedIndexChanged;\n}\n\nprotected void Ddl_SelectedIndexChanged(object sender, EventArgs e)\n {\n     RepeaterItem item  = (RepeaterItem)  Page.FindControl("repeatorid");\n     TextBox txt        = (TextBox) item.FindControl("TextBox4");\n     txt.Text           = ddl.SelectedItem.Text;     \n }	0
12497490	12497383	Convert a signed int to two unsigned short for purpose of reconstruction	int xy = -123456;\n// Split...\nushort m_X = (ushort) xy;\nushort m_Y = (ushort)(xy>>16);\n// Convert back...\nint back = (m_Y << 16) | m_X;	0
12077347	12077136	Regex extract optional group	^T(?<Number>\d+): (?<Warning>Warning: )?(?<Tag>[^:]+): (?<Message>.*)	0
4802438	4802416	How to combine 2 lists using LINQ?	var cartesianConcat = from a in seq1\n                      from b in seq2\n                      select a + b;	0
28279279	28279085	Backup a database using an sql query with datetime format	string query = string.Format("BACKUP DATABASE DbName TO DISK = 'C:\\app\\dbName{0}.Bak' WITH FORMAT, MEDIANAME = 'dbName', NAME = 'Full Backup of dbName';", DateTime.Now.ToString("yyyyMMdd"));	0
6004796	6002678	Bing Maps route poly line can not be removed from map	private void ResetPoints()\n{\n    if (this.Points.Count() > 0)\n    {\n        var firstPoint = this.Points.First();\n        this.Points.Clear();\n        this.Points.Add(firstPoint);\n    }\n}	0
6542780	6540077	NHibernate Criteria Search By Time Of Day	public class MsSql2008ExtendedDialect : MsSql2008Dialect\n    {\n        public MsSql2008ExtendedDialect()\n        {\n            RegisterFunction("DATEPART_HOUR", new SQLFunctionTemplate(NHibernateUtil.DateTime, "datepart(hh, ?1)"));\n        }\n    }	0
14913462	14913404	Removing duplicates from an array populated by a reader	List<string> distinctValues = new List<string>();\n\nwhile (reader.Read())\n{\n    string[] unique = reader[0].ToString().Split(',').Distinct().ToArray();\n\n    foreach (string s in unique)\n        if (!distinctValues.Contains(s))\n            distinctValues.Add(s);\n}\n\nforeach (string s in distinctValues)\n    dt.Rows.Add(s)	0
19463413	19463261	How do i get id of the image from gridview and increase hits?	protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)\n\n{\n    if (e.CommandName == "selectImage")\n    {\n\n        int rowIndex = Convert.ToInt32(e.CommandArgument); // Get the current row\n        int cellVal = Convert.ToInt32(grdView.Rows[rowIndex].Cells[2].Text);//Get the cell value\n\n        Response.Write(cellVal.ToString());\n\n    }\n}	0
16686066	16685881	Reading XML contents through LINQ to Dropdownlist	var result = XDocument.Load(fileName)\n                .Descendants("Capital")\n                .First(c => (string)c.Attribute("ID") == "1")\n                .Descendants("city")\n                .Select(c => new\n                {\n                    Text = (string)c.Attribute("name"),\n                    Value = (string)c.Attribute("value"),\n                })\n                .ToList();	0
13733673	13733645	Pass in Generic Type to a method	typeof(MyClass<>).MakeGenericType(myType)	0
7404205	2084806	Encapsulate Use Cases in a software	class LeaveManager{\n     int Apply(from, to);\n\n     bool Approve(leaveApplicationId, approverId);\n\n     bool Reject(leaveApplicationId, approverId);\n}	0
18708800	18707806	Kendo UI Grid not populating after call to read	public JsonResult GetImportMessages([DataSourceRequest] DataSourceRequest request, string importdate)\n{\n    IEnumerable<ImportHeader> messages = null;\n\n    var msgs = client.GetStringAsync(string.Format("api/importheaders?$filter=RecordSource eq '{0}'", importdate)).Result;\n    if (!string.IsNullOrWhiteSpace(msgs))\n        messages = JsonConvert.DeserializeObject<IEnumerable<ImportHeader>>(msgs);\n\n    return Json(messages.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);\n}	0
21475937	21475892	How to convert the date that have been retrieve from DB to only display d/mm/yyyy?	((DateTime)readPatient["pDOB"]).ToString("d");	0
11224912	11224335	Simple tutorial for connecting to a database	OracleClient.OracleConnection conn = new OracleClient.OracleConnection ();\nconn.ConnectionString = "Data Source=" + "<oracle data source name>;Integrated Security=yes";\ntry\n{\n  conn.Open();\n  OracleCommand command = conn.CreateCommand();\n  command.CommandText = "UPDATE <TableName> SET Task_status = 'Assigned' WHERE task_id = :taskId";\n\n  OracleParameter taskId = new OracleParameter();\n  taskId.DbType = DbType.Int32;\n  taskId.Value = retval3; // this is your variable, right?\n  taskId.ParameterName = "taskId";\n\n  command.Parameters.Add( taskId );\n\n  command.ExecuteNonQuery();\n  command.Dispose();\n}\ncatch ( Exception ex )\n{ \n  // Handle the exception     \n}\nfinally\n{\n    conn.Close();\n}	0
3499003	3382683	Convert transparent png in color to single color	for (int x = 0; x < bitmap.Width; x++)\n{\n    for (int y = 0; y < bitmap.Height; y++)\n    {\n        Color bitColor = bitmap.GetPixel(x, y);\n        //Sets all the pixels to white but with the original alpha value\n        bitmap.SetPixel(x, y, Color.FromArgb(bitColor.A, 255, 255, 255));\n    }\n}	0
10657276	10657098	Determine if point is in a rectangle using map coordiates	bool PointInRectangle(Point pt, double North, double East, double South, double West)\n{\n    // you may want to check that the point is a valid coordinate\n    if (West < East)\n    {\n        return pt.X < East && pt.X > West && pt.Y < North && pt.Y > South;\n    }\n\n    // it crosses the date line\n    return (pt.X < East || pt.X > West) && pt.Y < North && pt.Y > South;        \n}	0
4686843	4686803	formatting an asp:TextBox with thousand and decimal separators	myTextbox.Attributes.Add("onblur", "myJavascriptFormattingFunction();");	0
4427507	4427483	How to lowercase a string except for first character with C#	String newString = new String(str.Select((ch, index) => (index == 0) ? ch : Char.ToLower(ch)).ToArray());	0
25205916	25205886	How to implement a generic interface which implements another interface?	public interface ITransaction\n{\n\n}\n\npublic interface IVolatileTransaction<T> : ITransaction where T : ITransaction\n{\n\n}	0
25194474	25185522	Convert android json parsing in c#	JObject jsonObject = JObject.Parse(courselist);\n\nforeach (JProperty prop in jsonObject.Properties())\n{\n    Debug.WriteLine(prop.Name);  // chapter1\n    Debug.WriteLine(prop.Value["name"].ToString());  // Successful Sales\n\n    // Get page numbers and URLs\n    int count = 0;\n    foreach (JProperty pageProp in ((JObject)prop.Value).Properties())\n    {\n        if (pageProp.Name != "name")\n        {\n            Debug.WriteLine(pageProp.Name + ": " + \n                            pageProp.Value["url"].ToString());\n            count++;\n        }\n    }\n    Debug.WriteLine(count + " total pages.");\n}	0
29875397	29875250	while writing result into csv , format of number/text not getting set properly	static void WriteCsvFile()\n    {\n        FileInfo file = new FileInfo(@"<Path of the file>");\n        StreamWriter writer = new StreamWriter(@"D:\output.csv", false);\n        writer.WriteLine("{0},{1},{2}", "FNumber", "Name", "Size");\n        writer.WriteLine("{0},{1},{2:D}", "1", "Save.bng", file.Length);\n        writer.Close();\n    }	0
2536277	2536269	Howto write a class where a property can be accessed without naming it	public class MyClass\n{\n    public object this[string key]\n    {\n        get { return SubItems[key]; }\n        set { SubItems[key] = value; }\n    }\n}	0
17192465	17191208	How to get control content from a CustomMessageBox in windows phone	mb.Dismissed += (e1, e2) =>\n{\n    System.Diagnostics.Debug.WriteLine(tbName.Text);\n};	0
26525524	26525182	How to access the table from the Data Source in C#?	foreach(DataRow row in EmployeeDBDataSet.Employee.Rows)\n    {\n        if(row["Your column"].ToString() == password)\n        {\n            // code here\n        }\n    }	0
27548754	27548620	Make a phone call in Windows 8.1	public static void ShowPhoneCallUI(\n  string phoneNumber, \n  string displayName\n)	0
14717477	14576903	Arrange MultiDimensional arrays to descending or ascending	int[,] time = new int[5, 2] { { 0, 4 }, { 1, 5 }, { 5, 10 }, { 3, 4 }, { 0, 2 } };\n\nvar sorted = from x in Enumerable.Range(0, time.GetLength(0))\n                     select new Point()\n                     {\n                         X = time[x,0],\n                         Y = time[x,1]\n                     } into point\n                     orderby point.X ascending , point.Y ascending \n                     select point;\n\nint[,] sortedTime = new int[5,2];\nint index = 0;\nforeach (var testPoint in sorted)\n{\n  Point aPoint = (Point) testPoint;\n  sortedTime.SetValue(aPoint.X, index, 0);\n  sortedTime.SetValue(aPoint.Y, index, 1);\n\n  index++;\n}	0
16507279	16507245	Retrieve information from relational database	Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);\nif (firstArticle != null)\n{\n    textBox1.Text = firstArticle.nameArticle;\n    textBox2.Text = firstArticle.Subject.nameSubject;\n}	0
1644543	1644517	Move items from one listbox to another	foreach ( var item in new ArrayList(from.SelectedItems) ) {\n  from.Items.Remove(item);\n}	0
18741148	18741042	Need to calculate number of rows in sql on the basis of modify date	using (SqlConnection connection = new SqlConnection(connectionString))\n            {\n                connection.Open();\n\n                using (SqlCommand command = new SqlCommand("Select count(ID) from TableName where  ModifyDate>=@Today and ModifyDate<@NextDay", connection))\n                {\n                    command.Parameters.Add(new SqlParameter("Today",  DateTime.Today  ));\n                    command.Parameters.Add(new SqlParameter("Nextday", DateTime.Today.AddDays(1) ));\n\n                    int count = 0;\n                    int.TryParse( command.ExecuteScalar().ToString()   , out count);\n\n                }\n            }	0
24154704	24154590	How to get the extent of a layer in lat long in arcmap in c#	public ISpatialReference CreateSpatialRefGCS(ESRI.ArcGIS.Geometry.esriSRGeoCSType gcsType)\n{\n    ISpatialReferenceFactory spatialRefFactory = new SpatialReferenceEnvironmentClass();\n    IGeographicCoordinateSystem geoCS = spatialRefFactory.CreateGeographicCoordinateSystem((int)gcsType);\n    return (ISpatialReference)geoCS;\n}\n\npublic IEnvelope GetExtent(IFeatureLayer PolygonLayer) {\n    IEnvelope envelope = PolygonLayer.AreaOfInterest.Envelope;\n    envelope.Project(CreateSpatialRefGCS(esriSRGeoCSType.esriSRGeoCS_WGS1984));\n    return PolygonLayer.AreaOfInterest.Envelope;\n}	0
18403705	18403682	How to select multiple properties properly?	foreach (var ps in new MyEntity().MyObject.Select(o => new { o.p1, o.p2 }))\n       {\n            p1Sum += ps.p1;\n            p2Sum += ps.p2;   \n       }	0
18790340	18790273	Need to remove white space between two tags with Regex	var output = Regex.Replace(input, @"<mattext>\s*<", "<mattext><", RegexOptions.Multiline);	0
11987194	11984934	Replace first time a combination of chars occur in a string VB.NET	if(result.StartsWith("00"))\n       result= result.Replace(result.Substring(0, 2), "+");	0
25920110	25920004	c# For every 7 letters in the string add item string to Listbox	ListBox box = null;//set it yourself\nfor(int i = 0; i < s.Length; i+= 7)\n{\n    box.Items.Add(s.SubString(i, Math.Min(s.Length - i, 7));\n}	0
3253985	3200898	Master detail grid in Silverlight 4 - No headers for Detail grid	HeadersVisibility = false	0
18699541	18699321	Getting the key value paired differences in two data rows?	var updates = currentRow.ItemArray\n    .Select((o, i) => new { Row = o, Index = i })\n    .Where(r => (r.Row == null && updatedRow[r.Index] != null)\n        || (r.Row != null && updatedRow[r.Index] != null\n        && !r.Row.Equals(updatedRow[r.Index])))\n    .Select(r => new\n    {\n        Key = updatedRow.Table.Columns[r.Index].ColumnName,\n        Value = Convert.ToString(updatedRow[r.Index])\n    }).ToList();	0
24595910	23977753	ASP.NET Get all user sessions for web application	session_start/session_end	0
17955946	17945855	How to set databaseInstanceName in Database Trace Listener from C# code?	var configurationSourceBuilder = new ConfigurationSourceBuilder();\n\n// do other configuration here\n\nconfigurationSourceBuilder\n    .ConfigureLogging()\n        .LogToCategoryNamed("Category")\n            .SendTo.Database("Database Trace Listener")\n                .UseDatabase("DatabaseInstance");\n\n// or here\n\nvar configurationSource = new DictionaryConfigurationSource();\nconfigurationSourceBuilder.UpdateConfigurationWithReplace(configurationSource);\nEnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource);	0
5142535	5142394	Dynamically change resource of executable	AppDomain.CurrentDomain.SetData("CONFIG_FILE", "C:\Path\To\File.config");	0
1318629	241222	Need to disable the screen saver / screen locking in Windows C#/.Net	SetThreadExecutionState(ES_DISPLAY_REQUIRED)	0
2666445	2666274	How to eliminate "else-if" statements	public QueryStringParser(string QueryString)\n{\n    this._mode = DetermineMode(QueryString);\n}\n\nprivate Mode DetermineMode(string QueryString)\n{\n    // Input is NULL STRING\n    if (string.IsNullOrEmpty(QueryString))\n        return Mode.First;\n\n    bool hasFirst = QueryString.Contains(_FristFieldName);\n    bool hasSecond = !QueryString.Contains(_SecondFieldName);\n\n    // Query using FirstName\n    if (hasFirst && !hasSecond)\n        return Mode.Second;\n\n    //Query using SecondName\n    if (!hasFirst && hasSecond)\n        return Mode.Third;\n\n    //Insufficient info to Query data\n    throw new ArgumentException("QueryString has wrong format");\n}	0
13447866	13392017	How to change order of dynamic filter controls?	Control date_filter = FilterRepeater.Controls[1];\nFilterRepeater.Controls.RemoveAt(1);\nFilterRepeater.Controls.Add(date_filter);	0
26588838	26588774	How can I time how long it takes a small block of C# code to execute?	using System.Diagnostics;\n\n...\n\nStopwatch stopWatch = new Stopwatch();\n\nstopWatch.Start();\n\nvar userId = Int32.Parse(User.Identity.GetUserId());\n  using (var context = new IdentityContext())\n  {\n      roleId = context.Database.SqlQuery<int>("SELECT RoleId FROM AspNetUserRoles where UserId = " + userId).FirstOrDefault();\n  }\n\nstopWatch.Stop();\n\nTimeSpan ts = stopWatch.Elapsed;\n\nstring elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds / 10);	0
17970196	17966670	Two implementations of a method? (VS2012 + ReSharper 7.1)	Alt-Shift-T	0
23448219	23438259	How do I unit test a nested foreach loop?	var repo = new Mock<MyRepository>();\nrepo.Setup(r => r.GetParentObjects()).Returns(... a list with a couple of parent objects ...);\nrepo.SetUp(r => r.GetChildObjects(... id of first parent ...)).Returns(... list of child objects ...);\nrepo.SetUp(r => r.GetChildObjects(... id of secondparent ...)).Returns(... different list of child objects ...);\n\nvar result = new MyClass(repo.Object).GetParentAndChildObjects();\n\n... assertions to check 2 parents with appropriate children returned ...	0
9469426	9469306	deserialization of json string in c#	string s = "{\"data\":[{\"description\":\"xxxxxx\",\"created_time\":1330356685},    {\"description\":\"zzzz\",\"created_time\":1329817903}]}";\nJavaScriptSerializer jss = new JavaScriptSerializer();\nNewFriends nFrnds = jss.Deserialize(s, typeof(NewFriends)) as NewFriends;\nMessageBox.Show(nFrnds.data.Length.ToString());	0
27282255	27282156	C# compare multiple textbox values	List<TextBox> myTextBoxes = new List<TextBox>();\n\n//Add your textboxes to the list here...\n\nvar distinctBoxes = myTextBoxes.GroupBy(t=>T.Text);\nif(distinctBoxes.Count() == 4)\n{\n    //All values are distinct\n}\nelse\n{\n    foreach(var g in distinctBoxes.Where(g=>g.Count() > 1))\n    {\n        //These are the duplicate boxes\n    }\n}	0
4567154	4567147	Temp modification of NHibernate Entities	ISession.Evict	0
33375933	33375795	Adding a single backslash to a string to use in querying a Lucene Index	var parsed = query.Replace(" ", "?");	0
6739287	6729594	Writing contents of a DirectSound CaptureBuffer to a WAV file in C#	WaveFormat format = new WaveFormat(16000, 16, 1); // for mono 16 bit audio captured at 16kHz\nusing (var writer = new WaveFileWriter("out.wav", format)\n{\n    writer.WriteData(captureBuffer, 0, captureBuffer.Length);\n}	0
16858693	16857746	how to convert my base64string to bitmap in windows phone?	public void ConvertThis(string ImageText)\n{\n   if (ImageText.Length > 0)\n   {\n      Byte[] bitmapData = new Byte[ImageText.Length];\n      bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));\n      System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);\n      Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));\n   }\n}\n\npublic string FixBase64ForImage(string Image)\n{\n   System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image,Image.Length);\n   sbText.Replace("\r\n", String.Empty);\n   sbText.Replace(" ", String.Empty);\n   return sbText.ToString();\n}	0
13466610	13466176	Console application no more console after ILMerged	/target:exe	0
14812272	14812221	splitting a label that contains text and numbers	string[] data = label1.Text.Split(' ');\nlabel2.Text = data[0];\nlabel3.Text = data[1];	0
13382721	13381967	Show WPF window from test unit	[TestMethod]\n    public void TestMethod1()\n    {\n        MainWindow window = null;\n\n        // The dispatcher thread\n        var t = new Thread(() =>\n        {\n            window = new MainWindow();\n\n            // Initiates the dispatcher thread shutdown when the window closes\n            window.Closed += (s, e) => window.Dispatcher.InvokeShutdown();\n\n            window.Show();\n\n            // Makes the thread support message pumping\n            System.Windows.Threading.Dispatcher.Run();\n        });\n\n        // Configure the thread\n        t.SetApartmentState(ApartmentState.STA);\n        t.Start();\n        t.Join();\n    }	0
844435	844423	Set folder browser dialog start location	fdbLocation.SelectedPath = myFolder;	0
33813547	33811212	WPF - Bind Teeview to List	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        DataContext = this;\n\n        criteriaBundle = new ObservableCollection<CriteriaItem> {new CriteriaItem("root")};\n    }\n\n    public ObservableCollection<CriteriaItem> criteriaBundle { get; set; }\n}	0
11976122	11967883	How to include resources of a module in alternative views in Orchard?	Script.Require("somescript");	0
9095329	9095200	how to generate this list with asp.net?	//divMain should be a reference to the 'items' div...\n\nint i = 0;\n\nSystem.Web.UI.HtmlControls.HtmlGenericControl divCurrent = \n    new System.Web.UI.HtmlControls.HtmlGenericControl("div");\n\n\nforeach (string imgSrc in imgSrcs)\n{\n    Image img = new Image();\n    img.ImageUrl = imgSrc;\n    divCurrent.Controls.Add(img);\n    if (i++ ==5) {\n        divMain.Controls.Add(divCurrent);\n        divCurrent = new System.Web.UI.HtmlControls.HtmlGenericControl("div");\n        i = 0;\n    }\n}\n\n//then add the stragglers...\nif (divCurrent.Controls.Count > 0) divMain.Controls.Add(divCurrent);	0
20709560	20709543	How to detect if var is a string	if (sentNUD.Value.GetType() == typeof(string))\n{\n// string stuff\n}	0
24488753	24488681	second column of grid view accept only numbers in c# windows forms	private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n{\n    if (e.ColumnIndex == 1)\n    {\n        int i;\n\n        if (!string.IsNullOrEmpty(e.FormattedValue)  && !int.TryParse(Convert.ToString(e.FormattedValue), out i))\n        {\n            e.Cancel = true;\n            label1.Text ="please enter numeric";\n        }\n        else\n        {\n\n        }\n    }\n}	0
8668370	8668250	How to write an xml attribute without replace all attributes?	var doc = new XmlDocument();\ndoc.Load(path);\ndoc.DocumentElement.SetAttribute(key, value);\ndoc.Save(path);	0
22101266	22052347	Upload > 5 MB files to sharepoint 2013 programmatically	MemoryStream destStream;\n\nusing (System.IO.FileStream fInfo = new FileStream(fileInfo.FullName, FileMode.Open))\n{\n\n    byte[] buffer = new byte[16 * 1024];\n    byte[] byteArr;\n\n    using (MemoryStream ms = new MemoryStream())\n    {\n        int read;\n        while ((read = fInfo.Read(buffer, 0, buffer.Length)) > 0)\n        {\n            ms.Write(buffer, 0, read);\n        }\n        byteArr = ms.ToArray();\n    }\n\n    destStream = new MemoryStream(byteArr);\n\n    Microsoft.SharePoint.Client.File.SaveBinaryDirect(\n        context,\n        serverRelativeURL + directory + fileInfo.Name,\n        destStream,\n        true);\n\n    context.ExecuteQuery();\n    results = "File Uploaded";\n    return true;\n}	0
11393835	11393588	Different view for Ajax postback without duplicating controller	public ActionResult AddToCart(YourCartViewmodel cartViewmodel)\n{\n     if (ModelState.IsValid)\n     {\n         // do the standard/common db stuff here\n         if(Request.IsAjaxRequest())\n         {\n             return PartialView("myPartialView");\n         }\n         else\n         {\n             return View("standardView");\n         }\n     }\n     /* always return full 'standard' postback if model error */\n     return View(cartViewmodel);   \n}	0
15642397	15642288	Detect bet regex	bool ChechResult(int value)\n{\n    String input = @"L( 24, 25, 26, 27)";\n    String pattern = @"\d+";\n    foreach (Match match in Regex.Matches(input, pattern))\n    {\n        if(value == int.Parse(match.Value))\n        {\n            return true;\n        }\n    }\n    return false;\n}	0
7185208	1267122	Convert snippet from c# to vbscript	Dim sbox(255)\nDim key(255)\n\nSub RC4Initialize(strPwd)\n  dim tempSwap\n  dim a\n  dim b\n\n  intLength = len(strPwd)\n  For a = 0 To 255\n     key(a) = asc(mid(strpwd, (a mod intLength)+1, 1))\n     sbox(a) = a\n  next\n\n  b = 0\n  For a = 0 To 255\n     b = (b + sbox(a) + key(a)) Mod 256\n     tempSwap = sbox(a)\n     sbox(a) = sbox(b)\n     sbox(b) = tempSwap\n  Next\n\nEnd Sub\n\nFunction EnDeCrypt(plaintxt)\n  dim temp\n  dim a\n  dim i\n  dim j\n  dim k\n  dim cipherby\n  dim cipher\n\n  i = 0\n  j = 0\n\n  RC4Initialize "somesortofpassword"\n\n  For a = 1 To Len(plaintxt)\n     i = (i + 1) Mod 256\n     j = (j + sbox(i)) Mod 256\n     temp = sbox(i)\n     sbox(i) = sbox(j)\n     sbox(j) = temp\n\n     k = sbox((sbox(i) + sbox(j)) Mod 256)\n\n     cipherby = Asc(Mid(plaintxt, a, 1)) Xor k\n     dim h\n     h = hex(cipherby)\n     if Len(h) = 1 then\n        h = "0" & h\n      end if\n     cipher = cipher & h\n  Next\n\n  EnDeCrypt = cipher\nEnd Function	0
31706519	31705892	How to load an image asynchronously from URI in Xamarin forms	System.Uri uri;\nSystem.Uri.TryCreate(imageURI, UriKind.Absolute, out uri);\nTask<ImageSource> result = Task<ImageSource>.Factory.StartNew(() => ImageSource.FromUri(uri));\n_companyImage.Source = await result;	0
33267640	33266660	Linq select data from 3 tables	from d in Skills\nwhere (d.SkillID == 5 || d.SkillID == 6 || d.SkillID == 7) // or is not supported\nselect new\n{\n    Description = d.Description,\n    Employees = EmployeeSkills\n            .Where(es => es.SkillID == d.SkillID)\n            .Select(es => new \n            {\n                Level = es.Level,\n                YearsExperience = es.YearsOfExperience,\n                Emp = Employees.Single(emp => emp.EmployeeID == es.EmployeeID)                    \n            })\n            .Select(es => new \n            {\n                Level = es.Level,\n                YearsExperience = es.YearsExperience,\n                Name = es.Emp.FirstName + " " + es.Emp.LastName))                    \n            })           \n}	0
15505205	15505051	how to use Ninject intercept using InterceptAttribute	public class MyService : IMyService\n{\n    Logger log;\n\n    public MyService()\n    {\n        log = LogManager.GetLogger(this.GetType().FullName);\n    }\n\n    [Timing]\n    public virtual string GetString()\n    {\n        log.Info("log me!!");\n        return "Cool string !!!!";\n    }\n\n    public string GetUnInterceptString()\n    {\n        return "Not intercepted";\n    }\n}	0
21083031	21082694	XAML SampleData Binding to Values of a List of Strings	Text="{Binding}"	0
3005991	3005015	Excel c# convert cell to percentage	Excel.Range procentRange = xlWorksheet.get_Range("A1","A1");    \nprocentRange.NumberFormat = "###,##%";	0
11988694	11988608	Parsing a specific string to a DateTime	DateTime dt = DateTime.ParseExact("Mon Aug 13 15:04:51 -0400 2012",\n                                  "ddd MMM dd HH:mm:ss K yyyy",\n                                  CultureInfo.InvariantCulture)	0
22790754	22789411	Elastic Search to search for words that starts with phrase	curl -XPOST "http://localhost:9200/try/indextype/_search" -d'\n{\n"query": {\n    "prefix": {\n       "field": {\n          "value": "Butter"\n       }\n    }\n}\n}'	0
16978560	16978519	c# Dictionary<char,int> picking the key with the largest value	var item = charstat.OrderByDescending(r => r.Value)\n                          .Select(r => r.Key)\n                          .Take(5);	0
5251567	5251524	How could I download a file like .doc or .pdf from internet to my harddrive using  c#	using (var client = new System.Net.WebClient())\n{\n    client.DownloadFile( "url", "localFilename");\n}	0
8135071	8134945	LINQ on a double**	var topIndexes = Enumerable.Range(1, n-1)\n   .Select(index => new { index, relation = GetRelation(A[0], A[index]) })\n   .OrderByDescending (x => x.relation)\n   .Select(x => x.index);	0
24173462	24173425	How can I call C++ function from C# project	[DllImport("user32.dll")]\nstatic extern bool SetWindowDisplayAffinity(IntPtr hwnd, DisplayAffinity affinity);\n\nenum DisplayAffinity : uint\n{\n   None = 0,\n   Monitor = 1\n}	0
34157214	34156818	Get Current Method Name	public string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")\n{\n     return memberName;\n}	0
15026355	15025960	Add new column to DB	public class Work\n{\n   [Key]\n   public int id; {get; set;}\n\n   [ForeignKey("Member")]\n   public int memberId {get; set;}\n\n   public virtual Member Member {get; set;}\n}	0
17673377	17673093	passing parameters while sending mail	message.Body += "Hello <b>"+Session["Manager"].ToString()+"</b>,<br /><br />";\n  message.Body += Session["LoggedInUser"].ToString()+"has requested"+\n                  Session["TypeOfLeave"].ToString()+"for "+Session["NoOfDays"].ToString()+\n  mesaage.Body += "kindly login to the portal to accept or reject it";	0
32185955	32185570	stackpanel items alignment	Panel.Children.OfType<Control>().ToList().ForEach(child=>child.HorizontalAlignment =HorizontalAlignment.Left);	0
6331335	6331297	Ordering by the many side of an entity framework join	.OrderBy(i => i.MenuItems.SelectMany(c=>c.Course).DisplayOrder)	0
18846573	18823302	Change color of specific cells in DataGridView	dg.Rows[x].Cells[y].Style.BackColor = Color.Red;	0
12760939	12759707	Inserting into multiple tables ASP.NET & C#	using(TransactionScope tscope = new TransactionScope())\n{\n    using(SqlConnection conn = new SqlConnection(myconnstring)\n    {\n        conn.Open();\n\n        ... Call the necessary stored proc here\n\n        tscope.Complete();\n        conn.Close();\n    }\n}	0
11976735	11976602	How do I create a custom struct compatible with Rectangle?	class SmallRectangle\n{\n    public byte x { get; set; }\n    public byte y { get; set; }\n\n    public SmallRectangle(byte inx, byte iny)\n    {\n       x = inx;\n       y = iny;\n    }\n\n    public static explicit operator SmallRectangle(Microsoft.Xna.Framework.Rectangle big)\n    {\n        SmallRectangle small = new SmallRectangle((byte)big.x, (byte)big.y);\n\n        return small;\n    }\n\n    public WriteToFile(FileStream out)\n    {\n       //....\n    }\n}	0
32129911	28142064	MAC address of NIC card is changing	Status  NetworkInterfaceType    Speed       GetPhysicalAddress()    Description\n0   Down    Wireless80211           0           XXXXXXXXXXXX            Realtek RTL8188CUS Wireless LAN 802.11n USB Slim Solo\n1   Down    Wireless80211           0           XXXXXXXXXXXX            Microsoft Wi-Fi Direct Virtual Adapter\n2   Up      Ethernet                100000000   XXXXXXXXXXXX            Realtek PCIe GBE Family Controller\n3   Down    Ethernet                3000000     XXXXXXXXXXXX            Bluetooth Device (Personal Area Network)\n4   Up      Loopback                            XXXXXXXXXXXX            Software Loopback Interface 1\n5   Up      Tunnel                  100000      00000000000000E0        Microsoft Teredo Tunneling Adapter\n6   Down    Tunnel                  100000      00000000000000E0        Microsoft ISATAP Adapter	0
24703425	24702530	How to open a new tab in asp.net	protected void Button1_Click(object sender, EventArgs e)\n{\n    string url = "http://www.stackoverflow.com";\n    string script = string.Format("window.open('{0}');", url);\n\n    Page.ClientScript.RegisterStartupScript(this.GetType(), \n        "newPage" + UniqueID, script, true);\n\n    /* Use this if post back is via Ajax\n    ScriptManager.RegisterStartupScript(Page, Page.GetType(), \n        "newPage" + UniqueID, script, true); */\n}	0
33150604	33150518	How can I get an element in an array based on value rather than index with Json.NET in C#?	void Main()\n{\n    var root = JsonConvert.DeserializeObject<RootObject>(json);\n    var selectedTravel = root.Travels.FirstOrDefault(x => x.Id == 2);\n}\n\npublic class Travel\n{\n    [JsonProperty("date")]\n    public DateTime Date { get; set; }\n    [JsonProperty("id")]\n    public int Id { get; set; }\n}\n\npublic class RootObject\n{\n    public List<Travel> Travels { get; set; }\n}	0
22135328	22135275	How To Convert a Single Byte to a String	System.Text.Encoding.ASCII.GetString(new[]{myByte})	0
8283198	8283142	Dynamic gridview - how to reference in rowdatabound	GridView gdv = new GridView();\ngdv.ID = "gdv" + i.ToString();\npanel.Controls.Add(gdv);\n\n//set grid props	0
894912	894905	How to replace occurrences of "-" with an empty string?	string r = "123-456-7";\nr = r.Replace("-", "");	0
27872374	27872321	trouble converting function from vb to c#	public static List<DateTime> GetHolidays(string holidaysFile)\n{\n    string[] sAllDates = File.ReadAllLines(holidaysFile);\n    return (from sDate in sAllDates select Convert.ToDateTime(sDate)).ToList();\n}	0
2118086	2118068	Is there a way to retrieve the last character of a file without reading line by line?	string s = File.ReadAllText("test.txt");\nstring[] split = s.Split(s[s.Length - 1]);	0
29449587	29449038	select specific columns when using include statement with entity framework	var results = context.Products\n        .Include("ProductSubcategory")\n        .Where(p => p.Name.Contains(searchTerm)\n                    && p.DiscontinuedDate == null)\n        .Select(p => new\n                        {\n                            p.ProductID,\n                            ProductSubcategoryName = p.ProductSubcategory.Name,\n                            p.Name,\n                            p.StandardCost\n                        })\n        .AsEnumerable()\n        .Select(p => new AutoCompleteData\n                            {\n                                Id = p.ProductID,\n                                Text = BuildAutoCompleteText(p.Name,\n                                    p.ProductSubcategoryName, p.StandardCost)\n                            })\n        .ToArray();	0
24551972	24427768	Retrieving the Request Payload values from a HTTPRequest in c#	public void Put([FromBody]TinCan.Statement statement)\n{\n   var actor = statement.actor;\n   var context = statement.context;\n   var target = statement.target;\n   var timestamp = statement.timestamp;\n   var verb = statement.verb;\n\n   ...................	0
28404990	28404808	How to Wait 5 second after trigger is activated?	using UnityEngine;\nusing System.Collections;\n\npublic class DestroyerScript : MonoBehaviour {\n\n\nbool dead;\n\nIEnumerator OnTriggerEnter2D(Collider2D other)\n{\n    if (other.tag == "Player") \n    {\n        yield return new WaitForSeconds(5);\n        Application.LoadLevel("GameOverScene");\n        dead = true;\n        return dead;\n\n    }\n\n}\n}	0
868583	868572	How to convert object[] to List<string> in one line of C# 3.0?	List<string> fields = values.Select(i => i.ToString()).ToList();	0
958373	958273	CDATA in XML using C#	private static void WriteProperty(XmlWriter writer, string name, string type, string value)\n{\n    writer.WriteStartElement("Property");\n    writer.WriteAttributeString("name", name);\n    writer.WriteAttributeString("type", type);\n    writer.WriteCData(value);\n    writer.WriteEndElement();\n\n}\n\n// call the method from your code\nXPathExpression query = xPathNavigator.Compile(xpath);    \nXPathNavigator node = xPathNavigator.SelectSingleNode(query.Expression, xmlNamespaceManager);\nusing (XmlWriter writer = node.AppendChild())\n{\n    WriteProperty(writer, "someName", "String", "someValue");\n}	0
29942319	29942225	Generate Date Time offset	DateTimeOffset modified = input.AddMonths(-2);	0
19248298	19247822	Updating a Label with the backgroundworker progress	label2.Invoke(new Action(() => { label2.Text = e.ToString(); }));\nlabel2.Invoke(new Action(() => { label2.Refresh(); }));	0
2465045	2465040	Using lambda expressions for event handlers	public partial class MyPage : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        //snip\n        MyButton.Click += new EventHandler(delegate (Object o, EventArgs a) \n        {\n            //snip\n        });\n    }\n}	0
10993626	10993404	Write to a file but conversion cannot be done	string fileOut = ((Request.QueryString["msisdn"] )+ (Request.QueryString["shortcode"]) + (Request.QueryString["password"]).ToString());\n\nstring mydocpath = \n        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n    StringBuilder sb = new StringBuilder();\n\n    foreach (string txtName in Directory.EnumerateFiles(mydocpath,"outputreport.txt")) \n    {\n        using (StreamReader sr = new StreamReader(txtName))\n        {\n            sb.AppendLine(fileOut);\n            sb.AppendLine("= = = = = =");\n            sb.Append(sr.ReadToEnd());\n            sb.AppendLine();\n            sb.AppendLine();\n        }\n\n    }\n\n    using (StreamWriter outfile = \n        new StreamWriter(mydocpath + @"\outputreport.txt"))\n    {\n        outfile.Write(sb.ToString());\n    }	0
4721007	4720829	same problem with treeview	CTreeNode[] nodes = this.treeview.Nodes.Find(node.Name, true);\nList<CTreeNode> nodepath = new List<CTreeNode>();\nGetNodePath(nodes[0], nodepath);\n\nprivate void GetNodePath(CTreeNode node, List<CTreeNode> nodepath) {\n    nodepath.Add(node);\n    if (node.Parent != null) {\n        GetNodePath(node.Parent, nodepath);\n    }\n}	0
14498870	14431936	How to force datagridviewcell to end edit when row header is clicked	private void dataGridView_MouseClick( object sender, MouseEventArgs e ) {\n  DataGridView dgv = (DataGridView)sender;\n  if (dgv.HitTest(e.X, e.Y).Type == DataGridViewHitTestType.RowHeader) {\n    dgv.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;\n    dgv.EndEdit();\n  } else {\n    dgv.EditMode = DataGridViewEditMode.EditOnEnter;\n  }\n}	0
10306066	10290945	Correct use of UDP DatagramSocket	public UdpSocketClient(IPEndPoint remoteEndPoint, int localPort)\n        {\n            this.remoteEndPoint = remoteEndPoint;\n#if WINRT\n            this.socket = new DatagramSocket();\n            this.socket.MessageReceived += ReceiveCallback;\n\n            Logger.Trace("{0}: Connecting to {1}.", this, remoteEndPoint);\n            IAsyncAction connectAction = this.socket.ConnectAsync(remoteEndPoint.address, remoteEndPoint.port.ToString());\n            connectAction.AsTask().Wait();\n            Logger.Trace("{0}: Connect Complete. Status {1}, ErrorCode {2}", this, connectAction.Status, \n                connectAction.ErrorCode != null ? connectAction.ErrorCode.Message : "None");\n\n            dataWriter = new DataWriter(this.socket.OutputStream);\n#else\n            ...\n#endif\n        }	0
602107	601985	Reading Xml into a datagrid in C#	DataSet ds = new DataSet();\n        XmlTextReader xmlreader = new XmlTextReader(xmlSource, XmlNodeType.Document, null);\n        ds.ReadXml(xmlreader);	0
22804170	22780600	How to navigate links by button in WPF Modern UI in C#?	private void addGameButton_Click(object sender, RoutedEventArgs e)\n{\n    BBCodeBlock bs = new BBCodeBlock();\n    try\n    {\n        bs.LinkNavigator.Navigate(new Uri("/Pages/AddGame.xaml", UriKind.Relative), this);\n    }\n    catch (Exception error)\n    {\n        ModernDialog.ShowMessage(error.Message, FirstFloor.ModernUI.Resources.NavigationFailed, MessageBoxButton.OK);\n    }\n}	0
3303868	3301948	How can I retrieve a DataGridView from the clipboard? (It ends up being Null in clipboard)	Private Sub mnuCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCopy.Click\n    If dgvDisplaySet.GetClipboardContent Is Nothing Then\n        MsgBox("Nothing selected to copy to clipboard.")\n    Else\n        Clipboard.SetDataObject(dgvDisplaySet.GetClipboardContent)\n    End If\nEnd Sub	0
20704660	20704241	Set empty 'Start-Text' for ToolStripComboBox with DataSource	private void Init()\n{\n    cmbHersteller.Items.Clear();\n\n    var list = _pricelist.GetHersteller();\n    list.Insert(0, "");\n    cmbHersteller.ComboBox.DataSource = list;\n\n    cmbHersteller.ComboBox.SelectedIndex = 0;\n}	0
8527573	5399061	How to access columns in a table that have different cell widths from MS Word	for (int r = 1; r <= rng.Tables[1].Row.Count; r++)\n        {\n            for (int c = 1; c <= rng.Tables[1].Columns.Count; c++)\n            {\n                try\n                {\n                    Cell cell = table.Cell(r, c);\n                    //Do what you want here with the cell\n                }\n                catch (Exception e)\n                {\n                    if (e.Message.Contains("The requested member of the collection does not exist."))\n                    {\n                       //Most likely a part of a merged cell, so skip over.\n                    }\n                    else throw;\n                }\n            }\n        }	0
4734020	4733965	How to call this kind of implementation in Java and how to change it to C#?	public class B : A\n{\n   protected override void call1()\n   {\n      //new code here...\n   }\n}	0
20353376	20352561	Delete Row from DataGridView and Access Database, it`s delete my all database	foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)\n            {\n                dataGridView1.Rows.RemoveAt(item.Index);\n\n                con.Open();\n                ad.SelectCommand = new OleDbCommand("delete * from Animale where id = " + item.id.ToString, con);\n            }	0
9749343	9749319	How to check the Sub Dir's	foreach(var fi in di.EnumerateFiles(pattern, SearchOption.AllDirectories))\n    yield return fi;	0
28112472	28111174	Change OWIN Identity password with out old password by code?	var userId = User.Identity.GetUserId();\n\nvar token = await UserManager.GeneratePasswordResetTokenAsync(userId);\n\nvar result = await UserManager.ResetPasswordAsync(userId, token, newPassword);	0
7076279	7075932	I want to remove xml node from file where in xml user selects path?	string path4 = treeView1.SelectedNode.FullPath.ToString();\nXmlNode nodeToRemove = doc.SelectSingleNode(path4);\nXmlNode parentNode = nodeToRemove.ParentNode;\nparentNode.RemoveChild(nodeToRemove);	0
3601630	3600736	WPF XML Databind to ComboBox	XmlNode element = this.LocationCombo.SelectedItem as XmlNode;\nMessageBox.Show(element.Attributes["LCode"].Value.ToString() + element.InnerText.ToString());	0
3999545	3999514	Return a collection of objects from a bitmask	public static List<Thing> Decode(ushort mask) { \n  var list = new List<Thing>();\n  for ( var index = 0;  index < 16; index++ ) {\n    var bit = 1 << index;\n    if ( 0 != (bit & mask) ) { \n      list.Add(new Thing(index));\n    }\n  }  \n  return list;\n}	0
4028226	4028112	Is it possible to pass a new parameter value into a running thread?	object state	0
3023846	3023620	Insert a default row into a combobox that is bound to a datatable?	var list = table.AsEnumerable().Select(row => row.Field<string>("fieldA")).ToList();\nlist.Insert(0, "*");\nthis.cboList.DataSource = list;	0
3308996	3308982	Looking for a pattern / keep a property of several objects in sync	Observer pattern	0
11132572	11054449	Fluent Nhinernate mapping for hierarchical/ tree structure table	public class Employee\n{\n   public virtual long Id {get; private set;}\n   public virtual string FirstName {get;set;}\n   public virtual string LastName {get;set;}\n   public virtual Employee Manager {get;set;}\n   public virtual ICollection<Employee> ManagedEmployees {get; private set;}\n}\n\npublic class EmployeeMap : MapClass<Employee>\n{\n   Table("TEmployee");\n   SchemaAction.None();\n\n   Id(e => e.Id).GeneratedBy.HiLow("1000");\n   References(e => e.Manager, "ManagerId");\n   HasMany(e => e.Manager).KeyColumn("ManagerId").Cascade.All();\n}	0
10602021	10601453	How to retrieve value from attribute in XML?	string[] myString = new string[3];\n  //  for (int i = 0; i < 3; i++)\n  //  {\n        int i = 0;\n        foreach (string item in query)\n        {\n            myString[i] = (string)item;\n            i += 1;\n        }\n  //  }	0
16043084	15980979	ODP.NET Connection Pooling Parameters	Max Pool Size * Number of Worker Processes	0
14463029	14461746	DataGrid Horizontal Binding	Binding = new Binding(stat.Key) { Converter = new StatisticPersonalizedValueConverter() }\n\n\n\npublic class StatisticPersonalizedValueConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        if (value is StatisticPersonalizedValue)\n        {\n            return (value as StatisticPersonalizedValue).Value;\n        }\n        return string.Empty;\n\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        throw new NotImplementedException();\n    }\n}	0
12974779	12974515	How to update database using OleDbDataAdapter with sql query?	var cmd = new OleDbCommand("UPDATE tab1 SET col1 = col1*2, col2 = 300 WHERE col1 = 5", connection);\ncmd.ExecuteNonQuery();	0
6487628	6487576	bind a list variable to text box	public clas MyForm : Form\n{\n    List<ore> books = new List<ore>();//define at the class scope\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        FileStream fs = new FileStream("ore.dat", FileMode.Open);\n        BinaryFormatter bf = new BinaryFormatter();\n        books = (List<ore>)bf.Deserialize(fs);\n        fs.Close();\n\n        if (books.Count > 1)\n        {\n            textBox3.Text = books[0];//update the first text\n            textBox4.Text = books[1];//update the second text\n        }\n    } \n}	0
53776	53545	Get the App.Config of another Exe	System.Configuration.ConfigurationManager.AppSettings["myKey"]	0
19244067	19239924	How to pass cell values of grid view to message box	protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)\n {\n ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Are You sure to Delete EmpId:" + grid_admin.Rows[e.RowIndex].Cells[2].Text + " from the Role" + grid_admin.Rows[e.RowIndex].Cells[1].Text +"')", true); \n   }	0
14636838	14636787	Add a line in a txt file	public void InsertLineBefore(string file, string lineToFind, string lineToInsert)\n{\n    List<string> lines = File.ReadLines(file).ToList();\n    int index = lines.IndexOf(lineToFind);\n    // TODO: Validation (if index is -1, we couldn't find it)\n    lines.Insert(index, lineToInsert);\n    File.WriteAllLines(file, lines);\n}\n\npublic void InsertLineAfter(string file, string lineToFind, string lineToInsert)\n{\n    List<string> lines = File.ReadLines(file).ToList();\n    int index = lines.IndexOf(lineToFind);\n    // TODO: Validation (if index is -1, we couldn't find it)\n    lines.Insert(index + 1, lineToInsert);\n    File.WriteAllLines(file, lines);\n}	0
18403059	18402999	Set custom parameter in Route	routes.MapRoute(\n    name: "Plugin",\n    url: "{pluginName}/{controller}/{action}/{id}",\n    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }\n);\n\nroutes.MapRoute(\n    name: "Default",\n    url: "{controller}/{action}/{id}",\n    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }\n);	0
16502138	16502083	Dynamic column in Linq	var currentLang = GetCurrentLang();\nvar queryCountries = db.Countries.Where(r => r.Cities.Count > 0 );\n\nif (currentLang == "es")\n{\n   queryCountries = queryCountries.OrderBy(c => c.Name_Es);\n}\nelse if (...) // etc.	0
17958445	17958146	How to handle end of file when reading xml file	var doc = XDocument.Load(textReader);\nforeach (var commandXml in doc.Descendants("Command"))\n{\n    var command = new ATAPassThroughCommands();\n    var name = commandXml.Descendants("Name").Single().Value;\n    // I'm not sure what this does but it looks important...\n    CommandListContext.Add(name); \n    command.m_Name = name;\n    command.m_CMD = \n         Convert.ToByte(commandXml.Descendants("CMD").Single().Value, 16);\n    command.m_Feature = \n         Convert.ToByte(commandXml.Descendants("Feature").Single().Value, 16);\n    m_ATACommands.Add(command);\n}	0
31513385	31510232	Read serial port work good in windows XP but stop working and slow in windows 7	private void type(byte[] data)\n{\n   ...\n   serialPort1.DiscardInBuffer();\n}	0
19818683	19817944	using Linq - get groups from db table where one record in each group matches a search	...\nvar records = db.Records\n        .GroupBy(r => r.Group)\n        .Where(g => g.Any(r => r.Action == requestedAction && \n                               r.Username == requestedUsername)));\n...	0
22372892	22372613	Sorting of IPs in C#	List<string> unsortedIps = new List<string>();\n        unsortedIps.Add("192.168.1.103");\n        unsortedIps.Add("192.168.1.95");\n        unsortedIps.Add("192.168.1.4");\n        unsortedIps.Add("10.152.16.23");\n        unsortedIps.Add("192.168.1.1");\n\n        var sortedIps = unsortedIps\n            .Select(Version.Parse)\n            .OrderBy(arg => arg)\n            .Select(arg => arg.ToString())\n            .ToList();	0
8305790	8305673	Retireve a query as a byte array	try {\n         Reader = command.ExecuteReader();\n         if (Reader.Read())\n          {\n              return Reader.GetValue(0) as Byte[];\n          }\n        } finally {\n           MySqlCon.Close();\n        }	0
10705213	10697586	Trying to convert string to MarketDataIncrementalRefresh	string line = sr.ReadLine();\nQuickFix42.MessageFactory fac = new QuickFix42.MessageFactory();\nQuickFix.MsgType msgType = QuickFix.Message.identifyType(line);\nQuickFix.Message message = fac.create("", msgType.getObject() as string);\nmessage.setString(line, false);	0
30246693	30246228	Ask for credentials in email application	NameSpace.LogOn	0
26732197	26711994	Setting association to foreign key to inherited object using graphdiff and entity framework	public System.Guid? Weather_Id { get; set; }\n\n    [ForeignKey("Weather_Id")]\n    public virtual Weather Weather { get; set; }	0
7997560	7995606	Boxing Occurrence in C#	struct MyValType\n{\n    public override string ToString()\n    {\n        return base.ToString();\n    }\n}	0
9522506	9521916	Wrapping C++ for use in C#	myshape.dimensions.height = 15	0
23048343	23048318	Get a Specific Value from Serialized Data in Javascript	var desc = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(rep_desc)%>;	0
6180194	6180013	LINQ2SQL select rows based on large where	var items = from row in table\n            join intRow in intTable on row.TheIntColumn equals intRow.IntColumn\n            select row;	0
19773090	19772983	WebAPI, post one or collection objects to same action without changing message body	public HttpResponseMessage Post(IEnumerable<MyModel> models)\n{\n    return DoSomething(models);\n}\n\npublic HttpResponseMessage Post(MyModel model)\n{\n    return DoSomething(new List<MyModel> { model });\n}\n\nprivate HttpResponseMessage DoSomething(IEnumerable<MyModel> models)\n{\n    // Do something\n}	0
21304260	21303685	How to build a SQLite Query to handle string containing an apostrophe	var allUsers = await db.QueryAsync<Customer>("Select * From Customer Where CompanyName ='?'", Company);	0
16671079	16670921	c# convert a part of a json string to objects	var list = new JavaScriptSerializer().Deserialize<List<ROOT>>(json);\n\n\npublic class RESULT\n{\n    public List<string> TYPES { get; set; }\n    public List<string> HEADER { get; set; }\n    public List<List<string>> ROWS { get; set; }\n}\n\npublic class ROOT\n{\n    public RESULT RESULT { get; set; }\n}	0
9994015	9993979	Timespan division by a number	TimeSpan X = ...;\n\nvar Result = X.TotalMilliseconds / WhatEverNumber;	0
23388250	23386401	Serialize an object to a string in one line of code for debugging in the watch window	public class MyObject\n    {\n        public long Id { get; set; }\n        public string Name { get; set; }\n\n        public string ToString()\n        {\n            return string.Format("{0} {1}", Id, Name);\n        }\n    }	0
5952749	5952600	How can I temporarily prevent a form from getting focus/activating?	Form.ShowDialog	0
12593648	12593373	How to Extract an Html element from a snipet of Html with HtmlAgilityPack?	HtmlDocument document = new HtmlDocument();            \ndocument.LoadHtml("[your HTML string]");            \nvar node = document.DocumentNode.SelectNodes("//td/text()");\nvar tdNode = node.Where(s => s.InnerText == "TableEle1").Select(s => s);	0
15217439	15207523	Facing issue while trying to Fetch Access Token required for Facebook	public ActionResult GetFriendsDetails()\n{\n    List<User> UserList = new List<Models.User>();\n    var fb = new FacebookClient("MyAppID", "MySecret");\n    //This will give the Access Token\n    dynamic FriendsList = fb.Get("MyAppID/friends");\n    foreach (var item in FriendsList.data)\n    {\n        dynamic CurrentUser = fb.Get(item.id);\n        UserList.Add\n        (\n            new User\n            {\n                id = CurrentUser.id,\n                first_name = CurrentUser.first_name,\n                gender = CurrentUser.gender,\n                last_name = CurrentUser.last_name,\n                name = CurrentUser.name,\n                username = CurrentUser.username\n            }\n        );\n    }\n    return Json\n    (\n        UserList,\n        JsonRequestBehavior.AllowGet\n    );\n}	0
7913674	7639180	How to create a link inside a cell using EPPlus	string FileRootPath = "http://www.google.com";\n_Worksheet.Cells[intCellNumber, 1].Formula = "HYPERLINK(\"" + FileRootPath + "\",\"" + DisplayText + "\")";	0
21901513	21901330	How to use parameters in IN Clause sql informix	IDbCommand cmd = connection.CreateCommand(); //connection has been instantiated\ncmd.CommandTimeout = connection.ConnectionTimeout;\n\nvar query = @"SELECT COUNT(emp_num)\n              FROM tbl1 WHERE year IS NULL AND calc_year = @year AND camp IN ({0})";\n\n\ncmd.Parameters.Add(new SqlParameter("@year", calcYear));\nvar sb = new StringBuilder();\n//ids is a list/array of ids i want in the in clause\nfor (int i = 0; i < ids.Count; i++)\n{\n   sb.AppendFormat("@p{0},", i);\n   cmd.Parameters.Add(new SqlParameter("@p" + i, ids[i]));\n}\nif (sb.Length > 0) { sb.Length -= 1; }\nstring cmdText = string.Format(query, sb.ToString());\n\ncmd.CommandText = cmdText;\n\ncmd.Connection = connection;\nvar reader = cmd.ExecuteReader();	0
7145658	7145647	How do I change the format of a field in an OpenIso8583.Net message	public class Iso8583Extended : Iso8583Rev93\n{\n    private static readonly Template ExtendedTemplate;\n    static Iso8583Extended()\n    {\n        ExtendedTemplate = new Template();\n        ExtendedTemplate[Bit._128_MAC] = FieldDescriptor.AsciiFixed(16, FieldValidators.Hex);\n    }\n\n    public Iso8583Extended():base(ExtendedTemplate)\n    {\n    }\n}	0
8573868	8570125	Get all text from WebBrowser control	webBrowser1.Document.ExecCommand("SelectAll", false, null);\nwebBrowser1.Document.ExecCommand("Copy", false, null);	0
30347044	30346345	zero pading the end of list in multiples of random number in c#	int X=8820;\nfor (int i = 0; i < X - (myList.Count / X); i++)\n    myList.Add(0f);	0
34541186	34541143	Converting a Time String to 24hr Time as Time Only	string[] ar;\nstring s = "7:00 AM - 9:00 AM";\nar = s.Split('-');\nDateTime dateTime = DateTime.Parse(ar[0]);\ndateTime.ToString("HH:mm");	0
2817081	2816779	C# - Grabbing Input > DataSet > XML	public partial class Form1 : Form\n{\n    DataSet ds = new DataSet();\n\n    public Form1()\n    {\n        InitializeComponent();\n\n        ds.Tables.Add("dt");\n        ds.Tables[0].Columns.Add("id");\n        ds.Tables[0].Columns.Add("email");\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        int count = ds.Tables[0].Rows.Count;\n        ds.Tables[0].Rows.Add(count, textBox1.Text);\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        ds.Tables[0].WriteXml("email.xml");\n    }\n}	0
9523768	9523228	Find different word between two strings	string phrase1 = "Nola jumped off the cliff";\nstring phrase2 = "Juri jumped off the coach";\n\n//Split phrases into word arrays\nvar phrase1Words = phrase1.Split(' ');\nvar phrase2Words = phrase2.Split(' ');\n\n//Find the intersection of the two arrays (find the matching words)\nvar wordsInPhrase1and2 = phrase1Words.Intersect(phrase2Words);\n\n//The number of words that differ \nint wordDelta = phrase1Words.Count() - wordsInPhrase1and2.Count();\n\n//Find the differing words\nvar wordsOnlyInPhrase1 = phrase1Words.Except(wordsInPhrase1and2);\nvar wordsOnlyInPhrase2 = phrase2Words.Except(wordsInPhrase1and2);	0
19062921	19061039	WCF Client Catching SoapException from asmx webservice	catch (System.ServiceModel.FaultException FaultEx)\n  {\n   //Gets the Detail Element in the\n   string ErrorMessage;\n   System.ServiceModel.Channels.MessageFault mfault = FaultEx.CreateMessageFault();\n   if (mfault.HasDetail)\n     ErrorMessage = mfault.GetDetail<System.Xml.XmlElement>().InnerText;\n  }	0
4627820	4627114	Making a menu (color palette) from looping through colors	StringBuiler sb = new StringBuiler();\nforeach (Color color in new ColorConverter().GetStandardValues())          \n{             \n  sb.Append(string.format("<div style=\"float:left;width:5px;height:5px;background-color:#{0}\"></div>". color.ColorCode));        \n} \n\nltrlColorPalette.Text = sb.ToString();	0
20647945	20647621	Html Agility Pack Dll	Directory             | Framework\n----------------------+-------------------------------------------\nNet20                 | .NET 2.0\nNet40                 | .NET 4.0\nnet40-client          | .NET 4.0 Client Profile\nNet45                 | .NET 4.5\nsl3-wp                | Silverlight 3\nsl4                   | Silverlight 4\nsl4-windowsphone71    | Silverlight 4 used by Windows Phone 7.1+\nsl5                   | Silverlight 5\nwinrt45               | Windows RT	0
2720498	925509	Border in DrawRectangle	Pen pen = new Pen(Color.Black, 2);\npen.Alignment = PenAlignment.Inset; //<-- this\ng.DrawRectangle(pen, rect);	0
34200081	34185481	Model Binding a checkbox?	if (!string.IsNullOrEmpty(request.Form.Get("isNew")))\n        {\n            vehicle.IsNew = true;\n        }\n        else\n        {\n            vehicle.IsNew = false;\n        }	0
20990914	20990845	How can I show the progress process to client	protected void ASPxButton_cloture_Click(object sender, EventArgs e)\n{\n    Response.Write("procedure 1 begin");\n    Response.Flush();\n    // do procedure 1.....\n    Response.Write("procedure 1 finish");\n    Response.Flush();\n\n    Response.Write("procedure 2 begin");\n    Response.Flush();\n    // do procedure 2.....\n    Response.Write("procedure 2 finish");\n    Response.Flush();\n\n    // ...\n}	0
21523722	21523556	How to compare two pieces of html code and show differences	var p1 ="<h1>Title</h1>";\nvar p2 = "<h2>Title changed</h2>";\n\ndocument.body.innerHTML = diffString(p1, p2);	0
3963879	3963517	Class encapsulation with Repository Pattern	public class Person\n{\n    public string Name { get; protected set; }\n    public int Age { get; protected set; }\n}\n\npublic class PersonRepository\n{\n    public Person Get()\n    {\n        return new PersonBuilder("TestName", 25);\n    }\n\n    private class PersonBuilder : Person\n    {\n        public PersonBuilder(string name, int age)\n        {\n            this.Name = name;\n            this.Age = age;\n        }\n    }\n}	0
542942	542908	Help needed to convert code from C# to Python	foo = Portal("Foo")\n\nbar = Agent("bar")\n\nfoo.Connect("ip", 1234)\n\nfoo.Add(bar)\n\nbar.Ready = bar_Ready\n\ndef bar_Ready(sender, msg):\n\n    print msg.body	0
3105224	3105175	IF/ELSE statements on IFrame Source attribute	string pictarget = (Convert.ToInt32(empID) > 99999) ? \n    "http://website/OrgList:" + 00000 + "/picture" :\n    "http://website/OrgList:" + empID + "/picture";	0
2280223	2280142	Calculate points to create a curve or spline to draw an ellipse	double x = centre.x + radius*Math.cos(2*Math.PI/360 * i);\n  double y = centre.y + radius*Math.sin(2*Math.PI/360 * i);	0
18021892	18020764	NHibernate Select data from table based on non-primary key column	var whateverRecord = session.Query<WhateverType>().Where(x=>x.WhateverColumn == WhateverValue).FirstOrDefault();	0
6927577	6927457	.net DateTime formatting hide time if midnight?	DateTime time = DateTime.Now; \nstring txt = time.ToString(time == time.Date ? "M/dd/yyyy" : "M/dd/yyyy HH:mm:ss");	0
29013217	29012929	Regex not preventing wrong input from being proccessed	(\+1\d{10})|(\d{10})	0
8407506	8407447	DataGridView row loop and cell data access	foreach(DataGridViewRow row in members_dg.rows)\n{\n  // need to get info. This should show u what im looking for. \n  string name = row.Cells[0].Value.ToString();  // first column\n  string price = row.Cells[1].Value.ToString();  // second column\n  //etc\n  Member member = new Member(name, price, ...);\n}	0
5349037	5337683	How to SET extended file properties?	//creates new class of oledocumentproperties\n    var doc = new OleDocumentPropertiesClass();\n\n    //open yout selected file\n    doc.Open(pathToFile, false, dsoFileOpenOptions.dsoOptionDefault);\n\n    //you can set properties with summaryproperties.nameOfProperty = value; for example\n    doc.SummaryProperties.Company = "lol";\n    doc.SummaryProperties.Author = "me";\n\n    //after making changes, you need to use this line to save them\n    doc.Save();	0
27902666	27902611	Pressing delete on a white (blank) line in a List Box in C# Winforms	var selected = listBox.SelectedItem;\nif (!string.IsNullOrWhiteSpace(selected.ToString()))\n{\n    //Remove it\n    listBox.Items.Remove(selected);\n}	0
12044623	11750117	Programming a WPF app with MS Word-like windowing	Window.Show()	0
19393595	19392730	Setting UseMnemonic for ToolstripLabel	public Form1() {\n        InitializeComponent();\n        toolStrip1.Renderer = new MyRenderer();\n    }\n\n    private class MyRenderer : ToolStripProfessionalRenderer {\n        protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {\n            if (e.Item is ToolStripItem) e.Text = e.Text.Replace("&", "&&");\n            base.OnRenderItemText(e);\n        }\n    }	0
15435614	15435565	Looping through a viewmodel and updating a value in my C# MVC app	if (conditionMet == true)\n{\n    foreach(Occ occ in r.Occs)\n    {\n        occ.ratetocharge = occ.ratetocharge - 50;\n    }\n}	0
21523684	21479709	Style inherited control like base control	public class MyComboBox : ComboBox\n{\n    SetResourceReference(Control.StyleProperty, typeof(ComboBox));\n}	0
11596926	11595551	cocoaasynsocket to c sharp server	IPAddress.Any	0
4758877	4758817	Incorrect number of parameters supplied for lambda declaration	var m = Expression.Lambda<Func<Engine, Car>>(Expression.New(ci, engine), engine)	0
23657118	23656707	Is there a way to assign values to a combobox without using a datasource?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        var cbi1 = new ComboBoxItem("Item 1") { Id = 1 };\n        var cbi2 = new ComboBoxItem("Item 2") { Id = 2 };\n        var cbi3 = new ComboBoxItem("Item 3") { Id = 3 };\n        comboBox1.Items.Add(cbi1);\n        comboBox1.Items.Add(cbi2);\n        comboBox1.Items.Add(cbi3);\n    }\n\n    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        var id = ((ComboBoxItem)comboBox1.SelectedItem).Id;\n\n        MessageBox.Show(id.ToString());\n\n    }\n}\n\npublic class ComboBoxItem\n{\n    private readonly string text;\n\n    public int Id { get; set; }\n\n    public ComboBoxItem(string text)\n    {\n        this.text = text;\n    }\n\n    public override string ToString()\n    {\n        return text;\n    }\n}	0
10481062	10479914	DateTime filtering doesn't work	"..spRis_GetListaDocs @DateFilter = '" + Convert.ToDateTime(txtDate.Text).ToString("yyyy-MM-dd") + "'"	0
10658210	10645559	remove illegal 0x1f charector from xml	string s = File.ReadAllText(filepath);\ns = Regex.Replace(s, @"[\u0000-\u001F]", string.Empty);\nFile.WriteAllText(newFilepath, s);	0
27514298	27514088	Aggregate, sum and product of tuples in List	List<Tuple<string, int>> list = new List<Tuple<string, int>>();\n    list.Add(Tuple.Create<string, int>("dog", 25));\n    list.Add(Tuple.Create<string, int>("dog", 10));\n    list.Add(Tuple.Create<string, int>("cat", 5));\n    list.Add(Tuple.Create<string, int>("cat", 7));\n    list.Add(Tuple.Create<string, int>("other", 4));\n\n    Dictionary<string, int> dic = list.\n     GroupBy(t => t.Item1).\n     Where(grp => grp.Count() > 1).\n     ToDictionary(grp => grp.Key,\n                  grp => grp.Select(tuple => tuple.Item2).Aggregate((a, b) => a * b));	0
19374075	19373473	Xml Deserialize returms null values but xml has values	[XmlElement("arp")]\npublic int arp { get; set; }\n\n[XmlElement("nsu")]\npublic int nsu { get; set; }	0
21742681	21741488	How can I read an HTML file a Paragraph at a time?	//don't forgot to add the reference\nusing HtmlAgilityPack;\n\n//Function that takes the html as a string in parameter and return a list\n//of strings with the paragraphs content.\npublic List<string> GetParagraphsListFromHtml(string sourceHtml)\n{\n\n   var pars = new List<string>();\n\n   //first create an HtmlDocument\n   HtmlDocument doc = new HtmlDocument();\n\n   //load the html (from a string)\n   doc.LoadHtml(sourceHtml);\n\n   //Select all the <p> nodes in a HtmlNodeCollection\n   HtmlNodeCollection paragraphs = doc.DocumentNode.SelectNodes(".//p");\n\n   //Iterates on every Node in the collection\n   foreach (HtmlNode paragraph in paragraphs)\n   {\n      //Add the InnerText to the list\n      pars.Add(paragraph.InnerText); \n      //Or paragraph.InnerHtml depends what you want\n   }\n\n   return pars;\n}	0
33467066	33466570	Database queries in Enitity Framework model - variable equals zero	public float Efficiency\n{\n   get\n   {\n       using(var db = new ScoresContext())\n       {\n           var allGoalsInSeason = db.Goals.Count();\n           return (float)HisGoals.Count / allGoalsInSeason;\n        }\n    }\n}	0
855254	855047	Convert a System.Windows.Input.KeyEventArgs key to a char	KeyInterop.VirtualKeyFromKey	0
10328285	10328103	C# WinForms how to stop Ding sound in TreeView	private void treeView1_KeyDown(object sender, KeyEventArgs e) {\n        e.Handled = e.SuppressKeyPress = true;\n        this.BeginInvoke(new Action(() => \n            (new Form1()).ShowDialog()\n        ));\n    }	0
17885014	17883682	Extract node value from xml resembling string C#	string value = @"<ad nameId=""\862093\""></ad>,<ad nameId=""\862094\""></ad>,<ad nameId=""\865599\""></ad>";\n   var matches = Regex.Matches(value, @"(\\\d*\\)", RegexOptions.RightToLeft);\n   foreach (Group item in matches)\n   {\n     string yourMatchNumber = item.Value;\n   }	0
21369301	21369141	use a variable value in an expression?	var resourceManager = new ResourceManager("YourNamespace." + MyGlobalVariables.ResourceName, Type.GetType("YourNamespace." + MyGlobalVariables.ResourceName).Assembly);\nvar login_caption = resourceManager.GetString("login_caption", CultureInfo.CurrentCulture);	0
14790002	14789984	In C#, how to check if a property of an object in a List<> contains a string?	if (myList.Any(t => t.Message == "hello"))	0
3787781	3787765	Type conversion with Generic List and Interfaces in C# - Looking for an elegant solution	IList<IName> restricted = people.Cast<IName>().ToList();	0
23742868	23740558	How can I inject inline styling into a Document being loaded in my WPF WebBrowser?	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        wb.LoadCompleted += wb_LoadCompleted;\n        wb.Source = new Uri("http://www.google.com");          \n    }\n\n    void wb_LoadCompleted(object sender, NavigationEventArgs e)\n    {\n        var doc = wb.Document as HTMLDocument;\n        var collection = doc.getElementsByTagName("input");\n\n        foreach (IHTMLElement input in collection)\n        {\n            dynamic currentStyle = (input as IHTMLElement2).currentStyle.getAttribute("backgroundColor");\n\n            input.style.setAttribute("backgroundColor", "red");                \n        }\n\n\n\n    }\n}	0
32888902	32888197	C# - Straight-up answer for using Regex to compare strings?	string myString = "$randomText$";\nvar match = Regex.Match(myString , @"\$.+\$");	0
3390438	3390290	Build checksum of array of long values	unchecked\n {\n      long checksum = 0;\n      for( int i = 0; i < values.Length; i++)\n          checksum = checksum ^ values[i];\n      return checksum;\n }	0
18813118	18813040	DataContract for serializing interface subclasses	[KnownType(typeof(Subclass1))]\n[KnownType(typeof(Subclass2))]\n[DataContract]\npublic class BaseClass : ISomeInterface\n{\n\n}	0
2661357	2661351	How to spawn thread in C#	ThreadStart work = NameOfMethodToCall;\nThread thread = new Thread(work);\nthread.Start();\n...\n\nprivate void NameOfMethodToCall()\n{\n    // This will be executed on another thread\n}	0
8401655	8384663	How do I register my component (with constructor parameters) so an exception isn't thrown when I try to resolve it?	int i = 0;\nforeach (Type type in this.GetType().Assembly.GetTypes())\n{\n        if (formaterInterface.IsAssignableFrom(type) && !type.Equals(formaterInterface))\n        {\n                container.Register(Component.For<IFormater().ImplementedBy(type).Named(i.ToString()));\n                formatters.Add(container.Resolve<IFormater>(i.ToString()));\n                i++;\n        }\n}	0
3203883	3203832	Convert xml string to XML document in Internet Explorer - C#, ASP.NET	doc.LoadXml(xmlDS);\n        doc.Save(Response.OutputStream);	0
30882999	30882944	Changing current date time format	this.VoucherDate = DateTime.Now.ToString("MM/dd/yyyy HH:mm");	0
12541260	12541229	single byte array to 2d byte array in C#?	byte[] d = new byte[64];\nbyte[,] data = new byte[8,8];\n\nint row = 0;\nint column = 0;\n\nfor(i=0; i < d.Length; i++)\n{\n   row = i%8;\n   column = i/8;\n   data [row, column] = d[i];    \n}	0
13012732	13010657	How do i loop thourgh XPathNodeIterator and randomize its children?	XPathNavigator[] positions = new XPathNavigator[iterator.Count];\n    int i = 0;\n\n    while (iterator.MoveNext())\n    {\n        XPathNavigator n = iterator.Current;\n        positions[i] = n;\n\n        i++;\n    }	0
10255605	10255591	Reading an app setting value from the config file	app.config	0
29384101	29384015	How to run a program in the same folder?	String pwd = GetCurrentDirectory(); //Contains something like C:\Users\Daedric\TestApp\\nString finalString = Path.Combine(pwd, "test.txt"); //As per Corak	0
8360414	8349832	Left join with OrderBy in LINQ	myTasks = (from m in myTasksFiltered\n           join d in APITasks on m.TaskIssueId equals d.TaskIssueId\n               into joinedData\n           from d in joinedData.DefaultIfEmpty()\n           let index = d == null ? 0 : d.AnotherInternalId\n           orderby index\n           select m).ToList();	0
23814026	23810777	Query to find if a folder exists	string query = @"<View Scope='RecursiveAll'><Query><Where>\n                                                <And>\n                                                        <Eq>\n                                                            <FieldRef Name='FSObjType' />\n                                                            <Value Type='Text'>1</Value>\n                                                        </Eq>\n                                                        <Eq>\n                                                            <FieldRef Name='FileRef' />\n                                                            <Value Type='Text'>{0}</Value>\n                                                        </Eq>\n                                                </And>\n                                            </Where></Query></View>";	0
20550990	20550210	Looping through multiple SQL insert statements using C#	//open the text file for reading\n        using (TextReader tr = new StreamReader("Filepath"))\n        {\n            try\n            {\n                // read line from text file\n                string query = tr.ReadLine();\n                // split the string on the commas to make it easier to find the key value\n                string[] queryArray = query.Split(',');\n                int beginingOfKeyIndex = queryArray[8].IndexOf('\'') + 1; // add one because we don't want the '\n                // get the key value from the correct array element\n                string keyValue = queryArray[8].Substring(beginingOfKeyIndex, queryArray.Length - beginingOfKeyIndex);\n            }\n            catch (IOException)\n            {\n                // we get here when it tries to read beyond end of file or there is some other issue.\n                throw;\n            }\n        }	0
16972891	16972813	How do I run unit tests in VS based on different values of a static variable?	private static Object LockObject = new object();\n\n    public void TestMethod1()\n    {\n        lock(LockObject)\n        {\n            Object1.StaticMember = 1;\n            Object2 test = new Object2();\n            Assert.AreEqual("1", test.getStaticVal());\n        }\n    }\n\n    public void TestMethod2()\n    {\n        lock (LockObject)\n        {\n            Object1.StaticMember = 2;\n            Object2 test = new Object2();\n            Assert.AreEqual("2", test.getStaticVal());\n        }\n    }	0
5965375	5965342	How can I compare two unordered sequences (list and array) for equality?	var first = str.GroupBy(s => s)\n               .ToDictionary(g => g.Key, g => g.Count());\n\nvar second = lst.GroupBy(s => s)\n                .ToDictionary(g => g.Key, g => g.Count());\n\nbool equals = first.OrderBy(kvp => kvp.Key)\n                   .SequenceEquals(second.OrderBy(kvp => kvp.Key));	0
30200580	30200294	StreamReader row and line delimiters	string readContents;\nusing (StreamReader streamReader = new StreamReader(@"File.txt"))\n{\n    readContents = streamReader.ReadToEnd();\n    string[] lines = readContents.Split('\r');\n    foreach (string s in lines)\n    {\n         string[] lines2 = s.Split('\t');\n         foreach (string s2 in lines2)\n         {\n             Console.WriteLine(s2);\n         }\n    }\n}\nConsole.ReadLine();	0
6806960	6806906	Trying to import a library (DLLImport) getting a System.DLLNotFoundException	[DllImport ("__Internal")]\nextern static void YourLinkedNativeCode ();	0
6885880	6885711	WPF c#, bind datagrid column with code behind	var col = new DataGridTextColumn();\n            col.Header = "d";\n            col.Binding = new Binding("RoomNumber");\n            dataGrid1.Columns.Add(col);	0
9202975	9193068	How to set up an application to use DataContracts?	[DataContract]	0
28848788	28848627	Correct way for get fractional part double like int	public static int GetFrac2Digits(this double d)\n{\n    var str = d.ToString("0.00", CultureInfo.InvariantCulture);\n    return int.Parse(str.Substring(str.IndexOf('.') + 1));\n}	0
9469292	9469224	C#, abstract superclass implementing a concrete variable defined by the subclass?	public abstract class ThingManager<T> where T : ThingTask	0
7230564	7230494	trying to use single condition in sorting datagrid view column	var products = dbcontext.products\n                        .GroupBy(x => x.product_Id)\n                        .Select(a => new\n                        {\n                            productid = a.Key,\n                            prouctnam = a.FirstOrDefault().product_Name,\n                            productimage = a.FirstOrDefault().product_Image,\n                            productdescr = a.FirstOrDefault().product_Description,\n                            stockavailable = a.LongCount(),\n                            productprice = a.FirstOrDefault().product_Price\n                        });\n\nif (order == "d")\n{\n    order = "a";\n    dgvproducts.DataSource = products.OrderBy(a=>a.prouctnam).ToList();\n}\nelse\n{\n    order = "d";\n    dgvproducts.DataSource = products.OrderByDescending(a=>a.prouctnam).ToList();\n}	0
3747189	3747124	How can my application register itself as a browser in Windows 7?	...OpenSubKey(@"Software\Clients\StartMenuInternet",true)...	0
30478765	30470656	Unity - How to get data from a js script to a csharp script?	scoreData ["score"] = gamemaster.currentScore;	0
9152487	8978820	how to deselect a row in RadGrid for windows forms?	radGridView1.CurrentRow = null;\nradGridView1.GridElement.Update(Telerik.WinControls.UI.GridUINotifyAction.StateChanged);	0
13860157	13860104	Use the same object in a for loop - C#	private static List<string> _ListToWatch;\npublic static List<string> ListToWatch\n{\n    get\n        {\n         if(_ListToWatch == null) \n              _ListToWatch = new List();\n          return _ListToWatch;\n         }\n    set \n     {\n      _ListToWatch = value;\n     }\n\n}	0
4440676	4440624	Why there are the same variables of mine with a ':' in Visual Studio auto complete list?	public void Foo(int bar, string quux)\n{\n}\n\n// Before C# 4.0:\nFoo(42, "text");\n\n// After C# 4.0:\nFoo(bar: 42, quux: "text");\n\n// Or, equivalently:\nFoo(quux: "text", bar: 42);	0
21704650	21704437	Running a method in the background	private void worker_DoWork(object sender, DoWorkEventArgs e)\n    {\n      Dispatcher.BeginInvoke(() =>\n      {   \n        checkUserStats();\n      });\n    }	0
11776058	11776006	windows phone more than one navigation keys	/ImagePage.xaml?tag={0}&tag2={1}"	0
12344197	12338054	ANTLR rule to skip method body	rule1 : '(' \n  (\n    nestedParan\n  | (~')')*\n  )\n  ')';\n\nnestedParan : '('\n  (\n    nestedParan\n  | (~')')*\n  )\n  ')';	0
22880967	22875973	Take() Throws Not Implemented Exception Entity Framework 6 with MySQL	entities.MemberSite.\n    Where(s => s.SiteID == siteID).Select(s => s.Member).\n    OrderBy(m => m.DateCreated).Take(50).ToList();	0
10941412	10941306	regular expression to extract part of this HTML file	Match match = \n    Regex.Match(\n        ConnectionAPI.responseFromServer, \n        "\"\\**?ouser\\**?":\\s*\"([^\"]*)\",",\n        RegexOptions.IgnoreCase);\nString output = String.Empty;\n// Here we check the Match instance.\nif (match.Success)\n{\n    // Finally, we get the Group value and display it.\n    output = match.Groups[1].Value;\n    Console.WriteLine(output);\n}	0
5936890	5935411	How to control stereo-frames separately with C#? (NVIDIA 3D shutter glasses)	byte[] data = new byte[] {0x4e, 0x56, 0x33, 0x44,   //NVSTEREO_IMAGE_SIGNATURE         = 0x4433564e;\n0x00, 0x0F, 0x00, 0x00,   //Screen width * 2 = 1920*2 = 3840 = 0x00000F00;\n0x38, 0x04, 0x00, 0x00,   //Screen height = 1080             = 0x00000438;\n0x20, 0x00, 0x00, 0x00,   //dwBPP = 32                       = 0x00000020;\n0x02, 0x00, 0x00, 0x00};  //dwFlags = SIH_SCALE_TO_FIT       = 0x00000002;	0
6174750	6174577	Cannot pass guid as uniqueidentifier to storedprocedure	return (bool)command.ExecuteScalar();	0
28659831	28659789	How to parse this decenturl code?	using System;\nusing Newtonsoft.Json.Linq;\n\nclass Test\n{\n    static void Main()\n    {\n        string json = "[\"ok\", \"Google\", \"google\"]";\n        var array = JArray.Parse(json);\n        Console.WriteLine(array[0]); // For example\n    }\n}	0
26456747	26436272	Reactive UI 6: How can I achieve same functionality of version 4 in version 6	StartAsyncCommand = ReactiveCommand.CreateAsyncObservable(_ => \n    Observable.Timer(DateTimeOffset.Zero, TimeSpan.FromSeconds(1))\n        .Take(10)\n        .Scan(0, (acc,x) => acc + 10));\n\nStartAsyncCommand.ToProperty(this, x => x.Progress, out progress);	0
11504004	11503887	Dictionary with delegate as value	new Dictionary<Type, Func<object, int>>();\n\nvar cVisitor = new CVisitor();\n_messageMapper.Add(typeof(Heartbeat), \n   new Func<object, int>(heartbeat => cVisitor.Visit((Heartbeat)heartbeat)) \n);	0
10370304	10370293	How can I check if an int is a legit HttpStatusCode in .NET?	Enum.IsDefined(typeof(HttpStatusCode),value)	0
11504876	11504821	How To Scan All File in Folder and Subfolder?	Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*",SearchOption.AllDirectories).ToList();	0
16153904	16153721	algorithm to get first, second, third neighbors from a coordinate	Dictionary<Color, List<Point>>	0
27345927	27345854	C# read only first line from a text file	String[] languages = new String[] { "english", "french", "german"};\n\nstring line1 = File.ReadLines("MyFile.txt").First(); // gets the first line from file.\nif(languages.Contains(line1)) // check if first line matches specified languages\n{\n    // success\n    Console.WriteLine("Language is {0}", line1);\n}\nelse\n{\n    // fail\n    Console.WriteLine("Language not found: {0}", line1);    \n}	0
9852432	9852416	How can I get a screen resolution of Device (Windows Phone)	public void GetScreenResolution()  \n{  \n     string ScreenWidth = Application.Current.Host.Content.ActualWidth.ToString();  \n     string ScreenHeight = Application.Current.Host.Content.ActualHeight.ToString();  \n     MessageBox.Show(ScreenWidth + "*" + ScreenHeight);  \n}	0
3713268	3662777	Default access rights of files and directories	bool modified;\nDirectoryInfo directoryInfo = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyFolder");\nDirectorySecurity directorySecurity = directoryInfo.GetAccessControl();\nFileSystemAccessRule rule = new FileSystemAccessRule(\n    securityIdentifier,\n    FileSystemRights.Write |\n    FileSystemRights.ReadAndExecute |\n    FileSystemRights.Modify,\n    InheritanceFlags.ContainerInherit |\n    InheritanceFlags.ObjectInherit,\n    PropagationFlags.InheritOnly,\n    AccessControlType.Allow);\ndirectorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);\ndirectoryInfo.SetAccessControl(directorySecurity);	0
13631018	13630981	How can i change the int array to string	TextBox.Text = string.Format("({0})", string.Join(" ", arr));	0
6393540	6371521	How to create excel-like insertion behavior in Winforms?	var clipData = Clipboard.GetData(DataFormats.Text).ToString();\nif (string.IsNullOrEmpty(clipData))\n    return;\n\nvar dataSource = new DataTable("data");\ndataSource.Columns.Add("lines"); \n\nforeach(var line in clipData.Split('\n'))\n    dataSource.Rows.Add(line);\n\ndatagrid.DataSource = dataSource;	0
858375	858341	Get IP address in a console application	using System;\nusing System.Net;\n\n\nnamespace ConsoleTest\n{\n    class Program\n    {\n        static void Main()\n        {\n            String strHostName = string.Empty;\n            // Getting Ip address of local machine...\n            // First get the host name of local machine.\n            strHostName = Dns.GetHostName();\n            Console.WriteLine("Local Machine's Host Name: " + strHostName);\n            // Then using host name, get the IP address list..\n            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);\n            IPAddress[] addr = ipEntry.AddressList;\n\n            for (int i = 0; i < addr.Length; i++)\n            {\n                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
23973692	23973586	C# class code with data from multiple tables	foreach(User_Survey_Relation relatSingle in relation){\n    lstItem.addRange(db.Survey.Where(x => x.ID == relatSingle.SurveyID).ToList());\n}\n}	0
10588880	10588825	writing elements to an XML file in C#	for (int i = 0; i < 100000000; i++)\n {\n    textWriter.WriteStartElement("book"); \n    writer.WriteAttributeString("id", i.ToString());                \n    textWriter.WriteString(i.ToString());\n    textWriter.WriteEndElement(); \n }	0
30176770	30134279	How to open a DXF referenced file with SharpMap?	DxfFile dxf;\nusing (var stream = new FileStream(@"path\to\file.dxf", FileMode.Open))\n{\n    dxf = DxfFile.Load(stream);\n}\n\nforeach (var entity in dxf.Entities)\n{\n    switch (entity.EntityType)\n    {\n        case DxfEntityType.Line:\n            var line = (DxfLine)entity;\n            // insert code here to add the line to SharpMap using\n            // line.P1 and line.P2 as end points\n            break;\n    }\n}	0
4434055	4433936	VS2005 Debugger: Adding a watch on specific fields within all objects of a list?	for (int i = 0; i < foos.Count(); i++)\n {\n    Debug.Print("foos[{0}].x={1}",i,foos[i].x);\n }	0
4278615	4275581	c# How To test Inheritance of an Abstract class with protected methods with xunit	public class ClassB {\n    protected MethodB() {\n    }\n}\n\npublic class ClassA : ClassB {\n}\n\n\n[TestFixture()]\npublic class TestA {\n    [Test()]\n    public void IsInstanceOfB() {\n        ClassA a = new ClassA();\n        Assert.IsInstanceOf(typeof(ClassB), a);\n    }\n}	0
7022529	7022512	How to pass a IList<T> argument in a function	public class SomeObject\n    { }\n\n    public static List<T> MyFunction<T>(List<T> listaCompleta, int numeroPacchetti)\n    {\n        return listaCompleta;\n    }\n    static void Main(string[] args)\n    {\n        var someObjects = new List<SomeObject>();\n\n        var listPacchetti = (from SomeObject myso in someObjects\n                                           select myso).ToList();\n\n        listPacchetti =  MyFunction<SomeObject>(listPacchetti, 1);\n    }	0
22297539	22297106	reading a binary unknown size file in c#	string fileName = ...\nusing (var fp = System.IO.File.OpenRead(fileName)) // using provides exception-safe closing\n{\n    int b; // note: not a byte\n\n    while ((b = fp.ReadByte()) >= 0)\n    {\n        byte ch = (byte) b;\n        // now use the byte in 'ch'\n        create_frequency(ch);\n    }\n}	0
16237668	16237610	How to access the embedded xml in App_Data folder in C# project?	Server.MapPath("~/App_Data/yourxmlfile.xml")	0
24761403	24761366	Specifying named parameter	int messageType	0
21376856	21376552	Close Window after open another window?	Window2 _window2 = new Window2();\n_window2.Show();\nthis.Close();	0
12427929	12427864	Get the datepicker looks like the ones provided in Windows Task Scheduler	DateTime dt = DateTime.MinValue;\n try\n {\n    dt = dateTimePicker1.Value.Date.Add(dateTimePicker2.Value.TimeOfDay);\n\n }	0
1147162	1147149	how to make a Windows Form always display on the top?	form2.ShowDialog()	0
7845276	7845259	separate text and store in a list to bind in repeater in asp.net	List<string> list = yourString.Split('/').ToList();	0
10203831	10203410	Renaming a Telerik reporting legend item	labelItem1.TextBlock.Text = procChart.Report.Parameters["Due Beyond"].Value.ToString();//here\nlabelItem2.TextBlock.Text = procChart.Report.Parameters["DueMonday"].Value.ToString();//here	0
3251624	3251608	Implementing C# EventHandlers in F#	let invalidated = new DelegateEvent<System.EventHandler>()\n\n[<CLIEvent>]\nmember this.Invalidated = invalidated.Publish	0
6434545	6434529	Converting into Lambda Expression	double abc = y.Select(x => new Employee(x).Name)\n              .SomeMethod();	0
760533	760503	How to pass a method name in order to instantiate a delegate?	using System;\nusing System.Collections.Generic;\n\nnamespace TestDelegate\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            List<string> words = new List<string>() { "one", "two", "three", "four", "five" };\n            Action<string> theFunction = WriteBasic;\n\n            foreach (string word in words)\n            {\n                theFunction(word);\n            }\n            Console.ReadLine();\n        }\n\n        public static void WriteBasic(string message)\n        {\n            Console.WriteLine(message);\n        }\n\n        public static void WriteAdvanced(string message)\n        {\n            Console.WriteLine("*** {0} ***", message);\n        }\n\n    }\n}	0
8052819	8052753	How to parse Nullable<DateTime> from a SqlDataReader	int x = reader.GetOrdinal("Placed");\n\nif(!reader.IsDBNull(x))\n    _placed = reader.GetDateTime(x);	0
10355087	10354978	Remove objects from IEnumerable	Distinct()	0
1319202	1319191	How to convert double to string without the power to 10 representation (E-05)	string formatted = String.Format("{0:F20}", value);	0
31297529	31297358	Best way to get csv data from sting in C# to records in SQL Server?	create procedure myproc\n         @myvalue varchar(max),\n         @positionid int,\n         @isrequired int\n    as\n\n    INSERT INTO Skills (PositionId,Name,ListOrder,Score,ScoreNotes,isrequired)        \n           (select @PositionId,positionVal, skill, null, null, @isrequired \n     from dbo.fn_split (@myvalue, ',') )\n\n    GO	0
23628484	23628343	Set Class Using Eval in Item Data Bound	class="<%# Container.ItemIndex % 2 == 0 ? "bgWhite" : "bgBlack" %>"	0
7805291	7805251	how to make use of code reuse in c#?	using p2p;	0
2356931	2356898	Is there any way for a static method to access all of the non-static instances of a class?	public class Thing\n{\n   public static List<Thing> _things = new List<Thing>();\n\n   public Thing()\n   {\n       _things.Add(this);\n   }\n\n   public static void SomeEventHandler(object value, EventHandler e)\n   {\n      foreach (Thing thing in _things)\n      {\n           // do something.\n      }\n   }\n}	0
20718046	20717982	Want a button to disable for 30 second after click and enable it automatically	System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();\nprivate void button1_Click(object sender, EventArgs e)  // event handler of your button\n{                \n    timer.Interval = 30000; // here time in milliseconds\n    timer.Tick += timer_Tick;\n    timer.Start();\n    button1.Enabled = false;\n\n    // place get random code here\n}\n\nvoid timer_Tick(object sender, System.EventArgs e)\n{\n    button1.Enabled = true;\n    timer.Stop();\n}	0
28581272	28580609	How to save the SQL Server table xml column data in physical path as .xml format?	static void Main(string[] args)\n    {\n        // get connection string from app./web.config\n        string connectionString = "server=.;database=yourDB;Integrated Security=SSPI;";\n\n        // define query\n        string query = "SELECT MESSAGE FROM dbo.SamTest WHERE ID = 1;";\n\n        // set up connection and command\n        using (SqlConnection conn = new SqlConnection(connectionString))\n        using (SqlCommand selectCmd = new SqlCommand(query, conn))\n        {\n            // open connection, execute query to get XML, close connection\n            conn.Open();\n            string xmlContents = selectCmd.ExecuteScalar().ToString();\n            conn.Close();\n\n            // define target file name\n            string targetFileName = @"C:\tmp\test.xml";\n\n            // write XML out to file\n            File.WriteAllText(targetFileName, xmlContents);\n        }\n    }	0
778272	778252	How to get the current directory on a class library?	string assemblyFile = (\n    new System.Uri(Assembly.GetExecutingAssembly().CodeBase)\n).AbsolutePath;	0
33440275	33439604	How do I represent a graph given as an adjacency list in C#?	using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        Dictionary<int, List<int>> graph = new Dictionary <int, List<int>>();\n        graph[1] = new List<int> {2, 3, 4};\n        graph[2] = new List<int> {1, 3, 4};\n        graph[3] = new List<int> {1, 2, 4};\n        graph[4] = new List<int> {1, 2, 3, 5};\n        graph[5] = new List<int> {4, 6};\n        graph[6] = new List<int> {5};\n    }\n}	0
10506937	10506532	How to handle custom token across pages	//c#\n\n        HttpCookie cookie = new HttpCookie("myTokenCookie");\n        cookie.Value = tokenString;\n        Response.SetCookie(cookie);\n\n        // then get it back later\n        s = Request.Cookies["myTokenCookie"].Value;\n\n        // then you could write it into a hidden input for retrieval in JS	0
25122611	24917307	slow picture taking and processing on windows store app	StorageFolder temp = ApplicationData.Current.TemporaryFolder;\nIReadOnlyList<StorageFile> fileList = await temp.GetFilesAsync();	0
9661654	9661573	How to enable Selection for a GridView that assigns the DataSource in the code behind class?	GridView1.AutoGenerateColumns = true;\n GridView1.AutoGenerateSelectButton = true;	0
22861146	22860939	get page datacontext from listitemtemplate	{Binding ElementName=YourList, path=DataContext.YourCommand}	0
2035527	2035440	F# Riddle: how to call an overload of a method?	MyClass.Overload1(1,2)\nMyClass.Overload1<_,_>(unbox (box (1,2)) : System.Tuple<int,int>)\nMyClass.Overload1 1	0
4157262	4157191	How do I get members of a dynamically typed array in C#?	var list = result as IEnumerable;\nif(list != null) \n{\n   foreach (var i in list)\n   {\n       // Do stuff\n   }\n}	0
28952563	28952489	Place if statement inside a where clause in Linq for Entity framework	var query = context.Fields\n        .Where( \n            x => x.DeletedAt == null \n        );\n\n    // Apply search\n    if( searchCriteria != null )\n    {\n        if( searchCriteria.SearchTerm != "" )\n        {\n            query = query.Where(\n                x => x.Location.Contains( searchCriteria.SearchTerm )\n            );\n        }\n    }\n    return query;	0
4396656	4392022	I need a fast runtime expression parser	Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");\n\n  e.Parameters["Pi2"] = new Expression("Pi * Pi");\n  e.Parameters["X"] = 10;\n\n  e.EvaluateParameter += delegate(string name, ParameterArgs args)\n    {\n      if (name == "Pi")\n      args.Result = 3.14;\n    };\n\n  Debug.Assert(117.07 == e.Evaluate());	0
20066251	20056688	Creating a Custom DockPanel Template in designer	Project->Add UserControl...	0
1779963	1779705	Convert Plain Text Links to HTML links with regular expressions	\b(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]	0
3746545	3746530	Auto encoding detect in C#	public class Program\n{\n    static void Main(string[] args)\n    {\n        using (var reader = new StreamReader("foo.txt"))\n        {\n            // Make sure you read from the file or it won't be able\n            // to guess the encoding\n            var file = reader.ReadToEnd();\n            Console.WriteLine(reader.CurrentEncoding);\n        }\n    }\n}	0
30980976	30977809	Saving login Cookie and use it for other request	public YourClass\n{\n    private CookieContainer Cookies;\n\n    public YourClass()\n    {\n        this.Cookies= new CookieContainer(); \n    }\n\n    public void SendAndReceive()\n    {\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(...);\n        ....\n        request.UserAgent = agent;\n        request.Method = "GET";\n        request.ContentType = "text/html";\n        request.CookieContainer = this.Cookies;\n        ....\n\n        this.Cookies = (HttpWebResponse)request.GetResponse().Cookies;\n    }\n}	0
7187751	7187738	Filling a combobox with years	for (int i = 1950; i <= currentYear; i++) {\n   ComboBoxItem item = new ComboBoxItem();\n   item.Content = i;\n   myCombobox.Items.Add(item);\n}	0
15374076	15372132	WinRT c# load a sqlite database from folder asset	StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/db_in_assets.txt"));\n\nawait file.CopyAsync(ApplicationData.Current.LocalFolder, "db_in_local.db");	0
1409094	1406050	Hosting Multiple hosts under IIS for WCF	protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)\n{\n    if (HttpContext.Current != null)\n    {\n        string baseAddress = string.Format("http://{0}{1}{2}", HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port == 80 ? "" : ":" + HttpContext.Current.Request.Url.Port, HttpContext.Current.Request.CurrentExecutionFilePath);\n        Uri baseURI = new Uri(baseAddress);\n        return base.CreateServiceHost(serviceType, new Uri[] { baseURI });\n    }\n\n    //We did the best we could, but there is no current HTTP request.\n    //Just fall back to the base service host factory\n    return base.CreateServiceHost(serviceType, baseAddresses);\n}	0
17075956	17075922	Overlapping Regex Replace	string strRegex = @"(?<=\d)\s+(?=\d)";\n...\nstring strReplace = @",";	0
28098154	28091217	Updating bitmapSource - copying one to another	Jetmap.Freeze();	0
6393571	6393399	Save XElement to ZipFile via Stream	ms.Seek(0, SeekOrigin.Begin);	0
22070591	22067589	How to iterate through every mail item in every folder, Outlook Add-in 2010	private void ScanAllMailItems()\n    {\n        var theRootFolder = (Outlook.Folder)_outlookNameSpace.DefaultStore.GetRootFolder();\n        RecurseThroughFolders(theRootFolder, 0);\n    }\n\n    private void RecurseThroughFolders(Outlook.Folder theRootFolder, int depth)\n    {\n        if (theRootFolder.DefaultItemType != Outlook.OlItemType.olMailItem)\n            return;\n\n        foreach (object item in theRootFolder.Items)\n        {\n            var mailItem = item as Outlook.MailItem;\n            if (mailItem != null)\n            {\n                var mi = mailItem;\n                ScanMailBody(mi);\n            }\n        }\n\n        foreach (Outlook.Folder folder in theRootFolder.Folders)\n        {\n            RecurseThroughFolders(folder, depth + 1);\n        }\n    }	0
14116366	14116172	Equaling certain text parts of two diferent text files and making changes	List<string[]> stock = new List<string[]>(File.ReadAllLines("G:\\Stock.txt").Select(line => line.Split('|')));\nList<string[]> products = new List<string[]>(File.ReadAllLines("G:\\Products.txt").Select(line => line.Split(',')));\n\nproducts.ForEach(p =>\n{\n    // since not all arrays in this case are the same lenght, we will go backwards from the end\n    int productStockIndex = Array.IndexOf(p, p.Last());\n\n    // product name is before the stock count\n    int productNameIndex = productStockIndex - 1;\n\n    // get product name to find in Stock.txt and remove extra quotes from product name\n    string productName = p[productNameIndex].Replace("\"", "");\n\n    // check if Stock.txt contains the product\n    if (stock.Any(s => s[0] == productName))\n    {\n        // Update the stock count\n        p[productStockIndex] = stock.First(stk => stk[0] == productName)[1];\n    }       \n});	0
3341767	3341697	How do I automatically set assembly version during nightly build?	[assembly: AssemblyVersion("1.0.9.10")]	0
1698746	1694451	Cannot use pinvoke to send WM_CLOSE to a Windows Explorer window	[DllImport("user32.dll", SetLastError = true)]\nstatic extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n[DllImport("user32.Dll")]\npublic static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam);\n\nprivate const UInt32 WM_CLOSE          = 0x0010;\n\n...\n\n    IntPtr hWnd = FindWindow("ExploreWClass", null);\n    if (hWnd.ToInt32()!=0) PostMessage(hWnd, WM_CLOSE, 0, 0);	0
32660806	32658223	C# - creating groups of points	public IEnumerable<Point> GetPoints(Point origin, IEnumerable<Point> points, int distance)\n{\n    var result = new HashSet<Point>();\n    var found = new Queue<Point>();\n    found.Enqueue(origin)\n\n    while(found.Count > 0)\n    {\n        var current = found.Dequeue();\n        var candidates = points\n            .Where(p => !result.Contains(p) &&\n                   p.Distance(current) <= distance);\n\n        foreach(var p in candidates)\n        {\n            result.Add(p);\n            found.Enqueue(p)\n        }\n    }\n\n    return result;\n}	0
18096910	18093135	How to query from table's view in .Net C#?	string strquery = "select * from View_App_Academic where recruitment_id=@recruitment_id and ref_no=@ref_no";\n\nSqlCommand objCMD = new SqlCommand(strquery, conn);\nobjCMD.Parameters.AddWithValue("@recruitment_id", RecruitDropDownList.Text);\nobjCMD.Parameters.AddWithValue("@ref_no",RefDropDownList.Text);\nSqlDataAdapter myAdapter = new SqlDataAdapter();\nmyAdapter.SelectCommand = objCMD;\n\nDataSet myDataSet = new DataSet();\nmyAdapter.Fill(myDataSet);	0
16326034	15548044	Updating label with Timer	Label1.Invalidate();	0
269624	268595	How do I get latest clearcase label programmatically from C#?	Dim CC As New ClearCase.Application \nDim labelID As String\nSet aVersion = CC.Version("[Path-To]\BuildDCP.bat");\nSet someLabels = Ver.Labels;\nIf (someLabels.Count > 0) Then \n    ' the first label listed is the most recently applied\n    labelID = someLabels.Item(1).Type.Name\nEndIf	0
5265578	2039227	What's the file structure of a rar file compressed in store mode	RAR version 4.00 - Technical information\n          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	0
17017466	17017339	How to retrieve files from 2 different projects in the same solution without hard code the path?	~/../publicsite/files/attachment/mrfdocument/	0
19627646	19627465	Filter list with linq for similar items	1) var filteredItems = results.Where( p => p.Name != null && p.Name.ToUpper().Contains(queryString.ToUpper());	0
10408150	10408124	Call aspx page from another PC	TCP    0.0.0.0:2688    <hostname>:0    LISTENING	0
10094502	10094467	Writing Text To A Specific Point In A Text File C#	string fileContent = File.ReadAllText(path);\nfileContent.Replace("[FirstName]", "John");\nFile.WriteAllText(path, fileContent);	0
24910452	24910431	c# if statement inside while loop how to break out if user inputs valid data	if (Double.TryParse(thatOne, out y))\n{\n    break;\n}	0
18117781	17904973	Delete Folder From .Jar While Treating as a Zip	//Code to delete META-INF folder\nusing (ZipFile zip = ZipFile.Read(jarFile))\n{\n    List<string> files = zip.EntryFileNames.ToList<string>();\n    List<string> delete = new List<string>();\n    for (int i = 0; i < files.Count; i++)\n    {\n        if (files[i].Contains("META-INF"))\n        {\n            delete.Add(files[i]);\n        }\n    }\nzip.RemoveEntries(delete);\nzip.Save();\n}\nMessageBox.Show("Success!", "Success", MessageBoxButtons.OK, MessageBoxIcon.None);	0
19831343	19830967	Add new data into existing xml file	XDocument xdoc = XDocument.Load(path_to_xml);\n            xdoc.Element("metadata").Add(\n                new XElement("Employee",\n                    new XAttribute("ID", Convert.ToString(Employee.Id)),\n                    new XAttribute("firstName", Convert.ToString(Employee.FirstName)),\n                    new XAttribute("lastName", Convert.ToString(Employee.LastName)),\n                    new XAttribute("Salary", Convert.ToString(Employee.Salary))\n                    ));\n            xdoc.Save(path_to_xml);	0
17316209	17316069	Getting substrings from <br />	string[] ids = yourIds.Split(new string[] { "<br />" }, StringSplitOptions.RemoveEmptyEntries);	0
22312573	22312385	Splitting a DataTable into 2 using a column index	DataColumn[] aCols = table.Columns.Cast<DataColumn>()\n    .Where(c => c.ColumnName.EndsWith("A"))\n    .Select(c => new DataColumn(c.ColumnName, c.DataType))\n    .ToArray();\nDataColumn[] bCols = table.Columns.Cast<DataColumn>()\n    .Where(c => c.ColumnName.EndsWith("B"))\n    .Select(c => new DataColumn(c.ColumnName, c.DataType))\n    .ToArray();\n\nvar TableA = new DataTable();\nTableA.Columns.AddRange(aCols);\nvar TableB = new DataTable();\nTableB.Columns.AddRange(bCols);\n\nforeach (DataRow row in table.Rows)\n{ \n    DataRow aRow = TableA.Rows.Add();\n    DataRow bRow = TableB.Rows.Add();\n    foreach (DataColumn aCol in aCols)\n        aRow.SetField(aCol, row[aCol.ColumnName]);\n    foreach (DataColumn bCol in bCols)\n        bRow.SetField(bCol, row[bCol.ColumnName]);\n}	0
4700911	4700861	How to use delegates properly? (using WPF Storyboards as example)	EventHandler completedHandler = null; // For definite assignment purposes\ncompletedHandler = delegate\n{\n    storyboard.Stop();\n    Debug.WriteLine("LeavePageStoryboard.Completed");\n    NavigationService.Navigate(uri);\n    storyboard.Completed -= completedHandler;\n};\nstoryboard.Completed += completedHandler;	0
11795286	11795257	What does a function signature without implementation mean in a class definition?	public interface ISomeInterface {\n    void SomeMethod();\n}\n\npublic abstract SomeAbstractClass {\n    public abstract void SomeMethod();\n\n    public void AwesomeMethod() {\n        // I do awesome things; look at my method body!\n    }\n}	0
7576214	7576168	Left Joins in LINQ with multiple Critieria?	from s in db.tblCustomerPricingSchemes\n   .where(x => c.CustomerID == x.CustomerID && \n          x.PSLangPairID == l.LangPairs).DefaultIfEmpty()	0
23025334	23025090	Math error using % in a loop	for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)\n{\n    int index = listBoxDisp.Items.Add("Year:" + yearDisp.ToString());\n    if (checkBoxCensus.Checked == true)\n    {\n        if ((yearDisp % 10) == 0)\n        {\n            listBoxDisp.Items[index] += ",This is a census year";\n        }\n        else { }\n    }\n    else\n    {\n        //nothing needed\n    }\n    if (checkBoxElection.Checked == true)\n    {\n        if ((yearDisp % 4) == 0)\n        {\n            listBoxDisp.Items[index] += ",This is an election year";\n        }\n        else { }\n    }\n    else\n    {\n        //nothing\n    }\n}	0
32658185	32658034	Update model causes interface to be removed from DbContext when using Effort with Entity Framework	namespace Cssd.IT.PortalIntegration.DataAccess.HR.Dao\n{\n    using System;\n    using System.Collections.Generic;\n    using System.ComponentModel.DataAnnotations;\n\n    [MetadataType(typeof(CCS_DEPT_TBL_Meta))]\n    public partial class CCS_DEPT_TBL\n    {\n      ... Your additional constructors and methods here ...\n    }\n    public class CCS_DEPT_TBL_Meta\n    {\n        [Key]\n        public string DEPTID { get; set; }    \n    }\n}	0
16753757	16753600	Delete Row From Data Table	// Work on the first table of the DataSet\nDataTable dt1 = ds.Tables[0];\n// No need to work if we have only 0 or 1 rows\nif(dt1.Rows.Count <= 1) \n     return;\n\n// Setting the sort order on the desidered column\ndt1.DefaultView.Sort = dt1.Columns[0].ColumnName;\n\n// Set an initial value ( I choose an empty string but you could set to something not possible here \nstring x = string.Empty;    \n\n// Loop over the row in sorted order\nforeach(DataRowView dr in dt1.DefaultView)\n{\n    // If we have a new value, keep it else delete the row\n    if(x != dr[0].ToString())\n       x = dr[0].ToString();\n    else\n       dr.Row.Delete();\n\n}\n// Finale step, remove the deleted rows\ndt1.AcceptChanges();	0
4538367	4538321	Reading Datetime value From Excel sheet	double d = double.Parse(b);\nDateTime conv = DateTime.FromOADate(d);	0
20990450	20989462	What to use with WP8, SQL Compact Edition or Sqlite?	private void SelectFromDb()\n    {   \n    SQLite.SQLiteConnection conn = new SQLiteConnection(DB_PATH);\n    //conn.CreateTable<Product>();\n    //InsertSampleinDB(conn);\n    List<Product> myProducts = conn.Table<Product>().ToList().Where(x => x.Name.Length > 10);\n    }	0
7869758	7869516	How can I serialize a 3rd party type using protobuf-net or other serializers?	Serializer.*	0
7609500	7597243	Listbox multiitem selection on selectedindex change?	foreach (ListItem item in lstbox.Items)\n        {\n            if (item.Selected)\n            {\n               //code here\n\n            }\n        }	0
133290	132501	How do I sort a list of integers using only one additional integer variable?	#include <stdio.h>\n\nint main()\n{\nint list[]={4,7,2,4,1,10,3};\nint n;  // the one int variable\n\nstartsort:\nfor (n=0; n< sizeof(list)/sizeof(int)-1; ++n)\nif (list[n] > list[n+1]) {\nlist[n] ^= list[n+1];\nlist[n+1] ^= list[n];\nlist[n] ^= list[n+1];\ngoto startsort;\n}\n\nfor (n=0; n< sizeof(list)/sizeof(int); ++n)\nprintf("%d\n",list[n]);\nreturn 0;\n}	0
31860226	31859446	Deserialise XML to a c# class	XNamespace z = "http://schemas.microsoft.com/2003/10/Serialization/";\nXNamespace ns = "http://schemas.datacontract.org/ConfigurationInterfaces";\nvar list = XDocument.Load(filename)\n            .Descendants(ns + "Outputs")\n            .First()\n            .Descendants(ns + "InstrumentParameter")\n            .Select(e => new\n            {\n                id = (string)e.Attribute(z + "Id"),\n                ChannelNumber = (string)e.Element(ns + "ChannelNumber"),\n                InstrumentParameterType = (string)e.Element(ns + "InstrumentParameterType"),\n                IsMetaData = (string)e.Element(ns + "IsMetaData"),\n                Name = (string)e.Element(ns + "Name"),\n            })\n            .ToList();	0
29018679	29018609	How to use the Background property in c#?	PaginaMain.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xD3, 0x94, 0x48));	0
19975437	19973627	log4net doesn't produce a log file when my project is deployed with windows installer	FileInfo fi = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Assembly.dll.config");\nlog4net.Config.XmlConfigurator.Configure(fi);\n_log.Info("Hello logging...");	0
1590286	1589814	Deleting multiple rows in an unbound datagridview	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    // invert row selections\n    if (!row.Selected)\n    {\n        if (!row.IsNewRow)\n        {\n            row.Selected = true;\n        }\n    }\n    else\n    {\n        row.Selected = false;\n    }\n}\n\n// remove selected rows\nforeach (DataGridViewRow row in dataGridView1.SelectedRows)\n{\n    dataGridView1.Rows.Remove(row);\n}	0
19506416	19506386	filling an object from list using Lambda?	var credentials = userList.Where(e => e.Name == "Micheal" &&\n                                      e.EmailAddress == "mich@domain.com")\n                          .Select(e => new Credentials() \n                                 { Id = e.Id, Password = e.Password }).ToList();	0
12778715	12778020	Identify the screen is locked in WindlowsPhone	public App()  \n{  \nRootFrame.Obscured += Obscured;    \nRootFrame.Unobscured += Unobscured;    \n}	0
16334120	16334092	How to rename a "using Directive" C#	// for whole namespace\nusing Excel = Microsoft.Office.Interop.Excel;\n// use like this\nExcel.ApplicationClass excel = /* ... */;\n\n// or for single type\nusing ExcelApp = Microsoft.Office.Interop.Excel.ApplicationClass;\n// use like this\nExcelApp excel = /* ... */;	0
19692852	19692740	Update using user input for multiple arrays	Console.WriteLine("\nUpdate Player: Player {0} has a point total of {1} points",playerNumbers[playerIndex], playerpoints[playerIndex]);	0
10463110	10463042	how to get the Operator type from the string(a + b) Input in c#?	int a = 7;\nint b = 8;\nstring formula = "a+b";\nformula=formula.Replace("a",a.ToString()).Replace("b",b.ToString());\n\nvar calc = new System.Data.DataTable();\nConsole.WriteLine(calc.Compute(formula, ""));	0
25889288	25889214	Remove duplicates from a List<string> in C#	IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);\n\npublic static IEnumerable<TSource> DistinctBy<TSource, TKey>(\n    this IEnumerable<TSource> source,\n    Func<TSource, TKey> keySelector)\n{\n    var knownKeys = new HashSet<TKey>();\n    return source.Where(element => knownKeys.Add(keySelector(element)));\n}	0
17640125	17640069	Making maskedtextbox to read NULL from SqlDataReader	if (precti.Read())\n {\n\n      maskedTextBox2.Text = precti.IsDBNull(24) ? \n                            string.Empty : \n                            precti.GetDateTime(24).ToShortDateString(); \n }	0
7848879	7848774	Get all process of current active session	Process[] runningProcesses = Process.GetProcesses();\nvar currentSessionID = Process.GetCurrentProcess().SessionId;\n\nProcess[] sameAsthisSession = (from c in runningProcesses where c.SessionId == currentSessionID select c).ToArray();\n\nforeach (var p in sameAsthisSession)\n{\n   Trace.WriteLine(p.ProcessName); \n}	0
16487324	16486790	Encoding a C# string to a Google Maps API URL	var firstPart = new string[] {"3806", "Sterling Road", "Downers Grove", "IL"};\nvar secondPart = string.Format("{0}={1}", "sensor","false");\nvar joinedFirstPart = string.Join(" ", firstPart);\n//we want to encode only the parameters with white spaces\nvar encodedParams = HttpUtility.UrlEncode(joinedFirstPart);\nvar rootUrl = string.Format("http://maps.googleapis.com/maps/api/geocode/json?address={0}&{1}", encodedParams, secondPart);	0
29157004	29156949	How do I form a setting name from a passed parameter?	return Properties.Settings.Default["Name" + str]	0
9477632	9477574	Regular expression matching with several conditions	fromstate = Regex.Match(SubjectString, "from (.*?) state(.*?) to (.*?) state(.*?)are met:(.*)").Groups[0].Value; //from state\n\ntostate = Regex.Match(SubjectString, "from (.*?) state(.*?) to (.*?) state(.*?)are met:(.*)").Groups[2].Value; //to state\n\nconditions = Regex.Match(SubjectString, "from (.*?) state(.*?) to (.*?) state(.*?)are met:(.*)").Groups[4].Value; //conditions	0
31097497	31097236	Detect if two paths are the same	public static bool PathsSame(string pth1, string pth2)\n{\n\n    string fName = System.IO.Path.GetRandomFileName();\n    string fPath = System.IO.Path.Combine(pth1, fName);\n    System.IO.File.Create(fPath);\n    string nPath = System.IO.Path.Combine(pth2, fName);\n    bool same = File.Exists(nPath);\n    System.IO.File.Delete(fPath);\n    return same;\n}	0
30611912	30611647	How to store as a comma separated list of values stored in a string, in SQL server	cmd.Parameters.Add("@Joined", SqlDbType.VarChar).Value = Joined.Text;	0
7876843	7869168	How to increment in time?	private void btnStartWatch_Click(object sender, EventArgs e)\n{\n    timer1.Enabled = true;\n}\n\nprivate void btnPauseWatch_Click(object sender, EventArgs e)\n{\n    timer1.Enabled = false;\n}\n\nint i = 1;\nDateTime dt = new DateTime();\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    label1.Text = dt.AddSeconds(i).ToString("HH:mm:ss");\n    i++;\n}	0
29020895	28972748	wpf propertygrid sorts array in alphabetic order when expanded. Anyway to order it in numerical order?	public override string DisplayName {
\n  get {
\n    string formatStr="D" + this.collection.Count.ToString().Length.ToString();
\n    return"[" + index.ToString(formatStr) +"]";
\n  }
\n}	0
979627	979582	How do I handle an event in C# based on a cell click in a DataGridView?	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n        {\n          MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());\n        }	0
9278629	9278595	C# DateTime Parser Bug?	if (text.Length == 7)\n{\n    text = text.Substring(0, 2) + "0" + text.Substring(2);\n}\n// Now parse as ddMMyyyy	0
27688718	27688612	How to scrap data from web page using asp.net	string urls = "your web page";\n        string result = string.Empty;\n\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urls);\n        request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";\n\n        using (var stream = request.GetResponse().GetResponseStream())\n        using (var reader = new StreamReader(stream, Encoding.UTF8))\n        {\n            result = reader.ReadToEnd();\n        }\n\n        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n        doc.Load(new StringReader(result));\n\n        var elements = doc.DocumentNode.SelectNodes("//div[@class='one-third column']");\n        foreach (HtmlNode item in elements)\n        {\n            var node1 = item.SelectNodes(".//li");\n            foreach (HtmlNode li in node1)\n            {\n                var a = li.SelectSingleNode("//a").Attributes["href"].Value;//your link\n            }\n\n        }	0
23899919	23899705	trouble getting attributes from XML elements using LINQ	propMetrics.Descendants("metric").Attributes()	0
2338389	2338324	Grouping Values With C# And LINQ	var data = new []{\n    new { Date = new DateTime(2003, 1, 2), Product = "apple", Orders = (int?) 3 },\n    new { Date = new DateTime(2003, 1, 3),Product =  "orange", Orders = (int?) 5 },\n    new { Date = new DateTime(2003, 1, 4), Product = "grape", Orders = (int?) 2 },\n    new { Date = new DateTime(2003, 1, 4), Product = "grape", Orders = (int?) null }\n};\n\nvar result = data.GroupBy(x => x.Date)\n                 .Select(g => new {\n                   Date = g.Key,\n                   Apples = g.Where(x => x.Product == "apple").Sum(x => x.Orders),\n                   Oranges = g.Where(x => x.Product == "orange").Sum(x => x.Orders),\n                   Grapes = g.Where(x => x.Product == "grape").Sum(x => x.Orders)\n                 });	0
3008034	3008007	Taking 2 attributes from XElement to create a dictionary LINQ	Dictionary<string,string> test = xDoc.Descendants()\n    .Where(t => t.Name == "someelement")\n    .ToDictionary(\n        t => t.Attribute("myattr").Value.ToString(), \n        t => t.Attribute("otherAttribute").Value.ToString());	0
19649988	19649928	How to change the decimal to 12 digit string	string value = ((decimal)(12.50 * 100)).ToString().PadLeft(12, '0');	0
2146835	2145763	Get option to prewiev or save file after upload	Response.ContentType = "Application/pdf";\nResponse.AddHeader("content-disposition", "attachment;filename=" + fileNamn + ".pdf");\nResponse.BinaryWrite(dataPdf); //this is byte data*\nResponse.End();	0
27456068	27415829	Populating a TreeView from a Tree<T> object	void LoadDataTreeNode(TreeView treeView, DataTreeNode<T> dataTreeNode, HashSet<T> hashSet)\n{\n    treeView.Nodes.Clear();\n    LoadDataTreeNode(treeView.Nodes, dataTreeNode, hashSet);\n}\n\n\nbool LoadDataTreeNode(TreeNodeCollection treeNodes, DataTreeNode<T> dataTreeNode, HashSet<T> hashSet)\n{\n    bool result = hashSet.Contains(dataTreeNode.Data);\n    if (result)\n    {\n        var treeNode = new TreeNode(dataTreeNode.Data.ToString());\n\n        // Use this treeNode if at least one of its subtrees contains\n        // the required leaf node values.  Assume that all other\n        // subtrees will be discarded by the relevant recursive calls.\n        result = false;\n        foreach (var child in dataTreeNode.Children)\n        {\n            if (LoadDataTreeNode(treeNode.Nodes, child, hashSet))\n            {\n                result = true;\n            }\n        }\n\n        if (result)\n        {\n            treeNodes.Add(treeNode);\n        }\n   }\n    return result;\n}	0
2690412	2690385	Currency Format in C# to shorten the output string	return (moneyIn > 999) ? (moneyIn/(double)1000).ToString("c", ci) + "k" : moneyIn.ToString("c", ci);	0
34431	34395	How do I truncate a string while converting to bytes in C#?	static string Truncate(string s, int maxLength) {\n    if (Encoding.UTF8.GetByteCount(s) <= maxLength)\n    return s;\n    var cs = s.ToCharArray();\n    int length = 0;\n    int i = 0;\n    while (i < cs.Length){\n    int charSize = 1;\n    if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))\n    charSize = 2;\n    int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);\n    if ((byteSize + length) <= maxLength){\n    i = i + charSize;\n    length += byteSize;\n    }\n    else\n    break;\n    }\n    return s.Substring(0, i);\n}	0
31388310	31330150	Bing Maps Location object - how is equality determined?	public bool AreEqual(Location l1, Location l2){\n    return Math.Round(l1.Latitude, 6) == Math.Round(l2.Latitude, 6) &&\n        Math.Round(l1.Longitude, 6) == Math.Round(l2.Longitude, 6);\n}	0
18574511	18396082	Saving sent sms	[assembly: UsesPermission(Name = "android.permission.READ_SMS")]	0
13361391	13361248	How to retrieve data from Excel file using OleDbConnection	string filename = "@C:\Temp\Copy.xlsx";\n\nOleDbConnection con = new OleDbConnection(\n"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + \nfilename + ";Extended Properties=\Excel 8.0;HDR=YES;IMEX=1\"");	0
22077091	22075248	How to get Display Member of All Combobox columns in dataGridView in C#?	dgv.Rows[i].Cells[0].FormattedValue.ToString();\ndgv.Rows[i].Cells[1].FormattedValue.ToString();	0
3055373	3055195	String.Format not converting integers correctly in arabic	var culture = CultureInfo.CurrentCulture;\nculture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational; // Always use native characters\nstring formatted = string.Format(culture, "{0:d}{1:d}{2:d}", currentItem, of, count);	0
12180053	12180038	Randomly shuffle a List	Random rand = new Random();\nvar models = garage.OrderBy(c => rand.Next()).Select(c => c.Model).ToList();	0
15991063	15991038	How to start form2 in new process?	System.Diagnostics.Process.Start("Form2.exe");	0
249986	249926	Passing Eval from ASPX to Javascript function as Parameter	onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'	0
34387177	34248744	Using a generic type in a collection, without using a generic class in C#	class Foo \n{\n    private Dictionary<int, IRequest> pendingRequests;\n\n    void addRequest(int sequence, IRequest request)\n    {\n        pendingRequests[sequence] = request;\n    }\n}\n\nclass Request<T> : IRequest where T : Response \n{\n}\n\nclass Response\n{\n}\n\ninterface IRequest\n{\n}	0
26101534	26101447	c# view specified amount of data in datagridview	bi.DataSource = context.Table_Name.Take(50).ToList();	0
18649873	18649420	How do I query for tweets from another user?	var twitter = new LinqToTwitter.TwitterContext(auth);\nvar tweets = twitter.Status\n                    .Where(t => t.Type == LinqToTwitter.StatusType.User && t.ID == "Microsoft")\n                    .OrderByDescending(t => t.CreatedAt)\n                    .Take(50);	0
2871766	2871750	How can we get an autogenerated Id from the Table While Inserting?	PractiseDataContext pDc = new PractiseDataContext();\n\n\n\n// Here CustomerId is the Identity column(Primary key) in the 'CustomerDetails' table\n\nCustomerDetail cust = new CustomerDetail();\n\ncust.CustomerName = "LINQ to SQL";\n\n\n\npDc.CustomerDetails.InsertOnSubmit(cust);\n\npDc.SubmitChanges();\n\n\n\nResponse.Write(cust.CustomerId.ToString());	0
12746216	12745972	Is there a way to render an image saved with an activex control in the browser, without sending it to the server?	if (window.ActiveXObject) {\n    try {\n        var excelApp = new ActiveXObject ("Excel.Application");\n        excelApp.Visible = true;\n    }\n    catch (e) {\n        alert (e.message);\n    }\n}\nelse {\n    alert ("Your browser does not support this example.");\n}	0
17973459	17581718	Convert a C# DateTime to XML dateTime type	complexType name="Interaction">\n    <sequence>\n        <element name="ContactDate" type="string" minOccurs="0" maxOccurs="1"/>\n    </sequence>\n</complexType>	0
15367409	15359969	Custom panel with layout engine	internal class VerticalPanel : Panel {\n  private int space = 10;\n\n  public int Space {\n    get { return space; }\n    set {\n      space = value;\n      LayoutControls();\n    }\n  }\n\n  protected override void OnControlAdded(ControlEventArgs e) {\n    base.OnControlAdded(e);\n    LayoutControls();\n  }\n\n  protected override void OnControlRemoved(ControlEventArgs e) {\n    base.OnControlRemoved(e);\n    LayoutControls();\n  }\n\n  private void LayoutControls() {\n    int height = space;\n    foreach (Control c in base.Controls) {\n      height += c.Height + space;\n    }\n    base.AutoScrollMinSize = new Size(0, height);\n\n    int top = base.AutoScrollPosition.Y + space;\n    int width = base.ClientSize.Width - (space * 2);\n    foreach (Control c in base.Controls) {\n      c.SetBounds(space, top, width, c.Height);\n      c.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;\n      top += c.Height + space;\n    }\n  }\n}	0
767979	767869	How to Regex replace match group item with method result	public static string Replace( string input, string pattern, MatchEvaluator evaluator);	0
1174460	1034671	Change ASP.NET default Culture for date formatting	Public Shared Function FormatShortDate(ByVal d As Date) As String\n    If d=#1/1/0001# Then Return ""\n    If d=#1/1/1900# Then Return ""\n    'ISO/IEC 8824 date format\n    Return d.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)\nEnd Function	0
17110856	17110792	Reference object property as a method parameter	public static IEnumerable<T> MyMethod<T>(this IEnumerable<T> entity, \n                               string param, Func<T, string> selector)\n{\n    return entity.Where(l =>\n    System.Data.Objects.SqlClient.SqlFunctions.PatIndex(param, selector(l)) > 0);\n}	0
23563947	23563420	Writing to file in project folder - Operation not permitted	IsolatedStorageFile isoFile;\nisoFile = IsolatedStorageFile.GetUserStoreForApplication();\n\n// Open or create a writable file.\nIsolatedStorageFileStream isoStream =\n    new IsolatedStorageFileStream("Common/DataModel/EventsData.json",\n    FileMode.OpenOrCreate,\n    FileAccess.Write,\n    isoFile);\n\nStreamWriter writer = new StreamWriter(isoStream);	0
16572435	16572362	Rearrange a list based on given order in c#	var list = new List<string>{"CT", "MA", "VA", "NY"};\nvar order = new List<int>{2, 0, 1, 3};\nvar result = order.Select(i => list[i]).ToList();	0
26457095	26457027	Preload database in xamarin ios	string dbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "mydbfile.sqlite");\n\nif (!File.Exists (dbPath))\n    File.Copy (seedFile, dbPath);	0
24156843	24156165	items of the list lost after navigation in windows phone 8 c#	protected override void OnNavigatedTo(NavigationEventArgs e)\n{    \n    base.OnNavigatedTo(e);\n    if (PhoneApplicationService.Current.State.Contains["Contact"])\n    {\n        listOfContact = \n            PhoneApplicationService.Current.State["Contact"] as List<CustomContact>();\n    }\n}\n\n\n\nprotected override void OnNavigatedFrom(NavigationEventArgs e)\n{\n    base.OnNavigatedFrom(e);\n    PhoneApplicationService.Current.State["Contact"] = listOfContact;\n}	0
11207272	11207132	Need help on tree like structure data retrieval	public class HierarchyNode\n{\n    private decimal UserId;\n    private List<HierarchyNode> ChildNodes;\n\n    public List<HierarchyNode> IdentifySubNodeOfRequestedNode(int reqstedId)\n    {\n        if (this.UserId == reqstedId)\n        {\n            return this.ChildNodes;\n        }\n\n        return this.ChildNodes.\n            Select(childNode => childNode.IdentifySubNodeOfRequestedNode(reqstedId)).\n            FirstOrDefault(children => children != null);\n    }\n}	0
4106102	4106048	connect a help file to application	string fbPath = Application.StartupPath;\nstring fname = "help.chm";\nstring filename = fbPath + @"\" + fname;\nFileInfo fi = new FileInfo(filename);\nif (fi.Exists)\n{\nHelp.ShowHelp(this, filename, HelpNavigator.Find, "");\n}\nelse\n{\nMessageBox.Show("Help file Is in Progress.. ",MessageBoxButtons.OK, MessageBoxIcon.Information);\n\n}	0
1828680	1828346	How do I call GetCustomAttributes from a Base Class?	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]\nclass CustomAttribute : Attribute\n{}\n\nabstract class Base\n{\n    protected Base()\n    {\n        this.Attributes = Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute))\n            .Cast<CustomAttribute>()\n            .ToArray();\n    }\n\n    protected CustomAttribute[] Attributes { get; private set; }\n}\n\n[Custom]\n[Custom]\n[Custom]\nclass Derived : Base\n{\n    static void Main()\n    {\n        var derived = new Derived();\n        var attribute = derived.Attributes[2];\n    }\n}	0
5521693	5521676	All controls on a form are invisible	// \n        // WaveformWindow\n        // \n        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n        this.ClientSize = new System.Drawing.Size(398, 373);\n        this.Name = "WaveformWindow";\n        this.ShowInTaskbar = false;\n        this.Text = "WaveformWindow";\n      **this.Controls.Add(this.label1);**\n        this.ResumeLayout(false);	0
19659108	15594920	listening bluetooth device connecting windows phone	PeerFinder.Start()	0
11208480	11208199	How to Compare Values of Two Dictionary and Increment Count if DictA key,values Exists in DictB?	Dictionary<int, string> DicA = new Dictionary<int, string>();\nDicA.Add(1,"Mango");\nDicA.Add(2,"Grapes");\nDicA.Add(3,"Orange");\n\nDictionary<int, string> DicB = new Dictionary<int, string>();\nDicB.Add(1,"Mango");\nDicB.Add(2,"Pineapple");\n\nint counter = 0;\n\nforeach (var pair in DicA)\n{\n     string value;\n\n     if (DicB.TryGetValue(pair.Key, out value))\n     {\n          if (value == pair.Value)\n          {\n                counter++;\n          }\n     }\n}	0
4751096	4751033	How can I send an array as a parameter of a query string in c#?	wc.QueryString["data[email]"] = "test@stackoverflow.com";	0
33961665	33842521	Cannot send emails through ASP.NET application	SmtpClient client = new SmtpClient("localhost", 25);\nclient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;\nclient.PickupDirectoryLocation = @"C:\inetpub\mailroot\Pickup";\nclient.Send(mail);	0
26254471	26254325	How to bind and ConvertBack separated TextBox strings to an ObservableCollection<string>?	internal class ViewModel\n{\n    public ObservableCollection<string> MyObservableCollection { get; set; }\n\n    public string MyString\n    {\n        get { return string.Join(",", MyObservableCollection); }\n        set { // update observable collection here based on value }\n    }\n}\n\n<TextBox Text="{Binding MyString, Mode=TwoWay}"/>	0
8441538	8441517	SQL Check for duplicated username in Table	INSERT INTO DuplicateUserInTb1(EmployeeID, [Emp Name], Status, Issue) \nselect t.emp_id, t.empname, t.active, t.du \nfrom (select s1.emp_id, s1.empname,'Active' as active, 'Duplicate User' as du, ROW_NUMBER() OVER (PARTITION BY s1.empName ORDER BY s1.empName) as rowNum \nfrom table s1, \n(select emp_name, count(*) as counts\n from table \n group by emp_name\n having count(*) > 1) s2\n where s1.emp_name = s2.emp_name \n) t where t.rowNum = 1	0
23371040	23370908	Overloading Operator[] For Single Dimension Array	public class Matrix<T>\n{\n    private T[] array;\n\n    public T this[int row, int column]\n    {\n        get { return array[row + column]; }\n    }\n}	0
7615815	7615708	Create a Region or GraphicsPath from the non-transparent areas of a bitmap	Color pixel = bitmap.GetPixel(mouseLocation.X, mouseLocation.Y);\nbool hit = pixel.A > 0;	0
12747196	12747117	Optional argument followed by Params	using System;\n\nclass Test\n{\n    static void PrintValues(string title = "Default",\n                            params int[] values)\n    {\n        Console.WriteLine("{0}: {1}", title, \n                          string.Join(", ", values));\n    }\n\n    static void Main()\n    {\n        // Explicitly specify the argument name and build the array\n        PrintValues(values: new int[] { 10, 20 });\n        // Explicitly specify the argument name and provide a single value\n        PrintValues(values: 10);\n        // No arguments: default the title, empty array\n        PrintValues();\n    }\n}	0
18895268	18895097	string join the innertext of html childnodes	string x = String.Join(",", doc.DocumentNode\n    .SelectNodes("//h4").Elements()\n    .Select(el => el.InnerText)\n    .Where(text => !string.IsNullOrWhiteSpace(text)));	0
22574000	22573491	Working with Dictionary<int, Dictionary<string,int> in asp.net	var dt1 = new Dictionary<string, int> { { "Test1", 1 }, { "Test2", 1 }, { "Test3", 1 } };\nvar dt2 = new Dictionary<string, int> { { "Test11", 101 }, { "Test22", 201 }, { "Test33", 301 } };\n\nvar dt3 = new Dictionary<int, Dictionary<string, int>> { { 11, dt1 }, { 22, dt2 } };\n\nforeach (var kvp in dt3)\n{\n    var innerDict = kvp.Value;\n\n    foreach (var innerKvp in innerDict)\n    {\n         Console.WriteLine(kvp.Key);\n         Console.WriteLine(innerKvp.Key);\n         Console.WriteLine(innerKvp.Value);\n    }\n}	0
23011451	23009926	how to pick contacts from phonebook in windows phone 8 and use that contact in our app	private void SendInviteViaSMS(){\n\n        var phoneNumberChooserTask= new PhoneNumberChooserTask();\n        phoneNumberChooserTask.Completed += PhoneNumberChooserTaskOnCompleted;\n        phoneNumberChooserTask.Show();\n    }\n\n    private void PhoneNumberChooserTaskOnCompleted(object sender, PhoneNumberResult phoneNumberResult)\n    {\n        if (phoneNumberResult.TaskResult == TaskResult.OK)\n        {\n\n            Debug.WriteLine("The phone number for " + phoneNumberResult.DisplayName + " is " + phoneNumberResult.PhoneNumber);\n            var smsComposeTask = new SmsComposeTask();\n            smsComposeTask.To = phoneNumberResult.PhoneNumber;\n            smsComposeTask.Body = String.Format(" Hey {0}, Try this new application. It's great!",phoneNumberResult.DisplayName);\n            smsComposeTask.Show();\n        }\n    }	0
19565668	19565459	Convert string with 5+ decimals to int	int m = int.Parse(amount.Split('.')[0]);	0
18236814	18202966	How to make Chart Legend Items interactive in C#	private void HeapStatsChart_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)\n        {\n            HitTestResult result = HeapStatsChart.HitTest(e.X, e.Y);\n            if (result != null && result.Object != null)\n            {\n                // When user hits the LegendItem\n                if (result.Object is LegendItem)\n                {\n                    // Legend item result\n                    LegendItem legendItem = (LegendItem)result.Object;\n                    ColorDialog Colour = new ColorDialog();\n                    if (Colour.ShowDialog() == DialogResult.OK)\n                    {\n                        HeapChartColorPref[Convert.ToInt16(legendItem.Name.Substring(4))].color = Colour.Color;\n                        GenerateHeapStatsChart(HeapChartColorPref);\n                    }\n                }\n            }\n        }	0
27900317	27900277	How can I pass EventHandler as a method parameter	public static void BuildPaging(Control pagingControl\n                              , short currentPage\n                              , short totalPages\n                              , EventHandler eh // <- this one\n                              )\n{\n    for (int i = 0; i < totalPages; i++)\n    {\n        LinkButton pageLink = new LinkButton();\n        ...\n        pageLink.Click += eh;\n        pagingControl.Controls.Add(paheLink);\n    }\n}	0
24444238	24444145	Disable/ Hide a control inside a specific row of GridView	public class Animal\n{\n    public int RowNumber { get; set; }\n    public string Name { get; set; }\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        Gridview1.DataSource = new List<Animal>\n        {\n            new Animal {RowNumber = 1, Name = "One"},\n            new Animal {RowNumber = 2, Name = "Two"},\n            new Animal {RowNumber = 3, Name = "Three"},\n            new Animal {RowNumber = 4, Name = "Four"},\n        };\n        Gridview1.DataBind();\n    }\n}\n\nprivate int _counter;\n\nprotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        if (_counter == 0)\n        {\n            var linkButton = e.Row.FindControl("DeleteItemsGridRowButton") \n                as LinkButton;\n            linkButton.Visible = false;\n            _counter++;\n        }\n    }\n\n}	0
6330702	6330570	How to read a key from app setting file when value is know?	private static string readConfig(string value)\n    {\n        System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Windows.Forms.Application.ExecutablePath);\n        System.Configuration.AppSettingsSection ass = config.AppSettings;\n        foreach (System.Configuration.KeyValueConfigurationElement item in ass.Settings)\n        {\n            if (item.Value == value)\n                return item.Key;\n        }\n        return null;\n    }	0
26306615	26305883	How to find hour in getdate() is expired	DateTime DB_time = Convert.ToDateTime(dr_pass[2].ToString()); //time from database\n\nif (DateTime.Now < DB_time.AddHours(8)) \n{                \n    return true; // password valid\n}\nelse\n{ \n    return false; // password expired\n}	0
11397490	11395279	Can set the div content with jquery	script.Append("                                    $('<div id=foo class=vw1>"+ info +"</div>').appendTo('body');");	0
9823948	9823883	Adding a right click menu to an item	ContextMenu cm = new ContextMenu();\ncm.MenuItems.Add("Item 1");\ncm.MenuItems.Add("Item 2");\n\npictureBox1.ContextMenu = cm;	0
18280222	18280179	Encrypted string not being stored in database correctly	Convert.ToBase64String()	0
2167278	2167259	How do I execute javascript in a dynamically-added User Control	ScriptManager.RegisterStartupScript(this, this.GetType(), "initializeMap", "initializeMap();", true);	0
7312850	7312837	How do I delete a whole line containing a match in a multiline C# regex?	(^|\n).*Bogus.*\n?	0
5828867	5828650	Error as Input string was not in a correct format	public void CreatePDFDocument(string strHtml)\n    {\n\n        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");\n        // step 1: creation of a document-object\n        Document document = new Document();\n        // step 2:\n        // we create a writer that listens to the document\n        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));\n        StringReader se = new StringReader(strHtml);\n        HTMLWorker obj = new HTMLWorker(document);\n        document.Open();\n        obj.Parse(se);\n        document.Close();\n        ShowPdf(strFileName);\n\n\n\n    }\n\n\n\n\n\n\n\npublic void ShowPdf(string strFileName)\n    {\n        Response.ClearContent();\n        Response.ClearHeaders();\n        Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);\n        Response.ContentType = "application/pdf";\n        Response.WriteFile(strFileName);\n        Response.Flush();\n        Response.Clear();\n    }	0
12709008	12708943	How tear down integration tests	internal static class ListOfIntegrationTests {\n    // finds all integration tests\n    public static readonly IList<Type> IntegrationTestTypes = typeof(MyBaseIntegrationTest).Assembly\n        .GetTypes()\n        .Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(MyBaseIntegrationTest)))\n        .ToList()\n        .AsReadOnly();\n\n    // keeps all tests that haven't run yet\n    public static readonly IList<Type> TestsThatHaventRunYet = IntegrationTestTypes.ToList();\n}\n\n// all relevant tests extend this class\n[TestFixture]\npublic abstract class MyBaseIntegrationTest {\n    [TestFixtureSetUp]\n    public void TestFixtureSetUp() { }\n\n    [TestFixtureTearDown]\n    public void TestFixtureTearDown() {\n        ListOfIntegrationTests.TestsThatHaventRunYet.Remove(this.GetType());\n        if (ListOfIntegrationTests.TestsThatHaventRunYet.Count == 0) {\n            // do your cleanup logic here\n        }\n    }\n}	0
6669294	6669243	c# Lookup for a value in Dictionary of Dictionary	Dictionary<string, InfoObject> userLookup;	0
16997129	16746664	How to create database backup, when DB not stored in Microsoft SQL Server?	try\n{\n    SaveFileDialog sd = new SaveFileDialog();\n    sd.Filter = "SQL Server database backup files|*.bak";\n    sd.Title = "Create Database Backup";\n\n    if (sd.ShowDialog() == DialogResult.OK)\n    {\n        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["project_name.Properties.Settings.project??_nameConnectionString"].ConnectionString))\n        {\n            string sqlStmt = string.Format("backup database [" + System.Windows.Forms.Application.StartupPath + "\\dbname.mdf] to disk='{0}'",sd.FileName);\n            using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))\n            {\n                conn.Open();\n                bu2.ExecuteNonQuery();\n                conn.Close();\n\n                MessageBox.Show("Backup Created Sucessfully");\n            }                   \n        }\n    }\n}\ncatch (Exception)\n{\n    MessageBox.Show("Backup Not Created");\n}	0
5974553	5974493	Calling a wcf service method from Silverlight	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    var proxy = new ServiceReference1.HelloWorldServiceClient();\n    proxy.SayHelloCompleted += proxy_SayHelloCompleted;\n    proxy.SayHelloAsync(_nameInput.Text);\n}\n\nvoid proxy_SayHelloCompleted(object sender, ServiceReference1.SayHelloCompletedEventArgs e)\n{\n    if (e.Error == null)\n    {\n        this.Dispatcher.BeginInvoke(\n            () => _outputLabel.Text = e.Result\n        );\n    }\n    else\n    {\n        this.Dispatcher.BeginInvoke(\n            () => _outputLabel.Text = e.Error.Message\n        );\n    }\n}	0
25996470	25727553	Querying an array of arrays with the MongoDB C# driver	var q = Query.ElemMatch("Keys", Query.In("$elemMatch", new List<BsonValue> { "carrot" }));	0
4076861	4076782	Tree<String> Data Structure in C#	public class CustomTreeNode\n{\n    public String Label { get; set; }\n    public List<CustomTreeNode> Children { get; set; }\n}	0
3506154	3506111	How to split for only one string without using arrays	string xy = "01-India";\nstring xz = xy.Split('-')[0];	0
23881365	23881351	How to change the string into datetime format in c# asp.net	DateTime dt = DateTime.ParseExact\n               (result, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);	0
25372136	25371737	What is the entry point of a WPF application?	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n        // here you take control\n    }\n}	0
20206416	20205973	How big should a button image be?	internal abstract class ButtonBaseAdapter\n{\n  protected static int buttonBorderSize = 4;	0
841879	841848	LINQ2SQL: How do I declare a member variable of type var?	public class foo\n\n    IEnumerable<ScreenCycles> AllThreads;\n    private void getThread()\n    {\n       AllThreads = from sc in db.ScreenCycles\n                          join s in db.Screens on sc.ScreenID equals s.ScreenID\n                          select s;\n    }\n\n}	0
5987401	5986685	Application.Idle only fires after I mouse over my tray icon	Application.Idle	0
32395234	32312783	Background Task - Translating a string based on user language	ResourceLoader.GetForCurrentView().GetString("key");	0
4234655	4234631	How do I declare a DependencyProperty under the "Visibility" category instead of "Other"?	[Description("My Description"), Category("Visibility")]\npublic string ConnectorLabelText\n{\n    get { return (string)GetValue(ConnectorLabelTextProperty); }\n    set { SetValue(ConnectorLabelTextProperty, value); }\n}	0
16927188	16927142	What's the best way to get all the content in between two tagged lines of a file so that you can deserialize it?	var paneContent = new StringBuilder();\nbool lineFound = false;\nforeach (string line in File.ReadLines(path))\n{\n    if (line.Contains(tag))\n    {\n        lineFound = !lineFound;\n    }\n    else\n    {\n        if (lineFound)\n        {\n            paneContent.Append(line);\n        }\n    }\n}\nusing (TextReader reader = new StringReader(paneContent.ToString()))\n{\n    data = (PaneData)(serializer.Deserialize(reader));\n}	0
25763249	25763098	Cant call static list from codebehind	var jobOffers = JobOfferService.GetJobOffers();	0
1242432	1242314	C# combine 2 events in one method	private void dgv_CellEvent(object sender, DataGridViewCellEventArgs e)\n{\n    string abc = "123";\n}\n\n// In the event mapping\n\ndgv.CellEnter += dgv_CellEvent;\ndgv.CellClick += dgv_CellEvent;	0
8241185	8240284	outlook 2007 addin : How to remove particular userproperty of mailItem	UserProperty up = myMailItem.UserProperties["ParentMailRecipients"];\nif(up != null)\n    up.Delete();	0
15020523	15015577	model in expressions different from Model in ViewData	[HttpPost]\npublic ActionResult Edit(InvoiceDetailsViewModel invoice) {\n  using (var context = new HyperContext(WebSecurity.CurrentUserId)) {\n    if (ModelState.IsValid) {\n      if (invoice.ID == 0) {\n        ModelState.Remove("ID");\n        ModelState.Remove("Created");\n        ModelState.Remove("CreatedBy");\n        ModelState.Remove("Modified");\n        ModelState.Remove("ModifiedBy");\n        var dbItem = Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice);\n        context.Invoices.Add(dbItem);\n        context.SaveChanges();\n        invoice = Mapper.Map<InvoiceDetailsViewModel>(dbItem);\n        FillViewBag(context, invoice);\n        return PartialView(invoice);\n      }\n      else {\n        context.Entry(Mapper.Map<eu.ecmt.RecruitmentDatabase.Models.Invoice>(invoice)).State = System.Data.EntityState.Modified;\n        context.SaveChanges();\n        return Content(Boolean.TrueString);\n      }\n    }\n    FillViewBag(context, invoice);\n    return PartialView(invoice);\n  }\n}	0
21732190	21732063	How to create JSON post to api using C#	string result = "";\nusing (var client = new WebClient())\n{\n    client.Headers[HttpRequestHeader.ContentType] = "application/json"; \n    result = client.UploadString(url, "POST", json);\n}\nConsole.WriteLine(result);	0
6421754	6408588	How to tell if there is a console	// Property:\nprivate bool? _console_present;\npublic bool console_present {\n    get {\n        if (_console_present == null) {\n            _console_present = true;\n            try { int window_height = Console.WindowHeight; }\n            catch { _console_present = false; }\n        }\n        return _console_present.Value;\n    }\n}\n\n//Usage\nif (console_present)\n    Console.Read();	0
7453808	7453501	Interface for Application Settings	public interface ISettingsProvider\n{\n    void Load();\n\n    T Query<T>(string key);\n    void Set<T>(string key, T value);\n\n    void Save();\n}	0
3090262	3090247	How to raise an event in C# - Best Approach	class MyClass {\n\n    public event EventHandler SomethingHappened;\n\n    protected virtual void OnSomethingHappened(EventArgs e) {\n        EventHandler handler = SomethingHappened;\n        if (handler != null) {\n            handler(this, e);\n        }\n    }\n\n    public void DoSomething() {\n        OnSomethingHappened(EventArgs.Empty);\n    }\n\n}	0
16930253	16929407	C# console calling SQL - bad execution while string contains lithuanian letters	readname.CommandText = "SELECT [ID] FROM [Net7].[dbo].[GroupFilter] WHERE \n[GroupFilterName]=N'" + CE_ParentName_ + "'";	0
20442780	20442627	Deserialization of MemoryStream via BinaryFormatter	public static void SaveTree(TreeView tree)\n    {\n        using (var ms = new MemoryStream())\n        {\n            new BinaryFormatter().Serialize(ms, tree.Nodes.Cast<TreeNode>().ToList());\n\n            Properties.Settings.Default.tree = Convert.ToBase64String(ms.ToArray());\n            Properties.Settings.Default.Save();\n        }\n    }\n\n    public static void LoadTree(TreeView tree)\n    {\n        byte[] bytes = Convert.FromBase64String(Properties.Settings.Default.tree);\n        using (var ms = new MemoryStream(bytes, 0, bytes.Length))\n        {\n            ms.Write(bytes, 0, bytes.Length);\n            ms.Position = 0;\n            var data =  new BinaryFormatter().Deserialize(ms);\n            tree.Nodes.AddRange(((List<TreeNode>)data).ToArray());\n        }\n    }	0
7155509	7155389	Get scroll Position Percentage	double scrollPercentage = (double) \n                scrollbar.VerticalScroll.Value / scrollBar.VerticalScroll.Maximum;\n\nif (scrollPercentage > 0.6)\n{\n    ...\n}	0
6171173	6171050	Creating WPF popup   	Success win1 = new Success();\nwin1.Owner = this; // For example , see the parent window here\nwin1.WindowStartupLocation = WindowStartupLocation.CenterOwner;\nwin1.ShowDialog();	0
4482498	4482031	WINFORM or WPF: How to trigger custom event inside the constructor of the class that emits it	public UserControl1(IEnumerable<Action> subscribers)   {\n\n   this.OnValueChanged(new EventArgs());\n   this.Value = 100;\n}	0
28885907	28885692	Is there a way to protect a class variable from being modified outside of a function	public class AudioPlayer\n{\n\n    public float Volume \n    {\n       get { return _volume_NeverSetThisDirectly;}\n       set \n       {\n           _volume = value;\n           //Do other necessary things that must happen when volume is changed\n           ModifyChannelVolume(_volume_NeverSetThisDirectly);\n       }\n    }\n    [Browsable(false)]\n    [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n    [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n    private float _volume_NeverSetThisDirectly; //Never assign to this directly!\n}	0
8929737	8929538	How to create a csv and attach to email and send in c#	//Stream containing your CSV (convert it into bytes, using the encoding of your choice)\nusing (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(csv)))\n{\n  //Add a new attachment to the E-mail message, using the correct MIME type\n  Attachment attachment = new Attachment(stream, new ContentType("text/csv"));\n  attachment.Name = "test.csv";\n  mailObj.Attachments.Add(attachment);\n\n  //Send your message\n  try\n  {\n    using(SmtpClient client = new SmtpClient([host]){Credentials = [credentials]})\n    {\n      client.Send(mailObj);\n    }\n  }\n  catch\n  {\n    return "{\"Error\":\"Not Sent\"}";\n  }\n}	0
4414627	4414582	WP7 Linq to XML to get a child element of an XElement by name	XElement response = XElement.Parse(\n@"<response xmlns=""http://anamespace.com/stuff/"">\n    <error code=""ERROR_CODE_1"">You have a type 1 error</error>\n</response>");\n\nXNamespace ns = "http://anamespace.com/stuff/";\n\nXElement error = response.Element(ns + "error");\n\nstring code = (string)error.Attribute("code");\nstring message = (string)error;\n\nConsole.WriteLine(code);\nConsole.WriteLine(message);	0
20030432	20030296	conversion failed varchar to int	SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName = @name", con2);\npamt.SelectCommand.Parameters.AddWithValue("@name", cmbPujaName.SelectedValue);\nDataSet pamtds = new DataSet();\npamt.Fill(pamtds);	0
3436893	3436881	How can I detect all the sub folders under a giving main folder?	string MyPath = "c:\\myapp\\mainfolder\\";\nstring[] subArrFolders = IO.Directory.GetDiretories(MyPath);	0
9037541	9037287	XML Deserialization Problems in C#	public void ReadXml(System.Xml.XmlReader reader) {\n    mValue = reader.GetAttribute("value");\n    reader.Read();\n}	0
19219405	19137426	Cannot deserialize subclass in Find statement in MongoDB	public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)\n{\n    return new GeoJsonObjectSerializer<T>().Deserialize(bsonReader, nominalType, options):\n}	0
23757020	23756905	Validation of method in .cs file in asp.net	using  System.ComponentModel;	0
24992073	24992023	Delete a DbSet object that has containing DbSet objects	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<MapCompany>()\n        .HasOptional(a => a.MapLocations)\n        .WithOptionalDependent()\n        .WillCascadeOnDelete(true);\n}	0
22795290	22793699	Export to excel from sql server database not working properly	int i = 1;\n\nint j = 1;   \n//header row\nforeach(DataColumn col in dtMainSQLData.Columns)\n{  \n  ExcelApp.Cells[i, j]  = col.ColumnName;\n  j++;\n}\n\ni++;\n//data rows\nforeach(DataRow row  in dtMainSQLData.Rows)\n{\n    for (int k = 1; k < dtMainSQLData.Columns.Count + 1; k++)\n    {\n         ExcelApp.Cells[i, k]  = row[k-1].ToString();\n    }\n    i++;\n}	0
7881976	7881961	What makes my program work with a delay on windows startup?	Thread.Sleep()	0
18537622	18537568	How to read a cookie	if (Request.Cookies["userInfo"] != null)\n{\n    string userSettings, lastVisit ;\n    if (Request.Cookies["userInfo"]["userName"] != null)\n    {\n        userSettings = Request.Cookies["userInfo"]["userName"].ToString(); \n    }\n    if (Request.Cookies["userInfo"]["lastVisit"] != null)\n    {\n        lastVisit = Request.Cookies["userInfo"]["lastVisit"].ToString(); \n    }\n}	0
20589368	20589362	Is it Possible to expose a private variable in c# ?	Type type = yourObj.GetType();\nBindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;\nFieldInfo field = type.GetField("fieldName", flags);\nobject value = field.GetValue(yourObj);	0
1273890	1273872	How do I detect a USB drive letter from a c# application?	foreach (DriveInfo drive in DriveInfo.GetDrives())\n{\n    if (drive.DriveType == DriveType.Removable)\n    {\n        // Code here\n    }\n}	0
15082953	15082677	How to copy the latest file from one directory to another	DateTime myFileDate = source.GetFiles().Max(i => DateTime.ParseExact(i.Name.Substring(7, 8), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture));\nFileInfo myFile = source.GetFiles().Single(i => i.Name == "report_" + myFileDate.ToString("yyyyMMdd") + ".text");\nmyFile.CopyTo(Path.Combine(target.ToString(), myFile.Name), true);	0
24425749	24425625	Tracking DownloadProgress with synchronous download	using (var completedEvent = new ManualResetEventSlim(false))\nusing (WebClient wc = new WebClient())\n{\n    wc.DownloadFileCompleted += (sender, args) => \n    {\n        completedEvent.Set();\n    };\n    wc.DownloadProgressChanged += (sender, args) =>\n    {\n        progress = (float) args.BytesReceived / (float) args.TotalBytesToReceive;\n    };\n    wc.DownloadFileAsync(new Uri(noLastSegment + file), path);\n    completedEvent.Wait();\n}	0
5322552	5322220	Two Dates Parameters in SQL Function	strQuery = @"SELECT  fngcodeme(@HESAP, @BAS, @BIT, @DOV)";\n\ndt_stb = DateTime.Parse(txtBoxText1);\nmyCommand.Parameters.AddWithValue("@BAS", dt_stb);\ndt_sts = DateTime.Parse(txtBoxText2);\nmyCommand.Parameters.AddWithValue("@BIT", dt_sts)\n\n// do it for @Hesap and @Dov	0
29532712	29492862	Cannot get an httponly cookie with HttpWebResponse on windows phone 7 app	private CookieContainer cookiecontainer = new CookieContainer();\n\n    private void RequestPOST(string uri)\n    {\n         Uri myUri = new Uri(uri);\n\n         HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);\n         myRequest.Method = "POST";\n         myRequest.ContentType = "application/x-www-form-urlencoded";\n\n         myRequest.CookieContainer = this.cookiecontainer;\n\n         Debug.WriteLine("RequestStream : BEGIN");\n         myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);\n\n    }	0
25427516	25374413	Mono native binary bundle fails to load libc in newer Linux kernels	Mono.Posix.dll.config\nSystem.Drawing.dll.config\nSystem.Windows.Forms.dll.config	0
3580907	3580885	C# Accessing management objects in ManagementObjectCollection	ManagementObject mo = queryCollection.FirstOrDefault();	0
23935311	23935263	Read content of %APPDATA%	var path = Environment.ExpandEnvironmentVariables(@"%APPDATA%\Skype");	0
20467463	20465533	Insert value into radiobutton	radioTrue.IsChecked = arrAnswer[nAnswerNum] == 1;\nradioFalse.IsChecked = arrAnswer[nAnswerNum] == 2;	0
26783265	26781112	Chart won't evaluate Tooltip as String	Series S1 = chart1.Series["Series1"];\nstring legendToolTip = S1.Points.FindMinByValue("Y1").YValues[0] +\n              " - " +  S1.Points.FindMaxByValue("Y1").YValues[0] ;\nMessageBox.Show(legendToolTip );	0
26839391	26839347	Crystal reports 2008 sp5 generates a corrupt word document	oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length));\n                                           ^^^^^^^^^^^^^^	0
15417805	15417623	How to get linq sum of IEnumerable<object>	private static Func<object, object, object> GenAddFunc(Type elementType)\n{\n    var param1Expr = Expression.Parameter(typeof(object));\n    var param2Expr = Expression.Parameter(typeof(object));\n    var addExpr = Expression.Add(Expression.Convert(param1Expr, elementType), Expression.Convert(param2Expr, elementType));\n    return Expression.Lambda<Func<object, object, object>>(Expression.Convert(addExpr, typeof(object)), param1Expr, param2Expr).Compile();\n}\n\nIEnumerable<object> listValues;\nType elementType = listValues.First().GetType();\nvar addFunc = GenAddFunc(elementType);\n\nobject sum = listValues.Aggregate(addFunc);	0
16764942	16764745	Get Text Color from Range	Font.Color	0
4487389	4487357	aggregate list with linq with sum	public static IEnumerable<BrowserVisits> SumGroups(\n    IEnumerable<BrowserVisits> visits)\n{\n    return visits.GroupBy(\n        i => i.BrowserName,\n        (name, browsers) => new BrowserVisits() {\n            BrowserName = name,\n            Visits = browsers.Sum(i => i.Visits)\n        });\n}	0
22363484	22363383	Block page from being viewed if not from redirect in ASP.NET/C#	if(PreviousPage != null)\n{\n    if(PreviousPage.IsCrossPagePostBack == true)\n    {\n         Label1.Text = "Cross-page post.";\n    }\n}\nelse\n{\n    Label1.Text = "Not a cross-page post.";\n}	0
16552387	16552312	C# CheckBox to Button	if (checkbox1.Checked)\n{\n    //Do something\n}	0
21705390	21705229	How do I use a Controller which is in a Class Library?	static bool IsControllerType(Type t)\n{\n     return\n        t != null &&\n        t.IsPublic &&\n        t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&\n        !t.IsAbstract &&\n        typeof(IController).IsAssignableFrom(t);\n}	0
3781806	3781764	How can we convert binary number into its octal number using c#?	string binary = "10011";\nint integer = Convert.ToInt32(binary, 2);\nConsole.WriteLine(Convert.ToString(integer, 8));\n\nOutput: 23	0
13025069	12372591	Dynamic Where Condition on Entity Framework failed for Datetime with Cast	string temp = SearchedQuery.Trim();\n DateTime res;\n if (DateTime.TryParse(temp, out res))\n {\n query += ((" ( it." + field.Name + " >@p" + i + ""));\n\n query += " AND ";\n\n ObjectParameter pr = new ObjectParameter("p" + i, res);\n\n i++;\n\n query += ((" it." + field.Name + " <@p" + i + " ) "));\n\n ObjectParameter pr1 = new ObjectParameter("p" + i, res.AddDays(1));\n\n param.Add(pr);\n param.Add(pr1);\n\n\n query += " OR ";\n}	0
9130166	9127621	PerformDataBinding not firing in DataBoundControlAdapter for ListBox	void listBox_DataBinding(object sender, EventArgs e)\n{\n    ObjectDataSource ods = listBox.DataSourceObject as ObjectDataSource;\n    if (ods != null)\n    {\n        IEnumerable data = ods.Select();\n        PerformDataBinding(data);\n        ods.Selecting += (s, ev) => { ev.Cancel = true; };\n    }\n}	0
8506772	8506570	Dynamically Derive Label Name in Loop?	Label toUpdate = (Label)myTable.FindControl("Label1_1");\ntoUpdate.Text = childOne;	0
16862557	16862502	Assign all distinct items from one column of IEnumerable to SelectList	var selectListData = srcEnumerable.Select(x => x.DesiredField).Distinct();	0
10844361	10816932	How can I unit test a lock statement?	public class MyLock : IDisposable\n{\n    private object _toLock;\n\n    public MyLock(object toLock)\n    {\n        _toLock = toLock;\n        Monitor.Enter(_toLock);\n    }\n\n    public virtual void Dispose()\n    {\n        Monitor.Exit(_toLock);\n    }\n}	0
17676963	17663848	using string to set default selection of drop down list	int i = 0;\n            foreach (var item in catagoryDropDown.Items)\n            {\n                if (item.ToString().Equals("Sick Leave"))\n                {\n                    catagoryDropDown.SelectedIndex = i;\n                    break;\n                }\n                i++;\n            }	0
20754782	20754436	ImportRow make the new row column missing	DataTable dt= new DataTable();\n   dt= oldDT.Clone();\n    for (int i=0;i < oldDT.Rows.Count; i++)\n    {\n        dt.ImportRow(dataTable.Rows[i]);\n    }	0
14880231	14102938	Navigate Programmatically in Windows Media Center	System.Windows.Forms.SendKeys.SendWait(key);	0
2434949	2434912	Split string var	string strData = "1|2|3|4||a|b|c|d";\nstring[] strNumbers = strData.Split(new[] {"||"}, StringSplitOptions.None);\nstring[] strNumArray = strNumbers[0].Split('|');	0
28902684	28902206	problems with finding checkboxlist ID with findcontrol	var selectedControls = div.Controls.OfType(CheckBoxList).Where(item => item.Selected);\n\nforeach(CheckBoxList item in selectedControls)\n{\n    ...\n}	0
1576145	1576140	Best practice in checking if a string is a datetime before converting?	string text = "10/16/2009";\nDateTime result;\n\nif (DateTime.TryParse(text, out result))\n{\n    // success, result holds converted value\n}\nelse\n{\n    // failed\n}	0
9817804	9817591	Convert querystring from/to object	public T GetFromQueryString<T>() where T : new(){\n    var obj = new T();\n    var properties = typeof(T).GetProperties();\n    foreach(var property in properties){\n        var valueAsString = HttpContext.Current.Request.QueryString[property.PropertyName];\n        var value = Parse( valueAsString, property.PropertyType);\n\n        if(value == null)\n            continue;\n\n        property.SetValue(obj, value, null);\n    }\n    return obj;\n }	0
16467385	16466928	How to print text to bottom left corner in page in C#	void ProvideContent(object sender, PrintPageEventArgs e)\n    {\n        e.Graphics.DrawString("string containing variable number of lines", new Font("Arial", 12),\n            Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top);\n\n\n        string bottom = "Bottom line1\r\nBottom line2";\n        Font courier = new Font("Courier", 10);\n        Size sz = TextRenderer.MeasureText(bottom, courier);\n        e.Graphics.DrawString(bottom, courier, Brushes.Black,\n                    e.MarginBounds.Left, e.MarginBounds.Bottom - sz.Height);\n    }	0
8405915	8405871	hide paging numbers in gridview?	GridView.PagerSettings.Visible = false;	0
12123690	12123606	How to sort DropDownButton items?	List<string> list = (List<string>) btnKats.DropDownItems;\nlist.Sort();\nbtnKats.DropDownItems = list;	0
23504655	23504500	Linq query to get disjoint set in a many to many relation	db.Persons.Where(p => !p.Users.Any())	0
4526641	4526574	How to output the shortest path in Floyd-Warshall algorithm?	int[,] pathS = new int[matrixDimention, matrixDimention];\nfor (int i = 0; i < splitValues.Length; i++){\n    intValues[i / (matrixDimention), i % (matrixDimention)] = Convert.ToInt32(splitValues[i]);\n    pathS[i / (matrixDimention), i % (matrixDimention)] = -1;    \n}\n.....\nfor (int k = 1; k < n+1; k++)\n    for (int i = 1; i < n+1; i++)\n        for (int j = 1; j < n+1; j++)\n            if (intValues[i, j] > intValues[i, k] + intValues[k, j]){                \n                intValues[i, j] = intValues[i, k] + intValues[k, j];\n                pathS[i,j] = k;\n                string str_intvalues = intValues[i, j].ToString();\n                MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);\n            }\n            else{                \n                string str_intvalues = intValues[i, j].ToString();\n                MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);\n            }	0
12993174	12993153	Is it possible to apply math operations from a list in C# 4.0	List<Func<int, int, int>> lstMat = new List<Func<int, int, int>>()\n{\n    (x,y)=>x.CompareTo(y),\n    (x,y)=>x+y,\n    (x,y)=>x-y\n};\n\nint ir1=1;\nint ir2=2;\n\nint irNew= lstMat[1](ir1,ir2);	0
20412319	20412042	Is this the right way to query a SQL Server CE table for a record, populating and returning a custom object?	{\n    invItem = new InventoryItem{\n      Id = Convert.ToString(reader["Id"]),\n    .....\n    };\n}	0
10358969	10337604	Best practices to build an alert system using ravendb	public void Handle(BookUpdated msg)\n{\n    var book = Session.Load<Book>(msg.BookId);\n    var alerts = Session.Query<Alerts>()\n        .Search(x=>x.Keywords, book.Description)\n        .ToList();\n\n\n\n    // alert for book\n\n\n}	0
15887458	15887260	Update field using same field as key with Simple.Data	MyDb.MySchema.Table.UpdateAll(Field1: 5001, Condition: MyDb.MySchema.Table.Field1==5000 && MyDb.MySchema.Table.Field2==1)	0
14411382	14411368	Unable to access a new class added to a class library	namespace DotNetOpenAuth_Library\n{\n    public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval\n    {\n        //(snip)\n    }\n}	0
10442056	10441602	gtk# ScrolledWindow - scroll to top	scrollWin.get_vadjustment()->set_value(0);	0
23079693	23078936	Propagate DataContext to Dependency Property from ContentControl	Content="{Binding}"	0
8635905	8632479	Do I need to use a property ClassId to represent a relationship in the Code First (Entity Framework)?	var user = GetNewUserSomewhere();\ncontext.Users.Add(user);\n\n// Dummy profile representing existing one.\nvar profile = new Profile() { Id = 1 };\n// Informing context about existing profile.\ncontext.Profiles.Attach(profile);\n\n// Creating relation between new user and existing profile\nuser.Profile = profile;\n\ncontext.SaveChanges();	0
23333761	23332726	NUnit set test name programmatically	public static IEnumerable TestCases\n  {\n    get\n    {\n      yield return new TestCaseData( 12, 3 ).Returns( 4 );\n      yield return new TestCaseData( 12, 2 ).Returns( 6 );\n      yield return new TestCaseData( 12, 4 ).Returns( 3 );\n      yield return new TestCaseData( 0, 0 )\n        .Throws(typeof(DivideByZeroException))\n        .SetName("DivideByZero")\n        .SetDescription("An exception is expected");\n    }\n  }	0
28083883	28083741	multilevel inheritance with same method names c#	class A\n{\n    public string helloworld()\n    {\n        return "A";\n    }\n}\n\nclass B : A\n{\n    public new string helloworld()\n    {\n        return "B";\n    }\n}\n\nclass C: B\n{\n   public string hi(bool condition)\n   {\n      if(condition)\n      {\n         A instance = this;\n         return instance.helloworld(); // From class A\n      }\n      else\n      {\n          B instance = this;\n          return instance.helloworld(); // From class B\n      }\n    }\n}	0
15654488	15654278	50 shades of grey	public static Color GetShade(Color start, Color end, byte intervals, byte index)\n      {\n        var deltaR = end.R - start.R;\n        var deltaG = end.G - start.G;\n        var deltaB = end.B - start.B;\n\n        var intervalR = deltaR / intervals;\n        var intervalG = deltaG / intervals;\n        var intervalB = deltaB / intervals;\n\n        var finalR = start.R + (index * intervalR);\n        var finalG = start.G + (index * intervalG);\n        var finalB = start.B + (index * intervalB);\n\n        return new Color { R = (byte)finalR, G = (byte)finalG, B = (byte)finalB };\n      }	0
12461842	12461473	Modify the content of the home page programmatically in SharePoint 2010	using (var site = new SPSite(ApplicationResources.Url.SiteRoot))\n{\n    using (var web = site.OpenWeb())\n    {\n        var page = web.GetFile(ApplicationResources.Url.FullDefaultPageName);\n        var item = page.Item;\n        item["Wiki Content"] = NewContent(title, text);\n        item.Update();\n    }\n}	0
786281	786268	In .Net, how do you convert an ArrayList to a strongly typed generic list without using a foreach?	var list = arrayList.Cast<int>().ToList();	0
23461438	23426765	How to cache a page in Windows Phone 8.1	public MainPage()\n    {\n       this.InitializeComponent();\n       this.NavigationCacheMode = NavigationCacheMode.Required;\n    }	0
31585877	31580809	How to get access token with Xamarin.Auth?	var auth = new OAuth2Authenticator (\n               clientId: "CLIENT_ID",\n               scope: "basic",\n               authorizeUrl: new Uri ("https://api.instagram.com/oauth/authorize/"),\n               redirectUrl: new Uri ("REDIRECT_URL"));\n\nauth.AllowCancel = allowCancel;\n\n// If authorization succeeds or is canceled, .Completed will be fired.\nauth.Completed += (s, ee) => {\n    var token = ee.Account.Properties ["access_token"];\n};\n\nvar intent = auth.GetUI (this);\nStartActivity (intent);	0
4974972	4974945	How do you share a MS Access Database File in C#?	Mode=Share Deny None	0
12294315	12293912	how to convert T-SQL Query to linq	var result = var clearanceTypes = context.CLEARANCE_REQUEST\n    .Single(r => r.REQUEST_ID == 3)\n    .CLEARANCE_DOCUMENTS\n    .SelectMany(dt => dt.DOCUMENT_TYPES)\n    .Select(a => new \n    {\n        DocumentType = a,\n        IsOriginal = a.CLEARANCE_REQUEST_DOCUMENT.is_original\n    });	0
8710997	8708853	Closing process start from windows application on application close or exit	Process[] p = Process.GetProcessesByName("osk");\nforeach (var item in p)\n{\n    item.Kill();\n}	0
3444925	3444699	C# numeric enum value as string	public static class Program\n{\n    static void Main(string[] args)\n    {\n        var val = Urgency.High;\n        Console.WriteLine(val.ToString("D")); \n    }\n}\n\npublic enum Urgency \n{ \n    VeryHigh = 1,\n    High = 2,\n    Low = 4\n}	0
27173785	27173633	Group by one table and sum from another table in Linq	group new { i, tdi } by i.ItemId\n...\nselect new \n{\n   selection.Sum(x => x.tdi.quantity)\n}	0
9939342	9939233	Validate string to have no space char and only first and last char as delimeter	char delimiter = ...  \nstring delimiterString = delimiter.ToString();\nstring s = ...\nbool right = !s.Contains(' ') \n  && s.StartsWith(delimiterString) \n  && s.EndsWith(delimiterString)\n  && !s.Substring(1,s.Length-2).Contains(delimiter);	0
17339659	17339332	read text file delimited by enter in a dataset in C#	string[] dataFile = Directory.GetFiles(fullPath);\nDataSet ds = new DataSet();\nDataTable dt = ds.Tables.Add();\nDataRow dr;\n\ndt.Columns.Add("column1"); \ndt.Columns.Add("column2");\ndt.Columns.Add("column3");\n\nif (dataFile.Count() > 0)\n{\n    for (int x = 0; x < dataFile.Count(); x++)\n    {       \n        using (StreamReader sr = new StreamReader(dataFile[x]))\n        {\n            while (sr.Peek() != -1)\n            {\n                string[] fields;\n                fields = sr.ReadLine().Split(',');\n\n                if (fields.Count() == 3) // 3 columns\n                {\n                     dr = dt.NewDataRow();\n                     dr["column1"] = fields[0];\n                     dr["column2"] = fields[1];\n                     dr["column3"] = fields[2];\n                     dt.Rows.Add(dr);\n                }\n            }\n        }\n    }\n\n\n}\n\nds.Tables.Add(dt);	0
5042850	5042813	How to create this kind of XML?	XElement root = new XElement(\n    "Title",\n    new XElement("A",\n        new XElement("aaaaaaaaaaaaa")),\n    new XElement("B",\n        new XElement("bbbbbbbbbbbbb"))\n);	0
24640229	24640035	How to check if Worker Role is running in Azure Emulator	RoleEnvironment.IsEmulated	0
8466865	8466835	Multiple Implementation Attempts	public interface IProcess\n{\n    int ProcessItem(string workType);\n}\n\ninternal interface ITryProcess\n{\n    bool TryProcessItem(string workType, out int result);\n}\n\npublic class ProcessImplementation1 : ITryProcess\n{\n    public bool TryProcessItem(string workType, out int result)\n    {\n        result = -1;\n        return false;\n    }\n}\n\npublic class ProcessImplementation : IProcess\n{\n    public int ProcessItem(string workType)\n    {\n        var implementations = new List<ITryProcess>();\n        implementations.Add(new ProcessImplementation1());\n        // ...\n        int processId = -1;\n        foreach (ITryProcess implementation in implementations)\n        {\n            if (implementation.TryProcessItem(workType, out processId))\n            {\n                break;\n            }\n        }\n        if (processId < 0)\n        {\n            throw new InvalidOperationException("Unable to process.");\n        }\n        return processId;\n    }\n}	0
10096115	10096100	Add carriage return to a string	string s2 = s1.Replace(",", ",\n");	0
28305489	28304765	How to get text in stream from WebRequest?	using System;\nusing System.Collections.Generic;\nusing System.Net;\n\nnamespace Demo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");\n            request.Method = "POST";\n            request.ContentType = "image/png";\n\n            Console.WriteLine(GetRequestAsString(request));\n            Console.ReadKey();\n        }\n\n        public static string GetRequestAsString(HttpWebRequest request)\n        {\n            string str = request.Method + " " + request.RequestUri + " HTTP/" + request.ProtocolVersion + Environment.NewLine;\n            string[] headerKeys = request.Headers.AllKeys;\n\n            foreach (string key in headerKeys)\n            {\n                str += key + ":" + request.Headers[key];\n            }\n\n            return str;\n        }\n    }\n}	0
31854660	31854572	ASP Text Box Mode Date Time setting Current DateTime	txtDate.Text = DateTime.Now.ToLocalTime().ToString("yyyy-MM-ddTHH:mm");	0
12822479	12822323	Create menu items with click event handler in a loop from a list	MenuItem mnuItemDepth = new MenuItem();\nforeach (ClassDepth depth in ClassDepths.ListOfDepths)\n{\n    var tempDepth = depth;  //capture the loop variable here\n    MenuItem it = new MenuItem();\n    it.Header = depth.name;\n    it.Click += new RoutedEventHandler((s, a) => { ChangeDepth(tempDepth); });\n    mnuItemDepths.Items.Add(it);\n}	0
24472646	24472578	Invoke method on class' base field with Reflection	var InvokeMethod = typeof(YourClass).GetMethod("MethodName");\n// or Get.Methods() \n\nInvokeMethod.Invoke(Arguements);\n// if you use Get.Methods() you will get a collection of methods, enumerate in the collection to find what you want.	0
10289788	10288923	Managing two combobox of which only one must have a value	private void lookUpUsers_EditValueChanged(object sender, EventArgs e)\n{\n    if(lookUpUsers.EditValue != null)\n        lookUpRolesPr??dit.EditValue = null;\n}\n\nprivate void lookUpRolesPr??dit_EditValueChanged(object sender, EventArgs e)\n{\n    if(lookUpRolesPr??dit.EditValue != null)\n        lookUpUsers.EditValue = null;\n}	0
21364103	21364010	How to make a field which will be foreign key and primary key at the same time	public class Partner\n{\n    [Key]\n    [ForeignKey("User")]\n    public virtual int Id { get; set; }\n\n    public User User { get; set; }\n\n    public DateTime ExpiredDate { get; set; }\n}\n\npublic class Department\n{\n    [Key]\n    [ForeignKey("User")]\n    public virtual int Id { get; set; }\n\n    public User User { get; set; }\n\n    public string Prefix { get; set; }\n}	0
6147819	6147808	How to change all values in a Dictionary<string, bool>?	foreach (string key in parameterDictionary.Keys.ToList())\n  parameterDictionary[key] = false;	0
20096386	20095675	OnMouseEnter on Rect, Unity3D	GUI.Button (new Rect(0,0,10,10), new GUIContent("Button 1", "Button 1")); \n        string hover = GUI.tooltip;\n\n        if(hover=="Button 1"){\n            Debug.Log("Mouse is over button 1");\n        }	0
6250400	6216716	Constructing an object graph from a flat DTO using visitor pattern	class Customer\n{\n    private readonly Name name;\n    private readonly PostalAddress homeAddress;\n\n    public Customer(Name name, PostalAddress homeAddress, ...)\n    {\n        this.name = name;\n        this.homeAddress = homeAddress;\n        ...\n    }\n}\n\nclass CustomerFactory\n{\n    Customer Create(CustomerDTO customerDTO)\n    {\n        return new Customer(new Name(...), new PostalAdress(...));\n    }\n}	0
3978814	3646488	Locating the source of managed exceptions that aren't coming directly from my code?	var culture = new CultureAndRegionInfoBuilder("ug", CultureAndRegionModifiers.None);\n    var ci = new CultureInfo("en-US");\n    var ri = new RegionInfo("US");\n    culture.LoadDataFromCultureInfo(ci);\n    culture.LoadDataFromRegionInfo(ri);\n    culture.Register();	0
13578678	13578631	Using INotifyPropertyChanged in a Class	private string _someRandomText;\npublic string SomeRandomText {\n    get { return _someRandomText; }\n    set \n    {\n        _someRandomText = value;\n        NotifyPropertyChanged("SomeRandomText");\n    }\n}	0
8099442	8099300	Finding consecutive entries	var triplets = list.Select((item, index) => list.Skip(index).Take(3));\nvar candidates = triplets.Where(triplet => (triplet.Count() == 3) && \n                                           (triplet.All(item => item.Complete)));	0
1681825	1681517	Marshalling struct with embedded pointer from C# to unmanaged driver	[StructLayout(LayoutKind.Sequential)]\npublic struct IoctlWriteRegsIn\n{\n    public uint Address;\n    public IntPtr Buffer;\n    public uint Size;\n}	0
22875731	22872945	WPF Designer Extensibility for Fluent RibbonTabItem	public class WorkspaceView : UserControl {\n    public RibbonTabItem RibbonTabItem { get; set; }\n\n    protected override void OnInitialized(EventArgs e) {\n        base.OnInitialized(e);\n\n        if (DesignerProperties.GetIsInDesignMode(this)) {\n            if (RibbonTabItem != null) {\n                UIElement content = this.Content as UIElement;\n                DockPanel panel = new DockPanel();\n                Content = panel;\n                Ribbon ribbon = new Ribbon();\n                ribbon.Tabs.Add(RibbonTabItem);\n                DockPanel.SetDock(ribbon, Dock.Top);\n\n                panel.Children.Add(ribbon);\n                if (content != null) {\n                    panel.Children.Add(content);\n                    DockPanel.SetDock(content, Dock.Bottom);\n                }\n            }\n        }\n    }\n}	0
24203687	24203639	How to get values inside object got through Json	alert(_responseData[0].IdObservation);	0
10575270	10575046	Converting a simple JavaScript code	static Color dominantColor(Bitmap img)\n{\n    Hashtable colorCount = new Hashtable();\n    int maxCount = 0;\n    Color dominantColor = Color.White;\n\n    for (int i = 0; i < img.Width; i++)\n    {\n        for (int j = 0; j < img.Height; j++)\n        {\n            var color = img.GetPixel(i, j);\n\n            if (color.A == 0)\n                continue;\n\n            // ignore white\n            if (color.Equals(Color.White))\n                continue;\n\n            if (colorCount[color] != null)\n                colorCount[color] = (int)colorCount[color] + 1;\n            else\n                colorCount.Add(color, 0);\n\n            // keep track of the color that appears the most times\n            if ((int)colorCount[color] > maxCount)\n            {\n                maxCount = (int)colorCount[color];\n                dominantColor = color;\n            }\n        }\n    }\n\n    return dominantColor;\n}	0
1533459	1533217	Read output from svn into a string	private void SvnOutputHandler(object sendingProcess,\n                                      DataReceivedEventArgs outLine)\n{\n    Process p = sendingProcess as Process;\n\n    // Save the output lines here\n}\n\n\nprivate void RunSVNCommand()\n{\n    ProcessStartInfo psi = new ProcessStartInfo("svn.exe",\n                                                string.Format("update \"{0}\" {1}", parm1, parm2));\n\n    psi.UseShellExecute = false;\n    psi.CreateNoWindow = true;\n\n    // Redirect the standard output of the sort command.  \n    // This stream is read asynchronously using an event handler.\n    psi.RedirectStandardOutput = true;\n    psi.RedirectStandardError = true;\n\n    Process p = new Process();\n\n    // Set our event handler to asynchronously read the sort output.\n    p.OutputDataReceived += SvnOutputHandler;\n    p.ErrorDataReceived += SvnOutputHandler;\n    p.StartInfo = psi;\n\n    p.Start();\n\n    p.BeginOutputReadLine();\n    p.BeginErrorReadLine();\n\n    p.WaitForExit()\n}	0
25462100	25380051	How to get state="completed" PayPal Payments	The receiver account (info.severiano-facilitator@gmail.com) has the primary currency set     \nto USD but your transaction currency is in the EUR . Whenever you receive the payment in \nthe currency that your account doesn't hold , you need to manually accept the transaction \nby logging to the account . Once you accept the payment PayPal will prompt you to either :\n\n1. Deny the payment \n2. Or accept in the new currency and open the balance in the new currency \n3. Or accept the payment and convert the payment into your primary currency .\n\nFor now I have accepted the EUR currency( second choice 2.) for your sandbox account .   \nNow you should be fine with your next payment and you will receive the Payment status    \nas "completed ".	0
2756565	2756520	Implicit and Explicit implementation of interface	Customization oVar = new Customization();\noVar.GetColumnsDefinition(); // calls 1st method\nICustomization iVar = obj;\niVar.GetColumnsDefinition(); // calls 2nd method - explicit impl.	0
22594480	22594447	How can I implement a string split method in Java like c# does	String test = ";;;;";\n  String[] split = test.split(";", -1);\n  System.out.println(split.length);	0
3313506	3313324	Using LoadControl without a Page	Page page = HttpContext.Current.Handler as Page;\nif (page != null)\n{\n     // Use page instance to load your Usercontrol\n}	0
9802070	9791574	Get creation date for the file with SharpSvn	public static List<SvnFile> GetSvnFiles(this SvnClient client, string uri_path)\n{\n    // get logitems\n    Collection<SvnLogEventArgs> logitems;\n    client.GetLog(new Uri(uri_path), out logitems);\n\n    var result = new List<SvnFile>();\n\n    // get craation date for each\n    foreach (var logitem in logitems.OrderBy(logitem => logitem.Time))\n    {\n        foreach (var changed_path in logitem.ChangedPaths)\n        {\n            string filename = Path.GetFileName(changed_path.Path);\n            if (changed_path.Action == SvnChangeAction.Add)\n            {\n                result.Add(new SvnFile() { Name = filename, Created = logitem.Time });\n            }\n        }\n    }\n\n    return result;\n}	0
29575787	29496107	How to minimize floating point inaccuracy in rotating a point in 3D space about an arbitrary axis?	private static Vector3 RotateArbitrary(Vector3 Point, Vector3 AxisPoint, Vector3 AxisDirection, float Radians)\n        {\n            return Vector3.Add(Vector3.Transform(Vector3.Subtract(Point, AxisPoint), Quaternion.FromAxisAngle(AxisDirection, Radians)), AxisPoint);\n        }	0
18107966	18106784	Displaying 2 columns in one combobox	private void _Combobox1_Format(object sender, ListControlConvertEventArgs e)\n{\n    var x = (DateFilterType)e.ListItem;\n    e.Value = /* insert string concatenation stuff here... */;\n}	0
14918404	14917203	Finding if a string contains a date and time	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace RegTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string testDate = "3214312402-17-2013143214214";\n            Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}");\n            Match mat = rgx.Match(testDate);\n            Console.WriteLine(mat.ToString());\n            Console.ReadLine();\n        }\n    }\n}	0
1222105	1221976	Suggestions needed on most efficient way to retrieve an assembly version from an external assembly	AssemblyName.GetAssemblyName("foo.dll").Version	0
6479566	6479543	How to add lines of a text file into individual items on a ListBox (C#)	String text = File.ReadAllText("ignore.txt");\n\nvar result = Regex.Split(text, "\r\n|\r|\n");\n\nforeach(string s in result)\n{\n  lstBox.Items.Add(s);\n}	0
2185422	2184624	How to check if two System.Drawing.Color structures represent the same color in 16 bit color depth?	void MyTestMethod() {\n    TransparencyKey = Color.FromArgb(128, 128, 64);\n    BackColor = Color.FromArgb(128, 128, 71);\n\n    byte tR = ConvertR(TransparencyKey.R);\n    byte tG = ConvertG(TransparencyKey.G);\n    byte tB = ConvertB(TransparencyKey.B);\n\n    byte bR = ConvertR(BackColor.R);\n    byte bG = ConvertG(BackColor.G);\n    byte bB = ConvertB(BackColor.B);\n\n    if (tR == bR &&\n        tG == bG &&\n        tB == bB) {\n        MessageBox.Show("Equal: " + tR + "," + tG + "," + tB + "\r\n" +\n            bR + "," + bG + "," + bB);\n    }\n    else {\n        MessageBox.Show("NOT Equal: " + tR + "," + tG + "," + tB + "\r\n" +\n            bR + "," + bG + "," + bB);\n    }\n}\n\nbyte ConvertR(byte colorByte) {\n    return (byte)(((double)colorByte / 256.0) * 32.0);\n}\n\nbyte ConvertG(byte colorByte) {\n    return (byte)(((double)colorByte / 256.0) * 64.0);\n}\n\nbyte ConvertB(byte colorByte) {\n    return (byte)(((double)colorByte / 256.0) * 32.0);\n}	0
837	832	How do I most elegantly express left join with aggregate SQL as LINQ query	var collection=\n    from u in db.Universe\n    select new\n    {\n        u.id,\n        u.name,\n        MaxDate =(DateTime?)\n       (\n           from h in db.History\n           where u.Id == h.Id\n           && h.dateCol < yesterday\n           select h.dateCol \n       ).Max()\n    };	0
733253	733243	How to copy part of an array to another array in C#?	int[] b = new int[3];\nArray.Copy(a, 1, b, 0, 3);	0
5998145	5997360	locking a resource via lock within try. Is it wrong?	lock(whatever)\n{\n    try\n    {\n        MakeAMess();\n    }\n    finally\n    {\n        CleanItUp();\n        // Either by completing the operation or rolling it back \n        // to the pre-mess state\n    }\n}	0
5942992	5942971	read xml with linq	XNamespace  xmlns = "http://mysite.com/";\nvar doc = XElement.Parse(s);\nforeach (var v in doc.Descendants(xmlns + "name"))\n{\n    //do work\n}	0
25807607	25807329	Read all descendants of a single element	var desc = xd.Descendants("set1").Elements("entry");	0
14301290	14301011	How can I determine if the MSR is finished reading the data from the Credit Card using C#?	TextBox.TextChanged	0
31334641	31328336	Changing icon programmatically of a UIBarButton item in Xamarin	private void UpdateToolbar()\n{\n    // Check which items should be visible and add it to the list\n    var itemlist = new List<UIBarButtonItem>();\n\n    var img = IsCorrect ? "Icon_Correct" : "Icon_incorrect";\n    var mybtn= CreateToolbarItem(img);\n\n    itemlist.Add(mybtn);\n\n    // Set toolbaritems\n    SetToolbarItems(itemlist.ToArray(), false);\n}\n\npublic static UIBarButtonItem CreateToolbarItem(String name)\n{\n    var btn = new UIButton(UIButtonType.Custom);\n    btn.SetImage(UIImage.FromBundle(name), UIControlState.Normal);\n    btn.Frame = new CGRect(0, 0, 32, 32);\n\n    return new UIBarButtonItem(btn);\n}	0
25123097	25122942	How to make .ics file as downloadable c#	iCalendarSerializer serializer = new iCalendarSerializer(iCal);\nserializer.Serialize(Response.OutputStream, Encoding.ASCII);	0
8717406	8679751	How to update listview after Form.Show	public new void Show()\n{\n    if (_showdialog)\n    {\n        _dialog.Show(Control.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle));\n    }\n    else\n    {\n        _dialog.BringToFront();\n    }\n}	0
11159413	11158971	Maximum number of excel processes?	var apps = new List<Application>();\n for (int i=0;i<25;i++)\n {\n      apps.Add(new Application());\n }	0
26994374	26990657	Ext.Net retrieve DateField with GetCmp	X.GetCmp<DateField>("dfDate", new DateField.Config() { Format = "dd MMM yyyy"});	0
26522500	26521901	WebAPI route configuration for multiple HttpPost's with different actions	Using Route attribute\n\n[RoutePrefix("api/v2/my")]\npublic class MyV2Controller \n{\n    [HttpPost]\n    [Route("action1")]\n    public Task<UserModel> Action1([FromBody] FirstModel firstModel)\n    { }\n\n    [HttpPost]\n    [Route("action2")]\n    public Task<UserModel> Action2([FromBody] SecondModel secondModel)\n    { }\n}	0
4462442	4461853	Updating Splash labels in a SingleInstanceApplication : WindowsFormsApplicationBase	class SingleInstanceApplication : WindowsFormsApplicationBase {\n    private static SingleInstanceApplication instance;\n    public SingleInstanceApplication() {\n       instance = this;\n    }\n}	0
31915369	31910085	Use SetThreadExecutionState with app that doesn't already prevent sleep mode	using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var spotify = new Process();\n            spotify.StartInfo.FileName = "Spotify.exe";\n            spotify.StartInfo.Arguments = "-v -s -a";\n            Process.Start("powercfg", "-CHANGE -monitor-timeout-ac 0");\n            spotify.Start();\n            spotify.WaitForExit();\n            var exitCode = spotify.ExitCode;\n            spotify.Close();\n            Process.Start("powercfg", "-CHANGE -monitor-timeout-ac 1");\n        }\n    }\n}	0
16779018	16778018	Replacing a color C#	if (tempCol.ToArgb() == river.ToArgb()) \n{\n     city.SetPixel(x, y, Color.Yellow);\n}	0
6912425	6912228	Remove all zeroes except in numbers	string clean = Regex.Replace(dirty, @"(?<!\d)0+|0+(?!\d|$)", "");	0
3297825	3297730	How to calculate the amount that exists in 2 different text files	int start = "61111111111111111111111111111".Length + 1;\nint length = "2500000000".Length;\n\n\nstring[] lines = System.IO.File.ReadAllLines(filename);\nforeach(string line in lines)\n{\n  string data = line.SubString(start, length);\n  double number = double.parse(data, CultureInfo.InvariantCulture);\n  // sum it\n}	0
28961996	28957459	Giving a row number to mysql data based on date	SET @row_number=0; SELECT @row_number := @row_number +1 AS 'row number', table1.* FROM (SELECT physiotherapy_evaluation_form_id AS 'id',\nCONCAT( student_first_name, ' ', student_second_name, ' ', student_third_name, ' ', student_last_name ) AS 'student name',\ntherapist_first_name, date FROM physiotherapy_evaluation_form,student, therapist WHERE therapist_id = therapist_id_fk \nAND student_id_fk  =student_id AND  student_id = 2 AND date BETWEEN '2015-01-01' AND '2015-03-10' ORDER BY date ASC ) AS table1	0
11732687	11732460	what is the best way to run some in another location as if it was at a certain location?	//auto-generated (or half implemented) code\npublic partial User\n{\n    public partial void OnFirstNameChanged();\n\n    private string _FirstName = "";\n    public string FirstName\n    {\n        get\n        {\n            return _FirstName;\n        }\n        set\n        {\n            _FirstName = value;\n            OnFirstNameChanged();\n        }\n    }\n}\n\n//MyCustomStuff.cs\npublic partial User\n{\n    public partial void OnFirstNameChanged()\n    {\n        Console.Write(string.Format("Your name is {0}", FirstName));\n    }\n}	0
19187423	19187062	Multiple Keystrokes	SendKeys.Send("{TAB}{TAB}{ENTER}{TAB}{ENTER}{TAB}{ENTER}");	0
26946627	26813560	WPF: Using the value from listbox which binding with a datatable	private void result_box_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n\n        DataRowView view = result_box.SelectedItem as DataRowView;\n\n            if (view != null)\n            {                    \n                MessageBox.Show(view["ID"].ToString());\n                Searchbox.Text = view["ID"].ToString();\n            } \n\n    }	0
31654095	31654023	WPF: Validate TextBox content immediately	private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)\n{        \n    if (e.Key == YourKey)\n    {\n        //Do something\n    }\n}	0
1263553	1263527	Better word for inferring variables other than var	auto i = 3;	0
16316258	16314177	How to call another activity after certain time	new Thread(new ThreadStart(() =>\n                                 {\n        Thread.Sleep(10000);\n        RunOnUiThread(() =>\n                      {\n          Intent i = new Intent();\n          i.SetClass(this, typeof(Activity2));\n          StartActivity(i);\n\n          this.Finish();\n        });\n\n\n      })).Start();	0
6453364	6453344	wpf form freezing with get data from database	BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};  \nbgWorker.DoWork += (s, e) => {      \n    // Load here your data      \n    // Use bgWorker.ReportProgress(); to report the current progress  \n};  \nbgWorker.ProgressChanged+=(s,e)=>{      \n    // Here you will be informed about progress and here it is save to change/show progress. \n    // You can access from here savely a ProgressBars or another control.  \n};  \nbgWorker.RunWorkerCompleted += (s, e) => {      \n// Here you will be informed if the job is done. \n// Use this event to unlock your gui \n};  \nbgWorker.RunWorkerAsync();	0
17723658	17723276	Delete a single record from Entity Framework?	var employer = new Employ { Id = 1 };\nctx.Employ.Attach(employer);\nctx.Employ.Remove(employer);\nctx.SaveChanges();	0
1636197	1634934	Would C# benefit from distinctions between kinds of enumerators, like C++ iterators?	Reset()	0
11465413	11465194	need to add comments in an existing xml document	string input = @"<?xml version=""1.0"" encoding=""utf-8""?><Person><Name>Job</Name><Address>10dcalp</Address><Age>12</Age></Person>";\n        XDocument doc = XDocument.Parse(input);\n        XElement age = doc.Root.Element("Age");\n        XComment comm = new XComment("This is comment before Age");\n        age.AddBeforeSelf(comm);	0
5027287	5018253	Consume web service in asp.net app from a class library	var serviceName = new ServiceName\n    {\n        Credentials = new NetworkCredential("Username", "Password", "Domain"),\n        Url = "Here you put the correct url of the web service if you published somewhere else"\n    };\nserviceName.CallWebMethod();	0
16811746	16811633	C# Database adding to a table	public void AddQuestion(string title, string question, string answer)\n{\n\n    using (SqlConnection sqlConnection = new SqlConnection(connectionString))\n    using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(@Title, @Question, @Answer)", sqlConnection))\n    {\n        try\n        {\n            sqlConnection.Open();\n            sqlCommand.Parameters.Add(new SqlParameter("@Title", title));\n            sqlCommand.Parameters.Add(new SqlParameter("@Question", question));\n            sqlCommand.Parameters.Add(new SqlParameter("@Answer", answer));\n            sqlCommand.ExecuteNonQuery();\n        }\n        catch (Exception ex)\n        {\n            System.Diagnostics.Debug.WriteLine(ex); \n            throw; \n        }\n    }\n}	0
24011452	24010166	How can i add to dataGridView1 a data to the last row/column?	void PopulateApplications()\n{\n    dataGridView1.Rows.Clear();\n\n    DataGridViewImageColumn img = new DataGridViewImageColumn();\n    img.HeaderText = "Icon";\n    img.Name = "ImageCol";\n    dataGridView1.Columns.Add(img);\n    dataGridView1.Columns.Add("AppName", "Application Name");\n    dataGridView1.Columns.Add("Status", "Status");\n    foreach (Process p in Process.GetProcesses())\n    {\n        if (p.MainWindowTitle.Length > 1)\n        {\n            var icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName);\n            Image ima = icon.ToBitmap();\n            String status = p.Responding ? "Running" : "Not Responding";\n            dataGridView1.Rows.Add(ima, p.MainWindowTitle, status);\n        }\n    }\n}	0
2696568	2696441	Maintain one to one mapping between objects	public class ClassX\n{\n    private ClassY _Y;\n\n    public ClassY Y\n    {\n        get { return _Y; }\n        set\n        {\n            if (_Y != value)\n            {\n                var oldY = _Y;\n                _Y = value;\n\n                if (_Y == null)\n                {\n                    oldY.X = null;\n                }\n                else\n                {\n                    _Y.X = this;    \n                }\n            }\n        }\n    }\n}\n\npublic class ClassY\n{\n    private ClassX _X;\n\n    public ClassX X\n    {\n        get { return _X; }\n        set\n        {\n            if (_X != value)\n            {\n                var oldX = _X;\n\n                _X = value;\n                if (_X == null)\n                {\n                    oldX.Y = null;\n                }\n                else\n                {\n                    _X.Y = this;    \n                }\n\n            }\n        }\n    }\n}	0
27429360	27429209	SQL Parameter on c# context	db.SqlQuery<TEntity>("SELECT * FROM Table WHERE Column = @ParamName", \n               new SqlParameter("ParamName", parameterValue)).ToList();	0
23622536	23622448	Regex for taking only the domain name	[-a-z0-9_]+(?!://)(?:\.[-a-z0-9_]+)?(?=[/:]|$)	0
31043055	31042744	How to add a new property to an existing json without defining model class in C#?	dynamic original = JsonConvert.DeserializeObject(json, typeof(object));\noriginal.data[0].furit_items[0].quality = good;\nvar modifiedJson = JsonConvert.SerializeObject(original , Formatting.Indented);	0
4896638	4896339	How to compare two saved files with the filename of same url?	/etc/2011-01-02 2255/web-page-url.text\n/etc/2011-02-02 2255/web-page-url.text	0
29696601	29686780	Change regex pattern to match string one character at a time	(((4[0-6])|(11[5-9]|12[0-5]))(\.|?)?([0-9]{1,10})??(, )?)+	0
9618792	9615894	Upload Bitmap in a Stream using WCF	mystream.Seek(0, SeekOrigin.Begin)	0
19234071	19232220	Uploading Excel data to SQL Server Error	SqlCommand DropCommand = new SqlCommand(DropString, con);\nSqlCommand CreateCommand = new SqlCommand(CreateString, con);\n\ncon.Open();\n\nCreateCommand.ExecuteNonQuery();  // creates "dbo.students"\nDropCommand.ExecuteNonQuery();    // drops that same "dbo.students" right away ....\n\ncon.Close();	0
5083250	5083220	How To Disable "The document being saved contains tracked changes" Word Dialog Using C#	msDoc.Options.WarnBeforeSavingPrintingSendingMarkup = false;	0
20827666	20825451	Join two dictionaries by value diffs	var analyzed_symbols = new Dictionary<char, double>(){ {'a', 173}, {'b', 1522}, {'z', 99} };\nvar decode_symbols = new Dictionary<char, double>(){ {'?', 100}, {'?', 185}, {'e', 1622} };\n\nvar q = from a in analyzed_symbols\n        from d in decode_symbols\n        let tmp = new { A = a.Key, D = d.Key, Value = Math.Abs(a.Value - d.Value) }\n        group tmp by tmp.A into g\n        select new\n        {\n            Key = g.Key,\n            Value = g.OrderBy (x => x.Value).Select (x => x.D).First()\n        };\n\nvar replace_symbols = q.ToDictionary (x => x.Key, x => x.Value);	0
2957208	2957090	Need help in listbox multiple select	List<int>mySelectedIndices = new List<int>(lstRegion.GetSelectedIndices());	0
30847211	30846067	Writing to NetworkStream to authenticate with Varnish fails	var auth = string.Format("auth {0}\n", hash);\n\nbyte[] outStream = System.Text.Encoding.ASCII.GetBytes(auth);\nserverStream.Write(outStream, 0, outStream.Length);\nserverStream.Flush();\nserverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize); // Don't forget to read the response!!\nreturndata = System.Text.Encoding.ASCII.GetString(inStream);	0
32954055	32951985	How to set a Geometry data dynamically for a Path element in Windows Phone 8?	var xaml = "<Geometry xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"\n    + arrSound + "</Geometry>";\n\nvectorSound.Data = (Geometry)XamlReader.Load(xaml);	0
2038654	2038475	Adding controls to TabItems dynamically at runtime in C#	newbrowse.Dock = DockStyle.Fill;	0
14048096	14044771	"Must Declare the Scalar Variable" error when programatically declaring variables	using (SqlConnection connection = new SqlConnection(connectionString))\n{\n    SqlCommand cmd = new SqlCommand("InsertCommand="INSERT INTO [Table] WeekOf,User,OtherData)\n  VALUES (Convert(Date,@WeekOf,101), @User, @OtherData)"");\n    cmd.CommandType = CommandType.Text;\n    cmd.Connection = connection;\n    cmd.Parameters.AddWithValue("@WeekOf", WeekOfin.Text);\n    cmd.Parameters.AddWithValue("@User", YourUser.Text);\n    cmd.Parameters.AddWithValue("@OtherData", txtAddress.Text);\n    ...\n    ...\n    connection.Open();\n    try\n    {\n      cmd.ExecuteNonQuery();\n    }\n    catch (SqlException ex)\n    {\n      //MessageDlg.Show(ex.Message); //do what ever kind of logging or error trapping here that you want.. \n    }\n    //You will need to explain how you are populating or getting\n    // the MM/YY for WeekOf \n    //Personally I would refactor this code it's a bit unorthodox \n}	0
4446603	4238618	How can find an peak in an array?	% 50 Hz (Dude) -> 50Hz/44100Hz * 2048 -> ~2 Lower Lim\n% 300 Hz (Baby) -> 300Hz/44100Hz * 2048 -> ~14 Upper Lim\nlower_lim = 2;\nupper_lim = 14\nfor fund_cand = lower_lim:1:upper_lim\n    i_first_five_multiples = [1:1:5]*fund_cand;\n    sum_energy = sum(psd(i_first_five_multiples));\nend	0
12411247	12411142	Substring UTF-8 for both latin, chinese, cyrilic, etc	public string SubstringWithinUtf8Limit(string text, int byteLimit)\n{\n    int byteCount = 0;\n    char[] buffer = new char[1];\n    for (int i = 0; i < text.Length; i++)\n    {\n        buffer[0] = text[i];\n        byteCount += Encoding.UTF8.GetByteCount(buffer);\n        if (byteCount > byteLimit)\n        {\n            // Couldn't add this character. Return its index\n            return text.Substring(0, i);\n        }\n    }\n    return text;\n}	0
9829556	9829446	Show text portion in instead of numerical of enum in column	row.Cells["LevelId"].Value = Enum.GetName(typeof(YourEnum), row.Cells["LevelId"]);	0
6367069	6366851	How to apply Style programatically in CustomControl	this.SetResourceReference(ColorPickerButton.StyleProperty, "ColorPickerButtonStyle");	0
58277	51238	How do I conditionally set a column to its default value with MySqlParameter?	command.Parameters.AddWithValue("@parameter", null);	0
27904307	27864615	WP8.1 app crashes when navigating to another page	private async void ItemView_ItemClick(object sender, ItemClickEventArgs e)\n    {\n        {\n\n            var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;\n\n            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Frame.Navigate(typeof(Session), itemId));\n\n\n        }\n    }	0
1944632	1943032	How to access controls located in the listview from codebehind?	protected void CouncilListView_ItemInserted(Object sender, ListViewInsertedEventArgs e)\n{\n    foreach (DictionaryEntry Emailentry in e.Values)\n    {\n        if (Emailentry.Key == "Email") //table field name is "email"\n        {\n            message.To.Add(new MailAddress(Emailentry.Value.ToString()));\n        }\n    }\n}	0
24240468	24240318	Bind datagridview to List<Dictionary<string, string>>	public class Foo\n{        \n    public int Ean { get; set; }\n    public string Titre { get; set; }\n    public int Prix { get; set; }\n    public int Quantite { get; set; }\n}\n\nList<Foo> lst = new List<Foo>();\n\nFoo f = new  Foo();\nf.Ean = Convert.ToInt32(txtStockEAN.Text);\nf.Titre = txtStockTitre.Text;\nf.Prix = Convert.ToInt32(txtStockPrix.Text);\nf.Quantite = Convert.ToInt32(txtStockQuantite.Text);\nlst.Add(f);	0
8960278	8957380	How to reset ListBox SelectedItem to it's orginal state. WP7	public void Show()\n{\n     MessageBox.Show();\n     SelectedCustomer = _previouslySelectedCustomer;\n}	0
34169059	34103512	Inverting WriteableBitmap colors in Pdf Reader (UWP)	private async Task<WriteableBitmap> InvertPageAsync()\n{\n    using (var stream = new InMemoryRandomAccessStream())\n    {\n        await _page.RenderToStreamAsync(stream, _ro);\n\n        // Use WriteableBitmapEx's FromStream\n        WriteableBitmap newWb = await wb.FromStream(stream);\n\n        return newWb.Invert(); // ERROR IN HERE \n    }\n}\n\n\nasync Task UpdatePdf()\n{\n    // Load the document, page, etc. and PreparePageAsync\n    // ...\n    // ...\n\n    // Invert the page and show it in pageImage\n    pageImage.Source = await InvertPageAsync();\n}	0
12902932	12902864	Getting stackoverflow in entity framework with custom get	Address1 { get { ... address1 = employee.Address1; ...} }	0
29033904	28974892	The camera in a side-scrolling tile based game in moving slower than the character	g.DrawImage(p.PlayerSpriteCharSet,\n            new RectangleF(p.X - (float)pCamera.X, p.Y - (float)pCamera.Y, p.PlayerSize.Width, p.PlayerSize.Height),\n            new Rectangle(new Point(tilesetX_px, tilesetY_px), p.PlayerSpriteSize),\n            GraphicsUnit.Pixel);	0
18854457	13552938	How to edit a text file in c# with StreamWriter?	public void EditorialResponse(string fileName, string word, string replacement, string saveFileName)\n{\n    StreamReader reader = new StreamReader(directory + fileName);\n    string input = reader.ReadToEnd();\n\n    using (StreamWriter writer = new StreamWriter(directory + saveFileName, true))\n    {\n        {\n            string output = input.Replace(word, replacement);\n            writer.Write(output);                     \n        }\n        writer.Close();\n    }\n}	0
30623326	30607688	Pass array to C# from C++ via mono	MonoArray* theArray = mono_array_new(domain, containsClass, 1);\nmono_array_set(theArray, MonoObject*, 0, containsObject);\nargs[0] = theArray;\nmono_runtime_invoke(returnElementMethod, NULL, args, &exception); // <--- as expected, outputs "In ReturnElement: 7"	0
31273947	31165548	How to capture a response token sent by a REST API after a request?	string xtoken= response.Headers["custom-header"];\nConsole.WriteLine(xtoken);	0
7323351	7323326	Are explicitly Infinite Loops handled in .NET as a special case?	public int EndlessLoop()\n{\n    while (true)\n    {\n    }\n}	0
27910419	27909991	Play embedded WAV in standalone app	System.IO.Stream s = Resources.ResourceManager.GetStream("speedwarning");\nSoundPlayer player = new SoundPlayer(s);\nplayer.Play();	0
13984181	13983190	ActionResult returning a Stream	MemoryStream stream = someService.GetStream();\n\nreturn new FileStreamResult(stream, "application/pdf")	0
22525572	22525486	to get the file names in a directory (without getting path) in c#	string[] s = Directory.GetFiles(@"c:\\test");\nforeach (string filename in s)\n{     \n    string fname = Path.GetFileName(filename);\n}	0
33236953	33236768	Unpack a String and Arrange it Into Required Structure	String source = "{14*2*57241*5684}";\n  String[] items = source.Trim('{', '}').Split('*');\n\n  EMessage result = new EMessage() {\n    ID = (MessageID) items[0],  //TODO: convert String to MessageID type value here\n    length = Byte.Parse(items[1]),\n    data = items\n      .Skip(2)\n      .Select(item => int.Parse(item))\n      .ToArray()\n  };	0
31218192	31218092	Method that Returns All Products for a particular category ASP.net	public List<Product> GetAllProductsByCategory(int ProductTypeId)\n    {\n            using (GarageEntities db = new GarageEntities()) \n            {\n                List<Product> products = db.Products.where(x=>x.ProductTypeID==ProductTypeId).toList()\n                return products;\n            }  \n\n    }	0
21885165	21885064	Web Api already defines a member called 'Get' with the same parameter types	public class UsersController : ApiController\n{\n    // GET api/companies/GetByUser/{company_id}/{user_id}\n    public object GetByUser(int company_id, int user_id)\n    {\n       ...\n    }\n\n    // GET api/companies/GetByPlanet/{company_id}/{plant_id}\n    public IEnumerable<object> GetByPlanet(int company_id, int plant_id)\n    {\n       ...\n    }\n}	0
3782398	3782344	Adding items in WPF ListView with columns	public class ServerListItem \n{ \n    public string Flag { get; set; }\n    public string Name { get; set; }\n    public string IpAddress { get; set; }\n}	0
24494870	24494041	TCP server only accepts the message from one iOS device at a time	while (true) {\n var clientSocket = listeningSocket.Accept();\n Task.Factory.StartNew(() => HandleClient(clientSocket));\n}	0
29593250	29592988	Iterate over all elements of custom node of linkedlist	List<Node> nodes = Adj[i].ToList();	0
32175679	31984385	How to scroll up using Protractor.NET?	IWebDriver driver = MyWebDriver.WrappedDriver;\nIJavaScriptExecutor jse = (IJavaScriptExecutor)driver;\njse.ExecuteScript("scroll(0, -250);");	0
6862039	6861932	Creating objects in a foreach loop	private IEnumerable<StrongTypeResult> ConvertResults(List<Object> results)\n{\n return results.Select(result => new StrongTypeResult(result));\n}	0
17812553	17810974	Get the list numbers from Word document?	// Loop through each table in the document, \n        // grab only text from cells in the first column\n        // in each table.\n        foreach (Table tb in docs.Tables)\n        {\n            for (int row = 1; row <= tb.Rows.Count; row++)\n            {\n                var cell = tb.Cell(row, 1);\n                var listNumber = cell.Range.ListFormat.ListString;\n                var text = listNumber + " " + cell.Range.Text;\n\n                dt.Rows.Add(text);\n            }\n        }	0
8983066	8982910	Entity Framework Convert DateTime to string	DateTime dateValue;\n\nif (DateTime.TryParse(searchString, out dateValue))\n{\n    leaves = leaves.Where(l => l.StartDate == dateValue);\n}\nelse\n{\n    leaves = leaves.Where(s => s.Employee.Name.ToUpper().Contains(searchString.ToUpper()));\n}	0
2484685	2484664	Help with connection string	string connstring = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=true", Path.Combine(Directory.GetCurrentDirectory(), "MyDatabase01.accdb"));	0
5745342	5745301	Reading Template Field Label value thats bind to sqlDatabase Field	foreach (GridViewRow row in GridView2.Rows)\n{\n    if (((CheckBox)row.FindControl("AttendanceCheckBox")).Checked)\n    {\nInt32 StudentID = Convert.ToInt32(((Label)row.FindControl("studentIDLabel")).Text)\n....\n....\n}	0
2835738	2835182	How dynamic can I make my LINQ To SQL Statements?	var query = context.Messages\n    .AsQueryable();\n\nforeach (Filter filter in filterlist)\n{\n    query = query\n        .Where(m => m.Contains(filter));\n}	0
11666469	11666022	Telerik RadGrid - modifying text in the FilterMenu programatically	protected void Page_Load(object sender, EventArgs e)\n{\n    GridFilterMenu menu = RadGrid1.FilterMenu;\n    foreach (RadMenuItem item in menu.Items)\n    {   \n        if (item.Text == "StartsWith")\n        {\n            item.Text = "Your new text";\n        }\n    }\n}	0
3317974	3317914	How to programmatically scroll TreeView control?	TreeNode.EnsureVisible();	0
30298216	30297759	How to implement recursive self join entity framework?	void GetParents(Menu current) {\n    dbContext.Entry(current).Reference(m => m.Menu2).Load();\n    while (current.Menu2 != null) {\n        current = current.Menu2; \n        dbContext.Entry(current).Reference(m => m.Menu2).Load();\n    }\n}\n\nvoid GetChildren(Menu current) {\n    if (current == null) {\n        return;\n    } else {\n        dbContext.Entry(current).Collection(m => m.Menu1).Load();\n        foreach (var menu in m.Menu1) {\n            GetChildren(menu);\n        }\n    }\n}	0
30388476	30388394	WPF ScrollViewer Slow To Load With RichTextBox	VerticalScrollBarVisibility="Visible"	0
23948749	23943126	How to retrieve the selected group in a LongListSelector?	public class LongListGroupEntry\n{\n    public Group Key;\n    public Contact Value;\n}	0
5571369	5571266	create asterisk tree with C#	int rows = 5;\nStringBuilder sb = new StringBuilder();\n// top part\nfor (int i = 1; i <= rows; i++)\n{\n    for (int j = 1; j <= rows - i; j++)\n        sb.Append(' ');\n    for (int k = 1; k <= 2 * i - 1; k++)\n        sb.Append('*');\n    sb.AppendLine();\n}\n//bottom part\nfor (int n = rows - 1; n > 0; n--)\n{\n    for (int l = 1; l <= rows - n; l++)\n        sb.Append(' ');\n    for (int m = 1; m <= 2 * n - 1; m++)\n        sb.Append('*');\n    sb.AppendLine();\n}\nConsole.Write(sb.ToString());	0
12951501	12951387	Access to Sybase via C# in Windows 7 :ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified	%systemdrive%\Windows\SysWoW64\ODBCAD32.EXE	0
21767044	21766944	SelectList not selecting a default value from List<string>	var pickupTimeList = EntityLogic.PopulateTimeSlots(\n    vm.DateMileage.PickupDate,\n    vm.DateMileage.PickupDate.AddHours(-2), \n    vm.DateMileage.PickupDate.AddHours(2).AddMinutes(15)\n)\n.Select(x => new SelectListItem\n{\n    Value = x,\n    Text = x,\n});\n\nViewBag.PickupTimeList = new SelectList(PickupTimeList, "Value", "Text", "11:00 PM");	0
13925114	13924757	Select multiple rows & colums in datatable where value occurs more than once	var GetProductsRows = from DataRow dr in table.Rows\n    group dr by dr.Field<string>("Product Code") into gp\n    from rows in gp where gp.Count() > 1 select rows;	0
22501994	22493205	How can I get the color of a Panel pixel at the mouse location (RFC)	public Color getScrColor(Control ctl, Point location)\n{\n   Bitmap bmp = new Bitmap(1, 1);\n   Graphics g = Graphics.FromImage(bmp);\n   Point screenP = ctl.PointToScreen(location);\n   g.CopyFromScreen(screenP.X, screenP.Y, 0, 0, new Size(1, 1));\n   Color col = bmp.GetPixel(0, 0);\n   bmp.Dispose();\n   return col;\n}	0
5219998	5219903	Sorting and obtaining the top 5 rows from a dataview	dataGridView1.DataSource = dvData.ToTable().AsEnumerable().OrderBy(r => r["Beta"]).Take(5).ToList();	0
24648036	24645773	Proper structure of Connection string in C#	There are different ways to Create Connection String which depends on \nAuthentication type as you know \n1.> Windows Authentication \n2.> SQL Server Authentication	0
14430810	14415202	Video Player to play video	var url = await YouTube.GetVideoUriAsync(youTubeId, YouTubeQuality.Quality1080P);\nvar player = new MediaElement();\nplayer.Source = url.Uri;	0
15357503	15357401	Define last index of element in text with linq	var result = File.ReadLines(fileName)\n                 .Select((s,i) => new { Line = s, Index = i })\n                 .LastOrDefault(x => x.Line.Contains("i am"));\n\nint index = result == null ? -1 : result.Index;	0
10141719	10141653	Trim string at first punctuation character excluding white space	string s = "Hello, world!";\nstring t = new string(s.TakeWhile(c => !Char.IsPunctuation(c)).ToArray());	0
11263818	11263523	Find XmlNode where attribute value is contained in string	var result = missingPageSettingsXmlDocument\n                .SelectNodes(ITEM_XML_PATH)\n                .Cast<XmlNode>()\n                .FirstOrDefault(\n                    m => m.Attributes != null && \n                    m.Attributes["urlSearchPattern"] != null && \n                    urlSearchPattern.Contains(m.Attributes["urlSearchPattern"].ToString().ToLower())\n                 );	0
12349484	12349415	JSON Parsing in c#. The Json string is in a javascript file	class Program\n{\n    static void Main(string[] args)\n    {\n        var lst = new List<string>();\n        for (var i = 0; i < 1024 * 1024 * 10; i++)\n        {\n            lst.Add(i.ToString());\n            if(i%(1024 * 1024)==0)Console.WriteLine("+1m");\n        }\n        var wrt = Newtonsoft.Json.JsonConvert.SerializeObject(lst);\n        lst = null;\n        File.WriteAllText(@"F:\1.txt",wrt);\n        Console.WriteLine("written");\n        wrt = "";\n        GC.Collect();\n        wrt=File.ReadAllText(@"F:\1.txt");\n        lst=Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(wrt);\n        Console.WriteLine("read");\n        Console.WriteLine(lst.Count.ToString());\n    }\n}	0
2335226	2335113	Ignore binary serialization on a property	[Serializable()]\npublic class Foo\n{\n  public IList<Number> Nums { get; set; }\n\n  public long GetValueTotal()\n  {\n    return Nums.Sum(x => x.value);\n  }\n}	0
953506	953454	Sending notifications from C++ DLL to .NET application	protected override void WndProc(ref Message m)\n{\n    if (m.Msg = YOUR_MESSAGE)\n    {\n        // handle the notification\n    }\n    else\n    {\n        base.WndProc(ref m);\n    }\n}	0
4341394	4341311	help inserting new row into a db using linq	else\n    {\n        int cat = Convert.ToInt32(ddlCategory.SelectedValue);\n        SubCategory subCat = new SubCategory\n        {\n            SubCategoryName = name,\n            Active = false,\n            CategoryID = cat\n        };\n        db.SubCategories.InsertOnSubmit(subCat);\n    }	0
999080	999050	How to get all subsets of an array?	string[] source = new string[] { "dog", "cat", "mouse" };\n for (int i = 0; i < Math.Pow(2, source.Length); i++)\n {\n     string[] combination = new string[source.Length];\n     for (int j = 0; j < source.Length; j++)\n     {\n         if ((i & (1 << (source.Length - j - 1))) != 0)\n         {\n             combination[j] = source[j];\n         }\n    }\n    Console.WriteLine("[{0}, {1}, {2}]", combination[0], combination[1], combination[2]);\n}	0
14013944	14013918	Replace new line regex with a string	string LoadedFile = File.ReadAllText("1.txt");\nstring result = Regex.Replace(LoadedFile, "(Dialogue.+?)\r\n^((?!Dialogue).*)$", "$1\\N$2", RegexOptions.Multiline);	0
3110879	3110848	How to set attribute to an XML element using linq to xml in C#	string filename = @"C:\Temp\demo.xml";\nXDocument document = XDocument.Load(filename);\n\nvar stepOnes = document.Descendants("Step").Where(e => e.Attribute("Test").Value == "SampleTestOne");\nforeach (XElement element in stepOnes)\n{\n    if (element.Attribute("Status") != null)\n        element.Attribute("Status").Value = "Pass";\n    else\n        element.Add(new XAttribute("Status", "Pass"));\n}\n\ndocument.Save(filename);	0
6725801	6725781	C# Collection select value of the property with minimum value of another property	Car slowestCar = collection.MinBy(em => em.Speed);\nstring color = slowestCar.Color;	0
24074295	24070898	Fluent Assertions ThatAreNotDecoratedWith	public static MethodInfoSelector ThatAreNotDecoratedWith<TAttribute>( this MethodInfoSelector selectedMethods)\n{\n    IEnumerable<MethodInfo> methodsNotDecorated = selectedMethods.Where(\n        method =>\n            !method.GetCustomAttributes(false)\n                .OfType<TAttribute>()\n                .Any());\n\n    FieldInfo selectedMethodsField =\n        typeof (MethodInfoSelector).GetField("selectedMethods",\n            BindingFlags.Instance | BindingFlags.NonPublic);\n\n    selectedMethodsField.SetValue(selectedMethods, methodsNotDecorated);\n\n    return selectedMethods;\n}	0
7854807	7854762	Accessing content file in c# web application	Server.MapPath("/")+"bin\\XMLMetadata\\Actions.1.xml"	0
15829344	15829309	Remove Item have same key in List C#	source = source.GroupBy(t => t.id).Select(g => g.First()).ToList();	0
18183613	18183591	C#: Assign test result directly to variable	int a = 1, b = 2;\nbool c = a == b;	0
1871740	1871704	How to automatically determine best .NET type match of a value	Convert.ToInt32	0
13587149	13587102	Has my application been started by hand?	-minimized	0
5746516	5746355	Performing a JOIN in LINQ with a strongly-typed object	var results = from lookup in context.AlbumSongLookups\n              join song in context.Songs on lookup.SongID equals song.ID\n              where lookup.AlbumID == albumID\n              select song;	0
9447755	9447722	How to hold a different shopping cart time for every single user session	(DateTime.Now - Session[LastAccessTime]) > new TimeSpan(0, 20, 0)	0
7713097	7607175	How to get applications associated with a application pool in IIS7	ServerManager manager = new ServerManager();\n        foreach (Site site in manager.Sites)\n        {\n            foreach (Application app in site.Applications)\n            {\n\n                if (app.ApplicationPoolName.ToString() == AppPoolName)\n                {\n                     string appname = app.Path;\n                }\n            }\n        }	0
5670375	5670352	Convert object[] into Lookup with Linq	source.ToLookup(k => k[3], k => new object[] {k[1], k[2] });	0
25713342	25709453	Validating input parameters given to a method c#	[StringLengthValidator(0, 20)]\npublic string CustomerName;	0
10889893	10845868	Changing the name of a sharepoint list programmaticaly	using (SPSite mySite = new SPSite("http://server"))\n            {\n                //open the relevant site\n                using (SPWeb myWeb = mySite.OpenWeb("TestSite"))\n                {\n                    //loop through the lists\n                    foreach (SPList list in myWeb.Lists)\n                    {\n                        //when we find the correct list, change the name\n                        if (list.RootFolder.Name == "OrigListName")\n                        {\n                            //move the root folder\n                            list.RootFolder.MoveTo(list.RootFolder.Url.Replace("OrigListName", "OrigListName_New"));\n                        }\n                    }\n                }\n            }	0
21545953	21545902	Remove Punctuation characters at last from a string	string result=str.TrimEnd('.',',','[',']',' ');	0
20060470	20060416	How to Create This Json?	public class Options\n{\n    public string strokeColor { get; set; }\n    public double strokeOpacity { get; set; }\n    public int strokeWeight { get; set; }\n    public string fillColor { get; set; }\n    public double fillOpacity { get; set; }\n    public List<List<double>> paths { get; set; }\n}\n\npublic class RootObject\n{\n    public Options options { get; set; }\n}	0
5254443	5200764	Restart a WCF service hosted by a C# console application	AppDomain remoteDomain = AppDomain.CreateDomain("New Domain");\nIClass1 class1 = (IClass1)remoteDomain.CreateInstanceFromAndUnwrap(\n                           "Test1.dll", "Test1.Class1");	0
18699684	18699217	How to define an event to a .cs class that is returning a collection of labels?	public List<Label> drawLabel()\n{\n    lstLable = new List<Label>();\n    foreach (cOrderItem item in currOrder.OrderItems)\n    {\n        _lbl = new Label();\n        _lbl.Width = 200;// (int)CanvasWidth;\n        _lbl.BackColor = Color.AliceBlue;\n        _lbl.Text = item.ProductInfo.ProductDesc;\n        _lbl.Height = 20;\n        _lbl.Dock = DockStyle.Top;\n\n        //this is the event i want to define for drawign purpose.\n        _lbl.Paint += new PaintEventHandler(LblOnPaint);\n\n        lstLable.Add(_lbl);\n\n    }\n    return lstLable;\n}\n\n// The Paint event method\nprivate void LblOnPaint(object sender, PaintEventArgs e)\n{\n    // Example code:\n\n    var label = (Label)sender;\n\n    // Create a local version of the graphics object for the label.\n    Graphics g = e.Graphics;\n\n    // Draw a string on the label.\n    g.DrawString(label.Text, new Font("Arial", 10), Brushes.Blue, new Point(1, 1));\n}	0
22807823	22803172	c# windows application fill picturebox with image path stored in database	if (File.Exists(pathFromYourImage) // Just to check if path is valid\n{\n    PictureBox pb1 = new PictureBox();\n    pb1.Image = System.Drawing.Image.FromFile(pathFromYourImage);\n}	0
4671473	4671044	Deserializing JSON responses which contain attributes that conflict with keywords	class Media {\n    [JsonProperty("media_id")]\n    public int MediaId;\n    [JsonProperty("explicit")]\n    public int Explicit;\n}	0
2639465	2639418	Use reflection to get a list of static classes	IEnumerable<Type> types = typeof(Foo).Assembly.GetTypes().Where\n(t => t.IsClass && t.IsSealed && t.IsAbstract);	0
25304929	25303124	C# PowerShell with RunspacePool - How to import Exchange Cmdlets like Get-Mailbox?	// First import the cmdlets in the current runspace (using Import-PSSession)\npowershell = PowerShell.Create();\npowerShell.RunspacePool = runspacePool;\ncommand = new PSCommand();\ncommand.AddScript("Import-PSSession");\ncommand.AddParameter("Session", result[0]);\ncommand.AddParameter("CommandName", new[]{"Get-Mailbox", "Get-MailboxStatistics"});\ncommand.AddParameter("ErrorAction ", "SilentlyContinue ");\n\n\npowerShell.Invoke();	0
18244752	18244686	Is it possible to install or update a Windows Service on a remote host in C#?	Process process = new Process();\nprocess.Start(@"C:\Windows\System32\SC.exe", @"\\remotecomputer create newservice binpath= C:\Windows\System32\Newserv.exe start= auto obj= DOMAIN\username password= pwd");	0
23067351	23066645	Microsoft Unit Testing: How to connect to database	var con = new OracleConnection(); \n    con.ConnectionString = "User Id=<username>;Password=<password>;Data Source= <datasource>"; \n    con.Open();	0
19532913	19528201	AutoMapper decoupling domain from entity and beyond	create table t_order {\n    tracking_id varchar2(255) pk,\n    //other fields\n};\n\ncreate table t_order_booking_contact {\n     tracking_id varchar2(255) pk,\n     name varchar2(255),\n     //other fields\n}	0
12606793	12606094	How can I filter out specified keys in a DGV?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n  if (\n    (keyData >= Keys.D0 && keyData <= Keys.D9) ||\n    (keyData >= Keys.NumPad0 && keyData <= Keys.NumPad9) ||\n    (keyData == Keys.Decimal | keyData == Keys.OemPeriod) ||\n    (keyData == Keys.Back | keyData == Keys.Delete) ||\n    (keyData == Keys.Left | keyData == Keys.Up | keyData == Keys.Right | keyData == Keys.Down) ||\n    (keyData == Keys.Tab | keyData == Keys.Home | keyData == Keys.End | keyData == Keys.Enter)\n    ) {\n    return false;\n  }\n\n  return true;\n}	0
4134698	4133487	How to get the latest item created by a specific user by CAML query	SPQuery query = new SPQuery();\nquery.Query = @"<Where><Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'>" + _id + @"</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";\nquery.RowLimit = 1;	0
533778	533767	How do you iterate through every day of the year?	for(DateTime date = begin; date <= end; date = date.AddDays(1))\n{\n}	0
31511841	31511158	SAP get Sales Orders BAPISDORDER_GETDETAILEDLIST	salesDocuments.setValue("VBELN", "0000001258")	0
466388	466352	How to obtain a property value on descendant class	public string Process(BaseClass bc, string propertyName)\n        {\n            PropertyInfo property =  bc.GetType().GetProperty(propertyName);\n            return (string)property.GetValue(bc, null);\n        }	0
25246359	25246213	How to save an image to the clipboard only knowing the images path	BitmapSource bitmapSource = new BitmapImage(new Uri("C:\\MyImages\\MyImage.jpg"));\nSystem.Windows.Clipboard.SetImage(bitmapSource);	0
14793489	14612330	Sorting the Child ItemSource in a Parent-Child Combobox ItemSource Binding	var dataOptions = new DataLoadOptions();\ndataOptions.AssociateWith<InventoryCategory>(ic => ic.InventoryLists.OrderBy(o => o.InventoryDescription));\ndb.LoadOptions = dataOptions;	0
4285140	4285114	How to write a line only once in a text file	bool patternwritten = false;\n        while ((line = file.ReadLine()) != null)\n                                {\n          if (line.IndexOf(line2,StringComparison.CurrentCultureIgnoreCase) != -1)\n                if( !patternwritten){\n                  dest.WriteLine("Pattern Name :" + line2);\n                  patternwritten = true;\n                }\n                dest.WriteLine("LineNo : " + counter.ToString() + " : " + line);\n                                    counter++;\n                                }\n                                file.BaseStream.Seek(0, SeekOrigin.Begin);\n                                    //(0, SeekOrigin.Begin);\n                                counter = 1;	0
10494340	10490956	Anything like, "foreach (Row x in table.Rows)", but for Calendar control days?	protected void Calendar1_SelectionChanged(object sender, EventArgs e)\n{\n    AddToDates(Calendar1.SelectedDate);\n}\n\nprivate void AddToDates(DateTime newDate)\n{\n    DateTime selecteddate;\n    ArrayList datelist;\n    if (ViewState["SelectedDates"] != null)\n    {\n        datelist = (ArrayList)ViewState["SelectedDates"];\n        for (int x = 0; x < datelist.Count; x++)\n        {\n            selecteddate = (DateTime)datelist[x];\n            Calendar1.SelectedDates.Add(selecteddate);\n        }\n    }\n    else\n    {\n        datelist = new ArrayList();\n    }\n    if (datelist.Contains(newDate))\n    {\n        Calendar1.SelectedDates.Remove(newDate);\n        datelist.Remove(newDate);\n    }\n    else\n    {\n        Calendar1.SelectedDates.Add(newDate);\n        datelist.Add(newDate);\n    }\n\n    ViewState["SelectedDates"] = datelist;\n}	0
5171952	5171462	How to retrieve all embedded document value using the official C# driver for MongoDB?	List<Question> list = new List<Question>();\nMongoServer _server = MongoServer.Create("mongodb://localhost");\nMongoDatabase _database = _server.GetDatabase("test");\nvar query = Query.And(Query.EQ("AnswerChoices._id", new ObjectId("4d6d336ae0f84c23bc1fae00")));\nMongoCollection<Question> collection = _database.GetCollection<Question>("Question");\nMongoCursor<Question> cursor = collection.Find(query);\n\nvar id = new ObjectId("4d6d336ae0f84c23bc1fae00");\nforeach (var q in cursor)\n{\n    var answerChoice = q.AnswerChoices.Single(x=> x.AnswerChoiceId == id);\n    list.Add(q);\n}	0
22418490	22417766	Is there a way to check for ambiguous methods in C# reflection?	// user invoked "foo -format json -url www.google.com\n// your code does something like:\nvar args = new[] { "format", "url" };\nvar matchingMethods = typeof(SomeType).Assembly.GetTypes()\n    .Where(t => typeof(ICommand).IsAssignableFrom(t))\n    .SelectMany(t => t.GetMethods())\n    .Where(m => StringComparer.OrdinalIgnoreCase.Equals(m.Name, "foo"))\n    .Where(m => {\n        var parameters = m.GetParameters();\n        var isValid = parameters.All(p => p.IsOptional || args.Contains(p.Name))\n            && args.All(a => parameters.Any(p.Name == a));\n        return isValid;\n    })\n    .ToArray();	0
27852307	27851959	Efficient way to insert into buffer	Buffer.BlockCopy	0
1453626	1453327	Relation between length and font-size of a string and width of a textbox	//Get this value from somewhere...\n        TextBox textBox = new TextBox();\n        int maxWidth = 10;\n        int extraSpace = 3;\n\n        //Create sample string\n        StringBuilder sb = new StringBuilder(maxWidth);\n        sb.Append('w', maxWidth);\n\n        //Measure text \n        Size size = TextRenderer.MeasureText(sb.ToString(), textBox.Font);\n\n        //Set width of TextBox to needed width\n        textBox.Width = size.Width + extraSpace;	0
10895904	10895756	How to access HTML control in C# code behind without "runat=server"?	runat="server"	0
342026	340285	Get dataset child rows in proper order	DataSet1 ds = new DataSet1();\n\n//load data\nDataSet1.ChildTable.SortExpression = "Order";\n\nDataSet1.ParentTableRow parentRow = ds.ParentTable.FindByID(1);\nDataSet1.ChildTableRow[] childRows = parentRow.GetChildTableRows();\nArray.Sort<DataSet1.ChildTableRow>(childRows, new ChildTableCoparer());\n//Enumerate fields is right order	0
1678485	1678473	How to share settings between different versions of the same software	if (!Properties.Settings.Default.Upgraded)\n  {\n    Properties.Settings.Default.Upgrade();\n    Properties.Settings.Default.Upgraded = true;\n    Properties.Settings.Default.Save();\n    Trace.WriteLine("INFO: Settings upgraded from previous version");\n  }	0
1967824	1967821	How to add value for Complex Dictionary?	IDictionary<string,Dictionary<string,string>> myDictDict = new Dictionary<string,Dictionary<string,string>>();\nDictionary<string,string> dict = new Dictionary<string, string>();\ndict.Add ("tom", "cat");\nmyDictDict.Add ("hello", dict);	0
8489010	8488989	Can I declare constant integers with a thousands separator in C#?	const int x = 1000 * 1000;	0
20456491	20456375	Extracting sub string with regexp	try {\n    Regex regexObj = new Regex(@"T\.m\([""|'](.+?)[""|']\)");\n    Match matchResults = regexObj.Match(subjectString);\n    while (matchResults.Success) {\n        var neededvalue = matchResults.Groups[1].Value;\n    } \n} catch (ArgumentException ex) {\n    // Syntax error in the regular expression\n}	0
21281341	21263063	check Model State of a property	var propertyToValidate = ModelState["PropertyName"];\nif(propertyToValidate==null || //exclude if this could not happen or not to be counted as error\n    (propertyToValidate!=null && propertyToValidate.Errors.Any())\n   )\n{\n    //Do what you want if this value is not valid\n}\n //Rest of code	0
24765154	24494055	Using Passive Authentication in IdentityServer with OWIN in MVC5	AuthenticationMode = AuthenticationMode.Passive	0
1521794	1514354	GridView Page in UpdatePanel dropping 1 row	ScriptManager.RegisterAsyncPostBackControl(gvComments);	0
21856114	21833102	VSTO Addin Text Content Control	private void InsertIntoBookmark(string bookmarkName, string text)\n{\n    if (Document != null && Document.Bookmarks.Exists(bookmarkName))\n    {\n        var range = Document.Bookmarks[bookmarkName].Range;\n        Document.Bookmarks[bookmarkName].Delete();\n        range.Text = text;\n\n        // replace bookmark\n        Document.Bookmarks.Add(bookmarkName, range);\n    }\n}	0
1965054	1964992	How to extract a URL from a 200 character string of words in C#, preferably using RegExp	using (StreamReader reader = new StreamReader(File.OpenRead("c:\\test.txt")))\n{\n    string content = reader.ReadToEnd();\n    string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";\n    MatchCollection matches = Regex.Matches(content, pattern);\n    foreach (Match match in matches)\n    {\n        GroupCollection groups = match.Groups;\n        Console.WriteLine("'{0}' repeated at position {1}",\n                          groups[0].Value, groups[0].Index);\n    }\n}	0
3921803	3833678	Using JSON.NET, how do I serialize these inherited members?	Data = myClass.GetHashCode()	0
332932	332851	how to control datagridview cursor movement in C#	public class dgv : DataGridView\n{\nprotected override bool ProcessDialogKey(Keys keyData)\n{\n    Keys key = (keyData & Keys.KeyCode);\n    if (key == Keys.Enter)\n    {\n        return this.ProcessRightKey(keyData);\n    }\n    return base.ProcessDialogKey(keyData);\n}\nprotected override bool ProcessDataGridViewKey(KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Enter)\n    {\n        return this.ProcessRightKey(e.KeyData);\n    }\n    return base.ProcessDataGridViewKey(e);\n}	0
18630867	18630831	c# how to solve a issue using substring	var result = filename.Split('_')[0];	0
17865419	17854406	Create a status bar in Xcode / Xamarin	Window.SetContentBorderThickness (24, NSRectEdge.MinYEdge);	0
32434533	32434301	How to store a list in client side in asp.net	Session["stg"] = stg;\n\nvar list = (List<Stages>)Session["stg"];	0
9455909	9455668	asp.net web service : sending json within json	var TheData = JSON.stringify(MyObject).replace(new RegExp('\"', 'g'),'\\"');	0
13864790	13864666	issue with regex in C#	var text = File.ReadAllText(@"E:\check.txt");\nvar match = Regex.Match(text, @"(?s)<begin>.*?</end>").Value;	0
29990231	29989429	Programmatically inherit a table in C# windows form application	foreach(DataTable table in Tables)\n{\n    MyChildControl childControl = new MyChildControl();\n    childControl.Confiure(table); // Sets the data for the control.\n    layoutPanel.Controls.Add(childControl); // This call varies by UI method and what layoutPanel you are using\n}	0
25641060	25640446	C# WinForms, Adding tabs to a tab control, then adding a control to each tab programmatically	foreach (TabPage tabpage in tabCont.TabPages)\n{\n    EnergyTable table = new EnergyTable();\n    tabpage.Controls.Add(table);\n}	0
10049510	10049466	Custom Sorting of List<T>	events.OrderBy (e => e.Time == 0).ThenBy (e => e.Time);	0
12282645	12282487	How to prevent an infinite loop in ASP.net	Thread thread = new Thread( RunPotentiallyTooLongCode );\nthread.Start();\nBoolean success = thread.Join( 1000 );\nif( !success ) thread.Abort();	0
4103594	4096784	Problem in setting Checked property of radio button	protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Bind GridView here }	0
34536962	34536767	Casting ListBox.SelectedItems in c#	rightBox.Items.AddRange(leftBox.SelectedItems.Cast<object>().ToArray());	0
16652699	16652624	How to get XML namespace?	var textReader = new XmlTextReader(path);\nwhile(reader.NodeType != XmlNodeType.Element) textReader.Read();\nif (textReader.NamespaceURI == "http://www.portalfiscal.inf.br/nfe")\n{\n  //...\n}	0
7968390	7968252	Moderate changing of a number	IEnumerable<string> GetVariations(string input, int limit,char[] characters)\n{\n  if(limit==0)\n  {\n    yield return input;\n    yield break;\n  }\n  if(limit>input.Length)//Disallows fewer than `limit` changes.\n  {\n    yield break;\n  }\n  string remainder=input.SubString(1);\n  foreach(char c in characters)\n  {\n    int remainingLimit;\n    if(c==input[0])\n      remainingLimit=limit;\n    else\n      remainingLimit=limit-1;\n    foreach(string variedRemainder in GetVariations(remainder,remainingLimit,characters)\n      yield return c+variedRemainder;\n  }\n}\n\nList<int> GetVariations(int input, int count)\n{\n  return GetVariations(input.ToString(),count,new char[]{'0',...,'9'}).Select(int.Parse).ToList();\n}	0
26455499	26455061	How to create a new record to a junction table	public class Job\n{\n    //job\n    public int JobId { get; set; }\n    public int? JobNumber { get; set; }\n    public string JobName { get; set; }\n\n    [ForeignKey("CustomerPMId")] \n    public CustomerEmployee CustomerPM { get; set; }\n    [ForeignKey("CustomerSuperintendentId")]        \n    public CustomerEmployee CustomerSuperintendent { get; set; }\n}	0
22151357	22151037	How to extract href tag from a string in C#?	var hrefLink = XElement.Parse("<th><a href=\"Boot_53.html\">135 Boot</a></th>")\n                       .Descendants("a")\n                       .Select(x => x.Attribute("href").Value)\n                       .FirstOrDefault();	0
16237502	16235999	Detect CMYK from stream using System.Drawing	public static bool IsCMYK(Image image)\n{\n     var flags = (ImageFlags)image.Flags;\n     if (flags.HasFlag(ImageFlags.ColorSpaceCmyk) || flags.HasFlag(ImageFlags.ColorSpaceYcck))\n     {\n         return true;\n     }\n\n     const int PixelFormat32bppCMYK = (15 | (32 << 8));\n     return (int)image.PixelFormat == PixelFormat32bppCMYK;\n}	0
17524534	17524421	ios webview - how to check notifications when the app is not running	- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {\n   NSDictionary *remoteNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];\n    if (remoteNotif) {\n       /* handle the notification.\n    }\n}	0
29601084	29600891	How to use dependency injection for inherited class?	public class DiscoverController  : BaseApiController\n{\n   readonly IDiscoverService _discoverService;\n   readonly IAccessService _accessService;\n\n   public DiscoverController(IDiscoverService discoverService,IAccessService accessService)  : base(accessService)\n   {\n      _discoverService = discoverService;\n   }\n}	0
4723461	4723447	find out url from given paragraph using regex c#	public string[] ExtractURLs(string str)\n{\n    // match.Groups["name"].Value - URL Name\n    // match.Groups["url"].Value - URI\n    string RegexPattern = @"<a.*?href=[""'](?<url>.*?)[""'].*?>(?<name>.*?)</a>"\n\n    // Find matches.\n    System.Text.RegularExpressions.MatchCollection matches\n        = System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n    string[] MatchList = new string[matches.Count];\n\n    // Report on each match.\n    int c = 0;\n    foreach (System.Text.RegularExpressions.Match match in matches)\n    {\n        MatchList[c] = match.Groups["url"].Value;\n        c++;\n    }\n\n    return MatchList;\n}	0
14828871	14828800	How I can fill the DropDownList in the page_load	DataBind()	0
23350750	23350067	Making a void dynamic	var elementCopy = element;\n    ...\n    app[i].Click += (sender,evt) => run(elementCopy,dir);	0
1853174	1853043	How can I send input to Visual Studio using Windows API	SendKeys.SendWait("^C"); //CTRL+C\nvar selectedText = Clipboard.GetText();\nvar newText = Replace(selectedText);\nSendKEys.SendWait("^V"); //CTRL+V	0
10752640	10735296	Databind variable from code to designer object	private string firstString; // this is your field.\n\n        public string FirstString // this is your property wrapper for the above field.\n        {\n            get { return firstString; }\n            set { firstString = value; }\n        }	0
6183839	6183621	Copying data of only few columns to one more data table	DataTable newTable = oldTable.DefaultView.ToTable(false, "ColumnName1", "ColimnName2", "ColimnName3", "ColimnName4", "ColimnName5");	0
269100	266497	MSHTML: How can you clear the undo / redo buffer of MSHTML	//Extract undo manager\n    if (m_undoManager == null) \n    {\n      IServiceProvider serviceProvider = Document as IServiceProvider;\n\n      Guid undoManagerGuid = typeof(IOleUndoManager).GUID;\n      Guid undoManagerGuid2 = typeof(IOleUndoManager).GUID;\n      IntPtr undoManagerPtr = ComSupport.NullIntPtr;\n\n      int hr = serviceProvider.QueryService(ref undoManagerGuid2, ref undoManagerGuid, out undoManagerPtr);\n      if ((hr == HRESULT.S_OK) && (undoManagerPtr != ComSupport.NullIntPtr))\n      {\n        m_undoManager = (IOleUndoManager)Marshal.GetObjectForIUnknown(undoManagerPtr);\n        Marshal.Release(undoManagerPtr);\n      }\n    }\n\n    //And to clear the stack \n    m_undoManager.Enable(true);\n    Application.DoEvents();	0
8478912	8478752	Can I create a custom implict type cast?	if (typeof(Money).IsAssignableFrom(typeof(T))\n{\n    // special handling required to convert decimal to money\n    castedValue = new Money() { Value = value };  // ? best guess\n}\nelse\n{\n    castedValue =(T)value;\n}	0
20291948	20290046	Algorithm to find the shortest path in a matrix	1 1\n0 1	0
29836067	29825597	IronPython w/ C# - How to Read Values of Python Variables	var engine = Python.CreateEngine();\n//Set up the folder with my code and the folder with struct.py.\nvar searchPaths = engine.GetSearchPaths();\nsearchPaths.Add(@"C:\ACodeFolder");\nsearchPaths.Add(@"C:\tools\python\lib");\nengine.SetSearchPaths(searchPaths);\n\nvar mainfile = @"C:\ACodeFolder\mainfile.py";\nvar scope = engine.CreateScope();\nengine.CreateScriptSourceFromFile(mainfile).Execute(scope);\n\nvar expression = "my_variable";\nvar result = engine.Execute(expression, scope);\n//"result" now contains the value of my_variable".	0
1225992	1225945	How to release a handle through C#?	[System.Runtime.InteropServices.DllImport("Kernel32")]\nprivate extern static Boolean CloseHandle(IntPtr handle);	0
15618505	15577389	A simple UIPickerView in MonoTouch (Xamarin)?	public partial class StatusPickerPopoverView : UIViewController\n{\n    public StatusPickerPopoverView (IntPtr handle) : base (handle)\n    {\n    }\n\n    public override ViewDidLoad()\n    {\n        base.ViewDidLoad();\n\n        pickerStatus = new UIPickerView();\n        pickerStatus.Model = new StatusPickerViewModel();\n    }\n\n    public class StatusPickerViewModel : UIPickerViewModel\n    {\n        public override int GetComponentCount (UIPickerView picker)\n        {\n            return 1;\n        }\n\n        public override int GetRowsInComponent (UIPickerView picker, int component)\n        {\n            return 5;\n        }\n\n        public override string GetTitle (UIPickerView picker, int row, int component)\n        {\n\n            return "Component " + row.ToString();\n        }\n    }\n}	0
14362828	14362563	Inserting a TAB space into a TextBox	TextBox_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)\n{\n      if (e.KeyCode == Keys.Tab)\n      {\n          e.Handled = true;\n          SendKeys(^{TAB});\n      }\n}	0
18308772	18269914	Transistion from clockwise to counter-clockwise modes smoothly using WPF storyboard	private void reverseButton_Click(object sender, RoutedEventArgs e)\n{\n    Storyboard sbActive = bRotateClockwisely ? clockwiseStoryboard : counterClockwiseStoryboard;\n    Storyboard sbPaused = bRotateClockwisely ? counterClockwiseStoryboard : clockwiseStoryboard;\n\n\n    //I want the other storyboard can seek to where the animation is paused.\n    dProgress = sbActive.GetCurrentProgress();\n    dProgress = 1.0 - dProgress;\n\n    sbActive.Stop();           \n\n    sbPaused.Begin();\n    sbPaused.Seek(new TimeSpan((long)(duration.Ticks * dProgress)), TimeSeekOrigin.BeginTime);\n\n    bRotateClockwisely = !bRotateClockwisely;            \n}	0
12309880	12309767	How to determine whether my Azure connection string is valid	container.CreateIfNotExists(new BlobRequestOptions {\n    RetryPolicy = RetryPolicies.NoRetry });	0
1851946	1851937	How to write a regular expression to match a set of values?	(4[8-9]|5[0-7])+(32|10|13)48(32|10|13)111981066060	0
32477011	32476929	Listbox Data Binding Windows Phone	listbox.ItemsSource = List;	0
5325478	5324924	Adding values in web config dynamically? How To + Best way	public void saveIdentity(string username, string password, bool impersonate)\n    {\n        Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");\n        IdentitySection identitySection = (IdentitySection)objConfig.GetSection("system.web/identity");\n        if (identitySection != null)\n        {\n            identitySection.UserName = username;\n            identitySection.Password = password;\n            identitySection.Impersonate = impersonate;\n        }\n    objConfig.Save();\n}	0
14995392	14995351	.NET interface/constraint for object that implements certain operators	interface IAddable { void Add(object item); }\n...\npublic void TestAdd<T>(T t1, T t2) where T : IAddable\n{\n   return t1.Add(t2);\n}	0
10571865	10571822	How to remove the leftmost bit and add bit in its rightmost bit	int i=0xbf;\nint j=(i<<1) & 0xff;	0
6336667	6327118	Redirecting to a custom login page using Windows Identity Foundation	protected void Application_Start()\n{\n    AreaRegistration.RegisterAllAreas();\n\n    RegisterRoutes(RouteTable.Routes);\n\n    FederatedAuthentication.ServiceConfigurationCreated += new EventHandler<Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs>(FederatedAuthentication_ServiceConfigurationCreated);   \n}\n\n    void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)\n    {\n        var m = FederatedAuthentication.WSFederationAuthenticationModule;\n        m.RedirectingToIdentityProvider += new EventHandler<RedirectingToIdentityProviderEventArgs>(m_RedirectingToIdentityProvider);\n    }\n\n    void m_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)\n    {\n        var sim = e.SignInRequestMessage;\n        sim.HomeRealm = "Google";\n    }	0
12439406	12431112	How can I add a button to the WPF caption bar while using custom window chrome?	shell:WindowChrome.IsHitTestVisibleInChrome="True"	0
17058233	17058182	How to format double without fractional part	double value = 100233;\nstring a = (value.ToString("N0", CultureInfo.InvariantCulture));	0
8326650	8326614	Highlighting a TreeNode without using foreach, possible with LINQ?	treeView.Nodes.FirstOrDefault<TreeNode>(node => node.Text == text);	0
17270345	17270256	How to format date fetched by JQuery?	var s='2013-05-30T10:05:00+05:30';\nvar time_vl=s.split('T')[1].split('+')[0];	0
1316181	1316178	How can I position my userControl to the top right corner of my MasterPage?	#control {\n    position: absolute;\n    right: 0px;\n    top: 0px;\n}	0
11262196	11262094	Regex for parsing CSV	Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\MyFile.csv")\n\nReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited\n\nDim MyDelimeters(0 To 0) As String\nReader.HasFieldsEnclosedInQuotes = False\nReader.SetDelimiters(","c)\n\nDim currentRow As String()\nWhile Not Reader.EndOfData\n    Try\n        currentRow = Reader.ReadFields()\n        Dim currentField As String\n        For Each currentField In currentRow\n            MsgBox(currentField)\n        Next\n    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException\n        MsgBox("Line " & ex.Message &\n        "is not valid and will be skipped.")\n    End Try\nEnd While\nEnd Using	0
15570584	15569925	Duplicate row removal	from person in Persons\njoin customer in Customers on person.BusinessEntityID equals customer.PersonID\njoin salesOrderHeader in SalesOrderHeaders on customer.CustomerID equals salesOrderHeader.CustomerID\nwhere salesOrderHeader.SubTotal > 1000\njoin address in Addresses on salesOrderHeader.BillToAddressID equals address.AddressID\nwhere address.City == "Melton"\ngroup salesOrderHeader by new { person.FirstName, person.LastName } into g //new\nselect new {\n                g.Key.FirstName,\n                g.Key.LastName,\n                SubTotal = g.Sum(salesOrderHeader => salesOrderHeader.SubTotal),\n            address.City\n       }	0
17572121	17571949	find missing number from list of long	IEnumerable<long> GetMissingNumbers(long rangeStart, long rangeEnd, \n                                    IEnumerable<long> numbers)\n{\n    var existingNumbers = new HashSet<long>(numbers);\n\n    for(long n = rangeStart;n<=rangeEnd;n++)\n    {\n        if(!existingNumbers.Contains(n))\n            yield return n;\n    }\n}	0
10283250	10283237	C#.net can't assign null to a variable in an inline if statement	myEmployee.age = conditionMet ? someNumber : (int?)null;	0
3328951	3328915	Slow performance in reading from stream .NET	// Make sure the stream gets closed once we're done with it\nusing (Stream stream = resp.GetResponseStream())\n{\n    // A larger buffer size would be benefitial, but it's not going\n    // to make a significant difference.\n    while ((read = stream.Read(buffer, total, 1000)) != 0)\n    {\n        total += read;\n    }\n}	0
3651854	3651746	XML is displayed in one line problem	XmlDocument doc = new XmlDocument();\n  doc.LoadXml(xmlParam.Value.ToString());\n\n  using (StreamWriter wIn = new StreamWriter(xmlFile, false))\n  using (XmlTextWriter wr = new XmlTextWriter(wIn))\n  {\n    wr.Formatting = Formatting.Indented;\n    doc.WriteTo(wr); \n  }	0
27246457	27246391	Set foreground color of button	btn.Foreground=new SolidColorBrush(Colors.Yellow);	0
14351443	14351267	Change focus control when press enter key	protected override bool ProcessKeyPreview(ref Message m)\n{\n    if (m.Msg == 0x0100 && (int)m.WParam == 13)\n    {\n        this.ProcessTabKey(true);\n    }\n    return base.ProcessKeyPreview(ref m);\n}	0
4225409	4225281	How to retrieve the parent control and its children controls - Winforms C# 2	internal static IEnumerable<Control> EnumereAllControls(Control parentControl)\n{\n    yield return parentControl;\n\n    foreach (Control subControl in parentControl.Controls)\n    {\n        foreach (Control c in EnumereAllControls(subControl))\n            yield return c;\n    }\n}	0
24040730	24040265	Accessing applicataion bar from non UI class windows phone 8	private void myPopup_Close(object sender, System.EventArgs e)\n{\n   // get current Page\n   var currentPage = ((App.Current as App).RootVisual as PhoneApplicationFrame).Content as PhoneApplicationPage;\n    // hide popup\n    currentPage.ApplicationBar.IsVisible = true;\n}	0
18134715	18134681	Using LINQ: How To Return Array Of Properties from a Class Collection?	return list.Select(p=>p.TheProperty).ToArray()	0
31572613	31572074	How to get data from Drag 'n Dropped file that is not saved on disk	Private Sub ubFilepath_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ubFilepath.DragDrop\n    Try\n        If e.Data.GetDataPresent(DataFormats.Text) Then\n            Me.ubFilepath.Text = e.Data.GetData("Text")\n        ElseIf e.Data.GetDataPresent(DataFormats.FileDrop) Then\n            Dim fileNames() As String\n            Dim MyFilename As String\n            fileNames = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())\n            MyFilename = fileNames(0)\n            Me.ubFilepath.Text = MyFilename	0
21977142	21977101	Is there a way to abbreviate a custom class type declaration?	public class DD : Dictionary<string,Dictionary<int,myClass>>  { }	0
4213574	4213549	Adding a list view item to a listview in WPF	ListViewItem lvi = new ListViewItem();\n\nMyListView.Items.Add(lvi);	0
22400713	22400658	Cancel button in asp.net referal to aspx file	CausesValidation="False"	0
3464671	3464635	Deep Copy with Array	A[] array2 = array1.Select (a =>(A)a.Clone()).ToArray();	0
7790670	7790632	Microsoft Access WebBrowser Control	Dim objCollection As Object\nDim IE As Object\n\n' Create InternetExplorer Object\nSet IE = CreateObject("InternetExplorer.Application")\n\n' Send the form data To URL As POST binary request\nIE.Navigate "https://mywebpage.com"\n\n' Wait while IE loading...\nDo While IE.Busy\n    Application.Wait DateAdd("s", 1, Now)\nLoop\n\nSet objCollection = IE.document.GetElementById("ITEMID")\nobjCollection(0).Value = "value"	0
30165198	30165146	Delete 1st Object From List C#	var todel = newpa.ExistingPas.FirstOrDefault();\n  newpa.ExistingPas.Remove(todel);\n  //than add list back to session object if you want updated list	0
15582269	15582017	Reading out a table in C# with HtmlAgilityPack	string file = File.ReadAllText("a.html"); // gets the html\n\nCQ dom = file; // initializes csquery\nCQ td = dom["td"]; // get all td files\n\ntd.Each((i,e) => { // go through each\n    if (e.FirstChild != null) // if element has child (font)\n    {\n        if (e.FirstChild.NodeType != NodeType.TEXT_NODE) // ignore text node\n        {\n            if (e.FirstChild.InnerText == "1") // if number is 1\n            {\n                Console.WriteLine(e.NextElementSibling.InnerText); // output the text\n            }\n            if (e.FirstChild.InnerText == "8") // etc etc\n            {\n                Console.WriteLine(e.NextElementSibling.InnerText);\n            }\n        }\n    }\n\n});\n\nConsole.ReadKey();	0
3118371	3118334	Testing equality of DataColumn values in C#	row["Foo"].Equals(row["bar"])	0
6871862	6871347	How do I trigger or supress the display of Windows Virtual Keyboard	var virtualKeyboard = new System.Diagnostics.Process();\nvirtualKeyboard = System.Diagnostics.Process.Start("osk.exe"); // open\nvirtualKeyboard.Kill(); // close	0
24578853	24575500	Is there a way to use `dynamic` in lambda expression tree?	public virtual Expression<Func<TSubclass, object>> UpdateCriterion()\n{\n    var param = Expression.Parameter(typeof(TSubclass));\n    var body = Expression.Convert(Expression.Property(param, "ID"), typeof(object));\n\n    return Expression.Lambda<Func<TSubclass, object>>(body, param);\n}	0
634081	633985	Visual studio addin - finding current solution folder path	public String SolutionPath()\n    {\n        return Path.GetDirectoryName(_applicationObject.Solution.FullName);\n    }	0
11896832	11895916	Compare a selected list view item with a font style	ListViewItem item = lvwMessages.SelectedItems[0];\n            if(item.Font.Bold)\n\n                {\n                    lvwMessages.SelectedItems[0].Font = new Font(lvwMessages.Font, FontStyle.Regular);\n                }	0
7318401	6928174	Reference to a loaded Assembly	AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n\nstatic Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n    foreach (Assembly anAssembly in AppDomain.CurrentDomain.GetAssemblies())\n        if (anAssembly.FullName == args.Name)\n            return anAssembly;\n    return null;\n}	0
14680374	14680308	How do I get lazy loading with PLINQ?	var next = source.AsParallel()\n              .WithMergeOptions(ParallelMergeOptions.NotBuffered)\n              .Select(i => ExpensiveCall(i));	0
24745215	24745115	Use a single method to return data with different types	public T GetFromNode<T>(string xpathOfNode)\n{\n    XPathNavigator nodeNav = ipFormNav.SelectSingleNode(xpathOfNode, nsManager);\n    return (T)nodeNav.ValueAs(typeof(T));\n}	0
5344256	5344195	Converting from closed generics to open generics	public void Bla<T>() where T:class\n{\nUnityContainer.RegisterType<Func<IDataContextAdapter, IRepository<T>>>(\n    new InjectionFactory(c => \n                    new Func<IDataContextAdapter, IRepository<T>>(\n                        context => new Repository<T>(context))\n        )\n );\n}	0
29647237	29645844	Caching using dictionaries in a factory class	public class VmFactory\n{\n   private static ConcurrentDictionary<int, IClientCustomer> clientCustomers = \n        new ConcurrentDictionary<int, IClientCustomer>();\n\n    public IClientCustomer GetCustomerWrapper(ICustomer cust)\n    {\n       IClientCustomer clientCustomer;\n\n       if (!clientCustomers.ContainsKey(cust.ID))\n        {\n            clientCustomer = new ClientCustomer(cust);\n            clientCustomers.TryAdd(cust.ID, clientCustomer);\n        }\n        else\n        {\n            clientCustomer = clientCustomers[cust.ID];\n        }\n\n          return clientCustomer;\n   }\n}	0
12412669	12412144	How to implement SQL Server paging using C# and entity framework?	int skip =0;\nint take = 1000;\nfor (int i = 0; i < 150; i++)\n{\nvar rows = (from x in Context.Table\n            select x).OrderBy(x => x.id).Skip(skip).Take(take).ToList();\n\n//do some update stuff with rows\n\nskip += 1000;\n}	0
29291520	29291446	Managing and manipulating Data in tables	SELECT\n    SUM(Price)\nFROM\n    Items\n      INNER JOIN ProductNumber ON Items.Product_NumberREF = ProductNumber.ProductNumber	0
623478	623459	Calculate the last DayOfWeek of a month	static DateTime LastDayOfWeekInMonth(DateTime day, DayOfWeek dow)\n{\n    DateTime lastDay = new DateTime(day.Year, day.Month, 1).AddMonths(1).AddDays(-1);\n    DayOfWeek lastDow = lastDay.DayOfWeek;\n\n    int diff = dow - lastDow;\n\n    if (diff > 0) diff -= 7;\n\n    System.Diagnostics.Debug.Assert(diff <= 0);\n\n    return lastDay.AddDays(diff);\n}	0
22185866	22185804	Using spatial data methods in LINQ	System.Data.Entity	0
9027288	9026932	LINQ to DataSet Group By Multiple Columns - Method Syntax	var query = orders.AsEnumerable()   \n              .GroupBy(t => new {CountryCode= t.Field<string>("CountryCode"),\n                                 CustomerName=t.Field<string>("CustomerName"),\n                           (key, group)=> new {CountryCode = key.CountryCode,CustomerName=key.CustomerName})\n.Select(t => new {t.CountryCode, t.CustomerName});	0
4172968	1436713	Enable file logging for log4net from code instead of from configuration	Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();\nhierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/\n\nFileAppender fileAppender = new FileAppender();\nfileAppender.AppendToFile = true;\nfileAppender.LockingModel = new FileAppender.MinimalLock();\nfileAppender.File = Server.MapPath("/") + "log.txt";\nPatternLayout pl = new PatternLayout();\npl.ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n";\npl.ActivateOptions();\nfileAppender.Layout = pl;\nfileAppender.ActivateOptions();\n\nlog4net.Config.BasicConfigurator.Configure(fileAppender);\n\n//Test logger\nILog log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\nlog.Debug("Testing!");	0
22514308	22514010	how to store a part of dropdownlist text in a dynamically generated property	string DropDownText = "EhsanSajjad/03123009099";\n\nstring[] temp = DropDownText.Split('/');\n\nstring personName  = temp[0];\n\nstring CellNumber = temp[1];	0
18701612	18701576	handling multiple button actions in one action in C#	private void button_Click(object sender, EventArgs e)\n{\n    Button button = (Button)sender;\n    string text = button.Name.Substring("button".Length);\n    synthesizer.Speak(text);\n}	0
4242948	4242819	Getting the path of a file using fileupload control	protected void Button1_Click(object sender, EventArgs e)\n{\n    string filePath,fileName;\n    if (FileUpload1.PostedFile != null)\n    {\n        filePath = FileUpload1.PostedFile.FileName; // file name with path.\n        fileName = FileUpload1.FileName;// Only file name.\n    }\n}	0
9319560	9166516	ADAM binding using windows authentication?	var context = new DirectoryContext(DirectoryContextType.DirectoryServer, "server:389");\nvar schema = ActiveDirectorySchema.GetSchema(context);	0
5524834	5524734	How to display a registry key(s) in a text box C#	var runs = Registry.LocalMachine.OpenSubKey(\n   @"Software\Microsoft\Windows\CurrentVersion\Run");\n\nvar valueNames = runs.GetValueNames();\n\nvar values = new List<object>();\nforeach (var valueName in valueNames)\n{\n    values.Add(runs.GetValue(valueName));\n}	0
18277346	18276836	Programmatically inserting a new user into an aspnet membership schema	MembershipUser newUser = Membership.CreateUser("username", "password", "email@a.com");	0
27675062	27674595	count daily visitor of a website in c#	private void Form1_Load(object sender, EventArgs e)\n    {\n        // number of visitor\n        int totalNumbers = 0;\n        // Database\n        string dbConStr = "Server=.\\sqlexpress;Database=Test;Integrated Security=true;";\n         System.Data.SqlClient.SqlConnection sqlConnection1 = \n            new System.Data.SqlClient.SqlConnection(dbConStr);\n\n        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();\n        cmd.CommandType = System.Data.CommandType.Text;\n        cmd.CommandText = "INSERT CounterTable (totalNumbers, day) VALUES (@totalNumbers, getdate())";\n        cmd.Parameters.Add("totalNumbers",SqlDbType.Int).Value = totalNumbers;\n        cmd.Connection = sqlConnection1;\n\n        sqlConnection1.Open();\n        cmd.ExecuteNonQuery();\n        sqlConnection1.Close();\n    }	0
12849821	12849805	Read a file and replace test after a certain word	Regex rgx = new Regex(@"Open [^\s]+");\nstring result = rgx.Replace(text, newValue);\nFile.WriteAllText(activeSaveFile, result );	0
10881044	10880899	How to map fields in an object to another dynamically?	var config = new DefaultMapConfig().MatchMembers((m1, m2) => "Person" + m1 == m2);\nObjectMapperManager.DefaultInstance\n                   .GetMapper<Person, PersonRule>(config)\n                   .Map(person, personRule);	0
11020380	11018237	Open Excel application without new workbook	app.ActiveWorkbook.Close(false);\napp.visible = true;	0
5747017	5746963	C# program that replaces even numbers with the word even	var num = new List<string>();\nfor (int n = 0; n < 101; n++)\n{\n   num.Add(n % 2 == 0 ? "EVEN" : n.ToString());\n}	0
850875	850712	Iterate through a ControlCollection from a CreateUserWizardStep	IEnumerable<T> FindControls<T>(Control parent) where T : Control {\n   T t = parent as T;\n   if (t != null) yield return t;\n\n   foreach (Control c in parent.Controls) {\n      foreach (var c2 in FindControls<T>(c)) yield return c2;\n   }\n}	0
15560707	15557379	Connecting to RavenDb via. username and password	new DocumentStore\n{\n   Url = "http://your-server:8080",\n   DefaultDatabase = "your-db",\n   Credentials = new NetworkCredentials("foo", "bar");\n}	0
30234830	30234626	Get Start Date and End date for certain month count	int months = 14;\n    int currentYear = DateTime.Now.Year;\n\n    DateTime firstDate = new DateTime(currentYear, 1, 1);\n    DateTime lastDate = firstDate.AddMonths(months - 1);\n\n    var lastMonthDays = DateTime.DaysInMonth(lastDate.Year, lastDate.Month);\n    lastDate = lastDate.AddDays(lastMonthDays - 1);	0
25073467	25073020	How to convert List<T> to an Object	SerializedProperty myCustomList = serializedObject.FindProperty ("myCustomList");\n\n    for (int i = 0; i < myCustomList .arraySize; i++)\n    {\n        SerializedProperty elementProperty = myCustomList.GetArrayElementAtIndex(i);\n\n        //Since this the object is not UnityEngine.Object you can not convert them the unity way.  The compiler can determine the type that way so.....\n\n       MyCustomList convertedMCL = elementProperty.objectReferenceValue as System.Object as MyCustomList;\n    }	0
26761061	26760967	Change property name for client output	var displayNameAttribute = property.GetCustomAttributes\n                                    (typeof(DisplayNameAttribute), false)\n                                    .FirstOrDefault() as DisplayNameAttribute;\n\nstring displayName = displayNameAttribute != null \n                         ? displayNameAttribute.DisplayName \n                         : property.Name;	0
29042696	29020030	WPF Open With Menu	Process.Start("rundll32.exe", string.Format("shell32.dll,OpenAs_RunDLL {0}", somefile.ext));	0
30013029	30012584	how to export records in multiple csv files?	If (dt.Columns.Count == 0)\n{\n    for (int i = 0; i < columns.Length; i++)\n    {\n    dt.Columns.Add(columns[i], typeof(string));\n    }\n}	0
3609288	3609248	dataset top n rows in c#	dt.Rows.Cast<System.Data.DataRow>().Take(n)	0
14772457	14772286	Return one element from where-clause or the first one	var userProfile = context.UserProfiles.Where(up => up.UserId == userId)\n                       .OrderByDescending(up => up.IsActive).FirstOrDefault();	0
22755742	22754656	How to force a certain Event sequence	public partial class MainPage : PhoneApplicationPage\n{\n    private List<EventHandler<CancelEventArgs>> listOfHandlers = new List<EventHandler<CancelEventArgs>>();\n\n    private void InvokingMethod(object sender, CancelEventArgs e)\n    {\n        for (int i = 0; i < listOfHandlers.Count; i++) \n            listOfHandlers[i](sender, e);\n    }\n\n    public event EventHandler<CancelEventArgs> myBackKeyEvent\n    {\n        add { listOfHandlers.Add(value); }\n        remove { listOfHandlers.Remove(value); }\n    }\n\n    public void AddToTop(EventHandler<CancelEventArgs> eventToAdd)\n    {\n        listOfHandlers.Insert(0, eventToAdd);\n    }\n\n    public MainPage()\n    {\n        InitializeComponent();\n        this.BackKeyPress += InvokingMethod;\n        myBackKeyEvent += (s, e) => { MessageBox.Show("Added first"); e.Cancel = true; };\n        AddToTop((s, e) => { MessageBox.Show("Added later"); });\n    }\n}	0
23891799	23891148	How to calculate interval between a group of dates?	Total Users: 5\nTotal Time Avg. Session : 7.4	0
9892841	9892790	Deleting while iterating over a dictionary	myDictionary.Remove(key)	0
7018377	7018327	Create a custom TextBox where alredy contain a validation function	public class MyTextBox : TextBox\n{\n     System.Text.RegularExpressions.Regex regex = newSystem.Text.RegularExpressions.Regex("[^0-9.-]+"); \n     protected override void OnPreviewTextInput(TextCompositionEventArgs e)\n     {\n        e.Handled = !regex.IsMatch(e.Text);\n     }\n}	0
4167256	4167136	Datagrid View Button repeat	void CreateDeleteColumn()\n{            \n    bcol = new DataGridViewButtonColumn();\n    bcol.HeaderText = "Action ";\n    bcol.Text = "Delete";\n    bcol.Name = "deleteUserButton";\n    bcol.UseColumnTextForButtonValue = true;\n\n    UsersView.Columns.Add(bcol);\n}	0
9453177	9452063	How to add margin to WPF TabControl tabs?	public class MyTabControl : TabControl\n{\n    public override void OnApplyTemplate()\n    {\n        base.OnApplyTemplate();\n\n        var panel = Template.FindName("HeaderPanel", this) as FrameworkElement;\n\n        if(panel != null)\n        {\n            panel.Margin = new Thickness(20,2,2,2);\n        }\n    }\n}	0
11475865	11475831	c# - Do you need a DataTable to retreive data from a DataAdapter?	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
30532319	30531392	Add Items metroTabControl	Add Tab	0
25346758	25346713	sorting even numbers in a string then adding to a listbox	public string sortParity()\n           {\n              string userInput = TextBox1.Text;\n              string[] numberArray = userInput.Split(',');\n              foreach (string i in numberArray)\n              {\n               int x = Int32.Parse(i);\n\n                 if (x % 2 == 0){\n               ListBox1.Items.Add(x);\n             } \n                else {\n           ListBox2.Items.Add(x);\n        }\n          }\n      }	0
6347381	6347323	Deploy C# application for offline computer	setup.exe	0
12097032	12095965	Mongodb: How can I check if a point is contained in a polygon?	{ loc : [ 50 , 30 ] }	0
25989985	25989375	Is there any way to change the Color in SetPixel thickness?	Bitmap bm;\n\nGraphics g = Graphics.FromImage(bm);\netc\ng.FillEllipse(....);\netc\ng.Dispose();	0
30519344	30515255	How to detect the line of sight of a person using kinect?	Joint HeadJoint = this.bodies[faceIndex].Joints[JointType.Head];\nColorSpacePoint colorPoint = this.coordinateMapper.MapCameraPointToColorSpace(HeadJoint.Position);\nPoint HeadPoint = new Point(colorPoint.X, colorPoint.Y);\nPoint GazePoint = new Point(HeadPoint.X - Math.Sin((double)yaw * 0.0175) * 600, HeadPoint.Y - Math.Sin((double)pitch * 0.0175) * 600);\ndrawingContext.DrawLine(new Pen(System.Windows.Media.Brushes.Yellow, 5), HeadPoint, GazePoint);\ndrawingContext.DrawEllipse(System.Windows.Media.Brushes.LightBlue, null, HeadPoint, 70, 70);	0
27306849	27306685	Xamarin - clearing ListView selection	((ListView)sender).SelectedItem = null;	0
17044704	16812580	How can I do this with one QueryOver statement	var sessions = results.Select(cbtAppointmentDto => Session.QueryOver<TestSession>()\n                         .Where(x => x.SessionName == cbtAppointmentDto.ExamSeriesCode)\n                         .FutureValue()).ToOList();\n\nfor (int i = 0; i < sessions.Count; i++)\n{\n    var session = sessions[i].Value;\n    if (session != null)\n    {\n        results[i].TestStartDate = session.TestsStartDate;\n        results[i].TestEndDate = session.TestsEndDate;\n    }\n}	0
11894954	11894713	Highlighting User Defined Keywords in RichTextBox	int pointer = 0;\nint index = 0;\nstring keyword = "txtComKeyword1";\n\nwhile (true)\n{\n    index = richComResults.Text.IndexOf(keyword, pointer);\n    //if keyword not found\n    if (index == -1)\n    {\n        break;\n    }\n    richComResults.Select(index, keyword.Length);\n    richComResults.SelectionFont = new System.Drawing.Font(richComResults.Font, FontStyle.Bold);\n    pointer = index + keyword.Length;\n}	0
251364	251307	Changing the name in the header for a resource handler in C#	context.Response.AddHeader("content-disposition", "attachment; filename=" + resource);	0
33816860	33816490	How do I check if a file exists in a Windows Universal App	StorageFolder docs = KnownFolders.DocumentsLibrary;\nStorageFile file = docs.TryGetItemAsync("testFiles\\testFile.docx");	0
13274669	13273855	Converting string to ToolStripMenuItem	var m = menuStrip1.Items.Find(menuItem.CodeName, true);\nvar o = m.ToList();\nforeach (var p in o)\n{\n    p.Visible = false;\n}	0
12999896	12999256	asp gridview Print	function printItn() {\n        //you can put your contentID which is you want to print.\n\n        var printContent = document.getElementById('<%= pnlForm.ClientID %>');\n        var windowUrl = 'about:blank';\n        var uniqueName = new Date();\n        var windowName = 'Print' + uniqueName.getTime();\n\n        //  you should add all css refrence for your Gridview. something like.\n\n        var WinPrint= window.open(windowUrl,windowName,'left=300,top=300,right=500,bottom=500,width=1000,height=500');WinPrint.document.write('<'+'html'+'><head><link href="cssreference" rel="stylesheet" type="text/css" /><link href="gridviewcssrefrence" rel="stylesheet" type="text/css" /></head><'+'body style="background:none !important"'+'>');\n\n        WinPrint.document.write(printContent.innerHTML); \n        WinPrint.document.write('<'+'/body'+'><'+'/html'+'>');\n        WinPrint.document.close();\n        WinPrint.focus();\n        WinPrint.print();\n        WinPrint.close();\n        }	0
1707852	1707363	FlowDocument Force a PageBreak (BreakPageBefore)	Section section = new Section();\nsection.BreakPageBefore = true;\nsection.Blocks.Add(table1);\nflowDoc.Blocks.Add(section);	0
6077489	6077424	How to combine Database fields label together in crystal report	{YourTableName.AddressName} + " " + {YourTableName.AddressCity} + ", " + {YourTableName.AddressZip}	0
5811502	5811119	Trying to build a COM Component in C# that can be referenced and used from VB5/6	Dim response As String\nresponse = arcom.GetServiceResponse	0
576743	575318	Assigning Roles to Users	// create the LINQ-to-SQL Data context\nUsersAndRolesDataContext dc = new UsersAndRolesDataContext();\n\n// create new instace of "UserTbl" object\nUserTbl newUser = new UserTbl();\nnewUser.UserID = "newuser";\nnewUser.Name = "Some NewUser";\nnewUser.EMail = "newuser@somewhere.org";\nnewUser.Password = "TopSecret";\n\n// add new user to the table of users in the data context\ndc.UserTbls.InsertOnSubmit(newUser);\n\n// create new instance of a role\nRolesTbl newRole = new RolesTbl();\nnewRole.RoleId = "ADMIN";\nnewRole.RoleName = "Administrators";\nnewRole.Description = "User with administrative rights";\n\n// add new role into LINQ-to-SQL Data context\ndc.RolesTbls.InsertOnSubmit(newRole);\n\n// write out all changes back to database\ndc.SubmitChanges();	0
13091243	13090735	inserting data into tables with foreign keys	if (!tableB.tableAs.IsLoaded)\n    tableB.tableAs.Load();	0
24858683	24858638	Formatted string as datatype	public class ItemId\n   {\n        private string _id;\n\n        public string ID\n        {\n            get { return _value; }\n            set\n            {\n                //do some formatting here\n                _id= value;\n            }\n        }\n\n        public ItemId(string id)\n        {\n            ID = id\n        }\n\n        public override string ToString()\n        {\n            //do some extra formatting here if needed\n            return Value;\n        }\n   }	0
18148942	18148561	How I can get a value of a cell from access database in C#?	OleDbCommand MyOleDbComm2 = new OleDbCommand();\n                        ObjConn2.Open();\n                        MyOleDbComm2.CommandText =\n                            "Select fee from table2 " +                                \n                            " Where Table2.fdne1='" + textBox1.Text + "'";\n                        MyOleDbComm2.Connection = ObjConn2;\n                        var result= MyOleDbComm2.ExecuteScalar();\n                        ObjConn2.Close();	0
16787072	16787025	Is there any way to do a mathematical addition between methods?	public int setPositionX(int newPositionX)\n{\n    positionX = newPositionX;\n    return newPositionX;\n}	0
10512892	10512848	Possible to return Json data from C# class library	report.OriginalList = objectToSerialize;\n\nvar jsonStr = JsonConvert.Serialize(objectToSerialize);\nreport.ShopSales = jsonStr;\n\nreturn report;	0
3705734	3705603	How to require FileUpload with actual upload, not just selecting a file	protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)\n    {\n        args.IsValid = FileUpload1.PostedFile.ContentLength != 0;\n    }\n\n    private void Save()\n    {\n        if (Page.IsValid)\n        {\n            var myFileName = "somefile.jpg"\n            FileUpload1.PostedFile.SaveAs(myFileName);\n        }\n    }	0
12876416	12875909	send multiple messages from TCP server to Client(C sharp to Android)	public void SendMessage(TcpClient client, string message)\n{\n\n    //byte[] buffer = Encoding.ASCII.GetBytes(message);\n\n    NetworkStream stream = client.GetStream();\n    StreamWriter writer = new StreamWriter(stream);\n    writer.WriteLine(message);\n    writer.Flush();\n\n}	0
22537576	22537437	Saving content of property 'text' of my instance of a textbox - How to join all strings - C#	XmlDocument doc = new XmlDocument();\ndoc.LoadXml("<Cmp><Id>Value</Id><fecha_cbte >Value</fecha_cbte><Tipo_cbte>Value</Tip o_cbte></Cmp>");\nusing (XmlTextWriter writer = new XmlTextWriter("c:\\temp\\nicexml.xml",null))\n{\n  writer.Formatting = Formatting.Indented;\n  doc.Save(writer);\n}	0
13523785	13512664	How to select Dynamic column from List	public void Test() {\n    var data = new[] {\n        new TestData { X = 1, Y = 2, Z = 3 }\n    ,   new TestData { X = 2, Y = 4, Z = 6 }\n    };\n    var strColumns = "X,Z".Split(',');\n    foreach (var item in data.Select(a => Projection(a, strColumns))) {\n        Console.WriteLine("{0} {1}", item.X, item.Z);\n    }\n}\nprivate static dynamic Projection(object a, IEnumerable<string> props) {\n    if (a == null) {\n        return null;\n    }\n    IDictionary<string,object> res = new ExpandoObject();\n    var type = a.GetType();\n    foreach (var pair in props.Select(n => new {\n        Name = n\n    ,   Property = type.GetProperty(n)})) {\n        res[pair.Name] = pair.Property.GetValue(a, new object[0]);\n    }\n    return res;\n}\nclass TestData {\n    public int X { get; set; }\n    public int Y { get; set; }\n    public int Z { get; set; }\n}	0
10706500	10704988	Crystal Reports vertical alignment in FieldObject	//insert a CRLF after the first space\nReplace({TABLE.FIELD}, " ", " " + Chr(10) + Chr(13), 1, 1)	0
7630203	7563118	Saving an image of a UIElement rendered larger than it appears on screen	InvalidationHandler.ForceImmediateInvalidate = true;	0
29166062	29157539	How to manipulate a DropDownList DataTextField when bound to a cached string array	protected void DropDownList1_DataBound(object sender, EventArgs e)\n    {\n        foreach (ListItem myItem in DropDownList1.Items)\n        {\n            try\n            {\n                if (myItem.Text.Length > 8)\n                    myItem.Text = myItem.Text.Substring(0, 11) + "...";\n            }\n            catch (ArgumentOutOfRangeException ex) \n            { \n                //do nothing\n            }\n        }\n    }	0
21123220	19736947	Read a named attribute from a WMA file on Win XP or later?	using (var wmaStream = new NAudio.WindowsMediaFormat.WmaStream(fileName))\n{\n    titleAttribute = wmaStream["Title"];\n    authorAttribute = wmaStream["Author"];\n    //  ...\n    // read other meta tag attributes\n}	0
17093222	17073279	Metro App ListView Binding Item Issue	public MainPage()\n{\n     this.InitializeComponent();\n\n     NavigationCacheMode = NavigationCacheMode.Required;\n     this.Loaded += MainPage_Loaded;\n}\n\nvoid MainPage_Loaded(object sender, RoutedEventArgs e)\n{\n     lvProductVariants.ItemsSource = null; // Reset \n      Bind();\n}	0
15564958	15564944	Remove last 3 characters from string	myString.Substring(str.Length-3)	0
3186619	3186554	Set all values of IDictionary	foreach (int key in dictionary.Keys.ToList())\n    dictionary[key] = true;	0
11107333	11106617	How to properly use Image as ToolTip?	using (System.Drawing.Imaging.Metafile emf = new System.Drawing.Imaging.Metafile(path))\nusing (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(emf.Width, emf.Height))\n{\n    bmp.SetResolution(emf.HorizontalResolution, emf.VerticalResolution);\n\n    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))\n    {\n        g.DrawImage(emf,\n            new Rectangle(0, 0, emf.Width, emf.Height),\n            new Rectangle(0, 0, emf.Width, emf.Height),\n            GraphicsUnit.Pixel\n        );\n\n        return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());\n    }\n}	0
9698330	9698207	How to convert string into integer in WindowsPhone7	int val1 = Convert.ToInt32("123");\n\nint val2 = int.Parse("123");\n\nint val3 = 0;\nint.TryParse("123", out val3);	0
11984160	11984050	get set property always returns null	public ProductCollection GuaranteedProductCollections\n      {\n        get\n          {\n            if (_guaranteedProductCollection.Count > 0)\n              {\n                 return _guaranteedProductCollection;\n              }\n            else\n              {\n                _guaranteedProductCollection = MWProductGuaranteedHelper.CheckGuaranteedProductsFromList(ProdCollection);  // the problem appears to be here... \n                return _guaranteedProductCollection;\n              }\n           }\n      }	0
17266489	17261177	Extjs 3.4 How can I read filter data in my controller?	store.filters = [{\n    fn: function (item) {\n        return (new RegExp(productValue).test(item.get('Name')));\n    }\n}];\nstore.filter(store.filters);	0
25952074	25948794	Adding a variable to routeconfig ASP.net	routes.MapPageRoute(\n    page.pageName,\n    url,\n    "~/combine.aspx"\n    false,\n    new{ pageId = page.pageId }//or whatever variable value you want to use\n);	0
20783928	20783219	How to Stamp PDF with another PDF using iTextSharp	var backgroundDocument = PdfReader.Open("Background.pdf", PdfDocumentOpenMode.Import);\nvar backgroundPage = backgroundDocument.Pages.Cast<PdfPage>().First();\n\nvar document = new PdfDocument();\nvar page = document.AddPage(backgroundPage);	0
31336690	31336467	Return text from output stream in c#	var ts = ((long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000;\nResponse.ContentType = "text/plain";\nbyte[] bytes = System.Text.Encoding.UTF8.GetBytes(ts.ToString());\nResponse.OutputStream.Write(bytes, 0, bytes.Length);\nResponse.Flush();\n//now signal the httpapplication to stop processing the request.\nHttpContext.Current.ApplicationInstance.CompleteRequest();	0
4473364	4473239	How can I render the result of Html.Action() from within a custom helper?	page.Response.Write(htmlString);	0
7110599	7110509	Are there good reasons to wrap a single property in a #region in c#?	#region Property - Name\nprivate string _name;\n/// <summary>\n/// Gets or sets the name of the customer.\n/// </summary>\n/// <remarks>\n/// This should always be the full name of the customer in the format {First Name} {Last Name}.\n/// </remarks>\n/// <example>\n/// customer.Name = "Joe Bloggs";\n/// </example>\n/// <seealso cref="Customer"/>\n/// <value>\n/// The name of the customer.\n/// </value>\npublic string Name\n{\n    get\n    {\n        return _name;\n    }\n    set\n    {\n        _name = value;\n    }\n}\n#endregion	0
13724229	13698767	Check/Uncheck all items in radListView	for (int item = 0; item < AllowAccess_ListView.Items.Count; item++)\n{\n     AllowAccess_ListView.Items[item].CheckState = Telerik.WinControls.Enumerations.ToggleState.On;\n}	0
16836824	16836457	Get text from dynamically created WinForms textbox	private String[] GetTextBoxStrings()\n{\n    List<String> list = new List<String>();\n    foreach (Control c in this.Controls)\n    {\n        if (c is TextBox)\n            list.Add(((TextBox)c).Text);\n    }\n    return list.ToArray();\n}	0
6530146	6530090	How To Save The String Variable Data To Xml File	protected void Button1_Click(object sender, EventArgs e)\n{\n    using (StreamWriter fsWrite = new StreamWriter(@"F:/info.xml"))\n    {\n\n        fsWrite.WriteLine("<ROOT>" +\n            "<SIGN>1155</SIGN>" +\n            "<MAXLOOP>23</MAXLOOP>" +\n            "<TOTTAL_REC>5645</TOTTAL_REC>" +\n            "<PART_EXPORT>retert</PART_EXPORT>" +\n            "<LEAVE_EXPORT>retr</LEAVE_EXPORT>" +\n            "<SAL_TDS_EXPORT>rter</SAL_TDS_EXPORT>" +\n            "<HR_DET_EXPORT>rete</HR_DET_EXPORT>" +\n            "<SELECTIONWISE>ertre</SELECTIONWISE>" +\n            "</ROOT>");\n    }\n}	0
29722152	29721943	Converting double to int array	double[] first_value = new double[text.Length];\n        ... \n        for (int i = 0; i < text.Length; i++)\n        {\n            double get_first = r * i * (1 - i);\n            int index = (int)(i * text.Length);\n            first_value[index] = get_first;\n        }	0
31036299	31035933	Check if a string is a literal string known at compile time?	System.ComponentModel.TypeDescriptor	0
9386502	9047598	How do I disable keep-alive for a basicHttpRelayBinding to the Azure service bus?	private static System.ServiceModel.Channels.Binding GetBinding(System.ServiceModel.Channels.Binding bIn)\n    {\n        var bOut = new CustomBinding(bIn);\n        var transportElement = bOut.Elements\n              .Find<HttpsRelayTransportBindingElement>();\n        transportElement.KeepAliveEnabled = false;\n        return bOut;\n    }	0
23825907	23801914	how to ensure that user select different comobox option in Datagridview	for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)\n        {\n            for (int j = i + 1; j < dataGridView1.Rows.Count - 1;j++ )\n            {\n                if (dataGridView1.Rows[i].Cells[0].Value.ToString() == dataGridView1.Rows[j].Cells[0].Value.ToString())\n                {\n                    dataGridView1.Rows[j].Cells[0].Value = "";\n                }\n            }\n\n        }	0
29008103	29007957	Create a C# dictionary from DB query with repeated keys	var schoolCities = schoolsWithAddresses\n.Where(school => school.Address.City != null)\n.ToLookup(sc => sc.Address.City.Name.ToLower());	0
10746956	10746828	Converting a Console Application into a GUI that uses a BackgroundWorker	Console.SetOut	0
32902542	32902299	Convert multidimensional array to list of single array	int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };\n\nint[][] jagged = new int[arr.GetLength(0)][];\n\nfor (int i = 0; i < arr.GetLength(0); i++)\n{\n    jagged[i] = new int[arr.GetLength(1)];\n    for (int j = 0; j < arr.GetLength(1); j++)\n    {\n        jagged[i][j] = arr[i, j];\n    }\n}\n\nList<int[]> list = jagged.ToList();	0
34122000	34121929	How to handle two datagridviews errors with one method?	var grid = (DataGridView)sender;	0
1216828	1216536	nested xml with linq in repeater	var qListCurrentMonth = \n    (from feed in doc.Descendants("item")\n     select new \n     {\n         title = feed.Element("title").Value,\n         description = feed.Element("description").Value,\n         events = \n            (from ev in feed.Element("events").Elements("location")\n             select ev.Attribute("city").Value).Aggregate((x,y) => x+ "<br />" + y)\n      });	0
28214454	28186044	Quartz.net: Run a job for specific interval of time	ITrigger trigger = TriggerBuilder\n            .Create()\n            .WithDailyTimeIntervalSchedule(s =>  \n                         s.WithIntervalInMinutes(15)\n                          .OnMondayThroughFriday()\n                          .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(9, 0))\n                          .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(15, 0)))\n           .Build();	0
9352328	9352313	How to deserialize xml to object without locking the file?	new FileStream(File, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);	0
14369700	6834348	how to check whether a user is a member of distribution list/security group in AD C#	IsUserMemberOf("domain1\\username","domain2\\groupname")\n\n\nstatic bool IsUserMemberOf(string userName, string groupName)\n{\n using (var ctx = new PrincipalContext(ContextType.Domain,"domain1"))\n using (var groupPrincipal = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain,"domain2"), groupName))\n using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))\n {\n    return userPrincipal.IsMemberOf(groupPrincipal);\n }	0
17089369	17086640	Is there a managed API to manage IIS 8?	var manager = new ServerManager();\nmanager.Sites[0].Stop();\nmanager.Dispose();	0
4987485	4920532	How to split a Word document by section using C# and the Open XML SDK?	Paragraph1 // Section 1\n\nParagraph2 // Section 1\n\nSectionProperties (Section 1) // Defines what section 1 is like\n\nParagraph3 // Section 2\n\nParagraph4 // Section 2\n\nSectionProperties (Section 2) // Defines what section 2 is like\n\nParagraph5 // Section 3\n\nFinal SectionProperties // Defines what Section 3 is like. \n// This final definition exists within the Body tag itself.\n// Other SectionProperties exist under Paragraph Properties	0
5613476	5613467	After inserting, only one character is inserted of "string" in database	VARCHAR(50)	0
6236435	6236391	How to avoid useless white border in resized PNG with transparent background?	newimg.MakeTransparent(Color.White);	0
20011347	20011253	Where to add a polling function to a form?	using System.Timers;\nTimer serviceStatusTimer = new Timer(5000);\nprivate void OnLoaded(object sender, RoutedEventArgs e) // Window loaded event\n{\n    serviceStatusTimer.Elapsed += ServiceStatus;\n    serviceStatusTimer.Enabled = true;\n    serviceStatusTimer.Start();\n}	0
7178585	7178437	Get Nth item from SelectList	mySelectList.ElementAt(n)	0
6992621	6992377	How do i print any value after Main() method gets called?	class Myclass\n    {\n        // will print 1st also sets up Event Handler\n        static Myclass()\n        {\n            Console.WriteLine("1st");\n            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);\n        }\n\n        static void Main(string[] args)\n        {\n            Console.WriteLine("2nd"); // it will print 2nd\n        }\n\n        static void CurrentDomain_ProcessExit(object sender, EventArgs e)\n        {\n            Console.WriteLine("3rd");\n        }\n    }	0
29832562	29828795	Find GameObjects with keyword Unity	public static Object[] findObjectsFromIdentifier(int identifier) {\n    Object[] objects = GameObject.FindObjectsOfType( typeof( GameObject ) );\n    return objects.Where( obj => getIdentifierFromObject( obj ) == identifier ).ToArray();\n}	0
32176980	32176293	How to get value from IEnumerable collection using its Key?	public static IEnumerable<object> GetValues<T>(IEnumerable<T> items, string propertyName)\n{\n    Type type = typeof(T);\n    var prop = type.GetProperty(propertyName);\n    foreach (var item in items)\n        yield return prop.GetValue(item, null);\n}	0
3721688	3721673	Add image files to VS2010 project	Type t = typeof(SomeType);\nStream embeddedFileStream = t.Assembly.GetManifestResourceStream(t, "yourfilename.jpg")	0
32775970	32758797	How get images from .docx to stream with Aspose.Words	Stream imageStream = new MemoryStream();\ne.ImageStream = imageStream;	0
17382663	17374398	Ninject Convention Based Configuration	kernel.Bind(x => x\n    .FromThisAssembly()\n    .SelectAllClasses().EndingWith("MySuffix")\n    .BindAllInterfaces();	0
6175239	6175155	How to detect when owner form is closed from an inner control?	FindForm().FormClosing += parentForm_FormClosing;	0
12330443	12329421	Is there a way to check when mouse is above standard window control buttons (close, minimize etc)?	internal const int WM_NCMOUSEMOVE = 0x00A0;\n\nprotected override void WndProc(ref Message m)\n{\n    if (m.Msg == WM_NCMOUSEMOVE)\n    {\n        if ((int)m.WParam == 0x8)\n            Console.WriteLine("Mouse over on Minimize button");\n\n        if ((int)m.WParam == 0x9)\n            Console.WriteLine("Mouse over on Maximize button");\n\n        if ((int)m.WParam == 0x14)\n            Console.WriteLine("Mouse over on Close button");\n    }\n\n    base.WndProc(ref m);\n}	0
14889729	14889660	Remove a particular tag(<xs:any>) from xsd file using C#	XNamespace xs = "http://www.w3.org/2001/XMLSchema";\nvar doc = XDocument.Load(your xsd file);\ndoc.Descendants(xs + "any").Remove();	0
805610	805595	C# DropDownList with a Dictionary as DataSource	Dictionary<string, string> list = new Dictionary<string, string>();\n    list.Add("item 1", "Item 1");\n    list.Add("item 2", "Item 2");\n    list.Add("item 3", "Item 3");\n    list.Add("item 4", "Item 4");\n\n    ddl.DataSource = list;\n    ddl.DataTextField = "Value";\n    ddl.DataValueField = "Key";\n    ddl.DataBind();	0
29534792	29533160	Set filename to Lav Splitter Source filter	(lavSplitter as IFileSourceFilter).Load("c:\\a.avi", null);	0
5251417	5251355	Compare byte arrays with masking	for (int i = 0; i < data.Length; i++ )\n    {\n        if (mask[i] == 0xFF && data[i] != dataTemplate[i]) {\n            throw new Exception("arrays dont match!");\n        }\n    }	0
23906147	23906008	How to implement my own SelectionChangedEventHandler in c#	lines.SelectedIndex = 0;\nlines.SelectedItem = param.Component.Attributes.Items;// This items contains 1000000,3 00000, and so on.\n\nlines.SelectionChanged += (o,e) => {\n    MessageBox.Show("clist   _SelectionChanged1");\n    txtblk1ShowStatus.Text = lines.SelectedItem.ToString();\n};\n\nlines.SelectedIndex = lines.Items.Count - 1;	0
32314754	32314370	Create an IEnumerable<Interface> from a bunch of ICollection<Implementation> 's in C#	public IEnumerable<IEnumerable<IStuff>> GetStuffCollections()\n{\n    var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n    foreach (var property in properties)\n    {\n        Type pt = property.PropertyType;\n        if (pt.IsGenericType\n            && pt.GetGenericTypeDefinition() == typeof(ICollection<>)\n            && typeof(IStuff).IsAssignableFrom(pt.GetGenericArguments()[0]))\n        {\n            yield return (IEnumerable<IStuff>)property.GetValue(this);\n        }\n    }\n}	0
15239985	15239909	Parse json string using json.net?	class Program\n{\n    static void Main(string[] args)\n    {\n        var text = @"[{'Name':'AAA','Age':'22','Job':'PPP'},\n                    {'Name':'BBB','Age':'25','Job':'QQQ'},\n                    {'Name':'CCC','Age':'38','Job':'RRR'}]";\n\n        dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(text);\n        for (var i = 0; i < data.Count; i++)\n        {\n            dynamic item = data[i];\n            Console.WriteLine("Name: {0}, Age: {1}", (string)item.Name, (string)item.Age);\n        }\n\n        Console.ReadLine();\n    }\n}	0
21776750	21775069	PageIndexChanging Event in search button in asp.net?	private void grid()\n   {\n      if(!string.IsNullOrEmpty(yourSearchTextBox.Text)\n      {\n      // Then call search method. Make sure you bind the Grid in that method.\n      }\n      else\n      {\n      // Normally Bind the Grid as you are already doing in this method.\n      }\n   }	0
17190948	17190868	How to set parameter in method like settings type	public enum CustomType {\n      Type1 = 1,\n      Type2 = 2,\n      Type3 = 3\n };\n\npublic void Method(CustomType t)\n{\n    switch (t)\n    {\n        case CustomType.Type1:\n                  // code here\n                  break;\n        case CustomType.Type2:\n                  // code here\n                  break;\n        case CustomType.Type3:\n\n    }\n}	0
25663138	25379500	Events in Onvif Device Manager	onvif.utils.OdmSession odmSession = new onvif.utils.OdmSession(session);\nodmSession.GetPullPointEvents().Subscribe(\n    onvifEvent =>\n    {\n        try\n        {\n            foreach (var s in onvifEvent.message.Data.simpleItem)\n            {\n                if (s.name == "LogicalState")\n                {\n                    // code here\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            MessageBox.Show(e.Message);\n        } \n});	0
692480	692451	How to pass an array of bytes as a Pointer in C#	public static void Func_X_2(byte[] stream, int key, byte keyByte)\n{\n    stream[0] ^= (byte)(stream[0] + BitConverter.GetBytes(LoWord(key))[0]);\n    stream[1] ^= (byte)(stream[1] + BitConverter.GetBytes(LoWord(key))[1]);\n    stream[2] ^= (byte)(stream[2] + BitConverter.GetBytes(HiWord(key))[0]);\n    stream[3] ^= (byte)(stream[3] + BitConverter.GetBytes(HiWord(key))[1]);\n    stream[4] ^= (byte)(stream[4] + BitConverter.GetBytes(LoWord(key))[0]);\n    stream[5] ^= (byte)(stream[5] + BitConverter.GetBytes(LoWord(key))[1]);\n    stream[6] ^= (byte)(stream[6] + BitConverter.GetBytes(HiWord(key))[0]);\n    stream[7] ^= (byte)(stream[7] + BitConverter.GetBytes(HiWord(key))[1]);\n}\n\npublic static int LoWord(int dwValue)\n{\n    return (dwValue & 0xFFFF);\n}\n\npublic static int HiWord(int dwValue)\n{\n    return (dwValue >> 16) & 0xFFFF;\n}	0
20903374	20902268	How to databind textbox based on listview selection	DataTable dt = new DataTable();\ndt.Columns.Add("Name");\ndt.Columns.Add("Country");\n\ndt.Rows.Add("Name1", "Country1");\ndt.Rows.Add("Name2", "Country2");\n\nBindingSource bindingSource = new BindingSource();\nbindingSource.DataSource = dt;\nmovieListBox.DataSource = bindingSource;\nmovieListBox.ValueMember = "Name";\n\ntextBoxName.DataBindings.Add(new Binding("Text", movieListBox.DataSource, "Name", true, DataSourceUpdateMode.OnPropertyChanged));\ntextBoxCountry.DataBindings.Add(new Binding("Text", movieListBox.DataSource, "Country", true, DataSourceUpdateMode.OnPropertyChanged));	0
14519026	14518993	Distinct items on property from 2 lists	var results = Persons.Where(p => !personIds.Contains(p.Id));	0
1612907	1612848	C# Regular Expression to break pairs of semicolon-delimited values into array	#?([0-9]+;#[a-zA-Z\s]+)	0
4433218	4429663	How to save combined (new+modified) detached entities in Entity Framework?	foreach (var entity in entities)\n{\n  if (entity.Id == 0) // 0 = default value: means new entity\n  {\n    // Add object\n  }\n  else\n  {\n    // Attach object and set state to modified\n  }\n}	0
11094985	11094797	How to compare two lists with out order	var expected = new List<string>();\n        expected.Add("a");\n        expected.Add("b");\n        expected.Add("c");\n\n        var actual = new List<string>();\n        actual.Add("c");\n        actual.Add("a");\n        actual.Add("b");\n        actual.Add("e");\n        actual.Add("d");\n\n        // sort the lists\n        expected.Sort();\n        actual.Sort();\n\n        // if the lists are equal return true;\n        if (expected.SequenceEqual(actual))\n        {\n            // the lists have the same contents -- return true or whatever\n        }\n        else {\n            // union of both lists (abcde)\n            var unionOfBoth = expected.Union(actual).ToList();\n        }	0
21329189	21328664	WPF Application Relative path to a mp3 sound file	mplayer.Open(new Uri(@"../../Sounds/circles.mp3", UriKind.Relative));	0
6680805	6680779	Line breaks ignored when sending mail as plain text	Environment.NewLine	0
29969100	29968607	Using a database function with entity framework	var param1Parameter = param1 != null ?\n    new SqlParameter("param1", param1) :\n    new SqlParameter("param1", typeof(string));\n\n    var param2Parameter = param2 != null ?\n    new SqlParameter("param2", param2) :\n    new SqlParameter("param2", typeof(int));\n\n    return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<sp_TestSproc_Result>("sp_TestSproc @param1, @param2", param1Parameter, param2Parameter);	0
9156971	9156820	Serialize enum to string	public enum Color {red, green, blue, yellow,\n  pink}	0
25837787	25837502	MVVM Common app.config	link reference	0
23142631	23142417	How to run SQL Query in Visual Studio based on customer input?	using( SqlConnection conn = new SqlConnection( connectionString ) )\n{\n    conn.Open();\n    using( SqlCommand command = new SqlCommand( "your select statement", conn ) )\n    {\n        command.AddWithValue( "@Param1", YourTextBox.Text );\n        var reader = command.ExecuteReader();\n\n        reader.Read();\n        txtFoo.Text = reader["FooColumn"];\n        txtBar.Text = reader["BarColumn"];\n    }\n}	0
31748629	29560471	iframe innerHTML visible in browser, however is null in code	doc.document.getelementbyid	0
2519090	2519017	Is there a way to make ToEnum generic	myEnum = (TEnum)((object)value);	0
7919578	7919511	Get Epoch in C# for GMT	Timespan t = DateTime.UtcNow - new DateTime(1970, 1, 1);\ndouble ms = t.TotalMilliseconds ;	0
17704454	17703259	Determine Current Page	if (Frame1.Content.GetType() == typeof(Dashboard))\n        {\n            await home.DatabaseTest();\n        }	0
4064687	4064271	How prevent container control from being moved in user control during design-time?	using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\n[Designer(typeof(MyPanelDesigner))]\npublic class MyPanel : Panel {\n    private class MyPanelDesigner : ScrollableControlDesigner {\n        public override SelectionRules SelectionRules {\n            get { return SelectionRules.None; }\n        }\n    }\n}	0
21631887	21631520	MVC Attribute Routing - Default Controller Index with GET and POST	[Route("~/")]\n [Route]\n [Route("Index")]\n [HttpPost]\n [ValidateAntiForgeryToken]\n\n public ActionResult Index(String Username, String Password)	0
11345478	11345382	Convert object to JSON string in C#	public class ReturnData \n{\n    public int totalCount { get; set; }\n    public List<ExceptionReport> reports { get; set; }  \n}\n\npublic class ExceptionReport\n{\n    public int reportId { get; set; }\n    public string message { get; set; }  \n}\n\n\nstring json = JsonConvert.SerializeObject(myReturnData);	0
1785870	1785854	How do you divide integers and get a double in C#?	double pct = (double)x / (double)y;	0
20761632	20761414	How to display a datatable in the view?	private void btnDisplayFilter_Click(object sender, EventArgs e)\n{\n    using(filterForm filter = new filterForm())\n    {\n         if(filter.ShowDialog(this) == DialogResult.OK)\n         {\n             displayGridViewControl dg = new displayGridViewControl();\n             dg.myDatagridView.DataSource = filter.returnedDataList;\n             displayGridView.ShowDialog();\n         }\n     }\n}	0
8638245	8638118	C# replace part of string but only exact matches possible?	string fixedString = string.Join("|",\n                                 beginString\n                                    .Split('|')\n                                    .Select(s => s != "apple" ? s : "mango"));	0
21332316	21327336	Web Api variable parameters	[AcceptVerbs("GET")] [ActionName("Get")] \npublic HttpResponseMessage Get([FromUri] string file)	0
8550595	8550549	How to read SQL server schema info in .net?	DataTable t = _conn.GetSchema("Tables");	0
30548539	30547592	Room availability between two dates (beginner)	currentBooking = _ctx.Booking\n            .Where(b => b.RoomId == booking.RoomId)\n            .Select(b => (booking.CheckIn < b.CheckOut && booking.CheckIn > b.CheckIn))\n            .FirstOrDefault();\n\n        if (currentBooking)\n        {\n            throw new Exception("The Room is already out on that date.");\n        }	0
10653738	10653685	How to set Child Nodes to Parent Nodes in TreeView?	for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n{\n    TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString());\n    tnode.SelectAction = TreeNodeSelectAction.Expand;\n    // Add the new TreeNodes underneath the currently selected TreeNode.\n    TreeView1.SelectedNode.ChildNodes.Add(tnode);\n}\nTreeView1.SelectedNode.Expand();	0
24335861	24331359	Find the maximum distance between two series in a chart	double distance = 0;\nSeries series1 = tmpChart.Series[series1];\nSeries series2 = tmpChart.Series[series2];\nSeries seriesToEnumerate = series1.Points.Count() >= series2.Points.Count() ? series1 : series2;\n\nfor (int i = 0; i < series1.Count(); ++i)\n{\n    DataPoint point1 = series1.Points[i];\n    DataPoint point2 = series2.Points[i];\n\n    if (point1.X == point2.X)\n    {\n        distance = Math.Abs(point1.Y - point2.Y) // if greater than previous distance\n    }\n    else\n    {\n        // find two points in series2 whose X values surround point1.X, call them point3 and point4\n\n        // Interpolate between point3 and point4 to find the y value at the x of point1\n        double slope = (point4.Y - point3.Y) / (point4.X - point3.X);\n        double intercept = point4.Y - slope * point4.X;\n        double y2 = slope * point1.X + intercept;\n\n        distance = Math.Abs(point1.Y - y2); // if this is greater than previous distance\n    }\n}	0
16464281	16464247	How to check if it is zero datetime in c#	DateTime.MinValue	0
11719344	11719272	C#: Regex for any number plus a decimal point that does not have a limit	Regex isnumber = new Regex(@"^[0-9]+(\.[0-9]+)?$");	0
7283580	7283516	How to check the missing element in the sequence	selectedNumbers.Sort();\nselectedNumbers.Reverse();\n\nint maxPeriodNumber = 5; // This you know\nint lastValue = (int)selectedNumbers[0];\n\nif (lastValue < maxPeriodNumber)\n{\n    // Highest selected number is smaller than required, warn user or throw exception\n    return;\n}\n\nforeach (int val in selectedNumbers)\n{\n    if (val < (lastValue - 1))\n    {\n        // There is a gap in the numbering, warn user or throw exception\n        return;\n    }\n\n    lastValue = val;\n}\n\n// When you end up here, everything is ok and you can delete the items whose numbers are in the list	0
2980254	2980182	binary file to string	string myString;\nusing (FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open))\nusing (BinaryReader br = new BinaryReader(fs))\n{\n    byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));\n    myString = Convert.ToBase64String(bin);\n}\n\nbyte[] rebin = Convert.FromBase64String(myString);\nusing (FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create))\nusing (BinaryWriter bw = new BinaryWriter(fs2))\n    bw.Write(rebin);	0
7432308	7352407	Replace text in Word document with headings	tmpRange.set_Style(#your style);	0
24969324	24969018	Pass parameter to rdlc from page with reportviewer	YourReportViewer.LocalReport.DataSources.Add(new ReportDataSource("testDataSet", list));	0
8853061	8808460	Trying to find text on webpage that has no id using C#	_ctsLineListSearchGrid.Find(By.Tag("input",15)).Click();	0
26002519	26002484	Doing the same type of work with variables in c#	foreach(var pictureBox in this.Controls.OfType<PictureBox>())\n    pictureBox.Image = null;	0
9879282	9879246	ASMX HTTP Get Parameter is a C# Keyword	[WebMethod]\n[ScriptMethod(UseHttpGet = true)]\npublic void Test(string @interface)	0
21768498	21536684	unit testing a webapi async action	[Fact()]\npublic async void GetCustomer()\n{\n    var id = 2;\n\n    _customerMock.Setup(x => x.FindCustomerAsync(id))\n        .Returns(Task.FromResult(new Customer()\n                 {\n                  customerID = 2,\n                  firstName = "Tom",\n                 }));\n\n\n    var controller = new CustomersController(_customerMock.Object).GetCustomer(id);\n    var result = await controller as Customer;\n\n    Assert.NotNull(result);\n}	0
7759957	7759902	What is the fastest, case insensitive, way to see if a string contains another string in C#?	15,000 length string, 10,000 loop\n\n00:00:00.0156251 IndexOf-OrdinalIgnoreCase\n00:00:00.1093757 RegEx-IgnoreCase \n00:00:00.9531311 IndexOf-ToUpper \n00:00:00.9531311 IndexOf-ToLower\n\nPlacement in the string also makes a huge difference:\n\nAt start:\n00:00:00.6250040 Match\n00:00:00.0156251 IndexOf\n00:00:00.9687562 ToUpper\n00:00:01.0000064 ToLower\n\nAt End:\n00:00:00.5781287 Match\n00:00:01.0468817 IndexOf\n00:00:01.4062590 ToUpper\n00:00:01.4218841 ToLower\n\nNot Found:\n00:00:00.5625036 Match\n00:00:01.0000064 IndexOf\n00:00:01.3750088 ToUpper\n00:00:01.3906339 ToLower	0
7802739	7802681	Pass Byte Array that was in Session object to a Web Service (Asp.Net 2.0 asmx) through a JSON object	// returns a byte[]\nSystem.Convert.FromBase64String(base64String);\n// returns a string\nSystem.Convert.ToBase64String(byteData);	0
7990765	7990720	Delete all rows from one of the duplicate datatables	dt1= dt2.Copy();\ndt2.Rows.Clear();	0
11252817	11249796	How to send nonserializable objects as arguments to a proxy method. MarshalByRefObject wrapper?	[Serializable]\nclass MyThirdPartyClass : ThirdPartyClass, ISerializable\n{\n    public MyThirdPartyClass()\n    {\n    }\n\n    protected MyThirdPartyClass(SerializationInfo info, StreamingContext context)\n    {\n        Property1 = (AnotherClass)info.GetValue("Property1", typeof(AnotherClass));\n        Property2 = (AnotherClass)info.GetValue("Property2", typeof(AnotherClass));\n    }\n\n    public void GetObjectData(SerializationInfo info, StreamingContext context)\n    {\n        info.AddValue("Property1", Property1);\n        info.AddValue("Property2", Property2);\n    }\n}	0
10935072	10934861	exact command for storing in the oracle table	string query = @"INSERT INTO SOME_TABLE VALUES (SOME_COLUMN_1 = :SomeParam1,SOME_COLUMN_2 = :SomeParam2 )";\nOracleCommand command = new OracleCommand(query, connection) { CommandType = CommandType.Text };\ncommand.Parameters.Add(":SomeParam1", OracleDbType.Varchar2).Value = "Your Val 1";\ncommand.Parameters.Add(":SomeParam2", OracleDbType.Varchar2).Value = "Your Val 2";\nconnection.ExecuteNonQuery();	0
21047803	21023736	How do I implement double click feature to move camera back to previous position?	using UnityEngine;\nusing System.Collections;\n\npublic class DoubleClickBack : MonoBehaviour {     \npublic Camera mainCam;     \nfloat doubleClickStart = 0;\n\nvoid CheckDoubleClick() { \n\nvoid OnMouseUp() {     \n    if ((Time.time - doubleClickStart) < 0.3f) {   \n        this.OnDoubleClick();     \n        doubleClickStart = -1;     \n    }\n    else {     \n        doubleClickStart = Time.time;\n    }\n}\n}\n\nvoid OnDoubleClick() {\n    Debug.Log("Double Clicked!");     \n    mainCam.transform.position = new Vector3(0, 1, -7);     \n    Camera.main.orthographicSize = 0.4f;\n}     \n}	0
5209174	5200858	how to check for an empty collection in a db4o's SODA query	...\nquery.Descend("_list").Constrain(typeof(Item)).Not();\n...	0
2733987	2733957	Linq: Search a string for all occurrences of multiple spaces	Regex.Matches(input,@" {2,}").Cast<Match>().Select(m=>new{m.Index,m.Length})	0
3494282	3494090	How to sort a List in C#?	SortedList<int, Dictionary<string, string>> lngList;	0
10094440	10094313	inserting element into a list, if condition is met with C#	int index = list1.BinarySearch(must_enter);\nif (index < 0)\n list1.Insert(~index, must_enter);	0
7167775	7167753	Select 3 fields from 10 fields in table with LINQ	public List<Book> GetAllBook() {     \n\n    var q = (from c in this.LDEntities.Book              \n             select new Book() \n             { \n                 IdBook = c.IdBook, \n                 NameBook = c.NameBook, \n                 Athour = c.Athour }).ToList();     \n    return (q); \n}	0
11937538	11937474	How to determine the maximum color in an image?	occurences = int[256][256][256] \nfor x in picture.width()\n    for y in picture.height()\n        p = point(x,y) in picture;\n        occurences[p.red][p.blue][p.green]++;\n\nFind max value in occurences	0
16360248	16359817	Split and insert string into database	BULK\nINSERT YourTable\nFROM 'c:\csvtest.txt'\nWITH\n(\nFIELDTERMINATOR = ',',\nROWTERMINATOR = '\n'\n)\nGO	0
20677579	20677507	Upgrading NuGet version in solution	nuget.exe update -self	0
28694316	28693537	Create a .dll Library consisting GUI Components windows phone 8	frame.Navigate(new Uri(string.Format("/Adafy.Payment.Client.WindowsPhone;component/Pages/ProductDescription.xaml?productId={0}", productId), UriKind.Relative));	0
28690650	28690439	Add Change Event Handler to New Excel Sheet	worksheet.Change += WorksheetChangeEventHandler;	0
26458532	26457623	How do you properly write a foreach loop to upload multiple files in asp.net C#	if (FileUpload1.HasFiles)\n{\n    foreach (var file in FileUpload1.PostedFiles)\n    {\n        file.SaveAs(Path.Combine(Server.MapPath(ProperPath), file.FileName));\n        lblFilesUploaded1.Text += String.Format("{0}<br />", file.FileName);\n    }\n}	0
3813328	3813261	How to store delegates in a List	System.Collections.Generic.Dictionary<string, System.Delegate>	0
7678552	7677972	How can I serve a CSS file from a WCF Service?	public System.IO.Stream GetSytleFile(String widgetID)\n    {            \n        IWidget w = GetWidget(widgetID);\n        WebOperationContext.Current.OutgoingResponse.ContentType = "text/css";\n        return StreamBytes(w.GetEditorStyleFile());\n    }	0
32796216	32796144	Need to translate some UnityScript to C#	void spawn()\n    {\n        RaycastHit randomPoint = GetPointOnMesh();\n        GameObject spawnPreferences= (GameObject)Instantiate(prefab, randomPoint.point, Quaternion.identity);\n        spawnPreferences.transform.eulerAngles = new Vector3(0,Random.Range(0, 360),0);\n    }	0
24461043	24460997	Two different generic types as result and parameter	private T Call<T, TOther>(Uri uri, TOther parameters) where T:new()  { }	0
9234955	9033630	Mschart get value of a series at the cursor position	string ceva = detailChart.Series[1].Points[detailChart.ChartAreas[0].CursorX.Position].GetValueByName("Y").ToString(	0
7150029	7137810	RejectChanges for specific Entities	((IRevertibleChangeTracking)address).RejectChanges();	0
32694286	32693480	How to Insert text in the end of the document	private void button2_Click(object sender, EventArgs e)\n{\n    try\n    {\n        if (textBox1.Text != "")\n        {\n            Microsoft.Office.Interop.Word._Application oWord;\n            object oMissing = Type.Missing;\n            oWord = new Microsoft.Office.Interop.Word.Application();\n            oWord.Visible = false;\n            oWord.Documents.Open(filePath);\n            oWord.ActiveDocument.Characters.Last.Select();  // Line 1\n            oWord.Selection.Collapse();                     // Line 2\n            oWord.Selection.TypeText(textBox1.Text);\n            oWord.ActiveDocument.Save();\n            oWord.Quit();\n            MessageBox.Show("The text is inserted.");\n            textBox1.Text = "";\n        }\n        else\n        {\n            MessageBox.Show("Please give some text in the text box");\n        }\n    }\n    catch(Exception)\n    {\n        MessageBox.Show("Please right click on the window and provide the path");\n    }\n}	0
24288656	24287820	Best practice for storing enums and user defined values	public class CustomPaymentType\n{\n    public string paymentTypeName { get; private set; }\n    public int Id { get; private set; }\n\n    // if you need "Constant payment types usable in code, just add something like:\n    public static CustomPaymentType CashPayment\n    {\n        get { return new CustomPaymentType() { Id = 7, paymentTypeName= "CashPayment" } }\n    }\n\n    public static CustomPaymentType CreditPayment\n    {\n        get { return new CustomPaymentType() { Id = 7,paymentTypeName= "CreditPayment" } }\n    }\n}	0
32642074	32641664	How to search data from Database using Linq	var check = db.Job.ToList();\nvar SerachTile = check.Where(c => c.Title.Contains(Jobserach));	0
21443115	21032174	Scroll to Position in RichTextBox	TextPointer start = txtEditor.Selection.Start;\nFrameworkContentElement fce = (start.Parent as FrameworkContentElement);\nif (fce != null)\n{\n    fce.BringIntoView();\n}	0
14992703	14992412	How to export WKT from a Shapefile in c#?	/// <summary>\n/// Converts this shape into a Geometry using the default factory.\n/// </summary>\n/// <returns>The geometry version of this shape.</returns>\npublic IGeometry ToGeometry()\n{\n    return ToGeometry(Geometry.DefaultFactory);\n}	0
16898079	16897812	Best way to insert a list of values into Database using SQL and C#	using(SqlConnection conn = new SqlConnection(connString))\n{\n   for(int i=0; i < urlList.Length; i++)\n   {\n      string url   = urlList[i];\n      string title = titleList[i];\n      SqlCommand cmd = new SQlCommand({insert sql here});\n      cmd.ExecuteNonQuery();\n   }\n}	0
2473350	2473335	How do I implement this public accesible enum	public enum MyEnum { Alpha, Beta }\n// ... \nprivate MyEnum _value;\npublic MyEnum GetMyEnum { get { return _value; } }	0
26665278	26665167	How convert ToList method to LINQ expression	names.SelectMany(x => new[] { x.ToLower(), x.ToUpper() }).ToList()	0
3813280	3767849	How to Implement "if active" detection in an Html.Helper?	public static MvcHtmlString ActiveActionLink (this HtmlHelper helper, string labelText, string action, string controller)\n{\n    var cssProprties = controller;\n\n    // if this controller is the target controller, page is active.\n    if (helper.ViewContext.RouteData.Values["controller"].ToString() == controller)\n        cssProprties += " active";\n\n    return helper.ActionLink(labelText, action, controller, null, new { @class = cssProprties });\n}	0
22012057	21990648	Lambda statement syntax - help for a learner	decimal maxSlope = ScaleTableList.Where(x => x.Percentage == aPercentagePassedIn).Select(y => y.Slope).FirstOrDefault();	0
19269150	19269126	Linq two select statements, second one uses first ones result,	.Select(p => new\n        {\n            p.Box_ID,\n            p.TotalA,\n            p.TotalC,\n            DiffAC = p.TotalA - p.TotalC // calculate\n        });	0
20241197	20240991	Looking for Encryption and Decryption method without special characters	System.Web.HttpUtility.UrlEncode("cryptogram with special chars");	0
3564847	3564730	how to hide the particular row in the Gridview?	YourDataGridView.CurrentCell = null;\nYourDataGridView.Rows[rowIndexToHide].Visible = false;	0
7498162	7498134	How to Pass dictionary as the value of another dictionary?	Category_Dict.Add(bean.getId(), for_cat_dict);	0
3127844	3127836	Most performant way to store large amounts of static strings	public const string myVariable = "some static text";	0
614148	613327	abstract method in a virtual class	public abstract class BaseClass\n{\n    protected virtual void DeletePersonCore(Guid id)\n    {\n        //shared code\n    }\n\n    public void DeletePerson(Guid id)\n    {\n        //chain it to the core\n        DeletePersonCore(id);\n    }\n}\n\npublic class DerivedClass : BaseClass\n{\n    protected override void DeletePersonCore(Guid id)\n    {\n        //do some polymorphistic stuff\n\n        base.DeletePersonCore(id);\n    }\n}\n\npublic class UsageClass\n{\n    public void Delete()\n    {\n        DerivedClass dc = new DerivedClass();\n\n        dc.DeletePerson(Guid.NewGuid());\n    }\n}	0
3106776	3106731	How to check current mouse button state using Win32/User32 library?	[DllImport("user32.dll")]\npublic static extern short GetAsyncKeyState(UInt16 virtualKeyCode);	0
9291173	9291063	Using reflection to find constructors that have interface parameters	var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()\n    .Where(x =>\n        x.GetTypes().Any(y =>\n            typeof(PluginBase).IsAssignableFrom(y) &&\n            y.GetConstructors().Any(z =>\n                z.GetParameters().Count() == 1 && // or maybe you don't want exactly 1 param?\n                z.GetParameters().All(a => a.ParameterType.IsInterface)\n            )\n        )\n    );	0
8800386	8800212	Calling the on-screen keyboard using a button in C#	System.Diagnostics.Process.Start("osk.exe");	0
20287427	20269442	Datagrid inside datagrid - With filter based on parent datagrid value	foreach (var s in allShipments)\n        {\n            var svm = new ShipmentVM\n            {\n                Shipment = s,\n                Containers = (new CollectionViewSource { Source = allContainerVMs }).View\n            };\n            svm.Containers.Filter = (o) => (o as ContainerVM).Container.ShipmentID == svm.Shipment.ShipmentID;\n            allShipmentVMs.Add(svm);\n        }	0
13107304	13107064	How do I pass parameter to ViewModel's constructor in a WPF application?	Initalize(int Id)	0
28406691	28274084	How to take a image url from a datagridview and put it into a picturebox in c#	private void dgData_CellContentClick(object sender, DataGridViewCellEventArgs e)\n    {\n        picData.ImageLocation = dgData.CurrentRow.Cells[1].Value.ToString();\n        picData.SizeMode = PictureBoxSizeMode.StretchImage;\n    }	0
16582872	16582527	How to select specified page index in grid view	protected void Page_Load(object sender, EventArgs e)\n{\n   grvEm2Application.PageIndex = Convert.ToInt32(Request.QueryString["pageIndex"].ToString());  \n   fillGridOnLoad(); // it fills a grid view  with data\n}	0
32652700	32651453	I've made an unbeatable Tic Tac Toe AI, but I'd want to make it "dumber"	If(some stuff && difficulty.In("HARD", "INSANE")) \n    OppositeCorner();	0
22027464	22027318	Writing a recursive function in C# to create a string from characters	static string funcName(int n)\n{\n    if (n<10)\n        return (n%10).ToString();\n    return (n%10).ToString() + funcName(n/10);\n}	0
32081681	32079820	Select common value in navigation table using LINQ lambda expression	public InvestigatorGroup GetCommonGroup(string userId, string investigatorUserId)\n    {\n        using (GameDbContext entityContext = new GameDbContext())\n        {\n            IEnumerable<InvestigatorGroup> userGroups = entityContext.InvestigatorGroups\n                .Where(i => i.IsTrashed == false)\n                .Include(i => i.InvestigatorGroupUsers)\n                .Where(i => i.InvestigatorGroupUsers.Any(e => e.UserId.Contains(userId)))\n                .OrderByDescending(i => i.InvestigatorGroupId);\n\n            return userGroups.Where(i => i.InvestigatorGroupUsers.Any(e => e.UserId.Contains(investigatorUserId))).FirstOrDefault();\n\n        }\n    }	0
4464968	4464874	Substitute for Microsoft Data Access ApplicationBlocks obsolete SqlHelper class	var database = new SqlDatabase("<connection>");\nusing (var reader = database.ExecuteReader(...))\n{\n\n}	0
2971073	2971055	Left of a character in a string in C#	string email = "feedback@abc.comm";\nint index = email.IndexOf("@");\nstring user = (index > 0 ? email.Substring(0, index) : "");	0
23591806	23591679	C# xml linq query results formatting	public IEnumerable<string> getGenres()\n{\n    var genres = (from item in data.Descendants("genre")\n                 select item.Value).Distinct();\n\n    return genres.ToArray();\n}	0
18560970	18560959	how do round int with Ceiling	int x = 121;\n int y = (int)Math.Ceiling((double)x/8);	0
32020302	32020105	How can I parse specific text from a string?	string ipaddress = ipaddresses[i].Substring(0,ipaddresses[i].LastIndexOf("=")+1);	0
18866588	18866554	LINQ to XML - check for null?	from item in _documentRoot.Descendants("MyItems")\nlet idAttr = item.Attribute("id")\nselect new MyClass\n{\n    XMLID = idAttr != null ? idAttr.Value : string.Empty\n}).ToList<MyClass>();	0
26176914	26175688	How to use C# Facebook SDK call ids_for_business api?	protected void Button2_Click(object sender, EventArgs e)
\n{
\n  var fb = new FacebookClient();
\n  dynamic result = fb.Get("/v2.0/me/ids_for_business", new
\n  {
\n    client_id = "xxxxxxxxxxxxxxxxxxxxxx",
\n    client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
\n    access_token = Session["at"].ToString(),
\n    redirect_uri = "http://localhost:34025/WebForm1.aspx"
\n  });
\n  Label1.Text = "business ids:<br/>" + result.data;
\n
\n}	0
34230504	34230294	An Entity with identical table data	public abstract class Account\n{\n    // common entity code here\n    ...\n}\n\npublic class InvoicedAccount : Account {}\npublic class NonInvoicedAccount: Account {}\n\npublic YourContext : DbContext\n{\n    public DbSet<InvoicedAccount> InvoicedAccounts { get; set; }\n    public DbSet<NonInvoicedAccount> NonInvoicedAccounts { get; set; }\n\n    protected override void OnModelCreating( DbModelBuilder modelBuilder )\n    {\n        modelBuilder.Entity<InvoicedAccounts>().Map( m =>\n        {\n            m.MapInheritedProperties();\n            m.ToTable( "InvoicedAccountTable" );\n        } );\n\n        modelBuilder.Entity<NonInvoicedAccounts>().Map( m =>\n        {\n            m.MapInheritedProperties();\n            m.ToTable( "NonInvoicedAccountTable" );\n        } );\n    }\n}	0
18680484	18680432	Attempting to generate a alphabetic character string of varied length but am unable to successfully output	buffer=new string(buffer).PadLeft(paddingAmount,paddingCharacter).ToCharArray();	0
13417001	13414306	Passing additional information from SoapExtension to WebMethod implementation	[WebService]\npublic class ExampleWebService\n{\n    public CredentialContainer Container { get; set; }\n\n    [WebMethod]\n    [SoapHeader("Container")]\n    public void PerformSomething(string value)\n    {\n        var actualWebServiceClient = new MyWebServiceClient(Container.Url, ...);\n        actualWebServiceClient.SendValue(value);\n    }\n}\n\npublic class CredentialContainer : SoapHeader\n{\n    public string Url { get; set; }\n    ...\n}	0
4692904	4692789	Using WHMCS API with a C# .NET Application	// Instantiate the WebClient object\n WebClient WHMCSclient = new WebClient();\n\n // Prepare a Name/Value collection to hold the post values\n NameValueCollection form = new NameValueCollection();      \n form.Add("username", username);\n form.Add("password", password); // the password will still need encoding is MD5 is a requirement\n form.Add("action", "addinvoicepayment"); // action performed by the API:Functions\n form.Add("invoiceid", "1");\n form.Add("transid", "TEST");\n form.Add("gateway", "mailin");\n\n // Post the data and read the response\n Byte[] responseData = WHMCSclient.UploadValues("http://www.yourdomain.com/whmcs/includes/api.php", form);      \n\n // Decode and display the response.\n Console.WriteLine("\nResponse received was \n{0}",Encoding.ASCII.GetString(responseData));	0
32750248	32750162	Choosing initially selected value for a ComboBox with a List of KeyValuePair as DataSource	ComboBox comboBox = new ComboBox();\n\nprotected override void OnLoad(EventArgs e) {\n  comboBox.SelectedValue = 2;\n  base.OnLoad(e);\n}	0
14473989	14461812	XLinq: Copying element from one xml to other	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    public class Program\n    {\n        public static void Main()\n        {            \n            XElement a = XElement.Load("c:\\a.xml");\n            XElement b = XElement.Load("c:\\b.xml");\n            IEnumerable<XElement> c = b.Descendants().Except(a.Descendants());\n            foreach (XElement ele in c)\n            {\n                if (ele.HasElements == false)\n                {\n                    Console.Write(string.Format("Element: {0}\nValue: {1}\n", ele.Name.LocalName,  ele.Value));\n                }\n            }\n            Console.ReadKey();            \n        }\n    }\n}	0
3671593	3620927	How to use EzAPI FlatFile Source in SSIS?	pkg.SrcConn.Unicode = (fileFormat == FileFormat.UNICODE);\n\n       pkg.SrcConn.ConnectionString = srcFile;\n\n       pkg.SrcConn.Columns.Add().DataType = dataType;\n\n       pkg.SrcConn.Columns[0].ColumnType = "Delimited";\n\n       pkg.SrcConn.ColumnNamesInFirstDataRow = false;\n\n       pkg.SrcConn.ColumnDelimiter = ",";\n\n       pkg.SrcConn.RowDelimiter = "\r\n";\n\n       pkg.SrcConn.TextQualifier = "\"";\n\n       pkg.SrcConn.Columns[0].TextQualified = testObject.textQualified;\n\n       if (!pkg.Source.OutputColumnExists("col0"))\n\n       {\n\n           pkg.Source.InsertOutputColumn("col0");\n\n       }\n\n       pkg.Source.SetOutputColumnDataTypeProperties("col0", dataType, testObject.length, testObject.precision, testObject.scale, testObject.codePage);	0
11812304	11806877	How to set Custom View as Default View for SharePoint List?	SPView yourView = CurrentList.Views[UserView];\nyourView.DefaultView = true;\nyourView.Update();	0
31764739	31761971	Binding the "From" & "To" properties to a control height	myGrid.Visibility = Visibility.Visible;\nDBED.To = DESCRIPTION.ActualHeight + 4;\nDBED2.From = DESCRIPTION.ActualHeight + 4;	0
31860942	31860837	Converting query to lambda expression with joins and where clause	var result = Workspace.Prospects.Where(x=> x.NewId == 3)\n                  .Join(Workspace.Users.Where(x => x.IsActive == 1),\n                          p => p.UserId,\n                          u => u.Id,\n                          (p, u) => new { p.Id, p.UserId, p.NewId, p.Status })	0
8898067	8897448	How to update database when changes happen in datagridview	SqlCommand command = null;\ntry\n{\n  if (con.State == ConnectionState.Closed)\n  {\n      con.Open();\n  }\n\n  string updateQuery = @"UPDATE Hucre set VericiKB=@VericiKB \n         WHERE OrtamKB=@OrtamKimlikBilgisi and HucreKB=@HucreKB";\n  command = new SqlCommand(updateQuery, con);\n  command.Parameters.AddWithValue("@VericiKB", "VericiKB");//pass a variable here \n  SqlParameter param1 = command.Parameters.AddWithValue("@HucreKB", "HucreKB");//pass a variable here\n  SqlParameter param2 = command.Parameters.AddWithValue("@OrtamKB", "OrtamKB");//pass a variable here\n  param1.SourceVersion = DataRowVersion.Original;\n  param2.SourceVersion = DataRowVersion.Original;\n  //what is this ..??? da.UpdateCommand = command;\n  command.ExecuteNonQuery;\n }\n catch (Exception e)\n {\n    //Write or trap your exception here..\n }	0
34568370	34568316	inserting image in db table failes	BEGIN\n     UPDATE Person \n         SET [CompanyLogo] = (SELECT TestCompanyLogo.* \n                              FROM OPENROWSET(BULK 'd:\test.png', SINGLE_BLOB) TestCompanyLogo)                    \nEND	0
595854	595793	Best way to update a LINQ model coming from a form	public ActionResult Edit( int id )\n{\n      Person person = peopleService.GetPerson(id);\n      UpdateModel(person,new string[] { list of properties to update } );\n      peopleService.SavePerson(person);\n\n      ...\n}	0
32661332	32661297	How to get Label text from a list of controls	foreach (Label lbl in dvPurchaseOrder.Controls.OfType<Label>().Cast<Label>())\n{\n    lbl.Text = "";//Or other properties of the Label\n}	0
24560408	24560370	How can i compare two Lists for identical links?	HashSet<string> links = new HashSet<string>();	0
15936960	15932201	Unique identifier always null in Windows Phone Mobile Services	[DataContract(Name = "Alarms")]\npublic class Alarms\n{\n    [DataMember(Name = "id")]\n    public int Id { get; set; }\n\n    [DataMember(Name = "PatientId")]\n    public int PatientId { get; set; }\n\n    [DataMember(Name = "AlarmType")]\n    public string AlarmType { get; set; }\n\n    [DataMember(Name = "AlarmDate")]\n    public DateTime AlarmDate { get; set; }\n\n    [DataMember(Name = "AlarmName")]\n    public string AlarmName { get; set; }\n\n    [DataMember(Name = "IsEnabled")]\n    public bool IsEnabled { get; set; }\n}	0
8475720	8453036	Is there a way to safely determine max textures of XNA TextureCollection?	myDevice.GraphicsDeviceCapabilities.MaxSimultaneousTextures	0
164270	164192	How to get Single XElement object using Linq to Xml?	xdoc.Descendants()\n    .Where(x => x.HasAttribute("id") && x.Attribute("id")==id)\n    .Single();	0
15802760	15802692	How to send a string to report (*.rdlc)	var val = new ClassWithValueProperty { Value = "StringForReport" };\nreturn new List<ClassWithValueProperty> { val };	0
9284849	9284633	WIQL: How to get the content of a field of a work item returned by a query	WorkItemStore.GetWorkItem(int id)["Original Estimate"]	0
20540705	20540449	How to make global variables?	public class Global \n{\n    private static readonly Global instance = new Global();\n    public static Global Instance\n    {\n        get\n        {\n            return instance;\n        }\n    }\n\n    Global()\n    {\n    }\n    public string myproperty\n    {\n        get;set;\n    }\n    }	0
15818888	15817512	DataView RowFilter determine if a DateTime column is greater than another DateTime column plus 6 months	DataTable dt = new DataTable("MyTable"); // example data container\n\n...\n\nDataView dv = (from d in dt.AsEnumerable() where ((DateTime)d["A"]) > ((DateTime)d["B"]).AddMonths(6) select d).AsDataView();	0
4327081	4319878	How to get specific Range in Excel through COM Interop?	int startColumn = Header.Cells.Column;\n int startRow = header.Cells.Row + 1;\n Excel.Range startCell = this.sheet.Cells[startRow, startColumn];\n int endColumn = startColumn + 1;\n int endRow = 65536;\n Excel.Range endCell = this.sheet.Cells[endRow, endColumn];\n Excel.Range myRange = this.sheet.Range[startCell, endCell];	0
9590522	9590049	Populate Combobox in winforms (C#) from a range of column header in the dataGridView?	for(i = 2; i < dgv1.Columns.Count) \n{\n    cb.Items.Add(dgv1.Columns(i).HeaderText);\n}	0
34423272	34423195	Not invocable Model Variable on controller Where Statement	public ActionResult Index(string searchString = "")\n    { \n        var db = new ArponClientPosContext();            \n        var lowerSearch = searchString.ToLower();\n        var students = from s in db.Pos\n                   where s.Descripcion.ToLower().Contains(lowerSearch)\n                   select s;\n        return View("~/Views/HomePos/Index.cshtml", students.ToList());\n\n    }	0
34463464	34462367	How to store a column of data in excel to string[] in C#	string[] mColumn = null;\n        List<string> mlstColumn = new List<string>();\n\n        // get used range of column F\n        Range range = excelWorkSheet.UsedRange.Columns["F", Type.Missing];\n\n        // get number of used rows in column F\n        int rngCount = range.Rows.Count;\n\n        // iterate over column F's used row count and store values to the list\n        for (int i = 1; i <= rngCount; i++)\n        {\n            mlstColumn.Add(excelWorkSheet.Cells[i, "F"].Value.ToString());\n        }\n\n        // List<string> --> string[]\n        mColumn = mlstColumn.ToArray();\n\n        // remember to Quit() or the instance of Excel will keep running in the background\n        excelApp.Quit();	0
27923838	27923692	How to handle null values from SQLite DB with C#?	Paid = row.IsNull("Paid") ? 0 : row.Field<int>("Paid");	0
12909591	12909400	C#: How to add details to a DataTable and display it on a DataGridView without storing in the database	DataTable dt = new DataTable();\n    int value = 0;\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        dataGridView1.AutoGenerateColumns = true;\n\n        dt.Columns.AddRange(new DataColumn[]\n            {\n                new DataColumn("column1", typeof(string)),\n                new DataColumn("column2", typeof(int)),\n            });\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n\n        dt.Rows.Add("str value", value++);\n        dataGridView1.DataSource = dt;\n    }	0
24440145	24440074	ASP.NET MVC 4 get value from IQueryable	string Language= service.Get(UserId).Cast<Users>().FirstOrDefault().Language;	0
34138770	34138556	Linq way to check a property of one set against a property of another set	currectAnswers.AddRange(testQuestions.Where(\nt=>listOfQ.Any(l=>l.QuestionId==t.QuestionId && \nl.Answer==t.CorrectAnswer))	0
6236464	6232867	COM exceptions on exit with WPF	Dispatcher.CurrentDispatcher.InvokeShutdown();	0
6371188	6371086	Get string from Server.UrlEncode as uppercase	string url = "http://whatever.com/something";\nstring lower = Server.UrlEncode(url);\nRegex reg = new Regex(@"%[a-f0-9]{2}");\nstring upper = reg.Replace(lower, m => m.Value.ToUpperInvariant());	0
11078975	11078946	Getting Enum type from string	public static Type GetType(\n    string typeName\n)	0
11399985	11399863	create a query for date and average values	var query0 = from c in dc.Prices\n             where Convert.ToDateTime(c.data).CompareTo(left) >= 0\n                   && Convert.ToDateTime(c.data).CompareTo(right) <= 0\n                   && c.idsticker.Equals(x)\n              group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }\n                    into groupMonthAvg\n              select new\n              {\n                  years = groupMonthAvg.Key.Year,\n                  months = groupMonthAvg.Key.Month,\n                  prices = groupMonthAvg.Average(x=>x.value)\n              };	0
1548617	1548583	How do I create a view from a generic list?	void MyMethod(List<T> items)\n{\n    foreach(T item in items)\n    {\n    Html.RenderPartial(item.GetType().Name, item);\n    }\n}	0
2802134	2802127	how to append " in string in c#	String myStr = "Hello World";\nmyStr += "\"";	0
11626111	11625938	how to loop over generic List<T> and group per 3 items	for (var i = 0; i < Jobseekers.Count; i += 3)\n{\n    foreach (MemberProfile jobseekerProfile in Jobseekers.Skip(i).Take(3))\n    {\n\n    }\n}	0
1119075	1119055	wpf: change font size for WebBrowser control	public IHTMLDocument2 Document\n {\n     get\n     {\n           return webBrowser.Document as IHTMLDocument2;\n     }\n }\n...\nDocument.execCommand("FontSize", false, doubleValue.ToString())	0
3542249	3542237	Quick way to get the contents of a MemoryStream as an ASCII string	using (var stream = new MemoryStream())\n{\n    /* Write a JSON string to stream here */\n\n    string jsonString = Encoding.ASCII.GetString(stream.ToArray());\n}	0
29650441	29632626	MailKit Imap Get only messageId	var summaries = client.Inbox.Fetch (0, -1, MessageSummaryItems.Envelope);\nforeach (var message in summaries) {\n    Console.WriteLine (message.Envelope.MessageId);\n}	0
19681528	19681285	Removing XML node with no Descendants	var xDoc = XDocument.Load("input.xml");\n    xDoc.Descendants()\n        .Where(d => d.Name.LocalName == "line_item" && !d.HasElements)\n        .ToList()\n        .ForEach(e => e.Remove());	0
26797213	26796405	How to save a bitmapimge from url to an object of bitmap in wp8.1?	// Create source.\n        BitmapImage bImage = new BitmapImage();\n        bImage.UriSource = new Uri(@"https:www.example.com/folders/file.jpg", UriKind.RelativeOrAbsolute);\n\n        // Set the image source.\n        MyImage.Source = bImage;	0
16528287	16528082	Determine if a derived class implements a generic interface with itself as the generic parameter	//get the two types in question\nvar typeB = b.getType()\nvar typeA = typeB.BaseType;\nvar interfaces = typeA.GetInterfaces();\n\n//if the length are different B implements one or more interfaces that A does not\nif(typeB.GetInterfaces().length != interfaces.length){\n   return false;\n} \n\n//If the list is non-empty at least one implemented interface satisfy the conditions\nreturn (from inter in interfaces\n        //should be generic\n        where inter.IsGeneric\n        let typedef = inter.GetGenericTypeDefinition()\n        //The generic type of the interface should be a specific generic type\n        where typedef == typeof(IKnownInterface<>) &&\n        //Check whether or not the type A is one of the type arguments\n              inter.GetGenericTypeArguments.Contains(typeA)).Any()	0
12601685	12600908	Make column value as Header Columns	// build the new data table\nvar result = new DataTable();\nresult.Columns.Add("KundeID", typeof(Int32));\nresult.Columns.Add("KundeName", typeof(String));\nresult.Columns.Add("Comment", typeof(String));\nresult.Columns.AddRange(\n    (from c in \n         (from r in table.AsEnumerable() \n          where !r.IsNull("Produkt") && !string.IsNullOrEmpty(r.Field<string>("Produkt")) \n          select r.Field<string>("Produkt")).Distinct()    // added DISTINCT\n     select new DataColumn(c, typeof(bool))).ToArray()\n);\n\nforeach (var r in results)\n{\n    var productIndex = result.Columns.IndexOf(r.Produkt);\n    var vals = new List<object>() { r.KundeID, r.KundeName, r.Comment };\n    for (int i = 3; i < result.Columns.Count; i++)\n    {\n        if (i == productIndex)\n        {\n            vals.Add(true);\n        }\n        else\n        {\n            vals.Add(false);\n        }\n    }\n\n    result.LoadDataRow(vals.ToArray(), true);\n}	0
10331315	10331178	how to get event of change in enum value?	public enum PersonName\n  {\n      Eric,\n      George,\n      David,\n      Frank\n  }\n\n  private PersonName myPersonName\n\n  public PersonName MyPersonName\n  {\n      get { return myPersonName; }\n      set\n      {\n          myPersonName = value;\n          //simply call what you want done\n          PersonNamePropertyChanged();\n      }\n  }	0
3163182	3163166	asking for a XPath query string	//Node[normalize-space(text())="File and Folder Items"]/Node[1]	0
4430173	4430121	c# winform control access modifiers	public class MyForm : Form\n{\n  public MyForm()\n  {\n    InitializeComponenents();\n\n    MyButton = new Button { Text = "GO" } ;\n    this.Controls.Add(MyButton);\n  }\n\n  public Button MyButton { get; private set; }\n}	0
15096553	15095687	Looping through a regex replace	Regex needle = new Regex("\[letter\]");\nstring haystack = "123456[letter]123456[letter]123456[letter]";\nstring[] replacements = new string[] { "a", "b", "c" };\n\nint i = 0;\nwhile (needle.IsMatch(haystack))\n{\n    if (i >= replacements.Length)\n    {\n        break;\n    }\n\n    haystack = needle.Replace(haystack, replacements[i], 1);\n    i++;\n}	0
6434878	6402790	MySql's Exception : Variable 'character_set_client' can't be set to the value of 'utf16'	"server=localhost;database=maindb;uid=root;pwd=abc123;CharSet=utf8; port=3306";	0
20174485	17426679	Very bad SQLite performance on Windows Phone 8	await stmt.StepAsync().AsTask().ConfigureAwait(false))	0
16898819	16898731	Creating an JSON array in C#	new {items = new [] {\n    new {name = "command" , index = "X", optional = "0"}, \n    new {name = "command" , index = "X", optional = "0"}\n}}	0
5657081	5657056	convert string to DateTime in C# with EDT at the end	var parsed = DateTime.ParseExact("Wed, 13 Apr 2011 07:11:04 -0400 (EDT)", \n                                 "ddd, dd MMM yyyy HH:mm:ss zzz", null);	0
6322622	6322606	Check if the digits in a number are in ascending order	/012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210/	0
9681981	9681828	Access an item of Array of class using a member variable in place of index in C#	class ABCCollection : List<ABC>\n{\n  public ABC this[int id]\n  {\n    get { return this.Where(abc => abc.ID == id).FirstOrDefault(); }\n  }\n}	0
17725275	17724954	Given a vector, calculate a point at distance l	// Origin point (2, 3)\n  Double origin_x = 2.0;\n  Double origin_y = 3.0;  \n\n  // Point you are moving toward\n  Double to_x = 9.0;\n  Double to_y = 9.0;\n\n  // Let's travel 10 units \n  Double distance = 10.0;\n\n  Double fi = Math.Atan2(to_y - origin_y, to_x - origin_x);\n\n  // Your final point\n  Double final_x = origin_x + distance * Math.Cos(fi);\n  Double final_y = origin_y + distance * Math.Sin(fi);	0
5674013	5673842	c# skype4com how to write a status near my online icon?	using SKYPE4COMLib;\n\nnamespace SO5673842\n{\n    class Program\n    {\n        static void Main()\n        {\n            var skype = new Skype();\n            skype.CurrentUserProfile.MoodText = "Hello!";\n        }\n    }\n}	0
22645395	22636602	How to return HTTP 429?	throw new WebFaultException((System.Net.HttpStatusCode)429);	0
31596604	31596572	Splitting on multiple characters at once	string[] s = someString.Split(new [] { ',', '\n' });	0
1861259	1861195	Ctrl key press condition in WPF MouseLeftButtonDown event-handler	private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {\n        if(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) {\n            MessageBox.Show("Control key is down");\n        } else {\n            MessageBox.Show("Control key is up");\n        }\n    }	0
30046642	30046496	How to iterate through textboxes and apply calculations	private void sumTextBoxes()\n{\n    TextBox[] txt;\n    txt = new TextBox[] { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10 };\n\n    double sum = 0;\n    double value;\n\n    foreach (TextBox tb in txt)\n    {\n        if (tb !=null)\n        {\n            if (double.TryParse(tb.Text, out value))\n            {\n                sum += value;\n            }\n        }\n    }\n\n    textBox11.Text = sum.ToString();\n}	0
19941387	19939655	Insert piped SQL data into XML	var myXML = @"<?xml version='1.0' encoding='UTF-8'?>\n<call method="load">\n<credentials login="sampleuser"/>\n<importDataOptions jobsize="false"/>\n<version name="12" isDefault="false" />\n<rowData>";\n\nvar firstRow = true;\n\nwhile(dataset.hasrows){\n    if(firstRow)\n    {\n        firstRow = false;\n        myXML+= "<header>" + 1st row from the data set + "</header><rows>";\n    }\n    else\n    {\n        myXML+= "<row>"+ Nth row from dataset here+"</row>";\n    }\n}\n\nmyXML += @"</rows>\n</rowData>\n</call>";	0
1612563	1612358	Linq-To-Sql issue with datetime?	# High precision datetime fields are used. The solution is to set	0
21756317	21756182	Invalid object name when inputting data from .aspx into sql server	SqlCommand xp = new SqlCommand("Insert into userdatabase(Username, Email,\n    Password)Values(@Username, @Email, @Password)", User);\n                xp.Parameters.AddWithValue("@Username", InputUsername.Text);\n                xp.Parameters.AddWithValue("@Email", InputEmail.Text);\n                xp.Parameters.AddWithValue("@Password", InputPassword.Text);	0
10226210	10189574	open a fancybox on pageload	string script = @"<script type=""text/javascript"">$(document).ready(function() {$(""#termsandConditions"").fancybox({'transitionIn':'elastic','transitionOut':'elastic','speedIn':600,'speedOut':200,'overlayShow':false,'overlayOpacity': 0.5,'width':800,'href':""/Contents/Common/EN/TermandConditions.aspx""}).trigger('click');});</script>";\n                    Type cstype = this.GetType();\n                    ClientScriptManager cs = Page.ClientScript;\n\n                    if (!cs.IsStartupScriptRegistered(cstype, script))\n                    {\n                        cs.RegisterStartupScript(cstype, "fancybox", script);\n                    }	0
9097614	9096811	Parsing strings recursively	ResultData Parse(String value, ref Int32 index)\n{\n    ResultData result = new ResultData();\n    Index startIndex = index; // Used to get substrings\n\n    while (index < value.Length) \n    {\n        Char current = value[index];\n\n        if (current == '(')\n        {\n            index++;\n            result.Add(Parse(value, ref index));\n            startIndex = index;\n            continue;\n        }\n        if (current == ')')\n        {\n            // Push last result\n           index++;\n           return result;\n        }\n\n        // Process all other chars here\n    }\n\n    // We can't find the closing bracket\n    throw new Exception("String is not valid");\n}	0
17913974	17894668	How to call a Usercontrol from another in same window in WPF ?	(((control1).Parent as Panel).Children[1] as UserControl)	0
2548001	2547275	mySQL : using BETWEEN in table?	select\n    Time_ID,\n    Lesson_Time\nfrom\n    mydb.clock\nwhere\n    Lesson_Time <= TIME(NOW())\norder by\n    Lesson_Time DESC\nlimit 0, 1	0
3305990	3305875	How to get a partilcular item from a Dictionary object with index?	Dictionary<TKey, TValue>	0
24639612	24639538	Pass an asp web control as a CommandArgument	public void ChangeImage(object sender, CommandEventArgs e)\n{\n      ImageButton imageButton = sender as ImageButton;\n      string imageToChange = e.CommandArgument;\n      //Then you can assign the appropreate image\n      imageButton.ImageUrl = "~/Images/Penguins.jpg";\n\n}	0
4106425	4106369	How do I find the size of a 2D array?	a.GetLength(0);	0
30862738	30862533	How to show unique key exception before saving into database?	protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)\n{\n     var main = (sender as DropDownList);\n\n     foreach (GridViewRow row in gvItemList.Rows)\n     {\n           var ddl = (row.FindControl("ddlItem") as DropDownList);\n\n           if (main.ClientID != ddl.ClientID && ddl.SelectedValue == main.SelectedValue)\n           {\n                row.BackColor = System.Drawing.Color.Red;\n                string script = "alert('already selected!');";\n                ScriptManager.RegisterStartupScript(this, GetType(), \n                  "ServerControlScript", script, true);\n           }\n     }         \n}	0
22386698	22386260	Change Chart control Axis color?	//0 would be indice of chart area you wish to Change, Color.ColorYouWant\nChart.ChartAreas[0].AxisX.LineColor = Color.Red;\nChart.ChartAreas[0].AxisX.LineColor = Color.Red;\n\n//To change the Colors of the interlacing lines you access them like so\nChart.ChartAreas[0].AxisX.InterlacedColor = Color.Red;\nChart.ChartAreas[0].AxisY.InterlacedColor = Color.Red;\n\n//If you are looking to change the color of the Grid Lines\nChart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Red;\nChart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Red;	0
24987082	24987063	How to deep copy a Dictionary containing a List in C#?	var tmpStudents = students.ToDictionary(p => p.Key, p => p.Value.ToList());	0
7423600	7423434	Numbering list elements with Regex in C#	var input = "BLOCK\r\n    LIST1 Lorem ipsum dolor sit amet ...";\n\nvar levels = new List<string> { "BLOCK", "LIST1", "LIST2", "LIST3" };\nvar counter = levels.ToDictionary(level => level, level => 0);\n\n// Replace each key word with incremented counter,\n// while resetting deeper levels to 0.\nvar result = Regex.Replace(input, string.Join("|", levels), m =>\n{\n    for (int i = levels.IndexOf(m.Value) + 1; i < levels.Count; i++)\n    {\n        counter[levels[i]] = 0;\n    }\n    return (++counter[m.Value]).ToString() + ".";\n});	0
21568631	21568583	How can I extract a number from a string if it's next to a percent symbol?	string text = "43-20If you can find a way through the river of magma, I calculate a 60% chance you will arrive at one of the sources of sacred power. Here's another: 100%.";\n\nforeach (Match match in Regex.Matches(text, @"(\d+)%"))\n{\n    Console.WriteLine("Found: " + match.Groups[1].Value);\n}	0
3219931	3219664	How to find global catalog of Active Directory?	Forest.FindAllGlobalCatalogs()	0
25368629	25368573	Best place to put ConnectionString like values	web.config	0
1536756	1536739	Get a Windows Forms control by name in C#	this.Controls.Find()	0
12203942	12203872	Counting the number of cases in a switch statement	MethodInfo.GetMethodBody	0
19574158	19573511	Redirecting after submit from partial view	return RedirectToAction("List", new {\n    hasNationWideLeadPipes = model.HasNationWireLeadpipes,\n    leadtype = model.LeadType\n});	0
6441598	6441455	RichTextBox C# Set caret location winforms	richTextBoxUserText.Text = INITIAL_TEXT;\nrichTextBoxUserText.SelectAll();\nrichTextBoxUserText.SelectionColor = Color.Red;\nrichTextBoxUserText.SelectionProtected = true;\nrichTextBoxUserText.SelectionLength = 0;\nrichTextBoxUserText.SelectionStart = richTextBoxUserText.TextLength + 1;	0
12035977	12035846	Positioning of controls is incorrect on another PC in a Windows Forms application	1. Screen Resolution\n2. System Font Size	0
23051840	23051818	C# Display MessageBox when all items from ComboBox are removed	if (comboBox1.Items.Count == 0)\n        {\n            MessageBox.Show("Your combo is empty");\n        }	0
19435579	19435561	Unable to retrieve GET parameters from Jquery Ajax	public string setJsonValue()\n{\n   string data = Request.Params["jsonData"];\n   return data;\n   //System.Web.HttpContext.Current.Session[param] = value;            \n}	0
8789183	8786003	Proper way of delaying the loading of view until a web request or other long running task completes	class MyViewController : UIViewController {\n     void PlusOne (string url, string username)\n     {\n          ThreadPool.QueueUserWorkItem (delegate {\n              var wc = new WebClient ();\n              wc.UploadString (url, "+1");\n              BeginInvokeOnMainThread (delegate { PlusOneDone (username); });\n\n\n     void PlusOneDone (string username)\n     {\n           Console.WriteLine ("Plus one completed for {0}", username);\n     }\n }	0
7042878	7042318	how to get inbox folder instance?	var folder = Folder.Bind(service, WellKnownFolderName.Inbox);	0
13402259	13402157	EF Code First - Select with Foreign Key	public virtual Bar MyBar { get; set; }	0
10380423	10379641	Creating a part of XML document as a string	var nodes = new XElement("XmlNodes");\nforeach (var i in Enumerable.Range(1,10))\n{\n    nodes.Add(new XElement("ChildNode", \n        new XAttribute("Attribute1", 100), \n        new XAttribute("Attribute2", 200), \n        new XAttribute("Attribute3", 0)));\n}\n\nvar result = nodes.ToString().Replace("\" A", "\"\tA"); // **" A** becomes **"\tA**	0
475731	475725	Filtering list objects from another list	var selectedNames = ... // List of selected names\nvar selectedFields = (from f in fieldList\n                      where selectedNames.Contains(f.objectName)\n                      select f.FieldName).Distinct().ToList();	0
13986493	13986445	insert many files into List Box with different Threads	backgroundWorker = new BackgroundWorker();\nbackgroundWorker.WorkerReportsProgress = true;\nbackgroundWorker.DoWork +=\n(s1, e1) =>\n{\n    string fileToAdd = string.Empty;\n    someClass myClass= new someClass ();\n\n    foreach (string fileName in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))\n    {\n        if (myClass.iAviFormat(fileName))\n        {\n            if (myClass.isCorrectFormat(fileName))\n            {\n                backgroundWorker.ReportProgress(0, fileName);\n                //listBoxFiles.Items.Add(fileName);\n            }\n            else if (!myClass.isCorrectFormat(fileName))\n            {\n                fileToAdd = myClass.getNewFileName(fileName);\n                backgroundWorker.ReportProgress(0, fileToAdd);\n            }\n        }\n    }\n};	0
14958074	14958037	Programatically close TabItem in WPF	tabControl1.Items.RemoveAt(tabControl1.SelectedIndex);	0
31436012	31435656	Putting a stopwatch on a page without using the Form tag?	var h1 = document.getElementsByTagName('h1')[0],\n    start = document.getElementById('start'),\n    stop = document.getElementById('stop'),\n    clear = document.getElementById('clear'),\n    seconds = 0, minutes = 0, hours = 0,\n    t;\n\nfunction add() {\n    seconds++;\n    if (seconds >= 60) {\n        seconds = 0;\n        minutes++;\n        if (minutes >= 60) {\n            minutes = 0;\n            hours++;\n        }\n    }\n\n    h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);\n\n    timer();\n}\nfunction timer() {\n    t = setTimeout(add, 1000);\n}\ntimer();\n\n\n/* Start button */\nstart.onclick = timer;\n\n/* Stop button */\nstop.onclick = function() {\n    clearTimeout(t);\n}\n\n/* Clear button */\nclear.onclick = function() {\n    h1.textContent = "00:00:00";\n    seconds = 0; minutes = 0; hours = 0;\n}	0
12010194	11971402	Copy between two different AWS S3 accounts	"Principal": {\n    "AWS": "arn:aws:iam::1234567890:user/someusername"\n}	0
11718897	11717829	Bind distinct data to repater using linq to object distinct	var uniqueArea =searchresult.Select(m => m.HotelArea).Where(m => !string.IsNullOrEmpty(m)).Distinct();	0
14256015	14255921	MVC3 RegularExpression attribute - How do I refuse brackets	[Required]\n[RegularExpression(@"^[^\[\]]+$", ErrorMessage = "You cannot use '[' or ']' on the title ")]\npublic string Title { get; set; }	0
20296520	20259030	How to perform multiplication on two column for datagrid view and assigning it in third column?	foreach (DataGridViewRow row in dtgVOuchers.Rows)\n            {\n                row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));\n\n            }	0
10284664	10284512	Mapping querystring value as controller in route	routes.MapRoute("MyLang", "{lang}",\n     new { controller = "Home", action = "Home",  }\n\nclass HomeController{\n  public ActionResult Home(string lang)\n  {\n    return View();\n  }\n}	0
12529370	12529341	How can get object from a list<> with a int index?	aux = _list[positionInList];	0
8442063	8441570	C# FileSystemWatcher WaitForChanged Method only detects one file change	static void Main(string[] args)\n    {\n        FileSystemWatcher watcher = new FileSystemWatcher(@"f:\");\n        ManualResetEvent workToDo = new ManualResetEvent(false);\n        watcher.NotifyFilter = NotifyFilters.LastWrite;\n        watcher.Changed += (source, e) => { workToDo.Set(); };\n        watcher.Created += (source, e) => { workToDo.Set(); };\n\n        // begin watching\n        watcher.EnableRaisingEvents = true;\n\n        while (true)\n        {\n            if (workToDo.WaitOne())\n            {\n                workToDo.Reset();\n                Console.WriteLine("Woken up, something has changed.");\n            }\n            else\n                Console.WriteLine("Timed-out, check if there is any file changed anyway, in case we missed a signal");\n\n            foreach (var file in Directory.EnumerateFiles(@"f:\")) \n                Console.WriteLine("Do your work here");\n        }\n    }	0
33987271	33986635	Replacing certain letters with symbol	string texti = string.Empty;\nConsole.WriteLine("");\nConsole.WriteLine("Put in your sentence ..");\ntexti = Console.ReadLine();\n\nConsole.WriteLine("You entered the following ..");\nConsole.WriteLine(texti);\nforeach (char str in texti)\n{\n    switch (str)\n    {\n        case 'A':\n        case 'a':\n        case 'S':\n        case 's':\n        case 'N':\n        case 'n':\n            {\n                break;\n            }\n        default:\n            {\n                texti = texti.Replace(str, '*');\n                break;\n            }\n    }\n}\nConsole.WriteLine("Your new text");\nConsole.WriteLine(texti);	0
9250320	9248110	Dynamic images, preventing cache from the page that generates image	Response.Cache.SetCacheability(HttpCacheability.NoCache);	0
2892880	2892004	How to write to a custom event log?	if (!EventLog.SourceExists("MyApplicationEventLog"))\n{\n    EventSourceCreationData eventSourceData = new EventSourceCreationData("MyApplicationEventLog", "MyApplicationEventLog");\n    EventLog.CreateEventSource(eventSourceData);\n}\n\nusing (EventLog myLogger = new EventLog("MyApplicationEventLog", ".", "MyApplicationEventLog"))\n{\n    myLogger.WriteEntry("Error message", EventLogEntryType.Error);\n    myLogger.WriteEntry("Info message", EventLogEntryType.Information);\n}	0
26878638	26861498	How to load child node on expand kendo treeview	public JsonResult GetNodes(string id)\n    {\n        List<Node> node = new List<Node>();\n        List<string> drivers=new List<string>();\n        if (string.IsNullOrEmpty(id))\n        {\n            drivers.AddRange(Directory.GetLogicalDrives());\n        }\n        else\n        {\n            if(Directory.Exists(id))\n                drivers.AddRange(Directory.GetDirectories(id));\n        }\n\n            try\n            {\n                for (int i = 0; i < drivers.Count; i++)\n                {\n                    Node item = new Node();\n                    DirectoryInfo dirInfo = new DirectoryInfo(drivers[i]);\n                    item.id = dirInfo.FullName;\n                    item.Name = dirInfo.Name;\n                    item.hasChildren = HasNodes(drivers[i]);\n                    node.Add(item);\n                }\n            }\n            catch { }\n\n        return Json(node, JsonRequestBehavior.AllowGet);\n    }	0
18193706	18193248	Redirecting to a page using mvc	return RedirectToAction("Index", "Rental");	0
26306772	26306642	WinForms data binding to a custom property throws an exception	public bool CanEdit\n{\n    get { return this._CurrentRecord.CanEdit(); }\n}	0
29512383	29512149	Paging with PagedList, is it efficient?	IQueryable<Result> allResults = MyRepository.RetrieveAll();\n\nvar resultGroup = allResults.OrderByDescending(r => r.DatePosted)\n                                               .Skip(60)\n                                               .Take(30)\n                                               .GroupBy(p => new {Total = allResults.Count()})\n                                               .First();\n\nvar results = new ResultObject\n{\n    ResultCount = resultGroup.Key.Total,\n    Results = resultGrouping.Select(r => r)\n};	0
33562189	33551370	How to allocate multiple arrays in shared memory	__shared__.Array2D	0
15704734	15704607	Syntax error in INSERT INTO Statement while trying to input values in the Database	string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, [Username], [Password], [Email], [Address], City, Country, Zipcode)" +\n     " values (@p1, @p2, @p3,@p4, @p5,@p6, @p7,@p8,@p9,@p10)";	0
16809188	16807182	How much would it take for a C# TcpClient - TcpListener Server to overload?	Write({8 bytes});\n...\nWrite({12 bytes});\n...\nWrite({8 bytes});	0
13144337	13144228	How to get file path of content in class library	typeof(Some.Type.From.That.Assembly).Assembly.Location	0
13087911	13087808	How to seperate C# data connection code into a class file	private void button2_Click(object sender, EventArgs e) \n   {\n        DataRetriever dr = new DataRetriever();\n        DataSet fg = dr.GetData(comboBox.Text);\n        label1.Text = "No. of Rows:-    " + fg.Tables[0].Rows.Count.ToString();\n        dataGridView1.DataSource = fg.Tables[0];\n    }\n\npublic class DataRetriever\n{\n    public void GetData(string text)\n    {\n        OleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=c://library//lib.mdb");\n\n        OleDbDataAdapter cmd = new OleDbDataAdapter("select * from entry where LTRIM(subjet)=?", cn);\n        cmd.SelectCommand.Parameters.AddWithValue("1", text);\n        DataSet fg = new DataSet();\n        cmd.Fill(fg);\n   }\n}	0
14228704	14228651	Setting color by random number asp.net	private void GetRandColor()\n    {\n        Random r = new Random(DateTime.Now.Millisecond);\n\n        System.Drawing.Color[] colours = \n        {\n            System.Drawing.Color.Yellow, \n            System.Drawing.Color.LightGreen, \n            System.Drawing.Color.LightCyan,\n            System.Drawing.Color.LightSalmon,  \n            System.Drawing.Color.LightSkyBlue\n        };\n\n        int i = r.Next(0, colours.Length - 1);\n\n        System.Drawing.Color c = colours[i];\n\n        Button1.BackColor = c;\n    }	0
1209957	1209918	C# Accessing field syntax	FieldInfo ageField = typeof(Person).GetField("age");\nint age = (int) field.GetValue(person);	0
442170	435629	Castle Windsor - One class implementing multiple interfaces	AddComponent<>	0
5485843	5375370	Wrapper for DOTNET to native written in C++ CLI BestWay to pass strutures?	//signature\nvoid someFunction(SDATUM datum);\n\nvoid someFunctionWrapper(SDATUM datum){\npin_ptr<SDATUM>  datum_pin=&datum;\n\n\n//::SDATUM refers to the C-Type\nsomeFunction(*(::SDATUM*)datum_pin);\n}	0
8126576	8126396	How to tell Machine.Fake to satisfy a dependency with a given type	Establish context = () =>\n{\n    Configure(x => x.For<IFileProcesser>().Use<FileProcesser>());\n};	0
748398	748387	How to remove a stack item which is not on the top of the stack in C#	public class ItsAlmostAStack<T>\n{\n    private List<T> items = new List<T>();\n\n    public void Push(T item)\n    {\n        items.Add(item);\n    }\n    public T Pop()\n    {\n        if (items.Count > 0)\n        {\n            T temp = items[items.Count - 1];\n            items.RemoveAt(items.Count - 1);\n            return temp;\n        }\n        else\n            return default(T);\n    }\n    public void Remove(int itemAtPosition)\n    {\n        items.RemoveAt(itemAtPosition);\n    }\n}	0
17980417	17971601	does RemoveFromVisualTree sets all child controls to null?	System.Windows.Media.Visual	0
13347897	13335243	How to get last updated document in MongoDB with official C# driver	var query = Query.And(Query.GTE("age", 26), Query.EQ("taken", false));\nvar update = Update.Set("taken", true);\n\nvar result = collection.FindAndModify(\n    query, \n    update, \n    true // return new document\n);\n\nvar chosenDoc = result.ModifiedDocument;	0
24165523	24163988	How to Draw a Ray Along a Sprite in Unity	public Transform Head;\npublic Transform Hand;\npublic Transform Chest;	0
2730351	1798069	WCF Error : Manual addressing is enabled on this factory, so all messages sent must be pre-addressed	var factory = new ChannelFactory<IService>(new WebHttpBinding(), uri);\nfactory.Endpoint.Behaviors.Add(new WebHttpBehavior());\nvar proxy = factory.CreateChannel();	0
2844419	2844371	Allow user to only input text?	if (!char.IsLetter(e.KeyChar)) {\ne.Handled = true;\n}	0
3162068	3161959	In C# is there a way retrieve only built-in data type properties using reflection	var props = sourceType.GetProperties()\n    .Where(pi => .PropertyType.IsPrimitive\n              || pi.PropertyType == typeof(string))	0
5043333	5043220	.NET Read ReportParameter from Local report	List<ReportParameterInfo> parameters = ReportViewer1.LocalReport.GetParameters().Where(t => t.Name == "UserComments").ToList();\n    ReportParameterInfo userCommentsParams = parameters[0];\n    string comments = userCommentsParams.Values[0];	0
6922335	4781323	How do you create an MS Access table in C# programmatically?	CREATE TABLE MyTable (\n               [Count] AUTOINCREMENT NOT NULL PRIMARY KEY ,\n               [TimeAndDate] TIMESTAMP NOT NULL ,\n               [SerialNumber] VARCHAR( 14 ) NOT NULL ,\n               [Result] BIT NOT NULL ,\n               UNIQUE ([TimeAndDate]));	0
4903861	4903837	Using LINQ to generate a random size collection filled with random numbers	Random _rand = new Random();\nvar results = Enumerable.Range(0, _rand.Next(100))\n                        .Select(r => _rand.Next(10))\n                        .ToList();	0
11857824	11857721	c# list of interface with generic items	foreach (dynamic item in myList) \n{ \n    var value = item.Value; \n}	0
9317261	9317208	Working with date in C#	isOpen = (NOW > OpenTime AND NOW < (ClosingTime < OpeningTime ? ClosingTime + 24.00 : ClosingTime)	0
19430662	19430516	Asp.net controls not updating after a postback	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        //populate controls with data from database\n    }\n}	0
10380470	10247803	WCF REST Service - Replace a string parameter with a class instance on every method?	var wcfAccountRequired = instance as IWcfAccountRequired;\n        if (wcfAccountRequired != null)\n        {\n            (wcfAccountRequired).Account = Account;\n        }	0
33412206	33412090	Update Data in mdb Table	command.CommandText = "update " + user + " set [Date] =@Date [Text], [Begin] =@Begin [Text], [End] =@End [Text], [Pause] =@Pause [Text], [Worktime] =@Worktime [Text] where ID = @ID;";	0
26430266	26429955	XML serialize base class without knowing derived class	public class Serializer\n{\n    private static string Serialize(Base baseData)\n    {\n        var mappedBase = new Base();\n        // Do mapping\n        mappedBase.Foo = baseData.Foo;\n\n        var serializer = new XmlSerializer(typeof(Base));\n        var sb = new StringBuilder();\n        using (var writer = XmlWriter.Create(sb))\n        {\n            serializer.Serialize(writer, mappedBase);\n        }\n        return sb.ToString();\n    }\n\n    private static string Deserialize(...) { ... }\n}	0
5274157	5274140	Convert code from VB into C#	public event EventHandler<BidEventInfo> SendNewBid;	0
3478228	3477544	Changing dataset connection string at runtime	_myAdapter.Connection.ConnectionString = connectionString;	0
26676333	26676295	how join multiple cases into the switch statement	enum Day\n{\n    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday\n}\n\nprivate string Do(Day day)\n{\n    switch (day)\n    {\n        case Day.Monday:\n        case Day.Wednesday:\n        case Day.Friday:\n            return "Study";\n        case Day.Tuesday:\n        case Day.Thursday:\n            return "Play Futbol";\n        default: \n            return "Party";\n    }\n}	0
3134089	3134049	is there a way to remove the first line from a StreamReader	using (var sr = new StreamReader("data.csv")) {\n    sr.ReadLine();\n    using (var csv = new CsvReader(sr, true)) {\n        // etc..\n    }\n}	0
1665856	1665832	Get date of first Monday of the week?	DateTime input = //...\nint delta = DayOfWeek.Monday - input.DayOfWeek;\nDateTime monday = input.AddDays(delta);	0
9998758	9471463	Symbol MT2070 scanner receiving data from PC	myScannerSvcClient.SetAttributeByte(\n    (ushort)ATTRIBUTE_NUMBER.ATT_MIA_HOSTNUM,\n    (byte)ENUM_HOSTS.HOST_RAW\n    );	0
33214916	33214785	connection from menu doesnt work	NavigateURL="~/Vendor.aspx"	0
2692286	2692257	WCF Host as windows service faults	service.msc	0
21096205	21094267	LinqToTwitter Multiple User Authorizer	var auth = new SingleUserAuthorizer\n        {\n            Credentials = new SingleUserInMemoryCredentials\n            {\n                ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],\n                ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],\n                TwitterAccessToken = ConfigurationManager.AppSettings["twitterAccessToken"],\n                TwitterAccessTokenSecret = ConfigurationManager.AppSettings["twitterAccessTokenSecret"]\n            }\n        };	0
4605786	4605514	Timeout for individual tests in NUnit	Assert.That(actual, Is.EqualTo(expected).After(5000, 50));	0
25200282	25200191	Objects showing without LINQ	using System.Linq	0
7901960	7898790	Database design for Multi level Rolebased authorization	Item     Type  GroupId     C R U D\n   Form001    F    ALL_USERS   N Y N N\n   Form001    F    Sales       N R U N\n   Form002    F    Admin       N Y Y Y\n   All_FORMS  T:F  Admin       Y Y Y Y\n   Tab-045A   D    Sales       Y Y Y Y	0
2229111	2228845	Is it possible (with Moq) to stub method calls with Lambda parameters?	repository.Setup(x => x.Where(It.IsAny<Func<T, ISpecification<T>>()).Returns(list);	0
5991526	5989617	DataTable.Select expression fails using DateTime equals filter	query += string.Format(" AND ChangeToDT = #{0}#", ChangeDetected.ToString("MM/dd/yyyy"));	0
13826791	13826741	Convert List<List<int>> to double[][]	double[][] doubles = ints.Select(x => x.Select(y => (double)y).ToArray())\n                         .ToArray();	0
10694274	10381863	C# draw line from circle edge to circle edge	public static PointF getPointOnCircle(PointF p1, PointF p2, Int32 radius)\n    {\n        PointF Pointref = PointF.Subtract(p2, new SizeF(p1));\n        double degrees = Math.Atan2(Pointref.Y, Pointref.X);\n        double cosx1 = Math.Cos(degrees);\n        double siny1 = Math.Sin(degrees);\n\n        double cosx2 = Math.Cos(degrees + Math.PI);\n        double siny2 = Math.Sin(degrees + Math.PI);\n\n        return new PointF((int)(cosx1 * (float)(radius) + (float)p1.X), (int)(siny1 * (float)(radius) + (float)p1.Y));\n    }	0
20691795	20659248	Adding namespaces to XmlDocument using XmlNamespaceManager	public void addXmlns()\n{\n    string xml = @"<?xml version=""1.0""?>\n                    <kml>\n                    <Document>\n                    <Placemark>\n                    </Placemark>\n                    </Document>\n                    </kml>";\n\n    var xmldoc = new XmlDocument();\n\n    xmldoc.LoadXml(xml);\n\n    xmldoc.DocumentElement.SetAttribute("xmlns", "http://www.opengis.net/kml/2.2");\n    xmldoc.DocumentElement.SetAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2");\n    xmldoc.DocumentElement.SetAttribute("xmlns:kml", "http://www.opengis.net/kml/2.2");\n    xmldoc.DocumentElement.SetAttribute("xmlns:atom", "http://www.w3.org/2005/Atom");\n    xmldoc.DocumentElement.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");\n\n    string message;\n    message = xmldoc.InnerXml;\n\n    MessageBox.Show(message); // shows the updated xml  \n}	0
34333044	34332961	How can i dispose IDisposable when it is declared in a parameter?	using (var attachment1 = new System.Net.Mail.Attachment(path1))\nusing (var attachment2 = new System.Net.Mail.Attachment(path2))\n{\n    SendEmail("message", "subject", attachment1, attachment2);\n}	0
20627334	20627186	Using foreach and hashtable to find common element in three arrays	int[] a = new int[] { 1, 2, 3, 4, 5 };\n int[] b = new int[] { 2, 4, 6, 7, 8 };\n int[] c = new int[] { 3, 4, 5, 6, 9 };\n\n var result = a.Intersect(b).Intersect(c).ToArray(); // 4	0
32830564	32830153	Permissions to create CNG key	%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\Keys	0
29258200	28187392	How to add a non-property rule in FluentValidation?	public bool IsNumberUnique(CustomerType customerType, int id)\n{\n    var result = customerTypeRepository.SearchFor(x => x.Number == customerType.Number).Where(x => x.Id != customerType.Id).FirstOrDefault();\n\n    return result == null;\n}\n\npublic ValidationResult Validate(CustomerType customerType)\n{\n    CustomerTypeValidator validator = new CustomerTypeValidator();\n    validator.RuleFor(x => x.Id).Must(IsNumberUnique).WithState(x => CustomerTypeError.NumberNotUnique);\n    return validator.Validate(customerType);\n}	0
18740174	18740077	Save Image in PictureBox with overlapping Controls	Bitmap copy = new Bitmap(OriginalBitmap);\n\nGraphics g = Graphics.FromImage(copy);\n\ng.DrawImage(arrowBitmap, new Point(..));\n\ncopy.Save(...);	0
7936811	7935961	Creating Custom Control Based on Settings in C#	using System;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Configuration;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace Web\n{\n    public class SpecialLabel : Label\n    {   \n        protected override void OnLoad (EventArgs e)\n        {\n            base.OnLoad (e);\n\n            //get value from appsettings\n            if(!string.IsNullOrEmpty(this.ID)) {\n                Configuration rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration(null);\n                if (rootWebConfig1.AppSettings.Settings.Count > 0)\n                {\n                    KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings[this.ID];\n                    if (customSetting != null)\n                        this.Text = customSetting.Value;\n                }\n            }\n        }\n\n    }\n}	0
23309678	23296487	How do you insert odata edm?	Uri uri = new Uri("http://localhost:50222/odata");\n         var container = new CourseServiceRef.Container(uri);\n         CourseServiceRef.NotNeeded newTempAccount = new CourseServiceRef.NotNeeded()\n            { \n               Email = model.UserName,\n               Username1 = model.UserName \n            };\n\n         if (newTempAccount != null)\n        {\n            container.AddToNotNeededs(newTempAccount);\n            container.SaveChanges();\n        }	0
4198494	4198277	Invoke a C# inner Expression with a member property of a parameter to an outer expression	var customerFilter = this.CustomerCriteria.FilterPredicate();\n// create an expression that shows us invoking the filter on o.Customer\nExpression<Func<Order, bool>> customerOrderFilter = \n    o => customerFilter.Invoke(o.Customer);\n// "Expand" the expression: this creates a new expression tree\n// where the "Invoke" is replaced by the actual predicate.\nresult = result.And(customerOrderFilter.Expand())	0
19146561	19146501	How to replace Date Time in a String with Empty String using C#?	string input = "Print date :6/19/2013 11:31:55 AM ";\nvar result = Regex.Replace(input, @"\d{1,2}/\d{1,2}/\d{4} \d\d:\d\d:\d\d [AP]M", "");	0
11508302	11508240	How can I supply a List<int> to a SQL parameter?	ocmd.Parameters.Add("ListOfInts", String.Join(",",myList.ToArray());	0
11869830	11868787	Shade first row of table	private void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n    // For shading rows\n    if (dataGridView1.Rows.Count > 0)\n    {\n        dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;\n    }\n\n    // For shading columns\n    int colNum = 2; // Add your own code to get the column number you want\n    dataGridView1.Columns[colNum].DefaultCellStyle.BackColor = Color.LightGray;\n}	0
3599503	3598897	Facebook Fan Page feed	web.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";	0
7247611	7247521	Removing brackets	var value = "http://url.com/index?foo=[01234]&bar=1"; \nvalue = Regex.Replace(value, "foo=\\[(.*?)\\]","foo=$1");	0
3761382	3761359	add default to database populated dropdownbox	(SELECT 1 as X, 'abc' AS Y) UNION (SELECT X, Y FROM your_table);	0
17590072	17590045	Cannot implicitly convert from dialog result to bool	return (new BCustomerSettingsDialog()).ShowDialog() == DialogResult.OK;	0
29070365	29070306	Convert Date into ISO Date Format C#	string date = "02/14/2015"\n\nDateTime NewDate= DateTime.ParseExact(dateString, "MM/DD/YYYY", \nCultureInfo.InvariantCulture);\n\nstring NewFmt=NewDate.ToString("yyyy/MM/DD");	0
18865195	18865056	How to make a linq statement if a record exist	bool priceApplied = cn.OrderDressings.Any(x => x.OrderID == OrderID && x.OrderItemID == ProductID);\n\nif (priceApplied) {\n    var query = (from yy in cn.OrderDressings\n                where yy.OrderID == OrderID &&  \n                      yy.OrderItemID == ProductID\n               select yy.IsPriceApplied);\n    // do stuff.\n}\n\n// else.. do nothing.	0
15310157	15310110	random sleep between a set of time	Random rnd = new Random();\nint number = rnd.Next(3,11);	0
29628207	29628148	Foreach loop a List<T> in C# with random data generation	var rnd = new Random();\nforeach(patient ps in p)\n{\n    ps.ploc = rnd.Next(80, 220);\n}	0
15140963	15140903	aggregate two objects in a list into one	from person in PersonList\ngroup person by new { id = person.id, name = person.name } into grouping\nselect new Person\n{\n    id = grouping.Key.id,\n    name = grouping.Key.name,\n    goals = grouping.Sum(x => x.goals)\n}	0
11948960	11859208	Comparing listview column values with another listview column values and display the column value instead of other if it matches	if (messagelist.Items.Count > 0)\n            {\n                for (int i = 0; i < messagelist.Items.Count; i++)\n                {\n                    string mnum = messagelist.Items[i].Text;\n\n                    for (int j = 0; j < contactlist.Items.Count; j++)\n                    {\n                        if (contactlist.Items[j].SubItems[1].Text == mnum)\n                        {\n                            messagelist.Items[i].Text = contactlist.Items[j].Text;\n                        }\n\n                    }\n                }\n            }	0
7681102	7680885	Pass Value Selected From a User Control to a Parent	public class SomeClass : BaseControl\n{\n    public event EventHandler PersonSelected;\n\n    public string Name{get;set;}\n\n    protected void FindUser()\n    {\n        var find = new Button {ID = (ToString() + "search"), Text = "Search"};\n            find.Click += delegate(object sender, EventArgs e)\n                              {\n                                  if (PersonSelected!= null)\n                                  {\n                                      //forward this event to the page's event handler\n                                      PersonSelected(this, e);\n                                  }\n                              }; \n     }\n}\n\npublic class SomeOtherClass : Page\n{\n    public void Main()\n    {\n\n       var sp = (SomeClass)Control;\n                        sp.PersonSelected += BtnClick;\n     }\n\n    public void BtnClick(object sender, EventArgs e)\n    {\n        //Get some value from the (SomeClass)Control here\n     }\n}	0
1004186	1004156	Convert Method Group to Expression	Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);\n  Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);	0
2892590	2892551	Bug with DataBinding in WPF Host in Winforms?	var collectionView = CollectionViewSource.GetDefaultView(Products);\ncollectionView.Filter += item => ...;	0
8486262	8486195	read an image (TIF image) from FTP Server	class Program\n{\n    static void Main()\n    {\n        var filePath = "ftp://example.com/foo.tif";\n        var request = WebRequest.Create(filePath);\n        request.Credentials = new NetworkCredential("user", "pass");\n        using (var response = request.GetResponse())\n        using (var stream = response.GetResponseStream())\n        using (var img = Image.FromStream(stream))\n        {\n            img.Save("foo.jpg", ImageFormat.Jpeg);\n        }\n    }\n}	0
33961061	33961017	Can I set a Visual Studio 2015 C# application to reopen?	System.Windows.Forms.Application.Restart()	0
18240594	18239752	Exporting Data From Multiple DataGridViews on a Form to Multiple Excel Sheets in a Single Excel File	int count = workbook.Worksheets.Count;\nExcel.Worksheet addedSheet = workbook.Worksheets.Add(Type.Missing,\nworkbook.Worksheets[count], Type.Missing, Type.Missing);	0
23141624	23140751	How to save png file in Shared/ShellContent folder for secondary Tile	using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())\n            {\n                if (myIsolatedStorage.FileExists("Shared/ShellContent/logo.png"))\n                {\n                    return;\n                }\n\n                IsolatedStorageFileStream fileStream1 = myIsolatedStorage.CreateFile("Shared/ShellContent/logo.png");\n\n                Uri uri = new Uri("home.png", UriKind.Relative);\n                StreamResourceInfo sri = null;\n                sri = Application.GetResourceStream(uri);\n                BitmapImage bitmapImage = new BitmapImage();\n                bitmapImage.SetSource(sri.Stream);\n                WriteableBitmap wb = new WriteableBitmap(bitmapImage);\n\n                wb.WritePNG( fileStream1 as System.IO.Stream);\n\n                //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);\n\n                fileStream1.Close();\n            }	0
32226247	32225942	SessionID changing at every page call	protected void Session_Start(Object sender, EventArgs e) \n{\n    Session["init"] = 0;\n}	0
16903203	16903171	Making an object that travels with constant speed	// x += 1;\n class1.Move(x/2, x/2);	0
1343913	1343749	Get log4net log file in C#	var rootAppender = ((Hierarchy)LogManager.GetRepository())\n                                         .Root.Appenders.OfType<FileAppender>()\n                                         .FirstOrDefault();\n\nstring filename = rootAppender != null ? rootAppender.File : string.Empty;	0
4986044	4986023	Restricting scope of a class member beyond private	// Not actually valid C#!\npublic string Name\n{\n    // Only accessible within the property\n    string name;\n\n    get { return name; }\n    set\n    {\n        if (value == null)\n        {\n            throw new ArgumentNullException();\n        }\n        name = value;\n    }\n}	0
30071436	30071304	How to check if file is password protected & password passed by user is correct or not using dotnetzip in c#	public class ZipPasswordTester\n{\n    public bool CheckPassword(Ionic.Zip.ZipEntry entry, string password)\n    {\n        try\n        {\n            using (var s = new PasswordCheckStream())\n            {\n                entry.ExtractWithPassword(s, password);\n            }\n            return true;\n        }\n        catch (Ionic.Zip.BadPasswordException)\n        {\n            return false;\n        }\n        catch (PasswordCheckStream.GoodPasswordException)\n        {\n            return true;\n        }\n    }\n\n    private class PasswordCheckStream : System.IO.MemoryStream\n    {\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            throw new GoodPasswordException();\n        }\n\n        public class GoodPasswordException : System.Exception { }\n    }\n}	0
6071739	6071567	How to Zoom a Drawn Image in PictureBox	private void Scale_Click(object sender,\n  System.EventArgs e)\n{\n    // Create Graphics object\n    Graphics g = this.CreateGraphics();\n    g.Clear(this.BackColor);\n    // Draw a filled rectangle with\n    // width 20 and height 30\n    g.FillRectangle(Brushes.Blue,\n        20, 20, 20, 30);\n    // Create Matrix object\n    Matrix X = new Matrix();\n    // Apply 3X scaling\n    X.Scale(3, 4, MatrixOrder.Append);\n    // Apply transformation on the form\n    g.Transform = X;\n    // Draw a filled rectangle with\n    // width 20 and height 30\n    g.FillRectangle(Brushes.Blue,\n        20, 20, 20, 30);\n    // Dispose of object\n    g.Dispose();\n}	0
34446691	34446307	How to sorting dynamic in lambda entity framework?	using (var db = new ABCEntities()){\n  var columnExp = "columnName";\n  var query = db.LOCATIONs;\n  if(sort_order = "ASC")\n  {\n      query = query.OrderBy(columnExp).Tolist();  \n  }\n  else\n  {\n      query = query.OrderByDescending(columnExp).Tolist();\n  }\n}	0
31512998	31512075	backgroundWorker with foreach	public async void ButtonThatStartsEverything_Click(object sender, EventArgs e)\n{\n    await DoTheDownloadStuff();\n}\n\npublic async Task DoTheDownloadStuff()\n{\n    var client = new WebClient();\n\n    foreach(var item in ListBox1.Items)\n    {\n        var expanded = item.Split(';');\n        var num = expanded[0];\n        var result = await client.DownloadDataAsyncTask(new Uri("http://127.0.0.1/sv/" + num));\n        if (result.Contains("uva"))\n        {\n            listBox2.Items.Add(num);\n        }\n    }\n}	0
13190414	13189570	How to plot 2 kinds of chart on the same chart use EPPlus	ExcelChart chart = worksheet.Drawings.AddChart("chtLine", eChartType.LineMarkers);        \nvar serie1= chart.Series.Add(Worksheet.Cells["B1:B4"],Worksheet.Cells["A1:A4"]);\n//Now for the second chart type we use the chart.PlotArea.ChartTypes collection...\nvar chartType2 = chart.PlotArea.ChartTypes.Add(eChartType.ColumnClustered);\nvar serie2 = chartType2.Series.Add(Worksheet.Cells["C1:C4"],Worksheet.Cells["A1:A4"]);	0
15255883	15255799	How i am able to give two strings in DataTextField of radiobuttonlist?	RadioButtonList1.Items.Clear();\n\nforeach(var row in dt.Rows)\n{\n    var txt = row["name"].ToString() + " " + row["specification"].ToString();\n    var val = row["id"].ToString();\n    var item = new ListItem(txt,val);\n    RadioButtonList1.Items.Add(item);\n}	0
16875284	16875173	loading text from file hosts into listbox	string Path = @"C:\test.txt";\n        List<string> BlockedHosts = new List<string>();\n        using (StreamReader read = new StreamReader(Path))\n        {\n            while (!read.EndOfStream)\n            {\n                string[] data = read.ReadLine().Split(' ');\n                if (data.Count() >= 3)\n                {\n                    if (data[0] == "127.0.0.1" && data[2] == "#onlythis")\n                    {\n                        BlockedHosts.Add(data[1]);\n                    }\n                }\n            }\n        }\n     //Setting data in listbox\n     listBox1.DataSource = BlockedHosts;	0
1498017	1497997	C#, reliable way to convert a file to a byte[]	byte[] bytes = System.IO.File.ReadAllBytes(filename);	0
30809247	11076616	How to convert a Matrix4 or Quaternion to angle in degrees	Function cs_a_gr(cose)\n    Return 180 / PI * Acos(cose)\nEnd Function	0
8894706	8894661	How to make the below code generic?	private int SaveRecord<T>(T record, PortalConstant.DataSourceType dataSourceType, Func<IDataAccess, T, int> chooseSelector)\n{\n    int results = -1;\n\n    var dataPlugin = DataPlugins.FirstOrDefault(i => i.Metadata["SQLMetaData"].ToString() == dataSourceType.EnumToString());\n\n    if (dataPlugin != null)\n    {\n        results = chooseSelector(dataPlugin.Value, record);\n    }\n\n    return results;\n}	0
15981109	15980941	No overload for 'method' matches delegate 'delegate'	webKoordx.OpenReadCompleted += (sender, e) => MyMethod(e.Result, i);	0
13033378	13033331	How do you get the markup of a webpage in asp.net similar to php's get_file_contents	string html;\nusing (var client = new WebClient())\n{\n    html = client.DownloadString("http://www.google.com");\n}\nConsole.WriteLine(html);	0
1993149	1993046	DateTime region specific formatting in WPF ListView	using System.Windows;\nusing System.Windows.Markup;\nusing System.Globalization;\n\n...\n\nvoid App_Startup(object sender, StartupEventArgs e)\n{\n\n    FrameworkElement.LanguageProperty.OverrideMetadata(  \n        typeof(FrameworkElement),  \n        new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));\n}	0
26894679	26770375	How to Display high score using GUIText	get { if (_highscore == -1) \n        _highscore = PlayerPrefs.GetInt("Highscore", 0);\n        return _highscore; \n    }\n    set {\n        if (value > _highscore) {\n            _highscore = value;\n            highscoreReference.text = _highscore.ToString();\n            PlayerPrefs.SetInt("Highscore", _highscore);\n        }\n    }\n}	0
22540545	22539591	Get property name by attribute and its value	var propertiesWithAttribute = typeof(Entity).GetProperties()\n    // use projection to get properties with their attributes - \n    .Select(pi => new { Property = pi, Attribute = pi.GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault() as MyAttribute})\n    // filter only properties with attributes\n    .Where(x => x.Attribute != null)\n    .ToList();\n\nforeach (Entity entity in collection)\n{\n    foreach (var pa in propertiesWithAttribute)\n    {\n        object value = pa.Property.GetValue(entity, null);\n        Console.WriteLine("PropertyName: {0}, PropertyValue: {1}, AttributeName: {2}", pa.Property.Name, value, pa.Attribute.GetType().Name);\n    }\n}	0
18492144	18491960	Splitting an array of strings	//Functional style\nvar tokens = File.ReadLines(file)\n    .SelectMany(line => line.Split(',')) //split lines on commas\n    .Select(token => token.Trim(' ')) //remove spaces around tokens\n    .Select(token => token.Trim('"')); //remove quotes around tokens\n\n//Query style\nvar tokens = from line in File.ReadLines(file)\n             from token in line.Split(',')\n             select token.Trim(' ').Trim('"');	0
24151642	24102535	WCF GET method not getting latest data for iOS Client	[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];	0
5423706	5376029	Dependent objects with RegisterInstance	public class ClientUser : UserServiceBase, IClientUser   \n{\n     IDataServiceManager _dataServiceManager;      \n     public ClientUser()    \n     {             \n     }         \n\n     private IDataServiceManager DataServiceMgr     \n     {         \n          get { \n                _dataServiceManager = SnapFlowUnityContainer.Instance.Resolve<IClientUser>();   \n                return _dataServiceManager; \n              }         \n       }\n}	0
23870926	23869492	Listening to "Triggers" and reacting to them in Windows Phone	Sceduled Taks	0
5858186	5857976	Data Access Application Block 5.0 fluent configuration	SqlDatabase db = new SqlDatabase("some connection string from the config");\n        DbCommand cmd = db.GetSqlStringCommand(sqlStatement);\n        IDataReader reader = db.ExecuteReader(cmd);	0
28043086	28042830	C# HTTP post , how to post with List<XX> parameter?	var myObject = (dynamic)new JsonObject();\nmyObject.List = new List<T>();\n// add items to your list\n\nhttpClient.Post(\n    "",\n    new StringContent(\n        myObject.ToString(),\n        Encoding.UTF8,\n        "application/json"));	0
25193404	25192812	Wait all tasks with some conditions	TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();\n            Task<bool>[] tasks = new Task<bool>[3];\n            tasks[0] = Task.Factory.StartNew<bool>(() => Find(1, 2));\n            tasks[1] = Task.Factory.StartNew<bool>(() => Find(4, 7));\n            tasks[2] = Task.Factory.StartNew<bool>(() => Find(13, 14));\n\n            tasks[0].ContinueWith(_ =>\n            {\n                if (tasks[0].Result)\n                    tcs.TrySetResult(tasks[0].Result);\n            });\n\n            tasks[1].ContinueWith(_ =>\n            {\n                if (tasks[1].Result)\n                    tcs.TrySetResult(tasks[1].Result);\n            });\n\n            tasks[2].ContinueWith(_ =>\n            {\n                if (tasks[2].Result)\n                    tcs.TrySetResult(tasks[2].Result);\n            });\n\n            Task.WaitAny(tasks);\n\n            Console.WriteLine("Found");\n            ContinueWork();	0
1242024	1234755	Bold calendar dates	private void FormatCalendar()\n{\n    DataTable dtCalendar = this.Utils.GetDatesForCalendar(Session["LoginId"].ToString());\n    if (dtCalendar.Rows.Count != 0)\n    {\n        foreach (DataRow dr in dtCalendar.Rows)\n        {\n            if (!(System.Convert.IsDBNull(dr["LogDate"])))\n            {\n                RadCalendarDay NewDay = new RadCalendarDay();\n\n                NewDay.Date = Convert.ToDateTime(dr["LogDate"]);\n\n                txtDate.Calendar.SpecialDays.Add(NewDay);\n                txtDate.Calendar.SpecialDays[NewDay].ItemStyle.Font.Bold = true;\n            }\n        }\n    }\n}	0
8571671	8571618	LINQ OrderBy Clause - Force certain string to always be at the top	Menu[] sorted = ret.OrderBy(menu => menu.Title != "Favorites")\n                   .ThenBy(menu => menu.Title)\n                   .ToArray();	0
12091295	12091152	Run application from C# code with multiple arguments	process.StartInfo.Arguments = "\"My Manager\" 321";	0
9480156	9480048	how to declare a node of a list that each node is a two dimentional matrix	// Declare a list of matrices.\nList<int[,]> matrixList = new List<int[,]>();\n// Add a matrix to the list.\nmatrixList.Add(new int[5, 5]);	0
32114755	32084451	Unsafe C# - passing an unsafe pointer to a method	private unsafe byte* ReadIntoMemory(???	0
16669530	16669430	How can I reference an List<string> object's position index without searching for first occurrence?	var commands = listProcedure.Items.Cast<string>().ToList();\n\nvar xdoc = new XDocument(\n    new XDeclaration("1.0", "utf-8", null),\n    new XElement("commands",\n                commands.Select( (s, idx) => \n                    new XElement("command", s, new XAttribute("id", idx))\n                )));	0
4553294	4553234	sending ping with specific bytes amount using c#	using System.Net.NetworkInformation;\n\npublic void PingHost(string host, int packetSize, int packetCount)\n{\n    int timeout = 1000;  // 1 second timeout.\n    byte[] packet = new byte[packetSize];\n    // Initialize your packet bytes as you see fit.\n\n    Ping pinger = new Ping();\n    for (int i = 0; i < packetCount; ++i) {\n        pinger.Send(host, timeout, packet);\n    }\n}	0
13616467	13601288	How do I get AmazonId2 of a TransferUtilityUploadRequest	uploadRequest.UploadProgressEvent += (source, progress) =>\n{\n    Console.WriteLine("{0}% - {1} / {2}",\n        progress.PercentDone,\n        progress.TransferredBytes,\n        progress.TotalBytes);\n};	0
20132591	20132429	ASP.NET Get value from DropDownList in EditItemTemplate in codebehind	GridViewRow row = GridView1.Rows[e.RowIndex];\n\nDropDownList ddl = (DropDownList)row.FindControl("ddlUpgrade");\n\nSqlParameter _parm = new SqlParameter("@Upgrade", ddl.SelectedItem.ToString());\n    e.Command.Parameters.Add(_parm);	0
6114502	6114439	How might I reformulate a "MM/YYYY" date as "YYYYMM"?	string s = "11/2011";\ns = String.Format("{0}{1}", s.Split('/')[1], s.Split('/')[0]);	0
4630602	4630591	Saving an XML that has invalid characters	string pattern = String.Empty;\n//pattern =  @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])"; //XML 1.0\npattern =  @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])"; // XML 1.1\nRegex regex = new Regex(pattern, RegexOptions.IgnoreCase);\n\nif (regex.IsMatch(sString))\n{\n   sString = regex.Replace(sString, String.Empty);\n   File.WriteAllText(sString, sString, Encoding.UTF8);\n}\n\nreturn sString;	0
13306128	13305665	Loop through all descendants of a node and inspect them one by one	foreach(HtmlNode node in resultContainer)\n{\n    //check node type\n    switch(node.Name)\n    {\n        case "div":\n        {\n            break;\n        }   \n        case "p":\n        {\n        }\n        ///....etc\n    }\n\n    //get id\n    String id = node.Attributes["id"].Value;\n\n    //get class\n    String class = node.Attributes["class"].Value;\n\n}	0
9581833	9581661	How to sub date in datagridview in C#	DateTime dt1;\nDateTime dt2;\nif(DateTime.TryParse(dataGridView1[3,0].Value,out dt1) \n    && DateTime.TryParse(dataGridView1[5,0].Value,out dt2))\n    {\n        TimeSpan ts = dt1 - dt2;\n        int hours = ts.Hours;\n    }	0
19230904	19229811	How Can i Show a list Vertically in ASP.net C# Using DataGrid Or DataList View?	.box_rotate {\n -moz-transform: rotate(270deg);  /* FF3.5+ */\n   -o-transform: rotate(270deg);  /* Opera 10.5 */\n  -webkit-transform: rotate(270deg);  /* Saf3.1+, Chrome */\n             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=270);  /* IE6,IE7 */\n         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=270)"; /* IE8 */\n}	0
31496990	31496763	How to skip a condition?	if(txtWeb.Text != String.Empty)\n  Match matchWeb = regexWeb.Match(txtWeb.Text);	0
21711798	21690046	How are args represented (if at all) in Web API Attribute Routing annotations and if they aren't, how are they discovered?	[Route("api/InventoryItems/PostInventoryItem")]\npublic HttpResponseMessage PostInventoryItem([FromUri] InventoryItem ii)\n{\n    _inventoryItemRepository.PostInventoryItem(ii.ID, ii.pksize, ii.Description, ii.vendor_id, ii.dept,\n        ii.subdept, ii.UnitCost, ii.UnitList, ii.OpenQty, ii.UPC, ii.upc_pack_size, ii.vendor_item, ii.crv_id);\n    var response = Request.CreateResponse<InventoryItem>(HttpStatusCode.Created, ii);\n    string uri = Url.Link("DefaultApi", new { id = ii.ID });\n    response.Headers.Location = new Uri(uri);\n    return response;\n}	0
4510908	4510872	How to preview a html file without saving it?	protected void Page_Load(object sender, EventArgs e)\n    {\n        string htmlString = //initialise the string here\n        Response.Write(htmlString);\n        Response.End();\n    }	0
2800962	2800834	How to find attribute value	string xml = "<xml><xml2 val=\"ThisText\"/><xml2 val=\"ThatText\"/></xml>";\nvar doc = XDocument.Parse(xml);\nvar node = doc.Descendants().First(x => x.Attribute("val") != null \n            && x.Attribute("val").Value == "ThisText");\nTrace.WriteLine(node);	0
2294231	2294028	Select a HostName with Regex in C#?	string sOriginalUrl = "http://rs320tl.rapidshare.com/files/119371167/sth.rar";\nstring sPattern = "http://(?'host'[0-9a-zA-Z-.]*)/.*";\nRegex re = new Regex(sPattern, RegexOptions.ExplicitCapture);\nstring sHost = re.Match(sOriginalUrl).Groups["host"].Value;	0
12564452	12528036	Swap image in MenuItem onclick	protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e)\n        {\n            multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue);\n            if (menuTabs.Items[0].Selected == true)\n            {\n\n                menuTabs.Items[0].ImageUrl = "~/Images/widget1_over.png";\n                menuTabs.Items[1].ImageUrl = "~/Images/widget2.png";\n            }\n\n            if (menuTabs.Items[1].Selected == true)\n            {\n                menuTabs.Items[1].ImageUrl = "~/Images/widget2_over.png";\n                menuTabs.Items[0].ImageUrl = "~/Images/widget1.png";\n\n            }\n        }	0
29439562	29439186	can i return result to ajax via C#	This is how your c# code should look like. Let's discuss in chat if you have more questions.\n\n    //change the return type to string\n    [WebMethod(EnableSession = true)]\n    public static string save(string HTML, string Fname) \n    {            \n\n    ....\n\n    try\n    {\n        ....\n\n        if (string.IsNullOrEmpty(tempUser))\n        {\n            tempUser = "0";\n            return "some value 1";\n         }\n\n        ....\n\n        con.Close();  \n        return "some value 2";\n    }\n    catch (Exception ex)\n    {\n        CommonBLL.WriteExceptionLog(ex, "Form Save Default.aspx");\n        throw ex;\n    }        \n}	0
20027392	20027377	How do i remove chars from a string?	string g = mapData.Substring(start, index - start);\ng = g.Replace(@",", "");\ng = g.Replace(@"\", "");\nmap.Images.Add(g);	0
5177885	5177742	Combining the streams:Web application	//Execute the request\nHttpWebResponse response = null;\ntry\n{\n    response = (HttpWebResponse)request.GetResponse();\n}\ncatch (WebException we) { // handle web excetpions }\ncatch (Exception e) { // handle other exceptions }\n\nthis.Response.ContentType = "application/pdf";\n\nconst int BUFFER_SIZE = 1024;\nbyte[] buffer = new byte[BUFFER_SIZE];\nint bytes = 0;\nwhile ((bytes = resStream.Read(buffer, 0, BUFFER_SIZE)) > 0)\n{\n    //Write the stream directly to the client \n    this.Response.OutputStream.Write(buff, 0, bytes);\n}	0
14651501	14651317	Find changes in RavenDb session	// check if an entity has been modified\nsession.Advanced.HasChanged(entity)\n\n// check if there are any changes at all\nsession.Advanced.HasChanges	0
356971	356947	unidentified syntax in domain object constructor	new DomainObject<string>();	0
8168901	8168796	Show Tooltip while DataGridView Column is Resized	void dataGridView1_ColumnWidthChanged(object sender,  DataGridViewColumnEventArgs e)\n   {\n       toolTip1.SetToolTip(dataGridView1.Columns[i].Width.ToString());\n    }	0
9662913	9662850	how to change an item index in listview?	var currentIndex = listView1.SelectedItems[0].Index;\nvar item = listView1.Items[index];\nif (currentIndex > 0)\n{\n    listView1.Items.RemoveAt(currentIndex);\n    listView1.Items.Insert(currentIndex-1, item);\n}	0
9312066	9310194	Make a running process the active Window	[DllImport("user32.dll", CharSet=CharSet.Auto,ExactSpelling=true)]\npublic static extern IntPtr SetFocus(HandleRef hWnd);\n\n\n[TestMethod]\npublic void PlayAround()\n{\n    Process[] processList = Process.GetProcesses();\n\n    foreach (Process theProcess in processList)\n    {\n        string processName = theProcess.ProcessName;\n        string mainWindowTitle = theProcess.MainWindowTitle;\n        SetFocus(new HandleRef(null, theProcess.MainWindowHandle));\n    }\n\n}	0
11695359	11695083	c# is there a richtextbox flush feature	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        BackgroundWorker bg = new BackgroundWorker();\n        bg.DoWork += new DoWorkEventHandler(bg_DoWork);\n        bg.RunWorkerAsync();\n    }\n\n    void bg_DoWork(object sender, DoWorkEventArgs e)\n    {\n        for (int i = 0; i < 1000000000; i++)\n        {\n            Action action = () => richTextBox1.Text += "Line Number " + i;\n            richTextBox1.Invoke(action); \n        }\n    }\n}	0
13753819	13752026	How to update gridview row without datarowview?	/// <summary>\n    /// Gridview Row Data Bound \n    /// </summary>\n    protected void grdvOffers_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        // Converts the UTC date to PST timezone\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {  \n            Offer offer = ((Offer)e.Row.DataItem);\n            offer.Created = TimeZoneInfo.ConvertTimeFromUtc(offer.Created, CFrmFunctions.GetPresetTimeZone());\n            e.Row.DataItem = offer;\n            e.Row.DataBind();\n        }\n    }	0
466434	429165	Raising a decimal to a power of decimal?	// Adjust this to modify the precision\npublic const int ITERATIONS = 27;\n\n// power series\npublic static decimal DecimalExp(decimal power)\n{\n    int iteration = ITERATIONS;\n    decimal result = 1; \n    while (iteration > 0)\n    {\n        fatorial = Factorial(iteration);\n        result += Pow(power, iteration) / fatorial;\n        iteration--;\n    }\n}\n\n// natural logarithm series\npublic static decimal LogN(decimal number)\n{\n    decimal aux = (number - 1);\n    decimal result = 0;\n    int iteration = ITERATIONS;\n    while (iteration > 0)\n    {\n        result += Pow(aux, iteration) / iteration;\n        iteration--;\n    }\n}\n\n// example\nvoid main(string[] args)\n{\n    decimal baseValue = 1.75M;\n    decimal expValue = 1/252M;\n    decimal result = DecimalExp(expValue * LogN(baseValue));\n}	0
20641348	20641030	Parse Html Document Get All input fields with ID and Value	var doc = CQ.CreateDocumentFromFile(htmldoc); //load, parse the file\nvar fields = doc["input"]; //get input fields with CSS\nvar pairs = fields.Select(node => new Tuple<string, string>(node.Id, node.Value()))\n       //get values	0
24348905	24348876	How can I make a C# class with a constructor and have it return a string?	public class HttpException \n{\n    public string Text { get; private set; }\n    private readonly Exception ex;\n    public string Message { get { return this.ex.message; } }\n    public string InnerExceptionMessage { get { return this.ex.... } }\n    public string InnerExceptionInnerExceptionMessage { get { return this.ex....} }\n\n    public HttpException(string text, Exception ex)\n    {\n        this.Text = text;\n        this.Exception = ex;\n    }\n}	0
7431429	7431322	Sum Column in DataGridView ignore negative numbers	tot = tot + Math.Max(0, Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value));	0
23210655	23210575	Fileupload Regular expression validation fails for certain file name in asp.net	ValidationExpression="^.*\.(doc|DOC|docx|DOCX|pdf|PDF)$"	0
24866445	24866287	Windows 8 Phone Simplest way to populate a listbox using a list<string>	List<HistoryEntry> urls = new List<HistoryEntry>();\n        public MainPage()\n        {\n            InitializeComponent();\n        }\n\n        private void WebBrowser_Navigated(object sender, NavigationEventArgs e)\n        {\n             string url  = Convert.ToString(e.Uri).Remove(0, 11);\n             HistoryEntry urlObj = new HistoryEntry();\n             urlObj.URL = url;\n             urlObj.timestamp = DateTime.Now.ToString("HH:mm yyyy-MM-dd");\n             urls.Add(urlObj);\n             listBox.ItemsSource  = null;\n             listBox.ItemsSource = urls;\n        }\n\n        public  class HistoryEntry\n        {\n            public string URL { get; set; }\n            public string timestamp { get; set; }\n\n        }	0
7414375	7414303	Unit test a static method that calls a static method using moq	internal static class ThumbnailPresentationLogic\n{\n    public static string GetThumbnailUrl(List<Image> images)\n    {\n        return GetThumbnailUrl(images,\n           new Uri(ImageRetrievalConfiguration.GetConfig().ImageRepositoryName),\n           ImageRetrievalConfiguration.MiniDefaultImageFullUrl);\n    }\n\n    public static string GetThumbnailUrl(List<Image> images, Uri baseUri,\n        string defaultImageFullUrl)\n    {\n        if (images == null || images.FirstOrDefault() == null)\n        {\n            return defaultImageFullUrl;\n        }\n\n        Image latestImage = (from image in images\n                             orderby image.CreatedDate descending\n                             select image).First();\n\n        Uri fullUrl;\n\n        return \n            Uri.TryCreate(baseUri, latestImage.FileName, out fullUrl)\n                ? fullUrl.AbsoluteUri\n                : defaultImageFullUrl;\n    }\n}	0
2579941	2579914	Issue with dynamically loading a user control on button click	protected void Button1_Click(object sender, EventArgs e)\n{\n    Label1.Text = "UserControl - 1 button clicked!";\n\n    var ctrl = LoadControl("~/UserCtrl2.ascx");\n    ctrl.ID = "ucUserCtrl2";\n    PlaceHolder2.Controls.Add(ctrl);\n\n    this.SecondControlLoaded = true; // This flag saves to ViewState that your control was loaded.\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    var ctrl = LoadControl("~/UserCtrl1.ascx");\n    ctrl.ID = "ucUserCtrl1";\n    PlaceHolder1.Controls.Add(ctrl);\n\n    if (this.SecondControlLoaded)\n    {\n        var ctrl = LoadControl("~/UserCtrl2.ascx");\n        ctrl.ID = "ucUserCtrl2";\n        PlaceHolder2.Controls.Add(ctrl);\n    }\n}	0
20393801	20393659	C# Read file info from URL	System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http:\\your\url.ext");\nreq.Method = "HEAD";\nusing (System.Net.WebResponse resp = req.GetResponse())\n{\n    DateTime LastModified;\n    if(DateTime.TryParse(resp.Headers.Get("Last-Modified"), out LastModified))\n    { \n        //Check if date is good and then go to full download method.\n    }\n}	0
29758454	29758400	How do I get the "left-most 128 bits of a byte array"?	hash.Take(16).ToArray();	0
23490159	23490077	How to write recursive lambda expression (LINQ query)	var results = DbContext.Set<Folder>()\n            .Include(f => f.ParentFolder)\n            .Include(f => f.Files)\n            .Include(f => f.ChildFolders.Select(f1 => f1.ChildFolders).Select(f2 => f.ChildFolders.Select(f3 => f3.ChildFolders.Select(f4 => f4.ChildFolders.Select(f5 => f5.ChildFolders.Select(f6 => f6.Files))))))\n            .Where(f.ParentFolder == null);	0
22941505	22684881	Batch delete in Windows Azure Table Storage	var startTicks = string.Format("{0:0000000000000000000}", start);\nvar endTicks = string.Format("{0:0000000000000000000}", end);\nExpression<Func<DynamicTableEntity, bool>> filters = e => e.PartitionKey.CompareTo(startTicks) >= 0 && e.PartitionKey.CompareTo(endTicks) <= 0;	0
1572792	1572719	How can I bind a custom object in code-behind to a Grid in XAML?	Customer = new Customer() \n    { FirstName = "Jim", LastName = "Smith", Age = 45 };	0
9876008	9875918	Problems with Silverlight Toolkit in WP7	private void MenuItem_Click(object sender, RoutedEventArgs e)\n{\n    MenuItem menuItem = (MenuItem)sender;\n    MessageBox.Show("You chose to  " + menuItem.Header.ToString(),"Result",MessageBoxButton.OK);\n}	0
14395549	14394958	parse datetime to monthname	//Create localization object from http://stackoverflow.com/questions/3184121/get-month-name-from-month-number\nSystem.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();\n//Initialize dateTime\nDateTime.TryParse(KeyWord, out dateTime);\n//Write Month name in KeyWord\nKeyWord = string.Format("%{0}%", dtfi.GetMonthName(dateTime.Month));	0
21710928	21710912	Pass Value from input text area on button click to database	objCMD.Parameters.AddWithValue("@value", txtInput.Text).	0
7754643	7753196	How to change the order of datalist images from left to right or right to left?	Public Sub Swap(ByVal obj1 As Object, ByVal obj2 As Object)\n   Dim temp As Object = obj1\n   obj1 = obj2\n   obj2 = temp\nEnd Sub	0
11176498	11171010	How to make WPF DataGrid save changes back to database?	SqlCommandBuilder builder = new SqlCommandBuilder(a);\n    a.UpdateCommand = builder.GetUpdateCommand();\n    a.Update(d);	0
12868556	12868501	sorting array after json retrieval	jsResult.EVENTS = jsResult.EVENTS.OrderBy(e=>e.TIME).ToArray();	0
268034	268013	How do I convert a Bitmap to byte[]?	System.IO.MemoryStream stream = new System.IO.MemoryStream();\n        newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\n\n        PHJProjectPhoto myPhoto =\n            new PHJProjectPhoto\n            {\n                ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]\n                OrderDate = DateTime.Now,\n                ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,\n                ProjectId = selectedProjectId\n            };	0
13084132	13084055	Add Xml Node and Save it from string content of xml in c#	XDocument xDoc = XDocument.Parse(resourceContent);\nxDoc.Add(new XElement("name", "new content"));	0
864808	861042	How do I figure out the size of a loaded image using Silverlight 2?	private Image image;\n\n    public Page()\n    {\n        InitializeComponent();\n        LoadImage("image.png");\n    }\n\n    private void LoadImage(string path)\n    {\n\n        Uri uri = new Uri(path, UriKind.Relative);\n        BitmapImage bitmapImage = new BitmapImage();\n        bitmapImage.UriSource = uri;\n        bitmapImage.DownloadProgress += \n            new EventHandler<DownloadProgressEventArgs>(bitmapImage_DownloadProgress);\n    }\n\n    void bitmapImage_DownloadProgress(object sender, DownloadProgressEventArgs e)\n    {\n        if (e.Progress == 100)\n        {\n            Dispatcher.BeginInvoke(delegate()\n            {\n               double height = image.ActualHeight;\n               double width = image.ActualWidth;\n            });\n        }\n    }	0
2418988	2418898	What's the best way to remove portions of a string? (C#)	string myString = "1001--Some ingredient";\nstring myPortionOfString = myString.Substring(0, myString.IndexOf("--"));	0
1190447	1190423	Using SetWindowPos in C# to move windows around	IntPtr handle = process.MainWindowHandle;\nif (handle != IntPtr.Zero)\n{\n    SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);\n}	0
2039633	2039602	How to upload images using an API Key that gives you permission to upload? [Python source code included]	key=YOUR_API_KEY&image=http://example.com/example.jpg	0
27620691	27620387	How can I see what file was sent to my website via POST?	protected void Page_Load(object sender, EventArgs e)\n    {\n        Page.Response.ContentType = "text/xml";\n        System.IO.StreamReader reader = new System.IO.StreamReader ( Page.Request.InputStream );\n        String xmlData = reader.ReadToEnd ();\n        System.IO.StreamWriter SW;\n        SW = File.CreateText ( Server.MapPath(".")+@"\"+ Guid.NewGuid () + ".xml" );\n        SW.WriteLine ( xmlData );\n        SW.Close ();\n    }	0
4671760	4668056	How to call a private API from Monotouch?	Selector s = new Selector("myPrivateAPIMethodName");\nMyObjectToCallTheMethodOn.PerformSelector(s, parameterOfTheObject, 0);	0
20534818	20534699	C# How to upload large file to ftp ( File size must 500 MB - 1 GB)	NetworkStream passiveConnection;\nFileInfo fileParse = new FileInfo(openFileDialog.FileName);\nusing(FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open))\n{\n     byte[] buf = new byte[8192];\n     int read;\n\n     passiveConnection = createPassiveConnection();\n     string cmd = "STOR " + fileParse.Name + "\r\n";\n     tbStatus.Text += "\r\nSent:" + cmd;\n     string response = sendFTPcmd(cmd);\n     tbStatus.Text += "\r\nRcvd:" + response;\n\n     while ((read = fs.Read(buf, 0, buf.Length) > 0)\n     {\n         passiveConnection.Write(buf, 0, read);\n     }\n}\n\npassiveConnection.Close();\nMessageBox.Show("Uploaded");\ntbStatus.Text += "\r\nRcvd:" + new\nStreamReader(NetStrm).ReadLine(); \ngetRemoteFolders();	0
4688601	4688293	How to Initialize Values to a HashSet<String[,]> in C#	tblNames.Add(new [,] { { "0", "tblAssetCategory" }});	0
17824012	17821554	XNA - Copying a Model	Content.Load<Model>(filename)	0
15019326	15019294	Asp.net MVC 3 stored procedure to return one value from the table	cmd.Parameters.Add("@Email", SqlDbType.NChar).Value = email;\nvar UserId = cmd.ExecuteScalar();	0
11753379	11753345	How to call function with PaintEventArgs argumnt?	private PictureBox pictureBox1 = new PictureBox();\n\npictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);\n\nprivate void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)\n{\n   GetPixel_Example(e) ;\n}	0
6111158	6110820	Loading mixed mode assembly from unmanaged code	ref class Bootstrap\n{\npublic:\n    static void Initialize() { \n        // etc..\n    }\n};\n\nextern "C" __declspec(dllexport) \nvoid __stdcall LoadAndInitialize()\n{\n    Bootstrap::Initialize();\n}	0
8928287	8927528	how to translate an object from its current position to another one ? (successives translations)	DoubleAnimation slideDown =\n    new DoubleAnimation { By = 20, Duration = TimeSpan.FromSeconds(1.0) };	0
21779767	21595751	simple way to read xml data using linq	XNamespace ns = xDocument.Root.Attribute("xmlns").Value;\n\nList<CX_ITEMLIST> sList =\n    (from e in XDocument.Load(param.FileName).Root.Elements(ns + "itemEntry")\n     select new CX_ITEMLIST\n     {\n         TITLE = (string)e.Element(ns + "title"),\n         YEAR = (string)e.Element(ns + "year"),\n         ITEMNAME = (string)e.Element(ns + "itemname"),\n         CATRYLIST =\n         (\n             from p in e.Elements(ns + "categorylist").Elements(ns + "categories")\n             select new CATLIST\n             {\n                 IDTYPE = (string)p.Element(ns + "categoryid"),\n                 IDNUMBER = (string)p.Element(ns + "categoryName")\n             }).ToList()\n     }).ToList();	0
33311130	33311048	Update Wpf Image after FileSystemWatcher Event	b.Freeze()	0
2587988	2587734	How do I serialize a Dictionary<int, string>?	var lookup = new Dictionary<int, string>();\n\nlookup.Add(1, "123");\nlookup.Add(2, "456");\n\nusing (var ms = new MemoryStream())\n{\n    var formatter = \n       new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n\n    formatter.Serialize(ms, lookup);\n    lookup = null;\n\n    ms.Position = 0;\n    lookup = (Dictionary<int, string>) formatter.Deserialize(ms);\n}\n\nforeach(var i in lookup.Keys)\n{\n    Console.WriteLine("{0}: {1}", i, lookup[i]);\n}	0
1748167	1748101	Hierarchical object retrieve childsIds with linq	myListObject\n  .Where(child =>\n     myListObject\n     .Where(obj => obj.parentId==objectId)\n     .Select(obj => obj.id)\n     .Contains(child.parentId))\n  .Select(child => child.Id);	0
816589	816566	How do you get the current project directory from C# code when creating a custom MSBuild task?	string startupPath = System.IO.Directory.GetCurrentDirectory();\n\nstring startupPath = Environment.CurrentDirectory;	0
21157603	21157472	determine webclient already downloaded all data/string	isBusy = true;\nisBusyMessage = "Loading...";\n    WebClient client = new WebClient();\n    Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);\n    client.DownloadStringCompleted += (s, e) =>\n    {\n        if (e.Error == null)\n        {\n            RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);\n            hereRestProperty = new ObservableCollection<Item>(result.results.items);\n        }\n        else\n        {\n            MessageBox.Show(e.Error.ToString());\n        }\n        // Dispatcher.Invoke for lines below, if needed\n        // Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => {\n        isBusy = false;\n        isBusyMessage = "Finished";\n        // }));\n    };\n    client.DownloadStringAsync(uri);	0
14098871	14054446	C# StringBuilder: Check if it ends with a new line	myCode.Replace(string.Format("{0}{0}", Environment.NewLine),Environment.NewLine);	0
3213303	3211420	Return Top X Results From Linq To Objects Query in Order	var ofInterest = allMyNames\n                    .Distinct()\n                    .Where(x => x.CompareTo(from) >= 0 && x.CompareTo(to) <= 0)\n                    .OrderBy(x => x)\n                    .Take(4);	0
9416139	9416000	Abstract base class implementing derived class interface methods	public class OldClass : BaseClass, IOld\n{\n    public override double Meth2(int input)\n    {\n        return 0.0;\n    }\n}\n\npublic class NewClass : OldClass, INew // now implements IOld and INew using the Method2() from OldClass\n{\n    [Obsolete("This method is deprecated . Use Method3() instead.")]\n    public override double Meth2(int input)\n    {\n        return base.Meth2(input);\n    }\n    public float Meth3(int input)\n    {\n        return return 0.0f;\n    }\n}	0
29513788	29513745	Rendering a script bundle within webforms application issue	bundles.Add(new ScriptBundle("~/bundles/Query").Include(\n            "~/Scripts/WebForms/jquery-1.9.1",\n            "~/Scripts/WebForms/jquery-1.9.1.intellisense",\n            "~/Scripts/WebForms/bootstrap" \n            ));	0
9417062	9416588	working with MVC3 and c#,calling partial views from controller	public string GenerateUI()\n{    \nif(Student.IsEnrolled)\n  return EnrolledStudentModel.GenerateUI();\nelse\n  return UnenrolledStudentModel.GenerateUI();\n}	0
16628875	16628682	asp.net MVC 4 - output list of checkbox items, associate selections with user - allow display & editing later	PM> Install-Package MvcCheckBoxList	0
3909651	3909591	Efficient Multiple Deletion in Entity Framework 4	var ids = GetSelectedIds();\n\nforeach (var id in ids)\n{\n    var ws = new Workshop { Id = id };\n    db.Workshops.Attach(ws);\n    db.Workshops.DeleteObject(ws);\n}\n\ndb.SaveChanges();\nBindWorkshops();	0
21026366	20979500	Automatic content slider for Windows Phone	private DispatcherTimer playTimer;\n\npublic FirstLook()\n{\n    this.playTimer = new DispatcherTimer();\n    this.playTimer.Interval = TimeSpan.FromSeconds(2);\n    this.playTimer.Tick += this.OnPlayTimerTick;\n}\n\nprivate void OnPlayTimerTick(object sender, EventArgs e)\n{\n    this.slideView.MoveToNextItem();\n}\n\nprivate void OnPlayTap(object sender, GestureEventArgs e)\n{\n    if (this.playTimer.IsEnabled)\n    {\n        this.StopSlideShow();\n    }\n    else\n    {\n        this.playTimer.Start();\n        this.buttonImage.Source = new BitmapImage(new Uri("Images/pause.png", UriKind.RelativeOrAbsolute));\n    }\n}\n\nprivate void StopSlideShow()\n{\n    this.playTimer.Stop();\n    this.buttonImage.Source = new BitmapImage(new Uri("Images/play.png", UriKind.RelativeOrAbsolute));\n}	0
26700245	26700213	Json.net reading serialized array	List<LocalhostTiming> jsonResponse = JsonConvert.DeserializeObject<List<LocalhostTiming>>(htmlCode);	0
2791264	2791216	How should I store this information?	Dictionary<GroupIdType, HashSet<PrivilegeCodeType>>	0
3168067	3167946	Datatable subset of columns from another datatable	foreach (DataRow dr in dt.Rows)\n{\n  newDt.Rows.Add(dr["col1"],dr["col5"],etc);\n}	0
8792887	8792613	Win32 Browse for folder dialog: wrong folder returned when user creates a new folder	GetFileAttributes(folderName) == INVALID_FILE_ATTRIBUTES	0
32549222	32549152	How to query a database that matches a specific name in a foreign key?	subjectquery = "select * from subject where StudentID=2011017997";	0
6562740	6555952	Accessing the resources in the published application	typeof(Form1).Assembly.GetManifestResourceStream("PlayVideo.Resources.Video1.dat");	0
8789256	8788656	move value from one listbox to other using javascript and then read value using c#	ListBox2.Items.Count	0
20638935	20638883	Add items to end of selectlist	// Create a list from the result of GetStates\nvar states = svc.GetStates(user.Login, user.Password).ToList();\n// Add whatever you like\nstates.Add(...);\n// Create the SelectList\nm.StateList = new SelectList(states, "Key", "Value");	0
14146239	14146118	C#: Regex to do NOT match to a group of words	Regex r = new Regex(@"\b(?!office|blog|article)\w+\b");\nMatchCollection words = r.Matches("The office is closed, please visit our blog");\n\nforeach(Match word in words)\n{\n   string legalWord = word.Groups[0].Value;\n   ...\n}	0
8542426	8542340	C# Submit Button in Topic Control	//should work\nkeywords = Request["keywordSearch"];	0
3980387	3980300	Changing the incremental value of a C# Parallel.For loop	var odds = Enumerable.Range(1, _DataList.Length).Where(i => i % 2 != 0);\n\nTask.Factory.StartNew(() =>\n    Parallel.ForEach(odds, i =>\n    {\n        // do work for _DataList[i]                    \n    })\n);	0
14593453	14593452	How do I perpetuate private field data from a Component object into an Entity object using NHibernate?	using FluentNHibernate.Automapping.Alterations;\n\npublic class EntityOverride : IAutoMappingOverride<Entity>\n{\n    public void Override(AutoMapping<Entity> mapping)\n    {\n         mapping.Component(x => x.Component, c => \n         {\n               c.Map(Reveal.Member<Component>("fieldName1"),"columnName1");\n               c.Map(Reveal.Member<Component>("fieldName2"),"columnName2");\n               c.Map(Reveal.Member<Component>("fieldName3"),"columnName3");\n         });\n    }\n}	0
31457961	31456026	Deserializing XML gives me null instead of the object	Namespace = "http://tempuri.org/worldpay"	0
11788627	11788060	change font size of itextsharp	StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();\nstyles.LoadTagStyle("th", "color", "red");\nstyles.LoadTagStyle("th", "frontsize", "5");\npdfDoc.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));	0
25364087	25362195	Transform odbc connection strings to SqlClient	/// <summary>\n    /// Returns a SQLClient Connection String from an ODBC string \n    /// </summary>\n    private string ODBCToSqlClient(string ODBCConnectionString)\n    {           \n        OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder(ODBCConnectionString);                        \n        if (builder.ContainsKey("Uid"))            \n        {\n            //Standard Connection\n            return string.Format("Server={0};Database={1};User Id={2};Password={3};", builder["Server"], builder["Database"], builder["uid"], builder["pwd"]);\n        }\n        else \n        {\n            //Trusted Connection\n            return string.Format("Server={0};Database={1};Trusted_Connection=True;", builder["Server"], builder["Database"]);                \n        }\n    }	0
6201038	6200908	Enum parsing. String to Anchor	var s = "Top;Left";\ns = s.Replace(";", ", ");\nvar e = Enum.Parse(typeof(AnchorStyles), s);	0
22486965	22486616	Split string on uppercase only if next character is lowercase	var input = "MyFavouriteChocIsDARKChocalate";\nvar output = Regex.Replace(input, "(((?<!^)[A-Z](?=[a-z]))|((?<=[a-z])[A-Z]))", " $1");\nConsole.WriteLine(output);	0
11451847	11451682	How to popup a page on button click?	protected void Page_Load(object sender, EventArgs e)\n        {\n           HyperLink1.Attributes.Add("onclick", "centeredPopup('WebForm1.aspx','myWindow','500','300','yes');return false");\n        }\n\n\n<script language="javascript">\nvar popupWindow = null;\nfunction centeredPopup(url,winName,w,h,scroll){\nLeftPosition = (screen.width) ? (screen.width-w)/2 : 0;\nTopPosition = (screen.height) ? (screen.height-h)/2 : 0;\nsettings =\n'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'\npopupWindow = window.open(url,winName,settings)\n}\n</script>	0
4579564	4579506	How to do Alignment within string.Format c#?	Console.WriteLine(String.Format("{0,-10} | {1,5}", "Bill", 51));	0
16083353	16083259	Unit testing of dynamically created assembly	Assembly dynamicAssembly = //generated\nvar derivedInstances = dynamicAssembly.GetTypes()\n    .Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(BaseClass)))\n    .Select(t => (BaseClass)Activator.CreateInstance(t));\n\nforeach(BaseClass bc in derivedInstances)\n{\n    //run tests\n}	0
12953572	12953418	make a link if table cell has large data then its height	If descLength >= 75 then\n      CType(row.FindControl("shortDesc"), Label).Text = CType(row.FindControl("labelDesc"), Label).Text.Substring(0, 74) & "... <a href='/detailsfp.aspx?prodid=" & productIDM & "'>Full Description</a>"\n End If	0
20158479	20136981	how to get the datatable name from xsd file	if (cmbXsd.SelectedIndex == 0)\n\n            {\n                cmbDt.Items.Clear();\n                XmlDataDocument xmldd = new XmlDataDocument();\n                DataSet ds = xmldd.DataSet;\n                for (int j = 0; j <= dtfill.Rows.Count - 1; j++)\n                {\n                    string filename = dtfill.Rows[j][0].ToString();\n                    string dirpath = Path.Combine(Directory.GetCurrentDirectory(), filename);\n                    ds.ReadXmlSchema(dirpath);\n                    DataTableCollection dtc = ds.Tables;\n                    for (int i = 0; i < dtc.Count; i++)\n                    {\n                        DataTable dt = ds.Tables[i];\n                        GetTableNames(ds);\n                        break;\n                     }\n                    break;\n                }\n            }	0
19277341	19274990	How retrieve related Entity ID in CRM 2011	// I am assuming you already have 'priceId' \nvar price = (from p in _context<new_priceEntity>CreateQuery()\n             where p.id = priceId\n             select p).FirstOrDefault();\n\n//Price level Id is:\nvar priceLevelId = price.new_priceLevelId.Id;\n\n// get Price value\nvar priceLevel = (from p in _context<new_priceLevelEntity>CreateQuery()\n                  where p.id = priceLevelId \n                  select p).FirstOrDefault();	0
31428435	31409066	Generic argument in dynamic proxy interceptor	var method = typeof(CacheUtil).GetMethod("GetNativeItem");\n      var gMethod = method.MakeGenericMethod(invocation.Request.Method.ReturnType);\n\n      var objInCache = gMethod.Invoke(typeof(CacheUtil), BindingFlags.Static, null, new object[] { cacheKey }, CultureInfo.InvariantCulture);	0
28155594	28155333	set value to generic type <T>	public static List<T> ToList<T>(this IDataReader dr) where T: new()\n    {\n        var col = new List<T>();\n        var type = typeof(T);\n        var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n        while (dr.Read())\n        {\n            var obj = new T();\n            for (int i = 0; i < dr.FieldCount; i++)\n            {\n                string fieldName = dr.GetName(i);\n                var prop = props.FirstOrDefault(x => x.Name.ToLower() == fieldName.ToLower());\n                if (prop != null)\n                {\n                    if (dr[i] != DBNull.Value)\n                        prop.SetValue(obj, dr[i], null);\n                }\n            }\n            col.Add(obj);\n        }\n\n        dr.Close();\n        return col;\n    }	0
14397665	14397226	How to parse the below xml string in c#	XmlDocument document = new XmlDocument();\ndocument.Load(filePath);\n\nforeach (XmlNode node in document.GetElementsByTagName("a:regionCode"))\n    Console.WriteLine(node.InnerText);	0
20931641	20931413	How to find the next Anchor tag from previous in htmlagilitypack?	private static HtmlNode GetNextDDSibling(HtmlNode element)\n{\n    return element.SelectSingleNode("following-sibling::a");\n}	0
13650510	13646204	ServiceStack DTO Assembly	[Route]	0
23212704	23211884	Select all column in QueryExpression CRM 2011	query.ColumnSet = new ColumnSet(True);	0
26173239	26173222	Increment a SqlDataReader field value in C#	long tmp_index = (long)Sql_DR["indexx"] +1;	0
31191652	31191467	How to get the node value in XML	string str= "";\nXmlDocument xdoc = new XmlDocument();\nxdoc.Load("Your XML Path");\nXmlNodeList elements = xdoc.GetElementsByTagName("Info");\nfor (int i = 0; i < elements.Count; i++)\n{\n   str= elements[i].Attributes["name"].Value;\n}\nMessageBox.Show(str);	0
7969236	7962365	Custom Value Injection	public class SetRole : NoSourceValueInjection\n     {\n         protected override void Inject(object target)\n         {\n             dynamic t = target;\n             t.RoleName = Roles.GetRolesForUser(t.UserName).FirstOrDefault();\n         }\n     }\n\nuvm.InjectFrom(user)\n   .InjectFrom<SetRole>();	0
32591078	32590834	Convert string input to double in WPF application	double firstInputDouble;\n\nif(!double.TryParse(FirstInput.Content, out firstInputDouble)){\n    // something went wrong....\n}	0
29104736	29104590	I'm trying to load image in picturebox using OpenFileDialough but it's not working how i get path of Openfiledialough And how to load it	OpenDialog.Reset();\nOpenDialog.AutoUpgradeEnabled = true;\nOpenDialog.CheckFileExists = true;\nOpenDialog.CheckPathExists = true;\nOpenDialog.DefaultExt = "";\nOpenDialog.FileName = "";\nOpenDialog.Filter = "Images (.jpeg)|*.jpg;*.jpeg";\nOpenDialog.InitialDirectory = @"C:\";\nOpenDialog.Multiselect = false;\nOpenDialog.RestoreDirectory = false;\nOpenDialog.ShowHelp = false;\nOpenDialog.ShowReadOnly = false;\nOpenDialog.Title = this.Text;\n\nif (OpenDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n{\n    Image productimage = Image.FromFile(OpenDialog.FileName);\n    System.Drawing.Size defaultsize = new Size(129, 129);\n\n    if (productimage.Width > defaultsize.Width || productimage.Height > defaultsize.Height)\n    {\n        Common.ShowErrorMessage("Cannot load large image. Default size (128 X 128)", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);\n        return;\n    }\n    PicBox.Image = productimage;\n}	0
10293633	10293236	Accessing the ScrollViewer of a ListBox from C#	public class MyListBox : ListBox\n{\n    public ScrollViewer ScrollViewer\n    {\n        get \n        {\n            Border border = (Border)VisualTreeHelper.GetChild(this, 0);\n\n            return (ScrollViewer)VisualTreeHelper.GetChild(border, 0);\n        }\n    }\n}	0
13463824	13463581	ASP FileUpload with Image	input type="file"	0
21991502	21991250	How properly get the style made by blend in code behind (windows phone)	tg.Style = this.Resources["TopinsStyle"] as Style;	0
34328578	34320023	Logging to SQL Server in bulks using log4net	virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)	0
21749768	21749188	Object auto detect the datatype and convert to the datatype I need	namespace UnitTest\n{\n    using System;\n\n    public class Program\n    {\n        public static void Main(string[] args)\n        {\n            Console.WriteLine(ConvertToType(DateTime.Now).GetType().Name);\n            Console.WriteLine(ConvertToType<Guid>(Guid.NewGuid()).GetType().Name);\n            Console.Read();\n        }\n\n        public static dynamic ConvertToType(object obj)\n        {\n            //If you're unsure of the type you want to return.\n            return Convert.ChangeType(obj, obj.GetType());\n        }\n\n        public static T ConvertToType<T>(object obj)\n        {\n            //If you definitely know the type you want to return.\n            return (T)Convert.ChangeType(obj, typeof(T));\n        }\n    }\n}	0
20349322	20348205	Update children View Model from Parent raising events	Application.Current.Dispatcher.BeginInvoke((Action)(() => { /* update properties */ } )));	0
13577824	13577791	Error reading a from file - Encoding issue	File.ReadAllText("test.csv",System.Text.UTF8Encoding)	0
16859473	16859418	How to assign a timestamp format value in a parameter?	Timestamp = new byte[0];	0
12068887	12068804	Background creating a BitmapImage	public static BitmapImage convertFileToBitmapImage(string filePath)\n{\n    BitmapImage bmp = null;\n    Uri jpegUri = new Uri(filePath, UriKind.Relative);\n    StreamResourceInfo sri = Application.GetResourceStream(jpegUri);\n    AutoResetEvent bitmapInitializationEvt = new AutoResetEvent(false);\n    Deployment.Current.Dispatcher.BeginInvoke(new Action(() => {\n        bmp = new BitmapImage();\n        bmp.SetSource(sri.Stream);\n        bitmapInitializationEvt.Set();\n    }));\n    bitmapInitializationEvt.WaitOne();\n    return bmp;\n}	0
579232	579096	How to go about serving a singleton object over the network in C#?	[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] \nclass MySingleton : ...\n{...}	0
28003185	28003004	Entity Framework Query - Unable to fetch data	var customersList = context.Customers.Include(x => x.ReturnedCustomerItems.Select(y => y.ReturnedLotItem)).Where(x => x.IsDeleted == false).ToList();	0
26678051	26677801	How to get nuget package version programmatically?	string packageID = "ILMerge";\n\n//Connect to the official package repository\nIPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");\nvar version =repo.FindPackagesById(packageID).Max(p=>p.Version);	0
14531209	14531142	How to use RegistryKey.SetValue	key = Registry.LocalMachine.CreateSubKey(\n    @"Software\Microsoft\Windows\CurrentVersion\Policies\System",\n    RegistryKeyPermissionCheck.ReadWriteSubTree, // read-write access\n    rs);	0
240191	240171	Launching a Application (.EXE) from C#?	System.Diagnostics.Process.Start()	0
2670339	2670263	ASP.NET Download All Files as Zip	response.ContentType = "application/zip";\nresponse.AddHeader("content-disposition", "attachment; filename=" + outputFileName);\nusing (ZipFile zipfile = new ZipFile()) {\n  zipfile.AddSelectedFiles("*.*", folderName, includeSubFolders);\n  zipfile.Save(response.OutputStream);\n}	0
4384546	4378056	Finding overlaps in time ranges	public class TimeSlot\n{\n    public DateTime StartTime { get; set; }\n    public DateTime EndTime { get; set; }\n\n\n    public bool Overlaps(DateTime compareTime)\n    {\n        return Overlaps(new TimeSlot() { StartTime = compareTime, EndTime = compareTime });\n    }\n\n    public bool Overlaps(TimeSlot compareSlot)\n    {\n        return (\n            (compareSlot.StartTime.TimeOfDay >= StartTime.TimeOfDay && compareSlot.StartTime.TimeOfDay < EndTime.TimeOfDay) ||\n            (compareSlot.EndTime.TimeOfDay <= EndTime.TimeOfDay && compareSlot.EndTime.TimeOfDay > StartTime.TimeOfDay) ||\n            (compareSlot.StartTime.TimeOfDay <= StartTime.TimeOfDay && compareSlot.EndTime.TimeOfDay >= EndTime.TimeOfDay)\n        );\n    }\n}	0
31263494	31240980	PKCS11Interop : How to extract certificate with private key?	var oParams = new CspParameters(1, "ASIP Sante Cryptographic Provider");\noParams.Flags = CspProviderFlags.UseExistingKey;\noParams.KeyNumber = (int)KeyNumber.Signature;\noParams.KeyContainerName = System.Text.RegularExpressions.Regex.Replace(GetAttributeValue(item, CKA.CKA_SUBJECT).First().GetValueAsString(), @"[^\u0020-\u007E]", string.Empty);	0
26009321	25945665	Missing end tag in Xml Export by Response.TransmitFile	var myfile = new FileInfo(filePath);\n            if (myfile.Exists)\n            {\n                HttpContext.Current.Response.Clear();\n                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);\n                HttpContext.Current.Response.AddHeader("Content-Length", myfile.Length.ToString());\n                HttpContext.Current.Response.ContentType = "text/xml";\n                HttpContext.Current.Response.TransmitFile(myfile.FullName);\n                HttpContext.Current.Response.End();                \n            }	0
18784726	18775554	Opening a Folder With Large Number of Files and Retrieving Them	GetItemCountAsync();\nGetFilesAsync(uint startIndex, uint maxNumberOfItems);	0
1175456	1165967	Opaque dictionary key pattern in C#	//4.0 Beta1 GetHashCode implementation\n        int a = 5; int b = 10;\n        Tuple<int, int> t = new Tuple<int, int>(a, b);\n\n        Console.WriteLine(t.GetHashCode() == (((a << 5) + a) ^ b));	0
8560292	8559975	I think C# created a bitmap with a larger than usual header	1078 - 14 - 40 = 1024	0
16275025	16274508	How to call Google Geocoding service from C# code	var address = "123 something st, somewhere";\nvar requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));\n\nvar request = WebRequest.Create(requestUri);\nvar response = request.GetResponse();\nvar xdoc = XDocument.Load(response.GetResponseStream());\n\nvar result = xdoc.Element("GeocodeResponse").Element("result");\nvar locationElement = result.Element("geometry").Element("location");\nvar lat = locationElement.Element("lat");\nvar lng = locationElement.Element("lng");	0
995915	995901	Convert database row into object	.Create()	0
32808219	32808132	How to get the Value in [Display(Name="")] attribute in Controller for any property using EF6	MemberInfo property = typeof(ABC).GetProperty(s); \nvar dd = property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;\nif(dd != null)\n{\n  var name = dd.Name;\n}	0
9450703	9450676	How can i run a function after the program being on 12hrs in a row?	var timespan = new TimeSpan(12, 0, 0);\n        var timer = new System.Timers.Timer(timespan.TotalMilliseconds);\n        timer.Elapsed += (o, e) =>\n        {\n            // runs code here after 12 hours.\n        };\n        timer.Start();	0
10376264	10376253	Windows service - get current directory	System.Reflection.Assembly.GetEntryAssembly().Location	0
792021	791946	How can I pass my different request objects to the same method for formatting?	var fields = req1.GetType().GetFields( \n   BindingFlags.Instance | BindingFlags.NonPublic )\n  .Where( f=> f.FieldType == typeof( DateTime ) );	0
1882198	1882120	multidimensional arrays with multiple datatypes in C#?	// Creates and initializes a OrderedDictionary.\nOrderedDictionary myOrderedDictionary = new OrderedDictionary();\nmyOrderedDictionary.Add("testKey1", "testValue1");\nmyOrderedDictionary.Add("testKey2", "testValue2");\nmyOrderedDictionary.Add("keyToDelete", "valueToDelete");\nmyOrderedDictionary.Add("testKey3", "testValue3");\n\nICollection keyCollection = myOrderedDictionary.Keys;\nICollection valueCollection = myOrderedDictionary.Values;\n\n// Display the contents using the key and value collections\nDisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);	0
27775406	27775328	How to create an auto increment column and have it auto filled	private void AddAutoIncrementColumn()\n{\n    DataColumn column = new DataColumn();\n    column.DataType = System.Type.GetType("System.Int32");\n    column.AutoIncrement = true;\n    column.AutoIncrementSeed = 0;\n    column.AutoIncrementStep = 1;\n\n    // Add the column to a new DataTable.\n    DataTable table = new DataTable("table");\n    table.Columns.Add(column);\n}	0
11382470	11382437	How can I add a control to another control in C#?	this.Controls.Add(this.Field_ValueControl);	0
10734284	10734207	How to get specific directories for process	var directoryInfo = new DirectoryInfo(@"c:\temp\stackoverflow");\nforeach (var element in dinfo.GetDirectories(@"profile", SearchOption.AllDirectories).SelectMany(x => x.GetFiles()))\n{\n    Console.WriteLine (element);\n}	0
17238766	17238649	c# property setter body without declaring a class-level property variable	private string _mongoFormId;\n\npublic string mongoFormId \n{\n    get { return this._mongoFormId; }\n    set \n    {\n        this._mongoFormId = value;\n        revalidateTransformation();\n    }\n}	0
21596380	21578350	how to display a pop up message with ok and cancel button in windows phone 7 application development	MessageBoxResult m = MessageBox.Show("Heading", "What do want to say to user so that he/she can press ok or cancel", MessageBoxButton.OKCancel);\nif (m == MessageBoxResult.Cancel)\n{\n   //do what you want when user press cancel\n}\nelse if (m == MessageBoxResult.OK)\n{\n   //Do what you want when user press ok\n}	0
27910608	27909577	Regex to remove text between two chars in c#	string input = "Enter Type:=select top 10 type from cable}";\n\nSystem.Text.RegularExpressions.Regex regExPattern = new System.Text.RegularExpressions.Regex("(.*):=select.*}");\nSystem.Text.RegularExpressions.Match match = regExPattern.Match(input);\n\nstring output = String.Empty;\nif( match.Success)\n{\n    output = match.Groups[1].Value;\n}\n\nConsole.WriteLine("Output = " + output);	0
9421111	9419322	Combining two Regex validators	ValidationExpression="^.{1,60}$(?<=\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*)"	0
18549818	18549555	Multiple filter conditions Azure table storage	string date1 = TableQuery.GenerateFilterConditionForDate(\n                   "Date", QueryComparisons.GreaterThanOrEqual,\n                   DateTimeOffsetVal);\nstring date2 = TableQuery.GenerateFilterConditionForDate(\n                   "Date", QueryComparisons.LessThanOrEqual,\n                   DateTimeOffsetVal);\nstring finalFilter = TableQuery.CombineFilters(\n                        TableQuery.CombineFilters(\n                            partitionFilter,\n                            TableOperators.And,\n                            date1),\n                        TableOperators.And, date2);	0
5157276	5157170	Entity Framework Code First: How can I cast a set of entities returned from the database?	public ViewResult List(int id)\n{\n    var db = new ModelEntities();\n    var addresses = from a in db.Addresses.Where(x => x.CustomerID == id)\n                    select new AddressVM(a);\n    return View(addresses );\n}	0
5661239	5661010	how to make a download button in c# asp.net? with a query?	Response.ContentType = "image/jpeg";\nResponse.AppendHeader("Content-Disposition","attachment; filename=downloadedFile.JPG");\nResponse.TransmitFile( @"c:/my documents/images/file.xxx" );\nResponse.End();	0
20503315	20496766	Can I join a table to a list using linq?	var accountNumbers = lstFarmerProfiles.Select(x => x.AccountNo).ToArray();\n\nvar duplicationChecklist = \n        from profile in dataAccessdup.MST_FarmerProfile\n                                     .Where(p => accountNumbers\n                                                    .Contains(p.AccountNo))\n                                     .AsEnumerable() // Continue in memory\n        join param in lstFarmerProfiles on \n            new { profile.Name, profile.AccountNo} equals \n            new { param.Name, param.AccountNo}\n        select profile	0
15479511	15479174	how to overload two methods with different input parameters	private void calcResults()\n    {\n       MakePath(id, results.GetType(), _resultCount);\n       MakePath(id, "XYZ", _resultSICount)\n    }\n\n    private string MakePath(string subFolder, Type type, int index)\n    {\n        return MakePath(subFolder, type.Name, index);\n    }\n\n    private string MakePath(string subFolder, string tempFileName, int index)\n    {\n        string dir = System.IO.Path.Combine(_outputDir, subFolder);\n        string fileName = string.Format("{0} {1} {2}.xml",\n               tempFileName, _dateTimeSource.Now.ToString(DATE_FORMAT), index.ToString());\n        return System.IO.Path.Combine(dir, fileName);\n    }	0
16137930	16137897	How to remove a List string element if it contains a string element from another List?	foreach (var token in tokens)\n{\n    token.RemoveAll(str => sets.Any(s => str.Contains(s)));\n}	0
12880535	12880402	How to append controls to a panel?	Control c = Page.LoadControl("DData.ascx");\nPanel1.Controls.Add(c);	0
15406366	15406218	Generating a random number that isn't biased against positive proper fractions	var random = new Random();\nDouble n1 = random.NextDouble(); // 0 <= n < 1.0\nDouble n = random.NextDouble(); // 0 <= n < 1.0\nif (n1 < 0.5)\n    n = 0.25 + 0.75 * n; // 0.25 <= n < 1.0\nelse\n    n = 10.0 - 9.0 * n; // 1 < n <= 10	0
20687921	20685512	Wrapping method to make it generic with map method	T Find(IEnumerable<T> values, Func<T, ConcreteType> map)\n{\n    var dictionary = new Dictionary<ConcreteType, T>();\n    ConcreteType found = Find(MapAndRecord(values, map, reverseMapping));\n    // TODO: Handle the situation where it's not found. (Does Find\n    // return null?)\n    return dictionary[found];\n}\n\nprivate static IEnumerable<ConcreteType> MapAndRecord(\n    IEnumerable<T> values, Func<T, ConcreteType> map,\n    IDictionary<ConcreteType, T> reverseMapping)\n{\n    foreach (var value in values)\n    {\n        var mapped = map(value);\n        reverseMapping[mapped] = value;\n        yield return mapped;\n    }\n}	0
31705367	31704651	Parse xml by Xdocument	var attributes =  doc.Root.Descendants()\n                     .Where(elem => elem.HasAttributes)\n                     .SelectMany(e => e.Attributes());\n\nforeach (var attr in attributes)\n    Console.WriteLine("Name: {0}, value: {1}", attr.Name, attr.Value);	0
3388596	3388536	Will declaring a variable inside/outside a loop change the performance?	StringBuilder sb = new StringBuilder();\nforeach(Type item in myCollection)\n{\n   sb.Length = 0;\n}	0
28266186	28266003	SQL UPDATE CLASS_NUMBER BY NAME ORDER	with toupdate as (\n      select t.*, row_number() over (order by name) as new_class_num\n      from table t\n     )\nupdate toupdate\n    set class_num = new_class_num;	0
28845390	27307981	Add Entry DNS Client Resolver Cache wihout using the hostfile	oSession["x-overrideHost"]	0
1470514	1467964	How do I Iterate controls in a windows form app?	IList<TextBox> textBoxes = new List<TextBox>();\n\n???\n\n    for (int i = 0; i < 12; i += 1)\n    {\n        TextBox textBox = new TextBox();\n        textBox.Position = new Point(FormMargin, FormMargin + (i * (textBox.Height + TextBoxPadding)));\n        this.Controls.Add(textBox);\n        this.textBoxes.Add(textBox);\n    }	0
3094374	3094045	How to programmatically open Microsoft Infopath in C#?	void mDisplayForm_Click(object sender, EventArgs e)\n    {\n        int count = 0;\n        foreach (ToolStripMenuItem template in mDisplayForms)\n        {\n            if (sender.ToString() == template.Text)\n            {\n                Process infoPath = new Process();\n                infoPath.StartInfo.FileName = "InfoPath.exe";\n                infoPath.StartInfo.Arguments = templates[count];\n                infoPath.Start();\n                count++;\n            }\n        }\n    }	0
19701593	19701490	Initializing an object with a property that is dependent on another property	private int y;\n    public int Y\n    {\n        get { return y +z; }\n        set { y = value ; }\n    }	0
29535142	29534806	MethodInfo showing null when getMethod is invoked with parameters containing reference type	MethodInfo mi =ElementA.GetMethod("GetString",new Type[] { typeof(AttributeA)  ,typeof(System.String).MakeByRefType()});	0
12221829	12221626	Message pump in a console application	var queue = new BlockingCollection<ConsoleKeyInfo>();\n\nnew Thread(() =>\n{\n    while (true) queue.Add(Console.ReadKey(true));\n})\n{ IsBackground = true }.Start();\n\n\nConsole.Write("Welcome! Please press a key: ");\n\nConsoleKeyInfo cki;\n\nif (queue.TryTake(out cki, TimeSpan.FromSeconds(10))) //wait for up to 10 seconds\n{\n    Console.WriteLine();\n    Console.WriteLine("You pressed '{0}'", cki.Key);\n}\nelse\n{\n    Console.WriteLine();\n    Console.WriteLine("You did not press a key");\n}	0
1040738	1040707	C# get digits from float variable	private Int32 FractionalPart(double n)\n    {\n        string s = n.ToString("#.#########", System.Globalization.CultureInfo.InvariantCulture);\n        return Int32.Parse(s.Substring(s.IndexOf(".") + 1));\n    }	0
23285275	23285156	What is the best way to find the nearest lesser and greater values in a list to a given number	int value = 35;\nint[] list = new[] { 1, 8, 13, 20, 25, 32, 50, 55, 64, 70 };\nint? floor = null;\nint? ceil = null;\nint index = Array.BinarySearch(list, value);\nif (index >= 0) // element is found\n{\n    if (index > 0)\n        floor = list[index - 1];\n    if (index < list.Length - 1)\n        ceil = list[index + 1];\n}\nelse\n{\n    index = ~index;\n    if (index < list.Length)\n        ceil = list[index];\n    if (index > 0)\n        floor = list[index - 1];\n}\nConsole.WriteLine("floor = {0}", floor);\nConsole.WriteLine("ceil = {0}", ceil);	0
982698	982597	What is the fastest way to combine two xml files into one	var xml1 = XDocument.Load("file1.xml");\nvar xml2 = XDocument.Load("file2.xml");\n\n//Combine and remove duplicates\nvar combinedUnique = xml1.Descendants("AllNodes")\n                          .Union(xml2.Descendants("AllNodes"));\n\n//Combine and keep duplicates\nvar combinedWithDups = xml1.Descendants("AllNodes")\n                           .Concat(xml2.Descendants("AllNodes"));	0
5753132	5753112	how to create N Level xml file	var builder = new StringBuilder();\nusing (var writer = XmlWriter.Create(builder))\n{\n    writer.WriteStartElement("AlbumDetails");\n    writer.WriteStartElement("Album");\n    writer.WriteAttributeString("Id", "203");\n\n    writer.WriteElementString("Venue", "Wallingford School");\n\n    writer.WriteStartElement("PrintPackage");\n\n    .... etc.\n\n    writer.WriteEndElement(); // close PrintPackage\n\n    writer.WriteEndElement(); // close Album\n    writer.WriteEndElement(); // close AlbumDetails\n}\nConsole.WriteLine(builder.ToString());	0
8072188	8072172	C# Reference object in a collection by a string instead of integer	Dictionary<string, Foo>	0
7901378	7901360	Delete last char of string	strgroupids = strgroupids.Remove(strgroupids.Length - 1);	0
16478592	16478449	convert IntPtr to bitmapimage	Bitmap newBitmap = new Bitmap(width, height, Stride, PixelFormat, bitmapSource);	0
18255375	18255312	How to get method results with AsyncCallback?	test.EndCompensationPlan_Out_Sync(result)	0
8526992	8526866	Invoking Method on Object Instantiated From DLL	MethodInfo mInfo = classType.GetMethod("instrumentCommand");\n\nmInfo.Invoke(instrument_, new Object[] { _parameters});	0
10653206	10647358	XmlSerializer in WCF serialize wrong	[XmlSerializerFormat(SupportFaults=true)]	0
20473081	20472804	Events with lambda expression	private PointF[] points = new PointF[4];\n\n//Run once\npublic void Initialize()\n{\n    for (int i = 0; i < 4; i++)\n        buttons[i].Click += (s, e) => { show_coordinates(i); };\n}\n\npublic void Shuffle()\n{\n    for (int i = 0; i < 4; i++) \n    {\n        // here should be the computations of x and y\n        points[i] = new PointF(x,y);\n        // shuffling going on\n    }\n}\n\npublic void show_coordinates(int index)\n{\n    var point = points[index];\n    MessageBox.Show(point.X + " " + point.Y);\n}	0
30541019	30495740	How to get data from another table with ListView?	// Init\n        List<Message> msgs = CurrentUser.DisplayedMessages;\n        List<HooliganDB.Image> imgs = HooliganDB.Image.GetAll();\n\n        if (MessageList.Items.Count < CurrentUser.DisplayedMessages.Count)\n        {\n            // New messages found, rebind data\n            var resultTable = from m in msgs\n                              join i in imgs\n                              on m.ImageID equals i.ImageID\n                              select new\n                              {\n                                  MessageID = m.MessageID,\n                                  TimeStamp = m.TimeStamp,\n                                  Text = m.Text,\n                                  RoomID = m.RoomID,\n                                  ImageID = m.ImageID,\n                                  aspUserID = m.aspUserID,\n                                  Path = i.Path\n                              };\n\n            MessageList.DataSource = resultTable;\n            MessageList.DataBind();	0
25114120	25111008	How to set the focus on a child element with Modern UI	public LoginBasic()\n        {\n            InitializeComponent();\n            //FocusManager.SetFocusedElement(this, UserNameTextBox);\n            //Keyboard.Focus(UserNameTextBox);\n\n            this.IsVisibleChanged += LoginControl_IsVisibleChanged; \n\n\n        }\n\n\n\n\nvoid LoginControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n    {\n        if ((bool)e.NewValue == true)\n        {\n            Dispatcher.BeginInvoke(\n            DispatcherPriority.ContextIdle,\n            new Action(() => UserNameTextBox.Focus()));\n        }\n    }	0
2313754	2313728	Reusing a filestream	stream.SetLength(0)	0
25181867	25181829	How to read float values from binary file using c#?	float value = binaryReader.ReadSingle();	0
27140041	27139961	how to create a list of lists from one list using LINQ?	List<List<float>> lists = listVectors\n    .SelectMany(v => new[]{\n        new{k = 'x', v = v.x},\n        new{k = 'y', v = v.y},\n        new{k = 'z', v = v.z}})\n    .GroupBy(x => x.k)\n    .OrderBy(g => g.Key)\n    .Select(g => g.Select(x => x.v).ToList())\n    .ToList();	0
1154349	1154325	Better way to remove matched items from a list	myList.RemoveAll(IsMatching);	0
19180572	19176673	values not show in dropdownlist	DropDownList1.SelectedValue = "Some Value";	0
25547046	25546763	Timer only works in debug mode - c#	private static System.Threading.Timer timer;\n    private static System.Threading.Timer backupTimer;\n\n    static void Main(string[] args)\n    {\n\n        timer = new System.Threading.Timer(\n         e =>\n            {\n            //something\n        },\n        null,\n        TimeSpan.Zero,\n        TimeSpan.FromMinutes(1));\n\n\n        backupTimer = new System.Threading.Timer(\n         e =>\n         {\n             //something\n\n         },\n        null,\n        TimeSpan.Zero,\n        TimeSpan.FromHours(24));\n\n        Console.ReadLine();\n\n    }	0
7895885	7895554	Custom Events in C#	private void NewScan(Object param)\n{\n    Scan doScan = new Scan();\n    // Change the order so you subscribe first!\n    doScan.Text += new Scan.TextHandler(SetText);\n    doScan.StarScan(Convert.ToInt32(checkBoxBulk.Checked));\n}	0
15506062	15505992	Can you use C++ libraries natively in a C++/CLI WinForms application?	#include "NativeClass.h"\n\npublic ref class NativeClassWrapper {\n    NativeClass* m_nativeClass;\n\npublic:\n    NativeClassWrapper() { m_nativeClass = new NativeClass(); }\n    ~NativeClassWrapper() { delete m_nativeClass; }\n    void Method() {\n        m_nativeClass->Method();\n    }\n\nprotected:\n    // an explicit Finalize() method???as a failsafe\n    !NativeClassWrapper() { delete m_nativeClass; }\n};	0
2476806	2476748	writing 'bits' to c++ file streams	byte b;\nint s;\n\nvoid WriteBit(bool x)\n{\n    b |= (x ? 1 : 0) << s;\n    s++;\n\n    if (s == 8)\n    {\n        WriteByte(b);\n        b = 0;\n        s = 0;\n    }\n}	0
11850510	11850339	How to add Image button with stringbuilder in c#?	ImageButton imgBtn = new ImageButton();\n\nimgBtn.ImageUrl = @"~images\April.jpg";\n\nthis.Form.Controls.AddAt(0, imgBtn);	0
32792374	32791243	How do you set the readPreference for a single query against mongo using the c# driver	collection.WithReadPreference(ReadPreference.SecondaryPreferred).Find(...)	0
13005998	13005844	Intercept IE Context Menu Click in WebBrowser Control	// wb = WebBrowser control instance name\n// attach to the DocumentCompleted event\nwb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);\n\nvoid wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    // when the document loading is completed, attach to the document context showing event\n    wb.Document.ContextMenuShowing += new HtmlElementEventHandler(Document_ContextMenuShowing);\n}\n\nvoid Document_ContextMenuShowing(object sender, HtmlElementEventArgs e)\n{\n    // cancel showing context menu\n    e.ReturnValue = false;\n    // take a look at the 'e' parameter for everything else, you can get various information out of it\n}	0
16763234	16727215	how to set cursor position in gtk -Linux, MonoDevelop	Gdk.Display.Default.WarpPointer(Gdk.Display.DefaultScreen, 20, 20);	0
607921	607170	Databinding a Custom Control	#region IPropertyChanged\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected virtual void OnPropertyChanged(string propertyName)\n    {\n        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));\n    }\n\n    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)\n    {\n        if (null != PropertyChanged)\n        {\n            PropertyChanged(this, e);\n        }\n    }\n\n    #endregion	0
6825912	6825753	scheduler for Web-application	protected override void OnStart(string[] args)\n{ \n        var timer = new System.Timers.Timer();\n        timer.Elapsed += new ElapsedEventHandler(DoSomething);\n        //do something every 30 seconds\n        timer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds; \n        timer.Start();\n}\n\nprivate void DoSomething(object sender, ElapsedEventArgs e)\n{\n    //Do your timed event here...\n}	0
4097137	4097127	Getting Date or Time only from a DateTime Object	var day = value.Date; // a DateTime that will just be whole days\nvar time = value.TimeOfDay; // a TimeSpan that is the duration into the day	0
7150150	7149987	Looping trough lines of txt file uploaded via FileUpload control	private void populateListBox() \n{\n    FileUpload fu = FileUpload1; \n    if (fu.HasFile)  \n    {\n        StreamReader reader = new StreamReader(fu.FileContent);\n        do\n        {\n            string textLine = reader.ReadLine();\n\n            // do your coding \n            //Loop trough txt file and add lines to ListBox1  \n\n        } while (reader.Peek() != -1);\n        reader.Close();\n    }\n}	0
1929644	1929468	C# listbox to file listing	string source, fileToCopy, target;\nstring sourcefolder1 = @"K:\rkups";\nstring destinationfolder = @"K:\g_aa_ge\qc";\nDirectoryInfo di = new DirectoryInfo(destinationfolder);\nFileInfo[] annfiles;\n\nforeach (string s in listBox1.Items)\n{\n     fileToCopy = s;\n     source = Path.Combine(sourcefolder1, fileToCopy + ".ann");\n     target = Path.Combine(destinationfolder, fileToCopy + ".ann");\n     File.Copy(source, target);\n\n     annFiles = di.GetFiles("*.txt");\n\n     // Do whatever you need to do here...\n\n}	0
3249417	3249370	Is there a way to return the primary key of inserted record with NHibernate?	return newCar.Id;	0
370888	370571	Password protected PDF using C#	using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))\nusing (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))\n{\n    PdfReader reader = new PdfReader(input);\n    PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);\n}	0
13158410	12671194	Unable to download Office 365 SharePoint library item	var claimsHelper = new MsOnlineClaimsHelper(sharepointOnlineUrl, username, password);\n\nvar client = new WebClient();\nclient.Headers[ "Accept" ] = "/";\nclient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");\nclient.Headers.Add(HttpRequestHeader.Cookie, claimsHelper.CookieContainer.GetCookieHeader(new Uri(sharepointOnlineUrl))  );\n\nvar document = client.DownloadString( documentUrl );	0
24204820	24157581	C# validate input syntax and replace values	string data = "'({today} - ({date1} + {date2}))', 'user', 'info'"; // your string\n\nstring pattern = @"\{.*?\}"; // pattern that will match everything in format {anything}\nRegex regEx = new Regex(pattern); //create regex using pattern\n\nMatchCollection matches; // create collection of matches\nmatches = regEx.Matches(data); // get all matches from your string using regex\n\nfor (int i = 0; i < matches.Count; i++) // use this cycle to check if it s what you need\n{\n    Console.WriteLine("{0}", matches[i].Value);\n}	0
29293469	29271330	The type string is expected but a type integer was received with value 0	1) targeting_spec={"geo_locations":{"countries":"IN"]},"flexible_spec":[{"interests":["6006289279425"]}]}\n 2) targeting_spec={"geo_locations":{"countries":   ["IN"]},"interests":["6006289279425","46345343534"]}	0
3420376	3420366	How to split a string and assign each word to a new variable?	string[] nameParts = txtName.Text.Split(' ');\n\nstring firstName = nameParts[0];\nstring lastName = nameParts[1];	0
12747133	12745827	How to catch change event for a cell containing a formula	Function GetPrecedents(rInput As Range) As Range\n' Returns combined range of all precedents of the input range.\nDim rCell As Range, rPrec As Range, rOutput As Range\n\n    On Error Resume Next\n    For Each rCell In rInput\n        For Each rPrec In rCell.DirectPrecedents\n            If Not rPrec Is Nothing Then\n                If rOutput Is Nothing Then\n                    Set rOutput = rPrec\n                Else\n                    Set rOutput = Union(rOutput, rPrec)\n                End If\n            End If\n        Next\n    Next\n    Set GetPrecedents = rOutput\n\nEnd Function	0
4663026	4663008	How do I do division on HH:MM:SS format time strings in C#?	DateTime timeA = DateTime.Now;\n    DateTime timeB = DateTime.Now.AddHours(-10.0);\n\n    if ( (double)timeA.TimeOfDay.Ticks / (double)timeB.TimeOfDay.Ticks > 2.0f )\n        Console.WriteLine("Time A is more than twice time B");\n    else\n        Console.WriteLine("Time A is NOT more than twice time B");	0
28607715	28607604	Get all types and interfaces a class inherits from and implements in C#	var allInheritance = type.GetInterfaces().Union(new[] { type.BaseType});	0
22212280	22212151	How to use a serial field with Postgresql with Entity Framework Code First	public class Foo\n{\n    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]\n    public int displayID { get; set; }\n\n    [Key]\n    public int myKey { get; set; }\n\n}	0
15642644	15642507	Many NSTabViewItems in a Single NSTabView	? addTabViewItem:\n? insertTabViewItem:atIndex:\n? removeTabViewItem:	0
10496214	10496126	Hide placeholder if it has been shown before	if(Session["scriptRan"] != null) \n{\n    this.LoadScript.Visible = false; \n}\nelse\n{\n    Session["scriptRan"] = true;\n}	0
32951965	32950648	Enum to List<special> data	// Here's some example type definitions\npublic enum MyEnum {One, Two, Three};\n\npublic class MyClass : BaseClass {\n    public MyEnum EnumValue {get;set;}\n}\n\npublic class MyList : List<MyClass>\n\n\n// Here's how you'd use them\npublic void DoStuff() {\n    var list = new MyList();  // or new List<MyClass>();\n    list.Add(\n        new MyClass{ EnumValue = MyEnum.One },\n        new MyClass{ EnumValue = MyEnum.Two }\n    );\n\n    foreach (var item in list) \n    {\n        Console.WriteLine(item.EnumValue.ToString();\n    }\n\n}	0
17186882	17186641	How do I make letters to uppercase after each of a set of specific characters	string a = "fef-aw-fase-fes-fes,fes-,fse--sgr";\nchar[] chars = new[] { '-', ',' };\nStringBuilder result = new StringBuilder(a.Length);\nbool makeUpper = true;\nforeach (var c in a)\n{\n    if (makeUpper)\n    {\n        result.Append(Char.ToUpper(c));\n        makeUpper = false;\n    }\n    else\n    {\n        result.Append(c);\n    }\n    if (chars.Contains(c))\n    {\n        makeUpper = true;\n    }\n}	0
1197517	1197471	Accessing values in nested object[] inside of IList from Nhibernate ISQLQuery.List()?	foreach(var item in tags)\n{\n  int field1 = (int)item[0];\n  string field2 = (string)item[1];\n\n  // ...\n}	0
6778392	6777316	WPF Xaml passing Control in attribute	private static void OnHelpsListViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    // ListView listview = d as ListView;\n\n    // the propblem was with the line above, I was trying to convert the \n    // DependencyObject to a ListView and it's actually a TextBox, I should \n    // have been converting the new value of the DependencyProperty\n\n    TextBox box = d as TextBox;\n    ListView list = e.NewValue as ListView;\n    if(box == null || list == null) return;\n\n    box.PreviewKeyDown += delegate(object sender, KeyEventArgs e2)\n    {\n        if (e2.Key == Key.Down)\n            list.SelectedIndex += (list.SelectedIndex + 1 < list.Items.Count) ? 1 : 0;\n        else if (e2.Key == Key.Up)\n            list.SelectedIndex -= (list.SelectedIndex - 1 >= 0) ? 1 : 0;\n        else if (e2.Key == Key.Enter && list.SelectedIndex >= 0)\n        { \n            // do something for the enter key \n        }\n    };\n}	0
28834297	28833918	Convert ASCII file to Decimal file	class Program\n{\n    static void Main(string[] args)\n    {\n        string unconverted = "???"; // is what you get when using File.ReadAllText(file)\n\n        byte[] converted = Encoding.Unicode.GetBytes(unconverted);\n\n        converted = converted.Where(x => x != 0).ToArray(); //skip bytes that are 0\n\n        foreach (var item in converted)\n        {\n            Console.WriteLine(item);\n        }\n\n    }\n}	0
772051	772016	How to export pound symbol from a C# Web App to Excel correctly? (?? is produced instead of ?)	Response.Charset = "";\nResponse.ContentEncoding = System.Text.Encoding.Default;	0
12402656	12402613	Find memory consumed by simple console C# program	Process process = System.Diagnostics.Process.GetCurrentProcess();\nlong memoryUsedInBytes = process.WorkingSet64;	0
25054068	25040715	Outlook Addin - Get current selected calendar date	public void CreateCallenderItem_click(IRibbonControl control)\n{\n    // Get selected calendar date\n    Outlook.Application application = new Outlook.Application();\n    Outlook.Explorer explorer = application.ActiveExplorer();\n    Outlook.Folder folder = explorer.CurrentFolder as Outlook.Folder;\n    Outlook.View view = explorer.CurrentView as Outlook.View;\n\n    if (view.ViewType == Outlook.OlViewType.olCalendarView)\n    {\n        Outlook.CalendarView calView = view as Outlook.CalendarView;\n        DateTime calDateStart = calView.SelectedStartTime;\n        DateTime calDateEnd = calView.SelectedEndTime;\n\n        // Do stuff with dates. \n    }\n}	0
31498899	31497751	Multiple timers with different interval times in Windows Service	System.Threading.Timer	0
705989	697240	Setting XML Namepaces	rootNode.Add(new XElement(rt + "ChildNode", "Hello"));	0
2867502	2867429	Using lambda expressions and linq	IEnumerable<RemoteIssue> openIssues = AllIssues.Where(x=>\n        {\n            foreach (var v in desiredStatuses)\n            {\n                if (x.status == v)\n                    return true;\n            }\n            return false;\n        });	0
1641282	1641269	Finding a control within a TabControl	/// <summary>\n/// Finds a Control recursively. Note finds the first match and exists\n/// </summary>\n/// <param name="container">The container to search for the control passed. Remember\n/// all controls (Panel, GroupBox, Form, etc are all containsers for controls\n/// </param>\n/// <param name="name">Name of the control to look for</param>\npublic Control FindControlRecursive(Control container, string name)\n{\n    if (container == name) return container;\n\n    foreach (Control ctrl in container.Controls)\n    {\n        Control foundCtrl = FindControlRecursive(ctrl, name);\n\n        if (foundCtrl != null) return foundCtrl;\n    }\n\n    return null;\n}	0
22634415	22634236	How to read selected text on richTextBox?	richTextBox1.SelectedText	0
21032188	21032092	Match many regexes on the same string at once	bigregex = "(?:" + regex1 + "|" + regex2 + "|" + regex3 + ")"	0
20607301	20569198	Error in XML document	public static List<XmlData> DeserializeFromXml(string inputFile)\n    {\n        List<XmlData> mydata = new List<XmlData>();\n        XmlSerializer s = new XmlSerializer(typeof(List<XmlData>), new XmlRootAttribute("Asset"));\n        //XmlData[] deserializedObject = default(XmlData[]);\n       // byte[] byteArray = Encoding.UTF8.GetBytes(inputFile);\n     //   byte[] byteArray = Encoding.ASCII.GetBytes(inputfile);\n       // MemoryStream stream = new MemoryStream(byteArray);\n\n        Stream test = TitleContainer.OpenStream("pets.xml");\n        using (TextReader txtReader = new StreamReader(test))\n        {\n            mydata = (List<XmlData>)s.Deserialize(txtReader);\n        }\n\n        return mydata;\n    }	0
17288690	17288434	How to keep StateManagedCollection when created dynamically using C#?	protected void Page_Init(object sender, EventArgs e)\n{\n    BANANA.Web.Controls.BoundDataField field = null;\n    BANANA.Web.Controls.TemplateField tField = null;\n\n    tField = new BANANA.Web.Controls.TemplateField();\n    tField.ItemTemplate = new GridViewRadioButtonTemplate("APPSTATUS", _strRadioButtonID);\n    tField.ID = "APPSTATUS";\n    tField.Width = 30;\n    tField.HorizontalAlignment = BANANA.Web.Controls.HorizontalAlignment.Center;\n    this.FixedGrid1.Columns.Add(tField);\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        FixedGrid1.DataSource = _dt;\n        FixedGrid1.DataBind();\n    }\n}	0
12598166	12526177	How we can make subquery in linq using two different database	List<tbl_inv_emoheader> CheckMsgid = (from EMOheader in InvData.tbl_inv_emoheaders\n                                                  where (EMOheader.bln_export == true && (from i in GetEmail() select i).Contains(EMOheader.str_destbranch))\n                                                  select EMOheader).ToList();\n\n\nprivate static IEnumerable<string> GetEmail()\n    {\n        List<string> strEmails;\n        using (SharedSynchDataContext dc = new SharedSynchDataContext(Connections.Getencompass3()))\n        {\n            strEmails= (from l in dc.system_contacts\n                    where (l.rovctrlvan_email != string.Empty)\n                    select l.systemcode).ToList();\n        }\n        return strEmails;\n    }	0
1504549	1501079	DataGridView filtering	List<object> filteredData = new List<object>();\nforeach (object data in this.DataSource)\n{\n    foreach (var column in this.Columns)\n    {\n        var value = data.GetType().GetProperty(column.Field).GetValue(data,null)\n                                                            .ToString();\n        if (value.Contains(this.ddFind.Text))\n        {\n            filteredData.Add(data);\n            break;\n        }\n    }\n }\n\n this.ddGrid.DataSource = filteredData;	0
12517587	12517521	updating a list of records with linq-to-sql	using (SomeDC MyDC = new SomeDC())\n{\n    (from f in MyDC.Fruits\n               where TheFruitIDs.Contains(f.FruitID)\n               select f).ToList().ForEach(F => F.FruitSize = NewFruitSize);\n\n    MyDC.SubmitChanges();\n\n}	0
9881258	9880309	Creating a valid date from a MM/dd/yy format	DateTimeFormatInfo formatProvider = new DateTimeFormatInfo();\nformatProvider.Calendar.TwoDigitYearMax = DateTime.Now.Year;\n\nDateTime date = DateTime.ParseExact("12/12/22", "MM/dd/yy", formatProvider);	0
6907157	6907128	How to capture the first pattern after certain string	HtmlDocument doc = new HtmlDocument();\ndoc.Load("test.html"); // path to your HTML file\nvar node = doc.DocumentNode.SelectSingleNode("//td[@class='a10']");\nstring myDateString = node.InnerText;	0
16121212	16121083	Many-to-many without an inverse property	modelBuilder.Entity<Role>()\n    .HasMany(r => r.Privileges)\n    .WithMany() // <- no parameter = no inverse property\n    .Map(m =>\n    {\n        m.ToTable("RolePrivileges");\n        m.MapLeftKey("RoleId");\n        m.MapRightKey("PrivilegeId");\n    });	0
2609617	2608187	WPF ListView SelectedItem is null	private void CheckBox_Click(object sender, RoutedEventArgs e) {\n    var cb = sender as CheckBox;\n    var item = cb.DataContext;\n    myListView.SelectedItem = item;\n}	0
18569435	18569381	How to access individual fields within struct array	var values = handData.Select(x=>x.cardValue).ToArray();\nvar seeds = handData.Select(x=>x.cardSuit).ToArray();	0
21734398	21711779	Trim a Priority Queue	while (paraQueue.Count > newSize)\n{\n  paraQueue.Remove(paraQueue.Last());\n}	0
16613956	16612962	How to obtain Xml file path included in project, inside WebMethod	using System.Web;\n[WebMethod]\npublic static string GetLogs()\n{        \n    string resource = HttpContext.Current.Server.MapPath("Resource.xml");\n}	0
7199949	7199689	How Can I Change The Color Of Polyline Back to The Previous One On Click Google Api V2 C# Web App?	var activeColor = '#ff0000';\n var inactiveColor = '#0000FF';\n\n var points = [   \n                                   new GLatLng(24.85229, 67.01703),   \n                                   new GLatLng(24.914463, 67.0965958)]; \n                                   var polyline = new GPolyline(points, activeColor, 5, 0.7);  \n\nGEvent.addListener(polyline, "click", function() {\n           // swap activecolor with inactivecolor\n           var color = inactiveColor;\n           inactiveColor = activeColor;\n           activeColor = color;\n\n           // set activecolor\n           polyline.setStrokeStyle({ color: activeColor }); \n       }); \n       map.addOverlay(polyline);	0
27120106	27119883	Get email password from WPF application	Obfuscation is the process of renaming this meta-data in an Assembly so that it is no longer useful to a hacker but remains usable to the machine for executing the intended operations. It does not modify the actual instructions or mask them from observation by a hacker.	0
1110782	1110737	Can I Create a Web Service that has Properties?	var service = new Service();\nServiceData sd = new ServiceData();\nsd.ID = "ABC123";\nsd.Auth = "00000";\nservice.SD = sd;\nstring result = service.DoMyThing();	0
9633998	9633866	how to do sorting in repeater control using button click?	public void LinkButton2_Click(object sender, EventArgs e) \n{\n   //set the new select command with a ordery by\n   SqlDataSource1.SelectCommand = "SELECT * FROM [region_test] ORDER BY [regon_name]";\n\n   //refresh the repeater\n   rpt1.DataBind();\n}	0
25288492	25287960	Error of loading data from xml file in C# on dot net visual studio 2013 on win7	XDocument xml = XDocument.Load("xml.xml");\nXNamespace ns = "http://myWeb.com/MyApplication.xsd";\nvar element = xml.Root.Element(ns + "MyApplication").Element(ns + "myinformation");	0
18928791	18928730	C# Control 'tabControl' accessed from a thread other than the thread it was created on	if (tabControl.InvokeRequired) {\n     tabControl.Invoke(new Action(()=>{\n        RichTextBox rtb = (RichTextBox)tabControl.SelectedTab.Tag;\n        rtb.AppendText(strMessage + Environment.NewLine);\n         rtb.Select(rtb.Text.Length - 1, 0);\n         rtb.ScrollToCaret();\n     }));\n}	0
22964666	22964305	Write Date of last password change	MembershipUser u = Membership.GetUser("example@example.net");\ntxtPasswordChanged.Text = u.LastPasswordChangedDate.ToString("M/d/yyyy");	0
15794070	15794024	Saving a double array to a text file c#	File.WriteAllLines(\n    @"c:\data\myfile.txt" // <<== Put the file name here\n,   myDoubles.Select(d => d.ToString()).ToArray()\n);	0
13409500	13409425	Dictionary with Func as key	Func<int, int> f = x => x*x + 1;\n        Func<int, int> g = x => x*x + 1;\n        Console.WriteLine(f.Equals(g)); // prints False	0
19389487	19389454	Invalid expression term string in a method that accepts type as an argument	Wrapper.DecompressAndDeserialize(typeof(string), ms);	0
7905383	7891667	linq how to select a parent with a child collection that contains all of an array (or list) of values	var filteredGGs = from obj in gg                  \n                  let objAttribIds = obj.ProductAttributes\n                                        .Select(pa => pa.AttributeId)\n\n                  where !andAttributes.Except(objAttribIds).Any()\n\n                  select obj;	0
10414363	10413389	How to load resources from external assembly in WPF	Assembly asmbly = Assembly.LoadFrom("this_is_in_another_place/texts.dll")\n\n ResourceDictionary dic;\n\n using (Stream s = asmbly.GetManifestResourceStream("Texts.en-GB.xaml"))\n {\n    using (XmlReader reader = new XmlTextReader(s))\n    {\n        dic = (ResourceDictionary)XamlReader.Load(reader);\n    }\n }	0
17221584	17221561	DataTable distinct rows	DataTable getDistinctRows =	0
11118713	11118570	Error with saving and retrieving image from isolated storage	public void GetImages()   \n{   \n    string uri = "http://sherutnetphpapi.cloudapp.net/mini_logos/" + path;      \n    WebClient m_webClient = new WebClient();   \n    imageUri = new Uri(uri);   \n    m_webClient.OpenReadAsync(imageUri);  \n    m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_ImageOpenReadCompleted);   \n    m_webClient.AllowReadStreamBuffering = true;  \n\n} \n\n\nvoid webClient_ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) \n{        \n    var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication(); \n    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, System.IO.FileMode.Create, isolatedfile)) \n    { \n        byte[] buffer = new byte[e.Result.Length]; \n        while (e.Result.Read(buffer, 0, buffer.Length) > 0) \n        { \n            stream.Write(buffer, 0, buffer.Length); \n        } \n    }\n}	0
29983487	29983335	Bind HTML table on button click again	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n        LoadData();\n    }\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    //Write data to database\n    LoadData();\n}\n\nprivate void LoadData()\n{\n    using (SqlCommand cmd = new SqlCommand())\n    {\n        //Here goes your sql code that reads the database\n    }\n}	0
9967665	9967638	How to change the location of the splash screen image?	SplashScreenImage.jpg	0
28975839	28975733	C# avoid SQL Injection in a function	String[] parameters	0
12121107	12120845	How to go to the main window from popup in C# using "IWebDriver"?	for (String handle : driver.getWindowHandles()) {\n  driver.switchTo().window(handle);\n}	0
7272820	7272781	C# - Sorting a ListBox containing key/value pairs using LINQ	var sortedByKey = items.OrderBy(x => x.Split('=')[0]);\nvar sortedByValue = items.OrderBy(x => x.Split('=')[1]);	0
17678596	17678384	Count the number of Attributes in an XML Element	foreach (var element in config.DescendantsAndSelf())\n{\n    Console.WriteLine("{0}: {1} attributes", \n        element.Name, \n        element.Attributes().Count()\n    );\n}	0
18288657	18287989	multiplying number in a textbox to the quantity value	double amt = Convert.ToDouble(Amount.Text);\ndouble qnt = Convert.ToDouble(quantity.Value);\ndouble ans = amt * qnt;\nTotal.Text = ans.ToString();	0
21487615	21487401	Insert list of rows	for (int i = 0; i < dataPrescription.Rows.Count; i++)\n        {\n            string firstColumn = dataPrescription[0, dataPrescription.CurrentCell.RowIndex].Value.ToString();\n\n            string strMedications = "SELECT medicationID FROM MEDICATION WHERE medicationName=   ('" + firstColumn + "')";\n            SqlCommand cmdMedications = new SqlCommand(strMedications, connection);\n            SqlDataReader dr = new SqlDataReader(); //Insert this line in your code\n            SqlDataReader readMedications = cmdMedications.ExecuteReader();	0
22354862	22354774	Enable session in Web Api 2	public override void Init()\n{\n    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;\n    base.Init();\n}\n\nvoid MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)\n{\n    System.Web.HttpContext.Current.SetSessionStateBehavior(\n        SessionStateBehavior.Required);\n}	0
28510492	28509414	Registering for UIAutomation structure change events	CacheRequest request = new CacheRequest();\nrequest.TreeScope = TreeScope.Element | TreeScope.Descendants;\nusing (request.Activate())\n{\n    rootApplicationElement = AutomationElement.RootElement.FindAll(TreeScope.Children,\n           new PropertyCondition(AutomationElementIdentifiers.ProcessIdProperty, ApplicationInstance.ProcessId))[0];\n}	0
4780432	4780400	How to create web part to insert data in custom list	SPSite mySite = SPContext.Current.Site;  \nSPWeb myWeb = SPContext.Current.Web;  \nSPList myList = myWeb.Lists["Custom List"];  \nSPListItem myListItem = myList.Items.Add(); \nmyListItem["Title"] = oTextTitle.Text.ToString();  \nmyListItem["Employee Name"] = oTextName.Text.ToString();  \nmyListItem["Designation"] = oTextDesignation.Text.ToString();	0
4398419	4398270	How to split string preserving whole words?	static void Main(string[] args)\n    {\n        int partLength = 35;\n        string sentence = "Silver badges are awarded for longer term goals. Silver badges are uncommon.";\n        string[] words = sentence.Split(' ');\n        var parts = new Dictionary<int, string>();\n        string part = string.Empty;\n        int partCounter = 0;\n        foreach (var word in words)\n        {\n            if (part.Length + word.Length < partLength)\n            {\n                part += string.IsNullOrEmpty(part) ? word : " " + word;\n            }\n            else\n            {\n                parts.Add(partCounter, part);\n                part = word;\n                partCounter++;\n            }\n        }\n        parts.Add(partCounter, part);\n        foreach (var item in parts)\n        {\n            Console.WriteLine("Part {0} (length = {2}): {1}", item.Key, item.Value, item.Value.Length);\n        }\n        Console.ReadLine();\n    }	0
11126751	11108575	How to determine "real world" x, y coordinates from kinect depth data?	using (DepthImageFrame depthimageFrame = e.OpenDepthImageFrame())\n        {\n            if (depthimageFrame == null)\n            {\n                return;\n            }\n\n            pixelData = new short[depthimageFrame.PixelDataLength];\n\n            depthimageFrame.CopyPixelDataTo(pixelData);\n\n            for (int x = 0; x < depthimageFrame.Width; x++)\n            {\n                for (int y = 0; y < depthimageFrame.Height; y++)\n                {\n                        SkeletonPoint p = sensor.MapDepthToSkeletonPoint(DepthImageFormat.Resolution640x480Fps30, x, y, pixelData[x + depthimageFrame.Width * y]);                        \n                }\n            }\n\n        }	0
3510340	3510271	Using data from linq query	foreach (var order in results.Select(r => r.orderID).Distinct()) {\n   Console.WriteLine("Order: " + order);\n   Console.WriteLine("Items:");\n   foreach (var product in results.Where(r => r.orderItem == order)) {\n      Console.WriteLine(product.orderItem);\n   }\n}	0
8056436	8056321	Query to AS400 from a dataset	datasetname.tables[0].Rows[0].Item(0) \n\ndatasetname.tables[0].Rows[0].Item("ColumnName") \n\ndatasetname.tables[0].Rows[0][0] \n\ndatasetname.tables[0].Rows[0]["ColumnName"]	0
12809043	12808943	How can I get all Labels on a form and set the Text property of those with a particular name pattern to string.empty?	public void ClearLabel(Control control)\n{\n   if (control is Label)\n   {\n       Label lbl = (Label)control;\n       if (lbl.Text.StartsWith("label"))\n           lbl.Text = String.Empty;\n\n   }\n   else\n       foreach (Control child in control.Controls)\n       {\n           ClearLabel(child);\n       }\n\n}	0
25377037	25376799	How to create a context menu on datagrid and copy that value in winform	var str = YourDataGridView.Rows[ActiveCell.RowIndex].Cells[0].Value.ToString();\nClipboard.SetText(str);	0
33713247	33713186	Is it bad practice to store data in a library?	namespace traditional_poker\n{\n    public class poker\n    {\n       public class hand // use PascalCaseNamingConvention\n        {\n           public String Name\n            {\n                get; set;\n            }\n           public String[] cards // use PascalCaseNamingConvention\n            {\n                get; set;\n            }\n\n        }\n\n        List<hand> players;\n\n        public void AddPlayer(String name)\n        {\n            hand newHand = new hand();\n            newHand.Name = name;\n            players.Add(newHand); //null reference exception here! you should initialize players\n        }\n    }\n}	0
3603218	3603213	Including files in Silverlight app and retrieving in code as raw byte stream	Assembly.GetManifestResourceStream	0
18736021	18735936	Enumerator Int value convert to string three-digit base 2 number	int audioEncInt = (int)AudioEncoding.ADPCM_24Bit;\nstring audioEncStr = Convert.ToString(audioEncInt, 2).PadLeft(3, '0');	0
21609749	21609484	Enumerate files in mapped drive	var filenames4 =  System.IO.Directory\n            .EnumerateFiles("X:\\files\\", "*", System.IO.SearchOption.AllDirectories)\n            .Select(System.IO.Path.GetFileName); \n\n foreach (var file in filenames4)\n        {\n            Console.WriteLine("{0}", file);\n        }	0
33306598	33306222	Dont Listen Until Message Is Processed Windows Service	void ProcessCode() \n    {\n        while(true) {\n            //assuming that the Listen method blocks and waits for a message to be received.\n            var message = theListener.Listen("manager, "theQueue");\n            HandleMessage(message);\n        }\n    }	0
1416496	1416454	How to paste text in textbox current cursor?	var insertText = "Text";\nvar selectionIndex = textBox1.SelectionStart;\ntextBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);\ntextBox1.SelectionStart = selectionIndex + insertText.Length;	0
5319632	5319222	How to change the resolution of a WMV file in C#	MediaItem src = new MediaItem\n          (@"C:\WMdownloads\AdrenalineRush.wmv");\n      Job job = new Job();\n      job.MediaItems.Add(src);\n      job.ApplyPreset(Presets.VC1WindowsMobile);\n      job.OutputDirectory = @"C:\EncodedFiles";\n      job.Encode();	0
13405160	13404882	Format Data using Linq	IEnumerable<string> output = input\n    .GroupBy(i => i.Num)\n    .SelectMany(grp => grp.Select((item, idx) => string.Format("{0}_{1}", grp.Key, idx)));	0
18846717	18846524	Regex for capturing values in a delimited list	string str = "English (UK), French* , German and Polish  & Russian; Portugese and Italian";\n    string[] results = str.Split(new string[] { ",", ";", "&", "*" }, StringSplitOptions.RemoveEmptyEntries);\n    foreach (string s in results)\n        if (!string.IsNullOrWhiteSpace(s))\n            Console.WriteLine(s);	0
6716167	6716138	How to get this expression value model => model.Name?	return Convert.ToString(\n    expression.Compile().Invoke(modelInstance)\n);	0
2244337	2243669	How do I perform several string replacements in one go?	string foo = "the fish is swimming in the dish";\n\nstring bar = foo.ReplaceAll(\n    new[] { "fish", "is", "swimming", "in", "dish" },\n    new[] { "dog", "lies", "sleeping", "on", "log" });\n\nConsole.WriteLine(bar);    // the dog lies sleeping on the log\n\n// ...\n\npublic static class StringExtensions\n{\n    public static string ReplaceAll(\n        this string source, string[] oldValues, string[] newValues)\n    {\n        // error checking etc removed for brevity\n\n        string pattern =\n            string.Join("|", oldValues.Select(Regex.Escape).ToArray());\n\n        return Regex.Replace(source, pattern, m =>\n            {\n                int index = Array.IndexOf(oldValues, m.Value);\n                return newValues[index];\n            });\n    }\n}	0
2731815	2731778	send email C# using smtp server with username password authentification	mailclient.UseDefaultCredentials = true;	0
26851541	26851421	MouseHover code for a button in c# (to display a tooltp rectangle message)	toolTip1.SetToolTip(button1, "Underline");	0
11317873	11242482	C# - Get variable from webbrowser generated by javascript	foreach (HtmlNode link in root.SelectNodes("//script"))\n{\n    if (link.InnerText.Contains("+a+"))\n    {\n        string[] strs = new string[] { "var a='", "';document.write" };\n        strs = link.InnerText.Split(strs, StringSplitOptions.None);\n        outMail = System.Net.WebUtility.HtmlDecode(strs[1]);\n        if (outMail != "")\n        {\n            break;\n        }\n    }\n}	0
10498385	10498325	Find Item in ObservableCollection without using a loop	list.Where(x=>x.Title == title)	0
217452	125096	Can I turn off impersonation just in a couple instances	private WindowsImpersonationContext context = null;\npublic void RevertToAppPool()\n{\n    try\n    {\n        if (!WindowsIdentity.GetCurrent().IsSystem)\n        {\n            context = WindowsIdentity.Impersonate(System.IntPtr.Zero);\n        }\n    }\n    catch { }\n}\npublic void UndoImpersonation()\n{\n    try\n    {\n        if (context != null)\n        {\n            context.Undo();\n        }\n    }\n    catch { }\n}	0
21952926	21952542	How to set value from server side code to an asp.net TextBox with TextMode="Date"?	protected void Page_Load(object sender, EventArgs e)\n        {\n            this.txtExpenseDate.Text = DateTime.Now.ToString("yyyy-MM-dd");\n        }	0
11488849	11488720	Error while adding a row and then updating a row using EF	_db.ChampionCounters.Attach(champion);	0
11538799	11538644	The ObjectContext instance has been disposed and can no longer be used for operations that require a connection	using (var myEntities = new BusinessLogic.Entities())	0
1051879	1002427	How do I stop custom performance counter instance names from being auto converted to lower case	this.sharedCounter = new SharedPerformanceCounter(categoryName.ToLower(CultureInfo.InvariantCulture), this.counterName.ToLower(CultureInfo.InvariantCulture), this.instanceName.ToLower(CultureInfo.InvariantCulture), this.instanceLifetime);	0
33377318	33377187	Adding items to an array using a foreach loop in C#	foreach(string name in studentName)\n{\n    Console.Write("\tPlease enter a score for {0} <0 to 100>: ", name);\n    studentScore[counter] = Convert.ToInt32(Console.ReadLine());                \n    accumulator += studentScore[counter];\n    counter++;\n}\n\nConsole.WriteLine(accumulator);\nConsole.ReadLine();	0
3767862	3767846	Regex - match a string, but only where the next word is not 'x'	brown fox(?! that)	0
15380379	15380216	Passing multiple scalar parameters to WebAPI via HttpClient.PostAsJsonAsync	[HttpPost]\n[ActionName("TestString")]\npublic string TestString([FromBody] dynamic body)\n{\n  return "test " + body.a.ToString() + " " + body.b.ToString() + " " + body.c.ToString();\n}	0
33691642	33691165	'Cannot access a disposed object' error while saving object	public static void ConfirmationPaymentOrder(ConfirmPayments data)\n{\n    using (var dataContext = new DataContext(DBConnection))\n    {\n        foreach (OrdersConfirm orderConfirm in data.OrdersConfirm)\n        {\n            var result = SendRequestToConfirm(orderConfirm.Orders, orderConfirm.UserName, orderConfirm.Password);\n\n            dataContext.Orders.InsertOnSubmit(orderConfirm);\n        }\n        dataContext.SubmitChanges();\n    }\n}	0
407148	407130	Calling a C# method, and make it take 10 seconds to return	Thread.Sleep(TimeSpan.FromSeconds(10))	0
13084891	13084702	Best way to accept a generic method argument	TSource MyAction<TSource>(int id, TSource source, Action<T, TSource> action)\n        where TSource : IRead<T>; // TSource is now also returned from our method	0
17856869	17856726	How to check if a key exists in a MemoryCache	bool Contains(string key, string regionName)	0
3477033	3476995	out variables in a linq statement	var query = objectA.Where(a => a.type == 1)\n                   .Select(a => {\n                               string Field2;\n                               string Field3;\n                               TestMethod(a, out Field2, out Field3);\n                               return new {\n                                   a.Id, Field2, Field3\n                               };\n                           });\n                   .ToList();	0
12030205	12029446	C# screen scraper to grab values in sequential order	for (int i = 0; i < 32; i++)\n        {\n           string val=">" + i + "<";\n           int start= teamsURLFile.IndexOf(val);               \n           start = s.IndexOf(">",start+val.length);\n           int end = s.IndexOf("<",start);\n           string team= s.Substring(start, end - start -1);\n           //do whatever you want to do with team  \n\n        }	0
11053068	8300197	How to download a webpage in MetroStyle app (WinRT) and C#	public async Task<string> DownloadPageStringAsync(string url)\n    {\n        HttpClientHandler handler = new HttpClientHandler()\n        { UseDefaultCredentials = true, AllowAutoRedirect = true };\n\n        HttpClient client = new HttpClient(handler);\n        HttpResponseMessage response = await client.GetAsync(url);\n        response.EnsureSuccessStatusCode();\n        return await response.Content.ReadAsStringAsync();\n    }	0
16948340	16948280	How to remove instances from a List, which don't contain objects that match values from a Dictionary?	records.RemoveAll(x => \n    !(values.Any(v=>x.MyList.Contains(v)))\n);	0
15715232	15715029	Storing array in a c# data structure so it has behaves like a value	class Node\n{\n    private int[] _children;\n\n    public Node(int[] children)\n    {\n       this._children = (int[])children.Clone();//HERE IS THE IDEA YOU ARE LOOKING FOR\n    }\n\n    public int this[int index]\n    {\n        get { return this._children[index]; }\n        set { this._children[index] = value; }\n    }\n}	0
23605711	23568617	Windows Store App - XAML C# - How to access Page.Resource in code	object title = "NOT SET!";\n        object key = "PageName";\n        var page = (Page)rootFrame.Content;\n        page.Resources.TryGetValue(key, out title);	0
5093592	5093546	c# : Loading typed data from file without casting	.TryParse(...)	0
18864167	18863871	Show merge header in Gridview	protected void grvMergeHeader_RowCreated(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.Header)\n    {\n        GridView HeaderGrid = (GridView)sender;\n        GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);\n        TableCell HeaderCell = new TableCell();\n        HeaderCell.Text = "Employee Information";\n        HeaderCell.ColumnSpan = 3;\n        HeaderGridRow.Cells.Add(HeaderCell);\n\n        HeaderCell = new TableCell();\n        HeaderCell.Text = "Joining Date";\n        HeaderCell.ColumnSpan = 2;\n        HeaderGridRow.Cells.Add(HeaderCell);\n\n        grvMergeHeader.Controls[0].Controls.AddAt(0, HeaderGridRow);\n\n    }\n}	0
10476440	10476401	Distinct elements in LINQ	myCustomerList.GroupBy(product => product.Products_Id).Select(grp => grp.First());	0
17693045	17692845	How to choose the Data Stucture	static void Main(string[] args)\n        {\n            Table table = new Table();\n            int count1 = table.records.Where(r => r.Play == false && r.Outlook.ToLower() == "sunny").Count();\n        }\n\n        public class Record\n        {\n            public bool Play;\n            public string Outlook;\n        }\n\n\n        public class Table\n        {\n            //This should be private and Table should be IEnumarable\n            public List<Record> records = new List<Record>(); \n\n        }	0
22765940	22765390	Copying Shortcuts to Desktop	var shortcuts = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop))\n               .GetF??iles("*.lnk");\nstring destFolder = destinationDirectory.FullName;\nforeach(var f in shortcuts)\n    File.Copy(f.FullName, Path.Combine(destFolder,f.Name));	0
5005978	5005931	Listing values within enums using reflection in C#	System.Enum.GetNames(typeof(EVENT_TYPE))	0
17994200	17994043	how to use substring with a file path in c#	"C:\\TFS\\Deployment\\files\\1.0.1.1\\test\\test00.xml".Substring(0,31);	0
5580712	5580512	How to make the Close button disabled in a windows Form using C# coding	private const int dis_close_button = 0x200;\n    protected override CreateParams CreateParams\n    {\n        get\n        {\n            CreateParams ObjCP = base.CreateParams;\n            ObjCP.ClassStyle = ObjCP.ClassStyle | dis_close_button;\n            return ObjCP;\n        }\n    }	0
33874555	33874079	Build an executable file without Microsoft Visual Studio from project file	msbuild "C:\Users\Something\Documents\Visual Studio 2015\Blah path\Hello.csproj"	0
3195843	3195813	XML Serialization in C#	using System;\n\npublic class clsPerson\n{\n  public  string FirstName;\n  public  string MI;\n  public  string LastName;\n}\n\nclass class1\n{ \n   static void Main(string[] args)\n   {\n      clsPerson p=new clsPerson();\n      p.FirstName = "Jeff";\n      p.MI = "A";\n      p.LastName = "Price";\n      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());\n      x.Serialize(Console.Out, p);\n      Console.WriteLine();\n      Console.ReadLine();\n   }\n}	0
10604165	10604136	Assign Variable to another Variable and have changes in one be mirrored in the other	public class SomeMutableClass\n{\n    public string Name { get; set; }\n}\n\n// Two independent variables which have the same value\nSomeMutableClass x1 = new SomeMutableClass();\nSomeMutableClass x2 = x1;\n\n// This doesn't change the value of x1; it changes the\n// Name property of the object that x1's value refers to\nx1.Name = "Fred";\n// The change is visible *via* x2's value.\nConsole.WriteLine(x2.Name); // Fred	0
14199362	14199177	posting single item in json array to .net object	private Int32[] numbers;\n\n    public object Numbers\n    {\n        get { return numbers; }\n        set\n        {\n            if (value.GetType() == typeof(Int32))\n            {\n                numbers = new Int32[] { (Int32)value };\n            }\n            else if (value.GetType() == typeof(Int32[]))\n            {\n                numbers = (Int32[])value;\n            }\n        }\n    }	0
2762161	2762156	Passing 2D part of a 3D multidimensional array as a 2D method parameter array in C#	static byte[,][] array3d	0
16539689	16539516	File upload app is stuck	FtpWebRequest req = (FtpWebRequest)WebRequest.Create(@"ftp://" + **strUploadIP** + @"/" + strUser);\n    req.Method = WebRequestMethods.Ftp.MakeDirectory;\n    req.Credentials = new NetworkCredential(strUusername, strUpassword);\n    try {\n        using (var resp = (FtpWebResponse)req.GetResponse()) {\n            Console.WriteLine(resp.StatusCode);\n        }\n    } catch {\n        // TODO: Handle exception\n    }	0
5519537	5365506	UnitOfWork (NHibernate), only one active UoW/session at a time? (need advice)	if (HasActiveSession)\n{\n    isRootUnitOfWork = false;\n    session = GetActiveSession();\n}\nelse\n{\n    isRootUnitOfWork = true;\n    session = CreateSession();\n}	0
11122087	11121648	WPF localization with ResourceDictionary	var res = new ResourceDictionary {Source = new Uri("somepath")};\nthis.Resources.MergedDictionaries.Add(res);	0
20130	20061	Store data from a C# application	using (FileStream fs = new FileStream(....))\n{\n    // Read in stats\n    XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n    GameStats stats = (GameStats)xs.Deserialize(fs);\n\n    // Manipulate stats here ...\n\n    // Write out game stats\n    XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n    xs.Serialize(fs, stats);\n\n    fs.Close();\n}	0
29803254	29477610	Sharpdx tookit input won't work with windows 10 universal apps	using Windows.UI.Core;\nusing SharpDX.Toolkit;\nusing Windows.System;\nnamespace Example\n{\n    class MyGame : Game\n    {\n        public MyGame()\n        {\n            CoreWindow.GetForCurrentThread().KeyDown += MyGame_KeyDown;\n        }\n        void MyGame_KeyDown(CoreWindow sender, KeyEventArgs args)\n        {\n            System.Diagnostics.Debug.WriteLine(args.VirtualKey);\n        }\n    }\n}	0
3805933	3805883	Linq GroupBy Projection with Multiple Groups	foreach (var group in groups)\n {\n     foreach (var item in group)\n     {\n         string label = !string.IsNullOrEmpty(item.Section)\n                      ? item.Section\n                      : item.Label;\n\n         Console.WriteLine("{0,-8} | {1}", label, item.Data);\n     }\n\n     Console.WriteLine("-------------");\n }	0
11632687	11632326	Looking for a [maybe] design pattern	public final class PdfExtractorFactory {\n   public static PdfExtractor getExtractor(String filename) { ... }\n\n   ... // constructor, or singleton getter here\n}	0
1740827	1740698	WPF DataGrid control: adding the most recent row on top	myList.Insert(0, myobject);	0
3450888	3450821	How could HRESULT appear in an MIDL file?	import "oaidl.idl";\nimport "ocidl.idl";	0
1622237	1622202	How many newlines should a Mono application use between "using" statements, and the namespace declaration?	namespace SomeNameSpace {\n    using Something;\n    using SomethingElse;	0
412031	412014	Using a Timer in C#	this.Hide();\nvar t = new System.Windows.Forms.Timer\n{\n    Interval = 3000 // however long you want to hide for\n};\nt.Tick += (x, y) => { t.Enabled = false; this.Show(); };\nt.Enabled = true;	0
6901118	6901070	Getting selected value of a combobox	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    ComboBox cmb = (ComboBox)sender;\n    int selectedIndex = cmb.SelectedIndex;\n    int selectedValue = (int)cmb.SelectedValue;\n\n    ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;\n    MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        \n}	0
24554656	24554520	ASP.MVC 4 - Using First QueryString Parameter & Append to Action in Url	routes.MapRoute(\n    "CityRoute",\n    "{controller}/{action}/{City}",\n    new { controller = "House", action = "Location" }\n);	0
8210578	8176732	Set url in IHTMLDocument2	// 1. Create new document from URL\nIHTMLDocument2 NewDoc = (wb.Document as IHTMLDocument4).createDocumentFromUrl("http://www.stackoverflow.com", "null");\n// 2. Immediately stop navigating; the URL is still set\nNewDoc.execCommand("Stop", false, null);\n// 3. Now write your stuff to the document\n// ...	0
5087260	5087229	how to extract specific string from following using regex? the best way	// setup the input data\nstring inputString = "/asdfd...";\n\n// pull out string from beginning to second slash\n// firstPart = "/asdfd...fok-785452145x/"\nstring firstPart = inputString.Substring(0, inputString.IndexOf("/", 1));\n\n// grab last data element after the last hyphen\n// lastElement = "785452145x";\nstring lastElement = firstPart.Substring(firstPart.LastIndexOf("-") + 1);\n\n// do something with lastElement...	0
3381980	3379731	trigger on button click by keyboard input	private void abuttonispressed(object sender, System.Windows.Input.KeyEventArgs e)\n{\n    if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S)) \n    {\n        //click event is raised here\n        button1.Focus();\n        button1.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, button1));\n    } \n}	0
32227765	32227731	How to explicitly set ProcessAffectedObjects to false when using CaptureXml on AMO Server object?	bool processAffected	0
18312386	18279011	Max by primary key in EF	public int GetMaxPK<T>(this IQueryable<T> query, string pkPropertyName)\n{\n    // TODO: add argument checks\n    var parameter = Expression.Parameter(typeof(T));\n    var body = Expression.Property(parameter, pkPropertyName);\n    var lambda = Expression.Lambda<Func<T,int>>(body, parameter);\n    var result = query.Max (lambda);\n    return result;\n}	0
34228420	34227832	c# button click event. Extracting the coordinates from a two dimensional array	Button[,] buttons = new Button[10, 10];\n\nfor (int i = 0; i < buttons.GetLength(0); i++ )\n{\n     for(int j = 0; j < buttons.GetLength(1); j++)\n     {\n          buttons[i, j] = new Button()\n          {\n               Name = i + " " + j\n          };\n     }\n}	0
19139494	19136024	how to parse JSONString To Dataset?	DataSet myDataSet= JsonConvert.Deserialize<DataSet>(jsonstring)	0
11807817	11807423	How to read XML to create resx file	XMLTextReader reader = new XmlTextReader("FooBar.xml");\n\nResXResourceWriter writer = new ResXResourceWriter("FooBar.resx");\n\nwhile(reader.Read())\n{\n    if(reader.NodeType == XmlNodeType.Element && reader.Name == "string")\n       writer.AddResource(reader.GetAttribute("name"), reader.ReadString());\n}\n\nwriter.Generate();\nwriter.Close();	0
12252252	12252223	Connection to sql server express with visual studio 2010	using(var connection = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db2.mdf;Integrated Security=True;User Instance=True")\n{\n\n\n\n}	0
9375805	9375739	FileUpload in C# with PHP Server	using (var wc = new WebClient())\n{\n    wc.UploadFile("http://www.example.com/upload.php", "somefile.dat");\n}	0
8911566	8911366	Dealing with hours with no minutes when rounding DateTime to the 30 minutes	var now = DateTime.Now;\nDateTime result = now.AddMinutes(now.Minute >= 30 ? (60-now.Minute) : (30-now.Minute));\nresult = result.AddSeconds(-1* result.Second); // To reset seconds to 0\nresult = result.AddMilliseconds(-1* result.Millisecond); // To reset milliseconds to 0	0
17157016	17154917	How to add a trailing end of line to AttribueList using Roslyn CTP	var formattedUnit = (SyntaxNode)compUnit.Format(\n    new FormattingOptions(false, 4, 4)).GetFormattedRoot();\n\nformattedUnit = formattedUnit.ReplaceNodes(\n    formattedUnit.DescendantNodes()\n                 .OfType<PropertyDeclarationSyntax>()\n                 .SelectMany(p => p.AttributeLists),\n    (_, node) => node.WithTrailingTrivia(Syntax.Whitespace("\n")));\n\nstring result = formattedUnit.GetText().ToString();	0
4760480	4760410	Get access to resx file	MyFile.ResourceManager.GetString("PropertyOneName", MyFile.Culture)	0
1426149	1426129	Determine all referenced assemblies	Assembly.GetReferencedAssemblies	0
13339885	13339817	How to Bind with Combobox in silverlight	DisplayMemberPath="Title"\nSelectedValuePath="Title"\nSelectedValue="{Binding Path=Country,Mode=TwoWay}"	0
15216161	15215716	How to show a message with icon in notification are using C#	notifyIcon1.Visible = true;\nnotifyIcon1.Icon = SystemIcons.Exclamation;\nnotifyIcon1.BalloonTipTitle = "Balloon Tip Title";\nnotifyIcon1.BalloonTipText = "Balloon Tip Text.";\nnotifyIcon1.BalloonTipIcon = ToolTipIcon.Error;\nnotifyIcon1.ShowBalloonTip(1000);	0
14484864	14456572	Using Mail.dll with Microsoft Exchange Imap version 4	imap.Search(Flag.Seen)	0
24129852	24129633	UPDATE sql table value	cm.CommandText = "UPDATE ProduktTable SET [" + columnName + \n                 "] = @newValue WHERE Id = @id";\ncm.Parameters.Clear();\n\nSqlParameter sp_update_key = new SqlParameter();\nsp_update_key.ParameterName = "@id";\nsp_update_key.SqlDbType = SqlDbType.VarChar;\nsp_update_key.Value = IDNum;\ncm.Parameters.Add(sp_update_key);\n\nSqlParameter sp_update_value = new SqlParameter();\nsp_update_value.ParameterName = "@newValue";\nsp_update_value.SqlDbType = SqlDbType.VarChar;\nsp_update_value.Value = textBox2.Text;\ncm.Parameters.Add(sp_update_value);\ncn.Open();\ncm.ExecuteNonQuery();\ncn.Close();	0
3563887	3563794	How to decrypt the key	string signBase64 = ReadSignFromDB();//here you get the value from DB\nbyte[] bytes = Convert.FromBase64String(signBase64);\n//here you have created rsaCryptoServiceProvider;\nrsaCryptoServiceProvider.ImportCspBlob(bytes);	0
1918108	1777184	Simulating a keypress AND keyrelease in another application?	namespace ConsoleApplication1 \n{\nclass Program \n{ \n[DllImport("user32.dll")] \nstatic extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);\n\nstatic void Main(string[] args)\n{            \nwhile (true)\n{\nkeybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);\nThread.Sleep(3000);\n\nkeybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);\nThread.Sleep(1000);\n}\n}\n}\n\n}	0
11859704	11832212	Programmatically creating a treeview in sharepoint based on a column	using (SPSite Site = new SPSite(SPContext.Current.Site.Url + "/UberWiki"))\n{\n    using (SPWeb currentWeb = Site.OpenWeb())\n    {\n        // set the tree view properties\n        SPList list = currentWeb.GetList(currentWeb.Url+"/Lists/Pages");\n\n        SPFieldChoice field = (SPFieldChoice)list.Fields["Categories"];\n        treeView = new System.Web.UI.WebControls.TreeView();\n\n        // Add root nodes\n        foreach (string str in field.Choices)\n        {\n            rootNode = new System.Web.UI.WebControls.TreeNode(str);\n            treeView.Nodes.Add(rootNode);                        \n        }\n\n        // Add child nodes\n        foreach (SPListItem rows in list.Items)\n        {\n            childNode = new System.Web.UI.WebControls.TreeNode(rows["Title"].ToString());\n            treeView.FindNode(rows["Categories"].ToString()).ChildNodes.Add(childNode);\n        }\n    }\n    this.Controls.Add(treeView);\n    base.CreateChildControls();\n}	0
3436456	3436398	Convert a binary string representation to a byte array	string input ....\nint numOfBytes = input.Length / 8;\nbyte[] bytes = new byte[numOfBytes];\nfor(int i = 0; i < numOfBytes; ++i)\n{\n    bytes[i] = Convert.ToByte(input.Substring(8 * i, 8), 2);\n}\nFile.WriteAllBytes(fileName, bytes);	0
532841	532816	Read attributes values with linq	var feeds = (from item in doc.Descendants("item")\n             from category in item.Elements("category")\n             where category.Value=="Automotive" && \n                   category.Attribute("type").Value == "Channel"\n             select item).ToList();	0
24077947	24077819	Remove row from DataTable that contains value	DataRow[] result = dt2.Select("CtryCode = 'mm'");\nforeach (DataRow row in result)\n{\n    if (row["CtryCode"].ToString().Trim().ToUpper().Contains("MM"))\n    dt2.Rows.Remove(row);\n}	0
25653983	25653936	How to add a control from code-behind in a DIV	public void Page_Load(object sender, EventArgs e)\n{\n   var pnl = new Panel { ID = "Panel100" };\n   pnl.Controls.Add(new ImageButton());\n   Panel103.Controls.Add(pnl);\n}	0
22197853	22197700	Generate a random number if the number matched with the previous	Random _rand = new Random();\n  HashSet<int> _taken = new HashSet<int>();\n  object _syncRoot = new object();\n\n  private int RandomNumberGenerator() {\n    lock (_syncRoot) {\n      const int MAX_NUMBER = 10000;\n      if (_taken.Count == MAX_NUMBER) {\n        throw new Exception("All possible numbers are already generated.");\n      }\n\n      int random = _rand.Next(MAX_NUMBER);\n      while (_taken.Contains(random)) {\n        random = (random + 1) % MAX_NUMBER;\n      }\n      _taken.Add(random);\n      return random;\n    }\n  }	0
6801532	6786886	c# Crystal Report add sub report to a section	report.ReportClientDocument.SubreportController.ImportSubreportEx("Test", @"C:\test-sub.rpt", report.ReportClientDocument.ReportDefController.ReportDefinition.PageFooterArea.Sections[0], left, top, width, height);	0
7598392	7558880	FileStream Data Incomplete when Converting MemoryStream to FileStream	streamWriter.Flush();	0
31346249	31346124	Translate foreach to linq to solve running balance	var projected12MonthsBalance = months.Select(x => new SomeDate \n{ \n    Month = x, \n    Balance = SomeDates.TakeWhile(s => s.Month <= x).Sum(s => s.Balance) \n}).ToList();	0
1095087	1094480	How to bind a classes property to a TextBox?	txtComments.Text = customer.Comments;	0
8766454	8766364	How can I send key chords to text area with Selenium?	textarea.SendKeys(Keys.Shift + Keys.Enter);	0
1423954	1219520	TargetParameterCountException in Moq-based unit-test	public class Request\n    {\n        //...\n    }\n\n    public class RequestCreatedEventArgs : EventArgs\n    { \n        Request Request {get; set;} \n    } \n\n    //=======================================\n    //You must have sender as a first argument\n    //=======================================\n    public delegate void RequestCreatedEventHandler(object sender, RequestCreatedEventArgs e); \n\n    public interface IRepository\n    {\n        void Save(Request request);\n        event RequestCreatedEventHandler Created;\n    }\n\n    [TestMethod]\n    public void Test()\n    {\n        var repository = new Mock<IRepository>(); \n        Request request = new Request();\n        repository.Setup(a => a.Save(request)).Raises(a => a.Created += null, new RequestCreatedEventArgs());\n\n        bool eventRaised = false;\n        repository.Object.Created += (sender, e) =>\n        {\n            eventRaised = true;\n        };\n        repository.Object.Save(request);\n\n        Assert.IsTrue(eventRaised);\n    }	0
9770423	9486928	Render many elements to DrawingVisual	//temp visual\nDrawingVisual tmpVisual = new DrawingVisual();\nusing (DrawingContext dc = tmpVisual.RenderOpen())\n{\n     for (Int32 x = 0; x < widthCount; x++)\n          for (Int32 y = 0; y < heightCount; y++)\n          {\n              Color c;\n              Double value = mass[x, y];\n              c = GetColorByValue(value);\n              dc.DrawRectangle(new SolidColorBrush(c), null,\n                  new Rect(x * step - step / 2, y * step - step / 2, step, step));\n          }\n}\n\n//resize visual\ntmpVisual.Transform = new ScaleTransform(maxWidth/(widthCount * step),\n                        maxHeight/(heightCount * step));\n\n//visual to bitmap\nRenderTargetBitmap bitmap = \n    new RenderTargetBitmap(maxWidth, maxHeight, 96, 96, PixelFormats.Pbgra32);\nbitmap.Render(tmpVisual);\n\nusing (DrawingContext dc = Canvas.RenderOpen())\n{\n    Rect rect = new Rect(0, 0, widthCount * step, heightCount * step);\n    dc.DrawImage(bitmap, rect);\n}	0
7096340	7096309	Convert null field to zero before converting to int?	var LYSMKWh =\n    resultsDT.Rows[currentRow]["LYSMKWh"].Equals(DBNull.Value)\n    ? 0\n    : Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);	0
14606186	14605621	MySqlDataReader always Returning False even though data is there In Asp.net	public MySqlDataReader Consulta(String sql){\n            string connectionString = "Server=***;Port=3306;Database=****;UID=***;Pwd=****;pooling=false";\n   var conn = new MySqlConnection(connectionString);\n   conn.Open();\n\n   var cmd = new MySqlCommand(sql,conn);\n   var rs =cmd.ExecuteReader();\n   return (rs);\n}	0
9926957	9926231	Number formatting in c# - separate int and decimal parts	// works with either decimal or double\ndouble value = 123.095;\n\nvar mySpecialCurrencyFormat = new System.Globalization.NumberFormatInfo();\n\nmySpecialCurrencyFormat.CurrencyPositivePattern = 3;\nmySpecialCurrencyFormat.CurrencyNegativePattern = 8;\nmySpecialCurrencyFormat.NegativeSign = "-";\nmySpecialCurrencyFormat.CurrencySymbol = "cents";\nmySpecialCurrencyFormat.CurrencyDecimalDigits = 4;\nmySpecialCurrencyFormat.CurrencyDecimalSeparator = " dollars and ";\nmySpecialCurrencyFormat.CurrencyGroupSeparator = ",";\nmySpecialCurrencyFormat.CurrencyGroupSizes = new[] { 3 };\n\n\nConsole.WriteLine(value.ToString("C", mySpecialCurrencyFormat));	0
1877601	1877574	C# - Creating a List from an existing Dictionary	List<T>	0
14896362	14880548	Extended SqlProfileProvider, how do I call my custom method?	((MySqlProfileProvider)ProfileBase.Properties["ANY_PROFILE_PROPERTY"].Provider).ChangeConnectionString(sRequiredData);	0
26613544	26613488	How to pass parameters between two onclick event	public string username \n  { \n     get { return Session["username"] as string; }\n     set { Session["username"] = value; }\n  }	0
4207028	4207003	C# webBrowser Control how to get data under mouse pointer	webBrowser.Document.GetElementFromPoint(webBrowser.PointToClient(MousePosition))	0
2119367	2119337	C# Getting the Type of a Public Variable based on an Enum value	return typeof(DataBaseRecordInfo)\n    .GetProperty(field.ToString(), BindingFlags.Public | BindingFlags.Instance)\n    .PropertyType;	0
6150739	6150552	How to access html control value in code behind without using runat server?	string id = Request.Form["id"]	0
356911	356851	In C#, how do I invoke a DLL function that returns an unmanaged structure containing a string pointer?	[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct Info {\n\n    /// int\n    public int id;\n\n    /// char*\n    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]\n    public string szName;\n}\n\npublic partial class NativeMethods {\n\n    /// Return Type: Info*\n    ///id: int\n    [System.Runtime.InteropServices.DllImportAttribute("InfoLookup.dll", EntryPoint="LookupInfo")]\npublic static extern  System.IntPtr LookupInfo(int id) ;\n\n    public static LoopInfoWrapper(int id) {\n       IntPtr ptr = LookupInfo(id);\n       return (Info)(Marshal.PtrToStructure(ptr, typeof(Info));\n    }\n\n}	0
18026447	18024187	Windows Phone Resize an Image with a Storyboard	private void buttonStart_Click(object sender, RoutedEventArgs e)\n{\n    CreateAnimation(400, 200).Begin();\n}\n\nprivate Storyboard CreateAnimation(double from, double to)\n{\n    Storyboard sb = new Storyboard();\n    DoubleAnimation Animation = new DoubleAnimation();\n    Animation.From = from;\n    Animation.To = to;\n    Animation.Duration = new Duration(TimeSpan.FromSeconds(1.0));\n\n    Storyboard.SetTarget(Animation, ITEMNAME);\n    Storyboard.SetTargetProperty(Animation, new PropertyPath("(Width)"));\n\n    sb.Children.Add(Animation);\n\n    return sb;\n}	0
10450490	10450443	generic base class that implements interface	public abstract class BasePage<T> : Page, IBasePage where T : class { }	0
16346590	16346438	Convert FileUpload to X509Certificate2	var fileLength = file.PostedFile.ContentLength;\nvar certdata = new byte[fileLength];\n\nfile.FileContent.Read(certData, 0, fileLength);\n\nvar cert = new X509Certificate2(certData);	0
33900243	33900112	Path to store SQLite database in Xamarin Android	string path = Path.Combine(System.Enviroment.GetFolderPath(System.Enviroment.SpecialFolder.Personal), "data.txt");	0
27823778	27723655	Using RhinoMocks stub to return a value then an exception	var mockBLL = MockRepository.GenerateMock<IBLL>();\n\nmockBLL.Stub(x => x.SaveOrUpdateDTO(null, null))\n                   .IgnoreArguments()\n                   .Repeat.Twice()           // Allow to be called twice\n                   .WhenCalled(invocation =>\n            {\n                if (nSaveOrUpdateCount > 0)  // throw an exception if 2nd invocation\n                    throw new Exception();\n\n                nSaveOrUpdateCount++;\n            });\n\nSimpleIoc.Default.Register<IBLL>(() => mockBLL);	0
9274333	9274040	Uint to binary transfer	UInt64 a = 1234;\nfor (int i = 0; i < 64; i += 5)\n{\n    uint fiveBits = (uint)((a >> i) & 31);\n    // fiveBits is between 0 and 31\n}	0
186221	186160	How do I add to a list with Linq to SQL?	Item item;\nif (needNewOne)\n{\n     item = new Item();\n     db.InsertOnSubmit(item);\n}\nelse\n{\n     item = list[i];\n}\n///  build new or modify existing item\n///   :\ndb.SubmitChanges();	0
28278614	28277732	Error displaying data from DB to predefined columns of datagrid View on button click event	dataGridView1.Columns.Clear();\n            string getinputs = "SELECT ir.plu_code PLU_Code,ir.barcode Barcode,ir.product_name Product_Name  FROM inventory_register ir,inventory_value iv WHERE ir.dept_id='" + textBox1.Text + "' AND ir.barcode = iv.barcode";\n            connection.Open();\n\n            MySqlDataAdapter dataAdapter = new MySqlDataAdapter(getinputs, connection);\n            MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);\n            DataTable table = new DataTable();\n            dataAdapter.Fill(table);\n\n            datagridview1.DataSource = table;\n\n            connection.Close();	0
22597053	22597013	How to add new item to my list using C#?	list1[list1.Count() -1]	0
1905865	1905850	How do I convert a short date string back to a DateTime object?	DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);	0
18857672	18856200	Checking Updates from inside the App itself	WebResponse response= await request.GetResponseAsync();	0
31889591	31889556	Object with some fix properties and some dynamic properties serialization	public class TestClass : Dictionary<string, object>\n{\n    public string StudentName\n    {\n        get { return this["StudentName"] as string; }\n        set { this["StudentName"] = value; }\n    }\n\n    public string StudentCity\n    {\n        get { return this["StudentCity"] as string; }\n        set { this["StudentCity"] = value; }\n    }\n}	0
23274762	23274628	Using Iqueryable with Generic Repository doesn't find Records	_employeeRepository.Find()\n                .FirstOrDefault(i => i.User_Name == employee.User_Name)	0
20633430	20633268	Get WPF Name of shape at MouseDown Event	private void Superficie_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    string name = ((Shape)sender).Name;\n}	0
27947991	27947687	String of text search	var codes = "77,88,99".Split(',');\n\nvar predicate = PredicateBuilder.False<ZipCodes>();\nforeach(var c in codes)\n    predicate = predicate.Or(z=>z.ZipCode.Contains(c));\n\nvar answer = this.ZipCodes.Where(predicate).ToList();	0
24554041	24553976	c# windows phone 8.1 get button content as a string	private async void Holding(object sender, HoldingRoutedEventArgs) \n{\n    var obj = sender as Button;\n    var content = obj.Content;\n    await TextToSpeech(content);\n}	0
25153750	24128695	How to load Second View from First View with Xamarin/iOS	CallHistoryController callHistory = this.Storyboard.InstantiateViewController("CallHistoryController") as CallHistoryController;\nif (callHistory != null)\n{\n    this.NavigationController.PushViewController(callHistory, true);\n}	0
1068404	1068373	How to calculate the average rgb color values of a bitmap	BitmapData srcData = bm.LockBits(\n            new Rectangle(0, 0, bm.Width, bm.Height), \n            ImageLockMode.ReadOnly, \n            PixelFormat.Format32bppArgb);\n\nint stride = srcData.Stride;\n\nIntPtr Scan0 = srcData.Scan0;\n\nlong[] totals = new long[] {0,0,0};\n\nint width = bm.Width;\nint height = bm.Height;\n\nunsafe\n{\n  byte* p = (byte*) (void*) Scan0;\n\n  for (int y = 0; y < height; y++)\n  {\n    for (int x = 0; x < width; x++)\n    {\n      for (int color = 0; color < 3; color++)\n      {\n        int idx = (y*stride) + x*4 + color;\n\n        totals[color] += p[idx];\n      }\n    }\n  }\n}\n\nint avgB = totals[0] / (width*height);\nint avgG = totals[1] / (width*height);\nint avgR = totals[2] / (width*height);	0
9311296	9311051	Getting the correct encoding for a javascript file from a response stream to check against	script = script.TrimEnd();	0
12399253	12384736	Set button name from enum_	private void btnAddTerminatorElement_Click(object sender, RoutedEventArgs e)\n    {\n        Button button = (Button)sender;\n        MsoAutoShapeType shapeType = MsoAutoShapeType.msoShapeRectangle;\n\n        if (sender == this.btnAddTerminatorElement)\n            shapeType = MsoAutoShapeType.msoShapeFlowchartTerminator;\n\n        if (sender == this.btnAddDecisionElement)\n            shapeType = MsoAutoShapeType.msoShapeFlowchartDecision;\n\n        CreateChartElement(this.targetWorksheet.Shapes.AddShape(shapeType, 100, 100, 50, 50));\n    }	0
5990290	5990231	Convert a String to binary sequence in C#	string str = "Hello"; \nbyte []arr = System.Text.Encoding.ASCII.GetBytes(str);	0
20070457	20070131	C# filter multiline double quoted string with Regular expression	RegexOptions.SingleLine	0
566980	566940	Sorting a list based on string case	List<string> l = new List<string>();\n        l.Add("smtp:a");\n        l.Add("smtp:c");\n        l.Add("SMTP:b");\n\n        l.Sort(StringComparer.Ordinal);	0
299159	299117	How do I perform aggregation without the "group by" in Linq?	var average = (from a in MyStuff\n              select a.Value).Average();	0
19743720	19713039	Simple way to get number of rows in result set or ADO recordset	public void Main()\n{\n    ADODB.Recordset result = (ADODB.Recordset) Dts.Variables["result"].Value;\n    int rowCount = result.RecordCount;\n\n    Dts.TaskResult = (int)ScriptResults.Success;\n}	0
3451961	3451861	Algorithms for biased spawning of items	launcher_bias = 0.8*launcher_bias + 0.2*(1.0 - (last_item == launcher))\nrocket_bias = 0.8*rocket_bias + 0.2*(last_item == launcher)	0
19443634	19442708	Get and display json data in windows phone	Public MyJson()\n{\n   String myUrl = "Your WebService URL";\n   WebClient wc = new WebClient();\n   wc.DownloadStringAsync(new Uri(myUrl), UriKind.Relative);\n   wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);\n}\n\nprivate void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n{\n   var myData = e.Result;\n   // You will get you Json Data here..\n}	0
18750010	18749568	How do I code paths that are stored in database?	//Get active entries from table, call getWorkList\npublic static void WorkList(//Not sure of what path to use)\n{   \n//get active entries\n\nList<LogData> workList = GetWorkList();\n\nforeach(var work in workList)\n{\n    if(File.Exists(work.fileLocation))\n    {\n        File.Delete(work.fileLocation);\n    }\n}\n\n//check to see if date created in directory is older that x number of days\nif(DateTime.Now.Subtract(dt).TotalDays <= 1)\n{\n    log.Info("This directory is less than a day old");\n}\n//if file is older than x number of days\nelse if (DateTime.Now.Subtract(dt).TotalDays <= //not sure of what variable or property to use)\n{\n    File.Delete\n}\n//delete file	0
19811342	19811201	How to loop through a list of a generic type	IList list = val as IList; // note: non-generic; you could also\n                           // use IEnumerable, but that has some\n                           // edge-cases; IList is more predictable\nif(list != null)\n{\n    foreach(object obj in list)\n    {\n        strList.Add(obj.ToString());\n    }\n}	0
5730067	5729740	Compressing Pixel data to jpg/png format	//example 1: converting from bitmap\n        Bitmap myImage1 = new Bitmap(@"C:\myimage1.bmp");\n\n        myImage1.Save(@"C:\myimage1.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);\n        myImage1.Save(@"C:\myimage1.png", System.Drawing.Imaging.ImageFormat.Png);\n\n\n        //example 2: converting from pixels\n        Bitmap myImage2 = new Bitmap(10, 10);\n\n        //for loop to set some pixels\n        for (int x=0;x<10;x++)\n            for (int y=0;y<10;y++)\n                myImage2.SetPixel(x,y,Color.Blue);\n\n        myImage2.Save(@"C:\myimage2.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);\n        myImage2.Save(@"C:\myimage2.png", System.Drawing.Imaging.ImageFormat.Png);	0
34206107	34205974	How can i populate a treeview by ID and parentID using OLEDB	private void AddNode(List<Data> data, int parent)\n{\n    var parent = data.FirstOrDefault(x => x.ID == parent);\n    var dataItems = data.Where(x => x.Parent == parent);\n    foreach(var dataItem in dataItems)\n    {\n        AddNode(data, dataItem.ID);\n    }\n    Tree.Nodes.Add(parent.Name);\n}	0
22065540	22065388	MySql Linq to SQL conver int to string	var data = (from o in ObjectContext.MyTable.AsEnumerable().Where(d => d.a == a)\n                              select new MyObject\n                              {\n                                  Id = o.Id,\n                                  StringProperty = o.intColumn.ToString()\n                              });	0
26094697	26094500	EntityFramework: Add row function with row values as parameters	public ActionResult Create([Bind(Include = "Title,Body,SubTitle")]News model){\n  if (ModelState.IsValid){\n    ApplicationDbContext.News.Add(model);\n    ApplicationDbContext.News.SaveChanges();\n\n  }\n}	0
25077233	25077021	How to get path from a Content file from Helpers in C#/.net	string templatePath = Server.MapPath("/Content/templates/abc.html");	0
16524441	16522664	Cannot use Trace.WriteLine in Windows Store App	Debug.WriteLine	0
9048092	9047601	Is it possible to get the selected text of any window including non-UI automation elements?	CTRL + C	0
27227817	27226447	windows phone 8 change start page according to result from sqlite database	private async void Application_Launching(object sender, LaunchingEventArgs e) \n        { \n            try \n            { \n                await ApplicationData.Current.LocalFolder.GetFileAsync(DB_PATH); \n                Connection = new SQLiteAsyncConnection(DB_PATH); \n            } \n            catch (FileNotFoundException) \n            { \n              CreateDbAsync(); // create if not exists\n            } \n        }	0
18065499	18065323	Calculating first month of the current or next yearly quarter and the last month of the current yearly quarter based on a given date	int quarterCurr = 1;\nif (Convert.ToDouble(curMonth) / 3.0 > 1.0)\n{\n    quarterCurr = Convert.ToInt32(Convert.ToDouble(curMonth) / 3.0);\n    if (curMonth % 3 != 0)\n    {\n        quarterCurr = quarterCurr + 1;\n    }\n}\nint firstMonthCurr = 3 * (quarterCurr - 1) + 1;\nint lastMonthCurr = 3 * quarterCurr;\n\nint quarterNext = quarterCurr + 1;\nif (quarterNext > 4)\n{\n    quarterNext = 1;\n}\nint firstMonthNext = 3 * (quarterNext - 1) + 1;	0
23934851	23934481	User control does not retain private values, returns values set in Page_Load	public partial class MyControl: System.Web.UI.UserControl\n{\n   public int ControlID\n   {\n     get\n       {\n        if(ViewState["ControlID"]==null)\n           return 0;\n        return int.Parse(ViewState["ControlID"].ToString()); \n       }\n     set\n      {\n        ViewState["ControlID"] = value;\n      }\n   }\n  ....\n }	0
10633207	10633189	Getting HtmlDocument from string without using browser control	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar results = doc.DocumentNode\n    .Descendants("div")\n    .Select(n => n.InnerText);	0
23876563	23875403	How to display RowHeader in a GridView at runtime in C# Asp.Net?	var dt = new DataTable();\n\n//create columns\nfor(int i = 1; i <= 12; i++){\n    dt.Columns.Add(new DataColumn(i.ToString(CultureInfo.InvariantCulture), typeof(string)));\n}\n\n//create rows\nfor(int i = 0; i < 8; i++){\n    var newRow = dt.NewRow();\n    for(int j = 1; j <= 12; j++){\n        newRow[j.ToString(CultureInfo.InvariantCulture)] = string.Empty;\n    }\n    dt.Rows.Add(newRow);\n}\n\nmyGridView.DataSource = dt;\nmyGridView.DataBind();	0
20102011	20101944	button text change	btnEdit.Text = Request.QueryString["ID"] != null ? "Update" : "Add";	0
686084	686073	Ensure page is only accessed via SSL	If Not Request.IsSecure\n    Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))\nEnd If	0
19656458	19655411	Sorting list with linq by multiple parameters	var query = \n   db.Foos\n     .OrderBy(f =>\n         f.BusinessType == "A01 - Production" ? 0 :\n         f.BusinessType == "A06 - External trade without explicit capacity" ?\n           (f.InArea == "ME" ? 1 : (f.OutArea == "ME" ? 2 : 6)) :\n         f.BusinessType == "A02 - Internal trade" ? 3 :\n         f.BusinessType == "A04 - Consumption" ? 4 : 5)\n     .ThenBy(f =>\n         f.BusinessType == "A06 - External trade without explicit capacity" ?\n             (f.InArea == "ME" ? f.OutArea : \n             (f.OutArea == "ME" ? f.InArea : ""))  : "");	0
9670580	9648436	Fluent NHibernate IList<string>	HasMany(x => x.AddressLines).Element("AddressLine").Cascade.AllDeleteOrphan();	0
31598438	31597531	How to map properties of inner/nested classes in DataGridView through BindingSource?	public class MyGridClass\n{\n    public string FileName { get; set; }\n    public string Directory { get; set; }\n    public string Number { get; set; }\n    public string Prop1 { get; set; }\n    public string Prop2 { get; set; }\n}\n\nNesInfo ni = ...\n\nMyGridClass gc = new MyGridClass ( );\ngc.FileName = ni.FileName;\ngc.Directory = ni.Directory;\ngc.Number = ni.MapperInfo.Number;\ngc.Prop1 = ni.MapperInfo.Prop1;\ngc.Prop2 = ni.MapperInfo.Prop2;	0
8901663	8901476	Creating Windows Folders using impersonation	using (var impersonation = new ImpersonatedUser(decryptedUser, decryptedDomain, decryptedPassword))\n{\n  Directory.CreateDirectory(newPath);\n}	0
21430430	21430345	How can I remove year from my date with moment.js?	moment(StartDate, "MMM DD HH:mm");	0
9175419	9175384	Centering contents of a div - using CSS	text-align:center;	0
26752898	26752826	How to drag & drop only one file on form window	public Form1()\n{\n    InitializeComponent();\n    this.AllowDrop = true;\n    this.DragEnter += Form1_DragEnter;\n    this.DragDrop += Form1_DragDrop;\n}\n\nvoid Form1_DragEnter(object sender, DragEventArgs e)\n{\n    if (e.Data.GetDataPresent(DataFormats.FileDrop))\n        e.Effect = DragDropEffects.Copy;\n}\n\nvoid Form1_DragDrop(object sender, DragEventArgs e)\n{\n    var files = (string[])e.Data.GetData(DataFormats.FileDrop);\n    if (files.Length == 1)\n    {\n        // do what you want\n    }\n    else\n    {\n        // show error\n    }\n}	0
12983451	12983427	Accessing Form's Controls from another class	public partial class Form1 : Form\n{\n    // Static form. Null if no form created yet.\n    private static Form1 form = null;\n\n    private delegate void EnableDelegate(bool enable);\n\n    public Form1()\n    {\n        InitializeComponent();\n        form = this;\n    }\n\n    // Static method, call the non-static version if the form exist.\n    public static void EnableStaticTextBox(bool enable)\n    {\n        if (form != null)\n            form.EnableTextBox(enable);\n    }\n\n    private void EnableTextBox(bool enable)\n    {\n        // If this returns true, it means it was called from an external thread.\n        if (InvokeRequired)\n        {\n            // Create a delegate of this method and let the form run it.\n            this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable });\n            return; // Important\n        }\n\n        // Set textBox\n        textBox1.Enabled = enable;\n    }\n}	0
5127579	5127113	Key value schema to store GeoSpatial data?	{ loc: [20,30] } \n{ loc: { x: 20, y: 30 }}\n{ loc: { foo: 20, y: 30}}\n{ loc: { lat : 40.739037, long: 73.992964 } }	0
12865160	12865049	How to make pluggable static classes	public static class DB\n{\n    private static IDbInterface _implementation;\n\n    public static void SetImplementation(IDbInterface implementation)\n    {\n        _implementation = implementation;\n    }\n\n    public static Customer GetCustomerByID(int custId)\n    {\n        return _implementation.GetCustomerByID(custId);\n    }\n\n    ...\n}	0
15582141	15581938	Better way to extract coordinates from a string using regex	var results = Regex.Matches(Coord, @"X=(?<X>-?\d+.?\d+)\s+Y=(?<Y>\d+.?\d+)");\n\nfor (int i = 0; i < results.Count; i++)\n{\n    Console.WriteLine(string.Format("X={0} Y={1}", results[i].Groups["X"], results[i].Groups["Y"]));\n}	0
28972647	28972579	how to convert type 'string' to 'string[]' in c#?	String[] Boe;\n Boe = new String[1]; <---- i think the error might also be here \n BS = new Rectangle();\n for (int p = 0; p < 1; p++)\n {\n   //some code have been taken out \n\n     Boe[p] = "Yes"; <----- this is where the error is being displayed \n }	0
15481475	15481147	How to add a dynamically link in a dynamically added table	Page.Controls.Add(link);//Will add control in page\ncell.Controls.Add(link);//Will add control in table cell	0
15354747	15338089	How can i parse html file in windows phone 7?	HtmlDocument html = new HtmlDocument();\nhtml.Load(path_to_file);\nvar urls = html.DocumentNode.SelectNodes("//ul[@class='slides']/li/img")\n                            .Select(node => node.Attributes["src"].Value);	0
20873622	20857090	Coming from SQL to EF6 Which loading method should I start with? Lazy Loading, Explicit loading, Eager loading	questions.Select(q => new { q.ID, q.Title, AnswerCount = q.Answers.Count() })	0
5737569	5737481	How do you set up StructureMap to use a Singleton with the Use<>.For<> syntax	For<IFoo>().Singleton().Use<Bar>();	0
29695806	29678162	How to convert a C# object initializer to use a constructor using Resharper structural find and replace	public class Fruit\n{\n    public Fruit(string name, bool isTasty)\n    {\n        Name = name;\n        IsTasty = isTasty;\n    }\n\n    public string Name { get; set; }\n    public bool IsTasty { get; set; }\n}	0
1919957	1919887	OwnerDraw ComboBox with VisualStyles	// Draw Expand (plus/minus) icon if required\nif (ShowPlusMinus && e.Node.Nodes.Count > 0)\n{\n// Use the VisualStyles renderer to use the proper OS-defined glyphs\nRectangle expandRect = new Rectangle(iconLeft-1, midY - 7, 16, 16);\n\nVisualStyleElement element = (e.Node.IsExpanded) ? VisualStyleElement.TreeView.Glyph.Opened\n : VisualStyleElement.TreeView.Glyph.Closed;\n\nVisualStyleRenderer renderer = new VisualStyleRenderer(element);\nrenderer.DrawBackground(e.Graphics, expandRect);\n}	0
3113697	3113539	Can a windows form display the min and max buttons without the close button?	public partial class Form2 : Form\n{\n    public Form2()\n    {\n        InitializeComponent();\n        if (EnableMenuItem(GetSystemMenu(this.Handle, 0), SC_CLOSE, MF_GRAYED) == -1)\n            throw new Win32Exception("The message box did not exist to gray out its X");\n    }\n    private const int SC_CLOSE = 0xF060;\n    private const int MF_GRAYED = 0x1;\n    [DllImport("USER32")]\n    internal static extern int EnableMenuItem(IntPtr WindowHandle, int uIDEnableItem, int uEnable);\n    [DllImport("USER32")]\n    internal static extern IntPtr GetSystemMenu(IntPtr WindowHandle, int bReset);\n}	0
13604621	13604507	Parsing JSON with Newtonsoft	var str = @"{""think"":{""median"":1.24531,""test"":6.2342}}";\ndynamic dyn = JsonConvert.DeserializeObject(str);\nConsole.WriteLine((double)dyn.think.median);	0
12923626	12923505	Passing strings in c# to a static statement	// property\npublic SqlConnection myConnection { get; set; }\n\n// method\npublic SqlConnection GetSqlConnection()\n{\n     if (myConnection == null) \n       myConnection = new SqlConnection("user id=" + us + ";" +\n                                       "password=" + pas + ";server=PANDORA;" +\n                                       "Trusted_Connection=yes;" +\n                                       "database=NHS; " +\n                                       "connection timeout=30");\n\n     return myConnection;\n}	0
4487439	4487371	Getting dynamically added child controls to display in the UI	protected override void Render(HtmlTextWriter writer)\n{\n    base.Render(writer);\n    _otherReason.RenderControl(writer);\n}	0
24891449	24890858	Objective C equivalent of byte in C#	int64_t Encrypt(NSString *p) {\n    const char *cString = [p cStringUsingEncoding: NSASCIIStringEncoding];\n\n    unsigned long length = strlen(cString);\n    int64_t c = 31;\n    for (int i = 0; i < length; i++)\n        c = c * 47 + cString[i] % 97;\n\n    return c;\n}\n\nNSString *p = @"help";\nNSLog(@"p: %@", p);\n\nint64_t c = Encrypt(p);\nNSLog(@"c: lld", c);	0
11928948	11928887	Refresh ObservableCollection<T> when a property in T changes - WPF MVVM	DelegateCommand<Series> DeleteCommand { get; set; } \nDeleteCommand = new RelayCommand<Series>(OnDelete); \n\n// This method will gets execute on click the of Delete Button1\nprivate void OnDelete(Series series) \n{\n}	0
29198303	29198073	Get Random Color	public partial class Form1 : Form\n{\n    private Random rnd = new Random();\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));\n        BackColor = randomColor;\n    }\n}	0
27501291	24237052	Mapping a List using a Custom Resolver with Automapper	Mapper.CreateMap<CustomType1, CustomType2>()\n    .ForMember(x => FirstPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5)))\n    .ForMember(x => SecondPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5, 5)));\n\nMapper.CreateMap<Example1, Example2>();	0
20219183	20202171	Resize winrt page when on on screen keyboard showing	private void InputPaneShowing(InputPane sender, InputPaneVisibilityEventArgs args)\n {\n    args.EnsuredFocusedElementInView = true;\n    this.EditBox.Margin = new Thickness(0, 0, 0, args.OccludedRect.Height);\n };	0
26943070	26943054	Identify a Date range in a string	resultString = Regex.Match(subjectString, \n    @"(?<=\()         # Make sure the previous character is a (\n    \w+\s+\d+,\s+\d+  # Match a date\n    \s*\p{Pd}\s*      # Match a dash, surrounded by optional whitespace\n    \w+\s+\d+,\s+\d+  # Match a date\n    (?=\))            # Make sure the following character is a )", \n    RegexOptions.IgnorePatternWhitespace).Value;	0
14435919	14435867	Reset backcolor C# of 8*8 array	private void button1_Click(object sender, EventArgs e)\n{\n        for (int x = 0; x < btn.GetLength(0); x++)\n        {\n            for (int y = 0; y < btn.GetLength(1); y++)\n            {\n                btn[x, y].BackColor = Color.Black;\n            }\n        }\n}	0
7690422	7690389	C# - Unexpected results when converting a string to double	var str = "20.616378139";\nvar dbl = double.Parse(str, System.Globalization.CultureInfo.InvariantCulture);	0
17164328	17164276	how to call constructor from static constructor in c# so that normal constructor is executed first	public sealed class Singleton\n{\n    // I'd usually make it a property in real code, backed by a readonly field\n    public static readonly Singleton Instance;\n\n    static Singleton()\n    {\n        Instance = new Singleton();\n    }\n\n    private Singleton()\n    {\n        // Only invoked from the static constructor\n    }\n}	0
24219267	24219244	Cannot deserialize a JSON object	var stats = JsonConvert.DeserializeObject<List<Model_MarketStats>>(json);	0
17175961	17175916	send a email with C# via default email application (thunderbird, Outlook)	System.Diagnostics.Process.Start("mailto:test@test.com?subject=Hello&body=This%20is%20a%20test");	0
7388418	7388348	Need a little help with SelectMany	var query = from tuple in enumerable\n            from replacement in ReplacementFunction(tuple.Item1)\n            select Tuple.Create(replacement, tuple.Item2);	0
12727950	12725927	c# excel how to change a color of a particular row	Excel.Application application = new Excel.Application();\nExcel.Workbook workbook = application.Workbooks.Open(@"C:\Test\Whatever.xlsx");\nExcel.Worksheet worksheet = workbook.ActiveSheet;\n\nExcel.Range usedRange = worksheet.UsedRange;\n\nExcel.Range rows = usedRange.Rows;\n\nint count = 0;\n\nforeach (Excel.Range row in rows)\n{\n    if (count > 0)\n    {\n        Excel.Range firstCell = row.Cells[1];\n\n        string firstCellValue = firstCell.Value as String;\n\n        if (!string.IsNullOrEmpty(firstCellValue))\n        {\n            row.Interior.Color = System.Drawing.Color.Red;\n        }\n    }\n\n    count++;\n}\n\nworkbook.Save();\nworkbook.Close();\n\napplication.Quit();\n\nMarshal.ReleaseComObject(application);	0
24758456	24757706	Assigning Programmatic Dataset to Report	xsd file.xsd {/classes | /dataset} [/element:element]\n         [/language:language] [/namespace:namespace]\n         [/outputdir:directory] [URI:uri]	0
19348225	19163980	Custom PSHostUserInterface is ignored by Runspace	powershell.AddCommand("Write-Host").AddParameter("Testing...")	0
7218902	7217603	EF 4.1: Find Key Property Type from Code First with Fluent Mapping	public class MyContext : DbContext\n{\n\n    public void Test()\n    {            \n        var objectContext = ((IObjectContextAdapter)this).ObjectContext;\n\n        var mdw = objectContext.MetadataWorkspace;\n\n        var items = mdw.GetItems<EntityType>(DataSpace.CSpace);\n        foreach (var i in items)\n        {\n            Console.WriteLine("Class Name: {0}", i.Name);\n            Console.WriteLine("Key Property Names:");\n            foreach (var key in i.KeyMembers)\n            {\n                Console.WriteLine(key.Name);\n            }\n        }\n }	0
27860682	27860622	Get Data from DB With EF	var context = new EntitiesContext();//DbContext Object\n var list = ent.Customers; // will return all customers.	0
10577969	10568510	MonoDroid: Path to Assets to unzip a file with .NET framework	using (var stream = Context.Assets.Open("MyZipFolder/MyZip.zip"))\n { \n      var s = new ZipInputStream(stream);\n      // do read here ...\n }	0
30274860	30274313	Shortest way from a number to another in a clamped range	float a,b, bound1, bound2; // input data\nvar path1 = b - a; // straight way\nvar absPath1 = Math.Abs(path1);\nvar range = bound2 - bound1;\nvar path2 = range - absPath1 + 1;\nif(b > a) path2 = -path2;\nvar absPath2 = Math.Abs(path2);\nvar shortestPath = absPath1 > absPath2 ? path1 : path2;	0
31224695	31224617	How to selectively implement only one part of the interface	public interface IReadRepository<T>\n{\n    T Get(int id);\n}\n\npublic interface IWriteRepository<T> : IReadRepository<T>\n{\n    void Add(T entity);\n}	0
7064761	7064444	DataGridView RowValidating fires after selecting another control. Any workaround?	private void dataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e) {\n        Point pos = dataGridView.PointToClient(Control.MousePosition);\n        DataGridView.HitTestInfo hi = dataGridView.HitTest(pos.X, pos.Y);\n        if (hi.Type == DataGridViewHitTestType.Cell && hi.RowIndex != e.RowIndex) {\n            e.Cancel = !AllowChangeCurrent(); //Check if changing selection is allowed\n        }\n    }	0
12274104	12273256	RestSharp: Converting results	public class DealerResponse\n{\n    public bool valid { get;set; }\n    List<Dealer> data { get;set; }\n}\n\npublic class Dealer\n{\n    public string dealerId;         \n    public string branchId;   \n}	0
897570	897552	Assert that arrays are equal in Visual Studio 2008 test framework	CollectionAssert.AreEqual	0
24172412	24172283	Splitting list into two lists based on certain criteria	void Main()\n{\n        var names = new string[] {"Frank", "Jules", "Mark", "Allan", "Frank", "Greg", "Tim"};\n        var listA = new List<string>();\n        var listB = new List<string>();\n\n        // I'm not entirely sure where this comes from other than it's always\n        // the first element in the "names" list.\n        var needle = names[0]; // "Frank"\n\n        // this finds the location of the second "Frank"\n        var splitLocation = Array.IndexOf(names, needle, 1);\n\n        // here we grab the first elements (up to the splitLocation)\n        listA = names.Take(splitLocation).ToList();\n        // here we grab everything past the splitLocation\n        // (starting with the second "Frank")\n        listB = names.Skip(splitLocation).ToList();\n}	0
8265662	8207919	how to set gridview column item style in c#	GridView1.DataSource = ds.Tables[0];\nGridView1.DataBind();\nif (ds.Tables[0].Rows.Count > 0)\n{\n     int numberOfColumn = ds.Tables[0].Columns.Count;\n     if (numberOfColumn >= 5) // Since the 5th column you want to unwrap\n     GridView1.Columns[5].ItemStyle.Wrap = false;\n }	0
1262128	1262115	How do you display a custom UserControl as a dialog?	private void Button1_Click(object sender, EventArgs e)\n{\n    Window window = new Window \n    {\n        Title = "My User Control Dialog",\n        Content = new MyUserControl()\n    };\n\n    window.ShowDialog();\n}	0
10807836	10806577	Read data from socket, send response and close	int port = 12345;\n            IPAddress serverAddress = IPAddress.Parse("127.0.0.1");\n            TcpListener listener = new TcpListener(serverAddress, port);\n            listener.Start();\n\n            while (true)\n            {\n                TcpClient client = listener.AcceptTcpClient();\n\n                NetworkStream stream = client.GetStream();\n                byte[] data = new byte[client.ReceiveBufferSize];\n                int bytesRead = stream.Read(data, 0, Convert.ToInt32(client.ReceiveBufferSize));\n                string request = Encoding.ASCII.GetString(data, 0, bytesRead);\n                Console.WriteLine(request);\n                byte[] msg = System.Text.Encoding.ASCII.GetBytes("200 OK");\n\n                // Send back a response.\n                stream.Write(msg, 0, msg.Length);\n                client.Close();\n            }	0
19316513	19316285	Regex- replace x{n} with x{n-2}	var result = Regex.Replace(inputStr, "(A*)AA", "$1");	0
26955236	25168525	Facebook Login for Windows Phone 8.1	protected override void OnActivated(IActivatedEventArgs args)\n    {\n        if (args.Kind == ActivationKind.Protocol)\n        {\n            ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;\n\n            Uri responseUri = eventArgs.Uri;\n\n           //Now you can use responseUri to retrieve the access token and expiration time of token\n\n        }\n\n        base.OnActivated(args);\n    }	0
25740470	25738283	IOException HResult possible values	& 0xffff	0
3041914	3041883	How do I enumerate all the fields in a PDF file in ITextSharp	AcroFields af = ps.AcroFields;\n\n        foreach (var field in af.Fields)\n        {\n            Console.WriteLine("{0}, {1}",\n                field.Key,\n                field.Value);\n        }	0
30580056	30579701	Failed to open a handle to the device when opening GPIO pin	GPIO#   Power-on Pull   Header Pin\n4       PullUp           7\n5       PullUp          29\n6       PullUp          31\n12      PullDown        32\n13      PullDown        33\n16      PullDown        36\n17      PullDown        11\n18      PullDown        12\n19      PullDown        35\n20      PullDown        38\n21      PullDown        40\n22      PullDown        15\n23      PullDown        16\n24      PullDown        18\n25      PullDown        22\n26      PullDown        37\n27      PullDown        13\n35      PullUp          Red Power LED\n47      PullUp          Green Activity LED	0
7617768	7617032	inject class in to using statement with spring.net	IMyClassFactory _processorFactory; //inject this\nusing(var p = _processorFactory.Create())\n{\n  p.RunClass();\n}	0
8198872	8198672	filter a linq query based on the results of another query's results	var stores = ctx.Stores.Where(ps => ps.ParentStoreID == parent.ParentStoreID && ps.StoreID!=storeID);\n\nvar query = (from a in ctx.TransactionTable\n            from b in ctx.MappingTable.Where(x => x.TransactionId==a.TransactionId).DefaultIfEmpty()\n            where a.StoreID!=storeID && stores.Select(s => s.StoreID).Contains(a.StoreID)\n            select new\n            {\n                Transactions = a,\n                Mapping = b\n            }).ToList();	0
4064585	4064330	Regular Expression; extracting numbers from strings with the equals sign as the delimiter	// string input = "<your input>";\nMatch m = Regex.Match(input, @"\s*(?<dec>\d+)\s*=");\nList<int> intList = new List<int>();\n\nwhile (m.Success)\n{\n    intList.Add(Int32.Parse(m.Groups["dec"].Value));\n    m = m.NextMatch();\n}\n\n// Process intList	0
2967552	2966891	Displaying a WPF Window by name	string windowClass = "CreateWindow.MyWindow";\nType type = Assembly.GetExecutingAssembly().GetType(windowClass);\nObjectHandle handle = Activator.CreateInstance(null, windowClass);\nMethodInfo method = type.GetMethod("Show");\nmethod.Invoke(handle.Unwrap(), null);	0
11018419	11018365	Serialize A List That Contains Arrays & Other Lists	[Serializable]\npublic class MapData\n{\n    [Serializable]\n    public struct tileDataBackground\n    {\n        public int tileTextureX;\n        public int tileTextureY;\n    }\n ...	0
19220310	19220249	Convert a string containing monthName to Int of MonthDigit	int monthInDigit = DateTime.ParseExact(month, "MMM", CultureInfo.InvariantCulture).Month;	0
5735732	5735692	How do I access a file outside of my xap file in Silverlight	new Uri(App.Current.Host.Source, "../test.wmv");	0
7973030	7972974	How do I capture this latitude value in regex?	string GPSLocation = "Lat:42.747058 Long:-84.551892";\nvar values = GPSLocation.split(" ");\nif (values.Count > 0)\n{\n    string lat = values[0].split(":")[1];\n    return Decimal.Parse(lat);\n}\nreturn 0M;	0
1706534	1706519	How can I sort by a column that is included in a new{} section of a LINQ query?	var products = (from ... ).OrderBy(item => item.TotalPrice);	0
14636008	14376459	Azure Storage container size	long size = 0;\nvar list = container.ListBlobs();\nforeach (CloudBlockBlob blob in list) {\n    size += blob.Properties.Length;\n}	0
4278079	4278039	How to search int[] Array in list or Entity?	void (Run(int[] QTaskId)\n{\n var Que = calculateCtx.QTaskRelations.Where(q => QTaskId.Contains(q.QTaskId)).Select(q => q);\n}	0
6871211	6871122	Converting a string of numbers to a byte array, keeping their display value.	byte[] bytes = data.Select(c => (byte)(c - '0')).ToArray();	0
12700422	12700361	Map multiple PK with Entity Framework	[Key, System.ComponentModel.DataAnnotations.Schema.Column(Order = 0)]\n    public int ID { get; set; }\n\n\n    [Key, System.ComponentModel.DataAnnotations.Schema.Column(Order = 1)]\n    public int workflow_id { get; set; }	0
22059687	22059136	Store reference to method with unknown signature in C#	NotificationManager.RegisterObserver(this.ThirdParty, \n    "ThirdPartyData", \n    (i,j) => \n        {\n             // call the third party method\n             this.ThirdParty.ThirdPartyMethod(null, false, i);\n             // other custom logic here using j (the action dictionary)\n        });	0
31379177	31379074	How to remove the specific characters using regex	string inputStr = @"[SuppressMessage(""Microsoft.Globalization"", ""CA1303:Do not pass literals as localized parameters"",\nMessageId = ""YouSource.DI.Web.Areas.HelpPage.TextSample.#ctor(System.String)"",\nJustification = ""End users may choose to merge this string with existing localized resources."")]\n[SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"",\nMessageId = ""bsonspec"",\nJustification = ""Part of a URI."")]\npublic int Get1Number([FromBody]string name)";\nConsole.WriteLine(Regex.Replace(inputStr, @"(^|\s*)\[[\s\S]*?\]\s*public\s+", string.Empty));\n\npublic is also removed	0
20565666	20563979	How to assert id which changes with successive registered user using selenium webdriver?	if(Driver.getPageSource().contains("Success! Successfully saved with id:")){\n //Your page has the text.. \n //This is Java you need to convert to C#\n}	0
28021032	28020777	How to push json into a nested array - angularjs	JSON.parse("{\"IsCustomer\":false, \"UserText\":\"\", \"OptionItems\":[ {\"OptionId\":1,\"SortOrder\":1,\"OptionName\":\"Complaint\"}, {\"OptionId\":2,\"SortOrder\":2,\"OptionName\":\"Request\"}, {\"OptionId\":3,\"SortOrder\":3,\"OptionName\":\"Enquiry\"}]}")	0
15548927	15548829	How to read xml file using linq	var items = from item in xdoc.Descendants("item")\n       select new\n       {\n           Title = item.Element("title").Value,\n           Year = item.Element("year").Value,\n           Categories = item.Descendants("categories").Descendants().Select(x=>x.Value).ToList(),\n           Count = item.Element("count").Value\n       };	0
14143383	14143226	??# - how to parallel code that lock several object one by one	Parallel.Invoke(new ParallelOptions(), () =>\n    {\n        lock (securitiesLock)\n        {\n            while (!args.securitiesUpdates.IsNullOrEmpty())\n                securities.Enqueue(args.securitiesUpdates.Dequeue());\n        }\n    },\n    () =>\n    {\n        lock (orderUpdatesLock)\n        {\n            while (!args.orderUpdates.IsNullOrEmpty())\n                orderUpdates.Enqueue(args.orderUpdates.Dequeue());\n        }\n    },\n    () =>\n    {\n        lock (quotesLock)\n        {\n            while (!args.quotesQueue.IsNullOrEmpty())\n                quotes.Enqueue(args.quotesQueue.Dequeue());\n        }\n    });	0
19284482	19283557	Format Date with culture in Razor @Html.EditFor	[DataType(DataType.Date)]	0
13967840	13967672	Regex instead of string.replace function	string dotsPattern = @"\.\.+"; //2 or more dots.\nfname=Regex.Replace(fname, dotsPattern ,".");\nString firstSymbolDot = @"^\.";\nfname = Regex.Replace(fname, firstSymbolDot, String.Empty);\nstring symbolPattern = "[&#{}%~?]"; //any of given symbol;\nstring result = Regex.Replace(fname, symbolPattern, "_");	0
10072670	10072430	A Simple Wpf MVVM Binding Issue	View.DataContext = ViewModel	0
13797947	13797847	How to update two dictionaries concurrently	private object m_methodMonitor = new object();\n\nprivate void Update()\n{\n    lock (m_methodMonitor)\n    {\n        // Do whatever\n    }\n}\n\n\nprivate void Delete()\n{\n    lock (m_methodMonitor)\n    {\n        // Do whatever\n    }\n}	0
26105908	26105858	Casting a list of an object to another with implicit conversion	IEnumerable<myObject1> original; \n// ...\nIEnumerable<myObject2> converted = original.Cast<myObject2>();	0
12871784	12871768	Edit label control from other form	subForm sf = new subForm ();\n    sf.lblText.Text = "High";  \n    sf.ShowDialog();	0
16543178	16542996	Compare a nullable-int and a string for equality in C#	public static bool ObviouslyEquals<T>(this string  s, T? t) where T: struct\n    {\n        if (s == null && !t.HasValue)\n            return true;\n        if (s == null || !t.HasValue)\n            return false;\n        return s.Equals(t.Value.ToString());\n    }\n\n\nstring s;\nint? i; \nif (s.ObviouslyEquals(i))...	0
18284354	18284335	Adding concatenated strings as listbox items	string text = textBox1.Text + "hrs, " + \n              textBox2.Text + "min, " + \n              textBox3.Text + "sec.";\n\nif (checkBox1.Checked) text += " Novelty: " + textBox4.Text;\nlistBox1.Items.Add(text);	0
18495693	18494566	Building a htmlTable with dynamic rows and columns using C#	int totalObjects = rivers.Count;\nint totalCells = desiredRows * desiredColumns;\nHtmlTableRow newRow = new HtmlTableRow();\nfor( i = 0; i < totalCells; i++ )\n{\n    // make a new row when you get the desired number of columns\n    // skip the first, empty row\n    if( i % desiredColumns == 0 && i != 0 )\n    {\n        myTable.Rows.Add( newRow );\n        newRow = new HtmlTableRow();\n    }\n    // keep putting in cells\n    if( i < totalObjects )\n        row.Cells.Add(new HtmlTableCell(rivers[i]));\n    // if we have no more objects, put in empty cells to fill out the table\n    else\n        row.Cells.Add(new HtmlTableCell(""));\n}	0
6781816	6781523	WPF Get element at specific coordinates	foreach (FrameworkElement nextElement in myCanvas.Children)\n{\n    double left = Canvas.GetLeft(nextElement);\n    double top = Canvas.GetTop(nextElement);\n    double right = Canvas.GetRight(nextElement);\n    double bottom = Canvas.GetBottom(nextElement);\n    if (double.IsNaN(left))\n    {\n        if (double.IsNaN(right) == false)\n            left = right - nextElement.ActualWidth;\n        else\n            continue;\n    }\n    if (double.IsNaN(top))\n    {\n        if (double.IsNaN(bottom) == false)\n            top = bottom - nextElement.ActualHeight;\n        else\n            continue;\n    }\n    Rect eleRect = new Rect(left, top, nextElement.ActualWidth, nextElement.ActualHeight);\n    if (myXY.X >= eleRect.X && myXY.Y >= eleRect.Y && myXY.X <= eleRect.Right && myXY.Y <= eleRect.Bottom)\n    {\n        // Add to intersects list\n    }\n}	0
18464421	18464086	How do I represent the data of combo box as integer	string listVal = "";\nif(storedVal == 0)\n{\n    listVal = "Active";\n}\nelse if(storedVal == 1)\n{\n    listVal = "Inactive";\n}\nelse if(storedVal == 2)\n{\n    listVal = "Working";\n}\n\nif(listVal != "")\n{\n    // add to listbox\n}	0
26475757	26461639	How to know if user exists in AD Group efficiently	var context =  new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain);\nGroupPrincipal group = new GroupPrincipal(context,\n    farm.Properties[GlobalNavigationConstants.Keys.GlobalNavigationOneDriveADGroup].ToString());\n\nUserPrincipal usr = UserPrincipal.FindByIdentity(context, \n                                           IdentityType.Sid, \n                                           SPContext.Current.Web.CurrentUser.Sid);  \n\nvar found = usr.IsMemberOf(group);	0
3183436	3183334	How to make an email notifier like google calendar?	public void SendEmail()\n    {\n        MailMessage loMsg = new MailMessage();\n\n        loMsg.From = new MailAddress("from@domain.com");\n        loMsg.To.Add(new MailAddress("to@domain.com"));\n        loMsg.Subject = "Subject";\n        loMsg.Body = "Email Body";\n\n\n        var 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 System.Net.NetworkCredential("username", "password")\n        };\n\n        smtp.Send(loMsg);\n        }	0
18536569	18536034	Format text in string	void Main()\n{\n\nvar i = 10545;\nvar t = i.ToString().PadLeft(6, '0');\n\nvar d = DateTime.ParseExact(t, "HHmmss", System.Globalization.CultureInfo.InvariantCulture );\n\nConsole.WriteLine(string.Format("{0:HH:mm:ss}", d));\n}	0
24288977	24282467	Fancybox doesn't work after a success of an ajax call	jQuery(".delete a").fancybox({\n    'content': jQuery('#eliminar-cuenta').html(),\n     'type': 'html',\n    'modal': false,\n    'showCloseButton': false,\n    'onComplete': function () {\n        jQuery("input[type=checkbox]").uniform()\n\n        jQuery('#privacidad').fancybox({\n            enableEscapeButton: false,\n            hideOnOverlayClick: false,\n            showCloseButton: true,\n            onComplete: function () {\n                jQuery('#fancybox-close').off().on('click', function (e) {\n                    e.preventDefault();\n                    jQuery(".delete a").click();\n                });\n            }\n        });\n    }\n});	0
21829567	21820123	Label for TextBox in ContextMenu in WPF	ContextMenu contextMenu = new ContextMenu();\nMenuItem xMenuItem = new MenuItem();\n\nStackPanel panel = new StackPanel() { Orientation = Orientation.Horizontal };\n\nLabel label = new Label();\nTextBox xTextBox = new TextBox();       \n\npanel.Children.Add(label);\npanel.Children.Add(xTextBox);\n\nxMenuItem.Header = panel;\n\ncontextMenu.Items.Add(xMenuItem);	0
4497654	4490087	populate dropdown list from a list of objects	public class City\n{\n    int id;\n    string name;\n\n    public City(int id, string name)\n    {\n        this.id = id;\n        this.name = name;\n\n    }\n\n    public int Id\n    {\n        get { return id; }\n        set { id = value; }\n    }\n    public String Name\n    {\n        get { return name; }\n        set { name = value; }\n    }\n\n}	0
20156391	20156039	Injecting javascript with BHO using C# - how to escape strings properly	string jsonStr = @"[ \n  {""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },\n  { ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },\n  { ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }\n]";	0
24621296	3028192	How can i create array of my class with default constructor?	var a = Enumerable.Repeat(new MYCLASS(), 10).ToArray();	0
18471378	18471311	Creating a Dictionary in C# from an existing array	Dictionary<string, string> myDict = new Dictionary<string,string>();\n\n//Make sure your array has an even number of values\nif (myArray.Length % 2 != 0) \n    throw new Exception("Array has odd number of elements!");\n\nforeach (int i = 0; i < myArray.Length; i+=2)\n{\n    myDict.Add(myArray[i], myArray[i + 1]);\n}	0
26646513	26646392	How to get parameterized query?	Logger.Verbose(cmd.CommandText.Replace("@id", id.ToString()));	0
31980654	31980625	Unsubscribe from events in observableCollection	collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collection_CollectionChanged);\n\n// ...\n// and add the method\nvoid collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n{\n    if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)\n    {\n        foreach (var it in e.OldItems) {\n            var custclass = it as CustomClassName;\n            if (custclass != null) custclass.SomeEvent -= OnSomeEvent;\n        }\n    }\n}	0
8295740	8295612	Posting a message to a wall from code behind	var facebookClient = new FacebookClient(FbConf.testimonialsAppId, FbConf.testimonialsAppSecret);\n\n            IDictionary<string, string> parameters = new Dictionary<string, string>();\n\n            parameters.Add("message","message on the wall"));\n            parameters.Add("created_time", DateTime.Now.ToString());\n\n            dynamic result = facebookClient.Post(string.Format("{0}/feed", FbConf.testimonialsAppId), parameters);\n            var id = result.id;	0
9978634	9978564	Lambda expression and InvokeOperation	public void LoadEntities(QueryBuilder<Device> query, Action<ServiceLoadResult<Device>> callback, object state)\n    {\n        InvokeOperation<List<DivisionHierarchy>> obj = this.Context.GetAllDivisions();\n\n        obj.Completed += (sender, e) =>\n        {\n           try\n           {\n               if (sender is InvokeOperation<List<DivisionHierarchy>>)\n               {\n                   ObservableCollection<DivisionHierarchy> divisions = \n                       new ObservableCollection<DivisionHierarchy>((sender as InvokeOperation<List<DivisionHierarchy>>).Value);\n\n               }\n           }\n           catch  \n           {                 \n           }\n       } \n     }	0
3558160	3558081	Looking inside a lambda / expression tree	MethodCallExpression call = (MethodCallExpression)f2.Body;\nConstantExpression arg = (ConstantExpression)call.Arguments[0];\nConsole.WriteLine(arg.Value);	0
17728807	17728791	Multiple optional parameters calling function	myfunc(a, c:5);	0
10032600	10032330	Searching an array of XML Nodes	XmlNode[] nodes = ...;\nstring value = nodes.Single(n => n.LocalName == "Node2").InnerXml;\n// or .InnerText, depending on what you need.	0
10742508	10741004	Get Func<T> and Expression<Func<T>> from single parameter?	static void Assert(Expression<Func<bool>> assertionExpression) {\n    var func = assertionExpression.Compile(); // if you call func() it will execute the expression\n}	0
9381486	9380668	Populate relational objects in Entity	db.Defects.Include("Project").Where(d => d.DefectId.Equals(id));	0
20660688	20659830	Can I place multiple arrays on one chart using simple loop in c# instead of doing it one series at a time?	var arrayData = new[]\n    {\n        new double[100],\n        new double[100],\n        new double[100],\n        new double[100],\n        new double[100]\n    };\n\n    // values to the first five arrays are assigned here...\n    arrayData [0][0] = 1; // <- first element of the first array\n    arrayData [0][1] = 2; // <- second element of the first array\n    arrayData [1][0] = 1; // <- first element of the second array\n    arrayData [3][51] = 2; // <- fifty-second element of the fourth array\n\n    foreach (var series in chart1.Series)\n    {\n        foreach (var arrayItem in arrayData)\n        {\n            series.Points.AddXY(someGenericValue.ToString(), arrayItem);\n        }\n    }	0
4102090	4101182	hide node in treeview control	protected void Page_Load(object sender, EventArgs e)\n{\n  RemoveNodeRecurrently(TreeView1.Nodes, "Status");\n}\n\nprivate void RemoveNodeRecurrently(TreeNodeCollection childNodeCollection, string text)\n{\n  foreach (TreeNode childNode in childNodeCollection)\n  {\n    if (childNode.ChildNodes.Count > 0)\n      RemoveNodeRecurrently(childNode.ChildNodes, text);\n\n    if (childNode.Text == text)\n    {\n      TreeNode parentNode = childNode.Parent;\n      parentNode.ChildNodes.Remove(childNode);\n      break;\n    }\n  }\n}	0
22059538	22059501	How to display number in money format	Console.WriteLine(intValue.ToString("N1", CultureInfo.CreateSpecificCulture("hi-IN")));	0
11274953	11274943	Is there a reason for verbose boolean evaluation?	return location < Platypi.Length && Platypi[location] != null;	0
27040495	27040325	C# regex to convert camelCase to Sentence case	string input = "itIsTimeToStopNow";\nstring output = Regex.Replace(input, @"\p{Lu}", m => " " + m.Value.ToLowerInvariant());\noutput = char.ToUpperInvariant(output[0]) + output.Substring(1);	0
10248454	10248202	How to properly dispose multiple forms	static void ShowScreenSaver() {\n    foreach (Screen screen in Screen.AllScreens) {\n        ScreenSaverForm form = new ScreenSaverForm(screen.Bounds);\n\n        form.FormClosed += (sender, e) => {\n            form.Dispose();\n        };\n\n        form.Show();\n    }\n}	0
31769904	31769871	how to group by one column only using linq?	var queryGroupLog = from log2 in lg2.AsEnumerable()\n                    group log2 by log2.Field<string>("Phone") into groupPhone\n                    select new \n                    {\n                        Phone = groupPhone.Key,\n                        Status = groupPhone.OrderBy(p => p.Field<string>("Status"))\n                                           .LastOrDefault()\n                    };	0
24930249	24915426	Dropbox Chunked Upload returning a 404	request.ContentType = "application/x-www-form-urlencoded";	0
2713968	2713215	Implementing Dispose on a class derived from Stream	~ComStreamWrapper()\n{\n    Dispose(false);\n}\n\nprotected override void Dispose(bool disposing)\n{\n    base.Dispose(disposing);\n    if (!_Disposed)\n    {\n        iop.Marshal.FreeCoTaskMem(_Int64Ptr);\n        iop.Marshal.ReleaseComObject(_IStream);\n        _Disposed = true;\n    }\n}	0
4655843	4655669	Unable to connect to any of the specified MySQL hosts	"Server = myServerAddress;\n       Port = 1234;\n   Database = myDataBase;\n        Uid = myUsername;\n        Pwd = myPassword;"	0
1051270	1051255	Setting the LinqDataSource Where Clause using DateTime Column	LinqDataSource1.Where = "MyDateColumn == DateTime.Parse(" + DateTime.Now + ")"; \n//can't create a date from string in constructor use .Parse()...	0
1129406	1128766	Implementing a custom sort for WinForms ListView	Picture test1 = new Picture() { Name = "Picture #1", Size = 54 };\nPicture test2 = new Picture() { Name = "Picture #2", Size = 10 };\n\nthis.listView1.ListViewItemSorter = test1;\n\nthis.listView1.Items.Add(new ListViewItem(test1.Name) { Tag = test1 });\nthis.listView1.Items.Add(new ListViewItem(test2.Name) { Tag = test2 });\n\n public class Picture : IComparer\n    {\n        public string Name { get; set; }\n        public int Size { get; set; }\n\n        #region IComparer Members\n\n        public int Compare(object x, object y)\n        {\n            Picture itemA = ((ListViewItem)x).Tag as Picture;\n            Picture itemB = ((ListViewItem)y).Tag as Picture;\n\n            if (itemA.Size < itemB.Size)\n                return -1;\n\n            if (itemA.Size > itemB.Size)\n                return 1;\n\n            if (itemA.Size == itemB.Size)\n                return 0;\n\n            return 0;\n\n        }	0
5482329	5482188	How to Stop Inserting?	...\nDECLARE @rtn int\nBEGIN TRY\n  Insert into TR_employeesprovidercode \n    (employeeid, providercode) \n  values \n    (@employeeid, @providercode)\n  SET @rtn = 0\nBEGIN TRY\nBEGIN CATCH\n  IF ERROR_NUMBER() <> 2627\n     RAISERROR ('real error', 16, 1)\n  SET @rtn = 1\nEND CATCH\nRETURN @rtn	0
12943324	12942871	export to excel give me checkbox instead of string	from x in someTable\nselect new Model\n    {\n     .\n     .\n     .\n     IsActive = (isActive ? "True" : "False");\n     .\n     .\n    }	0
2766725	2766686	How do I use a Lambda expression to sort INTEGERS inside a object?	collEquipment.Sort((x, y) => y.ID - x.ID);	0
2712363	2712337	Passing a WHERE clause for a Linq-to-Sql query as a parameter	var times = DataContext.EventDateTimes;\nif (cond)\n    times = times.Where(time => time.StartDate <= ...);\n\nfrom row in ... join time in times ...	0
8294033	8293446	How to deal with parent.frames issue?	window.opener.parent.frames['map'].location.href = "map.aspx";	0
31604508	31604100	Finding numbers and doubles in text line in Regular Expressions	string input = "asdajkj asdk asdkj 10.1 asdasd";\n\nstring res = new string(input.SkipWhile(c => !Char.IsDigit(c)).TakeWhile(c => Char.IsDigit(c) || c == '.').ToArray());\n\nConsole.WriteLine(res); // 10.1	0
247822	247718	Output Parameter not Returned from Stored Proc	SqlParameter theOrganizationNameParam = new SqlParameter( "@OrganisationName", SqlDbType.NVarChar, 256 );\ntheOrganizationNameParam.Direction = ParameterDirection.Output;\ncm.Parameters.Add( theOrganizationNameParam );\ncm.ExecuteNonQuery();\nname = theOrganizationNameParam.Value;	0
4269449	4269081	LINQ on a list of a class	var selectedTransactions =\n        from t in data\n        join transactionId in bits on t.TransactionID equals transactionId\n        select t;	0
34046105	34045888	how to inherit the values of a foreign key in MVC 5? Invalid column name 'student_student_name'	public int student_id { get; set; }	0
5103351	5103133	How to use hyperlink inside ListView in Winforms C#	private void listView1_MouseClick(object sender, MouseEventArgs e)\n{\n  try {\n    string mailtoLink = "mailto:"+listView1.SelectedItems[0].SubItems[email_Column].Text;\n    System.Diagnostics.Process.Start(mailtoLink);\n  } catch(Win32Exception ex) {\n    MessageBox.Show("An error has occured: "+ ex.Message);\n  }\n}	0
27019857	27019672	Select from array only the best items	var latest = apps.GroupBy(i => i.Name)\n                 .Select(i => i.OrderByDescending(j => j.Version).First());	0
32202392	32201085	Waiting for action to be invoke before returning	var t = new TaskCompletionSource<int>();\n        _operatorManager.MakeCall(poste, "0" + number, (callId) =>\n        {\n            t.SetResult(callId);\n        });\n        t.Task.Wait();\n        _response.Clear();\n        _response.Add("callId", t.Task.Result);\n        return Ok(_response);	0
216649	216634	WPF with Windows Forms - STAThread	[STAThreadAttribute]\nstatic void Main(string[] args)	0
23805882	23805792	List Distinct entries based on property and sum of duplicates	var newList = list.GroupBy(x=> new {x.State , x.Label })\n                  .Select(x=> new YourClass(x.Key.State, x.Key.Label, x.Sum(x=>x.Value) ))\n                  .ToList();	0
6928253	6928223	Getting method parameters as an object[] in C#	[WebMethod]\npublic void CreateAccount(string arg1, int arg2, DateTime arg3)\n{ \n    CreateAccountImpl(arg1, arg2, arg3);\n}\n\nprotected void CreateAccountImpl(params object[] args)\n{\n    string log = args.Aggregate("", (current, next) => string.Format("{0}{1};", current, next));\n    Logger.Log("Creating new Account: " + args);\n\n    // create account logic\n}	0
31885112	31884812	How can you get the non-intersected portion of two lists of strings?	public static void test()\n    {\n        string test1 = "word1,word2,word3,word4";\n        string test2 = "word2,word4";\n\n        List<string> test1list = test1.Split(',').ToList();\n        List<string> test2Lists = test2.Split(',').ToList();\n        List<string> result = new List<string>();\n\n        foreach (var item in test1list)\n        {\n            if (!test2Lists.Contains(item))\n            {\n                if (result.Any())\n                {\n                    result.Add(","  +item );\n                }\n                else\n                {\n                    result.Add(item);\n                }\n\n            }\n        }\n\n        result.ForEach(p => Console.Write(p));\n        Console.ReadLine();\n    }	0
25510744	25509807	Sql Query for taking backup in MSAccess 2007?	void Main()\n{\n    CopyToZip(@"D:\temp\temp.accdb", @"D:\temp\temp.zip");\n}\nprivate static void CopyToZip(string source, string dest)\n{\n     using (ZipFile zip = new ZipFile(dest))\n     {\n         ZipEntry e = zip.UpdateFile(source, string.Empty);\n         e.Comment = "Database archived in date: " + DateTime.Today.ToShortDateString();\n         zip.Save();\n     }\n}	0
25458487	25458460	How to provide value to DataFormat parameter	var v = Doc(DataFormat.Xml);	0
4109775	4101825	How to reference a selected menu item in codebehind?	Sitecore.Context.Item.Name	0
30823541	30823027	Parsing Json into a dynamic c# object with a dynamic key	var myObj = JsonConvert.DeserializeObject<dynamic>(jsonString);\nConsole.WriteLine(myObj.calendars["joe@bobs.com"]);	0
1196546	1189375	ListView moving items	/// <summary>\n/// Move the given item to the given index in the given group\n/// </summary>\n/// <remarks>The item and group must belong to the same ListView</remarks>\npublic void MoveToGroup(ListViewItem lvi, ListViewGroup group, int indexInGroup) {\n    group.ListView.BeginUpdate();\n    ListViewItem[] items = new ListViewItem[group.Items.Count + 1];\n    group.Items.CopyTo(items, 0);\n    Array.Copy(items, indexInGroup, items, indexInGroup + 1, group.Items.Count - indexInGroup);\n    items[indexInGroup] = lvi;\n    for (int i = 0; i < items.Length; i++)\n        items[i].Group = null;\n    for (int i = 0; i < items.Length; i++) \n        group.Items.Add(items[i]);\n    group.ListView.EndUpdate();\n}	0
17111336	17089702	Force InkAnalyzer to recognizes shapes only	inkAnalyzer.AddStroke(stroke);\ninkAnalyzer.SetStrokeType(stroke, StrokeType.Drawing);	0
31457077	31385358	CopyFromScreen with virtual screen	Application.Current.MainWindow	0
29749420	29737645	How to insert data from textbox and date/time into Access database?	command.CommandText = "INSERT INTO Tracker(INum,IName,IVio,IDate,ISanc,ITodayDate,IGnG) values(@txtNumber,@txtName,@txtVio,@calDate,@txtSan,@calTodayDate,@txtGnG)";\n        command.Parameters.Add(new OleDbParameter("@txtNumber", txtNumber);\n        command.Parameters.Add(new OleDbParameter("@txtName", txtName);\n        command.Parameters.Add(new OleDbParameter("@txtVio", txtVio);\n        command.Parameters.Add(new OleDbParameter("@calDate", calDate);\n        command.Parameters.Add(new OleDbParameter("@txtSan", txtSan);\n        command.Parameters.Add(new OleDbParameter("@calTodayDate", calTodayDate);\n        command.Parameters.Add(new OleDbParameter("@txtGnG", txtGnG);\n        command.ExecuteNonQuery();	0
6099475	6099450	Question related to textbox used to keyin password	Textbox.UseSystemPasswordChar	0
20748292	20748134	Getting Attribute's value from xml in c#	var xml = XElement.Load(@"C:\\StoreServer1.xml");\nvar query = xml.Descendants("Groups").Descendants("Store").Where(e => int.Parse(e.Value) == 18).Select(e=> e.Attribute("WeekDayStClose").Value);	0
6256137	6256021	C# lambda expression question - how to join 2 tables using Lambda statements from the following SQL?	var results = context.boards.Where(b => b.bid == 1)\n                            .DefaultIfEmpty()\n                            .Join(context.categories, \n                                  b => b.bid,\n                                  c => c.cid,\n                                  (b, c) => c);	0
25700332	25699368	Forcefully show tooltip on "Enable=false" control	private void Form1_MouseMove(object sender, MouseEventArgs e) {\n        if (checkBox1.Bounds.Contains(e.Location)) {\n            toolTip1.Show("yadayada", this);\n        }\n    }	0
11890760	11201964	Access invisible columns in a Datagridview (WinForms)	private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n    var value = dataGridView.Rows[e.RowIndex].Cells[0].Value;\n}	0
13742992	13741461	Sorting elements in a HashTable, Dictionary or such	SortedList<TKey, TValue>	0
11462116	11462032	C# Date set as textbox, which send data to textfile as other format	string today = DateTime.Now.ToString("MMddyy");\n        LetterDate.Text = today;\n        var date = Convert.ToDateTime(LetterDate.Text).ToString("MMMM dd, yyyy");	0
3290940	3290859	How to create a new Thread to execute an Action<T>	private void ExecuteInBiggerStackThread(Action<Helper> action, Helper h)\n{\n    var operation = new ParameterizedThreadStart(obj => action((Helper)obj));\n    Thread bigStackThread = new Thread(operation, 1024 * 1024);\n\n    bigStackThread.Start(h);\n    bigStackThread.Join();\n}	0
19322974	19322922	Getting character at a particular index in a string c#	string myString = "HelloWorld";\nchar myChar = myString[index];	0
11161535	11161434	Using proxy with WebBrowser and WebRequest, how to include username and password?	var webProxy = new WebProxy(host,port);\nwebProxy.Credentials = new NetworkCredential("username", "password", "domain");\nvar webRequest = (HttpWebRequest)WebRequest.Create("http://example.com");\nwebRequest.Proxy = webProxy;	0
21733810	21733634	how to form one to many recordset query	using (var reader_user = cmd.ExecuteReader())\n{\n    while (reader_user.Read())\n    {\n        MapUser(reader_user);\n    }\n\n    reader_user.NextResult();\n\n    while (reader_user.Read())\n    {\n        Whatever(reader_user);\n    }\n}	0
5644363	5644304	Storing custom objects in Sessions	Class ShoppingCart {\n\n    public static ShoppingCart Current\n    {\n      get \n      {\n         var cart = HttpContext.Current.Session["Cart"] as ShoppingCart;\n         if (null == cart)\n         {\n            cart = new ShoppingCart();\n            HttpContext.Current.Session["Cart"] = cart;\n         }\n         return cart;\n      }\n    }\n\n... // rest of the code\n\n}	0
4103232	4101174	Regular Expression RegEx to validate Custom Excel formats	On Error GoTo complain\njunk = Format(dummyData,formatString)\n...	0
16570325	16569951	How to convert this hex string into a long?	int part1 = Convert.ToInt32("E9", 16)\nint part2 = Convert.ToInt32("4C827CEB", 16) //the last 4 bytes\nlong result = part1 * 4294967296 + part2  //4294967296 being 2^32. Result = 1002011000043	0
19019526	19004568	How to make SqlCeCommand case senstive?	SqlCeCommand myCmd = new SqlCeCommand("select * from ProgramTable where CAST(ObjName AS varbinary(10)) = CAST(@OBJName AS varbinary(10)) and ID = @ID");\n myCmd.Connection = DBConnection;\n myCmd.Parameters.Add("@OBJName", SqlDbType.NVarChar, 10).Value = ObjName;\n myCmd.Parameters.Add("@ID", SqlDbType.Int, 4).Value = IDValue;	0
34480059	34480020	Can't write char in console	int d = 5;\nchar e = (char)(d + 48);\nConsole.WriteLine("my Char: " + e);\nConsole.WriteLine("my Char: " + (char)(5 + '0')); // or	0
11303450	11303374	C# Multiplication Table	for (int i = 0; i <= 3; i++)\n{\n    Console.Write(i + "\t");\n    for (int j = 1; j <= 3; j++)\n    {\n        if (i>0) Console.Write(i * j + "\t");\n        else Console.Write(j + "\t");\n    }\n    Console.Write("\n");\n}	0
13353097	13353045	Linq select result with duplicating rows	var products = from p in _ctx.ExecuteFunction<GetProducts_Result>("GetProducts")\n               group p by new {p.Code, p.Name} into g\n               select new Product\n               {\n                   Code = g.Key.Code,\n                   Name = g.Key.Name,\n                   terms = g.Select(x => new Terms { \n                                            Term = x.Term, \n                                            Rate = x.Rate }).ToList()\n               };	0
23958857	22598513	RhinoETL merge table with webservice results	protected override Row MergeRows(Row wsRow, Row dbRow) {\n\n    Row row;\n\n    // if the db row doesn't exist, then the ws row is new, and it should be inserted\n    if (dbRow["id"] == null) {\n        row = wsRow.Clone();\n        row["action"] = "Insert";\n        row["deleted"] = false;\n        return row;\n    }\n\n    // if the ws row doesn't exist, it should be marked as deleted in the database (if not already)\n    if (wsRow["id"] == null) {\n        row = dbRow.Clone();\n        row["deleted"] = true;\n        row["action"] = dbRow["deleted"].Equals(true) ? "None" : "Update";\n        return row;\n    }\n\n    // ws and db descriptions match, but check and make sure it's not marked as deleted in database\n    row = wsRow.Clone();\n    row["deleted"] = false;\n    row["action"] = dbRow["deleted"].Equals(true) ? "Update" : "None";\n    return row;\n\n}\n\nprotected override void SetupJoinConditions() {\n    FullOuterJoin.Left("description").Right("description");\n}	0
30435280	30435224	Input string was not in a correct format in c# net int.parse	Double.Parse	0
10986951	10986845	C# Looping over DataTable, compare with previous or next row	for( int i = 0; i < ds.Tables["Invoices"].Rows.Count; i++ )\n{\n    if( i > 0 )\n    {\n       // Compare with previous row using index\n       if( ds.Tables["Invoices"].Rows[i]["Amount"] > ds.Tables["Invoices"].Rows[i - 1]["Amount"])\n       {}\n    }\n    if( i < ds.Tables["Invoices"].Rows.Count - 1 )\n    {\n        if( ds.Tables["Invoices"].Rows[i]["Amount"] > ds.Tables["Invoices"].Rows[i + 1]["Amount"])\n        {}\n    }\n}	0
8021840	8021791	How can I use GetAllUsers in the ASP Membership provider?	public static MembershipUserCollection GetAllUsers()	0
8738698	8738109	How to remove the merged datatable from the datatable using C#.Net?	D1.Columns.Add("ORIGINAL_DATATABLE_NAME", typeof(int));\nD2.Columns.Add("ORIGINAL_DATATABLE_NAME", typeof(int));\n\nforeach(DataRow row in D1.Rows)\n    row["ORIGINAL_DATATABLE_NAME"] = 1;\n\nforeach(DataRow row in D2.Rows)\n    row["ORIGINAL_DATATABLE_NAME"] = 2;\n\nD1.Merge(D2);\n\nDataRow[] rows = D1.Select("ORIGINAL_DATATABLE_NAME=1", "");\n\nDataSet ds = new DataSet();\nds.Merge(rows, false, MissingSchemaAction.Add);\nds.Tables[0].Columns.Remove("ORIGINAL_DATATABLE_NAME");	0
22372294	22372148	How to splite Trial c#	using System;\n\n   namespace ConsoleApplication1\n   {\n    class Program\n    {\n\n\n        static void Main(string[] args)\n        {\n            string emailsubject = "Email Test 2 CRM:0276002";\n\n            emailsubject = GetCrmSubjectNum(emailsubject);\n\n            Console.WriteLine(emailsubject);\n\n            Console.Read();\n        }\n\n\n\n        public static string GetCrmSubjectNum(string emailsubject)\n        {\n           emailsubject = emailsubject.Remove(0, emailsubject.IndexOf("CRM"));\n\n            return emailsubject;\n        }\n    }\n}	0
10799811	10799685	How to pass strings from C# to C++ (and from C++ to C#) using DLLImport?	[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);\npublic static string GetText(IntPtr hWnd)\n {\n     // Allocate correct string length first\n     int length       = GetWindowTextLength(hWnd);\n     StringBuilder sb = new StringBuilder(length + 1);\n     GetWindowText(hWnd, sb, sb.Capacity);\n     return sb.ToString();\n }\n\n\n[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]\n public static extern bool SetWindowText(IntPtr hwnd, String lpString);\nSetWindowText(Process.GetCurrentProcess().MainWindowHandle, "Amazing!");	0
21380129	21379654	Delete same rows in two tables	delete from table1\nwhere exists (\n    select * from table2 where table2.StudentName = Table1.StudentName\n)	0
4184050	4183963	How to get unique key for any method invocation?	public string GetSomeString(int someInt)\n{\n    MD5CryptoServiceProvider cryptoServiceProvider = new MD5CryptoServiceProvider();\n    byte[] data = Encoding.ASCII.GetBytes(String.Format("{0}{1}", "methodName", someInt));\n    data = cryptoServiceProvider.ComputeHash(data);\n    return Convert.ToString(data);\n}	0
24863579	24863501	File not found exception in Windows Phone app	var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;\n// not:\nvar folder = ApplicationData.Current.LocalFolder;	0
20092332	20092036	string separated by '\0' in C#	string name = "name"\nstring driverdll = "My.dll"\nstring setupdll = "MySteup.dll";\n\nstring output = String.Format("{0}\\0Driver={1}\\0Setup={2}\\0", name, driverdll, setupdll).	0
15925669	15925036	Get Base URL of My Web Application	string baseURL = HttpContext.Current.Request.Url.Host	0
23043427	23043393	Timer in seperate thread with long running task	_timer_Elapsed(null, null); // Get the timer to execute immediately	0
12461538	12461232	How to get byte array from telerik CaptchaImage?	using (MemoryStream ms = new MemoryStream())\n{\n    captchaImage.RenderImage().Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n    byte[] byteArray = ms.ToArray();\n    context.Response.BinaryWrite(byteArray);\n}	0
10652559	10652134	how to get selection range from excel 2010?	Microsoft.Office.Interop.Excel.Application ExApp = Globals.ThisAddIn.Application as Microsoft.Office.Interop.Excel.Application;\nMicrosoft.Office.Interop.Excel.Range SelectedRange = ExApp.Selection as Microsoft.Office.Interop.Excel.Range;	0
18622096	18616849	WPF User Control full sreen on maximize?	private const int GWL_STYLE = -16;\n    private const int WS_SYSMENU = 0x80000;\n    [DllImport("user32.dll", SetLastError = true)]\n    private static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n    [DllImport("user32.dll")]\n    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n    Then put this code in the Window's Loaded event:\n\nvar hwnd = new WindowInteropHelper(this).Handle;\nSetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);	0
7385856	7385782	Concatenate literals and staticresource string purely in xaml	{Binding Source={StaticResource AppInfoer}, Path=Title, StringFormat=Show {0}}	0
25539600	25539441	Sorting a List<KeyValuePair<int, string>> Uppercase and Lowercase	SortedDictionary<string, string> parameters = new SortedDictionary<string, string>(StringComparer.Ordinal);\n        parameters.Add("AC", "123");\n        parameters.Add("Ab", "123");\n        parameters.Add("Db", "123");\n        parameters.Add("CD", "123");	0
6531976	6531869	Distinct Linq filtering with additional criteria	var items = new[] {\n           new { Id=2, Priority=3 },\n           new { Id=2, Priority=5 },\n           new { Id=1, Priority=4 },\n           new { Id=4, Priority=4 },\n           new { Id=4, Priority=4 }\n        };\n\n        var deduped = items\n            .GroupBy(item => item.Id)\n            .Select(group => group.OrderByDescending(item => item.Priority).First())\n            .OrderBy(item => item.Id);	0
19589788	19589744	How to set out an sql string without getting newline in constant error	string strSQL = @"SELECT [Year],[Week No],StartDate,EndDate,Dept,[Clock No],\n         RTRIM(Name)+' '+ RTRIM(initial) as Name,[Own Hours],[Other Hours],\n           [Total Hours],[OT Premium] \n           FROM [Wages].[CHHours] \n           Where [Year]=@WageYear and [Week No]=@Week \n           Order by  [Year] DESC, [Week No] DESC,Dept,[Clock No]" ;	0
1167721	1167558	Problem Serializing a Class Containing a Collection using XML Serialization	[XmlArrayItem("Address", IsNullable=false)]\npublic string[] SendTo\n{\n    get\n    {\n        return this.sendToField;\n    }\n    set\n    {\n        this.sendToField = value;\n    }\n}	0
33922572	33895440	How to share pixel data between Bitmap and Bitmapsource without a reallocation?	WpfImage.Source = new SharedBitmapSource(DrawingBitmap);	0
30547397	30547183	How to query from the table using group by with EF6?	using(var db=new YourContext())\n{\n    var res= db.UserRoles.GroupBy(ur=>ur.userId)\n                         .Select(g=>new UserRoleDto()\n                                    { \n                                      userId = g.Key,\n                                      roleIds = g.Select(us=>us.roleId).ToList()\n                                    } \n                                ).ToList();\n}	0
1649369	1649363	How to get a property name?	return MethodBase.GetCurrentMethod().Name.Substring(4);	0
17880564	17879675	How to get SOAP return value using c#	XDocument xDocc = XDocument.Parse(responseSOAP);\nXmlReader xr = xDocc.CreateReader();\nxr.ReadToFollowing("userid");\nstring uid = xr.ReadElementString();	0
19430265	19164308	How to create an expression at runtime for use in GroupBy() with Entity Framework?	public static List<object> ListGroupKeys<TEntity>(this IQueryable<TEntity> source, string fieldName)\n        where TEntity : class, IDataEntity\n    {\n        var results = source.GroupBy(fieldName, "it").Select("new (KEY as Group)");\n\n        var list = new List<object>();\n        foreach (var result in results)\n        {\n            var type = result.GetType();\n            var prop = type.GetProperty("Group");\n\n            list.Add(prop.GetValue(result));\n        }\n\n        return list;\n    }	0
14668689	14668678	How do i add to a List<int> also the numbers in between?	for (int j = LR[i].start; j <= LR[i].end; j++)\n{\n    _fts.Add(j);\n}	0
31180247	31108549	Data truncated for column total on update	string[] words = footernetamount.Split(' ');\n            footernetamount = words[2];\n            string[] words3 = footernetamount.Split(',');\n            footernetamount = words3[0] + "." + words3[1];	0
6053058	6053000	can i use pocos with mongodb c# driver	MongoCollection<Thing> thingCollection = _db.GetCollection<Thing>("things");\nThing thing = col.FindAllAs<Thing>();\ncol.Insert(new Thing { Name = "Foo" });	0
12373241	12372711	Dynamically add projections to NHibernate query	baseQuery.SelectList(s => \n    s.SelectSum(c => c.GrossChargeAmount)\n    .GroupBy(() => accountAlias.AccountHolder))	0
17340510	17340284	How to perform multiple joins in LINQ	var values= from tp in tbltprop\n            join tb in tblcol ON tp.id equals tb.id into gj\n            from gjd in gj.DefaultIfEmpty()\n            join tpt in tblPropday ON tp.id equals tpt.id into gk\n            from gkd in gk.DefaultIfEmpty()\n            join tptr in tblProperResult ON tp.id equals tptr.id into gl\n            from gld in gl.DefaultIfEmpty()\n            where tp.id == @charpID1 && gkd.Id == @CharpID2\n            select new \n                   { \n                       TpName = tp.Name, \n                       Entity = gjd.Entity, \n                       TPTName = gjd.Name, \n                       ID = gkd.ID, \n                       Code = gld.Code\n                   };	0
8883917	8883859	How to start a Task class instance of MS TPL with some delay?	Task logManager = null;\nnew Timer((state) =>\n    {\n        logManager = Task.Factory.StartNew(() => { /* Some code*/}, TaskCreationOptions.LongRunning);\n    }, null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(-1));	0
25370737	25369405	Optional function parameter with default value by reference	private int dataArchiver(string toPlace, string aExtension)\n{\n    string tempVar = "";\n    return dataArchiver(toPlace, aExtension, ref tempVar);\n}\n\nprivate int dataArchiver(string toPlace)\n{\n    string tempVar = "";\n    return dataArchiver(toPlace, ".7z", ref tempVar);\n}\n\nprivate int dataArchiver(string toPlace, string aExtension, ref string createdName)\n{\n    return 0;\n}	0
1912935	1867998	NHibernate Get objects without proxy	iAmaSession.GetSessionImplementation().PersistenceContext.Unproxy(iAmaProxy)	0
4217630	4217594	saving to xml document	using (var storage = IsolatedStorageFile.GetUserStoreForApplication())\n{\n    using (Stream stream = storage.CreateFile("data.xml"))\n    {\n        doc.Save(stream);\n    }\n}	0
21854845	21854563	fill grid view from textbox and dropddown list values recursively on each button click	protected void btnAdd_Click(object sender, EventArgs e)\n{\n    DataTable dt = new DataTable();\n    DataRow dr;\n    dt.Columns.Add("Resource");\n    dt.Columns.Add("available");\n\n    foreach(GridViewRow row in grd.Rows)\n    {\n        dr = dt.NewRow();\n        dr["Resource"] = row.Cells[0].Text;\n        dr["available"] =row.Cells[1].Text;\n        dt.Rows.Add(dr);\n    }\n    dr = dt.NewRow(); \n    dr["Resource"] = ddlResource.SelectedItem.Text;\n    dr["available"] = txtavailable.Text;\n    dt.Rows.Add(dr);\n    grd.DataSource = dt;\n    grd.DataBind();\n}	0
33517739	33517669	How to check whether json object has some property	if(obj["proprty_name"] != null){\n    // do something\n}	0
9092187	9092160	Check if a folder exist in a directory and create them using C#	string path = @"C:\MP_Upload";\nif(!Directory.Exists(path))\n{\n    Directory.CreateDirectory(path);\n}	0
29959905	29958190	Windows Phone 8.1 - How to create a flyout (?) and dim the rest of the screen?	Placement = "Full"	0
1243966	1243933	Showing possible property values in custom webcontrol	public enum DateTimeFormat\n{\n    Year,\n    ...\n}	0
22881960	22863338	initializecomponent() don't exist in current context while using generics in c# web application	namespace check\n    {    \n       public partial class MainPage : UserControl\n       {\n            public MainPage()\n            {\n                InitializeComponent();\n                // Use the generic type Test with an int type parameter.\n                Test<int> Test1 = new Test<int>(5);\n                // Call the Write method.\n                Test1.Write();\n\n                // Use the generic type Test with a string type parameter.\n                Test<string> Test2 = new Test<string>("cat");\n                Test2.Write();\n            }\n       }\n\n       class Test<T>\n       {\n           T _value;    \n           public Test(T t)\n           {\n              // The field has the same type as the parameter.\n              this._value = t;\n           }    \n           public void Write()\n           {\n              MessageBox.Show(this._value);\n           }\n       }\n   }	0
32623496	32623387	using C#, address split and only display suburbs name	string res = string.Concat( address.Split('\n').Last().Where( x => !char.IsDigit(x))).Trim();	0
5390115	5389657	Sending POST requests by using libcurl	using System;\nusing SeasideResearch.LibCurlNet;\n\nnamespace Sample\n{\n    internal class Program\n    {\n        private static void Main(string[] args)\n        {\n            Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);\n\n            Easy easy = new Easy();\n            Easy.WriteFunction wf = MyWriteFunction;\n            easy.SetOpt(CURLoption.CURLOPT_URL, "http://google.com/index.html");\n            easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);\n            easy.Perform();\n            easy.Cleanup();\n            Console.WriteLine("Press any key...");\n            Console.ReadKey();\n        }\n\n        private static int MyWriteFunction(byte[] buf, int size, int nmemb, Object extraData)\n        {\n            foreach (byte b in buf)\n                Console.Write((char)b);\n\n            return buf.Length;\n        }\n    }\n}	0
31208960	31185809	Number input replacing decimal comma with dot	public class ApolloModelBinder : DefaultModelBinder\n{\n    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)\n    {\n        var request = controllerContext.HttpContext.Request;\n\n        decimal i;\n        var value = request.Form[propertyDescriptor.Name];\n        if (propertyDescriptor.PropertyType == typeof(decimal) && decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out i))\n        {\n            propertyDescriptor.SetValue(bindingContext.Model, i);\n            return;\n        }\n\n        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);\n    }\n}	0
8331515	8331144	Ensuring that child controls are created in main UI thread	using System.Threading;\npublic class YourForm\n{\n    SynchronizationContext sync;\n    public YourForm()\n    {\n        sync = SynchronizationContext.Current;\n        // Any time you need to update controls, call it like this:\n        sync.Send(UpdateControls);\n    }\n\n    public void UpdateControls()\n    {\n        // Access your controls.\n    }\n}	0
17593884	17593682	Getting the address location of variable	object variable = new object();\nGCHandle handle = GCHandle.Alloc(variable, GCHandleType.Pinned);\nIntPtr address = handle.AddrOfPinnedObject();	0
25383779	25383665	C# object to byte[]	TypeConverter obj = TypeDescriptor.GetConverter(objectMessage.GetType());\nbyte[] bt = (byte[])obj.ConvertTo(objectMessage, typeof(byte[]));	0
4887906	4887820	How do you pass an object from form1 to form2 and back to form1?	public partial class YourSecondForm : Form\n{\n    object PreserveFromFirstForm;\n\n    public YourSecondForm()\n    {\n       ... its default Constructor...\n    }\n\n    public YourSecondForm( object ParmFromFirstForm ) : this()\n    {\n       this.PreserveFromFirstForm = ParmFromFirstForm;\n    } \n\n    private void YourSecondFormMethodToManipulate()\n    {\n       // you would obviously have to type-cast the object as needed\n       // but could manipulate whatever you needed for the duration of the second form.\n       this.PreserveFromFirstForm.Whatever = "something";\n    }\n\n\n}	0
11971255	11971224	C#: Running a transaction on SQL Server 2008 via ADO.NET	DBFactoryDatabaseCommand.Transaction = dbTransaction;	0
21638274	21600454	Showing an updated list in a form	private void btnCreate_Click(object sender, EventArgs e)\n{\n    string username = txtUsername.Text;\n    int i = employee.employees.Count();\n    while (employee.AsEnumerable().Select(r => r.username == username).Count() > 0)\n    {\n        username = txtUserName.Text + i++;  //Makes sure you have no common usernames\n    }\n    employee.employees.Add(new Employee(){...});\n    employee.SaveFile(); //New method  \n}	0
3459176	3458812	Constraints taking either types in generics	public void MyGeneric<T>(T item) where T : MyClass1 or T : IMyInterface\n{\n  item.CoolThing();\n}	0
15408144	15406957	Accessing the properties of Win32_OperatingSystem	using System;\nusing System.Management;\nnamespace WMISample\n{\n    public class MyWMIQuery\n    {\n        public static void Main()\n        {             \n            try\n            {\n                ManagementClass osClass = new ManagementClass("Win32_OperatingSystem");\n                foreach (ManagementObject queryObj in osClass.GetInstances())\n                {\n                    foreach (PropertyData prop in queryObj.Properties)\n                    {\n                        //add these to your arraylist or dictionary \n                      Console.WriteLine("{0}: {1}", prop.Name, prop.Value);\n                    }                    \n                }\n            }\n            catch (ManagementException e)\n            {\n                //MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);\n            }\n        }\n    }\n}	0
23783967	23783863	Mapping a list of object models onto another list using linq	var TheListOfObjectsB  = TheListObjectsA.Select(a => new ObjectB() { Prop1  = a.Prop1, Prop2 = a.Prop2 }).ToList();	0
18042942	18042719	Removing CDATA tag from XmlNode	xml.innerText = xml.innerText.Replace("![CDATA[","").Replace("]]","");\nxmlDoc.Save();// xmlDoc is your xml document	0
3826253	3826222	Call a method when specific key combination is pressed anywhere in the app, as long as application is currently focused window	public MainWindow()\n{\n    InitializeComponent();\n    this.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);\n}\n\nvoid MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)\n{\n    if ((e.Key == Key.F11) && (Keyboard.Modifiers == ModifierKeys.Control))\n    { \n\n    }\n}	0
6522011	6521977	How can I pull a value out of a QueryString-like string with C#	var string1 = "?facets=All Groups||Brand&TitleTag=FOOBAR#back";\nvar pairs = HttpUtility.ParseQueryString(string1);\n\nstring titleTagValue = pairs["TitleTag"];\n\nif (!string.IsNullOrEmpty(titleTagValue) && titleTagValue.IndexOf('#') > -1)\n{\n    titleTagValue = titleTagValue.Substring(0, titleTagValue.IndexOf('#'));\n}	0
17928007	17927421	How to pass part of url as variable in c#?	var requestGuid = Request.Params["GUID"];\n\nif (string.IsNullOrEmpty(requestGuid))\n{\n    throw new InvalidOperationException("The request GUID is missing from the URL");\n}\n\nGuid guid;\n\nif (!Guid.TryParse(requestGuid, out guid))\n{\n    throw new InvalidOperationException("The request GUID in the URL is not correctly formatted");\n}\n\nusing(var connection = new SqlConnection("connection_string"))\n{\n    using(var command = new SqlCommand("spSurveyAnswer_Insert", connection))\n    {\n        command.CommandType = CommandType.StoredProcedure;        \n        command.Parameters.AddWithValue("firstParamName", selectValue1);\n        command.Parameters.AddWithValue("feedbackParamName", txtFeedBack.Text);\n        command.Parameters.AddWithValue("guidParamName", guid);\n\n        command.Connection.Open();\n        command.ExecuteNonQuery();\n    }\n}	0
31275952	31275229	Prevent specific character input UITextField	textField.ShouldChangeCharacters = (textField, range, replacementString) =>\n{\n    if (replacementString == " ")\n    {\n         return false;\n    }\n}	0
2916596	2916539	Concatenate Two Fields to Display in Dropdown List	List<Product> products = new List<Product>();\nproducts.Add(new Product() { ProductId = 1, Description = "Foo" });\nproducts.Add(new Product() { ProductId = 2, Description = "Bar" });\n\nvar productQuery = products.Select(p => new { ProductId = p.ProductId, DisplayText = p.ProductId.ToString() + " " + p.Description });\n\nskuDropDown.DataSource = productQuery;\nskuDropDown.DataValueField = "ProductId";\nskuDropDown.DataTextField = "DisplayText";\nskuDropDown.DataBind();	0
6857518	6857408	Handling buffer data obtained from rs232 port	var data=comPort.ReadExisting().ToString();\nvar result=data.Split(',').Last();	0
19486266	19486226	How to read a txt file and load the contents into an arraylist?	void LoadArrayList()\n{\n    TextReader tr;\n    tr = File.OpenText("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt");\n\n    string Actor;\n    Actor = tr.ReadLine();\n    while (Actor != null)\n    {\n        ActorArrayList.Add(Actor);\n        Actor = tr.ReadLine();\n    }\n\n}	0
20385431	20385215	Sorting an ObservableCollection partially while preserving the order for some as given	foreach (var item in items.Where(X => !X.Name.StartsWith("Item")).Union(items.Where(X => X.Name.StartsWith("Item")).OrderBy(X => Convert.ToInt32(X.Name.Replace("Item ", "")))))\n        {\n            Console.WriteLine(item.Name);\n        }	0
18556629	18556538	position of new windows after opening	int x = Screen.PrimaryScreen.WorkingArea.Top;\n int y = Screen.PrimaryScreen.WorkingArea.Left;\n this.Location = new Point(x, y);	0
16991580	16991471	LINQ group by with multiple counts	var query2 = query\n              .Where(m => m.Source == "UserRef")\n              .GroupBy(m => m.TrackId)\n              .Select(g => new FullReferrer {\n                 Customer = g.Key,\n                 FullRefFalseCount = g.Count(x => !x.FullRef),\n                 FullRefTrueCount = g.Count(x => x.FullRef)\n              });	0
2509177	2509109	Iterate through a DataTable to find elements in a List object?	if (lstAccounts.Exists(delegate(string sAccountNumber) { return sAccountNumber == drCurrentRow["AccountNumber"]; })	0
28585871	28584094	How to display multiple images in a single picturebox in c# windows form?	public partial class Form1 : Form\n{\n\n    private ImageList imagelst;\n\n    public Form1()\n    {\n        InitializeComponent();\n        imagelst = new ImageList();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        //pictures from your Harddrive\n        Image i = new Bitmap("rock.jpg");\n        imagelst.Images.Add("rock", i);\n\n        i = new Bitmap("scissors.jpg");\n        imagelst.Images.Add("scissors", i);\n\n        i = new Bitmap("paper.jpg");\n        imagelst.Images.Add("paper", i);\n    }\n\n    private void btnRock_Click(object sender, EventArgs e)\n    {\n        pictureBox1.Image = imagelst.Images["rock"];\n    }\n\n    private void btnScissors_Click(object sender, EventArgs e)\n    {\n        pictureBox1.Image = imagelst.Images["scissors"];\n    }\n\n    private void btnPaper_Click(object sender, EventArgs e)\n    {\n        pictureBox1.Image = imagelst.Images["paper"];\n    }\n}	0
6968438	6968269	How to use LIKE operator with wildcards in parameterized query in MS-Access using c#	string commandtext =@"SELECT student.roll_no, student.s_name, fee.fee_date, (fee.adm_fee+fee.mon_fee+fee.lib_fee+fee.exm_fee) AS fee, class.c_name FROM class INNER JOIN (fee INNER JOIN student ON fee.s_id = student.s_id) ON (fee.c_id = class.c_id) AND (class.c_id = student.c_id) WHERE student.s_name Like \"*"+name+"*\"";	0
10277362	10277220	how to draw a square in to a PictureBox?	using System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.pictureBox1.Image = this.Draw(this.pictureBox1.Width, this.pictureBox1.Height);\n    }\n\n    public Bitmap Draw(int width, int height)\n    {\n        var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);\n        var graphics = Graphics.FromImage(bitmap);\n        graphics.SmoothingMode = SmoothingMode.AntiAlias;\n        graphics.FillRectangle(new SolidBrush(Color.Tomato), 10, 10, 100, 100);\n\n        return bitmap;\n    }\n  }\n}	0
3823955	3822147	How to make a Binding in code?	var dsc = new DataSetCreator();\n  this.DataContext = dsc.PartnerStat();\n  // bind a textblock\n  Binding b = new Binding("FirstName");\n  textBlock1.SetBinding(TextBlock.TextProperty, b);\n  // bind the datagrid\n  // don't specify a path, it will bind to the entire collection\n\n  var b1 = new Binding(); \n  dataGrid1.SetBinding(DataGrid.ItemsSourceProperty, b1);	0
15151583	15151141	how to check data member is serialized or not in WCF?	[DataContract]\npublic class MyType\n{\n    // This property is serialized to the client.\n    [DataMember]\n    public int MyField1 { get; set; }\n\n    // This property is NOT serialized to the client.\n    public string MyField2 { get; set; }\n}	0
32792571	32791999	Go to certain website when item from combo box is selected	public Form1()\n    {\n        InitializeComponent();\n\n        tools.Items.Add("Movies");\n        tools.Items.Add("Music");\n        tools.Items.Add("Documents");\n        tools.Items.Add("Apps");\n\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        switch(tools.SelectedValue)\n        {\n            "Movies":\n                      Response.Redirect("google.com");\n                       break;\n            "Music":\n                      Response.Redirect("google.com");\n                       break;\n            "Documents":\n                      Response.Redirect("google.com");\n                       break;\n            "Apps":\n                      Response.Redirect("google.com");\n                       break;\n\n\n         }\n    }	0
25270224	25270155	Sum the rows in Gridview	decimal price = 0;\nforeach (DataGridViewRow row in DataGridView.Rows)\n{\n     price += row.Cells["Total"]!=null ? Convert.ToDecimal(row.Cells["Total"].Value) : 0;\n}\n\nlblTotalPrice.Text = "Total Cost: $"+ price.ToString("n2");	0
12321336	12320936	Regex to Find and Replace Text NOT in a Tag	Regex.Replace(s, @"((?<!^)\b[A-Z])(?=[^<>]+<[^\/>][^>]+>)", m => m.Value.ToLower());	0
21358539	21358242	C# Accessing a methods value dynamically using a string	string currentMarketSelected= this.marketTextBox.Text; // Specific market: COLXPM\n\nvar property = allmarketdata.@return.markets.GetType().GetProperty(currentMarketSelected);\ndynamic market = property.GetGetMethod().Invoke(allmarketdata.@return.markets, null);\nstring marketlabel=market.label.ToString();	0
26528654	26430108	get current windows user in webapp	System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();\n string[] a = Context.User.Identity.Name.Split('\\');\n string appNetworkUserId = Context.User.Identity.Name.ToString();	0
7819288	7819236	Making a Copy of Reference itself?	ListViewItem[] copiedItems = ListView.Items().OfType<ListViewItem>().ToArray();	0
15777186	15777141	How does getting and setting affect assigning of variables?	string userMessage; // class scope\n\n\n...\n\nif (condition) {\n     String userMessage = "blah"; // only available until the closing brace\n} // out of scope here	0
25997996	25992331	Troubles with a C# function and SqlCommand that execute a stored procedure	public static void sqlExecuteSp(string cmdText, DataTable parDt)\n{\n    using (SqlConnection conn = new SqlConnection())\n    {\n        using (SqlCommand comm = new SqlCommand())                    \n        {\n            conn.ConnectionString = ConfigurationManager.ConnectionStrings["FTBLConnectionStringSuperUser"].ConnectionString;\n            conn.Open();\n\n            using (SqlTransaction trans = conn.BeginTransaction())\n            {\n                comm.Connection = conn;\n                comm.CommandType = CommandType.StoredProcedure;\n                comm.Transaction = trans;\n\n                SqlParameter param = comm.Parameters.AddWithValue("@dt", parDt);\n                param.SqlDbType = SqlDbType.Structured;\n\n                comm.ExecuteNonQuery();\n\n                trans.Commit();\n            }\n        }\n\n        conn.Close();\n    }\n\n}	0
425871	425814	Converting a normalized phone number to a user-friendly version	String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))	0
1694650	1693454	How do I connect glade signals using GtkBuilder in C#?	builder.Autoconnect (this);	0
9441477	9440841	How to find filepath relative from one absolute to another?	string firstDirectory = "c:\\my\\dir";\n        string secondDirectory = "c:\\my\\other\\file.ext";\n\n\n        var first = firstDirectory.Split('\\');\n        var second = secondDirectory.Split('\\');\n\n        var directoriesToGoBack = first.Except(second);\n        var directoriesToGoForward = second.Except(first);\n\n        StringBuilder directory = new StringBuilder();\n\n        bool initial = true;\n        foreach (string s in directoriesToGoBack)\n        {\n            if (initial)\n            {\n                initial = false;\n            } else\n            {\n                directory.Append('\\');\n            }\n            directory.Append("..");\n\n        }\n\n        foreach (string s in directoriesToGoForward)\n        {\n            directory.Append('\\');\n            directory.Append(s);\n        }\n        Console.WriteLine(directory.ToString());	0
6528979	6428372	How to mock application path when unit testing Web App	public interface IPathProvider\n{\n    string GetAbsolutePath(string path);\n}\n\npublic class PathProvider : IPathProvider\n{\n    private readonly HttpServerUtilityBase _server;\n\n    public PathProvider(HttpServerUtilityBase server)\n    {\n        _server = server;\n    }\n\n    public string GetAbsolutePath(string path)\n    {\n        return _server.MapPath(path);\n    }\n}	0
23631688	23630369	DataContractSerializer cannot deserialize after namespace changed	xmlstr=xmlstr.Replace("<Type1>", "<Type1 xmlns:Namespace=\"http://example.com\">");	0
33798609	33797617	Xamarin Portable Library PCL Preprocessor Platform	using Xamarin.Forms;\n...\nif(Device.OS == TargetPlatform.Android)\n    Debug.WriteLine("I'm on Android");\nelse if(Device.OS == TargetPlatform.iOS)\n    Debug.WriteLine("This is iOS");	0
23086310	23086201	Going back one iteration in foreach loop in C#	// Pay attention to reversed order:\n// each currentNode.Remove() changes currentNode.Nodes.Count \nfor (int i = currentNode.Nodes.Count - 1; i >= 0; --i)  {\n  TreeNode childNode = currentNode.Nodes[i];\n\n  if (!someCondition) {\n    currentNode.Remove();                    \n  }\n}	0
6619852	6619807	Get File by path	string path = // path string here\n\n        File.ReadAllText(path);\n\n        File.OpenRead(path);\n\n        File.OpenWrite(path);	0
10795717	10700645	Saving Images from Image Control isn't working	File.WriteAllBytes()	0
31812043	31811912	Given a string with day of week, return integer	var inx = Array.FindIndex(CultureInfo.CurrentCulture.DateTimeFormat.DayNames, x=>x=="Sunday");	0
1646091	1646049	How to load an assembly without using Assembly.Load?	byte[] readAllBytes = File.ReadAllBytes("path");\nAssembly assembly = Assembly.Load(readAllBytes);	0
5967507	5967450	How do i define starting position of listbox?	private int ListIndex(int index){\n  return index - 1;\n}	0
11107558	11107505	Checking If a String Contains a Word and Then Checking If It Starts With said Word and If It Doesnt?	if (testString.IndexOf("Foo") == 0 && testString.LastIndexOf("Foo") == 0)\n        // "Foo foo foo"\n        return true;\n    else if (testString.IndexOf("Foo") == 0 && testString.LastIndexOf("Foo") > 0)\n        // "Foo foo Foo"\n        return false;\n    else if (testString.Contains("foo")  && testString.IndexOf("Foo") > 0)\n        // "foo Foo foo" or "foo foo Foo"\n        return false; \n    else if (testString.Contains("foo") && !testString.Contains("Foo"))\n        // "foo foo foo"\n        return true;	0
24411233	24411032	How to retrieve class object from ICollection?	var userDetailsObejct = (from u in user.UserDetails \n                         where u.id == Id\n                         select u).FirstOrDefault();	0
1716038	1716004	get key value pairs from xml using linq	string text = "<foo>...</foo>";\nvar pairs = XDocument.Parse(text)\n                     .Descendants("add")\n                     .Select(x => new { Key = x.Attribute("key").Value,\n                                        Value = x.Attribute("Value)".Value })\n                     .ToList();	0
24604746	24604693	Display same image from database on the next page	SqlCommand cmd = new SqlCommand("SELECT image FROM photo WHERE id=@id",con);\nSqlParameter param = new SqlParameter();\nparam.ParameterName = "@id";\nparam.Value = "Value_Of_parameter"; //Example 1\ncmd.Parameters.Add(param);\nSqlDataAdapter sda = new SqlDataAdapter(cmd);	0
2716282	2711004	How do I deploy a Mono Winforms Application to Suse Linux 11.0 Server Enterprise?	zypper addrepo http://ftp.novell.com/pub/mono/download-stable/SLE_11 mono-stable\nzypper refresh --repo mono-stable\nzypper dist-upgrade --repo mono-stable	0
18125805	18125738	Is there a better way to create acronym from upper letters in C#?	string.Join("", s.Where(char.IsUpper));	0
14981891	14973141	Access Azure Service config from C# program called by a startup script	while (!RoleEnvironment.IsAvailable) {\n     Thread.Sleep(1000);\n }\n RunExecutable();	0
13365143	13363554	How to fix image on Report.rdlc by giving path?	EnableExternalImages=true	0
16932007	16931778	Who is currently logged into a pc?	const string ns = @"root\cimv2";\n\n   var host = "your host";\n\n   var scope = new ManagementScope(string.Format(@"\\{0}\{1}", host, ns));\n\n   scope.Connect();\n\n//List of logged in users\n\n   using (var searcher = new ManagementObjectSearcher(scope, \n           new ObjectQuery("select * from Win32_LoggedOnUser")))\n   {\n\n          foreach (var logonUser in searcher.Get())\n          {\n               //see MSDN for available properties of Win32_LoggedOnUser, \n               //take into consideration "Dependent", "Antecedent" properties\n          }\n\n   }\n\n//list of processes\n\n  using (var searcher = new ManagementObjectSearcher(scope, \n                  new ObjectQuery( "select * from Win32_SessionProcess")))\n  {\n       foreach (var sessProc in searcher.Get())\n       {\n            //see "Antecedent" property\n       }\n  }	0
15891867	15891542	Writing to an XML file using standard microsoft libraries	XmlDocument myXmlDocument = new XmlDocument();\n\n            myXmlDocument.Load(@"..\..\XMLFile1.xml");\n\n            XmlNode root = myXmlDocument.DocumentElement;\n\n            //We only want to change one connection. \n            //This could be removed if you just want the first connection, regardless of name.\n            var targetKey = "sqlConnection1";\n\n            //get the add element we want\n            XmlNode myNode = root.SelectSingleNode(string.Format("add[@Name = '{0}']", targetKey));\n\n            var sql_Connection = "some sql connection";\n\n            //set the value of the connectionString attribute to the value we want\n            myNode.Attributes["connectionString"].Value = sql_Connection;\n\n            myXmlDocument.Save(@"..\..\XMLFile2.xml");	0
2245460	2245442	C# Split A String By Another String	string data = "THExxQUICKxxBROWNxxFOX";\n\nreturn data.Split(new string[] { "xx" }, StringSplitOptions.None);	0
15152487	15130180	Change text of ?Cancel? button on a UISearchBar using Monotouch?	UIButton btnCancel = (UIButton)SearchBar.Subviews[3];\nbtnCancel.SetTitle ("test", UIControlState.Normal);	0
1110098	1110070	How to get the values of an enum into a SelectList	Value = ((int)i).ToString();	0
3340561	3335819	byte[] to BitmapImage in silverlight	BitmapImage GetImage( byte[] rawImageBytes )\n{\n    BitmapImage imageSource = null;\n\n    try\n    {\n        using ( MemoryStream stream = new MemoryStream( rawImageBytes  ) )\n        {\n            stream.Seek( 0, SeekOrigin.Begin );\n            BitmapImage b = new BitmapImage();\n            b.SetSource( stream );\n            imageSource = b;\n        }\n    }\n    catch ( System.Exception ex )\n    {\n    }\n\n    return imageSource;\n}	0
3813610	3813340	Get value from ASP.NET MVC Lambda Expression	var result = ((LambdaExpression)expression).Compile().DynamicInvoke(model);	0
8443538	8443502	How do I change another program's window's size?	[DllImport("user32.dll", SetLastError = true)]\ninternal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);\n\nMoveWindow(ApplicationHandle, 600, 600, 600, 600, true);	0
3845104	3845093	Using UrlDecode from a WinForms app	System.Web	0
30515924	30515744	indexing a text file into two arrays	var lines = File.ReadLines(@"d:\temp\test.txt");\nList<string> apollo = lines.Take(6485).ToList();\nList<string> sabre = lines.Skip(6485).Take(6485).ToList();	0
17294857	17294004	Find Microsoft Windows Installer 3.1 or later	return System.Diagnostics.FileVersionInfo.GetVersionInfo(@"C:\Windows\System32\msi.dll").ProductVersion;	0
24813019	24812617	How to select DataGridViewRow by code	DataGridView.Rows.OfType<DataGridViewRow>().\nWhere(x => (string)x.Cells[0].Value == txt1.text).\nToArray<DataGridViewRow>()[0].Selected = true;	0
8990229	8977895	Building a dynamic expression tree to filter on a collection property	Expression left = Expression.Property(tpe, typeof(Trades).GetProperty("Name"));\nExpression right = Expression.Constant(value);\nExpression InnerLambda = Expression.Equal(left, right);\nExpression<Func<Trades, bool>> innerFunction = Expression.Lambda<Func<Trades, bool>>(InnerLambda, tpe);\n\nmethod = typeof(Enumerable).GetMethods().Where(m => m.Name == "Any" && m.GetParameters().Length == 2).Single().MakeGenericMethod(typeof(Trades));\nOuterLambda = Expression.Call(method, Expression.Property(pe, typeof(Office).GetProperty(fo.PropertyName)),innerFunction);	0
14199724	14199682	C# read the text of dynamically created text box from other methode	TextBox tb;\nprivate void Form1_Load(object sender, EventArgs e)\n{\n  tb=new TextBox();\n  ...\n  this.Controls.Add(tb);\n}	0
4479194	4468782	How to check an entity has been refered by other before delete it	ON DELETE RESTRICT	0
11294656	11294083	Split number into equal sized groups	groups (since you already have this calculated correctly)(should be a double)\n//   maxPerGroup = y\nmembersPerGroup = floor(amount/groups)\n\n\n\nList a = new List\n//Is the leftover value of the modulus\nleftover = amount%groups;\n//Loops for each group\nfor(int i=0;i<groups;i++){\n\n\n//If there is a left over value\nif(leftover>0){\n  a.Add(membersPerGroup +1);\n  leftover--;\n}else{\n  a.Add(membersPerGroup );\n}\n\n}	0
1373758	1373596	Fixed Panel Height in a SplitContainer	teamSplitContainer.SplitterDistance = teamSplitContainer.Height - 100;\nteamSplitContainer.FixedPanel = FixedPanel.Panel2;	0
8471804	8471520	Creating snapshot of application data - best practice	CompanyID    Name            ValidFrom     ValidTo\n12           Business Lld    2000-01-01    2008-09-23\n12           Business Inc    2008-09-23    NULL	0
13034388	13033409	To make grid in List View appeared in IDE	listView1.View = View.Details;	0
21070542	21066152	Get resulting size of RotateTransform	private static Bitmap RotateImage(Image b, float angle)\n    {\n        var corners = new[]\n            {new PointF(0, 0), new Point(b.Width, 0), new PointF(0, b.Height), new PointF(b.Width, b.Height)};\n\n        var xc = corners.Select(p => Rotate(p, angle).X);\n        var yc = corners.Select(p => Rotate(p, angle).Y);\n\n        //create a new empty bitmap to hold rotated image\n        Bitmap returnBitmap = new Bitmap((int)Math.Abs(xc.Max() - xc.Min()), (int)Math.Abs(yc.Max() - yc.Min()));\n        ...\n    }\n\n    /// <summary>\n    /// Rotates a point around the origin (0,0)\n    /// </summary>\n    private static PointF Rotate(PointF p, float angle)\n    {\n        // convert from angle to radians\n        var theta = Math.PI*angle/180;\n        return new PointF(\n            (float) (Math.Cos(theta)*(p.X) - Math.Sin(theta)*(p.Y)),\n            (float) (Math.Sin(theta)*(p.X) + Math.Cos(theta)*(p.Y)));\n    }	0
337126	337049	Generate WebService producer from WSDL in Visual Studio 2005	wsdl.exe	0
11454934	11454644	Executing batch file with ProcessStartInfo	private void simpleRun_Click(object sender, System.EventArgs e)\n{\n  System.Diagnostics.Process.Start(@"C:\listfiles.bat");\n}	0
15745851	15745811	regex to verify comma separated string	var songDetailsArray = songDetails.Split(",");\n\nif(songDetailsArray.Length != 5)\n{\n     throw new Exception("Enter data into all cells");\n}	0
4354801	4354744	Getting the userID of a logged in User in ASP.NET	using System.Web.Security;\n\nMembership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey;	0
10587762	10587643	How to release Bitmap, ReDraw Bitmap, and add it to PictureBox. Without leaking resources or causing much flicker	using (Bitmap GridBitMap = new Bitmap(x,y))\n{\n   using (Graphics ScoreGraphic = Graphics.FromImage(GridBitMap)\n   {\n     ...\n   }\n}	0
2342476	2342456	How to check if the mail has been sent sucessfully	SmtpMail.Send(message)	0
19727662	19727230	Refactoring the namespace of a class with a DataContract	[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/A.B.C")]	0
22490761	22490374	get detailsView values in Edit mode	TextBox tx = BP_Info_View.Rows[7].Cells[1].Controls[0] as TextBox;	0
26457406	26457291	unit test failing for converting string list to lowercase in c#	[TestMethod]\npublic void TestAddBook ()\n{\n    Book id = new Book (new string[] {"ABC", "DEF"});\n    id.AddBook ("GHI");\n\n    Assert.AreEqual (true, id.Exist ("ghi"));\n}	0
10714547	10714387	asp.net column chart coloring of each column in c#	Color[] colors = new Color[] { Color.Red, Color.Green, Color.Wheat, Color.Gray. Color.Black,  Color.Blue};\nforeach (Series series in chrtTickets.Series)\n{\n    foreach (DataPoint point in series.Points)\n    {\n        Random random = new Random();\n        int randomNumber = random.Next(0, 5);\n        point.LabelBackColor = colors[ randomNumber];\n    }\n}	0
502906	379162	WCF REST Starter Kit - A property with the name 'UriTemplateMatchResults' already exists	protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)\n        {\n            return new WebServiceHost2(serviceType, true, baseAddresses) {EnableAutomaticHelpPage = false};\n        }	0
17843134	17842937	How can you use threading to send multiple web requests at a time in c#?	protected void SearchButtonClick(object sender, EventArgs e)\n{\n    new Thread(() => MakeRequest(SearchForm.Text)).Start();\n}\n\nprotected void MakeRequest(string text)\n{\n    int resultCount = search.MakeRequests(text);\n\n    // tell UI thread to update label\n    Dispatcher.BeginInvoke(new Action(() =>\n            {\n                resultsLabel.Text += text + ": " + resultCount + "     occurances";\n            }));\n}	0
11011591	11011554	How to put standard value at top of dropdown	DropDownList1.Items.Insert(0,new ListItem("Please Select One","0"));	0
186833	186822	Capturing console output from a .NET application (C#)	Process compiler = new Process();\ncompiler.StartInfo.FileName = "csc.exe";\ncompiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";\ncompiler.StartInfo.UseShellExecute = false;\ncompiler.StartInfo.RedirectStandardOutput = true;\ncompiler.Start();    \n\nConsole.WriteLine(compiler.StandardOutput.ReadToEnd());\n\ncompiler.WaitForExit();	0
9965015	9965000	Resist User to go back after Login	// In the login page\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (User.Identity.IsAuthenticated)\n           Response.Redirect("~/Default.aspx");\n}	0
218600	218060	Random Gaussian Variables	Random rand = new Random(); //reuse this if you are generating many\ndouble u1 = rand.NextDouble(); //these are uniform(0,1) random doubles\ndouble u2 = rand.NextDouble();\ndouble randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *\n             Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)\ndouble randNormal =\n             mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)	0
8946506	8946310	How to know the repeating decimal in a fraction?	1. 13 goes into   7 0 times with remainder  7; bring down a 0.\n2. 13 goes into  70 5 times with remainder  5; bring down a 0.\n3. 13 goes into  50 3 times with remainder 11; bring down a 0.\n4. 13 goes into 110 8 times with remainder  6; bring down a 0.\n5. 13 goes into  60 4 times with remainder  8; bring down a 0.\n6. 13 goes into  80 6 times with remainder  2; bring down a 0.\n7. 13 goes into  20 1 time  with remainder  7; bring down a 0.\n8. We have already seen 13/70 on line 2; so lines 2-7 have the repeating part	0
15452710	15452647	How to check if string contains the text in C# Winforms	var a = "Data is provided to test only string";\nvar b = "test only string";\n\nif (a.Contains(b))\n     MessageBox.Show("yes");	0
20881751	20881645	how to display the statistics about all the files in a folder in C#	// Get the files in the directory and print out some information about them.\nSystem.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");\n\n\nforeach (System.IO.FileInfo fi in fileNames)\n{\n       Console.WriteLine("{0}: {1}: {2}", fi.Name, fi.LastAccessTime, fi.Length);\n}	0
20257002	20256914	In C#, how could i calculate weekday differences between two dates?	int allDays = (int)date.Subtract(startDate).TotalDays;\nint weekDays = Enumerable\n                .Range(1, allDays)\n                .Select(day => startDate.AddDays(day))\n                .Count(day => day.DayOfWeek != DayOfWeek.Saturday && day.DayOfWeek != DayOfWeek.Sunday);	0
5760167	5759827	Windows Azure Tables, querying using Contains	MyTable.Where(t => t.PartitionKey.CompareTo("image") >= 0).ToList();	0
3335629	3335603	C# Automatic Properties -- setting defaults	this.MyProperty = <DefaultValue>;	0
14395761	14395635	How match a css style text in C #	Regex myRegex = new Regex(@"<a id=""d(.+?)"" style=""(.+)"" ><\/a>");\n                                                           ^         no space in the string\n                                                             ^       the text between the tags is not matched\n                                                                ^    there is a space in the string	0
11664929	11664903	Find text with regular expression	img src='[^']+'	0
17688721	17688645	How to trim and extract JSON string via C# RegEx?	var jToken=JToken.Parse(data);\nJArray arr;\nswitch(jToken.Type)\n{\n    case JTokenType.Array:\n        arr=(JArray)jToken;\n        break;\n    case JTokenType.Object:\n        arr=(JArray)((JObject)jToken)["Data"];\n        break;\n    default:\n        throw new Exception();\n}\nvar output=arr.ToString();	0
1647445	1647265	How do I get all controls inside a specific RowDefinition/ColumnDefinition in a Grid?	public static class GridExtensions\n{\n    public static IEnumerable<DependencyObject> GetChildren(this Grid grid, int row, int column)\n    {\n        int count = VisualTreeHelper.GetChildrenCount(grid);\n        for (int i = 0; i < count; i++)\n        {\n            DependencyObject child = VisualTreeHelper.GetChild(grid, i);\n            int r = Grid.GetRow(child);\n            int c = Grid.GetColumn(child);\n            if (r == row && c == column)\n            {\n                yield return child;\n            }\n        }\n    }\n}	0
11902129	11901945	'Update-Database' in EF 4.3 code-first - Value cannot be null	public Type ConcreteType	0
13399002	12407475	How to properly use SPServiceApplicationCollection?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.ComponentModel;\nusing System.ServiceProcess;\nusing Microsoft.SharePoint;\nusing Microsoft.SharePoint.Administration;\nusing Microsoft.SharePoint.Administration.Health;\n\nnamespace ConsoleApplication1\n{\nclass Program\n{\nstatic void Main(string[] args)\n{\n    var solution = SPFarm.Local.Solutions["Your Service Application Name.wsp"];\n    string serverName = string.Empty;\n    foreach (SPServer server in solution.DeployedServers)\n    {\n        serverName += server.Name;\n        Console.WriteLine(server.Name);\n    }\n\n    if (solution != null)\n    {\n        if (solution.Deployed)\n        {\n            Console.WriteLine("{0} is currently deployed on: {1}", solution.Name, serverName);\n            Console.ReadLine();\n        }\n        else\n        {\n            Console.WriteLine("Error!  Solution not deployed!");\n            Console.ReadLine();\n        }\n    }\n  }\n }\n}	0
5520688	5520600	build a better data access layer	using(MyEntitiesContext context = new MyEntitiesContext())\n{\n    var idleUsers = from u in context.User\n                    where u.LoggedIn && u.LastActivity > DateTime.Now.AddMinutes(-30)\n                    select u;\n\n    foreach(User u in idleUsers)\n    {\n        u.Status = UserStatus.Idle;\n    }\n\n    context.SaveChanges();\n}	0
31457686	31457553	Get the bindingsource from a control	var source = textBox1.DataBindings["Text"].DataSource;	0
29213283	29213033	How to get string-value of selected cell in datagrid (VS 2008)	DataGridCell dc = test_dataGrid.CurrentCell;\nString cellValue =  test_dataGrid[dc.RowNumber, dc.ColumnNumber].ToString();	0
1976408	1973168	Update DataKeyNames field value in gridview	DataBind()	0
2378422	2374187	How to upload to YouTube using the API via a Proxy Server	YouTubeRequest request = new YouTubeRequest(settings);\nGDataRequestFactory f = (GDataRequestFactory)request.Service.RequestFactory;\nWebProxy myProxy = new WebProxy("http://proxy-server:port/", true);\nmyProxy.Credentials = CredentialCache.DefaultNetworkCredentials;\nf.Proxy = myProxy;	0
8155201	8153270	Does using a Castle singleton cause contention in ASP.NET web application	System.Collections.Generic.Dictionary<K,V>	0
18390479	18389873	force instantiation of xaml resource	public partial class App : Application\n{\n    public NotificationIcon NotifyIcon {get;set;}\n\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n\n        NotifyIcon = new NotificationIcon();\n        NotifyIcon.ApplicationExit += notificationIcon_ApplicationExit;\n    }\n\n    void notificationIcon_ApplicationExit(object sender, EventArgs eventArgs)\n    {\n        Application.Current.Shutdown();\n    }\n}	0
4244890	4244776	xml attributes from SQL in C#	StringReader rdr = new StringReader(str);\n\n        DataSet ds = new DataSet();\n\n        ds.ReadXml(str);\n        DataTable dt = ds.Tables[0];\n        datagridview.datasource = dt;	0
4927314	4926925	How to access services logs from my C# test?	// Create an EventLog instance and assign its log name.\nEventLog myLog = new EventLog("MyLogName");\n\n// Read the event log entries.\nforeach (EventLogEntry entry in myLog.Entries)\n{\n    Console.WriteLine("\tEntry: " + entry.Message);\n}	0
19002137	19001972	How to print GDI+ objects with correct dimensions?	gr.PageUnit = GraphicsUnit.Millimeter;	0
767621	767215	How to do a UDP multicast across the local network in c#?	JoinMulticastGroup()	0
26156861	26156825	Grouping list elements with GroupBy	private List<List<Recipient>> PageList(List<Recipient> recipients)\n{\n    return recipients.Select((x, i) => new { Index = i, Value = x })\n                     .GroupBy(x => x.Index / 2000) \n                     .Select(x => x.Select(v => v.Value).ToList())\n                     .ToList();\n}	0
4036119	3997346	Update Google Maps Javascript objects every 1 min using fresh data from database using C#?	function initialize() {\n...\nsetInterval("updateMarkers()",60000); //refresh every minute\n}	0
4271831	4271731	Changing DataType of column in DataTable from DateTime to String	dt.Columns.Add("DateStr");\n\nforeach (DataRow dr in dt.Rows)\n{\n    dr["DateStr"] = string.Format("{0:MM/dd/yyyy}", dr["OriginalDate"]);\n}	0
28607068	28606236	export datetime to excel	xlWorkSheet.Cells[1, 1].NumberFormat = "@";	0
24535536	24533497	How to post a gridview rows data when a checkbox checked state becomes true?	Protected Sub cb_CheckedChanged(sender As Object, e As EventArgs)\n    Dim row As GridViewRow = DirectCast(DirectCast(sender, CheckBox).NamingContainer, GridViewRow)\n    Dim rowIndex As Integer = row.RowIndex\n    Dim cb As CheckBox = DirectCast(gv.Rows(rowIndex).FindControl("cb"), CheckBox)\n  End Sub	0
25684959	25678719	XML Deserialization with dynamic fields	public class MyXmlRoot{\n\nprivate string[] allowedTags={"tagA","tagB","tagC"};\n\n[XmlAnyElement]\npublic List<XmlElement> children = new List<XmlElement>(); //populated after serialization\n\npublic string GetValueByKey(string key){\n  return children.Find(k => k.Name == key).InnerText;\n}\n\npublic void UseTags(){\n    for(int i=0;i<allowedTags.Length;i++){\n        Console.WriteLine(allowedTags[i]+" = "+GetValueByKey(allowedTags[i]));\n    }\n}\n\n}	0
16459680	16456507	C#: Casting '0' to int	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        Foo.Bar(0);\n        Console.ReadLine();\n    }\n}\n\nclass Foo {\n    public static void Bar(byte arg)  { Console.WriteLine("byte overload"); }\n    public static void Bar(short arg) { Console.WriteLine("short overload"); }\n    public static void Bar(long arg)  { Console.WriteLine("long overload"); }\n}	0
18483507	18483151	ASP.net Publish to server using default membership	1. "Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion"..\n2. Your stored oprocedure of the above name doesnot exist in the host.\n3. Make a script of the same from local and run it in host.\n4. This will solve your problem.	0
1701638	1700839	nhibernate - display order - pattern/solution?	IF EXISTS (SELECT name FROM sysobjects\n      WHERE name = 'colmodels_insupd' AND type = 'TR')\n   DROP TRIGGER employee_insupd\nGO\nCREATE TRIGGER colmodels_insupd\nON ColModels\nFOR INSERT, UPDATE\nAS\n\nupdate cm\nset displayorder = a.rownumber\nfrom\ncolmodels cm\ninner join\n(\nselect colmodels.id, row_number() OVER(partition by colmodels.reportid ORDER BY colmodels.displayorder, colmodels.id desc) as rownumber\nfrom colmodels inner join inserted \non colmodels.reportid = inserted.reportid and  colmodels.deleted = 0 and colmodels.hidden = 0 \n) a\non cm.id = a.id	0
17995892	17995706	c# - how to get the index of an item in the list in a single step?	var index = myList.FindIndex(a => a.Prop == oProp);	0
4008452	4008415	Performing a type of union of two IEnumerable collections	var groups1 = col1.ToLookup(e => e);\nvar groups2 = col2.ToLookup(e => e);\n\nvar col3 = col1.Union(col2)\n               .SelectMany(e => Enumerable.Repeat(e, \n                   Math.Max(\n                            groups1[e].Count(), \n                            groups2[e].Count()\n                   )\n                ));	0
6636404	6633858	How do I get an EPiServer page of a specific page type builder type with all its strongly typed properties correctly populated?	ContentPageType pageAsContentPageType = (ContentPageType) DataFactory.Instance.GetPage(page.PageLink);	0
11726658	11723283	How to write a "Between" Query Expression for today's date and two date attributes on an entity in a single condition?	new ConditionExpression("new_startdate", ConditionOperator.LessEqual, DateTime.UtcNow);\nnew ConditionExpression("new_enddate", ConditionOperator.GreaterEqual, DateTime.UtcNow);	0
33974849	33974800	move asp.net web site from pc to server	[Deployment automation][1]	0
34380302	34380216	Open an other form by clicking on a button	creationClasse c = new creationClasse();\nc.Show();	0
13234825	13234103	update an ObservableCollection with a BlockingCollection	class ElementHolder\n{\n    public ObservableCollection<Element> ElementsList { get; set; }\n    private ExternalService _externalService = new ExternalService();\n    private IDisposable _elementSubscription;\n    private Subject<Element> _elementSubject = new Subject<Element>();\n\n    public ElementHolder()\n    {\n        _externalService.ReceivedNewElement += _elementSubject.OnNext;\n        _externalService.Subscribe();\n\n        ElementList = new ObservableCollection<Element>();\n        _elementSubscription = _externalService.ObserveOnDispatcher().Subscribe(NextElement);\n    }\n\n    private void NextElement(Element e)\n    {\n        Element item = ElementsList.FirstOrDefault(o => o.ID == element.ID);\n        if (item == null) {\n            _elementList.Add(element);\n        }\n        else {\n            item.Update(element);\n        }\n    }\n}	0
19924329	19904889	C# property casting of model without loop?	public ActionResult Create(ParentsViewModel parent)\n    {\n        Type ptype = parent.GetType(); \n        PropertyInfo[] ppropinfo = ptype.GetProperties();\n        if (parent.RelationshipTypeID == 1)\n        {\n            Mother m = new Mother();\n            Type mtype = m.GetType();\n            PropertyInfo[] mpropinfo = mtype.GetProperties();\n            foreach (PropertyInfo minfo in mpropinfo)\n            {\n                foreach (PropertyInfo pinfo in ppropinfo)\n                {\n                    if (minfo.Name == pinfo.Name)\n                    {\n                        minfo.SetValue(m,pinfo.GetValue(parent));\n                    }\n                }\n            }\n var mres = m;\n db.MotherRepository.Add((mres));\n db.SaveChanges();\nreturn View(mres);\n        }\n\n}	0
22292998	22292609	How can I take the contents of a C# class and put into / take out of a string?	public string Serialize(ICollection<TestQuestionAnswerModel> answers)\n    {\n        JavaScriptSerializer serializer = new JavaScriptSerializer();\n        return serializer.Serialize(answers);\n    }\n\n    public ICollection<TestQuestionAnswerModel> Deserialize(string data)\n    {\n        JavaScriptSerializer serializer = new JavaScriptSerializer();\n        return (ICollection<TestQuestionAnswerModel>)serializer.Deserialize<ICollection<TestQuestionAnswerModel>>(data);\n    }	0
6247593	6246822	Find prime numbers in c#	public static void FirstPrime(int limit)\n    {\n        Stopwatch sw = new Stopwatch();\n        sw.Start();\n        bool[] composite = new bool[limit];\n        long sum = 0;\n        int count = 0;\n\n        for (int i = 3; i < limit; i++)\n        {\n            if (i % 2 == 1)\n            {\n                if (!composite[i])\n                {\n                    ++count;\n                    sum += i;\n                    for (int j = i; j < limit; j += 2 * i)\n                        composite[j] = true;\n                }\n            }\n        }\n        count++;\n        sum += 2;\n        Console.WriteLine("There are " + count + " prime numbers less than " + limit + " totalling " + sum);\n        sw.Stop();\n        Console.WriteLine("Time elapsed: {0}",sw.Elapsed);\n        Console.ReadKey();\n    }	0
2415566	2415402	Set Attribute @ run time	XmlAttributeOverrides attOv = new XmlAttributeOverrides();\n  XmlAttributes attrs = new XmlAttributes();\n  attrs.XmlElements.Add(new XmlElementAttribute("MyAttributeName"));\n  attOv.Add(typeof(MyTestClass), "MyAttribute", attrs);\n  XmlSerializer serializer = new XmlSerializer(typeof(MyTestClass), attOv);\n  //...	0
2564103	2564092	.NET Regular Expression for N number of Consecutive Characters	([a-zA-Z0-9])\1\1	0
32217888	32217750	How to get, compare and set a registry key value in hex	// Convert value as a hex in a string variable\nstring currentKey = Convert.ToInt32(winTrust.GetValue("State").ToString()).ToString("x");\nif (!currentKey.Equals("23c00"))\n {\n  winTrust.SetValue("State", 0x00023c00, RegistryValueKind.DWord);\n  winTrust.Close();\n }	0
8094712	8079809	Get navigation items in DevExpress eXpressApp Framework (XAF) application	((IModelApplicationNavigationItems) Application.Model).NavigationItems.AllItems	0
11833020	11832420	Why I do I fall into all of the hurdles for a simple update in EF?	public void Foo(int id, string name) {\n   var user = Db.Users.Local.SingleOrDefault(u => u.Id == id);\n   if (user == null) {\n      user = new User { Id = id };\n      Db.Users.Attach(user);\n   } \n\n   user.Name = name;\n   Db.SaveChanges();\n}	0
4937239	4937084	Help Marshaling a C function in C#	[DllImport ("your.dll")]\nextern int GetImageKN (short[] ndat) ;\n\nvar buffer = new short[160 * 120] ;\nvar result = GetImageKN (buffer)  ;	0
33759604	33743757	How do I reference an EF Configuration in another project via reflection?	class ProxyDomain : MarshalByRefObject\n{\n    public Assembly GetAssembly(string assemblyPath)\n    {\n        try\n        {\n            return Assembly.LoadFrom(assemblyPath);\n        }\n        catch (Exception ex)\n        {\n            throw new InvalidOperationException(ex.Message);\n        }\n    }\n}	0
1752353	1135094	How to eager load grandchildren of an aggregate with NHibernate?	var result =  session.CreateCriteria(typeof (TestCase))\n                .CreateAlias("Steps", "s")\n                .CreateAlias("s.Actions", "a")\n                .SetResultTransformer(CriteriaUtil.DistinctRootEntity);\n                .List();	0
10599569	10599445	Xml Reader Read Tags	var items = xDoc.Descendants("Products")\n    .Select(p => new\n    {\n        ProductNo=p.Element("Product_No").Value,\n        Stok = p.Element("Stok").Value,\n        ProductDetails = p.Element("Product_Details").Value,\n        Options = String.Join(";",p.Descendants("Options").Select(o=>o.Value))\n    })\n    .ToArray();	0
7791762	7791692	C# loop through an array of given labels	Label[] lray = { labelOne, labelDifferent, labelWhatElse };\nforeach (Label label in lray)\n{\n    label.ForeColor = Color.Black;\n}	0
12959148	12958740	Sql runs but doesn't show any content in calendar control	cmd.Parameters["@UsrDepartment"].Value = myDept	0
13611944	13611876	XML parsing is returning null for attributes	Dictionary<int, string> custXML = \n            doc.Descendants("DT100")\n               .ToDictionary(d => (int)d.Element("import_seq"),\n                             d => (string)d.Element("field_name"));	0
19009923	19009405	Populating Combox with first entry	var customers = \n    from c in ctx.Customers\n    orderby c.CustomerRef ascending\n    select new { CustomerId = c.CustomerID, CustomerRef = c.CustomerRef }).ToList();\n\ncustomers.Insert(0, new { CustomerID = -1, CustomerRef = "[Please Select]"});\n\ncboCustomerRef.DataSource = customers;\ncboCustomerRef.ValueMember = "CustomerID";\ncboCustomerRef.DisplayMember = "CustomerRef";	0
7521574	7521416	Accessing SQL CE from WP7 Mango error	using System.Collections.ObjectModel;	0
11081662	11081530	How to get size of cursor in C#	int cursorWidth = Cursor.Size.Width;\nint cursorHeight = Cursor.Size.Height;	0
31742250	31741946	model view view controller C#	public String GetString(String prompt = "")\n{\n    Console.WriteLine(prompt);\n    //return Console.ReadLine();\n    return "error is here";\n}	0
8231293	8231268	DateTime Format in "20111122"	MessageBox.Show(time.ToString("yyyyMMdd"));	0
16545352	16545330	Replace string spaces with an underscore	excel = excel.Replace(' ','_');	0
14399226	14390131	How to mandate workflows to include local types assembly name?	var settings = new XamlXmlReaderSettings()\n{\n    LocalAssembly = typeof(YourArgumentType).Assembly\n};\nvar reader = new XamlXmlReader(path, settings);\nActivity workflow = ActivityXamlServices.Load(reader);	0
11055465	11020384	How do I Update/Reload DataGridView BindingSource?	private void LoadDataGridView() {\n    // Fill a DataAdapter using the SelectCommand.\n    DataAdapter da = null;\n\n    // The Sql code here\n\n    // In case something fails, bail out of the method.\n    if (da == null) return;\n\n    // Clear the DataSource or else you'll get double of everything.\n    if (exerciseListDataGridView.DataSource != null) {\n        exerciseListDataGridView.DataSource.Clear();\n        exerciseListDataGridView.DataSource = null;\n    }\n\n    // I'm doing this off the top of my head, you may need to fill a DataSet here.\n    exerciseListDataGridView.DataSource = da.DefaultView;\n\n}	0
19263284	19263055	How to round decimal value into extract decimal point with zeros	// this code always round number to 4 places and adds two zeros at the end.\n   double TotalQty = 0.116220;\n   var DesTot= Math.Round(TotalQty, 4).ToString("0.000000");\n   Console.Write(DesTot);	0
23110460	23108406	How to send data while navigating another page without uri query	private void longList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n   {\n       if (PhoneApplicationService.Current.State.ContainsKey("Data"))\n          if (PhoneApplicationService.Current.State["Data"] != null)\n               PhoneApplicationService.Current.State.Remove("Data");\n         LongListSelector selector = sender as LongListSelector;\n         Writing data = selector.SelectedItem as Writing;\n         PhoneApplicationService.Current.State["Data"] = data ;\n         NavigationService.Navigate(new Uri("/WritingPage.xaml", UriKind.Relative));     \n    }\n\n\n//On second page\n//I assume you want to Data on page load\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n      Writing data = new Writing ();\n     data =(Writing)PhoneApplicationService.Current.State["Data"]\n     PhoneApplicationService.Current.State.Remove("Data");    \n    }	0
18845407	18845229	String trim. to remove last characters from the end	string test = "Care_CAR_3RD_DAY_201309177438417";\ntest = test.TrimEnd(new char[]{'_','0','1','2','3','4','5','6','7','8','9'});\n\n//output Care_CAR_3RD_DAY\ntest = "Care_CAR_3RD_DAY201309177438417";\ntest = test.TrimEnd(new char[]{'_','0','1','2','3','4','5','6','7','8','9'});\n\n//output Care_CAR_3RD_DAY	0
123067	122778	Capture console output for debugging in VS?	void my_printf(const char *format, ...)\n{\n    char buf[2048];\n\n    // get the arg list and format it into a string\n    va_start(arglist, format);\n    vsprintf_s(buf, 2048, format, arglist);\n    va_end(arglist); \n\n    vprintf_s(buf);            // prints to the standard output stream\n    OutputDebugString(buf);    // prints to the output window\n}	0
24435924	24435721	WPF - adding item of different template in listview	...\npublic Int32 Generation\n{\n    get ...\n}\n\npublic class GenerationTypeSelector : DataTemplateSelector\n  {\n    public override DataTemplate SelectTemplate(object item, DependencyObject container)\n    {\n        var transaction = (TransactionItem)item;\n        if (transaction .Generation == 0)\n            return Gen0Template;\n        else\n            return Gen1Template;\n    }\n  }	0
18942430	18942017	Unable To set row visible false of a datagridview	CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[MyGrid.DataSource];  \ncurrencyManager1.SuspendBinding();\nMyGrid.Rows[5].Visible = false;\ncurrencyManager1.ResumeBinding();	0
6195595	6192512	Store enum as string in database	class MyType\n{\n   public MyEnum MyEnum {get; private set;}\n   private string DBEnum { set { MyEnum = Convert(value);} }\n\n   private MyEnum Convert(string val)\n   {\n     // TODO: Write me \n   } \n}\n\n// cnn.Query<MyType>("select 'hello' as DBEnum")  <-- will set MyEnum	0
4622019	2796188	Explicit C# interface implementation of interfaces that inherit from other interfaces	interface IBaseInterface<T> where T : IBaseInterface<T>\n{\n    event EventHandler SomeEvent;\n}\n\ninterface IInterface1 : IBaseInterface<IInterface1>\n{\n    ...\n}\n\ninterface IInterface2 : IBaseInterface<IInterface2>\n{\n    ...\n}\n\nclass Foo : IInterface1, IInterface2\n{\n    event EventHandler IBaseInterface<IInterface1>.SomeEvent\n    {\n        add { ... }\n        remove { ... }\n    }\n\n    event EventHandler IBaseInterface<IInterface2>.SomeEvent\n    {\n        add { ... }\n        remove { ... }\n    }\n}	0
339141	339035	Extract RSS/ATOM URLs from HTML LINK tags	1. Convert an HTML into an XHTML with Tidy\n2. With the XHTML, use XPath to search for the link\n    /html/head/link[@type='application/rss+xml']	0
31108801	31108637	How to combine paths through a loop	public partial class Form1 : Form\n{\n    const string DirName = "Mydir";\n    const string RootFolder = @"c:\test";\n\n    public Form1()\n    {\n\n        CreateDirectories(0, 5, 5, RootFolder);\n\n\n        InitializeComponent();\n    }\n\n    public void CreateDirectories(int currentDepth, int maxDepth, int iterations, string root)\n    {\n        if (currentDepth > maxDepth)\n        {\n            return;\n        }\n        for (var i = 0; i < iterations; i++)\n        {\n            var currentDirName = Path.Combine(root, DirName + i.ToString());\n            Directory.CreateDirectory(currentDirName);\n            CreateDirectories(currentDepth + 1, maxDepth, iterations, currentDirName);\n        }\n    }\n}	0
13019115	13019049	Ensure that a lambda expression points to an actual property of a class?	public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)\n{\n    MemberExpression body = expression.Body as MemberExpression;\n    if (body != null)\n    {\n        PropertyInfo member = body.Member as PropertyInfo;\n        if (member != null)\n        {\n            return member;\n        }\n    }\n    throw new ArgumentException("Property not found");\n}	0
12691125	12690759	C# XML Deserialization into multiple objects	public class TestCommand\n{\n   public string description{get;set;}\n}\n\n[XmlRoot("NameCollection")]\npublic class NameCollection\n{\n    public string GenericName {get; set;}\n    public string GenericDescription {get; set;}\n\n   [XmlArray("Commands")]\n   [XmlArrayItem("Command", typeof(TestCommand))]\n   public TestCommand[] TestCommand {get;set;}\n}	0
19113445	19113240	TreeView from Database	DataSet ds = RunQuery("select PatientId,firstname from PatientDetails");\n\nfor (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n{\nTreeNode root = new TreeNode(ds.Tables[0].Rows[i]["ID"].ToString(), ds.Tables[0].Rows[i]["ID"].ToString());\nroot.SelectAction = TreeNodeSelectAction.Expand;\nTreeNode child = new TreeNode(ds.Tables[0].Rows[i]["ID"].ToString(), ds.Tables[0].Rows[i]["FirstName"].ToString());\nroot.ChildNodes.Add(child);\nTVPatArc.Nodes.Add(root);\n}	0
27558336	27557867	How to read a xml request from server into a dictionary key value	var root = XElement.Parse(xml);\nvar att = root.Nodes().Where(n => n.NodeType == XmlNodeType.Element)\n    .Select(node =>\n    {\n        var element = (XElement)node;\n        return element.Name.LocalName.Equals("att")\n            ? Tuple.Create(element.Attribute("attName").Value, ((XElement)element.FirstNode).Value)\n            : Tuple.Create(element.Name.LocalName, element.Value);\n    })\n    .ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);	0
25952964	25952888	Get All Controls in a Panel from Up-to-Down	Using System.Linq;\n\nforeach (var item in panel1.Controls.OfType<Control>().OrderBy(ee=>ee.TabIndex))	0
15926483	15925849	How to immediately remove cookies from browser	Request.Cookies["OptDepth"].Name = null;	0
27762259	27688694	Autofill an Integrated Windows Authentication	WebClient client = new WebClient();\n        CredentialCache cc = new CredentialCache();\n        cc.Add(new Uri("http://spSite"), "NTLM", new NetworkCredential(username, password, domain));\n        client.Credentials = cc;	0
7130906	7130834	Overwriting a document file	file.txt	0
2014427	2014286	removing dynamically created controls C#	for (int ix = this.Controls.Count - 1; ix >= 0; ix--)\n  if (this.Controls[ix] is PictureBox) this.Controls[ix].Dispose();	0
27356006	27320989	Mouse position values for SendInput	dx =  (x * 65536) / GetSystemMetrics(SystemMetric.SM_CXSCREEN);\ndy = (y * 65536) / GetSystemMetrics(SystemMetric.SM_CYSCREEN);	0
2714790	2714585	smooth scroll with autoscroll	if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) {\n  panel1.VerticalScroll.Value = e.NewValue;\n}	0
23620821	23614970	How to pass IUnknown argument to a COM interface using C#?	object retval;\nclient.GetSomething(SomeID.Magic, out retval);	0
31447731	31447386	How to save a Type in string format	arg2 = obj_type.AssemblyQualifiedName;	0
3829012	3828975	How to fill listbox from a List without any loop	ListBox1.DataSource = listSource;\nListBox1.DataBind();	0
9852203	9852154	How can I get characters until a specific character is reached?	// first find the index of your starting point\nint start = body.IndexOf("<img");\n// then find the index of your ending point\nint end = body.IndexOf("\"", start);\n// then retrieve that portion of the string\nstring goods = body.Substring(start, end - start);	0
1804628	1804623	how to load a XDocument when the xml is in a string variable?	XDocument.Parse(yourvariable)	0
21454862	21454122	Byte Array to Float Conversion C#	public float floatConversion(byte[] bytes)\n    {\n        if (BitConverter.IsLittleEndian)\n        {\n            Array.Reverse(bytes); // Convert big endian to little endian\n        }\n        float myFloat = BitConverter.ToSingle(bytes, 0);\n        return myFloat;\n    }	0
12044365	12043864	Is it possible to update a WCF Data Service (oData) entity without performing a query first?	using(var ctx = new MyContext())\n{\n   var dummyEntity = new MyEntity{ Id = 1 };\n   ctx.MyEntities.Attach(dummyEntity); // EF now knows you have an entity with ID 1 in your db but none of its properties have changed yet\n   dummyEntity.SomeProperty = 1; //the change to SomeProperty is now tracked\n   ctx.SaveChanges();// a single update is called to set entity with Id 1's 'SomeProperty' to 1  \n}	0
11734739	11732963	referring c# instance of object variable name with a string	ListBox abcFeed = LayoutRoot.FindName("abcFeed") as ListBox;	0
13792738	13792598	How do I deserialize this XML file?	XmlSerializer ser = new XmlSerializer(typeof(console[]),new XmlRootAttribute("consoles"));\nvar consoles = (console[])ser.Deserialize(stream);\n\n\npublic class console\n{\n    [XmlAttribute]\n    public string name;\n    public int year;\n    public string manufacturer;\n}	0
2407313	2407302	Convert XmlDocument to String	using (var stringWriter = new StringWriter())\nusing (var xmlTextWriter = XmlWriter.Create(stringWriter))\n{\n    xmlDoc.WriteTo(xmlTextWriter);\n    xmlTextWriter.Flush();\n    return stringWriter.GetStringBuilder().ToString();\n}	0
18517255	18516127	How to open a Web Page in Windows Phone 8 and get the HTML?	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    Deployment.Current.Dispatcher.BeginInvoke(() =>\n        {\n            string site;\n            site = textBox1.Text;\n            webBrowser1.Navigate(new Uri(site, UriKind.Absolute));\n            webBrowser1.LoadCompleted += webBrowser1_LoadCompleted;\n        });\n}\n\nprivate void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)\n        {\n            string s = webBrowser1.SaveToString();\n        }	0
7723843	7723714	CSS Header Color graduatly change from top left to bottom right	css3 gradient property	0
7440690	7440653	C#: Casting a partial class to a parent class and putting it into a Dictionary	var childList = db.GetChildList().Cast<Parent>().ToList();	0
8165046	8164942	How can I have a Label change dynamically based on a Slider Value?	public class SliderToTextConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, \n        object parameter, CultureInfo culture)\n    {\n        // Do the conversion from Slider.Value(int) to Text\n    }\n\n    public object ConvertBack(object value, Type targetType, \n        object parameter, CultureInfo culture)\n    {\n        return null;\n    }\n}	0
27504928	27504315	Creating Blob in Azure Blob Storage with the same name simultaneously	var access = AccessCondition.GenerateIfNoneMatchCondition("*");\nawait blobRef.UploadFromStreamAsync(stream, access, null, null);	0
6056475	6041369	Set DataTable as DataSource for Crystal Report	string strReportFilePath = ConfigurationManager.AppSettings["ReportsPath"] + "MyReport.rpt";\nrpt.Load(strReportFilePath);\nDataTable dt = GetDataTableFromOracle("select item_no, descr from items");\ndt.TableName = "FileNameOfTheTTX";\ncrvReportViewer.ReportSource = rpt;\ncrvReportViewer.DataBind();	0
438513	438188	Split a collection into n parts with LINQ?	static class LinqExtensions\n{\n    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)\n    {\n        int i = 0;\n        var splits = from item in list\n                     group item by i++ % parts into part\n                     select part.AsEnumerable();\n        return splits;\n    }\n}	0
4920606	4920470	Is it OK to have some logic codes inside a property of a data model class?	public class QuizItem\n{\n    public int QuizItemId { get; set; }\n    public string Question { get; set; }\n\n    private IEnumerable<Choice> choices;\n    public IEnumerable<Choice> Choices\n    {\n        get { return choices; }\n    }\n\n    public void SetChoices(IEnumerable<Choice> choices)\n    {\n        foreach (var x in choices)\n            x.QuizItem = this;\n\n        this.choices = choices;                \n    }\n}	0
28491339	28190119	NRules: match a collection	IEnumerable<Order> orders = null;\n\nWhen()\n    .Collect<Order>(() => orders, o => o.Cancelled)\n        .Where(x => x.Count() >= 3);\nThen()\n    .Do(ctx => orders.ToList().ForEach(o => o.DoSomething()));	0
10686275	10686262	sorting a list in linq	RepeaterSponsorGold.DataSource = listGold.OrderBy(n => n.nummer).ToList();	0
17597732	17597154	Cannot insert data into mbf database	public void ExecuteQuery(string query, Dictionary<string, object> parameters)\n{\nusing (SqlConnection conn = new SqlConnection(this.connectionString))\n{\n    conn.Open();\n\n    using (SqlCommand cmd = conn.CreateCommand())\n    {\n        cmd.CommandText = query;\n\n        if (parameters != null)\n        {\n            foreach (string parameter in parameters.Keys)\n            {\n                cmd.Parameters.AddWithValue(parameter, parameters[parameter]);\n            }\n        }\n\n        cmd.ExecuteNonQuery();\n    }\n}\n}	0
4829505	4828262	Working around awkward values in a legacy table with NHibernate	public virtual Category ParentCategory\n{\n    get { return CategoryId == _parentCategory.CategoryId ? null : _parentCategory; }\n    set { _parentCategory = value ?? this; }\n}	0
10518076	10517926	ListBox AutoSizes by item height	IntegralHeight = false;	0
12994972	12994760	Read XML and map to a List<T> dataset using C#	using System.Xml;\n\n...\n\nXmlDocument doc = new XmlDocument();\ndoc.Load("filename.xml"); //or doc.LoadXml(xmlString);\nXmlNodeList objects = doc.GetElementsByTagName("object"); //get list of objects from XML\n\nList<object> myObjects = new List<object> { new object()}; //replace this with your List<object>\n\nfor (int i = 0; i < myObjects.Count; i++)\n{\n    foreach (XmlNode o in objects)\n    {\n        if (o.Attributes["id"].Value == myObjects[i].id.ToString())\n        {\n            myObjects[i].Value1 = o.ChildNodes[0].InnerText;\n            myObjects[i].Value2 = o.ChildNodes[1].InnerText;\n        }\n    }\n}	0
3318521	3318349	How do I determine if a method is a generic instance of a generic method	if( methodInfo.Name == "Contains" \n    &&  methodInfo.DeclaringType.IsGenericType\n    && methodInfo.DeclaringType.GetGenericTypeDefinition() == typeof(ICollection<>))\n{	0
30658386	28457773	How to make Parse work with Xamarin's PCL project and MvvmCross?	MyProject.iOS\n - Reference to Parse.iOS.dll\n - Reference to the Portable Class Library\nMyProject.Android\n - Reference to Parse.iOS.dll\n - Reference to the Portable Class Library\nPortable Class Library\n - Parse Code\n - Xamarin Forms Code\n - Reference to either Parse.iOS.dll or Parse.Android.dll	0
27906212	27906034	How can you get a website application name within a website?	class Program\n{\n    static void Main(string[] args)\n    {\n        ServerManager serverManager = new ServerManager();\n        foreach (var site in serverManager.Sites)\n        {\n            Console.WriteLine("Site -> " + site.Name);\n            foreach (var application in site.Applications)\n            {\n                Console.WriteLine("  Application-> " + application.Path);\n            }\n        }\n\n\n        Console.WriteLine("Press any key...");\n        Console.ReadKey(true);\n    }\n}	0
21081218	21080442	DialogViewController Missing Back Button	public DialogViewController (RootElement root, bool pushing)	0
7176598	7176580	DateTime format in c#	"{0:MMMM d, yyyy}"	0
16834981	16789126	How to execute query that Entity Framework doesn't support and get returned data	using (MyEntities dataContext = new MyEntities())\n    {\n      var query = (from q in dataContext.Queries\n                     where q.Query_Name == queryName\n                     select q.Query).Single();\n\n\n\n      queryResults = dataContext.ExecuteStoreQuery<string>(query);\n      List<string> list = new List<string>(queryResults.ToArray<string>());\n      return list; }	0
31361507	31361282	selection change in wpf template combo box column changes values in other rows	IsSynchronizedWithCurrentItem="False"	0
1528327	1528266	List of valid resolutions for a given Screen?	var scope = new ManagementScope();\n\nvar query = new ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");\n\nusing (var searcher = new ManagementObjectSearcher(scope, query))\n{\n    var results = searcher.Get();\n\n    foreach (var result in results)\n    {\n        Console.WriteLine(\n            "caption={0}, description={1} resolution={2}x{3} " +\n            "colors={4} refresh rate={5}|{6}|{7} scan mode={8}",\n            result["Caption"], result["Description"],\n            result["HorizontalResolution"],\n            result["VerticalResolution"],\n            result["NumberOfColors"],\n            result["MinRefreshRate"],\n            result["RefreshRate"],\n            result["MaxRefreshRate"],\n            result["ScanMode"]);\n    }\n}	0
6766356	6766337	c# Equivalent to VB6 Public variable	// public string property\npublic string string_name { get; set; }\n\n// within class    \nstring_name = "test data";\nMsgBox(string_name); \n\n// from another class\nmyClassInstance.string_name = "other test data";	0
31410935	31410440	C# Convert string to array	var array = JArray.Parse(tagString).Values<string>();	0
25485517	25485264	Getting data from textbox into array	string text = "CAT";\n        int[] buffer = new int[text.Length];\n        int count = 0;\n        //add to buffer\n        foreach(char c in text)\n        {\n            buffer[count] = c;\n            count++;\n        }\n\n        //from buffer to text\n        StringBuilder builder = new StringBuilder();\n        foreach(char c in buffer)\n        {\n            builder.Append(c);\n        }\n        text = builder.ToString();	0
5793685	5793528	Conditionally hiding specific window from desktop screenshot	call the normal print screen function\nload image from clipboard\nget location and size of Window3 from desktop\nfill that rectangle in the image with black (or whatever)\nput the modified image back on the clipboard	0
16721514	16721391	All combinations of a list where each element can have few values	public static IEnumerable<T[]> GetLists<T>(T[] elements, int length)\n{\n    if(length == 1) foreach(var t in elements)\n        yield return new[] { t };\n    else foreach(var t in elements) foreach(var list in GetLists(elements, length - 1))\n        yield return new[] { t }.Concat(list).ToArray();\n}	0
30896008	30895793	Parsing IP Address to string doesn't work for some reason	var result = IpAddress.Parse(richTextBox1.Text.Trim());	0
8077580	8077510	Finding out which control has focus	bool FocusedElement = FocusManager.GetFocusedElement() == textBox;	0
9138911	9138874	How to add values from Dataset to a List?	DataTable dtDetails = ds.Table[0];\nList<int> lstExcelCurrencyCode =\n                    (from dr in dtDetails.AsEnumerable()\n                      select  dr.Field<int>("bd_id")).ToList<int>();	0
17363918	17363767	How to clear textboxes after update method	public ICommand addUser \n{\n    get\n    {\n        if (_addUser == null)\n        {\n            _addUser = new DelegateCommand(delegate()\n            {\n                try\n                {                            \n                    Service1Client wcf = new Service1Client();\n                    wcf.AddUser(User);\n                    Users.Add(User);\n                    wcf.Close();\n                    this.User = new User();\n                }\n                catch\n                {\n                    Trace.WriteLine("working...", "MyApp");\n                }\n            });\n        }\n\n        return _addUser;\n    }\n}	0
13600316	13600244	Set passed value in my ActionResult	public ViewResult Details(int id)\n{\n    var certificateDetails = db.Certificate.FirstOrDefault(p => p.ID == id);\n\n    if (certificateDetails == null)\n        return RedirectToAction("Create", "Certificate", new { userId = id });\n\n    return View(certificateDetails);\n}	0
27363005	27362980	Alternative for If-else	switch (btnDrank2.Text)\n{\n    case "Drank2":\n        btnDrank2.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";\n        drank[1].Naam = txtNaam.Text;\n        drank[1].Inhoud = txtInhoud.Text;\n        drank[1].Prijs = Convert.ToDouble(txtPrijs.Text);\n    break;\n\n    case "Drank3":\n        btnDrank3.Text = txtNaam.Text + "\n" + txtInhoud.Text + "cl";\n        drank[2].Naam = txtNaam.Text;\n        drank[2].Inhoud = txtInhoud.Text;\n        drank[2].Prijs = Convert.ToDouble(txtPrijs.Text);\n    break;\n}	0
24999155	24934835	Change size of all items from a Grid	IEnumerable<Grid> grids = mainGrid.Children.OfType<Grid>();\n            foreach (Grid itemGrid in grids)\n            {\n                IEnumerable<FrameworkElement> items = itemGrid.Children.OfType<FrameworkElement>();\n                foreach (FrameworkElement item in items)\n                    {\n                        item.Width = 100;\n                    }       \n            }	0
13489377	13474565	Fill Datagrid from another Form	Form1 form;\npublic Form2(Form f)// Constructor\n{\n form = f;\n IntializeComponent();\n }	0
3355049	3354964	The correct way to retreive data from a HttpWebRespose Stream then add text	WebClient web_client = new WebClient();\nbyte[] result = web_client.DownloadData("http://blah...");\nstring html = System.Text.Encoding.Default.GetString(result);\nhtml.IndexOf("<body>") ...	0
18923976	18820127	Using OWIN SelfHost with Facebook Authentication	public void Configuration(IAppBuilder app)\n{\n    var config = new HttpConfiguration();\n    config.SuppressDefaultHostAuthentication();\n    config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));\n\n    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();\n\n    config.MapHttpAttributeRoutes();\n\n    app.UseCookieAuthentication(CookieOptions);\n\n    app.UseExternalSignInCookie(ExternalCookieAuthenticationType);\n\n    app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);\n\n    app.UseFacebookAuthentication(\n        appId: "123456",           // obviously changed for this post\n        appSecret: "deadbeef");    // obviously changed for this post\n\n\n    app.UseWebApi(config);\n}	0
25585295	25585225	How to print numbers horizontally in line in Console?	class RandomNumbers\n{\n    private static Random random = new Random();\n    static void Main(string[] args)\n    {\n        var numbers = GenerateRandomNumbers(200,100,10);\n        foreach (var temp in numbers)\n        {\n            Console.Write(temp+" ");\n        }\n    }\n    static IEnumerable<int> GenerateRandomNumbers(int NumberOfElements)\n    {\n        return Enumerable.Range(0,NumberOfElements-1).OrderBy(n=>random.Next());\n    }\n    static IEnumerable<int> GenerateRandomNumbers(int min, int max, int numberOfElement)\n    {\n        return Enumerable.Range(0, numberOfElement - 1).Select(n => random.Next(max, min));\n    }\n}	0
12143879	12140273	Metro app - How to scroll to a particular control in StackPanel	function scrollTo(int childIndex)\n{\n            double offset = 0;\n            for (int i = 0; i < childIndex; i++)\n            {\n                var element = stack.Children[1] as FrameworkElement;\n                offset += element.ActualWidth + element.Margin.Left + element.Margin.Right;\n            }\n\n            if (offset > scroll.ActualWidth)\n                scroll.ScrollToHorizontalOffset(offset - scroll.ActualWidth);\n            else\n                scroll.ScrollToHorizonalOffset(0);\n}	0
18642634	18642507	insert into two tables	string insertSql = "INSERT INTO Rezervacija (date,time,table) OUTPUT INSERTED.Id VALUES (@date,@time,@table);"\n SqlCommand cmd = new SqlCommand(insertSql, con);\n\n cmd.Parameters.AddWithValue("@date", txtDate.Text);\n cmd.Parameters.AddWithValue("@time", ddlTime.SelectedItem.Text);\n cmd.Parameters.AddWithValue("@table", ddlTable.SelectedItem.Text);\n\nvar **reservationId** = (int)cmd.ExecuteScalar()\n\nstring insertSql2 = "INSERT INTO CLIENT (ID_CLIENT,FNAME,LNAME,EMAIL,PHONE,FK_RESERVATION) VALUES (@clientId, @fname, @lname, @email, @phone, @reservation"\n\nSqlCommand cmd2 = new SqlCommand(insertSql2, con);\ncmd.Parameters.AddWithValue("@clientId", clientId);\ncmd.Parameters.AddWithValue("@fname", fname);\ncmd.Parameters.AddWithValue("@lname", lname);\ncmd.Parameters.AddWithValue("@email", email);\ncmd.Parameters.AddWithValue("@phone", phone);\ncmd.Parameters.AddWithValue("@reservation", **reservationId**);	0
12650059	12650013	C# - File is corrupt after uploaded to server	using(StreamReader sourceStream = ...){\n   using(Stream requestStream = request.GetRequestStream())\n   {\n     sourceStream.CopyTo(requestStream);\n   }\n }	0
1119951	1119849	How do I use Optional Parameters in an ASP.NET MVC Controller	public ActionResult Index(string Country, int? Regions)	0
17318760	17318578	find selected radio button in dynamically genereted group in C#	var checkedButton = container.Controls\n                             .OfType<RadioButton>()\n                             .FirstOrDefault(r => r.GroupName=="YourGroup" && r.Checked);	0
23437308	23418177	Await in static method	AsyncPump.Run(async delegate\n\n{\n\n    await DemoAsync();\n\n});	0
17897895	17896740	cut a string from right side to maximal 25 chars even when string is less than 25 chars, remove newlines of all kinds	public static String Preview(String value) {\n    String[] newLines = new String[] { "<br>", "<br />", "\n", "\r", Environment.NewLine };\n\n    foreach (String newLine in newLines)\n      value = value.Replace(newLine, ""); // <- May be space will be better here\n\n    if (text.Length > 25) \n      return value.Substring(0, 25) + "?"; \n      // If you want string END, not string START, comment out the line above and uncomment this\n      // return value.Substring(value.Length - 25) + "?";\n    else\n      return value;\n  }\n\n  ...\n  // Test sample\n\n  String text = "abcd<br>efgh\r\r\n\n1234567890zxy\n\n1234567890abc";\n  String result = Preview(text); // <- abcdefgh1234567890zxy1234?\n\n  String text2 = "abcd<br>efgh\r\r";   \n  String result2 = Preview(text2); // <- abcdefgh	0
3611953	3611882	need help converting c++ definitions to c# equivalent	[DllImport("search.dll")]\n    [return: MarshalAs(UnmanagedType.U1)]\n    private static extern bool searchEvent(\n        int channel,\n        ref int condition,\n        [MarshalAs(UnmanagedType.U1)] bool next\n    );\n\n    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n    private struct Mumble {\n        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]\n        public string version;\n        public long time;\n        public IntPtr minute;\n        [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX)]\n        public ushort _dwell[];\n    }	0
22948809	22946632	How do we trouble shoot a long-running NETMF program that stops in production?	private void TimerCallback_SendSbcData(object stateInfo)\n{\n    try\n    {\n        SbcData data = new SbcData();\n        this.network.Send(data);\n    }\n    catch (Exception ex)\n    {\n        MyLogToCardMethod(ex.ToString());\n    }\n}	0
10012045	10011938	Find most significant bit of a BigInteger	var numBits = (int)Math.Ceil(bigInt.Log(2));	0
7497179	7496749	Problem with default value in dataGridview column when adding a new row	private void dataGridView1_DefaultValuesNeeded(object sender,\n    System.Windows.Forms.DataGridViewRowEventArgs e)\n{\n\n  e.Row.Cells["CustomerNumber"].Value = myOrderNumberValue;\n\n}	0
4439791	4438982	How to select textbox values in windows form	textBox.Select();	0
5271793	5271724	Get All IP Addresses on Machine	// Get host name\nString strHostName = Dns.GetHostName();\n\n// Find host by name\nIPHostEntry iphostentry = Dns.GetHostByName(strHostName);\n\n// Enumerate IP addresses\nforeach(IPAddress ipaddress in iphostentry.AddressList)\n{\n    ....\n}	0
3890293	3890239	How do you desearialize a bool from Xml with custom true and false values?	[XmlRoot(ElementName="response")]\npublic class Response()\n{\n  [XmlElement(ElementName="result")]\n  private string ResultInternal { get; set; }\n\n  [XmlIgnore()]\n  public bool Result{\n    get{\n      return this.ResultInternal == "Success";\n    }\n    set{\n      this.ResultInternal = value ? "Success" : "Failed";\n    }\n  }\n}	0
8210592	8164257	MVC Retrieve Multi Entry from View in Controller	string[] PhoneNumbers = collection.GetValues("PhoneNumber");	0
974764	974696	Umbraco - Get Node by ID programmatically	var node = new Node(nodeId).	0
27629670	27629516	How can i add the strings to child nodes inside a node?	TreeNode nextNode = rootNode;\nfor (int i = 0; i < test1.Count; i++) {\n  newNodeParsed = new TreeNode(test1[i]);\n  nextNode.Nodes.Add(newNodeParsed);\n  nextNode = newNodeParsed;\n}	0
26450930	26450192	is it possible to get js variable to assignt c# string with using Jurrassic Library	var engine = new Jurassic.ScriptEngine();\nvar result = engine.Evaluate(_JsVars);\nvar var1 = engine.GetGlobalValue<string>("js_var1");\nvar var2 = engine.GetGlobalValue<string>("js_var2");	0
15478191	15477888	Deserialize an XML in C# generated by XStream from java	[XmlRoot(ElementName = "ROOT")]\npublic class Root\n{\n    public int id { get; set; }\n    public int serial { get; set; }\n    public string date { get; set; }\n\n    [XmlArray(ElementName = "ITEMS")]\n    [XmlArrayItem("ITEM")]\n    public List<RootItem> Items { get; set; }\n}\n\npublic class RootItem\n{\n    public string name { get; set; }\n    public string idd { get; set; }\n    public string pd { get; set; }\n    public string ed { get; set; }\n}	0
34441279	34441257	ASP.NET MVC, How to add a specific filter in the model?	public partial class Employee {\n    public class EmployeeMD {\n        [Display(Name = "Last Name", Order = -9, \n        Prompt = "Enter Last Name", Description="Emp Last Name")]\n        public object LastName { get; set; }\n\n        [Display(Name = "Manager", AutoGenerateFilter=false)]\n        public object Employee1 { get; set; }\n    }\n}	0
34345262	34344962	How can I extract datetime from the following bytes?	int yearBase = 1993;\n\nint year = yearBase + (int) ((bytes[4] & 0xF0) >> 4) | ((bytes[3] & 0xE0) >> 1);\nint month = (int) (bytes[4] & 0x0F);\nint day = (int) (bytes[3] & 0x1F);\nint hour = (int) ((bytes[2] & 0xF8) >> 3);\nint min = (int) (((bytes[2] & 0x03) << 3) | ((bytes[1] & 0xE0) >> 5));\nint sec = (int) ((bytes[1] & 0x1F) << 1) | ((bytes[0] & 0x80) >> 7);\nint hundreths = (int) (bytes[0] & 0x7F);	0
303036	302775	Call a webpage from c# in code	WebRequest wr = WebRequest.Create("http://localhost:49268/dostuff.aspx");\nwr.Timeout = 3500;\n\ntry\n{\n    HttpWebResponse response = (HttpWebResponse)wr.GetResponse();\n}\ncatch (Exception ex)\n{\n    //We know its going to fail but that dosent matter!!\n}	0
28508530	28487800	Cannot set CurrentCell focus to first editable column in DataGridView	LastTabReachedEventArgs ev = new LastTabReachedEventArgs();\nev.currentCol = currentCol;\nev.currentRow = currentRow;\nOnLastTabReached(this, ev);\nreturn true;	0
28042470	28042333	C# - How can I get data from a registry key by a button.Name or button.Text?	string keyName = btn.Name;\n\n var value = Registry.GetValue(keyName, \n        "NoSuchName",\n        "Return this default if NoSuchName does not exist.");\n\n MessageBox.Show(value.ToString());	0
18264476	18264342	Getting average values from one Array to another Array	public class Foo \n {\n    List<int> main = new List<int>(100);\n    List<int> rollingAverages = new List<int>(100);\n\n    public void Add(int score)\n    {\n        main.Add(score);\n        if(main.Count > 10)\n        {\n            int rollingAverage = AverageLast10();\n            rollingAverages.Add(rollingAverage);\n        }\n    }\n\n    public int AverageLast10()\n    {\n        int sum = 0;\n        for(int i = main.Count - 10; i < 10; i++)\n        {\n            sum += main[i];\n        }\n        return sum / 10;\n    }\n }   \n\n\nSomewhere else in the code\n\nFoo foo = new Foo();\nfoo.Add(94);\nfoo.Add(94);\n...\n yadda yadda yadda	0
20119250	20119199	c# code to copy files between two dates	(file => file.LastWriteTime.Date >= DateTime.Today.AddDays(-5))	0
11797287	11797245	C# convert DOMAIN\USER to USER@DOMAIN	string[] parts = user.Split(new string[] {"/"},\n                            StringSplitOptions.RemoveEmptyEntries);\nstring user = string.Format("{0}@{1}", parts[1], parts[0]);	0
27070814	27070628	Linq query that involves doing group by with two tables that are not directly connected	dbContext.BoxesInputs\n.Select(g => new TempClass\n{\n    CategoryId = g.CategoryId,\n    ColorId = g.ColorId,\n    InputWeight = r.Weight,\n    OutputWeight = 0,\n})\n.Union(dbContext.BoxesOutputs\n    .Select(g => new TempClass\n    {\n        CategoryId = g.CategoryId,\n        ColorId = g.ColorId,\n        InputWeight = 0,\n        OutputWeight = r.Weight\n    })\n)\n.GroupBy(c => new { c.CategoryId, c.ColorId })\n.Select(g => new\n{\n    categoryId = g.Key.CategoryId,\n    colorId = g.Key.ColorId,\n    sumOfInputWeights = g.Sum(r => r.InputWeight),\n    sumOfOutputWeights = g.Sum(r => r.OutputWeight),\n}).ToList();\n\npublic class TempClass\n{\n    public int CategoryID { get; set; }\n    public int ColorID { get; set; }\n    public decimal InnerWeight { get; set; }\n    public decimal OuterWeight { get; set; }\n}	0
29122389	29122260	Read file from multiple encoding in c#	string result;\n            using (System.IO.StreamReader reader = new System.IO.StreamReader("FILENAME", true))\n            {\n                result = reader.ReadToEnd();\n            }	0
4271595	4271277	Programmatically Creating Image Button in WPF	ImageButton.SetImage(newButton, imageSource);	0
24914594	24913658	String Color change in Outlook Add in using C#?	Outlook.MailItem mailItem;\n\nmailItem.HTMLBody = "<html><body><font color="blue">Welcome</font></body></html>"	0
2766052	2766005	Cast an IList to a Collection	Collection<MyClass> coll = new Collection<MyClass>(myIList);	0
27985424	27985370	Wait for download to complete in BackgroundWorker	var locker = new object(); \n\nThread t = new Thread(new ThreadStart(() =>\n{\n    lock (locker)\n    {\n        //peform your downloading operation, and wait for it to finish.\n        client.DownloadFileTaskAsync(new Uri(""), Path.Combine(tempPath + ""));\n        while (/* not yet downloaded */) { }; \n        //inform the parent thread that the download has finished.\n        Monitor.Pulse(locker);\n    }\n}));\n\nt.Start();\n\nlock(locker)\n{\n    Monitor.Wait(locker);\n}	0
18707977	18707782	Disable maximize button of WPF window, keeping resizing feature intact	[DllImport("user32.dll")]\nprivate static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n[DllImport("user32.dll")]\nprivate static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n\nprivate const int GWL_STYLE = -16;\nprivate const int WS_MAXIMIZEBOX = 0x10000;\n\nprivate void Window_SourceInitialized(object sender, EventArgs e)\n{\n    var hwnd = new WindowInteropHelper((Window)sender).Handle;\n    var value = GetWindowLong(hwnd, GWL_STYLE);\n    SetWindowLong(hwnd, GWL_STYLE, (int)(value & ~WS_MAXIMIZEBOX));\n}	0
8152348	8152252	Getting the name of all DataMembers in a DataContract	Type T =(typeof(T));\nvar properties = T.GetProperties(BindingFlags.Public|BindingFlags.Instance);	0
16605635	16605558	Linkbutton opens a modalpopup but the popup its immediately closed	LnkButton.Attributes.Add("onclick", "OpenModalPopup('" + Link.ToString() + "', '" + WidthPopup.ToString() + "', '" + HeightPopup.ToString() + "' ); return false;");	0
1544924	1544905	BeginExecuteNonQuery without EndExecuteNonQuery	ThreadPool.QueueUserWorkItem(delegate {\n    using (SqlConnection sqlConnection = new SqlConnection("blahblah;Asynchronous Processing=true;") {\n        using (SqlCommand command = new SqlCommand("someProcedureName", sqlConnection)) {\n            sqlConnection.Open();\n\n            command.CommandType = CommandType.StoredProcedure;\n            command.Parameters.AddWithValue("@param1", param1);\n\n            command.ExecuteNonQuery();\n        }\n    }\n});	0
12913252	12912164	How to get external appSettings file name?	Configuration config = WebConfigurationManager.OpenWebConfiguration("~");\nAppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection("appSettings");\nString externalFilename = appSettingSection.File;	0
26617196	26605104	How can I update object that contains other objects in lists with npoco?	using (var scope = db.GetTransaction())\n {\n     db.Update(item);\n     foreach (var pictureLink in item.PictureLinks)\n     {\n         db.Update(pictureLink);\n     }\n     scope.Complete();\n  }	0
11088777	11088633	"Substring" a GridView BoundField object	Eval("description").ToString().Substring(0,60)	0
14431823	14428572	How to use RegisterType for a class that implements multiple interfaces?	container.Register(Component.For<IFoo,IBar>().ImplementedBy<FooBar>());	0
3688559	3688332	String Encoding	filepath.Replace("\", "/").Replace("%", "%25").Replace(" ", "%20").Replace("&", "&#38;")	0
22980576	22979942	Getting top element from Hashtable	hashtable.Cast<DictionaryEntry>().OrderBy(entry => entry.Value).Take(3);	0
26452858	26452792	Access variable value from one window in another one	public class WindowBase : Window\n{\n    protected static int foo = 5;\n\n    public int Foo\n    {\n        get\n        {\n            return foo;\n        }\n        set\n        {\n            foo = value;\n        }\n    }\n}\n\npublic partial class Window1 : WindowBase\n{\n    public Window1()\n    {\n        int bar = base.Foo;\n\n    }\n}\n\npublic partial class Window2 : WindowBase\n{\n    public Window2()\n    {\n        int bar = base.Foo;\n    }\n}	0
23787514	23787412	String/Int to double with precision defined onruntime	int value = 1562;\ndecimal d = value;\nwhile (d > 100) {\n    d /= 10;\n}	0
21452954	21432892	SIP TCP Channel with SIP Sorcery	static void Main(string[] args)\n{\n    SIPTCPChannel channel_Tcp = new SIPTCPChannel(new IPEndPoint(IPAddress.Any, 5060));\n    var Transport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());\n    Transport.AddSIPChannel(channel_Tcp);\n\n    IPEndPoint sipServerEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 5060);\n    Timer keepAliveTimer = new Timer(30000);\n\n    keepAliveTimer.Elapsed += (sender, e) =>\n    {\n        // If the TCP channel still has a connection to the SIP server socket then send a dummy keep-alive packet.\n        if(channel_Tcp.IsConnectionEstablished(sipServerEndPoint))\n        {\n            channel_Tcp.Send(sipServerEndPoint, new byte[] { 0x00, 0x00, 0x00, 0x00 });\n        }\n        else\n        {\n            keepAliveTimer.Enabled = false;\n        }\n    };\n\n    keepAliveTimer.Enabled = true;\n}	0
33108852	33108521	AddForce in unity	GetComponent<Rigidbody2d>().velocity = Vector2.zero;	0
2867622	2867567	joining two sets in LINQ	var set = setsA.GroupJoin(\n    setsB,\n    sa => sa.SsnA,\n    sb => sb.SsnB,\n    (a, bs) => new { SSN = a.SsnA, NAME = bs.Any() ? "setB" : "setA" });	0
16114328	14490541	Finding next/previos item and setting as current item	private ICollection<MyCoolClass> _someCollection\n\npublic void DeleteAndSetNext(IEnumerable<MyCoolClass> IEDelete)\n{\n    bool boolStop = false;\n    MyCoolClass NewCurrent = _someCollection.FirstOrDefault(a =>\n        {\n            if (!boolStop) boolStop = IEDelete.Contains(a);\n            return boolStop && !IEDelete.Contains(a);\n        });\n    foreach (MyCoolClass cl in IEDelete)\n    {\n        _someCollection.Remove(a);\n    }\n    CurrentMyCoolClass = NewCurrent ?? _someCollection.LastOrDefault();\n}\n\nMyCoolClass CurrentMyCoolClass\n{\n    get;\n    set;\n}	0
24748449	24748305	Split a string by capital letters in DataFormatString C# - MySQL	static string CapitalSplit(string str)\n{\n    StringBuilder result = new StringBuilder();\n    foreach (char c in str)\n    {\n        if (char.IsUpper(c))\n            result.Append(' ').Append(c);\n        else\n            result.Append(c);\n    }\n\n    return result.ToString().TrimStart(' ');\n}	0
23029980	23029743	how to add element to array	new[] {otherValue, _}	0
8896171	8895946	Binding a textbox to a datagridviewtextboxcolumn?	public class Foo\n{\n  public string Item { get; set; }\n}\n\nprivate void Form2_Load(object sender, EventArgs e)\n {\n  List<Foo> list = new List<Foo>()\n      {\n       new Foo() { Item="1" },\n       new Foo() { Item="2" }\n   };\n\n  dataGridView1.DataSource = list;\n  textBox1.DataBindings.Add("Text", list, "Item");\n}	0
13458049	13457917	Random iteration in for loop	Random r = new Random();\nforeach (int i in Enumerable.Range(0, 9).OrderBy(x => r.Next()))\n{\n    Console.WriteLine(i);\n}	0
28852026	28851880	How to remove last numbers of string with different lengths C#	List<string> elements = new List<string>() {"ABStreet 10 552896","ACLane 1520 155"};\n\nRegex r = new Regex(@"\d+$");\nforeach(string s in elements)\n    Console.WriteLine("[" + r.Replace(s, "").Trim() + "]");	0
19796655	19796489	Grabbing cookie set after post with httpWebClient	var cookies = cookieContainer.GetCookies(new Uri("http://rtchatserver/account/login"));	0
5020763	5019527	How to deserialise Xml content to string	public class Configuration : IXmlSerializable\n{\n    [XmlAttribute]\n    public string MyAttribute { get; set; }\n\n    [XmlText]\n    public string Content { get; set; }\n\n    public void ReadXml(XmlReader reader)\n    {\n        if(reader.NodeType == XmlNodeType.Element &&\n           string.Equals("Configuration", reader.Name, StringComparison.OrdinalIgnoreCase))\n        {\n            MyAttribute = reader["MyAttribute"];\n        }\n\n        if(reader.Read() &&\n           reader.NodeType == XmlNodeType.Element &&\n           string.Equals("SomeOtherXml", reader.Name, StringComparison.OrdinalIgnoreCase))\n        {\n            Content = reader.ReadOUterXml();  //Content = "<SomeOtherXml />"\n        }\n    }\n\n    public void WriteXml(XmlWriter writer) { }\n    public XmlSchema GetSchema() { }\n}	0
3184659	3184652	How do I Skip the first row in an sqldatareader	myReader.Read();\n\nwhile(myReader.Read())\n{\n   //do stuff\n}	0
470300	470272	How would you approach this design?	class ControlA\n{\n    void Frob<T>(IInterfaceB<T> something) where T : IHasSomeProperties, new()\n    {\n        something.ListOfT.Add(new T() { SomeProperty = 5 });\n        something.ListOfT.Add(new T() { SomeProperty = 14 });\n    }\n}	0
24914952	24914444	How to organize waiting until asynchronous file download is complete?	async void button_Click(object sender, RoutedEventArgs e) {     \n    action_1(); //Some action;\n\n    using (var wc = new WebClient()) // not sure if you can dispose at this scope \n                                     // or need to execute action_3 inside here too\n    {\n        var stream = await wc.OpenReadTaskAsync(new Uri("My uri", UriKind.Relative));\n        .. do your thing here\n    }\n\n    action_3() //Another action;\n}	0
23647051	23623711	MVVMCross - Sharing business logic across applications	assemblies other than Core	0
15554945	15554917	Using LINQ, is it possible to output a dynamic object from a Select statement? If so, how?	var listOfFoo = myData.Select(x => new {\n    someProperty = x.prop1,\n    someOtherProperty = x.prop2\n});	0
19261410	19259772	c# populating multiple cells from array	TextBox[] boxes = new TextBox[]{txtbox01, txtbox02, txtbox03, txtbox04, txtbox05, txtbox06};\n    int[] values = new int[]{val1, val2,val3, val4,val5, val6};\n    for(int i=0; i < values.Count; ++i)\n    {\n        //perform calculations\n\n        ...\n\n        boxes[i].Text = values[i];\n    }	0
1680546	1679945	C# - window form application - Close the application	Form2 f2 = new Form2();\n  f2.ShowDialog();\n  this.Close();\n  Application.Exit();	0
713340	713324	How to cast IntPtr to byte*	byte* ptr = (byte*)int_ptr;	0
16547166	16546747	How to calculate with text boxes and skip empty text boxes?	var list = new List<Tuple<TextBox, decimal>>(){\n            Tuple.Create(textBox1, 0.05m),\n            Tuple.Create(textBox2, 0.1m),\n            Tuple.Create(textBox3, 0.2m),\n            Tuple.Create(textBox4, 0.5m),\n            Tuple.Create(textBox5, 1m),\n            Tuple.Create(textBox6, 2m),\n            Tuple.Create(textBox7, 5m),\n            Tuple.Create(textBox8, 10m),\n            Tuple.Create(textBox9, 20m),\n            Tuple.Create(textBox10, 50m),\n            Tuple.Create(textBox11, 100m),\n        };\n    decimal sum = list.Sum(tuple =>{ \n        int a = 0;\n        int.TryParse(tuple.Item1.Text, out a);\n        return a * tuple.Item2;\n    });	0
11674178	11673655	Insert negative value into SQL Server decimal column throws error	string query = "INSERT INTO ticket_elements " +\n"(ticket_id, product_name, price, tax, amount) " +\n"VALUES (@ticket_id, @product_name, @price, @tax, @amount);" + \n"SELECT SCOPE_IDENTITY();",\n// Instantiate SqlCommand object with above query.\nsqlCommand.Parameters.Add("@ticket_id", ticket_id);\nsqlCommand.Parameters.Add("@product_name", pro2.ProductName);\nsqlCommand.Parameters.Add("@price", tPrice);\nsqlCommand.Parameters.Add("@tax", tax);\nsqlCommand.Parameters.Add("@amount", fixedAmountStr);	0
20296277	20296226	setting file size in grid view	if (size < 1024)\n            {\n                return string.Format("{0:#} bytes", size.Value);\n            }\n            else if(size < 1048576)\n            {\n                return String.Format("{0:#} KB", (size.Value / 1024));\n            }\n            else if(size < 1073741824)\n            {\n                return String.Format("{0:#} MB", ((size.Value / 1024) / 1024));\n            }\n            else\n            {\n                return String.Format("{0:#} GB", (((size.Value / 1024) / 1024) / 1024));\n            }	0
24710629	24710535	C# convert string to dictionary	public string GetUrl(string bitlyResponse)\n{\n    var responseObject = new\n    {\n        data = new { url = string.Empty },\n    };\n\n    responseObject = JsonConvert.DeserializeAnonymousType(bitlyResponse, responseObject);\n    return responseObject.data.url;\n}	0
25194918	25194735	Detect the order of clients connect to WCF Service	[ServiceContract]\npublic interface IService {\n  [OperationContract]\n  int GetMyIndex();\n  [OperationContract]\n  void AnyOtherMethod(string foo, int clientIndex);\n}\n\npublic class Service : IService {\n  static int m_Counter;\n  static object m_SyncRoot = new object();\n  public int GetMyIndex() {\n    lock (m_SyncRoot) {\n      m_Counter++;\n      return m_Counter;\n    }\n  }\n\n  public void AnyOtherMethod(string foo, int clientIndex) {\n    // do something\n  }\n}	0
12219626	12219437	How do I loop through all textboxes and make them run corresponding actions from action dictionary?	private void Form1_Load(object sender, EventArgs e)\n{\n    foreach (TextBox tb in this.Controls.OfType<TextBox>())\n    {\n        tb.Enter += new EventHandler(textBoxAll_Enter);\n        tb.Leave += new EventHandler(textBoxAll_Leave);\n    }\n}\n\nprivate void textBoxAll_Enter(object sender, EventArgs e)\n{\n    ((TextBox)sender).Text = "textbox gained focus";\n}\n\nprivate void textBoxAll_Leave(object sender, EventArgs e)\n{\n    ((TextBox)sender).Text = "textbox lost focus";\n}	0
25471665	25471640	Generic Method in C++	template < typename T>\nvoid WriteToFile( T content, File& streamFile)\n{\n    streamFile.open ( "path\to\file.txt", fstream::in\n                                | fstream::out| fstream::app);\n    streamFile << content;\n}	0
1183027	1182983	How to convert single dimensional arrays to multi dimensional ones? (C#)	using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace MiscellaneousUtilities\n{\n    public static class Enumerable\n    {\n        public static T[,] ToRow<T>(this IEnumerable<T> target)\n        {\n            var array = target.ToArray();\n            var output = new T[1, array.Length];\n            foreach (var i in System.Linq.Enumerable.Range(0, array.Length))\n            {\n                output[0, i] = array[i];\n            }\n            return output;\n        }\n\n        public static T[,] ToColumn<T>(this IEnumerable<T> target)\n        {\n            var array = target.ToArray();\n            var output = new T[array.Length, 1];\n            foreach (var i in System.Linq.Enumerable.Range(0, array.Length))\n            {\n                output[i, 0] = array[i];\n            }\n            return output;\n        }\n    }\n}	0
7361994	7361768	implementing request-reply pattern in .net	long id	0
21362686	21362635	How to pass value to a dropdownlist in asp.net?	ddlcol.DataSource= dt2            \n        ddlcol.DataTextField = "UserID";\n        ddlcol.DataValueField = "UserID";\n        ddlcol.DataBind();	0
2464665	2464613	Looking for a component (.NET or COM/ActiveX) that can play AVI files in a WinForms app	Video video;\n\npublic Form1(string[] args) {\n    InitializeComponent();\n\n    video = new Video(dialog.FileName);\n    video.Owner = panel1;\n}	0
26400955	26400782	Get total time duration by group from list	var data = from u in userLoginTrials\n           where u.LogoutTimeStamp != null\n           group u by u.UserId into g\n           select new\n           {\n               UserId = g.Key,\n               TotalTime = g.Sum(t => t.LogoutTimeStamp - t.TrialTimeStamp)\n           };	0
21114943	21114418	Regular expression only one character and 7 numbers	foundMatch = Regex.IsMatch(subjectString, \n    @"\b\n    (?:[a-z]\d{7}|\n    \d[a-z]\d{6}|\n    \d{2}[a-z]\d{5}|\n    \d{3}[a-z]\d{4}|\n    \d{4}[a-z]\d{3}|\n    \d{5}[a-z]\d{2}|\n    \d{6}[a-z]\d{1}|\n    \d{7}[a-z])\n    \b", \n    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);	0
28684830	28684052	Set Email Activity to Complete in CRM	if (_emailId != Guid.Empty)\n                {\n                    // Create the Request Object\n                    SetStateRequest state = new SetStateRequest();\n\n                    // Set the Request Object's Properties\n                    state.State = new OptionSetValue((int)Xrm.EmailState.Completed);\n                    state.Status = new OptionSetValue((int)2);\n\n                    // Point the Request to the case whose state is being changed\n                    EntityReference EntityMoniker = new EntityReference(Xrm.Email.EntityLogicalName, _emailId);\n                    state.EntityMoniker = EntityMoniker;\n\n                    // Execute the Request\n                    SetStateResponse stateSet = (SetStateResponse)_serviceProxy.Execute(state);\n                }	0
22999809	22999710	Retrieving JSON from a web site - What am I missing?	_download_serialized_json_data<RootObject>(url);	0
5765282	5764973	C# Windows Application - Linking a button to start a game	using System.IO;\nusing System.Reflection;\n...\n        string myDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);\n        string gameDir = Path.Combine(myDir, "MBO");\n        string gameExe = Path.Combine(gameDir, "marbleblast.exe");\n        process1.StartInfo.FileName = gameExe;\n        process1.StartInfo.WorkingDirectory = gameDir;\n        process1.SynchronizingObject = this;\n        process1.EnableRaisingEvents = true;\n        process1.Exited += new EventHandler(Process1Exited);	0
13596484	13596409	how to tell which panel fired the click event	void Form1_Click(object sender, EventArgs e)\n{\n    var panel = sender as Panel;\n    if (null != panel)\n    {\n        if (panel.Name.equals("Panel1"))\n        {\n             .. ...\n        }\n    }\n}	0
5671460	5671084	Edit row in gridview with hyperlink in ASP.NET	protected void Page_Load(object sender, EventArgs e)\n{   \n    if (!Page.IsPostBack)\n    {\n        if (Request.QueryString["productID"] != null)\n        {\n            productID = Convert.ToInt32(Request.QueryString["productID"]);\n            bindData(productID)\n        }\n        ...\n    }\n }\n   protected void bindData(int productID)\n    {\n     //to avoid sql injection as mentioned below use parameters \n      SqlConnection conn = new SqlConnection(ConnectionString); // define connection string globally or in your business logic\n      conn.Open();\n      SqlCommand sql = new SqlCommand("Select * From [Table] Where ID = @productID",conn);\n      SqlParameter parameter = new SqlParameter();\n      parameter.ParameterName = "@ID";\n   parameter.Value = productID;\n       sql.Parameters.Add(parameter);\n       conn.close()\n  }	0
9009474	9008903	Understanding a java class of a wsdl service	PlaceOrdersNoReceiptRequest.Orders orders = new PlaceOrdersNoReceiptRequest.Orders();\norders.getOrder().add(bet);\n\nPlaceOrdersNoReceiptRequest request = new PlaceOrdersNoReceiptRequest();\nrequest.setOrders(orders);	0
11852448	11852333	C# lambda and ascending values in array	public static IEnumerable<int> GetAscending(IEnumerable<int> input, int startIndex)\n{\n    var ascending = input.Skip(startIndex)\n        .Zip(input.Skip(startIndex + 1), (first, second) => new { Num = first, Next = second, Diff = second - first })\n        .SkipWhile(p => p.Diff <= 0)\n        .TakeWhile(p => p.Diff > 0)\n        .Select(p => Tuple.Create(p.Num, p.Next))\n        .ToArray();\n\n    if(ascending.Length == 0) return Enumerable.Empty<int>();\n\n    return ascending.Select(t => t.Item1).Concat(new int[] { ascending.Last().Item2 });\n}	0
12439876	12436228	Set ListView row background	int index = 1;\nListViewItem row = ListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;\nrow.BackGround = Brushes.Red;	0
256871	256832	C# - Fill a combo box with a DataTable	var languages = new string[2];\nlanguages[0] = "English";\nlanguages[1] = "German";\n\nDataSet myDataSet = new DataSet();\n\n// --- Preparation\nDataTable lTable = new DataTable("Lang");\nDataColumn lName = new DataColumn("Language", typeof(string));\nlTable.Columns.Add(lName);\n\nfor (int i = 0; i < languages.Length; i++)\n{\n    DataRow lLang = lTable.NewRow();\n    lLang["Language"] = languages[i];\n    lTable.Rows.Add(lLang);\n}\nmyDataSet.Tables.Add(lTable);\n\ntoolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;\ntoolStripComboBox1.ComboBox.DisplayMember = "Language";\n\ntoolStripComboBox1.ComboBox.BindingContext = this.BindingContext;	0
22560405	22559632	How to populate the fields in browser using Java or C#	package selenium.example;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.htmlunit.HtmlUnitDriver;\n\npublic class ExampleSearch  {\n    public static void main(String[] args) {\n\n        WebDriver driver = new HtmlUnitDriver();\n\n        // Open Google\n        driver.get("http://www.google.com");\n\n        WebElement element = driver.findElement(By.name("q"));\n\n        element.sendKeys("selenium best practices");\n\n        // Send form with element \n        element.submit();\n    }\n}	0
10875803	10874999	How to map a property with a complex type to a specific table column with code-first EF 4.3?	modelBuilder.Entity<Race>().Property(x => x.TotalMinutes.Value)\n   .HasColumnName("RACEMINUTES");	0
5490074	5489984	Can a ThreadPool be used from a Thread in C#?	object state = ...some value...;\nThreadPool.QueueUserWorkItem(MyHandler, state);\n\n...\n\nprivate void MyHandler(object state)\n{\n    object newState = ... do something with state ...\n    ThreadPool.QueueUserWorkItem(HandleMoreWorkToDo, newState);\n}	0
22796092	22775895	WPF How to use a validation rule in a textbox without creating an extra property to bind to in dialogbox?	public GenericDialogBox(string MainLabelContent, string WindowTitle, string TextboxDefaultText, ValidationRule rule)\n    {\n      this.DataContext = this;\n      Text = "";\n      if (rule != null)\n      {\n        TextBoxValidationRule = rule;\n      }\n      InitializeComponent();\n      MainLabel.Content = MainLabelContent;\n      Title = WindowTitle;\n\n      Binding binding = BindingOperations.GetBinding(MainTextBox, TextBox.TextProperty);\n      binding.ValidationRules.Add(rule);\n\n\n      MainTextBox.SelectAll();\n      MainTextBox.Focus();\n    }	0
12900005	12899935	Sliding a bitmap on the screen smoothly C#	class Form1 : Form {\n  Form1(){\n   this.doublebuffered = true;\n  }\n}	0
24133280	24132313	Initializing ExportFactory using MEF	public PartsManager()\n    {\n         ConstructContainer();\n    }\n\n    private void ConstructContainer()\n    {\n        var catalog = new DirectoryCatalog(@"C:\plugins\");\n        var container = new CompositionContainer(catalog);\n        container.ComposeParts(this);\n        container.SatisfyImportsOnce(this);\n    }	0
2461745	2461568	Accessing wrapped method attribute in C#	public static void ProcessStep(Action<bool> action) \n{ \n    ProcessStep(() => action(true), action.Method); //this is only example, don't bother about hardcoded true \n}	0
24709077	24708488	MSChart and a Filled Radar Chart	// Populate series data\ndouble[]    yValues = {65.62, 75.54, 60.45, 34.73, 85.42, 55.9, 63.6, 55.2, 77.1};\nstring[]    xValues = {"France", "Canada", "Germany", "USA", "Italy", "Spain", "Russia", "Sweden", "Japan"};\nchart1.Series["Default"].Points.DataBindXY(xValues, yValues);\n\n// Set radar chart type\nchart1.Series["Default"].ChartType = SeriesChartType.Radar;\n\n// Set radar chart style (Area, Line or Marker)\nchart1.Series["Default"]["RadarDrawingStyle"] = "Area";\n\n// Set circular area drawing style (Circle or Polygon)\nchart1.Series["Default"]["AreaDrawingStyle"] = "Polygon";\n\n// Set labels style (Auto, Horizontal, Circular or Radial)\nchart1.Series["Default"]["CircularLabelsStyle"] = "Horizontal";\n\n// Show as 3D\nchart1.ChartAreas["Default"].Area3DStyle.Enable3D = true;	0
13272845	13272805	How to pass in the entire object into a function in a repeater?	(Product)Container.DataItem	0
9025916	9025808	How do I find a variable length string between two marker characters in C#?	public string SubstituteStandardValues(string exp)\n{\n    var matches = Regex.Matches(exp, @"\$[a-z]+\$", RegexOptions.IgnoreCase);\n\n    foreach (Match match in matches)\n    {\n        // replace logic here...\n    }\n\n    return exp;\n}	0
17480125	17480060	c# WPF button link to user control page	private void btnHome_Click(object sender, RoutedEventArgs e)\n{\n    NavigationService.GetNavigationService(this).Navigate("home.xaml");\n}	0
26670892	26668308	How do I restrict user to select only single checkbox in gridview which i created dynamically	void mydatagridview_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n    int col = yourCheckboxColumnIndex;\n    for (int r = 0; r < mydatagridview.Rows.Count; r++)\n        if (r != e.RowIndex && e.ColumnIndex == col ) \n            mydatagridview[col , r].Value = false;\n}	0
32838041	32837945	How to properly validate file from user and detect extension change?	Image.FromStream	0
482749	465437	How to resolve instances with constructor parameters in custom IOC Container?	public T Create<T>()\n         {\n             if (registeredTypes.ContainsKey(typeof(T)))\n                 return (T)Activator.CreateInstance(registeredTypes[typeof(T)].\n                                                                       GetType());\n             else\n                 throw new DependencyResolverException("Can't\n                                       create type. Type " + typeof(T) + "\n                                                           not found.");\n         }	0
6788389	6409486	Refresh masterpage for subsites when applying a new one to root web	using (SPWeb w = ((SPSite)properties.Feature.Parent).OpenWeb())\n        {\n            Uri masterUri = new Uri(w.Url + "/_catalogs/masterpage/AdventureWorks.master");\n            w.CustomMasterUrl = masterUri.AbsolutePath;\n            w.AllowUnsafeUpdates = true;\n            w.Update();\n\n            foreach (SPWeb ww in w.Site.AllWebs)\n            {\n                if (!ww.IsRootWeb)\n                {\n                    Hashtable hash = ww.AllProperties;\n                    if (string.Compare(hash["__InheritsCustomMasterUrl"].ToString(), "True", true) == 0)\n                    {\n                        ww.CustomMasterUrl = masterUri.AbsolutePath;\n                        ww.AllowUnsafeUpdates = true;\n                        ww.Update();\n                    }\n                }\n            }\n        }	0
29557685	29557274	Using AutoMapper to create a new instance of an generic object	public void Save(T entity)\n{\n  Mapper.CreateMap<T, T>();\n  var newEntity = Mapper.Map<T, T>(entity);\n}	0
18855151	18855076	How do you create a dynamic select projection from a generic using Linq in C#?	public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> conversion) where T : class\n{\n    item = getItemCallback();\n    if (item != null)\n    {\n        doSomeThing(item);\n\n        if (conversion != null)\n            doSomethingElse(conversion(item));\n    }\n    return item;\n}	0
29317231	29297909	How to draw a sprite on a moving canvas	Vector2 Velocity { get; set; }\n    Vector2 relative { get; set; }\n    public void Update(GameTime gameTime, Vector2 center)\n    {\n\n        this.currentCentre = center;\n\n        Vector2 calculatedDirection = CalculateDirection();\n\n\n        if (speed > 0f || speed < 0f)\n        {\n            Velocity = calculatedDirection * speed * 0.1f;\n            relative = relative - Velocity;\n            position = currentCentre + relative;\n\n        }\n    }	0
3680489	3680394	Visual studio Attaching debugger to windows service -- attach greyed out	System.Diagnostics.Debugger.Launch();	0
19160404	19160156	Using Reflection to get number of bytes from PropertyType	int x;\nsizeof(x);	0
20795774	20780329	represent array of byte in datagridview	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        UpdateDataGridView();\n    }\n\n    private void UpdateDataGridView()\n    {\n        byte[] bmp = new byte[28];\n        List<BMPInfo> InfoList = new List<BMPInfo>();\n\n        using (var fs = new FileStream("D:\\x.bmp", FileMode.Open, FileAccess.Read))\n        {\n            fs.Read(bmp, 0, bmp.Length);\n        }\n\n        InfoList.Add(new BMPInfo\n        {\n            Offset = BitConverter.ToInt32(bmp, 10),\n            Size = BitConverter.ToInt32(bmp, 2),\n            Description = "Something"\n        });\n        dataGridView1.DataSource = InfoList;\n    }\n}\n\npublic class BMPInfo\n{\n    public long Offset { get; set; }\n    public long Size { get; set; }\n    public string Description { get; set;}\n}	0
16159265	16142008	Accessing another user' status via outlook interop dll	Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();\nNameSpace ns = outlookApp.GetNamespace("mapi");\nns.Logon(Missing.Value, Missing.Value, false, true);\nAddressEntries addressBook = ns.GetGlobalAddressList().AddressEntries;\nAddressEntry testSearch = addressBook["LastName, FirstName"];\nConsole.WriteLine("FreeBusy: {0}", testSearch.GetFreeBusy(DateTime.Now, 30, true));	0
23561181	23560611	add delete link label against data in the row in window form application c#	var col = new DataGridViewLinkColumn();\ncol.DataPropertyName = "Delete";\ncol.Name = "Delete";\n\nds.Tables[0].Columns.Add(col);	0
11611459	11611138	How to change the color of an image in XNA	batch.Draw(texture, myVector, Color.Green * 0.5f); //The float indicates the transparency of the green color	0
9891071	9890991	A few XmlElement attributes on a property C#	[XmlElement(typeof(int),\n ElementName = "ObjectNumber"),\nXmlElement(typeof(string),\n ElementName = "ObjectString")]\npublic ArrayList ExtraInfo;	0
1410685	1409936	Referencing Page.Title after it has been set as part of a asp:contentplaceholder	Master.Title = "Welcome: " + basketId	0
27706257	27704349	How to concatenate Datagridview rows values and store it into one datatable Cell	libArt +=  string.Join(",", row1.Cells.Cast<DataGridViewCell>().Where(c => c.Value != null).Select(c => c.Value.ToString()).ToArray());	0
14510428	14510386	How to comment properties of a class for Visual Studio intellisense?	/// <summary>Description A (working for intellisense)</summary>\npublic int iA { get; set; }	0
11951144	11950729	Unable to fire update and insert query in access using C# windows application	insert into tblU(UserName, [Password]) values('ops1', 'ops')	0
18416	18407	Most succinct way to determine if a variable equals a value from a 'list' of values	bool b = new int[] { 3,7,12,5 }.Contains(5);	0
30717407	30717144	Entity Framework - Select single record ordered by a property	homeVM.LastSaleAmount = salesService.GetSalesOrderHeaders()\n    .OrderByDescending(a => a.TotalDue)\n    .Select(a => a.TotalDue)\n    .First();	0
10937060	10935192	Get all security groups under specific folder	DirectoryEntry searchBase = new DirectoryEntry("LDAP://OU=CHC_APP,DC=cfs");\nDirectorySearcher searcher = new DirectorySearcher(searchBase);\nsearcher.Filter = "(&(objectCategory=group)(objectClass=group)(groupType:1.2.840.113556.1.4.803:=2147483648))";\n\nSearchResultCollection results = searcher.FindAll();\n\n//do something with results	0
4502544	4502512	Is there a way to specify multiple formats in C# for a decimal string like in VB?	whateverstring.ToString(" 00.00000;-00.00000");\n-29.69 -> "-29.69000"\n48 -> " 48.00000" <-notice space padding the front.	0
6957300	6957186	Conditional to detect a drive	if (Directory.Exists(@"E:\")){\n\nStreamWriter sw;         \nsw = File.AppendText ("E:\\SignIn.txt");         \nsw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + "Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");         \nsw.Close ();\n}\n\nelse{\nStreamWriter sw;         \nsw = File.AppendText ("C:\\SignIn.txt");         \nsw.WriteLine ("Date and Time: " + label5.Text + " | Name: " + Name_Box.Text + "Company: " + Company_Box.Text + " | Visiting: " + Visiting_Box.Text + " |");         \nsw.Close ();    \n}	0
4138987	4137839	How to screen scrape form results from a browser	javascript:var oForm = document.forms[0];var name = oForm.elements["name"].value; void window.open("http://www.mydomain.com/page.aspx?data=" + name ,"_blank","resizable,height=130,width=130");	0
12350786	12344010	Context Menu Strip -> Changing the color of Highlighted Items	private void aboutToolStripMenuItem_MouseEnter(object sender, EventArgs e)\n    {\n        ToolStripMenuItem TSMI = sender as ToolStripMenuItem;\n        TSMI.ForeColor = Color.Black;\n    }\n\n    private void aboutToolStripMenuItem_MouseLeave(object sender, EventArgs e)\n    {\n        ToolStripMenuItem TSMI = sender as ToolStripMenuItem;\n        TSMI.ForeColor = Color.White;\n    }	0
1124254	1124181	How can I reference a constructor from C# XML comment?	/// <seealso cref="PublishDynamicComponentAttribute(Type)"/>	0
13108074	13107949	Separate data between multiple instances	public class Model\n{ \n    public int progress;\n    public event EventHandler ProgressChanged;\n\n    public int Progress\n    {\n        get { return progress; }\n        set \n        { \n            progress = value;\n            if (ProgressChanged != null)\n            {\n                ProgressChanged(this, null);\n            }\n        }\n    }\n}\n\npublic class Copy\n{\n    public List<Model> models = new List<Model>();\n    public event EventHandler CopyProgrss; // FormModel binded to this event. \n    public void AddModel(Model m)\n    {\n        this.models.Add(m);\n        m.ProgressChanged += new EventHandler(m_ProgressChanged);\n    }\n\n    void m_ProgressChanged(object sender, EventArgs e)\n    {\n        Model currentModel = sender as Model;\n        int modelProgress = currentModel.Progress;\n        if (CopyProgrss != null)\n            CopyProgrss(modelProgress,null); // here you can caluclate your over progress. \n    }\n}	0
26004078	26003863	Async socket - Duplex communication with permanent sockets in c#	content = state.sb.ToString();\nif (content.IndexOf("<EOF>") > -1) {\n     // All the data has been read from the \n     // client. Display it on the console.\n     Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",\n                 content.Length, content );\n     // Echo the data back to the client.\n     Send(handler, content);\n\n     { // NEW \n         // Reset your state (persist any data that was from the next message?)      \n\n         // Wait for the next message.\n         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, \n         new AsyncCallback(ReadCallback), state);\n     }\n\n } else {\n      // Not all data received. Get more.\n      handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, \n      new AsyncCallback(ReadCallback), state);\n}	0
17549165	17549039	Entity Framework join table with additional field	public class UserCase\n{\n     public virtual User User { get; set; }\n     public virtual Case Case { get; set; }\n\n     public virtual string UserType { get; set; }\n}	0
23431879	23431499	Test method returns a string with Moq	[TestMethod]\n    public void GetTicketId()\n    {\n        var mockMyService = new Mock<IMyService>();\n        mockMyService.Setup(n => n.GetTicketId(It.IsAny<Coordinate[]>))\n                     .Returns("Not Null String");\n        var objectUnderTest = new ObjectUnderTest(mockMyService);\n\n        var ticketId = objectUnderTest.GetTicketId();\n\n        Assert.IsNotNull(ticketId);\n    }	0
30090708	30090681	How to take nth item in array to zth item in array?	string result = string.Join(" ", test.Skip(1).Take(3));	0
877172	877158	how to get a text from textbox that is betwen two dots	var parts = textbox.Text.Split(new char[] {'.'});\nif (parts.Length < 3) throw new InvalidOperationException("Invalid address.");\nvar middlePart = parts[1];	0
7659901	7659756	C# add line numbers to a text file	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\n\nnamespace AppendText\n{\n    class Program\n    {\n        public static void Main()\n        {\n            string path = Directory.GetCurrentDirectory() + @"\MyText.txt";\n\n            StreamReader sr1 = File.OpenText(path);\n\n\n            string s = "";\n            int counter = 1;\n            StringBuilder sb = new StringBuilder();\n\n            while ((s = sr1.ReadLine()) != null)\n            {\n                var lineOutput = counter++ + " " + s;\n                Console.WriteLine(lineOutput);\n\n                sb.Append(lineOutput);\n            }\n\n\n            sr1.Close();\n            Console.WriteLine();\n            StreamWriter sw1 = File.AppendText(path);\n            sw1.Write(sb);\n\n            sw1.Close();\n\n        }\n\n    }\n}	0
12230811	12206758	Is it possible to force a WebBrowser to, instead of opening in a new window, replace the currently opened window?	Processed = True\nWB1.Navigate2 URL	0
33626381	33528414	How to override OnLaunched() from Template10	sealed partial class App : BootStrapper\n{\npublic App()\n{\n    this.InitializeComponent();\n}\n\npublic override Task OnInitializeAsync(IActivatedEventArgs args)\n{\n    var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);\n    Window.Current.Content = new Views.Shell(nav);\n    return Task.FromResult<object>(null);\n}\n\npublic override Task OnStartAsync(BootStrapper.StartKind startKind, IActivatedEventArgs args)\n{\n    NavigationService.Navigate(typeof(Views.MainPage));\n    return Task.FromResult<object>(null);\n}\n}	0
24226997	24226548	How to draw an ellipse on position I touch Windows Phone?	elip.HorizontalAlignment = HorizontalAlignment.Left;\nelip.VerticalAlignment = VerticalAlignment.Top;\nelip.RenderTransform = new TranslateTransform() { X = 10, Y = 50 }	0
1615493	1615450	How can I send data with a TcpListener, and wait for the response?	byteRead = stream.Read(buffer, 0, 1000);	0
9949867	9945779	Getting User Permissions From Active Directory In SharePoint Groups	SPUtility.GetPrincipalsInGroup	0
18185038	18184909	Transforming without setting RenderTransform	var currentTransform = this.RenderTransform;\nvar myTransform = new RotateTransForm()\n{\n    Angle = 90\n};\nvar group = new TransformGroup();\ngroup.Children.Add(currentTransform);\ngroup.Children.Add(myTransform);\n\nthis.RenderTransform = group;	0
2322395	2322353	Streaming an XmlDocument for POST	var document = new XDocument(new XElement("Root", new XAttribute("Attr", "Value")));\nvar stream = new MemoryStream();\ndocument.Save(stream);\nstream.Position = 0;   //Important!\n\nSomeMethod("text/xml", stream);	0
19570464	19570215	WPF Listbox multi selection working like windows files select	ListBox.SelectionMode = SelectionMode.Extended	0
20059088	20057286	C# how to copy templet object data to a new object , but no the address	public class sData\n{\n    public string name;\n    public int Number;\n    public sData(string name,int Number)\n    {\n        this.poster_path = path; //copied from question, this might need updating.\n        this.Number = Number;\n    }\n\n    sData CreateCopy()\n    {\n        return new sData(name, number);\n    }\n\n}\n\n\nsData template = new sData("aaaa","0");\n\nsData realData1 = template.CreateCopy();\nrealData1.Number=100;	0
26943787	26928820	how to use sendkey.send method in my C# windows form application?	SendKeys.Send("^(V)");	0
30588925	30574229	Creating helppage for a webapi c#	var properties = parameter.ParameterDescriptor.ParameterType.GetProperties();\n var _prop = properties[2];\n Type _objType = _prop.PropertyType;\n object objInstance = Activator.CreateInstance(_objType);\n\nforeach (var subProperty in objInstance.GetType().GetProperties())\n  {\n      APIEndPointParameter _APIEndPointSubParameter = new APIEndPointParameter(subProperty.Name, "", "", false, subProperty.PropertyType.ToString(), null);\n      _APIEndPointParameter.SubParameters.Add(_APIEndPointSubParameter);\n   }	0
15038854	15038574	Inserting a parent entity with existing child in Fluent NHibernate	var user = new User\n    {\n        FirstName = "TestFirstName",\n        LastName = "TestLastName",\n        Unit = Session.Load<Unit>(unitId)\n    }	0
29207375	29206926	Split Sentence if it ends with period but not number containing decimal	var regex = new System.Text.RegularExpressions.Regex(@"(?<!\d)\.(?!\d)");\nvar myText = @"My package a mount is 85.5 daily, how can I make use of it. any body has an idea for that. please let me know.";\n\nConsole.WriteLine(regex.Replace(myText, Environment.NewLine));	0
20256863	20256690	How do i Take out the last value character inside a ListView Column	for (int i = 0; i < MMDetailsList.Items.Count; i++)\n{\n    string text = MMDetailsList.Items[i].SubItems[3].Text;\n    if (!string.IsNullOrEmpty(text))\n    {\n        if(char.IsLetter(text.Last()))\n        {\n            MessageBox.Show("Last Letter :" +text.Last());\n        }\n    }\n\n}	0
6585756	6583446	Store linq-to-sql objects in session, or alternate solution	...\nds.WriteObject(w, fi);\nw.Flush();\nms3.Position = 0;\nbuf = ms.ToArray();\n...	0
28711848	28688454	Screen Capture Not Capturing Dialog Boxes in My application	Bitmap bmpScreenshot = new Bitmap(Screen.AllScreens[1].Bounds.Width, Screen.AllScreens[1].Bounds.Height, PixelFormat.Format32bppArgb);\n\n            Graphics.FromImage(bmpScreenshot).CopyFromScreen(\n                                         Screen.AllScreens[1].Bounds.X,\n                                         Screen.AllScreens[1].Bounds.Y,\n                                         0,\n                                         0,\n                                         Screen.AllScreens[1].Bounds.Size,\n                                         CopyPixelOperation.SourceCopy);\n\n            this.picExtendedModitorScreen.Image = bmpScreenshot;\n            this.picExtendedModitorScreen.Refresh();	0
4704770	4704731	How to get class mapping information at runtime in Nhibernate?	ISessionFactory.GetClassMetadata	0
9317532	9306975	c# Panel with autoscroll - Srollbar position reset on a control focus	public class CustomPanel : System.Windows.Forms.Panel\n{\n    protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)\n    {\n        // Returning the current location prevents the panel from\n        // scrolling to the active control when the panel loses and regains focus\n        return this.DisplayRectangle.Location;\n    }\n}	0
2493134	2493054	How do I prevent a C# method from executing using an attribute validator?	[PrincipalPermissionAttribute(SecurityAction.Demand, Name="Bob",\nRole="Supervisor")]	0
11947908	11947796	Showing progress value from a list of tasks through ProgressBar	for(int i = 0; i < tasks.Count; i++)\n{\n    double percentage = (double)(i + 1) / (double)tasks.Count;\n    Action<double> update = p => \n    {\n        progressBar1.Value = (int)Math.Round(p * 100);\n    };\n    this.Invoke(update, percentage);\n    // Do tasks here...\n}	0
26617289	26615714	.Sum() in lambda expressions	var dato = db.Cuentas.Where(x => x.Codigo == codigo)\n                .Join(db.MovimientosPolizas, cuentas => cuentas.Id, movimientos => movimientos.IdCuenta, (cuenta, movimiento) => new { sumImporte = movimiento.Importe, cuenta = cuenta.Nombre })\n                .Sum(x => x.sumImporte);	0
5833015	5832928	Update ObservableCollection from BackgroundWorker/ProgressChanged Event	public class ComputerEntry : INotifyPropertyChanged\n    {\n        #region INotifyPropertyChanged Members\n\n        public event PropertyChangedEventHandler PropertyChanged;\n\n        #endregion\n\n        private void RaisePropertyChanged(String propertyName)\n        {\n            if (this.PropertyChanged != null)\n            {\n                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n            }\n        }\n\n        private String _ComputerName;\n        public String ComputerName\n        {\n            get\n            {\n                return _ComputerName;\n            }\n            set\n            {\n                if (_ComputerName != value)\n                {\n                    _ComputerName = value;\n                    this.RaisePropertyChanged("ComputerName");\n                }\n            }\n        }\n    }	0
11885115	11884751	users in one role cannot remove users from another (C#)	if (Roles.GetRolesForUser(userToDelete).Contains("admin") && !User.IsInRole("admin"))\n{   // only allow admins to remove other admins.\n   statuslbl.Text = "You do not have sufficient privileges to remove this user.    Only Administrator's can remove administrators from the system."; \n} else {\n}	0
24752761	24723456	disable flash in selenuim cross browser	FirefoxProfile profile = new FirefoxProfile();\nprofile.setPreference("plugin.state.flash", 0);\nFirefoxDriver driver = new FirefoxDriver(profile);	0
23811997	23808567	How to add choices to a field via csom	Field catField = list.Fields.AddFieldAsXml(@"\n            <Field Type='Choice' DisplayName='Category' Format='Dropdown'>\n                <Default>IT</Default>\n                <CHOICES>\n                  <CHOICE>IT</CHOICE>\n                  <CHOICE>Sales</CHOICE>\n                </CHOICES>\n</Field>", true, AddFieldOptions.DefaultValue);	0
14244659	14244622	How to extract data into client from WCF internally using Entity Framework	public IEnumerable<Bank_Configuration>  SelectBankConfiguration()\n{\n    using (EFEntities objEFEntities = new EFEntities())\n    {                             \n        var Result= from c in objEFEntities.Bank_Configuration \n                    select c;\n\n        return Result.ToArray();\n    }            \n\n}	0
19009575	19005955	How to create an internal search engine for objects	var searchPattern = "word1|word2";\n var regex = new Regex(searchPattern);\n var search = list.Select( o => \n                        new { Weight = regex.Matches(o.Header).Count * 20 \n                                     + regex.Matches(o.Content).Count * 10, \n                              Value = o})\n                  .OrderByDescending(o => o.Weight);	0
19800116	19799677	How to make a dropdownlist show selected value at top of dropdown instead of bottom?	protected void Page_PreRender(object sender, EventArgs e)\n{\n    var itemIndex = DropDownList1.SelectedIndex;\n    var item = DropDownList1.Items[itemIndex];\n    DropDownList1.Items.RemoveAt(itemIndex);\n    DropDownList1.Items.Insert(0, new ListItem(item.Text, item.Value));\n}	0
19933983	19933933	If statements in methods	public string mood()\n        {\n            var unhappiness = Hunger + Boredom;\n            string m = string.Empty;\n            if (unhappiness < 5)\n            {\n                m = "Happy";\n            }\n\n            if (unhappiness <= 5 && \n                unhappiness <= 10)\n            {\n                m = "Okay";\n            }\n\n            if (unhappiness <= 11 &&\n                unhappiness <= 15)\n            {\n                m = "Frustrated";\n            }\n\n            if (unhappiness <= 16)\n            {\n                m = "Mad";\n            }\n            return m;	0
13751698	13751510	Dataset row count to textbox	DataView dv = new DataView();\ndv = dtSet.Tables[0].DefaultView;\ndv.RowFilter = "Status='Closed'";	0
19598177	19598157	Check number of one list in another list	MyLottoNumbers.Intersect(TonightsLottoNumbers).Count()	0
27392884	27392792	Parsing xml in C#	for(int i = 0; i < instance.Items.Length; i++)\n{\n    object item = instance.Items[i];\n    if(item is reportFruit) {\n       // it is a fruit!!!\n       reportFruit fruit = (reportFruit)item;\n    }\n    if(item is reportVegetable) {\n       // it is not a fruit :'(\n       reportVegetable vegetable = (reportVegetable)item;\n    }\n}	0
8325511	8324146	How to rotate text in iTextSharp?	using (stream = new FileStream(temp_filename, FileMode.Create))\n{\n    iTextSharp.text.Document document = new iTextSharp.text.Document();\n    PdfWriter writer = PdfWriter.GetInstance(document, stream);	0
11905356	11905285	Get contents of a file in a folder inside project?	using System.IO;\n...\n\nstring folderPath = AppDomain.CurrentDomain.BaseDirectory; // or whatever folder you want to load..\n\nforeach (string file in Directory.EnumerateFiles(folderPath, "*.html"))\n{\n    string contents = File.ReadAllText(file);\n}	0
11024024	11023834	Loop within a date range for each month and each day	var dt2 = Calendar2.SelectedDate.Year;\nvar current = Calendar1.SelectedDate;\nwhile (current < dt2)\n{\n  current = current.AddMonths(1);\n  //do your work for each month here\n}	0
24426712	24419102	Clearly stating assemblies for auto-registration	typeof(global::Company.Product.BusinessLayer.ICommandHandler<>).Assembly	0
5265146	5265109	how do you set the innerhtml on a generic control (div) in c# code behind?	HtmlGenericControl divControl = new HtmlGenericControl("div");	0
9471978	9471556	How to correctly instance EF Object Data Context using DI with Castle?	container.Register(\n    .Component.For<ObjectDataContext>()\n    .DependsOn(\n        Dependency.OnValue(\n            "connectionString", ConnectionString("EntityFramework")))\n    .LifeStyle.PerWebRequest);	0
25251418	21941387	Process.Start to open multiple web pages	void ReportingClick(object sender, EventArgs e)\n{\n    System.Diagnostics.Process.Start("http://www.google.ca");\n    System.Threading.Thread.Sleep(1000);\n    System.Diagnostics.Process.Start("http://www.gmail.com");\n    System.Threading.Thread.Sleep(1000);\n    System.Diagnostics.Process.Start("http://www.stackoverflow.com");\n}	0
3426842	1198962	Merge two JSON objects programmatically	function MergeJSON (o, ob) {\n      for (var z in ob) {\n           o[z] = ob[z];\n      }\n      return o;\n}	0
15019327	15017933	Reading numbers, alphabets and special characters from text file one character at a time in c#	private static void parseFile(string fileName)\n{\n    string content = File.ReadAllText(fileName, Encoding.UTF8);\n    foreach (char character in content)\n    {\n        if (character >= 'A' && character <= 'Z')\n        {\n            // handle A-Z\n        }\n        else if (character >= 'a' && character <= 'z')\n        {\n            // handle a-z\n        }\n        else if (character >= '0' && character <= '9')\n        {\n            // handle 0-9\n        }\n        else\n        {\n            // handle everything else\n        }\n    }\n}	0
14287381	14282801	How to use ServiceStack MVC library without the default.htm page	SetConfig(new EndpointHostConfig {DefaultRedirectPath = "/Foo" });	0
21671830	21671636	Send Multiple Documents To Printer	var filenames = Directory.EnumerateFiles(@"c:\targetImagePath", "*.*", SearchOption.AllDirectories)\n                        .Where(s => s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".bmp"));\nforeach (var filename in filenames)\n{\n    //use filename\n}	0
14971460	14971211	Is there any way to override a MVC Controller Action?	public class MyController : Controller \n{\n    private OldController old = new OldController();\n\n    // OldController method we want to "override"\n    public ActionResult Product(int productid)\n    {\n        ...\n        return View(...);\n    }\n\n    // Other OldController method for which we want the "inherited" behavior\n    public ActionResult Method1(...)\n    {\n        return old.Method1(...);\n    }\n}	0
17434658	17434519	How to read from a file using C# code?	string line;\nList<double> values = new List<double>();\nstring path = Path.Combine(Application.StartupPath, "City.txt");\n\nSystem.IO.StreamReader file = new System.IO.StreamReader(path);\nwhile((line = file.ReadLine()) != null)\n{\n    values.Add(double.Parse(line));\n}\n\nfile.Close();	0
29002505	28963403	how to serialize a long string and maintain the formatting?	string.Join("<br/>", System.Text.RegularExpressions.Regex.Split(createCommentJson, @"(?:\\r\\n|\\n|\\r)"));	0
34050711	34050450	C# Get a List or array of id's after saving multiple objects to the database	dataObjectList.Select((o) => o.ID).ToList();	0
20828355	20828315	ViewModel ends up being a copy of Model - where is the benefit?	Mapper.CreateMap<Item, ItemDetailViewModel>();	0
22278482	22278012	C# SQL - new login sees all databases	Try This\n\n    CREATE DATABASE Devcom2;\n    GO\n    USE Devcom2;\n    GO\n    CREATE SCHEMA Devcom2;\n    GO\n    CREATE LOGIN Devcom2 WITH PASSWORD = '1234852';\n    EXEC sp_defaultdb @loginame='Devcom2', @defdb='Devcom2'\n    CREATE USER Devcom2 For LOGIN Devcom2 WITH DEFAULT_SCHEMA = Devcom2\n    EXEC sp_addrolemember 'db_owner','Devcom2'\n    GO\n\n\nhttp://www.sqlteachers.com/entries/2014-Creating-a-Database-and-Assigning-a-user-to-it	0
7687708	7645174	Add custom link to SharePoint list settings page by code	SPUserCustomAction customAction = spCustomList.UserCustomActions.Add();\ncustomAction.Url = "someurlhere";\ncustomAction.Name = "CustomName";\ncustomAction.Location = "Microsoft.SharePoint.ListEdit";\ncustomAction.Group = "GeneralSettings";\ncustomAction.Title = "Custom Settings";\ncustomAction.Update();	0
4237075	4237061	Connect to Sharepoint site using specific username/Password through WinForm App	var cc = new CredentialCache();\ncc.Add(\n    new Uri(sourceSite.Url), \n    "NTLM", \n    new NetworkCredential("user", "password"));\nsourceSite.Credentials = cc;	0
7461095	7461080	Fastest way to check if string contains only digits	bool IsDigitsOnly(string str)\n{\n    foreach (char c in str)\n    {\n        if (c < '0' || c > '9')\n            return false;\n    }\n\n    return true;\n}	0
3513409	3510586	Algorithm to calculate the number of combinations to form 100	def combinations(n: Int, step: Int, distance: Int, sum: Int = 100): List[List[Int]] =\n      if (n == 1) \n        List(List(sum))\n      else \n        for {\n          first <- (step until sum by step).toList\n          rest <- combinations(n - 1, step, distance, sum - first)\n          if rest forall (x => (first - x).abs <= distance)\n        } yield first :: rest	0
24804078	24802904	In Excel how to search a value in a column and get all the values in that row using C#	string query = @"SELECT * FROM [Sheet1$"+ (rowNumber-1) + ":" + (rowNumber) + "]";	0
7339853	7339505	How to insert a footnote into word using c#	Document doc = app.ActiveDocument;\n\nobject selStart = 12;\nobject selEnd = 14;\nobject missing = Type.Missing;\nobject footnote = "This is a footnote";\n\nRange range = doc.Range(ref selStart, ref selEnd);\ndoc.Footnotes.Add(range, ref missing, footnote);	0
6677116	6676993	Finding app config file from assembly	System.Configuration.Configuration config =\n                ConfigurationManager.OpenExeConfiguration(\n                ConfigurationUserLevel.None);\n\nstring configPath = config.FilePath;\n\nprivate static IConfigSource source = new DotNetConfigSource(configPath);	0
18302667	18302608	Is it possible to get a list of all links with a class on a webpage?	var web = new HtmlAgilityPack.HtmlWeb();\nvar doc = web.Load(url);\nvar list = doc.DocumentNode.SelectNodes("//a[@class='name notranslate']")\n               .Select(a => a.Attributes["href"].Value)\n               .ToList();	0
33116900	33116794	How to run a program and block its internet usage rights?	INetFwRule fire = (INetFwRule)Activator.CreateInstance(\n        Type.GetTypeFromProgID("HNetCfg.FWRule"));\n    fire.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;\n    fire.Description = "Block";\n    fire.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;\n    fire.Enabled = true;\n    fire.InterfaceTypes = "All";\n    fire.Name = "Block Internet";\n\n    INetFwPolicy2 firePolicy = (INetFwPolicy2)Activator.CreateInstance(\n        Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));\n    firePolicy.Rules.Add(fire);	0
1136653	1136278	How can I transfom an object graph to an external XML format	XElement results = new XElement("ExternalFoos",\n    from f in internalFoos\n    select new XElement("ExternalFoo", new XAttribute[] {\n        new XAttribute("GivenName", f.FirstName),\n        new XAttribute("FamilyName", f.LastName) } ));	0
5704287	5704198	C# foreach only get distinct values	string driverids = string.Join(",", _logsDutyStatusChange\n  .Select(item=>item.did)\n  .Distinct()\n  .ToArray());	0
23466594	23457288	How to reset User control's controls to its initial state in c#	foreach (Control ctrl in bodyPanel.Controls)\n{\n    if (ctrl.GetType().Name == "TimerUserControl")\n    {\n        TimerUserControl obj = ctrl as TimerUserControl;\n        obj.ResetControl();\n    }\n}	0
12690590	12686045	Syncfusion PDF Single Quotation automatically convert with tab space	htmlContent = htmlContent.ToString().Replace("?", "'");	0
10409462	10401622	How to override EmbeddedNavigator_ButtonClick (XtraGrid)	class MyGridControl : DevExpress.XtraGrid.GridControl {\n    public MyGridControl() {\n        EmbeddedNavigator.ButtonClick += EmbeddedNavigator_ButtonClick;\n    }\n    //...\n    void EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e) {\n    ? ? if(e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Delete) {\n        ? ? // ... your code is here\n        ? ? e.Handled = true;  // disable the default processing\n    ? ? }\n    ? ? if(e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Custom) {\n        ? ? // ... your code is here\n        ? ? e.Handled = true;  // disable the default processing\n    ? ? }\n    }\n}	0
18000924	18000796	How do I format a string?	string date = yourdateTime.ToString("dd/mm/yyyy");\nstring date = yourdateTime.ToString("dd/mm/yyyy HH:mm");\nstring date = yourdateTime.ToString("dd/mm/yyyy HH:mm:ss");\nstring date = yourdateTime.ToString("mmddyy"); // your desired	0
27996903	27996831	How to set parameter values in RDLC	DateTime dtStartDate = dateTimePicker1.Value;     \nDateTime dtEndDate = dateTimePicker2.Value;     \nReportParameter[] params = new ReportParameter[2]; \nparams[0] = new ReportParameter("StartDate", dtStartDate, false); \nparams[1] = new ReportParameter("EndDate", dtEndDate, false); \nthis.ReportViewer1.ServerReport.SetParameters(params);	0
2322175	2320840	How to detect user inactivity in my app (windows mobile, c#)	HKLM\System\GWE\ActivityEvent	0
31016735	30970450	Dapper, MS Access, Integers and "no value given for one or more required parameters"	conn.Execute( "INSERT INTO DisMember(FName, HighestGrade, Initials, LName) "\n            + "VALUES (@FName, @HighestGrade, @Initials, @LName);", dis\n            );	0
4538525	4538381	How to identify end of page is reached in pdf file using itextsharp	using (FileStream fs = File.Create("test.pdf"))\n        {\n            Document document = new Document(PageSize.A4, 72, 72, 72, 72);\n            PdfWriter writer = PdfWriter.GetInstance(document, fs);\n\n            document.Open();\n            int pageNumber = -1;\n\n            for (int i = 0; i < 20; i++)\n            {\n                if (pageNumber != writer.PageNumber)\n                {\n                    // Add image\n                    pageNumber = writer.PageNumber;\n                }\n\n                // Add something else\n            }\n\n            document.Close();\n        }	0
30932564	30932464	startIndex cannot be larger than length of string	string newFilenameExtension = Path.GetExtension("Sample".Trim());\nstring extn = string.Empty;\n\nif (!String.IsNullOrWhiteSpace(newFilenameExtension))\n{\n      extn = newFilenameExtension.Substring(1);\n}\n\nif(!String.IsNullOrWhiteSpace(extn))\n{\n      // Use extn here\n}	0
18705115	18704240	Part of my project started using incorrect connection string - how do I fix that?	using ( MyServer context = new MyServer(myconfig.ConnectionStrings["MyServerName"]))\n {\n }	0
15945844	15945733	select all xml nodes which contain a certain attribute	// Note that there's an implicit conversion from string to XName,\n// but this would let you specify a namespaced version if you want.\npublic List<string> RetrieveValuesForAttribute(XName attributeName)\n{\n    // Assume document is an XDocument\n    return document.Descendants()\n                   .Attributes(attributeName)\n                   .Select(x => x.Value)\n                   .ToList();\n}	0
4012907	4012878	How can i convert the string value to date time value and assign it to DateTimePicker	DateTimePicker p = new DateTimePicker();\nDateTime result;\nif (DateTime.TryParseExact("101025", "yyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result))\n{\n    p.Value = result;\n}	0
7403715	7403518	Accessing SelfHosted WCF Services outside a domain	proxy.ChannelFactory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;	0
8615095	8607777	How to use a cookie as a property with ASP.Net (c#)	int CurrentID\n    {\n        get\n        {\n            if (Request.Cookies["CurrentID"] != null)\n            {\n                return Request.Cookies["CurrentID"].Value.AsID();\n            }\n            else\n            {\n                Response.Cookies.Add(new HttpCookie("CurrentID", "0"));\n                return 0;\n            }\n        }\n        set\n        {\n            if (Response.Cookies["CurrentID"] != null)\n            {\n                Response.Cookies.Remove("CurrentID");\n                Request.Cookies.Remove("CurrentID");\n            }\n            Response.Cookies.Add(new HttpCookie("CurrentID", value.ToString()));\n        }\n    }	0
5612422	5612394	Are there any concurrent queue types in a .NET 3rd party library?	Queue<T>	0
12924263	12923034	Storing only task id in an array	JObject jobj = JObject.Parse(serializedData);\nUInt64[] idArr = ((JArray)jobj["data"]).Select(jItem => UInt64.Parse((string)((JObject)jItem["id"]))).ToArray();	0
6981944	6981899	How to get the client IP address from the request made to webservice	Request.UserHostAddress	0
975973	975886	Using MS Office's Spellchecking feature with C#	using Word;\n\npublic void checkspelling(string text) \n{\n    Word.Application app = new Word.Application();\n    object template=Missing.Value; \n        object newTemplate=Missing.Value; \n        object documentType=Missing.Value; \n        object visible=true; \n        object optional = Missing.Value; \n\n        _Document doc = app.Documents.Add(ref template, \n           ref newTemplate, ref documentType, ref visible);\n\n        doc.Words.First.InsertBefore(text); \n        Word.ProofreadingErrors errors = doc.SpellingErrors; \n\n        ecount = errors.Count; \n        doc.CheckSpelling( ref optional, ref optional, ref optional, \n            ref optional, ref optional, ref optional, ref optional, \n            ref optional, ref optional, ref optional, ref optional, \n        ref optional);\n\n        if (ecount == 0) \n        {\n    // no errors\n    }\n        else\n    {\n    // errros\n    }\n}	0
1170650	1170586	Linq to Sql Many to Many relationships	var e = some_entity;\n\nvar cs = dc.GetChangeSet();\n\nif (cs.Inserts.Any( x => x == e))\n{\n  dc.SomeTable.DeleteOnSubmit(e);\n}\n\ndc.SubmitChanges();	0
14284542	14283528	Positioning an OpacityMask in WPF	private void SetMask(double radius)\n{\n    var maskGeometry = new EllipseGeometry(CenterPos, radius, radius);\n    var maskDrawing = new GeometryDrawing(Brushes.Black, null, maskGeometry);\n    var maskBrush = new DrawingBrush\n    {\n        Drawing = maskDrawing,\n        Stretch = Stretch.None,\n        ViewboxUnits = BrushMappingMode.Absolute,\n        AlignmentX = AlignmentX.Left,\n        AlignmentY = AlignmentY.Top\n    };\n\n    Img.OpacityMask = maskBrush;\n}	0
90131	90117	How do I use .Net Generics to inherit a template parameter?	public class ServiceProxyHelper<T> where T : MyInterface { ... }	0
19548914	19546313	IIS7 Programmatically get App Pool version in ASP.NET	Version version = Environment.Version	0
4119992	4119976	Creating a new instance of an object on button push	void ButtonClick_H1(...)\n{\n  ClassName a;          //local variable\n  a = new ClassName();  // object belongs to this method\n}\n\n\nprivate  ClassName anObject;   // class field\nvoid ButtonClick_H2(...)\n{ \n  anObject = new ClassName();  // object belongs to  'this' Form\n}	0
21903834	21776450	Setting active a Chrome window (C++)	//Getting the HWND of Chrome\nHWND chromeWindow = FindWindow("Chrome_WidgetWin_1", NULL);\nHWND chrome = GetWindow(chromeWindow, GW_HWNDNEXT);\n\n//Setting the window to the foreground (implies focus and activating)\nSetForegroundWindow(chrome);	0
8495128	8495005	parsing int when doing json deserialization	int value;\n if (int.TryParse(serializer.ConvertToType<string>(dictionary["TheInt"]), out value)\n {\n    MyObject.TheInt = value;\n }	0
12143545	12143484	How do I save the last folder selected by the user?	Properties.Settings.Default.Reload();	0
7480793	7476079	Reactive extension method to convert a hot observable interval to a cold observable	ReplaySubject<int> sub = new ReplaySubject<int>();\nhotObservable.Subscribe(sub);\n//Now any one can subscribe to sub and it will get all items that hot observable sent to replay subject	0
9332111	9332058	How to know the central time in .NET	var CSTNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,\n        TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));\nif(CSTNow.TimeOfDay >= new TimeSpan(8,0,0)  && CSTNow.TimeOfDay < new TimeSpan(17,0,0))\n{\n/* Do something */\n}	0
8975825	8975698	Implementing custom IComparer with string	var example = new string[]{"c", "a", "d", "b"};\nvar comparer = new CustomStringComparer(StringComparer.CurrentCulture);\nArray.Sort(example, comparer);\n\n...\n\nclass CustomStringComparer : IComparer<string>\n{\n    private readonly IComparer<string> _baseComparer;\n    public CustomStringComparer(IComparer<string> baseComparer)\n    {\n        _baseComparer = baseComparer;\n    }\n\n    public int Compare(string x, string y)\n    {\n        if (_baseComparer.Compare(x, y) == 0)\n            return 0;\n\n        // "b" comes before everything else\n        if (_baseComparer.Compare(x, "b") == 0)\n            return -1;\n        if (_baseComparer.Compare(y, "b") == 0)\n            return 1;\n\n        // "c" comes next\n        if (_baseComparer.Compare(x, "c") == 0)\n            return -1;\n        if (_baseComparer.Compare(y, "c") == 0)\n            return 1;\n\n        return _baseComparer.Compare(x, y);\n    }\n}	0
13560962	13556985	SQLDataSource FilterExpressions: how get data with just similar values, not equal?	SqlDataSource1.FilterExpression = "Address like '%" + TextBox16.Text + "%'";	0
21006731	21006644	get Classes and Methods from another Assembly	foreach(var asm in loadedAssemblies)\n{\n   var classes = asm.GetTypes(); // you can use GetTypes to get all classes in that assembly\n   foreach(var c in classes)\n   {\n      // you can get all methods which is defined in this class with GetMethods\n      var methods = c.GetMethods();\n\n      // or you can get all properties defined in this class\n      var props = c.GetProperties();\n   }\n}	0
14863867	14858095	Multiple LINQ to SQL insert using IDENTITY from previous insert	using (var sms = new SmsDataDataContext(connection_string)\n {\n    foreach(SomeObject i in ListofObject)\n    {\n      TABLE1 t1 = CheckID(sms, i.ID);\n\n      if (t1== null)\n      {\n         TABLE1 new_row = new TABLE1();\n         sms.TABLE1.InsertOnSubmit(new_row);\n\n         TABLE2 update_row = new TABLE2();\n         new_row.Table2s.Add(update_row);\n\n      }\n    }\n    sms.SubmitChanges();\n  }	0
13919648	13919582	An Update statement in a loop	delete from question\n   where id = 2;\n\nwith new_order as (\n   select row_number() over (partition by survey_id order by question_no) as new_question_no,\n          question_no as old_question_no, \n          id\n   from question\n) \nupdate question \n  set question_no = nq.new_question_no\nfrom new_order nq\nwhere nq.id = question.id\n  and survey_id = 44;\n\ncommit;	0
13122366	13011417	How to display xml file in a web browser?	writer.WriteStartElement("table");\n    createNode("1","Product 1","1000",writer);\n    createNode("2", "Product 2", "2000", writer);\n    createNode("3", "Product 3", "3000", writer);\n    createNode("4", "Product 4", "4000", writer);\n    writer.WriteEndElement();\n    writer.WriteEndDocument();\n    writer.Close();\n    Response.ContentType = "text/xml";\n    Response.End();                            --------did you remember that part?	0
23779329	23779203	Prevent auto change row on enter key pressed in DataGrid	//base.OnPreviewKeyDown(e);\ne.Handled = true;	0
26392573	26392287	Dynamic Linq queries with sorting, nulls at end	class NullsAtEndComparer<T> : IComparer<T> where T : class\n{\n    private static readonly IComparer<T> _baseComparer = Comparer<T>.Default;\n\n    private readonly bool _ascending;\n\n    public NullsAtEndComparer(bool ascending = true)\n    {\n        _ascending = ascending;\n    }\n\n    public int Compare(T t1, T t2)\n    {\n        if (object.ReferenceEquals(t1, t2))\n        {\n            return 0;\n        }\n\n        if (t1 == null)\n        {\n            return 1;\n        }\n\n        if (t2 == null)\n        {\n            return -1;\n        }\n\n        return _ascending ? _baseComparer.Compare(t1, t2) : _baseComparer.Compare(t2, t1);\n    }\n}	0
15596926	15596887	How to create table in microsoft access with dynamic name in C#?	string tableName = "[" + fName + " " + lName + "]";	0
8861812	8785753	Find the largest polygon as it is completed	public Stack<SomePixelType> GetPolygonEdges(SomePixelType justSetPixel)\n{\n    visitedPixels.Clear();\n\n    if(!justSetPixel.IsPossiblePolygon)\n        return null; // Not a possible edge. No closed polygon could of been completed.\n\n    visitedPixels.Push(justSetPixel);\n\n    SomePixelType currentPixel = justSetPixel;\n    while(visitedPixels.Count > 0)\n    {\n        currentPixel  = currentPixel.GetNextPixel();\n        if(currentPixel == null) // No possible neighbouring polygon edges.\n        {\n            currentPixel = visitedPixels.Pop(); // Backtrack\n            continue;\n        }\n        if(currentPixel == justSetPixel)\n            return visitedPixels;\n\n        visitedPixels.Push(currentPixel);\n    }\n    return null; // Not closed.\n}	0
1446800	1446670	Converting from DbCommand object to OracleCommand object	string result = String.Empty;\nOracleConnection conn = new OracleConnection(connstr);\nOracleCommand cmd = new OracleCommand("PKG_AUCTION_ITEMS.IsAuctionItem",conn);\nmyCmd.CommandType = CommandType.StoredProcedure;\n\nusing (myCmd)\n{\n    myCmd.Parameters.AddWithValue("vItemName", itemName);\n    myCmd.Parameters.AddWithValue("vOpenDate", openDate);\n\n    // depending on whether you're using Microsoft's or Oracle's ODP, you \n    // may need to use OracleType.Varchar instead of OracleDbType.Varchar2.\n    // See http://forums.asp.net/t/1002097.aspx for more details.\n    OracleParameter retval = new OracleParameter("ret",OracleDbType.Varchar2,2);\n    retval.Direction = ParameterDirection.ReturnValue;\n    myCmd.Parameters.Add(retval);\n\n    myCmd.ExecuteNonQuery();\n    result = myCmd.Parameters["ret"].Value.ToString();\n}	0
13694540	13694486	Finding the index of a blank line within a string	string s = "safsadfd\r\ndfgfdg\r\n\r\ndfgfgg";\nstring[] lines = s.Split('\n');\nint i;\nfor (i = 0; i < lines.Length; i++)\n{\n    if (string.IsNullOrWhiteSpace(lines[i]))     \n    //if (lines[i].Length == 0)          //or maybe this suits better..\n    //if (lines[i].Equals(string.Empty)) //or this\n    {\n        Console.WriteLine(i);\n        break;\n    }\n}\nConsole.WriteLine(string.Join("\n",lines.Take(i)));	0
290269	290238	Is there a way to load a class file to assembly in runtime?	CodeDomProvider codeProvider = new CSharpCodeProvider();\nICodeCompiler compiler = codeProvider.CreateCompiler();\n\n// add compiler parameters\nCompilerParameters compilerParams = new CompilerParameters();\ncompilerParams.CompilerOptions = "/target:library /optimize";\ncompilerParams.GenerateExecutable = false;\ncompilerParams.GenerateInMemory = true; \ncompilerParams.IncludeDebugInformation = false;\ncompilerParams.ReferencedAssemblies.Add("mscorlib.dll");\ncompilerParams.ReferencedAssemblies.Add("System.dll");\n\n// compile the code\nCompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sourceCode);	0
2455598	2455501	How To Disable Subsonic's Primary Key Autoincrement?	if(column.IsPrimaryKey)\n        {\n            sb.Append(" NOT NULL PRIMARY KEY");\n            if(column.IsNumeric)\n                sb.Append(" AUTOINCREMENT ");\n        }	0
26625347	26625284	Web api GET (all) with optional parameters from SQL Server	from r in db.requests\nwhere r.status == status || status == ""\nselect new Models.Request	0
17114285	17114167	How to access a user selected item from a dropdown list that is within a fieldset and a content template in asp.net using c#	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var item =((DropDownList)sender).SelectedItem;\n}	0
17582217	17558125	How to get actual objects from C# Web API DbSet?	public static IEnumerable<Donut> GetDonutsSince(DateTime dt) {\n    HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") };\n    api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));\n\n    String url = "Donut/since?datetime=" + dt;\n    HttpResponseMessage response = api.GetAsync(url).Result;\n    String responseContent = response.Content.ReadAsStringAsync().Result;\n\n    IEnumerable<Donut> events = JsonConvert.DeserializeObject<IEnumerable<Donut>>(responseContent);\n\n    return donuts;\n}	0
651601	651592	How to display an error message box in a web application asp.net c#	try\n {\n     ....\n }\n catch (Exception ex)\n {\n     this.Session["exceptionMessage"] = ex.Message;\n     Response.Redirect( "ErrorDisplay.aspx" );\n     log.Write( ex.Message  + ex.StackTrace );\n }	0
9795592	9794160	ajax jquery post, needs some fine tuning for a beginner	url: "UserDAO.aspx/queryInvitedBy",	0
28214285	28214031	Use Autofac to inject a list of specified keyed/named items into component	builder.RegisterType<Component>().WithParameters(new[] {\n                        new ResolvedParameter((p,c) => p.Name == "serv",(p,c) => \n                            new List<ITerry>\n                            {\n                                c.ResolveKeyed<IService>(Services.Svc1),\n                                c.ResolveKeyed<IService>(Services.Svc3),\n                                c.ResolveKeyed<IService>(Services.Svc8),\n                            })\n            });	0
8624872	8624854	Check number of pairs in KeyValuePair list	int numberOfEntries = filelist.Count;	0
30747570	30747296	Using Switch for Simple Unity3D Patrol Movement	float someSmallValue = 0.5f; // Adjust this as per your needs\n\n    if (Vector3.Distance(transform.position, patrolPoints[currentPoint].position) < someSmallValue)\n    {\n        switch (moveType)\n        {\n            case MoveType.Forward:\n                currentPoint++;\n                if (currentPoint > patrolPoints.Length - 1)\n                {\n                    currentPoint -= 1;\n                    moveType = MoveType.Backwards;\n                }\n            break;\n\n            case MoveType.Backwards:\n                currentPoint--;\n                if (currentPoint < 0)\n                {\n                    currentPoint = 1;\n                    moveType = MoveType.Forward;\n                }\n            break;\n        }\n\n    }	0
17075043	17074916	Why is CodeContracts recommending a null check in a foreach loop	foreach (UIElement uiElement in list.Where(e => e != null))\n{\n   uiElement.SetValue(Grid.ColumnProperty, colunmn++);\n   uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count -1);\n   _uiRoot.Children.Add(uiElement);\n}	0
26251974	26251757	Bulk insert with EF	using(var db = new DBModelContainer())\n    {\n       db.tblMyTable.MergeOption = MergeOption.NoTracking;\n       // Narrow the scope of your db context\n       db.AddTottblMyTable (item);\n       db.SaveChanges();\n    }	0
14098215	14091266	using StreamReader to read XElement leaves open elements	StreamWriter.Flush()	0
7659304	7369688	How to register a client script resource at the bottom of webpage to enhance loading time	script.js	0
23083911	23075905	Building XML from CSV file (ASP.NET)	void Main()\n{\n     StringBuilder sb = new StringBuilder();\n     sb.Append("<Example>");\n\n    foreach(var line in File.ReadAllLines(@"c:\foo\line.csv"))\n    {\n      var row = line.Split(',');\n      if(row.Length>=3)\n      {\n        sb.Append("<Info>");\n        sb.Append("<Name>"+row[0]+"</Name>");\n        sb.Append("<Address>"+row[1]+"</Address>");\n        sb.Append("<Email>"+row[2]+"</Email>");\n        sb.Append("</Info>");\n      }\n      else//assume blank row. Break out of loop\n         break;\n   }\n   sb.Append("</Example>"); \n\n   //sb.ToString() has the piece of XML you want.\n}	0
7971093	7970998	Convert to DateTime object	string myDateTimeString = "2011-09-20_104627";\nDateTime myDateTimeObject;\nDateTime.TryParseExact(myDateTimeString,\n                       "yyyy-MM-dd_HHmmss",\n                       CultureInfo.InvariantCulture,\n                       DateTimeStyles.None,\n                       out myDateTimeObject);	0
20216671	20216272	save data in session one by one and save them altogether in database	[HttpPost]\npublic JsonResult SaveSubjectInfo(PreviousExamSubject previousExamSubject)\n{\n    List<PreviousExamSubject> list= (List<PreviousExamSubject>) Session["myitem"] ?? new List<PreviousExamSubject>();\n    list.Add(previousExamSubject);\n    Session["myitem"] = list;\n    return Json(JsonRequestBehavior.AllowGet);\n}	0
21509066	21381885	How do I select multiple grandchildren in linq?	EventPageDataModel dataModel = DataContext.Events\n            .Include(i => i.Categories)\n            .Include(i => i.Dates)\n            .Include(i => i.Dates.Select(d => d.EventDateDelegates))\n            .Include(i => i.Dates.Select(d => d.EventDateDelegates.Select(edd => edd.User)))\n            .Include(i => i.Dates.Select(d => d.Venue))\n            .FirstOrDefault(i => i.URL == url);	0
25926283	25926215	Read an XML file and show nodes in a combobox	List<String> nameList = new List<String>();\n            var NAME= XElement.Parse(xml);\n\n           if (NAME.Attribute("Name") != null)\n        {\n            nameList.Add(NAME.Attribute("Name").Value);\n        }	0
13768901	13768426	Loop through self referenting list to add in treeview	private List<Employees> employees;\nprivate void treew(TreeNode root, int? managerID)\n{\n    foreach (Employees option in employ.Where(x => x.MangerID == managerID))\n    {\n        TreeNode nodeOutput;\n        treew(nodeOutput, option.ID);\n        root.Nodes.Add(nodeOutput);\n    }\n}	0
3164642	3164619	Get unique filename in a multithreaded application	string.Format("file_{0}_{1:N}.xml", DateTime.Now.Ticks, Guid.NewGuid())	0
27448102	27447976	InitializeAsync in MediaCapture doesnt work	public async Task Foo()\n{\n    //code\n    try\n        {\n            MediaCapture mc = new MediaCapture();\n            await mc.InitializeAsync();\n\n            if (mc.VideoDeviceController.TorchControl.Supported == true)\n            {\n                mc.VideoDeviceController.TorchControl.Enabled = true;\n                if (mc.VideoDeviceController.TorchControl.PowerSupported == true)\n                {\n                    mc.VideoDeviceController.TorchControl.PowerPercent = 100;\n                }\n            }\n        }\n        catch(Exception ex)\n        {\n            //TODO: Report exception to user\n        }\n\n}	0
280425	280413	How do you find the caller function?	Console.WriteLine(new StackFrame(1).GetMethod().Name);	0
7470084	7470006	Regex to find numbers and parenthesize them in a passage	var data = "Lorem ipsum dolor sit amet 1, consectetur adipiscing elit. Sed mollis 2. Varius enim in tempor. Vivamus vel rutrum lacus. Donec quis ullamcorper purus. Nullam blandit tincidunt mattis. Nunc imperdiet nunc vel dolor 3 - dignissim semper. Cras blandit laoreet nisl sit amet faucibus. Sed porta, nisl ut molestie ultrices, libero metus scelerisque nibh, non imperdiet lectus sapien a lorem. Sed elementum 10 adipiscing erat, eget consectetur massa ultrices eget. Integer leo est, faucibus eu 24interdum eget, auctor bibendum ligula. Quisque luctus lectus vitae leo semper gravida. Cras et pulvinar leo. Nulla tristique98 ipsum ac urna luctus molestie.";\n        var newData = Regex.Replace(data, @"(\d+)", "($1)");\n        Console.WriteLine(newData);	0
2046743	2046674	Keeping a sorted list of elements, sorted by an attribute external to that element	List<T>	0
7485123	7484643	Deserialize classes with the same name from different assemblies	[XmlType(Namespace = "http://OurWebApp.eProc.com")]\npublic class Address { }	0
7354260	7354179	getting the full name of an assembly	sn -T path\to\your.dll	0
4898313	4898210	The Click event on a PictureBox is firing but no action is performed	private void pictureBox1_Click(object sender, EventArgs e)\n{\n\n    if (flagarrow == false)\n    {\n        flagarrow = true;\n    }\n    else\n    {\n        flagarrow = false;\n    }\n\n    pictureBox1.Invalidate();\n}	0
23077783	23071748	how to retrieve data from many to many relationship from the controller in the details action method and put the data in view details mvc 4	public ActionResult Details(int id = 0)\n    {\n\n        UsersInRoles usersinroles = db.UsersInRoles.Include(u => u.UserProfile).Include(r => r.Role).Where(i => i.UsersInRolesID == id).SingleOrDefault();\n        if (usersinroles == null)\n        {\n            return HttpNotFound();\n        }\n        return View(usersinroles);\n    }	0
22497867	22497702	How can I set the font colour?	graphicsImage.DrawString(textBox1.Text, new Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new Point(10, 210));	0
4467746	4302137	How can I convince Internet Explorer to allow authentication as another user?	using System.DirectoryServices.AccountManagement;\n\nprivate static bool IsLdapAuthenticated(string username, string password)\n{\n    PrincipalContext context;\n    UserPrincipal principal;\n\n    try\n    {\n        context = new PrincipalContext(ContextType.Domain);\n        principal = Principal.FindByIdentity(context, IdentityType.SamAccountName, username) as UserPrincipal;\n    }\n    catch (Exception ex)\n    {\n        // handle server failure / user not found / etc\n    }\n\n    return context.ValidateCredentials(principal.UserPrincipalName, password);\n}	0
2557800	2557595	Console app showing message box on error	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.FileName = "someapp.exe"\nstartInfo.Arguments = "somefile.txt";\n\nProcess jobProcess = Process.Start(startInfo);\n\n//wait for the process to potentially finish...if it generally takes a minute to end, wait a minute and a half, etc\nSystem.Threading.Thread.Sleep(60 * 1000);\n\nProcess[] processes = Process.GetProcessesByName("someapp");\n\nif (processes.Length == 0)\n{\n  break; //app has finished running\n}\nelse\n{\n  Process p = processes[0];  \n  IntPtr pFoundWindow = p.MainWindowHandle;\n  SetFocus(new HandleRef(null, pFoundWindow));\n  SetForegroundWindow((int)pFoundWindow);\n  SendKeys.SendWait("{ENTER}");          \n}\n\nint exitCode = jobProcess.ExitCode;	0
2906820	2906794	Equivalent lambda syntax for linq query	var x = a.SelectMany(a1=>b.Select(b1=>new {a1,b1}));	0
16334383	16334372	Search for same substrings in a list of strings	var listWithSubstring = originalList.Where(i => i.Contains("est"));	0
3388341	3388312	Adding a column value by using DataReader	txtusername.Text = dr.GetString(0);	0
4274723	4274712	Is there a less recursive feeling way of formatting numbers?	int decimalPlaces = 2;\ndouble pi = 3.14159;\npi.ToString("N" + decimalPlaces);	0
28132003	28131935	issue looping through each value of a 2D Jagged Array "Index was outside the bounds of the array"	for (int i = 0; i < results.Length; i++)\n{\n    // Get the length of the array that is at index i\n    for (int s = 0; s < results[i].Length; s++)\n    {\n        TextboxSummary.Text += results[i][s];\n    } \n}	0
16030402	16030312	How to compare two lists and get unmatching items - without using LINQ	var temp = new List<string>();\nforeach(var item in remoteFiles){\n  if(localfiles.Contains(item) == false){\n     temp.Add(item);\n  }\n}	0
4393559	4393539	Selecting elements using LINQ-to-XML	using System.Linq;	0
34345276	34345120	Difference in days between two dates in C# - returns integer	var a = new TimeSpan(5, 14, 0, 0);  // 5 days, 14 hours\n    var x = a.Days;  // Does not round up. = 5 \n    var y = (int) Math.Round(a.TotalDays);  // Rounds up. = 6	0
6715133	6715011	Dynamically creating/loading a user control only works once!	protected void addMoreDay_btn_Click(object sender, EventArgs e)\n{\n    Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");\n    Days_div.Controls.Add(OneMoreDay);\n    Session["MyControl"] += 1\n}\n\n\nprotected void Page_Init(object sender, EventArgs e)\n{\n    for (int i = 1; i <= (int)Session["MyControl"]; i++) {\n        Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");\n        Days_div.Controls.Add(OneMoreDay);        \n    }\n}	0
12848364	12848152	Asp.net redirect from login to main page	RedirectURL = Page.ResolveUrl("~/Main.aspx")	0
32783268	32782690	How to update only one row from inserted	public class Device\n{\n    public List<Feature> Features { get; set; }\n    public Feature PrimaryFeature { get; set; }\n    // ...\n}\n\npublic class Feature \n{ \n    public int Id { get; set; }\n    public int DeviceId { get; set; }\n    public string Value { get; set; }\n}	0
3479314	3479284	How can i format decimal property to currency	private decimal _amount;\n\npublic string FormattedAmount\n{\n    get { return string.Format("{0:C}", _amount);\n}	0
6535235	6534869	How do I add blanks for skipped elements in an xml for XmlReader?	XDocument document = XDocument.Load("file.xml");\n\nforeach (XElement item in document.Descendants("Part"))\n{\n    if (item.Element("Quantity") == null)\n         al.add(string.Empty);\n    else\n         al.add(item.Element("Quantity").value);\n\n\n}	0
12630400	12630305	How to check if string contains a string in string array	string _exists  = "Adults,Men,Women,Boys";\nstring  _check = "Men,Women,Boys,Adults,fail";\n\nbool b = _exists.Split(',').OrderBy(s=>s)\n                .SequenceEqual(_check.Split(',').OrderBy(s=>s));	0
18978791	18978689	Variable assignment within method parameter	int i;\nint j;\nint k;\n\ni = j = k = 42;	0
17033157	17032544	Exact same HTTP request results in text/html or application/json depending on server	filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;	0
16692322	16692249	How to query an embedded XML file using LINQ?	XElement doc;\nusing (var stream = typeof(SomeTypeInTheAssembly).Assembly\n                        .GetManifestResourceStream("MyXML.xml"))\n{\n    doc = XElement.Load(stream);\n}	0
1977129	1977045	How do I use a Save Dialog Box in C# to save an ASCII text file?	using (var stream = dlg.OpenFile())\nusing (var writer = new System.IO.StreamWriter(stream))\n{\n    writer.WriteLine("Success");\n}	0
11416239	11416191	How to convert MatchCollection to string array	var arr = Regex.Matches(strText, @"\b[A-Za-z-']+\b")\n    .Cast<Match>()\n    .Select(m => m.Value)\n    .ToArray();	0
3231264	3230928	import excel sheet in winform	Excel.Worksheet worksheet = new Excel.Worksheet();	0
19977643	19977337	Closing Excel application with Excel Interop without save message	object misValue = System.Reflection.Missing.Value;\nxlWorkBook.Close(false, misValue, misValue);	0
6396093	6396058	C# change string value to be next value in alphabetical order	string GetNextCode(string alphaCode)\n{\n    Debug.Assert(alphaCode.Length == 1 && Regex.IsMatch(alphaCode, "[a-yA-y]"));\n\n    var next = (char) (alphaCode[0] + 1);\n    return next.ToString();\n}	0
19109006	19108663	C# To F# loops to return a value	type Board =\n    member x.getPlayer (i: int) = 0 // Just a stub to allow typechecking\n\nlet move (cBoard: Board) =\n    let isZero x = x = 0\n    let found = seq { 0 .. 8 } |> Seq.tryFind (cBoard.getPlayer >> isZero)\n    defaultArg found 0	0
11026754	11025495	Set Windows/AD password so that it "never expires"?	int NON_EXPIRE_FLAG = 0x10000;\nval = (int) NewUser.Properties["userAccountControl"].Value;\nNewUser.Properties["userAccountControl"].Value = val | NON_EXPIRE_FLAG;\nNewUser.CommitChanges();	0
4844241	4844103	C# Chart - How to put custom labels on axes and string instead of double	myChart.ChartAreas[0].AxisX.LabelStyle.Format = "mm";\n// or other formats e.g. HH:mm etc...	0
28837289	28836591	Trying to connect to simple mdf file	DataContext db = new DataContext(@"Data Source=(localdb)\v11.0;\n                                   Integrated Security=true;\n                                   AttachDbFileName=C:\DATA\NORTHWND.MDF");	0
5464960	5120937	C# VSTO Outlook 2003 GetExchangeUser	this.Application.GetNamespace("MAPI").AddressLists["Global Address List"].AddressEntries["USER NAME"].Details(0);	0
30060891	30042255	ASP.NET web API related table data	context.Database.BeginTransaction	0
25442794	25421128	Separate string from dat file	using (Stream stream = File.Open(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n                using (StreamReader sr = new StreamReader(stream))\n                {\n                    char[] buffer = new char[500];\n                    int readBytes = sr.ReadBlock(buffer, 0, 59);\n                }	0
5962497	5955332	Invite users to register at my site through Facebook	fb:request-form	0
12425083	12425060	Getting Keys and Values from IEnumerable<Dictionary<string, object>>	IEnumerable<object> values = testData.SelectMany(x => x.Values);	0
14779970	14768052	C# Xml Deserialize plus design suggestions	private string policyName;\n[XmlAttribute("Type")]\npublic string Type\n{\n    private get\n    {\n        return this.policyType;\n    }\n    set\n    {\n        this.policyType = value;\n        try\n        {\n            this.PolicyType = (PolicyTypes)Enum.Parse(typeof(PolicyTypes), this.policyType);\n        }\n        catch(Exception)\n        {\n            this.PolicyType = PolicyTypes.DefaultPolicy;\n        }\n    }\n}\n\npublic PolicyTypes PolicyType\n{\n    get;\n    private set;\n}	0
11884165	11883312	NHibernate Query help, query a child collection's child value	var persons = (from person in session.Query<Person>()\n               from country in person.Countires\n               from state in country.States\n               where state.ID == 2\n               select person).ToList()	0
12213541	12213439	Creating sub items in solution explorer	Group Items	0
1494088	1494055	FluentNHibernate Lookup Table	HasManyToMany(x => x.Accessories)\n .Table("AccessoryProduct")\n .ParentKeyColumn("ParentProductID")\n .ChildKeyColumn("ChildProductID")\n .Cascade.None()\n .Inverse()\n .LazyLoad();	0
4424698	4421171	C# - Parsing XSD schema - get all elements to combobox	string xml = <your xml>;\nvar xs = XNamespace.Get("http://www.w3.org/2001/XMLSchema");\nvar doc = XDocument.Parse(xml);\n// if you have a file: var doc = XDocument.Load(<path to xml file>)\nforeach(var element in doc.Descendants(xs + "element"))\n{\n    Console.WriteLine(element.Attribute("name").Value);\n}\n// outputs: \n// auto\n// znacka\n// pocetOsob\n// maxRychlost\n// motor\n// vykon	0
19824103	19823867	c# json array response from http get garbled	string sURL = "http://api.planets.nu/games/list?limit=1";\n HttpWebRequest wrGetURL = (HttpWebRequest)WebRequest.Create(sURL);\n wrGetURL.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\n StreamReader objReader = new StreamReader(wrGetURL.GetResponse().GetResponseStream(), Encoding.UTF8);\n string sLine;\n sLine = objReader.ReadToEnd();\n Console.WriteLine(sLine);	0
20148965	20148740	Running parts of my application on a different CPU priority	using (Process p = Process.GetCurrentProcess())\n  p.PriorityClass = ProcessPriorityClass.High;\n\nenum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest }	0
2646338	2645587	Mdi Children Changed in .Net	public void AddChild(Form child) {\n  child.MdiParent = this;\n  child.FormClosed += child_FormClosed;\n  // Run your code to handle new child windows here...\n}\nprivate void child_FormClosed(object sender, FormClosedEventArgs e) {\n  // Your code to handle closed child windows here...\n}	0
3265412	3263380	Image is Clickable, without no hyperlink case surrounded	ui_BirthPlaceImage.Disabled = true;	0
23019403	23019266	Using ValueConverter in Style DataTrigger of ItemsControl but List is Empty	{Binding RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}, AncestorLevel=2}, Converter={StaticResource IsLastItemInContainerConverter}}	0
10204416	10195802	How to pass resolved instances from Inversion of Control to classes in application?	private ILoggerFactory _loggerFactory = LoggerFactory.NullLoggerFactory;\n\npublic ILoggerFactory LoggerFactory\n{\n    get { return _loggerFactory; }\n    set { _loggerFactory = value; }\n}	0
6119994	6119970	Set WPF Datagrid column as a Combobox itemsource	comboBox1.ItemsSource = dataGrid1.ItemsSource;\n        comboBox1.DisplayMemberPath = "ColumnName";	0
1751751	1751577	Proper way to scan a range of IP addresses	public bool\n   Ping (string host, int attempts, int timeout)\n   {\n      System.Net.NetworkInformation.Ping  ping = \n                                       new System.Net.NetworkInformation.Ping ();\n\n      System.Net.NetworkInformation.PingReply  pingReply;\n\n      for (int i = 0; i < attempts; i++)\n      {\n         try\n         {\n            pingReply = ping.Send (host, timeout); \n\n            // If there is a successful ping then return true.\n            if (pingReply != null &&\n                pingReply.Status == System.Net.NetworkInformation.IPStatus.Success)\n               return true;\n         }\n         catch\n         {\n            // Do nothing and let it try again until the attempts are exausted.\n            // Exceptions are thrown for normal ping failurs like address lookup\n            // failed.  For this reason we are supressing errors.\n         }\n      }\n\n      // Return false if we can't successfully ping the server after several attempts.\n      return false;\n   }	0
11377355	11377205	Grouping words according to their lengths c#	//string[] words = new string[] { "as", "asdf", "asdf", "asdfsafasd" };\n//string[] words = "as asdf asdf asdfsafasd".Split(' ');\n\nvar groups = "as asdf asdf asdfsafasd".Split(' ').GroupBy(x => x.Length);\n\nforeach (var lengthgroup in groups)\n{\n    foreach (var word in lengthgroup)\n    {\n        Console.WriteLine(word.Length + " : " + word);\n    }\n}	0
26910516	26909831	Access Current Page from a Block's Controller	public class MyBlockController : BlockController<MyBlock>\n{\n    private readonly PageRouteHelper _pageRouteHelper;\n\n    public override ActionResult Index(MyBlock currentContent)\n    {\n        Guid hostingPageId = _pageRouteHelper.Page.PageGuid;\n    }\n}	0
31449500	31449248	How to refrence a model from a dll file in MVC5	namespace YourProject.Controllers\n{\n    public class HomeController : Controller\n    {\n\n        #region Actions\n        public ActionResult Index()\n        {\n            try\n            {\n              NameofYourdll.ClassName tVar = new NameofYourdll.ClassName();\n             tVar.Create();\n                return View();\n            }\n            catch (Exception ex)\n            {\n               throw;\n            }\n        }\n        #endregion\n}}	0
17812236	17803409	How Can Execute Javascript Commands via GeckoFX	GeckoWebBrowser browser = ....;\n\nusing (AutoJSContext context = new AutoJSContext(browser.JSContext))\n{                               \n   string result;\n   context.EvaluateScript("3 + 2;", out result)\n}	0
5588709	5587279	C# application with C DLL crash at first access to DLL	IESHIMS.DLL	0
2681712	2681700	How to create a constructor of a class that return a collection of instances of that class?	public sealed class Subscriber\n{\n    // other constructors ...\n\n    // this constructor is not visible from outside.\n    private Subscriber(DataContext dc, int id)\n    {\n       // this line should probably be in another method for reusability.\n       this.subscription = dc._GetSubscription(id).SingleOrDefault();                \n    }\n\n    public List<Subscriber> CreateSubscribers(IEnumerable<int> ids)\n    {\n        using (DataContext dc = new DataContext())\n        {\n\n           return ids\n             .Select(x => new Subscriber(dc, x))\n             // create a list to force execution of above constructor\n             // while in the using block.\n             .ToList();\n        }            \n\n    }\n\n}	0
18214045	18213784	Factory or DI suitable for inheritance	public class QuoteFactory : IQuoteFactory\n{\n    public TQuote CreateQuote<TQuote>()\n        where TQuote : new() // or Quote if specific attributes requied to be set by factory\n    {\n        return new TQuote();\n    }\n}	0
1557079	1557010	How to determine the latest version number of a GAC assembly	Assembly a = Assembly.LoadWithPartialName ("foo.dll");\nreturn a.GetName ().Version	0
20916097	20916085	Checking Button Property Values - BackgroundImage	if (button1.BackgroundImage == null || button1.BackgroundImage.Width == 0)  // Error on this line\n{\n    button1.BackgroundImage = Properties.Resources.SubmitButton; // Works fine if put out of conditon\n}\nelse\n{\n    button1.BackgroundImage = null;\n}	0
19788488	19713263	Removing dangling CR in a file using C#	str.Replace("\r", "").Replace("\n", "\r\n")	0
32687898	32649755	Adding a TestCase to a SubSuite (ITestSuiteBase)	IStaticTestSuite staticTestSuite = SelectedSubSuit as IStaticTestSuite;\nstaticTestSuite.Entries.Add(sourceTestCase);\nthis.Plan.Save();	0
34221433	34205649	C# Creating Zip with multiple Word Docs inside	using (var ms = new MemoryStream())\n            {\n                using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))\n                {\n                    foreach (var attachment in byteList)\n                    {\n                        var entry = zipArchive.CreateEntry(attachment.Key);\n\n                        using (var originalFile = new MemoryStream(attachment.Value))\n                        {\n                            using (var zipEntryStream = entry.Open())\n                            {\n                                originalFile.CopyTo(zipEntryStream);\n                            }\n                        }\n                    }\n                }\n\n                Response.ContentType = "application/zip";\n                Response.AddHeader("Content-Disposition", "attachment;filename=" + "Reports.zip");\n                ms.Seek(0, SeekOrigin.Begin);\n                ms.CopyTo(Response.OutputStream);\n                Response.End();	0
600989	600971	Inserting rows into a database in ASP.NET	SqlConnection conn = new SqlConnection(connString);\nSqlCommand cmnd = new SqlCommand("Insert Into Table (P1, P2) Values (@P1, @P2)", conn);\ncmnd.Parameters.AddWithValue("@P1", P1Value);\ncmnd.Parameters.AddWithValue("@P2", P2Value);\ncmnd.ExecuteNonQuery();\nconn.Close();	0
16421333	16421172	Similar code in C# for a code in C++	string s = nChkSum.ToString("X3");	0
23037141	23037093	Read current line	if (e.KeyChar == (char)Keys.Enter)\n{\n     richTextBox1.AppendText("\t");\n\n      // Edited After Comment\n     var PrevLine = richTextBox2.Lines[richTextBox2.Lines.Count() - 1].ToString();\n     var TabsCount = System.Text.RegularExpressions.Regex.Matches(PrevLine, "\t").Count;\n}	0
33061561	33061547	Concatenate Property of a object in Collection.	string a = string.Join(";", Items.Select(item => item.Color));	0
22371006	22370777	OnNavigateTo change date/time picker value- windows phone	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n    {\n        base.OnNavigatedTo(e);\n  if(e.NavigationMode!=NavigationMode.Back)\n    {\n        if (NavigationContext.QueryString.ContainsKey("Id"))\n        {\n            Id.Text = NavigationContext.QueryString["Id"];\n\n        }\n        ScheduledAction currentReminder = ScheduledActionService.Find(NavigationContext.QueryString["Id"]);\n        if (currentReminder == null)\n        {\n            cBox.IsChecked = false;\n        }\n        else \n        {\n            cBox.IsChecked = true;\n            rrDate.Value = currentReminder.BeginTime;\n            hiddenTime.Text = rrDate.Value.ToString();\n            rrTime.Value = DateTime.Parse(hiddenTime.Text);\n        }\n      }\n    }	0
24196758	20487590	Check-in code into TFS Server by using TFS API	//Get the current workspace\n        WS = versionControl.GetWorkspace(workspaceName, versionControl.AuthorizedUser);     \n\n        //Mapping TFS Server and code generated\n        WS.Map(tfsServerFolderPath,localWorkingPath);\n\n        //Add all files just created to pending change\n        int NumberOfChange = WS.PendAdd(localWorkingPath,true);\n        //Get the list of pending changes\n        PendingChange[] pendings = WS.GetPendingChanges(tfsServerFolderPath,RecursionType.Full);\n\n        //Auto check in code to Server\n        WS.CheckIn(pendings,"CodeSmith Generator - Auto check-in code.");	0
821604	821407	Sql Server 2008 Closing Connections after database dropped	pooling=false	0
32399868	32398652	Multiple textBox validation and their combinations	if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox1.Text))                    \n  {\n     MessageBox.Show("Fill out textBox1 and textBox2"); \n     return;               \n  }\n// two filled out or two empty\nif (string.IsNullOrEmpty(textBox3.Text) != string.IsNullOrEmpty(textBox4.Text)) \n{\n     MessageBox.Show("Fill out or empty textBox3 and textBox4");\n     return;                \n}\n// two filled out or two empty\nif (string.IsNullOrEmpty(textBox5.Text) != string.IsNullOrEmpty(textBox6.Text)) \n{\n     MessageBox.Show("Fill out or empty textBox5 and textBox6"); \n     return;               \n}\n// if all empty error\n    if (string.IsNullOrEmpty(textBox3.Text) && string.IsNullOrEmpty(textBox5.Text)) \n    {\n         MessageBox.Show("Fill out 3,4 or 5,6 or 3,4,5,6");                \n    }	0
31700263	31700028	Using variables in SSIS	Row.unitprice	0
6168054	6168012	Extract items of IEnumerable<T> whose Key-Value is equal to one of the KeyValues in IEnumerable<U>	Ts.Where(t => Us.Select(u => u.SpecificValueOfSameType).Contains(t.SpecificValue))	0
22626411	22625759	How do I Convert the Animation of XAML Code to C#	public MainWindow()\n{\n    InitializeComponent();\n    Loaded += (s, e) =>\n       {\n          DoubleAnimation animation = new DoubleAnimation(200, 500, \n                                          TimeSpan.FromSeconds(0.2));\n          animation.AccelerationRatio = 0.1;\n          BeginAnimation(Window.TopProperty, animation);\n       };\n}	0
21250594	21250425	How to set the Tab Index or current Active control from code in C#	textBox.Select();	0
12234138	12232546	c# wrapping webdriver into a windows service	To configure how a service is started using the Windows interface \n\n1) Click Start, click in the Start Search box, type services.msc, and then press ENTER.\n\n2) In the details pane, right-click the service that you want to configure, and then click Properties.\n\n3) On the General tab, in Startup type, click Automatic, Manual, Disabled, or Automatic (Delayed Start).\n\n6) Type the password for the user account in Password and in Confirm password, and then click OK. If you select the Local Service account or Network Service account, do not type a password.	0
24671482	24671376	Match all digits but splitted in single characters	var matches = Regex.Matches("Hello world, '4567' is my number.", "\\d"); \n    foreach(Match match in matches)\n       Console.WriteLine(match.Value);	0
10252586	10252401	ListView doesn't show anything	foreach (DataRow dr in dt.Rows)\n        {\n            listView1.Items.Add(dr["NAME"].ToString());\n        }	0
9091067	9090913	How to send HTTP Post request to a socket using ASP.net C#	WebRequest request = WebRequest.Create(url);\nrequest.Method = "POST";\n\n\nstring postData = "Data to post here"\n\nbyte[] post = Encoding.UTF8.GetBytes(postData); \n\n//Set the Content Type     \nrequest.ContentType = "application/x-www-form-urlencoded";     \nrequest.ContentLength = post.Length;      \nStream reqdataStream = request.GetRequestStream();     \n// Write the data to the request stream.     \nreqdataStream.Write(post, 0, post.Length);      \nreqdataStream.Close();      \n// If required by the server, set the credentials.     \nrequest.Credentials = CredentialCache.DefaultCredentials;     \n\nWebResponse response = null;     \ntry     \n{\n    // Get the response.         \n    response = request.GetResponse();      \n}   \ncatch (Exception ex)     \n{         \n    Response.Write("Error Occured.");     \n}	0
7831861	7831789	Can I derive a grandchild for a class in C#?	using System;\n\npublic class Test\n{\n  public static void Main()\n  {\n      Grandchild g = new Grandchild();\n  }\n}\n\nclass Base\n{\n    public int i=10;\n}\n\nclass DerivedFromBase : Base\n{\n    public DerivedFromBase()\n    {\n      Console.WriteLine(i);\n    }\n}\n\nclass Grandchild : DerivedFromBase \n{\n   public Grandchild()\n   {\n      Console.WriteLine(i);\n   }\n}	0
14521721	14520788	Notifying ViewModel that Model Collection changed	public class TraceEntryQueue\n{\n    private readonly ObservableCollection<TraceEntry> _logEntries; \n\n    public TraceEntryQueue()\n    {\n        _logEntries = new ObservableCollection<TraceEntry>();\n    }\n\n    public void AddEntry(TraceEntry newEntry)\n    {\n        _logEntries.Add(newEntry);\n    }\n\n    public ObservableCollection<TraceEntry> GetLogEntries()\n    {\n        return _logEntries;\n    }\n}	0
23673531	23673165	Convert string to DateTime Format - wrong format	public void SaveFrameGpsCoordinate()\n{\n    int listSize = gpsDataList.Count - 1;\n\n    DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();\n    dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";\n    dateTimeFormatInfo.DateSeparator = "/";\n\n    //DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);\n    //DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);\n\n    DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);\n    DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);\n}	0
16986883	16957755	How to format data in C# ASP.Net MVC for datatable.net ajax call	public JsonResult GetData(int? Id)\n    {\n        List<sp_data_R_Result> tableData;\n        if (assetId != null)\n            tableData = DBData.Where(x => x.Id== Id).ToList();\n        else\n            tableData = DBData.ToList();\n\n        var res = new JsonResult\n        {\n            JsonRequestBehavior = JsonRequestBehavior.AllowGet,\n            Data = new\n                    {\n                        aaData = from d in tableData\n                                 select new object[]\n                                {\n                                  d.col1,\n                                  d.col2,\n                                  ...\n                                 }\n                    }\n        };\n\n        return res;\n    }	0
28360418	28360082	KeyDown event binding to user control	e.Handled = true;	0
8273031	8264596	How do I set __name__ to '__main__' when using IronPython hosted?	ScriptEngine engine = Python.CreateEngine();\n   ScriptScope mainScope = engine.CreateScope();\n\n   ScriptSource scriptSource = engine.CreateScriptSourceFromFile("test.py", Encoding.Default, SourceCodeKind.File);\n\n   PythonCompilerOptions pco = (PythonCompilerOptions) engine.GetCompilerOptions(mainScope);\n\n   pco.ModuleName = "__main__";\n   pco.Module |= ModuleOptions.Initialize;\n\n   CompiledCode compiled = scriptSource.Compile(pco);\n   compiled.Execute(mainScope);	0
9259055	8315251	How can I get cookies from HttpClientHandler.CookieContainer	int loop1, loop2;\nHttpCookieCollection MyCookieColl;\nHttpCookie MyCookie;\n\nMyCookieColl = Request.Cookies;\n\n// Capture all cookie names into a string array.\nString[] arr1 = MyCookieColl.AllKeys;\n\n// Grab individual cookie objects by cookie name.\nfor (loop1 = 0; loop1 < arr1.Length; loop1++) \n{\n   MyCookie = MyCookieColl[arr1[loop1]];\n   Response.Write("Cookie: " + MyCookie.Name + "<br>");\n   Response.Write ("Secure:" + MyCookie.Secure + "<br>");\n\n   //Grab all values for single cookie into an object array.\n   String[] arr2 = MyCookie.Values.AllKeys;\n\n   //Loop through cookie Value collection and print all values.\n   for (loop2 = 0; loop2 < arr2.Length; loop2++) \n   {\n      Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");\n   }\n}	0
29764464	29764349	How to get the PIDL of any folder to use in RegisterChangeNotify	IntPtr pidl = ILCreateFromPath(@"c:\path\file.ext");\nif (pidl != IntPtr.Zero)\ntry\n{\n    // do something\n}\nfinally\n{\n    Marshal.FreeCoTaskMem(pidl);\n}	0
7073381	7073343	List to two-dimensional Array	int i = 0;\nforeach(var number in integerList)\n{\n    integerArray[i % 500, (int)(i / 500)] = number;\n    i++;\n}	0
1608012	1607983	How can I use a foreach loop to delete all of the control in a panel?	private void ClearSearchResults()\n{\n    panel1.Controls.Clear();\n}	0
32308568	32306704	Unity - pass data between scenes	DontDestroyOnLoad (transform.gameObject);	0
9617601	9599725	Programmatically building tables in Visual Web Developer C#	public static void mTable()\n    {\n        Button btn = new Button();\n        btn.Click += new EventHandler(btnClick);\n    }\n\n    protected static void btnClick(object sender, EventArgs e)\n    { \n\n    }	0
31423280	31422719	How do you do map an entity to an table in Entity Framework 7?	protected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n    base.OnModelCreating(modelBuilder);\n\n    modelBuilder.Entity<SomeClass>().ForRelational().Table(tableName: "Test", schemaName: "Map");\n}	0
27586839	27586829	Access current form in a static void	public static void test(String s)\n{\n    form2 frm = new form2();\n    frm.mainName.Text = "";\n}	0
21725251	21409150	WebClient, accented character in a query string	string url = "http://myUrl.com/page";\nstring parameters = "param1=un&param2=ooohy??"\nbyte[] bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(parameters);\nWebRequest webRequest = WebRequest.Create(url);\nwebRequest.Method = "POST";\nwebRequest.ContentType = "application/x-www-form-urlencoded";\nwebRequest.ContentLength = bytes.Length;\n\nStream paramStream = webRequest.GetRequestStream();\nparamStream.Write(bytes, 0, bytes.Length);\nparamStream.Close();\n\nWebResponse response = webRequest.GetResponse();	0
8909730	8909695	How to Read First 512 Bytes of data from a .dat file in C#?	byte[] buffer = new byte[512];\ntry\n{\n     using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))\n     {\n          fs.Read(buffer, 0, buffer.Length);\n          fs.Close();\n     }\n}\ncatch (System.UnauthorizedAccessException ex)\n{\n     Debug.Print(ex.Message);\n}	0
14773735	14773618	Find IMEI / ESN of attached device programmatically	AT+CGSN	0
33839842	33802088	Validation failed for one or more entities. See 'EntityValidationErrors' property for more details, when trying to delete a row	public ActionResult Delete(int Id = 0)\n    {           \n        Register register = db.Registers.Find(Id);\n        register.status = 1;\n        db.Entry(register).State = EntityState.Modified;\n        db.SaveChanges();\n        return RedirectToAction("Index");\n    }	0
25477472	25477323	How to set the RowHeaderTemplate for a DataGrid programmatically?	public static DataTemplate DefaultHeaderTemplate = (DataTemplate)\n#if SILVERLIGHT || WinRT\n    XamlReader.Load(\n#else\n    XamlReader.Parse(\n#endif\n       "<DataTemplate " +\n       "    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +\n       "    <TextBlock Text=\"{Binding DisplayName, Mode=TwoWay}\" />" +\n       "</DataTemplate>"\n    );	0
2141940	2141895	search database table for value and put it in a datatable	'%' + @searchFileName + '%'	0
6866386	6796795	Low level keyboard hook set with SetWindowsHookEx stops calling function in C#	static HookProc hookProc;\n...\n\nhookProc = new HookProc(KeyboardHookProc);\nhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, IntPtr.Zero, 0);	0
30268054	30267972	How to create a JSON stringwith key/value pairs of web.config appsettings?	Dictionary<string, string> items = new Dictionary<string, string>();\nforeach (string key in ConfigurationManager.AppSettings) {\n    string value = ConfigurationManager.AppSettings[key];\n    items.Add(key, value);\n}\nstring json = JsonConvert.SerializeObject(items, Formatting.Indented);	0
6035022	6034946	How Can I Convert Between Two (numeric) Data Types Without Losing Any Data?	using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(ConvertExact(2.0, typeof(int)));\n        Console.WriteLine(ConvertExact(2.5, typeof(int)));\n    }\n\n    static object ConvertExact(object convertFromValue, Type convertToType)\n    {\n        object candidate = Convert.ChangeType(convertFromValue,\n                                              convertToType);\n        object reverse =  Convert.ChangeType(candidate,\n                                             convertFromValue.GetType());\n\n        if (!convertFromValue.Equals(reverse))\n        {\n            throw new InvalidCastException();\n        }\n        return candidate;\n    }\n}	0
23209384	23209238	Reading XML with XmlReader class	using (XmlReader reader = XmlReader.Create(filepath))\n{\n   while(reader.Read())\n   {\n      if (reader.IsStartElement())\n      {\n         switch (reader.Name)\n         {\n            case "Candidate":\n            string name = reader["CandidateName"];\n            break;\n\n            case "Vote":\n            string voteStr = reader["VoteString"];\n            break;\n         }\n      }\n   }\n}	0
8905696	8905617	Unable to set values to the data members of Datacontract embedded inside Member Contract from client	PartnerLogView partnerLogView = new PartnerLogView();\n\npartnerLogView.PartnerViewLogId =0;\n...\n...\n\nPartnerLogViewRequest request = new PartnerLogViewRequest();\nrequest.PartnerViewLog=partnerLogView;	0
18496356	18496232	Get most/least sold items in C# datatable	var mostBoughtIDs = purchases.AsEnumerable()\n                             .Where(r=>r.Field<DateTime>("time")>= lastMinute)\n                             .GroupBy(r=>r.Field<int>("id"))\n                             .OrderByDescending(g=>g.Sum(r=>r.Field<int>("quantity"))\n                             .Select(g=>g.First().Field<int>("id"))\n                             .Take(howMany);	0
12730987	12730813	Render Html in XAML + windows 8	ContentView.NavigateToString(w.description);	0
14878067	14877791	C# MySQL Insert, Delete, Update button?	cmd.CommandText = "insert into " + listTables.Items[listTables.SelectedIndex].ToString() + "(";\n\nforeach( var col in dataGridTableView.DataSource.DataTable[0].Columns)\n    cmd.CommandText += col.ColumnName +  "," ;\n\n// trim last comma off\n\ncmd.CommandText += ") Values( ";\n\n// access newly created row\n// iterate over the cells of the row, and add values to the command text we've been building\n// execute command text.	0
33462751	33462212	Add new row to DataGridView using textboxes	if ((!string.IsNullOrWhiteSpace(textBox6.Text)) || (!!string.IsNullOrWhiteSpace(textBox5.Text)) || (!string.IsNullOrWhiteSpace(textBox7.Text)))\n{\n    dataGridView1.Rows.Add(new object[] {textBox6.Text,textBox5.Text,textBox7.Text,dateTimePicker3.Value });\n}	0
2104162	2104151	Avoiding localiztion on formatting numbers written to file	String.Format(CultureInfo.InvariantCulture, "{0:0.####},{1:0.####}", x, y)	0
15781336	15781138	How can I efficiently stream large data from SQL Server 2008 to a web browser?	while (sqlReader.GetBytes(params))//params is a placeholder for the actual arguments and\n                                    //will have a byte array buffer and some counter indexes\n  {\n      context.Response.BinaryWrite(buffer);\n      //somecounter\n  }	0
14769843	14769616	How to assign access rights "Everyone" to a directory	DirectorySecurity sec = Directory.GetAccessControl(path);\n        // Using this instead of the "Everyone" string means we work on non-English systems.\n        SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);\n        sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));\n        Directory.SetAccessControl(path, sec);	0
851287	851248	C# Reflection: Get *all* active assemblies in a solution?	Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();	0
4764717	4763498	Datagridview checkboxcolumn validation	DataGridView.EndEdit();	0
1030027	1029983	How can I call a server side method from a linkbutton inside a gridview I am building programatically?	lb.Click += lb_Click;	0
6744887	6744590	add new event to button	protected void Page_Init(object sender, EventArgs e)\n{\n    Button a = new Button();\n    a.Width = 100;\n    a.Height = 100;\n    a.Text = "one";\n    a.Click += new EventHandler(test);\n    form1.Controls.Add(a);\n\n    Button b = new Button();\n    b.Visible = false;\n    b.Width = 100;\n    b.Height = 100;\n    b.Text = "two";\n    b.Click += new EventHandler(test2);\n    form1.Controls.Add(b);\n}\n\nprotected void test(object sender, EventArgs e)\n{\n    b.Visible = true;\n    Response.Write("aaaaaaaaaaaaaaaaaa");\n}\n\n\nprotected void test2(object sender, EventArgs e)\n{\n    Response.Write("bbbbbbbbbbbbbbb");\n}	0
2376311	2376291	Linq search that ignores nulls	IEnumerable<X> query = items;\nif (a.HasValue) {\n    query = query.Where(x => x.a == a.Value)\n}\nif (b.HasValue) {\n    query = query.Where(x => x.b == b.Value)\n}\nif (c.HasValue) {\n    query = query.Where(x => x.c == c.Value)\n}	0
26114152	26114113	How to insert Empty Text Box value into SQL 2008 database, through stored procedure?	cmd.Parameters.Add("@MachID", SqlDbType.Int).Value = string.IsNullOrEmpty(id) ? (object)DbNull.Value : id;	0
29770290	29770140	Deserialize and parse only needed arrays from JSON Array	void Main()\n{\n    var jsonString = File.ReadAllText(@"C:\text.json");\n    var json = JsonConvert.DeserializeObject<Response>(jsonString);\n}\n\npublic class Response\n{\n    public Outcomes[] outcomes { get; set; }\n}\n\npublic class Outcomes\n{\n    [JsonProperty("outcome_coef")]\n    public float OutcomeCoef { get; set; }\n\n    [JsonProperty("outcome_id")]\n    public int OutcomeId { get; set; }\n}	0
25112725	25112421	How to programmatically set data binding using C# xaml	this.UI_Boat.SetBinding(Rectangle.WidthProperty, new Binding()\n            {\n                Path = "Width",\n                Source = theBoat\n            });	0
12087628	12087354	Determining variable name on runtime	static void PrintVariableName<T>(Expression<Func<T>> expression)\n    {\n        Console.WriteLine(((MemberExpression)expression.Body).Member.Name);\n    }\n\n    static void Main(string[] args)\n    {\n        var a = "Hello, world!";\n\n        PrintVariableName(() => a);\n    }	0
32325888	32304714	Refresh Front-End on Data Change in Database by Other User in C#	SqlDataAdapter sdaTemp = new SqlDataAdapter();\nDataTable dtTemp = new DataTable();\nMyGlobalVariables.con.Open();\nsdaTemp = new SqlDataAdapter("Select * from Increment where ecode=(select MAX(ecode) from Increment) and UserID='"+MyGlobalVariables.MyUid+"'", MyGlobalVariables.con);\nMyGlobalVariables.con.Close();\nsdaTemp.Fill(dtTemp);\nMyGlobalVariables.dtEmp.Merge(dtTemp);\nMyGlobalVariables.dtEmp.AcceptChanges();\nMyGlobalVariables.bsEmp.MoveLast();	0
32432331	32432234	Getting Window of Event Sender	void treeListControl1_SelectedItemChanged(object sender, System.EventArgs e)\n{\n    var window = sender as RandomWindowType;\n    if (window == null)   // if it's not your random type\n      return;\n    // Take action\n}	0
14657528	14628899	What's the easiest way to save an object to a file without serialization attributes?	List<Person> persons = new List<Person>();\npersons.Add(new Person(){Name = "aaa"});\npersons.Add(new Person() { Name = "bbb" });\n\nJavaScriptSerializer javaScriptSerializer  = new JavaScriptSerializer();\nvar strData = javaScriptSerializer.Serialize(persons);\n\nvar persons2 = javaScriptSerializer.Deserialize<List<Person>>(strData);	0
18232979	18232803	Linq to Excel with multiple tabs	public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)\n{\n    Type t = typeof(T);\n    FieldInfo[] fields = t.GetFields();\n\n    string header = String.Join(separator, fields.Select(f => f.Name).ToArray());\n\n    StringBuilder csvdata = new StringBuilder();\n    csvdata.AppendLine(header);\n\n    foreach (var o in objectlist) \n        csvdata.AppendLine(ToCsvFields(separator, fields, o));\n\n    return csvdata.ToString();\n}	0
13516523	13516445	Getting combobox value in to another form	Form Form1Object = new Form1();\nForm1Object.cboxCliente.SelectedValue.ToString();	0
20702646	20492738	Creating multiple chart in c#	for(int i=0;i< 6;i++)\n{\nChart1.Series.Add("Series1" + t.ToString());\nChart1.ChartAreas.Add("ChartArea1" + t.ToString());\nChart1.Legends.Add("Legend1" + t.ToString());\n\nChart1.Series[t].ChartArea = "ChartArea1" + t.ToString();\nChart1.Series[t].ChartType = SeriesChartType.Column;\nChart1.Series[t].BorderWidth = 2;\n\nChart1.Series[t].ToolTip = "(#VALX,#VALY)";\nChart1.ChartAreas["ChartArea1" + t.ToString()].AxisX.Title = "Learning Domains";\nChart1.ChartAreas["ChartArea1" + t.ToString()].AxisY.Title = "Covered";\n}	0
177390	177373	How do I sort a generic list?	ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate)));	0
15364769	15364652	Show durations in an ASP.NET Bar Chart	List<int> durations = GetDurations(); // Change GetDurations to return a List<int> of the *minutes* of the timespan\nList<string> labels = GetLabels();  \n...\nchart.Series["Default"].Points.DataBindXY(xValues, durations);	0
17900326	17900248	string to byte[] without encoding or changing actual bytes at string	byte[] bytes = str.Split('-').Select(s => Convert.ToByte(s, 16)).ToArray();	0
20906787	20906701	Using LINQ to remove any value that is a duplicate	var distinct = list.GroupBy(x=>x).Where(y=>y.Count()==1).Select(z=>z.Key);	0
4938099	4937927	How to sort an UltraGrid by multiple columns programmatically?	UltraGridBand band = this.ultraGrid1.DisplayLayout.Bands[0];\n\n// Sort the rows by Country and City fields. Notice the order in which these columns\n// are set. We want to sort by Country and then sort by City and in order to do that\n// we have to set the SortIndicator property in the right order.\nband.Columns["Country"].SortIndicator = SortIndicator.Ascending;\nband.Columns["City"].SortIndicator    = SortIndicator.Ascending;\n\n// You can also sort (as well as group rows by) columns by using SortedColumns\n// property off the band.\nband.SortedColumns.Add( "ContactName", false, false );	0
1132533	1132494	String escape into XML	public static string XmlEscape(string unescaped)\n{\n    XmlDocument doc = new XmlDocument();\n    XmlNode node = doc.CreateElement("root");\n    node.InnerText = unescaped;\n    return node.InnerXml;\n}\n\npublic static string XmlUnescape(string escaped)\n{\n    XmlDocument doc = new XmlDocument();\n    XmlNode node = doc.CreateElement("root");\n    node.InnerXml = escaped;\n    return node.InnerText;\n}	0
17915402	17915269	How to use a plugin for input validation when using AngularJS Controllers?	//Inside directive\nvar ddo = {  //directive definition object\n    scope : {\n      msg : '=message'\n    },\n    link : function(scope, el, attrs) {\n        angular.element(el).warning(scope.msg);\n    }\n}\n\n//In html\n<input my-directive message="someVar" />\n\n//In controller\ncontrollerScope.someVar = /* call to your web service */	0
4456145	4452835	Fluent NHibernate mapping	public class EntityMap : ClassMap<Entity>\n{\n    public EntityMap()\n    {\n        Table("Entities");\n\n        Id(x => x.Id).GeneratedBy.GuidComb();\n        Map(x => x.Name).CustomSqlType("NVARCHAR").Length(50).Not.Nullable();\n        HasMany<Property>(x => x.Properties)\n            .Table("Properties")\n            .KeyColumn("PropertyName")\n            .Inverse()\n            .AsBag();\n    }\n}\n\npublic class PropertyMap : ClassMap<Property>\n{\n    public PropertyMap()\n    {\n        Table("Properties");\n\n        Id(x => x.Id).GeneratedBy.GuidComb();\n        Map(x => x.PropertyName).Length(50).Not.Nullable();\n        Map(x => x.IntValue);\n        Map(x => x.DecimalValue);\n    }\n}	0
7395029	5611658	Change margin programmatically in WPF / C#	test.Margin = new Thickness(0, -5, 0, 0);	0
5728526	5728494	How do you call a method from static main()?	var p = new Program();\nstring btchid = p.GetCommandLine();	0
29672568	29672124	alert ajax post method response from asp.net controller method in ajax success or in done function	.done(function (data, textStatus, jqXHR) { alert("Success: " + data.Response ); })	0
10412442	10412401	How to Read an embedded resource as array of bytes without writing it to disk?	public static byte[] ExtractResource(String filename)\n{\n    System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();\n    using (Stream resFilestream = a.GetManifestResourceStream(filename))\n    {\n        if (resFilestream == null) return null;\n        byte[] ba = new byte[resFilestream.Length];\n        resFilestream.Read(ba, 0, ba.Length);\n        return ba;\n    }\n}	0
7011749	7011620	Authenticating a SQL account user name and password in ASP.NET	public static bool checkConnection()\n{\n    SqlConnection conn = new SqlConnection("mydatasource");\n    try\n    {\n         conn.Open();\n         return true;\n    }\n    catch (Exception ex) { return false; }\n}	0
13183689	13183577	Is it a good practice to allow users to embed raw sql queries in an application?	String.Format	0
2084224	2083942	draw the two lines with intersect each other and need to find the intersect point in c# using directx?	static Point lineIntersect(Point a1, Point a2, Point b1, Point b2)\n{\n    float dx, dy, da, db, t, s;\n\n    dx = a2.X - a1.X;\n    dy = a2.Y - a1.Y;\n    da = b2.X - b1.X;\n    db = b2.Y - b1.Y;\n\n    if (da * dy - db * dx == 0) {\n        // The segments are parallel.\n        return Point.Empty;\n    }\n\n    s = (dx * (b1.Y - a1.Y) + dy * (a1.X - b1.X)) / (da * dy - db * dx);\n    t = (da * (a1.Y - b1.Y) + db * (b1.X - a1.X)) / (db * dx - da * dy);\n\n    if ((s >= 0) & (s <= 1) & (t >= 0) & (t <= 1)) \n        return new Point((int)(a1.X + t * dx), (int)(a1.Y + t * dy));\n    else\n        return Point.Empty;\n}	0
32708656	32707435	MS Exchange server cloud, getting all items in a different	FolderId RoomMailboxCalendarFolderId = new FolderId(WellKnownFolderName.Calendar, "room@domain.com");\n        CalendarView cvCalView = new CalendarView(DateTime.Now, DateTime.Now.AddDays(31));\n        FindItemsResults<Appointment> appointments = service.FindAppointments(RoomMailboxCalendarFolderId, cvCalView);	0
19923467	19923421	Get class names of all entities that inherit from a base entity	var names = assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t)).Select(t => t.Name);	0
8752312	8736624	C# passing dynamic method as parameter	public static void RunMethod(string script, string method, object[] param)\n{\n    try\n    {\n        dynamic dynamicObj = Scripts[script];\n        var operations = ironPython.Operations;\n        operations.InvokeMember(dynamicObj, method, param);\n    }\n    catch { }\n}	0
31847062	31846966	Method overload and generic parameter	static public void MyReset(this object col)\n{\n    Console.WriteLine("Not a collection!");\n}\n\nstatic public void MyReset<T>(this ICollection<T> col)\n{\n    col.Clear();\n    Console.WriteLine("Cleared!");\n}\n\nstatic public void MyReset<T>(this IWhateverYouLike<T> col)\n{\n    col.ClearItIfYouLike();\n    Console.WriteLine("Cleared!");\n}	0
1670406	1670392	C# DateTimePicker Custom Format	dateTimePicker1.CustomFormat = "dd/MM/yyyy";\ndateTimePicker1.Format = DateTimePickerFormat.Custom;	0
10173294	10173148	Is there a way to make XmlDocument parsing less strict	Tidy tidy = new Tidy();\ntidy.Options.FixComments = true;\ntidy.Options.XmlTags = true;\ntidy.Options.XmlOut = true;\n\nstring invalid = "<root>< <!--comment--->></root>";\nMemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes(invalid));\nMemoryStream output = new MemoryStream();\ntidy.Parse(input, output, new TidyMessageCollection());\n// TODO check the messages\n\nstring repaired = Encoding.UTF8.GetString(output.ToArray());	0
21549764	21549431	Regular Expression to extract multiple parts when some string parts are absent	(?:(\d{6}[-*][\dxX]{7}))?[^\d]*(\d{1,3}-\d{1,3}-\d{1,3}) ([FPTSUCD])=?([01][*-])	0
3104177	3104158	XmlReader breaks on UTF-8 BOM	private static string SerializeResponse(Response response)\n{\n    var output = new StringWriter();\n    var writer = XmlWriter.Create(output);\n    new XmlSerializer(typeof(Response)).Serialize(writer, response);\n    return output.ToString();\n}	0
29140624	29140461	Mouse wait to click action	MouseEnter_handler(object sender, EventArgs e)\n{\n    Button MyButton = sender as Button;\n    StopWatch sw = new StopWatch();\n    sw.Start();\n    while (sw.ElapsedMilliseconds < 1000)\n    {}\n    MyButton.Enabled = true;\n}	0
18016928	18016321	Change scrollbar value while scrolling even if the Focus is on a different object	public frmSTOverScrollText()\n{\n    InitializeComponent();\n    txtInput.MouseWheel += new MouseEventHandler(txtInput_MouseWheel);\n}\n\nvoid txtInput_MouseWheel(object sender, MouseEventArgs e)\n{\n    if (e.Delta < 0)\n    {\n        if (vsInput.Value + vsInput.LargeChange <= vsInput.Maximum)\n            vsInput.Value += vsInput.LargeChange;\n    }\n    else if (vsInput.Value - vsInput.LargeChange >= vsInput.Minimum)\n        vsInput.Value -= vsInput.LargeChange;\n}	0
26628784	26623184	Convert excel formulas to web based application	var Cost = 9790,
\n    Allocation = 0.03,
\n    Fee = 90,
\n    C1 = 0,
\n    C3 = 0,
\n    C1iterations = 100,
\n    C3iterations = 100;
\n
\nfunction Cell1() {
\n  if(--C1iterations) {
\n    C1 = Cell3() * Allocation;
\n  }
\n  else {
\n    C1iterations = 100;
\n  }
\n  return C1;
\n}
\n
\nfunction Cell3() {
\n  if(--C3iterations) {
\n    C3 = Cost + Cell1() - Fee;
\n  }
\n  else {
\n    C3iterations = 100;
\n  }
\n  return C3;
\n}
\n
\ndocument.body.innerHTML= 'Cell1: '+Cell1()+'<br>Cell3: '+Cell3();	0
21810121	21810075	SQLite: create table and add a row if the table doesn't exist	using (SQLiteConnection con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;"))\nusing (SQLiteCommand command = con.CreateCommand())\n{\n    con.Open();\n    command.CommandText = "SELECT name FROM sqlite_master WHERE name='account'";\n    var name = command.ExecuteScalar();\n\n    // check account table exist or not \n    // if exist do nothing \n    if (name != null && name.ToString() == "account")\n        return;\n    // acount table not exist, create table and insert \n    command.CommandText = "CREATE TABLE account (rowID INT, user VARCHAR(20), pass VARCHAR(20))";\n    command.ExecuteNonQuery();\n    command.CommandText = "INSERT INTO account (rowID, user, pass) VALUES (0, '', '')";\n    command.ExecuteNonQuery();\n}	0
6196884	6196770	datagridview export to excel	private void ToCsV(DataGridView dGV, string filename)\n    {\n        string separator = ",";\n        StringBuilder stOutput = new StringBuilder();\n        // Export titles: \n        StringBuilder sHeaders = new StringBuilder();\n        for (int j = 0; j < dGV.Columns.Count; j++)\n        {\n            sHeaders.Append(dGV.Columns[j].HeaderText);\n            sHeaders.Append(separator);\n        }\n        stOutput.AppendLine(sHeaders.ToString());\n        // Export data. \n        for (int i = 0; i < dGV.RowCount - 1; i++)\n        {\n            StringBuilder stLine = new StringBuilder();\n            for (int j = 0; j < dGV.ColumnCount; j++)\n            {\n                stLine.Append(Convert.ToString(dGV[j, i].Value));\n                stLine.Append(separator);\n            }\n            stOutput.AppendLine(stLine.ToString());\n        }\n\n        File.WriteAllText(filename, stOutput.ToString());\n    }	0
32288331	32287840	C# : generate array of random number without duplicates	Random rnd = new Random();\nrandomQuestionId = idS.OrderBy(_ => rnd.Next()).Take(4).ToArray();	0
16251325	16251298	How can I determine the parameterless-type of a C# generic type for checking purposes?	var type = list.GetType();\nif(type.IsGenericType && \n   type.GetGenericTypeDefinition().Equals(typeof(List<>)))\n{\n    // do work\n}	0
28620851	28615931	Odata V4 - entity null when trying to add one	public async Task<IHttpActionResult> Post([FromBody] User user)\n{\n  ...\n}	0
26226593	26226525	Using a while loop in c# with a factorial	int number = 7;  \nint i = 1;\nlong factorial = number;\nwhile (number > 1)\n{\n    factorial *= --number;\n    Console.WriteLine("{0}. {1} * {2} = {3}", i++, factorial/number, number, factorial);\n}\nConsole.WriteLine(factorial);	0
23848194	23845798	Sorting a paged WPF ListView will sort only the items on current page	private void Sort(string sortBy, ListSortDirection direction)\n{\n    var sortProperty = typeof(Server).GetProperty(sortBy);\n    if(sortProperty == null) return;\n    if (direction == ListSortDirection.Ascending)\n    {\n        Source = new ObservableCollection<Server>(Source.OrderBy(s => sortProperty.GetValue(s, null)));\n    }\n    else\n    {\n        Source = new ObservableCollection<Server>(Source.OrderByDescending(s => sortProperty.GetValue(s, null)));\n    }\n\n    view.Source = Source;\n    view.View.Refresh();\n}	0
8707099	8707072	How can I use the NavigationService as a result of a synchronous callback in Silverlight C# for WP7?	Dispatcher.BeginInvoke(() =>\n{\n    NavigationService.Navigate(...);\n});	0
13836029	13835954	Azure database with Ninject	NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.	0
7808057	7808042	Object initialization from single DataRow	Foo foo = dt.AsEnumerable().Select(dr =>\n    new Foo { Bar = Convert.ToIn32(dr["Bar"]),\n              Baz = Convert.ToDecimal(dr["Baz"]) }).Single();	0
27030601	27012813	To specify a DataGridView column header's text with an event	private void DGWBase_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)\n    {\n        DGWBase.Columns[1].HeaderText = "Waktu Mulai\nStarting Time";\n        DGWBase.Columns[2].HeaderText = "Nama Personil\nPersonnel Name";\n        DGWBase.Columns[3].HeaderText = "Nama Pekerjaan\nWorkshop Name";\n        DGWBase.Columns[4].HeaderText = "MPS No";\n        DGWBase.Columns[5].HeaderText = "Kuantitas\nQuantity";\n        DGWBase.Columns[6].HeaderText = "Operasi Kode\nOperation Code";\n        DGWBase.Columns[7].HeaderText = "Nama Operasi\nOperation Name";\n        DGWBase.Columns[8].HeaderText = "Produk Kode\nProduct Code";\n        DGWBase.Columns[9].HeaderText = "Nama Produk\nProduct Name";\n        DGWBase.Columns[10].HeaderText = "Permintaan Kersa\nJob Order";\n    }	0
2593926	2593916	Import external dll based on 64bit or 32bit OS	[DllImport("32bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]\npublic static extern int CallMe32 (IntPtr hWnd, String text, String caption, uint type);\n\n[DllImport("64bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]\npublic static extern int CallMe64 (IntPtr hWnd, String text, String caption, uint type);	0
23776696	23762154	List Both Local and Network Drives with Full Details	System.Management.ManagementClass mc = new System.Management.ManagementClass("Win32_LogicalDisk");\n\nSystem.Management.ManagementObjectCollection moc = mc.GetInstances();\nif (moc.Count != 0)\n{\n    foreach (System.Management.ManagementObject mo in mc.GetInstances())\n    {\n        string providerName = string.Empty;\n\n        if (mo["ProviderName"] != null)\n        {\n            providerName = mo["ProviderName"].ToString();\n        }\n\n        Console.WriteLine("\nName: {0}\nVolume Name: {1}\nProvider Name: {2}",\n                          mo["Name"].ToString(),\n                          mo["VolumeName"].ToString(),\n                          providerName);\n    }\n}	0
8478175	8478148	Databinding to show an assembly name	public class AssemblyNameConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        var assembly = (Assembly)value;\n        return assembly.GetName().Name;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n         throw new NotImplementedException();\n    }\n}	0
11132433	11132372	C# button click once a day	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        this.GetLeft.Value = invited.GetInviteCountByWeb().ToString();\n        HttpCookie oldCookie = Request.Cookies["Time"];\n        if (oldCookie != null)\n        {\n            if (DateTime.Now.ToString("yyyy-MM-dd") == Convert.ToDateTime(oldCookie.Values["GetTime"]).ToString("yyyy-MM-dd"))\n            {\n                this.IsGet.Value = "false";\n            }\n        }\n        else\n        {\n            HttpCookie newCookie = new HttpCookie("Time");\n            newCookie.Values.Add("GetTime", DateTime.Now.Date.ToString("yyyy-MM-dd"));\n            newCookie.Expires = DateTime.Now.AddHours(24.0);\n            Response.Cookies.Add(newCookie);\n        }\n    }	0
14283718	14283694	How do I use the same variable in 12 different button events?	double total = 0; \n\nprivate void btnItem2_Click(object sender, EventArgs e)\n    {\n\n\n        lblItemPrice.Text = string.Format("?{0:0.00}", btnItem2.Tag);\n\n        lstTill.Items.Add(btnItem2.Text + "\t" + (string.Format(btnItem2.Tag.ToString())));\n\n        this.lstTill.TopIndex = this.lstTill.Items.Count - 1;\n\n        total = total+ Convert.ToDouble(btnItem2.Tag);\n        lblTotalPrice.Text = "? " + Convert.ToString(lblItemPrice);\n    }	0
8729141	8729026	Linq-to-SQL Moving DataObject from one DataClass to another, keeping structure. Howto?	//pseudo-code \n//something like this \n\nTargetInstance target = new TargetInstance();\n\nforeach(Property sourceProperty in sourceinstance)\n{\n    if(target contains sourceProperty)\n    {\n        target[SourceProperty] = sourceInstance[SourceProperty];\n    }    \n}	0
4393900	4393631	select multiple items in asp.net listbox from code	foreach(ListItem i in ListBoxSourceDetail.Items)\n        {\n            ListBoxSourceEdit.Items.FindByText(i.ToString()).Selected = true;\n\n        }	0
8045533	8045355	Entity Framework, how to avoid this issue?	public static IEnumerable<T> IncludeUnsaved<T>(this ObjectSet<T> set) where T : class\n    {\n        var addedObjects = set.Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added);\n        var equalObjects = addedObjects.Select(e => e.Entity).OfType<T>();\n\n        return equalObjects.Concat(set);\n    }	0
13325279	13325220	XNA Scale in one direction	Matrix.CreateScale(1.0f, -1.0f,  1.0f); // Invert only one koordinate	0
2351952	2351939	Override DateTime.MinValue	DateTime? dateVal = null;	0
10036776	10036723	Open File Dialogs - setting the InitialDirectory location?	var imagePath = System.IO.Path.Combine( Application.StartupPath, "images" )\n\nopdPicture.Title = "Choose a Picture";\nopdPicture.InitialDirectory = imagePath ;	0
3371623	3371554	How to dynamically bind all events in an object to an EventHandler?	public static void GenericEventHandler(EventInfo info)\n    {\n        // do some logging here\n    }\n\n    public static void Bind(SourceOfManyEvents s)\n    {\n        foreach (var e in typeof(SourceOfManyEvents).GetEvents())\n        {\n            e.AddEventHandler(s, (Action<EventInfo>)GenericEventHandler);\n        }\n    }	0
14724571	14724385	Keeping the item named 'other' at the bottom of my ordered list	List<SelectListItem> test = new List<SelectListItem>\n{\n    new SelectListItem { Text="aaa", Value ="1"},\n    new SelectListItem { Text="ttt", Value="2"},\n    new SelectListItem { Text="bbb", Value = "3"},\n    new SelectListItem { Text="other", Value = "4"}\n}.OrderBy(x => x.Text == "other").ThenBy(x => x.Text).ToList();	0
33099454	33093973	How to iterate through every HTML table in a single HTML row	trRiskMgt.InnerHtml = Server.HtmlEncode("your data");// elementId.InnerHtml	0
33577995	33575969	List installed font names in Windows 10 Universal App	string[] fonts = Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies();\nforeach (string font in fonts)\n{\n    Debug.WriteLine(string.Format("Font: {0}", font));\n}	0
32474656	32473317	How To SetDataSouce on Crystal Report WIth Multiple Procedures	strPath = HttpContext.Current.Server.MapPath("~/Reports/") + RptName + ".rpt";\n            rptDoc.Load(strPath);\n\n            DataSet DS1 = new DataSet();\n            DS1 = objCommon.FillDataSetMTG(SqlConn, "USP_Report_JobCardDet", Convert.ToInt32(ViewState["Id"]), "JobEntryId");\n            rptDoc.Tables["USP_Report_JobCardDet"].SetDataSource(DS1);\n\n            DataSet DS2 = new DataSet();\n            DS2 = objCommon.FillDataSetMTG(SqlConn, "USP_Report_JobCard", Convert.ToInt32(ViewState["Id"]), "JobEntryId");\n            rptDoc.Tables["USP_Report_JobCard"].SetDataSource(DS2);	0
23502678	23502340	Get array with the position of a repeated char in a string	public int[] CharPositions(string input, char match)\n{\n    return Regex.Matches(input, Regex.Escape(match.ToString()))\n               .Cast<Match>()\n               .Select(m => m.Index)\n               .ToArray();\n}	0
19540893	19540821	Remove the time part and convert date time in different format	dateAndTime.ToString("MMMM dd,yyyy");	0
14703085	14697053	How to configure HttpClient via Unity container?	container.RegisterType<HttpClient>(\n    new InjectionFactory(x => \n        new HttpClient { BaseAddress = ConfigurationManager.AppSettings["ApiUrl"] }\n    )\n);	0
28127830	28127814	c# call base constructor with ref parameter	class B : A\n{\n    public B(ref int value): base(ref value)\n    {\n    }\n}	0
11969780	11949814	how to bind DataTable to legend in mschart	var l = chart1.Legends[0];\nl.LegendStyle = LegendStyle.Table;\nl.TableStyle = LegendTableStyle.Tall;\nl.BorderColor = Color.OrangeRed;\nl.Docking = Docking.Bottom;\nl.LegendStyle = LegendStyle.Table;\nl.HeaderSeparator = LegendSeparatorStyle.DashLine;\nl.HeaderSeparatorColor = Color.Red;\n\nvar firstColumn = new LegendCellColumn();\nl.ColumnType = LegendCellColumnType.SeriesSymbol;\nl.CellColumns.Add(firstColumn);\n\nvar secondColumn = new LegendCellColumn();\nl.ColumnType = LegendCellColumnType.Text;\nsecondColumn.Text = "#SER";\nl.CellColumns.Add(secondColumn);\n\nforeach (DataRow row in dt.Rows)\n{\n    var column = new LegendCellColumn();\n    column.ColumnType = LegendCellColumnType.Text;\n    column.HeaderText = row["x"].ToString();\n    column.Text = "#VALY";\n    l.CellColumns.Add(column);\n}	0
3711935	3711805	How to rotate a list of strings along an axis?	private void Form1_Paint(object sender, PaintEventArgs e)\n{\n    foreach (var str in data)\n    {\n        e.Graphics.TranslateTransform(str.X, str.Y);\n        e.Graphics.RotateTransform(30);\n        e.Graphics.DrawString(str.StringName, mFont, new SolidBrush(Color.Black), new Point(0, 0));\n        e.Graphics.ResetTransform();\n    }\n}	0
2647207	2647183	Intersection between sets containing different types of variables	HashSet<double> values = ...;\nIEnumerable<SomePoint> points = ...;\n\nvar result = points.Where(point => values.Contains(point.Z));	0
12095014	12094985	How to run a specific DOS Command	string command = string.Format("/c rundll32 printui, PrintUIEntry /o /n" + "\" POS Lexmark\"");	0
4979013	4978289	How to kill a thread?	while (!CancellationPending )\n{\n  // do stuff\n}	0
1965723	1965675	How to read string from pointer to buffer in C#	byte[] buffer = new byte[1000];\nint size;\nunsafe\n{\n  fixed ( byte* p = buffer )\n  {\n    size = GetError( ???, p, buffer.Length ); \n  }\n}\nstring result = System.Text.Encoding.Default.GetString( buffer, 0, size );	0
32631758	32371301	Connecting nhibernate to Postgresql in C#	.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ReportDB>())	0
16554280	16554210	Change table schema on middle table generated by Entity Framework	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n     modelBuilder.Entity<Message>().HasMany<Phone>(m => m.Phones).WithMany(p => p.Messages).Map\n           (\n            x =>\n               {\n                  x.ToTable("MessagePhone", "public");\n               }\n           );\n }	0
6467750	6467016	How to pass a value into the error message using fluent validation	RuleFor(x => x.Property).Length(1,255).WithMessage("Max number of chars is {0}", "255");	0
3095391	3095316	Using Func with instance method	class MyClass\n{\n   public Func<loan, user, bool> SendStuffAction ;\n\n   MyClass()\n   {\n      SendStuffAction = SendStuff;\n   }\n\n   bool SendStuff(loan loanVar, user userVar)\n   {\n      return true;\n   }\n}	0
26759045	26731433	ODataConventionModelBuilder with inherited entities	var entities = manager.getEntities(null, breeze.EntityState.Modified);\nfor (var i = 0; i < entities.length; i++) {\n    delete entities[i].entityAspect.extraMetadata;\n}	0
9982939	9977993	Is there a way to use Linq to SQL Stored Procedures to be called asynchronously	var task = Task.Factory.StartNew<IEnumerable<SQLPoco>(()=>{return SOMELINQTOSQL;});\ntask.ContinueWith((previousTask)=>{USE previousTask.Result;});	0
17270719	17270588	How can I change another page's dropdown in aspx?	window.close();\nif (window.opener && !window.opener.closed) {\nwindow.opener.location.reload();\n}	0
7128464	7128457	Handling Spaces in Application.ExecutablePath	GetLicStats(lmExec + " lmstat -a -c " + licport + "@\"" + curAdd + "\"");	0
11615981	11613696	C# Converting UTC to local time in a function dataset	row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)\n                                                   ? (DateTime)SqlDateTime.MinValue\n                                                   : eventArgs.Vtq.Timestamp.ToLocalTime();	0
6348788	6348736	Printing list permutation	foreach(var secondaryList in primaryListOfObjects) {\n    StringBuilder sb = new StringBuilder();\n    foreach(var str in secondaryList) {\n        sb.Append(str);\n    }\n    Console.WriteLine(sb.ToString());\n}	0
23082572	23080398	Attempting to access the member of a struct through a property on an enclosing class	ListView lvi = new ListView();        \nMyStruct ms;\nms.Width = 5;\nlvi.Size = ms;	0
1102691	1102578	Replacement of enum that requires translation and enumeration	private static Dictionary<ExportFormat, string> FormatDescriptions =\n    new Dictionary<ExportFormat,string>()\n{\n    { ExportFormat.Csv, "Comma Separated Values" },\n    { ExportFormat.Tsv, "Tab Separated Values" },\n    { ExportFormat.Excel, "Microsoft Excel 2007" },            \n};\n\npublic static string Describe(this ExportFormat e)\n{\n    var formats = e.Formats();\n    var descriptions = formats.Select(fmt => FormatDescriptions[fmt]);\n\n    return string.Join(", ", descriptions.ToArray());\n}	0
22523490	22522814	How to implement this kind of inheritance	public interface ISerializable<out T1, T2>\n{\n    T2 Serialize();\n    T1 Deserialize(T2 dto);\n}\n\npublic interface IA<out T1, T2>\n{\n    string Name { get; }\n}\n\npublic interface IASerializeAware<out T1,T2> :  IA<T1, T2>, ISerializable<T1,T2>\n{\n}\n\npublic abstract class ASerializeAwareBase<T1, T2> : Serializable<T1,T2>, IASerializeAware<T1,T2>\n{\n    public string Name { get; set; }\n}\n\npublic abstract class Serializable<T1, T2> : ISerializable<T1, T2>\n{\n    public T2 Serialize()\n    {\n        throw new NotImplementedException();\n    }\n\n    public T1 Deserialize(T2 dto)\n    {\n        throw new NotImplementedException();\n    }\n}	0
32753039	32753012	How to invoke Expression<Func<Entity, bool>> against a collection	return Customers.Values.AsQueryable().Where(expression);	0
1946540	1946515	Is it possible to insert DataRow into a DataTable at index 0?	DataTable table = //...\ntable.Rows.InsertAt(row, 0);	0
14877450	14875611	Disable row editing for only 1 cell in the grid	Public Sub PopupEditorMethod(ByVal sender As Object, ByVal e As ExecuteCommandEventArgs(Of OurObject))\n    Dim row = CType(e.OriginalSource, Xceed.Wpf.DataGrid.DataRow)\n    row.EndEdit()\n\n    'popup implementation\nEnd Sub	0
22837646	22837551	Convert string to datetime and remove the time part from the date	DateTime Var = Convert.ToDateTime(Dset.Tables[1].Rows[i]["Date"]).Date; //only date part\nstring date = Var.ToShortDateString();	0
30482770	30481390	Loading xml data to ListView in C#?	XDocument doc = XDocument.Load(Application.StartupPath + "/Employees.xml");\ndoc.Descendants("Employee").ToList()\n   .ForEach(x => listView1.Items.Add(\n                 new ListViewItem(\n                 new string[] { x.Attribute("ID").Value, x.Element("Name").Value }))\n           );	0
8887177	8887029	Parsing JSON file C#	JObject myObj = (JObject)JsonConvert.DeserializeObject(jsonString);\nforeach(var resource in myObj["Resources"])\n{\n    var props = resource.Children<JObject>().First();\n    Console.WriteLine(props["Type"] + " " + props["Properties"]["InstanceType"]["Ref"]);\n}	0
31365987	31365067	Displaying a txt file accessed via http with a winforms application	System.Net.WebClient wc = new System.Net.WebClient();\nstring url_data = wc.DownloadString("http://example.com/1.txt");\nrichtextBox1.Text = url_data;	0
13353506	13353387	Generic XML Deserialization into Undefined Objects	public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid)\n{\n    var expandoFromXml = new List<dynamic>();\n\n    var doc = XDocument.Load(file);\n    var nodes = doc.Root.Descendants(descendantid);\n\n    foreach (var element in doc.Root.Descendants(descendantid))\n    {\n        dynamic expandoObject = new ExpandoObject();\n        var dictionary = expandoObject as IDictionary<string, object>;\n        foreach (var child in element.Descendants())\n        {\n            if (child.Name.Namespace == "")\n                dictionary[child.Name.ToString()] = child.Value.Trim();\n        }\n        yield return expandoObject;\n    }\n}	0
20648435	20648112	Converting string amount value with parenthesis to double	string amtStr = "{100,000,000.00}";\n        amtStr = amtStr.Replace("{", "-").Replace("}", "").Replace("(", "-").Replace(")", "").Trim() ;\n        double amt = Convert.ToDouble(amtStr);	0
8008226	8007973	Changing the Type of a inherited property (to a inherited type)	public class ContainerEditor : ContainerBase\n{\n  public NodeEditor Root {\n    get { return (NodeEditor)base.Root; }\n    set { base.Root = value; }\n  }\n  ...\n}	0
21348581	21348259	How to Scroll To End of ListView After Data Added - WPF	((INotifyCollectionChanged)listView.ItemsSource).CollectionChanged +=\n     (s, e) =>\n     {\n         if (e.Action == \n             System.Collections.Specialized.NotifyCollectionChangedAction.Add)\n         {\n             listView.ScrollIntoView(listView.Items[listView.Items.Count - 1]);\n         }\n     };	0
20733943	20731663	How to press 'Esc' key in Selenium WebDriver using C#	using OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium.Interactions;\n\nIWebDriver driver = new FirefoxDriver(ffprofile);\ndriver.Navigate().GoToUrl("http://www.google.com");\ndriver.FindElement(By.Name("q")).SendKeys("Stack Overflow");\ndriver.FindElement(By.Name("q")).Submit();\n\nActions action = new Actions(driver);\naction.SendKeys(OpenQA.Selenium.Keys.Escape);	0
224244	224236	Adding a newline into a string in C#	string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";\n\ntext = text.Replace("@", "@" + System.Environment.NewLine);	0
12162280	12162034	Databinding to TreeView in XAML	public ReadOnlyCollection<Category> FirstGeneration { get; set; }	0
16922230	16921908	Send post data through winform	// You need to post the data as key value pairs:\nstring postData = "ver=1&cmd=abf";\nbyte[] byteArray = Encoding.UTF8.GetBytes(postData);\n\n// Post the data to the right place.\nUri target = new Uri("http://192.168.3.230/setcmd.cgx"); \nWebRequest request = WebRequest.Create(target);\n\nrequest.Method = "POST";\nrequest.ContentType = "application/x-www-form-urlencoded";\nrequest.ContentLength = byteArray.Length;\n\nusing (var dataStream = request.GetRequestStream())\n{\n    dataStream.Write(byteArray, 0, byteArray.Length);\n}\n\nusing (var response = (HttpWebResponse)request.GetResponse())\n{\n   //Do what you need to do with the response.\n}	0
29803869	29803458	Is there any way of locking an object in Swift like in C#	func lock(obj: AnyObject, blk:() -> ()) {\n    objc_sync_enter(obj)\n    blk()\n    objc_sync_exit(obj)\n}\n\nvar pendingElements = 10\n\nfunc foo() {\n    var sum = 0\n    var pendingElements = 10\n\n    for i in 0 ..< 10 {\n        proccessElementAsync(i) { value in\n\n            lock(pendingElements) {\n                sum += value\n                pendingElements--\n\n                if pendingElements == 0 {\n                    println(sum)\n                }\n            }\n\n        }\n    }\n}	0
23445456	23445305	CustomValidator not working with other validators	EnableClientScript = false	0
21412626	21412517	Converting a SQL Query to a Predicate Expression using Fluent Synatx	DateTime memberCutoff = ...;\nDateTime orderCutoff = ...;\nvar query = context.Customers\n                   .Join(context.Orders,\n                         c => c.Id, r => r.CustomerId, (c, r) => new { c, r })\n                   .Where(pair => pair.c.MemberSince > memberCutoff &&\n                                  pair.r.OrderDate > orderCutoff)\n                   .OrderBy(pair => pair.r.OrderDate);	0
5923546	5905049	How can I group on a nested property as well as having the same parent in LINQ?	void Sample(INumerable<SimeFile> simeFiles, Func<NoteChart, bool> noteChartPredicate)\n{\n  var xyz =\n    from sf in fimFiles\n    from nc in sf.NoteCharts\n    group nc by new{Matched=noteChartPredicate(nc), SimFile=sf} into g\n    select new{g.Key.SimFile, g.Key.Matched, NoteCharts = g.ToList()};\n  ...\n}\n\nSample(simFiles, nc => nc.BPM >= 130 && nc.BPM <= 150);	0
4818037	4817895	how to send text using HttpWebRequest class in C#	private void timer1_Tick(object sender, EventArgs e)    \n{\n    string strServer = "hhttp://www.mydomain.net/save.php";\n    try \n    {\n        var reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);\n\n        reqFP.Method = "POST";\n        reqFP.ContentType = "application/x-www-form-urlencoded";\n\n        reqFP.ContentLength = writeup.Length;\n\n        /*var rspFP = (HttpWebResponse)reqFP.GetResponse();\n        if (rspFP.StatusCode == HttpStatusCode.OK) \n        {*/\n            //WRITE STRING TO STREAM HERE\n            using (var sw = new StreamWriter(reqFP.GetRequestStream(), Encoding.ASCII))\n            {\n                sw.Write(writeup);\n            }   \n\n            rspFP.Close(); //is good to open and close the connection every minute\n        /*}*/       \n    }\n    catch (WebException) {\n        //I don't know why to use try/catch... \n        //but I just don't want any errors to be poped up...\n    }\n    writeUp = "";\n}	0
21232445	21231319	Change App.Config file at Runtime Not Worked for users without Administrator rights	exePath = Path.Combine( exePath, "MyApp.exe" );\n    Configuration config = ConfigurationManager.OpenExeConfiguration( exePath );\n    var setting = config.AppSettings.Settings[SettingKey];\n    if (setting != null)\n    {\n        setting.Value = newValue;\n    }\n    else\n    {\n        config.AppSettings.Settings.Add( SettingKey, newValue);\n    }\n\n    config.Save();	0
6433371	5723523	Use new ChannelFactory<TChannel>(string) if the config is in a string?	ConfigurationChannelFactory<TChannel>	0
1074578	1074378	C# Datagridview Checkbox Checked Event - multiple rows?	static int SelectColumnIndex = 0;\nPerformAction_Click(object sender, System.EventArgs e)\n{\n    string data = string.Empty;\n    foreach(DataGridViewRow row in MyDataGridView.Rows)\n    {\n      if(row.Cells[SelectColumnIndex].Value!=null &&\n             Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)\n      {\n        foreach(DataGridViewCell cell in row.Cells)\n        {\n          if(cell.OwningColumn.Index!= SelectColumnIndex)\n          {\n            data+= (cell.Value + " ") ; // do some thing\n          }\n        }\n        data+="\n";\n      }\n   }\n   MessageBox.Show(data, "Data");\n}	0
5362909	5362835	How do I add a html style container using C#?	HtmlGenericControl style = new HtmlGenericControl();\nstyle.TagName = "style";\nstyle.Attributes.Add("type", "text/css");\nstyle.InnerHtml = "body{background-color:#000000;}";\nPage.Header.Controls.Add(style);	0
8968951	8968924	How to compare two xml nodes?	web.config	0
13194928	13194614	How can i parse html string	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar teams = doc.DocumentNode.SelectNodes("//td[@width='313']")\n                .Select(td => new TeamClass\n                {\n                    TeamName = td.Element("a").InnerText,\n                    TeamId = HttpUtility.ParseQueryString(td.Element("a").Attributes["href"].Value)["ItemTypeID"]\n                })\n                .ToList();	0
4152725	4152655	How to transform this foreach to Linq?	var xList = XmlData.Elements().ToList();	0
12148386	12148310	Evaluation order of named parameters	int capturedY = genNum(); //It is important that Y is generated before X!\nint capturedX = genNum();\nfoo(capturedX, capturedY);	0
1685574	1682700	using FormView to insert	protected void frm_DataBound(object sender, EventArgs e)\n{\n    if (frm.CurrentMode == FormViewMode.Edit)//whatever your mode here is.\n    {\n        TextBox txtYourTextBox = (TextBox)frm.FindControl("txtYourTextBox");\n        txtYourTextBox.Text// you can set here your Default value\n    }\n}	0
34188736	34188717	Index and length must refer to a location in the string c#	int len = Math.Min(totalMarginMonth.ToString().Length, 5);\nc1.Text = totalMarginMonth.ToString().Substring(0, len);	0
11482078	10932121	listbox scroll to end in wp7	lstbox.Dispatcher.BeginInvoke(() =>\n                {\n                    lstbox.ItemsSource = null;\n                    lstbox.ItemsSource = lstContactModel;\n                    var Selecteditem = lstbox.Items[lstbox.Items.Count - 1];\n                    lstbox.ScrollIntoView(Selecteditem);\n                    lstbox.UpdateLayout();\n                });	0
12480690	12480534	How to compile c#/c++ files from Java Application	Runtime.getRuntime().exec()	0
23716514	23713130	During OnActionExecuting for Web API call - How to map to controller/action class from route string to read action attributes	public class Somefilter : ActionFilterAttribute\n    {\n        public override void OnActionExecuting(HttpActionContext actionContext)\n        {\n            var controller = actionContext.ControllerContext.Controller;\n            var someFilterattributes = actionContext.ActionDescriptor.GetCustomAttributes<Somefilter>()\n            var otherAttributes = actionContext.ActionDescriptor.GetCustomAttributes<Other>()\n        }\n    }	0
1373970	1373965	Store a xml inside a compiled DLL	Assembly.GetManifestResourceStream	0
8366040	8365997	How to load and read XML documents	XmlDocument doc = new XmlDocument();\n        doc.Load(spath);\n        foreach (XmlElement xe in doc.DocumentElement.SelectNodes("/Snippets/Snippet"))\n        {\n            string sName = xe.Attributes["name"].Value;\n            string sCode = xe.SelectSingleNode("/SnippetCode").InnerText;\n            listBox1.Items.Add(snippetName);\n            snippets.Add(sCode);\n        }	0
3958925	3958638	Cannot select checkbox in a databounded DataGridView	private void Form1_Load(object sender, EventArgs e)\n    {\n        DataGridViewCheckBoxColumn ck = new DataGridViewCheckBoxColumn();\n        dataGridView1.Columns.Insert(0,ck);\n    }	0
2987576	2987559	Check if a file is open	protected virtual bool IsFileinUse(FileInfo file)\n{\n     FileStream stream = null;\n\n     try\n     {\n         stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);\n     }\n     catch (IOException)\n     {\n         //the file is unavailable because it is:\n         //still being written to\n         //or being processed by another thread\n         //or does not exist (has already been processed)\n         return true;\n     }\n     finally\n     {\n         if (stream != null)\n         stream.Close();\n     }\n     return false; \n}	0
10854273	10850412	EntityDataSource create a where clause	var objectContext = ((IObjectContextAdapter)myDbContext).ObjectContext;	0
12958666	12958410	c# how can i click button in webbrowser ducument if the element has on ID?	var elems = webBrowser1.Document.InvokeScript("document.querySelectorAll('some-css-selector')");	0
19253612	19253459	How do you create a Datatable in wpf?	private void CreateDataTable()\n    {\n        System.Data.DataTable dt = new DataTable("MyTable");\n        dt.Columns.Add("MyColumn", typeof (string));\n        dt.Rows.Add("row of data");\n    }	0
8400887	8400635	How to get a resource path as a string from the project folder - WP7	var rs = Application.GetResourceStream(new Uri("1.xml", UriKind.Relative));\nStreamReader sr = new StreamReader(rs.Stream);\nstring s = sr.ReadToEnd();	0
922133	922013	Mocking a connection to a data source inside a function with Moq?	DateTime myDate = DateTime.Now;\n\nDataCollection tags = new DataCollection();\n\nMock<IDataReaderPlugin> dataReaderPlugin = new Mock<IDataWriterPlugin>();\ndataReaderPlugin.Setup(drp => drp.SnapshotUtc(It.IsAny<string[]>(), myDate)).Returns(tags);\n\nMock<IDataWriterPlugin> dataWriterPlugin = new Mock<IDataWriterPlugin>();\ndataWriterPlugin.Setup(dwp => dwp.Write(tags);    \n\nMyObject mo = new MyObject();\nmo.Execute();\n\nmock.Verify(foo => foo.Write(tags));	0
32023215	32023189	How to recognize operators in a string	var str = "=1.0.5";\nvar regex = new Regex("([<>=!]+)(.*)");\nvar result = regex.Match(str);\nConsole.WriteLine(result.Groups[1].Value);\nConsole.WriteLine(result.Groups[2].Value);	0
23078430	23078246	Printing values one by one	Console.WriteLine(Environment.NewLine + "Enter your name:" + s + Environment.NewLine + "Enter your address:" + n + Environment.NewLine + "Enter your phone number:" + m + Environment.NewLine + "Enter your dob:" + p);	0
24629450	24629354	select values at specified indices in a list	listIn = ind.Select(i => listIn[i]).ToList();	0
6935280	6139455	Retrieve a list of entites from CRM 2011, each with all of their related entities	from rule in EmailMatchingRule.Include("EmailMatchingRuleField")\nselect rule	0
16488810	16488623	unit testing to validate a password	Assert.AreEqual(status, MembershipCreateStatus.Success);\n\n var isAuthenticated = Membership.ValidateUser(user.Username, "12345");\n\n Assert.IsTrue(isAuthenticated);\n Assert.AreEqual(user.UserName, "testUserX");\n Assert.AreEqual(user.Email, "test.userx@abc.com");	0
4300845	4291409	How include a image in devexpress datagrid	private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)\n{\n    if (e.Column == colImage1 && e.IsGetData) {\n        string someValueFromDatabase = (string)gridView1.GetRowCellValue(e.RowHandle, colOne);\n        if (someValueFromDatabase == "a") {\n            //Set an icon with index 0\n            e.Value = imageCollection1.Images[0];\n        } else {\n            //Set an icon with index 1\n            e.Value = imageCollection1.Images[1];\n        }\n    }\n}	0
4381843	4381829	print double with digits after decimal point	var digits = 4;\nvar myDouble = Math.PI;\n\nvar formattedValue = myDouble.ToString("N" + digits.ToString(),\n    CultureInfo.CurrentCulture);	0
30627542	30626913	how can i get the value of index in listbox?	object selected = listBox1.Items[index];	0
2431403	2431358	Access entire urls for a particular keyword	HtmlDocument doc = new HtmlDocument();\ndoc.Load("file.htm");\nIEnumerable<HtmlNode> links = doc.DocumentElement.SelectNodes("//a[@href]");	0
23892390	23892289	LINQ Expression - Same value no more than twice	var extractedList = (from n1 in numList\n                         from n2 in numList\n                         from n3 in numList\n                         from n4 in numList\n                         where n1 + n2 + n3 + n4 > 80 && \n                             new int[]{n1, n2, n3, n4}\n                                 .GroupBy(x => x)\n                                 .Max(g => g.Count()) <= 2 \n                         select new { n1, n2, n3, n4, Rnd = rnd.NextDouble() })\n                         .OrderBy(z => z.Rnd)\n                         .Take(10)\n                         .ToList();	0
10483396	10483314	How to get full path of StreamWriter	string fileName = "relative/path.txt";\nstring fullPath = Path.GetFullPath(fileName);	0
19480423	19479935	How to copy more than one folder into another folder?	for (int i = 0 ; i < pathList.Count; i++)\n{\n   sourceDirectory = pathList.ElementAt(i);\n   targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog\n   dirSource = new DirectoryInfo(sourceDirectory);\n\n   string targetPath = target.Fullname+\n                  Path.DirectorySeparatorChar+\n                  sourceDirectory.Split(Path.DirectorySeparatorChar).Last());\n\n   Directory.CreateDirectory(targetPath);\n\n   dirTarget = new DirectoryInfo(targetPath);\n\n   CopyAll(dirSource, dirTarget);                \n }	0
896544	896533	how to match table value to a text box value using c#	while(Dreader.Read())\n{\n    if(Dreader["_password"].ToString()==txtbox.text)\n    {\n    objectofform.show()\n    }\n}	0
31238791	31238727	how to get the password of membership users in asp.net	MembershipUser usr = Membership.GetUser(username);\nstring resetPwd = usr.ResetPassword();\nusr.ChangePassword(resetPwd, newPassword);	0
26716873	26715565	Binding to a dictionary and create key	Mode=TwoWay	0
22782950	22781533	Login controller redirecting does not show page	success: function (response) {\n   alert("if this test dialog appears, so page will redirect");\n\n   //just add this line:\n   window.location.href = '@Url.Action("Index", "HomePage")';\n\n},	0
2998841	2998827	Microsoft membership management, multiple instances in the same database	applicationName="MyApplication"	0
5967767	5242511	Alter Sender email address - WebDav	strText = "From: " & <address of manager> & vbNewLine & _\n            "To: " & strTo & vbNewLine & _	0
1906698	1906631	C# how to write Regular Expression	class Program\n{\n    static void Main() \n    {\n        string s = @"/Pages 2 0 R/Type /Catalog/AcroForm\n/Count 1 /Kids [3 0 R]/Type /Pages\n/Filter /FlateDecode/Length 84";\n\n        var regex = new Regex(@"[\/]([^\s^\/]*)[\s]");\n        foreach (Match item in regex.Matches(s))\n        {\n            Console.WriteLine(item.Groups[1].Value);\n        }\n\n    }\n}	0
10142040	10137305	Linq to Entities Inner Join to datagrid	from a in db.Artist\njoin am in db.ArtistMovie on a.ArtistID equals am.ArtistID\njoin m in db.Movie on am.MovieID equals m.MovieID\nselect new {\n    MovieName = m.MovieName,\n    Year = m.Year,\n    ArtistName = a.ArtistName,\n    Age = a.Age\n};	0
11555920	11555721	AutoMapper Map If Not Null, Otherwise Custom Convert	Mapper.CreateMap<Foo, Foo2>()\n   .ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map<Bar,Bar2>(src.Bar)))	0
20643384	20643347	SQLCommand with Parameter no longer updates my table	string q = "update table set sqla=@para where sqlb=@parb and sqlc=@parc";	0
16398554	16398514	Removing values from a dictionary using loop	foreach (var archive in dictArchivedTitles)\n{\n    if(dictAllTheFiles.ContainsKey(archive.Key)\n        dictAllTheFiles.Remove(archive.Key);\n}	0
18077189	18076911	How to change the data layout of a data table with LINQ	var result =  dataSet.Tables["reportColumns"].AsEnumerable().GroupBy(x => x.Field<string>("Object"))\n    .Select(g => new\n    {\n        ColumnName = g.Key,\n        DefaultColumn = g.FirstOrDefault(p => p.Field<string>("Attribute") == "DefaultColumn").Field<string>("Value"),\n        Label = g.FirstOrDefault(p => p.Field<string>("Attribute") == "Label").Field<string>("Value"),\n        Type = g.FirstOrDefault(p => p.Field<string>("Attribute") == "Type").Field<string>("Value"),\n        Standard = g.FirstOrDefault().Field<int>("Standard")\n    }).ToList();	0
14848213	14836311	Validating textbox in Server Control using RequiredFieldValidator	_textBoxName.ID = "Name_" + UniqueID.Replace('$', '_')	0
2930433	2929882	Control of forward and backward button of browser	if (User.Identity.IsAuthenticated)\n{\n//Code to redirect to some other page\n}	0
12704765	12704578	Is it possible in a static method to call another static method via Parallel.For with different parameters?	public partial class Form1: Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n            this.Load += new EventHandler(Form1_Load);\n        }\n\n        void Form1_Load(object sender, EventArgs e)\n        {\n            Test();\n        }\n\n        static int Function1(int parameter1, int parameter2)\n        {\n            return (parameter1 + parameter2);\n        }\n\n        static void Test()\n        {\n            int[] nums = Enumerable.Range(0, 1000000).ToArray();\n            long total = 0;\n\n            // Use type parameter to make subtotal a long, not an int\n            Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>\n            {\n                subtotal += (nums[j] + Function1(1,2));\n                return subtotal;\n            },\n                (x) => Interlocked.Add(ref total, x)\n            );\n\n            MessageBox.Show(string.Format("The total is {0}", total));\n        }\n    }	0
11353985	11353959	LINQ: find items in a list that have frequency = 1	from p in PersonList\n// Group by name and zip\ngroup p by new { p.firstName, p.lastName, p.zipcode } into g\n// Only select those who have unique names within zipcode\nwhere g.Count() == 1\n// There is guaranteed to be one result per group: use it\nlet p = g.FirstOrDefault()\nselect new {\n    fName = p.firstname,\n    lName = p.lastname,\n    zip3 = p.zipcode,\n    id = p.id\n}	0
4167292	4167116	Determining Write Permissions to the Application Folder	%userprofile%\AppData\Local\VirtualStore\Program Files	0
1681792	1660486	How to add contacts into Calendar using Redemption.dll ? using C#	RDOSession session = new RDOSession();\nsession.Logon(System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, true, System.Reflection.Missing.Value, false);\n\nRDOFolder calendar = session.GetDefaultFolder(rdoDefaultFolders.olFolderCalendar);\n\nRDOAppointmentItem oAppointment = (RDOAppointmentItem)calendar.Items.Add(rdoItemType.olAppointmentItem);\n\noAppointment.Subject = "This is a test subject";\noAppointment.Body = "This is a test body";\noAppointment.Start = DateTime.Now;\noAppointment.End = DateTime.Now.AddMinutes(15);\noAppointment.ReminderSet = true;\noAppointment.ReminderMinutesBeforeStart = 30;\noAppointment.Importance = (int)rdoImportance.olImportanceNormal;\noAppointment.BusyStatus = rdoBusyStatus.olBusy;\n\noAppointment.Save();\n\noAppointment = null;\ncalendar = null;\nsession.Logoff();\nsession = null;	0
17625391	17625363	C# Regex search string for text including surrounding brackets	Regex myRegexE10 = new Regex(@"\[\bE1010\b\]")	0
2548811	2547539	Nhibernate transactions:Avoiding Nhibernate dependency in the service layer	public interface IDbContext {\n    void CommitChanges();\n    IDisposable BeginTransaction();\n    void CommitTransaction();\n    void RollbackTransaction();\n}\n\npublic class DbContext : IDbContext {\n    private readonly ISession _session;\n\n    public DbContext(ISession session)\n    {\n        Check.RequireNotNull<ISession>(session);\n        _session = session;\n    }\n\n    public void CommitChanges() { _session.Flush(); }\n\n    public IDisposable BeginTransaction() { return _session.BeginTransaction(); }\n\n    public void CommitTransaction() { _session.Transaction.Commit(); }\n\n    public void RollbackTransaction() { _session.Transaction.Rollback(); }\n\n}	0
7166641	7166514	How to delete specific node by attribute from XML?	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load("Parties.xml");\nXmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[@CustomerID='2']");\nt.ParentNode.RemoveChild(t);\nxmlDoc.Save();	0
8159302	8159188	regex to exclude @import urls in css file	(?<!@import\s*)url	0
30305073	30304533	net4 Enable/Disable NavigateUrl in Hyperlink	if (EndDate.SelectedIndex == 0)	0
34400731	34361156	How can I get the value from a child Dictionary created with json data	{\n                //Get the json and convert it to a Dictionary note the new dictionary will contain nested dictionaries\n                string json = "However You get it";\n                var jss = new JavaScriptSerializer();\n                var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);\n                //Loop thru the nested Dictionary to get the values you need\n                for (int i = 0; i < dict.Values.Sum(x =>x.Count); i++)\n                {\n                    foreach (var item in dict)\n                    {\n\n                        Label2.Text = (dict["data"][i]["attributes"]["firstName"]);\n\n                    }\n                }\n\n            }	0
23227660	23227021	In the Repository Pattern, where should I implement a Distinct method?	public interface IVehicleRepository : IRepository<Vehicle>{\n    IEnumerable<int> GetDistinctVehicle();\n}\n\npublic VehicleRepository : EfRepository<Vehicle>, IVehicleRepository{\n\n    public VehicleRepository(DbContext context) : base(context)\n    {\n    }\n\n\n    public IEnumerable<int> GetDistinctVehicle(){\n        Context.Set<Vehicle>().Select(x=> x.ModelYear).Distinct();\n    }\n\n}	0
28147039	28143102	exporting data to excel using NPOI in c#	application/vnd.openxmlformats-officedocument.spreadsheetml.sheet	0
18994285	18994264	Referencing a field by string	Type type = ActionPanel.ChangeSelectedActionBundle.GetType();\nPropertyInfo property = type.GetProperty(ButtonName);\nobject value = property.GetValue(ActionPanel.ChangeSelectedActionBundle, null);	0
32499273	32499163	How do I get a string representation from a nullable type?	var T = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");\nType nullableType = Nullable.GetUnderlyingType(T);\nstring typeName = nullableType != null ? nullableType.Name + "?" : T.Name;	0
25441400	25441352	Parse key=value with regular expression	(.*?)\s*=\s*([^\s]+)	0
13683500	13682743	To do some validation in the server-side when the node has been clicked in the DevExpress "ASPxTreeList" control	e.Cancel	0
31347842	31347799	Sort Dictionary by key then add all values to list	List<string> customerNames = (from c in customerNamesByIDs \n                              orderby c.Key \n                              select c.Value).ToList();	0
19695034	19694839	Doing a bulk insert with C#?	// Set up the column mappings by name.\nSqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping("ProductID", "ProdID");\nbulkCopy.ColumnMappings.Add(mapID);	0
2692568	2692028	How to pop Toolwindow in a defined position	public void Show(kTextBox source)\n{\n    Point control_origin = source.PointToScreen(new Point(0, 0));\n    this.Location = new Point(control_origin.X, control_origin.Y);\n    base.Show();\n}	0
22674556	22666843	How to consume a method of web service (asmx) that receives and returns xml	xml_result.LoadXml((WEBS.Cars(XElement.Parse(xml_send.OuterXml))).ToString());	0
429317	429225	Capture output from unrelated process	Process[] p = Process.GetProcessesByName("myprocess.exe");\n\n    StreamReader sr = new StreamReader(p[0].StandardOutput);\n\n    while (sr.BaseStream.CanRead)\n    {\n        Console.WriteLine(sr.ReadLine());\n    }	0
27282598	27282366	How to set the default page and URL in RouteConfig file	routes.MapRoute(\n  name: "Project",\n  url: "Project/{action}/{projectId}",\n  defaults: new { controller = "Project", action = "Index", projectId = UrlParameter.Optional }\n);\n\nroutes.MapRoute(\n  name: "Default",\n  url: "{controller}/{action}/{id}",\n  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }\n);	0
11591264	11591262	How to use getstring in datareader in C#?	List<string> strlst = new List<string>();\nOleDbDataReader dr = cmd.ExecuteReader();\n\nwhile (dr.Read())\n{\n    strlst.Add( Convert.ToString(dr[0]).Substring(0, 5)) ;\n}\nstring[] strarray = strlst.ToArray();	0
6485004	6484796	C# how can i use WMI to create user account in a remote computer	// you need to supply these parameters:\nstring domainName = "domain";\nstring computerName = "computer";\nstring userName = "name";\nstring password = "password";\n\nvar machineDirectory = new DirectoryEntry(@"WinNT://" + domainName + @"/" + computerName + ",computer");\nvar userEntry = machineDirectory.Children.Add(userName, "user");\n\nuserEntry.Invoke("SetPassword", password);\nuserEntry.CommitChanges();	0
10516419	10516089	How can I Get Bitmap From Project Folder?	Server.MapPath( "~/images/default_person.jpg" );	0
17659310	17659218	Custom validating a Model object in MVC	ModelState.AddModelError("someobject.somestring", "String cannot be empty);	0
31233275	31233193	How to seach in C# sql database by LIKE	"SELECT tbPhonebook.* FROM tbPhonebook WHERE Fname LIKE '%"+textBox1.Text+"%'"	0
17115343	17115034	How do I append a dataTable to a GridView?	DataTable schedulesTable1 = GetTableFromSessionOrFromGridView(); // whatever is practical\nDataTable schedulesTable2 = Transporter.GetDataTableFromAPI(callingURL);  // new table\nschedulesTable1.Merge(schedulesTable2);\ngvSchedules.DataSource = schedulesTable1;\ngvSchedules.DataBind();	0
21282752	21282685	Open RichTextFile without using DialogBox	this.NotePad.Rtf = System.IO.File.ReadAllText(fileName)	0
24110907	24104929	c# How to validate when pasting into textbox	private void phoneNumberValidity(object sender, EventArgs e)\n    {\n        counter4 = Convert.ToInt32(IsPhoneNumberCorrect(textBoxPhoneNumber.Text));\n        pictureBoxPhoneNumber.Image = imageList1.Images[counter4];\n        if (Regex.IsMatch(textBoxPhoneNumber.Text, "[^0-9-+]"))\n        {\n            Regex regex = new Regex("[^0-9-+]");\n            string output = regex.Replace(Clipboard.GetText(), "");\n            textBoxPhoneNumber.Text = output;\n        }\n        checkIfOk();\n        textBoxPhoneNumber.Focus();\n        }	0
24058584	24058492	How to extract connection string from another application's app.config / web.config file in C#	private const string configFile = @"C:\Directory\SubDirectory\file.config";\n\npublic static string GetConnectionString()        \n{ \n    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = configFile }; \n\n    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);\n\n    return config.ConnectionStrings.ConnectionStrings["MYConnectionString"].ConnectionString;\n}	0
4348030	4348003	Using environment variable in a file path	string path = Environment.ExpandEnvironmentVariables(value);	0
2388011	2387916	Looking for a Histogram Binning algorithm for decimal data	public static List<int> Bucketize(this IEnumerable<decimal> source, int totalBuckets)\n{\n    var min = source.Min();\n    var max = source.Max();\n    var buckets = new List<int>();\n\n    var bucketSize = (max - min) / totalBuckets;\n    foreach (var value in source)\n    {\n        int bucketIndex = 0;\n        if (bucketSize > 0.0)\n        {\n            bucketIndex = (int)((value - min) / bucketSize);\n            if (bucketIndex == totalBuckets)\n            {\n                bucketIndex--;\n            }\n        }\n        buckets[bucketIndex]++;\n    }\n    return buckets;\n}	0
19946227	19945806	How to call a base-class operator?	class A\n{\n    public virtual A Plus(A right)\n    {\n        return new A();\n    }\n\n    public static A operator + (A left, A right)\n    {\n        //Calculations and handle left == null case.\n        return left.Plus(right);\n    }\n}\n\nclass B : A\n{\n    public override B Plus(B right)\n    {\n        //Calculations\n        base.Plus(right);\n        return new A();\n    }\n}	0
9251984	9246999	Set max length of strings in radgrid / limit string length in radgrid with autogenerate columns	public static void SM_Dump_TruncStrings(ref List<myDataType> dump, int maxLength, bool addEllipses)\n    {\n        foreach (var sm in dump)\n        {\n            PropertyInfo[] infos = sm.GetType().GetProperties();\n            foreach (var info in infos)\n            {\n                if (info.PropertyType == typeof(string))\n                {\n                    var origValue = info.GetValue(sm, null) as string;\n                    if (origValue != null && origValue.Length > maxLength)\n                    {\n                        var newVal = origValue.Substring(0, maxLength);\n                        if (addEllipses)\n                            newVal += "...";\n                        info.SetValue(sm, newVal, null);\n                    }\n                }\n            }\n        }\n    }	0
12087580	12085723	I cann't get all ARecords of the Dns Zone	ManagementScope oMs = new ManagementScope("\\\\" + dnsServer + "\\root\\microsoftdns"); \nstring strQuery = "select * from microsoftdns_" + recType + "type where containername = '" + domain + "'"; \nManagementObjectSearcher oS = new ManagementObjectSearcher(strQuery); oS.Scope = oMs; \nManagementObjectCollection oRc = oS.Get();	0
22787553	22786776	Drawing bitmap on screen	e.UseDefaultCursors = false;\nCursor.Current = MyCursor;	0
31980124	31979688	Splitting a text document and matching only the first string	int number;\nvar rx = new Regex("<span class=\"friendPlayerLevelNum\">([0-9]+)</span>");\nvar match = rx.Match(html);\n\nif(match.Success && Int32.TryParse(match.Groups[1].Value, out number))\n    Console.WriteLine("Got the number: {0}", number);\nelse\n    Console.WriteLine("not found")	0
21288708	21288658	check if propertyInfo implements a class	public static bool IsOfType(PropertyInfo member)\n{\n    return typeof(Foo).IsAssignableFrom(member.PropertyType);\n}	0
18953672	18946788	How to add or subtract very large numbers without bigint in C#?	var s1 = "1234";\nvar s2 = "5678";\nvar carry = false;\nvar result = String.Empty;\n\nfor(int i = s1.Length-1;i >= 0; i--)\n{\n    var augend = Convert.ToInt32(s1.Substring(i,1));\n    var addend = Convert.ToInt32(s2.Substring(i,1));\n    var sum = augend + addend;\n    sum += (carry ? 1 : 0);\n    carry = false;\n    if(sum > 9)\n    {\n        carry = true;\n        sum -= 10;\n    }\n\n    result = sum.ToString() + result;\n}\n\nif(carry)\n{\n    result = "1" + result;\n}\n\nConsole.WriteLine(result);	0
3414929	3414900	How to get a Char from an ASCII Character Code in c#	char c1 = '\u0001';\nchar c1 = (char) 1;	0
13359210	13348963	Joining two tables with one to many relatipnship in entity framework code first	var result = Menus.Where(menu => menu.ID == id)\n                  .Select(menu => menu.Tasks)\n                  .FirstOrDefault();	0
17584815	17584451	Arranging in order with reference to a column	StackPanel sp=new StackPanel();\n    foreach(Model.questionhint qhm in lstQuestionHints)\n    {\n    StackPanel sp1=new StackPanel(){Orientation=Orientation.Horizontal};     \n        TextBlock tb = new TextBlock();\n        tb.Text = qhm.QuestionContent;              \n        tb.FontWeight = FontWeights.Bold;\n        tb.FontSize = 24;\n        sp1.Children.Add(lbl);\n\n        if (qhm.Option1.Trim().Length > 0 &&\n            qhm.Option2.Trim().Length > 0)\n        {\n            ComboBox cb = new ComboBox();\n            cb.Items.Add(qhm.Option1);\n            cb.Items.Add(qhm.Option2);\n            cb.Width = 200;\n            sp1.Children.Add(cb);\n        }\n       sp.Children.Add(sp1); \n    }\n    WrapPanelTest.Children.Add(sp);	0
30651756	30651655	How to get value from @Html.CheckBoxFor()	public ActionResult GetValues([Bind(Include = "cb")] yourmodelName yourmodelobject)\n        {\n            ViewBag.Value = yourmodelobject.cb\n           return View();\n        }	0
9005045	9004586	C# can I Scrape a webBrowser control for links?	HtmlWindow window = webBrowser1.Document.Window;\nstring str = window.Document.Body.OuterHtml;\n\nHtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();\nHtmlDoc.LoadHtml(str);\n\nHtmlAgilityPack.HtmlNodeCollection Nodes = HtmlDoc.DocumentNode.SelectNodes("//a");\n\nforeach (HtmlAgilityPack.HtmlNode Node in Nodes)\n{\n    textBox1.Text += Node.OuterHtml + "\r\n";\n}	0
31942630	31942343	C# progressbar IsIndeterminate while exectue a function	async void Button1_Click(object sender, RoutedEventArgs e)\n{\n    progressBar1.IsIndeterminate = true;\n    try\n    {\n        await Task.Factory.StartNew(() =>\n        {\n           scrape();\n        });\n    }\n    catch(AggregateException ae)\n    {}\n    finally\n    {\n         progressBar1.IsIndeterminate = false;\n    }\n}	0
14283007	14268525	Accessing Global Session Key in Umbraco	umbraco.library:Session(PMNInstructor)	0
6332529	6332472	RegEx to replace more than one hypen with one hypen in a string ? asp.net c#	string inputString = "Flat---Head-----Self-Tap-Scr---ews----3-x-10mm-8pc";\nstring outputString = Regex.Replace(inputString , @"-+", "-", RegexOptions.None);	0
3209379	3209217	Detect both left and right mouse click at the same time?	public bool m_right = false;\n    public bool m_left = false;\n\n    private void MainForm_MouseDown(object sender, MouseEventArgs e)\n    {\n        m_objGraphics.Clear(SystemColors.Control);\n\n        if (e.Button == MouseButtons.Left)\n            m_left = true;\n        if (e.Button == MouseButtons.Right)\n            m_right = true;\n\n        if (m_left == false || m_right == false) return;\n        //do something here\n    }\n\n    private void MainForm_MouseUp(object sender, MouseEventArgs e)\n    {\n        if (e.Button == MouseButtons.Left)\n            m_left = false;\n        if (e.Button == MouseButtons.Right)\n            m_right = false;\n     }	0
3723602	3723492	C# library to take screenshots?	var bounds = Screen.PrimaryScreen.Bounds;\nusing (var bmp = new Bitmap(bounds.Width,\n                            bounds.Height,\n                            PixelFormat.Format32bppArgb))\nusing (var gfx = Graphics.FromImage(bmp))\n{\n    gfx.CopyFromScreen(bounds.X,\n                       bounds.Y,\n                       0,\n                       0,\n                       bounds.Size,\n                       CopyPixelOperation.SourceCopy);\n    bmp.Save("shot.png");\n}	0
29501221	29501093	Searching data in a list using linq	var bookings = context.Bookings\n                      .Where(b => b.BookingItems\n                                   .Any(bi => !lotItemIdList.Contains(bi => bi.BookingItemId)));	0
17036297	17034127	Mobile Broadband C# interface to manage Profiles	MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();\nIMbnInterfaceManager infManager = (IMbnInterfaceManager)mbnInfMgr;\n\n//obtain the IMbnInterface passing interfaceID\nstring interfaceID = ?{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}?;\n\nIMbnInterface mbnInterface= infMgr.GetInterface(interfaceID);\n\nMbnConnectionProfileManager mbnProfMgr = new MbnConnectionProfileManager();\nIMbnConnectionProfileManager profileManager = \n                                  (IMbnConnectionProfileManager)mbnProfMgr;\n\nIMbnConnectionProfile[] profArr = \n(IMbnConnectionProfile[])profileManager.GetConnectionProfiles(mbnInterface);	0
6282481	6277701	iTextSharp produce PDF from existing PDF template	void fillPDF( String filePath, Map<String, String> fieldVals ) {\n  PdfReader reader = new PdfReader(myFilePath);\n\n  PdfStamper stamper = new PdfStamper( reader, outputFileStream );\n  stamper.setFormFlattening(true);\n\n  AcroFields fields = stamper.getAcroFields();\n\n  for (String fldName : fieldVals.keySet()) {\n    fields.setField( fldName, fieldVals.get(fldName) );\n  }\n\n  stamper.close();\n}	0
6820214	6817809	How to include unobtrusive javascript validation in your HtmlHelpers?	GetUnobtrusiveValidationAttributes()	0
3825537	3825270	Unity auto-factory with params	public class TestLog\n{\n    private Func<string, ILog> logFactory;\n\n    public TestLog(Func<string, ILog> logFactory)\n    {\n         this.logFactory = logFactory;\n    }\n    public ILog CreateLog(string name)\n    {\n        return logFactory(name);\n    }\n}\n\nContainer.RegisterType<Func<string, ILog>>(\n     new InjectionFactory(c => \n        new Func<string, ILog>(name => new Log(name))\n     ));\n\nTestLog test = Container.Resolve<TestLog>();\nILog log = test.CreateLog("Test Name");	0
19426532	19426409	Matching RegEx with specific end phrase but exclude from capture	(?=\s*Private & Confidential)	0
27992233	27188822	Huffman Tree, Wrong Encoding	.OrderByDescending	0
5241552	5241479	Drawing on a Image in C#	Image imgNew = Clipboard.GetImage(); //Getting the image in clipboard\nGraphics g = pictureBox1.CreateGraphics();\ng.DrawImage(imgNew, 0, 0, 150, 100);	0
15909464	15904438	Getting name for a WPF shape from variable	List<Ellipse> myEllipses = new List<Ellipse>();\n\nPrivate void A1_Click(object sender, RoutedEventArgs e)\n{\n    var myEllipse = new Ellipse();\n    myEllipses.Add(myEllipse);\n    ...\n}	0
8075290	7486824	How do I overwrite a file in MongoDB Gridfs?	server[dbName].GridFS.Delete(FileName);\nserver[dbName].GridFS.Upload(localName, FileName)	0
23424983	23424844	Visual C#: Move multiple files with the same extensions into another directory	//Assume user types .txt into textbox\nstring fileExtension = "*" + textbox1.Text;\n\nstring[] txtFiles = Directory.GetFiles("Source Path", fileExtension);\n\nforeach (var item in txtFiles)\n{\n   File.Move(item, Path.Combine("Destination Directory", Path.GetFileName(item)));\n}	0
9230752	9230512	Use of expando objects in views?	foreach(var prop in item as IDictionary<string, object>)\n{\n    <tr>\n        <td>\n            @prop.Key\n            @prop.Value\n        </td>\n    </tr>\n}	0
17727622	17727598	Retrieve the two first elements that match a condition	plotter.Model.Series.Where(x => x.IsSelected).Take(2);	0
23883869	23874028	How to find out if CheckBox was clicked on DataGrid.GotFocus()	bool isMouseOver = checkBox.InputHitTest(Mouse.GetPosition((IInputElement) checkBox)) != null;	0
8035800	8011297	MSScriptControl.ScriptControlClass - access a sub-object of the main object	[ComVisible(true)]\npublic class AAA\n{\n    public BBB Bbb { get; set; }\n}\n\n[ComVisible(true)]\npublic class BBB\n{\n    public CCC Ccc { get; set; }\n}\n\n[ComVisible(true)]\npublic class CCC\n{\n    public string MyString { get; set; }\n}	0
5300115	5300068	Manage null with LINQ	where String.Equals(p.LastName, lastName, StringComparison.OrdinalIgnoreCase)	0
8712899	8705388	How to export a datatable to a previous created PDF file while specifying a page to do that? (or creating a new page)	for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n                        {\n                            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)\n                            {\n                                datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;\n                                datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;\n                                Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));\n                                datatable.AddCell(phrase);\n                            }\n                        }\n\n+                        PdfContentByte content = pdfStamper.GetUnderContent(2);\n\n+                        datatable.WriteSelectedRows(0, -1, 70.0f, 400.0f, content);	0
33744272	33702624	Coded UI thinks control is in a different position	var ret=new Rectangle();\nGetWindowRect(obj.WindowHandle, ref ret);\nMouse.Hover(new Point(ret.X, ret.Y));	0
11339757	11339711	Namespaces inside a global namespace C#	namespace MyDll.General \n{ \n    ... \n}	0
12562722	12562650	Determine all indexes of an element appearing more than once in an array using c#	int[] indexes = input.Select((item, index) => new { item, index })\n                     .Where(x => x.item == "A")\n                     .Select(x => x.index)\n                     .ToArray();	0
13628648	13628481	Calling Awaitable Methods in Property Accessor [Windows Store Apps/Metro Apps]	private async Task SetAlbumSourceAsync()\n{\n    bmp = new BitmapImage();\n    var source = await AlbumThumbnail.OpenReadAsync();\n    bmp.SetSource(source);\n    RaisePropertyChanged("AlbumSource");\n}\n\nBitmapImage bmp;\npublic BitmapImage AlbumSource\n{\n    get\n    {\n        if (bmp == null) // might need a better sync mechanism to prevent reentrancy but you get the idea\n            SetAlbumSourceAsync();\n\n        return bmp;\n    }\n}	0
7800940	7800886	Need to write a Generic method which returns a list of data objects obtained from wrapper objects (passed to it)	public interface IFrontEndEntity<TEntity>\n{\n    TEntity GetEntity();\n}\npublic static class FrontEndExtensions\n{\n    public static IEnumerable<TEntity> GetEntities<TEntity>(this IEnumerable<IFrontEndEntity<TEntity>> frontEndItems)\n    {\n        return frontEndItems.Select(a => a.GetEntity());\n    }\n}\npublic class Dog\n{\n}\npublic class DogFrontEnd : IFrontEndEntity<Dog>\n{\n    public Dog Entity { get; set; }\n    public Dog GetEntity()\n    {\n        return Entity;\n    }\n}\npublic class Main\n{\n    public void Run()\n    {\n        IEnumerable<DogFrontEnd> dogFronEnds = new List<DogFrontEnd>();\n        IEnumerable<Dog> dogs = dogFronEnds.GetEntities();\n    }\n}	0
33112050	33111978	While loop to confirm user input	bool stop = false;\nwhile (!stop)\n{\n    Console.WriteLine("Please verify your birth date");\n    userValueTwo = Console.ReadLine();\n\n     try\n     {\n        DateTime birthdayTwo = DateTime.Parse(userValueTwo);\n     }\n     catch\n     {\n         Console.WriteLine("You did not enter a valid format.");\n         Console.ReadLine();\n     }\n\n     if (userValueTwo == userValue)\n     {\n         Console.WriteLine("Birth date confirmed.");\n         Console.ReadLine();\n         stop = true;\n     }\n\n    else \n    {\n        Console.WriteLine("Your birthday did not match our records. Please try again");\n        Console.ReadLine();\n    }\n}	0
1694438	1694418	Troubles creating a proper lambda expression	var xParam = Expression.Parameter(typeof(E), "x");\n  var propertyAccessExpr = Expression.Property(xParam, this._KeyProperty);\n  var lambdaExpr = Expression.Lambda<Func<E, bool>>(propertyAccessExpr, xParam);	0
31791425	31791356	MySqlException when passing table name as a parameter to MySqlCommand	string query = string.Format("SELECT * from {0}", sym);  \n cmd.CommandText = query; \n MySqlDataReader myresults = cmd.ExecuteReader();	0
20673697	20673086	Refine Enumerable LINQ WHERE statement with repeated parameters	return\n    from q in pSource\n    let sc = q.StaffContracts\n        .OrderByDescending(p => p.SignedDate)\n        .FirstOrDefault()\n    where sc != null\n    let ts = sc.Timespan\n    let sd = sc.SignedDate\n    where ts.HasValue\n    where sd.HasValue\n    where (sd.Value.AddMonths(ts.Value) - now).TotalDays <= value\n    select q;	0
20044882	20044431	Bitmap deep copy changing PixelFormat	Bitmap img = new Bitmap("C:\\temp\\images\\file.jpg");\n\n// Clone the bitmap.\nRectangle cloneRect = new Rectangle(0, 0, img.Width, img.Height);\nSystem.Drawing.Imaging.PixelFormat format =\n    img.PixelFormat;\nBitmap img2 = img.Clone(cloneRect, format);	0
8829110	8829094	How to apply templates to controls in Forms?	public class FormBase : Form\n{\n    protected override void OnLoad(EventArgs e)\n    {\n        base.OnLoad(e);\n        SettingControls();\n    }\n\n    // Declare as virtual to allow inheritors to override\n    public virtual void SettingControls()\n    {\n        // Code here\n    }\n}	0
28963838	28963476	Prevent Listbox selecting item at the very beginning	listBox1.SelectionMode = SelectionMode.None;\n        listBox1.DataSource = dataTable;\n        listBox1.SelectionMode = SelectionMode.One;	0
15994533	15994469	Print the EntityFramework Version at runtime	string version = typeof(DbSet).Assembly.GetName().Version.ToString();	0
19363353	19363270	Edit ParentViewModel elements from Children.xaml.cs	ParentViewModel vm = this.DataContext as ParentViewModel;\nif(vm!=null)\n{\nvm.SomeTextProperty = "Clicked";\n}	0
24332718	24332388	Make ImageView Circular	this.profileImage.InvokeOnMainThread (() => this.profileImage.SetImage (\n            url: new NSUrl (datum.user.profile_picture)\n        )\n    );\n\n// Make Image Profile Image Circular\nCALayer profileImageCircle = profileImage.Layer;\nprofileImageCircle.CornerRadius = 30;\nprofileImageCircle.MasksToBounds = true;	0
4609539	4609458	Add Attributes to root HTML Element of a Custom Control	public override void RenderBeginTag(HtmlTextWriter writer)\n{\n    writer.AddAttribute(HtmlTextWriterAttribute.Class, "[^_^]");\n    base.RenderBeginTag(writer);\n}	0
12516928	12516866	Using Ilmerge to combine multiple dlls in .NET	ilmerge /out:Merged.dll Lib1.dll Lib2.dll	0
31994678	31993266	How do I enable Parts/Components in Unity C# with only a game object in the script	ComponentYouNeed component = gameObject.GetComponentInChildren<ComponentYouNeed>();\ncomponent.enabled = false;	0
9122151	9122094	How to read a line from a file?	void read_one_record(ref int id, ref int stock, ref int published, ref double price, ref string type, ref string title, ref string author)\n    {\n        StreamReader myFile = File.OpenText("Inventory.dat");\n\n        id = int.Parse(myFile.ReadLine());\n        stock = int.Parse(myFile.ReadLine());\n        published= int.Parse(myFile.ReadLine());\n        stock = int.Parse(myFile.ReadLine());\n        price = double.Parse(myFile.ReadLine());\n        type = myFile.ReadLine();\n        title = myFile.ReadLine();\n        author = myFile.ReadLine();\n\n        myFile.Close();\n\n    }	0
30511393	30509587	PointToScreen multiple montors	static class ControlExtensions\n{\n    ///<summary>\n    /// Returns the position of the point in screen coordinates of that control instead\n    /// of the main-screen coordinates\n    ///</summary>\n    public static Point PointToCurrentScreen(this Control self, Point location)\n    {\n        var screenBounds = Screen.FromControl(self).Bounds;\n        var globalCoordinates = self.PointToScreen(location);\n        return new Point(globalCoordinates.X - screenBounds.X, globalCoordinates.Y - screenBounds.Y);\n    }\n}	0
3478814	3478713	Joining a Dictionary to a Datatable	foreach (DataRow row in table.Rows)\n{\n    var networkID = (string)row["Network_ID"];\n    if (input.ContainsKey(networkID))\n    {\n        row["NewKeyColumn"] = networkID;\n        row["NewKeyValue"] = input[networkID]\n    }\n}	0
15115432	15115241	how can i prevent launching my app multiple times?	using System.Diagnostics;\n\nstatic void Main(string[] args)\n{\n   String thisprocessname = Process.GetCurrentProcess().ProcessName;\n\n   if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)\n      return;           \n}	0
14530404	14530333	Updating List of Objects Saving to Database	List<Fighter> item = db.fight.Fighters.ToList<Fighter>();\nitem.ToList().ForEach(c => c.Draw++);\nforeach (var i in item)\n{\n    db.fight.Fighters.AddObject(i);\n}\n\ndb.SaveChanges();	0
14495874	14495755	How can I listen to mouse events of other processes	Windows Hooks	0
14347730	14347513	How to detect if a Word document is password protected before uploading the file to server?	public static Boolean IsProtected(String file)\n{\n    Byte[] bytes = File.ReadAllBytes(file);\n\n    String prefix = Encoding.Default.GetString(bytes.Take(2).ToArray());\n\n    // Zip and not password protected.\n    if (prefix == "PK")\n        return false;\n\n    // Office format.\n    if (prefix == "??")\n    {\n        // XLS 2003\n        if (bytes.Skip(0x208).Take(1).ToArray()[0] == 0xFE)\n            return true;\n\n        // XLS 2005\n        if (bytes.Skip(0x214).Take(1).ToArray()[0] == 0x2F)\n            return true;\n\n        // DOC 2005\n        if (bytes.Skip(0x20B).Take(1).ToArray()[0] == 0x13)\n            return true;\n\n        // Guessing\n        if (bytes.Length < 2000)\n            return false;\n\n        // DOC/XLS 2007+\n        String start = Encoding.Default.GetString(bytes.Take(2000).ToArray()).Replace("\0", " ");\n\n        if (start.Contains("E n c r y p t e d P a c k a g e"))\n            return true;\n\n        return false;\n    }\n\n    // Unknown format.\n    return false;\n}	0
10279424	10251977	Munq property injection of optional dependencies	container.Register<IDatabase>(c =>\n    new Database(c.Resolve<ILogger>())\n    {\n        // Property injection.\n        ErrorHandler = c.Resolve<IErorhandler>()\n    });	0
16339166	16338861	Create a static method that will parse any string to detect special characters and include \ before them	public static string ParseStringForSpecialChars(string stringToParse)\n{\n    const string regexItem = "[^a-zA-Z0-9 ]";\n\n    string stringToReturn = Regex.Replace(stringToParse, regexItem, @"\$&");\n\n    return stringToReturn;\n}	0
782010	781442	Serialize object to XmlDocument	public class MyFault\n{\n    public int ErrorCode { get; set; }\n    public string ErrorMessage { get; set; }\n}\n\npublic static XmlDocument SerializeFault()\n{\n    var fault = new MyFault\n                    {\n                        ErrorCode = 1,\n                        ErrorMessage = "This is an error"\n                    };\n\n    var faultDocument = new XmlDocument();\n    var nav = faultDocument.CreateNavigator();\n    using (var writer = nav.AppendChild())\n    {\n        var ser = new XmlSerializer(fault.GetType());\n        ser.Serialize(writer, fault);\n    }\n\n    var detailDocument = new XmlDocument();\n    var detailElement = detailDocument.CreateElement(\n        "exc", \n        SoapException.DetailElementName.Name,\n        SoapException.DetailElementName.Namespace);\n    detailDocument.AppendChild(detailElement);\n    detailElement.AppendChild(\n        detailDocument.ImportNode(\n            faultDocument.DocumentElement, true));\n    return detailDocument;\n}	0
4821039	4818964	How do you update multiple field using Update.Set in MongoDB using official c# driver?	var update = Update.Set("Email", "jdoe@gmail.com")\n                    .Set("Phone", "4455512");	0
331662	331231	c# gridview row click	if(e.Row.RowType == DataControlRowType.DataRow)\n{\n    e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'";\n}	0
16596423	16595650	Get Image Link From HTML in Windows Store App	var imgLinks = doc.DocumentNode.Descendants("img")\n                 .Select(img => img.Attributes["src"].Value)\n                 .ToList();	0
28595098	28595050	How to keep the "Provider Connection String" separate from the EF (EDMX) metadata information?	void InitContext() {\n\n    String actualConnectionString = ConfigurationManager.ConnectionStrings["server123"].ConnectionString;\n\n    String efConnectionString = String.Format(CultureInfo.InvariantCulture, "metadata=res://*/..;provider connection string={0};.", actualConnectionString);\n\n    _context = new MyEFContext( efConnectionString );\n}	0
29594738	29594523	LINQ to SQL, using subquery with IN operator	var friends_A = from f in entities.Friends\n                   where f.Friend_A != User.Identity.Name\n                   && f.Friend_B == User.Identity.Name\n                   select f.Friend_A;\n\nvar friends_B = from f in entities.Friends\n                   where f.Friend_A == User.Identity.Name\n                   && f.Friend_B != User.Identity.Name\n                   select f.Friend_B;\n\nvar posts = \n     from p in entities.Posts\n     let userName = p.UserName.ToLower()\n     where \n        userName == User.Identity.Name ||\n        friends_A.Concat(friends_B).Contains(userName)\n     orderby \n        p.DateAndTime\n     select new \n     { \n        p.UserName, \n        p.DateAndTime, \n        p.PostText \n     };	0
23862045	23861964	Get a string using regular expressions	Match match = Regex.Match(forReg, @"\,([^,]*)\,");\n            if (match.Success)\n            {\n                string age = match.Groups[1].Value;\n            }	0
8228463	8228319	Converting from engineering notation to double and REGEX, split a string into two parts; numbers and characters	public double ConvertMeasure(string measure)\n    {\n        measure = measure.ToLower().Replace(" ", "");\n        measure = measure.Substring(0, measure.Length - 1);\n        char m = measure.Last();\n        if (char.IsDigit(m))\n            return double.Parse(measure, CultureInfo.InvariantCulture);\n\n        double ret = double.Parse(measure.Substring(0, measure.Length - 1),\n                                  CultureInfo.InvariantCulture);\n        switch (m)\n        {\n            case 'm': return ret / 1E3;\n            case 'u': return ret / 1E6;\n            case 'n': return ret / 1E9;\n            case 'p': return ret / 1E12;\n        }\n        return ret;\n    }	0
25532561	25532262	Mapping a flat list to a hierarchical list with parent IDs C#	public HieraricalCategoryList MapCategories(FlatCategoryList flatCategoryList)\n{\n    var categories = (from fc in flatCategoryList.Categories\n                      select new Category() {\n                          ID = fc.ID,\n                          Name = fc.Name,\n                          ParentID = fc.ParentID\n                      }).ToList();\n\n    var lookup = categories.ToLookup(c => c.ParentID);\n\n    foreach(var c in categories)\n    {\n        // you can skip the check if you want an empty list instead of null\n        // when there is no children\n        if(lookup.Contains(c.ID))\n            c.ChildCategories = lookup[c.ID].ToList();\n    }\n\n    return new HieraricalCategoryList() { Categories = categories };\n}	0
23447540	23447485	C# get, set accessors in combination with array [system.null reference exception]	for (int i = 0; i < vakken.Length; i++)\n{\n     vakken[i] = new Vak(); // this basically allocates memory for your object\n}	0
2760761	2760583	I'd like access to a share on the network!	public partial class MyPage : System.Web.UI.Page\n  { \n    protected void Page_Load(object sender, EventArgs e)\n    {      \n      Thread myThread = new Thread(new ParameterizedThreadStart(ThreadMethod));\n      myThread.Start(HttpContext.Current.User); \n    }\n\n    private void ThreadMethod(object state)\n    {\n      WindowsPrincipal principal = state as WindowsPrincipal;\n\n      WindowsImpersonationContext impersonationContext = null;\n      try\n      {\n        if (principal != null)\n        {\n          Thread.CurrentPrincipal = principal;\n          impersonationContext = WindowsIdentity.Impersonate(((WindowsIdentity)principal.Identity).Token);\n        }\n\n        // Do your user specific stuff here...\n      }\n      finally\n      {\n        if (impersonationContext != null)\n        {\n          impersonationContext.Undo();\n        }\n      }\n    }\n  }	0
13981923	13976666	How to validate DateTime inside TextBoxFor ASP.NET MVC	public class ViewModel\n{\n    [Required]\n    [RegularExpression("\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}:\d{2}")]\n    public string MyDateTime { get; set; }\n\n    public Model ToPoco()\n    {\n        return new Model {\n            MyDateTime = DateTime.Parse(this.MyDateTime, "MM-dd-yyyy H:mm:ss")\n        };\n    }\n}\n\npublic class Model\n{\n    DateTime MyDateTime { get; set; }\n}	0
25568175	25566234	How to convert specific NTSTATUS value to the Hresult?	internal static class NativeMethods\n{\n    [DllImport("ntdll.dll")]\n    public static extern int RtlNtStatusToDosError(int status);\n}\n\ninternal static class Program\n{\n    //#define STATUS_DUPLICATE_OBJECTID        ((NTSTATUS)0xC000022AL)\n    private const int STATUS_DUPLICATE_OBJECTID = unchecked((int) (0xC000022A));\n\n    // HResult that is returned for the STATUS_DUPLICATE_OBJECTID\n    private const int CorrectHrStatusDuplicateObjectid = -2147019886;\n\n    private const int HresultWin32Prefix = unchecked((int)0x80070000);\n\n    static void Main(string[] args)\n    {\n        int code = NativeMethods.RtlNtStatusToDosError(STATUS_DUPLICATE_OBJECTID);\n        int hresult = code | HresultWin32Prefix;\n        Debug.Assert(hresult == CorrectHrStatusDuplicateObjectid, "Must be the same");\n    }	0
6653537	6653398	Only last task runs!	...\nTask validateMarked = Task.Factory.StartNew(() =>\n{\n    foreach (AccountContactViewModel viewModel in selectedDataList)\n    {\n        var localViewModel = viewModel;\n        if (localViewModel != null)\n        {\n            Task validate = Task.Factory.StartNew(\n                () => ValidateAccount(localViewModel),\n                (TaskCreationOptions)TaskContinuationOptions.AttachedToParent);\n        }\n    }\n});\n...	0
14279905	14279704	show all AD group members who are not in a table	var notLoggedIn = from groupMembers in groupPrincipal.Members\n                  where !employeeRepository.Select(p=> p.adUserName).Contains(groupMembers.DisplayName)\n                  select groupMembers;	0
29546243	29356790	How can I get the Multisampling capabilities of a graphics card with SlimDX in C#?	SlimDX.Direct3D11.Device device; //your created device\nSlimDX.DXGI.Format format = SlimDX.DXGI.Format.R8G8B8A8_Unorm; //Replace by the format you want to test, this one is very common still\nfor (int samplecount = 1; samplecount  < SlimDX.Device.MultisampleCountMaximum ; samplecount *= 2)\n{\n     int levels = device.CheckMultisampleQualityLevels(format, samplecount );\n     if (levels > 0)\n     {\n         //you can use a sampledescription of\n         new SampleDescription(samplecount, /* value between 0 and levels -1 */\n     }\n     else\n     {\n         // samplecount is not supported for this format\n     }\n}	0
15841898	15841820	Registering an application to a URI Scheme	public class SingleInstanceController\n    : WindowsFormsApplicationBase\n  {\n    public SingleInstanceController()\n    {\n      // Set whether the application is single instance\n      this.IsSingleInstance = true;\n\n      this.StartupNextInstance += new\n        StartupNextInstanceEventHandler(this_StartupNextInstance);\n    }\n\n    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)\n    {\n      // Here you get the control when any other instance is\n      // invoked apart from the first one.\n      // You have args here in e.CommandLine.\n\n      // You custom code which should be run on other instances\n    }\n\n    protected override void OnCreateMainForm()\n    {\n      // Instantiate your main application form\n      this.MainForm = new Form1();\n    }\n  }\n\n[STAThread]\nstatic void Main(string[] args)\n{    \n  SingleInstanceController controller = new SingleInstanceController();\n  controller.Run(args);\n}	0
24183060	24182867	GridView - Change footer from control in Grid Data Row using javascript	Label lblGrandTotal= (Label)grdProducts.FooterRow.FindControl("lblGrandTotal");	0
9158051	9158037	Why elements defined in a namespace cannot be explicitly declared?	protected class GetDataBL	0
7974432	7922664	How to prevent XtraGrid TextEdit from losing focus when moving cursor beyond contents	private void gridControl1_EditorKeyDown(object sender, KeyEventArgs e)\n    {\n        GridView view = (sender as GridControl).FocusedView as GridView;\n        VisualStyleElement.TextBox.TextEdit edit = view.ActiveEditor as VisualStyleElement.TextBox.TextEdit;\n        if (edit == null) return;\n        if (view.FocusedColumn.FieldName == "FirstName" && view.FocusedRowHandle % 2 == 0)\n        {\n            e.Handled = (e.KeyData == Keys.Right && edit.SelectionStart == edit.Text.Length) ||\n                (e.KeyData == Keys.Left && edit.SelectionStart == 0);\n        }\n    }	0
5643099	2322074	Unable to find a converter that supports conversion to/from string for the property of type 'Type'	[TypeConverter(typeof(TypeNameConverter))]\n[ConfigurationProperty("alertType", IsRequired=true)]\npublic Type AlertType\n{\n    get { return this[ "alertType" ] as Type; }\n    set { this[ "alertType" ] = value; }\n}	0
13306872	13306815	How to add list of missing values in c# list using Linq	list.AddRange(Enumerable.Range(1, 10)\n                        .Except(list.Select(m => m.RequiredValue))\n                        .Select(i => new MyClass() { RequiredValue = i } );	0
23990854	23990757	Delete hashs from line but keep string	if(line.Contains(lineData))\n{\n line=line.Replace("#","");\n}	0
15749796	15749445	Is there a trick in creating a generic list of anonymous type?	var list = Enumerable.Empty<object>()\n             .Select(r => new {A = 0, B = 0}) // prototype of anonymous type\n             .ToList();\n\nlist.Add(new { A = 4, B = 5 }); // adding actual values\n\nConsole.Write(list[0].A);	0
2062015	2061215	How to transform ASP.NET URL without URL routing or URL rewrite?	Request.Path	0
9583105	9582662	How to get a list of duplicate objects out of another list?	var duplicates = FilteredItems.GroupBy(i => i.NewFileName)\n                              .Where(g => g.Count() > 1)\n                              .SelectMany(r => r.ToList());\n\nforeach(var item in duplicates)\n    item.NewFileNameUnique = false;	0
549352	548158	Fixed Length numeric hash code from variable length string in c#	const int MUST_BE_LESS_THAN = 100000000; // 8 decimal digits\n\npublic int GetStableHash(string s)\n{\n    uint hash = 0;\n    // if you care this can be done much faster with unsafe \n    // using fixed char* reinterpreted as a byte*\n    foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))\n    {   \n        hash += b;\n        hash += (hash << 10);\n        hash ^= (hash >> 6);    \n    }\n    // final avalanche\n    hash += (hash << 3);\n    hash ^= (hash >> 11);\n    hash += (hash << 15);\n    // helpfully we only want positive integer < MUST_BE_LESS_THAN\n    // so simple truncate cast is ok if not perfect\n    return (int)(hash % MUST_BE_LESS_THAN)\n}	0
9812598	9689987	ListBox Shift-Click Multi-Select Anchor is not being set properly	if (SelectedIndex > 0) {\n     SelectedIndex--;\n     ListBoxItem item = ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as ListBoxItem;\n     item.Focus();\n}	0
22770155	22770115	Dictionary ContainsKey & Value in same Item	if(ServiceLIST.ContainsKey("testingName") \n && ServiceLIST["testingName"] == "testingStatus")	0
34076844	34076745	Converting to a specific date format?	myDate.ToString("yyyy-MM-dd HH':'mm':'ss")	0
6229983	6227544	Transform IObservable of strings into IObservable of XDocuments	IObservable<string> splitXmlTokensIntoSeparateLines(string s)\n{\n    // Here, you need to split tokens into separate lines (where 'token'\n    // is the beginning of an Xml element). This makes it easier down\n    // the line for the TakeWhile operator.\n\n    return new[] { firstPart, secondPart, etc }.ToObservable();\n}\n\nbool doesTokenTerminateDocument(string s)\n{\n    // Here, you should return whether the XML represents the end of one \n    // document\n}\n\nvar xmlDocuments = stringObservable\n    .SelectMany(x => splitXmlTokensIntoSeparateLines(x))\n    .TakeWhile(x => doesTokenTerminateDocument(x))\n    .Aggregate(new StringBuilder(), (acc, x), acc.Append(x))\n    .Select(x => {\n        var ret = new XDocument();\n        ret.Parse(x.ToString());\n        return ret;\n    })\n    .Repeat()\n    .TakeUntil(stringObservable.Aggregate(0, (acc, _) => acc));	0
20823677	20823596	AsyncFileUpload double upload	OnUploadedComplete="btnUpload_Click"	0
26355741	26355101	ASP.NET redirect from event handler hot by button clicked by JavaScript	function verifyReleaseOtherEmployeesCase() {\n    var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');\n    var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');\n\n    var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');\n\n    if (logonUser.value == lockedBy.value) {\n        button.click();\n    }\n    else if (confirm("Danish confirm message")) {\n        button.click();\n    }\n\n    return false;\n}\n\n <asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"\n    OnClientClick="return verifyReleaseOtherEmployeesCase()" />	0
1091901	1091870	How to convert DateTime? to DateTime	DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;	0
15696568	14987615	Black backcolor in Controls when it was set to transparent	elementHost.BackColorTransparent = true;	0
6824701	6824514	Advanced TextReader to EndOfFile	StreamReader sr = new StreamReader(fileName);\nstring sampleLine = sr.ReadLine();\n\n//discard all buffered data and seek to end\nsr.DiscardBufferedData();\nsr.BaseStream.Seek(0, SeekOrigin.End);	0
7123516	7123484	How to change the default OrderBy functionality so that it orders by a given value first?	return queryable.OrderBy(f => f.Name)\n                .ThenBy(f => f.SeriesId == 6 ? 0 : 1)\n                .ThenBy(s => s.SeriesId));	0
21886125	21879635	C# Create TreeView recursively from list	Dictionary<int, TreeNode> lastParent = new Dictionary<int, TreeNode>();\nforeach (Tuple<string, int> food in foods) {\n  TreeNodeCollection items;\n  if (food.Item2 == 0) {\n    items = treeView1.Nodes;\n  } else {\n    items = lastParent[food.Item2 - 1].Nodes;\n  }\n  TreeNode treeNode = items.Add(food.Item1);\n  if (lastParent.ContainsKey(food.Item2)) {\n    lastParent[food.Item2] = treeNode;\n  } else {\n    lastParent.Add(food.Item2, treeNode);\n  }\n}\ntreeView1.ExpandAll();	0
24516845	22832423	Excel date format using EPPlus	ws.Cells["A3"].Style.Numberformat.Format = "yyyy-mm-dd";\n  ws.Cells["A3"].Formula = "=DATE(2014,10,5)";	0
19194027	19193813	C# Loop through XML Parent Element with XmlTextReader	var xdoc = XDocument.Load("Alarms.xml");\n        foreach (var x in xdoc.Root.Elements("Alarm")) {\n            Console.WriteLine(x.ToString());\n            var date = x.Element("Date");\n            var time = x.Element("Time");\n            Console.WriteLine("Date = {0}", date == null ? "<empty>": date.Value);\n            Console.WriteLine("Time = {0}", time == null ? "<empty>": time.Value);\n            }	0
24639820	24639694	How to add controls / Elements to a form in the WPF C# code?	StackPanel myPanel = new StackPanel();\nmyWindow.Content = myPanel;	0
9489324	9483187	How to remove multiple selected items in ListBox?	private void button1_Click(object sender, EventArgs e) \n{ \n    for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)\n    { \n        int idx = listBox1.SelectedIndices[x];\n        listBox2.Items.Add(listBox1.Items[idx]); \n        listBox1.Items.RemoveAt(idx);\n    } \n}	0
10682940	10682892	Find the mouse location over a bitmap control and display a rectangle in c#	//panel.MouseMove += new MouseEventHandler(panel_MouseMove);\nvoid panel_MouseMove(object sender, MouseEventArgs e)\n{\n    Point myLocation = e.Location;\n    //Or e.X and e.Y\n}	0
23299948	23299603	Do I need to use DTO or POCO	Task t = new Task { Detail = ...  };\n\nusing (var context = new MyContext())\n{\n    context.Tasks.Add(t);\n    context.SaveChanges();\n}	0
3749589	3749516	Using a datetime as filename and parse the filename afterwards?	Imports System.Globalization\nModule Module1\n\nSub Main()\n    Dim enUS As New CultureInfo("en-US")\n    Dim d As String = Format(DateTime.Now, "yyyy-MM-dd_hh-mm-ss")\n    Dim da As Date = DateTime.ParseExact(d, "yyyy-MM-dd_hh-mm-ss", enUS)\n    Console.WriteLine("Date from filename: {0}", d)\n    Console.WriteLine("Date formated as date: {0}", Format(da, "dd.MM.yyyy HH:mm:ss"))\n\nEnd Sub\nEnd Module	0
16597692	16597653	Inheriting abstract classes with abstract properties	public class TestClass : MyBase\n{\n    private Employee _employee;\n\n    public Person Someone\n    {\n        get\n        {\n            return _employee;\n        }\n        set\n        {\n            if(!(value is Employee)) throw new ArgumentException();\n            _employee = value as Employee;\n        }\n}	0
8149002	8148651	Rotation of an object around a central vector2 point	public Vector2 RotateAboutOrigin(Vector2 point, Vector2 origin, float rotation)\n{\n    return Vector2.Transform(point - origin, Matrix.CreateRotationZ(rotation)) + origin;\n}	0
17835914	17832304	Convert HTML string to image	public void ConvertHtmlToImage()\n{\n   Bitmap m_Bitmap = new Bitmap(400, 600);\n   PointF point = new PointF(0, 0);\n   SizeF maxSize = new System.Drawing.SizeF(500, 500);\n   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),\n                                           "<html><body><p>This is a shitty html code</p>"\n                                           + "<p>This is another html line</p></body>",\n                                            point, maxSize);\n\n   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);\n}	0
18487231	18487121	Unable to use JSON	using Newtonsoft.Json;	0
22612343	22612082	Press a C# Application button from keyboard	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    switch (keyData)\n    {\n        case Keys.Right:\n            button1.PerformClick();\n            return true;\n        case Keys.Left:\n             //...\n        default:\n            return base.ProcessCmdKey(ref msg, keyData);\n    }\n}	0
5381141	5146909	Multiple image upload with jquery plugin	var hfc = Request.Files;\nfor (var i = 0; i < hfc.Count; i++)\n{\n    var hpf = hfc[i];\n    if (hpf.ContentLength > 0)\n    {\n        var _thumb = hpf.FileName;\n        hpf.SaveAs(\n            Request.PhysicalApplicationPath + @"\img/produkter\" + _imagePath["categoryImagePath"] + "resized/thumbs/" + StripInput(_thumb)\n        );\n    }\n    else\n    {\n        return string.Format("Add some data on file number: {0}, please? :-)", i);\n    }\n}	0
1155458	1155428	Re-order Items in a ListBox - Windows Forms - (Java programmer learning C#)	private void SetMyButtonProperties()\n{\n    // Assign an image to the button.\n    button1.Image = Image.FromFile("C:\\Graphics\\MyBitmap.bmp");\n    // Align the image on the button\n    button1.ImageAlign = ContentAlignment.MiddleRight;    \n}	0
16984242	16981241	Calling a constructor on custom view model changes output type to JSON	public MyViewModel()\n{\n}\n\npublic MyViewModel(Product product)\n{\n}	0
23380939	23377414	C#. Get all cell in a row by row index in a data grid	private void button2_Click(object sender, EventArgs e)\n{\n   List<string> items = new List<string>();\n   foreach (DataGridViewRow item in dataGridView1.Rows)\n   {\n     if (null != item && null != item.Cells[0].Value)\n     {\n       items.Add(item.Cells[0].Value.ToString());\n     }                \n   }\n}	0
7415483	7414823	How to reference an object in your view model using EF 4.1	public class GrantApplication : IEntity\n{\n   public int Id { get; set; }\n\n   public int MaritalStatusTypeId { get; set; }\n   public virtual MaritalStatusType MaritalStatusType { get; set; }\n}	0
5109310	5109276	Constrain a regex match's starting point	\G<[a-z]*>	0
15236233	15236168	What's a maintainable way to determine if a value is set to its type's default value?	public bool IsDefault<T>(T value)\n{\n    return EqualityComparer<T>.Default.Equals(value, default(T));\n}	0
30889436	30888276	C# Refactoring gigantic switch statement for ordering with LINQ	public ActionResult Index(AgentReportViewModel vm)\n{\n    var b = Agent.GetAgents();\n    vm.Agents = vm.SortAscending \n        ? b.OrderBy(x => GetValueByColumn(x, vm.SortByColumn))\n        : b.OrderByDescending(x => GetValueByColumn(x, vm.SortByColumn));\n    return View(vm);\n}\n\npublic object GetValueByColumn<T>(T x, string columnStr)\n{\n    // Consider caching the property info, as this is a heavy call.\n    var propertyInfo = x.GetType().GetProperty(columnStr);    \n    return propertyInfo.GetValue(x, null);\n}	0
29994958	29991062	Date from textbox to datetimepicker	DateTime dateTimeParsed;\nif (DateTime.TryParse(textBox.Text, out dateTimeParsed))\n    dateTimePicker.Value = dateTimeParsed;\nelse\n{\n    // Handle formatting errors\n}	0
11220804	11220209	Cannot reuse wpf window after closing	Window.Closing	0
11861547	11861240	wait for Download complete	public void PoolAndDownloadFile(Uri uri, string filePath)\n        {\n            WebClient webClient = new WebClient();\n            byte[] downloadedBytes = webClient.DownloadData(uri);\n            while (downloadedBytes.Length == 0)\n            {\n                Thread.Sleep(2000);\n                downloadedBytes = webClient.DownloadData(uri);\n            }\n            Stream file = File.Open(filePath, FileMode.Create);\n            file.Write(downloadedBytes, 0, downloadedBytes.Length);\n            file.Close();\n        }	0
7994351	7994329	How do i return IEnumerable<T> from a method	public interface IFactory<T>\n{    \n    IEnumerable<T> GetAll();\n    T GetOne(int Id);\n}	0
8600952	8600862	Regular expression to have at-least one alphabet, one number & one special character	if (Regex.IsMatch("Test123!@#",\n              @"^(?=.*?[a-z])(?=.*?\d)(?=.*?[!@#$%\^&*\(\)\-_+=;:'""\/\[\]{},.<>|`])", \n              RegexOptions.IgnoreCase))\n{\n    // do something\n}	0
2666099	2666072	How to Generate Server-Side tags dynamiclly	Dim t As TextBox\nt = New TextBox\nPlaceHolder1.Controls.Add(t)	0
27625450	27625343	How can i add a new child node to treeView1 under root treeNode?	TreeNode rootNode = treeView1.Nodes[0];  // select the root \nTreeNode newNode = new TreeNode("node1");  // new node\n\nrootNode.Nodes.Add(newNode);   // Adding to the collection under ROOT	0
29449511	29449169	updating query to read from Microsoft access database	string I = "UPDATE client SET client.Name = ?, client.Phone = ? WHERE client.ID = ?";\ncommand.CommandText = I;\ncommand.CommandType = CommandType.Text;\ncommand.Parameters.AddWithValue("?", Name.Text);\ncommand.Parameters.AddWithValue("?", Phone.Text);\ncommand.Parameters.AddWithValue("?", ID.Text);\nconnection.Open();\ncommand.ExecuteNonQuery();	0
26182639	26182550	Is there a way in Webforms to tell, on pageload, if the postback was caused by an Ajax request or just a regular full postback?	var isAjaxPostBack = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;	0
28239377	28239292	C# always call a base method from the base class	class A\n{\n    public virtual int Number { get { return Foo(); } }\n\n    public int Foo()\n    {\n        return 1;\n    }\n}	0
5653540	5653198	Help with simplifying a couple of regex's	text = Regex.Replace(text,\n    @"\." + change.Key + "([,;])",\n    "." + change.Value + "$1");	0
28758839	28748448	Plotting all X-axis date values in candlestick C#	chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.NotSet;\nchart1.ChartAreas[0].AxisX.Interval=1;	0
9071070	9032053	Microsoft Word VSTO Addin - Replacing bookmarks without deleting them	// Keep the name of the bookmark\nstring bookmarkName = bookmark.Name;\n// Insert your image, as before\nInlineShape shape = bookmark.Range.InlineShapes.AddPicture(path, ref _objectMissing, ref _objectMissing, ref _objectMissing);\n// Restore the bookmark\nObject range = shape.Range;\nyourDocumentVariable.Bookmarks.Add(bookmarkName, ref range);	0
22490377	22489952	Select within select at 'DataTable' with grouping	ORDER BY	0
10444445	10444370	How to remove all items except the first item from dropdownlist in C#?	var firstitem = drpAddressType.Items[0];\n\ndrpAddressType.Items.Clear();\ndrpAddressType.Items.Add(firstitem);	0
14429522	14429445	How can I allow things such as Ctrl-A and Ctrl-Backspace in a C# TextBox	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Control & e.KeyCode == Keys.A)\n        {\n            textBox1.SelectAll();\n        }\n        else if (e.Control & e.KeyCode == Keys.Back)\n        {\n            SendKeys.SendWait("^+{LEFT}{BACKSPACE}");\n        }\n    }	0
19127300	19127111	SQL query running as local user instead of user in connection string	Trusted_Connection = yes	0
24143498	24143042	how to get text box data from hidden form to current form?	Form3 form3;\n    public Form6(Form3 form3)\n    {\n        InitializeComponent();\n        this.form3=form3;\n    }\n\n\n private void L_Click(object sender, EventArgs e)\n    {\n       int result1 = form3.checkBox1.CheckState == CheckState.Checked ? 1 : 0;\n       int result2 = form3.checkBox11.CheckState == CheckState.Checked ? 1 : 0;\n       //...\n       //...   \n    }	0
28120320	28120180	Hidden Password for C# Login Screen - Help & Ideas	private void txtPassword_Enter(object sender, EventArgs e)\n    {\n        txtPassword.Text = "";\n\n        txtPassword.ForeColor = Color.Black;\n\n        txtPassword.UseSystemPasswordChar = true;\n    }\n\n    private void txtPassword_Leave(object sender, EventArgs e)\n    {\n        if (txtPassword.Text.Length == 0)\n        {\n            txtPassword.ForeColor = Color.Gray;\n\n            txtPassword.Text = "Enter password";\n\n            txtPassword.UseSystemPasswordChar = false;\n\n            SelectNextControl(txtPassword, true, true, false, true);\n        }\n    }	0
33003541	33003339	Check string format consist of specific words then number then specific words in c#	string[] input = new string[6]\n        {\n            "Auto_gen_1234@mail.com", // match\n            "Auto_gen_7302@mail.com", // match\n            "Auto_gen_8928@mail.com", // match\n            "Auto_gen_12345@mail.com", // not a match\n            "Auto_gen_72@mail.com", // not a match\n            "Auto_gen_Bob@mail.com" // not a match\n        };\n\n        string pattern = @"Auto_gen_\d{4}@mail.com";  //\d{4} means 4 digits\n        foreach (string s in input)\n        {\n            if (Regex.IsMatch(s, pattern))\n            {\n                Console.WriteLine(string.Format("Input {0} is valid",s));\n            }\n            else {\n                Console.WriteLine (string.Format("Input {0} is  not valid",s));\n            }\n        }\n        Console.ReadKey();	0
6736915	6683808	Custom wpf tab control with one permanent tab, all other tabs scrollable	IsItemsHost="true"	0
29807831	29807462	Passing Two Optional parameter to RedirectToRoute	[Route("Mall/{mallId?}/Store/{storeId?}/Products", Name = "Products")]\npublic ActionResult Products(string mallId = null, long? storeId)\n{\n    return View(products);\n}	0
19565391	19446021	Hide Console Window while using Process.StartInfo with diffent Username	ConnectionOptions remoteConnectionOptions = new ConnectionOptions();\nremoteConnectionOptions.Impersonation = ImpersonationLevel.Impersonate;\nremoteConnectionOptions.EnablePrivileges = true;\nremoteConnectionOptions.Authentication = AuthenticationLevel.Packet;\nremoteConnectionOptions.Username = strDomain + @"\" + strUsername;\nremoteConnectionOptions.SecurePassword = secPassword;\n\nManagementScope scope = new ManagementScope(@"\\" + strServername + @"\root\CIMV2", remoteConnectionOptions); ManagementPath p = new ManagementPath("Win32_Process");\n\nManagementClass classInstance = new ManagementClass(scope, p, null); object[] theProcessToRun = { "myExecutable.exe" };\n\nclassInstance.InvokeMethod("Create", theProcessToRun);	0
1613936	1613867	How do I know when an interface is directly implemented in a type ignoring inherited ones?	public static class TypeExtensions\n{\n    public static IEnumerable<Type> GetInterfaces(this Type type, bool includeInherited)\n    {\n        if (includeInherited || type.BaseType == null)\n            return type.GetInterfaces();\n        else\n            return type.GetInterfaces().Except(type.BaseType.GetInterfaces());\n    }\n}\n\n...\n\n\nforeach(Type ifc in typeof(Some).GetInterfaces(false))\n{\n    Console.WriteLine(ifc);\n}	0
1003816	1003762	Clearing a asp.net datagrid in ASPX page	grid.DataSource = GetSearchResults(); // may return an empty search result\ngrid.Databind();	0
707170	707163	How do you validate a composite format string in C# against its target argument types?	try/catch	0
3567646	3567552	Table doesn't have a primary key	DataColumn[] keyColumns = new DataColumn[1];\nkeyColumns[0] = dt.Columns["<columnname>"];\ndt.PrimaryKey = keyColumns;	0
31134051	31133952	Is there any way to get all sub directories from a given path?	string[] dirs = Directory.GetDirectories(@"c:\data", "*", SearchOption.AllDirectories);	0
6636419	6626336	How to extract validation rules from EntLib validation block?	public static void ExtractRules(Type targetType , string ruleSet) {\n        var settings = (ValidationSettings)ConfigurationManager.GetSection ( ValidationSettings.SectionName );\n        if ( settings != null ) {\n            var type = settings.Types.Where ( t => t.Name == targetType.FullName ).FirstOrDefault ( );\n            if ( type != null ) {\n                var data = type.Rulesets.Where ( t => t.Name == ruleSet ).FirstOrDefault();\n                if ( data != null ) {\n                    List<ValidatorData> validatorDatas = new List<ValidatorData> ( );\n                    data.Properties.ForEach ( (p) => {\n                       validatorDatas.AddRange( p.Validators.Cast<ValidatorData> ( ));\n                    } );\n\n                    data.Fields.ForEach ( (f) => {\n                        validatorDatas.AddRange ( f.Validators.Cast<ValidatorData> ( ) );\n                    } );\n                }\n            }\n        }\n    }	0
14047883	13751648	PetaPoco - Property names from a dynamic type	var e = new Dictionary<string, List<string>>();\n\nSql sql = new Sql("select col1 = 'asd', col2 = 'qwe'");\nvar d = mDataAccess.Query<dynamic>(sql);\n\nif (d != null && d.Count() > 0)\n{\n    List<string> cols = new List<string>();\n    foreach (var t in d.First())\n    {\n        cols.Add(t.Key);\n    }\n\n    foreach (var key in cols)\n    {\n        List<string> values = new List<string>();\n        foreach (var row in d)\n        {\n            foreach (var t in row)\n            {\n                if (t.Key == key) values.Add(t.Value.ToString());\n            }\n        }\n        e.Add(key, values);\n    }\n}\n\nreturn e;	0
102622	102614	Shape of a Winforms MessageBox	"message text...\nmore text..."	0
14783828	14783667	Skybound GeckoFX set host field	geckoWebBrowser1.Navigate(urlTB.Text, Skybound.Gecko.GeckoLoadFlags.None, \n                          referrerTB.Text, null, string.Format("Host: {0}\r\n",\n                          hostTB.Text));	0
9272086	9272054	How to Convert Date To 8 digit integer?	DateTime date = new DateTime(2012, 02, 14);\nstring toDb = date.ToString("yyyyMMdd");	0
21178951	21178722	How do I properly add a custom control to another custom control so that it will render in a form?	public PlateControl()\n        {\n            this.Size = new Size(600, 800);\n            List<WellControl> plateWells = new List<WellControl>();\n            int column = 1;\n            int row = 0;\n            for (int i = 1; i <= 96; i++)\n            {\n                column = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(i / 8)));\n                row = i % 8;\n                WellControl newWell = new WellControl(i + 1);\n                newWell.Name = "wellControl" + i;\n                newWell.Location = new Point(column * 50, row * 50);\n                newWell.Size = new System.Drawing.Size(45, 45);\n                newWell.TabIndex = i;\n                newWell.WellSize = 45;\n                plateWells.Add(newWell);\n                newWell.Visible = true;\n            }\n            this.Controls.AddRange(plateWells.ToArray());\n            InitializeComponent();\n        }	0
3973888	3973783	Extracting text from XML Element with attributes	x.SelectSingleNode("image[@size='large']")	0
23650034	23645517	how do i "link" to a property in another class	class ClassWithImportantProperty\n{\n    string myString = string.Empty;\n\n    public string MyImportantProperty\n    {\n        get { return myString; }\n        set\n        {\n            myString = value;\n            if (PropertyChanged != null)\n                PropertyChanged(myString, EventArgs.Empty);\n        }\n    }\n\n    public event EventHandler PropertyChanged;\n}\n\nclass SecondClass\n{\n    public string MyDependantString { get; set; }\n\n     public secondClass()\n     {\n         var classInstance = new ClassWithImportantProperty();\n         classInstance.PropertyChanged += classInstance_PropertyChanged;\n     }\n\n     void classInstance_PropertyChanged(object sender, EventArgs e)\n     {\n         MyDependantString = sender.ToString();\n     } \n}	0
3878419	3878391	How can i hide "setters" from all but one assembly?	[assembly: InternalsVisibleTo("MyLibrary.Repositories")]\npublic class Post\n{\n   public int PostId { get; internal set; }\n   public int Name { get; internal set; }\n      ...\n}	0
28809646	28805813	Display XML Content dynamically	[Test]\n    public void test()\n    {\n        var a = @"<XML>\n        <Field1>sometext</Field1>\n        </XML>";\n\n        var b = @"<Table Date ='20150302' Time = '0946'>\n       <Row>\n       <Field1>sometext</Field1>\n       <Field2>2341.5145</Field2>\n       </Row>\n       </Table>";\n\n        XDocument doc=XDocument.Parse(b);\n        PrintAllNodes(doc.Descendants());\n    }\n\n    private void PrintAllNodes(IEnumerable<XElement> nodes)\n    {\n        foreach (var node in nodes)\n        {\n            foreach (var xAttribute in node.Attributes())\n            {\n                Console.WriteLine(xAttribute.Name + ": " + xAttribute.Value);\n            }\n\n              Console.WriteLine(node.Name + " " + node.Value);\n        }\n\n    }	0
7023035	7022957	Pasting data into a WPF Datagrid	ObservableCollection<T>	0
23306268	23306234	Using Two "For" at the same time	for (int i2 = 0; i2 <= Globals.Player_HighIndex; i2++)	0
15368979	15357998	Print some text lines using Crystal Report formula	"line1" + chr(13) + chr(10) + "line2"	0
16477154	16474293	Renaming xml element of generic type only for specific type parameter	var xmlTypeAttr = typeof(Item).GetCustomAttributes(true).OfType<XmlTypeAttribute>().FirstOrDefault();\nvar customRoot = new XmlRootAttribute("DataOf" + xmlTypeAttr.TypeName);\nnew XmlSerializer(typeof(Data<Item>), customRoot).Serialize(s, new Data<Item>());	0
16798058	16796279	Add type parameter constraint to prevent abstract classes	abstract class Animal\n{\n    readonly string Name;\n    Animal() { }\n    public Animal(string name) { Name = name; }\n}\n\nabstract class Animal<T> : Animal where T : Animal<T>\n{\n    public Animal(string name) : base(name) { }\n}\n\nclass Penguin : Animal<Penguin>\n{\n    public Penguin() : base("Penguin") { }\n}\n\nclass Chimpanzee : Animal<Chimpanzee>\n{\n    public Chimpanzee() : base("Chimpanzee") { }\n}\n\nclass ZooPen<T> where T : Animal<T>\n{\n}\n\nclass Example\n{\n    void Usage()\n    {\n        var penguins = new ZooPen<Penguin>();\n        var chimps = new ZooPen<Chimpanzee>();\n        //this line will not compile\n        //var animals = new ZooPen<Animal>();\n    }\n}	0
23855484	23855351	EntityFramework - How to populate child members?	Include(b => b.BuySellPhoto.Photo)	0
13795798	13795533	Create a recurring appointment from c# in RadSchedular	recurringAppointment.RecurrenceRule = rrule.ToString()	0
16157239	16156699	C# Remove Readonly From Main Application Folder	// During update process:\nif (!IsAdministrator()) \n{\n    // Launch itself as administrator\n    ProcessStartInfo proc = new ProcessStartInfo();\n    proc.UseShellExecute = true;\n    proc.WorkingDirectory = Environment.CurrentDirectory;\n    proc.FileName = Application.ExecutablePath;\n    proc.Verb = "runas";\n\n    try\n    {\n        Process.Start(proc);\n    }\n    catch\n    {\n        // The user refused to allow privileges elevation.\n        // Do nothing and return directly ...\n        return false;\n    }\n    Application.Exit();\n}\n\n\n\npublic static bool IsAdministrator()\n{\n    var identity = WindowsIdentity.GetCurrent();\n    var principal = new WindowsPrincipal(identity);\n    return principal.IsInRole(WindowsBuiltInRole.Administrator);\n}	0
4476181	4476174	ASP.NET and C# fill a table with data from database	TableRow tabelaLinhas = new TableRow();	0
9252866	9252667	How to access custom class objects and change their data from a WCF service?	// First the Interface, things in here decorated with the Operation contract gets exposed, things with serializable are available to the client\n\nnamespace MyService\n{\n    [ServiceContract]\n    public interface ICustomer\n    {\n\n        [OperationContract]\n        int GetBalance(Guid CustomerId);\n    }\n\n    [Serializable]\n    public class Customer\n    {\n        public Guid Id;\n        public int Balance;\n    }\n}\n\n\n\n\n// 2nd class file is the code mapping to the interface\nnamespace MyService\n{\n    private List<Customer> Customers = new List<Customer>();\n    public class MyService : ICustomer\n    {\n        public int GetBalance(Guid CustomerId)\n        {\n            foreach(Customer c in Customers)\n            {\n                 if(c.Id == CustomerId)\n                 {\n                     return c.Balance;\n                 }\n            }\n        }\n    }\n}	0
15571672	15571132	Looping through nodes with XPathNavigator	using System;\nusing System.Linq;\nusing System.Xml.Linq;\n\nnamespace xmlTest\n{\n    class Program\n    {\n        static void Main()\n        {\n            XDocument doc = XDocument.Load("C:\\Users\\me\\Desktop\\so.xml");\n            var personDataDetails = (from p in doc.Descendants().Elements()                                     \n                                     where p.Name.LocalName == "personData"\n                                         select p);\n\n            foreach (var item in personDataDetails)\n            {\n                Console.WriteLine(item.ToString());\n            }\n\n            Console.ReadKey();\n        }\n    }\n}	0
20533556	20532798	Change texture on key down	enum Direction { Left = 1, Right = 2}\nDirection dir = Direction.Left; //or whatever\n\nprivate void CheckKeyboardAndUpdateMovement()\n{\n    KeyboardState keyboardState = Keyboard.GetState();\n\n    ChangeTexture((int)dir);\n    if (keyboardState.IsKeyDown(Keys.Left))\n    {\n        Movement -= Vector2.UnitX;\n        ChangeTexture(3);\n        dir = Direction.Left;\n    }\n    if (keyboardState.IsKeyDown(Keys.Right))\n    {\n        Movement += Vector2.UnitX;\n        ChangeTexture(4);\n        dir = Direction.Right;\n    }\n    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())\n    {\n        Movement = -Vector2.UnitY * JumpHeight;\n    }\n}	0
16484115	16444860	get sent mails via imap	[Gmail]/Sent Mail	0
8476361	8475830	Returning non JSON, non XML Data in WCF REST Service	[WebGet(UriTemplate = "file")]\n        public Stream GetFile()\n        {\n            WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";\n            FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);\n            int length = (int)f.Length;\n            WebOperationContext.Current.OutgoingResponse.ContentLength = length;\n            byte[] buffer = new byte[length];\n            int sum = 0;\n            int count;\n            while((count = f.Read(buffer, sum , length - sum)) > 0 )\n            {\n                sum += count;\n            }\n            f.Close();\n            return new MemoryStream(buffer); \n        }	0
4068350	4067519	Crystal Report grouping end of page	RecordNumber = 1 or Previous ({fieldname}) <> {fieldname}	0
20931145	20931080	asp.netHow to edit header text in Gridview while joining tables	var item = from c in db.Products\n                   join o in db.ProductCategories\n                   on c.ProdC_ID equals o.ProdC_ID\n                   select new\n                   {\n                      ProductID= c.Prod_ID,\n                      ProductName =c.Prod_Name,\n                      ProductPrice= c.Prod_Price,\n                      Amount= c.Prod_Amount,\n                       Picture=c.Prod_Picture,\n                       ProductDetail=c.Prod_Detail,\n                     ProdCName=  o.ProdC_Name\n                   };	0
31038004	31010470	How to connect to SharePoint on Office 365 with CSOM from C#?	ClientContext cc = new ClientContext("https://XXXX.sharepoint.com");\nSecureString pass = new SecureString();\n\nforeach (char c in "XXXX".ToCharArray();\n    pass.AppendChar(c);\n\ncc.Credentials = new SharePointOnlineCredentials("api@XXXX.onmicrosoft.com", pass);\ncc.Load(cc.Web);\ncc.ExecuteQuery();	0
5259323	5259175	Manage screen transitions with behaviors in silverlight	OldScreenContainer="{Binding ElementName=MyPanel}" NewScreen="{Binding MyNewScreen}"	0
30217451	30217064	How can I pass an app. configuration file as an argument to a console application?	static Main(string[] args)\n{\n    var configMap = new ExeConfigurationFileMap();\n    configMap.ExeConfigFilename = args[0];\n    var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);\n    var value = config.AppSettings.Settings["KeyName"].Value;\n\n    ...\n}	0
12682344	12681838	Parse command lines from the following string in C#?	var str = "httP;//whatvere[CanIncludeSpaces\"].url -a -b -c";\nvar endOfUrl = str.LastIndexOf(".url") + 4;\nvar args = str.Substring(endOfUrl).Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);\n//args is ["-a", "-b", "-c"]\n//also, the URL is easy to get:\nvar url = str.Substring(0, endOfUrl);\n//url is now 'httP;//whatvere[CanIncludeSpaces"].url'	0
8960393	8960322	How can I link one table with two reference tables in LINQ?	var results =\n    from j in table.GetAll()\n    join s in refTableStatuses.GetAll() on j.Status equals s.Key2\n    join t in refTableTypes.GetAll() on j.Type equals t.Key2\n    select new Job\n    {\n        Key1 = j.Key1,\n        Key2 = j.Key2,\n        Title = j.Title,\n        Status = s.Title, // value from Ref (Status) s\n        Type = t.Title    // value from Ref (Type) t\n    };	0
9044068	9039869	XNA changing blendstate from alpha to Additive	batch.Begin(SpriteSortMode.FrontToBack, BlendState.Additive);\nbatch.Draw(tex1, sprite1, null, Color.White, 0.0f, Vector2.Zero, 1.0f,\nSpriteEffects.None, layer1);\nbatch.Draw(tex2, sprite2, null, Color.White, 0.0f, Vector2.Zero, 1.0f,\nSpriteEffects.None, layer2);\nbatch.End();\n\n//new blend state, new begin...end\nbatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);\nbatch.Draw(tex3, sprite3, null, Color.White, 0.0f, Vector2.Zero, 1.0f,\nSpriteEffects.None, layer3);\nbatch.Draw(tex4, sprite4, null, Color.White, 0.0f, Vector2.Zero, 1.0f,\nSpriteEffects.None, layer4);\nbatch.End();	0
23359402	23359262	C# overloading with generic constraints	GetValueOrNull<T1,T2>(IDictionary<T1,T2>,T1)	0
1934403	1934346	Please help me read a string from my XML file and just print it out on a MessageBox	private static string GetHeroIcon(string name)\n{\n    XDocument doc = XDocument.Load("C:/test.xml");\n    return doc.Descendants(name).Single().Element("Icon").Value;\n}	0
2923184	2923170	trying to write to c:\temp in my console app	dataset.WriteXml(@"c:\temp\dataset.xml")	0
31543818	31543679	Return certain value from SQL Server table	public static Tuple<string,string> searchEmail(string email)\n{\n    string userName = "";\n    connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;\n    SqlConnection conn = new SqlConnection(connectionString);\n    {\n        conn.Open();              \n\n        using (SqlCommand comm = new SqlCommand("select UserName from Member where email = @email", conn))\n        {\n            SqlDataReader reader;\n            comm.Parameters.AddWithValue("@email", email);\n\n            reader = comm.ExecuteReader();\n            if (reader.HasRows)\n            {\n              while (reader.Read())\n              {                                \n                 userName = reader.GetString(0);\n              }\n            }\n        }          \n    }\n     conn.Close();\n     return new Tuple<string,string>(email,userName);\n}	0
20717586	20717543	How to implement nested for loop into Linq?	var result = string.Join("<br>",names.SelectMany(n =>\n       roles.Where(r => IsUserInRole(n, r)).Select(r => n + " : " + r))):	0
6985764	6983973	Problem with OleDbConnection string - folder name contain white space	var sb = new System.Data.OleDb.OleDbConnectionStringBuilder();\nsb.Provider = "Microsoft.Jet.OLEDB.4.0";\nsb.DataSource = @"E:\C# PROJECTS\AUSK\T-TOOL\T-TOOL\bin\Release\Config\simcard.xls";\nsb.Add("Extended Properties", "Excel 8.0");\nMessageBox.Show(sb.ToString());	0
9127456	9127412	C# Removing the whole string apart from the end	string str="http://www.website.com/images/a_image.png";\nstr=str.Substring(str.LastIndexOf("/")+1);	0
1004904	1004862	Can I add something to the user session in a custom MembershipProvider?	public object CustomObject\n{\n    get\n    {\n        if(System.Web.HttpContext.Current == null)\n        {\n            return null;\n        }\n        return System.Web.HttpContext.Current.Session["CustomObject"];\n    }\n    set\n    {\n        if(System.Web.HttpContext.Current != null)\n        {\n            System.Web.HttpContext.Current.Session["CustomObject"] = value;\n        }\n    }\n}	0
1774021	1773953	How do I parse a polyline metafile record out of a byte array?	byte[] buffer;\nfixed (byte* b = buffer)\n{\n   ushort* ptr = (ushort*)b;\n   int count = (int)*ptr;\n   var points = new Point[count];\n   for (int i = 0; i < count; i++)\n   {\n       int x = (int)*(++ptr);\n       int y = (int)*(++ptr);\n       points[i] = new Point(x, y);\n   }\n}	0
18416494	18416476	how enter in TextBox only digits from interval	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);\n    }	0
11501415	11501376	Using Interface to add a private setter	public interface IExtendable \n{       \n     Hashtable ExtendedProperties { get; } \n}	0
1841547	1840600	Retrieving SharePoint Services Site Column Data	using(SPSite site = new SPSite("http://portal"))\n{\n    using (SPWeb web = site.RootWeb)\n    {\n        foreach (SPField field in web.Fields)\n        {\n            Console.WriteLine(field.Title);\n        }\n    }\n}	0
13213127	13212609	Send file over SOCKET	std::ifstream file (filename, std::ios::ate | std::ios::binary);	0
28641580	28641533	if user start typing in textbox value change to input else if user didn't type any thing value change to an specific string in C#	Textbox myTxtbx = new Textbox();\nmyTxtbx.Text = "Enter text here...";\n\nmyTxtbx.OnFocus += OnFocus.EventHandle(RemoveText);\nmyTxtbx.LoseFocus += LoseFocus.EventHandle(AddText);\n\npublic RemoveText(object sender, EventArgs e)\n{\n     myTxtbx.Text = "";\n}\n\npublic AddText(object sender, EventArgs e)\n{\n     if(string.IsNullorEmpty(myTxtbx.Text))\n        myTxtbx.Text = "Enter text here...";\n}	0
29079457	29079149	Programmatically copy in-use files	VssBackup.cs	0
17376306	17376289	Split array string into another array	var anotherArray = arrData[0].Split('^');	0
4244900	4244874	Preventing selection of Past Date in .NET DateTimePicker	dateTimePicker.MinDate = DateTime.Today;	0
23166753	23166713	How to have a Select Query for access table Integer value?	String SelctInvQury = string.Format("Select * from invoicemst where invoice_no= {0} ", SvINVNo) ;	0
778926	778817	How to determine if a previous instance of my application is running?	Mutex mutex;\n\ntry\n{\n   mutex = Mutex.OpenExisting("SINGLEINSTANCE");\n   if (mutex!= null)\n   {\n      Console.WriteLine("Error : Only 1 instance of this application can run at a time");\n      Application.Exit();\n   }\n}\ncatch (WaitHandleCannotBeOpenedException ex)\n{\n   mutex  = new Mutex(true, "SINGLEINSTANCE");\n}	0
2080581	2079870	Dynamically adding members to a dynamic object	object x = new ExpandoObject();\nCallSite<Func<CallSite, object, object, object>> site = CallSite<Func<CallSite, object, object, object>>.Create(\n            Binder.SetMember(\n                Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.None,\n                "Foo",\n                null,\n                new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }\n            )\n        );\nsite.Target(site, x, 42);\nConsole.WriteLine(((dynamic)x).Foo);	0
20888335	20888059	How to Compare multi dimentional string array?	private void button1_Click(object sender, EventArgs e)\n{\n    var ary = new[]\n    {\n        "Color1       | Machine 1     | Pass 1 ",\n        "Color2       | Machine 2     | Pass 1 ",\n        "Color3       | Machine 1     | Pass 1 ",\n        "Color4       | Machine 1     | Pass 2 ",\n        "Color5       | Machine 2     | Pass 1 ",\n        "Color6       | Machine 2     | Pass 2 "\n    };\n\n    var seprated = from x in ary.Select(x => x.Split('|'))\n                    select new\n                    {\n                        key = x[1].Trim() + "&" + x[2].Trim(),\n                        value = x[0]\n                    };\n\n    var sb = new StringBuilder();\n    foreach (var key in seprated.Select(x => x.key).Distinct())\n    {\n        var colors = seprated.Where(x => x.key == key).Select(x => x.value.Trim()).ToArray();\n        sb.AppendLine(string.Format("{0} for {1}", string.Join("/", colors), key));\n    }\n\n    textBox1.Text = sb.ToString();\n}	0
9158365	9158283	LINQ Aggregate For Dates	var results = yourList.GroupBy(x => GetFirstDayOfWeek(x.Date))\n                      .ToDictionary(g => g.Key, g => g.Sum(x => x.Value));\n\n// ...\n\nprivate static DateTime GetFirstDayOfWeek(DateTime dt)\n{\n    // left as an exercise for the reader!\n}	0
13961540	13960551	iTextPdf how to break page	HTMLWorker.ParseToList	0
4875179	4875079	Regex to prevent textbox from accepting email addresses	Regex emailregex = new Regex("([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})");\nString s = "johndoe@example.com";\nMatch m = emailregex.Match(s);\nif (!m.Success) {\n   //Not an email address\n}	0
15793283	15792978	Page-global keyboard events in Windows Store Apps	public MyPage()\n{\n    CoreWindow.GetForCurrentThread().KeyDown += MyPage_KeyDown;\n}\n\nvoid MyPage_KeyDown(CoreWindow sender, KeyEventArgs args)\n{\n    Debug.WriteLine(args.VirtualKey.ToString());\n}	0
30313482	30313345	Deserialize Json - Object of objects	var json = @"{'MessageCodes': {\n  'Code1': 'Message 1',\n  'Code2': 'Message 2',\n  'Code3': 'Message 3',\n  'Code4': 'Message 4',\n  'Code5': 'Message 5',\n  'Code6': 'Message 6'}}";\n\nvar dict = JsonConvert.DeserializeObject<Test>(json);\n\npublic class Test\n{\n    public Dictionary<string, string> MessageCodes { get; set; }\n}	0
5548530	3159082	Configure LAME MP3 encoder in DirectShow application using IAudioEncoderProperties	[ComImport]\n[SuppressUnmanagedCodeSecurity]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n[Guid("ca7e9ef0-1cbe-11d3-8d29-00a0c94bbfee")]\npublic interface IAudioEncoderProperties\n{\n    /// <summary>\n    /// Is PES output enabled? Return TRUE or FALSE\n    /// </summary>      \n    int get_PESOutputEnabled([Out] out int dwEnabled);\n\n    /// <summary>\n    /// Enable/disable PES output\n    /// </summary>      \n    int set_PESOutputEnabled([In] int dwEnabled);\n\n    /// <summary>\n    /// Get target compression bitrate in Kbits/s\n    /// </summary>      \n    int get_Bitrate([Out] out int dwBitrate);\n\n    /// <summary>\n    /// Set target compression bitrate in Kbits/s\n    /// Not all numbers available! See spec for details!\n    /// </summary>      \n    int set_Bitrate([In] int dwBitrate);\n\n    ///... the rest of interface\n}	0
5169340	5167809	How to write this in Linq?	var result =(from ci in ctxt.CarInfos\n            where ci.CarKey == carKey\n            && ci.RegKey == regKey\n            && ci.TransactionDate <= transactionDate\n            orderby ci.TransactionDate descending\n            select ci.PartKey)\n            .FirstOrDefault();	0
32302601	32300598	Binding Event to a Method of the ViewModel without ICommand	static Delegate GetHandler(object dataContext, EventInfo eventInfo, string eventHandlerName)\n{\n    // get the vm handler we're binding to\n    var eventParams = GetParameterTypes(eventInfo.EventHandlerType);\n    var method = dataContext.GetType().GetMethod(eventHandlerName, eventParams.Skip(1).ToArray());\n    if (method == null)\n        return null;\n\n    // construct an expression that calls it\n    var instance = Expression.Constant(dataContext);\n    var paramExpressions = eventParams.Select(p => Expression.Parameter(p)).ToArray();\n    var call = Expression.Call(instance, method, paramExpressions.Skip(1));\n\n    // wrap it in a lambda and compile it\n    return Expression.Lambda(eventInfo.EventHandlerType, call, paramExpressions).Compile();\n}	0
2450681	2450657	Linq to XML query returining a list of strings	var query = from pii in xmlDoc.Descendants("piifilter")\nselect new CountrySpecificPIIEntity\n{\n   Country = pii.Attribut("country").Value,\n   CreditCardType = pii.Attribute("creditcardype").Value,\n   Language = pii.Attribute("Language").Value,\n   PIIList = pii.Elements("filters").Select(xe => xe.Value).ToList();\n};	0
20421420	20421333	Executing a simple stored procedure in SQL Server Management Studio	declare @voltageRating varchar(225);\nexec dbo.DetermineVoltage 'test 20V', @voltageRating output;	0
32917257	32903841	How to use WriteableBitmap.setpixel() efficiently in windows 10 uwp?	private void setPixelColors(int xCord, int yCord, int newColor)\n {\n     using (bit.GetBitmapContext())\n     {\n         _setPixelColors(xCord, yCord, newColor);\n     }\n }\n private void _setPixelColors(int xCord, int yCord, int newColor)\n {\n    Color color = bit.GetPixel(xCord, yCord);\n    if (color.R <= 5 && color.G <= 5 && color.B <= 5 || newColor == ConvertColorToInt(color))\n    {\n        //Debug.WriteLine("The color was black or same returning");\n        return;\n    }\n    setPixelColors(xCord + 1, yCord, newColor);\n    setPixelColors(xCord, yCord + 1, newColor);\n    setPixelColors(xCord - 1, yCord, newColor);\n    setPixelColors(xCord, yCord - 1, newColor);\n    //Debug.WriteLine("Setting the color here");\n    bit.SetPixel(xCord, yCord, newColor);\n }	0
6565641	6565199	C# How to use the view presenter pattern in a one to many form?	view.Presenter = this	0
873272	873254	How to check for the existence of a DB?	DbConnection db = new SqlConnection(connection_string);\ntry\n{\n    db.Open();\n}\ncatch ( SqlException e )\n{\n    // Cannot connect to database\n}	0
17678842	17678824	Custom DateTime, customising the date format	DateTime.Today.ToString("yyyyMMdd");	0
19796764	19233355	Archive a specific item in Exchange Server 2010	Item.Move	0
16178849	16178663	How to fix missing out 'if'	if (life <= 0)	0
12657603	12657479	Access to the port 'COM5' is denied	// Dispose() calls Dispose(true)\npublic void Dispose()\n{\n    Dispose(true);\n    GC.SuppressFinalize(this);\n}\n\n// The bulk of the clean-up code is implemented in Dispose(bool)\nprotected virtual void Dispose(bool disposing)\n{\n    if (disposing)\n    {\n        // free managed resources\n        if (_serialPort != null)\n        {\n            _serialPort.Dispose();\n            _serialPort = null;\n        }\n    }\n    // free native resources if there are any.\n}	0
5432985	5372499	subsonic 2.2 : how to order a collection by FK Title?	List<DAL.Product> lst = DAL.DB.Select().From<DAL.Product>()\n    .InnerJoin<DAL.Category>\n    .OrderAsc(DAL.Category.CategoryTitleColumn.ColumnName)\n    .Paged(x,y)\n    .ExecuteTypedList<DAL.Product>();	0
5606615	5606571	Image movement like Google Maps	// Add this transform to the image as RenderTransform\nprivate TranslateTransform _translateT = new TranslateTransform();\nprivate Point _lastMousePos = new Point();\n\nprivate void This_MouseDown(object sender, MouseButtonEventArgs \n{\n    if (e.ChangedButton == PanningMouseButton)\n    {\n        this.Cursor = Cursors.ScrollAll;\n        _lastMousePos = e.GetPosition(null);\n        this.CaptureMouse();\n    }\n}\n\nprivate void This_MouseUp(object sender, MouseButtonEventArgs e)\n{\n    if (e.ChangedButton == PanningMouseButton)\n    {\n        this.ReleaseMouseCapture();\n        this.Cursor = Cursors.Arrow;\n    }\n}\n\nprivate void This_MouseMove(object sender, MouseEventArgs e)\n{\n    if (this.IsMouseCaptured)\n    {\n        Point newMousePos = e.GetPosition(null);\n        Vector shift = newMousePos - _lastMousePos;\n        _translateT.X += shift.X;\n        _translateT.Y += shift.Y;\n        _lastMousePos = newMousePos;\n    }\n}	0
26819911	26819602	Best / easiest strings to find / replace	article = Regex.Replace(article, @":(\w+)(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}):", m => {\n  string content = m.Groups[1].Value;\n  string guid = m.Groups[2].Value;\n  switch (content) {\n    case "image": return "<img src=\"getimage?guid=" + guid + "\" alt=\"image\">";\n    case "video": return "<eeh... whatevs>";\n  }\n  return m.Value; // unrecognised content, so leave it unchanged\n});	0
1905212	1905193	Add two arraylists in a datatable	var table = new DataTable();\ntable.Columns.Add("value1");\ntable.Columns.Add("value2");\n\nfor (int i = 0; i < arrayListOne.Count; i++)\n{\n    var row = table.NewRow();\n    row["value1"] = arrayListOne[i];\n    row["value2"] = arrayListTwo[i];\n    table.Rows.Add(row);\n}	0
6541277	6541173	C# Formatting Long variable as String	String.Format("{0:#,##0}", *long variable*)	0
31030889	31027139	TransactionScope around Many to Many Insert with Entity Framework returns TimeoutException	TransactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);	0
27818540	27653398	How to bind the custom control template into native control	View CreateNewItem(object context)\n{\nvar view = this.ItemTemplate.CreateContent() as View;\nview.BindingContext = context;\nreturn view;\n}	0
5456349	5455972	EntityFramework show entities before saving changes	var inserted = context.ObjectStateManager\n                      .GetObjectStateEntries(EntityState.Added)\n                      .Where(e => !e.IsRelationship)\n                      .Select(e => e.Entity)\n                      .OfType<Cutomer>();	0
9521296	9520827	Binding to a dictionary - with a key of ' ( '	{Binding Path={me:PathConstructor Fields[(0)],')'}}	0
7108163	7107990	start an application included in the same solution	using System;\nusing System.Diagnostics;\n\n...\n\nProcessStartInfo startInfo = new ProcessStartInfo(@"C:\path\to\application\executable.exe");\nstartInfo.Arguments = "-o 99";\nProccess.Start(startInfo);	0
11774770	11754675	Encrypting a string of numerics into a string of alphanumerics	string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\n    private static string Base10To62(string S) \n    {\n        string R = "";\n        var N = long.Parse(S);\n        do { R += Chars[(int)(N % 0x3E)]; } while ((N /= 0x3E) != 0);\n        return R;\n    }\n\n    private static string Base62To10(string S) \n    {\n        long R = 0;\n        int L = S.Length;\n        for (int i = 0; i < L; i++) R += Chars.IndexOf(S[i]) * (long)(System.Math.Pow(0x3E, i));\n        return R.ToString();\n    }	0
9129227	9129033	Is there a .NET class for hotkeys that can be matched against incoming KeyEventArgs?	public class Action : Attribute {\n  public Keys HotKey {get;set;} \n}\n\n\n[Action(HotKey = (Keys.Control | Keys.A))]\npublic void MyMethod() {\n  ...\n}	0
6375296	6375192	How to add functionality to classes	public class MyCompositeObject: Base, IBoltOn\n{\n    protected IBoltOn BoltOn = new BoltOn();\n\n    # region IBoltOn members\n    public void SomeMethod()\n    {\n        BoltOn.SomeMethod();\n    }\n    public sometype SomeProperty {\n        get {\n           return BoltOn.SomeProperty;\n        }\n        set {\n            BoltOn.SomeProperty=value;\n        }\n    }\n    # endregion\n}	0
23134395	23134275	Sleep specific Ticks	System.Threading.Thread.Sleep(new TimeSpan(155000));	0
10004453	10004422	Wpf toggle button content on click	void MyButton_OnClick(object sender, RoutedEventArgs e)\n{\n    if(mybutton.Content.ToString() == "Add")\n    {\n        \\ Lines for add\n        mybutton.Content = "Save";\n    }\n    else\n    {\n        \\ Lines for Save\n        mybutton.Content = "Add";    \n    }\n}	0
12485974	12429655	Getting CheckBoxList Item values	private void btnGO_Click(object sender, EventArgs e)\n{\n    for (int i = 0; i < chBoxListTables.Items.Count; i++)\n    {\n          if (chBoxListTables.GetItemChecked(i))\n        {\n            string str = (string)chBoxListTables.Items[i];\n            MessageBox.Show(str);\n        }\n    }\n}	0
8496430	8496275	c# wait for a while without blocking	using System.Timers;\n\nvoid Main()\n{\n    Timer t = new Timer();\n    t.Interval = 500; //In milliseconds here\n    t.AutoReset = true; //Stops it from repeating\n    t.Elapsed += new ElapsedEventHandler(TimerElapsed);\n    t.Start();\n}\n\nvoid TimerElapsed(object sender, ElapsedEventArgs e)\n{\n    Console.WriteLine("Hello, world!");\n}	0
15638157	15637772	Send Enum value in another script?	public class XScript\npublic enum AState	0
24882434	24881732	Using older SignalR client on Windows 8.1 Metro Style app	var _hubConnection = new Microsoft.AspNet.SignalR.Client.Hubs.HubConnection("www.yahoo.com");	0
1549853	1549823	how to show contextmenustrip when a button is clicked in the right position	layoutMenus.Show(Cursor.Position.X, Cursor.Position.Y);	0
13055436	13055369	How to Save/Overwrite existing Excel file with Excel Interop - C#	ExcelApp.DisplayAlerts = False\nExcelWorkbook.Close(SaveChanges:=True, Filename:=CurDir & FileToSave)	0
30227111	30227086	LINQ how to use "group by" to simplify lists with duplicate attributes	// First GroupBy compound type\n.GroupBy(i => new { i.Type, i.Year })\n\n// Then select from the Group Key and\n// apply an Aggregate/query on the Grouped Values\n.Select(g => new {\n   Type = g.Key.Type,         // Pull out key values\n   Year = g.Key.Year,\n   Cost = g.Sum(i => i.Cost)  // Sum all items in group\n})	0
7204312	7204265	Receive image from c# in php	file_get_contents("php://input");	0
29584585	29584134	Dynamically build query for Azure DocumentDB	var result = new Stuff { A = "a", B = "b" };\nIQueryable<Stuff> query = client.CreateDocumentQuery<Stuff>(collectionLink);\nif (result != null)\n{\n    query = query.Where(s => s.A == result.A);\n    query = query.Where(s => s.B == result.B);\n}\n\nint numResults = query.AsEnumerable().Count();\nif (numResults > 0)\n{\n    // DoSomething();\n}	0
4449901	4449884	how i can check that the url ends with /	url.EndsWith("/")	0
9009549	9007427	Want to capture data from hyper terminal with C# web service	System.IO.Ports.SerialPort	0
10121270	10120936	Updating UI from background threads	void foo(string status)\n{\n    Invoke(new MethodInvoker(() => {InsertStatusMessage(status);}));\n}	0
6437374	6437284	Help with ASP.Net C# chart control	DataView dataView = new DataView(dt);\ndataView.RowFilter = "NAME = 'John'";\n\nChart1.Series[0].Points.DataBindXY(dataView, "NAME", dataView, "perc");	0
6598240	6598179	The right way to compare a System.Double to '0' (a number, int?)	if (Math.Abs(something) < 0.001)	0
24429841	24429112	Get xyz coordinates from starting point, quaternion and moved distance	// PresentationCore.dll \nusing System.Windows.Media.Media3D;\n\nMatrix3D matrix = Matrix3D.Identity;\nmatrix.Translate(new Vector3D(x, y, z));\nmatrix.Rotate(quaterion);\nvar newPoint = matrix.Transform(point);	0
1270475	1268500	Can I 'import' this value into a XML structure and parse it? C#	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(validxmlstring);	0
17730604	17729770	How do i bind data source to a ComboBox?	using (SqlConnection conn = new SqlConnection(conStr))\n        {\n            conn.Open();\n            SqlCommand cmd = new SqlCommand(sqlcmd, conn);\n\n            cmd.Parameters.AddWithValue("@Manufacture", manu);\n\n            SqlDataReader dr = cmd.ExecuteReader();\n\n            IList<string> modelList = new List<string>()\n            while (dr.Read())\n            {\n                modelList.add(dr[0].ToString());\n            }\n\n            ModelComboBox.DataSource = modelList;\n        }	0
6228673	6228199	Custom column names for DataGridView with associated DataSource	class Key\n{\n    [System.ComponentModel.DisplayName("Key")]\n    public string Value { get; }\n    [System.ComponentModel.DisplayName("Expire")]\n    public DateTime ExpirationDate { get; }\n}	0
11450039	11450009	How to perfom a mathematical operation in LINQ	Select(r = new { r.A, Difference = r.A - r.B })	0
18493556	18480491	Observing changes only within a window that commits successfully	IObservable<Unit> beginEditSignal = ...;\nIObservable<Unit> commitSignal = ...;\nIObservable<Unit> cancelEditSignal = ...;\nIObservable<T> propertyChanges = ...;\n\n\n// this will yield an array after each commit\n// that has all of the changes for that commit.\n// nothing will be yielded if the commit is canceled\n// or if the changes occur before BeginEdit.\nIObservable<T[]> commitedChanges = beginEditSignal\n    .Take(1)\n    .SelectMany(_ => propertyChanges\n        .TakeUntil(commitSignal)\n        .ToArray()\n        .Where(changeList => changeList.Length > 0)\n        .TakeUntil(cancelEditSignal))\n    .Repeat();\n\n\n// if you really only want a `Unit` when something happens\nIObservable<Unit> changeCommittedSignal = beginEditSignal\n     .Take(1)\n     .SelectMany(_ => propertyChanges\n         .TakeUntil(commitSignal)\n         .Count()\n         .Where(c => c > 0)\n         .Select(c => Unit.Default)\n         .TakeUntil(cancelEditSignal))\n     .Repeat();	0
19514375	19514119	String to datetime conversion issue with DatePicker	CalendarTrigger[0] = (result.Element("Next").Value != "") ? Convert.ToDateTime(result.Element("Next").Value).ToString("MM/dd/yyyy HH:mm:ss") :DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");	0
21915411	21915178	StatusLabel - how to reset, or allow status text to time out or fade away	public partial class Form1 : Form\n{\n    private System.Timers.Timer _systemTimer = null;\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        _systemTimer = new System.Timers.Timer(500); \n        _systemTimer.Elapsed += _systemTimer_Elapsed;\n    }\n\n    void _systemTimer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        toolStripStatusLabel1.Text = string.Empty;\n        _systemTimer.Stop(); // stop it if you don't want it repeating \n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        toolStripStatusLabel1.Text = "random text just as an example";\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        _systemTimer.Start();\n\n    }\n}	0
11561888	11561663	Get the Ip in use	class Program\n{\n    static void Main(string[] args)\n    {\n    TcpClient t = new TcpClient("www.microsoft.com", 80);\n\n\n    Console.WriteLine(GetMyIp(t.Client.LocalEndPoint.AddressFamily));\n    t.Close();\n}\n\nstatic private String GetMyIp(AddressFamily addr)\n{\n    String ipAddress = System.Net.Dns.GetHostEntry(\n        System.Net.Dns.GetHostName()\n        )\n        .AddressList.First(i => i.AddressFamily.Equals(addr)).ToString();\n    return ipAddress;\n}	0
28538446	28538445	Calculate AWG from Cross section unit mm? and vice versa	double Awg2CrossSection(int awg)\n{\n    var diameter = 0.127 * Math.Pow(92, (36.0 - awg) / 39.0);\n    return Math.PI / 4 * Math.Pow(diameter, 2);\n}\n\nint CrossSection2Awg(double crossSection)\n{\n    var diameter = 2 * Math.Sqrt(crossSection / Math.PI);\n    var result = -((Math.Log(diameter / 0.127)) / (Math.Log(92))) * 39 + 36;\n    return (int) result;\n}	0
19268703	19264715	Call to OData service from C#	var request = (HttpWebRequest)WebRequest.Create(URL);\n    request.Method = "GET";\n\n    request.ContentType = "application/xml";\n    request.Accept = "application/xml";\n    using (var response = request.GetResponse())\n    {\n        using (var stream = response.GetResponseStream())\n        {\n            var reader = new XmlTextReader(stream);\n            while (reader.Read())\n            {\n                Console.WriteLine(reader.Value);\n            }\n        }\n    }	0
8551887	8551386	Pass a string as argument from C# to callback function in C++	delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg, [MarshalAs (UnmanagedType.LPSTR)] string strArg);	0
11743547	11743419	XDocument, XElement : Sequence contains no matching element	XElement child = x.Descendants(siteNM + "siteMapNode")\n                .First(el => el.Attribute("title") != null && el.Attribute("title").Value == "Home");	0
4056885	4056872	How to pass variable into SqlCommand statement and insert into database table	cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;	0
1434516	1434505	Force external process to be killed after time period	// Call WaitForExit and then the using statement will close.\nusing (Process exeProcess = Process.Start(startInfo)) {\n    if(!exeProcess.WaitForExit(1000))\n          exeProcess.Kill();\n}	0
15503338	15502778	Console program hangs unless stepping through with debugger	while (success && x < size)\n{\n  if (_grid[location] == 0)\n  {\n    coords[x++] = location;\n    location += increment;\n\n    if (location >= GRID_SIZE)\n    {\n        success = false;\n    }\n    if (x > 0 && (location % GRID_LENGTH == 0)) // Right edge is out of bounds\n    {\n        success = false;\n    }\n    else\n    {\n        success = true;\n    }\n  }\n  x++;\n}	0
9903197	9903087	How does one make an object move with arrow keys?	private void Form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)\n{ \n   if (e.KeyCode == Keys.NumPad0)\n     {\n       MyShape.Width ++ ;\n     }\n}	0
28669221	28669141	Get value of a column and store it into an array - DataGridView	if(dataGridView3.SelectedRows != null && dataGridView3.SelectedRows.Count > 0)\n{\n    foreach (DataGridViewRow dgvr in dataGridView3.SelectedRows)\n    {\n        int tempVal = 0;\n        if(dgvr.Cells["Cust_Number"].Value != null && int.TryParse(dgvr.Cells["Cust_Number"].Value.ToString(), out tempVal))\n        {\n            capStore.Add(tempVal);\n        }\n    }\n}	0
14382045	14381554	How to query for maximum field value in Lucene.Net?	var sortBy = new Sort(new SortField("date_time_field", SortField.DOUBLE, true));\nvar hits = ... IndexSearcher.Search(query, null, 1, sortBy));\n\n...\n\nvar doc = searcher.IndexSearcher.Doc(hits.ScoreDocs[0]);	0
28884082	28883864	How can i set a Column in a CompositeId mapping with NHibernate	public class MapProduction : ClassMap<Production>\n{\n    public MapProduction()\n    {\n        CompositeId()\n            .KeyProperty(c => c.ProductionCode, "P_PRO")\n            .KeyProperty(c => c.Cycle, "C_CIC")\n            .KeyProperty(c => c.Crop, "C_CUL")\n            .KeyProperty(c => c.TechnologyLevel, "C_NVT");\n        Map(c => c.Area).Column("A_ARE");\n        Map(c => c.Productivity).Column("P_ARE");\n        Map(c => c.syncStatus).ReadOnly();\n    }\n}	0
28390733	28390702	Download From Google Translate	using (var client = new WebClient())\n        {\n            client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");\n            client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36");\n            client.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");\n            client.Headers.Add("Accept-Language", "en-US,en;q=0.8");\n            //client.Encoding = System.Text.Encoding.UTF8;\n\n            client.DownloadFile("http://translate.google.com/translate_tts?tl=ja&q=%E6%97%A5%E6%9C%AC%E8%AA%9E", @"test.mp3");\n        }	0
10571259	10570788	Deleting a Row in a Datatable -> DeletedRowInaccessible	private void dataGridView1_SelectionChanged()\n{ \n    DataTable tb = db1.gettable(1);\n    if(dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Index != -1 && \n       tb[dataGridView1.CurrentRow.Index].RowState != DataRowState.Deleted)\n    {\n        lname.Text = tb.Rows[dataGridView1.CurrentRow.Index][2].ToString(); \n        fname.Text = tb.Rows[dataGridView1.CurrentRow.Index][1].ToString(); \n    }\n}	0
13886150	13886115	How to create an List of int arrays?	List<int[]> arrayList = new List<int[]>();	0
5363513	5363487	Enum to formatted string	public static class WebWizDateFormat\n{\n    public const string USFormat = "MM/DD/YY";\n    public const string UKFormat = "DD/MM/YY";\n}\n\n// . . .\nstring dateFormat = WebWizDateFormat.USFormat;	0
9818006	9817955	How to get keys and values separately from List<KeyValuePair<Type,object>>?	var keys = list.Select(i => i.Key).ToArray()\nvar values = list.Select(i => i.Value).ToArray()	0
43516	43511	Can I prevent an inherited virtual method from being overridden in subclasses?	public sealed override void Render()\n{\n    // Prepare the object for rendering        \n    SpecialRender();\n    // Do some cleanup    \n}	0
4635225	4635147	Usage of Parallel.For	int[] numbers = { 1, 1, 2, 3, 5, 8, 13 };\nint[] squaredNumbers = new int[numbers.Length];\nParallel.For(0, numbers.Length, i => squaredNumbers[i] = (int)Math.Pow(numbers[i], 2));\nint sum = squaredNumbers.Sum();	0
1662152	1662103	Request for Creational Design/Pattern Suggestion	IRelatedType theObject = TheFactory.CreateObject(SomeEnum.SomeValue);\nRelatedTypeHelper theHelper=TheFactory.CreateHelper(theObject);\ntheHelper.DoSpecialThing(theObject);	0
5709548	5709470	ASP.net c# make hyperlink point to page anchor	GDQ.Attributes["href"] = "#Post";	0
21743136	21740041	Fluent NHibernate missing one to many references	public class MultipleItemsMap : ClassMap<MultipleItems>\n{\n    public MultipleItemsMap()\n    {\n        Id(i => i.id);\n        Map(i => i.Total);\n        Map(i => i.Discount);\n        HasMany(i => i.OrderItems).Access.CamelCaseField(Prefix.Underscore)\n            .Cascade.All();\n    }\n}	0
21983595	21983526	How to wrap a tag around second word?	public string cover2nd(string a) {\n        int pos = a.IndexOf(' ');\n        int posNext = a.IndexOf(' ',pos+1);\n        return a.Substring(0, pos) + "<span class='color'>" + \n               a.Substring(pos, posNext - pos) + "</span>" + a.Substring(posNext, a.Length - posNext );\n    }\n}	0
8330349	8330288	How can I hide an option in my drop down without changing the query	ListItem removeListItem = DepartmentType.Items.FindByText("Audits and Verifying");\nDepartmentType.Items.Remove(removeListItem);	0
9145164	9145127	ItextSharp (Itext) - set custom font for paragraph	Font contentFont = FontFactory.GetFont(???);\nParagraph para = new Paragraph(newTempLine, contentFont);	0
1612061	1612010	Mapping a URI to String-field in LINQ-to-SQL	public Uri Url\n{\n    get\n    {\n        return new Uri(_url);\n    }\n    set\n    {\n        _url = value.AbsoluteUri;\n    }\n}\n\n[Column(Name = "Url", DbType = "nvarchar(255)")]\nprivate string _url;	0
1210564	1210553	How can I accept strings like "$1,250.00" and convert it to a decimal in C#?	var d = Decimal.Parse(input, \n  NumberStyles.AllowCurrencySymbol |\n  NumberStyles.AllowDecimalPoint |\n  NumberStyles.AllowThousands);	0
31280125	31257825	How to delete old cookies after changing to manual machine key and wildcard cookies ASP.NET MVC 4.5	var myCookies = Request.Cookies.AllKeys;\nforeach (var cookieName in myCookies)\n{\n    var cookie = Request.Cookies[cookieName];\n    if (cookie == null) continue;\n    cookie.Value = "written " + DateTime.Now;\n    cookie.Expires = DateTime.Now.AddYears(-1);\n    Response.Cookies.Add(cookie);\n}	0
25414360	25414313	Probelm connecting with Sqlexpress	string constring = @"Data Source=DVSQL\SQLEXPRESS;Initial Catalog=DB;User ID=user;Password=****";	0
5667641	5665155	Initialising StructureMap with class that has a constructor with parameters	For<IMyClass>().Use<MyClass>()\n  .Ctor<string>("name").Is("theName")\n  .Ctor<string>("etc").Is("etcetera");	0
29190406	29190296	Appending text to FTP instead of overwriting	private static void AppendString(Uri target,byte[] data) {\n    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);\n    request.Method = WebRequestMethods.Ftp.AppendFile;\n    request.ContentLength = data.length;\n    request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");\n    Stream requestStream = request.GetRequestStream();\n    requestStream.Write(data, 0, data.Length);\n    requestStream.Close();\n    FtpWebResponse response = (FtpWebResponse) request.GetResponse();\n    response.Close();\n}	0
33439762	33439636	C# console app: How can I continue returning an error message until user enters valid data?	static int ReadItemsCountFromInput()\n{\n    while(true)\n    {\n        Console.WriteLine("enter items count: ");\n        string s = Console.ReadLine();\n        int r;\n        if(int.TryParse(s, out r) && r > 0)\n        {\n            return r;\n        }\n        else\n        {\n            Console.WriteLine("you should enter number greater than zero");\n        }\n    }\n}\n\nstatic double CalculateShipping(int items, double shippingCharge)\n{\n        if (items == 1)\n            shippingCharge = 2.99;\n        else if (items > 1 && items < 6)\n            shippingCharge = 2.99 + 1.99 * (items - 1);\n        else if (items > 5 && items < 15)\n            shippingCharge = 10.95 + 1.49 * (items - 5);\n        else if (items > 14)\n            shippingCharge = 24.36 + 0.99 * (items - 14);\n        return shippingCharge;\n}\n\nstatic void Main()\n{\n    int items = ReadItemsCountFromInput();\n    double result = CalculateShipping(items, 0);\n    Console.WriteLine("Shipping: {0}", result);\n}	0
30877707	30876548	Setting App.xaml-resources' value from codebehind	Application.Current.Resources["key"] = value	0
13766250	13763605	List all custom data stored in AppDomain	AppDomain domain = AppDomain.CurrentDomain;\n        domain.SetData("testKey", "testValue");\n\n        FieldInfo[] fieldInfoArr = domain.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);\n        foreach (FieldInfo fieldInfo in fieldInfoArr)\n        {\n\n            if (string.Compare(fieldInfo.Name, "_LocalStore", true) != 0)\n                continue;\n            Object value = fieldInfo.GetValue(domain);\n            if (!(value is Dictionary<string,object[]>))\n                return;\n            Dictionary<string, object[]> localStore = (Dictionary<string, object[]>)value;\n            foreach (var item in localStore)\n            {\n                Object[] values = (Object[])item.Value;\n                foreach (var val in values)\n                {\n                    if (val == null)\n                        continue;\n                    Console.WriteLine(item.Key + " " + val.ToString());\n                }\n            }\n\n\n        }	0
5742831	5742801	Store Null value in SQL Server	if (chkQCE3AS1.Checked)\n            cmd.Parameters.AddWithValue("QCEA1S1", selectedID);\n        else\n            cmd.Parameters.AddWithValue("QCEA1S1", DBNull.Value);	0
3365179	3365154	string.Format of a timer?	DataTime start = <set this somehow>\n\nvoid timer_Tick(...)\n{\n   var elapsed = DateTime.Now - start;\n\n   label1.Text = string.Format("{0:HH:mm:ss}", elapsed);\n}	0
1074795	1074775	checkbox array loop in c#	string myList = Request.Form["myList"];\nif(string.isNullOrEmpty(myList))\n{\n    Response.Write("Nothing selected.");\n    return;\n}\nforeach (string Item in myList.split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries))\n{\n  Response.Write(item + "<hr>");\n}	0
3529764	3529190	Reference to configurated project with log4net	var myDllConfig = ConfigurationManager.OpenExeConfiguration("foo.dll.config");\nXmlConfigurator.Configure(new FileInfo(myDllConfig.FilePath))	0
5002999	5001965	Using one socket object to send and receive multiple sockets in C#	Accept()	0
9545628	9498280	Use NAudio to get Ulaw samples for RTP	var pcmFormat = new WaveFormat(8000, 16, 1);\nvar ulawFormat = WaveFormat.CreateMuLawFormat(8000, 1);\n\nusing (WaveFormatConversionStream pcmStm = new WaveFormatConversionStream(pcmFormat, new Mp3FileReader("whitelight.mp3")))\n{\n    using (WaveFormatConversionStream ulawStm = new WaveFormatConversionStream(ulawFormat, pcmStm))\n    {\n        byte[] buffer = new byte[160];\n        int bytesRead = ulawStm.Read(buffer, 0, 160);\n\n        while (bytesRead > 0)\n        {\n            byte[] sample = new byte[bytesRead];\n            Array.Copy(buffer, sample, bytesRead);\n            m_rtpChannel.AddSample(sample);\n\n            bytesRead = ulawStm.Read(buffer, 0, 160);\n        }\n    }\n}	0
25012293	25012164	How to map SQL Server tables to DataTables correctly?	DataSet dataSet = new DataSet(dataSetName);\n\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n    SqlDataAdapter adapter = new SqlDataAdapter(\n        "SELECT CustomerID, CompanyName, ContactName FROM dbo.Customers", connection);\n\n    DataTableMapping mapping = adapter.TableMappings.Add("Table", "Customers");\n    mapping.ColumnMappings.Add("CompanyName", "Name");\n    mapping.ColumnMappings.Add("ContactName", "Contact");\n\n    connection.Open();\n\n    adapter.FillSchema(dataSet, SchemaType.Mapped);\n    adapter.Fill(dataSet);\n\n    return dataSet;\n}	0
2917638	2917329	How do I get results from a Linq query in the order of IDs that I provide?	var items = (from mytable in db.MyTable\n             where IDs.Contains(mytable.mytableID)\n             select mytable)\n            .ToArray()\n            .OrderBy(x => Array.IndexOf(ids, x.mytableID));	0
2378303	2378206	How to get current or focussed cell value in Excel worksheet using C#	Excel.Range rng = (Excel.Range) this.Application.ActiveCell;\n\n//get the cell value\nobject cellValue = rng.Value;\n\n//get the row and column details\nint row = rng.Row;\nint column = rng.Column;	0
16845295	16843072	Save xml file in Windows Store application	StorageFile file = await StorageFile.GetFileFromPathAsync(filename);\nusing (Stream fileStream = await file.OpenStreamForWriteAsync())\n{\n   doc.Save(fileStream);\n}	0
19112737	19111919	Scanning an image and saving it in a specific folder	Device scanner = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);\nItem scannnerItem = scanner.Items[1];\n// TODO: Adjust scanner settings.\n\nImageFile scannedImage = (ImageFile)dialog.ShowTransfer(scannnerItem, WIA.FormatID.wiaFormatPNG, false);\nscannedImage.SaveFile("path");	0
3275898	3275800	How to use Streetside of Bing map with silverlight?	BingMapAppSDK.msi	0
24451463	24424232	Old text file is downloaded while downloading from server	var httpClient = new HttpClient();\n\n  httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");\n\n  Xml = httpClient.GetStringAsync(URL).Result;	0
22321528	22321295	regex on a string to return text after last colon	(?<=\:\w{2,3}\:).*	0
13320789	13320757	Reversing simple string array	string[] elements = { "one", "two", "three" };	0
10949614	10948853	How to detect significant Peaks?	public bool IsPeak(Point prev, Point aPoint, Point next, float threshold)\n    {\n        return aPoint.Y - prev.Y > threshold && aPoint.Y - next.Y;\n    }	0
15133536	15133490	How to keep variable content over multiple requests?	System.Diagnostics	0
10329292	10300496	Load two windows on two separate screens	protected override void OnStartup(StartupEventArgs e)\n{\n    base.OnStartup(e);\n\n    Window1 w1 = new Window1();\n    Window2 w2 = new Window2();\n\n\n    Screen s1 = Screen.AllScreens[0];\n    Screen s2 = Screen.AllScreens[1];\n\n    Rectangle r1 = s1.WorkingArea;\n    Rectangle r2 = s2.WorkingArea;\n\n    w1.Top = r1.Top;\n    w1.Left = r1.Left;\n\n    w2.Top = r2.Top;\n    w2.Left = r2.Left;\n\n    w1.Show();\n    w2.Show();\n\n    w2.Owner = w1;\n\n\n}	0
26626535	26623146	How to use SQLite-Net Extensions with Composite keys	[CompositeForeignKey(typeof(Class1), "key1", "key2", "key3"]\npublic Tuple<int, int, int> Class1Key { get; set; }	0
26244470	26244188	Use Regex to find parentheses	string pattern = @"[\(\)\[\]\{\}]+$";	0
27176543	27176363	In an WinRT / Universal app how do I check for a change in the image source	if (UserPick.Source == "ms-appx:Assets/RPS3.png")	0
7678542	7678463	C# - Change a font style in a text box	richTextBox1.Find(title, RichTextBoxFinds.MatchCase);\nrichTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Italic);	0
15927511	15927203	Binding a title to selected combobox text	Title="{Binding SelectedItem.Content, ElementName=combobox1}"	0
16141922	16141643	Given two strings, is one an anagram of the other	public static bool IsAnagram(string s1, string s2)\n{\n    if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2))\n        return false;\n    if (s1.Length != s2.Length)\n        return false;\n\n    foreach (char c in s2)\n    {\n        int ix = s1.IndexOf(c);\n        if (ix >= 0)\n            s1 = s1.Remove(ix, 1);\n        else\n            return false;\n    }\n\n    return string.IsNullOrEmpty(s1);\n}	0
7404758	7403044	Databinding on Image but I need a byteArray	[DataMember]\npublic Image OntwerpImageImage\n{\n    get { return ConvertByteArrayToImage(OntwerpImage); }\n    set { OntwerpImage = ConvertImageToByteArray(value); }\n}\n\n//[DataMember]\npublic byte[] OntwerpImage { get; set; }\n\npublic Image ConvertByteArrayToImage(Byte[] bytes)\n{\n    var memoryStream = new MemoryStream(bytes);\n    var returnImage = Image.FromStream(memoryStream);\n    return returnImage;\n}\n\npublic Byte[] ConvertImageToByteArray(Image image)\n{\n    var memoryStream = new MemoryStream();\n    image.Save(memoryStream, ImageFormat.Jpeg);\n    return memoryStream.ToArray();\n}	0
16347525	16347498	How to add conditional condition to LINQ query based on a previously returned value	&& (assetsensor == null || ARL.SensorID == assetsensor.ID)	0
26788307	26603708	How to detect when data is received by udpclient?	if (!rtbPast.Dispatcher.CheckAccess()) // Invoke only when CheckAccess returns false\n{\n    // Call InformUser(data) again, but on the correct thread\n    rtbPast.Dispatcher.Invoke(new Action<string>(InformUser), data);\n\n    // We're done for this thread\n    return;\n}	0
33551342	33551108	Is there a .NET queue class that allows for dequeuing multiple items at once?	var bb = new BatchBlock<int>(10);\n var ab = new ActionBlock<int[]>((Action<int[]>)chunk=>HandleChunk(chunk));  \n\n bb.LinkTo(ab, new DataflowLinkOptions(){PropogateCompletion = true});\n\n for(int i = 0; i < 23; ++i)\n {\n     bb.Post(i);\n }\n\n bb.Complete();\n ab.Completion.Wait();	0
10122046	10121960	IEnumerable<Object> Data Specific Ordering	int maxID = items.Max(x => x.ID); // If you want the Last item instead of the one\n                                  // with the greatest ID, you can use\n                                  // items.Last().ID instead.\nvar strangelyOrderedItems = items\n    .OrderBy(x => x.ID == maxID ? 0 : 1)\n    .ThenBy(x => x.ID);	0
1548161	1548150	How to Save a setting for All users under Vista	System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)	0
936231	936195	How do I disable the 'X' button on a windows form from a UserControl?	protected override void OnClosing(CancelEventArgs e)\n    {\n        e.Cancel = true;\n    }	0
18002526	18002427	How to explicitly define an assembly reference for csdl, ssdl & msl files	Metadata=res://AdventureWorks, 1.0.0.0, neutral, a14f3033def15840/model.csdl|model.ssdl|model.msl	0
18130715	18129583	Adding controller/action to URI using UriBuilder	Url.Action("GetByList", "Listing", new { name = "John"})	0
7819577	7819489	Identify whether a MethodInfo instance is a property accessor	bool isSetAccessor = invocation.Method.DeclaringType.GetProperties() \n        .Any(prop => prop.GetSetMethod() == invocation.Method)	0
4848895	4848049	MonoTouch FinishedLaunching Method App Gets Killed	new Action(this.FetchDataFromWS).BeginInvoke(null, null);	0
16939324	16937646	Flatten xml for deserializing	[DataContract(Name = "Validation")]\npublic class FieldValidationModel\n{\n      [DataMember]\n      public string Annotation { get; set; }\n\n      [DataMember]\n      public PlanTypeCollection PlanTypes { get; set; }\n}\n\n[CollectionDataContract(ItemName="PlanType")]\npublic class PlanTypeCollection : Collection<string>  {}	0
4388362	4388341	How to call a method after user control is visible	userControl2.VisibleChanged += new EventHandler(this.UserControl2VisibleChanged);\n\nprivate void UserControl2VisibleChanged(object sender, EventArgs e)\n{\n   if(userControl2.Visible)\n   {\n      CallMyMethodIWantToRunWhenUserControl2IsVisibleHere();\n   }\n}	0
9404015	9403782	First underscore in a DataGridColumnHeader gets removed	"data__grid_thing"	0
3394213	3394169	How to retain value from a text box on button click from a view, asp.net mvc	TempData["YourData"] = TextBoxText;	0
34485580	34485491	Using GroupBy in linq to group the letters of a string	var text = System.IO.File.ReadAllText("file.txt");\nvar dictionary = new Dictionary<char,int>();\n//count every letter\nforeach (var symbol in text)\n{\n    //skip non letter characters\n    if (!char.IsLetter(symbol))\n         continue;\n\n    var key = char.ToLower(symbol);\n    if (dictionary.ContainsKey(key))\n         dictionary[key]++;\n    else\n         dictionary.Add(key,1);\n}\n//result output\nforeach (var pair in dictionary.OrderBy(p => p.Key))\n{\n    Console.Write("{0}: {1} ", pair.Key, pair.Value);\n}	0
22941407	22819896	How can I hide userid/password in a SQL Server connection string?	/// <summary>\n    /// Accepts a SQL Connection string, and censors it by *ing out the password.\n    /// </summary>\n    /// <param name="connectionString"></param>\n    /// <returns></returns>\n    public static string CensorConnectionString(string connectionString)\n    {\n        var builder = new DbConnectionStringBuilder() {ConnectionString = connectionString};\n        if (builder.ContainsKey("password"))\n        {\n            builder["password"] = "*****";\n        }\n        return builder.ToString();\n    }	0
18930101	18929781	How to efficiently create a list of objects inside of a generic method?	int id = ...\nvar data = connection.Query<Order>(\n    "select * from Orders where CustomerId = @id",\n    new { id }).ToList();	0
15706180	15706117	dynamicly add comboboxes to flowlayoutpanel	for (int i = 0 ....)	0
28547331	28547183	TextChanged want it to validate after the user has entered a date but it validates as the user is entering the date	private void Max_TextChanged(object sender, EventArgs e)\n{\n     DateTime date;\n\n     if (!DateTime.TryParse(Max.Text, out date))\n     {\n        formErrorProvider.SetError(this.Max, "The Date you entered is in invalid format");\n     }\n     else if (date > DateTime.Parse(AvailableMax.Text))\n     {\n        formErrorProvider.SetError(this.Max, "The Date you entered is out of range");\n     }\n     else\n     {\n        formErrorProvider.SetError(this.Max, string.Empty);\n        ToDate.MaxDate = date;\n        ToDate.Value = date;\n     }\n}	0
12556740	12556676	How to Start at Offset and Iterate through Entire List?	int start; // Set your desired start offset\n\nfor (int i = start; i < myList.Length; i++)\n{\n    // do stuff\n}\n\nfor (int j = 0; j < start; j++)\n{\n    // do stuff\n}	0
30939815	30930038	Exclude linq join condition based on parameter	bool includeJoin = false;\n\nIEnumerable<Foo> foos;\n\nif (includeJoin)\n{\n    foos = from f in fooList\n\n                //Exclude this join if includeJoin vairable is false!!\n                join b in barList on f.Foo_Id equals b.Foo_Id into g\n                from result in g.DefaultIfEmpty()\n\n\n                select new Foo { Foo_Id = f.Foo_Id };\n}\nelse\n{\n    foos = from f in fooList select new Foo { Foo_Id = f.Foo_Id };\n}\n\nvar results = foos.ToList();	0
12795042	12794846	How to beep using PC speaker?	Console.Beep();	0
1599521	1599338	How to raise a 401 (Unauthorized access) exception in Sharepoint?	throw new HttpException(401, "Unauthorized access");	0
3122850	3122741	find bold text in excel sheet using C#	using Microsoft.Office.Interop.Excel;\n\nint FindFirstBold(Range cell)\n{    \n    for (int index = 1; index <= cell.Text.ToString().Length; index++)\n    {\n        Characters ch = cell.get_Characters(index, 1);\n        bool bold = (bool) ch.Font.Bold;\n        if(bold) return index;\n    }\n    return 0;\n}	0
27034227	27034127	how do i add eula to program in winforms	if( MessageBox.Show(System.IO.File.ReadAllText(Application.StartupPath + "\\EULA.txt"),"Confirm Eula",MessageBoxButtons.YesNo) == DialogResult.Yes)\n           {\n               //user accepted Eula\n           }\n           else\n           {\n               // user disagreed\n           }	0
26310653	26291902	asp.net - searching for a data containing an apostrophe in the database	string value = txtSearchRP.Text;\nvalue = value.Replace("'", "['']");\nsqlDataSource3.SelectCommand = "SELECT * from tenant WHERE  (name LIKE '%" + value.ToString() +"%')";	0
20379067	20377467	Google column chart visualization from json object bug in MVC 4 C#	for (i in a.rows) {\n     for (j in a.cols) {\n       if (a.cols[j].type == "number") {\n         a.rows[i].c[j].v = Number(a.rows[i].c[j].v);\n       }\n     }	0
1746151	1746079	How can I open Windows Explorer to a certain directory from within a WPF app?	Process.Start(@"c:\test");	0
19574787	19573866	How to compare two DataTables and returns records with only the unmatching data	var q = from a in dtA.AsEnumerable()\n        join b in dtB.AsEnumerable()\n          on a.Field<string>("Currency") equals b.Field<string>("Currency")\n\n        where a.Field<double>("Rate1") != b.Field<double>("Rate1") || \n              a.Field<double>("Rate2") != b.Field<double>("Rate2") || ....\n\n        select new \n        {\n            Currency = a.Field<string>("Currency"),\n            Rate1    = a.Field<double>("Rate1") == b.Field<double>("Rate1") ? \n                           0 : a.Field<double>("Rate1"),\n            Rate2    = a.Field<double>("Rate2") == b.Field<double>("Rate2") ? \n                           0 : a.Field<double>("Rate2"),\n            ...\n        };	0
14654388	14653465	ASP.NET Razor get Area in URL	var area = ViewContext.RouteData.DataTokens["area"];	0
7995763	7984581	How to show the DropDown list of a ComboBox in WinForms (Telerik)	RadTextBoxItem item = this.radMultiColumnComboBox1.MultiColumnComboBoxElement.Children(2).Children(0).Children(0) as RadTextBoxItem;\n\nif (item != null) {\n    item.Click += OnTextBoxItem_Click;\n}	0
11702983	11702946	Trimming strings between two points	int beginidx = haystack.IndexOf('{');\nstring needle = haystack.SubString(beginidx,\n                                   haystack.IndexOf('}') - beginidx + 1).Trim();	0
7426236	3478675	Lock the Height resizing in a .NET Custom Control while in design mode	protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)\n    {\n        // EDIT: ADD AN EXTRA HEIGHT VALIDATION TO AVOID INITIALIZATION PROBLEMS\n        // BITWISE 'AND' OPERATION: IF ZERO THEN HEIGHT IS NOT INVOLVED IN THIS OPERATION\n        if ((specified&BoundsSpecified.Height) == 0 || height == DEFAULT_CONTROL_HEIGHT)                  \n        {\n            base.SetBoundsCore(x, y, width, DEFAULT_CONTROL_HEIGHT, specified);\n        }\n        else\n        {\n            return; // RETURN WITHOUT DOING ANY RESIZING\n        }\n    }	0
8337660	8337651	Want to show value of variable in alert box	Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showAlert(" + Session["sum3"] + ");", true);	0
15790685	15790641	How to take elements from range with lambda expressions and linq?	List<int> list = new List<int>();\nIEnumerable<int> interval = list.Skip(a).Take(b);	0
13645168	13645035	Custom DateTime formatting in c#	String.Format(new MyFormatProvider(), "{0:d}, {0:T}", dateAndTimeVar);	0
27220374	27219841	How To Add Items In A Multi-Dimensional Jagged Array?	class Program\n{\n    static void Main(string[] args)\n    {\n\n        List<List<string>> dataList = new List<List<string>>();\n\n        dataList.Add(new List<string> { "00000", "Mimzi Dagger", "100", "50", "75", "70", "45",    "10", "98", "83" });\n        dataList.Add(new List<string> { "00001", "Alexander Druaga", "89", "45", "80", "90", "15", "73", "99", "100", "61" });\n        dataList.Add(new List<string> { "00002", "Nicholas Zarcoffsky", "100", "50", "80", "50", "75", "100", "100" });\n        dataList.Add(new List<string> { "00003", "Kantmiss Evershot", "50", "100" });\n\n        for (int i = 0; i < dataList.Count; i++)\n        {\n            foreach (var item in dataList[i])\n            {\n                Console.WriteLine(item);\n            }\n        }\n\n        Console.ReadLine();\n\n    }\n}	0
22767630	22763486	C# entity framework 5 set a property only in create	if(myEntity.ObjectID <= 0)\n{\n    myEntity.DateAdded = DateTime.Now;\n}	0
1043063	1042994	Creating XML file header	XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";\nXNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";\nXDocument doc = new XDocument(\n    new XDeclaration("1.0", "utf-8", null),\n    new XElement(ns + "urlset",\n        new XAttribute(XNamespace.Xmlns + "xsi", xsi),\n        new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),\n        new XElement(ns + "url")\n    )\n);\n// save/writeto\nstring s = doc.ToString();	0
4500576	4482934	Customize ribbon in MS Word 2010 with automation in C#	RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Office\Word\Addins\RibbonLoaderLib.RibbonLoader");\n        key.SetValue("LoadBehavior",2,RegistryValueKind.DWord);\n        key.SetValue("Description","Ribbon Loader Add-In",RegistryValueKind.String);\n        key.SetValue("FriendlyName","Ribbon Loader Add-In",RegistryValueKind.String);\n        wordApp_.COMAddIns.Item("RibbonLoaderLib.RibbonLoader").Connect = true;	0
2712909	2712802	How to get an application's process name?	foreach (Process pr in Process.GetProcesses())\n{\n     try\n     {\n         Console.WriteLine("App Name: {0}, Process Name: {1}", Path.GetFileName(pr.MainModule.FileName), pr.ProcessName);\n     }\n     catch { }\n}	0
4430740	4427816	How can i write generic Primary key finder on EntityKey?	static void Main(string[] args)\n    {\n        var entity = GetEntityByKey<Entity>(Guid.Empty);\n    }\n    private static T GetEntityByKey<T>(object key) where T : class \n    {\n        using (var context = new ObjectContext("Name=ModelContainer"))\n        {\n            var set = context.CreateObjectSet<T>().EntitySet;\n            var pk = set.ElementType.KeyMembers[0]; // careful here maybe count can be o or more then 0\n            EntityKey entityKey = new EntityKey(set.EntityContainer.Name+"."+set.Name, pk.Name, key);\n            return (T)context.GetObjectByKey(entityKey);\n        }\n    }	0
18544986	18544884	XDocument load XML in Windows Phone 8	private XDocument xdoc = XDocument.Load(store.OpenFile("APPSDATA.xml", FileMode.Open));	0
19129900	19129689	NullReferenceException for an array of objects attribute of a list object	for (int j = 0; j < ret[0].Fees.Length; j++)\n{\n    if(persons[i].Fees == null)\n      persons[i].Fees = new List<double>();\n    persons[i].Fees[j] = ret[0].Fees[j].Amount; \n}	0
2225789	2225371	Linq group by DateTime / intervals	group t by\n new DateTime(t.Time.Year,t.Time.Month,t.Time.Day ,t.Time.Hour,t.Time.Minute,0) \ninto g	0
7427165	7427098	I need to determine value using LINQ to XML query?	var skills = from group in doc.Descendants("Group")\n             where (string) group.Attribute("name") == "G1"\n             from subskill in group.Descendants("SubSkill")\n             where (string) subskill == "G1skill1sub1"\n             select (string) subskill.Parent.Attribute("name");	0
19066403	19066263	User authentication mechanism for mvc4	[Authorize] // deny '?'\nclass AccountController\n{\n   [AllowAnonymous]\n   public ActionResult Register() { }\n\n   ...\n}	0
33556299	33556061	How to set cookie value?	var response = HttpContext.Current.Response;\nresponse.Cookies.Remove("mycookie");\nresponse.Cookies.Add(cookie);	0
5296364	5278281	How to Using Webdriver Selenium for selecting an option in C#?	// select the drop down list\n var education = driver.FindElement(By.Name("education"));\n //create select element object \n var selectElement = new SelectElement(education);\n\n //select by value\n selectElement.SelectByValue("Jr.High"); \n // select by text\n selectElement.SelectByText("HighSchool");	0
13405564	13404893	How to integrate FluentValidation into MVC4	FluentValidation.Mvc	0
32246612	32245532	Getting the list of all tags in Unity	UnityEditorInternal.InternalEditorUtility.tags	0
31400240	31398959	Using the logic from one lambda within a second lambda	public TModel GetByUniqueKey<TUniqueKey>(\n    Expression<Func<TModel, TUniqueKey>> uniqueKeySelector,\n    TUniqueKey value)\n{\n    return GetWhere(Expression.Lambda<Func<TModel,bool>>(\n        Expression.MakeBinary(\n            ExpressionType.Equal,\n            uniqueKeySelector.Body,\n            Expression.Constant(value, typeof(TUniqueKey))),\n        uniqueKeySelector.Parameters));\n}	0
5096395	5096179	WPF: Remove control's explicit foreground color	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        Box2.Foreground = Brushes.Black;\n        Box1.IsEnabled = false;\n        Box2.IsEnabled = false;\n        Box2.ClearValue(TextBox.ForegroundProperty);\n    }\n}	0
16620159	16620135	Sort a list of objects by the value of a property	cities.OrderBy(x => x.population);	0
15635688	15633138	Datagrid defaultcellstyle.format numeric WinForms	string NRFormat="### ### ##0.00"\ndatagridview1.Columns["col1"].DefaultCellStyle.Format = NRFormat;\ndatagridview1.Columns["col2"].DefaultCellStyle.Format = NRFormat;	0
11642725	11642369	Convert datetime c++ struct (received as bytes) to c# datetime instance	BinaryReader reader = new BinaryReader(networkStream);\nint year = reader.ReadUInt16();\nint month = reader.ReadByte();\nint day = reader.ReadByte();\nint hour = reader.ReadByte();\nint minute = reader.ReadByte();\nint ms = reader.ReadUInt16();\nint second = ms >> 10;\nint millist = ms & 1023;\nDateTime dt = new DateTime(year, month, day, hour, minute, second, millis);	0
651337	651214	Strategy for XmlSerialisation with an Interface?	[XmlInclude(typeof(DerivedClass))]\npublic abstract class BaseClass\n{\n    public abstract bool Property { get; set; }\n}\n\npublic class DerivedClass : BaseClass\n{\n    public override bool Property { get; set; }\n}	0
20267245	20261639	How do you wait on a Task Scheduler task to finish in a batch file or C#?	:loop\nfor /f "tokens=2 delims=: " %%f in ('schtasks /query /tn yourTaskName /fo list ^| find "Status:"' ) do (\n    if "%%f"=="Running" (\n        ping -n 6 localhost >nul 2>nul\n        goto loop\n    )\n)	0
336913	336884	How to compare two elements of the same but unconstrained generic type for equality?	public class Example<TValue>\n{\n    private TValue _value;\n    public TValue Value\n    {\n        get { return _value; }\n        set\n        {\n\n            if (!object.Equals(_value, value))\n            {\n                _value = value;\n                OnPropertyChanged("Value");\n            }\n        }\n    }\n}	0
9067291	9066200	Passing parameters to constructors using Autofac	.FindConstructorsWith(BindingFlags.NonPublic)	0
21935346	21934089	String was not recognized as a valid DateTime in C# asp.net	// Validation\n    DateTime dtOut_StartDate;\n    if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))\n    {\n        Message = "Start date is not a valid format.";\n        txtStartDate.CssClass = ErrorCssClass.TextBox;\n        txtStartDate.Focus();\n        return false;\n    }	0
22704106	22704034	How to convert char[] to UTF-8 byte[] in C#?	byte[] array = System.Text.Encoding.UTF8.GetBytes(new string(chars));	0
10817804	10815212	Store UID from message downloaded using POP protocol C#	string uid = Uid[y]; //obter id da mensagem	0
18387953	18387596	Closing one child-form closes other child-form	public partial class Form1 : Form\n  {\n    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer { Interval = 2000 };\n\n    public Form1()\n    {\n        InitializeComponent();\n        ShowForm3();\n        (new Form2()).ShowDialog(this);\n    }\n\n    void ShowForm3()\n    {\n        Form3 f3 = new Form3();\n        f3.Show();\n        timer.Tick += (sender, e) => f3.Close();\n        timer.Start();\n    }\n  }	0
26157959	26157886	Value of an Array at Index of Another Array	for (int i = 0; i < files.Length; i++) {\n   string file = files[i];\n   string comment = comments[i];\n}	0
11250129	11249277	Password recovery inside ModalPopUp extender	HyperLink2_ModalPopupExtender.Show();	0
29867430	29867237	C# WPF-Ask user before closing application if right-clicking the application icon on the system task bar	public MainWindow()\n{\n    InitializeComponent();\n    Closing += OnClosing;\n}\n\nprivate void OnClosing(object sender, CancelEventArgs cancelEventArgs)\n{\n    if (MessageBox.Show(this, "Your message", "Confirm", MessageBoxButton.YesNo) != MessageBoxResult.Yes)\n    {\n        cancelEventArgs.Cancel = true;\n    }\n}	0
18629602	13180180	Why is my flyout crashing when I try to create a StackPanel with two child elements and assign that to a Flyout?	case PlacementMode.Mouse:\n    throw new NotImplementedException("Mouse PlacementMode is not implemented.");	0
16673226	16622871	How to use transactions in the async csharp-SQLite wrapper?	await MyDatabaseManager.Connection.RunInTransactionAsync((SQLiteConnection connection) =>\n{\n  foreach (Hotel _hotel in listUpdates)\n  {\n    result = connection.Update(_hotel);\n\n    if (result == 0)\n    {\n      connection.Insert(_hotel);\n    }\n  }\n});	0
17173752	17113012	Take Top(X) of each grouped item in LINQ	public IQueryable<Inspections> \nGetLatestInspectionDatesForAllRestaurants(int numRecords)\n{\n     var subQuery =  _session.Query<Inspections>()\n     .OrderByDescending(x => x.InspectionDate);\n\n     var inspections = _session.Query<Inspections>()\n                        .Where(x => subQuery.Where(y => y.InspectionDate == \n                               x.InspectionDate).Take(numRecords).Contains(x))\n                        .OrderBy(x => x.WellDataId);\n    return inspections;\n}	0
31084360	30976456	How to Erase InkCanvas Strokes in Universal Windows Platform (Windows 10) app?	canvas.InkPresenter.InputProcessingConfiguration.Mode = Windows.UI.Input.Inking.InkInputProcessingMode.Erasing;	0
31438140	31438069	Read element within elements using XmlTextReader	var xDoc = XDocument.Load(filename);\n//var xDoc = XDocument.Parse(xmlstring);\nvar strings = xDoc.XPathSelectElements("//UniqueColumns/string")\n                .Select(x => x.Value)\n                .ToList();	0
20151908	20151581	Match with reges excluding string tags	string my_string_no_tags = matches[number].Groups[1].Value;	0
11178803	11178774	Overhead of establishing connection to database	using (var db = new SqlConnection(connectionString)) {\n    ... retrieve data ...\n}	0
27929222	27929109	Changing base class of a Window	xmlns:src="clr-namespace:MvvmHelper.Base;assembly=MvvmHelper"	0
9664591	9664474	Convert blob string to jpg file	string base64string = "iVBORw0KGgoAAAANSUhEUgAAAHgAAAA3CAMAAADwtH5ZAAADAFBMVEX//////P///v/+///3/f3//f+zoJL3///15/SK";  // Put the full string here\nbyte[] blob = Convert.FromBase64String(base64string);\nFile.WriteAllBytes(@"C:\Users\user\Desktop\fic.jpg", blob);	0
26303278	26303030	How can I delete rows and columns from 2D array in C#?	static void Main()\n        {\n            int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\n            var trim = TrimArray(0, 2, array);\n        }\n\n\n        public static int[,] TrimArray(int rowToRemove, int columnToRemove, int[,] originalArray)\n        {\n            int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1) - 1];\n\n            for (int i = 0, j = 0; i < originalArray.GetLength(0); i++)\n            {\n                if (i == rowToRemove)\n                    continue;\n\n                for (int k = 0, u = 0; k < originalArray.GetLength(1); k++)\n                {\n                    if (k == columnToRemove)\n                        continue;\n\n                    result[j, u] = originalArray[i, k];\n                    u++;\n                }\n                j++;\n            }\n\n            return result;\n        }	0
22018082	22017778	How do I sort the filenames read with Directoryinfo	List<string> lstfilename = System.IO.Directory\n    .EnumerateFiles(dir, "*.txt", System.IO.SearchOption.TopDirectoryOnly)\n    .Select(Path => new { \n        Path, \n        split = System.IO.Path.GetFileNameWithoutExtension(Path).Split('-')\n    })\n    .Where(x => x.split.Length == 2 && x.split.All(s => s.All(Char.IsDigit)))\n    .Select(x => new { \n        x.Path, \n        Num1 = int.Parse(x.split[0]),\n        Num2 = int.Parse(x.split[1]),\n    })\n    .Where(x => (startpagenext >= x.Num1 && startpagenext <= x.Num2) \n             || (endpagenext   >= x.Num1 && endpagenext   <= x.Num2))\n    .OrderBy(x => x.Num1).ThenBy(x => x.Num2)\n    .Select(x => x.Path)\n    .ToList();	0
14486793	14486538	grid view cells automatically adding 0 at the foot of subtotal grid view	AllowUsersToAddRow = false	0
18000346	17977717	Get current edited text from tag with attribute contenteditable='true'	document.getElementById("rawXML").value = document.getElementById("fileContents").innerText;	0
33110378	33105050	How can I create a test signing certificate?	X509Certificate2 signingCert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=busta-rpsts.com ");	0
20604390	20603879	How to search and dipaly a panel using drop down list selection?	protected void Dropdownlist1_Changed(object sender, EventArgs, e)\n{\n    string labelTxt= Dropdownlist1.SelectedValue;\n    if(labelTxt == label1.Text)\n    {\n        Panel1.Visible = true;\n        Panel2.Visible = false;\n    }\n    else if(labelTxt == label2.Text)\n    {\n        Panel1.Visible = false;\n        Panel2.Visible = true;\n    }\n\n}	0
4548348	4548316	Prevent Auto code change in Designer.cs for a specific line	using System;\nusing System.Windows.Forms;\n\nnamespace Bling\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n\n            dateTimePicker.MaxDate = DateTime.Now;\n        }\n    }\n}	0
19295078	19294968	Retrieve values of each record in Json string	string JsonString = "{'response':[{'bigINT':123456789,'smallINT':12345},{'bigINT':00000000,'smallINT':00000},{'bigINT':999999999,'smallINT':99999}]}";\n        JObject Jobj = JObject.Parse(JsonString);\n\n        foreach (var response in Jobj["response"]) \n        {\n          int firstbigINT = (int)response["bigINT"];\n          int firstsmallINT = (int)response["smallINT"];\n          use(bigINT,smallINT)\n        }	0
16022610	15905394	Get Xml Text node ID	"//w:t='[ALL]']"	0
14397633	14397291	Get Column value from DataGridRow in WPF	public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)\n    {\n        DataGridRow rowContainer = GetRow(dataGrid, row);\n        if (rowContainer != null)\n        {\n            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);\n\n            // try to get the cell but it may possibly be virtualized\n            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);\n            if (cell == null)\n            {\n                // now try to bring into view and retreive the cell\n                dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);\n\n                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);\n            }\n\n            return cell;\n        }\n\n        return null;\n     }	0
25999073	25998867	I have a DLL to establish an Oracle connection, how do I execute a query against that connection in my referencing code?	var cmd = new OracleCommand { Connection = dbConn.OraConn};	0
22899175	22899129	How to add an array to a list by value not by reference?	testList.Add(testArray.ToArray());	0
18706459	18706295	How I can I do TDD with Caller Info attributes?	var stackFrame = new System.Diagnostics.StackFrame(1, true);\n var fileName = stackFrame.GetFileName();\n var lineNumber = stackFrame.GetFileLineNumber();\n var callerMethod = stackFrame.GetMethod();	0
25864613	25864018	EntityFramework + ASP WebAPI + SelfReference model	public class ProductCategory\n{\n    [Key]\n    public int CategoryID { get; set; }\n\n    [ForeignKey("ParentCategory")]\n    public int? ParentCategoryId {get;set;}\n\n    public string CategoryName { get; set; }\n    public ProductCategory ParentCategory { get; set; }\n}	0
8635762	8635731	How to set focus on a particular row in a datagrid/gridview?	dataGridView1.ClearSelection();\nint nRowIndex = dataGridView1.Rows.Count - 1;\n\ndataGridView1.Rows[nRowIndex].Selected = true;\ndataGridView1.Rows[nRowIndex].Cells[0].Selected = true;	0
9598037	9590980	Map from ICollection<EFEntity> to ICollection<ViewModel> to ICollection<Object> with AutoMapper	AutoMapper.Map<DomainModel, ViewModelWithCollection>();\n\nAutoMapper.Map<EFEntity, object>()\n    .Include<EFEntity, ViewModel>();\n\nAutoMapper.Map<EFEntity, ViewModel>();	0
30833847	30833701	Summing a row from a list	var sum = z[1,0] + z[1,1] + z[1,2];\n\nif (matain == sum)\n  Console.WriteLine("Correct");\nelse\n  Console.WriteLine("Fail");\n\nConsole.ReadKey();	0
16829728	16829646	Create method with access to similar named field, but different types of object without inheritance	public interface IHasId { \n    int Id { get; set; } \n} \n\n\n  public class MyClass1 : IHasId\n  {\n      public int Id { get; set; }\n  }\n  public class MyClass2 : IhasId\n  {\n      public int Id { get; set; }\n  }\n\n\n...\n\n\nprivate void DoStuff<T>(T obj) \n    where T : IHasId // constraint my be moved to the class declaration\n{\n    int i = obj.Id();\n}	0
17978165	17977800	Accessing properties of object stored in session	// When retrieving an object from session state, cast it to \n// the appropriate type.\nArrayList stockPicks = (ArrayList)Session["StockPicks"];\n\n// Write the modified stock picks list back to session state.\nSession["StockPicks"] = stockPicks;	0
17663351	17662871	how to get the child nodes and group them from a parent node	var calcConceptIdGroupedByDataPointValue =\n        doc.Descendants("CalcConceptId")\n           .GroupBy(calcConceptId => calcConceptId.Attribute("DataPointValue"));	0
365228	365224	In what ways do you make use of C# Lambda Expressions?	var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname});	0
28180978	21235321	How can I have private data associated with public array members?	public class Path {\n\n    // private, wraps a node and metadata\n    private class NodeData {\n        public Node Node; // members visible only to parent class\n        public Vector3 CameraPosition;\n        public float TimeStamp;\n    }\n\n    // private member...\n    private NodeData[] nodeData;\n\n    // ...public method\n    public Node GetNode(int index) {\n        return nodeData[index].Node;\n    }\n}	0
15593633	15593586	Parsing file but get a NullReference exception?	Replace("\"", "")	0
27538457	27538437	How to get required parameters from a stored procedure in C#	SqlCommandBuilder.DeriveParameters	0
31889496	31889481	C# Cannot convert from 'ref xxx' to 'ref object'	class CommonFunctions\n{\n    public static void SetPropertyWithNotification<T>(ref T OriginalValue, T NewValue)\n    {\n        if (!OriginalValue.Equals(NewValue))\n        {\n            OriginalValue = NewValue;\n            //Do stuff to notify property changed                \n        }\n    }\n}\npublic class MyClass\n{\n    private List<string> _strList = new List<string>();\n    public List<string> StrList\n    {\n        get { return _strList; }\n        set { CommonFunctions.SetPropertyWithNotification(ref _strList, value); }\n    }\n}	0
22749628	22749511	How to extend method in C# subclass compared to Objective-C	public class A\n{\npublic virtual void doSomething() { Console.WriteLine("Class A"); }\n}\n\nclass B : A\n{\npublic override void doSomething()\n{\nbase.doSomething();\nConsole.WriteLine("Class Y");\n}\n}\n\nstatic void Main()\n{\nA b = new B();\nb.doSomething();\nConsole.ReadKey();\n}	0
26680195	26679406	How to hide Windows Phone 8.1 soft keyboard effectively?	private async void makeRequest(string title, int page)\n    {\n        myTextBox.IsEnabled = false;\n        myTextBox.IsTabStop = false;\n        // here is my httprequest and changing itemssource of listview\n        myTextBox.IsEnabled = true;\n        myTextBox.IsTabStop = true;\n    }	0
9576217	9575879	Redirect as a fresh request after using Response.Redirect	Response.Redirect(//to same page);	0
30259116	30258830	WPF - Change button image source when clicks button	Image img = new Image();\n    img.Source = new BitmapImage(new Uri(@"foo.png"));\n\n    SelectedBtn.Content=img	0
20065228	20065085	Make an icon blink wpf application	DispatcherTime _blinkTimer = new DispatcherTimer();\n\npublic void StartBlinking() {\n  _blinkTimer.Interval = TimeSpan.FromSeconds(1);\n  _blinkTimer.Elapsed += ToggleIconVisibility;\n  _blinkTimer.Start();\n}\n\npublic void StopBlinking() {\n  _blinkTimer.Stop();\n  _blinkTimer.Elapsed -= ToggleIconVisibility;\n}\n\nprivate void ToggleIconVisibility(object sender, EventArgs e)\n{\n  imgstop.Visibility = !imgstop.Visibility;\n}	0
4335066	4334904	MVVM - injecting model into viewmodels vs. getting model via singleton	public class Singleton<T> where T : class {\n    static object SyncRoot = new object( );\n    static T instance;\n    public static T Instance {\n        get {\n            if ( instance == null ) {\n                lock ( SyncRoot ) {\n                    if ( instance == null ) {\n                        ConstructorInfo ci = typeof( T ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null );\n                        if ( ci == null ) { throw new InvalidOperationException( "class must contain a private constructor" ); }\n                        instance = (T)ci.Invoke( null );\n                    }\n                }\n            }\n            return instance;\n        }\n    }\n}	0
6002242	6002201	Unable to clear array and string	Array.Clear(namesTable, 0, 40);\n//                      ^  ^\n//                      |  |_The number of elements to clear.\n//                      |\n//                      |____The starting index of the range of elements to clear.	0
13394225	13394173	How to convert this kind of Date (don't know which format it is)?	DateTime d = DateTime.ParseExact("2012-11-15T13:50:58+01:00", "yyyy-MM-ddTHH:mm:ssK", null);\n\nResponse.Write(d.Hour + "<br />");	0
27087588	27087450	Cannot Insert data into SQL Server database using a asp.net web app	insertBuyer.CommandText = "INSERT INTO Buyer VALUES (@FirstName, @LastName)";\n//insertBuyer.Connection=your connection\n\ninsertBuyer.Parameters.AddWithValue( "@FirstName", tb_firstName.Text );\ninsertBuyer.Parameters.AddWithValue( "@LastName", tb_lastName.Text );\ninsertBuyer.ExecuteNonQuery();// inserts your buyer info\n\ninsertCustAddress.CommandText = "INSERT INTO CustAddress VALUES(@street, @city, @state, @zip)";\n//insertCustAddress.Connection=your connection\ninsertCustAddress.Parameters.AddWithValue("@street", tb_streetAddress.Text);\ninsertCustAddress.Parameters.AddWithValue("@city", tb_city.Text);\ninsertCustAddress.Parameters.AddWithValue("@state", tb_state.Text);\ninsertCustAddress.Parameters.AddWithValue("@zip", tb_zip.Text);\ninsertCustAddress.ExecuteNonQuery();// inserts your customer info	0
12257557	12257483	c# - how to convert any date format to yyyy-MM-dd	string DateString = "11/12/2009";\nIFormatProvider culture = new CultureInfo("en-US", true); \nDateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);	0
3800495	3800464	How to split this string on commas, but only if it meets this criteria?	static List<string> SplitByComma(string str)\n    {\n        bool quoted = false;\n        bool attr = false;\n        int start = 0;\n        var result = new List<string>();\n        for(int i = 0; i < str.Length; ++i)\n        {\n            switch(str[i])\n            {\n                case '[':\n                    if(!quoted) attr = true;\n                    break;\n                case ']':\n                    if(!quoted) attr = false;\n                    break;\n                case '\"':\n                    if(!attr) quoted = !quoted;\n                    break;\n                case ',':\n                    if(!quoted && !attr)\n                    {\n                        result.Add(str.Substring(start, i - start));\n                        start = i + 1;\n                    }\n                    break;\n            }\n        }\n        if(start < str.Length)\n            result.Add(str.Substring(start));\n        return result;\n    }	0
1107505	1107492	Detect Combination Key Event	if (e.Control && e.KeyCode == Keys.K) {\n  //Your code here\n  }	0
1255797	1255790	How do you transform a Linq query result to XML?	XElement xml = new XElement("companies",\n            from company in db.CustomerCompanies\n            orderby company.CompanyName\n            select new XElement("company",\n                new XAttribute("CompanyId", company.CompanyId),\n                new XElement("CompanyName", company.CompanyName),\n                new XElement("SapNumber", company.SapNumber),\n                new XElement("RootCompanyId", company.RootCompanyId),\n                new XElement("ParentCompanyId", company.ParentCompanyId)\n                )\n            );	0
12354843	12354735	How to write simple query to XElement?	var v = from @interface in this.Elements("Interface")\n        select @interface.Element("InterfaceName").Value;	0
16809485	16809294	Lambda expression in attribute constructor	[Foo<SomeType>]	0
14851849	14851771	Winform show screen resolution	label1.Text = string.Format("Primary screen size = {0}x{1}", \n               Screen.PrimaryScreen.Bounds.Width, \n               Screen.PrimaryScreen.Bounds.Height);	0
25076179	24800038	WPF Navigation Parameter Binding	NavigationParameter="{Binding Path=DataContext.SelectedItem.Title, RelativeSource={RelativeSource AncestorType={x:Type dxui:PageAdornerControl}}}	0
33768915	33768854	How to disable a button if no items displayed in a ListView	if(address_list.Items.Count() = 0)\n{\nButton1.enabled = false\n}else\n {\n Button1.enabled = true\n }	0
15869399	15868817	Button inside a winforms textbox	protected override void OnLoad(EventArgs e) {\n        var btn = new Button();\n        btn.Size = new Size(25, textBox1.ClientSize.Height + 2);\n        btn.Location = new Point(textBox1.ClientSize.Width - btn.Width, -1);\n        btn.Cursor = Cursors.Default;\n        btn.Image = Properties.Resources.star;\n        textBox1.Controls.Add(btn);\n        // Send EM_SETMARGINS to prevent text from disappearing underneath the button\n        SendMessage(textBox1.Handle, 0xd3, (IntPtr)2, (IntPtr)(btn.Width << 16));\n        base.OnLoad(e);  \n    }\n\n    [System.Runtime.InteropServices.DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);	0
21281840	21278115	how to customize and delete from a telerik radgrid filter menu with code?	public void Page_Load(object sender, EventArgs e)\n{\n    GridFilterMenu menu = RadGrid1.FilterMenu;\n    int i = 0;\n    while (i < menu.Items.Count)\n    {\n        if (menu.Items[i].Text == "IsNull")\n        {\n            //Upadte Text\n            menu.Items[i].Text = "your_custom_string";\n        }\n        else if (menu.Items[i].Text == "IsEmpty")\n        {\n            //Rmeove menu item\n            menu.Items.RemoveAt(i);\n        }\n\n        i++;\n    }\n}	0
14511657	14511483	How to Get a specific Value of an XML Node from XDocument	private string RetrieveFormattedString(XDocument xDoc, string nodeName)\n{\n    return xDoc.Descendants("Template")\n                .First(t => t.Element("Name").Value == nodeName)\n                .Element("Format").Value;\n}	0
4898442	4898257	Putting datatable comma separated values in a string	DataTable dt = new DataTable();\n\nstring output;\nfor (int i = 0; i < dt.Rows.Count; i++)\n{\n    output = output + dt.Rows[i]["ID"].ToString();\n    output += (i < dt.Rows.Count) ? "," : string.Empty;\n}	0
13146126	12942858	unable to render Json string on client side	type: "GET",\n        url:'<%=VirtualPathUtility.ToAbsolute("~/ProgramListSimpledetail.aspx") %>',\n        data: dataObject,\n        contentType: "application/json; charset=utf-8",\n        dataType: "json",\n        success: function (data)	0
27250321	27247735	using HtmlAgilityPack to locate the text inside a span tag	nameNodes = doc.DocumentNode.SelectNodes("//*[@class='UL1']/li/span"); \n foreach (HtmlNode x in nameNodes)\n Debug.WriteLine(x.InnerText);	0
6625008	6624811	How to pass anonymous types as parameters?	public void LogEmployees (IEnumerable<dynamic> list)\n{\n    foreach (dynamic item in list)\n    {\n        string name = item.Name;\n        int id = item.Id;\n    }\n}	0
1600086	1600065	How to read attribute value from XmlNode in C#?	string employeeName = chldNode.Attributes["Name"].Value;	0
3869673	3868179	Read config file using XMl reader	private void loadConfig()\n        {\n\n            XmlDocument xdoc = new XmlDocument();\n            xdoc.Load( Server.MapPath("~/") + "web.config");\n            XmlNode  xnodes = xdoc.SelectSingleNode ("/configuration/appSettings");\n\n                foreach (XmlNode xnn in xnodes .ChildNodes)\n                {\n                    ListBox1.Items.Add(xnn.Attributes[0].Value  + " = " + xnn.Attributes[1].Value );\n                }              \n\n        }	0
23954836	23954521	C# Regex Matching Whole Word with MetaChars in	\bDESC \+ 7\%\B	0
30514103	30498424	Creating a hexadecimal NumericUpDown control	using System;\nusing System.Windows.Forms;\n\nclass HexUpDown : NumericUpDown {\n    public HexUpDown() {\n        this.Hexadecimal = true;\n    }\n\n    protected override void ValidateEditText() {\n        try {\n            var txt = this.Text;\n            if (!string.IsNullOrEmpty(txt)) {\n                if (txt.StartsWith("0x")) txt = txt.Substring(2);\n                var value = Convert.ToDecimal(Convert.ToInt32(txt, 16));\n                value = Math.Max(value, this.Minimum);\n                value = Math.Min(value, this.Maximum);\n                this.Value = value;\n            }\n        }\n        catch { }\n        base.UserEdit = false;\n        UpdateEditText();\n    }\n\n    protected override void UpdateEditText() {\n        int value = Convert.ToInt32(this.Value);\n        this.Text = "0x" + value.ToString("X4");\n    }\n}	0
17070009	16796280	submitting data via form to server c#	runat="server"	0
12364754	12364690	Calculate the coordinates in a circle	Math.pow(mouse_pos_x-center_circle_x,2)+Math.pow(mouse_pos_y-center_circle_y,2)<Math.pow(radius,2)	0
6200418	6200336	How to translate PHP JSON web service to C#?	[ServiceContract]\npublic interface IService\n{\n    [OperationContract]\n    [WebGet(UriTemplate="customers/{id}", ResponseFormat=WebMessageFormat.Json)]\n    Customer GetCustomer(string id);\n\n    [OperationContract]\n    [WebInvoke(UriTemplate="customers", ResponseFormat=WebMessageFormat.Json)]\n    Customer PostCustomer(Customer c);\n}	0
11409016	11408857	C# Free Image file from use	Bitmap tmpBmp = new Bitmap(fullfilename);\n                Bitmap image= new Bitmap(tmpBmp);\n                tmpBmp.Dispose();	0
7278692	7278663	C# - Array from XML as an embedded resource	XmlNodeList nodes = xml.SelectNodes("Items/Item");\n\nforeach ( XmlNode node in nodes )\n{\n     int id = int.Parse(node.SelectSingleNode("id").InnerText);\n}	0
32974468	32974318	How to use Lambda Expression as a String parameter C#	string ids = selectedUsers.Select(n=>n.ToString()).Aggregate((current, next) => current + ", " + next);\n// also works string.Join\n// string ids = string.Join(", ",selectedUsers);\nstring message = "Are you sure you want to delete user(s) ID: "+ids+"?";\nif (MessageBox.Show(this, message, "Confirmation Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)\n{ \n    //DoSomething();\n}	0
24920453	24642338	Any way to project "original plus a few changes" with a LINQ query?	private IEnumerable<X> BuildCollection(int setMe){\n    IEnumerable<Y> fromService = CallService();\n    IEnumerable<X> mapped = Map(fromService);\n    IEnumerable<X> filteredBySomething = FilterBySomething(mapped);\n\n    IEnumerable<X> sorted = filteredBySomething\n                                .OrderBy(x=>x.Property1)\n                                .ThenBy(x=>x.Property2);\n    // The method already returns IEnumerable<X> - make it an iterator    \n    foreach (var x in sorted)\n    {\n        x.Property3 = setMe;\n        x.Property4 = setMe;\n        yield return x;\n    }\n}	0
11058125	11001438	How to use the Microsoft Translator API over Windows Azure, for Windows Phone?	private void Button_Click_1(object sender, RoutedEventArgs e)\n{\n    var serviceUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");\n    var accountKey = "**********************"; // \n    var tcode = new Microsoft.TranslatorContainer(serviceUri);\n\n    tcode.Credentials = new NetworkCredential(accountKey, accountKey);\n    tcode.UseDefaultCredentials = false;\n    var query = tcode.GetLanguagesForTranslation();\n    query.BeginExecute(OnQueryComplete, query);\n}\n\npublic void OnQueryComplete(IAsyncResult result)\n{\n    var query = (DataServiceQuery<Microsoft.Language>)result.AsyncState;\n    var enumerableLanguages = query.EndExecute(result);\n    string langstring = "";\n    foreach (Microsoft.Language lang in enumerableLanguages)\n    {\n        langstring += lang.Code + "\n";\n    }\n    MessageBox.Show(langstring);\n}	0
28958318	28958235	convert formatted decimal string with thousand seperator	MaxValue.ToString("N2")	0
8954036	8947437	how to generate OAuth client identifier and client secret?	RandomNumberGenerator cryptoRandomDataGenerator = new RNGCryptoServiceProvider();\nbyte[] buffer = new byte[length];\ncryptoRandomDataGenerator.GetBytes(buffer);\nstring uniq = Convert.ToBase64String(buffer);\nreturn uniq;	0
1464233	1464162	Getting the display name from a domain \ alias combo	PrincipalContext c = new PrincipalContext(ContextType.Domain,"CONTOSO");\n        UserPrincipal principal = UserPrincipal.FindByIdentity(c,"steveh");\n        Console.WriteLine(principal.DisplayName);	0
16085933	16079000	DataServiceCollection to a String	g.Items.Aggregate((i, j) => i + delimeter + j)	0
18382275	18381510	Checking if a Vector3 is being shown on the screen	//class scope variables\nBoundingFrustum boundingFrustum;\n\n//in the init method\nboundingFrustum = new BoundingFrustum();\n\n//In the Update method or wherever you need to run a check check\nboundingFrustum.Matrix = view * projection;\n\nbool isPointInView = boundingFrustum.Contains(Vector3ToTest);	0
8777712	8777701	Best way to get the current month number in C#	string sMonth = DateTime.Now.ToString("MM");	0
13304273	13303725	How to convert List of objects with date to array indexed with day of month?	var days = Enumerable.Range(1, 31)\n                     .Select(i => list.Find(x => x.Day.Day == i))\n                     .Select(d => d != null ? d.Value : null)\n                     .ToArray();	0
18163422	18163096	Add items to popup programmatically	myPopup.Child = new DockPanel();	0
23956902	23956616	How To Remove Last Node In XML? C#	XmlDocument doc = new XmlDocument();\ndoc.Load(fileName);\nXmlNodeList nodes = doc.SelectNodes("/RecentFiles/File");\nnodes[nodes.Count].ParentNode.RemoveChild(nodes[nodes.Count]);\ndoc.Save(fileName);	0
5745310	5742803	How to find out how many quarters there are beween one quarter and the other in c#	public static int zwrocRozniceMiedzyKwartalami(Kwartal kwartal1, Kwartal kwartal2) {\n    var quartersPerYear = 4;\n    var yearDifference = kwartal2.Rok - kwartal1.Rok;\n    var differenceQuarters = (yearDifference * quartersPerYear) + (kwartal2.Numer - kwartal1.Numer);\n    return differenceQuarters;\n}	0
28308506	28308109	How to serialize only part of a list in C#	public class Sub2ClassField\n{\n    [XmlAttribute("field")]\n    public string strField { get; set; }\n    public bool ShouldSerializestrField()\n    {\n        return !string.IsNullOrEmpty(strValue);\n    }\n    [XmlAttribute("value")]\n    public string strValue { get; set; }\n    public bool ShouldSerializestrValue()\n    {\n        return !string.IsNullOrEmpty(strValue);\n    }\n\n    public Sub2ClassField()\n    {\n        strField = "";\n        strValue = "";\n    }\n\n    public override string ToString()\n    {\n        return strValue;\n    }\n}	0
250587	249971	WPF: How to apply a GeneralTransform to a Geometry data and return the new geometry?	PathGeometry geometry = new PathGeometry();\ngeometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true));\nScaleTransform transform = new ScaleTransform(2, 2);\nPathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform);	0
1571370	1571316	How to make this loop's body run in parallel in C#	IEnumerable<object> providers = null;\n\n        var waitHandles = new List<WaitHandle>();\n        foreach (var provider in providers)\n        {\n            var resetEvent = new ManualResetEvent(false);\n            waitHandles.Add(resetEvent);\n\n            ThreadPool.QueueUserWorkItem(s =>\n             {\n                 // do whatever you want.\n                 ((EventWaitHandle)s).Set();\n             }, resetEvent);\n        }\n\n        WaitHandle.WaitAll(waitHandles.ToArray());	0
2882088	2882070	changing date format from dd/MM/yyyy to MM/dd/yyyy	DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("MM/dd/yyyy")	0
7082850	7082751	How to implement in-memory logger for last 100 log lines?	Queue<string> _items = new Queue<string>();\n\npublic void WriteLog(string value)\n{\n    _items.Enqueue(value);\n    if(_items.Count > 100)\n        _items.Dequeue();\n}	0
3787677	3785958	Possible to loop through a list of variables, with names differ by numbers only?	Control[] array = new Control[100];\nforeach (Control c in FormX.Controls)\n{\n    int index;\n    if (c.Name.StartsWith("textbox") && int.TryParse(c.Name.Substring(7),out index))\n    {\n        array[index] = c;\n    }\n}	0
28929653	28929461	Loop Through Array of Images	public class ImageHandler : MonoBehaviour\n{\n    public Image img;\n    public List<Sprite> imageObjs;\n    private Sprite activeImage;\n\n    public void LoadLevelImage(int levelNumber)\n    {\n        this.activeImage = (Sprite)Instantiate(imageObjs[levelNumber - 1]);\n        img.sprite = activeImage;\n    }\n}	0
5402317	5402139	How can I display images (multimedia) from an EmailMessage?	item.Attachments	0
19174387	19173798	How to change the profile picture using bootstrap controls	protected void btnChangeUserPic2_Click(object sender, EventArgs e)\n{\n    try\n    {\n        string filePath = Server.MapPath("~/Upload/");                            \n        HttpPostedFile File = userPicFileUpload.PostedFile;\n        string fileExtn = Path.GetExtension(File.FileName).ToLower();\n        string filename = System.IO.Path.GetFileName(File.FileName);               \n        File.SaveAs(filename);\n        lblStatus.Visible = true;\n        lblStatus.Text = "Profile picture changed successfully !!";\n        profilepic.ImageUrl=filePath+filename;\n\n    }\n    catch (Exception ex)\n    {               \n    }\n\n}	0
10341659	10333278	Repeatcolumn property of DataList	datasource = GetDatasourceMethod();\nwhile(datasource.Count <= 3) {\n    datasource.Add(emptyItem);\n}\ndatalist.DataSource = dataSource;\ndatalist.DataBind();	0
15780253	15780222	How to return a multi-dimensional array from a web service method?	[WebMethod]\npublic  string[][]  GetAllItemsArray() \n{\n        FoodCityData.ShoppingBuddyEntities fdContext = new FoodCityData.ShoppingBuddyEntities();\n\n        IQueryable<Item> Query =\n       from c in fdContext.Item\n       select c;\n\n        List<Item> AllfNames = Query.ToList();\n        int arrayZise = AllfNames.Count;\n        String[][] xx = new String[arrayZise][2]; //change here\n        int i = 0;\n        int j = 0;\n        foreach(Item x in AllfNames)\n        {\n\n                xx[i][0] = x.ItemName.ToString();\n                xx[i][1] = x.ItemPrice.ToString();\n                i++;\n        }\n\n         return xx;\n }	0
27981199	27967817	OracleBulkCopy from CSV - Can not insert null column has value	using (OracleConnection connectiontodb = new OracleConnection(databaseconnectionstring))\n    {\n        connectiontodb.Open();\n        using (OracleBulkCopy copytothetable = new OracleBulkCopy(connectiontodb))\n        {\n    OracleTransaction tran = connectiontodb.BeginTransaction(IsolationLevel.ReadCommitted);\n          try\n          {\n            copytothetable.ColumnMappings.Add("TBL_COL1", "TBL_COL1"); \n            copytothetable.ColumnMappings.Add("TBL_COL2", "TBL_COL2"); \n            copytothetable.ColumnMappings.Add("TBL_COL3", "TBL_COL3"); \n            copytothetable.DestinationTableName = "DESTINATION_TABLE";\n            copytothetable.WriteToServer(datatable);\n            tran.Commit();\n          }\n          catch\n          {\n            tran.Roolback();\n          }\n        }\n    }	0
21120990	21120257	How can i isolate an UDP multicast address + port in a server	s.SetSocketOption(SocketOptionLevel.IP,\n    SocketOptionName.MulticastTimeToLive, 2);	0
13794507	13794376	Combo box for serial port	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        this.Load += Form1_Load;\n    }\n\n    void Form1_Load(object sender, EventArgs e)\n    {\n        var ports = SerialPort.GetPortNames();\n        cmbSerialPorts.DataSource = ports;\n    }\n\n    private void btnOk_Click(object sender, EventArgs e)\n    {\n        if (cmbSerialPorts.SelectedIndex > -1)\n        {\n            MessageBox.Show(String.Format("You selected port '{0}'", cmbSerialPorts.SelectedItem));\n            Connect(cmbSerialPorts.SelectedItem.ToString());\n        }\n        else\n        {\n            MessageBox.Show("Please select a port first");\n        }\n    }\n\n    private void Connect(string portName)\n    {\n        var port = new SerialPort(portName);\n        if (!port.IsOpen)\n        {\n            port.BaudRate = 19200;\n            port.Open();\n            //Continue here....\n        }\n    }\n}	0
30048105	29646257	OxyPlot WPF ViewMaximum	var orderedSeries = yourDataSeries.OrderBy(o => o.YValue).ToList();\n\nint lowestPoint = orderedSeries.First.YValue;\nint highestPoint = orderedSeries.Last.YValue;\n\nY = new OxyPlot.Axes.LinearAxis()\n{\n    Minimum = lowestPoint,\n    Maximum = highestPoint,\n    Position = OxyPlot.Axes.AxisPosition.Left,\n    IsPanEnabled = false\n};	0
657700	655276	Message Queue Error: cannot find a formatter capable of reading message	Messages messages = queue.GetAllMessages();\nforeach(Message m in messages)\n{\n  m.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" });\n  String message = m.Body;\n\n  //do something with string\n}	0
13925970	13925927	how to keep zero decimal place for zero?	Result_TextBox.Text = result.ToString("#.0000000");	0
1811700	1811686	Link to retrieve pdf file from DB- in asp.net	Response.Clear();\nResponse.AddHeader("Content-Disposition", "attachment; filename=" + fileName);\nResponse.AddHeader("Content-Length", targetFile.Length.ToString);\nResponse.ContentType = "application/pdf";\nResponse.WriteFile(targetFile.FullName);	0
5559900	5559397	Set multibinding for a xaml element in code behind	multiBinding.Bindings.Add(new Binding("V") { Source = curveEditPoint }); //If that object is accessible in the current scope.\nmultiBinding.Bindings.Add(new Binding("MinV") { Source = CV });\nmultiBinding.Bindings.Add(new Binding("MaxV") { Source = CV });\nmultiBinding.Bindings.Add(new Binding("ActualHeight") { Source = CV });	0
12081951	12080535	SharePoint 2007 c# need to get a document library (list name) from url, looking how to pass list name to GetListItems	string name = string.Empty;\nforeach (XmlNode ls in list.GetListCollection().ChildNodes)\n{\n    //Check whether list is document library\n    if (Convert.ToInt32(ls.Attributes["ServerTemplate"].Value) != 0x65)\n    {\n        continue;\n    }\n\n    string defaultViewUrl = Convert.ToString(ls.Attributes["DefaultViewUrl"].Value);\n\n    if (defaultViewUrl.Contains(listName))\n    {\n        name = ls.Attributes["Name"].Value;\n        break;\n    }\n}\n\nXmlNode ndListItems = list.GetListItems(name, null, ndQuery, ndViewFields, null, ndQueryOptions, null);\nXmlNodeList oNodes = ndListItems.ChildNodes;\n\n// rest of processing below...	0
32708511	32708474	Assign values from SQL Server procedure to variable in c#?	SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");\nSqlCommand cmd = new SqlCommand();\nSqlDataReader reader;\n\ncmd.CommandText = "StoredProcedureName";\ncmd.CommandType = CommandType.StoredProcedure;\ncmd.Connection = sqlConnection1;\n\nsqlConnection1.Open();\n\nint numRows = (int)cmd.ExecuteScalar();\n\nsqlConnection1.Close();	0
10570482	10570142	How to fill a MemoryStream with 0xFF bytes?	static void Fill(this Stream stream, byte value, int count)\n{\n    var buffer = new byte[64];\n    for (int i = 0; i < buffer.Length; i++)\n    {\n        buffer[i] = value;\n    }\n    while (count > buffer.Length)\n    {\n        stream.Write(buffer, 0, buffer.Length);\n        count -= buffer.Length;\n    }\n    stream.Write(buffer, 0, count);\n}	0
15900465	15900226	DateTime.ParseExact FormatException String was not recognized as a valid DateTime	string myDate = "30-12-1899 07:50:00:AM";\nDateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt", \n                                           CultureInfo.InvariantCulture)	0
33979847	33960375	How to get the processor serial number of Raspberry PI 2 with Windows IOT	public static HashSet<string> NetworkIds()\n    {\n        var result = new HashSet<string>();\n\n        var networkProfiles = Windows.Networking.Connectivity.NetworkInformation.GetConnectionProfiles().ToList();\n\n        foreach (var net in networkProfiles)\n        {\n            result.Add(net.NetworkAdapter.NetworkAdapterId.ToString());\n        }\n\n        return result;\n    }	0
6240824	6238051	T4MVC with ActionNames	public virtual ActionResult SomeAction() {\n        // Do stuff\n\n        return new EmptyResult();\n    }	0
5621957	5614343	Login user after signup	FormsAuthentication.RedirectFromLoginPage(mainSignUp.UserName, true);	0
34141500	34141278	How to show grid lines in unity?	GL.PushMatrix();\nmat.SetPass(0);\nGL.LoadOrtho();\nGL.Begin(GL.LINES);\n\n // Set colors and draw verts\n\nGL.End();\nGL.PopMatrix();	0
13887417	13883769	Using a ThreadStatic field with a Task	Action<object>	0
25639448	25639361	How to create Hash of on instance?	public class Product\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public string ModelNumber { get; set; }\n    public string Sku { get; set; }\n    public string Description { get; set; }\n    public double Price { get; set; }\n    public double NewPrice { get; set; }\n\n    public override int GetHashCode()\n    {\n        return Id ^ (Name ?? "").GetHashCode() ^ (ModelNumber ?? "").GetHashCode() ^ (Sku ?? "").GetHashCode()^ (Description ?? "").GetHashCode() ^ Price.GetHashCode() ^ NewPrice.GetHashCode();\n    }\n}	0
8089808	8089785	c# clone a cross-referencing list	namespace ConsoleApplication1\n{\n    [Serializable]\n    class MyItem\n    {\n        public int MyProperty { get; set; }\n        public MyItem RefTo { get; set; }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            List<MyItem> list1 = new List<MyItem>();\n            list1.Add(new MyItem() { MyProperty = 1 });\n            list1.Add(new MyItem() { MyProperty = 2 });\n            list1.Add(new MyItem() { MyProperty = 3 });\n\n            list1[1].RefTo = list1[0];\n            list1[2].RefTo = list1[1];\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                var bformatter = new BinaryFormatter();\n                bformatter.Serialize(stream, list1);\n                stream.Seek(0, SeekOrigin.Begin);\n                List<MyItem> clonedCopyList = (List<MyItem>)bformatter.Deserialize(stream);\n            }\n        }\n    }\n}	0
2531561	2531493	String compare in C#	var r = new Regex("^.{4}01$");\nif(r.Match(str) ...) ...	0
30205627	30203070	Azure blob DownloadToStream takes too long	var maxRetryCount = 3;\n        CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);\n        var blobRequestOptions = new BlobRequestOptions\n        {\n            ServerTimeout = TimeSpan.FromSeconds(30),\n            MaximumExecutionTime = TimeSpan.FromSeconds(120),\n            RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(3), maxRetryCount),\n        };\n\n        using (var memoryStream = new MemoryStream())\n        {\n            blockBlob.DownloadToStream(memoryStream, null, blobRequestOptions);\n        }	0
8654182	8654000	How to maintan transaction in Linq To Entites	using (TransactionScope scope = new TransactionScope()) \n{ \n    //Do something with context1 \n    //Do something with context2\n\n\n    //Save Changes but don't discard yet \n    context1.SaveChanges(false); \n\n    //Save Changes but don't discard yet \n    context2.SaveChanges(false);\n\n\n    //if we get here things are looking good. \n    scope.Complete(); \n\n    //If we get here it is save to accept all changes. \n    context1.AcceptAllChanges(); \n    context2.AcceptAllChanges();\n }	0
20783302	20782338	Find contacts having same phone numbers using Linq C#	var contactsWithduplicates = contacts\n                     .Where(contact => contact.Phones.Any(phone => \n                             contacts.Any(contact2 => contac2 != contact && contact2.Phones.Contains(phone))))\n                     .Distinct().ToList();	0
993792	985003	Embed Icon in WPF application	using(Stream stream = Application.GetResourceStream(new Uri("/Shutdown.ico")).Stream)\n{\n    this.notifyIcon.Icon = new SystemDrawing.Icon(stream);\n}	0
14866110	14865963	Save File to MyDocuments + App Folder	string path = System.IO.Path.Combine(Environment.GetFolderPath(\n    Environment.SpecialFolder.MyDoc??uments),"MyApp","settings.dat");\n\nif(Directory.Exists(path))\n{\n    //Exists\n}\nelse\n{\n    //Needs to be created\n}	0
17971911	17955325	Opening a client-side Excel file using EPPlus	if (FileUpload1.HasFile)\n        {\n\n            HttpPostedFile file = Request.Files[0];\n            myLabel.Text = file.FileName;\n            MemoryStream mem = new MemoryStream();\n            mem.SetLength((int)file.ContentLength);\n\n            file.InputStream.Read(mem.GetBuffer(), 0, (int)file.ContentLength);\n\n            ExcelPackage package = new ExcelPackage(mem);\n\n\n            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];\n            myLabel.Text += " " + worksheet.Name;\n\n        }	0
1473422	1473392	Is it acceptable to only use the 'else' portion of an 'if-else' statement?	bool myCondition = (....);\nif (!myCondition)\n{\n    ...\n}	0
34228035	34218823	ITextsharp get "at least one signature requires validating" after add annotation	annotation = PdfAnnotation.CreateFreeText(stamper.Writer, annotRect, "test", canvas);\n\nannotation.Put(PdfName.RC, new PdfString("<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:APIVersion=\"Acrobat:9.5.5\" xfa:spec=\"2.0.2\"  style=\"font-size:12.0pt;text-align:left;color:#FF0000;font-weight:normal;font-style:normal;font-family:Helvetica,sans-serif;font-stretch:normal\"><p dir=\"ltr\"><span style=\"font-family:Helvetica\">test</span></p></body>"));	0
16384982	16384903	Moving a control by dragging it with the mouse in C#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n\n    private Point MouseDownLocation;\n\n\n    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Left)\n        {\n            MouseDownLocation = e.Location;\n        }\n    }\n\n    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Left)\n        {\n            pictureBox1.Left = e.X + pictureBox1.Left - MouseDownLocation.X;\n            pictureBox1.Top = e.Y + pictureBox1.Top - MouseDownLocation.Y;\n        }\n    }\n\n}	0
31148996	31148938	How do I reverse ORDER BY to give me the smallest instead of the largest?	ORDER BY column_1 DESC, column_2, column_n	0
20437187	20436944	Ask for user input using a SpriteFont on the screen present	if (gameRestart)\n        {\n            if (Keyboard.GetState().IsKeyDown(Keys.Y))\n            {\n                // code for restart goes here\n            }\n            else if (Keyboard.GetState().IsKeyDown(Keys.N))\n            {\n                // do nothing, I guess?\n            }\n        }	0
29113506	29113308	Set a limit on the amount of numbers that can be entered into a "masked textbox"	private void Form1_Load(object sender, EventArgs e)\n    {\n        mtbMales.MaxLength = 3;\n        mtbMales.Mask = "000";\n    }	0
5136990	5136964	How to show Label Text from Datatable?	Label1.Text =  Repository.Instance.ReturnScore(ddlPlayer1.ToString(), ddlPlayer2.ToString()).Rows[0][0].ToString();	0
25906620	25899301	Get angle between two transforms in a single plane	void Update () \n{\n    Debug.Log(AngleInPlane(t1, t2.position, Vector3.up));\n    Debug.Log(AngleInPlane(t1, t2.position, Vector3.right));\n}\n\npublic float AngleInPlane(Transform from, Vector3 to, Vector3 planeNormal)\n{\n    Vector3 dir = to - from.position;\n\n    Vector3 p1 = Project(dir, planeNormal);\n    Vector3 p2 = Project(from.forward, planeNormal);\n\n    return Vector3.Angle(p1, p2);\n}\n\npublic Vector3 Project(Vector3 v, Vector3 onto)\n{\n    return v - (Vector3.Dot(v, onto) / Vector3.Dot(onto, onto)) * onto;\n}	0
7424388	7424344	If an object inherit from an abstract class that inherite from an interface will the object inherit from the interface?	using System;\n\ninterface IParent {}\nabstract class Parent : IParent {}\n\nclass Example : Parent\n{\n    static void Main()\n    {\n        Console.WriteLine(new Example() is IParent);\n    }\n}	0
977969	967968	How to smoothly animate Windows Forms location with different speeds?	public partial class Form1 : Form\n{\n    private bool go;\n    private int dx = 1;\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        if (go)\n        {\n            this.Location = new Point(this.Location.X + dx, this.Location.Y);\n            if (Location.X < 10 || Location.X > 1200)\n            {\n                go = false;\n                dx = -dx;\n            }\n            else\n            {\n                this.Invalidate();\n            }\n        }\n    }\n    private void button1_Click(object sender, EventArgs e)\n    {\n        go = true;\n        this.Invalidate();\n    }\n}	0
22629714	22622033	Windows Phone 8 ListBox MVVM scrolling issue	public class ItemsControlBehavior : Behavior<ListBox>\n{\n    protected override void OnAttached()\n    {\n        base.OnAttached();\n        AssociatedObject.ItemContainerGenerator.ItemsChanged += ItemContainerGenerator_ItemsChanged;\n    }\n\n    protected override void OnDetaching()\n    {\n        base.OnDetaching();\n        AssociatedObject.ItemContainerGenerator.ItemsChanged -= ItemContainerGenerator_ItemsChanged;\n    }\n\n    private void ItemContainerGenerator_ItemsChanged(object sender,\n        System.Windows.Controls.Primitives.ItemsChangedEventArgs e)\n    {\n        if (AssociatedObject.Items.Any())\n        {\n            AssociatedObject.ScrollIntoView(AssociatedObject.Items[AssociatedObject.Items.Count - 1]);\n        }\n    }\n}	0
1335269	1334815	How to bind control's two properties to two object properties properly	Binding b = new Binding("Test");  \nb.Source = tt;  \nt.SetBinding(TextBox.TextProperty, b);	0
18170673	18168219	How to add an extra properties argument to a textbox?	private void OnTextBoxChanged(object sender, EventArgs e)\n    {\n        var updatedTextBox = sender as TextBox;\n        object tagObject = updatedTextBox.Tag;\n\n        // Further converting of the tag here...\n\n    }	0
17379873	17378223	how to remove uploaded files from a folder?	using System.IO;\nFile.Delete ( string.Format ( @"{0}\{1}",  Server.MapPath ( "MyFiles" ), fileName ) );	0
10511708	10511643	Sorting DataGridView	dataGridView1.Sort(dataGridView1.Columns["yourcol"],ListSortDirection.Ascending);	0
5183850	5183568	SetParameter with IType doesn't result in meaningfull query	var setParamMethod = hibQuery.GetType().GetMethod("SetParameter`1");\nsetParamMethod.MakeGenericMethod(myValueType)\n    .Invoke(nhibQuery, new object[]{"UserId", intObject});	0
7720957	7720862	How to add an xml file as a resource to Windows Forms exe	XElement resource = XElement.Parse(Properties.Resources.CAppxmlfile);	0
20354764	20354645	EF 6 many to many data retrieval using LINQ	var query = from e in context.Employee\n            from o in e.Organizations\n            select new\n            {\n              EmployeeName = e.Name,\n              EmployeeId = e.Id,\n              OrganizationId = o.Id\n            }	0
22428027	22427230	How to Button onclick get selected radiobutton value inside listview in c#	private void btnSubmit_Click(object sender, EventArgs e)\n {\n     foreach(ListViewDataItem item in listView.Items)\n     {\n           var rbl = (RadioButtonList)item.FindControl("rblSelect")\n           var selectedValue = rbl.SelectedItem.Value;\n           var selectedText = rbl.SelectedItem.Text;\n           var selectedIndex = rbl.SelectedIndex;\n     }\n }	0
9520283	9511443	update password protected linked word document in C#	Private Sub Document_Open()\n\nDim xlApp As Object\nDim xlWB As Object\nDim myRange\n\nApplication.DisplayAlerts = wdAlertsNone\n\nSet xlApp = CreateObject("Excel.Application")\nSet xlWB = xlApp.Workbooks.Open("C:\ExcelFile.xls", , , , "password", "password")\nSet myRange = Selection.Range\n\n    Selection.WholeStory\n    Selection.Fields.Update\n    myRange.Select\n\nxlApp.Quit\nSet xlWB = Nothing\nSet xlApp = Nothing\n\nApplication.DisplayAlerts = wdAlertsAll\n\nEnd Sub	0
2188593	2188585	Convert String to Date in .NET if my incoming date format is in YYYYMMDD	string date = "20100102";\n   DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);	0
21973358	21973327	obtain all records in table with entity framework	var allSalesUploaded = db.UploadedFile.ToList();	0
4352066	4351752	ToolStripDropDownButton, how to remove all DropDownItems?	toolStripDropDownButton1.DropDownItems.Clear();	0
32769738	32768867	Outlook 2013: Programmaticaly reply to emails with HTML signature	MailItem.Close(OlInspectorClose.olDiscard)	0
21417398	21417276	How can i change label text from diferent class (C#)	public class ChangeTextForMaxSkill\n{\n    buildEditor editor;\n\n    public ChangeTextForMaxSkill(buildEditor editor) // inject reference to form\n    {\n        this.editor = editor;\n        Button button = new Button();\n        button.Click += new EventHandler(changeText);\n        form.Controls.Add(button);\n    }\n\n    private void changeText(object sender, EventArgs e)\n    {\n        // Get reference to the label\n        editor.maxSkillPoint_TextChanged(editor, "maxSkillPoint");\n    }\n}	0
33774954	33720270	EmguCV Canny black window	Gray grayCannyThreshold = new Gray(80.0);\nGray grayThreshLinking = new Gray(160.0);	0
13395739	13395566	Image White Line	graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;	0
7348078	7348047	linq and string of array problem. Try to find elements in string of array	using System.Linq;	0
10717062	10716800	Workaround to "Item has already been added. Key in dictionary" using the same key everytime but with a different value	if(StartInfo.EnvironmentVariables.ContainsKey("TMP_VAR"))\n    StartInfo.EnvironmentVariables["TMP_VAR"] = "C:/temp/sim";\nelse\n    StartInfo.EnvironmentVariables.Add("TMP_VAR", "C:/temp/sim");	0
14999857	14999773	C#, json .net - value of the two words	public class getFoldersDataFolders\n{\n    [JsonProperty(PropertyName = "Folder ID")]\n    public int FolderID { get; set; }\n    public string Name { get; set; }\n}	0
7378312	7378287	WP7 running method on exit	Page.OnNavigatingFrom	0
20114252	20072485	Devexpress DataGrid contextmenu disappear	private void gridViewOrders_MouseDown (object sender, MouseEventArgs e)\n {\n      GridView gv = sender as GridView;\n\n      if (gv != null)\n      {\n           if (e.Button == System.Windows.Forms.MouseButtons.Left)\n           {\n                ShowWaitScreen (message);\n                ...\n                CloseWaitScreen ( )\n           }\n       }\n }	0
9517981	9517323	Extract image URL in a string (RSS with syndicationfeed)	string source ="<img src=\"http://MyUrl.JPG.jpg\"";\nvar reg = new Regex("src=(?:\"|\')?(?<imgSrc>[^>]*[^/].(?:jpg|bmp|gif|png))(?:\"|\')?");\nvar match=reg.Match(source);\nif(match.Success)\n{\n  var encod = match.Groups["imgSrc"].Value;\n}	0
4956803	4956066	How do I access properties from page in ContentPlaceholder in my MasterPage	public partial class FooMaster : System.Web.UI.MasterPage\n{\n    // this is originally from the designer-file\n    protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder;\n\n    protected override void OnPreRender(System.EventArgs e)\n    {\n        var fooPageInstance = this.ContentPlaceHolder.BindingContainer as FooPage;\n        var fooPropertyInstance = fooPageInstance.fooProperty;\n        // TODO do something with the property\n    }\n}	0
12056644	12056523	remove escape characters from char in c#	string dbValue = ...; // FROM DB!\nstring cValue = dbValue == null ? String.Empty : dbValue.Trim('\0').Trim();	0
3725249	3725224	Linq2Sql: Using IQueryable in select	ToList()	0
6219339	6178043	Get a list of files in a Solution/Project using DXCore console application	static void Main(string[] args)\n{\n  string SolutionPath;\n  if (args != null && args.Length > 0)\n    SolutionPath = args[0];\n  else\n    SolutionPath = @"c:\Projects\TestDXCoreConsoleApp\TestDXCoreConsoleApp.sln";\n\n  try\n  {\n    ParserHelper.RegisterParserServices();\n\n    Console.Write("Parsing solution... ");\n\n    SolutionParser solutionParser = new SolutionParser(SolutionPath);\n    SolutionElement solution = solutionParser.GetParsedSolution();\n    if (solution == null)\n      return;\n\n    Console.WriteLine("Done.");\n\n    foreach (ProjectElement project in solution.AllProjects)\n      foreach (SourceFile file in project.AllFiles)\n        foreach (TypeDeclaration type in file.AllTypes)\n        {\n          Console.Write(type.FullName);\n          Console.WriteLine(", members: " + ((ITypeElement)type).Members.Count);\n        }\n  }\n  catch (Exception ex)\n  {\n    Console.WriteLine(ex.Message);\n  }\n  finally\n  {\n    ParserHelper.UnRegisterParserServices();\n  }\n\n  Console.ReadLine();\n}	0
2241124	2241105	How to best name fields and properties	public class Foo\n{\n    private string bar;\n    public string Bar { get { return bar; } }\n}	0
27312230	27311868	Multiple stored procedures in VS 2010	public class MyResultClass\n{\n    public string Column1 { get; set; }\n    public string Column2 { get; set; }\n}\n\nprivate static readonly Dictionary<string, IEnumerable<MyResultClass>> \n    CachedResults = new Dictionary<string, IEnumerable<MyResultClass>>();\n\nprotected void OnTreeViewSelectionChanged(object sender, EventArgs e)\n{\n    // I'm not overly familar with the treeview off the top of my head,\n    // so get selectedValue however you would normally.\n    var selectedValue = ????;\n    IEnumerable<MyResultClass> results;\n\n    // Try to find the already cached results and if false, load them \n    if (!CachedResults.TryGet(selectedValue, out results))\n    {\n        // GetResults should use your current methodology for getting the results\n        results = GetResults(selectedValue);\n        CachedResults.Add(selectedValue, results);\n    }\n\n    myGridView.DataSource = results;\n}	0
31916501	31916388	Creating a controller for a model using EF (No key error)	namespace MvcMusicStorePractice.Models\n{ \n    public class Album\n    {   \n        [Key]\n        public int AlbumId { get; set; }\n        public int GenreId { get; set; }\n        public int ArtistId { get; set; }\n        public string Title { get; set; }\n        public decimal Price { get; set; }\n        public string AlbumArtUrl { get; set; }\n\n        public virtual Genre Genre { get; set; }\n        public virtual Artist Artist { get; set; }\n    }\n}	0
22774109	22773928	c# Print rows from array that only contain positive integers	for (int r = 0; r < Rows; r++)\n{\n    bool rowOkay = true;\n    for (int c = 0; c < Cols; c++)\n    {\n        if (m[r, c] <= 0)\n        {\n            rowOkay = false;\n        }\n    }\n    if (rowOkay)\n    {\n        for(int i=0;i<Cols;++i) {Console.Write("{0} ", m[r,i]);}\n        Console.WriteLine();\n    }\n}	0
14021113	14021018	get all elements contain attributes from a namespace	XNamespace my = "http://www.my.com/";\nIEnumerable<XElement> list1 =\n        from el in xdoc.Root.DescendantsAndSelf()\n        where el.Attributes().Any(attr => attr.Name.Namespace == my)\n        select el;	0
29641844	29608066	Converting single dimension array to a 2D array in C# for AES data matrix	class Program\n{\n    static void Main(string[] args)\n    {\n        byte[] original = new byte[] { 99, 111, 98, 97, 112, 97, 115, 115, 99, 111, 98, 97, 112, 97, 115, 115 };\n        byte[,] result = MakeAState(original);\n\n        for (int row = 0; row < 4; row++)\n        {\n            for (int column = 0; column < 4; column++)\n            {\n                Console.Write(result[row,column] + "   ");\n            }\n            Console.WriteLine();\n        }\n\n\n    }\n\n    public static byte[,] MakeAState(byte[] block)\n    {\n        if (block.Length < 16)\n        {\n            return null;\n        }\n\n        byte[,] state = new byte[4,4];\n\n        for (int i = 0; i < 16; i++)\n        {\n            state[i % 4, i / 4] = block[i];\n        }\n\n        return state;\n    }\n}	0
3289882	3289779	Binding to ViewModel from XAML	{Binding DataContext.ListOfStatus, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TypeOfParentControl}}}	0
17461154	17435654	Problems associating a hyperlink to a shape / image	using (Image img = Image.FromFile(imgFolder + Consts.MENU_BUTTON))\n{\n    worksheet.Drawings.AddPicture("Menu", img, new ExcelHyperLink("#Menu!A1", UriKind.Relative));\n}	0
2636474	2636454	can we implement polymorphism using interface in c#?	IList<T>	0
34167030	34166941	Append delimited data to .txt file	try\n    {\n        string name = nameTextBox.Text;\n        string number = numberTextBox.Text;\n\n        using (TextWriter tsw = new StreamWriter("PhoneList.txt", true))\n        {\n            tsw.WriteLine(name + ", " + number);\n        }\n\n\n\n\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show(ex.Message);\n    }	0
22186153	22186107	How do I shutdown/close a process?	pname.ToList().ForEach(p => p.Kill());	0
23787422	23785971	regex match string agasint a pattern	var rgx = new Regex(@"(?i)^[a-z][a-z0-9]+\(name="".*?"",\s*country="".*?""\)$");	0
22658094	22612769	How to properly copy a row of data from one Access database to another using C#?	cmd.CommandText =@"INSERT INTO [;DATABASE="+ System.IO.Directory.GetCurrentDirectory() + @"\Out_data.mdb]." + treeView1.SelectedNode.Name +\n                 @" SELECT " + treeView1.SelectedNode.Name + ".* FROM " + treeView1.SelectedNode.Name + " WHERE (H11.[Added at:] = (#" + SelectedKey + "#))";	0
12092015	12091942	Custom html helper with LINQ expression in MVC 3	public static MvcHtmlString TagCloudFor<TModel , TProperty>( this HtmlHelper<TModel> helper , Expression<Func<TModel , TProperty>> expression )\n        where TProperty : IList<MyType>, IList<MyOtherType> {\n\n        //grab model from view\n        TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;\n        //invoke model property via expression\n        TProperty collection = expression.Compile().Invoke(model);\n\n        //iterate through collection after casting as IEnumerable to remove ambiguousity\n        foreach( var item in (System.Collections.IEnumerable)collection ) {\n            //do whatever you want\n        }\n\n    }	0
17599600	17526280	DataGridView To show cell content completely	DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;	0
33274080	33273899	How to get the "Date" of Max/Min Score with (name, course) group using Linq	var result = dt.AsEnumerable()\n           .GroupBy(r => new\n           {\n               name = r.Field<string>("Name"),\n               course = r.Field<string>("Course")\n           })\n           .Select(g => new\n           {\n               name = g.Key.name,\n               course = g.Key.course,\n               max = g.Max(r => r.Field<int>("score")),\nMax_Date    = g.FirstOrDefault(x=> x.Field<int>("score")==g.Max(r => r.Field<int>("score")).Date    ,\nMin_Date= g.FirstOrDefault(x=> x.Field<int>("score")==g.Min(r => r.Field<int>("score")).Date    ,\n               min = g.Min(r => r.Field<int>("score")),\n               ave = g.Average(r => r.Field<int>("score"))\n           }).Distinct().ToList();\nforeach (var item in result)\nConsole.WriteLine(s.name + "\t" + s.course + "\t" + s.max + "\t" + s.min + "\t" + (int)s.ave);	0
16300735	15550821	looping through IntPtr?	//assume this actually points to something (not zero!!)\nIntPtr pNative = IntPtr.Zero;\n\n//assume these are you image dimensions\nint w=640; //width\nint h=480; //height\nint ch =3; //channels\n\n//image loop\n//use unsafe\n//this is very fast!! \nunsafe\n{\n    for (int r = 0; r < h; r++)\n    {\n        byte* pI = (byte*)pNative.ToPointer() + r*w*ch; //pointer to start of row\n        for (int c = 0; c < w; c++)\n        {\n            pI[c * ch]      = 0; //red\n            pI[c * ch+1]    = 0; //green\n            pI[c * ch+2]    = 0; //blue\n\n//also equivalent to *(pI + c*ch)  = 0 - i.e. using pointer arythmetic;\n        }\n    }\n}	0
26712208	26712142	How to get all names and values of any object using reflection and recursion	object propertyValue = p.GetValue(obj, null);\nConsole.WriteLine(p.Name + ":- " + propertyValue);\n\nif (p.PropertyType.GetProperties().Count() > 0)\n{              \n    // what to pass in to recursive method\n    PrintProperties(propertyValue);\n}	0
13461852	13461505	Sql transactions with looping, one commit statment	using (TransactionScope scope = new TransactionScope())\n{\n    // your ado.net sql here\n\n    // if success then:\n    scope.Complete();\n}	0
12271025	12269269	Competitor app installs to same folder as mine, without requiring admin priveleges	var dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) \n          +    "\\MyCompanyName\\MyApplicationName";	0
20900039	20899865	Configuring log4net in unit tests to log to console and display proper date and time	BasicConfigurator.Configure();\nvar appender = LogManager.GetRepository()\n                         .GetAppenders()\n                         .OfType<ConsoleAppender>()\n                         .First();\n\nappender.Layout = new PatternLayout("%d %-5level %logger - %m%n"); // set pattern\nILog logger = LogManager.GetLogger(logger_name); // obtain logger	0
30381061	30380306	Youtube Api v3 multiple video duration	// define 2 separate requests\nSearchResource.ListRequest listRequestMedium = SearchResource.List("snippet");\nlistRequestMedium.Q = query;\nlistRequestMedium.Type = "video";\nlistRequestMedium.VideoDuration = SearchResource.ListRequest.VideoDurationEnum.Medium;\nSearchResource.ListRequest listRequestShort = SearchResource.List("snippet");\nlistRequestShort.Q = query;\nlistRequestShort.Type = "video";\nlistRequestShort.VideoDuration = SearchResource.ListRequest.VideoDurationEnum.Short;\n\nSearchListResponse shortVideos = listRequestShort.Fetch();\nSearchListResponse mediumVideos = listRequestMedium.Fetch();\n\n// merge the 2 result lists and iterate over them\nforeach (SearchResult searchResult in shortVideos.Items.Union(mediumVideos.Items).ToList()) {\n    // do something with the videos\n\n}	0
21727883	21727757	Find an integer after dot in c#	string[] ip1 = "92.44.12.5/28".Split('.', '/');\nint [] ipArray = Array.ConvertAll(ip1,Int32.Parse);\n\nConsole.WriteLine(ipArray[3]);	0
8537344	8537257	how to use Invoke method in a file of extensions/methods?	label.BeginInvoke( (Action) (() => label.Text = text));	0
7740962	7713044	how do i append a list of ids to a http webrequest in wp7?	StringBuilder idList = new StringBuilder();\n        bool flag = false;\n        foreach (KeyValuePair<string, WidgetBean> key in beanList)\n        {\n            WidgetBean bean = key.Value;\n            if (!flag)\n            {\n                flag = true;\n            }\n            else\n            {\n                idList.Append(bean.getId()).Append(',');\n            }\n          }	0
18608818	18540316	How to make One-To-One relationship with existing fields?	public class Customer\n{\n    public Customer()\n    {\n        Address = new Address();\n    }\n\n    public Guid Id { get; set; }\n    public string Name { get; set; }\n    public Address Address { get; set; }\n}\n\npublic class Address\n{\n    public Guid Id { get; set; }\n    public string City { get; set; }\n    public string Country { get; set; }\n    public string Street { get; set; }\n}\n\npublic  class  CustomerContext : DbContext\n{\n    public IDbSet<Customer> Customers { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n         modelBuilder.Entity<Customer>()\n                .HasRequired(x => x.Address)\n                .WithRequiredPrincipal();\n         base.OnModelCreating(modelBuilder);\n    }\n}	0
1341509	1341397	how to create shared folder in C# with read only access?	IWHSInfo2 info = new WHSInfoClass();    \nIShareInfo2 share = info.CreateShare("SharedFolderName", "SharedFolderDescription", 0);\n\nWHSUserPermission perm1 = new WHSUserPermission();\nperm1.userName = "User1";\nperm1.permission = WHSSharePermissions.WHS_SHARE_READ_ONLY;\nWHSUserPermission perm2 = new WHSUserPermission();\nperm2.userName = "User2";\nperm2.permission = WHSSharePermissions.WHS_SHARE_READ_WRITE;\n\n\nArray permsArray = Array.CreateInstance(typeof(WHSUserPermission), 2);\npermsArray.SetValue(perm1, 0);\npermsArray.SetValue(perm2, 1);\nshare.SetPermissions(permsArray);	0
22002197	22002196	Apply a Boolean Test to Each Value in a C# Dictionary	if( groupStacks.All( s => !s.Value.Any() ) ) {\n    //do something\n}	0
16808270	16806780	passing the value of dropdownlist into gridview	DataTable dttable = new DataTable();\nDataColumn column;\nDataRow row; \n\ncolumn = new DataColumn();\ncolumn.DataType = Type.GetType("System.String");\ncolumn.ColumnName = "EmpName";\ndttable.Columns.Add(column);\n\nrow = table.NewRow();   \nrow["EmpName"] = DropDownList1.SelectedText;\ndttable.Rows.Add(row);\n\nGridview1.DataSource = dttable;\nGridview1.DataBind();	0
7436177	7436103	Do function on only 1 Control of NumericUpDown	foreach (Control c in NumericUpDown.Controls.OfType<TextBox>())	0
28838622	28838305	How to detect ENTER key on button	Private Sub Button1_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles Button1.PreviewKeyDown\n    If e.KeyCode = Keys.Enter Then e.IsInputKey = True\nEnd Sub	0
29105586	29105350	Filter list using lambda or anything easier	var id1 = new List<int> { 2, 4, 6, 8, 9, 3, 5 };\n        var id2 = new List<int> { 2, 9, 7, 3, 15};\n        var memberOrders = id1.Intersect(id2);	0
19322646	19322390	Coordinates changed after rotation XAML-shape	var obj = sender as Grid;\n\nvar transform = obj.TransformToVisual(Field);\nPoint parentPoint = transform.TransformPoint(new Point(0, 0));	0
5979441	5979392	Fluent nhibernate, delete a non-nullable property and replace it	var oldBlueprint = notebook.Blueprint;\nnotebook.Blueprint = // new blueprint code;\nsession.Flush(); // might or might not be needed\nsession.Delete(oldBlueprint);	0
15114979	15114544	Rotating a scanned PDF file	images = array()\nimages[0] = masterimage.flip(false).rotate(0)\nimages[1] = masterimage.flip(false).rotate(180)\nimages[2] = masterimage.flip(true).rotate(0)\nimages[3] = masterimage.flip(true).rotate(180)\n\nfor i = 0...3\n    if qrCodePlacedCorrectly(images[i])\n        output = images[i]\n        quit	0
4413047	4412974	Regular Expression for a project Number help	\w{3}\d{4}-\d{3}\.\d{2}	0
22884961	22850356	Get application username for Audit table	DECLARE @username varchar(128)\n    SET @username = CONVERT(VarChar(128), CONTEXT_INFO());\n    PRINT @username\n    DECLARE @ID_User int\n    SET @ID_User = ( SELECT Users.ID_User\n                       FROM Users\n                         WHERE Users.Username=@username )\n    PRINT @ID_User	0
29259652	29259224	How to take out two integers from an array and make them two variables?	static void Main(string[] args)\n    {\n        int n = int.Parse(Console.ReadLine());\n        int[] array = new int[n];\n\n\n        for(int i=0; i<array.Length; i++)\n        {\n            array[i] = int.Parse(Console.ReadLine());\n\n        }\n\n\n\n        int n1 = array[0];\n        int n2 = array[1];\n        //...\n        //...\n        Console.WriteLine(n1);\n        Console.WriteLine(n2);\n\n\n\n\n    }	0
2497559	2497519	C# How to to tell what process is using a file?	handle.exe -a <filename>	0
8921903	8921848	How to get rows collection based on selected cells in DatagridView	List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();\n\nforeach(DataGridViewCell cell in dataGridView.SelectedCells)\n{\n    rowCollection.Add(dataGridView.Rows[cell.RowIndex];\n}	0
13411953	13408130	selecting dropdownlist item from sqldatamart asp.net	DataSourceSelectArguments args = new DataSourceSelectArguments();\nDataView view = (DataView)SqlDataSource1.Select(args);\nDataTable dt = view.ToTable();\n\nDropDownList[] array = { kw1, kw2, kw3, kw4, kw5, kw6 };\nint i;\nfor (i = 0; i < dt.Rows.Count;i++ )\n{\n    array[i].SelectedItem.Text = dt.Rows[i][0].ToString();\n}\n\n// If array length (number of DropDowns) is greater than rows in datasource\n// Remaining Dropdowns will get text N/A --- Now i=dt.Rows.Count\nfor (; i < array.Length; i++)\n{\n    array[i].SelectedItem.Text = "N/A";\n}	0
11086497	11086363	How to make these n methods to a single generic method?	public T GetError<T>(T obj) where T: BaseResponse\n{\n  obj.ErrorMessage= string.Format("Err msg related to {0}", typeof(T).Name);\n  return obj;\n}	0
10146910	10144268	check for windows installer mutex availability	bool msiIsRunning = false;\n    try\n    {\n        using(var mutex = Mutex.OpenExisting(@"Global\_MSIExecute"))\n        {\n            msiIsRunning = true;\n        }\n    }\n    catch (Exception)\n    {\n       // Mutex not found; MSI isn't running\n    }	0
2060872	2060706	why would a re-thrown exception in a button click not get back to the user?	Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);	0
8024008	8023868	Executing code after all the overrides of a virtual method	public void Render()\n{\n    DoRender()\n\n    foreach (var child in _children)\n    {\n        child.Render();\n    }\n}\n\nprotected virtual void DoRender()\n{\n}	0
3642116	3642099	in c#, how do i convert this data structure into Json	IEnumerable<Calendar> calendars = ...\n\nreturn Json(\n    calendars.Select(calendar => new\n    {\n        Names = calendar.CalendarEvents.Select(e => e.Name),\n        Dates = calendar.CalendarEvents.Select(e => e.Date)\n    })\n);	0
33284924	33284795	Confused about setting up a connection to a microsoft access database while using C#	string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\MyFolder\Northwind.accdb";\nusing( OleDbConnection cnn = new OleDbConnection(connectionString))\n{\n    try\n    {\n        cnn.Open();\n        Console.WriteLine("Connection Open!");\n        cnn.Close();\n    }\n    catch (Exception ex)\n    {\n        Console.WriteLine("Error: Connection Cannot be Opened!");\n    }\n}	0
26015352	26015257	How to get Image from resource project	new Uri("pack://application:,,,/Gestore;component/View/Resources/Images/immagine1.png")	0
9728949	9728926	How to convert this line from C# to VB.net (Windows Phone 7)	AddHandler btnAdd.Click, AddressOf btnAdd_Click	0
7873516	7873453	Getting Icon from ResourceStream	using(Stream stream = Application.GetResourceStream(new Uri("/MyNameSpace.ico")).Stream)\n{\n    Icon myIcon = new System.Drawing.Icon(stream);\n}	0
3204147	3203951	Is there any way to constrain a type parameter to EITHER a reference type OR a nullable value type?	public bool GetItem<T>(out T value)\n{\n    if (someCondition<T>())\n    {\n        value = someCalculation<T>();\n        return true;\n    }\n    else\n    {\n        value = default(T);\n        return false;\n    }\n}	0
11509958	11509804	Reading XML from URL and assign it to a list	XDocument xDoc = XDocument.Load("http://api.serviceu.com/rest/events/occurrences?orgkey=613dc2ce-0b32-4926-8e7e-33ee279be1cb");\nvar list = xDoc.Descendants("Occurrence")\n            .Select(o => new Item\n            {\n                Category = (string)o.Element("CategoryList"),\n                EMail = (string)o.Element("ContactEmail"),\n                Description = (string)o.Element("Description"),\n            })\n            .ToList();\n\n\npublic class Item\n{\n    public string Category;\n    public string EMail;\n    public string Description;\n}	0
2470119	2470103	Best way to manipulate XML in .NET	using System.Xml.Linq;\nusing System.Xml.XPath;\n\nvar doc = XElement.Load("test.xml");\ndoc.XPathSelectElement("//customer").Remove();\ndoc.Save("test.xml");	0
27233492	27232420	WPF How to Set selecteditem of bound combobox in a listview with different itemsource	public class SalesAgentRec\n    {\n        public string MCName { get; set; }\n        public string MCPostCode { get; set; }\n        public string MCSource { get; set; }\n        public string MCUid { get; set; }\n        public string MCRecs { get; set; }\n        public List<LookUpCollection_6> { get; set; }\n    }	0
26844008	26843959	Move ConnectionString to App.config	ConfigurationManager.ConnectionStrings["connection"].ConnectionString;	0
32373900	32373829	Unit Testing Json Result	JsonResult result = testController.GetStatuses();\nstring json = (string) result.Data;\nList<Status> statuses = JsonConvert.DeserializeObject<List<Status>>(json);\n// Check statuses	0
20891535	20891396	Generating tiff file from a multi-line text box in C#	System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(800, 1000); //Creates Bitmap\nusing(Graphics g = Graphics.FromImage(bitmap))\n{\n   RectangleF rect = new RectangleF(new PointF(0, 700), new SizeF(200,200)); // adjust these accordingly for your bounding rect\n   StringFormat drawFormat = new StringFormat();\n   drawFormat.Alignment = StringAlignment.Near;\n   g.DrawString("Comment: " + CommentBox.Text, outputFont, Brushes.Black, rect, drawFormat); // Writing the text from the comment box on to the Tiff file.\n}	0
17172522	17172381	Getting unique values from a list of objects with a List<string> as a property	var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList();	0
15195466	15195139	is-else statement	private void btnSort_Click(object sender, RoutedEventArgs e)    \n    {   \n     ArrayList Sorting = new ArrayList();\n                if (!this.lstbxResults.Items.Contains(this.lstbxResults.Items))\n                {\n                    foreach (var fSort in lstbxResults.Items)\n                    {\n                        Sorting.Add(fSort);\n                    }\n\n                    Sorting.Sort();\n\n                    lstbxResults.Items.Clear();\n\n                    foreach (var fSort in Sorting)\n                    {\n                        if (!this.lstbxResults.Items.Contains(fSort))\n                        {\n                            lstbxResults.Items.Add(fSort);\n                        }\n\n                    }\n                }\n    }	0
3279191	3278790	unknown number of cursors	public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables)	0
31006343	31005879	How to pass window and string parameter from code behind into User Control	MainWindow myRunnningMainWindow = (Application.Current.MainWindow as MainWindow);\n\n     if(myRunningWindow!=null)\n        {\n         //Do what you want with the main window\n        }	0
33764745	33660660	time out expired issue in lambda method for contains	string[] splits = keyword.Split(' ');\n\n        var fproducts = (from products in db.tbl_Product\n                         where splits.Any(item => products.Prod_Name_Fa.Contains(item) ||\n                    products.shortDesc.Contains(item) || products.Prod_Code.Contains(item))\n                         select products.ID).Distinct();	0
16149066	16148898	Select number of data based of a specific node	var xDoc = XDocument.Parse(xml);\nvar functions = xDoc.Descendants("function")\n                .Select(f => new\n                {\n                    Name = f.Element("name").Value,\n                    Types = f.Descendants("type").Select(t=>t.Value).ToList(),\n                    //Types = f.Descendants("type").Count()\n                    TypeValues = f.Descendants("type-value").Select(t=>t.Value).ToList()\n                })\n                .ToList();	0
625748	625721	C# Subclass with same method	abstract class SuperClass\n{\n    protected bool HasContentImpl(int chapterID, int institution)\n    {\n        Database db = new Database();\n        int result;\n\n        if (institution >= 0) // assuming negative numbers are out of range\n            result = db.ExecuteSpRetVal(chapterID, institution);\n        else\n            result = db.ExecuteSpRetVal(chapterID);\n\n        return result > 0;\n    }\n}\n\nclass SubClass1 : SuperClass\n{\n    public bool HasContent(int chapterID)\n    {\n        return base.HasContentImpl(chapterID, -1);\n    }\n}\n\nclass SubClass2 : SuperClass\n{\n    public bool HasContent(int chapterID, int institution)\n    {\n        return base.HasContentImpl(chapterID, institution);\n    }\n}	0
12061149	12061119	Is there a "cleaner" way to set the properties of a group of controls than this?	Slider Slider_1 = new Slider(); \nSetProperties(Slider_1,.....)\n\n\npublic void SetProperties(Slider slider,some other parameters)\n{\n    slider.SetValue(Grid.ColumnProperty, 0);\n    slider.Margin = new Thickness(30, 12, 0, 0);\n    slider.Orientation = Orientation.Vertical;\n    slider.Maximum = 10;\n    slider.StepFrequency = 0.25;\n    slider.TickFrequency = 0.25;\n    slider.TickPlacement = TickPlacement.Outside;\n    slider.Transitions = new TransitionCollection();\n    slider.Transitions.Add(new EntranceThemeTransition() { });\n}	0
637728	358700	How to install a windows service programmatically in C#?	//Installs and starts the service\nServiceInstaller.InstallAndStart("MyServiceName", "MyServiceDisplayName", "C:\PathToServiceFile.exe");\n\n//Removes the service\nServiceInstaller.Uninstall("MyServiceName");\n\n//Checks the status of the service\nServiceInstaller.GetServiceStatus("MyServiceName");\n\n//Starts the service\nServiceInstaller.StartService("MyServiceName");\n\n//Stops the service\nServiceInstaller.StopService("MyServiceName");\n\n//Check if service is installed\nServiceInstaller.ServiceIsInstalled("MyServiceName");	0
7076810	7076750	ASP.NET MVC3 - application start folder	Server.MapPath("~/Layouts");	0
26426111	26425986	How to set DataContext in a Dialog Window to its parent's DataContext	NieuwSimulatie NiewSimulatieWindow = new NieuwSimulatie()\n{\n    Owner = this,\n    DataContext = YourDataContext;\n};\n\nbool? SimulatieAangemaakt = NiewSimulatieWindow.ShowDialog();	0
31535202	31535122	c# json newtonsoft conversion	ReportDirections reportDirections = new ReportDirections();\nreportDirections.selected = "inbound";\n\nReportDetails ReportDetails = new ReportDetails();\nReportDetails.reportTypeLang = "conversations";\nReportDetails.reportDirections = reportDirections; // and so with the other props	0
25424513	25424426	How to access view path from inherited controller?	return View("/MaterController/MyViewName");	0
23738536	23738440	How to use TryParse	MessageBox::Show("Invalid Value....Try Again");	0
68772	68750	How do you write a C# Extension Method for a Generically Typed Class	namespace System.Web.Mvc\n{\n    public static class ViewPageExtensions\n    {\n        public static string GetDefaultPageTitle<T>(this ViewPage<T> v)\n        {\n            return "";\n        }\n    }\n}	0
5468026	5466873	Getting stdout from console app asyncronously without waiting for console to exit	sys.stdout.flush()	0
24062832	24062632	Save a file in folder opened by dialog box	var fbd = new FolderBrowserDialog();\nif(fbd.ShowDialog() == DialogResult.OK)\n{\n    var localPath= Path.Combine(fbd.SelectedPath, Path.GetFilename(remote_address));\n    File.Copy(remote_address, localPath);\n}	0
28492531	28492489	how to take two words from a string and then add a -	string output = "0123456789ABCDEF";\nint i = 2;\n\nwhile (i < output.Length) {\n    output = output.Insert(i, "-");\n    i += 3;\n}	0
2163911	2163560	How to check if a C# Bitmap is valid before adding it to a picturebox	private void button1_Click(object sender, EventArgs e) {\n        if (openFileDialog1.ShowDialog(this) != DialogResult.OK) return;\n        try {\n            Bitmap bmp = new Bitmap(openFileDialog1.FileName);\n            if (pictureBox1.Image != null) pictureBox1.Image.Dispose();\n            pictureBox1.Image = bmp;\n        }\n        catch (Exception ex) {\n            MessageBox.Show(ex.Message, "Could not load image");\n        }\n    }	0
791789	791756	Trying to parse XML tree with Linq to XML (C#)	List<Question> questions = (from question in xdoc.Element("survey").Element("questions").Elements("question")\n         select new Question\n         {\n           text = question.Element("text").Value,\n           anwsers = (from answer in question.Element("answers").Elements("answer")\n                select new Anwser\n                {\n                  content = answer.Element("v").Value\n                }).ToList()\n         }).ToList();	0
9169715	9169647	Want Checked Item From Listview	if (PackagesListView.Items.Count > 0)\n{                \n    for (int i = 0; i < PackagesListView.Items.Count; i++)\n    {\n        CheckBox PackageCheckBox= (CheckBox)PackagesListView.Items[i].FindControl("PackageCheckBox");\n        if (PackageCheckBox!= null)\n        {\n            if (PackageCheckBox.Checked.Equals(true))\n            {\n                //do your stuff here\n            }\n        }\n    }\n}	0
336729	336633	How to detect Windows 64-bit platform with .NET?	static bool is64BitProcess = (IntPtr.Size == 8);\nstatic bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();\n\n[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern bool IsWow64Process(\n    [In] IntPtr hProcess,\n    [Out] out bool wow64Process\n);\n\npublic static bool InternalCheckIsWow64()\n{\n    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||\n        Environment.OSVersion.Version.Major >= 6)\n    {\n        using (Process p = Process.GetCurrentProcess())\n        {\n            bool retVal;\n            if (!IsWow64Process(p.Handle, out retVal))\n            {\n                return false;\n            }\n            return retVal;\n        }\n    }\n    else\n    {\n        return false;\n    }\n}	0
12244388	12244191	How to flatten object properties using linq	var flattenTexts = texts\n    .GroupBy(x => x.Key)\n    .Select(x => new { Key = x.Key, \n                       De = x.First(y => y.LanguageId == "De").Value, \n                       En = x.First(y => y.LanguageId == "En").Value \n                     });	0
27106172	27019484	Enable JavaScript in PhantomJS with C#	phantomDriver.GetScreenshot();	0
27432686	27432608	incorrect syntax near keyword 'end'	query.AppendFormat("[{0}] {1}, ", fields[i], fieldtype[i]);	0
666585	666505	How can I add a new property in an already existing xml file?	XNamespace ns = @"http://schemas.microsoft.com/developer/msbuild/2003";\nXDocument doc = XDocument.Load(path);\nvar noWarn = (from grp in doc.Descendants(ns + "PropertyGroup")\n        from el in grp.Descendants(ns + "NoWarn")\n        select el).FirstOrDefault();\nif(noWarn==null) {\n    var grp = doc.Descendants(ns+"PropertyGroup").First();\n    grp.Add(new XElement(ns+"NoWarn", "1234"));\n} else {\n    noWarn.Value += "; 1234";\n}\ndoc.Save(path);	0
18819246	18583933	How to Place a Pause in a Windows Phone 8 Application	VibrationController.Default.Stop();	0
6639609	6639237	WPF Custom Control, DependencyProperty issue	this.Dispatcher.BeginInvoke((Action)(() =>\n{\n    viewModel.LastName = "asdf";\n\n    viewModel.LastName = "56udfh";\n\n    viewModel.LastName = "09ualkja";\n}),\nDispatcherPriority.DataBind);	0
30442569	30441922	Compare Position Array with button location	PointR s = new PointR();\n  s.X=button1.Location.X;\n  s.Y=button1.Location.Y;\nforeach (PointR w in _points)\n     {\n     if (s.X >= w.X && s.Y >=w.Y)\n      {\n            button1.PerformClick();\n             break;\n      }\n    }	0
27676509	27676409	new Bitmap - Parameter is not valid	Console.WriteLine(new System.IO.FileInfo("..//..//images//brick.jpg").FullName);	0
26603681	26602534	Use multithreading for multiple file copies	using System.IO;\nusing System.IO.Compression;\n\n.....\n\nstring startPath = @"c:\example\start";\nstring zipPath = @"c:\example\result.zip";\nstring extractPath = @"c:\example\extract";\n\nZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);\n\nZipFile.ExtractToDirectory(zipPath, extractPath);	0
25543240	25543102	Getting the Object From IGrouping in c#	var quer2 =\n      from  ff in ddd\n      from  ss in ff.availableHotels.OrderBy(x =>x.totalSalePrice) \n      group ss by ss.hotelCode\n      select new\n      {\n        GroupKey = ss.Key,      \n        GroupValuesList =  ss.ToList()\n      };\n\n\nConsole.WriteLine(quer2.First().GroupKey);	0
27418086	27402329	Sorting string fields with alphanumeric values in crystal report in C#	values.OrderBy(s=>s.Substring(0,3)).ThenBy(s=>Convert.ToInt32(s.Substring(3, s.Length-3)))	0
16081973	16081837	How to put variable into JSON	var msg = "my message"; // this would be set somewhere else in the code\nvar jsonObject = {\n    "alert" : "{0}",\n    "badge" : "7",\n    "sound" : "sound.caf",\n    "msg" : msg\n};\n\n// convert the object into a string\nvar jsonString = JSON.stringify(jsonObject);\n\npush.QueueNotification(new GcmNotification().ForDeviceRegistrationId(registrationId)\n        .WithJson(jsonString));	0
21110601	21110461	insert relative path for saving a zip file in asp.net	string path_cartella = Server.MapPath("~/temp/document");\nstring path_cartella_zip = Server.MapPath("~/temp/document_zip");	0
2165050	2165024	How SQL Server processes simultaneous requests?	SET DEADLOCK_PRIORITY	0
21518431	21517389	How to sync system clock with global date/time?	public class Example\n{\n    static void Main(string[] args)\n    {\n\n    }\n}	0
13286449	13286344	Directory.GetFiles with multiple filters, collect one string array	string sourceDir = "C:\\Users\\ozkan\\Desktop\\foto\\"\n string[] picList;        \n string pattern = "*.jpg|*.png|*.gif";\n string[] filters = pattern.Split('|');\n picList =  filters .SelectMany(f=> Directory.GetFiles(sourceDir , f)).ToArray();	0
15275836	15275637	Closure captured variable modifies the original as well	private class Closure\n{\n    public int j;\n    public int Method()\n    {\n        for (int i = 0; i < 3; i++)\n        {\n            this.j += i;\n        }\n        return this.j;\n    }\n}\nstatic void Main(string[] args)\n{\n    Closure closure = new Closure();\n    closure.j = 0;\n    Func<int> f = closure.Method;\n    int myStr = f();\n    Console.WriteLine(myStr);\n    Console.WriteLine(closure.j);\n    Console.Read();\n}	0
5679025	5678332	c# How to read a single file with normal and xml text elements	internal static class StreamExtensions\n{\n    public static void CopyTo(this Stream readStream, Stream writeStream)\n    {\n        byte[] buffer = new byte[4096];\n        int read;\n        while ((read = readStream.Read(buffer, 0, buffer.Length)) > 0)\n            writeStream.Write(buffer, 0, read);\n    }\n}	0
506637	505566	Loading custom configuration files	ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();\nconfigMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);	0
6449792	6449701	Copying information from a server	File.Copy(@"\\Server\Users",@"c:\userShare");	0
6448980	6448913	Displaying page numbers	using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        // usage program.exe page#\n        // page# between 1 and 100\n        int minPage = 1;\n        int maxPage = 100;\n        int currentPage = int.Parse(args[0]);\n\n        // output nice pagination\n        // always have a group of 5\n\n        int minRange = Math.Max(minPage, currentPage-2);\n        int maxRange = Math.Min(maxPage, currentPage+2);\n\n        if (minRange != minPage)\n        {\n            Console.Write(minPage);\n            Console.Write("...");\n        }\n\n        for (int i = minRange; i <= maxRange; i++)\n        {\n            Console.Write(i);\n            if (i != maxRange) Console.Write(" ");\n        }\n\n        if (maxRange != maxPage)\n        {\n            Console.Write("...");\n            Console.Write(maxPage);\n        }\n    }\n}	0
15329673	15329601	How to get all the values from appsettings key which starts with specific name and pass this to any array?	string[] repositoryUrls = ConfigurationManager.AppSettings.AllKeys\n                             .Where(key => key.StartsWith("Service1URL"))\n                             .Select(key => ConfigurationManager.AppSettings[key])\n                             .ToArray();	0
28924416	28922873	How to force object destruction when removed from an itemscontrol?	var ce = CharacterEditors[2];\nCharacterEditors.RemoveAt(2);\nce.Dispose();	0
2056177	2053545	Castle Windsor - Staging vs Production connectionString parameter for a Component	public interface IConnectionFactory\n{\n    public string GetConnectionString();\n}	0
29592571	29592236	Getting byte[16] to uint32[4]	String keyStr = "foobar";\n\nbyte[] keyBytes = new byte[16];\nEncoding.ASCII.GetBytes(keyStr).CopyTo(keyBytes, 0);\n\nUInt32[] keyArr = new UInt32[4];\n\nif (BitConverter.IsLittleEndian)\n    Array.Reverse(keyBytes);\n\nfor (int i = 0; i < 4; i++)\n    keyArr[i] = BitConverter.ToUInt32(keyBytes, i * 4);	0
29103088	29080839	How to enable Application Server role programattically on Windows 2008 R2 and Windows 7	ServerManagerCmd -install Application-Server AS-Ent-Services AS-Dist-Transaction AS-Incoming-Trans AS-Outgoing-Trans	0
16991983	16942378	Bandwidth throttling for Files in C#	long bps = (long)(102400 * ((double)percent / 100.0);   \nif (percent == 100)\n   bps = ThrottledStream.Infinite;\nts = new ThrottledStream(originalDestinationStream, bps);	0
34543033	34542860	Assign background image to button from database	byte[] data = (byte[]) dt.Rows[i][5];\nMemoryStream ms = new MemoryStream(data);\nbtn.BackgroundImage = Image.FromStream(ms);	0
27882002	27875390	One-to-one relationsip with optional dependent end using default conventions	modelBuilder.Entity<Person>().HasOptional(p => p.Car).WithRequired(c => c.Person);	0
19701585	19701362	Parsing data from HTML using HTMLAgilityPack	string name = "";\nvar node = htmlDocument.DocumentNode\n    .SelectSingleNode("//tr[@class='index']//td[@class='name']//a[@href]");\nif (node != null)\n    name = node.InnerText;	0
5373460	5373445	Performing XPath Queries on documents with default namespaces	xmlnsManager.AddNamespace("x", "http://namespaceFoo.com");\nXmlNode n1 = xmlData.SelectSingleNode("/Header", xmlnsManager);	0
4411134	4410943	How to compute a covariance matrix	public static void covm(double[,] x, out double[,] c)	0
437885	437864	Deriving a crypto key from a password	PasswordDeriveBytes pdb = new PasswordDeriveBytes("blahblahblah",null);\nbyte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };\nbyte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 0, iv);	0
23072080	23071822	Running exe from command line with parameters	public MainWindow()\n        {\n            var args = Environment.GetCommandLineArgs();\n            if (args.Length == 1)\n            {\n                MessageBox.Show("No argument provided");\n                Environment.Exit(0);\n            }\n            string arg1 = args[1];  // your argument\n            InitializeComponent();\n        }	0
22920508	22920398	Get count of open Thread of process in c#	p.Refresh();\nvar threadCount = p.Threads.Count;	0
5741058	5740756	Catching Unselecting All in ListView -- SelectedIndexChanged Firing Twice	this.listView1.ItemSelectionChanged += this.HandleOnListViewItemSelectionChanged;\n\n        private void HandleOnListViewItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e)\n        {\n            if (e.IsSelected)\n            {\n                this.detailsLabel.Text = this.GetDetails(e.Item);\n            }\n            else\n            {\n                this.detailsLabel.Text = String.Empty;\n            }\n        }	0
21329333	21328948	checked checkbox's value shown in listbox after button click	List<CheckBox> cbList=new List<CheckBox>();\n\npublic Form1()\n{\n        InitializeComponent();\n        btnOne.Click += btnOne_Click;\n        cbList.Add(chckOne);\n        cbList.Add(chckTwo);\n        //All the checkbox should be added into cbList.\n}\n\nvoid btnOne_Click(object sender, EventArgs e)\n{ \n    lstOne.Items.Clear();  \n    var checked_checkbox = cbList.Where(cb=>cb.Checked==true).ToList();\n    if(checked_checkbox.Count>0)\n    {\n        checked_checkbox.ForEach(x=>lstOne.Items.Add(x.Text));// Maybe you want put text of checkbox into listbox.\n    }\n}	0
16855532	16855333	Get folder on in same directory as App domain path	//NOTE:  using System.IO;\nString startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);\nInt32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);\nString newPath = Path.Combine(startPath.Substring(0, pos), "folder");  //replace "folder" if it's really something else, of course	0
2093269	2093150	Getting KeyNotFoundException when using key previously retrieved from key collection?	foreach(var item in _params)\n{\n   if(item.Key.ParamName.Equals(name))\n   {\n      return item.Value;\n   }\n}	0
13498042	13497739	Can someone please help me find the regex if an input string is a valid xml string?	bool TryGetValidXml(string s, out XDoxument res) {\n    try {\n        res = XDocument.Load(s);\n        return true;\n    } catch {\n        res = null;\n        return false;\n    }\n}	0
24046810	24044042	Javascript date to ASP.NET date: String was not recognized as a valid DateTime	myRequestDate = myRequestDate.Replace("\u200E", "");\nDateTime date5 = DateTime.ParseExact(myRequestDate, "d/M/yyyy", CultureInfo.InvariantCulture);	0
6000003	5996847	How to get all the image resources in a project?s sub folders?	Image image = new Image();\nimage.Source = new BitmapImage(new Uri(???pack://application:,,,/Images/ImageCategory1/Burn Disc.png???));	0
5916866	5916855	Using multiple versions of the same DLL	AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n    ...\n\n    static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n    {\n        if (/*some condition*/)\n            return Assembly.LoadFrom("DifferentDllFolder\\differentVersion.dll");\n        else\n            return Assembly.LoadFrom("");\n    }	0
20455345	20455317	How do i calculate the length of a line between two points?	Math.Sqrt(Math.Pow((end.Y - start.Y), 2) + Math.Pow((end.X - start.X), 2));	0
25514289	25513417	Cells text of DataGrid in a WPF project is being cleared when I scroll down and up	ScrollViewer.CanContentScroll="False"	0
30233702	30233458	Turn a webcam off	Camera.Dispose()	0
9754963	9754834	Setting Label object as per Listbox selected item	ListBoxItem item = ((ListBox)sender).SelectedItem as ListBoxItem;\nString itemText = (item != null) ? item.Content.ToString() : String.Empty;	0
19275129	19274607	Passing a variable name dynamically to a function	public class SomeClass\n{\n    public void myFunction(ref List<string> myList)\n    {\n    }\n}\n\npublic class SomeOtherClass\n{\n    public List<string> list1 { get; set; }\n    public List<string> list2 { get; set; }\n    public List<string> list3 { get; set; }\n\n    public void DoSomething(int listNumber)\n    {\n        SomeClass someObject = new SomeClass();\n\n        var parameter = typeof (SomeOtherClass).GetProperty("list" + listNumber).GetValue(this);\n        typeof (SomeClass).GetMethod("myFunction").Invoke(someObject, new[] {parameter});\n    }\n}	0
2056107	2056087	LINQ to XML - selecting XML to a strongly typed object	Skills = prd.Descendants("Skill").Select(e => new Skill(e.Value)).ToList(),	0
13496122	13495995	Compare members of a type - calculate the difference between members	var cheapestPrice = parts.Min(p => p.Price);\nvar list = parts.Select(p => new { \n    Part = p,\n    DiffPercentage = ((p.Price - cheapestPrice) / cheapestPrice) * 100 \n});\n\nforeach (var p in list)\n    Console.WriteLine("{0}: {1},{2}%", p.Part.PartNo, p.Part.Price, p.DiffPercentage);	0
441223	441126	How Do I Bypass MS Access Startup When Using OLE?	Private Function OpenDatabaseWithShell(pDatabaseFullPath As String) As Access.Application\n\nDim AccObj As Access.Application\n\n    On Error GoTo ErrorHandler\n\n    Set OpenDatabaseWithShell = Nothing\n\n    Dim cmd As String\n\n    On Error Resume Next\n\n    ' basically build full msaccess.exe path and append database name and command switches\n    cmd = SysCmd(acSysCmdAccessDir) & "MSAccess.exe """ & psDatabaseFullPath & """"\n    cmd = cmd & " /nostartup /excl"\n\n    'start ms access with shell\n    Shell PathName:=cmd\n\n    Do 'Wait for shelled process to finish.\n      Err = 0\n      Set AccObj = GetObject(pDatabaseFullPath)\n    Loop While Err <> 0\n\n    On Error GoTo ErrorHandler\n\n    'return access object\n    Set OpenDatabaseWithShell = AccObj\n\nNormalExit:\n    Exit Function\n\nErrorHandler:\n    'error logging here\n    Exit Function\n\nEnd Function	0
19288922	19288845	Aborting a thread via its name	Dictionary<string, Thread> threadDictionary = new Dictionary<string, Thread>();\nThread myThread = new Thread(() => beginUser(picture));\nmyThread.Name = Convert.ToString(TableID);\nmyThread.Start();\nthreadDictionary.Add("threadOne", myThread);\n\nthreadDictionary["threadOne"].Abort();	0
18396840	18396709	How To bind A dropdownlist from enum in asp.net MVC using C#	public enum CityType\n    {\n        [Description("Select City")]\n        Select = 0,\n\n        [Description("A")]\n        NewDelhi = 1,\n\n        [Description("B")]\n        Mumbai = 2,\n\n        [Description("C")]\n        Bangalore = 3,\n\n        [Description("D")]\n        Buxar = 4,\n\n        [Description("E")]\n        Jabalpur = 5\n    }\n\nIList<SelectListItem> list = Enum.GetValues(typeof(CityType)).Cast<CityType>().Select(x =>    new SelectListItem(){ \n    Text = EnumHelper.GetDescription(x), \n    Value = ((int)x).ToString()\n}).ToList(); \n\n    int city=0; \n    if (userModel.HomeCity != null) city= (int)userModel.HomeCity;\nViewData["HomeCity"] = new SelectList(list, "Value", "Text", city);\n\n\n @Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" })	0
12164812	12161584	Absolute coordinates of UIElement in WinRT	private void Button_Click(object sender, RoutedEventArgs e)\n{\n   var button = sender as Button;\n   var ttv = button.TransformToVisual(Window.Current.Content);\n   Point screenCoords = ttv.TransformPoint(new Point(0, 0));\n}	0
7876846	7875564	how to bind dropdown in 3-tier architecture	List<State> objLstState =new List<State>();\n            objLstState = StateManager.GetStates();  //This method returns a list of States\n            if(objLstState!=null && objListState.Count>0)\n            {\n              dropDownSchoolState.DataSource = objLstState;\n              dropDownSchoolState.DataTextField = "Name";\n              dropDownSchoolState.DataValueField = "ID";\n              dropDownSchoolState.DataBind();\n            }	0
22861504	22819106	Is there a way to determine how POCO properties are serialized with YamlDotNet?	[YamlAlias("name")]	0
3451242	3451061	How to do correct polygon rotation? ( in C# though it applies to anything )	x' = x*Cos(angle) - y*Sin(angle)\ny' = x*Sin(angle) + y*Cos(angle)	0
8540948	8540752	Expire Cookie From LoginView	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack && string.IsNullOrEmpty(Request.QueryString["forceLogout"]))\n    {\n        // log the user out \n    }\n    else\n    {\n        // Your original logic\n    }\n}	0
2714214	2714118	Many To Many NHibernate	results = session.Find(\n        "from nhRegistration.UniversityClass as\n        uc where personid is null");	0
3004473	2995665	How do I centralize common code in silverlight with a classical Client/Server design?	#SILVERLIGHT	0
8074797	7937160	how to pass the sysdate value fom Fluent Nhibernate	public DateTime getdbdate()\n        {\n            var dt = this.UnitOfWork.CurrentSession.CreateSQLQuery("select sysdate from dual where rownum<2").UniqueResult();\n\n            if (dt != null)\n\n                return (DateTime)dt;\n            else           \n\n            return DateTime.Now;\n\n        }	0
25628893	25628766	ListView with BaseAdapter, show only one row	_HistoryList.Adapter = new AddItemBaseAdapter(this, textFromEditText);	0
7789235	7789038	C# Won't Load A Certain XML, But Works in Browser	string url = "http://stats.us.playstation.com/warhawk/XmlFeedAction.action?start=1&end=1";\n\n        WebClient client = new WebClient();\n        client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";\n        client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";\n        string data = client.DownloadString(url);\n\n        XmlDocument doc = new XmlDocument();\n        doc.LoadXml(data);	0
25649439	25649404	C# .NET email client alternate tr row colors based on even / odd	int count = 0;\nforeach (var item in logList)\n{\n      if (count % 2 == 0)\n      {\n        sb.AppendLine("<tr><td style='background-color:#bada55;'>" + Path.GetFileName(item) + "</td></tr>");\n\n      }\n      else\n      {\n         sb.AppendLine("<tr><td style='background-color:#55bada;'>" + Path.GetFileName(item) + "</td></tr>");\n      }\n      count++;\n}	0
10987680	10962335	How to upload/update file by FileStream and ResumableUploader in C#	DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");\nClientLoginAuthenticator authenticator = new ClientLoginAuthenticator(APPLICATION_NAME, ServiceNames.Documents, USERNAME, PASSWORD);\n\nstring slug = "Legal contract";\nMediaFileSource mediaSource = new MediaFileSource("c:\\contract.txt", "text/plain");\nUri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full?v=3");\n\nResumableUploader ru = new ResumableUploader();\nru.InsertAsync(authenticator, createUploadUrl, mediaSource.GetDataStream(), mediaSource.ContentType, slug, new object());	0
22225974	22221177	Append template from a XSLT into another XSLT	string templateName = "GetMonth";\n\nXmlNode template = xslDoc.SelectSingleNode(string.Format("/xsl:stylesheet/xsl:template[@name = '{0}']", templateName), nsMgr);\n\nif (template != null)\n{\n  // will append the template as last child of xsl:stylesheet\n  xslDoc2.DocumentElement.AppendChild(xslDoc2.ImportNode(template, true));\n  // as alternative to insert as the first child use\n  // xslDoc2.DocumentElement.InsertBefore(xslDoc2.ImportNode(template, true), xslDoc2.DocumentElement.FirstChild);\n  // now Save\n  xslDoc2.Save("XSLT2.xslt");\n}	0
10807000	10806984	Is it ok to add an "All" item to a Flags enum?	All = A | B | C | D	0
11754629	11753464	Exception thrown while trying to retrieve the object associated with a property in a lambda expression	public static MvcHtmlString EnumDisplayFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)\n    {\n        //Get the model\n        TModel model = htmlHelper.ViewData.Model;\n\n        //Compile expression as Func\n        Func<TModel, TEnum> method = expression.Compile();\n\n        //Calling compiled expression return TEnum\n        TEnum enumValue = method(model);\n\n        return MvcHtmlString.Create(GetEnumDescription(enumValue));\n    }	0
21590553	21590431	Handmade POCO with Entity Framework 6?	using ProjectName.Models;\nusing System;\nusing System.Collections.Generic;\nusing System.Data.Entity.ModelConfiguration;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\npublic class ProfileMapping : EntityTypeConfiguration<Profile>\n{\n    public ProfileMapping()\n    {\n        // Primary Key\n        this.HasKey(t => t.Id);\n\n        // Map POCO name to Column Name\n        this.Property(t => t.Firstname)\n            .HasColumnName("First_Name")\n            .HasMaxLength("256");\n\n\n        // Table Mapping\n        this.ToTable("Profiles");\n\n        // Relationships\n        this.HasRequired(t => t.Roles);\n    }\n}	0
24003981	24003458	How to easilly see number of event subscriptions while debugging?	textBox1.TextChanged += textBox1_TextChanged;\n    MessageBox.Show("asdf");\n    textBox1.TextChanged -= textBox1_TextChanged;        \n    textBox1.Text = DateTime.Now.ToString();\n    textBox1.TextChanged += textBox1_TextChanged;\n    var eventField = textBox1.GetType().GetField("TextChanged", BindingFlags.GetField\n                                                               | BindingFlags.NonPublic\n                                                               | BindingFlags.Instance);\n\n    var subscriberCount = ((EventHandler)eventField.GetValue(textBox1))\n                .GetInvocationList().Length;	0
12954070	12954026	How can I open a text file relative to my MVC project?	StreamReader reader = new StreamReader(Server.MapPath("~/bin/log/log00001.txt"));	0
8434131	8434063	Cannot access a control which is in the repeater , from the code behind	public void outerFunction(object sender, RepeaterItemEventArgs  e)\n {\n      if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)\n      {\n         Label myLabel =  (Label) e.Item.FindControl("pageLabel");\n         myLabel.Text = "HELLO World";\n      }\n }	0
22230986	22230925	Closures: assigning a field to a local captures which value?	Foo m_currentFoo;\n\nvoid ReplaceFooWithDelayedDestruction()\n{\n    var oldFoo = m_currentFoo;\n\n    Dispatcher.BeginInvoke(() => { Destroy(oldFoo); } );\n\n    m_currentFoo = new Foo();\n}	0
12762506	12762036	datagridview cell click event	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    if (dataGridView1.CurrentCell.ColumnIndex.Equals(3) && e.RowIndex != -1){\n        if (dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null)\n            MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());   \n}	0
20105346	20105227	Best way to use a web service for continuous uploading	private static byte[] imageToByteArray(Image imageIn)\n    {\n        using (MemoryStream ms = new MemoryStream())\n        {\n            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n            imageIn.Dispose();\n            return ms.ToArray();\n        }\n    }	0
6036664	6036637	C#, how do I make a clock work with added hours?	myDateTime.AddHours(2).ToLongTimeString();	0
2193534	2193512	How can I capture the WINDOWS USERNAME included to my below code?	Console.WriteLine("UserName: {0}", System.Environment.UserName);	0
11607463	11607380	How to obtain Linq from Collections?	.OfType<type>()	0
160661	160604	Combine multiple LINQ expressions from an array	Func<int, bool>[] criteria = new Func<int, bool>[3]; \n            criteria[0] = i => i % 2 == 0; \n            criteria[1] = i => i % 3 == 0; \n            criteria[2] = i => i % 5 == 0;\n            Expression<Func<int, bool>>[] results = new Expression<Func<int, bool>>[criteria.Length];\n            for (int i = 0; i < criteria.Length; i++)\n            {\n                results[i] = f => true; \n                for (int j = 0; j <= i; j++)\n                {\n                    int ii = i;\n                    int jj = j;\n                    Expression<Func<int, bool>> expr = b => criteria[jj](b); \n                    var invokedExpr = Expression.Invoke(expr, results[ii].Parameters.Cast<Expression>()); \n                    results[ii] = Expression.Lambda<Func<int, bool>>(Expression.And(results[ii].Body, invokedExpr), results[ii].Parameters);\n                }\n            } \n            var predicates = results.Select(e => e.Compile()).ToArray();	0
24786523	24743102	Flatten results from hierachical XML file using Linq to XML	var results =\n        from x in xDoc.Elements("fs_response").Elements("results").Elements("result")\n        from m in x.Elements("metas").Elements("meta")\n        where m.Attribute("id").Value == "result_status"\n        select new\n        {\n        id = x.Attribute("id").Value,\n        resultStatusId = m.Attribute("id").Value,\n        resultStatus = m.Value,\n        };\n\n    foreach (var result in results.ToList())\n    {\n        Console.WriteLine("{0}: {1} = {2}", result.id, result.resultStatusId, result.resultStatus);\n    }	0
8596491	8596422	Creating array from existing one	T[] Add2Array<T>(T[] arr, T item)\n{\n   return arr.Concat(new[]{item}).ToArray();\n}	0
6535187	6533129	Fetch a specific Google Calendar event	CalendarService service = new CalendarService("test");\nservice.setUserCredentials(username, password);\nEventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full/s5uhaebith4jqn864j11ljkckg");\nEventFeed feed = service.Query(query);	0
5467342	5467114	Average extension method in Linq for default value	var q1 = from v in db.DbVersions select new { VersionId = v.Id, AvgScore = v.DbRatings.Average(x => x.Score) as Nullable<double> };\nvar q2 = from p in dbPlugins select new { Plugin = p, AvgScore = q1.Where(x => p.DbVersions.Select(y => y.Id).Contains(x.VersionId)).Average(x => x.AvgScore) as Nullable<double> };\ndbPlugins = q2.OrderByDescending(x => x.AvgScore).Select(x => x.Plugin).ToList();	0
12618436	12618263	How to generate string based on Pattern	public static class Generator\n{\n    static int current = 0;\n    static Random rand = new Random();\n\n    public static string NextId()\n    {\n        return string.Format("MA {0:0000000}/{1}/{2:00000}", \n          rand.Next() % 100000,\n          DateTime.Now.ToString("dd/MM/yyyy"),\n          current++ );\n    }\n}	0
26512059	26511997	Safely add collection in TPL	remainder =>\n{\n   Calls c = new Calls();\n   c.DialingNumber = "number..";\n   c.DialResult = "result...;\n   Dispatcher.Invoke(()=> // Get the dispatcher from your window and use it here\n   {\n       items.Add(c);\n   }\n},	0
26975903	26895519	Build HTMLTable from C# Serverside with InnerHtml string	HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml("<html><body><table>" + innerHtml + "</table></html></body>");\n\n    foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))\n    {\n        foreach (HtmlNode row in table.SelectNodes("//tr"))\n        {\n            foreach (HtmlNode cell in row.SelectNodes("td"))\n            {\n                var divExists = cell.SelectNodes("div");\n                if (divExists != null)\n                {\n                    foreach (HtmlNode div in cell.SelectNodes("div"))\n                    {\n                        string test = div.InnerText + div.Attributes["data-id"].Value;\n                    }\n                }\n            }\n        }\n   }	0
32265445	30724153	Jira Soap Api Add Watchers	JiraService.createUser(_auth, username.ToLower(System.Globalization.CultureInfo.CreateSpecificCulture("en-us")), password, fullname, email);	0
3871284	3870115	DataGridview Skip The Value Of First Row Column	private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)\n    {\n        decimal sum = 0.00m;\n\n        for (int i = 0; i < dataGridView1.Rows.Count; i++)\n        {\n            if (dataGridView1[1, i].Value != DBNull.Value)\n            {\n                sum = sum + Convert.ToDecimal(dataGridView1[1, i].Value);\n                textBox1.Text = sum.ToString("f2");\n\n            }\n\n        }\n    }	0
1149906	1149902	How to use custom classes in expressions like math objects?	public static Matrix operator +(Matrix mat)\n{\n    //do stuff  \n}	0
30080000	30079869	C# EF Update entites in one request	//delete all users where FirstName matches\ncontext.Users.Delete(u => u.FirstName == "firstname");\n\n//update all tasks with status of 1 to status of 2\ncontext.Tasks.Update(\n    t => t.StatusId == 1, \n    t2 => new Task {StatusId = 2});	0
2519899	2519751	How to shorthand array declaration in a method call?	func(New Object() { })	0
5724065	5723654	How do you change the font used for inline editing of the node text in a WinForms Treeview control?	[DllImport("user32.dll")]\ninternal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\ninternal const int WM_SETFONT = 0x0030;\ninternal const int TVM_GETEDITCONTROL = 0x110F;\n\nprivate void treeView1_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)\n{\n    TreeNode nodeEditing = e.Node;\n    IntPtr editControlHandle = SendMessage(treeView1.Handle, (uint)TVM_GETEDITCONTROL, IntPtr.Zero, IntPtr.Zero);\n    if (editControlHandle != IntPtr.Zero)\n    {\n        SendMessage(editControlHandle, (uint)WM_SETFONT, nodeEditing.NodeFont.ToHfont(), New IntPtr(1));\n    }\n}	0
3583198	3583082	C# Convert string array to dataset	internal static class Program\n{\n    private static void Main(string[] args)\n    {\n        string[] array = new [] { "aaa", "bbb", "ccc" };\n        DataSet dataSet = array.ToDataSet();\n    }\n\n    private static DataSet ToDataSet(this string[] input)\n    {\n        DataSet dataSet = new DataSet();\n        DataTable dataTable = dataSet.Tables.Add();\n        dataTable.Columns.Add();\n        Array.ForEach(input, c => dataTable.Rows.Add()[0] = c);\n        return dataSet;\n    }\n}	0
7489160	6628890	How to use EF Code-First without an app.conf file?	public partial class MyDb: DbContext\n{\n    public static string Connection\n    {\n        get\n        {\n\n            var result = new SqlCeConnectionStringBuilder();\n\n            result["Data Source"] = "MyDatabaseFile.sdf";\n\n            return result.ToString();\n        }\n    }\n\n    public MyDb()\n        : base(Connection)\n    {\n        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");\n    }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n\n    }\n\n    public DbSet<MyTable> MyTable { get; set; }\n\n}	0
2480049	2480039	Determine how an application is closed	private void btnMyExit_Click(object sender, EventArgs e)\n{\n    // TODO: add any special logic you want to execute when they click your own "Exit" button\n    doCustomExitWork();\n}\n\npublic static void OnAppExit(object sender, EventArgs e)\n{\n    doCustomExitWork();\n}\n\nprivate void doCustomExitWork()\n{\n    // TODO: add any logic you want to always do when exiting the app, omit this whole method if you don't need it\n}	0
21451613	21437236	Draw a line/border on a custom panel	protected override void OnRender(System.Windows.Media.DrawingContext dc)\n{\n    var pen = new System.Windows.Media.Pen(System.Windows.Media.Brushes.Black, 2);\n    for (int i = 0; i < _numberOfColumns; i++)\n    {\n        double x = (i + 1) * _columnWidth;\n        dc.DrawLine(pen, new Point(x, 0), new Point(x, 1000));\n    }\n    base.OnRender(dc);\n}	0
4398580	4398536	convert unicode escape sequences to string	"[uU]([0-9A-F]{4})"	0
5775994	5775952	How to get the immediate child elements of the root element using C# and XML?	var headings = yourXDocument.Root.Elements();	0
25435065	25431983	Deserializing JSON string and using in SQL query before returning results to Client Application	[DataContract]\n[Serializable]\npublic class MatterDetailTest\n{\n    [DataMember]\n    public string ID { get; set; }\n}	0
13436739	13436690	How to read from excel in a specific encoding?	Console.WriteLine(encodingHU.GetString(Encoding.Default.GetBytes(str)));	0
20473905	20270321	DataGrid Select Cells in only one Row	private object selectedItem;\n\nprivate void DataGrid_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)\n{\n    var dg = (sender as DataGrid);\n\n    if (selectedItem == null)\n        selectedItem = e.AddedCells.First().Item;\n\n    var allInSameRow = e.AddedCells.All(info => info.Item == selectedItem);\n\n    if (!allInSameRow)\n    {\n        dg.SelectedCells.Clear();\n        selectedItem = null;\n    }\n}	0
32652745	32650531	How to use HttpClient to get non-primitive types in MVC 6	...\nstring payload = await response.Content.ReadAsStringAsync();\nvar obj = JsonConvert.DeserializeObject<MyClass>(payload);\n...	0
5077431	5077385	how to call win32 dll from .NET application folder	[DllImport("Dllname.dll")]\n    static extern void Foo();	0
19976207	19957697	Drawing GUI stuff in scene view Unity3d	public class MyClass{\n    static MyStaticConstructor() {\n        SceneView.onSceneGUIDelegate += OnScene;\n    }\n    static void OnScene(SceneView sceneView) {\n        // Draw GUI stuff here for Scene window display\n    }\n}	0
27275328	27275254	How to get one datatable with two columns from another datatable with many columns in C#	string[] wantedColumns = { "Column1", "Column2", "Column3" }; // for example\nDataTable secondTable = firstTable.Copy();\nvar removeColumns = secondTable.Columns.Cast<DataColumn>()\n    .Where(col => !wantedColumns.Contains(col.ColumnName, StringComparer.InvariantCultureIgnoreCase))\n    .ToList();\nremoveColumns.ForEach(c => secondTable.Columns.Remove(c));	0
4016361	4016245	How to make a Linq sum	var sum = from p in list\n                  group p by new { Of = p.of, Order = p.order }\n                  into g\n                  select new MyClass\n                             {\n                                 of = g.Key.Of,\n                                 order = g.Key.Order,\n                                 qty = g.Sum(p=>p.qty)\n                             };	0
19404403	19404222	Bind Data in List<T> to DatagridView	var source = new BindingSource();\n     source.DataSource = new AddressAccess().getAllAddress().ToList();\n     dgvAddresses.AutoGenerateColumns=true;\n     dgvAddresses.DataSource = source;	0
31249197	31248989	C# How to extract certain info long string	string json = @"[\n   {\n     'Name': 'Product 1',\n     'ExpiryDate': '2000-12-29T00:00Z',\n     'Price': 99.95,\n     'Sizes': null\n   },\n   {\n     'Name': 'Product 2',\n    'ExpiryDate': '2009-07-31T00:00Z',\n    'Price': 12.50,\n    'Sizes': null\n  }\n]";\n\nList<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);\n\nConsole.WriteLine(products.Count);\n// 2\n\nProduct p1 = products[0];\n\nConsole.WriteLine(p1.Name);\n// Product 1	0
24201500	24188486	Accessing / Using a View Entity Framework 6 Code First approach	public class FooView\n{\n    [Key]\n    public string PartNumber { get; set; }\n    public string PartType   { get; set; }\n}	0
27023868	27023640	Bulk replace or remove a character in file names	foreach (var file in Directory.EnumerateFiles(mybadfilesource))\n {\n     var newfile = string.Format("{0}{1}",\n            Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),\n            Path.GetExtension(file));\n     File.Move(file, Path.Combine(mybadfilesource, newfile));\n }	0
14945427	14945368	TableLayoutPanel only shows last row - C#	for (int i = 0; i < numRows; ++i) {\n  Button btnProject = new Button();\n  btnProject.Text = "Fill In";\n  tlpProject.Controls.Add(btnProject, 1, i);\n}	0
4740013	4739833	disable/enable buttons	var that = this; //pointer to button\nwindow.setTimeout(function() { document.body.style.cursor = '';that.disabled = false; }, 1000);	0
16557706	16557463	put a <br /> tag after some text	public string SplitLine(string input)\n    {\n        var wordList = input.Split(' ');\n        var sb = new StringBuilder();\n        for (int index = 0; index < wordList.Length; index++)\n        {\n            if(index % 50 == 0 && index > 0)\n                sb.Append("<br/>" + wordList[index]);\n            else\n                sb.Append(wordList[index] + ' ');\n        }\n        return sb.ToString();\n    }	0
3057723	3057709	LINQ How to force query to materialize?	var filtered = data.Where(i => i.Count > 0).ToArray();\n\n// or\n\nvar filtered = data.Where(i => i.Count > 0).ToList();	0
8345949	8345636	Is there a good way to stream the results from an external process into a Visual Studio output pane?	Process.BeginOutputReadLine()	0
2946876	2946829	Check if there are any repeated elements in an array recursively	boolean hasRepeatedElements(list v) \n    if v.length <= 1 return false;\n    List less, greater;\n    x = v[0];\n    for each y in v, except v[0]\n        if y == x\n            return true;\n        else if y < x\n            less.add(y);\n        else if y > x\n            greater.add(y);\n    end;\n    return hasRepeatedElements(less) || hasRepeatedElements(greater);\nend;	0
11277963	11266345	How to update Facebook status?	using Microsoft.Phone.Tasks;\n\n...\n\nShareStatusTask shareStatusTask = new ShareStatusTask();\nshareStatusTask.Status = "Here's my new status!";\nshareStatusTask.Show();	0
4465756	4465639	Call C# dll from unmanaged C++ app without COM	Reverse P/Invoke	0
25174648	25174614	Interface Property Usage	e1.P = new Person();	0
18982781	18982714	How combine three inputs into one string value?	string comment = TextBox2.Text.Replace("'", "''");\ncomment = comment.Replace("\r\n", "<br />");\ncomment = Server.HtmlEncode(comment.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"));	0
12786828	12735750	Quartz.Net how to create a daily schedule that does not gain 1 minute per day	ITrigger trigger = TriggerBuilder.Create()\n    .WithDailyTimeIntervalSchedule\n      (s => \n         s.WithIntervalInHours(24)\n        .OnEveryDay()\n        .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(13, 0))\n      )\n    .Build();	0
29697904	29697784	Should I lock a file before I read it in C#	using(FileStream fileStream = new FileStream(\n                "myXmlFile.xml", \n                FileMode.Open, \n                FileAccess.Read, \n                FileShare.ReadWrite))	0
17145079	17144732	C# Encode a string with multiple types of characters to HTML	public string HTMLEncodeSpecialChars(string text)\n{\n  System.Text.StringBuilder sb = new System.Text.StringBuilder();\n  foreach (char c in text){\n    if(c>127) // chars not in ASCII\n      sb.Append(String.Format("&#{0};",(int)c));\n    else\n      sb.Append(c);\n  }\n  return sb.ToString();\n}	0
14702731	14701774	how to display text and image in a column of a gridview in asp.net c#	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n     if (e.Row.RowType == DataControlRowType.DataRow)\n     {\n         string img = ((Image)e.Row.FindControl("Image1")).ImageUrl;\n         string []ext=img.Split('.');\n         if (ext.Length == 1)\n         {\n             ((Image)e.Row.FindControl("Image1")).Visible = false;\n         }\n         else\n         {\n             ((Image)e.Row.FindControl("Image1")).Visible = true;\n         }\n      }\n     BindGrid();\n}	0
6215863	6215817	Extracting 'single item' from Multi Dimensional Array (c#)	var marray = new[] { new[] { 0, 1 }, new[] { 2, 3 }, new[] { 4, 5 } };\nConsole.WriteLine(marray[0][1]);	0
4207931	4207912	How to get array overlaps using LINQ?	numbers.Where(array => array.Any(value => numbersToFind.Contains(value)));	0
28006928	28005609	Process A Value From The Database Using Asp.net	if (e.Row.RowType == DataControlRowType.DataRow)\n{\n    Label lblFruit = e.Row.FindControl("lblFruit") as Label;\n    switch(value_from_database)\n    {\n       default:\n       case 1:\n         lblFruit.Text = "Apple";\n       case 2:\n         lblFruit.Text = "Orange";\n       // ... \n    }\n}	0
15104800	15104653	How to copy and validate data from one table (all varchar) to another (typed) in C#?	--begin a transaction to wrap validation and load\nBEGIN TRAN\n\n--Validate that no tickets are set to closed without a completion date\nSELECT * \nFROM bigTableOnLocalServer with (TABLOCKX) -- prevent new rows\nWHERE ticketState = '1' /* ticket closed */ and CompletionDate = 'open' \n\n--if validation fails, quit the transaction to release the lock\nCOMMIT TRAN\n\n--if no rows in result set 1, execute the load\nINSERT INTO RemoteServerName.RemoteServerDBName.RemoteSchema.RemoteTable (field1Int, Field2Money, field3text)\nSELECT CAST(Field1 as int), \n    CASE Field2Money WHEN 'none' then null else CAST(Field2Money as money) END,\n    Field3Text\nFROM bigTableOnLocalServer\nWHERE recordID between 1 and 1000000\n\n-- after complete, commit the transaction to release the lock\nCOMMIT TRAN	0
3309230	3309188	How to Sort a List<T> by a property in the object	List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();	0
7546066	7546015	How to use Named Pipes without the computer hanging if no one connects to the network?	NamedPipeServerStream pipeServer = new NamedPipeServerStream(\n   "<pipe-name>", \n   PipeDirection.InOut, \n   1, \n   PipeTransmissionMode.Byte, \n   PipeOptions.Asynchronous);	0
4206294	4206192	How would I get the text of the newly checked item in a checked listbox with C#	checkedListBox1.Items[e.Index]	0
16354828	16354814	Print a View without buttons	display:none	0
16792621	16767767	Email Delivery Message in Asp.net(how to check whether the email sended?)	message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;	0
10903901	10903683	Search Active Directory without using LDAP	dirSearcher.PageSize = 9000;	0
24121434	24120499	Doing some actions (setting language) before controller initializes in Web API	public class SetLanguageAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(HttpActionContext actionContext)\n    {\n        //Use actionContext.Request to access your request\n    }\n}	0
15611918	15611580	Converting Invalid DateTime	DateTime universalFormatDateTime = Convert.ToDateTime(dateTime).ToUniversalTime()	0
14393468	14393419	save data from datagridview silverlight to database	private void btnSave_Click(object sender, EventArgs e)\n    {\n        //get data back from the datagrid view\n        //assuming my gridview is bound to ObservableCollection<User>\n        var users= dataGridView1.DataSource as ObservableCollection<User>;\n        foreach (var user in users)\n        {\n            //perform the save\n        }\n\n    }	0
9081128	9079556	Display issue for WIndows Media Player in winforms	protected override void OnLoad(EventArgs e) {\n        axWindowsMediaPlayer1.ClientSize = new Size(axWindowsMediaPlayer1.ClientSize.Width, 44);\n        base.OnLoad(e);\n    }	0
4322022	4316956	ASP GridView List	protected void dataGridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)\n    {   \n        if(myList == null)        \n          myList = new List<myClass>();\n        foreach (object keys in dataGridView1.DataKeys[e.NewSelectedIndex].Values)\n        {\n            myList.Add(keys);\n        }            \n    }	0
3405751	3405713	how to select all listview items?	foreach (ListViewItem item in myListView.Items)\n{\n    item.Selected = true;\n}	0
16788491	16788198	c# - regex to find a string that comes after =	string input = "car[brand=saab][wheels=4]";\n\nstring product = "";\nDictionary<string, string> props = new Dictionary<string, string>();\n\nforeach (Match m in Regex.Matches(input, @"^(\w+)|\[(\w+)=(.+?)\]"))\n{\n    if (String.IsNullOrEmpty(product))\n        product = m.Groups[1].Value;\n    else\n        props.Add(m.Groups[2].Value, m.Groups[3].Value);\n}	0
16979129	16978685	Filter Results with LINQ	result = db.Non_Conformance.AsQueryable()	0
34228411	34227689	How to insert into column where otherColumn Equal someValue using Nhibernate	using (var session = new Configuration().Configure().BuildSessionFactory().OpenSession())  \n        {  \n            ClassCodes classcodes=session.Get<ClassCodes>(Originalcode);\n\n            classcodes.EquivalanceCode="EquivalanceCode value";\n\n            using (ITransaction transaction = session.BeginTransaction())  \n            {  \n                session.SaveOrUpdate(classcodes);  \n                transaction.Commit();  \n            }  \n        }	0
8199169	8199103	Subquery in a Lambda Expression or LINQ	vehicles.Where( v =>\n    (SqlMethods.Like(v.memo1, "%CERTIFIED%") || v.memo2 == "CERTIFIED") &&\n    udealer2.Any(d => d.ACC == "UCERT" && d.stockno == v.stockno)\n).OrderBy(v => v.model)\n.ThenByDescending(v => v.days)	0
20744559	20744328	Remove Blank Rows from a Multi Line Text Box and populate the array with the textbox elements	var array = txtBox.Text.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);	0
16658593	16658256	Metro App Customised ListView KeyDown event not firing	Window.Current.KeyDown	0
14059332	14059177	c# layering two arrays	public void Combine(int[,] first, int[,] second, int rowStart, int colStart)\n{\n    //TODO validate parameters, ensure arrays are all large enough, etc.\n\n    for (int i = 0; i < second.GetLength(0); i++)\n    {\n        for (int j = 0; j < second.GetLength(1); j++)\n        {\n            first[colStart + i, rowStart + j] |= second[i, j];\n        }\n    }\n}	0
9428326	9427578	SMO restore from networked SQLServer never finishes (called from C#)	res.NoRecovery = false;	0
24932389	24932077	Make a regex not match if a certain string is found in the match?	(?<!HOUSE[ ]*?)\bword\b	0
22608020	22607759	How to send email from windows phone 7 application	private void Email_Send(object sender, RoutedEventArgs e)\n{\nstring previousValue = string.empty;\nif (NavigationContext.QueryString.ContainsKey("school_name"))\n      previousValue = NavigationContext.QueryString["school_name"];\nEmailComposeTask emailComposeTask = new EmailComposeTask();\nemailComposeTask.Subject = "message subject";\nemailComposeTask.To = "recipient@example.com";\nemailComposeTask.Cc = "cc@example.com";\nemailComposeTask.Bcc = "bcc@example.com";\nemailComposeTask.Body = previousValue ;\nemailComposeTask.Show();\n}	0
21220664	21220467	Remove selected items from Listbox (ObservableCollection)	var selectedFiles = MyList.SelectedItems.Cast<object>().ToList();\nforeach (cListEntry item in selectedFiles)\n{\n   _myList.Remove(item);\n}	0
30788827	30768009	How to dynamically create Sharepoint ComboBoxes?	DropDownList ddlReturnDateMonth = new DropDownList();\nddlReturnDateMonth.CssClass = "dplatypus-webform-field-input";\nddlReturnDateMonth.Items.Add(new ListItem("Jan", "1"));	0
28555117	28549929	there is a way to activate a control WebView Desktop mode and not Mobile mode?	string userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/7.0; Touch; rv:11.0; WPDesktop) like Gecko"\nHttpRequestMessage httpRequestMessage = new HttpRequestMessage(\n    HttpMethod.Post, new Uri("http://whatsmyuseragent.com"));\nhttpRequestMessage.Headers.Append("User-Agent",userAgent);\n\nmyWebView.NavigateWithHttpRequestMessage(httpRequestMessage);	0
6484627	6482878	Change cursor in window caption	protected override void WndProc(ref Message m) {\n        if (m.Msg == 0x20) {  // Trap WM_SETCUROR\n            if ((m.LParam.ToInt32() & 0xffff) == 2) { // Trap HTCAPTION\n                Cursor.Current = Cursors.Hand;\n                m.Result = (IntPtr)1;  // Processed\n                return;\n            }\n        }\n        base.WndProc(ref m);\n    }	0
9363207	9363188	Format IEnumerable<double> while displaying in a console	String.Join(result.Select(d => d.ToString("0.00"))	0
12236119	12234464	Howto Add Custom Control Property in property Dialog Box	private bool isNum = true;\n\n[PropertyTab("IsNumaric")]\n[Browsable(true)]\n[Description("TextBox only valid for numbers only"), Category("EmSoft")] \npublic bool IsNumaricTextBox {\n  get { return isNum; }\n  set { isNum = value; }\n}	0
13408660	13408572	Is there a JSON library that can parse this value?	prods[0].ProductId	0
11071644	11070554	Find then hide drawn shape in image?	blobs[i].Rectangle;	0
13026393	13026269	Exit all instances of my app	var current = Process.GetCurrentProcess();\nProcess.GetProcessesByName(current.ProcessName)\n    .Where(t => t.Id != current.Id)\n    .ToList()\n    .ForEach(t => t.Kill());\n\ncurrent.Kill();	0
17356214	17356009	Match C# MD5 hashing algorithm with node.js	function createMd5(message) {\n    var crypto = require("crypto");\n    var md5 = crypto.createHash("md5");        \n    return md5.update(new Buffer(message, 'ucs-2')).digest('hex');\n}	0
11797092	11797065	How to convert a Datetime String into a Datetime object	var dateTime = DateTime.ParseExact(DateCreated, "yyyy-MM-dd HH:mm:ss.fff");	0
3702078	3701936	Append data to a .csv File using C#	string newFileName = "C:\\client_20100913.csv";\n\nstring clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;\n\n\nif (!File.Exists(newFileName))\n{\n    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;\n\n    File.WriteAllText(newFileName, clientHeader);\n}\n\nFile.AppendAllText(newFileName, clientDetails);	0
3758808	3758630	Using Linq Aggregate to return array of values	IEnumerable<long> GetResults(long[] input)\n    {\n        for (int i = input.Length -1; i >= 1; --i)\n            yield return input[i] / input[i - 1];\n    }	0
2657221	2657190	How to do simple math in datagridview	public void dataGridView_Cellformatting(object sender, DataGridViewCellFormattingEventArgs args)\n{\n    if(args.ColumnIndex == 9) //Might be 8, I don't remember if columns are 0-based or 1-based\n    {\n        DataGridViewRow row = dataGridView.Rows[e.RowIndex];\n        args.Value = (int)row.Cells[6].Value - (int)row.Cells[5].Value;\n    }\n}	0
7262801	7262729	Getting image from resource file. Create general function to retrieve resources	internal static System.Drawing.Bitmap price {\n        get {\n            object obj = ResourceManager.GetObject("price", resourceCulture);\n            return ((System.Drawing.Bitmap)(obj));\n        }\n    }	0
10515883	10515573	Send a SOAP request, where to start?	ServiceReference1.NotificationPortTypeClient client = new ServiceReference1.NotificationPortTypeClient(); \nclient.sendNotification(...);	0
2390835	2390825	How to dynamcially call a generic method based on a mapping in a dictionary?	var m = typeof(MyClass);\nvar mi = ex.GetMethod("Foo");\nvar mig = mi.MakeGenericMethod(_mapping["hyperlink"]);\n\n//Invoke it\nmig .Invoke(null, args);	0
23964150	23801106	Removal of child from aggregate root and database persistence	public void RemoveChild(ChildEntity child, IChildRepository repository)\n{\n    // check conditions, business logic etc\n    // remove using repository	0
2886325	2870731	DataGridView not displaying a row after it is created	TableAdapterManager.UpdateAll(DataSet)	0
1616928	1616688	Retain focus on a UI element, but click a button on a different dialog. WPF C#	public static void BackgroundFocus(this UIElement el)    \n{        \n    Action a = () => el.Focus();        \n    el.Dispatcher.BeginInvoke(DispatcherPriority.Background, a);    \n}	0
11148646	11093400	C# user defined callbacks to a method in a different class	public class A: ZZZ { // this class is NOT under my control\n   private b = new B(this);\n   b.UserCallback = myCallback;\n\n   static void myCallback(C x) {\n      // do something\n   }\n\n   // Elsewhere in the application expects a protected\n   // override method to exist in *this* class A to handle\n   // an event. But we want a method in class B to handle\n   // it and then call myCallback depending on the type of event\n\n   protected override void handle_some_event(event e) {\n      b.handle_event(e);\n   }\n}\n\npublic delegate void usercallback(Z z); // declare OUTSIDE both classes\n\npublic class B {    // this class IS under my control\n   public usercallback UserCallback = defaultCallback;\n   static void defaultCallback(Z z) { /* do nothing */ }\n\n   public handle_event(event e) {\n       // do stuff...\n       // then do the callback\n       UserCallback(z);\n   }    \n}	0
12673734	12299739	Setting when to scroll in WPF ScrollViewer	void FormElement_GotFocus(object sender, RoutedEventArgs e)\n{\n    FormElement element = sender as FormElement;\n    Point elementLocation = element.TranslatePoint(new Point(), canvasGrid);\n    double finalHeight = elementLocation.Y - (canvasScrollViewer.RenderSize.Height/2);\n    canvasScrollViewer.ScrollToVerticalOffset(finalHeight);\n}	0
33728705	28573526	ECDSA get public key in C#	public Tuple<byte[],byte[]> GetPublicKey(byte[] privateKey)\n{\n    BigInteger privKeyInt = new BigInteger(+1, privateKey);\n\n    var parameters = SecNamedCurves.GetByName("secp256k1");\n    ECPoint qa = parameters.G.Multiply(privKeyInt);\n\n    byte[] pubKeyX = qa.X.ToBigInteger().ToByteArrayUnsigned();\n    byte[] pubKeyY = qa.Y.ToBigInteger().ToByteArrayUnsigned();\n\n    return Tuple.Create(pubKeyX, pubKeyY);\n}	0
19520588	19519619	Many nested for loops	int[] limits = { 9, 20, 15, 30, 8, 40, 10 };\nint[] components = new int[limits.Length];\n\nbool done = false;\nwhile (!done)\n{\n    //do work here using the components\n    int M = components[0];\n    int N = components[1];\n    int O = components[2];\n    int P = components[3];\n    //etc\n    //first iteration M=0,N=0,O=0, etc\n\n    //this part does the incrementing for the next iteration\n    for (int j = 0; j < limits.Length; j++)\n    {\n        components[j]++;\n        if (components[j] < limits[j])\n            break;\n        components[j] = 0;\n        if (j == limits.Length - 1)\n            done = true;\n    }\n}	0
20703523	20703458	Is there a way of generating getter, setter functions in visual studio 2012 like in eclipse	Refactor->Encapuslate Field	0
11417457	11417231	Importing Any Excel Spreadsheet into a DataGridView - C#	public string[] GetExcelSheetNames(string excelFileName)\n{\n        OleDbConnection con = null;\n        DataTable dt = null;\n        String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";\n        con= new OleDbConnection(conStr);\n        con.Open();\n        dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n        if (dt == null)\n        {\n            return null;\n        }\n\n        String[] excelSheetNames = new String[dt.Rows.Count];\n        int i = 0;\n\n        foreach (DataRow row in dt.Rows)\n        {\n            excelSheetNames[i] = row["TABLE_NAME"].ToString();\n            i++;\n        }\n\n        return excelSheetNames;\n}	0
22391823	22391775	Problems casting in a foreach	s = (Spells) entry.Value;	0
5759558	5759516	Comma separated list from a C# 4.0 List	string csv = string.Join(",", list.Select(p => p.Email).ToArray());	0
7851988	7851090	Deploying C# console app with Oracle.DataAccess reference	System.BadImageFormatException	0
19783767	19759156	How to modify telerik pageview tabs	TabVsShape shape = new TabVsShape();\n        shape.RightToLeft = true;\n        foreach (RadPageViewPage p in radPageView1.Pages)\n        {\n            p.Item.Shape = shape;\n            p.Item.MinSize = new Size(65, 0); //if you need to increase the page item size\n        }	0
23170564	23168741	Creating a calculator in C#	totalTxt.TextChanged += new EventHandler(TextChanged);\npaidTxt.TextChanged += new EventHander(TextChanged);\n\nvoid TextChanged (object sender, EventArgs e)\n{\n    remainTxt.Text = Convert.ToString(int.Parse(totalTxt.Text) - int.Parse(paidTxt.Text));\n}	0
1958352	1958306	Concatening objects with LINQ, under a condition	public List<MyError> GroupErrorsByErrorCode(List<MyError> errors)\n    {\n        var result = errors.GroupBy(e => e.ErrorCode).Select(group => new MyError\n            {\n                ErrorCode = group.Key,\n                // EDIT: was \n                // Errors = group.SelectMany(g => g.Errors)\n                Errors = new ArrayList(group\n                           .SelectMany(g => g.Errors.Cast<MyEntryError>())\n                           .ToList())\n            });\n        return result;\n    }	0
12501706	12462996	Mini Profiler integrate with SqlConnection	...\nusing StackExchange.Profiling;\nusing StackExchange.Profiling.Data;\n...\nusing( DbConnection conn = new ProfiledDbConnection( new SqlConnection( ConnectionString ), MiniProfiler.Current ) ) {\n        using( DbCommand command = conn.CreateCommand() ) {\n            command.CommandText = CommandText;\n            command.Connection = conn;\n            command.CommandType = SQLCommandType;\n            foreach( SqlParameter p in ParamsToAdd ) {\n                command.Parameters.Add( p );\n            }\n            conn.Open();\n            DbDataReader rdr;\n            try {\n                rdr = command.ExecuteReader();\n            } catch( Exception ex ) {\n                //log error\n            }\n            using( rdr ) {\n                while( rdr.Read() ) {\n                    yield return (IDataRecord)rdr;\n                }\n            }\n        }\n    }	0
7825611	7825587	How can I avoid loading an assembly dynamically that I have already loaded using Reflection?	Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();	0
23648242	23648030	How to retireve 10 nodes from a XML file?	var nodes = e.OfType<XmlNode>().Take(10);	0
1103417	1103402	How does VS compile console applications to show "Press any key to continue"?	echo off\nYourApp.exe\npause	0
31722261	31721715	Add text before selected text in another textbox	private void rich1_SelectionChanged(object sender, EventArgs e)\n    {\n        rich2.SelectionLength = rich1.SelectionLength;\n        rich2.SelectionStart = rich1.SelectionStart;\n\n    }\n\nprivate void button2_Click(object sender, EventArgs e)\n    {\n        rich2.SelectedRtf = @"{\rtf1\ansi{colour=12}" + rich2.SelectedRtf;\n        rich1.ForeColor = Color.Blue;\n    }	0
27283816	27268090	Retrieve messages from AMS enabled IBM web sphere MQ	mqrc 2110	0
33985987	33983051	C# Entity Framework - Stack Overflow when inserting data into child table	public class Parent\n{\n  public Parent()\n  {\n    Children = new List<child>(); \n    parentId = Guid.NewGuid(); \n  }\n\n  [Key]\n  public Guid parentId { get; set; }\n\n  [Required]\n  [StringLength(4)]\n  public string parentData { get; set; }\n\n  public virtual List<Child> Children { get; set; }\n}\n\npublic class Child\n{\n  public Child()\n  {\n   childId = Guid.NewGuid();\n  }\n\n  [Key]\n  public Guid childId { get; set; }\n\n  [ForeignKey("Parent")]\n  public Guid parentId { get; set; }\n\n  [Required]\n  [StringLength(65)]\n  public string childData { get; set; }\n\n  public virtual Parent Parent { get; set; }\n}	0
22905007	22904744	Multiple data sources (ODBC, OleDB, SQL) with one class	ConnectionStringSettings c = ConfigurationManager.ConnectionStrings[name];\nDbProviderFactory factory = DbProviderFactories.GetFactory(c.ProviderName);\nusing (IDbConnection connection = factory.CreateConnection())\n{\n    connection.ConnectionString = c.ConnectionString; \n    ... etc...\n}	0
4217331	4217297	Add column and Update a DataTable with lookup data	var mapping = mapping_values.ToDictionary(p => p.Value1, p => p.Value2);\nforeach(DataRow row in table.Rows) \n    row["Status Text"] = mapping[row.Field<int>("Status Value")];	0
14555869	14555701	Extension methods syntax for many to many relationship	var result = from allReports in Reports\n             join userRoles in userRoles on allReports.ReportId equals userRoles.ReportId\n             join roles in Roles on userRoles.RoleId equals roles.RoleId\n             where userRoles.UserId == userid\n             select allReports;	0
12201579	12201506	How to change stack size of a console application?	int stackSize = 1024*1024*64;\nThread th  = new Thread( ()=>\n    {\n        //YourCode\n    },\n    stackSize);\n\nth.Start();\nth.Join();	0
24082001	24063824	Image map based on HSL or HSI values	convert glass.jpg -blur 0x2 -canny 0x1+5%+10% edges.jpg	0
12804995	12804945	Moving elements from one list to the other list	var s1 = new List<string>() { "a", "b", "c" };\nvar s2 = new List<string>() { "d", "e", "f" };\ns2.AddRange(s1.Take(2)); \ns1.RemoveRange(0, 2);	0
28074983	28074861	Json.Net Changing from JObject loops to JArray	using System;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\n\nclass Test\n{\n    static void Main(string[] args)\n    {\n        string text = File.ReadAllText("Test.json");\n        JObject json = JObject.Parse(text);\n        var ids = from bank in json["bank"]\n                  from endpoint in bank["endpoints"]\n                  where (string) endpoint["epName"] == "FRED001"\n                  select (string) endpoint["epId"];\n        foreach (var id in ids)\n        {\n            Console.WriteLine(id);\n        }\n    }\n}	0
25764723	25764664	Dont exit a method till all Threads are complete	Thread.Join()	0
7373766	7373335	How to open a child windows under parent window on menu item click in WPF?	MyChildWindow cw = new MyChildWindow();\ncw.ShowInTaskbar = false;\ncw.Owner = Application.Current.MainWindow;\ncw.Show();	0
5906288	5906265	Add Row to DataGridView	Dim dgvRow As New DataGridViewRow\n        Dim dgvCell As DataGridViewCell\n\n        dgvCell = New DataGridViewTextBoxCell()\n        dgvCell.Value = "anis"\n        dgvRow.Cells.Add(dgvCell)\n\n        dgvCell = New DataGridViewTextBoxCell()\n        dgvCell.Value = "khan"\n        dgvRow.Cells.Add(dgvCell)\n\n        DataGridView1.Rows.Add(dgvRow)	0
5987538	5987328	In C#, is it possible to get a hash from a byte array that is filename safe?	var originalBytes = Encoding.ASCII.GetBytes(data);\nvar hashedBytes = Hasher.ComputeHash(originalBytes);\n\nvar builder = new StringBuilder();\nforeach (Byte hashed in hashedBytes)\n    builder.AppendFormat("{0:x2}", hashed);\n\nreturn builder.ToString();	0
18862775	18862173	In WPF, when drag the customized titlebar in the no-border window, the window will be restored, how to implement it?	private bool _isMouseDown = false;\n\n    private void DragRectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        _isMouseDown = true;\n        this.DragMove();\n    }\n\n    private void DragRectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n    {\n        _isMouseDown = false;\n    }\n\n    private void DragRectangle_MouseMove(object sender, MouseEventArgs e)\n    {\n        // if we are dragging and Maximized, retore window\n        if (_isMouseDown && this.WindowState == System.Windows.WindowState.Maximized)\n        {\n            _isMouseDown = false;\n            this.WindowState = System.Windows.WindowState.Normal;\n        }\n    }	0
1050421	1050364	DataGridView selected cell style	using System.Drawing.Font;\n\nprivate void dataGridView_SelectionChanged(object sender, EventArgs e)\n    {\n\n    foreach(DataGridViewCell cell in ((DataGridView)sender).SelectedCells)\n{\ncell.Style = new DataGridViewCellStyle()\n{\nBackColor = Color.White,\nFont = new Font("Tahoma", 8F),\nForeColor = SystemColors.WindowText,\nSelectionBackColor = Color.Red,\nSelectionForeColor = SystemColors.HighlightText\n};\n}\n    }	0
29150311	29149911	Sql server get result of one month before	DECLARE @StartDate DATETIME, @EndDate DATETIME, @currentDate date\nset @currentDate = GETDATE()\nSET @StartDate = DATEADD(mm,-1, @currentDate))\nselect count(status)  from [full]\nwhere (date_reception> @StartDate and status = 'OPEN')	0
17723897	17723601	How do I register single event listener for all buttons	EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(Button_Click));\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n\n}	0
15482161	15481662	Using C# to find nodes within .csproj files	XmlDocument xmldoc = new XmlDocument();\nxmldoc.Load(@"c:\test.txt");\n\nXmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);\nns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");\nXmlNode node = xmldoc.SelectSingleNode("//msbld:TheNodeIWant", ns);\n\nif (node != null)\n{\n    MessageBox.Show(node.InnerText);\n}	0
23914868	23914683	Attributes on method parameters	Type myType = typeof(MyType)\nMethodInfo method = myType.GetMethod('Post');\nforeach (ParameterInfo parameter in method.GetParameters())\n{\n    if (parameter.IsDefined(typeof(FromUri), false))\n    {\n        // attempt to find value in uri\n    }        \n    else if (parameter.IsDefined(typeof(FromPost), false))\n    {\n        // from post body\n    }\n    else\n    {\n        // have to find out myself!\n    }\n}	0
14769611	14769406	Is there a way to make every class in a project implement an interface (without doing a bulk find and replace)	[assembly:YourAspect]	0
3266844	3266187	Excel colours getting distorted when being copied from one template to another using VSTO(C#)	Workbook1.Colors = Workbook2.Colors	0
11289340	11289273	Many update statements in one Transaction in Entity Framework	using (TransactionScope transaction = new TransactionScope())\n{\n    var report = reportRepository.Update(reportModel);\n    var book = bookRepository.Update(bookModel);\n    var mobile = mobileRepository.Update(mobileModel);\n    ...\n    transaction.Complete();\n}	0
32620145	32614702	Linq Intersect Comma Delimited String with List Containing Strings Any & All	reports = reports.Where(r => r.ItemIds.Split(',').ToList().Intersect(ItemIdsList).Count() > 0); // instead of .Any()  \nreports = reports.Where(r => r.ItemIds.Split(',').ToList().Intersect(ItemIdsList).Count() == ItemIdsList.Count()); // instead of .All()	0
1376779	1376572	C#, how to handle constant tables	static readonly int[,] constIntArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }};	0
28898864	28897161	Syntax to call generic C# method from NLua	class AssetManager\n{\n    private ContentManager content;\n    private Dictionary<string, Texture2D> textures; // fonts, sprites, models and so on\n\n    AssetManager(ContentManager  pContent)\n    {\n        this.content = pContent;\n        this.textures = new Dictionary<string, Texture2D>();\n    }\n\n    public void LoadTexture(string pName, string pAssetName)\n    {\n        this.textures.Add(pName, this.content.Load<Texture2D>(pAssetName);\n    }\n    public Texture2D GetTexture(stirng pName)\n    {\n        return this.Textures.ContainsKey(pName) ? this.Textures[pName] : null;\n    }\n}	0
5369744	5367594	Unity: Register two interfaces as one singleton with interception	var container = new UnityContainer()\n    .AddNewExtension<Interception>()\n    .RegisterType<I1, C>()\n    .RegisterType<I2, C>()\n    .RegisterType<C>(\n        new ContainerControlledLifetimeManager(),\n        new Interceptor<TransparentProxyInterceptor>(),\n        new InterceptionBehavior<PolicyInjectionBehavior>()\n    );	0
4279156	4279142	c# custom control winform	Control.WndProc	0
13831562	13831528	C# MySQL - Retrieve data from specifi column and insert into variable	var cmd = new MySqlCommand("SELECT 1 FROM table WHERE id = 1", databaseCon);\nint id = (int)cmd.ExecuteScalar();	0
31268337	31268095	Randomize items and their locations in a list of length 3	var fruits = new List<string> { "apple", "orange", "mango" };\nvar r = new Random();\nvar newOrderFruits = fruits.OrderBy(x => r.Next()).ToList();\nnewOrderFruits.Dump();	0
19992016	19991957	Filter one list using index value obtained from another list using linq	var result = String.Join(",", valueList\n    .Where(vl => fieldList.Select(fl => fl.FieldIndex)\n                          .Contains(valueList.IndexOf(vl))))	0
500385	500376	select child object collection with lambdas	return this._categories.SelectMany(c => c.SubCategories);	0
855061	855043	Converting a collection.foreach from c# to VB.Net	parts.ForEach(AddressOf TestMethod)	0
12374486	12373738	How do I set a cookie on HttpClient's HttpRequestMessage	var baseAddress = new Uri("http://example.com");\nvar cookieContainer = new CookieContainer();\nusing (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })\nusing (var client = new HttpClient(handler) { BaseAddress = baseAddress })\n{\n    var content = new FormUrlEncodedContent(new[]\n    {\n        new KeyValuePair<string, string>("foo", "bar"),\n        new KeyValuePair<string, string>("baz", "bazinga"),\n    });\n    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));\n    var result = client.PostAsync("/test", content).Result;\n    result.EnsureSuccessStatusCode();\n}	0
10859831	10859782	Proper Translation of linear regression equation to C#	var sumX = pts.Sum(pt => pt.X);\nvar slope = (numberOfPoints * pts.Sum(pt => pt.X * pt.Y) -\n             sumX * pts.Sum(pt => pt.Y)) /\n            (numberOfPoints * pts.Sum(pt => pt.X * pt.X) -\n             sumX * sumX)	0
30619911	30614653	Retrofit unit tests to large solution, IOC, Moq	public SomeConstructor(ISomeDependency someDependency = null) {\n    if(null == someDependency) {\n        someDependency = new SomeDependency();\n    }\n    _someDependency = someDependency;\n}	0
365751	354869	How do I use DMProcessConfigXML to provision my Windows Mobile device?	XmlDocument configDoc = new XmlDocument();\nconfigDoc.LoadXml(\n    "<wap-provisioningdoc>"+\n    "<characteristic type=\"BrowserFavorite\">"+\n    "<characteristic type=\"Microsoft\">"+\n    "<parm name=\"URL\" value=\"http://www.microsoft.com\"/>"+\n    "</characteristic>"+\n    "</characteristic>"+\n    "</wap-provisioningdoc>"\n    );\nConfigurationManager.ProcessConfiguration(configDoc, false);	0
9624307	9621625	Displaying filtered rows in DataGridView	else\ndr.Visible = false;	0
5074467	5073511	Background worker proper way to access UI	class AuthUserData\n  {\n    public string Name;\n    public string Password;\n  }\n\n  private void button1_Click(object sender, EventArgs e)\n  {\n     var authData = new AuthUserData() { Name = textBox1.Text, Password = textBox2.Text };\n     worker.RunWorkerAsync(authData);\n  }\n\n  void worker_DoWork(object sender, DoWorkEventArgs e)\n  {\n     // On the worker thread...cannot make UI calls from here.\n     var authData = (AuthUserData)e.Argument;\n     UserManagement um = new UserManagement(sm.GetServerConnectionString());\n     e.Result = um;\n     e.Cancel = um.AuthUser(textBox1.Text, textBox2.Password));\n  }\n\n  void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n  {\n     // Back on the UI thread....UI calls are cool again.\n     var result = (UserManagement)e.Result;\n     if (e.Cancelled)\n     {\n        // Do stuff if UserManagement.AuthUser succeeded.\n     }\n     else\n     {\n        // Do stuff if UserManagement.AuthUser failed.\n     }\n  }	0
30875378	30875326	How to show a svg image into Image control?	using(FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read))\n{\n  DrawingImage image = SvgReader.Load(stream);\n\n  // SvgReaderOptions options = new SvgReaderOptions(...);\n  // DrawingImage image = SvgReader.Load(stream, options);\n}	0
25679041	25638214	Mouse clicks on the created regions in Venn diagram	leftOnlyRegion = new Region(leftVenn);	0
10375998	10375984	How do I clear selection of a gridview row?	Gridview has a property called SelectedIndex.  \nIf you want to unselect any rows then set this property to -1.	0
30329817	30329733	How to pass base parameters from an overloaded constructor into the derived class	public Health(int size, string name, int height, double weight)\n    : base(name, height, weight)\n{\n    newSize = size;\n}	0
13122704	13122562	split string and put them line after line	string tmp = @"What is ""that"" ENUM ""No"", ""Yes"", ""OK"", ""Cancel";\n\nstring[] tmpList = tmp.Split(new Char[] { ' ',',', ';' }, StringSplitOptions.RemoveEmptyEntries);\n\nvar row = new object[] { tmpList[0], tmpList[3], string.Join("\n", tmpList.Skip(4).ToArray()) };	0
5252527	5252353	How can I dynamically define this label?	BrushConverter bc = new BrushConverter();\n            Label classname_label = new Label();\n            classname_label.Content = "Physics 101";\n            classname_label.Foreground = (Brush)bc.ConvertFrom("#FF3535A0");\n            Canvas.SetLeft(classname_label, 10);\n            Canvas.SetTop(classname_label, 10);\n            Canvas.SetRight(classname_label, 10);\n            classname_label.Height=30;\n            classname_label.Width=280;\n            classname_label.FontFamily =new System.Windows.Media.FontFamily("MS Reference Sans Serif");\n            classname_label.FontSize=16;\n            classname_label.FontWeight = System.Windows.FontWeights.Bold;\n            //Control you want to contain label \n            left_canvas.Controls.Add(classname_label);	0
6987791	6987748	How do I compress Object[][] in C#	object[][] objects = new[] {new[] {"a"}};\nBinaryFormatter formatter = new BinaryFormatter();\nusing (MemoryStream memoryStream = new MemoryStream())\nusing (GZipStream gZipStream = new GZipStream(File.OpenWrite("C:\\zipped.zip"), \n    CompressionMode.Compress))\n{\n    formatter.Serialize(gZipStream, objects);\n}\n\n//unzipping\nusing (GZipStream gZipStream = new GZipStream(File.OpenRead("C:\\zipped.zip"), \n    CompressionMode.Decompress))\n{\n    objects = (object[][])formatter.Deserialize(gZipStream);\n    Console.WriteLine(objects[0][0]); //a\n}	0
21832176	19153732	Visual Studio 2012 (x64) - Windows Phone Toolkit - How to Add WP toolkit custom controls to toolbox in VS	In my windows 8 machine it usually points to\nyour project where WPToolkit is installed\n[WPtoolkit.4.2013.08.16\lib\sl4-windowsphone71\Microsoft.Phone.Controls.Toolkit.dll]\nPlease note, Although, I have chosen a WP8 project, I had to choose the 7.1 dll to make to add it to the Toolbox. the wp8 folder failed to add.	0
32683871	32683672	Solve font cropped only in first line of textbox WPF	TextBlock.LineStackingStrategy="BlockLineHeight"	0
2537085	2536668	Make outgoing call with built-in modem in C#	// Set the port name, baud rate and other connection parameters you might need\nSerialPort port = new SerialPort("COM1", 9600 );\nport.Open();\nport.ReadTimeout = 1000;\nport.NewLine = "\r";\nport.WriteLine("ATZ"); // reset the modem\nport.ReadTo("OK\r\n"); // wait for "OK" from modem\nport.WriteLine("ATDT 12345678"); // dial number with dialtone\nstring response = port.ReadTo("\r").Trim(); // read until first newline\nport.Close();	0
33700175	33679631	When role assignment changes, authorization token still presents a user with the old roles	public class CustomAuthorizeAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        if (!filterContext.HttpContext.Request.IsAuthenticated)\n        {\n            // Redirect to login page\n            filterContext.Result = Redirect("Login", "Index");\n            return;\n        }\n\n        var roles = GetRolesFromDb();\n        if (!Roles.Any(r => roles.Contains(r)))\n            filterContext.Result = Redirect("Error", "AccessDenied");\n    }\n\n    private RedirectToRouteResult Redirect(string controller, string action, string area = "")\n    {\n        return new RedirectToRouteResult(new RouteValueDictionary(new\n        {\n            controller,\n            action,\n            area,\n        });\n    }\n}	0
2301133	2301118	Builtin Function to Convert from Byte to Hex String	byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };\n\nvar str = BitConverter.ToString(vals).Replace("-", "");\nConsole.WriteLine(str);\n\n/*Output:\n  01AAB1DC10DD\n */	0
30947863	30931715	Validate Google idToken - certificate verification fails using RSACryptoServiceProvider	curl https://www.googleapis.com/oauth2/v2/tokeninfo?id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IjkyNGE0NjA2NDgxM2I5YTA5ZmFjZGJiNzYwZGI5OTMwMWU0ZjBkZjAifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTEwNTcwOTc3MjI2ODMwNTc3MjMwIiwiYXpwIjoiMzY0MzgxNDQxMzEwLXRuOGw2ZnY2OWdnOGY3a3VjanJhYTFyZWpmaXRxbGpuLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXRfaGFzaCI6IlAzLU1HZTdocWZhUkZ5Si1qcWRidHciLCJhdWQiOiIzNjQzODE0NDEzMTAtdG44bDZmdjY5Z2c4ZjdrdWNqcmFhMXJlamZpdHFsam4uYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJjX2hhc2giOiJjd3hsdXBUSkc4N2FnbU1pb0tSYUV3IiwiaWF0IjoxNDM0NDcyODc2LCJleHAiOjE0MzQ0NzY0NzZ9.Gz_WljZOV9NphDdClakLstutEKk65PNpEof7mxM2j-AOfVwh-SS0L5uxIaknFOk4-nDGmip42vrPYgNvbQWKZY63XuCs94YQgVVmTNCTJnao1IavtrhYvpDqGuGKdEB3Wemg5sS81pEthdvHwyxfwLPYukIhT8-u4ESfbFacsRtR77QRIOk-iLJAVYWTROJ05Gpa-EkTunEBVmZyYetbMfSoYkbwFKxYOlHLY-ENz_XfHTGhYhb-GyGrrw0r4FyHb81IWJ6Jf-7w6y3RiUJik7kYRkvnFouXUFSm8GBwxsioi9AAkavUWUk27s15Kcv-_hkPXzVrW5SvR1zoTI_IMw	0
20529404	20529283	How can I deserialize an array of JSON objects using JSON.NET?	List<Product> deserializedProduct = JsonConvert.DeserializeObject<List<Product>>(object);	0
25616915	25616806	C# Finding specific strings in a sentence and storing in a multidimensional array	List<string> sentenceList = new List<string>(new String[]\n{"Gerald has a nice car", "Rachel has a cute cat"});\n\n        List<string> entityList = new List<string>(new String[] \n{ "Gerald", "car", "Rachel", "cat" });\n\nforeach (string sentence in sentenceList)\n{\n    var words = sentence.Split(" ".ToCharArray());\n    var valid_words = words.Where (w => entityList.Any (en_li => en_li.Equals(w)));\n    // do something with valid_words. It's an enumerable with the words that match.\n}	0
9602894	9602694	How to get char from KeyCode on KeyPress for OEM?	protected override void OnKeyPress(KeyPressEventArgs e)\n{\n    base.OnKeyPress(e);\n    if (false == Char.IsDigit(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.') e.Handled = true;\n}	0
24214568	24214443	Loop through 2D array and print results with format	string[,] multiPropertySelect = new string[,] { { "StaffID", "Dept" }, { "StaffID", "Dept" }, { "StaffID", "Dept" }, { "StaffID", "Dept" } };\n\n     for (int x = 0; x < multiPropertySelect.GetLength(0); ++x)\n     {\n        Console.WriteLine(string.Format("{0}, {1}", multiPropertySelect[x, 0], multiPropertySelect[x, 1]));\n     }\n\n     Console.ReadKey();	0
26180676	26180447	Filter gridview datasource	// save your datatable in session while binding gridview\n    // Session["Dt_GridView"]=Your_datatable; \n    protected void FilterResult(object sender, EventArgs e)\n    {\n        try\n        {\n           // DataTable dt = (DataTable)gvwResavePositions.DataSource; this reutrn null\n            // hence\n            //gvwResavePositions.DataSource as DataTable this will return null\n\n\n\n            DataTable dt = (DataTable)Session["Dt_GridView"];\n\n         dt.DefaultView.RowFilter = string.Format("strPaperId = '{0}'",\n                txtPaperId.Text);\n         gvwResavePositions.DataSource = dt;\n          gvwResavePositions.DataBind();\n            }\n        catch (Exception ex)\n        {\n            var t = ex.Message;\n        }\n    }	0
27123231	27064750	How to display a column only in an edit mode GridView in c#	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n        {\n            if (GridView1.EditIndex >= 0)\n                return;\n\n            if ((e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) &&\n            (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header))\n            {\n                e.Row.Cells[4].Visible = false;\n            }\n        }	0
29441667	29441462	3 tier application with Identity and EF	Microsoft.AspNet.Identity.EntityFramework	0
17448402	17447238	How to sort particular colum rows in datatable	dataTable.DefaultView.Sort = "Name asc";	0
15357793	15357731	How I can waiting some time in c# (windows service)	public static int Main() {\n   /* Adds the event and the event handler for the method that will \n      process the timer event to the timer. */\n   myTimer.Tick += new EventHandler(TimerEventProcessor);\n\n   // Sets the timer interval to 5 seconds.\n   myTimer.Interval = 5000;\n   myTimer.Start();\n\n   // Runs the timer, and raises the event. \n   while(exitFlag == false) {\n      // Processes all the events in the queue.\n      Application.DoEvents();\n   }\nreturn 0;\n}	0
25008272	24998822	Selenium WebDrive - Chrome unexpected alert open	var options = new InternetExplorerOptions();\n    options.UnexpectedAlertBehavior = OpenQA.Selenium.IE.InternetExplorerUnexpectedAlertBehavior.Ignore;\n\ndriver = new InternetExplorerDriver(options);	0
30932160	30931971	Convert string[] of json object to List<T>	var list = jsonobjects.Select(JsonConvert.DeserializeObject<T>).ToList();	0
1308310	1308301	Constructing a DateTime one step at a time	DateTime d = new DateTime((long)0);\nd = d.AddYears(2000);	0
7706926	7706652	How to return csv values from a List<T>	list\n    .Select(i=>i.Name)\n    .Distinct()\n    .Select(name => \n       name + "," + \n       String.Join(",", (from y in list.Select(i=>i.Year).Distinct().OrderBy(y=>y)\n                        join item in list.Where(i=>i.Name == name) \n                        on y equals item.Year into outer\n                    from o in outer.DefaultIfEmpty()\n                    select ((o == null) ? "0" : o.Value.ToString()) \n                         ).ToArray()));	0
8882748	8882667	how can I get the fraction of the decimal in sql	decimal total = /* get value from database */;\ndecimal fraction = decimal.Remainder(total, 1m);	0
1832035	1832005	Generate several megabytes of of random data in C#	int streamSize = (1024 * 1024) * 15; // Let's make 15 Mbytes of junk\n\nint left = streamSize;\n\nwhile (left > 0)\n{\n    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();\n    byte[] buffer = new byte[1024];\n    rng.GetBytes (buffer);\n\n    SendBytes (buffer); // Send it to network interface\n\n    left -= 1024;\n}	0
15066876	15066735	How to search and return string values in C# using input text file	StreamReader reader = new StreamReader("sample.txt");\n        string x = reader.ReadToEnd();\n        List<string> users = new List<string>();\n        int numberOfUsers;\n\n        Regex regex = new Regex(@"(U|u)ser:(?<username>.*?) appGUID");\n        MatchCollection matches = regex.Matches(x);\n        foreach (Match match in matches)\n        {\n            string user = match.Groups["username"].ToString().Trim();\n            if (!users.Contains(user)) users.Add(user);\n        }\n        numberOfUsers = users.Count;	0
3565041	3565015	BestPractice - Transform first character of a string into lower case	Char.ToLowerInvariant(name[0]) + name.Substring(1)	0
3705239	3704981	C# fully trusted assembly with SecuritySafeCritical funciton still throwing SecurityExceptions	private Assembly LoadAssemblyFromFile(string file)\n{\n    FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, file);\n    perm.Assert();\n\n    return Assembly.LoadFile(file);\n}	0
12095652	12095594	Updating string properties of an object using enumeration	MyObject data = new MyObject();\nforeach (var pi in typeof(MyObject).GetProperties().Where(i =>\n                                      i.PropertyType.Equals(typeof(string)))\n{\n   var control = FindControl("txt" + pi.Name) as ITextControl;\n   if (control != null)\n       pi.SetValue(data, control.Text, null);\n}	0
18169301	18169284	Incorrect syntax near 'First Name'	SqlCommand cmd = new SqlCommand("UPDATE Records SET [First Name]='" + textBox2.Text + "',[Last Name]='" + textBox3.Text + "',[Middle Initial]='" + comboBox1.Text + "',Gender='" + comboBox2.Text + "',Address='" + textBox4.Text + "',Status='" + comboBox3.Text + "',Year='" + comboBox4.Text + "',Email='" + textBox5.Text + "',Course='" + comboBox5.Text + "',[Contact Number]='" + textBox6.Text + "'+     WHERE ([Student ID]='" + textBox1.Text + "')", con);\n            cmd.ExecuteNonQuery();\n            con.Close();	0
961753	961699	How to change character encoding of XmlReader	using(XmlReader r = XmlReader.Create(new StreamReader(fileName, Encoding.GetEncoding("ISO-8859-9")))) {\n    while(r.Read()) {\n        Console.WriteLine(r.Value);\n    }\n}	0
13876619	13876428	passing values from popup window to parent window	string redirectUrl = "creation.aspx?id =" + value1.Text + "&" + value.Text;\nScriptManager.RegisterStartupScript(this, GetType(), "Redirect", "window.parent.location = " + redirectUrl , true);	0
13193028	13192963	How to write the create new xml if the xml file is not found in my WPF project?	public void loadXML()\n{\n    XDocument document = new XDocument();\n\n    if(!File.Exists("MyXmlFile.xml")){\n        //Populate with data here if necessary, then save to make sure it exists\n        document.Save("MyXmlFile.xml");\n    }\n    else{\n        //We know it exists so we can load it\n        document.load("MyXmlFile.xml");\n    }\n\n    //Continue to work with document\n\n\n}	0
32233550	32229824	Detect solution configurations in Visual Studio 2010	Conditional Compilation Symbols	0
26520256	26520182	display data from two datarows c#	//This is your intial data which depends on the num_int and row[17]\nDataRow[] result1 = MainWindow.dt.Select("number ='" + num_int + "' and Group ="'+group + '"");\nDataRow[] result2 = MainWindow.listUlg.Select("Ulg ='" +row[17]+"'");\n\nfor(var i = 0; i < Math.Min(result1.Length, result2.Length); i++){\n   MessageBox.Show(result2[i][1] + " " + result1[i][2]);\n}	0
23376121	23375992	Deserialize Dictionary<string, MyClass> from json, possible without Newtonsoft.Json?	var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, MyClass>>(myObjectJson);	0
17416644	17416111	How to convert datatable to dictionary in ASP.NET/C#	// Start by grouping\nvar groups = table.AsEnumerable()\n        .Select(r => new {\n                      ClassID = r.Field<int>("ClassID"),\n                      ClassName = r.Field<string>("ClassName"),\n                      StudentID = r.Field<int>("StudentID"),\n                      StudentName = r.Field<string>("StudentName")\n                  }).GroupBy(e => new { e.ClassID, e.ClassName });\n\n// Then create the strings. The groups will be an IGrouping<TGroup, T> of anonymous objects but\n// intellisense will help you with that.\nforeach(var line in groups.Select(g => String.Format("{0},{1}|+{2}<br/>", \n                                       g.Key.ClassID, \n                                       g.Key.ClassName,\n                                       String.Join(" and ", g.Select(e => String.Format("{0},{1}", e.StudentID, e.StudentName))))))\n{\n    Response.Write(line);\n}	0
31815685	31813271	Showing a messagebox from within a TableRowGroup inherited class	Task.Factory.StartNew(() => MessageBox.Show(message, "Title", MessageBoxButton.OK, MessageBoxImage.Warning));	0
21565696	21565659	How to find the index of the first char of a substring of string?	string test = "HelloWorld";  // World in uppercase \nint pos = test.IndexOf("world", StringComparison.CurrentCultureIgnoreCase);\nConsole.WriteLine(pos.ToString());	0
31428890	31428376	How to convert Binary images and display it in Repeater?	bytes = (byte[])dt.Rows[i]["BookPic"];\n                        base64String = Convert.ToBase64String(bytes, 0, bytes.Length);\n\n                        Image img = (Image)rptBooks.Controls[i].FindControl("ImgBookPic");\n                        img.ImageUrl = "data:image/png;base64," + base64String;	0
8548031	8547799	Text files to test the functionality of a search engine	"<a href=\""	0
19725774	19725674	Entity Framework - How to NOT update related objects	this.DbContext.Entry(orderItem.Product).State = EntityState.Detached;	0
21024373	21024329	Averaging with Linq while ignoring 0s cleanly	AvgItem1 = g.Select(x => (int)x["Item1"]).Where(x => x != 0).Average(),\nAvgItem2 = g.Select(x => (int)x["Item2"]).Where(x => x != 0).Average(),\nAvgItem3 = g.Select(x => (int)x["Item3"]).Where(x => x != 0).Average(),\nAvgItem4 = g.Select(x => (int)x["Item4"]).Where(x => x != 0).Average(),\nAvgItem5 = g.Select(x => (int)x["Item5"]).Where(x => x != 0).Average(),	0
8488495	8488415	Url doesnt point to area index file	context.MapRoute(\n    "Admin_default",\n    "Admin/{controller}/{action}/{id}",\n    new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional },\n    new string[] { "skylearn.Areas.Admin.Controllers" }\n);	0
8182421	8181886	Datagrid: generate columns from a property of the ItemsSource collection	foreach(var p in properties)\n {\n      //grid add new gridcolumn\n      //set binding to ArticleConfigurationSet Property Name\n      var b = new Binding("ArticleConfigurationSet"+p.Name);\n      //add binding to gridcolumn\n }	0
19552866	19548176	LinqToExcel dot in header	excel.AddMapping<Part>(x => x.Manufacturer, "Mfg#");	0
24735268	24734875	C# MessageBox with DialogResult giving "No overload for method 'Show' takes '3' arguments"	DialogResult dialogresult = MessageBox.Show("Are you sure?", "text", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);	0
1744446	1744388	Access Known Class's Parameter Named After Generic Class	public IQueryable<T> FindAll()\n{\n    return _ctx.GetTable<T>();\n}\n\npublic void Add(T entity)\n{\n    _ctx.GetTable<T>().InsertOnSubmit(entity);\n}	0
17867386	17867135	Literal Values from Database to RadioButtonList	var val = HttpServerUtility.HtmlEncode(dt.Rows[RowNo]["Distractor1"].ToString());\nRbloptions.Items.Insert(0, new ListItem(val, val));	0
16650417	16650329	Check two unique values, sql	INSERT mytable (A, B)\nSELECT 'A1', 'B1'\nWHERE NOT EXISTS (SELECT * FROM mytable WHERE A= 'A1' AND B = 'B1')	0
27953006	27952784	C# make line height adjust to ellipse	graphGraphics = e.Graphics;\n\ngraphGraphics.FillEllipse(new SolidBrush(Color.White), this.graphBoundries);\ngraphGraphics.DrawEllipse(graphPen, this.graphBoundries);\n\nGraphicsPath clipPath = new GraphicsPath();\nclipPath.AddEllipse(this.graphBoundaries);\n\ngraphGraphics.SetClip(clipPath, CombineMode.Replace);\n\n// draw your line	0
27467002	27463876	Passing bitmap from c# to c++	BitmapData bmpData = bitmapFrame.LockBits(new Rectangle(0, 0, bitmapFrame.Width, bitmapFrame.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, \n            System.Drawing.Imaging.PixelFormat.Format24bppRgb);\n\nativeFunctions.FaceTracker(bmpData.Scan0 , bitmapFrame.Width, bitmapFrame.Height);\n\nbitmapFrame.UnlockBits(bmpData); //Remember to unlock!!!	0
8406889	8406773	ASP.NET MVC controller actions with custom parameter conversion?	public class MyListBinder : IModelBinder\n{   \n     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n     {   \n        string integers = controllerContext.RouteData.Values["idl"] as string;\n        string [] stringArray = integers.Split(',');\n        var list = new List<int>();\n        foreach (string s in stringArray)\n        {\n           list.Add(int.Parse(s));\n        }\n        return list;  \n     }  \n}\n\n\npublic ActionResult GetItems([ModelBinder(typeof(MyListBinder))]List<int> id_list) \n{ \n    return View(); \n}	0
22828233	22827286	How to Read Txt File to a Webpage TextBox	var fileStream = new StreamReader(fileuplodID.PostedFile.InputStream);\n        string Data = fileStream.ReadToEnd();	0
2541486	2541469	Resize a ListView depending on how many items?	if (myListView1.SelectedItems.Count > 0) {\n    label14.Text = myListView1.SelectedItems[0].Text.ToString();\n}	0
6471934	6471877	Help checking if number value in string is odd C#	var option = GetOption(5);\nvar isOdd = int.Parse(option[option.Length - 1].ToString()) % 2 == 1;	0
3512235	3512005	any third party tool available for multiple file uploads	public void ProcessRequest (HttpContext context) \n{\n    HttpFileCollection hfc = context.Request.Files;\n    for (int i = 0; i < hfc.Count; i++)\n    {\n        HttpPostedFile hpf = hfc[i];\n        if (hpf.ContentLength > 0)\n        {   \n            string imageLocation = "C:\\ImageLocation\\" + theFileNameToSaveAs;\n\n            hpf.SaveAs(imageLocation);\n        }\n    }\n    context.Response.Redirect("../callingpage.aspx"); \n}	0
22456623	22454266	Table Layout Displaying WaitCursor Always	TableLayoutPanel1.UseWaitCursor = false;	0
18339407	18316873	Replace Text in Word document using Open Xml	using ( WordprocessingDocument doc =\n                    WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))\n            {\n                var body = doc.MainDocumentPart.Document.Body;\n                var paras = body.Elements<Paragraph>();\n\n                foreach (var para in paras)\n                {\n                    foreach (var run in para.Elements<Run>())\n                    {\n                        foreach (var text in run.Elements<Text>())\n                        {\n                            if (text.Text.Contains("text-to-replace"))\n                            {\n                                text.Text = text.Text.Replace("text-to-replace", "replaced-text");\n                            }\n                        }\n                    }\n                }\n            }\n        }	0
13946008	13796740	Identifying a property name with a low footprint	// Sending an object:\nm_eventStream.Push(objectInstance);\n\n// 'handling' an object when it arrives:\nm_eventStream.Of(typeof(MyClass))\n.Subscribe ( obj =>\n{\n    MyClass thisInstance = (MyClass) obj;\n    // Code here will be run when a packet arrives and is deserialized\n});	0
4774833	4774820	How to find the child class name from base class?	this.GetType().Name	0
10589310	10583278	How to get URI from which REST API (ServiceStack) being consumed	var aspnetReq = (HttpRequest)RequestContext.Get<IHttpRequest>().OriginalRequest;	0
848184	848147	How to convert Excel sheet column names into numbers?	public static int GetColumnNumber(string name)\n{\n    int number = 0;\n    int pow = 1;\n    for (int i = name.Length - 1; i >= 0; i--)\n    {\n        number += (name[i] - 'A' + 1) * pow;\n        pow *= 26;\n    }\n\n    return number;\n}	0
9297698	9297599	C#, multithreaded filling of a multidimensional array	Parallel.For(0, n, method)	0
3773874	3773585	Filtering a query in Entity Framework based upon a child value	var query = from p in context.ParentTable \n            from c in p.ChildTable \n            where p.IsActive == true \n                  && c.Name == "abc" \n            select p;	0
22310003	22309715	How to name axis in excel using C#?	Excel.Axis axisq = myChartq.Chart.Axes(Excel.XlAxisType.xlValue,\n               Excel.XlAxisGroup.xlPrimary);\naxisq.HasTitle = true;\naxisq.AxisTitle.Text = "Value axis NAME";\n\naxisq = myChartq.Chart.Axes(Excel.XlAxisType.xlCategory,\n                Excel.XlAxisGroup.xlPrimary);\naxisq.HasTitle = true;\naxisq.AxisTitle.Text = "Category axis NAME";	0
25406341	25406163	Serialize list of strings as an attribute	public class FrameSection\n{\n   [XmlAttribute]\n   public string Name { get; set; }\n\n   [XmlIgnore]\n   public string[] StartSection { get; set; }\n\n   [XmlAttribute("StartSection")]\n   public string StartSectionText\n   {\n      get { return String.Join(",", StartSection); }\n      set { StartSection = value.Split(','); }\n   }\n}	0
787069	787052	Trying to understand TransactionScope	// Inside each using TransactionScope(), hhok up the current transaction completed event\nTransaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted);\n\n// handle the event somewhere else\nvoid Current_TransactionCompleted(object sender, TransactionEventArgs e)\n{\n  //  check the status of the transaction\n  if(e.Transaction.TransactionInformation.Status == TransactionStatus.Aborted)\n    // do something here\n}	0
6323939	6323765	Build an object from another object in C# using generic code	public void CopyValues<TSource, TTarget>(TSource source, TTarget target)\n{\n    var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);\n\n    foreach (var property in sourceProperties)\n    {\n        var targetProperty = typeof(TTarget).GetProperty(property.Name);\n\n        if (targetProperty != null && targetProperty.CanWrite && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))\n        {\n            var value = property.GetValue(source, null);\n\n            targetProperty.SetValue(target, value, null);\n        }\n    }\n}	0
12319613	12319498	RegEx in c# for a piped (|) pattern string	var str = "ID | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Col8";\nvar strA = str.Split(" | ".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();\nvar strExtract = new List<string> { strA[2], strA[4] };\nstrA.RemoveAt(2);\nstrA.RemoveAt(3);\nConsole.WriteLine(string.Join(" | ", strA.ToArray()));	0
22320100	22319750	Get focus on a textbox inside a gridview	FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"	0
32043847	32043286	How can i add image when i want to respone page in asp.net?	string img = "<img src='https://cdn3.iconfinder.com/data/icons/simple-web-navigation/165/tick-128.png' width='128' height='128'>";\n        Response.Write("<br/>" + "SAMPLE" + img); ;	0
14407757	14407534	Create PrincipalContext using windows authentication	public static List<string> getGrps(string userName)          \n{          \n    List<string> grps = new List<string>();          \n\n    try          \n    {\n        var currentUser = UserPrincipal.Current;\n        RevertToSelf();             \n        PrincipalSearchResult<Principal> groups = currentUser.GetGroups();          \n        IEnumerable<string> groupNames = groups.Select(x => x.SamAccountName);          \n        foreach (var name in groupNames)          \n        {          \n            grps.Add(name.ToString());          \n        }          \n        return grps;          \n    }          \n    catch (Exception ex)          \n    {          \n        // Logging         \n    }          \n}	0
289363	289307	Can you combine multiple lists with LINQ?	var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );	0
652421	652366	XNA: Preventing a method from returning	public override void Update() { \n    if (movingRobot) {\n        OnlyUpdateRobotPosition();\n    }\n    else {\n        DoStuffPerhapsIncludingStartingRobotMove();\n    }\n}	0
17402521	17402096	How to add XML attribute in XML file in C#	//Store the namespaces to save retyping it.\nstring xsi = "http://www.w3.org/2001/XMLSchema-instance";\nstring xsd = "http://www.w3.org/2001/XMLSchema";\nXmlDocument doc = new XmlDocument();\nXmlSchema schema = new XmlSchema();\nschema.Namespaces.Add("xsi", xsi);\nschema.Namespaces.Add("xsd", xsd);\ndoc.Schemas.Add(schema);\nXmlElement docRoot = doc.CreateElement("eConnect");\ndocRoot.SetAttribute("xmlns:xsi",xsi);\ndocRoot.SetAttribute("xmlns:xsd",xsd);\ndoc.AppendChild(docRoot);\nXmlNode eConnectProcessInfo = doc.CreateElement("eConnectProcessInfo");\nXmlAttribute xsiNil = doc.CreateAttribute("nil",xsi);\nxsiNil.Value = "true";\neConnectProcessInfo.Attributes.Append(xsiNil);\ndocRoot.AppendChild(eConnectProcessInfo);	0
8854448	8418730	Regex C# for ~ delimited text file	public string GetInvoiceNumber(string line)\n{\n    if(line == null)\n    {\n        throw new ArgumentNullException("line");\n    }\n\n    var res = line.Split('~');\n\n    if(res.Length < 8)\n    {\n        throw new ArgumentException("The given line of text does not contain an invoice number!", "line");\n    }\n\n    return res[7];\n}	0
2962904	2962539	How to get a list of groups in an Active Directory group	PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DomainName"); \nGroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "TestGroup"); \n\nArrayList users = new ArrayList();\nArrayList groups = new ArrayList(); \n\nif (grp != null) \n{ \n    foreach (Principal p in grp.GetMembers(false)) //set to false\n    {\n        if (p.StructuralObjectClass == "user")\n            users.Add(p.Name);\n        else if (p.StructuralObjectClass == "group")\n            groups.Add(p.Name);\n    }\n}    \ngrp.Dispose(); \nctx.Dispose();	0
6713034	6713017	ASP.net Converting inputbox string to integer?	int myNewID = 0;\n\n    if(int.TryParse(txtID.Text, out myNewID))\n     {\n        //your code here\n    }\n    else\n    {\n       //your error handling here\n    }	0
18459641	18457158	How to convert back from string to Enum	public class PropertyValue\n{\n    private PropertyInfo propertyInfo;\n    private object baseObject;\n\n    public PropertyValue(PropertyInfo propertyInfo, object baseObject)\n    {\n        this.propertyInfo = propertyInfo;\n        this.baseObject = baseObject;\n    }\n\n    public string Name\n    {\n        get { return propertyInfo.Name; }\n\n    }\n\n    public Type PropertyType\n    {\n        get { return propertyInfo.PropertyType; }\n    }\n\n    public object Value\n    {\n        get\n        {\n            var retVal = propertyInfo.GetValue(baseObject, null);\n            if (PropertyType.IsEnum)\n            {\n                retVal = retVal.ToString();\n            }\n            return retVal;\n        }\n        set\n        {\n            if (PropertyType.IsEnum)\n            {\n                value = Enum.Parse(propertyInfo.PropertyType, value.ToString());\n            }\n            propertyInfo.SetValue(baseObject, value, null);\n        }\n    }\n}	0
2469193	2468994	How to detect that a process is started using C# code[windows service]	//in startup code...\ntimer = new System.Threading.Timer(CheckProcessAndKillIeIfNeedBe, null, 0L, (long)TimeSpan.FromMinutes(1).TotalMilliseconds);\n\n//some method elsewhere\npublic void CheckProccessAndKillIeIfNeedBe(object state)\n{\n  //do the process check and kill IE if conditions are met          \n}	0
3062659	3062595	Gridview making a column invisable	gridviewNameHere.Columns[index].Visible = false;	0
18996754	18996501	Create XML attribute in c#	XmlElement error = Errors.CreateElement("Error");\nXmlAttribute errName= Errors.CreateAttribute("Name");\nerrName.value="abc"\nerror.Attributes.Append(errName);	0
4385115	4384818	add a node to specific child node	private TreeNode FindNode(TreeNode root, String name)\n{\n    foreach (TreeNode node in root.Nodes)\n    {\n        if (node.Nodes.Count > 0)\n            return FindNode(root, name);\n        if (node.Name == name)\n            return node;\n    }\n    return null;\n}	0
14226552	14226473	C# Parsing XML File	var xdoc = XDocument.Load(path_to_xml);\nvar entries = from e in xdoc.Descendants("entry")\n              select new {\n                 Id = (int)e.Attribute("id"),\n                 Type = (string)e.Attribute("type"),\n                 Name = (string)e.Element("name"),\n                 Description = (string)e.Element("description")\n              };	0
5497123	5497064	C#: How to get the full path of running process?	using System.Diagnostics;\n var process = Process.GetCurrentProcess(); // Or whatever method you are using\n string fullPath = process.MainModule.FileName;\n //fullPath has the path to exe.	0
20114130	20113719	Get image from other ASP.Net project	Virtual Directory	0
19952547	19952461	How to short a data filling function?	var myProducts = connection.Query<Product>("SELECT * FROM Product");	0
15549608	15543301	Filter Outlook AppointmentItem gives strange result	Items.IncludeRecurrences	0
20009716	20009658	Reading a UTF-8 File in C#	byte[] fileBytes = File.ReadAllBytes(inputFilename);\nStringBuilder sb = new StringBuilder();\n\nforeach(byte b in fileBytes)\n{\n    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  // adds 8 '0's to left of the string\n}\n\nFile.WriteAllText(outputFilename, sb.ToString());	0
5193527	5193507	Convert image from one format to another	using (Image img = Image.FromFile(@"c:\pic.bmp")) {\n     img.Save(@"c:\pic.jpg" ,ImageFormat.Jpeg); \n}	0
22770334	22770229	Comparing two times: determine if one is on a different day	public bool IsDifferentDays(DateTime time1, DateTime time2) {\n    if (time1 > time2) {\n\n      return true;\n\n    }\n      return false;\n}	0
21065621	21065469	C# Regular Expression to insert "_" after third, then seventh character with a new line after the eighth character	var s = "goeirjew98rut34ktljre9t30t4j3der";\nRegex.Replace(s, @"(\w{3})(\w{4})(\w{1})", "$1_$2_$3\n").Dump();	0
15454198	15453070	Ninject Singleton Factory	public class FooFactory : IFooFactory\n{\n    // allows us to Get things from the kernel, but not add new bindings etc.\n    private readonly IResolutionRoot resolutionRoot;\n\n    public FooFactory(IResolutionRoot resolutionRoot)\n    {\n        this.resolutionRoot = resolutionRoot;\n    }\n\n    public IFoo CreateFoo()\n    {\n        return this.resolutionRoot.Get<IFoo>();\n    }\n\n    // or if you want to specify a value at runtime...\n\n    public IFoo CreateFoo(string myArg)\n    {\n        return this.resolutionRoot.Get<IFoo>(new ConstructorArgument("myArg", myArg));\n    }\n}\n\npublic class Foo : IFoo { ... }\n\npublic class NeedsFooAtRuntime\n{\n    public NeedsFooAtRuntime(IFooFactory factory)\n    {\n        this.foo = factory.CreateFoo("test");\n    }\n}\n\nBind<IFooFactory>().To<FooFactory>();\nBind<IFoo>().To<Foo>();	0
15946649	15945264	C# Delaying writing to XML	var doc = new XmlDocument();\ndoc.Load(FileName);\nXmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };\n\nnew System.Threading.Timer((_) =>\n    {\n        using (var writer = XmlWriter.Create(destinationFile, settings))\n        {\n            doc.Save(writer);\n        }\n    })\n.Change(15000, -1);	0
22612346	22612146	Is there a regular expression for this?	j(\<[^\<]*?\>\s*)*u(\<[^\<]*?\>\s*)*s(\<[^\<]*?\>\s*)*t(\<[^\<]*?\>\s*)*	0
26440419	26400648	Get next fire time only by looking at cron expression	var expression = new CronExpression("0 26 13 17 10 ? 2015");\nDateTimeOffset? time = expression.GetTimeAfter(DateTimeOffset.UtcNow);	0
16517517	16517411	Add string after a specified string	string html = "<head></head><body><img src=\"stickman.gif\" width=\"24\" height=\"39\" alt=\"Stickman\"><a href=\"http://www.w3schools.com\">W3Schools</a></body>";\nvar index = html.IndexOf("<head>");\n\nif (index >= 0)\n{\n     html = html.Insert(index + "<head>".Length, "<base href=\"http://www.w3schools.com/images/\">");\n}	0
11874676	11874507	how to use EF repository's find method?	Query(u=>u.Name == "Bob");	0
33691636	33691550	Check value of datatable to update or insert in c#	var rows = dataTable.Select(string.Format("DocumentId = {0}", documentId));\n\nif (rows.Length == 0)\n{\n   // Add your Row\n}\nelse\n{\n   // Update your Days\n   rows[0]["Days"] = newDayValue;\n}	0
12190053	12189811	Retrieving (Validating) a portion of a string	Regex re = new Regex(@"\$LOOP\b");	0
32497807	27146490	How can I mix TPH and TPT in Entity Framework 6?	protected override void OnModelCreating ( DbModelBuilder modelBuilder )\n{\n    // Not changed\n    modelBuilder\n        .Entity<BaseEntity> ()\n        .ToTable ( "BaseTable" );\n\n\n    // --- CHANGED ---\n    modelBuilder.Entity<BaseEntity> ()\n        // TPH => Discriminator\n        .Map<Inherited_TPH> ( m => m.Requires ( "Type" ).HasValue ( 1 ).IsOptional () ) \n        // TPT => Mapping to table\n        .Map<Inherited_TPT> ( m => m.ToTable ( "Inherited_TPT" ) ); \n\n    // Not changed\n    modelBuilder\n        .Entity<SomethingElse> ()\n        .ToTable ( "SomethingElse" )\n        .HasKey ( t => t.Id );\n}	0
19030597	19029978	Break up String with string Manupilation or Regular Expression	List<String> output=Regex.Matches(input,@"(?s)(?i)\bTask\b\s*\d+:.*?(?=\bTask\b|$)") \n                         .Cast<Match>()\n                         .Select(x=>x.Value)\n                         .ToList();	0
18654402	18653618	How can I map constants and class property values to a Dictionary<int, object>?	Contact myContact = ...;\n\ntypeof(ContactKeys)\n    .GetFields(BindingFlags.Public | BindingFlags.Static)\n    .ToDictionary(f => (int)f.GetValue(null),\n                  f => typeof(Contact).GetProperty(f.Name).GetValue(myContact));	0
24487392	24486858	Group rows in DataGridView	protected override void OnCellPainting(DataGridViewCellPaintingEventArgs args)\n{\n  base.OnCellPainting(args);\n\n  args.AdvancedBorderStyle.Bottom =\n    DataGridViewAdvancedCellBorderStyle.None;\n\n  // Ignore column and row headers and first row\n  if (args.RowIndex < 1 || args.ColumnIndex < 0)\n    return;\n\n  if (IsRepeatedCellValue(args.RowIndex, args.ColumnIndex))\n  {\n    args.AdvancedBorderStyle.Top =\n      DataGridViewAdvancedCellBorderStyle.None;\n  }\n  else\n  {\n    args.AdvancedBorderStyle.Top = AdvancedCellBorderStyle.Top;\n  }\n}	0
22138966	22138795	From Idle to Action using GlobalMouseKeyHook (C#)	Application.Run();	0
19843265	19843212	DateTime format for c#	DateTime dt = DateTime.ParseExact("10.01.2013", "MM.dd.yyyy", CultureInfo.InvariantCulture);	0
3751751	3751715	Convert BitmapSource to Image	private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)\n{\n  System.Drawing.Bitmap bitmap;\n  using (MemoryStream outStream = new MemoryStream())\n  {\n    BitmapEncoder enc = new BmpBitmapEncoder();\n    enc.Frames.Add(BitmapFrame.Create(bitmapsource));\n    enc.Save(outStream);\n    bitmap = new System.Drawing.Bitmap(outStream);\n  }\n  return bitmap;\n}	0
1489364	1489243	How can I convert ticks to a date format?	datename(month,(MachineGroups.TimeAdded-599266080000000000)/864000000000) +\n  space(1) +\n  datename(d,(MachineGroups.TimeAdded-599266080000000000)/864000000000) +\n  ', ' +\n  datename(year,(MachineGroups.TimeAdded-599266080000000000)/864000000000);	0
6120461	6111282	Problem calling Google Chart API from C# App	byte[] fileBytes = null;\n\n    WebClient client = new WebClient();\n    fileBytes = client.DownloadData(url);\n    MemoryStream theMemStream = new MemoryStream();\n\n    theMemStream.Write(fileBytes, 0, fileBytes.Length);\n    System.Drawing.Image img2 = System.Drawing.Image.FromStream(theMemStream);	0
18747216	18746695	XMLSerializer and creating an XML Array with an attribute	[XmlRoot(ElementName = "subject_datas")]\n    public class SubjectDatas\n    {\n        [XmlElement(ElementName = "subject_data")]\n        public List<SubjectData> SubjectDatas2 { get; set; }\n\n        public SubjectDatas(IEnumerable<SubjectData> source)\n        {\n            SubjectDatas2= new List<SubjectData>();\n            this.SubjectDatas2.AddRange(source);\n            Type = "array";\n        }\n\n        private SubjectDatas()\n        {\n            Type = "array";\n        } \n\n        [XmlAttribute(AttributeName = "type")]\n        public string Type { get; set; }\n    }	0
886496	886488	Copy one string array to another	targetArray = new string[sourceArray.Length];\nsourceArray.CopyTo( targetArray, 0 );	0
814826	814821	How do I ensure that objects are disposed of properly in .NET?	protected override void Dispose(bool disposing)\n{\n    if (disposing)\n    {\n        // dispose managed resources here\n    }\n    // dispose unmanaged resources here\n}	0
10363734	10363690	How to get the checked items of checkboxes created dynamically and write that value to a file in WPF?	private void button5_Click(object sender, RoutedEventArgs e)\n{\n string str="";\n foreach (UIElement child in canvas.Children)\n {\n   if(child  is CheckBox)\n     if(((CheckBox)child).IsChecked)\n       str+=((CheckBox)child).Content;\n\n }\n string fp6 = @"D:\List2.txt";\n File.WriteAllText(fp6,str);\n\n}	0
25806088	25805905	Non-standard joining of two lists	var MyList = List1.Concat(List2.Except(List1).ToList());	0
34224929	34224455	Nunit Test A C# Model	var x = "myexpectedstring"\nvar y = "myexpectedstring"\n\nAssert.Equal(x, y);	0
29449812	29449388	WPF C# Custom UI Element?	[Category("Common")]\npublic string Label { get; set; }	0
4615132	4614119	Dynamic checkboxlist	string URLName = row["URLName"].ToString();\n            bool enabled = Convert.ToBoolean(row["Enabled"]);\n\n            checkedListBox1.Items.Add(URLName, enabled);	0
34491829	34490460	How does application layer unit tests look like in DDD?	this._balances	0
7543208	7543204	Is it possible to put two Lambda expressions inside a single query?	testing.Where(x => x == null || x == ("")  );	0
28555922	28555847	Inserting a string in the middle of another string or splitting the string into two parts	StringBuilder sb = new StringBuilder();\n\nsb.Append(string1.Substring(0,string1.Length/2));\nsb.Append(string2);\nsb.Append(string1.Substring(string1.Length/2,string1.Length- string1.Length/2));\n\nConsole.WriteLine(sb.ToString());	0
32484422	32484325	How specify generated folder(Directory) Name in C#	string dayPath = DateTime.Today.ToString("yyyyMMdd");\nstring newPath = Path.Combine(location, dayPath);\nDirectory.CreateDirectory(newPath);\n........	0
15007170	15007031	Join two list on a specified column	List<first> flist= new List<first>();\nList<second> slist= new List<second>();\n\nvar result = from f in flist\n             join s in slist on f.ID equals s.ID into g\n             select new {\n                 f.name,\n                 f.ID,\n                 itemAttr = g.Any() ? g.First().itemAttr : null\n             };	0
30753718	30751969	Invoking control hanging application	if (_control.InvokeRequired)\n    {\n       IAsyncResult result = _control.BeginInvoke((Action)(() => control.text = text));\n       _control.EndInvoke(result);\n    }\n    else\n    {\n        _control.Text = text;\n    }	0
14938694	14938296	Application heartbeat monitoring, possibly via SQL server	System.Net.Mail.MailMessage	0
18803006	18802924	Doing mathematical operations on operands of various sizes, only known at runtime	public static T Add<T>(T a, T b) where T: struct\n{\n    dynamic first = a;\n    dynamic second = b;\n    return first + second;\n}	0
19044440	19041675	Is it possible to get a list of site collections of a SharePoint server?	SPServiceCollection services = SPFarm.Local.Services;\n        foreach(SPService curService in services)\n        {\n            if(curService is SPWebService)\n            {\n                SPWebService webService = (SPWebService)curService;\n\n\n                foreach(SPWebApplication webApp in webService.WebApplications)\n                {\n                    foreach(SPSite sc in webApp.Sites)\n                    {\n                        try\n                        {\n                            Console.WriteLine("Do something with site at: {0}", sc.Url);\n                        }\n                        catch(Exception e)\n                        {\n                            Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);\n                        }\n                    }\n                }\n            }\n        }	0
13722216	13721686	Parse this json string to string array c#	string json = "{\"postalcode\":\"12345\",\"postalcity\":\"SOME-CITY\",\"country\":\"UK\",\"box\":false}";\n\nvar dict = new JavaScriptSerializer().Deserialize<Dictionary<string,object>>(json);\nvar postalCode = dict["postalcode"];\n\n//Array is also possible\nstring[] result = dict.Select(kv => kv.Value.ToString()).ToArray();	0
17952740	17952386	Is it possible to modify a control property's get and set methods without extending the control?	public static void SetValue(this HiddenField c, string text)\n{\n    c.Value = HttpUtility.HtmlEncode(text);\n}\n\npublic static string GetValue(this HiddenField c)\n{\n    return HttpUtility.HtmlDecode(c.Value);\n}	0
22596199	22596146	Use linq to filter by property of subcollection	stores = allData.Stores\n    .Where(s => storeIDs.Contains(s.ID))\n    .Select(s => new Store\n    {\n        ID = s.ID,\n        annualData = s.annualData\n            .Where(x => years.Contains(x.Year))\n            .ToList()\n    });	0
3475874	3475861	Logger application for c# console application	class MyClass\n{\n    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();\n\n    public void MyMethod()\n    {\n        // available logging levels TRACE,INFO,DEBUG,WARN,ERROR, FATAL\n        Logger.Debug("Debug message"); \n    }\n}	0
2569231	2569166	Converting Negative Decimal To String Loses the -	decimal myDecimalValue = -39m;\nstring s = String.Format("${0:0.00}", myDecimalValue); // $-39.00	0
28077534	28076520	Twitter streaming api with linq2twitter / tweetinvi	var searchResponse =\n            await\n            (from search in twitterCtx.Search\n             where search.Type == SearchType.Search &&\n                   search.Query == "\"LINQ to Twitter\""\n             select search)\n            .SingleOrDefaultAsync();	0
22734717	22734706	Working with enum in C#	value = (short)mode;	0
6104330	5884789	Using pdflatex.exe to Convert TeX to PDF within a C#/WPF Application	string filename = "<your LaTeX source file>.tex";\nProcess p1 = new Process();\np1.StartInfo.FileName = "<your path to>\pdflatex.exe";\np1.StartInfo.Arguments = filename;\np1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\np1.StartInfo.RedirectStandardOutput = true;\np1.StartInfo.UseShellExecute = false;\n\nProcess p2 = new Process();\np2.StartInfo.FileName = "<your path to>\bibtex.exe";\np2.StartInfo.Arguments = Path.GetFileNameWithoutExtension(filename);\np2.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\np2.StartInfo.RedirectStandardOutput = true;\np2.StartInfo.UseShellExecute = false;\n\np1.Start();\nvar output = p1.StandardOutput.ReadToEnd();\np1.WaitForExit();\n\np2.Start();\noutput = p2.StandardOutput.ReadToEnd();\np2.WaitForExit();\n\np1.Start();\noutput = p1.StandardOutput.ReadToEnd();\np1.WaitForExit();\n\np1.Start();\noutput = p1.StandardOutput.ReadToEnd();\np1.WaitForExit();	0
1381523	1381420	How can a child thread notify a parent thread of its status/progress?	class Service\n{\n  public delegate void JobStatusChangeHandler(string status);\n\n  // Event add/remove auto implemented code is already thread-safe.\n  public event JobStatusHandler JobStatusChange;\n\n  public void PerformWork()\n  {\n    SetStatus("STARTING");\n    // stuff\n    SetStatus("FINISHED");\n  }\n\n  private void SetStatus(string status)\n  {\n    JobStatusChangeHandler snapshot;\n    lock (this)\n    {\n      // Get a snapshot of the invocation list for the event handler.\n      snapshot = JobStatusChange;\n    }\n\n    // This is threadsafe because multicast delegates are immutable.\n    // If you did not extract the invocation list into a local variable then\n    // the event may have all delegates removed after the check for null which\n    // which would result in a NullReferenceException when you attempt to invoke\n    // it.\n    if (snapshot != null)\n    {\n      snapshot(status);\n    }\n  }\n}	0
5801590	5801467	How to Convert Int[][] to Double[][]?	.Select(x => (double)MyIntegerParse(x))	0
5640428	5640357	Fastest way to fill a matrix with Random bytes	Random random = new Random();\nbyte[] row = new byte[size * size];\nrandom.NextBytes(row);\nBuffer.BlockCopy(row, 0, fullMap, 0, size * size);	0
10943657	10943651	Pass array as a parameter to another	private void check(string keyword, params arr[] msg_arr)	0
31955130	31954882	Downsides to Using the Same Value for Key and IV?	IV = DeriveBytes(salt + password + "IV")\nkey = DeriveBytes(salt + password + "key")	0
32202498	31941481	How do you set the name of a Azure SQL Server in C#?	var result = client.Servers.CreateOrUpdateAsync(\n      _resourceGroupName, "my-Server", new ServerCreateOrUpdateParameters...	0
24769366	24769334	How to remove \r\n from string c#	text = text.Replace(System.Environment.NewLine, string.Empty);	0
16830409	16805807	How to open PDF from C# application running as an administrator	Process.Start("explorer.exe","<FullyQualifiedPath>\Help.pdf");	0
34200976	34198507	Take first item from Include collection	var model = from t in db.TankCentres\n                    where t.Live == true\n                    select new ViewAllTanksViewModel\n                    {\n                        Id = t.Id,\n                        Name = t.Name,\n                        Address = t.Address,\n                        Live = t.Live,\n                        ExperienceId = t.ExperienceId,\n                        MainImageVM = t.ProfileImages.FirstOrDefault()\n                    };	0
3320457	3320403	Can I send only byte array with asynchronous Socket class?	string sendMessage = "This is a clarified example now";\nbyte[] byteMessage = System.Text.Encoding.ASCII.GetBytes(sendMessage)	0
950766	950726	Dynamic Sort Criteria for Generic List	public override List<oAccountSearchResults> SearchForAccounts<T>(\n              oAccountSearchCriteria searchOptions,\n              Func<oAccountSearchResults, T> keyExtract) where T : IComparable {\n  List<oAccountSearchResults> results = Service.SearchForAccounts(searchOptions);\n\n  results.Sort(a,b) => keyExtract(a).CompareTo(keyExtract(b)));\n  return results;\n}	0
18952334	18933713	RegEx to Validate URL with optional Scheme	^(http(s)?://)?[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-??\.\?\,\'\/\\\+&amp;%\$#_]*)?$	0
20340597	20290447	ObjectAnimator Proxy to Animate TopMargin can't find setting/getter	[Export]\npublic int getTopMargin()\n{\n  var lp = (ViewGroup.MarginLayoutParams)mView.LayoutParameters;\n  return lp.TopMargin;\n}\n\n[Export]\npublic void setTopMargin(int margin)\n{\n  var lp = (ViewGroup.MarginLayoutParams)mView.LayoutParameters;\n  lp.SetMargins(lp.LeftMargin, margin, lp.RightMargin, lp.BottomMargin);\n  mView.RequestLayout();\n}	0
11503579	11503536	Find out is a generic type implement an interface	public IList<T> MyMethod<T>() where T : class, IMyInterface1\n{\n    if (typeof(IMyInterface2).IsAssignableFrom(typeof(T)))\n    {\n        // code here\n    }\n\n    return myResult;\n}	0
18457058	18456950	How do i check database table through datatable and extract information of another column of database table?	string queryString = "Select [friendshipstatus] from [tblfriend] where [username] = @username and [friend] = @friend";\nusing (SqlConnection connection = new SqlConnection(connectionString))\nusing (SqlCommand command = new SqlCommand(queryString, connection))\n{\n    command.Parameters.AddWithValue("@username", username);\n    command.Parameters.AddWithValue("@friend", friendname );\n\n    connection.Open();\n    using (SqlDataReader reader = command.ExecuteReader())\n    {\n        if(reader.Read()) // you have matching record if this condition true \n        {\n            friendship = reader.GetString(0); // get the value of friendshipstatus \n        }\n    }\n}	0
19041101	19040723	How to Unit Test when the WPF Application is needed?	public interface IExceptionManager\n{\n    event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;\n}\n\npublic class ExceptionManager : IExceptionManager\n{\n    Application _app;\n\n    public ExceptionManager(Application app)\n    {\n        _app = app;\n    }\n\n    public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException\n    {\n        add\n        {\n            _app.DispatcherUnhandledException += value;\n        }\n\n        remove\n        {\n            _app.DispatcherUnhandledException -= value;\n        }\n    }\n}\n\npublic class MockExceptionManager: IExceptionManager\n{\n    public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;\n}	0
1117929	1117842	how to invoke IE to open a local html file?	using System.Diagnostics;\n\nProcess the_process = new Process();\nthe_process.StartInfo.FileName = "iexplore.exe";\nthe_process.StartInfo.Verb = "runas";\nthe_process.StartInfo.Arguments = "myfile.html";\nthe_process.Start();	0
4405101	4402774	Silverlight: How to do this data binding?	void AutoCompleteTextBox_Loaded(object sender, EventArgs e)\n{\n    ((AutoCompleteTextBox)sender).ItemsSource = Bar.GetNames();\n}	0
30462947	30458213	Does Roslyn actually allow you to manipulate TreatWarningsAsErrors for a CSharp project?	compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Error)	0
26151646	26122617	EPPlus / How to get data from pivot table? Or how to manipulate data easily?	var zip = new ExcelPackage(file).Package;\nvar recordspart = zip.GetPart(new Uri("/xl/worksheets/sheet1.xml", UriKind.Relative));\nvar recordsxml = XDocument.Load(recordspart.GetStream());	0
1206708	1202389	Diagram element tooltips in a Nevron diagram	someShape.StyleSheet.Style.InteractivityStyle = new NInteractivityStyle("Tooltip text");	0
5287884	5287752	C# How to use DataAnnotations StringLength and SubString to remove text	var attribute = typeof(ModelClass).GetProperties()\n                                  .Where(p => p.Name == "Description")\n                                  .Single()\n                                  .GetCustomAttributes(typeof(StringLengthAttribute), true) \n                                  .Single() as StringLengthAttribute;\n\nConsole.WriteLine("Maximum Length: {0}", attribute.MaximumLength);	0
6339707	6339584	how to show alert popup after finishing database processing?	ClientScript.RegisterStartupScript(this.GetType(), "FileUploadMessage", "jAlert('success', 'Your file has been uploaded.', 'Success Dialog');", true);	0
32835720	32809978	Passing Model and its object as a parameter	public void Logto<T>(T modifyObject, IEnumerable<dynamic> query, decimal Id) where T : class, IEntity\n{\n     var original = db.Set<T>().AsNoTracking().FirstOrDefault(e => e.N100 == Id);\n     var modified = original.ModifiedValues<T>(modifyObject).ToList();\n     // some code here\n}	0
3394945	3360617	use xpath to select all attributes in a element and add those to a list	var elements = new List<List<string>>();\n\n// this selects all 'Scene' elements\nXPathNodeIterator elem = nav.Select("//Scene");\nwhile(elem.MoveNext())\n{\n    XPathNavigator elemNav = elem.Current.Clone();\n\n    var attributes = new List<string>();\n\n    // now select all attributes of this particular 'Scene' element\n    XPathNodeIterator attr = elemNav.Select("@*");\n    while(attr.MoveNext())\n    {\n        attributes.Add(attr.Current.Value);\n    }\n\n    elements.Add(attributes);\n}	0
17683808	17683620	C# Actively detect Lock keys	private static IntPtr HookCallback(\n    int nCode, IntPtr wParam, IntPtr lParam)\n{\n    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)\n    {\n        int vkCode = Marshal.ReadInt32(lParam);\n        Keys key = (Keys)vkCode;\n        if (key == Keys.Capital)\n        {\n            Console.WriteLine("Caps Lock: " + !Control.IsKeyLocked(Keys.CapsLock)); \n        }\n        if (key == Keys.NumLock)\n        {\n            Console.WriteLine("NumLock: " + !Control.IsKeyLocked(Keys.NumLock));\n        }\n        if (key == Keys.Scroll)\n        {\n            Console.WriteLine("Scroll Lock: " + !Control.IsKeyLocked(Keys.Scroll));\n        }\n        Console.WriteLine((Keys)vkCode);\n    }\n    return CallNextHookEx(_hookID, nCode, wParam, lParam);\n}	0
6739384	6739340	Format a decimal using at least 2 places and at most 6 places	.ToString("0.00####");	0
29216347	29215503	Invalid token in XML	XmlNode node = doc.DocumentElement.SelectSingleNode("//update[@appId='" + appID + "']"); //appId=CSV_Load	0
10001628	10001576	Convert characters string to Unsigned int	var symbol = "BA";\nvar encoded = symbol.Aggregate(0u, (acc, c) => (uint)(acc * 100 + c - 'A' + 13));	0
1502617	1502526	Using p/invoke to call a function from a C api	using System;\nusing System.Runtime.InteropServices;\n\npublic static class MyCApi\n{\n    [StructLayout(LayoutKind.Sequential)]\n    public struct CASHTYPE\n    {\n        public int CashNumber;\n        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]\n        public CURRENCYTYPE[] Types;\n    }\n\n    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n    public struct CURRENCYTYPE\n    {\n        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2)]\n        public string Name;\n        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]\n        public string NoteType;\n        public int NoteNumber;\n    }\n\n    [DllImport("MyCApi.dll")]\n    public static extern int GetData(ref CASHTYPE cashData);\n}	0
19318935	19318508	How to convert dynamic json into a custom string?	// DynamicJson - (IsObject)\nvar objectJson = DynamicJson.Parse(@"{""foo"":""json"",""bar"":100}");\nforeach (KeyValuePair<string, dynamic> item in objectJson)\n{\n    Console.WriteLine(item.Key + ":" + item.Value); // foo:json, bar:100\n}	0
31680972	31680854	Adding a Parameter to a Button_Click event in WPF	private void TerminateAll_Click(object sender, RoutedEventArgs e) \n{\n    List<string> processes = // get the list\n    TerminateAll(processes);\n}\n\npublic void TerminateAll(List<string> processes)\n{\n   foreach(string process in processes)\n     Terminate(process);\n}\nprivate void Terminate(string process)\n{\n  // terminate the process\n}	0
7624978	5825104	How to display data from a SQLite database into a GTK# TreeView?	ListStore SetupModel( TreeView tv ){\n    var m = new ListStore(typeof(string),typeof(string));\n\n    var nameCol = new TreeViewColumn( "Name", \n      new CellRendererText(), "text", 0 );\n    tv.AppendColumn( nameCol );\n\n    var colourCol = new TreeViewColumn( "Colour", \n      new CellRendererText(), "text", 1 );\n    tv.AppendColumn( colourCol );\n\n    tv.Model = m;\n    return m;\n  }\n\n  void PopulateData( ListStore model ) {\n    model.AppendValues( "Fred", "Blue" );\n    model.AppendValues( "Bob", "Green" );\n    model.AppendValues( "Mary", "Yellow" );\n    model.AppendValues( "Alice", "Red" );\n  }	0
10417791	10400875	Using WebRequest to obtain cookies to automatically log into Sharepoint Online, getting variour errors	sprequest.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0";	0
3124557	3124464	Prevent multiline TextBox from "stealing" scroll event	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass MyTextBox : TextBox {\n    protected override void WndProc(ref Message m) {\n        // Send WM_MOUSEWHEEL messages to the parent\n        if (m.Msg == 0x20a) SendMessage(this.Parent.Handle, m.Msg, m.WParam, m.LParam);\n        else base.WndProc(ref m);\n    }\n    [DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}	0
6532890	6532655	Draw and Clear String over a Control C#	void Label_OnPaint(object sender, PaintEventArgs e) {\n  base.OnPaint(e);\n  Label lbl = sender as Label;\n  if (lbl != null) {\n    string Text = lbl.Text;\n    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n    if (myShowShadow) { // draw the shadow first!\n      e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault);\n    }\n    e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault);\n  }\n}	0
30915886	30913037	NHibernate QueryOver group by without selecting the grouped by column	var subquery =\n    QueryOver.Of<SomeEntity>()\n        .Where(_ => _.SomeOtherEntity.Id == someId)\n        .Select(\n            Projections.ProjectionList()\n                .Add(Projections.SqlGroupProjection("max(MaxPerGroupProperty) as maxAlias", "SomeGroupByProperty",\n                    new string[] { "maxAlias" }, new IType[] { NHibernate.NHibernateUtil.Int32 })));\n\nvar parentQuery = session.QueryOver<SomeEntity2>()\n    .WithSubquery.WhereProperty(x => x.MaxPerGroupPropertyReference).In(subquery).List();	0
10788143	10787574	C# Regular expression to match these strings	Regex sWordMatch = new Regex(\n      @"""[^""]*""" + // groups of characters enclosed in quotes\n      @"|[^""\s]*\S+[^""\s]*", // groups of characters without whitespace not enclosed in quotes	0
16888915	16888890	how to add images from file location WPF	image1.Source = new BitmapImage(new Uri(filePath));	0
32419976	32419948	String matching from a list	if (list.Any(x => adrBarTextBox.Text.Contains(x)))\n{\n   //...\n}	0
31084634	31034166	How to install/get started with MEF 2	System.ComponentModel.Composition.Registration	0
6112276	6110433	Json.NET - convert JSON to XML and remove XML version, encoding?	var strXML = "";\n var writer = new StringBuilder();   \n var settings = new System.Xml.XmlWriterSettings() { OmitXmlDeclaration = true};\n var xmlWriter = System.Xml.XmlWriter.Create(strXML, settings);   \n xmlDoc.Save(xmlWriter);\n strXML = writer.ToString();	0
20326044	20325996	Splitting Text and Integer from values in a Drop Down List	String [] str=drpdownList.SelectedItem.ToString().Split('-');\nString str1=str[0].Trim();\nString str2=str[1].Trim();	0
14313479	14313427	How to assign plain XML to C# variable	XDocument document = XDocument.Parse("<Employees></Employees>")	0
13753214	13753193	Setting a DateTime to the first of the next month?	olddate = olddate.AddMonths(1);\nDateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, \n    0, 0, 0, olddate.Kind);	0
19329915	19329818	reassigning a pointer in csharp	var[] curtable = table;\ni = start[k];\nint idx = i >> m;\n\ni <<= tablebits;\nn = k - tablebits;\n\n/* make tree (n length) */\nwhile (--n >= 0) \n{\n    if (curtable[idx] == 0) \n    {\n        right[avail] = left[avail] = 0;\n        curtable[idx] = avail++;\n    }\n    if (i & 0x8000) \n    {\n          idx = curtable[idx];\n          curtable = right;\n    }\n    else  \n    {\n          idx = curtable[idx];\n          curtable = left;\n     }\n    i <<= 1;\n}\ncurtable[idx] = j;	0
6325127	6325098	Search a string for a specific character	int index = inputValue.IndexOfAny(new char[] {'+' , '-' , '*' , '/' , '%'});\n    if (index != -1)\n    {\n        modifier = inputValue[index];\n        goto DoMath;\n    }	0
6441616	6441563	Reducing variable usage while checking a group of controls	if(!group_Box.productType.Controls.OfType<CheckBox>().Any( c => c.Checked ) )\n{\n...\n}	0
25044545	25044443	Merge two arrays in a Key => Value	int[] numbers = { 1, 2, 3, 4 };\nstring[] words = { "one", "two", "three" };\n\nvar numbersAndWords = numbers.Zip(words, (number, word) => new KeyValuePair<string,int>(word, number);	0
14944863	14942064	LineAndMarker<MarkerPointsGraph> only see markers, but no lines?	Action UpdateData = delegate()\n                        {\n                            ((LineGraph)plotter.Children.ElementAt(startIndex + i)).DataSource = ds;\n                            ((LineGraph)plotter.Children.ElementAt(startIndex + i)).LinePen = new Pen(new SolidColorBrush(Colors.Green), 1);\n\n                            ((PointsGraphBase)plotter.Children.ElementAt(startIndex + i + 1)).DataSource = ds;\n                            ((MarkerPointsGraph)plotter.Children.ElementAt(startIndex + i + 1)).Marker = new CirclePointMarker { Size = 5, Fill = Brushes.Red };                 \n                        };\n\n                        this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, UpdateData);	0
9271379	9271361	using a namespace in c#	using YourNameSpace;	0
28843718	28843305	Create JSON with LINQ	AccountParticulars = ac.AccountParticulars.Select(ap => new \n{\n    Name = ap.Name,\n    Credit = g.Where(entry => ap.Id == entry.AccountParticularId).Sum(entry => entry.Credit),\n    Debit = g.Where(entry => ap.Id == entry.AccountParticularId).Sum(entry => entry.Debit),\n})	0
2624613	2623927	ERROR_MORE_DATA ---- Reading from Registry	[DllImport("offreg.dll", CharSet = CharSet.Auto, SetLastError = true)]\npublic static extern uint ORGetValue(IntPtr Handle, string lpSubKey, string lpValue, out int pdwType, StringBuilder pvData, ref int pcbData);\n\n  int pdwtype;\n  var buffer = new StringBuilder(256);\n  int pcbdata = buffer.Capacity;\n  uint ret3 = ORGetValue(myKey, "", "DefaultUserName", out pdwtype, buffer, ref pcbdata);\n  string myValue = buffer.ToString();	0
26577124	26568542	Flipping a 2D Sprite Animation in Unity 2D	void Flip()\n{\n    // Switch the way the player is labelled as facing\n    facingRight = !facingRight;\n\n    // Multiply the player's x local scale by -1\n    Vector3 theScale = transform.localScale;\n    theScale.x *= -1;\n    transform.localScale = theScale;\n}	0
15307246	15307217	Remove empty XML elements	foreach (var info in xdoc.Descendants(tns + "sign"))\n        {\nif(info.Element(tns + "current-message").Value != "")\n                {\n                Items.Add(new ItemViewModel()\n                    {\n                        ID = i.ToString(),\n                        LineOne = info.Element(tns + "direction").Value,\n                        LineTwo = info.Element(tns + "current-message").Value,\n                        LineThree = info.Element(tns + "name").Value\n\n                    });\n                i++;\n                }\n        }	0
27792841	27792755	how to close a currently opened window not by using "This.Close", but accessing a method of a class	using System.Windows;\n\npublic\nstatic\nclass WindowManager\n{\n    private\n    static\n    Window CurrentWindow;\n\n    public\n    static\n    void CloseCurrentWindow ()\n    {\n        WindowManager.CurrentWindow.Close ();\n    }\n\n    public\n    static\n    void ShowMainWindow ()\n    {\n        MainWindow Window = new MainWindow ();\n\n                                      Window.Show ();\n        WindowManager.CurrentWindow = Window;\n    }\n}	0
7555933	7555867	Delete Lines in a textfile	private void button1_Click(object sender, EventArgs e)\n    {\n        StringBuilder newText = new StringBuilder();\n        using (StreamReader tsr = new StreamReader(targetFilePath))\n        {\n            do\n            {\n                string textLine = tsr.ReadLine() + "\r\n";\n\n                {\n                    if (textLine.StartsWith("INSERT INTO"))\n                    {\n\n                        newText.Append(textLine + Environment.NewLine);\n                    }\n\n                }\n            }\n            while (tsr.Peek() != -1);\n            tsr.Close();\n        }\n\n        System.IO.TextWriter w = new System.IO.StreamWriter(@"C:\newFile.txt");\n        w.Write(newText.ToString());\n        w.Flush();\n        w.Close();\n    }	0
2675111	2675035	regex matches with intersection in C#	string input = "a a a";\nRegex regexObj = new Regex("a a");\nMatch matchObj = regexObj.Match(input);\nwhile (matchObj.Success) {\n    matchObj = regexObj.Match(input, matchObj.Index + 1); \n}	0
4598485	4598431	Using LINQ to get items from same collection where numbers are logical following	IEnumerable<int> items = //whatever\nvar pairs = items.Zip(items.Skip(1), (f, s) => Tuple.Create(f, s))\n    .Where(t => t.Item1 + 1 == t.Item2);	0
31641112	31640835	Use of LINQ to select a subset of option chains	decimal margin = 5.99m; // set it programatically, I made it 5.99 because of the underlying_price value in your JSON\ndecimal underlying_price = Decimal.Parse(data.underlying_price);\nvar pairs = data.puts.Join(data.calls, put => put.strike, call => call.strike, (put, call) =>\n    new OptionPair\n    {\n        Call = call,\n        Put = put,\n        Expiry = DateTime.Parse(call.expiry), // or from put, this is kind of ugly - the dates theoretically can be different\n        Strike = Decimal.Parse(call.strike), // or rom call\n    }).Where(pair => Math.Abs(pair.Strike - underlying_price) < margin);	0
3878264	3878148	Correct Process for Routing with Admin Subsite	/Areas\n    /Admin\n        /Controllers\n            NewsController.cs\netc.	0
15124072	15120855	Parsing Resx file with C# crashes on relative paths	try\n{\n    XDocument xDoc = XDocument.Load(resxFile);\n\n    var result = from item in xDoc.Descendants("data")\n    select new\n    {\n        Name = item.Attribute("name").Value,\n        Value = item.Element("value").Value\n    };\n\n    resxGrid.DataSource = result.ToArray();           \n}	0
21328230	21327918	Unity3D - get component	if(gamemaster.GetComponent<MainGameLogic>().backfacedisplayed==true)\n    {\n        gamemaster.GetComponent<MainGameLogic>().BackfaceDisplay();\n    }	0
180558	180452	How do I set a click event for a form?	Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded\n\n    AddHandler e.Control.MouseClick, AddressOf Example_MouseClick\nEnd Sub\n\nPrivate Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick\n    MessageBox.Show("Click")\nEnd Sub	0
17266090	17265933	Algorithm for filtering top-level directories among a list of paths, C#	string inputDir = "/dir1/subdir/sub-subdir";\nstring [] Split = inputDir.Split(new Char [] {'/'}, StringSplitOptions.RemoveEmptyEntries); \nstring outputDir = Split[0];	0
7517011	7516311	Replace continuous space with single space and multiple "&nbsp" elements	string str = "<B>This is          Whitespace      Node </B>";\nRegex rgx = new Regex("([\\S][ ])");\nstring result = rgx.Replace(str, "$1.")\n                        .Replace(" .","?")\n                        .Replace(" ","&nbsp")\n                        .Replace("?"," ");	0
19165415	19162661	How to return from WCF service event per session to my main form	public class MyFormFunctions\n{\n    public static job_Event(Job obj)\n    {\n         /// do something to form\n    }\n}\n        public string startProcess(string str)\n        {\n            Job job = new job();            \n            MyFormFunctions.job_Event(job);\n\n        }	0
26695154	26695130	Linq search from comma separated string to double	if (!String.IsNullOrEmpty(searchItemcode))\n{\n    var itemList = searchItemcode.Split(',').Select(p => double.Parse(p.Trim()));\n    priceHistory = priceHistory.Where(s => itemList.Contains(s.ITEM_CODE));\n}	0
18579746	11947562	iTextSharp: Set different border size for 2 tables	//my first tabe\nstrHTMLContent.Append("<table width='100%' border='1'>");\n\n//the 2nd table that I don't want to have border\nstrHTMLContent.Append("<table border='0'>");	0
23924227	23923816	How to Customize Exported Excel from Console Application?	SqlDataReader dr = cmd.ExecuteReader();\nsw.WriteLine("LocalSKU\tItemName\tPrice\tPrice2\tCost\tSupplierName\tSupplierSKU");\nwhile (dr.Read())\n{\n    sw.WriteLine(dr["LocalSKU"].ToString() + "\t" + dr["ItemName"].ToString() + "\t" + dr["Price"].ToString() + "\t" + dr["Price2"].ToString() + "\t" + dr["Cost"].ToString() + "\t" + dr["SupplierName"].ToString() + "\t" + dr["SupplierSKU"].ToString());\n}	0
12012515	12012262	How to refresh the UI of a Metro Style app?	private async void Button_Click(object sender, RoutedEventArgs e)\n{\n    btnStatus.Content = "Test started";\n    await Task.Delay(3000); // Wait 3 seconds\n    btnStatus.Content = "Test Ended"\n}	0
29569738	29568844	Decoding \\uXXXX characters	Console.WriteLine	0
16113861	16113615	Access UserProfile from a controller MVC 4	[HttpPost]\npublic ActionResult Create(Character character)\n{\n    if (ModelState.IsValid)\n    {\n        character.user = db.UserProfiles.Find(u => u.UserID = (int) Session["UserID"]); \n\n        db.Characters.Add(character);\n        db.SaveChanges();\n    ...\n}	0
15258643	15258263	How to change ILoggerFacade implementation to trace caller method using CallerMemberName attribute?	public interface ILoggerFacade\n{\n    void Log(string message, Category category, \n             Priority priority, [CallerMemberName] string callerMethod = "");\n}	0
729316	729295	How to cast Expression<Func<T, DateTime>> to Expression<Func<T, object>>	using System;\nusing System.Linq.Expressions;\n\nclass Test\n{\n    // This is the method you want, I think\n    static Expression<Func<TInput,object>> AddBox<TInput, TOutput>\n        (Expression<Func<TInput, TOutput>> expression)\n    {\n        // Add the boxing operation, but get a weakly typed expression\n        Expression converted = Expression.Convert\n             (expression.Body, typeof(object));\n        // Use Expression.Lambda to get back to strong typing\n        return Expression.Lambda<Func<TInput,object>>\n             (converted, expression.Parameters);\n    }\n\n    // Just a simple demo\n    static void Main()\n    {\n        Expression<Func<string, DateTime>> x = text => DateTime.Now;\n        var y = AddBox(x);        \n        object dt = y.Compile()("hi");\n        Console.WriteLine(dt);\n    }        \n}	0
31195368	31195178	How to do a nested select in where clause, in LINQ?	... select cri.TaxFormID).FirstOrDefault()	0
7408581	7408560	Linq: Getting a List<String> from List<Customer> based on customer.name	List<string> names = custs.Select(x=>x.Name).ToList();	0
31036890	31036551	Trouble with infinite loop	UserOption = GetOptionFromUser();	0
10529411	10528775	How to add a menu item to Excel 2010 Cell Context Menu - old code doesn't work	//reset commandbars\nApplication.CommandBars["Cell"].Reset();	0
2592720	2592653	Trying to create a .NET DLL to be used with Non-.NET Application	namespace AESEncryption\n{\n    [Guid("[a new guid for the interface]")]\n    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n    public interface IEncrypt        {\n        string Encrypt(string data, string filePath);\n    }\n\n    [Guid("[a new guid for the class]")]\n    [ComVisible(true)]\n    [ClassInterface(ClassInterfaceType.None)]\n    public class EncryptDecryptInt : IEncrypt\n    {\n        public string Encrypt(string data, string filePath)\n        {\n            // etc.\n        }\n    }\n}	0
8053226	8053191	How do I convert a string into a byte array in C#?	Encoding.UTF8.GetBytes(string)	0
13883426	13883365	Creating List that contains only one of each entry	be.TblUNotes\n  .Where(a => a.Quarter == Q && a.Year == Y)\n  .GroupBy(m => m.SubId)\n  .Select(g => g.FirstOrDefault())//or g.OrderBy(m => m.Data).FirstOrDefault(), for example, I don't know which item you wanna take\n  .ToList();	0
31726215	31726104	C# Ping - how many attempts?	Ping.Send()	0
3807646	3807629	How to parse html and return array of values in c# using regex.split	HtmlDocument doc = new HtmlDocument();\ndoc.Parse(str);\n\nIEnumerable<string> cells = doc.DocumentNode.Descendants("td").Select(td => td.InnerText);	0
586629	586525	Listbox Scrollbar customization in WPF	1. Right click your ListView\n2. Select "Edit Control Parts --> Edit a copy"\n3. Now right click the ScrollViewer in "Objects and Timeline"\n4. Select "Edit Control Parts --> Edit a copy" again\n5. Now you're editing a template for the ScrollViewer and you can play\n   with the size of the VerticalScrollBar	0
23058373	23057872	C# OpenXML image in center	wordDoc.MainDocumentPart.Document.Body.AppendChild(\n    new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)) \n    { \n        ParagraphProperties = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties() \n        { \n            Justification = new DocumentFormat.OpenXml.Wordprocessing.Justification() \n            { \n                Val = DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center \n            } \n        } \n    });	0
27164534	27164266	XNA - Make sprite unable to go out of borders	if(Mouse.GetState().X > 0 && Mouse.GetState().X < yourWindowWidth)            \n    spritePosition.X = Mouse.GetState().X;\nelse if (Mouse.GetState().X < 0)\n    spritePosition.X = 0;\nelse                   //The mouse is out from the right side of the window.\n    spritePosition.X = yourWindowWidth;\nif(Mouse.GetState().Y > 0 && Mouse.GetState().Y < yourWindowHeight)\n    spritePosition.Y = Mouse.GetState().Y;\nelse if (Mouse.GetState().Y < 0)\n    spritePosition.Y = 0;\nelse                   //The mouse is out from the bottom side of the window.\n    spritePosition.Y = yourWindowHeight;	0
6619871	6464591	Space bar key press validation for text box with tinyMCE editor	if (Textbox1.Text.Replace("&nbsp;", "").Replace("<br />", "").Trim().Length <= 0)\n{\n    //Statement here\n}	0
26754487	26754330	Find the item with the lowest value of a property within a list	Person minIdPerson = persons[0];\nforeach (var person in persons)\n{\n    if (person.ID < minIdPerson.ID)\n        minIdPerson = person;\n}	0
8942469	8942313	Command prompt hide/remove while taking screen shot	myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;	0
31189181	31189071	Unload Assemblies loaded by Ninject	Kernel.Release	0
25163140	25159315	WCF with windows authentication problems	var proxy = new MyServiceClient();\nproxy.ClientCredentials.Windows.ClientCredential.Domain = "MyDomain";\nproxy.ClientCredentials.Windows.ClientCredential.UserName = "MyUsername";\nproxy.ClientCredentials.Windows.ClientCredential.Password = "MyPassword";\nproxy.DoSomething();\nproxy.Close();	0
11030575	11030410	Combine Two Lists of Dictionaries	var finalList = list1.Union(list2).ToList();	0
9487137	9129377	Magento - salesOrderShipmentList by order_increment_id	private void GetShipments()\n    {\n        // Create the filter array\n        filters theFilters = new filters();\n\n        // get the order's id from its incrementId\n        salesOrderEntity theOrder = this.mageObject.MageService.salesOrderInfo(this.mageObject.MageSessionId, this.Session["orderID"] as string);\n\n        // Create the "C#" version of the associative array using a generic list\n        List<associativeEntity> theEntities = new List<associativeEntity>\n            {\n                new associativeEntity { key = "order_id", value = theOrder.order_id } \n            };\n\n        // Make the generic list back into an array\n        theFilters.filter = theEntities.ToArray();\n\n        // Here are your sales orders\n        salesOrderShipmentEntity[] x =\n            this.mageObject.MageService.salesOrderShipmentList(this.mageObject.MageSessionId, theFilters);	0
18340204	18340046	Passing parameter to a function in C#	private void Output(Person p)\n{\n     idBox.Text = p.id;\n     fnameBox.Text = p.name;\n     lNameBox.Text = p.lName;\n}	0
4106313	4106287	How do I use the Aggregate function to take a list of strings and output a single string separated by a space?	string.Join	0
25124762	25025690	WPF - Focus Control Within DataTemplate applied to FlyoutControl	private void TextThatWantsFocus_Loaded(object obj, RoutedEventArgs e)\n{\n    var text = obj as FrameworkElement;\n    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(delegate()\n        { text.Focus(); }));\n}	0
9568282	9566896	binding data in asp.net treeview control?	da.Fill(ds,"Table1");\nda.Fill(ds,"Table2");	0
26402820	26402605	How do I map complex json to model in ASP.Net MVC	public class QuestionTemplateModel\n{\n    [BsonId]\n    [BsonRepresentation(BsonType.ObjectId)]\n    public string Id { get; set; }\n    public string Name { get; set; }\n    public string MathML { get; set; }\n    public string Expression { get; set; }\n    public string QType { get; set; }\n    public Dictionary<string, VariableDetails> Rules = new Dictionary<string, VariableDetails>() { get; set; }\n\n}\n\n\n\npublic class VariableDetails\n{\n    public string variableType { get; set; }\n    public string min { get; set; }\n    public string max { get; set; }\n}	0
11357015	11356895	Linq to XML - Find an element	var relatedDocs = doc.Elements("Document")\n   .Where(x=>x.Element("GUID").Value == givenValue)\n   .Where(x=>!x.Element("IndexDatas")\n              .Elements("IndexData")\n              .Any(x=>x.Element("Name") == someValue);	0
7451783	7451764	Selecting from one sequence based on a filter on a second sequence	var filtered = outer\n       .Zip(inner, (o, i) => new {Outer = o, Inner = i})\n       .Where(pair => outerFilter(pair.Outer))\n       .Select(pair => pair.Inner);	0
6442865	6442215	Replace images with alternate text html agility pack	var images = doc.DocumentNode.SelectNodes("//img");\nif (images != null)\n{\n    foreach (HtmlNode image in images)\n    {\n        var alt = image.GetAttributeValue("alt", "");\n        var nodeForReplace = HtmlTextNode.CreateNode(alt);\n        image.ParentNode.ReplaceChild(nodeForReplace, image);\n    }\n}\n\nvar sb = new StringBuilder();\nusing (var writer = new StringWriter(sb))\n{\n    doc.Save(writer);\n}	0
12419743	12419107	WCF pub-sub model, Invoking Subscribers all at once	Parallel.ForEach(subscribers.ToArray(), subscriber =>\n{\n    try\n    {\n        object ClientResult;\n        ClientResult = publishMethodInfo.Invoke(\n            subscriber.CallBackId, new object[] { ClData });\n    }\n    ...\n});	0
32456354	32456006	Display the values in Datatable with Two decimal places to looks like time Format	decimal a = 5;\ndecimal b = 6;\n\nConsole.WriteLine(string.Format("{0:#,###.00}, {1:#,###.00}", a , b));	0
6646306	6646185	Filter data from an XML document	var s = @"\n                <JamStatus>\n<IPAddress Value=""10.210.104.32 "" FacId=""2"">\n<Type>Letter</Type>\n<JobId>1</JobId>\n<fi>50-30C-KMC-360A</fi>\n<TimestampPrinting>1309464601:144592</TimestampPrinting>\n</IPAddress>\n<IPAddress Value=""10.210.104.32 "" FacId=""2"">\n<Type>Letter</Type>\n<JobId>2</JobId>\n<fi>50-30C-KMC-360A</fi>\n<TimestampPrinting>1309465072:547772</TimestampPrinting>\n</IPAddress> \n<IPAddress Value=""10.210.104.32 "" FacId=""2"">\n<Type>Letter</Type>\n<JobId>2</JobId>\n<fi>50-30C-KMC-360A</fi>\n<TimestampPrinting>1309465072:547772</TimestampPrinting>\n</IPAddress>  \n</JamStatus>";\n\n            XElement xel = XElement.Parse(s);\n\n            Console.WriteLine(xel.XPathSelectElements("//IPAddress")\n                .GroupBy(el => new Tuple<string, string>(el.Element((XName)"JobId").Value, el.Element((XName)"TimestampPrinting").Value))\n                .Max(g => g.Count())\n            );	0
24835899	24835614	Many to many relationships - Sql To Linq	var res = from source in UserTask\n          join target in UserTask on source.TaskId equals target.TaskId\n         where source.UserId == 2\n            && target.UserId == 1\n       orderby source.TaskId\n        select source.TaskId;	0
27592541	27592400	Find all occurrences of a pattern whether they overlap or not	var regX = new Regex(@"\w\w\w.\w?");\nstring pattern = "dog cat fun toy";\n\nint i = 0;\nwhile (i < pattern.Length)\n{\n    var m = regX.Match(pattern, i);\n    if (!m.Success) break;\n\n    Console.WriteLine(m.Value);\n    i = m.Index + 1;\n}	0
27128673	27128517	Reading a website using C# Agility Pack from a proxied server application hosted in IIS 7	var request = WebRequest.Create("http://foo.bar/file.doc");\nrequest.Credentials = new System.Net.NetworkCredential("username", "password");	0
10377736	10376928	When I output a string into a checked list box in windows forms only the first line of the string is shown next to the checkbox	this.checkedListBoxTasks.Items.Add(this.textBoxTask.Text);\nthis.checkedListBoxTasks.Items.Add(this.textBoxDescription.Text);\nthis.checkedListBoxTasks.Items.Add(this.textBoxDueDate.Text);	0
10835631	10835544	Linq To Sql: Retrieving a parent entity without the children attached	DataContext.DeferredLoadingEnabled	0
13625951	13528431	Sitecore: Assign workflow to an item programmatically	newItem.Editing.BeginEdit();                    \nnewItem.Fields["__Workflow"].Value = "{4D1F00EF-CA5D-4F36-A51E-E77E2BAE4A24}"; //Set workflow\nnewItem.Fields["__Workflow state"].Value = "{7F39DF46-B4B9-4D08-A0D4-32DE6FD643D1}"; //Set   workflow state to Unposted.\nnewClassified.Editing.EndEdit();	0
4681085	4681023	WP7 - read from CSV file? Or what to do with the data?	string csv = "abc,123,def,456";\nstring[] elements = csv.Split(',');\nforeach (string s in elements)\n    System.Diagnostics.Debug.WriteLine(s);	0
12394921	12394884	need get unique set of keys from Multiple dictionaries<Datetime,double>	dicts.SelectMany(d => d.Keys).Distinct().ToArray();	0
28402835	28402337	ZedGraph - How to hardcode axis value?	string[] labels = new string[48];\nfor(int i=0; i<24; i++)labels[i] = ""+i;\nfor(int i=0; i<24; i++)labels[i] = ""+(i+24);\nZedGraph.ZedGraphControl.GraphPane.XAxis.Type = AxisType.Text\nZedGraph.ZedGraphControl.GraphPane.XAxis.Scale.TextLabels = labels;	0
1964002	1963993	Getting the integer value from enum	var number = (int)((game) Enum.Parse(typeof(game), pick));	0
17984885	17980606	How to smoothly navigate to a different panorama item	SlideTransition slideTransition = new SlideTransition();\nslideTransition.Mode = SlideTransitionMode.SlideRightFadeIn;\nITransition transition = slideTransition.GetTransition(panorama_main);\ntransition.Completed += delegate\n{\n    transition.Stop();\n};\nPanoramaItem pItem = (PanoramaItem)panorama_main.Items[3];\npanorama_main.DefaultItem = pItem; \ntransition.Begin();	0
17553176	17553111	Casting int array to object array	System.Int32	0
10150870	10150807	Copy properties of one object to another object with same base	public partial class DanubeDataSet \n{\n    partial class ProductsRow\n    {\n        public decimal TotalCost\n        {\n            get\n            {\n                return Quantity * Price;\n            }\n        }\n    }\n}	0
29628893	29628567	how to validate a textbox for specific pattern in Windows form c#	private void CheckInput(object sender, KeyPressEventArgs e)\n{\n    // Make sure only digits, . and + \n    if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '+')\n    {\n        e.Handled = true;\n    }\n    // Make sure . is in correct places only\n    else if (e.KeyChar == '.')\n    {\n        for (int i = textBox1.SelectionStart - 1; i >= 0; i--)\n        {\n            if (textBox1.Text[i] == '.')\n            {                       \n                e.Handled = true;\n                break;\n            }\n            else if (textBox1.Text[i] == '+') break;\n        }\n    }\n    // Make sure character before + is a digit\n    else if (e.KeyChar == '+' \n        && !char.IsDigit(textBox1.Text[textBox1.SelectionStart - 1]))\n    {\n        e.Handled = true;\n    }\n}	0
12516306	12516048	What do you suggest I use for statically creating a collection of string values?	public static class DefinedRoles\n{\n    public const string Accounting = "Regular User, Accounting, Administrator";\n}	0
12251956	12251910	C# Dynamically Get Variable Names and Values in a Class	var dict = typeof(Settings)\n    .GetFields(BindingFlags.Static | BindingFlags.Public)\n    .ToDictionary(f=>f.Name, f=>f.GetValue(null));	0
933698	933687	Read XML Attribute using XmlDocument	XmlNodeList elemList = doc.GetElementsByTagName(...);\n    for (int i = 0; i < elemList.Count; i++)\n    {\n        string attrVal = elemList[i].Attributes["SuperString"].Value;\n    }	0
16142565	15809424	json parameter to request on Windows 8 (RT)	public static async Task<string> LoadData(string json, string serverUrl)  \n{\n    var request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.LocalServer));\n    request.ContentType = "application/json";\n    request.Method = "POST";\n\n    using (var requestStream = await request.GetRequestStreamAsync())\n    {\n        var writer = new StreamWriter(requestStream);\n        writer.Write(json);\n        writer.Flush();\n    }\n\n    using (var resp = await request.GetResponseAsync())\n    {\n        using (var responseStream = resp.GetResponseStream())\n        {\n            var reader = new StreamReader(responseStream);\n            return  = reader.ReadToEnd();\n        }\n    }\n}	0
15102149	15101915	How to add date objects to C# lists?	var mealList = new List<Meals>\n{\n     new Meals { Start = dtmealStart1, End = dtmealStart1 },\n     /* Repeat for the rest of them possibly incorporating some kind of loop to generate this list */\n};\n\n//and then get your sorted list\nvar sortedMealList = mealList.OrderBy(m => m.Start);	0
30811276	30809812	How get value from JSON string?	var photo = wall[0].Attachments[0].Instance as Photo\nif (photo != null)\n    var uri = photo.Photo604	0
27575184	27575009	Syntax error when inserting many columns into MySQL	string cmdText = @"INSERT INTO animes\n                  (JapanTitle,AmericanTitle,GermanTitle,AnimeType,.....)\n                  VALUES(@japtitle, @usatitle, @germantitle, @animtype, ....)";\nMySqlCommand cmd = new MySqlCommand(cmdText, connection);\ncmd.Parameters.AddWithValue("@japtitle",  entity.JapanTitle);\ncmd.Parameters.AddWithValue("@usatitle",  entity.AmericanTitle);\ncmd.Parameters.AddWithValue("@germantitle",  entity.GermanTitle);\ncmd.Parameters.AddWithValue("@animtype",  entity.AnimeType);\n....\ncmd.ExecuteNonQuery();	0
20341619	20341437	How to Execute Update SQL Script in ASP.Net	SqlConnection sqlConnection = new SqlConnection();\nSqlCommand sqlCommand = new SqlCommand();\nsqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";\n\npublic void samplefunct(params object[] adparam)\n   {\n       sqlConnection.Open();\n       sqlCommand.Connection = sqlConnection;\n       sqlCommand.CommandType = CommandType.StoredProcedure;\n       sqlCommand.CommandText = "SPName";\n\n       sqlCommand.Parameters.Add("@param1", SqlDbType.VarChar).Value = adparam[0];\n       sqlCommand.Parameters.Add("@param2", SqlDbType.VarChar).Value = adparam[1];\n       sqlCommand.Parameters.Add("@Param3", SqlDbType.VarChar).Value = adparam[2];\n       sqlCommand.ExecuteNonQuery();\n}	0
9839443	9824955	How to force grid to propagate value to datasource immediately on change?	private void OnCellValueChanging(object sender, CellValueChangedEventArgs e)\n    {\n        _gridView.SetFocusedRowCellValue(_gridView.FocusedColumn, e.Value);\n    }	0
9843768	9840833	Implementing a DSL on .NET	System.Reflection.Emit	0
5882913	5882815	How to create a Bitmap deep copy	B.Clone(new Rectangle(0, 0, B.Width, B.Height), B.PixelFormat)	0
15074704	15074656	How to identify object calls to parent functions	string type = objb.GetType().Name; //will be "B"	0
9527635	9527087	What's wrong with this linq? trying to make an IN clause	var gestiones = (from G in db.Gestion select new GestionesDataSet()\n        {\n           GestionInicio = G.HoraInicio,\n           GestionFin = G.HoraFin,\n           @Tipificacion = ((from T in db.Tipificacion select T).Where( x => x.IdTipificacion == G.IDTipificacion).Count() > 0 ?\n                            (from T in db.Tipificacion where T.IdTipificacion == G.IDTipificacion select T.Nombre).FirstOrDefault() : ""),\n           LlamadaInicio = G.Llamada.HoraInicio,\n           LlamadaFin = G.Llamada.HoraFin,\n           Login = G.Llamada.Sesion.Usuario.Nombre\n        }).ToList();	0
25072013	25045541	Dynamic select sentence with LINQ - Join 2 DataTables	IQueryable linqData = (from row1 in dtMain.AsEnumerable()\n                       join row2 in dtSec.AsEnumerable()\n                       on row1.Field<Object>("frameworkIdTemporal1") equals row2.Field<Object>("frameworkIdTemporalSec1")\n                       into result\n                       from subRight in result.DefaultIfEmpty()\n                       select\n                       new { row1, row3 = (subRight == null) ? (dtSec.NewRow()) : subRight })\n                       .AsQueryable().Select(strSelect);	0
2665240	2665223	get username from Webservice	Context.Request.ServerVariables["LOGON_USER"]	0
11227733	11226789	C# COM Add In failing while calling from thread	Marshal.GetActiveObject	0
4343256	4337912	How to convert unpacked decimal back to COMP-3?	String sign = "c";\nif (value < 0) {\n    sign = "d";\n    value = -1 * value;\n}\nString val = value + "d"\n\nbyte[] comp3Bytes = new BigInteger(val, 16).toByteArray();	0
11428221	11427996	How to query data from entity object along with ICollection data	var DrinkedCoffies = ctx.CoffeeUsers.SelectMany(u => u.DrinkedCoffees, (u, cof) => new { FirstName = u.FirstName, LastName = u.LastName, DateDrinked = cof.DateDrinked } );	0
21874370	21874282	Not a valid win32 application while launching the installer	async/await	0
3381313	3381270	Loading textures using TextureLoader from Resources	texture = new Bitmap(Properties.Resources.image);	0
22299480	22299299	How to declare Exchange Web Service	// Identify the service binding and the user.\nExchangeServiceBinding service = new ExchangeServiceBinding();\nservice.RequestServerVersionValue = new RequestServerVersion();\nservice.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;\nservice.Credentials = new NetworkCredential("<username>", "<password>", "<domain>");\nservice.Url = @"https://<FQDN>/EWS/Exchange.asmx";	0
25442371	25403489	Postsharp OnMethodBoundryAspect on interface implementation	public SomeObject GetSomething(){\n    MethodExecutionArgs methodExecutionArgs = new MethodExecutionArgs(null, null);\n\n    /* original method code here */ \n\n    methodExecutionArgs.ReturnValue = returnValue;\n    <>z__a_1.a0.OnSuccess(methodExecutionArgs);\n    return (SomeObject)methodExecutionArgs.ReturnValue;\n}	0
16803988	16803675	Mapping two lists of characters to make them reciprocal	string,string	0
2241711	2241594	C# - fastest way to compare two strings using wildcards	if (mask[index]!= word[index])) && (mask[index] != ' ')	0
21211081	21211032	ASCII converter without system.text library in C#	var byteArray = dataString.Select(x => (byte)x).ToArray();	0
8849798	8849001	Using a .Net DLL in Microsoft Access VBA	Private Sub btnMain_Click()\n\n    Dim tm As TestDLL.Class1\n    Dim foo As String\n\n    Set tm = New TestDLL.Class1\n    foo = tm.testMethod\n\n    lblBarr.Caption = foo\n\nEnd Sub	0
32464428	32458987	assign one of the cut images to a sprite renderer	Sprite[] allSprites = Resources.LoadAll<Sprite>("mySprite");  \nGetComponent<SpriteRenderer>().sprite = allSprites[0];	0
491916	491563	Implementing filters for a SQL table display on a view in ASP.NET MVC (C#) and LINQ-to-SQL?	public ActionResult Open(string sort, string technician, \n    string category, string priority)\n{\n    // generate query\n    // filter stuff\n    // order/sort stuff\n}	0
1836709	1832428	Possible authentication problem? Loading a JSON via WebClient in Silverlight 4	private void beginGet(string endpoint, OpenReadCompletedEventHandler callback)\n{\n  WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);  \n  WebClient wc = new WebClient();  \n  wc.Credentials = new NetworkCredential(username, password);\n  wc.UseDefaultCredentials = false; \n  wc.OpenReadCompleted += callback;  \n  wc.OpenReadAsync(new Uri(baseURL + endpoint));\n}	0
25817958	25798770	Dynamic Invocation of WCF Service Using Reflection	...\n...\n        WsdlImporter importer = new WsdlImporter(metaSet);\n\n        //BEGIN INSERT\n        XsdDataContractImporter xsd = new XsdDataContractImporter();\n        xsd.Options = new ImportOptions();\n        xsd.Options.ImportXmlType = true;\n        xsd.Options.GenerateSerializable = true;\n        xsd.Options.ReferencedTypes.Add(typeof(KeyValuePair<string, string>));\n        xsd.Options.ReferencedTypes.Add(typeof(System.Collections.Generic.List<KeyValuePair<string, string>>));\n\n        importer.State.Add(typeof(XsdDataContractImporter), xsd);\n        //END INSERT\n\n        Collection<ContractDescription> contracts = importer.ImportAllContracts();\n...\n...	0
24192594	24192249	App capability removed after pubblication	WebBrowser w = new WebBrowser();	0
5843080	5842961	How to navigate after callling async web method completed?	private void _ws_InitializeConnexionCompleted(object sender, InitializeConnexionCompletedEventArgs e)\n {\n        if (e.Error != null)\n        {\n            this.Member = e.Result;\n            this.Navigate("/View/profile.xaml");\n        }\n        else\n        {\n            MessageBox.Show("error.");\n        }\n    }\n}\n\nprotected void Navigate(string address)\n{\n    if (string.IsNullOrEmpty(address))\n          return;\n\n    Uri uri = new Uri(address, UriKind.Relative);\n    Debug.Assert(App.Current.RootVisual is PhoneApplicationFrame);\n    ((PhoneApplicationFrame)App.Current.RootVisual).Navigate(uri);            \n}	0
5518632	5518404	How to get the stream for a template on a Document Library	web.GetFile(templetAddr).OpenBinaryStream()	0
16821340	16820922	LINQ join on a subquery with a union	on loctab.empID equals mstr.prem_emp\nselect //... perform your select on the unioned tables.	0
8408566	8408525	Adding a week to a date time picker	private void AddDaysToDatePicker(int days, DateTimePicker startDTP, DateTimePicker endDTP)\n{\n    endDTP.value = startDTP.Value.AddDays(days);\n}	0
3509093	3509071	How to alias fields from a DataTable in LINQ?	var output = dataTable.Rows.Cast<DataRow>().Select(r => new \n    {\n       alias1 = r["Column1"].ToString(),\n       alias2 = r["Column2"].ToString(),\n       alias3 = r["Column3"].ToString(),\n       /// etc...\n    });	0
6902846	6902745	Capture return code of Console application in VBscript?	exitcode = WshShell.Run(strCommand, , true])	0
9866578	9866520	How do I populate a list of Images from a directory?	string directory = @".\card_images\";\nList<Image> HandCards = new List<Image>();\nforeach (string myFile in\n          Directory.GetFiles(directory, "*.png", SearchOption.AllDirectories))\n{\n    Image image = new Image();\n    BitmapImage source = new BitmapImage();\n    source.BeginInit();\n    source.UriSource = new Uri(myFile, UriKind.Relative);\n    source.EndInit();\n    image.Source = source;\n\n    HandCards.Add(image);\n}	0
13060556	13052167	Using Accord.Net's Codification Object to Codify second data set	// Compute the result for a sunny, cool, humid and windy day:\ndouble[] input = codebook.Translate("Sunny", "Cool", "High", "Strong").ToDouble(); \n\nint answer = target.Compute(input);\n\nstring result = codebook.Translate("PlayTennis", answer); // result should be "no"	0
748354	292756	How to prevent ASP.NET 3.5 SP1 from overriding my action?	public class HtmlFormAdapter : ControlAdapter \n{\n    protected override void Render(HtmlTextWriter writer)\n    {\n        HtmlForm form = this.Control as HtmlForm;\n\n        if (form == null)\n        {\n            throw new InvalidOperationException("Can only use HtmlFormAdapter as an adapter for an HtmlForm control");\n        }\n        base.Render(new CustomActionTextWriter(writer));\n    }\n\n\n    public class CustomActionTextWriter : HtmlTextWriter\n    {\n        public CustomActionTextWriter(HtmlTextWriter writer) : base(writer)\n        {\n            this.InnerWriter = writer.InnerWriter;\n        }\n\n        public override void WriteAttribute(string name, string value, bool fEncode)\n        {\n            if (name == "action")\n            {\n                value = "";\n            }\n            base.WriteAttribute(name, value, fEncode);      \n        }\n    }\n}	0
18551828	18551686	How do you get host's broadcast address of the default network adapter? C#	using System;\nusing System.Net.NetworkInformation;\n\npublic class test\n{\n public static void Main()\n {\n  NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();\n  foreach(NetworkInterface Interface in Interfaces)\n  {\n   if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;\n   if (Interface.OperationalStatus != OperationalStatus.Up) continue;\n   Console.WriteLine(Interface.Description);\n   UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;\n   foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)\n   {\n    Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);\n    Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);\n   }\n  }\n }\n}	0
2886567	2886532	In C#, how do you send a refresh/repaint message to a WPF grid or canvas?	public static class ExtensionMethods\n{\n   private static Action EmptyDelegate = delegate() { };\n\n   public static void Refresh(this UIElement uiElement)\n   {\n      uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);\n   }\n}	0
31854592	31854474	change format of datetime.now	var dt = DateTime.Now;\nusers.userlast = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);	0
10505999	10505952	C#: How to form a correct MySQL connection string?	MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();\nconn_string.Server = "mysql7.000webhost.com";\nconn_string.UserID = "a455555_test";\nconn_string.Password = "a455555_me";\nconn_string.Database = "xxxxxxxx";\n\nusing (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))\nusing (MySqlCommand cmd = conn.CreateCommand())\n{    //watch out for this SQL injection vulnerability below\n     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",\n                                    OSGconv.deciLat, OSGconv.deciLon);\n     connection.Open();\n     cmd.ExecuteNonQuery();\n}	0
15394078	15393877	The Data Bound ComboBox doesn't update until the application is restarted	public void LoadCb()\n{\n    SqlConnection cn = new SqlConnection("connectionstring");\n    SqlDataAdapter da = new SqlDataAdapter("select DealerId, DealterName from Dealers", cn);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n    comboBox1.DataSource = dt;\n    comboBox1.DisplayMember = "DealerName";\n    comboBox1.ValueMember = "DealerId";\n}	0
18934936	18934722	Setting wallpaper programmatically always tiling image	rkWallPaper.SetValue("WallpaperStyle", "2");\n  rkWallPaper.SetValue("TileWallpaper", "0");	0
16718724	16718030	Efficient way to unindent lines of code stored in a string	static IEnumerable<string> UnindentAsMuchAsPossible(IEnumerable<string> input)\n{\n    const int TabWidth = 4;\n\n    if (!input.Any())\n    {\n        return Enumerable.Empty<string>();\n    }\n\n    int minDistance = input\n        .Where(line => line.Length > 0)\n        .Min(line => line\n            .TakeWhile(Char.IsWhiteSpace)\n            .Sum(c => c == '\t' ? TabWidth : 1));\n\n    return input\n        .Select(line => line.Replace("\t", new string(' ', TabWidth)))\n        .Select(line => line.Substring(Math.Min(l.Length, minDistance));\n}	0
15707227	15699366	How to retrieve the NAME and ID attibute values that ASP.NET MVC would use when building an HTML control for a model property	public static string FullHtmlNameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n    {\n        if (htmlHelper == null) { throw new ArgumentNullException("htmlHelper"); }\n        if (expression == null) { throw new ArgumentNullException("expression"); }\n\n        return htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));\n    }	0
8228138	8228014	Recursive loop missing the first value in c#	private DataSet BindGridView(int id, List<int> userids)\n{\n    string GetOrgIDs = "select OrganisationID from tbl_organisation where ParentID =@ParentID";\n    MySqlParameter[] paramet = new MySqlParameter[1];\n    paramet[0] = new MySqlParameter("@ParentID", MySqlDbType.Int32);\n    paramet[0].Value = id;\n    List<int> children = new List<int>(); // new local list\n    MySqlDataReader reader = server.ExecuteReader(CommandType.Text, GetOrgIDs, paramet);\n    while (reader.Read())\n    {\n        int orgid = Convert.ToInt32(reader["OrganisationID"]);\n        userids.Add(orgid);\n        children.Add(orgid);  // also add to local list\n    }\n    reader.Close();\n\n    foreach(int child in children)\n    if (child != 0)\n    {\n        BindGridView(child, userids);\n    }\n}	0
30238911	30238715	Unit-Test a function	[TestMethod]\npublic void GetInfo_ClonesAllProperties()\n{\n    // arrange\n    var myClass = new myClass() { FirstName = "John", SurName = "Smith" };\n\n    // act\n    var clone = myClass.GetInfo();\n\n    // assert\n    Assert.AreEqual(clone.FirstName,"John");\n    Assert.AreEqual(clone.SurName,"Smith");\n}	0
21816059	21815970	XML Multiple attributes	var points = XDocument.Load(filename)\n            .Descendants("Point")\n            .Select(p => new Point((int)p.Attribute("x"), (int)p.Attribute("y")))\n            .ToList();	0
15002160	14956240	How to filter the list using another list?	List<Employee> filteredRecords = (from a in EmployeeList join b in selectedEmployeeIds on a.ID equals b select a).ToList();	0
6544589	6544548	How To Add In List Array Using Loop I am Getting Error?	List<double> res = new List<double>();             \nfor(int a=0;a<_dt.Rows.Count;a++) {\n    double PW =Convert.ToDouble(_dt.Rows[a]["POWER"]);             \n    int VOL =Convert.ToInt32(_dt.Rows[a]["VOLTAGE"]);             \n    double PV = PW * VOL;             \n    res.Add(PV);         \n}	0
7180130	7180063	C# one-liner to grab specific data from an RSS feed	SyndicationFeed.Load(XmlReader.Create("http://weblogs.asp.net/scottgu/rss.aspx")).Items.Count();	0
20982844	19587733	Npgsql and update data in gridview	public partial class Secured_pia : System.Web.UI.Page\n    {\n        String sConn = "Your connection string";\n        private NpgsqlConnection conn;\n        private NpgsqlDataAdapter da;\n        private DataSet ds = new DataSet();\n        private DataTable dt = new DataTable();\n        private NpgsqlCommandBuilder cb;\n\n        public Secured_pia ()\n        {\n            InitializeComponent();\n        }\n//your form load code above goes here but you will have to do \n//a global declaration like I did here instead of in the form load event like you have. \n\n//update button implementation.  \nprivate void btnUpdate_Click(object sender, EventArgs e)\n {\n    cb = new NpgsqlCommandBuilder(da);           \n    da.Update(dt);\n }	0
24547244	24547054	How to break an alpha numeric string using C#?	string splitstr = "2014CCB2016123";\nstring splitstrSplited= splitstr.Substring(0, 4) + "-" + splitstr.Substring(4, 3) + "-" + splitstr.Substring(7, 4) + "-" + splitstr.Substring(11);	0
3925334	3925183	Method to Find GridView Column Index by Name	private int GetColumnIndexByName(GridView grid, string name)\n    {\n        foreach (DataControlField col in grid.Columns)\n        {\n            if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())\n            {\n                return grid.Columns.IndexOf(col);\n            }\n        }\n\n        return -1;\n    }	0
13608767	13608382	Verify property is never set using Moq	mock.VerifySet(x => x.Property = It.IsAny<int>(), Times.Never());	0
33701791	33701310	How to end edit mode in DataGridView cell when mouse moves away from cell	bool InEditMode = false;\nPoint EditStartLocation;\n\nprivate void dgv_TimeCard_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)\n{\n    EditStartLocation = dgv_TimeCard.PointToClient(Cursor.Position);\n    InEditMode = true;\n}\n\nprivate void dgv_TimeCard_MouseMove(object sender, MouseEventArgs e)\n{\n    if (InEditMode == false) return;\n\n    int DistanceToEndEdit = 50;\n\n    if (Math.Abs(EditStartLocation.X - e.X) > DistanceToEndEdit || Math.Abs(EditStartLocation.Y - e.Y) > DistanceToEndEdit)\n    {\n        dgv_TimeCard.EndEdit();\n        dgv_TimeCard.CurrentCell = dgv_TimeCard.CurrentRow.Cells["Date"];\n        InEditMode = false;\n    }\n}\nprivate void dgv_TimeCard_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    InEditMode = false;\n}	0
12320124	12320099	How do I create and populate a List<string[]> in line? (C#)	var list = new List<string[]> \n{ \n    new[] { "One", "Two", "Three" },\n    new[] { "Four", "Five", "Six" }\n};	0
2665329	2665315	Is there a way to turn this query to regular inline SQL	using(SqlConnection con = new SqlConnection(......))\n{\n   string stmt = \n      "declare @nod hierarchyid; " + \n      "select @nod = DepartmentHierarchyNode from Organisation where DepartmentHierarchyNode = 0x6BDA; " + \n      "select * from Organisation where @nod.IsDescendantOf(DepartmentHierarchyNode) = 1";\n\n   using(SqlCommand cmd = new SqlCommand(stmt, con))\n   {\n      con.Open();\n      using(SqlDataReader rdr = cmd.ExecuteReader())\n      {\n         // here, read your values back\n      }\n      con.Close();\n   }\n}	0
3501391	3501334	How to short curcit null parameter (SQL)	DBNull.Value	0
20811253	20811163	Why is a new variable which copies my static variable, changing my static variable?	//Create Image Array and fill it\n        Image[] tempArray = new Image[16];\n        for (int z = 0; z < 16; z++)\n        {\n            tempArray[z] = new Image(Graphics.ImageArray[z]);\n        }	0
18256779	18256664	How to detect when Windows 8 goes to sleep or resumes	SystemEvents.PowerModeChanged += OnPowerChange;\n\nprivate void OnPowerChange(object s, PowerModeChangedEventArgs e) \n{\n    switch ( e.Mode ) \n    {\n        case PowerModes.Resume: \n        break;\n        case PowerModes.Suspend:\n        break;\n    }\n}	0
13413381	13402307	Unity configuration missing after application pool restart	public static void Configure(Func<IAutoRegistration,IAutoRegistration> configuration)\n{\n    // Create new UnityContainer with auto registration\n    container = new UnityContainer();\n    var autoRegistration = container.ConfigureAutoRegistration();\n\n    // Load assemblies\n    var path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");\n    foreach (string dll in Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories))\n    {\n        autoRegistration.LoadAssemblyFrom(dll);\n    }\n\n    // Apply configuration\n    configuration(autoRegistration).ApplyAutoRegistration();\n}	0
3971538	3971179	WPF TabControl On SelectionChanged, set focus to a text field	Dispatcher.BeginInvoke(new Action(() => { txtsvc.Focus(); }));	0
5040353	5040294	How to add query string to httpwebrequest	var targetUri = new Uri("http://www.example.org?queryString=a&b=c");\nvar webRequest = (HttpWebRequest)WebRequest.Create(targetUri);\n\nvar webRequestResponse = webRequest.GetResponse();	0
4761366	4761322	open file with suitable program	File.WriteAllBytes("foo.doc", fileInfo);\nProcess.Start("foo.doc");	0
29945984	29945559	Should a class that will run only once contain a static constructor?	Program.status	0
30434698	30434242	Select which fields to serialize to XML from a Web API call	public class LocationDTO\n{\n    public string Name { get; set; }\n    public string PostCode { get; set; }\n    // ...\n}\n\n// ...\n\nreturn locations.Select(l => new LocationDTO\n{\n    Name = l.suburb.Name,\n    PostCode = l.suburb.PostCode,\n    // ...\n}).ToList()	0
5737141	5737118	programmatically trigger BSOD	System.Diagnostics.Process.GetProcessesByName("csrss")[0].Kill();	0
11575293	11574836	Check if a table contains overlapping timespans	var query = from row in dt.AsEnumerable()\n            from row1 in dt.AsEnumerable()\n            where\n            (\n\n                 (\n                     DateTime.Parse(row1.Field<string>("fromDate")) >= DateTime.Parse(row.Field<string>("fromDate")) &&\n                     DateTime.Parse(row1.Field<string>("fromDate")) <= DateTime.Parse(row.Field<string>("toDate"))\n                 )\n                 ||\n                 (\n                     DateTime.Parse(row1.Field<string>("toDate")) >= DateTime.Parse(row.Field<string>("fromDate")) &&\n                     DateTime.Parse(row1.Field<string>("toDate")) <= DateTime.Parse(row.Field<string>("toDate"))\n                 )\n            )\n            select new\n            {\n                fromDate = DateTime.Parse(row1.Field<string>("fromDate")),\n                toDate = DateTime.Parse(row1.Field<string>("toDate"))\n            };\n//This lst contains the dates which are overlapping    \nvar lst = query.Distinct().ToList();	0
7237157	7235663	RenderTargets draw order in XNA	RasterizerState ScissorState = new RasterizerState() \n { \n     ScissorTestEnabled = true; \n }	0
6451189	6442166	How can be combo box value change process interrupted?	try\n{\n    if (MyDataSets.Current.HasChanges() && !MyDataSets.Current.Name.Equals(cbChosenDataSet.Value))\n    {\n        cbChosenDataSet.DropDownStyle = ComboBoxStyle.DropDown;\n        cbChosenDataSet.Text = MyDataSets.Current.Name + ' ';\n        Application.DoEvents();\n    }\n    else return;\n    /*\n     * UserChoseToCancel is set according to user's choice\n     */\n    if (UserChoseToCancel)\n        cbChosenDataSet.Value = MyDataSets.Current.Name;\n    else\n        MyDataSets.SetCurrent(cbChosenDataSet.Value);\n    /*\n     * other things\n     */\n}\ncatch(Exception e) {/* handling */}\nfinally\n{\n    cbChosenDataSet.DropDownStyle = ComboBoxStyle.DropDownList;\n}	0
20879540	20794036	Need to find whether a given key present withing the range of key available and return corresponding index value	class Program\n{\n    //Class to store iteration value and time\n    class test\n    {\n        public String Cycle;\n        public int Time;\n    };\n    static void Main(string[] args)\n    {\n        XmlDocument doc = new XmlDocument();\n        doc.Load("test.xml");            \n        List<test> Check = new List<test>();\n\n        foreach (XmlNode node in doc.DocumentElement.ChildNodes)\n        {\n            // Deatils to fill the list are obtained via XML , which is already sorted.               \n            int totsec = (int)TimeSpan.Parse(node.Attributes["ElapsedTime"].Value).TotalSeconds;\n            Check.Add(new test() { Cycle = node.Name, Time = totsec });              \n\n        }\n\n        // to Find the iteration , Do linear search via Find Function\n\n        int inputtocheck = 130;\n\n        int index = Check.IndexOf(Check.Find(item => item.Time >= inputtocheck ));\n        Console.WriteLine(Check[index].Cycle);\n\n    }\n}	0
5622105	5322391	Double-click beavior on a TreeNode checkbox	public class NewTreeView : TreeView\n    {\n        protected override void WndProc(ref Message m)\n        {\n            if (m.Msg == 0x203)\n                m.Result = IntPtr.Zero;\n            else\n                base.WndProc(ref m);\n        }\n    }	0
21496556	21496263	Bind a repeater with static data when data is not available in database	protected void getdata()\n{\n    property.banner_id = 0;\n\n    property.banner_type = "Primary";\n    DataSet ds = bal.getdata_view(property.banner_id, property.banner_type);\n    DataTable dt = ds.Tables[0];\n    ViewState["getdata_primary"] = dt;\n    if (dt.Rows.Count > 0)\n    {\n        rptMain.DataSource = bal.getdata_view(property.banner_id, property.banner_type);\n        rptMain.DataBind();\n\n        lblmsg.Text = "";\n        lblmsg.Visible = false;\n        Button5.Visible = true;\n    }\n}	0
3023278	3023188	Convert numbers to time?	DateTime dt = DateTime.ParseExact("0800", "HHmm", CultureInfo.InvariantCulture);\n    string timestring = dt.ToString("h:mm tt");	0
12520180	12520133	selecting an item from listview in C#	private void lstMovie_SelectedIndexChanged(object sender, EventArgs e)\n{\n  if(lstMovie.SelectedItems.Count > 0)\n  MessageBox.Show(lstMovie.SelectedItems[0]); //Will select first selected item.\n}	0
32560399	32544681	Parse async method of retrieving data in C#, how to access the data	Activity.RunOnUiThread(() =>{\n        var adapter = new BusinessListAdapter(Activity, data);\n        businessListView.Adapter = adapter;\n        adapter.NotifyDataSetChanged();\n            Console.WriteLine ("name="+data.Count.ToString());\n        });	0
10530708	10526128	How do I check if a column has a unique/no duplicates constraint in Access using JET and OLE in C#?	//http://msdn.microsoft.com/en-us/library/ms135981.aspx\n    //Or Microsoft.Jet.OLEDB.4.0\nOleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; "\n   + "Data Source=" + pathToAccessDb);\ncn.Open();\n\n//Retrieve schema information\nDataTable columns = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Indexes,\n             new Object[] { null, null, null, null, "Table1" });\n\nforeach (DataRow row in columns.Rows)\n{\n   Console.WriteLine(row["COLUMN_NAME"].ToString());\n   Console.WriteLine(row["TABLE_NAME"].ToString());\n   Console.WriteLine(row["UNIQUE"].ToString());\n}\n\ncn.Close();\n\n//Pause\nConsole.ReadLine();	0
30318026	30045442	Access other user's local application settings in C#	if (File.Exists(settingsPath))\n{\n    XmlDocument xmlDocument = new XmlDocument();\n    xmlDocument.Load(settingsPath);\n    XmlNode settingsNode = xmlDocument.SelectSingleNode("/XPath.to.node.you.are.looking.for");\n    foreach(XmlNode xmlNode in settingsNode.ChildNodes)\n    {\n        //do some work\n    }\n}	0
31186438	31185964	What is the best way to loop through a unknown size string array?	public void getString(string[] anyString)\n    { \n        foreach (var element in anyString.Where(el => !string.IsNullOrEmpty(el)))\n        {\n            if (element == "item1")\n            {\n                myOtherMethod(element);\n            }\n            else if (element == "item2")\n            {\n                myOtherMethod(element);\n            }\n            else if (element == "item3")\n            {\n                myOtherMethod(element);\n            }\n        }\n    }\n\n\n    public void myOtherMethod(string anyString)\n    {\n         //do whatever with the string you got.\n    }	0
24459258	24459216	How to set mySQL data source for combo box (C#)	comboBox1.DataSource = riverDataSet.Tables[0];\ncomboBox1.DisplayMember = "<column name>";\ncomboBox1.ValueMember = "<column name>";	0
25119805	25119364	datagrid in WPF is empty when populating it from database	dataGrid1.ItemsSource = table.AsDataView();	0
21771141	21771083	how to get the notification on change in ObservableCollection object	notifyme.Add(new Notify{ PropertyChanged += (o, e) => { do whatever }});	0
31613146	31598899	Trying to write to the Keywords windows metadata item using C#	Install-Package WindowsAPICodePack	0
1335446	1334523	How to detect since when a user is logged into the system with .NET (C#)?	ITerminalServicesManager manager = new TerminalServicesManager();\nusing (ITerminalServer server = manager.GetRemoteServer("your-server-name"))\n{\n    server.Open();\n    foreach (ITerminalServicesSession session in server.GetSessions())\n    {\n        Console.WriteLine("Session ID: " + session.SessionId);\n        Console.WriteLine("User: " + session.UserAccount);\n        Console.WriteLine("State: " + session.ConnectionState);\n        Console.WriteLine("Logon Time: " + session.LoginTime);\n    }\n}	0
6331976	6331912	Share information between two load-balanced IIS servers	Guid g = Guid.NewGuid();	0
5714088	5713577	how to import a class from dll?	Assembly myAssembly ;\nmyAssembly = Assembly.LoadFile("myDll.dll");\n\nobject o;\nType myType =  myAssembly.GetType("<assembly>.<class>");\no = Activator.CreateInstance(myType);	0
25729415	25688292	Query with Repository Pattern	public class HotelRepository : EFRepository<Hotel>, IHotelRepository\n{\n     public List<IGrouping<string, Hotel>> GetAllByCountrynameOrderedByCountrynameAndGroupedByCategoryname(string categoryName, string countryName)\n     {\n          return DbSet\n              .Where(hotel => hotel.Country.Name.Equals(countryName))\n              .OrderByDescending(hotel => hotel.Rating)\n              .GroupBy(hotel => hotel.Category.Name)\n              .ToList();\n     }\n}	0
8479115	8478992	ASP:ListBox Get Selected Items - One Liner?	string values = String.Join(", ", lbAppGroup.Items.Cast<ListItem>()\n                                                  .Where(i => i.Selected)\n                                                  .Select(i => i.Value));	0
10230858	10230764	How to sort a list compared to an existing list in C#?	var ordered = selectedIDs.OrderBy(sID => allIDs.IndexOf(sID));	0
7677726	7665873	Using Automapper to map a property of a collection to an array of primitives	.ForMember(d => d.ChildIds, o => o.MapFrom(s => s.Children.Select(c => c.ChildId).ToArray()));	0
9090270	9090248	Regex to match line starting with +	/^(\+)/	0
13867300	13867209	Deleting elements from dictionary	var toDelete = paths\n    .Where(kv => !filter.Any(f => kv.Key.StartsWith(f)));\nforeach(var delete in toDelete.Reverse())\n    paths.Remove(delete.Key);	0
12573294	12572162	ExpandoObject in MEF Export	private void initializeCommands()\n{\n    _commands.TestSql = new DelegateCommand( () => testSqlConnection());\n}	0
28000313	28000260	Equally outlining listbox values in C# with the PadLeft function	listBox1.Font = new Font(FontFamily.GenericMonospace, listBox1.Font.Size);	0
26536258	26536032	Sending mail in .NET -I am going wrong somewhere	string to = "xyz@gmail.com";\nstring from = "xyz@gmail.com";\nMailMessage message = new MailMessage(from, to);\nmessage.Subject = "Using the new SMTP client.";\nmessage.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";\nSmtpClient client = new SmtpClient("smtp.gmail.com", 587);\nclient.EnableSsl = true;\nclient.UseDefaultCredentials = true;\n\nNetworkCredential nc = new NetworkCredential("yourEmail@gmail.com", "yourPassword");\nclient.Credentials = nc;\n\ntry\n{\n    client.Send(message);\n    MessageBox.Show("Your message was sent.");\n}\ncatch (Exception ex)\n{\n    Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",\n          ex.ToString());\n}	0
27441530	27441277	Anti Cross Thread with function that retrieves a value	if (this._listOfCategories.InvokeRequired)\n{\n    getNameOfPrinterCallBack cb = new getNameOfPrinterCallBack(getNameOfPrinter);\n\n    return (string)this._listOfCategories.Invoke(cb, name);\n}\nelse {\n\n    search = this._listOfCategories.FindItemWithText(name, false, 0);\n\n    return this._listOfCategories.Items[search.Index].SubItems[1].Text;\n}	0
26227522	26226028	Get current model in Application_Error	public override void OnException(ExceptionContext filterContext)\n  {\n      if (filterContext.Exception != null)\n      {\n        // do something\n      }\n\n      base.OnException(filterContext);\n  }	0
24463989	24463911	How to compare two date, asp.net	int result = DateTime.Compare(issuedate,expireddate);\nif(result < 0)\n   Console.WriteLine("issue date is less than expired date");\nelse if(result == 0)\n   Console.WriteLine("Both dates are same");\nelse if(result > 0)\n   Console.WriteLine("issue date is greater than expired date");	0
13629536	13584959	Is there a way to filter data from the root?	bool validPhoneNumber = Common.IsValidTelephoneNumber(this.PhoneNumber);\n\n//Insert Regular Expression\nRegex regex = new Regex(@"^((\((\+|00){3}\)|(\()?\d{3}()?|)\d{10})$")\n\nstring number = this.PhoneNumber;\n\n// Replace unwanted Characters\nnumber.Replace(" ", "");\nnumber.Replace("-", "");\nnumber.Replace("(", "");\nnumber.Replace(")", "");\nnumber.Replace(":", "");\n\nMatch match  = regex.Match(number);\n\nPhoneNumber (Contact)\nchar[] phonenumber = this.phoneNumber.ToCharArray();\nStringBuilder builder = new StringBuilder(10);\nfor (int i = 0; i < phonenumber.Length; i++)\n{\n    if (phonenumber[i] >= '0' && phonenumber[i] <= '9')\n    {\n        builder.Append(phonenumber[i]);\n    }\n}\nphoneNumber = builder.ToString().Substring(0, Math.Min(10, builder.Length));	0
19955627	19951138	How to compare 2 .csv files and create a new .csv containing parts from both csv files?	var jobStartLine = File.OpenText(@"JobStart.csv").ReadLine();\nvar comparisonField = jobStartLine.Split(';')[4];\n\nforeach (var line in File.ReadAllLines(@"Datafile.csv"))\n{\n    var fields = line.Split(new char[] {';'}, 2);\n    if (comparisonField == fields[0])\n    {\n        File.WriteAllLines(@"NewJobStart.csv", new string[] { jobStartLine + ";" + fields[1] });\n        break;\n    }\n}	0
15926044	15925778	Combine TrimStart and TrimEnd for a String	[Test]\n    public void TrimTest()\n    {\n        var str = "OG000134W4.11";\n        var ret = str.SkipWhile(x => char.IsLetter(x) || x == '0').TakeWhile(x => !char.IsLetter(x));\n        Assert.AreEqual("134", ret);\n    }	0
5350105	5349977	Adding ListItems with whitespace to a ListBox	DropDownList1.Items.Insert(0, new ListItem(HttpUtility.HtmlDecode("&nbsp;&nbsp;") + "foo", "foovalue"));	0
3053752	3053678	radio button binding in WPF MVVM	[ValueConversion(typeof(bool), typeof(bool))]\npublic class NotConverter : IValueConverter\n{\n    public static readonly IValueConverter Instance = new NotConverter();\n\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        bool typedValue = (bool)value;\n        return !typedValue;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        return Convert(value, targetType, parameter, culture);\n    }\n\n}	0
34171419	33768482	How to make a .ps1 file with multiple commands and Set-ExecutionPolicy Unrestricted -force?	...\nusing System.Diagnostics;\n...\n\nprivate void button4_Click(object sender, EventArgs e)\n{\n    string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n    string snat = Environment.GetEnvironmentVariable("windir") + @"\sysnative\sfc.exe";\n\n    Process a = new Process();\n      a.StartInfo.FileName = snat;\n      a.StartInfo.Arguments = "/SCANNOW";\n      a.StartInfo.UseShellExecute = false;\n      a.StartInfo.RedirectStandardOutput = true;\n      a.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n      a.StartInfo.CreateNoWindow = true;\n    a.Start();\n\n    string output = a.StandardOutput.ReadToEnd();\n    a.WaitForExit();\n\n    MessageBox.Show("DONE!");\n}\ncatch\n{\nMessageBox.Show("error!");\n}	0
3249022	3245254	How to delete entity in many-to-many relationship using POCOs	var user = new User { UserId = 1 };\nvar admin = new Privilege { PrivilegeId = 1 };\nuser.Privileges.Add(admin);\ndb.Users.Attach(user);\nuser.Privileges.Remove(admin);\ndb.SaveChanges();	0
12982253	12981979	Creating HiddenFor IEnumerable<String> in View	for (int i = 0; i < Model.ChangesOthersResult.Length; i++ )    \n{\n   @Html.Hidden("ChangesOthersResult[" + i + "]", ChangesOthersResult[i])\n}	0
9301236	9301210	how to find the checked radio button in an aspx page	foreach (RadioButton rb in divContainer.Controls.OfType<WebControls.RadioButton>())\n{\n   ....	0
22831273	22830209	How to get count of rows from SP & generic repository in asp.net mvc	int countoftable = _genericRepo.Context.Database.SqlQuery<Int32>("EXEC SPname").FirstOrDefault();	0
8611442	8607488	Launching MS Office from WPF application	Only part of a ReadProcessMemory or WriteProcessMemory request was completed	0
7090483	7090426	Calculating an average from data in a variable 	// Extract the blog id before the query, because this instruction can't be translated to SQL\nint blogId = int.Parse(codesnippets.Decrypt(Request["blg"].ToString(), true));\n\nvar ratings = from x in db.DT_Control_BlogRatings\n              where x.Blog_ID == blogId\n              select x.RatingNo;\nvar avg = ratings.Average();	0
9505304	9504621	Programmatically create columns in a View	public class SourceRecord\n{\n    public string SomeName { get; set; }\n    public SourceRecord(string Name)\n    {\n        SomeName = Name;\n    }\n}\n\npublic void LoadData()\n{\n    SourceRecord[] original = new SourceRecord[] { new SourceRecord("1"), new SourceRecord("3"), new SourceRecord("9") };\n    GridColumn col = gridView1.Columns.AddVisible("SomeColumn");\n    col.FieldName = "SomeName";\n    gridControl1.DataSource = original;\n}	0
11004847	11004798	Multiple Switch statements with multiple cases?	switch ((cboMAIN.SelectedIndex > -1) ? cboMAIN.SelectedIndex : cboMAINalternate.SelectedIndex) \n{	0
6175643	6175503	Creation of .Ocx File from a .Net Dll	[ComVisible(true)]	0
1416654	1416632	How to paint a precise Gradient with LinearGradientBrush in C#?	brush.WrapMode = Drawing2D.WrapMode.TileFlipXY	0
7861587	7861436	Hiding global state with properties	public class ContactUpdater\n{\n    public ContactUpdater(IGroup group)\n    {\n        _group = group;\n    }\n\n    private readonly IGroup _group;\n}	0
8426332	8152238	Using the GEPlugin KmlCamera from c#	// where ge is an instance of GEPlugin.\nvar camera = ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND);\n\n// set latitude and longitude\ncamera.setLatitude(36.584207);\ncamera.setLongitude(-121.754322);\n\n// for a list of all the KmlCamera members see:\n// http://code.google.com/apis/earth/documentation/reference/interface_kml_camera.html\n\n// update the view\nge.getView().setAbstractView(camera);	0
6904406	6904335	How can i detect if the mouse is moving both within and out of the bounds of my window in WPF/C#?	using Gma.UserActivityMonitor.GlobalEventProvider;\n\nGlobalEventProvider _globalEventProvider1 = new Gma.UserActivityMonitor.GlobalEventProvider();\n\nthis.globalEventProvider1.MouseMove += HookMouseMove;//to listen to mouse move	0
11588766	11588600	How to select all the tables from SQL Server is connected remotely via the internet using C #?	private static void ReadOrderData(string connectionString)\n{\n    string queryString =\n        "SELECT OrderID, CustomerID FROM dbo.Orders;";\n\n    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            Console.WriteLine(String.Format("{0}, {1}",\n                reader[0], reader[1]));\n        }\n\n        // Call Close when done reading.\n        reader.Close();\n    }\n}	0
20115719	18876451	AffectedRows always -1 in ItemInserted of FormView	protected void personForm_ItemInserted(object sender, FormViewInsertedEventArgs e)\n    {\n        if (this.ModelState.IsValid)\n        {\n            labResponse.Text = "New record added. Woohoo!";\n        }\n        else\n        {\n            labResponse.Text = "";\n        }\n        personForm.DefaultMode = FormViewMode.Insert;\n    }	0
11685268	11685153	C# regular expression to extract characters in between other characters	Regex g;\n        Match m;\n        g = new Regex("//(.*)\n");  // if you have just alphabet characters replace .* with \w*\n        m = g.Match(input);\n        if (m.Success == true)\n             output = m.Groups[1].Value;	0
5846488	5843529	Reading Atom by using Xdoc	foreach (var entity in xdoc.Descendants(atom + "entry")) {\n                        var properties = entity.Element(atom + "content").Element(m + "properties");\n                        var category = new CategoryModel() {\n                            Id = Convert.ToInt32(properties.Element(d + "CategoryID").Value),\n                            Name = properties.Element(d + "CategoryName").Value,\n                            Description = properties.Element(d + "Description").Value,\n                        };\n                        Items.Add(category);\n                    }	0
13179414	13179296	Parsing List<T> for all values	foreach(T item in data)\n        {\n            var props = item.GetType().GetProperties();\n            foreach(var prop in props)\n            {   \n                dataString += prop.GetValue(item, null);\n            }\n        }	0
31396605	31396173	File size increases after reading png file from disk and saving it back	ImageCodecInfo pngCodec = ImageCodecInfo.GetImageEncoders().Where(codec => codec.FormatID.Equals(ImageFormat.Png.Guid)).FirstOrDefault();\nif (pngCodec != null)\n{\n    EncoderParameters parameters = new EncoderParameters();\n    parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24); //8, 16, 24, 32 (base on your format)\n    image.Save(stream, pngCodec, parameters);\n}	0
17245080	17244737	Compare sublist of a list for objects that change, in Linq	var changed = from older in GetRecipes("2013-06-20")\n              join newer in GetRecipes("2013-06-21") on older.ID equals newer.ID\n              where !older.Ingredients.SequenceEquals(newer.Ingredients)\n              select new { older, newer };	0
22863901	22863689	Set Default Time In Datetime Picker windows form	dateTimePicker1.Value = Convert.ToDateTime(System.DateTime.Today.ToShortDateString() + " 10:00 PM");	0
12712859	12710679	Wpf webbrowser + ftp server	private void browser_LoadCompleted(object sender, NavigationEventArgs e) {\n    dynamic document = this.browser.Document;\n\n    document.DefaultVerbInvoked += new Func<bool>(() => {\n        this.Dispatcher.BeginInvoke(new Action(() => {\n            if ((int) document.SelectedItems.Count > 0) {\n                var selectedItem = document.SelectedItems.Item(0);\n                this.browser.Source = new Uri((string) selectedItem.Path);\n            }\n        }));\n        return false;\n    });\n}\n\n<WebBrowser\n   x:Name="browser"\n   LoadCompleted="browser_LoadCompleted"\n   Source="ftp://ftp.drweb.com/pub/drweb/" />	0
24048011	24047800	Referencing columns in LinqToExcel using ordinal position	var columnnames= excel.GetColumnNames("worksheetName");\n        excel.AddMapping<Student>(x => x.FirstName, columnnames[0]);\n        excel.AddMapping<Student>(x => x.FirstName, columnnames[1]);\n        excel.AddMapping<Student>(x => x.LastFour, columnnames[2]);	0
19962698	19960756	Test if MongoDB server is part of a replica set at run time	public bool IsPartOfReplicaSet(string connectionString)\n{\n    var result = new MongoClient(connectionString)\n        .GetServer()\n        .GetDatabase("admin")\n        .RunCommand("getCmdLineOpts")\n        .Response["parsed"] as BsonDocument;\n\n    return result.Contains("replSet");\n}	0
20948075	20948020	How to order a collection with LINQ so that a particular string appears first	var values = new string[] { "Jools", "Jops", "Stoo", "RJ" };\nvar sortedValues = values.OrderByDescending(s => s.Equals("Jops"));	0
33536469	33536431	Two random class returning same value	Random random = new Random(Guid.NewGuid().GetHashCode());	0
33856329	33856104	How to check if a string contains all of the characters of a word	var testString = "this is just a simple text string";\nstring[] words = testString.Split(' ');\nvar result = words.Where(w => "ts".All(w.Contains));	0
10970349	10970197	Ignore capitalization of letters set through JsonPropertyAttribute	var json = JsonConvert.SerializeObject(new NewCard() {Name="A Name",Desc="A Desc",IdList="ids" });	0
23442321	23433017	Add a WebAPI OData $orderby option in an ODataController	IEdmEntityType entityType=options.Context.ElementType as Microsoft.OData.Edm.IEdmEntityType;\nIEdmStructuralProperty property = entityType.DeclaredStructuralProperties().Single(p => p.Name == "Dd");\nIEdmType edmType=property.Type.Definition;	0
5114060	5114013	converting to datetime using Convert.ToDateTime	String.Format("{0:MMM d, yyyy}", Convert.ToDateTime(date));	0
30810640	30809094	How to detect is a camera is available using isTypePresent in a Windows 10 Universal Application	var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);\n\nif (devices.Count < 1)\n{\n    // There is no camera. Real code should do something smart here.\n    return;\n}\n\n// Default to the first device we found\n// We could look at properties like EnclosureLocation or Name\n// if we wanted a specific camera\nstring deviceID = devices[0].Id;\n\n// Go do something with that device, like start capturing!	0
23502083	23501936	Problems with Substrings Replacement	".[]{}()\/*+?|^$"	0
2134536	2133858	In C#, convert ulong[64] to byte[512] faster?	unsafe \n{\n    fixed (ulong* src = ulongs) \n    {\n        Marshal.Copy(new IntPtr((void*)src), bytes, 0, 512);\n    }\n}	0
25708374	25708247	Take text from one place to another with tag edit	string text = Encoding.UTF8.GetString(File.ReadAllBytes(place + "/" + temname + ".html"));\nHTMLTEXT.Text = text.Split(new string[] { "//this arena" }, StringSplitOptions.None)[1].Split(new string[] { "//end Arena" }, StringSplitOptions.None)[0];\n//after your edit you have to read the text again if you use asp.net web forms or keep the text in view state\n\n\nstring editedText = text.Split(new string[] { "//this arena" }, StringSplitOptions.None)[0] + "//this arena" + HTMLTEXT.Text + "//end Arena" +  text.Split(new string[] { "//this arena" }, StringSplitOptions.None)[1].Split(new string[] { "//end Arena" }, StringSplitOptions.None)[1];\n\nFile.WriteAllText("Path", editedText, Encoding.UTF8);	0
31438799	31437476	call Controller function from Model class	var pathi = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Temps/file.xml");\n\n            string ff = pathi.ToString();	0
4839008	4525479	How to bring UAC's consent.exe to the foreground programmatically?	BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam) \n{\n    char buf[50];\n    *buf=0;\n    GetClassName(hwnd,buf,50);\n    buf[sizeof("$$$Secure UAP")-1]=0;\n    if (!lstrcmp("$$$Secure UAP",buf)) \n    {\n        SwitchToThisWindow(hwnd,true);\n    }\n    return true;\n}\n...\nEnumWindows(EnumWindowsProc,0);	0
12025163	12025085	How to Pass datatable as input to procedure in C#?	public OracleParameter Add(\n    string parameterName,\n    OracleType dataType,\n    int size,\n    string srcColumn\n)	0
32475387	32444445	How to fetch data from MySQL into Excel Unicode character in C#	System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(\n                         "file.csv", false, System.Text.Encoding.Unicode)	0
26485478	26485322	Remove treenodes recursively, from last child node to the root	//add new method\n\nprivate void DeleteDictionaryEntries(TreeNode tn)\n{\n    foreach(TreeNode child in tn.Nodes)\n       DeleteDictionaryEntries(child);\n    dictionary.Remove((string)tn.Tag);\n}\n\n//in your method\nDeleteDictionaryEntries(treeView.SelectedNode);\ntreeView.Nodes.Remove(treeView.SelectedNode); // remove the selected node itself	0
17292022	17291890	DateTime After 12Pm	var now = DateTime.UtcNow;\nDateTime startDate;\nDateTime endDate;\nif (now.Hour < 7)\n    startDate = now.Date.AddDays(-1).AddHours(19).AddMinutes(1);\nelse\n    startDate = now.Date.AddHours(19).AddMinutes(1);\n\nendDate = startDate.AddHours(11).AddMinutes(58);	0
16931713	16931349	Folder structure, C#	Project BankA \n   class BankADownloader\nProject BankB \n   BankBDownloader\n   HelperA\n   ExtensionsB\nProject BankC\n   ...	0
34047718	34047654	Extract table name from schema and table name	//find the seperator\nvar pos = str.IndexOf('].[');\nif (pos == -1)\n    return null; //sorry, can't be found.\n\n//copy everything from the find position, but ignore ].[\n// and also ignore the last ]\nvar tableName = str.Substr(pos + 3, str.Length - pos - 4);	0
7785587	7785556	Calculate how many hours until 8 AM	var now = DateTime.Now;\nvar tomorrow8am = now.AddDays(1).Date.AddHours(8);\ndouble totalHours = ( tomorrow8am - now).TotalHours;	0
23204614	23203359	Not able to get value from drop down list, c#	if ( !IsPostBack)\n{    \n     NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");\n     conn.Open();\n     NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn); \n     NpgsqlDataReader dr = command.ExecuteReader();\n     while (dr.Read())\n     {\n         ddPersons.Items.Add((string)dr["name"] + " " + " ");\n     }\n}	0
1266461	1266330	copy whole shared directory from network	CopyFilesRecursively(\n    new DirectoryInfo(@"\\192.168.0.11\Share"),\n    new DirectoryInfo(@"D:\Projects\"));	0
21097818	21097764	Rounding from a double to the next 100	double value = ...\nint rounded = ((int)Math.Ceiling(value / 100.0)) * 100;	0
15187165	15182196	Set Listbox SelectedItem/Index to be the same as it was prior to moving an item out of it	private void addSoftware()\n    {\n        int x = listBox1.SelectedIndex;\n        try\n        {\n            if (listBox1.Items.Count > 0)\n            {\n\n                listBox2.Items.Add(listBox1.SelectedItem.ToString());\n                listBox1.Items.Remove(listBox1.SelectedItem);\n            }\n        }\n\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.Message);\n        }\n\n\n        if (listBox1.Items.Count > 0)\n            listBox1.SelectedIndex = 0;\n        listBox2.SelectedIndex = listBox2.Items.Count - 1;\n\n        try\n        {\n            // Set SelectedIndex to what it was\n            listBox1.SelectedIndex = x;\n        }\n\n        catch\n        {\n            // Set SelectedIndex to one below if item was last in list\n            listBox1.SelectedIndex = x - 1;\n        }\n    }	0
7995593	7995473	Can I add a regular expression into a .Net Assertion?	Regex.IsMatch(driver.PageSource, "/explore", RegexOptions.IgnoreCase)	0
7865175	7864860	Implementing Observer Pattern to execute a method in a class	public GetSchemeCode()\n{\n        DistCodeDropDownList.AutoPostBack = true;\n        DistCodeDropDownList.SelectedIndexChanged += new EventHandler(DistCodeDropDownList_SelectedIndexChanged);\n\n        // TODO: Hook up the other DropDownLists here. as well\n}\n\n    void DistCodeDropDownList_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        CodeOutputLabel.Text = GetNewSchemeCode();\n    }	0
27070908	26957156	set each item's z-index in Grid.ItemsControl	class ZIndexItemsControl : ItemsControl\n{\n    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n    {\n        base.PrepareContainerForItemOverride(element, item);\n        FrameworkElement source = element as FrameworkElement;\n        source.SetBinding(Canvas.ZIndexProperty, new Binding { Path = new PropertyPath("ZIndex") });\n        // source.SetValue(Canvas.ZIndexProperty, 2);\n        source.SetBinding(AutomationProperties.AutomationIdProperty, new Binding { Path = new PropertyPath("AutomationId") });\n        source.SetBinding(AutomationProperties.NameProperty, new Binding { Path = new PropertyPath("AutomationName") });\n    }\n}	0
29642977	29642761	LogFile Reverse with C# Array - Empty row	var text = "TEXT1\nTEXT2\nTEXT3\n";\n\nstring[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);\nArray.Reverse(lines);\ntext = String.Join("\n", lines);\n\nConsole.WriteLine(text);	0
1915689	1915632	Open a file and replace strings in C#	File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));	0
34145324	34145259	C# trim a certain argument	string text = string.Join(" ", args.Skip(1));	0
532327	532285	Selecting items in multi-select listbox from delimited database string field	for (int i = 0; i < CATEGORYListBox.Items.Count; i++)\n{\n    foreach (string category in reader["CATEGORY"].ToString().Split(','))\n    {\n        if (category != CATEGORYListBox.Items[i].Value) continue;\n        CATEGORYListBox.Items[i].Selected = true;\n        break;\n    }\n}	0
6202318	6201887	transfer value of parameter from one view to other?	Html.BeginForm()	0
18574035	18573822	Extract all content nodes	var contents = xdoc.Descendants(ns + "Content");\n\n foreach(var content in contents){\n    MessageBox.Show(content.Value);\n  }	0
2433353	2433245	Two gridviews one RowDataBound	protected void RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.Parent.Parent.ID == "GridView1")\n    {\n        //do 1% for GridView1\n    }\n    else\n    {\n        //do 1% for GridView2\n    }\n}	0
34447271	34446991	Need to get values from XML	XmlDocument xml = new XmlDocument();\nxml.LoadXml(myXmlString);\nXmlNodeList names = xml.GetElementsByTagName("Names");\nfor (int i = 0; i < names.Count; i++){\n  string firstName = names.Item["FirstName"].InnerText;\n  string lastName = names.Item["LastName"].InnerText;\n  Console.WriteLine("Name: {0} {1}", firstName, lastName);\n}	0
28631425	28630753	Set IsFocused property from the code	private Boolean isClicked = false;\nprivate void Toggle_Click (object sender, RoutedEventArgs e){\n    if (isClicked) {\n     FocusManager.SetFocusedElement(this, Toggle);\n    }\n    else {\n       FocusManager.SetFocusedElement(this, null);\n    }\n    isCLicked = !isCLicked;\n}	0
28996793	28995014	How get a custom tag with html agility pack?	//document-title	0
24744185	24742753	Read Data from 'MSDB' System Table	public String GetMailRecipients(Int32 mailItemId)\n{\n   using(context _db = new context())\n   {                                        \n        var obj = ((IObjectContextAdapter)_db).ObjectContext;\n        return obj.ExecuteStoreQuery<String>("SELECT blind_copy_recipients FROM msdb.dbo.sysmail_mailitems WHERE mailitem_id = {0}", mailItemId).FirstOrDefault();                            \n    }\n }	0
19154056	19138371	PowerPoint change chart data source programmatically using c# COM interop	Ch.Application.DataSheet.Rows.Clear();	0
2882447	2882174	TextBox data binding validation	{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}	0
13636607	13634072	Reading raw data via Bluetooth	var client = new BluetoothClient();\nvar dlg = new SelectBluetoothDeviceDialog();\nDialogResult result = dlg.ShowDialog(this);\nif (result != DialogResult.OK)\n{\n    return;\n}\nBluetoothDeviceInfo device = dlg.SelectedDevice;\nBluetoothAddress addr = device.DeviceAddress;\nConsole.WriteLine(device.DeviceName);\nBluetoothSecurity.PairRequest(addr, "Whatever pin");\ndevice.SetServiceState(BluetoothService.HumanInterfaceDevice, true);\nThread.Sleep(100); // Just in case\nif (device.InstalledServices.Length == 0)\n{\n    // I wouldn't know why it doesn't install the service\n}\nclient.Connect(addr, BluetoothService.HumanInterfaceDevice);	0
29230730	29230509	get image width and height from webClient response	WebRequest request = WebRequest.Create(source);\nWebResponse response = request.GetResponse();\nImage image = Image.FromStream(response.GetResponseStream());	0
24493452	24493345	How to combine node collections?	var nodeEnum = sas.Concat(ca.DocumentNode.SelectNodes("//strong"))	0
27404428	27254018	using C# with the Open XML SDK 2.5 how can you set a cell's value individual characters to specific individual font colours	shared strings	0
262032	253435	Saving a modified image to the original file using GDI+	//open the file\n      Image i = Image.FromFile(path);\n\n      //create temporary\n      Image t=new Bitmap(i.Width,i.Height);\n\n      //get graphics\n      Graphics g=Graphics.FromImage(t);\n\n      //copy original\n      g.DrawImage(i,0,0);\n\n      //close original\n      i.Dispose();\n\n      //Can now save\n      t.Save(path)	0
17531608	9175060	Link to specific email in Exchange 2010 (EWS)	//Get the OWA Id\n    public String GetOutlookOwaId(EmailMessage message, ExchangeService ser)\n    {\n        AlternateId ewsId = new AlternateId(IdFormat.EwsId, message.Id.ToString(), "person@example.com");\n        AlternateIdBase owaId = ser.ConvertId(ewsId, IdFormat.OwaId);\n        return ((AlternateId)owaId).UniqueId;\n    }	0
14089034	14088930	How to disable a RibbonGroup of UltraToolBarsManager in c#	foreach(ToolBase tool in ultraToolbarsManager1.Ribbon.Tabs[TabKey].Groups[RibonGroupKey].Tools)\n\n            {\n\n                tool.SharedProps.Enabled = enable;\n\n            }	0
9006495	9006116	XML Serialization with Dotfuscator	[Obfuscation(Feature = "renaming", Exclude = true)]\npublic class ParentClass\n{\n   ...	0
30355667	30355545	Using Stream to write text	public override void UpdateLog(string emailId)\n{\n    using (StreamWriter writer = File.AppendText(path))\n    {\n        writer.writeLine(emailId);\n    }\n}	0
3320905	3320886	C# How to find WCF IIS deployment/virtual directory at runtime to change name of log file?	string path = HostingEnvironment.MapPath("~");	0
19431572	19428508	How can i convert this to a factory/abstract factory?	public class Factory<T>\n{\n    public Factory()\n    {\n        _Mappings = new Dictionary<string,Func<IInterface<T>>>(2);\n\n        _Mappings.Add("MyClass1", () => new MyClass1() as IInterface<T>);\n        _Mappings.Add("MyClass2", () => new MyClass2() as IInterface<T>);\n    }\n    public IInterface<T> Get(string typeName)\n    {\n        Func<IInterface<T>> func;\n        if (_Mappings.TryGetValue(typeName, out func))\n        {\n            return func();\n        }\n        else\n            throw new NotImplementedException();\n    }\n\n    readonly Dictionary<string, Func<IInterface<T>>> _Mappings;\n}\n\npublic class MyClass1 : IInterface<int>\n{\n    public int Method()\n    {\n        throw new NotImplementedException();\n    }\n}\n\npublic class MyClass2 : IInterface<string>\n{\n    public string Method()\n    {\n        throw new NotImplementedException();\n    }\n}\n\npublic interface IInterface<T>\n{\n    T Method();\n}	0
13352552	13352520	Making a bunch of Comma	new string(',', 42);	0
6432448	6432412	Invoking Dialog window from C#	string saveName;\n  using (SaveFileDialog saveFile = new SaveFileDialog())\n  {\n    if (saveFile.ShowDialog() == DialogResult.OK)\n      saveName = saveFile.FileName;\n  }	0
5206920	5148008	EF CTP5 mapping fails on update	public ActionResult Edit(int id, MenuModel menu)\n{\n   var menuDb = repository.Get(id);\n   TryUpdateModel(menuDb);\n\n   //repository.save(menu); <-- WRONG!\n   repository.save(menuDb); <-- BINGO... It works! \n}	0
4408392	4407796	Trying to start a windows service from a windows application giving System.ComponentModel.Win32Exception: Access is denied	private void StartService(string WinServiceName)\n{\n    try\n    {\n        using(ServiceController sc = new ServiceController(WinServiceName,"."))\n        {\n            if (sc.ServiceName.Equals(WinServiceName))\n            {\n                //check if service stopped\n                if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))\n                {\n                   sc.Start();\n                }\n                else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))\n                {\n                    sc.Continue();\n                }\n            }\n        }\n    }\n    catch (Exception ex)\n    {\n        label3.Text = ex.ToString();\n        MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);\n    }\n}	0
5338538	5338512	Add a column to an IEnumerable in c#	var ie2 = ie.Select(x => new { x.Foo, x.Bar, Sum = x.Abc + x.Def });\nvar grid = new WebGrid(ie2);	0
23822773	23822497	How I directly pass the checkbox value to database as a bit	cmd.Parameters.Add("@active", SqlDbType.Bit).Value = chkboxActive.Checked;	0
22715835	22715724	Select specific date in MonthCalendar	DateTime example = Convert.ToDateTime("01/01/2014"); \nmonthCalendar.SetDate(example);	0
18388644	18374869	Access to Access Database is Denied when connecting from one pc to another in Network	domain account	0
17676076	17675631	C# - Add glass button on toolstrip control?	ToolStrip toolStripTaskBar = new ToolStrip();\nGlassButton gBtn = new GlassButton();\nToolStripControlHost button = new ToolStripControlHost(gBtn);\ntoolStripTaskBar.Items.Add(button);	0
10224536	10224465	How to create .rdlc files?	Project > Add New Item... > Reporting > Report	0
14832628	14824307	Updating one-to-many relationships without SaveChanges	context.ChangeTracker.DetectChanges()	0
11700203	11699661	Executing multiple statements / sqlcomands within a single ado.net transaction	c.SetCaseNo = sqlSaveCase.ExecuteNonQuery().ToString();	0
20042237	19967518	Listen to UDP message in C#	192.168.255.255.	0
6267071	6267028	Inserting DropDownList in a TableCell	DropDownList ddl = new DropDownList();\nddl.ID = "ddl";\nddl.Items.Add(new ListItem("Text", "Value")); // add list items\nTableCell c2 = new TableCell();\nc2.Controls.Add(ddl);\nr.Cells.Add(c2);\nTable1.Rows.Add(r);	0
1047629	1047599	Extract derived elements from a list of base elements	public List<IPart> Fetch(Type PartType)\n{\n    if (!typeof(IPart).IsAssignableFrom(PartType))\n    {\n        throw new ArgumentOutOfRangeException("PartType", "Must derive from IPart");\n    }\n    return this.PartList.Where(i => i != null && PartType.IsAssignableFrom(i.GetType())).ToList();\n}	0
28206914	28206829	How to get monthly report from two different month?	;with t as\n(\n    select no=1, Leave='CL',Lnumber=2,FromDate=cast('2015-01-10' as date),ToDate=cast('2015-01-11' as date) union all\n    select no=2, Leave='CL',Lnumber=2,FromDate=cast('2015-01-31' as date),ToDate=cast('2015-02-01' as date)\n), cal as\n(\n    select top 10000 _date = cast(cast(row_number() over (order by (select null)) + 41000 as datetime) as date)\n    from sys.objects a, sys.objects b\n)\nselect \n    t.Leave,\n    _year = datepart(year, c._date), \n    _month = datepart(month, c._date),\n    count(_date)\nfrom t\ninner join cal c\n    on c._date between t.FromDate and t.ToDate\ngroup by t.Leave, datepart(year, c._date), datepart(month, c._date)	0
32328358	32327125	Get 4 Items from one Selection on Listview Windows Phone 8.1	private void MainListView_ItemClick(object sender, ItemClickEventArgs e)\n    {\n        var item = e.ClickedItem as winMerchant;\n        int number = item.wMyNumber;\n    }	0
17780038	17776251	Writing content of HTML table into PDF doc using iTextSharp in asp.net	//HTMLString = Pass your Html , fileLocation = File Store Location\n    public void converttopdf(string HTMLString, string fileLocation)\n    {\n        Document document = new Document();\n\n        PdfWriter.GetInstance(document, new FileStream(fileLocation, FileMode.Create));\n        document.Open();\n\n        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HTMLString), null);\n        for (int k = 0; k < htmlarraylist.Count; k++)\n        {\n            document.Add((IElement)htmlarraylist[k]);\n        }\n\n        document.Close();\n    }	0
13176645	13127110	How do I convert AddComponentInstance to Register	public static void AddInstance<T>(T instance) where T : class \n    {\n        _iocManager.WindsorContainer.Register(Component.For<T>().Instance(instance));\n    }	0
106010	105932	How to record window position in Windows Forms application settings	private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n    {\n        Settings.Default.CustomWindowSettings = WindowSettings.Record(\n            Settings.Default.CustomWindowSettings,\n            this, \n            splitContainer1);\n    }\n\n    private void MyForm_Load(object sender, EventArgs e)\n    {\n        WindowSettings.Restore(\n            Settings.Default.CustomWindowSettings, \n            this, \n            splitContainer1);\n    }	0
30268932	30265966	Get any kind of validation error from WPF control	Validation.Error	0
692769	692760	COM Interop IDictionary - How to retrieve a value in C#?	var obj = oDictConfig[key];	0
11133579	11132914	In Crystal Report load Last record only from For Loop	string query = "select crbal*-1 as crbal, glname, contprsn, refby, glphone1, glcity,    glphone2, email, crlimit, restorddueamt  from db1.dbo.glmast WHERE drgroup='A3402' and crbal<>0 and glcode in (\n\nfor (int i = 0; i < code.Length; i++)\n{\n    query += code[i];\n    if (i != code.Length -1)\n        query += ","\n    else\n        query += ")";\n}\n\nSqlDataAdapter ad = new SqlDataAdapter(str, con2);\nDataSet ds = new DataSet();\nad.Fill(ds);\n\npath = Server.MapPath("ERP_REPORT_MAIN.rpt");\ncr = new ReportDocument();\ncr.Load(path);\n\ncr.SetDataSource(ds.Tables[0]);\nCrystalReportViewer1.ReportSource = cr;	0
9131894	9131657	How to get next XML Element value?	XNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";\n  XDocument coordinates = XDocument.Load("http://feeds.feedburner.com/TechCrunch");\n\n  foreach (var item in coordinates.Descendants("item"))\n  {\n          string link = item.Element("guid").Value;\n          string description = item.Element("description").Value;\n          string content = item.Element(nsContent + "encoded").Value;\n\n  }	0
17794524	17791475	Retrieving Model MetaData from within a validation attribute	protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n{\n    var model = validationContext.ObjectInstance;\n\n    var displayName = validationContext.DisplayName;\n    var propertyName = model.GetType().GetProperties()\n        .Where(p => p.GetCustomAttributes(false).OfType<DisplayAttribute>().Any(a => a.Name == displayName))\n        .Select(p => p.Name).FirstOrDefault();\n    if (propertyName == null)\n        propertyName = displayName;\n\n    var property = model.GetType().GetProperty(propertyName);\n    var uppercaseAttribute = property.GetCustomAttributes(typeof(UppercaseAttribute), false).SingleOrDefault() as UppercaseAttribute;\n\n    if (uppercaseAttribute != null)\n    {\n        // some code...\n    }\n\n    // return validation result...\n}	0
9838648	9820617	Data binding to EF entities or to ViewModel	ObservableCollection<AuthorViewModel>	0
34280844	34280791	How to constantly check something in WinForms/C#?	private Thread checkThread;\n\nprivate void StartThreadMethod() \n{\n        checkThread = new Thread(new ThreadStart(CheckGameComplete));\n        checkThread.Start(); \n}\n\npublic void CheckGameComplete() \n{\n          // Do the checking here\n          // call checkThread.Stop() once checking is done.\n}	0
21477161	21477056	Atomicty of read/write operation over string in c#	string x = "Hello";\nstring y = x; // This is an atomic operation: Reference assignment.	0
20997522	20997324	How to update Dictionary if it contains item with same key using LINQ?	private static IEnumerable<KeyValuePair<string, object>> FromCookies(HttpCookieCollection cc)\n        {\n            return (from string cookie in cc.AllKeys select new KeyValuePair<string,object>(cookie, cc[cookie]));\n        }	0
7322870	7322816	How do I check if all fields are filled in	void buttonAdd_Click(object sender, EventArgs e)\n{\n    if (string.IsNullOrWhiteSpace(textBoxField.Text))\n    {\n         // Show message?\n         MessageBox.Show(....);\n\n         return; // Don't process\n    }\n\n    // Field has a value, do your thing here...\n\n}	0
5322846	5318030	Change function into dependencyproperty	public static DependencyProperty DownloadPicProperty =\n    DependencyProperty.Register("DownloadPic", typeof(byte[]), typeof(ImageControl));\n\npublic byte[] DownloadPic\n{\n    get { return (byte[])GetValue(DownloadPicProperty); }\n    set { SetValue(DownloadPicProperty, value); }\n}\n\n...\nImageControl imageControl = ...;\nimageControl.DownloadPic = DownloadPicture();	0
16325504	16325467	Convert IEnumerable <T> to LookUp<T,K>	IEnumerable<User> seq = ...;    \nILookup<string, IList<string>> lookup = seq.ToLookup(u => u.UserName, u => u.MemberOf);	0
31710671	31710572	Get Data from Mysql Database to array in C# array out of bounds	List<int> userData = new List<int>();\n    MySqlConnection bag = new MySqlConnection(connstring);\n\n    MySqlCommand cmd = new MySqlCommand("Select readerid From readers",bag);\n\n    bag.Open();\n    MySqlDataReader oku = cmd.ExecuteReader();\n\n    while (oku.Read())\n    {\n    int current = Convert.ToInt32(oku["readerid"]);\n    userData.Add(current);\n\n    listBox1.Items.Add(current);\n    }	0
26996879	26978400	Stop Office Interop Copy/Paste from ignoring region settings	cnt = Regex.Replace(cnt, @"(?<main>\d+)\.(?<decimals>\d{2,3})", "${main},${decimals}").Replace("$", "???");	0
10981565	10981287	C# Array as part of MySQL Select Statement?	string guids = "''" + string.Join("'',''", myArrayList) + "''"; \nstring query = string.format("SELECT * FROM remotetable WHERE NOT id IN ({0})", guids);	0
12429076	12428947	How do I convert a querystring to a json string?	var dict = HttpUtility.ParseQueryString("ID=951357852456&FNAME=Jaime&LNAME=Lopez");\nvar json = new JavaScriptSerializer().Serialize(\n                    dict.AllKeys.ToDictionary(k => k, k => dict[k])\n           );	0
5504091	5468348	How to perform "nslookup host server"	[DllImport("dnsapi", EntryPoint="DnsQuery_W", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]\nprivate static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved);\n[DllImport("dnsapi", CharSet=CharSet.Auto, SetLastError=true)]\nprivate static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);\n\n...	0
3739391	3739369	Data encapsulation in C# using properties	private string _mystring;\npublic string MyString\n{\n  get {return _mystring;}\n  set \n  {\n      if (IsAcceptableInput(value))\n         _mystring = value;\n  }\n}	0
11132875	11132825	ASP.NET MVC Model with a foreign key property	return Name + ((State == null) ? "" : ", " + State.Name);	0
15646273	15645750	How to capture keystroke(s) pressed in certain time period for DataGridView keypress event?	private System.Diagnostics.Stopwatch Watch = new System.Diagnostics.Stopwatch();\nprivate string _KeysPressed;\npublic string KeysPressed\n{\n    get { return _KeysPressed; }\n    set \n    {\n        Watch.Stop();\n        if (Watch.ElapsedMilliseconds < 300)\n            _KeysPressed += value;\n        else\n            _KeysPressed = value;\n        Watch.Reset();\n        Watch.Start();\n    }\n}        \nprivate void KeyUpEvent(object sender, KeyEventArgs e)\n{\n    KeysPressed = e.KeyCode.ToString();\n    if (KeysPressed == "AB")\n        lblEventMessage.Text = "You've pressed A B";\n    else if (KeysPressed == "ABC")\n        lblEventMessage.Text = "You've pressed A B C";\n    else\n        lblEventMessage.Text = "C-C-C-COMBOBREAKER!!!";\n}	0
1132668	1132641	Accessing C# Variable from Javascript?	function showtime() {\n                 zone(\n                      document.getElementById('<%=hiddenZone.ClientID%>'),\n                      clock\n                   );\n            }	0
4129335	4129259	c# ms chart : how do i count how many data points i have?	int numPoints = chart1.Series[0].Points.Count;	0
13084326	13084145	How can I update a Table without refresh the entire site razor	success: function (response){}	0
15713130	15712808	How we can select the value of an <option> in <select> by using text in <option>text<option>	var doc = new HtmlAgilityPack.HtmlDocument();\nHtmlAgilityPack.HtmlNode.ElementsFlags.Remove("option");\ndoc.LoadHtml(html);\n\nvar values = doc.DocumentNode.SelectNodes("//select[@name='selectname']/option")\n                .Where(o => o.InnerText=="text")\n                .Select(o => o.Attributes["value"].Value)\n                .ToList();	0
7846358	7846286	c# finding similar colors	Color nearest_color = Color.Empty;\nforeach (object o in WebColors)\n{\n    // compute the Euclidean distance between the two colors\n    // note, that the alpha-component is not used in this example\n    dbl_test_red = Math.Pow(Convert.ToDouble(((Color)o).R) - dbl_input_red, 2.0);\n    dbl_test_green = Math.Pow(Convert.ToDouble\n        (((Color)o).G) - dbl_input_green, 2.0);\n    dbl_test_blue = Math.Pow(Convert.ToDouble\n        (((Color)o).B) - dbl_input_blue, 2.0);\n\n    temp = Math.Sqrt(dbl_test_blue + dbl_test_green + dbl_test_red);\n    // explore the result and store the nearest color\n    if(temp == 0.0)\n    {\n        nearest_color = (Color)o;\n        break;\n    }\n    else if (temp < distance)\n    {\n        distance = temp;\n        nearest_color = (Color)o;\n    }\n}	0
29062167	29061910	a custom event for pressing the 'Enter key' in C#	public partial class UserControl1 : UserControl {\n    public event EventHandler EnterPressed;\n\n    public UserControl1() {\n        InitializeComponent();\n        textBox1.KeyDown += textBox1_KeyDown;\n    }\n\n    protected void OnEnterPressed(EventArgs e) {\n        var handler = this.EnterPressed;\n        if (handler != null) handler(this, e);\n    }\n\n    void textBox1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyCode == Keys.Enter) {\n            OnEnterPressed(EventArgs.Empty);\n            e.Handled = e.SuppressKeyPress = true;\n        }\n    }\n}	0
9808376	9782689	C# - Capture Output from a Child Window of a new Process	UDK.com make	0
6500454	6500160	How do I convert Paypal's HH:MM:SS DD Mmm(.) YYYY PST/PDT to a C# UTC DateTime?	public static DateTime ConvertPayPalDateTime(string payPalDateTime)\n{\n  // Get the offset.\n  // If C# supports switching on strings, it's probably more sensible to do that.\n  int offset;\n  if (payPalDateTime.EndsWith(" PDT"))\n  {\n     offset = 7;\n  }\n  else if (payPalDateTime.EndsWith(" PST"))\n  {\n     offset = 8;\n  }\n  else\n  {\n    throw some exception;\n  }\n\n  // We've "parsed" the time zone, so remove it from the string.\n  payPalDatetime = payPalDateTime.Substring(0,payPalDateTime.Length-4);\n\n  // Same formats as above, but with PST/PDT removed.\n  string[] dateFormats = { "HH:mm:ss MMM dd, yyyy", "HH:mm:ss MMM. dd, yyyy" };\n\n  // Parse the date. Throw an exception if it fails.\n  DateTime ret = DateTime.ParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);\n\n  // Add the offset, and make it a universal time.\n  return ret.AddHours(offset).SpecifyKind(DateTimeKind.Universal);\n}	0
2434649	2434624	Setting time to 23:59:59	yourDateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59);	0
4504634	4504620	Regular Expressions (.NET) - How can I match a pattern that contains a variable number of digits at the end of the string?	pattern = @"portfolio\d{1,3}"	0
21015957	21015934	How to get text until a symbol in string	String text="acsbkjb/123kbvh/123jh/";\nint index=text.IndexOf('/');  \nString text2="";\n\nif(index>=0)\ntext2=text.Substring(0,index);	0
32764468	32763771	Converting decimal number c#	(0.5m).ToString(".00");\n        (0.15m).ToString(".00");	0
23201600	23200536	Making a jukebox, adding track list to list box from .text file	1 - string[] lines = File.ReadAllLines("firstFile.txt");\n..\n4 - for (int l = 2; l < lines.Length; l++) mediaLibrary[0].Items.Add(lines[l]);	0
14936166	14935995	How do I delete a user with a role in ASP.NET MVC4 SimpleMembership?	void DeleteUserRoles(string username)\n{\n    foreach (var role in Roles.GetRolesForUser(username))\n        Roles.RemoveUserFromRole(username, role);            \n}	0
13217596	13217156	Cropping picture, getting Rectangle from X,Y?	public static Bitmap CropImage(Image source, int x,int y,int width,int height)\n{\n    Rectangle crop = new Rectangle(x, y, width, height);\n\n    var bmp = new Bitmap(crop.Width, crop.Height);\n    using (var gr = Graphics.FromImage(bmp))\n    {\n        gr.DrawImage(source, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);\n    }\n    return bmp;\n}	0
8649312	8649214	Value for XML Root Element is completely wrong, not finding child nodes	string myDataString = @"<allData>\n                          <allDataDetails>\n                            <quoteid>ABC123</quoteid>\n                            <customername>John Smith</customername>\n\n                          </allDataDetails>\n                          <allDataDetails>\n                            <quoteid>DEF456</quoteid>\n                            <customername>Jane Doe</customername>\n\n                          </allDataDetails>\n                        </allData>";\n             XDocument entityXml = XDocument.Parse(myDataString);\n\n\n             var myRows = from d in entityXml.Descendants("allDataDetails")\n                      select new\n                        {\n                            quoteid = d.Element("quoteid").Value\n                            ,customername = d.Element("customername").Value\n                        };\n             foreach (var rw in myRows)\n                 Console.WriteLine(rw.customername + "\t" + rw.quoteid);	0
220957	220828	Only allow one server to access a file on a network drive	FileStream fs = new FileStream(\n  FilePath, \n  FileMode.Open,\n  FileAccess.ReadWrite, \n  FileShare.None\n);	0
22833739	22833306	How to filter names from a table and get the row that we want in C#?	List<User> filtered = User.where(u => u.UserName.ToLower().Contains(FilterString.ToString())).ToList();	0
9211139	9113432	Where to keep dictionaries in app using Dependency Injection	public interface IApplicationService\n    {\n        List<User> Users{get;set;}\n    }\n\n    public class ApplicationService : IApplicationService\n    {\n        public List<User> Users\n        {\n            get { return (App.Current as App).Users; }\n            set { (App.Current as App).Users = value; }\n        }\n    }\n\n    public partial class MainWindow : UserControl\n    {\n        readonly IApplicationService _applicationService\n        public MainWindow(IApplicationService applicationService)\n        {\n            _applicationService=applicationService;\n        }\n    }	0
7092471	7092424	Selected value of DataGridViewComboBoxCell	dgBatch.Value = "selectedValue"	0
9760391	9760351	Updating the content of a code behind generated button	Button myButton;\n\nvoid MakeButtonQ() \n{ \n    Button b2 = new Button(); \n    b2.Content = Class1.Question; \n    b2.Height = 150; \n    b2.Width = 230; \n    b2.Background = new SolidColorBrush(Colors.White); \n    b2.Foreground = new SolidColorBrush(Colors.Black); \n    stackPanel1.Children.Add(b2); \n\n    myButton = b2\n} \n\nvoid ChangeButtonsContent()\n{\n    myButton.Content = "Content changed";\n}	0
12630956	12626651	Accessing data in `RetrieveMultiple`	contact1.fullname	0
27459805	27459756	Displaying enum in the console C#	enum Month\n{\n    January=1,\n    February=2\n}\nstatic void Main(string[] args)\n{\n    Console.WriteLine(((Month)1));\n}	0
19239688	19239587	Get quotient and remainder from array in c#	int[] Numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };\nfloat CalculatedBy = 3.5F;\n\nforeach (int number in Numbers)\n{\n    if (number % CalculatedBy != 0)\n    {\n        int quotient = (int) Math.Floor(number / CalculatedBy);\n        float remainder = number - quotient * CalculatedBy;\n        Console.WriteLine("Value {0}: Result is : Q is {1} and R is {2}", number, quotient, remainder);\n    }\n}	0
34219262	34219191	How to pass parameter to static class constructor?	public class A\n{\n    private static string ParamA { get; set; }\n\n    public static void Init(string paramA)\n    {\n        ParamA = paramA;\n    }\n}	0
6116753	6116709	c# method inside of a class that returns values	public static class drug\n{\n    public static class coc\n    {\n        public const double var1 = 156;\n        public const double var2 = 4;\n        public const double var3 = 8;\n        public const double var4 = 164;\n    }\n    public static class mar\n    {\n        public const double var1 = 234;\n        public const double var2 = 64;\n        public const double var3 = 34;\n        public const double var4 = 342;\n    }\n}	0
6629621	6363883	Two-way data binding with converter doesn't update source	private void mycontrol_LostFocus(object sender, RoutedEventArgs e)\n{\n    if (mycontrol.IsModified)\n    {\n        var binding = mycontrol.GetBindingExpression(MyControl.SampleProperty);\n        binding.UpdateSource();\n    }\n}	0
12873687	12870363	Using common color values between c# and c dll	int value = Color.Red.ToArgb();	0
30175397	30175186	How Can I Manipulate a File Path as a String?	var imagePath = "/ImageFolder/Gallery/AnAlbum/image.jpg";\nvar folder = Path.GetDirectoryName(imagePath);\nvar imageFile = Path.GetFileName(imagePath);\nvar newImageUrl = folder + "/thumb/thumb_" + imageFile;\nreturn newImageUrl;	0
13884726	13876418	Fixing key processing conflict between custom controls, in case of more than one control on a form?	protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)\n    {\n        base.OnPreviewKeyDown(e);\n\n        switch (e.KeyCode)\n        {\n            case Keys.Up:\n            case Keys.Down:\n            case Keys.Left:\n            case Keys.Right:\n                e.IsInputKey = true;\n                break;\n            default:\n                break;\n        }\n    }	0
24068905	24056538	while reading the word document,need to add invisible text into it	Dim par As Paragraph\n\n'set reference to appropriate paragraph\nSet par = ActiveDocument.Paragraphs(2)\n\nDim cc As ContentControl\nSet cc = ActiveDocument.ContentControls.Add( _\n            wdContentControlRichText, par.Range)\n\ncc.Tag = "VERIFIED"\n\n'options\n'disable deletion of CC\ncc.LockContentControl = True\n\n'disable edition of CC\ncc.LockContents = True	0
13095664	13087751	Unrar file with subdirectory	RarArchive archive = RarArchive.Open(@"D:\Archives\Test.rar");\nforeach (RarArchiveEntry entry in archive.Entries)\n{\n    try\n    {\n        string fileName = Path.GetFileName(entry.FilePath);\n        string rootToFile = Path.GetFullPath(entry.FilePath).Replace(fileName, "");\n\n        if (!Directory.Exists(rootToFile))\n        {\n            Directory.CreateDirectory(rootToFile);\n        }\n\n        entry.WriteToFile(rootToFile + fileName, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);\n    }\n    catch (Exception ex)\n    {\n        //handle your exception here..\n    }\n}	0
32953422	32952677	How to select values and key in a Dictionary of lists?	var someLinks = Links.Where(kvp => kvp.Value.Any(ml => ml.TargetUrl == "Some value")) \n                           // all key.value pairs where the Value contains the target URL\n                     .Select(kvp => kvp.Key);   //keys for those values	0
31261495	31261021	How to change the size of label in bar chart	chart.Series[1].Points[0].AxisLabel = "Pursue_Noble_Thoughts";	0
9713251	9713048	skip first row in read of Excel file	DataRow row = dt.Rows[0];\ndt.Rows.Remove(row);\ntechGrid.DataSource = dt;	0
17651445	17651319	DateTime Format Handling	DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);	0
18812993	18812332	getting vertex points of GeometryModel3D to draw a wireframe	MeshGeometry3D mg3 = (MeshGeometry3D)modelScull.Geometry;\n\n    for(int index=0;index<mg3.TriangleIndices.Count; index+=3)\n    {\n        ScreenSpaceLines3D wireframe = new ScreenSpaceLines3D();\n\n        wireframe.Points.Add(mg3.Positions[mg3.TriangleIndices[index]]);\n        wireframe.Points.Add(mg3.Positions[mg3.TriangleIndices[index+1]]);\n        wireframe.Points.Add(mg3.Positions[mg3.TriangleIndices[index+2]]);\n        wireframe.Points.Add(mg3.Positions[mg3.TriangleIndices[index]]);\n\n        wireframe.Color = Colors.LightBlue;\n        wireframe.Thickness = 1;\n\n        Viewport3D1.Children.Add(wireframe);\n    }	0
16062481	16041087	Loading Assemblies into a separate AppDomain in a WindowsAzure WorkerRole	AppDomain currentDomain = AppDomain.CurrentDomain;\nAppDomain BrokerJobDomain = AppDomain.CreateDomain("WorkerPluginDomain" + Guid.NewGuid().ToString(), null,  AppDomain.CurrentDomain.SetupInformation );	0
25308883	25308836	Sort an array of strings as integers but there can be a non integer value	string[] SortedArray = UnsortedArray\n    .OrderBy(z => \n    {\n        int tmp;\n        if (int.TryParse(z, out tmp))   // Take care of culture\n        {\n            return tmp;\n        }\n\n        return int.MinValue;    // Or MaxValue depending if non-numbers should\n                                // be first or last\n    })\n    .ToArray();	0
20922750	20922683	Remove an Item from the ListBox when user Clicks on it	found.Items.Remove(found.SelectedItem);	0
9392949	9392140	How do I access this property from 'code-behind'?	lbSource.SetValue(DragDropManager.AllowDrag, false);	0
4463745	4463550	WPF app.config writing	\Program Files\	0
3033320	3018254	How do I get the User Entered Value in AjaxControlToolkit ComboBox when the enter key is pressed?	//*****************************************************************\n// Fix AjaxToolKit ComboBox Text when Enter Key is pressed bug.\n//*****************************************************************\npublic void FixAjaxToolKitComboBoxTextWhenEnterKeyIsPressedIssue(AjaxControlToolkit.ComboBox _combobox)\n{\n    TextBox textBox = _combobox.FindControl("TextBox") as TextBox;\n    if (textBox != null)\n    {\n        if (_combobox.Items.FindByText(textBox.Text) == null)\n        {\n            _combobox.Items.Add(textBox.Text);\n        }\n            _combobox.Text = textBox.Text;\n        }\n    }\n}	0
29577699	29577465	converting a grayscale image to black and white image in c#	Bitmap bmp = new Bitmap(file);\n int width = bmp.Width;\n int height = bmp.Height;\n int[] arr = new int[225];\n int i = 0;\n Color p;\n\n //Grayscale\n for (int y = 0; y < height; y++)\n {\n     for (int x = 0; x < width; x++)\n     {\n         p = bmp.GetPixel(x,y);\n         int a = p.A;\n         int r = p.R;\n         int g = p.G;\n         int b = p.B;\n         int avg = (r+g+b)/3;\n         avg = avg < 128 ? 0 : 255;     // Converting gray pixels to either pure black or pure white\n         bmp.SetPixel(x, y, Color.FromArgb(a, avg ,avg, avg));\n     }\n }\n pictureBox2.Image = bmp;	0
1061353	966288	How do I Dynamically Load Assemblies Not on Disk into an ASP .Net Web Application?	protected void Page_Load(object sender, EventArgs e)\n{\n   AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);\n   Assembly assembly = Assembly.Load("PhantomAssembly");\n   Type t = assembly.GetType("PhantomAssembly.Test");\n   MethodInfo m = t.GetMethod("GetIt");\n   Response.Write(m.Invoke(null, null));\n   t.GetMethod("IncrementIt").Invoke(null, null);\n}\n\nprivate static Assembly AssemblyResolve(object sender, ResolveEventArgs args)\n{\n   Assembly asssembly = Assembly.Load(File.ReadAllBytes(@"C:\PhantomAssembly.dll"));\n   return asssembly;\n}	0
29339899	29339780	Reading XML giving null	XmlTextReader reader = new XmlTextReader ("<file name>");\n            while (reader.Read()) \n            {\n                switch (reader.NodeType) \n                {\n                    case XmlNodeType.Element:	0
4188937	4188877	Determine Click Once Publish Directory	ApplicationDeployment.CurrentDeployment.ActivationUri	0
11271241	10990732	Change fonts and colors for C# Interactive Window in Visual Studio 2012 RC with Roslyn June 2012 CTP	Roslyn - Interactive Window Error Output\nRoslyn - Interactive Window Output	0
2584449	2584384	LINQ: Select Elements that Only Appear Once in a List	int[] arr = { 2, 3, 4, 5, 8, 2, 3, 5, 4, 2, 3, 4, 6 };\nvar q =\n    from g in arr.GroupBy(x => x)\n    where g.Count() == 1\n    select g.First();	0
30397622	30397468	How do graphing applications calculate viewing area?	var margin = 0.1; (ten percent of data range)\nvar ymin = data.min();\nvar ymax = data.max();\nvar data_range = abs(ymax - ymin);\nvar y_plot_min = ymin - data_range * margin;\nvar y_plot_max = ymax + data_range * margin;\nset_plot_y_limits(y_plot_min, y_plot_max);	0
9407152	9407083	Variable access from Form1 to From2	public class Form1\n{\n  public decimal Total {get; set;}\n}\n\npublic class Form2\n{\n  public Form2()\n  {\n    var form1 = new Form1();\n    form1.Show();\n\n    ..later, after use has done some work and you need the variable\n    var total = form1.Total;\n  }\n}	0
2655842	2655799	How to disable ListView navigation through keyboard	private void listView1_PreviewKeyDown(object sender, KeyEventArgs e)\n    {\n        e.Handled = true;\n    }	0
24592801	24592759	How can I automatically produce one depolyment directory from multiple projects	%windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe MySolution.sln /p:OutputPath="c:\foo"	0
27984133	27983959	DataTable object initializer with Primary Key	private DataTable _products;\n\npublic void ClassName()\n{\n    _products = new DataTable\n    {\n        Columns = { { "Product", typeof(string) }, { "Lot", typeof(string) }, { "Qty", typeof(int) } }\n    };\n    _products.PrimaryKey = new[] { _products.Columns[0] };\n}	0
31531295	31531254	How to use foreach for two c# listbox?	for (int i = 0; i < listBox2.Items.Count; i++)\n{\n    try\n    {\n        messagebox(listBox2.Items[i]);        \n        messagebox(listBox1.Items[i]);\n    }\n    catch (Exception) { }\n}	0
24295266	24149844	Capture two blocks in a string	int descriptionBegin = 0;\nint descriptionEnd = 0;\nint messageBegin = 0;\nint messageEnd = 0;\nforeach (string j in errorList)\n{\n    descriptionBegin = j.IndexOf("<Description>") + 13; // starts after the opening tag\n    descriptionEnd = j.IndexOf("</Description>") - 13; // ends before the closing tag\n    messageBegin = j.IndexOf("<Message>") + 9; // starts after the opening tag\n    messageEnd = j.IndexOf("</Message>") - 9; // ends before the closing tag\n    descriptionDiff = descriptionEnd - descriptionBegin; // amount of chars between tags\n    messageDiff = messageEnd - messageBegin; // amount of chars between tags\n    string description = j.Substring(descriptionBegin, descriptionDiff); // grabs only specified amt of chars\n    string message = j.Substring(messageBegin, messageDiff); // grabs only specified amt of chars\n}	0
16384470	16365040	Verify method called with parameter and call order	[TestClass]\n    public class TestMethodParam\n    {\n        [TestMethod]\n        public void TestMethod1()\n        {\n            var repairCarCalls = new List<string>();\n            Mock<ICarService> carService = new Mock<ICarService>();\n\n            var car = new Car\n            {\n                Name = "1"\n            };\n\n            var car2 = new Car\n            {\n                Name = "2"\n            };\n\n            carService.Setup(c => c.RepairCar(It.IsAny<Car>())).Callback<Car>(c => repairCarCalls.Add(c.Name));\n\n            var carManager = new CarManager(carService.Object);\n\n            //act\n            carManager.Serve();\n\n            //assert: \n            var expectedCalls = new[] { car.Name, car2.Name };\n            CollectionAssert.AreEqual(expectedCalls, repairCarCalls);\n        }\n    }	0
19774551	19751804	Is there any english language grammar set in Speech Recognition in Windows Phone 8	// Load the pre-defined dictation grammar by default\n  // and start recognition.\n  SpeechRecognitionUIResult recoResult = await recoWithUI.RecognizeWithUIAsync();\n\n  // Do something with the recognition result\n  MessageBox.Show(string.Format("You said {0}.", recoResult.RecognitionResult.Text));	0
13777509	13777037	Color cells of a matrix with 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;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        protected override void OnPaint(PaintEventArgs e)\n        {\n            base.OnPaint(e);\n\n            for (int x = 0, y = 0; x + y != (this.Width + this.Height); x++)\n            {\n                var color = Color.Red;\n                if (x % 2 == 0 && y % 2 != 0) { color = Color.Blue; }\n\n                e.Graphics.FillRectangle(new SolidBrush(color), x, y, 1, 1);\n\n                if (x == this.Width)\n                {\n                    x = -1;\n                    y++;\n                }\n            }\n        }\n    }\n}	0
658317	658303	How to get image with its name and any extension?	string imageFilename = System.IO.Directory.GetFiles( imageDirectory, name + ".*" ).First();	0
13071026	13069137	How to set tooltip for a ListviewSubItem	ToolTip     mTooltip;\n    Point mLastPos = new Point(-1, -1);\n\n    private void listview_MouseMove(object sender, MouseEventArgs e)\n    {\n        ListViewHitTestInfo info    =   mLV.HitTest(e.X, e.Y);\n\n\n        if (mLastPos != e.Location)\n        {\n            if (info.Item != null && info.SubItem != null)\n            {\n                mTooltip.ToolTipTitle = info.Item.Text;\n                mTooltip.Show(info.SubItem.Text, info.Item.ListView, e.X, e.Y, 20000);\n            }\n            else\n            {\n                mTooltip.SetToolTip(mLV, string.Empty);\n            }\n        }\n\n        mLastPos = e.Location;\n    }	0
15117731	15117654	How to check if a zip file is not in use by another process before downloading	public class FileManager\n{\n    private string _fileName;\n\n    private int _numberOfTries;\n\n    private int _timeIntervalBetweenTries;\n\n    private FileStream GetStream(FileAccess fileAccess)\n    {\n        var tries = 0;\n        while (true)\n        {\n            try\n            {\n                return File.Open(_fileName, FileMode.Open, fileAccess, Fileshare.None); \n            }\n            catch (IOException e)\n            {\n                if (!IsFileLocked(e))\n                    throw;\n                if (++tries > _numberOfTries)\n                    throw new MyCustomException("The file is locked too long: " + e.Message, e);\n                Thread.Sleep(_timeIntervalBetweenTries);\n            }\n        }\n    }\n\n    private static bool IsFileLocked(IOException exception)\n    {\n        int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);\n        return errorCode == 32 || errorCode == 33;\n    }\n\n    // other code\n\n}	0
14417311	14417268	Change namespaces at once	Refactor .. Adjust Namespaces	0
4125848	4125217	WHERE IN CLAUSE for LINQ to XML	var filter = new List<string> {"1", "2", "4"};\n\nvar query = from p in barcode.Descendants("BAR_CODE")\n            where filter.Contains(p.Value)\n            select p.Value;	0
24312115	24312033	How can i display each new image in pictureBox1?	private void timer1_Tick(object sender, EventArgs e)\n{\n      count++;\n      string fileName = mainDirectory + count.ToString("D6") + ".jpg";\n      sc.CaptureScreenToFile(fileName , System.Drawing.Imaging.ImageFormat.Jpeg);\n      sc.CaptureScreen();\n      label2.Text = count.ToString();\n      if (count == 1)\n      {\n          label4.Text = string.Format("{0:N2} KB", GetFileSizeOnDisk(fileName).ToString());\n          label4.Visible = true;\n      }    \n      pictureBox1.ImageLocation =  fileName;   \n}	0
27227014	27192859	How to get information about current user distribution list from outlook using WPF business app	private List<string> GetCurrentUserMembership()\n    {\n        Outlook.Application outlook = new Outlook.Application();\n        Outlook.MailItem oMsg = (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);\n        Outlook.Inspector oInspector = oMsg.GetInspector;\n\n        //session.Logon("", "", false, false);\n        var sb = new List<string>();\n        Outlook.AddressEntry currentUser = outlook.Session.CurrentUser.AddressEntry;\n        if (currentUser.Type != "EX") return sb;\n\n        var exchUser = currentUser.GetExchangeUser();\n\n        if (exchUser == null) return sb;\n\n        var addrEntries = exchUser.GetMemberOfList();\n        if (addrEntries == null) return sb;\n\n        foreach (Outlook.AddressEntry addrEntry in addrEntries)\n        {\n            sb.Add(addrEntry.Name);\n        }\n        return sb;\n\n    }	0
6906455	6906397	Sorting array of formatted time strings	Array.Sort(timeSplit, delegate(string first, string second)\n{\n    return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));\n});	0
400777	400733	How to get ASCII value of string in C#	string value = "9quali52ty3";\n\n// Convert the string into a byte[].\nbyte[] asciiBytes = Encoding.ASCII.GetBytes(value);	0
22411243	22389820	Change SeriesChartType color like Window task manager	Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click\n\n    //Add an area chart to go under your line series\n    Chart1.Series.Add("UnderSeries")\n    Chart1.Series(0).BorderWidth = Chart1.Series(0).BorderWidth + 2\n    Chart1.Series("UnderSeries").ChartType = SeriesChartType.Area\n\n    //To create a semi transparent color, set alpha to 127. \n    //To create a transparent color, set alpha to any value from 1 through 254.\n    Chart1.Series("UnderSeries").Color = Color.FromArgb(127, Color.Aqua)\n\n    //place area chart over your line\n    For Each pt As DataPoint In Chart1.Series(0).Points\n        Chart1.Series("UnderSeries").Points.AddXY(pt.XValue, pt.YValues(0))\n    Next\n\n    //reorder series so line is above area chart\n    Dim topSeries As Series = Chart1.Series(0)\n    Chart1.Series.Remove(topSeries)\n    Chart1.Series.Add(topSeries)\n\nEnd sub	0
28420620	28419389	WPF XAML two buttons that change webbrowser url on a different window	((MainWindow)App.Current.MainWindow).webBrowser1.Navigate(new Uri("http://address1.com"));	0
1638764	1638669	How to get "Host:" header from HttpContext (asp.net)	string requestedDomain = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];\nstring requestScheme = HttpContext.Current.Request.Url.Scheme;\nstring requestQueryString = HttpContext.Current.Request.ServerVariables["QUERY_STRING"];\nstring requestUrl = HttpContext.Current.Request.ServerVariables["URL"];	0
5539887	5539854	How to click a button through coding?	protected void ButtonA_Click(...)\n{\n    DoWork();\n}\n\nprotected void ButtonB_Click(...)\n{\n    // do some extra work here\n    DoWork();\n}\n\nprivate void DoWork()\n{\n    // do the common work here\n}	0
30363384	30363233	How use bitmask operator	int[] elem = new int[] { 1, 2, 3 };\ndouble maxElem = Math.Pow(2, elem.Length);\n\nfor (int i = 0; i < maxElem; first++)\n{\n    for (int run = 0; run < elem.Length; run++)\n    {\n        int mask = 1, sum = 0;\n        if ((i & mask) > 0) // ADD THIS LINE\n        {\n            sum += elem[run];                    \n        }\n        mask <<= 1;\n    }\n}	0
10419025	10389319	Mocking a method with conditional arguments using Moq	It.Is<string>(a => Equals(a, "foo2.txt"))	0
6885193	6885169	How to find max value in a column in a datarow[] ?	int roomno = roomCollection.Max (r => (int) r["room"]);	0
5491092	5491061	Compare ticks to date time (5 mins from now)	if( new DateTime(ticks) > DateTime.Now.AddMinutes(5))\n   return false;\nelse return true;	0
31229663	25997874	How to find and click links/buttons by href? (GeckoFx browser)	GeckoElementCollection fblikes = webBrowser.Document.GetElementsByTagName("a");\n            foreach (GeckoHtmlElement item in fblikes)\n            {\n                string aux = item.GetAttribute("href");\n                if (aux != null && aux != "" && aux.Equals("p.php?p=facebook"))\n                {\n                    item.Click();\n\n                }\n            }	0
15576849	15576761	cancelling a function	class Program\n{\n    static void Main(string[] args)\n    {\n        var token = new CancellationTokenSource();\n        var t = Task.Factory.StartNew(\n            o =>\n            {\n                while (true)\n                    Console.WriteLine("{0}: Processing", DateTime.Now);\n            }, token);\n\n        token.CancelAfter(1000);\n        t.Wait(token.Token);\n    }\n}	0
14644566	14644494	Changing the state of check box in grid view	void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n  if (e.Row.RowType == DataControlRowType.DataRow)\n  {\n       CheckBox chk = (CheckBox)e.Row.FindControl("chkBoxID");\n       if(DataBinder.Eval(e.Row.DataItem, "datasourceColumnName").ToString() == "someval")\n             chk.Enabled = false;\n  }\n}	0
18014025	18013932	How to force Windows Phone 8 to re-load data from server	string site = "http://192.168.1.17:5465/MessagesWCF/Messages.svc/Test?nocache=" + Guid.NewGuid();	0
17271534	16960235	Localizing a Windows Foundation Workflow service	resources.GeneralStrings.Timeout	0
2766957	2765751	how do i know how many clients are calling my WCF service function	public class ConsoleOutputMessageInspector : IDispatchMessageInspector\n{\n    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)\n    {\n         Console.WriteLine("Starting call");\n         // count++ here\n         return null;\n    }\n\n    public void BeforeSendReply(ref Message reply, object correlationState)\n    {\n        // count-- here\n        Console.WriteLine("Returning");\n    }\n}	0
22358678	22358368	How to get Line-s from Canvas Children in WPF	foreach(var child in Canvas.Children)\n{\n    var l = child as Line;\n    if(l != null && (l.X1 < mx1 && lX2 > mx2) && (l.Y1 < my1 && lY2 > my2))\n    {\n        // You can't remove item from collection you enumerate thru\n        // Canvas.Children.Remove(l);\n        LinesToDelete.Add(l);\n    }\n}	0
14315433	14315290	How to find Requiredfieldvalidator	if (_clients.ReferenceRequired == true)\n   {\n        RequiredFieldValidator1.ValidationGroup = "Ac";\n        AutoCompleteExtender7.ValidationGroup= "Ac";\n    }\n    else\n    {\n        RequiredFieldValidator1.ValidationGroup = "none";\n        AutoCompleteExtender7.ValidationGroup = "none";\n    }	0
32402008	32384307	How to Serialize the fingerprint of Digital Persona in C# and saved to a database	tempFingerPrint = Fmd.SerializeXml(resultConversion.Data);	0
22542681	22542524	Convert Datetime String to Datetime in Original Timezone	DateTimeOffset dto = DateTimeOffset.ParseExact("20110316 11:03:22.276919 -0400s", @"yyyyMMdd HH\:mm\:ss\.FFFFFF zzz\s", null);\nConsole.WriteLine(dto.DateTime);	0
14410022	14409988	How can I add a message to an exception without losing any information in C#?	ex.InnerException	0
5276518	5259800	Where to set up AutoMapper to convert asmx proxy objects to domain objects?	var request = Mapper.Map<DomainObject, ServiceReferenceObject>(requestDomainObject);\nvar result = ws.DoSomething(request);\nvar resultDomainObject = Mapper.Map<ServiceReferenceObject, DomainObject>(result);	0
20032476	20032450	Detect if a string contains uppercase characters	fullUri.Any(c => char.IsUpper(c));	0
710533	710508	How best to loop over a batch of Results with a C# DbDataReader	do {\n   while (reader.Read()) {\n      if (!reader.IsDBNull(0)) {\n         //do things with the data....\n      }\n   }\n} while (reader.NextResult());	0
7241121	7241027	EF 4.1 - Problem accessing DB from same app on different machines	Database.SetInitializer<YourDataContext>(null);	0
29628931	29628647	How to write tsql search function with a variable or unknown amount of parameters?	CREATE FUNCTION [dbo].[Search]\n(\n    @firstname VarChar(50),\n    @lastname VarChar(80),\n    @userId VarChar(50),\n    @vehicle VarChar(50)\n)\nRETURNS @returntable TABLE\n(\n    firstname VarChar(50),\n    lastname VarChar(80),\n    userId VarChar(50),\n    vehicle VarChar(50),\n    passengers VarChar(50)\n)\nAS\nBEGIN\n    INSERT @returntable\n    SELECT * FROM Drivers\n    Where (@firstname IS NULL OR firstname = @firstname) AND \n          (@lastname IS NULL OR lastname = @lastname) AND  \n          (@userId IS NULL OR userid = @userId) AND \n          (@vehicle IS NULL OR vehicle = @vehicle)\nRETURN\nEND	0
24539071	24538837	Marshaling C++ struct with fixed size array into C#	[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]\n  public byte[] AnArray;	0
28654427	28650841	How can I add more buttons for other actions without messing up my virtual joystick?	void Update() \n{\n    int i = 0;\n    while (i < Input.touchCount)\n    {\n        if (Input.GetTouch(i).position.x > joystick_center.x - 150 && Input.GetTouch(i).position.x < joystick_center.x + 150)\n        {\n            if (Input.GetTouch(i).phase != TouchPhase.Ended && Input.GetTouch(i).phase != TouchPhase.Canceled && playerDataScript.playerStatus == "alive")\n            {\n\n                //joystick movement code\n\n            } else {\n                // reset joystick movement\n            }\n        }\n\n        ++i;\n    }\n}	0
29447900	29445262	Get row number for selected item from list view c#	private void ListView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (ListView1.SelectedIndex > -1)\n    {\n        // Add 1 so you have 1 - 10 instead of 0 - 9\n        int rowNumber = ListView1.SelectedIndex + 1;\n\n        // Your example says you want to delete the selected index\n        // so you still would want to use the selected index\n        ListView1.Items.RemoveAt(ListView1.SelectedIndex);\n\n        // After you remove the item, this method will fire again\n        // but the selected index will be -1 so none of this code will\n        // execute again.\n    }\n}	0
12932946	12932932	sort of the flow order	return _Repository.GetAll().Select(x => x.Name)\n                           .OrderBy(r => r)\n                           .Distinct()\n                           .ToList();	0
21580225	21537528	Infragistics XamDataChart - Column X Labels - half showing up	catX.Interval = 1;	0
12272955	12272459	How to display the current camera resolution on screen	Deployment.Current.Dispatcher.BeginInvoke( ()=> { resolutionValueTextBlock.Text = "resolution: " + camera.Resolution.ToString(); });	0
26364227	26363460	EF relationship to slow changing dimension	public class a_b_relationship \n{\n  public a_b_relationship_id(table_a a, table_b b)\n  {\n    table_a = a;\n    table_b = b;\n    ValidTime(20);\n  }\n\n  public int a_b_relationship_id { get; set; }\n  public int table_a_id { get; set; }\n  public int table_b_id { get; set; }\n  public DateTime valid_from { get; set; }\n  public DateTime valid_to { get; set; }\n\n  public virtual IEnumerable<table_a> table_as { get; set; }\n  public virtual IEnumerable<table_b> table_bs { get; set; }\n\n\n  private void ValidTime(int validMinutes)\n  {\n    valid_from = DateTime.Now();\n    valid_to = DateTime.Now().AddMinutes(validMinutes);\n  }\n}	0
11672419	11672237	Using datatable as datasource in micrsosoft report viewer	this.reportViewer.LocalReport.DataSources.Clear(); \nDataTable dt = new DataTable(); \ndt = this.inputValuesTableAdapter.GetData();     \n\nMicrosoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt); \n\nthis.reportViewer.LocalReport.DataSources.Add(rprtDTSource); \nthis.reportViewer.RefreshReport();	0
1995192	1995157	Viewing JSON output in a simple WCF rest service	Content-type: application/json	0
3083782	3083327	How to implement an IN clause in LinQ	var output = machines.Where(machine => \n     machine.ProductionToolsLink\n     .Any(link => tools.Select(tool => tool.code).Contains(link)));	0
3748620	3748603	Get Bitmap Handle (IntPtr) from byte[] using C# .net	new Bitmap( new MemoryStream(bytes)).GetHbitmap()	0
9947306	9946972	How to get the name of the token	{"20120101":{ "name":"Jeff", "Status":"Sleepy", "Weight":212}, { "name":"Cathy", "Status":"Angry", "Weight":172}}	0
6140402	6137770	Fix Graphics draw area size	public class Scanner : Panel\n{\n    private Image _scanner;\n\n    public Scanner()\n    {\n        this.SetStyle(ControlStyles.ResizeRedraw, true);\n\n        CreateScanner();\n    }\n\n    private void CreateScanner()\n    {\n        Bitmap scanner = new Bitmap(300, 300);\n        Graphics g = Graphics.FromImage(scanner);\n\n        g.DrawEllipse(Pens.Green, 25, 25, 250, 250);\n\n        g.Dispose();\n        _scanner = scanner;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n\n        int shortestSide = Math.Min(this.Width, this.Height);\n\n        if (null != _scanner)\n            e.Graphics.DrawImage(_scanner, 0, 0, shortestSide, shortestSide);\n    }\n\n}	0
3128324	3128204	how detect caller id from phone line?	TTAPI tapi = new TTAPI();\n\ntapi.TE_CALLINFOCHANGE += (sender, e) =>\n{\n    if (e.Cause == CALLINFOCHANGE_CAUSE.CIC_CALLERID)\n    {\n        Console.WriteLine(e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNUMBER));\n        Console.WriteLine(e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNAME));\n    }\n}\n\ntapi.Initialize();\n\n// ...\n// Keep the TAPI object in memory so it can listen for events\n// ...\n\ntapi.ShutDown();	0
19545028	19544951	How can I unselect text after it has been highlighted?	rtb.Selection.Select(rtb.Selection.Start, rtb.Selection.Start);	0
10263303	10260525	Combining observables	loadLocal(id)\n    .Where(x => x != null)\n    .Concat(Observable.Defer(() => loadServer(id)))\n    .Take(1);	0
33792590	33792350	Remove characters before reaching a set of wanted characters in a string	string s = "b\0OU0IDBGR9247884874<<<<<<<<<<<<<<<|8601130M1709193BGR8601138634<3|IVANOV<";\ns = string.Join("", Regex.Split(s, "(ID|I<|P<|V<|VI)").Skip(1));	0
30019877	30019861	How to return a single value from a database?	return context.Users.Where(x => x.Username.Equals(username) && \n    x.Password.Equals(password))\n    .Select(x => x.UserID)\n    .First(); // or FirstOrDefault(); // or .Single();	0
28108800	28108764	Creating a function to handle generic types of data items and convert to list	public List<T> CreateList<T>(T item)\n{\n  List<T> list = new List<T>{item};\n  //or\n  //list.Add(item);\n  return list;\n}	0
10056588	10050145	how do i loop through each readlistviewitem, check the value, and set it to bold?	protected void ResultItem_DataBound(object sender, RadListViewItemEventArgs e)\n    {        \n        var dItem = e.Item as RadListViewDataItem;\n        var dObj = dItem.DataItem as QT.FullTicket;\n        //if no read date, mark as unread (bold)\n        if (dObj.AssigneeView == null)\n        {            \n            var headerLabel = e.Item.FindControl("lblHeader") as Label;\n            headerLabel.Style.Add("Font-Weight", "Bold");\n            headerLabel.Style.Add("Color", "Orange");\n        }\n    }	0
10395009	10391957	How to Override Children.Add method of Canvas class in WPF	public void Add(UserControl element)\n{\n    bool alreadyExist = false;\n    element.Uid = element.Name;\n    foreach (UIElement child in this.Children)\n    {\n        if (child.Uid == element.Uid)\n        {\n            alreadyExist = true;\n            this.BringToFront(child);\n        }\n    }\n    if (!alreadyExist)\n    {\n        this.Children.Add(element);\n        this.UpdateLayout();\n        double top = (this.ActualHeight - element.ActualHeight) / 2;\n        double left = (this.ActualWidth - element.ActualWidth) / 2;\n        Canvas.SetLeft(element, left);\n        Canvas.SetTop(element, top);\n    }\n}	0
16729675	16729308	Advice on using the latest .Net technologies, for developing a new web based application	end of life	0
26924319	26890837	How to add a result tolerance to a NUnit TestCase	[TestCase(0, -17.778, .005)]\n[TestCase(50, 10, 0)]\npublic void FahrenheitToCelsius2(double fahrenheit, double expected, double tolerance)\n{\n    double result = (fahrenheit - 32) / 1.8;\n    Assert.AreEqual(expected, result, tolerance);\n}	0
29512883	29411663	How to calculate the difference of pitch and yaw anlges in two adjacent frames	oldFrame = (FaceTrackFrame)frame.Clone();	0
9738360	9738318	BeginInvoke fails because a window handle has not been created	private void FireFileCountChanged() {\n    if (FileCountChanged != null && this.IsHandleCreatedHandle)\n        BeginInvoke(new DeferEvent(FireFileCountChangedDeferred), 2);\n}	0
33589357	33588980	C# Changing Label Text to Listbox Selection Text	private void instanceSelection_SelectedIndexChanged(object sender, EventArgs e)\n        {\n\nif(instanceSelection.SelectedIndex > -1)\n     instanceTxt.Text = instanceSelection.Items[instanceSelection.SelectedIndex].ToString();\n        }	0
2326439	2325997	Effect To Show Panel in C#.net	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n      timer1.Interval = 16;\n      timer1.Tick += new EventHandler(timer1_Tick);\n      panel1.BackColor = Color.Aqua;\n      mWidth = panel1.Width;\n\n    }\n    int mDir = 0;\n    int mWidth;\n    void timer1_Tick(object sender, EventArgs e) {\n      int width = panel1.Width + mDir;\n      if (width >= mWidth) {\n        width = mWidth;\n        timer1.Enabled = false;\n      }\n      else if (width < Math.Abs(mDir)) {\n        width = 0;\n        timer1.Enabled = false;\n        panel1.Visible = false;\n      }\n      panel1.Width = width;\n    }\n\n    private void button1_Click(object sender, EventArgs e) {\n      mDir = panel1.Visible ? -5 : 5;\n      panel1.Visible = true;\n      timer1.Enabled = true;\n    }\n  }	0
6861142	6860602	Json.Net: JsonSerializer-Attribute for custom naming	[JsonProperty(PropertyName = "Myname")]	0
17110465	17110244	Regex Pattern for filter out anything that doesn't Match	string matchedText = null;\nvar match = Regex.Match(myString, @"MV:[0-9]+");\nif (match.Success)\n{\n    matchedText = Value;\n}\nConsole.WriteLine((matchedText == null) ? "Not found" : matchedText);	0
12073582	12039099	NHibernate matching property as a substring	foreach Name in Politicians FeedEntry.Content.Contains(Name)	0
1517592	1517586	How do I replace all the spaces with %20 in C#	System.Web.HttpUtility.UrlEncode(string url)	0
9733838	9733607	C# extension methods as control default value causes design window to error	this.dateTimePicker1.Value = DateTime.Today.NextDay();	0
7300695	7300649	access control value in all rows GridView	foreach (GridViewRow row in grvPhoneType.Rows) {\n string  PhoneNumber = (((row.cells(0).FindControl("txtPhoneNo")) as TextBox).Text);\n // Do what ever with PhoneNumber\n   }	0
34133541	34133213	Converting Nanoseconds to Datetime	long nanoseconds = 1449491983090000000;\nDateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\nDateTime result = epochTime.AddTicks(nanoseconds / 100);	0
18856316	18856252	DataGridView not showing Columns/Data	dataGridView1.DataSource = ds;\ndataGridView1.DataMember = ds.Tables[0].TableName;\n//or if you want to use DataTable as DataSource for your grid\ndataGridView1.DataSource = ds.Tables[0];	0
9750227	9750201	How can I block return button?	e.Cancel = true;	0
32852221	32851968	How can I get 100% CPU saturation with simple WCF app?	for (int cont = 0; cont < 100; i++)\n{\n    ThreadPool.QueueUserWorkItem(new WaitCallback((a) =>\n    {\n        while (true) \n        { \n        }\n    }));\n}	0
33644912	33644803	Cannot configure timeout from connection string	using (var command = new SqlCommand("dbo.test", connection) {    \nCommandType = CommandType.StoredProcedure })\n{\n      connection.Open();\n      Console.WriteLine("ConnectionTimeout: {0}", \n      connection.ConnectionTimeout);\n      command.CommandTimeout = 120;\n      command.ExecuteNonQuery();\n      Console.WriteLine("Finished");\n      connection.Close();\n}	0
19011658	19011556	DataRow - How to cancel adding row to datatable?	....\n    foreach (string column in columns)\n        {\n            if (row["Name"] == "")\n            {\n                row = null;\n                break; //--> Add this line\n            }\n            else\n            {\n                row[column] = cell;\n            }\n        }\n....	0
10119535	10115975	MonoTouch.Dialog: Setting Image of StyledStringElement in Background	myElement.Image = PlaceHolderImage;\nThreadPool.QueueUserWorkItem ((v) =>\n{\n    var image = GetImageFromSomeFunctionThatWillTakeTime ();\n    BeginInvokeOnMainThread (() =>\n    {\n        myElement.Image = image;\n        myRoot.ReloadData ();\n    });\n});	0
15171360	15060513	Automagical Outlook 365 Credentials	CredentialCache.DefaultCredentials	0
25397401	25397274	How to fire OnSelectedIndexChanged of GridView using c# code	grid1.DataSource = versions.DefaultView;\ngrid1.SelectedIndex = 0;\ngrid1.DataBind();\n\ngrid1_SelectedIndexChanged(grid1, new EventArgs());	0
3024681	3009417	What's the best way to implement one-dimensional collision detection?	switch_on ( 0 ), ( length: 8 ), switch_on ( 1 ), // x = zero here \nsegment ( length: 8 ), switch_off ( 0 ),\nsegment ( length: 8 ), switch_off ( 1 ),\nsegment ( length: 488 ), switch_on ( 2 ),\nsegment ( length: 8 ), switch_on ( 3 ),\nsegment ( length: 8 ), switch_off ( 2 ),\nsegment ( length: 8 ), switch_off ( 3 ),\n...	0
21359860	21359680	Create 2D array of custom objects from XML	a = (int)cols.Element("a"),\nb = (int)cols.Element("b"),\nc = (int)cols.Element("c"),\nd = (int)cols.Element("d")	0
9944388	9944293	Excluding items from a list by object property	public class Item\n{\n    public int Id { get; set; }\n}\n\nclass ItemComparer : IEqualityComparer<Item>\n{\n    public bool Equals(Item x, Item y)\n    {    \n        if (Object.ReferenceEquals(x, y)) return true;\n\n        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))\n            return false;\n\n        return x.Id == y.Id;\n    }\n\n    public int GetHashCode(Item value)\n    {\n        if (Object.ReferenceEquals(value, null)) return 0;\n\n        int hash = value.Id.GetHashCode();\n\n        return hash;\n    }\n\n}	0
17151078	17106514	C# XML nullable attribute	[XmlAttribute(AttributeName = "action")]\n    public EAction Action\n    {\n        get;\n        set;\n    }\n\n    public bool ShouldSerializeAction()\n    {\n        return this.Action != EAction.None;\n    }	0
17745009	17744910	C# How to prevent the event handler assigned to multiple controls being called twice?	private void radio_checked(object sender, EventArgs e)\n{\n    //Check if this is a radio button. It might be a checkbox!\n    if(sender is RadioButton)\n    {\n        RadioButton btn = (RadioButton)sender;\n        if(btn.Checked)\n            Console.WriteLine("{0} Radio checked!", btn.Text);\n    }\n}	0
4774169	4774062	Convert Sum to an Aggregate product expression	public static class MyExtensions\n{\n    public static double Product(this IEnumerable<double?> enumerable)\n    {\n        return enumerable\n          .Aggregate(1.0, (accumulator, current) => accumulator * current.Value);\n    }\n}	0
10289043	10288654	How to traverse the list view column	private void InsertOrUpdateItem(ListView listView, string[] saLvwItem)\n    {\n        if (saLvwItem == null || saLvwItem.Length < 4)\n        {\n            return;\n        }\n\n        bool bFound = false;\n        foreach (ListViewItem lvi in listView.Items)\n        {\n            if (lvi.SubItems[2].Text == saLvwItem[2])\n            {\n                // item already in list\n                // increase the ItemNumber\n                lvi.SubItems[1].Text = (Convert.ToInt32(lvi.SubItems[1].Text) + Convert.ToInt32(saLvwItem[1])).ToString();\n                bFound = true;\n                break;\n            }                \n        }\n\n        if (!bFound)\n        {\n            // item not found\n            // create new item\n            ListViewItem newItem = new ListViewItem(saLvwItem);\n            listView.Items.Add(newItem);\n        }\n\n    }	0
26206497	26206367	How can I print the contents of a WebBrowser control?	private void PrintHelpPage()\n{\n    // Create a WebBrowser instance. \n    WebBrowser webBrowserForPrinting = new WebBrowser();\n\n    // Add an event handler that prints the document after it loads.\n    webBrowserForPrinting.DocumentCompleted +=\n        new WebBrowserDocumentCompletedEventHandler(PrintDocument);\n\n    // Set the Url property to load the document.\n    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");\n}\n\nprivate void PrintDocument(object sender,\n    WebBrowserDocumentCompletedEventArgs e)\n{\n    // Print the document now that it is fully loaded.\n    ((WebBrowser)sender).Print();\n\n    // Dispose the WebBrowser now that the task is complete. \n    ((WebBrowser)sender).Dispose();\n}	0
3246561	3246509	Iterate textboxes in order by name, inside a tab control	public IEnumerable<Control> GetChildrenRecursive(Control parent)\n{\n    var controls = new List<Control>();\n    foreach(Control child in parent.Controls)\n        controls.AddRange(GetChildrenRecursive(child));\n    controls.Add(parent); //fix\n    return controls;\n}\n\nTextBox[] textboxes = GetChildrenRecursive(this)\n       .OfType<TextBox>().OrderBy(i => i.Name).ToArray();	0
23273180	23272271	Make a query dynamically depending on ComboBox choice	string agentsValue = string.empty;\nif (!comboq1.Text.equals(string.empty))\n{ agentsValue = "Agents."+comboq1.text; }\nif (!agentsValue.equals(string.empty))\n{ agentsValue +=","; }\nif (!comboq2.Text.equals(string.empty))\n{ \nif (agentsValue.equals(string.empty))\n{ agentsValue = "Agents."+comboq2.text; }\nelse\n{ agentsValue += "Agents."+comboq2.text; }\n}	0
9349993	9349822	Clashing Bookings Comparing DateTimes using CompareTo	bool clashing = (OldBookingTime_Start <= NewBookingTime_End)\n             && (NewBookingTime_Start >= OldBookTime_End);\n\nAvailable = !clashing;	0
5656317	5656296	passing a List<{Anon:string}> to a function in C#	var list = new List<MyClass>();\nvar myStringList = (from myClass in list\n              select myClass.StringField).ToList();\nvar processedStrings = processStrings(myStringList);	0
30201724	30201690	Giving out even Numbers from 0-100 without using a Modulo-Operator with a for-loop in a c# Console	for(int i = 0; i <= 100; i += 2)\n{\n     // Only even numbers in i\n}	0
20082135	20081894	Is it possible to create a RESTful WCF service as JSON passthrough not declaring ServiceKnownType	[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]\npublic Stream SomeMethod(......)\n{\n    //Call other WS  and get the Json response\n\n    var data = new MemoryStream(Encoding.UTF8.GetBytes(json));\n    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";\n    WebOperationContext.Current.OutgoingResponse.ContentLength = data.Length;\n\n    return data;\n}	0
12706879	12706716	Split information from a database-column to Text and Numbers	string address = "Streetname 44";\n\nvar index = address.LastIndexOf(' ');\n\nvar houseNo = address.Substring(index + 1);\nvar streetName = address.Remove(index);	0
2997924	2997883	How to get asp.net return drop down list to return value as int	DropDownList d = Your_Drop_Down_List;\n\nint i;\n\nif(int.TryParse(d.SelectedValue, out i))\n{\n  do stuff with i here.\n}\nelse\n{\n  //selected value did not parse.\n}	0
13768727	13767750	XNA setting Color by String	var prop = typeof(Color).GetProperty(nameOfColor);\nif (prop != null)\n    return (Color)prop.GetValue(null, null);\nreturn default(Color);	0
8878691	8878399	How to discover financial Year based on current datetime	public static class DateTimeExtensions\n{\n    public static string ToFinancialYear(this DateTime dateTime)\n    {\n        return "Financial Year " + (dateTime.Month >= 4 ? dateTime.Year + 1 : dateTime.Year);\n    }\n\n    public static string ToFinancialYearShort(this DateTime dateTime)\n    {\n        return "FY" + (dateTime.Month >= 4 ? dateTime.AddYears(1).ToString("yy") : dateTime.ToString("yy"));\n    }\n}	0
26033548	26033483	How to prevent Client from crashing while the server is not running?	try\n{\n    client.Connect("XXX.XXX.XXX.XXX", port);\n}\ncatch(Exception e)\n{\n    //XXX\n}	0
1228744	1228701	Code for decoding/encoding a modified base64 URL	base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');	0
9692019	9689481	Updating datagridview and saving into new dataset	DataSet cloneSet = dataSet.Clone();	0
17978398	17977505	How use the string in the select from table?	// Build a data table and add columns\nDataTable dt = new DataTable();\ndt.Columns.Add("IDRank");\ndt.Columns.Add("Blah");\n\n// Add rows to the table\nfor (int i = 1; i < 5; i++) {\n    DataRow dr = dt.NewRow();\n    dr["IDRank"] = i;\n    dr["Blah"] = "Blah" + i.ToString();\n    dt.Rows.Add(dr);\n}           \n\n// Get a DataView to table\nDataView dv = dt.AsDataView();\n\n// Define the filter\nstring filter = "IDRank = 2";\n\n// Apply the filter\ndv.RowFilter = filter;\n\n// Run the query\nvar Query1 = from P in dv.ToTable().AsEnumerable() select P;	0
32561018	32560563	C# Parse Json string into Array (equivalent of Json.parse in Javascript)	string result = @"[['Angelica','Ramos'],['Ashton','Cox']]";\nstring[][] arr = JsonConvert.DeserializeObject<string[][]>(result);	0
9237109	9236888	how to remove an item and subitem from a listview and a text file	OnRemoveButtonClickHandler()\n{\n    listXuid.Items.Remove(listXuid.SelectedItem);\n\n    // open the file for overwriting\n    foreach (var item in listXuid.Items)\n    {\n        // write out each item in your format\n    }\n}	0
25691167	25690449	Convert from an Interface type to a concrete Type in C# and reflection	List<ILoad> list = new List<ILoad>();\nlist = GetALlIloads();\n\nFactory f = new Factory();\n\nforeach (var item in list)\n{\n    dynamic concreteType = item;\n    var converted = f.ConvertToMeasure(concreteType);\n}\n\npublic class A: Iload\n{\n  // something\n} \n\npublic class B: ILoad\n{\n   //Something\n}\n\npublic class Factory\n{\n    public List<Measure> ConvertToMeausre(A model)\n    {\n        return some List<Measure>\n    }\n\n    public List<Measure> ConvertToMeausre(B model)\n    {\n        return some List<Measure>\n    }\n}	0
8000964	8000537	How to access span with needed innerhtml?	HtmlElementCollection iframes = WebBrowser1.Document.GetElementsByTagName("iframe");\nHtmlElement iframe = iframes(0 /* iframe index */); // \n\nHtmlElementCollection spans = iframe.Document.GetElementsByTagName("span");\nfor (i = 0; i < spans.Count; i++) {\n    HtmlElement span = spans(i);\n    if (span.GetAttribute("customAttr") == "customAttrValue") {\n        string onclick = span.Children(0).GetAttribute("onclick"); //span.Children(0) should return the <a>\n        WebBrowser1.Document.InvokeScript(onclick);\n    }\n}	0
8425586	8425338	C# Regex remove character within the element name only, without replacing the value	Regex tagRegex = new Regex("<[^>]+>");\nyourXML = tagRegex.Replace(yourXML, delegate(Match thisMatch)\n{\n   return thisMatch.Value.Replace(":", "_");\n});	0
23224727	23131999	Getting a Light Vector on a Quad	N' = (P1-P0) x (P2-P1); // or any other non-zero vector combination.\nN = N' / |N'|;           // it is better if normal is unit vector\nL = L' / |L'|;           // the same goes for light\n// now you need some temporary vector n which is L projected onto N\nn = N * (N.L)\n// now the shift direction (lie on the Quad plane)\nD' = L - N\n// and now scale by d - perpendicular distance of Quad or point to projection source (light)\nD = D' * d\n// the rest is easy\nQi = Pi + D	0
25051977	25050460	Trouble with setting focus/select to Form1 after I show Form2 using AxAcroPDFLib	private void returnFocus(object sender, EventArgs e)\n    {\n        lstboxItems.Focus();\n    }\nthis.lstboxItems.LostFocus += new System.EventHandler(this.returnFocus);	0
17472377	17472311	First character of string to upper ASP.Net	char.ToUpper(User.Identity.Name[0]) + User.Identity.Name.Substring(1)	0
2098141	2098084	Is there a method to find out if a double is a real number in C#?	public static class ExtensionMethods\n{\n    public static bool IsARealNumber(this double test)\n    {\n        return !double.IsNaN(test) && !double.IsInfinity(test);\n    }\n}	0
12535344	12535281	What is correct way to a remove few characters at the end of string C#	String.Join("<br/><br/>", MessageList);	0
17842637	17838685	C# Validating Multiple TextBoxes	box1.TextChanged += TextchangedHandler();\nbox2.TextChanged += TextchangedHandler();\nbox3.TextChanged += TextchangedHandler();	0
17306219	17305140	Authentication with Soap service in C# console	Api.Servicereference1.PortClient object = new Api.Servicereference1.PortClient();\nusing ( OperationContextScope scope = new OperationContextScope(object.InnerChannel))\n{\n     MessageHeader soapheader = MessageHEader.CreateHeader("name","ns",payload);\n     OperationContext.Current.OutgoingMessageHeaders.Add(soapheader);\n     object.testmethod();\n}	0
21559334	21532408	Need to convert listview item of string type to long variable	long lVal = (long)Convert.ToDouble(lvwView1.Items[0].SubItems[7].Text);	0
3720526	3718823	HttpWebResponse, and chunked http. How to read one single chunk?	Socket.Receive	0
15827959	15827777	button click method doesn't work as it's visibility changes	private void pic_Image_MouseEnter(object sender, MouseEventArgs e)\n{\n    btn_AddImage.Visible = true;\n    btn_RemoveImage.Visible = true;\n    if (pic_Image.Image != null)\n        btn_RemoveImage.Visible = true;\n}	0
31280299	31279911	Getting changes for a specific entity	public static DbEntityEntry<T> GetEntityChanges2<T>(DbContext c, T entity) where T: class\n{\n    return c.Entry(entity);\n}	0
28165661	28165367	InvalidOperation type String from data source Error	nvarchar(30)	0
2174185	2174182	How can I save a "setting" in a C# application?	Properties.Settings.Default.MySettingName	0
24485445	24485360	Linq query to select data from table and join 2 tables	var listOfItems = from e in context.StatusDescription\n                  join s in context.Schedules on e.ScheduleId equals s.Id\n                  join a in context.Accounts on e.AccountId equals a.Id\n                  select new \n                  {\n                      Description = e.Description,\n                      ScheduleStart = s.DateFrom,\n                      ScheduleEnd = s.DateTo,\n                      AccountCode = a.AccountCode\n                  }	0
3508955	3508943	Include If Else statement in String.Format	formattedTimeSpan = String.Format("{0} hr{1} {2} mm {3} sec",\n    Math.Truncate(timespan.TotalHours),\n    Math.Truncate(timespan.TotalHours) == 1 ? "" : "s",\n    timespan.Minutes,\n    timespan.Seconds);	0
15623120	15623068	Must declare the scalar variable "@campusVisitDate"	else\n    {\n        cmd.Parameters.AddWithValue("@onCampus", 0);\n        cmd.Parameters.AddWithValue("@campusVisitDate",null);  \n    }	0
11672433	11671598	Reset settings to SpecialFolder	[global::System.Configuration.UserScopedSettingAttribute()]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Configuration.DefaultSettingValueAttribute(null)]\n    public string TemporaryDirectory\n    {\n        get\n        {\n            if (this["TemporaryDirectory"] == null)\n            {\n                return System.IO.Path.GetTempPath();\n            }\n            return ((string)this["TemporaryDirectory"]);\n        }\n        set\n        {\n            if (System.IO.Directory.Exists(value) == false)\n            {\n                throw new System.IO.DirectoryNotFoundException("Directory does not exist.");\n            }\n            this["TemporaryDirectory"] = value;\n        }\n    }	0
6328534	6328288	How to comment a line of a XML file in C# with System.XML	String xmlFileName = "Sample.xml";\n\n// Find the proper path to the XML file\nString xmlFilePath = this.Server.MapPath(xmlFileName);\n\n// Create an XmlDocument\nSystem.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();\n\n// Load the XML file in to the document\nxmlDocument.Load(xmlFilePath);\n\n// Get the target node using XPath\nSystem.Xml.XmlNode elementToComment = xmlDocument.SelectSingleNode("/configuration/system.web/customErrors");\n\n// Get the XML content of the target node\nString commentContents = elementToComment.OuterXml;\n\n// Create a new comment node\n// Its contents are the XML content of target node\nSystem.Xml.XmlComment commentNode = xmlDocument.CreateComment(commentContents);\n\n// Get a reference to the parent of the target node\nSystem.Xml.XmlNode parentNode = elementToComment.ParentNode;\n\n// Replace the target node with the comment\nparentNode.ReplaceChild(commentNode, elementToComment);\n\nxmlDocument.Save(xmlFilePath);	0
9427991	9427479	Ideal c# reduction method for values of the same type, with bitwise approach?	static int[] Reduce(IEnumerable<myclass> items)\n    {\n        HashSet<int> uniqueValues = new HashSet<int>();\n\n        foreach (var item in items)\n        {\n            uniqueValues.Add(item.myproperty);\n        }\n\n        return uniqueValues.ToArray();\n    }	0
33058685	33058410	How to change ListView cell's backcolor using c# windows form?	for (int i = 0; i < listView1.Items.Count; i++)\n        {\n            if (i % 2 == 0)\n                listView1.Items[i].BackColor = Color.Blue; \n            else\n                listView1.Items[i].BackColor = Color.White; \n        }	0
546512	546369	How to insert CookieCollection to CookieContainer?	request.CookieContainer = new CookieContainer();\nrequest.CookieContainer.Add(response.Cookies);	0
30032391	30031508	Using Linq Calculate sum of ObservableCollection value	Collection obj = new Collection();\n\nobj.MetalCollection.SelectMany(m => m.GoldCollection).GroupBy(g => g.Category).Select(t => new { t.Key, MySum = t.Sum(n => n.Weight).ToString() });	0
21176043	21175951	Change text color of old date using javascript	var dt =  document.getElementById("yourDate"); //get your date\nvar today = new Date(); //get date today\nif(dt.value <  today )\n{\n    dt.style.color="red";  \n}	0
15111554	15110110	How to find the height of the left and right subtree in C#	public int TreeDepth( TreeNode<T> tree, int depth = 0 )\n{\n    int leftDepth = tree.Left != null \n        ? TreeDepth( tree.Left, depth + 1 ) \n        : depth;\n    int rightDepth = tree.Right != null \n        ? TreeDepth( tree.Right, depth + 1 ) \n        : depth;\n    return leftDepth >= rightDepth \n        ? leftDepth \n        : rightDepth;\n}	0
32676001	32669533	GridView Cell selection from Filtered Row	foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            //gets the value of the id from the id cell\n            int id = int.Parse(row.Cells[0].Value.ToString());\n            //let's say we wany the person with id 5\n            if (id == 5) //this is our guy \n            {\n                //let's say the name is stored in the cell with index of 1 and we wanna show it in textbox1\n                textBox1.Text = row.Cells[1].Value.ToString();\n            }\n        }	0
2110555	2110431	C# Find if a word is in a document	string pattern = "foo";\nstring input = null;\nstring lastword = string.Empty;\nstring firstword = string.Empty;\nbool result = false;\n\nFileStream FS = new FileStream("File name and path", FileMode.Open, FileAccess.Read, FileShare.Read);\nStreamReader SR = new StreamReader(FS);\n\nwhile ((input = SR.ReadLine()) != null) \n{\n    firstword = input.Substring(0, input.IndexOf(" "));\n    if(lastword.Trim() != string.Empty) { firstword = lastword.Trim() + firstword.Trim(); } \n\n    Regex RegPattern = new Regex(pattern);\n    Match Match1 = RegPattern.Match(input);\n    string value1 = Match1.ToString(); \n\n    if (pattern.Trim() == firstword.Trim() || value1 != string.Empty) { result = true;  }\n\n    lastword = input.Trim().Substring(input.Trim().LastIndexOf(" "));\n}	0
30877733	30871852	Export data to multiple Excel sheets?	oXL = CREATEOBJECT("Excel.Application")\noBook = oXL.Workbooks.Open("<the file containing the sheet you want first>")\n* Copy second sheet to first workbook\noBook2 = oXL.Workbooks.Open("<the file containing the sheet you want second>")\noBook2.Sheets[1].Copy(, oBook.Sheets[1])\noBook2.Close()\n* Copy third sheet to first workbook\noBook2 = oXL.Workbooks.Open("<the file containing the sheet you want third>")\noBook2.Sheets[1].Copy(, oBook.Sheets[2])\noBook2.Close()\n* Etc.\n\noBook.Save()\noBook.Close()\noXL.Quit()	0
3758303	3754154	Interop Word - Delete Page from Document	Doc.ActiveWindow.Selection.GoTo wdPage, PageNumber\nDoc.Bookmarks("\Page").Range.Text = ""	0
5947678	5947581	modify data in columns in SQL Server	"UPDATE usertb SET [srpassword] = '" + password + "' WHERE [srusername] = '" + username + "'	0
5505346	5505228	Generate image from XAML View	public static Image GetImage(Visual target)\n{\n    if (target == null)\n    {\n        return null; // No visual - no image.\n    }\n    var bounds = VisualTreeHelper.GetDescendantBounds(target);\n\n    var bitmapHeight = 0;\n    var bitmapWidth = 0;\n\n    if (bounds != Rect.Empty)\n    {\n        bitmapHeight = (int)(Math.Floor(bounds.Height) + 1);\n        bitmapWidth = (int)(Math.Floor(bounds.Width) + 1);\n    }\n\n    const double dpi = 96.0;\n\n    var renderBitmap =\n        new RenderTargetBitmap(bitmapWidth, bitmapHeight, dpi, dpi, PixelFormats.Pbgra32);\n\n    var visual = new DrawingVisual();\n    using (var context = visual.RenderOpen())\n    {\n        var brush = new VisualBrush(target);\n        context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));\n    }\n\n    renderBitmap.Render(visual);\n\n    return new Image\n    {\n        Source = renderBitmap,\n        Width = bitmapWidth,\n        Height = bitmapHeight\n    };\n}	0
21751903	20856370	How to hide Thumbnail view option in Active reports 6.0	{\n  // Check fot TableOfContents Control\n  if (control.Name == "TableOfContents")\n {\n                        // Getting the TabControl.\n                        var contColletion = control.Controls;\n                        Control tabCollection = contColletion[0];\n                        TabControl tabControl = (TabControl)tabCollection;\n                        tabControl.Appearance = TabAppearance.Normal;\n                        // Remove the Thumbnail Tab from Control.\n                        tabControl.TabPages.RemoveAt(1);\n                    }\n                }	0
4626251	4626202	Populate a DataSet using Context - Entity Framework 4	DataSet dataSet = new DataSet("myDataSet");\ndataSet.Tables.Add(new DataTable());\n//Setup the table columns.\n\nforeach (CmsCategory categories in context.spCmsCategoriesReadHierarchy(n,sl,nn))\n{\n    DataRow row = dataSet.Tables[0].NewRow();\n    row["A"] = categories.A;\n    row["B"] = categories.B;\n\n    dataSet.Tables[0].Rows.Add(row);\n}	0
28067606	28066754	Get Count on Entity with ICollection that has specific property value	var count = _db.Renders.Count(render => render.Comments.Any(c => c.CommentApproved));	0
12149214	12149107	Simple conversion of IEnumerable<T> to JSON in Monotouch	var list = new List<string>() { "value1", "value2" };\n\nvar result = new System.Json.JsonArray(list.Select(x => (System.Json.JsonValue)x));\n\nConsole.WriteLine( result.ToString() );	0
12232224	12231696	Im using richTextBox to view log but how do i make it not ot move down to a new line each time?	private void timer1_Tick(object sender, EventArgs e)\n{\n    richTextBox1.Text = "";\n    // Add the rest of the code here\n}	0
32668626	32668574	Find the bigger number out of two numbers stored as strings in C#	shorterString = shorterString.PadLeft(longerString.Length, '0');	0
21613611	21613244	How to fetch an object with find while also including another object?	var supplier = fetchedObject.Supplier;	0
3865069	3865026	Is there a LINQ query that will give me the sum of several maximum values?	var locationsToInclude = new List<int> { 123, 124 };\n\nvar sum = transaction\n    .Where(t => locationsToInclude.Contains(t.location))\n    .GroupBy(t => t.location)\n    .Sum(g => g.Max(t => t.transactions));	0
8582360	8582285	DDD Service or Entity to model a gift card amount reduction	class GiftCard\n{\n    public long Id {get; private set;}\n    public double Amount {get; private set;}\n\n    public void Apply(Transaction tx)\n    {\n         if(tx.Amount > Amount)\n         {\n            handle insufficient funds\n         }\n         else\n         {\n            Amount -= tx.Amount;\n            //other logic if necessary\n         }\n    }\n}	0
13626297	13568120	Advanced debugging advice in WPF GarbageCollection	GC.GetTotalMemory(true);	0
12774395	12774316	Linq to Entity Where built by looping over data	var searchValue = searchValues[0];\n\nIQueryable<DatabaseType> returnValue =\ncontext.DatabaseType.Where(y =>\n    y.Field1.Contains(searchValue) ||\n    y.Field1.Contains(searchValue));	0
30504426	30504320	How to assign a single column of a multi dimensional array to a single dimensional one?	string[,] twoDArray = new [,] {{"1","2"}, {"3","4"}, {"5","6"}};\nint len = twoDArray.GetLength(0);\nstring[] oneDArray = new string[len];\n\nfor(int r=0;r<len; r++)\n    oneDArray[r] = twoDArray[r,1];	0
17804658	17795982	How can I simplify the registration of a large set of closed generic versions of the same open generic implementation?	container.Register(\n    Component.For(typeof(IFoo<>))\n      .ImplementedBy(typeof(Foo<>))\n);	0
33306780	33297753	Creating two inner joins to get wanted result in linq .net, is there a smarter way?	public ItemDescriptionIdentity GetDescriptionIdentityInfo(int tradeItemId)\n{\n    var query = (from item in _db.TradeItems\n                 join identity in _db.ItemIdentities \n                   on item.itemIdentities equals identity.id\n                 join identitys in _db.ItemDescriptionIdentitiesOnTradeItems\n                   on identitys.itemIdentitiesId equals identity.id\n                 join descriptionIdentity in _db.ItemDescriptionIdentities\n                   on identitys.itemDescriptionIdentitieId equals descriptionIdentity.id\n                  where item.id == tradeItemId\n                  select descriptionIdentity);\n\n    return result.FirstOrDefault() as ItemDescriptionIdentity;\n}	0
16601933	15947795	Line chart - changing border width removes space	void Form1_Paint(object sender, PaintEventArgs e) {\n    float[] dashValues = { 8, 5, 2, 4 };\n    Pen blackPen = new Pen(Color.Black, 5);\n    blackPen.DashPattern = dashValues;\n    blackPen.Width = 3;\n    //blackPen.StartCap=LineCap.Round\n    blackPen.StartCap =LineCap.Flat;\n    //blackPen.StartCap=LineCap.Round\n    blackPen.EndCap = LineCap.Flat;\n    e.Graphics.DrawLine(blackPen, new Point(85, 95), new Point(405, 95));\n}	0
9554395	9554257	combobox constant value	public partial class Form1 : Form\n{\n    static string selection;\n    public Form1()\n    {\n        InitializeComponent();\n        comboBox1.SelectedItem = selection;\n    }\n\n    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        selection = (string)comboBox1.SelectedItem;\n    }\n}	0
17980152	17979780	How do I close a toolstripmenuitem that is set to autoclose = false?	toolStripDropDownButton.HideDropDown();	0
11743573	11738642	Store array[,] in user settings	MySettings settingsTest = new MySettings();\nsettingsTest.user_credits = new string[user_credits_array, 10];\nsettingsTest.user_credits[new_user_id, 0] = user_name;\nsettingsTest.user_credits[new_user_id, 1] = user_email;\nsettingsTest.user_credits[new_user_id, 2] = user_acc_name;\nsettingsTest.user_credits[new_user_id, 3] = user_acc_pass;\nsettingsTest.user_credits[new_user_id, 4] = sSelectedClient;\nsettingsTest.user_credits[new_user_id, 5] = server_inkomend;\nsettingsTest.user_credits[new_user_id, 6] = server_uitgaand;\nsettingsTest.user_credits[new_user_id, 7] = server_port + "";\nsettingsTest.user_credits[new_user_id, 8] = ssl_state;\n\n\nsettingsTest.Save(MySettings.GetDefaultPath());\nMySettings anotherTest = MySettings.Load(MySettings.GetDefaultPath());	0
6142607	6141821	Run application via shortcut using Process.Start C#	UseShellExecute = false	0
28588386	28587472	Casting of literalControl on search	private Control FindAspControlByIdInControl(Control control, string id)\n{\n    foreach (Control childControl in control.Controls)\n    {\n        if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) && childControl is WebControl)\n        {\n            return childControl;\n        }\n\n        if (childControl.HasControls())\n        {\n            Control result = FindAspControlByIdInControl(childControl, id);\n            if (result != null) return result;\n        }\n    }\n\n    return null;\n}	0
8503592	8503558	How to display a text (Html format) in a website (Asp.net C#)	div1.InnerHtml=formattedtext;	0
25335632	25335256	insert xml data into sql server c# twilio	GetTwilioResponse(customTypeToHoldTwilioAPIparams params)\n{\n    Here would be your code for calling the Twilio API.  \n    Somewhere in here, if the response from Twilio is good, then call a method in another class that will call the stored procedure;\n}	0
8165122	8164859	Install a Windows service using a Windows command prompt?	"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" "c:\myservice.exe"	0
4010942	4010919	Any suggest to store a value in a lambda expression	Func<string, string, int> getOccurrences = null;\ngetOccurrences = (text, searchTerm) => \n{\n   int i = text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);\n   return i == -1 ? 0 : getOccurrences(i + searchTerm.Length), searchTerm) + 1;\n}	0
512968	512954	Bound Textbox to a currency, how to get the double?	double d = double.Parse ("$10.10", NumberStyles.Currency);	0
24764630	24764565	Is there a defined value in the standard namespaces for the golden ratio?	readonly double GoldenRatio = (1 + Math.Sqrt(5)) / 2;\nconst double GoldenRatio = 1.61803398874989484820458683436;	0
3457433	3457405	Insert into mysql database	command.CommandText = "INSERT INTO mail(" + s2[0] + ") values" + "('" + s2[1] + "')";	0
5313285	5313193	Convert from JSon to Object Collection	[\n    {\n        "message": "@12:55 Big Rally on South Bound of Dr. B.A. Road. Motorists may use RAK Road, P. D'Melow Road & A.B. Road for CST.\n -visit icicilombard.com",\n        "picture": "",\n        "medium": "API",\n        "timestamp":"03\/15\/2011 12:55:42 IST"\n    }\n]	0
8847711	8847679	Find average of collection of timespans	double doubleAverageTicks = sourceList.Average(timeSpan => timeSpan.Ticks);\nlong longAverageTicks = Convert.ToInt64(doubleAverageTicks);\n\nreturn new TimeSpan(longAverageTicks);	0
20171919	20171909	Linq create a list of some type from a list of another type	var result = list.Select(x=>x.ToSomeObject()).ToList();	0
29516593	29516413	Creating a KeyValuePair list by iterating over an array	var myList = objects\n    .Select((f, index) =>  new KeyValuePair<Foo, float>(f, (index + 1) * 0.2f))\n    .ToList();	0
33380709	33348016	Retrieve email with exchange web services and put it in a datagrid	URLGRID.ItemsSource = findResults.Where(t => t is EmailMessage).Select(item => new { item.DateTimeReceived, ((EmailMessage)item).Sender.Name, item.Subject });	0
7304721	7304695	Why does this method for computing a SHA-256 hash always return a string of 44 characters?	Convert.ToBase64String(hashedBytes)	0
13272926	13272552	Comparing value types cast to object	public bool Compare(object value1, object value2)\n{\n    if (value1.GetType() == value2.GetType())\n    {\n        return value1.Equals(value2);\n    }\n    else\n    {\n        //your logic for handling different numbers\n    }\n}	0
22823370	22802391	How to detect 1 Skeleton at a time from Kinect?	int trackingID;\nskeletonTracked = new Skeleton();\nbool first = true;\nSkeleton skeleton;\nSkeleton[] skeletons = new Skeleton[6];\n\n...\n\npublic void AllFramesReady(object sender, AllFramesReadyEventArgs e)\n{\n    using (SkeletonFrame sFrame = e.OpenSkeletonFrame())\n    {\n        sFrame.CopySkeletonDataTo(skeletons);\n        skeleton = (from s in skeletons where s.TrackingState == SkeletonTrackingState.Tracked select s).FirstOrDefault();\n        if (skeleton == null)\n            return;\n\n        if (skeleton.TrackingState == SkeletonTrackingState.Tracked)\n        {\n            if (first)\n            {\n                skeletonTracked = skeleton;\n                trackingId = skeleton.TrackingID;\n                ...\n                first = false;\n            }\n\n            if (skeleton.TrackingID == trackingId)\n            {\n                ...\n            }\n        }\n    }	0
1947025	1946990	Get empty slot with lowest index from an array	var result = list.Where(i => IsItemEmpty(i)).FirstOrDefault();	0
14554182	14554102	HtmlAgilityPack - Keep text position upon removal of node	public static void RemoveChildKeepGrandChildren(HtmlNode parent, HtmlNode oldChild)\n{\n    if (oldChild.ChildNodes != null)\n    {\n        HtmlNode previousSibling = oldChild.PreviousSibling;\n        foreach (HtmlNode newChild in oldChild.ChildNodes)\n        {\n            parent.InsertAfter(newChild, previousSibling);\n            previousSibling = newChild;  // Missing line in HtmlAgilityPack\n        }\n    }\n    parent.RemoveChild(oldChild);\n}	0
21845071	21844986	Pulling an item from listview	var newVariable = ListView1.Items[1].SubItems[1].Text	0
16422503	16377151	LookUpEdit not selecting newly entered value when it's a double	private void OnProcessNewValue_Double(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e) \n{\n    ObservableCollection<double> source = (ObservableCollection<double>)(sender as LookUpEdit).Properties.DataSource;\n\n    if (source != null) {\n        if ((sender as LookUpEdit).Text.Length > 0) {\n            double val = Convert.ToDouble((sender as LookUpEdit).Text);\n            source.Add(val);\n            e.DisplayValue = val;\n            (sender as LookUpEdit).Refresh();\n        }\n    }        \n    e.Handled = true;\n}	0
9897018	9896929	Set value for DictionaryEntry	IDictionary dictionary = new Hashtable();\nconst string key = "key";\nconst string value = "value";\ndictionary[key] = null; // set some trigger here\n\nforeach(var k in dictionary.Keys.OfType<object>().ToArray()) \n{\n    if(dictionary[k] == null) \n        dictionary[k] = value;\n}	0
29947634	29945038	readbytes of a file and running it	// Read file content from project resources\nbyte[] fileContent = MyProject.Properties.Resources.MyFile;\n\n// <Do your stuffs with file content here>\n\n// Write new file content to a temp file\nstring tempFile = "yourfile.exe";\nFile.WriteAllBytes(tempFile , fileContent );\n\n// Run the app\nProcess proc = Process.Start(new ProcessStartInfo(tempFile));	0
27398430	27398359	Generic type in constructor parameter	public class Myclass<T>\n{\n    public Myclass(IEnumerable<T> ListeValeurChampPerso, string str, int a)\n     {\n       foreach (var vr in ListeValeurChampPerso)\n       {...\n       }\n    }\n}	0
21191019	21189222	Topological sort with support for cyclic dependencies	function topoSort(graph) \n  state = []\n  list = []\n  for each node in graph\n    state[node] = alive\n  for each node in graph\n    visit(graph, node, list, state)\n  return list\n\nfunction visit(graph, node, list, state)\n  if state[node] == dead\n    return // We've done this one already.\n  if state[node] == undead\n    return // We have a cycle; if you have special cycle handling code do it here.\n  // It's alive. Mark it as undead.\n  state[node] = undead\n  for each neighbour in getNeighbours(graph, node)\n    visit(graph, neighbour, list, state)\n  state[node] = dead\n  append(list, node);	0
8511803	8511769	Regex - Including '+' when looking for a decimal	string match = Regex.Match(subject, @"-?(\d+((\.\d+)|\+)?)|(\.\d+)").Value\n    .Replace("+", ".5");	0
1227151	1227132	How can I make a specific TabItem gain focus on a TabControl without click event?	MainTabControl.SelectedIndex = 0;	0
10120444	10120120	Linq: How to optimize a request with a table/list as parameter?	using (MyDatabaseEntities context = new MyDatabaseEntities())\n{\n   return context.Persons\n    .Where(p => ages.Contains(p.Age))\n    .Select(p => new {p, p.Car, p.Company, p.Address})\n    .ToList();\n}	0
16982938	16982850	Time Control for a Replay System	(nextFrame.Timestamp - currentFrame.Timestamp)	0
11848818	11848732	c# Search String value for variations of an abbreviation	if (Regex.IsMatch(yourTextBox.Text, @"((\.|,|\s)AB(\.|,|\s)"))) {\n    // do something\n}	0
1334483	1237683	XML Serialization of List<T> - XML Root	public XmlDocument GetEntityXml<T>()\n{\n    XmlDocument xmlDoc = new XmlDocument();\n    XPathNavigator nav = xmlDoc.CreateNavigator();\n    using (XmlWriter writer = nav.AppendChild())\n    {\n        XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("TheRootElementName"));\n        ser.Serialize(writer, parameters);\n    }\n    return xmlDoc;\n}	0
11824790	11824738	How to pass string from C# to delphi dll function?	[DllImport ("ServerTool.dll"), CallingConvention=CallingConvention.StdCall)]	0
12922459	12922420	How to use object initializers with using statements?	using (FrmSomeForm someForm = new FrmSomeForm(){\n    SomePropA = "A",\n    SomePropB = "B",\n    SomePropC = "C"\n})\n{\n    someForm.ShowDialog();\n}	0
13823687	13293888	How to call a C# library from Native C++ (using C++\CLI and IJW)	wchar_t * DatePickerClient::pick(std::wstring nme)\n{\n    IntPtr temp(ref);// system int pointer from a native int\n    String ^date;// tracking handle to a string (managed)\n    String ^name;// tracking handle to a string (managed)\n    name = gcnew String(nme.c_str());\n    wchar_t *ret;// pointer to a c++ string\n    GCHandle gch;// garbage collector handle\n    DatePicker::DatePicker ^obj;// reference the c# object with tracking handle(^)\n    gch = static_cast<GCHandle>(temp);// converted from the int pointer \n    obj = static_cast<DatePicker::DatePicker ^>(gch.Target);\n    date = obj->PickDate(name);\n    ret = new wchar_t[date->Length +1];\n    interior_ptr<const wchar_t> p1 = PtrToStringChars(date);// clr pointer that acts like pointer\n    pin_ptr<const wchar_t> p2 = p1;// pin the pointer to a location as clr pointers move around in memory but c++ does not know about that.\n    wcscpy_s(ret, date->Length +1, p2);\n    return ret;\n}	0
12466115	12464134	restsharp unsuccessful post	var client = new RestClient("http://localhost:14437/Service.svc");\nvar request = new RestRequest("XmlService/PEmploy", Method.POST);\nrequest.RequestFormat = DataFormat.Json;\nmyRef.Employee emp = new myRef.Employee() { EmpNo = 101, EmpName = "Mahesh", DeptName = "CTD" };\nrequest.AddParameter("Employee", emp);\nRestResponse<myRef.Employee> response = (RestResponse<myRef.Employee>)client.Execute<myRef.Employee>(request);	0
10660006	10658669	Where can I find a simple but flexible JSON parser for C#?	string mystring = \n    @"\n    {\n        ""maps"": {\n            ""earth"": {\n                ""colors"": [\n                    ""blue"",\n                    ""green""\n                ]\n            },\n            ""moon"": {\n                ""colors"": [\n                    ""black"",\n                    ""white""\n                ]\n            }\n        }\n    ";\n\ndynamic j = JsonConvert.DeserializeObject(mystring);\nforeach (var c in j.maps["earth"].colors)\n{\n    Console.WriteLine(c);\n}	0
11024365	11024228	Format TimeSpan to mm:ss for positive and negative TimeSpans	private string FormatTimeSpan(TimeSpan time)\n{\n    return ((time < TimeSpan.Zero) ? "-" : "") + time.ToString(@"mm\:ss");\n}	0
2203061	2203049	How can I create an Array of Controls in C#.NET?	List<Control>	0
7947942	7942128	DataGridView as a property type	/// tried this attribute - did not work\n/// [Designer(typeof (System.Windows.Forms.Design.ControlDesigner))]\n\n/// this did not work either\n[Editor("System.Windows.Forms.Design.DataGridViewComponentEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(ComponentEditor))]\n[Designer("System.Windows.Forms.Design.DataGridViewDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]\npublic class ucInheritedDataGridView : DataGridView { }	0
27987705	27986900	Compare two sql dates using Linq	var query = from user in this.Query()\n            where ((user.LastLoginDate.Date == user.CreateDate.Date\n                && user.LastLoginDate.Hour == user.CreateDate.Hour\n                && user.LastLoginDate.Minute == user.CreateDate.Minute\n                && user.LastLoginDate.Second <= user.CreateDate.Second + 10)\n                ||(user.LastLoginDate.Date == user.CreateDate.Date\n                && user.LastLoginDate.Hour == user.CreateDate.Hour\n                && user.LastLoginDate.Minute + 1 == user.CreateDate.Minute\n                && 60 - user.CreateDate.Second + user.LastLoginDate.Second <= 10)) \n            select std;	0
10886293	10885827	Binding empty dictionary to a listbox	BindingSource b = new BindingSource();\nb.DataSource = this.contactpersonenListBox;\nlsContactpersonen.DisplayMember = "Value";\nlsContactpersonen.ValueMember = "Key";\nlsContactpersonen.DataSource = b;	0
10583386	10583115	Is there a LINQ extension or (a sensible/efficient set of LINQ entensions) that determine whether a collection has at least 'x' elements?	public static bool AtLeast<T>(this IEnumerable<T> source, int count)\n{\n    // Optimization for ICollection<T>\n    var genericCollection = source as ICollection<T>;\n    if (genericCollection != null)\n        return genericCollection.Count >= count;\n\n    // Optimization for ICollection\n    var collection = source as ICollection;\n    if (collection != null)\n        return collection.Count >= count;\n\n    // General case\n    using (var en = source.GetEnumerator())\n    {\n        int n = 0;\n        while (n < count && en.MoveNext()) n++;\n        return n == count;\n    }\n}	0
18827331	18827199	Get a list from a dynamic json result	resultList.Where((child, index) => (index) %2!=0);	0
21800498	21799165	Can a Cache WorkerRole add to its own cache?	Microsoft.WindowsAzure.Caching	0
7520228	7501938	Access token Google+	string url = "https://accounts.google.com/o/oauth2/token";\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());\nrequest.Method = HttpMethod.POST.ToString();\nrequest.ContentType = "application/x-www-form-urlencoded";\n\n// You mus do the POST request before getting any response\nUTF8Encoding utfenc = new UTF8Encoding();\nbyte[] bytes = utfenc.GetBytes(parameters); // parameters="code=...&client_id=...";\nStream os = null;\ntry // send the post\n{\n    webRequest.ContentLength = bytes.Length; // Count bytes to send\n    os = webRequest.GetRequestStream();\n    os.Write(bytes, 0, bytes.Length);        // Send it\n}\n\ntry\n{\n    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n    {\n        // Do stuff ...	0
1522224	1522208	Weighted Random Number Generation in C#	if (random.NextDouble() < 0.90)\n{\n    BlinkGreen();\n}\nelse\n{\n    BlinkRed();\n}	0
17672465	17671702	How deserialize Byte array to object - Windows 8 / WP 8	using (var ms = new MemoryStream(byteArr))\n    {\n        var yourObject = serializer.ReadObject(ms);\n    }	0
19275016	19274601	Passing a Parameter to ReportView	ReportParameter p = new ReportParameter("CustomerID", strCustomerID);\n\nthis.reportViewer1.ServerReport.SetParameters(new ReportParameter[] { p });	0
13219496	13219305	User control used as a class	MyClass Data {get; set;}	0
21907258	21900261	Printing a pdf file on client side printer in asp.net C#?	Process printjob = new Process();\n\n    printjob.StartInfo.FileName = @"D:\R&D\Changes to be made.pdf" //path of your file;\n\n    printjob.StartInfo.Verb = "Print";\n\n    printjob.StartInfo.CreateNoWindow = true;\n\n    printjob.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n\n    PrinterSettings setting = new PrinterSettings();\n\n    setting.DefaultPageSettings.Landscape = true;\n\n    printjob.Start();	0
962997	962983	Windows Forms: Access settings stored in a .settings file outside a Form	using TestForm1.Properties;\n\n//... namespace/class stuff here\n\nSettings.Default.Test = "Hello World!";\nSettings.Default.Save();\nString test = Settings.Default.Test;	0
17360192	17359176	Cross-thread operation accessed from a thread other than the thread it was created on	public delegate void InvokeDelegate();\n\nprivate void Invoke_Click(object sender, EventArgs e)\n{\n   myTextBox.BeginInvoke(new InvokeDelegate(InvokeMethod));\n}\npublic void InvokeMethod()\n{\n   myTextBox.Text = "Executed the given delegate";\n}	0
30276501	30205450	Using SendKeys when Windows locks gets Access Denied	using (var driver = new ChromeDriver())\n{\n    // Go to the home page\n    driver.Navigate().GoToUrl("yourloginpageurl");\n\n    var userNameField = driver.FindElementByName("userIdTextInput");\n    userNameField.SendKeys("aaa");\n\n    var passwordField = driver.FindElementByName("pwdIdTextInput");\n    passwordField.SendKeys("bbb");\n\n    var loginButton = driver.FindElementByXPath("//form[@id='abc']/button");\n    loginButton.Click();\n\n}	0
25063766	25063701	Reverse Sorting with IComparable	public int CompareTo(User b)\n{\n    return b.total.CompareTo(this.total);\n}	0
7748200	7747074	ASP.NET Routing Constraint For Specific URL	routes.MapRoute("", "Specialties/Urology", new { controller = "someothercontroller", action = "someotheraction" });\nroutes.MapRoute("", "Specialties/{speciality}", new { controller = "specialities", action = "show" });	0
10958625	10958594	c# winforms how to get the highest ColumnIndex	int max = dgv.SelectedCells.Cast<DataGridViewCell>().Max(c => c.ColumnIndex);	0
23987225	11578374	Entity Framework 4.0: How to see SQL statements for SaveChanges method	context.Database.Log = msg => Trace.WriteLine(msg);	0
22923502	22921924	Trying to create a one user program that is password protected	SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Login", con);\nDataTable dt = new DataTable();\nsda.Fill(dt);\nif (dt.Rows[0][0].ToString() == "0")\n{\n    RegistrationForm rf = new RegistrationForm();\n    rf.Show();\n}\nelse\n{\n    this.Hide();\n    LoginForm lf = new LoginForm();\n    lf.Show();\n}	0
13067275	13066306	Only 1 of 2 progress bars gets updated in BackgroundWorker	System.Threading.Thread.Sleep(1);	0
20052083	20051986	data insert using input output stored procedure	connection.Open();\nvar cmd = new SqlCommand("sp_InsertCashPooja", connection);\ncmd.Parameters.AddWithValue("FirstName", frmFirstName);\n// Add all the others parameters in same way\nvar id = (int)cmd.ExecuteScalar();\nconnection.Close();	0
30203933	30193019	Migrating from Nhibernate to EF6	--------------------------------------------------\n| Id | OldKey                                  |\n--------------------------------------------------\n| 1|   3d09565d-eb84-4e9c-965c-d530c1be8cf2    |\n--------------------------------------------------\n| 2|   54a93dbc-7ce8-4c88-a8e0-70cc48a84073    |\n--------------------------------------------------	0
33380970	33380606	Display names in a table below corresponding image-mvc4	foreach (var item in Model)\n{\n    <tr>    \n        <td>\n            <img src="data:image/png;base64,@Convert.ToBase64String(item.Picture,0,item.Picture.Length)" width="250" height="250" class="img-circle" />               \n        </td> \n    </tr>  \n    <tr> \n        <td>\n            <b>@item.Name</b>\n        </td> \n    </tr> \n    <tr>  \n        <td>                \n            <b>@item.Position</b>\n        </td> \n    </tr>\n}	0
11401171	11401110	How do I clear a column name in datagridview	MyDataGridView.Columns["ColName"].Name = string.Empty	0
10364120	10364035	How to compute rank of IEnumerable<T> and store it in type T	var first = myArray.Select((s, i) => { s.Rank = i; return s; });	0
17317523	17317466	c# - How to convert Timestamp to Date?	var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(1372061224000 / 1000d)).ToLocalTime();\nConsole.WriteLine(dt); // Prints: 6/24/2013 10:07:04 AM	0
9486243	9485845	XmlSerializer loading wrong assembly	XmlSerializer serializer = new XmlSerializer(hello.GetType);	0
21785016	21784653	How to use GroupBy in LINQ?	var products = from listProducts in repository.All()\n                where listProducts.Code == "48654"\n                group listProducts by listProducts.family into grp\n                select grp;	0
6441331	6441152	Parsing Date Format to specific culture	protected void Application_BeginRequest(object sender, EventArgs e)\n{\n    CultureInfo cInfo = new CultureInfo("en-ZA");\n    cInfo.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";\n    cInfo.DateTimeFormat.DateSeparator = "/";\n    Thread.CurrentThread.CurrentCulture = cInfo;\n    Thread.CurrentThread.CurrentUICulture = cInfo;\n}	0
17484802	17483532	How to get data from MS Word forms	for (int i = 1; i <= docs.FormFields.Count; i++) \n{ \n    totaltext += " \r\n "+ docs.FormFields[i].Result.ToString();\n}	0
14672470	14671460	EntityFramework Code First inheritance with custom discriminator	modelBuilder.Entity<Member>()\n.Map<Field>(m => \n{\n    m.ToTable("Fields");\n    m.Requires("ValueType").HasValue((int)Service.DataTypes.MemberType.Field).IsRequired();\n})\n.Map<SECONDTYPE>(m =>\n{\n    m.Requires("ValueType").HasValue(42);\n});	0
21288108	21287485	Is there a strongly-typed way to update a subdocument in MongoDB?	var query = Query.And(\n    Query<Band>.EQ(b => b.Name == "Rush"),\n    Query<Band>.EQ(b => b.Members[-1].FirstName == "Geddy"));\nvar update = Update<Band>\n    .Set(b => b.Members[-1].Instrument, "Keyboards")\n    .Set(b => b.Members[-1].LastName, "Leex");	0
7250756	7250648	Creating Custom Design and Saving Canvas to JPEG	myCanvas.InvalidateVisual();	0
2887179	2887015	I want to form a m x n matrix by giving some numbers as input in c#	int[] arr = new int[3 + 1/3, 3]	0
16740393	16740237	XML File to SQL Additive Insert	declare @data xml = '<People>\n    <Person>\n        <Name>Gerald</Name>\n    </Person>\n    <Person>\n        <Name>Ron</Name>\n    </Person>\n    <Person>\n        <Name>Becky</Name>\n    </Person>\n</People>'\n\n--Convert xml to rows example:\nSELECT N.value('.', 'varchar(50)') as value \nFROM @data.nodes('/People/Person/Name') as T(N)\n\n-- use merge to find rows and insert when not found\nMerge Table1 as tgt\nusing (\n        SELECT N.value('.', 'varchar(50)') as Name \n        FROM @data.nodes('/People/Person/Name') as T(N)\n      ) src\non (tgt.name = src.name)\nwhen not matched then\ninsert (name)\nvalues (src.name);	0
7721811	7721729	how to gate array of timer in c#	Timer[] timers = new Timer[50];\nstring timerNames = new string[50];\n\nint i = 0;\n\nforeach (int dataValue in _dataValues)\n{    \n     timeNames[i] = string.Format("{0}",i);\n     timer[i] = new Timer();\n     timer[i].Interval = dataValue;\n     i++;\n}	0
30187224	30186974	How can I save a variable from a database and use it in C#?	OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);\n     OleDbDataReader reader = cmd.ExecuteReader();\n    int result=-1 ;\n     if (reader.HasRows)\n     {\n       reader.Read();\n       result = reader.GetInt32(0);\n     }\nif (result != -1)\n{\n     strSQL = "UPDATE materials SET ";\n     strSQL = strSQL + "Dscr = 'concrete', ";\n     strSQL = strSQL + "width=50 ";\n     strSQL = strSQL + " WHERE ID="+result;\n     objCmd = new OleDbCommand(strSQL, db_def.conn);\n     objCmd.ExecuteNonQuery();\n}	0
24896425	24896350	Passing additional parameters to event Action;	insertRequest.ProgressChanges += progress => { /* Do something with filePath here */ };	0
18316511	18314793	Translating key from Keys enumeration to ScanCode and VirtualKey	MapVirtualKey(vk, MAPVK_VK_TO_VSC)	0
2899116	2899090	compare a brush and color	if(((SolidColorBrush)backBrush).Color == SystemColors.ActiveCaption)	0
15932732	15932666	Error using .RemoveAt to delete a DataTable row in a loop	int maxRows = AfdelingDT.Rows.Count;\nmaxRows -= 1;\nfor(int i = maxRows;i >= 0; i--)\n{\n   if (Convert.ToInt16(AfdelingDT.Rows[i][0]) == Convert.ToInt16(removeRowTB.Text))\n   {\n      AfdelingDT.Rows.RemoveAt(i);\n   }\n}	0
16503126	16503079	Ruby, variables and their C# equivalent	class MyClass: IMyInterface {\n\n    // "const" makes it constant, not the name\n    public const int CONSTANT = 42;\n\n    // static member variable - somewhat like Ruby's @@variable\n    private static int classVariable;\n    public static int ExposedClassVariable; // but use properties  \n\n    // @variable - unlike Ruby, can be accessed outside "self" scope\n    int instanceVariable;\n    public int ExposedInstanceVariable;     // but use properties\n\n    void method (int parameter) {\n        int localVariable;\n    }\n}	0
31479462	31479345	Error populating a kendo grid using Json	o.Customers != null ?   o.Customers.ShortName  : ""	0
4430810	4430699	Listview upload control	FileUploadControl.FileName	0
11762346	11748803	How to reflect text from a text box to a datagrid	private void textBoxURL_TextChanged(object sender, EventArgs e)\n    {\n        try\n        {\n            foreach (DsVersions.ASSEMBLY2Row row in dsVersions.ASSEMBLY2.Rows)\n            {\n                row.URL = textBoxURL.Text;\n            }\n        }\n        catch\n        {\n\n        }\n    }	0
5271489	5271442	Deserializing into a List without a container element in XML	[XmlElement("result")]\npublic List<Result> Results { get; set; }	0
13730136	13723284	how to get the RadTab of RadPageView control	var a = rmpProjectStatus.FindPageViewByID(txtMyTextBox2.Parent.ID).Index ;	0
3982359	3971523	working with images as a database table column	string conn = "Data Source=servername\\SQL2008; Initial Catalog=MyData;UID=MyID;PWD=mypassword;";\n        using (SqlConnection dbConn = new SqlConnection(conn))\n        {\n            dbConn.Open();\n            string sql = "SELECT DATALENGTH(image_column), image_column FROM images_table ";\n            using (SqlCommand cmd = new SqlCommand(sql, dbConn))\n            {\n                using (SqlDataReader reader = cmd.ExecuteReader())\n                {\n                    while (reader.Read())\n                    {\n                        int size = reader.GetInt32(0);\n                        byte[] buff = new byte[size];\n                        reader.GetBytes(1, 0, buff, 0, size);\n                        MemoryStream ms = new MemoryStream(buff, 0, buff.Length);\n                        ms.Write(buff, 0, buff.Length);\n                        StoreImage(Image.FromStream(ms, true));\n                    }\n                }\n            }\n        }	0
23862687	23862677	Parameter optional from controller	pubblic ActionResult Comentar()\n     {\n          return RedirectToAction("GeneralTop",new {name:"test",option:4,id:3});\n     }	0
14509940	14508699	XML AppendChild not writing to the xml file when used in a loop	XmlElement dataElm = xdoc.CreateElement(@"rs:data");\ndataElm.InnerText = contents;\nxdoc.DocumentElement.AppendChild(dataElm);	0
19594324	19594218	NUnit how can I prevent code repetition	[Test]\npublic void Transform_NonNullOptionObject_ValuePropertyIsTheSame()\n{\n    OptionObjectTransform transform = InitTransform();\n    CustomOptionObject result = transform.Transform(optionObject);\n    var expected = new[] { optionObject.Value, optionObject.FormCode };\n    var actual = new[] { result.Value, result.FormCode };\n    Assert.AreEqual(expected, actual);\n}	0
22165550	22165525	Like statement equivalent in Windows Azure table	myTable.Where(userinfo => userinfo.Username.StartsWith("D");	0
20202181	20040338	Not able to see my linkbutton control inside a <td> element	sb.Append("<a href=\"#\" onclick=\"openNewWin('" + texturl + "')\" >Read More...</a>");	0
20982819	20981467	How to create a Byte array that contains a real Image?	private void Button_Click_1(object sender, RoutedEventArgs e)\n    {\n        Random rnd = new Random();\n\n        Byte[] ByteArray = new Byte[(int)MyImage.Width * (int)MyImage.Height * 3];\n\n        rnd.NextBytes(ByteArray);\n\n        var image = BitmapSource.Create((int) MyImage.Width, (int) MyImage.Height, 72, 72,\n            PixelFormats.Bgr565, null, ByteArray, (4*((int)MyImage.Width * 16 + 31)/32));\n\n        MyImage.Source = image;\n    }	0
5757359	5757324	Is there Boxing/Unboxing when casting a struct into a generic interface?	void bar<T>(T value) where T : IComparable<T> { /* etc. */ }	0
6521552	6521473	how we can attach Ajax model popup with a Data grid default edit button	ModalPopup Demonstration	0
2852603	2852167	C# Same DataSource + Multiple DataGridViews = Data Binding Issues?	dsInformation.AcceptChanges();	0
6029387	6029254	How to implement usage of multiple strategies at runtime	public interface IProcessor\n{         \n    ICollection<OutputEntity> Process(ICollection<InputEntity>> entities);\n    string SomeField{get;set;}\n}\n\n\npublic class Engine\n{\n    public Engine(IEnumerable<IProcessor> processors)\n    {\n        //asign the processors to local variable\n    }\n\n    public void ProcessRecords(IService service)\n    {\n        // getRecords code etc.\n        foreach(var processor in processors)\n        {\n            processor.Process(typeRecords.Where(typeRecord => typeRecord.SomeField == processor.SomeField));\n        }\n    }\n}	0
1856679	1856663	How to start another project in the solution in Debug mode	System.Diagnostics.Debugger.Launch();	0
15954667	15954524	Program wait for an event to occur in c#	private void button2_Click(object sender, EventArgs e)\n {\n    if (this.textBox3.Text != "")\n    {\n       this.listView1.Items.Clear();\n       button3.Click += Function;\n    }\n }\n private void Function(object sender, EventArgs e)\n {\n     this.listView1.Items.Add(this.textBox3.text);\n     button3.Click -= Function;\n }	0
25187876	25187103	How to display the sorting arrow on page load and during sort in GridView	ViewState["sortExp"] = e.SortExpression;\nPullData(e.SortExpression, sortOrder);	0
33889265	25258365	wcf task with parameters	public IAsyncResult BeginSomeMethod(string parameter1, string parameter2, AsyncCallback callback, object state)\n    {\n\n        var task = Task<List<int>>.Factory.StartNew((res) => my_function(state, parameter1, parameter2), state);\n        return task.ContinueWith(res => callback(task));\n    }\n\n    public List<int> EndSomeMethod(IAsyncResult result)\n    {\n        return ((Task<List<int>>)result).Result;\n    }\n\n    private List<int> my_function(object state, string parameter1, string parameter2)\n    {\n        //implementation goes here\n    }	0
28611374	28610915	System.ArgumentOutOfRangeException in a gridview	protected void Btn1_Click(object sender, EventArgs e)\n{\n    Button btn = (Button)sender;\n    GridViewRow gvRow = (GridViewRow)btn.NamingContainer;\n    string rute = gvRow.Cells[0].Text;\n    string rute1 = gvRow.Cells[1].Text;\n    string rute2 = gvRow.Cells[2].Text;\n    string rute3 = gvRow.Cells[3].Text;\n    string rute4 = gvRow.Cells[4].Text;\n}	0
5725858	5725846	how to get string from string list?	var result = stringList.Where(i => i.StartsWith("04"));	0
20476566	20476455	Decrypting The Password From Cipher Text To Plain Text	protected void btnAuthenticate_Click(object sender, EventArgs e)\n{\n    string EPass = Helper.ComputeHash(txtPassword.Text, "SHA512", null);\n    if (EPass == lblmsg.Text) \n    {\n        Label1.Text = "You are the correct user";       \n    }\n}	0
30926550	30926137	Read Node attributes from XML file	var cityList = new List<City>();            \nXDocument xDoc = XDocument.Load(Server.MapPath("/App_Data/Countries.xml"));\nforeach (XElement xCountry in xDoc.Root.Elements())\n{\n    int id = int.Parse(xCountry.Element("Id").Value);\n    string name = xCountry.Element("City").Value;                \n    cityList.Add(new City(id, name));\n}	0
26272660	26171577	How to post image as byte array in visual studio webtest	public async Task<ResponseEntity<SendStreamResponse>> Post([FromUri]int jobId)\n{\n    byte[] stream = await Request.Content.ReadAsByteArrayAsync();\n\n    return await SendStreamAsync(jobId, stream);\n}	0
15100385	15100143	Editable cells in ReadOnly Columns DataGridView	Foreach(DataGridViewRow row in DataGridView1.Rows)\n{\n   If(!row.Cells[2].Value.Equals(null) || !row.Cells[2].Value.Equals(String.Empty))\n     {\n        row.Cells[2].ReadOnly = true;\n     }\n}	0
6767272	6767192	C# Open Office Documents and Xps Files from MemoryStream	System.IO.Stream docStream = ...any xps as stream;\nPackage package = Package.Open(docStream);\n\n//Create URI for Xps Package\n//Any Uri will actually be fine here. It acts as a place holder for the\n//Uri of the package inside of the PackageStore\nstring inMemoryPackageName = string.Format("memorystream://{0}.xps", Guid.NewGuid());\nUri packageUri = new Uri(inMemoryPackageName);\n\n//Add package to PackageStore\nPackageStore.AddPackage(packageUri, package);\n\nXpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);\nFixedDocumentSequence fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence();\n\n// Do operations on xpsDoc here\nDocViewer.Document = fixedDocumentSequence;\n\n//Note: Please note that you must keep the Package object in PackageStore until you\n//are completely done with it since certain operations on XpsDocument can trigger\n//delayed resource loading from the package.\n\n//PackageStore.RemovePackage(packageUri);\n//xpsDoc.Close();	0
23113049	23109821	Selenium IWebElement matches selector	public static bool ElementIs(this IWebDriver driver, IWebElement item, By selector)\n    {\n        return (bool)(driver as IJavaScriptExecutor).ExecuteScript(string.Format("return $(arguments[0]).is(\"{0}\")", selector.ToString().Split(' ')[1]), item);\n    }	0
584356	579921	How do i get the the full name of the proxyed type for a nhibernate DynamicProxy?	((INHibernateProxy)proxy).HibernateLazyInitializer.PersistentClass	0
3699146	3699084	how to remove namespace from XML root element?	public class BINDRequest\n{\n    [XmlAttribute]\n    public string CLIENT_REQUEST_ID { get; set; }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var request = new BINDRequest\n        {\n            CLIENT_REQUEST_ID = "123"\n        };\n        var serializer = new XmlSerializer(request.GetType());\n        var xmlnsEmpty = new XmlSerializerNamespaces();\n        xmlnsEmpty.Add("", "");\n        using (var writer = XmlWriter.Create("result.xml"))\n        {\n            serializer.Serialize(writer, request, xmlnsEmpty);\n        }\n    }\n}	0
8471351	8471197	How to load image from binary data in Asp.Net?	string encodedString = "your image data encoded as base 64 char array";\nbyte[] data = Convert.FromBase64String(encodedString);\n\nResponse.BinaryWrite(data);	0
3997715	3997677	cannot convert string to char	sb.AppendFormat("mboxCreate(\"product_productpage_rec{0}\")", i);	0
13519719	13519706	Convert string to data in form of dd/mm/yyyy	"dd/MM/yyyy"	0
27901348	27901059	Can't save sound from microphone	private void btnStopnSave_Click(object sender, EventArgs e)\n  {\n     label1.Visible = false;\n     mciSendString("pause Som", null, 0, 0);\n\n     string filename = "whatever";\n     mciSendString("save Som " + filename, null,0, 0);\n     mciSendString("close Som", null, 0, 0);\n  }	0
25012399	25012043	C# chart data won't display	Refresh();	0
3914517	3912938	How can I capture CTRL-BACKSPACE in WPF/C#?	Key key = (e.Key == Key.System ? e.SystemKey : e.Key);\nif (e.KeyboardDevice.Modifiers == ModifierKeys.Control) {\n    switch (key) {\n        case Key.A: keyStroke = 0x01; break;\n        case Key.B: keyStroke = 0x02; break;\n        case Key.Back: // Do something\n        break;\n    }\n}	0
11019920	10846295	Select item with null value in DevExpress Combobox with datasource	protected void PREFERENCE_DataBound(object sender, EventArgs e)\n    {\n        for (int i = 0; i < PREFERENCE.Items.Count; i++)\n        {\n            if (PREFERENCE.Items[i].GetValue("ID") == DBNull.Value)\n                PREFERENCE.Items[i].Selected = true;\n        }\n    }	0
17321025	17302577	how to bind XtraReport to password protected sqlce(3.5) in C# wpf?	string password = GetPasswordFromTheUser();\nXtraReport report = new MyReport();\nSomeTableTableAdapter adapter = (SomeTableTableAdapter)report.DataAdapter;\nadapter.Connection.ConnectionString += ";Password=" + password;\nreport.ShowPreviewDialog();	0
9474127	8406377	HTTP response header, format for "Expires"	DateTime.Now.AddDays(30).ToUniversalTime()\n    .ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'");	0
28415788	28396436	c# serialize dictionary into xml file	static public class XmlDictionarySerializer<A, B>\n{\n    public class Item\n    {\n        public A Key { get; set; }\n        public B Value { get; set; }\n    }\n\n    static public void Serialize(IDictionary<A, B> dictionary, string filePath)\n    {\n        List<Item> itemList = new List<Item>();\n        foreach (A key in dictionary.Keys)\n        {\n            itemList.Add(new Item() { Key = key, Value = dictionary[key] });\n        }\n\n        XmlDataSerializer.Serialize<List<Item>>(itemList, filePath);\n    }\n\n    static public Dictionary<A, B> DeserializeDictionary(string filePath)\n    {\n        Dictionary<A, B> dictionary = new Dictionary<A, B>();\n        List<Item> itemList = XmlDataSerializer.Deserialize<List<Item>>(filePath);\n        foreach (Item item in itemList)\n        {\n            dictionary.Add(item.Key, item.Value);\n        }\n        return dictionary;\n    }\n}	0
28824107	28824053	How to use transactions for different contexts?	try\n{\n    res = DoFirstSubOperation(context);\n    if (res) \n        res = DoSecondSubOperation(context);\n    if (res) \n        res = DoThirdSubOperation(context);    \n\n    if (res)\n        transaction.Commit();\n    else\n        transaction.Rollback();\n}\ncatch\n{\n    transaction.Rollback();\n}	0
26269110	26250949	Convert C# Byte Array to Object Threw SerializationException	private byte[] Compress(DataSet dataset)\n{\n    Byte[] data;\n    MemoryStream mem = new MemoryStream();\n    GZipStream zip = new GZipStream(mem, CompressionMode.Compress);\n    dataset.WriteXml(zip, XmlWriteMode.WriteSchema);\n    zip.Close();\n    data = mem.ToArray();\n    mem.Close();\n    return data;\n}\n\nprivate DataSet Decompress(Byte[] data)\n{\n    MemoryStream mem = new MemoryStream(data);\n    GZipStream zip = new GZipStream(mem, CompressionMode.Decompress);\n    DataSet dataset = new DataSet();\n    dataset.ReadXml(zip, XmlReadMode.ReadSchema);\n    zip.Close();\n    mem.Close();\n    return dataset;\n}	0
32250387	32250244	How to delete a registry key using c#	string str = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts";\nstring[] strSplit = strLocal.Split('\\');\n            using (RegistryKey oRegistryKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts", true))\n            {\n                RegistryKey hdr = oRegistryKey.OpenSubKey(strSplit[strSplit.Length-2], true);\n                foreach (String key in hdr.GetSubKeyNames())\n                    hdr.DeleteSubKey(key);\n                hdr.Close();\n                oRegistryKey.DeleteSubKeyTree(strSplit[strSplit.Length - 2]);\n            }	0
8678045	8676876	Finding a control inside another control in WPF	TextBlock objTextBlock = (TextBlock)LogicalTreeHelper.GetChildren(objHyperlink).Cast<System.Windows.Documents.InlineUIContainer>().FirstOrDefault().Child;	0
15207381	15207186	Custom ListBox with transparent backcolor issue	protected override void OnPaintBackground(PaintEventArgs pevent)\n{\n    IntPtr hdc = pevent.Graphics.GetHdc();\n    Rectangle rect = this.ClientRectangle;\n    NativeMethods.DrawThemeParentBackground(this.Handle, hdc, ref rect);\n    pevent.Graphics.ReleaseHdc(hdc);\n}\n\n\ninternal static class NativeMethods\n{\n    [DllImport("uxtheme", ExactSpelling = true)]\n    public extern static Int32 DrawThemeParentBackground(IntPtr hWnd, IntPtr hdc, ref Rectangle pRect);\n}	0
20701479	20681157	crystal reports fix group section height	1. Insert 11 group sections.\n2. Place the data field in 1st group section. \n3. In the remaining 10 group sections place a line and write the supress condition for individual group section on the number of records retrived. For e.g if 5 records are retrived then 5 group sections with lines should get displayed and remaining sections with lines should get supressed, If 10 records are retrived then all 10 sections should get supressed.	0
27291902	27291720	Create XML Amazon Envelope in C#	XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";\nvar elm = new XElement("AmazonEnvelope",\n                       new XAttribute(XNamespace.Xmlns + "xsi", ns),\n                       new XAttribute(ns + "noNamespaceSchemaLocation", "amzn-envelope.xsd"));	0
10484652	10484501	Pushing data from an ASP.NET MVC Controller to a View	long polling	0
12976459	12976118	Performing a Parent then Child sort in Linq	return myData.Select(x => new { key = (x.Parent ?? x).Type, item = x})\n             .OrderBy(x => x.key)\n             .ThenBy(x => x.item.Parent != null)\n             .Select(x => x.item);	0
1907165	1907077	Serialize a Bitmap in C#/.NET to XML	[XmlIgnore]\npublic Bitmap LargeIcon { get; set; }\n\n[Browsable(false),EditorBrowsable(EditorBrowsableState.Never)]\n[XmlElement("LargeIcon")]\npublic byte[] LargeIconSerialized\n{\n    get { // serialize\n        if (LargeIcon == null) return null;\n        using (MemoryStream ms = new MemoryStream()) {\n            LargeIcon.Save(ms, ImageFormat.Bmp);\n            return ms.ToArray();\n        }\n    }\n    set { // deserialize\n        if (value == null) {\n            LargeIcon = null;\n        } else {\n            using (MemoryStream ms = new MemoryStream(value)) {\n                LargeIcon = new Bitmap(ms);\n            }\n        }\n    }\n}	0
12401158	12382247	Date in X-Axis - .Net Charts	Chart1.ChartAreas["ChartArea1"].AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;\n        Chart1.Series["Series1"].XValueType = ChartValueType.Date;\n        DayOfWeek ds = DayOfWeek.Wednesday;\n        double dblIntervalOffset = Convert.ToDouble(ds);\n        Chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = dblIntervalOffset;\n        Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = min;\n        Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = max;\n        Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 7;\n        Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = false;	0
12206079	12205766	Getting control from Repeater ItemTemplate server-side	if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType !=   \n       ListItemType.AlternatingItem) return;	0
12854095	12854031	How do i color a specific part of text in a richTextBox?	public void ColorText(RichTextBox box, Color color)\n        {\n            box.Select(start, 5);\n            box.SelectionColor = color;\n        }	0
4079616	4079483	how to change a c# console project to windows forms application project?	[STAThread]\nstatic void Main() {\n    Application.EnableVisualStyles();\n    Application.SetCompatibleTextRenderingDefault(false);\n    Application.Run(new YourMainForm());\n}	0
32452252	32451923	How to create SyntaxFactory.UsingStatement in Roslyn through string	SyntaxFactory\n.UsingStatement(SyntaxFactory.Block()/* the code inside the using block */)\n.WithDeclaration(SyntaxFactory\n    .VariableDeclaration(SyntaxFactory.IdentifierName("var"))\n    .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory\n         .VariableDeclarator(SyntaxFactory.Identifier("logger"))\n         .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory\n             .ObjectCreationExpression(SyntaxFactory.IdentifierName(@"MethodLogger"))\n             .WithArgumentList(/* arguments for MethodLogger ctor */)))	0
20801947	20801910	Getting error when trying to insert a value into a database and get the last inserted id	createorder = new SqlDataAdapter("INSERT INTO [order] (user_id, date) VALUES ('" + userno2 + "', '12-12-2013');select SCOPE_IDENTITY();", con);	0
7690804	7690313	Dynamically deny access to locations	void Page_Load( ... ) \n{\n    if ( this.Context.User != null &&\n         !this.Context.User.IsInRole( "FileDeny" )\n        )\n       Response.Redirect( FormsAuthentication.LoginUrl );	0
16447215	16447171	C# Application Lags when Communicating over TCP	void StartListener()\n{\n    System.Threading.Thread listenerThread = new System.Threading.Thread(ListenerThread));\n    listenerThread.IsBackground = true; // Causes the thread to close if the app is closed\n    listenerThread.Start();\n}\n\nvoid ListenerThread()\n{\n    TcpListener tcp = new TcpListener(IPAddress.Parse("192.168.1.66"),9000);\n    tcp.Start();\n    UpdateStatus("Start Listening \r\n"); //1\n    Socket s = tcp.AcceptSocket();\n    UpdateStatus("Client Has Connected \r\n"); //1\n\n    // Listen for more messages, or close the listener here.\n}\n\nvoid UpdateStatus(string message)\n{\n    if(InvokeRequired)\n        Invoke((MethodInvoker)delegate { UpdateStatus(message); });\n    else\n        Textbox.Text = message;\n}	0
32620475	32620337	Using all the dates in a given table	(LoanStatus = 'Approved' and ApprovalDate > @startDate AND ApprovalDate < @endDate) OR (LoanStatus = 'Settled' and SettleDate > @startDate AND SettleDate < @endDate) OR ... same for the rest of loan status values	0
2074225	2074019	Fixing number of decimals in crystal report	Format Field...	0
20571970	20571894	Enable remote blog publishing for custom blog engine	MetaWeblog API	0
12191534	12191102	How to create a camera capture guide line bars	Point tapLocation = e.GetPosition(viewfinderCanvas);\n\n// Position the focus brackets with the estimated offsets.\nfocusBrackets.SetValue(Canvas.LeftProperty, tapLocation.X - 30);\nfocusBrackets.SetValue(Canvas.TopProperty, tapLocation.Y - 28);\n\n// Determine the focus point.\ndouble focusXPercentage = tapLocation.X / viewfinderCanvas.Width;\ndouble focusYPercentage = tapLocation.Y / viewfinderCanvas.Height;\n\n// Show the focus brackets and focus at point.\nfocusBrackets.Visibility = Visibility.Visible;\ncam.FocusAtPoint(focusXPercentage, focusYPercentage);	0
21701819	18963178	Sending null parameters to Sql Server	command.Parameters.AddWithValue("@param1", param1 ?? Convert.DBNull);	0
9318136	9318016	string with special characters conversion	//On the sender side\nbyte[] bytesA = Encoding.Default.GetBytes(A);\nbyte[] bytesB = Encoding.Default.GetBytes(B);\nstring encA = Convert.ToBase64String(bytesA);\nstring encB = Convert.ToBase64String(bytesB);\n\nstring C = encA + "|" + encB;\n\n//On the receiver side\nstring[] parts = C.Split('|');\nstring A = Encoding.Default.GetString(Convert.FromBase64String(parts[0]));\nstring B = Encoding.Default.GetString(Convert.FromBase64String(parts[1]));	0
11018467	11018371	Recursion, C# with array of char after return	static void PrintReverse(ref char[] Chars)\n{\n    Console.Write(Chars[Chars.Length - 1]);\n    Array.Resize(ref Chars, Chars.Length - 1);\n    if (Chars.Length == 0) return;\n    PrintReverse(ref Chars);\n}	0
19446490	19446342	inheritance of private members in c#	public class Base\n{\n    private int value = 5;\n\n    public int GetValue()\n    {\n        return value;\n    }\n}\n\npublic class Inherited : Base\n{\n    public void PrintValue()\n    {\n        Console.WriteLine(GetValue());\n    }\n}\n\nstatic void Main()\n{\n    new Inherited().PrintValue();//prints 5\n}	0
7488015	7487955	Getting a distinct list with additon of the totals	var results = methodList\n                   .Select(l => l.Split(';'))\n                   .GroupBy(a => a[0])\n                   .Select(g => \n                       new \n                       {\n                           Group = g.Key, \n                           Count = g.Count(),\n                           Total = g.Sum(arr => Int32.Parse(arr[1])) \n                       });\n\n foreach(var result in results)\n      Console.WriteLine("{0} {1} {2}", result.Group, result.Count, result.Total);	0
22401594	22401575	Parse list of numbers from "dirty" string	var r = new Regex(@"\d+");\nvar result = r.Matches("fr365.43//236hu");\nforeach (Match match in result)\n{\n    Console.WriteLine(match.Value);\n}\n// outputs 365 then 43 then 236	0
24952877	24952830	Check if string contains strictly a string	bool bFound = str.split('|').Contains("p1")	0
6254414	6254389	Linq query to get items out of set of sets	listOfClassA.SelectMany(a => a.ListOfClassB).Distinct();	0
27098351	27077834	How to Remove Apply Button in a Telerik RadColorPicker From Code Behind	'Code behind\ncolourPicker.CssClass="noApplyButtonColorPicker" 'ADDING A CSS CLASS HERE WILL ENSURE THAT IT APPLIES ONLY TO COLOUR PICKERS WHICH YOU CHOOSE TO.\n\n/*CSS*/\n.noApplyButtonColorPicker .rcpApplyButton\n{\n  display:none !important;\n}	0
15616682	15616625	Denied Accessing files in C#	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
12477714	12477686	Can't convert string[] to byte[]	{\n    image = Path.Combine("Images", "Gallery", album.Substring(94), file);\n    tempFile = File.ReadAllBytes(image);\n}	0
26955437	26955405	How to pass Form2 button click value to Form 1	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        Alert AlertObj = new Alert();\n\n        if (AlertObj.ShowDialog() == DialogResult.Yes)\n            textBox1.Text = AlertObj.ResultText ;\n        else\n            textBox1.Text = "No";\n\n    }\n}\n\n\n public partial class Alert : Form\n{\n    public Alert()\n    {\n        InitializeComponent();\n    }\n\n    public string ResultText {get; set;}\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        ResultTest = "Yes";\n        DialogResult = DialogResult.Yes;    \n    }\n}	0
6389663	6389608	Windows Phone 7 Empty Data message for Listbox?	public bool IsDataLoaded\n{\n    get\n    {\n        return _IsDataLoaded;\n    }\n    set\n    {\n        _IsDataLoaded = value;\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs("IsDataLoaded"));\n            PropertyChanged(this, new PropertyChangedEventArgs("EmptyMessage"));\n        }\n    }\n}	0
6093635	6093598	How to declare the KeyPress Event Handler in a common way to all TextBoxes?	foreach (var control in this.Controls)\n {\n     var text = control as RichTextBox;\n     if (text != null)\n          text.KeyPress += new KeyPressEventHandler(this.Comn_KeyPress);\n }	0
23070883	23070517	Get dataGridView selected row value	richTextBox1.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();	0
1844624	1844461	How can I search into database with WPF and Linq-to-entities model	var Query = Context.MyDataSet; //Whatever is the standard base query\n\nif (!string.IsNullOrEmpty(NameFilter))\n    Query = Query.Where(e => e.Name.Contains(NameFilter));\n\nif (!string.IsNullOrEmpty(SurnameFilter))\n    Query = Query.Where(e => e.Surname.Contains(SurnameFilter));\n\n...\n\nvar Result = Query.ToList();	0
13234659	13181884	Searching a String using C#	string input = @"</script><div id='PO_1WTXxKUTU98xDU1'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>";\n        string startString = "div id='";\n\n        int startIndex = input.IndexOf(startString);\n\n        if (startIndex != -1)\n        {\n            startIndex += startString.Length;\n            int endIndex = input.IndexOf("'", startIndex);\n            string subString = input.Substring(startIndex, endIndex - startIndex);\n        }	0
5565137	5565105	How to IsSelected a ComboBoxItem in code behind?	comboBox1.SelectedIndex = 0;	0
25507650	25507084	How to Join single table to it self in SQL Server 2008?	Create table  #UnsplitData (EmpCode varchar (10), ReportsTo varchar(20), FirstName varchar (10)) \ninsert into #UnsplitData\nvalues ('emp_0101', 'emp_0102,emp_0103', 'John')\n, ('emp_0102', 'emp_0103', 'Sally')\n, ('emp_0103', Null, 'Steve')\n\n\n\nselect *, employee.FirstName + ', ' + Reports.FirstName\nfrom  #UnsplitData Employee \njoin \n(\n    select t.EmpCode , split.value  as Reportsto, ReportName.Firstname\n    from  #UnsplitData t\n    cross apply dbo.fn_Split( ReportsTo, ',') split\n    join #UnsplitData ReportName \n        on ReportName.EmpCode = split.value\n) Reports\n    On Employee.EmpCode = Reports.empcode	0
23538584	23538213	Do I have to implement a ViewModel when using multiple Models in one View?	public class MainViewModel\n{\n    public ModelA ModelA { get; set; }\n    public ModelB ModelB { get; set; }\n}	0
21235804	21235758	CenterScreen Window on Un-Maximizing, on StateChanged	var workingArea = System.Windows.SystemParameters.WorkArea;\nthis.Left = (workingArea.Width - this.Width) / 2 + workingArea.Left;\nthis.Top = (workingArea.Height - this.Height) / 2 + workingArea.Top;	0
23274724	23274723	Weird issue when removing columns from a datatable	for (int x = 0; x < csv_datatable.Columns.Count; x++)\n{\n    csv_datatable.Columns.RemoveAt(3);\n}	0
2649697	2649685	3 Dimensional Array	myarray = new int[1,width, height];	0
30017157	30016541	Using DispatcherTimer with a BackgroundWorker and a ProgressBar	private void UpdateProgressbar(int percentage)\n{\n    if (InvokeRequired)\n    {\n        this.BeginInvoke(new Action<int>(UpdateProgressbar), new object[] { percentage });\n        return;\n    }\n\n    pb.Value = percentage;\n}\n\nprivate void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    UpdateProgressbar(e.ProgressPercentage);           \n}	0
265938	265896	How do I delete a read-only file?	using System.IO;\n\nFile.SetAttributes(filePath, FileAttributes.Normal);\nFile.Delete(filePath);	0
7751985	7751901	Fastest way possible to validate a string to be only Alphas, or a given string set	foreach(char c in Value)\n{\n   if(!char.IsLetter(c))\n      return false;\n}	0
15344141	15343854	_doPostBack passing parameter	Request["__EVENTARGUMENT"]	0
22449130	22449071	Set time value to tomorrow 9 am	DateTime.Today.AddDays(1).AddHours(9)	0
5934143	5934080	Using select scoped value in insert statements?	String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity,\n    CustState, CustZip, SubId) \nVALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem +   \n    "', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" + \n    DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "'," + \n    newSubID.toString() + ")";	0
28056452	28056386	How do I multiply two inputs from the user (console)?	int hours = Int32.Parse(hrsWrkd);\nstring grossPay = (hourlyRate * hours).ToString();	0
457504	457307	Setting access rights for a directory - receiving exception "No flags can be set"	DirectoryInfo dirInfo = new DirectoryInfo("C:\\TestDir2");\n            DirectorySecurity dirSecurity = dirInfo.GetAccessControl();\n\n            dirSecurity.AddAccessRule(new FileSystemAccessRule("ASPNET", FileSystemRights.Write|FileSystemRights.DeleteSubdirectoriesAndFiles, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));\n\n\n            dirInfo.SetAccessControl(dirSecurity);	0
21665230	21664288	entity framework - two people with the same data	public class PrivateMessageHeader {\n    public PrivateMessageHeader() { Messages = new List<PrivateMessageDetail>; }\n    public int PrivateMessageHeaderId {get;set;}\n    public DateTime ThreadTime {get;set;} // Date of the start of thread\n    public string User1 {get;set;}\n    public string User2 {get;set;}  // this could be made to a list to allow multiples\n\n    public ICollection<PrivateMessageDetail> Messages {get;set;}\n}\n\npublic class PrivateMessageDetail {\n    public int PrivateMessageDetailId {get;set;}\n    public DateTime MessageDate {get;set;}\n    public string FromUser {get;set;} // Don't need ToUser, it's already in header\n    public string Message {get;set;}\n\n    public PrivateMessageHeader parent {get;set;}\n}	0
23891421	23891184	How to Save a Boolean Value in C#	private void Form1_Load(object sender, EventArgs e)\n{\n    cookiecutter = Convert.ToBoolean(Properties.Settings.Default.cookiecutter);\n}\n\nprivate void Form1_FormClosed(object sender, FormClosedEventArgs e)\n{\n    Properties.Settings.Default.cookiecutter = cookiecutter;\n    Properties.Settings.Default.Save();\n}	0
3899678	3899644	Convert python to c#	class Program\n{\n    static void Main()\n    {\n        var secret = "secret";\n        var data = "data";\n        var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));\n        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));\n        Console.WriteLine(BitConverter.ToString(hash));\n    }\n}	0
20622511	20622005	Xml Deserializer to deserialize 2-Dimensional Array	public static void Main()\n    {\n\n        int[,] B = new int[2, 5];\n        B[0, 0] = 5;\n        B[0, 1] = 3;\n        B[0, 2] = 5;  \n\n        DeepSerialize<int[,]>( B,"test3");\n        int[,] des= DeepDeserialize<int[,]>("test3");\n\n\n\n    }\n\n public static void DeepSerialize<T>(T obj,string fileName)\n    {\n        //            MemoryStream memoryStream = new MemoryStream();\n        FileStream str = new FileStream(fileName, FileMode.Create);\n        BinaryFormatter binaryFormatter = new BinaryFormatter();\n        binaryFormatter.Serialize(str, obj);\n        str.Close();\n    }\n    public static T DeepDeserialize<T>(string fileName)\n    {\n        //            MemoryStream memoryStream = new MemoryStream();\n        FileStream str = new FileStream(fileName, FileMode.Open);\n\n        BinaryFormatter binaryFormatter = new BinaryFormatter();\n        T returnValue = (T)binaryFormatter.Deserialize(str);            \n        str.Close();\n        return returnValue; \n    }	0
6965228	6965184	How to set filter for FileSystemWatcher for multiple file types?	FileSystemWatcher objWatcher = new FileSystemWatcher(); \nobjWatcher.Filter = "*.*"; \nobjWatcher.Changed += new FileSystemEventHandler(OnChanged); \n\nprivate static void OnChanged(object source, FileSystemEventArgs e) \n{ \n    // get the file's extension \n    string strFileExt = getFileExt(e.FullPath); \n\n    // filter file types \n    if (Regex.IsMatch(strFileExt, @"\.txt)|\.doc", RegexOptions.IgnoreCase)) \n    { \n        Console.WriteLine("watched file type changed."); \n    } \n}	0
8910187	8910120	Need to know when a non-modal window has closed	Window childWindow = new ....\nchildWindow.Closed += (sender, e) =>\n    {\n        // Put logic here\n        // Will be called after the child window is closed\n    };\nchildWindow.Show();	0
9377740	9377290	SynchronizationContext.Current is null on resolving with Unity in WPF	// Must run in the main thread\ncontainer.RegisterInstance(SynchronizationContext.Current);	0
16020831	16018835	Open Windows form from non UI thread	var th = new Thread(() =>\n{\n    var form = new YourForm();  \n    form.FormClosing += (s, e) => Application.ExitThread();\n    form.Show();\n    Application.Run();\n});\nth.SetApartmentState(ApartmentState.STA);\nth.Start();	0
3467628	3467518	how to take 6 numbers after the dot - but without round the number?	System.Math.Truncate (102.123456789 * factor) / factor;	0
13515342	13515145	How to Loop Through CheckBoxList and insert if Box is checked	connection.Open()\nvar insertUser = new SqlCommand(insCmd, connection);   \n\nforeach(var item in CheckBoxList1.Items)\n{\n  if(!item.Selected) continue;\n  insertUser.Parameters.Clear();\n  // your code where you can use Item.Text to add parameters\n  // i have no idea about your textboxes though \n  insertUser.ExecuteNonQuery();\n}\nconnection.Close();	0
29327689	29148484	Handle multiple similar requests in webapi	[HttpPost]\npublic void Post(IEnumerable<InstagramUpdate> instagramUpdates)\n{\n    foreach (var instagramUpdate in instagramUpdates)\n    {\n        if (WaitingToProcessSubscriptionUpdate(instagramUpdate.Subscription_id))\n        {\n            // Ongoing request, do nothing\n        }\n        else\n        {\n            // Process update\n        }\n    }\n}\n\nprivate bool WaitingToProcessSubscriptionUpdate(string subscriptionId)\n{\n    // Check in the in memory cache if this subscription is in queue to be processed. Add it otherwise\n    var queuedRequest = _cache.AddOrGetExisting(subscriptionId, string.Empty, new CacheItemPolicy\n    {\n        // Automatically expire this item after 1 minute (if update failed for example)\n        AbsoluteExpiration = DateTime.Now.AddMinutes(1)\n    });\n\n    return queuedRequest != null;\n}	0
5484639	5471515	WebDriver + C# + Select a value from drop down	WebElement dateOfBirth =  webdriver.FindElement(By.Id("join_birth_day")).FindElement(By.CssSelector("option[value='3']")).Select();	0
5766898	5766494	Word Interop app to write text to the end of an open document	Marshal.GetActiveObject("Word.Application")	0
2499462	2499314	Number of repeating in multidimensional array	int[][] jaggedArray =\n{\n    new[] { 1, 1, 2 },\n    new[] { 2, 1, 3 },\n    new[] { 1, 2, 1 }\n};\n\nforeach (var number in Enumerable.Range(1, 3))\n{\n    Console.Write("Number " + number + "-  ");\n    for (int index = 0; index < jaggedArray.Length; index++)\n    {\n        int[] innerArray = jaggedArray[index];\n\n        var count = innerArray.Count(n => n == number);\n\n        Console.Write(count + " times on position " + (index + 1) + ", ");\n    }\n\n    Console.WriteLine();\n}	0
24903656	24648529	How to set cell formatting in particular column in datagridview using VB.Net?	Private Sub grdLedgerDetails_EditingControlShowing(sender As Object, e As                    System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdLedgerDetails.EditingControlShowing\n    Select grdLedgerDetails.CurrentCell.ColumnIndex\n        Case 2, 3\n            RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress\n        Case 4, 5\n            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress\n    End Select\nEnd Sub\n\n\n\nPrivate Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)\n    If Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And e.KeyChar <> "." Then\n        e.Handled = True\n    End If\n       End Sub	0
11222913	11222850	How to initialize a contructor which accepts DropDownList array?	DropDownList[] parameter = new DropDownList[1]; // create an array of DropDownList \n\nparameter[0] = DropDownList1; // add DropDownList1 to the array (the reference to the drop down list you want include)\n\nvar yourClass = new FillDropDowns(parameter); // make a new instance of the class by passing the array via the constructor	0
11000008	10999782	Creating VCS file via C# but either outlook or C# don't like my dates	BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//hacksw/handcal//NONSGML v1.0//EN\nBEGIN:VEVENT\nUID:uid1@example.com\nDTSTAMP:19970714T170000Z\nORGANIZER;CN=John Doe:MAILTO:john.doe@example.com\nDTSTART:19970714T170000Z\nDTEND:19970715T035959Z\nSUMMARY:Bastille Day Party\nEND:VEVENT\nEND:VCALENDAR	0
20378060	20376783	Protobuf-net fails to deserialize Guid	[Datacontract(Namespace = "http://lorem")]\npublic class MyCustomData {\n\n  [DataMember(Order = 0)]\n  public int Dummy { get; set; } // had to define, otherwise I get invalid wire-type exception\n\n  [DataMember(Order = 1)]\n  public Guid Id { get; set; } // now ok\n\n  [DataMember(Order = 2)]\n  public int MyInt { get; set; } // serializes/deserializes ok\n}	0
6931663	6931501	Casting different objects from TcpClient serialized object stream?	object deserializedObject = Deserialize(....);\nif (deserializedObject is string)\n    ProcessString ((string)deserializedObject);\nelse if (deserializedObject is byte[])\n    ProcessBytes ((byte[])deserializedObject);\nelse if (deserializedObject is Uri)\n    ProcessUri ((Uri)deserializedObject);\nelse\n    throwOrLog (deserializedObject);	0
10437891	10437772	Linq: Select all items group by name with count equal 0	from c in orders  \ngroup c by c.name into g\n  select new {\n    Name = g.Key,\n    Price = g.Where(c => (int)c.date.DayOfWeek == this._monday).Sum(c => c.Price)\n  }	0
9063063	9062147	add querystring value on javascript	/*\n* <summary>\n* Get the querystring value\n* </summary>\n* <param name="key">A string contains the querystring key</param>\n* <param name="defaultVal">Object which get returns when there is not key</param>\n*\n*/\n\nfunction getQuerystring(key, defaultVal) {\n    if (defaultVal == null) {\n        defaultVal = "";\n    }\n    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");\n    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");\n    var qs = regex.exec(window.location.href);\n    if (qs == null) {\n        return defaultVal;\n    }\n    else {\n        return qs[1];\n    }\n}	0
30242580	30242367	Generating 4 Unique Numbers in a string	namespace ClassLibrary1\n{\n    public class Class1\n    {\n        public void Generate()\n        {\n            string remainingDigits = "0123456789";\n            System.Random r = new System.Random();\n            string output = null;\n            int count = 10;\n            int index = r.Next(count);\n            output += remainingDigits[index];\n            remainingDigits = remainingDigits.Remove(index, 1);\n            count -= 1;\n            index = r.Next(count);\n            output += remainingDigits[index];\n            remainingDigits = remainingDigits.Remove(index, 1);\n            count -= 1;\n            index = r.Next(count);\n            output += remainingDigits[index];\n            remainingDigits = remainingDigits.Remove(index, 1);\n            count -= 1;\n            index = r.Next(count);\n            output += remainingDigits[index];\n        }\n    }\n}	0
14283719	14283600	Resharper 7: Sort Method by name, within a #Region	ReSharper-->Tools-->Cleanup Code-->Reorder type members	0
5919191	5827208	Move a borderless Winform holding right mouse button, possibly with native methods	public partial class DragForm : Form\n{\n    // Offset from upper left of form where mouse grabbed\n    private Size? _mouseGrabOffset;\n\n    public DragForm()\n    {\n        InitializeComponent();\n    }\n\n    protected override void OnMouseDown(MouseEventArgs e)\n    {\n        if( e.Button == System.Windows.Forms.MouseButtons.Right )\n            _mouseGrabOffset = new Size(e.Location);\n\n        base.OnMouseDown(e);\n    }\n\n    protected override void OnMouseUp(MouseEventArgs e)\n    {\n        _mouseGrabOffset = null;\n\n        base.OnMouseUp(e);\n    }\n\n    protected override void OnMouseMove(MouseEventArgs e)\n    {\n        if (_mouseGrabOffset.HasValue)\n        {\n            this.Location = Cursor.Position - _mouseGrabOffset.Value;\n        }\n\n        base.OnMouseMove(e);\n    }\n}	0
6594820	6593812	initializing a 48bpp bitmap from a file in c#	Bitmap img1 = new Bitmap(100, 100, PixelFormat.Format48bppRgb);\n        img1.Save("c:/temp/img1.bmp", ImageFormat.Bmp);	0
3412254	3405298	How to refresh record after an update with a SP	dt.RowChanged += new DataRowChangeEventHandler(_update_fields);\n\n\n    private void _update_fields(object sender, DataRowChangeEventArgs e)\n    {\n        try\n        {\n            if (e.Action == DataRowAction.Add)\n            {\n                conn.Open();\n                cmd = conn.CreateCommand();\n                cmd.CommandText = "SELECT IDENT_CURRENT('" + e.Row.Table.TableName + "')";\n                dt.Rows[dt.Rows.Count - 1][0] = int.Parse(cmd.ExecuteScalar().ToString()) + 1;\n                dt.AcceptChanges();\n                conn.Close();\n            }\n            adapt.Update(dt);\n        }\n        catch (SqlException ex)\n        {\n            Debug.WriteLine(ex.Message);\n        }\n        catch (Exception ex)\n        {\n            Debug.WriteLine(ex.Message);\n        }\n    }	0
25579092	25579083	Where to define connection string as global in C# windows app(Like WebConfig in Web App)?	app.config	0
1771264	1771168	Set values with a Linq-Query?	int rankPosition = 1;\nvar sortedListKFZ = listKFZ.OrderBy(r => r.Price).Select(r => {\n    r.MesaAdvertNumber = ++rankPosition;\n    return r;\n});	0
639488	639471	Use XML serialization to serialize a collection without the parent node	[XmlElement("Passenger")]\npublic List<Passenger> Passengers {get; set;}	0
32581582	32581375	Save C# winform controls created in run time	[Serializable]\nclass ControlFactory\n{\n    enum ControlType\n    {\n        TextBox\n    }\n    ControlType Type {get;set;}\n    Point Position {get;set;}\n    //etc.\n    Control Create()\n    {\n        switch(Type)\n        {\n            case ControlType.TextBox:\n                TextBox txt = new Textbox();\n                // apply settings\n                return txt;\n        }\n    }\n}	0
587017	586972	How to get multidimensional length - of one axis	SSISVariableNameValue.GetLength(0);	0
9461753	9454979	How to monitor a window's position with Win32?	var hook = SetWinEventHook(EVENT_SYSTEM_MOVESIZESTART,    \n    EVENT_SYSTEM_MOVESIZEEND, NULL, WinEventProc, \n    0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);	0
29464779	29464515	Getting wrong results from json document in MongoDB c#	String regex = String.Format("({0})", String.Join("|", TextBox2.Text));\nvar query     = Query.Matches("clinical_study.location.facility.address.city", regex);\nvar query2 = collection.Find(query);	0
25063813	25063755	How can I use regex pattern to replace this following string	(?<=\{[^}]*)\sor\s(?=[^{]*\})	0
21086368	21086306	LINQ EF copy and paste a record with a difference field	using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())\n{\n    var qlstfld = from lstflds in cwContext.tblListFields\n                              where lstflds.listId == theLongSrc\n                              select lstflds;\n\n    foreach (var item in qlstfld)\n    {\n        cwContext.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Added);\n        item.Id = 0;\n        item.listId = theLongDes; //this field must be change in paste\n    }\n    cwContext.SaveChanges();\n}	0
23134316	23134262	How to get value of element with XDocument and Linq to XML	XNamespace ns = "http://Mynamespace";\n\nthis.RequestId = (string)doc.Descendants(ns + "RequestID").FirstOrDefault();	0
19789161	19750681	How to close previous mdi child in parent form	if (ActiveMdiChild != null)\n    ActiveMdiChild.Close();	0
17023894	17013898	detect cd/dvd in cd drive and play on window media player	char szDrives[MAX_PATH];      \nlong TotalNumberOfFreeBytes  = 0;\nlong FreeBytesAvailable = 0;\n\n// Get all the drives on your system. Divide by 4 as strlen("C:\") ==  4\nint noOfDrives =(GetLogicalDriveStrings(MAX_PATH,szDrives)/4);\n\nfor(int i=0;i<noOfDrives ;i++)\n{\n   // find CD ROM drives\n   if (DRIVE_CDROM == GetDriveType(&drivestr[i*4]))\n   {  \n          if(!GetDiskFreeSpaceEx(&drivestr[i*4],\n               &FreeBytesAvailable,\n               NULL,\n               &TotalNumberOfFreeBytes  ))\n          {\n             // Disk in drive, enumerate files \n             // using FindFirstFile/FindNextFile\n             // and play video if any\n          }\n   }\n}	0
13994643	13994572	How do I stop a date/time comparison from failing when a user is in a different time zone?	DateTime ToUniversalTime()	0
28778824	28777042	How can I update the GUI with live results from a for loop?	for (int i = 0; i < 100000; i++)\n{\n    labelToShow.Text = i.ToString(); // live update of information on the GUI\n    labelToShow.Invalidate();\n    Application.DoEvents();\n\n    double s1 = rnd.NextDouble();\n    double s2 = rnd.NextDouble();\n    w = Math.Sqrt(-2 * Math.Log(s1)) * Math.Cos(2 * Math.PI * s2);\n}	0
16754624	16675528	Office 2007 PIA - Embed non-text files	public void InsertFile(Microsoft.Office.Interop.Word.Selection CurrentSelection, string FileName)\n{\nobject FileName = fileName;\nobject missing = Type.Missing;\nCurrentSelection.InlineShapes.AddOLEObject(ref missing, ref FileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);\n}	0
2480454	2480436	continue to <label> in C# like in java	goto <label>;	0
17317979	17317227	Reading JSON using JSON.NET	{\n"adjusted_amount":200,\n"amount":2,\n"uid":"admin",\n"extra_params": {"uid":"admin","ip":"83.26.141.183","user_agent":"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.52 Safari/537.36"}\n}\n\npublic class RecData1\n{\n    public string uid { get; set; }\n    public int amount { get; set; }\n    public int adjusted_amount { get; set; }\n    //public string extra_params { get; set; }\n}	0
34422379	34421719	WPF datagrid automatic sorting by chosen column	datagrid.Items.SortDescriptions.Add(new SortDescription("DueDate", ListSortDirection.Ascending));	0
16528930	16528318	Dropped data when loading CSV into DataGridView in C# WinForms	String myFilePath = @"c:\test.csv";\nDataTable dt = new DataTable();\ndt.Columns.Add("HAB_CODE");\ndt.Columns.Add("SIZE");\ndt.Columns.Add("COVER");\n\nusing (var myCsvFile = new TextFieldParser(myFilePath)){\n    myCsvFile.TextFieldType = FieldType.Delimited;\n    myCsvFile.SetDelimiters(",");\n    myCsvFile.CommentTokens = new[] { "HEADER", "COMMENT", "TRAILER" };\n\n    while (!myCsvFile.EndOfData) {\n        string[] fieldArray;\n        try {\n            fieldArray = myCsvFile.ReadFields();\n            dt.Rows.Add(fieldArray);\n        }\n        catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {\n            // not a valid delimited line - log, terminate, or ignore\n            continue;\n        }\n    // process values in fieldArray\n    }    \n}	0
21676016	21673520	Can we assign a particular dataset column value to a variable	String str = DataSet.Tables[0].Rows[RowIndex]["ColumnNameOrIndex"].ToString();\nString str = DataSet.Tables["TableName"].Rows[0]["ColumnName"].ToString();	0
11456713	3137207	Is there a better way to get the page count from a PrintDocument than this?	public static int GetPageCount(PrintDocument printDocument)\n{\n    int count = 0;\n    printDocument.PrintController = new PreviewPrintController();\n    printDocument.PrintPage += (sender, e) => count++;\n    printDocument.Print();\n    return count;\n}	0
14583872	14583770	Model changes updating View-Model WPF	private void UpdateLabelValue()\n{\n  Name = "Value Updated";\n}	0
18634643	18634458	Universal data fetcher from similar entities	public IList<T> GetReferenceWithPredefinedItem<T>(DbSet<T> dbset) where T:IReference\n{\n    var data = from a in dbset\n               orderby a.Title\n               select a;\n\n    var list = data.ToList();\n    list.Insert(0, new PredefinedReferenceItem());\n\n    return list;\n}	0
10765991	10765940	Without using a html parser is there a way, using an ordinary string method to get the part of a string between two specified strings, in my case tags	var description = Regex.Match(s, @"<description>(.*)</description>").Groups[1];	0
3721778	3721731	i get date in wrong format - need help	DateTime MyDate = DateTime.ParseExact("7/16/2010", "M/dd/yyyy", CultureInfo.InvariantCulture);	0
31130801	31130244	How to allow only specific alphabets in a Textbox?	private void myTextBox_KeyDown(object sender, KeyEventArgs e)\n{\n         if (myTextBox.Text.Length == 2)\n          { \n                 if (myTextBox.Text.StartsWith("LP"))\n                 {\n                    //yourcode\n                 }\n                 else\n                 {\n                         myTextBox.Text = string.Empty;\n                 }\n           }\n}	0
22502209	22502056	How to make required field validator on dropdownlist?	ServiceChannelDropDownList.DataBind();\nServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));	0
28980362	28980233	Button that dynamically inserts checkbox to a checkboxlist in wpf	List.Add(new BoolStringClass { Selected = true, Texto = "NEW ENTRY" });	0
23167562	23166974	C# packet sent to c++ winsockets	string myString = "abc";\n        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(myString);\n\n\n        using (MemoryStream ms = new MemoryStream())\n        {\n\n            ms.Write(BitConverter.GetBytes(buffer.Length), 0, 4);\n            ms.Write(buffer, 0, buffer.Length);\n\n            //... rest of code...\n        }	0
15567021	15566935	Custom attributes in WPF user control	public class UC_TitleBar : UserControl\n{\n    public static readonly DependencyProperty ShowCloseButtonProperty = DependencyProperty.Register("ShowCloseButton", \n                                                    typeof(Boolean), typeof(UC_TitleBar), new FrameworkPropertyMetadata(false));\n    public bool ShowCloseButton\n    {\n        get { return (bool)GetValue(ShowCloseButtonProperty); }\n        set { SetValue(ShowCloseButtonProperty, value); }\n    }\n}	0
25368890	25368773	Filter by date using lambda expression	var dt = DateTime.Today.AddDays(-10);	0
12278583	12261461	Can't get the telerik radgridview to highlight the SelectedItem when binding to viewmodel with a selecteditem already set	private void CaseGridView_DataLoaded(object sender, EventArgs e)\n    {\n        var grid = sender as RadGridView;\n        if (grid != null)\n        {\n            grid.SelectedItem = vm.CurrentlySelectedItem;\n            if (grid.SelectedItem != null)\n            {\n                grid.ScrollIntoView(grid.SelectedItem);\n            }\n        }\n    }	0
18641619	18386358	Take main text from E-Mail, put in string. Where do I even start?	using (var client = new ImapClient("imap.gmail.com", 993,\n         "username", "password", AuthMethod.Login, true))\n        {\n            var uids = client.Search(SearchCondition.Unseen());\n            if (uids.Length >= 1)\n            {\n                var message = client.GetMessage(uids[0], false, "inbox");\n                return new MessageInfo {EnclosedText = message.Body, Sender = message.From.ToString()};\n            }\n            return new MessageInfo();\n\n        }	0
2164841	2164799	how to display files inside directory	string[] filePaths = Directory.GetFiles(@"c:\dir");\nfor (int i = 0; i < filePaths.Length; ++i) {\n    string path = filePaths[i];\n    Console.WriteLine(System.IO.Path.GetFileName(path));\n}	0
32438281	32433282	C# Ajax can't get data from controller response	return this.Content(xmlString, "text/xml");	0
25179822	25061884	How can I search a collection of several list<T> with queries?	MongoCursor elements = collection.Find(Query.ElemMatch("list",MyQueryInput));	0
9816776	9814463	mouse movements in wpf	protected override void OnMouseDown(MouseButtonEventArgs e)\n{\n    base.OnMouseDown(e);\n}\nprotected override void OnPreviewMouseDown(MouseButtonEventArgs e)\n{\n    base.OnPreviewMouseDown(e);\n}	0
20176584	20176465	C# WinForms: Make CheckBox look like a RadioButton	private void radioButtons_Click(object sender, EventArgs e) {\n        var button = (RadioButton)sender;\n        button.Checked = !button.Checked;\n    }	0
7134914	7134893	insert multiple ids from a department	Insert into jos_users_quizzes(quiz_id, user_id) select (your_quiz_id, user_id) from   jos_users where department='selectd_depatment'	0
33608359	33608302	Dictionary of list of dictionary c#	Dictionary <string, List<Dictionary<string,string>>> field;	0
9536905	9536851	a parameterless ctor exist but unity goes to another one while resolving	this.container.RegisterType<IConsumerTokenManager, InMemoryTokenManager>(new InjectionConstructor());	0
5970072	5970055	Converting LINQ statement from query to fluent c# syntax	var props = target\n    .GetType()\n    .GetProperties()\n    .Select(p => new { \n        Name = p.Name, \n        Value = p.GetValue(target, null)\n});	0
870353	869266	How to catch (and hopefully fix) a GDI resource leak	GetGuiResources()	0
24344554	24344423	Reading Binary/Byte from SQL on C# ASP	var result = (Byte[])dr["presentationDocBigData"];	0
1127790	1127773	Is there any way to determine text direction from CultureInfo in asp.net?	System.Globalization.CultureInfo.CurrentCulture.TextInfo.IsRightToLeft	0
9024432	9023835	Is there a way to get all the entities inside SaveChanges method in Entity Framework	ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged | EntityState.Deleted)	0
8148673	8148636	XML Syntax when Using Colon (:), in Tags	XNamespace dc = "http://purl.org/dc/elements/1.1/";\n\n\nvar query = from lst in XElement.Load(@"foo.xml").Elements(dc +"creator")\n\n            select ...	0
14148023	14147971	.NET WebBrowser Control in WindowForms	System.Net.ServicePointManager.ServerCertificateValidationCallback = \n  (sender, certificate, chain, errors) => true;	0
8665893	8665176	How to get cell value from a gridview?	int lastrow = grdPrevious.Rows.Count - 1;\nLabel lb = (Label)grdPrevious.Rows[lastrow].FindControl("Label5");\nResponse.Write(lb.Text);	0
30868570	30849033	ASP.NET EF6 - 2 Tables & 1 Link Table	[HttpPost]\n    [ValidateAntiForgeryToken]\n    public ActionResult Create(EmployeeContactViewModel employeecontactviewmodel)\n    {\n        if (ModelState.IsValid)\n        {\n            var employee = new EmployeeModel {\n                FirstName = employeecontactviewmodel.FirstName,\n                LastName = employeecontactviewmodel.LastName\n            };\n\n            var contact = new ContactInfoModel {\n                Data = employeecontactviewmodel.ContactInfo\n            };\n\n\n            db.Employee.Add(employee);\n            db.Contact.Add(contact);\n            db.SaveChanges();\n\n            var contactLink = new ContactLinkModel {\n                ContactID = employee.ID,\n                ContactInfoID = contact.ID\n            };\n\n            db.ContactInfo.Add(contactLink);\n            db.SaveChanges();\n\n            return RedirectToAction("Index");\n        }\n\n        return View(employeecontactviewmodel);\n    }	0
16767627	16767481	XDocument changes tab to space	var path = @"C:\test.xml";\nXmlDocument doc = new XmlDocument();\nXmlTextReader reader = new XmlTextReader(path);\ndoc.Load(reader);\nvar s = doc.SelectSingleNode("*/@*").InnerText;\nConsole.WriteLine("|{0}|, {1}", (int)s[0], s.Length); // prints 9 - ASCII code of tab\ndoc.Save(path);	0
7725035	7724983	Printing the first 30 ASCII characters in c# results in a box	control characters	0
2597342	2596419	How to get a list of all domains?	using (var forest = Forest.GetCurrentForest())\n{\n    foreach (Domain domain in forest.Domains)\n    {\n        Debug.WriteLine(domain.Name);\n        domain.Dispose();\n    }\n}	0
14155618	14155548	Upload checking in DB	try\n{\n    // Code to process upload\n    Response.Redirect("/success.aspx");\n}\ncatch (Exception)\n{\n    Response.Redirect("/failure.aspx");\n}	0
11961305	11959353	Alter Servlet parameters of a request using a Proxy Page	public void ProcessRequest(HttpContext context)\n{   \n    HttpResponse response = context.Response;\n\n    // Get the URL requested by the client (take the entire querystring at once\n    //  to handle the case of the URL itself containing querystring parameters)\n    string uri = Uri.UnescapeDataString(context.Request.QueryString.ToString());\n\n\n    // Get token, if applicable, and append to the request\n    string token = getTokenFromConfigFile(uri);\n\n\n    // Add the 'TIMESTAMP' Value  to the Valtus Service\n    string styleparam = "&STYLES=";\n    if (uri.Contains(styleparam))\n    {\n        int position = uri.IndexOf(styleparam) + styleparam.Length;\n        uri = uri.Insert(position, "TIMESTAMP");\n    }\n\n    System.Net.WebRequest req = System.Net.WebRequest.Create(new Uri(uri));	0
15957444	15907402	Page 404'ing when running a SQL statement then redirecting	Response.Redirect("http://website.com", false);	0
25272101	25271834	Gyroscope and accelerometer data from Windows?	using Windows.Devices.Sensors;\n\nprivate Accelerometer _accelerometer;\n\nprivate static void DoStuffWithAccel()\n{\n   _accelerometer = Accelerometer.GetDefault();\n   if (_accelerometer != null)\n   {\n      AccelerometerReading reading = _accelerometer.GetCurrentReading();\n      if (reading != null)\n      double xreading = reading.AccelerationX;\n      ... etc.\n   }\n}	0
23426484	23426399	How to search the same object with different Equal concepts?	Dictionary(IEqualityComparer<TKey> comparer)	0
13160560	13144756	Control Excel Within WebBrowser Control	Dim MyRange As Microsoft.Office.Interop.Excel.Range\n\n... code ...\n\nMyRange.CopyPicture(Microsoft.Office.Interop.Excel.XlPictureAppearance.xlScreen,Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap)\n\nIf Clipboard.GetDataObject IsNot Nothing Then\n   Dim Data As IDataObject = Clipboard.GetDataObject\n\n   If Data.GetDataPresent(DataFormats.Bitmap) Then\n       Dim img As Image = Data.GetData(DataFormats.Bitmap, True)\n\n       PictureBox1.Height = img.Height\n       PictureBox1.Width = img.Width\n       PictureBox1.Image = img\n   End If\nEnd If	0
10338075	10338018	How to get a property value using reflection	var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);	0
32292446	32292416	Syntax error missing operator need help in between date	cmd = new OleDbCommand("Select COUNT(*) from AttendanceDatabase  WHERE EmpName =@EmpName and Status =@Status and Date between @d1 and @d2", con)	0
34232866	34232808	C# Override Compare method of IComparer Interface	v2v1.CompareTo(v1v2)	0
29395636	29372049	Get all members of list	public List<string> GetListMembers(string membersList, string status, string since = "")\n    {\n        List<string> li = new List<string>();\n        //to see what does <dc> means? follow this link https://apidocs.mailchimp.com/api/rtfm/\n        string linkPage = @"http://<dc>.api.mailchimp.com/export/1.0/list/?apikey={0}&id={1}&status={2}{3}";\n        ListInfo list = mc.GetLists().Data.Where(x => x.Name == membersList).FirstOrDefault();\n        linkPage = string.Format(linkPage, conectionMailChimp, list.Id, status, !string.IsNullOrEmpty(since) ? "&since=" + since : string.Empty);\n\n        WebClient wc = new WebClient();\n        string text = wc.DownloadString(linkPage);\n        text = text.Replace("\"", "");\n        string[] res = text.Split(new[] { "]\n[" }, StringSplitOptions.None);\n\n        for (int i = 1; i < res.Length; i++)\n            li.Add(res[i].Split(new[] { "," }, StringSplitOptions.None)[0].ToString());\n\n        return li;\n    }	0
4100637	4100573	Kill session on popup close until the closing of browser	bc_notice=1	0
25584912	25584890	Set StaticResource style of a control in code behind	TextBlock myTextBlock= new TextBlock ()\n    {\n        FontFamily = new FontFamily("Segoe UI Light");\n        Style = Resources["TextBlockStyle"] as Style,\n    };	0
24970355	24970315	c# mysql - there is already an open datareader associated with this connection which must be closed first	dr.Close();\n                    conn.Close(); \n\n    }\n    catch (Exception n)\n    {\n        Console.Write(n.Message);\n        MessageBox.Show(n.Message);\n    }	0
17237530	17215026	how to close all background threads of a Windows Service application ?	myThread.isBackground = true	0
5279507	5279448	Objects need to be disposed in a specific order: is this a code smell?	foreach (panel in Panels.Where(p => p != theSpecialPanel))\n{\n   panel.Dispose();\n}\ntheSpecialPanel.Dispose();	0
25155737	25155644	How to send Push Notification to some specific users using Pushwoosh Web API in C#?	string[] arr = new string[1];\n arr[0] = "9d48ac049ca6f294ea25ae25f3472b0e7e160ba06729397f9985785477560b3a";\n\n JObject json = new JObject(\n           new JProperty("application", pwApplication),\n           new JProperty("auth", pwAuth),\n           new JProperty("notifications",\n               new JArray(\n                   new JObject(\n                       new JProperty("send_date", "now"),\n                       new JProperty("content", new JObject(new JProperty("en", pushContentEnglish), new JProperty("es", pushContentSpanish))),               \n                       new JProperty("data", new JObject(new JProperty("custom", new JObject(new JProperty("t", notificationType), new JProperty("i", objectId))))),\n                       new JProperty("devices", new JArray(arr))\n                       ))));	0
28089749	28086701	WPF C#: How to add a usercontrol to a thumb control programatically?	Thumb tmbDragThumb = new Thumb();\ntmbDragThumb.DragDelta += new DragDeltaEventHandler(Thumb_DragDelta);\nControlTemplate template = new ControlTemplate();\nvar fec= new FrameworkElementFactory(typeof(UserControl1 ));\ntemplate.VisualTree = fec;\ntmbDragThumb.Template = template;\n\nSweetCanvas.Children.Add(tmbDragThumb);	0
20706000	19865621	Unauthorizedaccessexception: how to wait on input from user. Windows Phone c#	private void PlayGuessGame()\n    {\n        bool hasWon = false;\n        int secretNumber = r.Next(1, 3);\n        int tries = 1;\n\n        messageTextBox.Text = "Guess a number";\n\n        while (!hasWon)\n        {\n            autoEvent.WaitOne();\n            if (guess == secretNumber) //if user wins\n            {\n                this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Congratulations! You've guess the correct number! It took {0} tries."; }));\n\n            }\n            else\n            {\n                tries++;\n                if (guess < secretNumber)\n                    this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Guess higher!"; }));\n                else\n                    this.Invoke(new MethodInvoker(delegate { messageTextBox.Text = "Guess lower!"; }));\n\n                this.Invoke(new MethodInvoker(delegate { lastGuessTextBox.Text = guess.ToString(); }));\n            }\n\n        }\n    }	0
30968908	30968854	Validation of asp.net identity password	var password = "password_to_test";\n\n if (password.Any("!@#$%^&*".Contains)\n  && password.Any(char.IsDigit)\n  && password.Any(char.IsLower)\n  && password.Any(char.IsUpper))\n  {\n      //valid!\n  }	0
27425832	27425466	SQL server creating a view with a guid and select distinct clause	create table Something\n(\n    SomeVal varchar(10)\n)\ninsert Something\nselect 'asdf' union all \nselect 'asdf' union all \nselect 'qwer' union all \nselect 'qwer'\n\ngo\n\ncreate view MyView as\n    select SomeVal, ROW_NUMBER() over (order by SomeVal) as RowNum\n    from Something\n    group by SomeVal\n\ngo\n\nselect *\nfrom MyView\n\ngo\n\ndrop view MyView\ndrop table Something	0
541444	541415	How to return first object of a collection from its parent	Page firstPage = Session.Linq<Page>()\n.OrderBy(page => page.Index)\n.FirstOrDefault(page=> page.Location.URL == "some-location-url");	0
3065463	3065163	Prompt with UAC when user doesn't have access to copy a file	Process p = new Process();\np.StartInfo.FileName = "copy.exe";\np.StartInfo.Arguments = new [] { pathFrom, pathTo };\np.Verb = "runas";\np.Start();	0
9385694	9385610	How to parse double in scientific format using C#	string s = " 0.12961924D+01";\ns = s.Trim().Replace("D", "E");\n//s should now look like "0.12961924E01"    \ndouble v2 = Double.Parse(s, NumberStyles.Float);	0
4636858	4636818	How do I nest multiple ViewModels in a top level ViewModel, in a sort of hierarchy that can be dispersed throughout my Views?	public SubViewModel SubAVM { \n   get { \n      return subAVM;\n   }\n   set{\n   if (subAVM == value)\n   {\n      return;\n   }\n   subAVM = value; //implement the OnPropertyChanged ...\n   }\n}	0
6501997	6501797	Resize image proportionally with MaxHeight and MaxWidth constraints	public static void Test()\n{\n    using (var image = Image.FromFile(@"c:\logo.png"))\n    using (var newImage = ScaleImage(image, 300, 400))\n    {\n        newImage.Save(@"c:\test.png", ImageFormat.Png);\n    }\n}\n\npublic static Image ScaleImage(Image image, int maxWidth, int maxHeight)\n{\n    var ratioX = (double)maxWidth / image.Width;\n    var ratioY = (double)maxHeight / image.Height;\n    var ratio = Math.Min(ratioX, ratioY);\n\n    var newWidth = (int)(image.Width * ratio);\n    var newHeight = (int)(image.Height * ratio);\n\n    var newImage = new Bitmap(newWidth, newHeight);\n\n    using (var graphics = Graphics.FromImage(newImage))\n        graphics.DrawImage(image, 0, 0, newWidth, newHeight);\n\n    return newImage;\n}	0
4476278	4474972	Comparing Oracle Table with SQL Server table	INSERT INTO [SQLServer].[dbo].[table]\nSELECT columns\n  FROM [Oracle].[database].[schema].[table] x\n WHERE NOT EXISTS(SELECT NULL\n                    FROM [SQLServer].[dbo].[table] y\n                   WHERE y.student_number = x.student_number)	0
9816559	9816337	Algorithm to extract 2 levels down	string Str = "&|L1|L2|L3|&";\n            for(int i= 0;i<Str.Length;i++)\n            {\n                if (Str[i] == 'L' && Str[i+1] == '1')\n                {\n                    MessageBox.Show(Str[i].ToString() + Str[i+1].ToString() + " Found");\n                }\n            }	0
9500943	9500728	Extract text from pdf to c#	public static string GetPDFText(String pdfPath)\n{\n    PdfReader reader = new PdfReader(pdfPath); \n\n    StringWriter output = new StringWriter();  \n\n    for (int i = 1; i <= reader.NumberOfPages; i++) \n        output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));\n\n    return output.ToString();\n}	0
20666369	20628995	Trying to get twitter profile information in c#	var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +\n                               "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " +\n                               "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " +\n                               "oauth_version=\"{6}\"";\n\n            var authHeader = string.Format(headerFormat,\n                Uri.EscapeDataString(oauth_nonce),\n                Uri.EscapeDataString(oauth_signature_method),\n                Uri.EscapeDataString(oauth_timestamp),\n                Uri.EscapeDataString(oauth_consumer_key),\n                Uri.EscapeDataString(oauth_token),\n                Uri.EscapeDataString(oauth_signature),\n                Uri.EscapeDataString(oauth_version)\n            );	0
21600354	21600243	Design pattern: singleton with setting capabilities	using System.Collections.Generic;\nusing System.Collections.Concurrent;\n\nnamespace MyApplication \n{\n    class FooMultiton \n    {\n        private static readonly ConcurrentDictionary<object, FooMultiton> _instances\n        = new ConcurrentDictionary<object, FooMultiton>();\n\n        private FooMultiton() {}\n\n        public static FooMultiton GetInstance(object key) \n        {\n            _instances.TryAdd(key, new FooMultiton()); // This would of course be new MyLogger(_dbName)\n            return _instances[key];\n        }\n    }\n}	0
21405101	21404734	How to add and get Headervalues in webapi c#	var re = Request;\n    var headers = re.Headers;\n\n    if (headers.Contains("Custom"))\n    {\n        string token = headers.GetValues("Custom").First();\n    }\n\n    return null;	0
11988714	11986840	WPF TreeView refreshing	private void RefreshViews()\n{\n    XmlEditor.Clear();\n    XmlEditor.Text = IndentXml();\n\n    UnselectSelectedItem();\n\n    XmlTree.Items.Refresh();\n    XmlTree.UpdateLayout();\n}\n\nprivate void UnselectSelectedItem()\n{\n    if (XmlTree.SelectedItem != null)\n    {\n        var container = FindTreeViewSelectedItemContainer(XmlTree, XmlTree.SelectedItem);\n        if (container != null)\n        {\n            container.IsSelected = false;\n        }\n    }\n}\n\nprivate static TreeViewItem FindTreeViewSelectedItemContainer(ItemsControl root, object selection)\n{\n    var item = root.ItemContainerGenerator.ContainerFromItem(selection) as TreeViewItem;\n    if (item == null)\n    {\n        foreach (var subItem in root.Items)\n        {\n            item = FindTreeViewSelectedItemContainer((TreeViewItem)root.ItemContainerGenerator.ContainerFromItem(subItem), selection);\n            if (item != null)\n            {\n                break;\n            }\n        }\n    }\n\n    return item;\n}	0
21699560	21699504	Revert string.Format	public bool IsPatternCandidate(\n  string formatPattern, \n  string formattedString, \n  IList<string> arguments)\n{\n  //Argument checks\n\n  Regex regex = new Regex("{\\d+}");      \n  string regexPattern = string.Format("^{0}$", regex.Replace(formatPattern, "(.*)"));\n  regex = new Regex(regexPattern);\n\n  if (regex.IsMatch(formattedString))\n  {\n    MatchCollection matches = regex.Matches(formattedString);\n    Match match = matches[0];\n    for (int i = 1; i < match.Groups.Count; i++)\n    {\n      arguments.Add(match.Groups[i].Value);\n    }\n\n    return true;\n  }\n\n  return false;\n}	0
22519195	22517817	Get size of SqlDataReader payload	DECLARE @maxRowSize int\nSET @maxRowSize =\n(\nSELECT SUM(DataSize) AS MaxRowSize\nFROM\n(\nSELECT COLUMN_NAME, DATALENGTH(COLUMN_NAME) as DataSize\nfrom information_schema.columns \nwhere table_name = 'shop' -- enter table name only, do NOT enter the schema\n) AS SCHEM\n)\nSELECT COUNT(Id) as NumOfRows, --optional\n@maxRowSize as MaxRowBytes, --optional\nCOUNT(id) * @maxRowSize as MaxQueryBytes\nFROM Shop -- Enter schema name if needed	0
16815457	16815233	Parsing to JSON in C#	new { ... }	0
2899671	2899566	How to remove words based on a word count	if (wordColl.Count > 70)\n{\n    foreach (var subWord in wordColl.Cast<Match>().Select(r => r.Value).Take(70))\n    {\n        //Build string here out of subWord\n    }\n}	0
5758130	5758089	Accessing a master page public variable from user control	HtmlForm mainform = (HtmlForm)Master.FindControl("form1");	0
15748079	15747800	Custom numeric format string based on number sign	public string Format(decimal value)\n{\n   string s = (value*100).ToString("0.0;0.0");\n   if(value < 0)\n      s = "(" + s + ")";\n    return s;\n}	0
27863356	27302438	PRISM MEF Creating and using a new RegionManager	RegionManager.Regions["region"].Add(ServiceLocator.Current.GetInstance<view>());	0
651714	651682	Byte array as an out parameter not recognized	public bool DownloadFile(string URI, out byte[] docContents, out string returnFiletype)	0
7909147	7908972	How to write a HTTP Request	public static void decryptContainer(string dlc_content) \n   {\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/paste");\n        request.Method = "POST";\n        request.ContentType = "application/x-www-form-urlencoded";\n        request.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";\n\n        byte[] _byteVersion = Encoding.ASCII.GetBytes(string.Concat("content=", dlc_content));\n\n        request.ContentLength = _byteVersion.Length\n\n        Stream stream = request.GetRequestStream();\n        stream.Write(_byteVersion, 0, _byteVersion.Length);\n        stream.Close();\n\n        HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n        using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n        {\n            Console.WriteLine(reader.ReadToEnd());\n        }\n    }	0
5161135	5159893	Binding with CollectionViewSource	IsSynchronizedWithCurrentItem = false	0
19546051	19545315	Printing out Hashtable without using a loop in c#	Hashtable mhash = new Hashtable();\n\nvar sb = new StringBuilder();\n\nforeach (var myhash in mhash)\n{\n    sb.AppendLine(myhash.ToString()); -- Note you format your hash however you want here\n}\n\nLogging.traceMessage(DateTime.Now, sb.ToString());	0
7936688	7936678	C# string to list	var toEmailAddresses = new List<string> { "someone@gmail.com" }	0
75178	75123	Remove columns from DataTable in C#	DataTable t;\n       t.Columns.Remove("columnName");\n       t.Columns.RemoveAt(columnIndex);	0
23066814	23055563	Can I read XML Attributes dynamically in WPF C#	var xml = XElement.Parse(@"your xml");\nforeach (var attr in xml.Attributes())\n{\n\n}	0
7655038	7655019	How set property name/value dynamically?	//Once:\nMapper.CreateMap<FromType, ToType>();\n\n//Then:\nMapper.Map(viewModel.Tests, _parentObject.Tests);	0
1378622	1378378	How to determine which fields where changed in a Linq-To-Sql Object	DataClasses1DataContext context;\nClass1 instance = context.GetChangeSet().Updates.OfType<Class1>().First();\ncontext.Class1s.GetModifiedMembers(instance);	0
19355209	19194912	Google map Api Share location issue in Firefox	navigator.geolocation.getCurrentPosition	0
5310542	5310486	How to use the real parameters when creating a stub method in RhinoMocks?	unitOfWorkStub.Stub(x => x.DoInTransaction(Arg<Action>.Is.Anything))\n              .WhenCalled(x => ((Action)x.Arguments[0])());	0
9007070	9006986	Use mysql in a C# Windows Application within Visual Studio 2010	using MySql.Data.MySqlClient;\n\nstring dbConnectionString = "SERVER=server_address;DATABASE=db_name;UID=user;PASSWORD=pass;";\nMySqlConnection connection = new MySqlConnection(dbConnectionString);\nconnection.Open();\nMySqlCommand command = connection.CreateCommand();\ncommand.CommandText = "select name from mytable";\nMySqlDataReader Reader = command.ExecuteReader();    \nwhile (Reader.Read())\n{\n     string name = "";\n     if (!Reader.IsDBNull(0))\n         name = (string)Reader["name"];\n}\nReader.Close();	0
18355742	18355653	How Can I open the Text file in my MVC application?	public ActionResult Log()\n{\n    var fileContents = System.IO.File.ReadAllText(Server.MapPath("~/Views/Builder/TestLogger.txt"));\n    return Content(fileContents);\n}	0
7602475	7602419	Dynamic Increase / Decrease the number with C#	void IncreaseBtn_Click(Object sender, EventArgs e)\n{\n    var value = this.myLabel.Text;\n    var intValue = 0;\n    Int32.TryParse(value, out intValue);\n    this.myLabel.Text = (++intValue).ToString();\n}\n\nvoid DecreaseBtn_Click(Object sender, EventArgs e)\n{\n    var value = this.myLabel.Text;\n    var intValue = 0;\n    Int32.TryParse(value, out intValue);\n    this.myLabel.Text = (--intValue).ToString();\n}	0
4117017	4114824	odbc instructions to connect to oracle	using (var conn = new OracleConnection("Some connection string"))\n    using (var cmd = conn.CreateCommand())\n    {\n       conn.Open();\n       cmd.CommandText = "SELECT id FROM foo";\n       using (var reader = cmd.ExecuteReader())\n       {\n          while (reader.Read())\n          {\n             int id = reader.GetInt32(0);\n          }\n       }\n    }	0
8831136	8830978	Convert comma separated twitter user-ids to corresponding screen names	string ids = "YOUR IDs";\n   int limit = 100;\n   List<string[]> store = new List<string[]>();\n   var split = ids.Split(',');\n   int counter = 0;\n   while (true) {\n       var batch = string.Join(",", split.Skip(counter++ * limit).Take(limit));\n       if (string.IsNullOrEmpty(batch)) break;\n       //Make your call here\n   }	0
10499149	10499124	Method signature containing "this" as a parameter modifier	var secureString = "someString".ConvertToSecureString();	0
4397495	4397435	Setting a ASP.NET Session in jquery.click()	Request.Cookies	0
29942972	29942784	Subtracting from an XML file	var fileName = @"c:\test.xml";\nvar manufacturer = "Yokohama";\nvar amount = 100;\n\nvar doc = XDocument.Load(fileName);\nvar node = doc.XPathSelectElements("Stock/Tyre/Manufacturer")\n              .FirstOrDefault(x => x.Value == manufacturer);\nif (node != null)\n{\n    var valueNode = node.Parent.XPathSelectElement("Quantity");\n    if (valueNode != null)\n        valueNode.SetValue(Convert.ToInt32(valueNode.Value)  - amount);\n}\n\ndoc.Save(fileName);	0
28895804	28895469	Edit Controller in MVC doesn't change data in database	[HttpPost]\n    public ActionResult Edit(EditViewModel model)\n    {\n\n        if (!ModelState.IsValid)\n        {\n            return View(model);\n        }\n        else\n        {\n            WorkerServices.PostEditViewModel(model);\n            return RedirectToAction("Index");\n        }	0
938071	938040	Create a dictionary on a list with grouping	var groupedDemoClasses = (from demoClass in mySepcialVariableWhichIsAListOfDemoClass\n                          group demoClass by demoClass.GroupKey\n                          into groupedDemoClass\n                          select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());	0
16551524	16551278	Filter files in a directory according to a date in the file name	var files = arquivos\n           .Select(f => new{OrgName = f, Parts = new FileInfo(f).Name.Split('.')})\n           .GroupBy(x=>x.Parts[1])\n           .Select(g=>g.OrderByDescending(x=>x.Parts[2]).First().OrgName);\n\nforeach (string arquivo in files)\n{\n    .....\n}	0
14288526	14288237	Can C# Winstore app access email app?	Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().Show("Foo");	0
9014530	9014479	Find a value in a range = is there such a code keyword in c#?	if (new int[] { 1, 2, 3 }.Contains(2))\n{\n    Console.WriteLine("bleh");\n}	0
11982505	11981738	How to create a copy of items in database without breaking FK constraints?	SET TERM !! ;\n\nCREATE TRIGGER Deep_Copy_Room FOR Location\nBEFORE INSERT\nPOSITION 0\n\nAS BEGIN\n\nNEW.id = GEN_ID (id_GEN, 1);\nINSERT INTO Room (id, name, size, fk) \n       VALUES (GEN_ID(id_GEN, 1), Roo_name, Roo_Size, NEW.id) \n       WHERE SELECT id, name, size, FK_id FROM Room AS Roo_Id, Roo_name, Roo_size\n               WHERE SELECT id, name, addrss FROM Location AS Loc_Id, Loc_name, Loc_address\n                       WHERE fk = Copy_From_id;\nINSERT INTO Item (id, name, type, value, fk_id) \n       VALUES (GEN_ID(id_GEN,1), Ite_name, Ite_type, Ite_value, Roo_id)\n       WHERE SELECT id, name, type, value, FK_id FROM RoomItem AS Ite_Id, Ite_name, Ite_type, Ite_value, Roo_Id)\n               WHERE SELECT id, name, size, FK_id FROM Room AS Roo_Id, Roo_name, Roo_size, Loc_id\n                       WHERE SELECT id, name, address FROM Location AS Loc_Id, Loc_name, Loc_address\n                               WHERE Loc_id = Copy_From_id;\n\nEND\n\nSET TERM ; !!	0
11302085	11301962	How do I post back information from a webpage that has post-generated content?	for (int i = 0; i < 10 ; i++)\n{\n    LinkButton link = new LinkButton() { ID = "link_" + i };\n    link.Text = "Link " + i;\n    link.Click+=new EventHandler(link_Click);\n    this.Form.Controls.Add(link);\n}\n\nprotected void link_Click(object sender, EventArgs e)\n{\n    //Every time a link is clicked it will get here in the server side\n}	0
19356097	19355774	Drag and drop a file into application window using WPF and data binding	string filename = (string)((DataObject)e.Data).GetFileDropList()[0];	0
7956898	7956813	Is It Possible To Generate a SQL Update Script For One Row Of Data?	Database > Tasks > Generate Scripts	0
13181639	13181258	c# using 2d arrays for buttons	private void button5_Click(object sender, EventArgs e)\n{\n   for (int col = 0; col < btns.GetLength(1); ++col)\n   {\n      var btn = btns[0, col];\n   //snip\n}\n\nprivate void button6_Click(object sender, EventArgs e)\n{\n   for (int col = 0; col < btns.GetLength(1); ++col)\n   {\n      var btn = btns[1, col];\n   //snip\n}	0
19216049	19208293	Format by template in Scala	val subDomain = "sd"\nval url = s"$subDomain.maindomain.com"	0
7365075	7364780	New WPF window only shows underneath originating window	e.Handled	0
21893034	21892942	Deserialize a JSON Schema with JSON.Net	var tacoProperties =\n       JsonConvert.DeserializeObject<IDictionary<string, TacoProperty>>(json);	0
29320265	29318638	Save and read settings value in Windows Phone 8.1	roamingSettings.Values["surname"] = surnamesBox.SelectedItem.ToString();	0
18146907	18142364	How to encrypt password on SQL Server and ASP.NET C#	//Hash user password\nString passwordHash = BCrypt.HashPassword(thePassword);\n//Verify user password\nbool passwordIsCorrect = BCrypt.Verify(thePassword, passwordHash);	0
11332256	11331842	Casting a Web Control taken from a GridView cell in VB	Dim button As DataGridViewButtonCell = DirectCast(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewButtonCell)\nMessageBox.Show(button.Value)	0
31128013	31128003	How I can call the windows Date and Time Process	Process.Start("control","timedate.cpl");	0
13026201	13022068	Is a good practice to do several callbacks to get data from DB in Silverlight?	public async Data GetData()\n{\n    return await _myService.GetDataAsync();\n}	0
26093024	26082781	Updating ListView from multiple background Tasks keeps adding the same ListViewItem	foreach (Server server in Servers)\n{\n    Server tmpServer = server;\n    Task<ListViewItem> mainTask = Task.Factory.StartNew<ListViewItem>(() =>\n    {\n        return GetMonitorData(tmpServer);\n    });\n\n    Task contTask = mainTask.ContinueWith(task =>\n    {\n        lstServers.Items.Add(task.Result);\n    }, TaskScheduler.FromCurrentSynchronizationContext());\n}	0
6038582	6038565	How do I change the font of the selected text in a rich text box in c#	richTextBox1.SelectionFont = new Font("Arial", 16);	0
11347649	11347576	How to make a circle shape label in Window Form?	System.Drawing.Graphics graphics = this.CreateGraphics();\nSystem.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);\ngraphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);	0
14097592	14097502	Remove duplicate web application names from foreach loop	DataView view = new DataView(dt);\ndt = view.ToTable(true, "Name", "Port Numbers");	0
3068716	3067764	Problem with building with csc task in Ant	csc.exe	0
12658548	12652998	Get Raw document from MongoDB through NoRM	db.GetCollection<test>().FindOne(new { Id = "235272479242" });	0
1172239	1172175	How do I get the sum of the Counts of nested Lists in a Dictionary without using foreach?	var i = dd.Values.Sum(x => x.Count);	0
20330223	20330093	Round off in listview	string val=listView1.Columns[2].ToString(); \n\ndouble i; \nif(Double.TryParse(val, out i)) \n{\n    Console.WriteLine(Math.Round(i)); // you can use Math.Round without second\n                                      // argument if you need rounding to the \n                                      // nearest unit  \n}	0
6749412	6749258	Remove anchor tag from Text	using System;\nusing System.Text.RegularExpressions;\n\npublic class Test\n{\n        public static void Main()\n        {\n                String sample = "<a href=\"http://test.com\" rel=\"nofollow\">LoremIpsum.Net</a> is a small and simple static site that <a href=\"http://test123.com\" rel=\"nofollow\">provides</a> you with a decent sized passage without having to use a generator. The site also provides an all caps version of the text, as well as translations, and an <a href=\"http://test445.com\" rel=\"nofollow\">explanation</a> of what this famous.";\n\n                String re = @"<a [^>]+>(.*?)<\/a>";\n                Console.WriteLine(Regex.Replace(sample, re, "$1"));\n        }\n}	0
9672624	9672575	Returning the existence of a key in a dict by searching key substring	bool containsKey = myDictionary.Keys.Any(x => x.Contains("mySubString"));	0
12959216	12959113	How can i set image link without adding it to my project?	var path = new UrlHelper(Request.RequestContext).Content("~/Content/Images/Funny/");	0
9161673	9161644	Loop inside Namespaces of an assembly?	var namespaces = library.GetTypes().GroupBy(t => t.Namespace);\nforeach (var typesInNamespace in namespaces)\n{\n    foreach (var type in typesInNamespace)\n    {\n      ...\n    }\n}	0
12999060	12998999	get date time from a reliable external source	The Network Time Protocol (NTP) and its simplified form (SNTP) are widely used to \nsynchronize network resources, due to their simplicity and effectiveness.	0
2714219	2714171	Accessing deleted rows from a DataTable	_dt.DefaultView.RowStateFilter	0
12735505	12734720	Why date format dd/MM/yy shows a time as well?	string a = String.Format("{0:MM/dd/yy}", DateTime.Now);	0
13106448	13106420	create folder and copy set of files to local disk	Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);	0
25893160	25867811	Change Colour of div inside asp repeater on itemdatabound	((HtmlGenericControl)(e.Item.FindControl("divColour"))).Attributes["style"] += ("background:" + rndColour + ";)");	0
13922720	13922681	in C#, how can I get the HTML content of a website before displaying it?	string GetPageSource (string url)\n{\nHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);\nwebrequest.Method = "GET";\nHttpWebResponse webResponse = (HttpWebResponse)webrequest.GetResponse();\nstring responseHtml;\nusing (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream()))\n{\n    responseHtml = responseStream.ReadToEnd().Trim();\n}\n\nreturn responseHtml;\n}	0
16639723	16639688	How do I make the taskbar icon go away?	ShowInTaskbar = false;	0
15303737	15303664	Adding more than one column to a C# list from MySQL Select	var list = (from IDataRecord r in dataReader\n            select new \n                   {\n                        Field1 = (string)r["Field1"],\n                        Field2 = (int)r["Field2"],\n                         ...\n                   }\n            ).ToList();	0
9519756	9519611	What is the best way to "inherit" a set of variable and routines that are static so they can be overridden	public class Singleton\n{\n   private static Singleton instance;\n\n   private Singleton() {}\n\n   public static Singleton Instance\n   {\n      get \n      {\n         if (instance == null)\n         {\n            instance = new Singleton();\n         }\n         return instance;\n      }\n   }\n}	0
3396449	3396391	Object array dynamic	List<object> list = new List<object>();\nlist.Add(key);	0
20832469	20832440	How to use a lookup table in entity?	using (var db = new GameAlertDBEntities())\n{\n    var user = db.Users.First(); // or any other query for user\n    var friends = user.Friends;\n}	0
17784862	17426860	Silverlight application get randomly stucks after loading plugin	/// <summary>\n/// ALL THE APP POP UP HAVE TO INHERIT from ChildWindowEx\n/// prevents the greyish app bug\n/// </summary>\npublic class ChildWindowEx : ChildWindow\n{\n    protected override void OnClosed(EventArgs e)\n    {\n        base.OnClosed(e);\n        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, true);\n    }\n}	0
2857286	2857107	delete attachment file	var filePath = "C:\\path\\to\\file.txt";\nvar smtpClient = new SmtpClient("mailhost");\nusing (var message = new MailMessage())\n{\n    message.To.Add("to@domain.com");\n    message.From = new MailAddress("from@domain.com");\n    message.Subject = "Test";\n    message.SubjectEncoding = Encoding.UTF8;\n    message.Body = "Test " + DateTime.Now;\n    message.Attachments.Add(new Attachment(filePath));\n}\nif (File.Exists(filePath)) File.Delete(filePath);\nConsole.WriteLine(File.Exists(filePath));	0
25206291	25180232	Can I detect a lack of a Console when running a Mono application in the background?	if (Console.In is StreamReader) {\n    Console.WriteLine("Interactive"); \n} else {\n    Console.WriteLine("Background"); \n}	0
1304987	1304981	Convert a string array to a concantenated string in C#	string[] theArray = new string[]{"Apples", "Bananas", "Cherries"};\nstring s = string.Join(",",theArray);	0
30971455	30969910	How do I properly post to a php web service using JSON and C#	Public static void Main (string[] args)\n{\n    using (var client = new WebClient())\n    {\n            var Parameters = new NameValueCollection {\n            {action = "login"},\n            {login = "demouser"},\n            {password = "xxxx"},\n            {checksum = "xxxx"}\n\n            httpResponse = client.UploadValues( "https://devcloud.fulgentcorp.com/bifrost/ws.php", Parameters);\n            Console.WriteLine (httpResponse);\n    }\n\n}	0
23293105	23292979	How to convert a JArray into a string?	Inv = Response.rgInventory.toString();	0
32261064	32242342	How to insert records into a Self referencing table via Fluent nHibernate?	References(x => x.ParentCategory).Cascade.SaveUpdate();\n\n        HasMany(x => x.Categories)\n            .Cascade.SaveUpdate();	0
22279412	22279400	make property as readonly using dataannotation attribute	[Editable(false)]\npublic string Name { get; set; }	0
26506951	26506657	ParseExact without time in format gives 12:00 AM	Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-BE");	0
683033	678540	Capturing the first frame of a video with WPF	FFMpeg.exe -i "c:\MyPath\MyVideo" -vframes 1 "c:\MyOutputPath\MyImage%d.jpg"	0
529847	529647	Need a smaller alternative to GUID for DB ID but still unique and random for URL	if( !item456.BelongsTo(user123) )\n{\n  // Either show them one of their items or a show an error message.\n}	0
1289230	1289203	Loading a control From a master Page	Page.Header.Controls.Add(new LiteralControl(" <script src="jquery" type="text/javascript"></script> "));	0
21413246	21411878	Saving a canvas to png C# wpf	Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas);\n            double dpi = 96d;\n\n\n            RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);\n\n\n            DrawingVisual dv = new DrawingVisual();\n            using (DrawingContext dc = dv.RenderOpen())\n            {\n                VisualBrush vb = new VisualBrush(cnvs);\n                dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));\n            }\n\n            rtb.Render(dv);	0
4875164	4875136	help with regex sentence	C.*\.C.*	0
3283458	3283278	Reading the XML values using LINQ	var applications = from p in xml.Descendants("Application") \n             select new { Nomy = p.Element("nomy").Value\n                        , Description = p.Element("Description").Value \n                        , Name = p.Element("Name").Value\n                        , Code = p.Element("Code").Value\n             };\n\nvar appRoles = from r in xml.Descendants("Role")\n               select new { Name = r.Element("Name").Value\n                          , ModifiedName = r.Element("ModifiedName").Value\n               };	0
16141101	16138275	Simple HTTP POST in Windows Phone 8	var values = new List<KeyValuePair<string, string>>\n                    {\n                        new KeyValuePair<string, string>("api_key", "12345"),\n                        new KeyValuePair<string, string>("game_id", "123456")\n                    };\n\nvar httpClient = new HttpClient(new HttpClientHandler());\nHttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values));\nresponse.EnsureSuccessStatusCode();\nvar responseString = await response.Content.ReadAsStringAsync();	0
18001735	18001481	using C# GUI with C++ projects	Process.Start(example.exe)	0
13667080	13667001	Using User32.dll SendMessage To Send Keys With ALT Modifier	ushort action = (ushort)WM_SYSKEYDOWN;\nushort key = (ushort)System.Windows.Forms.Keys.F1;\nuint lparam = (0x01 << 28);\nSendMessage(hWnd, action, key, lparam);	0
22278978	22278539	positioning objects from a text file	static class Program\n{\n    static void Main(string[] args)\n    {\n        using (StreamReader sr = new StreamReader(@"D:\1.txt"))\n        { \n            String s = null;\n            while ((s = sr.ReadUntil('-')) != null)\n            {\n                if (s.StartsWith("P"))\n                { \n\n                    //crate object\n                }\n                if (s.StartsWith("B"))\n                {\n\n                    //..\n                }\n            }\n        }\n    }\n\n    public static String ReadUntil(this StreamReader reader, char delimeter)\n    {\n        StringBuilder sb = new StringBuilder();\n        char c;\n        while ((c = (char)reader.Read()) != 0)\n        {\n            if (c == delimeter)\n                return sb.ToString();\n            else\n                sb.Append(c);\n        }\n\n        return sb.Length == 0 ? null:sb.ToString();\n\n    }\n}	0
13721743	13721672	Add a range of items to the beginning of a list?	myList.InsertRange(0, moreItems);	0
28102218	28102187	Correct syntax to initialize static array	public static string[] PAlphCodes = new string[] {\n            "1593",\n            "1604",\n            "1740",\n        };	0
21885114	21884954	Format a double in a string and keeping the decimal point	var results = string.Format("{0:00000000.0}", 191.5));	0
23637554	23630551	MongoDB Serialisation/Deserialisation of objects	BsonClassMap.RegisterClassMap<GenericIdentity>(cm =>\n{\n    cm.MapProperty(c => c.Name);\n    cm.MapProperty(c => c.AuthenticationType);\n    cm.MapCreator(i => new GenericIdentity(i.Name, i.AuthenticationType));\n});	0
11116220	11115299	Data Grid View multi querystring issue	// code behind\npublic string createUrl(object itemName, object link)\n{\n     return string.Format("showItem.aspx?itemID={0}&link={1}",\n         itemName.ToString(),\n         HttpUtility.UrlEncode(link.ToString()));\n}	0
10315411	9999137	MonoDroid - Draw Ellipse in runtime	[Activity(Label = "MonoAndroidApplication1", MainLauncher = true, Icon = "@drawable/icon")]\npublic class Activity1 : Activity\n{\n    protected override void OnCreate(Bundle bundle)\n    {\n        base.OnCreate(bundle);\n        var targetView = new OvalView(this);\n        SetContentView(targetView);\n    }\n}\n\npublic class OvalView : View\n{\n    public OvalView(Context context) : base(context) { }\n\n    protected override void OnDraw(Canvas canvas)\n    {\n        RectF rect = new RectF(0,0, 300, 300);\n        canvas.DrawOval(rect, new Paint() { Color = Color.CornflowerBlue });\n    }\n}	0
25558057	25558010	Musical representation of pi	c = 1 // tonic or root\nd = 2\ne = 3 // third (major in this case)\nf = 4\ng = 5 // perfect fifth\na = 6\nb = 7\nc = 8 //octave\nd = 9	0
29554822	29554754	Inserting data into local database using parameters	conn.Open();\n\n string strQuery = "INSERT INTO webtable (Id, url_name) VALUES (@id, @url)";\n SqlCommand cmd = new SqlCommand(strQuery, conn);\n cmd.Parameters.AddWithValue("@url", "nagia");\n cmd.Parameters.AddWithValue("@id", "9");\n cmd.Connection = conn;\n cmd.ExecuteNonQuery();\n conn.Close();	0
5716973	5716926	Strange DateTimePicker Formatting Behavior	checkedListBox1.Items.Add(dateTimePicker1.Value.ToString("dd/MM/yy"));	0
17420844	17420754	select row in winforms grid view	//For multiple row selection.\nIList rows = dg.SelectedItems;\n\n//For single row selection;\nDataRowView row = (DataRowView)dg.SelectedItems[0];\n\n//You can then access them via their column name;\nrow["yourColumnName"];\n\n//So to assign to say your label..\nLabelSelectedRow.Text = row["CODE"] + " " + " row[NAME] + " " + row[PRICE];	0
21608381	21607608	Auto fill in text when onlick button in asp	protected void btnFill_Click(object sender, EventArgs e)\n{\n    txtSalary.Text = "100";\n    txtCommision.Text = "20";\n}	0
4877595	4877556	workaround needed: notify a user that exe is missing dependencies from within the application?	try { \n      Assembly.Load(..);\n }\n catch(TypeLoadException ex) {\n\n         //Let the user know which type from what dll was not loaded.\n }	0
5436623	5403852	Retrieve ClientId from Html.TextBoxFor in a EditorTemplates	public static partial class HtmlExtensions\n{\n    public static MvcHtmlString ClientIdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n    {\n        return MvcHtmlString.Create(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));\n    }\n}	0
9821182	9821011	Parameter casting in reflections in C# VS2010	method.Invoke(object,new object[]{1, "test", true});	0
17627982	17627903	Access strings resources from embedded .resx in dll?	public static string getStringByName(string var)\n    {\n        System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();\n        string resName = asm.GetName().Name + ".Properties.Resources";\n        var rm = new ResourceManager("ValhallaLib.StringResource", asm);\n\n        return rm.GetString(var);\n    }	0
32318031	32317705	How to use a mathematic equation to stop object going off screen?	using UnityEngine;\nusing System.Collections;\npublic class Paddle : MonoBehaviour {\n\n    public Texture texture;\n\n    public void Update () {\n\n        Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y , 0f);\n\n        float mousePosInBlocks = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;\n\n        paddlePos.x = Mathf.Clamp(mousePosInBlocks, leftValue, rightValue);\n\n        this.transform.position = paddlePos;\n    }\n}	0
1338552	1338517	How can I write xml with a namespace and prefix with XElement?	using System;\nusing System.Xml.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n    XNamespace ci = "http://somewhere.com";\n    XNamespace ca = "http://somewhereelse.com";\n\n    XElement element = new XElement("root",\n    new XAttribute(XNamespace.Xmlns + "ci", ci),\n    new XAttribute(XNamespace.Xmlns + "ca", ca),\n    new XElement(ci + "field1", "test"),\n    new XElement(ca + "field2", "another test"));\n    }\n}	0
34415990	34415507	How do I get a datagrid that is bound to an observable collection to notify of deletions using mvvm?	BookList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler( BookList_CollectionChanged );\n\nvoid BookList_CollectionChanged( object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e )\n{\n    if ( e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove )\n    {\n\n    }\n}	0
2884967	2882539	Working with Checkbox column in DataGrid in Winforms project	foreach (DataGridViewRow item In DataGridName.Rows)\n{\n\n    If (item.Cells(0).Value)\n    {\n        MyMethod(item.Cells(0).Value);\n    }   \n\n}	0
2085654	2085304	Export c++ functions inside a C# Application	namespace SOMENAMESPACE\n{\n                public ref class SOMECLASS\n                {\n                               public: \n                               SOMETYPE func(param A,char b[tot]);\n\n                };\n}	0
4823753	4822930	Choosing the adapter SendTo uses to transmit a multicast frame	Socket.Bind()	0
8768750	8768720	making model property optional	public class Page1ViewModel\n{\n    [Required]\n    [Display(Name = "Email Address")]\n    [DataType(DataType.EmailAddress)]\n    [RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage= "Invalid Email Address")]\n    public string Email { get; set; }\n\n    //Other properties\n\n}\n\npublic class Page2ViewModel\n{\n    [Display(Name = "Email Address")]\n    [DataType(DataType.EmailAddress)]\n    [RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage    = "Invalid Email Address")]\n    public string Email { get; set; }\n\n    //Other properties\n}	0
21771603	21769398	How to use RestSharp for non standard url containing symbols like = and ::?	var client = new RestClient("http:// mysite.com/api/");\nvar request = new RestRequest("v2.php", Method.GET);\nrequest.AddParameter("method", "information::method");\nrequest.AddParameter("token", authenticationToken);\nrequest.AddParameter("target_id", targetId);	0
11383864	11383443	gridview not showing values via BLL?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing NopSolutions.NopCommerce.Nop.DataAccess.MegaProductMenuTableAdapters;\n\nnamespace NopSolutions.NopCommerce.BusinessLogic.MegaProductsMenu\n{\n    [System.ComponentModel.DataObject]\n    public class categoriesBLL\n    {\n\n        private Nop_CategoryTableAdapter _categoriesAdapter = null;\n        protected Nop_CategoryTableAdapter Adapter\n        {\n            get\n            {\n                if (_categoriesAdapter == null)\n                    _categoriesAdapter = new Nop_CategoryTableAdapter();\n\n                return _categoriesAdapter;\n            }\n        }\n\n        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]\n        public NopCommerce.Nop.DataAccess.MegaProductMenu.Nop_CategoryDataTable GetCategories()\n        {\n            return Adapter.GetCategories();\n        }\n\n    }\n\n}	0
20613028	20612040	How to invoke WCF service method	web.config	0
18154046	18153998	How do I remove all HTML tags from a string without knowing which tags are in it?	public static string StripHTML(string input)\n{\n   return Regex.Replace(input, "<.*?>", String.Empty);\n}	0
5746061	5745512	How to read a .NET Guid into a Java UUID	BitConverter.isLittleEndian	0
10069746	10069653	how to implement join using LINQ and EntityFramework	from r in Roles\nfrom q in Queues\nwhere r.RoleId == q.RoleId\nwhere q.QueueId == 361\nselect new { r.RoleId, q.QueueId /*other bits you want*/}	0
20326268	20076143	LongListSelector scrolling issues	VirtualizingStackPanel.VirtualizationMode="Standard"	0
16492911	16492847	Select record in self-hierarchy that falls into a date range	public Record GetRecord(int RecordId, DateTime Date)\n{\n  var r = records.firstOrDefault(record => record.Id == RecordId && record.Date < Date)\n\n  if(r != null && r.ParentId != null)\n    return GetRecord(r.ParentId, Date)  // Get the parent, if existing..\n  else\n    return r;                           // Return the matching record\n}	0
19532881	19532676	How to convert a string to int in aspx source page	TabIndex='<%# Int32.Parse(Eval("Id").ToString())>'	0
17950781	17936874	Ajax client-side framework failed to load, sys undefined	protected void Application_Start(object sender, EventArgs e)\n{\n    RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");\n}	0
32363448	32186172	How can I pass a SSL certificate to Nowin when using Nancy	using System;\nusing System.Net;\nusing System.Threading.Tasks;\nusing Nancy.Owin;\nusing Nowin;\n\npublic class Program\n{\n    static void Main(string[] args)\n    {\n        var myNancyAppFunc = NancyMiddleware.UseNancy()(NancyOptions options =>\n        {\n            // Modify Nancy options if desired;\n\n            return Task.FromResult(0);\n        });\n\n        using (var server = ServerBuilder.New()\n            .SetOwinApp(myNancyAppFunc)\n            .SetEndPoint(new IPEndPoint(IPAddress.Any, 8080))\n            .SetCertificate(new X509Certificate2("certificate.pfx", "password"))\n            .Build()\n        )\n        {\n            server.Start();\n\n            Console.WriteLine("Running on 8080");\n            Console.ReadLine();\n        }\n    }\n}	0
6418485	6418378	How to determine that a UserControl Collection Property has changed at Design Time?	class StringCollection : System.Collections.IList {\n        private List<object> impl = new List<object>();\n        public int Add(object value) {\n            Console.Beep();\n            impl.Add(value);\n            return Count;\n        }\n\n        public void Clear() {\n            impl.Clear();\n        }\n\n        // etc...\n    }	0
2478747	2478276	How can I get SQLite to work in C#	SQLiteConnection connection = new SQLiteConnection("Data source=PATH_TO_YOUR_DB;Version=3");\nconnection.Open();\nSQLiteCommand command = connection.CreateCommand();\ncommand.CommandText = "insert into something values (1,2,3)";\ncommand.ExecuteNonQuery();\nconnection.Close();	0
9596144	9595825	Capture specific modifier key	[DllImport("user32.dll")]\n    private static extern short GetAsyncKeyState(Keys key);\n\n    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)\n    {\n        Console.WriteLine("Ctrl:{0}, LCtrl:{1}, RCtrl:{2}",\n        GetAsyncKeyState(Keys.ControlKey) < 0,\n        GetAsyncKeyState(Keys.LControlKey) < 0,\n        GetAsyncKeyState(Keys.RControlKey) < 0);\n    }	0
19866561	18192333	Changing an Entity creates a new one as well	City object = new City();\nobject.name = "Some name";\nobject.countryID = someCountry.countryID;  //this will work as intended\n//object.country = someCountry;  //this will work NOT as intended\nyourContext.City.addObject(object);\nyourContext.saveChanges();	0
9899098	9898869	Get Prettified JSON from MVC 3 JsonResult	JsonConvert.SerializeObject( myObjectDestinedForJSON, Formatting.Indented);	0
7106361	7106313	c# splitting and retrieving values from a string	string link = "http://localhost:55164/Images/photos/2/2.jpg"; // your link\nstring[] x = link.Split('/'); // split it into pieces at the slash\nstring filename = (x.Length >= 1) ? x[x.Length - 1] : null; // get the last part\nstring dir = (x.Length >= 2) ? x[x.Length - 2] : null; // get the 2nd last part	0
15756908	15717693	Deserialize a XML fragment to class that has been generated by xsd.exe	XmlSerializer serializer = new XmlSerializer(typeof(RootClass));\n        using (TextReader reader = new StreamReader(filePath))\n        {\n            RootClass parameterFromFile = (RootClass)serializer.Deserialize(reader);\n        }	0
11964226	11964162	Concat byte values with a operator?	byte[] byteData = (new byte[]{0,0}).Concat(Encoding.UTF8.GetBytes("asas")).Concat(new byte[]{20}).ToArray();	0
2659986	2659721	How to find ALL descendants using HierarchyID for SQL Server	DECLARE @root hierarchyID;\n\nSELECT @root = col\nFROM yourTable\nWHERE [whatever uniquely identifies this row]\n\nSELECT *\nFROM yourTable\nWHERE col.IsDescendantOf(@root) = 1	0
10182640	10182622	How to call a stored procedure from MVC that requires a list of ids	String.Join(",", areaIds)	0
29914699	29884219	How to get user name, email, etc. from MobileServiceUser?	ServiceUser user = this.User as ServiceUser;\n    var identities = await user.GetIdentitiesAsync();\n    var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();\n    var aadAccessToken = aad.AccessToken;\n    var aadObjectId = aad.ObjectId;	0
22749422	22749303	Entity Framework Add Performance Degrades With More Rows	var msg = new Message()\n    {\n        MessageId = new Guid(),\n        Author = user,\n        Body = body,\n        SendTime = DateTimeOffset.UtcNow,\n        PadId = new Guid(pad_id)\n    };\n\n    // pad.Messages.Add(msg); // don't need this.\n    db.Messages.Add(msg);	0
2316810	2316776	Check if values of Dictionary contains an element with certain field value	using System.Linq;\n...\n_identityMap.Values.Any(x=>x.extension==extension)	0
26018877	26018658	extend enum with attribute in other assembly	public enum MyExtendedEnumeration\n{\n    [MyAttribute("The First Value")]\n    TheFirstValue = TheEnumeration.TheFirstValue,\n\n    [MyAttribute("The 2nd Value")]\n    TheSecondValue = TheEnumeration.TheFirstValue\n}	0
2299079	2274836	Sign data with MD5WithRSA from .Pem/.Pkcs8 keyfile in C#	string pemContents = new StreamReader("pkcs8privatekey.pem").ReadToEnd();\n        var der = opensslkey.DecodePkcs8PrivateKey(pemContents);\n        RSACryptoServiceProvider rsa = opensslkey.DecodePrivateKeyInfo(der);\n\n        signature = rsa.SignData(data, new MD5CryptoServiceProvider());	0
12203520	12203481	Convert label text to decimal	Decimal.TryParse	0
2227180	2218931	Extension of Binary search algo to find the first and last index of the key value to be searched in an array	int bs1(int a[], int val, int left, int right)\n{\n    if(right == left) return left;\n    int mid = (right+left)/2;\n\n    if(val > a[mid]) return bs1(a, val, mid+1, right);\n    else return bs1(a, val, left, mid);\n}	0
22792535	22792389	How to keep json file format valid while using Json.net library to write new record to existing to json file?	var fileName = WebConfigurationManager.AppSettings["JsonFileLocation"];\nList<Students> studentsList = new List<Students>();\n\nusing (var sr = new StreamReader(fileName))\n{\n var jsonStudentsText = sr.ReadAllText();\n studentsList = JsonConvert.DeserializeObject<List<Students>>(jsonStudentsText); \n}\n\nstudentsList.Add(new Students{name = name, grade = grade});\n\nusing (var sw = new StreamWriter(fileName))\n{\n using (JsonWriter jw = new JsonTextWriter(sw))\n {\n  jw.Formatting = Formatting.Indented;\n  JsonSerializer serializer = new JsonSerializer();\n  serializer.Serialize(jw, studentsList);\n }\n}	0
22000198	21999985	JSON Naming issue using Lastfm API	public class ArtistImage\n{\n    [JsonProperty("size")]\n    public string Size { get; set; }\n\n    [JsonProperty("#text")]\n    public string Uri { get; set; }\n}	0
1506819	1506499	XML Serialization of HTML	public class Result\n{\n    [XmlIgnore]\n    public String htmlValue\n    {\n        get;\n        set;\n    }\n\n    private static XmlDocument _dummyDoc;\n\n    [XmlElement("htmlValue")]\n    public XmlCDataSection htmlValueCData\n    {\n        get { return _dummyDoc.CreateCDataSection(htmlValue); }\n        set { htmlValue = (value != null) ? value.Data : null; }\n    }\n}	0
18890220	18890120	Update a progressbar when steps are arbitrary	// At some point when you start your computation:\npBar.Maximum = myFileList.Count;\n\n// Whenever you want to update the progress:\npBar.Value = progress;\n\n// Alternatively you can increment the progress by the number of lines processed\n// since last update:\npBar.Increment(dLines);	0
8355610	8355339	How to build a query like the selectbyexample using linq-to-entities?	var p = new Person {Age = 25};\n\n       src.Where(el => p.Age == null ? true : el.Age == p.Age)\n           .Where(el => p.Name == null ? true : el.Name == p.Name)\n           .Where(el => p.City == null ? true : el.City == p.City);	0
14924802	14924756	Transform a Model3DGroup twice	var model = ModelImporter.Load(gameAssetPath);\nvar modelRotation = new Model3DGroup();\nmodelRotation.Children.Add(model);\nvar t1 = new TranslateTransform3D(\n        placedObject.SpawnCoordinates.X,\n        placedObject.SpawnCoordinates.Y,\n        placedObject.SpawnCoordinates.Z);\nvar t2 = new RotateTransform3D(\n         new AxisAngleRotation3D(), \n        placedObject.SpawnCoordinates.Roll, \n        placedObject.SpawnCoordinates.Pitch, \n        placedObject.SpawnCoordinates.Yaw);\nvar tg = new TransformGroup();\ntg.Children.Add(t1);\ntg.Children.Add(t2);\nmodelRotation.Transform = tg;	0
27607098	27606970	How to open Excel-workbooks without the message The workbook contains links to other data sources. programmatically?	Application.AskToUpdateLinks = False	0
4942381	4941922	Apply Transition with Silverlight Toolkit to Grid containing Canvas in Windows Phone 7	TurnstileTransition turnstileTransition = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardIn};\n    ITransition transition = turnstileTransition.GetTransition(Canvas1);\n    transition.Completed += delegate\n    {\n        transition.Stop();\n    };\n    transition.Begin();	0
8676225	8676193	How can I make the value of a field default to something when a class is constructed?	private int _status=3;\n\npublic int Status\n{\n  get { return _status;}\n  set {_status=value;}\n}	0
15609174	15609150	Finding in a list that contains an attribute of an object	var query = EmployeeList.Where(employee => employee.Roles\n                                                   .Any(role => role.Id == roleID))\n                                                   .ToList();	0
30239075	30238948	Sharing Dictionary Values	Dictionary<string, string> myDictionary = new Dictionary<string, string>()\n        {\n            {"cat", "miaow"},\n            {"dog", "woof"},\n            {"iguana", "grekkkk?"}\n\n        };\npublic void Main()\n{\n\n    // create a dictionary and add values\n\n\n    // get a value from the dictionary and display it\n    MessageBox.Show(myDictionary["cat"]);\n\n    // call another procedure\n    up();\n\n    // call another procedure that calls another procedure\n    sh();\n\n}\n\npublic void up() \n{\n\n    // get a value from the dictionary and display it\n    MessageBox.Show(myDictionary["dog"]);\n\n}\n\npublic void sh()\n{\n\n    // call another procedure\n    up();\n\n}	0
8397718	8397010	How to generate xml file with specific structure from  datatables?	//Read the teachers element from xml schema file\nXElement teachers = XDocument.Load(schemaFile).Descendants("teachers").SingleOrDefault();\n\nif (teachers != null)\n{\n    DataTable dt = new DataTable();\n    dt.Columns.Add("id");\n    dt.Columns.Add("name");\n\n\n    dt.Rows.Add("1", "john");\n    dt.Rows.Add("2", "philips");\n    dt.Rows.Add("3", "sara");\n\n    XDocument doc = new XDocument();\n    foreach (DataRow row in dt.Rows)\n    {\n        XElement teacher = new XElement("teacher");\n        teacher.SetAttributeValue("id", row["id"]);\n        teacher.SetAttributeValue("name", row["name"]);\n        teacher.SetAttributeValue("short", row["name"].ToString().Substring(0,2));\n\n        teachers.Add(teacher);\n    }\n    doc.Add(teachers);\n    doc.Save(newFilename);\n }	0
7468466	7468385	Setting the default values of AssemblyInfo.cs	32 bit: HKLM\Software\Microsoft\Windows NT\CurrentVersion\n64 bit: HKLM\Software\Wow6432Node\Microsoft\WindowsNT\CurrentVersion	0
21259299	21259006	Round a number based on a ratio in C#	Math.Pow(factor, Math.Floor(Math.Log(ratio, factor)))	0
26507801	26507645	HttpListener handling multiple requests	private void startlistener(object s)\n{\n    while (true)\n    {               \n        ////blocks until a client has connected to the server\n        ProcessRequest();\n    }\n}	0
13163619	13163560	Reading different int from the same textbox	foreach(char c in TextBox.Text)\n{\n  // TODO: send current number. Cast to string if needed: (string)c \n}	0
15571954	15571715	Auto Resize Font to fit rectangle	private void MeasureStringMin(PaintEventArgs e)\n{\n\n    // Set up string. \n    string measureString = "Measure String";\n    Font stringFont = new Font("Arial", 16);\n\n    // Measure string.\n    SizeF stringSize = new SizeF();\n    stringSize = e.Graphics.MeasureString(measureString, stringFont);\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
11594799	11594784	How to connect a URL address to image	Process.Start("http://www.stackoverflow.com");	0
3265952	3265651	Determine if a Form from another project is open	public class Form2 : Form\n{\n    Mutex m;\n    protected override void OnShown(EventArgs e)\n    {\n        base.OnShown(e);\n        m = new Mutex(true, "Form2");\n    }\n\n    protected override void OnClosed(EventArgs e)\n    {\n        base.OnClosed(e);\n        m.ReleaseMutex();\n    }\n}\n\npublic class Form3 : Form\n{\n    bool form2IsOpen;\n    public Form3()\n    {\n        try\n        {\n            Mutex.OpenExisting("Form2");\n            form2IsOpen = true;\n        }\n        catch (WaitHandleCannotBeOpenedException ex)\n        {\n            form2IsOpen = false;\n        }\n    }\n}	0
23951881	23951794	How to: Add a string to a string array using File.ReadAllLines	public void CreateNewFolder()\n{\n    List<String> lines = File.ReadAllLines(stringFile, Encoding.UTF8).ToList();\n    lines.Add("Test");\n    File.WriteAllLines(stringFile, lines.ToArray(), Encoding.UTF8);\n    //Calling the ToArray method for lines is not necessary \n}	0
33615660	33615411	C# appointing distinct array elements randomly to another array	int[] card1 = nums.OrderBy(it => Guid.NewGuid()).Take(6).ToArray();	0
17869731	17869538	Compare two strings in javascript; ASP. NET c#	function ButtonClick(a, b)\n{\n  if (a == b) \n  {\n     alert("Correct!");\n  }\n  else\n  {\n     alert("Wrong!");\n  }\n\n}	0
18054410	18051571	multiple arraylist repeat subjectname display in sequence	Dim hasMultiple As New Dictionary(Of String, Boolean)\n    For Each subject As String In arraysub\n        If hasMultiple.ContainsKey(subject) Then\n            hasMultiple(subject) =  True\n        Else\n            hasMultiple.Add(subject, False)\n        End If\n    Next\n\n    Dim output As New List(Of String)\n    Dim subCount As New Dictionary(Of String, Integer) \n    For Each subject As String In arraysub\n        If Not subCount.ContainsKey(subject) Then\n            subCount.Add(subject, 0)\n        End If\n        subCount(subject) += 1\n        If hasMultiple(subject) Then\n            output.Add(subject & "_" & subCount(subject))\n        Else\n            output.Add(subject)\n        End If\n    Next	0
11590978	11590968	How can I enumerate everything in an enum?	foreach (Numbers n in Enum.GetValues(typeof(Numbers))) \n{\n    Console.WriteLine(n.ToString());\n}	0
31945584	31944476	c# new line printing out a String	private void PrintReceiptPage(object sender, PrintPageEventArgs e)\n{\n    string message = "Haalloodhsak dfsdfsfdsfsdfdssdddddddddddddddsf  Tetsn dfgdfgdfgdfg dfgdfgdfgdfg dfgdfgdfgdfggdfdfg gdgdgdffgddfgdfgdfggdf dfgdfgdfgdfggdf";\n    int yMargin;\n    // Print receipt\n    Font myFont = new Font("Times New Roman", 15, FontStyle.Bold);\n    yMargin = e.MarginBounds.Y;\n\n    // Create rectangle for drawing. \n    float x = 150.0F;\n    float y = 150.0F;\n    float width = 200.0F;\n    float height = 50.0F;\n    RectangleF drawRect = new RectangleF(x, yMargin, width, height);\n\n    e.Graphics.DrawString(message, myFont, Brushes.Red, drawRect);\n}	0
19336405	19336272	unit testing a function that doesn't return a value	[Setup]	0
2161205	2161171	Read Content in Dll programatically and write it into another file in Silverlight	System.Reflection.Assembly.Load	0
10354449	10354275	C# How to stop a method if it takes longer than 2 seconds?	public void gethtml()\n    {\n        HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://msnbc.com/");\n        WebRequestObject.Timeout = (System.Int32)TimeSpan.FromSeconds(2).TotalMilliseconds;\n        try\n        {\n            WebResponse Response = WebRequestObject.GetResponse();\n            Stream WebStream = Response.GetResponseStream();\n\n            StreamReader Reader = new StreamReader(WebStream);\n            string webcontent = Reader.ReadToEnd();\n            MessageBox.Show(webcontent);\n        }\n        catch (System.Net.WebException E)\n        {\n            MessageBox.Show("Fail");\n        }\n    }	0
16108196	16108093	Newton.JSON convert dynamic object to JObject instead of dynamic object	string result = @"{""AppointmentID"":463236,""Message"":""Successfully Appointment Booked"",""Success"":true,""MessageCode"":200,""isError"":false,""Exception"":null,""ReturnedValue"":null}";\ndynamic d = JsonConvert.DeserializeObject<dynamic>(result);\n\nstring message = d.Message;\nint code = d.MessageCode;\n...	0
8750691	8750666	Correct format for a naughty regular expression	(?<![a-zA-Z])sas(?![a-zA-Z])	0
4932743	4932375	get node from xml in c#	// Loading from a file, you can also load from a stream\n        XDocument loaded = XDocument.Load(@"d:\test.xml");\n        // Query the data \n        var query = from c in loaded.Descendants("MetadataFormConfig")\n                where (string)c.Attribute("FieldInternalName") == "Test"\n                select c;	0
10678119	10676649	Attach window to window of another process	MyWindow window = new MyWindow();\nwindow.ShowActivated = true;\n\nHwndSourceParameters parameters = new HwndSourceParameters();\n\nparameters.WindowStyle = 0x10000000 | 0x40000000;\nparameters.SetPosition(0, 0);\nparameters.SetSize((int)window.Width, (int)window.Height);\nparameters.ParentWindow = newParent;\nparameters.UsesPerPixelOpacity = true;\nHwndSource src = new HwndSource(parameters);\n\nsrc.CompositionTarget.BackgroundColor = Colors.Transparent;\nsrc.RootVisual = (Visual)window.Content;	0
5655374	5655363	the easiest way to get number from string	string input = "valueID = 234232";\nvar split = input.Split(new char[] {'='});\nint value = int.Parse(split[1].Trim());	0
24492432	24490417	Populate treeview wthout parentid field	foreach (DataRow dr in table.Rows) {\n  if (!treeView1.Nodes.ContainsKey(dr["ID"].ToString())) {\n    treeView1.Nodes.Add(dr["ID"].ToString(), dr["ID"].ToString());\n  }\n  treeView1.Nodes[dr["ID"].ToString()].Nodes.Add(dr["SubID"].ToString());\n}	0
5348852	5348844	How to convert a string to ASCII	string s = "hallo world";\nforeach( char c in s)\n{\n    Console.WriteLine(System.Convert.ToInt32(c));\n}\nConsole.ReadLine();	0
13021085	13020838	How to know if the user has permission on a parent node of a tree?	public class Permission\n{\n  public ID { get; set; }\n  public ParentID { get; set; }\n  public Name { get; set; }\n}\n\nint userPermissionID = 3;  // Division two\nint objectPermissionID = 7; // Department 2.2\nbool hasAccess = false;\n\nList<int> check = new List<int>();\ncheck.add(objectPermissionID);\n\nhasAccess = userPermissionID == objectPermissionID;\n\nwhile(!hasAccess && check.count > 0)\n{\n  var permissions = context.Permissions\n    .Where(p => check.Contains(p.ID))\n    .ToList();\n\n  hasAccess = permissions.Any(p => p.ParentID = userPermissionID)\n\n  check = permissions.Select(p => p.ParentID).ToList();\n}\n\nif (hasAccess)\n{\n  ..	0
4250410	4249064	Using GetHashCode to test equality in Equals override	public static void Main()\n{\n    var c1 = new Class1() { A = "apahaa", B = null };\n    var c2 = new Class1() { A = "abacaz", B = null };\n    Console.WriteLine(c1.Equals(c2));\n}	0
24402523	24402325	How to add text in active document using c#	(DTE.ActiveDocument.Selection as EnvDTE.TextSelection).Text = "my new text";	0
19731357	19731262	Using linq group by statement as a subquery	from b in bands\ngroup b by new { b.Region, b.DayName } into g\nselect new {\n   g.Key.Region,\n   g.Key.DayName,\n   StartDate = g.Min(x => x.StartDate),\n   EndDate = g.Max(x => x.EndDate),\n   AllBandsFromGroup = g,\n   FirstBand = g.First(),\n   LastBandPeriod = g.Last().Period\n}	0
20889607	20889104	Save HTML content of some specific tags using HtmlAgilityPack	var xpath = "//td[@class='text_11' and @width='80%' and @valign='top']";\nvar td = doc.DocumentNode.SelectSingleNode(xpath);\nstring html = td.InnerHtml; // check also if td is not null	0
20026126	20025320	Connection string to a live database asp.net C#	{\n        MySqlConnection cs = new MySqlConnection(@"Data Source = 000.000.00.000;username=*******;password=******; Initial Catalog = database; Integrated Security = true");\n       MySqlDataAdapter da = new MySqlDataAdapter ();\n        da.InsertCommand = new MySqlCommand("INSERT INTO Customer(FirstName,LastName) VALUES (@FirstName,@LastName)", cs);\n        da.InsertCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = firstname.Text;\n        da.InsertCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = lastname.Text;\n\n        cs.Open();\n        da.InsertCommand.ExecuteNonQuery(); \n        cs.Close();\n    }	0
19208690	12695700	OLE Object in Crystal Report	CRAXDRT.OleObject to3 = report2.Sections[i].AddPictureObject("YourPictureName.bmp", 0, 0);\nto3.Height = 1600;  //just a number as height\nto3.Width = 1250;   //just a number as width\nto3.Left = 0;       //the left part of the object will be start from the value which you set for this property\nto3.Top = 0;        //the top part of the object will be start from the value which you set for this property	0
18759046	18758744	How to use threading to update a DataTable which tends to change dynamically by Main Thread?	if(DGV.InvokeRequired)\nDGV.Invoke(new EventHandler(delegate\n{\n     DGV.DataSource= currentDataTable;\n}));\nelse DGV.DataSource= currentDataTable;	0
14678109	14678010	DateTime.AddYear, AddMonth, AddDay, AddHour, AddMinute doesn't add?	hourToWaitTo = Convert.ToInt32(txtboxHourToWaitTo.Text);\nminuteToWaitTo = Convert.ToInt32(txtboxMinuteToWaitTo.Text);\n\nDateTime endTime = new DateTime(currentYear, currentMonth, currentDay, hourToWaitTo, minuteToWaitTo, 0);	0
25405056	25404950	C# Looking for a key in a hash table and gather the corresponding value	Point value;\nif (Hash.ContainsKey(YourKey))\n{\n    value = (Point)Hash[YourKey];\n}	0
11777911	11777875	Insert statement when having GUID as primary key	Newid()	0
10341337	10341301	Get remote port of a connected TcpClient	var port = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port	0
1609155	1609149	WPF - How to access method declared in App.xaml.cs?	((App)Application.Current).YourMethod ....	0
9408430	9406799	Full Text Search with constantly updating data	{\n  _id,\n  title,\n  content,\n  rating, //increment it \n  status(new, updated, delete) // you need this for lucene\n}	0
10062550	10062525	How can I create a list of .aspx pages?	DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("/MyPages"));\nFileInfo[] fileinfo = directoryInfo.GetFiles("*.aspx");\n\n// do data binding here	0
16061512	16061489	What to put in the Type targetType parameter in IValueConverter	typeof(string)	0
12584612	12582550	Setting 404 response while still displaying page	protected void Page_Load(object sender, EventArgs e) \n{ \n    Response.StatusCode = 404; \n    Response.End(); \n}	0
6618897	6618868	Regular expression for version numbers	\d+(?:\.\d+)+	0
2576594	2576570	Controller Action Methods with different signatures	public ActionResult Index(int? id){ \n    if( id.HasValue ){\n        File file = fileRepository.GetFile(id.Value);\n        if (file == null) return Content("Not Found");\n            return Content(file.FileID.ToString());\n\n    } else {\n        return Content("Index ");\n    }\n}	0
26013829	26013718	How do I exactly match a word with C#'s contains function?	bool contains = Regex.IsMatch(m.text, @"\bMaterial\b");	0
19606391	19606303	Image is showing even in false if-else statement in c#.net	Map.Visible = false;\nMapImage.Visible = false;	0
27827205	27826990	Storing multiple selected cells of type string from a datagridview to a list	List<String> listProducts = new List<string>();\n            for (int i = 0; i < dataGridViewIndex.SelectedCells.Count;i++)\n            {\n                listProducts.Add(dataGridViewIndex.SelectedCells[i].Value.ToString());\n            }	0
23446282	23445995	Make program beep on every exception raised	try\n{\n     // your code here\n}\ncatch (Exception) // this goes to every single exception, if you want to beep on a specific one just replace the Exception with the exception you expect e.g NullReferenceException\n{\n     Console.Beep();\n     throw;\n}	0
10780510	10775318	Monotouch set properties not keeping property values	public static class SelectedRound\n{\n    public static string RoundID {get;set;}\n    public static string Date {get;set;}\n}	0
6125616	6125519	Date & Time Separation	DateTime dt;\nstring Temp1 = "Your Date";\nif (Temp1.LastIndexOf("GMT") > 0)\n{\n    Temp1 = Temp1.Remove(Temp1.LastIndexOf("GMT"));\n}\nTemp1 = "Wed May 25 23:43:31 UTC+0900 2011";\nif (Temp1.LastIndexOf("UTC") > 0)\n{\n     Temp1 = Temp1.Remove(Temp1.LastIndexOf("UTC"), 9);\n     string[] split = Temp1.Split(' ');\n     Temp1 = split[0] + " " + split[1] + " " + split[2] + " " + split[4] + " " + split[3];\n}\nif (DateTime.TryParse(Temp1, out dt))\n{\n     // If it is a valid date\n     string date = dt.ToShortDateString();\n     string time = dt.ToShortTimeString();\n}	0
21164850	21164434	How to use Linq instead of foreach to Group and Count	AlleCoaches.ToList()\n.ForEach(n=>n.NumOfPlayer=AllePlayer.Where(n=>coachNumer==n.coachNumer).Count());	0
11853440	11853096	Adding Image to FixedPage in WPF	var bitImage = new BitmapImage();\nbitImage.BeginInit();\nbitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);\nbitImage.DecodePixelWidth = 250;\nbitImage.CacheOption = BitmapCacheOption.OnLoad;\nbitImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;\nbitImage.EndInit();\nbitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);\nbitImage.Freeze();\n\nvar tempImage = new Image {Source = bitImage};\nvar imageObject = new ImageObject(tempImage, fileName);\nbitImage.StreamSource.Dispose();\npage.Children.Add(imageObject);	0
18932673	18931480	Parsing unbranched XML in C#	class MX\n{\n    public string BatchNo { get; set; }\n    public string SpecimenID { get; set; }\n    //and so on\n    static public List<MX> Arr = new List<MX>();\n}\nprotected void Page_Load(object sender, EventArgs e)\n{        \n    XDocument doc = XDocument.Load(Server.MapPath("~/xml/a.xml"));\n    List<string> ListBatchNo = new List<string>();\n    foreach (var node in doc.Descendants("BatchNo."))\n    {\n        ListBatchNo.Add(node.Value);\n    }\n    List<string> ListSpecimenID = new List<string>();\n    foreach (var node in doc.Descendants("SpecimenID"))\n    {\n        ListSpecimenID.Add(node.Value);\n    }\n    MX.Arr.Clear();\n    for (int i = 0; i < ListBatchNo.Count; i++)\n    {\n        MX obj = new MX();\n        obj.BatchNo = ListBatchNo[i];\n        obj.SpecimenID = ListSpecimenID[i];\n        MX.Arr.Add(obj);\n    }\n    GridView2.DataSource = MX.Arr;\n    GridView2.DataBind();\n}	0
21166751	21166701	Preventing a control from loading	protected void Page_Load(object sender, EventArgs e)\n{\n\n    if ((string)HttpContext.Current.Session["System"] == "sysA")\n    {\n        gvSystemB.Visible = false;\n    }\n    else\n    {\n        gvSystemA.Visible = false;\n    }\n\n}	0
4923685	4923266	How to plot how variables change in Visual Studio	someVariable = {someVariable}	0
426013	426001	Converting MSSQL GetUTCDate() into PHP/Unix/MySQL Ticks	DateTime dt = something; //Get from db\n\nTimeSpan ts = dt - new DateTime(1,1,1970); // off the top of my head, check order of params\n\nlong ticks = ts.TotalTicks; // again off the top of my head, check property name	0
652999	652978	Parameterized Query for MySQL with C#	private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = @param_val_1 AND VAL_2 = @param_val_2;";\npublic bool read(string id)\n{\n    level = -1;\n    MySqlCommand m = new MySqlCommand(readCommand);\n    m.Parameters.AddWithValue("@param_val_1", val1);\n    m.Parameters.AddWithValue("@param_val_2", val2);\n    level = Convert.ToInt32(m.ExecuteScalar());\n    return true;\n}	0
24688006	24687462	How to make an unbound POST action in webapi 2.2 odata	[HttpPost]\n[ODataRoute("RegisterNewUser")]\npublic IHttpActionResult InitializeUser(ODataActionParameters parameters)\n{\n    // code to save user to DB & initialize account information...\n    return Ok<User>(new User());\n}	0
9585824	9585715	Ordering with linq and integers with zeros at the end	List<PackCard> packCards = db \n  .PackCardEntities \n  .OrderBy(pc => pc.PackNumber) \n  .ThenBy(pc => pc.PickPosition == null) \n  .ThenBy(pc => pc.PickPosition) \n  .ToList() \n  .ToPackCards();	0
737226	737217	How do I adjust the brightness of a color?	Color c1 = Color.Red;\n    Color c2 = Color.FromArgb(c1.A,\n        (int)(c1.R * 0.8), (int)(c1.G * 0.8), (int)(c1.B * 0.8));	0
11771167	11771166	How do I get Dapper.Rainbow to insert to a table with AutoIncrement on SQLite?	public class ESVLIntegration\n{\n    public long? Id { get; set; }\n    public String ProcessId { get; set; }\n    public long UserId { get; set; }\n    public String Status { get; set; }\n    public DateTime StartDate { get; set; }\n    public DateTime EndDate { get; set; }\n    public String Operation { get; set; }\n    public String SNEquip { get; set; }\n    public String CardName { get; set; }\n    public String FilePath { get; set; }\n    public Boolean Processed { get; set; }\n}	0
6295169	6294948	Pull RSS Feeds From Facebook Page	var req = (HttpWebRequest)WebRequest.Create(url);\nreq.Method = "GET";\nreq.UserAgent = "Fiddler";\n\nvar rep = req.GetResponse();\nvar reader = XmlReader.Create(rep.GetResponseStream());\n\nSyndicationFeed feed = SyndicationFeed.Load(reader);	0
6804841	6798319	LINQ display previous date	var q = from c in context.Wxlogs\n               where\n               c.LogYear == year && c.LogMonth == mm && c.LogTime.Contains("08:59")\n               orderby c.LogDate2\n                let dm = EntityFunctions.AddDays(c.LogDate2, -1)\n                select new {dm, c.Rain_today};	0
18742602	18742430	Search Button in C# Database with access	private void Button1_Click(object sender, EventArgs e)\n{\n    this.CostumersBindingSource.Filter = "[ID]  = ' " + this.TextBox1.Text + "'";\n}	0
8506246	8504992	converting C to C#	[StructLayout(LayoutKind.Sequential)]\nunsafe struct SockAddr {\n    public ushort sa_family;\n    public fixed byte sa_data[14]; // Note: sizeof(char) == 2 in C#\n}\n\n[StructLayout(LayoutKind.Sequential)]\nunsafe struct SockAddr_In {\n    public short sin_family;\n    public ushort sin_port;\n    public In_Addr sin_addr;\n    public fixed byte sin_zero[8];\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct In_Addr {\n    public byte s_b1, s_b2, s_b3, s_b4;\n}\n\npublic static unsafe void CStyle() {\n    SockAddr s;\n    SockAddr* ps = &s;\n\n    SockAddr_In* psa = (SockAddr_In*)ps;\n\n    var inAddr = new In_Addr();\n\n    inAddr.s_b1 = 192;\n    inAddr.s_b2 = 168;\n    inAddr.s_b3 = 168;\n    inAddr.s_b4 = 56;\n    psa->sin_addr = inAddr;\n    Console.WriteLine("{0}.{1}.{2}.{3}", \n                       psa->sin_addr.s_b1, psa->sin_addr.s_b2, \n                       psa->sin_addr.s_b3, psa->sin_addr.s_b4);\n}	0
18236454	18236000	How to add dependency reference programmatically	EnvDTE80.DTE2 pEnv = null;\nType myType = Type.GetTypeFromProgID("VisualStudio.DTE.8.0");          \npEnv = (EnvDTE80.DTE2)Activator.CreateInstance(myType, true);\n\nSolution2 pSolution = (Solution2)pEnv.VS.Solution;\nProject pProject = pSolution.Projects[0];\npProject.References.Add(string referenceFilePath);	0
31681916	31681655	how do I validate a user input in a Textbox against a column from a SQL Server table	SqlConnection cnn = null;\n        SqlCommand cmd = null;\n        SqlDataAdapter sda = null;\n        DataTable Dt = new Datatable();\n\n        cnn = new SqlConnection(strConnectionString);\n        cmd = new SqlCommand("Select COLUMN FROM WHEREVER WHERE VALUE =@TextboxValue", cnn);\n        cnn.Open();\n        cmd.CommandType = CommandType.Text;\n        cmd.Parameters.Add("@TextboxValue", SqlDbType.VarChar).Value = Textbox.Text;\n        sda = new SqlDataAdapter(cmd);\n        sda.Fill(dt);\n\n       if (dt.rows.count > 0 ) \n        {\n           //MATCH FOUND\n        }	0
25665198	25665042	Enum in Read from Database	(EnBranche) Enum.Parse(typeof(EnBranche),\n                       dataSet.Tables["Firmen"].Rows[i].ItemArray[5].ToString())	0
6805765	6805685	How to loop for controls, in multi user controls?	UserControl[] ucs = new UserControl[3]{\n         usercontrol1,\n         usercontrol2,\n         usercontrol3\n   };\n   foreach (UserControl uc in ucs){\n        foreach (Control c in uc.FindControl("PnlTab1").Controls)\n        {\n            if (c is TextBox)\n                ((TextBox)c).Enabled = true;\n        }\n   }	0
2658195	2658187	How can i return abstract class from any factory?	static Dictionary<DataModelType, Func<object>> s_creators =\n    new Dictionary<DataModelType, Func<object>>()\n    {\n        { DataModelType.Radyoloji,  () => new Radyoloji() },\n        { DataModelType.Company,    () => new Company() },\n        { DataModelType.Muayene,    () => new Muayene() },\n        { DataModelType.Satis,      () => new Satis() },\n    };	0
25213291	25211912	Reading nodes in xml using xpath query	NameTable nt = new NameTable();\nXmlNamespaceManager nsmgr;\nnsmgr = new XmlNamespaceManager(nt);\n\nstring strURI = "www.google.com"; // the default namespace, must match your doc.\nnsmgr.AddNamespace("g", strURI);  // add your own prefix (anything you want really)\n\n// Query with the "g" prefix, that you just defined.\nXmlNode ndNode = doc.SelectSingleNode("//g:Person", nsmgr);	0
12285862	12268873	Efficient way to both filter and replace by regex	void AddToIfMatch(List<string> list, string str; Regex regex; \n                                        MatchEvaluator evaluator)\n{\n    bool hasBeenEvaluated = false;\n    string str2 = regex.Replace(\n        str, \n        m => {HasBeenEvaluated = true; return evaluator(m);}\n    );\n    if( hasBeenEvaluated ) {list.Add(str2);}\n}	0
6564413	6564379	Select Multiple items in listbox in wpf using c#	MyListBox.SelectedItems.Add(item1);\nMyListBox.SelectedItems.Add(item2);\n.....	0
8657586	8657033	how can I use singleton or a static instance for my global website settings	//sample code\npublic sealed class BaseWebPage : Page\n{\nstatic BaseWebPage instance=null;\nstatic readonly object padlock = new object();\n\nBaseWebPage()\n{\n}\n\npublic static BaseWebPage Instance\n{\n    get\n    {\n        if (instance==null)\n        {\n            lock (padlock)\n            {\n                if (instance==null)\n                {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n}	0
7817091	7816730	Running privoxy with C# ProcessStartInfo	static void StartPrivoxy(Process p)\n    {\n        p.StartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Privoxy\privoxy.exe");\n        p.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\Privoxy\";\n        p.Start();\n    }	0
4637	4629	How can I read the properties of a C# class dynamically?	String propName = "Text";\nPropertyInfo pi = someObject.GetType().GetProperty(propName);\npi.SetValue(someObject, "New Value", new Object[0]);	0
7065951	7065910	Select a specific range of elements?	var doc = XDocument.Parse(xml);\n\nvar result = doc.Element("urlset").Elements("url")\n    .SkipWhile(x => x.Element("loc").Value != "e2")\n    .TakeWhile(x => x.Element("loc").Value != "e4");	0
32241568	32241499	C# How Can I Convert String Into If Else Conditioning	if(Convert.ToInt32(txt_payment.Text) < dr["ending_balance"]){\n      MessageBox.Show("The Payment Is Greater Than Ending Balance");	0
374392	367966	How to intercept debugging information ( Debugview style ) in C#?	MDbgEngine mg;\n MDbgProcess mgProcess;\n try\n {\n       mg = new MDbgEngine();\n       mgProcess = mg.Attach(debugProcess.Id);\n }\n catch (Exception ed)\n {\n       Console.WriteLine("Exception attaching to process " + debugProcess.Id );\n       throw (ed);\n }\n mgProcess.CorProcess.EnableLogMessages(true);\n mgProcess.CorProcess.OnLogMessage += new LogMessageEventHandler(HandleLogMessage);\n mg.Options.StopOnLogMessage = true;\n mgProcess.Go().WaitOne();\n bool running = true;\n Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n  while (running)\n   {\n       try\n       {\n           running =mgProcess.IsAlive;\n           mgProcess.Go().WaitOne();\n        }\n        catch\n         {\n            running = false;\n         }\n     }	0
20697925	20697686	Add 10 months automatically to textbox2 based on user selected date in textbox1	DateTime add_Months = Convert.ToDateTime(textbox1.Text).AddMonths(10);\ntextbox2.Text = add_Months.ToString();	0
3210034	3210010	How to calculate free disk space?	using System;\nusing System.IO;\n\nclass Test\n{\n    public static void Main()\n    {\n        DriveInfo[] allDrives = DriveInfo.GetDrives();\n\n        foreach (DriveInfo d in allDrives)\n        {\n            Console.WriteLine("Drive {0}", d.Name);\n            Console.WriteLine("  File type: {0}", d.DriveType);\n            if (d.IsReady == true)\n            {\n                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);\n                Console.WriteLine("  File system: {0}", d.DriveFormat);\n                Console.WriteLine(\n                    "  Available space to current user:{0, 15} bytes", \n                    d.AvailableFreeSpace);\n\n                Console.WriteLine(\n                    "  Total available space:          {0, 15} bytes",\n                    d.TotalFreeSpace);\n\n                Console.WriteLine(\n                    "  Total size of drive:            {0, 15} bytes ",\n                    d.TotalSize);\n            }\n        }\n    }\n}	0
24925966	24925472	Remove blank row from dataset	for (int i = dt.Rows.Count - 1; i >= 0; i--)\n{\n    if (dt.Rows[i]["col1"] == DBNull.Value && dt.Rows[i]["col2"] == DBNull.Value)\n     {\n        dt.Rows[i].Delete();\n     }\n}\ndt.AcceptChanges();\nds.Tables.Add(dt);\nreturn ds;	0
344811	344741	How do I Create an Expression Tree by Parsing Xml in C#?	using System.Linq.Expressions; //in System.Core.dll\n\nExpression BuildExpr(XmlNode xmlNode)\n { switch(xmlNode.Name)\n    { case "Add":\n       { return Expression.Add( BuildExpr(xmlNode.ChildNodes[0])\n                               ,BuildExpr(xmlNode.ChilNodes[1]));\n       } \n\n      /* ... */\n\n    }\n }	0
16154116	16153628	LINQ - Speeding up query that has a join to a huge table	var expiredAccounts = (from x in ExpiredAccount\n                       select x.Account.AccountName).ToList()	0
2117027	2117015	string output to html formatting problem	string feedImage ="http://im.media.ft.com/m/img/rss/RSS_Default_Image.gif"\nrssImageStyle = "style=\"background-image:url('" + feedImage + "')\"";	0
14420659	14420603	Display downtime page when publishing application	app_offline.htm	0
7552122	7348644	Android: How can I port ExecuteScalar to Java?	public int ExecuteScalar(/* code...*/) {\n    Cursor cursor = database.rawQuery(sql, selectionArgs);\n    try {\n        cursor.moveToNext();\n        int val = cursor.getInt(0);\n        cursor.close();\n        return val;\n    }   \n    catch (Exception e) {\n        /* code...*/\n    }\n    return -1;\n}	0
15168805	15168386	Serialize XML to File causing malformations?	using (XmlTextWriter myWriter = new XmlTextWriter(ms, new System.Text.UTF8Encoding(false)))\n        {\n            myWriter.Flush();\n            //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\"");\n            ser.Serialize(myWriter, myCCR);\n        }	0
22144603	22013611	Read a record selected in DataGridView table and read through info of that record into fields that is not shown in the table	byte[] Rec = new byte[1024];\nFileInfo file_info = new FileInfo(import.FileName);\nlong a = file_info.Length;\nint rec_num_to_read = Dgv.CurrentRow.Index + 1;\n\nusing (FileStream Fs = new FileStream(import.FileName, FileMode.Open, FileAccess.Read))\nusing (BinaryReader Br = new BinaryReader(Fs))\n{\n    while ((a = Br.Read(Rec, 0, 1024)) > 0)\n    {\n        Fs.Seek(rec_num_to_read * 1024, SeekOrigin.Begin); // I moved this out of the foreach loop\n\n        foreach (var rec in Rec)\n        {\n            Label_Product1.Text = DecodeString(Rec, 3, 12);\n            // Some more info to decode\n        }\n    }\n}	0
15439696	15419700	User Master Account to send SMS on behalf of a Sub Account	var twilio = new TwilioRestClient("Master SID", "Master Auth Token");\n        var subAccount = twilio.GetAccount("SubAccount SID");\n        var subAccountClient = new TwilioRestClient(subAccount.Sid, subAccount.AuthToken);\n        var response = subAccountClient.SendSmsMessage(sender, recipient.ConvertToE164Format(), message);\n\n        return response.Sid;	0
19158341	19158249	remove item from a list	var toRemove = cardList.SingleOrDefault(c => c.Name == mycard.Name);\nif (toRemove != null) cardList.Remove(toRemove);	0
12427516	12427455	Split servervariables user_logon	var numbers = user_logon.Split("\\")[1];	0
7901948	7901751	C# WPF - Adorner ZIndex	Panel.SetZIndex(ad, 20)	0
4979795	4979693	Converting template content to color overlay	sampler2D Texture1Sampler : register(S0);\n\n//-----------------\n// Pixel Shader\n//-----------------\n\nfloat4 main(float2 uv : TEXCOORD) : COLOR\n{\n    float4 color = tex2D( Texture1Sampler, uv );\n    float4 alphaMaskColor = float4(color.a,color.a,color.a,color.a); //Pre-multiplied Alpha in WPF\n    return alphaMaskColor;\n}	0
21623803	21623761	Load a RPT file into C# windows service	rd.Load(AppDomain.CurrentDomain.BaseDirectory+(@"..\Reports\InvoiceDocument.rpt"));	0
24353811	24353757	Creating a void for the event "SelectionChangeCommitted" for a ComboBox array	private void cmbALL_SelectionChangeCommitted(object sender, EventArgs e)\n{\n    ComboBox thisOne = (ComboBox)sender;\n    //Code...\n}	0
2047697	2047631	Find a specific class in a file using reflection?	string path = "INSERT PATH HERE";\n\nvar assembly = Assembly.LoadFile(path);\nforeach (var type in assembly.GetTypes())\n{\n    Debug.WriteLine(type.Name);\n\n    // do check for type here, depending on how you wish to query\n}	0
9716191	9716065	How to remove a certificate Store added by makecert	crypt32.dll	0
7068256	7068084	How can I use backgroundworker in my browser?	// add progress bar\n        private ProgressBar progressBar1;\n\n\n        //create event for ProgressChanged \n        Browser.ProgressChanged += Browser_ProgressChanged;\n        ...\n\n        // set progress bar value when ProgressChanged event firing \n        void Browser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e) {\n        if (e.MaximumProgress > 0) {\n            int prog = (int)(100 * e.CurrentProgress / e.MaximumProgress);\n            progressBar1.Value = prog;\n        }\n    }	0
18964391	18964370	Converting ticks to DateTime	static readonly DateTime _unixEpoch =\n    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n\npublic static DateTime DateFromTimestamp(long timestamp)\n{\n    return _unixEpoch.AddSeconds(timestamp);\n}	0
24333344	24332780	How to trigger a Generic Class method recursively changing the type of T?	public static class MyGenericClass<T> where T : class\n{\n    public static T MyGenericMethod()\n    {\n    T o = (T)Activator.CreateInstance(typeof(T));\n    PropertyInfo[] pi = typeof(T).GetProperties();\n\n    for(int i = 0; i < pi.Count(); i++) \n    {\n        if(pi[i].Name == "MyClass2Property") \n        {\n            //How to proceed ?\n            Type t = typeof (MyGenericClass<>);\n            Type genericType = t.MakeGenericType(new System.Type[] { pi[i].PropertyType });\n            var c = Activator.CreateInstance(genericType);\n            dynamic mgm = Convert.ChangeType(c, genericType);\n            mgm.MyGenericMethod(); \n        }\n        else \n        {\n            pi[i].SetValue(o, Convert.ChangeType(someValue, pi[i].PropertyType), null);\n        }\n    }\n}	0
27013283	27013172	How to get what's in datatable where exist in another datatable by LINQ	var result = (from a in dt1.Rows\n             join b in dt2.Rows\n             on dt1.Rows["emp_num"]==dt2.Rows["emp_num"]\n             select a).CopyToDataTable<DataRow>();	0
19827174	19819769	Windows Phone 8 - Pass an argument to callback function	private void abcRenew_Click(object sender, EventArgs e)\n{\n    var api = new abcAPI();\n\n    Action<IAsyncResult> callback = asynchronousResult =>\n    {\n        /* Now `api` is in scope */\n    };\n\n    api.CallBack = new AsyncCallback(callback);\n    api.getNewAbc();\n}	0
17921343	8477843	Storing 2 columns into a List	List<string> [] list= new List<String> [];\nlist[0]=new List<string>();\nlist[1]=new List<string>();\n\nlist[0].add("hello");\nlist[1].add("world");	0
13382112	13381930	Linq query a string array in c# if contains either of two values?	if(!tmp.Select(x => x.Split('=')[0])\n                    .Intersect(new[] { "foo", "baz" }, \n                               StringComparer.InvariantCultureIgnoreCase).Any())\n    doSomething();	0
1627857	1623935	Load dll's from Environment Variable Path from a service	if isdeployed\n    addpath(ctfroot);\n    addpath(toolboxdir('signal'));\n    %more addpath(toolboxdir('toolboxname')) statements\nend	0
12951671	12951638	Replace string in file using a SQL procedure	try catch	0
13563691	13563343	Simple way to Export DataGridView to Excel	int cols;\n//open file \nStreamWriter wr = new StreamWriter("GB STOCK.csv");\n\n//determine the number of columns and write columns to file \ncols = dgvStock.Columns.Count;\nfor (int i = 0; i < cols - 1; i++)\n{ \n    wr.Write(dgvStock.Columns[i].Name.ToString().ToUpper() + ",");\n} \nwr.WriteLine();\n\n//write rows to excel file\nfor (int i = 0; i < (dgvStock.Rows.Count - 1); i++)\n{ \n    for (int j = 0; j < cols; j++)\n    { \n        if (dgvStock.Rows[i].Cells[j].Value != null)\n        {\n            wr.Write(dgvStock.Rows[i].Cells[j].Value + ",");\n        }\n        else \n        {\n            wr.Write(",");\n        }\n    }\n\n    wr.WriteLine();\n}\n\n//close file\nwr.Close();	0
6517177	6517143	inheritance - exercise	protected int [] arr;	0
29372939	4275984	How to convert decimal to string value for dollars and cents separated in C#?	double val = 125.79;\n double roundedVal = Math.Round(val, 2);\n double dollars = Math.Floor(roundedVal);\n double cents = Math.Round((roundedVal - dollars), 2) * 100;	0
12025295	12024958	Creating a video out of a set of images	//load the first image\nBitmap bitmap = (Bitmap)Image.FromFile(txtFileNames.Lines[0]);\n//create a new AVI file\nAviManager aviManager = \n    new AviManager(@"..\..\testdata\new.avi", false);\n//add a new video stream and one frame to the new file\nVideoStream aviStream = \n    aviManager.AddVideoStream(true, 2, bitmap);\n\nBitmap bitmap;\nint count = 0;\nfor(int n=1; n<txtFileNames.Lines.Length; n++){\n    if(txtFileNames.Lines[n].Trim().Length > 0){\n        bitmap = \n           (Bitmap)Bitmap.FromFile(txtFileNames.Lines[n]);\n        aviStream.AddFrame(bitmap);\n        bitmap.Dispose();\n        count++;\n    }\n}\naviManager.Close();	0
3317532	3279626	How to get EmailId from outlook in C#	public string GetEmaiId(string userId)\n    {\n        string email = string.Empty;\n        DirectorySearcher objsearch = new DirectorySearcher();\n        string strrootdse = objsearch.SearchRoot.Path;\n        DirectoryEntry objdirentry = new DirectoryEntry(strrootdse);\n        objsearch.Filter = "(& (cn=" + userId + ")(objectClass=user))";\n        objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;\n        objsearch.PropertiesToLoad.Add("cn");\n        objsearch.PropertyNamesOnly = true;\n        objsearch.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;\n        objsearch.Sort.PropertyName = "cn";\n        SearchResultCollection colresults = objsearch.FindAll();\n        foreach (SearchResult objresult in colresults)\n        {\n            email = objresult.GetDirectoryEntry().Properties["mail"].Value.ToString();\n        }\n        objsearch.Dispose();\n        return email;\n    }	0
13373075	13373051	How to read xml stream using c#?	[WebInvoke(UriTemplate = "UpdateFile/{id}", Method = "POST")]\npublic bool UpdateTestXMLFile(string id, Stream createdText)\n{\n   DataSet ds = new DataSet(); \n   ds.ReadXml(createdText)\n\n   string filenamewithpath = System.Web.HttpContext.Current.Server.MapPath(@"~/files/" + id+".xml");\n   ds.WriteXml(filenamewithpath);      \n}	0
34264414	34261249	NEST elastic search: how to return certain fields along with aggregated results?	var result = esClient.Search<EType>(q => q\n    .Index(esClient.Index)\n    .Routing(id.ToString(CultureInfo.InvariantCulture)\n    .Aggregations(agHash => agHash\n        .Terms("Hash", eeHash => eeHash\n            .Field(fHash => fHash.hashValue)\n        .Aggregations(agType => agType\n            .Terms("Types", eeType => eeType\n                .Field(fType => fType.typeValue))))));	0
25524980	25516499	ILNumerics: Get mouse coordinates with ILLinePlot	ILGroup plotcubeGroup = e.Target as ILGroup;\n ILGroup group = plotcubeGroup.Children.Where(item => item.Tag == "LinePlot").First() as ILGroup;\n if(group != null)\n    {\n    // continue with same logic as above\n    }	0
12185963	12185799	WatiN - working with WatIn in winForm	Settings.AutoStartDialogWatcher = false;\nvar ie = new IE(webBrowser1.ActiveXInstance);\nie.GoTo("http://www.google.com");	0
2208704	2208604	Binding excel file to datagridview	OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c://Org.xls;Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;" + (char)34);\n    DataSet myExcelData=new DataSet();\n\n    conn.Open();\n\n    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [Sheet1$]", conn);\n    myDataAdapter.Fill(myExcelData);\n\n    ultraGrid1.DataSource = myExcelData;\n\n    conn.Close();	0
21306993	21305889	Grouping a range using linq	var result = prices.GroupBy(x => x.Price < 10 ? "0-10" \n                                              : x.Price < 20 ? "10-20" : ">20")\n                   .Select(g => new { g.Key, g }	0
33891999	33891866	c# show underscore _ in date instead of dash -	String.Format("{0}_{1:yyyy_MM_dd}", "filename", DateTime.Now);	0
608738	608732	What is the simplest way to validate a date in asp.net C#?	DateTime.TryParse();	0
10027359	10027339	Converting Xml To String.New Line per tag?	XmlTextWriter xmlTextWriter = new XmlTextWriter("file.xml",null);    \nxmlTextWriter.Formatting = Formatting.Indented;	0
18894187	18857981	Problems with running Sybase SQL Script from C# - too many parameters	;Named Parameters=false	0
259987	259883	strip out tag occurrences from XML	var elements = doc.Descendants("RemovalTarget").ToList().Reverse();\n/* reverse on the IList<T> may be faster than Reverse on the IEnumerable<T>,\n * needs benchmarking, but can't be any slower\n */\n\nforeach (var element in elements) {\n    element.ReplaceWith(element.Nodes());\n}	0
8408061	8407549	Enable logging to two different locations in log4net	private  ILog Log  {\n    get {\n        if (!_ConfiguratorSet) {\n            _ConfiguratorSet = true;\n            XmlConfigurator.Configure(new FileInfo(_ConfigFile)); //<--- STATIC\n        }\n        return _log;\n    }\n}	0
2802827	2802387	C#: Populating a UI using separate threads	private delegate IList<MyObject> PopulateUiControl();\n\nprivate void myThread_DoWork(object sender, DoWorkEventArgs e) {\n    PopulateUiControl myDelegate = FillUiControl;\n\n    while(uiControl.InvokeRequired)\n        uiControl.Invoke(myDelegate);\n}\n\nprivate IList<MyObject> FillUiControl() {\n    uiControl.Items = myThreadResultsITems;\n}	0
25691041	25690867	Iterating json from a certain key	Debug.WriteLine(((object)a.First["synonym"]).ToString());	0
27227234	27227125	Where can I find all tables used in ManagementObjectSearcher in win32 API	ManagementObjectSearcher wmi = new ManagementObjectSearcher\n    ("SELECT * FROM meta_class WHERE __CLASS LIKE 'Win32_%'");\nforeach (ManagementObject obj in wmi.Get())\n    Console.WriteLine(obj["__CLASS"]);	0
11038866	11038703	c# regex parse file in ical format and populate object with results	string line = "LAST-MODIFIED:20120504T163940Z";\nvar p = Regex.Match(line, "(.*)?(:|;)(.*)$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Singleline);\nConsole.WriteLine(p.Groups[0].Value);\nConsole.WriteLine(p.Groups[1].Value);\nConsole.WriteLine(p.Groups[2].Value);\nConsole.WriteLine(p.Groups[3].Value);	0
22487661	22487326	Getting ValueMember from selected item in a ListBox with C#	foreach (var item in listBox1.SelectedItems) {\n  MessageBox.Show("ID = " + ((DataRowView)item)["people_id"].ToString());\n}	0
2986842	2986779	Resize Access Database Column/Field Programmatically with C#	CurrentDb.Execute "ALTER TABLE YourTable ALTER COLUMN YourTextField TEXT(20);"	0
27564136	27563940	Find value within gridview column	bool found = false;\nforeach(GridViewRow row in GridView1.Rows)\n{\n   TableCell cell = row.Cells[1];\n   if(cell.Text.Contains("Live"))\n   {\n      found = true;\n      break;\n   }\n}\n\nif(found)\n{\n    GridView1.Columns[2].Visible = true;\n}	0
27054234	27053536	Set database connection string at run time	DataContext myContext = new DataContext(customConnectionString);	0
7198892	7198878	how to distingish between local and static variables of same name	Something.number	0
14456796	14456620	How do I stop [ ] appearing when inserting the value of a KeyValuePair<string, string> into a list control?	var aoObjectArray = new Dictionary<string, string>();\naoObjectArray["A1"] = "Warehouse";\naoObjectArray["A2"] = "Front Office";\naoObjectArray["A3"] = "Developer Office";\n\nforeach (KeyValuePair<string, string> oTemp in aoObjectArray)\n{\n    ((ComboBox)listControl).Items.Add(string.Format("{0} - {1}", oTemp.Key, oTemp.Value));\n}	0
33155158	33057518	How do I prevent code from modifying the browser history?	AutoPostBack="false"	0
14544815	14544795	Differencing Two String Lists in C#	List<string> DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase)).ToList();	0
16920047	16919994	Format for a timer in AJAX C#	CurrentDateTime.Text = DateTime.Now.ToString("dddd, MMMM d HH:mm:ss");	0
34309169	34309111	How do create a join by using linq?	public List<Image> GetImagesInfo(int tradeItemId)\n    {\n        var query = (from item in _db.ImagesOnTradeItems\n                     join image in _db.Images on item.imageId equals image.id\n                     where item.tradeItemId == tradeItemId\n                     select image);\n        return query.ToList();\n    }	0
6773454	6773442	How can I parse a date like 07/21/2011 23:59:59 in c#	CultureInfo provider = CultureInfo.InvariantCulture;\nDateTime.ParseExact("07/21/2011 23:59:59","MM/dd/yyyy HH:mm:ss",provider)	0
20949974	20949569	not able to read xml in C# xml to linq	XNamespace ns = "http://www.w3.org/2005/Atom";\nvar posts = (from p in rssFeed.Root.Elements(ns + "entry")\n             select new\n             {\n                 Title = p.Element(ns + "title").Value,\n                 Link = p.Element(ns + "link").Value,\n             }).ToList();\n\nforeach (var post in posts)\n{\n    Console.WriteLine(post.Title);\n}	0
9210623	9210305	Combining Lambda Expressions	System.Linq.Expressions.BinaryExpression binaryExpression =\n  System.Linq.Expressions.Expression.MakeBinary(\n    System.Linq.Expressions.ExpressionType.AndAlso,\n    firstExpression,\n    secondExpression);	0
3367713	3164655	nhibernate auditing with events on update	public override bool OnFlushDirty( object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types )\n{\n    bool result = false;\n\n    if (entity is IAuditable) {\n        var auditable = (IAuditable)entity;\n\n        Set( x => auditable.Modifier, propertyNames, auditable, currentState, SecurityManager.Identity );\n        //Set( x => auditable.DateModified, args.Persister, auditable, args.State, TwentyClock.Now );\n\n        result = true;\n    }\n\n    return result;\n}	0
7655240	7654930	Cross Postback from Masterpage	TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");	0
19668914	19668784	How to calculate the age getting data from a GridView	DateTime brithday;\n            DataGridViewColumn col = new DataGridViewColumn();\n            col.HeaderText = "Age";\n            col.Name = "ageBoD";\n            col.CellTemplate = new DataGridViewTextBoxCell();\n            int column = dataGridViewX1.Columns.Count;\n            dataGridViewX1.Columns.Insert(column, col);\n\n            for (int i = 0; i < dataGridViewX1.Rows.Count; i++)\n            {\n                brithday = Convert.ToDateTime(dataGridViewX1[3, i].Value);\n                dataGridViewX1[column, i].Value = brithday.Year - DateTime.Now.Year;\n            }	0
3759353	3759322	Can we implement interface without overriding some of its method.I heard this is possible in some cases	interface IFoo\n{\n    void Bar();\n}\n\nclass Parent\n{\n    public void Bar() {}\n}\n\nclass Child : Parent, IFoo {}	0
15163715	15163394	Retrieve date of the prior Tuesday	var yesterday = DateTime.Now;\n\nwhile(yesterday.DayOfWeek != DayOfWeek.Tuesday) {\n  yesterday = yesterday.AddDays(-1);\n}	0
16056737	16056346	Lable control in argument	private void updateStatus(string massageText, System.Windows.Forms.Control control)\n{\n    txtStatus.Text = massageText;\n    control.BackColor = Color.Red;\n }	0
4096004	4095924	What tools do I need to make a GIS/GPS Navigation Software by C#	public bool SendGpsMessage(string GPSSentence)	0
18723735	18723590	How to convert foreach loop to a Linq query?	var gift = Convert.ToDouble(\n               gifts.Cast<List<object>>().First(x => x[0] == planYear)[1]);	0
19675218	19675179	Get refined set using Linq	var final = sampleDataGroups.Where(p => p.Description.Equals("Test1"));	0
25417785	25417658	How can I inherit all of the properties and controls along with the code from a previously created form?	public partial class Form2 : Form1\n{\n    public Form2()\n    {\n        InitializeComponent();\n    }\n}	0
21503940	21503661	converting nested XML to 3d array	int[][][] result = xDoc\n    .Root\n    .Elements("player")\n    .Select(p => p\n        .Elements("levels")\n        .Elements("level")\n        .Select(l => l\n            .Elements()\n            .Select(e => int.Parse(e.Value))\n            .ToArray()\n        ).ToArray()\n    ).ToArray();	0
25160369	25160261	How do I set a string to an attribute value in an xml file?	ID = xmlNodeComplex.ParentNode.Attribute["ID"].Value;	0
22413300	22413175	programmatically detect current git branch checked out from C# code	new FileRepository (some dir).getBranch ()	0
24385963	24365228	Pass a local variable to CodeMethodInvokeExpression in workflow foundation	codeMethodInvokeExpression.Parameters.Add(new CodePrimitiveExpression(error));	0
3880395	3880339	How to tell if calling assembly is in DEBUG mode from compiled referenced lib	IsAssemblyDebugBuild(Assembly.GetCallingAssembly());\n\nprivate bool IsAssemblyDebugBuild(Assembly assembly)\n{\n    foreach (var attribute in assembly.GetCustomAttributes(false))\n    {\n        var debuggableAttribute = attribute as DebuggableAttribute;\n        if(debuggableAttribute != null)\n        {\n            return debuggableAttribute.IsJITTrackingEnabled;\n        }\n    }\n    return false;\n}	0
7532079	7531977	Using Regex to replace a specific string occurrence but ignore others based on neighboring characters	string pattern = @"(?<=^|\s)15\(1\)(?=\s|$)";\nstring result = Regex.Replace(input, pattern, "15");\nConsole.WriteLine(result);	0
8839314	8839190	Changing one picture to another onclick in vb.net	Dim OldImage As Image\n\nPrivate Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click\n    OldImage = PictureBox1.Image 'This will store the image before changing. Set this in Form1_Load() handler\n\n    PictureBox1.Image = Image.FromFile("C:\xyz.jpg") 'Method 1 : This will load the image in memory\n    PictureBox1.ImageLocation = "C:\xyz.jpg" 'Method 2 : This will load the image from the filesystem and other apps won't be able to edit/delete the image\n    PictureBox1.Image = My.Resources.Image 'Method 3 : This will also load the image in memory from a resource in your appc\n\n    PictureBox1.Image = OldImage 'Set the image again to the old one\nEnd Sub	0
14931584	14417516	What settings on Exchange do we need to check to avoid a ServiceRequestException from being thrown?	ServicePointManager.ServerCertificateValidationCallback = this.CertificateValidationCallBack;\nExchangeService exchangeWebService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);\n\nexchangeWebService.Credentials = new WebCredentials("username@domain.local", "myPassword");\nexchangeWebService.AutodiscoverUrl("username@domain.com", this.RedirectionUrlValidationCallback);\n\nCalendarFolder calendarFolder = CalendarFolder.Bind(exchangeWebService, new FolderId(WellKnownFolderName.Calendar, "username@domain.com"));	0
30046454	30046136	Linq to join two lists and filter using a value of inner list value	var searchByPhone = new List<Tuple<string,string>>();\nsearchByPhone.Add(Tuple.Create("12324344", "message one"));\nsearchByPhone.Add(Tuple.Create("45646565", "message two"));\nsearchByPhone.Add(Tuple.Create("56868675", "message three"));\n\n//you should already have this list populated somehow, i'm declaring it here just for the sake of making the code compile\nvar clientlist = new List<Client>();\n\n//this list will hold your results\nList<ClientObject> resultList = new List<ClientObject>();\n\n\nsearchByPhone.ForEach(tp => resultList.AddRange(\n                clientlist.Where(cl => cl.phones.Any(ph=>ph.phoneno == tp.Item1)).Select(cl => new ClientObject {id = cl.id, firstname = cl.firstname, lastname = cl.lastname, message = tp.Item2, phonenumber = tp.Item1}).ToList()));	0
16164618	16163860	What's with instantiating from a type parameter T not allowing constructor aguments?	Func<string, T>	0
6411404	6411218	How to create instance by string Array?	System.Reflection.Assembly assem = Assembly.Load("");\n\nobject thisObj = assem.CreateInstance("Customers");\nforeach (PropertyInfo pi in thisObj.GetType().GetProperties)\n{\n   // List all properties in object \n   ...\n}	0
12131577	12131548	how to Check if a XML child element exists with Linq to XML	bool b = xdocument.Descendants("IncomingConfig").Any();	0
8255429	8254809	How to parse JSON string that can be one of two different strongly typed objects?	public static object test(string inputString)\n    {\n        object obj = null;\n        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(inputString)))\n        {\n            try\n            {\n                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ASErrorResponse));\n                obj = ser.ReadObject(ms) as ASErrorResponse;\n            }\n            catch (SerializationException)\n            {\n\n            }\n        }\n\n        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(inputString)))\n        {\n            try\n            {\n                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ASResponse));\n                obj = ser.ReadObject(ms) as ASResponse;\n            }\n            catch (SerializationException)\n            {\n\n            }\n        }\n\n        return obj;\n    }	0
32457913	32457452	How to Copy a table from MS Access and Change in .txt or other format?	StringBuilder result = new StringBuilder();\n //write columns\n    for (int i = 0; i < dt.Columns.Count; i++)\n    {\n        result.Append(dt.Columns[i].ColumnName);\n        if(i == dt.Columns.Count - 1)\n        {\n        result.Append("\n");\n        }\n        else\n        {\n        result.Append(",");\n        }\n\n    }\n     //write rows       \n    foreach (DataRow row in dt.Rows)\n    {\n        for (int i = 0; i < dt.Columns.Count; i++)\n        {\n            result.Append(row[i].ToString());\n           if(i == dt.Columns.Count - 1)\n           {\n            result.Append("\n");\n           }\n           else\n           {\n           result.Append(",");\n           }\n        }\n    }\n\n    //write result to a file        \n   StreamWriter file = new StreamWriter(@"your file");\n   file.WriteLine(result.ToString());	0
10505527	10505428	Selecting rows from IEnumerable based on a percentage	var rows = repository.GetRows(100);\n\nrows.OrderBy(Guid.NewGuid()).Take(25).ToList().ForEach(m => task1.Run(m));\nrows.OrderBy(Guid.NewGuid()).Take(50).ToList().ForEach(m => task2.Run(m));\nrows.ToList().ForEach(m => task3.Run(m));	0
30785321	30785106	Find each string in a list from a table column	var regex = new Regex("string one|string two|string three|...|string one thousand");	0
2855324	2855245	Abstract base class to force each derived classes to be Singleton	public abstract class Singleton\n{\n    private static readonly object locker = new object();\n    private static HashSet<object> registeredTypes = new HashSet<object>();\n\n    protected Singleton()\n    {\n        lock (locker)\n        {\n            if (registeredTypes.Contains(this.GetType()))\n            {\n                throw new InvalidOperationException(\n                    "Only one instance can ever  be registered.");\n            }\n            registeredTypes.Add(this.GetType());\n        }\n    }\n}\n\npublic class Repository : Singleton\n{\n    public static readonly Repository Instance = new Repository();\n\n    private Repository()\n    {\n    }\n}	0
31869424	31868005	How to get column header with non empty data in row?	DataTable dt = new DataTable();\nforeach (DataGridViewColumn col in dataGridView1.Columns)\n{\n    bool empty = false;\n    foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n        if (row.Cells[col.Index].Value.ToString() == string.Empty)\n        {\n             empty = true;\n        }\n        break;\n    }\n    if (empty == false)\n    {\n        dt.Columns.Add(col.HeaderText);\n    }\n}	0
23216012	23215491	Exiting from timer based polling loop	static readonly ManualResetEvent reset = new ManualResetEvent(false);\n\nstatic void Main(string[] args)\n{\n    var t = new Timer(TimerCallback, null, -1, 1000);\n    t.Change(0, 1000);\n    reset.WaitOne(); // the application will sit here until the timer tells it to continue.\n}\n\nprivate static void TimerCallback(object state)\n{\n    try\n    { \n       // do stuff.\n    }\n    catch (Exception e)\n    {\n        failureCounter++;\n        if (failureCounter > 5)\n        {\n            reset.Set(); // release the reset event and the application will exit,\n            return;\n        }\n    }\n}	0
32577941	32569373	Remove a SIP address from user via exchange	string idTermEmail = "sip:" + txtTermFirstName.Text + "." + txtTermLastName.Text + "@domain.com";\n\n\n        PSCommand command3 = new PSCommand();\n        command3.AddCommand("Set-Mailbox");\n        command3.AddParameter("Identity", username);\n\n        var sipAddress = new Hashtable();            \n\n        sipAddress.Add("remove", idTermEmail);\n        command3.AddParameter("EmailAddresses", sipAddress);\n\n        powershell.Commands = command3;\n        powershell.Invoke();	0
6354113	6354091	how to get the integer value of an enum, when i only have the type of the enum	private TypeValues GetEnumValues(Type enumType, string description)\n        {\n            TypeValues wtv = new TypeValues();\n            wtv.TypeValueDescription = description;\n            List<string> values = Enum.GetNames(enumType).ToList();\n            foreach (string v in values)\n            {\n                //how to get the integer value of the enum value 'v' ?????\n\n               int value = (int)Enum.Parse(enumType, v);\n\n                wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v });\n            }\n            return wtv;\n\n        }	0
27364247	27363744	How to write name of the file's owner to the file using c#?	File.Copy(@"1.txt", @"2.txt", true);\nstring userName = System.IO.File.GetAccessControl(@"1.txt").GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();\nvar fs = File.GetAccessControl(@"2.txt");\nvar ntAccount = new NTAccount("DOMAIN", userName);\nfs.SetOWner(ntAccount);\n\ntry {\n   File.SetAccessControl(@"2.txt", fs);\n} catch (InvalidOperationException ex) {\n   Console.WriteLine("You cannot assign ownership to that user." +\n    "Either you don't have TakeOwnership permissions, or it is not your user account."\n   );\n   throw;\n}	0
24871425	24871375	C# method implementation with dot notation	public class SampleClass : IControl, ISurface\n{\n    void IControl.Paint()\n    {\n        System.Console.WriteLine("IControl.Paint");\n    }\n    void ISurface.Paint()\n    {\n        System.Console.WriteLine("ISurface.Paint");\n    }\n}	0
3186345	3185868	Retrieving values from fckeditor in code behind in c#	var abcd = [[nameOfEditor]].Value;	0
761070	761003	Draw a single pixel on Windows Forms	e.Graphics.FillRectangle(aBrush, x, y, 1, 1);	0
24830160	24830027	Issue with converting DOC to PNG	Image image = Image.FromStream(ms);\n Bitmap myBitmap = new Bitmap( image, new Size( 320,480 ) ); \n myBitmap.Save( "MyImage.png", System.Drawing.Imaging.ImageFormat.Png );	0
15315874	15315671	How can I modify a custom xml node	public class Foo {\n  private string _bar;\n  public string Bar \n  {\n    get { return String.IsNullOrEmpty(_bar) ? _bar = "default value" : _bar; }\n    set { _bar = value; }\n  } \n}	0
28012837	28012688	DispatcherTimer loses time while I'm dragging its Window	DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Render);	0
1120238	1120228	How to dynamically call a class' method in .NET?	using System;\nusing System.Reflection;\n\nclass Program\n{\n    static void Main()\n    {\n    caller("Foo", "Bar");\n    }\n\n    static void caller(String myclass, String mymethod)\n    {\n    // Get a type from the string \n    Type type = Type.GetType(myclass);\n    // Create an instance of that type\n    Object obj = Activator.CreateInstance(type);\n    // Retrieve the method you are looking for\n    MethodInfo methodInfo = type.GetMethod(mymethod);\n    // Invoke the method on the instance we created above\n    methodInfo.Invoke(obj, null);\n    }\n}\n\nclass Foo\n{\n    public void Bar()\n    {\n    Console.WriteLine("Bar");\n    }\n}	0
1852632	1852618	How can I make this lambda work?	this.Invoke(new Action(() => txtForm.Rtf = temp))	0
23697108	23688579	List of files within a folder, within a list in SharePoint 2010 through its ASMX web services	Microsoft.Sharepoint.Client	0
24730112	24730079	i need to get string format data in a file as it is	string str = ((char)fileOperation.ReadByte()).ToString();\n Console.Write(str + "");	0
23013904	23013876	How to implement interface in successor	class Student : Human, IComparable<Student>	0
10116954	10116919	Serial Port Buffer / Baud Rate / Lost data	serialPort.WriteTimeout = 500;	0
22957505	22957336	Loop through list of ints from database	foreach (var item in _ad)\n{\n    if (item.BehandlingarId == id)\n    {\n        return View();\n    }\n}	0
25604662	25604404	Passing the results from multiple stored procedures to a view	public class VehicleViewModel\n{\n    public ICollection<VehicleModel> VehicleModels { get; set; }\n}\n\npublic ActionResult Vehicles(int? makeId, int? countryId)\n{\n    if(!makeId.HasValue || !countryId.HasValue)\n    {\n        RedirectToAction("Error");\n    }\n\n    var models = db.spVehicleGetModels(makeId, false, true, countryId);\n    var viewModel = new VehicleViewModel { VehicleModels = models.ToList() };\n    return View(viewModel);\n}	0
11269110	11268928	Delete Where NOT in Clause - Linq-To-SQL	db.accounts.Where(x => !ListIDs.Contains(x.ID))	0
16000416	15820806	Issue with a manually instantiated SessionState provider	object storeLockId = new object();\nsessionStateContainer.Add("SomeKey", "SomeValue");\nvar test = sessionStateContainer["SomeKey"];\nConsole.WriteLine("var test: " + test.ToString());\n\nsessionState.Add("AnotherKey", "SomeOtherValue");\nvar test2 = sessionState["AnotherKey"];\nConsole.WriteLine("var test2: " + test2.ToString()); \n\n// End the request\nprovider.SetAndReleaseItemExclusive (context, sessionStateContainer.SessionID, \n                                     storeData, storeLockId, true);\nprovider.EndRequest(context);	0
14586144	14585709	Openning a URL containing a query string	Process.Start(new ProcessStartInfo("explorer.exe", "\"" + @"http://www.google.com/search?q=stackoverflow" + "\""));	0
10756358	10756295	How change name of contextMenuStrip item	contextMenuStrip.Items[0].Text = "your-text-here";	0
10917194	10916186	Get not regular XML values	gpsResponseXML.Descendants("Property").Where(el => el.Attribute("Name").Value == "X").Attributes("Value").FirstOrDefault().Value)	0
2195981	2195957	Convert DateTime to yyyyMMdd int	int x = date.Year * 10000 + date.Month * 100 + date.Day	0
23791007	23777906	How to get all album artists from KnownFolders.MusicLibrary storage folder?	KnownFolders.MusicLibrary.GetFoldersAsync(CommonFolderQuery.GroupByArtist);	0
18394536	18394461	C# finding the shortest and longest word in a array	string[] word = new string[5];\nfor (int i = 0;i<= word.length ; i++)\n            {\n\n               Console.WriteLine("Type in a word");\n                word[i] = Console.ReadLine();\n            }\n            int min = word[0].Length;\n            int max = word[0].Length;\n            string maxx="";\n            string minn="";\nfor (int i = 0; i<=word.length ; i++)\n            {\n              int length = word[i].Length;   \n              if (length > max)\n                 {\n                   maxx = word[i];\n\n                  }\n             if (length < min) \n              {\n                 minn = word[i];\n                Console.Write("Longest");\n              }\n\n\n\n         }\n  Console.Write("Shortest:"+maxx);\n  Console.Write("Longest"+minn);\n  Console.ReadKey(true);\n    }	0
30346005	30345846	Async in JScript	System.Threading.Tasks	0
13349153	13314725	Migrations in Entity Framework in a collaborative environment	Add-Migration M2	0
4481674	4481622	XDocument deleting a node	xdoc.Descendents("Snippet").Where(xe => xe.Attribute("name") != null \n    && xe.Attribute("name").Value == "foreach").Single().Remove()	0
28748066	27362714	Dynamically assign click event	private void MyAddin_Startup(object sender, EventArgs e) \n{\n    // setup event handlers\n    Application.SheetBeforeRightClick +=\n        MyRightClickFunction; \n}\n\nprivate void MyRightClickFunction(object sh, Excel.Range target, ref bool cancel)\n{\n    // 'target' is the cell or selected range clicked\n    ... \n}	0
31131733	31131630	Push Notification for Windows 8.1	var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();\nvar uri = channel.Uri	0
1534318	1534269	Keystroke combinations in c# winforms app	override void OnKeyDown( object sender, KeyEventArgs e )\n{\n    bool myKeysPressed = (e.KeyCode == Keys.A) &&\n                         ((e.Modifiers & Keys.Alt) == Keys.Alt) &&\n                         ((e.Modifiers & Keys.Shift) == Keys.Shift) &&\n                         ((e.Modifiers & Keys.Control) == Keys.Control);\n}	0
4174342	4174315	Make simple [C#]	foreach (var friend in friends)\n{\n    friend.Value.blockQuote = GetBlockQuote(friend.Value.nick);\n\n    Uri uri;\n    if (friend.Value.photo == "0")\n    {\n        if (friend.Value.sex == 1)\n        {\n            uri = new Uri(@"avatars\man.jpg", UriKind.Relative);\n        }\n        else if (friend.Value.sex == 2)\n        {\n            //da default\n            uri = new Uri(@"avatars\woman.jpg", UriKind.Relative);\n        }\n        else\n        {\n            uri = null; // insert error handling here\n        }\n    }\n    else\n    {\n        uri = new Uri(friend.Value.photo.Replace(@"\", "").Replace(@"s_", ""), UriKind.Absolute);\n    }\n    var img = new BitmapImage();\n    img.BeginInit();\n    img.UriSource = uri;\n    img.EndInit();\n    friend.Value.profilePhoto = img;\n}	0
7890388	7890132	How can I change font color in gridview DevExpress c#	private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)\n    {\n        if(e.Column.FieldName == "Field2")\n        {\n            var data = gridView1.GetRow(e.RowHandle) as Sample;\n            if(data == null)\n                return;\n\n            if (data.Field2 < 0)\n                e.Appearance.ForeColor = Color.Red;\n        }\n    }	0
22850576	22850526	Trigger a password behavior on and off in a textbox	txtPassword.PasswordChar = '\0';	0
19762344	19762229	How to set two values for same definition in enum, C#	public sealed class MyFakeEnum {\n\n  private MyFakeEnum(int value, string description) {\n    Value = value;\n    Description = description;\n  }\n\n  public int Value { get; private set; }\n\n  public string Description { get; private set; }\n\n  // Probably add equality and GetHashCode implementations too.\n\n  public readonly static MyFakeEnum Value1 = new MyFakeEnum(1, "value1");\n  public readonly static MyFakeEnum Value2 = new MyFakeEnum(2, "value2");\n}	0
745556	745553	C# .NET - How do I load a file into a DataSet?	DataTable dt = new DataTable("files");\ndt.Columns.Add("name", typeof(string));\ndt.Columns.Add("size", typeof(int));\ndt.Columns.Add("content", typeof(byte[]));	0
20245609	20245539	Search for similar values in 2 arrays	var matches = from data in listData\n              join serverData in listServerData \n                  on new {id = data.Id, content = data.Content} equals \n                     new {id = serverData.sId, content = serverData.sContent}\n\n             select new {\n                 <whatever you need>\n             }	0
20939326	20939290	Serialize C# POCO containing non-english characters into JSON	var div = document.createElement('div');\ndiv.innerHTML = encoded;\nvar decoded = div.firstChild.nodeValue;	0
10137342	10137327	Splitting a string from a specific point in C#	new FileInfo(@"C:\Windows\System32\calc.exe").Name	0
7766061	7765855	Creating a dynamic UI in winforms	partial class Form1 : Form\n{\n    List<TextBox> textBoxes = new List<TextBox>(); // or stack\n    const int textBoxWidth = 200;  // control variables for TextBox placement\n    const int textBoxHeight = 50;\n    const int textBoxMargin = 5;\n\n    void button1_Click(object sender, EventArgs e)\n    {\n        this.Height += textBoxHeight + textBoxMargin;\n        TextBox tb = new TextBox();\n\n        if (textBoxes.Count == 0)\n        {\n            tb.Top = textBoxMargin;\n        }\n        else\n        {\n            tb.Top = ((textBoxHeight + textBoxMargin) * textBoxes.Count) + textBoxMargin;\n        }\n\n        tb.Left = textBoxMargin;\n        tb.Height = textBoxHeight;\n        tb.Width = textBoxWidth;\n        textBoxes.Add(tb);\n        this.Controls.Add(tb);\n    }\n}	0
2881509	2881409	Text property in a UserControl in C#	[EditorBrowsable(EditorBrowsableState.Always)]\n[Browsable(true)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n[Bindable(true)]\npublic override string Text	0
23454836	23454796	How to bring up Color Picker Pallete C#	private void button1_Click(object sender, System.EventArgs e)\n{\n    ColorDialog MyDialog = new ColorDialog();\n    // Keeps the user from selecting a custom color.\n    MyDialog.AllowFullOpen = false;\n    // Allows the user to get help. (The default is false.)\n    MyDialog.ShowHelp = true;\n    // Sets the initial color select to the current text color.\n    MyDialog.Color =  textboxMain.BackColor;\n\n    // Update the text box color if the user clicks OK  \n    if (MyDialog.ShowDialog() == DialogResult.OK)\n         textboxMain.BackColor =  MyDialog.Color;\n}	0
14521448	14521405	Convert Long Value to DateTime in C#	DateTime.FromOADate()	0
8163912	8163793	How to access control on MainForm from other Thread without coupling?	private delegate void doSomethingWithTheControlsDelegate(object obj);\n\npublic void doSomethingWithTheControls(object obj) {\n if (this.InvokeRequired) {\n   this.BeginInvoke(new doSomethingWithTheControlsDelegate(this.doSomethingWithTheControls), obj);\n } else {\n   // do something\n }\n}	0
11244262	11243373	How to search for a substring	xDataForLINQ.Descendants("pickUpPoint")\n            .FirstOrDefault(p => (string) p.Attribute("puKey") + p.Value == tourPickUp)	0
5813958	5813299	How to Assign a Datasource to a Checkboxlist in an ITemplate	public membershipChkLst(DataTable dt)\n{\n   chklst  = new CheckBoxList();\n   chklst.ID = "chklstid";\n   chklst.DataSource = dt;\n   chklst.DataBind();\n}	0
22533900	22533259	How to open new tab on ASP C# and focus stay on current page then current page redirect to another page on click button?	Response.Redirect(url);	0
19353222	19353203	Set default controller in MVC4	public class RouteConfig\n    {\n        public static void RegisterRoutes(RouteCollection routes)\n        {\n            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n            routes.MapRoute(\n                name: "Default",\n                url: "{controller}/{action}/{id}",\n                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }\n            );\n        }\n    }	0
16680449	16680336	Retrieve a list of items where an item exists in one of the items lists	List<Project> _MemberProjects =\n                _Db.Projects.Where(p =>\n                     p.Users.Any(u => u.UserID == _User.UserID )\n                ).ToList();	0
8944568	8944543	Getting the ID of an inserted row	id = (int) command.ExecuteScalar()	0
12024997	12024955	Detect property change	public class Bar\n{\n    private bool _initializing;\n\n    private string _foo;\n    public string Foo\n    {\n        set\n        {\n            _foo = value;\n            if(!_initializing)\n                NotifyOnPropertyChange();\n        }\n    }\n\n    public Bar()\n    {\n        _initializing = true;\n        Foo = "bar";\n        _initializing = false;\n    }\n}	0
10000112	10000045	How to close a tab when a form embedded in it closed?	private void ClientForm_FormClosing(object sender, FormClosedEventArgs e)\n    {\n      ((TabControl)((TabPage)this.Parent).Parent).TabPages.Remove((TabPage)this.Parent);\n    }	0
595826	595810	Do i need to close a MySqlConnection in asp.net?	SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");\n\nSqlCommand selectCMD = new SqlCommand("SELECT CustomerID, CompanyName FROM Customers", nwindConn);\nselectCMD.CommandTimeout = 30;\n\nSqlDataAdapter custDA = new SqlDataAdapter();\ncustDA.SelectCommand = selectCMD;\n\nDataSet custDS = new DataSet();\ncustDA.Fill(custDS, "Customers");	0
6375199	6375122	How to parse JSON Response into Dictionary?	JObject json = JObject.Parse(jsonResponseData);\n ...\n mydic.Add(json["New SessionResult"]["Key"], json["New SessionResult"]["Value"]	0
8122915	8122447	Is there any event which Fires when observes that a node from TreeList had the check mark checked from code?	void treeList1_NodeChanged(object sender, NodeChangedEventArgs e) {\n    if(e.ChangeType == NodeChangeTypeEnum.CheckedState) { \n        // do something\n    }\n}	0
24752577	24751998	Listbox event after barcode scaning	string scannerInput = "";\n\nprivate void listBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if ((int)e.KeyChar == 13)\n    {\n        listBox1.Items.Add(scannerInput );\n        scannerInput = "";\n    }\n    else scannerInput += e.KeyChar.ToString();\n}	0
32921534	32921298	Assign the old value of dropdown to the same dropdown after edit button clicked in grid view	string category = (e.Row.FindControl("lblCategory") as Label).Text;\nListItem item = ddlCategories.Items.FindByText(category);\nif(item != null)\n    item.Selected = true;	0
31997311	31997218	Read Line From Text File With More Than Int.Max Number of Lines	public static IEnumerable<T> MySkip<T>(this IEnumerable<T> list, ulong n)\n{\n    ulong i = 0;\n    foreach(var item in list)\n    {\n        if (i++ < n) continue;\n        yield return item;\n    }\n}	0
28347791	28323082	Web Api 2 route configuration with legacy asmx services in api folder	private void Application_BeginRequest(object sender, EventArgs e)\n{\n    string url = Request.Url.AbsolutePath.ToLower();\n\n    if (url.StartsWith("/api") && url.Contains(".asmx") && !url.Contains("/api/legacy/"))\n    {\n        url = Request.Url.AbsolutePath.Replace("/api/", "/api/legacy/");\n\n        Context.RewritePath(url);\n    }\n}	0
18386001	18385637	detect Internet Connection/Disconnection in Console App C#	public static void ConnectToPUServer()\n{\n    var client = new WebClient();\n    while (i < 500 && networkIsAvailable)\n    {\n        string html = client.DownloadString(URI);\n        //some data processing\n        Console.WriteLine(i);\n        i++;\n        URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";\n    }\n    Console.WriteLine("Complete.");\n    writer.Close();\n\n}\n\nstatic void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)\n{\n    networkIsAvailable = e.IsAvailable;\n    if (!networkIsAvailable)\n    {\n        Console.WriteLine("Internet connection not available! We resume as soon as network is available...");\n    }\n    else\n    {\n        ConnectToPUServer();\n    }\n}	0
23458694	23449142	How to make a button in a custom control to fire onClick event and have it handled in the main form where the custom control resides?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        trayMap.MyCustomClickEvent += MyCustomClickEvent;  // i'm assuming trayMap is the name of user control in main form.\n    }\n\n    private void btnInForm_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show("Test Button In Form", "btnInForm Button Clicked", MessageBoxButtons.OK);\n    }\n\n    private void MyCustomClickEvent(object sender, EventArgs e)\n    {\n        Button button = sender as Button;\n        MessageBox.Show("Test Button In TrayMap", button.Text + " Button Clicked", MessageBoxButtons.OK);\n    }\n}	0
6750648	6750621	create .exe from c# windows application	ilmerge.exe exefile.exe [dlls-to-internalize.dll ..] /out:exefile-out.exe /t:exe	0
28616010	28615578	Linq left join with group join	var A = new [] { new Foo { Bar = 1 }, new Foo { Bar = 2 }};\nvar B = new [] { new Foo { Bar = 2 }};\n\nvar C = from x in A\n        join y in B on x.Bar equals y.Bar into z\n        from y in z.DefaultIfEmpty()\n        where y == null\n        select x;	0
5797607	5250966	Documentation for Finer Points of FtpWebRequest	using (FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse())\n        {\n            try\n            {\n                using (Stream dataStream = response.GetResponseStream())\n                {\n                    using (StreamReader reader = new StreamReader(dataStream))\n                    {\n                       return reader.ReadToEnd();\n                    }\n                }\n            }\n            finally\n            {\n                response.Close();\n            }\n        }	0
27040449	27040225	Find missing items in a list based on a mask	resultString = Regex.Replace(subjectString, @"\D+", "");	0
28074653	28074139	MVVM - Display messages from multiple model entities in the view	public interface IMessageHandler\n{\n    void SendMessage(string msg);\n}\n\npublic class MessageHandler : IMessageHandler\n{\n    public ObservableCollection<string> Messages { get; set; }\n    public void SendMessage(string msg)\n    {\n        App.Current.Dispatcher.BeginInvoke(new Action(() => Messages.Add(msg)));\n    }\n}\n\npublic class ViewModel1 \n{\n    private readonly IMessageHandler _messageHandler;\n\n    public ViewModel1(IMessageHandler messageHandler)\n    {\n        _messageHandler = messageHandler;\n    }\n}\n\npublic class ViewModel2 \n{\n    private readonly IMessageHandler _messageHandler;\n\n    public ViewModel2(IMessageHandler messageHandler)\n    {\n        _messageHandler = messageHandler;\n    }\n}	0
13736520	13736480	How do I convert a single char to a string?	String myString = "Hello, World";\nforeach (Char c in myString)\n{\n    String cString = c.ToString(); \n}	0
26821793	26821001	How to get each status of process from backgroundWorker on front of Form	(sender as BackgroundWorker).ReportProgress((int)(100.0 / totalSteps * i), null);\n\n  void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n\n        progressBar1.Value =(int) e.ProgressPercentage;\n    }	0
13823447	13823380	Remove decimals in a currency	String.Format("{0:C0}",Amount)	0
11195838	11195775	How to insert a tabSpace into a string?	string ab = "a\tb";	0
28462464	28363243	How add row to DataGrid?	private void AddNewRowMenuItem_OnClick(object sender, RoutedEventArgs e)\n    {\n        job pipainput = new job(JobsDataGrid.Items.Count+1,"",0,"");\n        XmlSerializer xmls = new XmlSerializer(typeof(job));\n        var sb = new StringBuilder(512);\n\n        using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))\n            {\n                xmls.Serialize(sw, pipainput);\n            }\n\n        XmlDocument xmlk = new XmlDocument();\n        xmlk.LoadXml(sb.ToString());\n\n        XmlNode pipa = XMLData.Document.ImportNode(xmlk.ChildNodes[1], true);\n        XMLData.Document.DocumentElement.AppendChild(pipa);\n    }	0
685329	685318	How to create a property class in c#?	Dictionary<TKey, TValue>	0
10984852	10982307	How to change page orientation from c# with open xml sdk	WordprocessingDocument wd = someDoc;\n\nwd.MainDocumentPart.Document.Body.Append(\n    new Paragraph(\n        new ParagraphProperties(\n            new SectionProperties(\n                new PageSize() { Width = (UInt32Value)15840U, Height = (UInt32Value)12240U, Orient = PageOrientationValues.Landscape },\n                new PageMargin() { Top = 720, Right = Convert.ToUInt32(right * 1440.0), Bottom = 360, Left = Convert.ToUInt32(left * 1440.0), Header = (UInt32Value)450U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U }))));	0
7827217	7827068	In c# is there an easy way to test if a value is in an inline-coded set?	//Generic.  All items in the set and the candidate must be the same type.\npublic static bool In<T>(this T item, params T [] set)\n{\n  return set.Contains(item);\n}\n\nbool result = x.In(MyEnum.A, MyEnum.B, MyEnum.C);\n\n//Non-generic and non-typesafe.  Anything goes.  Use with care!\npublic static bool In(this object item, params object [] set)\n{\n  return set.Contains(item);\n}\n\n\nbool result = x.In(MyEnum.A, MyEnum.B, 42);\n\n//int-specific.  \npublic static bool In(this int item, params int [] set)\n{\n  return set.Contains(item);\n}\n\n\nbool result = x.In((int)MyEnum.A, (int)MyEnum.B, 42);	0
20146494	20146370	Format double - thousands separator with decimal but no trailing zeros	{0:#,0.######}	0
9160122	9157413	How to add the dll search path in the code?	Environment.SetEnvironmentVariable	0
1825991	1824758	DataBind listBox selected item to textboxes	usersBindingSource = new BindingSource();\n usersBindingSource.DataSource = _presenter.Users;\n\n usersListBox.DataSource = usersBindingSource;\n usersListBox.DisplayMember = "Name";\n usersListBox.ValueMember = "Id";\n\n nameTextBox.DataBindings.Add("Text", usersBindingSource, "Name", true, DataSourceUpdateMode.OnPropertyChanged);\n loginTextBox.DataBindings.Add("Text", usersBindingSource, "Login", true, DataSourceUpdateMode.OnPropertyChanged);	0
8454367	8454262	An extension method for Session variables	public static string FormatHostAndUrl(this HttpSessionStateBase session)\n{\n    return string.Format("http://{0}{1}",session["CurrentHost"],new Uri((string)Session["currentUrl"]).PathAndQuery);\n}	0
8501015	8500668	Point in polygon in terms of Longitude - Latitude	declare @point geometry\ndeclare @polygon geometry\nset @point =  geometry::STGeomFromText('POINT (-88.22 41.50000001)', 4326)\nset @polygon = geometry::STGeomFromText('POLYGON ((-88.2 41.5, -88.2 41.6, -88.3 41.6, -88.3 41.5, -88.2 41.5))', 4326)--124\nSelect @point.STIntersection(@polygon).ToString()	0
13899246	13891887	Duplicate row check in a datatable using C#	public static DataTable FilterDataTable(DataTable table) \n    {\n        // Erase duplicates\n        DataView dv = new DataView(table);\n        table = dv.ToTable(true, table.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray()); \n\n        // Get Null values\n        List<DataRow> toErase = new List<DataRow>();\n        foreach (DataRow item in table.Rows)            \n            for (int i = 0; i < item.ItemArray.Length; i++)\n            {\n                if (item.ItemArray[i].GetType().Name == "DBNull")\n                { toErase.Add(item); break; }\n\n            }            \n        //Erase Null Values\n        foreach (DataRow item in toErase)            \n            table.Rows.Remove(item);\n\n        return table;            \n    }	0
22056083	21988886	Dependency Injection with 2 constructors	// Using default constructor\nthis.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor());\n\n// Using ISomeService constructor\nthis.unityContainer.RegisterType<ILogger, NLogger>(new InjectionConstructor(new ResolvedParameter<ISomeService>()));	0
22753448	22753378	AutoMapper and DateTime to String mapping not working	Mapper.CreateMap<Company, CompanyDto>()\n      .ForMember(d => d.CreatedDateTime,\n        expression => expression.ResolveUsing(s=>s.CreatedDateTime.ToString("g")));\n\n// now do the Mapper.Map from Company to CompanyDto.	0
17992820	17992735	Select full row when clicking on rowheader in a Datagridview	dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;	0
4275949	4275878	LINQ: How to dynamically use an ORDER BY in linq but only if a variable is not string.empty or null	public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string memberName)  \n{  \n    ParameterExpression[] typeParams = new ParameterExpression[] { Expression.Parameter(typeof(T), "") };  \n\n    System.Reflection.PropertyInfo pi = typeof(T).GetProperty(memberName);  \n\n    return (IOrderedQueryable<T>)query.Provider.CreateQuery(  \n        Expression.Call(  \n            typeof(Queryable),  \n            "OrderBy",  \n            new Type[] { typeof(T), pi.PropertyType },  \n            query.Expression,  \n            Expression.Lambda(Expression.Property(typeParams[0], pi), typeParams))  \n    );  \n}	0
22001411	22001346	find all strings between quotation marks	private static IList<string> betweenQuotes(string input)\n{\n    var result = new List<string>();\n\n    int leftQuote = input.IndexOf("\"");\n\n    while (leftQuote > -1)\n    {\n        int rightQuote = input.IndexOf("\"", leftQuote + 1);\n        if (rightQuote > -1 && rightQuote > leftQuote)\n        {\n            result.Add(input.Substring(leftQuote + 1, (rightQuote - (leftQuote + 1))));\n        }\n        leftQuote = input.IndexOf("\"", rightQuote + 1);\n    }\n\n    return result;\n}	0
33221459	33220463	Change label text (characters) with a timer in a way to create animation?	char code = "\ue052"[0]; // U+E052 is the first character of the progressring\n\npublic Application()\n        {\n            InitializeComponent();\n\n            progressringLabel.Text = code;\n        }\n\nprivate void progressringTimer_Tick(object sender, EventArgs e)\n        {\n            code++;\n            progressring.Text = code.ToString();\n            if (code == "\ue0CB"[0])\n            {\n                code = "\ue052"[0]; // When the code ends up being the last progressring character, revert back to the first one so that it won't go into the other characters\n            }\n        }	0
1430074	1430063	Convert List of longs to string array	string[] arr = list.Select(l => l.ToString()).ToArray();	0
19269382	19267800	UnauthorizedAccessException when writing a file after UAC	FileMode.Create	0
22206227	22205506	Reading DigitalProductId from registry comes back null	var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);\n\nvar reg = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);\n\nvar digitalProductId = reg.GetValue("DigitalProductId") as byte[];	0
24051315	24051231	Implement a property with a private set	public interface IExample{\n      int Test{get;}\n}\n\npublic class Example : IExample{\n      private int _test;\n      public int Test{\n            private set{\n               _test=value;\n            }\n            get{\n               return _test;\n            }\n      }\n}	0
22710385	22709069	connect asp repeaters with objects outside repeaters	protected void fmFrom_SelectedIndexChanged(object sender, EventArgs e)\n{\n    for (int i = 0; i < rateRepeater.Items.Count; i++)\n    {\n        DropDownList from = (DropDownList)rateRepeater.Items[i].FindControl("fmFrom");\n        ((TextBox)FindControl("TextBox" + (i + 1))).Text = from.SelectedValue.ToString();\n    }\n}	0
4081252	4080316	How to implement Invoke method?	public class MyFirstObject {\n  private string MyValue {get;set;}\n  public void UpdateMyValue(string newValue) { MyValue = newValue; }\n}\n\npublic class MySecondObject {\n  MyFirstObject myFirstObject;\n  public MySecondObject {\n    myFirstObject = new MyFirstObject;\n    myFirstObject.UpdateMyValue( "someNewValue" );\n  }\n}	0
2616268	2616137	Detecting run-time game platform in XNA	OperatingSystem os = Environment.OSVersion;\n PlatformID pid = os.Platform;\n switch (pid) \n {\n   //Do whatever\n }	0
1806267	1806265	How to display integers in messagebox in Visual C#?	System.Windows.Forms.MessageBox.Show(myGame.P2.Money.ToString());	0
17853283	17852262	C# Serialize Object instance to XML	var xmlSerializer = new XmlSerializer(ListOfA.GetType(), new Type[] { typeof(B) });	0
25192418	18499701	Prevent Entity Framework DataFirst Timeout from being over ridden when model is updated	public partial class MyDbEntities : DbContext \n{\n    public MyDbEntities (string ConnectionString)\n        : base(ConnectionString)\n    {\n        this.SetCommandTimeOut(360);\n    }\n\n    public void SetCommandTimeOut(int Timeout)\n    {\n        var objectContext = (this as IObjectContextAdapter).ObjectContext;\n        objectContext.CommandTimeout = Timeout;\n    }\n}	0
33599900	33421927	How to provide default value for a parameter in PowerShell help for compiled cmdlets	private int _quantity = 25;\n\npublic int Quantity\n{\n    get { return _quantity; }\n    set { _quantity = value; }\n}	0
12349142	12348899	C# How I can retrieve this information?	HtmlElementCollection tData = wb.Document.GetElementsByTagName("td");\n\n                foreach (HtmlElement td in tData)\n                {\n                    string name = "";\n                    if (td.GetAttribute("classname") == "name")\n                    {\n                        name = td.InnerText;\n                    }\n                }	0
4807448	4807325	How to convert this linqTOsql query to lambda	var entries = entry2CatsTable\n                .Join(streamEntryTable, e2c => e2c.streamEntryID, sEntries => sEntries.seID, (e2c, sEntries) => new { e2c, sEntries })\n                .Where(item => item.e2c.catID == catID)\n                .OrderByDescending(item => item.sEntries.seDateCreated)\n                .ThenBy(item => item.e2c.e2cOrder)\n                .Select(item => item.sEntries);	0
1278865	1278830	Checkbox validation	if (!checkBox1.Checked && !checkBox2.Checked)\n{\n    MessageBox.Show("Please select at least one!");\n}\nelse if (checkBox1.Checked && !checkBox2.Checked)\n{\n    MessageBox.Show("You selected the first one!");\n}\nelse if (!checkBox1.Checked && checkBox2.Checked)\n{\n    MessageBox.Show("You selected the second one!");\n}\nelse //Both are checked\n{\n    MessageBox.Show("You selected both!");\n}	0
9840659	9840171	validate xml file using xsd in C#.. How much does it actually validate?	settings.ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationFlags;	0
18992180	18992113	SQL CONVERT function working in SQL Server but not in application	var when = sdr.GetDateTime(i);\n// now format when	0
5976035	5975321	C# - How to chceck if external firewall is enabled?	Namespace = "Root\SecurityCenter2"  (might be "Root\SecurityCenter" on pre-vista)\nQuery = "SELECT * From FirewallProduct"	0
11270987	11270977	Add a space to a label Programmatically?	string User = Environment.UserName;\ntoolStripStatusLabel1.Text = "This Software is Licensed to: " + User;\n// Add a space after 'to:'	0
19576223	19574468	Is there a way to deserialize a json response that has a dynamic name into C# class?	public class Response\n{\n    [JsonProperty("data")]\n    public Dictionary<string, ItemContainer> { get; set; }\n}\n\npublic class ItemContainer\n{\n    [JsonProperty("Item")]\n    public Item Item { get; set; }\n}	0
18278847	18278614	how to sent a SMTP email with a Unicode sender name	var bytes = Encoding.UTF8.GetBytes(Name);\n    var base64 = Convert.ToBase64String(bytes);\n    message.AddHeader('Sender', String.Format("=?UTF-8?B?{0}?= <{1}>", base64, email));	0
2959196	2959161	Linq: convert string to int array	string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";\nint[] ia = s1.Split(';').Select(n => Convert.ToInt32(n)).ToArray();	0
17904036	17903027	Two textboxes which sum of values are complementary	public static readonly DependencyProperty Text1Property =\n        DependencyProperty.Register("Text1", typeof(decimal), typeof(Form), \n                                    new PropertyMetadata(default(decimal)));\n\n    public decimal Text1\n    {\n        get { return (decimal)GetValue(Text1Property); }\n        set\n        {\n            SetValue(Text1Property, value);\n            SetValue(Text2Property, TotalValue - value);\n        }\n    }	0
8838189	8837581	Which design pattern for ordering and filtering data?	public enum SortMethod\n{\n    Newest,\n    Oldest,\n    LowestPrice,\n}\n\npublic class Foo\n{\n    public DateTime Date {get;set;}\n    public decimal Price {get;set;}\n}\n\n\n...\nvar strategyMap = new Dictionary<SortMethod, Func<IEnumerable<Foo>, IEnumerable<Foo>>>\n                  {\n                      { SortMethod.Newest, x => x.OrderBy(y => y.Date) },\n                      { SortMethod.Oldest, x => x.OrderByDescending(y => y.Date) },\n                      { SortMethod.LowestPrice, x => x.OrderBy(y => y.Price) }\n                  };\n\n...\nvar unsorted = new List<Foo>\n               {\n                   new Foo { Date = new DateTime(2012, 1, 3), Price = 10m },\n                   new Foo { Date = new DateTime(2012, 1, 1), Price = 30m },\n                   new Foo { Date = new DateTime(2012, 1, 2), Price = 20m }\n               };\n\nvar sorted = strategyMap[SortMethod.LowestPrice](unsorted);	0
25919062	25918507	How to convert large Binary string to Hexa decimal string format in C#?	string BinaryData = "1011000000001001001000110100010101100111100000000001000001111011100010101011";\n\nint count = 0;\nvar hexstr = String.Concat(\n                BinaryData.GroupBy(_ => count++ / 4)\n                          .Select(x => string.Concat(x))\n                          .Select(x => Convert.ToByte(x, 2).ToString("X"))\n             );	0
16816276	16816171	Using linq to filter a search	var query = db.invites.AsQueryable();\n\nif(!string.IsNullOrEmpty(userInput.Division.Text))\n    query = query.Where(invite => invite.Division == userInput.Division.Text);\n\nif(!string.IsNullOrEmpty(userInput.Status.Text))\n    query = query.Where(invite => invite.Status== userInput.Status.Text);	0
24621929	24621658	Extracting XML values from two nodes	var doc = XDocument.Parse(xml);\nvar r = doc.Descendants("Record")\n    .Where(n => n.Element("Field").Attribute("guid").Value == "07a188d3-3f8c-4832-8118-f3353cdd1b73")\n    .Select(n => new { ModuleId = n.Attribute("moduleId").Value, Field = n.Element("Field").Value });\n\nvar a = r.ToArray();	0
6359194	6357340	App. architecture with MVP and some specific unit testing scenarios	public class BaseController\n{\n  private IScreenRepository _screen = NullScreenRepository.Instance;\n  public IScreenRepository Screen {get { return _screen; } set { _screen = value; } } \n\n}	0
32584591	32583905	Dynamic size of telerik grid	.Scrollable(scrolling => scrolling.Enabled(false))	0
30490454	30490199	how to disable all rows in gridview in asp.net	protected void OnRowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            Label lblEndDate = (Label)e.Row.FindControl("lblStudyEndDate");\n            TextBox tbSomeTB = e.Row.FindControl("tbSomeTB") as TextBox;\n\n            DateTime EndDate = DateTime.Parse(lblEndDate.Text);\n            if (EndDate < DateTime.Today)\n            {\n                e.Row.BackColor = System.Drawing.Color.DarkGray;\n                tbSomeTB.Enabled = false;\n            }\n        }\n    }	0
4312143	4312022	Trying to separate code in a client server model where the client isn't trusted and with minimal duplication	// lightweight data class thats shared\npublic class Item\n{\n    public int Weight { get; set;  }\n    public string Name { get; set; }\n}\n\n// decorator pattern class that adds behaviour\npublic class ServerItem\n{\n    private Item item;\n    public ServerItem(Item item)\n    {\n        this.item = item;\n    }\n\n    public void Use()\n    {\n        // do something with item;\n    }\n}\n\nServerItem currentServerItem = new ServerItem(currentItem);	0
13420332	13419718	How can I get the current Umbraco user in a Media.AfterSave event handler?	User currentUser = User.GetCurrent();	0
10006601	10006563	How to execute c# console application from batch file	"C:\Users\mahesh\Documents\Visual Studio Projects\Foo\bin\Debug\Foo.exe"\nFoo\nFoo.exe\n"\Some other folder\foo"	0
2084404	2084326	What is the usage of binding a datagridview to an arraylist full of for example some employee objects in c#?	Private Sub DataGridView1_RowEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowEnter\n        Dim Persons As List(Of Person) = CType(Me.DataGridView1.DataSource, List(Of Person))\n        Dim SelectedPerson As Person = Persons(e.RowIndex)\n        MsgBox(SelectedPerson.Name)\nEnd Sub	0
31716625	31716463	Avoiding multiple if statements in C# factory method	if-statements	0
2645877	2645599	L2E many to many query	var codes = from u in Users\n            from pg in u.PrivilegeGroups\n            from p in pg.rdPrivileges\n            where u.userId == "SomeUserID"\n            select p.code;	0
29807161	29807079	I want to access controls of derive class from base class on onLoad() override in c# (Master page derive from one masterClass)	public class BaseClass\n{\n    public override OnLoad(object sender, EventArgs e)\n    {\n        base.OnLoad(e);\n\n        SetLabels();        //This will call the appropriate child class method\n    }\n\n    public virtual void SetLabels()\n    {\n\n    }\n}\n\npublic class ChildClass1 : BaseClass\n{\n    public override void SetLabels()\n    {\n        //Set the label here\n    }\n}\n\npublic class ChildClass2 : BaseClass\n{\n    public override void SetLabels()\n    {\n        //Set the label here\n    }\n}	0
5894839	5892669	Display issue while add control Programmatically  in WP7 using Visual studio 2010	Button nw = new Button();    \n       nw.VerticalAlignment = System.Windows.VerticalAlignment.Top;\n       nw.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;                    \n       nw.Margin = new Thickness(80, 150, 0, 0);      \n       ContentPanel.Children.Add(nw);	0
27271840	27271767	How to get a match on lookup list using Linq?	var q = products.Where(x => LookupList.Any(\n                                          s => s.Period == x.Period && \n                                          x.MinValue >= s.MinValue && \n                                          x.MaxValue <= s.MaxValue));	0
30130270	30129431	Including DB2 Environment with WPF Build	using System.Diagnostics;\nclass Program\n{\n    static void Main()\n    {\n        Process.Start("C:\\pathToExe");\n    }\n}	0
9691690	9691575	C# gridview row onclick	protected void ChangedRow(object sender, EventArgs e)\n        {\n            this.GridView1.SelectedRow.BackColor = System.Drawing.Color.Red;\n....\n        }	0
34264342	34264226	Check if a string contains only letters, digits and underscores	bool validA = sname.All(c => Char.IsLetterOrDigit(c) || c.Equals('_'));	0
5457558	5457472	DateTime.ToString formatting	string.Format(ci, "{0:ddd} {0:d}", x)	0
15596543	15593166	Binding TreeView with a ObservableCollection	public class Media : INotifyPropertyChanged \n{\n   string _name;\n   string Name {\n       get {return _name;} \n       set { _name=value; OnPropertyChanged("Name");}} //OnPropertyChanged is important!\n   ...\n}	0
17089187	17089147	A way to get a DataRow from a DataRowView	DataRow row = ((DataRowView)SelectedZone).Row;	0
1076525	1076475	Linq to XML - Check for null element while parsing for DateTime	var accountSettings =\n  from settings in templateXML.Descendants("Account")\n  select new Account {\n    AccountExpirationDate = \n      string.IsNullOrEmpty((string)settings.Element("AccountExpirationDate")) \n            ? (DateTime?)null\n            : DateTime.Parse(settings.Element("AccountExpirationDate").Value) \n  };	0
18138773	18138430	get back and fore colors from excel cell to datagrid view c#	internal int getInteriorColorAt(int row, int col)\n{\n  return ((Excel.Range)excelRange.Cells[row, col]).Interior.Color;\n}\n\ninternal int getFontColorAt(int row, int col)\n{\n  return ((Excel.Range)excelRange.Cells[row, col]).Font.Color;\n}	0
33924172	33922120	Check if method implements interface method marked with attribute	methodSymbol.ContainingType\n    .AllInterfaces\n     .SelectMany(@interface => @interface.GetMembers().OfType<IMethodSymbol>())\n     .Any(method => methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(method)));	0
9913764	9913049	Refrences break console app from running on other machines	if (smartData == null)\n   throw new Exception("Smart data is null; aborting");\n\nif (smartData.Any() == false)\n   throw new Exception("Smart data instance is valid but has no elements; aborting");\n\nbool conversion = int.TryParse(smartData[1].ToString(), out temp);	0
10795299	10795255	Alternative for NameValueCollection to be used in serialization	List<Tuple<string, string>>	0
14648410	14647859	How do i downsample an 8 bit bitmap array of size 20x30 to 10x15	org_img[20][30]; --monochrome values\nsampled_img[10][15];\n\nfor(int i=0; i < 10; i++)\n{\n    for(int j=0; j < 15; j++)\n    {\n        int average = org_img[2*i][2*j] + org_img[2*i+1][2*j]+ org_img[2*i][2*j+1] + org_img[2*i+1][2*j+1];\n        average = average>>2; --integer division by 4.\n        sampled_img[i][j] = average;\n    }\n}	0
6642701	6642609	MySQL Query To Retrieve Data With Column Names	private void PrintColumnNames(DataSet dataSet)\n{\n    // For each DataTable, print the ColumnName.\n    foreach(DataTable table in dataSet.Tables)\n    {\n        foreach(DataColumn column in table.Columns)\n        {\n            Console.WriteLine(column.ColumnName);\n        }\n    }\n}	0
10583847	10583155	Access OTF font	System.Drawing	0
21019761	21019625	How to print without showing the Printing Dialogue?	pd.ShowDialog();\nif (pd.ShowDialog() != true) return;	0
11413968	11413938	Hiding title bar in windows form application	this.FormBorderStyle = FormBorderStyle.None; // Assuming this code is in a method on your form	0
33616085	33579071	Reflections on a unit test looking for generics in an interface	var entitiesInUnitOfWork = typeof(IUnitOfWork).GetProperties()\n    .Where(x => \n        x.PropertyType.IsGenericType && \n        x.PropertyType.GetGenericTypeDefinition() == typeof(IQueryable<>) &&  \n        typeof(IEntity<Guid>).IsAssignableFrom(x.PropertyType.GetGenericArguments()[0])\n    .Distinct();	0
6741404	6741392	Is there a way to pass parameters/variables in an XPath statement in .NET?	private object SelectSingleNodeTyped(XPathNavigator nav, string select, XsltArgumentList parameters)\n{\nmyContext.ArgList = parameters;\nXPathExpression exp = nav.Compile(myXPathSelect);\nexp.SetContext(myContext);\nobject obj = nav.Evaluate(exp);	0
3686925	3621710	Sourcing 'Fatal Error' resulting from MySQL ExecuteNonQuery?	string sql = @"load data infile 'c:/myfolder/Data/" + aFile.Name \n+ "' ignore into table t_data fields terminated by '' enclosed by '' lines terminated by '\n'";\nMySqlCommand cmd = new MySqlCommand(sql, conn);\ncmd.CommandTimeout = Timeout;\ncmd.ExecuteNonQuery();	0
32314868	32293177	SQL Command Parameters	notifyDate3Parameter.ParameterName = "@NotifyDate13"	0
9911619	9911591	how to get current url in code behind?	Request.Url.AbsoluteUri	0
10432486	10432045	Does the Task Parallel Library provide a way to pool open connections?	Parallel.ForEach()	0
9002868	9002778	Make sync a void method that rises an event, returning event args	public class Client\n        {\n            NetClient m_NetClient = new NetClient();\n            AutoResetEvent _lock = new AutoResetEvent(false);\n            bool result;\n\n            public bool Connect(string ip, int port)\n            {\n                m_NetClient = new NetClient();\n                m_NetClient.Connected += _NetClient_Connected;\n                m_NetClient.Connect(ip, port);\n                _lock.WaitOne();//wait for thread to finish\n                return result;\n            }\n\n            private void _NetClient_Connected(object sender, EventArgs e)\n            {\n                //...\n                result = e.Result;\n                _lock.Set(); //inform waiters\n            }\n        }	0
27862686	27862516	ASP.NET MVC Retrieve data with certain name	db.Objects.Where(o => o.Name == "Tree").ToList();	0
13025490	13025432	when casting from a number the value must be a number less than infinity	decimal num = 0;\nif (monthlytable.Rows[u][3] != DBNull.Value)\n    num = Math.Round((decimal)monthlytable.Rows[u][3], 2, MidpointRounding.AwayFromZero)\nstring Maxmonthlytable = num.ToString();	0
14186218	14186147	Iterating over columns of database tables using entity framework	foreach (PropertyInfo propertyInfo in typeof(CustomerInfo).GetProperties())	0
15931478	15931289	how to change a sql timeout after command has been started	MySqlConnection.Close()	0
16973360	16973149	Dictionary to XML	XElement el = new XElement("root",\n      UserClassDict.Select(kv => new XElement(kv.Key, \n       kv.Value.ControlNumbers.Select(num => new XElement("controlNumbers", num))))\n);	0
26758544	26758454	C# How to Access a Specific Index of a List of Classs	StudentRecord editRecord = null;\n\nforeach(var indexRecord in lstRecords)\n{                   \n    if(indexRecord.intStudentNumber == intChosenRecord))\n    {\n        editRecord = indexRecord;\n        break; // Exits the loop.\n    }\n}	0
29783295	29780559	How to change variable for a certain period of time	if (Input.GetKeyDown("a")) {\n    goUp();\n    StartCoroutine("ReduceSpeedAfter5Seconds");\n}\n\nIEnumerator ReduceSpeedAfter5Seconds() {\nGetComponent<Rigidbody2D> ().velocity = new Vector2 (0, 10);\n        yield return new WaitForSeconds(5.0f);\n}	0
9673668	9673360	Create, store and retrieve dynamic data with C#	ConcurrentDictionary<string, string[,]>	0
8743745	8741943	WinForms DataGridView behaviour similar to SQL Server Management Studio	private void myGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e) \n{ \n    // Note the check to see if the current row is dirty\n    if (string.IsNullOrEmpty(myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].FormattedValue.ToString()) &&  myGrid.IsCurrentRowDirty) \n    { \n        e.Cancel = true; \n        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = "Mandatory"; \n        MessageBox.Show("Error message"); \n    } \n    else \n    { \n        myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = string.Empty; \n    } \n}	0
33742791	33742696	Getting all files in UWP app folder	StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;\nStorageFolder assets = await appInstalledFolder.GetFolderAsync("Assets");\nvar files = await assets.GetFilesAsync();	0
3501763	3501667	Asp.net + C#: Copy DataColumn from tableA to table B	TableB.Columns.Add(columnToAdd.ColumnName, columnToAdd.DataType)	0
24753834	24753620	Combine two non-identical rows of a datatable	DataTable dt1 = new DataTable();\nDataTable dt2 = new DataTable();\n\ndt1.Columns.Add("id", typeof(Int32));\ndt2.Columns.Add("Name", typeof(String));\n\nDataRow dr = dt1.NewRow();\ndr["id"] = 1;\ndt1.Rows.Add(dr);\n\ndr = dt1.NewRow();\ndr["id"] = 2;\ndt1.Rows.Add(dr);\n\ndr = dt2.NewRow();\ndr["name"] = "XXX";\ndt2.Rows.Add(dr);\n\ndr = dt2.NewRow();\ndr["name"] = "YYY";\ndt2.Rows.Add(dr);\n\nDataTable dt3 = new DataTable();\ndt3.Columns.Add("id", typeof(Int32));\ndt3.Columns.Add("Name", typeof(String));\n\nfor (int i = 0; i < dt1.Rows.Count; i++)\n{\n    dr = dt3.NewRow();\n\n    dr["id"] = dt1.Rows[i]["id"];\n    dr["name"] = dt2.Rows[i]["name"];\n    dt3.Rows.Add(dr);\n}	0
14326860	14280960	Custom control in DataGridView cell	public override void DetachEditingControl()\n    {\n        DataGridView dataGridView = this.DataGridView;\n\n        if (dataGridView == null || dataGridView.EditingControl == null)\n        {\n            throw new InvalidOperationException("Cell is detached or its grid has no editing control.");\n        }\n\n        DataGridViewCheckBoxComboBoxCellEditingControl ctl = DataGridView.EditingControl as DataGridViewCheckBoxComboBoxCellEditingControl;\n        if (ctl != null)\n        {\n            ctl.CheckBoxItems.Clear();  //Forgot to do this.\n            ctl.EditingControlFormattedValue = String.Empty;\n        }\n\n        base.DetachEditingControl();\n    }	0
1135373	1134615	Schedule a job in hosted web server	private static CacheItemRemovedCallback OnCacheRemove = null;\n\nprotected void Application_Start(object sender, EventArgs e)\n{\n    AddTask("DoStuff", 60);\n}\n\nprivate void AddTask(string name, int seconds)\n{\n    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);\n    HttpRuntime.Cache.Insert(name, seconds, null,\n        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,\n        CacheItemPriority.NotRemovable, OnCacheRemove);\n}\n\npublic void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)\n{\n    // do stuff here if it matches our taskname, like WebRequest\n    // re-add our task so it recurs\n    AddTask(k, Convert.ToInt32(v));\n}	0
11756077	11744124	RX - How to subscribe for condition state, but only when this state doesn't change for x period of time?	BehaviorSubject<int> value = new BehaviorSubject<int>(0);\n\nvalue.Select(v => v < 50).DistinctUntilChanged().Throttle(TimeSpan.FromSeconds(10))\n.Where(x => x).Subscribe(b => DoSomething());	0
11259952	11259864	Reading file formatted with C in C#	using (BinaryReader br = new BinaryReader(File.Open("file", FileMode.Open)))\n{\n  int a = br.ReadInt32();\n  int b = br.ReadInt32();\n  int c = br.ReadInt32();\n  int d = br.ReadInt32();\n  double e = br.ReadDouble();\n  double f = br.ReadDouble();\n  ...\n}	0
26886336	26859910	Passing parameter from client side to web method in asp.net telerik	function clientItemRequesting(sender, eventArgs) {\n        var context = eventArgs.get_context();\n        context["FilterString"] = "value sent to server";\n    }	0
19230434	19230257	Merge rows in the same DataTable	DataRow target = table.Rows[0];\nDataRow source = table.Rows[1];\n\nfor (int i = 0; i < table.Columns.Count; i++)\n{\n    target[i] = target[i] ?? source[i];\n}\n\ntable.Remove(source);	0
26239740	26239100	How extract some value from JArray and put into a JSon	auxiliarJson.SelectToken("Inners").Replace(JToken.Parse("["+arraytoMerge[innerCount].ToString()+"]")); //My Solution!	0
6519416	6519123	help with try catch statement	private void SetupConnection()\n{\n    conn.ConnectionString = \n        ConfigurationManager.ConnectionStrings["ZenLive"].ConnectionString;\n\n    bool success = false;\n\n    while(!success)\n    {\n        try\n        {\n            OdbcDataAdapter da = \n               new OdbcDataAdapter("SELECT * FROM MTD_FIGURE_VIEW1 '", conn);\n\n            da.Fill(ds);\n            success = true;\n        }\n        catch(Exception e)\n        {\n            Log(e);\n            Thread.Sleep(_retryPeriod)\n        }\n    }\n}	0
5093126	5018934	Is there a BinaryFormatter alternative which runs in medium trust	public object Deserialize<T>(System.IO.Stream serializationStream)\n{\n    JsonSerializer serializer = new JsonSerializer();\n    T instance;\n\n    BsonReader reader = new BsonReader(serializationStream);\n    instance = serializer.Deserialize<T>(reader);\n\n    return instance;\n}\n\npublic void Serialize(System.IO.Stream serializationStream, object graph)\n{\n    JsonSerializer serializer = new JsonSerializer();\n\n    using (BsonWriter writer = new BsonWriter(serializationStream))\n    {\n        serializer.Serialize(writer, graph);\n    }\n}	0
16451596	16451538	How can I open a specific text file without using OpenFileDialog?	richTextBoxPrintCtrl1.LoadFile(fullPathToRtfFile);	0
2175317	2175209	Retrieve Images from sql server database	connection.Open();\n        SqlCommand command1 = new SqlCommand("select imgfile from myimages where imgname=@param", connection);\n        SqlParameter myparam = command1.Parameters.Add("@param", SqlDbType.NVarChar, 30);\n        myparam.Value = txtimgname.Text;\n        byte[] img = (byte[])command1.ExecuteScalar();\n        MemoryStream str = new MemoryStream();\n        str.Write(img, 0, img.Length);\n        Bitmap bit = new Bitmap(str);\n        connection.Close();	0
11642299	11641842	linq2sql join select data that is not in another table	from u in db.Employees\nwhere !(from e in db.ExpenseTeamMembers\n        where e.expMgrPk == selectedMgr.pk\n        select e.empPk).Contains(u.pk)\nselect u.Name	0
22538469	22538322	Pass a Struct from C++ to CLI	public value struct CallbackInfo\n{\npublic:\n    int callbackType;\n    SystemInfo systemInfo;     \n};	0
19312098	19306979	A socket message from Python to C# comes through garbled	message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")	0
29145201	29144993	How to Add NewLine to RichTextBox from ViewModel	"\\line"	0
21003530	21003444	Trying to format URL for Action using multiple params in MVC	routes.MapRoute(\n        name: "SettingsRoute",\n        url: "Settings/{id}/{siteId}",\n        defaults: new\n        {\n            controller = "Settings",\n            action = "Index",\n            siteId = UrlParameter.Optional\n        }\n    );	0
23407336	23405837	How to check user is in many roles in asp.net identity	using Microsoft.AspNet.Identity;\nvar manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());\n\nvar roles = new List<string> { "admin", "contributor" };\nvar currentUser = manager.FindById(User.Identity.GetUserId());  \n\nif (currentUser.Roles.Any(u => roles.Contains(u.Role.Name)))\n{\n\n}	0
16821187	16821143	How to use a lambda expression as a parameter?	Func<CustomType, string> lambda;  \nswitch (sortBy)\n{\n    case "name":\n        lambda = s => s.Name.ToString();\n        break;\n    case "surname":\n        lambda = s => s.Surname.ToString();\n        break;\n}\n\norderedList = this.Sort<CustomType, string>(\n    lstCustomTypes,\n    lambda,\n    direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);	0
24402007	20367368	Send POST request to apache server with htaccess using WebClient	private string post(string content)\n{\n    var result = String.Empty;\n    var uri = new Uri(_url);\n\n    WebRequest req = HttpWebRequest.Create(uri);\n    req.Method = "POST";\n    req.ContentType = "text/xml";\n\n    String encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:pass"));\n    req.Headers.Add("Authorization", "Basic " + encoded);\n\n    using (var s = req.GetRequestStream())\n    using (var sw = new StreamWriter(s, Encoding.UTF8))\n    {\n        sw.Write(content);\n    }\n    using (var s = req.GetResponse().GetResponseStream())\n    using (var sr = new StreamReader(s, Encoding.UTF8))\n    {\n        result = sr.ReadToEnd();\n    };\n    return result;\n}	0
28125086	28119615	Google OAuth2 with Server to Server authentication returns "invalid_grant"	var params = new List<KeyValuePair<string, string>>();\nparams.Add(new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));\nparams.Add(new KeyValuePair<string, string>("assertion", finalJwt));\nvar content = new FormUrlEncodedContent(pairs);\nvar message = client.PostAsync(url, content).Result;	0
2717962	2717925	update table with c# and mysql	command.Connection = (Insert connection string here);\ncommand.CommandText = (Insert update statement);\nint numRowsUpdated = command.ExecuteNonQuery();	0
32952856	32952719	How to clear ASP.NET cache thread-safely?	private object lockRoles = new object();\n\npublic Roles GetRoles\n{\n  get \n  {\n    object cached = HttpContext.Current.Cache["key"];\n    if(cached == null) \n    {\n      lock(lockRoles)\n      {\n        cached = HttpContext.Current.Cache["key"];\n        if (cached == null) \n        {\n          cached = new GetRolesFromDb(...);\n          HttpContext.Current.Cache["key"] = cached; \n        }\n      }\n    }\n    return (Roles)cached;\n  }\n}    \n\npublic void ClearRoles()\n{\n  HttpContext.Current.Cache.Remove("key");\n}	0
12058217	12058082	How to check a file is present or not in UNC path?	outPath=@"\\DevSrv\outPath\result.txt";\n//Or\noutPath="\\\\DevSrv\\outPath\\result.txt";	0
13820239	13819809	How to differ between System variable and Custom variable	int i = 10;\nstring str = "";\nvar isPrimitive = i.GetType().IsValueType || i is string; // returns true since i is value type\nvar isPrimitiveWithString = str.GetType().IsValueType || str is string; \n // returns true\n\nCustomClass obj = new CustomClass();\nvar isPrimitive3 = obj.GetType().IsPrimitive; // returns false	0
6152020	6145685	How did they implement this syntax in the Massive Micro-ORM, multiple args parameters?	Test(age: 40, name: "Lasse", args: new object[] { 10, 25 });	0
11971648	11895437	Graphical glitch occuring in XNA on Windows Phone 7 in Landscape orientation	public Game1()\n    {\n        graphics = new GraphicsDeviceManager(this);\n        Content.RootDirectory = "Content";\n\n        graphics.PreferredBackBufferWidth = 480;\n        graphics.PreferredBackBufferHeight = 800;\n        graphics.IsFullScreen = true;\n\n        // Frame rate is 30 fps by default for Windows Phone.\n        TargetElapsedTime = TimeSpan.FromTicks(333333);\n\n        // Extend battery life under lock.\n        InactiveSleepTime = TimeSpan.FromSeconds(1);\n    }	0
1153361	1153322	WPF dependency property return value	public static readonly DependencyProperty ValueProperty =\n    DependencyProperty.Register("Value", typeof(int), typeof(OwnerClass),\n        new FrameworkPropertyMetadata(0, null, new CoerceValueCallback(CoerceValue)));\n\npublic int Value\n{\n    get { return (int)GetValue(ValueProperty); }\n    set { SetValue(ValueProperty, value); }\n}\n\nprivate static object CoerceValue(DependencyObject d, object value)\n{\n    return (int) value + 1;\n}	0
6840968	6827125	How do I write a byte [] into an Excel file?	for (int F = 0; F < (21*SECT); F++)\n{\n     Console.WriteLine(AllY[F]);   // Shows the byte array mentioned.\n     MyYData[F] = AllY[F].ToString();  // The data is sotred as succesions of strings.\n}\nConsole.ReadKey();\n\nExcel.Application excelApp = new Excel.Application();\nexcelApp.Visible = true;\nstring myPath = @"C:\Documents and Settings\John\My Documents\DATA.xls";   // The main downside to this code, is that the document must exist prior to code execution (but i'm sure you guys can figure out a way for the code to create de document).\nexcelApp.Workbooks.Open(myPath);                                                            \n\nfor (int r = 1; r < ((21 * SECT)+1); r++)  // r must be set to 1, because cell 0x0 doesn't exist!\n{\n     int rowIndex = r;\n     int colIndex = 1;\n     excelApp.Cells[rowIndex, colIndex] = MyYData[r-1];\n     excelApp.Visible = true;\n}\nConsole.ReadKey();	0
10372645	10363178	How to input \t from asp.net	var inputText = tb.Text;\n        if (inputText.Length == 2)\n        {\n            var escaped = System.Text.RegularExpressions.Regex.Unescape(inputText);\n            if (escaped.Length == 1)\n            {\n                var character = escaped.ToCharArray()[0];\n                if (char.IsControl(character))\n                {\n                    inputText = character.ToString();\n                }\n            }\n        }	0
20910831	20910547	How to get access to containers' event from user control?	protected override void OnParentChanged(EventArgs e)\n{\n    base.OnParentChanged(e);\n\n    if (this.Parent != null)\n    {\n        this.Parent.SizeChanged += OnFormSizeChanged; // this.ParentForm.SizeChanged += ...\n    }\n}\n\nvoid OnFormSizeChanged(object sender, EventArgs e)\n{\n    // ...\n}	0
13054388	13054220	Filter C# collection of float given a minimum difference value between adjacent elements	List<float> orderedList = new List<float>() { 12, 14, 34, 45 };\nList<float> itemsToRemove = orderedList.Where((item, index) =>\n                            index < orderedList.Count - 1 &&\n                            orderedList[index + 1] - item < threshhold).ToList();	0
13075232	13056097	SelectSingleNode Html Document	return doc.DocumentNode.SelectSingleNode("//span[@title='"+input+"']").InnerText;	0
7334840	7334799	use a if condition to find which page redirects to current page in asp.net	Request.UrlReferrer	0
24119182	24118975	Set Registry Value	public class RegistryEditor\n{\n    RegistryKey m_key;\n    public RegistryEditor()\n    {\n        m_key = Registry.CurrentUser.OpenSubKey("Software\\Company name", true);\n        m_key = m_key.CreateSubKey("Product name", RegistryKeyPermissionCheck.ReadWriteSubTree);\n    }\n    public string GetValue(string name)\n    {\n        return m_key.GetValue(name, "").ToString();\n    }\n    public void SetValue(string name, string value)\n    {\n        m_key.SetValue(name, value, RegistryValueKind.String);\n    }\n            ~RegistryEditor()\n    {\n        m_key.Close();\n    }\n}	0
29266196	29266142	Converting a Datetime from the datatable to a specific format of string C# ASP.NET	DateTime pmdate = (DateTime) dt.Rows[0]["PMDate"];\nlblDate.Text = pmdate.ToString("g");	0
8914656	8858740	Could use some help conceptualizing how to finish implementing a Microsoft Chart w/ drill-down capabilities under MVC	foreach (Series series in lineChart.Series)\n{\n    series.Url = string.Format("javascript: DrillChart('{0}')", series.PostBackValue);\n}	0
12586286	12585758	Setting the correct index for a combobbx item	public partial class Form1 : Form\n{\n    HashSet<Order> list = new HashSet<Order>();\n\n    public Form1()\n    {\n        InitializeComponent();\n        LoadData();\n        comboBox1.DisplayMember = "OrderName";\n        comboBox1.ValueMember = "OrderNum";\n        comboBox1.DataSource = list.ToArray<Order>();\n    }\n\n    private void LoadData()\n    {\n        // Load some sample data\n        for(int x = 0; x < 10; x++)\n        {\n            Order o = new Order(){OrderName = "Name" + x, OrderNum = x};\n            list.Add(o);\n        }\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        // Select the item with order number = 4 \n        var x = list.Where<Order>(o => o.OrderNum == 4).FirstOrDefault<Order>();\n        comboBox1.SelectedItem = x;\n\n    }\n}\n\npublic class Order\n{\n    public string OrderName;\n    public int OrderNum;\n    public override string ToString()\n    {\n        return this.OrderName;\n    }\n}	0
2458387	2458349	.NET Extension Objects with XSLT -- how to iterate over a collection?	public static XPathNodeIterator GetSomeCollection()\n{    \n    XmlDocument xmlDoc = new XmlDocument();\n\n    string[] stringsToReturn = new string[] { "String1", "String2", "String3" };\n\n    XmlElement root = xmlDoc.CreateElement("Strings");\n\n    xmlDoc.AppendChild(root);\n\n    foreach (string s in stringsToReturn)\n    {\n        XmlElement el = xmlDoc.CreateElement("String");\n\n        el.InnerText = s;\n\n        root.AppendChild(el);\n    }\n\n    XPathNodeIterator xNodeIt = xmlDoc.CreateNavigator().Select(".");\n\n    return xNodeIt;\n}	0
10126805	9997508	Referenced Assembly Not Found - How to get all DLLs included in solution	AppDomain.CurrentDomain.GetAssemblies()	0
30589673	30589496	failure to run a perl script using C#	perlStartInfo.Arguments = "C:\\e\\oa\\Evergreen\\evg\\scripts\\helper\\program.pl -config " + config_location;	0
28852680	28851801	Multipart download of SQLServer IMAGE type data	create proc dbo.GetImageData(@key int, @start bigint, @length bigint) as\nbegin\n\n    select substring(MyImageValue, @start, @length)\n    from dbo.MyImageTable\n    where MyKey = @key\n\nend	0
12033332	12006446	Are there any IoC frameworks that do not use JIT compilation that support interception?	container.AddDecorator()	0
11348796	11348679	ILookup how can I use a Where method?	string jobsToMatch = "Programmer,QA";\nvar relevantNames = jobsToMatch.Split(',');\nvar myLookup = \n    myList.Where(x => relevantNames.Contains(x.Name))\n      .ToLookup(k => k.Job, x => new { x.Name, x.Job, x.Phone });	0
7090880	7088076	Can you use a static method in WCF that accesses HttpContext.Current.Items?	_CurrentRequest = request;	0
16073973	16073446	How to prevent listView on escalating columns and bind it to ViewModel?	private void CreateColumns()\n{\n    myView.Columns.Clear();\n    //...\n}	0
6151003	6150882	Load XML File from Project Directory	XDocument myxml = XDocument.Load(@"assets\myxml.xml");	0
32184193	32182624	Android - Issue with async tasks	async void	0
31474665	31474575	Extract RGB information from image into an array	private void GetPixel_Example(PaintEventArgs e)\n{\n\n// Create a Bitmap object from an image file.\nBitmap myBitmap = new Bitmap("YOURFILENAME.jpg");\n\n// Get the color of a pixel within myBitmap.\nColor pixelColor = myBitmap.GetPixel(50, 50);\n\n}	0
2574798	2574564	Save a 32-bit Bitmap as 1-bit .bmp file in C#	using System.Drawing.Imaging;\nusing System.Runtime.InteropServices;\n...\n\npublic static Bitmap BitmapTo1Bpp(Bitmap img) {\n  int w = img.Width;\n  int h = img.Height;\n  Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);\n  BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);\n  byte[] scan = new byte[(w + 7) / 8];\n  for (int y = 0; y < h; y++) {\n    for (int x = 0; x < w; x++) {\n      if (x % 8 == 0) scan[x / 8] = 0;\n      Color c = img.GetPixel(x, y);\n      if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));\n    }\n    Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length);\n  }\n  bmp.UnlockBits(data);\n  return bmp;\n}	0
5570028	5569994	Left Justify a String in C# with the length dynamically given	private static string LeftJustify(string field, int len)\n{\n    return field.PadRight(len);\n}	0
19731855	19731696	How to get the last navigation url in silverlight application	private List<Uri> _navigationHistory = new List<Uri>();\n\nvoid  onNavigated(object sender, NavigationEventArgs e)\n{\n    _navigationHistory.Add(e.Uri);\n}\n\nprivate Uri getBackUri()\n{\n    return _navigationHistory.Count > 1\n        ? _navigationHistory[_navigationHistory.Count - 2]\n        : null;\n}	0
18650791	18641945	How do I programmatically create irregular buttons in Xamarin?	this.View.AddSubview(energyCircleView);	0
13556223	13555134	How to capture a null Parameter and allow Parsing with DBNull in ADO.NET	oleCommand.Parameters.Add(new OleDbParameter("@LastName", OleDbType.VarChar, 20, \n                                             ParameterDirection.Input, false, 10, \n                                             0, "LastName", \n                                             DataRowVersion.Original, null)\n                         ).Value = String.IsNullOrEmpty(last) ? DBNull.Value : last;	0
32091256	32090126	How to get date only if time is 00:00:00 from DateTime c#	public static string ConvertToMyDateTimeFormat(Nullable<DateTime> value, CultureInfo IFormateProvider)\n        {\n            if (value.HasValue)\n            {\n                if (value.Value.TimeOfDay.Ticks > 0)\n                {\n                    return value.Value.ToString(IFormateProvider);\n                }\n                else\n                {\n                    return value.Value.ToString(IFormateProvider.DateTimeFormat.ShortDatePattern);\n                }\n            }\n            else\n            {\n                return string.Empty;\n            }\n        }	0
870560	870531	Ordinal Date Format C#	new DateTime(year, 1, 1).AddDays(day - 1);	0
18494966	18494043	Serial Port Communication missing one byte	String indata = sp.ReadExisting();\n        sp.DiscardOutBuffer();\n        sp.DiscardInBuffer();	0
28781048	28780926	Convert html with Persian characters to pdf using iTextSharp	PdfPTable pdfTable = new PdfPTable(1);\npdfTable.RunDirection = PdfWriter.RUN_DIRECTION_RTL;	0
22179052	22178566	unable to save images from picturebox to datagridview	private void Display(Bitmap desktop) {\n  if (desktop != null) {\n    Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, \n                            pictureBox1.ClientSize.Height);\n    using (Graphics g = Graphics.FromImage(bmp)) {\n      g.DrawImage(desktop, Point.Empty);\n    }\n    pictureBox1.Image = bmp;\n    dataGridView1.Rows.Add(bmp);\n  }\n}	0
3307222	3306996	adding extra items on top of ComboBox DataSource	IList comboboxDataSource = new List<string>();\ncomboboxDataSource.Add("one");\ncomboboxDataSource.Add("two");\ncomboboxDataSource.Add("three");\n\ncomboboxDataSource.Insert(0, "Please choose an item");\ncomboBox1.DataSource = comboboxDataSource;	0
9723231	9722885	Gridview , how to simple higlight the results of a searched termn in the gridview?	public TextBox txtSearch = new TextBox();\n txtSearch.Text = "Goswami";\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            tc.Text = tc.Text.Replace(txtSearch.Text, "<span style='color:Red;'>" + txtSearch.Text + "</span>");\n        }\n    }            \n}	0
8606855	8606752	View to String from another controller	string t = ViewToString.RenderPartialToString("Index", null, this.ControllerContext);	0
7767228	7767175	How can i find my propertyinfo type?	public virtual void Freez()\n{\n    foreach (var prop in this.GetType().GetProperties())\n    {\n        if (prop.PropertyType.IsClass && typeof(EntityBase).IsAssignableFrom(prop.PropertyType))\n        {\n            var value = (EntityBase) prop.GetValue(this, null);\n            value.Freez();\n        }\n\n        if (typeof(ICollection).IsAssignableFrom(prop.PropertyType))\n        {\n            var collection = (ICollection)prop.GetValue(this, null);\n            if (collection != null)\n            {\n                foreach (var obj in collection)\n                {\n                    if (obj is EntityBase)\n                    {\n                        ((EntityBase)obj).Freez();\n                    }\n                }\n            }\n        }\n    }\n}	0
2357866	2357855	Round double in two decimal places in C#?	inputValue = Math.Round(inputValue, 2);	0
6576823	6576809	How to format complex mathematical expressions?	var fontWidth = parent.font.Width;\nvar index = parent.visibilityIndex;\nvar offset = (Position + parent.Prompt.Length - index) * fontWidth;\nreturn new Vector2(parent.Coordinates.X + offset, parent.Coordinates.Y);	0
6157489	6157451	How to traverse a multi-hierarchy array in C#	VisitNode(Node n){\n        foreach(var cn in n.Children){\n            VisitNode(cn);\n        }\n        //Do what you want to do with your node here\n        Console.Writeline(n.Value);\n   }	0
32158201	32158153	how to simplify code to print all items in an array use one line code in c#	Console.WriteLine(String.Join(" ",prime.Where(n => n > 0)));	0
22735226	22735016	get a List of Max values across a list of lists	// Here I declare your initial list.\n List<List<double>> list = new List<List<double>>()\n {\n     new List<double>(){3,5,1},\n     new List<double>(){5,1,8},\n     new List<double>(){3,3,3},\n     new List<double>(){2,0,4},\n };\n\n // That would be the list, which will hold the maxs.\n List<double> result = new List<double>();\n\n\n // Find the maximum for the i-st element of all the lists in the list and add it \n // to the result.\n for (int i = 0; i < list[0].Count-1; i++)\n {\n     result.Add(list.Select(x => x[i]).Max());\n }	0
33825748	33825152	Loading a list of entities containing the parent as a property	public IList<Agency> Agencies1 { get; set; }\n    public IList<Agency> Agencies2 { get; set; }\n    [NotMapped]\n    public string AllAgencies\n    {\n        get\n        {\n            return Agencies1.Concat(Agencies2).ToList();\n        }\n    }	0
25528675	25528235	How to Deserialize JSON with JavaScriptSerializer to Tuples	//using System;\n        //using System.Collections.Generic;\n        //using System.Linq;\n        //using Newtonsoft.Json.Linq;\n\n        string validJson = "[" + json + "]";\n        JArray jsonArray = JArray.Parse(validJson);\n        List<Tuple<string, string>> tupleJson = jsonArray\n            .Select(p => new Tuple<string, string>((string)p["name"], (string)p["value"]))\n            .ToList();	0
25715656	25715537	Access Child controls of split container .net	(RichTextBox)((SplitContainer )tabControl1.SelectedTab.Controls["split"]).Panel1.Controls["textbox"]	0
2905841	2899338	Know who got the focus in a Lost Focus event	public System.Windows.Forms.Control FindFocusedControl()\n{\n    return FindFocusedControl(this);\n}\n\npublic static System.Windows.Forms.Control FindFocusedControl(System.Windows.Forms.Control container)\n{\n    foreach (System.Windows.Forms.Control childControl in container.Controls)\n    {\n        if (childControl.Focused)\n        {\n            return childControl;\n        }\n    }\n\n    foreach (System.Windows.Forms.Control childControl in container.Controls)\n    {\n        System.Windows.Forms.Control maybeFocusedControl = FindFocusedControl(childControl);\n        if (maybeFocusedControl != null)\n        {\n            return maybeFocusedControl;\n        }\n    }\n\n    return null; // Couldn't find any, darn!\n}	0
18140047	18123157	unwanted html created in table td while clicking the checkbox in nopCommerce	.Editable(editing => editing.Mode(GridEditMode.InCell))	0
1290459	1290451	How to group items by index? C# LINQ	input\n   .Select((value, index) => new { PairNum = index / 2, value })\n   .GroupBy(pair => pair.PairNum)\n   .Select(grp => grp.Select(g => g.value).ToArray())\n   .ToArray()	0
2780708	2780233	How can I avoid a specific string pattern from being replaced by Regex.replace ()	string content = "Pakistan is <a href=\" Pakistan is\">Pakistan an islamic country</a>";\nstring content2= Regex.Replace(content,@"\bPakistan\b", "India");\nstring content3 = Regex.Replace(content2, @"(?<=\<\s*a[^<]+)\bIndia\b(?=.*?\>)", "pakistan");        \nConsole.WriteLine(content3);	0
16574471	16568156	Cascade Update one-to-many with NHibernate	var newFoo = new Foo();\n    var newBar = new Bar();\n    var newSon = new Son();\n\n    _session.Save(newBar);\n\n    newSon.Bar = newBar;\n    newBar.Sons.Add(newSon);\n    Foo.Bar = newBar;	0
11876062	11875819	How can I use reflection to find which open generic argument on an open generic type implements a generic interface?	var genericArguments = typeof(ValueImplementation<,>).GetGenericArguments();\nvar implementedInterfaces = typeof(ValueImplementation<,>).GetInterfaces();\n\nforeach (Type _interface in implementedInterfaces) {\n    for (int i = 0; i < genericArguments.Count(); i++) {\n        if (_interface.GetGenericArguments().Contains(genericArguments[i])) {\n            Console.WriteLine("Interface {0} implements T{1}", _interface.Name, i + 1);\n        }\n    }\n}	0
21567155	21567122	How do I pass a "'" as part of an argument to a shell script?	myProcess.StartInfo.Arguments = @"C:\path\to\script.js title's";	0
31470183	31470125	Linq data from two table with aggregate functions	var query = from p in db.Products\n          where p.CategoryID = 1\n          select new {\n             Name = p.ProductName,\n             ImagePath = p.ImagePath,\n             TotalReviews = p.Reviews.Count()                \n          };\n\n    var results = query.ToList();	0
10287101	10287056	How to find a center of point3d array?	new Point3D(points.Average(p => p.X),\n            points.Average(p => p.Y),\n            points.Average(p => p.Z));	0
3864296	3863793	C# serialize large array to disk	StateInformation[] diskReady = GenerateStateGraph();\nBinaryFormatter bf = new BinaryFormatter();\nusing (Stream file = File.OpenWrite(@"C:\temp\states.dat"))\n{\n  foreach(StateInformation si in diskReady)\n    using(MemoryStream ms = new MemoryStream())\n    {\n      bf.Serialize(ms, diskReady);\n      byte[] ser = ms.ToArray();\n      int len = ser.Length;\n      file.WriteByte((byte) len & 0x000000FF);\n      file.WriteByte((byte) (len & 0x0000FF00) >> 8);\n      file.WriteByte((byte) (len & 0x00FF0000) >> 16);\n      file.WriteByte((byte) (len & 0x7F000000) >> 24);\n      file.Write(ser, 0, len);\n    }\n}	0
15369738	15361521	How do I exclude a property of all items in IEnumerable when using ShouldBeEquivalentTo?	subject.ShouldBeEquivalentTo(expected, config =>\n                config.Excluding(ctx => ctx.PropertyPath == "Level.Level.Text"));	0
10109588	10100994	How to get control with lower zindex when mouse clicked in wpf?	IsHitTestVisible = False	0
3719781	3719613	Display error if a treeview root node contains a child node	private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {\n        addNewToolStripMenuItem.Enabled = tvwACH.Nodes.Count > 1;\n    }	0
2325282	2325222	How can I trim a List<string> so preceding and succeeding blank lines are removed?	public static void TrimList(this List<string> list) {\n        while (0 != list.Count && string.IsNullOrEmpty(list[0])) {\n            list.RemoveAt(0);\n        }\n        while (0 != list.Count && string.IsNullOrEmpty(list[list.Count - 1])) {\n            list.RemoveAt(list.Count - 1);\n        }\n    }	0
7972941	7970186	Create a page programatically with C# in SharePoint 2007	PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);\n\nstring pageName = ?MyCustomPage.aspx?;\n\nPageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();\n\nPageLayout currPageLayout = pageLayouts[0];\n\nPublishingPageCollection pages = publishingWeb.GetPublishingPages();\n\nPublishingPage newPage = pages.Add(pageName,currPageLayout);\n\nnewPage.ListItem[FieldId.PublishingPageContent] = ?This is my content?;\n\nnewPage.ListItem.Update();\n\nnewPage.Update();\n\nnewPage.CheckIn(?This is just a comment?);	0
25979613	25979543	Cannot find stored procedure	string strSQL = "StP_Map_Preload";	0
24250894	24250538	Do action until specific time in C#	_cc.Turn = 50; //the C motor will start running in 50% speed\n\n    _cc.LeftSpeed = 0; //the B motor will stop working\n    _cc.RightSpeed = 0; //the A motor will stop working\n\n    _cc.MoveCar();\n\n    System.Threading.Thread.Current.Sleep(1000);	0
7073937	7073213	Can you tell me some ways for this model in UI WPF?	public class WebPage\n{\n    public string Href { get; set; }\n    public string PageTitle { get; set; }\n    public List<WebPage> LinksInPage { get; set; }\n}\n\npublic class Root\n{\n    public string Title { get; set; }\n    public string Url { get; set; }\n    public List<WebPage> WebPages { get; set; }\n}\n\n\n    <HierarchicalDataTemplate DataType="{x:Type data:Root}"\n                              ItemsSource="{Binding Path=WebPages}">\n                <TextBlock Text="{Binding Title}"></TextBlock>\n    </HierarchicalDataTemplate>\n\n    <HierarchicalDataTemplate DataType="{x:Type data:WebPage}"\n                              ItemsSource="{Binding Path=LinksInPage}">\n                <TextBlock Text="{Binding PageTitle}"></TextBlock>\n    </HierarchicalDataTemplate>	0
15615275	15569433	Programmatically identifying file type associations in Windows Store app?	var document = XDocument.Load("AppxManifest.xml");\nvar xname = XNamespace.Get("http://schemas.microsoft.com/appx/2010/manifest");\n\nvar fileTypeElements = \n    document.Descendants(xname + "FileTypeAssociation").Descendants().Descendants();\nvar supportedFileExtensions = \n    fileTypeElements.Select(element => element.Value).ToArray();	0
13950035	13337254	Connect to 9gag with HttpClient	Cookie cookie = new Cookie();\n\n        cookie.Domain = "9gag.com";\n\n        cookie.Name = "ts1";\n\n        cookie.Value = "VALUEOFTHISCOOKIE";\n\n        this._Cookies.Add(new Uri("http://9gag.com"), cookie);	0
11261921	11261750	Create a global available array by the size of an updown	if (series.Length > 0) { series = new string[numericUpDown1.Value]; }	0
29577965	29574833	Changing value of the listBox	listBox1.Items.Insert(listBox1.SelectedIndex, "new Value");\nlistBox1.Items.Remove(listBox1.SelectedItem);	0
34076542	34076404	Create selectlist from list from another list	where ur.RoleId == new Guid(Properties.Settings.Default.TechID)	0
7609946	7609800	How to subclass UIApplication in Monotouch?	[Register ("UIApplicationMain")]\n public class UIApplicationMain : UIApplication {\n    ...	0
4072069	4071914	C# DateTime to Javascript DateTime	sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "),");	0
20823338	20399676	breeze array , after push items, know in the server that array has changed	MultyProfilesList: {  \n         name: 'multyProfilesList'\n         complexTypeName: 'PersonAccessDTO:#myServer.Entities'\n         isPartOfKey: false,\n         isScalar: false\n       }	0
7645103	7645010	changing the colour of certain characters and count in RichTextBox	private void ColorTheKs()\n{\n    for(int i = 0; i< richTextBox1.Text.Length; i++)\n    {\n        if (richTextBox1.Text[i] == 'K')\n        {\n            richTextBox1.SelectionStart = i;\n            richTextBox1.SelectionLength = 1;\n            richTextBox1.SelectionColor = Color.Red;\n            richTextBox1.SelectionBackColor = Color.Yellow;\n        }\n    }\n}	0
21776290	21776179	How to set metadaType in two class	namespace Validation.Access\n{\n    [MetadataType(typeof(TransferModuleValidation))]\n    public partial class Sales { }\n\n    [MetadataType(typeof(TransferModuleValidation))]\n    public partial class Product { }\n\n    public partial class TransferModuleValidation\n    {\n        [MaxLength(3, ErrorMessage = "Must be less than or 3 characters")]\n        public string Currency { get; set; \n    }\n}	0
9831802	9831494	Reading byte array are inconsistent with writing byte array into File	provider.Padding = PaddingMode.PKCS7;	0
21485798	21485576	Alternative to Google Drive SDK with less dependencies	GET /plus/v1/people/me HTTP/1.1\nAuthorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg\nHost: googleapis.com	0
33809868	33809591	Assigning each column to corresponding checkbox	string sql = "SELECT * FROM bus_seats WHERE sefer_id = 1";\nusing (SQLiteCommand command = new SQLiteCommand(sql, connect))\n{\n     SQLiteDataReader reader = command.ExecuteReader();\n     while (reader.Read())\n     {\n         var seat = reader["seatNumber"].ToString();\n         var chk = string.Format("checkBox{0}", seat);\n\n         if (reader["seatTaken"].ToString() == "True")\n         {\n             ((CheckBox)form1.FindControl(chk)).BackColor = Color.CornflowerBlue;\n         }\n     }\n}	0
12432807	12432719	WebBrowser URI in Listbox	if (!radListControl1.Items.Contains(webBrowser1.Url.ToString()))\n     radListControl1.Items.Add(webBrowser1.Url.ToString());	0
21482357	21482285	Pass a method as a parameter to another method	private void MeasureTime(Action m)\n    {\n        var sw = new System.Diagnostics.Stopwatch();\n        sw.Start();\n        m();\n        sw.Stop();\n        ShowTakenTime(sw.ElapsedMilliseconds);\n    }	0
17974638	17972268	Async/Await with a WinForms ProgressBar	public void GoAsync() //no longer async as it blocks on Appication.Run\n{\n    var owner = new Win32Window(Process.GetCurrentProcess().MainWindowHandle);\n    _progressForm = new Form1();\n\n    var progress = new Progress<int>(value => _progressForm.UpdateProgress(value));\n\n    _progressForm.Activated += async (sender, args) =>\n        {\n            await Go(progress);\n            _progressForm.Close();\n        };\n\n    Application.Run(_progressForm);\n}	0
2604591	2490577	Suppress task switch keys (winkey, alt-tab, alt-esc, ctrl-esc) using low-level keyboard hook	bool ControlDown = (GetKeyState(VK_CONTROL) & 0x8000) != 0;\nif (lParam.Key == VK_ESCAPE && ControlDown)\n    suppress = true;	0
14872973	14815576	NHibernate - map interface or abstract component with mapping-by-code/Conformist	Component<HashedPassword>(x => x.Password, comp =>\n{\n    comp.Map(x => x.Hash);\n    comp.Map(x => x.Salt);\n});	0
7916963	7916551	SelectCommand with Parameters provides empty result	DECLARE @queryString VARCHAR(3000)\n\nSET @queryString ='SELECT id, '+@FROM+' AS from, '+@TO+' AS to FROM Dictionary WHERE +'@FROM+' LIKE %'+@SEARCHSTRING+'%'	0
18740135	18739827	Not able re-login after session timeout in asp.net mvc4 application	url: 'Main/BoolLogin',	0
17513942	17513842	C# - Storing a struct inside a struct of same type	public struct Vector3\n{\n    float x,y,z;\n    public Vector3 Normalized \n    { \n        get \n        { \n            ... build the normalized struct and return it ... \n        } \n    }\n}	0
19969207	19968322	Redirect from .aspx url to .aspx page	routes.MapPageRoute("aspx-redirection", "{page}.aspx", "~/aspx/{page}.aspx");	0
14951947	14725934	C# Enable/disable Windows 7 / Windows 7 Embedded Firewall	result = (fwPolicy2.get_FirewallEnabled(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC));	0
32495638	32494163	Alter a list of strings based on the items	private List<string[]> FilterData(List<string[]> datatable)\n    {\n        // List is made of String Array, so need string[] variable not list\n        string[] previousRow = null ;\n        string[] currentRow;\n        string[] rowDifferences ;\n\n        // to store the result\n        List<string[]> resultingDataset = new List<string[]>();\n\n        foreach (var item in datatable)\n        {\n            if (previousRow == null)\n            {\n                previousRow = item;\n                resultingDataset.Add(previousRow); // add first item to list\n                continue;\n            }\n\n            currentRow = item; \n\n            // check and replace with "-" if elment exist in previous \n            rowDifferences = currentRow.Select((x, i) => currentRow[i] == previousRow[i] ? "-" : currentRow[i]).ToArray();  \n            resultingDataset.Add(rowDifferences);\n\n            // make current as previos\n            previousRow = item;\n        }\n        return resultingDataset;\n    }	0
15773634	15773435	Set child's Visible=false but keep AutoScrollbars of parent	panel1.AutoScroll = false;\npanel1.AutoScrollMinSize = new Size(panel2.Right, panel2.Bottom);	0
12453117	12452995	Reflection with Datagridview	Type commonType = typeof(PointCommonInformation);\n\nforeach (PropertyInfo item in commonType.GetProperties())\n{\n        object propertyObject = item.GetValue(pointCommonInfo, null);\n        string propertyValue = propertyObject == null ? string.Empty : propertyObject.ToString();\n        DGVPointCtrl.Rows[j].Cells[item.Name].Value = propertyValue;    \n}	0
8521095	8521026	how to replace a string ignoring case?	var regex = new Regex( str, RegexOptions.IgnoreCase );\nvar newSentence = regex.Replace( sentence, "new value" );	0
11489189	11489181	Opening a preexisting Form	Form2 newForm = new Form2();\nnewForm.Show();	0
25137970	25132664	How can I get same value in windows and web project with ToString() function?	104.2677519379845M.ToString()	0
9236271	9226108	How to find an XML node from a line and column number in C#?	XNode FindNode(string path, int line, int column)\n{\n    XDocument doc = XDocument.Load(path, LoadOptions.SetLineInfo);\n    var query =\n        from node in doc.DescendantNodes()\n        let lineInfo = (IXmlLineInfo)node\n        where lineInfo.LineNumber == line\n        && lineInfo.LinePosition <= column\n        select node;\n    return query.LastOrDefault();\n}	0
15276872	15256451	How to calculate the coordinates of the 4 corners (edge) of the map with BingMap?	//Position, decimal degrees\n lat = 46.6023\n lon = 7.0964\n\n //Earth???s radius, sphere\n R=6378137\n\n // DO THE SAME FOR B C D\n\n //offsets in meters for A\n dn = -47600\n de = -47600\n\n //Coordinate offsets in radians\n dLat = dn/R                      // -0.0074629942881440144669203562106\n dLon = de/(R*Cos(Pi*lat/180))    // -0.00746374633301685016002447644032\n\n //OffsetPosition, decimal degrees\n latA = lat + dLat * 180/Pi // 46.174701924759107796879309401922\n lonA = lon + dLon * 180/Pi // 6.6687588357618898589751458712973	0
28568479	28568281	Dock.Left/Right breaks simple docking based layout	Panel panel = new Panel { AutoSize = false, Dock = DockStyle.Bottom };	0
3073867	3073856	C# Regex Replace How to append text to end of each line(C#)	string newString = oldString.Replace("\r\n", "Text\r\n");	0
5809776	5809596	Winforms: how to open combobox properly?	private void comboBox1_enter(object sender, EventArgs e)\n      {\n         comboBox1.DroppedDown = true;\n      }	0
15033094	15033023	White space padding in WebBrowser control	string captcha = "<style>html, body {{ padding: 0; margin: 0 }}</style><img src=\"http://www.reddit.com/captcha/{0}/.png\" border=\"0\"></img>";\nwebBrowser1.DocumentText = String.Format(captcha, iden);	0
23092207	23092115	Showing a messagebox the moment the user clicks out of the textbox	private void Button_Click(object sender, RoutedEventArgs e)\n      {\n            name = textbox_Name.Text;\n            age = textbox_age.Text;\n            gender = textbox_gender.Text;\n            if (gender != "World" || name != "World" || age!="World" )\n            {\n                MessageBox.Show("Invalid Entry.");\n            }         \n       }	0
23407509	23407430	Readline split by anything else than letters	string line = Console.ReadLine();\nstring[] segments = Regex.Split(input: line, pattern: "\W");	0
2579629	2579598	Lambda expression will not compile	(DateTime p1, DateTime p2) => ...	0
21198763	21198708	joining statement with linqdatasource	//Change following variables accordingly\nvar ctx = new YourDbContext();\nvar id = 3;\n\nfrom tblWeekDays in ctx.WeekDays\njoin tblDayTimes in ctx.DayTimes\non tblWeekDays.WeekDayId == tblDayTimes.WeekDayId\nwhere tblWeekDays.classID == id\nselect new\n{\n    WeekDay = tblWeekDays.WeekDay,\n    TimeFrom = tblDayTimes.TimeFrom,\n    TimeTo = tblDayTimes.TimeTo\n};	0
10278408	10278151	How do I use group by in LINQ?	var query =\n    from t in db.tableName    \n    group t by new { t.column1, t.column2 } into g\n    select new { g.Key.column1, g.Key.column2 };	0
11855164	10217558	Nhibernate QueryOver - Performing a Has All for a Many-to-Many relationship	Part part =  null;\nCar car = null;\nvar qoParts = QueryOver.Of<Part>(() => part)\n                .WhereRestrictionOn(x => x.PartId).IsIn(partIds)\n                .JoinQueryOver(x => x.Cars, () => car)\n                .Where(Restrictions.Eq(Projections.Count(() => car.CarId), partIds.Length))\n                .Select(Projections.Group(() => car.CarId));	0
16096468	16096283	How to increment a number and output to label	private void checkWord()\n{\n    if (txtInput.Text.ToLower().Trim() == lblQuery.Text.ToLower())\n    {\n        score++;\n    }\n}	0
2280571	2279795	how to get nearest point on a SqlGeometry object from another SqlGeometry object?	declare @g geometry = 'LINESTRING(0 0, 10 10)' \ndeclare @h geometry = 'POINT(0 10)' \n\nselect @h.STBuffer(@h.STDistance(@g)).STIntersection(@g).ToString()	0
31706430	31706162	How to get buildnumber / revision from Assembly? (4th digit)	public static Version GetAssemblyVersion (Assembly asm)\n{\n    var attribute = Attribute.GetCustomAttribute(asm, typeof(AssemblyFileVersionAttribute), true) as AssemblyFileVersionAttribute;\n    return new Version(attribute.Version);\n}	0
31974591	31974369	Adding parameters to stored procedure in C# with AddWithValue method	SqlCommand sqlCmd = new SqlCommand();\n   sqlCmd.CommandTimeout = 15;\n   sqlCmd.CommandType = CommandType.StoredProcedure;\n   sqlCmd.CommandText = "updateSalesReps"	0
2258609	2244118	C# How to get the send of behalf email address in outlook add-in	using System;\nusing System.Runtime.InteropServices;\nusing System.Diagnostics;\nusing System.Reflection;\n\nnamespace Helpers\n{\n    internal class EmailHelper\n    {\n        public static string GetSenderEmailAddress(Microsoft.Office.Interop.Outlook.MailItem mapiObject)\n        {\n            Microsoft.Office.Interop.Outlook.PropertyAccessor oPA;\n            string propName = "http://schemas.microsoft.com/mapi/proptag/0x0065001F";\n            oPA = mapiObject.PropertyAccessor;\n            string email = oPA.GetProperty(propName).ToString();\n            return email;\n        }\n    }\n}	0
4684525	4684493	using key/value collection in session	Dictionary<TKey, TValue>	0
4356078	4354206	Need expert's comment on deciding DB storage or file base	Please make this decision for me. THANKS THANKS	0
29778335	29776021	Avoid namespace for nested member xml serialisation	[XmlElement("REQUEST")]\n[XmlElement(Type = typeof(AuthenticateRequest))]\n    public Request.BaseRequest Request\n    {\n        get;\n        set;\n    }	0
25510632	25510270	Delete elements from a JSON	var names = new List<string>(){"@wetLease","mealCodes" , "@operatedBy"};\n\nvar jObj = JObject.Parse(json);\n\njObj.Descendants().OfType<JProperty>()\n    .Where(p=>names.Contains(p.Name))\n    .ToList()\n    .ForEach(p=>p.Remove());\n\nvar newjson = jObj.ToString();	0
13673849	13672864	Azure - Accessing the same blob from worker role as in web role	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(\n    CloudConfigurationManager.GetSetting("MyStorageAccount"));	0
25304587	25218753	Transfer ownership of Google Drive documents	var initializer = new ServiceAccountCredential.Initializer(ServiceAccountId)\n        {\n            Scopes = scope,\n            User = AdminEmail1\n        };\n\n        var credential = new ServiceAccountCredential(initializer.FromCertificate(certificate));\n\n        var driveService = new DriveService(new BaseClientService.Initializer()\n        {\n            HttpClientInitializer = credential,\n            ApplicationName = ApplicationName\n        });	0
2497619	2497538	How is this Nested Set SQL query converted into a LINQ query?	var query = from node in nested_category\n            from parentNode in nested_category\n            where node.lft >= parentNode.lft && node.rgt <= parentNode.rgt\n                 && node.name == "FLASH"\n            orderby parent.left\n            select parent.name;	0
18881090	18406839	send data from standby application to active application	SendKeys.Send("your text");	0
8704873	8704161	C# array within a struct	class Record\n{\n    char[] name;\n    int dt1;\n}\nclass Block {\n    char[] version;\n    int  field1;\n    int  field2;\n    RECORD[] records;\n    char[] filler1;\n}\n\nclass MyReader\n{\n  BinaryReader Reader;\n\n  Block ReadBlock()\n  {\n    Block block=new Block();\n    block.version=Reader.ReadChars(4);\n    block.field1=Reader.ReadInt32();\n    block.field2=Reader.ReadInt32();\n    block.records=new Record[15];\n    for(int i=0;i<block.records.Length;i++)\n      block.records[i]=ReadRecord();\n    block.filler1=Reader.ReadChars(24);\n    return block;\n  }\n\n  Record ReadRecord()\n  {\n    ...\n  }\n\n  public MyReader(BinaryReader reader)\n  {\n    Reader=reader;\n  }\n}	0
3780060	3780007	Forbidden to browse WCF svc file?	servicemodelreg ???ia	0
2118437	2118413	How to send the mail from c#	try\n{\n SmtpMail.Send(oMailMessage);\n}\ncatch (Exception ex)\n{\n//breakpoint here to determine what the error is:\nConsole.WriteLine(ex.Message);\n}	0
2435384	2435367	how to place - in a string	String value = "8329874566";\n\nString Result = value.Substring(0,3) + "-" + value.Substring(3,2) + "-" + value.Substring(6);	0
4843182	4843031	Unsafe Int32 pointer to a Byte[] array	byte[] bgImageBytes = new byte[1000];\nunsafe\n{   \n   // Make a byte pointer to the byte array\n   fixed (byte* bgImgPtr = bgImageBytes)   {\n      // Make a UInt32 pointer to the byte pointer\n      UInt32* bgImgIntPtr = (UInt32*)bgImgPtr;\n   }\n}	0
30604240	30603540	Split string input into jagged array	string[][] AdvListKeys = key.Split(',')\n                            .Select(o => o.Split('|'))\n                            .ToArray();	0
5997905	5997600	How to edit an individual cell in a datagrid?	col4.IsReadOnly = true	0
32387621	32387330	Checking a Property of an Object In a Queue	foreach (Test tests in submittedTest)\n{\n    if (tests.Name == tempName)\n    {\n        System.Windows.Forms.MessageBox.Show("Your score was --");\n    }\n}	0
13476709	13474398	Duplicate groups in ListView designer	class MyListView : ListView {\n    protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n        if (this.DesignTime && this.Groups.Count == 0) {\n            // Add the groups here\n            //...\n        }\n    }\n}	0
4327352	4300169	Change button background	Uri dir = new Uri("red_flag.png", UriKind.Relative);\nImageSource source = new System.Windows.Media.Imaging.BitmapImage(dir);\nImage image = new Image();\nimage.Source = source;\nStackPanel stack = new StackPanel();\nstack.Children.Add(image);\nmyButton.Content = stack;	0
32642136	32642135	WebApi2 Controller using Json.NET failing to deserialize single property	using Newtonsoft.Json;\n\npublic class Deliverable\n{\n    [JsonProperty(Required = Required.Always)]\n    public decimal EstimatedCost { get; private set; }\n}	0
9729184	9728424	Converting image into data:image/png;base64 for web page disaplay	imgCtrl.Src = @"data:image/gif;base64," + Convert.ToBase64String(File.ReadAllBytes(Server.MapPath(@"/images/your_image.gif")));	0
12555593	12555040	GetElementById from HttpWebResponse	string html = @"<form action=""/file.php"" method=""post"">\n                <input name=""abc"" id=""abc"" type=""hidden"" value=""some_random_value"" />\n                </form>";\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\n//Xpath\nvar value1 = doc.DocumentNode.SelectSingleNode("//input[@id='abc']")\n                             .Attributes["value"].Value;\n\n//Linq\nvar value2 = doc.DocumentNode.Descendants("input")\n                .First(i => i.Attributes["id"] != null && \n                            i.Attributes["id"].Value == "abc")\n                .Attributes["value"].Value;	0
16889150	16863723	Search an Object list for duplicate keys, and place string values into a string array	// Get a new list of unique items to add our duplicated items to\nList<SearchValue<Byte>> finalSearchItems = (from x in searchValues\n                            group x by x.ItemId into grps\n                            orderby grps.Key\n                            where grps.Count() == 1\n                            select grps).SelectMany(group => group).ToList();\n\nbyte[] duplicateIds = (from x in searchValues\n             group x by x.ItemId into grps\n             where grps.Count() > 1\n             select grps.Key).ToArray();\n\n// Smash the string 'Value' into 'Values[]'\nforeach (byte id in duplicateIds)\n{\n    SearchValue<Byte> val = new SearchValue<byte>();\n    val.ItemId = id;\n    // Smash\n    val.Values = (from s in searchValues\n              where s.ItemId == id\n              select s.Value).ToArray();\n    finalSearchItems.Add(val);\n}	0
10828384	10819306	How can I cast an expression from type interface, to an specific type	public List<IFoo> GetFoos<T>(Expression<Func<T, bool>> predicate) where T : class, IModel \n{\n    var result = new List<IFoo>();\n    var repository = new Repository<T>();\n    result.AddRange(repository.GetEntities(predicate).ToList().ConvertAll(c => (IFoo)c));\n    return result;\n}	0
17803328	17803247	How to creat a new list from existing list with elements which contains the same id in Linq to object?	list.GroupBy(x => new { x.RefId, x.RefName })\n    .Select(g => new TestNew() {\n        RefId = g.Key.RefId,\n        RefName = g.Key.RefName,\n        ListGroup = g.Select(y => new Group() {\n            ID = y.ID,\n            Name = y.Name\n        }).ToList()\n    }).ToList();	0
8505113	8504598	ByRef parameters with Expression trees in C#	private static Func<int> Wrap(MyDelegate dele)\n    {\n        var fn = dele.Method;\n        var result = ParameterExpression.Variable(typeof(int));\n        var block = BlockExpression.Block(\n            typeof(int),\n            new[] { result },\n            new Expression[]\n            {\n                Expression.Call(fn, result),\n                result,\n            });\n        return Expression.Lambda<Func<int>>(block).Compile();\n    }	0
26839745	26839654	Append to a json file in windows application	string ans = JsonConvert.SerializeObject(tempDate, Formatting.Indented);\nif (File.Exists(@"E:\" + " device.json")\n  File.AppendAllText(@"E:\" + " device.json", appendText);\nelse\n  System.IO.File.WriteAllText(@"E:\" + " device.json", ans);	0
20216527	20216074	VB6 to VB.NET conversions button stlye	Enable Visual Styles	0
23217017	23198538	LinkText not working when you have a link with text-transform set to uppercase	By.LinkText	0
32606203	32606117	Change Name of a Control within a command	private Control _previousControl	0
14806385	14806253	Can I create an xml file at a specified location using XElement?	x.Save(@"D:\DirectoryName\Data.xml");	0
21675303	21675072	Linq Join using Lambda in VB.NET	Dim marketValues = req.SelectedAccounts.Join(assetAllocations, \n                                             Function(a1) a1.ModelCode, \n                                             Function(a2) a2.APLID, \n                                             Function(a1, a2) New With { a1, a2 }) _\n                                       .Select(Function(o) New With \n                                       { \n                                            Key .MarketValue = o.a1.MarketValue, _\n                                            Key .AssetAllocationName = o.a2.AssetAllocationName, _\n                                            Key .AccountID = o.a1.AccountID, _\n                                            Key .Weight = o.a2.Weight, _\n                                            Key .MarketValueWeight = ((o.a1.MarketValue * o.a2.Weight) / 100) \n                                        }).ToList()	0
2571394	2571378	how to parse a UUID in C#	Guid responseId = new Guid(id.Replace("-", ""));	0
22753591	22749032	Data not coming in dataset	scmd.Parameters.AddWithValue("@ttl",ttl);	0
28920063	28918006	Mocking a tree data structure	public static bool isBalanced(Node root){\n\n        if(root==null){\n            return true; \n        }\n        else{\n            int lHight = root.left.height();\n            int rHight = root.right.height();\n            if(Math.Abs(lHight - rHight) > 1)\n            {\n                return false;\n            }\n\n            return isBalance(root.left) && isBalance(root.right);\n\n        }\n    }	0
28514262	28489338	Limiting List Iterations in a For Loop (Closest To Player)	class ColliderManager\n{\n    Dictionary<TKey, Collider> colliders;\n    Dictionary<Vector2, List<TKey>> collidersByChunks;\n\n    public void AddCollider(TKey pKey, Collider pCOllider)\n    {\n        this.colliders.Add(pKey, pCollider);\n\n        foreach(Vector2 chunkCoord in this.GetChunkCoords(pCollider.Rectangle))\n        {\n            List<TKey> collidersAtChunk = null;\n            if(!this.collidersByChunks.TryGetValue(chunkCoord, out collidersAtChunk))\n            {\n                collidersAtChunk = new List<TKey>();\n                this.collidersByChunks.Add(chunkCoords, collidersAtChunk);\n            }\n\n            collidersAtChunk.Add(pKey, pCollider);\n        }\n    }\n\n    private Vector2[] GetChunkCoords(Rectangle pRectangle)\n    {\n        // return all chunks pRectangle intersects\n    }\n}	0
23051370	23048285	How to call async method in constructor?	async void	0
17989890	17989169	Can I find out if no threads are waiting for a Semaphore?	private static SemaphoreSlim semPool = new SemaphoreSlim(3, 3);\n\nsemPool.Wait(cts.Token);\n\npublic static void CancelAllDownloads()\n    {\n        cts.Cancel();\n        cts = new CancellationTokenSource();\n    }	0
19477876	19477302	Order list where date is string	var temp = (from e in myList.Dates\n                    orderby DateTime.Parse(e.Date)\n                    select e\n                   ).ToList();\n  myList.Dates = temp;	0
12742080	12729267	C# - Insert Multiple Records at once to AS400	using (iDB2Connection connection = new iDB2Connection(".... connection string ..."))\n        {\n            // Create a new SQL command\n            iDB2Command command = \n                new iDB2Command("INSERT INTO MYLIB.MYTABLE VALUES(@COL_1, @COL_2", connection);\n\n            // Initialize the parameters collection\n            command.DeriveParameters();\n\n            // Insert 10 rows of data at once\n            for (int i = 0; i < 20; i++)\n            {\n                // Here, you set your parameters for a single row\n                command.Parameters["@COL_1"].Value = i;\n                command.Parameters["@COL_2"].Value = i + 1;\n                // AddBatch() tells the command you're done preparing a row\n                command.AddBatch();\n            }\n\n            // The query gets executed\n            command.ExecuteNonQuery();\n        }\n    }	0
32071207	32067626	Cast non-pointer to pointer type in fixed expression	&viewScaleDesc	0
13745024	13744784	How to convert a List<T> into a Dictionary<> using a T property as key and rest of properties as List<T1>	productsPerPeriodPerCategory =\n        groupedProducts\n            .GroupBy(p => p.categoryId)\n            .ToDictionary(\n                g => g.Key,\n                g =>\n                g.Select(\n                    r =>\n                    new Data {xValue = r.prodDate, yValue = r.amount.ToString()}));	0
19219323	19209240	How to set the back color of the header in a radGridView	private void radGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e)\n{\n    if (e.CellElement is GridHeaderCellElement)\n    {\n        if (e.CellElement.Text == "Your header cell text") //checking for the text in header cell\n        {\n            e.CellElement.DrawBorder = true;\n            e.CellElement.DrawFill = true;\n            e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid;\n            e.CellElement.BackColor = Color.Green;\n            e.CellElement.ForeColor = Color.Red;\n        }\n    }\n}	0
1254688	1254600	Retrieve Html attributes using Regex	\<(?<tag>[a-zA-Z]+)( (?<name>\w+)="?(?<value>\w+)"?)*\>	0
32595734	32595414	Time for a command to be executed	System.Threading.Thread t = new System.Threading.Thread(delegate()\n{\n    try\n    {\n        DateTime cmdStartTime = DateTime.UtcNow;\n        instrument = programmer.GetInstrument(_address);\n        DateTime cmdEndTime = DateTime.UtcNow;\n\n        TimeSpan totalCmdRuntime = cmdEndTime - cmdStartTime;\n        Debug.WriteLine(String.Format("Programmer.GetInstrument({0}) command took {1} mSec to execute", _address, totalCmdRuntime.TotalMilliseconds));\n    }\n    catch { }\n});\nt.Name = "GetInstrumentTimer";\nt.Start();	0
32753968	32753954	How to loop through an array of checkbox	foreach(var checkedItem in myCheckBoxArray.Where(item => item.Checked))\n{\n    MessageBox.Show(checkedItem);\n}	0
27546496	27545754	sending a data table with outlook API in C#	StringBuilder table = new StringBuilder();                    \n                    table.Append("<table style=\"width:100%\">\n<tr>\n");\n                    int columnsCount = dtData.Columns.Count;\n                    foreach (DataColumn column in dtData.Columns)\n                    {\n                        table.Append("<td>" + column.ColumnName + "</td>\n");\n                    }\n                    table.Append("</tr>\n");\n                    foreach (DataRow row in dtData.Rows)\n                    {\n                        table.Append("<tr>\n");\n                        for (int i = 0; i < columnsCount; i++)\n                        {\n                            table.Append("<td>" + row[i] + "</td>\n");\n                        }\n                        table.Append("</tr>\n");\n                    }\n                    table.Append("</table>\n");\n\n                    //use table as your messagebody into given code	0
33159970	33159310	Find related id from array in C#	private Pet[] SetDuplicateTo(Pet[] pets)\n{\n    int currentDupNumber = 1;\n    foreach (var pet1 in pets)\n    {\n        if (pet1.DuplicateTo > 0) { continue; }\n        var relatedPets = (from p in pets where pet1.RelatedTo.Split(',').Select(r => r.Trim()).Contains(p.id.ToString()) select p).ToList();\n        if (relatedPets.Count > 0)\n        {\n            pet1.DuplicateTo = currentDupNumber;\n            foreach (var pet2 in relatedPets)\n            {\n                pet2.DuplicateTo = currentDupNumber;\n            }\n        }\n        currentDupNumber++;\n    }\n    return pets;\n}	0
13237858	13237705	How can I change the model without having to delete the database?	Prevent saving changes that require table re-creation	0
18390727	18390632	C# Program that converts decimal number to binary	Console.Write("Number = ");\nint n = int.Parse(Console.ReadLine());\nstring counter = "";\n\nwhile (n >= 1)\n{\n   counter = (n % 2) + counter;\n   n = n / 2;\n}\nConsole.Write(counter);	0
17700567	17700505	Send parameter with accentuation c#	myParam4.Value = HttpUtility.HtmlDecode(row.Cells[0].Text);	0
17826709	17825451	how to get saved queries in tfs 2012 using c#	var project = workItemStore.Projects[selectedProject];\n        QueryHierarchy queryHierarchy = project.QueryHierarchy;\n        var queryFolder = queryHierarchy as QueryFolder;\n        QueryItem queryItem = queryFolder[folder];\n        queryFolder = queryItem as QueryFolder;\n        foreach (var item in queryFolder)\n        {\n            listQueries.Items.Add(item.Name);\n        }	0
5017959	5017877	Is it possible to loop through properties that have a certain DataAnnotation AND a certain value? .NET C#	// Check all properties for a dependency property attribute.\nconst BindingFlags ALL_PROPERTIES = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;\nvar matchingProperties = new Dictionary<PropertyInfo, DependencyPropertyAttribute>();\nforeach ( PropertyInfo property in m_ownerType.GetProperties( ALL_PROPERTIES ) )\n{\n    object[] attribute = property.GetCustomAttributes( typeof( DependencyPropertyAttribute ), false );\n    if ( attribute != null && attribute.Length == 1 )\n    {\n        // A correct attribute was found.\n        DependencyPropertyAttribute dependency = (DependencyPropertyAttribute)attribute[ 0 ];\n\n        // Check whether the ID corresponds to the ID required for this factory.\n        if (dependency.GetId() is T)\n        {\n            matchingProperties.Add(property, dependency);\n        }\n    }\n}	0
25108805	25107984	How to reduce same strings in a 'foreach'?	var runeTotals = new Dictionary<string, int>();\nforeach(RuneSlot runeSlot in rune.Slots)\n{\n    var runeName = staticApi.GetRune(RiotSharp.Region.lan, runeSlot.RuneId, RuneData.tags, Language.es_ES).Name;\n    if (runeTotals.ContainsKey(runeName))\n    {\n        runeTotals[runeName] += 1;\n        continue;\n    }\n    runeTotals.Add(runeName, 1);\n}\n\nforeach (var runeTotal in runeTotals)\n{\n    richTextBox1.Text = runeTotal.Value + "x " + runeTotal.Key + "\n" + richTextBox1.Text;\n}	0
15789118	15788372	page life cycle when OnServerValidate fails (custom validator)	var prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(EndRequest);\n\nfunction EndRequest(sender, args) {\n  functionX();\n}	0
9525759	9476681	CredUIPromptForCredentials forcing manual selection of user name	save = false	0
15548914	15548808	Linq RemoveAll removes all items	DataTable keepTheseRows = table.AsEnumerable()\n    .GroupBy(r => r.Field<int>("LinkId"))\n    .Select(g => g.First())  // takes the first of each group arbitrarily\n    .CopyToDataTable();	0
30077550	30077514	need help creating a using a derived textbox class in c#	class MyTextBox : TextBox\n{            \n     public MyTextBox()\n     {\n         //base.PropertyName = value;\n     }\n}	0
23443020	23427101	Mapping/Transformation to handle Enum model with LinqToExcel	MyEnumProperty = (MyEnumProperty)Convert.ToInt32(c["ColumnNameInExcel"])	0
4239396	4239254	C# Regular Expression need help	var s = "[['o_Module.Id'].Text]"; \n//"[Object[Key='o_Module.Id'].Text]"; //ALSO MATCHES THIS\nvar r = new System.Text.RegularExpressions.Regex(@"(\[?.*\[?')(.*)('.*)");\nvar m = r.Match(s);\nif (m.Success)\n{\n    //0 contains whole string\n    Console.WriteLine(m.Groups[2].Value); //Prints o_Module.Id\n}	0
11158416	11117372	Using Reflection to get static method with its parameters 	using System.Reflection;    \nstring methodName = "getLogon";\nType type = typeof(WLR3Logon);\nMethodInfo info = type.GetMethod(\n    methodName, \n    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);\n\nobject value = info.Invoke(null, new object[] { accountTypeId } );	0
6774840	6774558	How would I serialize XML with nested Elements into an object	XDocument dok = XDocument.Load(Server.MapPath("XMLFile.xml"));\n    XmlSerializer mySerializer = new XmlSerializer(typeof(Quiz));\n    TextReader TW = new StringReader(dok.ToString());\n    Quiz quizData= mySerializer.Deserialize(TW) as Quiz;	0
12053182	12052965	If status = 0 show this image in listBox	listBox.Controls.Add(new Label() { Text = "Status: ", Image = System.Drawing.Image.FromFile(status == "0" ? "succes.png" : status == "1" ? "warning.png" : "alarm.png") });	0
2533287	2531837	How can I get the PID of the parent process of my application	using System;\nusing System.Management;  // <=== Add Reference required!!\nusing System.Diagnostics;\n\nclass Program {\n    public static void Main() {\n        var myId = Process.GetCurrentProcess().Id;\n        var query = string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);\n        var search = new ManagementObjectSearcher("root\\CIMV2", query);\n        var results = search.Get().GetEnumerator();\n        results.MoveNext();\n        var queryObj = results.Current;\n        var parentId = (uint)queryObj["ParentProcessId"];\n        var parent = Process.GetProcessById((int)parentId);\n        Console.WriteLine("I was started by {0}", parent.ProcessName);\n        Console.ReadLine();\n    }\n}	0
25282601	11053865	How to make sure that my software is connected to the right server?	// Encoded RSAPublicKey\nprivate static String PUB_KEY = "30818902818100C4A06B7B52F8D17DC1CCB47362" +\n    "C64AB799AAE19E245A7559E9CEEC7D8AA4DF07CB0B21FDFD763C63A313A668FE9D764E" +\n    "D913C51A676788DB62AF624F422C2F112C1316922AA5D37823CD9F43D1FC54513D14B2" +\n    "9E36991F08A042C42EAAEEE5FE8E2CB10167174A359CEBF6FACC2C9CA933AD403137EE" +\n    "2C3F4CBED9460129C72B0203010001";\n\npublic static void Main(string[] args)\n{\n  ServicePointManager.ServerCertificateValidationCallback = PinPublicKey;\n  WebRequest wr = WebRequest.Create("https://encrypted.google.com/");\n  wr.GetResponse();\n}\n\npublic static bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain,\n                                SslPolicyErrors sslPolicyErrors)\n{\n  if (null == certificate)\n    return false;\n\n  String pk = certificate.GetPublicKeyString();\n  if (pk.Equals(PUB_KEY))\n    return true;\n\n  // Bad dog\n  return false;\n}	0
13048880	13048857	How to track time between two button clicks in C# in a Windows form application?	public partial class Form1 : Form\n    {\n        Stopwatch stopwatch = new Stopwatch();\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n        private void button1_Click(object sender, EventArgs e)\n        {\n            stopwatch.Start();\n\n        }\n        private void button2_Click(object sender, EventArgs e)\n        {\n\n            stopwatch.Stop();\n            var milliSeocnds = stopwatch.ElapsedMilliseconds;\n            var timeSpan = stopwatch.Elapsed;\n        }\n    }	0
12580421	12580392	SELECT AS in Linq with WHERE clause	public IList<string> GetNames(int p_ID)\n{\n    return db.mytable.Where(c => c.ID_fk == p_ID)\n                     .Select(x => x.FirstName + " " + x.Surname)\n                     .ToList();\n}	0
11255492	11255446	ASP.NET enum dropdownlist validation	TypeDropDownList.Items.Add("Please Specify","");\n foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())\n {\n    TypeDropDownList.Items.Add(EnumToDropDown.GetEnumDescription(newPatient), newPatient.ToString());\n }	0
14416969	14416853	lock/Monitor with multiple threads	Asynchronous Procedure Calls	0
21618056	21616951	Get the current user, within an ApiController action, without passing the userID as a parameter	RequestContext.Principal	0
19861344	19861301	How to get number from string using Regex?	[0-9]+(-[0-9]+)*	0
24075425	24041519	How to get selected TreeViewItem items header?	TreeViewItem tvItem = null;\ntvItem = ContainGenerator.ContainerFromItem(myTreeView.SelectedItem) as TreeViewItem;\n\nMessageBox.Show(tvItem.Header);	0
9645043	9644909	How to set the font of only the selected child inside my mdiParent	Form.ActiveMdiChild	0
29560231	29560171	How do I properly bind TextBox Text with ViewModel Property	set { _filePath = value; OnPropertyChanged("FilePath"); }	0
29143697	29143561	Applying Style to DataGridCell programmatically with Converter	style2.Setters.Add(new Setter(TextBlock.ForegroundProperty, new Binding("Item.Dif"){Converter = new RedValues()} ))};	0
4623207	4622309	How to create a subquery Projection, give it an Alias, and sort by the Alias in NHibernate with the Criteria API	DetachedCriteria sum = DetachedCriteria.For(typeof(MasterAsset), "asset2")\n                    .SetProjection(Projections.Sum("PhysicCondition"));\n\nDetachedCriteria count = DetachedCriteria.For(typeof(MasterAsset), "asset3")\n                    .SetProjection(Projections.Count("PhysicCondition"));\n\nSession.CreateCriteria(typeof(MasterAsset), "asset1")\n                    .SetProjection(Projections.ProjectionList()\n                    .Add(Projections.Property("IDMasterAsset"), "IDAsset"))\n                    .Add(Subqueries.PropertyLt("PhysicCondition", sum))\n                    .Add(Subqueries.PropertyLe("PhysicCondition", count))\n                    .AddOrder(Order.Asc("IDAsset"))\n                    .List();	0
10516464	10516415	Give element name programmatically	TextBlock station = new TextBlock() { Name="Something" };	0
8973945	8971315	C# to MASM difficulity with FILETIME	invoke GetLocalTime,addr time\ninvoke SystemTimeToFileTime,addr time,addr fTime\n\nxor eax,eax\nxor ebx,ebx\n\nmov eax,fTime.dwLowDateTime\nmov ebx,fTime.dwHighDateTime\n\nsal ebx,32 ;shift HighDateTime left 32 bits\nadd ebx,eax ;add HighDateTime and LowDateTime together\n\nmov edx,ebx ;edx has the ticks?	0
7945094	7943278	Cast EF query result to extended type with extended property taken from EF query	public IEnumerable<RecentTag> GetRecentTags(int numberofdays)\n{\n    DateTime startdate = DateTime.Now.AddDays(-(numberofdays));\n\n    IEnumerable<RecentTag> tags = Jobs\n        .Where(j => j.DatePosted > startdate) // Can't use DateTime.Now.AddDays in Entity query apparently\n        .SelectMany(j => j.Tags)\n        .GroupBy(t => t, (k, g) => new RecentTag\n        {\n            TagID = k.TagID,\n            Name = k.Name,\n            Count = g.Count()\n        })\n        .OrderByDescending(g => g.Count)\n        .Select(a => a);\n\n    return tags;\n}	0
10625342	10625292	The string was not recognized as a valid DateTime. There is an unknown word starting at index 0	DateTime currentdate;\nint result;\ntry\n{\n  // EXAMPLE: 2012-04-15 15:23:34:123 \n  DateTime backupdate =\n     DateTime.ParseExact (\n       "yyyy-MM-dd HH:mm:ss:fff", //mind the casing\n       imageflowlabel.Text, \n       CultureInfo.InvariantCulture);\n  currentdate = System.DateTime.Now.AddHours(-2);    \n  result = currentdate.CompareTo(backupdate);\n}\ncatch (Exception ex)\n{\n  ...	0
17093006	17092994	How do I get the value of specific cells on a gridview based on checkbox selections on the same row?	foreach (GridViewRow row in gvShows.Rows)\n{\n    CheckBox chk = row.Cells[0].FindControl("chkCheckBox") as CheckBox;\n    if (chk != null && chk.Checked)\n    {\n        //Access the data written in cell\n        dataSource = row.Cells[1].Text; \n        //if you are using DataKeys in GridView, which I particularly like to do\n        //(and it's useful for data you do not dsiplay), you \n        //can access data like this:\n        showId = gvShows.DataKeys[row.RowIndex]["showId"].ToString()\n    }\n}	0
18993466	18993443	Simplify Retrieving Input Into Array	List<T>	0
3883357	3883324	Initialize runtime value-type array with specific value?	bool[] foo = Enumerable.Repeat(true, someVariable.Count)\n                       .ToArray();	0
2898481	2898321	find users that are following other users	ctx.Followers.Where(f => f.FollowedID == CurrentUser.UserId)\n             .Select(f => f.FollowerUser).Distinct()	0
12063880	12062474	Use Object Name as Link with ActionLink, Not Hard-coded Literal	grid.Column("Name", format: (item) => @Html.ActionLink((string)item.Name, "Edit", new { id = item.Id })	0
29396696	29320701	Reading from FTP Server randomly returns a blank text file	public void Update()\n{ \n  lock(lockObject)\n  {\n    if(CheckForInternetConnection())\n    {\n      if (DownloadFile(uri,path))\n      {\n        char[] charsToTrim = { '\r', '\n' };\n        string onlineFile = File.ReadAllText(path).TrimEnd(charsToTrim);\n        if (onlineConfigFile.Equals("") || onlineConfigFile == null)\n          MessageBox.Show("Downloaded file is empty");\n       //still do stuff here regardless of the message\n       //If the other user really do intend to delete the list\n      }\n    }\n  }\n}	0
12920153	12919784	How to programmatically discover whether the running application is installed?	private void CheckApplicationStatus() {\n    if (ApplicationDeployment.IsNetworkDeployed) {\n        // Do something that needs doing when the application is installed using ClickOnce.\n    } else {\n        // Do something that needs doing when the application is run from VS.\n    }\n}	0
7839959	7839342	ReportDocument serialization	public static byte[] SerializeToBytes<T>(T original)\n{\n    byte[] results;\n    using (MemoryStream stream = new MemoryStream())\n    {\n        BinaryFormatter binaryFormatter = new BinaryFormatter();\n        binaryFormatter.Serialize(stream, original);\n        stream.Seek(0, SeekOrigin.Begin);\n        results = stream.ToArray();\n    }\n\n    return results;\n}	0
25157478	25156915	Stop execution of a method c#	bool stop = false;\n\nforeach (string item in Processes)\n{\n    if (stop)\n        break;\n\n    //do-your-stuff\n\n    Application.DoEvents(); //this will force the winform app to handle events from the GUI\n}\n\n//Add an eventhandler to your stop-button\nprivate void stopButton_Click(System.Object sender, System.EventArgs e)\n{\n    stop = true;\n}	0
2737213	2737009	Fill WPF listbox with string array	string[] list = new string[] { "1", "2", "3" };\n\n    ObservableCollection<string> oList;\n    oList = new System.Collections.ObjectModel.ObservableCollection<string>(list);\n    listBox1.DataContext = oList;\n\n    Binding binding = new Binding();\n    listBox1.SetBinding(ListBox.ItemsSourceProperty, binding);\n\n    (listBox1.ItemsSource as ObservableCollection<string>).RemoveAt(0);	0
22045487	22045306	How do I determine if a device is a desktop browser?	var isMobile = {\n        Android: function() {\n            return navigator.userAgent.match(/Android/i);\n        },\n        BlackBerry: function() {\n            return navigator.userAgent.match(/BlackBerry/i);\n        },\n        iOS: function() {\n            return navigator.userAgent.match(/iPhone|iPad|iPod/i);\n        },\n        Opera: function() {\n            return navigator.userAgent.match(/Opera Mini/i);\n        },\n        Windows: function() {\n            return navigator.userAgent.match(/IEMobile/i);\n        },\n        any: function() {\n            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());\n        }\n    };\n\n    if(isMobile.any()){\n        // Mobile!\n    } else {\n        // It is desktop\n    }	0
11482736	11481971	validate keyboard input for ASCII and special charachters	public int CountChars(string value)\n        {\n            int result = 0;\n            foreach (char c in value)\n            {\n              if (c>127)\n                {\n                    result = result + 10; // For Special Non ASCII Codes Like "ABC??????"\n                }\n\n                else\n                {\n                    result++; // For Normal Characters Like "ABC"\n                }\n            }\n            return result;\n        }	0
2417908	2417866	How to continue from where I have been searching to find the index?	//...\nint indexend = message.IndexOf("h", index); \n//...	0
14508565	14508461	Data Annotation for virtual member?	public class LogViewModel\n{\n    public int LogID {set;get;}\n    public int UserID {set;get;}\n\n    [Display(Name = "Assignee")]\n    public string UserName {set;get;}\n}	0
32264976	32259017	Setting default position for new toolwindow in VsPackage	Style = VsDockStyle.MDI	0
1824648	1824601	How to get POST data as array with C#	public void ProcessRequest(HttpContext context)\n{\n    using (var reader = new StreamReader(context.Request.InputStream))\n    {\n        string postedData = reader.ReadToEnd();\n        foreach (var item in postedData.Split(new [] { '&' }, StringSplitOptions.RemoveEmptyEntries))\n        {\n            var tokens = item.Split(new [] { '=' }, StringSplitOptions.RemoveEmptyEntries);\n            if (tokens.Length < 2)\n            {\n                continue;\n            }\n            var paramName = tokens[0];\n            var paramValue = tokens[1];\n            var values = paramValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);\n            foreach (var value in values)\n            {\n                var decodedValue = context.Server.UrlDecode(value);\n                // Do something with the decoded value which corresponds to paramName\n            }\n        }\n    }\n}	0
7637711	7634723	Replace a substring in C#	private void button1_Click(object sender, EventArgs e)\n    {\n        string inputString = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]";\n        string replacementString = "Blah";\n        string pattern = @"\((.+?)\s+ago\)";\n        int backreferenceGroupNumber = 1;\n        string outputString = Replace(inputString, replacementString, pattern, backreferenceGroupNumber);\n        MessageBox.Show(outputString);\n    }\n\n    private string Replace(string inputString, string replacementString, string pattern, int backreferenceGroupNumber)\n    {\n        return inputString.Replace(Regex.Match(inputString, pattern).Groups[backreferenceGroupNumber].Value, replacementString);\n    }	0
29563286	29563106	How to get int from generics enum?	static void Main(string[] args)\n    {\n        DoSomething<ConsoleKey>();\n        Console.ReadKey(true);\n    }\n\n    public static T DoSomething<T>() where T : struct, IConvertible, IComparable, IFormattable\n    {\n        T pom1 = Enum.GetValues(typeof(T)).Cast<T>().Max();\n        Console.WriteLine(pom1);\n        //Cast to object to bypass bits of the type system...Nasty!!\n        int pom4 = (int)(object)pom1;\n        Console.WriteLine(pom4);\n        //Use Convert\n        int pom5 = Convert.ToInt32(pom1);\n        Console.WriteLine(pom5);\n        //Take advantage of passing a IConvertible\n        int pom6 = pom1.ToInt32(System.Globalization.CultureInfo.CurrentCulture);\n        Console.WriteLine(pom6);\n        return pom1;\n    }	0
6547643	6547381	How to select with omitting a specific child using XPath?	"/*/*/*[not(self::form)]"	0
3400914	3400205	XDocument to dataSet, my nested nodes are getting treated as new tables?	lstCountry.Items \n    .Cast<ListItem>() \n    .Where(i=> i.Selected) \n    .Select(x => new XElement("CountryCode", x.Value))	0
32848421	32846125	How refresh all values in a datagrid column?	for (Int32 i = 0; i <= Ele_Soc.Count - 1; i++) \n{\n    Ele_Soc.Item(i).Soc_cod = "Yes";\n    OnPropertyChanged("Ele_Soc");\n}\n\nObservableCollection<Model_Soc> Tmp = Ele_Soc;\nEle_Soc = null;\n\nOnPropertyChanged("Ele_Soc");\nEle_Soc= Tmp;\nOnPropertyChanged("Ele_Soc");	0
30896047	30895840	How to convert to LINQ Queries	foreach (var pair in dict.Where(pair => input.DealInputs.ContainsKey(pair.Key)))\n{\n    input.DealInputs[pair.Key] = pair.Value;\n}	0
31815756	31815574	Getting values from JSON objects using LINQ	string json1 = @"{'name':'NARM','options':['N','A', 'P']}";\nstring json2 = @"{'name':'NARM','options':['N','A']}";\n\nvar j1 = JObject.Parse(json1);\nvar j2 = JObject.Parse(json2);\n\nvar diff = j1["options"].Select(x => (string)x)\n            .Except(j2["options"].Select(x => (string)x))\n            .ToList();	0
29075782	29075560	Save a multi-line string to a text file on multiple lines	sw.Write(entity.comments.Replace("\n", "\r\n"));	0
11931131	11929305	Regular Expressions to find and replace text	var result =   Regex.Replace(text,@"(WEX_CI[\s][\da-zA-Z\.]+)","$1.NEW");	0
11436506	11435424	String escaping issue with Roslyn statement creation	var parseStatementArgument = @"var statement = Syntax.ParseStatement(@""Console.WriteLine (""""Hello {0}"""", parameter1);"");";\n    var st = Syntax.InvocationExpression(\n                                Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.IdentifierName("Syntax"), Syntax.IdentifierName("ParseStatement")))\n                                    .AddArgumentListArguments(\n                                        Syntax.Argument(Syntax.LiteralExpression(\n                                            SyntaxKind.StringLiteralExpression,\n                                            Syntax.Literal(\n                                                text: "@\"" + parseStatementArgument.Replace("\"", "\"\"") + "\"",\n                                                value: parseStatementArgument)\n                                )));	0
2298821	2298783	.NET Custom Xml Serialization	public class MyConfig\n{\n    [XmlElement] \n    public string ConfigOption { get; set; }\n    [XmlElement] \n    public MyUri SomeUri { get; set; }\n}\n\npublic class MyUri\n{\n    [XmlAttribute(Name="uri")]\n    public Uri SomeUri { get; set; }\n}	0
12527396	12527243	Having trouble with monodevelop	using System.IO;\nusing System.Net;\nusing System.Net.Security;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Text;\n\npublic class MyAwesomeProgram\n{\n    public MyAwesomeProgram() \n    {\n        ServicePointManager.ServerCertificateValidationCallback =\n                ValidateServerCertficate;\n    }\n\n    private static bool ValidateServerCertficate(object sender, X509Certificate certificate,\n        X509Chain chain, SslPolicyErrors sslpolicyerrors)\n    {\n        //This is where you should validate the remote certificate\n        return true;\n    }\n\n    public void FetchAwesomeStuff (string url) \n    {\n        var wr = WebRequest.Create (url);\n        var stream = wr.GetResponse().GetResponseStream ();\n        Console.WriteLine (new StreamReader (stream).ReadToEnd ());\n    }\n}	0
2387156	2387107	ASP.NET DropDownList with DataSource doesn't select any item	ddlTopics.SelectedValue = this.Page.Request.Url.PathAndQuery;\n\n    // Summary:\n    //     Gets the value of the selected item in the list control, or selects the item\n    //     in the list control that contains the specified value.	0
15799632	15799265	sorting a text file using bubble sort and IComparable Interface	private static void BubbleSort<T>(T[] list) where T : IComparable\n{\n    T temp;\n    bool isSorted = false;\n\n    while (!isSorted)\n    {\n        isSorted = true;\n        for (int i = 0; i < list.Length - 1; i++)\n        {\n            if (list[i].CompareTo(list[i + 1]) > 0)\n            {\n                temp = list[i];\n                list[i] = list[i + 1];\n                list[i + 1] = temp;\n                isSorted = false;\n            }\n        }\n    }\n}	0
2189672	2189658	ADO.NET: convert a DataTable to an array of DataRows	DataRow[] rows = myDataTable.Select();	0
1347193	1343874	Using loops to get at each item in a ListView?	private IEnumerable<ListViewSubItem> GetItemsFromListViewControl()\n{                      \n    foreach (ListViewItem itemRow in this.loggerlistView.Items)\n    {            \n        for (int i = 0; i < itemRow.SubItems.Count; i++)\n        {\n            yield return itemRow.SubItems[i]);\n        }\n    }\n}	0
9938164	9937466	How to use C# read the value of the TD?	WebBrowser web = new WebBrowser();\nweb.DocumentCompleted += (sender, args) =>\n    {\n        var result = web.Document\n            .GetElementsByTagName("input")\n            .Cast<HtmlElement>()\n            .Where(e => e.GetAttribute("name") == "ivcd_item")\n            .Select(e=>e.GetAttribute("value"))\n            .ToArray();\n    };\nweb.DocumentText = htmlstring;	0
20795593	17326111	How to get chart type of a particular chart using Open XML SDK?	private IEnumerable<Type> GetExcelChartTypes()\n        {\n            IEnumerable<Type> items = new List<Type>();\n            try\n            {\n                DocumentFormat.OpenXml.Drawing.Charts.LineChart linechart = new DocumentFormat.OpenXml.Drawing.Charts.LineChart();\n                items = Assembly.GetAssembly(linechart.GetType()).GetTypes().Where(S => S.Name.EndsWith("Chart"));\n            }\n            catch\n            {\n\n            }\n            return items;\n        }	0
18674383	18657976	Disable images in Selenium Google ChromeDriver	var options = new ChromeOptions();\n\n    //use the block image extension to prevent images from downloading.\n    options.AddExtension("Block-image_v1.0.crx");\n\n    var driver = new ChromeDriver(options);	0
5873713	5872507	Entity Framework 4.1 Mapping Relationships by setting Foreign Keys	[Key]\npublic int GroupId { get; set; }        \npublic int ParentGroupId { get; set; }	0
5030141	5030102	C# - Pass data back to view from ActionFilter via ViewData	AsQueryable()	0
34028432	34027994	How to close a sub form from another sub form without closing main form c#	private void OpenForm2(object sender, EventArgs e)\n{                        \n    var callingForm = sender as form1;\n    if (callingForm != null)\n       {\n           callingForm.Close();\n       }\n    this.Close();\n}	0
3602479	3601948	Generic method, unboxing nullable enum	Type t = typeof(Nullable<>).MakeGenericType(lEnumType);\n            var ctor = t.GetConstructor(new Type[] { lEnumType });\n            return (T)ctor.Invoke(new object[] { pObject });	0
5006261	5006107	Help Parsing a field using LINQ to XML	var  doc = XElement.Load("test.xml");\nvar results = doc.Descendants("Value").Where(x =>  \nx.Parent.Attribute("id").Value.StartsWith("Attribute")).Select(x => x.Value);	0
32212075	32211739	How to call unsafe code from ASP.NET xproj	{\n    "compilationOptions": { "allowUnsafe": true }\n}	0
3336406	3336186	Saving listbox items to file	Stream s;\nthis.sfd_Log.Filter = "Textfiles (.txt)|.txt";\nDialogResult d = this.sfd_Log.ShowDialog();\nif ((d == DialogResult.OK) && (this.lb_Log.Items.Count != 0))\n{\n    if ((s = this.sfd_Log.OpenFile()) != null)\n    {\n        StreamWriter wText = new StreamWriter(s);\n        for (int i = 0; i < this.lb_Log.Items.Count; i++)\n        {\n            wText.Write((this.lb_Log.Items[i]));\n        }\n        wText.Flush();\n        s.Close();\n    }\n}	0
126959	126925	How can I ensure a dialog will be modal when opened from an IE BHO?	IWebBrowser2 browser = siteObject as IWebBrowser2;\nif (browser != null) hwnd = new IntPtr(browser.HWND);\n(new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd));\n\n...\n\n// Wrapper class so that we can return an IWin32Window given a hwnd\npublic class WindowWrapper : System.Windows.Forms.IWin32Window\n{\n    public WindowWrapper(IntPtr handle)\n    {\n        _hwnd = handle;\n    }\n\n    public IntPtr Handle\n    {\n        get { return _hwnd; }\n    }\n\n    private IntPtr _hwnd;\n}	0
22011347	22009581	C# Icon in XAML	System.Windows.Media.ImageSource iconSource;\nusing (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath))\n{\n    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(\n    sysicon.Handle,\n    System.Windows.Int32Rect.Empty,\n    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());\n}\nreturn iconSource;	0
20601087	20601057	How to evaluate to false if one file is missing from a list of files	fileExists = true;\n    foreach(string fl in files)\n    {\n        if(!File.Exists(Path.Combine(Dir,fl)))\n        {\n           fileExists = false;\n           break;\n        }\n    }	0
3673037	3672941	Formatting Dates and DateTimes for User's timezone including Timezone Offset in C# (.net)	DateTimeOffset utcDto = new DateTimeOffset(utcDt, TimeSpan.Zero);\nDateTimeOffset localDateTime = TimeZoneInfo.ConvertTime(utcDto, localTimeZone);\nstring dateString = localDateTime.ToString("dd MMM yy - HH:mm:ss (zzz)");	0
3130521	3130491	How to avoid implementing INotifyPropertyChanged manually	abstract class Container : INotifyPropertyChanged\n{\n  Dictionary<string, object> values;\n\n  protected object this[string name]\n  {\n    get {return values[name]; }\n    set \n    { \n      values[name] = value;\n      PropertyChanged(this, new PropertyChangedEventArgs(name));\n    }\n  }\n}\n\nclass Foo : Container\n{\n  public int Bar \n  {\n    {get {return (int) this["Bar"]; }}\n    {set { this["Bar"] = value; } }\n  }\n}	0
26082148	26082036	write a c# program which accept a parameter as a particular date and give the output total number of days	DateTime dt = new DateTime();\n        int currentyear, currentmonth, borthmonth, birthyear, years, month;\n        dt = Convert.ToDateTime("1993-08-04");//here i assume you are taking date of birth\n        currentyear = Convert.ToInt32(DateTime.Now.Year);\n        currentmonth = Convert.ToInt32(DateTime.Now.Month);\n        birthyear = Convert.ToInt32(dt.Year);\n        borthmonth = Convert.ToInt32(dt.Month);\n        years = currentyear - birthyear;\n        if (currentmonth - borthmonth > 0)\n        {\n            month = Convert.ToInt32(currentmonth - borthmonth);\n        }\n        else\n        {\n            years = years - 1;\n            month = Convert.ToInt32((12 - borthmonth) + currentmonth);\n        }\n        Console.WriteLine(years.ToString() + "/" + month.ToString());// here i am printing the result into console	0
10733352	10423989	Get list of all Outlook folders and subfolders	foreach (MAPIFolder folder in olNS.Folders)\n{\n    GetFolders(folder);\n}\n\npublic void GetFolders(MAPIFolder folder)\n{\n    if (folder.Folders.Count == 0)\n    {\n         Console.WriteLine(folder.FullFolderPath);\n    }\n    else\n    {\n         foreach (MAPIFolder subFolder in folder.Folders)\n         {\n              GetFolders(subFolder);\n         }\n    }\n}	0
16664681	16664532	How to get IMG tag's source from given HTML string using c#	string html = .......\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\nvar link = doc.DocumentNode.SelectSingleNode("//img").Attributes["src"].Value;	0
25199340	25199317	How to check the current view mode of a fromview in code behind	protected void FormView_DataBound(object sender, EventArgs e)\n{    \n//Here I want to add codes only if the current view of the Formview is read only (neither insert nor edit modes).\n   if (FormView.CurrentMode == FormViewMode.ReadOnly)\n   {\n   }\n}	0
2819438	2819337	Parsing values from XML into types of Type	configProps[configurableProp.getName()] =\n        Convert.ChangeType(attValue, configPropType);	0
25895210	25880379	How do you make Speech to Text work in Windows (Phone) 8.1 Universal App	var synth = new SpeechSynthesizer();\n     var voice = SpeechSynthesizer.DefaultVoice;\n     var newuserText = TheMessage\n     var stream = await synth.SynthesizeTextToStreamAsync(newuserText);\n     var mediaElement = new MediaElement();\n     mediaElement.SetSource(stream, stream.ContentType);\n     mediaElement.Play();	0
7754790	7754569	How to Fill TextBoxes from DataGridView on Button Click Event	txt_EnrollNo.Text = this.dgv_EmpAttList.CurrentRow.Cells[1].Value.ToString();\ntxt_FirstInTime.Text = this.dgv_EmpAttList.CurrentRow.Cells[2].Value.ToString();	0
4221562	4220722	C# Regular expressions negative lookahead exclude from match	private void test()\n{\n    string t = @"<a href=""image-CoRRECTME.aspx?ALSO=ME&leaveme=<%= MyClass.Text %>&test2=<%= MyClass2.Text %>&last_test=nothing"">somelink</a>";\n    string fixed_string = Regex.Replace(t, "(?<=href=\"|href=\"[^\"]*%>)([^\"]*?)(?=<%|\")", TestMatchEvaluator);\n}\n\nprivate string TestMatchEvaluator(Match m)\n{\n    return m.Value.ToLower();\n}	0
11858846	11772001	Select Data from combo box and shows the information to it in List Box c#	private void Edit_TS_Load(object sender, EventArgs e)\n    {\n        using (satsEntities Setupctx = new satsEntities())\n        {\n            var DeleteRT = (from DelRT in Setupctx.requiredtimings\n                           join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID\n                           select new {ls.locStatname, DelRT.RequiredLocationStationID}).Distinct().ToList();\n\n            cbLocStation.DataSource = DeleteRT.ToList();\n            cbLocStation.DisplayMember = "locStatname";\n            cbLocStation.ValueMember = "RequiredLocationStationID";\n\n        }\n    }	0
22780161	22728470	How to Convert JSON Data into an Object?	public void SubmitCustomForm()\n{\n    List<string> theErrors = new List<string>();\n\n    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();\n    var dict = serializer.Deserialize<Dictionary<string, string>>(_Context.Request["formdata"]);\n\n    foreach (KeyValuePair<string, string> pair in dict)\n    {\n        theErrors.Add(pair.Key + " = " + pair.Value);\n    }\n\n    _Context.Response.Write(new\n    {\n        Valid = theErrors.Count == 0,\n        Errors = theErrors,\n        Message = "Form Submitted"\n    }.ToJson());            \n}	0
7915806	7915366	Linq to Entities - Left outer join with Lambda expression	var query =\nfrom nv in db.NewsVersion\njoin cp in db.ChangeProcess on nv.NewsId equals cp.DocumentId into joined\nfrom j in joined.Where(x => x.EndDate == null).DefaultIfEmpty()\nwhere nv.NewsId = "B2301B7F-D37E-4CF5-9392-01844564BFCC"\nselect new { NewsVersion = nv, ChangeProcess = j };	0
3826551	3822019	How can I find out, whether a certain type has a string converter attached?	public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString)\n{\n   // Checks to see if the value passed is valid.\n   return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))\n            .IsValid(aString);\n}	0
13134677	13123424	Get the PDF page that contains the PdfTextField	protected int PaginaCampo(string campofirma, PdfDocument document)\n{\n    for (int i = 0; i < document.Pages.Count; i++)\n    {\n        PdfAnnotations anotations = document.Pages[i].Annotations;\n        for (int j = 0; j < anotations.Count; j++)\n        {\n            if (anotations[j].Title != campofirma) continue;\n            return i;\n        }\n    }\n    return -1;\n}	0
6146689	6146640	How to iterate a C# class look for all instances of a specific type, then calling a method on each instance	public class Program\n{\n    static void Main(string[] args)\n    {\n        Overlay overlay = new Overlay();\n        foreach (FieldInfo field in overlay.GetType().GetFields())\n        {\n            if(typeof(Control).IsAssignableFrom(field.FieldType))\n            {\n                Control c = field.GetValue(overlay) as Control;\n                if(c != null)\n                    c.Draw();\n            }\n        }\n    }\n}	0
13487142	13486999	get values from XML with xpath when having Namespace	XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());\nnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-02-03T16:54:46");\n\nvar str = doc.XPathSelectElement("/root/ns:myFields/ns:Financial/ns:Quote/ns:Price", nsmgr)\n            .ToString(SaveOptions.DisableFormatting);\nConsole.WriteLine(str);	0
15080875	15080704	What would be the XPATH expression to select all Checked Nodes of a TreeView?	XDocument xml = XDocument.Load(reader);\nxml.Root.DescendantsAndSelf().Where(node =>\n{\n  try\n  {\n    return node.Attribute("Checked").Value.ToString() != "True";\n  }\n  catch\n  {\n    //no attribute @Checked \n    return true;\n  }\n}).Remove();	0
1338448	1330357	NHibernate, validation logic and AutoDirtyCheck	FlushMode.Never	0
28147457	28147155	Set date time picker from a string (date and time)	string pattern = "dd/MM/yyyy HH:mm:ss";\n        DateTime parsedDate;\n\n        string dateValue = "27/11/2014 17:35:59";\n        if (DateTime.TryParseExact(dateValue, pattern, null,\n                                  DateTimeStyles.None, out parsedDate))\n        {\n            MessageBox.Show(string.Format("Converted '{0}' to {1:d}.", dateValue, parsedDate));\n        }\n        else\n        {\n            MessageBox.Show(string.Format("Unable to convert '{0}' to a date and time.",\n                              dateValue));\n        }	0
15029453	15028778	How to get ListBox to load after selecting ComboBox value?	private void cb_Sessions_SelectedValueChanged(object sender, EventArgs e)\n{\n    listBox_Sessions.Visible = true;\n\n    if (cb_Sessions.SelectedValue != null)\n        LoadSessionListbox();\n}	0
14052729	14052534	multiplying int to double c#	if (!string.IsNullOrWhiteSpace(Textbox1.text))\n        {\n            int qty = Int32.Parse(Textbox1.text);\n            double rate = Double.Parse(Textbox2.text);\n            Textbox3.text = (rate * (double)qty).ToString();\n        }\n        else\n        {\n            //Give appropriate message to user for entering quantity in textbox 1\n        }	0
33196709	33196446	How to remove elements from a windows forms webbrowser control	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    webBrowser1.Document.GetElementById("ads").OuterHtml = "";\n    webBrowser1.Document.GetElementById("navigation").OuterHtml = "";\n    webBrowser1.Document.GetElementById("donate").OuterHtml = "";\n    webBrowser1.Document.GetElementById("social_bookmarking_buttons").OuterHtml = "";\n}	0
31923319	31922882	MongoDB C# Drivier - Deserializing HybridDictionary	[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]\npublic HybridDictionary SubSections \n{ \n    get { return this._SubSections; } \n    private set { this._SubSections = value; } \n}	0
5013857	5013840	Checkbox validation with LINQ	btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;	0
7382963	7356670	How to close Main window or application from ShowDialog window	private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)\n    {\n        if (e.CloseReason == CloseReason.UserClosing)\n        {\n            Application.Exit();\n\n        }\n    }	0
8961374	8961267	returning a boolean if a DB field contains data	var TheListOfObjects = (from thetable in MyDC.TheTable\n                        ....\n                        select new MyObject()\n                        {\n                            MyBool = (thetable.MyField == null) ? false : thetable.MyField.Contains("*") //check if it's null in-line\n\n                         }).ToList();	0
27106244	27106151	How to handle null exception when converting from object to string?	string str = (obj == null) ? string.Empty : obj.ToString();	0
9224714	9224666	XML Serialization on a custom data	[XmlIgnore]\npublic List<string> CardList { get; private set; }\n\n[XmlAttribute("cards")]\npublic string Cards {\n   get { return String.Join(",", CardList); }\n   set { CardList = value.Split(",").ToList(); }\n}	0
30995458	30995373	How to call simple web-service in c# and show response in text-box?	private void button1_Click(object sender, EventArgs e)\n{\n    var client = new WebClient();\n    var response = client.DownloadString("http://localhost:8000"); // or whatever your url might look like\n\n    myTextBox.Text = response;\n}	0
5237988	5237912	.NET HEX Colors too long for HTML	System.Text.RegularExpressions.Regex.Replace("#FFFAFAD2", "#..", "#")	0
18643037	18637092	Using a RenderTarget2D causes blurring	new RenderTarget2D(GraphicsDevice, pixelWidth, pixelHeight, false, SurfaceFormat.Bgr565, DepthFormat.Depth24Stencil8);	0
1716481	1716378	Hashtable how to get string value without toString()	public class myHashT\n{\npublic myHashT () { }\n...\n\nprivate Hashtable _ht;\n\npublic string this[object key]\n{\n  get\n  {\n     return _ht[key].ToString();\n  }\n  set\n  {\n     _ht[key] = value;\n  }\n}	0
8111531	8111483	How to use an object inside an EventHandler	private DispatcherTimer dt = null; \n\npublic MainPage()    \n{    \n    InitializeComponent();    \n    this.dt = new DispatcherTimer();    \n    this.dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1 Second    \n    this.dt.Tick += new EventHandler(dtTick);    \n}    \n\nprivate void startButton_Click(object sender, RoutedEventArgs e) \n{ \n     if (this.dt != null)\n              this.dt.Start(); \n}	0
19141042	19139993	How can I remove ctl00_Body_ from ctl00_Body_grvDocs_ctl45_hypDocNav in gridview's hyperlink	ClientIDMode="Static"	0
21088799	21088417	LINQ to add Xattribute using loop	foreach (XElement b in xDoc.Descendants("B"))\n{\n    int seq = 1;\n    foreach (XElement c in b.Elements("C"))\n        c.Add(new XAttribute("Sno", seq++));\n}	0
33037580	33026454	Reflection to find all methods with a PostSharp aspect applied	[MulticastAttributeUsage(PersistMetaData = true)]	0
13505215	13504501	ListView Row Remove Button from SQL	var con = new SqlCeConnection("Data Source=" + "|DataDirectory|\\Database1.sdf");\n                String str = "UPDATE employee SET Isdeleted ='1' WHERE empID= '"+ empID +"'";\n                var cmd = new SqlCeCommand(str,con);\n\n                try\n                {\n                    con.Open();\n                }\n                catch (Exception a)\n                {\n                    Console.WriteLine(a.ToString());\n                }\n                finally\n                {\n                    cmd.ExecuteNonQuery();\n                    con.Close();\n                }	0
14353550	14353521	Adding a dictionary to a collection - just the values?	comboWagonTypes.Items.AddRange(GetAllWagonTypes().Values);	0
11650421	11650215	How to get the type argument to a generic method?	public Type Magic(Action action)\n{\n    return action.Method.GetGenericArguments().First();\n}	0
15084098	14705494	Outlook New Mail Window opened from C# seems to have focus but my app still has it	private void label1_Click(object sender, EventArgs e)\n{\n  // mainform.BringToFront(); // doesn't work\n  BeginInvoke(new VoidHandler(OtherFormToFront));\n}\n\ndelegate void VoidHandler();\n\nprivate void OtherFormToFront()\n{\n  mainform.BringToFront(); // works\n}	0
16546025	16545913	No performance gains with Parallel.ForEach and Regex?	Parallel.ForEach	0
7837976	7837957	Starting SQL Server via C#	System.Diagnostics.Process process = new System.Diagnostics.Process();\n        process.StartInfo.FileName = "net start \"Sql Server (SQLEXPRESS)\"";\n        process.Start();	0
20598878	20598799	WPF: Need help develping and Binding a Double <--> Converter	[ValueConversion(typeof(double) ,typeof(string))]\npublic class DoubleConverter : IValueConverter\n{\n    public object Convert(object value ,Type targetType ,object parameter ,CultureInfo culture)\n    {\n        double doubleType = (double)value;\n        return doubleType.ToString();\n    }\n\n    public object ConvertBack(object value ,Type targetType ,object parameter ,CultureInfo culture)\n    {\n        string strValue = value as string;\n        double resultDouble;\n        if ( double.TryParse(strValue ,out resultDouble) )\n        {\n            return resultDouble;\n        }\n        return DependencyProperty.UnsetValue;\n    }\n}	0
1110885	1110866	How can I get part of the following string?	if (url.ToLower().Contains("/tools/search.aspx"))\n{\n   //do stuff here\n}	0
31880828	31880767	Fill ComboBox with Results of LINQ Query, Directly	InitializeComponent();\n    companyComboBox.ItemsSource = companyQuery.ToList();\n    companyComboBox.DisplayMemberPath = "Name";\n    companyComboBox.SelectedValuePath = "ID";	0
23844959	23543392	Windows 8.1 store app Download file using authentication and header	var httpClientHandler = new HttpClientHandler();\n                        httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");\n                        var client = new HttpClient(httpClientHandler);\n                        System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));\n                        request.Headers.Range = new RangeHeaderValue(0, null);\n                        HttpResponseMessage response = await client.SendAsync(request);	0
29412879	29411434	How to show progressbar while generating Excel sheet with data in C#	private void button1_Click(object sender, EventArgs e)\n    {\n        int ProgressToBeupdated = 100;\n\n        BackgroundWorker WorkerThread = new BackgroundWorker();\n\n        WorkerThread.WorkerReportsProgress = true;\n\n        WorkerThread.DoWork += WorkerThread_DoWork;\n        WorkerThread.ProgressChanged += WorkerThread_ProgressChanged;\n\n        WorkerThread.RunWorkerAsync(new object());\n\n\n    }\n\n    void WorkerThread_ProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n        progressBar1.Value = e.ProgressPercentage;\n    }\n\n    void WorkerThread_DoWork(object sender, DoWorkEventArgs e)\n    {\n\n        for (int i = 0; i < 100; i++)\n        {\n            Thread.Sleep(500);\n            (sender as BackgroundWorker).ReportProgress(i);       \n        }\n    }	0
28565899	28557786	Get column names for each updated items in Radgrid	protected void radGridTranslation_ItemCommand(object _sender, GridCommandEventArgs _event)\n{\n    if (_event.Item is GridDataItem)\n    {\n        if (_event.CommandName == myRadGrid.UpdateCommandName)\n        {\n            GridDataItem l_dataItem = (GridDataItem)_event.Item;\n            Dictionary<string, string> l_gridUpdatedItemList = new Dictionary<string, string>();\n            l_dataItem.ExtractValues(l_gridUpdatedItemList);\n\n            foreach (KeyValuePair<string, string> l_updatedItemWithColumn in l_gridUpdatedItemList)\n            {\n                // Key = The column name\n                // Value = The cell value\n            }\n        }\n    }\n}	0
15251253	15251159	What's the Best Way to Add One Item to an IEnumerable<T>?	arr = arr.Append("JKL");\n// or\narr = arr.Append("123", "456");\n// or\narr = arr.Append("MNO", "PQR", "STU", "VWY", "etc", "...");\n\n// ...\n\npublic static class EnumerableExtensions\n{\n    public static IEnumerable<T> Append<T>(\n        this IEnumerable<T> source, params T[] tail)\n    {\n        return source.Concat(tail);\n    }\n}	0
3064639	3054096	Is there such a thing as a MemberExpression that handles a many-to-many relationship?	business.Addresses.First().State.StateID;	0
18141167	18046722	store a blob string in database table	CloudBlockBlob blockBlob = new CloudBlockBlob();\nusing (var fileStream = System.IO.File.OpenRead(path + "/" + up.GetName().ToString()))\n{\n      blockBlob.UploadFromStream(fileStream);\n}\nstring URL = blockBlob.Uri.OriginalString;	0
8994342	8994285	How do I use Target=_blank on a response.redirect?	response.write("<script>");\nresponse.write("window.open('page.html','_blank')");\nresponse.write("</script>");	0
12741345	12741269	Exclude string match using c# regex	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar imgs = doc.DocumentNode.Descendants("img")\n    .Where(n => n.Attributes["border"] == null)\n    .ToList();	0
18679559	18677111	How to select an Item from asp:Dropdownlist on Page load from Code Behind C#?	txt_examtype.SelectedValue =  dt.Rows[0]["ExamType"].ToString()	0
4457381	4457359	Is it a good/acceptable practice to declare variable as interface type?	List<string>	0
14472371	14391150	How to get a MongoDatabase when using appharbor and mongohq	var connectionstring = ConfigurationManager.AppSettings.Get("(MONGOHQ_URL|MONGOLAB_URI)");\nvar url = new MongoUrl(connectionstring);\nvar client = new MongoClient(url);\nvar server = client.GetServer();\n\nvar database = server.GetDatabase(url.DatabaseName);	0
11750639	11750585	C# - Load a text file as a class	var csc = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } } );\nvar cp = new CompilerParameters() {\n    GenerateExecutable = false,\n    OutputAssembly = outputAssemblyName,\n    GenerateInMemory = true\n};\n\ncp.ReferencedAssemblies.Add( "mscorlib.dll" );\ncp.ReferencedAssemblies.Add( "System.dll" );\n\nStringBuilder sb = new StringBuilder();\n\n// The string can contain any valid c# code\n\nsb.Append( "namespace Foo{" );\nsb.Append( "using System;" );\nsb.Append( "public static class MyClass{");\nsb.Append( "}}" );\n\n// "results" will usually contain very detailed error messages\nvar results = csc.CompileAssemblyFromSource( cp, sb.ToString() );	0
3795639	3795608	how do I delay action on mouse enter rectangle c#	static void MouseEnteredYourRectangleEvent(object sender, MouseEventArgs e)\n    {\n        Timer delayTimer = new Timer();\n        delayTimer.Interval = 2000; // 2000msec = 2 seconds\n        delayTimer.Tick += new ElapsedEventHandler(delayTimer_Elapsed);\n    }\n\n    static void delayTimer_Elapsed(object sender, EventArgs e)\n    {\n        if(MouseInRectangle())\n            DoSomething();\n\n        ((Timer)sender).Dispose();\n    }	0
14999323	14999165	How to get the cell name(not value in it) in excel using c#	r = Activecell.Row \nc = ActiveCell.Column	0
11540580	11540464	asp.net postback data	if(!isPostBack)\n   {\n        //Clear Table\n   }	0
905664	905447	How to prevent ListBox.SelectedIndexChanged event?	lb.Items.Clear();\n lb.Items.AddRange(reportColumnList.ReportColumns.ToArray());	0
34223349	34223258	How to set DateTimePicker to specific time?	private void button1_Click(object sender, EventArgs e)\n{\n    dateTimePicker1.Value = new DateTime(2000, 1, 1, 14, 30, 0);\n}	0
11169267	11168986	Assigning data template to list box at runtime	myListBox.ItemTemplate = (DataTemplate)Resources["resourceKey"];	0
18638558	18637760	Getting the foreground window when a hotkey is pressed	//Listen for the hotkey\nprotected override void WndProc(ref Message m)\n{\n    base.WndProc(ref m);\n\n    if (m.Msg == WM_HOTKEY)\n    {\n        Keys vk = (Keys)(((int)m.LParam >> 16) & 0xFFFF);\n        int fsModifiers = ((int)m.LParam & 0xFFFF);\n\n        //Perform action when hotkey is pressed\n        if (vk == userHotkey)\n        {\n            minimizeWindow();\n        }\n    }\n}\n\n//Minimize the currently active window\nprivate void minimizeWindow()\n{\n    //Get a pointer to the currently active window\n    IntPtr hWnd = getCurrentlyActiveWindow();\n    if (!hWnd.Equals(IntPtr.Zero))\n    {\n        //Minimize the window\n        ShowWindowAsync(hWnd, SW_SHOWMINIMIZED);\n    }\n}\n\n//Get the currently active window\nprivate IntPtr getCurrentlyActiveWindow()\n{\n    this.Visible = false;\n    return GetForegroundWindow();\n}	0
8006062	8005402	How to integrate SQL with Windows forms?	private bool ValidateUser(String UserName, string HashedPassword)\n{\n    //Use datareader etc to query\n    // SQL Query\n    string strSql = "Select UserLogin From UserLogin Where UserLoginID=" + UserName + " UserPassword = " + HashedPassword;\n    //check for returned rows count\n    //return true if found                \n}	0
1330360	1329961	C#: Removing common invalid characters from a string: improve this algorithm	char[] BAD_CHARS = new char[] { '!', '@', '#', '$', '%', '_' }; //simple example\nsomeString = string.Concat(someString.Split(BAD_CHARS,StringSplitOption.RemoveEmptyEntries));	0
33971278	33971206	How to execute a method after completion of three proccesses in .net	using System;\nusing System.Diagnostics;\n\nclass Program\n{\n  static int count = 0;\n  static object obj = new object();\n  static void Main(string[] args)\n  {\n    Process[] Processes = new Process[3];\n    for (int i = 0; i < 3; i++)\n    {\n        Processes[i] = Process.Start("notepad.exe");\n        Processes[i].EnableRaisingEvents = true;\n        Processes[i].Exited += Program_Exited;\n    }\n    Console.ReadLine();\n  }\n\n  private static void Program_Exited(object sender, System.EventArgs e)\n  {\n    lock (obj)\n    {\n        count++;\n    }\n    if (count == 3)\n        Console.WriteLine("Finised");\n  }\n}	0
8548629	8548579	Library to extract data from html string	public string StripHTMLTags(string str)\n        {\n            StringBuilder pureText = new StringBuilder();\n            HtmlDocument doc = new HtmlDocument();\n            doc.LoadHtml(str);\n\n            foreach (HtmlNode node in doc.DocumentNode.ChildNodes)\n            {\n                pureText.Append(node.InnerText);\n            }\n\n            return pureText.ToString();\n        }	0
2272789	2272755	how can i learn my client ip with .NET?	static void Main(string[] args)\n    {\n        const string url = "http://www.whatismyip.com/automation/n09230945.asp";\n\n        var client = new WebClient();\n        try\n        {\n            var myIp = client.DownloadString(url);\n            Console.WriteLine("Your IP: " + myIp);\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine("Error contacting website: " + ex.Message);\n        }\n    }	0
14964037	14963355	making XML nodes dynamically	StringBuilder xmlForApi = new StringBuilder();\nint customerCounter = 1;\nforeach(Customer c in Customers)\n{\n    xmlForApi.AppendFormat("<FirstName_{0}>{1}</FirstName_{0}><LastName_{0}>{2}</LastName_{0}>", customerCounter, c.FirstName, c.LastName)\n    customerCounter++;\n}	0
689194	688939	Detect user logged on a computer using ASP.NET app	Request.ServerVariables["LOGON_USER"]	0
1084592	1084556	Can't find control in edit mode in DataList	protected void DataList1__ItemDataBound(Object sender, DataListItemEventArgs e)\n  {\n    if (e.Item.ItemType == ListItemType.EditItem)\n    {\n        Label lbl = (Label)e.Item.FindControl("lbl");\n        lbl.Text = "edit mode";\n    }\n  }	0
13912361	13878058	Install MS Outlook 2010 in silent mode using c#	Process process = new Process();\n     process.StartInfo.FileName = @"C:\temp\Setup.exe";\n     process.StartInfo.Arguments = @"/config \\C:\temp\config.xml";\n     process.Start();\n     process.WaitForExit();	0
15113813	15113507	How can I check file extension of a file in IsolatedStorage?	if (Path.GetExtension(file) != ".jpg")\n{\n    ...\n}	0
15139313	15074479	External page load issue in Windows 8 App	{\n    textboxUri.Text = "http://www.google.com/";\n    WebView1.Navigate(new Uri(textboxUri.Text));\n\n    WebView1.LoadCompleted += LoadCompletedEvent;\n}\n\nvoid LoadCompletedEvent(object sender, eventargs e)\n{\n    //Now the website has loaded, do what you want here\n}	0
21129764	21129412	show count on minimized windows of your application in c#	// draw an image to overlay\nvar dg = new DrawingGroup();\nvar dc = dg.Open();\ndc.DrawEllipse(Brushes.Blue, new Pen(Brushes.LightBlue, 1), new Point(8, 8), 8, 8);\ndc.DrawText(new FormattedText("3", System.Threading.Thread.CurrentThread.CurrentUICulture, System.Windows.FlowDirection.LeftToRight,\n    new Typeface("Arial"), 16, Brushes.White), new Point(4, 0));\ndc.Close();\nvar geometryImage = new DrawingImage(dg);\ngeometryImage.Freeze();\n\n// set on this window\nvar tbi = new TaskbarItemInfo();\ntbi.Overlay = geometryImage;\n\nthis.TaskbarItemInfo = tbi;	0
19418685	19418648	How to get value from selected checkbox in ASP gridview?	protected void btnClick_Click(object sender, EventArgs e)\n{ \n    StringBuilder sbQuery = new StringBuilder();\n    bool flag = false;\n    foreach (GridViewRow row in gridview1.Rows)\n    {\n\n        if (((CheckBox)row.FindControl("chk")).Checked)\n        {\n            flag = true;\n           //------\n\n        }\n\n    }\n\n\n}	0
17566536	17566332	Retrieving VarChar(MAX) from SQL Server using C# and a stored procedure	if (rdr.HasRows)\n                    {\n                        while(rdr.Read())\n                        {\n                            string fieldValue = rdr[0].ToString();\n                        }\n\n                    }\n                    else\n                    {\n                        Console.WriteLine("No rows found.");\n                    }	0
31425219	31425180	no operator for enum-int but for enum-0?	public FormatType Format\n    {\n        get { return _format; }\n        set\n        {\n            // red line under value > 2.\n            if (value < 0 || (int)value > 2) throw new FileParseException(ParseError.Format);\n            _format = value;\n        }\n    }	0
27557756	27557499	Display of webservice description	namespace WebApplication1\n{\n    /// <summary>\n    /// Summary description for WebService1\n    /// </summary>\n    [WebService(Namespace = "http://tempuri.org/", Description = "Something about your service")]\n    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n    [System.ComponentModel.ToolboxItem(false)]\n    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. \n    // [System.Web.Script.Services.ScriptService]\n    public class WebService1 : System.Web.Services.WebService\n    {\n\n        [WebMethod(Description = "What this method does")]\n        public string HelloWorld()\n        {\n            return "Hello World";\n        }\n    }\n}	0
9599920	9599896	Change setting in user control 's configuration file has no effect	AppName.exe.config	0
22903759	22903646	How do I use this query in vb.net - I cannot get my head around converting from c# to vb.net	Dim query As New ObjectQuery("Select * FROM Win32_Battery")\n\nFor Each o As ManagementObject In New ManagementObjectSearcher(query).Get()\n    Dim level = CUInt(o.Properties("EstimatedChargeRemaining").Value)\nNext	0
17053675	17053648	How to Parse string into BigInteger?	BigInteger reallyBigNumber = BigInteger.Parse("12347534159895123");	0
3806716	3806663	converting a byte array from a native method to a managed structure	[DllImport("my_lib.dll", SetLastError = true)]\ninternal static extern Int32 Foo(out NATIVE_METHOD_REPLY replyBuffer, Int32 replySize);	0
26066315	25897931	Removing XML namespace from WebApi	[DataMember(EmitDefaultValue = false)]\npublic CustomSourceRecord OperationResult { get; set; }	0
25367848	25361967	Passing combobox selected value to WCF to get data from a silverlight 5 Pivot Viewer Client	var proxy = new Service1Client();\n\nproxy.GetAllEmployeesCompleted += proxy_GetAllEmployeesCompleted;\nproxy.GetAllEmployeesAsync(selectedItem.ToString());	0
15832030	15831777	How to write a lambda expression to create a burndown chart	var allFaults = i_Context.Faults.GetAllFaults();\nvar faults = \n  listOfDays.Select(d => new { Day = d.Date,\n                               OpenFaults =\n                                   allFaults.Count(f => f.FaultCloseDateTime >=\n                                                           d.Date)\n                             });	0
15235683	15235483	How to change numbers into formatted strings	int x = 34549321;\nstring xs = string.Format("{0:#,##,k}",x);\n// Produces xs = 34,549k	0
2622265	2621675	How to perform a many-to-many Linq query with Include in the EF	var result = (from b in Context.B.Include("C")\n              where b.A.Any(x => x.A.Equals(aId))\n              select b);	0
10000801	10000701	Read whole file in blocks in c#	string[] blocks = (file.ReadAllText(file)).split(new string[] {"\n\n\n"}, StringSplitOptions.None)	0
12257905	12257854	Searching a list of objects for a non empty property	Func<MyType, bool> SelectorToPredicate<T>(Func<MyType, T> selector)\n{\n    EqualityComparer<T> comparer = EqualityComparer<T>.Default;\n    return x => !comparer.Equals(selector(x), default(T));\n}	0
16572500	16572418	Distinct Value from Linq Query	var titleList = mNewItems.Select(i => i.Title).Distinct().ToList();	0
4348437	4348344	C# - WireShark detects incomming packets but application does not receive them	var udpClient = new System.Net.Sockets.UdpClient(9998);\nByte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);	0
7577287	7577203	How to call a parent class's method from child class in c#?	public class TestClass : Page\n{\n    public void OtherMethod()\n    {\n        ((Site)this.Master).MyMethod();\n    }\n}	0
25519911	25519739	How to get array element containing '/' in the string array	foreach (string s in arrdate)\n{\n   if (s.contains("/"))\n   {\n       //do something with s like add it to an array or if you only look for one string assign it and break out of the loop.\n   }\n}	0
4989769	4989686	How to iterate through an XDocument's Nodes	foreach (XElement xe in doc.Descendants("Profile"))\n{\n    MessageBox.Show(xe.Element("username").Value);\n}	0
10497697	8849459	Entity Framework Custom Property using external Parameters	[NotMapped]\n    public decimal CostPerMonth\n    {\n        get { return (LoanAmount * Rate)/12 ; }\n    }	0
1189348	1187636	Can I add a WCF DataContract to a complex type?	[DataContract]\n[KnownType(typeof(WHS2SmugmugShared.Photo))]\n[KnownType(typeof(WHS2SmugmugShared.PhotoInfo))]\npublic class Photo\n{\n//code here\n}	0
25554401	25554234	Search for a string in a multi dimensional string array and get index of item	private string getBlockDataOrName(string nameOrData, string index)\n{\n    String[][] blocks = {\n                            new []{ "stone", "grass", "dirt", "trees", "logs", "shovel", "bedrock" },\n                            new []{ "6", "0", "2", "0", "5", "5", "0" }\n                        };\n\n    if (nameOrData == "Data")\n        return blocks[1][Array.IndexOf(blocks[1], index)];\n    else\n        return blocks[0][Convert.ToInt64(index)];\n\n}	0
14887060	14887047	Preventing IndexOutOfRangeException on arrays	if (index < array.Length)	0
28353994	28352918	Parsing XML With LINQ Issue	using System;\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing System.Xml.Linq;\n\nnamespace WaitForIt\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string thexml = @"<Response xmlns=""http://tempuri.org/""><Result xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:string>18c03787-9222-4c9b-8f39-44c2b39c788e</a:string><a:string>774d38d2-a350-4711-8674-b69404283448</a:string></Result></Response>";\n\n        XDocument doc = XDocument.Parse(thexml);\n        XNamespace ns = "http://tempuri.org/";\n\n        var result = doc.Descendants(ns + "Result");\n        var resultStrings = result.Elements();\n\n        foreach (var el in resultStrings)\n        {\n            Debug.WriteLine(el.Value);\n        }\n\n        // output:\n        // 18c03787-9222-4c9b-8f39-44c2b39c788e\n        // 774d38d2-a350-4711-8674-b69404283448\n     }        \n   }\n}	0
639119	639093	Counting controls on the page	public int CountControls(Control top)\n{\n    int cnt = 1;\n    foreach (Control c in top.Controls)\n        cnt += CountControls(c);\n    return cnt;\n}	0
27911402	27904303	C# - Create a tree structure of a flat list (by dates)	previousYear = -1\npreviousMonth = -1\npreviousDay = -1\nfor each file in list\n{\n    if (file.date.year != previousYear)\n    {\n        output file.date.year\n        previousYear = file.date.year\n        // set previousMonth to default to force a new month folder\n        previousMonth = -1\n    }\n    if (file.date.Month != previousMonth)\n    {\n        output file.date.month\n        previousMonth = file.date.month\n        // set previousDay to default to force a new day folder\n        previousDay = -1\n    }\n    if (file.date.day != previousDay)\n    {\n        output file.date.day\n        previousDay = file.date.day\n    }\n    // and then output the file name\n    output file.name\n}	0
20505726	20503575	Calculate Monday as first day of the week with a stored procedure	DECLARE @CurrentWeekday AS INT\nDECLARE @LastSunday AS DATETIME\nDECLARE @LastMonday AS DATETIME\n\nSET @CurrentWeekday = DATEPART(WEEKDAY, GETDATE())\n// Count backwards from today to get to the most recent Sunday.\n// (@CurrentWeekday % 7) - 1 will give the number of days since Sunday; \n// -1 negates for subtraction.\nSET @LastSunday = DATEADD(DAY, -1 * (( @CurrentWeekday % 7) - 1), GETDATE())\n// Monday is obviously one day after last Sunday.\nSET @LastMonday = DATEADD(DAY, 1, @LastSunday)\n\nSELECT COUNT(od.id) [new_job_posting_this_week] \nFROM rs_job_posting od\nWHERE od.date_created >= @LastMonday	0
32532316	32531455	How to make a button mouse over highlight a text area	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;\n\nnamespace WindowsFormsApplication4\n{\n    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            Clipboard.SetText("Box 1: " + textBox1.Text + "\r\nBox 2: " + textBox2.Text + "\r\nBox 3: " +textBox3.Text);\n        }\n\n        private void highlightbox(object sender, EventArgs e)\n        {\n            textBox1.BackColor = Color.LightGray;\n            textBox2.BackColor = Color.LightGray;  \n        }\n\n        private void unhighlightbox(object sender, EventArgs e)\n        {\n            textBox1.BackColor = Color.Empty;\n            textBox2.BackColor = Color.Empty;\n        }\n\n    }\n}	0
31693318	31693269	How do I get the next whole number after a given floating point value in C#	var nextNumber = Math.Floor(oldNumber) + 1;	0
24136005	24126022	C# - How to Change Dynamically the Mask of the MaskedTextBox?	public class CustomMaskedBox : MaskedTextBox\n{\n    public CustomMaskedBox()\n    {\n        this.MaskInputRejected += CustomMaskedBox_MaskInputRejected;\n        this.Enter += CustomMaskedBox_Enter;\n        this.Leave += CustomMaskedBox_Leave;\n    }\n\n    void CustomMaskedBox_Leave(object sender, EventArgs e)\n    {\n        if (this.MaskFull)\n        {\n            this.BackColor = Color.LightGreen;\n        }\n        else\n        {\n            this.Mask = "(00) 0000-0000";\n            this.BackColor = Color.LightGreen;\n        }\n\n        if (!this.MaskCompleted)\n        {\n            this.BackColor = Color.LightCoral;\n        }\n\n    }\n\n    void CustomMaskedBox_Enter(object sender, EventArgs e)\n    {\n        this.BackColor = Color.LightBlue;\n    }\n\n    void CustomMaskedBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)\n    {\n        if (this.MaskFull)\n        {\n            this.Mask = "(00) 0000-00000";\n            this.BackColor = Color.LightYellow;\n        }\n    }\n}	0
28790285	28782399	Converting a string HEX to color in Windows Phone Runtime c#	using System.Reflection;     // For GetRuntimeProperty\nusing System.Globalization;  // For NumberStyles\nusing Windows.UI;            // for Color and Colors\nusing Windows.UI.Xaml.Media; // for SystemColorBrush\n\n// from #AARRGGBB string\nbyte a = byte.Parse(hexColor.Substring(1, 2),NumberStyles.HexNumber);\nbyte r = byte.Parse(hexColor.Substring(3, 2),NumberStyles.HexNumber);\nbyte g = byte.Parse(hexColor.Substring(5, 2),NumberStyles.HexNumber);\nbyte b = byte.Parse(hexColor.Substring(7, 2),NumberStyles.HexNumber);\n\nWindows.UI.Color color = Color.FromArgb(a, r, g, b);\nWindows.UI.Xaml.Media.SolidColorBrush br = new SolidColorBrush(color);\n\n// From Name\nvar prop = typeof(Windows.UI.Colors).GetRuntimeProperty("Aqua");\nif (prop != null)\n{\n    Color c = (Color) prop.GetValue(null);\n    br = new SolidColorBrush(c);\n}\n\n// From Property\nbr = new SolidColorBrush(Colors.Aqua);	0
18976065	18915077	Programmatically creating a connection string for mapping an Entity Framework Code-First model with an existing Sql Azure federation database	var   customerEntity = new CrmEDMContainer(ConnectionStringCustomerDB());\n                    var connection = new SqlConnection();\n                    connection =(SqlConnection) customerEntity.Database.Connection;\n                    connection.Open();\n                    var command = new SqlCommand();                \n                    string federationCmdText = @"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";\n                    command.Connection = connection;\n                    command.CommandText = federationCmdText;\n                    command.ExecuteNonQuery();\nreturn customerEntity ;	0
25898551	25898230	Decoding protobuf without schema	--decode_raw	0
29452667	28899864	SlideView Crashes the Windows Phone 8.1 App	Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => frame.Navigate(typeof(YourPage)));	0
31783390	31783211	Elegant way to change control visibility in wpf	somecontrol.Visibility = somecontrol.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;	0
31505496	31505389	c# string of numbers to array of two value numbers	var input = "38482645351404";\nvar numbers = Enumerable.Range(0, input.Length/2).Select(i => int.Parse(input.Substring(i*2, 2))).ToArray();	0
30986367	30985568	Application is missing required files	compas.ico	0
4870179	4812159	How to close a console application within the specified number of hours?	public static void Main(string[] args)\n    {\n        string stoptime = ConfigurationManager.AppSettings["Stoptime"];\n        DateTime timeEnd = Convert.ToDateTime(stoptime);\n\n        today = DateTime.Now;\n        Console.WriteLine(today);\n\n        for (int i = 0; i < 100000; i++)\n        {\n            id.Add(i.ToString());\n        }\n\n        foreach(string item in id)\n        {\n            today = DateTime.Now;\n\n            if (timeEnd.CompareTo(today) >= 0)\n            {\n                Console.CursorLeft = 0;\n                Console.Write(item + " " + today);\n            }\n            else\n            {\n                Console.WriteLine();\n                Console.WriteLine("break.");\n                break;\n            }\n        }\n\n        Console.ReadKey();\n    }	0
5406573	5406433	Combining Dictionary<A,B> + Dictionary<B,C> to create Dictionary<A,C>	Dictionary<int, string> first = new Dictionary<int, string> { {1, "hello"}, {2, "world"}};\n\nDictionary<string, bool> second = \n    new Dictionary<string, bool> { { "hello", true }, {"world", false}};\n\nvar result = (from f in first\n              join s in second on f.Value equals s.Key\n              select new { f.Key, s.Value }).ToDictionary(x => x.Key, y => y.Value);	0
8856813	8853082	Custom XML serialization - Include class name	var xmlOverrides = new XmlAttributeOverrides();\nvar attributes = new XmlAttributes();\nattributes.XmlElements\n     .Add(new XmlElementAttribute("ExampleObject", typeof (ExampleObject)));\nxmlOverrides.Add(typeof(Message<ExampleObject>), "Body", attributes);\n\nvar serializer2 = new XmlSerializer(typeof(Message<ExampleObject>), xmlOverrides);	0
29755933	29717732	How to keep async system.net.socket listener alive in windows application	StartListening(); Thread.Sleep(Timeout.Infinite);	0
3975940	3972528	Get Application Path of offending DLL from Exception	Assembly.GetCallingAssembly()	0
23708786	23708689	Convert Task<String> to String in Windows 8 apps	public async Task<string> readweb()\n    {\n        var uri = new Uri(@"http://stackoverflow.com/");\n        var httpClient = new HttpClient();\n        var data = await httpClient.GetStringAsync(uri);\n        string text = data;\n        return text;\n    } \n\nprivate async void Something()\n{\n    var data = await readweb();\n}	0
10687138	10686598	Changing the name of a value in a combobox	selectdirectories.Items[selectdirectories.Items.IndexOf("Data")] = "<Default>";	0
9026119	9025967	String parsing and matching algorithm	Dictionary<string,string> latestPackages=new Dictionary<string,string>(packageNameComparer);\n\nforeach element\n{\n    (package,version)=applyRegex(element);\n\n    if(!latestPackages.ContainsKey(package) || isNewer)\n    {\n        latestPackages[package]=version;\n    }\n}\n\n//print out latestPackages	0
8356363	8356250	Storing pointer to method parameter for later reuse	private Closure<Item, DateTime> closure = null;\npublic IEnumerable<Item> GetDayData(DateTime day)\n{\n    if (closure == null)\n    {\n        this.closure = new Closure<Item, DateTime>() {\n            Predicate = i => i.IsValidForDay(this.closure.Variable)\n        }\n    }\n    // assign here, else you only capture it the first time\n    closure.Variable = day;\n    this.items.Where(this.closure.Predicate);\n}	0
17522271	17521913	How to Copy file to specific directory & Set Filename, Extension using OpenDialog in WPF?	OpenFileDialog op = new OpenFileDialog();\nstring folderpath = System.IO.Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\ContactImages\\";\nop.Title = "Select a picture";\nop.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +\n            "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +\n            "Portable Network Graphic (*.png)|*.png";\n\nbool? myResult;\nmyResult = op.ShowDialog();\nif (myResult != null && myResult == true)\n{\n  imgContactImage.Source = new BitmapImage(new Uri(op.FileName));\n  if (!Directory.Exists(folderpath))\n  {\n     Directory.CreateDirectory(folderpath);\n  }\n  string filePath = folderpath + System.IO.Path.GetFileName(op.FileName);\n  System.IO.File.Copy(op.FileName, filePath, true);\n }	0
28848974	28836258	EF Code First Many to Many BaseEntity Inheritance	public abstract class BaseEntity : IEntity\n{\n    [Key]\n    public Guid Id { get; set; }\n\n    [ForeignKey("ObjectId")]\n    public virtual ICollection<Note> Notes { get; set; }\n\n    protected BaseEntity()\n    {\n        Id = Guid.NewGuid();\n        Notes = new List<Note>();\n    }\n}\n\npublic class Note\n{\n    [Key]\n    public Guid Id { get; set; }\n    public Guid ObjectId { get; set; } //student, school, etc\n    public string Name { get; set; }\n    public string Value { get; set; }\n\n    public Note()\n    {\n        Id = Guid.NewGuid();\n    }\n}	0
22562300	22562008	Use == operator with generic type in a Where Linq statement	public string Get<TEntity, TId>(TId id)\n    where TEntity: IHasAnIdField<TId>\n{\n    var query = new SQLinq<TEntity>();\n\n    // predicate: i => i.Id == id    \n    var arg = Expression.Parameter(typeof(TEntity), "i");\n    var predicate =\n        Expression.Lambda<Func<TEntity, bool>>(\n            Expression.Equal(\n                Expression.Property(arg, "Id"),\n                Expression.Constant(id))\n            arg);\n\n\n    query = query.Where(predicate);\n    var sql = query.ToSQL().ToQuery();\n    return sql;\n}	0
26462557	26462449	Many to many as in code first approach in existing SQL Server New	CREATE TABLE Items\n(\n    Id INT PRIMARY KEY,\n    Title NVARCHAR(MAX),\n)\n\nCREATE TABLE Packages\n(\n    Id INT PRIMARY KEY,\n    Title NVARCHAR(MAX),\n)\n\nCREATE TABLE ItemPackages\n(\n    ItemId INT NOT NULL,\n    PackageId INT NOT NULL,\n    FOREIGN KEY (ItemId) REFERENCES Items(Id),\n    FOREIGN KEY (PackageId) REFERENCES Packages(Id)\n)	0
12532786	12532734	Referencing a specific repeater item instance	var student = (Student)repeater.Items[3];	0
20658092	20658007	Listview.count - InvalidArgument=Value of '0' is not valid for 'index	while (reader.Read())\n        {\n            int sira = listView1.Items.Count;\n\n            listView1.Items.Add("Put some text here"); // <- Add a new item\n\n            listView1.Items[sira].SubItems.Add(reader.GetString("id"));\n            listView1.Items[sira].SubItems.Add(reader.GetString("ad"));\n            listView1.Items[sira].SubItems.Add(reader.GetString("soyad"));\n            listView1.Items[sira].SubItems.Add(reader.GetString("evrakulastimi"));\n            listView1.Items[sira].SubItems.Add(reader.GetString("basvurusonuclandimi"));\n        }	0
24364088	24363760	How to work with the periodic agent in windows phone	Background agents	0
9662457	9662412	In generics how can we set one type exactly similar to another?	public class GameInitializatorAdaptee<u> : \n  CollectionInitializationAdapter<Game, u>	0
30650116	5457821	Overload generic List's Add with extension method	class Program\n{\n    static void Main(string[] args)\n    {\n        var x = new List<Tuple<string,string>> { { "1", "2" }, { "1", "2" } };\n    }\n}\npublic static class Extensions\n{\n    public static void Add<T1,T2>(this List<Tuple<T1,T2>> self, T1 value1, T2 value2)\n    {\n        self.Add(Tuple.Create( value1, value2 ));\n    }\n}	0
32287873	32287776	How to concat all the column than row of a datatable?	var paramValues = String.Join(",", \n                     rows.Select(x => "(" + String.Join(",", x.ItemArray) + ")" ));	0
8304747	8304625	Setting what table a DbContext maps to	public class State\n{\n  public int StateId {get;set;}\n  public string StateName {get;set;}\n}\n\npublic class LookupContext : DbContext\n{\n  public DbSet<State> States {get;set;}\n  // ... more lookups as DbSets\n}	0
23853258	23853054	How can I write a image onto another?	public Bitmap AddLogo(Bitmap original_image, Bitmap logo)\n    {\n        /// Add validation here (not null, logo smaller then original, etc..)\n        Bitmap with_logo = new Bitmap(original_image);           \n\n        /// To get the right corner use:\n        int x_start_value = (original_image.Width - logo.Width) - 1;\n        int x_stop_value = original_image.Width -1;\n        /// \n\n        /// You can add ofset (padding) by starting x and\or y from your value insted of 0\n\n        for (int y = 0; y < logo.Height; y++)            \n        {\n\n            /// For left corner\n            ///for (int x = 0; x < logo.Width; x++)\n            int logo_x = 0;\n            for (int x = x_start_value; x < x_stop_value; x++)                \n            {\n                with_logo.SetPixel(x, y, logo.GetPixel(logo_x, y));\n                logo_x++;\n            }\n        }\n\n        return with_logo;\n    }	0
9890777	9888149	How to compare in MS Chart with historical data	chart1.Series.Clear();\n\n        string[] months = { "Jan", "Feb", "Mar", "Apr" };\n        double[] thisYearSales = { 10000.23, 98000, 95876, 78097 };\n        double[] lastYearSales = { 99000, 99000, 90876, 88097 };\n\n        Series thisYear = chart1.Series.Add("this year");\n        thisYear.Points.DataBindXY(months, thisYearSales);\n\n        Series lastYear = chart1.Series.Add("last year");\n        lastYear.Points.DataBindXY(months, lastYearSales);\n        lastYear.ChartType = SeriesChartType.Line;	0
6652502	6622370	Using LInq to SQL to get all the user email from ASP.NET Membership	grid.DataSource = from MembershipUser u in Membership.GetAllUsers()\n              select new\n              {\n                  Firstname = u.UserName,\n                  Email = u.Email                                   \n              };	0
372235	372158	FindControl in a RoleGroup in a LoginView	public Control RecursiveFindControl(Control parent, string idToFind)\n{\n    for each (Control child in parent.ChildControls)\n    {\n        if (child.ID == idToFind)\n        {\n            return child;\n        }\n        else\n        {\n            Control control = RecursiveFindControl(child, idToFind);\n            if (control != null)\n            {\n                return control;\n            }\n        }\n    }\n    return null;\n}	0
20696732	20696660	How to validated that an object contains only alphabet characters with DataAnnotation?	[RegularExpression(@"^[\p{L}]+$")]	0
23252633	23245691	Generate custom unique key in asp.net dynamic data	public class YourDbContext{\n\npublic override int SaveChanges()\n{\n     foreach (var entry in this.ChangeTracker.Entries())\n     {\n            var caseEntry = entry.Entity as @case;\n            if (caseEntry != null)\n            {\n\n                if (entry.State == EntityState.Added)\n                {\n                    caseEntry.Id = GenerateId();                       \n                }\n\n            }\n     }\n     return base.SaveChanges();\n}\n\n}	0
15710562	15710153	Read GnuPlot output into image in C#	string Path = @"z:\tools\gnuplot\bin\gnuplot.exe";\n        Process GnuplotProcess = new Process();\n        GnuplotProcess.StartInfo.FileName = Path;\n        GnuplotProcess.StartInfo.UseShellExecute = false;\n        GnuplotProcess.StartInfo.RedirectStandardInput = true;\n        GnuplotProcess.StartInfo.RedirectStandardOutput = true;\n        GnuplotProcess.Start();\n        StreamWriter SW = GnuplotProcess.StandardInput;\n        StreamReader SR = GnuplotProcess.StandardOutput;\n        SW.WriteLine("set terminal pngcairo size 300,200");\n        SW.WriteLine("plot f(x) = sin(x*a), a = .2, f(x), a = .4, f(x)");\n        SW.WriteLine("exit");\n\n        Image png = Image.FromStream(SR.BaseStream);\n        png.Save(@"z:\tools\try3a.png");\n\n        GnuplotProcess.Close();	0
13398525	13397470	how to update many to many EF code first	public void Create(Exchanger ex, long clientId)\n    {\n        if (_context != null)\n        {\n            ex.ClientId = clientId;\n            ex.LastTimeUpdated = DateTime.UtcNow;\n\n           **var ps = ex.PaymentSystems.Select(x=>x.Id);\n            var ps2 = _context.PaymentSystems.Where(x => ps.Any(y => y == x.Id)).ToList();\n            ex.PaymentSystems.Clear();\n            foreach (var pp in ps2)\n            {\n                ex.PaymentSystems.Add(pp);\n            }**\n\n            _context.Exchangers.Add(ex);\n            _context.SaveChanges();\n        }\n\n    }	0
28997835	28997617	Keep a Windows Service running without a timer	private TcpListener _listener;\n\npublic void OnStart(CommandLineParser commandLine)\n{\n    _listener = new TcpListener(IPAddress.Any, commandLine.Port);\n    _listener.Start();\n    Task.Run((Func<Task>) Listen);\n}\n\nprivate async Task Listen()\n{\n    IMessageHandler handler = MessageHandler.Instance;\n\n    while (true)\n    {\n        var client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);\n\n        // Without the await here, the thread will run free\n        var task = ProcessMessage(client);\n    }\n}\n\npublic void OnStop()\n{\n    _listener.Stop();\n}\n\npublic async Task ProcessMessage(TcpClient client)\n{\n    try\n    {\n        using (var stream = client.GetStream())\n        {\n            var message = await SimpleMessage.DecodeAsync(stream);\n            _handler.MessageReceived(message);\n        }\n    }\n    catch (Exception e)\n    {\n        _handler.MessageError(e);\n    }\n    finally\n    {\n        (client as IDisposable).Dispose();\n    }\n}	0
8621143	8621097	DateTime format with REST and json	static DateTime ConvertFromUnixTimestamp(double timestamp)\n{\n    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n    return origin.AddSeconds(timestamp);\n}\n\n\nstatic double ConvertToUnixTimestamp(DateTime date)\n{\n    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n    TimeSpan diff = date - origin;\n    return Math.Floor(diff.TotalSeconds);\n}	0
7117953	7117911	Regex camelcase in c#	string[] split = ("North Korea").Split(' ');\n\nStringBuilder sb = new StringBuilder();\n\nfor (int i = 0; i < split.Count(); i++)\n{\n    if (i == 0)\n        sb.Append(split[i].ToLower());\n    else\n        sb.Append(split[i]);\n}	0
43017	42990	Regex to match against something that is not a specific substring	foo.*(?<!bar)	0
9589919	9577139	CodeDomProvider Code Generation Fails in Web Project but not Console App	cp.ReferencedAssemblies.Add(HttpContext.Current.Server.MapPath("bin\\MyApp.Data.dll"));	0
8368941	8368885	Dynamically adding properties to a dynamic object?	dynamic d = new ExpandoObject();\n((IDictionary<string,object>)d)["test"] = 1;\n//now you have d.test = 1	0
25605397	25604273	How To Display Date In Locale For 0 Values?	using System;\n\nnamespace ConsoleApplication2\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int[] savedDates = new int[] { 000000, 010000, 000013 };\n\n        foreach (var item in savedDates)\n        {\n            DateTime date = ConvertToDate(item);\n            Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());\n        }\n        Console.ReadLine();\n    }\n\n    private static DateTime ConvertToDate(int item)\n    {\n        string temp = item.ToString("D6");\n        int day = int.Parse(temp.Substring(0, 2));\n        int month = int.Parse(temp.Substring(2, 2));\n        int year = int.Parse(temp.Substring(4, 2));\n\n        if (day == 0)\n            day = 1;\n\n        if (month == 0)\n            month = 1;\n\n        year += 2000;\n\n\n        return new DateTime(year, month, day);\n    }\n}\n}	0
10154703	10154419	Selecting in arrays the elements from a column of a datagridview	for ( int i=1; i<150; i++) \n  array[i] = MyDataGridView[1,i].value ;\nor\n  array[i]=  MyDataGridView.Rows[i].Cells[1].Value;	0
10483481	10483381	Set day of year DateTime	dayOfThisYear = new DateTime(DateTime.UtcNow.Year, 1, 1).AddDays(dayOfYear - 1);	0
17742581	17742434	Querying a database with an unknown number of paramaters	string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };\nstring cmdText = "SELECT * FROM Tags {0}";\n\nstring[] paramNames = tags.Select(\n            (s, i) => "@tag" + i.ToString()\n        ).ToArray();\n\nstring cmdWhere = paramNames.Length > 0 ? String.Format("WHERE Name IN ({0})", string.Join(",", paramNames)) : "";\nusing (SqlCommand cmd = new SqlCommand(string.Format(cmdText, cmdWhere)))\n{\n    for (int i = 0; i < paramNames.Length; i++)\n    {\n        cmd.Parameters.AddWithValue(paramNames[i], tags[i]);\n    }\n}	0
4030787	4029857	C# Linq Weighted Average Based on Date	var k = (from b in TableB\n        join bb in LinkAtoB on b.B_ID equals bb.B_ID into b_join\n        from ab in b_join.DefaultIfEmpty()\n        where b.B_DATE.CompareTo(DateTime.Now.AddDays(-7)) > 0\n        select new {ab.A_ID, DaysAgo = (DateTime.Now - b.B_DATE).Days} into xx\n        group xx by xx.A_ID into yy\n        select new {yy.Key, Weighted = yy.Sum(x=> 7 - x.DaysAgo) / yy.Count()} into zz\n        join a in TableA on zz.Key equals a.A_ID\n        select new {a.A_ID, a.A_Other_Stuff, zz.Weighted}).ToList();	0
9289049	9289007	Regular Expression for URL validation	Uri.IsWellFormedUriString(YourURLString, UriKind.RelativeOrAbsolute)	0
33729600	33698494	How to filter by several class name in opencover and report generator in bat	-filter:"+[*]*.AutomapperConfigurators.* +[*]ProjectName.BL.ServiceInteraction.*"	0
9733165	9731684	How to use Group by for tables in relation?	var Doctor = PatientsMasterItem.DoctorsMasterItem;\n\nvar PatientList = Doctor.PatientMasterItems;\n\nif(PatientList.Count() > 1)\n{\n\n}\nelse\n{\n\n}	0
3892048	3892042	Create HTTP post request and receive response using C# console application	System.Net.WebClient	0
11708343	11708145	how to set a fixed image map hotspot point?	int orig_width = 1600;\nint orig_height = 1200;\nint design_width = 800;\nint design_height = design_width * orig_height / orig_width; // keeps aspect ratio, or just use 600\n\nint coord_x1 = design_width * 752 / orig_width;\nint coord_y1 = design_height * 394 / orig_height;\nint coord_x2 = design_width * 1394 / orig_width;\nint coord_y2 = design_height * 491 / orig_height;\n\n...\nstring body = @"Good day, <br /><br />   \n    <b> Please participate in the new short safety quiz </b>"   \n    + link +   \n    @"<br /><br /> <h1>Picture</h1><br/><img width='"\n    + design_width +\n    "' height='"\n    + design_height +\n    @"' src='cid:image1' usemap ='#clickMap' alt='Click HERE'>";   \n\n// ...\n\nbody += "<map id ='clickMap' name='clickMap'> " +   \n      "<area shape ='rect' coords ='"\n      + coord_x1 + "," + coord_y1 + "," + coord_x2 + "," + coord_y2 +\n      "' href ='http://localhost/StartQuiz.aspx?testid="\n      + quizid + "' alt='Quiz' /></map>";	0
32648668	32647162	HTML Agility and String was not recognized as a valid DateTime	butikEndTime.replace(".","/");\nDateTime date = DateTime.ParseExact(butikEndTime, "dd/M/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);	0
20554658	20554358	XML element is not appended - XPath	var nodeList = layoutDocument.SelectNodes("//Layout[@class]");\nif (nodeList != null && nodeList.Count > 0)\n{\n    foreach (XmlNode node in nodeList)\n    {\n        XmlNode newNode = layoutDocument.CreateElement("iconlink");\n        XmlAttribute imageAtr = layoutDocument.CreateAttribute("image");\n        imageAtr.Value = "CC_Status_Background.png";\n        newNode.Attributes.Append(imageAtr);\n        node.AppendChild(newNode);\n        layoutModified = true;\n    }\n}	0
8122080	8119751	Serialization error while sending data table to WCF service	DataTable dt = new DataTable();\n...\ndt.TableName = "Table1";	0
16546979	16541932	Assert Javascript value in C# with Selenium	driver.FindElement(By.Id("j_idt13:JNumber")).GetAttribute("value");	0
29957554	29957498	Making a Subclass with one parameter to change a value of Parent Class	public class Shirt : Clothing\n{\n    public void ReNameShirt()\n    {\n//        Shirt Po = new Shirt(); You are a shirt, there is no need to create one.\n        name = "blue shirt";\n//        return ReNameShirt(); This will cause infinite recursion and crash.\n    }	0
31383286	31383093	How to convert DataTable values to json using C#?	Dictionary<string, string> dict = \n    dt.AsEnumerable()\n    .ToDictionary<DataRow, string, string>(row => row.Field<string>(1),\n                                           row => row.Field<string>(2));\n\nstring json = Newtonsoft.Json.JsonConvert.SerializeObject(dict);	0
6062785	6062725	How to avoid repeated code?	void SetupDataSource(DropDownList ddl, DataTable dt, string dataValueFieldm, string dataTextField)\n{\n    if (ddl != null)\n    {\n        ddl.DataValueField = dataValueField;\n        ddl.DataSource = dt;\n        if (!string.IsNullOrEmpty(dataTextField)) \n        {\n            ddl.DataTextField  = dataTextField;\n        }\n\n        ddl.DataBind();\n    }\n    else\n    {\n       throw new ArgumentNullException("ddl");\n    }\n}	0
19735337	19735319	monthCalender date format to yyyy-mm-dd : c#	monthCalendar1.SelectionStart.Date.ToString("yyyy-MM-dd");	0
1144544	1144535	HtmlEncode from Class Library	string TestString = "This is a <Test String>.";\nstring EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);	0
9330495	9330289	Using Linq to extract data from XML	XNamespace ns = "http://www.infoaxon.com/BPT/Services/Schemas/";\n var v = from page in doc.Elements("ReachResponseEnvelope").Elements("BPTResponse")\n                    select page;\n\n foreach (var record in v)\n {\n  var installRevenueElement = record.Element(ns+ "QuotePricing").Element(ns+ "TotalPricing").Element(ns + "InstallRevenue");\n  Console.WriteLine(installRevenueElement.Value);\n }	0
23592375	23591932	Set Default Image For Image Column?	dgv_AddJournal.CurrentRow.Cells["SearchAccount"].Value = Accounting.Genral.Properties.Resources._1396284460_system_search; \n            dgv_AddJournal.CurrentRow.Cells["SearchCostCenter"].Value = Accounting.Genral.Properties.Resources._1396284460_system_search;\n            dgv_AddJournal.CurrentRow.Cells["DeleteAccount"].Value = Accounting.Genral.Properties.Resources._1398281700_Gnome_Edit_Clear_64;\n            dgv_AddJournal.CurrentRow.Cells["DeleteCost"].Value = Accounting.Genral.Properties.Resources._1398281700_Gnome_Edit_Clear_64;	0
12381568	12381508	LINQ statement getting value from one table depending on the other table	var query = from subAgent in db.SubAgents\n            select subAgent.agent;	0
23543879	23543729	Marking an item in ListView	listView.Items[foundItem.Index].Selected = true;\nlistView.Select();	0
6051541	6051501	How to prevent recursion	public static void Save(OrderInfo item) {\n  for (int i = 0; i < item.Count; i++) {\n    if (item[i].Changed) {\n      item[i].Save();\n    }\n  }\n  if (item.Changed) {\n    item.Changed = false; // prevents recursion!\n    item.Save();\n    if error saving then item.Changed = true; // reset if there's an error\n  }\n}	0
32371314	32356384	Achieve table layout with String.Format	foreach (IMetricContract contract in metrics)\n            {\n                name = contract.Name;\n                desc = contract.Description;\n\n                Console.Write("".PadRight(13,'#')+name.PadRight(41,'i'));\n                Console.WriteLine(desc + "\n");\n\n            }	0
2096529	2096488	How to practically use Events?	btnMyButton.Click += (o, ev) => { SetTextLabel(label1, "You clicked the button"); };	0
8514006	8513915	C# Convert to Interface	public class Lookup<K, V>\n{\n    private readonly Func<K, V> lookup;\n    protected Lookup(Func<K, V> lookup)\n    {\n        this.lookup = lookup;\n    }\n\n    public static implicit operator Lookup<K, V>(Dictionary<K, V> dict)\n    {\n        return new Lookup<K, V>(k => dict[k]);\n    }\n\n    public V this[K key]\n    {\n        get { return lookup(key); }\n    }\n}	0
15857323	15857305	Reference to a directory?	DirectoryInfo di = new DirectoryInfo(textbox.Text);	0
29808149	29807992	Loading a combo box data source	bool TeamPlayers(string teamName, ComboBox team)//Makes the players of the selected team available for selection as scorers\n{\n    Dictionary<string, string[]> teamNames = new Dictionary<string, string[]>();\n\n    teamNames.Add("Canada", new string[] { "Johny Moonlight", "DTH Van Der Merwe", "Phil Mackenzie" });\n    teamNames.Add("New Zealand", new string[] { "Dan Carter", "Richie Mccaw", "Julian Savea" });\n    teamNames.Add("South Africa", new string[] { "Jean de Villiers", "Bryan Habana", "Morne Steyn" });\n\n    team.DataSource = teamNames[teamName];\n    return (true);\n}	0
3766535	3764317	How to stop certificate errors temporarily with WCF services	/// <summary>\n    /// Sets the cert policy.\n    /// </summary>\n    private static void SetCertificatePolicy()\n    {\n        ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;\n    }\n\n    /// <summary>\n    /// Certificate validation callback.\n    /// </summary>\n    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)\n    {\n        Debug.WriteLine("Trusting X509Certificate '" + cert.Subject + "'");\n        return true;\n    }	0
12998260	12997338	Getting number of disk accesses from BufferedStream	(filesize + bufsize - 1) / bufsize	0
10417242	10415920	ToolTip with text + databinder.eval	Tooltip='<%# "ID:" + DataBinder.Eval(Container.DataItem, "ID") %>'	0
11592716	11592529	String was not recognized as a valid DateTime	//20/7/2012 7:42:19 PM\n"dd/M/yyyy h:mm:ss tt",	0
10607989	10607758	Import data from a SQL DB Table's Column (a DataSet) into a TextBox?	protected void btnGetNPMEmailAddresses_Click(object sender, EventArgs e)\n{\n    // TODO:: Populate ObjectDataSource_Designee\n    DataSet dataSet = GetDS(ObjectDataSource_Designee);\n\n    string emails = string.Empty;\n    for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)\n    {\n        emails = emails + dataSet.Tables[0].Rows[i]["EmailAddresses"].ToString() + Environment.NewLine;\n    }\n    txbResults.Text = emails;\n}\n\nprivate DataSet GetDS(ObjectDataSource ods)\n{\n    var ds = new DataSet();\n    var dv = (DataView)ods.Select();\n    if (dv != null && dv.Count > 0)\n    {\n        var dt = dv.ToTable();\n        ds.Tables.Add(dt);\n    }\n    return ds;\n}	0
25405338	25361878	Master Page label control not keeping value on postback	protected void Page_PreRender(object sender, EventArgs e)\n    {\n        if(Session["Date"] != null)\n        {\n        string opponent = (string)Session["Opponent"];\n        string location = (string)Session["Location"];\n        DateTime GameDate = (DateTime)Session["Date"];\n        //DateTime CalendarDate = (DateTime)Session["Calendar"];\n        lblOponenet.Text = opponent;\n        lblLocation.Text = location;\n        lblGameDate.Text = GameDate.ToString();           \n\n        }\n\n    }\n    protected void Page_Load(object sender, EventArgs e)\n    {\n\n\n    }	0
31360972	31360388	PostAsJsonAsync cannot find requested URI	[Route("api/register/")]\npublic class RegisterController : ApiController	0
17646470	17646362	How underline text in MS Word with wavy red lines?	targetWord.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;	0
8022736	8022724	Textbox values to array	TextBox tb = (TextBox) Controls["txtText" + i];	0
17104369	17095567	Delete local SVN authentication credentials with SharpSVN	using (SvnClient client = new SvnClient())\n\n{\n\n    //delete all Svn Authentication credential stored in the computer    \n    foreach (var svnAuthenticationCacheItem in client.Authentication.GetCachedItems(SvnAuthenticationCacheType.UserNamePassword))    \n    {   \n        svnAuthenticationCacheItem.Delete();    \n    }\n\n}	0
14437248	14437207	Find matching string from List of Class/Object	var result = PropertyIds.Except(properties.Select(p => p.PropertyId));	0
14288157	14284256	How to manually set upstream proxy for fiddler core?	oSession["X-OverrideGateway"] = "someProxy:1234";	0
13166324	12994188	How can I play H.264 RTSP video in Windows 8 Metro C# XAML app?	MediaElement.SetSource	0
28192913	28192663	Remove item from List that I'm iterating, or filtering complex List of duplicates	public List<Dimensions> Consolidation(List<Dimensions> vm)\n{\n    return vm.GroupBy(d=>new {d.TypeId, d.Width, d.Height}) // if there are any duplicates, they are grouped here\n            .Select(g=>new Dimensions(){TypeId = g.Key.TypeId , \n                                        Width = g.Key.Width, \n                                        Height = g.Key.Height,\n                                        PeacesForItem = g.Sum(dim=>dim.PeacesForItem)}) // number of duplicates in group calculated\n            .ToList();\n}	0
9196857	9196796	Group a collection and return a Dictionary	public ILookup<string, PriceDetail> GetGroupedPriceDetails(IEnumerable<PriceDetail> priceDetails)\n{\n     return priceDetails.ToLookup(priceDetail => priceDetail.Code);\n}	0
22462087	22461386	Like and Dislike button in Gridview. How to implement?	protected void BtnLike_Click_Click(object sender, EventArgs e)\n    {\n\n\n        GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;\n        Button BtnLike_Click = (Button)row.FindControl("BtnLike_Click");\n        Button btnDislike_Click = (Button)row.FindControl("btnDislike_Click");\n        BtnLike_Click.Enabled = false;\n        btnDislike_Click.Enabled = true;\n    }\n\n    protected void btnDislike_Click_Click(object sender, EventArgs e)\n    {\n        GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;\n        Button BtnLike_Click = (Button)row.FindControl("BtnLike_Click");\n        Button btnDislike_Click = (Button)row.FindControl("btnDislike_Click");\n        BtnLike_Click.Enabled = true ;\n        btnDislike_Click.Enabled = false ;\n    }	0
18098825	18096781	Use only list/collection to store data locally on webpage	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.ComponentModel;\n\nnamespace BindingListSample\n{\n    public partial class _Default : System.Web.UI.Page\n    {\n        static List<Employee> bindingL = new List<Employee>();\n        protected void Btn_Click(object sender, EventArgs e)\n        {\n            bindingL.Add(new Employee { Name = TxtName.Text });\n            GrvSample.DataSource = bindingL;\n            GrvSample.DataBind();\n        }\n    }\n    public class Employee\n    {\n        public string Name { get; set; }\n    }\n}	0
22707717	22707683	DateTime TryParse Exact returning 0001:01:01	"dd'/'M'/'yyyy"	0
3118346	3118208	How can i use unioan and nested from linq?	var id = \n  (from task in stock.CTasks select new { task.id, task.workorder, jobseqno= task.jobseqno } )\n  .Union(from card in stock.NonRoutineCards select new { card.id, card.workorderno, jobseqno = card.cardno })\n  .Union(from card in stock.AdditionalWorkCards select new { card.id, card.workorderno, jobseqno = card.cardno })\n  .Where(x => x.workorderno.TrimEnd() == ToNo && x.jobseqno == ToSeq)\n  .FirstOrDefault();	0
26714939	26714669	Find value via property name in json.net?	jt["results"].Children()\n    .Select(t => t["address_components"])\n    .Where(a => a != null)\n    .Children()\n    .Where(c => c["types"].Children().Contains("country"))\n    .Select(a => a["long_name"])\n    .ToArray();	0
1990318	1990287	Save struct into a file In C#	System.IO	0
9842427	9840592	How can I assign a variable from a static property using Expression Trees?	var dateTimeNow = Expression.Property(\n    Expression.Property(null, typeof(DateTime).GetProperty("Now")),\n    "Date");	0
22653553	22653512	how to combine multiple LINQ Expressions	var albumList = db.Albums.Include(a => a.Artist).Include(a => a.Genre) //1st part\n    .Where(a=>a.GenreId==GenreId).OrderByDescending(x=>x.AlbumId) //2nd part\n    .ToList(); //3rd part	0
9683579	9683414	Create a custom exception using C#	catch (MyException ex)\n        {\n            Console.WriteLine(ex.ErrorCode);\n        }	0
33284455	33283572	Trying to get a working web.config section for this programmatic AD FS configuration	SecurityTokenHandlers = System.IdentityModel.Services.FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;	0
10708694	10708556	How do I make a checkbox checked by default in a Data Grid View?	foreach (DataGridViewRow row in dataGridView.Rows)     \n{\n    row.Cells[CheckBoxColumn.Name].Value = true;     \n}	0
6334252	6305505	How do I extract attachments from a pdf file?	Map<String, byte[]> files = new HashMap<String,byte[]>();\n\nPdfReader reader = new PdfReader(pdfPath);\nPdfDictionary root = reader.getCatalog();\nPdfDictionary names = root.getAsDict(PdfName.NAMES); // may be null\nPdfArray embeddedFiles = names.getAsArray(PdfName.EMBEDDEDFILES); //may be null\nint len = embeddedFiles.size();\nfor (int i = 0; i < len; i += 2) {\n  PdfName name = embeddedFiles.getAsName(i); // should always be present\n  PdfDictionary fileSpec = embeddedFiles.getAsDict(i+1); // ditto\n  PRStream stream = (PRStream)fileSpec.getAsStream(PdfName.EF);\n  if (stream != null) {\n    files.put( PdfName.decodeName(name.toString()), stream.getBytes() );\n  }\n}	0
20533956	20533855	How to mark instance for deletion in XNA/Monogame	Enemy e = new Enemy();\n\n// do stuff with enemy\n\n// Set to null\ne = null;	0
19910693	19910320	Accessing a class field using a string	//get the property indicated by parameter 'field'\n//Use 'GetField' here if they are actually fields as opposed to Properties\n//although the merits of a public field are dubious...\n       var prop = object1.GetType().GetProperty(field);\n//if it exists\n        if (prop!=null)\n        {\n          //get its value from the object1 instance, and compare\n          //if using Fields, leave out the 'null' in this next line:\n          var propValue = prop.GetValue(object1,null);\n\n          if (propValue==null) return false;\n          return propValue;\n        }\n        else\n        {\n          //throw an exception for property not found\n        }	0
24350973	24350844	Do I need to dispose of dynamically-created controls before exiting a form?	USER Objects	0
9652743	9652539	How get name of method in the method	public void MyMethod(Notifier not)\n{ \n    if(not.HasValue())\n    {\n        string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;\n        throw new Exception(methodName + ": " + not.Value);\n    }\n}	0
34335563	34335471	Can I dispose multiple Objects in a single go?	inst1?.Dispose();\ninst2?.Dispose();\ninst3?.Dispose();	0
25878634	25878489	Console keeps giving me NAN	Math.Log10(monthly-borrowed*rate)	0
11992740	11947301	Restart page numbering in header with OpenXML SDK 2.0	string headerID = "YOUR_HEADER_ID";\nint pageNumberStart = 1\n\nvar paragraph = new Paragraph(\n   new ParagraphProperties(\n      new SectionProperties(\n         new HeaderReference { Id = headerID },\n         new PageNumberType { Start = pageNumberStart }\n      )\n   )\n);	0
214152	214124	winforms html editor	Me.WebBrowser1.Navigate("about:blank")\nApplication.DoEvents()\nMe.WebBrowser1.Document.OpenNew(False).Write("<html><body><div id=""editable"">Edit this text</div></body></html>")\n\n'turns off document body editing\nFor Each el As HtmlElement In Me.WebBrowser1.Document.All\n    el.SetAttribute("unselectable", "on")\n    el.SetAttribute("contenteditable", "false")\nNext\n\n'turns on editable div editing\nWith Me.WebBrowser1.Document.Body.All("editable")\n    .SetAttribute("width", Me.Width & "px")\n    .SetAttribute("height", "100%")\n    .SetAttribute("contenteditable", "true")\nEnd With\n\n'turns on edit mode\nMe.WebBrowser1.ActiveXInstance.Document.DesignMode = "On"\n'stops right click->Browse View\nMe.WebBrowser1.IsWebBrowserContextMenuEnabled = False	0
2142807	2141335	Is there a way to use Expression.In() in a case insensitive way?	.Add(Restrictions.In(\n    Projections.SqlFunction("lower", NHibernateUtil.String, Projections.Property("targetName")), \n    new object[] {"target1", "target2"} ))	0
11308445	11308346	ASP.NET - Export gridview data to excel and directly send a mail	string filename = "Test.xls"; \n        System.IO.StringWriter tw = new System.IO.StringWriter();\n        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);\n\n        //Get the H`enter code here`TML for the control.\n        yourGrid.RenderControl(hw);\n        //Write the HTML back to the browser.\n        Response.ContentType = "application/vnd.ms-excel";\n        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");\n\n        Response.Write(tw.ToString());	0
17831474	17827611	Using streamreader in c#	private void GetExchangeRate()\n{\n    string[] lines = File.ReadAllLines("Exchange.txt");\n\n    foreach (var line in lines) { \n        //Suppose your line contains 'Singapore' and you want to do somthing if line contains the singapore then you should do as \n         if(line.Contains("Singapore"))\n          {\n               lblDisplay.Text = "Singapore"\n          }\n       //Do your functionality that is which line to display depending upon country\n       // You can match the line and display them according to your need  \n    }\n }	0
5701812	5701760	How to find Vertical Scrollbar width of a Scrollviewer in C#	SystemParameters.VerticalScrollBarWidth	0
14203764	14199748	Overcoming ambiguity in HTMLAgility pack (Windows Phone 7)	HtmlDocument doc = new HtmlDocument();\n        // v== Add this line before loading a document\n        HtmlNode.ElementsFlags.Remove("form"); \n        doc.Load("doc.html");	0
14504629	14504545	Check if renaming of a folder is successful by using a batch file	process.StartInfo.FileName = @"C:\MyBatchFile.bat";\n        process.Start();\n        process.WaitForExit();\n\n        // Check if renaming is successful.\n        if (process.ExitCode != 0)\n        {\n            // Renaming failed.\n        }	0
23141671	23065666	how to avoid common tern in elasticsearch	.Query(b => b.CommonTerms(c => c.CutOffFrequency(0.1)))	0
10361219	10360885	How to find what object called a context menu	private void menuIndexEdit_Opening(object sender, CancelEventArgs e)\n{\n    if (contextMenuStrip1.SourceControlis PictureBox)\n    {\n        string strname = ((PictureBox)contextMenuStrip1.SourceControl).Name;\n    }\n}	0
2081964	2081953	User Control - Custom Properties	[Description("Test text displayed in the textbox"),Category("Data")] \npublic string Text {\n  get { return myInnerTextBox.Text; }\n  set { myInnerTextBox.Text = value; }\n}	0
556922	556909	better way to fill a dropdownlist with linq to xml	cboChannel.DataSource = feeds.Where(x => !String.IsNullOrEmpty(x.channel)).ToList();	0
10916674	10915474	Get last item added in a BindlingList	class Program\n{\n    static object last_item;\n\n    static void Main(string[] args)\n    {\n        BindingList<object> WorkoutScheduleList = new BindingList<object>();\n\n        WorkoutScheduleList.ListChanged += (s, e) => {\n            if (e.ListChangedType == ListChangedType.ItemAdded)\n                last_item = WorkoutScheduleList[e.NewIndex];\n        };\n\n        WorkoutScheduleList.Add("Foo");\n        WorkoutScheduleList.Add("Bar");\n        WorkoutScheduleList.Insert(1, "FooBar");\n\n        //prints FooBar\n        Console.WriteLine(String.Format("last item added: {0}", last_item));\n    }\n}	0
17054560	17054130	C# .net Selenium, how to insert a date and time using sendKeys()	var query = driver.FindElement(By.Name("txtbox"));\nDateTime y = DateTime.Today;\nquery.SendKeys(y.ToString()); // you shouldn't send string "y", but the y.ToString()	0
21426388	21426354	How to close a file after creating it	File.Open(path, FileMode.Open)	0
2996600	1764875	Tables created programmatically don't appear in WebBrowser control	var tbody = doc.CreateElement("TBODY");\n\n...\n\ntbody.AppendChild(row1);\ntable.AppendChild(tbody);\ndiv.AppendChild(table);	0
10189157	10189048	JSON RPC Returns numbers as property names	[JsonProperty("1")]	0
19068882	19068536	Impact of SQL Transaction in WCF Transaction	[OperationBehavior(TransactionScopeRequired = true)]	0
22708984	22695315	Add element to Json within JArray	string json = @"[\n    {""1"":""One"",""2"":""AddThree""},\n    {""1"":""One"",""2"":""Two""},\n    {""1"":""One"",""2"":""AddThree""}\n    ]";\n\n    JArray rows = JArray.Parse(json);\n    foreach (var row in rows)\n    {\n        string s = row["2"].ToString();\n        if (s == "AddThree")\n        {\n            row["3"] = "Three";\n        }\n    }\n\n    Console.WriteLine(rows.ToString());\n    Console.ReadKey();	0
7995161	7995024	Saving excel in clients Machine using Interop	public FilePathResult GetFile()\n{\n    string name = System.IO.Path.GetTempPath()+Guid.NewGuid().ToString()+".xls";\n    // do the work\n    xlWorksheet.Save(name);\n    return File(name, "Application/x-msexcel");\n}	0
2373393	2373355	Connecting to ACCDB format MS-ACCESS database through OLEDB	"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\marcelo.accdb;Jet OLEDB:Database Password=MyDbPassword;"	0
10613825	10613716	How can I arrange items in a table - MVC3 view (Index.cshtml)	foreach (var f in m.Foods)\n{\n    <tr>\n        <td>@f.Type</td>\n        foreach (var a in m.AmountOfVitamins)\n        {\n            <td>a.Amount</td>\n        }\n    </tr> \n}	0
8780878	8780450	button event with validation and actions	private void bCheck_Click(object sender, EventArgs e)\n        {\n            bool found = false;\n            foreach (Label l in pole)\n            {\n                if (l.Location == lblCovece.Location && l.Text == txtGoal.Text)\n                {\n                    l.BackColor = Color.Green;\n\n                    score += int.Parse(l.Text);\n                    lblResultE.Text = score.ToString();\n                    found = true;\n                }\n            }\n            if (!found)\n            {\n                score -= 10;\n                lblResultE.Text = score.ToString();\n            }\n        }	0
31441197	31441101	How can I get the Items in a DataGrid into a List<T> or some other collection?	var list = DataGrid.Items.OfType<yourType>().OrderBy(q => q.CurrentTime).ToList();	0
24484206	24483958	WP8 Item not found in LongListSelector	llsTest.ScrollTo(list[15]);	0
9975334	9974879	How to pass a view model in custom event args	public void Handle(ViewModelChangedEventArgs message)\n{  \n    var viewModel = viewModelFactory.Create(typeof(AnotherViewModel));\n}	0
11873617	11873179	Format String to Datetime with Timezone	string dts = "May 16, 2010 7:20:12 AM CDT";\nDateTime dt = \n    DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "MMM dd, yyyy H:mm:ss tt zzz", null);	0
17280962	17280869	Concat bits into one string	var bitString = string.Concat(encoded.Select(bit => bit ? "1" : "0"))	0
34366138	34362217	UWP: How do you decrease the quality of a selected image?	using (IRandomAccessStream fileStream = await result.OpenAsync(FileAccessMode.Read))\n{\n    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);\n    using (var encoderStream = new InMemoryRandomAccessStream())\n    {\n        BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(encoderStream, decoder);\n        var newHeight = decoder.PixelHeight / 2;\n        var newWidth = decoder.PixelWidth / 2;\n        encoder.BitmapTransform.ScaledHeight = newHeight;\n        encoder.BitmapTransform.ScaledWidth = newWidth;\n\n        await encoder.FlushAsync();\n\n        byte[] pixels = new byte[newWidth * newHeight * 4];\n\n        await encoderStream.ReadAsync(pixels.AsBuffer(), (uint)pixels.Length, InputStreamOptions.None);\n}	0
12311135	12311043	MySql get transactions that occurred with the current date	var date = new DateTime(2012, 9, 5);\nvar dateEntities = Entities.Where(e => EntityFunctions.DiffDays(e.Date, date) == 0 )	0
13252783	13252691	Making a batch file in C# then executing it	cd C:\Users\Steve Jobs\Pictures\SetMACE_v1006\nsetMACE_x64.exe "C:\Users\Steve Jobs\Documents\avast.cap" -d  >>logfile.txt	0
10907061	10906919	Parsing Friendly Routed URL Parameter	if (!Page.IsPostBack)\n{\n    if (Page.RouteData.Values["EventID"] != null)\n    {\n        int eventID = Convert.ToInt32(Page.RouteData.Values["EventID"]);\n    }\n}	0
9560123	9552335	How to open a packaged file with WinRT	public override async Load()\n    {\n        var file = await GetPackagedFile("assets", "world.xml");\n        LoadXml(file);\n    }\n\n    private async void LoadXml(StorageFile file)\n    {\n        XmlLoadSettings settings = new XmlLoadSettings() { ValidateOnParse = false };\n        XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(file, settings);\n\n        foreach (IXmlNode xmlNode in xmlDoc.ChildNodes)\n        {\n            //ProcessNode(xmlNode);\n        }\n    }\n\n    private async Task<StorageFile> GetPackagedFile(string folderName, string fileName)\n    {\n        StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;\n\n        if (folderName != null)\n        {\n            StorageFolder subFolder = await installFolder.GetFolderAsync(folderName);\n            return await subFolder.GetFileAsync(fileName);\n        }\n        else\n        {\n            return await installFolder.GetFileAsync(fileName);\n        }\n    }\n}	0
8242598	8242541	Parsing xml element to class	XmlDocument doc = new XmlDocument();\ndoc.Load("file.xml");\n\nXmlNodeList nodes = doc.SelectNodes("/account_order/row/exchangerate");\nforeach (XmlNode node in nodes)\n{\n    XmlAttribute ccyAttribute = node.Attributes["ccy"];\n    //etc...\n}	0
19191425	18665832	Printing Excel 2003 sheet using c#	object misValue = System.Reflection.Missing.Value;\n\nMicrosoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();\nMicrosoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(Form1.excelPath, misValue, misValue, misValue, \n    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);\nMicrosoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];\n\n//bring about print dialogue\nbool userDidntCancel = excelApp.Dialogs[Microsoft.Office.Interop.Excel.XlBuiltInDialog.xlDialogPrint].Show(misValue,\n    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue,\n    misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue,\n    misValue, misValue, misValue, misValue, misValue);	0
3125329	3125153	Dynamically loading a resource and reading the correct value for the CurrentUICulture	public static string EnumToString<T>(object obj)\n{\n      string key = String.Empty;\n\n      Type type = typeof(T);\n\n      key += type.Name + "_" + obj.ToString();\n\n      Assembly assembly = Assembly.Load("EnumResources");\n\n      string[] resourceNames = assembly.GetManifestResourceNames();\n\n      ResourceManager = null;\n\n      for(int i = 0; i < resourceNames.Length; i++)\n      { \n           if(resourceNames[i].Contains("Enums.resources"))\n           {\n                //The substring is necessary cause the ResourceManager is already expecting the '.resurces'\n                rm = new ResourceManager(resourceNames[i].Substring(0, resourceNames[i].Length - 10), assembly);\n\n                return rm.GetString(key);\n           }\n\n           return obj.ToString();\n      }\n\n}	0
13510548	13510348	Make Regex stop looking at \n	(?<=ces)[^\\n]+	0
23950973	23883387	ThisMember Composite object with recursive mapping	var catDTO = new CategoryDTO {\n  Title = "Parent",\n  ChildrenNodes = new List<CategoryDTO> { new CategoryDTO { Title = "Child" }}\n};            \n\nvar mapper = new MemberMapper();\nmapper.CreateMap<CategoryDTO, Category>(category => new Category {\n  ChildrenNodes = \n    category.ChildrenNodes == null ? null :\n      category.ChildrenNodes.Select(c => mapper.Map<CategoryDTO, Category>(c)).ToList()\n});\n\nvar mappedCategory = mapper.Map<CategoryDTO, Category>(catDTO);	0
10894018	10893781	How to find the number of items in a DynamicNodeList?	var root = Model.NodeById(id);\nvar nodes = root.Descendants("ChartItem");\n\nif (nodes.Count() > 0)\n{\n    s = s + "<ul>";\n}	0
10690935	10690668	Deserialize a restful uri	public class GeoNames\n{\n    [XmlElement("country")]\n    public Country[] Countries { get; set; }\n}\n\npublic class Country\n{\n    [XmlElement("countryName")]\n    public string CountryName { get; set; }\n\n    [XmlElement("countryCode")]\n    public string CountryCode { get; set; }\n} \n\nclass Program\n{\n    static void Main()\n    {\n        var url = "http://ws.geonames.org/countryInfo?lang=it&country=DE";\n        var serializer = new XmlSerializer(typeof(GeoNames), new XmlRootAttribute("geonames"));\n        using (var client = new WebClient())\n        using (var stream = client.OpenRead(url))\n        {\n            var geoNames = (GeoNames)serializer.Deserialize(stream);\n            foreach (var country in geoNames.Countries)\n            {\n                Console.WriteLine(\n                    "code: {0}, name: {1}", \n                    country.CountryCode, \n                    country.CountryName\n                );\n            }\n        }\n    }\n}	0
26280826	26268776	How to Generate CheckBoxes checked inside a DataGridView dynamically in C#?	DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();\n            dataGridView1.Columns.Add(chk);\n            chk.HeaderText = "Check Data";\n            chk.Name = "chk";\n            dataGridView1.Rows[2].Cells[3].Value = true;	0
9279271	9278811	Cursor moving to next cell in DataGridView	private bool dont_jump;\n    private int col_index;\n    private int row_index;\n\n    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n    {\n        dont_jump = true;\n        col_index = e.ColumnIndex;\n        row_index = e.RowIndex;\n    }\n\n    private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n    {\n        if (dont_jump)\n        {\n            dont_jump= false;\n            dataGridView1.CurrentCell = dataGridView1[col_index, row_index];\n        }\n    }	0
1532848	1532429	How can I write an XML on my hard drive to GetRequestStream	XmlDocument sampleRequest = new XmlDocument();\n    sampleRequest.Load(@"C:\SampleRequest.xml");\n    //byte[] bytes = Encoding.UTF8.GetBytes(sampleRequest.ToString());\n    byte[] bytes = Encoding.UTF8.GetBytes(sampleRequest.OuterXml);	0
3386163	3385625	How to capture Post data from silverlight app?	using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))\n        {\n            string t = sr.ReadToEnd();\n        }	0
6801158	6711478	C# CheckBoxList update in SQL Server	if (CheckBoxList1.Items[i].Selected)\n        {\n            PartnerName = CheckBoxList1.Items[i].Text;\n            Update(PartnerName, CheckBoxList1.Items[i].Selected);\n        }	0
12559942	12559817	Rename parameters type for client	[DataContract(Name = "Model1")]\npublic class Model1V1\n{ ...	0
24397628	24347145	Windows phone and Sqlite. Making a select	var returnedCollection = App.db.Query(?select Email from Usuario?);\nfor (int i = 0; i < returnedCollection.Count(); i++)\n{\nMessageBox.Show(returnedCollection[0].Email.ToString());\n}	0
21267151	21267093	Conversion of C# decimal values of System.Array in into string	StringBuilder sb = new StringBuilder();\n\nsb.Append(((double)data.GetValue(0)).ToString(CultureInfo.InvariantCulture));	0
32078792	32074072	Detect tap in Samsung Gear VR	using UnityEngine;\npublic class ClickDetector:MonoBehaviour {\n\n    public int button=0;\n    public float clickSize=50; // this might be too small\n\n    void ClickHappened() {\n        Debug.Log("CLICK!");\n    }\n\n    Vector3 pos;\n    void Update() {\n      if(Input.GetMouseButtonDown(button))\n        pos=Input.mousePosition;\n\n      if(Input.GetMouseButtonUp(button)) {\n        var delta=Input.mousePosition-pos;\n        if(delta.sqrMagnitude < clickSize*clickSize)\n          ClickHappened();\n      }\n    }\n}	0
20329059	20285033	Create a random point within a polygon using arcobjects in C#?	private double GetRandomDouble(double Min, double Max)\n        {\n            //TODO:\n            // seed\n            Random random = new Random();\n            return random.NextDouble() * (Max - Min) + Min;\n        }\n\n\n\nprivate IPoint Create_Random_Point(IGeometry inGeom)\n        {\n\n                double x = GetRandomDouble(inGeom.Envelope.XMin, inGeom.Envelope.XMax);\n                double y = GetRandomDouble(inGeom.Envelope.YMin, inGeom.Envelope.YMax);\n\n\n                IPoint p = new PointClass();\n                p.X = x;\n                p.Y = y;\n\n                return p;\n        }	0
16274966	16273363	Sorting grid view column using linq	string sortColumn = e.SortExpression;\n    IQueryable<BusinessRisk> sortedList = (from p in this.BusinessRiskList\n                                           select new BusinessRisk\n                                           {\n                                               BusinessRiskText = p.BusinessRiskText,\n                                               IsActive = p.IsActive,\n                                               Description = p.Description,\n                                               BusinessObjective = new BusinessObjective { BusinessObjectiveText = p.BusinessObjective.BusinessObjectiveText }\n                                           }).AsQueryable().OrderBy(e.SortExpression);\n\n\n\n\n    this.BusinessRiskList = sortedList.ToList<BusinessRisk>();\n    gvBussinessRisks.DataSource = sortedList;\n    gvBussinessRisks.DataBind();	0
23965250	23965052	Extract Two Nodes from one XElement and create a new XElement	var parsed = XElement.Parse('here your xml as string');\n\nvar addTree = new XElement("addTree",\n    new XElement("channel_texting_id", parsed.Element("channel_texting_id").Value),\n    new XElement("channel_id", parsed.Element("channel_id").Value));	0
33746618	33746590	Pause until external window handle is either closed or button pressed	while (SomeWindow.IsActive); // Perform loops until SomeWindow is active	0
26661730	26659030	How to get Image.Source as string	Xamarin.Forms.Image objImage;\n..\n..\n\n..\nif (objImage.Source is Xamarin.Forms.FileImageSource)\n{\n    Xamarin.Forms.FileImageSource objFileImageSource = (Xamarin.Forms.FileImageSource)objImage.Source;\n    //\n    // Access the file that was specified:-\n    string strFileName = objFileImageSource.File;\n}	0
21134719	21134479	Generic class with unused generic parameter in constructor	public class My<T,S>\n{\n   public My(G<S> g, T t)\n   {\n       // code that DOES NOT use S in any way\n   } \n}	0
29439011	29438972	When button clicked +1	private int Amount = 0;\nprivate void Button1_Click(object sender, RoutedEventArgs e)\n{\n    Amount++;\n    Label.Content = Amount;\n}	0
4195232	4194822	Validation of input into partial view	try\n{\n  UpdateModel(evaluation, "evaluation");\n  //"Update to db" code\n}\ncatch\n{\n  Evaluation.ViewModels.EvaluationEditViewModel viewModel = new    \n  Evaluation.ViewModels.EvaluationEditViewModel();\n  viewModel.evaluation = evaluation;\n  return View(viewModel);\n}	0
13204533	13204515	How to call JavaScript function in HTML from external script	function1();	0
7341196	6851961	Using RegSetKeySecurity to avoid registry redirection	[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]\ninternal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string stringSecurityDescriptor, int stringSDRevision, out IntPtr ppSecurityDescriptor, ref int securityDescriptorSize);\n\nstring sddl = "...";\nIntPtr secDescriptor = IntPtr.Zero;\nint size = 0;\nConvertStringSecurityDescriptorToSecurityDescriptor\n   (\n      sddl,\n      1,                              // revision 1\n      out secDescriptor,\n      ref size\n   );\n\n// get handle with RegOpenKeyEx\n\nRegSetKeySecurity\n(\n     handle,\n     0x00000004,                      // DACL_SECURITY_INFORMATION\n     secDescriptor\n);	0
30834304	30831782	Enumerate and apply WPF styles programmatically	VisualStateManager.GoToState(HelloWorldButton, "MouseOver", true);	0
25649446	25648747	ListView - Binding listviewitem data to an object	public class Test : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)\n    {\n        var e = PropertyChanged;\n        if (e != null)\n            e(this, args);\n    }\n\n    private bool isTrue;\n    public Boolean IsTrue\n    {\n        get { return isTrue; }\n        set\n        {\n            if (isTrue == value)\n                return;\n            isTrue = value;\n            OnPropertyChanged(new PropertyChangedEventArgs("IsTrue"));\n        }\n    }\n\n    public string Name { get; private set; }\n\n    public Test(Boolean isTrue, string name)\n    {\n        this.isTrue = isTrue;\n        Name = name;\n    }\n}	0
1728318	1728303	How can I split and trim a string into parts all on one line?	List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();	0
25306679	25306599	how to know if a string contains any of the strings on a list?	var result1 = lst01.Any(v=> myString.Contains(v));\n var result2 = lst02.Any(v=> myString.Contains(v));	0
5807363	5807310	Images in a WPF Window throw exception when launched via reflection	Source="/AssemblyName;component/image/effect.png"	0
23783537	23783409	How to add view in MVC 4	UserAdd()	0
507562	505167	How do I make a WinForms app go Full Screen	private void Form1_Load(object sender, EventArgs e)\n{\n    this.TopMost = true;\n    this.FormBorderStyle = FormBorderStyle.None;\n    this.WindowState = FormWindowState.Maximized;\n}	0
12979882	12979854	C# compare datetime with current datetime	TimeSpan diff = date2.Subtract(date1);\n       if(diff.Hours > 30)\n{\n//do action;\n}	0
17088593	17067670	Gridview, change visible values	protected string QuarterConvert(object strValue)\n    {\n        string retString = "";\n\n        switch (Convert.ToString(strValue))\n        {\n            case "1":\n                retString = "Q1";\n                break;\n            case "2":\n                retString = "Mid-Year";\n                break;\n            case "3":\n                retString = "Q3";\n                break;\n            case "4":\n                retString = "Year-End";\n                break;\n            default:\n                break;\n\n        }\n        return retString;\n    }	0
27482303	27360839	Dynamically adding rows to ASP.NET repeater in reaction to event	FilterState state = GetState();\nstate.Conditions.Add(new ConditionState { Item = condition });\nSetState(state);	0
6737554	6737504	Help with String parsing	var dummy = 0;\n\nvar intStrings =\n    testString.Split(',')\n        .Where(s => s.Contains(":") && int.TryParse(s.Split(':')[1], out dummy))\n        .ToArray();\n\nvar result = String.Join(",", intStrings);	0
7572073	7572006	LINQ Select distinct from a List?	var groupedPersons = personList.GroupBy(x => x.City);\nforeach (var g in groupedPersons)\n{\n    string city = g.Key;\n    Console.WriteLine(city);\n    foreach (var person in g)\n    {\n        Console.WriteLine("{0} {1}", person.Name, person.LastName);\n    }\n}	0
1044279	1044196	How to Sort a GridItemCollection	GridItemCollection items = (GridItemCollection)Session["driveLayout"];\nvar sortedItems = items.OfType<GridItem>().OrderBy(item => item.GridItems["VolumeGroup"].ToString().ToLower());	0
7199761	7199742	How can I ensure my c# string ends in a period?	namespace ExtensionMethods\n{\n    public static class StringExtensionMethods\n    {\n        public static string EnsureEndsWithDot(this string str)\n        {\n            if (!str.EndsWith(".")) return str + ".";\n            return str;\n        }\n    }\n}	0
30119254	30119174	Converting a hex string to its BigInteger equivalent negates the value	string hex = "09782E78F1636";\n      BigInteger b1 = BigInteger.Parse(hex,NumberStyles.AllowHexSpecifier);\n    Console.WriteLine(b1);	0
4945082	4945022	Retrieve value from attribute in HTML tag in asp.NET	mytag.Attributes["nameofmyattribute"]	0
13276624	13276147	programmatically reboot in safe mode then execute program	bcdedit /set {current} safeboot Minimal	0
9348458	9348434	Separating a string to multiple parts	String s = "22.3'33'44";\nString[] parts = s.Split('\'');	0
5758573	5758526	What is the fastest way to read data from a DbDataReader?	using (connection)\n    {\n        SqlCommand command = new SqlCommand(\n          "SELECT CategoryID, CategoryName FROM dbo.Categories;" +\n          "SELECT EmployeeID, LastName FROM dbo.Employees",\n          connection);\n        connection.Open();\n\n        SqlDataReader reader = command.ExecuteReader();\n\n        while (reader.HasRows)\n        {\n            Console.WriteLine("\t{0}\t{1}", reader.GetName(0),\n                reader.GetName(1));\n\n            while (reader.Read())\n            {\n                Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),\n                    reader.GetString(1));\n            }\n            reader.NextResult();\n        }\n    }	0
5384073	5384018	uploading via http	Server.MapPath("~/")	0
15102546	15102523	In C# how to remove items in an array after a certain length?	myList = myList.Take(maxLength).ToList();	0
11001188	11000346	add a line to SPFile object	using (var readStream = file.OpenBinaryStream())\n{ \n  using(var reader = new StreamReader(readStream)\n  {\n    var allText = reader.ReadToEnd();\n    var writeStream = new MemoryStream();\n    using(var writer = new TextWriter(writeStream))\n    {\n      writer.Write(allText);\n      writer.Write(extraText);\n    }\n    file.SaveBinary(writeStream.ToArray();\n  }\n}	0
11246411	11244609	NHibernate fluent HasMany mapping inserts NULL Foreign key	test.Orders.Add(new Order("test") { Company = test });	0
12918314	12918227	How to passing object as parameter in C++?	#include <iostream>\n#include <string>\n\ntemplate <class T> void test(const T& val)\n{\n    std::cout << val << "\n";\n}\n\n\nint main(int ac, char **av)\n{\n    std::string x = "Hello World";\n    test(x);\n    int y = 101;\n    test(y);\n}	0
8625188	8625180	Ask for a linq to manipulate arrays of array	var results = from x in myArray\n              from s in x.Students\n              select new { x.Mark, name = s };	0
11812434	11812059	Windows 8 Metro focus on grid	CoreWindow.GetForCurrentThread().KeyDown += Window_KeyDown;	0
17525879	17524240	Compare Validation for dates of format dd-MMM-yyyy	function ValidateDate() {\n        var fromdate = document.getElementById("txtFromDate");\n        var todate = document.getElementById("txtToDate");\n        var endDate = todate.value;\n        var startDate = fromdate.value;\n\n        /* Convert the date 01-Jan-1991 to Jan 1, 1991 */\n\n        var splitdate = startDate.split("-");\n        var dt1 = splitdate[1] + " " + splitdate[0] + ", " + splitdate[2];\n        var splitdate = endDate.split("-");\n        var dt2 = splitdate[1] + " " + splitdate[0] + ", " + splitdate[2];\n\n        var newStartDate = Date.parse(dt1); //Parse the date to  milliseconds since January 1, 1970, 00:00:00 UTC\n        var newEndDate = Date.parse(dt2);\n\n        if (newStartDate > newEndDate ) {\n            alert("Please ensure that the End Date is greater than or equal to the Start Date.");\n            return false;\n        }\n    }	0
3253573	3253542	Type Casting Part of a string to int in where clause LinQ C#	var columns = from c in factory.GetColumnNames("eventNames") \n              where Regex.IsMatch(c, @"\d+")\n              select c;	0
18602855	18602793	Add XElement only if value exists	XDocument doc = new XDocument();\n\nvar order = new XElement("purchaseOrder",\n                new XElement("Name", order.Name),\n                new XElement("Address", order.Address));\n\nif(order.Shipper!=null) order.Add(new XElement("Shipper", order.Shipper));\n\ndoc.Add(order);	0
3346966	3346460	How to generate xsi:schemalocation attribute correctly when generating a dynamic sitemap.xml with LINQ to XML?	XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; \nXNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; \nreturn new XElement(ns + "urlset",  \n    new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),\n    new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),\n    new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),\n    from node in GetNodes() \n    select new XElement(ns + "url", \n        new XElement(ns + "loc", node.Loc), \n        new XElement(ns + "lastmod", node.LastMod), \n        new XElement(ns + "priority", node.Priority) \n    ) \n).ToString();	0
11840793	11840655	C# reference variables use clarification	A a = new A(); // new object A created, reference a assigned that address\nB b = new B(); // new object B created, reference b assigned that address\na = b; // we'll assume that is legal; the value of "b", i.e. the address of B\n       // from the previous step, is assigned to a\nc = null; // c is now a null reference\nb = c; // b is now a null reference	0
24663849	24662951	Add multiple images to canvas with C#	private int index = 1;\n\n    public void chooseImage_Completed(object sender, PhotoResult e)\n    {\n        if (e.TaskResult != TaskResult.OK || e.ChosenPhoto == null)\n        {\n            return;\n        }\n\n        Image img = new Image();\n        WriteableBitmap SelectedBitmap = new WriteableBitmap(60, 60);\n        img.Width = 100;\n        img.Height = 100;\n        img.Name = "img";\n        SelectedBitmap.SetSource(e.ChosenPhoto);\n\n        img.Source = SelectedBitmap;\n        img.Name = "Photo " + index++; // Set unique name here \n        e.ChosenPhoto.Position = 0;\n        CollageCanvas.Children.Add(img);\n        Canvas.SetTop(img, 50);\n        Canvas.SetLeft(img, 50);\n    }	0
24509271	24508842	fetching data from web site	string html = e.Result;\n       string theBody = "";\n       RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;\n       Regex regx = new Regex("<body>(?<theBody>.*)</body>", options);\n       Match match = regx.Match(html);\n       if (match.Success)\n       {\n           theBody = match.Groups["theBody"].Value;\n       }	0
18220633	18220226	I need to get some values ??from XML	XElement data = XElement.Load(@"C:\Test.xml");\n\nvar newsResults = data.Element("news")\n               .Descendants("news")\n               .Select(x => new\n               {\n                   Name = (string)x.Attribute("name"),\n                   Date = (DateTime)x.Attribute("date")\n               });\n\nforeach (var news in newsResults)\n{\n    Console.WriteLine("News: {0}, Date: {1}", news.Name, news.Date);\n}	0
8691022	8690953	Mouse emulation in a different program	[DllImport("USER32.DLL")]\n    public static extern IntPtr FindWindow(string lpClassName,\n        string lpWindowName);\n\n    // Activate an application window.\n    [DllImport("USER32.DLL")]\n    public static extern bool SetForegroundWindow(IntPtr hWnd);\n\n    [DllImport("user32.dll")]\n    private static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);	0
9772655	9772532	Format double/decimal value in MVC 3 Grid	grid.Column("TotalSum2", "Monto", format: (item) => item.TotalSum2.ToString("#,#"))	0
11938517	11938346	Can't add items to my ListView	// Set to details view.\nlistView1.View = View.Details;\n// Add a column with width 20 and left alignment.\nlistView1.Columns.Add("longitud", 20, HorizontalAlignment.Left);\nlistView1.Columns.Add("candidat", 20, HorizontalAlignment.Left);\n//... and so on	0
28062476	28059561	Json.NET Serializing Run throws StackOverflowException	try\n{\nvar _run = new Run()\n}\ncatch (Exception ex)\n{\n//serialize your erorr\n}\nfinally\n{\n//impossible but still\nif (_run != null)\n{\n//serialize _run\n}\n}	0
27540768	27540611	C# - How is ctrl+A input turned into a smiley?	string str = Console.ReadLine();            \n        Console.WriteLine((int)str[0]);  // Integer value of character.\n        // Console.OutputEncoding ( to get further detail)\n        Console.ReadLine();	0
3000261	3000229	how to populate an entity you have extended in the Entity Framework?	public string JobName { get { return this.JobType.Name; } }	0
15195192	15195115	How can I make all of my buttons in a form to make its text to uppercase/lowercase?	private void Form1_Load(object sender, EventArgs e)\n{\n    foreach(var ctrl in this.Controls)\n        if (ctrl.GetType() == typeof(Button))\n            ((Button)ctrl).Text = ((Button)ctrl).Text.ToUpper();\n}	0
26306385	26304429	How to get list of photos to a ListElement of a xaml page?	// Get the photoStorageFile as StorageFile not System.Object\nStorageFile photoStorageFile = await cameraCapture.CapturePhoto() as StorageFile;\n\n// Now we can properly set the source of the bitmapImage\nusing (IRandomAccessStream fileStream = await photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))\n{\n     // Set the image source to the selected bitmap\n     BitmapImage bitmapImage = new BitmapImage();\n\n     await bitmapImage.SetSourceAsync(fileStream);\n     bitmap.Source = bitmapImage;\n}	0
12921906	12756957	How do you retrieve the X.509 certificate that was used to construct a X509AsymmetricSecurityKey?	var data        = {Get data that was signed as an array of bytes}\nvar signature   = {Get signature as an array of bytes}\n\n// key variable is of type X509AsymmetricSecurityKey\n\nusing(var rsa = key.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false) as RSACryptoServiceProvider)\n{\n    if(rsa != null)\n    {\n        using(var halg = new SHA256CryptoServiceProvider())\n        {\n            if (!rsa.VerifyData(data, halg, signature))\n            {\n                throw new SecurityException("Signature is invalid.");\n            }\n        }\n    }\n}	0
5947404	5947212	Connecting to SQL Server in ASP.NET	SqlConnection conn = new SqlConnection("Data Source=serverName;"\n           + "Initial Catalog=databaseName;"\n           + "Persist Security Info=True;"\n           + "User ID=userName;Password=password");\n\nconn.Open();\n\n// create a SqlCommand object for this connection\nSqlCommand command = conn.CreateCommand();\ncommand.CommandText = "Select * from tableName";\ncommand.CommandType = CommandType.Text;\n\n// execute the command that returns a SqlDataReader\nSqlDataReader reader = command.ExecuteReader();\n\n// display the results\nwhile (reader.Read()) {\n    //whatever you want to do.\n}\n\n// close the connection\nreader.Close();\nconn.Close();	0
18780825	18766914	How do I export a Gridview Control to Excel in DotNetNuke?	private void DataTableToExcel(DataTable dataTable)\n{\n    StringWriter writer = new StringWriter();\n    HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);\n    GridView gridView = new GridView();\n    gridView.DataSource = dataTable;\n    gridView.AutoGenerateColumns = true;\n    gridView.DataBind();\n    gridView.RenderControl(htmlWriter);\n    htmlWriter.Close();\n\n    Response.Clear();\n    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");\n    Response.Charset = "";\n    Response.Write(writer.ToString());\n    Response.End();\n}	0
3600456	3600104	Send e-mail in same thread for gmail using smtp in c#	var smtpClient = new SmtpClient("smtp.gmail.com",587);\nsmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;\nsmtpClient.EnableSsl = true;\nsmtpClient.UseDefaultCredentials = false;\nsmtpClient.Credentials = new NetworkCredential("USERNAME@gmail.com"\n            ,"PASSWORD");\nusing (MailMessage message = new MailMessage("USERNAME@gmail.com","USERNAME@gmail.com"))\n{\n    message.Subject = "test";\n    smtpClient.Send(message);\n}\n\nusing (MailMessage message = new MailMessage("USERNAME@gmail.com","USERNAME@gmail.com"))\n{\n    message.Subject = "Re: test";\n    message.Headers.Add("In-Reply-To", "<MESSAGEID.From.Original.Message>");\n    message.Headers.Add("References",  "<MESSAGEID.From.Original.Message>");\n    smtpClient.Send(message);\n}	0
6664820	6664582	Regex accent insensitive?	string input =@"?????????????????????????????";\n     string pattern = @"\w+";\n     MatchCollection matches = Regex.Matches (input, pattern, RegexOptions.IgnoreCase);	0
9326408	9325573	How to populate settings with Unity?	var container = new UnityContainer();\ncontainer.AddNewExtension<EnrichmentExtension>();\ncontainer.RegisterType<SomeSettings>(new Enrichment<SomeSettings>((original, ctx) =>\n  {\n    ctx.NewBuildUp<ISettingsProvider>().PopulateSettings(original);\n  }));	0
4644280	4644211	Entity Framework Date Parsing	var begin = new DateTime(2011, 1, 1);\nvar end = begin.AddHours(24);\n\nApps = (from app in context.Instances\n             where \n               (app.ReleaseDate >= begin) and\n               (app.ReleaseDate < end)\n             select new ScalpApp\n             {\n             Image = app.Image,\n             PublisherName = app.PublisherName,\n             }).ToList();	0
1005902	1005149	Is there a way to derive from a class with an internal constructor?	public type MethodName(params)\n{\n   this.anInstanceOf3rdPartyClass.MethodName(params);\n}	0
20252081	20251982	Removing a varying substring from strings in C#	int aptStartIndex = line.ToLower().IndexOf(" apt ");\nint aptEndIndex = line.IndexOf(" ", aptStartIndex + 5);\nline = line.Substring(0, aptStartIndex) + line.Substring(aptEndIndex);	0
32476177	32475500	Searching a DataTable for a DataType	var dateColumns = dt.Columns.Cast<DataColumn>().Where(x => x.DataType == typeof(DateTime));\n    foreach (DataColumn column in dateColumns)\n    {\n        foreach (DataRow row in dt.Rows)\n        {\n            row[column.ColumnName] = DateTime.Parse("1/1/4");\n        }\n    }	0
28568772	28565945	How to use canvas content as a bitmap?	public static BitmapSource CreateBitmapSourceFromVisual(\n    Double width,\n    Double height,\n    Visual visualToRender,\n    Boolean undoTransformation)\n{\n    if (visualToRender == null)\n    {\n        return null;\n    }\n    RenderTargetBitmap bmp = new RenderTargetBitmap((Int32)Math.Ceiling(width),                                                        (Int32)Math.Ceiling(height), 96,96, PixelFormats.Pbgra32);\n\n    if (undoTransformation)\n    {\n        DrawingVisual dv = new DrawingVisual();\n        using (DrawingContext dc = dv.RenderOpen())\n        {\n            VisualBrush vb = new VisualBrush(visualToRender);\n            dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));\n        }\n        bmp.Render(dv);\n    }\n    else\n    {\n        bmp.Render(visualToRender);\n    }\n  return bmp;\n}	0
12636302	12636198	Array with two classes	IDictionary<int, string> h = new Dictionary<int, string>();\n            h.Add(1, "a");\n            h.Add(2, "b");\n            h.Add(3, "c");\n\nSortedList<int, string> s = new SortedList<int, string>();\n            s.Add(1, "a");\n            s.Add(2, "b");	0
6422130	6422091	Convert IDictionary to Dictionary	var newDict = new Dictionary<string, decimal>(oldDictionary)	0
31486460	31485372	How to handle strings that are accessible application wide?	public static class Claims\n{\n  public static readonly String View = "http://schemas.mycompany.com/claims/view";\n  public static readonly String Edit = "http://schemas.mycompany.com/claims/edit";\n  public static readonly String Upvote = "http://schemas.mycompany.com/claims/upvote";\n}	0
20461352	20290025	Enum parameter sent from C# WS client is received as null by Java WS	public OperationResponse serviceOperation(@WebParam(name = "queryType") String queryType)	0
25031839	25031772	How to count the number of columns with specific data in MS SQL	SELECT\n    EmployeeID,\n    PID,\n    (\n        CASE WHEN [1] = 'D' OR [1] = 'N' THEN 1 ELSE IF [1] = 'D/N' THEN 2 ELSE 0 END\n      + CASE WHEN [2] = ...\n      + ...\n      + CASE WHEN [31] = 'D' OR [31] = 'N' .....\n    ) AS shift_totals,\n    (\n        CASE WHEN [1] IS NOT NULL THEN 1 ELSE 0 END\n      + CASE WHEN [2] IS ...\n      + ...\n    ) AS day_totals	0
33395507	33395348	c# Regex replace with insert	(?<!\|)&(?!\|)	0
15399373	15399323	Validating whether a textbox contains only numbers	int parsedValue;\nif (!int.TryParse(textBox.Text, out parsedValue))\n{\n    MessageBox.Show("This is a number only field");\n    return;\n}\n\n// Save parsedValue into the database	0
6575355	6575300	C# How to remove text between BBCode	\[quote([^\[]*)\](.*?)\[\/quote\]	0
13308740	13308678	Regex pattern to match file version	string pattern =@"\d+\.\d+\.\d+\.[0-9F]+";	0
389350	389298	Update more than one database using same ObjectDataSource using C#	public void DeleteMyObject(int objectId)\n{\n    SqlConnection connectionOne = new SqlConnection("MyFirstDbConnection");\n    SqlConnection connedtionTwo = new SqlConnection("MySecondDbCOnnection");\n    SqlCommand myCommand = new SqlCommand(connectionOne);\n    myCommand.CommandText = "DELETE FROM myTable where myid = " + objectId.ToString();\n    connectionOne.Open();\n    myCommand.ExecuteNonQuery();\n    connectionOne.Close();\n    myCommand.Connection = connectionTwo;\n    connectionTwo.Open();\n    myCommand.ExecuteNonQuery();\n    connectionTwo.Close();\n}	0
4981411	4981390	Convert a list to a string in C#	string combindedString = string.Join( ",", myList.ToArray() );	0
31548198	31546874	Differentiating between processes with the same name outside of my application?	var wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId='{0}'", processId);\nvar searcher = new ManagementObjectSearcher(wmiQuery);\nvar retObjectCollection = searcher.Get();\nforeach (ManagementObject retObject in retObjectCollection)\n    Console.WriteLine("[{0}]", retObject["CommandLine"]);	0
1984106	1984090	New row inserted for each page refresh	Response.Redirect(url);	0
26050503	26049911	DataTable - Dynamic Linq OrderBy using Lambda expressions	var columns = new string[] { "Category", "Country" };\n\nvar rows = dt.AsEnumerable().OrderBy(x => 0);\nforeach(var columnName in columns)\n{\n    rows = rows.ThenBy(r => string.IsNullOrEmpty(Convert.ToString(r[category])))\n               .ThenBy(r => Convert.ToString(r[category]));\n}	0
1349582	1349543	Redirecting stdout of one process object to stdin of another	Process out = new Process("program1.exe", "-some -options");\nProcess in = new Process("program2.exe", "-some -options");\n\nout.UseShellExecute = false;\n\nout.RedirectStandardOutput = true;\nin.RedirectStandardInput = true;\n\nusing(StreamReader sr = new StreamReader(out.StandardOutput))\nusing(StreamWriter sw = new StreamWriter(in.StandardInput))\n{\n  string line;\n  while((line = sr.ReadLine()) != null)\n  {\n    sw.WriteLine(line);\n  }\n}	0
13630826	13630776	Redirect to page on button click	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack) Session["prev"] = Request.UrlReferrer.ToString();\n    if(Session["prev"] == null) {some code that disables the back button goes here!}\n}\nprotected void BackButton_Click( object sender , EventArgs e )\n{      \n   Response.Redirect(Session["prev"] as string);\n}	0
1166691	1166229	How can I post something to a Wall using Facebook Developer Toolkit?	FacebookService.API.stream.publish(...);	0
737437	737409	Are get and set functions popular with C++ programmers?	class Foo\n{\npublic:\n    std::string bar() const { return _bar; } \n    void bar(const std::string& bar) { _bar = bar; } \nprivate:\n    std::string _bar;\n};	0
32643551	32643268	I'm learning C# - how can this simple program improve?	var choices = new Dictionary<string, string>()\n{\n    { "1", "Steel" },\n    { "2", "Iron" },\n    { "3", "Aluminium" },\n};\n\nwhile (true)\n{\n    Console.Write("Please enter a metal type: ");\n    string textStr = Console.ReadLine();\n\n    if (choices.ContainsKey(textStr))\n    {\n        Console.WriteLine("You have selected {0}.", choices[textStr]);\n        break;\n    }\n    else\n    {\n        Console.WriteLine("Wrong selection!");\n    }   \n}	0
31366020	31365983	Set DataGridViewCheckBoxCell on all TabPage tabs	void myDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n    int clickedRow = e.RowIndex;\n    int clickedColumn = e.ColumnIndex;\n    if (clickedColumn != 0) return;\n    DataGridView myDataGridView = (DataGridView)sender;\n\n    if (!ToggleAllRowSelection)\n    {\n        foreach (TabPage myTabPage in tabControl1.TabPages)\n        {\n            DataGridView grd = myTabPage.Controls.OfType<DataGridView>().FirstOrDefault();\n            if(grd != null)\n            {\n                grd.Rows[clickedRow].Cells[0].Value  = false;\n            }\n        }\n    }\n}	0
23360223	23264028	Add lines between two inline images in word	object StartPos = 0;\n        object Endpos = 1;\n        Microsoft.Office.Interop.Word.Range rng = doc.Range(ref StartPos, ref Endpos);\n        object NewEndPos = rng.StoryLength - 1;\n        rng = doc.Range(ref NewEndPos, ref NewEndPos);\n        rng.Select();\n\n        var pText = doc.Paragraphs.Add();\n        pText.Format.SpaceAfter = 10f;\n        pText.Range.Text = String.Format("This is line");\n        pText.Range.InsertParagraphAfter();\n\n        object StartPos1 = 0;\n        object Endpos1 = 1;\n        Microsoft.Office.Interop.Word.Range rng1 = doc.Range(ref StartPos1, ref Endpos1);\n        object NewEndPos1 = rng.StoryLength - 1;\n        rng1 = doc.Range(ref NewEndPos, ref NewEndPos);\n        rng1.Select();\n        doc.InlineShapes.AddPicture(loc +@"\" + dt + ".jpeg");	0
5607661	5606982	How to delete a TcpChannel object in .NET	private void button1_Click(object sender, EventArgs e)\n    {\n        channel = new TcpChannel(port);\n\n        Trace.WriteLine("Start Connection received at Server");\n        ChannelServices.RegisterChannel(channel, false);\n\n\n        //Initiate remote service as Marshal\n        RemotingServices.Marshal(this, "Server", typeof(Server));\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        Trace.WriteLine("Stop Connection at Server");\n\n        channel.StopListening(null);\n        RemotingServices.Disconnect(this);\n        ChannelServices.UnregisterChannel(channel);\n        channel = null;\n    }	0
27321669	27321471	Split string and validate each part	var re = new Regex("\d{4}\|\d{4}\|\d\d\|\w\w\|\d\|\d{8}\|\d\d");\nvar valid = re.IsMatch(input);	0
8049444	8008821	How to know the state of an sql instance in a c# program	using Microsoft.SqlServer.Management.Smo.Wmi;\n\nManagedComputer mc = new ManagedComputer("localhost");\nforeach (Service svc in mc.Services) {\n    if (svc.Name == "MSSQL$SQLEXPRESS"){\n        textSTW.Text = svc.ServiceState.ToString();\n    }\n    if (svc.Name == "MSSQL$TESTSERVER"){\n        textST1.Text = svc.ServiceState.ToString();\n    }\n    if (svc.Name == "MSSQL$TESTSERVER3") {\n        textST2.Text = svc.ServiceState.ToString();\n    }\n}	0
17034905	17034881	regex to find ip address after key words	"D\sH\sP.*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])"	0
5537630	5537604	Add specific Button with Control constructor?	Controls.Add(\n    new Button    \n    {\n       Text = "Press me",\n       Left = 400,\n       // initialize any properties you wish\n    });	0
10299785	10292135	How can i extract a string text from a file using loop while all over the file?	string word = "\"Was? Wo war ich? Ach ja<pa>\"Jain\"Romil<pa>\"";\nstring[] stringSeparators = new string[] { "<pa>\"" };\nstring ans=String.Empty;\nstring[] text = word.Split(stringSeparators, StringSplitOptions.None);\n\nforeach (string s in text)\n{\n    if (s.IndexOf("\"") >= 0)\n    {\n        ans += s.Substring(s.IndexOf("\"")+1);\n    }\n}\nreturn ans;	0
32111513	32111393	Eliminate comma(,) from a column of a Data Table using LINQ	first.SetField("SameReferences", string.Format("{0},{1}", duplicate, \n                first.Field<string>("SameReferences")).Trim(','));	0
10347798	10347603	Get ASP.NET development server port number	Request.Url.Port	0
1225308	1225294	Find a file within all possible folders?	var files = new List<string>();\n     //@Stan R. suggested an improvement to handle floppy drives...\n     //foreach (DriveInfo d in DriveInfo.GetDrives())\n     foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))\n     {\n        files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "Cheese.exe", SearchOption.AllDirectories));\n     }	0
4553855	4553706	Convert string of numbers to array of numbers c#?	var nums = s.Split(' ').Select(n=>Int32.Parse(n)).ToList();\nvar grid = nums.Split(nums.Count / 3);	0
22835315	22827203	Linq to EF: find the nearest Nullable Datetime from now	static void Main(string[] args)\n    {\n        DateTime? d0 = null;\n        DateTime? d1 = new DateTime(2013, 1, 1);\n        DateTime? d2 = new DateTime(2014, 1, 1);\n        DateTime? d3 = new DateTime(2015, 1, 1);\n        DateTime? d4 = null;\n\n        List<DateTime?> dts = new List<DateTime?>() { d0, d1, d2, d3, d4 };\n        //I finally replaced x with x.Value, and compile error disappeared\n        var v = dts.Where(x => x.HasValue).OrderBy(x =>\n            (Math.Abs((DateTime.Now - x.Value).TotalMilliseconds)));\n\n        foreach (var x in v)\n            Console.WriteLine(x);\n\n        Console.ReadLine();\n    }	0
12912076	12909799	Grouping of Xml Elements using Linq	var query =\n    from xe in doc.Element("taxdata").Elements("table")\n    from gr in xe.Elements("row").GroupBy(_ => _.Attribute("locid").Value)\n    select new\n    {\n        id = xe.Attribute("id").Value,\n        locid = gr.Key,\n        rows = gr.Count(),\n    };	0
17016170	17015392	trying to parse negative monetary amount from string into decimal	sAmount = decimal.Parse(line[1].Replace("\"", ""));	0
18490701	18490637	Take 4 places after decimal for a double variable	double result = Math.Truncate(10000 * something) / 10000;	0
21038246	21038141	How to get "drop down button" size of ComboBox in C# winforms	using System.Windows.Forms;\n\n  ...\n\n  int arrowWidth = SystemInformation.VerticalScrollBarWidth;	0
29701173	29701113	How can I cast SQL DateTime Null to c# 'DateTime?' (Nullable<DateTime>)?	CompletionDate = !dr.IsNull("CompletionDate") ? (DateTime)dr["CompletionDate"] : new DateTime?();	0
9103055	9068321	How should I unit test my WebFormMVP Presenters with Moq'd Views when using the Supervising Controller Pattern	Assert.That(mock.Object.Model.Message, Is.EqualTo(expected));	0
12371208	12371131	How to redirect from an action to another action but provide its parameters in MVC 3?	return RedirectToAction("Index", "Controller", new {v1 = "Hello", i1 = 123});	0
6638960	6638863	How to select with linq to entity Categories and SubCategories?	var q = from item in context.Items\n        select new {\n            ItemID = item.ItemID,\n            CategoryName = item.Category.Name,\n            SubCategoryName = item.SubCategory.Name,\n            ItemName = item.ItemName\n        };	0
28739662	28738819	Loading controls inside a tab page in a tab control in C#?	Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load\n\n  Dim frmUser As New UserForm\n  frmUser.TopLevel = False\n  frmUser.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle\n\n  Me.TabControl1.TabPages(0).Controls.Add(frmUser)\n  frmUser.Show()\n\nEnd Sub	0
17667121	17666970	Convert UTC time to local time using Nodatime	// Since your input value is in UTC, parse it directly as an Instant.\nvar pattern = InstantPattern.CreateWithInvariantCulture("ddMMyyHHmmss");\nvar parseResult = pattern.Parse("150713192900");\nif (!parseResult.Success)\n    throw new InvalidDataException("...whatever...");\nvar instant = parseResult.Value;\n\nDebug.WriteLine(instant);  // 2013-07-15T19:29:00Z\n\n// You will always be better off with the tzdb, but either of these will work.\nvar timeZone = DateTimeZoneProviders.Tzdb["Pacific/Auckland"];\n//var timeZone = DateTimeZoneProviders.Bcl["New Zealand Standard Time"];\n\n// Convert the instant to the zone's local time\nvar zonedDateTime = instant.InZone(timeZone);\n\nDebug.WriteLine(zonedDateTime);\n  // Local: 7/16/2013 7:29:00 AM Offset: +12 Zone: Pacific/Auckland\n\n// and if you must have a DateTime, get it like this\nvar bclDateTime = zonedDateTime.ToDateTimeUnspecified();\n\nDebug.WriteLine(bclDateTime.ToString("o"));  // 2013-07-16T07:29:00.0000000	0
14182640	14182180	Working with a timer to show the label for some time	private void Form1_Load(object sender, EventArgs e)\n    {\n        timer1.Interval = 10000;\n        timer1.Tick += new System.EventHandler(this.timer1_Tick);\n        label1.Visible = true;\n        timer1.Start();\n    }\n\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        timer1.Stop(); //If timer is not stopped, timer1_Tick event will be called for every 10 seconds\n        label1.Visible = false;\n    }	0
34428679	34428409	Sum Row From Gridview	foreach (GridViewRow row in analysispack1.Rows)\n{\n    showit += Convert.ToDecimal(row.Cells[2].Text.Replace("%", string.Empty));\n}	0
4744924	4744480	add a column between two columns of a gridview	var column = new DataGridViewTextBoxColumn();\n// initialize column properties\n...\nmyGridView.Columns.Insert(2, column);	0
17352027	17342710	Using the Rally REST API, how to query and return a *complete* JSON object?	_rallyAPIMajor\n_rallyAPIMinor\n_ref\n_objectVersion\n_refObjectName	0
16576777	16576713	How to get or parse parameter from onitemdatabound method	protected void DormatItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    var obj = sender as Sitecore.Collection.Childlist;\n    if (obj != null)\n    {\n        // To do here\n    }\n}	0
16431362	16431287	Calculate date difference in months	DateTime x1 = DateTime.ParseExact("20119", "yyyyM", CultureInfo.InvariantCulture);\nDateTime x2 = DateTime.ParseExact("20135", "yyyyM", CultureInfo.InvariantCulture);\n\nint months =  Math.Abs((x2.Month - x1.Month) + 12 * (x2.Year - x1.Year));	0
20765234	20764871	Timing of Task Result Evaluation	var stopwatch = Stopwatch.StartNew();\n    var results = Test();\n\n\n    Console.WriteLine("Time after running Test {0}", stopwatch.ElapsedMilliseconds);\n\n    foreach (var result in results)\n    {\n        Console.WriteLine("Looping {0}", stopwatch.ElapsedMilliseconds);\n    }	0
12926310	12926289	Two decimal format for ListView column	DisplayMemberBinding="{Binding Path=TotalPrice, StringFormat=Now {0:c}!}"	0
25016696	25016419	Why when searching for an item in Tree View there is never a match?	private void FindByText()\n{\n    TreeNodeCollection nodes = treeView1.Nodes;\n    foreach (TreeNode n in nodes)\n    {\n        if (n.Text == this.textBox2.Text)\n            n.BackColor = Color.Yellow;\n        FindRecursive(n);\n    }\n}	0
26797707	26797471	How to get string from formatted url in asp.net c#	string lastPartUrl =HttpContext.Current.Request.Url.AbsoluteUri.Split('/').Last();	0
3767636	3759309	Max length for bound field in gridview in ASP.Net	if (e.Row.RowType == DataControlRowType.DataRow) \n    {\n        for (int i = 1; i < dgv.Columns.Count - 1; i++)\n        {\n            if ((e.Row.Cells[i].Controls.Count > 0) && (e.Row.Cells[i].Controls[0].GetType().ToString() == (new TextBox()).ToString()))\n            {\n                ((TextBox)e.Row.Cells[i].Controls[0]).Width = 40;\n                ((TextBox)e.Row.Cells[i].Controls[0]).MaxLength = 5;\n            }\n        }\n    }            \n    //To make the text box accept numbers, delete, backspace, numlock,dot only\n    e.Row.Attributes.Add("onkeypress", "javascript: var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;  return ((Key >= 48 && Key <= 57) || (Key == 110) || (Key == 190) || (Key == 8) || (Key == 46) || (Key == 144))");	0
1689662	1689652	how do i dispose of a class that is a property of another class?	class Service : IDisposable\n{\n    public DataContext DC= new DataContext();\n\n    public void Dispose( )\n    {\n        DC.Dispose( );\n    }\n}	0
25788583	25787769	Delete selected datatable row from database	private static void Row_Changed(object sender, DataRowChangeEventArgs e)\n{\n    try\n    {\n        MySqlCommandBuilder cmdb = new MySqlCommandBuilder(sda);\n        sda.Update(dbDataset);                \n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show(ex.Message);\n    }\n}\n\nprivate void Row_Deleted(object sender, DataRowChangeEventArgs e)\n{\n    try\n    {\n        SqlCommandBuilder cmdb = new SqlCommandBuilder(da);\n        da.Update(dt);                \n    }\n    catch (Exception ex)\n    {\n        Console.WriteLine(ex.Message);\n    }\n}	0
10634488	10634395	set name on method arguments	MethodBuilder.DefineParameter	0
6590210	6540682	All GridView rows disappear while selecting a row	// if (!Page.IsPostBack)	0
11598215	11598134	C# Regular Expression to skip some special characters	private bool IsValid(string str)\n {\n    Regex r = new Regex(@"^[a-z]+$");\n    Console.WriteLine(str + " : " + r.IsMatch(str).ToString()); \n    return r.IsMatch(str);\n }	0
3963839	3961831	Help Translating a small C# WCF app into Visual Basic (part 2)	Public Sub AddMessage(ByVal message As String) Implements IMessage.AddMessage\n        Dim msgCallback As IMessageCallback\n\n        Dim removedSubscribers As New List(Of IMessageCallback)()\n\n        For Each msgCallback In subscribers\n            If (CType(msgCallback, ICommunicationObject).State = CommunicationState.Opened) Then\n                msgCallback.OnMessageAdded(message, DateTime.Now)\n            Else\n                removedSubscribers.Add(msgCallback)\n            End If\n        Next\n\n        For Each msgCallback In removedSubscribers\n            subscribers.Remove(msgCallback)\n        Next\n    End Sub	0
2577899	2577873	How to simulate array of events in C#? (like in VB6)	for (int i = 0; i < observed.Length; ++i)\n{\n    int idx = i;\n    observed[idx].WhateverEvent += delegate(object sender, EventArgs e)\n                                   {\n                                       MyHandler(sender, e, idx);\n                                   };\n}	0
464411	464196	Workaround to see if Excel is in cell-edit mode in .NET	Private Function isEditMode() As Boolean\n    isEditMode = False\n    Try\n        oExcel.GoTo("###")\n    Catch Ex As Exception\n       ' Either returns "Reference is not valid." \n       ' or "Exception from HRESULT: 0x800A03EC"\n       If ex.Message.StartsWith("Exception") then isEditMode  = True\n    End Try \nEnd Function	0
27683876	27683766	How to download excel file after exporting data from Dataset to Excel?	private void GenerateFile(string strPath)\n{\n     var file = new FileInfo(@strPath);\n\n     Response.Clear();\n     Response.ContentType = "application/vnd.ms-excel";\n     Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");\n     Response.AddHeader("Content-Length", file.Length.ToString());\n     Response.TransmitFile(file.FullName);\n     HttpContext.Current.ApplicationInstance.CompleteRequest();\n}	0
882224	881967	anchor IE 6 bug	Response.Redirect(Request.Url.PathAndQuery + "&New=1&#create");	0
20341678	20341644	Is there a way to create folders with security in c#?	using System.IO; \n\nstring path = @"c:\newHiddenFolder";\nif (!Directory.Exists(path)) \n{ \n  DirectoryInfo di = Directory.CreateDirectory(path); \n  di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; \n}	0
24880517	24880480	Count startswith with linq	if (!source.StartsWith(target)) return 0;\nreturn target.Length;	0
14750470	14750434	Is it possible to have one comment for property and private variable	/// <summary>a description here</summary>\npublic A Owner {get;set;}	0
29615230	29612155	How to get current path on azure webjob/console app	%WEBROOT_PATH%\App_Data\jobs\%WEBJOBS_TYPE%\%WEBJOBS_NAME%	0
30645391	30644180	Get modelstate key for viewmodel property	System.Web.Mvc.ExpressionHelper.GetExpressionText(LambdaExpression expression);	0
28106043	28105798	how to Join two column in datarow array in Select statement?	myTable.Select(string.Format("Name = '{0}' AND Family='{1}",name,surname));	0
20387501	20387339	Search with for values with a loop	private void button4_Click(object sender, EventArgs e)\n {\n     uint offset = 0x0154d6e4;\n     uint value= 844705;\n     uint randBuff = Loaded_DLL.Extension.ReadUInt32(offset);\n\n     while (randBuff != value)\n     {\n         offset = (offset + 4);\n         randBuff = Loaded_DLL.Extension.ReadUInt32(offset);\n\n     }\n     if(randBuff == value)\n         listBox1.Items.Add(randBuff.ToString("x8"));\n     else\n        listBox1.Items.Add("Value not found!");\n }	0
6319592	6319560	string value validation in C#	if (ResultVal is byte[]) {\n           // SourVal is Invalid;\n        } else if ( ResultVal is String ) { \n            //SourVal is valid;\n        }	0
1492011	1491968	How to read data for nested classes?	using System;\nusing System.Collections.Generic;\n\nclass Program {\n\n    class Outer {\n\n        static Dictionary<int, Outer> _ids = new Dictionary<int, Outer>();\n\n        public Outer(int id) {\n            _ids[id] = this;\n        }\n\n        public class Inner {\n            public Outer Parent {\n                get;\n                set;\n            }\n\n            public Inner(int parentId) {\n                Parent = Outer._ids[parentId];\n            }\n\n        }\n    }\n\n    static void Main(string[] args) {\n        Outer o = new Outer(1);\n        Outer.Inner i = new Outer.Inner(1);\n    }\n}	0
4854307	4854255	Getting WPF Dispatcher from library	Application.Current.Dispatcher	0
2223779	2223741	How do I pass more than one value to a custom RoleProvider GetUserRoles method in my MVC app?	RoleProvider rp = Roles.Provider;\n    (rp as MyRoleProvider).GetPermissions(privateKey,userName);	0
33745910	33536050	Subtable in ReportViewer	LocalReport.SubreportProcessing += Customers_SubreportProcessing;\n\nprivate void Customers_SubreportProcessing(object sender, SubreportProcessingEventArgs e)\n{\n    ReportParameterInfo customerId = e.Parameters.FirstOrDefault(c => c.Name == "CustomerId");\n    if (customerId== null)\n        return;\n\n    Customer customer = _customersList\n        .FirstOrDefault(c => c.CustomerId == customerId.Values.FirstOrDefault());\n\n    if (e.ReportPath == "CustomersOrders") // Name for subreport CustomersOrders.rdlc\n    {\n        e.DataSources.Add(new ReportDataSource("Orders", customer.Orders));\n    }\n    else if (e.ReportPath == "CustomersComments") // Name for subreport CustomersComments.rdlc\n    {\n        e.DataSources.Add(new ReportDataSource("Comments", customer.Comments));\n    }\n}	0
1987100	1987060	How do I get access to an image of the desktop buffer in .NET?	Graphics.CopyFromScreen	0
8757844	8757782	adding a text line and a link button to a GridViewRow	// Filename\n        string filename = "...";\n        Label lbl_filename = new Label();\n        lbl_filename.Text = filename;\n        // ...\n\n        // Button\n        LinkButton button = new LinkButton();\n        button.Text = "Download";\n        // ...\n\n        GridViewRow row = new GridViewRow(i, i, DataControlRowType.DataRow, DataControlRowState.Normal);\n        TableCell cell = new TableCell();\n        cell.ColumnSpan = some_columnspan;\n        cell.HorizontalAlign = HorizontalAlign.Left;\n        cell.Controls.Add(lbl_filename); // add control\n        cell.Controls.Add(button); // add control\n        row.Cells.Add(cell);	0
26919321	26919206	For looping and string	string word = "To je";\nword = word.Substring(0,word.Length - 3);\nword += "...";\n\nConsole.WriteLine(word);	0
7128394	7033379	c# VSTO Outlook link image without it being embedded	In key HKCU\Software\Microsoft\Office\14.0\Outlook\Options\Mail\\nAdd a REG_DWORD named "Send Pictures With Document"\nSet the value to 0	0
10038690	10038664	Sorting a List by two variables	(c1.LastName ?? c1.EntityName).CompareTo(c2.LastName ?? c2.EntityName)	0
2898035	2896169	Extract enumeration data from .XSD file	XmlSchema schema = XmlSchema.Read(XmlReader.Create("v1.xsd"), \n    new ValidationEventHandler(ValidationCallbackOne));\nXmlSchemaSet schemaSet = new XmlSchemaSet();\nschemaSet.Add(schema);\nschemaSet.Compile();\n\nIEnumerable<string> enumeratedValues = schema.Items.OfType<XmlSchemaSimpleType>()\n    .Where(s => (s.Content is XmlSchemaSimpleTypeRestriction) \n        && s.Name == "Type")\n    .SelectMany<XmlSchemaSimpleType, string>\n        (c =>((XmlSchemaSimpleTypeRestriction)c.Content)\n            .Facets.OfType<XmlSchemaEnumerationFacet>().Select(d=>d.Value));\n\n// will output Op1, Op2, Op3...\nforeach (string s in enumeratedValues)\n{\n    Console.WriteLine(s);\n}	0
3845660	3845642	Returning a generic List from a function	List<T> GetEvens<T>( ... )	0
19135079	19134585	Linq to Entities with a referenced property	public class MasterDataViewModel<T> :  where T : IDBEntity, new()\n{\n    public T CurrentItem { get; set; }\n\n    public void ReloadItem(int id)\n    {\n        using (var context = new DatabaseContext())\n        {\n            CurrentItem = context.Set<T>().Find(id);\n        }\n    }\n}	0
9544970	9544493	Advice: Persisting User Input for dynamically created user controls	var contacts = new List<EF4Entity>()\nif (Session["Contacts"] != null){\n  contacts = Session["Contacts"] as List<EF4Entity>\n}\n\nvar newContact = new EF4Entity()\n//fill your new contact here\ncontacts.Add(newContact)\n\n//bind your RadPanelItems here\n\n//store it to the session\nSession["Contacts"] = contacts	0
6524471	6524407	how to find the longest string in a string[] using LINQ	var strings = new string[] { "1", "02", "003", "0004", "00005" };\n\nstring longest = strings.OrderByDescending( s => s.Length ).First();	0
9802863	9802095	How to stop annoying window security popup?	Internet Options-> Advanced->Security->Enable Integrated Windows Authentication	0
18569108	18568661	ASP.NET MVC Controller extension method to make Log available to all controllers	public abstract class BaseController : Controller\n{\n    public ILog Log\n    {\n        get { return LogManager.GetLogger(GetType()); }\n    }\n}	0
16531042	16521591	How to Parse Datetime sec.ms	// you said you were starting with a string\nstring s = "1368352924.281610000";\n\n// but you are going to need it as a double.\n// (If it's already a double, skip these two steps)\nvar d = double.Parse(s);\n\n// starting at the unix epoch\nDateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n\n// simply add the number of seconds that you have\nDateTime dt = epoch.AddSeconds(d);\n\n\nDebug.WriteLine("{0} {1}", dt, dt.Kind);  // prints  05/12/2013 10:02:04 Utc	0
5899654	5899577	Test my MVC2 Controller	ActionResult action = _myControllerToTest.Notes(null, null);\nAssert.IsNotNull(action);\n\nViewResult viewResult = action as ViewResult;\nAssert.IsNotNull(viewResult);\n\n// Check viewResult for correct view path and model data	0
29250752	29250627	How to find last alphabet in a string using c# .net	string chars = "1234B0097D576676";\nchar Result = chars.LastOrDefault(x => Char.IsLetter(x));	0
1048204	1048199	Easiest way to read from a URL into a string in .NET	using(WebClient client = new WebClient()) {\n   string s = client.DownloadString(url);\n}	0
9905527	9905456	Asp.net charts- How to remove the background grid?	Chart1.ChartAreas["YourChartArea"].AxisX.MajorGrid.Enabled = false;\nChart1.ChartAreas["YourChartArea"].AxisY.MajorGrid.Enabled = false;	0
10665046	10664937	How can I add and remove records from a collection with LINQ	Details = Details.Where(cityDetail=>cityDetail.Text != null && !string.IsNullOrEmpty(cityDetail.Text.TextWithHtml)).ToList();	0
5500793	5500696	Creating web controls inside a content placeholder programmattically	this.Master.Controls.FindControl("ContentPlaceHolderID").Controls.Add(yourControl);	0
10278769	748062	How can I return multiple values from a function in C#?	public Tuple<int, int> GetMultipleValue()\n{\n     return Tuple.Create(1,2);\n}	0
1733993	1733912	How do I handle dragging of a label in C#?	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n      label1.MouseDown += new MouseEventHandler(label1_MouseDown);\n      textBox1.AllowDrop = true;\n      textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);\n      textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);\n    }\n\n    void label1_MouseDown(object sender, MouseEventArgs e) {\n      DoDragDrop(label1.Text, DragDropEffects.Copy);\n    }\n    void textBox1_DragEnter(object sender, DragEventArgs e) {\n      if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy;\n    }\n    void textBox1_DragDrop(object sender, DragEventArgs e) {\n      textBox1.Text = (string)e.Data.GetData(DataFormats.Text);\n    }\n  }	0
31054371	31054067	Using variables inside a switch statement throws and compiler error	DateTime startDate = DateTime.Now, endDate = DateTime.Now;	0
11324848	11324711	Redirect from asp.net web api post action	public HttpResponseMessage Post()\n{\n    // ... do the job\n\n    // now redirect\n    var response = Request.CreateResponse(HttpStatusCode.Moved);\n    response.Headers.Location = new Uri("http://www.abcmvc.com");\n    return response;\n}	0
30484928	28191074	Returning a simple Guid with RestSharp	{ "id": "4bae9421-4fe0-4294-a659-9bc37388344b" }	0
13266928	13266841	C# LINQ to XML: number of elements, that have two same attributes?	var book = doc.Descendants("Book") // Note Book, not Books\n              .Where(x => x.Element("Author").Value == newBook.Author &&\n                          x.Element("Title").Value == newBook.Title)\n              .FirstOrDefault();\n\nif (book != null)\n{\n    int copies = (int) book.Element("NumberOfCopies");\n}	0
2550967	2550957	Appending data to Datatable	dtExcel.ImportRow()	0
22588277	22587543	Get-Set returning null when accessed by a button	public class FolderUpdate\n{\n    .... \n}\n\n\npublic FolderUpdate Folders { get; set; }\n\nprivate void btnTemBrow_Click(object sender, EventArgs e)\n{\n     ...\n     Folders.SwTemplate = tempText;\n}\n\nprivate void btnDirBrow_Click(object sender, EventArgs e)\n{\n     ...\n     Folders.SwDir = dirText;\n}\n\n\n// Then when you are reading them\nvar folders = swSheetFormatCycle.Form1.Folders;\nstring swDir = folders.SwDir;\nstring swTemplate = folders.SwTemplate;	0
16681305	16637257	ReadText from file in ANSII encoding	String parsedStream;\n        var parsedPage = await WebDataCache.GetAsync(new Uri(String.Format("http://bash.im")));\n\n        var buffer = await FileIO.ReadBufferAsync(parsedPage);\n        using (var dr = DataReader.FromBuffer(buffer))\n        {\n            var bytes1251 = new Byte[buffer.Length];\n            dr.ReadBytes(bytes1251);\n\n            parsedStream = Encoding.GetEncoding("Windows-1251").GetString(bytes1251, 0, bytes1251.Length);\n        }	0
6709643	6709525	Rendering Dynamic asp.net webpage into string invoked from another page	string generated = new WebClient().DownloadString("generatetemplate.aspx?myparams=params");	0
8353001	8325679	How do I copy a HttpRequest to another web service?	string buffString = System.Text.UTF8Encoding.UTF8.GetString(buff);\n\nusing (Stream stm = req.GetRequestStream())\n{\n    bool stmIsReadable = stm.CanRead;  //false, stream is not readable, how to get\n                                       //around this?\n                                       //solution: read Byte Array into a String,\n                                       //modify <wsa:to>, write String back into a\n                                       //Buffer, write Buffer to Stream\n\n    buffString = buffString.Replace("http://localhost/WS/Service.asmx", WSaddress);\n\n    //write modded string to buff\n    buff = System.Text.UTF8Encoding.UTF8.GetBytes(buffString);\n\n    stm.Write(buff, 0, (int)buff.Length);\n}	0
28855413	28855219	C# Opening a program from a local directory	const string relativePath = "bin/rkill.exe";\n\n//Check for idle, removable drives\nvar drives = DriveInfo.GetDrives()\n                      .Where(drive => drive.IsReady\n                             && drive.DriveType == DriveType.Removable);\n\nforeach (var drive in drives)\n{\n    //Get the full filename for the application\n    var rootDir = drive.RootDirectory.FullName;\n    var fileName = Path.Combine(rootDir, relativePath);\n\n    //If it does not exist, skip this drive\n    if (!File.Exists(fileName)) continue;\n\n    //Execute the application and wait for it to exit\n    var process = new Process\n    {\n        StartInfo = new ProcessStartInfo\n        {\n            FileName = fileName\n        }\n    };\n\n    process.Start();\n    process.WaitForExit();\n}	0
25959267	25934397	How to stop browser navigating in csharp for windowsphone	private void webBrowser_Navigating(object sender, NavigatingEventArgs e)\n    {\n        stop.IsEnabled=true;\n        stop.Click += new RoutedEventHandler((object caller, System.Windows.RoutedEventArgs f) =>\n        {\n            stopPressed = true;\n        });\n\n        if (stopPressed == true)\n            e.Cancel = true;\n    }	0
23955596	23955184	Using DataGridView events to save data back on the database	void dataGridView_DataSourceChanged(object sender, EventArgs e)\n    {\n        MessageBox.Show("datasourcechanged");\n    }	0
21639493	21639441	Can I write a file to a folder on a server machine from a Web API app running on it?	string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Platypus{0}.csv", dbContextAsInt));	0
26685483	26685223	How can I use SQLite query parameters in a WinRT app?	db.Execute("UPDATE PhotraxBaseData SET photosetName = ? WHERE photosetName = ?", newName, oldName);	0
21371089	21371034	How do I apply an attribute to a single type in an inheritance tree?	[System.AttributeUsage(System.AttributeTargets.All,\n AllowMultiple = false,\n Inherited = false)]\npublic JsonVehicleConverterAttribute : System.Attribute\n{\n ...\n}	0
765127	765112	Changing my Repeater DataSource when there are no items	If Not IsPostBack Then\n\n            Dim sBasePath As String = System.Web.HttpContext.Current.Request.ServerVariables("APPL_PHYSICAL_PATH")\n            If sBasePath.EndsWith("\") Then\n                sBasePath = sBasePath.Substring(0, sBasePath.Length - 1)\n            End If\n\n            sBasePath = sBasePath & "\" & "pics" & "\" & lblID.Text\n\n            Dim oList As New System.Collections.Generic.List(Of String)()\n\n            For Each s As String In System.IO.Directory.GetFiles(sBasePath, "*_logo.*")\n\n                'We could do some filtering for example only adding .jpg or something \n                oList.Add(System.IO.Path.GetFileName(s))\n\n            Next\n\n            If oList.Count = 0 Then\n\n              oList.Add("Path to a image with no image text")\n\n            End If\n\n   repImages.DataSource = oList\n                repImages.DataBind()\n\n\n        End If	0
19112310	19099035	Disable network adapter without WMI	Process.Start("cmd.exe","/c netsh interface set interface 'Local Area Connection' DISABLED");	0
17226156	17225169	Stack trace of function that has been inlined	[MethodImpl(MethodImplOptions.NoInlining)]	0
3889233	3888810	Populate DataTable with records from database?	// Create a connection to the database        \nSqlConnection conn = new SqlConnection("Data Source=MyDBServer;Initial Catalog=MyDB;Integrated Security=True");\n// Create a command to extract the required data and assign it the connection string\nSqlCommand cmd = new SqlCommand("SELECT Column1, Colum2 FROM MyTable", conn);\ncmd.CommandType = CommandType.Text;\n// Create a DataAdapter to run the command and fill the DataTable\nSqlDataAdapter da = new SqlDataAdapter();\nda.SelectCommand = cmd;\nDataTable dt = new DataTable();\nda.Fill(dt);	0
30392165	28338207	How to set focus on a control within a custom control?	protected override void OnEnter(EventArgs e)\n{\n    base.OnEnter(e);\n    textBox.Select();\n}	0
19171612	19171588	Interface name expected - but I don't understand how to implement it	interface ICommonEvents {\n    void OnError(string message, OnErrorEventsArgs.ShowExceptionLevel showException, Exception exception);\n    event EventHandler<OnErrorEventsArgs> OnErrorEvent {add;remove;}\n}\n// Keep the implementation the same\npublic class CommonEvents : DisposanbleObject, ICommonEvents {\n    ...\n}\n// Here is your derived class:\npublic class ItemDal : Common.Dal.BaseDal, ICommonEvents {\n    private readonly CommonEvents ce = ... // Initialize your common events\n    void OnError(string message, OnErrorEventsArgs.ShowExceptionLevel showException, Exception exception) {\n        ce.OnError(message, showException, exception);\n    }\n    event EventHandler<OnErrorEventsArgs> OnErrorEvent {\n        add {ce.OnErrorEvent += value;}\n        remove {ce.OnErrorEvent -= value;}\n    }\n}	0
4291374	4291329	Applying progress bar to the winform on button click	private void button1_Click(object sender, EventArgs e)\n{\n    ProgressBar p = new ProgressBar();\n    p.Location = new Point(10, 10);\n    p.Size = new Size(100, 30);\n    this.Controls.Add(p);\n}	0
10717917	10717849	How to avoid code duplication here?	public override void CalcV(IV iv, int index = -1)\n{\n    ....\n    double v = index > -1 ? GetV(a,b,c, index) : GetV(a,b,c);\n\n    ....\n}	0
21968163	21952809	Highlight a line in a RichTextBox	public void SelectLine(int line)\n    {\n        int c = 0;\n        TextRange r;\n\n        foreach (var item in editor.Document.Blocks)\n        {\n            if (line == c)\n            {\n                r = new TextRange(item.ContentStart, item.ContentEnd);\n                if (r.Text.Trim().Equals(""))\n                {\n                    continue;\n                }\n                r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);\n                r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White);\n                return;\n            }\n            c++;\n        }\n    }	0
9291931	9291866	Advice on a design of a recursive method	public TimeSpan GetTotalDuration()\n{\n    if (SubTasks != null)\n        return GetDuration() + SubTasks.Sum(t => t.GetTotalDuration()); \n\n    return GetDuration();\n}	0
3657410	3657377	Regular Expression for email validation.	try {\n    address = new MailAddress(address).Address;\n} catch(FormatException) {\n    //address is invalid\n}	0
8505066	8488227	Create firewall rule to open port per application programmatically in c#	using NetFwTypeLib; // Located in FirewallAPI.dll\n...\nINetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(\n    Type.GetTypeFromProgID("HNetCfg.FWRule"));\nfirewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;\nfirewallRule.Description = "Used to block all internet access.";\nfirewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;\nfirewallRule.Enabled = true;\nfirewallRule.InterfaceTypes = "All";\nfirewallRule.Name = "Block Internet";\n\nINetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(\n    Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));\nfirewallPolicy.Rules.Add(firewallRule);	0
6221155	6221121	accessing class that creates list from database	List<Command> myCommands = CommandDB.GetCommands();\nforeach(Command com in myCommands)\n{\n    //Do stuff\n}	0
2635005	2634817	How can i get the between cell addresses	Option Explicit\n\nPrivate Sub calculateRangeOneByOne()\n    Dim rangeIterator As Range\n    Dim rangeToIterate As Range\n    Dim sum As Double\n\n\n    Set rangeToIterate = Range("A8", "E8")\n    sum = 0#\n    For Each rangeIterator In rangeToIterate\n        sum = sum + rangeIterator\n    Next\n\n\nEnd Sub	0
23242724	23242683	Can you Count() your assets? (windows 8 store app)	//To Access Folder\n        var InstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;\n        //Get the Images Folder\n        InstalledFolder = await InstalledFolder.GetFolderAsync("Assets");\n        //Get files\n        var files = await InstalledFolder.GetFilesAsync(); \n        var count = files.Count;	0
10658915	10295776	A circular reference was detected while serializing an object of type	jr.Data = prom.Select(p => new \n{ \n    ID = p.ID, \n    Name = p.Name, \n    DepartmentID = p.DepartmentID,\n    BrandID = p.BrandID\n}).ToArray();	0
23781894	23779516	log4net - Check/get configured LogLevel in C#	private readonly List<Level> logLevels = new List<Level>\n{\n     Level.Alert,\n     Level.All,\n     Level.Critical,\n     Level.Debug,\n     Level.Emergency,\n     Level.Error,\n     Level.Fatal,\n     Level.Fine,\n     Level.Finer,\n     Level.Finest,\n     Level.Info,\n     Level.Log4Net_Debug,\n     Level.Notice,\n     Level.Off,\n     Level.Severe,\n     Level.Trace,\n     Level.Verbose,\n     Level.Warn\n};\n\npublic IList<Level> EnabledLogLevels(ILog logger)\n{\n    List<Level> levels = new List<Level>();\n\n    foreach (Level level in logLevels)\n    {\n        if (logger.Logger.IsEnabledFor(level))\n        {\n            levels.Add(level);\n        }\n    }\n\n    return levels;\n}	0
13202316	13202275	Adding a fixed number of spaces to the end of a variable length string	message = message.PadRight(message.Length + 35, ' ');	0
33301576	33301519	Assigning Querystring variable with Linq	DateTime startDate  = DateTime.Parse(start);\ntest = client.GetEventInstances().Where(e => e.StartDate.Date == startDate.Date);	0
5739120	5738346	How to programatically in c# get the latest top "n" commit messages from a svn repository	private static IList<string> GetLatestCommitMessages(Uri repository, int count)\n{\n    using (var client = new SvnClient())\n    {\n        System.Collections.ObjectModel.Collection<SvnLogEventArgs> logEntries;\n        var args = new SvnLogArgs()\n        {\n            Limit = count\n        };\n\n        client.GetLog(repository, args, out logEntries);\n\n        return logEntries.Select(log => log.LogMessage).ToList();\n    }\n}	0
3489474	3489453	How can I convert an enumeration into a List<SelectListItem>?	Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {\n    Text = v.ToString(),\n    Value = ((int)v).ToString()\n}).ToList();	0
33214754	33126412	How to embed file to word docx?	using System.Collections.Specialized;\n...\n...\n//Copy the Filename to Clipboard (setFile function uses StringCollection)\nStringCollection collection = new StringCollection();\ncollection.Add(Environment.CurrentDirectory + "\\MyFile.zip");\nClipboard.SetFileDropList(collection);\n\n//Paste into the selected Range.\nrange.Paste();	0
31270130	31237613	How to register a global filter with mvc 6, asp.net 5	public void ConfigureServices(IServiceCollection services)\n{\n   services.AddMvc();\n   services.ConfigureMvc(options =>\n   {\n      options.Filters.Add(new YouGlobalActionFilter());\n   }\n}	0
30357449	30357162	String to int in c#	string str = "100";\nint a = Convert.ToInt32(str);	0
14586329	14585623	Enumerating RecordSet in DataFlow Script Component as Data Source	DataTable datatable = new DataTable();\n    System.Data.OleDb.OleDbDataAdapter oAdapter = new System.Data.OleDb.OleDbDataAdapter();\n\n    oAdapter.Fill(datatable,ReadOnlyVariables["User::XXXXX"]);\n\n    foreach (DataRow row in datatable.Rows)\n    {\n        Output0Buffer.AddRow();\n        Output0Buffer.CoverAmount = Convert.ToInt32(row["XXXX"].ToString());\n    }	0
33486090	33485523	GridView foreach from one index to another	protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        var index = e.Row.RowIndex;\n        if(index > 14)\n        {\n             //Do stuff\n        }\n        else if (index >= 15 && index <= 30)\n        {\n             //Do other stuff\n        }\n    }	0
31001551	31000714	How to modify current line in multicolored richtextbox in C#	// GET LAST LINE\nstring LastLineText = richTextBox1.Lines[richTextBox1.Lines.Count() - 1];\nint LastLineStartIndex = richTextBox1.Text.LastIndexOf(LastLineText);\n\n// SELECT TEXT\nrichTextBox1.SelectionStart = LastLineStartIndex;\nrichTextBox1.SelectionLength = LastLineText.Length;\n\n// REPLACE TEXT\nrichTextBox1.SelectedText = "Line 4";	0
1241248	1241156	WPF image control source	imagebox.Source = new BitmapImage(new Uri(openfile.FileName));	0
13630763	13630623	Model and partial model, how to avoid the redundant code?	public class UserModel : UserModelBase\n{\n    ...\n}	0
4077891	4077862	Declaring MySql command	SqlCommand comm;\nif (cbBackup.Checked)\n{\n    log("Making backup, this might take a while..");\n\n    comm = new SqlCommand(GetFromResources("databaseInstaller.qry.osrose_backup.sql"), conn);\n} \n\ncomm = new SqlCommand(GetFromResources("databaseInstaller.qry.anotherfile.sql"), conn);	0
10659434	10659208	How to design a class to prevent circular dependencies from calling derived members before construction?	interface IKernel\n{\n    // Useful members, e.g. AvailableMemory, TotalMemory, etc.\n}\n\nclass Kernel : IKernel\n{\n    private readonly Lazy<FileManager> fileManager;  // Every kernel has 1 file manager\n    public Kernel() { this.fileManager = new Lazy<FileManager>(() => new FileManager(this)); /* etc. */ }\n\n    // implements the interface; members are overridable\n}\n\nclass FileManager\n{\n    private /*readonly*/ IKernel kernel;  // Every file manager belongs to 1 kernel\n    public FileManager(IKernel kernel) { this.kernel = kernel; /* etc. */ }\n}	0
13051389	13051268	How do I add a value to my txt file one time only?	if (!File.ReadAllText("students.txt").Contains(newRecord))\n{\n  // write to file...\n}	0
29309776	29309687	How to close a windows form after message box OK is clicked?	if (updateRequired)\n{\n    DialogResult dialog = MessageBox.Show("FleetTrack? update required.\n\nA new version of FleetTrack? is available on your Driver Hub. You must download"\n+ " the latest update to use FleetTrack?.", "FleetTrack? Update Required", MessageBoxButtons.OK);\n    if (dialog == DialogResult.OK)\n    {\n        Application.Exit();\n    }\n} else \n    Application.Run(new Login());	0
21013606	21013570	Reading an XML and parse through xml to get a particular value	var xdoc = XDocument.Load(path_to_xml);\nvar storeName = xdoc.Root.Elements()\n                    .Where(s => (int)s.Attribute("departmenid") == id)\n                    .Select(s => (string)s.Attribute("store_name"))\n                    .FirstOrDefault();	0
6409182	6409139	Batch Update/insert in using SQLCommand in C#	SqlCommand command = new SqlCommand();\n// Set connection, etc.\nfor(int i=0; i< items.length; i++) {\n    command.CommandText += string.Format("update mytable set s_id=@s_id{0} where id = @id{0};", i);\n    command.Parameters.Add("@s_id" + i, items[i].SId);\n    command.Parameters.Add("@id" + i, items[i].Id);\n}\ncommand.ExecuteNonQuery();	0
24091710	24091645	Search xml file for a given inner text value, return its parent	XDocument doc = XDocument.Load(filename); // Path to the XML file from the post.\nXElement node = doc.Root.Elements("Q").Where(e => e.Element("SKU").Value == " Unique Value ").FirstOrDefault();	0
33162922	33162823	How to Split an Already Split String	foreach (var item in betSlipwithoutStake)\n    {\n        test1 = item.Text;\n        splitText = test1.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);\n\n        if (!test.Exists(str => str == splitText[0]))\n            if(splitText[0].Contains("("))\n                test.Add(splitText[0].Split('(', ')')[1]);           \n            else\n                test.Add(splitText[0]);\n    }	0
3528647	3528305	How to use a DataAdapter with stored procedure and parameter	protected DataTable RetrieveEmployeeSubInfo(string employeeNo)\n        {\n            SqlCommand cmd = new SqlCommand();\n            SqlDataAdapter da = new SqlDataAdapter();\n            DataTable dt = new DataTable();\n            try\n            {\n                cmd = new SqlCommand("RETRIEVE_EMPLOYEE", pl.ConnOpen());\n                cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));\n                cmd.CommandType = CommandType.StoredProcedure;\n                da.SelectCommand = cmd;\n                da.Fill(dt);\n                dataGridView1.DataSource = dt;\n            }\n            catch (Exception x)\n            {\n                MessageBox.Show(x.GetBaseException().ToString(), "Error",\n                        MessageBoxButtons.OK, MessageBoxIcon.Error);\n            }\n            finally\n            {\n                cmd.Dispose();\n                pl.MySQLConn.Close();\n            }\n            return dt;\n        }	0
7643884	7643825	How to pass command line argument in .net windows application	var info = new System.Diagnostics.ProcessStartInfo();\n  info.FileName = "cmd.exe";\n  info.Arguments = "/C";\n  info.UseShellExecute = true;\n  var process = new System.Diagnostics.Process();\n  process.StartInfo = info;\n\n  process.Start();\n  process.WaitForExit();	0
5139369	5051145	Inserting multiple rows to a database in a single call	insert into mytable (col1, col2)\n  values (1, 2),\n         (3, 4),\n         (5, 6)	0
1367786	1367486	How can I check if a Win32 Window pointer is a valid .Net Control?	Control AssociatedDotNetControl = \n    Control.FromChildHandle(Win32WindowPointerAshWnd);\n\nif(AssociatedDotNetControl != null)\n{\n    // this is a .NET control\n}\nelse\n{\n    // this is not a .NET control\n}	0
18112557	18112082	Using SQL Server "LEFT" function result in poor performance when running Batch data than without it	sqlAsk += " SELECT Year, Make, Model, Style AS Trim, Squish_Vin AS SquishVin, '' AS VehicleId FROM ED_SQUISH_VIN_V3_90 ";\n        //@@sqlAsk += " WHERE @parmVehicleSquishVin = Squish_VIN ";\n        sqlAsk += " WHERE Squish_VIN like '"+squishVin+"%'";	0
6089125	6088795	How to deal with sequential calling event handlers?	private bool IsAdding { get; set; }\nprivate int item_index;\nprivate IList m_collection;\n\npublic void AddNewItem(object item)\n{\n    if (item == null)\n    {\n        throw new Exception("Cannot add null item."); // little bit of contracting never hurts\n    }\n\n    m_collection.Add(item);\n    IsAdding = true;\n    ItemIndex = collection.Count - 1; //I'm just making assumptions about this piece but it is not important how you decide what your index is to answer the question\n\n    if (OnNewItem != null)\n    {\n       OnNewItem(this, EventArgs.Empty); \n    }\n}\n\npublic int ItemIndex\n{\n   get { return item_index =; }\n   set\n   {\n       item_index = value;\n       if (!IsAdding && OnScroll != null) //won't double fire event thanks to IsAdding\n       {\n           OnScroll(this, EventArgs.Empty);\n       }\n       IsAdding = false; //need to reset it\n   }\n}	0
5513224	5512921	WPF RichTextBox appending coloured text	TextRange tr = new TextRange(rtb.Document.ContentEnd,? rtb.Document.ContentEnd);\ntr.Text = "textToColorize";\ntr.ApplyPropertyValue(TextElement.?ForegroundProperty, Brushes.Red);	0
12601421	12598773	Is it okay to use Elmah instead of try/catch?	try {\n  ...\n}\ncatch (Exception e) {\n  Elmah.ErrorSignal.FromCurrentContext().Raise(e)\n}	0
991023	991017	How to add to a list using Linq's aggregate function C#	context.Items\n  .Select(item => new DestinationType(item.A, item.B, item.C))\n  .ToList();	0
31757196	31757126	Display sum and average of numbers 1 to 100	using System;\nusing System.Linq;\n\nnamespace SumAndAverage\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var data = Enumerable.Range(1, 100);\n            Console.WriteLine("the sum is " + data.Sum());\n            Console.WriteLine("the average is " + data.Average());\n        }\n    }\n}	0
11423515	10905549	How to convert a json string?	public class JsonData\n{\n    public string name { get; set; }\n    public Arguments[] args { get; set; }\n}\n\npublic class Arguments\n{\n    public MouseDet mouseDet { get; set; }\n}\n\npublic class MouseDet\n{\n    public int rid { get; set; }\n    public int posx { get; set; }\n    public int posy { get; set; }\n}\n\n...\n\nvar posx = foo.args[0].mouseDet.posx;	0
7177788	7177476	Trouble when i am moving the list box items from listbox1 to listbox 2 in WPF?	if (listBox2.SelectedItem == null)\n{\n    System.Windows.MessageBox.Show("*Please Select unassigned Wks ");\n    return;\n}\nelse\n{\n    if (listBox2.SelectedIndex > -1)\n    {\n        Object obj = listBox2.SelectedItem;\n        listBox1.Items.Add(obj);\n        listBox2.Items.Remove(obj);\n    }\n}	0
24531559	24531424	Databinding ListBox to a List of a Class that Contains a navigation Property Of Other Class?	if (Session["AllUsers"] == null)\n{\n    LoadDataForUser();\n}\n\nvar lstUser = (List<Entities.User>)Session["AllUsers"];\n\nddlEmployees.DataTextField = "UserName";//I am getting Error here\nddlEmployees.DataValueField = "UserID";\nddlEmployees.DataSource = from user in lstUser\n                           select new { user.UserID, UserName = user.UserDetail.Name };\nddlEmployees.DataBind();\n\nListItem li = new ListItem("--Select Users--", "-1");\nddlEmployees.Items.Insert(0, li);	0
1293577	1293549	string to variable name	using System.Reflection;\n...\nmyCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);	0
33584317	33581627	How to make correct encapsulation with multithreading .NET C#	public class RfidReaderHardware {\n    public event EventHandler Received;\n\n    public RfidReaderHardware() {\n        syncContext = System.Threading.SynchronizationContext.Current;\n    }\n\n    protected void OnReceived(EventArgs e) {\n        if (syncContext == null) FireReceived(e);\n        else syncContext.Send((_) => FireReceived(e), null);\n    }\n\n    protected void FireReceived(EventArgs e) {\n        var handler = Received;\n        if (handler != null) Received(this, e);\n    }\n\n    private System.Threading.SynchronizationContext syncContext;\n}	0
2221789	2221722	Browser detection	if (Request.Browser.Type.Contains("Firefox")) // replace with your check\n{\n    ...\n} \nelse if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check\n{\n    if (Request.Browser.MajorVersion  < 7)\n    { \n        DoSomething(); \n    }\n    ...\n}\nelse { }	0
16567311	16566773	Changing column widths of excel when exporting data to Excel file [C#]	worksheet.Cells.Style.EntireColumn.AutoFit()	0
1290435	1290413	WPF/Forms: Creating a new control programmatically that can have events	public Window1()\n{\nInitializeComponent();\n\nButton button = new Button();\nbutton.Click += new RoutedEventHandler(button_Click);\n}\n\nvoid button_Click(object sender, RoutedEventArgs e)\n{\nComboBox combo = new ComboBox();\ncombo.SelectionChanged += new SelectionChangedEventHandler(combo_SelectionChanged);\n}\n\nvoid combo_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n// Do your work here.\n}	0
16399749	16399115	compare two tables for matching and update or move and delete rows	--update action\nupdate  a \nset a.id = b.id, a.match =1\nfrom _persons a inner join _personals b \non a.social = b.social or a.taxnumber = b.taxnumber\n\n--delete / insert action\ndeclare @RowCount as integer\nselect  @RowCount = count(a.id) from _persons a  \nwhere ID not in (\n        select a.id\n        from _persons a inner join _personals b \n        on a.social = b.social or a.taxnumber = b.taxnumber\n    )\n\nif @RowCount>0 \nbegin\ninsert into _Personals (ID, fname, lname, address, social, taxnumber)\nselect ID, fname, lname, address, social, taxnumber from _persons a\nwhere ID not in (\n                select a.id\n                from _persons a inner join _personals b \n                on a.social = b.social or a.taxnumber = b.taxnumber\n            )\ndelete _persons\nwhere ID not in \n    (\n            select a.id\n            from _persons a inner join _personals b \n            on a.social = b.social or a.taxnumber = b.taxnumber\n    )\nend	0
17851046	17850695	Getting value from UI Element	Button.Text \nLabel.Text\nTextbox.Text	0
13310049	13306484	Programmatically create a key binding for textbox input	var textBinding = new Binding("Text") { Source = textBoxInput };\n        buttonConfirmAddKitType.SetBinding(ButtonBase.CommandParameterProperty, textBinding);\n        var keybinding = new KeyBinding\n        {\n            Key = Key.Enter,\n            Command = command,\n        };\n        keybinding.CommandParameter = textBoxInput.Text;\n        textBoxInput.InputBindings.Add(keybinding);	0
23841335	23841126	How to make that when the mouse is enter a usercontrol the control will move to another location?	private void zedGraphControl_MouseLeave(object sender, EventArgs e)\n        {\n            if(this.Location == new Point(12, 400))\n                this.Location = new Point(Width / 2 - this.Width / 2, Height / 2 - this.Height / 2);\n        }\n\n        private void zedGraphControl_MouseEnter(object sender, EventArgs e)\n        {\n            if (this.Location == new Point(Width / 2 - this.Width / 2, Height / 2 - this.Height / 2))\n                this.Location = new Point(12, 400);\n        }\n\n        protected override void OnMouseLeave(EventArgs e)\n        {\n            this.Refresh();\n            this.Invalidate();\n            base.OnMouseLeave(e);\n        }\n\n        protected override void OnMouseEnter(EventArgs e)\n        {\n            this.Refresh();\n            this.Invalidate();\n            base.OnMouseEnter(e);\n        }	0
29025051	29024946	Create a file in c#	using System; using System.IO;\n\nnamespace CreateFile {\n\nclass MainClass\n{\n\n        public static void Main (string[] args)\n        {\n        Console.WriteLine ("Enter the File name:");\n        string filename = Console.ReadLine (); \n        FileInfo fi = new FileInfo(@"G:\New folder (5)\" + filename + ".txt");\n        //You can use any extension to create respective file.\n                StreamWriter sw;\n\n                if (!fi.Exists)\n                {\n                    using (FileStream fs = fi.Create())\n                    {\n\n                    }\n                }\n        }\n    }\n}	0
11110536	11110478	Trim a char array	public static void Trim(Char[] str) {\n\n    int maxI = 0; // an optimisaiton so it doesn't iterate through chars already encountered\n    for(int i=0;i<str.Length;i++) {\n        if( Char.IsWhitespace( str[i] ) ) str[i] = '\0';\n        else { maxI = i; break };\n    }\n\n    for(int i=str.Length-1;i>maxI;i--) {\n        if( Char.IsWhitespace( str[i] ) ) str[i] = '\0';\n    }\n}	0
2590499	2590476	Writing datatable to database file, one record at a time	var inputRecordSet = // connect somehow\nvar outputRecordSet = // ditto\n\nwhile (!inputRecordSet.EOF)\n{\n    outputRecordSet.Hour = inputRecordSet.Hour;\n\n    outputRecordSet.Day1 = inputRecordSet.Day;\n    outputRecordSet.KWForecast = inputRecordSet.Day1;\n    outputRecordSet.Insert();\n\n    outputRecordSet.Day2 = inputRecordSet.Day;\n    outputRecordSet.KWForecast = inputRecordSet.Day2;\n    outputRecordSet.Insert();\n\n    // and so on... for seven days\n\n   inputRecordSet.MoveNext();\n}	0
33742933	33742749	Unable to post simple string data to Web API from AngularJS	public class SaveModel \n{\n    public string DATA {get; set;}\n}\n\n\n[HttpPost]\n[Route("api/SkeltaInterfaceController/SaveWorkflow")]\npublic bool SaveWorkflow([FromBody] SaveModel model)\n{ ...	0
3514026	3513961	opening a file in the browser instead of downloading it	response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", reportItem.ExportName));	0
7372908	7372305	WPF with page navigation NullReferenceException	// If the user doesn't want to navigate away, cancel the navigation \n        if (result == MessageBoxResult.No) \n            e.Cancel = true;\n        else  // Remove Handler\n        {\n            if (this.NavigationService != null)\n                this.NavigationService.Navigating -= new NavigatingCancelEventHandler(NavigationService_Navigating);\n        }\n    }	0
8624302	8624041	Discover serial ports in C#	SerialPort.GetPortNames()	0
16500337	16500006	Read XML with C# with custom deserializer	public class MyModel\n{\n    [XmlIgnore]\n    public bool Foo \n    {\n        get\n        {\n            return string.Equals(FooXml, "true", StringComparison.OrdinalIgnoreCase);\n        }\n        set\n        {\n            FooXml = value.ToString();\n        }\n    }\n\n    [XmlElement("Foo")]\n    public string FooXml { get; set; }\n}	0
15254913	15254486	How to filter tree structure?	bool Filter(MyNode node,int type)\n{\n//remove children\nforeach(MyNode child in node.Children.Where(c=>!Filter(c, type)).ToArray())\n    node.Children.Remove(child);\n//return if should be retained\nreturn node.Type==type || node.Children.Count>0;\n}	0
11384328	11384188	Hightlight text inside richtextbox in runtime	private void button1_Click(object sender, EventArgs e)\n        {\n            if (richTextBox1.Text.Contains("red"))\n            {\n                richTextBox1.SelectionStart = 0;\n                richTextBox1.SelectionLength = richTextBox1.Text.Length;\n                richTextBox1.SelectionBackColor = Color.Black;\n                richTextBox1.SelectionColor = Color.White;\n            }\n        }	0
28657386	28657039	Add attribute to XML in ASP.NET webservices	public XmlDocument productsAll()\n{\n    // define connection string\n    string conString = "Data Source=my_db.com;Integrated Security=True";\n\n    // define SQL query to use \n    string query = "SELECT ID AS '@ID', Name FROM dbo.Products FOR XML PATH('Product'), ROOT('Products')";\n\n    // set up connection and command objects\n    using (SqlConnection sqlConn = new SqlConnection(conString))\n    using (SqlCommand sqlCmd = new SqlCommand(query, sqlConn))\n    {\n       // open connection\n       sqlConn.Open();\n\n       // execute query, read out the XML from the T-SQL query\n       string xmlContents = sqlCmd.ExecuteScalar().ToString();\n\n       // close connection\n       sqlConn.Close();\n\n       // parse XML received from SQL Server into a XmlDocument and return\n       XmlDocument xmlDom = new XmlDocument();\n       xmlDom.LoadXml(xmlContents);\n\n       return xmlDom;\n    }\n}	0
18438398	18437826	how to delete image file after upload in C#?	FileInfo info1 = new FileInfo(folderPath + filename);\n            if (info1.Exists)\n            {\n                info1.Delete();\n            }	0
22593481	22579923	RSA Sign with PHP, verify with C#	rsa.FromXmlString("{XML_KEY}");\nsuccess = rsa.VerifyData(bytesToVerify, new SHA1CryptoServiceProvider(), signedBytes);	0
14614777	14613908	LINQ query with a generic table	private static void Load<T>()\n{\n   ...\n   var genericQuery = contexto.GetTable<T>();\n   ...\n}	0
16887655	16887621	MySqlDataReader close connection	using(MySqlConnection connect = new MySqlConnection(connectionStringMySql))\nusing(MySqlCommand cmd = new MySqlCommand())\n{\n    string commandLine = "SELECT id,token FROM Table WHERE id = @id AND token = @token;";\n    cmd.CommandText = commandLine;\n\n    cmd.Parameters.AddWithValue("@id", id);\n    cmd.Parameters.AddWithValue("@token", token);\n\n    cmd.Connection = connect;\n    cmd.Connection.Open();\n\n    using(msdr = cmd.ExecuteReader())\n    {\n\n         //do stuff.....\n    } // <- here the DataReader is closed and disposed.\n\n}  // <- here at the closing brace the connection is closed and disposed as well the command	0
3232439	3232357	What is the easiest way to validate a UPN and a NT login name?	WindowsIdentity wi = new WindowsIdentity("alias@example.com");	0
23958264	22105659	Update Cloudwatch Custom Metric in C#	mdr.MetricData = new List<MetricDatum>();\n            mdr.MetricData.Add(dataPoint);\n\n            PutMetricDataResponse resp = cloudwatch.PutMetricData(mdr);\n            Debug.Assert(resp.HttpStatusCode == System.Net.HttpStatusCode.OK);	0
2587845	2587827	Need help in Hashtable implementation	string sentence = whatever;\nint minimum = whatever;\nvar words = sentence.Split(' ');\nvar longWords = from word in words \n                where word.Length >= minimum \n                select word;\nforeach(var longWord in longWords) \n    Console.WriteLine(longWord);	0
31816220	31804370	Update to Azure Application Insights 1.1, now data is not sent	tc = new TelemetryClient();\ntc.InstrumentationKey = "GET YOUR KEY FROM THE PORTAL";\ntc.TrackEvent("SampleEvent");	0
2464218	2431958	How to modify IIS handler mapping permissions via Wix or a Custom Action	strComputer = "."\nSet objWMIService = GetObject _\n    ("winmgmts:{authenticationLevel=pktPrivacy}\\" _\n        & strComputer & "\root\microsoftiisv2")\n\nvdir = "W3SVC/1/ROOT"\n\nSet colItems = objWMIService.ExecQuery _\n    ("Select * from IIsWebVirtualDirSetting WHERE Name = '" & vdir & "'")\n\nFor Each objItem in colItems\n    ''WScript.Echo objItem.AppRoot\n    objItem.AccessExecute = "False"\n    objItem.Put_()\nNext	0
24439986	24439894	How do I split a string by a character, but only when it is not contained within parentheses?	var input = "((Why,Heck),(Ask,Me),(Bla,No))";\n\nvar result = Regex.Matches(input, @"\([^\(\)]+?\)")\n                  .Cast<Match>()\n                  .Select(m => m.Value)\n                  .ToList();	0
9314423	9314288	Bold in RichtextBox	int srt = bold.Find(name);	0
10893379	10893311	Find files with matching patterns in a directory c#?	string pattern = @"(23456780|otherpatt)";	0
29255897	29255783	Import Excel SpreadSheet To Array	string[] list = myvalues.OfType<object>()\n                        .Skip(1)\n                        .Select(o => o.ToString()).ToArray();	0
6911852	6910915	Unable to Export the Dynamically added row to Gridview to Excel	public static Control GetPostBackControl(Page page)\n{\n    Control control = null;\n\n    string ctrlname = page.Request.Params.Get("__EVENTTARGET");\n    if (ctrlname != null && ctrlname != string.Empty)\n    {\n        control = page.FindControl(ctrlname);\n    }\n    else\n    {\n        foreach (string ctl in page.Request.Form)\n        {\n            Control c = page.FindControl(ctl);\n            if (c is System.Web.UI.WebControls.Button)\n            {\n                control = c;\n                break;\n            }\n        }\n    }\n    return control;\n}	0
10544603	10544472	How to make a collection of values for same key in a dictionary object?	collection.GroupBy(x => x.Property).ToDictionary(x => x.Key, x => x.Select(y => y.Value).ToList());	0
25993978	25993912	Not able to set a registry value in C#	if (key != null)\n        {\n            // Key doesn't exist.\n            key.SetValue("system_module", "Application Location");\n        }	0
2273619	2273597	Unexpected operation order in Stack<T> related one liner	stack.Peek().set_Value(stack.Pop().Value);	0
834715	834610	How to get the name of a subreport from a Crystal Report in C#?	using CrystalDecisions.CrystalReports.Engine;\n//snip\n\n//Where report is the parent rpt of type ReportDocument (or a subclass of ReportDocument)\nforeach(ReportDocument subreport in rpt.Subreports)\n{\n    if(subreport.Name = "Multiple")\n    {\n        //Not the most elegant solution, but should work\n        SubreportObject subrpt = (SubreportObject)subreport;\n        subrpt.Height = 0;\n    }\n}	0
8823460	8823126	LINQ query to return MAX date, where all days of that week meet a certain criteria	DateTime maxWeek =\n            dt.Where(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday).GroupBy(\n                d => new GregorianCalendar().GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)).Where(\n                    g => g.Count() > 2).OrderBy(g => g.Key).Last().Max();	0
15379486	15363564	how to get the second level text from the leaf?	RadTreeNode node_tmp = new RadTreeNode();\n      node_tmp = node;\n          while (node_tmp.ParentNode != null)\n                {\n                   p_txt = node_tmp.Text.TrimEnd();\n                   node_tmp = node_tmp.ParentNode;\n\n                }	0
18239283	18236602	Opengl and opencl can use only 1 kernel in a single shared context	glFinish (...)	0
14725163	14725004	C# Remove Phone Number from String?	var myRegex = new Regex(@"((\d){3}-1234567)|((\d){3}\-(\d){3}\-4567)|((\d){3}1234567)");\nstring newStringWithoutPhoneNumbers =  myRegex.Replace("oldStringWithPhoneNumbers", string.Empty);	0
6351467	6351407	Add items to a list, then make them into ListItems	protected List<Exception> Exceptions = new List<Exception>();\n\nprotected void SomeMethod()\n{\n    try\n    {\n        ...\n    }\n    catch(Exception e)\n    {\n        this.Exceptions.Add(e);\n    }\n}	0
18572592	18570289	how to replace <br> tag with <br/> tag using HtmlAgilityPack?	document.OptionWriteEmptyNodes = true;	0
19189729	19189713	String manipulation in C#. How to extract a string from a string?	Path.GetFileNameWithoutExtension()	0
8708026	8707997	How to print the byte array as the following	for( int i = 0; i < array.size(); i+=2 )\n{\n  print( (short)((array[i] << 8) | (array[i+1])));\n}	0
5953503	5950123	How to configure the LifeStyle based on a marker interface	container.Register\n            (\n                AllTypes.FromThisAssembly()\n                .Where(c=> c.GetInterface(typeof(LifestyleUponInterface.InterfaceForSingleton).Name)!=null )\n                .Configure( c=> c.LifeStyle.Singleton )\n            );\n            container.Register\n            (\n                AllTypes.FromThisAssembly()\n                .Where(c => c.GetInterface(typeof(LifestyleUponInterface.InterfaceForTransient).Name) != null)\n                //.If(Component.IsInNamespace("<yourNamespace>"))\n                .Configure(c => c.LifeStyle.Transient)\n            );	0
20706998	20703846	Session variable has old value, needs to update with page redirect	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostback)\n    {\n        if (this.Session["value1"] != null)\n        {\n            lbl1.Text = (String)this.Session["value1"].ToString();\n        }\n    }\n}	0
25470030	25470013	Left to right for DateTimePicker in C#	if (CultureInfo.CurrentCulture.TextInfo.IsRightToLeft)\n{\n   this.dateTimePicker.RightToLeftLayout = true;\n}\nelse\n{\n   this.dateTimePicker.RightToLeftLayout = false;\n}	0
13686991	13686942	Extract IEnumerable out of another IEnumerable	IEnumerable<Product> products = offerList.Offers.Select(o => o.Product);	0
20630124	20630040	Has got any real benefit of PLINQ?	int[] src = Enumerable.Range(0, 100).ToArray();\nvar query = src.AsParallel()\n               .Select(x => ExpensiveFunc(x));	0
7537708	7534170	Time-varying values in Rx	var booleans = new BehaviorSubject<bool>(chk.Checked)\nvar chkEvents = ... //generate boolean observable from checkbox check event\nchkEvents.Subscribe(booleans);\n\nObservable.Interval(TimeSpan.FromSeconds(10))\n .Where(i => booleans.First())\n .Subscribe(i => DoIO());	0
6347492	6346996	How can I convert this method from C++ to C#?	byte[] buffer;\n    private void writeString(int location, string value, int length)\n    {\n        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();\n\n        if (value.Length < length)\n        {\n            Array.Copy(encoding.GetBytes(value), 0, buffer, location, value.Length);\n            Array.Clear(buffer, location, length - value.Length);\n        }\n        else Array.Copy(encoding.GetBytes(value), 0, buffer, location, length);\n    }	0
3048243	3048087	Converting one alphabet to another	public class ISO9TransliterationProvider {\n    private readonly Dictionary<Char, Char> charMapping = new Dictionary<char,char>() {\n        { '?', 'A' }, \n        { '?', 'B' } \n        //etc.\n    };\n\n    public string ToLatin(string cyrillic) {\n        StringBuilder result = new StringBuilder();\n        foreach (char c in cyrillic)\n            result.Append(charMapping[c]);\n        return result.ToString();\n    }\n}	0
10000093	9999941	Issue with my Space Invaders Clone	var LeftMost  = Type1Invaders.Where(i => i.invaderVis).FirstOrDefault();\nvar RightMost = Type1Invaders.Where(i => i.invaderVis).LastOrDefault();	0
2066735	2066489	How can you add a Certificate to WebClient (C#)?	class MyWebClient : WebClient\n{\n    protected override WebRequest GetWebRequest(Uri address)\n    {\n        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);\n        request.ClientCertificates.Add(new X509Certificate());\n        return request;\n    }\n}	0
15002197	14962341	Interface contract confuses static checker	public class Foo : IFoo\n{\n    private string _field;\n\n    public string Property\n    {\n        get { return _field; }\n    }\n\n    private void SetField()\n    {\n        _field = " foo ";\n    }\n\n    private string Method()\n    {\n        SetField();\n        return _field.Trim();\n    }\n}	0
27401185	27384486	Global Json Formatting not working	using System.Web.Http;\n\npublic class UserController : ApiController\n{\n    [Route("user/getalluser")]\n    public IEnumerable<User> Get()\n    {\n        return GetAllUser();\n    }\n}	0
19912205	19912083	How to get each tablerow in regex from a string (C#)?	\<tr[\s\S]*?\/tr\>	0
10666281	10666224	How Write a Stream into a xml file in Isolated Storage	using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(saveToPath, FileMode.Create))    \n{    \n  stream.CopyTo(fileStream);\n}	0
3001797	3001747	Implementing a runtime Look Up Table in C#	Tuple<int,int,int>	0
23427537	23426607	Multiple values from checkbox to array C# WPF	mainwindow.xaml\n<CheckBox Content="CheckBox"  Name="checkBox1" Command="{Binding YourCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay} />\n\nviewmodel.cs\n\nvoid YourCommand(object parameter)\n{\n    // do your logic\n\n}	0
26851019	15726310	Got Reversed Image from Byte Array when converting to Base64	MemoryStream memoryStream = new MemoryStream();\nbitmap.Save(memoryStream, ImageFormat.Bmp);\n\n// Skip header\nIEnumerable<byte> bytes = memoryStream.ToArray().Skip(54);	0
772618	772509	Finding how a foreach collection gets modified	object[] snap;\nlock (list)\n{\n   snap = list.ToArray();\n}\nforeach (object x in snap) ...	0
591002	590991	Merging two IEnumerable<T>s	public static IEnumerable<Person> SmartCombine(IEnumerable<Person> fallback, IEnumerable<Person> translated) {\n  return translated.Concat(fallback.Where(p => !translated.Any(x => x.id.equals(p.id)));\n}	0
9030347	9030326	Comparing List to List with a Twist	var diff1 = List1.Except(List2);\nvar diff2 = List2.Except(List1);	0
3405841	3405804	do we need to lock this queue?	Queue<T>	0
19931587	19931055	How to replace white spaces to &nbsp; between end of tag and start of text	(?<=&nbsp;)\s|\s(?=&nbsp;)	0
14815887	14815396	Own Add Method for Dictionary<TKey,TValue> which takes Expression<Func<T>> as parameter	var OrigionalValues = new ExpressionDictionary<object,object>();	0
33030768	33030725	how can i literaly read in C# a xml node with multiple atributes?	string cadenaValue = null;\nstring hotelValue = null;\nif (node.Attributes != null)\n{\n    var cadenaAttribute = node.Attributes["Cadena"];\n    if (cadenaAttribute != null) \n        cadenaValue = cadenaAttribute.Value;\n\n    var hotelAttribute = node.Attributs["Hotel"];\n    if (hotelAttribute != null)\n        hotelValue = hotelAttribute.Value;\n}\n\nif (cadenaValue != null)\n{\n    Console.WriteLine(cadenaValue);\n}\n\nif (hotelValue != null)\n{\n    Console.WriteLine(hotelValue);\n}	0
31226782	31226764	Way to check if a DateTime is between two Dates in C#	DateTime from = new DateTime(1960,1,1);\nDateTime to = new DateTime(1990, 12, 31);\nDateTime input = DateTime.Now;\nConsole.WriteLine(from <= input && input <= to); // False\ninput = new DateTime(1960,1,1);\nConsole.WriteLine(from <= input && input <= to); // True	0
32077978	32077067	Replace with values a given pattern in a string	private static String Replace(String str)\n{\n    var dictionary = new Dictionary<string, string>\n    {\n        {"primaryColour", "blue"},\n        {"secondaryColour", "red"}\n    };\n\n    string pattern = @"@Model\.(?<name>\w+)";\n    return Regex.Replace(str, pattern, m => \n        {\n            string key = m.Groups["name"].Value;\n            key = FirstCharacterToLower(key);\n            string value = null;\n            if (dictionary.TryGetValue(key, out value))\n                return value;\n            else\n                return m.Value;\n        });\n}	0
10709399	10709389	Is there any way to have a single static field value for all C<>?	class BaseC\n{\n    protected static O = new O();\n}\n\nclass C<T>: BaseC ...	0
16798125	16743357	Add only a percentage of rows to DataTable	Random rand = new Random();\n\n// Mark every row as not selected yet.\nint[] nonSelectedRows = new int[dt.Rows.Count];\nfor(int i = 0; i < dt.Rows.Count; i++)\n    nonSelectedRows[i] = 1;\n\nint numSelected = 0;\nint numLeft = dt.Rows.Count;\nint targetNum = dt.Rows.Count * errPercentage;\nwhile(numSelected < targetNum)\n{\n    for (int row = 0; row < dt.Rows.Count; row++)\n    {\n       // Each record has a 1/numleft chance of getting selected.\n       boolean isSelected = rand.Next(numLeft) == 0; \n\n       // Check to make sure it hasn't already been selected.\n       if(isSelected && nonSelectedRows[row] > 0)\n       {\n           dtRandomRows.ImportRow(dt.Rows[row]);\n           nonSelectedRows[row] = -1; // Mark this row as selected.\n           numSelected++;\n           numLeft--;\n       }\n\n       // We've already found enough to match our targetNum.\n       if(numSelected >= targetNum)\n           break;\n    }\n}	0
31397649	31397540	How can I convert this SQL to LINQ	var data = (from e in context.TableMessages\n            where context.TableViewedMessageLogs\n                     .Where(x => x.User_Email == 'asd@asd')\n                     .Select(x => x.Message_Id).Contains(e.Id) == false\n            select e)\n           .ToList();	0
16171022	16120721	WP7 - How to download and save files from skydrive	private void liveClient_DownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)\n{\n    Stream stream = e.Result;\n\n    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n        using (IsolatedStorageFileStream fileToSave = storage.OpenFile("tasks.xml", FileMode.Create, FileAccess.ReadWrite))\n        {\n            stream.CopyTo(fileToSave);\n            stream.Flush();\n            stream.Close();\n        }\n    }\n}	0
8135319	8135051	Notify Modal forms' parent that it needs to action something	BushBreaksLodgeManagerMain myManager = (BushBreaksLodgeManagerMain)this.Owner;	0
31872930	31872793	Using Math functions in Entity framework with mysql	var place= dbContext.Places.FirstOrDefault(x => Math.Pow(x.Lat,0.5) > 0);	0
4745251	4731032	Linq to Sql: returning limited number of rows per group	var limitedUsers = from p in dc.Products\n                   group p by p.UserName into g\n                   select new\n                   {\n                     UserName = g.Key,\n                     Products = g.Take(dc.UserLimits\n                                         .Where(u => u.UserName == g.Key)\n                                         .Single().DisplayLimit)\n                   };	0
12898478	12897891	Wrong rectangle drawing with gif animation using MSDN example	private void DrawFrame() {\n        if (currentFrame < frameCount - 1) {\n            currentFrame++;\n        } else {\n            loopCounter++;\n            currentFrame = 0;\n        }\n        this.Invalidate();\n    }\n\n    protected override void OnPaint(PaintEventArgs e) {\n        base.OnPaint(e);\n\n        int XLocation = currentFrame * frameWidth;\n        Rectangle rect = new Rectangle(XLocation, 0, frameWidth, frameHeight);\n        e.Graphics.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);\n    }	0
8032715	8032659	C# convert from uint[] to byte[]	byte[] byteArray = uintArray.SelectMany(BitConverter.GetBytes).ToArray();	0
9831961	9831843	Connect with OleDbConnection	protected void login_Click(object sender, EventArgs e)\n    {\n        OleDbConnection connect = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\parodeghero\\Documents\\Visual Studio 2010\\Projects\\Project3\\Project3\\App_Data\\QA.mdb;Persist Security Info=True");\n        //set up connection string\n        OleDbCommand command = new OleDbCommand("select * from Employee where Login=@login", connect);\n        OleDbParameter param0 = new OleDbParameter("@login", OleDbType.VarChar);\n\n        param0.Value = employeeID.Text;\n        command.Parameters.Add(param0);\n\n        try\n        {\n            connect.Open();\n        }catch(Exception err){ Debug.WriteLine(err.Message);}\n\n        //middle tier to run connect\n        OleDbDataAdapter da = new OleDbDataAdapter(command);\n\n        DataSet dset = new DataSet();\n\n        da.Fill(dset);	0
14732174	14732087	How to convert smalldatetime retrieved from database back to smalldatetime to be reposted to the database	CultureInfo provider = CultureInfo.InvariantCulture;\nstring dateAsText = "12/14/2012 12:00:00 PM";\nDateTime something = DateTime.ParseExact(dateAsText, "MM/dd/yyyy hh:mm:ss tt", provider);	0
7352782	7352678	Populate a ListView with URL webservice query	private void MyThreadProc()\n{\n    // get the data from the web service here\n\n    this.Invoke(new EventHandler(delegate\n    {\n        // update your ListView here\n    }));\n}	0
3015648	3015615	How to install wiimote library in Visual C# Express Edition	Solution 'MyApplication' (1 project)\n-  MyApplication\n   + Properties\n   + References\n   + ...	0
13253473	13253384	Adding ProgressBar to DataGrid column	public class SomeVal : INotifyPropertyChanged\n{\n   public int ProgressValue{...}\n}\n\ndatagrid.ItemsSource = new [] {new SomeVal()};	0
26896744	26896615	Obtaining a token for authentication	using (HttpClient client = new HttpClient())\n{\n  var response = await client.PostAsync(url, new StringContent(credentials));\n  result = await response.Content.ReadAsStringAsync();\n}	0
18963347	18962706	camera for a hexagonal grid	for(int y = yPixelOffset / tileHeight; y < displayHeight; y++) {\n    for(int x = xPixelOffset / tileWidth; x < displayWidth; x++) {\n        // draw tile[x,y] at (displayLeft + x * tileWidth - xPixelOffset,\n        //    displayTop + y * tileHeight - yPixelOffset)\n    }\n}	0
10934060	10933949	Making a file backup program	string path = @"c:\temp\MyTest.txt";\nstring path2 = path + "temp";\n\ntry \n{\n        // Create the file and clean up handles.\n        using (FileStream fs = File.Create(path)) {}\n\n        // Ensure that the target does not exist.\n        File.Delete(path2);\n\n        // Copy the file.\n        File.Copy(path, path2);\n        Console.WriteLine("{0} copied to {1}", path, path2);\n\n        // Try to copy the same file again, which should succeed.\n        File.Copy(path, path2, true);\n        Console.WriteLine("The second Copy operation succeeded, which was expected.");\n    }	0
20228603	20226572	Clicking enter in dialog not working properly	private void textBox2_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyCode == Keys.Enter) {\n            button1.PerformClick();\n            e.Handled = e.SuppressKeyPress = true;\n        }\n    }	0
28681459	28680665	Access C# Enums and Classes from other namespaces in IronPython	import clr\nclr.AddReference("assembly_name")\nfrom EnumTest import EnumTest\nfrom EnumTest.EnumTest import FooEnum	0
18921015	18920828	Gridview presentation of date different than query in one cell	DATEADD(DAY, 0, @startDateParam)	0
11846024	11845852	ASP.NET MVC 3 Restrict access to a view based on time of year/accessible date range	public ActionResult SummerOnly()\n{\n   if (!(DateTime.Now > new DateTime(2012,8,8)))\n       return View("Error");    \n\n   return View("GoodView");\n}	0
20503257	20502481	How to know if an input is only partially complete in Roslyn's ScripEngine	Syntax.IsCompleteSubmission	0
2928382	2927850	Convert ten character classification string into four character one in C#	Dictionary<string, int>	0
22860113	22860046	Convert C# unit test to a method	public Byte[] ComputeCrc16(string input) \n{\n    var calculator = new CRC16();\n    var bytes = StringToByteArray(input);\n\n    return calculator.ComputeHash(bytes, 0, bytes.Length);\n}	0
333034	332973	Check whether an array is a subset of another	bool isSubset = !t2.Except(t1).Any();	0
12324679	12324650	How to insert new guid on sql select statement for a column	string query = @"Select Student, newid() as  Id, Name, DOB from Student where Name = Ken";	0
31972701	31972605	Get string between a known string and any non-alphanumeric character	string input = "Global.bar1>foobar";\nvar output = Regex.Match(input, @"Global.([\w]+)").Groups[1].Value;	0
3432671	3432624	WPF assembly reference missing - project still building	xmlns:d3="clr-namespace:Microsoft.Research.DynamicDataDisplay;assembly=DynamicDataDisplay"	0
14075374	14074992	How to show User name after login when not present in DB?	lblFName.Text = Session["lblFName"] != null ? Session["lblFName"].ToString();  \nlblLName.Text = Session["lblLName"] != null ? Session["lblLName"].ToString();	0
3921244	3921224	Activate tabpage of TabControl	tabControl1.SelectedTab = MyTab;	0
13377859	13377714	Is there a C# equivalent to C++ __FILE__, __LINE__ and __FUNCTION__ macros?	public void DoProcessing()\n{\n    TraceMessage("Something happened.");\n}\n\npublic void TraceMessage(string message,\n    [CallerMemberName] string memberName = "",\n    [CallerFilePath] string sourceFilePath = "",\n    [CallerLineNumber] int sourceLineNumber = 0)\n{\n    Trace.WriteLine("message: " + message);\n    Trace.WriteLine("member name: " + memberName);\n    Trace.WriteLine("source file path: " + sourceFilePath);\n    Trace.WriteLine("source line number: " + sourceLineNumber);\n}	0
17340419	17339928	C# - How To Convert Object To IntPtr And Back?	// object to IntPtr (before calling WinApi):\nList<string> list1 = new List<string>();\nGCHandle handle1 = GCHandle.Alloc(list1);\nIntPtr parameter = (IntPtr) handle1;\n// call WinAPi and pass the parameter here\n\n// back to object (in callback function):\nGCHandle handle2 = (GCHandle) parameter;\nList<string> list2 = (handle2.Target as List<string>);\nlist2.Add("hello world");	0
24585504	24584985	Jump ComboBox on Arrow key pressed	using System;\nusing System.Windows.Forms;\n\nclass MyComboBox : ComboBox {\n    protected override bool IsInputKey(Keys keyData) {\n        if ((keyData == Keys.Up) || (keyData == Keys.Down)) return false;\n        return base.IsInputKey(keyData);\n    }\n}	0
31402470	31399542	How to open a program into a XAML c# window	using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Process p = Process.Start("notepad.exe");\n        p.WaitForInputIdle(); // Allow the process to open it's window\n        SetParent(p.MainWindowHandle, this.Handle);\n    }\n\n    [DllImport("user32.dll")]\n    static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n}\n}	0
5389077	5388969	Join two tables in Linq to SQL	var query = from u in db.Users\nselect new { User = u;\nFirstName = u.UserTables.FirstName }	0
11529310	11527570	Routing optional parameters	routes.MapHttpRoute(\n    name: "Route1",\n    routeTemplate: "{controller}/{id}",\n    defaults: new { id = RouteParameter.Optional }\n);	0
21281819	21281369	Merging lists of objects using linq while showing preference over a condition in one list	var result = (from a in listA\n              join b in listB on a.Property1 equals b.Property1 into g\n              from j in g.DefaultIfEmpty()\n              select new Content() { \n                   // Favour listA's culture code\n                   CultureCode = j == null ? a.CultureCode : j.CultureCode, \n                   Property1 = a.Property1 \n              });	0
462791	462747	Explicit Element Closing Tags with System.Xml.Linq Namespace	divTag.SetValue(string.Empty);	0
9394616	9394347	Wpf create window lock	static long Locked = 0;\n\nstatic void CreateWindow(...)\n{\n   if(0 == Interlocked.Exchange(ref Locked, 1))\n   {\n      try\n      {\n         CreateWindowImpl(...);\n      }\n      finally \n      {\n         Interlocked.Exchange(ref Locked, 0);\n      }\n   }\n}	0
6049518	6033737	DataSet - Apply conditioning format of the entire column?	for(int i = 0; i< ds.Tables[0].Rows.Count; i++)\n{\n    for(int j = 0; j < ds.Tables[0].Columns.Count; j++)\n    {\n        var columnName = ds.Tables[0].Columns[j].ColumnName;\n        if(columnName == "Number")\n        {\n            ds.Tables[0].Rows[i][columnName] = SpecialFormat(columnName, ds.Tables[0].Rows[i]));\n        }\n    }\n}\n\nprivate string SpecialFormat(string column, DataRow dataRow)\n{\n    string value = dataRow[column].ToString();\n    if (!string.IsNullOrEmpty(value))\n    {\n        if (value == "0")\n            return "";\n        if (value == "1")\n            return "T";\n    }\n    return "";\n}	0
16018850	16018564	Javascript RegEx Object Double Escape Special Characters	mystring.replace(/(\\)/g, '\\\\')	0
4829048	4828850	ASP.net c# Sorting a data table	SELECT\n    <field list>\nFROM\n    <TableName>\nWHERE\n    <Clause>\nORDER BY\nCASE @OrderBy\n    WHEN 'Field1' THEN Field1\n    WHEN 'Field2' THEN Field2\n    WHEN 'Field3' THEN Field3\nEND	0
14949337	14948414	Creating a Series based on the difference of 2 other Series in MS Charts	for (int i = 0; i < dsS.Tables[0].DefaultView.Count;i++) {\n        double y = Convert.ToDouble(dsV1.Tables[0].DefaultView[i][1]) - Convert.ToDouble(dsS.Tables[0].DefaultView[i][1]);\n        double x = Convert.ToDateTime(dsV1.Tables[0].DefaultView[i][0]).ToOADate();\n        chartIndicators.Series["H"].Points.AddXY(x, y);                \n    }	0
11212988	11212853	How to design a Questionnaire framework/object model?	// pseudocode \nclass Person \n   int PersonID \n   IList Responses     \n\nclass Response\n   int ResponseID\n   int QuestionID \n   string ResponseValue \n\nclass Question\n   int QuestionID\n   string QuestionText \n   IList AllowedResponses \n   bool AllowsMultipleResponses	0
34361092	34360646	Retrieve HTML from page after given amount of time C# WPF	using (var driver = new ChromeDriver())\n{\n     driver.Navigate().GoToUrl(url);\n     var columns = driver.Divs(By.ClassName("col-md-6"));\n     // here you access the elements using driver object\n}	0
33800083	33799945	Get a black/no image with asp.net web api	var httpRequest = HttpContext.Current.Request;\n\nforeach (string file in httpRequest.Files)\n{\n    var postedFile = httpRequest.Files[file];\n    var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + postedFile.FileName);\n    postedFile.SaveAs(filePath);\n}	0
29164888	29164730	Confused about how get RegistryKey value	for (int i = 0; i < subKeys.Length; i++)	0
28824353	28824281	C#: Increment only the last number of a String	string input = "127.3.2.21.4";\nint lastIndex = input.LastIndexOf('.');\nstring lastNumber = input.Substring(lastIndex + 1);\nstring increment = (int.Parse(lastNumber) + 1).ToString();\nstring result = string.Concat(input.Substring(0, lastIndex + 1), increment);	0
206347	206323	How To: Execute command line in C#, get STD OUT results	// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = "YOURBATCHFILE.bat";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();	0
14759568	14759461	New to C#, can't find data table	Choose Items...	0
10026180	9780908	Using unity interception to solve exception handling as a crosscutting concern	public IMethodReturn Invoke(IMethodInvocation input,\n                GetNextInterceptionBehaviorDelegate getNext)\n{\n   IMethodReturn ret = getNext()(input, getNext);\n   if(ret.Exception != null)\n   {//the method you intercepted caused an exception\n    //check if it is really a method\n    if (input.MethodBase.MemberType == MemberTypes.Method)\n    {\n       MethodInfo method = (MethodInfo)input.MethodBase;\n       if (method.ReturnType == typeof(void))\n       {//you should only return null if the method you intercept returns void\n          return null;\n       }\n       //if the method is supposed to return a value type (like int) \n       //returning null causes an exception\n    }\n   }\n  return ret;\n}	0
23171644	23171184	write data from JSON in C#	class Example\n{\n    public survey[] surveys{ get; set; }//Data renames to surveys\n}\n\nclass survey //Singular\n{\n    public string title { get; set; }\n    public int id { get; set; }\n}	0
15716256	15716171	ASP.NET, C#, How to dynamically identify the properties or method of a user control and add value to them?	// will load the assembly\nAssembly myAssembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\MyClassLibrary.dll");\n\n// get the class. Always give fully qualified name.\nType ReflectionObject = myAssembly.GetType("MyClassLibrary.ReflectionClass");\n\n// create an instance of the class\nobject classObject = Activator.CreateInstance(ReflectionObject);\n\n// set the property of Age to 10. last parameter null is for index. If you want to send any value for collection type\n// then you can specify the index here. Here we are not using the collection. So we pass it as null\nReflectionObject.GetProperty("Age").SetValue(classObject, 10,null);\n\n// get the value from the property Age which we set it in our previous example\nobject age = ReflectionObject.GetProperty("Age").GetValue(classObject,null);\n\n// write the age.\nConsole.WriteLine(age.ToString());	0
16733919	16733875	Refresh div data on success method using jquery ajax	public ViewResult ShowSata(int id, string data)\n {\n       var model = GetDBData(id, data);\n       return PartialView("MyDataView")\n }	0
33477232	33477170	FileStream download pulls page HTML	Response.Clear();\nResponse.BinaryWrite(buffer);\nResponse.End();	0
30650337	30644952	How to exit full screen mode for media element in windows 8.1 store app	mediaSimple.IsFullWindow = !mediaSimple.IsFullWindow;	0
17660860	17656045	UI Automation switch window	if ( (windowplacement.flags & WPF_RESTORETOMAXIMIZED) > 0 )\n     {\n        windowPattern.SetWindowVisualState( WindowVisualState.Maximized );\n     }\n     else\n     {\n        windowPattern.SetWindowVisualState( WindowVisualState.Normal );\n     }	0
17019610	17019347	C# Find day first time and last time in a range of dates	var result = File.ReadAllLines("yourPath")\n            .Select(line => DateTime.ParseExact(line, \n                                   "yyyy-MM-dd HH:mm:ss", \n                                    CultureInfo.CurrentCulture))\n            .GroupBy(d => d.Date)\n            .SelectMany(g => new[] { g.Min(), g.Max() });	0
19806017	19805861	How to configure Debug.WriteLine output file?	Debug.Listeners.Add(new TextWriterTraceListener("c:\\temp\\test.txt"));\nDebug.AutoFlush = true;\nDebug.WriteLine("test");	0
21233271	21233164	How can i make custom cursor in (C#)	System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(Properties.Resources.Cursor1);\nCursor mCursor = new Cursor(cursorMemoryStream);\nthis.Cursor = mCursor;	0
3856151	3855591	DirectoryInfo accessing a virtual folder	var request = (HttpWebRequest)WebRequest.Create("http://servername/directoryname/");\nvar response = (HttpWebResponse)request.GetResponse();\n\nusing (var reader = new StreamReader(response.GetResponseStream()))\n{\n    string body = reader.ReadToEnd();\n}	0
26209909	26209836	Splitting one String into two?	var arr = txt.Replace("[Subject]","").Split(new string[]{"[Body]"}),\nsubject = arr[0],\nbody = arr[1];	0
4427560	4416750	Need help with binding Telerik's RADStrip dynamically	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!Page.IsPostBack)\n        {\n            DataSet ds = GetDataSet();\n\n            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n            {\n                CreateRootTab(i, ds);\n            }\n            RadTabStrip1.SelectedIndex = 0;\n        }\n    }\n\n    private void CreateRootTab(int index, DataSet ds)\n    {\n        for (int i = 0; i < ds.Tables[0].Columns.Count; i++)\n        {\n            var tab = new RadTab();\n            tab.Text = (string) ds.Tables[0].Rows[index].ItemArray[i];\n            RadTabStrip1.Tabs.Add(tab);\n        }\n    }\n\n    private DataSet GetDataSet()\n    {\n        bllQuesType objbllQuesQType = new bllQuesType();\n        var ds = new DataSet();\n        return objbllQuesType.GetQuesType();\n    }	0
11479474	11479173	Cons of using IE compatibility mode	X-UA-Compatible	0
20649388	20648753	Poplulate a specific column when a row is added to a datagridview	private void inventoryDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)\n{\n    int lastRow = inventoryDataGridView.Rows.Count - 1;\n    inventoryDataGridView.Rows[lastRow - 1].Cells[2].Value = accountNumber;\n}	0
28486643	28478995	How do I add a new GeoFence in a WP8.1 background task?	public void AddGeoFence(Geopoint gp, String name, double radius)\n{\n    // Always remove the old fence if there is any\n    var oldFence = GeofenceMonitor.Current.Geofences.Where(gf => gf.Id == name).FirstOrDefault();\n    if (oldFence != null)\n        GeofenceMonitor.Current.Geofences.Remove(oldFence);\n    Geocircle gc = new Geocircle(gp.Position, radius);\n    // Just listen for exit geofence\n    MonitoredGeofenceStates mask = 0;\n    mask |= MonitoredGeofenceStates.Exited;\n    // Construct and add the fence\n    Geofence newFence = new Geofence(new string(name.ToCharArray()), gc, mask, false, TimeSpan.FromSeconds(7), DateTimeOffset.Now, new TimeSpan(0));\n    GeofenceMonitor.Current.Geofences.Add(newFence);\n}	0
34473621	34473584	After progress bar becomes invisible, make text below take its space	progressbar.Visible = false;\nmsgLabel.Top = progressbar.Top;\nmsgLable.Left = progressbar.Left;\nmsgLabel.Visiible = true;	0
21623595	21621711	How to share single Viewmodel in two or more views?	public LinkWindow(string path, object viewModel)\n{\n    InitializeComponent();\n    this.DataContext = viewModel;    \n}	0
15001390	15001295	How to map complex one-to-many with Entity Framework and Fluent API	HasMany(x => x.Employee).WithRequired().HasForeignKey(x => x.CompanyID);\nHasMany(x => x.Janitors).WithRequired().HasForeignKey(x => x.CompanyID);\nHasMany(x => x.Students).WithRequired().HasForeignKey(x => x.CompanyID);\nHasMany(x => x.Professors).WithRequired().HasForeignKey(x => x.CompanyID);	0
9463502	9461902	How to unit test an event subscribtion with NUnit	var subscriber = new TheSubscriber();\nvar handlerField = typeof(TheSubscriber)\n    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)\n    // if field with such name is not present, let it fail test\n    .First(f => f.Name == "myHandler");\n\nvar handlerInstance = handlerField.GetValue(subscriber);\nvar someEventField = typeof(TheHandler)\n    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)\n    .First(f => f.Name == "myRealWorldEvent");\n\nvar eventInstance = (EventHandler) someEventField.GetValue(handlerInstance);\nvar subscribedMethod = eventInstance\n    .GetInvocationList()\n    .FirstOrDefault(d => d.Method.Name == "OnSomethingHappens");\n\nAssert.That(subscribedMethod, Is.Not.Null);	0
4457504	4454930	Is there a more efficient method to find dupes in Sql server	-- TSQL (SQL Server 2005/2008): --\n\nselect CompanyID from tbl_CustomerInfo\n    group by CompanyID\n    having COUNT(*)>1	0
26417786	26417724	Simulate deriving from a value type	public static class MyConstants\n{ \n  public static char Zero{get{return '0';}}\n  ....\n}	0
7796024	7795986	How to use an Expression<Func<Model, bool>> in a Linq to EF where condition?	return ctx.Customers.AsExpandable().Where(condition)	0
27895804	27895054	need help in following syntax	public static DataTable LoadGrid(string selectedItem,string yearSelected)\n{\n    DataTable tbl;\n    string query = string.Format( @" SELECT top 10 SalesOrderID, RevisionNumber, OrderDate,DueDate,ShipDate, Status,OnlineOrderFlag,SalesOrderNumber,PurchaseOrderNumber,AccountNumber, CustomerID, SalesPersonID, st.Name AS TerritoryName,BillToAddressID, ShipToAddressID,ShipMethodID, CreditCardID, CreditCardApprovalCode,CurrencyRateID, SubTotal, TaxAmt, Freight,TotalDue,Comment, soh.rowguid, soh.ModifiedDate \n                FROM Sales.SalesOrderHeader as soh \n                INNER JOIN Sales.SalesTerritory as st \n                    ON soh.TerritoryID = st.TerritoryID\n                WHERE  st.Name = '{0}' AND Datepart(year,OrderDate) = '{1}'", selectedItem, yearSelected);\n\n    tbl=DataAccess.cmd(query);\n    return (tbl);\n}	0
3723420	3718152	How to check what version of Windows Media Player is installed on the machine?	HKLM\nSoftware\Microsoft\MediaPlayer\PlayerUpgrade\nPlayerVersion	0
32491070	32490186	How persist all values in a select made from @Html.ListBoxFor in a MVC.net web page?	public IEnumerable<SelectListItem> Items \n    {\n        get\n        {            \n            if (HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"] == null)\n            {\n                return null;\n            }\n            else\n            {\n                return (IEnumerable<SelectListItem>)HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"];\n            }\n        }\n\n        set\n        {\n            if (value.Count() > 0) //http post reset value\n            {\n                HttpContext.Current.Session["MY_ITEMS_TO_LIST_FOR"] = value;\n            }\n        }\n    }	0
205258	57560	How do I check that a Windows QFE/patch has been installed from c#?	strComputer = "."\nSet objWMIService = GetObject("winmgmts:" _\n    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")\nSet colQuickFixes = objWMIService.ExecQuery _\n    ("Select * from Win32_QuickFixEngineering")\nFor Each objQuickFix in colQuickFixes\n    Wscript.Echo "Computer: " & objQuickFix.CSName\n    Wscript.Echo "Description: " & objQuickFix.Description\n    Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID\n    Wscript.Echo "Installation Date: " & objQuickFix.InstallDate\n    Wscript.Echo "Installed By: " & objQuickFix.InstalledBy\nNext	0
17034413	17034396	Downloading xml file from a url using c#	public static string DownloadString(string address) \n{\n    string text;\n    using (var client = new WebClient()) \n    {\n        text = client.DownloadString(address);\n    }\n    return text;\n}\n\nprivate static void Main(string[] args) \n{    \n    var xml = DownloadString(@"http://www.ploscompbiol.org/article/fetchObjectAttachment.action?uri=info%3Adoi%2F10.1371%2Fjournal.pcbi.1002244&representation=XML");            \n    File.WriteAllText("blah.xml", xml);\n}	0
32672543	32672426	Getting text as string from selected item in ListBox	private void phoneListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n    Thing lbi = ((sender as ListBox).SelectedItem as Thing);\n    string selected = lbi.Name.ToString();\n }	0
15383767	15383731	Passing data from one desktop/web application to another desktop app	web service	0
4099425	4099379	c# how to add strings to a list so that they will be accessible from DataSource	chart1.DataSource = myReader;\nchart1.Series["Series1"].XValueMember = "reporttime";\nchart1.Series["Series1"].YValueMembers = "datapath";\nchart1.DataBind();	0
27478806	27478713	Time elapsed between two functions	int numberOfIterations = 1000; // you decide on a reasonable threshold.\nsample.palindrome(); // Call this the first time and avoid measuring the JIT compile time\nStopwatch sw = new Stopwatch();\nsw.Start();\nfor(int i = 0 ; i < numberOfIterations ; i++)\n{\n   sample.palindrome(); // why console write?\n}\nsw.Stop();\nConsole.WriteLine(sw.ElapsedMilliseconds); // or sw.ElapsedMilliseconds/numberOfIterations	0
31874031	31873827	Messagebox does not show if there rows affected in the database C# MySQL	int numberOfrows = cmd.ExecuteNonQuery();\n       if (numberOfrows > 0)\n        {\n             //means update is sucessful\n                MessageBox.Show("Client Successfully Updated!");\n\n        } \n        btnReg.Click -= this.btnUpdt_Click;\n        btnReg.Click += this.btnReg_Click;	0
18003457	18003330	Most Elegant Way to Set ComboBox by Value	ddContact.DisplayMember = "DisplayText";\nddContact.ValueMember = "ID";\nddContact.DataSource = dt;\nddContact.Value = Convert.ToInt32(dt.Rows[0]["ID"]);	0
11420203	11419980	How do I generate LinkButton's that are created from another Link_Command event on Postback?	string test1234 = Page.Request.Params.Get("__EVENTTARGET");	0
6308094	6308038	Problem controlling the flow of an application	public MainForm()\n{\n    InitializeComponent();\n    a = new A();\n    a.ItemsFound += new A.NewItemsFoundEventHandler(a_FoundItems);\n    a.ItemsLoaded += new A.ItemsLoadedEventHandler(a_ItemsLoaded);\n    a.LoadItems();\n    a.CheckForUpdates();\n}	0
691043	691035	Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute	public DateTime DateCreated\n{\n   get\n   {\n      return this.dateCreated.HasValue\n         ? this.dateCreated.Value\n         : DateTime.Now;\n   }\n\n   set { this.dateCreated = value; }\n}\n\nprivate DateTime? dateCreated = null;	0
13831001	13830776	How to create a "data base txt" file in Windows Phone project	private void ReadTones()\n{\n  string tonesPath = "/PhoneReadFileResource;component/Data/tones.txt";\n  Uri tonesUri = new Uri(tonesPath, UriKind.Relative);\n  StreamResourceInfo sri = Application.GetResourceStream(tonesUri);\n  StreamReader rdr = new StreamReader(sri.Stream);\n  TextDisplay.Text = rdr.ReadToEnd();\n}	0
128692	128674	What is the most efficient way to save a byte array as a file on disk in C#?	File.WriteAllBytes()	0
13622315	13622109	DTO to existing object without loosing rest of existing object data	Mapper.CreateMap<DTOContact,OriginalContact>()\n  .ForMember(dest => dest.CustomerCode, options => options.Ignore());	0
28519424	28519372	How to open a file from listview control in C#	System.Diagnostics.Process.Start(Path.Combine(currentDir, selectedFile));	0
10365114	10364580	Getting treenode text after an edit	private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {\n        this.BeginInvoke(new Action(() => afterAfterEdit(e.Node)));\n    }\n    private void afterAfterEdit(TreeNode node) {\n        string txt = node.Text;   // Now it is updated\n        // etc..\n    }	0
585498	585451	Choosing the right image size in Compact Framework	mypicturebox.Image = ImageFactory.Image01;	0
21903131	21902975	Get count of longest list inside a list with LINQ	var max = attributes.Max(a => a.values.Count)	0
28876102	27676921	Using ServiceStack.OrmLite how can I add a bool column with a default value?	[Default(typeof(bool), "0")]	0
997441	982117	Is ModelState and AddModelError persistant in a Controller/Action?	container.Register(\n        AllTypes\n            .FromAssemblyNamed("Aplication")\n            .BasedOn<IController>()\n            .Configure(c => c.LifeStyle.Is(LifestyleType.Transient))\n            .WithService\n            .FirstInterface()\n        );	0
29393827	29393012	How to get object json when deserializing array	if (tokenType is JArray)\n                {\n                    var arr = JsonConvert.DeserializeObject(message) as JArray;\n                    foreach (var item in arr)\n                    {\n                        try\n                        {\n                            var agentParameter = item.ToObject<Foo>();\n                            agentParameter.JSON = item.ToString();\n                            result.Add(agentParameter);\n                        }\n                        catch (Exception)\n                        {\n                            LogProvider.Error(string.Format("Failed to Deserialize message. Message text: \r\n {0}", item.ToString()));\n                        }\n                    }\n                }	0
10760566	10759772	How to show image from URL in datagridview cell?	foreach (DataRow row in t.Rows)\n    {\n                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(row["uri"].ToString());\n                    myRequest.Method = "GET";\n                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();\n                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());\n                    myResponse.Close();\n\n                    row["Img"] = bmp;\n    }	0
18185000	18184885	Reading CSV into using OLEDB	ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+openFileDialog1.FileName +";Extended Properties=text;HDR=Yes;FMT=Delimited");	0
3319920	3319896	How to get String.Format not to parse {0}	string result = string.Format("{{Ignored}} {{123}} {0}", 543);	0
8627461	8627280	Setting source for MediaElement in windows phone 7?	this.Sound.Source = new Uri("/Sounds/fusrodah.wma", UriKind.Relative);	0
28889661	28889507	Get next available ID from array of names	string[] folderArray = { "1 - Name", "4 - Another name", "3 - Another name" };\n    var listId = new List<int>();\n    foreach (var item in folderArray)\n    {\n       var tempId = 0;\n        if (int.TryParse(item.Split('-')[0].Trim(), out tempId))\n           listId.Add(tempId);\n    }\n\n\n\n\n   listId.Sort();\n   for (var i=1 ;i<listId.Count ;i++)\n   {\n      if(listId[i]-listId[i-1]>1)\n        {\n          Console.WriteLine(listId[i-1]+1);\n          break;\n        }\n   }	0
15047945	15047874	How to find string between some characters using regex in c#	(.*?)[<([{](.*?)[>)\]}]	0
19763000	19762949	How do I remove empty cells in a string array?	return Regex.Split(lines, @"[^-'a-zA-Z]")\n                              .Where(x=>!string.IsNullOrWhiteSpace(x)).ToArray();	0
24434038	24369238	How do I find all XML elements whose value is in a list of values using LINQ	IEnumerable<XElement> MyElements = from e in GroupA.Elements("Element")\n         where GroupB.Elements("Element").Any(b => b.Value == e.Value)\n         select e;	0
24882690	24882632	Getting a Text between two texts	String SecondText = "Project Name - this is the text I want to get, Contact Name -";\n\n  // Pay attention to + + "Project Name".Length; and - Place1\n  int Place1 = SecondText.IndexOf("Project Name") + "Project Name".Length;\n  int Place2 = SecondText.IndexOf("Contact Name") - Place1;\n  Name = SecondText.Substring(Place1, Place2);	0
28417506	28416763	Using LINQ to fill the list with the latest available value	public static class ReportListExtensions\n{\n    public static Report GetReport(this IEnumerable<Report> reports, DateTime date)\n    {\n        return new Report\n        {\n            AnnouncementDate = date,\n            ValueAnnounced = reports.OrderByDescending(r => r.AnnouncementDate)\n                                    .First(r => r.AnnouncementDate < date)\n                                    .ValueAnnounced\n        };\n    }\n}	0
18661093	18660793	Secure WCF via X.509 certificate with BinarySecurityToken	[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.SimpleServiceSoap", ProtectionLevel=System.Net.Security.ProtectionLevel.Sign)]	0
19424692	19424625	how to pass stored procedure value into a webform?	using (SqlConnection con = new SqlConnection(ConnectionString)) {\n    con.Open();\n    using (SqlCommand command = new SqlCommand("ProcedureName", con)) {\n        command.CommandType = CommandType.StoredProcedure;\n        using(SqlReader reader = command.ExecuteReader()){\n            if (reader.HasRows) {\n                 while(reader.Read()) {\n                     ... process SqlReader objects...\n                 }\n            }\n        }\n    }\n}	0
1400911	1400806	Ordinal Position of Element in IENumerable Collection (Linq to XMl )	var AllSections = from s in xmlDoc.Descendants("section")\n    select new\n    {\n        id = s.Attribute("id").Value,\n        themeTitle = s.Element("themeTitle").Value,\n        themeText = s.Element("themeText").Value,\n        objects = (from a in AllObjects \n                   join b in s.Descendants("object")\n                       on a.Attribute("accessionNumber").Value\n                       equals b.Attribute("accessionNumber").Value\n                   select a).Select((a, index) =>\n                       new\n                       {\n                           Index = index,\n                           ObjectTitle = a.Element("ObjectTitle").Value,\n                           ObjectText = a.Element("textentry").Value,\n                       })\n    };	0
21039352	20989491	Control Template Xaml	public MainMenuPage()\n    {\n        InitializeComponent();\n        BaseTemplateHelper = new GPBaseTemplateHelper();\n\n        if (BaseTemplateHelper != null)\n        {\n            this.DataContext = BaseTemplateHelper;\n        }\n    }	0
6423348	6423245	how to get property of entity of entity by name	/// <summary>\n    /// Gets an object property's value, recursively traversing it's properties if needed.\n    /// </summary>\n    /// <param name="FrameObject">The object.</param>\n    /// <param name="PropertyString">The object property string.\n    /// Can be the property of a property. e.g. Position.X</param>\n    /// <returns>The value of this object's property.</returns>\n    private object GetObjectPropertyValue(Object FrameObject, string PropertyString)\n    {\n        object Result = FrameObject;\n\n        string[] Properties = PropertyString.Split('.');\n\n        foreach (var Property in Properties)\n        {\n            Result = Result.GetType().GetProperty(Property).GetValue(Result, null);\n        }\n\n        return Result;\n    }	0
29959002	29958799	How can I create a dynamic ListView columns for MySQL searches?	DataTable dt = new DataTable();\nusing (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))\n {\n    SqlCommand cmd = new SqlCommand("SELECT `entry`, `name` FROM `accounts` WHERE `name` LIKE %@name%", con);\n    cmd.Parameters.AddWithValue("@name", "somename");\n    SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);\n    dAdapter.Fill(dt);\n }\nforeach (DataColumn dc in dt.Columns)\n {\n    listView1.Columns.Add(dc.ColumnName, 50, HorizontalAlignment.Left);\n\n }	0
24610388	24610224	simple calculator in C# like this 6+4	var result = 0;\nif (sign == "+")\n{\n    result = num1 + num2;\n}\nelse if (sign == "-")\n{\n    result = num1 - num2;\n}\nelse if (sign == "*")\n{\n    result = num1 * num2;\n}\nelse if (sign == "/")\n{\n    result = num1 / num2;\n}\nelse\n{\n    Console.WriteLine("Wrong operation sign ...");\n}\n\nConsole.WriteLine("{0}{1}{2}={3}", num1, sign, num2, result);  \n\nConsole.ReadLine();	0
4123648	4123590	Serialize an object to XML	XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));\n var subReq = new MyObject();\n using(StringWriter sww = new StringWriter())\n using(XmlWriter writer = XmlWriter.Create(sww))\n {\n     xsSubmit.Serialize(writer, subReq);\n     var xml = sww.ToString(); // Your XML\n }	0
15073342	15073294	User control's children properties in the Properties window	// your grid control instantiated somewhere:\nDataGridVIew myInnerDataGridVIew = new ...\n\npublic DataGridVIew MyInnerDataGridVIew \n{ \n  get { return myInnerDataGridVIew; } \n  set { myInnerDataGridVIew = value; } \n}	0
3809649	3809520	A class definition for a date class that contains three integer data members:month,day,year	public class WeirdRequirements\n{\n    int m_year, m_month, m_day;\n    public delegate void MessagePrinter(string message);\n    public MessagePrinter PrintMessage = Console.WriteLine;\n\n    public WeirdRequirements()\n    {\n        m_year = 2000;\n        m_month = 1;\n        m_day = 1;\n        PrintMessage("default");\n    }\n\n    public WeirdRequirements(int Month, int Day)\n    {\n        m_year = 2004;\n        m_month = Month;\n        m_day = Day;\n        PrintMessage("int Month, int Day");\n    }\n\n    public WeirdRequirements(int Year, int Month, int Day)\n    {\n        m_year = Year;\n        m_month = Month;\n        m_day = Day;\n        PrintMessage("int Year, int Month, int Day");\n    }\n\n    public void PrintValues()\n    {\n        PrintMessage(string.Format("Year={0} Month={1} Day={2}", m_year, m_month, m_day));\n    }\n}	0
4276009	4275935	LINQ: Paging tecnique, using take and skip but need total records also - how to implement this?	var query = from e in db.Entities where etc etc etc;\n\nvar pagedQuery = \n    from e in query.Skip(pageSize * pageNumber).Take(pageSize)\n    select new\n    {\n        Count = query.Count(),\n        Entity = e\n    };	0
10514620	10513664	How to deploy a database programatically with C#	ExecuteNonQuery(...)	0
21983035	21982864	Dynamic connection strings based on Production/Debug flag	namespace MyApp\n{\n    class DatabaseInterface\n    {\n        public static string getConnectionString()\n        {\n            return myFlag ? "Data Source=server;Initial Catalog=db" : "AnotherString";\n        }\n    }  \n }	0
29478701	29474820	Negative eulerAngles in Unity	if (steerAngle > 180)\n    steerAngle -= 360;	0
32497046	32453373	Condition to get specific cell value in ultragrid	foreach (UltraGridRow row in grdOtherItemsInfo.Rows)\n        {\n            foreach (UltraGridRow urow in grdChemicalItemInfo.Rows[row.Index].ChildBands[0].Rows)\n            {\n                if (Convert.ToBoolean(urow.Cells[OtherItemStoreRequisitionForBatchChild.IsAutoDispense].Value))\n                {\n                    foreach (UltraGridCell col in urow.Cells)\n                    {\n                        col.Activation = Activation.ActivateOnly;\n                    }\n                }\n            }\n        }	0
3935567	3935524	How could I encode a string of 1s and 0s for transport?	byte[] convertToBytes(string s)\n{\n    byte[] result = new byte[(s.Length + 7) / 8];\n\n    int i = 0;\n    int j = 0;\n    foreach (char c in s)\n    {\n        result[i] <<= 1;\n        if (c == '1')\n            result[i] |= 1;\n        j++;\n        if (j == 8)\n        {\n            i++;\n            j = 0;\n        }\n    }\n    return result;\n}	0
15123168	15122926	ThreadStateException when printing from WebBrowser	fsw.SynchronizingObject = this;	0
27117987	27117883	Selecting Attributes from XML	root.SelectSingleNode("/root/movie/@title").Value	0
23669705	23669464	How to get database values to gridview in c#?	status.MobNo = Convert.ToString(dsstatuses.Tables[0].Rows[i]["MobNo"]);\n      status.PhoneNo = Convert.ToString(dsstatuses.Tables[0].Rows[i]["PhoneNo"]);\n      status.IsActive = Convert.ToBoolean(dsstatuses.Tables[0].Rows[i]["IsActive"]);\n\n      Branchmaster.Add(status);\n   }\n   return Branchmaster;\n\n}	0
7669896	7647941	Retriving SPListItem through External List's whose Source is from SQL Server 08 Stored Procedure	const string entityName = "Name of internal name of the entity";\nconst string systemName = "name of the external system";\nconst string nameSpace = "name space of ect";\n\nBdcService bdcservice = SPFarm.Local.Services.GetValue<BdcService>();\nIMetadataCatalog catalog = bdcservice.GetDatabaseBackedMetadataCatalog(SPServiceContext.Current);\nILobSystemInstance lobSystemInstance = catalog.GetLobSystem(systemName).GetLobSystemInstances()[systemName];\nIEntity entity = catalog.GetEntity(nameSpace, entityName);\nIFilterCollection filters = entity.GetDefaultFinderFilters();\nComparisonFilter filter= (ComparisonFilter)filters[0];\nIEntityInstanceEnumerator enumerator = entity.FindFiltered(filters, lobSystemInstance);\ndisplayTable = entity.Catalog.Helper.CreateDataTable(enumerator);	0
33478765	33477875	How to start using MailKit library?	Assemblies->Extensions	0
7217600	7217215	Smooth multiplayer movement	protected override void Update(GameTime gameTime)\n{\n    Vector2 sMove = new Vector2(Position.X - DrawPosition.X, Position.Y - DrawPosition.Y);\n    sMove.Normalize();\n    // START CHANGE\n    sMove = Vector2.Multiply(sMove, Math.Min(Vector2.Distance(DrawPosition, Position), Speed * gameTime.ElapsedGameTime.TotalSeconds));\n    // END CHANGE\n    DrawPosition.X += sMove.X;\n    DrawPosition.Y += sMove.Y;\n}	0
10443005	10442975	find count of elements contains in both collections	coll1.Intersect(coll2 ).Count()	0
6617071	6617046	Monitor a file for changes	FileInfo.Length	0
18592614	18592406	data not coming from ItemsSource	public string[] EventsList\n{\n    get\n    {\n        string[] values = {"event1", "event2"};\n        return values;\n    }\n}	0
32248147	32221846	How to make sure that button has been clicked?	Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, AutomationElement yourAE,TreeScope.Element, new AutomationEventHandler(OnStartInvoke));\n\nprivate static void OnStartInvoke(object src, AutomationEventArgs e)\n{\n    //logic\n}	0
24999168	24999094	Windows Phone Screen Rotation Problems	DisplayInformation.AutoRotationPreferences	0
12522926	12522896	How to replace a word in a string	using System.Text.RegularExpressions;\n\nRegex re = new Regex("\band\b", RegexOptions.IgnoreCase);\n\nstring and = "This is my input string with and string in between.";\n\nre.Replace(and, ",");	0
24924158	24914165	Cyclic dependency via property injection in Castle Windsor	container.Register(Component.For<ILazyComponentLoader>()\n                            .ImplementedBy<LazyOfTComponentLoader>());\n\npublic class CompositeModule : ICompositeModule\n{\n    private IEnumerable<IModule> _childModules;\n    public CompositeModule(IEnumerable<IModule> childModules) \n    {\n        _childModules = childModules;\n    }\n}\n\npublic class CheckChildrenModule : IModule\n{\n    private Lazy<ICompositeModule> _compositeModule;\n    public CheckChildrenModule(Lazy<ICompositeModule> compositeModule)\n    {\n        _compositeModule = compositeModule;\n    }\n\n    public void DoStuff() \n    {\n        _compositeModule.Value.DoStuff();\n    }\n}	0
14512868	14512712	Can you store the whole page instead of the state in Metro Winstore app?	this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;	0
18212750	18212350	Showing Dialog After Long Process	this._backgroundWorker.RunWorkerCompleted +=\n                          new RunWorkerCompletedEventHandler(bw_WorkComplete);\n\n  ....\n\nvoid bw_DoWork(object sender, DoWorkEventArgs e)\n{\n    BackgroundWorker _worker = sender as BackgroundWorker;\n    if (_worker != null)\n    {\n        FileInfo existingFile = new FileInfo("C:\\MyExcelFile.xlsx");\n        ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile, _worker);\n\n        e.Result = new JavaScriptSerializer().Serialize(data);\n     }\n }\n\n private void bw_WorkComplete(object sender, RunWorkerCompletedEventArgs e)\n {\n    SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";\n    saveFileDialog1.ShowDialog();\n\n    if (saveFileDialog1.FileName != "")\n    {\n       string json = e.Result.ToString();\n       File.WriteAllText(saveFileDialog1.FileName, json);\n    }\n}	0
17148048	17144876	TypeInitializationException when accessing App.Config connection string	var connectionString = ConfigurationManager.ConnectionStrings["vistConnectionString"].ConnectionString;\nSqlConnection con = new SqlConnection(connectionString);\ntry { con.Open(); }	0
20364549	20364523	For loop with if(array[i + 1]) goes out of array bounds; how to loop to beginning?	for (int i = 0; i < array.Length; i++)\n{\n    if ((i + 1 < array.Length && array[i + 1] != 0) || (i + 1 == array.Length && array[0] != 0))\n        // Do something (obviously in this example, this will always occur)\n    {\n}	0
24189445	24189122	how to show two seperate random items from 2 listbox into a messagebox?	Random random = new Random();\nint randomNumber = random.Next(1, listboxname.Items.Count);\nlistboxname.Select();\nlistboxname.SelectedItem = listboxname.Items[randomNumber];\n\n\nint randomnumwhat = random.Next(1, listBoxwhat.Items.Count);\nlistBoxwhat.Select();\nlistBoxwhat.SelectedItem = listBoxwhat.Items[randomnumwhat];\n\nMessageBox.Show(listboxname.SelectedItem.ToString() + (" ") +(listBoxwhat.SelectedItem.ToString()));	0
17576759	17576427	Windows phone - C# - Retrieving contact email	EmailAddressChooserTask eact = new EmailAddressChooserTask();\neact.Completed += eact_Completed;\neact.Show();\n\nvoid eact_Completed(object sender, EmailResult e)\n{\n    if (e.TaskResult == TaskResult.OK)\n    { \n       string selectedEmail = e.Email;\n    }\n    else\n    {\n       //nothing chosen\n    }      \n}	0
9834674	9834575	How to create indefinite Background Threads in a loop in C#.NET	Task.Factory.StartNew()	0
11225930	11225814	OnClick event with HTML table	var tablecell = document.getElementsByTagName("TD"):\n\nfor( index = 0; index < tablecell.length ; index++)\n{\n  tablecell[i].onclick = function(){\n  window.open( 'newpage.aspx');\n  };\n}	0
32734699	29996742	How can I save my Sharepoint list value as currency/decimal?	spli["Section5Total"] = Convert.ToDecimal(boxSection5Total.Text);	0
34213175	34210451	Dynamic IoC controller resolving ASP.NET 5	public void ConfigureServices(IServiceCollection services)\n{\n    HomeController controller;\n\n    var controllerFactory = Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(typeof(HomeController), Type.EmptyTypes);\n    controller = (HomeController)controllerFactory(services.BuildServiceProvider(), null);\n}	0
22507644	22507361	asp:gridview dynamically created columns	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack)\n    {\n        LoadData(); //if you did this without checking IsPostBack, you'd rebind the GridView and lose the existing rows\n    }\n\nprotected void LoadData()\n{\n    //bind GridView etc\n}	0
3997051	3996999	SQL Query: For each value, determine the percentage of rows that contain the value?	SELECT\n    NoteCount,\n    COUNT(*) ContactsWithThisNoteCount,\n    COUNT(*) / (SELECT COUNT(*) FROM Contacts) PercentageContactsWithThisNoteCount\nFROM \n    Contacts\nGROUP BY\n    NoteCount	0
5769005	5768948	Extract variables from string math expression	done = false;\nstate = start;\nwhile(!done)\n{\n    switch(state)\n    {\n    case start:\n        if(expression[i] > 'a' && expression[i] < 'z')\n            state = start;\n        else if(expression[i] == '+')\n        {\n            // seen first operand and waitng for second\n            // so we switch state\n            state = add;\n        }\n        break;\n    case add:\n        if(expression[i] > 'a' && expression[i] < 'z')\n            state = add;\n        else\n            done = true;\n        break;\n    }\n}	0
10950330	10949865	How to use RestSharp's default XmlDeserializer for elements with attributes	request.RootElement = "root";	0
10323488	10323461	Substring go to End of String	EndVariable.Substring(15)	0
23928869	23928789	How can I define a method on an already initialized object?	class Square\n{\n  public Calc Calc { get; private set;\n  ...\n  public Square()\n  {\n     this.Calc = new Calc();\n  }\n}	0
3048647	3048324	Adding a query string to a hyperlink in a asp.net data grid (c#)	HyperLink link = (HyperLink)e.Row.Cells[5].Controls[0];\n                link.NavigateUrl = "~/viewDocuments.aspx?id=" + current.ID;	0
1892767	1892762	Remove HTML tags from string saved in database - ASP.NET	ltrDesc.Text = Value from database\n\n<div style="width:100px; height:100px; overflow:scroll">\n    <asp:Literal ID="ltrDesc" runat="server" />\n</div>	0
8318327	8318279	Creating Dynamic Tables in ASP.NET via button onclick event	List<securityApps> AppsListVS{\n get\n { \n    if(ViewState["AppListVS"] == null\n       this.AppListVS = new List(securityApps)();\n     return (List<securityApps>)ViewState["AppListVS"];\n }\n set\n {\n      ViewState["AppListVS"] = value;\n }\n}	0
11507176	11487770	ANTLR: Can I have ',' be one token on one context, and another outside of said context?	L_CURLY : '{' {setComma();};\nR_CURLY : '}' {clearComma();};\nCOMMA : {isComma}? => ',';	0
5917960	5917866	How do I write regex to break a HTML string into pieces?	string input = @"This is sample <p id=""short""> the value of short </p> <p id=""medium""> the value of medium </p> <p id=""large""> the value of large</p>";\n\n\nstring before = input.Substring(0, input.IndexOf("<"));\nstring xmlWrapper = "<html>" + input.Substring(input.IndexOf("<")) + "</html>";\nXElement xElement = XElement.Parse(xmlWrapper);\n\nvar shortElement =\n    xElement.Elements().Where(p => p.Name == "p" && p.Attribute("id").Value == "short").SingleOrDefault();\nvar shortValue = shortElement != null ? shortElement.Value : string.Empty;\n\nvar mediumElement =\n    xElement.Elements().Where(p => p.Name == "p" && p.Attribute("id").Value == "medium").SingleOrDefault();\nvar mediumValue = shortElement != null ? shortElement.Value : string.Empty;\n\nvar largelement =\n    xElement.Elements().Where(p => p.Name == "p" && p.Attribute("id").Value == "large").SingleOrDefault();\nvar largeValue = shortElement != null ? shortElement.Value : string.Empty;	0
24931827	24930762	Mangled name even after extern c	extern "C"	0
20376527	20243757	Create the same hash in PHP as OracleMembershipProvider	public string EncodePassword(string pass, string salt)\n        {\n            byte[] bytes = Encoding.Unicode.GetBytes(pass);\n            //byte[] src = Encoding.Unicode.GetBytes(salt); Corrected 5/15/2013\n            byte[] src = Convert.FromBase64String(salt);\n            byte[] dst = new byte[src.Length + bytes.Length];\n            Buffer.BlockCopy(src, 0, dst, 0, src.Length);\n            Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);\n            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");\n            byte[] inArray = algorithm.ComputeHash(dst);\n            return Convert.ToBase64String(inArray);\n        }	0
241885	241789	Parse DateTime with time zone of form PST/CEST/UTC/etc	DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);\nDateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);\nDateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);	0
5961444	5961299	Set DNS to 'Obtain automatically' programmatically	ManagementClass mClass = new ManagementClass("Win32_NetworkAdapterConfiguration");\nManagementObjectCollection mObjCol = mClass.GetInstances();\nforeach (ManagementObject mObj in mObjCol)\n{\n  if ((bool)mObj["IPEnabled"])\n  {\n     ManagementBaseObject mboDNS = mObj.GetMethodParameters("SetDNSServerSearchOrder");\n     if (mboDNS != null)\n     {\n        mboDNS["DNSServerSearchOrder"] = null;\n        mObj.InvokeMethod("SetDNSServerSearchOrder", mboDNS, null);\n     }\n  }\n}	0
31065491	31065405	C# PrintDocument prints all the text in one messy pile	20, 100	0
25591710	25591643	Creating a variable to fit all class type	interface ICanDoSomething {\n    void DoSomething();\n}\n\nclass A : ICanDoSomething {\n    void DoSomething(){\n        //some code\n    }\n}\n\nclass B : ICanDoSomething{\n    void DoSomething(){\n        //some code\n    }\n}\n\nclass Controller {\n    public ICanDoSomething theObject;\n    public void DoSomething(){\n        theObject.DoSomething();\n    }\n}\n\n....	0
28238058	28237908	Updating a list using Linq	var query = from quest in myList\n            join oldquest in _ryderQuestions\n            on new { quest.QuestionID, quest.ShowOn, quest.QuestionOrder }\n        equals new { oldquest.QuestionID, oldquest.ShowOn, oldquest.QuestionOrder }\n            select new {oldquest, quest};\n\nforeach(var item in query}\n    item.oldquest.SelectedOption = item.quest.SelectedOption	0
14449757	14449699	Is it bad practise to use Type as a 'Property'?	public enum FruitKind { Apple, Orange }\npublic abstract class Fruit\n{\n  private Fruit(FruitKind kind)\n  {\n      this.Kind = kind;\n  }\n  public FruitKind Kind { get; protected set; }\n  private class Apple : Fruit\n  {\n      public Apple() : base(FruitKind.Apple) {}\n  }\n  public static Fruit MakeApple() { return new Apple(); }\n  // similarly for orange\n}	0
7880559	7879005	Setting call with an index	int i = random.Next(1, 301);\n        string newstring = MySolution.Properties.Settings.Default["settingname" + i].ToString();	0
825538	825237	How can you find a user in active directory from C#?	searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", yourSearchTerm)	0
4521479	4521431	2 dimensional array	public class Seat\n{\n    public string ID { get; set; }\n    public bool Occupied { get; set; }\n}\n\nint rows = 10, cols = 10;\nSeat[,] seats = new Seat[rows,cols];\n\nfor (int i = 0; i < rows; ++i )\n{\n    for (int j = 0; j < cols; ++j)\n    {\n         seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };\n    }\n}\n\nforeach (var seat in seats)\n{\n    Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );\n}	0
1133240	1015571	Public getter, protected setter with CodeDOM	ToSerializableType()	0
1509584	1509564	How to properly store state in a C# .Net application	public void ChangeAppSettings(string applicationSettingsName, string newValue)\n{\n    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\n    KeyValueConfigurationElement element = config.AppSettings.Settings[applicationSettingsName];\n\n    if (element != null)\n    {\n        element.Value = newValue;\n    }\n    else\n    {\n        config.AppSettings.Settings.Add(applicationSettingsName, newValue);\n    }\n\n    config.Save(ConfigurationSaveMode.Modified, true);\n\n    ConfigurationManager.RefreshSection("appSettings");\n}	0
11825406	11825217	Color Excel header	Worksheet.Range["A1","G1"].Interior.Color = Excel.XlRgbColor.rgbDarkBlue;\nWorksheet.Range["A1","G1"].Font.Color = Excel.XlRgbColor.rgbWhite;\n// where "A1" to "G1" is your header range	0
3378119	3378010	How to invoke (non virtually) the original implementation of a virtual method?	var x = new C();\n        var m = typeof (A).GetMethod("M");\n        var dm = new DynamicMethod("proxy",  typeof (void), new [] {typeof(C)}, typeof (C));\n        var il = dm.GetILGenerator();\n        il.Emit(OpCodes.Ldarg_0);\n        il.Emit(OpCodes.Call, m);\n        il.Emit(OpCodes.Ret);\n        var action = (Action<C>)dm.CreateDelegate(typeof (Action<C>));\n        action(x);	0
6851527	6830712	IEnumerable from QueryHistory takes around 10 seconds to move to the first ChangeSet	histEnumerable.ToObservable(Scheduler.TaskPool).Subscribe(a => DoSomething(a));	0
12000579	11579225	Converting from VB6 to C# over MSCOMM to serialport	Byte[] _bytesToSend = new Byte[7];\n_bytesToSend[0] = 170;\n_bytesToSend[1] = 2;\nserialPort1.Open();\nserialPort1.Write(_bytesToSend, 0, _bytesToSend.Length);\nserialPort1.Close();	0
20475860	20475245	Progress bar withing a foreach loop	public void PlayAll()\n    {\n        pb.Maximum = Convert.ToInt32(ListSize());  //Total lenght of the full song.\n        pb.Step = 1;\n        int i = 1;\n        foreach (MusicNote m in list)\n        {\n            m.sp.Stop();\n            m.sp.Play();\n            Thread.Sleep(m.NoteDuration * 100);\n            pb.Value = i++;\n        }\n    }	0
2600732	2600500	c# linq to xml to list	var ID2 = (from sportpage in xDoc.Descendants("SportPages").Descendants("SportPage")\n           where sportpage.Attribute("type").Value == "Karate"\n           select sportpage)\n          .Descendants("LinkPage")\n          .Descendants("IDList")\n          .Elements("string")\n          .Select(d => d.Value)\n          .ToList();	0
1800560	1800554	Chopping Doubles in C#	Math.Truncate	0
4172831	4172794	How to insert in two related tables within the same context( how to retrieve the identity value before SaveChanges )?	detail.Header = header;	0
21082548	21082457	How can I nest my for loop to go back and forward in a tab control page in C#.net	if (tabControl1.SelectedIndex < tabControl1.TabCount)\n        tabControl1.SelectedIndex++;	0
28282393	27819954	In structuremap, how do I scan assemblies and add all registrations as singletons?	using StructureMap.TypeRules	0
5796063	5795577	A way to parse .NET enum string or int value attributed with 'Flags'	static bool IsFlagDefined(Enum e)\n{\n    decimal d;\n    return !decimal.TryParse(e.ToString(), out d);\n}	0
3125884	3125864	Adding rows to dataset	DataSet ds = new DataSet();\n\n DataTable dt = new DataTable("MyTable");\n dt.Columns.Add(new DataColumn("id",typeof(int)));\n dt.Columns.Add(new DataColumn("name", typeof(string)));\n\n DataRow dr = dt.NewRow();\n dr["id"] = 123;\n dr["name"] = "John";\n dt.Rows.Add(dr);\n ds.Tables.Add(dt);	0
23136392	23136326	Caching information with timeout	System.Runtime.Caching	0
24231675	24231264	code to cancel installation procedure in Windows Form Application	using System.Diagnostics;\n\nProcess[] ProcessList = Process.GetProcessesByName("Your Setup FileName");\nforeach (Process process in ProcessList)\n{\n    process.Kill();\n}	0
34474994	34474883	How to print this dictionary?	//example\nusing System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        var dic = new Dictionary<string, Dictionary<string,HashSet<string>>>\n        {\n            {"k", new Dictionary<string,HashSet<string>>\n                {\n                    {"k1", new HashSet<string>{"a","b","c"}}\n                }\n            },\n            {"k3", new Dictionary<string,HashSet<string>>\n                {\n                    {"k4", new HashSet<string>{"1","2","3"}}\n                }\n            }\n\n        };\n\n        foreach(var p in dic)\n        {\n            Console.Write(p.Key + " -- ");\n            foreach(var p1 in p.Value)\n            {\n                Console.Write(p1.Key + " -- ");\n                foreach(var str in p1.Value)\n                {\n                    Console.Write(str + " ");\n                }\n            }\n            Console.WriteLine();\n        }\n    } \n}\noutput: k -- k1 -- a b c\n        k3 -- k4 -- 1 2 3	0
14967548	14967457	How to extract custom header value in Web API message handler?	IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");\nvar id = headerValues.FirstOrDefault();	0
2749152	2749133	Storing the records in csv file from datatable	// we'll use these to check for rows with nulls\nvar columns = yourTable.Columns\n    .Cast<DataColumn>();\n\n// say the column you want to sort by is called "Date"\nvar rows = yourTable.Select("", "Date ASC"); // or "Date DESC"\n\nusing (var writer = new StreamWriter(yourPath)) {\n    for (int i = 0; i < rows.Length; i++) {\n        DataRow row = rows[i];\n\n        // check for any null cells\n        if (columns.Any(column => row.IsNull(column)))\n            continue;\n\n        string[] textCells = row.ItemArray\n            .Select(cell => cell.ToString()) // may need to pick a text qualifier here\n            .ToArray();\n\n        // check for non-null but EMPTY cells\n        if (textCells.Any(text => string.IsNullOrEmpty(text)))\n            continue;\n\n        writer.WriteLine(string.Join(",", textCells));\n    }\n}	0
1904179	1904137	Adding a blank selection item to the list in drop down list	ddlMylist.Items.Insert(0, new ListItem([key], [text]));\nddlMylist.SelectedIndex = 0;	0
21676712	21676200	How should I pass multiple DateTime parameters to an ApiController method?	config.Routes.MapHttpRoute(\n    name: "ActionWithStartAndEnd",\n    routeTemplate: "api/{controller}/{action}/{start}/{end}"\n);	0
15828475	15758645	Howto programmatically get the default template on Openoffice writer	private XComponentContext oStrap = uno.util.Bootstrap.bootstrap();    \nXMultiServiceFactory oServMan = (XMultiServiceFactory) oStrap.getServiceManager();\nXComponentLoader oDesk = (XComponentLoader) oServMan.createInstance("com.sun.star.frame.Desktop");\nstring url = @"private:factory/swriter";\nPropertyValue[] propVals = new PropertyValue[0];\nXComponent oDoc = oDesk.loadComponentFromURL(url, "_null", 0, propVals);\nvar DefaultTemplate = ((XDocumentPropertiesSupplier)oDoc).getDocumentProperties().TemplateURL;	0
23782970	23782901	Add grid in listview	lv.Items.Add(e1);	0
12809429	12809380	Parse XML with C#	XNamespace xns = "http://www.arin.net/whoisrws/core/v1"; //The default xmlns from the root element.\n\nvar orgRefHandle =\n  XDocument.Parse(xml)\n  .Root\n  .Element(xns + "net")\n  .Element(xns + "orgRef")\n  .Attribute("handle").Value;	0
13270624	13269691	How to change datagridview column width after binding datasource?	dgvShowRecords.AutoResizeColumns();	0
19374372	19374275	WinForms controls out of size on bigger screens	" Automatic Scaling in Windows Forms "	0
21678090	21677996	How to do this in c#?	var controlList = new List<Control>{ Control1, Control2, Control3 /*etc*/};\n\n\nvar count = myList.Count;\nfor (var i = 0; i < controlList.Count; i++) {\n  controlList[i].Visible = count > i;\n}	0
32981343	32979002	How can I disable a single ReSharper "Parameter Can Be of Type" suggestion?	// ReSharper disable once SuggestBaseTypeForParameter	0
17407597	17407502	Object oriented design issues - abstract, derived/implementing types - a use case scenario	abstract class Base {\n    public Base(object o) { }\n    public abstract void M();\n}\n\nclass Derived : Base { \n   public Derived(object o) : base(o) { }\n   public override void M() { } \n}	0
30405763	30405119	Add watermark below image but within print area in C#	y=-size.Height + e.MarginBounds.Bottom; \nx = e.MarginBounds.Left; \ne.Graphics.DrawImage(Image, e.MarginBounds); \n\n// note the change.  Using e.graphics instead of gpr below\ne.Graphics.DrawString(watermark, font, brush, printArea);	0
6858899	6852970	Sharepoint SPListItem retrieve column index by name	public static class SPListItemExtension\n{\n    public static int getIndexByName(this SPListItem item, string name)\n    {\n        for (int i = 0; i < item.Fields.Count; i++)\n        {\n            if (item.Fields[i].InternalName.Equals(name))\n            {\n                return i;\n            }\n\n        }\n        return -1;\n    }\n\n}	0
460984	441109	Get DateTime For Another Time Zone Regardless of Local Time Zone	int bias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 0);\nint daylightBias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 8);	0
19656457	19615604	How do I send parameters to Stimulsoft?	public virtual ActionResult GetReportSnapshot()\n        {\n         var data = (ComparativeBalanceReportDS) TempData["ComparativeSession"];       \n          StiReport report = new StiReport();\n         report.Dictionary.DataStore.Clear();\n         report.Load(Server.MapPath("~/Content/StimulReports/SampleReport.mrt"));\n         report["@enterpriseId"] = data.EnterpriseId;\n         report["@toDocumentNumber"] = data.NumberFilter.FromDocumentDocumentNumber;\n         report["@fromDocumentNumber"] = data.NumberFilter.ToDocumentDocumentNumber;\n         report["@fromDate"] = data.DateFilter.FromDocumentDate.Value;\n         report["@toDate"] = data.DateFilter.ToDocumentDate.Value;\n         return StiMvcViewer.GetReportSnapshotResult(HttpContext, report);\n\n        }	0
7042462	7041824	Retrieve MSAccess database column description	string columnName = "myColumnName"\n\nADOX.Catalog cat = new ADOX.CatalogClass();\nADODB.Connection conn = new ADODB.Connection();\nconn.Open(ConnectionString, null, null, 0);\ncat.ActiveConnection = conn;\nADOX.Table mhs = cat.Tables["myTableName"];\n\ncolumnDescription = mhs.Columns[columnName].Properties["Description"].Value.ToString();\n\nconn.Close();	0
19393898	19393735	Compare DateTime by Javascript, Jquery	function isPast(date) {\n  return new Date() > date;\n}	0
923445	921308	How can I generate a temporary Zip file, then auto-remove it after it is downloaded?	Response.Flush();\nResponse.Close();\nif(File.Exist(tempFile))\n{File.Delete(tempFile)};	0
17144348	17144198	Linq filter a list of objects based on another list	AllThings.Where(thing => thing.Countries.Intersect(interestingCountries).Count() == interestingCountries.Count);	0
2822475	2821851	Is this ok in a DI world?	public interface IRepository<T>{\n    void Insert(T item);\n }\n\n public class AuctionItem : IRepository<IAuctionItem> {\n\n   public void Insert(IAuctionItem item) {\n      _dataStore.DataContext.AuctionItems.InsertOnSubmit((AuctionItem)item);\n      _dataStore.DataContext.SubmitChanges();\n   }\n\n }	0
3441713	3441338	How do I hash first N bytes of a file?	var sha1 = SHA1Managed.Create();\n\nFileStream fs = \\whatever\nusing (var cs = new CryptoStream(fs, sha1, CryptoStreamMode.Read))\n{\n    byte[] buf = new byte[16];\n    int bytesRead = cs.Read(buf, 0, buf.Length);\n    long totalBytesRead = bytesRead;\n\n    while (bytesRead > 0 && totalBytesRead <= maxBytesToHash)\n    {\n        bytesRead = cs.Read(buf, 0, buf.Length);\n        totalBytesRead += bytesRead;\n    }\n}\n\nbyte[] hash = sha1.Hash;	0
3873483	3873281	How to convert string to local Date Time?	var zones = TimeZoneInfo.GetSystemTimeZones();    // retrieve timezone info\nstring value = "09/20/2010 14:30";\n\nDateTime CompletedDttm = DateTime.ParseExact(value, "MM/dd/yyyy HH:mm",    \n    new CultureInfo("en-US"));\nDateTime FinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, \n    TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), \n    TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"));\nstring output = FinalDttm.ToString(new CultureInfo("en-GB"));\n\nFinalDttm = TimeZoneInfo.ConvertTime(CompletedDttm, TimeZoneInfo.Local, \n    TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"));\noutput = FinalDttm.ToString(new CultureInfo("de-DE"));	0
29572689	29572419	How to prompt the "Choose a default program" in code?	string FilePath = "C:\\Text.txt";//Your File Path\nSystem.Diagnostics.Process proc = new System.Diagnostics.Process();\nproc.EnableRaisingEvents = false;\nproc.StartInfo.FileName = "rundll32.exe";\nproc.StartInfo.Arguments = "shell32,OpenAs_RunDLL " + FilePath;\nproc.Start();	0
29538168	29537860	Add few records to gridview from DataTable	DataTable dt=yourdata;\nDataRow[] dr=dt.Select("columnname='Maths'");\n\nforeach (DataRow row in dr) {\n   dt.ImportRow(row);\n}\nGridView1.DataSource=dt;\nGridView1.DataBind();	0
19122737	19108479	How to query for items that don't exist by date	SELECT\n    counts.CalDate,\n    counts.CampaignId,\nFROM\n    (SELECT\n         cal.[Date] as CalDate,\n         c.CampaignId,\n         (SELECT COUNT(*) FROM CampaignStats WHERE CampaignID = c.CampaignId AND StatDate = cal.[Date]) AS StatCount\n    FROM \n    CalendarMonths cal, Campaigns c) counts\nWHERE\n    counts.StatCount = 0	0
10125632	10125585	Error message Nullable object must have a value	Column = (CompanyColumnsEnumDTO?) column	0
3940611	3913615	Returning HttpStatus codes with message from WCF Rest service that IParameterInspector AfterCall can handle	public void SetResponseHttpStatus(HttpStatusCode statusCode)\n{\n    var context = WebOperationContext.Current;\n    context.OutgoingResponse.StatusCode = statusCode;\n}	0
19583291	19583023	How to get total no seconds from a string in time format greater than 24hrs using C#	string s = "24:55:00.00";\nstring hoursS = s.Split(':')[0];\ndouble hours = int.Parse(hoursS);\n\ndouble totalSeconds = hours*3600;\n\ns = s.Substring(hoursS.Length);\ns = "00" + s;\ndouble d = (int)TimeSpan.Parse(s).TotalSeconds;\n\ntotalSeconds += d;\nConsole.WriteLine(totalSeconds);	0
26940119	26939262	Reading ALL attributes from a file (nested ones, too!)	[System.Serializable]\npublic class Item {\n\n    [XmlAttribute("name")]\n    public string name = "";\n    [XmlAttribute("type")]  \n    public string type;\n    [XmlAttribute("value")]\n    public int value = 0;\n    [XmlAttribute("weight")]\n    public float weight = 0.0f;\n\n    [XmlElement("mods")]\n    public Mods mods = new Mods();\n}\n\n[System.Serializable]\npublic class Mods\n{\n    [XmlAttribute("healthMod")]\n    public int healthMod = 0;\n    [XmlAttribute("staminaMod")]\n    public int staminaMod = 0;\n    [XmlAttribute("manaMod")]\n    public int manaMod = 0;}\n}	0
13924623	13893239	How to get Logger in void Main with Ninject.Extensions.Logging?	new StandardKernel().Get<ILoggerFactory>().GetCurrentClassLogger();	0
11724245	11724193	Comparison between time of 2 DateTime c#	if (DateTime1.TimeOfDay > DateTime2.TimeOfDay)\n{\n    MessageBox.Show("DateTime1 is later");\n}	0
978602	977329	How can I determine which mouse button raised the click event in WPF?	void OnClick(object sender, RoutedEventArgs e)\n{\nif (SystemParameters.SwapButtons) // Or use SystemInformation.MouseButtonsSwapped\n{\n// It's the right button.\n}\nelse\n{\n// It's the standard left button.\n}\n}	0
16283212	16283021	Linq: X objects in a row	public static class EnumerableExtensions {\n    public IEnumerable<T> InARow<T>(this IEnumerable<T> list, \n                                    Predicate<T> filter, int length) {\n        int run = 0;\n        foreach (T element in list) {\n            if (filter(element)) {\n                if (++run >= length) return true;\n            } \n            else {\n                run = 0;\n            }\n        }\n        return false;\n    }\n}	0
20456223	20456190	get latest 5 files in directory listing by date	.Take(5)	0
24665662	24664960	C# export of large datatbase to XML	XmlWriterSettings set = new XmlWriterSettings();\nset.ConformanceLevel = ConformanceLevel.Document;\nset.Indent = true;\n//comm is your command object\nusing (XmlReader reader = comm.ExecuteXmlReader())\nusing (XmlWriter writer = XmlWriter.Create(File.Open("testing.xml",FileMode.OpenOrCreate,FileAccess.Write),set)) \n{\n      while (!reader.EOF)\n      {\n          writer.WriteStartElement("test");\n          writer.WriteNode(reader, true);\n          writer.WriteEndElement();\n      }\n}	0
10381310	10381217	Validate input string	public bool IsAlpha(string strToCheck)\n  {\n    Regex objAlphaPattern=new Regex("[^a-zA-Z]");\n\n    return !objAlphaPattern.IsMatch(strToCheck);\n  }\nRegards	0
30135167	30115405	How do I convert a ListView SelectedItem into an IObservable?	private readonly ReplaySubject<TuningChangeEvent> tuningChange = new ReplaySubject<TuningChangeEvent>();\n\n\n        private void OneTuner_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) {\n           tuningChange.OnNext(TuningChangeEvent.tune(1,Convert.ToInt32(OneTuner.Value)));\n        }	0
23364365	23341613	English mail displays Chinese characters in some email clients	message.BodyEncoding = System.Text.Encoding.UTF8;	0
10147527	10147490	Create a new list containing references to elements from other lists?	List<Base> baseList = new List<Base>();\nbaseList.Add(a);\nbaseList.AddRange(bs);\nbaseList.AddRange(cs);\n// now you can modify the items in baseList	0
8079237	8079211	How to sort an array of the objects of a class according to a numeric property of the class	objectsOfMyClass.OrderByDescending(obj => obj.NumericProperty)	0
8726948	8726932	How to pass values in URL in c#	Response.Redirect("ChangePassword.aspx?MyParam=MyValue");	0
24331733	24328979	Passing value from a C# program into a Windows environment variable	for /F "delims=" %%a in ('abc.exe "any parameter"') do set datayyyymmdd=%%a	0
13958054	13957982	Changing variable value from different scope	Form2 otherForm = new Form2();\nbool x = false;\notherForm.FormClosing += (s,args)=> x = true;	0
1225729	1225675	how to figure out if a facebook user is logged to facebook connect in from C#	public static string SessionKey\n    {\n        get { return GetFacebookCookie("session_key"); }\n    }\n\n    private static string GetFacebookCookie(string propertyName)\n    {\n        var fullName = ApiKey + "_" + propertyName;\n\n        if (HttpContext.Current == null || HttpContext.Current.Request.Cookies[fullName] == null)\n            return null;\n\n        return HttpContext.Current.Request != null ? HttpContext.Current.Request.Cookies[fullName].Value : null;\n    }	0
11286691	11286633	Is it possible to compile an audio file together with my c# file into a single exe?	Namespace.ResourceFile.FileName	0
18233800	18233364	Create a gridview programmatically with column and rows RSS	List<string> names = new List<string>();\n names.Add(" the alghabban  ");\n GridView newGrid = new GridView();                         \n newGrid.DataSource = names;\n newGrid.DataBind();	0
28440340	28372757	alphanumeric string in OData v4's function string parameter is parsed as int into string, or null	[ODataRoute("/Parameters/Default.GetForConstant(constant={constant})"]	0
7962478	7962211	Programatically disable caps lock	if(Control.IsKeyLocked(Keys.CapsLock))\n        SendKeys.SendWait("{CAPSLOCK}This Is An Over Capitalized Test String");\n    else\n        SendKeys.SendWait("This Is An Over Capitalized Test String");	0
31136957	31135381	Read data stored with CArchive Ar(&SaveDataStoreDetail, CArchive::store);	CArchive Ar(&SaveDataStoreDetail, CArchive::load);\n...\nAr>>sDmdDataStore.iMachineNo;\nAr>>sDmdDataStore.csOptName;\nAr>>sDmdDataStore.csLocationofStone;	0
4344827	4344366	Multiple Combo Boxes With The Same Data Source (C#)	private List<TSPrice> GetPriceList()\n{\n  return new List<TSPrice>\n             {\n               new TSPrice(0, ""),\n               new TSPrice(0, "Half Day"),\n               new TSPrice(0, "Full Day"),\n               new TSPrice(0, "1 + Half"),\n               new TSPrice(0, "2 Days"),\n               new TSPrice(0, "Formal Quote Required")\n             };\n}\n\nprivate void BindPriceList(ComboBox comboBox, List<TSPrice> priceList)\n{\n  comboBox.DataSource = priceList();\n  comboBox.ValueMember = "Price";\n  comboBox.DisplayMember = "Description";\n  comboBox.SelectedIndex = 0;\n}    \n\nBindPriceList(objInsuredPrice, GetPriceList());\nBindPriceList(objTPPrice, GetPriceList());\nBindPriceList(objProvSum, GetPriceList());	0
13536222	13536187	Check to see if 3 keys are pressed	if (e.KeyCode == Keys.X && e.Control && e.Shift) {\n    // CTRL+SHIFT+X was pressed!\n}	0
29693111	29692450	Select query dynamically from matrix linq	var item = query.First();\n    string key = "A";\n\n    var p = item.GetType().GetProperty(key.ToLower());\n    var type = (Type)p.GetValue(item, null);	0
7186764	7185609	How to append string representation of a specified object to a instance	m_afc.QualifiedInstanceFilter = string.Format("^({0} : {1})$", Regex.Escape(this.Class), Regex.Escape(this.Instance));	0
4724467	4724250	How can I get running totals of integer values from a List()?	var sum = 0;\nforeach (var p in list) {\n  sum += p.Length;\n  p.Index = sum;\n}	0
18030564	18030515	Overriding a Unity registration using configuration?	container.RegisterType( ... );\ncontainer.LoadConfiguration(); // override with configuration\ncontainer.RegisterType( ... ); // override once again, this time with manual mapping	0
9432602	9432471	c# DataTable Select Wildcard with Int32	table.Select("Convert(Age, 'System.String') like '3%');	0
720171	720157	Finding all classes with a particular attribute	IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) \n                              where TAttribute: System.Attribute\n { return from a in AppDomain.CurrentDomain.GetAssemblies()\n          from t in a.GetTypes()\n          where t.IsDefined(typeof(TAttribute),inherit)\n          select t;\n }	0
29549508	29548518	How to Use AutoMapper for Find Method?	public IEnumerable<PaisViewModel> Find(Expression<Func<PaisViewModel, bool>> predicate)\n{\n    return _paisService.Find(predicate).Select(p => Mapper.Map(p, Pais.GetType(), PaisViewModel.GetType()));\n}	0
11853835	11853627	How can i make that my application will close and start and close automatic over and over again?	Timer timer;\n\npublic void StartTimer()\n{\n    timer = new Timer();\n    timer.Interval = 5000; // 5 seconds\n    timer.Tick += new EventHandler(timer_Tick);\n    timer.Start();\n}\n\nvoid timer_Tick(object sender, EventArgs e)\n{\n    Process[] p = Process.GetProcessesByName("TheApp");\n    if (p.Length == 0) {\n        // Restart the app if it is not running any more\n        Process.Start(@"C:\Programs\Application\TheApp.exe");\n    } else {\n        p[0].CloseMainWindow();\n    }\n}	0
2562008	2560891	How to restrict access to a class's data based on state?	public class MatchedCustomer : Customer\n{\n    public MatchedCustomer(Customer customer)\n    {\n        // set properties from customer, i.e.\n        FirstName = customer.FirstName;\n    }\n}	0
7477418	7477399	Is there an data type that acts both as a list and a dictionary?	var set = new HashSet<int>();\nset.Add(4);\nset.Add(4);   // there is already such an element in the set, no new elements added	0
14653768	14653684	Covariance with ICollection in C#	private void ProcessEventCollection<T>(ICollection<T> existing, IEnumerable<T> newlist)\n    where T : IViperEvent	0
12254407	12254337	Can a managed C++ assembly return an object to C#?	public ref class MyManagedClass{\n. . .\n}	0
12820291	12801956	Carousel control help needed	private const double DEFAULT_SCALE = 0.5;\nprivate const double MINIMUM_SCALE = 0;\nprivate const double MAXIMUM_SCALE = 1;\nprivate double _scale = DEFAULT_SCALE;	0
25496539	25496429	Can you change the name of a C# Winforms button via the App.config file?	btnGoogle.Text = ConfigurationManager.AppSettings["GoogleCaption"];	0
3440342	3440301	Is it possible to return a mock from another mock using Moq in C#?	[SetUp] \nprivate void SetupMarketRow() \n{ \n   var marketTotalRow = new Mock<ITotalRow>(); \n   marketTotalRow.Setup(r => r.TotalBudgetCurrentFact).Returns(1860716); \n   marketTotalRow.Setup(r => r.TotalBudgetEvol).Returns(-26); \n   marketTotalRow.Setup(r => r.TotalBudgetPreviousFact).Returns(2514079); \n\n\n   var localMarketReport = new Mock<IReport>(); \n   localMarketReport.Setup(r => r.TotalRow).Returns(marketTotalRow.Object);   \n   // Red swiggley here saying invalid candidate   \n\n}	0
10381450	10371331	How to formulate a MapPageRoute with a hash (#) in it?	string url = Page.GetRouteUrl("Topics", new { ID = 1, name = "title" });\nResponse.Redirect(url + "#bottom");	0
21927694	21927507	No route in the route table matches the supplied values after RedirectToAction	RedirectToAction("OtherAction", "OtherController", new {culture = "value"});	0
29641682	29641488	Need linq query to obtain specific result set	from t in db.Table\ngroup t by new {t.Category, t.Question} into g\norder by g.Category\nselect new \n{\n    CategoryName = t.FirstOrDefault().Category, //might be required to handle null here\n    Question = t.FirstOrDefault().Question, //might be required to handle null here\n    TotalCount = t.Count(),\n    AnsLessEqual3 = t.Where(d => d.Answer<=3).Count(),\n    Ans5 = t.Where(d => d.Answer = 5).Count(),\n    Ans789 = t.Where(d => d.Answer = 7 || d.Answer = 8 || d.Answer = 9).Count()\n}	0
27009522	27009422	How to add Ionic.Zip.dll in c#.net project and use it to create a zip from folder?	using (ZipFile zip = new ZipFile())\n {\n     zip.AddFiles(.....);\n     zip.Save(....);\n\n }	0
2462150	2462105	How to detect when window is closed when using Show() in WinForms C#	Form.Closed	0
18366871	18366787	Stop a key from firing an event in C# using ProcessCmdKey?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n     if (keyData == Keys.Right)\n    {\n\n        numericUpDown1.Value = Convert.ToDecimal(numericUpDown1.Value + 1);\n        return true;\n    }\n     if (keyData == Keys.Left)\n    {\n        try\n        {\n            numericUpDown1.Value = Convert.ToDecimal(numericUpDown1.Value - 1);\n            return true;\n        }\n        catch { }\n    }\n}	0
23776654	23776268	Extension method with generic parameter called from subclass instance	GetType()	0
3574790	3574710	DataGridView rows can't change their background color at the initialization stage	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    e.CellStyle.BackColor = Color.PaleGreen\n}	0
2408248	2408160	Generate lambda Expression By Clause using string.format in C#?	internal static Expression<Func<TModel, T>> GenExpressionByClause<TModel, T>(string column)\n    {\n        var columnPropInfo = typeof(TModel).GetProperty(column);\n        var formatMethod = typeof (string).GetMethod("Format", new[] {typeof (string), typeof (object)});\n\n        var entityParam = Expression.Parameter(typeof(TModel), "e");\n        var columnExpr = Expression.MakeMemberAccess(entityParam, columnPropInfo);\n        var formatCall = Expression.Call( formatMethod, Expression.Constant("{0}"), columnExpr);\n        var lambda = Expression.Lambda(formatCall , entityParam) as Expression<Func<TModel, T>>;\n        return lambda;\n    }	0
32403359	32402880	How to print C# 3D jagged array	for (int x = 0; x < foos.Length; x++) {\n            for (int y = 0; y < foos[x].Length; y++) {\n                for (int z = 0; z < foos[x][y].Length; z++) {\n                    Console.WriteLine(foos[x][y][z].Member);\n                }\n            }\n        }	0
3295885	3295859	How do I get NHibernate to do a join?	var criteria = Session.CreateCriteria(typeof(Store));\nvar join = criteria.CreateCriteria("Employees");\njoin.Add(Restrictions.Not(Restrictions.Eq("SomeStatus1", true));\nreturn criteria.List<Store>();	0
13597487	13597473	Use KeyValuePair<String, String> in Parallel.ForEach	Parallel.ForEach(symbolsConfigured, kvp =>\n            {...});	0
11120971	11120789	C# Reading a logfile into a listview	StreamReader reader = new StreamReader(@"C:\Users\jdudley\file.txt");\n// Will be incremented every time ID shows up so it must started at -1 so we don't\n// try and start inserting at 1.\nint rowIndex = -1;\nwhile (!reader.EndOfStream)\n{\n    string line = reader.ReadLine();\n    string[] parsedLine = line.Split(new char[] { '=' });\n    if(!this.dataGridView1.Columns.Contains(parsedLine[0]))\n    {\n        dataGridView1.Columns.Add(parsedLine[0],parsedLine[0]);\n    }\n    if (parsedLine[0].Trim().Equals("id"))\n    {\n        rowIndex++;\n        dataGridView1.Rows.Add();\n    }\n    dataGridView1[parsedLine[0], rowIndex].Value = parsedLine[1];\n}	0
8245977	8245794	copy two columns in a datatable	for (int i = 0; i < TickerPrice.Rows.Count; i++)\n{\n    DataRow destRow = Recap.NewRow();\n    destRow["Move Ticker price"] = TickerPrice.Rows[i]["CHG_PCT_1D"];\n    destRow["Move Index price"] = IndexPrice.Rows[i]["CHG_PCT_1D"];\n\n    Recap.Rows.Add(destRow);\n}	0
2281255	2280987	Merging two lists into one and sorting the items	List a = { 1, 3, 5, 7, 9 }\nList b = { 2, 4, 6, 8, 10 }\nList result = { }\nint i=0, j=0, lastIndex=0\nwhile(i < a.length || j < b.length)\n    // If we're done with a, just gobble up b (but don't add duplicates)\n    if(i >= a.length)\n        if(result[lastIndex] != b[j])\n            result[++lastIndex] = b[j]\n        j++\n        continue\n\n    // If we're done with b, just gobble up a (but don't add duplicates)\n    if(j >= b.length)\n        if(result[lastIndex] != a[i])\n            result[++lastIndex] = a[i]\n        i++\n        continue\n\n    int smallestVal\n\n    // Choose the smaller of a or b\n    if(a[i] < b[j])\n        smallestVal = a[i++]\n    else\n        smallestVal = b[j++]\n\n    // Don't insert duplicates\n    if(result[lastIndex] != smallestVal)\n        result[++lastIndex] = smallestVal\nend while	0
22757567	22731649	How to select an bounded combo box value and display its value into an Label Text	private void bind()\n    {\n        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AttendanceManagmentSystem.Properties.Settings.Cons1"].ConnectionString);\n        con.Open();\n        SqlDataAdapter da = new SqlDataAdapter("Select EmpId from EmpDetail", con);\n        DataTable dt = new DataTable();\n        da.Fill(dt);\n        comboBox1.DisplayMember = "EmpId";\n        comboBox1.ValueMember = "EmpId";\n        comboBox1.DataSource = dt;\n        con.Close();\n    }\n    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        label5.Text = comboBox1.Text;\n    }	0
16193489	16193249	Cannot add icon in shell extension with C#	protected override ContextMenuStrip CreateMenu()\n{\n    //  Create the menu strip.\n    var menu = new ContextMenuStrip();\n\n    //  Create a 'count lines' item.\n    var itemCountLines = new ToolStripMenuItem\n    {\n        Text = "Count Lines...",\n        Image = Properties.Resources.CountLines\n    };\n\n    //  When we click, we'll count the lines.\n    itemCountLines.Click += (sender, args) => CountLines();\n\n    //  Add the item to the context menu.\n    menu.Items.Add(itemCountLines);\n\n    //  Return the menu.\n    return menu;\n}	0
4202383	4202333	Convert WriteableBitmap pixel format to Bgra32 in c# wpf	if (bmpSource.Format != PixelFormats.Bgra32)\n     bmpSource = new FormatConvertedBitmap(bmpSource, PixelFormats.Bgra32, null, 0);	0
27016418	27016291	How to clear everything in winforms Panel?	myTreeViewBase.Nodes.Clear();	0
5260918	5260873	Requires regex for US Phone Format	(<your current regex>)|(___-___-____)	0
797880	797875	how to add event in dataGrid in C#	yourobject.NameOfEvent += new NameOfEventHandler(method);	0
11396206	11395991	Using WYSIWYG/Rich text editor control in display mode (SharePoint)	SPSecurity.RunWithElevatedPrivileges(delegate()\n{\n    using (SPSite site = new SPSite(web.Site.ID))\n    {\n       // Do things by assuming the permission of the "system account".\n    }\n});	0
18900604	18897093	How can I write a raw string of XML to a file reliably, to a base-64 encoded string?	// write string out\nbyte[] data = Encoding.UTF8.GetBytes(xmlString);\n\nusing (StreamWriter writer = File.CreateText(fullPath + "Module" + i + "D" + historicDataCount +  ".bin"))\n    using (ToBase64Transform transformation = new ToBase64Transform())\n    {                    \n        byte[] buffer = new byte[transformation.OutputBlockSize];\n\n        int i = 0;    \n        while (data.Length - i > transformation.InputBlockSize)\n        {\n            transformation.TransformBlock(data, i, data.Length - i, buffer, 0);\n            i += transformation.InputBlockSize;\n            writer.Write(Encoding.UTF8.GetString(buffer));\n        }\n\n        // final block\n        buffer = transformation.TransformFinalBlock(data, i, data.Length - i);\n        writer.Write(Encoding.UTF8.GetString(buffer));\n    }	0
693134	693111	How do I force showing '+' sign using StringFormat	PS C:\Users\jachymko> '{0:+0.0%;-0.0%}' -f 2.45\n+245,0%\nPS C:\Users\jachymko> '{0:+0.0%;-0.0%}' -f -2.45\n-245,0%	0
10626225	10622418	How to get IP of VPN / Network with specific name and if it is connected?	foreach (var item in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())\n        {\n            Console.Write(item.Name + " - " + item.OperationalStatus.HasFlag(System.Net.NetworkInformation.OperationalStatus.Up) + " : ");\n            foreach (var item2 in item.GetIPProperties().UnicastAddresses)\n            {\n                if (!item2.Address.IsIPv6LinkLocal)\n                    Console.Write(item2.Address.ToString());\n            }\n            Console.WriteLine();\n        }	0
3985249	3985209	What is the best way of converting a number to a alphabet string?	int input = 123450;\nstring output = "";\n\nwhile (input > 0)\n{\n    int current = input % 10;\n    input /= 10;\n\n    if (current == 0)\n        current = 10;\n\n    output = (char)((char)'A' + (current - 1)) + output;\n}\n\nConsole.WriteLine(output);	0
2508456	2507826	Avoiding Redundancies in XML documents	string xml = @"<persons>\n<person> \n  <eye> \n    <info> \n       <color>blue</color> \n    </info> \n  </eye> \n  <hair> \n    <info> \n       <color>blonde</color> \n    </info> \n  </hair> \n</person>\n<person> \n  <eye> \n    <info> \n       <color>green</color> \n    </info> \n  </eye> \n  <hair> \n    <info> \n       <color>brown</color> \n    </info> \n  </hair> \n</person>\n</persons>";\n\nXDocument document = XDocument.Parse(xml);\n\nvar query = from person in document.Descendants("person")\n            select new\n            {\n                EyeColor = person.Element("eye").Element("info").Element("color").Value,\n                HairColor = person.Element("hair").Element("info").Element("color").Value\n            };\n\nforeach (var person in query)\n    Console.WriteLine("{0}\t{1}", person.EyeColor, person.HairColor);	0
1772218	1772140	Using App.config to set strongly-typed variables	int i = Settings.Default.IntSetting;\n\nbool b = Settings.Default.BoolSetting;	0
13132873	13132690	Failing to use Array.Copy() in my WPF App	for(int i = 0; i < 8; i++)\n{\n    sendBuf[i+memloc] = Convert.ToSByte(version[i]);\n}	0
7607247	7607232	C# MVC - Get UserId from Session array	string[] userProfile = Session["UserProfile"] as string[];\nstring id = userProfile[0];	0
18925262	18925221	Get two linq queries into one listbox	var items = dataTable.Select(p => string.Format("{0} : {1}", p.NAME, p.TOTALS));\nlistBox1.Items.AddRange(items.ToArray());	0
24489791	24489317	Web api routing - default actions with custom actions mapped twice	[RoutePrefix("api/prospect")]\npublic class ProspectController: ApiController\n{\n    [Route("{id}")]\n    public ProspectDetail Get(int id)\n    {\n        ...\n        return prospect;\n    }\n}	0
4703041	4702993	How to make your object act as another type when comparing?	public static implicit operator bool(Validate v)\n    {\n        // Logic to determine if v is true or false\n        return true;\n    }	0
16833810	16833219	How convert const wchar_t* from C DLL to C# string automatically	[DllImport(dll, CallingConvention = CallingConvention.Cdecl)]\n  [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyMarshaller))]\n  private static extern string SysGetLibInfo();	0
17915718	17915661	Skip specific value in sequence, using LINQ, IEnumerable?	Roles.GetAllRoles().Where(v=> !v.Equals("user"))	0
34338753	34338674	Getting both values from 2 arrays	string[] sName = new string [] { "John", "Mary", "Keith", "Graham", "Susan" };\nint[] iMarks = new int [] { 34, 62, 71, 29, 50 };\nstring sSearch;\n\n//...\nint iNumber = Array.IndexOf(sName, sSearch);\n\nif (iNumber >=0)\n{\n    Console.WriteLine(sSearch + " Has been found " + iMarks[iNumber]);\n}	0
1504902	1504871	Options for initializing a string array	string[] items = { "Item1", "Item2", "Item3", "Item4" };\n\nstring[] items = new string[]\n{\n  "Item1", "Item2", "Item3", "Item4"\n};\n\nstring[] items = new string[10];\nitems[0] = "Item1";\nitems[1] = "Item2"; // ...	0
17515970	17487048	NV12 format and UV plane	W x H x 3 / 2	0
6329140	6329114	How to read values from custom section in web.config	NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");\nstring userName = section["userName"];\nstring userPassword = section["userPassword"];	0
23567759	23567626	C# Mongodb find first by comparing field values	post = db.GetCollection<Post>().Linq().First(x => x.CharCount != x.Body.Length);	0
28509654	28509626	How can I modify a member of an object list with a common superclass in C#?	Engine door = toys.OfType<Car>().Select(c => c.Engine).FirstOrDefault();	0
25642641	25624982	Delete contents of bookmark without deleting bookmark in ms word using c#	public void cleanBookmark(string bookmark)\n    {\n        var start = currentDocument.Bookmarks[bookmark].Start;\n        var end = currentDocument.Bookmarks[bookmark].End;\n        Word.Range range = currentDocument.Range(start, end);\n        range.Delete(); \n        //The Delete() only deletes text so if you got tables in the doc it leaves the tables empty. \n        //The following removes the tables in the current range.\n        if (range.Tables.Count != 0)\n        {\n            for (int i = 1; i <= range.Tables.Count; i++)\n            {\n                range.Tables[i].Delete();\n            }\n        }\n        currentDocument.Bookmarks.Add(bookmark, range);\n    }	0
28257980	28257872	Force a thread which does unknown work to stop after a set amount of time	Thread.Abort	0
11255315	11254784	How can I search a DataGridView and then highlight the cell[s] in which the value is found?	dataGridView.Rows[X].Cells[Y].Value	0
4810104	4809386	Nested lambda expression translated from SQL statement	_employeeService.Where(e=>(e.emp_id==emp) && (dep == null || dep.contains(e.dep_id)) );	0
10361563	10361540	Get number of objects in a collection	int itemCount = yourCollection.Count;	0
3929418	3929334	Detect Month changed in month calendar C#	private int MonthValue = 0;\nprivate bool bChanged = false;\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    MonthValue = monthCalendar1.TodayDate.Month;\n}\nprivate void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)\n{\n\n    if (MonthValue != monthCalendar1.SelectionStart.Month)\n    {\n        //changed\n        bChanged = true;\n        MonthValue = monthCalendar1.SelectionStart.Month;\n    }\n    else\n    {\n        //not changed\n        bChanged = false;\n    }\n}	0
9053614	9053564	C# merge one directory with another	public static void CopyAll(DirectoryInfo source, DirectoryInfo target)\n{\n    if (source.FullName.ToLower() == target.FullName.ToLower())\n    {\n        return;\n    }\n\n    // Check if the target directory exists, if not, create it.\n    if (Directory.Exists(target.FullName) == false)\n    {\n        Directory.CreateDirectory(target.FullName);\n    }\n\n    // Copy each file into it's new directory.\n    foreach (FileInfo fi in source.GetFiles())\n    {\n        Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);\n        fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);\n    }\n\n    // Copy each subdirectory using recursion.\n    foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())\n    {\n        DirectoryInfo nextTargetSubDir =\n            target.CreateSubdirectory(diSourceSubDir.Name);\n        CopyAll(diSourceSubDir, nextTargetSubDir);\n    }\n}	0
10128284	10127871	How can I read image pixels' values as RGB into 2d array?	using System.Drawing;\n\nBitmap img = new Bitmap("*imagePath*");\nfor (int i = 0; i < img.Width; i++)\n{\n    for (int j = 0; j < img.Height; j++)\n    {\n        Color pixel = img.GetPixel(i,j);\n\n        if (pixel == *somecondition*)\n        {\n            **Store pixel here in a array or list or whatever** \n        }\n    }\n}	0
27846967	27846791	How to Pass Values from TextArea to another view on ASP .NET MVC 4	...\n\n[HttpPost]\npublic ActionResult Index(string text)\n{\n    TempData["Text"] = text;\n    return RedirectToAction("About", "Home");\n}\n\npublic ActionResult About()\n{\n    ViewBag.Message = TempData["Text"];\n    return View();\n}	0
800306	800275	Bundle enterprise library instead of installing	Microsoft.Practices.CompositeUI.dll\nMicrosoft.Practices.CompositeUI.WinForms.dll\nMicrosoft.Practices.CompositeUI.WPF.dll\nMicrosoft.Practices.EnterpriseLibrary.Common.dll\nMicrosoft.Practices.EnterpriseLibrary.Data.dll\nMicrosoft.Practices.EnterpriseLibrary.Data.SqlCe.dll\nMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.dll\nMicrosoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll\nMicrosoft.Practices.EnterpriseLibrary.Logging.dll\nMicrosoft.Practices.ObjectBuilder.dll\nMicrosoft.Practices.SmartClient.ConnectionMonitor.dll\nMicrosoft.Practices.SmartClient.DisconnectedAgent.dll\nMicrosoft.Practices.SmartClient.EndpointCatalog.dll\nMicrosoft.Practices.SmartClient.EnterpriseLibrary.dll	0
25160527	25159781	how to visible false edit commandbutton inside Gridview	protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)\n{\n\n   //Code Here to Disable button. I'd use a Foreach loop like this.\n   foreach(GridViewRow gvr in GridView1.Rows)\n   {\n        Label label = ((Label)gvr.FindControl("label"));\n        LinkButton edit = ((LinkButton)gvr.FindControl("edit"));\n        if (label.Text == 1)\n        {\n           edit.Visible = false;\n        }\n   }       \n}	0
28556135	28556022	WPF, Access combobox selected item	private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    var itemIndex = combobox.Text;\n    string name = (combobox.SelectedItem as ComboBoxItem).Name;\n    var obj = dock.FindName("Exp_Name");\n    if (obj == null)\n    {\n        Expander expander = new Expander();\n        expander.Header = name;\n        expander.Name = "Exp_Name";\n        dock.Children.Add(expander);\n        this.RegisterName(expander.Name, expander);\n    }\n    else\n    {\n        var element = obj as Expander;\n        element.Header = name;\n    }\n}	0
2118727	2118688	Return Tuple from EF select	var productCount = from product in context.products\n                select new {Product = product, Count = products.Orders.Count };\nvar final = from item in productCount.AsEnumerable()\n            select Tuple.Create(item.Product, item.Count);	0
816284	816269	with dynamic, awkward reflection no more?	// Via 'dynamic'    \ndynamic dx = GetSomeCLRObject();\ndx.DoSomething();\ndx.SomeMember = 2;\n\n// Via Reflection\nobject x = GetSomeCLRObject();\nType xt = x.GetType();\nMemberInfo DoSomethingMethod = xt.GetMethod("DoSomething");\nDoSomethingMethod.Invoke(x, null);\nPropertyInfo SomeMemberProperty = xt.GetProperty("SomeMember");\nSomeMemberProperty.SetValue(x, 2);	0
11557354	11557304	Getting next row from SQL Server	declare @CurrentID int = 123;\nselect top 1 * from [MyTable] where [MyTable].[ID] > @CurrentID;	0
16391289	16388190	Best design to convert a data object to a DataTable	public class Converter\n{\n    public DataTable Convert(Apple obj)\n    {\n\n    }\n    public DataTable Convert(Orange obj)\n    {\n\n    }\n    public DataTable Convert(Mango obj)\n    {\n\n    }\n    public DataTable Convert(Avocado obj)\n    {\n\n    }\n}	0
7956591	7956408	App.config multi-project access strategies	public class FirstProjectClass \n{\n  public static int SyncEveryMinutes\n  {\n      get { return (int)ConfigurationManager.AppSetting["SyncEveryMinutes"] };\n  }\n}\n\n\npublic class SecondProjectClass\n{\n  public void ShowConfigedValue()\n  {\n      Console.Writeline("Syncing every {0} minutes", FirstProjectClass.SyncEveryMinutes);\n  }\n}	0
20089138	20089074	Hide/Show table in UpdatePanel in asp.net	yourDropDownList.Attributes["onChange"] = "someJavaScriptFunction();";	0
23032482	23032452	How to optimize this linq query by getting two numbers in one call?	var query = from p in myContext.Products\nwhere p.Price < 50\nselect p;\n\nvar products = query.ToList();\nint numberOfItems = products.Count;	0
7475164	7474022	Trouble Mocking Lambda withing Unitofwork's Repository	cFieldRepositoryMock.Setup(x => x.GetFirst(query, It.IsAny<Func<IQueryable<CField>, IOrderedQueryable<CField>>>()));	0
2136567	2136459	how to query sql server database size	class Program\n{\n    static void Main(string[] args)\n    {\n        string strCount;\n        SqlConnection Conn = new SqlConnection\n           ("Data Source=ServerName;integrated " +\n           "Security=sspi;initial catalog=TestingDB;");\n        SqlCommand testCMD = new SqlCommand\n           ("sp_spaceused", Conn);\n\n        testCMD.CommandType = CommandType.StoredProcedure;        \n\n        Conn.Open();\n\n        SqlDataReader reader = testCMD.ExecuteReader();\n\n        if (reader.HasRows)\n        {\n            while (reader.Read())\n            {\n               Console.WriteLine("Name: " + reader["database_name"]); \n               Console.WriteLine("Size: " +  reader["database_size"]); \n            }\n        }\n\n        Console.ReadLine();\n    }\n}	0
14891731	14891488	how to calculate height and width of image	Bitmap btmp;\nstring image = "~/Images/2013-02-14_225913.png";\nmyBitmap = new Bitmap(image);\n\nint height= btmp.Height;\nint weight = btmp.Width;	0
33383040	33381922	Code placement strategy for partials for when migrating from ObjectContext to DbContext in Entity Framework	Models/<Model>.Partial.cs	0
6870665	6870570	Find controls in listview item template of the same type	OnItemDataBound="Expenses_ItemDataBound"\n\nprotected void Expenses_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n\n    if (e.Item.ItemType == ListViewItemType.DataItem)\n    {\n\n        Label ExpenseTypeLabel = (Label)e.Item.FindControl("ExpenseTypeLabel");\n\n        string ExpenseType = (ExpenseTypeLabel.Text.ToString());\n\n        if (ExpenseType == "Mileage")\n        {\n            // disable button\n        }\n    }\n}	0
30838578	26687241	How define a generic type from an object type?	public void CreateListByNonGenericType(object myObject)\n{\n    Type objType = myObject.GetType();\n    Type listType = typeof(List<>).MakeGenericType(objType);\n\n    //We can not use here generic version of the interface, as we\n    // do not know the type at compile time, so we use the non generic \n    // interface IList which will enable us to Add and Remove elements from\n    // the collection\n    IList lst = (IList)Activator.CreateInstance(listType);\n}	0
7253228	7251903	Binding a TreeView control	private TreeNode AddNode(TreeNode node, string key)\n{\n  val child = node.ChildNodes.Cast<TreeNode>().FirstOrDefault(_ => _.Value == key);\n  if(child != null)\n     return child;\n\n  child = new TreeNode(key, key);\n  node.ChildNodes.Add(child);\n  return child;\n}	0
8385031	8384797	How to get the xml attribute value of root?	XDocument xdoc = XDocument.Load(targetFileName);\nvar attrib = xdoc.Root.Attribute("options").Value;\n\n// attrib = "idprefix:realID"	0
16936156	16936109	Input string was not in a correct format from null data from DataTable	if(dt.Rows[i]["DocEntry"]!= DBNull.Value)\n{\n   oDT.SetValue("hDocEntry", i, int.Parse(dt.Rows[i]["DocEntry"].ToString()));\n}	0
2273261	1847144	Adding a cloned SPView to a list	SPView thisView = thisList.DefaultView;\nthisView = thisView.Clone("High Priority", 100, true, false);\nthisView.Query = "<GroupBy Collapse=\"TRUE\" GroupLimit=\"100\"><FieldRef Name=\"dlCategory\" /></GroupBy><Where><Eq><FieldRef Name=\"dlPriority\"></FieldRef><Value Type=\"Number\">2</Value></Eq></Where>";\nthisView.Update();	0
10271247	10271171	Creating a dynamic table	using System.Web.UI.WebControls;	0
7936060	7933833	AMI Asterisk Manager Interface Originate Action	OriginateAction oc = new OriginateAction();\noc.Context = "YourDialPlanContext";\noc.Priority = 1;\n\n// Channel is however you're dialing (extensions, SIP, DAHDI, etc.)\noc.Channel = "SIP/12125551212@Your-Sip-Prover-Peer-Name"; \n// or in the alternative\n// oc.Channel = "ZAP/ZapChannelName/12125551212";\n\noc.CallerId = "9998887777";\n\n// This is the extension you want dialed once the call is connected\n// 300 in our example\noc.Exten = "300";\noc.Timeout = 60000;               // Our timeout in ms\noc.Variable = "VAR1=ABC|VAR2=25"; // If you need to pass variables to the dialplan\n\n// Async should be set to true, unless you want your code to wait until the call\n// is complete\noc.Async = true;         \n\n// Go ahead and place the call\nManagerResponse originateResponse = AsteriskManager.SendAction(oc, oc.Timeout);	0
25712617	25712578	Enter DateTime value from one form to another form in TextBox	public Form3(DateTime chkindate)\n{\n    InitializeComponent();\n    ChkInDate = chkindate;\n    CheckInTxt.Text = chkindate.ToString(); // add this line\n}	0
29352599	29352459	How to splice IP address into network address in C# / asp.net?	var s = "10.20.30.1 / 24";\ns = s.Substring(0, s.LastIndexOf(".")); //"10.20.30"	0
7467434	7388901	How to insert null value into DateTime column? 	IF DATEDIFF(DD, @DATE, '1/1/1753') = 0\n    SET @DATE = NULL	0
7526319	7526211	How to add Pushpin Onclick Event?	foreach (var root in Transitresults)\n    {\n        var accentBrush = (Brush)Application.Current.Resources["PhoneAccentBrush"];\n\n        var pin = new Pushpin\n        {\n            Location = new GeoCoordinate\n                {\n                    Latitude = root.Lat,\n                    Longitude = root.Lon\n                },\n            Background = accentBrush,\n            Content = root.Name,\n            Tag = root\n        };\n        pin.MouseLeftButtonUp += BusStop_MouseLeftButtonUp;\n\n\n        BusStopLayer.AddChild(pin, pin.Location);\n\n    }\n}\n\nvoid BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n{\n    var root =  ((FrameworkElement)sender).Tag as BusStop;\n    if (root != null)\n    {\n        // You now have the original object from which the pushpin was created to derive your\n        // required response.\n    }\n}	0
14164649	14157994	How to hide what's outside a ScrollViewer?	System.Windows.Forms.PictureBox pictureBox = new System.Windows.Forms.PictureBox();\n        pictureBox.Width = (int)Math.Sqrt((double)game.Map.grid.Count) * 50; pictureBox.Height = (int)Math.Sqrt((double)game.Map.grid.Count) * 50;\n        game.Map.afficher(pictureBox);\n        System.Windows.Forms.ScrollableControl sc = new System.Windows.Forms.ScrollableControl();\n        sc.Controls.Add(pictureBox);\n        sc.AutoScroll = true;\n        windowsFormsHost1.Child = sc;	0
15979482	15979388	Days in month without weekends to xml files	foreach (DateTime weekDay in AllDatesInMonth(...).Where(d=>d.DayOfWeek!= DayOfWeek.Saturday && d.DayOfWeek!=DayOfWEek.Sunday)){\n\n...\n}	0
18983216	18982482	How to Download File	window.location = '@Url.Action("Method", "Controller")';	0
34403305	34245903	JwtBearerAuthentication with ASP.Net 5	dvnm update -u	0
1259418	1259412	How do I select a C# variable using a string	Dictionary<string, int>	0
10215339	10214901	Linq: Difference between 2 DateTimes in TimeSpan	Tickets.Where(t => \n      SqlFunctions.DateDiff("second", t.Date, myTicket.Date) < 120));	0
10298031	9241226	add a host header to a website on IIS 7 programmatically	static void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)\n    {\n        using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))\n        {\n            var bindings = directoryEntry.Properties["ServerBindings"];\n            var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);\n            if (bindings.Contains(header))\n              throw new InvalidOperationException("Host Header already exists!");\n            bindings.Add(header);\n            directoryEntry.CommitChanges();\n        }\n    }	0
31707850	31707678	What is a syntax of transferring data from listView (Visual studio, c#) to another database?	using (var conn = new SqlConnection())\n        {\n            foreach (var item in listView1.Items)\n            {\n                string firstValue = item.SubItem.First();\n                string secondValue = item.Subitem.Last();\n                String insertSQL = @"INSERT INTO SALES_TABLE(pay_type, pay_amount) \n                                VALUES (@val1 , @val2)";\n                SqlCommand cmd = new SqlCommand(insertSQL, conn);\n                cmd.Parameters.AddWithValue("@val1",firstValue);\n                cmd.Parameters.AddWithValue("@val2", secondValue);\n                cmd.ExecuteNonQuery();\n            } \n        }	0
15949727	15949693	I want count uniques along with value in array?	var itemCounts = list.GroupBy(l => l)\n                     .Select(g => new { key = g.Key, count = g.Count()});	0
33431567	33431429	How to get file from FileStremResult object in Asp.Net MVC Web application?	[HttpPost]\npublic ActionResult MyMethod(MyViewModel model)\n{\n\n     HttpResponseBase response = ControllerContext.HttpContext.Response;\n\n    response.ContentType = "application/pdf";\n    response.AppendHeader("Content-Disposition", "attachment;filename=yourpdf.pdf");\n\n    FileStreamResult document = CreateDocument(model);\n    //Write you document to response.OutputStream here\n    document.FileStream.Seek(0, SeekOrigin.Begin);\n    document.FileStream.CopyTo(response.OutputStream, document.FileStream.Length);\n\n    response.Flush();\n\n    return new EmptyResult();\n}	0
12146762	12146509	How do I mainain the state of checkbox?	if (IsPostBack) { \n    // It is a postback, don't bind data\n} else { \n    // It is not a postback, bind data\n}	0
1772488	1772380	Equivalent of the php fmod in C#	double lon_rad = ((lon1+dlon_rad + Math.PI) % (2*Math.PI)) - Math.PI;	0
1328902	1328803	How to rebuild a struct from bytes after transfer [C#]	/* Define you structure like this (possibly) */\nstruct MESSAGE\n{\n  [MarshalAs(UnmanageType.ByValArray, SizeConst=8)]\n  byte[]    cCommand;\n  [MarshalAs(UnmanagedType.LPStr)]\n  string  sParameter;\n};\n\n/* Read data into an instance of MESSAGE like this */\nbyte[] bytes = new byte[Marshal.SizeOf(MESSAGE)];\n\nsocket.Receive(bytes, 0, bytes.Length);\nIntPtr ptr = Marshal.AllocHGlobal(bytes.Length);\n\ntry\n{\n    Marshal.Copy(bytes, 0, ptr, bytes.Length);\n    m = (MESSAGE)Marshal.PtrToStructure(ptr, typeof(MESSAGE));\n}\nfinally\n{\n    Marshal.FreeHGlobal(ptr);\n}	0
20091038	20082365	Retrieve list of all accounts in CRM through C#?	/* If you only want name */\nvar accounts = context.AccountSet.Select(acc => acc.Name);\n/* If you want more attributes */\nvar accounts = context.AccountSet\n    .Select(acc => new\n        {\n            name = acc.Name,\n            guid = acc.AccountId,\n            parent = acc.ParentAccountId,\n            number = acc.AccountNumber\n        });\n/* No need to call .ToList() on accounts, just iterate through the IQuerable */\nforeach (var account in accounts)\n{\n    // Add account to drop down\n}	0
3242017	3241965	Bind gridview inside of usercontrol from content page	//in user control, add this method\npublic void BindGrid()\n{\n    gvInnerGrid.DataBind();\n}\n\n//on your page\nuserControl.BindGrid();	0
5494493	5494476	How do I calculate x where a^x=b?	var x = Math.Log(b, a);	0
7732450	7732375	Calling a method from a created instance	class Player\n{\n    private Screen parentScreen;\n\n    public Player(Screen parentScreen) { this.parentScreen = parentScreen; }\n\n    public MyMethodThatHasToCallScreensMethod()\n    {\n        parentScreen.ResetHUD();\n    }\n}\n\n\nclass Screen\n{\n    public Player CreatePlayer()\n    {\n        return new Player(this);\n    }\n}	0
26098910	26098806	Linq insert selected data into ObservableCollection	var server = from e in _fileElement.Elements("computerprefix")\n             where e.Attribute("name") != null\n             select new ServersLogins\n             {\n                 Server = e.Attribute("name").Value,\n                 Logins = new ObservableCollection(\n                              from i in e.Elements("user")\n                              select new Login\n                              {\n                                  User = i.Attribute("name"),\n                                  Password = i.Attribute("password")\n                              })\n             };	0
5353413	5353261	Does Facebook open a canvas app with a Post request? It's causing havoc with my MVC actions	[HttpPost]\npublic ActionResult CanvasLoad(FacebookPostLoadViewModel model)\n{\n    // Do your load logic and show your view or RedirectToAction("Otherview");\n    return View("Friend", model);\n}	0
25721970	25713220	How do i disable page transition animations in windows phone 8?	TransitionService.NavigationInTransition	0
2708449	2704463	How to assign default values and define unique keys in Entity Framework 4 Designer	public partial class MyEntityClass\n{\n    public MyEntityClass()\n    {\n        CreationDate = DateTime.Now;\n    }\n}	0
16775074	16774412	Relog can't open a binary log file if executed from C#	public static bool WaitForFileLock(string path, int timeInSeconds)\n{\n  bool fileReady = false;\n  int num = 0;\n\n  while (!fileReady)\n  {\n    if (!File.Exists(path))\n    {\n      return false;\n    }\n\n    try\n    {\n      using (File.OpenRead(path))\n      {\n        fileReady = true;\n      }\n    }\n    catch (Exception)\n    {          \n      num++;\n      if (num >= timeInSeconds)\n      {\n        fileReady = false;\n      }\n      else\n      {\n        Thread.Sleep(1000);\n      }\n    }\n  }\n\n  return fileReady;\n}	0
19854677	19854607	How can I perform indexing in datagridview in c# .net	private int page = 0;\nprotected void ShowNextResults_Click(object sender, EventArgs e)\n{\n      page++;\n\n      dataGridView1.CurrentCell = null; //required to control row visibility as we cannot hide current cell\n\n      int from = page * 10;\n      int to = from + 10;\n\n      for (int i = 0; i < dataGridView1.Rows.Count; i++)\n      {\n           if (i >= from || i < to)\n           {\n                dataGridView1.Rows[i].Visible = true;\n           }\n           else\n           {\n                dataGridView1.Rows[i].Visible = false;\n           }\n      }\n}	0
17861064	17860501	How to depend by parent class	kernel.Bind<IManager>().To<Manager>().Named("Registration").WithConstructorArgument("settings", new Custom1Settings());\n\nkernel.Bind<IHandler>().To<Handler>().WithConstructorArgument("manager", ctx => ctx.Kernel.Get<IManager>("Registration"));	0
20321132	20318248	Error 401 attempting to retrieve a web response	req.Headers.Add("Access-Control-Request-Headers","accept, origin, x_session, content-type");\nreq.Headers.Add("Access-Control-Request-Method","POST");	0
591600	591543	C# how to disable webbrowser usage	((Control)webBrowser1).Enabled = false;	0
34368265	34368170	how to get number of items checked in checklist in textbox?	for (int i = 0; i < checkedListBox1.Items.Count; i++)\n            {\n                if (checkedListBox1.GetItemChecked(i))\n                {\n                    string str = (string)checkedListBox1.Items[i];\n                    textBox1.Text += str;\n                }\n            }	0
31141874	31118717	Return actual patched property value from patchcommand in RavenDb	output()	0
8083190	8083076	C# creating a CSV file so contents of one field wraps in a cell	myCell.Style.IsTextWrapped = true;	0
32830840	32827857	Inserting a Template into a Template - C# Open XML SDK 2.0/2.5	foreach (BookmarkStart bookmark in mainDoc.RootElement.Descendants<BookmarkStart>().Where(b => String.Equals(b.Name, bookmarkName)))\n            {\n                var parent = bookmark.Parent;\n\n                using (WordprocessingDocument newTemplate = WordprocessingDocument.Open(template2, false))\n                {\n                    var newTemplateBody = newTemplate.MainDocumentPart.Document.Body;\n                    foreach (var element in newTemplateBody.Elements().Reverse<OpenXmlElement>())\n                    {\n                        parent.InsertAfterSelf<OpenXmlElement>((OpenXmlElement)element.Clone());\n                    }\n                }\n            }	0
14719372	14718921	Set the image dynamically	pbAdvertisingSpace.Image = Resources.yourImage;	0
6848185	6848006	How to detect a non zero value in a binary file?	int index = -1;    \nfor(int i = 0 ; i < arr.Length ; i++)\n{\n    if(arr[i] != 0)\n    {\n        index = i;\n        break;\n    }\n}	0
1363777	1363773	C# Data Structure Like Dictionary But Without A Value	HashSet<T>	0
15030963	14817597	Reading signed integers from serial port	while....\n{\n  if (comBufferLength >= 2)\n  {\n     imsb1 = BitConverter.ToInt16(comBuffer, 0);\n     if (comBufferLength >= 4)\n       imsb2 = BitConverter.ToInt16(comBuffer, 2);\n       ....	0
17376072	17376057	rdr is a 'variable' but is used like a 'method'	KEMASKINI_ID.Text = rdr2["IDPENGGUNA"].ToString();\nKEMASKINI_IC.Text = rdr2["NoIC"].ToString();\nKEMASKINI_NAMA.Text = rdr2["nama"].ToString();\nKEMASKINI_MASUK.Text = rdr2["idpengguna"].ToString();\nKEMASKINI_CAPAIAN.Text = rdr2["kodaccesslevel"].ToString();	0
5245491	5244561	Nhibernate + QueryOver: filter with Where ignoring sensitive	Domain.User User = Session.QueryOver<Domain.User>()\n       .WhereRestrictionOn(x=>x.Login).IsInsensitiveLike("username")\n       .SingleOrDefault();	0
29939861	29939638	Linq statement with 2 joins a where and need a count	var count = (from p in _db.Personen\n             join pc in _db.Postcodes on p.Postcode equals pc.postcode\n             join r in _db.Regios on pc.RegioId equals r.RegioId\n             where p.Leeftijd >= leeftijdgetal[0] && leeftijd[1] <= p.Leeftijd && \n                   r.RegioNaam == regio && \n                   p.Geslacht == geslacht &&\n                   p.Showit == 1\n            )\n            .Distinct()\n            .Count();	0
1376017	1375867	querying for local groups	DirectoryEntry machine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");\nforeach (DirectoryEntry child in machine.Children)\n{\n    if (child.SchemaClassName == "Group")\n    {\n        Debug.WriteLine(child.Name);\n    }\n}	0
18651640	18639297	Using XmlWriter with more than 1 same attributes with diffrent values	writer.WriteStartElement("MyGuest");\nwriter.WriteAttributeString("Type","Adult");\nwriter.WriteAttributeString("Number","2");\nwriter.WriteEndElement();\n\nwriter.WriteStartElement("MyGuest");\nwriter.WriteAttributeString("Type","Child");\nwriter.WriteAttributeString("Age","12");\nwriter.WriteAttributeString("Number","2");\nwriter.WriteEndElement();	0
17487099	17477304	How to manipulate Pivot control to looks linear?	private void pivoteSelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n\n        Pivot pivot = (Pivot)sender;\n\n        if (lastselectedIndex == 2 && pivot.SelectedIndex == 0)\n        {\n            pivot.SelectedIndex= 2;\n            return;\n        }\n        else if (lastselectedIndex == 0 && pivot.SelectedIndex == 2)\n          {\n            pivot.SelectedIndex= 0;\n            return;\n        }\n\n\n        lastselectedIndex = pivote.SelectedIndex;\n    }	0
7403804	7399876	help with parsing json in .net	public class Place\n    {\n\n        public string ID { get; set; }\n        public string Name { get; set; }\n        public float Latitude { get; set; }\n        public float Longitude { get; set; }\n\n    }\nprivate void Run()\n{\n    List<Place> places = new List<Place>();\n    JObject jObject = JObject.Parse(json);\n    foreach (var item in jObject)\n    {\n        JToken jPlace = jObject[item.Key];\n        float latitude = (float)jPlace["Latitude"];\n        float longitude = (float)jPlace["Longitude"];\n        string name = (string)jPlace["Name"];\n        places.Add(new Place { ID = item.Key, Name = name, Latitude = latitude, Longitude = longitude });\n\n    }\n}	0
20438225	20438184	What are the rules for "safe" lifting of local variables referenced in a lambda expression?	for(int i = 0; i < n; i++) {\n    int index = i;\n    DoSomething(delegate() {\n        myArray[index] = /* something */;\n    });\n}	0
4644479	4644297	Equivalent to C# null in managed c++	bool Test::TestStringNumber(String^ testData)\n{\n  return !String::IsNullOrEmpty( testData );\n}	0
31111118	31103858	Run an activity on application start to fetch data from the internet	Task.Run(() => {\n  return FetchData();\n}).ContinueWith(task => {\n  // process the result of FetchData here.\n  // this can be another thread, so watch out, if you want to modify UI, \n  // you must do it in RunOnUiThread()\n});	0
2734289	2734271	Best way to test if an object is in a set of objects?	if (new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) }.Contains(obj.GetType()))	0
9120686	9119444	Copying a part of a byte[] array into a PDFReader	if (outbyte != null && outbyte.Length > 0 && retval > 0)\n{\n    Array.Copy(outbyte, 0, currentDocument.Data, startIndex, retval);\n}	0
4882805	4876839	Creating LinFu interceptors for all types within an assembly	Func<IServiceRequestResult, bool> shouldInterceptServiceInstance = request=>request.ServiceType.Name.EndsWith("Repository");\n\nFunc<IServiceRequestResult, object> createProxy = request =>\n{\n   // TODO: create your proxy instance here\n   return yourProxy;\n};\n\n// Create the injector and attach it to the container so that you can selectively\n// decide which instances should be proxied\nvar container = new ServiceContainer();\nvar injector = new ProxyInjector(shouldInterceptServiceInstance, createProxy);\ncontainer.PostProcessors.Add(injector);\n\n// ...Do something with the container here	0
286652	286639	Get the name of a property by passing it to a method	static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression)\n{\n    var member_expression = expression.Body as MemberExpression;\n    if (member_expression == null)\n    return;\n\n    var member = member_expression.Member;\n    if (member.MemberType != MemberTypes.Property)\n    return;\n\n    var property = member as PropertyInfo;\n    var name = property.Name;\n\n    // ...\n}	0
28648706	28648570	Copy from Excel using C#	Range range = _workSheet .UsedRange;\n\nint rows = range.Rows.Count;\nint cols = range.Columns.Count;\n\n// nested loops to take values from used range of cell one by one\nfor(int r=1; r <= rows; r++)\n    for(int c=1; c <= cols; c++)\n        object cellValue = range.Cells[r,c].Value2;\n\n// take values from one row\nint row = 1;\nfor(int c=1; c <= cols; c++)\n    object cellValue = range.Cells[row,c].Value2;	0
26180459	25569247	Telerik, How to export GridView to Excel in these circunstances?	RadGridView grid = new RadGridView();\n        grid.Columns.Add("Col1");\n        grid.Columns.Add("Col2");\n\n        for (int i = 0; i < 10; i++)\n        {\n            grid.Rows.Add("cell 1" , "cell 2");\n        }\n\n        ExportToExcelML exporter = new ExportToExcelML(grid);\n        exporter.RunExport("D:\\test.slx");	0
8604362	8604340	Best way to add an array of objects to a list of extended objects	extendedCustomerList.AddRange(customerArray.Select(\n    c => new ExtendedCustomer() {\n        Customer = c\n    }));	0
1678620	1673776	Preventing duplicate matches in RegEx	Regex r = new Regex(@"(\{[0-9]+\}|\[[^\[\]]+\])(?<!\1.*\1)",\n                    RegexOptions.Singleline);	0
21170769	21170720	Return only certain columns to JSON in LINQ	[WebMethod]\npublic static string getProjectByID(int id)\n{\n    using (dbPSREntities4 myEntities = new dbPSREntities4())\n    {\n        var thisProject = myEntities.tbProjects.Where(x => x.ProjectID == id);\n\n        var columns = thisProject.Select(x => new { x.ProjectContactFirstName, x.ProjectContactLastName }).ToList();\n\n        JavaScriptSerializer serializer = new JavaScriptSerializer();\n\n        var json = serializer.Serialize(columns); \n\n        return json;\n    }\n}	0
14387570	14387502	Attempting to populate a dropdownlist through LINQ to entities in C#	ddlSemester.DataSource = semester.ToList();	0
2854635	2854438	How to generate a cryptographically secure Double between 0 and 1?	// Step 1: fill an array with 8 random bytes\nvar rng = new RNGCryptoServiceProvider();\nvar bytes = new Byte[8];\nrng.GetBytes(bytes);\n// Step 2: bit-shift 11 and 53 based on double's mantissa bits\nvar ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);\nDouble d = ul / (Double)(1UL << 53);	0
1728308	1728286	How to get/set the position of the mouse relative from the application window?	Point p = this.PointToClient(Cursor.Position);	0
17296674	17296592	How do you subtract from a negative integer but add to a positive?	int IncOrDec(int arg)\n{\n    return arg >= 0 ? ++arg : --arg;\n}	0
11703335	11703050	how to create a thread	Suspend()\nResume(), (except in some thread ctors)\nJoin()\nAbort()\nIsAlive()	0
33982032	33981890	Converting lots of files from xls to xlsx with Microsoft Compatibility Pack	var convertProcess = \n    Process.Start(@"c:\Program Files (x86)\Microsoft Office\Office12\excelcnv.exe",\n                  string.Format(@" -nme -oice {0} {1}", filename, destinationFilename));\nconvertProcess.WaitForExit();	0
31506853	31506820	Regular Expression matching empty string before a character in c#	^\s*'.*	0
1193474	1193340	An easy way of iterating over all unique pairs in a collection	for (int i = 0; i < list.Count-1; i++)\n  for (int j = i+1; j < list.Count; j++)\n     Foo(list[i], list[j]);	0
926843	830408	How to inspect XML streams from the debugger in Visual Studio 2003	(new StreamReader(xmlStream)).ReadToEnd();	0
14417156	14416613	using let keyword in linq to combine queries	var result = new ObjectThatContainsBothData() \n             {\n                 SomeProp1 = db.Peaches.Where(...).Select(...).ToList(),\n                 SomeProp2 = db.Apples.Where(...).Select(...).ToList()  \n             };	0
20058337	20058303	File.Delete isn't working to delete image from sub folder	var fixedPath = Server.MapPath("~/" + path);\n\nif (File.Exists(fixedPath))\n{\n  File.Delete(fixedPath);\n}	0
2970239	2970184	Issue with EnumWindows	Process.MainWindowHandle	0
8890999	8890618	How to convert Color back from string?	var p = test.Split(new char[]{',',']'});\n\nint A = Convert.ToInt32(p[0].Substring(p[0].IndexOf('=') + 1));\nint R = Convert.ToInt32(p[1].Substring(p[1].IndexOf('=') + 1));\nint G = Convert.ToInt32(p[2].Substring(p[2].IndexOf('=') + 1));\nint B = Convert.ToInt32(p[3].Substring(p[3].IndexOf('=') + 1));	0
23708828	23698553	Is it possible to keep a list of open generic types in one place?	public class MessageProcessor\n{\n    private static class MessageHandlerHolder<TMessage>\n    {\n        public static readonly ConditionalWeakTable<MessageProcessor, IMessageHandler<TMessage>> MessageHandlers =\n            new ConditionalWeakTable<MessageProcessor, IMessageHandler<TMessage>>();\n    }\n\n    public void AddHandler<TMessage>(IMessageHandler<TMessage> handler)\n    {\n        MessageHandlerHolder<TMessage>.MessageHandlers.Add(this, handler);\n    }\n\n    public void Handle<TMessage>(TMessage message)\n    {\n        IMessageHandler<TMessage> handler;\n        if (!MessageHandlerHolder<TMessage>.MessageHandlers.TryGetValue(this, out handler))\n            throw new InvalidOperationException("...");\n        handler.Handle(message);\n    }\n}	0
3482099	3465196	How to serialize two object with `one-to-many` relationship?	[XmlIgnore]	0
11852484	11848005	Assembly.LoadFrom with path and full assembly name	private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {\n    var name = new AssemblyName(args.Name);\n    string path = System.IO.Path.Combine(IntPtr.Size == 8 ? "x64" : "x86", name.Name + ".dll");\n    path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), path);\n    var asm = Assembly.LoadFrom(path);\n    var found = new AssemblyName(asm.FullName);\n    if (name.Version != found.Version) throw new System.IO.FileNotFoundException(name.FullName);\n    return asm;\n}	0
23198559	23198359	How to get data from observablecollection and display into console application in c#?	for (int i = 0; i < object1.Count; i++)\n {\n      Console.WriteLine(string.Concat(object1[i].item1, "---", object1[i].Item2)\n }	0
11750074	11749842	Is there a better way to trim whitespace and other characters from a string?	text = Regex.Replace(text, @"^[\s,]+|[\s,]+$", "");	0
33237002	33146325	How do I add in an save dialogue function in my export to excel codes?	Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n    Response.AddHeader("content-disposition", "attachment;  filename=products.xlsx");\n    excel.SaveAs(memoryStream);\n    memoryStream.WriteTo(Response.OutputStream);\n    Response.Flush();\n    Response.End();	0
9347925	9347912	how to validate two controls using one validator	protected void Button1_Click(object sender, EventArgs e)\n{\n    if (TextBox1.Text == null) \n    {\n        if (TextBox2.Text == null) \n        {\n            errorMsg.InnerText = "Error" //use a span with runat server\n        }\n    }\n}	0
10522069	10522025	Timing of parallel actions using the Task Parallel Library in C#	public class Piggy { \n   public void GreedyExperiment() { \n       Thread.Priority = ThreadPriority.Highest;\n       for (var i=0;i<1000000000;i++) {\n           var j = Math.Sqrt(i / 5);\n       }\n   }\n}	0
18285123	18284208	Data table with x columns built from 2D array with index?	DataTable dt = new DataTable();\ndt.Columns.Add("Date");\ndt.Columns.Add("DateLabel1");\n\nDataRow dr = dt.NewRow();\ndr[0] = date;\ndr[1] = value;\ndt.Rows.Add(dr);\n\ndr = dt.NewRow();\ndr[0] = date1;\ndr[1] = value1;\ndt.Rows.Add(dr);	0
8777775	8777643	In DDD, why they often make use of methods instead of properties?	DateTime.Now	0
32443152	32070262	Performance counters over custom period of time	// load performance counter\nvar numOfCalls = new PerformanceCounter(...);\n\n// read initial value for the period\nnumOfCalls.NextValue();\n\n// wait desired period\nThread.Sleep(5000);\n\n// read final value, the counter will internally calculate it based on the two samples\nnumOfCalls.NextValue();	0
6330411	6328822	Adding newer prices to old one which builds up to the total price in a textbox in C#	if (boxes[i].Checked == true)\n{\nselect += SecondMenuList[i].ToString() + "   :  " + "\t\t" +\n    Check[i].ToString("c") + "\r\n";\n\nPrice += Check[i];\n\nTotalPrice = Price.ToString("c");\ntxtTotalPrice.Text = (String.IsNullOrEmpty(txtTotalPrice.Text)?0:(Int32.Parse(txtTotalPrice.Text)+TotalPrice)).ToString();\n}	0
8244966	8244827	How would I change the border color of a button?	buttonName = "btn" + y.ToString() + x.ToString();\nButton btn = this.Controls.Find(buttonName, true)[0] as Button;\nbtn.BackColor = System.Drawing.Color.Blue;\nbtn.FlatStyle = FlatStyle.Flat\nbtn.FlatAppearance.BorderColor = Color.Red;\nbtn.FlatAppearance.BorderSize = 1;	0
24138192	24134346	How to Send bytes array in dataset and read from it	for (var i = 0; i < images.Count(); i++)\n                {\n\n                    DataRow row = dt.NewRow();\n                    row["id"] = images[i].id;\n                    row["ProjectIcons"] = Convert.ToBase64String(images[i].ProjectIcons);//convert here byte array to base64\n                    dt.Rows.Add(row);\n                }	0
31172938	31170814	Entity Framework 6: Creating database with multiple contexts	var migrationConfig = new MyApp.Data.Migrations.Configuration\n        {\n            TargetDatabase = new DbConnectionInfo(tenantProfile.ConnectionString, "MySql.Data.MySqlClient")\n        };\n        var migrator = new DbMigrator(migrationConfig);\n        migrator.Update();	0
461766	461742	How to convert an IPv4 address into a integer in C#?	// IPv4\nint intAddress = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes(), 0);\nstring ipAddress = new IPAddress(BitConverter.GetBytes(intAddress)).ToString();	0
18256649	18256581	How to make last row in a dataGridView on a Windows Form to be displayed all the time while still allowing the remaining rows to scroll	dataGridView2.ColumnHeadersVisible = false;	0
28540325	28417086	Wp8:Not able to get checkBox in listbox	private void GetItemsRecursive(DependencyObject lb)\n{\n    var childrenCount = VisualTreeHelper.GetChildrenCount(lb);\n\n    for (int i = 0; i < childrenCount; i++)\n    {\n        DependencyObject child = VisualTreeHelper.GetChild(lb, i);\n\n        if (child is CheckBox) // specific/child control \n        {\n            CheckBox targeted_element = (CheckBox)child;\n\n            targeted_element.IsChecked = true;\n\n            if (targeted_element.IsChecked == true)\n            {\n\n                return;\n            }\n        }\n\n        GetItemsRecursive(child);\n    }\n}	0
26052947	26052865	Simulating a mouse pointer click (can move but can't click)	[DllImport("user32.dll")]\nstatic extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);\n\n[Flags]\npublic enum MouseEventFlags\n{\n    LEFTDOWN = 0x00000002,\n    LEFTUP = 0x00000004,\n    MIDDLEDOWN = 0x00000020,\n    MIDDLEUP = 0x00000040,\n    MOVE = 0x00000001,\n    ABSOLUTE = 0x00008000,\n    RIGHTDOWN = 0x00000008,\n    RIGHTUP = 0x00000010\n}\n\n[System.Runtime.InteropServices.DllImport("user32.dll")]\nstatic extern bool SetCursorPos(int x, int y);\n\npublic static void LeftClick(int x, int y)\n{\n    SetCursorPos(x, y);\n    mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);\n    mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);\n}	0
27005066	27004541	Usercontrol contains a combobox, but the Items set at design time are not in the run time	[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic ComboBox.ObjectCollection Item {\n  get { return baseComboBox.Items; }\n}	0
27462813	27462682	WPF set parent (Window)	var w = new Window();\nw.Owner = Window.GetWindow(this);\nw.Show();	0
8550737	8550726	How to excute some code only for the first asp:button click	protected void Button1_Click(object sender, EventArgs e)\n{\n    if (Session["Clicked"] == null)\n        Session["Clicked"] = true;\n    else {\n        // We already ran this function once, so do other stuff from now on\n        ...\n        return;\n    }\n\n   // Code below this comment will be executed only on the 1st button click\n   ...\n}	0
2847541	2847530	DateTime Format	someDateInstance.ToString("dd.MM.yyyy HH:mm:ss")	0
28172618	28172244	get the real file name from temp	string fileName = System.IO.Path.GetFileName(fullName); // "AAA.PDF.GGG.ORT"\nstring[] fileNameToken = fileName.Split('.');\nstring originalFileName = string.Format("{0}.{1}", fileNameToken[0], fileNameToken[1]);	0
9792164	9791962	What's the syntax to inherit documentation from another indexer?	cref="IInterface{T}.this[long,long]"	0
2013774	2013731	C#: How to simplify this string-of-numbers-to-various-date-parts-code	DateTime date;\nif (DateTime.TryParseExact(\n    digits, \n    new[] { "dd", "ddMM", "ddMMyyyy" }, \n    CultureInfo.InvariantCulture, \n    DateTimeStyles.None, \n    out date))\n{\n    int day = date.Day;\n    int month = date.Month;\n    int year = date.Year;    \n}	0
15953192	15952256	EventHandler with FormClosingEventArgs	private void label7_Click(object sender, EventArgs e)\n{\n    var result = MessageBox.Show("Are you sure you want to exit?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\n    if (result == DialogResult.Yes)\n    {\n       Application.Exit();\n    }\n}\n\nlabel7.Click += label7_Click;	0
13704707	13704560	How to pass Stringified JSON to C# Method?	public partial class _Default : Page \n{\n  [WebMethod]\n  public static string DoSomething(string myJsonData)\n  {\n    // deserialize your JSON\n    // do something cool with it\n  }\n}	0
30697534	30682737	Load DropNet user token and secret from a database in a C# WinForms application	UserAccountManagerBLL accMan = new UserAccountManagerBLL();\n\n        UserToken = accMan.GetToken(Email);\n        UserSecret = accMan.GetSecret(Email);\n\n        _Client = new DropNetClient(appKey, appSecret, UserToken, UserSecret);	0
31850526	31844465	Deserialized xml gives a null XElement	public class MyClass\n{\n    public DateTime MyDate { get; set; }\n\n    public string MyXml\n    {\n        set\n        {\n            //XML element should contain only one root element\n            //<MyXml> element act as root element\n            string myXml = "<myXml>"+ value +"</myXml>";\n            RootXml = XElement.Parse(myXml);\n        }\n    }\n\n    public XElement RootXml;\n\n}	0
24180219	24180075	How do you access the number of times a delegate has been called?	int callCount = 0;\nAction handler = () => callCount++;\n\n_testObj.TaskCompletedForItems += handler;\n// Do stuff\n\nAssert.AreEqual(expectedCount, callCount);	0
34566541	34566462	How do I manage multiple growing lists?	var minIndex = emd.IndexOf(emd.Min());	0
30582683	30582329	Get IWin32Window Parent Handle in VSTO Addin to Center saveFileDialog	public class WindowHandle : System.Windows.Forms.IWin32Window\n {\n      public WindowHandle(IntPtr handle)\n      {\n          _hwnd = handle;\n      }\n\n      public IntPtr Handle\n      {\n          get { return _hwnd; }\n      }\n\n      private IntPtr _hwnd;\n   }	0
26544172	26511088	Code first many to many relationship with attributes in relational table	public class BookStudent\n{\n    [Key, Column(Order = 0)]\n    public int BookID { get; set; }\n    [Key, Column(Order = 1)]\n    public int StudentID { get; set; }\n    public DateTime FromDate { get; set; }\n    public DateTime ToDate { get; set; }\n\n    //below two lines will define foreign key\n    public Student Student { get; set; }\n    public Book Book { get; set; }\n}\n\n\npublic class Context : DbContext\n{\n    public Context() : base("name=DefaultConnection") { }\n    public DbSet<Book> Books { get; set; }\n    public DbSet<Student> Students { get; set; }\n    public DbSet<BookStudent> BookStudents { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        //remove below code\n        //modelBuilder.Entity<Book>().HasMany<Student>(t => t.Students).WithMany(t => t.Books).Map(t =>\n        //{\n        //    t.MapLeftKey("BookId");\n        //    t.MapRightKey("StudentId");\n        //    t.ToTable("BookStudents");\n        //});\n    }\n}	0
19108938	18890932	How to avoid entering duplicate values into table through winform?	try\n{\n    object Name = cmd.ExecuteNonQuery();\n    MessageBox.Show("Client details are inserted successfully");\n    txtName.Clear();\n    txtContactPerson.Clear();\n    BindData();\n}\ncatch(Exception ex)\n{\n    //Handle exception, Inform User\n}\nfinally\n{\n    con.Close();\n}	0
4230441	4228692	how to open a database in a webMatrix C# file?	using WebMatrix.WebData;\nusing WebMatrix.Data;	0
7441569	7441061	Can a Windows Service take hours to shutdown gracefully?	protected override void OnShutdown() \n{\n    base.RequestAdditionalTime(MaxTimeout);\n    serviceCore.OnShutdown();\n    Stop(); \n}	0
18169648	18169640	Can I combine a LINQ and a foreach that I use to add objects to a collection?	objectiveDetail1.Where(a => objectiveDetail2.All(\n                       b => b.ObjectiveDetailId != a.ObjectiveDetailId))\n                      .ToList().ForEach(_uow.ObjectiveDetails.Add);	0
5760682	5354894	How do I invoke a validation attribute for testing?	[TestMethod]\npublic void PhoneNumberIsValid()\n{\n    var dude = new Person();\n    dude.PhoneNumber = "666-978-6410";\n\n    var result = Validator.TryValidateObject(dude, new ValidationContext(dude, null, null), null, true);\n\n    Assert.IsTrue(result);\n}	0
17217398	17217095	Application dropping connection to Salesforce, any way to retry on Exception?	For i as Integer = 1 To 3\n    Try\n         qr = sfservice.queryMore(qr.queryLocator)\n         Exit For\n    Catch ex as Exception\n    End Try\nNext i	0
3540512	3540447	How to get the Screen position of a control inside a group box control?	Point p = groupBox1.PointToScreen(button1.Location);	0
10550090	10549788	How to perform multiple Linq to Entities orderings dynamically	using (var db = new MyContainer())\n{\n    var orderSpec = orderSpecs[0];\n    IQueryable<DbVersion> dVersions = null;\n\n    var mapping = new Dictionary<int, Func<DbVersion, object>>()\n    {\n        { 0, ver => ver.Name },\n        { 1, ver => ver.Built },\n        { 2, ver => ver.Id }\n    };\n\n    if (orderSpec.Descending)\n        dVersions = db.Versions.OrderByDescending(mapping[orderSpec.Column]);\n    else\n        dVersions = db.Versions.OrderBy(mapping[orderSpec.Column]);\n\n    foreach (var spec in orderSpecs.Skip(1))\n    {\n        if (spec.Descending)\n            dVersions = dVersions.ThenByDescending(mapping[spec.Column]);\n        else\n            dVersions = dVersions.ThenBy(mapping[spec.Column]);\n    }\n}	0
1789478	1786385	SQL Server Search, how to return the total count of rows?	;WITH SearchArticles (aid, cnt, headline, descr, cid, img, datepub) as (  \nSELECT DISTINCT\n            a.ArticleID, \n            COUNT(*) AS KeywordMatch,\n            a.Headline,\n            a.ShortDescription,\n            a.CategoryID,\n            a.ArticleSectionImage,\n            a.DatePublished\n        FROM \n            Article a\n        JOIN SearchWords sw ON a.ArticleID = sw.ArticleID\n        WHERE\n            EXISTS \n            (\n                    SELECT \n                      1 \n                    FROM \n                      iter_charlist_to_tbl(@temp, ' ') s \n                    WHERE\n                      s.nstr = sw.SearchWord\n            )\n            AND\n                    a.ArticleState = 3      \n        GROUP BY \n            a.ArticleID, a.Headline, a.ShortDescription, a.CategoryID,\n            a.ArticleSectionImage, a.DatePublished\n) SELECT COUNT(*) FROM SearchArticles	0
6836796	6836691	Getting all permutations for weightings according to an interval	static void Main(string[] args)\n{\n    var nbSystems = 2;\n    var nbSteps = 3;\n\n    var steps = GetSteps(0, 1, nbSteps).Select(n => Math.Round(n, 2)).ToArray();\n    foreach (var seq in GetCombinations(steps, nbSystems))\n        Console.WriteLine(string.Join(", ", seq));\n}\n\nprivate static IEnumerable<decimal> GetSteps(decimal min, decimal max, int count)\n{\n    var increment = (max - min) / count;\n    return Enumerable.Range(0, count + 1).Select(n => min + increment * n);\n}\n\nprivate static IEnumerable<IEnumerable<T>> GetCombinations<T>(\n    ICollection<T> choices, int length)\n{\n    if (length == 0)\n    {\n        yield return new T[0];\n        yield break;\n    }\n\n    foreach (var choice in choices)\n        foreach (var suffix in GetCombinations(choices, length - 1))\n            yield return Enumerable.Concat(new[] { choice }, suffix);\n}	0
16436711	16436318	Getting index of element by attribute value	using System;\nusing System.Linq;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main()\n        {\n            string xml = "<root><if attribute=\"cat\"></if><if attribute=\"dog\"></if><if attribute=\"rabbit\"></if></root>";\n            XElement root = XElement.Parse(xml);\n\n            int result = root.Descendants("if")\n                .Select(((element, index) => new {Item = element, Index = index}))\n                .Where(item => item.Item.Attribute("attribute").Value == "dog")\n                .Select(item => item.Index)\n                .First();\n\n            Console.WriteLine(result);\n        }\n    }\n}	0
30918177	30918054	Application self-closing on demand	public static void Main(...)\n{\n    while(true)\n    {\n        // do job\n\n        if(exit condition)\n            return;\n    }\n}	0
11510381	11505781	Save background image of slide	For x = s.Shapes.Count to 1 Step -1\n  sShapes(x).Delete\nNext	0
2593422	2593386	Accessing ImageButton Contents	((Planet)((ImageButton)e.OriginalSource).Content).DistanceFromTheSun	0
10669518	10665288	How to prevent displaying "program terminated Unexpectedly" window?	[DllImport("kernel32.dll", SetLastError = true)]\n    static extern int SetErrorMode(int wMode);\n\n    [DllImport("kernel32.dll")]\n    static extern FilterDelegate SetUnhandledExceptionFilter(FilterDelegate lpTopLevelExceptionFilter);\n    public delegate bool FilterDelegate(Exception ex);\n\n    App()\n    {\n        FilterDelegate fd = delegate(Exception ex)\n        {\n            return true;\n        };\n        SetUnhandledExceptionFilter(fd);\n\n        SetErrorMode(SetErrorMode(0) | 0x0002 );\n    }	0
10918283	10911475	Specify a Triangle's Vertices based on radius and center coordinate	void BuildTriangle(Vector2 Center, float Radius, float Angle, Vector2[] tri)\n{\n   for (int i=0; i<3; i++)\n   {\n      t[i].X = Center.X + Radius * (float) Math.Cos(Angle + i * 2 * MathHelper.PI/3);\n      t[i].Y = Center.Y + Radius * (float) Math.Sin(Angle + i * 2 * MathHelper.PI/3);\n   }\n}	0
12687525	12687453	How to loop over lines from a TextReader?	string line;\nwhile ((line = myTextReader.ReadLine()) != null)\n{\n    DoSomethingWith(line);\n}	0
31986700	31983771	How to add a new row to Winforms DataGridView in my custom column	DataGridView.NotifyCurrentCellDirty(true);	0
2331245	2331225	How to refresh ObjectContext cache from db?	Context.Refresh(RefreshMode.StoreWins, somethings);	0
10847045	10846886	Programmatically Pressing Buttons on a Web Page	string postDataStr = string.Format("resync=true&scanscheduled=&otherpara=xyz");\nbyte[] postData = Encoding.ASCII.GetBytes(postDataStr);\n\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("http://server1/rsyncwebgui.php"));\nreq.Method= "POST";\nreq.ContentType = "application/x-www-form-urlencoded";\nreq.ContentLength = postData.Length;\nusing(var reqStream = req.GetRequestStream())\n{\n    reqStream.Write(postData, 0, postData.Length);\n}\n\nHttpWebResponse response = (HttpWebResponse )req.GetResponse();	0
18179015	18178888	Does a singleton need to be refreshed with data from webservice?	public override T GetAndSet<T>(string key, ref int duration, Func<T> method) {\n    var data = _cache == null ? default(T) : (T) _cache[key];\n\n    if (data == null) { //check\n        lock (sync) { //lock\n\n            //this avoids that a waiting thread reloads the configuration again\n            data = _cache == null ? default(T) : (T) _cache[key];\n            if (data == null) { //check again\n                data = method();\n\n                if (duration > 0 && data != null) {                 \n                    _cache.Insert(key, data, null, DateTime.Now.AddSeconds(duration), Cache.NoSlidingExpiration);\n                }\n            }\n        }\n    }\n\n    return data;\n}	0
22780672	22780478	Referencing an element in an array inside a list	public Cell GetCell(List<Cell[]> list, int row, int cell)\n{\n    if (list.Count < row || list[row].Length < cell)\n        return;\n\n    return list[row][cell];\n}	0
7361475	7361448	Windows Forms load on base of Windows	System.OperatingSystem osInfo = System.Environment.OSVersion	0
986884	986790	How to place a form in help-requested mode?	[DllImport("user32.dll")] private static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wp, IntPtr lp);\nprivate const int WM_SYSCOMMAND = 0x112;\nprivate const int SC_CONTEXTHELP = 0xf180;\n\nprivate void button1_Click(object sender, EventArgs e) {\n  button1.Capture = false;\n  SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_CONTEXTHELP, IntPtr.Zero);\n}	0
19318701	19313949	How can I remove a phrase from a string?	var result = Regex.Replace(yourStringVariable, "(?<=(&code=|&number=|&fromdate=|&todate=))[^&]+", "");	0
17962868	17962784	Using MailMessage to send emails in C#	MailMessage emailMessage = new MailMessage();\n        emailMessage.From = new MailAddress("account2@gmail.com", "Account2");\n        emailMessage.To.Add(new MailAddress("account1@gmail.com", "Account1"));\n        emailMessage.Subject = "SUBJECT";\n        emailMessage.Body = "BODY";\n        emailMessage.Priority = MailPriority.Normal;\n        SmtpClient MailClient = new SmtpClient("smtp.gmail.com", 587);\n        MailClient.EnableSsl = true;\n        MailClient.Credentials = new System.Net.NetworkCredential("account2@gmail.com", "password");\n        MailClient.Send(emailMessage);	0
13177526	13177139	How to use Rowspan in Gridview for 1st Column only	void GridView31_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow )\n    {\n        if (e.Row.RowIndex % 4 == 0)\n        {\n            e.Row.Cells[0].Attributes.Add("rowspan", "4");\n        }\n        else\n        {\n            e.Row.Cells[0].Visible = false;\n        }\n    }\n}	0
25605299	25604920	how could i store docs pdf image files in database using stored procedure in C#	SqlParameter fileP = new SqlParameter("@Upload", SqlDbType.VarBinary);\nfileP.Value = bytes; //Here, you're assigning the value to the parameter.\nSqlCommand myCommand = new SqlCommand();\nmyCommand.Connection = someSqlConnection;\nmyCommand.CommandText = "YOUR UPDATE STATEMENT";\nmyCommand.Parameters.Add(fileP);\nmyCommand.ExecuteNonQuery();	0
13819845	13819756	ASP Login template custom drop down list	DropDownList ddl = (DropDownList)Login1.LoginView.FindControl("ddlDomain");	0
25338418	25338267	Extract string from HTML	var html = "<td class=\"Labels\"> CODE (Sp Number): </td><td width=\"40.0%\"> KLE3KAN918D429</td>";\nvar labelIndex = html.IndexOf("<td class=\"Labels\">");\nvar pctIndex = html.IndexOf("%", labelIndex);\nvar closeIndex = html.IndexOf("<", pctIndex);\nvar key = html.Substring(pctIndex + 3, closeIndex - pctIndex - 3).Trim();\nSystem.Diagnostics.Debug.WriteLine(key);	0
25633580	25608513	my DataGridView is blank after setting DataSource for it	public Worksheet exportToExcel(System.Data.DataTable dataTable)\n{\n    //Wrap in using statements to make sure controls are disposed\n    using (Form frm = new Form())\n    {\n        using(DataGridView dgv = new DataGridView())\n        {   \n            //Add dgv to form before setting datasource                             \n            frm.Controls.Add(dgv);  \n            dgv.DataSource = dataTable;   \n            return exportToExcel(dgv);\n        }\n    }   \n}	0
8837306	8837278	Finding if a file is in use - specifically an xls file	File.Open("worksheet.xls", FileMode.Open, FileAccess.Read, FileShare.None);	0
7454547	7445824	Foreach Sub Item In ListView	for (int i = 0; i < listView1.Items.Count; i++)\n{\n    int ii = 1;\n    MessageBox.Show(listView1.Items[i].SubItems[ii].Text);\n    ii++;\n}	0
33092142	33091967	Bind Same Data To Multiple Drop Down Lists	var employees = new List<ListItem>\n{\n    new ListItem("Fran", "14"),\n    new ListItem("George", "3")\n};\n\nddlemp1.DataSource = employees;\nddlemp1.DataBind();\n\nddlemp2.DataSource = employees;\nddlemp2.DataBind();\n\n...\n\nddlemp5.DataSource = employees;\nddlemp5.DataBind();	0
12889861	12889785	asp.net insert an element by index into an arraylist	al.Insert(1, "bcd");	0
11724405	11686690	Handle ModelState Validation in ASP.NET Web API	using System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.Filters\n{\n    public class ValidationActionFilter : ActionFilterAttribute\n    {\n        public override void OnActionExecuting(HttpActionContext actionContext)\n        {\n            var modelState = actionContext.ModelState;\n\n            if (!modelState.IsValid)\n                actionContext.Response = actionContext.Request\n                     .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);\n        }\n    }\n}	0
255965	255955	How do I make a Windows Forms control readonly?	Color clr = textBox1.BackColor;\n    textBox1.ReadOnly = true;\n    textBox1.BackColor = clr;	0
6337725	6337680	String was not recognized as a valid DateTime	string format = "dd/MM/yyyy hh:mm tt";\nstring stringDate = DateTime.Now.ToString(format, CultureInfo.InvariantCulture);\nDateTime dateTime = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);	0
28340639	28278238	how to download Pdf to client machine	System.IO.FileStream file = new System.IO.FileStream(Server.MapPath("~/" + fileUploadLoc" System.IO.FileMode.OpenOrCreate);\n PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, file);	0
15972589	15972442	Issue comparing String to array, then returning value from a second array?	Dictionary<string,string> countriesByDialingCode = new Dictionary<string,string>();\n\n...\n\ncountriesByDialingCode.Add("00", "USA");\ncountriesByDialingCode.Add("44", "USA");\n\n...\n\nstring country = countriesByDialingCode["44"];	0
860845	858668	Castle Windsor: How do I register a factory method, when the underlying type isn't accessible to my assembly?	[TestFixture]\npublic class WindsorTests {\n    public interface IDataService {}\n\n    public class DataService: IDataService {}\n\n    public interface IDataFactory {\n        IDataService Service { get; }\n    }\n\n    public class DataFactory: IDataFactory {\n        public IDataService Service {\n            get { return new DataService(); }\n        }\n    }\n\n    [Test]\n    public void FactoryTest() {\n        var container = new WindsorContainer();\n        container.AddFacility<FactorySupportFacility>();\n        container.AddComponent<IDataFactory, DataFactory>();\n        container.Register(Component.For<IDataService>().UsingFactory((IDataFactory f) => f.Service));\n        var service = container.Resolve<IDataService>();\n        Assert.IsInstanceOfType(typeof(DataService), service);\n    }\n}	0
20576231	20575775	change setter value in style	private void btnCancel_Click_1(object sender, RoutedEventArgs e)\n    {\n        var button = sender as Button;\n        if (button != null) button.FontSize = 30;\n    }	0
239409	239381	How to Convert complex XML structures to DataSet with multiple tables	DataSet myDataSet = new DataSet();\n\nmyDataSet.ReadXml("myXmlFile.xml");	0
27175838	27139967	How to make Aggregate Root method only accessible for a Domain Event and nothing else.	public void someMethod(SomeOccuredEvent event)	0
5977300	5936891	Can't load Flowdocuments with xml entites from textfile	public FlowDocument Load(string path)\n    {\n        using (StreamReader sReader = System.IO.File.OpenText(path))\n        {\n            using (Stream s = sReader.BaseStream)\n            {\n                return (FlowDocument)XamlReader.Load(s);\n            }\n        }\n    }	0
10069695	6841285	Change the size of scrollbar in winforms	this.vScrollBar1.LargeChange = this.vScrollBar1.Maximum / 2;	0
910663	910591	Extension method for Dictionary of Dictionaries	class SomeType { }\nstatic void Main()\n{\n    var items = new Dictionary<long, Dictionary<int, SomeType>>();\n    items.Add(12345, 123, new SomeType());\n}\n\npublic static void Add<TOuterKey, TDictionary, TInnerKey, TValue>(\n        this IDictionary<TOuterKey,TDictionary> data,\n        TOuterKey outerKey, TInnerKey innerKey, TValue value)\n    where TDictionary : class, IDictionary<TInnerKey, TValue>, new()\n{\n    TDictionary innerData;\n    if(!data.TryGetValue(outerKey, out innerData)) {\n        innerData = new TDictionary();\n        data.Add(outerKey, innerData);\n    }\n    innerData.Add(innerKey, value);\n}	0
5459623	5459595	Grid Star-Size in code behind	rowDefinition.Height = new GridLength(0.5, GridUnitType.Star);	0
1896568	1896554	Working with DefaultOrEmpty in LINQ	var select = str.Select(s => String.IsNullOrEmpty(s) ? "nodata" : s);	0
32267732	32267218	Double if else without brackets	if(condition)\n//enter if statement\n//leave if statement	0
12701615	12667586	How To update Text box contents after a selection change in ListPicker in windows phone 7?	{\n        lp = new ListPicker();            \n        lp.BorderBrush = new SolidColorBrush(Colors.White);\n        lp.BorderThickness = new Thickness(3);\n        lp.Margin = new Thickness(12, 5, 0, 0);\n        lp.Width = 400;\n        int x = noofrows();\n        for (int a = 1; a <= x; a++)\n        {\n            string str1 = returnID(a);\n            lp.Items.Add(str1);                \n        }\n        lp.SelectionChanged += (s, e) =>\n        {\n            selectedItem = Convert.ToInt32(lp.SelectedItem);\n            txtid.Text = selectedItem.ToString();\n            txtName.Text = SelectName(selectedItem);\n            txtAge.Text = SelectAge(selectedItem);\n            txtContact.Text = SelectContact(selectedItem);\n        };\n        LayoutRoot.Children.Add(lp);    \n\n    }	0
18071813	18071778	.NET MySqlCommand @ placeholder conflicted with MySQL variable	Database=testdb;Data Source=localhost;User Id=root;Password=hello;Allow User Variables=True	0
906293	906100	Run one instance from the application	string procName = Process.GetCurrentProcess().ProcessName;\n  if (Process.GetProcessesByName(procName).Length == 1)\n  {\n      ...code here...\n  }	0
7148471	7146567	winforms listview not showing items in detailsview	using System;\nusing System.Windows.Forms;\n\npublic class LVTest : Form {\n    public LVTest() {\n        ListView lv = new ListView();\n        lv.Columns.Add("Header", 100);\n        lv.Columns.Add("Details", 100);\n        lv.Dock = DockStyle.Fill;\n        lv.Items.Add(new ListViewItem(new string[] { "Alpha", "Some details" }));\n        lv.Items.Add(new ListViewItem(new string[] { "Bravo", "More details" }));\n        lv.View = View.Details;\n        Controls.Add(lv);\n    }\n}\n\npublic static class Program {\n    [STAThread] public static void Main() {\n        Application.Run(new LVTest());\n    }\n}	0
813409	809934	Assembly.LoadFrom - using Evidence overload to verify strong name signature	var assemblyName = new AssemblyName(<fully qualified type name>);\nassemblyName.CodeBase = <path to assembly>\n\nAssembly.Load(assemblyName);	0
4392417	4392371	How to retrieve the url address of a page hosting composite control?	Request.Url	0
32245142	32230545	XAML - Dynamic creation of different GridViews from only a Source	var result = from act in list\n             group act by act.groupname into grp\n             orderby grp.Key\n             select grp;	0
12792310	12791595	Unable to add QuickTime control to Windows Forms project in Visual Studio	Apple QuickTime Control 2.0	0
23279228	23279120	How to limit scope of a constant to method/block	public int SomeMethod(int a) {\n    const int SomeCompileTimeConstant = 10; // obviously this doesn't exist\n\n    return a + SomeCompileTimeConstant;\n}	0
18119444	18119018	How to use StopWatch multiple times in C#?	static void Main(string[] args)\n    {\n        Console.WriteLine("Method 1 Time Elapsed (ms): {0}", TimeMethod(Method1));\n        Console.WriteLine("Method 2 Time Elapsed (ms): {0}", TimeMethod(Method2));\n    }\n\n    static long TimeMethod(Action methodToTime)\n    {\n        Stopwatch stopwatch = new Stopwatch();\n        stopwatch.Start();\n        methodToTime();\n        stopwatch.Stop();\n        return stopwatch.ElapsedMilliseconds;\n    }\n\n    static void Method1()\n    {\n        for (int i = 0; i < 100000; i++)\n        {\n            for (int j = 0; j < 1000; j++)\n            {\n            }\n        }\n    }\n\n    static void Method2()\n    {\n        for (int i = 0; i < 5000; i++)\n        {\n        }\n    }\n}	0
31441085	31440996	How can store variable while select query in LINQ?	var q = from p in m.TblOzvs.AsEnumerable()\n         where (p.OzviyatNumber == txtSearch.Text) \n         let calcVal = Calculate._RPMajmoSoodeGhest(p.OzviyatNumber)\n         select new mylist\n         {                     \n             Col1 = p.OzviyatNumber.ToString(),\n             Col2 = p.Name,\n             Col3 =  calcVal[1],              \n             Col4 = calcVal[0]\n         };	0
30576842	30574849	How to mark a multiple selection on a DataGrid control?	Dispatcher.BeginInvoke(new Action(delegate\n            {\n                foreach (var item in e.RemovedItems)\n                {\n                    SelectedItems.Add(item);\n                }\n                SelectedItemsList.Add(SelectedItem);\n            }), System.Windows.Threading.DispatcherPriority.ContextIdle, null);	0
1770218	1770155	XmlDocument.Save omitting elements	class Program\n{\n    static void Main(string[] args)\n    {\n        var listener = new TcpListener(IPAddress.Loopback, 9999);\n        listener.Start();\n        while (true)\n        {\n            var client = listener.AcceptTcpClient();\n            using (var stream = client.GetStream())\n            using (var reader = new StreamReader(stream))\n            {\n                Console.WriteLine(reader.ReadToEnd());\n            }\n        }\n    }\n}	0
7611177	7611080	Filtering a list with linq	var filter = productList.Where(p => p.Product.IsFamily)\n                        .GroupBy(p => p.Product.FamilySku)\n                        .Select(grp => grp.OrderByDescending(p => p.Product.FamilySku).First())\n                        .Concat(productList.Where(p => !p.Product.IsFamily));	0
12039806	12020367	C# DataGridView (CheckBox) Cell Click Multiple Callbacks	void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    if (dataGridView1.Columns[e.ColumnIndex].Name == "checkboxcolumn")\n    {\n        Console.WriteLine("Click");\n        bool isChecked = (bool)dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue;\n        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !isChecked;\n        dataGridView1.EndEdit();\n    }\n}	0
30355099	30354313	Getting Last Used Column in Range Excel	for i = 1 to activesheet.usedrange.columns.count\nif cells(2,i).value = format(date,"dd/mm/yy") ' input your desired date format here\nmsgbox cells(2,i).column\nend if	0
2668964	2668890	Need file read in from form load	private void mainForm_Load(object sender, EventArgs e) \n{\n    string fileName = @"..\..\MealDeliveries.txt";\n\n    if (!File.Exists(fileName))\n    {\n        MessageBox.Show("File not found!");\n        return;\n    }\n\n    using (StreamReader sr = new StreamReader(fileName))\n    {\n        //first line is delivery name \n        string strDeliveryName = sr.ReadLine(); \n        while (strDeliveryName != null)\n        { \n            //other lines \n            Delivery d = new Delivery(strDeliveryName, sr.ReadLine(),\n                                      sr.ReadLine(), sr.ReadLine(),\n                                      sr.ReadLine(), sr.ReadLine(),\n                                      sr.ReadLine());\n            mainForm.myDeliveries.Add(d);\n\n            //check for further values\n            strDeliveryName = sr.ReadLine();\n        }\n    }\n    displayDeliveries();\n}	0
4639448	4584080	schema validation XML	private void ValidationCallBack(object sender, ValidationEventArgs e)\n{  \n    throw new Exception();\n}\n\npublic bool validate(string sxml)\n{\n    try\n    {\n        XmlDocument xmld=new XmlDocument ();\n        xmld.LoadXml(sxml);\n        xmld.Schemas.Add(null,@"c:\the file location");\n        xmld.validate(ValidationCallBack);\n        return true;\n    }\n    catch\n    {\n        return false;\n    }\n}	0
34525069	34524947	Add data at the end of existing data in resource file	var reader = new ResXResourceReader("filename");\nvar node = reader.GetEnumerator();\nvar writer = new ResXResourceWriter("filename");\nwhile (node.MoveNext())\n{\n    writer.AddResource(node.Key.ToString(), node.Value.ToString());\n}\nvar newNode = new ResXDataNode("name", "value");\nwriter.AddResource(newNode);\nwriter.Generate();\nwriter.Close();	0
23358233	23357764	how to include cpp header files in a c# program	[StructLayout(LayoutKind.Sequential)]	0
8646798	8646770	C# how to stop the program after a certain time?	try \n{\n    terminal.Bind(client);     \n}\ncatch(Exception ex)\n{\n    return;\n}	0
1566367	1555278	How to create CodeFunction2 with IEnumerable<> Type?	string returnType = "System.Collections.Generic.IEnumerable<" + tableNameAsSingular + ">"; \nCodeFunction2 finderFunction = (CodeFunction2)entityServiceClass.AddFunction("Get" + table.Name, vsCMFunction.vsCMFunctionFunction, returnType, -1, vsCMAccess.vsCMAccessPublic, null);	0
25749920	25749235	Get application directory in both console application and its unit tests	// Get normal filepath of this assembly's permanent directory\nvar path = new Uri(\n        System.IO.Path.GetDirectoryName(\n        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)\n    ).LocalPath;	0
9118510	9118497	How to create a Text file and save it to a shared-directory?	\\server\directory\Public\3rd\ASN\1175_0001.txt	0
417020	416968	get attribute name in addition to attribute value in xml	if (reader.HasAttributes) {\n  Console.WriteLine("Attributes of <" + reader.Name + ">");\n  while (reader.MoveToNextAttribute()) {\n    Console.WriteLine(" {0}={1}", reader.Name, reader.Value);\n  }\n  // Move the reader back to the element node.\n  reader.MoveToElement();\n}	0
26181022	26145811	How to show the label for couple of seconds and show another label in form	private void Form3_Load(object sender, EventArgs e)\n    {\n        timer1.Interval = 5000;\n        timer1.Enabled = true;\n        timer1.Tick += new EventHandler(timer1_Tick);\n\n        timer2.Interval = 1000;\n        timer2.Start();\n    }\n\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        this.DialogResult = DialogResult.OK;\n        timer1.Stop();\n    }\n\n    int StopTime = 0;\n    private void timer2_Tick(object sender, EventArgs e)\n    {\n        StopTime++;\n        if (StopTime == 1)\n        {\n            label1.Text = "  Connecting to smtp server..";\n        }\n        if (StopTime == 2)\n        {\n            label1.Text = "     Fetching recipients..";\n        }\n        if (StopTime == 3)\n        {\n            label1.Text = "  Attaching G-code files..";\n        }\n        if (StopTime == 4)\n        {\n            label1.Text = "                Done!!";\n            StopTime = 0;\n            timer2.Stop();\n        }\n    }	0
16528259	16487936	how to save MemoryStream to JPEG in Windows 8 c#	private async void Save_Image(MemoryStream image)\n    {\n        // Launch file picker\n        FileSavePicker picker = new FileSavePicker();\n        picker.FileTypeChoices.Add("JPeg", new List<string>() { ".jpg", ".jpeg" });\n        StorageFile file = await picker.PickSaveFileAsync();            \n\n        if (file == null)\n            return;\n        using (Stream x = await file.OpenStreamForWriteAsync())\n        {\n            x.Seek(0, SeekOrigin.Begin);\n            image.WriteTo(x);\n        }\n\n    }	0
32054731	32054466	How to match timestamps of different formats	for (int i = 0; i < ListA.Count(); i++)\n{\n    bool found = false;\n\n    for (int j = 0; j < ListB.Count(); j++)\n    {\n        DateTime aItem = DateTime.ParseExact(ListA[i], "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);\n        DateTime bItem = DateTime.ParseExact(ListB[j], "HH:mm", System.Globalization.CultureInfo.InvariantCulture);\n\n        if (aItem.ToString("HH:mm") == bItem.ToString("HH:mm"))\n        {\n              if (!found)\n              {\n                  Console.WriteLine("{0}    {1}", ListA[i], ListB[j]);\n                  found = true;\n              }\n              else\n                  Console.WriteLine(ListA[i]);\n        }\n    }\n}	0
13223082	13223053	ASP.NET Application Object Getters and Setters	string[] usersTable = (string[])Application["users"];	0
14862495	14861185	How to add a texture to dynamically generated terrain vertices in xna	vertices[x + y * terrainWidth].TextureCoordinate.X = x;\nvertices[x + y * terrainWidth].TextureCoordinate.Y = y;	0
1755514	1755504	Programatically get the version number of a DLL	Assembly assembly = Assembly.LoadFrom("MyAssembly.dll");\nVersion ver = assembly.GetName().Version;	0
10114300	10114255	Using LINQ to project a list to a key / count 2-dimensional array	users.GroupBy(x => x.FirstName)\n     .Select(x => new { Name = x.Key, Count = x.Count() })	0
31563033	31562674	How should I remove objects from a list when a cancel dialog result is returned?	var list1 = new List<int>() { 1, 2, 3};\nvar list2 = new List<string>() { "Abc", "Def", "Ghi"};\n\nobject[] tempData = new[] { list1.ToList(), list2.ToList() };\n\n//... user changes something in list1, list2 ...\nlist1.Add(12); list1.Remove(3);\nlist2.Remove("Def");\n\nif(cancel)\n{\n   list1 = tempData[0] as List<int>;\n   list2 = tempData[1] as List<string>; \n}	0
11614618	11614569	How do I suppress the output of namespaces with XML serialization?	var ns = new XmlSerializerNamespaces();\nns.Add("", "");\nserializer.Serialize(writer, decision, ns);	0
12394206	12394145	c# Create several xdocuments from xelements	string xml = "<Root><Child1>aaa</Child1><Child2>bbb</Child2></Root>";\n\nXDocument xDoc = XDocument.Parse(xml);\n\nvar xDocs = xDoc.Root.Elements()\n    .Select(e => new XDocument(e))\n    .ToList();	0
337171	337165	Help me with that CrossThread?	private void resizeThreadSafe(int width, int height)\n{\n    if (this.form.InvokeRequired)\n    {\n        this.form.Invoke(new DelegateSize(resizeThreadSafe,\n            new object[] { width, height });\n        return;\n    }\n    this.form.Size = new Size(width, height);\n    this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next\n}	0
3483299	3483256	insert data to db in loop performance	System.Data.SqlClient.SqlBulkCopy bc = new System.Data.SqlClient.SqlBulkCopy("...");\n\n// Begin a loop to process managable-size batches of source data.\n\nusing (System.Data.DataTable dtTarget = new System.Data.DataTable("sqlTable"))\n{\n\n   // Populate dtTarget with the data as it should appear\n   // on the SQL Server side.\n   // If the mapping is simple, you may be able to use\n   // bc.ColumnMappings instead of manually re-mapping.\n\n   bc.DestinationTableName = "sqlTable";\n   bc.WriteToServer(dtTarget);\n}\n\n// End loop.	0
3308457	3308437	How to detect running ASP.NET version	System.Environment.Version.ToString()	0
3991562	3991536	Generating a literal for each item in an item collection	StringBuilder sb = new StringBuilder("");\nforeach(item in collection)\n{\n    sb.Append("<script type=\"text/javascript\">");\n    //do your javascript stuff here\n    sb.Append("</script>");\n}\n\nliteral.Text = sb.ToString();	0
8013889	8013439	How to use SortMode in DataGridView	public Form1()\n{\n InitializeComponent();\n\n SortableBindingList<person> persons = new SortableBindingList<person>();\n persons.Add(new Person(1, "timvw", new DateTime(1980, 04, 30)));\n persons.Add(new Person(2, "John Doe", DateTime.Now));\n\n this.dataGridView1.AutoGenerateColumns = false;\n this.ColumnId.DataPropertyName = "Id";\n this.ColumnName.DataPropertyName = "Name";\n this.ColumnBirthday.DataPropertyName = "Birthday";\n this.dataGridView1.DataSource = persons;\n}	0
12851432	12850949	Regex Option - no recursive regex	var json = "[{\"name\":\"joe\",\"message\":\"hello\",\"sent\":\"datetime\"},{\"name\":\"steve\",\"message\":\"bye\",\"sent\":\"datetime\"}]";\n\nvar serializer = new JavaScriptSerializer();\nvar result = serializer.Deserialize<object[]>(json);\n\n// now have an array of objects, each of which happens to be an IDictionary<string, object>\nforeach(IDictionary<string, object> map in result)\n{\n    var messageValue = map["message"].ToString();\n    Console.WriteLine("message = {0}", messageValue);\n}	0
29232839	29231676	Using C# WebBrowser within app	webBrowser1.Navigate(URL);	0
16398844	16398395	Invoke or BeginInvoke cannot be called on a control until the window handle has been created	if (! fTypeLabel.IsHandleCreated) return;  // emergency exit\n      fTypeLabel.Invoke(new MethodInvoker(fuelTypeChosen));	0
31734175	31733770	How to upload multiple files in mvc 5 to server and store file's path with Entity Framework	incident.FilePaths = new List<FilePath>();\nforeach(var file in upload)\n{\n    // your code except last line\n    incident.FilePaths.Add(photo); \n}\n// rest of your code	0
6022887	6022832	How do I decode HTML that was encoded in JS using encodeURIComponent()?	string s = System.Uri.UnescapeDataString(html);	0
2552691	2552681	C# How to calculate first 10 numbers out a bill number of 12?	(n / 100) % 97 == n % 100	0
2118874	2118848	how to invoke user's (non-outlook) email application from .NET program	Process.Start("mailto:hurr@durr.com");	0
28766932	28765791	iTextSharp - Setting zoom to "Fit page" and maintain it	outline = new PdfOutline(root, new PdfDestination(PdfDestination.FIT), someTitle,true);	0
7319911	7319835	HTML5/razor how to alter length of a input text box	.editor-field input[type="text"], .editor-field select\n{\n  width:100px;\n}	0
23192738	23192642	String array to Int array	class Program\n{\n   static void Main()\n   {\n       string numberStr = Console.ReadLine(); // "1 2 3 1 2 3 1 2 ...."\n       string[] splitted = numberStr.Split(' ');\n       int[] nums = new int[splitted.Length];\n\n       for(int i = 0 ; i < splitted.Length ; i++)\n       {\n         nums[i] = int.Parse(splitted[i]);\n       }\n   }\n}	0
19428275	19428035	Change CSS in backend	myDiv.Attributes.CssStyle.Add("color", "white");	0
12369642	12369332	Best way to copy a comboBox from form1 to form2	public class Context{\n  ...\n  ...\n  public List<Foo> FooItems {\n    get{...}\n  }\n}\n\npublic class Form1 {\n  ...\n  combobox.AddRange(this.context.FooItems);\n  ...\n}\n\npublic class Form2 {\n  ...\n  combobox.AddRange(this.context.FooItems);\n  ...\n}	0
13947711	13947695	How do I return this variable using if statements?	return (!(x < 0 || x >= 20) && (y < 0 || y >= 20))	0
1591751	1525808	Replace MergeFields in a Word 2003 document and keep style	if (values.ContainsKey(fieldName))\n          {\n             mergeField.Result = (values[fieldName]);\n          }	0
19529939	19460149	C# - remove property tag items from tif file	img.RotateFlip(RotateFlipType.Rotate180FlipNone);\nimg.RotateFlip(RotateFlipType.Rotate180FlipNone);\nimg.Save("cleared_" + fileName, Encoder, EncoderParams);	0
9592438	9592294	AutoMapper configuration of List	opt => opt.Ignore()	0
10916409	10916190	PLINQ bad performance	Stopwatch sw = new Stopwatch();\n\n        int[] vals = Enumerable.Range(0, 10000000).ToArray();\n\n        sw.Start();\n        var x1 = vals.Where(x => x % 2 == 0).ToList();\n        sw.Stop();\n        Console.WriteLine("Sequential Execution {0} milliseconds", sw.ElapsedMilliseconds);\n\n\n        sw.Restart();\n        var x2 = vals.Where(x => x % 2 == 0).AsParallel().ToList();\n        sw.Stop();\n        Console.WriteLine("Parallel Execution {0} milliseconds", sw.ElapsedMilliseconds);	0
34046823	34046006	Opening a file and using the string within	// Read your file using File.ReadAllLines\nString[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };\nforeach (var line in lines)\n{\n     String[] values = line.Split(' ');\n     string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);\n     int xCoordinate = Convert.ToInt32(x);            \n}	0
11297511	11297233	Traversing nodes but including the starting node in the result in Neo4J with Gremlin	posts = []\ng.v(4).out('POSTED').aggregate(posts).iterate()\ng.v(4).out('KNOWS').out('POSTED').aggregate(posts).iterate()\nreturn posts.unique()	0
1886876	1886866	How to find extension of a file?	string myFilePath = @"C:\MyFile.txt";\nstring ext = Path.GetExtension(myFilePath);\n// ext would be ".txt"	0
25433718	25433036	Switching the values Year and Day fields in a list of type DateTime	foreach(var item in SourceList)\n{\n    int newYear = Convert.ToInt32(item.Year.ToString().Substring(0,2) + item.Day.ToString());\n    DateTime result = new DateTime(newYear, item.Month, 10);\n    ResultList.Add(result);\n}	0
5802575	5801804	Utility to import/export data in SQLServer	using Migrator.Framework;\nusing System.Data;\n\nnamespace DBMigration\n{\n        [Migration(20080401110402)]\n        public class CreateUserTable_001 : Migration\n        {\n                public void Up()\n                {\n                        Database.CreateTable("User",\n                                new Column("UserId", DbType.Int32, ColumnProperties.PrimaryKeyWithIdentity),\n                                new Column("Username", DbType.AnsiString, 25)\n                                );\n                }\n\n                public void Down()\n                {\n                        Database.RemoveTable("User");\n                }\n        }\n}	0
23924277	23924183	Keep user's settings after altering assembly/file version	// Copy user settings from previous application version if necessary\nif (MyApp.Properties.Settings.Default.UpdateSettings)\n{\n    MyApp.Properties.Settings.Default.Upgrade();\n    MyApp.Properties.Settings.Default.UpdateSettings = false;\n    MyApp.Properties.Settings.Default.Save();\n}	0
29563936	29563600	trying to write a program to undersatnd pre & post increments and unary operators	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine("After pre {0}", PreInc());\n        Console.WriteLine();\n        Console.WriteLine("After post {0}", PostInc());\n        Console.ReadLine();\n    }\n\n    public static int PreInc()\n    {\n        int a = 0;\n\n        do {\n            Console.WriteLine("PreIncrement value of a is {0}", ++a);\n        } while (a < 10);\n\n        return a;\n    }\n\n    public static int PostInc()\n    {\n        int a = 0;\n\n        do {\n            Console.WriteLine("PostIncrement value of a is {0}", a++);\n        } while (a < 10);\n\n        return a;\n    }\n}	0
281374	280072	Tools to assist with continual Java to C# Conversion	* A Java Virtual Machine implemented in .NET\n* A .NET implementation of the Java class libraries\n* Tools that enable Java and .NET interoperability	0
22820440	22819831	Limiting a string to alphabetical letters, C#	if (Regex.IsMatch("yourtexthere", "^[a-zA-Z]{1,25}$").Success) {\n    // it matches                \n}	0
7113700	7113598	Binding a RichTextBox to a Slider Control in C#	//<RichTextBox.LayoutTransform>\n//    <ScaleTransform ScaleX="{Binding ElementName=mySlider, Path=Value}"\n//                    ScaleY="{Binding ElementName=mySlider, Path=Value}"/>\n//</RichTextBox.LayoutTransform>\n\nScaleTransform scaleTransform = new ScaleTransform();\nBinding scaleXBinding = new Binding("Value");\nscaleXBinding.Source = mySlider;\nBinding scaleYBinding = new Binding("Value");\nscaleYBinding.Source = mySlider;\nBindingOperations.SetBinding(scaleTransform,\n                             ScaleTransform.ScaleXProperty,\n                             scaleXBinding);\nBindingOperations.SetBinding(scaleTransform,\n                             ScaleTransform.ScaleYProperty,\n                             scaleYBinding);\n\nRichTextBox newText = new RichTextBox();\nnewText.LayoutTransform = scaleTransform;	0
17327323	17324333	Setting permissions on private key for a certificate using code	X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);\nX509Certificate2 c = store.Certificates\n    .Find(X509FindType.FindBySubjectName, SIGNED_SUBJECT, true) \n    .Cast<X509Certificate2>()\n    .FirstOrDefault();\n    store.Close();\n\nRSACryptoServiceProvider rsa = c.PrivateKey as RSACryptoServiceProvider;\nConsole.WriteLine("Certificate thumbprint:" + c.Thumbprint);\nConsole.WriteLine("From machine key store?: " + rsa.CspKeyContainerInfo.MachineKeyStore);\nConsole.WriteLine("Key container name: " + rsa.CspKeyContainerInfo.KeyContainerName);\nConsole.WriteLine("Key unique container name: " + rsa.CspKeyContainerInfo.UniqueKeyContainerName);	0
1124240	1124216	What is the shortest code to compare two comma-separated strings for a match?	public class StringHelpers\n{\n    private static readonly char[] separator = ",".ToCharArray();\n    public static bool UserCanAccessThisPage(\n        string userAccessGroups, \n        string pageItemAccessGroups)\n    {\n        return userAccessGroups\n            .Split(separator) // split on comma\n            .Select(s => s.Trim()) // trim elements\n            .Contains(pageItemAccessGroups); // match\n    }\n}	0
23985612	23985548	Wrapping a Model with a visual control	class AppleModel\n{\n   int PipCount { get; set; }    // Auto Property\n   Boolean isFresh {get ; set; } // Auto Property\n}\n\nclass AppleView : PictureBox\n{\n\n  private AppleModel _model; \n\n  public AppleView( AppleModel model )\n  {\n         this._model = model;\n     .........\n  }\n\n  int PipCount \n  { \n   get { return this._model.PipCount; } \n   set { this._model.PipCount = value; }\n  }\n\n  int isFresh \n  { \n   get { return this._model.PipCount; } \n   set { this._model.PipCount = value; }\n  }\n}	0
17863395	17863258	How to calculate the time that has passed since a file was created	DateTime fileCreatedDate = File.GetCreationTime(path);\nTimeSpan difference = DateTime.Now.Subtract(fileCreatedDate);\nif(difference.TotalDays > 365)\n{\n\n}	0
18872171	18871594	DataGridView doesn't show data: DataSet is empty	private void Form1_Load(object sender, System.EventArgs e)\n{\n    // Bind the DataGridView to the BindingSource \n    // and load the data from the database.\n    dataGridView1.DataSource = bindingSource1;\n    GetData("select * from Alex_db");\n}	0
23860706	23860511	Load image from url to ImageView - C#	private Bitmap GetImageBitmapFromUrl(string url)\n{\n     Bitmap imageBitmap = null;\n\n     using (var webClient = new WebClient())\n     {\n          var imageBytes = webClient.DownloadData(url);\n          if (imageBytes != null && imageBytes.Length > 0)\n          {\n               imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);\n          }\n     }\n\n     return imageBitmap;\n}\n\nvar imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");\nimagen.SetImageBitmap(imageBitmap);	0
5947178	5947081	Getting a LSB of a BMP binary image	GetPixel()	0
21051380	21050293	in C# how do I convert what I think is a string of hex ascii to something i can read?	private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n        //RxString = serialPort1.ReadExisting();\n        byte [] bytesRead = new byte[serialPort1.BytesToRead];\n        serialPort1.Read(bytesRead, 0, bytesRead.Length);\n        RxString = ByteArrayToString(bytesRead);\n        this.Invoke(new EventHandler(DisplayText));\n        //Console.WriteLine("Hex ouput: {0}", ByteArrayToString(bytesRead)); \n    }\n\n    private void DisplayText(object sender, EventArgs e)\n    {\n        textBox1.AppendText(RxString);\n    }\n\n    public string ByteArrayToString(byte[] inBytes)\n    {\n        StringBuilder hex = new StringBuilder(inBytes.Length * 2);\n        foreach (byte b in inBytes)\n            hex.AppendFormat("{0:x2}", b);\n        return hex.ToString();\n    }	0
14056530	14056508	Change foreach loop to lambda	List<string> onlineModelsNumbers = OnlineModels.Select(om => om.model_id.ToString()).ToList();	0
28937789	28937064	Contact Us Page	From domain must match authenticated domain	0
31379230	31378966	Comparing file size with existing value	//Create a dictionary that holds the file name with it's size\n        Dictionary<string, long> FileNameAndSizes = new Dictionary<string, long>();\n\n        //Key of dictionary will contain file name\n        //Value of dictionary will contain file size\n        FileNameAndSizes.Add("file1.dll", 17662);\n        FileNameAndSizes.Add("file2.dll", 19019);\n\n        //Iterate through the dictionary\n        foreach (var item in FileNameAndSizes)\n        {\n            //Look for file existance\n            if (File.Exists(Directory.GetCurrentDirectory() + "\\dll\\" + item.Key))\n            {\n                FileInfo f = new FileInfo(Directory.GetCurrentDirectory() + "\\dll\\" + item.Key);\n                var s1 = f.Length;\n\n                //Compare the current file size with stored size\n                if (s1 != item.Value)\n                {\n                    MessageBox.Show(f.Name + "modified DLL file, please change it to original");\n                }\n            }\n        }	0
12717166	12716389	How can I set a form to have a transparent background in c#?	this.BackColor = Color.White;\nthis.TransparencyKey = Color.White;	0
27279993	27275704	Get any parameter from a Post Method in a Web Api controller	if (HttpContext.Current.Request.Form.Count > 0)\n        {\n            sb.Append("<html>");\n            sb.AppendFormat("<body onload='document.forms[0].submit()'>Loading...");\n            sb.AppendFormat("<form action='{0}' method='post'>",your_url);\n            foreach (string key in HttpContext.Current.Request.Form.AllKeys)\n            {\n                sb.AppendFormat("<input type='hidden' name='{0}' value='{1}'>", key,\n                    HttpContext.Current.Request.Form[key]);\n            }\n            sb.Append("</form>");\n            sb.Append("</body>");\n            sb.Append("</html>");\n\n\n\n        }	0
14812737	14812656	How to format a string to include blank spaces in C#	string s = "2345000012999922";\ns = s.Insert(14, " ").Insert(10, " ").Insert(8, " ").Insert(4, " ");\nConsole.WriteLine(s);	0
33185546	33185482	How to programmatically change the scale of a canvas?	ScaleTransform scale = new ScaleTransform(MainCanvas.LayoutTransform.Value.M11 * ScaleRate, MainCanvas.LayoutTransform.Value.M22 * ScaleRate);\nMainCanvas.LayoutTransform = scale;\nMainCanvas.UpdateLayout();	0
11305502	11305447	Format function to display custom character(s) if number is zero	double posValue = 1234;\ndouble negValue = -1234; \ndouble zeroValue = 0;\n\nstring fmt = "+##;-##;**Zero**";\n\nConsole.WriteLine("value is positive : " + posValue.ToString(fmt));    \nConsole.WriteLine();\n\nConsole.WriteLine("value is negative : " +negValue.ToString(fmt));    \nConsole.WriteLine();\n\nConsole.WriteLine("value is Zero : " + zeroValue.ToString(fmt));\nConsole.WriteLine();	0
23954258	23953771	add 10 empty rows to gridview	var list = new List<string>();\n\nfor (int i = 0; i < 10; i++)\n{\n    list.Add(string.Empty);\n}\ngv_Others.DataSource = list;\ngv_Others.DataBind();	0
15707885	15707458	Bad data exception in C#	static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)\n{\n    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();\n    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);\n    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);\n    DES.Mode = CipherMode.CFB;\n    DES.Padding = PaddingMode.ISO10126;\n    FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);\n    ICryptoTransform desdecrypt = DES.CreateDecryptor();\n    CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);\n    FileStream fsDecrypted = new FileStream(sOutputFilename,FileMode.Create,FileAccess.Write);\n    cryptostreamDecr.CopyTo(fsDecrypted);\n    fsDecrypted.Flush();\n    fsDecrypted.Close();\n}	0
2023259	2023187	loop through all rows and columns of a gridview using C#	int rowscount = gv.Rows.Count;\nint columnscount = gv.Columns.Count;\nfor (int i = 0; i < rowscount; i++)\n{\n    // Create the row outside the inner loop, only want a new table row for each GridView row\n    DataRow row = empTable.NewRow();\n    for (int j = 1; j < columnscount; j++)\n    {\n        // Referencing the column in the new row by number, starting from 0.\n        row[j - 1] = gv.Rows[i][j].Tostring();\n    }\n    MynewDatatable.Rows.Add(row);\n}	0
13471972	13415897	WPF grid cells in C# no text	Span span = new Span();\nspan.Foreground = Brushes.Black;\nspan.Inlines.Add(new Run("Text"));\n\ntextBlock.Inlines.Add(span);\n\nLabel cell = new Label();\n\ncell.MinHeight = cellHeight;\ncell.MaxWidth = cellWidth * 3;\ncell.MinWidth = cellWidth;\ncell.ToolTip = "toolTip";\ncell.BorderThickness = new Thickness(2);\n\nTextBlock cellText = new TextBlock();\ncellText.HorizontalAlignment = HorizontalAlignment.Stretch;\ncellText.TextWrapping = TextWrapping.WrapWithOverflow;\n\ncell.Content = cellText;	0
15762366	15706322	How to resume broken download between a c# server and Java client	[WebGet(UriTemplate = "ResumeDownload/{clientID}/{fileName}/{startByte}")]\n        public Stream resumeDownload(String clientID, String fileName, String startByte)\n        {\n            MemoryStream responseStream = new MemoryStream();\n            Stream fileStream = File.Open(@jobRepPath + fileName.Replace("___", "."), FileMode.Open);\n\n            fileStream.Seek(Convert.ToInt32(startByte), SeekOrigin.Begin);\n\n            int length = (int)(fileStream.Length - Convert.ToInt32(startByte));\n            byte[] buffer = new byte[length];\n            fileStream.Read(buffer, 0, length);\n            responseStream.Write(buffer, 0, length);\n\n            fileStream.Close();\n            responseStream.Position = 0;\n\n            return responseStream; \n        }	0
739169	739114	Formatting of XML created by DataContractSerializer	var ds = new DataContractSerializer(typeof(Foo));\n\nvar settings = new XmlWriterSettings { Indent = true };\n\nusing (var w = XmlWriter.Create("fooOutput.xml", settings))\n    ds.WriteObject(w, someFoos);	0
2251380	2251272	remove rows of a table except the first 2	int rowCount = myTable.Rows.Count;\nfor(int i = 2; i < rowCount; i++) {\n    myTable.Rows.RemoveAt(i);\n}	0
33580493	33580346	How can i write sum query with linq to sql to calculate sum of the nchar field value?	int sum = behzad.MYTEMPDB.where(p => p.fileid.trim()=dropdown1.text() \n          && p.name=dropdownlist2.text()).sum( p => Convert.ToInt32(p.Count));	0
2697927	2697762	How can i initialise a server on startup?	_svc = new ServiceHost(new MonitoringSystemService()), address);	0
21559263	21559209	convert dictionary of lists to another type of list	GetDict().ToDictionary(\n    kvp => kvp.Key,\n    kvp => kvp.Value.ConvertAll(DTOMapper.ToDTO)\n);	0
17351308	17350834	Silverlight - Change Font Size of Data Grid Header in C#	Style s = new Style(typeof(DataGridColumnHeader));\ns.BasedOn = this.DataGrid_CardDetails.ColumnHeaderStyle;\ns.Setters.Add(new Setter(DataGridColumnHeader.FontSizeProperty, 26));\n\nthis.DataGrid_CardDetails.ColumnHeaderStyle = s;	0
4413387	4403975	How to Create an XLS from a CSV, List, or DataSet using C#?	public static void ExportDStoExcel(DataSet ds, string filename)\n    {\n        HttpResponse response = HttpContext.Current.Response;\n        response.Clear();\n        response.Charset = "";\n\n        response.ContentType = "application/vnd.ms-excel";\n        response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");\n\n        using (StringWriter sw = new StringWriter())\n        {\n            using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n            {\n                DataGrid dg = new DataGrid();\n                dg.DataSource = ds.Tables[0];\n                dg.DataBind();\n                dg.RenderControl(htw);\n                response.Write(sw.ToString());\n                response.End();\n            }\n        }\n\n    }	0
6222889	6221096	Regex to match the path before the resource from a URL	var uri = new Uri("http://www.domain.com/path/to/page1.html?query=value#fragment");\n\nConsole.WriteLine(uri.Scheme); // http\nConsole.WriteLine(uri.Host); // www.domain.com\nConsole.WriteLine(uri.AbsolutePath); // /path/to/page1.html\nConsole.WriteLine(uri.PathAndQuery); // /path/to/page1.html?query=value\nConsole.WriteLine(uri.Query); // ?query=value\nConsole.WriteLine(uri.Fragment); // #fragment\nConsole.WriteLine(uri.Segments[uri.Segments.Length - 1]); // page1.html\n\nfor (var i = 0 ; i < uri.Segments.Length ; i++)\n{\n    Console.WriteLine("{0}: {1}", i, uri.Segments[i]);\n    /*\n    Output\n    0: /\n    1: path/\n    2: to/\n    3: page1.html\n    */\n}	0
19479123	19479046	How can I see all the text accumulated in JsonWriter during a JsonConverter class debugging?	((Newtonsoft.Json.JsonTextWriter)(writer))._writer.ToString()	0
9534022	9532919	How to get Color and coordinates(x,y) from Texture2D XNA c#?	Color[,] colors2D = new Color[texture.Width, texture.Height];\n     for (int x = 0; x < texture.Width; x++)\n     {\n         for (int y = 0; y < texture.Height; y++)\n         {\n             colors2D[x, y] = colors1D[x + y * texture.Width]; \n         }\n     }	0
16219254	16218957	Serializing object to XML	[XmlRoot("Config")]\n    public class ConfigSerializer\n    {\n        [XmlArray("Nodes"),XmlArrayItem("N")]\n        public List<Node> LstNodes { get; set; }\n    }	0
7610901	7610875	Parse string using RegEx and C#	JObject o = JObject.Parse(@"{\n  ""Stores"": [\n    ""Lambton Quay"",\n    ""Willis Street""\n  ],\n  ""Manufacturers"": [\n    {\n      ""Name"": ""Acme Co"",\n      ""Products"": [\n        {\n          ""Name"": ""Anvil"",\n          ""Price"": 50\n        }\n      ]\n    },\n    {\n      ""Name"": ""Contoso"",\n      ""Products"": [\n        {\n          ""Name"": ""Elbow Grease"",\n          ""Price"": 99.95\n        },\n        {\n          ""Name"": ""Headlight Fluid"",\n          ""Price"": 4\n        }\n      ]\n    }\n  ]\n}");\n\nstring name = (string)o.SelectToken("Manufacturers[0].Name");\n// Acme Co\n\ndecimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");\n// 50\n\nstring productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");\n// Elbow Grease	0
9132459	9132403	Connect to a deployed SQL Server Express database	"Data Source=.\SQLEXPRESS; ...."	0
397986	397980	incrementing array value with each button press?	numbers[1] += 2;	0
23130249	23130047	Byte array debug	string s = BitConverter.ToString(stream);	0
27842883	27842790	How to select a row in gridview by code based on its key value?	var keyValue = 1; // Replace with your Convert.ToInt32(Request.QueryString["RowToSelectID"])\n for (int i = 0; i <= this.gridview1.DataKeys.Count - 1; i++)\n {\n   if ((int)gridview1.DataKeys[i].Value == keyValue )\n    {\n       this.gridview1.SelectedIndex = i;\n   }\n}	0
32656696	32655950	Hide gridview cell (value) base on other cell value	protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n   if (e.Row.RowType == DataControlRowType.DataRow)\n   {\n        Label lbl=e.Row.FindControl("your cotrol Id")as Label;\n       if(lbl!=null && lbl.Text.Trim()=="some string")\n       {\n           e.Row.FindControl("deactivate btn Id").Visible = false;\n           e.Row.FindControl("delete btn Id").Visible = false;\n           e.Row.FindControl("edit btn Id").Visible = false;\n       }\n   }\n }	0
2418311	2418270	C# - Get a list of files excluding those that are hidden	DirectoryInfo directory = new DirectoryInfo(@"C:\temp");\nFileInfo[] files = directory.GetFiles();\n\nvar filtered = files.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden));\n\nforeach (var f in filtered)\n{\n    Debug.WriteLine(f);\n}	0
12360156	12360092	How to copy a file in a random order and random time?	System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("dirctory path");\n\n    List<System.IO.FileInfo> files = di.GetFiles().ToList();\n\n    di = null;  // at this point I don't think you need to hold on to di\n\n    // the static Directory will return string file names\n\n    // randomize files using the code in the link \n    Random random = new Random();\n    foreach (System.IO.FileInfo fi in files)\n    {\n        Thread.Sleep(random.Next(1000, 3600000));\n        // should probaly test the fi is still valid\n        fi.CopyTo("desitination");\n    }	0
30473649	30468696	How to perform a join of two sets and populate navigation properties	(from t in db.Teapots.Include(t => t.Material.Manufacturer)\n join c in db.Cups\n on new { t.MaterialId, t.ColorId } equals new { c.MaterialId, c.ColorId }\n where t.Id == id\n select new \n  {\n     Teapot = t,\n     Cup = c,\n     Material = t.Material,\n     Manufacturer = t.Material.Manufacturer,\n  })\n.AsEnumerable()\n.Select(a => new ViewModel.Data.TeapotsWithInfo \n  { \n     Teapot = a.Teapot, \n     Cup = a.Cup \n  })\n.SingleOrDefault();	0
4709380	4708592	WriteableBitmap failing badly, pixel array very inaccurate	ChangeNotification(intTest[(int)click.X,(int)click.Y].ToString("X8"));	0
18752016	18729837	From arduino to netmf	uint angle = 3000;//angle is int 500 to 5500\n\nuint temp;\nbyte pos_hi,pos_low;\n\ntemp = angle & 0x1f80;  //get bits 8 thru 13 of position\npos_hi = (byte) (temp >> 7);     //shift bits 8 thru 13 by 7\npos_low = (byte) (angle & 0x7f); //get lower 7 bits of position	0
6271751	6271704	Array substring in deferred execution	Skip(n).Take(m)	0
28809521	28809036	Insert a new entity without creating child entities if they exist	public void InsertProduct(Product item)\n{\n    // Calling this code before the context is aware of the Child\n    // objects will cause the context to attach the Child objects to the     \n    // context and then set the state.\n    // CustomerContext.Entry(childitem).State = EntityState.Unchanged\n    CustomerContext.Entry(item.ChildObject).State = EntityState.Modified;\n\n    CustomerContext.Entry(item).State = EntityState.Added;\n    CustomerContext.Set<Product>().Add(item);\n}	0
2949325	2893184	LINQ to Sql: Insert instead of Update	function Stuff()\n{    \n    Wrapper x = new Wrapper();\n    Type a = new Type();\n    InsertType(a);\n    x.Type = a;\n    InsertOnSubmit(x);\n}\n\nfunction InsertType (Type a)\n{\n    InsertOnSubmit(a);\n}	0
1001850	996643	How to implement Excel vbA in C#	using Excel = Microsoft.Office.Interop.Excel;\n ...\n object mis = Type.Missing;\n\n Excel.FormatCondition cond =\n    (Excel.FormatCondition)range.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue,\n    Excel.XlFormatConditionOperator.xlEqual, "=1",\n    mis, mis, mis, mis, mis);\n    cond.Interior.PatternColorIndex = Excel.Constants.xlAutomatic;\n    cond.Interior.TintAndShade = 0;\n    cond.Interior.Color = ColorTranslator.ToWin32(Color.White);\n    cond.StopIfTrue = false;	0
138615	138552	Can Regex be used for this particular string manipulation?	>>> import re\n>>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k")\n"axbx'cPdPe'fxgh'iPj'k"	0
23995597	23995217	C# Byte array split	public static byte[][] Split(byte[] arr, byte keyword)\n        {\n            var result = new List<List<byte>>();\n\n            var piece = new List<byte>();\n\n            foreach (var b in arr)\n            {\n                if (b != keyword)\n                {\n                    piece.Add(b);\n                }\n                else\n                {\n                    result.Add(piece);\n                    piece = new List<byte>();\n                }\n            }\n\n            result.Add(piece);\n\n            return ToArrayOfArray(result);\n        }\n\npublic static T[][] ToArrayOfArray<T>(List<List<T>> list)\n        {\n            var res = new T[list.Count][];\n\n            for (int i = 0; i < list.Count; i++)\n            {\n                res[i] = list[i].ToArray();\n            }\n\n            return res;\n        }	0
9508834	9488137	How to determine if a Couchbase bucket exists using .NET client?	public static class CouchbaseClientExtensions {\n\n    public static bool BucketExists(this CouchbaseClient client, CouchbaseClientSection section = null) {\n\n        section = section ?? (CouchbaseClientSection)ConfigurationManager.GetSection("couchbase");\n\n        var webClient = new WebClient();            \n        var bucketUri = section.Servers.Urls.ToUriCollection().First().AbsoluteUri;\n\n        var response = webClient.DownloadString(bucketUri + "/buckets");               \n        var jss = new JavaScriptSerializer();\n        var jArray = jss.DeserializeObject(response) as object[];\n\n        foreach (var item in jArray) {\n            var jDict = item as Dictionary<string, object>;\n            var bucket = jDict.Single(kv => kv.Key == "name").Value as string;\n            if (bucket == section.Servers.Bucket) {\n                return true;\n            }                               \n        }\n        return false;\n    }\n}	0
26535184	26532836	How do I listen for TimeSlider Event in ArcMap using C#	ITimeDisplayEvents_DisplayTimeChangedEventHandler DTC_EH;\n\n\n\n    private void enableTimeDisplayEventHandler(bool enable = true)\n        {\n\n            IMxDocument pMxDoc = ArcMap.Document;\n            IMap pMap = pMxDoc.FocusMap;\n            IActiveView pActiveView = pMap as IActiveView;\n            IScreenDisplay pScreenDisplay = pActiveView.ScreenDisplay;\n            ITimeDisplay pTimeDisplay = pScreenDisplay as ITimeDisplay;\n\n    DTC_EH = new ITimeDisplayEvents_DisplayTimeChangedEventHandler(this.OnDisplayTimeChangedEventHandler);\n                        ((ITimeDisplayEvents_Event)pTimeDisplay).DisplayTimeChanged += DTC_EH;\n}\n\n\nprivate void OnDisplayTimeChangedEventHandler(IDisplay d, object oldvalue, object newvalue)\n{\n            IMxDocument pMxDoc = ArcMap.Document;\n            IMap pMap = pMxDoc.FocusMap;\n            IActiveView pActiveView = pMap as IActiveView;\n            pActiveView.Refresh();\n}	0
3326876	3326867	Grouping data with a LINQ query	var result = from ticket in TicketTable\ngroup ticket by ticket.CreateDate.Date into g\nselect new {Date = g.Key, Count = g.Count() };	0
552637	552629	c# print the class name from within a static function	Console.WriteLine(new StackFrame().GetMethod().DeclaringType);	0
17657213	17656887	Create pairs of nodes from an XML file	var doc = XElement.Load(fileName);\n\nDictionary<string, string> dic = doc\n     .Descendants("Documentid")\n     .ToDictionary(e => e.Value, \n                   e => e.Parent.Parent.Parent.Element("Documentcode").Value );\n\n // verify\n Console.WriteLine(dic["12"]);\n Console.WriteLine(dic["25"]);	0
18838308	18837548	Using an image in the resource folder in a function which takes file path to image as parameter	string apppath = Application.StartupPath;\n    string resname = @"\Resource.bmp";\n    string localfile = "";\n    localfile = apppath + resname;//Create the path to this executable.\n    //Btw we are going to use the "Save" method of Bitmap class.It\n    //takes an absolute path as input and saves the file there.\n\n    //We accesed the Image resource through Properties.Resources.Settings and called Save method\n    //of Bitmap class.This saves the resource as a local file in the same folder as this executable.\n    Properties.Resources.Image.Save(localfile);\n\n    MessageBox.Show("The path to the local file is : " + Environment.NewLine + localfile + Environment.NewLine +\n    "Go and check the folder where this executable is.",\n    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);\n\n\n    //localfile is the path you need to pass to some function like this;\n    //SomeClass.Somefunction(localfile);	0
31518603	31518344	Must click "X" on MDIParent form multiple times to close application, each click closes MDIChild	private void _AssetFormBase_FormClosing(object sender, FormClosingEventArgs e)\n{\n    if (e.CloseReason == CloseReason.UserClosing)\n    {\n        e.Cancel = true;\n        this.Hide();\n    }\n}	0
7796465	7795620	WCF - how to make custom errors?	[OperationContract]\n[FaultContract(typeof(CustomFault))]\nstring WillThrowArgumentException();	0
725423	725413	How to access a timer from another class in C#	public class SomeOtherClassThatDoesStuff\n{\n   public event EventHandler SomethingHappened;\n\n   public void DoStuff()\n   {\n      ...\n      if( SomethingHappened != null )\n         SomethingHappened;\n      ...\n   }\n}\n\npublic class Form1\n{\n\n    private void Button1_Click(object sender, EventArgs e )\n    {\n\n      SomeOtherClassThatDoesStuff o = new SomeOtherClassThatDoesStuff();\n      o.SomethingHappened += new EventHandler(EnableTimer);\n\n      o.DoStuff();\n    }\n\n    private void EnableTimer(object sender, EventArgs e )\n    {\n       myTimer.Enabled = true;\n    }\n}	0
11609239	11609210	Defining functions which can take a lot of parameters in C#	void WriteAll(params object[] args) {\n   for(int i = 0; i < args.Length; i++)\n       Console.WriteLine(args[i]);\n}	0
18870934	18834893	SSDP Search in Windows Phone 8	MAN: "ssdp:discover"\r\n	0
3263967	3263937	In C#/VB, how do YOU determine whether a method is declared normally or as an extension method?	public ISomething GetSomething(this ISomewhere somewhere) {  }	0
16049165	16047084	Implementing method in a functional style	var query = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries)\n    .Aggregate(new List<string>(), (memo, segment) => {\n\n        memo.Add(memo.DefaultIfEmpty("").Last() + "/" + segment);\n\n        return memo;\n\n    }).Aggregate(new List<string>(), (memo, p) => {\n\n        memo.Add(p);\n        memo.Add(p + "/default");\n\n        return memo;\n\n    });	0
17685501	17666696	display html in geckofx	GeckoWebBrowser::LoadHtml(string content, string url)	0
3840590	3840196	C# Override an attribute in a subclass	public static void Main()\n{\n    var attribute = GetAttribute(typeof (MyWebControl), "StyleString", false);\n    Debug.Assert(attribute != null);\n\n    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", false);\n    Debug.Assert(attribute == null);\n\n    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", true);\n    Debug.Assert(attribute == null);\n}\n\nprivate static ExternallyVisibleAttribute GetAttribute(Type type, string propertyName, bool inherit)\n{\n    PropertyInfo property = type.GetProperties().Where(p=>p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();\n\n    var list = property.GetCustomAttributes(typeof(ExternallyVisibleAttribute), inherit).Select(o => (ExternallyVisibleAttribute)o);\n\n    return list.FirstOrDefault();\n}	0
1272198	1272096	Resharper throws OutOfMemoryException on big solution	editbin /LARGEADDRESSAWARE devenv.exe	0
5656540	5656457	Parsing a Auto-Generated .Net Date Object with Javascript/JQuery	function deserializeDotNetDate(dateStr) {\n  var matches = /\/Date\((\d*)\)\//.exec(dateStr);\n\n  if(!matches) {\n    return null;\n  }\n\n  return new Date( parseInt( matches[1] ) );\n}\n\ndeserializeDotNetDate("/Date(1304146800000)/");	0
29529175	29528874	listbox selected text with listbox text + custom text (richtextbox)	private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\nvar str =listBox1.SelectedItem.ToString();\nif(str=="aaa")\n{\n        richTextBox1.Text = str + "custom text 1";\n}\nelse if(str=="bbb")\n{\n        richTextBox1.Text = str + "custom text 2";\n}\n...\n\n\n    }	0
26376559	26376459	Finding the width of a control from inside the control in WPF	Width="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ActualWidth}"	0
15040509	15040454	How to set ComboBox to not show a part of string in it's items?	mycomboBox.Items.Add(new ListItem("Value To Display", "actual value"));\nmycomboBox.Items.Add(new ListItem("First item text", "This was a dog"));	0
12736157	12736047	How to inject my database context into all my repository classes	kernel.Bind<your-database-context>().ToSelf().InRequestScope()	0
3746497	3746476	Can I use a lambda expression with params keyword?	static int myMethod (int n, params  MyDel[] lambdas) {	0
34197206	34197066	How to use multiple event handler text_changed in C#?	"Name LIKE '%" + tbName.Text + "%' AND MiddleName LIKE '%" + tbMiddleName.Text + "%'"	0
32800343	32800217	Validating String in C#	Regex.IsMatch(input, "^\\s*9\\s*1\\s*1");	0
5254528	5254514	Asynchronous HTTP calls in Windows Phone 7	public void send(string url)\n{\n    WebClient c = new WebClient();\n    c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted);\n    c.DownloadStringAsync(new Uri(url));\n}	0
1393130	1392897	Looking for a .NET ObjectReflector that will help me simplify reflecting an object	foreach (PropertyInfo pi in oProps)\n           {\n                Type colType = pi.PropertyType;\n\n                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      \n                ==typeof(Nullable<>)))\n                 {\n                     colType = colType.GetGenericArguments()[0];\n                 }	0
23013013	23010944	Auto format parameters one per line	ReSharper | Options | Code Editing | C# | Formatting Style | Line Breaks and Wrapping | Line Wrapping:	0
5003906	5003581	Separate a string with a certain pattern into a dictionary	var input = @"{YYYY}./.{mm}-{CNo}\/{WEPNo}#{XNo+YNo}";\nRegex ex = new Regex(@"\{(?<key>.+?)\}(?<value>[^{}]*)");\nvar dictionary = ex.Matches(input).Cast<Match>()\n  .ToDictionary(m => m.Groups["key"].Value, m => m.Groups["value"].Value);	0
2035788	2035087	Draw image on a form from a separate thread	private void SomethingCalledFromBackgroundThread()\n    {\n        panel1.Invoke(new DoUpdatePanel(UpdatePanel), Color.Blue);\n    }\n\n    private delegate void DoUpdatePanel(Color aColor);\n\n    private void UpdatePanel(Color aColor)\n    {\n        panel1.BackColor = aColor;\n    }	0
2522882	2522594	Linq-To-Objects group by	Dictionary<string, Dictionary<string, double>> temphours \n    = (from user in hours\n       group user by GetDepartment(user.Key) into department\n       select new {\n          Key = department.Key\n          Value = (from userInDepartment in department\n                   from report in userInDepartment.Value\n                   group report by report.Key into g // To tired to think of a name =)\n                   select new {\n                       Key = g.Key\n                       Value = g.Sum(reportInG => reportInG.Value)\n                   }).ToDictonary(ud => ud.Key, ud=> ud.Value);\n       }).ToDictonary(u => u.Key, u=> u.Value);	0
13459238	13453763	Persisting Push Notification Channels in Windows 8	... Therefore, your app should request a channel each time the app launches. ...	0
16699154	16696964	Multiple Markers for Google Maps API V3 With Literal Asp.Net Control	var myOptions = {zoom: 16, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }	0
25381340	25381252	How do I get a random number/letter generator to generate 3 Letters then 6 Numbers? in WPF	public string RandomGenerator()\n    {\n        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n        var numbers= "0123456789";\n        var random = new Random();\n\n        var letterResult = new string(Enumerable.Repeat(chars, 3).Select(s => s[random.Next(s.Length)]).ToArray());    \n        var numberResult = new string(Enumerable.Repeat(number, 6).Select(s => s[random.Next(s.Length)]).ToArray());\n\n        txtReference.Text = letterResult + numberResults;\n\n        return result;\n\n    }	0
28569937	28569798	Simultaneous Animation For Same Element in WPF	var rt = new RotateTransform();\nvar tt = new TranslateTransform();\nvar transform = new TransformGroup();\ntransform.Children.Add(rt);\ntransform.Children.Add(tt);\nimage.RenderTransform = transform;\n\n// run animations	0
14967795	14967731	get;set; with DateTime to validate with .TryParse?	public partial class DTVitem\n{\n    private DateTime _datevalue;\n\n    public string dt\n    {\n        get { return _datevalue.ToString(); }\n        set { DateTime.TryParse(value, out _datevalue) ;}\n    }\n}	0
33476451	33475754	stackoverflow with dllimport from IIS	char    stmt[163840+1]; // allocation alot of memory\nchar    stmt2[163840+1];	0
4875730	4875540	how to get value of checked item from checkedlistbox	foreach(object itemChecked in checkedListBox1.CheckedItems)\n{\n     DataRowView castedItem = itemChecked as DataRowView;\n     string comapnyName = castedItem["CompanyName"];\n     int? id = castedItem["ID"];\n}	0
10351972	10351886	Compile-time check a value to implement several interfaces	public void someMethod<T>(T param) where T : IFoo, IBar\n{...}	0
10437660	10437451	Avoid Duplicating Object Initializer Value	var now = DateTime.Now;\nUser user = new User\n{\n     FirstName = "Tex",\n     Surname = "Murphy",\n     AddedDateTime = now,\n     ModifiedDateTime = now\n};	0
6314253	6314217	XDocument - Expression help	var products = document.Descendants("item")\n    .Select(arg => \n        new Product\n        {\n            Name = arg.Parent.Attribute("name").Value,\n            Hwid = arg.Attribute("hwid").Value,\n            Href = arg.Element("href").Value,\n            Localization = arg.Element("localization").Value,\n            BuildDateTime = DateTime.Parse(arg.Element("build.start").Value),\n            IcpBuildVersion = arg.Element("build.icp").Value\n        })\n    .ToList();	0
7358514	7350184	Calling JavaScript function from codebehind C# in a user control	ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('Hello World');});", true);	0
26960439	26959208	Unable to access WPF Elements from user class	public class sc\n{\n  string name, content, stopol, client, bkpset;\n  public void getndadd(FrameworkElement element)\n  {\n     var elem = element;\n     ...\n  }\n}\n\n public MainWindow()\n {\n    InitializeComponent();\n    sc.getndadd(textBox1);\n }	0
9414797	9414570	How to get id from String with using Regex	Regex.Match(text, @"id=(\d+)").Groups[1].Value;	0
2321080	2320657	Getting action filters list from base Controller	public sealed class MyRedirectAttributeAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n\n        if (!filterContext.ActionDescriptor.IsDefined(typeof(RequireSSLAttribute), true))\n        {\n            filterContext.HttpContext.Response.Redirect("~/Controller/Action");\n        }\n\n        base.OnActionExecuting(filterContext);\n    }\n}true	0
31116987	31116793	TeamCity - Unable to authenticate via API	String username = "abc";\n    String password = "123";\n    String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));\n    request.Headers.Add("Authorization", "Basic " + encoded);	0
23466943	23366194	How to create a custom .NET ComboBox with the textbox active during edit	BOOL CWinApp::PreTranslateMessage(MSG* pMsg)\n{\n    if (FilterWindowsFormsMessages(pMsg))\n    {\n        return TRUE;\n    }\n\n    return CWinApp::PreTranslateMessage(pMsg);\n}\n\nBOOL CWinApp::FilterWindowsFormsMessages(MSG* pMsg)\n{\n    Message message = Message::Create(IntPtr(pMsg-&gt;hwnd), \n                                      int(pMsg-&gt;message), \n                                      IntPtr((void*)pMsg-&gt;wParam), \n                                      IntPtr((void*)pMsg-&gt;wParam));\n\n    if (Application::FilterMessage(message))\n    {\n        return TRUE;\n    }\n\n    return FALSE;\n}	0
2725190	2724954	Using ManagementObject to retrieve a single WMI property	var enu = manageObjSearch.Get().GetEnumerator();\n        if (!enu.MoveNext()) throw new Exception("Unexpected WMI query failure");\n        long sizeInKilobytes = Convert.ToInt64(enu.Current["TotalVisibleMemorySize"]);	0
27442272	27442189	Building a bit flag using linq / lambda	int myFlag = myVar.Where(a => a.IsSelected)\n                  .Select(x => x.Flag) \n                  .Aggregate((current, next) => current | next);	0
728444	728432	How to programmatically click a button in WPF?	ButtonAutomationPeer peer =\n  new ButtonAutomationPeer( someButton );\nIInvokeProvider invokeProv =\n  peer.GetPattern( PatternInterface.Invoke )\n  as IInvokeProvider;\ninvokeProv.Invoke();	0
26696647	26696522	Is a listbox.item an object or a string? C#	private void FindMyString(string searchString)\n{\n   // Ensure we have a proper string to search for. \n   if (searchString != string.Empty)\n   {\n      // Find the item in the list and store the index to the item. \n      int index = listBox1.FindString(searchString);\n      // Determine if a valid index is returned. Select the item if it is valid. \n      if (index != -1)\n         listBox1.SetSelected(index,true);\n      else\n         MessageBox.Show("The search string did not match any items in the ListBox");\n   }\n}	0
9695598	9695510	How can I access the MainForm from within a class in a separate project?	public class MainForm : Form\n{\n    Shape _shape1 = new Shape();\n\n    public MainForm()\n    {\n        InitializeComponent();\n        _shape.ShapeNameChanged += HandleShapeNameChanged;\n    }\n\n    public void HandleShapeNameChanged(object sender, ShapeChangeEventArgs e)\n    {\n        textBox1.Text = e.NewName;\n    }\n}\n\npublic class Shape\n{\n    public event EventHandler<ShapNameChangedEventArgs> ShapeNameChanged;\n}	0
6377656	6377454	escaping tricky string to CSV format	/// <summary>\n/// Turn a string into a CSV cell output\n/// </summary>\n/// <param name="str">String to output</param>\n/// <returns>The CSV cell formatted string</returns>\npublic static string StringToCSVCell(string str)\n{\n    bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));\n    if (mustQuote)\n    {\n        StringBuilder sb = new StringBuilder();\n        sb.Append("\"");\n        foreach (char nextChar in str)\n        {\n            sb.Append(nextChar);\n            if (nextChar == '"')\n                sb.Append("\"");\n        }\n        sb.Append("\"");\n        return sb.ToString();\n    }\n\n    return str;\n}	0
22876505	22876214	Should I use Session State or FormAuthentication to keep track of a signed-in user?	FormsAuthentication.SetAuthCookie("username", false);	0
677359	677204	Counting the number of flags set on an enumeration	internal static UInt32 Count(this Skills skills)\n    {\n        UInt32 v = (UInt32)skills;\n        v = v - ((v >> 1) & 0x55555555); // reuse input as temporary\n        v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp\n        UInt32 c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count\n        return c;\n    }	0
31558649	31513389	Combining LINQ with OData AddQueryOption	// Filter by assets that can be displayed online\nassets = assets.Where(a => a.DisplayOnline);\n\n// Filter by assets that are active\nassets = assets.Where(a => a.Status == EPublishStatus.Active);\n\n// Addtional filters..\nassets = assets.Where(a => x == y);\n\n// Get the string for the dynamic filter\nstring dynamicQuery = GetDynamicQuery(assets);\n\n// Get base OData Asset call (https://api-dev.company.com/odata/Assets)\nIQueryable<Asset> serviceCall = _container.Assets;\n\n// Apply the new dynamic filter\nserviceCall = serviceCall.AddQueryOption("$filter", dynamicQuery);\n\n// Resultant OData query (Success!)\nhttps://api-dev.company.com/odata/Assets?$filter=DisplayOnline and Status eq Models.Status'Active' and (Levels/any(l:l/LevelId eq 18)) or (Levels/any(l:l/LevelId eq 19))	0
21116792	21116706	How to replace a HttpCookie in MVC3	var cookie = Request.Cookies["cookieName"];\nif (cookie != null)\n{\n    cookie.Value = "new value";\n    Response.SetCookie(cookie);\n}	0
15202298	15202281	C# - efficient random string/int generator	string uniqueName = Guid.NewGuid().ToString("N");	0
20939284	20939143	Select element value with xpath	var nsmgr = new XmlNamespaceManager(doc.NameTable);\nnsmgr.AddNamespace("ns", "http://example.com/authentication/response/1");\nvar xpath = "/ns:AuthenticateResponse/ns:AuthenticationRequirements/ns:PostBack";\nvar node = doc.SelectSingleNode(xpath, nsmgr);	0
19351980	19351018	Click based movement not working	float speedForThisFrame = speed;\nif((mousePosition-position).Length() < speed) speedForThisFrame = (mousePosition-position).Length();	0
4004674	4004426	How i can open all items in accordion control in silverlight?	private void CheckResultAccordion(IEnumerable<ListSearchResult> results)\n        {\n            ResultAccordion.ItemsSource = null;\n            ResultAccordion.ItemsSource = results;\n            ResultAccordion.UpdateLayout();\n            OpenAllAccordionItems(results.Count());\n            ResultAccordion.Visibility = Visibility.Visible;\n        }\n\nprivate void OpenAllAccordionItems(int count)\n        {\n            while (count > 1)\n            {\n                ResultAccordion.SelectedIndex = count - 1;\n                count--;\n            }\n        }	0
3814139	3814089	How can I get the sum of numbers from a diagonal line?	public int sumarDiagonal() \n{ \n int x = 0; \n for (int i = 0; i < Math.Min(Filas,Columnas); ++i) \n  x += m[i,i]; \n return x; \n} \n\npublic int sumarAntiDiagonal() \n{ \n int x = 0; \n for (int i = 0; i < Math.Min(Filas,Columnas); ++i) \n  x += m[Filas - 1 - i,i]; \n return x; \n}	0
32010162	32009244	How to remove \" and \r\n from string retrived from database	System.Text.RegularExpressions.Regex.Unescape(databaseString);	0
32328990	32328947	Insert a variable in the middle of the string but keep the single quotes (C#)	string.Format("//div[contains(@id,'msgError') and contains(text(),'{0}')]", textMessage)	0
13797794	13797727	DateTime and CultureInfo	System.Globalization.CultureInfo cultureinfo =\n        new System.Globalization.CultureInfo("nl-NL");\nDateTime dt = DateTime.Parse(date, cultureinfo);	0
14077327	13995259	Naudio - Convert 32 bit wav to 16 bit wav	void _waveIn_DataAvailable(object sender, WaveInEventArgs e)\n{\n    byte[] newArray16Bit = new byte[e.BytesRecorded / 2];\n    short two;\n    float value;\n    for (int i = 0, j = 0; i < e.BytesRecorded; i += 4, j += 2)\n    {\n        value = (BitConverter.ToSingle(e.Buffer, i));\n        two = (short)(value * short.MaxValue);\n\n        newArray16Bit[j] = (byte)(two & 0xFF);\n        newArray16Bit[j + 1] = (byte)((two >> 8) & 0xFF);\n    }\n}	0
8256854	8256799	How to make Generic method in C#	public TemplateBase Map< TemplateBase>(TemplateBase request) where TemplateBase : new\n{\nreturn new TemplateBase()\n{\n....\n}\n}	0
6276261	6276137	How to convert DataView,DataRowView to Generic Typed Lists	List<Bills> bills = yourDataView.Rows.Select(t => new Bills() {BillNumber = t["BillNumber"], BillDate = t["BillDate"], BilledTo = t["BilledTo"]}).ToList();	0
4306294	4306193	filesystemwatcher multiple files	bool wasLastObjectProcessed = true\n\nfunction onFileWatcherCreateFile\n    lock wasLastObjectProcessed\n        if wasLastObjectProcessed and processFile(file)\n            #do some code here that you need to do if it is processed\n        else\n           wasLastObjectProcessed = false\n        endif\n    endlock\nendfunction	0
15586962	15586009	LINQ query to Sum value over date ranges	SortedSet<DateTime> splitdates = new SortedSet<DateTime>();\nforeach (var item in _list)\n{\n    splitdates.Add(item.Period.Start);\n    splitdates.Add(item.Period.End);\n}\n\nvar list = splitdates.ToList();\nvar ranges = new List<DateRange>();\nfor (int i = 0; i < list.Count - 1; i++)\n    ranges.Add(new DateRange() { Start = list[i], End = list[i + 1] });\n\nvar result = from range in ranges\n             from c in _list\n             where c.Period.Intersect(range) != null\n             group c by range into r\n             select new Capacities(r.Key.Start, r.Key.End, r.Sum(a => a.Capacity));	0
31548503	31544379	How to clean up after a Visual Studio Tools For Office (VSTO) 2010 Outlook Add-In completes	GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n GC.WaitForPendingFinalizers();	0
28849181	28848421	How to send and receive an unexpectable size of json data over http?	private static TResponse GetResponseValue<TResponse>(WebRequest webRequest)\n{\n    using (var webResponse = webRequest.GetResponse())\n    using (var responseStream = webResponse.GetResponseStream())\n    using (var streamReader = new StreamReader(responseStream))\n    using (var jsonTextReader = new JsonTextReader(streamReader))\n    {\n        var jsonSerializer = new JsonSerializer();\n        return jsonSerializer.Deserialize<TResponse>(jsonTextReader);\n    }\n}	0
7343086	7342784	Add more rows to a gridview	private void showMoreButton_Click(object sender, EventArgs e)\n{\n    int i = 1;\n    while(i <= numberOfRowsToDisplay)\n    {\n        dataGridView1.Rows.Add(yourDataStream[numberOfRowsDisplayed + i][0], yourDataStream[numberOfRowsDisplayed + i][1]);\n        i++;\n    }\n    numberOfRowsDisplayed = numberOfRowsDisplayed + numberOfRowsToDisplay;        \n}	0
18121699	18114950	Enity Framework updating with a child table causing errors	foreach (var t in foundDefinition.Tables.ToList())\n    Context.Tables.Remove(t);\n\nfoundDefinition.Tables = batchToUpdate.Tables;\nthis.context.SaveChanges();	0
14081309	14081220	Screen capturing in logon screen	ScreenCapture sc = new ScreenCapture();\n// capture entire screen, and save it to a file\nImage img = sc.CaptureScreen();\n// display image in a Picture control named imageDisplay\nthis.imageDisplay.Image = img; \n// capture this window, and save it\nsc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);	0
19873201	19872805	How to set Filter in run time ? for gridview in C#, Winforms, DevExpress	// Create a data adapter. \nOleDbDataAdapter adapter = \n    new OleDbDataAdapter("SELECT * FROM gridview", connection);\n\n// Create and fill a dataset. \nDataSet sourceDataSet = new DataSet();\nadapter.Fill(sourceDataSet);\n\n// Specify the data source for the bindingsource. \ninvoiceBindingSource.DataSource = sourceDataSet.Tables[0];\n\n// Specify the data source for the grid control. \ngridControl1.DataSource = invoiceBindingSource;\n\n// error show in this line\ninvoiceBindingSource.Filter = \n    string.Format("invoice_number = '{0}'", textEdit5.Text);	0
24114128	24111672	Microsoft pubCenter ads not showing in my WP8 app	xmlns:UI="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"\n\n<UI:AdControl ApplicationId="test_client" AdUnitId="Image480_80" Height="80" Width="480" VerticalAlignment="Bottom" ErrorOccurred="AdControl_ErrorOccurred"/>	0
31633083	31632643	How should I get user input in a model using MVVM pattern?	public class WebService {\n    public void Login(string username, string password) { ... }\n    public Data GetData() { ... }\n    public void AddNewData(Data data) { ... }\n}	0
24235538	24197338	How do I create a Many to Many Relationship in CRM 2013 using Web Services	crmService.AddLink(account, "company_a_c", contact);\ncrmService.SaveChanges();	0
14649750	14647216	c# treeview ignore double click only at checkbox	private void TreeViewDoubleClick(object sender, EventArgs e)\n{\n    var localPosition = treeView.PointToClient(Cursor.Position);\n    var hitTestInfo = treeView.HitTest(localPosition);\n    if (hitTestInfo.Location == TreeViewHitTestLocations.StateImage) \n        return;\n\n    // ... Do whatever other processing you want\n}	0
2005037	2004971	Clearing checkboxes within groupboxes	setCheckBoxesUnChecked(this);\n\npublic function setCheckBoxesUnChecked(Control parent)\n{\n    foreach (Control ctrl in parent.Controls)\n    {\n        if (ctrl is CheckBox)\n            ((CheckBox)ctrl).Checked = false;\n\n        setCheckBoxesUnChecked(ctrl);\n    }\n}	0
2903820	2903762	Use TinyInt to hide/show controls?	class Program {\n    static void Main(string[] args) {\n        MyButtons buttonsVisible = MyButtons.Button1 | MyButtons.Button2;\n        buttonsVisible |= MyButtons.Button8;\n\n        byte buttonByte = (byte)buttonsVisible; // store this into database\n\n        buttonsVisible = (MyButtons)buttonByte; // retreive from database\n    }\n}\n\n[Flags]\npublic enum MyButtons : byte {\n    Button1 = 1,\n    Button2 = 1 << 1,\n    Button3 = 1 << 2,\n    Button4 = 1 << 3,\n    Button5 = 1 << 4,\n    Button6 = 1 << 5,\n    Button7 = 1 << 6,\n    Button8 = 1 << 7\n}	0
29899492	29899288	Can't get Value in a SelectListItem to be read as a string	var Dgates = cc_Db.Dim_Responsibility.Select(new{\n              Value = s.Responsibility_Key,\n              Text = s.Responsibility + " - " + s.Level\n}).ToList().Select(a => new SelectListItem\n          {\n              Value = a.Value.ToString(),\n              Text = a.Text\n          }).ToList();	0
23564866	23564552	How to initialize a multi - dimensional array of struct	struct test_struct\n    {\n        double a, b, c, d, e;\n        public test_struct(double a, double b, double c, double d, double e)\n        {\n            this.a = a;\n            this.b = b;\n            this.c = c;\n            this.d = d;\n            this.e = e;\n        }\n    };\n\n    private test_struct[,] Number =\n    {\n        {\n\n            new test_struct(12.44, 525.38, -6.28, 2448.32, 632.04),\n            new test_struct(-378.05, 48.14, 634.18, 762.48, 83.02),\n            new test_struct(64.92, -7.44, 86.74, -534.60, 386.73),\n\n        },\n\n        {\n            new test_struct(48.02, 120.44, 38.62, 526.82, 1704.62),\n            new test_struct(56.85, 105.48, 363.31, 172.62, 128.48),\n            new test_struct(906.68, 47.12, -166.07, 4444.26, 408.62),\n        },\n    };	0
32339173	32337875	Populate DataGridView with a default empty row	//put your connection string\n//example: @"data source=(localdb)\v11.0;initial catalog=YourDatabase;integrated security=True;"\n//example @".\sqlexpress;;initial catalog=YourDatabase;integrated security=True;"\nvar connection = W"Your Connection String" ;\n//your command\n//example: "SELECT * FROM Category"\nvar command = "Your Command";\n\nvar tableAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);\nvar dataTable= new DataTable();\n//Get data\ntableAdapter.Fill(dataTable);\n\n//Set databindings\nthis.bindingSource1.DataSource = dataTable;\nthis.dataGridView1.DataSource = this.bindingSource1;\nthis.bindingNavigator1.BindingSource = this.bindingSource1;	0
14592705	14592579	IN clause in SQL with no value - C#	var query = @"SELECT * FROM TableA"\nif(activeNames.length > 0)\n  query += " WHERE NOT Name IN (" + names + ")";	0
18188420	18188198	How To Get Label Text Value On CheckChange Event	CheckBox chk = (CheckBox)sender; \nGridViewRow gr = (GridViewRow)chk.Parent.Parent;\nvar lbl = (Label) gr.FindControl("lblTitle");  \nif(lbl !=null)\n{          \n    var lblText = lbl.Text;\n}	0
17974	17944	How to Round Up The Result Of Integer Division	int pageCount = (records + recordsPerPage - 1) / recordsPerPage;	0
24635034	24634988	How to get last string character before "."	String Test="~/Images/31/Demo.jpg";\nPath.GetFileNameWithoutExtension(Test);	0
24622153	24621527	Matching property/value data between two arrays	static DateTime GetLatestHeartBeat(string[] props, string[] vals)\n    {\n        ConcurrentBag<int> heartIndxs = new ConcurrentBag<int>();\n        // find the indices of "Heart" in parallel\n        Parallel.For(0, props.Length,\n            index =>\n            {\n                if (props[index].Contains("Heart"))\n                {\n                    heartIndxs.Add(index);\n                }\n            });\n        // loop over each heart index to find the latest one\n        DateTime latestDateTime = new DateTime();\n        foreach (int i in heartIndxs)\n        {\n            DateTime currentDateTime;\n            if (DateTime.TryParse(vals[i], out currentDateTime) && (currentDateTime > latestDateTime))\n                latestDateTime = currentDateTime;\n        }\n\n        return latestDateTime;\n    }	0
32397661	32397051	Datatable with Parent and Child to JSON format	var obj = dt.AsEnumerable()\n            .GroupBy(r => r["Head"])\n            .ToDictionary(g => g.Key.ToString(),\n                          g => g.Select(r => new {\n                                                item = r["Item"].ToString(),\n                                                quantity = (int)r["Quantity"]\n                                             })\n                                .ToArray());\n\nvar json = JsonConvert.SerializeObject(obj);	0
26126757	26122002	Using Streamreader to Convert File Contents to String Array, then Compressing	string jobDirVar = [FilePath];\n    byte[] bytesToCompress = File.ReadAllBytes(jobDirVar);\n    byte[] decompressedBytes = new byte[bytesToCompress.Length];\n    using (FileStream fileToCompress = File.Create(FilePath))\n        {\n            using (GZipStream compressionStream = new GZipStream(fileToCompress, CompressionMode.Compress))\n            {\n                compressionStream.Write(bytesToCompress, 0, bytesToCompress.Length);\n            }\n        }\n\n        using (FileStream fileToDecompress = File.Open(FilePath, FileMode.Open))\n        {\n            using (GZipStream decompressionStream = new GZipStream(fileToDecompress, CompressionMode.Decompress))\n            {\n                decompressionStream.Read(decompressedBytes, 0, bytesToCompress.Length);\n            }\n        }	0
4755812	4755533	Validate CSV file	public abstract class RuleBase\n{\n  public abstract bool Test();\n  public virtual bool CanCorrect()\n  { \n     return false;\n  }\n}	0
5486326	5486227	Include JavaScript files from a control if the files have not been included before	if (!Page.ClientScript.IsClientScriptIncludeRegistered(typeof(MyControl), "someName")) {\n    Page.ClientScript.RegisterClientScriptInclude(typeof(MyControl), "someName", ResolveUrl("./something.js"));\n}	0
29680425	23943723	Fluent Validator missing SetCollectionValidator() method	RuleForEach(e => e.PhoneNumbers).SetValidator(new PhoneValidator());	0
14770251	14770228	How to convert a file of any type into byte array?	var bytes = File.ReadAllBytes(pathToFile)	0
24003892	24003241	Get Data from Controls created by listview?	//Iterate through the rows of the List View\nforeach (item ListViewItem in lstView.Items)\n{\n     //If the control is a data item\n     if (item.ItemType = ListViewItemType.DataItem)\n     {\n          RadioButtonList  rbl = item.FindControl("rblAnswers") as RadioButtonList;\n          if(rbl != null)\n          {\n          //do something\n          }\n\n          TextBox tb = item.FindControl("txttest") as TextBox;\n          if(tb != null)\n          {\n          //do something    \n          }\n     }\n}	0
26207422	26207298	regex for base64 encoded crt file	var START = "-----BEGIN CERTIFICATE-----";\nvar END = "-----END CERTIFICATE-----";\nvar certs = Regex.Matches(DATA, START+ "(.+?)" + END,RegexOptions.Singleline)\n                 .Cast<Match>()\n                 .Select(m => Convert.FromBase64String(m.Groups[1].Value))\n                 .ToList();	0
22918579	22918508	Must declare the scalar variable "@Email"	SqlCommand cmd = new SqlCommand("Select * from tblRegister where Email = @Email", con);\n  cmd.Parameters.AddWithValue("@Email", lblEmail.Text);\n  SqlDataReader rdr = cmd.ExecuteReader();\n  //...	0
25315582	25314414	How can I check if a line contains specific string from a list of strings?	string[] line = { "peter has", "julia has", "elvis has", "carol has" };\nstring[] mylist = {"peter", "elvis"};\nList<string> newitems = new List<string>();\nstring checkeditem;\nforeach (var item in line)\n{\n    foreach (var check in mylist)\n    {\n        if (item.Contains(check))\n        {\n            checkeditem = item.Replace("has", "checked");\n            newitems.Add(checkeditem);\n\n        }\n    }\n\n}\n//You can bind the newitems with your textbox1 here	0
32481377	32480861	Factory Methods with PerWebRequest lifestyle	protected void Application_BeginRequest(object sender, EventArgs args)\n{\n    System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);\n}	0
21315236	21312550	how to keep track of running location for a long running parallel program	var tasks = new Queue<Pair<int[],Task>>();\n    foreach (var temp in Generator()) {\n        var arr = temp;\n        tasks.Enqueue(new Pair<int[], Task>(arr, Task.Run(() ={\n            //... use arr as needed\n        }));\n        var tArray = t.Select(v => v.Value).Where(t=>!t.IsCompleted).ToArray();\n        if (tArray.Length > 7) {\n            Task.WaitAny(tArray);\n            var first = tasks.Peek();\n            while (first != null && first.B.IsCompleted) {\n                Storage.UpdateStart(first.A);\n                tasks.Dequeue();\n                first = tasks.Count == 0 ? null : tasks.Peek();\n            }\n        }\n    }\n\n...\nclass Pair<TA,TB> {\n    public TA A { get; set; }\n    public TB B { get; set; }\n    public Pair(TA a, TB b) { A = a; B = b; }\n}	0
22279720	22279696	Comparing Element of list A and B and finding elements that are not present in List B?	List<int> res = A.Except(B).ToList();	0
13720773	13570075	DrawableGameComponent as library, how to handle the content?	Game.Content.Load<Texture2D>	0
17641104	17641084	Concatenate words in a string into a single word string	String concatenatedString = example.Replace(" ", String.Empty);	0
2213737	2213730	Method writing pattern	var c = new SomeClass();\nc.SampleMethod = inputParam => inputParam.ToLower();\nc.DoSomeTaskThatReliesOnSampleMethodReturningAnUpperCaseString();\nc.SampleMethod = null;\nc.DoSomeTaskThatCallsSampleMethod(); // NullReferenceException	0
1154906	1154874	C# : instantiate a List, given a reference to a Type	Type typeList = typeof(List<>);\nType actualType = typeList.MakeGenericType(myType);\nobject obj = Activator.CreateInstance(actualType);	0
18670506	18669887	Assigning an array of pixels to GTK# DrawingArea	byte[] pixels = new byte[width * height * 4];\n// ...\nGdk.GC gc = new Gdk.GC(drawingArea.GdkWindow);\ndrawingArea.GdkWindow.DrawRgb32Image(gc, 0, 0, width, height, RgbDither.None, pixels, width * 4);	0
12790130	12532034	Windows 8 C# Store app - Link to store and reviews	Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store:REVIEW?PFN=MY_PACKAGE_FAMILY_NAME"));	0
10764164	10764131	AutoPostBack="true" will do unexpected table invisible in ASP page	this.xx.Visible = CheckBox1.Checked;	0
10173415	10173390	how to iterate a dictionary<string,string> in reverse order(from last to first) in C#?	foreach( var item in d.Reverse())\n{\n    ...\n}	0
33869631	33869479	How to send parameter in REST api in xamarin.forms?	using (var cl = new HttpClient())\n{\n    var formcontent = new FormUrlEncodedContent(new[]\n    {\n            new KeyValuePair<string,string>("email_id","shahbuddin@peerbits.com"),\n            new KeyValuePair<string, string>("password","shah")\n        });\n\n\n    var request = await cl.PostAsync("http://192.168.1.100/apps/jara/web/api/user/login", formcontent);\n\n    request.EnsureSuccessStatusCode();\n\n    var response = await request.Content.ReadAsStringAsync();\n\n    jsonResponselogin res = JsonConvert.DeserializeObject<jsonResponselogin>(response);\n\n    lbl1.Text = res.code + " " + res.status + " " + res.message;\n\n}	0
26409325	26406368	is it possible to have a select statement in the resultset of a linq query?	from a in table_a\nwhere a.test == 1\norderby a.number\nlet column_b = (from b in table_b where b.column_c == a.column_c select b.column_a).SingleOrDefault()\nselect new { a.column_a, column_b }	0
31571965	31571779	Creating XAML grid rows programatically	StackP = new StackPanel();\nStackP.Orientation = Orientation.Horizontal;	0
31588481	31588331	Max Value from a field as a condition	DELETE \nFROM wgcdoccab \nWHERE numdoc = (\n    SELECT MAX(numdoc) FROM WGCDOCCAB WHERE\n    serie ='1' and tipodoc ='FSS' and contribuinte ='999999990' and  datadoc = CONVERT(varchar(10),(dateadd(dd, -1, getdate())), 120))	0
20000801	20000582	How to keep a one-to-one relationship between polymorphic classes in different layers?	private Dictionary<Type, Func<DomainAbstractClass, PresentationAbstractClass>> factory = \n    new Dictionary<Type, Func<DomainAbstractClass, PresentationAbstractClass>>\n    {\n        { typeof(ConcreteDomainClass1), (x) => new ConcretePresentationClass1(x) },\n        { typeof(ConcreteDomainClass2), (x) => new ConcretePresentationClass2(x) },\n        ....\n    };\n\npublic PresentationAbstractClass ObtainPresentationClassFromDomainClass(DomainAbstractClass domainClass)\n{\n    return factory[domainClass.GetType()](domainClass);\n}	0
33358852	33358438	DataGridView get row values	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if (e.RowIndex > -1)\n        {\n            var val = this.dataGridView1[e.ColumnIndex,  e.RowIndex].Value.ToString();\n        }\n    }	0
24825639	24825527	Looping until end of String C#	for (int i = 0; i < stringVariable.Length; i++)\n{\n    char x = stringVariable[i]; //is the i'th character of the string\n}	0
10108032	10107647	Extracting digits from a string five at a time in C#	var register = new StringBuilder();\n\nusing(var stream = File.Open("File1.txt"))\n{\n   bool ended, fileEnded;   \n   int buffer;\n   while(!ended)\n   {\n      while(register.Length < 5 && !fileEnded)\n      {\n         buffer = stream.ReadByte();\n         if(buffer == -1)\n         {\n            fileEnded = true;\n            break;\n         }\n\n         var myChar = (char)buffer;\n         if(Char.IsNumber(myChar))\n            StringBuilder.Append(myChar);\n      }\n\n      //at this point you have 5 characters in register (or have run out of file).\n      //perform your logic, then remove the front character\n      register.Remove(0,1);\n\n      //repeat the loop. You won't get any more new characters once you reach the end of file,\n      //but the main loop will keep running until you set ended to true\n      if(WereDone())\n         ended=true;\n   }\n   stream.Close();\n}	0
2959021	2958889	.Net Removing all the first 0 of a string	string Strip0s(string s)\n{\n    return string.Join<int>(".", from x in s.Split('.') select int.Parse(x));\n}	0
24743600	24743387	Change Win8 StyleApp Button and Content Text Color	private void button_Click(object sender, RoutedEventArgs e)\n    {\n        button1.BorderBrush = new SolidColorBrush(Colors.Orange);\n    }	0
10486227	10485763	Combine expressions for Where statement	Pseudo\nvar query = _session.QueryOver<Employee>()\nfor each expression in expressions\n   query = query.Where(expression)	0
6125645	6125578	How can I use ':' character in a name of XDocument element?	XNamespace ns = "http://purl.org/dc/elements/1.1/";\nvar document = new XDocument(\n            new XDeclaration("1.0", "utf-8", null),\n            new XElement("rss", new XAttribute(XNamespace.Xmlns + "dc", ns)\n                         new XElement("channel",\n                                      new XElement("title", "test"),\n                                      new XElement(ns + "creator", "test"),\n            ....	0
4719217	4709289	entity framework when many to many is holding data	INSERT INTO Texts \nSELECT TD.TextDescriptionId, L.LanguageId, '', 0, GETDATE(), GETDATE(), L.TwoLetterISOLanguageName \nFROM TextDescriptions TD \nINNER JOIN Languages L ON 1 = 1 \nLEFT JOIN Texts T ON \nT.TextDescriptionId = TD.TextDescriptionId AND \nT.LanguageId = L.LanguageId \nWHERE TextId IS NULL	0
20804782	20804657	Stop program from running when pressed different keys from the statement	string key_pressed="";\nwhile(key_pressed=="")\n{\n  string key_pressed = Console.ReadLine().ToUpper();\n  if (key_pressed.Equals("A"))\n  {\n     //code here\n  }\n  else if (key_pressed.Equals("B"))\n  {\n    //code here\n  }\n  // else-if cases for C and D\n  else\n  {\n    // code for the "wrong key" case. Beep, perhaps.\n    key_pressed=""; // so the loop continues\n  }\n} // end of while loop	0
28337348	28315897	Filtering a data tree, building a new tree	DataTreeNode<string> createFilteredTree(List<List<DataTreeNode<string>>> paths, List<int> types, List<bool> flags, string filter, string title)\n    {\n        DataTreeNode<string> root = new DataTreeNode<string> (new keyValuePair<string, int> ("SEARCH RESULTS", 0));\n        foreach (List<DataTreeNode<string>> path in paths)\n        {\n            if (!passesFilter (path, types, flags, filter))\n                continue;//don't need this path\n            path.Reverse ();\n            DataTreeNode<string> curNode = root;\n            DataTreeNode<string> found;\n            foreach (DataTreeNode<string> node in path)\n            {\n                found = curNode.FindTreeNode (node1 => node1.Data.Equals (node.Data));\n                if (found == null)\n                {\n                    found = node.Clone ();\n                    curNode.AddChild (found);\n                }\n                curNode = found;\n            }\n        }\n        return root;\n    }	0
19215580	19215442	declaring a list inside a class and it's the same list in every instance?	using System.IO;\nusing System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n       MyClass one = new MyClass();\n        MyClass two = new MyClass();\n        MyClass three = new MyClass();\n\n        one.Load(10);\n        two.Load(50);\n        three.Load(100);\n\n        System.Console.WriteLine("One.Count  " + one.Params.Count);\n        System.Console.WriteLine("Two.Count " +two.Params.Count);\n        System.Console.WriteLine("Three.Count  "+ three.Params.Count);\n    }\n}\n\npublic class MyClass\n {\n     public List<int> Params = new List<int>();\n\n      public void Load(int data)\n        {\n            Params.Add(data);\n        }\n}	0
25942157	25941763	Trying to apply bold to a whole row but keep getting null reference - NPOI	var style = wb2.CreateCellStyle();\nstyle.SetFont(font);\n\nr = sheet.CreateRow(0);\nr.RowStyle = style;	0
24784385	24387788	How do I ensure I have authorization to the root page of my website?	if (Request.AppRelativeCurrentExecutionFilePath == "~/")\n    HttpContext.Current.RewritePath("default.aspx");	0
2937738	2937712	Regex to extract portions of file name	compNumber:   /^R\d{6}(COMP|CRIT)(?=_)/\ndate:         /(?<=_)\d{8}(?=_)/\nserialNumber: /(?<=_)\d{3}[A-Z]\d{4}(?=_)/\n\npart:         /(?<=_).*?(?=_)/	0
21773692	20659894	How to generate basic reports in Winforms Devexpress?	private void button1_Click(object sender, EventArgs e) \n{\n    // Create a report. \n    XtraReport1 report = new XtraReport1();\n\n    // Show the report's preview. \n    ReportPrintTool tool = new ReportPrintTool(report);\n\n    tool.ShowPreview();\n}	0
30469086	30462575	to labels put random values from database c#	OleDbConnection connection = new OleDbConnection();\n            connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=names.mdb";\n            connection.Open();\n            OleDbCommand command = new OleDbCommand();\n            command.Connection = connection;\n            command.CommandText = "SELECT ID,nickname FROM names ORDER BY rnd(ID)";\n            foreach (Control control in Controls)\n  {\n    if (control is Label)\n    {\n      OleDbDataReader reader = command.ExecuteReader();\n      reader.Read();\n      control.Text = reader["nickname"].ToString();\n      reader.Close();\n    }\n  }\n            connection.Close();	0
13632248	13516555	Obtaining Depth Information of Facial Points Using Kinect	private EnumIndexableCollection<FeaturePoint, PointF> ColourPoints;\n\n        private EnumIndexableCollection<FeaturePoint, Vector3DF> DepthPoints;	0
9937415	9937373	File Upload in database using fileupload control	protected void btnSubmit_Click(object sender, EventArgs e) \n {\n  if (Fu.HasFile) {\n  string filepath = Fu.PostedFile.FileName;\n  //save the file to the server\n  Fu.PostedFile.SaveAs(Server.MapPath(".\\") + file);\n  lblStatus.Text = "File Saved to: " + Server.MapPath(".\\") + file;\n\n }\n}	0
20961047	20960316	Get folder path from Explorer window	IntPtr MyHwnd = FindWindow(null, "Directory");\n    var t = Type.GetTypeFromProgID("Shell.Application");\n    dynamic o = Activator.CreateInstance(t);\n    try\n    {\n        var ws = o.Windows();\n        for (int i = 0; i < ws.Count; i++)\n        {\n            var ie = ws.Item(i);\n            if (ie == null || ie.hwnd != (long)MyHwnd) continue;\n            var path = System.IO.Path.GetFileName((string)ie.FullName);\n            if (path.ToLower() == "explorer.exe")\n            {\n                var explorepath = ie.document.focuseditem.path;\n            }\n        }\n    }\n    finally\n    {\n        Marshal.FinalReleaseComObject(o);\n    }	0
33624615	33561429	A speedy way to match a text to multiple regex pattern	Parallel.For	0
15812245	15200648	c# Outlook add-in custom Icons with custom Region Form	IPM.Note.XXXX	0
29837348	29834454	Setting a button icon in C#	btnEdit.Icon = new SymbolIcon(Symbol.Cancel);	0
17384696	17384638	Setting values to EMPTY but not NULL by default in C#	public personalinfo info = new personalinfo();\npublic addressinfo currentaddr = new addressinfo();\npublic telephone currenttel = new telephone();	0
5819064	5818925	How to draw ishihara-transformations (circles in circle without intersection)?	struct { double x, y, r; } Circle;\n\nbool circleIsAllowed(const std::vector<Circle>& circles, const Circle& newCircle)\n{\n   for(std::vector<Circle>::const_iterator it = circles.begin(); it != circles.end(); ++it) // foreach(Circle it in circles)\n   {\n      double sumR = it->r + newCircle.r; // + minimumDistanceBetweenCircles (if you want)\n      double dx = it->x - newCircle.x;\n      double dy = it->y - newCircle.y;\n      double squaredDist = dx*dx + dy*dy;\n      if (squaredDist < sumR*sumR) return false;\n   }\n\n   return true; // no existing circle overlaps\n}	0
22039898	22039094	C# - Apply attribute to method conditionally from app.config	[TestClass]\npublic class TestsForAreaX\n{\n    [TestCategory("LongRunning"), TestMethod]\n    public void TestFoo()\n    {\n        //Do test logic here\n    }\n    [TestCategory("ShortRunning"), TestMethod]\n    public void TestBar()\n    {\n      //Do test logic here\n    }\n} enter code here	0
23562937	23562600	How can i make my exe to be bounded to some other exe?	Application.exit()	0
10896879	10896617	HTML Encoding alpha, beta, gamma	public string ForceHtmlEncode(string input)\n{\n    return string.Concat(input.Select(c => "&#" + (int)c + ";"));\n}	0
12908119	12908044	Dictionary Contains key, but crashes saying it doesn't	public object RetrieveItemRun(int item)\n    {\n        if (dictionary.ContainsKey(item))\n        {\n            MessageBox.Show("Retrieving" + item.ToString());\n            return dictionary[item];\n        }\n        return null;\n    }	0
27114482	27110049	Code to convert a .docx to an ooxml document package	private WordprocessingMLPackage getPkgFromString(string wordOpenXML)\n    {\n\n        // The string is UTF-16; convert it to UTF-8\n        byte[] utf16Bytes = Encoding.Unicode.GetBytes(wordOpenXML);\n        byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);\n\n        return  WordprocessingMLPackageFactory.createWordprocessingMLPackage(utf8Bytes);\n    }	0
9667066	9666657	How to move focus on next cell in a datagridview on Enter key press event	private void dataGridView1_KeyDown(object sender, KeyEventArgs e)\n        {\n            if (e.KeyCode == Keys.Enter)\n            {                \n                e.SuppressKeyPress=true;\n                int iColumn = dataGridView1.CurrentCell.ColumnIndex;\n                int iRow = dataGridView1.CurrentCell.RowIndex;\n                if (iColumn == dataGridView1.Columns.Count-1)\n                    dataGridView1.CurrentCell = dataGridView1[0, iRow + 1];\n                else\n                    dataGridView1.CurrentCell = dataGridView1[iColumn + 1, iRow];\n\n            }\n        }	0
18143096	18122312	ABCPDF: Split PDF files into single page PDF files	Doc theSrc = new Doc();\ntheSrc.Read("C://development//pdfSplitter//Bxdfbc91ca-fc05-4315-8c40-798a77431ee0xP.pdf");\n\nint srcPagesID = theSrc.GetInfoInt(theSrc.Root, "Pages");\nint srcDocRot = theSrc.GetInfoInt(srcPagesID, "/Rotate");\n\nfor (int i = 1; i <= theSrc.PageCount; i++)\n{   \n    Doc singlePagePdf = new Doc();\n    singlePagePdf.Rect.String = singlePagePdf.MediaBox.String = theSrc.MediaBox.String;\n    singlePagePdf.AddPage();\n    singlePagePdf.AddImageDoc(theSrc, i, null);\n    singlePagePdf.FrameRect();\n\n    int srcPageRot = theSrc.GetInfoInt(theSrc.Page, "/Rotate");\n    if (srcDocRot != 0)\n    {\n        singlePagePdf.SetInfo(singlePagePdf.Page, "/Rotate", srcDocRot);\n    }\n    if (srcPageRot != 0)\n    {\n        singlePagePdf.SetInfo(singlePagePdf.Page, "/Rotate", srcPageRot);\n    }\n\n    singlePagePdf.Save("C://development//pdfSplitter//singlePDF//singlePage"+i+".pdf");\n    singlePagePdf.Clear();\n}\ntheSrc.Clear();	0
21096706	21077173	Can't remove items from ComboBox without crashing	private void deleteItem(ComboBox comboBox, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Delete)\n    {\n        if (comboBox.Items.Count == 1)\n        {\n            comboBox.Items.Clear();\n\n            return;\n        }\n\n        comboBox.Items.Remove(comboBox.SelectedItem);\n\n        e.Handled = true; // I do not think this really contributes anything in this case.\n    }\n}	0
32355244	32354454	Fluent NHibernate mapping ignore all classes that inherit from generic base class	AutoMap.AssemblyOf<TEntity>().Where(x => x != typeof (Repo<TEntity, TOverride>));	0
16464238	16462282	DateTime format with milliseconds for DevExpress control EditMask property	// Append millisecond pattern to current culture's full date time pattern \nstring fullPattern = DateTimeFormatInfo.CurrentInfo.FullDateTimePattern;\nfullPattern = Regex.Replace(fullPattern, "(:ss|:s)", "$1.fff");	0
28828810	28828407	Selecting least common item from an enum	foreach (var enumVal in Enum.GetValues(Minute))\n{\n    if (reservations.All(r => r.Minute != enumVal))\n    {\n        return enumVal;\n    }\n}\n\nreturn reservations.Where(r => r.Hour == Hour.eleven)\n                   .GroupBy(r => r.Minute)\n                   .OrderBy(m => m.Count())\n                   .Select(rr => rr.Key)\n                   .Last();	0
5867388	5848990	Retrieve an object in one DB4O session, store in another ('disconnected scenario')	Person person = new Person() { FirstName = "Charles", LastName = "The Second" };\nDb4oUUID uuid;\n\nusing (IObjectContainer client = server.OpenClient())\n{\n    // Store the new object for the first time\n    client.Store(person);\n\n    // Keep the UUID for later use\n    uuid = client.Ext().GetObjectInfo(person).GetUUID();\n}\n\n// Guy changed his name, it happens\nperson.FirstName = "Lil' Charlie";\n\nusing (var client = server.OpenClient())\n{\n    // Get a reference only (not data) to the stored object (server round trip, but lightweight)\n    Person inactiveReference = (Person) client.Ext().GetByUUID(uuid);\n\n    // Get the temp ID for this object within this client session\n    long tempID = client.Ext().GetID(inactiveReference);\n\n    // Replace the object the temp ID points to\n    client.Ext().Bind(person, tempID);\n\n    // Replace the stored object\n    client.Store(person);\n}	0
23883666	23883632	Getting a value from database in C#	lblID.Text = reader.GetValue(0).ToString();	0
4295221	4295198	Nested lists, how I can do this with lambda expression?	var queries = list.SelectMany(sublist => sublist).ToList();	0
17658196	17656082	Trouble connecting to Oracle with c#	System.Data.OracleClient	0
8379632	8337239	How do I calculate angle from two coordinates?	float x1 = 9112.94f;\nfloat y1 = 22088.74f;\n\nfloat x2 = 9127.04f;\nfloat y2 = 22088.88f;\n\nfloat angleRadians;\n\nfloat diffX = x2 - x1;\nfloat diffY = y2 - y1;\n\nfloat atan2Result = (float)Math.Atan2(diffX, diffY);\nangleRadians = atan2Result / 2;\nif (angleRadians < 0.0f)\n    angleRadians += (float)Math.PI;\n\nfloat tempCosine = (float)Math.Cos(angleRadians);\nfloat tempSine = -((float)Math.Sin(angleRadians));	0
14262547	14256486	Use images of my resources - Compact Framework	Image myImage = Properties.Resources.my_image;\n\npictureBox1.Image = myImage;\npictureBox2.Image = myImage;\npictureBox3.Image = myImage;\npictureBox4.Image = myImage;\n...\npictureBoxN.Image = myImage;\n\n// Later on when you are done using it\nmyImage.Dispose();	0
23077701	23077687	Querying a colunm from SQL database using linq	var ids = from customer in db.Customers select customer.AccountNo;	0
9210148	9210059	Deserialize XML into Dictionary<string, string>	XDocument.Load([file path, stream, whatever]).Descendants("data").Descendants()\n    .ToDictionary(element => element.Name, element => element.Value)	0
11665854	11665696	How do I get a culture specific short date string?	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n    var item = (DateTime)value;\n    if (item != null)\n    {\n        return item.ToString(culture.DateTimeFormat.ShortDatePattern, culture);\n    }\n    return null;\n}	0
12207226	12207156	Linq to XML using Take() to get first two elements	var commentsList = doc.Descendants("comment").Take(2);	0
9658566	9658463	C# XNA How do I set a Texture2D to a single color?	Texture2D texture = /*copy the texture you want to change*/;\nPixel pixel;/*note it's really inexact, so don't mind it, the idea is to show how it would be done*/\nfor(int i=0; i<texture.width; i++)\n{\n  for(int j=0; j<texture.height; j++)\n  {\n    pixel = texture.GetPixel(i, j);\n    if(pixel.Color.A==1)\n      pixel.Color = Color.White;\n  }\n}	0
9605895	9605592	How to set a default zoom of 100% using iTextSharp 4.0.2?	PdfWriter writer = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);\n\n//this creates a new destination to send the action to when the document is opened. The zoom in this instance is set to 0.75f (75%). Again I use doc.PageSize.Height to set the y coordinate to the top of the page. PdfDestination.XYZ is a specific PdfDestination Type that allows us to set the location and zoom.\nPdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 0.75f);\n\n//open our document\ndoc.Open();\n\n//here you put all the information you want to write to your PDF\n\n//create a new action to send the document to our new destination.\nPdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);\n\n//set the open action for our writer object\nwriter.SetOpenAction(action);\n\n//finally, close our document\ndoc.Close();	0
4669256	4668804	Visual Studio: Setting a conditional breakpoint without setting an unconditional one first	Sub addBreakpointWithCondition()\n    Dim cond As String = InputBox("Enter the condition")\n    DTE.Debugger.Breakpoints.Add(File:=DTE.ActiveDocument.FullName,\n        Line:=DTE.ActiveDocument.Selection.CurrentLine, Condition:=cond)\nEnd Sub	0
32764208	32763459	How to show validatioin errors on different columns from IDataErrorInfo?	public class ViewModel : INotifyPropertyChanged, IDataErrorInfo\n{\n     // Do this for each involved property in your ViewModel\n     private string _newReferralName;\n     public string NewReferralName\n     {\n         get { return _newReferralName; }\n         set\n         {\n             _name = value;\n             RaisePropertyChanged("NewReferralName");\n\n             // The tricky part. Notify that the related properties \n             // have to be refreshed (in the View) and, thus, reevaluated\n             RaisePropertyChanged("Phone");\n             RaisePorpertyChanged("PriorAuthorizationNumber");\n         }\n     }\n     ...\n\n     // INotifyPropertyChanged implementation\n     public event PropertyChangedEventHandler PropertyChanged;\n     void RaisePropertyChanged(string prop)\n     {\n         if (PropertyChanged != null)\n            PropertyChanged(this, new PropertyChangedEventArgs(prop));\n     }\n\n}	0
14896108	14896083	ToString() number formatting	x.ToString("0.######")	0
10269880	10269794	How to call CreateUser function manually in asp.net membership provider	CreateUser()	0
1173986	1173955	best way to find end of body tag in html	// Given an HTML document in "htmlDocument", and new content in "newContent"\nstring newHtmlDocument = htmlDocument.Replace("</body>", newContent+"</body>");	0
15142455	15142388	How to poll from worker thread for cancellation	List<Action> actions = new List<Action>()\n{\n    ()=> DoTask1(cancelToken),\n    ()=> DoTask2(cancelToken),\n    ()=> DoTask3(cancelToken),\n    ()=> DoTask4(cancelToken),\n};\n\nforeach(var action in actions)\n{\n    if (!cancelToken.IsSet)\n        action();\n}	0
8511361	8511284	Getting Filename from url in C#	Request.Url.AbsolutePath	0
26369705	26353031	How to change the Brightness stetting on Windows Phone 8.1 camera?	_mediaCaptureMgr.VideoDeviceController.Brightness.Capabilities.Supported	0
7441372	7441344	Is it possible to query a user-specified column name without resorting to dynamic SQL?	"WHERE " + Sanitize(column) + " = @Value");	0
3316748	3316712	C# WindowsForms equivalent for VB6 indexed controls	protected void cmdButtons_Click(object sender, System.EventArgs e)	0
11672595	11672542	ASP.NET MVC4 Redirect to login page	[Authorize]	0
5955009	5954889	Showing Notes using String.Join	var showNotes = from r in em.Test\n                where r.Name == getName\n                select new { Name = r.UserName, Notes = r.Note }\n\nvar userNotes = showNotes.Select((x,i) => string.Format("{0}. {1}-{2}", \n                                                        i, \n                                                        x.Notes, \n                                                        x.Name));\n\ntbShowNote.Text = String.Join(Environment.NewLine, userNotes );	0
3942608	3942017	Reading Stream and open that document	private void LoadAttachment()\n    {\n            byte[] ImageData = ... get data from somewhere ...\n\n            Response.Buffer = true;\n            String filename = "itakethis.fromdatabase";\n            Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);\n            Response.ContentType = GetMimeType(filename);//you can try to extrapolate it from file extension\n            if(ImageData.Length > 0)\n                Response.BinaryWrite(ImageData);\n            else\n                Response.BinaryWrite(new byte[1]);\n            Response.Flush();\n            ApplicationInstance.CompleteRequest();\n    }	0
29621443	29608778	WPF - GetBindingExpression in PropertyChangedCallback of DependencyProperty	private static void TestChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)\n    {\n        var textBox = (TextBox)o;\n        // start listening\n        textBox.LayoutUpdated += SomeMethod();\n    }\n\n   private static void SomeMethod(...)\n   {\n      // this will be called very very often\n      var expr = textBox.GetBindingExpression(TextBox.TextProperty); \n      if(expr != null)\n      {\n        // finally you got the value so stop listening\n        textBox.LayoutUpdated -= SomeMethod();	0
8926594	8926293	Linq subquery with in a query	userInfo = (from myUserField in myUserFields\n            join otherUserField in otherUserFields\n            on myUserField.FieldName == otherUserField.FieldName\n            where otherUserField.Chosen == true \n            select new UserInfoModel {\n                MyCaption = otherUserField.FieldAlias,\n                MyValue = myUserField.FieldName\n            }).ToList();	0
18205209	18204957	XMLDocument to xml file	var doc = new XmlDocument();\nvar node = doc.ImportNode(returnedDataFromWebMethod, true);\ndoc.AppendChild(node);\ndoc.Save("output.xml");	0
22451888	22447331	Manually add a migration?	add-migration yourMigrationName	0
24921508	24791915	Databinding to a Combobox, two List<object>, selected value should be copied AND shown	for(int i = 0, i < 21, i++)\n{\n    listCombo[i].SelectedIndex = listOne.IndexOf(listOne.Where(x => x.name == listTwo[i].name).First();\n}	0
19519268	18652240	Inserting an empty row in DataGridView	DataGridViewRow row = dataGridView1.Rows[Index];\nrow.DividerHeight = 1;	0
15275377	15275217	Split a filename in 2 groups	int lengthFilename = filename.Length - 4; //substract the string ".xls";\nint middleLength = lengthFilename/2;\nString filenameA = filename.SubString(0, middleLength);\nString filenameB = filename.SubString(middleLength, lengthFilename - middleLength);	0
16549188	16548880	Merge duplicate datatable records into XML document	var X = from item in Data\n        group item by item.cat1 into g\n        select new XElement(\n            "CATEGORY",\n            new XAttribute("NAME", g.Key),\n            from it in g\n            group it by it.cat2 into k\n            select new XElement("CATEGORIES2", new XAttribute("NAME", k.Key),\n                from i in k.Select(x=>x.cat3).Distinct()\n                select new XElement("CATEGORIES3", new XAttribute("NAME",i))\n                )\n        );	0
24606381	24605884	How to pop up a childwindow from another .xam file button click?	AddChildButton objChild = new AddChildButton();\n    objChild.Show();	0
19524619	19523008	Verifying set with another mock returns null	[Test]\npublic void Test1()\n{\n    string testString = "test";\n\n    mockOne.SetupGet(o => o.Val).Returns(testString);\n    UnitUnderTest.CopyVal();\n    mockTwo.VerifySet(t => t.Val = It.Is<string>(x => x == mockOne.Object.Val));\n}	0
14465239	14465132	WPF - PreviewMouseLeftButtonDown finding the visual owning control of e.OriginalSource	e.Source	0
26844824	26844095	mssql query, set non xml data size	using (var testConnection = new SqlConnection()) {\n    testConnection.ConnectionString = @"Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;";\n    testConnection.Open();\n    using (var testCommand = new SqlCommand("exec prAdvListToXML", testConnection))\n    using (XmlReader testXmlReader = testCommand.ExecuteXmlReader())\n    using (XmlWriter testFileWriter = XmlWriter.Create(@"C:\temp\output.xml")) {\n        testFileWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-16'");\n        testFileWriter.WriteNode(testXmlReader, true);\n    }\n}	0
1799333	1799253	Validation on a mobile 6 phone?	public interface IValidatable {\n    public bool IsValid();\n}\n\npublic class TextBoxRequired : Textbox, IValidatable {\n    public bool IsValid() {\n        return !string.IsNullOrEmpty(this.Text);\n    } \n}\n\n//\npublic static class ValidationHelper {\n    public static bool IsFormValid(Form form) {\n        //loop through all controls in the form\n        //find IValidatable and call IsValid\n    }\n}	0
9479797	9479573	Interrupt Console.ReadLine	using System;\nusing System.Threading;\nusing System.Runtime.InteropServices;\n\nnamespace ConsoleApplication2 {\n    class Program {\n        static void Main(string[] args) {\n            ThreadPool.QueueUserWorkItem((o) => {\n                Thread.Sleep(1000);\n                IntPtr stdin = GetStdHandle(StdHandle.Stdin);\n                CloseHandle(stdin);\n            });\n            Console.ReadLine();\n        }\n\n        // P/Invoke:\n        private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };\n        [DllImport("kernel32.dll")]\n        private static extern IntPtr GetStdHandle(StdHandle std);\n        [DllImport("kernel32.dll")]\n        private static extern bool CloseHandle(IntPtr hdl);\n    }\n}	0
32123346	32123321	How to translate this List to Java?	List<String> stopWords = new ArrayList<>(Arrays.asList("ON","OF","THE","AN","A" ));	0
25383140	25325336	How to fake arg constructor JustMock	var expected = "StringArg";\n        string arg = null;\n        Mock.Arrange(() => new A(Arg.AnyString)).DoInstead<string>(x => arg = x);\n\n        new A(expected);\n\n        Assert.Equal(expected, arg);	0
17172435	17172106	Insert Data Set into Oracle Table	string cmdText = "INSERT INTO MY_INSERT_TEST(Col1, Col2, Col3) VALUES(?, ?, ?)";\nusing(OdbcConnection cn = getDBConnection())\nusing(OdbcCommand cmd = new OdbcCommand(cmdText, cn))\n{\n    cn.Open();\n    cmd.Parameters.AddWithValue("@p1", "");\n    cmd.Parameters.AddWithValue("@p2", "");\n    cmd.Parameters.AddWithValue("@p3", "");\n    foreach(DataRow r in dt.Rows)\n    {\n         cmd.Parameters["@p1"].Value =  r["Column3"].ToString());\n         cmd.Parameters["@p2"].Value =  r["Column1"].ToString());\n         cmd.Parameters["@p3"].Value =  r["Column2"].ToString());\n         cmd.ExecuteNonQuery();\n    }\n}	0
32910847	32910787	How to select minimum element without transforming it?	var foo = fooList.Aggregate((f1, f2)=> f1.Bar2 < f2.Bar2 ? f1 : f2);	0
18483871	18483826	How to get a String value from web.config in MVC4	string pathValue = ConfigurationManager.AppSettings["azureLogUrl"];	0
24944486	24941877	GUI Label is staying on screen when camera facing away from object?	void OnGUI \n{\n    if(NPCScreenPosition.z >= Camera.main.nearClipPlane)\n        GUI.Label(new Rect(left, top, 150, 25), gameObject.name.ToString());\n}	0
19773017	19772608	Where to set custom control defaults	[DefaultValue(false)]\npublic new bool AllowUserToAddRows {\n  get { return base.AllowUserToAddRows; }\n  set { base.AllowUserToAddRows = value; }\n}	0
30391593	30381505	ResourceDictionary in wpf as dll application	var rd = new ResourceDictionary();\n   rd.Source = new Uri("pack://application:,,,/GeoLocations Screens;component/ThemedWindowStyle.xaml");\n   Resources.MergedDictionaries.Add(rd);	0
3698470	3698450	How to convert linq selector into predictor	Func<Person, string> projection = x => x.Name;\n\nFunc<Person, bool> predicate = x => projection(x) == customerName;	0
23496019	23495947	Insert to data table where values are equal to mine variables	SqlCeCommand cmd = new SqlCeCommand("update Kambariai set your_field_name='" + textBox1.Text + "' where Kliento ID='" + s + "'and Kambario r??is='" + s1 + "'and Viet? skai?ius='" + s2 + "'and Vie?nag?s laikas dienomis='" + s3 + "'", conn);\ncmd.ExecuteNonQuery();	0
26858885	26858777	How can i check if both textBoxes are with text inside and then to enable another button?	public Form1()\n{\n    InitializeComponent();\n\n    txtHost.TextChanged += textBox_TextChanged;\n    txtUploadFile.TextChanged += textBox_TextChanged;\n\n    textBox_TextChanged(null, null);\n}\n\nprivate void textBox_TextChanged(Object sender, EventArgs e)\n{\n    btnUpload.Enabled = txtHost.TextLength > 0 && txtUploadFile.TextLength > 0;\n}	0
8308214	8308115	using a chart with values from textboxes	double[] yValues = { 10, 27.5, 7, 12, 45.5};\n    string[] xNames = { ?Mike?, ?John?, ?William?, ?George?, ?Alex? };\n   myChart.Series[0].Points.DataBindXY(xNames, yValues);	0
1589487	1585737	WPF: Error using a custom control in the ItemTemplate of another custom control	// not public LineThicknessComboBox()\nstatic LineThicknessComboBox()        \n{\n            DefaultStyleKeyProperty.OverrideMetadata(\n               typeof(LineThicknessComboBox)\n                        , new FrameworkPropertyMetadata(\n                              typeof(LineThicknessComboBox)));\n}	0
13120736	13120063	Update datagridview from last row	if (e.ColumnIndex != 3)\n    return;\n\nint nextRowIndex = e.RowIndex - 1;\nint lastRowIndex = SecondaryGridView.Rows.Count;\n\ntry\n{\n    if (nextRowIndex <= lastRowIndex)\n    {\n        var value = SecondaryGridView.Rows[e.RowIndex].Cells[3].Value.ToString();\n        SecondaryGridView.Rows[nextRowIndex].Cells[2].Value = value;\n    }\n}\ncatch(Exception exception){}	0
1846983	1846975	How do you embed app.config in C# projects?	textBox.Text = Resources.MyConfigValue;	0
14610907	14610518	How to prevent execution of controller actions based on condition?	public class CheckSessionFilterAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        if (filterContext.HttpContext.Session["MyObject"] == null)\n        {\n            // redirect must happen OnActionExecuting (not OnActionExecuted)\n            filterContext.Result = new RedirectToRouteResult(\n              new System.Web.Routing.RouteValueDictionary {\n              {"controller", "Tools"}, {"action", "CreateSession"}\n\n        }\n        base.OnActionExecuting(filterContext);\n    }   \n}	0
19179563	19179491	LINQ get List<string> from List<List<string>> with any	List<string> data = new List<string>();\nList<List<string>> datas = new List<List<string>>();\nList<string> dataSearch = new List<string>();\n\ndataSearch.Add("01");\ndataSearch.Add("02");\n\n// same as your code\n\nvar result = datas.Where(i => dataSearch.Contains(i[0])).ToList();	0
30613659	30612880	convert number of days into years,months,days	var dor = new DateTime(2013, 08, 08);\nvar doj = new DateTime(2000, 02, 14);\n\nvar totalmonths = (dor.Year - doj.Year) * 12 + dor.Month - doj.Month;\ntotalmonths += dor.Day < doj.Day ? -1 : 0;\n\nvar years = totalmonths / 12;\nvar months = totalmonths % 12;\nvar days = dor.Subtract(doj.AddMonths(totalmonths)).Days;	0
6973575	6972521	How do I execute a controller action from an HttpModule in ASP.NET MVC?	public void OnError(HttpContextBase context)\n{\n    context.ClearError();\n    context.Response.StatusCode = 404;\n\n    var rd = new RouteData();\n    rd.Values["controller"] = "error";\n    rd.Values["action"] = "notfound";\n    IController controller = new ErrorController();\n    var rc = new RequestContext(context, rd);\n    controller.Execute(rc);\n}	0
18707575	18683171	Extract a certain part of HTML with XPath and HTMLAbilityPack	foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='yt-lockup clearfix  yt-lockup-video yt-lockup-grid context-data-item']"))\n            {\n                String val = node.Attributes["data-context-item-id"].Value;\n                videoid.Add(val);\n            }	0
32287333	32287252	c# How to get index of panel control placed in tabcontrol's current tabpage	int index = 0;\n foreach (var item in tabControl1.TabPages[tabControl1.SelectedIndex].Controls)\n {\n      if (item is Panel)\n      {\n           Panel panel = (Panel)item;\n           if (panel.Name == label1.Text)\n           {\n                index = tabControl1.TabPages[tabControl1.SelectedIndex].Controls.IndexOf(panel);\n                break;\n           }\n      }\n }	0
18513112	18513075	Is there a shortcut for incrementing a value and setting one at the same time?	value2 = ++value;	0
5949112	5945451	access one web user control datalist Template Item to some othere web user and check validation	UserControl user1 = (UserControl)this.NamingContainer.FindControl("[Object usercontrol]");\nDataList dl = (DataList)user1.FindControl("[Object datalist]");\nLinkButton lbtn = (LinkButton)dl.FindControl("[Object LinkButton]");\n\n// Check the validation\nif(lbtn != null)\n{\n   // Do stuff\n}\nelse\n{\n   // Do other stuff\n}	0
12728327	12727610	Click on Groupcaption in LayoutView	LayoutView View = (sender as LayoutView);\n        var hi = View.CalcHitInfo(e.Location);\n        if (hi.HitTest == LayoutViewHitTest.LayoutItem && hi.LayoutItem is DevExpress.XtraLayout.LayoutControlGroup)\n        {\n            var Border = (hi.LayoutItem.ViewInfo.BorderInfo as DevExpress.Utils.Drawing.GroupObjectInfoArgs);\n            if (Border.CaptionBounds.Contains(e.Location))\n            {\n                MessageBox.Show("Hit Group: " + Border.Caption);\n                return;\n            }\n        }\n        MessageBox.Show("Missed!");	0
16071989	16071929	Getting Sum of Multiple Columns and summing up values for the same id from a list	var query = from r in list\n            group r by r.Grade into g\n            select new {\n               Grade = g.Key,\n               Total = g.Sum(x => x.Col1 + x.Col2 + x.Col3 + x.Col4)\n            };	0
3391453	3391407	Missing constructor in a class derrived from a generic class	public class TeamRepository : GenericRepository<Team, AppDataContext>\n{\n    public TeamRepository() : base() { }\n    public TeamRepository(AppDataContext db) : base(db) { }\n}	0
3631091	3631026	How to determine whether TextChanged was triggered by keyboard in C#?	public class MyForm : Form\n{\n    private bool _ignoreTextChanged;\n\n    private void listView1_SelectionChanged( object sender, EventArgs e )\n    {\n       _ingnoreTextChanged = true;\n       textBoxPilot.Text = listView1.SelectedValue.ToString(); // or whatever\n    }\n\n    private void textBoxPilot_TextChanged( object sender, TextChangedEventArgs e )\n    {\n       if( _ignoreTextChanged )\n       {\n           _ignoreTextChanged = false;\n           return;\n       }\n\n       // Do what you would normally do.\n    }\n}	0
8169168	8169046	Converting Int to String inside a LINQ expression	var groups = // your query;\n\ngroups.ForEach(item => item.group_name = item.group_name + item.mCount.ToString);	0
15386382	15386293	Possible null assignment to entity marked with notnull attribute	public void GetUserList(string url)\n{\n  var request = (HttpWebRequest)WebRequest.Create(url);\n  var responseStream = request.GetResponse().GetResponseStream();\n  if (responseStream != null)\n  {\n    string response;\n    using (var stream = new StreamReader(responseStream))\n    {\n      response = stream.ReadToEnd();\n    }\n    response = DelimiterStrings.Aggregate(response, (current, delim) => current.Replace(delim, "\n"));\n    foreach (var line in response.Split(DelimiterChars))\n    {\n      MainWindow.UserList.Add(line);\n    }\n  }\n}	0
9319603	9187378	Remove a value from querystring in MVC3 and redirect to the resulting URL	protected void StripQueryStringAndRedirect(System.Web.HttpContextBase httpContext, string[] keysToRemove)\n{\n    var queryString = new NameValueCollection(httpContext.Request.QueryString);\n\n    foreach (var key in keysToRemove)\n    {\n        queryString.Remove(key);\n    }\n\n    var newQueryString = "";\n\n    for (var i = 0; i < queryString.Count; i++)\n    {\n        if (i > 0) newQueryString += "&";\n        newQueryString += queryString.GetKey(i) + "=" + queryString[i];\n    }\n\n    var newPath = httpContext.Request.Path + (!String.IsNullOrEmpty(newQueryString) ? "?" + newQueryString : String.Empty);\n\n    if (httpContext.Request.Url.PathAndQuery != newPath)\n    {\n        httpContext.Response.Redirect(newPath, true);\n    }\n}	0
9348653	9348642	How to create user controls with parameters?	public int MyIntProperty { get; set; }	0
17090945	17090890	Access the Application object inside a Window class in WPF?	// assuming that you derivate of Application is named App\n((App)Application.Current).SomePropertyOfApp = ...	0
9777808	9777231	Linq to XML Get parent element attribute value by querying it's children	XDocument xDoc = XDocument.Load(new StringReader(xml));    \n\nvar Tuples = xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "PType")\n            .Join(\n                xDoc.Descendants("Node").Where(n => n.Attribute("Text").Value == "SType"),\n                n1 => n1.Parent,\n                n2 => n2.Parent,\n                (n1, n2) => new\n                {\n                    ParentsValue = n1.Parent.Attribute("Text").Value,\n                    PValue = n1.Element("Node").Attribute("Text").Value,\n                    SValue = n2.Element("Node").Attribute("Text").Value\n                }\n            );\n\n\nvar result = Tuples.Where(n => n.PValue == "12" && n.SValue == "1")\n                   .Select(n => n.ParentsValue)\n                   .ToArray();	0
5312754	5312544	C# XDocument needs to be parsed to XML again	XDocument outer = response.GetResponseStream();\nString innerXml = outer.Element("report").Value;\nXDocument inner = XDocument.Parse(innerXml);	0
8537381	8537147	SQL Server Update DateTime type to null	DateTime? myDate = null;	0
3838179	3837978	Getting to the web part gallery in sharepoint via code	SPSite site = new SPSite( siteCollectionUrl );\nSPWeb web = site.OpenWeb();\nSPList webPartGallery = web.GetCatalog( SPListTemplateType.WebPartCatalog );\n...	0
26282604	6386069	Can AnsiStrings be used by default with Dapper?	Dapper.SqlMapper.AddTypeMap(typeof(string), System.Data.DbType.AnsiString);	0
7966741	7966713	which event will be fired when a particular row is clicked in datagridview?	void dataGridView1_RowHeaderMouseClick( object sender, DataGridViewCellMouseEventArgs e){\n\n    if(e.RowIndex == Whatever row you want){\n      [Do something]\n      }\n\n }	0
33109156	32116778	How to define the suggestion area in a AutoSuggestBox for Windows 10?	var grid = VisualTreeHelper.GetChild(AutoSuggestBox, 0) as Grid;\n           var border = grid?.FindName("SuggestionsContainer") as Border;\n           if (border != null)\n           {\n              var height = border.ActualHeight;\n              Debug.WriteLine(height);\n           }	0
16485827	16485693	how to solve redundant data in listbox	void fill_listbox()\n{\n    string item = txtContent.Text;\n    if(!listBox.Items.Contains(item))\n    {\n        listBox1.Items.Add(item);\n    }\n    textBox1.Text = listBox1.Items.Count.ToString();\n\n\n}	0
21520824	21520725	How to log Client IP Address and Machine Name in ASP.net	Request.UserHostAddress\n\nRequest.UserHostName	0
15063788	15063624	Schedule a task refreshing HttpContext.Cache every day at a certain time	var req = (HttpWebRequest)WebRequest.Create(URL);\nreq.Timeout = 30000;        \nreq.KeepAlive = false;\nreq.Method = "GET";\nvar res = (HttpWebResponse)req.GetResponse();\nif (res.StatusCode == HttpStatusCode.OK){\n    // Your cache should be refreshed\n}	0
926166	925886	C# convert a string for use in a logical condition	public static bool Compare<T>(string op, T x, T y) where T:IComparable\n{\n switch(op)\n {\n  case "==" : return x.CompareTo(y)==0;\n  case "!=" : return x.CompareTo(y)!=0;\n  case ">"  : return x.CompareTo(y)>0;\n  case ">=" : return x.CompareTo(y)>=0;\n  case "<"  : return x.CompareTo(y)<0;\n  case "<=" : return x.CompareTo(y)<=0;\n }\n}	0
18129823	18129677	Is it possible to return a struct from a Linq2Entities query?	var q = db.MyTable\n    //do your processing here (Where, Any, Join, whatever)\n    .ToList() //or AsEnumerable or ToArray\n    .Select(t => new MyStruct { ID = t.ID, Desc = t.Desc });	0
9086261	9086168	random number guessing game	static void Main(string[] args)\n\n{\n\nRandom random = new Random();\n\nint returnValue = random.Next(1, 100);\n\n        int Guess = 0;\n\n        Console.WriteLine("I am thinking of a number between 1-100.  Can you guess what it is?");\n\n        while (Guess != returnValue)\n        {\n            Guess = Convert.ToInt32(Console.Read());\n\n            if (Guess < returnValue)\n            {\n                Console.WriteLine("No, the number I am thinking of is higher than " + Guess + ". Can you guess what it is?");\n            }\n            else if (Guess > returnValue)\n            {\n                Console.WriteLine("No, the number I am thinking of is lower than " + Guess + ". Can you guess what it is?");\n            }\n\n        }\n\n        Console.WriteLine("Well done! The answer was " + returnValue);\n        Console.ReadLine();\n\n}	0
4958201	4957162	Nullable string property/column in nHibernate + Fluent	public string Genero\n{\n    get { return _genero; }\n    set { _genero = string.IsNullOrEmpty(value) ? value : value.Trim(); }\n}	0
21048345	21026285	Load Image from Embedded resource WP8 / C#	string [] names = curAssembly.GetManifestResourceNames();	0
14361106	14361053	DateTime.Parse date format	DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)	0
1180736	1180730	C# determine a Nullable property DateTime type when using reflection	pi.PropertyType == typeof(DateTime?)	0
11348324	11265276	Calculate BPM from Kinect sensor data	var ticks = Math.Abs(firstLow.Ticks - secondLow.Ticks);\nvar elapsedTime = new TimeSpan(ticks);\n\nvar bpm = (int) (60000/elapsedTime.TotalMilliseconds);	0
22238106	22237502	OrderBy with built in condition	var midnight = new DateTime(0).TimeOfDay;\n\ntrips = trips.OrderBy(t=> t.PickupTime.TimeOfDay == midnight ?\n                             DateTime.MaxValue :\n                             t.PickupTime);	0
3786472	3786436	how to 'not' a lambda expression for entity framework	Expression<Func<T, bool>> not = Expression.Lambda<Func<T, bool>> (\n    Expression.Not (matchExpression.Body),\n    matchExpression.Parameters [0]);	0
26964202	26961381	Using two different stored procedures to insert/select with ListView	Insert Into Table1 (Name, Address, ZipCode) Values (@Name, @Address, @Zipcode)	0
29918056	29917824	DataTable Foreach - Getting to Table Data but only returning one result	DataRow[] rows =  tblAnswers.Select("QuestionID = " + PgeNum);\n if (rows.Length != 0)\n    {\n      foreach (DataRow dr in rows)\n      {      \n        string ansTxt = dr["AnswerText"].ToString();\n        rblAnswers.Items.Add(ansTxt);\n       }\n\n     }	0
1840938	1830570	Opacity is not getting applied to the WPF Popup control	popUp.Child = new Button() \n{\n    Width = 300,\n    Height = 50,\n    Background = Brushes.Gray,\n    Opacity = 0.5 // set opacity here\n};	0
1845717	1845699	[C#]Add XSL reference in XMLDocument	var xDoc = new XmlDocument();\nvar pi = xDoc.CreateProcessingInstruction(\n    "xml-stylesheet", \n    "type=\"text/xsl\" href=\"cdcatalog.xsl\"");\nxDoc.AppendChild(pi);	0
13159033	13158969	From String textBox to hex 0x byte[] c#	string input = "AA 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF";\nbyte[] bytes = input.Split().Select(s => Convert.ToByte(s, 16)).ToArray();	0
17527805	17527734	double scrollbars on resizing with maximize and restore browser-window	html, body { overflow: hidden; }	0
8209874	8209765	how use graphvis in C# application?	private static string GenDiagramFile(string pathToDotFile)\n{\n    var diagramFile = pathToDotFile.Replace(".dot", ".png");\n\n    ExecuteCommand("dot", string.Format(@"""{0}"" -o ""{1}"" -Tpng", \n                 pathToDotFile, diagramFile));\n\n    return diagramFile;\n}\n\nprivate static void ExecuteCommand(string command, string @params)\n{\n    Process.Start(new ProcessStartInfo(command, @params) {CreateNoWindow = true, UseShellExecute = false });\n}	0
10626563	10626455	(C#) - store each word between Split in an array	String str = "hello:my:name:is:lavi";\nvar words = str.Split(":");\nConsole.WriteLine(words[1]); //This prints out 'my';\nfor (int i=0;i<words.Length;i++) {  //This will print out each word on a separate line\n    Console.WriteLine(words[i]);\n}	0
12010475	12009414	Deserializing an array with json.net	var itemList = ((JObject)JsonConvert.DeserializeObject(json))["response"]\n                .Skip(1)\n                .Select(x => JsonConvert.DeserializeObject<Item>(x.ToString()))\n                .ToList();\n\n\npublic class Item\n{\n    public int mid { set; get; }\n    public string date { set; get; }\n    public int @out { set; get; }\n    public int  uid { set; get; }\n    public int read_state { set; get; }\n    public string title { set; get; }\n    public string body { set; get; }\n}	0
17865698	17546560	Is there a way to change attributes in runtime using postsharp?	public class DisplayNameAttribute : System.ComponentModel.DisplayNameAttributes\n{\n        private string name;\n\n        public DisplayNameAttribute() { }\n        public DisplayNameAttribute(String name) { this.name = name; }\n\n        public override string DisplayName \n        { \n            get \n            { \n                return DisplayNameValue;\n            } \n        }\n\n        public string DisplayNameValue\n        {\n            get\n            {\n                /* e.g logic for reading from dictionary file */\n                return myDictionary[name];\n            }\n            set\n            {\n                name = value;\n            }\n        }\n    }\n}	0
20423345	20423228	C# trim string returned from function	string input = "Server 00:11:22:33:44:55 124 06-12-13";\nvar match = Regex.Match(input, ".+[0-9a-f]{2}([-:][0-9a-f]{2}){5}");\nif (match.Success)    \n   string result = match.Value; // "Server 00:11:22:33:44:55"	0
3534037	3534021	Winforms C# change string text order	var variableContainingLastNameFirstName = "LastName, FirstName";\n\nvar split = variableContainingLastNameFirstName.Split(new char[] {',' });\nvar firstNamelastName = string.Format("{0}, {1}", split[0], split[1]);	0
25073880	24872966	PrintDocument issues with Windows Server 2008 R2 Standard 64-bit	PrintDocument pd = new PrintDocument();\npc = new StandardPrintController();\npd.PrintController = pc;\n// Yadda Yadda Yadda...\npd.PrinterSettings.PrinterName = "My Printer Name";	0
2648392	2648275	How do you reflect on an attribute applied to a return value?	MethodInfo mi = typeof(Class1).GetMethod("TestMethod");\nobject[] attrs = mi.ReturnTypeCustomAttributes.GetCustomAttributes(true);	0
10445117	10444983	Linq to entities - Lambda - Concatenate strings	string prefixCondition = ...\nint invoiceNumberCondition = ...\n\nInvoices.Where( f =>\n  f.invoice_prefix == prefixCondition\n  &&\n  f.invoice_number == invoiceNumberCondition \n)	0
4617714	4617696	help with getting src from img tag	HtmlDocument doc = new HtmlDocument();\ndoc.Load("file.htm"); //or whatever HTML file you have\nHtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img[@src]");\nif (imgs == null)\n   return;\nforeach (HtmlNode img in imgs)\n{\n   if (img.Attributes["src"] == null)\n      continue;\n   HtmlAttribute src = img.Attributes["src"];\n   //Do something with src.Value\n}	0
30622409	30621491	changing the format of date in listview c#	lstitem.SubItems.Add(DateTime.Parse(Class1.reader[1].ToString()).ToString("MM/dd/yyyy"));	0
10032295	10020165	how to add an image and item to a imageComboxBoxEdit	ImageComboBoxItem someItem = new ImageComboBoxItem();\n        someItem.Description = "Text To Display";\n        someItem.ImageIndex = 0;\n        someItem.Value = 0;\n\n        imageComboBoxEdit1.Properties.Items.Add(someItem);	0
6731991	6731897	Populate dropdownlist - avoid multiple database calls	public List<items> GetDropdownlistItems()\n{\n    string cacheKey = "dropdownlistItems";\n\n    if (HttpContext.Current.Cache[cacheKey] != null)\n    {\n        return (List<items>)HttpContext.Current.Cache[cacheKey];\n    }\n\n    var items = GetItemsFromDatabase();\n\n    HttpContext.Current.Cache.Insert(cacheKey, items, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);\n\n    return items;\n}	0
31159557	31137863	Office 365 API - Embed image	// Update with attachments\nawait m.UpdateAsync();\n// Send the message\nawait m.SendAsync();	0
29579390	29579359	How to display a variable mantissa length	var format = String.Format("0.{0}", new string('0', _Digits));\nlabel1.Text = _DataFloat.ToString(format);	0
9412852	9412785	C# -> Retrieving dataset from SQL Server 2008	//get the connection string from web.config\n string connString = ConfigurationManager .ConnectionStrings["Platform"].ConnectionString;\n DataSet dataset = new DataSet();\n\n using (SqlConnection conn = new SqlConnection(connString))\n {\n     SqlDataAdapter adapter = new SqlDataAdapter();                \n     adapter.SelectCommand = new SqlCommand("select * from [NAMES]", conn);\n     conn.Open(); \n     adapter.Fill(dataset);\n }	0
22083303	22083199	Method for calculating a value relative to min & max values	public static int CalculateRelation(int input, int inputMin, int inputMax, int outputMin, int outputMax)\n{\n    //Making sure bounderies arent broken...\n    if (input > inputMax)\n    {\n        input = inputMax;\n    }\n    if (input < inputMin)\n    {\n        input = inputMin;\n    }\n    //Return value in relation to min og max\n\n    double position = (double)(input - inputMin) / (inputMax - inputMin);\n\n    int relativeValue = (int)(position * (outputMax - outputMin)) + outputMin);\n\n    return relativeValue;\n}	0
12349695	12349404	How can i retrieve Session ID from particular Session Variable	/ In a user control or page\nstring sessionId = this.Session.SessionID; \n\n// In a normal class, running in a asp.net app.\nstring sessionId = System.Web.HttpContext.Current.Session.SessionID;	0
13147097	13147022	How can I order a Dictionary<string,string> by a substring within the value?	var ordered = unordered.OrderBy(x => x.Value.Split(':').Last())\n                       .ToDictionary(x => x.Key, x => x.Value);	0
25803337	25803255	compare 2 values to 1 value in c#	if(new [] { value1, value2, value3, ... }.Any(x => x <= 0))	0
30307510	30307373	Abbreviated definition of a webdriver html element	[FindsBy(How = How.XPath, Using = ".//input[@name='USER']")]\npublic IWebElement userFieldElement { get; set; }	0
30640854	30640757	How to hide a column in a DataGrid?	if (!CurrentUser.IsInRole("Admin"))\n {\n     this.dgCustomers.Columns[2].Visible = false;\n     btnDelete.Visible = false;\n     btnUpload2.Visible = false;\n }	0
17828757	17828631	How can I put my semicolon on same line on rich text box?	richTextBox1.AppendText(crtCommand.ExecuteScalar().ToString().TrimEnd('\r', '\n', ' ') + ";");	0
14280782	14279569	How to play simple slideshow of multiple images in WPF UserControl in Winform	public delegate void MyDelegate();\n\n    public void Refresh()\n    {\n        //this.Refresh();\n          this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, (MyDelegate) delegate() { });        \n    }	0
4428925	4428840	Passing parameter to controller function from jQuery function '$.ajax'	data: "strData = " + searchstring	0
5956530	5938784	Can the Outlook object model MailItem object be loaded from a file?	Namespace.OpenSharedItem	0
24742351	24742180	Load database connection strings from another file	string GetAppSetting(Configuration config, string key)\n{\n    KeyValueConfigurationElement element = config.AppSettings.Settings[key];\n    if (element != null)\n    {\n        string value = element.Value;\n        if (!string.IsNullOrEmpty(value))\n            return value;\n    }\n    return string.Empty;\n}	0
30068113	30067976	Programatically Uninstall a Software using c#	msiexec.exe /x {PRODUCT-GUID}	0
5119077	5115484	How to create a new view every time navigation occurs in PRISM?	public class EmployeeDetailsViewModel : IRegionMemberLifetime\n{\n    public bool KeepAlive\n    {\n        get { return false; }\n    }\n}	0
1286893	1286859	Controlling SQL stored procedure multiple outputs in C#	DataSet allData = new DataSet ();\n ...\n ...\n ...\n  adapter.Fill(allData);	0
19371213	19371095	How do I find Console.WriteLine() values when I have no console? Or How do I print out values at run-time with no Console.	System.Diagnostics.Trace.WriteLine("I'm adding the cost of this answer to your tab.");	0
23966320	23966151	Select all 'a' Node with HtmlAgilityPack	//following LINQ selector used to replace XPath query : //a[@href]\nforeach (HtmlNode node in doc.DocumentNode.Descendants("a").Where(o => "" != o.GetAttributeValue("href", "")))\n{\n    var att = node.GetAttributeValue("href", "")\n    if (att != "")\n    {\n        node.Attributes.Add("onClick", String.Format("gotoLink('{0}');", att.Value));\n        att.Value = "#";\n    }\n}	0
14342555	14342371	Create an XML file from another XML file with tags that are not empty	XDocument xdoc = XDocument.Load(path_to_xml);\nxdoc.Descendants("Employee")\n    .Where(e => e.Descendants().Any(d => String.IsNullOrEmpty(d.Value)))\n    .Remove();\nxdoc.Save(path_to_xml);	0
10489600	10472367	How to add remote proxy to all WebClient requests	HtmlWeb hw = new HtmlWeb();\n        hw.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";\n        hw.PreRequest = new HtmlAgilityPack.HtmlWeb.PreRequestHandler(p.ProxyOnPreRequest); // this is proxy request\n        HtmlAgilityPack.HtmlDocument doc = hw.Load(openUrl);\n\n    public bool ProxyOnPreRequest(HttpWebRequest request)\n    {\n        WebProxy myProxy = new WebProxy("203.189.134.17:80");\n        request.Proxy = myProxy;\n        return true; // ok, go on\n    }	0
827267	827252	C# - Making one Int64 from two Int32s	public long MakeLong(int left, int right) {\n  //implicit conversion of left to a long\n  long res = left;\n\n  //shift the bits creating an empty space on the right\n  // ex: 0x0000CFFF becomes 0xCFFF0000\n  res = (res << 32);\n\n  //combine the bits on the right with the previous value\n  // ex: 0xCFFF0000 | 0x0000ABCD becomes 0xCFFFABCD\n  res = res | (long)(uint)right; //uint first to prevent loss of signed bit\n\n  //return the combined result\n  return res;\n}	0
5311418	5311331	How to initialize static variables in web services	public class WebService1 : System.Web.Services.WebService\n{\n\n    public static int loadedFromDataBase;\n\n    static WebService1()\n    {\n        loadedFromDataBase = ...\n    }\n\n    [WebMethod]\n    public string HelloWorld()\n    {\n        return loadedFromDataBase.ToString();\n    }\n}	0
9941007	9940930	Using a variable from a returned list<> method	List<string> results = new List<string>();\n results = mDB.Select(mQuery);\n string result = results[0].ToString();\n\n MessageBox.Show(result);	0
9810964	9810826	How can I find the euclidean "zone" that a point on a 2D graph falls on?	indexi = (int)(coords.X/map[0,0].length)\nindexj = (int)(coords.Y/map[0,0].height)	0
12369032	12368935	Loading a DataTable with a XML string	//Your xml\nstring TestSTring = @"<Contacts> \n                    <Node>\n                        <ID>123</ID>\n                        <Name>ABC</Name>\n                    </Node>\n                    <Node>\n                        <ID>124</ID>\n                        <Name>DEF</Name>\n                    </Node>\n            </Contacts>";\nStringReader StringStream = new StringReader(TestSTring);\nDataSet ds = new DataSet();\nds.ReadXml(StringStream);\nDataTable dt = ds.Tables[0];	0
29309251	29308502	Generating a rectangle in windows store app	Rectangle r = new Rectangle();\nmyGrid.Children.Add(r);	0
10251107	10251064	make a query string from a list	var parameterizedQuery = new SqlCommand(\n    "INSERT INTO JOBQUESTIONS (JOBAPPLICATIONID, \n        QUESTIONTEXT, TYPEID, HASCORRECTANSWER, CORRECTANSWER, ISREQUIRED) \n    VALUES (@JobId, '@QuestionText', @TypeID , @HasCorrectAnswer , '@CorrectAnswer',\n        @IsRequired)");\n\nparameterizedQuery.Parameters.Add("@JobId", SqlDbType.Int).Value = 123;	0
20944816	20944756	How to convert a protected property in VB.net to c#	protected ArticleSummariesTableAdapter SummariesAdapter {\n    get {\n        if (_ArticleSummariesAdapter == null) {\n            _ArticleSummariesAdapter = new ArticleSummariesTableAdapter();\n        }\n\n        return _ArticleSummariesAdapter;\n    }\n}	0
32153051	32153010	Remove Properties From a Json String using newtonsoft	JObject.Parse(json)	0
11237499	11237416	Storing render from RenderTarget2D to Color Array Error	RenderTarget2D unprocessed = new RenderTarget2D( /*...*/);\ngraphics.GraphicsDevice.SetRenderTarget(unprocessed);\ngraphics.GraphicsDevice.Clear(Color.Black);\n\n//Drawing\nspriteBatch.Begin();\nspriteBatch.Draw(/*...*/);\nspriteBatch.End();\n\n//Getting\ngraphics.GraphicsDevice.SetRenderTarget(null);	0
13779226	13778869	Windows Phone 7 XNA Game, MouseMove, OnUpdate	protected override void Update(GameTime gameTime)\n{\n  // snip...\n\n  MouseState mouseState = Mouse.GetState();\n\n  //Respond to the position of the mouse.\n  //For example, change the position of a sprite \n  //based on mouseState.X or mouseState.Y\n\n  //Respond to the left mouse button being pressed\n  if (mouseState.LeftButton == ButtonState.Pressed)\n  {\n    //The left mouse button is pressed. \n  }\n\n  base.Update(gameTime);\n}	0
1085592	1085584	How do I programmatically retrieve the actual path to the "Program Files" folder?	Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)	0
7861373	7861172	how to show data from Listview in Textbox?	public class Form2\n{\n    public string Name\n    {\n        get { return textbox1.Text; }\n        set { textbox1.Text = value; }\n    }\n    public string phonenumber\n    {\n        get { return textbox2.Text; }\n        set { textbox2.Text = value; }\n\n    }\n\n }\n\npublic class Form1\n{\n\n  private void btnedit_Click(object sender, eventargs e)\n  {\n      for (int i = 0; i < lv.Items.Count; i++)\n      {\n        // is i the index of the row you selected?\n        if (lv.Items[i].Selected == true)\n        {  \n          //I show here the second field text (SubItems[1].Text) from the selected row(Items[i]) \n                Message.Show(lv.Items[i].SubItems[1].Text);\n                break;\n        }            \n      }\n      Form2 frm2 = new Form2();\n      frm2.Name= text1;\n      frm2.phonenumber = text2;\n      frm2.Show();\n      this.Hide();  //// if you want to hide the form1\n    }\n  }\n}	0
16668030	16667979	RegEx in C#, getting the values without criterias	foreach (Match match in matches)\n{\n    Console.Out.WriteLine(match.Groups[1].Value);\n}	0
7337733	7337693	C# Rearrange text in a string	text = text.Replace(": \r\n", ": ");	0
16362971	16263597	IS there any equivalent data structure available in C# for BlockingCollection<KeyValuePair<string,string>>	public int GetHashCode(KeyValuePair<string, string> referenceObj)\n    {\n        //Check whether the object is null \n        if (Object.ReferenceEquals(referenceObj, null)) return 0;\n\n        //Get hash code for the Name field if it is not null. \n        int hashProductName = referenceObj.Equals(default(KeyValuePair<string, string>)) ? 0 : referenceObj.Value.GetHashCode();\n\n        return hashProductName;\n    }\n}	0
20765360	20765348	i need to eliminate xmlns property from every element	Setting on root element(Grid) is sufficient enough.	0
8283835	8283796	Converting double to string giving unexpected output	using System;\n\nnamespace test1{\n    class MainClass {\n        public static void Main (string[] args)     {\n            double d = 0.005;\n            d = d/100;\n            string str = String.Format("{0:0.#####}",d);\n            Console.WriteLine ("The double converted to String:  "+str);\n        }\n    }\n}	0
13635087	13634966	display image in telerik grid column depending on status stored in database	columns.Template(o => \n{\n     if (o.Foo)\n     {\n       %> \n           <img src="img1.gif" />\n       <%\n     }\n     else\n     {\n       %>\n           <img src="img2.gif" />\n       <%\n     }\n}).ClientTemplate("<# if (Foo) { #> <img src='img1.gif'/> <# } else { #> <img src='img2.gif' /> <# } #>");	0
32594750	32593390	How to get cell's column type in smartsheet	// Set the Access Token\nToken token = new Token();\ntoken.AccessToken = YOUR_ACCESS_TOKEN;\n\n// Use the Smartsheet Builder to create a Smartsheet\nSmartsheetClient smartsheet = new SmartsheetBuilder().SetAccessToken(token.AccessToken).Build();\n\n// Get Sheet\nlong sheetId = YOUR_SHEET_ID;\nSheet sheet = smartsheet.SheetResources.GetSheet(sheetId, null, null, null, null, null, null, null);\n\n// Examine columns and write Title and Type for each column.\nforeach (Column column in sheet.Columns)\n{\n    Response.Write(column.Title + ": " + column.Type.ToString() + "<br/><br/>");\n}	0
23112155	23111172	Display arbitrary controls on a WPF Window	public class WizardUserControl : UserControl\n{\n   ...\n   // All your standard wizard code stuff/behavior/business logic/etc...\n   ...\n   ...\n\n   public void InsertCustomizedControl(UserControl customizedControl)\n   {\n      CustomGridArea.Children.Clear();\n      CustomGridArea.Children.Add(customizedControl);\n   }\n}	0
31406275	31406154	How to return object from list in constructor	public MyClass FindOrCreate(int instanceId)\n{\n    MyClass obj = CachedList().Find(T => T.Id == instanzId);\n    //create obj when it does not exist\n\n    return obj;\n}	0
10946922	10946888	How to convert string to XML using C#	string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";\n    xDoc.LoadXml(xml);	0
31825423	31824880	How to split a string into key-value pairs via new line dictionary<string,string>	var lines = text.Split(\n    Environment.NewLine.ToCharArray(),\n    StringSplitOptions.RemoveEmptyEntries);\n\nvar INFO =\n    lines[0].Split(',')\n        .Zip(lines[1].Split(','), (key, value) => new { key, value })\n        .Where(x => !String.IsNullOrEmpty(x.value))\n        .ToDictionary(x => x.key, x => x.value);	0
8143719	8143692	Scrape Table from web page in c#	HtmlDocument doc = ...\nvar myTable = doc.DocumentNode\n                 .Descendants("table")\n                 .Where(t =>t.Attributes["id"].Value == someTableId)\n                 .FirstOrDefault();\n\nif(myTable != null)\n{\n    ///further parsing here\n}	0
677231	673722	Regex help with sample pattern. C#	string input = @"hello world [2] [200] [%8] [%1c] [%d]";\nRegex example = new Regex(@"\[(%\w+)\]");\nMatchCollection matches = example.Matches(input);	0
12212689	12212570	Grid view sorting for particular column	string methodName = "OrderBy";\nif (direction == SortDirection.Descending) {\n    methodName += "Descending";\n}\n\nvar paramExp = Expression.Parameter(typeof(T), String.Empty);\nvar propExp = Expression.PropertyOrField(paramExp, sortExpression);\n\n// p => p.sortExpression\nvar sortLambda = Expression.Lambda(propExp, paramExp);\n\nvar methodCallExp = Expression.Call(\n                            typeof(Queryable),\n                            methodName,\n                            new[] { typeof(T), propExp.Type },\n                            source.Expression,\n                            Expression.Quote(sortLambda)\n                        );\n\nreturn (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);	0
32497119	32496932	Bytes to signed short	short val;\n val = (byte1 << 8) | byte2;	0
19441644	19160035	Apply gravity to individual objects in Farseer Physics	Body.GravityScale = -1.0f;	0
20648008	20647593	Insert dropdownlist value selected	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack)\n    {\n        // populates Departments dropdownlist\n        using (dbOrganizationEntities1 myEntities = new dbOrganizationEntities1())\n        {       \n           var allDepartments = from tbDepartments in myEntities.tbDepartments\n                    select tbDepartments;\n           ddlDepartments.DataSource = allDepartments;\n           ddlDepartments.DataValueField = "DepartmentID";\n           ddlDepartments.DataTextField = "DepartmentName";\n           ddlDepartments.DataBind();\n        }\n    }\n}	0
619351	619260	Get all lucene values that have a certain fieldName	IndexReader.Open(/* path to index */).Terms(new Term("companyName", String.Empty));	0
22963159	22963018	Checking if my object implements a generic interface in C#	typeof(TestA).GetInterfaces()\n    .Any(i => i.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>))	0
29952317	29902500	DataContractSerializer with Multi-tiered data structures	Product prod = context.Products\n    .Include(p => p.Rules.Select(r => r.PriceConditions.Select(p => p.Prices)));	0
2185372	2185238	How do I stop a DateTime validator from padding?	if (DateTime.TryParse(dateCheck, out select) && dateCheck > default(DateTime))\n    e.IsValid = true;\nelse\n    e.IsValid = false;	0
3285991	3285799	how to connect to an open window of internet explorer using c#?	public class Form1 : System.Windows.Forms.Form\n{\n    static private SHDocVw.ShellWindows shellWindows = new\n    SHDocVw.ShellWindowsClass();\n\n    public Form1()\n    {\n       InitializeComponent();    \n       foreach(SHDocVw.InternetExplorer ie in shellWindows)\n       {\n           MessageBox.Show("ie.Location:" + ie.LocationURL);\n           ie.BeforeNavigate2 += new\n           SHDocVw.DWebBrowserEvents2_BeforeNavigate2EventHandler(this.ie_BeforeNavigate2);\n       }\n}\n\n public void ie_BeforeNavigate2(object pDisp , ref object url, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)\n {\n  MessageBox.Show("event received!");\n } \n}	0
12521848	12521818	Get partial string from string	int startPosition = text.LastIndexOf(" is");\nif (startPosition != -1)\n{\n    int endPosition = text.IndexOf(' ', startPosition + 1); // Find next space\n    if (endPosition == -1)\n       endPosition = text.Length - 1; // Select end if this is the last word?\n}	0
25334476	25333925	Unable to find an entry point in C++/CLI	using Callee;\n\nnamespace Caller\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Byte[] calcs = new Byte[10];\n            UInt64[] fil_size = new UInt64[10];\n            String[] files = new String[1];\n            files[0] = "file1";\n\n            Class1.process_these_files(1, files, calcs, fil_size);\n\n        }\n    }\n}	0
6365134	6365110	c# compare datetime for day of month and time	bool areEqual = (d1.Day == d2.Day)\n             && (Math.Abs((d1.TimeOfDay - d2.TimeOfDay).TotalSeconds) < 1.0);	0
3115687	2818250	getting the heading of a selected text in word	> 'By Dhiraj Bajracharya '2010 Sub\n> getHeaddingsRecursive(arange As Range)\n> If MainHeading <> "" Then Exit Sub On\n> Error GoTo err\n>     If Subheading = "" Then\n>         If arange.Paragraphs(1).OutlineLevel =\n> WdOutlineLevel.wdOutlineLevel2 Then\n>             Subheading = arange.Text\n>             Exit Sub\n>         End If\n>     End If\n>     If arange.Paragraphs(1).OutlineLevel =\n> WdOutlineLevel.wdOutlineLevel1 Then\n>          MainHeading = arange.Text\n>     End If    Call getHeaddingsRecursive(arange.Previous(wdParagraph,\n> 1)) err: End Sub	0
45037	45030	How to parse a string into a nullable int	public static int? ToNullableInt32(this string s)\n{\n    int i;\n    if (Int32.TryParse(s, out i)) return i;\n    return null;\n}	0
29546027	29545894	How can I add a blank line to my StringBuilder?	sb.AppendLine("<br/>");	0
15240072	15239723	how to copy datatable column and value to another datatable	private void CopyColumns(DataTable source, DataTable dest, params string[] columns)\n{\n foreach (DataRow sourcerow in source.Rows)\n {\n   DataRow destRow = dest.NewRow();\n    foreach(string colname in columns)\n    {\n      destRow[colname] = sourcerow[colname];\n    }\n   dest.Rows.Add(destRow);\n  }\n}\n\nCopyColumns(source, destiny, "Column1", "column2");	0
24212580	24211987	Pass custom collection object from Controller to View with JQuery	private Workbook GetWorkbooksByProject(int projectId)\n{\n    WorkBookDataManager dataManager = new WorkBookDataManager();\n    var workbookColl = dataManager.GetWorkBooksById(null, projectId, null);   \n    return workbookColl;\n}\n\npublic JsonResult GetWorkbooks(int projectId)\n{\n    var model = GetWorkbooksByProject(projectId);\n    return Json(model, JsonRequestBehavior.AllowGet);\n}\n\npublic ActionResult WorkbooksList(string term, int projectId = -1)\n{\n    if (this.SelectedProject != projectId)\n    {\n        try\n        {\n            this.WorkbookColl = GetWorkbooksByProject(projectId);\n            this.SelectedProject = projectId;\n        }\n        catch (Exception exc)\n        {\n            log.Error("Could not load projects", exc);\n        }\n    }\n\n    return this.View("_Workbook", this.WorkbookColl);\n}	0
10948664	10948622	Converting a resource set into dictionary using linq	var resourceDictionary = resourceSet.Cast<DictionaryEntry>()\n                                    .ToDictionary(r => r.Key.ToString(),\n                                                  r => r.Value.ToString());	0
3793670	3793261	How to make the background image transparent in windows mobile?	private readonly ImageAttributes imgattr;\n.ctor() {\n    imgattr = new ImageAttributes();\n    Color trns = new Bitmap(image).GetPixel(0, 0);\n    imgattr.SetColorKey(trns, trns);\n}\n\nprotected override void OnPaint(PaintEventArgs e) {\n    e.Graphics.DrawImage(image,\n                         new Rectangle(0, 0, Width, Height),\n                         0, 0, image.Width, image.Height,\n                         GraphicsUnit.Pixel,\n                         imgattr);\n}	0
3525914	3525844	How can I create a string of random characters (as for a password...)?	Path.GetRandomFileName	0
7585629	7585542	Transparent border in WPF programmaticaly	border.Background = Brushes.Transparent;	0
4049738	4049680	C#, Linq data from EF troubles	var company = companies.FirstOrDefault();\ntxtDeliveryName.Text = company.Name;\ntxtDeliveryState.Text = company.State;	0
1904124	1892064	How do I detect a custom plugin in Firefox/IE/Chrome?	solved:\n\ndocument.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",\n   "<TH ALIGN=left>i",\n   "<TH ALIGN=left>name",\n   "<TH ALIGN=left>filename",\n   "<TH ALIGN=left>description",\n   "<TH ALIGN=left># of types</TR>")\nfor (i=0; i < navigator.plugins.length; i++) {\n   document.writeln("<TR VALIGN=TOP><TD>",i,\n      "<TD>",navigator.plugins[i].name,\n      "<TD>",navigator.plugins[i].filename,\n      "<TD>",navigator.plugins[i].description,\n      "<TD>",navigator.plugins[i].length,\n      "</TR>")\n}\ndocument.writeln("</TABLE>")	0
14750347	14750290	how to display the Event output reversly in C#?	foreach (var log in eventLog.Entries.Cast<EventLogEntry>().Reverse()) {...}	0
11655627	11655548	Merging two classes into a Dictionary using LINQ	// Project both lists (lazily) to a common anonymous type\nvar anon1 = list1.Select(foo => new { foo.Id, foo.Information });\nvar anon2 = list2.Select(bar => new { bar.Id, bar.Information });\n\nvar map = anon1.Concat(anon2).ToDictionary(x => x.Id, x => x.Information);	0
34135935	34135826	Deep copy of a list with class elements	var list2 = list1.Select(item => new TestClass(item)).ToList();	0
11296082	11295662	SharePoint XML Parse c#	NameTable nameTable = new NameTable();\n    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nameTable);\n    nsmgr.AddNamespace("z", "#RowsetSchema");\n\n    List<XmlNodeList> rows = (from row in data.AsEnumerable()\n                              select row.SelectNodes("//z:row", nsmgr)).ToList();	0
8054611	8054176	Listbox Not binding to a BindingList<T>	ObservableCollection<T>	0
17220516	17220253	HtmlAgilityPack Attributes.Remove on Image Only Removes One, When There Are Two	image.Attributes.Remove	0
13192946	13192637	Get specific folders path from a full way with Path class ASP.NET MVC 3	var directoryInfo = new DirectoryInfo(abovePath);\nvar parentDirectoryName = directoryInfo.Parent.Name;\nvar grandParentDirectoryName = directoryInfo.Parent.Parent.Name;	0
6896486	6889811	eMail from asp.net c# program very slow	Thread backgroundThread = new Thread(new ThreadStart(EMailPrepareAndSend));\nbackgroundThread.Name = "Secondary";\nbackgroundThread.Start();	0
22061562	21986644	Use Addin project in another application	EnvDTE80.DTE2 dte2;\ndte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.11.0");\n\nConnect objConnect = new Connect();\nArray objArray = null;\nobjConnect.OnConnection(dte2, ext_ConnectMode.ext_cm_UISetup, null, ref objArray);	0
22740633	22740054	How call Connection Properties window in my C# application and use it?	PM> Install-Package DataConnectionDialog	0
15803524	15802392	Where to store data securely from a Windows service?	Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData	0
27032025	27031815	how to fetch phone number from xml in c#	var doc = new XmlDocument();\ndoc.LoadXml(xml);\nvar children = doc["root"].ChildNodes;\nforeach (XmlNode c in children)\n{\n    if (c.Name == "dialInNumber")\n    {\n        var type = c["phoneType"].InnerText;\n        var number = c["rawNumber"].InnerText;\n        //Do stuff with type and number\n    }\n}	0
31381056	31380123	Many Class Library and need only one to load in a project -C#	switch (pActivity)\n{\n    case "class1":\n        MyRef _class1 = new MyRef();\n                break;\n    case "class2":\n        NewRef _class2 = new NewRef();\n        break;\n    case "class3":\n        RevisionRef _class3 = new RevisionRef();\n        break;\n    default:\n        break;\n}	0
29036763	29034844	Join 3 tables and databind to a ComboBox	var infoQuery =\n                    (from MovieGen in dbContext.GenreMovies\n                    select new { MovieGen.RowID, Genre=MovieGen.MovieGenre})\n                    .Union\n                        (from MusicGen in dbContext.GenreMusics\n                        select new {MusicGen.RowID, Genre=MusicGen.MusicGenre).Union(from PodcastGen in dbContext.GenrePodcasts select new {PodcastGen.RowID, Genre=PodcastGen.PodcastGenre).ToList();\n\n\n        GridSortSearch.DataTextField = "Genre";\n        GridSortSearch.DataSource = infoQuery;\n        GridSortSearch.DataBind();	0
9763257	9763228	How to add user control to panel	var myControl = new MyProject.Modules.Masters();\npanel1.Controls.Add(myControl);	0
19384262	19384039	Is it possible to have internal-like access modifier at instantiation rather than declaration?	Assembly Lib:\n   Interface A;\n   Interface B; //Utilizes multiple properties with a { get; } pattern.\n\n   //Contains more interface definitions like Interface B\n\nAssembly Impl: //References Lib \n    Class 123; //Utilizes multiple properties with a { get; internal set; } \n               //pattern. Implements B.\n\n    //Contains more class definitions like Class 123\n\n    Class MyImpl; //Implements Interface A and utilizes Class 123.\n\nClientApplication:\n    //Consumes implementations of Interface A and B provided by Impl.	0
33636964	33636908	LINQ Group By Multiple parameters or fields	MYFLIGHTS.GroupBy(g => \n    new { \n        g.DepartureFlights.First().Segments.First().MarketingAirline, \n        g.DepartureFlights.FirstOrDefault().StopCount\n    });	0
12840048	12838219	Use ActiveX in C#	dynamic utilites = Activator.CreateInstance(Type.GetTypeFromProgID("ASDF.Utilites.UTF.Converter"));\nutilites.Convert(outFile, xmlProp.xml);	0
7402655	7402613	How to merge only the missing rows	vwBusPark.Except(dataSet.BusinessPark, DataRowComparer<YourRow>.Default)	0
8425210	8425179	How to copy individual subitem from ListView?	private void button1_Click(object sender, EventArgs e)\n    {\n        if (listView1.SelectedItems.Count != 0)\n        {\n            Clipboard.SetText(listView1.SelectedItems[0].Text);\n        }\n    }	0
9962627	9962587	How to create a textbox that has decimal value	private int _inputNumber = 0;\n    private void Form_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)\n    {\n        if (!Char.IsNumber(e.KeyChar)) return;\n        _inputNumber = 10*_inputNumber + Int32.Parse(e.KeyChar.ToString());\n        ReformatOutput();\n    }\n\n    private void ReformatOutput()\n    {\n         myOutput.Text = String.Format("{0:0.00}", (double)_inputNumber / 100.0);\n    }	0
17121788	17121757	how to access Session to store DataTable in class other than controller in .net MVC	var dt=HttpContext.Current.Session["sessionname"];	0
10909766	10909631	Why are form's tool events Private as a default?	private void uxHelloButton_Click(object sender, RoutedEventArgs e)\n{\n    SomethingToDo(...);\n}\nprotected void SomethingToDo(...)\n{\n    ....\n}	0
24932435	24932380	Can you use LINQ to do a process such as converting part of a list and assigning to another?	Enumerable.Range(0, numberOfInputs)\n          .ToList()\n          .ForEach(j => inputs[j + inputsOffset] = double.Parse(strings[j + stringsOffset]));	0
22472742	22472492	get unique ID of WP8	In WMAppManifest.xml -> Capabilities tab -> switch on ID_CAP_IDENTITY_DEVICE	0
11504666	11502799	How to Set unique IDs to DataRepeater Link Labels	private void accessLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n    {\n        //Access Link Clicked\n        int RequestNumber = r_msgs.CurrentItemIndex;\n        MessageBox.Show(RequestNumber.toString()+1);\n        //Remaining Code\n    }	0
21285775	21285585	Fill dropdownlist when there is no data in database	public string getAge(Guid uID)\n{\n    using (var context = new dbEntities())\n    {\n        var user = context.UserInformation.First(c => c.UserId == uID);\n\n        if(user != null && !String.IsNullOrEmpty(user.?lder))\n          return user.?lder;\n        else\n          return string.empty;\n    }\n}	0
7864888	7861275	Checking selected value in ComboBox - SilverLight4	if ((sender as ComboBox).SelectedValue.ToString() == "Szafa")\n        {\n            MessageBox.Show("TEST");\n        }	0
12659648	12658922	Come back from third window to first window in history	//Check for the first page and remove the remaining back stack in your ThirdPage.xaml\n\n  while(!NavigationService.BackStack.First().Source.OriginalString.Contains("FirstPage"))\n  {\n      NavigationService.RemoveBackEntry();\n  }\n\n  NavigationService.GoBack();	0
14048674	14047719	How to draw a rectangle that looks like CAD elevation drawings	float[] cmpArray = new float[4]{0.0F, 0.2F, 0.7F, 1.0F};\nblackPen.CompoundArray = cmpArray;	0
13375112	13373721	Removing a listview item from a listview item button	public override View GetView(int position, View convertView, ViewGroup parent)\n{\n    OrderLineItem item = GetItemAtPosition(position);\n\n    var view = convertView;\n\n    if (view == null)\n    {\n        view = Context.LayoutInflater.Inflate(Resource.Layout.CustomListItem, parent, false)) as LinearLayout;\n\n        var removeButton = view.FindViewById(Resource.Id.btnRemove) as Button;\n\n        removeButton.Click += (s, e) => {\n            var originalView = (View)s;\n            var originalItem = originalView.Tag as MvxJavaContainer<OrderLineItem>;\n            Items.Remove(originalItem);\n            this.NotifyDataSetChanged();\n        };\n    }\n\n    // ...........\n    var tagButton = view.FindViewById(Resource.Id.btnRemove) as Button;\n    tagButton.Tag = new MvxJavaContainer<OrderLineItem>(item);\n\n    return view;\n}	0
8140062	7426087	CRM 2011 - Retrieving FormattedValues from joined entity	var acs =\n    from a in context.AccountSet\n    join c in context.ContactSet on a.PrimaryContactId.Id equals c.ContactId\n    into gr\n    from c_joined in gr.DefaultIfEmpty()\n    select new\n    {\n        account_addresstypecode = a.Address1_AddressTypeCode,\n        account_addresstypename = a.FormattedValues["address1_addresstypecode"],\n        contact_addresstypecode = c_joined.Address1_AddressTypeCode,\n        contact_addresstypename = a.FormattedValues["c_0.address1_addresstypecode"],\n        a.FormattedValues\n    };\n\nforeach (var ac in acs)\n{\n    foreach (var pair in ac.FormattedValues)\n    {\n        Console.WriteLine("{0} {1}", pair.Key, pair.Value);\n    }\n}	0
15506220	15399777	Embedded Windows Media Player refuses to unload media	mediaPlayerObj.currentPlaylist.clear();	0
9551499	9544527	Configure LINQPad to work with NHibernate Profiler	HibernatingRhinos.Profiler.Appender.Util.GenerateAssembly.Compile	0
6557530	6557347	Increase distance when draw a ellipse	public double[] CalculatePosition(double centerX, \n                                 double centerY, \n                                 double radiusX,\n                                 double radiusY,\n                                 double angle)\n{\n    double[] position = new double[2];\n    position[0] = Math.Cos(angle) * radiusX + centerX;\n    position[1] = Math.Sin(angle) * radiusY + centerY;\n    return position;\n}	0
18366497	18366428	How do you begin a storyboard from a different thread?	App.Current.Dispatcher.Invoke((Action)delegate\n{\n      System.Windows.Media.Animation.Storyboard sb =\n            (System.Windows.Media.Animation.Storyboard)FindResource("sbClose");\n      BeginStoryboard(sb);\n});	0
10022254	10021995	Assign values to arrays on structs using a comfortable code	class Buys\n{\n    private double[] _buys;\n\n    public Buys (int capacity)\n    {\n        _buys = new double[capacity];\n    }\n\n    public double this[int index]\n    {\n        get { return _buys; }\n        set \n        {\n            if (value > 100)\n            {\n                if (Department == "CLOTH")\n                    value = value * .95;\n                if (Department == "FOOD")\n                    value = value * .90;\n                if (Department == "OTHER")\n                    value = value * .97;\n            }\n            _buys = value;\n        }\n    }\n}\n\nstruct Departments\n{\n    public string Department;\n    public Buys Buys;\n}\n\nstatic void Main()\n{\n    var departments = new Departments[3];\n    departments[0].Department = "CLOTH";\n    departments[1].Department = "FOOD";\n    departments[2].Department = "OTHER";\n    departments[0].Buys = new Buys(5);\n    departments[0].Buys[0] = 105;\n}	0
5106907	5106496	client/server win program	Admin.Handle()	0
978975	978959	End of month calculations	bool IsEndOfMonth(DateTime date) {\n        return date.AddDays(1).Day == 1;\n    }\n    DateTime AddMonthSpecial(DateTime date) {\n        if (IsEndOfMonth(date))\n            return date.AddDays(1).AddMonths(1).AddDays(-1);\n        else\n            return date.AddMonths(1);\n    }	0
20271385	20271157	How to play a presentation with Powerpoint object model	presentation.SlideShowSettings.Run();	0
8816721	8816691	trying to call a method in the where of a linq statment	SqlMethods.Like()	0
10859496	10859116	Can I stop a custom Excel task pane from being closed, moved, or resized by a user?	private void ThisAddIn_Startup(object sender, System.EventArgs e)\n{\n   var taskPaneContainer = new TaskPaneContainer();\n   var taskPane = this.CustomTaskPanes.Add(taskPaneContainer, "My Task Pane");\n   taskPane.DockPosition = MsoCTPDockPosition.msoCTPDockPositionRight;\n   taskPane.DockPositionRestrict = MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoChange;\n   taskPane.Visible = true;\n}	0
21088252	21082755	vsto: Caling different excel workbooks from windows form application in same solutions using c#	Microsoft.Office.Interop.Excel.Application xlApp;\n            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;\n            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;\n            object misValue = System.Reflection.Missing.Value;\n\n            xlApp = new Microsoft.Office.Interop.Excel.Application();\n            xlApp.Visible = true;\n            xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\knm\Documents\Book2.xlsx");\n            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n            xlWorkSheet.Activate();\n\n\n            xlWorkBook.Close(true, misValue, misValue);\n            xlApp.Quit();	0
569202	565493	Email Templating with Delimiters	IHttpHandler pageInstance = PageParser.GetCompiledPageInstance(viewPath, physicalPath, HttpContext);\n    pageInstance.ProcessRequest(HttpContext);	0
22820640	22820558	Getting text from specific richtextbox line	string firstLine = RichTextBox.Lines[0];	0
9937233	9937150	Performance impact of virtual methods	Premature optimization is the root of all evil.	0
27343170	27343146	Button Click Operation/ Click again, does opposite?	timer1.Enabled = !timer1.Enabled;	0
5150618	5150610	How to simulate mouse click with the WebBrowser control	button.InvokeMember("click");	0
8777650	8777575	Draw a circle boundary?	void DrawCircle(int centerX, int centerY, int radius)\n{\n    int x,y;\n    x=-radius;\n    while(x < radius)\n    {\n        y=sqrt(radius*radius-x*x);\n        draw(x+centerX,y+centerY);\n        y=-y;\n        draw(x+centerX,y+centerY);\n        x++;\n    }\n}	0
32686821	32685133	C# - Trying to make a Simple User input to character output Console program	if (choice == 'a')\n{\n    Console.WriteLine("apple");\n}\nelse if (choice =='b')\n{\n    Console.WriteLine("bobby");\n}\nelse if (char choice = 'c')\n{\n    Console.WriteLine("charlie");\n}\nelse\n{\n    Console.WriteLine("No Letters entered");\n}	0
8341299	8341270	How to use a Foreach in a base type list in C#	foreach (Bee bee in Tile.Within.OfType<Bee>())\n{\n    bee.selected = !bee.selected;\n}	0
15994406	10065357	Xml file reading by its node c#	foreach (XmlNode node in nodes)\n{\n  PlaceHolder1.Controls.Add(new LiteralControl("<table><tr><td>" + node["Name"].InnerText + "</td><td>"+node["Contact"].InnerText+"</td><td>"+node["Email"].InnerText+"</td><td>"+node["City"].InnerText+"</td><td>"+node["Country"].InnerText+"</td></tr></tabel>")); \n}	0
9728118	9727985	Round values on serialization when using XmlSerializer to serialize to an XML string	[XmlIgnore()]\npublic float SomeValue { get; set; }\n\n[XmlAttribute("SomeValue")]\npublic float SomeValueRounded\n{\n    get { return (float)Math.Round(SomeValue, 2); }\n    set { SomeValue = value; }\n}	0
4437610	4437353	How to pass parameters to callback?	AsynchronousVisibleButtonDelegate asyncDeleg = new AsynchronousVisibleButtonDelegate(AsynchronousVisibleButton);\n        AsyncCallback callback = new AsyncCallback(p =>\n                                                       {\n                                                           var anotherState =\n                                                               p.AsyncState as AsynchronousVisibleButtonDelegate;\n                                                           b.Visible = anotherState.EndInvoke(p);\n                                                       });\n        asyncDeleg.BeginInvoke(b, callback, asyncDeleg);	0
16075375	16075266	Viewing Row number in GridView Control C#	foreach (DataGridViewRow r in  dataGridView1.Rows)\n{\n    dataGridView1.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();\n}	0
17230976	17230862	Nested Object Deserialization of JSON results in an empty object	[{"ObjA":"FOO",\n  "SubObjA":[{\n    "A":0,\n    "B":true,\n    "C":2,\n    "D":0.2\n    }],\n  "ObjB":false,\n  "ObjC":295,\n  }]	0
20048489	19951533	Get value of out parameter before assigning	using System;\nusing System.Reflection.Emit;\n\nnamespace Test774\n{\n    class MainClass\n    {\n        public static void Main(string[] args)\n        {\n            var a = 666;\n            DoWork(out a);\n        }\n\n        public static int DoWork(out int param)\n        {\n            var dynamicMethod = new DynamicMethod("ParameterExtractor", typeof(int), new [] { typeof(int).MakeByRefType() });\n            var generator = dynamicMethod.GetILGenerator();\n            generator.Emit(OpCodes.Ldarg_0);\n            generator.Emit(OpCodes.Ldind_I4);\n            generator.Emit(OpCodes.Ret);\n            var parameterExtractor = (MethodWithTheOutParameter)dynamicMethod.CreateDelegate(typeof(MethodWithTheOutParameter), null);\n            Console.WriteLine(parameterExtractor(out param));\n            param = 1;\n            return 0;\n        }\n\n        public delegate int MethodWithTheOutParameter(out int a);\n    }\n}	0
1901133	1901109	How to use the IR port on the back of my netbook to change the channel	System.IO.Ports.SerialPort	0
23656997	23656279	Access properties of extending class in a base class query from DB with Entity Framework TPH pattern	foreach (r in requests)\n{\n   var rq = r as RequestQuestion;\n   if(rq != null)\n   {\n      string rq = rq.Question\n   }\n\n   var rfw = r as RequestForWork;\n   if(rfw != null)\n   {\n      string wn = rfw.WorkName;\n   }\n}	0
15365540	15365395	Selecting enum values based on key names	Enum.GetValues(typeof(Animals)).OfType<Animals>()\n    .Where(x => x.ToString().StartsWith("Cat"))\n    .Select(x => (int)x).ToArray();	0
2324644	2324626	Extract a ZIP file programmatically by DotNetZip library?	public void ExtractFileToDirectory(string zipFileName, string outputDirectory)\n{\n     ZipFile zip = ZipFile.Read(zipFileName);\n     Directory.CreateDirectory(outputDirectory);\n      foreach (ZipEntry e in zip)\n      {\n        // check if you want to extract e or not\n        if(e.FileName == "TheFileToExtract") \n          e.Extract(outputDirectory, ExtractExistingFileAction.OverwriteSilently);\n      }\n}	0
685010	684953	How to get latest revision number from SharpSVN?	using(SvnClient client = new SvnClient())\n{\n   SvnInfoEventArgs info;\n   Uri repos = new Uri("http://my.server/svn/repos");\n\n   client.GetInfo(repos, out info);\n\n   Console.WriteLine(string.Format("The last revision of {0} is {1}", repos, info.Revision));\n}	0
30339141	30336697	how can I display the information in a textbox from this code?	// This is just to show that you need to create text box which needs to be set to multiline\nvar tb = new TextBox();\ntb.Multiline = true;\n\n// search in: LocalMachine_32\nkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");\nforeach (String keyName in key.GetSubKeyNames())\n{\n    RegistryKey subkey = key.OpenSubKey(keyName);\n    // here just add a line with a program name        \n    string name = subkey.GetValue("DisplayName") as string;      \n    if (!string.IsNullOrEmpty(name))\n    {\n        tb.Text += name;\n        tb.Text += "\n\r";\n    }\n}	0
10428143	10428005	C# XML Deserialize Array elements null	"api.paycento.com/1.0"\n"api.playcento.com/1.0"	0
15882570	15879469	Unable to create xml file	// XmlInclude is necessary because our class doesn't explicitly mention derived object\n[XmlInclude(typeof(ObjectDerived))]\nclass MyRootClass {\n    public ObjectBase { get; set; }\n}\nclass ObjectBase {\n    // some properties here\n}\nclass ObjectDerived : ObjectBase {\n    // more properties here\n}\n...\nvar serializer = new XmlSerializer(typeof(MyRootClass));	0
29262576	29262550	Creating a List<string> off of one of List<Object>'s string properties	var carNames = cars.Select(c => c.Name).ToList();	0
13089114	13089107	Is there a C# equivalent of java's AbstractList?	System.Collections.ObjectModel.Collection<T>	0
4254364	4254339	How to loop through all the files in a directory in c # .net?	string[] files = Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);	0
10521267	10521169	Avoiding input element value posted back to server but allow MVC validation to occur	public class FileViewModel\n{\n    //other stuff contained within the File class\n\n    [Required]\n    public string FileCompanyCode { get; set: }\n}	0
11154076	11109712	Data can't be copied to dataset in datagridview from treeview	// will allow you to drop your data anywhere on gridview where a cell is\nif (hitTest.Type == DataGridViewHitTestType.Cell)\n{\n   e.Effect = DragDropEffects.Move;\n   var data = (object[])e.Data.GetData(typeof(string[]));\n\n   // causes error - if there is already data bound to the control\n   //   see image below\n   //dataGridView1.Rows.Insert(hitTest.RowIndex, data);\n\n   DataTable dt = (DataTable) dataGridView1.DataSource;\n   DataRow dr = dt.NewRow();\n   dr.ItemArray = data;\n   dt.Rows.Add(dr);\n}	0
6024991	6024910	Add List box to List<ListBox> to pass to foreach loop ASP.NET	var listboxen =\n    from control in _pH_Outer_MainCri.Controls\n    where control is ListBox\n    select control as ListBox;	0
26354764	26354444	How to make my ASP.NET Web Api only take XML but also return JSON?	if (Request.Content != null) {\n    if (System.Web.HttpContext.Current.Request.ContentType.StartsWith(MediaType.Xml)) {\n        //Perform your Logic here\n    }\n    /*\n    //you can skip below  MediaType.Json  block \n    if (System.Web.HttpContext.Current.Request.ContentType.StartsWith(MediaType.Json)) {\n    }\n    */\n}	0
20798151	20798042	New ways to update my windows application over internet	makecert -sv ClickOnceTestApp.pvk\n     -n CN=Sample ClickOnceTestApp.cer\n     -b 01/01/2012 -e 12/31/2100 -r	0
12121071	12121051	How to change a DateTime Format	DateTime.ToString()	0
31969945	31966983	How to save Color Scheme in ppt application c# vsto	String programfilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n            String msOfficePath = "Microsoft\\Templates\\Document Themes\\Test.thmx";\n            String fullPath = Path.Combine(programfilesPath, msOfficePath);\n\n            Globals.ThisAddIn.Application.ActivePresentation.SaveCopyAs(fullPath);	0
5951548	5951411	Can I access the Object State of a data entity in LINQ to SQL?	var changes = DbContext.GetChangeSet();\nif(changes.Updates.Contains(EntityToCheck))\n  //Changed state\nelse if(changes.Inserts.Contains(EntityToCheck))\n  //New state\nelse if(changes.Deletes.Contains(EntityToCheck))\n  //Delete state	0
24676939	24637703	Open a .txt file on Android	string realPath = Application.persistentDataPath + "/PATH/" + fileName;\n\n    if (!System.IO.File.Exists(realPath))\n    {\n        if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PATH/"))\n        {\n            System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PATH/");\n        }\n\n        WWW reader = new WWW(Application.streamingAssetsPath + "/PATH/" + realPath);\n        while ( ! reader.isDone) {}\n\n        System.IO.File.WriteAllBytes(realPath, reader.bytes);\n    }\n\n    Application.OpenURL(realPath);	0
7445212	7438404	How to get overlap range of two range	Loop\n   Get the range that starts next (R1)\n   if the next range of the other person (R2) starts before R1 ends\n      Add the range from begin of R2 and min( end of R1 end of R2 ) to results\n   Increase the counter for the person which gave you R1	0
29371816	29371221	how to get raw bytes from querystring	var wind1250 = Encoding.GetEncoding(1250);\n\n\nvar querystring = HttpUtility.UrlDecode(Request.Url.Query, wind1250);//;    \nvar qs = HttpUtility.ParseQueryString(querystring);\nResponse.Write(qs["Where"]);	0
3505391	3505347	Converting a byte swapping/shifting code snippet from C++ to .NET	enum eIM { eD = 0, eV, eVO, eVC }\nint value = System.Net.IPAddress.HostToNetworkOrder((int)eIM.eV);	0
1950762	1944576	Convert a pdf file to text in C#	gswin32c.exe -q -dNODISPLAY -dSAFER -dDELAYBIND -dWRITESYSTEMDICT -dSIMPLE -c save -f ps2ascii.ps "test.pdf" -c quit >"test.txt"	0
27614927	27614858	how to compare two list and subtract single column value in c#	foreach(var item in LoadedList.Where(r=>r.LoadingType == "U"))\n{\n    item.Quantity *= -1;\n}\n\nvar summary = from d in LoadedList\n              group d by new { Brand = d.BrandCode, Packing = d.PackingCode, Grade = d.GradeCode } into g \n              select new { Brand = g.Key.Brand, Packing = g.Key.Packing, Grade = g.Key.Grade, Quantity = g.Sum(e => e.LoadingQty) }	0
5276664	4977890	show line breaks in output	MvcHtmlString.Create(Model.Post.Description.Replace(Environment.NewLine, "<br />"))	0
26373532	26111820	How to hide the vertical gridlines of the group header in betterlistview control?	protected override void OnDrawGroup(BetterListViewDrawGroupEventArgs eventArgs)\n{\n    eventArgs.Graphics.FillRectangle(SystemBrushes.Window, eventArgs.GroupBounds.BoundsInner);\n    base.OnDrawGroup(eventArgs);\n}	0
2943371	2943248	Non-resizeable, bordered WPF Windows with WindowStyle=None	private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    var interopHelper = new WindowInteropHelper(this);\n    var hwndSource = HwndSource.FromHwnd(interopHelper.Handle);\n    hwndSource.AddHook(WndProcHook);\n}\n\nprivate IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n{\n    if (msg == 0x84 /* WM_NCHITTEST */)\n    {\n         handled = true;\n         return (IntPtr)1;\n    }\n}	0
1454114	1454094	Refer to 'Program Files' on a 64-bit machine	System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles);	0
26024567	26024448	Working with a large list of Objects, need better (sorted) performance	var lookup = masterList.ToLookup(tho => tho.GUID);\n// Now you have a hash-table based lookup containing the lists of TheirObject grouped by GUID\nforeach(string GUID in GUIDs)\n{\n    filteredList = lookup[GUID].ToList();\n    // Do your stuff with filteredList\n}	0
8061504	8061471	The error in getting the exact value from the XML node when the '\' value is in string and that string in passed used as xml instead of file	string s = "\\";	0
2619675	2619664	C#: Convert Byte array into a float	float myFloat = System.BitConverter.ToSingle(mybyteArray, startIndex);	0
12037350	12036592	Debugging HTML in WebBrowser Control	function myMethod(arg1, arg2)\n{\n    // when myMethod executes you will get prompt that with which \n     // debugger you want to execute\n    // then from prompt select "New Instance of Visual Studio 2xxx"\n    debugger; \n\n    //\n    ...\n    ...\n}	0
2568386	2568273	How to use Contains() in my join	from det in Source\nfrom map in Map\nwhere SqlMethods.Like(map.DetailText, "%" + map.SearchText + "%"))\nselect new {det, map}	0
11167216	11167171	show pixel value of .TIF image on the basis of X Y coordinates in c#	string imgPath;\nimgPath = @"C:\Documents and Settings\shree\Desktop\2012.06.09.15.35.42.2320.tif";\n\nBitmap img;\nimg = new Bitmap(imgPath, true);\n\nColor pixelColor = img.GetPixel(50, 50); // 50, 50 or any "VALID" pixel in your bitmap	0
3714505	3714457	Binary numbers only TextBox	private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {\n        // Allow backspace, 0 and 1\n        e.Handled = !("\b01".Contains(e.KeyChar));\n    }	0
1642994	1642705	SQL Server connection string Asynchronous Processing=true	Asynchronous Processing=True	0
4801343	4645427	Facebook Application Invite, get list of invited friends	if( Request["ids"] != null )\n     ((Site)Master).FbInviteSent(Request.QueryString["ids[]"].ToString().Split(','));	0
1796052	1796011	how to create dynamic controls and events?	btn.Clicked += this.btnClickedEventHandler;	0
31464965	31464595	How to get filenames in a folder 1 by 1 and use them in .txt file	DirectoryInfo dinfo1 = new DirectoryInfo(path);\nFileInfo[] Files1 = dinfo1.GetFiles("*.*");\nstring[] StringsToReplace = {"oldtext1", "oldtext2", "oldtext2"};\nstring text = File.ReadAllText("path/text.txt");\n\n\nfor(int i=0; i < StringsToReplace.Length; i++)\n{\n    if(i >= Files1.Length)\n    {\n        break;\n    }\n    text = text.Replace(StringsToReplace[i], "path" + Files1[i].Name);   \n}\n\nFile.WriteAllText("path/text.txt", text);	0
9842489	9842435	A neat way to divide in two and reorder a list?	var list = new List<String> { "aaa", "aab", "aac", "baa", "bab", "bac" };\n var index = list.IndexOf("aac");\n var r = list.Skip(index).Concat(list.Take(index)).ToList();	0
19773210	19772916	Groupby, sum with multiple joins in Linq lamda	EntryCategories\n       .Join(TimeReportEntries, ec => ec.Id, tr => tr.WorkItem.Id, (ec, tr) => new { ec, tr })\n       .Join(Timesheets, ecs => ecs.tr.Timesheet.Id, t => t.Id, (ecs, t) => new { ecs, t })\n       .Join(Users, ts => ts.t.User.Id, u => u.Id, (ts, u) => new\n        {\n            WorkItemId = ts.ecs.tr.WorkItem.Id\n            Employee = ts.t.User.FirstName + " " + ts.t.User.LastName,\n            Hours = ts.ecs.tr.Hours\n        })\n       .GroupBy(x => x.WorkItemId)\n       .Select(x => new \n        { \n            WorkItemId = x.Key, \n            Hours = x.Sum(y => y.Hours)\n        });	0
25064667	25064617	Removing string using regular expressions	"<div class=\"([^\"]*)\">"	0
7929241	7927648	Install SQL Server Express with C# application	Install the custom application first. Then install SQL Server Express.	0
2529835	2529743	How to keep an item selected? - ListView	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MyListView : ListView {\n  protected override void WndProc(ref Message m) {\n    if (m.Msg == 0x201 || m.Msg == 0x203) {  // Trap WM_LBUTTONDOWN + double click\n      var pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);\n      var loc = this.HitTest(pos);\n      switch (loc.Location) {\n        case ListViewHitTestLocations.None:\n        case ListViewHitTestLocations.AboveClientArea:\n        case ListViewHitTestLocations.BelowClientArea:\n        case ListViewHitTestLocations.LeftOfClientArea:\n        case ListViewHitTestLocations.RightOfClientArea:\n          return;  // Don't let the native control see it\n      }\n    }\n    base.WndProc(ref m);\n  }\n}	0
18111268	18110021	Entity Framework populate entity at starting	if (!context.PostalCodes.Any())\n{\n    IEnumerable<PostalCode> postalCodes = ReadPostalCodes();\n    foreach(var postalCode in postalCodes)\n    {\n        context.PostalCodes.Add(postalCode);\n    }\n    context.SaveChanges();\n}	0
32576254	32576237	JSON string not Deserialize properly with boolean and string	class JsonResponse\n{\n  public bool Success { get; set; }\n  public string Response { get; set; }\n}	0
15380837	15380463	Allow user defined Strings in c#	var userstring = "The Name of the Item with the Id {ID} is {Name}. It's Description is {Description}. It has the Value {Value} and the Status {Status}.";\nvar result = userstring.Replace("{ID}", Id).Replace("{Name}", Name).Replace("{Description}", Description).Replace("{Value}", Value).Replace("{Status}", Status);	0
12553007	12552980	Getting a value of 0 when dividing 2 longs in c#	label10.Text =  (((int)((double)dInfo.AvailableFreeSpace/dInfo.TotalSize)*100)).ToString();	0
15848572	15847822	Opening Web Browser click in default browser	webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(WebBrowser_Navigating);\n\nvoid WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) {\n        e.Cancel = true;\n        Process.Start(e.Url);\n    }	0
33089881	33033889	Reference .pfx file from within my WebSite application	var newCertPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~\" + certName);	0
10110890	10110190	How to pass a string containing extended ascii chracters to an unmanaged C++ dll	[DllImport("c:\\USBPD.DLL")]\nprivate static extern int WriteText([In] byte[] text, int length);\n\npublic static int WriteText(string text)\n{\n    Encoding enc = Encoding.GetEncoding(437); // 437 is the original IBM PC code page\n    byte[] bytes = enc.GetBytes(text);\n    return WriteText(bytes, bytes.Length);\n}	0
2505802	2505508	Updating DataGrid From a BackGroundWorker	//In Form.Designer.cs\n\n Label myLabel = new Label();\n\n\n //In code behind under Background worker method\n LabelVlaueSetter SetLabelTextDel = SetLabelText; \n if (myLabel .InvokeRequired)\n {\n\n   myLabel.Invoke(SetLabelTextDel, "Some Value");\n }\n\n private delegate void LabelVlaueSetter(string value);\n\n //Set method invoked by background thread\n private void SetLabelText(string value)\n {\n   myLabel.Text = value;\n }	0
27748179	27748077	Regex that returns a list	var listOfNumbers = Regex.Matches(y, @"\d+")\n                           .OfType<Match>()\n                           .Select(m => m.Value)\n                           .ToList();	0
25549180	25549032	Printing only the active window in C#	// Takes a snapshot of the window hwnd, stored in the memory device context hdcMem\nHDC hdc = GetWindowDC(hwnd);\nif (hdc)\n{\n    HDC hdcMem = CreateCompatibleDC(hdc);\n    if (hdcMem)\n    {\n        RECT rc;\n        GetWindowRect(hwnd, &rc);\n\n        HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc));\n        if (hbitmap)\n        {\n            SelectObject(hdcMem, hbitmap);\n\n            PrintWindow(hwnd, hdcMem, 0);\n\n            DeleteObject(hbitmap);\n        }\n        DeleteObject(hdcMem);\n    }\n    ReleaseDC(hwnd, hdc);\n}	0
13194938	13194898	LINQ operator to split List of doubles to multiple list of double based on generic delimiter	List<List<double>> result = values.GroupDelimited(x => x == double.NaN)\n                                  .Select(g => g.ToList())\n                                  .ToList();	0
1742334	1742304	C# Update and Delete row table using tableAdapter, mdb access, dataGridView	this.estacionamientoTableAdapter.Adapter.UpdateCommand = new System.Data.SqlClient.SqlCommand("update statement",this.connection);	0
25282465	25282076	How to use App.config in WPF application for log4net configuration	log4net.Config.XmlConfigurator.Configure()	0
3389126	3386749	Loading a file to a Bitmap but leaving the original file intact	public static Image LoadImageNoLock(string path) {\n        var ms = new MemoryStream(File.ReadAllBytes(path)); // Don't use using!!\n        return Image.FromStream(ms);\n    }	0
30042103	30041969	Count the number of occurrences of a string in a row	public void BindStates(DataTable states)\n{\n    int numberUsa = 0;\n    foreach (DataRow row in states.Rows)\n    {\n        if (row[1].ToString() == "USA")\n        {\n            numberUsa++;\n        }\n    }\n\n    Console.WriteLine(numberUsa.ToString());\n}	0
7841423	7841348	How to construct dynamic query in LINQ?	where textBox1.Text.Split(' ').All(t => d.Element("Description").Value.Contains(t))	0
12828888	12828854	How to instantiate a new instance of a property in C#	public class SearchModel\n{\n    public SearchModel()\n    {\n        Tags = new List<TagDetails>();\n    }\n    public List<TagDetails> Tags { get; set; }\n}	0
14304800	14304686	Getting a Class to recognise and loop through its own Properties	foreach (PropertyInfo propertyInfo in type.GetProperties())\n{\n  var propertyValue = propertyInfo.GetValue(this);\n  propertyInfo.SetValue(this, new_value);\n}	0
3471954	3471635	get first name last name of logedin windows user?	Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\nWindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;\n// or, if you're in Asp.Net with windows authentication you can use:\n// WindowsPrincipal principal = (WindowsPrincipal)User;\nusing (PrincipalContext pc = new PrincipalContext(ContextType.Domain))\n{\n    UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);\n    return up.DisplayName;\n    // or return up.GivenName + " " + up.Surname;\n}	0
8255019	8254976	LINQ2SQL: how to merge two columns from the same table into a single list	var all = homeLocation.Union(workLocation).ToList();	0
2514136	2514131	Exception from within a finally block	try\n{\n    DoSomethingWithDevice();\n}\nfinally\n{\n    try\n    {\n        LockDevice();\n    }\n    catch (...)\n    {\n        ...\n    }\n}	0
11340070	11339868	Programatically remove wifi (Wireless Network Connection) icon from system tray (notification area) in Windows 7	regedit regcmd.reg	0
17988492	17988024	BeginGetResponse in Background	string contactsRetriveDate = "";\n    DateTime a;\n    string now = DateTime.Now.ToString("MM/dd/yyyy");\n    string then = "";\n    do\n    {\n        contactsRetriveDate = IS.ReadContactsRetriveDate();\n        if (contactsRetriveDate != "")\n        {\n            a = DateTime.ParseExact(contactsRetriveDate, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);\n            a.ToString("MM/dd/yyyy");\n        }\n    }\n    while(then!=now);\n    MessageBox.Show("Estj");	0
19523005	19522868	Where does the new line come from. Read from a file and put in a string. Then output to the console	aText.WriteLine(lineToWrite);	0
6994037	6993950	Searching for files with a .dcm extension in a particualr drive c#	string startFolder = @"c:\";\n    DirectoryInfo directoryInfo = new DirectoryInfo(startFolder);\n    IEnumerable<System.IO.FileInfo> fileList = directoryInfo.GetFiles("*.*", System.IO.SearchOption.AllDirectories);	0
33981792	33976928	JSON.NET some fields are null after deserialization	public string id\n{\n    get { return jobId; }\n    set { jobId = value; }\n}\npublic string ConceptTextItem\n{\n    get { return item; }\n    set { item = value; }\n}	0
895516	895470	How do I scroll a RichTextBox to the bottom?	richTextBox.SelectionStart = richTextBox.Text.Length;\nrichTextBox.ScrollToCaret();	0
20786309	20785916	DataTable need to sum a column with filter on it	var query = (from t in table.AsEnumerable()\n             where t["Status"].ToString().Trim() != "Closed" \n                  && t["Product"].ToString().Trim() == "B"\n             select Convert.ToInt32(t["TotalVolume"]) \n                 - Convert.ToInt32(t["ShipedVolume"])).Sum();	0
28003332	28001970	using SpeechRecognizerUI in my WP 8 app causing it crash unexpectedly?	WMAppManifest.xml	0
15807283	15806393	PInvoke: Issue with returned array of doubles?	extern "C" __declspec(dllexport)\nint __stdcall Poll(CyberHand::Hand* hand, double* buffer, size_t bufferSize)\n\n[DllImport("foo.dll")]\nprivate static extern int Poll(IntPtr hand, double[] buffer, int bufferSize)	0
13437563	13437534	Inline if statament to determine i++ or i-- increment in for loop	i += length < 0 ? -1 : 1	0
2185246	2184260	Unit testing something with ObserveOnDispatcher	var frame = new DispatcherFrame();\nDispatcher.CurrentDispatcher.BeginInvoke(\n  DispatcherPriority.Background, \n  new Action(() => frame.Continue = false));\nDispatcher.PushFrame(frame);	0
23691605	23691592	Add new column at specified position programmatically in C# Datagridview	dataGridView1.Columns.Insert(5, columnSave);	0
32769665	32768917	MySql temp table survives after connection closed (from .NET)	Pooling=False;	0
3616513	3616400	How to decode one Int64 back to two Int32?	[StructLayout(LayoutKind.Explicit)]\npublic struct UnionInt64Int32 {\n    public UnionInt64Int32(Int64 value) {\n        Value32H = 0; Value32L = 0;\n        Value64 = value;\n    }\n    public UnionInt64Int32(Int32 value1, Int32 value2) {\n        Value64 = 0;\n        Value32H = value1; Value32L = value2;\n    }\n    [FieldOffset(0)] public Int64 Value64;\n    [FieldOffset(0)] public Int32 Value32H;\n    [FieldOffset(4)] public Int32 Value32L;\n}	0
3013093	3013041	C# remove redundant paths from a list	List<string> sampleList = new List<string>\n{\n   "C:\\Folder1",\n   "D:\\Folder2",\n   "C:\\Folder1\\Folder3",\n   "C:\\Folder111\\Folder4",\n   "C:\\Folder1"\n};\n\nstring sep = Path.DirectorySeparatorChar.ToString();\nList<string> shortList = sampleList.Where (l => \n    sampleList.Where(s => \n        l.StartsWith(s + (s.EndsWith(sep) ? String.Empty : sep)) && s != l).Count() == 0\n).Distinct().ToList();	0
24378609	24374360	WP8 change background image when button clicked	public static class FrameworkElementExtensions\n    {\n        public static object TryFindResource(this FrameworkElement element, object resourceKey)\n        {\n            var currentElement = element;\n\n            while (currentElement != null)\n            {\n                var resource = currentElement.Resources[resourceKey];\n                if (resource != null)\n                {\n                    return resource;\n                }\n\n                currentElement = currentElement.Parent as FrameworkElement;\n            }\n\n            return Application.Current.Resources[resourceKey];\n        }\n    }\n\n        private void PageTitle_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n        {\n            ApplicationTitle.Style = (Style)ApplicationTitle.TryFindResource("PhoneTextTitle1Style");\n        }	0
8857245	8844818	Get Value From Dynamic Text Box ASP.NET	protected void UpdateQuestionName_Click(object sender, EventArgs e)\n    {\n        int QuestionnaireId = (int)Session["qID"];\n        GetData = new OsqarSQL();\n\n        //get the button that caused the event\n        Button btn = (sender as Button);\n        if (btn != null)\n        {\n                //here's you question text box if you need it\n                TextBox questionTextBox = (btn.Parent.FindControl("QuestionName") as TextBox);\n\n                // Update question name\n                GetData.InsertQuestions(questionTextBox.Text, QuestionnaireId);\n\n\n\n                //and in case you want more of the associated controls\n                //here's your data list with text boxes\n                DataList answersDataList = (btn.Parent.FindControl("nestedDataList") as DataList);\n                //and if answersDataList != null, you can use answersDataList.Controls to access the child controls, where answer text boxes are\n        }\n\n    } // End NewQNRButton_Click	0
1803591	1803535	C# , detect selected text on windows?	[ DllImport("user32.dll") ]\n\nstatic extern int GetForegroundWindow();\n\n[ DllImport("user32.dll") ]\nstatic extern int GetWindowText(int hWnd, StringBuilder text, int count); \n\nprivate void GetActiveWindow()\n{\n\nconst int nChars = 256;\nint handle = 0;\nStringBuilder Buff = new StringBuilder(nChars);\n\n   handle = GetForegroundWindow();\n\n   if ( GetWindowText(handle, Buff, nChars) > 0 )\n   {\n   this.captionWindowLabel.Text = Buff.ToString();\n   this.IDWindowLabel.Text = handle.ToString();\n   }\n\n}	0
10035639	10035616	Find a string in an ArrayList	bool contains = arrayList.Contains(yourString);	0
10415362	10415244	how can I switch two menuItems in wpf with Icommand	Visibility="{Binding ElementName=otherControl,Path=Visibility,Converter={StaticResource HiddenToVisibleConverter}}"	0
17254161	17198233	Insert a hyperlink with named anchor (#) into ms word	Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;\nstring test_file_Path = created_folder + "\\test2.docx";\nobject linkAddr = test_file_Path;\nstring test_bookmark = "testsbookmark";\nobject linkSubAddr = test_bookmark;\n// you may need more parameters here\nMicrosoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr, ref linkSubAddr);\nWordApp.ActiveWindow.Selection.InsertAfter("\n");	0
11294840	11294718	How to display text in DataGridViewComboBoxColumn when the databound value is null	//attach in code or via designer:\ndataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);\n\n\n    //example implementation:\n    void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n    {  \n        if (e.ColumnIndex == Column1.Index && e.Value==null)//where Column1 is your combobox column\n        {\n            e.Value = "Empty";\n            e.FormattingApplied = true;\n        }\n    }	0
17271604	17271219	Saving page state mvc4	public class ConnectionViewModel\n{\n    public string AuthenticationType { get; set; }\n    public string ConnectionString { get; set; }\n    ...\n}\n\npublic ActionResult Login()\n{\n    // pass in defaults \n    return View(new ConnectionViewModel\n    {\n        AuthenticationType = "Windows",\n        ConnectionString = "..."\n    });\n}\n\n[HttpPost]\npublic ActionResult Login(ConnectionViewModel viewModel)\n{\n    // pass view model back into view to retain values\n    return View(viewModel);\n}	0
6111760	6111712	how to remove carriage returns, newlines, spaces from a string	string input = @"<TestItem1Request>\n  <Username>admin</Username>\n  <Password>123abc..@!</Password>\n  <Item1>this is an item</Item1>\n</TestItem1Request>";\n\nstring result = XElement.Parse(input).ToString(SaveOptions.DisableFormatting);\nConsole.WriteLine(result);	0
28143754	28143500	Check if string contains a list of strings in any order	string[] words = query.ToLower().Split(' ');\nvar products = from p in All select p;\nforeach (var word in words)\n{\n    products = products.Where(x => x.ProductName.ToLower().Contains(word));\n}\nreturn products.Take(limit).ToList();	0
18799802	18799629	inserting to SqlLite takes too long	conn_sql.Open();\nusing(var tran = conn_sql.BeginTransaction()) // <--- create a transaction\n{\n     cmd_sql = conn_sql.CreateCommand();\n     cmd_sql.Transaction = tran; ? // <--- assign the transaction to the command\n? ? ? ? ? ? ??\n     for (int i = 0; i < iTotalRows; i++)\n     {\n          // ...\n          cmd_sql.CommandText = SQL;\n          cmd_sql.CommandType = CommandType.Text;\n          cmd_sql.ExecuteNonQuery();\n          //cmd_sql.Dispose();\n\n     }\n     tran.Commit(); // <--- commit the transaction\n} // <--- transaction will rollback if not committed already	0
4151124	4151071	C# Loop through Files and Repeat Until Every Combination of Comparisons is Complete	string CompareMyFolders()\n{\n    string FinalValue = "";\n    DirectoryInfo[] folders = new DirectoryInfo[5];\n    folders[0] = new DirectoryInfo("C:\\FolderA\\");\n    folders[1] = ...;\n    folders[2] = ...;\n    folders[3] = ...;\n    folders[4] = ...;\n\n    for(int i = 0; i < folders.Length - 1; i++)\n        for(int j = i + 1; j < folders.Length; j++)\n            FinalValue += CompareFolders(folders[i], folders[j]);\n\n    return FinalValue;\n}\n\nstring CompareFolders(DirectoryInfo folder1, DirectoryInfo folder2)\n{\n    string value = "";\n    // compare the files in both directory\n    // append the returning data to the value\n\n    return value;\n}	0
9369687	9369423	Reading parameters like signup[product][handle] in ASP.NET	var nvc = new NameValueCollection();\nnvc.Add(HttpUtility.ParseQueryString(Request.Params));	0
9286761	9286645	Constant value properties	Clazz.get_Speed:\nIL_0000:  ldc.i4.5  //push integer value 5 on evaluation stack   \nIL_0001:  ret	0
8910811	8910733	string to parse out a URL	System.Uri	0
5370668	5370641	How to set object property through Reflection	newValue = Convert.ChangeType(givenValue, prop.PropertyType);\nprop.SetValue(target, newValue, null);	0
26886501	26886385	How to assign multiple values to ASP.NET pages from DB	protected string ManagerData(String sValue)\n{\n    string UsrName = User.Identity.Name;\n    string mName;\n    string mNum;\n    using (SqlConnection connection = new SqlConnection(Common.ConnectionString))\n    {\n        using (SqlCommand cmd = new SqlCommand("select ManagerName,ManagerNumber from Managers where UserName=@UserName"))\n        {\n            SqlParameter para = new SqlParameter("UserName", UsrName);\n            cmd.Parameters.Add(para);\n            cmd.Connection = connection;\n            connection.Open();\n            using (SqlDataReader reader = cmd.ExecuteReader())\n            {\n                reader.Read();\n                mName = reader.GetString(0);\n                mNum = reader.GetString(1);\n            }\n        }\n    }\n\n    if(sValue = "name")\n     return mName;\n    else\n     return mNum    \n}\n\n<h5>Your Manager is:<%:ManagerData("name") %> </h5>\n\n<h5>Your Managers Number is:<%:ManagerData("number") %> </h5>	0
17877945	17877705	Tiny image size when adding an image to a button from an imagelist in c#	imageList.ImageSize = new Size(call.Width, call.Height);	0
10579188	10578247	Balanced Pool of Away and Home Games Algorithm	X = (Team_Number_1 + Team_Number_2) % 2	0
22807353	22806923	How to set timer inside while	static class Program\n{\n    private static readonly Random Rnd = new Random((int)DateTime.UtcNow.Ticks);\n\n    static void Main(string[] args)\n    {            \n        var stopwatch = new Stopwatch();\n\n        stopwatch.Start();\n        bool isFound;\n        while (true)\n        {\n            isFound = Find();\n\n            if (isFound || stopwatch.Elapsed.TotalSeconds >= 10)\n                break;\n        }\n\n        Console.WriteLine("Is found: {0}, Spent time: {1} sec(s)", isFound, stopwatch.Elapsed.TotalSeconds);\n        Console.ReadLine();\n    }\n\n    private static bool Find()\n    {\n        return Rnd.Next(1000) >= 999;\n    }\n}	0
10709252	10656847	Console App launched from windows service has no file system access	Process p = new Process(); \np.StartInfo.FileName = agent.AgentLocation; /// Physical path to executable \np.StartInfo.WorkingDirectory = agent.AgentLocation.Substring(0, agent.AgentLocation.LastIndexOf("\\") + 1);\np.StartInfo.CreateNoWindow = true; \np.StartInfo.ErrorDialog = false; \np.StartInfo.RedirectStandardError = true; \np.StartInfo.RedirectStandardInput = true; \np.StartInfo.RedirectStandardOutput = true; \np.StartInfo.UseShellExecute = false; \np.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; \np.Start();	0
34448781	34434287	How to get country of a user from active directory form Membership.GetUser(uname)	PrincipalContext ctx = new PrincipalContext(\n                                        ContextType.Domain,\n                                        ConfigurationManager.AppSettings["ADDomainName"],\n                                        ConfigurationManager.AppSettings["ADContainer"],\n                                        ConfigurationManager.AppSettings["ADUserName"],\n                                        ConfigurationManager.AppSettings["ADPassword"]);\n                UserPrincipal users = UserPrincipal.FindByIdentity(ctx, user.UserName);\n                DirectoryEntry entry = users.GetUnderlyingObject() as DirectoryEntry;\n                PropertyCollection props = entry.Properties;\n\n                if (entry.Properties["countryCode"].Value != null)\n                {\n                    user.CountryCode = entry.Properties["countryCode"].Value.ToString();\n                }	0
9363035	8234618	How to do named multiqueries using C# Facebook SDK	var fb = new FacebookClient("access_token");\ndynamic result = fb.Get("fql",\n    new\n        {\n            q = new\n            {\n                id = "SELECT uid from user where uid=me()",\n                name = "SELECT name FROM user WHERE uid IN (SELECT uid FROM #id)",\n            }\n        });	0
22968697	22936222	Dynamic Expression in StimulSoft Reports	{(Consigner.HasLoan == true) ? "Loan:"+Consigner.LoanAmount:""}	0
10555951	10148967	Can a WCF client become faulted without a triggering event?	try\n{\n    ...\n    client.Close();\n}\ncatch (CommunicationException e)\n{\n    ...\n    client.Abort();\n}\ncatch (TimeoutException e)\n{\n    ...\n    client.Abort();\n}\ncatch (Exception e)\n{\n    ...\n    client.Abort();\n    throw;\n}	0
9145969	9145403	WP7: Dynamically add items to a Grid	foo.VerticalAlignment = VerticalAlignment.Top;	0
13005865	13005684	How to stop foreach loop in a given state	foreach (var item in Items)\n{           \n  try\n  {\n    //Exception\n  }\n  catch (Exception)\n  {\n    continue;//Will move to next item of "Items" of FOREACH LOOP\n  }\n\n  int a = 1 + 1;//If exception gets this line will not execute\n }	0
25201203	25197893	How to remove a Namespaceprefix of an attribute?	foreach (var attr in doc.Descendants()\n                        .SelectMany(d => d.Attributes())\n                        .Where(a => a.Name.Namespace == ns))\n{\n   attr.Parent.Add(new XAttribute(attr.Name.LocalName, attr.Value));\n   attr.Remove();\n}	0
24927975	24927885	Passing paramerets are showing wrong for a Custom Method	string[] arrline= ReadFromFile(filepath,count,ref lineCount);	0
7913574	7913461	C# How do I take my sqlDataReader offline?	private DataTable OpenDataStream(String sql)\n{\n\n    DataTable dt = new DataTable();\n\n    SqlCommand sqlComm = new SqlCommand();\n    sqlComm.Connection = new SqlConnection();\n    sqlComm.Connection.ConnectionString = @"Myconnectionstring";\n    sqlComm.CommandText = sql;\n    sqlComm.Connection.Open();\n    SqlDataReader data = null;\n    data = sqlComm.ExecuteReader();\n\n    dt.Load(data);\n\n    data.Close();\n\n    return dt;\n}	0
16435596	16433885	Disposed button still disposed after postback when in updatepanel	Button.Visible=false;	0
18142043	18141957	how to check if any checkbox is checked in grid,wpf	foreach(var child in Checksum_Collection.Children)\n{\n    if(child.getType() == typeof(CheckBox))\n    {\n        if(child.IsChecked)\n            MsgBox ("CheckboxName");    // or do whatever u want\n    }\n}	0
2911810	2911745	I want to get 2 values returned by my query. How to do, using linq-to-entity	foreach (var dept_ in dept_list)\n{\n   dt.Rows.Add(dept_.dept_id, dept_dept_name);\n}	0
10846377	10832533	bug in a table creation using smo	table.create()	0
16019865	16019791	How can I sort my string array from .GetFiles() in order of date last modified in asp.net-webpages?	var filesInOrder = new DirectoryInfo(path).GetFiles()\n                        .OrderByDescending(f => f.LastWriteTime)\n                        .Select(f => f.Name)\n                        .ToList();	0
7320309	7318491	XML validation on XSD during XSLT transformation	document()	0
27863042	27249760	C# - Machine has 250 ips, I can only retrieve 50 from code	System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()	0
19795447	19795407	Convert a list to a dictionary and sum up values using linq	var result = myList                             // No flattening\n    .GroupBy(x => x.Code)                       // Group the items by the Code\n    .ToDictionary(g => g.Key, g => g.Sum(v => v.Value)); // Total up the values	0
5453802	5453783	Where to locate custom membership, roles, profile providers in a 3-tier setup?	MyServiceLayerObject.DoThing()	0
29041122	29040990	Create new instance of MailAddress using stored variables instead of strings for parameters	myMessage.From = new MailAddress(fromEmailAddress, fromDisplayName);	0
1129223	1129204	How to use WM_Close in C#?	...Some Class...\n[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]\nstatic extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\n//I'd double check this constant, just in case\nstatic uint WM_CLOSE = 0x10;\n\npublic void CloseWindow(IntPtr hWindow)\n{\n  SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);\n}\n...Continue Class...	0
20429676	20429220	Passing a model class through a checkbox value to the controller	Request.Form["Schools"].ToString()	0
20277931	20277831	How do I find the amount of items being selected in a ListBox?	int numberSelectedItems = listBox1.SelectedItems.Count;	0
354857	354842	Converting XAML ObjectDataProvider to C#	FooSourceDS.ObjectType = typeof(myNamespace.FooSource)	0
3543640	3543563	Problem with reading XML node	//load the object with the xml file from the web...\ndoc.LoadXml(WeatherXML);\nXmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);\nnsMgr.AddNamespace("m", "http://www.w3.org/2005/Atom");\n\n//go to the main node.. \nXmlNodeList nodes = doc.SelectNodes("m:feed", nsMgr);\nConsole.WriteLine(nodes.Count);    // outputs 1	0
10021177	10015732	group by month and year parts using queryover	session.QueryOver<...>()\n   .SelectList(list => list\n      .Select(GroupProperty(Projections.SqlProjection(...)))\n      .SelectSum(x => x.Price)\n   );	0
5850609	5850596	Conversion of long to decimal in c#	Decimal fileSizeInMB = Convert.ToDecimal(fileSize) / (1024.0m * 1024.0m);	0
2527360	2527338	Make program make sure it has 3 instances of itself running at all times?	using System.Diagnostics;\n\n        // ...\n\n        string proc = Process.GetCurrentProcess().ProcessName;\n        Process[] processes = Process.GetProcessesByName(proc);\n\n        if (processes.Length != 3)\n        {\n            // ...\n        }	0
12056226	12056011	Linq add same items in the same list	from produce in BoughtProductList\ngroup produce.price by new {produce.id, produce.product_name} into grp\nselect new{grp.id, grp.product_name, TotalPrice = grp.Sum()};	0
5830779	5830730	How to select non-distinct elements along with their indexes	foreach (var grp in\n   str.Select((s, i) => new { s, i })\n      .ToLookup(pair => pair.s, pair => pair.i)\n      .Where(pair => pair.Count() > 1))\n{   \n    Console.WriteLine("{0}: {1}", grp.Key, string.Join(", ", grp));\n}	0
26337600	26332644	Using linq to group a table that contains substrings	// db is my datacontext\nvar groupByOS = (from c in\n                      (from d in db.DeviceInfo \n                       where d.Os.ToUpper().Contains("ANDROID") ||\n                       d.Os.ToUpper().Contains("IOS")\n                       group d by new { d.Os } into dev\n                       select new\n                       {\n                         User = dev.Key.Os.ToUpper().Contains("ANDROID") ? "Android" : "iOS",\n                         DeviceCount = dev.Count()\n                       })\n                 group c by new { c.User } into newgrp\n                 select new\n                 {\n                     newgrp.Key.User,\n                     Count = newgrp.Sum(q => q.DeviceCount)\n                 }).ToList();	0
17162728	17162703	Default ping timeout	public PingReply Send(string hostNameOrAddress)\n{\n    return this.Send(hostNameOrAddress, 5000, this.DefaultSendBuffer, null);\n}	0
17101022	17101007	How to retrieve an object of a specific subclass?	e.Components.OfType<theType>();	0
23437976	23437318	How to select full DataGridView and update it?	private void dataGridView1_DataBound(object sender, EventArgs e)\n{\n    foreach (GridViewRow row in dataGridView1.Rows)\n    {\n         ......\n    }\n}	0
7670928	7632502	Create IIS Application from Code	DirectoryEntry defaultWebSite = GetWebSiteEntry(DEFAULT_WEB_SITE_NAME);\n  DirectoryEntry defaultWebSiteRoot = new DirectoryEntry(defaultWebSite.Path + "/Root");\n\n  //Create and setup new virtual directory\n  DirectoryEntry virtualDirectory = defaultWebSiteRoot.Children.Add(applicationName, "IIsWebVirtualDir");\n\n  virtualDirectory.Properties["Path"][0] = physicalPath;\n  virtualDirectory.Properties["AppFriendlyName"][0] = applicationName;\n  virtualDirectory.CommitChanges();\n\n  // IIS6 - it will create a virtual directory\n  // IIS7 - it will create an application\n  virtualDirectory.Invoke("AppCreate", 1);\n\n  object[] param = { 0, applicationPoolName, true };\n  virtualDirectory.Invoke("AppCreate3", param);	0
4673089	4673020	dissecting a generic type	// Omitted null checking, type validation, etc. for brevity\nstatic string GetNonGenericTypeName(Type genericType)\n{\n    Type baseType = genericType.GetGenericTypeDefinition();\n\n    // This is PROBABLY fine since the ` character is not allowed in C# for one of\n    // your own types.\n    int stopIndex = baseType.FullName.IndexOf('`');\n\n    return baseType.FullName.Substring(0, stopIndex);\n}	0
2546	2527	Find node clicked under context menu	void treeView1MouseUp(object sender, MouseEventArgs e)\n{\n    if(e.Button == MouseButtons.Right)\n    {\n        // Select the clicked node\n        treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);\n\n        if(treeView1.SelectedNode != null)\n        {\n            myContextMenuStrip.Show(treeView1, e.Location);\n        }\n    }\n}	0
5780008	5778196	Assigning a value to my view model from my dependency property from xaml in a user control	KeyDownValue="{Binding Path=KeyThatWasPressed, Mode=TwoWay}"	0
17085576	17078798	Get Application Icon Id - Monodroid	Intent intent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);\nResolveInfo resolveInfo = context.PackageManager.ResolveActivity(intent, PackageInfoFlags.MatchDefaultOnly);\nint appIcon = resolveInfo.IconResource;	0
2728539	2650742	How to bold text With Compact Framework	; style=bold	0
11891716	11891145	How do I copy a list without using too much memory?	public class ClassExample \n{     \n    public ObservableCollection<OriginalObjectType> OriginalObjectTypes { get; set; }      \n\n    public void ConvertNewObjectTypesToOriginal(ObservableCollection<ObjectType2> objectType2s)\n     {\n         if (this.OriginalObjectTypes == null)\n             this.OriginalObjectTypes = new ObservableCollection<OriginalObjectType>();\n         else\n             this.OriginalObjectTypes.Clear();\n\n         foreach (var objectType2 in objectType2s)         \n         {\n             var originalObjectType = new OriginalObjectType { Value = objectType2.Value };\n             this.OriginalObjectTypesTemp.Add(originalObjectType);\n         }\n     }  \n}	0
31528861	31483538	How to change the font size of a grid's children text blocks dynamically in c#?	private void changeSzie_Click(object sender, RoutedEventArgs e)\n{\n    var dynamicStyle = new Windows.UI.Xaml.Style();\n\n    var targetType = typeof(Windows.UI.Xaml.Controls.TextBlock);\n\n    dynamicStyle.TargetType = targetType;\n\n    dynamicStyle.Setters.Add(new Setter(Windows.UI.Xaml.Controls.TextBlock.FontSizeProperty, int.Parse(textbox.Text)));\n\n    if (mainGrid.Resources.Keys.Contains(targetType))\n    {\n        mainGrid.Resources.Remove(targetType);\n    }\n\n    mainGrid.Resources.Add(targetType, dynamicStyle);\n}	0
27252849	27252711	How to use replace function in linq	string res = rgx2.Replace(body, "");\nres = rgx3.Replace(res, "");	0
1826128	1825760	Retrieving display value of lookup field in Dynamics CRM C# plugin	Owner ownerLookup = (Owner)entity["ownerid"];\nstring ownerName = ownerLookup.name;	0
28003881	27982216	Access the Windows context indexing file attribue using dotnet	// read\nvar isContentIndexed = ((attributes & FileAttributes.NotContentIndexed) != FileAttributes.NotContentIndexed);\n\n// set\nFile.SetAttributes(path, (File.GetAttributes(path) | FileAttributes.NotContentIndexed));\n\n// remove\nFile.SetAttributes(path, (File.GetAttributes(path) & ~FileAttributes.NotContentIndexed));	0
20933040	20927304	Sending Content of ContentPresented as Attached Command Parameter	AttachedCommand:CommandBehavior.CommandParameter="{Binding}"	0
8136237	8135897	How to parse xml	XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";\nXNamespace atom = "http://www.w3.org/2005/Atom";\n\nint id = 54;\n\nXDocument doc = XDocument.Load("feed.xml");\n\nList<XElement> properties = doc.Element(atom + "feed")\n                        .Elements(atom + "entry")\n                        .Elements(atom + "content")\n                        .Elements(m + "properties")\n                        .ToList();\n\nXElement propertiesEl = properties.Count() > 1 ? properties.FirstOrDefault(p => (int)p.Element(m + "LastID") == id) : properties[0];\n\nList<string> names = propertiesEl.Elements().Select(el => el.Name.LocalName).ToList();	0
3973267	3973184	Parse and pivot student assignment data in c#	// print some header information\nforeach (var student in studentList)\n{\n    Display(student.Name);\n    foreach (var assignment in assignmentList)\n    {\n       if (Exists(student, assignment, studentAssignmentPairs))\n           Display("<complete>");\n       else\n           Display("<incomplete>");\n    }\n    // newline\n}	0
13877398	13877335	Linq query stage in a process	var query = from e in context.Employees\n            join ea in context.EmployeeAudit \n                 on e.EmployeeId equals ea.EmployeeId into g\n            where g.OrderByDescending(x => x.DateCreated)\n                   .FirstOrDefault().AuditCode == "SubmittedToHR"\n            select e;	0
33700384	33700282	How to keep focus on TextBox while typing in it?	textBox1.Focus();\ntextBox1.SelectionStart = textBox1.Text.Length;	0
22882296	22882283	How to clear a textbox in asp.net?	TextBox1.Text = string.Empty;	0
25408517	25408377	Action getting a null parameter C# MVC 4	[HttpPost]\npublic ActionResult Default(int cono, string firstName, string lastName, string branch, string salesRep, bool statustype)\n{\n    //Query the Search Options with the database and return the matching results to the Results Page.\n    var results = EmployeeDb.EmployeeMasters.Where(e => e.StatusFlag == statustype);\n\n    results = results.Where(e => e.CompanyNumber == cono);\n    if (!branch.IsNullOrWhiteSpace())\n    {\n        results = results.Where(e => e.Branch == branch);\n    }\n    if (!firstName.IsNullOrWhiteSpace())\n    {\n        results = results.Where(e => e.FirstName == firstName);\n    }\n    if (!lastName.IsNullOrWhiteSpace())\n    {\n        results = results.Where(e => e.LastName == lastName);\n    }\n\n    return Results(results.ToList()); \n}	0
12109621	12102000	Send Win API paste cmd from background C# app	private void SendCtrlV()\n{\n    IntPtr hWnd = GetFocusedHandle();\n    PostMessage(hWnd, WM_PASTE, IntPtr.Zero, IntPtr.Zero);\n}\n\nstatic IntPtr GetFocusedHandle()\n{\n    var info = new GuiThreadInfo();\n    info.cbSize = Marshal.SizeOf(info);\n    if (!GetGUIThreadInfo(0, ref info))\n        throw new Win32Exception();\n    return info.hwndFocus;\n}	0
13800206	13797043	Change ImageUrl of image outside Repeater with value from inside Repeater	HtmlImage aImage=(HtmlImage)RptRow.Parent.Parent.Parent.FindControl("aImage"); \n // RptRow is RepeaterItem \n aImage.Src = "Your url";	0
3050008	3049980	How are these numbers converted to a readable Date/Time string?	long l = 1272740342854;\nDateTime dt = new DateTime(1970, 1, 1).AddMilliseconds(l);\nConsole.WriteLine(dt);	0
17625404	17621714	Renaming event handlers of a legacy WinForms application using Resharper	void On{.+}\(object sender, EventArgs e\)	0
15874872	15874300	Log in as different user using asp.net windows authentication	runas /user:DOMAIN\USER "c:\Program Files (x86)\Mozilla Firefox\firefox.exe"	0
7446617	7445911	Getting Expression Text for lambda Expressions	public static string GetMemberName(this LambdaExpression expr) {\n  var lexpr = expr;\n  MemberExpression mexpr = null;\n  if (lexpr.Body is MemberExpression) {\n    mexpr = (MemberExpression) lexpr.Body;\n  } else if (lexpr.Body is UnaryExpression) {\n    mexpr = (MemberExpression) ((UnaryExpression) lexpr.Body).Operand;\n  }\n  if (mexpr == null) {\n    return null;\n  }\n  return mexpr.Member.Name;\n}	0
11072529	11072473	How to truncate a file down to certain size but keep the end section?	using(MemoryStream ms = new MemoryStream(10 * 1024 * 1024)) {\n    using(FileStream s = new FileStream("yourFile.txt", FileMode.Open, FileAccess.ReadWrite)) {\n        s.Seek(-10 * 1024 * 1024, SeekOrigin.End);\n        s.CopyTo(ms);\n        s.SetLength(10 * 1024 * 1024);\n        s.Position = 0;\n        ms.CopyTo(s);\n    }\n}	0
2086032	2085769	Identifying a certain node in XML	ds.Tables("infNFe").Rows(0).Item(2)	0
16647807	16643658	Trying to access battery level, c#	foreach (ManagementObject obj in searcher.Get()) {\n        foreach (var prop in obj.Properties) {\n            if (prop.Value != null) {\n                txtBox.AppendText(string.Format("{0} = {1}", prop.Name, prop.Value));\n            }\n        }\n    }	0
3794293	3793997	Pass arguments to running application	static class Program\n{\n    [STAThread]\n    static void Main(params string[] Arguments)\n    {\n        SingleInstanceApplication.Run(new ControlPanel(), NewInstanceHandler);\n    }\n\n    public static void NewInstanceHandler(object sender, StartupNextInstanceEventArgs e)\n    {\n        string imageLocation = e.CommandLine[1];\n        MessageBox.Show(imageLocation);\n        e.BringToForeground = false;\n        ControlPanel.uploadImage(imageLocation);\n    }\n\n    public class SingleInstanceApplication : WindowsFormsApplicationBase\n    {\n        private SingleInstanceApplication()\n        {\n            base.IsSingleInstance = true;\n        }\n\n        public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)\n        {\n            SingleInstanceApplication app = new SingleInstanceApplication();\n            app.MainForm = f;\n            app.StartupNextInstance += startupHandler;\n            app.Run(Environment.GetCommandLineArgs());\n        }\n    }  \n}	0
27617604	27617289	How to get values in expression	class Program\n{\n    static void Main(string[] args)\n    {\n        string path = GetPropertyName<Test>(x => x.Test2.Application.Id);\n    }\n\n    static string GetPropertyName<T>(Expression<Func<T, object>> expression)\n    {\n        var memberExpression = (MemberExpression)expression.Body;\n        return GetMemberExpressionPath(memberExpression);\n    }\n\n    static string GetMemberExpressionPath(MemberExpression exp)\n    {\n        string s = null;\n\n        var rootExp = exp.Expression as MemberExpression;\n        if (rootExp != null)\n        {\n            s = GetMemberExpressionPath(rootExp);\n        }\n\n        //var paramExp = exp.Expression as ParameterExpression;\n        //if (paramExp != null)\n        //{\n        //    s = paramExp.Name;\n        //}\n\n        return (s != null ? s + "." : "") + exp.Member.Name;\n    }\n\n}	0
10805137	10804996	c# How can i know if a certain process is running on a remote machine	Process[] processList = Process.GetProcesses("machineName");	0
17537710	17537663	How to add child where parent element's attribute = x	var query = from positions in myDoc.Descendants("position")\n            where (string)positions.Attribute("index").Value == n\n            select positions;\nforeach (var position in query)\n{\n    position.Add(new XElement("character", "g"));\n}	0
23834384	23834355	How to switch Property Name based on String Variable?	var PropertyName = "SecondProperty";\n var result = db.GetData().Where(i = i.GetType().GetProperty(PropertyName).GetValue(i).ToString().Contains(someString));	0
17299914	17213866	How can I open a file for edit (check-out) in Perforce using p4api.net.dll	//creating changelist\n    Changelist cl = new Changelist();\n    cl.Description = change_description;\n    cl.ClientId = workspace_name;\n    cl = rep.CreateChangelist(cl);\n    return cl;\n}	0
19710134	19709971	SQL to LINQ with many joins	new {col1 = x.col1, col2 = x.col2, ...} equals new { col1 = y.col1, col2 = y.col2, ...}	0
1148894	1148883	Duplicate a linked list	public static Node Duplicate(Node n)\n    {\n        // handle the degenerate case of an empty list\n        if (n == null) {\n            return null;\n        }\n\n        // create the head node, keeping it for later return\n        Node first = new Node();\n        first.Data = n.Data;\n\n        // the 'temp' pointer points to the current "last" node in the new list\n        Node temp = first;\n\n        n = n.Next;\n        while (n != null)\n        {\n            Node n2 = new Node();\n            n2.Data = n.Data;\n            // modify the Next pointer of the last node to point to the new last node\n            temp.Next = n2;\n            temp = n2;\n            n = n.Next;\n        }\n\n        return first;\n\n    }	0
34443660	34443486	Dock Panel on Button Click C#	public Form1()\n{\n    InitializeComponent();\n    panel1.BringToFront();\n}\n\nprivate void Up_Click(object sender, EventArgs e)\n{\n    panel1.Dock = DockStyle.Fill;\n    panel2.Dock = DockStyle.Top;\n}\n\nprivate void Down_Click(object sender, EventArgs e)\n{\n    panel1.Dock = DockStyle.Fill;\n    panel2.Dock = DockStyle.Bottom;\n}	0
30937897	30937812	Get Identity of all objects after SaveChanges	context = new MyContext();\nList<abc> addedABCs = new List<abc>();\nList<xyz> addedXYZs = new List<xyz>();\nforeach (var x in lstX)\n{ \n    var abc = new abc{ name= x.abcName };\n    addedABCs.Add(abc);\n    context.abcs.Add(abc);\n\n    var xyz = new xyz{ name = x.xyzName };\n    addedXYZs.Add(xyz);\n    context.xyzs.Add(xyz);\n}\n\ncontext.SaveChanges();\n\nforeach (var abc in addedABCs) \n{\n    Console.WriteLine("Added item with ID {0}", abc.Id);\n}	0
3036365	3036311	Unable to Hide Update Button in GridView Editing	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) \n{ \n  GridView1.EditIndex = -1;\n  bindGrid();\n}	0
4131390	4131369	How can I replace this pattern with Regex?	String input = @"...src=""/foo/bar""..";\nString output = Regex.Replace(input, "src=\"[^\"]*\"", (m) => m.ToString().Replace('/', '\\'));	0
25175885	25175761	c# compare string list to regex list	foreach(string item in StringList)\n{\n  foreach(var reg in regexList)\n  {\n    if(reg.IsMatch(item))\n     ///Do something \n  }\n}	0
30619499	30619225	Open existing window in Gtk#	Actwindow myWindow = new Actwindow();\nmyWindow.Show(); // or similar	0
3856748	3856738	Using web.config in a Self-Hosted c# WCF console app (setting MaxStringContentLength server side)	app.config	0
26118881	26101791	Nhibernate Rollback and Check success of Transaction with Stored Procedure	session.CreateSQLQuery(...).ExecuteUpdate();	0
18694175	18694101	Make middle column take all the remaining space	HorizontalAlignment="Stretch"	0
18343469	18343378	Convert PartialView to HTML	public static string RenderViewToString(ControllerContext context, string viewName, object model)\n    {\n        if (string.IsNullOrEmpty(viewName))\n            viewName = context.RouteData.GetRequiredString("action");\n\n        var viewData = new ViewDataDictionary(model);\n\n        using (var sw = new StringWriter())\n        {\n            var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);\n            var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);\n            viewResult.View.Render(viewContext, sw);\n\n            return sw.GetStringBuilder().ToString();\n        }\n    }	0
2039433	2039425	Access XAML Instantiated Object from C#	FindResource("MyConnection")	0
15163900	15163874	how to read int value from dataset? in C#	function GetIntValue()\n{\nSqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);\n\n    con.Open();\n\n    SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Employees",con);\n    int numberOfEmployees = (int)cmdCount.ExecuteScalar();\n    Response.Write("Here are the " + numberOfEmployees.ToString() + " employees: <br><br>");\n\n    SqlCommand cmd = new SqlCommand("SELECT * FROM Employees",con);\n    SqlDataReader dr = cmd.ExecuteReader();\n    while(dr.Read()) {\n        Response.Write(dr["LastName"] + "<br>");\n    }\n    con.Close();\n}	0
7733346	7733208	Looking for a slicker way to convert delimited string to StringDictionary	private static readonly StringDictionary streetTypes = new StringDictionary\n{\n    {"ALY","Alley"},{"AVE","Avenue"},{"ALY","Alley"},{"BLVD","Boulevard"},{"CIR","Circle"},\n    {"CT","Court"},{"CTR","Center"},{"DR","Drive"},{"EXPY","Expressway"},{"FWY","Freeway"},\n    {"HALL","Hall"},{"HWY","Highway"},{"JCT","Junction"},{"LN","Lane"},{"LP","Loop"},\n    ...        \n};	0
25948970	25670739	How to make AutoFac use same instance of nested dependency per top-level object? (SignalR dependency injection per hub)	container.Register(Component.For<Hub>().LifestyleTransient());\ncontainer.Register(Component.For<FooRepo>().LifestyleTransient());\ncontainer.Register(Component.For<BarRepo>().LifestyleTransient());\ncontainer.Register(Component.For<Context>().LifestyleBoundTo<Hub>()); // Important bit	0
34518797	34518573	Implicit interface inheritance	interface IFirstInterface\n{\n    bool IsReal(); \n}\ninterface ISecondInterface\n{\n    bool IsReal();\n}\n\npublic class ExampleClass : IFirstInterface, ISecondInterface\n{\n    // will be used for IFirstInterface\n    bool IFirstInterface.IsReal(){}\n\n    // will be used for ISecondInterface\n    public bool IsReal(){}\n}	0
8213675	8213605	Get values from an enum into a generic List	List<T> list = System.Enum.GetValues(typeof(T))\n                          .Cast<T>()\n                          .ToList<T>();	0
12274518	12274295	Why Doesn't Regex give a chance to input data?	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString() , @"^[a-zA-Z]+$")) \n         e.Handled = true;\n}	0
7744248	7744161	Using reflection to find DynamicMethods	DivideInvoker invoker = CreateInvoker();\nMethodInfo method = invoker.Method;\n// method will contain the MethodInfo of the Division dynamic method\n// so you could use reflection on it	0
11448270	11447529	Convert an object to an XML string	public string ToXML()\n    {\n        var stringwriter = new System.IO.StringWriter();\n        var serializer = new XmlSerializer(this.GetType());\n        serializer.Serialize(stringwriter, this);\n        return stringwriter.ToString();\n    }\n\n public static YourClass LoadFromXMLString(string xmlText)\n    {\n        var stringReader = new System.IO.StringReader(xmlText);\n        var serializer = new XmlSerializer(typeof(YourClass ));\n        return serializer.Deserialize(stringReader) as YourClass ;\n    }	0
27554865	27552597	Unity Parameter Injection with the InjectionConstructor	container.RegisterType(typeof(GraphClient), \n                       new InjectionFactory(c => new GraphClient(RootUri)));	0
9261112	9261070	Set Datetime format - C# 	string myFormat = Value.ToString("dd/MM/yyyy");	0
23990185	23990105	How to add first n numbers in an array c#	for (i = 1; i < totalnumber; i++)\n{\n    Xdis[i] = XDis[i-1] + Xvelo[i-1];\n    Ydis[i] = YDis[i-1] + Yvelo[i-1];\n    Zdis[i] = ZDis[i-1] + Zvelo[i-1]; \n}	0
2223228	2222646	How to restore an IIS Metabase backup using C#	const uint MD_BACKUP_HIGHEST_VERSION = 0xfffffffe;\nconst uint MD_BACKUP_NEXT_VERSION = 0xffffffff;\nconst uint MD_BACKUP_SAVE_FIRST = 2;\n\nusing(DirectoryEntry de = new DirectoryEntry("IIS://Localhost"))\n{\n  // Backup using the next version number (MD_BACKUP_NEXT_VERSION)\n  de.Invoke("Backup", new object[] {\n      "test-backup",\n      MD_BACKUP_NEXT_VERSION,\n      MD_BACKUP_SAVE_FIRST\n  });\n\n  // Restore the highest version number (or specify the specific version)\n  de.Invoke("Restore", new object[] {\n    "test-backup",\n    MD_BACKUP_HIGHEST_VERSION,\n    0\n  });\n}	0
7245211	7234981	How to change buttonstyle in WPF, triggered by a boolean?	this.DataContext = Classname;	0
5032573	5032430	Set Copy to Output folder by code	buildItem.SetMetadata("CopyToOutputDirectory", "Always");	0
22237171	22236707	How could I control the DialogResult of a button?	if (!isAllInfoEntered())\n{\n    this.DialogResult = DialogResult.None;\n    //Show the message box\n    return;\n}	0
11816404	11816007	How to get checkbox value from a gridview with a child gridview	foreach (GridViewRow row in gvMaster.Rows) \n{\n    if (row.RowType == DataControlRowType.DataRow) \n    {\n        GridView gvChild = (GridView) row.FindControl("nestedGridView");\n        // Then do the same method for check box column \n        if (gvChild != null)\n        {\n            foreach (GridViewRow row in gvChild .Rows) \n            {\n                if (row.RowType == DataControlRowType.DataRow) \n                {\n                    CheckBox chk = (CheckBox) row.FindControl("chkselect");\n                    if (chk.Checked)\n                    {\n                        // do your work\n                    }\n                }\n            }\n        }\n    }\n}	0
4611908	4611655	How do I POST data from an asp.net MVC controller to a non-MVC asp.net page?	// name / value pairs. field names should match form elements\nstring data = field2Name + "=" + field1Value + "&" + field2Name+ "=" + field2Value\n\nHttpWebRequest request = (HttpWebRequest) WebRequest.Create(<url to other applications form action>);\n\n// set post headers\nrequest.Method = "POST";\nrequest.KeepAlive = true;\nrequest.ContentLength = data.Length;\nrequest.ContentType = "application/x-www-form-urlencoded";\n\n// write the data to the request stream         \nStreamWriter writer = new StreamWriter(request.GetRequestStream());\nwriter.Write(data);\n\n// iirc this actually triggers the post\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();	0
5303847	5303762	Setting a classes' properties from NameValueCollection	var col = HttpUtility.ParseQueryString(decodedString);\nvar cp = new ConfirmationPage();\n\nforeach (var prop in typeof(ConfirmationPage).GetProperties())\n{\n    var queryParam = col[prop.Name];\n    if (queryParam != null)\n    {\n         prop.SetValue(cp,queryParam,null);\n    }\n}	0
8236747	8236679	Replacing string in c# to block skype phone formatting	string ThePhone = "XXX-XXX-XXXX";\nstring SkypeBlock = "-<span style=\"display:none;\">-</span>";\n\nThePhone = ThePhone.Substring(0, 8) + SkypeBlock + ThePhone.Substring(8, 4);	0
11655041	11654723	How to populate a ComboBox After adding new item	... \nclass A\n{\n    private ObservableCollection<string> variables = new ObservableCollection<string>();\n\n    ...\n    private void FillVariablesList() \n    {\n        variables.Clear();\n        variables.Add(""); \n        variables.Add(New_Variable); \n\n        foreach (Variable v in this.theTaskHost.Variables) \n        { \n            if (!v.SystemVariable && v.DataType == TypeCode.String) \n                variables.Add(v.Name); \n        }\n\n        this.comboBox.DataSource = null;\n        this.comboBox.DataSource = variables;\n    }\n}	0
23608026	23607958	Checking for null on object before trying to access it	editItem.FrameVent = fd.Where(x => x.hardwaretype == 39 && x.name.StartsWith("Frame Vent"))\n                       .Select(p => p.hardwareid)\n                       .FirstOrDefault();	0
14583561	14583422	Keep getting errors on a basic c# console app	result1 = new checkConvertValue().formula1(num);	0
28726801	28725968	Using ToLookup with two fields	var queryResult = getRouteInfoPdfPurpose.OrderBy(t => t.Day).ThenBy(n => n.CustomerNbr).ToLookup(t => new {t.Day, t.CustomerNbr });	0
10586214	10586151	Find duplicates in google site map	XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";\nvar duplicates =\n    from loc in doc.Root.Elements(ns + "url").Elements(ns + "loc")\n    group loc by loc.Value into g\n    where g.Count() > 1\n    select g.Key;	0
8161943	8161854	Append Text Insert to ListBox or ComboBox1	richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString(); \n\nforeach (string line in richTextBox.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)\n{\n    listBox1.Items.Add(line); \n}	0
2128246	2128241	Using string constants in implicit conversion	public static implicit operator TextType(String text) {\n    return new TextType(text);\n}	0
16593721	16593613	LINQ combined columns contain	var items = listOfObjects.Where(t => (t.firstName + " " + t.middleInitial + " " +  t.lastName).Contains(x));	0
3824505	3824487	What content-type do I use for http response headers that contain a file attachment of unknown file type?	application/octet-stream	0
13599096	13584550	Custom OrderBy on a List of List	public List<Person> GetSortedList(List<Person> personList)\n{\n   foreach (var person in personList)\n   {\n       person.CarList=person.CarList.OrderByDescending(x => x.Name== "BMW").ToList();\n   }\n return personList;\n}	0
3515802	3515788	Trouble getting data out of a xml file	".../address_component[type='administrative_area_level_1']/short_name"\n                            ?                           ?	0
12595697	12595612	C#.NET: How to create self data relationship on single DataTable?	DataRelation relation = new DataRelation("ParentChild",\n        result.Tables["Employee"].Columns["UserID"],\n        result.Tables["Employee"].Columns["ManagerID"],\n        true);\n\nrelation.Nested = true;\nresult.Relations.Add(relation);	0
7479205	7479117	Delete Items in an ObservableCollection That are Bound to A GridView	this._searchTerms.Remove(this.listView1.SelectedItem);	0
21031068	21031021	Redirect root View to a view in a different folder (Area folder) not in Root	return RedirectToAction("Action", "Controller", new { area = "areaName" });	0
2485060	2485027	TimeSpan to Localized String in C#	public static string ConvertToReadable(this TimeSpan timeSpan) { \n    return string.Format("{0} {1} {2} {3} {4} {5}",\n        timeSpan.Days, (timeSpan.Days > 1 || timeSpan.Days == 0) ? "days" : "day",\n        timeSpan.Hours, (timeSpan.Hours > 1 || timeSpan.Hours == 0) ? "hours" : "hour",\n        timeSpan.Minutes, (timeSpan.Minutes > 1 || timeSpan.Minutes == 0) ? "minutes" : "minute");\n}	0
6637064	6636957	product trader pattern in c#	public abstract class Creator<ProductType, SpecType>\n{\n    public Creator(SpecType aSpec) { _aSpecification = aSpec; }\n\n    public SpecType GetSpecification() { return _aSpecification; }\n\n    public abstract ProductType Create();\n\n    private SpecType _aSpecification;\n}\n\npublic class ConcreteCreator<ProductType, ConcreteProductType, SpecType> : Creator<ProductType, SpecType> where ConcreteProductType : ProductType, new()\n{\n    public ConcreteCreator(SpecType aSpec) : base(aSpec) { }\n\n    public override ProductType Create() { return new ConcreteProductType(); }\n}	0
33295046	33294738	Read all values from CSV into a List using CsvHelper	public static List<string> ReadInCSV(string absolutePath) {\n    List<string> result = new List<string>();\n    string value;\n    using (TextReader fileReader = File.OpenText(absolutePath)) {\n        var csv = new CsvReader(fileReader);\n        csv.Configuration.HasHeaderRecord = false;\n        while (csv.Read()) {\n           for(int i=0; csv.TryGetField<string>(i, out value); i++) {\n                result.Add(value);\n            }\n        }\n    }\n    return result;\n}	0
11609774	11609724	Can we convert UTC time to 24 hour Format? if yes, then How?	DateTime UniversalScheduleDate = DateTime.SpecifyKind(\nDateTime.Parse(txtDate.Text),DateTimeKind.Utc);\n\nstring formattedDate = DateTime.UniversalScheduleDate.ToString("HH:mm:ss tt");	0
13462204	13462141	LINQ lambda expression append OR statement	var predicate = PredicateBuilder.False<Product>();\npredicate = predicate.Or (obj=>obj.Id == id);\nif(name.HasValue)  predicate = predicate.Or (obj=>obj.Name == name);\n\nreturn query.Where(predicate);	0
5511825	5511778	Method to access/set a session object in C# .net	public MyData SessionStore\n{\n    get { return (MyData)(Session["MyData"]) ?? new MyData(); }\n    set { Session["MyData"] = value; }\n}	0
12058782	12058697	Reflection - get method for a nullable<datetiime>	Type t = typeof (Nullable<DateTime>);\n\nConsole.WriteLine(t.Name);   // Nullable`1\nif (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))\n{\n    Type t2 = Nullable.GetUnderlyingType(t);\n    Console.WriteLine("Nullable"+t2.Name); // NullableDateTime\n}	0
29030803	29030723	Read a stored PDF from memory stream	public void LoadPdf(byte[] pdfBytes)\n    {\n        var stream = new MemoryStream(pdfBytes);\n        LoadPdf(stream)\n    }\n\n    public void LoadPdf(Stream stream)\n    {\n        // Create PDF Document\n        var pdfDocument = PdfDocument.Load(stream);\n\n        // Load PDF Document into WinForms Control\n        pdfRenderer.Load(_pdfDocument);\n    }	0
10466083	10466041	How can I generate DDL scripts from Entity Framework 4.3 Code-First Model?	Update-Database -Script	0
29608167	29595296	Add Imap Folder Mailkit	var toplevel = client.GetFolder (client.PersonalNamespaces[0]);\nvar mailkit = toplevel.Create ("mailkit", false);\nvar archive = mailkit.Create ("archive", true);\nvar flagged = mailkit.Create ("flagged", true);	0
23983665	23982633	ScriptManager breaks upon publishing to IIS	ScriptManager.RegisterStartupScript(this.searchBut, searchBut.GetType(), "jquery", "     <script src=\"" + Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/Scripts/DataTables-1.10/jquery.js\" type=\"text/javascript\"></script>", false);	0
15965076	15964864	Change the datetime display format on datagridview date column	string date = this.ToolStripTextBox2.Text;\n   DateTime dtDate = DateTime.ParseExact(date, "dd/MM/yyyy", null);	0
26303724	26303551	Getting Data from SQL DB for ASP.NET Web Forms API	// Create a connection to the database        \n    SqlConnection conn = new SqlConnection("Data Source=MyDBServer;Initial Catalog=MyDB;Integrated Security=True");\n    // Create a command to extract the required data and assign it the connection string\n    SqlCommand cmd = new SqlCommand("SELECT * FROM Product", conn);\n    cmd.CommandType = CommandType.Text;\n    // Create a DataAdapter to run the command and fill the DataTable\n    SqlDataAdapter da = new SqlDataAdapter();\n    da.SelectCommand = cmd;\n    DataTable dt = new DataTable();\n    da.Fill(dt);\nList<Product> products = new List<Product>();\nforeach(DataRow row in dt.Rows)\n{\n    products.add(New Product{ row["Id"], row["Name"], row["Category"], row["Price"]});\n}	0
10673072	10673016	Two Imagebutton with same OnClick event.	protected void CheckIMG(object sender, ImageClickEventArgs e)\n{\n    HiddenField imgNameHF = (HiddenField)DetailsView1.FindControl("sent_info_to_db_HF");\n    ImageButton imgb=(ImageButton) sender;\n    imgNameHF.Value = "'<%# CheckValue(Eval('" + imgb.ImageUrl + "')%>'";\n}	0
13192548	13191871	XmlDocument from XML string that contains custom namespaces causes XmlException?	XNamespace  my = "http://foobar.com/";\n\n var doc = new XDocument(new XElement("root", \n                new XAttribute(XNamespace.Xmlns +  "my", my)));\n\n var body = new XElement("body");\n doc.Root.Add(new XElement("item", new XAttribute("id", 12345), body));\n\n string innerItem = @"<aaa><bbb my:attr=""55"">Foo</bbb></aaa>";       \n string itemWrap = @"<wrap xmlns:my=""http://foobar.com/"">" + innerItem + "</wrap>";\n\n XElement item = XElement.Parse(itemWrap);\n body.Add(item.Element("aaa"));\n\n Console.WriteLine(doc);	0
11968286	11965495	How can I close the TextWriter stream on Windows XP successfully?	using(var writer = new StreamWriter(@"")\n{\n    // ...\n\n    writer.Flush();\n}	0
15449851	15449473	Replacing XML serialization of class member	[Serializable()]\npublic class Camera\n{\n    public string name;\n    public int index;\n    public double distance;\n    public List<string> CameraList { get; set; }\n\n    private GMarkerGoogle _marker;\n    [XmlIgnore()]\n    public GMarkerGoogle Marker\n    {\n        set\n        {\n            _marker = value;\n            MarkerPosition = _marker.position;\n            MarkerRotation = _marker.rotation;\n        }\n        get\n        {\n            if (_marker == null)\n            {\n                _marker = new GMarkerGoogle(MarkerPosition, MarkerRotation);\n            }\n\n            return _marker;\n        }\n    }\n\n    public double MarkerPosition { get; set; }\n    public double MarkerRotation { get; set; }\n\n    public Camera()\n    {\n    }\n}	0
32010816	32009527	Clearing All ComboBoxes method	private void ClearAllComboboxes()\n    {\n        List<ComboBox> comboBoxes = new List<ComboBox>();\n\n        GetLogicalChildCollection<ComboBox>(container, comboBoxes);\n\n        comboBoxes.ForEach(combobox => combobox.SelectedIndex = -1);\n    }\n\n    private static void GetLogicalChildCollection<T>(DependencyObject parent,List<T> logicalCollection) where T : DependencyObject\n    {\n\n        var children = LogicalTreeHelper.GetChildren(parent);\n        foreach (object child in children)\n        {\n            if (child is DependencyObject)\n            {\n                DependencyObject depChild = child as DependencyObject;\n                if (child is T)\n                {\n                    logicalCollection.Add(child as T);\n                }\n                GetLogicalChildCollection(depChild, logicalCollection);\n            }\n        }\n    }	0
6248105	6247842	How do I search for files using C# on a windows OS	string SearchDirectory = "C:\\SomeDirectory\\";\nList<String> FilesToSearch = new List<string>();\n//Populate FilesToSearch from your csv...\nforeach (String CurrentFileToSearch in FilesToSearch)\n{\n    if (System.IO.File.Exists(SearchDirectory + TargetFileName))\n    {\n        //Do Something!\n    }\n}	0
22130661	22130301	how to setup Twilio	var message = twilio.SendSmsMessage("[YOUR_FROM_NUMBER]","[YOUR_TO_NUMBER]","[MESSAGE_BODY]");\nif (message.RestException != null) {\n\n    //An error happened calling the REST API\n    Debug.Writeline(message.RestException.Message);\n\n}	0
18612374	18609779	C# Regular Expressions info from urls	string pattern = "(video[\w-]+)";\nstring url = "http://blahblah/video-12341237293";\n\nMatch match = Regex.Match(url, pattern);\n// Here you can test Match to check there was a match in the first place\n// This will help with multiple urls that are dynamic rather than static like the above example\n\nstring result = match.Groups[1].Value;	0
22144030	22143850	Datepicker Value change windows phone 8	private void dateData_Loaded(object sender, RoutedEventArgs e)\n    {\n      if(NavigationContext.QueryString.ContainsKey("Date"))\n       {\n        dateData.Value = DateTime.Parse(NavigationContext.QueryString["Date"]);\n        NavigationContext.QueryString.Remove("Date");\n       }\n    }	0
12146784	12145618	Localize Data validation errors	if (PropertyGetters.ContainsKey(columnName))\n            {\n                ValidationContext context = new ValidationContext(this, null, null)\n                {\n                    MemberName = columnName\n                };\n\n                List<ValidationResult> results = new List<ValidationResult>();\n                var value = GetType().GetProperty(columnName).GetValue(this, null);\n\n                return !Validator.TryValidateProperty(value, context, results)\n                           ? string.Join(Environment.NewLine, results.Select(x => x.ErrorMessage))\n                           : null;\n            }\n\n            return null;	0
1336323	1336200	Return values from two long running methods, using threads	Resource r1 = null; // need to initialize, else compiler complains\nResource r2 = null;\n\nThreadStart ts1 = delegate {\n    r1 = MySystem.GetResource(ipAddress1);\n};\nThreadStart ts2 = delegate {\n    r2 = MySystem.GetResource(ipAddress2);\n};\nThread t1 = new Thread(ts1);\nThread t2 = new Thread(ts2);\nt1.Start();\nt2.Start();\n// do some useful work here, while the threads do their thing...\nt1.Join();\nt2.Join();\n// r1, r2 now setup	0
11012394	11006994	Getting textarea content after setting it with innerHtml	if (!IsPostBack)\n    {\n        ces = new ContentEditorService.ContentEditorService();\n        strRtfDir = Server.MapPath("Testfile.rtf");\n\n        string strContents = ces.loadEditorContents(strRtfDir);\n        TextArea1.InnerText = strContents;\n    }	0
2358415	2358375	WPF definition of FontSize	FormattedText formattedText = new FormattedText(\n            textBox1.Text.Substring(0, 1),  \n            CultureInfo.GetCultureInfo("en-us"),\n            FlowDirection.LeftToRight,\n            new Typeface(textBox1.FontFamily.ToString()),\n             textBox1.FontSize,\n            Brushes.Black \n            );	0
8578636	8578562	Running cmd.exe with arguments from c#	System.Diagnostics.Process.Start("c:\temp\des.exe", "XXXX input.abcd output.zip");	0
6141788	6141726	Simple Find and Replace with Visual Studio Regular Expression	IObjectSet\<{.+}\>	0
6612476	6612454	relative path to consume local asmx	url: "<%= VirtualPathUtility.ToAbsolute("~/WebServicesASMX/PMywebserv.asmx/Test") %>",	0
23188834	23188783	How to check if file download is complete	static void Main(string[] args)\n{\n    using (WebClient myWebClient = new WebClient())\n    {\n        myWebClient.DownloadFileCompleted += DownloadCompleted;\n        myWebClient.DownloadFileAsync(new Uri("http://someUrl"), @"e:\file.mp3");\n    }\n\n    Console.ReadLine();\n}\n\npublic static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)\n{\n    Console.WriteLine("Success");\n}	0
16226556	16184687	Populating a Datagrid with records between a date and time period - Using C# and OLE DB	SqlConnection con = new SqlConnection(MyconnectionString);\ncon.Open();\nstring SQLQuery = "SELECT EmailID, receiveDateTime " \n                + "WHERE EmailTable.receiveDateTime " \n                + "BETWEEN @dateFrom AND @dateTo";\n\nSqlCommand cmd = new SqlCommand(SQLQuery );\ncmd.Parameters.AddWithValue("@dateFrom", fromDateTime.Value.ToOADate());\ncmd.Parameters.AddWithValue("@dateTo", toDateTime.Value.ToOADate());	0
28120452	28120246	Custom validation method that accesses other model properties	public class OneWheelchairPerTrainAttribute : ValidationAttribute\n{\n  public override bool IsValid(object value, ValidationContext context)\n  {\n    Object instance = context.ObjectInstance;\n    Type type = instance.GetType();\n    // Here is your timetableId\n    Object timeTableId = type.GetProperty("TimetableId ").GetValue(instance, null);\n\n    //Do validation ...\n   }\n}	0
3986987	3986977	How to deallocate COM server object forcefully from C# .NET	System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp);	0
938578	938464	PopUp window on a specific time in WPF?	private System.Windows.Threading.DispatcherTimer popupTimer;\n\n// Whatever is going to start the timer - I've used a click event\nprivate void OnClick(object sender, RoutedEventArgs e)\n{\n    popupTimer = new System.Windows.Threading.DispatcherTimer();\n\n    // Work out interval as time you want to popup - current time\n    popupTimer.Interval = specificTime - DateTime.Now;\n    popupTimer.IsEnabled = true;\n    popupTimer.Tick += new EventHandler(popupTimer_Tick);\n}\n\nvoid popupTimer_Tick(object sender, EventArgs e)\n{\n    popupTimer.IsEnabled = false;\n    // Show popup\n    // ......\n}	0
24260669	24260448	How to get public property in ImageURL?	ImagePicture.ImageUrl = string.Format("ImageHandler.ashx?ID={0}", this.ID);	0
1421282	1421247	How do I reference the Sqlite db file in the App_Data folder for my ASP.NET Web Application?	Server.MapPath(@"~\App_Data\Your.db");	0
15857029	15856793	Simplest approach to a dynamic where clause	ParameterExpression p = Expression.Parameter(typeof(Person));\nExpression personType = Expression.MakeMemberAccess(p, typeof(Person).GetProperty("PersonType"));\nExpression personTypeExpression = Expression.Constant(false);\nif (IncludeLazyPeople)\n    personTypeExpression = Expression.OrElse(personTypeExpression, Expression.Equal(personType, Expression.Constant((int)PersonTypes.Lazy)));\n\n//... same as above only with different Constant values\n\n// filter the people for all included types\nvar filteredPeople = ctx.People.Where(Expression.Lambda<Func<Person,bool>>(personTypeExpression,p));	0
16477828	16175979	How to handle the movement of the Hero in a physic engine?	//If we have the key pressed, add velocity\nif (KeyPressed)\n{\n   Hero.speed += constant;\n}\nelse if (!KeyPressed)\n{\n    //If it's stopped, don't move it! \n    if (Hero.speed == 0)\n    {\n       //In this case, you do nothing\n    }\n    //If it has been moving, reduce the velocity\n    else\n    {\n       Hero.speed -= constant;\n    }\n}\n\n//Let's check\nif (Hero collided with Wall)\n{\n       Hero.speedX = 0;\n}	0
23939923	23939507	How to query with a join with linq to sql	var gifts = (from c in db.Categories\n             from g in c.Gifts\n             where c.Name.Contains(searchTerm)\n             select g).Distinct().ToList();	0
14363217	14363162	Add drag behavior to a form with FormBorderStyle set to None	private const Int32 WM_NCHITTEST = 0x84;\nprivate const Int32 HTCLIENT = 0x1;\nprivate const Int32 HTCAPTION = 0x2;\n\nprotected override void WndProc(ref Message m)\n{\n    if (m.Msg == WM_NCHITTEST)\n    {\n        base.WndProc(ref m);\n\n        if ((Int32)m.Result == HTCLIENT)\n            m.Result = (IntPtr)HTCAPTION;\n\n        return;\n    }\n\n    base.WndProc(ref m);\n}	0
32198278	32197373	C# print html document from html string	WebBrowser webBrowser = new WebBrowser();\nvoid Print(string str)\n{\n   webBrowser.DocumentText = str;\n   webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;\n}\nvoid webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n   webBrowser.Print();\n}	0
5836190	5835364	How can I lag a computer in c#? CREATE lag!	using System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace LagTimer\n{\n    class Program\n    {\n        [return: MarshalAs(UnmanagedType.Bool)]\n        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]\n        public static extern bool BlockInput([In, MarshalAs(UnmanagedType.Bool)] bool fBlockIt);\n\n        static void Main(string[] args)\n        {\n            Thread t = new Thread(LagTick);\n            t.Start();\n\n            while (true) { } // Prevent the app from exiting\n        }\n\n        static void LagTick()\n        {\n            while (true)\n            {\n                BlockInput(true);\n                System.Threading.Thread.Sleep(250);\n                BlockInput(false);\n\n                // TODO: Randomize time in between ticks\n                Thread.Sleep(100);\n\n                // TODO: Add logic for when to "sputter" the mouse\n            }\n        }\n    }\n}	0
3774024	3773919	P/Invoke C# struct with strings to C void*	[DllImport("LIBRARY.DLL", EntryPoint = "command")]\npublic static extern int Command(IntPtr Handle, int CommandNum, ref FormatInfoType Data, int DataSize);	0
9619418	9619324	how to read a Xml file and write into List<>?	XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));\n\nusing(FileStream stream = File.OpenWrite("filename"))\n{\n    List<MyClass> list = new List<MyClass>();\n    serializer.Serialize(stream, list);\n}\n\nusing(FileStream stream = File.OpenRead("filename"))\n{\n    List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);\n}	0
33917319	33916086	File compression in Unity3D	using UnityEngine;\nusing System.Collections;\nusing CielaSpike; //include ninja threads\n\npublic class MyAsyncCompression : MonoBehaviour {\n\n\n    public void ZipIt(){\n        //ready data for commpressing - you will not be able to use any Unity functions while inside the asynchronous coroutine\n        this.StartCoroutineAsync(MyBackgroundCoroutine()); // "this" means MonoBehaviour\n\n    }\n\n    IEnumerator MyBackgroundCoroutine(){\n        //Call CompressFolder() here\n        yield return null;\n    }\n\n    private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) {\n        /*...\n         *... \n          ...*/\n    }\n\n}	0
5186381	5186354	How to convert byte array to image and display in datagrid?	MemoryStream ms = new MemoryStream(imageBytes);\n Image image= Image.FromStream(ms);	0
15185565	15185538	How to play music in window form application by clicking button C#	SoundPlayer snd = null;\n\nprivate void musicbutton_Click(object sender, EventArgs e) {\n    Stream str = Properties.Resources.mySoundFile;\n    snd = new SoundPlayer(str);\n    snd.Play();\n}	0
2150474	2150455	How do I create an MD5 hash digest from a text file?	using System.Security.Cryptography;\n\n    public string HashFile(string filePath)\n    {\n        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n        {\n            return HashFile(fs);\n        }\n    }\n\n    public string HashFile( FileStream stream )\n    {\n        StringBuilder sb = new StringBuilder();\n\n        if( stream != null )\n        {\n            stream.Seek( 0, SeekOrigin.Begin );\n\n            MD5 md5 = MD5CryptoServiceProvider.Create();\n            byte[] hash = md5.ComputeHash( stream );\n            foreach( byte b in hash )\n                sb.Append( b.ToString( "x2" ) );\n\n            stream.Seek( 0, SeekOrigin.Begin );\n        }\n\n        return sb.ToString();\n    }	0
21041905	21041296	In LINQ Query convert the string to datetime and check with today's date	// Our required date\nDateTime reportDate = new DateTime(2014,1,1).Date; \n// Let's find number of days between now and required day. Ensure that the date is not in the future!\nint deltaDays = (DateTime.Now.Date - date).Days; \n// Let's get the list of dates which we need the reports for\nvar dates = Enumerable.Range(0, deltaDays + 1).Select(dd => DateTime.Now.Date.AddDays(-dd).ToString("MM/dd/yyyy")).ToArray();\n// and query by this list\nvar query = (from o in db.Order_Reports\n          where o.ReportDueDateTime in dates\n          select o);	0
34490709	34474850	Is stream Reading can make and send Null to blob storage	StorageCredentials creds = new StorageCredentials(\n                ConfigurationManager.AppSettings["accountName"],\n                ConfigurationManager.AppSettings["accountKey"]\n                );\n            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);\n            CloudBlobClient client = account.CreateCloudBlobClient();\n            CloudBlobContainer contain = client.GetContainerReference("your container name");\n            contain.CreateIfNotExists();\n    CloudBlockBlob blob = contain.GetBlockBlobReference("your blob name");\n    using (var stream = System.IO.File.OpenRead("your file"))\n                    blob.UploadFromStream(stream);	0
14857557	14853693	Using get/set asp.net c# theres too many properties	public class Person \n{\n  Guid Id {get; set;}\n  string Name {get; set;}\n  // ad infinitum the truely unique things that relate to an Individual\n\n  Address BusinessAddress {get; set;}\n  Address HomeAddress {get; set;}\n  Person Spouse {get; set;}\n}\n\npublic class Address\n{\n  Guid Id {get; set;}\n  Line1 {get; set;}\n  // ad infinitum all the truly unique things that relate to an address\n}	0
102583	102567	How to shutdown the computer from C#	using System.Management;\n\nvoid Shutdown()\n{\n    ManagementBaseObject mboShutdown = null;\n    ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");\n    mcWin32.Get();\n\n    // You can't shutdown without security privileges\n    mcWin32.Scope.Options.EnablePrivileges = true;\n    ManagementBaseObject mboShutdownParams =\n             mcWin32.GetMethodParameters("Win32Shutdown");\n\n     // Flag 1 means we want to shut down the system. Use "2" to reboot.\n    mboShutdownParams["Flags"] = "1";\n    mboShutdownParams["Reserved"] = "0";\n    foreach (ManagementObject manObj in mcWin32.GetInstances())\n    {\n        mboShutdown = manObj.InvokeMethod("Win32Shutdown", \n                                       mboShutdownParams, null);\n    }\n}	0
27906282	27906230	Why is downloading a file failing from the server	string actualPath = Server.MapPath("~\\FileStore\\myFile.DAT");\nif (File.Exists(actualPath))	0
12758439	12758306	How to draw a filled polygon using Graphics	using (Graphics g = Graphics.FromImage(bmp))\n{\n    g.FillPolygon(fillPen, myArray);\n    g.DrawPolygon(borderPen, myArray);\n}	0
1192290	1192281	How to save unicode data to oracle?	command.Parameters.Add (":UnicodeString",\n                        OracleType.NVarChar).Value = stringToSave;	0
26960538	26960306	How can I pull quantity from a DB and multiply it to get the total	TextBox2.Text = sum;	0
22611470	22611045	How to read from an XML and display in a textbox and label in a Winform	var xDocument = XDocument.Load(@"C:\Users\..\Survey.xml");\n\nvar questionList = xDocument\n                       .Element("questions")\n                       .Elements("question")\n                       .Select(elem => new Questions\n        {\n            QuestionType = elem.Element("type").Value,\n            QuestionText = elem.Element("text").Value,\n            SplashScreenText = elem.Element("splashText").Value,\n            Choices = elem.Element("choices").Elements("choice").Select(ch =>\n                   new Choice\n                   {\n                       AnswerChoice = ch.Value\n                   }).ToArray()\n        }).ToList();	0
14243938	14237970	TVN_SELCHANGING Message in c#	private const int WM_REFLECT = 0x2000;\n\nprotected override void WndProc(ref Message m) {\n    if (m.Msg == WM_REFLECT + WM_NOTIFY) {\n        var nmhdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));\n        if (nmhdr.code == TVN_SELCHANGINGW) {\n           var notify = (NMTREEVIEW)Marshal.PtrToStructure(m.LParam, typeof(NMTREEVIEW));\n           // etc..\n        }\n    }\n    base.WndProc(ref m);\n}	0
11243560	11242375	Create a password encrypted and store it in sqlite to use in authentication	byte[] salt = Guid.NewGuid().ToByteArray[];\nRfc2898DeriveBytes saltedHash = new Rfc2898DeriveBytes("P@$$w0rd", salt, 1000);	0
1397391	779405	How do I restart my C# WinForm Application?	static void RestartApp(int pid, string applicationName )\n    {\n        // Wait for the process to terminate\n        Process process = null;\n        try\n        {\n            process = Process.GetProcessById(pid);\n            process.WaitForExit(1000);\n        }\n        catch (ArgumentException ex)\n        {\n            // ArgumentException to indicate that the \n            // process doesn't exist?   LAME!!\n        }\n        Process.Start(applicationName, "");\n    }	0
29612824	29602193	C# AES encrypt with CFB NoPadding Mode in Java	"AES/CFB8/NoPadding"	0
25431828	25429699	Convert byte array string back to a string	byte[] binaryData;\ntry {\n      binaryData = \n         System.Convert.FromBase64String(base64String);\n}\ncatch (System.ArgumentNullException) {\n      //handling error\n}\n\nstring myString = Encoding.Unicode.GetString(binaryData);	0
27793274	27778352	Get column names using aliases	var columns = new List<string>();\n                    DbCommand cmd = cnn.CreateCommand("SELECT * FROM Table1",  CommandType.Text);\n                    DataTable Dt= cnn.GetDataTable(cmd);\n                    foreach (System.Data.DataColumn col in dt.Columns)\n                    {\n                        columns.Add(col.ColumnName);\n                    }	0
16009342	16009157	Add increment index number in a collection	for (int i = 0; i < comments.Count; ++i)\n    comments[i].IndexNo = i+1;	0
32121289	32121166	Create Byte Array Refactoring	Func<int, byte[]> createByteArray = size => Enumerable.Range(0, size)\n                                            .Select(i => (byte)(i % 256))\n                                            .ToArray();	0
10252577	10252570	C# No overload method 'ToString' takes 1 arguments - simple	MessageBox.Show(Y.ToString());	0
19347724	19347449	Split xml file based on nodes	XNamespace ns="someNs3";\n\n//get all Child elements\nvar childElements=doc.Descendants().Elements(ns+"Child").ToList();\n\n//remove those child elements\ndoc.Descendants().Elements(ns+"Child").ToList().ForEach(x=>x.Remove());\n\nint i=1;\nforeach(var child in childElements)\n{\n    //add that child to children element\n    doc.Descendants().Elements(ns+"Children").First().Add(child);\n    //save it to new file!\n    doc.Save("file"+i+".xml");\n    doc.Descendants().Elements(ns+"Child").ToList().ForEach(x=>x.Remove());\n    i++;\n}	0
7787673	7787637	Searching a list of strings in C#	var listEntry = all.Where(entry => \n          string.Equals(entry, temp, StringComparison.CurrentCultureIgnoreCase))\n         .FirstOrDefault();\n\nif (listEntry != null) all.Remove(listEntry);	0
8471693	8417226	Setting child control width in Layout event handler of the FlowLayoutPanel	protected override void OnSizeChanged(EventArgs e)\n{\n  if (!DesignMode && IsHandleCreated)\n    BeginInvoke((MethodInvoker)delegate{base.OnSizeChanged(e);});\n  else\n    base.OnSizeChanged(e);\n}	0
21297334	21297268	How do I get to the main method from another method c#	public static void main()\n{\n    // do some stuff\n    // ...\n    WriteToFile(filename, obj, pos, size);\n    // ...\n    // Program execution automatically returns here after WriteToFile is done.\n    // do some more stuff\n    // ...\n    // Program ends.  Thank you for playing.\n}\n\nstatic void WriteToFile(string filename, Customer obj, int pos, int size)\n{\n    // yada yada\n    // No need for a Main() call\n    // We're done, and about to leave the WriteToFile method.  See you later.\n}	0
24921637	24921274	Modify bytes in image to add black zones left and right	public byte[] FixImage(byte[] imageData,  int bitsPerPixel)\n{\n    int bytesPerPixel = bitsPerPixel / 8;\n    List<byte> data = new List<byte>();\n    for (int i = 0; i < imageData.Length; i += 384 * bytesPerPixel)\n    {\n        data.AddRange(new byte[64*bytesPerPixel]);\n        data.AddRange(imageData.Skip(i).Take(384 * bytesPerPixel));\n        data.AddRange(new byte[64 * bytesPerPixel]);\n    }\n    return data.ToArray();\n}	0
17131129	17129181	Bind List of objects to datagridview with Fluent NHibernate - ToString override	References(x => x.Material).Column("IdMaterialu").Not.LazyLoad();\n References(x => x.Producent).Column("IdProducenta").Not.LazyLoad();	0
7552809	7513956	C# Word Interop, Pasting Clipboard into Paragraph	for (int i = 0; i < foundList.Count; i++)\n{\n    oPara[i] = oDoc.Content.Paragraphs.Add();\n    string tempS = foundList[i].Paragraph;\n    tempS = tempS.Replace("\\pard", "");\n    tempS = tempS.Replace("\\par", "");\n    Clipboard.SetText(tempS, TextDataFormat.Rtf);\n    oPara[i].Range.InsertParagraphAfter();\n    oPara[i].Range.Paste();\n    oPara[i].KeepTogether = -1;\n    oPara[i].Range.Font.Size = 10;\n    oPara[i].Range.Font.Name = "Arial";\n}	0
7041315	7041103	Force dialog close in C#	if (openFileDialog1.ShowDialog() == DialogResult.OK) {\n    // open file\n}	0
8440068	8439831	Not Parsing XML Data Correctly with Linq to XML	.Descendants("Temp")	0
2744450	2744422	How to escape forward slash?	sqlCommand.CommandText = String.Format("update [{0}] set [{1}] = @val where id = @Id",\n                                    tableName, ColumnName);\nsqlCommand.Parameters.AddWithValue("@Id", rowId);\nsqlCommand.Parameters.AddWithValue("@val", forwardSlashText);\nnumRowsAffected = sqlCommand.ExecuteNonQuery();	0
414755	414741	How Do I Pass A Method Reference to A Different Method in C#	public class EventBuilder\n{\n    private static RoutedEventHandler _buttonClickHandler;\n\n    public EventBuilder(RoutedEventHandler buttonClickHandler)\n    {\n        _buttonClickHandler = buttonClickHandler;\n    }\n\n    public static void EnableClickEvent()\n    {\n        myButton.Click += new RoutedEventHandler(_buttonClickHandler);\n    }\n}	0
27744316	27744191	Retrieving values from two tables from my Access DB and subtracting/output the result in C#	decimal incomeSum = 0m;\ndecimal expenseSum = 0m;\ntry\n{\n    .....\n    while (reader.Read())\n    {\n\n        incomeSum = Convert.ToDecimal(reader["Total income"]);\n        total_income.Text = income.ToString();\n    }                \n\n    ....\n    while (reader2.Read())\n    {\n        expenseSum = Convert.ToDecimal(reader2["Total expenses"]);\n        total_expenses.Text = expenseSum.ToString();\n    }\n}\ncatch (Exception ex)\n{\n    MessageBox.Show("Error" + ex);\n}\nbalance.Text = (incomeSum - expenseSum).ToString();	0
15091384	15090700	XNA RenderTarget2D in Windows Phone	GraphicsDevice.SetRenderTarget(textureBuffer);\n\nspriteBatch.Begin();\nspriteBatch.Draw(textureSummer, new Vector2(0, 0), Color.White); // texture Summer is a 20x20 pixels texture while the screen resolution is 480 x 800\nspriteBatch.End();\n\nGraphicsDevice.SetRenderTarget(null); // switch back \n\nspriteBatch.Begin();\nspriteBatch.Draw(textureBackground, new Vector2(0,0), Color.White); // This is a 480x800 image and my resolution is set to 480x800\nspriteBatch.Draw(textureBuffer, new Vector2(0,0), Color.White);\nspriteBatch.End();	0
7365373	6720137	How to focus on a specific cell when adding a new row to Datagrid?	dg.ItemsSource.Add(data);\ndg.SelectedItem = data;                  //set SelectedItem to the new object\ndg.ScrollIntoView(data, dg.Columns[0]);  //scroll row into view, for long lists, setting it to start with the first column\ndg.Focus();                              //required in my case because contextmenu click was not setting focus back to datagrid\ndg.BeginEdit();                          //this starts the edit, this works because we set SelectedItem above	0
8615915	8615897	How to Compare two date without timeline in C#	DateTime.Now.Date	0
24867169	24780598	Rewrite rules for localization	public class LocaleParser : IHttpModule\n{\n   public void Init(HttpApplication context)\n   {\n      context.BeginRequest += context_BeginRequest;\n   }\n\n   void context_BeginRequest(object sender, EventArgs e)\n   {\n       var req = HttpContext.Current.Request.Url.AbsoluteUri;\n       var targetUrl = req;\n\n        if (req.IndexOf('/') != -1)\n        {\n            var langparm = req.Split('/')[1].ToLower();\n\n            switch (langparm)\n            {\n                case "pt":\n                    HttpContext.Current.Items["locale"] = "PT";\n                    targetUrl = req.Substring(3);\n                    break;\n                case "en":\n                    HttpContext.Current.Items["locale"] = "EN";\n                    targetUrl = req.Substring(3);\n                    break;\n                case "es":\n                    HttpContext.Current.Items["locale"] = "ES";\n                    targetUrl = req.Substring(3);\n                    break;\n            }\n        }\n    }\n}	0
7181119	7181039	LINQ to SQL multiple commits, how should I implement transactions?	tgdd = new Data();\n context.Datas.InsertOnSubmit(tgdd);\n\n int count = 0;\n foreach (???)\n {\n      count += 1;\n      tgd = new Data2();\n      tgd.Tgdd = tgdd;\n      tgd.count = count;\n      context.Datas2.InsertOnSubmit(tgd);  //if this crashes, I want to roll\n                                           //back what happened to table 1(Datas)\n }\n\n context.SubmitChanges();	0
2042848	2042447	Highlight one column in Asp.net Chart Control Series	myChart.Series[0].Points[theColumnIndex].Color = System.Drawing.Color.Red;	0
4491748	4491679	Is it possible to wrap a C# singleton in an interface?	//Register instance at some starting point in your application\n  container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());\n\n  //This single instance can then be resolved by clients directly, but usually it\n  //will be automatically resolved as a dependency when you resolve other types. \n  IActiveSessionService session = container.Resolve<IActiveSessionService>();	0
10738717	10738501	Neatest way of preserving application settings between upgrades?	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
6001899	6001813	writing a large stream to a file in C#.Net 64K by 64K	public delegate void ProgressCallback(long position, long total);\n    public void Copy(Stream inputStream, string outputFile, ProgressCallback progressCallback)\n    {\n        using (var outputStream = File.OpenWrite(outputFile))\n        {\n            const int bufferSize = 4096;\n            while (inputStream.Position < inputStream.Length)\n            {\n                byte[] data = new byte[bufferSize];\n                int amountRead = inputStream.Read(data, 0, bufferSize);\n                outputStream.Write(data, 0, amountRead);\n\n                if (progressCallback != null)\n                    progressCallback(inputStream.Position, inputStream.Length);\n            }\n            outputStream.Flush();\n        }\n    }	0
18467482	18467203	Declare variable in one line if statement	var user = User.Current.Very.Complex.Path;\nvar email = user != null ? user.Email : "default@mail.com";	0
24079572	24079168	Binding random colors to items of listbox	public class RandomColorGenerator\n{\n  public Color randomBrush { \n\n    get {return generateRandomColor(); }\n\n}\n....	0
19075422	19075374	How do i make that the counter in the timer tick event will count 5 minutes back?	private void timer1_Tick(object sender, EventArgs e)\n    {\n        count ++;\n        countBack = 5 - count/60;\n        TimerCount.Text = TimeSpan.FromSeconds(count).ToString();\n        if(!TimerCount.Visible) TimerCount.Visible = true;\n        if (count == 300){\n            timer1.Enabled = false;\n            count = 0;\n        }\n    }	0
5716860	5716766	In C# How to dynamically specify a member of a object, like obj["abc"] in PHP	p1.GetType().GetProperty("age").GetValue(p1,null);	0
6867302	6867141	parse XML using LINQ to XML	foreach (var selected in reportDataRow.Elements("columnData").Where(a =>a.Attribute("colNum").Value == value))\n        {\n            yield return selected.Element("data").Value;\n        }	0
15124187	15123924	How to retrieve a substring based on a first list match	string val1 = (sample.Split(',').FirstOrDefault(w => myList.Any(m => w.Contains(m))) ?? string.Empty).Trim();	0
2236206	2236189	how to get path of the file to be deleted from the server	string fileName = Server.MapPath(@"/Template/copy.jpg");	0
14517497	14511734	Can I register all IoC container components in single layer, or each layer where used?	container.RegisterType<ISercice1, MyImplementation1>(new PerThreadLifetime())	0
24187967	24171360	StarterSite Password reset page modification not going well	var db = Database.Open("StarterSite");\n        var sqlquery = "SELECT Courriel FROM UserProfile WHERE UserId = @0";\n        Courriel = db.QueryValue(sqlquery,WebSecurity.GetUserId(email));	0
1733363	1733355	Dynamic control and its Event	ImageButton imbtnAdd = new ImageButton();\nimbtnAdd.ID = "imbtn" + columnName;\nimbtnAdd.ImageUrl = "btn_add_icon.gif";\nimbtnAdd.Width = 20;             \n\nimbtnAdd.Click += imbtnAdd_Click;\n\ncontainer.Controls.Add(imbtnAdd);\n\n// ...\n\nprivate void imbtnAdd_Click(object sender, EventArgs e)\n{\n    // handle event\n}	0
29572433	29572374	C# Define local variable with an linq enumeration	List<object> listData = new List<object>();\nList<EmployeeAdvanced> workDataList = GetEmployeeWorkAdvancedData();\nList<EmployeeBasic> employeeList = GetEmployeeBasicData();\n\nlistData .AddRange(\n          from employee in employeeList\n          where employee.SomeNumber  > 0\n          let workData = workDataList.FirstOrDefault(x=> x.ID==employee.EmployeeID)\n             select new{\n             ID = employee.ID,\n             SSN = employee.SSN\n             StreetAddress = workData.Address,\n             Zipcode = workData.Zipcode}\n);	0
26786304	26785964	Regular expression for number between fix set of strings c#	number_of_records~\^~(\d+)\|\^\|	0
6499842	6499799	How can I convert datatype for argument passed into Thread in C#	MyFunction (object arg) {\n    if (arg is Type1) { ProcessType1(arg as Type1); }\n\n    else if (arg is Type2) { ProcessType2(arg as Type2); }\n\n    else if (arg is Type3) { ProcessType3(arg as Type3); }\n}	0
23920543	23919727	sum of gridview column, skipping duplicates	int sumOfValues = 0;\nList<string> addedInvoiceNumbers = new List<string>();\nforeach (DataRow dr in rows)\n{\n   //if row is selected and the list doesn't contain the InvoiceNumber\n   if (dr[0] == true && !addedInvoiceNumbers.Contains(dr[2]))\n   {\n      sumOfValues += dr[3];\n      addedInvoiceNumbers.Add(dr[2]);\n   }\n}	0
20086591	20086541	print with incremental order all combinations of string without repetition	foreach (string s in combinations.OrderBy(str => str.Length))\n{\n    Console.WriteLine(s);\n}	0
713105	713057	convert bool[] to byte[] C#	bool[] bools = { true, false, true, false, false, true, false, true,\n                     true };\n\n    // basic - same count\n    byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);\n\n    // pack (in this case, using the first bool as the lsb - if you want\n    // the first bool as the msb, reverse things ;-p)\n    int bytes = bools.Length / 8;\n    if ((bools.Length % 8) != 0) bytes++;\n    byte[] arr2 = new byte[bytes];\n    int bitIndex = 0, byteIndex = 0;\n    for (int i = 0; i < bools.Length; i++)\n    {\n        if (bools[i])\n        {\n            arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);\n        }\n        bitIndex++;\n        if (bitIndex == 8)\n        {\n            bitIndex = 0;\n            byteIndex++;\n        }\n    }	0
8997868	8997838	Understanding working of Timer control in C#	System.Timers.Timer	0
727304	726745	How to get NHibernate SchemaExport to create SQL Server Timestamp columns?	DECLARE @sql nvarchar(255)\nDECLARE @sql2 nvarchar(255)\nWHILE EXISTS\n(\n    select 1 from INFORMATION_SCHEMA.COLUMNS \n    where COLUMN_NAME = 'Timestamp'\n    and DATA_TYPE = 'varbinary'\n)\nBEGIN\n    select  @sql = 'ALTER TABLE [' + table_name + '] DROP COLUMN [Timestamp]',\n    @sql2 = 'ALTER TABLE [' + table_name + '] ADD [Timestamp] timestamp not null'\n    from    INFORMATION_SCHEMA.COLUMNS \n    whereCOLUMN_NAME = 'Timestamp'\n    andDATA_TYPE = 'varbinary'\n    exec    sp_executesql @sql\n    exec    sp_executesql @sql2\nEND\nGO	0
21972501	21972357	Create an event handler for control created programmatically	TextBox specRegionText = new TextBox();\nRadioButton specRegionRadio = new RadioButton();\nspecRegionRadio.Checked += (s,e) => specRegionText.IsEnabled = true;\nspecRegionRadio.Unchecked += (s,e) => specRegionText.IsEnabled = false;	0
22837344	22836311	jQuery - how to properly show all records between two dates?	var now = new Date(); // today\nvar nowMS = now.getTime(); // get # milliseconds for today\nvar week = 1000*60*60*24*7; // milliseconds in one week\nvar oneWeekFromNow = new Date(nowMS + week);	0
30466083	30465792	How to convert string with a T and Z to DateTime	var dateString = "20150521T205510Z";\n\nvar date = DateTime.ParseExact(dateString,\n                   "yyyyMMdd'T'HHmmss'Z'",\n                   CultureInfo.InvariantCulture);	0
20785647	20785502	C# generating random double number range	public static class RandomExtensions\n{\n    public static double NextDouble(this Random RandGenerator, double MinValue, double MaxValue)\n    {\n        return RandGenerator.NextDouble() * (MaxValue - MinValue) + MinValue;\n    }\n}	0
4185445	4185408	Convert object to byte array in c#	int i = 2200;\nbyte[] bytes = BitConverter.GetBytes(i);\nConsole.WriteLine(bytes[0].ToString("x"));\nConsole.WriteLine(bytes[1].ToString("x"));	0
31750550	31750177	How to delete extra added lines in a regex statement	(?:(?:"([^"}]*)")|(\w+))\s*:\s*(?:(?:"([^"}]*)")|(\w+))	0
9317238	9181523	Need a way to have front end wait for a lengthy process to finish without stopping system message flow	try {\n    WaitHandle handle = BackgroundProcess.BeginStart();\n    if ( !handle.WaitOne( Timeout ) ) {\n        . . .\n       return false;\n    }\n\n    List<WaitHandle> waitHandles = new List<WaitHandle>();\n    foreach ( Module module in BackgroundProcess.Transit.SubModules ) {\n        WaitHandle waitHandle = module.GetWaitHandleForState( Module.States.Running );\n        waitHandles.Add( waitHandle );\n    }\n\n    if ( !WaitHandle.WaitAll( waitHandles.ToArray(), Timeout ) ) {\n        . . . \n        return false;\n    }\n\n    // If we get here, everything is communicating properly.\n    . . .\n\n} catch ( Exception ex ) {\n    . . .\n    return false;\n}\n\nreturn true;	0
31387764	31387659	Get a value back from the MVC view outside of the model	Session["email"] = email;	0
26954854	26951562	How to move the player to a specific point in a 2D Unity Game	Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);\nfloat targetX = 100; // replace it with your value\nfloat targetY = 100; // replace it with your value\nif (screenPosition.y > Screen.height || screenPosition.y < 0)\n{\n     transform.position = Camera.main.ScreenToWorldPoint(new Vector3(targetX, targetY, camera.nearClipPlane));\n}	0
30341056	30339948	Setting an XML attribute in the model	[XmlRoot("finPOWERConnect")]\npublic class ApplicationData\n{\n    [XmlElement("finAccount")]\n    public List<Account> Accounts {get; set; }\n}\n\n[XmlRoot("finAccount")]\npublic class Account\n{\n    [XmlAttribute("version")]\n    public string Version { get; set; } \n    //Account stuff\n}\n???	0
2968217	2967911	How to keep ComboBox from scrolling? C#	combobox.MouseWheel += new MouseEventHandler(combobox_MouseWheel);\n\nvoid combobox_MouseWheel(object sender, MouseEventArgs e)\n{\n    ((HandledMouseEventArgs)e).Handled = true;\n}	0
23380667	23374469	EF 6 - How to solve foreign key error for composite key?	public class SampleContext : DbContext\n    {\n        public IDbSet<Category> Categories { get; set; }\n        public IDbSet<Product> Products { get; set; }\n        protected override void OnModelCreating(DbModelBuilder modelBuilder)\n        {\n             base.OnModelCreating(modelBuilder);\n        }\n    }\n    public class Category\n    {\n        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]\n        public int CategoryId { get; set; }\n        [Key, Column(Order = 1)]\n        public int ShopId { get; set; }\n        public string Name { get; set; }\n    }\n    public class Product \n    {\n        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]\n        public int ProductId { get; set; }\n        public int ShopId { get; set; }\n        public int CategoryId { get; set; }\n        [ForeignKey("CategoryId, ShopId")]\n        public virtual Category Category { get; set; }\n    }	0
1700708	1700695	Getting output from one executable in an other one	Process myApp = new Process(@"C:\some\dirs\foo.exe", "someargs");\nmyApp.StartInfo.UseShellExecute = false;\nmyApp.StartInfo.RedirectStandardOutput = false;\n\nmyApp.Start();\n\nstring output = myApp.StandardOutput.ReadToEnd();\np.WaitForExit();	0
3193321	3193312	IEnumerable without data	Enumerable.Empty<T>()	0
33790008	33789574	Entity Framework One to Many Relations ship Fluent API with composite keys	public class PatientClientPhysicianConfiguration : \n    EntityConfigurationBase<PatientClientPhysician>\n{\n    public PatientClientPhysicianConfiguration()\n    {\n        ToTable("patientclientphysician");\n\n        // Composite key:\n        HasKey(t => new { t.ClientId, t.PatientId, t.PhysicianId });\n\n        Property(m => m.ClientId).HasColumnName("clientid");\n        Property(m => m.PatientId).HasColumnName("patientid");\n        Property(m => m.PhysicianId).HasColumnName("physicianid");\n\n        HasRequired(m => m.Patient).WithMany().HasForeignKey(p => p.PatientId);\n        HasRequired(m => m.Client).WithMany().HasForeignKey(c => c.ClientId);\n        HasRequired(m => m.Physician).WithMany().HasForeignKey(p => p.PhysicianId);\n    }\n}	0
22759740	22759524	Gridview change row BackColor programmatically through a checkbox	private void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)\n{\n    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)\n    {\n        // Handle your checkbox state change here\n    }\n}	0
28363865	28363402	How to register an inheriting service with constructor parameters?	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        object parameter = new object();\n        ServiceLocator.Default.\n            RegisterInstance<INthChildService>(new NthChildService(parameter));\n    }\n}	0
17667561	17664472	Transform a list with legacy data to a new list using Linq	var result=lista.SelectMany(\n    a=>Regex.Split(x.Name,"#;\d+#;"),(a,b)=>new {id=a.id,name=b});	0
8722976	8722940	c# - Use alias in another file	The scope of a using directive is limited to the file in which it appears.	0
32256216	32256138	Clear C# String from memory	// do stuff with the string	0
16170339	16170290	C# Performance penalty for Int32 literals to floats	.method private hidebysig static \n    void Main (\n        string[] args\n    ) cil managed \n{\n    // Method begins at RVA 0x2050\n    // Code size 8 (0x8)\n    .maxstack 1\n    .entrypoint\n    .locals init (\n        [0] float32 x\n    )\n\n    IL_0000: nop\n    IL_0001: ldc.r4 44\n    IL_0006: stloc.0\n    IL_0007: ret\n} // end of method Program::Main	0
12076344	12076281	Retrieving item from List collection when each index have a set of items	var hint = QHintList[0].Hint;\nConsole.WriteLine(hint);	0
4887390	4886239	Problem setting BlindCopyTo ItemValue in Lotus Notes	IList<string> receiverList = GetReceiver();\ndocument.ReplaceItemValue( "BlindCopyTo", receiverList.ToArray<string>() );	0
16345861	16345133	C# WPF Change Resource On Click	XmlDataProvider provider = (XmlDataProvider) this.FindResource("rssSource");\n       provider.Source = new Uri("CHANGE WITH TEXTBOX VALUE");	0
17392807	17392737	Scan for key press in Console without pausing it	Console.CursorVisible = false;\n while(true)\n {\n       game g = new game();\n       g.Draw(cHP, mHP, name,posX,posY,blip);\n       Thread.Sleep(50); //might not be required depending\n                         //on what you want to do\n\n       var cki = Console.ReadKey(true);\n       if (cki.KeyChar == 'w') MoveY(1);// Here it is\n       if (cki.KeyChar == 's') MoveY(-1); // and here\n }	0
15660388	15660276	How can I change border style in a panel?	string selectedStyle = DropDownList1.SelectedItem.ToString();\n\nif (selectedStyle == "Dotted")\n{\n    Panel1.BorderStyle = System.Web.UI.WebControls.BorderStyle.Dotted;\n}\nelse if (selectedStyle == "Solid")\n{\n    Panel1.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;\n}\n// and so on ...	0
30393190	30393079	Converting Json.Net JValue to int	int storedValue = myJValue.ToObject<int>();	0
8587896	8587872	How to get only specific field from the list	filteredLessons.Select(l => l.lessonId).ToList();	0
24787330	24786746	Javascript from C# code behind only refreshes in Google Chrome	window.location.href	0
19053593	19053430	Datatable - Sum Each Cell In a Row	table.Columns.Add("Total", typeof(decimal));\nforeach (DataRow row in table.Rows)\n{\n    decimal rowSum = 0;\n    foreach (DataColumn col in table.Columns)\n    {\n        if(!row.IsNull(col))\n        {\n            string stringValue = row[col].ToString();\n            decimal d;\n            if(decimal.TryParse(stringValue, out d))\n                rowSum += d;\n        }\n    }\n    row.SetField("Total", rowSum);\n}	0
15184652	15184614	Getting the asp image url using a function from another CS	public static class GeneralHelper\n{\n  public static string GetImagePath(string imgName)\n  {\n    string Finalurl = "~/App_Themes/Default/Images/" + imgName;\n    return Finalurl;\n  }\n}	0
2654040	2653993	How to access data from multiple tables	var q = from u in db.user\n        from e in db.employee\n        where u.Name == "smith" && e.company == "xyz"\n        select new\n        {\n           User = u,\n           Employee = e\n        };	0
23299732	23295872	WPF Listbox style	InterfacesView view = CollectionViewSource.GetDefaultView(Interfaces);\n    view.GroupDescriptions.Add(new PropertyGroupDescription("Name"));\n    view.SortDescriptions.Add(new SortDescription("Name",ListSortDirection.Ascending));	0
16903003	16901849	How to increase download speed of the file from web-sites?	request.AddRange	0
13095581	13095425	How to convert object that contains a member variable that is an array to an array of objects?	class ObjectWithArray\n{\n    int iSomeValue;\n    SubObject[] arrSubs;\n\n    ObjectWithArray(){} //whatever you do for constructor\n\n\n    public ObjectWithoutArray[] toNoArray(){\n        ObjectWithoutArray[] retVal = new ObjectWithoutArray[arrSubs.length];\n\n        for(int i = 0; i < arrSubs.length;  i++){\n          retVal[i] = new ObjectWithoutArray(this.iSomeValue, arrSubs[i]);\n        }\n\n       return retVal;\n    }\n}\n\nclass ObjectWithoutArray\n{\n    int iSomeValue;\n    SubObject sub;\n\n    public ObjectWithoutArray(int iSomeValue, SubObject sub){\n       this.iSomeValue = iSomeValue;\n       this.sub = sub;\n    }\n}	0
5079266	5079221	How to Convert this string "Tue Feb 22 00:00:00 UTC+0200 2011" to a DateTime?	var dateTimeObject = DateTime.ParseExact("Tue Feb 22 00:00:00 UTC+0200 2011", "ddd MMM d HH:mm:ss UTCzzzzz yyyy", CultureInfo.InvariantCulture);	0
10523599	10523544	Dynamically creating controls based on variable	GridView myGV = (GridView)FindControl(myGVstr)	0
31208113	31207672	Define DesignWidth with a constant in a XAML file	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n  xmlns:constants="clr-namespace:app.Constants"\n  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"\n  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"\n  mc:Ignorable="d"\n  d:DesignWidth="{Binding Source={x:Static constants:Constants.ApplicationWidth}}">	0
24469261	24440717	Setting session variable causes slowness in FileContentResult rendering in MVC	[SessionState(SessionStateBehavior.Disabled)]	0
12429600	11534574	Using an list in a query in entity framework	public static List<Tag> fillUsed(List<int> docIds = null)\n        {\n            List<Tag> used = new List<Tag>();\n\n            if (docIds == null || docIds.Count() < 1)\n            {\n                used = (from t in frmFocus._context.Tags\n                        where t.Documents.Count >= 1\n                        select t).ToList();  \n            }\n            else\n            {    \n                used = (from t in frmFocus._context.Tags\n                        where t.Documents.Any(d => docIds.Contains(d.id))\n                        select t).ToList();  \n            }\n            return used;\n        }	0
19875132	19866570	How do I encrypt user.settings	System.Configuration.Configuration config =\n                ConfigurationManager.OpenExeConfiguration(\n                ConfigurationUserLevel.PerUserRoamingAndLocal);\n\nConfigurationSection connStrings = config.GetSection("userSettings/Progname.Properties.Settings");\n\nconnStrings.SectionInformation.ProtectSection(provider);	0
4357717	4357707	Remove time from a date/time string	DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);\nString.Format("{0:MM/dd/yy}", dt);	0
23998745	15769414	Configure log4net logging in dll	if (!log4net.LogManager.GetRepository().Configured)\n{\n    // my DLL is referenced by web service applications to log SOAP requests before\n    // execution is passed to the web method itself, so I load the log4net.config\n    // file that resides in the web application root folder\n    var configFileDirectory = (new DirectoryInfo(TraceExtension.AssemblyDirectory)).Parent; // not the bin folder but up one level\n    var configFile = new FileInfo(configFileDirectory.FullName + "\\log4net.config");\n\n    if (!configFile.Exists)\n    {\n        throw new FileLoadException(String.Format("The configuration file {0} does not exist", configFile));\n    }\n\n    log4net.Config.XmlConfigurator.Configure(configFile);\n}	0
10641230	10481063	How can I get a thumbnail from a movie without playback starting Monotouch	NSUrl data = new NSUrl(info.ObjectForKey(new NSString("UIImagePickerControllerMediaURL")).ToString());\n\n//get the video thumbnail\nMPMoviePlayerController movie = new MPMoviePlayerController(data);\nmovie.ShouldAutoplay = false;\nUIImage videoThumbnail = movie.ThumbnailImageAt(0.0, MPMovieTimeOption.NearestKeyFrame);	0
16530423	16529998	whats wrong in this logic of finding longest common child of string	String.ToUpper	0
26829786	26829576	How to iterate through a list and while iterating, iterate through another list and replace values for upper list with inner list key value pairs	lstCrawlUrls = lstCrawlUrls.Select(pr => lstReplaceWordsFromUrls.Aggregate(pr, (str, mr) =>( str.Replace(mr.Key, mr.Value); )));	0
30939099	30909079	Windows Phone 8.1 get image from base64 string	var imageBytes = Convert.FromBase64String(base64String);\nusing (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())\n{\n    using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))\n    {\n        writer.WriteBytes((byte[])imageBytes);\n        writer.StoreAsync().GetResults();\n    }\n\n    var image = new BitmapImage();\n    image.SetSource(ms);\n}	0
7918249	7918217	LINQ/Lambda equivalent of SQL in	var movieratings = new int[] {1, 2, 7, 8, 9, 10, 11};\nlist.ratings = list.ratings.Where(x => movieratings.Contains(x.Value));	0
31397052	31395247	Convert string containing a date in multiple formats to a string containing a date in the "CCYYMMDD" format	var inputDate = "4/28/2006 12:39:32:429AM";\n\n        //1 - parse into date parts\n        char[] delimiterChars = { '/' };\n\n        string[] dateParts = inputDate.Split(delimiterChars);\n        var month = int.Parse(dateParts[0].ToString());\n        var day = int.Parse(dateParts[1].ToString()); \n        var year = 0;\n\n        string yearString = dateParts[2].ToString();\n\n        //strip of the time for the year part\n        if (yearString.Length > 5)\n            year = int.Parse(yearString.Substring(0, 4));\n\n        //2 - Create date object\n        DateTime testDate = new DateTime(year, month, day);\n\n        //3 - format date\n        var outputDate = testDate.ToString("yyyyMMdd");\n\n        Console.WriteLine("Input date: " + inputDate);\n        Console.WriteLine("Output date: " + outputDate);\n\n        Console.ReadLine();	0
14687758	14687508	What information can we access from current logged in user MVC4	Request.UserHostAddress	0
15535693	15535498	Loop through XML Nodes	List<Ticket> supportTickets = \n    (from x in doc.Descendants("ticket")\n     select new Ticket\n     {\n         ID = x.Element("id").Value,\n         TicketID = x.Element("tid").Value,\n         DeptID = x.Element("deptid").Value,\n         UserID = x.Element("userid").Value,\n         Name = x.Element("name").Value,\n         Email = x.Element("email").Value,\n         Subject = x.Element("subject").Value,\n         Message = x.Element("message").Value,\n     }).ToList();	0
2655496	2655485	Why would you have multiple databindings to a WinForms control?	TextBox1.DataBindings.Add("Enabled", myPresentationModel, "IsTextBox1Enabled");	0
25045311	25045251	How can I return text from a form to a textbox C#?	((TextBox)sender).Text = ...	0
18387732	18386443	Pass C# Variables to Powershell Engine	string mailbox = _mailBoxTextBox.Text;\n...\npowershell.AddParameter("Mailbox", mailbox);	0
28320396	28318128	Trying to display a list property in XtraReport	public class StringData {\n    public String S {get; set;}\n}	0
4511876	4511829	C# DateTimePicker Max Date range	System.Globalization.CultureInfo.DateTimeFormat.Calendar.MaxSupportedDateTime	0
16183277	16183220	How to save XML node values to string parameters	var stream = context.Request.InputStream;\nbyte[] buffer = new byte[stream.Length];\nstream.Read(buffer, 0, buffer.Length);\nXDocument doc = XDocument.Parse(Encoding.UTF8.GetString(buffer));\nvar tradeNo = doc.Descendants("trade_no").FirstOrDefault().Value;\nvar outTradeNo = doc.Descendants("out_trade_no").FirstOrDefault().Value;	0
16930423	16930263	Wrap text between two asterisks in HTML *bold*	var str = "This is my string and *this text* should be wrapped with";\n\nvar updatedstr = String.Concat(\n          Regex.Split(str, @"\*")\n          .Select((p, i) => i % 2 == 0 ?  p : \n               string.Concat("<strong>", p, "</strong>"))\n          .ToArray()\n );	0
29494870	29494829	Unable to convert object to double	avgGPA = value == DBNull.Value ? 0D : Convert.ToDouble(value);	0
11678481	11677813	Find UTC Time for ALL USA TimeZone for below Times using C#.net	DateTime.UtcNow.Hour	0
7792288	7792240	Calling a STATIC METHOD in C#	static void GetLocationFromIP()\n{\n    string strIPAddress = Request.UserHostAddress.ToString();\n    strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];\n\n    if (strIPAddress == null || strIPAddress == "")\n    {\n        strIPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();\n    }\n\n    string city = string.Empty;\n    string region = string.Empty;\n    string country = string.Empty;\n    double latitude = -1.00;\n    double longitude = -1.00;\n\n    LocationTools.GetLocationFromIP(strIPAddress, out city, out region, out country, out latitude, out longitude)\n}	0
21530189	21529596	NHibernate Performance	ISession session = sessionFactory.OpenSession();\nITransaction tx = session.BeginTransaction();\n\nstring hqlDelete = "delete ObjectA a where a.property = :someValue";\n\nint deleteddEntities = s.CreateQuery( hqlDelete )\n   .SetString( "someValue", someValue)\n   .ExecuteUpdate();\n\ntx.Commit();\nsession.Close();	0
13321145	13320985	still Not able to Hide Horizontal Scrollbar of FlowLayoutPanel in WinForms Apps	int vertScrollWidth = SystemInformation.VerticalScrollBarWidth;\n\npannel.Padding = new Padding(0, 0, vertScrollWidth, 0);	0
19485346	19456891	How can I map tables using fluent api in asp.net MVC5 EF6?	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{   \n    base.OnModelCreating(modelBuilder); // <-- This is the important part!\n    modelBuilder.Configurations.Add(new EngineeringDesignMap());\n    modelBuilder.Configurations.Add(new EngineeringProjectMap());\n}	0
23164454	23164265	foreach loop not starting console output at expected value	Console.BufferHeight = 9999;\n\n...\n\n// now you'll be able to scroll up and see all your numbers\nforeach (var item in lister)\n{\n    Console.WriteLine(item);\n}	0
10293991	10293227	How can I generate a JavaScript object literal in C#?	Product product = new Product();\nproduct.Name = "Apple";\nproduct.Expiry = new DateTime(2008, 12, 28);\nproduct.Price = 3.99M;\nproduct.Sizes = new string[] { "Small", "Medium", "Large" };\n\nstring json = JsonConvert.SerializeObject(product);\n//{\n//  "Name": "Apple",\n//  "Expiry": new Date(1230422400000),\n//  "Price": 3.99,\n//  "Sizes": [\n//    "Small",\n//    "Medium",\n//    "Large"\n//  ]\n//}\n\nProduct deserializedProduct = JsonConvert.DeserializeObject<Product>(json);	0
4817916	4817518	how to only query newest version?	var maxQuery = \n from rh in MailSort\n group rh by rh.BarCode into latest\n select new { BarCode = latest.Key, MaxVersion = latest.Max(l => l.Version) }\n;\n\nvar query = \n from rh2 in MailSort\n join max in maxQuery on new {rh2.BarCode, Version = rh2.Version } \n  equals new { max.BarCode, Version = max.MaxVersion }\n select new { rh2.BarCode, rh2.Version, rh2.AppCode }\n;\n\nvar barCodes = query.ToList();	0
23725823	23725811	Kick off N Number of Asynchronous methods	await Task.WhenAll(packages.Select(_myService.AddCars))	0
13263703	13248829	equivalent frame in windows application and navigate from page to another page?	private void button_Click(object sender, EventArgs e)\nusercontol1 user=new usercontrol1();\npanel.controls.clear();\npanel.controls.add(user);	0
31438474	31426175	How to increase pivot header height in UWP?	private void Page_Loaded(object sender, RoutedEventArgs e)\n{\n    foreach (PivotHeaderItem phItem in FindVisualChildren<PivotHeaderItem(mainPivot))\n     {\n         phItem.Height = 110;\n    }\n}\n\n//Find all children\npublic static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject\n{\n    if (depObj != null)\n    {\n        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)\n        {\n            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);\n            if (child != null && child is T)\n            {\n                yield return (T)child;\n            }\n\n            foreach (T childOfChild in FindVisualChildren<T>(child))\n            {\n                yield return childOfChild;\n            }\n        }\n    }\n}	0
3189064	3188959	Pattern for using IEnumerator<T> in interfaces	IEnumerator<T>	0
9344778	9344726	c# using excel file from embedded resource	xlApp.Workbooks.Open(fileName);	0
15562314	15558463	Properly Update an XmlNode within an XmlDocument	XmlDocument doc = new XmlDocument();\ndoc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +\n           "<title>Pride And Prejudice</title>" +\n           "</book>");\n\nstring xPath = "/book/title";\nXmlNode node = doc.SelectSingleNode(xPath);\nnode.InnerText = "new title";\nConsole.WriteLine(doc.OuterXml); //it's changed	0
16193014	16192964	How to load values into Dictionary using { }	Dictionary<byte, byte> dict = new Dictionary<byte, byte>() { { 1, 1 }, { 2, 2 } };	0
23615888	23615873	foreach can not get an enumerator of a struct element	foreach (sorular s in soru) {\n    var i = s.dogrucevap;\n    ...\n}	0
19304642	19304327	Add to a readonly collection in a constructor?	var node = new Node\n {\n     Children =\n    {\n        new Node(),\n        new Node()\n    }\n };	0
9594589	9594582	How do I remove all objects in a List<string> on Windows Phone 7 Silverlight C#?	myList.Clear()	0
12133740	11192963	Adding Comments to Parameter in DLL	/// <summary>\n/// This method does something.\n/// </summary>\n/// <param name="zain">Zain to be processed.</param>\n/// <returns>True if it went okay, false otherwise.</returns>	0
34418029	34417158	Find Window By Caption what is the caption of the window?	[DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern int GetWindowTextLength(IntPtr hWnd);\n    [DllImport("user32.dll")]\n    private static extern bool IsWindowVisible(IntPtr hWnd);	0
5114190	5113982	Is there a generic method to iterate and print a values in an unknown collection?	static void Print<T>(IEnumerable<T> items)\n{\n    var props = typeof(T).GetProperties();\n\n    foreach (var prop in props)\n    {\n        Console.Write("{0}\t", prop.Name);\n    }\n    Console.WriteLine();\n\n    foreach (var item in items)\n    { \n        foreach (var prop in props)\n        {\n            Console.Write("{0}\t", prop.GetValue(item, null));\n        }\n        Console.WriteLine();\n    }\n}	0
18777586	18656908	Timezone issue with UIDatePicker Date: 1 Hour Wrong	DateTime.SpecifyKind(datePicker.Date, DateTimeKind.Utc).ToLocalTime();	0
34476015	34475990	How can i write to a text file while replacing number on same line?	postsCounter += 1;\nlabel2.Text = postsCounter.ToString();\nlabel2.Visible = true;\nSystem.IO.File.WriteAllText(filePath, postsCounter.ToString());	0
639210	639156	Make svcutil pick up documentation from C# files?	[DescriptionAttribute]	0
30578133	30575472	Custom Control check if resizing is started	private bool userResizing = false;\n\nprotected override void WndProc(ref Message m) {\n  const int wmNcHitTest = 0x84;\n  const int htBottomLeft = 16;\n  const int htBottomRight = 17;\n  const int WM_EXITSIZEMOVE = 0x232;\n  const int WM_NCLBUTTONDWN = 0xA1;\n\n  if (m.Msg == WM_NCLBUTTONDWN) {\n    if (!userResizing) {\n      userResizing = true;\n      Console.WriteLine("Start Resizing");\n    }\n  } else if (m.Msg == WM_EXITSIZEMOVE) {\n    if (userResizing) {\n      userResizing = false;\n      Console.WriteLine("Finish Resizing");\n    }\n  } else if (m.Msg == wmNcHitTest) {\n    int x = (int)(m.LParam.ToInt64() & 0xFFFF);\n    int y = (int)((m.LParam.ToInt64() & 0xFFFF0000) >> 16);\n    Point pt = PointToClient(new Point(x, y));\n    Size clientSize = ClientSize;\n    if (pt.X >= clientSize.Width - 16 && \n        pt.Y >= clientSize.Height - 16 &&\n        clientSize.Height >= 16) {\n      m.Result = (IntPtr)(IsMirrored ? htBottomLeft : htBottomRight);\n      return;\n    }\n  }\n  base.WndProc(ref m);\n}	0
19011892	19011527	Retaining enum values in asp.net	public UrlType UrlPattern\n{\n    get\n    {\n        if (ViewState["UrlPattern"] != null)\n            return (UrlType)Enum.Parse(typeof(UrlType), ViewState["UrlPattern"].ToString());\n        return UrlType.Normal; // Default value\n    }\n    set\n    {\n        ViewState["UrlPattern"] = value;\n    }\n}	0
7820656	7820470	How to send notifications or messages on website or to fellow website moderators using c sharp and asp.net?	ID (guid or identity)\nTITLE (text)\nTEXT (text)\nTYPE (bit, 0=announcement 1=message)\nFROM (foreign key to USERS)	0
19105486	19105306	Stored Value in Checkbox and Capture Submitted Values Checked	foreach (Checkbox cb in YOurcheckboxlist)\n {\n      if (cb.Checked) {\n// get the name and insert\n}\n }	0
3606970	3606918	how can i get value of the selected index on double click of the listview of winform?	private void listView1_DoubleClick (object sender, EventArgs e) {\n    if (listView1.SelectedIndices.Count > 0)\n        MessageBox.Show ("Selected Index is " + listView1.SelectedIndices[0]);\n    else\n        MessageBox.Show ("No item selected");\n}	0
2228210	2228029	Disable certain nodes of a tree control	void TreeView_BeforeCheck(object sender, TreeViewCancelEventArgs e)\n{\n    var IsReadOnly = e.Node.Tag as bool?;\n\n    if (IsReadOnly != null)\n    {\n        e.Cancel = IsReadOnly.Value;\n    }\n}	0
16571936	16571821	Specify separate web applications within same solution - Visual Studio 2012	- SOLUTION\n+- Root\n+- Application 1\n+- Application 2	0
17976732	17976694	not all paths return a value in anonymous method	.TakeWhile (x => {\n        foreach (var i in seq){\n            if (i < x/2){\n                if (isAbundant (x - i))\n                    return false;\n                else\n                    return true;\n            }\n        }\n\n        // If there are no elements in seq, you'll reach here, and never return a value!\n        // Add something here, ie:\n        return false;\n    })	0
2205631	2205587	How to call unmanaged c++ function that allocates output buffer to return data in c#?	[StructLayout(LayoutKind.Sequential)]\npublic struct PARAMETER_DATA\n{        \n    public IntPtr data;   // tried also SizeParamIndex = 1 instead of SizeConst\n\n    [MarshalAs(UnmanagedType.I4)]                      \n    public int size;\n}\n\n[DllImport("thedll.dll", SetLastError = true, ExactSpelling = true)]\nprivate extern static uint GetParameters(ref PARAMETER_DATA outputData);\n\npublic static uint GetParameters(out String result)\n{\n    PARAMETER_DATA outputData = new PARAMETER_DATA();\n    result= Marshal.PtrToStringAnsi(outputData.data, outputData.size );\n    Marshal.FreeHGlobal(outputData.data); // not sure about this\n}	0
11548776	11548416	Calling SubmitChanges() in LINQ-to-SQL from multiple threads	public static void ProcessingStarted(int messageId)\n{\n    using (DataContext dc = new DataContext())\n    {\n        var update = dc.QueuedMessages.SingleOrDefault(m => m.Id == messageId);\n        if (update != null)\n        {\n            update.ProcessingStarted = true;\n            dc.SubmitChanges();\n        }\n    }\n}	0
10686754	10681976	wrap text in Tab control	With TabControl1\n        'Increase the size of the tabs\n        .ItemSize = New Size(.ItemSize.Width, .ItemSize.Height * 2)\n\n        'Put two lines of text on the first tab\n        .TabPages(0).Text = "Foo" + Convert.ToChar(13) + "Bar"\n\n    End With	0
5574225	5574142	Blow dictionary out to a list	dictionary\n  .SelectMany(pair => Enumerable.Repeat((double)pair.Key, pair.Value))\n  .OrderByDescending(x => x)\n  .ToList();	0
17688814	17688003	The number of elements in ICollection is zero in many-to-many relationship	public ICollection<Advertisment> favouriteAdvertismentsByUser(int UserID)\n{\n    GetHiredDBContext db = new GetHiredDBContext();\n\n    // First of all, you probably forgot to "include" FavouriteAdvertisments\n    var users = db.Users.Include(u => u.FavouriteAdvertisments);\n\n    // Second of all, use linq!\n    return users.SingleOrDefault(u => u.UserID == UserID).FavouriteAdvertisments;\n}	0
32224559	32224506	Copying Members from class list to string list in C#	public class Country {\n    public string Id {get; set;}\n    public string Name {get; set;}\n}\n\n// In using method ...\n{\n    List<Country> list1 = // assign countries\n\n    // Either \n    List<string> list2 = new List<string>();\n    list1.Select(c => c.name).ForEach(list2.Add);\n\n    // OR\n    var list2 = list1.Select(c => c.name).ToList();\n}	0
5050141	5050102	convert datetime to date format dd/mm/yyyy	DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);\n\nstring s = dt.ToString("dd/M/yyyy");	0
15910453	15907963	Autocomplete: Asynchronous population with WCF using threads	RxProperty = Observable.FromEvent<TextChangedEventHandler, TextChangedEventArgs>(\n        h => new TextChangedEventHandler(h),\n        h => AssociatedObject.TextChanged += h,\n        h => AssociatedObject.TextChanged -= h)\n\n        .Select(t => ((TextBox)t.Sender).Text)\n\n        .Throttle(TimeSpan.FromMilliseconds(400))\n\n        .SubscribeOnDispatcher()\n        .Take(10)\n        .TakeUntil(AssociatedObject.TextChanged );	0
8502526	8502399	how to change the values of label in listview from codebehind?	protected void LVP_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n    if (e.Item.ItemType == ListViewItemType.DataItem)\n    {\n        Label EmpIDLabel = (Label)e.Item.FindControl("EmpIDLabel");\n\n        System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;\n        EmpIDLabel.Text = rowView["EmpID"].ToString();\n    }\n}	0
12748839	12748641	Inserting Related Records into Database via Entity Framework	private IList<ProductImage> productImages_;\npublic virtual IList<ProductImage> ProductImages {\n   get {\n     return productImages_ ?? (productImages_= new List<ProductImage>());\n   }\n   set { productImages_ = value;}\n}	0
16426013	16423795	Json.net deserialization array of interfaces	private static JToken ReorderJToken(this JToken jTok)\n    {\n        if (jTok is JArray)\n        {\n            var jArr = new JArray();\n            foreach (var token in jTok as JArray)\n            {\n                jArr.Add(token.ReorderJToken());\n            }\n            return jArr;\n        }\n        else if( jTok is JObject)\n        {\n            var jObj = new JObject();\n            foreach(var prop in (jTok as JObject).Properties().OrderBy(x=> x.Name))\n            {\n                prop.Value = prop.Value.ReorderJToken();\n                jObj.Add(prop);\n            }\n            return jObj;\n        }\n        return jTok;\n    }	0
7514193	7513598	ASP.NET C# GridView - variable number of columns and image thumbnail	gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound);\n\n...\n\nvoid gridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        DataView dataSource = (DataView)gridView1.DataSource;\n\n        DataColumn imageUrlColumn = dataSource.Table.Columns["ImageUrl"];\n        if (imageUrlColumn != null)\n        {\n            int index = imageUrlColumn.Ordinal;\n\n            DataControlFieldCell cell = (DataControlFieldCell)e.Row.Controls[index];\n            string imageUrl = cell.Text;\n\n            cell.Text = GenerateThumbnailUrl(imageUrl);\n        }\n    }\n}	0
32539505	32539206	Using UnsafeRegisterWaitForSingleObject failed with exception when exiting app?	wh.SafeWaitHandle = new SafeWaitHandle(p, true);	0
21973354	21941474	Load different version of assembly into separate AppDomain	Assembly asm = pluginDomain.GetAssemblies().First(a => a.GetName().Name == "Plugin");\nType p = asm.GetTypes().First(t => t.GetInterfaces().Contains(typeof(IPlugin)));\nvar pluginInstance = (IPlugin)pluginDomain.CreateInstanceAndUnwrap(asm.FullName, p.FullName);	0
3632485	3632433	LINQ to SQL group by with take	var results = table\n    .GroupBy(x => x.GroupId)\n    .Select(x => new { Row = x, Value = x.Max(y => y.Value) })\n    .OrderByDescending(x => x.Value)\n    .Select(x => x.Row)\n    .Take(10);	0
16017882	16016777	Reload DataTable bound to Datagrid in WPF	public event PropertyChangedEventHandler PropertyChanged;\n\npublic void OnPropertyChanged(String info)\n{\n    if (PropertyChanged != null)\n    {\n        PropertyChanged(this, new PropertyChangedEventArgs(info));\n    }\n}\n\npublic DataTable CurrentDataTable\n    {\n        get\n        {\n            return _dataTable;\n        }\n        set\n        {\n            _dataTable = value;\n            OnPropertyChanged("CurrentDataTable");\n        }\n    }\n}	0
6946183	6945775	Find & replace certain text within a node in an XML file	string path = @""<File name=""dev\Desktop\Working\Test\English\1312\myopic.dll"">";\nstring pattern = @"\d\d\d\d";\nRegex regex = new Regex(pattern);\nstring replacement = "%NUM%";\n\nstring result = regex.Replace(input, replacement);\n//result is: <File name="dev\Desktop\Working\Test\English\%NUM%\myopic.dll">	0
24679990	24679875	Boolean check if any of the drives contain a specific drivetype	// Get all the drives.\nDriveInfo[] allDrives = DriveInfo.GetDrives();\n\n// Check if any cdRom exists in the drives.\nvar cdRomExists = allDrives.Any(drive=>drive.DriveType==DriveType.CDRom);\n\n// If at least one cd rom exists. \nif(cdRomExists)\n{\n    // Get all the cd roms.\n    var cdRoms = allDrives.Where(drive=>drive.DriveType==DriveType.CDRom);\n\n    // Loop through the cd roms collection.\n    foreach(var cdRom in cdRoms)\n    {\n        // Check if a cd is in the cdRom.\n        if(cdRom.IsReady)\n        {\n\n        }\n        else // the cdRom is empty.\n        {\n\n        }\n    }\n}\nelse // There isn't any cd rom.\n{\n\n}	0
21557099	21556296	Would the process of determining whether a string has been modified cause performance hits? If so, could we optimize this further?	string a = "ABC";\nstring b = a;\nbool c = a == b; // Very fast.	0
564463	561798	How do I align text for a single subitem in a ListView using C#?	// Make owner-drawn to be able to give different alignments to single subitems\nlvResult.OwnerDraw = true;\n...\n\n// Handle DrawSubItem event\nprivate void lvResult_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)\n{\n    // This is the default text alignment\n    TextFormatFlags flags = TextFormatFlags.Left;\n\n    // Align text on the right for the subitems after row 11 in the \n    // first column\n    if (e.ColumnIndex == 0 && e.Item.Index > 11)\n    {\n        flags = TextFormatFlags.Right;\n    }\n\n    e.DrawText(flags);\n}\n\n// Handle DrawColumnHeader event\nprivate void lvResult_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)\n{\n    // Draw the column header normally\n    e.DrawDefault = true;\n    e.DrawBackground();\n    e.DrawText();\n}	0
686315	686305	Converting a List of Base type to a List of Inherited Type	var ListOfA = ListOfB.Cast<A>().ToList();	0
5593716	5593686	C# make datetimepicker work as only timepicker	timePicker = new DateTimePicker();\ntimePicker.Format = DateTimePickerFormat.Time;\ntimePicker.ShowUpDown = true;	0
18633922	18633739	printing barcode from winforms application	BarcodeDraw bdraw = BarcodeDrawFactory.GetSymbology(BarcodeSymbology.Code128);\nImage barcodeImage = bdraw.Draw("barcodetext", barcodeImageHeight);\ng.DrawImage(barcodeImage, barcodeRect);	0
4247591	4246045	How to get SharePoint file creator name using AllDocs table?	using (SPSite site = new SPSite("http://your.sharepoint.server/"))\n{\n    using (SPWeb web = site.OpenWeb())\n    {\n        SPList list = web.Lists["Documents"];\n        SPListItem item = list.Items[0];\n        string author = (string)item["Author"];\n        DateTime modified = (DateTime)item["Modified"];\n    }\n}	0
15124180	15124040	Unable to connect to any of the specified MySQL hosts	private void button1_Click(object sender, EventArgs e)\n        {\n            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connString))\n            {\n                if (radioButton1.Checked)\n                {\n                    timerEnabled = 1;\n                }\n\n                connection.Open();\n\n                //update the settings to the database table \n                MySqlCommand command = connection.CreateCommand();\n                command.CommandText = "update Admin_Settings set Difficulty='" + comboBox3.Text + "'," + "NoOfQuestions='" + comboBox4.Text + "'," + "NoOfChoices='" + comboBox5.Text + "'," +\n                    "Subject='" + comboBox8.Text + "'," + "Timer='" + comboBox2.Text + "," + "TimerEnabled=" + timerEnabled + "," + "TimerType='" + comboBox1.Text + "'";\n\n\n                command.ExecuteNonQuery();\n\n                MessageBox.Show("Settings updated");\n            }\n        }	0
15828122	15828021	EWS save/export EmailMessage in other format	message.Load(new PropertySet(ItemSchema.MimeContent));\nMimeContent mimcon = message.MimeContent;\nFileStream fStream = new FileStream("c:\test.eml", FileMode.Create);\nfStream.Write(mimcon.Content, 0, mimcon.Content.Length);\nfStream.Close();	0
20346323	20331311	Deserialization : NullReferenceException	// Change your Message's ConfigurationElements property with this\n[XmlArray("release")]\n[XmlArrayItem("rlse")]\npublic List<ConfigurationElement> ConfigurationElements { get; set; }	0
14998745	14998651	Logic Help needed	bool toggle = false;\nbool exitloop = false;\nint checkinterval = 600; // time in seconds between check\n\nwhile(!exitloop)\n{\n    bool is_online = check_online();                             \n\n    if (is_online) \n    {\n        if (!toggle) \n        {\n            Console.WriteLine("Online!" + DateTime.Now.ToString();\n            toggle = true;\n        }\n    }\n    else\n    {\n        if (toggle) \n        {\n            Console.WriteLine("Offline!" + DateTime.Now.ToString());\n            toggle = false;\n        }\n    }\n\n    Thread.Sleep(checkinterval * 1000);\n\n    // it would be a good idea to allow a mechanism\n    // to exit from the infinite loop.\n    if (check_if_we_should_exit_loop()) \n    {\n        exitloop = true;\n    }\n}	0
19227671	19227074	Design for interface that can be "implemented N times"	public interface IComposition<T>\n{\n    T Dependency { get; set; }\n}\n\npublic class MyClass: IComposition<TypeA>, IComposition<TypeB>\n{\n    IComposition<TypeA>.TypeA Dependency { get; set; }\n    IComposition<TypeB>.TypeB Dependency { get; set; }\n}	0
5147115	5135761	How to delete file after end of streaming wcf	OperationContext clientContext = OperationContext.Current;\nclientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)\n   {\n      if (fileStream != null)\n         fileStream.Dispose();\n   });	0
17238837	17238745	SQL Command to save a table to text file	sql.ex = new SqlCommand("EXEC xp_cmdshell 'bcp \"SELECT * FROM SRO_VT_SHARD.._RefPackageItem\" queryout " + \n         textBox1.Text + " -T -c '",sql.connection);	0
7309281	7309220	Constructing a linq query with dynamic ListItem columns that are type boolean	DataTable dt = siteTemplateList.GetItems().GetDataTable();\nvar query = from template in dt.Rows\n            where template[selectedBA].Equals(true)\n            select template;	0
15133019	14856944	Infopath 2007 - How to set ScreenTip programmatically in C# code behind?	XPathNavigator test2 = MainDataSource.CreateNavigator().SelectSingleNode("my:myFields/my:buttonSet", NamespaceManager);\n        if (test2.Value == "FALSE")\n        {\n            test2.SetValue("TRUE");\n        }\n        else\n        {\n            test2.SetValue("FALSE");\n        }\n        XPathNavigator tooltip = MainDataSource.CreateNavigator().SelectSingleNode("my:myFields/my:tooltip", NamespaceManager);\n        tooltip.SetValue("Custom Tooltip DEMO");\n    }	0
7975530	7975344	Disable Text on Windows Phone 7 Icon	private void RefreshApplicationTile()\n    {\n        ShellTile tile = ShellTile.ActiveTiles.First();\n        if (tile != null) {\n            StandardTileData NewTileData = new StandardTileData\n            {\n                Title = String.Empty,\n                BackgroundImage = new Uri(@"/Background.png", UriKind.Relative),\n                BackTitle = String.Empty,\n                BackBackgroundImage = new Uri(@"/BackBackground.png", UriKind.Relative),\n    ....\n            };\n            tile.Update(NewTileData);\n        }\n    }	0
9356026	9355877	loading combobox with datasource	cmbjobcode.DataSource = dt.DefaultView;	0
11982091	11981988	9 character unique random string (for single table)	public static string CreateRandomString(int length)\n{\n    length -= 12; //12 digits are the counter\n    if (length <= 0)\n        throw new ArgumentOutOfRangeException("length");\n    long count = System.Threading.Interlocked.Increment(ref counter);\n    Byte[] randomBytes = new Byte[length * 3 / 4];\n    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\n    rng.GetBytes(randomBytes);\n\n    byte[] buf = new byte[8];\n    buf[0] = (byte)count;\n    buf[1] = (byte)(count >> 8);\n    buf[2] = (byte)(count >> 16);\n    buf[3] = (byte)(count >> 24);\n    buf[4] = (byte)(count >> 32);\n    buf[5] = (byte)(count >> 40);\n    buf[6] = (byte)(count >> 48);\n    buf[7] = (byte)(count >> 56);\n    return Convert.ToBase64String(buf) + Convert.ToBase64String(randomBytes);\n}	0
1097158	1097147	Is there a better way to determine if a string can be an integer other than try/catch?	if (int.TryParse(string, out result))\n{\n    // use result here\n}	0
17998151	17997964	Passing data into a separate form	private void SaveButton_Click(object sender, EventArgs e)\n{\n     StringBuilder sb = new StringBuilder();\n     foreach (string error in errorSet)\n        sb.AppendLine(error);\n\n    if(sb.Lenght> 0)\n    {\n        Form2 frm = new Form2(sb.ToString());\n        frm.Show();\n    } \n}	0
30846731	30844237	LINQ: Query body must end with a select clause or a group clause	var query = csvlines.Skip(1).Select(x =>\n        {\n            var data = x.Split(',');\n\n            return new User\n            {\n                CSRName = data[6],\n                CallStart = data[0],\n                CallDuration = data[1],\n                RingDuration = int.Parse(data[2]),\n                Direction = int.Parse(data[3]),\n                IsInternal = int.Parse(data[4]),\n                Continuation = int.Parse(data[5]),\n                ParkTime = int.Parse(data[7])\n            };\n        });	0
15241755	15241710	Accessing the raw http request in MVC4	protected override void OnActionExecuted(ActionExecutedContext filterContext)\n{\n    var request = filterContext.HttpContext.Request\n    var inputStream = request.InputStream;\n    inputStream.Position = 0;\n    using (var reader = new StreamReader(inputStream))\n    {\n        string headers = request.Headers.ToString();\n        string body = reader.ReadToEnd();\n        string rawRequest = string.Format(\n            "{0}{1}{1}{2}", headers, Environment.NewLine, body\n        );\n        // TODO: Log the rawRequest to your database\n    }\n}	0
10547701	10547638	How to receive a SQL-Statement as a DataTable	public static DataTable GetDataTable(string sConnStr, string sTable)\n{\n    using (SqlConnection sqlConn10 = new SqlConnection(sConnStr))\n    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM EmployeeIDs", sqlConn10))\n    {\n        sqlConn10.Open();\n        DataTable dt = new DataTable();\n        adapter.Fill(dt);\n        return dt;\n    }\n}	0
19919158	19919117	Filling array with random "cards" of enum	var r = new Random();\n r.Next(min,max);	0
14797638	14797437	Binding properties to controls using reflection	Binding myBinding = new Binding("MyDataProperty"); //name of the property on the object which is used as binding source\n  myBinding.Source = myObject;\n  textbox.SetBinding(TextBlock.TextProperty, myBinding);	0
8585242	8585142	How to check a session variable in asp.net 4.0?	Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); \nResponse.Cache.SetCacheability(HttpCacheability.NoCache); \nResponse.Cache.SetNoStore();	0
25080742	25079794	Ajax tabContainer properties setting	protected void btnAddCat_Click(object sender, EventArgs e)\n{\n    if (TabConAddInfo.ActiveTab.TabIndex == 0)\n    {\n        addSplash();\n    }\n    else if (TabConAddInfo.ActiveTab.TabIndex == 1)\n    {\n        addMainCat();\n    }\n}	0
32508277	32508147	Move current Form to left side of screen	Rectangle r = Screen.FromControl(this).WorkingArea;\nthis.Bounds = new Rectangle(r.Left, 0, this.Width, r.Height);	0
11930466	11929443	Move to next cell in the next row in excel using c#	var excelApp = this.Application;\nint skipRows = 1;\nint skipCells = 0;\nvar nextRange = excelApp.ActiveCell.Offset[skipRows, skipCells].Select();	0
8889691	8889161	Get previous element of a dictionary	Dictionary<string, string> svrs = new Dictionary<string, string>();\n            svrs.Add("NLDN1234", "ok");\n            svrs.Add("NLDN1235", "ok");\n            svrs.Add("NSTM2345", "ok");\n            svrs.Add("NSTM9874", "ok");\n\n            SortedDictionary<string, string> sortedSvrs = new SortedDictionary<string, string>(svrs);\n\n            for (int i = 0; i < sortedSvrs.Keys.Count; i++)\n            {\n                var key = sortedSvrs.Keys.ElementAt(i);\n                Console.WriteLine(key +" " + sortedSvrs[key]);\n                // any extra operation\n                //\n            }	0
2893514	2893481	Concise C# code for gathering several properties with a non-null value into a collection?	public static IEnumerable<T> GetAllNonNullAs(this X x)\n{\n    return new[] { x.A, x.B, x.C }.Where(t => t != null);\n}	0
17805130	17804594	Accessing different Masterpages from Base Class	public partial class SiteMasterPage : System.Web.UI.MasterPage\n{\n   ....\n   // GetCurrentUser\n}\n\npublic partial class MainMasterPage : SiteMasterPage\n{\n   ....\n}\n\npublic partial class PopupMasterPage : SiteMasterPage\n{\n}	0
18855430	18855286	Find ultimate parent of an entity using recursion in c#	internal <entity> FetchParentComponentRecursive(<entity> entity)\n{\n  if (component.ParentEntity == null)\n  {\n     return component;\n  }\n  else\n  {\n     return FetchParentComponentRecursive(entity.ParentEntity);\n  }\n}	0
25589368	25589303	C# Cannot make a custom richtextbox in a class	public static RichTextBox ControledText = new RichTextBox();	0
10261598	10203191	How to create Linq2Sql query that will group records from linked table and calculate 2 count fields	from c in db.GetTable<Country>()\nwhere c.Allowed\nselect new CountryTeamsInfo\n{\n    CountryId = c.Id,\n    TeamsTotal = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed),\n    TeamsHasOwner = db.GetTable<Team>().Count(t => t.CountryId == c.Id && t.Allowed && t.OwnerId != 0),\n}	0
14607231	14306126	Serialization of only changed members	Update.Set(name, value)\nUpdate.Push(name, value)	0
5967312	5967140	How to perceive in code if developer pressed F5 or Ctrl-F5	static void Main(string[] args)\n{\n\n    if (System.Diagnostics.Debugger.IsAttached)\n       Console.WriteLine("f5");\n     else\n       Console.WriteLine("ctrl f5");\n    string s = Console.ReadLine();\n\n}	0
3674324	3674158	Get all users from AD domain	var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x.y.com", "DC=x,DC=y,DC=com"));\nvar searcher = new DirectorySearcher(dirEntry)\n         {\n             Filter = "(&(&(objectClass=user)(objectClass=person)))"\n         };\nvar resultCollection = searcher.FindAll();	0
25045738	25044722	How can I pass a value from a Button_Click event to Page_Load	int doWhat;\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        //doWhat = Convert.ToUInt16(ViewState["doWhat"]);\n        doWhat = Convert.ToUInt16(HiddenField1.Value);\n\n        if (doWhat == 1)\n        {\n            // code to dynamically load group 1 controls\n        }\n        else\n        {\n            // code to dynamically load group 2 controls\n        }\n        Label1.Text = Convert.ToString(doWhat);\n    }\n\n    protected void Button_Click(object sender, EventArgs e)\n    {\n        //Do Nothing\n\n        //Button btn = sender as Button;\n        //if (btn.ID == "Button1")\n        //{\n        //    doWhat = 1;\n        //}\n        //else\n        //{\n        //    doWhat = 2;\n        //}\n        //ViewState.Add("doWhat", doWhat); \n    }	0
14325534	14324794	How to parse JSON array (as a string) to Dictionary<string,string> in C#?	var dic = serializer.Deserialize<Dictionary<string, Dictionary<string, string>[]>>(jsonString)["Updated"][0];\nvar firstName = dic["FIRST_NAME"];\nvar lastName = dic["LAST_NAME"];	0
9115605	9114493	Print Migradoc document with MVC 3	// Save the document...\nconst string filename = "HelloWorld.pdf";\npdfRenderer.PdfDocument.Save(filename);\n// ...and start a viewer.\nProcess.Start(filename);	0
15997750	15997318	How to test that 8:00 PM is valid prior to 12:00 AM?	// force the date format to be 12hour like in US\nSystem.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");\nSystem.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");\n\nDateTime start = DateTime.Parse("1/1/2013 7:00 PM").ToUniversalTime();\nDateTime end = start.AddHours(5); // returns 1/2/2013 12:00:00 AM as it should\n\nConsole.WriteLine(end - start); // 05:00:00\nConsole.WriteLine((end - start) > TimeSpan.Zero); // True	0
22792426	22792230	Incrementing a score counter on a gesture match	int scoreCntr = 0;\nvoid matcher_GestureMatch(Gesture gesture)\n{\n    lblGestureMatch.Content = gesture.Name;\n    scoreCntr++;\n\n    var soundEffects = Properties.Resources.punchSound;\n    var player = new SoundPlayer(soundEffects);\n    player.Load();\n    player.Play();\n\n    lblScoreCntr.Content = scoreCntr;\n}	0
22389280	22389147	Copy text from a CMD window executed through a C# windows form	Process p = new Process();\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = "cmd.exe";\np.StartInfo.Arguments = "/c ping 192.168.1.1"; //or your thing\np.Start();\n\np.WaitForExit();\nstring result = p.StandardOutput.ReadToEnd();\n\nSystem.Windows.Forms.Clipboard.SetText(result);	0
33512923	33430109	How to turn multiple documents result to one document using Marklogic REST API in .net C#?	URI uri = new URI("xdbc://admin:admin@localhost:9091/xcc-testing");\n        ContentSource contentSource = ContentSourceFactory.newContentSource(uri);\n        Session session = contentSource.newSession("xcc-testing");\n        Request request = session.newAdhocQuery("<result>{for $i in /info return $i}</result>");\n        ResultSequence rs = session.submitRequest(request);\n        string content = "";\n        while (rs.hasNext())\n        {\n            ResultItem rsItem = rs.next();\n            XdmItem item = rsItem.getItem();\n            string output = item.asString();\n            content = output;\n        }	0
4053472	4053418	Regular DateTime question	DateTime.Now.DayOfWeek	0
17363350	17363147	how to parse a file for a specified condition in c#	static void Main()\n{\n    var lines = ReadAllLines(@"path\to\your\file.txt");\n\n    var lineNumbers = lines.Where(l => Criteria(l))\n                           .Select((s, i) => i);\n\n    foreach (var i in lineNumbers)\n    {\n        Console.WriteLine("Criteria met on line " + i);\n    }\n}\n\nstatic bool Criteria(string s)\n{\n    int i = int.Parse(Regex.Match(s, "(?<=Rows_affected: )\d+").Value);\n\n    return i > 500;\n}	0
1613438	1613239	Getting the object out of a MemberExpression?	Expression<Func<string>> expr = () => foo.Bar;\nvar me = (MemberExpression)((MemberExpression)expr.Body).Expression;\nvar ce = (ConstantExpression)me.Expression;\nvar fieldInfo = ce.Value.GetType().GetField(me.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\nvar value = (Foo)fieldInfo.GetValue(ce.Value);	0
28558327	28558182	Convert a sequence of numbers into a zero based order?	var actualPositionsFound = new[] { 100, 50, 200 };\nvar indices = actualPositionsFound.OrderBy(n => n)\n                                  .Select((n, i) => new { n, i })\n                                  .ToDictionary(o => o.n, o => o.i);\nvar result = actualPositionsFound.Select(n => indices[n]).ToList();	0
1380342	1380294	How to write a test for a method that returns an IEnumerable	Enumerable.SequenceEqual	0
16473707	16458118	How to stop the ringtone default in windows phone	SoundEffectInstance currentSI;\nusing (var stream = TitleContainer.OpenStream("PATH"))\n{\n    var effect = SoundEffect.FromStream(stream);\n    currentSI = effect.CreateInstance();\n    FrameworkDispatcher.Update();\n    currentSI.Play();\n}	0
32721861	32721687	MVVM WPF Data Binding issue	public class Users :ObservableCollection<User>\n{\n    public User GetById(int id)\n    {\n        return this.First(u => u.ID == id);\n    }\n\n}	0
16648241	16648176	c# draw - Add random lines in a image	Random rnd = new Random();\nGraphics g = Graphics.FromImage(bitmap);\nfor (int i=0; i<n; i++) {\n    // calculate line start and end point here using the Random class:\n    int x0 = rnd.Next(0, bitmap.Width);\n    int y0 = rnd.Next(0, bitmap.Height);\n    int x1 = rnd.Next(0, bitmap.Width);\n    int y1 = rnd.Next(0, bitmap.Height);\n    g.DrawLine(Pens.White, x0, y0, x1, x1);\n}	0
17037057	16862328	Convert Stored Procedure into HQL nhibernate	var results = session.CreateCriteria<DrMaster>()\n    .Add(Expression.EqProperty("fDate",\n        Projections.Conditional(Expression.Eq("Date", null), \n            Projections.SubQuery(DetachedCriteria.For<DrMaster>()\n                .Add(Expression.EqProperty("fPropertyId", "PropertyId"))\n                .SetProjection(Projections.Max("fDate"))),\n            Projections.Property("Date"))))\n    .Add(Expression.EqProperty("fPropertyId", "PropertyId"))\n    .List<DrMaster>();	0
1834940	1834753	LINQ to SQL and a running total on ordered results	List<Item> myList = FetchDataFromDatabase();\n\ndecimal currentTotal = 0;\nvar query = myList\n               .OrderBy(i => i.Date)\n               .Select(i => \n                           {\n                             currentTotal += i.Amount;\n                             return new { \n                                            Date = i.Date, \n                                            Amount = i.Amount, \n                                            RunningTotal = currentTotal \n                                        };\n                           }\n                      );\nforeach (var item in query)\n{\n    //do with item\n}	0
27619740	27619537	Grammar or txt into a string to parse later in C#	string speech = "i want a tiger";\n\n        var allAnimals = File.ReadAllLines(@"Default Animals.txt");\n        if (allAnimals.Any(x => speech.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) != -1))\n        {\n            kevin.speak("It worked");\n        }\n        else\n        {\n            kevin.speak("It didnt work");\n        }	0
25659728	25620856	Accessing AppResources in a separate project without build dependency	return resourceManager.GetString(stringResourceName, System.Globalization.CultureInfo.CurrentCulture);	0
15550186	15549918	Return XML from Web Api Controller	GlobalConfiguration.Configuration.Formatters.Clear();\nGlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());	0
12335900	12318819	ZeroMQ context destruction causes poller to ETERM but doesn't continue	if (e.Errno == ETERM)\n        {\n            //Catch a termination error. \n            Debug.WriteLine("Terminated! 1");\n            client.Close();\n            return;\n        }	0
8424892	8424813	User Defined TabPage Loading into TabControl	List<record> cUngroupedRecords = new List<record>();\n\n        Dictionary<string, List<record>> cGroupedRecords = new Dictionary<string, List<record>();\n\n        foreach (record Record in cUngroupedRecords)\n        {\n            string sFirstChar = Record.LastName[0].ToString();\n            List<record> cRecords;\n\n            if (cGroupedRecords.ContainsKey(sFirstChar)) {\n                cRecords = cGroupedRecords[sFirstChar];\n            } else {\n                cRecords = new List<string>();\n                cGroupedRecords.Add(sFirstChar, cRecords);\n            }\n            cRecords.Add(Record);\n        }	0
9037893	9037009	Implementing a plug-in/templating system c#	Activator.CreateInstance(Type.GetType(templateName));	0
30544628	30544395	how to query database and show information in winforms?	var connection = new SqlConnection("ConnectionString");\n            connection.Open();\n            var command = new SqlCommand("SELECT id FROM Table WHERE id='" + textBox2.Text + "",connection);\n            var reader = command.ExecuteReader();\n            if (reader.Read())\n            {\n                textBox1.Text = reader["id"].ToString();\n            }\n            else\n            {\n                ///No entry found\n            }\n            connection.Close();	0
19739164	19739124	Change table cell color depending on value in asp and C#	for(int rows=0;rows<Table1.Rows.Count;rows++)\n            {\n                for (int cols = 0; cols < Table1.Rows[rows].Cells.Count; cols++)\n                {\n                    if (Convert.ToInt32(Table1.Rows[rows].Cells[cols].Text.ToString()) == 1)\n                    {\n                        Table1.Rows[rows].Cells[cols].BackColor = Color.Green;\n                    }\n                    else if (Convert.ToInt32(Table1.Rows[rows].Cells[cols].Text.ToString()) == 0)\n                    {\n                        Table1.Rows[rows].Cells[cols].BackColor = Color.Red;\n                    }\n                }\n            }	0
8560671	8547445	401 unauthorized using google task	StringBuilder sb = new StringBuilder();\nsb.Append("Authorization: OAuth oauth_version=\"1.0\",");\nsb.AppendFormat("oauth_nonce=\"{0}\",", EncodingPerRFC3986(nonce));\nsb.AppendFormat("oauth_timestamp=\"{0}\",", EncodingPerRFC3986(timeStamp));\nsb.AppendFormat("oauth_consumer_key=\"{0}\",", EncodingPerRFC3986(consumerKey));\nif (!String.IsNullOrEmpty(token))\n{\n    sb.AppendFormat("oauth_token=\"{0}\",", EncodingPerRFC3986(\n}\nsb.Append("oauth_signature_method=\"HMAC-SHA1\",");\nsb.AppendFormat("oauth_signature=\"{0}\"", EncodingPerRFC3986(signature));\n\nreturn sb.ToString();	0
403638	403572	How to get random double value out of random byte array values?	byte[] result = new byte[8];\nrng.GetBytes(result);\nreturn (double)BitConverter.ToUInt64(result,0) / ulong.MaxValue;	0
14442325	14438935	How do I display an MJPEG stream in a Windows Form application?	// class attribute\nMjpegDecoder m_mjpeg;\n\n// In the constructor\nm_mjpeg = new MjpegDecoder();\nm_mjpeg.FrameReady += mjpeg_FrameReady;\n\n// Private method\nprivate void mjpeg_FrameReady(object sender, FrameReadyEventArgs e)\n{\n\n        yourPictureBox.Image = e.Bitmap;\n}	0
18488473	18488234	How to manage two list object reference that are pointing to same collection?	using (var memoryStream = new MemoryStream())\n{\n   var binaryFormatter = new BinaryFormatter();\n   binaryFormatter.Serialize(memoryStream, <Your Original List Object>);\n   memoryStream.Position = 0;\n\n   <You actual List Object> =  binaryFormatter.Deserialize(memoryStream);\n}	0
32846647	32827248	Start Sonicwall netextender from .Net application	cd c:\Program Files (x86)\SonicWALL\SSL-VPN\NetExtender\\nNECLI connect -s IPADDRESS -d DOMAINNAME -u USERNAME-p PASSWORD	0
26992722	26992646	How do I add Generic constraints?	class MyGenericClass<T> where T : class, IYourCommonInterface\n{\n    public void do()\n    {\n    }\n}	0
13187260	13187137	date format in .net - how do I say use the given cultureinfo?	var text = date1.ToString(CultureInfo.CreateSpecificCulture("fr-FR")\n  .DateTimeFormat.ShortDatePattern);	0
14872745	14872552	How to delete all sub folders with name "test" in C#	var testDirectories = Directory.GetDirectories(@"C:\", "test.*");\n\n  foreach (var directory in testDirectories)\n  {\n      Directory.Delete(directory, true);\n  }	0
17837224	17828774	Get Resources with string	string st = Properties.Resources.ResourceManager.GetString(tableName);	0
14058784	14058597	Validate an XmlDocument using an XSD String in C#?	using (StringReader stringReader = new StringReader(xsdString))\nusing (XmlTextReader xmlReader = new XmlTextReader(stringReader))\n{\n    xmlDocument.Schemas.Add(null, xmlReader);\n}	0
27462950	27462640	Can you set an object name as input from a texbox?	class Employee \n{\n  ....\n  piblic string Name {get;set;}\n}\n\nEmployee GetByName(string name)\n{\n     return listOfAllEmployees.Where(e => e.Name = name);\n}	0
466074	465543	How do display the Integer value of an IPAddress	public double IPAddressToNumber(string IPaddress)\n    {\n        int i;\n        string [] arrDec;\n        double num = 0;\n        if (IPaddress == "")\n        {\n            return 0;\n        }\n        else\n        {\n            arrDec = IPaddress.Split('.');\n            for(i = arrDec.Length - 1; i >= 0 ; i = i -1)\n                {\n                    num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));\n                }\n            return num;\n        }\n    }	0
1698427	1698401	How can I convert a list of domain objects to viewmodels on the Controller in ASP.NET MVC	IList<BallViewModel> _balls = _ballsService.GetBalls(searchCriteria)\n    .Select(b => new BallsViewModel\n                 {\n                     ID = b.ID,\n                     Name = b.Name,\n                     // etc\n                 })\n    .ToList();	0
12966987	12966734	How To Show System.Diagnostics In Front Of WinForm Using Win32 API	Process process = (Process)lvi.Tag; \nShowWindow(process.MainWindowHandle, SW_SHOWMAXIMIZED);\nBringWindowToTop(process.MainWindowHandle);	0
16176657	16174909	Method in xaml.cs to change text in xaml from localized resx resource	AppResources.appDesc	0
28780539	28779210	How to cast int value to list int value of Flag enums	var lstEnumValues = new List<int>Enum.GetValues(typeof(DataAccessPoliceis)).Cast<int>())\n.Where(enumValue => enumValue != 0 && (enumValue & x) == enumValue).ToList();	0
17047777	17047675	Update Progress bar from Class' BackgroundWorker	EventHandler<ProgressChangedEventArgs>	0
33082533	33082361	How to filter an xml list based on whether it has a particular attribute	var replyComments = (from comment in CommentsEx.Descendants()\n                    where comment.Name.LocalName == "commentEx"\n                    from attrib in comment.Attributes()\n                    where attrib.Name.LocalName == "paraIdParent"\n                    select comment).ToList();	0
31427524	31427491	How to check String Contains Alphabets or Digits-Regular Expression c#	Regex.Matches(folderPath, @"[a-zA-Z0-9]").Count	0
17370451	17369702	What is the maximum number of rows a DataGridView can render OK?	DataTable dt = new DataTable();\nfor (int i = 0; i < 10; i++)\n{\n   dt.Columns.Add(i.ToString());\n}    \nfor (int j = 0; j < 200000; j++)\n{\n   DataRow row = dt.NewRow();\n   for (int k = 0; k < 10; k++)\n   {\n      row[k] = Guid.NewGuid().ToString();\n   }\n   dt.Rows.Add(row);\n}\ndataGridView1.DataSource = dt;	0
27212034	27062175	Bitmap ArgumentException after returning in using statement	GC.Collect();\nGC.WaitForPendingFinalizers();\nSystem.Threading.Thread.SpinWait(5000);	0
11781159	11781011	compare value from datagridview to fileinfo	var path = column.Text; // or wherever you get the path from\npath = Path.Combine(@"C:\absolute\path\", path);\nif (File.Exists(path))\n{\n   // Do something\n}	0
26643335	26641638	Queryhistory for a range of changeset in TFS for specific info	var changes = vcs.QueryHistory(\n    path, \n    VersionSpec.Latest, \n    0, \n    RecursionType.Full, \n    null, \n    VersionSpec.ParseSingleSpec("C100", null), // starting from changeset 100\n    VersionSpec.ParseSingleSpec("C200", null), // ending with changeset 200\n    int.MaxValue, \n    true, \n    false);\n\n foreach(Changeset change in changes)\n {\n     Console.WriteLine("{0} {1}", change.ChangesetId, change.Comment);\n }	0
32704449	32703783	Why does the assignment from a dynamic object throw a RuntimeBinderException?	IDictionary<string, JToken>	0
34221819	34221657	Filter DataGrid for name with TextBox dynamically	private void TextBox_TextChanged(object sender, EventArgs e)\n{\n    DataView dv = ds.Tables[0].DefaultView;\n    dv.RowFilter = string.Format("Name like '%{0}%'", Filter.Text);\n    haupt?bersichtgrid.ItemsSource = dv;\n}	0
3308751	3305322	Fastest Way to extract from SQL Lite in C#	Dispatcher UIDispatcher = Dispatcher.CurrentDispatcher;\nBackgroundWorker bw = new BackgroundWorker();\nbw.DoWork += (sender,e) =>\n{\n    // Use a linq query to yield an IQueryable/IEnumerable List of data from DB\n    foreach(Data data in DataList)   // Enumerated here\n    {\n        UIDispatcher.Invoke(DispatcherPriority.ContextIdle, new Action(() => \n        { \n            myOC.Add(data);\n        }));\n    }    \n};	0
22204137	22203946	User change value in the array	static void ChangeArray(int[] array)\n{\n    int index = Convert.ToInt32(Console.ReadLine());\n    int newValue= Convert.ToInt32(Console.ReadLine());\n\n    if(index <= array.Length && index >= 0)\n    {\n        array[index] = newValue;\n    }\n    Console.WriteLine("\n=============\n");\n    for (int i = 0; i < array.Length; i++)\n    {\n        Console.Write("{0}", array[i]);\n    }\n    Console.WriteLine("\n=============\n");\n}	0
4834870	4834819	C# MessageBox To Front When App is Minimized To Tray	MessageBox.Show(new Form() { TopMost = true }, "You have not inputted a username or password. Would you like to configure your settings now?",\n                 "Settings Needed",\n                 MessageBoxButtons.YesNo,\n                 MessageBoxIcon.Question);	0
19916685	19915545	Globally Override Linq to SQL to save object strings as Empty Strings instead of NULL	public partial class NorthwindDataContext\n{\n    public override void SubmitChanges(ConflictMode failureMode)\n    {\n        this.EmptyNullProperties();\n\n        base.SubmitChanges(failureMode);\n    }\n\n    private void EmptyNullProperties()\n    {\n        var propertiesToEmpty =\n            from entity in this.GetChangeSet().Inserts\n            from property in entity.GetType().GetProperties()\n            where property.CanRead && property.CanWrite\n            where property.PropertyType == typeof(string)\n            where property.GetValue(entity) == null\n            select new { entity, property };\n\n        foreach (var pair in propertiesToEmpty)\n        {\n            pair.property.SetValue(pair.entity, string.Empty);\n        }\n    }\n}	0
30308461	30308222	Regex split into words and punctuation/symbols	\s*(\b|[->])\s*	0
17610886	17597642	how to cancel Task quicker	cancellationToken.WaitHandle.WaitOne(TimeSpan.FromMinutes(5));	0
5610789	5610770	How to flat xml to one line in c# code?	XDocument document = XDocument.Load("test.xml");\ndocument.Save("test2.xml", SaveOptions.DisableFormatting);	0
11750161	11750098	Load Dynamic Control in Asp.net (Asp Page Lifecyle)	protected override void CreateChildControls()\n    {\n        base.CreateChildControls();\n        //now load your control here\n    }	0
16735625	16722872	Obtaining exact path without filename	string executingtitle = _applicationObject.Solution.FullName;\nstring[] title = executingtitle.Split( ',' );\nstring filename = title[0];\nstring filepath = Path.GetFullPath(filename);	0
7355768	7355689	Linq: how to get values of second level nodes	var books = from book in document.Descendants("book")\n            let title = book.Element("title").Value\n            let price = book.Element("Price")\n            let currency = price.Element("Currency").Value\n            let amount = price.Element("Amount").Value\n            select new\n            {\n                Title = title,\n                Price = new\n                {\n                    Currency = currency,\n                    Amount = amount\n                }\n            };	0
251853	251467	How can I create a video from a directory of images in C#?	double framesPerSecond;\nBitmap[] imagesToDisplay;     // add the desired bitmaps to this array\nTimer playbackTimer;\n\nint currentImageIndex;\nPictureBox displayArea;\n\n(...)\n\ncurrentImageIndex = 0;\nplaybackTimer.Interval = 1000 / framesPerSecond;\nplaybackTimer.AutoReset = true;\nplaybackTimer.Elapsed += new ElapsedEventHandler(playbackNextFrame);\nplaybackTimer.Start();\n\n(...)\n\nvoid playbackNextFrame(object sender, ElapsedEventArgs e)\n{\n    if (currentImageIndex + 1 >= imagesToDisplay.Length)\n    {\n            playbackTimer.Stop();\n\n            return;\n    }\n\n    displayArea.Image = imagesToDisplay[currentImageIndex++];\n}	0
15204945	15204131	Use a variable in ViewModel	public interface ITest \n{\n  void Test(string testInput);\n}\n\npublic class TestImpl : ITest\n{\n  public int TestId { get; private set; }\n\n  void ITest.Test(string testInput)\n  {\n    int intOut; //I think this is your point of confusion, right?\n    if (!int.TryParse(testInput, out intOut))\n      return;\n\n    TestId = intOut; \n  } \n}	0
21286540	21265575	Assert a method was called whilst verifying the parameters are correct	var mockProvider = MockRepository.GenerateMock<IItemProvider>();\nvar target = new ItemService(mockProvider);\nItem testItem = null;\n\nmockProvider.Expect(c => c.SaveItem(Arg<Item>.Is.Anything))\n.WhenCalled(call =>\n{\n    testItem = (Item)call.Arguments[0];\n});\n\n\ntarget.SaveItem(item);//item initialised elsewhere\n\n\nAssert.AreEqual(item.Id, testItem.Id);	0
12628855	12628737	LINQ "where" with parameter	private Expression<Func<Record, bool>> GetMonthBoolFunc(int value)\n{\n    return a => (a.codedID/10000 == value); \n}\n\nvar q = openedDatabase.RecordTable.Where(GetMonthBoolFunc(1));	0
15577523	15577464	How to count of sub-string occurrences?	Regex.Matches(input, "OU=").Count	0
13872313	13871525	Downloading image, serializing to base-64 string, converting to ImageSource	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n{\n    if (value == null)\n        return null;\n\n    string imageBase64String = (string)value;\n    byte[] imageAsBytes = Convert.FromBase64String(imageBase64String);\n\n    using (var ms = new MemoryStream(imageAsBytes))\n    {\n        var decoder = System.Windows.Media.Imaging.BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOptions.OnLoad);\n\n        return decoder.Frames[0];\n    }\n}	0
13016114	13015972	How to print text to specific position using c#?	//Replace with path to the form\nvar pdfFormLocation = "C:\\pdfForm.pdf"; \n\n//Adjust below path to a temp location\nvar pdfPath = String.Format("C:\\temp\\{0}", Guid.NewGuid().ToString());\nFile.Copy(pdfFormLocation, pdfPath, true);\n\nvar reader = new PdfReader(pdfPath);\nvar output = new FileStream();\nvar stamper = new PdfStamper(reader, output);\n\n//the form field names can be a little hairy\nstamper.AcroFields.SetField("topmostSubform[0].Page1[0].f1_01_0_[0]", "Your Name");\n\n//make the form no longer editable\nstamper.FormFlattening = true;\n\nstamper.Close();\nreader.Close();\n//now you can go print this file from pdfPath	0
2116884	2116859	Testing properties with reflection using attributes	object value = propertyInfo.GetValue(instance, null);\n\nif (value == null)\n   //Null value\nelse if (DBNull.Value.Equals(value))\n   //DB Null	0
11943085	11938922	Calculate time for a logarithmic algorithm	totaltime = 0;\nfor i := 0 to 5 do\nbegin\n  starttime = now;\n  for j := 0 to 10 do\n    run algorithm(i*10^6+j)\n  endtime = now;\n  totaltime := totaltime + 10^5*(endtime - starttime);\n  writeln('10 iterations near ', i*10^6, ' takes ', endtime - starttime, ' seconds');\nend;\nwriteln('approximate time for complete algorithm to run is', totaltime);	0
2501028	2500969	How do I turn an array of bytes back into a file and open it automatically with C#?	byte[] filedata = GetMyByteArray();\nstring extension = GetTheExtension(); // "pdf", etc\n\nstring filename =System.IO.Path.GetTempFileName() + "." + extension; // Makes something like "C:\Temp\blah.tmp.pdf"\n\nFile.WriteAllBytes(filename, filedata);\n\nvar process = Process.Start(filename);\n// Clean up our temporary file...\nprocess.Exited += (s,e) => System.IO.File.Delete(filename);	0
29351795	29351545	Converting WriteableBitmap to Byte array - Windows phone 8.1 - Silverlight	public static byte[] ConvertToByteArray(WriteableBitmap writeableBitmap)\n{\n    using (var ms = new MemoryStream())\n    {\n        writeableBitmap.SaveJpeg(ms, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);\n        return ms.ToArray();\n    }\n}	0
1565961	1565771	How to search for a node using Linq to XML Query?	var Property1 = doc.Root.Elements("local").Elements("section")\n    .Where(x => x.Attribute("name") == "B").Elements("subsection")\n    .Where(x => x.Attribute("name") == "B").Elements("innersection")\n    .Where(x => x.Attribute("name") == "B").Element("Property1");	0
13141668	13141251	Youtube feed parse xml c# razor	XDocument xDoc = XDocument.Load("https://gdata.youtube.com/feeds/api/standardfeeds/most_viewed");\nXNamespace media = "http://search.yahoo.com/mrss/";\nXNamespace yt = "http://gdata.youtube.com/schemas/2007";\n\nvar items = xDoc.Descendants(media + "group")\n                .Select(i => new\n                {\n                    Title = i.Element(media + "title").Value,\n                    Content = i.Element(media + "content").Attribute("url").Value,\n                    Thumbnail = i.Element(media + "thumbnail").Attribute("url").Value,\n                    Uploaded = (DateTime)i.Element(yt + "uploaded"),\n                })\n                .ToList();	0
26600603	26600508	Drawline with same pen width, but the line widths are different in result	Bitmap b = new Bitmap(400, 400);\n        Graphics g = Graphics.FromImage(b);\n\n        g.PageUnit = GraphicsUnit.Point;\n        g.Clear(Color.White);\n        Pen pen = new Pen(Color.Red, 1.2f);\n\n        for (float i = 20f * pen.Width; i < 200f * pen.Width; i = i + 20f * pen.Width)\n        {\n            g.DrawLine(pen, 10f, i, 190f, i);\n        }\n\n        g.Dispose();\n        b.Save("c:/temp/test.png", ImageFormat.Png);\n        b.Dispose();	0
3374192	3373584	Programmatically open and close firefox	public void SearchForWatiNOnGoogle()\n{\n    using (var browser = new Firefox("http://www.google.com"))\n    {\n        browser.TextField(Find.ByName("q")).TypeText("WatiN");\n        browser.Button(Find.ByName("btnG")).Click();\n        browser.Close();\n\n     }\n  }	0
684181	684133	Passing C# data type parameters to dll written in C++?	[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]\npublic struct RECO_DATA {\n\n    /// wchar_t[200]\n    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=200)]\n    public string FirstName;\n\n    /// wchar_t[200]\n    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=200)]\n    public string Surname;\n}	0
17098933	17098715	if statement glitching	(lane - 1) * (float)Math.PI * 0.5f	0
16800447	16800371	how to search dictionary by Key using linq	var value = Resources_and_Groups[resID.ToString()];	0
23642986	23642949	Getting subcontrol in Repeater	protected void repRunResults_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    //capture current context.\n    Repeater repRunResults = (Repeater)sender;\n    Label laMessage = e.Item.FindControl("laMessage"); //<-- Used e.Item here\n    DSScatterData.RunResultsRow rRunResults = (DSScatterData.RunResultsRow)((DataRowView)(e.Item.DataItem)).Row;\n\n    //show message if needed.\n    int iTotal = this.GetTotal(m_eStatus, rRunResults.MaxIterations, rRunResults.TargetLimit);\n    if(iTotal == 100)\n    {\n        laMessage.Text = "The computed total is 100.";\n    }\n    else\n    {\n        laMessage.Text = "The computed total is NOT 100.";\n    }\n}	0
968717	968711	Convert IOrderedEnumerable to XElement	XElement element = new XElement("container", list)	0
10622979	10622801	asp.net gridview with drop down , text box and checkbox	foreach(GridViewRow row in gvMyGrid.Rows)\n{\n    DropDownList ddl1 = (DropDownList)row.FindControl("ddl1");\n    //code here to save this value\n}	0
20010928	20010803	How can I make the file path, in order to find the correct files on any PC?	string picPath = (AppDomain.CurrentDomain.BaseDirectory + "mypicture.jpg");	0
23363056	23362890	How to use the value of inner xml of an xml node in c#	String contractId = node2.SelectSingleNode("ContractID").InnerXml;	0
22264201	22256470	Cannot set Content-MD5 header in WebApi Response	response.Content.Headers.ContentMD5 = MD5.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(result));	0
20349970	20349771	Assign default value to property	class Class1\n{\n    string sUrl = "www.google.com";\n    public string Url\n    {\n        get\n        {\n            return sUrl;\n        }\n        set\n        {\n            sUrl = value;\n        }\n    }\n}	0
21367553	21366409	accessing a user control from masterpage	//Master page from user control\n    LoginControl control\n\n    Page page = (Page)this.Page;\n    MasterPage master = (MasterPage)page.Master;\n\n    control= (LoginControl )master.FindControl("studentcontrol");\n\n    if (control!= null)\n    {\n        Label1.Text = "found";\n    }	0
2187967	2187845	how to make pre-set public property to private while creating a custom control	[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\npublic new string Mask {\n    get { return base.Mask; }\n    set { base.Mask = value; }\n}	0
18110892	17579923	ComboBoxes not getting populated from stored procedure	sc.CommandType = CommandType.StoredProcedure;\nSqlDataReader dr = sc.ExecuteReader();	0
14924589	14924385	Trying to get all children of a selected object that can have unlimited nested children objects	public List<Folder> GetFolderChildsRecursive(Int32 forlderId)\n{\n    List<Folder> childsOfFolder = context.Folder.Where(e=>e.ParentId == folderId).ToList();\n    foreach(Folder child in childsOfFolder)\n    {\n        List<Folder> childs = GetFoldersRecursive(child.Id);\n        childsOfFolder.AddRange(childs);\n    }\n    return childOfFolder;\n}	0
7256811	7256743	How to determine if a field has 'new' modifier via reflection?	AstBuilder.SetNewModifier	0
11387383	11386954	How to assign variable to buttons in a loop to use those variables on click?	protected void btnKatil_Click(object sender, EventArgs e)\n {\n      string value = ((Button) sender).CommandArgument;\n      Response.Write(value);\n }	0
13832066	13830209	How Parallel Run Of Calling A Method	List<string> links = new List<string>() { link1, link2, link3};\n\nConcurrentDictionary<string, string> summariesByLink = new ConcurrentDictionary<string, string>();\n\nParallel.ForEach(links, link => {\n\n  if (!string.IsNullOrEmpty(link))\n  {\n    string[] link_ar = link.Split(sep, StringSplitOptions.None);\n    string page = link_ar[1];\n    string filter = link_ar[2];\n    string code = link_ar[3];\n    string summary = MyMethod( page, filter, code);\n\n    summariesByLink.Add(link, summary);\n  }\n}	0
1328214	1327134	BOM encoding for database storage	Encoding utf8onlynotasridiculouslysucky= new UTF8Encoding(false);	0
7670449	7670399	Calculation in List with Duplications	var q = from u in users\n                group u by u.ID into g\n                select new user { ID = g.Key, money = (int)g.Average(u => u.money) };\n\n        foreach (user u in q)\n        {\n            Console.WriteLine("{0}={1}", u.ID, u.money);\n        }	0
18655364	18654747	Redirecting to a webpage when an error occurs in a view	protected void Application_Error(object sender, EventArgs e) {\n  Exception exception = Server.GetLastError();\n  Response.Clear();\n\n  HttpException httpException = exception as HttpException;\n\n  if (httpException != null) {\n    string action;\n\n    switch (httpException.GetHttpCode()) {\n      case 404:\n        // page not found\n        action = "HttpError404";\n        break;\n      case 500:\n        // server error\n        action = "HttpError500";\n        break;\n      default:\n        action = "General";\n        break;\n      }\n\n      // clear error on server\n      Server.ClearError();\n\n      Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));\n    }	0
11518600	11518529	How to call a button click event from another method	private void SubGraphButton_Click(object sender, RoutedEventArgs args)\n    {\n    }\n\n    private void ChildNode_Click(object sender, RoutedEventArgs args)\n    {\n       SubGraphButton_Click(sender, args);\n    }	0
28101201	28078037	C# VSTO Access Sheet Control from Form	public frmInput()\n{\n    InitializeComponent();\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    Globals.sheet1.textbox1.text="Test"; //I was missing Globals\n}	0
21664289	21664167	SaveAs() file in Application's folder from fileUpload in ASP C#	if (FileUpldFile.HasFile)\n            {\n            string savelocation=Server.MapPath("~/Documents/");\n                try\n                {\n                    //saving the file\n                    FileUpldLicenceFileMOT.SaveAs(savelocation + FileUpldFile.FileName);\n    ...	0
22910026	22909730	How to access the a particular value from the data table?	string temp;\nString query="Your Query that retrieves the data you want";\nSqlCommand cmd=new SqlCommand(query,con);//con is your connection string\nDataTable dt=new DataTable();\ncon.Open();//Open your connection to database\nSqlDataAdapter da=new SqlDataAdapter(cmd);\nda.Fill(dt);\nif(dt.Rows.Count>0)\n{\n    temp=dt.Rows[0]["SlNo"].ToString();\n}\ncon.Close();	0
4562591	4541619	.NET - Long Line in RichTextBox Wrapped after 3,510 Characters	richTextBox1.RightMargin = \nTextRenderer.MeasureText(sb.ToString(), this.richTextBox1.Font).Width;	0
22831331	22831126	To call a method in usercontrol from another user control in asp.net	protected void Save_Click(object sender, EventArgs e)\n        {\n\n         Sample1 ctrlB = new Sample1();\n\n            ctrlB.IsValid();\n      }	0
15136418	15135717	how to get Audit failurelog for windows security log in c#	class Program\n{\n    static void Main(string[] args)\n    {\n        EventLog log = EventLog.GetEventLogs().First(o => o.Log == "Security");\n        log.EnableRaisingEvents = true;\n        log.EntryWritten += (s, e) => { Console.WriteLine(e.Entry.EntryType); };\n        Console.WriteLine(log.LogDisplayName);\n        Console.ReadKey();\n    }\n}	0
3297403	3297360	How to fix error in exporting Excel data to SQL Server database?	INSERT INTO Table1 SELECT ISNULL(YourColumn, GETDATE()) FROM OPENROWSET(...)	0
20408586	20408315	Wait for all threads to finish	var directories = Directory.EnumerateDirectories(path, "*"\n    , SearchOption.AllDirectories);\n\nvar query = directories.AsParallel().Select(dir =>\n{\n    var files = Directory.EnumerateFiles(dir, "*.mp3"\n        , SearchOption.TopDirectoryOnly);\n    //TODO create custom object and add files\n});	0
26767708	26767383	Don't split between specific characters	string s = "The quick /little brown/ fox";\nstring[] result = Regex.Matches(s, @"((/.+/)|(\b\w+\b))").Cast<Match>().Select(m => m.Value).ToArray();\nresult.ToList().ForEach(x => Console.WriteLine(x));	0
31081373	30196128	Listbox SelectedItem binding to UserControl	public static readonly DependencyProperty SelectedProperty = DependencyProperty.Register(\n    SelectedPropertyName,\n    typeof(object),\n    typeof(TileContainer),\n    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));	0
9913234	9912988	how can i add items which are checked to arraylist  in Gridview c# asp.net	protected void SelectedFriends_Click(object sender, EventArgs e)\n      {\n\n        list.Clear();\n\n        foreach (GridViewRow row in GridView1.Rows)\n        {\n            // Access the CheckBox\n            CheckBox cb = (CheckBox)row.FindControl("FriendSelector");\n\n            if (cb != null && cb.Checked)\n            {\n\n                string friendname = GridView1.Rows[row.RowIndex].Cells[1].Text.ToString();\n                list.Add(friendname);\n\n            }\n         }\n\n\n    }	0
8967495	8964199	How can I scrape text based on a fields ID using WatiN?	using (myIE)\n        {\n            //this loads the website\n            myIE.GoTo(txtbxWebSite.Text);                \n            //stores the text from the area on the site in a string called 'temp'\n            string temp = myIE.Div(Find.ById("doc-original-text")).ToString();\n            //displays the string scraped\n            MessageBox.Show(temp); }	0
14116940	14116824	WinForm : How to exclusively dock on a side of a screen	Application Desktop Toolbars	0
15767630	15748949	Move Up, Move Down Buttons for ListBoxes in Visual Studio	private void btnUp_Click(object sender, EventArgs e)\n{\n    MoveUp(ListBox1);\n}\n\nprivate void btnDown_Click(object sender, EventArgs e)\n{\n    MoveDown(ListBox1);\n}\n\nvoid MoveUp(ListBox myListBox)\n{\n    int selectedIndex = myListBox.SelectedIndex;\n    if (selectedIndex > 0)\n    {\n        myListBox.Items.Insert(selectedIndex - 1, myListBox.Items[selectedIndex]);\n        myListBox.Items.RemoveAt(selectedIndex + 1);\n        myListBox.SelectedIndex = selectedIndex - 1;\n    }\n}\n\nvoid MoveDown(ListBox myListBox)\n{\n    int selectedIndex = myListBox.SelectedIndex;\n    if (selectedIndex < myListBox.Items.Count - 1 & selectedIndex != -1)\n    {\n        myListBox.Items.Insert(selectedIndex + 2, myListBox.Items[selectedIndex]);\n        myListBox.Items.RemoveAt(selectedIndex);\n        myListBox.SelectedIndex = selectedIndex + 1;\n\n    }\n}	0
21523405	21523307	Save data in local variable using by silverlight(wcf+linq) connection	void serv_GetAssetList(object sender, ServiceReference.GetAssetListCompletedEventArgs e)\n    {\n\n   MessageBox.show(e.result.count);\n\n\n    }	0
355852	355813	Abstracting UI data formatting	litWeight.Text = Utility.FormatWeight(person.Weight);	0
20777510	20751449	Linq to sql to return related data	var m = db.UserModels.Include(u => u.Roles);\nreturn View(m.ToList());	0
7043279	7002341	Open XML - How to add a watermark to a docx document	static void Main(string[] args)\n{\n    //var doc = WordprocessingDocument.Open(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", true);\n    //AddWatermark(doc);\n    //doc.MainDocumentPart.Document.Save();\n    byte[] sourceBytes = File.ReadAllBytes(@"C:\Users\loggedinuser\Desktop\TestDoc.docx");\n    MemoryStream inMemoryStream = new MemoryStream();\n    inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length);\n\n    var doc = WordprocessingDocument.Open(inMemoryStream, true);\n    AddWatermark(doc);\n    doc.MainDocumentPart.Document.Save();\n\n    doc.Close();\n    doc.Dispose();\n    doc = null;\n\n    using (FileStream fileStream = new FileStream(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", System.IO.FileMode.Create))\n    {\n        inMemoryStream.WriteTo(fileStream);\n    }\n\n    inMemoryStream.Close();\n    inMemoryStream.Dispose();\n    inMemoryStream = null;\n}	0
34169283	34169143	Putting string from array into label in C#. What is wrong with this code?	public partial class Form1 : Form\n    {\n    public string[] words = new string[8] { "MIS3640", "is", "called", "Problem", "Solving", "and", "Software", "Design" };\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    private void button1_Click(object sender, EventArgs e)\n    {\n\n        label1.Text = "";\n        for (int i = 0; i < words.Length; i++)\n        {\n            addTo(words[i]);\n        }\n    }\n\n    private void addTo(string words)\n    {\n        label1.Text = label1.Text + " " + words;\n    }\n   }	0
10057111	10057066	Find position of minimum element in array	Tuple<int, int, int> minimumIndex = null;\ndouble minimumValue = Double.Max;\n\nfor (var i = 0; i < _mapSize; i++) {\n  for (var j = 0; j < _mapSize; j++) {\n    for (var k = 0; k < _lastDimension; k++) {\n      var current = _distance[i][j][k];\n      if (current <= minimumValue) {\n        minimumValue = current;\n        minimumIndex = Tuple.Create(i, j, k);\n      }\n    }\n  }\n}\n\nConsole.WriteLine("{0} {1} {2}", minimumIndex.Item1, minimumIndex.Item2, minimumIndex.Item3);	0
12019781	12019687	Crash on user control custom event	void ImageButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n{\n    if ((mouse_down) && (mouse_in) && Click != null)\n    {\n        Click(this, null);\n    }\n    mouse_down = false;\n}	0
3523543	3523494	Select integers from string[], and return int[]	var numbers = values.Select(\n    s => {\n        int n;\n        if (!int.TryParse((s ?? string.Empty), out n)) \n        {\n            return (int?)null;\n        }\n        return (int?)n;\n    }\n)\n.Where(n => n != null)\n.Select(n => n.Value)\n.ToArray();	0
19229997	19229051	How can I select distinct column combinations from a DataTable object with another column as a condition?	DataView dv = new DataView(dt);\n            dv.Sort = "ID ASC, HireDate DESC, TermDate DESC";\n\n            string lastID = "0";\n            List<DateTime> addedHireDatesForUser = new List<DateTime>();\n\n            foreach (DataRowView drv in dv)\n            {\n                if (drv["ID"].ToString() != lastID)\n                {\n                    addedHireDatesForUser = new List<DateTime>();\n                    addedHireDatesForUser.Add(DateTime.Parse(drv["HireDate"].ToString()));\n\n                    // NEXT ID, ADD ROW TO NEW DATATABLE\n                }\n                else if (!addedHireDatesForUser.Contains(DateTime.Parse(drv["HireDate"].ToString())))\n                {\n                    addedHireDatesForUser.Add(DateTime.Parse(drv["HireDate"].ToString());\n\n                    // NEXT DATE, ADD ROW TO NEW DATATABLE\n                }\n\n                lastID = drv["ID"].ToString();\n            }	0
33460761	33460345	SqlBulkCopy - Add rows along with additional values to database	DbDataReader dr = command.ExecuteReader();\n\nDataTable table = new DataTable("Customers");\ntable.Load(dr);\ntable.Columns.Add("StudentId", typeof(int));\ntable.Columns.Add("BatchCode", typeof(string));\ntable.Columns.Add("Email", typeof(string));\n\nforeach (DataRow row in table.Rows)\n{\n    row["StudentId"] = GetStudentId(row);\n    row["BatchCode"] = GetBatchCode(row);\n    row["Email"] = GetEmail(row);\n}\n\n\n// SQL Server Connection String\nstring sqlConnectionString = @"Data Source=sample;Initial Catalog=ExcelImport;User ID=sample;Password=sample";\n\n// Bulk Copy to SQL Server \nSqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);\nbulkInsert.DestinationTableName = "Customer_Table";\nbulkInsert.WriteToServer(table);	0
13574486	13574442	Trying to send a file to another class in C#	if (ofd.ShowDialog(this).Equals(DialogResult.OK))\n{\n    var path = ofd.FileName;\n\n    //Pass the path to the dataPoints class and open the file in that class.\n}	0
31856243	31855550	Cannot add item to memory cache after item expiration	MemoryCache cache = new MemoryCache("C");\nCacheItemPolicy policy = new CacheItemPolicy\n{\n    UpdateCallback = null,\n    SlidingExpiration = new TimeSpan(0, 0, 5)\n};\n\ncache.Add("key", "value", policy);\nConsole.WriteLine("1) " + cache.Get("key")); // Prints `1) value`\n\nSystem.Threading.Thread.Sleep(5250); // Wait for "key" to expire\nConsole.WriteLine("2) " + cache.Get("key")); // Prints `2) `\n\n// Just showing the the cache policy still works once an item expires.\ncache.Add("key2", "value2", policy);\nConsole.WriteLine("3) " + cache.Get("key2")); // Prints `3) value2`\n\nSystem.Threading.Thread.Sleep(5250); // Wait for "key2" to expire\nConsole.WriteLine("4) " + cache.Get("key2")); // Prints `4) `	0
7335683	7335630	Problem with LINQ to XML	var items= xdoc.Root.Elements("ITEM");	0
12744185	12731658	Linq2Xml - how to get nodes and childnodes related	foreach (var flight_item in l_flights)\n        {\n\n            Console.Write('\n'+"New flight item:"+'\n');\n            Console.Write('\t'+flight_item.arrivalDateTime + '\n');\n            Console.Write('\t'+flight_item.arrivingCity + '\n');\n\n            foreach (var item in flight_item.crewmember)\n            {\n                var employeeId = item.Element(s + "employeeId").Value;\n                var isDepositor = item.Element(s + "isDepositor").Value;\n                var isTransmitter = item.Element(s + "isTransmitter").Value;\n\n                Console.Write("\t  " + employeeId + "\n");\n                Console.Write("\t  " + isDepositor + "\n");\n                Console.Write("\t  " + isTransmitter + "\n");\n\n            }\n\n        }	0
2184105	2178046	WPF ContentControl : how to change control opacity in disabled mode in .cs file?	public override void OnApplyTemplate()\n{\n    //...\n    if (this.IsEnabled == false)\n    {\n        this.Opacity = 0.4;\n    }\n}	0
26547730	26547499	how can I do change color of text when pressed / after that press / again? like comment in visual	private void richTextBox1_KeyUp(object sender, KeyEventArgs e)\n    {\n        if (txtGuid.Text.Contains("//"))\n        {\n            txtGuid.ForeColor = Color.Red;\n        }\n    }	0
13515683	13515581	C#: if else statement with listView	string message = "BAD";\nvar msgColor = System.Drawing.Color.Red;\nforeach (ListViewItem item in listView1.Items)\n{\n    if (item.SubItems[5].Text.Contains("Yes"))\n    {\n        message = "GREAT";\n        msgColor = System.Drawing.Color.Green;\n        break;   // no need to check any more items - we have a match!\n    }\n}\nlabelContainsVideo2.Text = message ;\nlabelContainsVideo2.ForeColor = msgColor;	0
20519425	20519031	How to prepare a string with foreign / accented characters for XML in C#?	string str ="?C?mo puede hacerse esto?";\n        string newMStr = string.Empty; \n\n        foreach (var ch in str)\n        {\n            int chCode = Convert.ToInt16(ch); \n            if (chCode>127)\n            {\n                newMStr += string.Format("&#{0};", chCode);\n            }\n            else\n            {\n                newMStr += ch;    \n            }\n\n\n        }\n\n\n        //Print  NewMstr	0
34001234	34000659	How to replace this switch - case with a Dictionary<string, Func<>>?	private static void Main(string[] args)\n    {\n        var blueHandler = new Action<string, string>((x, y) => { });\n        var redHandler = new Action<int, int>((x, y) => { Console.WriteLine(x);});\n\n        var redStr = "Red";\n        var blueStr = "Blue";\n\n        var colorSelector = new Dictionary<string, Invoker>();\n        var a = 10;\n        var b = 20;\n        colorSelector.Add(redStr, new Invoker(redHandler, a, b));\n        colorSelector.Add(blueStr, new Invoker(blueHandler, a, b));\n\n        colorSelector["Red"].Invoke();\n    }\n\n    public class Invoker\n    {\n        private Delegate _handler;\n        public object[] _param;\n        public Invoker(Delegate handler, params object[] param)\n        {\n            _param = param;\n            _handler = handler;\n        }\n\n        public void Invoke()\n        {\n            _handler.DynamicInvoke(_param);\n        }\n    }	0
16724457	16724227	Saving Items from Listbox to SQL Server table using LINQ	List<Student> students = new List<Student>();\ndouble dub = 0;\nitems = MyListBox.Items.Cast<String>().ToList();\n\nfor (int i = 0; i < items.Length; i++)\n{\n     if (i % 2 == 0)\n     {\n         dub = double.Parse(items[i]);\n     }\n     else\n     {\n         Student s = new Student();\n         s.Name = items[i];\n         s.Marks = dub;\n         students.Add(s);\n     }\n}	0
4275605	4275432	Need guidance regarding Helpprovider	Help.ShowHelp(this, "C:\\Documents and Settings\\Administrator\\Desktop\\ACHWINAPP.chm");	0
2707272	2707269	is there a GetElementByTagName that handles if the tag isn't there	serving.Name = "defaultName";\nXmlNodeList elemList = servingElement.GetElementsByTagName("serving_description");\nif (elemList != null && elemList.Count > 0)\n    serving.Name = elemList[0].InnerText;	0
33247539	33245297	Autoselecting checklist items after I've selected a dropdown list item with a related primary key C# ASP.NET	protected void ddlstore_SelectedIndexChanged(object sender, EventArgs e)\n{\n    int storeId = int.Parse(ddlstore.SelectedValue);\n\n    using (StuffContainer context = new StuffContainer())\n    {\n        var employees = context.Employees\n           .Where(x => x.StoreId == storeId)\n           .Select(x => x.Id).ToList();\n        var customers = context.Customers\n           .Where(x => x.StoreId == storeId)\n           .Select(x => x.Id).ToList();\n\n        foreach(ListItem item in chkemp.Items)\n            item.Selected = employees.Contains(int.Parse(item.Value));\n\n        foreach(ListItem item in chkcust.Items)\n            item.Selected = customers.Contains(int.Parse(item.Value));\n    }\n}	0
2858222	2857606	Can we change the text/background color of an individual property in PropertyGrid	private /*protected virtual*/ PropertyGridView CreateGridView(IServiceProvider sp) {\n        return new PropertyGridView(sp, this);\n    }	0
12651855	12651806	Get next event in sequence every second with reactive-extensions	Observable<NewsItem> nis = _source\n    .Zip(Observable.Timer(Timespan.FromSeconds(5), TimeSpan.FromSeconds(5)), (e, _) => e)\n    .Select(eventArgs => eventArgs.Item);	0
9456453	9456211	Castle Windsor Register Component by Convention	var container = new WindsorContainer();\ncontainer.Register(\n    AllTypes.FromAssemblyContaining<EntityFrameworkLinkRepository>()\n        .BasedOn<IRepository>()\n        .WithService.Select((type, types) => type.BaseType != null && type.Name.EndsWith(type.BaseType.Name)\n                                                    ? new[] {type.BaseType}\n                                                    : Enumerable.Empty<Type>()));	0
5026238	5025509	How to estimate method execution time?	public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)   \n   {\n       var iar = F.BeginInvoke(null, new object());\n       if (iar.AsyncWaitHandle.WaitOne(Timeout))\n       {\n           Completed = true;\n           return F.EndInvoke(iar);\n       }\n         F.EndInvoke(iar); //not calling EndInvoke will result in a memory leak\n         Completed = false;\n       return default(T);\n   }	0
32943607	32943535	How do I use data I receive from API in JSON format?	List<Medio> list = JsonConvert.DeserializeObject<List<Medio>>(your_string)	0
22298934	22298815	Calculating a leap year without the leap year function	var year = now.Year;\n\nif (year % 4 == 00 && !(year % 100 == 0 && year % 400 != 0))\n{\n    ....\n}	0
6799134	6799108	grid view count	LinkButton1.Text = "TotalCount (" + Repeater1.Items.Count.ToString() + ")";	0
26820757	26820652	how to insert in multiple sql table with only one function of add in DAL class c#	string q=@"insert into t1(ID,name) values('A','ABC');\n           insert into t2(ID2,name2) values('B','DEF');\n           insert into t3(ID3,name3) values('C','GHJ')";\ncmd=new SqlCommand(q,con);\ncon.open();\ncmd.ExecuteNonQuery();	0
17013962	17013947	Dropdown Returning Wrong value asp.net server control	if(!IsPostBack)\n{\n  joblist = util.getJobList(orgid);\n  this.joblistdropdown.DataSource = joblist;\n  joblistdropdown.DataTextField = "Jobtitle";\n  joblistdropdown.DataValueField = "Id";\n  this.joblistdropdown.DataBind();\n}	0
8477697	8477664	How can I generate UUID in C#	System.Guid.NewGuid()	0
33087046	33086170	Two borders for panel	e.Graphics.DrawRectangle(pen1, \n    this.ClientRectangle.Left, this.ClientRectangle.Top,\n    this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1);\ne.Graphics.DrawRectangle(pen2, \n    this.ClientRectangle.Left + 1, this.ClientRectangle.Top + 1,\n    this.ClientRectangle.Width - 3, this.ClientRectangle.Height - 3);	0
16511973	16511939	Restful API GET failing with 'The parameters dictionary contains a null entry for parameter 'id' of non-nullable type' '	//public List<Models.DirectionChoices> Get([FromUri]string q)\n   public List<Models.DirectionChoices> Get([FromUri]string id)	0
22951313	22781143	how to get session of username and update his username to the database whenever the user updates the gridview?	string strCommandText = "UPDATE EntryTable SET [ModifiedBy]=@Modifier, [Name]=@Name, [BlogType]=@BlogType, [Description]=@Description, [DateEntry]=@DateEntry, [BlogStory]=@BlogStory WHERE [BlogID]=@BlogID";\n\nSqlCommand cmd = new SqlCommand(strCommandText, myConnect);\ncmd.Parameters.AddWithValue("@BlogID", blogid);\ncmd.Parameters.AddWithValue("@Name", strName);\ncmd.Parameters.AddWithValue("@BlogType", strBlogType);\ncmd.Parameters.AddWithValue("@DateEntry", datDate);\ncmd.Parameters.AddWithValue("@Description", strDescription);\ncmd.Parameters.AddWithValue("@BlogStory", strBlogStory);\ncmd.Parameters.AddWithValue("@Modifier", Session["Username"]);	0
7034196	7033890	C# convert an ArrayList of type ints into a Point[]	public Point[] ToPointGrid(int width, int height)\n{\n  Point[] points = new Point[dataList.Count];\n  for(int index = 0; index < dataList.Count; ++index)\n  {\n    points[index] = new Point(index, height - (dataList[index] * height) / range + (minimum * height) / range);\n  }\n  return points;\n}	0
33871210	33869167	How to have concept of some dynamic class	void Main()\n{\n    var a = new A(){ Name = "A" };\n    var b = new B(){ Name = "B" };\n\n    INameProvider provider = new BNext(b);  \n    //...   \n}\n\n//original classes  \npublic class A{\n\n    public string Name { get; set; }\n}\n\npublic class B{\n\n    public string Name { get; set; }\n    public string Id { get; set; }\n}\n\n//common interface\npublic interface INameProvider {\n    string Name { get; set; }\n}\n\n//adapters\npublic class ANext : A, INameProvider \n{\n    public ANext(A a)\n    {\n        this.Name = a.Name;     \n    }\n}\n\npublic class BNext : B, INameProvider \n{\n    public BNext(B b)\n    {\n        this.Name = b.Name;\n        this.Id = b.Id;\n    }\n}	0
2002419	2001700	How to optimize memory usage in this algorithm?	Enum LogReason { Operation, Error, Warning };\nEnum EventKind short { DataStoreOperation, DataReadOperation };\nEnum OperationStatus short { Success, Failed };\n\nLogRow\n{\n  DateTime EventTime;\n  LogReason Reason;\n  EventKind Kind;\n  OperationStatus Status;\n}	0
13022424	13022362	How can I query Windows 8's People app?	ContactPicker cp = new ContactPicker();\nvar contacts =  await cp.PickMultipleContactsAsync();\nif (contacts != null && contacts.Count > 0)\n{\n    MessageDialog md = new MessageDialog(contacts[0].Name);\n    md.ShowAsync();\n}	0
14007348	14007334	How to convert FileInfo into FileInfo[]	paths.Select(p => new FileInfo(p)).ToArray();	0
2029173	2027808	Get list of supported fonts in ITextSharp	Dim myCol As ICollection\n  //Returns the list of all font families included in iTextSharp.\n  myCol = iTextSharp.text.FontFactory.RegisteredFamilies\n  //Returns the list of all fonts included in iTextSharp.\n  myCol = iTextSharp.text.FontFactory.RegisteredFonts	0
16280611	16280571	How can i get the Complete user name in Windows 7 using WPF?	Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\nWindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;\n// or, if you're in Asp.Net with windows authentication you can use:\n// WindowsPrincipal principal = (WindowsPrincipal)User;\nusing (PrincipalContext pc = new PrincipalContext(ContextType.Domain))\n{\n    UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);\n    thisUsername = up.DisplayName;\n    // or return up.GivenName + " " + up.Surname;\n}	0
2539293	2539272	How do I return the first string variable that isn't null or emtpy	var myString = new string[]{first, second, third, fouth, fifth}\n      .FirstOrDefault(s => !string.IsNullOrEmpty(s)) ?? "";\n\n//if myString == "", then none of the strings contained a value	0
29012630	29009788	Invoke a SignalR hub from controller in MVC	//somewhere you setup your connection once, you decide where\n//variables should probably be members of some class\nvar hubConnection = new HubConnection("http://your_end_point:port/");\nvar hubProxy = hubConnection.CreateHubProxy("MyHub");\nawait hubConnection.Start();\n...\n//somewhere else in your controller you use the proxy to do your calls\nhubProxy.Invoke("AddMessage", "foo", "bar");	0
17720423	17720250	Insert Update Delete in DataTable in gridview	myGridView.DataSource = myDataTable;\nmyGridView.DataBind();	0
10390034	10389837	Trying to save a manual DataTable to my SQL Server CE table	using (SqlCeConnection con = new SqlCeConnection(connectionString))   \n{   \n    con.Open();   \n    SqlCeCommand cmd = new SqlCeCommand("Select * from MyTable1 Where 1=0", con);\n    SqlCeDataAdapter da = new SqlCeDataAdapter();\n    da.SelectCommand = cmd;\n    SqlCeCommandBuilder cb = new SqlCeCommandBuilder(da);\n    da.Update(table1);\n}	0
26917433	26914395	EF backward compatible DB migrations	public class MyDBContext: DbContext \n{\n    public MyDBContext() : base("myConnString")\n    {            \n        //Disable initializer\n        Database.SetInitializer<MyDBContext>(null);\n    }\n    public DbSet<A> As { get; set; }\n    public DbSet<B> Bs { get; set; }\n}	0
9898497	9826843	Consuming a webservice php with C#	minOccurs="1" maxOccurs="1"	0
14251134	14251114	How to add all active forms names to menustrip items in windows application C#	foreach (Form form in Application.OpenForms)\n{\n    ms.Items.Add(form.Name);\n}	0
34408773	34406099	How to SendAndSave email with EWS with windows auth and identity without a mailbox?	EmailMessage test2 = new EmailMessage(service);\nString bodyContent = "<html><head><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">Hello World</head><body></body></html> ";\n\nCDO.Message msMessage = new CDO.Message();\nmsMessage.BodyPart.Charset = "UTF-8";\nmsMessage.HTMLBody = bodyContent;\nmsMessage.HTMLBodyPart.Charset = "UTF-8";\nmsMessage.AddAttachment("c:\\temp\\Document.docx");\nADODB.Stream asMessageStream = msMessage.GetStream();\nasMessageStream.Type = ADODB.StreamTypeEnum.adTypeBinary;\nbyte[] bdBinaryData1 = new byte[asMessageStream.Size];\nbdBinaryData1 = (byte[])asMessageStream.Read(asMessageStream.Size);\nservice.TraceEnabled = true;\ntest2.MimeContent = new MimeContent("UTF-8", bdBinaryData1);\ntest2.ToRecipients.Add("user@domain.com");\ntest2.Subject = "test";\ntest2.SendAndSaveCopy();	0
23006811	23006289	How to attach local html file with project	var localURL = Path.Combine(Directory.GetCurrentDirectory(), "PrintAds.htm");\nthis.webBrowser1.Url = new System.Uri(localURL, System.UriKind.Absolute);	0
2109796	2107463	Is there a way to color tabs of a tabpage in winforms?	private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)\n{\n    // This event is called once for each tab button in your tab control\n\n    // First paint the background with a color based on the current tab\n\n   // e.Index is the index of the tab in the TabPages collection.\n    switch (e.Index )\n    {\n        case 0:\n            e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds);\n            break;\n        case 1:\n            e.Graphics.FillRectangle(new SolidBrush(Color.Blue), e.Bounds);\n            break;\n        default:\n            break;\n    }\n\n    // Then draw the current tab button text \n    Rectangle paddedBounds=e.Bounds;\n    paddedBounds.Inflate(-2,-2);  \n    e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, this.Font, SystemBrushes.HighlightText, paddedBounds);\n\n}	0
18315957	18315885	Get static property of class from generic type parameter	typeof(TEntity).GetProperty("MyProp", BindingFlags.Public | BindingFlags.Static)	0
18631762	18631710	implictly typed local variable 'var' to an explicitly typed local variable	IEnumerable<dynamic> collection = Enumerable.Range(0, 10).Where(x => x % 2 != 0)\n      .Reverse()\n      .Select(x => new { original = x, sqrt = Math.Sqrt(x) });	0
15498426	15497518	how to add html control "anchor tag" dynamically in gridview?	TemplateField t = new TemplateField();\n        DynamicTemplate mt = new DynamicTemplate(ListItemType.Item);\n\n        HtmlImage img = new HtmlImage();\n        img.ID = "btnEdit";\n        img.Src = "~/images/image.gif";\n        img.Alt = "An image";\n        img.Attributes.Add("class", "cssimage");\n        mt.AddControl(img, "Text", "Edit");\n        t.ItemTemplate = mt;\n        t.HeaderText = "Activity";\n        GridView1.Columns.Add(t);\n        GridView1.DataSource = dtOutPutResult;\n        GridView1.DataBind();	0
11679667	11676807	Parallelization of CPU bound task continuing with IO bound	BlockingCollection<T>	0
3420591	3420522	assign to a generic collection from a generic collection inside collection + linq + C#	var students = GetAllStudentCollection();\nvar subjects = students.SelectMany(stu=>stu.StudentSubjectCollection);	0
18987806	18987737	.get List<string> from controller method and display	public JsonResult Search(string input, SearchBy searchBy)\n  {          \n        Manager manger = new Manager();\n        List<string> MyList = manger.GetData(input, searchBy);                                                         \n        return Json(MyList, JsonRequestBehavior.AllowGet);\n  }	0
14160612	14159426	Should factories set model properties?	var model = this.factory.Create();\nmodel.Id = 10;\nmodel.Name = "X20";	0
3717713	3717429	How to create LINQ to SQL Group by with condition?	bool someFlag = false;\nvar result = from t in tableName\n      group t by new { FieldA = (someFlag ? 0 : t.FieldA), t.FieldB } into g\n      select g;	0
19686960	19686870	How to access Canvas.Left property of a StackPanel in code?	Canvas.SetLeft(myStackPanel, newValue);	0
18257930	18257834	Get the first occurance in a dictionary LINQ	Caption = string.Format("{0}_{1}",\n                        benefits.Where(b => b.Key == p.BenefitID)\n                                .Select(b => b.Value)\n                                .FirstOrDefault(), // Or First\n                        p.Name);	0
303294	302558	Debugging any entry point	System.Diagnostics.Debugger.Break()	0
14439063	14438133	Castle Dynamic Proxy how to merge data in CreateClassProxyWithTarget	public static class MongoExtensions\n{\n    static readonly ProxyGenerator pg = new ProxyGenerator();\n    public static MongoCollection GetRetryCollection(this MongoDatabase db, string collectionName, int retryCount = 5, int pauseBetweenRetries = 2000)\n    {\n        var coll = db.GetCollection(collectionName);\n        return (MongoCollection)pg.CreateClassProxyWithTarget(typeof(MongoCollection), coll, new object[] { db, collectionName, coll.Settings }, new RetryingInterceptor { RetryCount = retryCount, PauseBetweenCalls = pauseBetweenRetries });\n    }\n}	0
4235170	4235008	C# file/folder monitor	// for file\nfileSysWatchFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;\n// for folder\nfileSysWatchDir.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.LastWrite;	0
1721972	1617107	Entity Framework - partial commit	foreach (System.Data.Objects.ObjectStateEntry x in MyEntity.ObjectStateManager.GetObjectStateEntries(EntityState.Added)) // or modified for that matter.\n{\n   if (x.EntityKey != null)\n   {  \n      if (x.Entity is MyClass) // look haven't tested this code, merely example and may have typo's\n      {\n         MyClass tmpObject = (MyClass)x.Entity;\n         MyEntity.Refresh(RefreshMode.StoreWins, x);\n      }\n   }\n}	0
17349919	17348383	Align two chart areas windows forms	if (this.chrtMain.ChartAreas.Count > 0)\n  {\n    ca.AlignmentOrientation = AreaAlignmentOrientations.Vertical;\n    ca.AlignWithChartArea = this.chrtMain.ChartAreas[0].Name;\n  }	0
26508750	26506319	How to spawn a collider after exiting a trigger? (Bomberman style game)	public class bomb : MonoBehaviour {\n\nBoxCollider collider;\n\nvoid Start () {\n    collider = gameObject.GetComponent<BoxCollider> ();\n}\n\nvoid OnTriggerExit(Collider other)\n{\n    collider.isTrigger = false;\n\n}	0
1890057	1890008	C# Linq finding value	var q = from m in context.Depts\n        where\n        !context.Persons.Select(p => p.DeptID).Contains(m.DeptID)\n        select new { DeptID = m.DeptID };	0
3108817	3108792	How to use combination of enums in switch case in c#?	[Flags]\npublic enum UploaderType\n{\n    None = 0,\n    BrandLogo = 1,\n    ReportingLogo = 2,\n    DocumentTemplate = 4,\n    MModalTemplate = 8,\n}	0
9105116	9099756	trying to create a custom cmdlet, which takes [ref] as a parameter	protected override void ProcessRecord() \n{ \n    //main method, this is executed when cmdlet is run \n    int r = Convert.ToInt32(this.Remainder.Value); \n    int q = _csharpDivideRemainderQuiotent(a,b, ref r);\n    this.Remainder.Value = r;\n    WriteObject(q); \n}	0
22213548	22213268	how to transform the following in C#?	public TreeView ConvertNode(Node rootNode)\n{\n    var tree = new TreeView\n    {\n        Id = rootNode.AutoIncrementId,\n        Text = rootNode.Text,\n        Items = new List<TreeView>()\n    };\n\n    if (rootNode.Nodes != null)\n    {\n        foreach (var node in rootNode.Nodes)\n        {\n            tree.Items.Add(ConvertNode(node));\n        }\n    }\n\n    return tree;\n}	0
4031937	4031889	How do I transfer a file to a function, if it lies in internete	public form1()\n{\n    InitializeComponent();\n\n    System.Net.WebClient Client = new WebClient();\n    Stream strm = Client.OpenRead("http://www.csharpfriends.com");\n    StreamReader sr = new StreamReader(strm);\n    string line;\n    do\n    {\n        line = sr.ReadLine();\n        listbox1.Items.Add(line);\n    }\n    while (line !=null);\n    strm.Close();\n}	0
11789167	11789125	Accessing a Web Control in a User Control from the User Control's constructor	public partial class NewsArticleContainer : System.Web.UI.UserControl\n{\n   List<string> NewsArticle = null;\n   public NewsArticleContainer(List<string> toCreateNewsArticle)\n   {\n      NewsArticle = toCreateNewsArticle;\n   }\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n       foreach(string s in NewsArticle)\n       {\n          //dynamically create your label control and add it to this user control\n          Label lb = new Label;\n          lb.Text = s;\n          this.Controls.Add(lb);\n       }\n    }\n}	0
9402552	9402081	Reading a list of links in xml	XElement x = XElement.Parse(e.Result);\nIEnumerable<XElement> links = x.Elements("link");\nforeach(XElement link in links)\n{\n    .... read node logic ....\n}	0
23079933	22968256	How to force cleanup of BitmapImage in Silverlight	private static async Task<BitmapImage> LoadBitmapImageAsync(byte[] imageData)\n    {\n        BitmapImage bi = new BitmapImage();\n\n        TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>();\n\n        EventHandler<RoutedEventArgs> openedHandler = (s2, e2) => taskCompletionSource.TrySetResult(null);\n        EventHandler<ExceptionRoutedEventArgs> failedHandler = (s2, e2) => taskCompletionSource.TrySetResult(null);\n\n        bi.ImageOpened += openedHandler;\n        bi.ImageFailed += failedHandler;\n\n        using (MemoryStream memoryStream = new MemoryStream(imageData))\n        {\n            bi.SetSource(memoryStream);\n        }\n\n        await taskCompletionSource.Task;\n\n        bi.ImageOpened -= openedHandler;\n        bi.ImageFailed -= failedHandler;\n        return bi;\n    }	0
29392550	29391335	How to pass data from childform to parentform	public partial class Form2 : Form\n{\n    public Form2(Form1 frm1)\n    {\n        InitializeComponent();\n        Form1Prop = frm1;\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Form1Prop.SetFilepath("HIHI");\n\n        Form1Prop.DataGridPropGrid.Rows.Add("HIH", "KI", "LO", "PO");\n    }\n\n    public Form1 Form1Prop { get; set; }\n}\n\n\n\n\n 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        Form2 frm2 = new Form2(this);\n        frm2.Show();\n    }\n\n    public void SetFilepath(string filepath)\n    {\n        textBox1.Text = filepath;\n    }\n\n    public DataGridView DataGridPropGrid\n    {\n        get\n        {\n            return dataGridView1;\n        }\n    }\n}	0
8073032	8072975	Please help on regex in c#	0[0-9]{3}[wn][d0]0{2}[a-z0-9]{7}	0
2092551	2092538	Getting Parent Page name	window.opener	0
25569524	25569379	Can I perform action before/after all tests	[CodedUITest]\npublic class MyTestClass\n{\n    [ClassInitialize]\n    public void DoSomethingFirst()\n    {\n        // your code here that will run at the beginning of each test run.\n    }\n\n    [TestInitialize]\n    public void RunBeforeEachTest()\n    {\n        // your test initialization here\n    }\n\n    [TestMethod]\n    public void MyTestMethod()\n    {\n    }\n}	0
23782849	23777237	Excel interop how to set text direction from left to right	Workbook xlWorkbook = null;\n            _Worksheet xlWorksheet = null;\n\n           //Open work sheet\n            xlApp.Visible = false;\n            xlWorkbook = xlApp.Workbooks.Open(file, Type.Missing, false);\n            xlWorksheet = xlWorkbook.Sheets[1];\n\n            //Gets relevant column\n            Range range = (Range)xlWorksheet.get_Range(column, Type.Missing);\n\n            //Set text direction\n            range.EntireColumn.ReadingOrder = (int)Constants.xlLTR;\n\n            xlWorkbook.Save();\n\n            System.Runtime.InteropServices.Marshal.ReleaseComObject(range);	0
15924106	15923230	MVVM - Collection with polymorphism	public class FlightViewModel\n{\n    private Flight _flight;\n\n    public FlightViewModel(OutFlight outFlight)\n    {\n        FlightNumber = outFlight.FlightNumber;\n        FlightType = FlightType.OutFlight;\n       _flight = outFlight;\n    }\n\n    public FlightViewModel(InFlight inFlight)\n    {\n        FlightNumber = inFlight.FlightNumber;\n        FlightType = FlightType.InFlight;\n       _flight = inFlight;\n    }\n\n    public int FlightNumber \n    { \n       get { return _flight.FlightNumber; }\n       set { _flight.FlightNumber = value; }\n    }\n\n    public FlightType FlightType { get; set; }\n\n    ... other properties\n}	0
21847564	21847349	unable to open the default mail client	var process = @"mailto:some.guy@someplace.com?subject=an email&body=see attachment";\n System.Diagnostics.Process.Start(process);	0
13248924	13248780	How to get the text sent to console output in an event or method	MemoryStream ms = new MemoryStream();\nProgressStream progressStream = new ProgressStream(ms);\nConsole.SetOut(new StreamWriter(progressStream));	0
8396694	8395508	x-axis label is not shown at right place in ms chart using windows application	Chart1.ChartAreas[0].AxisX.IsMarksNextToAxis = false;	0
14227772	14227501	Remove a portion of XML, edit it, then add back to xml at original position	XElement root = XElement.Parse(input);\n                XElement dataElement = root.Descendants("DATA").FirstOrDefault();\n                XCData cdata = dataElement == null ? null : dataElement.FirstNode as XCData;\n                if (cdata == null)\n                {\n                    return;\n                }\n\n                XElement nestedXml = XElement.Parse(cdata.Value);\n                XNamespace ns = @"http://www.com";\n                var com = nestedXml.Descendants(ns + "PLACES").First();\n\n                com.Value = "Incomplete App Email sent to member." + com.Value;\n\n                cdata.Value = nestedXml.ToString(SaveOptions.DisableFormatting);\n                string updatedOutput = cdata.ToString();	0
19732261	19732090	WPF how to reset grid row and column sizes to "*" in code	rowDef.Height = new GridLength(1, GridUnitType.Star);	0
1312642	1312591	How to store and retrieve constants that are not configurable in ASP.NET?	public static class DbConstants\n{\n    public static const string CustomersTableName = "CUST";\n    public static const string ProductsTableName = "PROD";\n    ...\n}	0
347370	347347	Data binding to a list inside a data bound object	public class RecipeDetails\n{\n    public RecipeDetails()\n    {\n        _ingredients = new ObservableCollection<RecipeIngredient>();\n    }\n\n    public string Name { get; set; }\n    public string Description { get; set; }\n\n    private ObservableCollection<RecipeIngredient> _ingredients;\n\n    private ObservableCollection<RecipeIngredient> Ingredients\n    {\n        get { return _ingredients; }\n    }\n}	0
2252736	2240018	How to convert in Linq statement and assign correct value	var pcs = collection.ToLookup(a => a.TotType);\n\nforeach(var bttcoll in processResult\n    .PAndLReport\n    .BreakdownTotTypeCollection)\n{\n  var items = pcs[bttcoll.ToTType];\n    //do you have a constructor that takes an IEnumerable<Item> ?\n  bttcoll.BreakdownCollection = new BreakdownCollection(items)\n}	0
22183268	22182132	Cast To Interface	if(request.Sorts.Count == 1)\n        {\n            pRequest.SortMember = request.Sorts[0].Member;\n            pRequest.SortDirection = (int)request.Sorts[0].SortDirection;\n\n        }\n\n        if (request.Filters.Count >= 1)\n        {\n            foreach(var item in request.Filters)\n            {\n               if(item is Kendo.Mvc.FilterDescriptor)\n               {\n                   var descriptor = (Kendo.Mvc.FilterDescriptor)item;\n                   pRequest.Startdate = (DateTime)descriptor.ConvertedValue;\n               }\n            }\n\n        }\n        else\n        {\n            var endDate = new TimeSpan(4000, 0, 0, 0, 0);\n            pRequest.Startdate = DateTime.UtcNow - endDate;\n        }	0
25768718	25768475	get xml node value from xml string	XNamespace ns1 = "http://www.your.example.com/xml/person";\nXNamespace ns2 = "http://www.my.example.com/xml/cities";\n\nvar elem = XElement.Parse(xml);\nvar value = elem.Element(ns2 + "homecity").Element(ns2 + "name").Value;\n\n//value = "London"	0
2849257	2849234	Is there a faster way to check if this is a valid date?	String DateString = String.Format("{0}/{1}/{2}", model_.Date.Month, (7 * multiplier) + (7 - dow) + 2),model_.Date.Year);\n\nDateTime dateTime;\nif(DateTime.TryParse(DateString, out dateTime))\n{\n    // valid\n}	0
24036914	24036788	for a string value how to get "..."	string fName = ofd.FileName;\nif (fName.Length > 10)\n{\n    fName = string.Format("{0}...{1}{2}",\n                Path.GetPathRoot(fName), \n                Path.DirectorySeparatorChar, \n                Path.GetFileName(fName));\n}\ntextBox1.Text = fName;	0
33801898	33801695	Perform action while key is pressed	bool keyHold = false;\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        if (keyHold) \n        {\n            //Do stuff\n        }\n    }\n\n    private void Key_up(object sender, KeyEventArgs e)\n    {\n        Key key = (Key) sender;\n        if (key == Key.A) //Specify your key here !\n        {\n            keyHold = false;\n        }\n    }\n\n    private void Key_down(object sender, KeyEventArgs e)\n    {\n        Key key = (Key)sender;\n        if (key == Key.A) //Specify your key here !\n        {\n            keyHold = true;\n        }\n    }	0
22131850	22129698	When and how to call asynch method in ViewModel in windows phone wp8	public Document Document\n{\n    get { return this._document; }\n    set\n    {\n        if (this._document == value)\n            return;\n        this._document = value;\n        RaisePropertyChanged("Document");\n    }\n}\n\npublic async Task<Document> GetDocument\n{\n    // ...\n}\n\nprivate async Task LoadData()\n{\n    Document = GetDocument();\n}\n\npublic void Initialize() \n{\n    LoadData();\n}	0
28090661	27551485	How do I search Twitter for a specific hashtag? API's	// Pass your credentials to the service\n        TwitterService service = new TwitterService("App_ConsumerKey", "App_ConsumerSecret");\n        service.AuthenticateWith("accessToken", "tokenSecret");\n\n        SearchOptions options = new SearchOptions { Q = "#specifichashtag", Count = 100, Resulttype = TwitterSearchResultType.Recent };\n        var searchedTweets = service.Search(options);	0
32735637	32735581	how to reverse the textbox input method in c#	EPF_NO.PasswordChar = '\0';	0
16935819	16933534	How to set MS Chart LegendItem image size	LegendItem legendItem = new LegendItem();\nLegendCell cell1 = new LegendCell();\ncell1.Name = "cell1";\ncell1.Text = "legend text";\n// here you can specify alignment, color, ..., too\nLegendCell cell2 = new LegendCell();\ncell2.Name = "cell2";\ncell2.CellType = System.Windows.Forms.DataVisualization.Charting.LegendCellType.Image;\ncell2.Image = "path of your img";\ncell2.Size = new Size(.....);\nlegendItem.Cells.Add(cell1);\nlegendItem.Cells.Add(cell2);	0
30077840	30076508	High Score Unity3D using PlayerPrefs	public void PlayerWin()\n    {\n        gameOver = true;\n\n        //Update the highscore\n        float bestTime = 0;\n        bool isNewHighscore = false;\n\n        if (gameTime < PlayerPrefs.GetFloat("Best Time"))\n        {\n            PlayerPrefs.SetFloat("Best Time", gameTime);\n        }\n        //TODO: Not sure if I have done this correct trying to complete the code to read and store the highscore\n\n        bestTime = PlayerPrefs.GetFloat("Best Time"); // ADD THIS LINE HERE\n\n        //Pop up the win message\n        UIController.GameOver(WIN_MESSAGE, gameTime, bestTime, isNewHighscore);\n    }	0
27880226	27880149	Linq expression to join a list and a dictionary	var parts = new List<string> { "part1", "part2", "part3" };\n var quantities = new Dictionary<string, int> { { "part1", 45 }, { "part3", 25 } };\n\n        var result = string.Join("|", \n               from p in parts select quantities.ContainsKey(p) \n                        ? quantities[p].ToString() : "");	0
12787473	12787368	C# datetime parse issue	DateTime testDate = DateTime.ParseExact("2012-08-10T00:51:14.146Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);\n\n        Trace.WriteLine(testDate);  //  8/9/2012 8:51:14 PM\n        Trace.WriteLine(testDate.ToString()); //  8/9/2012 8:51:14 PM\n        Trace.WriteLine(testDate.ToUniversalTime()); //  8/10/2012 12:51:14 AM\n        Trace.WriteLine(testDate.Kind); // Local\n\n       testDate = DateTime.ParseExact("2012-08-10T00:51:14.146Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);\n\n        Trace.WriteLine(testDate);//  8/10/2012 12:51:14 AM\n        Trace.WriteLine(testDate.ToString());//  8/10/2012 12:51:14 AM\n        Trace.WriteLine(testDate.ToUniversalTime());//  8/10/2012 12:51:14 AM\n        Trace.WriteLine(testDate.Kind); // Utc	0
19236993	19232932	How do I get a byte array from HttpInputStream for a docx file?	//viewmodel.File is HttpPostedFileBase\n\nviewModel.File.InputStream.Position = 0; //<-----This fixed it!\n\nbyte[] fileData;\nusing (var binaryReader = new BinaryReader(viewModel.File.InputStream))\n{\n    fileData = binaryReader.ReadBytes(viewModel.File.ContentLength);\n}	0
10379144	10361083	Getting value of a column on click of a row in jqGrid	protected void ModifyAccountUserDetailsjqGrid_RowSelecting(object sender, Trirand.Web.UI.WebControls.JQGridRowSelectEventArgs e)\n        {\n            ModifyAccountUserDetailsjqGrid.SelectedRow;   \n        }	0
4058924	4058776	How can I convert CFAbsoluteTime to DateTime in C#?	TimeSpan span = TimeSpan.FromSeconds(CFAbsoluteTimeFloatValue);\nvar cshartpDateTime = new DateTime(2001, 1, 1).Add(span);	0
11741393	11741365	converting string to List<string>	value.Split(',').ToList();	0
24873822	24873712	c# plug in string value	Dictionary<string, string> map = new Dictionary<string, string>();\nmap["aaa"] = "123";\nmap["bbb"] = "456";\nmap["ccc"] = "789";\n\nwhile (...)\n{\n   Console.WriteLine(lines[counter] + " |" + map[lines[counter]] + "|");\n}	0
33274041	32835743	How to disable xamdatagrid cell editing in wpf	private async void RenewDataGrid_OnCellUpdated(object sender, CellUpdatedEventArgs e)\n{\n    row.Cells[4].IsEnabled = false;\n    DoEvents();\n    await datacontext.CalculateFdtotalAmount();\n    DoEvents();\n    row.Cells[4].IsEnabled = true;\n}\n\n\n\n    public object ExitFrame(object f)\n    {\n        ((DispatcherFrame)f).Continue = false;\n        return null;\n    }\n    public void DoEvents()\n    {\n        DispatcherFrame frame = new DispatcherFrame();\n        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,\n            new DispatcherOperationCallback(ExitFrame), frame);\n        Dispatcher.PushFrame(frame);\n    }	0
5807992	5807947	How to Know This is the Last Iteration of a Loop?	for(int i=0; i<myList.Length; i++) { ... }	0
2481736	2480782	how to call any method of Project from classlibrary?	public Class1(GetDataDelegate getData)\n    {\n        GetData += getData;\n    }\n\n    //blah blah blah\n}	0
17646580	17537276	Binding Selected RowCount to TextBlock not Firing OnPropertyChanged after DataGrid Scroll	Cultures.SelectedItems.CollectionChanged += SelectedItems_CollectionChanged;\n\nvoid SelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n{\n    this.RaisePropertyChanged("TotalSelectedCultures");\n}	0
13392514	13391920	Listbox item change on click WP7	private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n    {\n        var imageSource = ((sender as Image).Source as BitmapImage).UriSource.OriginalString;\n        if (imageSource.Contains("On"))\n        {\n            (sender as Image).Source = new BitmapImage(new Uri("Images/Off.png", UriKind.Relative));\n        }\n        else\n        {\n            (sender as Image).Source = new BitmapImage(new Uri("Images/On.png", UriKind.Relative));\n        }\n    }	0
19764234	19763969	How to provide arguments at startup to application	string cmd = Application.ExecutablePath.ToString() + " /arg1 /arg2 /arg3 .....";\nRegistryKey rk = Registry.CurrentUser.OpenSubKey\n        ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n         rk.SetValue(AppName, cmd);	0
28448962	28447884	How to call Code Behind from server side	cbRating1WithoutExceptionP1_CheckedChanged(null, EventArgs.Empty);	0
30192634	30192020	ASP.NET Splitting string into an array not working from objective-c?	string Items = Request.QueryString["Items"];\nItems = HttpUtility.UrlDecode(Items);\nstring[] ItemsArray = Regex.Split(Items, "*");	0
8519271	8518317	Changing Font Size for ListView Column in C#	// Draws column headers.\nprivate void listView1_DrawColumnHeader(object sender,\n    DrawListViewColumnHeaderEventArgs e)\n{\n    using (StringFormat sf = new StringFormat())\n    {\n        // Store the column text alignment, letting it default\n        // to Left if it has not been set to Center or Right.\n        switch (e.Header.TextAlign)\n        {\n            case HorizontalAlignment.Center:\n                sf.Alignment = StringAlignment.Center;\n                break;\n            case HorizontalAlignment.Right:\n                sf.Alignment = StringAlignment.Far;\n                break;\n        }\n\n        // Draw the standard header background.\n        e.DrawBackground();\n\n        // Draw the header text.\n        using (Font headerFont =\n                    new Font("Helvetica", 10, FontStyle.Bold)) //Font size!!!!\n        {\n            e.Graphics.DrawString(e.Header.Text, headerFont,\n                Brushes.Black, e.Bounds, sf);\n        }\n    }\n    return;\n}	0
216733	207837	Adding functonality to Linq-to-SQL objects to perform common selections	using System;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nclass Program {\n    static void Main(string[] args) {\n        Console.WriteLine(StringPredicate(c => Char.IsDigit(c)));\n        var func = StringPredicate(c => Char.IsDigit(c)).Compile();\n        Console.WriteLine(func("h2ello"));\n        Console.WriteLine(func("2ello"));\n    }\n\n    public static Expression<Func<string,bool>> StringPredicate(Expression<Func<char,bool>> pred) {\n        Expression<Func<string, char>> get = s => s.First();\n        var p = Expression.Parameter(typeof(string), "s");\n        return Expression.Lambda<Func<string, bool>>(\n            Expression.Invoke(pred, Expression.Invoke(get, p)),\n            p);\n    }\n}	0
14083610	14083457	Adding a Stylesheet with the HAP	// doc is the HtmlDocument\nvar style = doc.CreateElement("style");\nvar text = doc.CreateTextNode("some CSS here");\nstyle.AppendChild(text);\ndoc.DocumentNode.AppendChild(style); // or, AppendChild to any node	0
19856632	19856570	Regular Expression to get value between substrings	Regex rgx = new Regex("%.*?(?:22|$)");	0
22140196	22139928	Convert double[] to double* in c#	unsafe { \n    Double[] a = { 1.0, 2.0, 3.0, 4.0, 5.0 };\n    fixed (double* aP = a) {\n      for (int i = 0; i < a.Length; i++) {\n        System.Console.WriteLine(*aP + i);\n      }\n    }\n  }	0
12025486	12025465	how to search a treenode and return it?	public TreeNode FindNodeByText(TreeView m, string s)\n{\n    TreeNodeCollection nodes = m.Nodes;\n    foreach (TreeNode n in nodes)\n    {\n        if (n.Text == s)\n            return n;\n        else\n            return FindNodeByTextInTreeNode(n, s);\n    }\n\n    return null;\n}\n\npublic TreeNode FindNodeByTextInTreeNode(TreeNode node, string s)\n{\n    TreeNodeCollection nodes = node.ChildNodes;\n    foreach (TreeNode n in nodes)\n    {\n        if (n.Text == s)\n            return n;\n        else\n            return FindNodeByTextInTreeNode(n, s);\n    }\n\n    return null;\n}	0
15761353	15703937	How to arrange datatable columns inside gridview?	var columns = JobListGrid.Columns.CloneFields(); //Will get all the columns bound dynamically to the gridview.\nvar columnToMove = JobListGrid.Columns[0]; //My first column is Action Column\nJobListGrid.Columns.RemoveAt(0);           // Remove it\nJobListGrid.Columns.Insert(columns.Count - 1, columnToMove); // Moved to last\nJobListGrid.DataBind();                    // Bind the grid .	0
3737896	3735988	How to POST Raw Data using C# HttpWebRequest	public static string HttpPOST(string url, string querystring)\n    {\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n        request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc\n        StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());\n\n        try\n        {\n            requestWriter.Write(querystring);\n        }\n        catch\n        {\n            throw;\n        }\n        finally\n        {\n            requestWriter.Close();\n            requestWriter = null;\n        }\n\n        HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n        using (StreamReader sr = new StreamReader(response.GetResponseStream()))\n        {\n            return sr.ReadToEnd();\n        }\n    }	0
1792343	660294	How do I declare a chain of responsibility using decorators in Ninject?	Bind<IEmailSender>().To<LoggingEmailSender>();\nBind<IEmailSender>().To<SmtpClientEmailSender>().WhenInjectedInto<LoggingEmailSender>();	0
5675597	5675547	how to hide rows from datagrid which doestn get data from datatable	dataGridView.Rows[rowIndex].Visible = false;	0
16727460	16727306	(Resolved) How to get values from excel without change in their cell format type?	CellVal = objWorkbook.WorkSheets(1).Cells(6, 1).Value\nMsgBox CellVal	0
207515	207497	How do I set full trust for a single Web Part in SharePoint?	gacutil.exe \i C:\Path\To\Dll.dll	0
17907049	17906966	How do I get a bool from a different thread?	delegate T MyDelegate<out T>();\npublic bool MethodName()\n{\n    bool b = (bool)this.Invoke(new MyDelegate<bool>(() => getBool()));\n    return b;\n}	0
6726400	6726111	Clean, efficient, infallible method of programmatically generating C# code files	var unit = new CodeCompileUnit();\n\nvar @namespace = new CodeNamespace("GeneratedCode");\nunit.Namespaces.Add(@namespace);\n\n// AddDefault() doesn't exist, but you can create it as an extension method\n@namespace.Imports.AddDefault();\n@namespace.Imports.Add(new CodeNamespaceImport("MyApi.CoolNameSpace"));\n\nvar @class = new CodeTypeDeclaration("GeneratedClass");\n@namespace.Types.Add(@class);\n\n@class.TypeAttributes = TypeAttributes.Class | TypeAttributes.Public;\n\nvar constructor = new CodeConstructor();\nconstructor.Attributes = MemberAttributes.Public;\nconstructor.Parameters.Add(\n    new CodeParameterDeclarationExpression(typeof(string), "name"));\n\nconstructor.Statements.Add(???);\n\n@class.Members.Add(constructor);\n\nvar provider = new CSharpCodeProvider();\n\nvar result = provider.CompileAssemblyFromDom(new CompilerParameters(), unit);	0
18667890	18657960	ZedGraph plotting large amount of data	int window = (buffer.Length / maxWidth) + 1;\n\nfor (int x = 0; x < buffer.Length; x += window)\n{\n    double min = double.MaxValue;\n    double max = double.MinValue;\n\n    for (int j = 0; j < window; j++)\n    {\n        int index = x + j;\n\n        if (index < buffer.Length)\n        {\n            double value = buffer[x+j];\n            if (value < min)\n            {\n                min = value;\n            }\n\n            if (value > max)\n            { \n                max = value;\n            }\n        }\n    }\n\n    list.Add(x, min);\n    list.Add(x + (window - 1), max);\n}	0
4867455	4858734	Formatting Microsoft Chart Control X Axis labels for sub-categories to be like charts generated in Excel	foreach (string monthName in monthNames)\n{\n    CustomLabel monthLabel = new CustomLabel(startOffset, endOffset, monthName, 1,     LabelMarkStyle.Box);\n    theChart.ChartAreas["Default"].AxisX.CustomLabels.Add(monthLabel);\n    //increment startOffset and endOffset enough to position the next label\n    //under the correct "section"\n}	0
26798503	26798326	A chart element with the name 'John' already exists in the 'SeriesCollection'	Chart1.Series.Add(seriesName);	0
13179363	13177989	Combo Box selecting multiple items	string same = "same" + Environment.NewLine + "next Line";\n List<string> lstring = new List<string> { "one", "two - a", "two - b", "three", "three", same, same };\n cb1.ItemsSource = lstring;	0
9498297	9497977	Generic Interface with TDelegate as an event?	public interface IAsyncSearch<TData, TArgs>\n{\n    event EventHandler<SpecialDataEventArgs<TArgs>> SearchCompletedEvent;\n    void SearchAsync(TData term);\n}\n\npublic class SpecialDataEventArgs<T> : EventArgs\n{\n    public SpecialDataEventArgs(T data)\n    {\n        Data = data;\n    }\n\n    public T Data { get; private set; }\n}	0
32457121	32457062	Getting values from list which only exist once in C#	var newList = new List<int>() { 12, 65, 312, 52, 312, 85, 14 }\n            .GroupBy(x => x)\n            .Where(x => x.Count() == 1)\n            .Select(x => x.Key)\n            .ToList();	0
11499198	11499159	How to extract number from string c#	string sInput = "transform(23, 45)";\nMatch match = Regex.Match(sInput, @"(\d)+",\n              RegexOptions.IgnoreCase);\n\nif (match.Success)\n{\n    foreach (var sVal in match)\n             // Do something with sVal\n}	0
3788677	3788504	Embedded Binary Resources - how can I enumerate the image files embedded?	Assembly assembly = Assembly.GetExecutingAssembly();\nforeach (string s in assembly.GetManifestResourceNames())\n{\n    //match on filenames here. you can also extention matching to find images.\n}	0
2187434	2170871	Pasing data from one form to other	private void btnEdit_Click(sender e, EventArgs arg)\n{\n   if (grdMyData.SelectedRows.Count == 0)\n       return; //nothing to do\n\n   MyClass selectedRow = (MyClass)grdMyData.SelectedRows[0].DataBoundItem;\n   Form2 frm2 = new Form2(selectedRow);\n   if (frm2.ShowDialog() == DialogResult.OK)\n   {\n        //do something if needed\n   }\n}	0
22701460	22700987	How to use the Factory pattern with Generics?	P Create<P, V, IV>(params object[] args) \n      where P : IPresenter<V> where V :IV, IV: IView {	0
1044166	1040948	Restoring a Differential Backup with an SMO Restore object	// before executing the SqlRestore command for myFullRestore...\nmyFullRestore.NoRecovery = true;	0
31688954	31688863	Accessing a static property in a asp.net web-api project class from a console project class	ValuesController.getState();	0
27339649	27339601	How do I place multiple columns from a single row into a single textbox or label?	label_vendor_City_State_Zip.Text = vendor_City + ", " + vendor_State_Prov + "  " + vendor_Zip_Country_Code;	0
3295016	3294605	How can I select and iterate through multiple rows from the database in C#?	foreach (var currentView in mySource.Select(DataSourceSelectArguments.Empty))\n{\n     // Do something with currentView (may need to give it a type if you are interested in it)\n}	0
7640248	7640180	Call javascript from server side on postback	ScriptManager.RegisterStartupScript(this,this.GetType(),"key","javscriptfunction();" , false);	0
14077255	14077168	How do you set FontFamily in C# winforms Control (e.g. TextBox) from a html/css style string (ie: Futura,Verdana,Arial)	private FontFamily FindFontByCSSNames(string cssNames)\n{\n    string[] names = cssNames.Split(',');\n    System.Drawing.Text.InstalledFontCollection installedFonts = new System.Drawing.Text.InstalledFontCollection();\n    foreach (var name in names)\n    {\n\n        var matchedFonts = from ff in installedFonts.Families where ff.Name == name.Trim() select ff;\n\n        if (matchedFonts.Count() > 0)\n            return matchedFonts.First();\n    }\n\n    // No match, return a default\n    return new FontFamily("Arial");\n}	0
14773033	14771280	trigger oncommand event from page_load event in asp.net	object mysender = (object)ControNameHere;\nCommandEventArgs mye = new CommandEventArgs(null, ControNameHere.CommandArgument);\nbtn_Command(mysender, mye);	0
10253378	10253348	How to bind to the ItemsSource of a DataDrid from inside DataRow?	{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=DataGrid}}	0
12211348	12211143	XML SelectSingleNode where sibling = 'something'	var xmlDoc = new XmlDocument();\nxmlDoc.Load(path);\nConsole.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText);	0
9146562	9146533	How to access static methods of generic types	O.MyStaticMethod();	0
14313858	14313845	Logic to write the first 10 numbers without using any for loop	Console.WriteLine("{0}",(10*(10+1))/2);	0
8283890	8283842	Use ? chars in sqlite using c#	Use_id LIKE '%120%'	0
12117330	12116977	SQL Server 2008 connection with C#	Data Source=SERVERSQLCOMPUTER \MPIT_TEST;Initial Catalog=[Test_MPITRACKER];Integrated Security=True;Connect Timeout=30;User Instance=True	0
18346353	18346251	How to find Maximum Value of Multiple Properties	int? total = report.SelectMany(p => p.SnapshotRecords)\n  .Where(record => record.Zip == "63103")\n  .GroupBy(g => new\n    {\n      g.Zip,\n      g.ProductID\n    })\n  .Sum(s => new int?[]\n    {\n      s.Sum(g => g.Monday),\n      s.Sum(g => g.Tuesday),\n      s.Sum(g => g.Wednesday),\n      s.Sum(g => g.Thursday),\n      s.Sum(g => g.Friday),\n      s.Sum(g => g.Saturday),\n      s.Sum(g => g.Sunday)\n    }.Max()\n  );	0
22836232	22835742	How to get values of passed in object using C#	private void InComing_Callback(object objCallParams)\n{\n    // If you know that objCallParams will always be of the type FormParameters:\n    var params = (FormParameters)objCallParams;\n\n    // if you are not so sure about that\n    var notSoSureParams = objCallParams as FormParameters;\n    if (notSoSureParams != null)\n    {\n\n    }\n}	0
16157858	16157744	How to convert multi-level xml into objects using LINQ to XML?	var result = xmlDoc.Descendants("myobject")\n                .Select(m => new\n                {\n                    Property1 = m.Attribute("property1").Value,\n                    Property2 = m.Attribute("property2").Value,\n                    Property3 = m.Descendants("property3").Select(p3=>p3.Value).ToList()\n                })\n                .ToList();	0
30606007	30605806	Access to the return value from the database by linq	var ID = concerthallID.FirstOrDefault();	0
30580221	30444837	Is it possible to bind to a property on the container of the Adorned Element?	MaxWidth="{Binding ElementName=adornedElement, Mode=OneWay, Path=AdornedElement.Parent.ActualWidth}"	0
23087002	23086825	Get JSON response using RestSharp	var client = new RestClient("http://myurl.com/api/");\n\nvar request = new RestRequest("getCatalog?token={token}", Method.GET); \n\nrequest.AddParameter("token", "saga001", ParameterType.UrlSegment);   \n\n// request.AddUrlSegment("token", "saga001"); \n\nrequest.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };\n\nvar queryResult = client.Execute(request);\n\nConsole.WriteLine(queryResult.Content);	0
22389177	22388752	search for node using contains in c#	HtmlDocument doc = new HtmlDocument();\n         doc.Load(@"C:\file.html");\n         var root = doc.DocumentNode;\n         var a_nodes = root.Descendants("li").Where(c=>c.GetAttributeValue("id","")\n                       .Contains("searchResult")).ToList()	0
17038786	17035914	To set Asp Radio button attribute (value) to a string	string strResult = rdotest.Attributes["Value"];	0
20070025	20069225	Find HID Devices C#	[StructLayout(LayoutKind.Sequential)]\nstruct GUID\n{\n    public int a;\n    public short b;\n    public short c;\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]\n    public byte[] d;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct SP_DEVICE_INTERFACE_DATA\n{\n    public uint cbSize;\n    public GUID InterfaceClassGuid;\n    public uint Flags;\n    public IntPtr Reserved;\n}	0
7366001	7365276	How to scrape text from an html page using C#?	public string GetWebRequest()\n{\n    return webBrowser1.Document.Body.InnerText;\n}	0
24800875	24800507	Need help to get a sub string from a given string	string s = @".\abc_xyz\drff\dsqa_license_db\dgfx\xsad_license_db.rfds-17343";\n\n  string[] splitChar = { @"\"};\n\n int yourCriteria = 3;\n\n   string[]  splitString = s.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);\n\n  StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i < yourCriteria; i++)\n  {\n     if (sb.Length == 0)\n   sb.AppendFormat("{0}", splitString[i]);\n   else\n  sb.AppendFormat(@"\{0}", splitString[i]);\n\n  }\n    //now do whatever you want to with sb.ToString();	0
27437320	27437238	how to add fieldnames into json output of C# webservice	var JaggedArray = new List<Object>();\nforeach (DataRow rs in objDataSet.Tables[0].Rows)\n{\n    JaggedArray.Add(new \n                    { \n                        City = rs["AddCity"].ToString(), \n                        State = rs["AddState"].ToString(), \n                        Zip = rs["AddZip"].ToString()\n                    });\n}	0
8353352	8353331	How to create one string from list of String?	String.Join(Environment.NewLine, Errors.ToArray())	0
3559207	3559143	Date Range wildcard	System.IO.File.Move(files[i], @"C:\Checks\XMLFiles\" + DateTime.Now.ToString("MM-dd-yyyy-") + ".xml");	0
6338688	6338661	Passing a textbox to a void	private void FirstNameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)\n{\n    apostropheCheck(((TextBox)sender).Text);\n}	0
14190264	14181749	How do I post to a Facebook page with FacebookClient	const string accessToken = "MY_ACCESS_TOKEN";\nconst string pageId = "MY_PAGE_ID";\n\nvar client = new FacebookClient(accessToken);\n\ndynamic parameters = new ExpandoObject();\nparameters.title = "test title";\nparameters.message = "test message";\n\nvar result = client.Post(pageId + "/feed", parameters);	0
28258132	28258033	turning strings to ints and getting the total value by addition	// Add this up here\nint totals = 0;\n\nfor(int i = 0; i < blueHex1CardNumbers.Length; i++)\n{\n    int j = Random.Range(1, 6);\n    // increment it as you go\n    totals += j;\n\n    string myString = j.ToString();\n    blueHex1CardNumbers[i] = myString;\n}\n\n// use your totals here	0
9374841	9374617	Want to do Recursion, load category in undercategory	private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    foreach (Kategorie kategorie in mainViewModel.Kategorien)\n    {\n        LoadTreeviewItem(kategorie, null);\n    }\n}\n\nprivate void LoadTreeviewItem(Kategorie kategorie, TreeViewItem parentItem)\n{\n   //Stop condition\n   if(kategorie == null) return;\n\n   TreeViewItem newChild = new TreeViewItem();\n   newChild.Header = kategorie.Bezeichnung;\n   treeView.Items.Add(newChild);\n\n   if(parentItem != null) // Add to parent if it is not null\n   {\n      parentItem.Items.Add(newChild);\n   }\n   else //Otherwise this is the top level so add to treeview\n   {\n      treeView.Items.Add(newChild);\n   }\n\n   foreach (Kategorie subkategorie in kategorie.Unterkategorie)\n   {\n       LoadTreeviewItem(subkategorie, parentItem);\n   }\n}	0
3313106	3313086	Get the set of grouped values as a list using linq	var flattened = rows.SelectMany(x=>x.Values).ToList();	0
24805262	24804741	Checking to see if file exist after it is downloaded from server	string curFile = @"c:\temp\test.txt";\nConsole.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");	0
32760380	32760198	Setting width of table inside another table is not reflecting in created pdf	innerTable.WidthPercentage = 62.5f;	0
10653005	10652691	Need StatusStrip to fill its items from Right to Left	statusStrip1.RightToLeft = RightToLeft.Yes;	0
23584367	23584280	ASP.NET MVC 4 - Adding member variable not a part of a database column	[NotMapped]\n public string Whatever { get; set; }	0
19437500	19433109	Resizing tabs individually and programmatically in C# with Winforms	void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {\n  var controls = tabControl1.SelectedTab.Controls.Cast<Control>();\n  if (controls.Any()) {\n    this.Height = controls.Max(x => x.Bottom) + 72;\n  }\n}	0
15400268	15400124	Getting and parsing webpage from Internet on C# or C++	using System.Net;\nusing System.IO;\nusing System.Windows.Forms;\n\nstring result = null;\nstring url = "http://www.devtopics.com";\nWebResponse response = null;\nStreamReader reader = null;\n\ntry\n{\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url );\n    request.Method = "GET";\n    response = request.GetResponse();\n\n    ContentType contentType = new ContentType(response.ContentType);\n    Encoding encoding = Encoding.GetEncoding(contentType.CharSet);\n\n    reader = new StreamReader( response.GetResponseStream(), encoding);\n    result = reader.ReadToEnd();\n}\ncatch (Exception ex)\n{\n  // handle error\n  MessageBox.Show( ex.Message );\n}\nfinally\n{\n  if (reader != null)\n      reader.Close();\n  if (response != null)\n      response.Close();\n}	0
10356837	10356715	Word Template - Sections - Bringing those sections in a WinForms app	using Microsoft.Office.Interop.Word;\n...\n\nforeach (Section section in wDoc.Sections) \n{\n  ....\n}	0
8572576	8565978	Installing a specific driver for a specific device programmatically (and when pre-install fails)	[DllImport("newdev.dll", SetLastError = true, CharSet = CharSet.Auto)]\n[return: MarshalAs(UnmanagedType.Bool)]\nprotected static extern bool InstallSelectedDriver(\n      IntPtr HwndParent,\n      IntPtr DeviceInfoSet,\n      string Reserved,\n      [MarshalAs(UnmanagedType.Bool)] bool Backup,\n      out UInt32 Reboot);	0
17006279	17006103	Parsing Amazon s3 bucket listing with C# XmlDocument (Unity3d)	XmlDocument xmlDoc = new XmlDocument();\n        xmlDoc.Load("http://s3.amazonaws.com/themall/");\n\n        XmlNamespaceManager namespaceManager =\n            new XmlNamespaceManager(xmlDoc.NameTable);\n        namespaceManager.AddNamespace("ns",\n            "http://s3.amazonaws.com/doc/2006-03-01/");\n\n        XmlNode titleNode =\n            xmlDoc.SelectSingleNode("//ns:Name", namespaceManager);\n        if (titleNode != null)\n            Console.WriteLine(titleNode.InnerText);	0
16552620	16490211	How to delete records in Amazon Dynamodb based on a hashkey?	List<Document> results = null;\nvar client = new AmazonDynamoDBClient("myamazonkey", "myamazonsecret");\nvar table = Table.LoadTable(client, "mytable");\nvar batchWrite = table.CreateBatchWrite();\nvar batchCount = 0;\n\nvar search = table.Query(new Primitive("hashkey"), new RangeFilter());\ndo {\n  results = search.GetNextSet();\n  search.Matches.Clear();\n  foreach (var document in results)\n  {\n    batchWrite.AddItemToDelete(document);\n    batchCount++;\n    if (batchCount%25 == 0)\n    {\n      batchCount = 0;\n      try\n      {\n        batchWrite.Execute();\n      }\n      catch (Exception exception)\n      {\n       Console.WriteLine("Encountered an Amazon Exception {0}", exception);\n      }\n\n      batchWrite = table.CreateBatchWrite();\n     }\n   }\n   if (batchCount > 0) batchWrite.Execute();\n  }\n} while(results.Count > 0);	0
1851808	1851795	Is there a function that returns index where RegEx match starts?	Regex rx = new Regex("as");\n            foreach (Match match in rx.Matches("as as as as"))\n            {\n                int i = match.Index;\n            }	0
15487304	15487191	c# - DateTime conversion terminates foreach loop	dayOutDateTimePicker.Value.ToString()	0
12532579	12516235	Finding all which match	var query = new List<BsonValue>{"A","B","C"};\n\nvar results = collection.FindAs<MyObject>(Query.In("Identifiers", query));\nvar valid = results.Where(r => !r.Identifiers.Except(a).Any()).ToList();	0
15483953	15364785	Save an excel file as values using C#	using Excel = Microsoft.Office.Interop.Excel;\nExcel.Range targetRange = (Excel.Range)CurrentSheet.UsedRange;\ntargetRange.Copy(Type.Missing);\ntargetRange.Paste(Excel.XlPasteType.xlPasteValues, \n    Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);	0
3772351	3772123	Filtering out duplicate XElements based on an attribute value from a Linq query	class Program\n{\n    static void Main(string[] args)\n    {\n        string xml = "<foo><property name=\"John\" value=\"Doe\" id=\"1\"/><property name=\"Paul\" value=\"Lee\" id=\"1\"/><property name=\"Ken\" value=\"Flow\" id=\"1\"/><property name=\"Jane\" value=\"Horace\" id=\"1\"/><property name=\"Paul\" value=\"Lee\" id=\"1\"/></foo>";\n\n        XElement x = XElement.Parse(xml);\n        var a = x.Elements().Distinct(new MyComparer()).ToList();\n    }\n}\n\nclass MyComparer : IEqualityComparer<XElement>\n{\n    public bool Equals(XElement x, XElement y)\n    {\n        return x.Attribute("name").Value == y.Attribute("name").Value;\n    }\n\n    public int GetHashCode(XElement obj)\n    {\n        return obj.Attribute("name").Value.GetHashCode();\n    }\n}	0
8491283	8490864	Ordering Datatable using Linq Or without creating copy of DataTable	DataView dataView = new DataView(myDataTable);\n      dataView.Sort = "ID";\n     DataTable d = dataView.ToTable();	0
24600982	24600859	SQL search on three fields from one parameter	SELECT\n   PersonId,\n   FirstName,\n   SecondName,\n   LastName\nFROM Person\nWHERE FirstName + ' ' + SecondName + ' ' + LastName = @fullname	0
11198576	8393239	Word 2007 add-in selected text help needed	using Word = Microsoft.Office.Interop.Word;\nusing Office = Microsoft.Office.Core;\n\npublic String getSelected(){\n    Word.Document app = add_in.Globals.ThisAddIn.Application.ActiveDocument;\n    String keyword = app.Application.Selection.Text;\n    return keyword;\n}	0
34356202	34356090	Adding a glyphicon to a control through c#	var glyph = new HtmlControls.HtmlGenericControl();\nglyph.InnerHtml = "<span class=\"glyphicons glyphicons-restart\"></span> Reset";\nbtnBarButtonBar.SummaryButton.Controls.Add(glyph);	0
7911591	7911448	C#: Get first directory name of a relative path	static string GetRootFolder(string path)\n{\n    while (true)\n    {\n        string temp = Path.GetDirectoryName(path);\n        if (String.IsNullOrEmpty(temp))\n            break;\n        path = temp;\n    }\n    return path;\n}	0
333268	333175	Is there a way of making strings file-path safe in c#?	'Clean just a filename\nDim filename As String = "salmnas dlajhdla kjha;dmas'lkasn"\nFor Each c In IO.Path.GetInvalidFileNameChars\n    filename = filename.Replace(c, "")\nNext\n\n'See also IO.Path.GetInvalidPathChars	0
30941253	30941130	C# - How to open a doc with word using arguments	ProcessStartInfo startInfo = new ProcessStartInfo("winword");\n startInfo.Arguments = "/a /b";	0
8334761	8334730	Parsing a value from string to an unknown variable type	string sValue = line.Split(new char[] {'='})[1]);\n        object oValue;\n        switch (f.FieldType.Name.ToLower())\n        {\n            case "system.string":\n               oValue = sValue;\n               break;\n\n            case "system.int32":\n                oValue = Convert.ToInt32(sValue);\n                break;\n         etc...\n\n      f.SetValue(current, oValue);	0
15933802	15929924	Detecting sprites in C#-XNA	class Game1\n{\n    List<Rectangle> cardSpriteAreas; // this is where you store the card's areas\n\n    public void Update()\n    {\n         Point position = GetInterestingPosition(); // this is the point you want to check\n         foreach(var spriteArea in cardSpriteAreas)\n         {\n              if (spriteArea.Contains(position))\n              {\n                   // position is contained within the card's area!\n              }\n         }\n    }\n}	0
11571912	11571834	How to remove duplicate users from a list but amalgamate their roles	from details in detailsList\ngroup details by new {Id = details.Id, Name = details.Name} into groupedDetails\nselect new PersonDetails()\n{\n    Id = groupedDetails.Key.Id,\n    Name = groupingDetails.Key.Name,\n    Roles = groupingDetails.SelectMany(member => member.Roles).ToList()\n}	0
20666125	20551579	Deserialize bitmap image and compare it with images in resources	[XmlIgnore]\npublic Bitmap UpToDate\n{\n    get\n    {\n        //Only null if file entered is invalid. This causes image to be blank\n        if (UpToDateString == null) \n            return null;\n\n        //Translates from the resource specified to the bitmap object being used\n        var resourceObject = Resources.ResourceManager.GetObject(UpToDateString);\n        return (Bitmap) resourceObject;\n    }\n}\n\n//This holds the reference for which resource image to use\n[XmlElement("UpToDate")]\npublic string UpToDateString { get; set; }	0
11521562	11521426	read specific line this xml?	var guides = from query in dataFeed.Descendants("MaxPayne3")\n                                             select new NewGamesClass\n                                             {\n                                                 GameGuide = (string)query.Element("Guide")\n\n                                             };\n\nAchivementsListBox.ItemsSource = guides.Where( ngc => ngc.GameGuide.StartsWith("Chapter 4:"));	0
18660316	18659013	delete element from document in MongoDB using C#	for (int j = 0 ; j < idlist.Count ; j++)\n{\n    var queryDeleteValue = new QueryDocument("_id", idlist[j]);\n    var update = Update.Unset("Flash_point");\n    collectionInput.Update(queryVerwijderValue, update);\n}	0
14375967	14375916	removing top value of stack<string> and poping the rest	if (simpleStack.Count > 0)\n{\n    simpleStack.Pop(); // remove top item, discarding it\n    string open = simpleStack.Pop(); // Fails if stack has only 1 element\n\n    PopulateListView(open);\n    complicatedStack.Push(open);\n}	0
24936027	24572227	Lightswitch 2013 set date to now	myapp.AddEditBooks.created = function (screen) {\n\nscreen.Bookshelf.Bookloandate= Date.now();\n};	0
11894379	11863741	Get facebook post using C# SDK	string test = VendorShop.Services.Sess.getQueryString("signed_request");\nvar signed_request_obj  = testClient.ParseSignedRequest( appSecret, test);\nvar obj = testClient.Get(\n"https://graph.facebook.com/ur_postid?access_token=ur_accesstoken");	0
20037557	20011907	Write Specific SubItems to .txt while looping through ListView Control?	var indices = new [] { 0, 1, 2, 4, 9 }; // whatever you want\nforeach (int i in indices)\n{\n    sb.Append(string.Format("{0}!", lvI.SubItems[i].Text));\n}	0
16738893	16738539	C# split into pre-allocated array changes array allocation	static void TEST(string arg)\n{\n    string[] aArgs = new String[3];\n    string[] argSplit = arg.Split(null,3);\n    argSplit.CopyTo(aArgs, 0);\n}	0
7453622	7453248	Longest Consecutive Sequence in an Unsorted Array	def destruct_directed_run(num_set, start, direction):\n  while start in num_set:\n    num_set.remove(start)\n    start += direction\n  return start\n\ndef destruct_single_run(num_set):\n  arbitrary_member = iter(num_set).next()\n  bottom = destruct_directed_run(num_set, arbitrary_member, -1) \n  top = destruct_directed_run(num_set, arbitrary_member + 1, 1)\n  return range(bottom + 1, top)\n\ndef max_run(data_set):\n  nums = set(data_set)\n  best_run = []\n  while nums:\n    cur_run = destruct_single_run(nums)\n    if len(cur_run) > len(best_run):\n      best_run = cur_run\n  return best_run\n\ndef test_max_run(data_set, expected):\n  actual = max_run(data_set)\n  print data_set, actual, expected, 'Pass' if expected == actual else 'Fail'\n\nprint test_max_run([10,21,45,22,7,2,67,19,13,45,12,11,18,16,17,100,201,20,101], range(16, 23))\nprint test_max_run([1,2,3], range(1, 4))\nprint max_run([1,3,5]), 'any singleton output fine'	0
23722607	23722163	Using relative paths with Web Api	string root_path = HttpRuntime.AppDomainAppPath;\nstring image_folder_path = root_path+"images";\n/// Use the path	0
13923540	13923440	When is it safe to read a file	string filename = "Test.txt";\n\ntry\n{\n   using(FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None))\n   {\n      // Read content here\n   }\n}\ncatch(IOException)\n{\n    // Occurs if the file cannot be exclusively locked.\n}	0
27758404	25911169	Correct configuration for a mono hosted wcf service using ajax and json	RequestFormat = WebMessageFormat.Json,	0
25689385	25687795	How to process events fast during a busy process, is there an Update command?	using System.Windows.Threading;  //DispatcherFrame, needs ref to WindowsBase\n\n//[SecurityPermissionAttribute(SecurityAction.Demand, Flags =   SecurityPermissionFlag.UnmanagedCode)]\npublic void DoEvents()\n{\n    DispatcherFrame frame = new DispatcherFrame();\n    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,\n        new DispatcherOperationCallback(ExitFrame), frame);\n    Dispatcher.PushFrame(frame);\n}\n\npublic object ExitFrame(object f)\n{\n    ((DispatcherFrame)f).Continue = false;\n\n    return null;\n}	0
17543685	17543641	Not calling a datatable row based on field	for (int i = 0; i < variants.Rows.Count; i++)\n        {\n          if(variants.Rows[i]["Variant"].ToString()!="#AAB")\n            variantsList.InnerHtml += "<li><a href=\"#" + variants.Rows[i]["Variant"].ToString() + "\">" + variants.Rows[i]["EngineSize"].ToString()</a></li>";\n        }	0
16030326	16030034	ASP.Net MVC - Read File from HttpPostedFileBase without save	// Read bytes from http input stream\nBinaryReader b = new BinaryReader(file.InputStream);\nbyte[] binData = b.ReadBytes(file.InputStream.Length);\n\nstring result = System.Text.Encoding.UTF8.GetString(binData);	0
6019982	6014807	Maximum String Length of PrintArea in Excel	Sub PrintRangeTest()\n\n    Dim i As Integer\n    Dim j As Integer\n    Dim newName As String\n    newName = ""\n    Dim rng As Range\n\n    For i = 1 To 100000 //some arbitrarily large number\n        newName = ""\n        For j = 1 To i\n            newName = newName & "a"\n        Next\n\n        Set rng = ActiveSheet.Range(Cells(1, 1), Cells(i, i))\n        rng.Name = newName\n\n        ActiveSheet.PageSetup.PrintArea = rng\n    Next\n\nEnd Sub	0
24653005	24651830	LINQ - Generate a set of Random Integers whose sum falls inside a range	int totalNumbers = totalVisits * 3;\n    int[] selection = new int[totalNumbers];\n    int sum;\n    do {\n        sum = 0;\n        for (int i = 0; i < totalNumbers; ++i) {\n            sum += selection[i] = valueNumbers[r.Next(valueNumbers.Length)];\n        }\n    } while (sum < min || sum > max);\n    for (int j = 0; j < selection.Length; j+=3) {\n        visitScores.Add(selection[j] + selection[j+1] + selection[j+2]);\n    }	0
31948662	31947017	Entity Framework Relationships with Existing Data	[Table("Clients")]\nclass Client \n{\n  [Key]\n  public int Client_Id {get;set;}\n  public virtual ICollection<Note> Notes {get;set;}\n}\n\n[Table("Notes")]\nclass Note \n{\n  [Key]\n  public int Note_Id {get;set;}\n  public int Account_Id {get;set;}\n  [ForeignKey("Account_Id")]\n  public virtual Client Client {get;set;}\n}	0
27242346	27242143	JSON array to C# List	string json = "[\"on4ThnU7\",\"n71YZYVKD\",\"CVfSpM2W\",\"10kQotV\"]";\n  var result = new JavaScriptSerializer().Deserialize<List<String>>(json);	0
8031713	8031681	How do you add a file explorer option in C#?	Shell Extensions	0
2267020	2266986	Inheriting from StreamWriter with smallest possible effort	public class CustomStreamWriter : StreamWriter\n{\n    public CustomStreamWriter(Stream stream)\n        : base(stream)\n    {}\n\n    public override void Write(string value)\n    {\n        //Inspect the value and do something\n\n        base.Write(value);\n    }\n}	0
14268522	14268390	User-friendly Property Names in .NET, like those in Rails	[DisplayName("Full name")]\npublic string FullName { get; set; }	0
6604907	6604885	How can I perform full recursive directory & file scan?	private static void TreeScan( string sDir )\n{\n    foreach (string f in Directory.GetFiles( sDir ))\n    {\n        //Save f :)\n    }\n    foreach (string d in Directory.GetDirectories( sDir ))\n    {\n        TreeScan( d ); \n    }\n}	0
9409557	9408659	dataview rowfilter value to datatable convertion	if (datavw.Count > 0)             \n   {                 \n     DT = datavw.ToTable(); // This will copy dataview's RowFilterd values to datatable              \n   }	0
5314514	5314238	How do I set the serialization options for the geo values using the official 10gen C# driver?	public class C {\n  [BsonRepresentation(BsonType.Double, AllowTruncation=true)]\n  public decimal D;\n}	0
22970717	22969962	Alternative to Static Abstract Property for lazy loading	public abstract class Loadable<T> where T: Loadable<T>, new()\n{\n    private readonly static ConcurrentDictionary<int, T> _cache = new ConcurrentDictionary<int, T>();\n\n    private readonly static Func<int, T> _addDelegate = key => {\n        T item = new T();\n        item.SetData(SQLiteDB.main.getRowById(_tableName, key));\n        return item;\n    };\n\n    private static readonly string _tableName;\n\n    static Loadable()\n    {\n        var prop = typeof(T).GetProperty("TableName", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);\n        if (prop == null)\n            throw new NotSupportedException(string.Format("Type '{0}' does not support TableName", typeof(T)));\n\n        _tableName = (string)prop.GetValue(null);\n    }\n\n    protected abstract void SetData(DataRow data);\n\n    public virtual int Id { get; set; }\n\n    public static T GetById(int id)\n    {\n        return _cache.GetOrAdd(id, _addDelegate);\n    }\n}	0
23695818	23695264	project linq group by result into a single view model object?	var countsQuery =\n    _db.Departments.All()\n        .Select(p => new { key = 1, count = 0 })\n        .Union(_db.Students.All().Select(p => new { key = 2, count = 0 }))\n        .GroupBy(p => p.key)\n        .Select(p => new { key = p.Key, count = p.Count() }).ToList();\nvar counts = new CountsVm()\n    {\n        DepartmentCount =\n            countsQuery.Where(p => p.key == 1)\n                       .Select(p => p.count)\n                       .FirstOrDefault(),\n        StudentCount =\n            countsQuery.Where(p => p.key == 2)\n                       .Select(p => p.count)\n                       .FirstOrDefault()\n    };	0
1337058	1337050	Modify ValueType from extension method?	IsVisible = IsVisible.Toggle();	0
6089234	6089215	One line LINQ to flatten string[] to a string?	var message = string.Join(\n    ";", \n    decoder.AllKeys\n           .Select(x => string.Format("{0}: {1} ", x, decoder[item]))\n           .ToArray()\n);	0
3267240	3266991	Binding to a ScrollViewer's ViewportWidth and ViewportHeight	private void ScrollViewer_Loaded(object sender, RoutedEventArgs e)\n{\n   ScrollViewer sv = sender as ScrollViewer;\n   ViewModel vm = sv.DataContext as ViewModel;\n\n   vm.ScrollViewerHeight = sv.ViewportHeight;\n   vm.ScrollViewerWidth = sv.ViewportWidth;\n}	0
34176522	34176331	How can i read a text file key value and assign the values to strings vars?	string[] lines = File.ReadAllLines(Authentication.AuthenticationFileName);\n\n// Get the position of the = sign within each line\nvar pairs = lines.Select(l => new { Line = l, Pos = l.IndexOf("=") });\n\n// Build a dictionary of key/value pairs by splitting the string at the = sign\nvar dictionary = pairs.ToDictionary(p => p.Line.Substring(0, p.Pos), p => p.Line.Substring(p.Pos + 1));\n\n// Now you can retrieve values by key:\nvar value1 = dictionary["key1"];	0
8431714	8429669	A non priority queue with insert priority	QueueEntity Head;\nQueueEntity Tail\n\nclass QueueEntity\n{\n       QueueEntity Prev;\n       QueueEntity Next;\n       ...   //queue content; \n}\n\nand then do this:\n\n//Read\nlock(Tail)\n{\n  //get the content\n  Tail=Tail.Prev;\n}\n\n//Write\nlock(Head)\n{\n   newEntity = new QueueEntity();\n   newEntity.Next = Head ;\n   Head.Prev = newEntity;\n   Head = newEntity;\n}	0
7784490	7784456	How can I implement an interface and inherit from a base class?	public partial class form1 : Form, ICloneable	0
23064359	23062230	How to identify which button is clicked in dynamically allocated buttons in Window Store App	private void Button_Clicked(object sender, RoutedEventArgs e)\n{\n    var button = (Button)sender;\n    var grid = (Grid)button.Parent;\n    var lblUserName = (TextBlock)grid.FindName("lblUserName");\n    pageTitle.Text = lblUserName.Text;\n}	0
19556698	19556637	Find index of first Char(Letter) in string	test = '5555Z187456764587368457638'\n\nfor i in range(0,len(test)):\n    if test[i].isalpha():\n            break\n\nprint test[i:]	0
16960515	16950040	Posting webBrowser1_DocumentCompleted keeps looping	private bool WaitingForData;\n\nprivate void GetData()\n{\n    webBrowser1.Navigate(inputURLID);\n    WaitingForData = true;\n}\n\nprivate void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    if (WaitingForData) SendData();\n    WaitingForData = false;\n}	0
15302608	15250692	Unable to DataBind to ListView because of SelectMethod	Convert.ToString(Page.RouteData.Values["categoryName"]);\n\n\n\nConvert.ToInt32(Page.RouteData.Values["scID"]);	0
28201128	28200660	Getting extended property from Exchange/Outlook appointment	viewFind.PropertySet = new PropertySet(ep);	0
20660407	20660321	Set breakpoint on specific value of watched variable	if(System.Diagnostics.Debugger.IsAttached && yourVariable == specificValue)\n  System.Diagnostics.Debugger.Break();	0
12108657	12108628	Limiting the files that can be selected using Open FIle Dialog box	openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";	0
25121321	25121021	Generic Execution of Stored Procedure in CSharp	public DataTable RunSP_ReturnDT(string procedureName, List<SqlParameter> parameters, string connectionString)\n    {\n        DataTable dtData = new DataTable();\n        using (SqlConnection sqlConn = new SqlConnection(connectionString))\n        {\n            using (SqlCommand sqlCommand = new SqlCommand(procedureName, sqlConn))\n            {\n                sqlCommand.CommandType = CommandType.StoredProcedure;\n                if (parameters != null)\n                {\n                    sqlCommand.Parameters.AddRange(parameters.ToArray());\n                }\n                using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))\n                {\n                    sqlDataAdapter.Fill(dtData);\n                }\n            }\n        }\n        return dtData;\n    }	0
29301152	29300372	Send message with APPCOMMAND_MEDIA_NEXT_TRACK	SendMessage(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)((int)cmd << 16));	0
32396565	32396016	Unable to Deserialize Object using Newton Json	protected override object DeserializeCore(Type type, byte[] value) {\n        var str = System.Text.Encoding.UTF8.GetString(value);\n        return JsonConvert.DeserializeObject(str, type);\n    }	0
9722907	9722639	How to generate a Program template by generating an abstract class	class MainClass {\n   static void Main(string[] args) {\n      // Where ProcessingStrategy is your abstract class.\n      // SpecificProcessingStrategy is someone else's implementation.\n      //\n      ProcessingStrategy strategy = new SpecificProcessingStrategy();\n\n      // Processor is implemented and provided by you and calls the appropriate methods on the \n      // ProcessingStrategy..\n      // \n      Processor processor = new Processor( strategy );\n      processor.Process();\n   }\n}	0
10459544	10459476	Looking for example or tips on how to iterate over a table based on results	var q=  from p in yourTable\n     where p.ParentID == null  // well get all parents\n      select new \n       {\n             ParentID = p.ParentID,\n            child =  from c in yourTable\n                      where c.ParentID == p.ID select\n                           new  {\n                                ChildID=c.ID,\n                                ParentID = c.ParentID\n                                }\n      };	0
7980886	7980834	How do I remove trailing digits fitting a pattern from a string in C#?	var tmp = str.TrimEnd('0');\nvar result = tmp.Substring(Math.Max(0,tmp.Length - 6));	0
4595440	4595116	Non-clickable Context Menu Header	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        contextMenuStrip1.Items.Insert(0, new ToolStripLabel("Please select an option"));\n        contextMenuStrip1.Items.Insert(1, new ToolStripSeparator());\n    }\n}	0
6761214	6760565	Where can I safely store data files for a ClickOnce deployment?	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
3970512	3970040	How can I prevent system clipboard image data being pasted into a WPF RichTextBox	public Window1()\n{\n    InitializeComponent();\n\n    _rtf.PreviewKeyDown += OnClearClipboard;\n}\n\nprivate void OnClearClipboard(object sender, KeyEventArgs keyEventArgs)\n{\n    if (Clipboard.ContainsImage() && keyEventArgs.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) != 0)\n        Clipboard.Clear();\n}	0
27154338	27153598	How do I create a new table of results using LINQ?	/// <summary>\n    /// Your entity\n    /// </summary>\n    public class Events\n    {\n        public int EventID { get; private set; }\n        public string Name { get; set; }\n        public DateTime EventDate { get; set; }\n    }\n\n    public class Program\n    {\n        static void Main(string[] args)\n        {\n            // Query all events\n            IEnumerable<Events> events = null; \n\n            // Group them by Date\n            events\n                .GroupBy(e => e.EventDate)\n                .Select(g => new\n                {\n                    Date = g.Key,\n                    Count = g.Count()\n                });\n        }\n    }	0
13381638	13381468	Convert from string to any basic type	public static object StringToType(string value, Type propertyType)\n{\n   var underlyingType = Nullable.GetUnderlyingType(propertyType);\n   if(underlyingType == null)\n          return Convert.ChangeType(value, propertyType,  CultureInfo.InvariantCulture);\n   return String.IsNullOrEmpty(value)\n          ? null\n          : Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);	0
4531837	4513307	Modifying a collection returned from ObjectDataSource	public class MyObjectDataSource : ObjectDataSource\n{\n    private MyObjectDataSourceView _view;\n    private MyObjectDataSourceView GetView()\n    {\n        if (_view == null)\n        {\n            _view = new MyObjectDataSourceView(this, "DefaultView", Context);\n            if (IsTrackingViewState)\n            {\n                ((IStateManager)_view).TrackViewState();\n            }\n        }\n        return _view;\n    }\n\n    protected override DataSourceView GetView(string viewName)\n    {\n        return GetView();\n    }\n}\n\npublic class MyObjectDataSourceView : ObjectDataSourceView\n{\n    public MyObjectDataSourceView(MyObjectDataSource owner, string name, HttpContext context)\n        : base(owner, name, context)\n    {\n    }\n\n    protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)\n    {\n        IEnumerable dataSource = base.ExecuteSelect(arguments);\n        // TODO: do your stuff here\n        return dataSource;\n    }\n}	0
3978502	3978428	Parse a HTML combox in C#	webBrowser1.DocumentCompleted += \n          new WebBrowserDocumentCompletedEventHandler(ParseOptions);\n\n    webBrowser1.Url = new Uri("C:\\1.html", UriKind.Absolute);\n\n    private void ParseOptions(object sender,\n        WebBrowserDocumentCompletedEventArgs e)\n    {\n        HtmlElement elems = webBrowser1.Document.GetElementById("region");\n    }	0
7254430	7254409	How could I pass a parameter to a WHERE clause?	SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.U_User WHERE URI=@umail", cn);\nda.SelectCommand.Parameters.AddWithValue("@umail", umail);	0
17247798	17241548	Get specific number of points on Google Area Chart?	var options = {\n                 vAxis: { gridlines: { count: 100} }\n            };	0
1770929	1770424	How do I change a foreign key association using Entity Framework?	var customer = Context.Customers.Where(c.Id == id).First();\ncustomer.Class = Context.Classes.Where(c.Id == classId).First();	0
9710064	9709946	Elegant arguments in constructor	new _Empresa(\n  n: _nombre.Text, \n  r: _rfc.Text\n  ...\n  );	0
19934970	19934417	EF: Custom Data Validation in IsValid()	public override bool IsValid(object value)\n{\n  var objectToValidate = value as MyValidatableClass;\n\n  // some code for validation.\n  if (objectToValidate.SomeProperty != "correct")\n    return false;\n}	0
32984428	32984405	WebBrowser control's rendered page differs from IE	Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]\n"your_application_name.exe"=dword:00002328	0
13327852	13327691	XMLTextReader missing first element	var document = XDocument.Load("file.xml");\nvar config = document.Root;\n\nvar userName = (string)config.Element("username");\nvar password = (string)config.Element("password");\nvar autologin = (bool)config.Element("autologin");	0
13593207	13590750	How to write FDF to PDF using iTextSharp c#	string newFile = Server.MapPath("~/") + "ModF23_Final.pdf";\nstring pdfTemplate = Server.MapPath("~/") + "ModF23.pdf";\n\nPdfReader pdfReader = new PdfReader(pdfTemplate);\nPdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));\nAcroFields pdfFormFields = pdfStamper.AcroFields;\npdfFormFields.SetField("2", FirstName.Text);\npdfFormFields.SetField("2-1", LastName.Text);\npdfStamper.FormFlattening = true;\npdfStamper.Close();	0
11658712	11658463	how to send multiple check box item lists to class	protected void check1_SelectedIndexChanged(object sender, EventArgs e)\n{\n   string checking = "";\n   for (int z = 0; z < check1.Items.Count; z++)\n   {\n      if (check1.Items[z].Selected)\n      {\n         checking += "\u2022" + check1.Items[z].Text;\n      }\n   }\n\n   Mail emailsystem = new Mail();\n   emailsystem.GetEmail(comment.Text, StatusList.SelectedValue, checking );\n}	0
29103722	29103336	checking for null value using dapper.net	// snip\n    user = result.Read<UserData>().FirstOrDefault();\n}\nif(user == null)\n{\n    // no such user exists, go do something about it	0
5739026	5738979	How to parse parameters to a .NET application from Windows startup?	RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n rkApp.SetValue("Low CPU Detector", "\"" + Application.ExecutablePath.ToString() + "\" /fromStartup");	0
6740886	6740841	What is the most efficient way to obtain the list of keys from a KeyedCollection?	var keys = collection.Dictionary.Keys;	0
7569841	7442766	Pass validation errors in own control 	#region IDataErrorInfo Members\n\n    public string Error\n    {\n        get { throw new NotImplementedException(); }\n    }\n\n    public string this[string columnName]\n    {\n        get { throw new NotImplementedException(); }\n    }\n\n    #endregion\n    // Your Code	0
14915827	14915626	Character Repetition	public void FindCharRepetitions(string toCheck)\n    {\n        var result = new Dictionary<char, int>();\n        foreach (var chr in toCheck)\n        {\n            if (result.ContainsKey(chr))\n            {\n                result[chr]++;\n                continue;\n            }\n            result.Add(chr, 1);\n        }\n\n       foreach (var item in result)\n       {\n           Console.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value);\n       }\n    }	0
4367449	4367327	How to rewrite code that navigates node list	public String sqlReading(String fileName, String path, String nodeId)\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load(fileName);\n\n    XmlNode foundNode = doc.SelectNodes(path).SelectSingleNode("*[@id='" + nodeId + "']/GUIDisplay/sqlSearchString");\n    if (foundNode != null)\n        return foundNode.InnerText;\n    return string.Empty;\n\n}	0
23702415	23254069	How to configure Entity Framework many-to-many with bi-directional lookup	HasMany().WithMany()	0
17927548	17927417	Get line with starts with some number	string output=File.ReadAllLines(path)\n                  .Last(x=>!Regex.IsMatch(x,@"^[\r\n]*$")); \nif(output.StartsWith("9"))//found	0
2723752	2723735	How to remove all zeros from string's beginning?	string no_start_zeros = s.TrimStart('0');	0
6179976	6179739	Show only a part of an ItemsControl's source at first	public class MyItemSource\n{\n    private List<string> source = { ... };\n\n    public MyItemSource()\n    {\n        this.ShowThisMany = 20;\n    }\n\n    public int ShowThisMany\n    {\n        get;\n        set; // this should call\use the INotifyPropertyChanged interface\n    }\n\n    public IEnumerable<string> this[]\n    {\n        return this.source.Take(this.ShowThisMany);\n    }\n}\n\n...\nMyItemsSource myItemsSource = new MyItemsSource();\nItemsControl.Source = myItemsSource;\n...\n\nvoid OnShowMoreClicked(...)\n{\n    myItemsSource.ShowThisMany = 50;\n}	0
20710811	20710754	How to convert float to int without losing the decimal ? Just like it's shown in memory	float f = 4.4f;\nvar bytes = BitConverter.GetBytes(f);\nint i = BitConverter.ToInt32(bytes, 0);	0
5314040	5313994	How would I do this MySQL query in C#?	SELECT\n--Choose the columns you want here\nFROM\nGrants\nINNER JOIN GrantsKeyConn ON Grants.ID = GrantsKeyConn.GrandsID\nINNER JOIN KeyWords ON GrantsKeyConn.KeyWordsID = KeyWords.ID\nWHERE\n--Filter here\nORDER BY\n--Order here	0
9311657	9311495	Get USD to INR exchange rate dynamically in C#?	WebRequest webrequest =WebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=INR");\n        HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();\n        Stream dataStream = response.GetResponseStream();\n        StreamReader reader = new StreamReader(dataStream);\n        string responseFromServer = reader.ReadToEnd();\n        XmlDocument doc = new XmlDocument();\n        doc.LoadXml(responseFromServer);\n        string value = doc.InnerText;\n        MessageBox.Show(value);\n        reader.Close();\n        dataStream.Close();\n        response.Close();	0
15575921	15575739	Trace Class - How to set Autoflush by code	Trace.AutoFlush = true;	0
25698597	25698535	Get Weight from Weighing Machine which is connected to COM1 and Get Fat content in milk from optional VGA	void spCom1_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n    spCom1.Open();\n    ....	0
29316145	29315507	Unity 5: access/modify AnimatorController from C# script in editor	public class AnimImportTools: MonoBehaviour{\n//.....\n\n    [MenuItem("CONTEXT/AnimatorController/Make transitions immediate")]\n    private static void makeTransitionsImmediate(){\n        UnityEditor.Animations.AnimatorController ac = Selection.activeObject as UnityEditor.Animations.AnimatorController;\n        foreach(var layer in ac.layers){\n            foreach(var curState in layer.stateMachine.states){\n                foreach(var transition in curState.state.transitions){\n                    transition.duration = 0.0f;\n                    transition.exitTime = 1.0f;\n                }\n            }\n        }\n    }\n//.....\n}	0
7905620	7853128	Dynamically build a table into a placeholder	private void AddTableTitles()\n    {\n        TableHeaderCell site  = new TableHeaderCell();\n        TableHeaderCell name  = new TableHeaderCell();\n        TableHeaderCell type  = new TableHeaderCell();\n        TableHeaderCell model = new TableHeaderCell();\n        TableHeaderRow  th    = new TableHeaderRow();\n\n        site.Controls.Add(AddSiteHeader());            \n        th.Controls.Add(site);\n        //AssignPlaceHolder.Controls.Add(th);\n\n        name.Controls.Add(AddMachNameHeader());            \n        th.Controls.Add(name);\n        //AssignPlaceHolder.Controls.Add(th);\n\n        type.Controls.Add(AddMachTypeHeader());            \n        th.Controls.Add(type);\n        //AssignPlaceHolder.Controls.Add(th);\n\n        model.Controls.Add(AddMachModelHeader());            \n        th.Controls.Add(model);\n\n        AssignPlaceHolder.Controls.Add(th);\n    }	0
34481913	34481826	Correct syntax for RowFilter	([Name, Surname] = 'xyz, abc' OR [Name, Surname] = 'uvw, def')"	0
9886060	9870124	Prevent CheckBox Checked event from firing	e.Handled = true;	0
7001904	6990392	How to remove controls from a container without container updating	panel.Visible = false;\n\n while (panel.Controls.Count > 0)\n {\n    panel.Controls[0].Dispose();\n }\n\n panel.Visible = true;	0
3448502	3448331	Fluent nHibernate - Map a list of strings	HasMany (o => o.PostAttachments).ForeignKeyConstraintName ("FK_Attachment_Post");	0
11828334	11828092	C# adding values to an instance after using a constructor	public class ComputeParam : IAction    \n{    \n    int _n;    \n    int _time;    \n    public ComputeParam()    \n    {    \n    }    \n    public ComputeParam(int n)    \n    {    \n        this._n = n;    \n    }  \n    public int Time \n    { \n        get { return this._time; }\n        set { this._time = value; }\n    }\n\n    public int N\n    {\n        get { return this._n; }\n        set { this._n = value; }\n    }\n\n\nfor(int i = 0; i < t.Count; i++) \n{ \n    ((ComputeParam)t[i]).Time = 6;\n}	0
17952117	17951764	c# propertygrid convert from uint to string	public class FruitConverter : TypeConverter\n{\n    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)\n    {\n        return fruits[(uint)value];\n    }\n}	0
33486604	33485825	What's the best way to create a line that starts at a point on another line and extends at a given angle for a given length?	1. figure out origin of the new branch<p>\n    a. BreakOffDistance = a random number less than the parent length (random distance from the start of the parent branch)\n    b. NewBranchOriginX = ParentBranchOriginX + BreakOffDistance * cos(ParentBranchAngle);\n    c. NewBranchOriginY = ParentBranchOriginY + BreakOffDistance * sin(ParentBranchAngle);\n2. figure out a random angle to the new, child line;\n    a. figure out random angle between 10 and 80 or 100 and 170.\n    b. NewBranchAngle = ParentBranchAngle - 90 + RandomAngle.\n       (all branch angles relative to horizontal, right?)\n3. figure out random length of new branch - less than parent?\n4. The previous steps determine the new branch - origin point, angle and length.  But to figure out its endpoint so you can draw it:\n    a. NewBranchEndX = NewBranchOriginX + NewBranchLength * cos(NewBranchAngle);\n    b. NewBranchEndY = NewBranchOriginY + NewBranchLength * sin(NewBranchAngle);	0
23504054	23503932	Template method pattern where each implementation requires different arguments?	public abstract DoAuthenticate( AuthenticationContext context );\n...\n\npublic UserWindowsLogon : User\n{\n  public override bool DoAuthenticate( AuthenticationContext context )\n  { \n     if ( context is UserWindowsAuthenticationContext )\n     {\n        // proceed\n     }\n  }\n}\n\npublic UserApplicationLogon : User\n{\n  public override bool DoAuthenticate( AuthenticationContext context )\n  {\n     if ( context is UserAplicationAuthenticationContext )\n     {\n        // proceed\n     }\n   } \n}\n\npublic abstract class AuthenticationContext { }\n\npublic class UserWindowsAuthenticationContext : AuthenticationContext\n{\n   public string windowsDomain;\n   public string password;\n}\n\npublic class UserApplicationAuthenticationContext : AuthenticationContext\n{\n   public string password;\n}	0
10169217	10169092	Split multi-lingual string using Regex to uni-lingual tokens	splitArray = Regex.Split(subjectString, \n    @"(?<=\p{IsArabic})    # (if the previous character is Arabic)\n    [\p{Zs}\p{P}]+         # split on whitespace/punctuation\n    (?=\p{IsBasicLatin})   # (if the following character is Latin)\n    |                      # or\n    (?<=\p{IsBasicLatin})  # vice versa\n    [\s\p{P}]+\n    (?=\p{IsArabic})", \n    RegexOptions.IgnorePatternWhitespace);	0
821935	819402	Add item in separated rows in listview	listView1.View = View.List;	0
19080586	19080508	Checklistbox issue displaying selection in message box	string display = "";\n\n// Every item in this collection is an item \n// with CheckState = Checked or Indeterminate\nif (clb.CheckedItems.Count != 0)\n{\n    StringBuilder sb = new StringBuilder();\n    foreach(string item in clb.CheckedItems)\n        sb.AppendLine(item);\n    display = "Items needed\n-----------\n\n\n" + sb.ToString();\n}\nelse\n{\n    display = "No items checked";\n}  \nMessageBox.Show(display, "Title");	0
19912977	19912853	Retrieve Image From Program Resources	imageList1.Images.Add(Properties.Resources.myImage);	0
4661624	4661248	Access a shared folder(which is protected)	System.IO.Directory.GetFolders(@"\\Server\Share");	0
12928175	12928144	create a set get class and pass parameter in constructor	public class pair\n{\n    public string Key { get; private set; }\n    public string Value { get; private set; }\n\n    public pair(string key, string value)\n    {\n        this.Key= key;\n        this.Value = value;\n    }   \n}	0
2927441	2927406	How to make multilanguage C# console application?	System.Resources.ResourceManager mgr = new\n    System.Resources.ResourceManager("MyConsoleApp.MyResource",\n    System.Reflection.Assembly.GetExecutingAssembly()) ;\n\nConsole.WriteLine ( mgr.GetString ("resourceName"));\n\nConsole.ReadLine ();	0
17146757	17125878	httpResponse one or two characters shorter	[ServiceContract] public class RawService {\n    [OperationContract, WebGet]\n    public System.IO.Stream GetValue()\n    {\n        string result = "Hello world";\n        byte[] resultBytes = Encoding.UTF8.GetBytes(result);\n        return new MemoryStream(resultBytes);\n    } }	0
11983569	11983496	C# Transactions on Oracle & SQL Server via ADO.NET failing	databaseConnectivityObject.DBFactoryDatabaseCommand.Transaction = databaseConnectivityObject.DBFactoryDatabaseConnection.BeginTransaction();	0
19527702	19481417	Calling API: How to provide these parameters (key, nonce and signature)	Convert.ToBase64String	0
1738522	1738492	Combine elements of my List	int counter = 0;\nforeach Action currAction in Action\n{\n    if (currAction.Type == "fold")\n    {\n        ++counter;\n    }\n    else\n    {\n        if (counter > 0)\n        {\n            \\ print it out and reset to zero\n        }\n        DoStuff();\n    } \n }	0
32691491	32525000	Linq SubSelect with Expression Trees	var whereExp = cars.AsQueryable<Car>().Where(whereConditionSub).Expression;\nvar countMethod = new Func<IQueryable<Car>, int>(Queryable.Count).Method;\nvar eSub1 = Expression.Call(countMethod, whereExp);	0
24941739	24941647	Get Server Machine IP	string hostName = System.Net.Dns.GetHostName();\nstring ipAddress = System.Net.Dns.GetHostEntry(hostName).AddressList[index].ToString();	0
7539990	7539973	linq changing order of columns	from t in table \nselect new{ Id = t.Id, Article = t.Article, Lot = t.Lot }	0
29507340	29457152	IExplorerBrowser - Browse in place without starting default application	HResult ICommDlgBrowser3.OnDefaultCommand(IntPtr ppshv)\n    {\n        if (SelectedItems.Count > 0)\n        {\n            var item = SelectedItems[0];\n\n            ShellNativeMethods.ShellFileGetAttributesOptions sfgao;\n            item.NativeShellItem2.GetAttributes(ShellNativeMethods.ShellFileGetAttributesOptions.Folder, out sfgao);\n            bool isFolder = (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.Folder) != 0;\n\n            if (isFolder)\n            {\n                Navigate(SelectedItems[0]);\n                return HResult.Ok;\n            }\n        }\n        return HResult.False;\n    }	0
28669517	28669272	Retrieve BASE64 encryption from AJAX call	{"ProductSizeAndColor":{"productIds":"prod174690614"}}	0
26732408	26732291	How to get Bus Reported Device Description using C#	string description = (string)device.GetPropertyValue("Description");	0
11386139	11378876	How can I animate a TextBlock when a SelectionChanged() event of a ListBox is called?	private string _textBlockText;\n        public string textBlockText\n        {\n            get { return _textBlockText; }\n            set\n            {\n                if (txtSample.Text != value)\n                {\n                    if (Storyboard1.GetCurrentState() != ClockState.Active)\n                        Storyboard1.Begin();\n                    txtSample.Text = value;\n                }\n            }\n        }	0
4997136	4997085	How to convert to double with 2 precision - string after dot?	double d = double.Parse(s,CultureInfo.InvariantCulture);\nstring s=string.Format("{0:0.00}",d);	0
4870481	2466060	GridView - set selected index by searching through data keys	foreach(GridViewRow myRow in GridView1.Rows)\n{\n    if(GridView1.DataKeys[myRow.RowIndex].Value.Equals("keyValue"))\n    {\n        GridView1.SelectedIndex = myRow.RowIndex;\n        break;\n    }\n}	0
16305135	16305077	Modifying a datetime object	DateTime date = DateTime.Now.Date;\nDateTime time = DateTime.Now;\n\nDateTime dateAndTime = date.Date + time.TimeOfDay;	0
28455626	28455582	How can I use this variable C#	string delimiter = "id=ContentPlaceHolder1_txtDirecciones style=\"HEIGHT: 19px; WIDTH: 190px\" type=text readOnly value=" ;	0
15530220	15526390	What steps do you need to take to regenerate the manifest when using Click Once deployment	-update	0
21309182	21308989	while increasing height particular row of data grid view affecting last row also	for (int i = 0; i < gv.Rows.Count - 1; i++)	0
4134809	4134641	Sequential Asynchronous Tasks Without Blocking	Task firstTask = new Task(()=>RunStepOne());\nfirstTask.ContinueWith(task=>()=>RunSecondStep());\nfirstTask.Start();	0
21935944	21935430	Confirm Delete with Password in ASP.NET MVC	if (Membership.ValidateUser(username, password))\n      // Do Delete\n   else\n      // Don't do Delete	0
23850442	23850399	Add split strings to properties in new list	listOfProducts.Add(new Product() { Id = idPart, ProductName = gtinPart });	0
22438029	22239033	Unwanted page refresh after AJAX request that runs SQL	live.js	0
28786120	28786011	Format string not working in C# getter	private DateTime _pe1;\npublic string PassportEnd1\n{\n    get { return _pe1.ToString("yyyymmdd"); }\n    set { _pe1 = DateTime.ParseExact(value, "dd.mm.yyyy", CultureInfo.InvariantCulture); }\n}	0
16900758	16900668	Library function to generate URL from an ASP.Net Web API controller?	var uri = linker.GetUri<FooController>(r => r.Get(<parameter values go here>));	0
2333548	2333412	XmlDocument::Save() appends the xml in file	fs.SetLength(0);	0
21367604	21367366	List of double arrays - how detect duplicates	var results = list.GroupBy(a => String.Join(",", a.Select(d => d.ToString())))\n                  .Where(g => g.Count() > 1)\n                  .Select(g => g.First())\n                  .ToList();	0
5815368	5814134	Get email address from OpenID Provider with DotNetOpenAuth	switch (response.Status)\n {\n     case AuthenticationStatus.Authenticated:\n         var fetch = response.GetExtension<FetchResponse>();\n         string email = String.Empty; \n         if (fetch != null)\n         {\n            email =  fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);\n         }  \n        break;\n    //...\n}	0
1539711	1539685	How programmatically submit a form without a submit button in WebBrowser	HtmlElementCollection elements = this.webBrowserControl.Document.GetElementsByTagName("Form");  \n\nforeach(HtmlElement currentElement in elements)\n{\n    currentElement.InvokeMember("submit");\n}	0
30485026	30483223	VSTO Outlook 2013 Addin Quit	Outlook.Application outlook = new Outlook.Application();\n\nif (outlook.Application.COMAddIns.Item("OutlookAddIn").Connect)\n{\n    outlook.Application.COMAddIns.Item("OutlookAddIn").Connect = false;\n}\nelse\n{\n    outlook.Application.COMAddIns.Item("OutlookAddIn").Connect = true;\n}	0
23122172	23122043	Rotate a point using transformation matrix	var point = new PointF(100, 150);\nvar center = new PointF(100, 100);\nvar angle = 45;\n\nvar rotateMat = Cv2.GetRotationMatrix2D(new Point2f(center.Y, center.X), angle, 1);\nvar resultPoint = (rotateMat * point.ToMat()).ToMat().ToPointF();\n\nstatic class Hlp\n{\n  public static PointF ToPointF(this Mat mat)\n  {\n    return new PointF((float)mat.Get<double>(1, 0), (float)mat.Get<double>(0, 0));\n  }\n  public static Mat ToMat(this PointF point)\n  {\n    return new Mat(3, 1, MatType.CV_64FC1, new double[] { point.Y, point.X, 1 });\n  }\n}	0
22815567	22815419	Create a html file and save in a folder	String content = GenerateHtml();\n        System.IO.File.WriteAllText(@"C:\yoursite.htm", contents);	0
9480208	9479910	ASP.NET Control visibility dilemma	protected void odsSomething_ObjectCreating(object sender, ObjectDataSourceEventArgs e)\n{\n    e.ObjectInstance = YourInsntanceAlreadyInThePage;\n}	0
15377728	15376321	Running time take its too long for adding and finding string from txt	static Dictionary<int, string> getDBList(string DBname)\n{\n    Dictionary<int, string> WordsDictionary = new Dictionary<int, string>();\n    string[] files;\n\n    try\n    {\n        files = Directory.GetFiles(@"dbase/", DBname);\n        foreach (string file in files)\n            foreach (string line in File.ReadAllLines(file))\n            {\n                 string data = line.Trim().ToUpperInvariant();\n                 int hash = data.GetHashCode();\n\n                 if(!WordsDictionary.ContainsKey(hash))\n                     WordsDictionary.Add(hash, data);                   \n            }\n        }\n\n\n    catch (Exception ex)\n    {\n        Console.WriteLine(ex.ToString());\n        return new Dictionary<int, string>();\n    } \n    return WordsDictionary;\n}\n\nstatic bool SearchText(string text, Dictionary<int, string> WordsDictionary)\n{\n    int hash = text.Trim().ToUpperInvariant().GetHashCode();\n\n    if (WordsDictionary.ContainsKey(hash))\n        return true;\n    else\n        return false;\n}	0
20298884	20298799	ListBox not databinding	public struct StyleDocumentFile\n{\n    public string Image { get; set; }\n    public string FileName { get; set; }\n    public string State { get; set; }\n}	0
27602297	27601267	Replace \r\n in a csv column using Regex	var result = Regex.Replace(input, @"""(?:(\r\n)|[^""])+""", delegate(Match m)\n            {\n                if (string.IsNullOrEmpty(m.Groups[1].Value))\n                    return m.Value;\n                return m.Value.Replace("\r\n", " ");\n            });	0
23318149	23317976	Find node with the highest density in graph	public Node LeaderIs(List<Node> list)\n{\n    Node Leadernode = null;\n    int LeadernodeDensity = 0;\n    for (int k = 0; k < list.Count; k++)\n    {\n        var i = YelloWPages.GetNode(k, list);\n        int iDensity = Node.GetDensity(i); \n        if ( iDensity > LeadernodeDensity)\n        {\n            Leadernode = i;\n            LeadernodeDensity = iDensity;\n        }\n\n    }\n    return Leadernode;\n}	0
10213371	9235203	TreeView Where Root And All Nodes Thereafter Are Derived From First Sub-Folder - How To Specify Correct Path?	if(subDirs.Lenght != 0)        // or > 0\n{\n  string pathToSubFolders = Path.Combine(dirInfo.ToString(), subDirs[0].ToString());\n  PopulateTreeView(treeView1, pathToSubFolders);\n}\nelse\n{\n  //Do Something Here\n}	0
22573124	22564499	MonoGame Key Pressed String	private string _stringValue = string.Empty;\n\n    protected override void Update(GameTime gameTime)\n    {\n        var keyboardState = Keyboard.GetState();\n        var keys = keyboardState.GetPressedKeys();\n\n        if(keys.Length > 0)\n        {\n            var keyValue = keys[0].ToString();\n            _stringValue += keyValue;\n        }\n\n        base.Update(gameTime);\n    }	0
10130514	10130362	Randomly assign the contents of a Button	List<string> Shuffle(List<string> answers)\n    {\n        Random r = new Random();\n        Dictionary<int, string> d = new Dictionary<int, string>();\n        foreach (var answer in answers)\n        {\n            d.Add(r.Next(), answer);\n        }\n        return d.OrderBy(a => a.Key).Select(b => b.Value).ToList();\n    }	0
4393574	4393563	How do I load an XML formatted string into an XElement	XElement x = XElement.Parse(xmlstring);	0
9726811	9726442	Bitmap to Base64String 	public string BitmapToBase64(BitmapImage bi)\n        {\n            MemoryStream ms = new MemoryStream();\n            PngBitmapEncoder encoder = new PngBitmapEncoder();\n            encoder.Frames.Add(BitmapFrame.Create(bi));\n            encoder.Save(ms);\n            byte[] bitmapdata = ms.ToArray();\n\n            return Convert.ToBase64String(bitmapdata);\n        }	0
20315506	20313220	playing array filled with pcm values in real time	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        var player = new Player();\n\n        var rand = new Random();\n        var bytes = new byte[32000];\n        rand.NextBytes(bytes);\n\n        player.AddSamples(bytes);\n    }\n}	0
4521131	4521060	Name cannot be found in current context	// keep a static instance around\n    static Tester tester = new Tester();\n? ? static void contract_details(object sender, ContractDetailsEventArgs e) // This method has to be static.\n? ? {\n        // call the method on the static instance        ? ? ? ? \n? ? ? ? tester.MyOptionChainsInput(e.ContractDetails.Summary.Expiry, e.ContractDetails.Summary.Strike); \n? ? ?}	0
1325050	1325025	Unique Application Key	Guid.NewGuid()	0
32295427	32294997	Read a txt file in C#	string checkMacOutcome = "";\n        var psi = new System.Diagnostics.ProcessStartInfo(ejecutable_CheckMac, archivo_temporal);\n        psi.UseShellExecute = false;\n        psi.CreateNoWindow = true;\n        psi.RedirectStandardOutput = true;\n\n        using (var proc = System.Diagnostics.Process.Start(psi))\n        {\n            using (StreamReader sr = proc.StandardOutput)\n            {\n                checkMacOutcome = sr.ReadToEnd();\n            }\n        }\n\n        StreamWriter writetext = new StreamWriter(archivo_resultado);\n        writetext.WriteLine(checkMacOutcome);\n        writetext.Close();	0
17347023	17297374	Adding an euler angle to a Quaternion	Quaternion result = PitchRotationQuaternion * oldTransform * YawRotationQuaternion;	0
30279352	30279300	change the order of a file	files.Reverse();	0
1049431	1049411	C# string handling how get path and args from a string	string[] pathAndArgs = Text.Split(new Char[] { '/"' }, 3);\nstring[] args = pathAndArgs[2].Split(new Char[] { ' ' }, 2);	0
7248166	7246886	How do I cancel and rollback a custom action in VS2010 Windows Installer?	using Microsoft.Deployment.WindowsInstaller;\nnamespace CustomAction1\n{\n    public class CustomActions\n    {\n        [CustomAction]\n        public static ActionResult ActionName(Session session)\n        {\n            try\n            {\n                session.Log("Custom Action beginning");\n\n                // Do Stuff...\n                if (cancel)\n                {\n                    session.Log("Custom Action cancelled");\n                    return ActionResult.Failure;\n                }\n\n                session.Log("Custom Action completed successfully");\n                return ActionResult.Success;\n            }\n            catch (SecurityException ex)\n            {\n                session.Log("Custom Action failed with following exception: " + ex.Message);\n                return ActionResult.Failure;\n            }\n         }\n    }\n}	0
21544106	21543024	Convert a delimited string to a dictionary<string,string>	"=key1=value1=key2=value2=key3=value3"\n    .Split('=')                            // Split into an array of strings\n    .Skip(1)                               // Skip the first (empty) value\n    .Select((v, i) => new { v, i })        // Get value and index\n    .GroupBy(x => x.i / 2)                 // Group every pair together\n    .ToDictionary(g => g.First().v,        // First item in group is the key\n                  g => g.Last().v)         // Last item in group is the value	0
20860944	20860193	WPF Delete Row from grid	this.chartForm.sciChartControl.ContentGrid.Children.Remove(scs);\nthis.chartForm.sciChartControl.ContentGrid.RowDefinitions.Remove(this.techIndicatorToRowDefinitionMap["ADX"]);	0
12453429	12453357	Split and replace string	string path = "/fm/Templates/testTemplate/css/article.jpg";\npath = path.Substring(path.IndexOf('/', 1)).Replace("/", "\\\\");	0
1743931	1743898	IIS6 Running a ASP.NET Virtual Dir under a classic ASP Website	It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.	0
10820846	10820788	Get Mouse State without access to MouseEventArgs?	private void timer1_Tick(object sender, EventArgs e) {\n  this.Text = "Mouse Is " + (MouseButtons == MouseButtons.Left);\n}	0
29957097	29952360	How to deal with RadioGroup.SetOnCheckedChangeListener?	radG.CheckedChange += (sender, e) => {\n    Console.WriteLine(view.FindViewById<RadioButton>(e.CheckedId).Text);\n}	0
9684044	9683992	How to properly write file path for portable files?	string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n\npath = System.IO.Path.Combine(path, "User Guide Outline.pdf");\nSystem.Diagnostics.Process.Start(path);	0
2708297	2708243	Custom Control Overriding Command Button	protected override Size DefaultSize\n        {\n            get\n            {\n                return new Size(840, 340);\n            }\n        }	0
9518470	9518275	C# Retrieve FormFields from Word Document and Insert into Text file	foreach(Field wdField in workDoc.Fields)\n    {\n        if (wdField.Type == WdFieldType.wdFieldMergeField)\n        {\n            wdField.Select();\n            string fieldText = wdField.Result.Text;\n        }\n    }	0
6767867	6767794	Linq to XML, C#	foreach (var node in xDoc.Descendants()) \n{ \n    node.Name = ns + node.Name.LocalName; \n}	0
1644254	1644079	How can I use the Dispatcher.Invoke in WPF? Change controls from non-main thread	Application.Current.Dispatcher.BeginInvoke(\n  DispatcherPriority.Background,\n  new Action(() => this.progressBar.Value = 50));	0
18833707	18829777	how to add cookies in my Katana Hosted WebAPI with Basic Authentication,	var identity = new ClaimsIdentity(CookieAuthenticationDefaults.ApplicationAuthenticationType);\nidentity.AddClaim(new Claim(ClaimTypes.Name, "Test"));\nAuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, new AuthenticationProperties()\n{\n    IsPersistent = true\n});	0
13951010	13950499	Why am I getting a runtime error when I try to convert from an ImageSource to a BitmapImage?	private void Window_Loaded_1(object sender, RoutedEventArgs e)\n{\n    var image = new BitmapImage(new Uri("sample.bmp", UriKind.Relative));\n    MyImage.Source = image;\n}	0
14412529	14412507	How to add a DataRow into a different DataTable?	this.currentDataTable.Rows.Add(drr.ItemArray);	0
22183301	22183176	How to pass a parameter to hub in SignalR?	ConnectionId, EmployeeID	0
28642893	28642851	How to remove PictureBoxes dynamically?	private void timer1_Tick(object sender, EventArgs e)\n    {\n        Random rnd = new Random();\n        int l = rnd.Next(1,545);\n        RD[ndrop] = new PictureBox();\n        RD[ndrop].BackColor = System.Drawing.Color.MediumBlue;\n        RD[ndrop].Size = new Size(5, 5);\n        RD[ndrop].Location = new Point(l, 0);\n        RD[ndrop].LocationChanged += pb_LocationChanged;\n        this.Controls.Add(RD[ndrop]);\n        ndrop++;\n        dropIt();\n    }\n\n\nvoid pb_LocationChanged(object sender, EventArgs e)\n    {\n        // FORM_LASTBOUND is the Y-Axis point after which you wanted to remove the picturebox.\n        if ((sender as PictureBox).Top > FORM_LASTBOUND)\n        {\n            this.Controls.Remove(sender as PictureBox);\n        }\n\n    }	0
20076932	20075530	How to Save a Hashed Password and Salt to Varbinary Table Column From Code First Seed Method?	public static byte[] Base64StringToByteArray(string base64String) {\n        return Convert.FromBase64String(base64String);\n    }\n\n\n    public static byte[] UnicodeStringToByteArray(this string source) {\n        return Encoding.Unicode.GetBytes(source);\n    }\n    public static byte[] UTF8StringToByteArray(this string source)\n    {\n        return Encoding.UTF8.GetBytes(source);\n    }	0
31654166	31451947	ASP .NET MVC 5 model binding of byte[] produces null value with ajax GET reqest	public ActionResult Index(IEnumerable<byte> status, byte type)	0
11206070	11205828	Suggestions for a long lasting operation for testing purpose	Stopwatch stopWatch = new Stopwatch();\n        stopWatch.Start();\n\n        for (int i = 0; i < 10000000; i++)\n        {\n            double test = 1000; \n            test = (test * 100000.00001)/100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n            test = (test * 100000.00001) / 100000.123123;\n\n        }\n\n        stopWatch.Stop();\n        var executionTime = stopWatch.ElapsedMilliseconds;	0
12248742	12248674	How can I assert that a C# async method throws an exception in a unit test?	[ExpectedException(typeof(NotImplementedException))]	0
7095070	7094392	Data Grid View Reversing Members: Resolved	dataGridView1.AutoGenerateColumns = false;\nDataGridViewColumn column = new DataGridViewColumn();\n        column.DataPropertyName = "Question Number";\n        column.HeaderText = "Question Number";\ndataGridView1.Columns.Add(column);	0
27325023	27324859	How to write half-space in c#	TextBox.Text += '\u2009';	0
15528536	15528330	Convert class to string to send via email	public static string ClassToString(Object o)\n{\n    Type type = o.GetType();\n    StringBuilder sb = new StringBuilder();\n    foreach (FieldInfo field in type.GetFields())\n    {\n        sb.Append(field.Name).AppendLine(": ");\n        sb.AppendLine(field.GetValue(o).ToString());\n    }\n    foreach (PropertyInfo property in type.GetProperties())\n    {\n        sb.Append(property.Name).AppendLine(": ");\n        sb.AppendLine(property.GetValue(o, null).ToString());\n    }\n    return sb.ToString();\n}	0
30433914	30433592	Why is the size of byte array not bmp.Width * bmp.Height * 4 after converting a Bitmap into a byte array?	public static byte[] BitmapToByteArray(Bitmap bitmap)\n{\n    BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);\n    int numbytes = bmpdata.Stride * bitmap.Height;\n    byte[] bytedata = new byte[numbytes];\n    IntPtr ptr = bmpdata.Scan0;\n\n    Marshal.Copy(ptr, bytedata, 0, numbytes);\n\n    bitmap.UnlockBits(bmpdata);\n\n    return bytedata;\n}	0
6330346	6330233	Read ID from URL and create a new one	int ID = 0;\n\nint.TryParse(Request.QueryString["ID"], out ID);\n\nif (ID > 0)\n{\n    Response.Redirect(String.Format("http://www.xyzabc.com/DisplayProduct?ID={0}", ID));\n}	0
25854661	25854136	Foreach noop hides all elements in mocked Dbset	mockItemDbSet.As<IQueryable<Item>>().Setup(m => m.GetEnumerator()).Returns(() =>\n        {\n            var enumerator = items.GetEnumerator();\n            enumerator.Reset();\n            return enumerator;\n        });	0
17372435	17372407	C# - binding datatable to reportviewer	var reportDataSource1 = new ReportDataSource { Name = "WpfApplication17_User", Value = _users };\nstring exeFolder = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);\n_reportViewer.LocalReport.ReportPath =exeFolder + @"\Reports\Report1.rdlc";\n_reportViewer.LocalReport.DataSources.Add(reportDataSource1);\n_reportViewer.RefreshReport();	0
28645680	28634006	Find the name of the invoked method of a Func delegate	public static class Invoker {\n    public static void Invoke(Proxy proxy, Expression<Func<Proxy,string>> online) {\n        var methodName = ((MethodCallExpression)online.Body).Method.Name;\n\n        if (IsCached(proxyName, methodName)) {\n            output = GetFromCache(proxyName, methodName);\n        } else {\n            if (IsFuncCached(methodName)) {\n                func = GetFuncFromCache(methodName);\n            } else {\n                func = online.Compile();\n                // add func to "func cache"...\n            }\n            output = func(proxy);\n        }\n    }\n}	0
30898231	30898034	How can I omit NULL values when converting DataRow to a Dictionary in C#?	Dictionary<string, Dictionary<string, object>> DataTableToDictionary(DataTable dt, string prefix, string id)\n    {\n        var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != id);\n        return dt.Rows.Cast<DataRow>()\n                 .ToDictionary(r => prefix + r[id].ToString(),\n                               r => cols.Where(c => !Convert.IsDBNull(r[c.ColumnName])).ToDictionary(c => c.ColumnName, c => r[c.ColumnName]));\n    }	0
13461047	13299011	I need to send whole word at a time but Selenium webdriver send keys alphabet by alphabet.. Any suggestion	string recipient_last_name = myReader2["last"].ToString().ToLower();\nIWebElement tPATIENT_LAST_NAME = driver.FindElement(By.Name("LAST_NAME"));  \n          tPATIENT_LAST_NAME.SendKeys(recipient_last_name);	0
3085947	3085909	C# generics - Can I make T be from one of two choices?	Class D<T> where T : A, Ibc {...}	0
21600390	21599286	Commit after MessageBox in C#	using (var scope = TransactionHelper.Instance)\n{\n var process = true;\n var aMessage = "";\n try\n {\n   //Enter you code and functions here\n   //Whenever you find a piece of code to be working incorrectly, Raise an error\n   if(!someCode(blabla))\n      throw new Exception("This someCode quited on me!");\n   //Whenever your code does what it needs to do, end with a commit\n   scope.Commit();\n }\n catch(Exception ex) //Catch whatever exception might occur\n {\n  scope.FullRollBack(); \n  aMessage = ex.Message;\n  process = false;\n }\n finally \n {\n  //only here you will use messageboxes to explain what did occur during the process\n  if (process)\n    MessageBox.Show("Succesfully Committed!");\n  else\n    MessageBox.Show(string.Format("Rollback occurred, exception Message: {0}"\n                    , aMessage);\n }\n}	0
32093330	32091182	How to manage the onClose of windows phone 8.1 application	Application.Suspending	0
28426386	28426279	Escaping backslashes in string	string path = @"C:\some_folder\\some_file.bin";\n   string exactPath = string.Join("\\",path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));	0
4746032	4745994	How can I add to a List's first position?	List<T>.Insert(0, item);	0
13930392	13930331	Exactly how long is `InSingletonScope` for a webapp?	Application_Start()	0
24146195	24146079	LINQ - Cannot implicitly convert type with custom data model list property	Submodels = x.Select(s => new Submodel{SubmodelName = s.Submodel}).ToList()	0
28587429	28587278	Fetch data From Two tables using Linq	var result = from a in Context.Articles\n             join c in Context.Comments on a.ArticleId equals c.ArticleId\n             select new{ Article = a, Comment = c});	0
2891264	2891258	How to create a dll file	Class Library	0
29427663	29427530	How to get value from Dictionary<string,object>	var res = from l in MyList\n              from q in SomeDictionary\n              from w in q.Value\n              where w.Value == l\n              select w;	0
6904990	6903408	Parse through paramaterized string for oledb	public void ExecuteQuery(string sql, params object[] parameters)\n{\n    //format the sql string with safe parameter names\n    var paramNames = new string[parameters.Length];\n    for (int i = 0; i<parameters.Length; i++)\n    {\n        paramNames[i] = "?";\n    }\n    sql = string.Format(sql, paramNames);\n\n    using (OleDbConnection sqlConnect = drtevs.GetConnection())\n    {   \n        OleDbCommand command.CommandText = sql;\n\n        foreach (int i = 0; i< parameters.Length; i++)\n        {\n            command.Parameters.Add(new OleDbParameter("?", parameters[i]));\n        }\n\n        command.ExecuteNonQuery();\n\n    }\n}	0
12465836	12371388	Popup position to Bottom-Right	PART_Popup.CustomPopupPlacementCallback += (Size popupSize, Size targetSize, Point offset) => new[] { new CustomPopupPlacement() { Point = new Point(targetSize.Width - popupSize.Width, targetSize.Height) } };	0
34207449	34207383	How can I prevent a "possible loss of fraction"?	_percentageOfQtyShipped = frbdcbl.QtyShipped/(double)frbdcbl.QtyOrdered;	0
15366335	15366172	testing a Post in WebAPI from a form with JSON	jQuery.post	0
15441492	15441376	Replace the ServerName in a UNC Path	string path = @"\\server1\folder\child";\n\nvar uri = new Uri(path);\n\nstring newPath = @"\\server2" + uri.AbsolutePath.Replace('/', '\\');\n\nvar x = new Uri(newPath);	0
25281162	25281020	Convert string to datetime now format	TimeSpan tsDifference = DateTime.ParseExact("23:59", "HH:mm", System.Globalization.CultureInfo.InvariantCulture) - DateTime.Now;	0
27836301	27836156	Get first word on every new line in a long string?	using System;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string str ="name1|10|junk data.....\nname2|9|junk data.....\nname3|8|junkdata.....\nname4|7|junk data.....";\n\n        foreach (var line in str.Split('\n'))\n        {\n            Console.WriteLine(line.Split('|')[0]);  \n        }\n    }\n}	0
4740292	4739407	Exporting a Certificate as BASE-64 encoded .cer	/// <summary>\n/// Export a certificate to a PEM format string\n/// </summary>\n/// <param name="cert">The certificate to export</param>\n/// <returns>A PEM encoded string</returns>\npublic static string ExportToPEM(X509Certificate cert)\n{\n    StringBuilder builder = new StringBuilder();            \n\n    builder.AppendLine("-----BEGIN CERTIFICATE-----");\n    builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));\n    builder.AppendLine("-----END CERTIFICATE-----");\n\n    return builder.ToString();\n}	0
12229676	12229532	Unable to use an index on the selected item of a ListBox	if (emails.SelectedItem != null)\n{\n    var item = emails.SelectedItem.ToString();\n    for (int i = 1; i < item.Length; i++)\n    {\n         clone.Items.Add(item.Insert(i, "."));\n    }\n}	0
31087295	31073763	Create a console application that opens a TCP/IP connection and print the inputted string - in C++, C# or Java	String hostName = args [0];\n    int portNumber = Integer.parseInt(args [1]);\n    String transmit = args [2];\n\n    try (\n        Socket echoSocket = new Socket(hostName, portNumber);\n        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);\n        BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));\n        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))\n    )\n        {\n            out.println(transmit);\n            String response = in.readLine ();\n            while (response != null) {\n                System.out.println("echo: " + response);\n                response = in.readLine ();\n            }\n        }	0
2617925	2617896	Split comma separated string to count duplicates	IEnumerable<string> strings = ...;\n\nDictionary<string,int> result = strings.SelectMany(s => s.Split(','))\n                                       .GroupBy(s => s.Trim())\n                                       .ToDictionary(g => g.Key, g => g.Count());	0
32824897	32824835	Foreach Statement	protected void btnAdd_Click(object sender, EventArgs e)\n{\n\n    foreach (ListViewItem item in lvPODetails.Items)\n    {\n        TextBox quantity = (TextBox)item.FindControl("txtQuantity");\n        Literal ltr = (Literal)item.FindControl("ltRefNo");\n\n\n        con.Open();\n        SqlCommand cmd = new SqlCommand();\n        cmd.Connection = con;\n        cmd.CommandText = "INSERT INTO Inventory VALUES (@ProductID, @Quantity)";\n        cmd.Parameters.AddWithValue("@ProductID", ltr.Text);\n        cmd.Parameters.AddWithValue("@Quantity", quantity.Text);\n        cmd.ExecuteNonQuery();\n        con.Close();\n\n    }\n\n}	0
22208451	22208245	Find next closest date	List<string> dates = new List<string>();\n            dates.Add("1/10/14");\n            dates.Add("2/9/14");\n            dates.Add("1/15/14");\n            dates.Add("2/3/14");\n            dates.Add("2/15/14");\n\n            var allDates = dates.Select(DateTime.Parse).OrderBy(d=>d).ToList();\n            var inputDate = DateTime.Parse("1/13/14");\n\n            var closestDate = inputDate >= allDates.Last()\n                ? allDates.Last()\n                : inputDate <= allDates.First()\n                    ? allDates.First()\n                    : allDates.First(d => d >= inputDate);	0
9590890	9588265	Understanding WCF Windows Authentication	OperationContext.Current.ServiceSecurityContext.WindowsIdentity	0
6916080	6914771	Accessing variables of a referenced class library in a Winforms application	dataLibrary.DataAdapters.tblCustomerTableAdapter customerAdapter = new dataLibrary.DataAdapters.tblCustomerTableAdapter(); //this is the instance of the dataAdapter\n    dataLibrary.DataSet.tblCustomerDataTable customerTable = new dataLibrary.DataSet.tblCustomerDataTable(); //this is the instance of the dataTable\n\n    int rowsCount = customerTable.Rows.Count;	0
9739281	9739223	Regex finding the pattern	var result = Regex.IsMatch(input, @"NAME\s.*?\sRANK\s{3}");	0
5039658	5039631	In a drap and drop between explorer and your app, how to know your app directory?	Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)	0
950804	950747	C# Removing rows from a datagrid where a cell value is not NULL using LIKE	strFilterText+= string.IsNullOrEmpty(txtboxValue.Text)? " IS NULL" : " LIKE '%" + txtboxValue.Text + "%'";	0
28839695	28839410	Output my XML schema to HTML	MemoryStream ms = new MemoryStream();\nschema.Write(ms);\nms.Flush();\nreturn new FileStreamResult(ms, "text/xml");	0
10829884	10828720	How to validate xml file with schema where schema is in string format	StringReader stringReader = new StringReader("XmlSchema"); \nXmlSchema xmlSchema;\nxmlSchema = XmlSchema.Read(stringReader, null);\nsettings.Schemas.Add(xmlSchema);	0
21017503	21017115	Problems with dynamic height in Windows Phone 8 (see sketch inside)	var BAndCHeight = contentGrid.ActualHeight - element_A.ActualHeight;	0
14120459	14120246	Page cannot be null during converting a grid	Page.Form.Controls.Add(gv);	0
9133734	9133350	how to get windows phone 7 GPS timespan diff	x = earthRadius * cos(latitude) * cos(longitude);\ny = earthRadius * -sin(latitude);\nz = earthRadius * cos(latitude) * sin(longitude);	0
5199928	5199888	Task.Factory.StartNew with multiple parameters	Task<Domain> someDomainTask = Task<Domain>.Factory.StartNew(() => \n  { \n    return ImportDomain(myConstructor, myAttributes, myDate);\n  } \n);\nDomain someDomain = someDomainTask.Result;	0
24169210	24169163	Getting the percentage of a slider	double distanceFromMin = (slider1.Value - slider1.Minimum);\ndouble sliderRange =  (slider1.Maximum - slider1.Minimum);\ndouble sliderPercent = 100 * ( distanceFromMin / sliderRange );	0
27646551	27646476	How to fire form click event even when clicking on user controls in c#	[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]\n    protected override void WndProc(ref Message m)\n    {\n        // 0x210 is WM_PARENTNOTIFY\n        // 513 is WM_LBUTTONCLICK\n        if (m.Msg == 0x210 && m.WParam.ToInt32() == 513)\n        {\n            // get the clicked position\n            var x = (int)(m.LParam.ToInt32() & 0xFFFF);\n            var y = (int)(m.LParam.ToInt32() >> 16);\n\n            // get the clicked control\n            var childControl = this.GetChildAtPoint(new Point(x, y));\n\n            // call onClick (which fires Click event)\n            OnClick(EventArgs.Empty)\n\n            // do something else...\n        }\n        base.WndProc(ref m);\n    }	0
2592944	2592684	Returning S_FALSE from a C# COM dll	/PreserveSig	0
9739536	9739032	Set up application resources from code	ResourceDictionary myResourceDictionary = new ResourceDictionary();\n\nmyResourceDictionary.Source = new Uri("Dictionary1.xaml", UriKind.Relative);\nApplication.Current.Resources.MergedDictionaries.Add(myResourceDictionary);\n\nmyResourceDictionary.Source = new Uri("Dictionary2.xaml", UriKind.Relative);\nApplication.Current.Resources.MergedDictionaries.Add(myResourceDictionary);	0
22690882	22690842	Extract a string field from list	var status = StudentInfo.Where(x => x.ID == studentId)\n                        .Select(x => x.Status)\n                        .FirstOrDefault();	0
3917999	3917471	WorkflowItemPresenter contents disappear on build	Activity IActivityTemplateFactory.Create(System.Windows.DependencyObject target)\n{\n    return new Trigger \n    {\n        DisplayName = "lol trigger",\n        Condition = new ActivityFunc<bool>(),\n        Child = new ActivityAction(),\n        MatchType = MatchType.Lol\n    };\n}	0
5195691	5195653	How to get all drives in PC with .NET using C#	foreach(var drive in DriveInfo.GetDrives())\n{\n    Console.WriteLine("Drive Type: {0}", drive.DriveType);\n    Console.WriteLine("Drive Size: {0}", drive.TotalSize);\n    Console.WriteLine("Drive Free Space: {0}", drive.TotalFreeSpace);\n}	0
3752337	3751649	C# - Combobox index change after editing	private int currentIndex;\n\npublic Form1()\n{\n    InitializeComponent();\n\n    comboBox1.SelectedIndexChanged += RememberSelectedIndex;\n    comboBox1.KeyDown += UpdateList;\n}\n\nprivate void RememberSelectedIndex(object sender, EventArgs e)\n{\n    currentIndex = comboBox1.SelectedIndex;\n}\n\nprivate void UpdateList(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Enter && currentIndex >= 0)\n    {\n        comboBox1.Items[currentIndex] = comboBox1.Text;\n    }\n}	0
1354376	1354367	Display List contents specific field in a ComboBox (C#)	public class PriceChange {\n    public string Description{\n        get;\n        set;\n    }\n    // ...\n}	0
34253008	34252953	How to change Opacity of WPF window via if-else condition?	private void rt_tick(object sender, EventArgs e) //round timer\n{\n   if(i!=0)\n   {\n       i--;\n       txbTime.Text = "";\n       txbTime.Text = Convert.ToString(i) + "s";\n   }\n   else \n   { \n        this.Opacity = 0.7;\n   }                \n}	0
10102940	10102896	C# - Fastest way to find one of a set of strings in another string	Regex rx = new Regex("(" + string.Join("|", swearWords) + ")");\nrx.IsMatch(myString)	0
8055795	8038236	MonoTouch and "Applications are expected to have a root view controller at the end of application launch" error	if (UIDevice.CurrentDevice.CheckSystemVersion (5, 0))\n            window.RootViewController = navigation; \n        else\n            window.AddSubview (navigation.View);	0
3133940	3133010	How do I change the URL of a SoapHttoClientProtocol object?	[SoapDocumentMethod]	0
19261387	19261343	Random value from Dictionary?	List<T>	0
27165281	27165107	Check HMAC-SHA1 without key in C#	var hmacSha = new HMACSHA1(Encoding.UTF8.GetBytes("yourConstantKey"));	0
920922	11804	Returning Large Results Via a Webservice	WS-ReliableMessaging	0
6896094	6895863	Customize a struct so that it serializes as a Int32	private int intValue;                // Legacy field\nprivate SomeStruct structValue;      // New field\n\n[OnDeserialized]\nprivate void OnDeserialized(StreamingContext context)\n{\n  if (intValue != 0)\n  {\n      // Old format, initialize struct with int value.\n      structValue = new SomeStruct(intValue);\n  }\n}	0
17788511	17788400	How do I translate a query that uses ROW_NUMBER() into linq?	var index=1;\nvar pageIndex=1;\nvar pageSize = 10;\ndata.Select(x => new\n{\n    RowIndex = index++,\n    Sno = x.Sno,\n    Name = x.Name,\n    Age = x.Age\n}).OrderBy(x => x.Name)\n.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();	0
2106932	2106883	How to interrogate method attributes via a delegate?	class Program\n{\n    static void Main(string[] args)\n    {\n        // display the custom attributes on our method\n        Type t = typeof(Program);\n        foreach (object obj in t.GetMethod("Method").GetCustomAttributes(false))\n        {\n            Console.WriteLine(obj.GetType().ToString());\n        }\n\n        // display the custom attributes on our delegate\n        Action d = new Action(Method);\n        foreach (object obj in d.Method.GetCustomAttributes(false))\n        {\n            Console.WriteLine(obj.GetType().ToString());\n        }\n\n    }\n\n    [CustomAttr]\n    public static void Method()\n    {\n    }\n}\n\npublic class CustomAttrAttribute : Attribute\n{\n}	0
22895660	22895562	For loop pattern	for (int i = 0; i < 10; i++)\n        {\n            for (int j = 0; j <=i; j++)\n            {\n                Console.Write("*");\n            }\n            Console.WriteLine();\n        }	0
847373	847047	how to change colour of newly added text in Rich Text box	private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {            \n        this.richTextBox1.SelectionColor = Color.Red;\n    }	0
14963859	14952333	WCF Multiple Base Classes in one interface?	[DataContract]\npublic class Model2\n{\n    private string status;\n    private string name;\n    private string telephone;\n\n    public Model2(){}\n\n    public Model2(string sStatus, string sName, string sTelephone)\n    {\n        Status = sStatus;\n        Name = sName;\n        Telephone = sTelephone;\n    }\n    ...etc	0
18394013	18393603	JSON object deserialize to c# object - OpenTSDB	internal class OpenTSDBResponse\n    {\n        [JsonProperty("metric")]\n        public string Metric { get; set; }\n\n        [JsonProperty("tags")]\n        public Tags Tags { get; set; }\n\n        [JsonProperty("aggregateTags")]\n        public string[] AggregateTags { get; set; }\n\n        [JsonProperty("dps")]\n        public Dictionary<string,double> TimeValues { get; set; }\n    }	0
4963153	4962906	How would I do this in with in nhibernate? Automatically changing fields?	public class User\n{\n   ...\n   private string userName;\n   public virtual string UserName\n   {\n       get{return StringFormatter.ToTitleCase(userName.Trim());}\n       set{userName = StringFormatter.ToTitleCase(value.Trim());}\n   }\n   private string email\n   public virtual string Email\n   {\n       get{return email.Trim().ToLower();}\n       set{email= value.Trim().ToLower();}\n   }\n   ...\n}	0
26302836	26302656	using foreach and multiple insert rows?	connection.Open()\nOleDBCommand command = new OleDbCommand();\ncommand.Connection = connection;\ncommand.CommandText = "SELECT EID From Table";\n\nusing (OleDbDataReader dr = command.ExecuteReader())\n{\n    while (dr.read())\n    {\n        //new connection\n        for(var i = 0;i < 10;i++)\n        {  \n            //insert (int)dr["EID"] into 2nd table\n        }\n\n    }\n}	0
14057083	14057049	Log In user with the membership provider	if(Membership.ValidateUser(model.Username , model.Password))\n    {\n        FormsAuthentication.SetAuthCookie( model.UserName, model.RememberMe );\n        if(string.IsNullOrEmpty(returnUrl))\n            {//...	0
14973834	12237104	How to read file in windows application root directory in C#.net?	string yourpath = Environment.CurrentDirectory + @"\YourImage.jpg";\nFileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);\nImage image = Image.FromStream(stream);\nstream.Close();	0
14464714	14463655	Mute SoundPlayer for just my app	DllImport("winmm.dll")]\nprivate static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);\n\n[DllImport("winmm.dll")]\nprivate static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);\n\n/// <summary>\n/// Returns volume from 0 to 10\n/// </summary>\n/// <returns>Volume from 0 to 10</returns>\npublic static int GetVolume()\n{\n  uint CurrVol = 0;\n  waveOutGetVolume(IntPtr.Zero, out CurrVol);\n  ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);\n  int volume = CalcVol / (ushort.MaxValue / 10);\n  return volume;\n}\n\n/// <summary>\n/// Sets volume from 0 to 10\n/// </summary>\n/// <param name="volume">Volume from 0 to 10</param>\npublic static void SetVolume(int volume)\n{\n  int NewVolume = ((ushort.MaxValue / 10) * volume);\n  uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));\n  waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);\n}	0
21677715	13229374	Fluent Nhibernate, adding collation as part of convention	public class CaseInsensitiveStringConvention : IPropertyConventionAcceptance, IPropertyConvention\n{\n    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)\n    {\n        // More work could be done here to ensure you get nvarchars only\n        criteria.Expect(c => c.Property.PropertyType == typeof(string));\n    }\n\n    public void Apply(IPropertyInstance instance)\n    {\n        instance.CustomSqlType("text COLLATE NOCASE");\n    }\n}	0
26205314	26205041	removing similar string from an array in c#	for(int i = 0; i < strList.Length; i++)\n{   \n  Uri uriToCompare = new Uri(strArray[i]);\n  for(int j = i+1; j < strArray.Length; j++){\n     Uri uri = new Uri(strArray[j]);\n     if( uriToCompare.Host  == uri.Host){\n        strList.RemoveAt(j);\n     }     \n  }\n}	0
5787731	5787640	Order list<T> on a numerical base	ItemsList = ItemsList.OrderByDescending(x => x.Views, new IntComparer()).ToList();	0
4039722	4039708	SQL Server: Try to Delete	DELETE FROM ... WHERE NOT EXISTS (...	0
13042881	13042837	Populating textBox with value depending on button click count	private List<string> messages= new List<string>(){"Fruits", "Vegetables", "Grains", "Poultry"};\nprivate int clickCount = 0;\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n   MyTextBox.Text = messages[clickCount];\n   clickCount++;\n   if (clickCount == messages.Count)\n      clickCount = 0;\n\n}	0
8267649	8267632	Can any one tell what's wrong in my conversion from string to Date time	M/dd//yyyy	0
10819641	10819575	How to list active application windows using C#	public delegate bool WindowEnumCallback(int hwnd, int lparam);\n\n[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool EnumWindows(WindowEnumCallback lpEnumFunc, int lParam);\n\n[DllImport("user32.dll")]\npublic static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);\n\n[DllImport("user32.dll")]\npublic static extern bool IsWindowVisible(int h);\n\nprivate List<string> Windows = new List<string>();\nprivate bool AddWnd(int hwnd, int lparam)\n{\n    if (IsWindowVisible(hwnd))\n    {\n      StringBuilder sb = new StringBuilder(255);\n      GetWindowText(hwnd, sb, sb.Capacity);\n      Windows.Add(sb.ToString());          \n    }\n    return true\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    EnumWindows(new WindowEnumCallback(this.AddWnd), 0);\n}	0
5653143	5653045	How to protect a *.sdf (sqlCE file) with a password	CREATE DATABASE "secure.sdf" \nDATABASEPASSWORD '<enterStrongPasswordHere>'	0
17649237	17649036	Finding next 30 days from today	jsonData.friends.data.Where(BdayItems =>\n{\n    if (BdayItems.birthday != null)\n    {\n        var originalBirthday = DateTime.Parse(BdayItems.birthday);\n        var today = DateTime.Today; //Storing this prevents a race condition.\n        var birthdayThisYear = originalBirthday.AddYears(today.Years - originalBirthday.Years);\n        var thirtyDaysFromNow = today.AddDays(30);\n\n        return birthdayThisYear >= today && birthdayThisYear <= thirtyDaysFromNow;\n    }\n\n    return false;\n});	0
12341299	12336668	How can I send information from a Kinect to an Arduino?	0,180\n0,90\n1,45	0
6029053	6029023	Displaying rows dynamically	dataGridView1.Rows.Add(cnt);\nfor (int i = 0; i < cnt; i++)\n{\n    DataRow row = ds.Tables[0].Rows[i];\n    dataGridView1.Rows[i].Cells[0].Value = row.ItemArray.GetValue(0).ToString();\n    dataGridView1.Rows[i].Cells[1].Value = row.ItemArray.GetValue(1).ToString();\n}	0
3168002	3167971	How can I transform or copy an array to a linked list?	LinkedList<YourObjectType> ListOfObjects=new LinkedList<YourObjectType>(YourObjectArray);	0
10196513	10196481	Trimming a float	"#0.0000"	0
23233142	23233036	verify textbox value from c# in asp.net (if matched value = textbox.text else value = "no match found")	bool matchfound= false;\n    using (SearchResultCollection results = searcher.FindAll())\n    {\n        foreach (SearchResult result in results)\n        {\n            string name = (string)result.Properties["samaccountname"][0];\n            if (name == TextBoxSearch.Text)\n            {\n                TextBoxSearch.Text = name;\n                matchfound =true;\n                break;\n            }\n        }\n    }\n    if(!matchfound)\n        TextBoxSearch.Text = "No match found";	0
32554793	32553220	C# Get CPU cache miss performance counter	var pc = new PerformanceCounter("PCM Core Counters", "L2 Cache Misses", "total_"); // instead of total_ you can use number of core\nvar value = pc.RawValue; // or pc.NextValue() and so on.	0
15191300	15190996	ManyToMany relationship to the same table	[ManyToMany("CATEGORIES_CATEGORIES", \n            LocalKey="ID", ForeignKey="ID",  \n            LocalLinkKey="CATEGORIES_ID", ForeignLinkKey="SUBCATEGORIES_ID")]\npublic abstract CSList<Category> Subcategories { get; }	0
24579915	24577050	Adding data to a RadioButtonList in a random order	ans.Add(new ListItem("option 1", "y"));\nans.Add(new ListItem("option 2", "n"));\nans.Add(new ListItem("option 3", "n"));\nans.Add(new ListItem("option 4", "n"));\nans.Add(new ListItem("option 5", "n"));	0
24701210	24697505	Player stops moving upon contact with a gameObject	void FixedUpdate()\n{\n    horizontalVelocity = Input.GetAxis("Horizontal") * playerMoveSpeed;\n\n    rigidbody.velocity = new Vector3(horizontalVelocity, verticalVelocity, 0.0f);\n}	0
4723610	4723573	How to listen to IIS shutdown event in ASP.NET	void Application_End(object sender, EventArgs e) \n    {\n        //  SHUTDOWN CODE HERE\n    }	0
26965974	26965812	Datagridview values to insert into SQL Server CE database	//Before loop\ncms.Parameters.Add(<parameterNameHere>);\n\n// In the loop\n for (int i = 0; i < dgDataPoint.Rows.Count; i++)\n {\n   com.Parameters["DPName"]= \n       dgDataPoint.Rows[i].Cells["DataPointName"].Value;\n   ...\n}	0
3788377	3786493	Mapping a navigation property to a stored procedure	public Application GetApplicationAndAssistantsByApplicationID(int applicationID)\n{\n   var application =\n      (from a\n      in context.GetApplicationByID(applicationID)\n      select a).FirstOrDefault();\n\n   // call your other stored procedure...\n   var assistants = context.GetAssistantsByApplicationID(applicationID)\n                           .ToArray();\n   // as the assistants are materialized they will automatically show up\n   // in application.Assistants too.\n\n   return application;\n}	0
13352709	13350690	Getting pictures from an ftp server(locally) to display on website	ImageUrl = '<%# \n    String.Format(@"/getimage.aspx?boatid={0}&imageid={1}&extension={2}", \n                  Eval("BoatId"), \n                  Eval("Image.ImageId"), \n                  Eval("Image.Extension")) %>'	0
5496346	5492742	Out and Ref parameters with FakeItEasy	[Test]\npublic void Output_and_reference_parameters_can_be_configured()\n{\n    var fake = A.Fake<IDictionary<string, string>>();\n    string ignored = null;\n\n    A.CallTo(() => fake.TryGetValue("test", out ignored))\n        .Returns(true)\n        .AssignsOutAndRefParameters("foo");\n\n    // This would of course be within you SUT.\n    string outputValue = null;\n    fake.TryGetValue("test", out outputValue);\n\n    Assert.That(outputValue, Is.EqualTo("foo"));\n}	0
9844597	9843335	How to store data or persist it across forms	public class MyFirstView : Form\n{    \n  private ModelClass m_model;\n  public MyFirstView(ModelClass model)\n  {\n     m_model = model;\n     m_model.OnDataRefresh += this.Model_OnDataRefresh;\n  }   \n}\n\npublic class MySecondView : Form\n{    \n  private ModelClass m_model;\n  public MySecondView(ModelClass model)\n  {\n     m_model = model;\n     m_model.OnDataRefresh += this.Model_OnDataRefresh; \n  }   \n}\n\npublic class ModelClass \n{\n   private DataAccessClass m_dataAccess;\n\n   public event EventHandler OnDataRefresh = {}; // fired when data is refreshed\n\n   public void EnsureDataIsLoaded();  // queries the db if we haven't already\n   public void RefreshData(); // refreshes the data from the db\n   public IList<Entity> GetDataList(); // access to data items\n}	0
33288689	33288308	Parse String with Regex c#	public static Dictionary<string, object> FilterAPIData(string data)\n    {\n        var r = new Regex(@"\[\w+\], \'[\w/]+\'");\n\n        var result = r.Matches(data);\n        var dict = new Dictionary<string, object>();\n\n        foreach (Match item in result)\n        {\n            var val = item.Value.Split(',');\n            dict.Add(val[0], val[1]);\n        }\n\n        return dict;\n    }	0
3919336	3919312	How to avoid application crashing when download file using WebClient();	try\n{\n    WebClient.DownloadFile(uri, myPath);\n}\ncatch(WebException webEx)\n{\n     // There was an exception due to network or path problems...\n     // Notify the user? \n}	0
30715503	30715444	Select element by Class Name in a page with multiple elements - Selenium and C#	FindElements(By.ClassName("colSerialNumber"))	0
13327510	13323825	Find position far enough away	public class Planet\n{\n  public Planet Parent;     //if null, I'm the first in chain\n  public float OrbitRadius; //From my parent\n  public float OrbitAngle;  //0-360 around my parent\n  public float Radius;      //Planet size\n\n  //EDIT:\n  public Vector3 Position;\n\n  public void CalculatePosition()\n  {\n    if(Parent == null) this.Position = new Vector(0, 0, 0);\n    this.Position = Parent.Position + OrbitRadius + Math.Sin(OrbitAngle * Math.PI / 180.0f);  //Check if it has to be done for each vector component\n  }\n\n}	0
30330040	30329288	Filter objects in list in a parent list	foreach(var store in Stores)\n{\n  store.Brands=store.Brands.Where(b=>b.Variety==5).ToList();\n}	0
9992191	9992120	troubles creating regex expression	(\w+)\((\d+)\)=(\S+)	0
4406359	4406353	How to call .cs file from a .aspx.cs in asp.net c#	public class YourClass\n{\n    public void YourMethod (DropDownList dowpdownlist)\n    {\n        //do stuff here with dowpdownlist\n    }\n}	0
10536998	10536537	Cannot get data from my gridview	GridFactures.Rows[i].Cells[6].Controls[0].Text.ToString()	0
6528262	6528256	How to do an outer join in LINQ?	var query = from person in people\n    join pet in pets on person equals pet.Owner into gj\n    from subpet in gj.DefaultIfEmpty()\n    select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };	0
10870087	10866358	How to encode string for ID3 tags in C#	WebClient client = new WebClient();    \nclient.Encoding = Encoding.UTF8;\nString htmlCode = client.DownloadString(requestURL);	0
5668292	5667852	firing EVENTS only to a specific dynamic object?	Dictionary<string, WcfObjectType>	0
13392371	13391995	Adding Currency to array elements	string[,] Pizza = new string[5, 5]\n{\n    {"Name of Pizza \t",   "Small",        "Medium",       "Large",        "XLarge"},\n    {"Plain \t \t",           "8.80",       "12.80",    "16.80",    "20.80"},\n    {"Hawaian \t",         "10.90",      "15.90",       "20.90",        "25.90"},\n    {"Beefy \t \t",           "10.90",      "16.90",        "21.90",        "26.90"},\n    {"Vegetarian \t",       "10.90",      "14.90",      "19.90",        "24.90"}\n};\n\n//print the array\nConsole.WriteLine("what type of Pizza do you want?");\nfor (int i = 0; i < Pizza.GetLength (0); i++)\n{\n    Console.WriteLine();\n\n    for (int j = 0; j < Pizza.GetLength (1); j++)\n\n        if(j > 0 && i > 0){\n            Console.Write("$" + Pizza[i, j] + '\t');\n        }\n        else{\n            Console.Write(Pizza[i, j] + '\t');\n        }\n}	0
11993055	11992936	Converting a list into XML	public string BuildLists(List<KeyValuePair<string, int>> pairs)\n{\n    int CurrentLevel = 1;\n    StringBuilder s = new StringBuilder();\n\n    s.Append("<ul>");\n\n    foreach (KeyValuePair<string, int> pair in pairs)\n    {\n        if(pair.Value > CurrentLevel)\n        {\n            //Nest more\n            for(int i = 0; i < pair.Value - CurrentLevel; i++)\n            {\n                s.Append("<li><ul>");\n            }\n        }\n        else if(pair.Value < CurrentLevel)\n        {\n            //Close Tags\n            for(int i = 0; i < CurrentLevel - pair.Value; i++)\n            {\n                s.Append("</ul></li>");\n            }\n        }\n\n        s.Append("<li>" + pair.Key + "</li>");\n\n        CurrentLevel = pair.Value\n    }\n\n    //Close everything.\n    for(int i = 0; i < CurrentLevel - 1; i++)\n    {\n        s.Append("</ul></li>");\n    }\n\n    s.Append("</ul>");\n    return s.ToString();\n}	0
1260173	1259949	How do I implement a progress bar in C#?	private void StartBackgroundWork() {\n    if (Application.RenderWithVisualStyles)\n        progressBar.Style = ProgressBarStyle.Marquee;\n    else {\n        progressBar.Style = ProgressBarStyle.Continuous;\n        progressBar.Maximum = 100;\n        progressBar.Value = 0;\n        timer.Enabled = true;\n    }\n    backgroundWorker.RunWorkerAsync();\n}\n\nprivate void timer_Tick(object sender, EventArgs e) {\n    if (progressBar.Value < progressBar.Maximum)\n        progressBar.Increment(5);\n    else\n        progressBar.Value = progressBar.Minimum;\n}	0
26716841	24366201	Faster Regex expression for extracting Stored procedure name	^\s*[^(--)]{0}(CREATE +PROCEDURE|ALTER +PROCEDURE)\s+(?<ParentProcName>(\w|_|\[|\]|\.)*)	0
22055796	22055695	Saving and screenshot [image] to a database	string cmdText = @"UPDATE users SET profile_image_dir = @file\n                   WHERE username = @uname";\n\nusing(MySqlConnection cn = new MySqlConnection(.....))\nusing(MySqlCommand cmd = new MySqlCommand(cmdText, cn))\n{\n   cn.Open();\n   cmd.Parameters.AddWithValue("@file", open.FileName);\n   cmd.Parameters.AddWithValue("@uname", User.Details.Username);\n   cmd.ExecuteNonQuery();\n}	0
970650	970453	Draw text at center	Size textSize = TextRenderer.MeasureText(Text, Font);\nfloat presentFontSize = Font.Size;\nFont newFont = new Font(Font.FontFamily, presentFontSize, Font.Style);\nwhile ((textSize.Width>textBoundary.Width || textSize.Height > textBoundary.Height) && presentFontSize-0.2F>0)\n{\n   presentFontSize -= 0.2F;\n   newFont = new Font(Font.FontFamily,presentFontSize,Font.Style);\n   textSize = TextRenderer.MeasureText(ButtonText, newFont);\n}\nstringFormat sf;\nsf.Alignment = StringAlignment.Center;\nsf.LineAlignment = StringAlignment.Center;\ne.Graphics.DrawString(Text,newFont,Brushes.Black,textBoundary, sf);	0
10468751	10468675	Auto update C# listbox	MethodInvoker objMethodInvoker = delegate\n        {\n             //access and assign data to list control here               \n        };\n        if (InvokeRequired)\n            BeginInvoke(objMethodInvoker);\n        else\n            objMethodInvoker.Invoke();	0
11062296	11062195	Finding records between a given date range in sql with a varchar column	QueryDate = string.Format("(convert(datetime, Order.Begin, 105) >= @startdate and convert(datetime, Order.End, 105)<= @enddate;"	0
6282370	6282298	Detecting idle users in Winforms	GetLastInputInfo()	0
6190011	6189858	Saving XML File with c# and keep the format of empty element	myXmlDocument.Save(@"C:\t2.xml", SaveOptions.DisableFormatting);	0
951255	947265	Marshalling a Linked List	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\nprivate struct LocaleInfo { \n   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = BUFFER_SIZE)]\n   public string countryName; \n   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = BUFFER_SIZE)]\n   public string localeName; \n   public IntPtr next; \n};	0
4409543	4086154	can i set a role description when adding a new role	public static class RolesEx\n{\n  public static void CreateRole(string roleName, string description)  \n  {  \n    Roles.CreateRole(roleName);\n\n    var c = new SqlConnection("connString");  \n    var cmd = c.CreateCommand();\n    cmd.CommandText =\n      string.Format(\n        "UPDATE aspnet_Roles SET Description = '{0}' WHERE ApplicationId = (SELECT ApplicationId FROM aspnet_Applications WHERE LoweredApplicationName = '{1}') AND  LoweredRoleName = '{2}'",\n        description, Roles.ApplicationName.ToLower(), roleName.ToLower());\n    cmd.CommandType = CommandType.Text;\n    c.Open();\n    var i = cmd.ExecuteNonQuery();\n    c.Close();\n  }\n}	0
17024292	17024267	Retrieving data from Dictionary C#	var value = op.startCollection()["Henvendelser"];	0
818095	818092	Key down event affected by buttons	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    if (keyData.Equals(Keys.Right))\n    {\n        MessageBox.Show("Right Key Pressed!");\n    }\n\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
11539739	11539631	How to convert utf8 string to utf8 byte array?	string value = "\u00C4 \uD802\u0033 \u00AE";    \nbyte[] bytes= System.Text.Encoding.UTF8.GetBytes(value);	0
29530869	29479007	Creating LINQ from SQL	DataTable tblMaster = new DataTable();\nDataColumn dc = new DataColumn("pday", Type.GetType("System.String"));\ntblMaster.Columns.Add(dc);\ntblMaster.Rows.Add(new Object[]{"Nov 28 2011 12:00AM"});\ntblMaster.Rows.Add(new Object[]{"Apr 27 2013 11:10PM"});\ntblMaster.Rows.Add(new Object[]{"Jul 18 2011 12:00AM"});\ntblMaster.Rows.Add(new Object[]{"Mar 19 2012 10:01PM"});\n\nDateTime PDay = new DateTime(2011,11,28);\n\n//foreach(var row in tblMaster.AsEnumerable())\n//{\n//  Console.WriteLine("{0}", Convert.ToDateTime(row[0]));\n//}\n\nvar qry = tblMaster.AsEnumerable()\n         .Where(p=>Convert.ToDateTime(p.Field<string>("pday"))==PDay);\n//qry.Dump();	0
1976349	1965443	Windows Forms: How to display multiple values in a column	dataGridView1.Columns.Add("Column1", "Column1");\ndataGridView1.Columns.Add("Column2", "Column2");            \ndataGridView1.Columns.Add("Column3", "Column3");\n\n//this is the key line...to allow \n in column\ndataGridView1.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;\n\ndataGridView1.Rows.Add(new object[] { 1, "v1  v2", "vl1\nvl2\nvl3" });\ndataGridView1.Rows.Add(new object[] { 2, "v3  v4", "vl4\nvl5\nvl6" });	0
3969561	3969535	How can I store the actual control in a list?	var controls = new List<Control>();\n\nforeach(var control in Page.Controls)\n{\n    controls.Add(control);\n}	0
3703456	3703386	IQueryable Extension: create lambda expression for querying a column for a keyword	public static IQueryable<T> Where<T>(\n    this IQueryable<T> source, string columnName, string keyword)\n{\n    var arg = Expression.Parameter(typeof(T), "p");\n\n    var body = Expression.Call(\n        Expression.Property(arg, columnName),\n        "Contains",\n        null,\n        Expression.Constant(keyword));\n\n    var predicate = Expression.Lambda<Func<T, bool>>(body, arg);\n\n    return source.Where(predicate);\n}	0
31657776	31655816	C# Outlook Acces CommandBar Programmatically	set sExplorer = CreateObject("Redemption.SafeExplorer")\n sExplorer.Item = Application.ActiveExplorer\n set Ribbon = sExplorer.Ribbon\n oldActiveTab = Ribbon.ActiveTab\n Ribbon.ActiveTab = "Home"\n set Control = Ribbon.Controls("OneNote")\n Control.Execute\n Ribbon.ActiveTab = oldActiveTab 'restore the active tab	0
31092623	31092299	linq ExecuteQuery array parameter	var data = context.ExecuteQuery<Some>( "SELECT * FROM Table WHERE field IN ({0})", string.Join(",",arrayParam.Select(n=>n.ToString())));	0
1215529	1215479	Deserializing variable Type JSON array using DataContractJsonSerializer	JArray a = JArray.Parse(jsonStr);	0
15090677	15090246	Invalid object name 'dbo.Infoes' when retrieving data from DB using EF	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();\n        base.OnModelCreating(modelBuilder);\n    }	0
31383361	31383183	I need to invoke a method in WCF before my operation contracts gets called	IDispatchMessageInspector.AfterReceiveRequest	0
16456851	16456741	How to select objects with highest value of Property A, grouped by Property B?	var result = list.GroupBy(x=>x.Grouper)\n                .Select(x=>x.OrderBy(y=>y.Sorter).First())\n                .ToList();	0
14717797	14717711	Label that turns into textbox when clicked?	input {\n    border: none;\n    padding: 2px;\n}\ninput:focus {\n    border: 1px solid black;\n}	0
13724056	13723960	Access gridview as property from usercontrol	public GridView MyGrid\n{\n    get{ return this.GridView1;}\n}	0
4382681	3456901	How to rebuild .net CF application and deploy in windows mobile emulator using command-line	devenv /deploy Release "MySolutionName.sln"	0
454918	438335	How to do Hit testing in GDI+ for rotated shapes with real shape measurements (inches)?	public static bool HitTest(Rectangle bounds, float angle, Point location)\n        {\n            if (angle == 0) return bounds.Contains(location);\n\n            using (Matrix matrix = new Matrix())\n            {\n                matrix.RotateAt(angle, Center(bounds));\n                using (GraphicsPath path = new GraphicsPath())\n                {\n                    path.AddRectangle(bounds);\n                    path.Transform(matrix);\n                    return path.IsVisible(location.X, location.Y);\n                }\n            }\n        }	0
7357039	7357027	How to restrict a textbox without entering any single quotes?	private void PAddress_Text_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if(e.KeyChar=='\'')\n        {\n            e.Handled=true;\n        }\n    }	0
20567896	20567859	List AddRange from a specific index?	list2.Add(100);\nlist2.AddRange(list1.Skip(1));	0
3826085	3822459	How to save date of last application run-time?	// Access setting    \nProperties.Settings.Default.RunTime= DateTime.Today;\n// Save all settings\nProperties.Settings.Default.Save();	0
15167778	15167642	C# SQL Multiple IN Selectors	// endpoints = comma-delimited list of endpoints\n// conferenceCalls = comma-delimited list of conference calls\n\nstring SQLQuery = "select * from Calls " + \n                  "where CallerID = @UserName and " + \n                  "EndpointType in ({0}) and " + \n                  "ConferenceCall in ({1}) " + \n                  "order by JoinTime desc";\n\ncmd = new MySqlCommand((string.Format(SQL, endpoints, conferenceCalls)),connection);	0
24527136	24527090	Read just a part of a big string	string aLine;\n            StringReader strRead = new StringReader(str);\n            aLine = strRead.ReadLine();\n\n            if (aLine.Contains("MESSAGE"))\n            {\n\n              //Write the whole file on disc\n\n            }	0
20066122	20065645	ASP.NET - Controls submit wrong information	public void Page_Load(object sender, EventArgs e) \n{\n  if (!IsPostBack)\n  {\n    var myObj = GetdataFromDb();\n    TextBox1.Text = myObj.Subject;\n    TextBox2.Text = myObj.Desctiption;\n  }\n}	0
18605390	18604986	Data not displaying out despite auto-selecting gridview row	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!IsPostBack)\n            {\n\n                gvnric.SelectedIndex = 0;\n                gvnric_SelectedIndexChanged(this, EventArgs.Empty);\n            }\n        }	0
26947843	26940692	How can I clear all the pushpins from my Bing Map and still be able to add more after that?	var mapLayerChildren = from c in DataLayer.Children select c;\nvar kinderGarten = mapLayerChildren.ToArray();\nfor (int i = 0; i < kinderGarten.Count(); i++)\n{\n    if (kinderGarten[i] is Pushpin)\n    {\n        DataLayer.Children.Remove(kinderGarten[i]);\n    }\n}	0
19461542	19461519	Splitting String Array, then using each element seperately	deviceSel = st.Split(splitChar);\nstring toDisplay = "";\nforeach (string device in deviceSel)\n{\n    toDisplay += device + Environment.NewLine;\n\n}\nMessageBox.Show(toDisplay);	0
12179166	12178857	store azure table diagonistics data into sql server database	PerfDataEntities pde = new PerfDataEntities(RoleEnvironment.GetConfigurationSettingValue("PerfDataEntities"));	0
25363561	25363400	Login administrator c# from local database bug	if((username == admin.UserName) && (password == admin.Password))	0
2554881	2553663	How to determine if birthday or anniversary occured during date range	public static bool IsBirthDayInRange(DateTime birthday, DateTime start, DateTime end)\n{\n    DateTime temp = birthday.AddYears(start.Year - birthday.Year);\n\n    if (temp < start)\n        temp = temp.AddYears(1);\n\n    return birthday <= end && temp >= start && temp <= end;\n}	0
5788903	5788883	How can I convert a DateTime to an int?	dateDate.Ticks	0
21988433	21988006	Use foreach loop to find duplicate in Observable Collection	bool anyDuplicates = studentList.Select(i => i.Name).Distinct().Count() \n                     < studentList.Count();	0
21866796	21865909	log message to text box from other class	public partial class MainForm : Form\n{\n    engine connEngine = new engine();\n\n    public MainForm()\n    {\n        InitializeComponent();\n\n        connEngine.log = s => { msgLog(s); };\n    }\n\n    private void Start_Click(object sender, EventArgs e)\n    {\n        msgLog("Connection Start Clicked");\n\n        if (connEngine.StartConnection(txtIPAddress.Text, 8002) == false)\n        {\n            msgLog("Connection Start Failed"); \n        }\n        else\n        {\n            msgLog("Connection Start Success");\n        }\n\n    }\n\n    void msgLog(string message)\n    {\n        txtMessageLog.AppendText(message + Environment.NewLine);\n    }\n\n\n    private void MainForm_Load(object sender, EventArgs e)\n    {\n        msgLog("Form Load Success");\n    }\n\n}\n\nclass engine\n{\n    internal Action<string> log;\n\n    public bool StartConnection(string txtIPAddress, int p)\n    {\n        log("StartConnection started");\n        //do something\n        return true;\n    }\n}	0
19573323	19573214	Inconsistent accessibility - Developing a Web Service	public class Employee	0
27483702	27483266	how to change metro theme using caliburn.micro	MahApps.Metro.ThemeManager.ChangeAppTheme(App.Current, "BaseDark"); // Or "BaseLight"	0
19151739	19151651	Trimming empty lines resulting from splitting a string	RichTextBox1.AppendText(Environment.NewLine + line.Trim().Replace("));",");") + ");" + Environment.NewLine);	0
25928426	22246127	How do I read the summary out of an XML file	private static void ReadTheSummarys()\n    {\n      XmlReader xmlReader = XmlReader.Create("Test.xml");\n      bool isSummary = false;\n      while (xmlReader.Read())\n    {\n    //checks if the current node is a summaray\n    if (xmlReader.Name == "summary")\n    {\n      isSummary = true;\n      continue;\n    }\n\n    if (isSummary)\n    {\n      //Replace and trim for pure Comments without spaces and linefeeds\n      string summary = xmlReader.Value.Trim().Replace("\n", string.Empty);\n      if (summary != string.Empty)\n      {\n        //Writes the pure comment for checking\n        Console.WriteLine(summary);           \n      }\n    isSummary = false;\n    }\n\n    }\n\n    }	0
11793619	11793438	Is it possible to redirect from one page in Project A to a page in Project B from within the same solution	ProjectA.PageNamespace page = new ProjectA.PageNamespace()	0
19565026	19558801	Converting Console app to Windows Service	using System.ServiceProcess;\nusing System.Threading;\n\nnamespace myService\n{\n    class Service : ServiceBase\n    {\n        static void Main()\n        {\n            ServiceBase.Run(new Service());\n        }\n\n        public Service()\n        {\n            Thread thread = new Thread(Actions);\n            thread.Start();\n        }\n\n        public void Actions()\n        {\n            // Do Work\n        }\n    }\n}	0
19837740	19837672	Convert To Double	double value = double.Parse(stringValue, CultureInfo.InvariantCulture);	0
13733583	13714499	How To Capture Data with FiddlerCore?	URLMonInterop.SetProxyInProcess("127.0.0.1:8888", "<-loopback>");	0
1438969	1438265	How do get reference to a related parent object when selecting a list of child objects using entity framework	var q = from u in Context.Users\n        where u.UserId == userId\n        from ts in u.TimeSheets\n        select new \n        {\n            ProjectName = ts.Project.Name,\n            Date = ts.Date,\n            TimeSpent = ts.TimeSpent\n        };	0
23807506	23807269	How to reverse a number and compare it with its original value	public int SolveProblem004()\n    {\n        int result = 0;\n        for (int a = 999; a >= 100; --a) {\n            for (int b = 999; b >= a; --b) {\n                int product = a * b;\n                if (product <= result) break;\n                if (IsPalindromic(product)) { result = product; break; }\n            }\n        }\n        return result;\n    }\n\n    public static bool IsPalindromic(int i)\n    {\n        return i == Reverse(i);\n    }\n\n    public static int Reverse(int number)\n    {\n        if (number < 0) return -Reverse(-number);\n        if (number < 10) return number;\n        int reverse = 0;\n        while (number > 0) {\n            reverse = reverse * 10 + number % 10;\n            number /= 10;\n        }\n        return reverse;\n    }	0
14359381	14359219	how to get indication of "success" from removeall	return !Passengers.Any(x => x.PassengerName == name);\n--- OR ---\nreturn (Passengers.Count(x => x.PassengerName == name) == 0);	0
10714763	10713310	Is there an equivalent in C++ to LINQ with respect to DataTables?	struct Man\n{\n    std::string name;\n    int age;\n};\n\nMan src[] =\n{\n    {"Kevin",14},\n    {"Anton",18},\n    {"Agata",17},\n    {"Terra",20},\n    {"Layer",15},\n};\n\nauto dst = from(src).where(  [](const Man & man){return man.age < 18;})\n                .orderBy([](const Man & man){return man.age;})\n                .select( [](const Man & man){return man.name;})\n                .toVector();	0
14448571	14448552	Can this be done with less code using lambda?	people.Where(p => p.Kids.Any(k => k.age < 5))	0
12431224	12431200	Cant delete row properly due to quotation marks	using (var conn = ...)\nusing (var command = new SqlCommand("delete from faculty where schoolName = @School", con)) {\n   command.Parameters.AddWithValue("@School", schoolName);	0
29187909	29187817	Saving edits to database made in datagridview	public static DataSet SelectSqlRows(string connectionString,\n    string queryString, string tableName)\n{\n    using (SqlConnection connection = new SqlConnection(connectionString))\n    {\n        SqlDataAdapter adapter = new SqlDataAdapter();\n        adapter.SelectCommand = new SqlCommand(queryString, connection);\n        SqlCommandBuilder builder = new SqlCommandBuilder(adapter);\n\n        connection.Open();\n\n        DataSet dataSet = new DataSet();\n        adapter.Fill(dataSet, tableName);\n\n        //code to modify data in DataSet here\n\n        builder.GetUpdateCommand();\n\n        //Without the SqlCommandBuilder this line would fail\n        adapter.Update(dataSet, tableName);\n\n        return dataSet;\n    }\n}	0
8262199	8262116	Return Func from Func	public static Expression<Func<TResult, bool>> GetPredicate<TKey>\n    (Expression<Func<TResult, TKey>> selector, TResult input, object value)\n{\n    // Note: Move "early out" here so that bulk of method is less deeply nested.\n    // Really? Why make this generic in TKey then?\n    if (typeof(TKey) != typeof(string))\n    {\n        throw new Exception("Type not supported");\n    }\n\n    var parameter = Expression.Parameter("input");\n    var invocation = Expression.Invoke(selector, input);\n    var constant = Expression.Constant(value);\n    var equality = Expression.Equal(invocation, constant);\n    return Expression.Lambda<Func<TResult, bool>>(equality, parameter);\n}	0
23404688	23404500	How Can I split A String from the end to some character I want	var path = @"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg";\n\nSystem.IO.FileInfo myImageFile = new System.IO.FileInfo(path);\n\nConsole.WriteLine(myImageFile.Name); // gives 1620855_759701257391419_1132489417_n.jpg	0
7011497	7011429	How to auto start a winform application programmatically in c#?	hkcu\Software\Microsoft\Windows\CurrentVersion\Run	0
2795901	2795835	Reading data file into an array C#	int[,] iMap = new int[iMapHeight, iMapWidth];\nusing (var reader = new StreamReader(fileName))\n{\n    for (int i = 0; i < iMapHeight; i++)\n    {\n        string line = reader.ReadLine();\n        for(int j = 0; j < iMapWidth; j++)\n        {\n            iMap[i, j] = (int)(line[j] - '0');\n        }\n    }\n}	0
26269640	26269318	How can I extract proxy ip address using C# regex	WebProxy[] ProxyArray = Regex.Matches(input, @"(?<ip>\d*\.\d*\.\d*\.\d*).*?>\s*(?<port>\d+)\s*<")\n               .Cast<Match>().Select(m => new WebProxy(m.Groups["ip"].Value + ":" + m.Groups["port"].Value)).ToArray();	0
17625261	13254153	Bug in the string comparing of the .NET Framework	public static void SO_13254153_Question()\n{\n    string x = "\u002D\u30A2";  // or just "-???" if charset allows\n    string y = "\u3042";        // or just "???" if charset allows        \n\n    var invariantComparer = new WorkAroundStringComparer();\n    var japaneseComparer = new WorkAroundStringComparer(new System.Globalization.CultureInfo("ja-JP", false));\n    Console.WriteLine(x.CompareTo(y));  // positive one\n    Console.WriteLine(y.CompareTo(x));  // positive one\n    Console.WriteLine(invariantComparer.Compare(x, y));  // negative one\n    Console.WriteLine(invariantComparer.Compare(y, x));  // positive one\n    Console.WriteLine(japaneseComparer.Compare(x, y));  // negative one\n    Console.WriteLine(japaneseComparer.Compare(y, x));  // positive one\n}	0
21813850	21813236	implement a comparer function that works to different classes	Age As String	0
24165028	24164946	Split string to specific array position c#	string data = @"this/\is/\a/\test/\string";\nstring[] result = (@"/\" + data).Split(new[] {@"/\"}, StringSplitOptions.None);\nresult[0] = null;	0
11246993	11246026	How come the Oracle query cannot find table, when it can reach other tables of same ownership?	GRANT ALL ON CHOWNER.BENTLEY TO ADMINROLE;	0
12942329	12941864	Pass complex json via hidden variable and read in mvc 3 controller	public static void Test()\n{\n    string JSON = @"[\n        {'name':'Scooby Doo', 'age':10},\n        {'name':'Shaggy', 'age':18},\n        {'name':'Daphne', 'age':19},\n        {'name':'Fred', 'age':19},\n        {'name':'Velma', 'age':20}\n    ]".Replace('\'', '\"');\n\n    Console.WriteLine("Using JavaScriptSerializer");\n    JavaScriptSerializer jss = new JavaScriptSerializer();\n    object[] o = jss.DeserializeObject(JSON) as object[];\n    foreach (Dictionary<string, object> person in o)\n    {\n        Console.WriteLine("{0} - {1}", person["name"], person["age"]);\n    }\n\n    Console.WriteLine();\n    Console.WriteLine("Using JSON.NET (Newtonsoft.Json) parser");\n    JArray ja = JArray.Parse(JSON);\n    foreach (var person in ja)\n    {\n        Console.WriteLine("{0} - {1}", person["name"].ToObject<string>(), person["age"].ToObject<int>());\n    }\n}	0
9884439	9822475	Datagrid inside another datagrid	private void Expander_Expanded(object sender, RoutedEventArgs e)\n    {\n    int rowIndex = this.DataGridForEvents.SelectedIndex;\n    List<DataGridRow> rows = GetRows();\n    rows[rowIndex].DetailsVisibility = Visibility.Visible;\n    }\n\nprivate void Expander_Collapsed(object sender, RoutedEventArgs e)\n{\nint rowIndex = this.DataGridForEvents.SelectedIndex;\nList<DataGridRow> rows = GetRows();\nrows[rowIndex].DetailsVisibility = Visibility.Collapsed;\n}\n\n\n\npublic List<DataGridRow>  GetRows()\n{\nList<DataGridRow> rows = new List<DataGridRow>();\nforeach (var rowItem in this.DataGridForEvents.ItemsSource)\n{\nthis.DataGridForEvents.ScrollIntoView(rowItem, this.DataGridForEvents.Columns.Last());\nFrameworkElement el = this.DataGridForEvents.Columns.Last().GetCellContent(rowItem);\nDataGridRow row = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement);\nif (row != null)\nrows.Add(row);\n}\nreturn rows;\n}	0
28404015	28403903	Return Bitmap image from function after decreasing quality	using(var ram = new MemoryStream())\n{\n    bmp1.Save(ram, jgpEncoder, myEncoderParameters);\n    ram.Seek(0, SeekOrigin.Begin); // reset stream to start so it can be read again\n    return new Bitmap(ram);\n}	0
6819946	6819853	c# WebClient Downloading a Zip Corrupts it	e.Response.TransmitFile(filePath);	0
23323830	23323632	C# changing other buttons colour in turn	// Populate dictionary\n        Dictionary<Button, Color> myButtons = new Dictionary<Button, Color>();\n        myButtons.Add(button1, Color.Red);\n        myButtons.Add(button2, Color.Blue);\n        myButtons.Add(button3, Color.Green);\n        myButtons.Add(button4, Color.Purple);\n        myButtons.Add(button5, Color.Pink);\n        myButtons.Add(button6, Color.PaleVioletRed);\n\n        // Get first untouched occurrence\n        var buttonToBeChanged = myButtons.Reverse().FirstOrDefault(x => x.Key.BackColor.IsSystemColor);\n\n        // No buttons left\n        if (buttonToBeChanged.Key == null)\n            MessageBox.Show("No buttons left!");\n        else\n            buttonToBeChanged.Key.BackColor = buttonToBeChanged.Value;	0
3160126	3160106	Set default value in a DataContract?	[DataContract]\npublic class MyClass\n{\n    [DataMember]\n    public string ScanDevice { get; set; }\n\n    public MyClass()\n    {\n        SetDefaults();\n    }\n\n    [OnDeserializing]\n    private void OnDeserializing(StreamingContext context)\n    {\n        SetDefaults();\n    }\n\n    private void SetDefaults()\n    {\n        ScanDevice = "XeroxScan";\n    }\n}	0
24724986	24724862	Change image on button click	private int currentImageIndex = 2; // Initialize this to whichever image number you want\n\nprivate void Button_Click(object sender, RoutedEventArgs e) \n{\n    if(currentImageIndex < 25) // if not at the last image, increment and set new image\n    {\n        currentImageIndex++;\n        Main_Frame.Source = new BitmapImage(new Uri("/Assets/Eye_thing/im" + currentImageIndex + ".jpg", UriKind.Relative));\n    }\n}\n\nprivate void Button_Click_1(object sender, RoutedEventArgs e)\n{\n    if(currentImageIndex > 2) // if not at the first image, decrement and set new image\n    {\n        currentImageIndex--;\n        Main_Frame.Source = new BitmapImage(new Uri("/Assets/Eye_thing/im" + currentImageIndex + ".jpg", UriKind.Relative));\n    }\n}	0
31627976	31622905	How to Get the Index of the First Item Showing in ListView in C#	int getFirstVisibleItem(ListView lv)\n{\n    ListViewHitTestInfo HI;\n    for (int i = 0; i < Math.Min(lv.ClientSize.Width, lv.ClientSize.Height); i += 3)\n    {\n        HI = lv.HitTest(i, i);\n        if (HI.Item != null) return HI.Item.Index;\n    }\n    return -1;\n}	0
21780342	21779597	Trying to log in to a website through a C# program	HtmlDocument doc = webBrowser1.Document;\nHtmlElement email = doc.GetElementById("email");\nHtmlElement pass = doc.GetElementById("pass");\nHtmlElement submit = doc.GetElementById("LoginButton");\n\nemail.SetAttribute("value", "InsertYourEmailHere");\n//Same for password\n\nsubmit.InvokeMember("Click");	0
1379300	1379195	C#: Executing a SQL script stored as a resource	string commandText;\nAssembly thisAssembly = Assembly.GetExecutingAssembly();\nusing (Stream s = thisAssembly.GetManifestResourceStream(\n      "{project default namespace}.{path in project}.{filename}.sql"))\n{\n   using (StreamReader sr = new StreamReader(s))\n   {\n      commandText = sr.ReadToEnd();\n   }\n}	0
30208718	30194355	Access textbox from another class	public partial class Form1 : Form\n  {\n    Log log;\n    public Form1()\n    {\n        InitializeComponent();\n        log = new Log(richTextBox1);\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        log.AddLog(DateTime.Now.ToString());\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        log.AddLog();\n    }\n}\n\npublic class Log\n{\n    RichTextBox rtb;\n    public Log(RichTextBox rtb)\n    {\n        this.rtb = rtb;\n    }\n\n    public void AddLog(string msg)\n    {\n        rtb.Text += msg + Environment.NewLine;\n    }\n\n    public void AddLog()\n    {\n        rtb.Text += DateTime.Now.ToString() + Environment.NewLine;\n    }\n}	0
8168613	8168578	Break inner foreach loop and continue outer foreach loop	foreach(var item in items)\n{\n  bool flag = false;\n  foreach(var otheritem in otheritems)\n  {\n    if (!double.TryParse(otheritem))\n    {\n        flag = true;\n        break;\n    }\n  }\n  if(flag) continue;\n\n  DoStuff();\n}	0
16591771	16591532	Want to create a comment system in asp.net	"Delete from mobiles_pos where username = @UserName and createdDate = @createdDate"	0
24374109	24373866	Average int Array elements with a GroupBy	var newChart = chart.GroupBy(x => x.DateAdded.RoundUp(TimeSpan.FromSeconds(60)))\n.Select(x => new ChartPoint\n{\n    DateAdded = x.Key,\n    X = x.Key.ToString(@"HH:mm:ss"),\n    Y = Enumerable.Range(0, 3).Select(i => (int)Math.Round(x.Average(z => z.Y[i]))).ToArray()\n});	0
20245546	20161854	Getting mapped column names of properties in entity framework	using ( var context = new YourEntities() )\n{\n  var objectContext = ( ( IObjectContextAdapter )context ).ObjectContext;\n  var storageMetadata = ( (EntityConnection)objectContext.Connection ).GetMetadataWorkspace().GetItems( DataSpace.SSpace );\n  var entityProps = ( from s in storageMetadata where s.BuiltInTypeKind == BuiltInTypeKind.EntityType select s as EntityType );\n  var personRightStorageMetadata = ( from m in entityProps where m.Name == "PersonRight" select m ).Single();\n  foreach ( var item in personRightStorageMetadata.Properties )\n  {\n      Console.WriteLine( item.Name );\n  }\n}	0
30892349	30890104	Determine whether assembly is a gui application	private PEFileKinds GetFileType(string inFilename)\n    {\n        using (var fs = new FileStream(inFilename, FileMode.Open, FileAccess.Read))\n        {\n            var buffer = new byte[4];\n            fs.Seek(0x3C, SeekOrigin.Begin);\n            fs.Read(buffer, 0, 4);\n            var peoffset = BitConverter.ToUInt32(buffer, 0);\n            fs.Seek(peoffset + 0x5C, SeekOrigin.Begin);\n            fs.Read(buffer, 0, 1);\n            if (buffer[0] == 3)\n            {\n                return PEFileKinds.ConsoleApplication;\n            }\n            else if (buffer[0] == 2)\n            {\n                return PEFileKinds.WindowApplication;\n            }\n            else\n            {\n                return PEFileKinds.Dll;\n            }\n        }\n    }	0
29963930	29780154	How to draw rectangle over a plot?	var Event = new PolygonAnnotation();\n\nEvent.Layer = AnnotationLayer.BelowAxes;\nEvent.StrokeThickness = 5;\nEvent.Stroke = OxyColor.FromRgb(0, 0, 255);\nEvent.LineStyle = LineStyle.Automatic;\n\nEvent.Points.Add(new DataPoint(X, Y));\nEvent.Points.Add(new DataPoint(X, Y));            \nEvent.Points.Add(new DataPoint(X, Y));\nEvent.Points.Add(new DataPoint(X, Y));	0
6019279	6019155	How to open a new form window within same window in C#?	YourForm.IsMdiContainer = True\n\nNewForm.MdiParent = YourForm;\nNewForm.Show();	0
10032441	10032423	Passing in func via where clause	public IEnumerable<string> FilterNames(Func<string, bool> filter)\n{\n    return people.Select(person => person.Name)\n                 .Where(filter);\n}	0
11993036	11993009	winapi declaration in c#	public static class WinApi {\n    public const int PROCESS_ALL_ACCESS = /* whatever the value is */;\n\n    [DllImport("kernel32.dll")]\n    public static extern IntPtr OpenProcess(int dwDesiredAccess,\n        bool bInheritHandle, int dwProcessId);\n}	0
3062767	3062720	Count items in Dictionary that begin with certain text	int count = dict.Count(D=>D.Key.StartsWith("Test"));	0
32278408	32278024	Find and retrieve keyed value from anywhere in JSON string	var metadataObj = JArray.Parse(postMetadataJsonStr);\nvar dict = metadataObj.ToDictionary(x => (string)x["key"], x => (double)x["value"]);\n\nConsole.WriteLine(dict["geo_latitude"]);	0
17669524	17669326	Detecting when a microphone is unplugged	using System.Runtime.InteropServices;\n    const int WM_DEVICECHANGE = 0x0219;\n     // new device is pluggedin\n     const int DBT_DEVICEARRIVAL = 0x8000; \n     //device is removed \n    const int DBT_DEVICEREMOVECOMPLETE = 0x8004; \n     //device is changed\n    const int DBT_DEVNODES_CHANGED = 0x0007; \n    protected override void WndProc(ref Message m)\n    {\n        if (m.Msg == WM_DEVICECHANGE\n         {\n              //Your code here.\n         }\n       base.WndProc(ref m);\n    }	0
7350770	7350121	Keeping a log file under a certain size	private static void ShrinkFile(string file)\n{\n  using(var sr = new StreamReader(file))\n  {\n    for (int i = 0; i < 9; i++) // throw away the first 10 lines\n    {\n        sr.ReadLine();\n    }\n\n    // false here means to overwrite existing file.\n    using (StreamWriter sw = new StreamWriter(file, false))\n    {\n      sw.Write(sr.ReadToEnd());\n    }\n  }\n}	0
27647325	27643536	image (noninlineshape) from Word to clipboard to file	int number = doc.InlineShapes.Count;\nMessageBox.Show(number.ToString()); // 0 to begin with\n\nforeach (Microsoft.Office.Interop.Word.Shape s in doc.Shapes) {\n    MessageBox.Show(s.Type.ToString());\n    if (s.Type.ToString() == "msoTextBox") {\n        MessageBox.Show(s.TextFrame.TextRange.Text);\n    } else if (s.Type.ToString() == "msoPicture") {\n        s.ConvertToInlineShape();\n    }\n}\n\nnumber = doc.InlineShapes.Count;\nMessageBox.Show(number.ToString());  // Now it's 1 as it should be\n\nInlineShape ils = doc.InlineShapes[1];\nils.Select();\napplication.Selection.Copy();\n\nIDataObject data = Clipboard.GetDataObject();\nif (data.GetDataPresent(DataFormats.Bitmap)) {\n    Image image = (Image)data.GetData(DataFormats.Bitmap, true);\n    image.Save("c:\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);\n}	0
1912919	1912894	Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#	theDate.ToString("yyyy-MM-dd HH':'mm':'ss")	0
4731975	4731891	Drag on Drop onto a composite User Control with multiple text boxes	public CompositeControl() {\n        InitializeComponent();\n\n        PreviewDragEnter += new DragEventHandler(CompositeControl_DragEnter);\n        PreviewDragOver += new DragEventHandler(CompositeControl_DragEnter);\n\n        textBox1.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);\n        textBox1.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);\n        textBox1.PreviewDrop += new DragEventHandler(CompositeControl_Drop);\n\n        textBox2.PreviewDragEnter += new DragEventHandler(textBox_PreviewDragEnter);\n        textBox2.PreviewDragOver += new DragEventHandler(textBox_PreviewDragEnter);\n        textBox2.PreviewDrop += new DragEventHandler(CompositeControl_Drop);\n\n        Drop += new DragEventHandler(CompositeControl_Drop);\n    }\n\n    void textBox_PreviewDragEnter(object sender, DragEventArgs e) {\n        e.Handled = true;\n    }	0
3974178	3974004	FileSystemWatcher - minimum permissions needed on target directories?	directoryHandle = NativeMethods.CreateFile(\n    directory,                                 // Directory name\n    UnsafeNativeMethods.FILE_LIST_DIRECTORY,   // access (read-write) mode\n    UnsafeNativeMethods.FILE_SHARE_READ |\n    UnsafeNativeMethods.FILE_SHARE_DELETE |\n    UnsafeNativeMethods.FILE_SHARE_WRITE,      // share mode\n    null,                                      // security descriptor\n    UnsafeNativeMethods.OPEN_EXISTING,         // how to create\n    UnsafeNativeMethods.FILE_FLAG_BACKUP_SEMANTICS |\n    UnsafeNativeMethods.FILE_FLAG_OVERLAPPED,  // file attributes\n    new SafeFileHandle(IntPtr.Zero, false));   // file with attributes to copy	0
17395113	17304386	How does one make function calls or trigger events from a Native component into a C#/XAML component?	//.h\n[Windows::Foundation::Metadata::WebHostHidden]\npublic interface class ICallback\n{\npublic:\n    virtual void Exec( Platform::String ^Command, Platform::String ^Param);\n};\n//.cpp\nICallback ^CSCallback = nullptr;\nvoid Direct3DInterop::SetCallback( ICallback ^Callback)\n{\n    CSCallback = Callback;\n}\n//...\n\nif (CSCallback != nullptr)\n    CSCallback->Exec( "Command", "Param" );\n\nC#\npublic class CallbackImpl : ICallback\n{\n    public void Exec(String Command, String Param)\n    {\n        //Execute some C# code, if you call UI stuff you will need to call this too\n        //Deployment.Current.Dispatcher.BeginInvoke(() => { \n        // //Lambda code\n        //}\n    }\n}\n//...\nCallbackImpl CI = new CallbackImpl();\nD3DComponent.SetCallback( CI);	0
1631133	1631054	Using SqlDataAdapter to insert a row	var sqlQuery = "select * from Customers where 0 = 1";\ndataAdapter = new SqlDataAdapter(sqlQuery, conn);\ndataSet = new DataSet();\ndataAdapter.Fill(dataSet);\n\nvar newRow = dataSet.Tables["Customers"].NewRow();\nnewRow["CustomerID"] = 55;\ndataSet.Tables["Customers"].Add(newRow);\n\nnew SqlCommandBuilder(dataAdapter);\ndataAdapter.Update(dataSet);	0
22470756	22468474	Issue with currency formating	private static string calculateTakeHome(string p, double income)\n    {\n        double numOne = double.Parse(p,System.Globalization.NumberStyles.Currency);\n        double outcome = income - numOne;\n        return outcome.ToString("C2");\n\n    }	0
8704405	8704383	Going through a list and adding its individual values to a statement	foreach(var i in mylist)\n{\n    ramChart.Series["RAM"].Points.AddY(i);\n}	0
21394673	21394660	How to make Process.Start a blocking call?	Process sampleProcess= new Process();\nsampleProcess.StartInfo = sampleProcessInfoObject;\nsampleProcess.Start();\nsampleProcess.WaitForExit(); // Will wait indefinitely until the process exits	0
29564640	29562745	Order a list with unique rows with a given row as first item, then reorder the list but without the first row	return Enumerable.Select(GetTable()\n            .OrderByDescending(o => o.Name == country)\n            .ThenBy(o => o.Name), b =>\n                new ComboBoxBase.ComboBoxListStructGuid { Id = b.CountryID, Description = b.Country }).ToList();	0
14229933	14229185	Mapping a column to a table which has no foreign key constraint between them using fluent Nhibernate	public class TariffConfigMap : EntityBaseMap<TariffConfig>\n{\n\n    public TariffConfigMap() : base()\n    {\n       this.Initialize("TariffConfig");\n       References(prop => prop.Determinator)\n            .ColumnName("TariffDeterminatorCd");           \n    }\n\n}	0
4509428	4509415	Check whether a folder exists in a path in c#?	if (Directory.Exists(Path.Combine(txtBoxInput.Text, "RM"))\n{\n    // Do Stuff\n}	0
19897443	19897332	asp.net: how to access contents of a textbox inside the cell of a table that was created from the code behind	protected void sumbitChange_Click(object sender, EventArgs e)\n{\n    TextBox student1 = StatusRow.FindControl("student1") as TextBox;\n    Confirm.InnerText = "The students status was changed to " + student1.Text;\n\n}	0
8039524	8039478	Call aspnet webservice like a method	[WebMethod(EnableSession = true)]\npublic static string ReadSearch(string nm_what, string nm_where, int pageindex)\n{\n}\n\n//from another page\nprotected void Page_Load(object sender, EventArgs e)\n{ \n    //example\n    string s = Search.ReadSearch("this","here",2); //add namespace and references needed\n}	0
33411848	33410582	notepad on top of a winform	using System.Runtime.InteropServices;\n...\n\n// Even if it is "user32.dll" it will do on IA64 as well\n[DllImport("user32.dll", SetLastError = true)]\nstatic extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, \n                                int X, int Y, int cx, int cy, int uFlags);\n\n ...\n\n// Since Process is IDisposable, put it into "using"\nusing (Process process = new Process()) {\n  process.StartInfo.FileName = "notepad.exe";\n  process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;\n  process.Start();\n\n  // wait for main window be created\n  process.WaitForInputIdle();\n\n  // Insert (change Z-order) as the topmost - (IntPtr) (-1); \n  // NoMove, NoSize - 0x0002 | 0x0001\n  SetWindowPos(process.MainWindowHandle, (IntPtr) (-1), 0, 0, 0, 0, 0x0002 | 0x0001);\n}	0
30127780	30127651	Regex to remove this string in C#?	(?:\n|\t|\r|.){1,3}.*\@sc.*'	0
3580679	3580635	Can you open a JPEG, add text, and resave as a JPEG in .NET?	var filePath = @"D:\Pictures\Backgrounds\abc.jpg";\nBitmap bitmap = null;\n\n// Create from a stream so we don't keep a lock on the file.\nusing (var stream = File.OpenRead(filePath))\n{\n    bitmap = (Bitmap)Bitmap.FromStream(stream);\n}\n\nusing (bitmap)\nusing (var graphics = Graphics.FromImage(bitmap))\nusing (var font = new Font("Arial", 20, FontStyle.Regular))\n{\n    // Do what you want using the Graphics object here.\n    graphics.DrawString("Hello World!", font, Brushes.Red, 0, 0);\n\n    // Important part!\n    bitmap.Save(filePath);\n}	0
16924906	16924791	How to write a dynamic Lambda Expression to access Nth Parent entity?	protected void Process(int count, int id)\n{\n    var query = session.Query<A>().Where(BuildFilter(count,id));\n    var result = query.ToList();\n}\n\nprivate static Expression<Func<A, bool>> BuildFilter(int count, int id)\n{\n   var x = Expression.Parameter(typeof(A), "x");\n\n   Expression instance = x;\n   if (count != 0)\n   {\n      var prop = typeof(A).GetProperty("ParentA");\n      while (count > 0)\n      {\n         instance = Expression.Property(instance, prop);\n         count--;\n      }\n   }\n\n   var instanceId = Expression.Property(instance, "Id");\n   var compareId = Expression.Constant(id);\n   var body = Expression.Equal(instanceId, compareId);\n\n   return Expression.Lambda<Func<A, bool>>(body, x);\n}	0
12890285	12890204	Logging from a console application	string strLogText = "Some details you want to log.";\n\n// Create a writer and open the file:\nStreamWriter log;\n\nif (!File.Exists("logfile.txt"))\n{\n  log = new StreamWriter("logfile.txt");\n}\nelse\n{\n  log = File.AppendText("logfile.txt");\n} \n\n// Write to the file:\nlog.WriteLine(DateTime.Now);\nlog.WriteLine(strLogText);\nlog.WriteLine(); \n\n// Close the stream:\nlog.Close();	0
12836056	12834675	LOAD DATA INFILE with variables	Allow User Variables=true;	0
5020578	5020197	Sorting nested Lists within object using c# Lambda Expressions	var orderedTestCollection = testCollection.Orderby(tc=>tc.quickTest.SortField) // orders all the testCollection objects\n\n\n    //orders and only takes 2 elements of the lists inside the each test collection object\n    foreach(var tc in testCollection)\n    {\n       tc.quickTest.NestedQuickTest = tc.quickTest.NestedQuickTest.Orderby(nqt=>nqt.SortField).Take(2);\n    }	0
8936557	8936529	How to avoid writing every variation of a simple "if contains" statement for different strings	string[] parts = new [] {"PART#1", "PART#2", "PART#3"};\nint count = parts.Count(s => textBox2.Text.Contains(s));\nif (count >= 2) ...	0
4695036	4693537	Adding a ToolTip to an OvalShape in C#	bool hoverSeen = false;\n\n    private void ovalShape1_MouseHover(object sender, EventArgs e) {\n        if (!hoverSeen) {\n            hoverSeen = true;\n            // Todo, fix position\n            Point pos = ovalShape1.Parent.PointToClient(Cursor.Position);\n            toolTip1.Show("On oval", ovalShape1.Parent, pos);\n        }\n    }\n\n    private void ovalShape1_MouseLeave(object sender, EventArgs e) {\n        if (hoverSeen) toolTip1.Hide(ovalShape1.Parent);\n        hoverSeen = false;\n    }	0
20437738	20437279	Getting JSON data from a response stream and reading it as a string?	var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();\nvar jsonObject = serializer.DeserializeObject(sr.ReadToEnd());	0
11466812	11466712	copying from one list box to other listbox	foreach (var item in Listbox1.Items)\n {\n     listbox2.Items.Add(item.ToString());\n }	0
19076461	19075261	Set window position in the center	this.Location = new Point((SystemInformation.PrimaryMonitorSize.Width - this.Width) / 2, (SystemInformation.PrimaryMonitorSize.Height - this.Height) / 2);	0
11649794	11649452	Add lookup field to list from a RootWeb	strInternalFieldName = colFields.AddLookup(strInternalFieldName, targetListID, currentWeb.Site.RootWeb.ID, true);\nthen it works fine	0
3681442	3679579	check for groups a user is a member of	using System.DirectoryServices.AccountManagement;\n\nstatic void Main(string[] args)\n{\n    ArrayList myGroups = GetUserGroups("My Local User");\n}\npublic static ArrayList GetUserGroups(string sUserName)\n{\n    ArrayList myItems = new ArrayList();\n    UserPrincipal oUserPrincipal = GetUser(sUserName);\n\n    PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();\n\n    foreach (Principal oResult in oPrincipalSearchResult)\n    {\n        myItems.Add(oResult.Name);\n    }\n    return myItems;\n}\n\npublic static UserPrincipal GetUser(string sUserName)\n{\n    PrincipalContext oPrincipalContext = GetPrincipalContext();\n\n    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);\n    return oUserPrincipal;\n}\npublic static PrincipalContext GetPrincipalContext()\n{\n    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);\n    return oPrincipalContext;\n}	0
19978123	19860140	How to get twitter user_timeline using Mono?	mozroots --import --ask-remove	0
32051476	32050116	WPF, C# - SelectAll in ?heckEdit	public bool? AllSelected\n{\n    get \n    { \n        // Check if all are checked\n        if (!MyProperty.Any(x => !x.IsChecked))\n        {\n            return true;\n        }\n\n        // Check if none are checked\n        if (!MyProperty.Any(x => x.IsChecked))\n        {\n            return false;\n        }\n\n        // Otherwise some are checked.\n        return null;\n    }\n\n    set\n    {\n        _allSelected = value;\n\n        MyProperty.ForEach(x => x.IsChecked = value);\n\n        OnPropertyChange("AllSelected");\n    }\n}	0
33653125	33652316	c# Get Path from a busy file using openFileDialog in winforms	openFileDialog1.ValidateNames = false;	0
2658065	2658054	Converting to Byte Array after reading a BLOB from SQL in C#	byte[] binDate = (byte[])row["Date"];	0
24442473	17591710	Converting a NV12 (YUV4:2:0) Byte array to RGB byte Array	CLIP(X) ( (X) > 255 ? 255 : (X) < 0 ? 0 : X)\n// YCbCr -> RGB\nCYCbCr2R(Y, Cb, Cr) CLIP( Y + ( 91881 * Cr >> 16 ) - 179 )\nCYCbCr2G(Y, Cb, Cr) CLIP( Y - (( 22544 * Cb + 46793 * Cr ) >> 16) + 135)\nCYCbCr2B(Y, Cb, Cr) CLIP( Y + (116129 * Cb >> 16 ) - 226 )	0
11899487	11899440	Why do I have to create a Map in AutoMapper	public abstract class Mapper<TFrom, TTo>\n{\n    private void Configure()\n    {\n        Mapper.CreateMap<TFrom, TTo>();\n    }\n\n    public TTo Map(TFrom @from)\n    {\n        Configure();\n        return Mapper.Map<TFrom, TTo>(@from);\n    }\n\n    public IEnumerable<TTo> Map(IEnumerable<TFrom> fromList)\n    {\n        return fromList == null\n            ? null \n            : fromList.Select(Map).ToList();\n    }\n}	0
9336766	9336555	Writting XML files	[XmlArray("Configurations")]\n[XmlArrayItem("Configuration")]	0
20793413	20793348	Having problems to find the right syntax to select XML info using LINQ-to-XML	// get networkAdapter element first\nvar networkElement = doc.Root\n                        .Element("networkAdapters")\n                        .Elements("networkAdapter")\n                        .First(a => (string)a.Attribute("id") == networkAdapter.networkAdapterId.ToString());\n\n// iterate over ipAddress elements\nforeach(var address in networkElement.Element("ipAddresses").Elements("ipAddress"))\n{\n    // you have to declare item here,\n    // otherwise you'll add the same item more then once to the list\n    var item = new IpAddress();\n    item.networkAdapterId = networkAdapter.networkAdapterId;\n\n    item.address    = (string)address.Attribute("address");\n    item.subnetMask = (string)address.Attribute("subnetMask");\n    item.index      = (int)address.Attribute("index");\n\n    ipAddressList.Add(item);\n}	0
12072426	12072241	When chaining a base constructor, how can I reuse initialization code in an overload	public class CustomException : Exception\n{\n    private readonly string _customField;\n\n    public CustomException(string customField, string message)\n        : base(message)\n    {\n        Init(out _customField, customField);\n    }\n\n    public CustomException(string customField)\n        : base()\n    {\n        Init(out _customField, customField);\n    }\n\n    private Init(out string _customField, string customField)\n    {\n        _customField = customField;\n    }\n}	0
13642721	13627668	mvc3 checkboxfor enum without enum being in model	public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct\n{\n    StringBuilder sb = new StringBuilder();\n\n    foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())\n    {\n        TagBuilder builder = new TagBuilder("input");\n        long targetValue = Convert.ToInt64(item);\n        long flagValue = Convert.ToInt64(modelItems);\n\n        if ((targetValue & flagValue) == targetValue)\n            builder.MergeAttribute("checked", "checked");\n\n        builder.MergeAttribute("type", "checkbox");\n        builder.MergeAttribute("value", item.ToString());\n        builder.MergeAttribute("name", name);\n        builder.InnerHtml = item.ToString();\n\n        sb.Append(builder.ToString(TagRenderMode.Normal));\n    }\n\n    return new HtmlString(sb.ToString());\n}	0
31442153	31437925	How can I include If-None-Match header in HttpRequestMessage	request.Headers.TryAddWithoutValidation("If-None-Match", "8001");	0
19365660	19365168	Remove All from List where each line doesn't contain any item from another list	products.RemoveAll(p => !fruits.Any(f => f.IndexOf(p, StringComparison.CurrentCultureIgnoreCase) >= 0));	0
29718661	29718587	How to fill a 2 dimensional array's row with random numbers from Enumerable.Range list c#	static void InitMatrix(int[,] mat)\n{\n    Random rnd = new Random();\n\n    for (int i = 0; i < mat.GetLength(0); i++)\n    {\n        List<int> numbers = Enumerable.Range(1, 45).ToList();\n\n        if(mat.GetLength(0)< mat.GetLength(1))\n        {\n           for (int j = 0; j < mat.GetLength(1); j++)\n           {\n               int index = rnd.Next(0, numbers.Count );\n               mat[i, j] = numbers[index];\n               numbers.RemoveAt(index);\n           }\n        }\n    }\n}	0
9289500	9289475	Difference of two DataTables in c#	DataTable table1= ds.Tables["table1"];\nDataTable table2= ds.Tables["table2"];\nvar diff= table1.AsEnumerable().Except(table2.AsEnumerable(),\n                                                    DataRowComparer.Default);	0
9330026	9329911	How to get value from applicationSettings?	string s = SDHSServer.Properties.Settings.DOServer_WebReference1_Service;	0
13442804	13442535	Usage of ITemplate in custom control	public class Tooltip : WebControl	0
22326669	6540160	How to retrieve a subset of fields using the C# MongoDB driver?	usersCollection.FindAllAs<User>()\n               .SetFields(Fields<User>.Include(user => user.FirstName,\n                                               user => user.LastName)\n                                      .Exclude(user => user.SSN)\n               .ToArray();	0
10268852	10268749	C# abstract base class - extending the implementation	public class GeoLocation\n        {\n            public double Longitude { get; set; }\n            public double Latitude { get; set; }\n            public string LocationName { get; set; }\n        }\n\n        public class GeoLocationEx : GeoLocation\n        {\n            public double Address { get; set; }\n        }\n\n        public abstract class Base<T>\n        {\n            public abstract T GeoLocation { get; set; }\n        }\n\n        public class Concrete : Base<GeoLocation>\n        {\n            public override GeoLocation GeoLocation\n            {\n                get;\n                set;\n            }\n        }\n\n        public class Concrete2 : Base<GeoLocationEx>\n        {\n            public override GeoLocationEx GeoLocation\n            {\n                get;\n                set;\n            }\n        }	0
11574366	11574320	Could not find a part of the path 'C:\	"C:\\CMSExportedData\\Sales-" + DateTime.Now.ToString("yyyyMMdd") + ".txt"	0
15829626	15829582	Count lines for a particular string combination	string[] lines = File.ReadAllLines(filePath)\nint count = lines.Count(input => input.Contains("ProductServices") && \n                                 input.Contains("Add Product"));	0
3790726	3790681	Regular expression to remove HTML tags	var pattern = @"<(img|a)[^>]*>(?<content>[^<]*)<";\nvar regex = new Regex(pattern);\nvar m = regex.Match(sSummary);\nif ( m.Success ) { \n  sResult = m.Groups["content"].Value;	0
19975840	19975784	automatically login to windows after startup	LockWorkStation()	0
40754	40730	How do you give a C# Auto-Property a default value?	public int X { get; set; } = x; // C# 6 or higher	0
19470283	19469894	Referencing buttons with numbers	int i = 1;\n        Control[] matches = this.Controls.Find("Card" + i.ToString(), true);\n        if (matches.Length > 0 && matches[0] is Button)\n        {\n            Button btn = (Button)matches[0];\n            // ... do something with "btn" ...\n            btn.PerformClick();\n        }	0
19966428	19711324	how to read Custom headers in AfterReceiveRequest() method	var requestXML = request.ToString();\nvar headerData = System.Text.Encoding.UTF8.GetBytes(requestXML);\n  using (MemoryStream memoryStream = new MemoryStream(headerData))\n  {\n         using (XmlReader xmlReader = new XmlTextReader(memoryStream))\n         {\n              xmlReader.MoveToContent();\n              while (xmlReader.Read())\n              {\n                  if (xmlReader.NodeType == XmlNodeType.Element)\n                  { \n                      //read whatever element is desired      \n                  }\n               }\n          }\n    }	0
21255108	21254826	Calculate a percentage column in controller for use in view	var calls = db.Calls.Where(x =>x.status != "Resolved" && x.status != "Closed").ToList();\nvar callsCount = calls.Count();\n\nvar sites = calls.GroupBy(calls => new { calls.site })\n          .Select(s => new SiteVM\n          {\n              Site = s.Key.site,\n              Number = s.Count(),\n              Perc = callsCount / s.Count() * 100\n          }).OrderByDescending(z => z.Number);	0
21648176	21647879	Add a Value Type independed	Expression.Add(...	0
26918030	26916463	Matrix of Toggles	using UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\n\npublic class NewBehaviourScript : MonoBehaviour\n{\n    string[] keywords;\n    bool[] kws;\n\n    void Awake()\n    {\n        int amount = 27;\n        keywords = new string[amount];\n        kws = new bool[amount];\n        for (int i = 0; i < amount; i++) keywords[i] = "" + i;\n    }\n\n    void OnGUI()\n    {\n        int columns = 4;\n        int x, y;\n        for (int index = 0; index < keywords.Length; index++)\n        {\n            x = 100 * (index % columns);\n            y =  30 * (index / columns) + 30;\n            bool oldValue = kws[index];\n            kws[index] = GUI.Toggle(new Rect (x, y, 100, 30), kws[index], keywords[index]);\n            if (kws[index] != oldValue)\n            {\n                Debug.Log("Switched: " + keywords[index] + " to " + kws[index]);\n            }\n        }\n    }\n}	0
2193018	2189376	How to change row color in datagridview?	foreach (DataGridViewRow row in vendorsDataGridView.Rows) \n     if (Convert.ToInt32(row.Cells[7].Value) < Convert.ToInt32(row.Cells[10].Value)) \n     {\n         row.DefaultCellStyle.BackColor = Color.Red; \n     }	0
8260757	8260612	C to C# callback raises exception after a while	bool l_bResult = DLLDownloadConfigration(OnDownloadStatusUpdate, OnDownloadFinished);	0
1839326	1839222	how to remove unnecessary properties from user control?	[Browsable(false)]\npublic override bool AutoScroll {\n  get { return base.AutoScroll; }\n  set { base.AutoScroll = value; }\n}\n[Browsable(false)]\npublic new Size AutoScrollMargin {\n  get { return base.AutoScrollMargin; }\n  set { base.AutoScrollMargin = value; }\n}	0
12219201	10978912	Facebook Login with Selenium for C#	IWebDriver driver = new FireFoxDriver();\ndriver.GoToUrl("www.facebook.com");\n\nvar element = driver.FindElement(By.Id("email"));\nelement.SendKeys(email);\n...\nelement = driver.FindElement(By.Id("submit button id"));\nelement.Click();	0
8881631	8881456	How to test an 7zip arhive?	SevenZipExtractor zipfile=new SevenZipExtractor("path to your archive");\nif (zipfile.Check())\n{\nMessageBox.Show("Your archive or zip is ok");\n}\nelse\n{\nMessageBox.Show("Your archive or zip is not ok");\n}	0
3584449	3583074	Execute Parameterized SQL StoredProcedure via ODBC	OdbcCommand ODBCCommand = new OdbcCommand("{call getDetailsFromEmail (?)}", ODBCConnection);\nODBCCommand.CommandType = CommandType.StoredProcedure;\nODBCCommand.Parameters.AddWithValue("@KundenEmail", KundenEmail);	0
4275492	4275440	How to Convert Hex String to Hex Number	Convert.ToInt32("3A", 16)	0
19954218	19954131	Windows phone background agent ShellTile cant be added	using System.Linq;	0
17454888	17454565	Stack with AddUniqueItem	public static void PushUnique<T>(this Stack<T> stack, T item\n    , IEqualityComparer<T> comparer = null)\n{\n    comparer = comparer ?? EqualityComparer<T>.Default;\n    var otherStack = new Stack<T>();\n    while (stack.Any())\n    {\n        var next = stack.Pop();\n        if (!comparer.Equals(next, item))\n            otherStack.Push(next);\n    }\n\n    foreach (var next in otherStack)\n        stack.Push(next);\n    stack.Push(item);\n}	0
28843508	28835833	How to check connection to mongodb	var connectionString = "mongodb://localhost";\nvar client = new MongoClient(connectionString);\nvar server = client.GetServer();\nserver.Ping();	0
1042781	980053	Removing the default MDI menu of a MDI Container form when a MDI Child is maximized	private void OnForm_Load(object sender, EventArgs e)\n{\n    this.MainMenuStrip = new MenuStrip();\n}	0
20164413	20164363	How to get particular character position from string using C#	var pos = a.IndexOf('E');	0
4363511	4363493	Currency validation issue	Type="Currency"	0
26345814	26341861	how to clear memory of WritableBitmap	var bmp = new System.Windows.Media.Imaging.BitmapImage();\nbmp.SetSource( e.ChosenPhoto );\nvar ib = new ImageBrush() { ImageSource = bmp, Stretch = Stretch.Fill };\nContentPanel.Background = ib;	0
20040017	20039932	How do I determine the generic type of an implemented interface using reflection?	PropertyInfo.PropertyType.GenericTypeArgument	0
2127475	2127445	How can I play video files?	// [ C# ]\nWMPLib.WindowsMediaPlayer Player;\n\nprivate void PlayFile(String url)\n{\n    Player = new WMPLib.WindowsMediaPlayer();\n    Player.PlayStateChange += \n        new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);\n    Player.MediaError += \n        new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);\n    Player.URL = url;\n    Player.controls.play();\n}\n\nprivate void Form1_Load(object sender, System.EventArgs e)\n{\n    // TODO  Insert a valid path in the line below.\n    PlayFile(@"c:\myaudio.wma");\n}\n\nprivate void Player_PlayStateChange(int NewState)\n{\n    if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)\n    {\n        this.Close();\n    }\n}\n\nprivate void Player_MediaError(object pMediaObject)\n{\n    MessageBox.Show("Cannot play media file.");\n    this.Close();\n}	0
12264399	12264163	RESTful WCF receiving Base64 message. Need to convert message back to XML	byte[] encodedMessageAsBytes = System.Convert.FromBase64String(requestString);\n\nstring message = System.Text.Encoding.Unicode.GetString(encodedMessageAsBytes);	0
19520966	19510449	Disk space in WinRT using C# in Windows 8	var freeSpaceProperty = "System.FreeSpace";\nvar applicationData = Windows.Storage.ApplicationData.current;\nvar localFolder = applicationData.localFolder;\n\nlocalFolder.getBasicPropertiesAsync().then(function (basicProperties) {\n    // Get extra properties\n    return basicProperties.retrievePropertiesAsync([freeSpaceProperty]);\n}).done(function (extraProperties) {\n    var propValue = extraProperties[freeSpaceProperty];\n    if (propValue !== null) {\n        outputDiv.innerText = "Free Space: " + propValue;\n}\n}, function (error) {\n    // Handle errors encountered while retrieving properties\n});	0
9544909	9540955	How do I filter results from an association table that is linked to only one other table?	var query = context.GeoBoundaries\n                   // Try either g.GeoBoundaries or g.GeoBoundary1\n                   .Where(g => g.GeoBoundaries.Any(a => a.GeoID == 29);\n                   .Select(g => new { g.GoeID, g.Name });	0
14186952	14186824	XmlException: The input document has exceeded a limit set by MaxCharactersFromEntities	var doc = new XmlDocument();\n\n        using (var stream = new MemoryStream(Encoding.Default.GetBytes(xml)))\n        {\n            var settings = new XmlReaderSettings();\n\n            // The default is 0, but setting it here allows us to document exactly why we are taking this approach.\n            settings.MaxCharactersFromEntities = 0;\n\n            using (var reader = XmlReader.Create(stream, settings))\n            {\n                doc.Load(reader);\n            }\n        }	0
14187952	14186114	Implement an interface in C++?	Derived* d_ptr = new Derived();\nBase b = *d_ptr; // object slicing, d's methods will become Base methods;\nBase* b_ptr = &b;\nb_ptr->Update(); // will call Base::Update()	0
11938738	11938391	Postsharp move some logic from run time to compile time based on condition	yield return method	0
15882119	15882046	C# multi-dimension array sort based on user input	// assumes stringdata[row, col] is your 2D string array\nDataTable dt = new DataTable();\n// assumes first row contains column names:\nfor (int col = 0; col < stringdata.GetLength(1); col++)\n{\n    dt.Columns.Add(stringdata[0, col]);\n}\n// load data from string array to data table:\nfor (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)\n{\n    DataRow row = dt.NewRow();\n    for (int col = 0; col < stringdata.GetLength(1); col++)\n    {\n        row[col] = stringdata[rowindex, col];\n    }\n    dt.Rows.Add(row);\n}\n// sort by third column:\nDataRow[] sortedrows = dt.Select("", "3");\n// sort by column name, descending:\nsortedrows = dt.Select("", "COLUMN3 DESC");	0
14473423	14473278	Dictionary-like structure with custom search behavior	public static class DictionaryRangeExtensions\n{\n    public IEnumerable<T> FindValuesInRange(this Dictionary<double,T> dictionary, double lowerBound, double upperBound)\n    {\n         dictionary.Where(kvp=> kvp.Key > lowerBound && kvp.Key < uppoerBound).Select(kvp=>kvp.Value);\n    }\n}	0
32915280	32915078	How can i create a filter by with Linq?	var filteredProducts = Products;\nif(model.man != null)\n    filteredProducts = filteredProducts.Where(x => (from man in model.man where man.HasValue() select man.Value).Contains(x.manId));\nif(model.size != null)\n    filteredProducts = filteredProducts.Where(x => (from size in model.size where size.HasValue() select size.Value).Contains(x.sizeId));\n//etc\nvar enumerate = filteredProducts.ToList();	0
15207495	15207425	Fill A Graphic With Text Using RectangleF and DrawString	Graphics.MeasureString	0
8578268	8578110	how to extract common file path from list of file paths in c#	using System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        List<string> Files = new List<string>()\n        {\n            @"c:\abc\pqr\tmp\sample\b.txt",\n            @"c:\abc\pqr\tmp\new2\c1.txt",\n            @"c:\abc\pqr\tmp\b2.txt",\n            @"c:\abc\pqr\tmp\b3.txt",\n            @"c:\a.txt"\n        };\n\n        var MatchingChars =\n            from len in Enumerable.Range(0, Files.Min(s => s.Length)).Reverse()\n            let possibleMatch = Files.First().Substring(0, len)\n            where Files.All(f => f.StartsWith(possibleMatch))\n            select possibleMatch;\n\n        var LongestDir = Path.GetDirectoryName(MatchingChars.First());\n    }\n}	0
18551711	18551690	How to remove each item that appears in first collection from second collection using linq?	var solution = list1.Except(list2);	0
30912089	30893506	Table in Word document with n columns to fit as per page size and allow truncated columns to break across page using Aspose.words for .Net	string dst = dataDir + "table.doc";\n\nAspose.Words.Document doc = new Aspose.Words.Document();\nDocumentBuilder builder = new DocumentBuilder(doc);\n\n// Set margins\ndoc.FirstSection.PageSetup.LeftMargin = 10;\n//doc.FirstSection.PageSetup.TopMargin = 0;\ndoc.FirstSection.PageSetup.RightMargin = 10;\n//doc.FirstSection.PageSetup.BottomMargin = 0;\n\n// Set oriantation\ndoc.FirstSection.PageSetup.Orientation = Aspose.Words.Orientation.Landscape;\n\nAspose.Words.Tables.Table table = builder.StartTable();\n\nfor (int i = 0; i < 5; i++)\n{\n    for (int j = 0; j < 20; j++)\n    {\n        builder.InsertCell();\n        // Fixed width\n        builder.CellFormat.Width = ConvertUtil.InchToPoint(0.5);\n        builder.Write("Column : " + j);\n    }\n    builder.EndRow();\n}\nbuilder.EndTable();\n\n// Set table auto fit behavior to fixed width columns\ntable.AutoFit(AutoFitBehavior.FixedColumnWidths);\n\ndoc.Save(dst, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(Aspose.Words.SaveFormat.Doc));	0
5961481	5961442	Sending a class as a parameter to a thread?	class X : BaseClass\n{ \n   ...\n}\n\nclass Y : X\n{ \n    int yField;\n}\n\n...\n\nint Main(BaseClass instance)\n{ \n    if (instance is Y) (instance as Y).yField = 1;\n}	0
29353554	29353182	Can't access variable from code behind	Inherits="go._default"	0
14355235	14354922	Remove blue outlining of buttons	public class NoFocusCueButton : Button\n{\n    public NoFocusCueButton() : base()\n    {\n        InitializeComponent();\n\n        this.SetStyle(ControlStyles.Selectable, false);\n    }\n\n    protected override bool ShowFocusCues\n    {\n        get\n        {\n           return false;\n        }\n    }\n}	0
5889945	5889869	close a programatically created window with a button on that window	btn.Click += (q,w) => wnd.Close();	0
11797617	11797553	Select From database when multiple checkbox checked	string inClause = "1, 2, 3";\n\nvar sqls = "SELECT * FROM Brands WHERE Name in (" + inClause +")";	0
14336622	14336307	SMTP server without using default port(587)	MailMessage mailMsg = new MailMessage();\n    mailMsg.To.Add("somEmailAddress@SomMailHost.com");\n    // From\n    MailAddress mailAddress = new MailAddress("spongebob@sandymail.com");\n    mailMsg.From = mailAddress;\n\n    // Subject and Body\n    mailMsg.Subject = "subject";\n    mailMsg.Body = "body";\n\n    // Init SmtpClient and send on port 587\n    SmtpClient emailClient = new SmtpClient("mailserver", 587);\n    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");\n    emailClient.Credentials = credentials;\n    emailClient.Send(mailMsg);	0
21391316	21391059	Populate user control TextBox with Session variable	mybox.Text = (String)Session["var1"];	0
7530045	7529968	Sending screenshot via C#	System.IO.Stream stream = new System.IO.MemoryStream();\nEkran.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);\nstream.Position = 0;\n// later:\nAttachment attach = new Attachment(stream, "MyImage.jpg");	0
11799519	11799425	Listbox bound to ObservableCollection empty	{ get; set;}	0
9586716	9586664	Using Exit button to close a winform program	this.Close();	0
14695329	14695282	how to make search of a string in a data base in c#	"SELECT * FROM table1 where Nom like '%" + textBox1.Text + "%'"	0
14639624	14553198	How to perform crossover of double numbers in my GA implementation?	BitArray BAA1 = new BitArray(BitConverter.GetBytes(a1));\nBitArray BAA2 = new BitArray(BitConverter.GetBytes(a2));\n\n    for (int i = r.Next(0, 64); i > 0; i--)\n            {\n                temp = BAA1.Get(i);\n                temp2 = BAA2.Get(i);\n\n                BAA1.Set(i, temp2);\n                BAA2.Set(i, temp);\n\n\n                temp = BAB1.Get(i);\n                temp2 = BAB2.Get(i);\n\n                BAB1.Set(i, temp2);\n                BAB2.Set(i, temp);\n            }\n\n        byte[] tempbytes = new byte[BAA1.Length];\n\n        BAA1.CopyTo(tempbytes, 0);\n        double baa1 = BitConverter.ToDouble(tempbytes, 0);\n\n        BAA2.CopyTo(tempbytes, 0);\n        double baa2 = BitConverter.ToDouble(tempbytes, 0);	0
4861491	4861143	No post values when using html helpers	[HttpPost]\npublic ActionResult SendReply([Bind(Prefix="SendReplyPmForm")]SendReplyPmForm SendReplyForm)\n{\n  ...\n}	0
9015531	9015449	How to compile cs files into separate dll	csc /target:library /out:Something.xyz *.cs	0
13539074	13537679	Drawing a triangle in GDI+ given a rectangle	// Create a matrix and rotate it 45 degrees.\nMatrix myMatrix = new Matrix();\nmyMatrix.Rotate(45, MatrixOrder.Append);\ngraphics.Transform = myMatrix;\ngraphics.FillPolygon(new SolidBrush(Color.Blue), points);	0
17984736	17984659	How can I process through a list and put its contents into a new parent and child object?	var separator = new[] { "-" };\nvar topics = data.Select(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))\n    .GroupBy(strings => strings[0])\n    .Select(grouping => new Topic\n    {\n        Name = grouping.Key,\n        SubTopics = grouping.Select(s => new SubTopic {Name = s[1]}).ToList()\n    })\n    .ToArray();	0
13635038	13634868	Get the Default Gateway	public static IPAddress GetDefaultGateway()\n{\n    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();\n    if(card == null) return null;\n    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();\n    return address.Address;\n}	0
15083792	15083722	How do I convert an enum to a list and replace '_' with ' ' (space)	Enum.GetNames(typeof(EnumType)).Select(item => item.Replace('_',' '));	0
34252850	34252809	exit from a do while when a key is pressed (c#)	do{\nConsole.SetCursorPosition(Console.WindowWidth/2-2,3);\nswitch(fotograma++%4)\n    {\n            case 0 :\n                Console.Write("|");\n                break;\n            case 1 :\n                Console.Write("/");\n                break;\n            case 2 :\n                Console.Write("-");\n                break;\n            case 3 :\n                Console.Write("\\");\n                break;      \n        }\n    System.Threading.Thread.Sleep(50);\n\n}while(!Console.KeyAvailable);	0
18356641	18339619	Updating UILabel from another ViewController	ToString()	0
9296697	9296676	List all attributes of a user in AD by C# code	System.DirectoryServices	0
5848995	5848982	Binding data to a ToolStripComboBox	List<string> items = new List<string>{"item1", "item2", "item3"};\ntoolStripComboBox1.ComboBox.DataSource = items;	0
20655508	20655383	make compiled queries while sending 2 int	public static Func<DataClassesDataContext, int, int, int, IQueryable<tbl_desc_index>>\neditordetail1 = \n    CompiledQuery.Compile((DataClassesDataContext db, int a, int b, int c) =>\n             from p in db.tbl_desc_indexes\n             where p1.ed_journal_id == a && p.j_id == b && p.j_id1 == c\n             select p);	0
22426970	22415815	How do you change strings in a .NET exe? (Translation)	ilasm.exe /EXE /RESOURCE=[RES FILENAME].res .\[SAVED IL FILENAME].il	0
28198133	28198032	How to format display String to currency in C#	display = string.Format("Service Amount: {0}",service.ToString("C"));\nConsole.WriteLine(display);	0
2712968	2712954	Is there a way to compare date "strings" in C# without converting the strings?	if ( DateTime.Parse(date2) <=  DateTime.Parse(date1))\n\n{\n  // perform some code here\n}	0
15848758	15848575	Shortest declaration of the read/write property in F#	type Foo() =\n     member val Text : string = null with get, set	0
17052531	17052397	Add Ajax CalendarExtender to a dynamic textBox in ASP.NET C#	AjaxControlToolkit.CalendarExtender calenderDate = new AjaxControlToolkit.CalendarExtender();\n\n            for (int i = 0; i < 2; i++)\n            {\n                Label label = new Label();\n                TextBox text = new TextBox();\n                label.Text = Convert.ToString("varName");\n                ph1.Controls.Add(label);\n\n                text.ID = "myId" + i;\n\n                ph1.Controls.Add(new LiteralControl("&nbsp;"));\n\n                ph1.Controls.Add(text);\n\n\n                calenderDate.TargetControlID = text.ID;\n                ph1.Controls.Add(calenderDate);\n\n\n                ph1.Controls.Add(new LiteralControl("<br />"));\n            }	0
8146783	8134056	Find whether a dynamically called url has image in it	this one helped---\nhttp://stackoverflow.com/questions/1639878/how-can-i-check-if-an-image-exists-at-http-someurl-myimage-jpg-in-c-asp-net\n\n\nthis one too worked\n\n               try\n                {\n                    WebClient client = new WebClient();\n                    client.DownloadData(ImageUrl);\n\n                }\n                catch\n                {\n                    imgPhoto.ImageUrl = ../User/Images/ResourceImages/Candychocolate1.jpg";//default image path\n                }	0
23928770	23928741	How to get in a string one word and the following words separated by space?	string text = "nome varchar(20) NOT NULL DEFAULT NULL AUTO INCREMENT";\nMatch m = Regex.Match(text, @"DEFAULT\s+\S+");\nif (m.Success)\n{\n    string output = m.Value;\n}	0
17125431	17124481	How to move rectangle in the grid	Grid.SetColumn(pic, newColumnNumber);\nGrid.SetRow(pic, newRowNumber);	0
18067610	18066726	Search a text file for 2 strings and then write all the lines between the strings to another file	static List<string> LinesBetween(string path, string start, string end)\n{\n    var lines = new List<string>();\n    var foundStart = false;\n\n    foreach (var line in File.ReadLines(path))\n    {\n        if (!foundStart && line == start)\n            foundStart = true;\n\n        if(foundStart)\n            if (line == end) break;\n            else lines.Add(line);\n    }\n\n    return lines;\n}	0
2684560	2684518	Scheduling load with a round robin algorithm?	Queue<Server> q = new Queue<Server>();\n\n//get the next one up\nServer s = q.DeQueue();\n\n\n//Use s;\n\n\n//put s back for later use.\nq.Enqueue(s);	0
13945944	13945869	How to encrypt (Connection String) webconfig on deployment? For security reason	aspnet_regiis.exe -pef "connectionStrings" C:\	0
688670	688667	C#: How to convert long to ulong	long x = 10;\nulong y = (ulong)x;	0
30893312	30893240	how to display dates from two different tables?	public DateTime Date { get; set; }\npublic DateTime ChecklistDate { get; set; }\n\nprotected override void FillObject(DataRow dr)\n{\n    if (dr["Date"] != DBNull.Value)\n        Date = Convert.ToDateTime(dr["Date"]);\n    if (dr["ChecklistDate"] != DBNull.Value)\n        ChecklistDate = Convert.ToDateTime(dr["ChecklistDate"]);\n}\n\n\n<asp:BoundField DataField="Date" HeaderText="Service Date" SortExpression="Date"  dataformatstring="{0:dd/MM/yyyy}"></asp:BoundField>\n<asp:BoundField DataField="ChecklistDate" HeaderText="Checklist Date" SortExpression="ChecklistDate"  dataformatstring="{0:dd/MM/yyyy}"></asp:BoundField>	0
727325	727308	Linq query to include a subtype	var peopleInOakland = \n    from p in entities.DbObjectSet.OfType<Person>()\n    from a in p.Addresses.OfType<MailingAddress>()\n    where a.City == "Oakland"\n    select \n        new { Person = p, Addresses = p.Addresses.OfType<MailingAddress>() };	0
7986782	7986707	How to round a decimal point up?	double x = 0.434;\nint y = (int)Math.Ceiling(x*10);\nx = y/10.0;	0
5674072	5674021	Cast in List object	myA = myB.Cast<A>().ToList();	0
14689496	14689446	Searching a random Array for a specific value	bool found = false;\n for (int i = myArray.Length - 1; i >=0 ; i--) \n     if(myArray[i] == 5)\n        found = true;\n if(found)\n {\n\n }\n else\n {\n\n }	0
13927294	13925758	Get image from Webpage and show (Windows Phone)	void ImageDownloader() \n    {\n        WebClient client = new WebClient();\n        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);\n        client.DownloadStringAsync(new Uri("http://apod.nasa.gov/apod/astropix.html"));\n\n    }\n\n    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n    {\n        string str = e.Result.Remove(0,(e.Result.IndexOf("SRC=")+5));\n        str = "http://apod.nasa.gov/apod/"+str.Substring(0, (str.IndexOf(".jpg")+4));\n        ImageBrush imb = new ImageBrush();\n        imb.ImageSource = new BitmapImage(new Uri(str));\n        LayoutRoot.Background = imb;\n    }	0
23593436	23593407	Parsing xml file with linq	XNamespace ns = "urn:oasis:names:tc:opendocument:xmlns:container";\n\nvar rootFiles = xml.Descendants(ns + "rootfile");	0
24292859	24292576	Static event tries to declare non static instance	using System;\n\npublic static class Test\n{\n    public static void Main()\n    {\n        EventsClass.someDelegateEvent += func;\n        EventsClass.Raise();\n\n    }\n\n\n    public static void func(int number){\n        Console.WriteLine(number);\n    }\n\n}\n\npublic static class EventsClass\n{\n    public delegate void someDelegate(int num);\n\n    public static event someDelegate someDelegateEvent;\n\n    public static void Raise()\n    {\n        if (someDelegateEvent != null)\n        someDelegateEvent(6);\n    }\n}	0
6968959	6960607	Filepath to xml within xlsx in c#	string filename = "c:\\test\\file.xslx";\n            string partPath = "/_rels/.rels";\n\n            Package xpsPackage = Package.Open(fileName, FileMode.Open)\n            Uri partUri = new Uri(partPath, UriKind.Relative);\n            PackagePart xpsPart = xpsPackage.GetPart(partUri);\n\n            Stream xpsStream = xpsPart.GetStream(FileMode.Open)\n            XmlReader xmlReader = XmlReader.Create(xpsStream);\n\n            XdmNode input = processor.NewDocumentBuilder().Build(xmlReader);	0
17499179	17499109	rearranging the elements in list	var numbers = new List<Int32>{1,2,3,4,5};\n    var loggedInUsers = numbers.Where(x=>x == 4);\n    var restOfUsers = numbers.Where(x=>x != 4);\n    var joinedLists = loggedInUsers.Union(restOfUsers).ToList();	0
19252335	18513850	How should we parse a specific JSON date format in the ASP.NET C# application?	return (new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(reader.Value)));	0
26386812	26386412	How to add BLOB data into my SQL command	IDbDataParameter param = cmd.CreateParamter();\nparam.ParameterName = "@Photo";\nparam.Value = blob;\nparam.Size = blob.Length;\nparam.DbType = DbType.Binary;\ncmd.Parameters.Add(param);	0
10851583	10851252	Pass a label as parameter to a function	public void ChangeLabel(string msg, Label label) {\n    if (label.InvokeRequired)\n        label.Invoke(new MethodInvoker(delegate {\n            label.Text = msg;\n        }));\n    else\n        label.Text = msg;\n}	0
565119	565075	How to set the value of a read-only property with generic getters and setters?	public Guid ItemId\n{\n    get;\n    private set;\n}\n\npublic TransactionItem()\n{\n    this.ItemId = Guid.Empty;\n}	0
33904526	33873592	Where I can find Microsoft.DirectX assembly to reference	Microsoft.DirectX	0
22463190	22463083	How do I command a page to reload in ASP.NET?	Response.Redirect(thisPage);	0
15292086	15291941	How to return collection of ListViewItems?	// declared in AnimalManager class\n    private static List<Animal> AnimalList { get; set; }\n\n\n     public static ListViewItem[] DisplayAllAnimals()\n    {\n        //Show animals on ListView by proper column\n        var listViewItems = new List<ListViewItem>();\n        foreach (var animal in AnimalList)\n        {\n            ListViewItem item = new ListViewItem(animal.Id); // generated ID\n            item.SubItems.Add(animal.AnimalSort); // AnimalSort\n            item.SubItems.Add(animal.Name); //Name\n            item.SubItems.Add(animal.Age); //Age\n            item.SubItems.Add(animal.Gender.ToString()); // Animal gender\n            listViewItems.Add(item);\n\n        }\n\n        return listViewItems.ToArray();\n    }\n\n\n    // Mainform UI class where its used\n    lsbOverview.Items.AddRange(AnimalManager.DisplayAllAnimals());	0
23123649	23123620	two dimension arrays C# how to do a for loop? or search through the array?	Dictionary<string, List<DateTime>>	0
13570575	13569568	ToolTip with image inside of it	jQuery/JavaScript	0
11182690	11182533	Current index of a letter in OnKeyDown	private void richTextBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        MessageBox.Show(richTextBox1.SelectionStart.ToString());\n    }	0
20605643	20540890	Casting of WPF controls	this.Children.Add(HOST);	0
27814973	27814810	How to get scroll width from web browser control in wpf/windows c#	IEWb.Document.Body.ScrollRectangle.Height;\nIEWb.Document.Body.ScrollRectangle.Width;	0
18159076	18159041	Remove last x elements from the list	static class ListEx\n{\n    public static void RemoveFrom<T>(this List<T> lst, int from)\n    {\n        lst.RemoveRange(from, lst.Count - from);\n    }\n}	0
4810980	4810918	How to group using LINQ, then get value of largest group	var bestReason = successfulReasons\n    .GroupBy(r => r.Reason)\n    .OrderByDescending(grp => grp.Count())\n    .First().Key;	0
28450283	28450170	Sorting out a list of items in ascending date	results = CurrentPage.Children.Where("eventDate >= minDate AND eventDate < maxDate", month)\n                           .OrderBy("eventDate asc")\n                           .Skip(currentPage * itemsPerPage)\n                           .Take(itemsPerPage);	0
13467131	13466889	How to know while user editing the WPF DataGrid Cell is empty?	void MainDataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)\n{\n   TextBox tb = e.Column.GetCellContent(e.Row) as TextBox;\n   tb.TextChanged+=new TextChangedEventHandler(tb_TextChanged); \n}\n\nvoid tb_TextChanged(object sender, TextChangedEventArgs e)\n{\n   //here, something changed the cell's text. you can do what is neccesary\n}	0
9092055	9090846	Trouble with submitting XML to Rest Service	var request = CreateBaseRequest(body);\n        HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();\n        Stream Answer = WebResp.GetResponseStream();\n        StreamReader response = new StreamReader(Answer);\n        var r = response.ReadToEnd();\n\n static HttpWebRequest CreateBaseRequest(string postData)\n    {\n\n        var req = (HttpWebRequest)HttpWebRequest.Create(@"https://xyz.com/");\n\n        req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";\n        req.Method = "POST";\n        req.KeepAlive = true;\n\n        byte[] buffer = Encoding.ASCII.GetBytes(postData);\n\n        req.ContentLength = buffer.Length;\n        Stream PostData = req.GetRequestStream();\n        PostData.Write(buffer, 0, buffer.Length);\n        PostData.Close();\n\n        return req;\n\n    }	0
4324144	4323888	How do I programatically change the layout of a Word 2010 document?	Document.ActiveWindow.View.Type = wdPrintView;	0
4119194	4119161	How to set timeout for webBrowser navigate event	public void NavigateTo(Uri url) {\n        webBrowser1.Navigate(url);\n        timer1.Enabled = true;\n    }\n\n    private void timer1_Tick(object sender, EventArgs e) {\n        timer1.Enabled = false;\n        MessageBox.Show("Timeout on navigation");\n    }\n\n    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n        if (e.Url == webBrowser1.Url && timer1.Enabled) {\n            timer1.Enabled = false;\n            // etc..\n        }\n    }	0
14728434	14728388	c# how do i compare two string that have matching letters but one has a whitespace	if (tenInstrucType.Trim().Equals(instrucType.Trim()))	0
9518973	9518781	Sorting objects in ArrayList by DateTime variable inside the objects	// Assuming EventHolder is a List<Event>\nEventHolder.Sort((d1, d2) => DateTime.ParseExact(d1.Date_And_Time,"dd/MM/yyyy HH:mm",region).CompareTo(DateTime.ParseExact(d2.Date_And_Time,"dd/MM/yyyy HH:mm",region)));	0
22218297	22218205	Store json in variable	json_callback=renderExampleThreeResults	0
26880118	26839112	Is there a way to check the validity of internal hyperlinks/Cross references added via a bookmark inside an active word document?	Dim doc As Word.Document\n\nDim fld As Word.Field\n\nDim rng As Word.Range\n\nDim str As String\n\n\n\nSet doc = ActiveDocument\n\nFor Each fld In doc.Fields\n\n    If fld.Type = wdFieldRef Then\n\n        str = fld.Code\n\n        str = Replace(str, "REF ", "")\n\n        str = Replace(str, "\h", "")\n\n        str = Trim(str)\n\n      ???need handle the error if the bookmark has been deleted.\n\n        Set rng = doc.Bookmarks(str).Range\n\n    End If\n\nNext	0
2127027	2120719	TargetInvocationException on Image update in WPF	private void Instance_VideoRefresh()\n{\n    if (VideoImageContainer.Instance.VideoImage != null)\n        this.VideoCapture.Dispatcher.Invoke(\n                System.Windows.Threading.DispatcherPriority.Normal,\n                new Action(\n                  delegate()\n                  {\n                      videoImage.Source = VideoImageContainer.Instance.VideoBitmapSourceImage;\n                  }\n              ));\n}	0
15052630	15052572	invalid operation exception in copying data from data grid to database table	string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations) VALUES ('"+row.Cells[0]+"','"+row.Cells[1]+"',"+row.Cells[2]+",'"+row.Cells[3]+"');";	0
5622123	5621018	xml element list to array of common base type	[XmlRoot("TestFile")]\npublic class TestFile\n{\n    [XmlElement(ElementName = "string", Type = typeof(ValueString))]\n    [XmlElement(ElementName = "bool", Type = typeof(ValueBool))]\n    public List<Test> Tests;\n}	0
6023664	6023584	c# read in two bytes from string	string myString = "313233343536373839";\nint strLen = myString.Length;\n\nfor (int i=0; i<strLen; i+=2)\n{\n    string myChars = myString.Substring(i, 2);\n    // do something with myChars here ...\n}	0
8060988	8060947	Preventing textbox value from changing	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    if (Regex.IsMatch(textBox1.Text, "[0-9]"))\n    {\n        MessageBox.Show("Only letters please");\n        textBox1.Text = Regex.Replace(textBox1.Text, "[0-9]", String.Empty);\n    }\n}	0
13019303	13019207	Executing KeyDown method after pressing button	public MyForm()\n{\n    InitializeComponent();\n    KeyPreview = true;\n}\n\nprotected override void OnKeyDown(KeyEventArgs e)\n{\n    // Insert key presses logic\n    base.OnKeyDown(e);\n}	0
19260114	19254586	Fastest way to get values from 2d array	var startRow = -1; // "row" in the new array.\nvar endRow = -1;\n\nvar match = "D";\n\nfor (int i = 0; i < arr.GetLength(1); i++)\n{\n    if (startRow == -1 && arr[0,i] == match) startRow = i;\n    if (startRow > -1 && arr[0,i] == match) endRow = i + 1;\n}\n\nvar columns = arr.GetLength(0);\nvar transp = new String[endRow - startRow,columns]; // transposed array\n\nfor (int i = startRow; i < endRow; i++)\n{\n    for (int j = 0; j < columns; j++)\n    {\n        transp[i - startRow,j] = arr[j,i];\n    }\n}	0
23060010	23059885	RichTextBox delete old output, and set new output when clicking a button	string newstring =txtInput.Text;\nrichTextBox.Text+=newString;	0
12800559	12800448	How to display string with maximum of 200 characters & trim the last few charaters till whitespace	string myString = inputString.Substring(0, 200);\n\nint index = myString.LastIndexOf(' ');\n\nstring outputString = myString.Substring(0, index);	0
11316626	11316490	Convert a 1d array index to a 3d array index?	int zDirection = i % zLength;\nint yDirection = (i / zLength) % yLength;\nint xDirection = i / (yLength * zLength);	0
10297739	10297008	how to get the last child of the parent node in Tree View using asp.net?	TreeNode t=TreeView1.SelectedNode.ChildNodes[TreeView1.SelectedNode.ChildNodes.Count - 1];	0
30948871	30948298	How to display WCF HTTP codes in service response	[DataContract]\npublic class Response<T>\n{\n    [DataMember]\n    public T Result { get; set; }\n\n    [DataMember]\n    public int Status { get; set; }\n}\n\n// then your declaration\nResponse<List<User>> serverResponse = Response<List<User>>();\n\n// on success\nserverResponse.Result = userList;\nserverResponse.Status = 200; // ok\n\n// on fail\nserverResponse.Status = 500; // fail\n\n// and contract\n[OperationContract]\n[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/GetUsers")]\nResponse<List<User>> GetUsers();	0
10680426	10679104	application block cache scavenging event	public class MyBackingStoreLog : IBackingStore\n{\n    // TODO: Implement all IBackingStore, pay attention to the Remove method\n    public void Remove(string key)\n    {\n        Log(string.format("{0} was just removed from cache", key));\n    }\n}	0
291820	291804	Split a Pascal-case string into logical set of words	Regex r = new Regex("([A-Z]+[a-z]+)");\nstring result = r.Replace("CountOfWidgets", m => (m.Value.Length > 3 ? m.Value : m.Value.ToLower()) + " ");	0
8155698	8069658	How can I react to windows waking from sleep mode in a wpf application?	Microsoft.Win32.SystemEvents.PowerModeChanged += this.SystemEvents_PowerModeChanged;\n\nprivate void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)\n{\n    if (e.Mode == PowerModes.Resume)\n        {\n            //Do Some processing here\n        }\n}	0
3468256	3468137	How to remove the inherited style on Text Box object from <td> that the text box is nested in	.TaskFormField {\n      font-size: 10px !important;\n    }\n\n    .TaskFormField {\n      font-size: 12px; /* One could believe that the font size should be 12px,\n                  but it remains 10px because the !important keyword is used. */\n    }	0
19658042	19656508	Converting an Image to Byte Array in Windows Store App	private async Task DoWork()\n{\n    var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/MyImage.png"));\n    var b64 = await ConvertStorageFileToBase64String(file);\n}\n\nprivate async Task<string> ConvertStorageFileToBase64String(StorageFile File)\n{\n    var stream = await File.OpenReadAsync();\n\n    using (var dataReader = new DataReader(stream))\n    {\n        var bytes = new byte[stream.Size];\n        await dataReader.LoadAsync((uint)stream.Size);\n        dataReader.ReadBytes(bytes);\n\n        return Convert.ToBase64String(bytes);\n    }\n}	0
24152617	24151275	How to bind WinForm's listbox selecteditems	List<KeyValuePair<string, Course>> coursesList = new List<KeyValuePair<string, Course>>();\nList<Course> cList = // Get your list of courses\n\nforeach (Course crs in cList)\n{\n    KeyValuePair<string, Course> kvp = new KeyValuePair<string, Course>(crs.Name, crs);\n    cList.Add(kvp);\n}\n\n// Set display member and value member for your listbox as well as your datasource\nlistBox1.DataSource = coursesList;\nlistBox1.DisplayMember = "Key"; // First value of pair as display member\nlistBox1.ValueMember = "Value"; // Second value of pair as value behind the display member\n\nvar studentsList = // Get your list of students somehow\n\nforeach (Student student in studentsList)\n{\n    foreach (KeyValuePair<string, Course> item in listBox1.Items)\n    {\n        // If students course is value member in listBox, add it to selected items\n        if (student.Course == item.Value)\n            listBox1.SelectedItems.Add(item);\n    }\n}	0
28304165	28303969	how to convert csv to xml with different headers	string[] source = File.ReadAllLines("text.csv");\nstring IGNORE_ROW = "XXXXX";\nList<string> data = new List<string>();\nstring test = "";\nfor (int i = 0; i < source.Length; i++)\n{\n    string[] _str = source[i].Split(',');\n    if (String.IsNullOrWhiteSpace(_str[0])) _str[0] = test;\n    else\n    {\n        test = _str[0];\n        _str[0] = IGNORE_ROW;\n    }\n\n    source[i] = String.Join(",", _str);\n}\n\nXElement data = new XElement("Root",\n    from str in source\n    where str.StartsWith(IGNORE_ROW) == false\n    let fields = str.Split(',')\n    select new XElement(fields[0],\n        new XElement("APPLICATION_NAME", fields[1]),\n        new XElement("START_TIME", fields[2]),\n        new XElement("STOP_TIME", fields[3]),\n        new XElement("SERVICE_DESCRIPTION", fields[4]),\n        new XElement("FILING_STATUS", fields[5]),\n        new XElement("TIME_OF_LAST_UPDATE", fields[6]),\n        new XElement("RECORD_STATUS", fields[7])\n    )\n);\nConsole.WriteLine(data);	0
2067100	2067075	How do I determine a mapped drive's actual path?	[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]\n    public static extern int WNetGetConnection(\n        [MarshalAs(UnmanagedType.LPTStr)] string localName, \n        [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, \n        ref int length);	0
19192287	19116072	Get All Configuration Files Across Application	using (var stream = assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().Single(n => n.EndsWith("Scripts.config")))) {\n    using (var sr = new StreamReader(stream)) {\n        var content = sr.ReadToEnd();\n        ...\n    }\n}	0
19677290	19662937	Write Data to Excel using Oledb	//for reading data \n Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;READONLY=FALSE\"\n\n //for writing data \n Extended Properties=\"Excel 8.0;HDR=NO;IMEX=3;READONLY=FALSE\"	0
9891567	9891324	LINQ to Create / Filter Object from Two Properties in HashSet	return groupsFieldsAuthority\n         .Where(x => x.Group == this)\n         .OrderBy(x => x.Group.Name)\n         .Select(x => new FieldAuthority(x.FieldDef, x.Authority))\n         .ToList();	0
3504230	3217234	Not able to read return value from spamassassin when launched from C# console	Process p = new Process();\n        p.StartInfo.RedirectStandardOutput = true;\n        p.StartInfo.UseShellExecute = false;\n\n        p.StartInfo.Arguments = @" /C C:\spamassassin.exe -e -L < C:\SPAM_TEST.MAI";\n        p.StartInfo.FileName = @"C:\WINDOWS\System32\cmd.exe";\n        p.OutputDataReceived += (sender, arguments) => Console.WriteLine("Received output: {0}", arguments.Data);\n        p.Start();\n        p.BeginOutputReadLine();\n        p.WaitForExit();\n        Console.WriteLine("Exit code: " + p.ExitCode);\n        p.Close();	0
2437990	2437966	An item with the same key has already been added	if (\n    sessionFactoryConfigPath != null && \n    sessionFactories.ContainsKey(sessionFactoryConfigPath)\n) {\n    sessionFactory = cfg.BuildSessionFactory();\n\n    if (sessionFactory == null)\n    {\n        throw new InvalidOperationException("cfg.BuildSessionFactory() returned null.");\n    }\n\n    sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);\n} else (sessionFactoryConfigPath != null) {\n    sessionFactory = sessionFactories[sessionFactoryConfigPath];\n}	0
14868107	14867942	Select particular node value from XML	XmlNode node = xml.DocumentElement.SelectSingleNode("/appSettings/connectionstring");\n\nstring nodeval=node.InnerText;	0
1987960	1987950	Using / or \\ for folder paths in C#	string path = @"C:\"  //Look ma, no escape	0
3239802	3206345	How can I best utilize Json.NET to modify parts of an existing JSON object?	string json = @"{""currentVersion"" : ""10.0"", \n                    ""folders"" : [], \n                    ""services"" : [\n                        {""name"" : ""nyc"", ""type"" : ""MapServer""}, \n                        {""name"" : ""philly"", ""type"" : ""MapServer""}\n                    ]\n                }";\n\nstring[] keepList = new string[] { "nyc" };\n\nJObject o = JObject.Parse(json);\nJArray services = (JArray)o["services"];\nJArray newServices = new JArray();\n\nforeach (JToken service in services)\n{\n    foreach (string keeper in keepList)\n    {\n        if ((string)service["name"] == keeper)\n        {\n            newServices.Add(service);\n            break;\n        }\n    }\n}\n\nservices.Replace(newServices);\n\nstring output = o.ToString();	0
21218387	21217802	Binding From sql to variables using the string name	Type type = address.GetType();\n\nfor (int i=0; i < reader.FieldCount; i++)\n{\n    var property = type.GetProperty(reader.GetName(i));\n\n    var setMethod = property.GetSetMethod();\n\n    setMethod.Invoke(address, new object[]{reader[i]});\n}	0
19301861	19300975	How To Access a property with a given expression	abstract class FooActivator<T> where T : class\n{\n    protected abstract Func<Foo, Bar<T>> ChosenProperty { get; }\n\n    public void Activate(T param)\n    {\n        var foo = new Foo();\n        ChosenProperty(foo).Method(param);\n    }\n}\n\nclass MyClassFooActivator : FooActivator<MyClass>\n{\n    protected override Func<Foo, Bar<MyClass>> ChosenProperty\n    {\n        get { return x => x.SomeBarMyClassProperty; }\n    }\n}	0
2176253	2176223	How do I pass an event handler as a method parameter?	EventHandler<MouseButtonEventArgs>	0
14170283	14170165	How can I add this WPF control into my WinForm?	public Form1()\n{\n  InitializeComponent();\n\n  ElementHost host= new ElementHost();\n  host.Size = new Size(200, 100);\n  host.Location = new Point(100,100);\n\n  AvalonEditControl edit = new AvalonEditControl();\n  host.Child = edit;\n\n  this.Controls.Add(host);\n}	0
7543625	7543615	Getting values from dictionary	foreach (KeyValuePair<int, int> kvp in myDictionary)\n{\n   var first = kvp.Key;\n   var second = kvp.Value;\n}	0
5757661	5757612	How does a WPF application know where to start?	public static void Main() {\n        MyAppName.App app = new MyAppName.App();\n        app.InitializeComponent();\n        app.Run();\n    }	0
10433695	10433607	How to retrieve the value of a colum in GridView	GridView1.Rows[rowId].Cells[columnId].Value	0
11781331	11781273	linq for a for loop inside a foreach loop	allItems = all.SelectMany(a => a.Items)\n              .Where(a => a.Item.TruckItemID.Equals(CarItem.CarItemID));	0
12056531	12056442	Last k elements of a List	var klist = list.Skip(Math.Max(0,list.Count - k)).Take(k);	0
9853077	9853015	How to Insert System.Datetime object into SqlServer via DbCommand with parameters	Database db = DBUtil.GetInstance().GetDataBase();\n    DbCommand cmd = db.GetSqlStringCommand(@"INSERT INTO [XXX] (\n    ...\n                                                          ,[FirstDate]\n    ...\n    ) VALUES (@FirstDate,...");\n\n   db.AddInParameter(cmd, "@FirstDate", DbType.DateTime, DateTime.Now );	0
25802334	25802073	Sending Mail automatically to the user who logs in	public bool Email(this string body, string subject, string sender, string recipient, string server)\n    {\n        try\n        {\n            // To\n            MailMessage mailMsg = new MailMessage();\n            mailMsg.To.Add(recipient);\n\n            // From\n            MailAddress mailAddress = new MailAddress(sender);\n            mailMsg.From = mailAddress;\n\n            // Subject and Body\n            mailMsg.Subject = subject;\n            mailMsg.Body = body;\n\n            // Init SmtpClient and send\n            SmtpClient smtpClient = new SmtpClient(server);\n            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();\n            smtpClient.Credentials = credentials;\n\n            smtpClient.Send(mailMsg);\n        }\n        catch (Exception ex)\n        {\n            throw new Exception("Could not send mail from: " + sender + " to: " + recipient + " thru smtp server: " + server + "\n\n" + ex.Message, ex);\n        }\n\n        return true;\n    }	0
16303859	16097768	How to get property from dynamic JObject programmatically	JObject myResult = GetMyResult();\nreturnObject.Id = myResult["string here"]["id"];	0
7378595	7378573	Constraint one generic parameter to be a subtype of the other	public static void RegisterType<T,U>() where U : T\n{\n    myContainer.RegisterType<T, U>();\n}	0
19773907	19761077	Need help converting numbers with decimals to other bases C#	33259 / 8 = 4157 remainder 3\n4157  / 8 = 519  remainder 5\n519   / 8 = 64   remainder 7\n64    / 8 = 8    remainder 0\n8     / 8 = 1    remainder 0\n1     / 8 = 0    remainder 1	0
21397369	21396615	match query datetime in database ms access	Global.dbCon.Open();\n  string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Format(DateOccurred, 'mm/dd/yyyy') = Format( '" + dt2+ "', 'mm/dd/yyyy') ORDER BY ID";\n  Global.reader = Global.riyeder(kalimatsql2);\n  if (Global.reader.HasRows) {\n     while (Global.reader.Read()) {\n        int idku = Convert.ToInt32(Global.reader.GetValue(0));\n        MessageBox.Show(idku.ToString());\n     }\n  }\n  Global.dbCon.Close();	0
29900411	29900364	How to Limit a Parameter in a Method?	public enum Option\n{\n    Option1,\n    Option2\n}\n\npublic void Add1(Option option, int variable)\n{\n    int ToReturn;        \n    ToReturn = variable + 1;\n\n    switch(option)\n    {\n        case Option1:\n            Var1 = ToReturn;\n            break;\n        case Option2:\n            Var2 = ToReturn;\n            break;\n    }\n}	0
13774240	13771083	Html Agility Pack get all elements by class	var findclasses = _doc.DocumentNode.Descendants("div").Where(d => \n    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")\n);	0
3908286	3907807	Get leading whitespace	public static string GetLeadingWhitespace(this string s, int tabLength = 4, bool trimToLowerTab = true)\n{\n  return new string(' ', s.GetLeadingWhitespaceLength());\n}\n\npublic static int GetLeadingWhitespaceLength(this string s, int tabLength = 4, bool trimToLowerTab = true)\n{\n  if (s.Length < tabLength) return 0;\n\n  int whiteSpaceCount = 0;\n\n  while (Char.IsWhiteSpace(s[whiteSpaceCount])) whiteSpaceCount++;\n\n  if (whiteSpaceCount < tabLength) return 0;\n\n  if (trimToLowerTab)\n  {\n    whiteSpaceCount -= whiteSpaceCount % tabLength;\n  }\n\n  return whiteSpaceCount;\n}	0
16034020	14705283	Changing Xml Build Action property programmatically in run time?	Configuration cfg = new Configuration();\n         cfg.Configure();\n         string   file="@\\mappingfilesPath \\DynamicMappingfiles.hbm.xml";\n         cfg.AddFile(new FileInfo(file));\n         cfg.AddAssembly(this.GetType().Assembly);	0
22069422	22068988	Convert List<object> to List<MyEnumType> with MyEnumType in Type variable	static object ConvertList<T>(List<string> stringList)\n    {\n        return stringList.Select(a => (T)Enum.Parse(typeof(T), a)).ToList();\n    }\n\n    static object ConvertList(List<string> stringList, Type enumType)\n    {\n        var method = new Func<List<string>, object>(ConvertList<object>).Method.GetGenericMethodDefinition();\n        return method.MakeGenericMethod(enumType).Invoke(null, new object[] { stringList });\n    }	0
2976180	2972056	How to convert a method that takes an OnError and OnCompleted into an Observable	var observable = Observable.Create<XElement>( \n    observer => \n    {\n        client.GetAsync<XElement>( \n        "resource1", \n        observer.OnError, \n        x => \n        {\n           observer.OnNext(x);\n           observer.OnCompleted();\n        }); \n        return () => {};\n    });	0
6335030	6334836	Reading an XML Feed into XElement	var xml = XElement.Load(uri);	0
4099384	4099366	How do I check if a number is positive or negative in c#?	bool positive = number > 0;\nbool negative = number < 0;	0
831029	831009	thread with multiple parameters	Thread standardTCPServerThread = \n  new Thread(\n    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)\n  );	0
24158100	24122920	Typing text into mergeFields located in text boxes in Word Document, using Interop.Word	Document wordDoc = wordApp.Documents.Open(@"C:\test.docx");\nBookmark bkm = wordDoc.Bookmarks["text1"];\nMicrosoft.Office.Interop.Word.Range rng = bkm.Range;\nrng.Text = "My address is...";	0
9264634	9264560	Issue with sql where clause when using datetime	string sql = "Select * from [project] where [condition] = 0 AND [Time] < GetDate()";	0
9888931	9888809	C# Console/Server access to web site	#region webclient with cookies\npublic class WebClientX : WebClient\n{\n    public CookieContainer cookies = new CookieContainer();\n    protected override WebRequest GetWebRequest(Uri location)\n    {\n        WebRequest req = base.GetWebRequest(location);\n        if (req is HttpWebRequest)\n            (req as HttpWebRequest).CookieContainer = cookies;\n        return req;\n    }\n    protected override WebResponse GetWebResponse(WebRequest request)\n    {\n        WebResponse res = base.GetWebResponse(request);\n        if (res is HttpWebResponse)\n            cookies.Add((res as HttpWebResponse).Cookies);\n        return res;\n    }\n}\n#endregion	0
1833006	1832962	Can you execute another EXE file from within a C# console application?	var proc = new Process();\n        proc.StartInfo.FileName = "something.exe";\n        proc.StartInfo.Arguments = "-v -s -a";\n        proc.Start();\n        proc.WaitForExit();\n        var exitCode = proc.ExitCode;\n        proc.Close();	0
11463723	11463651	How to query by where clause with EF code first	db.Users.Where(x=>x.ExternalId == externalId).ToList();	0
4272317	4272136	how to use controls of 1 from in another form?	public class MainForm\n{\n  private void OnEditClick()\n  {\n    EditForm editForm = new EditForm();\n    DialogResult result = editForm.ShowDialog(this);\n    //check the result for ok/cancel etc if your using them.\n    whatever = editForm.TextBox1;\n    whatever2 = editForm.TextBox2;\n}\n\npublic class EditForm\n{\n  public string TextBox1 { get { return textBox1.Text;} }\n  public string TextBox2 { get { return textBox2.Text;} }\n  // etc\n}	0
927112	927035	Custom multiselect gridview breaks on Row Update commands	internal class InputCheckBoxField : CheckBoxField\n    {\n        //... Some boilerplate for ID and other properties here\n\n        protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)\n        {\n            base.InitializeDataCell(cell, rowState);\n\n            if (cell.Controls.Count == 0)\n            {\n                CheckBox chk = new CheckBox();\n                chk.ID = CheckBoxID;\n                chk.AutoPostBack = true;\n                cell.Controls.Add(chk);\n\n                //This was the needed check\n                if(ReadOnly && rowState == DataControlRowState.Edit)\n                    chk.Enabled = false;\n            }\n        }\n    }	0
4007150	4007138	C# Replacing matching substrings in a string	var str = "20 40 30 30 30 30";\nvar distinctstr = String.Join(" ", str.Split().Distinct());	0
7945399	7945269	Pad Zero With Decimals	private double Calc(int places)\n    {\n        return 1 / (Math.Pow(10, places + 1));\n    }	0
13214303	13207251	Change ListBox background color	var item = ListBox_Main.Items[0] as ListBoxItem ;\nitem.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 255, 0));	0
21552405	21551425	Change image route to external link	public static MvcHtmlString ImageUrl(this HtmlHelper html, string imageName)\n{\n    return String.Format("http://somedomain.com/path/to/image/{0}", imageName);\n}	0
4244486	4244446	creating a new folder and a text file inside that folder	var dir = @"D:\New folder\log";  // folder location\n\nif(!Directory.Exists(dir))  // if it doesn't exist, create\n    Directory.CreateDirectory(dir);\n\n// use Path.Combine to combine 2 strings to a path\nFile.WriteAllText(Path.Combine(dir, "log.txt"), "blah blah, text");	0
8315171	8315154	Get the largest key in a dictionary	myDictionary.Keys.Max();	0
23284142	23284106	Retrieving the value from the database and assigning it to different textboxes having a delimeter in it	string t = "a$b$c$d";\n\nstring[] temp  = t.Split('$');\n\ntxt1.Text = temp[0] !=null ? temp[0] : "" ;	0
32147227	32137106	Is it possible to add a Mobile Service to Windows Azure Subscription programmatically	azure mobile create "service-name" "server-admin" "server-password	0
13246444	13237505	How do I access a .net resource for an IKVM-ported java library	var asm = Assembly.GetExecutingAssembly();\nvar stream = asm.GetManifestResourceStream("FeatureExtraction.StanfordNLP_Models.englishPCFG.ser.gz");\nvar inp = new ikvm.io.InputStreamWrapper(stream);\nvar x = new java.io.ObjectInputStream(inp);	0
1303860	1303852	How can one set up a thread in C# to only execute when CPU is idle?	Thread thread = Thread.CurrentThread;\nthread.Priority = ThreadPriority.Lowest;	0
11637695	11637644	Is there a way to execute a block of code during any uncaught exception?	You can use \n\n    try\n    {\n\n    }\n    catch(Exception ex)\n    {\n      //your treatment does not contain throw ex.\n      //mute exception in order to not change state\n    }\n\nYou can use this in your webform or in your gloabl.asax in Application_Error (in order to centralize exception treatment)	0
4379233	4379158	Can you pass an enity-framework table/collection as a parameter into a function (asp.net/C#)	public void LoadDropDownList<T>(DropDownList dropDown, ObjectSet<T> table, \n    bool isNew, int otherId)\n{\n    // Do something\n}	0
1678798	1660242	stop current thread until input is received from another window wpf C#	secondRibbonWindow.showDialog();	0
31594731	31593016	Call stored procedure in a Linq-to-Entities query	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace EF_SP\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            using (var context = new NorthwindEntities())\n            {\n                var results = context.GetSalesByCategory("Seafood", "1998");\n\n                foreach (var result in results)\n                    Console.WriteLine("{0} {1}", result.ProductName, result.TotalPurchase);\n            }\n\n            Console.WriteLine("Press any key. . .");\n            Console.ReadKey(true);\n        }\n    }\n}	0
2078081	2077981	Cut files to clipboard in C#	byte[] moveEffect = new byte[] {2, 0, 0, 0};\nMemoryStream dropEffect = new MemoryStream();\ndropEffect.Write(moveEffect, 0, moveEffect.Length);\n\nDataObject data = new DataObject();\ndata.SetFileDropList(files);\ndata.SetData("Preferred DropEffect", dropEffect);\n\nClipboard.Clear();\nClipboard.SetDataObject(data, true);	0
16888650	16888597	How do I select XElements by their XText Value?	var elements = this.Descendants("descriptor")\n                   .Where(d => d.Element("content").Attribute("name") != null &&\n                               d.Descendants("foo").Any(x => (string) x.Element("bar") == "someValue")))\n                   .ToList();	0
867787	867785	How can I ease the pain of initializing dictionaries of Lists in C#?	foreach (DataRow dr in ds.Tables[0].Rows)\n{\n    Foo.GetValueOrCreateDefault( dr["Key"] ).Add( dr["Value"].ToString() )\n}	0
29729829	29729684	Format decimal number with custom amount of digits after comma	public static string FormatDecimal(this decimal value, int decimalSeparator = 2)\n    {\n        return  value.ToString(string.Format("0.{0}", new string('0', decimalSeparator)));\n    }	0
10293893	10293874	Button click in web application with ASP.NET and C#	public void ButtonClick(Object sender, EventArgs e)\n{\n    Response.Redirect("~/asdfg.aspx");\n\n}	0
17447152	17446933	C# Reading particular values in a string	Mytext.Substring(Mytext.indexof("totalResults="),7);	0
16049383	16049102	how to assign DbEntities object to my model object in EF Database first	ViewStudentDetail.Student = DbAccess.StudentDetails.FirstOrDefault(student => student.Username == username);	0
16436892	16436785	How to update related tables in entity-framework?	public static int UpdateTour(Tour tour)\n{\n   using (var context = new aisatourismEntities())\n     {\n        Tour tUpd = context.Tour.FirstOrDefault(t => t.Id == tour.Id);\n          if (tUpd != null)\n            {\n                tUpd.Title = tour.Title;\n                tUpd.TourPlan.Id= tour.TourPlan.Id;\n                tUpd.TourPlan.TourId= tour.TourPlan.TourId;\n                tUpd.TourPlan.Title = tour.TourPlan.Title;\n            }\n          return context.SaveChanges();\n     }\n }	0
12528134	12527639	c# how do i make my list 1 based rather than 0 based	var tb = textBoxList;\n                                    int newDef = def - 1;\n                                    tb[newDef].Text = "occupied";	0
18230795	18230651	Design - Log user downloads	public class SimpleHandler : IHttpHandler\n{\n    public bool IsReusable\n    {\n        get { return false; }\n    }\n\n    public void ProcessRequest(HttpContext context)\n    {\n        string fileToServe = context.Request.QueryString["file"];\n\n        if (!string.IsNullOrEmpty(fileToServe))\n        {\n            //Log request here...\n\n            context.Response.ContentType = "content type for your file here";\n            context.Response.WriteFile("~/path/" + fileToServe);\n        }\n    }\n}	0
12619092	12599086	How to tell what permissions a user has to an additional Outlook mailbox	private bool SearchFoldersVisible(RDOStore2 mailbox)\n    {\n        var searchFolders = mailbox.Searches;\n        try\n        {\n            var throwErrorIfNoAccess = searchFolders.Count;\n        }\n        catch (COMException)\n        {\n            return false;\n        }\n        finally\n        {\n            Marshal.ReleaseComObject(searchFolders);\n        }\n        return true;\n\n    }	0
30830551	30830473	How to read last line from output process class?	string lastLine = null;\nwhile (!process.StandardOutput.EndOfStream) \n{\n    lastLine = process.StandardOutput.ReadLine();\n}\n\n//do what you want here with lastLine;	0
3487049	3487028	C++ to C# array declaration	//untested\n[Structlayout]\nstruct Elf32_Ehdr \n{\n  [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]\n  Byte   e_ident[16];   // Magic number and other info\n  Uint16  e_type;       // Object file type\n  ...\n}	0
20069612	20069589	Counting the number of occurrences of every distinct value of a list	var counts = list.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());	0
523677	523669	How to write and send text to mIRC in C#/Win32?	IntPtr mainHandle = FindWindow("mIRC", null);\nIntPtr serverHandle = FindWindowEx(mainHandle, new IntPtr(0), "MDIClient", null);  \nIntPtr chanHandle = FindWindowEx(serverHandle, new IntPtr(0), "mIRC_Channel", null);  \nIntPtr editHandle = FindWindowEx(chanHandle, new IntPtr(0), "richEdit20A", null);\nSendMessage(editHandle, 0x000C, 0, "Hello World");	0
1842319	1842311	Is it possible to build an assembly, and force it to a specific build #?	[assembly: AssemblyVersion("1.0.0.0")]	0
9520350	9507314	encoding and decoding a binary guid in PHP	oldguids=true	0
27158985	27150335	Is there any other approach to set a value to a Property (of an Instance) without using Reflection?	var propertyInfo = MyObject.GetType().GetProperty(fieldName);\nif (propertyInfo != null && propertyInfo.CanRead)\n    propertyInfo.SetValue(MyObject, "Some value", null);	0
20386418	20382320	Using reflection to set a property of a control	Private void SetProperty(Object ctrl, string propertyName, string value)\n    {\n        string name = propertyName.Split('.').First();\n        PropertyInfo property = ctrl.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);\n        if (name != propertyName)\n        {\n            ctrl = property.GetValue(ctrl, null);\n            SetProperty(ctrl, propertyName.Replace(string.Concat(name, "."), string.Empty), value);\n            return;\n        }\n        TypeConverter converter = TypeDescriptor.GetConverter(property.PropertyType);\n        if (converter != null && converter.CanConvertFrom(typeof(String)))\n                property.SetValue(ctrl, converter.ConvertFrom(value), null);\n    }	0
26348731	26348676	C# syntax for new object with if statement for id and string	type = item.Type == 1 ? new TypeMinimal(1, "volunteer") : new TypeMinimal(2, "staff");	0
22027257	22027191	How to get hour from C# DateTime without leading zero?	System.DateTime.Now.ToString("%h")	0
31996369	31996368	Dapper: Multi-Mapping with repeating column names	string sql = "SELECT ID, "\n    + "ERR1 AS ErrorCode, "\n    + "ERR2 AS ErrorCode, "\n    + "ERR3 AS ErrorCode "\n    + "FROM ERR_TB";\n\nList<Entry> entries = connection.Query<Entry, BpcError, BpcError, BpcError, Entry>(sql,\n(entry, e1, e2, e3) =>\n{\n    if (e1 != null)\n        entry.Errors.Add(e1);\n\n    if (e2 != null)\n        entry.Errors.Add(e2);\n\n    if (e3 != null)\n        entry.Errors.Add(e3);\n\n    return entry;\n},\nsplitOn: "ErrorCode, ErrorCode, ErrorCode")\n.ToList();	0
20527997	20527762	How do I delete an entry from an XML file?	string text = lstAnimals.SelectedItem.ToString();\n        string animalName = text.Substring(0, text.IndexOf("is")).Trim();           \n        XDocument xDoc = XDocument.Load("Animals.xml"); //here is your filepath\n        XElement element = (from x in xDoc.Descendants("Animal")\n            where x.Element("Name").Value == animalName  \n            select x).First();\n        element.Remove();\n        xDoc.Save("Animals.xml");\n        lstAnimals.Items.Remove(lstAnimals.SelectedItem);	0
9710576	9709622	StreamReader inside foreach loop of CheckedItems	using(StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.ASCII)){\n    while ((line = reader.ReadLine()) != null)\n    {\n        foreach (String itemChecked in fightsList.CheckedItems)\n       {\n       }\n    }\n}	0
5973641	5973422	WPF ComboBox delayed filtering	private void textBox1_TextChanged(object sender, TextChangedEventArgs e)\n    {\n        if (!tmr.Enabled)\n        {\n            tmr.Enabled = true;\n            tmr.Start();\n        }\n\n\n        TimeSinceType = DateTime.Now;\n\n    }\n\npublic DateTime TimeSinceType { get; set; }\n\nprotected void Load()\n{\n      tmr = new Timer();\n      tmr.Interval = 200;\n      tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);\n}\n\nvoid tmr_Elapsed(object sender, ElapsedEventArgs e)\n{\n    if ((DateTime.Now - TimeSinceType).Seconds > .5)\n    {\n        Dispatcher.BeginInvoke((Action)delegate()\n        {\n            //LoadData();\n            tmr.Stop();\n        });\n    }\n}	0
12303428	11868290	How can I get the current Active Solution Platform name for use in a Visual Studio add-in? (C#)	object[] openProjects = (object[])applicationObject.ActiveSolutionProjects;\nProject activeProject = (Project)openProjects[0];\nstring configurationName = activeProject.ConfigurationManager.ActiveConfiguration.ConfigurationName;\nstring platformName = activeProject.ConfigurationManager.ActiveConfiguration.PlatformName;	0
8438190	8436876	Given a collection object, would like to assign to a local variable of specific type	var x = listObject as IDictionary;\n        if (x != null)\n        {\n            var en = x.GetEnumerator();\n            while(en.MoveNext())\n            {\n                Console.WriteLine(en.Key);\n                Console.WriteLine(en.Value);\n            }\n        }	0
386772	386762	Properly disposing of a DbConnection	public void Dispose()\n{\n    Dispose(true);\n    GC.SuppressFinalize(this);\n}\n\nprotected virtual void Dispose(bool disposing)\n{\n    if (!disposed)\n    {\n        if (disposing)\n        {\n            // Dispose managed resources.\n        }\n\n        // There are no unmanaged resources to release, but\n        // if we add them, they need to be released here.\n    }\n    disposed = true;\n\n    // If it is available, make the call to the\n    // base class's Dispose(Boolean) method\n    base.Dispose(disposing);\n}	0
21217767	21217731	NullReferenceException when creating a list from a ListBox item	// Initialize paragraphList\n        paragraphList = new List<String>();	0
7804379	7803710	how to reload all localized string in a WPF window?	x:Static	0
23891816	23891739	C# String match (result) from .txt file	Messagebox.Show("True, the match is '" + line + "'");	0
17914647	17875636	C# IOS Set event handler to table rows	public override bool FinishedLaunching (UIApplication app, NSDictionary options)\n    {\n        this.window = new UIWindow (UIScreen.MainScreen.Bounds); \n        //---- instantiate a new navigation controller \n        this.rootNavigationController = new UINavigationController(); \n        this.rootNavigationController.PushViewController(new MyUITableViewController(), false);\n\n        //---- set the root view controller on the window. the nav \n        // controller will handle the rest\n        this.window.RootViewController = this.rootNavigationController;\n        this.window.MakeKeyAndVisible (); \n        return true;\n    }	0
13391574	13391306	Save images from listview to a folder	img.Save(@"C:\MyImage.jpg", ImageFormat.Jpeg);	0
9261837	9260704	Changing my Domain	//Set the correct format for the AD query and filter\nstring ldapQueryFormat = @"LDAP://" + domainName + ".local/DC=" + domainName + ",DC=local";	0
919836	916296	How can I cycle a USB device from C#?	System.Diagnostics.Process proc = new System.Diagnostics.Process();\n proc.StartInfo.FileName = "DEVCON";\n proc.StartInfo.Arguments = "Remove *usb"*MI_01";\n proc.StartInfo.RedirectStandardError = true;\n proc.StartInfo.RedirectStandardOutput = true;\n proc.StartInfo.UseShellExecute = false;\n proc.Start();	0
25090279	25090105	How can I get all TextBoxes inside of a Custom UserControl?	private IEnumerable<TextBox> FindControls(ControlCollection controls)\n{\n  List<TextBox> results = new List<TextBox>();\n  foreach(var control in controls) \n  {\n     var textBox = control as TextBox;\n     if (textBox != null && textBox.MaxLength > 0)\n     { \n       results.Add(textBox);\n     } \n     else if(textBox == null) \n     {\n       results.AddRange(FindControls(control.Controls));\n     }\n  }\n\n  return results;\n}	0
2898275	2898199	switch linq syntax	var folders = this.bdd.Rights\n                  .Join(this.bdd.Folders,\n                        r => r.RightFolderId,\n                        f => f.FolderId,\n                        (r,f) => new { Outer = r, Inner = f })\n                  .Join(this.bdd.RightSpecs,\n                        r => r.Outer.RightSpecId,\n                        rs => rs.SpecIdRight,\n                        (r,rs) => new { Outer = r, Inner = rs })\n                  .Where(r => r.Outer.Outer.RightUserId == userId)\n                  .Where(r => r.Inner.SpecRead == true)\n                  .Where(r => r.Inner.SpecWrite == true)\n                  .Select(r => r.Outer.Inner);	0
7878498	7878474	c# Regex WWPN validation	([0-9a-f]{2}:){7}[0-9a-f]{2}	0
8297611	8297186	Extracting into named groups parts of a url via Regex	Match result = Regex.Match(str, @"^/find/products/(?<Query>\w*)?/?\n    (?<SubsQuery>with/(?<Subset>\w*))?/?\n    (?<PageQuery>page/(?<Page>\d)?/)?\n    $",\n    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);	0
22592286	22012134	cellendedit event in gridview add row in another gridview?	DataGridViewRow row2 = (DataGridViewRow)dataGridView2.Rows[i].Clone();	0
3790460	3790424	Usage of Oracle binding variables with LIKE in C#	sql = "SELECT somedata FROM sometable WHERE machine LIKE :machineName || '%' ";	0
2183442	2182459	Fastest way to remove chars from string	public static unsafe string StripTabsAndNewlines(string s)\n    {\n        int len = s.Length;\n        char* newChars = stackalloc char[len];\n        char* currentChar = newChars;\n\n        for (int i = 0; i < len; ++i)\n        {\n            char c = s[i];\n            switch (c)\n            {\n                case '\r':\n                case '\n':\n                case '\t':\n                    continue;\n                default:\n                    *currentChar++ = c;\n                    break;\n            }\n        }\n        return new string(newChars, 0, (int)(currentChar - newChars));\n    }	0
23314264	23314206	Writing data to a database not working	command.CommandText = "INSERT INTO [User] (Gender,Name,DOB) VALUES(@Sex,@Name,@DOB)";	0
32589659	32589143	Parsing an IPv6 loopback address to a Uri	var uri = new Uri("http://[::1]:8080");	0
19598437	19502400	C# and serial communication how to flush the device to read same data again?	{ \nmySerialPort.Open();\n        byte[] bytesToSend = StringToByteArray("A00265F9");// correct command to reset READER\n        mySerialPort.Write(bytesToSend, 0, 4);\n}\npublic static byte[] StringToByteArray(string hex)\n        {\n            return Enumerable.Range(0, hex.Length)\n                             .Where(x => x % 2 == 0)\n                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))\n                             .ToArray();\n        }	0
31597735	31596092	Customizing HTML in my custom ValidationSummary extension	public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "")\n{\n    string retVal = "";\n    string errorList = "";\n\n    foreach (var key in helper.ViewData.ModelState.Keys)\n    {\n        retVal = "";\n\n        foreach (var err in helper.ViewData.ModelState[key].Errors)\n        {\n            retVal += "<div class='alert alert-danger'>";\n            retVal += "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>??</button>";\n            retVal += "<i class='icon-remove-sign'></i>";\n            retVal += helper.Encode(err.ErrorMessage);\n            retVal += "</div>";\n            errorList += retVal;\n        }\n\n\n    }\n\n    return errorList.ToString();\n}	0
11117251	11114100	How to return Dataset result from function in Oracle	CREATE OR REPLACE FUNCTION res_set_2(obj_id VARCHAR2)\n   RETURN varchar2 AS\n   my_xml varchar2(32767);\nBEGIN\n\n   SELECT xmlelement("DATASET", xmlagg(\n                       xmlelement("ROW", xmlforest(t1.col1, t1.col2, ..., t2.col1, ...))\n                                      )).getStringVal()\n     INTO my_xml \n     FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id \n    WHERE t2.bankingId=obj_id;\n\n   RETURN my_xml;\nEND;	0
13098329	13071823	Convert Expression from a Textbox to Math Expression in Code Behind	Calculator Cal = new Calculator();\ntxt_LambdaNoot.Text = (Cal.Evaluate(txt_C.Text) / fo).ToString();	0
8098652	8098146	Sorting 3 numbers without branching	int abs (int a) \n{\n    int b = a;\n    b = (b >> (sizeof(int)*CHAR_BIT-1) & 1);\n    return 2 * b * (a) + a; \n}\nint max (int a, int b) { return (a + b + abs(a - b)) / 2; }\nint min (int a, int b) { return (a + b - abs(a - b)) / 2; }\n\n\nvoid sort (int & a, int & b, int & c)\n{       \n   int maxnum = max(max(a,b), c);\n   int minnum = min(min(a,b), c);\n   int middlenum = a + b + c - maxnum - minnum;\n   a = maxnum;\n   b = middlenum;\n   c = minnum;\n}	0
16727154	16722311	NancyFx binding a model to a dynamic type?	dynamic model = this.Bind<DynamicDictionary>();	0
30380104	30379375	How to determine if a cell is empty in a .csv file?	if split[0] != null && split[0] != "" {\n    column.Add(splits[0]);\n}	0
10608046	10608001	How can I delete rows from related tables in EF 4?	CASCADE DELETE	0
32301444	32301276	Unexpected output from checking if mouse within control	var pos = button.PointToClient(Cursor.Position);\nSystem.Diagnostics.Debug.WriteLine(pos);         // Now it is easy\nif (button.ClientRectangle.Contains(pos)) {\n    // etc...        \n}	0
15373262	15373218	Put multiple values in an array	List<sik> input = new List<sik>();\n\nfor (int i = 0; i < 5; i ++)\n{\n    var newInput = new sik();        \n    newInput.skId = securitiesArray[i].skId;\n    newInput.country = securitiesArray[i].country;\n    input.Add(newInput);\n}	0
14839591	14839474	Joining Url and relative file path into valid Uri?	new Uri(new Uri("http://localhost/"), "virtualdirectory\\path\\to\\my\\file.html".Replace("\\","/"));	0
19494052	19493882	How to clear TreeViewItem's Parent property?	TreeView1.Items.Remove(MyTreeViewItem)	0
15140191	15139669	Find a data in richtextBox, I have used the Rich Text format	public void FindAllMatches(string searchText)\n{\n    int start = 0;\n    int increment = searchText.Length;\n    bool complete = false;\n    while (!complete)\n    {\n        start = richTextBox1.Find(searchText, start, RichTextBoxFinds.MatchCase);\n        if (start >= 0) start += increment;\n        else complete = true;\n    }\n}	0
33588521	33587263	Quality drop from 2nd frame GIF Resize Magick.NET	MagickNET.UseOpenCL = false;	0
32325496	32325275	DatePicker in ViewPager	Android.Support.V4.App	0
27618752	25742603	Save changes to a database in Entity Framework 6	using(dbEntity amadeus = new dbEntities())\n{\n    if (entry.Key.ToString() == applicationName)\n    {\n        IRole role = entry.Value;\n        role.StatusChange(userName);\n    }\n}	0
16891773	16891574	Write byte array to storage file in windows phone	StorageFile sampleFile = await myfolder.CreateFileAsync(imagename.ToString(), \n   CreateCollisionOption.ReplaceExisting);\nawait FileIO.WriteBytesAsync(sampleFile, ImageArray);	0
14247707	14242870	Convert C# Matrix to c++ FLOAT*	void myClass::myManagedCPPFunction(Matrix^ matTransform)	0
10182580	10182463	Updating the value of a subItem in a ListViewItem inside a listview c# (Winforms)	if(listView1.SelectedItems != null)\n{\n   ListViewItem item = listView1.SelectedItems[0];\n   item.SubItems[0].Text = "Sister";\n}	0
8727320	8725326	How to make use of AutoScrollbar when drawing contents with GDI+	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        this.AutoScroll = true;\n        this.AutoScrollMinSize = new Size(3000, 1000);\n        this.ResizeRedraw = true;\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);\n        e.Graphics.DrawLine(Pens.Black, 0, 0, 3000, 1000);\n        base.OnPaint(e);\n    }\n}	0
10029486	10029408	Generic extension method for generic list's	public static List<TModel> ToModel<TModel>(this IEnumerable<IEntity> entity) \n    where TModel : IBaseViewModel\n{\n    // magic\n}	0
34289583	34289497	Is there any library like LitJSON for java?	String json = gson.toJson(personA);    \nPerson personB = gson.fromJson(json, Person.class);	0
11523014	11522577	WebClient DownloadFileAsync - How can I display download speed to the user?	mWebClient.DownloadProgressChanged += (sender, e) => progressChanged(e.BytesReceived);\n//...\nDateTime lastUpdate;\nlong lastBytes = 0;\n\nprivate void progressChanged(long bytes)\n{\n    if (lastBytes == 0)\n    {\n        lastUpdate = DateTime.Now;\n        lastBytes = bytes;\n        return;\n    }\n\n    var now = DateTime.Now;\n    var timeSpan = now - lastUpdate;\n    var bytesChange = bytes - lastBytes;\n    var bytesPerSecond = bytesChange / timeSpan.Seconds;\n\n    lastBytes = bytes;\n    lastUpdate = now;\n}	0
20048347	20048172	Loop multiply int to lower int	public int Factorial(int Z)\n{\n    if (Z < 0) then return 0;\n\n    int res = 1;\n    for (int Y = 1; Y <= Z; Y++)\n    {\n        res *= Y;\n    }\n    return res;\n}	0
14703528	14703460	Filtering strings	string cleanData = Regex.Replace(stringtext, @"\[..\]", "");	0
28989809	28989735	How to verify if my text contains a word using regex and C#	bool valid = Regex.IsMatch(input,@"^[a-zA-Z]{3}[0-9]{9}$");	0
19139639	19139257	Change a list of items after its constructed	type Node() as this =\n    let children = new ResizeArray<Node>()\n    let mutable parent : Node = this\n    member this.Parent with get() = parent\n    member this.AddChild(node : Node) =\n       children.Add(node)\n       node.Parent <- this	0
9205348	9205282	Sharing views between controllers without using the Shared folder	return View("~/Views/StudentSearch/SearchView.cshtml", model);	0
28503260	28503189	Can method inheritated from interface return another type that in interface?	interface IObject<T> where T : IObject<T>\n{\n    T GetSomeObject();\n}\n\npublic class ObjectClass : IObject<ObjectClass> { ... }	0
5626240	5625917	Delete a lot of files and sub folders with c# and threads	Directory.Delete(directory, true);	0
4437115	4436982	how to open screen on full screen	Button1.Attributes.Add("onclick","window.open('Default.aspx','','fullscreen=yes')");	0
13537016	13536990	Reading from lines in a txt file, if a box is one part, variable equals second	StreamReader reader = File.OpenText(@"C:\weapons.txt");\nwhile (!reader.EndOfStream)\n{\n    string currentLine = reader.ReadLine();\n    string[] words = currentLine .Split(",");\n    if (this.box_weapon.SelectedItem.ToString()  == words[0])\n    {\n     ammoType = words[1];\n    }\n\n}	0
6680715	6610967	WPF DataGrid - Retain selection when disabling	public class FormMainDataGrid : DataGrid\n    {\n        public FormMainDataGrid() : base() {\n            this.IsEnabledChanged += new DependencyPropertyChangedEventHandler(DataGrid_IsEnabledChanged);\n            this.SelectionChanged += new SelectionChangedEventHandler(DataGrid_SelectionChanged);\n        }\n\n        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs args)\n        {\n            if (this.IsEnabled)\n            {\n                _selectedValue = this.SelectedValue;\n            }\n        }\n\n        private object _selectedValue;\n\n        private void DataGrid_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs args)\n        {\n            this.Dispatcher.BeginInvoke((Action)(() =>\n            {\n                this.SelectedValue = _selectedValue;\n            }), null);\n        }\n    }	0
17308189	17308059	Prevent access to derived classes except via factory	public abstract class ITop {\n    public static ITop MakeMeOne(whatever x) {\n        if(x == something) {\n            return BottomA(x);\n        }\n        else {\n            return BottomB(x);\n        }\n    }\n\n    private class BottomA : ITop {\n        public BottomA(whatever x) {}\n    }\n\n    private class BottomB : ITop {\n        public BottomB(whatever x) {}\n    }\n}	0
18235682	18235528	using value of boolean to display information	Message = isPGUID ? "ParentGuide" : "Guid is not the parent Guid";	0
8378838	8378802	How to try to convert object to double, and if it fails take it as string ?	static void Add(List<object> list, XPathNavigator thisNavigator)\n{\n    string s = thisNavigator.ValueAsString;\n    double d;\n    if(double.TryParse(s, out d))\n    {\n        list.Add(d);\n    }\n    else\n    {\n        list.Add(s);\n    }\n}	0
12823910	12823850	How to find the positive difference between two DateTime in C#	double days = Math.Abs((date1-date2).TotalDays);	0
25886636	25884301	Create instance of a type in another domain without assembly name	public static Object GetInstanceFrom(AppDomain domain, string typeFullName)\n    {\n        Object objectInstance = null;\n\n        var myAssembly = domain.GetAssemblies().Where(w => w.GetTypes().Select(s => s.FullName.ToUpperInvariant()).Contains(typeFullName.ToUpperInvariant())).FirstOrDefault();\n\n        if (myAssembly != null)\n        {\n            var myTypeFromAssembly = myAssembly.GetTypes().Where(w => w.FullName.ToUpperInvariant() == typeFullName.ToUpperInvariant()).FirstOrDefault();\n            if (myTypeFromAssembly != null)\n            {\n                objectInstance = System.Activator.CreateInstance(myTypeFromAssembly);\n            }\n        }\n\n        return objectInstance;\n    }	0
20594582	20594408	get value from gridview(textbox)	protected void ASPxGridView1_CustomColumnDisplayText(object sender,  \n ASPxGridViewColumnDisplayTextEventArgs e)\n{\n    if (e.Column.FieldName == "Column1")\n    {\n        int a= Convert.ToInt32(e.Value).ToString();\n    }\n\n    if (e.Column.FieldName == "Column2")\n    {\n\n        string b= e.Value.ToString();\n    }	0
29311249	29310529	JSON.NET Converter: If a given value is missing use default deserialization	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n      var jToken = JToken.Load(reader);\n      if (jToken.HasValues)\n      {\n        var xmlBlob = jToken[XMLKEY];\n        if (jToken.First.Path == XMLKEY)\n        { \n          var delphiObject = CoreFactory.CrossPlatformProperties.DeserializeDelphiObject(xmlBlob.Value<string>());\n          return delphiObject;\n        }\n      }\n      return serializer.Deserialize(jToken.CreateReader());\n    }	0
29018517	29018354	Getting Started with LightInject	using LightInject;\nusing System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var container = new ServiceContainer();\n            container.Register<IFoo, Foo>();\n            container.Register<IBar, Bar>();\n            var foo = container.GetInstance<IFoo>();\n            foo.DoFooStuff();\n        }\n    }\n\n    public interface IFoo\n    {\n        void DoFooStuff();\n    }\n\n    public class Foo : IFoo\n    {\n        // this property is automatically populated!\n        public IBar MyBar { get; set; }\n\n        public void DoFooStuff()\n        {\n            MyBar.DoBarStuff();\n            Console.WriteLine("Foo is doing stuff.");\n        }\n    }\n\n    public interface IBar\n    {\n        void DoBarStuff();\n    }\n\n    public class Bar : IBar\n    {\n        public void DoBarStuff()\n        {\n            Console.WriteLine("Bar is doing stuff.");\n        }\n    }\n}	0
32134340	32134303	How to stop duplicating code on same page in asp.net	protected void Step02SubmitButton_Click(object sender, EventArgs e)\n{\n     myfunction();\n}           \n\nprotected void Step02PreviousButton_Click(object sender, EventArgs e)\n{\n     myfunction();\n}\n\nprotected void myfunction()\n{\n    Session["Step02AllServices"] = Step02AllServices.Checked;\n     Session["Step02ContentUploading"] = Step02ContentUploading.Checked;\n     Session["Step02ContentLayoutChecking"] = Step02ContentLayoutChecking.Checked;\n     Session["Step02TestingVariousBrowsers"] = Step02TestingVariousBrowsers.Checked;\n     Session["Step02TestingFunctionality"] = Step02TestingFunctionality.Checked;\n     Session["Step02ResponsiveLayouting"] = Step02ResponsiveLayouting.Checked;\n     Session["Step02ResponsiveTesting"] = Step02ResponsiveTesting.Checked;\n}	0
12720234	12720166	List cannot maintain unique elements, but HashSet cannot access via index. How?	public class HashList<T> {\n   private HashSet<T> _hashSet;\n   private List<T> _list;\n\n   public T this[int i]\n   {\n       return _list[i];\n   }\n\n   public void add(T item) \n   {\n       if (_hashSet.add(item))\n          _list.add(item);\n   }\n}	0
2378720	2378542	.NET Object from VB6 without use of regasm.exe?	Sub Main()\n    Dim CORHost As New mscoree.CorRuntimeHost\n    Dim Domain As Object\n    Dim AssemblyFilename As String\n    Dim Classname As String\n    Dim Result As Object\n\n    AssemblyFilename = "mscorlib"\n    Classname = "System.Collections.ArrayList"\n\n    CORHost.Start\n    CORHost.CurrentDomain Domain\n    Set Result = Domain.CreateInstance(AssemblyFilename, Classname).Unwrap()\n\n    Result.Add "test"\n    MsgBox Result.Count\nEnd Sub	0
7976158	7976105	Undesired output from foreach loop and IF statement	StringBuilder sb = new StringBuilder(mainWindow.ChangeTextBox);\nforeach (AddEntry list in addedEntry)\n{\n    sb.AppendLine(list.Type);\n\n    if (list.DisplayType == 1) \n        sb.AppendLine("URL: " + list.URL);\n\n    if (list.DisplayType == 0 || list.DisplayType == 1) {\n        sb.AppendLine("User Name: " + list.UserName);\n        sb.AppendLine("Password: " + list.Password);\n    }\n\n    if (list.DisplayType == 2) {\n        sb.AppendLine("Software Name: " + list.SoftwareName);\n        sb.AppendLine("Serial Code: " + list.SerialCode);\n        sb.AppendLine("Software Name: " + list.SoftwareName);\n    }\n\n    sb.AppendLine();\n}  \n\nmainWindow.ChangeTextBox = sb.ToString();	0
10400294	10388209	How to bind XML data to RadioButtonList using XmlDocument?	XmlNodeList xNodeList = xAddress.DocumentElement.SelectNodes("response");\n\nvar addrs = new List<KeyValuePair<string, string>>();\n\nforeach (XmlNode xNode in xNodeList)\n{\n   var xAddr = xNode["address"].InnerText;\n   var xLatLng = xNode["latlng"].InnerText;\n   addrs.Add(new KeyValuePair<string, string>(xAddr, xLatLng));   \n}\nrbMultiAdd.DataSource = addrs;\nrbMultiAdd.DataTextField = "Key";\nrbMultiAdd.DataValueField = "Value";\nrbMultiAdd.DataBind();	0
3863937	3863817	Define class-implementations in an interface	interface IClass1\n{\n    String S { get; set; }\n\n    Class2 SubClass { get; set; }\n}	0
20855764	20855283	Detect HTML5 in c#	var elem = document.createElement("input");\nelem.setAttribute("multiple", "true");\nvar isMultipleSupported = elem.multiple === true;\n\nif (isMultipleSupported)\n  ...\nelse\n  ...	0
5092826	5092584	How to pass value in a constructor to enable or disable a button in asp.net control?	[BrowsableAttribute(True)]\n[DefaultValue("true")]\npublic bool IsNew { get; set; }\n\nprotected void Page_Init(object sender, EventArgs e)\n{\n    btnAdd = IsNew;\n}	0
34299127	34272557	C# Generic parameter from a string variable	MethodInfo method = typeof(class).GetMethod("Populate");\nmethod = method.MakeGenericMethod(p.PropertyType);\n_val = method.Invoke(class, new object[] { _prms });	0
1294879	1294816	Access linkbutton from datalist on pageload with c# asp.net	void dlRecommendations_ItemDataBound(object sender, DataListItemEventArgs e)\n    {\n        var link = e.Item.FindControl("lnkEdit") as LinkButton;\n        if (link != null)\n        {\n            link.Enabled = UserHasRight;//if user has right then enabled else disabled\n        }\n    }	0
20787448	20787349	Convert byte* to byte[] in c#	String myStr;\nfixed (byte* pImageName = outBuffer)\n{\n   var convertedArray = new byte[outLength];\n\n   System.Runtime.InteropServices.Marshal.Copy(new IntPtr(pImageName), convertedArray , 0, outLength);\n\n   myStr = System.Text.Encoding.UTF8.GetString(convertedArray);\n}	0
28894958	28858446	How to know that Active Directory exists with only ip address?	...\nusing System.DirectoryServices.Protocols;\n...\n\nstring server = "192.168.1.1";\n\nusing (LdapConnection ldapConnection = new LdapConnection(server))\n{\n    ldapConnection.AuthType = AuthType.Anonymous;\n\n    SearchRequest request = new SearchRequest(null, "(objectclass=*)",\n          SearchScope.Base, "defaultNamingContext");\n\n    SearchResponse result = (SearchResponse)ldapConnection.SendRequest(request);\n\n    if (result.Entries.Count == 1)\n    {\n        Console.WriteLine(result.Entries[0].Attributes["defaultNamingContext"][0]);\n    }\n}	0
23503388	23503323	how to print jagged array in text file	using (StreamWriter st = new StreamWriter(filePath))\n{\n   for (int row = 0; row < arr.GetLength(0); row++)\n   {\n       for (int col = 0; col < arr.GetLength(1); col++)\n       {\n            st.Write(arr[row,col] + " ");\n       }\n       st.WriteLine();\n   }\n}	0
10725893	10725633	windows form keeping datagridview up to date	private void Form1_Load(object sender, EventArgs e)\n    {\n        Timer timer = new Timer();\n        timer.Interval=1000; // time in milliseconds\n        timer.Tick+=new EventHandler(timer_Tick);\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n       //Do your update here\n    }	0
30105091	30075351	How to delete an item from this listbox?	foreach(int selected in RequestedSelected)\n{\n   RegimeItem item = model.RequestedExercises.FirstOrDefault(i => i.RegimeItemID == selected);\n   if(item != null)\n   {\n      User user = db.Users.Find(id);\n      user.RegimeItems.Remove(item);\n   }\n}	0
21977231	21977144	Launching an application with an URI from winform	var url = "myprotocl://10.0.0.123";\nvar psi = new ProcessStartInfo();\npsi.UseShellExecute = true;\npsi.FileName = url; \nProcess.Start(psi);	0
1228686	1228539	How to bind list to dataGridView?	...\nprivate void BindGrid()\n{\n    gvFilesOnServer.AutoGenerateColumns = false;\n\n    //create the column programatically\n    DataGridViewCell cell = new DataGridViewTextBoxCell();\n    DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()\n    {\n        CellTemplate = cell, \n        Name = "Value",\n        HeaderText = "File Name",\n        DataPropertyName = "Value" // Tell the column which property of FileName it should use\n     };\n\n    gvFilesOnServer.Columns.Add(colFileName);\n\n    var filelist = GetFileListOnWebServer().ToList();\n    var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList\n\n    //Bind BindingList directly to the DataGrid, no need of BindingSource\n    gvFilesOnServer.DataSource = filenamesList \n}	0
21098520	21045501	Copy existing data base (storage file) to storage folder	using System.Reflection;\n\n\npublic MainPage()\n{\n  this.InitializeComponent();\n  Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;\n  Stream stream = asm.GetManifestResourceStream("YourNamespace.filename.extension");\n\n\n  ConvertToFileAndCopyToLocalDirectory(stream);\n}	0
21949434	21874648	Issue with Object Context Translate method for parent child object	var preCalPolViewMap = new DataReaderAutoMap<PreCalPolView>();\n            var premiumCalculationASViewMap = new DataReaderAutoMap<PremiumCalculationASView>()\n                    .Specify((s, t) => t.PreCalPolView = preCalPolViewMap.Create(objReader));\n            result = premiumCalculationASViewMap.CreateList(objReader);	0
27052589	27052227	How to extract last 5 digits from a link	string someUrl = "www.mywebsite.com?agent_id=12345";\nvar match = Regex.Match(someUrl, "[?&]agent_id=(\d+)";\n\nif (match.Success) {\n    Session["agent_id"] = match.Groups[1].Value;\n}	0
1108254	1107462	Expose multiple collections as a single collection	public class CrossTab\n{\n    public VariableList Variables { get; set; }\n\n    public ObservableCollection<VariableCode> ShownCodes\n    {\n        get\n        {\n            return new ObservableCollection<VariableCode>(\n                Variables\n                    .SelectMany(variable => variable.VariableCodes)\n                    .Where(code => code.IsShown)\n                );\n        }\n    }\n}	0
34068144	34067955	Issue with building ASP.NET 5 library	"frameworks": {\n    "dnx451": { },\n    "dnxcore50": { } <-- remove this line\n},	0
14966234	14966178	Using LINQ for CSV data	TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv");\nparser.TextFieldType = FieldType.Delimited;\nparser.SetDelimiters(",");\nwhile (!parser.EndOfData) \n{\n    //Processing row\n    string[] fields = parser.ReadFields();\n    foreach (string field in fields) \n    {\n        //TODO: Process field\n    }\n}\nparser.Close();	0
9606634	9606477	How to make list from datagridview?	var data = \n    dataGridView.Rows.Cast<DataGridViewRow>()\n    .Select(\n        row =>\n            new\n            {\n                 Col5 = row.Cells[Column5.Index].Value,\n                 Col6 = row.Cells[Column6.Index].Value,\n            })\n    .ToList();	0
10998198	10998150	Getting part of the filename C#	string sData = "dayhappy_02_02345.csv";\nstring[] sArr = sData.split('_');\n\nstring sPart1 = sArr[1];\nstring sPart2 = sArr[2];	0
22028889	22027392	Queue that stores User's entered Array and displays it	public class Program\n{\n    static void Main(string[] args)\n    {\n        (new Program()).Ask();\n    }\n\n    private void Ask()\n    {\n        string history = "";\n\n        while (true)\n        {\n            Console.Write("Len > ");\n            int len = int.Parse(Console.ReadLine());\n\n            int[] arr = new int[len];\n            for (int i = 0; i < len; i++)\n            {\n                Console.Write("El{0} > ", i);\n                arr[i] = int.Parse(Console.ReadLine());\n            }\n\n            Console.WriteLine();\n            string str = string.Join(",", arr);\n            Console.WriteLine("Arr > {0}", str);\n\n            Console.WriteLine("His > {0}", history);\n            history += string.Format("[{0}] ", str);\n\n            Console.WriteLine("Again?");\n            if (Console.ReadLine().Length == 0)\n                break;\n            Console.WriteLine();\n        }\n    }\n}	0
5172961	5172748	C# - Capture spacebar press during console application execution	private static StatusObject Status;\n\npublic static void main(params string[] args)\n{\n   var thread = new Thread(PerformProcessing);\n   Status = new StatusObject();\n   thread.Start(Status);\n\n   while(thread.IsAlive)\n   {\n      if(keyAvailable)\n         if(Console.ReadKey() == ' ')\n            ShowStatus(Status);\n\n      //This is necessary to ensure that this main thread doesn't monopolize\n      //the CPU going through this loop; let the background thread work a while\n      Thread.Yield();\n   }\n\n   thread.Join();\n}\n\npublic void PerformProcessing(StatusObject status)\n{\n   //do your file parsing, and at significant stages of the process (files, lines, etc)\n   //update the StatusObject with vital info. You will need to obtain a lock.\n}\n\npublic static void ShowStatus(StatusObject status)\n{\n   //lock the StatusObject, get the information from it, and show it in the console.\n}	0
1586064	1582510	Get pathes of assemblies used in Type	public static IEnumerable<string> GetReferencesAssembliesPaths(this Type type)\n{           \n    yield return type.Assembly.Location;\n\n    foreach (AssemblyName assemblyName in type.Assembly.GetReferencedAssemblies())\n    {\n        yield return Assembly.ReflectionOnlyLoad(assemblyName.FullName).Location;\n    }\n}	0
3815012	3814940	How to detect if my site is in Facebook iframe or standalone site	if ( top === window )\n{\n  // page is not framed\n}	0
14390665	14364864	There exists both implicit conversions from 'float' and 'float' and from 'float' to 'float'	float currElbowAngle = LeftArm ? 0.0f + Elbow.transform.localRotation.eulerAngles.y \n                               : 360f - Elbow.transform.localRotation.eulerAngles.y	0
15168066	15168001	Using Moq for a repository interface method?	IRepository Repository { get; }	0
5868931	5868790	Saving content of a treeview to a file and load it later	public static void SaveTree(TreeView tree, string filename)\n    {\n        using (Stream file = File.Open(filename, FileMode.Create))\n        {\n            BinaryFormatter bf = new BinaryFormatter();\n            bf.Serialize(file, tree.Nodes.Cast<TreeNode>().ToList());\n        }\n    }\n\n    public static void LoadTree(TreeView tree, string filename)\n    {\n        using (Stream file = File.Open(filename, FileMode.Open))\n        {\n            BinaryFormatter bf = new BinaryFormatter();\n            object obj = bf.Deserialize(file);\n\n            TreeNode [] nodeList = (obj as IEnumerable<TreeNode>).ToArray();\n            tree.Nodes.AddRange(nodeList);\n        }\n    }	0
11763699	11671319	Telerik RadGauge + Data Binding	Binding value = new Binding();         \nvalue.Source = (chart.Chart as GuiAnalogQueue);         \nvalue.Path = new PropertyPath("AnalogValue");\nneedle.SetBinding(Needle.ValueProperty, value);	0
2150643	2109502	Can I specify a range with the IntegerValidator attribute on a custom ConfigurationSection?	[ConfigurationProperty("waitForTimeSeconds", IsRequired=true, \n                       DefaultValue="10")]	0
24255289	24254964	Parsing JSON feed using JSON.Net	var json = new WebClient().DownloadString("http://4gp.tw/b036/1402972549560.txt");\nvar obj = JObject.Parse(json);\nvar query =\n    from JObject ev in obj.PropertyValues()\n    from JObject evid in ev.PropertyValues()\n    select new\n    {\n        Description = (string)evid["Description"],\n        OutcomeDateTime = Convert.ToDateTime((string)evid["OutcomeDateTime"]),\n        Teams =\n            from JObject comps in evid["Competitors"]["Competitors"]\n            select (string)comps["Team"],\n    };	0
28547002	28546224	Get fixed array values from unsafe struct	public static double[] CopyFixedDoubleArray(this Data data)\n{\n    unsafe\n    {\n        return new[] { data.Values[0], data.Values[1], data.Values[2] };\n    }\n}	0
2129834	2129809	Match elements between 2 collections with Linq in c#	string[] collection1 = new string[] { "1", "7", "4" };\nstring[] collection2 = new string[] { "6", "1", "7" };\n\nvar resultSet = collection1.Intersect<string>(collection2);\n\nforeach (string s in resultSet)\n{\n    Console.WriteLine(s);\n}	0
7176368	7146752	How Can I Convert Xaml Code To C# (Setter Property in WPF)	else if (c.Type == typeof(AutoCompleteBox))\n{\n    //var style = new Style(typeof(TextBox));\n    ctrl = new AutoCompleteBox { FontSize = 14, MaxDropDownHeight = 90, Name = c.ControlID };\n    ctrl.TabIndex = c.TabOrder;\n    ctrl.MaxWidth = 200;\n\n    var style = new Style(typeof(TextBox));\n    var binding = new Binding("TabIndex") { ElementName = c.ControlID };\n    var setter = new Setter(TextBox.TabIndexProperty, binding);\n    style.Setters.Add(setter);\n    (ctrl as AutoCompleteBox).TextBoxStyle = style;\n\n    if (c.SpName != null && c.DisplayMember != null)\n    {\n        DataTable dt = sqlHelper.ExecuteSelectProcedure(c.SpName);\n        var cmb = ctrl as AutoCompleteBox;\n        cmb.ItemsSource = dt.AsEnumerable().Select(r => r.Field<string>(c.DisplayMember)).ToList();\n    }\n}	0
3227694	3227597	How do I find the subjectdistinguishedname of a x509 certificate?	Options -> Certificates -> Certificate -> Details -> Subject	0
32753628	32753088	Not getting VS2013 Intellisense for custom config even with schema defined	DotNetConfig.xsd	0
3603636	3603607	ClickOnce, my app crashes Visual C# Express	try/catch	0
9783624	9703003	DataGridView: Apply an edit to all selected rows	DataGridViewSelectedRowCollection selected;\n\nprivate void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n{\n    DataGridView dgv = (DataGridView)sender;\n    DataGridViewCell cell = dgv.CurrentCell;\n    if (cell.RowIndex >= 0 && cell.ColumnIndex == 1) // My checkbox column\n    {\n        // If checkbox value changed, copy it's value to all selectedrows\n        bool checkvalue = false;\n        if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true))\n            checkvalue = true;\n\n        for (int i=0; i<selected.Count; i++)\n            dgv.Rows[selected[i].Index].Cells[cell.ColumnIndex].Value = checkvalue;\n    }\n\n    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n}\n\nprivate void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n{\n    selected = dataGridView1.SelectedRows;\n}	0
32735484	32735110	Check if row exist in SQLite PCL UWP	MovieID movie = (from p in db.Table<MovieID>() \n            where p.ID == searchId \n            select p).FirstOrDefault();\nif(movie !=null)\n{\n//movie exists\n}\nelse\n{\n  //movie do not exists\n}	0
7830538	7830441	How to convert an action to a defined delegate of the same signature?	static void Main(string[] args)\n{\n\n    Program p = new Program();\n    p.SomeMethod();\n}\n\npublic class Fruit\n{ }\n\npublic class Apple : Fruit { }\n\npublic delegate void FruitDelegate<in T>(T f) where T : Fruit;\n\nclass Test\n{\n    public static void Notify<T>(FruitDelegate<T> del)\n        where T : Fruit, new()\n    {\n        T t = new T();\n        del.DynamicInvoke(t);\n    }\n}\n\nprivate void AppleHandler(Apple apple)\n{\n    Console.WriteLine(apple.GetType().FullName);\n}\n\npublic void SomeMethod()\n{\n    FruitDelegate<Apple> del = new FruitDelegate<Apple>(AppleHandler);\n    Test.Notify<Apple>(del);\n}	0
10981517	3954848	How to avoid persistence logic in domain model?	public class Group\n{\n    private Collection<Person> _persons;\n\n    public Group(Collection<Person> persons)\n    {\n        if (persons == null)\n            throw new ArgumentNullException("persons");\n\n        _persons = persons;    \n    }\n\n    public IEnumerable<Person> Persons\n    {\n        get { return _persons; }\n    }\n\n    public void AddPerson(Person p)\n    {\n        if (p == null)\n            throw new ArgumentNullException("p");\n\n        _persons.Add(p);\n        DoSideAffect();\n    }\n}\n\npublic class GroupRepository\n{\n    public Group FindBy(Criteria c)\n    {\n        // Use whatever technology (EF, NHibernate, ADO.NET, etc) to retrieve the data\n\n        var group = new Group(new Collection<Person>(listOfPersonsFromDataStore));\n\n        return group;\n    }\n\n    public void Save(Group g)\n    {\n        // Use whatever technology to save the group\n        // Iterate through g.Persons to persist membership information if needed\n    }\n}	0
13987946	13951534	unmanaged array marshaling and size as pointer	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]\ndelegate int StreamRead(IntPtr ptr, byte* buffer, int* bytes);	0
22856417	22851485	Upgrading .NET from 3.5 to 4.5 breaks dependencies	var obj = new Envox.ADXVoice.ADXVoice();	0
7597841	7585700	Add data to sharepoint form programmatically on client	string strBatch = "<Method ID='1' Cmd='Update'>" + \n    "<Field Name='ID'>141</Field>" +\n    "<Field Name='Description'>My new Description</Field></Method>" +\n    "</Method>"; \n\nXmlDocument xmlDoc = new System.Xml.XmlDocument();\n\nSystem.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");\n\nelBatch.SetAttribute("OnError","Continue");\nelBatch.SetAttribute("ListVersion","1");\nelBatch.SetAttribute("ViewName",\n    "0d7fcacd-1d7c-45bc-bcfc-6d7f7d2eeb40");\n\nelBatch.InnerXml = strBatch;\n\nXmlNode ndReturn = WssLists.UpdateListItems("List_Name", elBatch);	0
1771457	1771414	return html from a web service in asp.net	[WebMethod]\npublic string GetHTML()\n{\n    return "<HTML><TITLE>...";\n}	0
31506313	31503102	Injection and parameterless constructor in WPF	private RemindersListing()\n{\n    InitializeComponent();\n}\n\npublic RemindersListing(IReminderReadLogic reminderReadLogic) : this()\n{\n    ...\n\n}	0
8143093	8142735	Function Declarations with Generics in C#	public static string MultiWhereToString(IEnumerable<ICondition<T>> whereConditions)	0
3253547	3253020	Splash screen doesn't hide - using Microsoft.VisualBasic library	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;\n\nnamespace WindowsFormsApplication1\n{\n    static class Program\n    {\n        [STAThread]\n        static void Main(string[] args)\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            new MyApp().Run(args);\n        }\n    }\n    public class MyApp : WindowsFormsApplicationBase\n    {\n        protected override void OnCreateSplashScreen()\n        {\n            this.SplashScreen = new Form2();\n        }\n        protected override void OnCreateMainForm()\n        {\n            // Do your initialization here\n            //...\n            System.Threading.Thread.Sleep(5000);  // Test\n            // Then create the main form, the splash screen will automatically close\n            this.MainForm = new Form1();\n        }\n    }\n}	0
20301991	20301915	Sort text file array by date in C#	x.Split(',')	0
16698285	16680400	Reading only numbers in CSV file C#	StreamReader reader = new StreamReader(@"F:\BP1.csv");\n        List<double> numbers = new List<double>();\n        double buffer = 0;\n\n        while (!reader.EndOfStream)\n        {\n            string line = reader.ReadLine();\n            string[] tokens = line.Split(',');\n\n            foreach (string s in tokens)\n            {\n                if (double.TryParse(s, out buffer))\n                    numbers.Add(buffer);\n            }\n        }\n\n        foreach (double d in numbers)\n            Console.WriteLine(d.ToString());\n        reader.Close();	0
13035630	13035608	C# Getting the focus on a button / making it active	private void picStart_Click(object sender, EventArgs e)\n{\n  timer1.Start();\n  picBreak.Visible = true;\n  picStart.Visible = false;\n  picBreak.Focus(); // Focus picBreak here?\n}	0
12114788	12113703	How to redirect in a base controller's OnActionExecuting method	base.OnActionExecuting(filterContext);\nif (filterContext.Result != null) {\n  return; // something got short-circuited\n}	0
32826078	32822367	Format Exception Raises When Converting Simple Numeric String to Int in C#	string date = "9/28/2015 12:00:00 AM"; // In My Code, This Var Contain Unseen Unicode Char.\n    var cleanDate = new string(date.Where(c => char.IsNumber(c) || char.IsPunctuation(c) || char.IsWhiteSpace(c) || char.IsLetter(c)).ToArray());\n    DateTime date = DateTime.ParseExact(cleanDate, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);	0
18471267	18471189	Deleting a row completely from a dataset	ds.AcceptChanges()	0
26931440	26929153	C# Serial communcation with arduino	serial.DtrEnable = true;\n        serial.RtsEnable = true;	0
419063	419019	Split List into Sublists with LINQ	public static List<List<object>> Split(List<object> source)\n{\n    return  source\n        .Select((x, i) => new { Index = i, Value = x })\n        .GroupBy(x => x.Index / 3)\n        .Select(x => x.Select(v => v.Value).ToList())\n        .ToList();\n}	0
23778813	23774209	Cannot read text from pdf by ITextSharp in C#	//open document\nDocument pdfDocument = new Document("input.pdf");\n//create TextAbsorber object to extract text\nTextAbsorber textAbsorber = new TextAbsorber();\n//accept the absorber for all the pages\npdfDocument.Pages.Accept(textAbsorber);\n//get the extracted text\nstring extractedText = textAbsorber.Text;\n// create a writer and open the file\nTextWriter tw = new StreamWriter("extracted-text.txt");\n// write a line of text to the file\ntw.WriteLine(extractedText);\n// close the stream\ntw.Close();	0
22313719	22313089	WP8 - C# - Getting object value from Telerik RadPickerBox	this.NewPassword1.Password	0
7473316	7473227	c# set DataContext column values without strongly typing it	Type productType = Type.GetType("PRODUCT");\nvar product = Activator.CreateInstance(productType);\nproductType.GetProperty("PRD_CODE").SetValue(product, "code1");\nproductType.GetProperty("PRD_DESC").SetValue(product, "description1");\n\nType tableType = table.GetType();\ntableType.GetMethod("InsertOnSubmit").Invoke(table, new object[] {product});	0
1510537	1510507	Checkbox: Display depending on value of session?	if( Session["VSSsnap"] != null )\n{\n CheckBox1.Checked = Convert.ToBoolean(Session["VSSsnap"]);\n}	0
25244138	25244078	How to access ContactStore in Shared project	#if WINDOWS_APP\n     //do your logic here\n#else\n     //do windows phone logic here\n#endif	0
32648955	32646477	Windows Universal App SetTitleBar	Window.Current.SetTitleBar(BackgroundElement);	0
18446648	18446440	Rotating 3D primitives around its own axis	(1) Transform the tile back to the origin.\n(2) Perform rotation.\n(3) Transform back to original position.	0
22298772	22297308	Set height and Width of Pop Window on button click which button is reside in that window	function resize_now(){\n    window.moveTo(new_posx,new_posxy);\n    window.resizeTo(newSizeX, newSizeY);\n}	0
7410608	7410579	Linq finding elements and foreach loop	var tablesByCategory = getTables().ToLookup(t => t.CategoryId);\nforeach(var category in categories)\n{\n    category.Tables = tablesByCategory[category.Id];\n}	0
19003534	19003482	How to check if list contains byte array?	bool contains = list.Any(x => x.SequenceEqual(buffer));	0
9721410	9720628	how to set the generated item for itemscontrol in databinding?	protected override DependencyObject GetContainerForItemOverride()\n    {\n        return new ListBoxItem();\n    }	0
20351056	20350770	Check DataGridView for Nulls	for (int i = 0; i < (DataGridView1.Rows.Count); i++)\n  {\n      string colTimeOut = DataGridView1.Rows[i].Cells[4].Value.ToString();    \n      MessageBox.Show(colTimeOut);\n      if (String.IsNullOrEmpty(colTimeOut))\n\n      {\n          OLEDB_Connection.Open();\n          updateCmd.Connection = OLEDB_Connection;\n          updateCmd.CommandText = "INSERT INTO TestDB (TimeOut) VALUES (@TIMEOUT)";\n          updateCmd.Parameters.AddWithValue("@TIMEOUT", varTime);\n          updateCmd.ExecuteNonQuery();\n          OLEDB_Connection.Close();\n\n      }\n\n  else	0
24440703	24439994	Do I need to dispose or destroy custom cursors	private Cursor CustomCursor;\n\nprivate void customCursorButton_Clicked(object sender, EventArgs e)\n{\n    if (CustomCursor == null) CustomCursor = NativeMethods.LoadCustomCursor(@"c:\windows\cursors\aero_busy.ani");\n    this.Cursor = CustomCursor;\n}\n\nprivate void defaultCursorButton_Clicked(object sender, EventArgs e)\n{\n    var prev = this.Cursor;\n    this.Cursor = Cursors.Default;\n    if (prev == CustomCursor) {\n        CustomCursor.Dispose();\n        CustomCursor = null;\n    }\n}\n\nprotected override OnFormClosed(FormClosedEventArgs e) \n{\n    base.OnFormClosed(e);\n    if (CustomCursor != null) CustomCursor.Dispose();\n}	0
13679349	13679326	Result of LINQ.Any to string	var match = stringArray.FirstOrDefault(s => stringToCheck.Contains(s));\nif(match != null) {\n    // match was found\n}	0
6297151	5959328	DateTime Value to null	DateValue(Parameters!BeginDate.Value)	0
11874125	11873228	controlling a physical device via c#	SerialPort port = new SerialPort("COM1", 2400, Parity.None, 8, StopBits.One);\n  port.Open();\n  port.Write(new byte[] {0x00, 0xFF, 0xFF}, 0, 3);\n  port.Close();	0
7462987	7462868	Efficient algorithm for removing an array from another array	public static uint[] RemoveRange(this uint[] source_array, uint[] entries_to_remove)\n{\n    var referenceCount = new Dictionary<uint, int>();\n    foreach (uint n in source_array)\n    {\n        if (!referenceCount.ContainsKey(n))\n            referenceCount[n] = 1;\n        else\n            referenceCount[n]++;\n    }\n    foreach (uint n in entries_to_remove)\n    {\n        if (referenceCount.ContainsKey(n))\n            referenceCount[n]--;\n    }\n    return referenceCount.Where(x => x.Value > 0)\n                         .Select(x => Enumerable.Repeat(x.Key, x.Value))\n                         .SelectMany( x => x)\n                         .ToArray();\n}	0
21335451	21048434	Programmatically checkout a previous checked in file version	Item versionedItem = versionControlServer.GetItem(itemIDs[0], versionNo);	0
30871475	30871062	Verify failing with default / expected parameters	// Arrange\nMock<ExpiryNotifier> target = new Mock<ExpiryNotifier>();\nMock<MailServiceWrapper> mailMock = new Mock<MailServiceWrapper>();\ntarget.Setup(t => t.getMailService()).Returns(mailMock.Object);\n\n// Act\ntarget.Object.notify();\n\n// Assert\nmailMock.Verify(\n            m => m.SendMail(\n                It.IsAny<string>(),\n                It.IsAny<string>(),\n                It.IsAny<string[]>(),\n                It.IsAny<string[]>(),\n                It.IsAny<string[]>(),\n                It.IsAny<string>(),\n                It.IsAny<string>(),\n                It.IsAny<string[]>()\n            ), \n            Times.Exactly(1)\n        );	0
4451172	4450551	How do I receive JSON formated data into C# method argument	public bool TestMethod(object obj1, object obj2)	0
355829	355816	C# mutex - error calling from ASP.NET and console application	MutexSecurity and MutexAccessRule ?	0
6328493	6328455	Is there some uniqueID of each computer, to differentiate one from other?	ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");\ndsk.Get();\nstring volumeSerial = dsk["VolumeSerialNumber"].ToString();	0
4182492	4182471	how to run visual studio without plugin and all third party feature	\Common7\IDE\devenv.exe	0
27603815	27603404	WebClient download string (a few chars page) is so slow	string result;\nusing (var webClient = new System.Net.WebClient())\n{\n    webClient.Proxy=null;\n    String url = "http://bg2.cba.pl/realmIP.txt";\n    result = webClient.DownloadString(url);\n}	0
6155888	6155620	Inserting Entity into SQL Compact 4 Table with Identity column using LINQPad	(from dm in this.Mapping.GetTable(typeof(People)).RowType.DataMembers \n    select new  { dm.DbType, dm.Name, dm.IsPrimaryKey , dm.IsDbGenerated }\n ).Dump();	0
33094834	33094035	Search between two dates in database c#	public void LoadAttendance()\n    {\n        con.Open();\n        cmd = new OleDbCommand("Select * from AttendanceDatabase WHERE EmpName = @EmpName and Date between @d1 and @d2", con);\n        cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text);\n        cmd.Parameters.AddWithValue("@d1", dtDate1.Value.Date);\n        cmd.Parameters.AddWithValue("@d2", dtDate2.Value.Date);\n        DataAdapter = new OleDbDataAdapter(cmd);\n        DataTable = new DataTable();\n        DataAdapter.Fill(DataTable);\n        dgvAttendance.DataSource = DataTable;\n        con.Close();\n    }	0
22798550	22798434	Creating a shared static field in c#	private static void showObjectCounter()\n{\n    Counter val1 = new Counter();\n    Console.WriteLine("Total objects created = {0}", Counter.objectCount());\n    Counter val2 = new Counter();\n    Console.WriteLine("Total objects created = {0}", Counter.objectCount());\n    Counter val3 = new Counter();\n    Console.WriteLine("Total objects created = {0}", Counter.objectCount());\n    Counter val4 = new Counter();\n    Console.WriteLine("Total objects created = {0}", Counter.objectCount());\n}	0
1990677	1990644	Generating thumbnail images in WPF	using (var ms = new MemoryStream(e.Result))\n{\n    var bi = new BitmapImage();\n    bi.BeginInit();\n    bi.StreamSource = ms;\n    bi.DecodePixelWidth = _maxThumbnailWidth;\n    bi.EndInit();\n\n    var encoder = new JpegBitmapEncoder();\n    encoder.Frames.Add(BitmapFrame.Create(bi));\n    using (var fs = new FileStream(filename, FileMode.Create))\n    {\n        encoder.Save(fs);\n    }\n}	0
20776681	20776599	Avoid repetition in code in wcf and ef	IEnumerable<T>	0
20119623	20119285	Change format of unmanaged image byte array	new Bitmap(720, 576, 2160, System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(m_pBuffer));	0
2671280	2671215	What is the most efficient way to detect if a string contains a number of consecutive duplicate characters in C#?	int threshold = 3;\nstring stringToMatch = "thisstringrepeatsss";\nstring pattern = "(\\w)\\" + threshold" + "+";\nRegex r = New Regex(pattern);\nMatch m = r.Match(stringToMatch);\nWhile(m.Success)\n{\n                   Console.WriteLine("character passes threshold " + m.ToString());\n                   m = m.NextMatch();\n}	0
13356690	13354322	How do I calculate a person's age in months/years?	var d1 = new NodaTime.LocalDate(1997, 12, 10);\nvar d2 = new NodaTime.LocalDate(2012, 11, 13);\n\nvar period = NodaTime.Period.Between(d1, d2);\nvar m = period.Months;\nvar y = period.Years;	0
10816644	10816520	Regex to get value of a particular attribute?	string str = "<Button Name = \"btn1\" /><TextBox Name=\"txtbox1\"/>";\nvar attrs = XElement.Parse("<r>"+str+"</r>").Elements().Attributes("Name").Select(a => a.Value);\n\nforeach (var attr in attrs) Console.WriteLine(attr);	0
4276875	4276816	Manipulating XML names and values from file in C#	using System;\nusing System.Linq;\nusing System.Xml.Linq;\nusing System.Xml.XPath;\n\nclass Program\n{\n    static void Main()\n    {\n        var values = from field in XDocument.Load("test.xml")\n                          .XPathSelectElements("//CP[@name='My Messages']/field")\n                     where field.Attribute("name") != null\n                     select field.Attribute("name").Value;\n        Console.WriteLine("total values: {0}", values.Count());\n        foreach (var value in values)\n        {\n            Console.WriteLine(value);\n        }\n    }\n}	0
16049450	16049274	reading same element but different value	using System.Xml;\nusing System.IO;\nusing System.Text;\nusing System;\n\n public class Example\n{\n   public static void Main()\n   {\n        XmlDocument xmlDoc= new XmlDocument(); \n\n        try {\n            xmlDoc.Load("files.xml"); \n        }catch(System.Xml.XmlException e){\n            Console.WriteLine(e);   \n        }\n\n        XmlNodeList defs = xmlDoc.GetElementsByTagName("File");\n\n        for (int i = 0; i < defs.Count; i++)\n        {\n            string fn = defs[i].Attributes["FileName"].Value;\n            string fh = defs[i].Attributes["FileHash"].Value;\n            Console.WriteLine("File:  " + fn + "\tHash:  " + fh);\n        }  \n    }\n}	0
22119926	22119067	MultiThreading in windows froms C#	Thread BackgroundThread = new Thread\n(\nnew ThreadStart(() =>\n{\n    //Fetch data here\n    GridCustomerList.BeginInvoke(\n     new Action(() =>\n     {\n         //Set DataSource here\n     }\n     ));\n}\n\n));	0
32104537	32104337	Adding Stuff into a Gridview with a For-Loop	for(int j = 0;  j < this.img16x16.Images.Count; j++)\n{\n    row = new DataGridViewRow();\n    //Add first cell and its data to the variable "row"\n    //Size changes\n    //Add second cell and its data to the variable "row"\n\n    //Add "row" to the grid:\n    dataGridView1.Rows.Add(row);\n}	0
7443103	7428762	Two way databinding in ASP.NET	public List<Income> AdditionalIncomeList \n        {\n            get { return ViewState["AdditionalIncome"] as List<Income>; }\n            set { ViewState["AdditionalIncome"] = value; }\n        }                \n            foreach (RepeaterItem item in AddIncomeSources.Items)\n            {\n                var amount = (TextBox)item.Controls.Cast<Control>().First(c => c.ID == "Amount");\n                var document = (DropDownList)item.Controls.Cast<Control>().First(c => c.ID == "Document");\n                AdditionalIncomeList[item.ItemIndex].Amount = amount.Text.ToDouble();\n                AdditionalIncomeList[item.ItemIndex].IncomeDocument = document.SelectedValue;\n            }\n            AddIncomeSources.DataSource = AdditionalIncomeList;\n            AddIncomeSources.DataBind();	0
6060326	6059786	Using the php engine inside a c# application	string code = "echo 'test';";\n\nSystem.Diagnostics.Process ProcessObj = new System.Diagnostics.Process();\nProcessObj.StartInfo.FileName = "php-win.exe";\nProcessObj.StartInfo.Arguments = String.Format("-r \"{0}\"", code);\nProcessObj.StartInfo.UseShellExecute = false;\nProcessObj.StartInfo.CreateNoWindow = true;\nProcessObj.StartInfo.RedirectStandardOutput = true;\nProcessObj.Start();\nProcessObj.WaitForExit();\nstring Result = ProcessObj.StandardOutput.ReadToEnd();\nMessageBox.Show(Result);	0
2191191	2191120	.NET DateTime to SqlDateTime Conversion	var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");	0
4658567	4658305	How to determine that one array is a part of another one?	int FindIndexOfSeq<T>(byte[] src, byte[] tag)\n{\n    Int32 tagCount = tag.Count();            \n\n    // If `tag` is not empty and `src` contains `tag`\n    if (tagCount > 0 && src.Intersect(tag).Count() == tagCount)\n    {\n        // Find index of first element in `tag`\n        Int32 tagStartIndex = Array.IndexOf(src, tag.First());\n\n        // Get the matching slice of `tag` from `src`\n        var newSrc = src.Skip(tagStartIndex).Take(tag.Count()).ToList();\n\n        // Zip them together using their difference\n        var sum = Enumerable.Zip(tag, newSrc, (i1, i2) => Convert.ToInt32(i2 - i1)).Sum();\n\n        // If total of their differences is zero, both sequences match\n        if (sum == 0)\n        {\n            // return starting index of `tag` in `src`\n            return tagStartIndex;\n        }\n    }\n\n    // return `Not Found`\n    return -1;\n}	0
11738238	11723265	Monitor folder with FileSystemWatcher fails after first time	Watcher = new FileSystemWatcher(ftpFolder, "*_finish.txt");	0
3135917	2323238	Setting up Axiom3D (or finding a 2d C# openGL engine)	cd C:\axiom3d\samples <-- or where ever it's actually installed\nsample1.exe <-- or what ever it's actually called	0
31378209	31377358	Selenium don't run ExecuteScript change option	IJavaScriptExecutor js = browserToRun as IJavaScriptExecutor;\n js.ExecuteScript("$('#ddlAcounts').val('123').trigger('change')");	0
21811865	21811645	filter data based on day, week and month	Week = new State() { \n    Download = db.Download.Where(x => DbFunctions.DiffDays(DbFunctions.TruncateTime(x.Time), Day) <= 7).Count(), \n    Visit = db.Visit.Where(x => DbFunctions.DiffDays(DbFunctions.TruncateTime(x.Time), Day) <= 7).Count() }	0
21078543	21076578	Unity - Help wanted with meshes using c#	Mesh mesh = GetComponent<MeshFilter>().sharedMesh;\nVector3[] vertices = mesh.vertices;\nint[] triangles = mesh.triangles;\n...	0
34371196	34356907	CRm Dynamics 2013 How to change the colour of Chart bars based on Owner	isVisibleInLegend="false"	0
8240918	8240877	syntax in LINQ IEnumerable<string>	rep.GetIp()\n   .Where(x => x.CITY == CITY)\n   .GroupBy(y => o.Fam)\n   .Select(z => new IpDTO\n                    {\n                        IId = z.Key.Id,\n                        IP = z.Select(x => x.IP).Distinct()\n                    })\n   .SelectMany(item => item.IP)\n   .ToList()\n   .ForEach(PAINTIP)	0
21630087	21629933	card matching game	int[] Cards = new int[16] {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8};	0
150334	150213	How do I use LINQ to query for items, but also include missing items?	if (!dailyCountList.Any())\n      return;\n\n  //make a dictionary to provide O(1) lookups for later\n\n  Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime);\n\n  DateTime minDate = dailyCountList[0].EventDateTime;\n  DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime;\n\n  int DayCount = 1 + (int) (maxDate - minDate).TotalDays;\n\n  // I have the days now.\n  IEnumerable<DateTime> allDates = Enumerable\n    .Range(0, DayCount)\n    .Select(x => minDate.AddDays(x));\n\n  //project the days into RegistrationCounts, making up the missing ones.\n  List<RegistrationCount> result = allDates\n      .Select(d => lookup.ContainsKey(d) ? lookup[d] :\n          new RegistrationCount(){EventDateTime = d, Count = 0})\n      .ToList();	0
20083745	19948535	How to pass parameter to the constructor of the XAML-Page	public sealed partial class Page2 : Page\n{\n    public Page2()\n    {\n        this.InitializeComponent();\n    }\n\n    protected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n        var p3 = new Page3(e.Parameter);\n        // do something\n        base.OnNavigatedTo(e);\n    }\n}\n\npublic sealed partial class Page3 : Page\n{\n    public Page3(object parameter)\n        : base()\n    {\n        this.NavigationCacheMode = NavigationCacheMode.Required;\n        this.InitializeComponent();\n    }\n}	0
4407715	4407631	Is there Windows system event on active window changed?	hEvent = SetWinEventHook(EVENT_SYSTEM_FOREGROUND , \n    EVENT_SYSTEM_FOREGROUND , NULL, \n    WinEventProcCallback, 0, 0, \n    WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);\n\n.......\n\nVOID CALLBACK WinEventProcCallback ( HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)\n{\n    /* your code here */\n}	0
5198214	5187153	Can a Console Application reference its .exe.config if the .config is in another folder?	Dim fileMap As ExeConfigurationFileMap = New ExeConfigurationFileMap()\n\nfileMap.ExeConfigFilename = "....../AppName.config"\n\nDim externalConfig As Configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)\n\nDim appS As AppSettingsSection = externalConfig.Sections("appSettings")\n\nDim reportURL As String = appS.Settings("URL").Value\n\nConsole.Writeline(reportURL)	0
31768019	31767758	How to test or work with DisconnectedItem on ListView in VS2010?	BindingOperations.DisconnectedSource	0
8438979	8438786	Calling an async method from a non-async method	static Task<string> PrepareAwaitable(int x)\n{\n    return Task.Factory.StartNew<string>(() =>\n    {\n        return "Howdy " + x.ToString();\n    });\n}	0
30252048	30242290	FileDescriptora Missing Characters	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic sealed class FILEGROUPDESCRIPTORA\n{\n    public uint cItems;\n    public FILEDESCRIPTORA[] fgd;\n}	0
15228911	15228845	How to connect to a running instance of outlook from C#	System.Runtime.InteropServices.Marshal.GetActiveObject()	0
330350	330346	C# read a JPEG from file and store as an Image	Image i = Image.FromFile("image.jpg");	0
11713190	11703719	How do I get shapes in a swimlane shape object from visio automation?	public class ShapeWrapper\n{\n    public IVisio.Shape Shape { get; set; }\n\n    private List<ShapeWrapper> children = new List<ShapeWrapper>();\n    public List<ShapeWrapper> Children { get { return this.children; } }\n\n    public ShapeWrapper(IVisio.Shape shape)\n    {\n        Shape = shape;\n    }\n}\n\nprivate void FindChildren(ShapeWrapper shapeWrapper, \n                              List<IVisio.Shape> addedShapes)\n{\n    IVisio.Selection children = shapeWrapper\n       .Shape.SpatialNeighbors[\n            (short)IVisio.VisSpatialRelationCodes.visSpatialContain, \n            0,\n            (short)IVisio.VisSpatialRelationFlags.visSpatialFrontToBack];\n\n    foreach (IVisio.Shape child in children)\n    {\n        if (!addedShapes.Contains(child))\n        {\n             //MessageBox.Show(child.Text);\n             ShapeWrapper childWrapper = new ShapeWrapper(child);\n             shapeWrapper.Children.Add(childWrapper);\n\n             FindChildren(childWrapper, addedShapes);\n        }\n    }\n}	0
7927067	7926693	Validation using attributes	public class User\n{\n    [Required(AllowEmptyStrings = false, ErrorMessage = "EmailIsRequired")]\n    public string EmailAddress { get; set; }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var value = "test@test.com";\n\n        var context = new ValidationContext(value, null, null);        \n        var results = new List<ValidationResult>();\n        var attributes = typeof(User)\n            .GetProperty("EmailAddress")\n            .GetCustomAttributes(false)\n            .OfType<ValidationAttribute>()\n            .ToArray();\n\n        if (!Validator.TryValidateValue(value, context, results, attributes))\n        {\n            foreach (var result in results)\n            {\n                Console.WriteLine(result.ErrorMessage);\n            }\n        }\n        else\n        {\n            Console.WriteLine("{0} is valid", value);\n        }\n    }\n}	0
31001577	31001067	How to rewrite this C# code that deals with a Stream and a byte buffer	let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) =\n    let bufferLen : int = 4096\n    let buffer : byte array = Array.zeroCreate bufferLen\n\n    let rec copy () =\n        match stream.Read(buffer, 0, bufferLen) with\n        | count when count > 0 ->\n            outstream.Write(buffer, 0, count)\n            copy ()\n        | _ -> ()\n\n    copy ()	0
18380385	18380161	Making an HttpWebRequest from the following given POST data	ASCIIEncoding encoder = new ASCIIEncoding();\nbyte[] data = encoder.GetBytes(serializedObject); // the data you wanted to send\n\nHttpWebRequest request = new WebRequest.Create("https://api.twitter.com/oauth/request_token") as HttpWebRequest;\nrequest.Method = "POST";\nrequest.ContentType = "application/x-www-form-urlencoded";\nrequest.ContentLength = data.Length;\n\nrequest.GetRequestCode().Write(data, 0, data.Length);	0
6114255	6114157	How can I select the previous char from the cursor position in a RichTextBox	rtb.SelectionFont.Name	0
1601661	1601646	How to test if numeric conversion will change value?	if ((int)(double)x != x) { \n  // won't convert\n} else {\n  // will convert\n}	0
5240641	5240634	How can I get an assembly that isn't referenced in my project?	AppDomain.CurrentDomain.GetAssemblies()	0
14517605	14516671	SELECT top 35 Lat Lan records with reference to a particular Lat Lan from MS SQL Table	CREATE FUNCTION dbo.calcDistance (\n    @latA AS NUMERIC(38, 35),\n    @longA AS NUMERIC(38, 35),\n    @latB AS NUMERIC(38, 35),\n    @longB AS NUMERIC(38, 35)\n    )\nRETURNS NUMERIC(38, 35)\nAS\nBEGIN\n    RETURN (DEGREES(ACOS(SIN(RADIANS(@latA)) * SIN(RADIANS(@latB)) + COS(RADIANS(@latA)) * COS(RADIANS(@latB)) * COS(RADIANS(@longA - @longB)))) * 69.09 * 1.6093)\nEND	0
16342873	16342483	How to find a list of Elemenets/Attributes from a specific Element in XML?	var groups = from group in doc.Descendants("GROUP")\n            where (string)group.Attribute("meetsMark") == "1"\n            select group\n\nvar subgroups = from subgroup in groups.Descendants("GROUP")\n           where subgroup.Attribute("code").Value == "SECONDARY"\n           select subgroup;\n\nforeach( var subgroup in subgroups )\n{\n   System.Console.WriteFormat( "code = {0}", subgroup.Attribute("code").Value );\n\n   var sums = from summary in subgroup.Descendants("SUMMARY")\n\n   foreach( var sum in sums )\n   {\n       System.Console.WriteFormat( "sum = {0}", subgroup.Attribute("sum").Value );\n       System.Console.WriteFormat( "number = {0}", subgroup.Attribute("number").Value );\n   }\n}	0
14275363	14274777	Signing security token using sha256	CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");	0
32550674	32548714	How to use credentials from C#	public class PasswordRepository\n{\n    private const string PasswordName = "ServerPassword";\n\n    public void SavePassword(string password)\n    {\n        using (var cred = new Credential())\n        {\n            cred.Password = password;\n            cred.Target = PasswordName;\n            cred.Type = CredentialType.Generic;\n            cred.PersistanceType = PersistanceType.LocalComputer;\n            cred.Save();\n        }\n    }\n\n    public string GetPassword()\n    {\n        using (var cred = new Credential())\n        {\n            cred.Target = PasswordName;\n            cred.Load();\n            return cred.Password;\n        }\n    }\n}	0
27693640	27688361	asp.net API post values received are null from postmaster	{\n    "incidentId":4,\n    "incidentTitle":"this is some text"\n}	0
16436412	16436037	How to Get Shortest/Longest Posting Lists	public List<T> GetSmallestPosting()\n{\n    if(_Index!=null)\n       return  _Index.Values.First(v => v.Count == _Index.Min(kv => kv.Value.Count)).ToList();\n\n    return null;\n}\n\npublic List<T> GetLongestPosting()\n{\n    if(_Index!=null)\n      return   _Index.Values.First(v => v.Count == _Index.Max(kv => kv.Value.Count)).ToList();\n\n    return null;\n}	0
14364592	14364153	Searching for an item in a dataset and showing it in a combo box	DataTable products = new DataTable();\nproducts.Columns.Add("Product_Name");\nproducts.Columns.Add("Product_BarCode");\n\nproducts.Rows.Add("test1", 123456);\nproducts.Rows.Add("test", 923456);\nproducts.Rows.Add("test8", 823456);\nproducts.Rows.Add("test", 723456);\nproducts.Rows.Add("test0", 023456);\n\nproductname_tb.DataSource = products;\nproductname_tb.DisplayMember = "Product_Name";\nproductname_tb.ValueMember = "Product_BarCode";\n\n// select the "test8" item by using it's Product_BarCode value of 823456\nfor (int i = 0; i < productname_tb.Items.Count; i++)\n{\n    if (((System.Data.DataRowView)(productname_tb.Items[i])).Row.ItemArray[1].ToString() == "823456")\n    {\n        productname_tb.SelectedItem = productname_tb.Items[i];\n        break;\n    }\n}	0
20298941	20298832	How to convert value of aspx combobox selected item to int?	devId=Convert.ToInt32(cmbDealer.SelectedItem.Value.ToString())	0
7168328	7168058	How to check if a C# Stream is resizable?	public static bool IsResizable(this Stream stream)\n    {\n        bool result;\n        long oldLength = stream.Length;\n\n        try\n        {\n            stream.SetLength(oldLength + 1);\n            result = true;\n        }\n        catch (NotSupportedException)\n        {\n            result = false;\n        }\n\n        if (result)\n        {\n            stream.SetLength(oldLength);\n        }\n\n        return result;\n    }	0
20897423	20897363	how to retrieve all value from table data from database in asp.net & display in string/label	con.Open();\nstring query = "select Calf_ID,Plant,date1,Event from Holiday_Master ";\ncmd = new SqlCommand(query, con);\ncmd.CommandType = CommandType.Text;\n\nusing (SqlDataReader dr = cmd.ExecuteReader())\n{\n   GridView1.DataSource = dr;\n   GridView1.DataBind();\n}\n\ncon.Close();	0
9080210	9001882	Make a Buttonfield Execute a javascript	If e.Row.RowType = DataControlRowType.DataRow Then\n       Dim btnbutton As LinkButton = DirectCast(e.Row.Cells(13).Controls(0), LinkButton)\n       btnbutton.Attributes.Add("onclick", "javascript:return ShowDialog()")	0
10469429	10469354	C# changing the background image of multiple controls	PictureBox _lastPictureBox = null;\nImage _lastPictureBoxImage = null;\n\nprivate void Pic_Click(object sender, System.EventArgs e)\n{\n    PictureBox pb = (PictureBox)sender;\n    if (_lastPictureBox != null) \n    {\n      // update the previous one, eg:\n       _lastPictureBox.BackgroundImage = _lastPictureBoxImage;\n    }\n\n    // now set it to the current one:\n   _lastPictureBox = pb;\n   _lastPictureBoxImage = pb.Image;\n   switch (pb.Name)\n   {\n     case "1": \n       pb.BackgroundImage = Properties.Resources.OtherImg; //creates the background\n       pb.BackgroundImageLayout = ImageLayout.Stretch;\n    break;\n    case "2":\n      pb.BackgroundImage = Properties.Resources.OtherImg; //creates the background\n      pb.BackgroundImageLayout = ImageLayout.Stretch;\n    break;\n  }	0
15793036	15792968	How to convert this into a dictionary of a dictionary	var dictionary = data.ToDictionary(group => group.Key, \n    group => group.ToDictionary(item => item.Time, item => item.TR));	0
10665271	10665161	Allowing people to mod a program	Assembly.LoadFrom("plugin.dll")	0
24345012	24337655	WritableBitmap - Save custom live tile as Transparent PNG	using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n        using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".png", System.IO.FileMode.Create, isf))\n        {\n              Cimbalino.Phone.Toolkit.Extensions.WriteableBitmapExtensions.SavePng(b, imageStream);\n\n        }\n    }	0
14774095	14773387	Dynamically adding a new way to display collection information in WPF	public class EmployeesViewModel {\n    public Filter Filter { get; set;}\n    public ObservableCollection<Employee> Employees { get; set;}\n    public Employee SelectedEmployee { get; set;}\n    public RoutedCommand SaveSelectedEmployee { get; set;}\n    ???\n}	0
4102047	4102025	using linq, how can i create a IEnumerable<> from a property of another IEnumerable<>	var peoplesDogs = people.SelectMany(p => p.Dogs);	0
1835662	1831620	How can you inject a session reference	For<HttpSessionStateBase>().TheDefault.Is.ConstructedBy(() => new HttpSessionStateWrapper(HttpContext.Current.Session));	0
8774816	8774794	Encoding / Decoding resulting only in alpha-numerical sequence	Convert.ToBase64String(arrayOfBytes)	0
9730430	9724043	Loading Embedded XSD with Imports into DataSet	internal void ReadXSDSchema(XmlReader reader, bool denyResolving)	0
26964007	26963923	Issue Seperate Arguments to Exe in one construct	adb shell	0
27814178	27813757	Parse Eposodes with a Regular Expression	S(?<season>\d{1,2})|(?<eposode>(?<=E)\d{1,2})	0
1480857	1477297	Can i use text box names as values in a list?	var sumX = from Control control in Controls\n            where \n                control.GetType() == typeof (TextBox) \n                && control.Name.StartsWith("box")\n            select Convert.ToInt32(((TextBox)control).Text);	0
11455056	11455031	Overload Base Constructor	public class foo\n{\n    public foo(string a, string b) { ... }\n}\n\npublic class bar : foo\n{\n    public bar(): base("apple", "banana") // call base constructor\n    {\n\n    }\n}	0
3507641	3507513	listbox or listview of thumbnails with a directory as the input in c#	using Microsoft.Win32;\nusing System.Collections.Generic;\n\nlv.ItemsSource = null;\nList<XmlElement> elements = new List<XmlElement>();\nMicrosoft.Win32.FileDialog fd = new Microsoft.Win32.OpenFileDialog();\nbool ?a = fd.ShowDialog();\nif (a == true)\n{\n     XmlDocument doc = new XmlDocument();\n     string dir = fd.FileName.Remove(fd.FileName.Length - fd.SafeFileName.Length, fd.SafeFileName.Length);\n     string[] files = Directory.GetFiles(dir);\n     foreach (string file in files)\n     {\n           XmlElement item = doc.CreateElement(file.Remove(0,dir.Length));\n           item.SetAttribute("Name", file.Remove(0, dir.Length));\n           item.SetAttribute("Type", Path.GetExtension(file));\n           item.SetAttribute("Image", "images\\cat.png");\n           elements.Add(item);\n      }\n}\nlv.ItemsSource = elements;	0
4154616	4154359	Performing an audit using reflection	var assembly = System.Reflection.Assembly.GetExecutingAssembly();\n\nvar methods = assembly.GetTypes()\n              .Where(t => t is System.Web.Mvc.Controller)\n              .SelectMany(t => t.GetMethods())\n              .Where(m => m.ReturnType is ActionResult)\n              .Where(m => m.GetCustomAttributes(typeof(TargetAttribute), false).Length > 0)\n              .ToArray();\n\nbool implementsITarget = false;\n\nforeach(method in methods)\n{\n    foreach(param in method.GetParameters())\n    {\n        if(param.ParameterType is ITarget) \n        {\n            implementsITarget = true;\n            break;\n        }\n    }\n    Assert.True(implementsITarget , String.Format("Controller {0} has action {1} that does not implement ITarget but is decorated with TargetAttribute", method.DeclaringType, method.Name) );\n    implementsITarget = false;\n}	0
7107112	7106845	How to overwite nodes in an xml file?	filename = @"c:\path\sample.xml";\n\n  XDocument doc = XDocument.Load(filename);\n\n  var result = (from node in doc.Descendants("WindowEntry")\n                         where node.Element("Name").Value == "maduranga"\n                         select  node.Element("Name")).ToList();\n\n  if(result.Count!=0)\n    result[0].Value = "NewValue";\n\n  doc.Save(filename);	0
28565752	28564680	Result of a Select query into another table	private void button1_Click(object sender, EventArgs e)\n  {\n  SqlDataAdapter SDA = new SqlDataAdapter();\n  DataTable dt = new DataTable();\n  SqlConnection con = new SqlConnection("Data Source=HOME;Initial   \n                           Catalog=Test;Integrated Security=True");\n\n  SqlCommand cmd = new SqlCommand("insert into list (pname, pprice)\n  select pname, pprice from products where pid='" +textBox1.Text+"'", con);\n  con.Open();\n  SDA.SelectCommand = cmd;\n  SDA.Fill(dt);\n  con.Close();\n  MessageBox.Show("Product Added");\n\n  }	0
11803197	11803145	Can you write a formula to Excel from C# when writing to a range of cells?	((Range)worksheet.Cells[row, col]).Formula = myFormula	0
12132636	12128119	Run animations one at time	public void startbtn_Click(object sender, RoutedEventArgs e)\n{\n    engine.resetSequence(); // Start from sequence 0\n    // Animate first button\n    animate(engine.animate()); \n}\n\n\nprivate void animate(int index)\n{\n\n    // Storyboard for each button is in the format of ButtonAnimation_INDEX where INDEX is 1, 2, 3 or 4\n       Storyboard btnAnimation = (Storyboard)this.Resources["ButtonAnimation_" + index];\n       // Added completed event function handler\n       btnAnimation.Completed += btnAnimation_Completed;\n       if (btnAnimation != null)\n       {\n           btnAnimation.Begin();   \n        }\n}\n\n\nvoid btnAnimation_Completed(object sender, EventArgs e)\n{\n     // If another button can be animated in the sequence\n     if (engine.CurrentSequence() < engine.getCurrentLevel())\n     {\n         // Increment the sequence position\n         engine.nextSequence();\n         // Run the animation with the next button\n         animate(engine.animate());\n     }\n}	0
23754337	23753520	How to open jar file from c# without opening commad prompt	var processInfo = new ProcessStartInfo("java.exe", "-jar app.jar")\n                  {\n                      CreateNoWindow = true,   /*no window*/\n                      UseShellExecute = false\n                  };\nProcess proc;\n\nif ((proc = Process.Start(processInfo)) == null)\n{\n  //do someting usefull with the error\n}\n\nproc.WaitForExit();\nproc.Close();	0
5004907	5004614	Detect user idle (per application instance)	Application.AddMessageFilter	0
9573098	9571847	InvalidOperationException when enumerating through a list of results to provide multiple textbox's with text	var ObjectContext = new ObjectContext();\n\n    var details = ObjectContext.TableLocation\n                    .First(x => x.LocationName == LocationValue)\n                    .Select(x => \n                            new { \n                                PostalCode = x.postalCode,\n                                Phone1 = x.phoneNumber1,\n                                Phone2 = x.phoneNumber2,\n                                Supervisor = x.supervisor\n                            });\n\ntxtPostalCode.Text = details.PostalCode;\ntxtPhone1.Text = details.Phone1;\ntxtPhone2.Text = details.Phone2;\ntxtSupervisor.Text = details.Supervisor;	0
29535471	29490657	Foreign Key - Dataannotation	public class Person : BaseEntity\n{\n    public string FirtName { get; set; }\n    public string LastName { get; set; }\n\n    public virtual PersonAddress Address { get; set; }\n    ...\n}\n\npublic class PersonAddress : BaseEntity\n{\n    DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]\n    [Key, ForeignKey("Person")]\n    public override int ID { get; set; }\n\n    [ForeignKey("ID")]\n    public virtual Person Person { get; set; }\n    ...\n}	0
19976001	19975979	using returned value of tuple	Tuple<bool, string> chk = check();	0
18226167	18164170	Appy Html Agility Pack Changes to Web Page	HtmlDocument doc = new HtmlDocument();\ndoc.Load("somefile.html");\n\n// modify doc in memory\n\ndoc.Save("somefile.html");	0
21053475	21053310	Exception on date format	theDate.ToString("yyyy-MM-dd HH:mm:ss.000")	0
31323562	31323493	Reading Text from Comma-Delimited file	if (line.Contains(mySearchString)) \n{\n   var text = line.Split(",")[1];\n   /*do something else with text*/\n}	0
31411024	31410344	How download an Excel File from SharePoint using WinForm app	using System.Net;\n\nWebClient webClient = new WebClient();\nwebClient.DownloadFile("http://example.com/myfile.txt", @"c:\myfile.txt");	0
9897657	9897402	Writing a Replace Regex	Regex.Match(input, @"(?:.*?\.)?(.{3})[^.]*?_IN_(\d+)");	0
5702940	5694721	SharePoint 2010 event listener - SPItemEventReceiver with multithreading	SPEventReceiverDefinition eventReceiver = eventReceivers.Add();\neventReceiver.Name = receiverName;\neventReceiver.Synchronization = SPEventReceiverSynchronization.Asynchronous; \neventReceiver.Type = SPEventReceiverType.ItemAdded;\neventReceiver.SequenceNumber = sequenceNumber; \neventReceiver.Assembly = assemblyFullName ;\neventReceiver.Class = assemblyClassName ;\neventReceiver.Data = receiverData ;\n\neventReceiver.Update();	0
17700022	17699896	KeyNotFoundException unhandled by user	HtmlDocument htmlDoc = HtmlPage.Document;\nstring productCode;\n\nif (!htmlDoc.QueryString.TryGetValue("productCode", out productCode))\n{\n    productCode = htmlDoc.GetElementById("vidWeeklyFeature").GetProperty("value").ToString();\n}	0
17849658	17849619	Setting default active tab for tabcontainer	tcQuestion.ActiveTabIndex = 0	0
2181959	2180779	Castle components dispose order	internal class CriticalService : ICriticalService, IStartable\n{\n    private readonly IEmailService email;\n\n    public CriticalService(IEmailService email) {\n        this.email = email;\n    }\n ...\n}	0
28904949	28904846	How to validate username and password from text file? | Winforms C#	private void button1_Click(object sender, EventArgs e){\n     string[] lines = System.IO.File.ReadAllLines(@"D:\C#\test.txt");\n     String username = lines[0];\n     String password = lines[1];\n}	0
9906500	9906125	How to get records from list view	for (int i = 0; i < listView1.Items[0].SubItems.Count; i++)\n    {\n       string s = listView1.Items[0].SubItems[i].Text;\n    }	0
26122949	26122716	Unable to get full image from server	public static bool GetFileFromURL(string url, string filename)\n{\n    try\n    {\n        var req = WebRequest.Create(url);\n        using (Stream output = File.OpenWrite(filename))\n        using (WebResponse res = req.GetResponse())\n        using (Stream s = res.GetResponseStream())\n            s.CopyTo(output);\n        return true;\n    }\n    catch\n    {\n        return false;\n    }\n}	0
30902219	30902008	RichTextbox write in place to current line	// Get the index of the last line in the richtextbox\nint idx = rtb.Lines.Length - 1;\n\n// Find the first char position of that line inside the text buffer\nint first = rtb.GetFirstCharIndexFromLine(idx);\n\n// Get the line length\nint len  = rtb.Lines[idx].Length;\n\n// Select (Highlight) that text (from first to len chars)\nrtb.SelectionStart = first;\nrtb.SelectionLength = len;\n\n// Replace that text with your update\nrtb.SelectedText = "Processed: " + recordCount + " Records.";	0
21681885	21681719	Retrieve JSON with StackOverflow in C#	var stream = webRequest.GetResponse().GetResponseStream();\nMemoryStream m = new MemoryStream();\nnew System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress).CopyTo(m);\ntry\n{\n    string str = Encoding.UTF8.GetString(m.ToArray()); \n    Console.Write(str);\n    Console.Read();\n}\nfinally\n{\n ........\n}	0
21416475	21415970	regex replace matches with function and delete other matches	public string translateSearchTerm(string searchTerm) {\n    string result = "";\n\n    result = Regex.Replace(searchTerm.ToLower(), @"field(.*?)(?=\=)", delegate(Match Match) {\n        string fieldId = Match.Groups[1].Value;\n        return getFieldName(Convert.ToInt64(fieldId));\n    });\n\n    log.Info(String.Format("result={0}", result));\n\n    return result;\n}	0
2260967	2260961	Sock shows inconsistent/impossible results after repeat use	}catch (Exception ex) {\n   Console.WriteLine(ex);\n}	0
2259725	2259671	Is there a more efficient way to get the number of search results from a google query?	...\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(googleUri);\nrequest.Referer = "http://www.your-referer.com";\nHttpWebResponse response = (HttpWebResponse)req.GetResponse();\nStream responsestream = response.GetResponseStream();\nStreamReader responsereader = new StreamReader(responsestream);\nJObject jo = JObject.Parse(responsereader.ReadToEnd());\nint resultcount = (int)jo.SelectToken("responseData.cursor.estimatedResultCount");\n...	0
2212595	2212577	Callback from Delphi dll to C# app	type TCallback = procedure(val: integer); stdcall;	0
20613461	20610799	Windows Service exception using NLog to write to file on Windows Server 2008 R2	maxLevel="Deubg"	0
4390284	4389817	How to force file download on Telerik RadEditor?	var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/path/to/file.txt"));\nResponse.AddHeader("Content-Type", "text/plain");\nResponse.AddHeader("Content-Displosition", "attachment;filename=file.txt;size=" + bytes.Length);\nResponse.Flush();\nResponse.BinaryWrite(bytes);\nResponse.Flush();\nResponse.End();	0
21603781	21596448	How to get user destination by code in c#	{\n   "ip": "115.113.234.46",\n    "country_code": "IN",\n    "country_name": "India",\n    "region_code": "",\n    "region_name": "",\n    "city": "",\n    "zipcode": "",\n    "latitude": 20,\n    "longitude": 77,\n    "metro_code": "",\n    "areacode": ""\n}	0
16672412	16660859	Writing jpeg image into a SQL Server 2000 style TEXT field	MemoryStream ms = [your stream];\n        Byte[] memoryBytes = ms.ToArray();\n        StringBuilder sBuilder  = new StringBuilder();\n\n        foreach(byte nextByte in memoryBytes)\n            sBuilder.Append((char)nextByte);\n\n        string res = sBuilder.ToString();	0
9062546	9033847	Execute Powershell script in C# without UserName and Password	/// COMMAND : `Set-ExecutionPolicy Unrestricted`	0
20657953	20657754	calling multiple dropdownlist index change methods within the another ddl index change	protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)\n{\n    BuildChart();\n}\n\nprotected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)\n{\n    BuildChart();\n}\n\nprivate BuildChart()\n{\n    var ddl3Value = DropDownList3.SelectedValue;\n    var ddl2Value = DropDownList2.SelectedValue;\n\n    if(ddl3Value != null && ddl2Value != null)\n    {\n        //build chart.\n    }\n}	0
3745670	3745591	C# WinForm Timers - Notify parent class that a timer event has been raised	class Parent\n{\n  List<Child> _children = new List<Child>();\n\n  public Parent()\n  {\n    _children.Add(new Child());\n    _children.Add(new Child());\n    _children.Add(new Child());\n\n    // Add handler to the child event\n    foreach (Child child in _children)\n    {\n      child.TimerFired += Child_TimerFired;\n    }\n  }\n\n  private void Child_TimerFired(object sender, EventArgs e)\n  {\n    // One of the child timers fired\n    // sender is a reference to the child that fired the event\n  }\n}\n\nclass Child\n{\n  public event EventHandler TimerFired;\n\n  protected void OnTimerFired(EventArgs e)\n  {      \n    if (TimerFired != null)\n    {\n      TimerFired(this, e);\n    }\n  }\n\n  // This is the event that is fired by your current timer mechanism\n  private void HandleTimerTick(...)\n  {\n    OnTimerFired(EventArgs.Empty);\n  }\n}	0
3724266	3724044	Should I close a socket (TCPIP) after every transaction?	while(bCollectData)\n{\n   _socket.recv(...); //this line will wait for response from server\n   //... process message and start another wait in the next iteration.\n}	0
1855843	1855815	Calculating info_hash from UrlEncoded query string	var s = "%5d%96%b6%f6%84%5e%ea%da%c5%15%c4%0e%403h%b9Ui4h";\n\nvar ms = new MemoryStream();\nfor (var i = 0; i < s.Length; i++)\n{\n    if (s[i] == '%')\n    {\n        ms.WriteByte(\n            byte.Parse(s.Substring(i + 1, 2), NumberStyles.AllowHexSpecifier));\n        i += 2;\n    }\n    else if (s[i] < 128)\n    {\n        ms.WriteByte((byte)s[i]);\n    }\n}\n\nbyte[] infoHash = ms.ToArray();\nstring temp = BitConverter.ToString(infoHash);\n// "5D-96-B6-F6-84-5E-EA-DA-C5-15-C4-0E-40-33-68-B9-55-69-34-68"	0
10924300	10922669	NUnit tests fail due to Enterprise Library	web.config	0
23279269	23091396	Change resource file reference on btn click	InitializeCulture()	0
3352614	3345348	How to specify a min but no max decimal using the range data annotation attribute?	[Range(typeof(decimal), "0", "79228162514264337593543950335")\n  ] public decimal Price { get; set; }	0
8739966	8739848	How to validate a file name which has a date in it using a C# regular expression	var fileRegex = new Regex(@"^(?<Date>\d{12})Rate$");\nvar match = fileRegex.Match(Path.GetFileNameWithoutExtension(fileName));\n\nDateTime fileNameDate;\nbool success = match.Success && \n                   DateTime.TryParseExact(\n                      match.Groups["Date"].Value,\n                      "yyyyMMddHHmm",\n                      CultureInfo.CurrentCulture, \n                      DateTimeStyles.None, \n                      out fileNameDate);	0
19070547	19070431	Fetch (x,y) from a 2D Array where condition matches	var lst = array2D.SelectMany((x,r) => x.Select((a,c)=> new {a,b=new Point(c,r)})\n                                       .Where(a=>a.a==0)\n                                       .Select(a=>a.b)).ToList();	0
6542072	2178414	How to read only new content in VSTO Outlook MailItem body?	Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)\n\n    Dim theLine As String\n    Dim aBody()\n    Dim bFound As Boolean\n    Dim ctr As Long\n\n    aBody = Array(Split(Item.Body, vbNewLine))\n    bFound = False\n\n    For ctr = 0 To UBound(aBody(1))\n        theLine = aBody(1)(ctr)\n        If InStr(theLine, "From:") > 0 Then\n            Exit For\n        End If\n\n        If InStr(UCase(theLine), "ATTACH") > 0 Then\n            bFound = True\n        End If\n\n    Next\n\n    If bFound Then\n        If Item.Attachments.Count < 1 Then\n            Dim ans As Integer\n\n            ans = MsgBox("Do you really want to send this without any attachments?", vbYesNo)\n            If ans = 7 Then\n                Cancel = True\n                Exit Sub\n            End If\n        End If\n    End If\n\nEnd Sub	0
5359182	5358816	Setting a WPF button to visible within an IConnectionPoint event handler	public void ConnectivityChanged(NLM_CONNECTIVITY newConnectivity)\n    {\n        if (newConnectivity == NLM_CONNECTIVITY.NLM_CONNECTIVITY_DISCONNECTED ||\n            ((int)newConnectivity & (int)NLM_CONNECTIVITY.NLM_CONNECTIVITY_IPV4_NOTRAFFIC) != 0)\n        {\n            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(\n                delegate()\n                {\n                    buttonStart.Visibility = Visibility.Hidden;\n                }\n            ));\n        }\n        // ...\n    }	0
17847024	17824127	Passing a value, retrieved from a linq statement in a view, to its controller	ViewContext.Controller	0
31243640	31243587	How to dynamically pass name of calling method as a parameter in the same method?	MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();\nstring methodName = method.Name;\nstring className = method.ReflectedType.Name;\n\nstring fullMethodName = className + "." + methodName;	0
1357627	1356755	COM Interop (how to pass an array to the com) via classic ASP	public int Add(int val1, int val2, out object outputz)\n{\n    int total = val1 + val2;\n    outputz = new object[5]\n      {\n          "test1",\n          "test2",\n          "test3",\n          "test4",\n          "test5"\n      };\n\n    return total;\n}	0
3806386	3805545	How do I change the style of a disabled control?	using System;\nusing System.Windows.Forms;\n\nclass RichLabel : RichTextBox {\n    public RichLabel() {\n        this.ReadOnly = true;\n        this.TabStop = false;\n        this.SetStyle(ControlStyles.Selectable, false);\n    }\n    protected override void OnEnter(EventArgs e) {\n        if (!DesignMode) this.Parent.SelectNextControl(this, true, true, true, true);\n        base.OnEnter(e);\n    }\n    protected override void WndProc(ref Message m) {\n        if (m.Msg < 0x201 || m.Msg > 0x20e)\n            base.WndProc(ref m);\n    }\n}	0
2570371	2570244	Problem with Killing windows explorer?	using System;\nusing System.Runtime.InteropServices;\n\nnamespace ExplorerZap\n{\n    class Program\n    {\n        [DllImport("user32.dll")]\n        public static extern int FindWindow(string lpClassName, string lpWindowName);\n        [DllImport("user32.dll")]\n        public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);\n\n        [return: MarshalAs(UnmanagedType.Bool)]\n        [DllImport("user32.dll", SetLastError = true)]\n        public static extern bool PostMessage(int hWnd, uint Msg, int wParam, int lParam);\n\n        static void Main(string[] args)\n        {\n            int hwnd;\n            hwnd = FindWindow("Progman", null);\n            PostMessage(hwnd, /*WM_QUIT*/ 0x12, 0, 0);\n            return;\n        }\n    }\n}	0
24242388	24241469	Regular Expression for SFTP URL	ng-pattern="/sftp://.+/"	0
8058458	8058348	How to load a file with words into a list where the file has over 3 million lines	List<string> wordsDictionary = new List<string>( 100000 );	0
1716788	1716719	Possibility of Implementing Minimize-to-Tray in C# in an Attribute	class TrayForm : Form\n{\n    NotifyIcon notifyIcon = new NotifyIcon();\n    protected override void OnFormClosing(FormClosingEventArgs e)\n    {\n        if (e.CloseReason != CloseReason.WindowsShutDown && e.CloseReason != CloseReason.ApplicationExitCall)\n        {\n            e.Cancel = true;\n            this.Hide();\n            this.notifyIcon.Visible = true;\n        }\n\n        base.OnFormClosing(e);\n    }\n\n    protected override void OnSizeChanged(EventArgs e)\n    {\n        if (WindowState == FormWindowState.Minimized)\n        {\n            this.Hide();\n            this.notifyIcon.Visible = true;\n        }\n\n        base.OnSizeChanged(e);\n    }\n}	0
18321371	18320916	How to send xml through an HTTP request, and receive it using ASP.NET MVC?	[HttpPost]\n[ValidateInput(false)]\npublic ActionResult Index()\n{\n    string xml = "";\n    if(Request.InputStream != null){\n        StreamReader stream = new StreamReader(Request.InputStream);\n        string x = stream.ReadToEnd();\n        xml = HttpUtility.UrlDecode(x);\n    }\n    ...\n    return View(model);\n}	0
12730002	12729922	How to set CultureInfo.InvariantCulture default?	Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;	0
32261205	32259878	AWS SDK in Windows 10 Universal App	Install-Package AWSSDK	0
27227601	27227549	CSS is affecting all pages, but I just want to use it for one	.cssbox input[type=text]:focus,\n.cssbox input[type=password]:focus,\n.cssbox textarea:focus,\n.cssbox select:focus   \n{\n   border-color: #66afe9;\n   outline: 0;\n   -moz-box-shadow: 0 0 3px 0 #95B8E7;\n   -webkit-box-shadow: 0 0 3px 0 #95B8E7;\n   box-shadow: 0 0 3px 0 #95B8E7;\n }	0
27831390	27831135	parsing string for value having newline character	string[] parts = InnerText.Split("\n".ToCharArray());\nstring partIWant = parts[parts.Length - 2];	0
22835075	22834551	How to remove all HTML formatting from string	htmlinput =\n "<br /> <b>Error:</b> Undefined value xyz in /var/www/sdsd/sdsd/asdsd.php <br />"\n\n nonhtmloutput =\n Regex.Replace(htmlinput,@"\<.*?\>", String.Empty)	0
27153616	27013044	Retrieving drop down list items from list of controls	public IEnumerable<ListItem> GetListItems(ControlCollection controls)\n{\n    return controls.OfType<DropDownList>().SelectMany(c => c.Items.OfType<ListItem>());\n}	0
3830679	3830581	how to run the exe file in internet explorer by using the .net application	System.Diagnostics.Process.Start(@"\"C:\Program Files (x86)\Internet Explorer\iexplore.exe\" \"[path to my file]\"");	0
31109305	31107423	c# restart a tcp server	private void restartServer()\n    {\n      try { \n        try {\n            check = false;\n            tcpListener.Stop();\n            textBox1.BeginInvoke((MethodInvoker)(() => textBox1.AppendText("Server stopping..\r\n")));\n            t2.Abort();\n            check = true;\n            startThread();\n        }\n        catch(ThreadAbortException){\n\n        }\n         }  \n        catch(ThreadAbortException)\n      {\n          Thread.ResetAbort();\n      }\n    }	0
32564111	32562717	Datagridview cellclick event for next rows	void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    //if click is on new row or header row\n    if( e.RowIndex == dataGridView1.NewRowIndex || e.RowIndex < 0)\n        return;\n\n    //Handle First Button Click\n    if( e.ColumnIndex  == dataGridView1.Columns["Your First Button"].Index)\n    {\n        //Do the stuff for first button click\n        MessageBox.Show("First Button Clicked");\n    }\n\n    //Handle Second Button Click\n    if( e.ColumnIndex == dataGridView1.Columns["Your Second Button"].Index)\n    {\n        //Do the stuff for second button click\n        MessageBox.Show("Seccond Button Clicked");\n    }\n\n}	0
5397772	5397650	C# Async Http request, How to stop skipping?	var urls = new List<string>();\n\n            var tasks = urls.Select(url =>\n                {\n                    var request = WebRequest.Create(url);\n                    var task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);\n                    task.Start();\n                    return task;\n                }).ToArray();\n\n            Task.WaitAll(tasks);\n\n            foreach (var task in tasks)\n            {\n                using (var response = task.Result)\n                using (var stream = response.GetResponseStream())\n                using (var reader = new StreamReader(stream))\n                {\n                    var html = reader.ReadToEnd();\n                }                                \n            }	0
7714202	7714130	Return Value by closing MainWindow	Application.Current.Shutdown(1);	0
32009119	32008916	Update a Progress Bar (located in window) from a Page that is called inside a frame of that window	//get the window hosting the page\nvar window = Window.GetWindow(this) as dash;\n// check for null\nif (window != null) {\n    //set value of the progressbar\n    window.prgbar = 75;\n}	0
28340591	28339347	Filtering data source so a user can only see their own info	partial void CustomersByLoggedInUser_PreprocessQuery(ref IQueryable<Customer> query)\n    {\n    if (!Application.Current.User.HasPermission(Permissions.SecurityAdministration))\n    {\n        Guid guid = (Guid)Membership.GetUser().ProviderUserKey;                \n\n        IEnumerator cusUsers = this.CustomerUsers.GetEnumerator();\n\n        CustomerUser current;\n        CustomerUser found = null;\n        while (cusUsers.MoveNext())\n        {\n            current = (CustomerUser)cusUsers.Current;\n\n            if (current.GebruikerID == guid)\n            {\n                found = current;\n            }\n        };\n\n        try\n        {                \n            if (found != null)\n            {\n                filter = e => e.CustomerID == found.Customer1.CustomerID;\n            }\n            else\n            {\n                filter = e => e.CustomerID == "-1";\n            }\n        }\n        catch (Exception ex)\n        {\n\n        }\n\n    }\n}	0
9107241	9107216	print select value from json object	JObject parsed = JObject.Parse(json);\n JToken response = parsed["response"];\n JArray venues = (JArray)response["venues"];\n JValue names = (JValue)venues[1]["name"];	0
12811305	12811271	Order by a field descendingly	UnUsedServices = UnUsedServices.OrderByDescending(si => si.utility).ToList();	0
30519285	30519142	Add a hyperlink to grid column	.ClientTemplate("<a href='" + Url.Action("GetPdf", "Home") + "?fileName=#= FileName #'>#=FileName#</a>");\n\npublic ActionResult GetPdf(string fileName)\n{\n    string path = FileHelper.GetFullPath(fileName);\n    FileStream stream = new FileStream(path, FileMode.Open);\n    return File(stream, "application/pdf", fileName + ".pdf");\n}	0
28713242	28713167	Entity Framework Object contains same object	modelBuilder.Entity<ProjectPage>()\n             .HasOptional(e => e.Header)\n             .WithMany()\n             .HasForeignKey(m => m.HeaderId);\n\n modelBuilder.Entity<ProjectPage>().\n             .HasOptional(e => e.Footer)\n             .WithMany()\n             .HasForeignKey(m => m.FooterId);	0
9044044	9043967	How to get max element in a string array by linq?	string[] Files = { "NO. 1", "NO. 2", "NO. 3", "NO. 4", "NO. 5", "NO. 6", "NO. 7" };\nvar max = Files.OrderByDescending(x => int.Parse(x.Replace("NO. ", ""))).First();	0
26395174	26395052	how to access a child element dynamically in WPF	((TextBlock)b.FindName("t1")).Text = "newString";	0
29983591	29983399	Joining two files in C#, split options	string[] files = { "f1.txt", "f2.txt" };\n\n var allLines = files.SelectMany(i => System.IO.File.ReadAllLines(i));\n\n System.IO.File.WriteAllLines("new.txt", allLines.ToArray());	0
4928270	4716582	Dropdown list selected item always set to default value	if (!Page.IsPostBack)\n    {\n//LoadDropdownListHere();\n    }	0
1159841	1159750	How do I marshal an array of bytes to a struct?	static public T ReadStructure<T>(byte[] bytes)\n    where T : struct\n{\n    int len = Marshal.SizeOf(typeof(T));\n    IntPtr i = Marshal.AllocHGlobal(len);\n\n    try\n    {\n        Marshal.Copy(bytes, 0, i, len);\n        return (T)Marshal.PtrToStructure(i, typeof(T));\n    }\n    finally\n    {\n        Marshal.FreeHGlobal(i);\n    }\n}	0
30173023	30172721	how to set Reportviewer controls report server Url and report path properties in asp.net	ReportServerUrl="http://vm-xx-xxxxx/reportserver"\nReportPath="/xxx+xxx+And+xxx/WorkOrder+UAT"	0
15861334	15858584	How to scale a image based on its rotation	Matrix origin = Matrix.CreateTranslation(0, 0, 0);\nMatrix scale = Matrix.CreateScale(1f);\nMatrix rotation = Matrix.CreateRotationZ(MathHelper.ToRadians(rotate));\nMatrix translation = Matrix.CreateTranslation(0, 0, 0);\n\nVector2 pos1 = Vector2.Transform(new Vector2(Texture.Width / 2, Texture.Height / 2), origin * scale * rotation * origin);\nVector2 pos2 = Vector2.Transform(new Vector2(Texture.Width, Texture.Height), origin * scale * rotation * translation);\n\nint width = (int)Math.Abs(pos2.X - pos1.X) * 2;\nint height = (int)Math.Abs(pos2.Y - pos1.Y) * 2;\n\nfloat scaleX = (graphics.PreferredBackBufferWidth / width);\nfloat scaleY = (graphics.PreferredBackBufferHeight / height);	0
1848806	1843829	Parameter unexpectedly initialized when invoked from unit test	_c = new CacheImplementationSelector(_listOfImplementations, _stubCacheImplementationSelectorDelegate);	0
10207779	10207658	How to bind DataGridViewColumn to comboBox?	private void BindComboBox()\n{\n  comboBox1.DataSource = dataGridView.DataSource;\n  comboBox1.DisplayMember = "The column Name you want to bind";\n}	0
27501497	27501020	How to find out if there is a connection between two arbitrary vertices in direction graph?	var tryGetPaths = _graph.TreeBreadthFirstSearch(__source__);\nIEnumerable<Edge<YourItemType>> path;\nif (tryGetPaths(__target__, out path))\n{\n    // we have connectivity!\n}	0
6477299	6477281	Click event for radio button	if(radiobutton.Checked)\n   {\n      // Place your code for POPUP\n      mpeQCAttribute.Show();           // mpeQCAttribute is the ModalPopupExtender\n   }	0
6270401	6270374	LINQ Multiple Order By	var sortedPamphlets = db.Pamphlets.Include("Category").Include("Program")\n                        .OrderBy(p => p.Category.CategoryName)\n                        .ThenBy(p => p.PamphletName)\n                        .ToList();	0
31169684	31169598	A better solution for Webscraping	int pos = html.IndexOf("From today's featured article");	0
13821929	13821879	matching and replacing text in a string while keeping non replaced text	//the named group has the name "everythingElse"\nvar regex = new Regex(@"using(?<everythingElse>[^\r\n]+)");\nvar content = new string [] { /* ... */ };\n\nfor(int i = 0; i < content[i]; i++)\n{\n     content[i] = regex.Replace(content[i], "${everythingElse}");\n}	0
2023958	2016804	HR-XML Error, trying to deserialize XML examples	protected static ImportTest.CandidateService.ProcessCandidateType DeserializeProcessCandidate(string path)\n    {\n        CandidateService.ProcessCandidateType processCandidate = null;\n        XmlRootAttribute root = new XmlRootAttribute("ProcessCandidate");\n        XmlSerializer serializer = new XmlSerializer(typeof(CandidateService.ProcessCandidateType), new XmlAttributeOverrides(), new Type[0], root, "http://www.hr-xml.org/3");\n        StreamReader reader = null;\n\n        try\n        {\n            reader = new StreamReader(path);\n            processCandidate = (CandidateService.ProcessCandidateType)serializer.Deserialize(reader);\n            reader.Close();\n        }\n        catch (Exception ex)\n        {\n            reader.Close();\n            throw (new Exception(ex.InnerException.Message));\n        }\n\n        return processCandidate;\n    }	0
21165630	21165029	Find maximum sum leaf to root path in a Binary Tree	1\n   2   3\n311  6    3	0
28394416	28394283	I am making a sudoku on c#	while( d != 0 )	0
30412026	30411562	Parameter names in abstract tupled function	abstract createEmployee: firstName:string * lastName:string -> Employee	0
2333458	2333422	How to define a ConfigurationSection	type="Optima.ReportEngine.ReportEngineConfig, Optima.ReportEngineAssembly"	0
26996699	26996486	My property only has a get, but I want that value to change everytime I call it	class Zwakmonster : IMonster\n{\n    private string mijnNaam;\n    private string mijnKleur;\n    private int lives = 10;\n\n    public string Naam\n    {\n        get { return mijnNaam; }\n        set { mijnNaam = value; }\n    }\n\n    public string Kleur\n    {\n        get { return mijnKleur; }\n        set { mijnKleur = value; }\n    }\n\n    public int Levens\n    {\n        get { return lives; }\n    }\n\n    public void Hit()\n    {\n        lives = lives - 1;\n    }\n}	0
1727440	1727420	C# - Generic interfaces	public interface IMyShape<T>\n{\n   T X { get; }\n   T Y { get; }\n}\n\npublic class IntSquare : IMyShape<int>\n{\n   int X { get { return 100; } }\n   int Y { get { return 100; } }\n}\n\npublic class IntTriangle : IMyShape<int>\n{\n   int X { get { return 200; } }\n   int Y { get { return 200; } }\n}\n\npublic class FloatSquare : IMyShape<float>\n{\n   float X { get { return 100.05; } }\n   float Y { get { return 100.05; } }\n}	0
23584136	23583948	Summing same elements in List<>	foreach (Fruits item in tblFruits.GroupBy(x => x.Name))\n{\n    tblFruitsTotal.Add(new Fruits() \n    { \n        ID = tblFruitsTotal.Any() ? tblFruitsTotal.Max(x=>x.ID) + 1 : 1,\n        Name = item.First().Name, \n        Amount = item.Sum(x => x.Amount) \n    });\n}	0
10313666	10311646	selected changed used to find data in another datagridview store previous value	private void MyErrorGrid_SelectionChanged(object sender, EventArgs e)\n    {\n\n        string getPartSelected;\n\n        getPartSelected = MyErrorGrid.CurrentCell.Value.ToString();\n\n        foreach(DataGridViewRow allrow in ParetoGrid.Rows)\n        {\n            ParetoGrid.Rows[allrow.Index].DefaultCellStyle.BackColor = Color.Empty;\n            ParetoGrid.Rows[allrow.Index].Selected = false;\n        }\n        //might need a do while\n        foreach (DataGridViewRow row in ParetoGrid.Rows)\n        {\n            var cellValue = row.Cells["Keycode"].Value;\n\n            if (cellValue != null && cellValue.ToString() == getPartSelected)\n            {\n                ParetoGrid.Rows[row.Index].DefaultCellStyle.BackColor = Color.Red;\n                ParetoGrid.Rows[row.Index].Selected = true;\n\n\n            }\n        }\n\n    }	0
11870591	11866480	How to implement NOT IN without establishing relationship	var peopleWithOrdersInRange = QueryOver.Of<Order>()\n    .WhereRestrictionOn(x => x.CreatedDate).IsBetween(fromDate).And(toDate)\n    .SelectGroup(x => x.CreatedBy.Id);\n\nvar results = Session.QueryOver<Person>()\n    .WithSubquery.WhereProperty(x => x.Id).NotIn(peopleWithOrdersInRange)\n    .List();	0
24765517	24764828	Find Partial String Matches Using LINQ Without Loops	private List<string> ProcessAuthorizationRoles(List<string> pDefinedRoles, CustomIdentityClass pIdentity)\n{\n    return pIdentity.Roles.FindAll(x => pDefinedRoles.Exists(y => x.Contains(string.format(":{0}", y))));\n}	0
18068138	18068087	How can I implement a dictionary whose value is also a key?	Two-way dictionary	0
10850846	10850745	403 - Forbidden: Access is denied	/admin/	0
5504439	4199976	C# Bitmap BitmapImage bitmapsource	System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96,\n    System.Windows.Media.PixelFormats.Bgr24, null, pFrame, linesize * height,\n    width * 3 ));	0
26192208	26184813	Listview SelectedIndexChanged with MessageBox fires ItemDrag	private void listView1_SelectedIndexChanged(object sender, EventArgs e) {\n        this.BeginInvoke(new Action(() => MessageBox.Show("Okay now")));\n    }	0
5252309	5252207	Want C# program to launch a WPF app	using System.Diagnostics;\n\nProcess myProc;\nmyProc = Process.Start("calc.exe");	0
924132	924019	Rounding issues with allocating dollar amounts across multiple people	0.13    0.133\n 0.13    0.133\n+0.13   +0.133\n_____   ______\n 0.39    0.399 -> 0.40	0
3343771	3341032	During FlowLayoutPanel scrolling, background distorts + flickers	using System;\nusing System.Windows.Forms;\n\nclass MyFlowLayoutPanel : FlowLayoutPanel {\n    public MyFlowLayoutPanel() {\n        this.DoubleBuffered = true;\n    }\n    protected override void OnScroll(ScrollEventArgs se) {\n        this.Invalidate();\n        base.OnScroll(se);\n    }\n}	0
18929716	18929588	replace blank spaces before first word in string, then remove extra blank spaces	private string removeThem(string str)\n{ \n    return String.Join(" ", (str ?? "").Split(new [] { ' ' },\n        StringSplitOptions.RemoveEmptyEntries));\n}	0
23082025	23081510	get all lines from a huge textfile after a string	bool found=false;\nList<String> lines = new List<String>();\nforeach(var line in File.ReadLines(@"C:\MyFile.txt"))\n{\n\n if(found)\n {\n   lines.Add(line);\n }\n if(!found && line.Contains("UNIQUEstring"))\n {\n   found=true;\n }\n\n}	0
818857	818826	Usage of generated Actionscript proxy enum from C#	var imgType:ImageType = new ImageType();\nimgType._imageType = "Png";	0
7603254	7590994	Excel column data type exclusive of the header row	private SpreadsheetGear.ValueType[] GetColumnTypes(IRange range, bool hasHeader)\n{\n    SpreadsheetGear.ValueType[] columnTypes = new SpreadsheetGear.ValueType[range.ColumnCount];\n    for (int i = 0; i < range.ColumnCount; i++)\n    {\n        columnTypes[i] = range[hasHeader ? 1 : 0, i].ValueType;\n    }\n    return columnTypes;\n}	0
6501872	6377922	Querying an IEnumerable for objects with like attributes and within a certain time threshold	var clusters = SharpLearning.Clustering.KCluster(k, iterations, listOfIClusterableObjects);\n\nforeach (var cluster in clusters) {\n    // Process some data.\n    // clusters is a List<Cluster<T>> where your objects can be viewed in the .Members attribute\n}	0
2655317	2655080	How to make tooltip move with mouse (winforms)	toolTip1.Show(_toolTipText, this, new Point(lblRevisionQuestion.Left + e.X + 1, lblRevisionQuestion.Top + e.Y + 1), int.MaxValue);	0
26062363	26062076	Ask user for 5 numbers then add together for total using a loop	using System;\n class SumDoubles\n {\n    static void Main()\n    {   \n        //Declare variables\n        double DblSumTotal = 0;\n        double LIMIT = 0;\n\n\n        //Ask user to input 5 numbers to be added\n        Console.Clear();\n        Console.WriteLine("Enter 5 numbers to be added together.");\n        do \n        {\n            double d;\n            if (!double.TryParse(Console.ReadLine(), out d)) {\n                Console.WriteLine("Format error!!!");\n            } else {\n                DblSumTotal = DblSumTotal + d;\n                LIMIT = LIMIT + 1;\n            }\n\n        } while (LIMIT < 5);\n\n        //Output total\n        Console.WriteLine("The total sum of the 5 numbers is " + DblSumTotal);\n        Console.ReadLine();\n    }   \n}	0
15007202	15005204	Repeated web service calls via a proxy web service - performance	[WebMethod]\npublic static void ImportRecord(MyRecord[] myRecords)\n{\n   try\n   {\n      OpenConnection();\n      for (int counter = 0; counter < myRecords.Length; counter++)\n      {\n         3rdPartyWS.ImportRecord(myRecords[counter]);\n      }\n   }\n   finally\n   {\n      CloseConnection();\n   }\n}	0
3986618	3986580	How to compare two Dictionary<string,int> to find if any of the value has changed?	foreach (var kvp in personalizePatientChartDictionaryOriginal)\n{\n    int value;\n    if (personalizePatientChartDictionary.TryGetValue(kvp.Key, out value))\n    {\n        if (kvp.Value != value)\n        {\n            hasDictionaryChanged = true;\n            break;\n        }\n    }\n}	0
2836884	2828729	How to add a new item in a sharepoint list using web services in C sharp	listService.Url = @"http://server/site/subsite/_vti_bin/Lists.asmx";	0
15347312	15345422	SertiveStack.Text Deserialize json to object always converts to string and behaves strangely with quotes	string json6 = "[\"hello\",\"world\"]";\n\nvar list = json6.FromJson<List<string>>();\nlist.PrintDump();\n\nvar array = json6.FromJson<string[]>();\narray.PrintDump();\n\nvar arrayObj = json6.FromJson<object[]>();\narrayObj.PrintDump();	0
9259618	9259544	Filter memberof groups of user	var filteredGroup = groups.FindAll(item =>\n{\n    return item.Contains("Hey");\n});	0
12014108	12013946	Looking for RegEx to grab element that doesn't match attribute	string foo = @"<bogus><siteMapNode title='Our Clients' url='~/OurClients'>\n                <siteMapNode title='Website Portfolio' url='~/OurClients/Portfolio' />\n                <siteMapNode title='Testimonials' url='~/OurClients/Testimonials' />\n                </siteMapNode>\n\n            <siteMapNode title='Contact' url='~/Contact' />\n            <siteMapNode title='' url='~/Pharmacy' />\n            <siteMapNode url='~/ClinicWebsiteDevelopment' />\n            <siteMapNode url='~/HospitalWebsiteDevelopment' /></bogus>";\n\n\nXDocument doc = XDocument.Parse(foo);\n\nvar elements = doc.Root.Elements("siteMapNode");\nforeach (var elem in elements) {\n    if (elem.Attribute("title") == null)\n        Console.WriteLine("This one doesn't have the attribute!");\n}	0
30676081	30647285	AutoCompleteStringCollection with TextChanged Event	private void AddSearchToDropDown ()\n   {\n      Task.Factory.StartNew (() =>\n      {\n         if (CanAdd && filterTxtBox.Text.Length > 2)\n         {\n            CanAdd = false;\n            Thread.Sleep (4000);\n            this.Invoke(new Action(() =>\n            {\n               filterTxtBox.AutoCompleteMode = AutoCompleteMode.None;\n               m_suggestedTests.Add (filterTxtBox.Text);\n               filterTxtBox.AutoCompleteMode = AutoCompleteMode.Suggest;\n               CanAdd = true;\n             }));\n         }\n      });\n   }	0
9758643	9757127	Issue adding DataRowView to DataGrid with dot in name	DataColumn.ColumnName	0
15089598	15089373	Extract the k maximum elements of a list	static IEnumerable<double> TopNSorted(this IEnumerable<double> source, int n)\n{\n    List<double> top = new List<double>(n + 1);\n    using (var e = source.GetEnumerator())\n    {\n        for (int i = 0; i < n; i++)\n        {\n            if (e.MoveNext())\n                top.Add(e.Current);\n            else\n                throw new InvalidOperationException("Not enough elements");\n        }\n        top.Sort();\n        while (e.MoveNext())\n        {\n            double c = e.Current;\n            int index = top.BinarySearch(c);\n            if (index < 0) index = ~index;\n            if (index < n)                    // if (index != 0)\n            {\n                top.Insert(index, c);\n                top.RemoveAt(n);              // top.RemoveAt(0)\n            }\n        }\n    }\n    return top;  // return ((IEnumerable<double>)top).Reverse();\n}	0
2395007	2394991	How to convert number to next higher multiple of five?	int x = int.Parse(maskedTextBox1.Text)/5;\nint y = Math.Min(Math.Max(x,1),12)*5; // between [5,60]\n// use y as the answer you need	0
3686802	3686644	How to use global variables in ObjectDataSource.SelectMethod?	protected **static** SearchOption search;	0
17462773	17462143	Convert richtextbox text into a stream c#	var stream = new MemoryStream(Encoding.Unicode.GetBytes(richTextBox1.Rtf));	0
24293755	24286116	Xamarin.IOS date format	DateTime d = DateTime.ParseExact("20140713T190000Z","yyyyMMdd'T'HHmmss'Z'",null);	0
18835789	18835588	Get pixel length from PixelFormat	Image.GetPixelFormatSize(image.PixelFormat);	0
17947013	17939524	Obtaining database schema using enterprise library data access block	Database db = DatabaseFactory.CreateDatabase();\nDbConnection conn = db.CreateConnection();\nDataTable dt = conn.GetSchema();	0
4487663	4487642	How to call var from another form in C#	Class A\n{\n        A a ;\n\n   A()\n   {\n        a = new A();\n    }\n}	0
26169975	26153370	Square Connect API Item Creation syntax	post.AddBody(new {\n    name = testname,\n    variations = new object[] {\n        new {\n            name = "Small",\n            pricing_type = "FIXED_PRICING",\n            price_money = new {\n                currency_code = "USD",\n                amount = 400\n            }\n        }\n    },\n    sku = "123"\n});	0
21828417	21700687	Performance of clearing Sort-/GroupDescriptions on ICollectionView	VirtualizingPanel.IsVirtualizingWhenGrouping="True"	0
3095604	3095560	Formatting ip address in C#	string GetFirstIPv4Address()\n{\n    IPAddress[] addressList = Dns.GetHostAddresses(hostname);\n\n    foreach (IPAddress ip in addressList)\n    {\n        if (ip.AddressFamily.ToString() == "InterNetwork")\n        {\n            //This is an IPv4 address\n            return ip.ToString();\n        }\n    }\n    return "127.0.0.1";\n}	0
6104728	6104261	How do I pass any validation control to a method?	public static void AddExceptionMessageAsValidator(Page page, Exception ex, string message, string validationGroup)\n    {\n        CustomValidator exValidator = new CustomValidator();\n        exValidator.IsValid = false;\n        if (message != null)\n            exValidator.ErrorMessage = message;\n        else\n            exValidator.ErrorMessage = ex.Message;\n\n        exValidator.Text = String.Empty;\n\n        if (!String.IsNullOrEmpty(validationGroup))\n            exValidator.ValidationGroup = validationGroup;\n\n        page.Validators.Add(exValidator);\n    }	0
395446	395321	Is it Possible to Make a Generic Control in .Net 3.5?	public partial class MessageControl : MessageControlBase\n{    \n    public MessageControl()    \n    {\n        InitializeComponent();    \n    }\n}\n\npublic class MessageControlBase : MessageBase<Post>\n{}	0
1942458	1942442	Encrypt a filename in C# without including unusable chars in the resulting string	.Replace()	0
20470454	20470389	How to get running applications in windows?	Process[] processes = Process.GetProcesses();\nforeach(Process p in processes)\n{\n    if(!String.IsNullOrEmpty(p.MainWindowTitle))\n    {\n        listBox1.Items.Add(p.MainWindowTitle);\n    }\n}	0
22927679	21135980	Password hashing different salt with same username	byte[] salt1 = new byte[8];\nusing (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())\n  {\n  // Fill the array with a random value.\n  rngCsp.GetBytes(salt1);\n  }	0
15897831	15897796	How to save only a specific item using Entity Framework?	SaveChanges()	0
28614947	28614945	C# Get Startup Project's Assembly Name	string ProjectName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;	0
17379515	17378807	Prevent same child window multiple times in MDI form	Form instance = null;\n\n  // Looking for MyForm among all opened forms \n  foreach (Form form in Application.OpenForms) \n    if (form is MyForm) {\n      instance = form;\n\n      break; \n    }\n\n  if (Object.ReferenceEquals(null, instance)) {\n    // No opened form, lets create it and show up:\n    instance = new MyForm();\n    instance.Show();\n    ...\n  }\n  else {\n    // MyForm has been already opened\n\n    // Lets bring it to front, focus, restore it sizes (if minimized)\n    if (instance.WindowState == FormWindowState.Minimized)\n      instance.WindowState = FormWindowState.Normal; \n\n    instance.BringToFront();\n\n    if (instance.CanFocus) \n      instance.Focus();\n    ...\n  }	0
10556992	10439418	Programmatically encrypt Outlook email using Inspector	private static void addOutlookEncryption(ref Outlook.MailItem mItem) {\n        CommandBarButton encryptBtn;\n        mItem.Display(false);\n        encryptBtn = mItem.GetInspector.CommandBars.FindControl(MsoControlType.msoControlButton, 718, Type.Missing, Type.Missing) as CommandBarButton;\n        if (encryptBtn == null) {\n            //if it's null, then add the encryption button\n            encryptBtn = (CommandBarButton)mItem.GetInspector.CommandBars["Standard"].Controls.Add(Type.Missing, 718, Type.Missing, Type.Missing, true);\n        }\n        if (encryptBtn.Enabled) {\n            if (encryptBtn.State == MsoButtonState.msoButtonUp) {\n                encryptBtn.Execute();\n            }\n        }\n        mItem.Close(Outlook.OlInspectorClose.olDiscard);\n    }	0
31900656	31899976	Is it better to set the SelectedValue of a drop-down list or to set the Selected property of the specific item?	ddl.Items.FindByValue(5) //may return null..\n                        .Selected = True; //throws NullReferenceException	0
20727676	19876173	How to print a .rdlc (SSRS) report as duplex mode?	printDoc.DefaultPageSettings.PaperSize = new PaperSize("PaperA5", 583, 827); \n printDoc.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(0, 0, 0, 0);\n printDoc.PrinterSettings.Duplex = Duplex.Vertical;\n printDoc.PrintPage += new PrintPageEventHandler(PrintPage);\n printDoc.Print();	0
4584830	4584814	Change DataSource in XtraGrid	gridView.PopulateColumns()	0
31937377	31936738	C# Lambda expression with IComparer and Array.Sort (converting from Java to C#)	class PregnancyIndividual : IComparer\n    {\n        int IComparer.Compare(object a, object b)\n        {\n            PregnancyIndividual ind1 = (PregnancyIndividual)a;\n            PregnancyIndividual ind2 = (PregnancyIndividual)b;\n            int res = 1;\n            double fitness1 = ind1.FitnessCalculator.calculateFitness(ind1);\n            double fitness2 = ind2.FitnessCalculator.calculateFitness(ind2);\n            if (fitness1 > fitness2)\n            {\n                return -1;\n            }\n            if (fitness1 == fitness2)\n            {\n                return 0;\n            }\n\n            return res;\n        }    \n    }	0
26336399	26334356	XMLTextReader get children	while (Reader.Read())\n{\nif (Reader.NodeType == XmlNodeType.EndElement)\nbreak;\n\nnodeGuid = Reader.GetAttribute(XmlNodeGuidAttribute);\nmeshGUIDs.Add(nodeGuid);\n}	0
4785510	4785493	Reflection from DTO	PropertyInfo property = typeof(SomeType).GetProperty(fieldName);\nobject value = property.GetValue(instance, null);	0
25288805	25288662	How can I add a SPACE halfway through a string value?	string t = s.Substring(0, 17) + " " + s.Substring(17);	0
15524404	15513827	How to write a page whitelist in an asp.net website	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!Page.IsPostBack)\n        {\n            Dictionary<string,string> allowedUrls = LoadAllowedURLs();\n\n            if (!allowedUrls.ContainsKey(Request.Path))\n            {\n                Response.Redirect("Some_default_redirect_page.aspx");   \n            }\n        }\n\n    }	0
28273568	28273062	Get text from Input field in Unity3D with C#	public class test : MonoBehaviour {\n    void Start ()\n    {\n        var input = gameObject.GetComponent<InputField>();\n        var se= new InputField.SubmitEvent();\n        se.AddListener(SubmitName);\n        input.onEndEdit = se;\n\n        //or simply use the line below, \n        //input.onEndEdit.AddListener(SubmitName);  // This also works\n    }\n\n    private void SubmitName(string arg0)\n    {\n        Debug.Log(arg0);\n    }\n}	0
31875846	31875025	Convert int timestamp to DateTime using Entity Framework	public partial class MyEntity\n{\n    public DateTime Date\n    {\n        get { return ConvertToDateTime(this.IntDate); }\n    }\n}	0
34483524	34483471	Null exception at removing a child node from a tree view node	for(int i = tn.Nodes.Count - 1 ; i >= 0 ; i--)\n{\n    TreeNode item = tn.Nodes[i];\n   //....\n}	0
14650082	14649972	How can I have different protection levels for a struct inside a class in C#?	struct MyStruct\n{\n    public readonly int Field1;\n    public readonly int Field2;\n\n    public MyStruct(int i, int j)\n    {\n        Field1 = i;\n        Field2 = j;\n    }\n}	0
29390305	29390076	How do I create Optional Type injection for a base class?	public Subclass {\n   private BaseClass bc1 = null;\n   private BaseClass<SomeType> bc2 = null;\n   private dynamic SomeValue = null;\n   public Subclass(){\n     //I still have base class operation ability, but now...\n     bc2 = new BaseClass<SomeType>();\n     SomeValue = bc2.Method();\n }	0
33594887	33594802	How can i display in a middle of a progressBar some text?	if ( progressBar1.Value == 100% )\n{\n   label1.Text = "Process finished";\n}	0
1205531	1205077	C# Detect Remote Application Failure	bool keepSending = true; // set this to false to shut down the thread\nvar hb = new Thread(() => \n    {\n         while (true)\n             SendHeartbeatMessage();   \n    }).Start();	0
27600584	27600379	How to use c# variable with sql server query?	Query = "SELECT DISTINCT T1.* FROM mail_Reply T2 JOIN mail_Messages T1 ON (T2.[" \n          + messageId + "]=T1.[" + messageId + "] OR T2.[" + parrentId + "]=T1.[" \n          + messageId + "])";\n    return ExecuteDataTable();	0
3935489	3935431	Databinding a label in C# with additional text?	private string _bindToValue = "Value from DataSource";\n    private string _customText = "Some Custom Text: ";\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        var binding = new Binding("Text",_bindToValue,null);\n        binding.Format += delegate(object sentFrom, ConvertEventArgs convertEventArgs)\n                              {\n                                  convertEventArgs.Value = _customText + convertEventArgs.Value;\n                              };\n\n        label1.DataBindings.Add(binding);\n    }	0
21851683	21850963	How to use Open Text Summarizer API?	SummarizerArguments sumargs = new SummarizerArguments\n                                          {\n                                              DictionaryLanguage = "en",\n                                              DisplayLines = sentCount,\n                                              DisplayPercent = 0,\n                                              InputFile = "",\n                                              InputString = OriginalTextBox.Text // here your text\n                                          };\nSummarizedDocument doc = Summarizer.Summarize(sumargs);\nstring summary = string.Join("\r\n\r\n", doc.Sentences.ToArray());\n// do some stuff with summary. It is your result.	0
15896184	15893495	Sitecore - Update workflow history	public bool Execute(Item item, ID commandId, string comment)\n{\n    var workflowId = item[FieldIDs.Workflow];\n\n    if (String.IsNullOrEmpty(workflowId))\n    {\n        throw new WorkflowException("Item is not in a workflow");\n    }\n\n    IWorkflow workflow = item.Database.WorkflowProvider.GetWorkflow(workflowId);\n\n    var workflowResult = workflow.Execute(commandId.ToString(), item, comment, false, new object[0]);\n    if (!workflowResult.Succeeded)\n    {\n        var message = workflowResult.Message;\n        if (String.IsNullOrEmpty(message))\n        {\n            message = "IWorkflow.Execute() failed for unknown reason.";\n        }\n        throw new Exception(message);\n    }\n    return true;\n}	0
8009393	8009356	How to always run the project instead of displayed file (.aspx), with F5, in VS10, when building af website	default.aspx	0
25056580	25056350	use DateTime or String in .net Web Service method sigs	TimeZoneInfo.ConvertTimeToUtc(thisTime, TimeZoneInfo.Local)\n\nDateTime.UtcNow	0
10639927	10363015	How to get the project directory from a Visual Studio Add-in	string projectDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);	0
590467	589831	Getting Matched Values in the Same Group, RegEx C#	Regex re = new Regex(@"[<>]\s*(?<name>\w+)");\nMatchCollection matches = re.Matches("type_name \"abc\" < text1 > text2 >  \"ab123\" < text3");            \nforeach (Match m in matches)\n{\n   string name = m.Groups["name"].Value;\n}	0
17592696	17592147	How to build a hierarchy with use Linq to object?	public void SomeMethod() {\n     // here you get your `list`\n     var tree = GetTree(list, 0);\n}\n\npublic List<Tree> GetTree(List<Personal> list, int parent) {\n    return list.Where(x => x.ParentId == parent).Select(x => new Tree {\n        Id = x.Id,\n        Name = x.Name,\n        List = GetTree(list, x.Id)\n   }).ToList();\n}	0
29611041	29601089	Issues with getting records from azure storage by timestamp interval	int count = 0;\ndo\n{\n    TableQuerySegment<DynamicTableEntity> querySegment =\n        await currentTable.ExecuteQuerySegmentedAsync(query, token);\n    token = querySegment.ContinuationToken;\n\n    foreach (DynamicTableEntity entity in querySegment)\n    {\n        ++count;\n    }\n}\nwhile (token != null);	0
2221667	2221629	How to get number from a string	string numString;\nforeach(char c in inputString)\n    if (Char.IsDigit(c)) numString += c;\nint realNum = int.Parse(numString);	0
12349421	12349333	Filling email template from C# program	Process.Start("mailto:someone@example.com?cc=someone_else@example.com&subject=This%20is%20the%20subject&body=This%20is%20the%20body");	0
17487033	17486834	How to get IP of computer on lan if you have the computers name, using c#	String name = "Name";\nIPHostEntry ipHostInfo = Dns.GetHostEntry(name);            \n// OR you can get the name of the current computer using \n// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());                \n\n// Get the first IPv4 address\nIPAddress ip = ipHostInfo.AddressList.Where(n => n.AddressFamily == AddressFamily.InterNetwork).First();	0
25139785	25139731	Nunit Assert List<SomeObject> contains unique values	.Equals()	0
12655272	12655225	How do you pass in the get; method of a property to a method that accepts a Func?	GetFish(() => getFish);	0
18786753	18783832	Using ASP.Net SqlMembershipProvider with multiple databases	MembershipUser user = Membership.Providers["SPECIFICPROVIDERNAME"].GetUser(username, false);	0
7213949	7213836	extracting the common prefixes from a list of strings	var list = new List<String> {\n    "abc001", "abc002", "abc003", "cdef001",\n    "cdef002", "cdef004", "ghi002", "ghi001"\n};\nvar prefixes = list.Select(x = >Regex.Match(x, @"^[^\d]+").Value).Distinct();	0
12086075	10755968	Using Reflection to create a Mock of an interface that is unknown during buildtime	var method = typeof(MockRepository).GetMethod("GenerateMock").MakeGenericMethod(semiknown.FieldType);\nvar mock_semiknown = method.Invoke(null, null);	0
28981108	28962133	Value does not fall within the expected range windows store app	var orderData = JsonConvert.DeserializeObject<OrderRootClass>(response);\n\nOrderListView.ItemsSource = orderData.orders; // here	0
16895751	16895536	C# int to char conversion in streamwriter	FileStream binaryWriter = new FileStream(this.outputFilePath, FileMode.Create,FileAccess.ReadWrite);\n//some code here\nbinaryWriter.WriteByte(0xFE);\n//some code here\nbinaryWriter.Close();	0
3054390	3054346	How to return a value based on the type of the generic T	public T Get<T>(string key) { \n   object value = null;\n   if ( typeof(T) == typeof(int) ) { \n     value = 11011;\n   } else if ( typeof(T) == typeof(string) ) { \n     value = "hello";\n   }\n   return (T)value;\n}	0
11857158	11857015	Getting image in selected listview Item?	private void listView1_DoubleClick(object sender, EventArgs e)\n{\n    foreach (ListViewItem itm in listView1.SelectedItems)\n    {\n        int imgIndex = itm.ImageIndex;\n        if ( imgIndex >= 0 && imgIndex < this.imageList1.images.Count)\n        {\n            pictureBox1.Image = this.imageList1.images[imgIndex];\n        }\n    }\n}	0
11690170	11690028	Find a pattern in string and replace it	class Program\n{\n    static void Main(string[] args)\n    {\n        string data = @"This is a long text \n@[Alphanumeric1](Alphanumeric2:Alphanumeric3) again long text \n@[Alphanumeric11](Alphanumeric22:Alphanumeric33) again long text\n@[Alphanumeric111](Alphanumeric222:Alphanumeric333)";\n\n        Debug.WriteLine(ReplaceData(data));\n    }\n\n    private static string ReplaceData(string data)\n    {\n        return Regex.Replace(data, @"@\[.+?\]\(.*?:(.*?)\)", match => match.Groups[1].ToString());\n    }\n}	0
17422980	17422938	SHA256 adds \n into value	byte[] hash = x.ComputeHash(bytes);\n    string hashString = string.Empty;\n    foreach (byte x in hash)\n    {\n        // Turn each byte into it's hex equivalent (00 to FF).\n        hashString += String.Format("{0:x2}", x);\n    }\n    return hashString;	0
31398706	31398655	PHP $_GET['something'] equivalent in C#	string test = Request.QueryString["something"];\n        if (test == "today")\n        {\n            // we've got test logic\n        }\n        else\n        {\n           test = string.Empty;\n        }	0
14223607	14223379	Most efficient way of reading a BinaryFormatter serialized object from a NetworkStream?	using (var networkStream = client.GetStream()) //get access to stream\n{\n    while(!networkStream.EndOfStream) //still has some data\n    {\n        var buffer = new byte[1234]; //get a buffer\n        await SourceStream.ReadAsync(result, 0, buffer); //read from network there\n\n        //om nom nom buffer     \n        Foo obj;\n        using(var ms = new MemoryStream()) //process just one chunk\n        {\n             ms.Write(buffer, 0, buffer.Length);\n             var formatter = new BinaryFormatter();\n             obj = formatter.Deserialize(ms);   //desserialise the object        \n        } // dispose memory\n\n        //async send obj up for further processing\n    }\n}	0
6364407	6358001	How to Enable Trusted Applications to Run Inside the Browser, silverlight5.0	Enable running application out of browser	0
9556136	8655988	overriding default format provider of a culture	decimal.ToString("c")	0
10518756	10518694	Adding a row to a google spreadsheet	ListEntry row = new ListEntry();\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "firstname", Value = "Joe" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "lastname", Value = "Smith" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "age", Value = "26" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "height", Value = "176" });	0
16816301	16816082	C# naming convention for initialized variable - are there special cases?	WebImage uploadImage = WebImage.GetImageFromRequest();	0
29414933	29414877	Strange exception: String was not recognized as a valid DateTime	DateTime dateTime = DateTime.ParseExact("02-02-2015  10:00:00.000", \n                    "dd-MM-yyyy HH:mm:ss.fff", \n                    CultureInfo.InvariantCulture, \n                    DateTimeStyles.AllowInnerWhite);	0
1698783	1698724	How can I implement an interface that can take many object types	public interface IViewModel<T>\n{\n    void Map(T domainObject);\n}\n\npublic class CarViewModel : IViewModel<Car>\n{\n    public Map(Car domainObject) { ... }\n}	0
8072648	8072583	Filling a ComboBox with LINQ on Silverlight (WPF)	string XmlString = e.Result;\n\n    XDocument elem = XDocument.Load(XmlReader.Create(new StringReader(XmlString)));\n\n    var feedLanguages = \n            (from nod in elem.Descendants("languages_index")\n            select new Language_Index\n            {\n                    Name = nod.Element("item").Attribute("name").Value,\n                    Status = nod.Element("item").Attribute("status").Value,\n                    Prefix = nod.Element("item").Attribute("prefix").Value\n            }).ToList();\n\n    LanguageSelector.ItemsSource = feedLanguages;	0
30139035	30138180	How to create connection with the database in another computer using a SQL Server database?	string _conStr =  @"Data Source=198.162.10\YourServername;Initial\nCatalog=YourDatabaseName;Connect Timeout=50;Persist Security Info=True;\nUser ID=YourUserName;Password=YourPassword";	0
5024729	5024587	How to select category of Bing News Results?	request.News = new NewsRequest();	0
7654450	7650879	Get value of default report parameters after running ReportExecutionService.render()	//get the SOAP call to the SSRS service started\n        ReportExecutionService rs = new ReportExecutionService();\n\n        //this will contain all of the details needed for execution\n        ExecutionInfo execInfo = rs.LoadReport(reportLocation, historyID);\n\n        //and here are the default value(s)\n        execInfo.Parameters[i].DefaultValues[]	0
21920384	21920332	Selecting array values from specific indexes order by index array	var results = ind.Select(i => xs[i]).ToArray();	0
13951117	13951062	Load a (0/1) string into a bit array	var res = new BitArray(str.Select(c => c == '1').ToArray());	0
7904129	7902799	Enterprise Library 5.0: Work with many categories in logs	builder.ConfigureLogging()\n         .WithOptions.DoNotRevertImpersonation()\n         .LogToCategoryNamed("Category1")\n             .SendTo.FlatFile("MyMessages1")\n             .FormatWith(new FormatterBuilder()\n                .TextFormatterNamed("Text Formatter 1").UsingTemplate(FORMAT_TEXT))\n             .ToFile(path)\n         .LogToCategoryNamed("Category2")\n             .SendTo.SharedListenerNamed("MyMessages1");	0
15780397	15780322	multi select ctrl+button click at runtime	List<TControl> selectedControls = new List<TControl>();\n\nprivate void TControl_Click(object sender, EventArgs e)\n{\n    if ((ModifierKeys & Keys.Control) == 0)\n        return;\n\n    TControl tc = (TControl)sender;\n    if (selectedControls.Contains(tc))\n        return; // you can remove control here\n\n    selectedControls.Add(tc);\n}	0
18100872	18100783	How to convert a list into data table	public static DataTable ToDataTable<T>(List<T> items)\n{\n        DataTable dataTable = new DataTable(typeof(T).Name);\n\n        //Get all the properties\n        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n        foreach (PropertyInfo prop in Props)\n        {\n            //Setting column names as Property names\n            dataTable.Columns.Add(prop.Name);\n        }\n        foreach (T item in items)\n        {\n           var values = new object[Props.Length];\n           for (int i = 0; i < Props.Length; i++)\n           {\n                //inserting property values to datatable rows\n                values[i] = Props[i].GetValue(item, null);\n           }\n           dataTable.Rows.Add(values);\n      }\n      //put a breakpoint here and check datatable\n      return dataTable;\n}	0
22403505	22403347	Methods signatures in a parent class that don't have to be overriden?	public abstract class A : OriginalBaseClass\n{\n    protected override void FilterByLetter(char a)\n    {\n        // Don't do anything\n    }\n}\n\npublic abstract class B : OriginalBaseClass\n{\n    protected override void FilterByLetter(char a, char b)\n    {\n        // Don't do anything\n    }\n}\n\npublic class ClassThatNeedsOnlyTwoParameterOverload : A\n{\n    protected override void FilterByLetter(char a, char b)\n    {\n        // Add necessary code\n    }\n}\n\npublic class ClassThatNeedsOnlyOneParameterOverload : B\n{\n    protected override void FilterByLetter(char a)\n    {\n        // Add necessary code\n    }\n}	0
24356499	24356466	Making A Beep in C# WPF	SystemSounds.Beep.Play();	0
25000944	25000104	Resolving xml namespace from attributes values	items.Where(i => \n  baseNs  + "A" == \n  i.GetNamespaceOfPrefix(i.Attribute(xmlInstanceNs + "type").Value.Split(new Char[] { ':' })[0]) + "A")	0
20975708	20962578	MySQL Using Old Auth Method	SET SESSION old_passwords=0; \nSET PASSWORD FOR userID=PASSWORD('password');\n\nSET SESSION old_passwords=false; \nSET PASSWORD FOR userID=PASSWORD('password');	0
4526605	4526580	open video in fullscreen mode 	FullScreenMode = True	0
33064452	33063418	simulate keyboard input / insert string into textarea (adwords)	function setKeywordText(text) {\n    var el = document.getElementById("gwt-debug-keywords-text-area");\n    el.value = text;\n    var evt = document.createEvent("Events");\n    evt.initEvent("change", true, true);\n    el.dispatchEvent(evt);\n}\n\nsetKeywordText("test");	0
23253859	23253462	Parse XML and get elements from it using C#	foreach (XmlNode host in hosts) \n{\n    var hostname = ((XmlElement) host.SelectSingleNode("hostnames/hostname")).GetAttribute("name");\n    var ipv4Address = ((XmlElement) host.SelectSingleNode("address[@addrtype='ipv4']")).GetAttribute("addr");\n    var vendor = ((XmlElement) host.SelectSingleNode("address[@addrtype='ipv6']")).GetAttribute("vendor");\n    // Add to list\n}	0
33688528	27216470	How to update primary key values of first table into foreign keys in the second table (Entity framework code first model)?	person.Memberships = new List<Membership> { m };	0
21647760	21647587	A HTML page is downloaded instead of a ZIP file	WebClient webClient = new WebClient();\nwebClient.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");\nwebClient.Headers.Add(HttpRequestHeader.Referer, "http://www.tneu.edu.ua/study/timetable/");\nwebClient.DownloadFile("http://www.tneu.edu.ua/engine/download.php?id=801", "local.zip");	0
3103859	3103317	How to populate a gridview with database data help?	DataSource = reader	0
20634504	20634024	Delete 2 tables with FK rlsp through WCF	DELETE FROM VenueAvailabilities WHERE VenueId = @VenueId;	0
18125599	18125293	Parsing array in JSON using ASP.NET C#	// Parse JSON\nJObject o = JObject.Parse(json);	0
3466615	3466551	How to remove nulls from byte array?	var usefulBuffer = RecvBuffer2.SkipWhile(x => x == 0).ToArray()	0
3474169	3472388	Determine the bounding rect of a WPF element relative to some parent	public static Rect BoundsRelativeTo(this FrameworkElement element,\n                                         Visual relativeTo)\n{\n  return\n    element.TransformToVisual(relativeTo)\n           .TransformBounds(LayoutInformation.GetLayoutSlot(element));\n}	0
18685079	18684947	thousand separator for integer in formatString	{Binding StringFormat={}{0:N0}}	0
22047030	21548828	C# Serial Port reading HEX data	SerialPort sp = (SerialPort) sender;\n// string s = sp.ReadExisting();\n// labelSerialMessage.Invoke(this.showSerialPortDelegate, new object[] { s });\n\nint length = sp.BytesToRead;\nbyte[] buf = new byte[length];\n\nsp.Read(buf, 0, length);\nSystem.Diagnostics.Debug.WriteLine("Received Data:" + buf);\n\nlabelSerialMessage.Invoke(this.showSerialPortDelegate, new object[] { \n    System.Text.Encoding.Default.GetString(buf, 0, buf.Length) });	0
17255992	17255662	how to reload an aspx page within an iframe when click event triggers from the control within an iframe	string script = "this.window.parent.location=this.window.parent.location;this.window.close();";\n        if (!ClientScript.IsClientScriptBlockRegistered("REFRESH_PARENT"))\n            ClientScript.RegisterClientScriptBlock(typeof(string), "REFRESH_PARENT", script, true);	0
5700694	5700631	How do I use command line arguments in my C# console app?	using System;\n\npublic class CommandLine\n{\n   public static void Main(string[] args)\n   {\n       for(int i = 0; i < args.Length; i++)\n       {\n           if( args[i] == "-throw" )\n           {\n               // call http client args[i+1] for URL\n           }\n       }\n   }\n}	0
3964713	3964599	Setting the time programatically in Windows 7	public class Program \n{\n    public struct SystemTime\n    {\n        public ushort Year;\n        public ushort Month;\n        public ushort DayOfWeek;\n        public ushort Day;\n        public ushort Hour;\n        public ushort Minute;\n        public ushort Second;\n        public ushort Millisecond;\n    };\n\n    [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]\n    public extern static bool Win32SetSystemTime(ref SystemTime st);\n\n    public static void Main(string[] args)\n    {\n        SystemTime st = new SystemTime\n        {\n            Year = 2010, Month = 10, Day = 18, Hour = 16, Minute = 12, DayOfWeek = 1\n        };\n    }\n}	0
3383401	3383307	C# Storing original positions of Tab Pages within a Tab Control	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        for (int page = 0; page < tabControl1.TabCount; ++page)\n            tabControl1.TabPages[page].Tag = page;\n    }\n\n    private List<TabPage> hiddenPages = new List<TabPage>();\n\n    public void ShowTab(TabPage page) {\n        int pos = (int)page.Tag;\n        int insertPoint;\n        for (insertPoint = 0; insertPoint < tabControl1.TabCount; ++insertPoint) {\n            if (pos <= (int)tabControl1.TabPages[insertPoint].Tag) break;\n        }\n        tabControl1.TabPages.Insert(insertPoint, page);\n        hiddenPages.Remove(page);\n    }\n}	0
8719121	8719034	Using DeflateStream in C++?	namespace io = boost::iostreams;\n\nstd::ifstream file("hello.z", std::ios_base::binary);\nio::filtering_streambuf<io::input> in;\nin.push(io::zlib_decompressor());\nin.push(file);\nio::copy(in, std::cout);	0
9013924	9013804	Get Registry Value C#	const string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background";\nusing (var hklm64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))\nusing (var key = hklm64.OpenSubKey(keyPath))\n{\n    var value = (int)key.GetValue("OEMBackground", 2);\n}	0
33399904	33399777	How do I add another method?	using System.Diagnostics;\n\nStopwatch stopwatch = new Stopwatch();\nusing (var writer = new StreamWriter(filename, true))\n{\n    foreach (string website in lstWebSites)\n    {\n        for (var i = 0; i < 4; i++)\n        {\n\n            MyWebRequest request = new MyWebRequest();\n            stopwatch.Start();\n            request.Request();\n            stopwatch.Stop();\n            Console.WriteLine("Time elapse: {0}", stopwatch.Elapse);\n            stopwatch.Restart();\n        }\n    }\n}	0
9653626	9653494	Associate values between two lists with LINQ?	List<Person> newList = (from master in listMaster\n                        from list in myList\n                        where master.id == list.id\n                        select master).ToList<Person>();	0
24116922	24116414	Parsing a feed in C#	XmlDocument xdoc = new XmlDocument();\n        xdoc.Load("http://scotjobsnet.co.uk.ni.strategiesuk.net/testfeed.xml");\n        if (xdoc != null)\n        {\n            XmlElement root = xdoc.DocumentElement;\n            XmlNodeList xNodelst = root.SelectNodes("job");\n            foreach (XmlNode node in xNodelst)\n            {\n                string location = node.SelectSingleNode("location").InnerText;\n                Response.Write("<br/> location = " + location);\n            }\n        }	0
8566047	8565982	Trim string from beginning to substring c#	string huh = "ok \r\n *S 38773 get 3042";\nstring trimmed = huh.Substring(huh.IndexOf("*S"));	0
21974501	21964704	How to display property from FK obj but edit the ID when editting the datafield?	public JsonResult EmployeeJqGridDataRequested()\n{\n      var bugGridModel = new BugJqGridViewModel();\n\n      var db = new bugContext();\n      var bugs = from b in db.Bugs\n                 join bt in db.BugTypes on b.BugTypeId equals bt.BugTypeId\n                 join bs in db.BugStati on b.BugStatusId equals bs.BugStatusId\n                 select new { b.BugId, bt.BugTypeName, bs.BugStatusName,b.DateReported,b.Description };\n      return bugGridModel.Grid.DataBind(bugs);\n}	0
18820267	18820101	WcfTestClient - Sequence contains no elements [When value is null]	public PlayerActionResult DoAction(PlayerActionType type, int uid);\npublic PlayerActionResult DoAction(PlayerActionType type, int uid, string pparam);\npublic PlayerActionResult DoAction(PlayerActionType type, int uid, string pparam, int  amount);\n//etc...	0
20058162	20058116	How can you fire the Button Click event without actually clicking the button?	Cancel(null,null)	0
14807398	14807107	How to determine which column is dragged in datagridview in c# winform	private void dataGridView1_MouseUp(object sender, MouseEventArgs e)\n    {\n        var hitTest = dataGridView1.HitTest(e.X, e.Y);\n        string colDragged = dataGridView1.Columns[hitTest.ColumnIndex].Name;\n        MessageBox.Show("Column Dragged is " + colDragged.ToString());\n    }	0
24963115	24959184	Windows phone app with many image - best way?	Working with resource files directly	0
16835010	16828221	Prevent alert message while scrapping	[DllImport("user32.dll", SetLastError = true)]\n    static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);\n    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]\n    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\n    private void Form1_Deactivate(object sender, EventArgs e)\n    {\n        IntPtr hwnd = FindWindow(null, "Message from webpage");\n        hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Button", "OK");\n        uint message = 0xf5;\n        SendMessage(hwnd, message, IntPtr.Zero, IntPtr.Zero);\n    }	0
7254969	7254835	TabIndex changed to Enter for all forms in C#	private void Form_KeyDown(object sender, KeyEventArgs e)\n{\n    if(Keys.Enter == e.KeyCode) \n    {\n       SendKeys.Send("{TAB}");\n       e.Handled = true;//set to false if you need that textbox gets enter key\n    }\n}	0
14688725	14688539	How to calculate total amount?	public void Quantity_TextChanged(object sender, KeyEventArgs e)\n{\n      var total = Price.Text * Quantity.Text;  // store the price * the quantity in the total variable\n\n      MessageBox.Show(total);  // show the total in a message box\n}	0
7171195	7171131	How to get error message when retriving data from db, but no values there	if (dr == null || !dr.HasRows) \n{\n//NO record found\n   lblError.Text ="No Records Found!";\n}\nelse\n{\n//Record Found SUCCESS!\nwhile(dr.Read())\n{\n  textBox1.text=dr[0].ToString();\n  textBox2.text=dr[0].ToString();\n  textBox3.text=dr[0].ToString();\n}\n\n}	0
8190510	8190493	Inherit the calling class's variables	private class ClassB\n  {\n     private readonly ClassA _owner;\n\n     public ClassB(ClassA owner)\n     {\n          _owner = owner;\n     }\n\n     public DoSomething()\n     {\n     }\n  }	0
8421448	8421384	how to implement Collection object	public ObservableCollection<ParserClass> GetCollection(string[] baa)\n{\n  var result = new ObservableCollection<ParserClass>();\n  foreach(string foo in baa)\n  {\n    var data = new ParserClass(foo);\n    result.Add(data);\n  }\n  return result;\n}\n\npublic class ParserClass \n{\n  public ParserClass (string baa)\n  { \n    //..\n  }\n\n  public string pro1 \n  {\n    get { /* etc */ } \n  }\n}	0
1957545	1957514	how to access all public variables in the class sequentially?	FieldInfo [] fields = typeof(YourClass).GetFields(BindingFlags.Public | BindingFlags.Instance);	0
33884732	33883056	For loop to Populate Textblocks	for (int i = 1; i < 41; i++)\n{\n    TextBlock tb = (this.FindName(string.Format("textblock_{0}", i)) as TextBlock);\n    tb.Text = array[i].ToString();\n}	0
8258918	8258876	How to check the first two values of a string	if (!string.IsNullOrEmpty(strNewTel)\n    && (strNewTel.StartsWith("06")\n        || strNewTel.StartsWith("07")) {\n\n}	0
32613129	32609730	Converted From VB.NET to C# - Not Returning Values Correctly	[DllImport("mykaddll.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]\n        public static extern int HolderName([Out] StringBuilder dBuff);\n\n        //....\n\n        StringBuilder sbBuff = new StringBuilder(200);\n        res = HolderName(sbBuff);\n        buf = sbBuff.ToString().Trim();\n        ShowMsg("HolderName():" + (res == 0 ? "OK:" + buf : "FAIL"));	0
5202304	5202244	Pass a Table Type to a Stored Proc from c#?	SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(\n    "@tvpNewCategories", addedCategories);\ntvpParam.SqlDbType = SqlDbType.Structured;\ntvpParam.TypeName = "dbo.CategoryTableType";	0
8410642	8409867	Reset DataGridView formatting to default	var ds = dgv.DataSource;\ndgv.DataSource = null;\ndgv.DataSource = ds;	0
3766825	3766813	make description for a property	public class FooAttribute : Attribute\n{\n    public string Description { get; set; }\n}\n\npublic class Bar\n{\n    [Foo(Description = "Some description")]\n    public string BarProperty { get; set; }\n}\n\npublic class Program\n{\n    static void Main(string[] args)\n    {\n        var foos = (FooAttribute[])typeof(Bar)\n            .GetProperty("BarProperty")\n            .GetCustomAttributes(typeof(FooAttribute), true);\n        Console.WriteLine(foos[0].Description);\n    }\n}	0
21964751	21964627	Create and Save an image which is stored as varbainary variable with sql in a specified directory in c#	public static void ByteArrayToImage(byte[] imgByte)\n{\n    MemoryStream ms = new MemoryStream(imgByte);\n    Image img = Image.FromStream(ms);\n    img.Save(@"C:\imageTest.png");\n}	0
34066881	34062640	Deploy DLL automaticaly on build	packages\GeckoFX.1.0.4\output	0
1380495	1380437	How can I bind to a sub-property of a specific item in a List<T>?	ledVideoActiveChannel1.DataBindings.Add("LedOn", _myDevice.VideoChannels[0], "VideoActive");\nledOutOfRangeChannel1.DataBindings.Add("LedOn", _myDevice.VideoChannels[0], "OutOfRange");	0
5174430	5169841	MSBuild: define subprojects build configuration in BuildEngine	BuildPropertyGroup bpg = new BuildPropertyGroup ();\nbpg.SetProperty ("Configuration", "Release");\nengine.GlobalProperties = bpg;	0
6309502	6309398	How to make this simple SQL query into a Linq Statement?	var query = from ds in context.DataSheets \n             where ds.IsParent == true \n             && ds.RevisionNum == context.DataSheets.Where(\n                                  ds => ds.DataDefinitionId == 34).Max(\n                                  ds => ds.RevisionNum)	0
31267627	31262596	XML&WCF POST request: some parameters are read, other not	[DataContract]\npublic class WrapClienti\n{ \n    [DataMember(Order=1)]\n    public string CAP { get; set; } \n\n    [DataMember(Order=2)]\n    public string PROV { get; set; } \n\n    ...etc\n}	0
25558790	25558614	Simple JSON read in C# (was using Java - need it in .NET)	JObject jObject = JObject.Parse(result);\nstring bearerToken = jObject.Value<string>("access_token");	0
11651550	11651388	How to get a site element value?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.Load(//Load document);\n\nvar isLive = doc.DocumentNode.Descendants("span").Where(d => d.Attributes.Contains("id") && d.Attributes["id"].Value.Contains("isLive")).SingleOrDefault();\n\nstring result = isLive.InnerText;	0
11341997	11341961	How to pass value of C# variable to javascript?	if(s1 == "Computer" )  \n   { \n     sb.Append("<tr><td>"+s1+"</td></tr>"); \n   }	0
2221540	2221407	Repository and Specification pattern	bannerRepository.Find.IsAvailableForFrontend.IsSmallMediaBanner.Exec()	0
27973361	27973257	Subtracting days from a date using linq	inDate = inDate.AddDays(-daysPrior)\nvar query = dataContext.Where(x => x.SomeDate >= inDate)	0
737940	737917	All Enum items to string (C#)	string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));	0
1984482	1984406	Unable to cast from object array to a string array	Array.ConvertAll	0
670399	664879	How to find empty port to start WCF web ServiceHost	public static bool TryPortNumber(int port)\n{\ntry\n{\n\nusing (var client = new System.Net.Sockets.TcpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))\n{\nreturn true;\n}\n}\ncatch (System.Net.Sockets.SocketException error)\n{\nif (error.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse /* check this is the one you get */ )\nreturn false;\n/* unexpected error that we DON'T have handling for here */\nthrow error;\n}\n}	0
10414382	10414268	In ASP.NET/VB.NET, how do I declare Properties/Events such as IsPostBack/Init on an interface that a user control will implement?	Public Class MyPage\n    Inherits Page\n    Implements IView\n\n    Public ReadOnly Property IsPostBack() As Boolean Implements IView.IsPostBack\n        Get\n            Return MyBase.IsPostBack\n        End Get\n    End Property\nEnd Class\n\nPublic Interface IView\n    Public ReadOnly Property IsPostBack() As Boolean\nEnd Interface	0
11458356	11453153	How to clump a series of messages	(M/N)*(max(1-slider/max)+k*(slider/max)cosine(PI*N/T))	0
4913359	4913331	How to query an XML document with LINQ?	var businesses = (\n    from node in doc.Descendants(ns + "businessEntity")\n    let legalName = node.Element(ns + "legalName")\n    let abn = node.Element(ns + "ABN")\n    // etc...\n    select new\n    {\n        LegalName = new\n        {\n            EffectiveFrom = (string)legalName.Element(ns + "effectiveFrom"),\n            GivenName = (string)legalName.Element(ns + "givenName"),\n            FamilyName = (string)legalName.Element(ns + "familyName"),\n        },\n        Abn = new\n        {\n            IdentifierValue = (string)abn.Element(ns + "identifierValue"),\n            IsCurrentIndicator = (string)abn.Element(ns + "isCurrentIndicator"),\n            ReplacedFrom = (string)abn.Element(ns + "replacedFrom"),\n        },\n        // etc...\n    }).ToList();\n\n\nConsole.WriteLine(businesses[0].LegalName.GivenName);\nConsole.WriteLine(businesses[0].Abn.IsCurrentIndicator);	0
31789600	31789404	make xml from result of wcf service's response	System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());\n\nx.Serialize(Console.Out,p);\nConsole.WriteLine();\nConsole.ReadLine();	0
4890831	4890472	C#/Salesforce: Must Constrain Generic, Cannot Constrain Generic	class LeadReader: SalesforceReader<SalesforceUtilities.Salesforce.Lead, object[]>	0
14546510	14546290	How to return multiple Models from Service Layer?	List<Page> Pages	0
278791	278768	How to detect a truncated file in C#	private void myForm_Load(object sender, EventArgs e)\n{\n    var fileWatcher = new System.IO.FileSystemWatcher();\n\n    // Monitor changes to PNG files in C:\temp and subdirectories\n    fileWatcher.Path = @"C:\temp";\n    fileWatcher.IncludeSubdirectories = true;\n    fileWatcher.Filter = @"*.png";\n\n    // Attach event handlers to handle each file system events\n    fileWatcher.Changed += fileChanged;\n    fileWatcher.Created += fileCreated;\n    fileWatcher.Renamed += fileRenamed;\n\n    // Start monitoring!\n    fileWatcher.EnableRaisingEvents = true;\n}\n\nvoid fileRenamed(object sender, System.IO.FileSystemEventArgs e)\n{\n    // a file has been renamed!\n}\n\nvoid fileCreated(object sender, System.IO.FileSystemEventArgs e)\n{\n    // a file has been created!\n}\n\nvoid fileChanged(object sender, System.IO.FileSystemEventArgs e)\n{\n    // a file is modified!\n}	0
30403852	30403573	Are delegates a good approach to share variables between two windows?	public static class Session { \n    public static String Name { get; set; }\n}\n\n//Window1\npublic Window1() {\n    Session.Name = "Window 1 instantiated.";\n}\n\n//Window2\npublic Window2() {\n    txtControl.Text = Session.Name;\n}	0
5978017	5977981	AutoComplete ComboBox in DataGridView using C#.net Windows Application	AutoCompleteCustomSource, AutoCompleteMode and AutoCompleteSource.	0
26671713	26671624	How to efficiently select child objects through LINQ	var jobReport = db.Jobs.SelectMany(j => j.JobReports)\n                       .Single(jr => jr.ReportId == reportId);	0
9028433	4680352	Store sensitive information inside keepass database from c#	var dbpath = @"C:\path\to\passwords.kdbx";\nvar masterpw = "Your$uper$tr0ngMst3rP@ssw0rd";\n\nvar ioConnInfo = new IOConnectionInfo { Path = dbpath };\nvar compKey = new CompositeKey();\ncompKey.AddUserKey(new KcpPassword(masterpw));\n\nvar db = new KeePassLib.PwDatabase();\ndb.Open(ioConnInfo, compKey, null);\n\nvar kpdata = from entry in db.RootGroup.GetEntries(true)\n                select new\n                {\n                    Group = entry.ParentGroup.Name,\n                    Title = entry.Strings.ReadSafe("Title"),\n                    Username = entry.Strings.ReadSafe("UserName"),\n                    Password = entry.Strings.ReadSafe("Password"),\n                    URL = entry.Strings.ReadSafe("URL"),\n                    Notes = entry.Strings.ReadSafe("Notes")\n\n                };                                                                                  \n\nkpdata.Dump(); // this is how Linqpad outputs stuff\ndb.Close();	0
14598328	14597806	Enum - combobox binding with one item as exception	string[] TestNames = Enum.GetNames(typeof(SampleEnumUnits));\nvar list = from test in TestNames where test != "Enum you wish to remove" select Enum.Parse(typeof(SampleEnumUnits), test);\ncmbDisplayUnit.ItemsSource = list;	0
4938284	4938220	var in console command C#	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        var colorName = Console.ReadLine();\n        try {\n            ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName, true);\n            if (color == Console.BackgroundColor) throw new ArgumentException("That would make invisible output");\n            Console.ForegroundColor = color;\n            Console.WriteLine("Okay");\n        }\n        catch (ArgumentException ex) {\n            Console.WriteLine(ex.Message);\n        }\n        Console.ReadLine();\n    }\n}	0
22106809	22106707	Convert Queryable Byte to Byte[]	byte[] bytes = File.ReadAllBytes(    \n    ctx.Files.Where(x => x.Id == 1).Select(x => x.FileName).Single()\n);	0
14673062	14673003	Lambda function using a delegate	myDelegate myDelegateInstance = new myDelegate(x => x * x);\nConsole.WriteLine("x^2 = {0}", myDelegateInstance(3));	0
15435130	15429787	Add a Button to a GridView programmatically	CommandField cField = new CommandField();\ncField.EditText = "Edit";\ncField.DeleteText = "Delete";\ncField.UpdateText = "Update";\ncField.CancelText = "Cancel";\n\ncField.ShowEditButton = true;\ncField.ShowDeleteButton = true;\n\nGridView1.Columns.Add(cField);	0
13822435	13818009	EF, get entity tree	using (var context = new ModelContainer())\n{\n    var container =     context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);\n    var entitySet =     container.BaseEntitySets[someEntityName];\n    var navProperties = set.ElementType.Members.Where(member => member.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty).Select(member => member.Name).ToList();\n}	0
1279016	1278989	How can I set LINQ SelectMany projection via Func parameter?	public static List<string> GetVideosAttribute( Func<Video,string> selector )\n{\n    var Videos = QueryVideos(HttpContext.Current);\n    return Videos.Where(v => v.Type == "exampleType"\n                 .Select( selector )\n                 .Distinct()\n                 .OrderBy(s => s)\n                 .ToList();\n}\n\n\nvar speakers = GetVideosAttribute( v => v->SpeakerName );\nvar topics = GetVideosAttribute( v => v->Topic );	0
26598101	26598042	Web API self host - bind on all network interfaces	var baseAddress = string.Format("http://*:9000/"); \n        using (WebApp.Start<Startup> (baseAddress)) \n        {\n            Console.WriteLine("Server started");\n            Thread.Sleep(1000000);\n        }	0
3341932	3335754	How to hide the tool tips	private void usrcntrlPPD_Leave(object sender, EventArgs e)\n    {\n        this.Dispose();\n    }	0
8096431	8075572	How to set the browser title to the active user control in a Silverlight Application	HtmlPage.Document.SetProperty("title", this.GetType().Name);	0
31840454	31838914	Replace a big chunk of html	Regex.Replace()	0
2126659	2126641	Cascade window programmatically using C# application	using System.Windows.Forms;\n\n// cascade\nthis.LayoutMdi(MdiLayout.Cascade);\n\n// close all\nForm[] children = this.MdiChildren;\nfor (int i = 0; i < children.Length; i++) {\n    children[i].Close();\n}\n\n// minimize all\nforeach (Form child in this.MdiChildren) {\n    child.WindowState = FormWindowState.Minimized;\n}	0
13852289	13791411	Streamreader isn't returning the correct values from my text file, can't figure out how to properly read my text files C#	var lines = File.ReadAllLines(load_dialog.FileName);\nint lineCount = lines.Count();\nint totalChars = 0;\nint totalPipes = 0; // number of "|" chars\n\nforeach (var s in lines)\n{\n    var entries = s.Split('|');  // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)\n    totalChars += s.Length;   // add the number of chars on this line to the total\n    totalPipes = totalPipes + entries.Count() - 1; // there is always one more entry than pipes\n}	0
8775533	8775444	inserting records from datatable into list	foreach(DataRow row1 in dt.Rows) {\n   StringBuilder sb = new StringBuilder();\n   foreach(DataColumn col in dt.Columns) {\n      sb.Append(row1[col].ToString();\n      sb.Append('\t');\n   }\n   mylist.Add(sb.ToString());\n}	0
33811233	33794855	newtonsoft.json parser in a C# CLR for SQL Server 2008 R2 - How to deploy?	CREATE ASSEMBLY System_Runtime_Serialization FROM 'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\System.Runtime.Serialization.dll'\nWITH PERMISSION_SET = UNSAFE\nGO	0
7939999	3415434	Default 3D chart transparency with ASP.NET Chart Control?	// After all series manipulation, add this\nchart.ApplyPaletteColors();\nforeach (var serie in chart.Series)\n    serie.Color = Color.FromArgb(220, serie.Color);	0
12070351	12066486	How to register Javascript to a CS file?	protected void Page_PreRender(object sender, EventArgs e)\n    {\n        if (strLoginJson != string.Empty)\n        {\n            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "LoginControlJSON", "<script language='javascript' type='text/javascript'>GetLoginJson(" + strLoginJson + ");</script>", false);\n        }\n    }	0
29756122	29756043	Serilog with Autofac	builder.Register<ILogger>((c, p) =>\n{\n    return new LoggerConfiguration()\n      .WriteTo.RollingFile(\n        AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "/Log-{Date}.txt")\n      .CreateLogger();\n}).SingleInstance();	0
24398263	24393294	Download files based on their type, or how to give two options to Response.AppendHeader	protected void gridExpenditures_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n    if (e.CommandName == "Download")\n    {\n        var filePath = Server.MapPath("~/Match/Files/") + e.CommandArgument;\n        var contentType = MimeTypes.GetContentType(filePath);\n        if (string.IsNullOrEmpty(contentType))\n        {\n            contentType = "application/octet-stream";\n        }\n        Response.Clear();\n        Response.ContentType = contentType;\n        Response.AppendHeader("content-disposition", "FileName=" + e.CommandArgument);\n        Response.TransmitFile(filePath);\n        Response.End();\n    }\n}	0
12959533	12950561	Palette Bitmap - Fractal Color Cycling	ColorPalette palette = originalBitmap.Palette;\nColor first = palette.Entries[0];\nfor (int i = 0; i < (palette.Entries.Length - 1); i++)\n{\n    palette.Entries[i] = palette.Entries[i + 1];\n}\npalette.Entries[(palette.Entries.Length - 1)] = first;\noriginalBitmap.Palette = palette;	0
22242671	22241485	The faster way foreach a bit array and insert bit digit to database	using Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System;\nusing System.Data;\nusing System.Data.SqlClient;\n\nnamespace BitsTest\n{\n    [TestClass]\n    public class BitsTester\n    {\n        [TestMethod]\n        public void BitsTest()\n        {\n            // random seed for emulating bit-array file\n            Random rand = new Random();\n\n            DataTable table = new DataTable();\n            table.Columns.Add("bit",typeof(bool));\n\n            string cs = @"Data Source=(localdb)\v11.0;Initial Catalog=bittest;Integrated Security=True";\n\n            // 2007040 records = 245kb of bits\n            for (int i = 0; i < 2007040; i++)\n                table.Rows.Add(rand.Next() % 2 == 0);\n\n            using (SqlBulkCopy bulk = new SqlBulkCopy(cs))\n            {\n                bulk.DestinationTableName = "bits";\n                bulk.WriteToServer(table);\n            }\n        }\n    }\n}	0
2192224	2192156	Garbagecollection of eventhandlers	EventHandlerType handler = (s, a) => UpdateTransactions(selected);\nselected.OnNewTransaction += handler;\n\n// When you want to remove the handler do this (make sure you "store" handler somewhere)\nselected.OnNewTransaction -= handler;	0
33853240	33853213	How to write a specific line of a text file?	var lines = File.ReadAllLines(@"D:\Desktop\asd.txt");\nlines[5] = "some value";\nFile.WriteAllLines(@"D:\Desktop\asd.txt", lines);	0
7810270	7810245	passing an array from one button to another one	class YourClass\n{\n  private int[,] data;\n\n  private void button1_Click(object sender, EventArgs e) \n  {\n    this.data = new ...\n  }\n\n  private void button2_Click(object sender, EventArgs e)\n  {\n    // process a data\n    if (this.data != null)\n    {\n       this.data ...\n    }\n  }\n}	0
33369340	33368219	Getting A Value From Stored Proc Which Doesn't Need Parameters	string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;\n        SqlConnection conn = new SqlConnection(connection);\n\n        SqlCommand com = new SqlCommand(\n            "SELECT        TOP (1) Month " +\n            "FROM          Past_Places", conn);\n\n        try\n        {\n            conn.Open();\n            SqlDataReader reader = com.ExecuteReader();\n            while (reader.Read())\n            {\n                PastMonth.Text = reader["Month"].ToString();\n            }\n            reader.Close();\n        }\n        finally\n        {\n            conn.Close();\n        }	0
12446411	12375022	Creating a simple Hello World app with MonoMac	this.btnHello.Activated += delegate {\n    this.Title = "Hello World";\n};	0
5822756	5822648	Dealing/resolving NullReferenceExceptions in ViewModels	public sealed class NullObject {\n    public static readonly NullObject Default = new NullObject();\n    public static object GetNotNull( object value ) {\n        return object.ReferenceEquals( value, null ) ? (object)Default : value;\n    }\n}\n//....\nprivate object someField;\npublic object SomeProperty {\n    get { return NullObject.GetNotNull( this.someField ); }\n}	0
633690	633656	Programming against an enum in a switch statement, is this your way to do?	[Test]\npublic void ShouldOnlyHaveFourStates()\n{\n    Assert.That(Enum.GetValues( typeof( DrivingState) ).Length == 4, "Update unit tests for your new DrivingState!!!");\n}	0
5265679	5265649	How do you make this parameter access syntax possible?	public class SampleClass {\n     public int value;\n\n     public SampleClass(int v)\n     { value = v; }\n\n     public static implicit operator int (SampleClass c)\n     {\n       return c.value;\n     }\n}	0
28518528	17958630	How to use a dll in both windows application and web forms application even if it references web stuff (like nUnit)?	public virtual bool IsWeb()\n{\n    return (System.Web.HttpContext.Current != null);\n}\n\npublic virtual bool IsSessionEnabled()\n{\n    return IsWeb() && (System.Web.HttpContext.Current.Session != null)\n}	0
33413325	33191842	Retrieve 'Last Saved By' file property programmatically	string lastSavedBy = null;\n        using (var so = ShellObject.FromParsingName(file))\n        {\n            var lastAuthorProperty =     so.Properties.GetProperty(SystemProperties.System.Document.LastAuthor);\n            if (lastAuthorProperty != null)\n            {\n                var lastAuthor = lastAuthorProperty.ValueAsObject;\n                if (lastAuthor != null)\n                {\n                    lastSavedBy = lastAuthor.ToString();\n                }\n            }\n        }	0
10072395	10072285	Call generic method for subclass from generic method for superclass	public void DoSmth<T>(T obj)\n    where T : Superclass\n{\n\n   //untested but something like this\n    Subclass obj2 = (obj as Subclass);   \n    if(obj2 != null)\n    {\n        DoSmth2(obj2);\n    }\n    //...\n}	0
16179130	16179056	Using numericUpDown to display panels on certain values	pet1Panel.Visible = (petNumNumericUpDown.Value >= 1);\npet2Panel.Visible = (petNumNumericUpDown.Value >= 2);\n...	0
8046072	8044795	How does the MVVM pattern work for validating data?	public class EmployeeViewModel : IDataErrorInfo, INotifyPropertyChanged\n{\n    public string FirstName { /* get set and NotifyChanged here...*/ }\n\n    public string LastName { /* get set and NotifyChanged here...*/ }\n\n    public string Error\n    {\n        get { return error; }\n    }\n\n    public string this[string columnName]\n    {\n        get \n        {\n            string error = string.Empty;\n            switch (columnName)\n            {\n                case "FirstName":\n                    if(string.IsNullOrEmpty(this.FirstName))\n                        error = "FirstName can not be blank";\n                    else if (this.FirstName == "Ekk")\n                        error = "Ekk is my name, you should change!";\n                    break;\n                case "LastName":\n                    if(string.IsNullOrEmpty(this.LastName))\n                        error = "LastName can not be blank";\n                    break;\n            }\n            return error;\n        }\n    }\n}	0
20845762	20844610	Need regex to find text in C#	string expr = @"Content=""[^""]*""";\nSystem.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(expr);\nstring data = @"<SomeControl Content=""sup""><anotherControl Content=""hey""><athird Content=""yo""></athird></anotherControl></SomeControl>"; // This will be replaced with actual file content\nvar res = reg.Matches(data);\nvar occuranceCount = res.Count;	0
25638549	25638438	comparing datarow value with a string in if	foreach (DataRow dr in dsQuestions.Tables[0].Rows)\n            {\n               if (dr["Data"].tostring().Equals(indicater[0]))\n                {\n                    dr["IsSelected"] = true;\n               }	0
10852827	10852634	Using a 32bit or 64bit dll in C# DllImport	[DllImport("MyDll32.dll", EntryPoint = "Func1", CallingConvention = CallingConvention.Cdecl)]\nprivate static extern int Func1_32(int var1, int var2);\n\n[DllImport("MyDll64.dll", EntryPoint = "Func1", CallingConvention = CallingConvention.Cdecl)]\nprivate static extern int Func1_64(int var1, int var2);\n\npublic static int Func1(int var1, int var2) {\n    return IntPtr.Size == 8 /* 64bit */ ? Func1_64(var1, var2) : Func1_32(var1, var2);\n}	0
12855513	12853077	How to edit event which was saved ealier from full calender in MVC 4?	eventRender: function(event, element, view) {}	0
27804756	27492460	Searching an array string with a binary search sub string	string searchfor = textBox1.Text\n    Assembly assm = Assembly.GetExecutingAssembly();\n    using (Stream datastream = assm.GetManifestResourceStream("WindowsFormsApplication2.Resources.file1.txt"))\n    using (StreamReader reader = new StreamReader(datastream))\n    {\n        string lines;\n        while ((lines = reader.ReadLine()) != null)\n        {\n            if (lines.StartsWith(searchfor))\n            {\n                label1.Text = "Found";\n                break;\n            }\n            else\n            {\n                label1.Text = "Not found";\n            }\n        }\n    }	0
2401873	2401523	how to insert row in first line of text file?	static void WriteABC(string filename)\n{\n    string tempfile = Path.GetTempFileName();\n    using (var writer = new StreamWriter(tempfile))\n    using (var reader = new StreamReader(filename))\n    {\n        writer.WriteLine("A,B,C");\n        while (!reader.EndOfStream)\n            writer.WriteLine(reader.ReadLine());\n    }\n    File.Copy(tempfile, filename, true);\n}	0
8669174	8669107	How to Convert a Nullable DateTime variable's null value to DbNull.Value	dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, (object) myDate ?? DbNull.Value);	0
3018705	3018700	Aribitrary System.DateTime to four character military time string	DateTime.Now.ToString("HHmm")	0
24695099	24694498	To Check for a particular format in textbox	private void textBox1_Validated(object sender, EventArgs e)\n    {\n    bool FoundMatch = false;\n    if(combobox1.text.contains("hardners"))\n        {\n\n            try {\n                FoundMatch = Regex.IsMatch(textBox1.text, "\\APHY\\0+\\z");\n            } catch (ArgumentException ex) {\n\n                // Syntax error in the regular expression\n            }\n        }\n        else\n        {\n            try\n            {\n                FoundMatch = Regex.IsMatch(textBox1.text, "\\APH\\0+\\z");\n            }\n            catch (ArgumentException ex)\n            {\n                // Syntax error in the regular expression\n            }\n        }\n\n   }	0
7269827	7269488	How can I bind the SelectedItemValue from a TreeView back to a ViewModel in Silverlight?	ItemsSource="{Binding ChildItems}"\n SelectedItem="{Binding SelectedChild}"	0
6908552	6900913	Get only id of a my ManyToOne object	public class FooToBarResult\n{\n    public string FooId { get; set; }\n    public int BarId { get; set; }\n}\n\nIList<BlockToComponentResult> result = session\n       .CreateSQLQuery(@"SELECT bar_id as BarId, id as FooId FROM `foo`")\n       .SetResultTransformer(Transformers.AliasToBean<FooToBarResult>())\n       .List<FooToBarResult>();	0
6613858	6604085	Intercepting a method with reflection	public object Intercept(object proxy, MethodInfo method, object[] args)\n{\n    var data = method.GetCustomAttributes(typeof(TimeAttribute), true);\n\n    object result = default(object);\n\n    foreach (object d in data)\n    {\n        if (d.GetType() == typeof(TimeAttribute)) // [Time] attribute\n        {\n            result = method.Time(proxy, args, Log.Write).DynamicInvoke(args);\n        }\n    }\n    return result;\n}	0
5808612	5808594	Bind a repeater to an object	TestProgram myProgram = new TestProgram("5");\n\nList<TestProgram> programs = new List<TestProgram>{myProgram};\n\nprogram_list.DataSource = programs;\nprogram_list.DataBind();	0
11300544	11300429	Assign to class property from XML randomly	IList<string> randomAnswers = _list\n    .Select(c => c.Definite)\n    .OrderBy(c => Guid.NewGuid())\n    .ToList();\n\nfor (int index = 0; index < randomAnswers.Length; index++)\n{\n    _list[index].Random = randomAnswers[index];\n}	0
16052197	16052137	how can i calculate different timezone (following daylight saving) from a given time	var varLondon = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");//Returns Timezone based on particular ID, ID can be related to pasific timezone, Indian TimeZone,etc.\n        var varGoogleplex = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");\n        var now = DateTimeOffset.UtcNow; //Gives you local clock time for your currrent time zone\n        TimeSpan TSLondonOffset = varLondon.GetUtcOffset(now); //will return you timespan of current time zone and specified one.\n        TimeSpan TSGoogleplexOffset = varGoogleplex.GetUtcOffset(now);	0
22218911	22218843	Button that expands ComboBox causing infinite loop	button.MouseEnter -= MouseEnter2;	0
24084638	24082664	Getting parameter for method when passed through JSON	redirectUrl = Url.Action("Observation", "PP", new { AccountID })	0
1755719	1754711	Database performance with Nhibernate and Activerecord	public IQuerable<Order> GetOrdersBySellerId(int sellerId)\n{\n     string hql = @"select  o \n                    from     Order o, Product p\n                    where    p.Seller.SellerID=:sellerID\n                    and      p in elements(o.Items )";\n\n     SimpleQuery<Order> q = new SimpleQuery<Order>(hql);\n     q.SetParameter("sellerID", sellerID);\n            return q.Execute().AsQueryable();\n}	0
13471367	13471223	Get text in brackets using regular expression	string input = @"some text {{text in double brackets}}{{another text}}...";\nvar matches = Regex.Matches(input, @"\{\{(.+?)\}\}")\n                    .Cast<Match>()\n                    .Select(m => m.Groups[1].Value)\n                    .ToList();	0
892909	891598	c# generated csv file sent via email embedded to bottom of email in lotus note	var mailMessage = new MailMessage();\nAttachment data = new Attachment(attachment, contentType); \nContentDisposition disposition = data.ContentDisposition;\ndisposition.FileName = "message.csv";\nmailMessage.Attachments.Add(data);	0
33208103	33208102	How to do a simple dataGridView search / filter?	private void searchbutton_Click(object sender, EventArgs e)\n    {\n    string searchValue = searchtextBox.Text;\n    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\n    try\n    {\n        bool valueResult = false;\n        foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            for (int i = 0; i < row.Cells.Count; i++)\n            {\n                if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().Equals(searchValue))\n                {\n                    int rowIndex = row.Index;\n                    dataGridView1.Rows[rowIndex].Selected = true;\n                    valueResult = true;\n                    break;\n                }\n            }\n\n        }\n        if (!valueResult)\n        {\n            MessageBox.Show("Unable to find " + searchtextBox.Text, "Not Found");\n            return;\n        }\n    }\n    catch (Exception exc)\n    {\n        MessageBox.Show(exc.Message);\n    }\n}	0
15348363	15348192	Get list of email addresses from ADGroup	void Main()\n{\n    string groupName = "somegroup";\n    string domainName = "somedomain";\n\n    using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))\n    {\n        using(GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName))\n        {\n            var sams = from x in grp.GetMembers(true) select new {x.SamAccountName, };\n            var users = from sam in a.Distinct()\n                let usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sam)\n                select new { usr.SamAccountName, usr.DisplayName, usr.EmailAddress};\n            //do something with users...\n        }\n    }\n}	0
12872899	12872740	DoubleClick on a row in ListView	private void lvLista_DoubleClick(object sender, EventArgs e)\n{\n\n    MessageBox.Show(lvLista.SelectedItems[0].SubItems[0].Text);\n}	0
11001476	11001322	write to csv in MVC with data containing a comma	"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}"	0
6455933	6455822	convert HashTable to Dictionary in C#	public static Dictionary<K,V> HashtableToDictionary<K,V> (Hashtable table)\n{\n   return table\n     .Cast<DictionaryEntry> ()\n     .ToDictionary (kvp => (K)kvp.Key, kvp => (V)kvp.Value);\n}	0
20220574	20220530	How to select by child collection value in LINQ	var _tours = Context.Tours.Where(i => i.IsActive == true)\n  .Include(cat => cat.TourCategories).\n  .Where(x => x.TourCategories.Any(y => y.TourCategoryID == tourCategory)	0
7212401	7212392	C# creating multiple rectangles using for loop	for (int shift = 0; shift < 6; shift++)\n{\n    Rectangle hozBarRect = new Rectangle(xPos_ + VERT_BAR_WIDTH, yPos_ + (10 * shift), HOZ_BAR_WIDTH, HOZ_BAR_HEIGHT);\n\n    // Draw the rectangle here\n}	0
8049311	8048951	C# Regex: Getting URL and text from multiple "a href"-tags	Regex r = new Regex(@"<a.*?href=(""|')(?<href>.*?)(""|').*?>(?<value>.*?)</a>");\n\nforeach (Match match in r.Matches(html))\n    yield return new Tuple<string, string>(\n        match.Groups["href"].Value, match.Groups["value"].Value);	0
728000	727996	Preventing methods from being inherited	Foo myBar = new Bar(); // This is legal\nmyBar.FooSpecificMethod(); // What should this do?  \n                           // It's declared a Foo, but is acutally a Bar	0
11785238	11771026	Entity Framework object has datetime field that I want to convert to short date string before I pass to view (ASP.NET MVC4)	public virtual DateTime? DueDate { get; set; }\n\n public string DueDateString\n        {\n            get { return DueDate != null ? DueDate.ToString() : string.Empty; }\n        }	0
16740316	16740126	Given a list of objects, extract N objects that have a similar size	Deque leastSet = new LinkedList(); // use a Deque instead of a Set because order is important, and presumably your inputArray doesn't contain duplicates anyway; if the input may contain duplicates, then use a LinkedHashSet instead\nDeque currentSet = new LinkedList();\n\n// initialize deques with first N elements\nfor(int i = 0; i < N; i++) {\n    leastSet.addLast(inputArray[i]);\n    currentSet.addLast(inputArray[i]);\n}\n\nfor(int i = N; i < inputArray.length; i++) {\n    currentSet.removeFirst();\n    currentSet.addLast(inputArray[i]);\n    if((currentSet.peekLast() - currentSet.peekFirst()) < (leastSet.peekLast() - leastSet.peekFirst())) {\n        leastSet = currentSet.clone();\n    }\n}	0
9802780	9743007	Add a Header Row To Excel File through File Helpers	// Class record\n[DelimitedRecord("|")]\npublic class MyClass\n{\n    public string Field1 { get; set; }\n    public int Field2 { get; set; }\n    public string Field3 { get; set; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        // create some data to export\n        MyClass[] rows = new MyClass[2] { \n          new MyClass() { Field1 = "Apples",  Field2 = 23, Field3 = "Yes" },\n          new MyClass() { Field1 = "Oranges", Field2 = 17, Field3 = "No"} \n        };\n\n        ExcelStorage provider = new ExcelStorage(typeof(MyClass));\n        // Set the destination Excel spreadsheet\n        provider.FileName = @"MyClass.xlsx";\n\n        // Template.xlsx contains just the column headers on row 1\n        provider.TemplateFile = @"Template.xlsx"; \n        // StartRow is after the header row\n        provider.StartRow = 2; \n\n        provider.OverrideFile = true;\n        provider.InsertRecords(rows);\n    }\n}	0
6583847	6583772	MVVM base view model class	public abstract class ViewModelBase<T>\n{\n    public abstract ObservableCollection<T> Items { get; set; }\n}	0
9149738	9149728	Convert binary string into integer	int output = Convert.ToInt32(input, 2);	0
15258723	15258620	Get a single element of CSV file	var item = abc.Split(',');\nlistaCsv.Add(new Alimento() { Codice = item[0], Descrizione = item[1], \nCarboidrati = int.Parse(item[2])};	0
30018011	30017859	Datagridview - selete a column to populate	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    //do something like row.Cells["Name or number"].Value = random number;\n}	0
13318455	13318362	Get Enums by Index relation in C#	public enum UserRole\n{\n    Admin = 1,\n    Leader = 2,\n    Editor = 3,\n    Guest = 4\n}\n\nIList<UserRole> roles = new List<UserRole> { UserRole.Leader, UserRole.Editor };\n\nvar min = roles.Min();\n\nvar max = roles.Max();\n\nvar result1 = Enum.GetValues(typeof(UserRole)).Cast<UserRole>()\n                  .Where(x => x >= min);\n\nvar result = Enum.GetValues(typeof(UserRole)).Cast<UserRole>()\n                 .Where(x => x <= max);	0
9025494	9025278	How do I simulate a Tab key press when Return is pressed in a WPF application?	private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)\n        {\n            if (e.Key == Key.Enter)\n            {\n                TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);\n                request.Wrapped = true;\n                ((TextBox)sender).MoveFocus(request);\n            }\n        }	0
10059255	10059016	Foreign Key Just showing a number which is associated with the primary key	return View(db.tblReviews.Include("tblGame").ToList());	0
5885151	5884999	How to implement file processing in Windows Service?	public void Start()\n{\n    FileSystemWatcher fsw = new FileSystemWatcher();\n    fsw.Path = "\\server\share";  //or use your inputdir\n    fsw.NotifyFilter = NotifyFilters.Size;  //(several others available)\n    fsw.Filter = "*.jpg";\n    fsw.Changed += new FileSystemEventHandler(OnChanged);\n    fsw.EnableRaisingEvents = true;\n}\n\nprivate void OnChanged(object source, FileSystemEventArgs e)\n{\n    //do stuff.\n}	0
6388953	6388852	C# - How to compare two different text files	File.WriteAllLines("FileC.txt",\n  File.ReadAllLines("FileB.txt").Except(File.ReadAllLines("FileA.txt")));	0
31743136	31742938	c# enumerate values from new instance of a class	public string GetLongText(StringReader reader)\n{\n    // Get a reference to the private field\n    var field = reader.GetType().GetField("LongText", BindingFlags.NonPublic | \n                         BindingFlags.Instance)\n\n    // Get the value of the field for the instance reader\n    return (string)field.GetValue(reader);                 \n}	0
31444332	31444012	Get owner from datatable object	this.MyTableAdapter.Connection.Open();\n   var schema = this.MyTableAdapter.Connection.GetSchema("Tables");\n   this.MyTableAdapter.Connection.Close();\n   var owner = schema.Select("TABLE_NAME = 'MyTable'")[0]["TABLE_SCHEMA"];	0
29577968	29577944	How to tell if a particular day of the year has already passed?	if (DateTime.Today > yourTestDate)\n{\n    //do stuff.\n}	0
12383220	12383179	Executing a C# method by calling it from client-side by ajax	[WebMethod]\n public static object storeLocal(string brand)\n {\n     HttpContext.Current.Session.Add("Brand", brand);\n     return "value" +brand;\n }	0
4324516	4312004	How to have unique entity framework connection strings in each user configuration file	EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();\n    if (serverName=="Local")\n    {\n        ecb.ProviderConnectionString = Properties.Settings.Default.ServerLocalConnectionString;\n    }\n    else\n    {\n        ecb.ProviderConnectionString = Properties.Settings.Default.ServerConnectionString;\n    }\n\n    ecb.Metadata = "res://*/";\n    ecb.Provider = "System.Data.SqlClient";\n    SomeEntities context = new SomeEntities(new EntityConnection(ecb.ToString());	0
27297032	27296902	Storing list of objects in a SQL Server database with code-first	public class PossibleAnswer {\n      public Guid Id {get;set;}\n      public Guid MultipleChoiceQuestionId {get;set;}\n      public string Answer {get;set;}\n }	0
28908125	28908087	Is there a way to select two values into same IEnumerable using LINQ in C#?	IEnumerable<int> allInts = MyCollection.Select(i => i.A)\n                                       .Concat(MyCollection.Select(i => i.B));	0
6936101	6936089	How to programatically select first row of DataGridView	dataGridView1.Rows[0].Selected = true;	0
26444366	26443852	How disable window when start IE	var key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true)\n    .OpenSubKey("Policies", true)\n    .OpenSubKey("Microsoft", true);\n\n    key = key.OpenSubKey("Internet Explorer", true) ?? key.CreateSubKey("Internet Explorer", RegistryKeyPermissionCheck.ReadWriteSubTree);\n    key = key.OpenSubKey("Main", true) ?? key.CreateSubKey("Main", RegistryKeyPermissionCheck.ReadWriteSubTree);\n    key.SetValue("DisableFirstRunCustomize", 1, RegistryValueKind.DWord);	0
925109	925066	Transfer data from SQL Server to MySQL	LOAD DATA INFILE	0
4765827	4765789	Getting files by creation date in .NET	using System.Linq;\n\nDirectoryInfo info = new DirectoryInfo("");\nFileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();\nforeach (FileInfo file in files)\n{\n    // DO Something...\n}	0
9914327	9905626	Code Conversion - MFC C++ to a VSTO Excel Addin in C#	m_pControllerReference = new ExcelReference(0,0,0,0, "Sheet1"); // Cell A1\n  m_referenceSheetName = (string)XlCall.Excel(XlCall.xlSheetNm, m_pControllerReference ); \n  m_controllerSheetId =  XlCall.Excel(XlCall.xlSheetId, m_referenceSheetName);\n  // or just: \n  m_controllerSheetId =  m_pControllerReference.SheetId;	0
27719653	27719064	How do I use a linq query to update the underlying database table	var amexQuery = (from c in amexTable\n            where c.Date == date\n            select c).FirstOrDefault();\n\namexQuery.AdjustedClose  = newValue\n//call to Submit Changes to Update DB Change	0
19925390	19842543	How do I get all of the property names from a model?	var type = Type.GetType("AssemblyQualifiedName of my Type");\n\nvar properties = type.GetProperties();	0
22667199	22666477	Registry Delete Value	string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";\nusing (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))\n{\n    if (key == null)\n    {\n        // Key doesn't exist. Do whatever you want to handle\n        // this case\n    }\n    else\n    {\n        key.DeleteValue("123");\n    }\n}	0
14869857	14869657	Creating 2 arrays from a text file	using (FileStream fileStream = new FileStream("filename", FileMode.Open, FileAccess.Read, FileShare.Read))\n        {\n            using (StreamReader streamReader = new StreamReader(fileStream))\n            {\n                while (streamReader.Peek() > -1)\n                {\n                    string line = streamReader.ReadLine();\n                    string[] parts = line.Split('\t');\n\n                    outputs[lineCounter] = int.Parse(parts[0]);\n\n                    inputs[lineCounter] = new int[4];\n                    inputs[lineCounter][0] = int.Parse(parts[1]);\n                    inputs[lineCounter][1] = int.Parse(parts[2]);\n                    inputs[lineCounter][2] = int.Parse(parts[3]);\n                    inputs[lineCounter][3] = int.Parse(parts[4]);\n\n                    lineCounter++;\n                }\n            }\n        }	0
33126566	33126043	getting a count based on multiples of three	usersSatisfied\n.GroupBy(c => c.UserName)\n.Where(grp => grp.Count() % 3 == 0)\n.Select(grp => grp.Key);	0
13845062	13838759	Crystal report paremeters to be printed more than 1 times in detail Section	local numbervar TimesToPrint := 8;\nlocal numbervar i; //for-loop counter \nlocal stringvar out; //return variable\n\nfor i := 1 to TimesToPrint do\n    out := out + {?YourParameter} + chr(13); //format your output\n\nout	0
5500370	5500173	Enum to dictionary	public static Dictionary<int, string> ToDictionary(this Enum @enum)\n{\n  var type = @enum.GetType();\n  return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));\n}	0
6419526	6419263	How can I select what columns come in from a DataSet into a DataTable?	// Assumes that connection is a valid SqlConnection object.\n\nstring queryString = "SELECT CustomerID, CompanyName FROM dbo.Customers";\nSqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);\n\nDataSet customers = new DataSet();\nadapter.Fill(customers, "Customers");\n\nDataTable table = customers.Tables[0];	0
16518873	16518615	Find object by css class from code behind	runat="server" ID="xxx"	0
6418853	6418520	Invoke Windows Magnifier	keybd_event(0x5B, 0x45, 0, new UIntPtr(0));\n        keybd_event(0xBB, 0x45, 1, new UIntPtr(0));	0
10036693	10036661	Datetime subtract, datespan divide	TimeSpan delta = TimeSpan.FromTicks((d2.Subtract(d1).Ticks) / 5);	0
21524972	21524829	Change datetime format	Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US");\n\n    customCulture.DateTimeFormat.ShortDatePattern = "yyyy/M/d";\n\n    System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;\n    System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;\n\n    DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("M/d/yyyy"));\n    Console.WriteLine(dt.ToString())	0
1345606	1344543	Copying a class from DataContext causes a cached data load on next database call in Entity Framework?	db.Detach(newArea); return newArea;	0
4818776	4818680	Reactive Extensions: Pairing values from an IObservable	var keyPressed = Observable.Create<ConsoleKey>(\n    o =>\n        {\n            while (true)\n            {\n                var consoleKeyInfo = Console.ReadKey(true);\n                o.OnNext(consoleKeyInfo.Key);\n            }\n        }\n    );\n\nvar paired = keyPressed\n    .BufferWithCount(2)\n    .Select(x => new {a = x[0], b = x[1]});\n\npaired.Subscribe(Console.WriteLine);	0
19255937	19255712	How to return multiple string variables from a single SQL Select Statement in Asp.Net/C# Codebehind?	lblString1.Text = row["ClientActive"].toString(); lblString2.Text = row["TotalB"].toString(); etc.	0
34393847	34393816	How does Enviorment GetFolderPath work when called from wcfservice that is hosted on webhotel	Console.WriteLine("MachineName: {0}", Environment.MachineName);\nConsole.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString());\nConsole.WriteLine("GetFolderPath: {0}",Environment.GetFolderPath(Environment.SpecialFolder.System));	0
12064207	12064075	How to read the data from string contaning XML in c#?	var xml = "<a header='0'> <row dc='123' al='45' msg='1-st line'/> <row dc='678' al='8' msg='second-line'/> </a>";\nvar doc = XElement.Parse(xml);\nvar list = from x in doc.Descendants("row")\n            select new \n            {\n                dc = (int)x.Attribute("dc"),\n                al = (int)x.Attribute("al"),\n                msg = (string)x.Attribute("msg")\n            };	0
32335896	32335781	Multiple Dependency Properties	public static readonly DependencyProperty FooTextProperty =\n            DependencyProperty.RegisterAttached("FooText", typeof(string), typeof(TouchScrolling), null);	0
21798445	21797594	How can i set System.Data.SQLite to show header?	SQLiteConnection connection = new SQLiteConnection("Data Source=" + path);\n\nconnection.Open();\n\nSQLiteDataReader reader = new SQLiteCommand(connection) { CommandText = "select * from message" }.ExecuteReader();\n\nbool needHeader = true;\nwhile (reader.Read())\n{\n    // show header if this is the first row\n    if(needHeader){\n        ShowHeader(reader);\n        needHeader = false;\n    }\n    //...\n}\n\nreader.Close();\nconnection.Close();\n\nvoid ShowHeader(SQLiteDataReader reader){\n    for (int i=0;i < reader.FieldCount;i++) \n    { \n      string fieldName = reader.GetName(i); \n      // use your display method here\n      Console.Write(fieldName+"\t"); \n    }         \n}	0
31289762	31289661	Getting a list of power of 2 ints from an input value in C#	var bitsPerByte = 8;\nfor (int i = 0; i < (sizeof(int) * bitsPerByte) /*32*/; i++) {\n var powerOfTwo = 1 << i;\n if ((number & powerOfTwo) != 0) yield return powerOfTwo;\n}	0
10410830	10409105	Change button border and disabled appearance	private void button3_Paint(object sender, PaintEventArgs e)\n            {\n\n                SolidBrush br = new SolidBrush(Color.Blue);\n                Pen pen = new Pen(br);\n                pen.Width = 3;\n                pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;\n                  // to draw left border\n                e.Graphics.DrawLine(pen, new Point(0, 0), new Point(0, this.button3.Width));\n                SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property\n                // Draw string to screen.\n                e.Graphics.DrawString("Sample", Font, drawBrush, 5f, 3f);\n                this.button3.Text = "";\n    }	0
22916774	22915556	Databinding to a BlockingCollection	public ICollectionView UploadRequestsView {get;set;}\n\n    public UploadRequester(Dispatcher dispatcher)\n    {\n        this.dispatcher = dispatcher;           \n        this.uploadRequestsBlocking = new BlockingCollection<UploadRequest>();\n\n        UploadRequestsView = CollectionViewSource.GetDefaultView(uploadRequestsBlocking);\n\n        this.consumerTask = Task.Factory.StartNew(this.ConsumeUploadRequests);\n    }\n\n    public void AddUploadRequest(UploadRequest uploadRequest)\n    {\n        uploadRequestsBlocking.Add(uploadRequest);\n        UploadRequestsView.Refresh()\n    }\n\n    private void ConsumeUploadRequests()\n    {\n        foreach (var uploadRequest in this.uploadRequestsBlocking.GetConsumingEnumerable())\n        {\n            uploadRequest.Status = "Uploading...";\n\n            Thread.Sleep(2000);\n            uploadRequest.Status = "Successfully uploaded";\n\n            Thread.Sleep(500);\n            dispatcher.Invoke(() => UploadRequestsView.Refresh());\n        }\n    }	0
25392011	25391795	Creating generic extension method for getting list of values' Display Name attribute strings	public static List<string> CreateList<T>()\n{\n    return Enum.GetValues(typeof(T)).Cast<Enum>().Select(v => v.GetDisplayName()).ToList();\n}	0
14477625	14477564	Select XML node where namespace is changing between requests in WCF	// assuming XmlDocument doc has already been loaded with the XML response\nXmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);\nnsm.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");\nXmlNode body = doc.SelectSingleNode("/soap:Envelope/soap:Body", nsm);	0
17917293	17915938	How to detect if concurrent GC is running in .Net	System.Runtime.GCSettings.	0
14194094	14179124	How to organize a list of items within a view based on an item's property?	public class Vendor\n{\n    public string VendorName { get; set; }\n    public IEnumerable<VendorInfo> VendorData { get; set; }\n}\n\npublic class VendorInfo\n{\n    public decimal Amount { get; set; }\n    public decimal Tax { get; set; }\n}\n\npublic class MyViewModel\n{\n    public IEnumerable<Vendor> Vendors { get; set; }\n}	0
4677989	4677969	How can I display multiple images in a loop in a WP7 app?	Dispatcher.BeginInvoke( () => { /*  your UI code */ } );	0
26507606	26490206	Duplicate Entity with new key	db.ContextOptions.LazyLoadingEnabled = false;\ndb.PERS936AB.MergeOption = MergeOption.NoTracking;\nvar new_request = db.PERS936AB.Single(r => r.ID == id);\nnew_request.Year = currentYear;\ndb.PERS936AB.AddObject(new_request);\ndb.SaveChanges();	0
34281438	34280293	How to read properties from DLL before Assembly.LoadFile()	FileVersionInfo.GetVersionInfo	0
26546707	26546491	Removing the default print button functionality in Print Preview Dialog	ToolStripButton b = new ToolStripButton();\n b.ImageIndex = ((ToolStripButton)((ToolStrip)dlgPreview.Controls[1]).Items[0]).ImageIndex;\n\n        ((ToolStrip)dlgPreview.Controls[1]).Items.Remove(((ToolStripButton)((ToolStrip)dlgPreview.Controls[1]).Items[0]));\n        b.Visible = true;\n        ((ToolStrip)dlgPreview.Controls[1]).Items.Insert(0, b);\n        ((ToolStripButton)((ToolStrip)dlgPreview.Controls[1]).Items[0]).Click += new System.EventHandler(this.button1_Click);	0
20411808	20411761	Regex Replace String Between []	Regex yourRegex = new Regex(@"\(.*\)|\[.*\]");	0
6019672	6019600	How do I set an image for ContextMenuStrip items?	this.toolStripButton1.Image = Bitmap.FromFile("c:\\NewItem.bmp");\nthis.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;\nthis.toolStripButton1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;\nthis.toolStripButton1.Name = "toolStripButton1";\nthis.toolStripButton1.Text = "&New";\nthis.toolStripButton1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;\nthis.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);	0
23921688	23921210	Grouping lists into groups of X items per group	public static IEnumerable<IGrouping<int, TSource>> GroupBy<TSource>\n    (this IEnumerable<TSource> source, int itemsPerGroup)\n{\n    return source.Zip(Enumerable.Range(0, source.Count()),\n                      (s, r) => new { Group = r / itemsPerGroup, Item = s })\n                 .GroupBy(i => i.Group, g => g.Item)\n                 .ToList();\n}	0
3892372	3840710	reset user password	DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");\nDirectoryEntry HostedUser = AD.Children.Find(hostedUserName, "user");\n\nstring password = new HostedGuiAddMachines().CreateRandomPassword(8);\nHostedUser.Invoke("SetPassword", new object[] { password });\nHostedUser.Close();\nAD.Close();	0
12603362	12603073	regarding app.config	AppName.exe.config	0
4391139	4391093	convert string number to integer	string k = "12,000";\n int i = Convert.ToInt32(k.Replace(",", ""));	0
17944448	17944399	Concatenate string in GroupBy	SomeList.GroupBy(x => new {x.Code, x.Location});	0
1071590	1071579	User Control Click - Windows Forms	foreach (Control control in Controls)\n{\n    // I am assuming MyUserControl_Click handles the click event of the user control.\n    control.Click += MyUserControl_Click;\n}	0
1911604	1911574	.NET screen objects touch detection	if (a.left <= b.right && b.left <= a.right &&\n    a.top <= b.bottom && b.top <= a.bottom)	0
16872081	16871976	trying to perform a search from a winform application wrong encoding	string hebrew = "????, ????";\nstring query = "http://bing.com?q={0}";\nUri url = new Uri(String.Format(query, Uri.EscapeDataString(hebrew)));	0
17295430	17295310	Efficient way to get max key value from Dictionary?	int max = int.MinValue;\n\nforeach (int i in dict.Keys)\n    max = Math.Max(max, i);	0
3575874	3575856	C# Generics syntax help	public interface IRepository<T, E> \n    where T : class\n    where E : class	0
17704215	17704169	How to write superscript in a string and display using MessageBox.Show()?	var o2 = "O?";       // or "O\x2082"\nvar unit2 = "unit?"; // or "unit\xB2"	0
9371882	9322689	how to get words count from MS Word without carriage return and hidden text using c#	int stWordCount = wordobj.ActiveDocument.ComputeStatistics(Word.WdStatistic.wdStatisticWords);	0
20105177	20102221	Declare variable in if statement and then using it later in code	int[] charLevelHp = { 100, 100, 100, 100,\n                      120, 120, 120,\n                      150, 150,\n                      180, 180 };\n\nint charLevel = 1;\nint charHp = charLevelHp[charLevel];	0
13390583	13390472	How to get from .wav sound into double[] C#	BinaryReader reader = new BinaryReader(waveFileStream);\n\n//Read the wave file header from the buffer. \n\nint chunkID = reader.ReadInt32();\nint fileSize = reader.ReadInt32();\nint riffType = reader.ReadInt32();\nint fmtID = reader.ReadInt32();\nint fmtSize = reader.ReadInt32();\nint fmtCode = reader.ReadInt16();\nint channels = reader.ReadInt16();\nint sampleRate = reader.ReadInt32();\nint fmtAvgBPS = reader.ReadInt32();\nint fmtBlockAlign = reader.ReadInt16();\nint bitDepth = reader.ReadInt16();\n\nif (fmtSize == 18)\n{\n    // Read any extra values\n    int fmtExtraSize = reader.ReadInt16();\n    reader.ReadBytes(fmtExtraSize);\n}\n\nint dataID = reader.ReadInt32();\nint dataSize = reader.ReadInt32();\n\n\n// Store the audio data of the wave file to a byte array. \n\nbyteArray = reader.ReadBytes(dataSize);\n\n// After this you have to split that byte array for each channel (Left,Right)\n// Wav supports many channels, so you have to read channel from header	0
21166922	21166166	TFS API - check in all files regardless of status	// create a workspace on my production server\ntry\n{\n    wSpace = vcsProdServer.GetWorkspace(cWsMapping, vcsProdServer.AuthorizedUser);\n}\ncatch\n{\n    wSpace = vcsProdServer.CreateWorkspace(cWsMapping);\n    wSpace.Map(pProjectName, combinedPath);\n}\nwSpace.Get();	0
7495666	7495527	Folder Browser Dialog Box in ASP.Net	// Clear the content of the response\nResponse.ClearContent();    \n\n// Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header\nResponse.AddHeader("Content-Disposition", "attachment; filename=" + savedNameWithExtension);\n\n// Add the file size into the response header\nResponse.AddHeader("Content-Length", myfile.Length.ToString());\n\n// Set the ContentType\nResponse.ContentType = ReturnExtension(myfile.Extension.ToLower());\n\n// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)\nResponse.TransmitFile(myfile.FullName);\n\n// End the response\nResponse.End();	0
28100556	28100473	Overwrite Access Database resulting Unrecognized Format	private string dirA = @"D:\Destination A\Database\db1.accdb";\nprivate string dirB = @"D:\Destination B\App_Data\db1.accdb";\nprivate void button1_Click(object sender, EventArgs e)\n{\n    if (File.Exists(dirB))\n    {\n       File.Delete(dirB);\n    }\n    File.Copy(dirA, dirB);\n}	0
1301300	1091172	Can't add a routed command to a CheckBox in WPF	Command="{x:Static local:MainWindow.SwitchContextCommand}"	0
3679846	3679812	C#: How do I dynamically load/instantiate a DLL?	Assembly.Load	0
4879539	4879522	How to split a string to List<string> without splitting words?	public static IEnumerable<string> SmartSplit(this string input, int maxLength)\n{\n    int i = 0;\n    while(i + maxLength < input.Length)\n    {\n        int index = input.LastIndexOf(' ', i + maxLength);\n        yield return input.Substring(i, index - i);\n\n        i = index + 1;\n    }\n\n    yield return input.Substring(i);\n}	0
10871430	10869826	How is GlyphIndices property encoded in GlyphRun object?	GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri(@"C:\WINDOWS\Fonts\TIMES.TTF"));\nconst char character = '?';\nushort glyphIndex;\nglyphTypeface.CharacterToGlyphMap.TryGetValue(character, out glyphIndex); \nMessageBox.Show("Index = " + glyphIndex);	0
230463	230454	How to Fill an array from user input C#?	string []answer = new string[10];\nfor(int i = 0;i<answer.length;i++)\n{\nanswer[i]= Console.ReadLine();\n}	0
25088778	25088706	Windows Forms Application Basics: Keeping all forms in one window	public void button_Click(object sender, EventArgs e)\n        {\n            this.panelBoarder.Controls.Clear() //Hide old content\n\n            if (this.pageTwo == null)\n                this.pageTwo = new PageTwo(); // Create Page Two\n\n            this.panelBoarder.Controls.Add(this.pageTwo);\n            this.pageTwo.Visible = true;\n        }	0
27543388	27528734	Compilation error creating a fan-out index from multiple string arrays using RavenDB	from doc in docs\nfrom text1 in ((IEnumerable<dynamic>)doc.Texts1)\nfrom text2 in ((IEnumerable<dynamic>)doc.Texts2)\nfrom text3 in ((IEnumerable<dynamic>)doc.Texts3)\n\nselect new\n{\n    Text1 = text1,\n    Text2 = text2,\n    Text3 = text3\n}	0
17862710	17862491	Is there a keyed SHA256 hash algorithm that is FIPS compliant for .NET?	FIPS.sys Algorithms	0
24563654	24563607	LINQ statement to find the max amount days using datetime	var issues = new[]\n{\n    new Issue { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(4) },\n    new Issue { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(12) },\n    new Issue { StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(1) }\n};\n\nvar theIssue =\n    issues.OrderBy(issue => (issue.StartDate - issue.EndDate).TotalDays)\n          .First();	0
1408731	1408609	Best way to implement Repository Pattern?	public interface IRepository<T> \n{\n        ...\n        IList<T> FindAll();\n        IList<T> FindBySpec(ISpecification<T> specification);\n        T GetById(int id);\n}\n\npublic interface ISpecificRepository : IRepository<Specific> \n{\n        ...\n        IList<Specific> FindBySku(string sku);\n        IList<Specific> FindByName(string name);\n        IList<Specific> FindByPrice(decimal price);\n}	0
3689189	3687487	How to properly bind to a child object?	private BindingSource bndProposal = new BindingSource();\nbndProposal.DataSource = typeof(Model.Proposal);\nlkpAgency.DataBindings.Add("EditValue", bndProposal, "CurrentAgency");\nlkpAgency.Properties.DataSource = FusionLookups.LookupAgencies;\nlkpAgency.Properties.DisplayMember = "Name";\nlkpAgency.Properties.ValueMember = null;	0
2040158	2040118	Find the length of an array without using the Length property	object[] o_arr = new object[5];\n\n// code to initialise array\n\nint i = 0;\nforeach(object o in o_arr)\n{\n    i++;\n}\n\nConsole.WriteLine(i);	0
11320640	11320353	Returning a calculated value from Moq with multiple values passed in	var navMock = new Mock<INavigationService>();  \n     navMock  \n    .Setup(x => x.GetUrlForSystem(It.IsAny<NavigationService.System>(), It.IsAny<string>()))  \n    .Returns((NavigationService.System n, string s) => s);	0
19596316	19596087	Change XML node attribute value via WCF servive	xml.Save(path);	0
13285975	13285924	how to define the multiple where clauses in generics classes C#	public class TestStep<StartEvent, CompletedEvent> \n    where StartEvent : MyBase1, MyInterface1, new()\n    where CompletedEvent : MyBase2, MyInterface2, new()\n{\n}	0
10618898	10617021	Get rendering parameters when multiple sublayouts of the same type are on the page	protected Sitecore.Web.UI.WebControls.Sublayout CurrentSublayout\n    {\n        get\n        {\n            Control c = Parent;\n            while (c != null && !(c is Sitecore.Web.UI.WebControls.Sublayout))\n            {\n                c = c.Parent;\n                if (c == null)\n                    break;\n            }\n\n            return c as Sitecore.Web.UI.WebControls.Sublayout;\n        }\n    }\n\n    protected NameValueCollection CurrentParameters\n    {\n        get\n        {\n            if (CurrentSublayout == null)\n                return null;\n\n            NameValueCollection parms = WebUtil.ParseUrlParameters(CurrentSublayout.Parameters);\n\n            var sanitizedValues = new NameValueCollection();\n            for (int i = 0; i < parms.Count; i++)\n            {\n                if (!string.IsNullOrEmpty(parms[i]))\n                    sanitizedValues.Add(parms.Keys[i], parms[i]);\n            }\n\n            return sanitizedValues;\n        }\n    }	0
26437992	26437878	how to store null values in listbox c#	ListBoxItem itm2 = new ListBoxItem();\nitm2.Content = MyReader.IsDBNull(2) ? "" : MyReader.GetString(2);\nthis.listb2.Items.Add(itm2);	0
5721015	5682364	Adding/Removing MetaColumn from MetaTable	[MetadataType(typeof(FooMetadata))]\n[TableGroupName("Foo")]\n    public partial class Foo \n{ \n\n        [ScaffoldColumn(true)]\n        public string MyNewColumnNotinDBTable\n        {\n            get\n            {\n                return "FooBar";\n            }\n        }\n}\n\n\n\n public class FooMetadata\n    {\n        [ScaffoldColumn(false)]     // hide Id column\n        public object Id { get; set; }\n\n\n        public object Name { get; set; }\n\n        public object MyNewColumnNotinDBTable { get; set; }\n    }	0
23722482	23721354	How to create a Feedback Response in C#	var cred = new NetworkCredential("UserName", "Password", "Domain");\nvar tfs = \n    new TfsTeamProjectCollection(new Uri("YourServerUrl/Collection"), cred);\nvar workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));\nvar workItemTypes = workItemStore.Projects["ProjectName"].WorkItemTypes;\nvar workItemType = workItemTypes["Feedback Response"];\nvar workItem = new WorkItem(workItemType);\n\nworkItem.Title = "Feedback Response 1";\nworkItem.Description = "Totally awesome piece of software!";\nworkItem.Save();	0
21687652	21650412	Hide another application while keeping it active	const int GWL_STYLE = -16;\nconst long WS_VISIBLE = 0x10000000;\n\nwhile (true)\n{\n    var handle = FindWindow(null, "Application Caption");\n\n    if (handle == IntPtr.Zero)\n    {\n        Thread.Sleep(200);\n    }\n    else\n    {\n        int style = GetWindowLong(handle, GWL_STYLE);\n\n        if ((style & WS_VISIBLE) != 0)\n        {\n            ShowWindow(handle, 0x06);\n            break;\n        }\n    }\n}	0
13581133	13559422	Getting errror when trying to run Monotouch-bindngs sample facebook	ld: framework not found AdSupport collect2: ld returned 1 exit status	0
23648429	23648306	Check all values in Array1 exist in values of array2?	var contains = ! b.values.Except(a.values).Any();	0
15121915	15121174	Pulling all Customers modified in QuickBooks since certain datetime using .NET Dev Kit	Intuit.Ipp.Data.Qbd.CustomerQuery customerQuery = new Intuit.Ipp.Data.Qbd.CustomerQuery();\ncustomerQuery.ItemsElementName = new ItemsChoiceType4[] { ItemsChoiceType4.StartCreatedTMS, ItemsChoiceType4.EndCreatedTMS };\ncustomerQuery.Items = new object[] { new DateTime(2012, 01, 01), new DateTime(2013, 01, 01) };\nList<Intuit.Ipp.Data.Qbd.Customer> customersList = customerQuery.ExecuteQuery<Intuit.Ipp.Data.Qbd.Customer>(context).ToList();	0
10703274	10703196	Limit data query and get only last 1000 rows	query.OrderByDescending(criteria).Take(rowCount).OrderBy(criteria)	0
22737470	22737367	What number is a specified digit and how many of them are there in a number?	int digitToSearch = 3;\nint count = 0;\nwhile (number != 0)\n{\n    int digit = number % 10;\n    if (digit == digitToSearch)\n        count++;\n    number /= 10;\n}	0
18825496	18823376	Nhibernate unexpected row count rising after deletes	catch (Exception ex)\n{\n    _session = _session.SessionFactory.OpenSession();\n}	0
13445614	13445510	PayPal datetime (payment_date) parsing issue	DateTime paymentDate;\nDateTime.TryParseExact(HttpUtility.UrlDecode(r["payment_date"]),\n    "HH:mm:ss MMM dd, yyyy PST", CultureInfo.InvariantCulture,\n    DateTimeStyles.None, out paymentDate);	0
18896944	18896802	C# returning from inside a using block	var stream = new StreamReader(fileName);\ntry {\n    return DoSomethingWithTheStream(stream);\n}\nfinally {\n    stream.Dispose();\n}	0
32826323	32826234	How to strip sensitive information from exception message in c#	try\n{\n    RunSensitiveMethod();\n}\ncatch (SecurityTokenValidationException e)\n{\n    // Perhaps something fancier if needed.\n    logger.Log(e);\n    throw new MyCustomException("We screwed up!");\n}	0
15777451	15777363	Add event handler from ClassA to an event called in ClassB	class SettingsForm\n{\n    public void OnTimerEvent(object sender, EventArgs e)\n    {\n        throw new NotImplementedException();\n    }\n}\n\nclass RTimer\n{\n    Timer timer = new Timer();\n    public void StartTimer(SettingsForm settingForm)\n    {\n        timer.Tick += settingForm.OnTimerEvent;\n        timer.Interval = 5000;\n        timer.Enabled = true;\n    }\n}	0
27353204	27343024	Using SQL Server Geography in C# entities without referencing Entity Framework	Microsoft.SqlServer.Types.SqlGeography	0
13742943	13728872	how to access textbox from within class file	private TextBox  gettextbox ( )\n    {\n\n        //without master page\n           /*System.Web.UI.Page Default = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;\n             TextBox TextBox1 = (TextBox)Default[0].FindControl("TextBox1");*/\n\n        //with master page\n       System.Web.UI.Page Default = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;\n   ContentPlaceHolder cph = Default.Controls[0].FindControl("ContentPlaceHolder1") as ContentPlaceHolder;\n           TextBox Textbox1 = (TextBox)cph.FindControl("TextBox1");\n           return Textbox1;\n    }	0
12741298	12734121	Evolve a Graph ZedGraph	tmr.Interval = 6;\ntmr.Tick += new EventHandler(tmr_Tick);\ntmrActive = true;\ntmr.Start();\nvoid tmr_Tick(object sender, EventArgs e)\n{\n   DrawPoint(zedGraphControl1, points, num);   //points is an PointPair array of length num with the new points that i want to add to my Curves(1 point for each Curve)      \n   zedGraphControl1.AxisChange();\n   zedGraphControl1.Refresh();\n   if (Start.Enabled == false) Freeze.Enabled = true;\n}\nprivate void DrawPoint(ZedGraphControl zgc, PointPair[] p, int num)\n    {\n        GraphPane myPane = zgc.GraphPane;\n\n        if (myPane.CurveList.Count < num)\n        {\n            DrawCurves(zgc, num);\n        }\n        for (int i = 0; i < num; i++)\n        {\n            myPane.CurveList[i].AddPoint(p[i]);\n        }\n        actPos = p[0].X;\n        mResize(zgc, actPos);\n    }	0
9598537	9596971	Getting the connection string in a c# service	MyProject.Properties.Settings.Default.MyConnectionString;	0
9462565	9462246	datagridview index change	grid.FirstDisplayedScrollingRowIndex = grid.Rows[2].Index;\nDataGgridridView1.Refresh()\ngrid.CurrentCell = grid.Rows[2].Cells(1) // need to ensure that this is an existing, visible cell\n\ngrid.Rows[2].Selected = True	0
25830030	25829935	Play background music with DirectSound	Dim soundDevice As New Device\nsoundDevice.SetCooperativeLevel(Me.Handle, CooperativeLevel.Normal)\nDim bd As New BufferDescription\nbd.Flags = BufferDescriptionFlags.GlobalFocus\nDim sb As New SecondaryBuffer(My.Resources.ResourceManager.GetStream("MyFile.wav"), bd, soundDevice)\nsb.play(0, BufferPlayFlags.Default)	0
17144985	16982621	C# FreePIE YEI Space Sensor 3 - Stream Data	TSS_EXPORT TSS_Error tss_getLastStreamData(TSS_Device_Id device, char * output_data, unsigned int output_data_len, unsigned int * timestamp);	0
2803812	2803637	Connecting to a network drive programmatically and caching credentials	net use h: \\MACHINE1 <password> /user:<domain>\<user>\nnet use i: \\MACHINE2 <password> /user:<domain>\<user>\nnet use j: \\MACHINE3 <password> /user:<domain>\<user>	0
3710349	3710112	A scenario where static virtual methods make sense	class VertexMeshLoaderObj : IVertexMeshLoader\n{\n  VertexMesh IVertexMeshLoader.LoadFromFile(string fname) { \n    LoadFromFile(fname);\n  }\n  public static VertexMesh LoadFromFile(fname) {\n    ...\n  }\n}	0
32034189	32034154	Double divided by 1	if (Counter % 10 == 0) then { \n    Console.WriteLine("Tick Tock"); \n}	0
4907515	4907341	WPF- How to set event Up, Down, Left, Right without using the Up, Down, Left and Right Arrow Key?	SendKeys.Send("{UP}");//For UP arrow key	0
5757244	5756645	Linq to Xml selecting elements	XDocument xml =\n    XDocument.Load(\n      @"Path to your xml");\n\n  var q = from x in xml.Descendants("item")\n          orderby Convert.ToInt32(x.Attribute("id").Value) ascending\n          select new Calendar\n                   {\n                     Name = x.Elements("Name").Select(a => a.Value).ToList<String>(),\n                     Date = x.Elements("Date").Select(a => a.Value).ToList<String>()\n                   };\n\n  List<Calendar> calendars = q.ToList<Calendar>();\n}\n\npublic class Calendar\n{\n  public List<String> Name { get; set; }\n  public List<String> Date { get; set; }  \n}	0
7716248	7622945	Remove user account from administrators group on remote machine using C# and AccountManagment namespace	public bool RemoveUserFromAdminGroup(string computerName, string user)\n {\n        try\n        {\n            var de = new DirectoryEntry("WinNT://" + computerName);\n            var objGroup = de.Children.Find(Settings.AdministratorsGroup, "group");\n\n            foreach (object member in (IEnumerable)objGroup.Invoke("Members"))\n            {\n                using (var memberEntry = new DirectoryEntry(member))\n                    if (memberEntry.Name == user)\n                        objGroup.Invoke("Remove", new[] {memberEntry.Path});\n            }\n\n            objGroup.CommitChanges();\n            objGroup.Dispose();\n\n            return true;\n        }\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.ToString());\n            return false;\n        }\n }	0
350835	350736	How do I view 'raw' PNG image data 	Bitmap bmp = new Bitmap(@"c:\temp\48bpp.png");\n  BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),\n    ImageLockMode.ReadOnly, PixelFormat.Format48bppRgb);\n  // Party with bd.Scan0\n  //...\n  bmp.UnlockBits(bd);	0
32408100	32408081	How to write a c# log file?	public class YourClass\n{\n  private static Logger logger = LogManager.GetCurrentClassLogger();\n\n  public void ButtonWasPressedEvent()\n  {\n    logger.Info("Thanks for pressing dude!");\n  }\n}	0
11001358	11001059	How generate Guid from entity framework when object created	[DatabaseGenerated(DatabaseGeneratedOption.Identity)]\npublic Guid Id { get; set; }	0
12834426	12834249	Execute stored procedure from WPF	con.Open(); \n\nusing (SqlCommand cmd = new SqlCommand("submitdata", con))\n{\n    cmd.CommandType = CommandType.StoredProcedure;\n\n    SqlParameter param1 = new SqlParameter("@Firstname", SqlDbType.VarChar);\n    param1.Value = "my first name";\n\n     // ... the rest params\n\n    cmd.Parameters.Add(param1);\n\n    // cmd.Parameters.Add(param2);....\n\n    cmd.ExecuteNonQuery(); \n}\n\ncon.Close();	0
2329710	2329579	Reaching child records in a SQL Server table	-- define a table to hold the primary keys of the selected master rows\nDECLARE @MasterIDs TABLE (HeaderNo INT)\n\n-- fill that table somehow, e.g. by passing in values from a C# apps or something\n\nINSERT INTO dbo.NewTable(LineCodeNo, Item, Quantity, Price)\n   SELECT SalesLineCodeNo, Item, Quantity, Price \n   FROM dbo.SalesOrderLine sol\n   INNER JOIN @MasterIDs m ON m.HeaderNo = sol.SalesHeaderNo	0
14877565	14656333	How to get the item selected from ListVIew	Segment seg= ListView.SelectedItem as Segment;\nif (seg!= null)\n{\n    tbckChoiceSelected.Text = compa.CompanyName;//TextBlock called bckChoiceSelected\n}	0
8918070	8918042	Linq to Xml - Create XAttribute conditionally	new XElement("OnlineOrder", ((customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(o=>o.Type=="Online").Any())\n        ? customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(p1 => p1.Type == "Online").Select(\n            (o1 => new List<XAttribute>() { new XAttribute("Amount", o1.Amount),\n                    new XAttribute("CardType", o1.CardType),\n                    new XAttribute("Quantity", o1.Quantity) }\n            ))\n        : null)),	0
3945343	3945322	Same number in all 5 boxes and it's supposed to be 5 different numbers in 5 different boxes	public void RandomNumber(int min, int max)\n    {\n        Random random = new Random();\n\n        int num = random.Next(min, max);\n        int num2 = random.Next(min, max);\n        int num3 = random.Next(min, max);\n        int num4 = random.Next(min, max);\n        int num5 = random .Next(min, max);\n\n        lblPickFive_1.Text = num.ToString();\n        lblPickFive_2.Text = num2.ToString();\n        lblPickFive_3.Text = num3.ToString();\n        lblPickFive_4.Text = num4.ToString();\n        lblPickFive_5.Text = num5.ToString();\n    }	0
16947655	16947616	add "Where" to a linq statement?	public object getItemList(string term) {\n    var repo = getRepo();\n    return from i in repo.getItem() \n           where i.Name == term\n           select new { name = i.name, itemType = i.itemType.name };\n}	0
4636156	4636111	Get size of image on a web page	Content-Length	0
12859780	12858867	How to get around with this conversion issue?	var f = float.Parse("6.9");\nvar d = (double)f;\nSystem.Diagnostics.Debug.WriteLine(d.ToString()); //6.90000009536743	0
12214659	12178379	Dashed shapes drawing in unexpected scale	e.Graphics.ScaleTransform(1, 1);	0
21321914	21320933	Group a DataTable into separate DataTables?	DataTable table; //Your Datatable\nList<DataTable> allCountryTables = new List<DataTable>();\n\n//Get distinct countries from table\nDataView view = new DataView(table);\nDataTable distinctValues = view.ToTable(true, "Country");\n\n//Create new DataTable for each of the distinct countries identified and add to allCountryTables list    \nforeach (DataRow row in distinctValues.Rows)\n{\n    //Remove filters on view\n    view.RowFilter = String.Empty;\n    //get distinct country name\n    String country = row["Country"].ToString());\n    //filter view for that country\n    view.RowFilter = "Country = " + country;\n    //export filtered view to new datatable\n    DataTable countryTable = view.ToTable();\n    //add new datatable to allCountryTables \n    allCountryTables.Add(countryTable);\n}	0
8633	8625	Generic type conversion FROM string	public class TypedProperty<T> : Property where T : IConvertible\n{\n    public T TypedValue\n    {\n        get { return (T)Convert.ChangeType(base.Value, typeof(T)); }\n        set { base.Value = value.ToString();}\n    }\n}	0
10449445	10449294	Minimum value in 2 arrays	var resMin = res_was.Min();\nvar powMin = pow_con.Min();\nfor(int i = 0; i < n; i++)    \n{\n      if(res_was[i] == resMin && pow_con[i] == powMin)\n      {\n         Console.writeLine(i);\n         break;\n      }    \n}	0
11816950	11816879	Getting all the nodes in a specific level of a tree	IEnumerable<simpletest> ElementsAtDepth(int depth) {\n    if(depth > 0) {\n        foreach(simpletest child in this.Children)\n            foreach(simpletest element in child.ElementsAtDepth(depth - 1))\n                yield return element;\n    }\n    else {\n        foreach(simpletest element in this.Children)\n            yield return element;\n    }\n}	0
5325483	5325370	How to catch errors from worker threads in console application written in C#	public static void Main(string[] args)\n{             \n    string[] files = System.IO.Directory.GetFiles(@".", "*.*");      \n\n    Parallel.ForEach(files, x =>\n    {\n      try\n      {\n        MyAction(x);\n      }\n      catch(Exception ex)\n      {\n        Console.WriteLine(ex.ToString());\n      }\n    });        \n}\n\nstatic void MyAction(string x)\n{      \n  throw new ApplicationException("Testing: " + x);\n}	0
15938378	15938267	How to open file that is shown in listbox?	Dictionary<string, string> startupinfoDict = new Dictionary<string, string>();\n    private void readfiles()\n    {\n        string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);\n\n        var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));\n\n        foreach (string file in files)\n        {\n            startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));\n            startupinfoDict.Add(Path.GetFileNameWithoutExtension(file), file);\n        }\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        if (listBox1.SelectedItem != null)\n        {\n            string s = listBox1.SelectedItem.ToString();\n\n            if (startupinfoDict.ContainsKey(s))\n            {\n                Process.Start(startupinfoDict[s]);\n            }\n        }\n    }	0
18098484	16954144	How to change the visibility of the button got by Xpath in Selenium	IWebElement element = driver.FindElement();\n  js.ExecuteScript("arguments[0].style.visibility = 'visible', arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", element);\n  element.Click();	0
8446580	8430450	Silverlight 4 application freezes without throwing any exception	private void ChildWindow_Closed(object sender, EventArgs e)\n    {\n        this.DialogResult = false;\n    }	0
6343764	6343114	How to implement an atomic switch from one IObserver to another?	public class ExchangeableObserver<T> : IObserver<T> {\n  private IObserver<T> inner;\n\n  public ExchangeableObserver(IObserver<T> inner) {\n    this.inner=inner;\n  }\n\n  public IObserver<T> Exchange(IObserver<T> newInner) {\n    return Interlocked.Exchange(ref inner, newInner);\n  }\n\n  public void OnNext(T value) {\n    inner.OnNext(value);\n  }\n\n  public void OnCompleted() {\n    inner.OnCompleted();\n  }\n\n  public void OnError(Exception error) {\n    inner.OnError(error);\n  }\n}	0
19549352	19548538	Reading Excel data with comma separated and carriage returns	string[] Codes = reader["Code"].ToString().Trim().Split('\n');\n  string[] IDs = reader["ID"].ToString().Trim().Split(',');\n\n\n\n   for (int i = 0; i <= Codes.Count() - 1; i++)\n   {\n     //table.rows.add one by one..  \n   }	0
13540032	13539864	How to open a new browser window after clicking on a link in rich text box(C#)	RichTextBox1_LinkClicked(System.Object sender, System.Windows.Forms.LinkClickedEventArgs e)\n{\n    Process.Start(e.LinkText);\n    //open link with default application\n}	0
2012345	2012282	Open Excel File on a specific worksheet	using Excel; \n\n Excel.Application excelApp = new Excel.ApplicationClass();\n\n  // if you want to make excel visible to user, set this property to true, false by default\n  excelApp.Visible = true;\n\n // open an existing workbook\n string workbookPath = "c:/SomeWorkBook.xls";\n    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,\n        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",\n        true, false, 0, true, false, false);\n\n\n\n// get all sheets in workbook\n   Excel.Sheets excelSheets = excelWorkbook.Worksheets;\n\n  // get some sheet\n string currentSheet = "Sheet1";\n    Excel.Worksheet excelWorksheet = \n        (Excel.Worksheet)excelSheets.get_Item(currentSheet);\n\n // access cell within sheet\n  Excel.Range excelCell = \n        (Excel.Range)excelWorksheet.get_Range("A1", "A1");	0
8298675	8298640	How to join two List<string> in c# using LINQ	var distinctCountriesList = homeCountry.Union(covCountry).ToList();	0
23784590	23653485	How to add objects to a RadioButtonList based on random order ?	Random ran = new Random();\nvar numbers = Enumerable.Range(1, 4).OrderBy(i => ran.Next()).ToList();\n\nList<ListItem> ans= new List<ListItem>();\nans.Add(new ListItem(rsQuestion["a"].ToString(), "A"));\nans.Add(new ListItem(rsQuestion["b"].ToString(), "B"));\nans.Add(new ListItem(rsQuestion["c"].ToString(), "C"));\nans.Add(new ListItem(rsQuestion["d"].ToString(), "D"));\n\nforeach (int num in numbers)\n{\n    RadioButtonList1.Items.Add(ans[num - 1]);\n}	0
1009373	1009349	Use a linq expression to get a single array or list of strings from inside a collection of objects without using foreach and addrange	var result2 = buddies.SelectMany(b => b.Sayings);	0
21132167	21103143	Rendering Textured Terrain With SharpDX Toolkit	AddressU = wrap;	0
21155042	21155003	Get attributes of all properties in a class c#	typeof(EmployeeModel).GetProperty(?First?).GetCustomAttributes(...)	0
17294602	17294030	How to Seed all my data properly Code First configuration	...\nAddresses = new List<Address> { \n                    new Address\n                        {\n                            Id = 1, //depends on if you have an address defined and how your schema is created\n                            StreetName = "asd",\n                            ZipCode = "123",\n                            Country = "abc",\n                            Cycle = 2\n                        }},\n...	0
24550776	24529172	How to get location by address in wp8 and display in AutoCompleteBox?	private async void Maps_GeoCoding(string sender)\n    {\n        var myAddress = new List<String>();\n        var myGeolocator = new Geolocator();\n        var myGeoposition = await myGeolocator.GetGeopositionAsync();\n        var myGeocoordinate = myGeoposition.Coordinate;\n        MyGeoCoordinate =\n            CoordinateConverter.ConvertGeocoordinate(myGeocoordinate);\n        if (MyGeoCoordinate == null) return;\n        var geoQuery = new GeocodeQuery { SearchTerm = sender, GeoCoordinate = MyGeoCoordinate };\n        var locations = await geoQuery.GetMapLocationsAsync();\n        var location = locations.FirstOrDefault();\n        if (location != null)\n        {\n            myAddress.Add(location.Information.Address.City + " " + location.Information.Address.Street + " " + location.Information.Address.HouseNumber);\n            MapWithMyLocation.Center = location.GeoCoordinate;\n        }\n        TxtSearch.ItemsSource = myAddress;\n    }	0
6848697	6848657	Merge Portions of a data table into one	DataTable table = new DataTable();\nDataTable existing = listOfTables[0];\n\nfor(int i = 20; i < 30; i ++)\n{\n    table.Columns.Add(existing.Column[i].Name;\n    table.Columns.Add(existing.Column[i + 20].Name;\n}\n\nforeach(DataTable table in listOfTables)\n{\n    foreach(DataRow row in table.Rows)\n    {\n        DataRow newRow = table.NewRecord();\n        foreach(Column column in table.Columns)\n        {\n           newRow[column.Name] = row[column.Name];\n        }\n        table.Rows.Add(row);\n    }\n}	0
14687434	14687311	Parse Json Twitter search	JObject.Parse	0
21338498	21338349	.net Datagrid WinForm - Adding a DataGridViewButtonColumn Automatically Adds a Row	dataGridView1.AllowUserToAddRows = false;	0
19595533	19594847	How to get all properties that are anotated with some attribute?	var attributeSymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.OneToOneAttribute");\nvar propertySymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.Program")\n                     .GetMembers()\n                     .Where(m => \n                            m.Kind == CommonSymbolKind.Property && \n                            m.GetAttributes().Any(a => a.AttributeClass.MetadataName == attributeSymbol.MetadataName));	0
9117718	9117608	Face detection for C# in ASP.NET	Allowing OpenCV functions to be called from .NET compatible languages such as C#	0
20271918	20270266	Json.Net PopulateObject Appending list rather than setting value	var serializerSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};\n\n\nJsonConvert.PopulateObject(jasonString, myObject, serializerSettings)	0
18784488	18784411	Reading a specific time file and writing the contents to another one	string temp_file_format = "ScriptLog_" + DateTime.Now.ToString("dd_MM_yyyy_HH") + "*";	0
2797239	2797204	How can i discover that object is attached to specific Object Context?	bool isPresent = objectStateManager.TryGetObjectStateEntry(((IEntityWithKey)order).EntityKey, out stateEntry);\nif (isPresent)\n{\n    Console.WriteLine("The entity was found");\n}	0
25752169	25748939	Run Access Queries via Interop?	var accApp = new Microsoft.Office.Interop.Access.Application();\naccApp.OpenCurrentDatabase(@"C:\Users\Public\Database1.accdb");\nMicrosoft.Office.Interop.Access.Dao.Database cdb = accApp.CurrentDb();\n\nMicrosoft.Office.Interop.Access.Dao.Recordset rst = \n        cdb.OpenRecordset(\n            "SELECT FullName FROM ClientQuery", \n            Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenSnapshot);\nwhile (!rst.EOF)\n{\n    Console.WriteLine(rst.Fields["FullName"].Value);\n    rst.MoveNext();\n}\nrst.Close();\naccApp.CloseCurrentDatabase();\naccApp.Quit();	0
18654468	18654123	Reverse elements of a string array	string[] myString = {"a","b","c","d", "e"};\nfor(int i = 0; i < myString.Length/2; i++)\n{\n   myString[i] += myString[myString.Length -1 -i];\n   myString[myString.Length -1 -i] = ""+myString[i][0];\n   myString[i] = "" + myString[i][1];\n}	0
9538366	9538213	XMLString needs to change the format	var doc = XDocument.Load(...);\nvar groups = doc.Descendants(ProductGroup);\n\nvar newDoc = new XElement("ProductGroups", \n    groups.Select(pg => new XElement("Name", \n            new XAttribute("Id", pg.Element("Id").Value), \n            pg.Element("Name").Value) ));\n\n\nnewDoc.Save(...);	0
27771453	27771319	Can't read all lines in file that being used by another process	File.Open(@"C:\process.log", FileMode.Open,FileAccess.ReadWrite, FileShare.ReadWrite);	0
20484244	20483998	c++ jagged array slice in c#	for (int i = 0; i < parallelopipedPts.Length; i++)\n{\n    parallelopipedPts[i] = new double[3];\n}	0
21706824	21706770	Checking if string contains multiple letters	// isolate the letters\nstring[] letters = new string[] { "D", "E", "F" }; // other strings or letters\n\n// interate between your data\nforeach(DictionaryWord word in dictionaryWords)\n{\n    // check if the work does not contain any letter\n    if (!letters.Any(x => word.Contains(x))\n    {\n        // Word does not contain letters, word is good\n    }\n}	0
2246326	2246271	Is there a XML to LINQ Generator?	Assembly.GetManifestResourceStream	0
28357972	28357245	Possible to move a Form from one Container to another? How?	Form2 f = new Form2();\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        f = new Form2()\n        {\n            Top = 0,\n            Left = 0,\n            Width = 100,\n            Height = 100,\n            TopLevel = false\n        };\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n\n        int x = int.Parse(this.textBox1.Text);             \n        this.tabControl1.TabPages[x].Controls.Add(f);\n        f.Show();\n\n        this.tabControl1.Refresh();\n    }	0
31933009	31917163	while assigning value to asp hidden field, escape character gets cleared	string jsonString = Convert.ToString(Page.Request.QueryString["searchdata"]);\njsonString = HttpUtility.UrlDecode(jsonString);\n// Here I am getting following json string\n// {"StartDate":"\/Date(1436466600000)\/","EndDate":"\/Date(1439145000000)\/","ClassType":0,"InstructorID":0}\n// By using following line I have corrected json string and now it is being deserialized to object.\njsonString = jsonString.Replace("/", "\\/");\nJavaScriptSerializer oJS = new JavaScriptSerializer();\nChartSearchCriteria oRootObject = new ChartSearchCriteria();\noRootObject = oJS.Deserialize<ChartSearchCriteria>(jsonString);	0
23152863	22666144	Detect current VSIX package's version from code	var doc = new XmlDocument();\n        doc.Load(manifestPath);\n        var metaData = doc.DocumentElement.ChildNodes.Cast<XmlElement>().First(x => x.Name == "Metadata");\n        var version = identity.GetAttribute("Version");	0
21496642	21492699	How can I make certain properties of my EF code-first classes internal to my DAL?	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n\n    {\n        modelBuilder.Entity<User>().HasMany(x => x.Projects);\n    }	0
13975628	13975554	How to perform arithmetic operation between the datavariable accessing value and the integer value in C#?	int result = Convert.ToInt32(Application["Amount"]) + 2;	0
8717990	8717965	how to override set in C# of automatic properties	private float _inverseMass;\n\npublic float inverseMass\n{\n    get { return _inverseMass; }\n    set\n    {\n        _inverseMass = value;\n        onMassChanged();\n    }\n}	0
28521096	28521075	how to change text dynamically added button c#	this.Controls.Find("btn55",true).FirstOrDefault().Text = "BBB";	0
11292351	11289090	Detect broken stream in VideoMixingRenderer	IMediaEvent::GetEvent	0
9858736	9858639	Multithreading Arrays	public void ParalellizeArrayFill(int threadCount, float[] array)\n{\n    if (array == null || array.Length == 0)\n        throw new ArgumentException("Array cannot be empty");\n\n    if (threadCount <= 1)\n        throw new ArgumentException("Thread count should be bigger than 1");\n\n    int itemsPerThread = array.Length / threadCount;\n    for (int i = 0; i < threadCount; i++)\n    {\n        Thread thread = new Thread( (state) => FillArray(array, i*itemsPerThread, itemsPerThread));\n        thread.Start();\n    }  \n}\n\nprivate void FillArray(float[] array, int startIndex, int count)\n{\n    for (int i = startIndex; i < startIndex + count; i++)\n    {\n        // init value\n        array[i] = value; \n    }\n}	0
13208092	13207887	Date format issue in C#	var jsdate = "Tue Jan 15 00:00:00 UTC+0530 2008";\n var format = "ddd MMM d HH:mm:ss UTCzzzzz yyyy";\n var date = DateTime.ParseExact(jsdate, format, CultureInfo.InvariantCulture);\n\n Console.WriteLine(date.ToString("dd/MMM/yyyy"));	0
28710735	28667045	JSON.NET unable to serialize excel array	object[,] zeroBasedArr = new object[oneBasedArr.GetLength(0), oneBasedArr.GetLength(1)];\nArray.Copy(oneBasedArr, 1, darr, 0, oneBasedArr.GetLength(0) * oneBasedArr.GetLength(1));	0
2540175	2540146	How do you create a unit-testing stub for an interface containing a read-only member?	public class IIdentityStub : IIdentity{\n    private string _name;\n\n    public IIdentityStub(string name){\n        _name = name;\n    }\n\n    public string Name { get { return _name; } }\n}	0
27411188	27407636	Binding a TextBox's Height to Parent via Code	Double.NaN	0
1651109	1651092	How do I make the params keyword usage similar to writing to the Console	void MyMethod(string format, params object[] obj) {\n    var formattedString = String.Format(format, obj);\n    // do something with it...\n}	0
4321309	4321300	C#: easiest way to populate a ListBox from a List	List<string> MyList = new List<string>();\n        MyList.Add("HELLO");\n        MyList.Add("WORLD");\n\n        listBox1.DataSource = MyList;	0
6388158	6387995	How to detect if the control is input control or not in windows and overwrite the input	public Form1()\n    {\n        InitializeComponent();\n        TextBox textBox = new TextBox();\n        textBox.TextChanged += CheckInputText;\n    }\n\n    public void CheckInputText(object sender, EventArgs e)\n    {\n        // Modify text in the input control.\n    }	0
11471683	11471606	how to add new datatable to dataset at first position	var tables = new DataTable[4];\ntables[0] = mynewtable;\ntables[1] = mydataset.Tables[0];\ntables[2] = mydataset.Tables[1];\ntables[3] = mydataset.Tables[2];\nmydataset.Tables.Clear();\nmydataset.Tables.Add(Tables[0]);\nmydataset.Tables.Add(Tables[1]);\nmydataset.Tables.Add(Tables[2]);\nmydataset.Tables.Add(Tables[3]);	0
21515083	21514367	Save x amount of lines with StreamWriter and Console output	// Keeps most recent 100???200 lines.\nList<string> cache = new List<string>();\n\nwhile (true)\n{\n    // Create new writer, overwriting old file (if it already exists).\n    using (var streamWriter = new StreamWriter(/* ... */))\n    {\n        // Write last 100 lines from cache.\n        if (cache.Count > 0)\n            streamWriter.WriteLine(string.Join(Environment.NewLine, cache));\n\n        // Get next line and write it.\n        string line = /* your implementation */\n        streamWriter.WriteLine(line);\n\n        // Append to cache.\n        cache.Add(line);\n\n        // If cache limit reached, we need to recycle.\n        if (cache.Count == 200)\n        {\n            // Keep only most recent 100 lines.\n            cache = cache.Skip(100).ToList();\n\n            // Start a new iteration, causing the file to be overwritten.\n            continue;\n        }\n    }\n}	0
31620759	31620630	Open native maps in Windows phone 8 application on button click	BingMapsDirectionsTask bingMapsDirectionsTask = new BingMapsDirectionsTask();\nGeoCoordinate spaceNeedleLocation = new GeoCoordinate(47.6204,-122.3493);\nLabeledMapLocation spaceNeedleLML = new LabeledMapLocation("Space Needle", spaceNeedleLocation);\nbingMapsDirectionsTask.End = spaceNeedleLML;\nbingMapsDirectionsTask.Show();	0
3124978	3124960	How can you nibble (nybble) bytes in C#?	byte x = 0xA7;  // For example...\nbyte nibble1 = (byte) (x & 0x0F);\nbyte nibble2 = (byte)((x & 0xF0) >> 4);\n// Or alternatively...\nnibble2 = (byte)((x >> 4) & 0x0F);\nbyte original = (byte)((nibble2 << 4) | nibble1);	0
27696827	27696682	Regex or split logic to create array of text between curly braces in C#	[TestMethod]\npublic void TestRegex()\n{\n    var input = "select * from cable where exchange like " +\n                "'%{Enter Exchange:}%' and Type like '%{Enter Type:}%'";\n\n    var result = Regex.Matches(input, @"%\{(.+?)\}%")\n            .Cast<Match>()\n            .Select(m => m.Groups[1].Value)\n            .ToArray();\n\n    result.Should().HaveCount(2);\n    result.Should().Contain("Enter Exchange:");\n    result.Should().Contain("Enter Type:");\n}	0
8898718	8898042	Multiple users in Windows Forms	static void Main()\n{\n  Application.EnableVisualStyles();\n  Application.SetCompatibleTextRenderingDefault(false);\n\n  DialogResult running = DialogResult.OK;\n  while (running == DialogResult.OK) {\n    form_login login = new form_login();\n    Application.Run(login);\n    running = login.DialogResult;\n    if (login.DialogResult == DialogResult.OK)\n      Application.Run(new Form1());\n      // or your other forms...\n  }\n}	0
20154972	20154336	How to create a testing / temp in memory only DataTable using Linq	const int cols = 6;\nconst int rows = 20;\n\nDataTable nt = new DataTable("new table");\n\nnt.Columns\n  .AddRange(\n     Enumerable\n      .Range(1,cols)\n      .Select(x => new DataColumn("col"+x.ToString())).ToArray());\n\nEnumerable\n .Range(1,rows).ToList()\n .ForEach(x => nt.Rows\n                 .Add(\n                  Enumerable\n                  .Range(1,cols)\n                  .Select(y => "row"+x.ToString()+"col"+y.ToString()).ToArray()));	0
15096173	15095942	File name from StreamReader C# - asp.net MVC3 to array	var fileName = System.Web.HttpContext.Current.Server.MapPath(\n    "/Video/" + fnList[i] + ".srt");\nStreamReader file = new StreamReader(fileName);	0
19277950	19264676	Obtaining UI dispatcher in Windows phone 8	class DotNetClass : IWindowsRuntimeInterface\n{\n    void AlertCaller(string message)\n    {\n        Deployment.Current.Dispatcher.BeginInvoke(() =>\n        {\n            MessageBox.Show(message);\n        }\n    }\n}	0
10224173	10223784	Export into excel file without headers c# using Oledb	commandString = "Insert into [Sheet1$] (F1, F2) values('test1', 'test2')"	0
11361907	11361035	Reading a RSS feed using visual C#	public static List<RssNews> Read(string url)\n{\n    var webClient = new WebClient();\n\n    string result = webClient.DownloadString(url);\n\n    XDocument document = XDocument.Parse(result);\n\n    return (from descendant in document.Descendants("item")\n            select new RssNews()\n                {\n                    Description = descendant.Element("description").Value,\n                    Title = descendant.Element("title").Value,\n                    PublicationDate = descendant.Element("pubDate").Value\n                }).ToList();\n}	0
26672636	26672617	How to use base constructor data to another constructor in the same class?	public Employee(string firstName, string lastName): this(firstName) // this, not base\n{\n    LastName = lastName;\n}	0
26656869	26655316	How do can I programmatically automate the comparison of Visual Studio Solution Files?	Combined.sln	0
3972692	3972652	Get the extents on a drawing using the database without opening the drawing	Database database = new Database(false, true);\n\nString drawingFilePath = @"C:\Drawings\MyDrawing.dwg";\n\ndatabase.ReadDwgFile(drawingFilePath, FileShare.ReadWrite, true, String.Empty);\ndatabase.UpdateExt(true);\n\nPoint3d extentsMax = database.Extmax;\nPoint3d extentsMin = database.Extmin;	0
23829921	23829753	Get new access token from json object c# weatherbug api	JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(YourJsonResponse);\nvar token = jObject.SelectToken("OAuth20").SelectToken("access_token");	0
12676037	12576762	How to encode & decode non Ascii characters?	string str="?rgrgrgr??hhtt?";\nstr=str.Replace("?", "\u00e1");	0
20197537	20197136	Use the ref and out keyword on a pointer parameter	ref Link*	0
14861210	14861137	store parent-child relationship	Dictionary<string, string[]>	0
4172463	4171193	ASP.NET - Getting the object inside Repeater ItemTemplate with/without Eval	if (e.Item.ItemType = ListItemType.Item)\n{\n  photo p = (photo)e.DataItem;\n  Textbox txtTime = (Textbox)e.Item.FindControl("txtTime");\n\n  txtTime.text = (p.Time == null ? "" : ((DateTime)p.Time).ToString("dd/MM/yyyy HH:mm:ss"));\n}	0
9148070	9147908	LINQ expression to find XElement and loop through attributes which can each add to listbox	XDocument doc = XDocument.Load("your XML");\nvar device = doc.Descendants("device").Select(item => item).Where(\n                        item => item.Attribute("name").Value.ToString().Equals("some name")).FirstOrDefault();\n\nif(null != device)\n{\n    var items = device.Attributes().Select(item => item).Where(item =>  item.Value == "True");\n    if(null != items)\n    {\n        //you can also customize name according to your needs here\n        yourListBox.AddRange(items.Select( item => item.Name.ToString() ).ToList());\n    }\n}	0
14345150	14345128	Two MessageBox quit confirmation messages	var confirmationBox = MessageBox.Show(@"Do you want to quit", @"Title",\n    MessageBoxButtons.YesNo);\n\nif (confirmationBox == DialogResult.Yes)\n{\n    var confirmationBox2 = MessageBox.Show(@"Are you sure?", @"", MessageBoxButtons.YesNo);\n    if (confirmationBox2 == DialogResult.No)\n    {\n        e.Cancel = true;\n    }\n}	0
21879877	21879245	How to differentiate between Values in String Array in c#	Dictionary<string, string> _dic = new Dictionary<string, string>();\nstring line = "1 03/MAR/2013 06:41:06 9448485859 00:15 0.40 **";\nstring line1 = "SNo Date Time Number Duration/Volume Amount";\nline.Replace('*', ' ');\nstring[] split1 = line.Split(new Char[] { ' ' });\nstring[] split2 = line1.Split(new Char[] { ' ' });\n\nfor (int _i = 0; _i < line.Length; _i++)\n{\n    _dic.Add(split1[_i], split2[_i]);\n}	0
29759918	29759861	Can't find selected item in listbox C# ASP.NET	protected void Page_Load(object sender, EventArgs e)\n{ \n    if(!IsPostBack) \n    {\n      ListBox1.Items.Clear();\n      SelectAllUsers();\n    }\n}	0
29265831	29265700	Duplicate values in Xml database	var duplicate = doc.Element("Players").Elements("player").Where(x => (string)x.Attribute("name").Value == userName).SingleOrDefault();	0
22352888	22352346	Set Timer For Windows phone 8 App Using XAML With C#	//make global declaration of a counter variable \n\n\n int counter =60;    \n    void OnTimerTick(Object sender, EventArgs args)\n       {       \n         counter --;\n         if(counter<0)\n         {\n          newTimer.Stop();\n          counter=60;\n         }\n        else\n         {\n          clock.Text =counter.ToString();\n         }\n       }	0
6169381	6169306	Session Variable being created and access before long process?	public static class MyApplicationStateBag\n{\n    public static Dictionary<string,object> Objects {get; private set;}\n}	0
19360563	19359907	Howto use a Timer in c#	public partial class Char1 : Form\n{\n    private System.Timers.Timer aTimer;\n\n    public static void OnTimedEvent(object source, ElapsedEventArgs e)\n    {\n        Mainprog.count += 1;\n    }\n    public Char1()\n    {\n        InitializeComponent();\n        aTimer = new Timer();\n        aTimer.Interval = 2000;\n        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n    }\n\n    private void checkBox1_CheckedChanged(object sender, EventArgs e)\n    {\n        if(checkBox1.Checked)\n        {\n            aTimer.Start();\n        }\n        else\n        {\n            aTimer.Stop();\n        }\n    }\n}	0
11437474	11435328	How to only read cells with values with in a specific range in Excel - using VSTO C#	foreach (Excel.Range cell in namedRange.Cells)\n            {\n                if (String.IsNullOrEmpty(cell.Value.ToString()))\n                {\n                    string thisCellHasContent = cell.Value.ToString();\n                    string thisCellAddress = cell.Address.ToString();\n                }\n            }	0
13309443	13309417	Using optional arguments	_order.GetComputers(ramSizeInGB: ram);	0
11888672	11888603	Storing user details in application variable	void Application_Start(object sender, EventArgs e)\n{\n    var userList = new List<string>();\n    Application["UserList"] = userList;\n}\nvoid Session_Start(object sender, EventArgs e)\n{\n    var userName = Membership.GetUser().UserName;\n\n    List<string> userList;\n    if(Application["UserList"]!=null)\n    {\n        userList = (List<string>)Application["UserList"];\n    }\n    else\n        userList = new List<string>();\n    userList.Add(userName);\n    Application["UserList"] = userList;\n}	0
26220055	26219947	Request uri too long with webservice	using (var client = new HttpClient())\n{\n    client.BaseAddress = new Uri("http://<url>/webservice.php");\n    client.DefaultRequestHeaders.Accept.Clear();\n    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));\n\n    var jsonContent = JsonConvert.SerializeObject(new YourObject\n    {\n        // Pseudo code... Replace <...> with your values etc\n        Operation = <YourOperation>,\n        ElementType = <YourElementType>,\n        Element = <YourElement>,\n        // etc...\n    });\n\n    HttpResponseMessage response;\n    using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))\n    {\n        response = await client.PostAsync("youroperation/", httpContent);\n    }\n\n    // Do something with response if you want\n}	0
622971	622735	How have you structured your network oriented apps?	_irService.SendCommand(someAsciiCommand);	0
20965431	20965223	get single element from list in C#	((HiddenField)GridViewPagingControl.FindControl("TotalRows")).Value = Convert.ToString(List.First().tRecordCount);	0
26506152	26506002	C# Accessing Method from Controller	using VehicleAudits2_v1.classes;\n\npublic class SomeController : Controller\n{\n\n  public ActionResult SomeAction()\n  {\n    ConvertImage convert = new ConvertImage();\n    convert.base64ToImage("SomeValue");\n    return View();\n\n  }\n\n}	0
29231689	29228664	How to invoke the explicitly interface implement method while the interface is private/internal?	// Some test stuff, replace this with your own.\nExpression e = null;\nSqlProvider p = new SqlProvider();\n\n// Get the IProvider interface\nvar iProvider = typeof(SqlProvider).FindInterfaces((t, o) => t.FullName == "System.Data.Linq.Provider.IProvider", null).FirstOrDefault();\n\nif (iProvider != null)\n{\n    // Get the Compile method on the interface\n    MethodInfo m = iProvider.GetMethod("Compile");\n\n    // Call it!\n    var output = m.Invoke(p, new object[] { e });\n}	0
2483054	2483023	How To Test if a Type is Anonymous?	private static bool CheckIfAnonymousType(Type type)\n{\n    if (type == null)\n        throw new ArgumentNullException("type");\n\n    // HACK: The only way to detect anonymous types right now.\n    return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)\n        && type.IsGenericType && type.Name.Contains("AnonymousType")\n        && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))\n        && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;\n}	0
24457591	24457330	Binding a DataGridView to a Object list	Class AttendancePresenter \n{\n    private readonly BindingList<IAttendance> _attendanceList;\n\n    public AttendancePresenter()\n    {\n        _attendanceList = new BindingList<IAttendance>();\n        _View.AttendanceGrid = _attendanceList;\n    }\n\n    private void AddAttendance()\n    {\n        _attendanceList.Add(attendanceModel);\n    }\n\n    private void GetAttendance()\n    {\n        _attendanceList.Clear();\n\n        var attendance = _DataService.GetAttendance();\n\n        foreach (var attendant in attendance)\n        {\n            _attendanceList.Add(attendant);\n        }\n    }\n\n    private void Save()\n    {\n        _DataService.InsertAttendance (_attendanceList);\n    }\n}	0
10040327	10019674	How can I make a C# UI remove Panel Controls using a button listener (basically)?	Controls.SetChildIndex(PartLayout,0); //this sets the PartLayout Panel (Extended)\n                                      //to the 0 index or the front/visible layer	0
4503186	4503108	EF: Deleting from Many-to-Many (Bridge) table	var query = from item in context.Table1\n            where item.id1 == id1\n            select item;\n\nvar table1 = query.Single();\ntable1.Table2s.Clear();\n\ncontext.SaveChanges();	0
1501221	1501188	How do I group by Events by year using a single LINQ query?	var yearsList = from e in Events\n                group e by e.EventDate.Year into g\n                select new { Year = g.Key, Events = g };	0
18150084	18135982	Alter hosted Winform control from ViewModel	public string VlcUrl\n{\n    get { return (string)GetValue(VlcUrlProperty); }\n    set { SetValue(VlcUrlProperty, value); }\n}\n\npublic static readonly DependencyProperty VlcUrlProperty =\n        DependencyProperty.Register("VlcUrl", typeof(string), typeof(VlcPlayer), new PropertyMetadata(null, OnVlcUrlChanged));\n\nprivate static void OnVlcUrlChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n{\n    var player = obj as VlcPlayer;\n    if (obj == null)\n       return;\n\n    obj.ChangeVlcUrl(e.NewValue);\n}\n\nprivate void ChangeVlcUrl(string newUrl)\n{\n    //do stuff here\n}	0
11106840	11105419	Can I break my report into groups with LINQ?	var groups = _repository.GetAll()\n  .GroupBy(x => x.RowKey.Substring(0, 2))\n  .Select(x => new \n  { \n    RowKey = x.Key, // + "00"\n    Count = x.Count(),\n    SubItems = x\n      .GroupBy(y => y.RowKey.Substring(0, 4))\n      .Select(z => new \n      { \n        RowKey = z.Key, \n        Count = z.Count() \n      })\n  });\n\nforeach(var outerGroup in groups)\n{\n  Console.WriteLine(outerGroup.RowKey + " " + outerGroup.Count);\n  foreach(var innerGroup in outerGroup.SubItems)\n  {\n    Console.WriteLine(innerGroup.RowKey + " " + innerGroup.Count);\n  }\n}	0
23190205	23190129	How to express common keyboard input in an else if statement?	while(true) \n {\n    Console.Write("Please enter your age ");\n    string agestring = Console.ReadLine();\n    int age;\n    var array = ()\n\n    if (Int32.TryParse(agestring, out age))\n    {\n        if (age >= 21)\n        {\n            Console.WriteLine("congrats, you can get drunk!");\n        }\n\n        else if (age < 21)\n        {\n            Console.WriteLine("Sorrrrrryyyyyyy =(");\n        }\n        //If you want the program to exit after a valid input, break to get out of loop\n        break;\n\n    }\n    else if (age != ????)\n    {\n        Console.WriteLine("Sorry Thats not a valid input, Please enter a correct number.\n");\n\n    }\n}	0
1457906	1442251	How is coordination of child views best handled in MVP?	public class ChildViewOne {\n    private IEventAggregator evtAggregator;\n\n    public ChildViewOne(IEventAggregator evtAggregator) {\n        this.evtAggregator = evtAggregator;\n    }\n\n    private void OnEventOccured(){\n        evtAggregator.GetEvent<EventOccured>().Publish();\n    }\n}\n\npublish class ChildViewTwo {\n    private IEventAggregator evtAggregator;\n\n    public ChildViewTwo(IEventAggregator evtAggregator) {\n     evtAggregator.GetEvent<EventOccured>().Subscribe(OnEventOccured);\n    }\n\n    private void OnEventOccured() {\n        // Do something here...\n    }\n}	0
15727225	15727113	How do I pass a collection of strings as a TextReader?	public TextReader GetTextReader(IEnumerable<string> lines)\n{\n    return new StringReader(string.Join("\r\n", lines));\n}	0
26406128	26405855	Creating sitecore item programmatically in specific language	using (new LanguageSwitcher("en-gb"))\n{\n    var rootItem = currentDatabase.GetItem(RootItemPath);\n    var item = rootItem.Add(selectedItem.Name, CommunityProjectTemplateId);\n\n    // Do your editing on item here...\n}	0
19769415	19769398	How do I disable Mnemonics in a WPF MenuItem?	public class EscapeMnemonicsStringConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        string str = value as string;\n        return str != null ? str.Replace("_", "__") : value;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new NotImplementedException();\n    }\n}	0
2825481	2825351	'Lexical' scoping of type parameters in C#	public F<X>.X F<X>.X { get; set; }    // error\npublic F<X>.X F<X>.G.X { get; set; }  // OK	0
7680699	7679207	change application resources in code	// retrieve\ndouble spinnerAngle = (double)App.Current.Resources["spinnerAngle"]\n\n// set\nApp.Current.Resources["spinnerAngle"] = spinnerAngle ;	0
16143458	16143416	Substring in c# and add one by one	string name = "1100_PF_R_06230_1";\n var num = (name.Substring(name.LastIndexOf('_')+1));	0
1969100	1969089	Call a method each time before any other method is called	public void Foo() {\n    Bar()\n    FooCore();\n}\nprotected virtual void FooCore() {...} // default Foo implementation\nprivate void Bar() {...} // your special code	0
2898554	2898509	Parse filename, insert to SQL	strFileName.Substring(0,strFileName.IndexOf("_"));	0
27544887	27544520	App config in Window Service	ConfigurationManager.AppSetting["key"]	0
24990645	24989929	How do I parse ms outlook 2003 email body for a string i.e. keyword 'error'	for(int i=1;i<=subFolder.Items.Count;i++)\n{\n    item = (Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];\n    if(item.Body.Contains("errors"))\n        {\n            Console.WriteLine("Item: {0}", i.ToString());\n            Console.WriteLine("Subject: {0}", item.Subject); \n            Console.WriteLine("Sent: {0} {1}",  \n            item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());\n            Console.WriteLine("Categories: {0}", item.Categories);\n            Console.WriteLine("Body: {0}", item.Body);\n            Console.WriteLine("HTMLBody: {0}", item.HTMLBody); \n        }\n}	0
28218561	28217680	I want to call a function immediately as the user select any item from dropdown on page postback how to do it?	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n        DropDownList ddl = sender as DropDownList;\n        RepeaterItem rptItems = ddl.NamingContainer as RepeaterItem;\n        DropDownList ddlItems = rptItems.FindControl("DropDownList1") as DropDownList;\n        ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "showname", "javascript: alert('" + ddlItems.SelectedItem.ToString()   + "');", true);\n}	0
23014066	23013927	remove nested values from object in linq	copyAgencies[0].Programs.RemoveAll(x => !chkIds.Contains(x.ProgramId));	0
6590187	6590159	How do I set a C# checkbox property to "unchecked" for the purpose of saving a setting?	private void chkBackup_CheckChanged(object sender, EventArgs e)\n{\n    Properties.Settings.Default.Backup = chkBackup.Checked;\n    Properties.Settings.Default.Save();\n}	0
8616496	8616266	Center of a ModelVisual3D	Point avg\nfor (point in points)\n    avg = avg + point\n    ++count\n\navg /= count	0
14318157	14318069	Setting the scrollbar position of Listbox	object item = ...\nlistBox.Items.Add(item);\nlistBox.ScrollIntoView(item);	0
6618933	5629209	How to replace OpenExeConfiguration in a web context (asp.net mvc 1)	System.Configuration.Configuration config = null;\n                    if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty))\n                        config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");\n                    else\n                        config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);	0
12079045	12078942	How to convert from ARGB to hex aarrggbb?	return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}",\n                     color.A,\n                     color.R,\n                     color.G,\n                     color.B);	0
34050987	34049558	wpf - improve speed of placing large image onto canvas	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        var brush = new ImageBrush(new BitmapImage(new Uri("thumbnail.jpg", UriKind.Relative)));\n        canvas_view.Background = brush;\n        this.Loaded += MainWindow_Loaded;\n    }\n\n    async void MainWindow_Loaded(object sender, RoutedEventArgs e)\n    {\n        var bi = await LoadBigImage();\n        canvas.Background = new ImageBrush(bi);\n    }\n\n    async Task<BitmapImage> LoadBigImage()\n    {\n        var bi = new BitmapImage(new Uri("fullsize.jpg", UriKind.Relative));\n        bi.Freeze(); // note: must freeze DP objects when passing between threads\n        return bi;\n    }\n}	0
115351	115328	How can I do Databinding in c#?	editBox.DataBindings.Add("Text", car, "Name");	0
8046721	8046508	Fetch n nodes matching attribute condition in xml file using XPATH	Codes/QualityCode[@Status=1][position() < 10]	0
5788923	5788881	how to get the application physical path in windows forms application	System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)	0
16774923	16774893	sort list by double variable and view the 5 first	ViewBag.TopFive = teams.OrderByDescending(x => x.Score).Take(5);	0
22578430	22578286	How do I order the digits 1-10 randomly into an array and then call each part of the array one at a time?	static void Main(string[] args)\n    {\n        Random random = new Random();\n\n        var range = Enumerable.Range(1, 10).ToList();\n        int[] rnd = new int[10];\n\n        int j = 0;\n        do\n        {\n            int i = random.Next(0, range.Count);\n            rnd[j++] = range[i];\n            range.RemoveAt(i);\n        }\n        while(range.Count > 1);\n\n        rnd[j] = range[0];\n    }	0
2826458	2825995	stored procedure for importing txt in sql server db	CREATE procedure dbo.UpdateTable\n\n    @FilePath varchar(max)\nAS\n\n declare @sql varchar(max)\n declare @parameters varchar(100)\n set @parameters = 'FIRSTROW = 2, MAXERRORS = 0, FIELDTERMINATOR = ''\\t'', ROWTERMINATOR = ''\\n'' '\n SET @SQL = 'BULK INSERT TMP_UPTable FROM ' + @FilePath + @parameters\n\nEXEC (@SQL)\n\nRETURN	0
16287225	16287131	C# large numbers of static numerical arrays	string myResource = "1, 2, 3.4, 5.6";\n        double[] values = myResource.Split(',').Select(Convert.ToDouble).ToArray();	0
33892358	33824062	Custom ModelValidatorProvider - get access to containertype property	Data.cshtml\n{\n   @model MyPageData\n\n   @using(Html.BeginForm())\n   {\n     @Html.EditorFor(f => f.MyPage.Fields)\n   }\n}	0
33953015	33952814	ASP.NET C# reportviewer Parameter	ReportParameter[] parameters = new ReportParameter[yournumberofparamaters];\nparameters[0] = new ReportParameter("name", value);\nparameters[1] = new ReportParameter("name", value);\nparameters[2] = new ReportParameter("name", value);\nthis.Log_ReportViewer.LocalReport.SetParameters(parameters);	0
730327	730300	How to throw exception without resetting stack trace?	catch (Exception ex) {\n  if (!HandleException(ex)) {\n    throw;\n  }\n}	0
10874663	10874554	How to access controller ViewData and TempData from its child object - notification provider implementation	public class HomeController\n{\n    public ActionResult Index()\n    {\n        var notificationProvider = new NotificationProvider(this);\n        notificationProvider.LoadNotifications();\n        return View();\n    }\n}	0
891127	891053	Adding a list of UserControls with buttons to a PlaceHolder - no event?	if (!IsPostBack)	0
6558677	6558594	Performing SQL "in" equivalent in EF	public class R {\n   public int Id {get; set;}\n}\n\npublic IEnumerable<R> InClause(IEnumerable<int> ids) {\n   var subset = ids.ToList();\n\n   return dbContext.Query<R>.Where(r => subset.Contains(r.Id));\n}	0
16307926	16307898	Sort a list of objects containing list each with orderby	humanList.OrderBy(h=>h.ListHumanAttributes.First(a=>a.Name=="Age").Value);	0
8325281	8317634	EF 4.2 Code First, how to map with fluent API?	Database.SetInitializer<YourContext>(null);	0
3944816	3944803	Use LINQ to get items in one List<>, that are not in another List<>	var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));	0
1981719	1980515	WebBrowser keyboard shortcuts	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n    switch (keyData)\n    {\n        case Keys.Control|Keys.Tab:\n            NextTab();\n            return true;\n        case Keys.Control|Keys.Shift|Keys.Tab:\n            PreviousTab();\n            return true;\n        case Keys.Control|Keys.N:\n            CreateConnection(null);\n            return true;\n    }\n    return false;	0
4829013	4828772	Linq to XML - Multiple Elements into Single Class	var xml = XElement.Parse(\n    @"<appSettings><add key=""Prop1"" value=""1"" /><add key=""Prop2"" value=""2"" /></appSettings>");\nnew ConfigProp\n{\n    Prop1=xml\n        .Elements("add")\n        .Single(element=>element.Attribute("key").Value == "Prop1")\n        .Attribute("value")\n        .Value,\n    Prop2 = xml\n        .Elements("add")\n        .Single(element => element.Attribute("key").Value == "Prop2")\n        .Attribute("value")\n        .Value\n};	0
2862157	2862151	How to Remove Last digit of String in .Net?	string foo = "21524116476CA2006765B";\nstring bar = foo.Substring(0, Math.Max(foo.Length - 1, 0));	0
13114642	13114609	How to convert three Windows Forms applications to one?	- MySolution\n    - Project: Form1\n    - Project: Form2\n    - Project: Form3	0
8081315	8081273	String Manipulation using Split Method	Regex.Matches(diagnosis, @"\d+\.\d+").Cast<Match>().Select(m => m.Value);	0
13431095	13431002	Regex Including Characters in a Non-Capturing Group?	(.+?)(?:\(|ft|feat)	0
1757482	1757448	How do I properly return a char * from an Unmanaged DLL to C#?	[DllImport("api.dll")]\n[return : MarshalAs(UnmanagedType.LPStr)]\ninternal static extern string errMessage(int err);\n...\nstring message = errMessage(err);	0
13165908	12703786	D3 - Dynamic Data Display WPF datetime axis internal format	var axis = (DateTimeAxis)plotter.MainHorizontalAxis;\ndouble xMin = axis.ConvertToDouble(date1); \ndouble xMax = axis.ConvertToDouble(date2);\nRect visibleRect = new Rect(xMin, 0, xMax - xMin, 1 - 0);\n//not sure what bounds you want for y axis, so assumed 1 for example purposes.	0
11923314	11921818	How to fix the Ajax calender Month in asp.net?	Protected Sub yourCalendar_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs) Handles yourCalendar.DayRender\n    If e.Day.IsOtherMonth Then\n    e.Cell.Text = ""\n    End If\nEnd Sub	0
16251807	16250551	How to get something like "descendant-AND-self::" to htmlNode	HtmlDocument doc = new HtmlDocument();\nHtmlNode.ElementsFlags.Remove("form");\ndoc.Load(myTestHtm);\n\nforeach (var v in doc.DocumentNode.SelectNodes("//form"))\n{\n    Console.WriteLine(v.OuterHtml);\n}	0
845095	845089	How to Initialize a Multidimensional Char Array in C?	char DirectionPosition[][ 5 ][ 3 ] = {{"00", "10", "", "01", ""},\n                                    {"01", "11", "", "02", "00"},\n                                    {"02", "12", "", "03", "01"},\n                                    {"03", "13", "", "04", "02"},\n                                    {"04", "14", "", "", "03"},\n                                    {"10", "20", "00", "11", ""},\n                                    {"11", "21", "01", "12", "10"},\n                                    {"12", "22", "02", "13", "11"},\n                                    .\n                                    .\n                                    .\n                                    .\n                                    {"44", "", "34", "", "43"},};	0
1099100	1098644	Switch statement without default when dealing with enumerations	public class Test {        \n  public string GetDecision(bool decision) {\n    switch (decision) {\n       case true: return "Yes, that's my decision";                \n       case false: return "No, that's my decision"; \n    }\n  }\n}	0
32739902	32739671	Delete last decimal value in a double	input = input.Substring(0,input.Length-1);	0
16124475	16123392	Infinite Loop parsing a table using htmlagilitypack	var res = doc.DocumentNode.SelectNodes("//table//tr[td]")\n             .Select(row => row.Descendants("td")\n                                .Select(td => td.InnerText).ToList())\n             .ToList();	0
11468069	11467957	C# LINQ - convert nested dictionary to a list	var flattened =\nfrom kvpOuter in nestedDictionary\nfrom kvpInner in kvpOuter.Value\nselect new SomeObject()\n{\n    var1 = kvpOuter.Key,\n    var2 = kvpInner.Key,\n    someStringVar = kvpInner.Value\n};\nvar list = flattened.ToList(); // if you need a list...	0
7970403	7954988	Decorating a generic interface with Structuremap	public class ServiceRegistrationConvention : IRegistrationConvention\n{\n    public void Process(Type type, Registry registry)\n    {\n        var interfacesImplemented = type.GetInterfaces();\n\n        foreach (var interfaceImplemented in interfacesImplemented)\n        {\n            if (interfaceImplemented.IsGenericType && interfaceImplemented.GetGenericTypeDefinition() == typeof(IServiceOperation<,>))\n            {\n                var genericParameters = interfaceImplemented.GetGenericArguments();\n                var closedValidatorType = typeof(ValidateServiceDecorator<,>).MakeGenericType(genericParameters);\n\n                registry.For(interfaceImplemented)\n                    .EnrichWith((context, original) => Activator.CreateInstance(closedValidatorType, original,\n                                                                                context.GetInstance<IValidationService>()));\n            }\n        }\n    }\n}	0
3424631	3424601	how to start this process	string arguments = \n    "-i \"c:\\Program Files\\My App\\MyContextMenuExtension.dll\"";\n\narguments += " \"c:\\Program Files\\MyApp\\LogicNP.EZShellExtensions.dll\"";\n\nSystem.Diagnostics.Process.Start("TestFile.exe", arguments);	0
14425196	14358676	How to configure asp.net webforms WebMethod Date format	yyyy-MM-ddTHH:mm:ss.fffZ	0
14293822	14293710	timed refresh of GUI in WPF	public MainWindow()\n    {\n        InitializeComponent();\n\n        DispatcherTimer t = new DispatcherTimer();\n        t.Tick += t_Tick;\n        t.Interval = new TimeSpan(0, 0, 0, 0, 300);\n        t.Start();\n    }\n    Random r = new Random();\n    void t_Tick(object sender, EventArgs e)\n    {\n        byte[] rnd = new byte[4];\n        r.NextBytes(rnd);\n        this.Background = new SolidColorBrush(Color.FromArgb(rnd[0], rnd[1], rnd[2], rnd[3]));\n    }	0
34108011	34107936	EF - Update multiple rows in database without using foreach loop	using (var db = new MyDbContext())\n{\n  string fromUser = ""; //sender\n  string toUser = ""; //receiver\n  var messages = db.Message.Where(x => x.FromUser == fromUser && x.ToUser == toUser)\n                 .ToList();\n  messages.ForEach(m => m.IsRead = true);\n  db.SaveChanges();\n}	0
4803833	4803759	Printing a document in C#	private void Print_Click(object sender, EventArgs e)\n      {\n        PrintDocument printDocument = new PrintDocument();\n        printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);\n\n        PrintDialog printDialog = new PrintDialog \n        {\n            Document = printDocument\n        };\n\n        DialogResult result = printDialog.ShowDialog();\n\n        if (result == DialogResult.OK)\n        {\n            printDocument.Print(); // Raises PrintPage event\n        }\n    }\n\n    void printDocument_PrintPage(object sender, PrintPageEventArgs e)\n    {\n        e.Graphics.DrawString(...);\n    }	0
2322690	2309500	Disable Outlook Security Message Box	mailItem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3003001F");	0
10833832	10833740	How To Stay Protected Against ListviewSelectedIndexChanged	ListView lv = (ListView)sender;\n if (lv.FocusedItem != null && lv.FocusedItem.SubItems.Count > 3)\n {\n   textBox2.Text = lv.FocusedItem.SubItems[3].Text;\n   textBox3.Text = lv.FocusedItem.SubItems[0].Text;\n }	0
18638541	18638218	Fluent API for having multiple foreign keys from same class	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n\n    }	0
31448123	31426112	set page margins programmatically in crystal report	ReportDocument rd = new ReportDocument();\nPageMargins margins;\n// Get the PageMargins structure and set the \n// margins for the report.\nmargins = rd.PrintOptions.PageMargins;\nmargins.bottomMargin = 350;\nmargins.leftMargin = 600;\nmargins.rightMargin = 350;\nmargins.topMargin = 300;\n// Apply the page margins.\nrd.PrintOptions.ApplyPageMargins(margins);	0
20242944	20241867	show user control when button_click event	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!Page.IsPostback)\n    {\n        loginUserControl.Visible = false;\n    }\n}	0
16454625	16454537	Get a file's root path	silliness = Path.Combine( Path.GetDirectoryName(fb.SelectedPath),\n                          folder.Replace(fb.SelectedPath, String.Empty)\n                         )	0
29799926	29799473	How do i remove a specific collection from my model in C#	LastObsResults.Remove(LastObsResults.FirstOrDefault(obs => obs.ObsName == name));	0
2417177	2417093	Converting time to Military	oos.ToString("M/d/yyyy HH:mm");	0
2399364	2399356	c# list comparer use two compare elements	outerCompare = x.Country.Name.CompareTo(y.Country.Name);\nif (outerCompare != 0)\n{\n    return outerCompare;\n}\nelse\n{\n    return (x.Name.CompareTo(y.Name));\n}	0
4162860	4162843	C# Array, How to make data in an array distinct from each other?	var b = a.Distinct().ToArray();	0
21869098	21868926	suppress "number stored as text" warning in Excel VSTO with C#	Dim c As Range\n\nFor Each c In Selection.Cells\n    c.Errors(xlNumberAsText).Ignore = True\nNext c	0
17250067	17249937	how to display Date and Time in a well mannered format	string gettime(DateTime updatedat)\n{\n     string toren = "A moment earlier";\n     TimeSpan ts = DateTime.Now - updatedat;\n     if (ts.TotalSeconds<60)\n     {\n          toren = ts.TotalSeconds.ToString() + " seconds ago";\n     }\n     else if (ts.TotalMinutes < 60)\n     {\n          toren = ts.TotalMinutes.ToString() + " minutes ago";\n     }\n     else if (ts.TotalHours < 24)\n     {\n          toren = ts.TotalHours.ToString() + " hours ago";\n     }\n     else if (ts.TotalDays < 30)\n     {\n          toren = ts.TotalDays.ToString() + " days ago";\n     }\n     else \n     {\n          double month = ts.TotalDays / 30;\n          if (month<13)\n          {\n               toren = month.ToString() + " months ago";\n          }\n          else\n          {\n               double year = month / 12;\n               toren = year.ToString() + " years ago";\n          }\n     }\n     return toren;\n}	0
28186809	28186689	How to typecast in c# with T type and access its property and variables	private List<ParentClass> AssignValue<T>(List<ParentClass> lstParent)\n    {\n        foreach (var item in lstParent)\n        {\n            dynamic objData = Convert.ChangeType(item, typeof(T));\n            if (objData != null)\n            {\n                //This call would throw exception if CommonProperty is not member of the T Class\n                objData.CommonProperty = 5;\n            }\n        }\n        return lstParent;\n\n    }	0
14072119	14060785	Passing first values in drop down list when clicking search button	method="post"	0
2049971	2049823	Trying to figure how to call function from other class without making it static	public static void dolol(mainform frm)\n{\n    frm.changetext(s);\n}	0
11000188	11000079	Retrieve dictionary item by number	m_GermanEnglish.ElementAt(index);	0
29284712	29284418	Input from CSV file to a text field in Web C# without using UIMap/Recorded code	[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\data.csv", "data#csv", DataAccessMethod.Sequential), DeploymentItem("data.csv"), TestMethod]\n        [TestMethod]\n        public void openBrw()\n        {\n\n            BrowserWindow browser = BrowserWindow.Launch("www.google.com");\n            UITestControl UISearch = new UITestControl(browser);\n            UISearch.TechnologyName = "Web";\n            UISearch.SearchProperties.Add("ControlType", "Edit");\n            UISearch.SearchProperties.Add("Id", "lst-ib");\n//search by column1\n            Keyboard.SendKeys(UISearch, TestContext.DataRow["column1"].ToString());            \n\n        }	0
2721445	2721417	Export to RSS Feed	System.ServiceModel.Syndication	0
3033744	3033536	Loading embedded resource on Windows 7	Splash.Image = Properties.Resources.Logo;	0
2114835	2114823	How do I check if an object contains a byte array?	if(data.GetType().Name == "Byte[]") \n{\n    // assign to array\n}	0
13511438	13511348	Detecting if it is the last instance of the application c#	if(Process.GetProcessesByName("yourprogram").Length == 0)\n{\n    // It's the only instance!\n}	0
32095382	32091966	Problems with nusoap in Windows Phone	var result = await c.testAsync(check);	0
4882560	4880347	How do I pass a C# interface to an external COM object for its use?	[ComVisible(true)]\n[Guid("28888fe3-c2a0-483a-a3ea-8cb1ce51ff3d")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface ITextStoreACP \n{\n    uint AdviseSink(\n        ref Guid Iid, \n        [MarshalAs(UnmanagedType.IUnknown)] object pUnknown, \n        uint Mask\n        );\n    .......\n}\n\n\npublic class TextStore : ITextStoreACP\n{\n    #region ITextStoreACP Members\n\n    public uint AdviseSink(ref Guid Iid, object pUnknown, uint Mask)\n    {\n        throw new NotImplementedException();\n    }\n    .....\n}	0
10066306	10066290	How can I call method of form1 in form2 without create new instance of form1	static class TreeNodeCollectionHelper\n{\n    public static int GetCheckedNodesCount(TreeNodeCollection nodes)\n    {\n        ...\n    }\n}	0
22530161	22530004	Remove Row from GridView	if (e.CommandName == "Delete")\n        {\n        if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))\n        {\n            int rowIndex = Convert.ToInt32(e.CommandArgument);\n            DataTable table = CreateDataTable(false, string.Empty, string.Empty);\n            table.Rows.RemoveAt(rowIndex) \n            grdSelectedProducts.DataSource = table;\n            grdSelectedProducts.DataBind();\n        }\n    }	0
12234295	12200109	Microsoft Exchange Folders.findItems results limited to a 1000	Set-ThrottlingPolicy -Identity <ThrottlingPolicyIdParameter> [-EWSFindCountLimit <UInt32>]	0
12157872	12157681	How to determine the position of the cursor in KeyDown event?	textbox1.CaretIndex	0
4695259	4695222	get number of pages in search results	var doc = new HtmlWeb().Load(url);\nvar elem = doc.GetElementById("someID");\nvar classedLinks = doc.DocumentNode.Descendants("img")\n    .Where(e => e.GetAttributeValue("class", "").Contains("SomeClass"));	0
8648805	8648768	How do I open default browser in fullscreen mode from a C# desktop application?	ActiveForm.SendKeys("{F11}");	0
2871892	2871849	How to access other project forms in solution explorer for VS2008 C#?	using HR;\n\nprivate void ShowForm()\n{\n  HR.Form1 hrForm = new HR.Form1();\n  hrForm.Show();\n}	0
10532355	10532308	find combobox that have selections	foreach (var comboBox in BoxContainer.Children.OfType<ComboBox>())\n    if (comboBox.SelectedItem != null)\n        MessageBox.Show(comboBox.Name);	0
11501039	11435334	Telerik RadChart Alternating Background StripLines On ASP Ajax control	public void GenerateStripLines(RadChart chart, int minValue, int maxValue, int step)\n{\n   for (int i = minValue; i <= maxValue + step; i+=step)\n   {\n      Color zoneColor;\n\n      if (i % 2 == 0)\n         zoneColor = Color.White;\n      else\n         zoneColor = Color.WhiteSmoke;\n\n      var item = new ChartMarkedZone() { ValueStartY = i, ValueEndY = i + step };\n      item.Appearance.FillStyle.MainColor = zoneColor;\n      chart.PlotArea.MarkedZones.Add(item);\n   }           \n}	0
32631138	32628983	Validation Where Value Is Stored In My Web.config File	var SellMaximum = decimal.Parse(System.Configuration.ConfigurationManager.AppSettings["SellMaximum"].ToString());	0
6274442	6274411	How to apply transaction in Entity framework	using (TransactionScope transaction = new TransactionScope())\n{\n    bool success = false;\n    try\n    {\n        //your code here\n        UpdateTable1();\n        UpdateTable2();\n        transaction.Complete();\n        success = true;\n    }\n    catch (Exception ex)\n    {\n        // Handle errors and deadlocks here and retry if needed.\n        // Allow an UpdateException to pass through and \n        // retry, otherwise stop the execution.\n        if (ex.GetType() != typeof(UpdateException))\n        {\n            Console.WriteLine("An error occured. "\n                + "The operation cannot be retried."\n                + ex.Message);\n            break;\n        }\n    }    \n\n    if (success)\n        context.AcceptAllChanges();\n    else    \n        Console.WriteLine("The operation could not be completed");\n\n    // Dispose the object context.\n    context.Dispose();    \n}	0
16299319	16292960	Is it possible to change the Double column Decimal Size	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace DAO_test\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // required COM reference: Microsoft Office 14.0 Access Database Engine Object Library\n            var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine();\n            Microsoft.Office.Interop.Access.Dao.Database db = dbe.Workspaces[0].OpenDatabase(@"C:\__tmp\testData.accdb");\n            Microsoft.Office.Interop.Access.Dao.Field fld = db.TableDefs["poiData"].Fields["lon"];\n            Console.WriteLine("Properties[\"DecimalPlaces\"].Value was: " + fld.Properties["DecimalPlaces"].Value);\n            fld.Properties["DecimalPlaces"].Value = 5;\n            Console.WriteLine("Properties[\"DecimalPlaces\"].Value is now: " + fld.Properties["DecimalPlaces"].Value);\n            db.Close();\n            Console.WriteLine("Hit a key...");\n            Console.ReadKey();\n        }\n    }\n}	0
22732899	22732857	C# use of unassigned variable?	ThreeD boardOne = new ThreeD();\nThreeD boardTwo = new ThreeD();\nThreeD boardThree = new ThreeD();	0
9299054	9298706	How to check for duplicates in an array and then do something with their values?	var totalQuantities = new Dictionary<int, int>();\nforeach(var raw in sourceArr) {\n    var splitted = raw.Split(':');\n    int id = int.Parse(splitted[0]);\n    int qty = int.Parse(splitted[1]);\n    if(!totalQuantities.ContainsKey(id)) {\n        totalQuantities[id] = 0;\n    }\n    totalQuantities[id] += qty;\n}\n\nvar result = new string[totalQuantities.Count];\nint i=0;\nforeach(var kvp in totalQuantities) {\n    result[i] = string.Format("{0}:{1}", kvp.Key, kvp.Value);\n    i++;\n}	0
32013436	32013389	Delegates with methods that have different number of parameters	ListSorter.myDelegate += (() => A(5));\nListSorter.myDelegate += B;	0
19783693	19769606	EntityFramework / LinQ load entity from database to dto	var result = from tuple in (from address in context.Adresses\n                            join person in context.Persons on address.PersonId equals person.Id\n             select new { person.Id, address.Id1, address.Id2})\n             group tuple by new { tuple.Id1, tuple.Id2 } into myGrouping\n             select \n                 new MyObj \n                     { \n                         Id1 = myGrouping.Key.Id1,\n                         Id2 = myGrouping.Key.Id2,\n                         PersonIds = myGrouping.Select(x => x.PersonId).Distinct()\n                     };	0
6470071	6469966	Getting a Weighted Average Date Value?	DateTime dateA = ...;\nDateTime dateB = ...;\nTimeSpan difference = dateA - dateB;\ndouble units = difference.Ticks;\n// Do your weighted logic here on 'units'.\nDateTime average = dateA + new TimeSpan(units);	0
15554417	15554348	Composite Model Binding Performance with INotifyPropertyChanged	private SolidColorBrush _redBrush;\nprivate SolidColorBrush IndicatorRedBrush\n{\n    get{ return _redBrush ?? (_redBrush = \n        Application.Current.FindResource("IndicatorRedBrush") as SolidColorBrush)); \n}\n\n... same for white brush\n\npublic SolidColorBrush ShiftOverageBrush {\n    get {\n        if (ShiftOverage.HasValue && ShiftOverage.Value.Milliseconds < 0) {\n            return IndicatorRedBrush;\n        }\n\n        return IndicatorWhiteBrush;\n    }\n}	0
30228204	30223623	Apply a TableStyle to a Word Table	TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };	0
31839646	31839024	How do I get the user's SID from the server?	WindowsIdentity.GetCurrent().User.Value	0
11700841	11700813	C# byte[][] SHA1	byte[] data = new byte[DATA_SIZE];\n\nbyte[] result; \n\nSHA1 sha = new SHA1CryptoServiceProvider(); \n    // This is one implementation of the abstract class SHA1.\n\nresult = sha.ComputeHash(data);	0
34350588	34336577	Convert Canvas to ImageSource	Canvas c = new Canvas();\nelement.OpacityMask = new VisualBrush( c );	0
13742129	13742017	C# string with special characters to MySQL varchar column	"charset=utf8"	0
1851399	1851366	compairing some pattern with regular expression C#	\d+0 obj\<\<.*\>\>endobj	0
27409961	27409835	How to make a non-decreasing row in c#	int a, b, c, mak, min, mid;\n    a = Convert.ToInt32(tba.Text);\n    b = Convert.ToInt32(tbb.Text);\n    c = Convert.ToInt32(tbc.Text);\n    mak=b;\n    if (a > mak)\n        mak=a;\n    if (c > mak)\n        mak=c;\n    min=a;\n    if (b < min)\n        min=b;\n    if (c < min)\n        min=c;\n    mid=c;\n    if (a!=mak && a!=min)\n        mid = a;\n    if (b!=mak && b!=min)\n        mid=b;\n    tbd.Text=Convert.ToString(mid);\n    tbg.Text=Convert.ToString(mak);\n    tbf.Text=Convert.ToString(min);	0
14119997	14119947	How to change the font color of some substring in the textbox in C# Winform?	if( myRichTextBox.TextLenght >= 5 )\n{\nmyRichTextBox.Select( 0, 5 );\nmyRichTextBox.SelectionColor = Color.Green;\n}\n\nif( myRichTextBox.TextLenght >= 15 )\n{\nmyRichTextBox.Select( 10, 15 );\nmyRichTextBox.SelectionColor = Color.Red;\n}	0
29376189	29376140	Comparing session variables with javascript variables	var example2 = "Jake"\nif ('<%=Session["example1"]%>' === example2){\n   Code\n}	0
8614231	8614113	How can I set Unity to dependency inject repositories to my service layer?	public class AccountService : BaseService, IService<Account> \n{ \n    public AccountService(StorageHelperType accountRepo, StorageHelperType productRepo) { base.Initialize(); \n        _accountRepository = accountRepo; \n        _productRepository = productRepo;  \n}	0
8023807	8023796	Open a new console with every new Thread in C#?	A process can be associated with only one console	0
1547657	1547595	Remove multiple char types from end of string	returnValue = returnValue.TrimEnd(' ', ',');	0
24169860	24169697	WPF: UI not updated on value change in bound object	OnPropertyChanged("DiscountingRate");	0
22234014	22233644	Find value in DataSet DataTable	for (i = 1; i <= iCount; i++)\n {\n    if (myDataset.Tables[0].AsEnumerable().Any(i => Convert.ToInt32(i["KeyID"]) == i))\n    {\n\n\n    }\n\n }	0
4494527	4493970	How to correctly update entities in EF4 using POCO and custom ObjectContext?	public void UpdateOrder(Order o)\n{\n   var stub = new Order { Id = o.OrderId }; // create stub with EntityKey\n   ctx.Orders.Attach(stub); // attach stub to graph\n   ctx.ApplyCurrentValues("Orders", o); // override stub with values.\n   ctx.SaveChanges();\n}	0
21085451	21085299	Dynamic object to hold temporary data	class MainParser {\n  public MyObject Parse(Filename file){\n    //Build the relevant parser implementation according to the type of the file \n    IParser myParser = ParserFactory.BuildParser(file) \n\n    //Build the intermediate object\n    DTOObject intermediateObject = myParser.Parse(file);\n\n    //Finish the build\n    return BuildMyObject(intermediateObject);\n  }\n\n  private MyObject BuildMyObject(DTOObject dtoObject){\n     //Do validation and so on\n  }\n}	0
33311365	33311188	How do I add a button with action to ShowInputAsync from MahApps.Metro	var browserDialog = new MyCustomDialog();\nawait this.ShowMetroDialogAsync(browserDialog);	0
16445142	16445090	Need help accessing webbrowser control from form1	frm.MyWebBrowserControl	0
33081740	33081355	How would i assign only DisplayName and Name from PrincipalSearcher to List?	var list = searcher.FindAll().Select(s => new {name = s.Name, displayName = s.DisplayName});	0
17803143	17800568	Customize DevExpress scheduler control timeline view header	var timeScaleWeek = new DevExpress.XtraScheduler.TimeScaleWeek();\ntimeScaleWeek.DisplayFormat = "yyyy.MM.dd";\nschedulerControl1.Views.TimelineView.Scales.Add(timeScaleWeek);	0
16339492	16338917	Iterating through JSON using System.Json	string json = @"{ ""People"": { ""Simon"" : { Age: 25 }, ""Steve"" : { Age: 15 } } }";\n\nvar people =  JsonConvert.DeserializeObject<JObject>(json)["People"];\n\nvar dict = people.Children()\n                 .Cast<JProperty>()\n                 .ToDictionary(p => p.Name, p => p.Value["Age"]);	0
28195429	28194658	Returning text to a button from a database C# DataColumnCollection	private void main_Click(object sender, EventArgs e)\n    {\n        Database db = new Database();\n        DataRowCollection dra = db.ReturnDataRowCollection("SELECT itemname FROM menuitems WHERE Category = 'main'");\n        int count = 0;\n        foreach (DataRow dr in dra)\n        {\n            btns[count].Text = dr["itemname"].ToString();\n            btns[count].Visible = true;\n            count++;\n        }\n    }	0
2656328	2656212	Invert the 1bbp color under a rectangle	protected override void OnPaint(PaintEventArgs e) {\n        e.Graphics.DrawImage(mImage, Point.Empty);\n        ImageAttributes ia = new ImageAttributes();\n        ColorMatrix cm = new ColorMatrix();\n        cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = -0.99f;\n        cm.Matrix40 = cm.Matrix41 = cm.Matrix42 = 0.99f;\n        ia.SetColorMatrix(cm);\n        var dest = new Rectangle(50, 50, 100, 100);\n        e.Graphics.DrawImage(mImage, dest, dest.Left, dest.Top, \n            dest.Width, dest.Height, GraphicsUnit.Pixel, ia);\n    }	0
23339373	23338084	Exporting parameters from RSA provider takes long time in monodevelop c#	public RSACryptoServiceProvider ()\n    : this (1024)\n{\n    // Here it's not clear if we need to generate a keypair\n    // (note: MS implementation generates a keypair in this case).\n    // However we:\n    // (a) often use this constructor to import an existing keypair.\n    // (b) take a LOT of time to generate the RSA keypair\n    // So we'll generate the keypair only when (and if) it's being\n    // used (or exported). This should save us a lot of time (at \n    // least in the unit tests).\n}	0
12475971	12475793	Close tabs from Tabcontrol but keep One tab Active in the end	if (tabControl != null && tabControl.Items.Count > 1)\n    tabControl.Items.Remove(tabItem);	0
22199423	22012231	Loop in write xml for treeview	private void CreateNodes(int parentId)\n{\n    DataTable dt = GetMenu(0);\n    foreach(DataRow dr in dt.Rows)\n    {\n        writer.WriteStartElement("Node");\n        writer.WriteStartAttribute("Id");\n        writer.WriteValue(dr["MenuId"].ToString());\n        writer.WriteEndAttribute();\n\n        writer.WriteStartAttribute("Name");\n        writer.WriteValue(dr["MenuName"].ToString());\n        writer.WriteEndAttribute();\n\n        **CreateNodes(Convert.ToInt32(dr["MenuId"]));**\n        writer.WriteEndElement();\n    }\n}	0
14170258	14170246	Retrieving the name of an image	var path  = "../../Images/PozeOne.jpg";\n\nImage imageOne = Image.FromFile(path);\n\nstring name = Path.GetFilename(path);	0
7044068	7043895	update panel with ClientScriptManager	ScriptManager.RegisterStartupScript()	0
24698535	24698067	How to open a Microsoft Word Document in Full Screen Reading View?	wordApplication.ActiveWindow.View.ReadingLayout = true;	0
21678983	21678961	Unable to decode danish characters for email	var str = HttpUtility.HtmlDecode("&#229;");\n\nvar str = WebUtility.HtmlDecode("&#229;");	0
16023885	16023796	Where to place calculation logic in N-Tier C# application	public class Task : DomainBase\n{\n    public virtual ICollection<Subtask> Subtasks { get; set; }\n\n    [Display(Name = "Subtask(s) Total Cost")]\n    [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]\n    //calculated property\n    public virtual double TotalSubTaskCost\n    {\n        get\n        {\n            if (Subtasks == null)\n                return 0;\n            if (!Subtasks.Any())\n                return 0;\n            double it = Subtasks.Where(a => a != null).\n                Aggregate<Subtask, double>\n                    (0, (current, a) => current + a.TotalCost);\n            return it;\n\n        }\n\n    }\n\n }	0
32951715	32951239	Convert foreach loop to Linq expression	List<ListItem> items = ListValueString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)\n    .Select(lstItem => new { lstItem, listTexts = lstItem.Split(':') })\n    .Select(x => new ListItem()\n    {\n        ListText = x.listTexts[0],\n        ListId = Int32.Parse(x.listTexts[1]),\n        IsActive = true,\n        IsInUse = Int32.Parse(x.listTexts[1]) == _defaultString\n    })\n    .ToList();\nvar _ListItems = new ObservableCollection<ListItem>(items);	0
700683	649336	SQL to MS Access export	Access.ApplicationClass app = new Access.ApplicationClass();\nAccess.DoCmd doCmd = null;\n\napp.NewCurrentDatabase(_args.Single("o"));\ndoCmd = app.DoCmd;\n\n//Create a view on the server temporarily with the query I want to export\n\ndoCmd.TransferDatabase(Access.AcDataTransferType.acImport,\n    "ODBC Database",\n     string.Format("ODBC;DRIVER=SQL Server;Trusted_Connection=Yes;SERVER={0};Database={1}", _args.Single("s"), _args.Single("d")),\n     Microsoft.Office.Interop.Access.AcObjectType.acTable,\n     viewName,\n     exportDetails[0], false, false);\n//Drop view on server\n\n//Releasing com objects and exiting properly.	0
25147846	25147798	Two dimensional C# Array initialized with 2 other arrays	private static readonly Unit[] LengthUnits = { Unit.Millimeters, Unit.Inches, Unit.Centimeters };\nprivate static readonly Unit[] AngleUnits = { Unit.Degrees, Unit.Radians };\nprivate static readonly Unit[][] UnitTypes = { LengthUnits, AngleUnits };	0
2613683	2613597	How to use keyboard shortcuts to select a portion of waveform instead of mouse drag and drop?	private void panel1_MouseDown(object sender, MouseEventArgs e) {\n  if (e.Button == MouseButtons.Left) {\n    if (Control.ModifierKeys == Keys.Shift) SetSelectionEnd(e.X);\n    else SetSelectionStart(e.X);\n  }\n}	0
24976352	24976167	Read and add multiple numbers on different console lines	int result = 0;\n\nwhile (true)\n{\n    string line = Console.ReadLine();\n    if (string.IsNullOrWhiteSpace(line))\n    {\n        break;\n    }\n\n    result += line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)\n                  .Select(int.Parse)\n                  .Sum();\n}\n\nConsole.WriteLine(result);	0
14687639	14685386	How to navigate to view from another project	NavigationService.Navigate(new Uri("/YOURPROJECTNAME;component/MainPage.xaml", UriKind.Relative));	0
20944850	20944335	Convert CollectionView.CurrentItem as a DataRow?	DataRow row = (this.View.CurrentItem as DataRowView).Row;	0
20512681	20512311	Convert datatable to byte array	private string (DataTable dt)\n{\nstring rw = "";\nStringBuilder builder = new StringBuilder();\n\nforeach(DataRow dr in dt.Rows)\n{\n  foreach(DataColumn dc in dr.Columns)\n  {\n      rw = dc[0].ToString();\n      if (rw.Contains(",")) rw = "\"" + rw + "\"";\n      builder.Append(rw + ",");\n  }\n  builder.Append(Environment.NewLine);\n}\nreturn builder.ToString()\n}	0
19825666	19825584	How do I change foreground color of a button when clicked?	(sender as Button).Foreground = new SolidColorBrush(Colors.LightGray);	0
27167848	27167327	Regex for matching attribute values in invalid xml file	(?<match>"((\g<match>|[^"]*))*?")(?=\s|\/|>)/gm	0
12040647	12040622	How to deal with hidden file extensions	Path.GetExtension()	0
4115255	4115246	.Net Function for Removing HTML from a String?	public static string StripTags(string html) {\n\n    System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex("<(.|\\n)+?>");\n    return objRegExp.Replace(html, "");\n\n}	0
926202	926067	Simple histogram generation of integer data in C#	uint[] items = new uint[] {5, 6, 1, 2, 3, 1, 5, 2}; // sample data\nSortedDictionary<uint, int> histogram = new SortedDictionary<uint, int>();\nforeach (uint item in items) {\n    if (histogram.ContainsKey(item)) {\n        histogram[item]++;\n    } else {\n        histogram[item] = 1;\n    }\n}\nforeach (KeyValuePair<uint, int> pair in histogram) {\n    Console.WriteLine("{0} occurred {1} times", pair.Key, pair.Value);\n}	0
16182157	16182036	reading from XML file to Sql server table C#	rfidip = (node.SelectSingleNode("rfidip") != null)? node.SelectSingleNode("rfidip").InnerText.ToString(): string.Empty;	0
21327572	21327499	How to store data grid into datatable?	DataTable dt = new DataTable();\ndt.Columns.Add("values",typeof(string));\nforeach (DataGridViewRow gridRow in dataGridView_settings.Rows)\n{\n      for (int i = 0; i < dataGridView_settings.Columns.Count; i++)\n      {\n          DataRow dtRow = dt.NewRow();\n          dtRow[0] = gridRow.Cells[i].Value;\n          dt.Rows.Add(dtRow);\n      }\n}	0
22793764	22793694	Get AutoGenerated Id from SQL Server using LINQ	CreateWordDoc doc = new CreateWordDoc(meo);\n meo.Id= meoData.id\n int test = meo.Id;	0
3197764	3197529	How to Achieve Group Results by Max Date in Entity Framework	var query = from zone in \n            this.Context.Zones\n            where zone.PageID == pageID\n            group zone by new { zone.PageID, zone.ZoneID } into zoneGroup\n            let maxDate = zoneGroup.Max(x => x.DateCreated)\n            select zoneGroup.Where(x => x.DateCreated== maxDate);\n\n\nforeach (var result in query)\n{\n     // ... do something  \n}	0
22616353	22616310	C# String to Float	string myFloat = "1.94";\ndecimal f = decimal.Parse(myFloat);	0
5902548	5902491	C# .Net 4.0 Console App - how to stay alive until all threads complete?	ParallelOptions options = new ParallelOptions();\n                    Parallel.ForEach(items, options, item=>\n                    {\n// Do Work here\n                        }\n                    });	0
10737224	10736301	Importing directory of file using c#, need a filename column?	Inputs and Outputs	0
25579673	25579574	how to give a panel its exact size in c#?	if (found == false)\n                {\n                    if (i > 0 && ctot25 != 0 || ctot50 != 0 || ctot100 != 0)\n                    {\n                        //Somthethin\n\n                        Label lbl_Name = new Label { Location = new Point(50, 50), Text = (dataGridView1.Rows[i].Cells[1].Value).ToString() };\n                         this.Controls.Add(lbl_Name);\n\n                         //The rest of the codes\n\n                    }\n                }	0
6675227	6665987	The model item passed into the dictionary is of type 'MyType', but this dictionary requires a model item of type 'MyType'	Assembly.Load('myAssemblyName')	0
23460892	23460863	Calculating multilingual string length in C# for storage in an Oracle VARCHAR2 field	Encoding.UTF8.GetBytes(stringValue).Length	0
7560739	7560503	Inserting new tuples into a 1 to many relationship tables using c# DataSet	GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName,      this.type);\nthis.groupsTableAdapter.Update(this.GroupsDataSet.Groups);\nthis.groupsDataSet.Members.AddMembersRow(memberName, addedGroup);\nthis.membersTableAdapter.Update(this.GroupsDataSet.Members);	0
15481667	15331601	Web API OData - Expose ComplexType with ODataModelBuilder	public class Status\n{\n   // whatever you have here...\n}\n\n// essentially create a duplicate class\npublic class DerivedStatus : Status { }\n\n// using modelBuilder...\nmodelBuilder.ComplexType<Status>();\nmodelBuilder.EntitySet<DerivedStatus>("Statuses");	0
27474966	27474866	Problems with datagridview	dgv_All.Rows[12].DefaultCellStyle	0
7196293	7185175	log4net appender to mysql in c# application	The connection type (provider) can be specified by setting the connectionType property	0
12149659	12075062	Saving each WAV channel as a mono-channel WAV file using Naudio	var reader = new WaveFileReader("fourchannel.wav");\nvar buffer = new byte[2 * reader.WaveFormat.SampleRate * reader.WaveFormat.Channels];\nvar writers = new WaveFileWriter[reader.WaveFormat.Channels];\nfor (int n = 0; n < writers.Length; n++) \n{\n    var format = new WaveFormat(reader.WaveFormat.SampleRate,16,1);\n    writers[n] = new WaveFileWriter(String.Format("channel{0}.wav",n+1), format);\n}\nint bytesRead;\nwhile((bytesRead = reader.Read(buffer,0, buffer.Length)) > 0) \n{\n    int offset=  0;\n    while (offset < bytesRead) \n    {\n        for (int n = 0; n < writers.Length; n++) \n        {\n            // write one sample\n            writers[n].Write(buffer,offset,2);\n            offset += 2;\n        }           \n    }\n}\nfor (int n = 0; n < writers.Length; n++) \n{\n    writers[n].Dispose();\n}\nreader.Dispose();	0
27280046	27279753	How to get list of user in a particular role?	public ActionResult Index()\n{\n        // Assuming that Coordinator has RoleId of 3\n        var users = Context.Users.Where(x=>x.Roles.Any(y=>y.RoleId == 3)).ToList();\n        return View(users);\n}	0
6606989	6602297	How can I query if a user of one domain is a member of a group in another AD domain?	/* Connection to Active Directory\n */\nstring sFromWhere = "LDAP://WIN-COMPUTER:389/";\nDirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\user", "password");\n\n/* To find all the groups that "user1" is a member of :\n * Set the base to the groups container DN; for example root DN (dc=dom,dc=fr) \n * Set the scope to subtree\n * Use the following filter :\n * (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)\n */\nDirectorySearcher dsLookFor = new DirectorySearcher(deBase);\ndsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";\ndsLookFor.SearchScope = SearchScope.Subtree;\ndsLookFor.PropertiesToLoad.Add("cn");\n\nSearchResultCollection srcGroups = dsLookFor.FindAll();	0
204870	204814	Is there any valid reason to ever ignore a caught exception	try {\n  // Do something that might generate an exception\n} catch (System.InvalidCastException ex) {\n  // This exception is safe to ignore due to...\n} catch (System.Exception ex) {\n  // Exception handling\n}	0
3051455	3051321	Closing workbook in Excel programmatically	using Excel = Microsoft.Office.Interop.Excel;\n(...)\nvar app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");\n// I have english excel, but another culture and need to use english culture to use excel calls...\nThread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");\napp.Workbooks["DataSheet"].Close(false, false, false);	0
12655657	12655632	How to get count of selected entries from Compact Edition SQL?	string sql = string.Format("SELECT COUNT(*) FROM {0})"	0
1900999	1900975	Invoking a pop-up 'confirm' message box in ASP.NET	private void OpenConfirmPrompt()\n{\n    string strScript = "<script language=JavaScript>alert('File Uploaded');</script>";\n\n    if (!ClientScript.IsStartupScriptRegistered("open"))\n    {\n        ClientScript.RegisterStartupScript(typeof(Page), "open", strScript);\n    }\n}	0
27986006	27985418	LINQ to XML extract nested elements	var result = from p in xmlDoc.Descendants("person")\n             from a in p.Descendants("address")\n             where p.Element("personNumber").Value == "2" \n             select new \n                 { \n                   City = a.Element("city").Value, \n                   Location = a.Element("location").Value \n                 };	0
454773	201883	How can you get a ComboBox child of a DataGridView to process all keys, including "."?	public bool EditingControlWantsInputKey(\n    Keys key, bool dataGridViewWantsInputKey)\n{\n    // Let the DateTimePicker handle the keys listed.\n    switch (key & Keys.KeyCode)\n    {\n        case Keys.Left:\n        case Keys.Up:\n        case Keys.Down:\n        case Keys.Right:\n        case Keys.Home:\n        case Keys.End:\n        case Keys.PageDown:\n        case Keys.PageUp:\n            return true;\n        default:\n            return false; // I changed this to: return !dataGridViewWantsInputKey.  My usercontrol can now receive Q, period, dollar, etc.\n    }\n}	0
10333287	10333190	How to input and exception	try\n{\n    current code\n}\ncatch (exception e)\n{\n    error message to user\n}	0
9089574	9089509	create string list in XML settings file	var stringArray = new string[100]; //value of the string\nvar stringArrayIdentifier = new string[100]; //refers to what you will call the field \n//<identifier>string</identifier>\n\nvar settings = new XmlWriterSettings\n                   {Indent = true, IndentChars = "\t", NewLineOnAttributes = false};\nusing (XmlWriter writer = XmlWriter.Create("PATH", settings))\n{\n    writer.WriteStartDocument();\n    foreach (int i = 0; i < stringArray.Length; i++)\n    {\n        writer.WriteStartElement(stringArrayIdentifier[i]);\n        writer.WriteString(stringArray[i]);\n        writer.WriteEndElement();\n    }\n    writer.WriteEndDocument();\n}	0
8954931	8954886	Xml with two attributes in C#	XmlElement el = xmlDoc.CreateElement("ElementName");\nel.SetAttribute("Type", "FirstAttribute");\nel.SetAttribute("Name", "SecondAttribute");\nel.InnerText = ...;	0
1330899	1330082	Subsonic: Simple Repository - Update Crash	SimpleObject simpleReloaded = repo.Single<SimpleObject>(simple.ID);	0
24084595	24070026	Inset automatically all child classes' instances into Dictionary	foreach( Type type in Assembly.GetExecutingAssembly().GetTypes() )\n{\n    if( type.BaseType == typeof( pet ) )\n    {\n        pet aPet = Activator.CreateInstance( type ) as pet;\n        // Now add aPet to your dictionary\n    }\n}	0
16595006	16594155	How to pass parameters in proper manner in C#?	SqlCommand cmd = new SqlCommand();\n   cmd.Connection = OpenConnection();\n   cmd.CommandText = _query;\n   cmd.CommandType = CommandType.StoredProcedure;	0
2070294	2070246	How to map int into enum with EF	[EdmScalarProperty]\npublic int EnumPropInteger {get;set}\npublic MyEnum EnumProp\n{\n    get { return (MyEnum) EnumPropInteger; }\n    set { EnumPropInteger = (int)value; }\n}	0
23919188	23919187	WPF TextBlock refresh in real time	namespace ThrowAway\n{\n\npublic partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        DoCrazyLoop();\n    }\n\n    public void DoCrazyLoop()\n    {\n        DateTime myBirthday = new DateTime(1984, 01, 19);\n        bool breakLoop = false;\n        Timer t = new Timer(o =>\n        {\n            breakLoop = true;\n        }, null, 10000, 100);\n\n        while (breakLoop == false)\n        {\n            TimeSpan daysAlive = DateTime.Now.Subtract(myBirthday);\n            MyTextBlock.Text = daysAlive.TotalDays.ToString();\n        }\n    }\n }\n}	0
13296016	13295967	How can I send information to the console in vs2012 C#	Console.WriteLine(...)	0
9410756	9397176	Capturing an image behind a rectangle	g.CopyFromScreen(relativePosition.X + 2, relativePosition.Y+48,  Point.Empty.X, Point.Empty.Y, bmp.Size);	0
1460882	1460813	Filtering a ObservableCollection by user input	x.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0\nx.EmployeeNumber.ToString().IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0	0
10787005	10786975	How can I move an user control into a panel?	Control myBox1 = LoadControl("~/box/MyBox.ascx");\nif (condition) \n{ \n    panelLeft.Controls.Add(myBox1); \n} \nelse \n{ \n    panelRight.Controls.Add(myBox1); \n}	0
3953236	3953223	C# - Best way to store sets of data (In a table)	public class User\n{\n    public string Name { get; set; }\n    public string IPAddress { get; set; }\n    public string AnotherProperty { get; set;}\n}\n\n\nDictionary<string, User> userTable = new Dictionary<string, User>();\n\nuserTable.Add(userName, new User(){Name = "fred", IPAddress = "127.0.0.1", AnotherProperty = "blah"});	0
13228866	13228738	C# Timer get static method with parameters?	public static class TimerEventsInitializations\n{\n    public static void InitializeWeatherReader()\n    {\n        Timer t = new Timer(1000);\n        t.Elapsed += new EventHandler(MyEventHandler);\n        t.Start();\n    }\n\n    public static void MyEventHandler()\n    {\n       YahooWeatherManager.GetYahooWeatherRssItem("", "http://xml.weather.yahoo.com/ns/rss/1.0")\n    }\n}	0
29008567	29008497	Cross-thread operation not valid: Control 'statusStrip' accessed from a thread other than the thread it was created on	this.BeginInvoke((Action)(() => toolStripStatusLabel1.Text = "This text was set safely."));	0
358978	358912	Remove characters using Regex	StringBuilder pattern = new StringBuilder();\nforeach (string s in arrayOfStringsToRemove)\n{\n    pattern.Append("(");\n    pattern.Append(Regex.Escape(s));\n    pattern.Append(")|");\n}\nRegex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |\n    replacement);	0
3690684	3690673	How to convert this string to an array of integers?	int[] result = "158,141,90,86".Split(',').Select(int.Parse).ToArray();	0
14002614	14002265	Convert a part of a json string to array or list or dictionary?	var jsonSerializer = new JsonSerializer();\n                dynamic stuff = jsonSerializer.Deserialize(new JsonTextReader(new StringReader(json)));\n                var ffff = stuff.response.message;\n\n                var jss = new JsonSerializer();\n                dynamic st = jsonSerializer.Deserialize(new JsonTextReader(new StringReader((string)ffff)));\n\n                var bv = 0;\n                foreach (var msg in st)\n                {\n                    bv++;\n                }	0
12704209	12703816	How to read file (Metro/WinRT)	public string CurrentFileBuffer\n{\n    get; private set;\n}\n\npublic async void ReadTextFile(string Path)\n{\n    var folder = Package.Current.InstalledLocation;\n    var file = await folder.GetFileAsync(Path);\n    var read = await FileIO.ReadTextAsync(file);\n    CurrentFileBuffer = read;\n}	0
11985309	11981111	How to Add Business Logic to the Domain Service in Domain-Driven-Design?	public class Client\n{\n    public string Ip { get; set; }\n    // More properties if needed\n\n    public List<Vote> Votes { get; set; }\n\n    public bool ExceedLimitInDay()\n    {\n    }\n}\n\npublic class Vote\n{ \n    public int Id { get; set; } \n    public DateTime VoteTime { get; set; } \n    public Article Article { get; set; } \n    public Client { get; set; } \n}\n\npublic class Article   \n{   \n    public int Id { get; set; }   \n    public string Title { get; set; }   \n    public string Content { get; set; }   \n\n    public List<Vote> Votes { get; set; }\n\n    public bool IsRepeated(string ip)\n    {\n        return Votes.Select(v => v.Client.Ip == ip).Any();      \n    }\n}	0
11803645	11803518	Extract properties of sql connection string	string connStr = "Data Source=SERVERx;Initial Catalog=DBx;User ID=u;Password=p"; \n\nvar csb = new SqlConnectionStringBuilder(connStr);\n\nstring dataSource = csb.DataSource;\nstring initialCatalog = csb.InitialCatalog;	0
1482191	1482135	Custom AuthorizeAttribute	[CheckArticleExistence]\npublic ActionResult Tags(int articleId)\n{\n...\n}	0
3635798	3635723	How to iterate over 3D String array in C#	foreach (string[,] array in cross)\n{\n   for (int i = 0; i < array.GetLength(0); i++)\n   {\n       for (int j = 0; j < array.GetLength(1); j++)\n       {\n           string item = array[i, j];\n           // do something with item\n       }\n   }\n}	0
5162437	5162409	How to show the "Display Settings" window from C#	Process.Start("control", "desk.cpl")	0
1419197	1419163	From C#, open an arbitrary application	System.Diagnostics.Process process = new System.Diagnostics.Process();\nprocess.StartInfo = \n    new System.Diagnostics.ProcessStartInfo("C:\...\...\myfile.html");\nprocess.Start();\nprocess.WaitForExit(); // this line is the key difference	0
11840973	11831079	Determine clicked row in DevExpress GridControl	TableViewHitInfo hi = ((TableView)gridControl.View).CalcHitInfo(e.OriginalSource as DependencyObject);\n\nif (hi.InRow)\n{\n    //Do work...\n}	0
1958238	1958229	How to compare generic types?	Type type = propertyInfo.PropertyType;\nif (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))\n{\n    ...\n}	0
18595884	18593275	After re-setting the ItemsSource of a WPF ListView it throws an ArgumentException	FileSetting selectedItem;\nprivate void lstViewFolderSettings_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    selectedItem = lstViewFolderSettings.SelectedItem as FileSetting;\n    txtFolder.Text = selectedItem.FolderPath;\n    txtType.Text = selectedItem.Name;\n    txtXPath.Text = selectedItem.XPath;\n\n    lstViewFolderSettings.UnselectAll();\n}	0
8063615	8063589	Summing a list by one property after filtering by another property	double sum = sil.Where(i => i.Part == SomePart).Sum(i => i.NrOfParts);	0
7884974	7884804	Get Last Element in C# using XElement	XDocument doc = XDocument.Load("yourfile.xml");          \n        XElement root = doc.Root;\n        Console.WriteLine(root.Elements("post").Last());	0
1969668	1969652	How to handle generic inheritance	public class GenericBaseClass<T> where T : BaseClass\n{\n    public List<T> collection { get; set; }\n}\n\npublic class GenericDerivedClass1 : GenericBaseClass<DerivedClass1>\n{\n    // Here the collection property will be of type List<DerivedClass1>\n}	0
8532511	8532157	Ways to match a set in memory to a set in database	Dictionary<Document, ISet<Barcode>>	0
12491744	12490969	How to Get Selected Sheet Names in Excel	var sheets = Application.ActiveWindow.SelectedSheets;\n\nvar names = new List<string>();\nforeach (Excel.Worksheet sh in sheets)\n{\n  names.Add(sh.Name);\n}	0
26621088	26620346	Extract Data from Excel File and Store in SQL Server database	Microsoft.Office.Interop.Excel	0
7725598	7724357	 BackgroundWorker OnProgressChanged still fired after RunWorkerCompleted fired	private void button1_Click(object sender, EventArgs e) {\n        if (progressBar1.Value == progressBar1.Maximum) progressBar1.Value = progressBar1.Minimum;\n        else progressBar1.Value = progressBar1.Maximum;\n    }	0
20226143	19888612	Finding the user who modified the shared drive folder files	string owner = System.IO.File.GetAccessControl(e.FullPath).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();\nConsole.WriteLine(owner);	0
29326933	29326796	Deserialize Json with unknown fields / properties	var definition = new { Name = "" };\n\nstring json1 = @"{'Name':'James'}";\nvar customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);\n\nConsole.WriteLine(customer1.Name);\n// James\n\nstring json2 = @"{'Name':'Mike'}";\nvar customer2 = JsonConvert.DeserializeAnonymousType(json2, definition);\n\nConsole.WriteLine(customer2.Name);\n// Mike	0
2445726	2445681	Abstract Methods in "Product" - Factory Method C#	public abstract class WS\n{\n\n    // All derived classes will have to implement this\n    public abstract double Calculate(double a, double b);\n\n    // This can be overriden by derived classes (since it's a virtual method)\n    public virtual string Compare(double a, double b)\n    {\n        // Some default implementation.\n        // Any derived classes can override this implementation if they want\n    }\n}	0
12713788	12713696	Retrive a Digit from a String using Regex	string query = new Uri("http://www.somedomain.com?id=someid").Query;\nvar dict = HttpUtility.ParseQueryString(query);\n\nvar value = dict["id"]	0
7591420	7591401	filtering specific lines in C#	var lines = File.ReadAllLines(filepath)\n                .Select(l=>l.Trim())\n                .Where(l=>l.StartsWith("description"));\ntextBox1.Text = String.Join(Environment.NewLine, lines);	0
20372635	20371759	Type mismatch convert a .doc/docx into a PDF?	Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();\n        wordDocument = appWord.Documents.Open(@"D:\desktop\filename.docx");\n        wordDocument.ExportAsFixedFormat(@"D:\desktop\DocTo.pdf", WdExportFormat.wdExportFormatPDF);	0
4970604	4970003	Set ImageAnnoation image using embedded Resources instead of a file name	private string imageName = "myImage";\n\n//in constructor\nNamedImage foo = new NamedImage(imageName , Properties.Resources.myImage);\nmChart.Images.Add(foo);\n\n//where creating the annotation\nImageAnnotation imgAnnotation = new ImageAnnotation();\nimgAnnotation.Image = imageName;	0
5744196	5737774	How to avoid the ScatterViewItem from capturing mouse up events?	Parent.MouseUpEvent += yourHandler	0
20545191	20537820	Windows Phone read from text file	System.IO.Stream src = Application.GetResourceStream(new Uri("solutionname;component/text file name", UriKind.Relative)).Stream;\n            using (StreamReader sr = new StreamReader(src))\n              {\n                 string text = sr.ReadToEnd();\n              }	0
22361131	22336401	Problems with upgrade from a Windows Phone 7.5 project to WP8	Windows 8 Windows Phone 8: In Windows Phone 8 if you call Show method from the app Activated or Launching event handlers an InvalidOperationException is thrown with the message Error Displaying MessageBox. Alternatively, you should call the Show method from the Page.OnNavigatedTo(NavigationEventArgs) method.	0
17571336	17571260	Check if List<string> contains any value besides specified	var flag = sourceList.Except(new[] { "E", "F", "G" }).Any();	0
34437141	34436804	OutOfMemoryException when reading a string	using (var json= new JsonTextReader(streamReader))\n{\n    JsonSerializer serializer = new JsonSerializer();\n    return (List<MyObject>)serializer.Deserialize(json, typeof(List<MyObject>));\n}	0
24264355	24263615	Measure Courier character width to fill a Listbox	SizeF charSize = e.MeasureString("k", listBFont, \n                                 PointF.Empty, StringFormat.GenericTypographic);	0
32611241	32610178	datagridview autoscroll if some rows are hidden?	int lastRow = dgvLog.Rows.GetLastRow(DataGridViewElementStates.Visible);\nif (lastRow >= 0)\n    dgvLog.FirstDisplayedScrollingRowIndex = lastRow;	0
13256230	13256001	How to get access to parameters value in Returns() using FakeItEasy?	var factory = A.Fake<IFactory> ();\nA.CallTo (() => factory.Create (A<string>.Ignored, A<string>.Ignored))\n              .ReturnsLazily ((string name, string data) => new Data (name, data));\nvar module = new QuickModule (factory);\nvar list = module.GetData ();	0
3093962	3093926	Add entry to list while debugging in Visual Studio	myList.Add(foo)	0
7851610	7851471	Retrieving SelectedItem from ComboBox error	string myValue = reader["my_table_column"].toString();\nComboBoxItem item = new ComboBoxItem();\nitem.Content = myValue;\nmyCombo.Items.Add(item);	0
14547120	14547091	Parse string to date with "PST" format	DateTime dt1 = DateTime.ParseExact("2013-01-14 21:09:06 PST".Replace("PST", "+2"), "yyyy-mm-dd HH:mm z", culture);\nDateTime dt2 = DateTime.ParseExact("2013-01-14 21:09:06 PDT".Replace("PDT", "+2"), "yyyy-mm-dd HH:mm z", culture);\nDateTime dt3 = DateTime.ParseExact("2013-01-14 21:09:06 PLT".Replace("PLT", "+2"), "yyyy-mm-dd HH:mm z", culture);	0
10733599	10733413	Save MdiChildren on Application exit	private void MDIParent1_FormClosing(object sender,\nFormClosingEventArgs e)\n{\nif (MessageBox.Show("Close?",\nAppDomain.CurrentDomain.ToString(), MessageBoxButtons.YesNo) ==\nDialogResult.No)\n{\ne.Cancel = true;\n}\n}	0
29778110	29770775	signalR calls a server method and that method calls a callback method ,outside the hub. How can I call client function from that method?	var hubContext =  GlobalHost.ConnectionManager.GetHubContext<AzureGuidanceEventHubReceiver>();\nhubContext.Clients.All.displayMessage(dataToDisplay);	0
3923022	3922913	How to serialize class members as attributes to xml in C#	[Serializable]\npublic class SerializationTest2\n{\n    [XmlAttributeAttribute]\n    public string MemberA { get; set; }\n}\n\n[Test]\npublic void TestSerialization()\n{\n    var d2 = new SerializationTest2();\n    d2.MemberA = "test";\n    new XmlSerializer(typeof(SerializationTest2))\n        .Serialize(File.OpenWrite(@"c:\temp\ser2.xml"), d2);\n}	0
13769703	13769631	C# display a string into a table	// create an instance of your table, whatever it may be.\n        // create an instance of a row\n        // add row to your table\n        var line = "hello world";\n        foreach (var letter in line)\n        {\n            // create an instance of a column\n            // add column to your row\n            // add label to your column\n            // set text property of lable = letter\n        }	0
32435969	32428838	Trouble with sending using TCP File Transfer Client	private void TransferFile(string _sFileName, string _sIPAdress)\n        {\n            List<Byte> bFileBuffer = File.ReadAllBytes(_sFileName).ToList();\n\n\n            byte[] bFileName = Encoding.ASCII.GetBytes(_sFileName);\n            bFileBuffer.InsertRange(0, bFileName);\n\n            //Get the File name length, BitConvertor occupies the first 4 bytes\n            byte[] brcvdDataCount = BitConverter.GetBytes((UInt32)_sFileName.Count());\n            bFileBuffer.InsertRange(0, brcvdDataCount);\n\n\n            //Open TCP/IP Connection\n            TcpClient tcpClientSocket = new TcpClient(_sIPAdress, 8080);\n            NetworkStream nsNetworkStream = tcpClientSocket.GetStream();\n            nsNetworkStream.Write(bFileBuffer.ToArray(), 0, bFileBuffer.Count);\n            nsNetworkStream.Close();\n\n        }??	0
13306566	13306295	Need to add a hyperlinkfield to a gridview containing data from another column	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n       HyperLink hlControl = new HyperLink();\n       hlControl.Text = e.Row.Cells[0].Text; \n       hlControl.NavigateUrl = "page.aspx?id=" + e.Row.Cells[0].Text;\n       e.Row.Cells[3].Controls.Add(hlControl);\n    }\n}	0
33464300	33464271	C# - How to find a difference between lowest and highest numbers	// Intialize your list (or use the existing one)\nvar list = new List<decimal>{ 1.75m, 1.25m, 2.03m, 1.44m};\n// The result is maximum of the list minus minimum of the list\nvar result = list.Max() - list.Min();\n// Print or use the result\nConsole.WriteLine(result);  // prints the result 0.78	0
14036594	14036427	Validate SQL queries and result sets	commit transaction;	0
21381185	21381157	How to get all minutes in a day?	var startTime = DateTime.Now.Date;\nvar minsOfDay = \n  Enumerable.Range(0, 1440).Select(i => startTime.AddMinutes(i)).ToList();	0
4250416	4250241	How do you use LINQ to find the duplicate of a specific property?	var result = from c in customers\n                 join c2 in customers on c.LastName equals c2.LastName\n                 where c != c2\n                 select c;	0
4622509	2458025	How to properly downcast in C# with a SWIG generated interface?	// .cpp\nclass foo : public bar {\n}\n\n///////////// part of swig\n// .i (swig)\n%extend foo {\n    static foo* GetFoo( bar* iObj ) {\n         return (foo*)iObj;\n   }\n}	0
19776391	19776282	Best way to store a List of GUID and DateTime objects	Dictionary<TKey, TValue>	0
2364406	2357897	Tamperproof table	recordid  tableid  hash	0
22577181	22577093	How do i upload a file to my ftp at weebly.com?	FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(\n    ftpUrl + "/" +??Path.GetFileName(fileName));	0
25199959	24979857	IoC container in MVVMLight - How to pass concrete implementation to the specified element?	SimpleIoc.Default.Register<MainViewModel>(() => new MainViewModel(new X(), new Y(), new Z(), new M(), new N(), SimpleIoc.Default.GetInstance<IDataService>("B")), "B");	0
5889231	5889047	c# library for data aggregation?	int quarters = (int)((eventDate - new DateTime(1, 1, 1)).TotalMinutes / 15);	0
3650870	3650831	Getting rid of an array name in C# XML Serialization	[XmlRootAttribute(ElementName="Root", IsNullable=false)] \npublic class RootNode \n{ \n    [XmlAttribute("Name")] \n    public string Name { get; set; } \n\n    public string SomeKey { get; set; } \n\n    [XmlElement("Element")] \n    public List<int> Elements { get; set; } \n}	0
33226231	33226170	How to create an invoice in asp.net	hw.Write("<H1>This is my title</H1>");\nGridView1.RenderControl(hw);	0
29934675	29918857	Assembly file version management in Silverlight application	Eg- [assembly: AssemblyTrademark("1.1.1.7")]	0
23705116	23704942	The underlying connection was closed - webAPI ,WCF	"Parent": {\n                    "$ref": "1"\n                }	0
32432257	32431950	Format ItemTemplate GridView money item to thousand seperator ASP.NET?	protected string Format_Number(string Number)\n {\n    // Variable\n    string value = string.Empty;\n    decimal castValue = 0;\n    bool isValid = false;\n\n    // Check\n    if (Number != string.Empty)\n    {\n        // Parse\n        isValid = decimal.TryParse(Number, out castValue);\n\n        // Check & Set Decimal Valud\n        if (isValid) value = castValue.ToString("0,0");\n    }\n\n\n    return value;\n }	0
16239151	16239003	Double getting converted to Int WPF C#	string value = Math.Abs(-17.00).ToString("0.00");\n\n//value: "17.00"	0
19741596	19740651	How to extract values from the button in listbox?	public void My_Click_Event(object sender, EventArgs args)\n{\n  var o = ((FrameworkElement)sender).Tag;\n}	0
22839945	22834448	Import embedded csv file to a SQL Server database	using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BetfairDatabaseMDI.embeddedResources.Competition.csv"))\n                {\n                    using (StreamReader reader = new StreamReader(stream))\n                    {\n                        while (!reader.EndOfStream)\n                        {\n                            string result = reader.ReadLine();\n                            result = "'" + result + "'";\n                            result = result.Replace(",", "','");\n\n                            MySqlCommand("INSERT INTO Competition " +\n                                        "VALUES (" + result + ")");\n                        }\n                    }\n                }	0
7429714	7429067	How does MessageQueue.BeginReceive work and how to use it correctly?	MoveNext()	0
29976242	29976021	LINQ distinct with corresponding counts based on a List property	var tagCounts = photos\n    .SelectMany(photo => photo.Tags)\n    .GroupBy(tag => tag, (tag, group) => new { tag, count = group.Count() })\n    .ToDictionary(tuple => tuple.tag, tuple => tuple.count);	0
22856214	22856043	How to convert DataTable Cell Value to Object Array in C#	dtentercodemfm.Columns.Add("objrow", typeof (object[]));\ndtentercodemfm.Columns.Add("objrow1", typeof (object[]));	0
17901461	17901098	Programmatically change SQL Server configuration	var query = @"BACKUP DATABASE [aveed_co] \n                        TO  DISK = 'C:\bakup.bak' WITH  INIT \n                        ,NOUNLOAD\n                        ,NAME = N'aveed_co'\n                        ,NOSKIP\n                        ,STATS = 10\n                        ,NOFORMAT \n                        ,COMPRESSION";\n        using (var connection = new SqlConnection(@"Server=myServerAddress;Database=aveed_co;User Id=myUsername;Password=myPassword;"))\n        {\n            connection.Open();\n            using (var command = new SqlCommand(query, connection))\n            {\n                command.CommandTimeout = 0;\n                command.ExecuteNonQuery();\n            }\n        }	0
15612597	15612393	issue removing a XDocument node based on its attribute	doc.Descendants("CreditCard")\n   .Where(x => (string)x.Element("Name") == name)\n   .Remove();	0
34405075	34384873	MySql Raspberry Pi Connection from Outsitde LAN	address.pagekite.me	0
18180848	18128621	Set selected date for TimePicker(Extended Toolkit - WPF) control	StartTimeText.Value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Second);\nStopTimeText.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);	0
7388099	7386345	Maximum possible length of FileVersionInfo.FileVersion string on Windows	var info = System.Diagnostics.FileVersionInfo.GetVersionInfo(path);\n        var version = string.Format("{0}.{1}.{2}.{3}", \n            info.FileMajorPart, info.FileMinorPart, info.FileBuildPart, info.FilePrivatePart);	0
20465995	20465847	Enumerate all open connections	IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();\n        TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();	0
27341459	27341397	Saving Streaming Data in SQL Server 2012	private static void Stream_FilteredStreamExample()\n{\n    var stream = Stream.CreateFilteredStream();\n    stream.AddTrack("ebola");\n    stream.MatchingTweetAndLocationReceived += (sender, args) =>\n    {\n        if (!args.Tweet.IsRetweet)\n        {\n            using (SqlConnection conn = new SqlConnection(@"Data Source=xxxx;Initial Catalog=Surveillance;Integrated Security=True"))\n            {\n            conn.Open();\n            var tweet = args.Tweet;\n            if(args.Tweet.Coordinates!=null)\n            {\n                using (SqlCommand myCommand = new SqlCommand("INSERT INTO TwitterDatabase(Tweet,Latitude,Longitude) values '"+tweet.Text+"','"+tweet.Coordinates.Latitude+"','"+tweet.Coordinates.Longitude+"')",conn))\n                {\n                    myCommand.ExecuteNonQuery();\n                }\n             }\n             }\n        }\n    };\n  stream.StartStreamMatchingAnyCondition();\n}	0
27966928	27966868	Why is it necessary for each and every Table to have a Primary Key?	where oldcolN=oldvalN	0
15352234	15352097	Properly parsing strings line by line from a website	WebClient client = new WebClient();\n   string downloadString = client.DownloadString("https://example.com/Testing.php");\n\n   string[] stringSeparators = new string[] {"<br/>"};\n   string[] Lines = downloadString.Split(stringSeparators, StringSplitOptions.None);\n   foreach (string line in Lines)\n   {\n        string[] words = line.Split('|');\n        foreach (string word in words)\n        {\n\n                 ListViewItem item = new ListViewItem();\n                 item.add(word);\n\n        }\n       listView1.Items.Add(item);\n    }	0
4559614	4559572	Variable to list assignment in C#?	int[] arr = new[] { 1, 2 };\n\nint a, b;\nPopulate(arr, out a, out b);\n\nstatic void Populate<T>(T[] arr, out T t1, out T t2)\n{\n    t1 = arr[0];\n    t2 = arr[1];\n}	0
31144006	31143895	How to merge three dimensional array in one array	IEnumerable<Comment>[][] moderatedComments;\nvar merged = moderatedComments.SelectMany(x => x).SelectMany( x => x );\n// merged is IEnumerable<Comment>	0
1420493	1400481	Only Allow Certain Users to Edit ASPxGridView	protected void ASPxGridView1_DataBound(object sender, EventArgs e)\n{ \n  if (!User.IsInRole(ConfigurationSettings.AppSettings["EditActiveDirectoryGroup"]))\n  {\n    foreach (GridViewColumn c in ASPxGridView1.Columns)\n    {\n      if (c.GetType() == typeof(GridViewCommandColumn))\n      {\n        c.Visible = false;\n      }\n    }\n  }\n}	0
23009689	23009501	Hide Status bar in Windows Phone 8.1 Universal Apps	StatusBar statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();\n\n// Hide the status bar\nawait statusBar.HideAsync();\n\n//Show the status bar\nawait statusBar.ShowAsync();	0
7827437	7827407	C# Best way to convert dynamic to string	string value = Convert.ToString(dataTable.Rows[i][columnName]);	0
21537234	21490696	Creating an Infragistics XamDataChart Programatically with multiple ColumnSeries	List<List<DataPointObjects>> MasterList \n\nmethod NewDataReceived(args){\n\n    foreach Chart{\n      new List<DataPointObjects> temp;\n         Loop through data{\n           Create new data point objects\n           add them to temp\n         }\n      add temp to MasterList\n    }\n\n   // Now that we have all of our chart points\n  Create xAxis\n  Create yAxis\n  Foreach chart in MasterList\n  {\n      Assign xAxis data\n      Assign yAxis data\n\n      Build a ColumnSeries\n      assign it x and y axis\n\n      if chart doesnt contain these axises then add them\n\n      if chart series doesnt containt this new series then add it\n  }\n  chart.datacontext = null\n  chart.datacontext = this\n\n}	0
16269684	16269157	C# variable NumericUpDown	Control[] matches;\nfor (int i = 0; i < 35; i++)\n{\n    br.BaseStream.Position = 0x6316 + i * 4;\n    matches = this.Controls.Find("numericUpDown" + (91 - i).ToString(), true);\n    if (matches.Length > 0 && matches[0] is NumericUpDown)\n    {\n        ((NumericUpDown)matches[0]).Value = br.ReadInt16();\n    }\n}	0
18525247	18524180	Access Resource Folder in Code	BitmapImage test2=\n            new BitmapImage(new Uri("pack://application:,,,/Resources/test2.png", UriKind.Absolute));\nmyImage.Source = test2;	0
24559303	24559262	C# String Splitting of a path to get every sub path	var itpath = item.IterationPath.Split('\\');\n\nint i = 1;\nvar result = itpath.Select(x => string.Join("\\", itpath.Take(i++))).ToList();	0
13014208	12979259	Writing a comment to a file in VSS 6.0 without using checkin method	string Comment { get; }	0
5974744	5974152	XML Data management in .NET	// load the XML file into an XElement\nXElement xml = XElement.Load(filePath);\n\n// add a new book\nxml.Add(\n    new XElement("BOOK",\n        new XElement("TITLE", "book 3"),\n        new XElement("AUTHOR", "author 3"),\n        new XElement("PRICE", 0.1),\n        new XElement("YEAR", 2012)));\n\n// remove a book that matches the desired title     \nxml.Elements("BOOK").Where(x => x.Element("TITLE").Value == "book 1").Remove();\n\n// to edit an existing element:\nxml.Elements("BOOK")\n    .Single(x => x.Element("TITLE").Value == "book 2") // take a single book\n    .Element("AUTHOR").Value = "new author";  // and change its author field	0
12378454	12377985	Use a list or array to build a query string in MVC3	var routeValues = new RouteValueDictionary();\n            for (var i = 0; i < SelectedDivisions.Count; i++)\n            {\n                routeValues["SelectedDivisions[" + i + "]"] = SelectedDivisions[i];\n            }\n            action.AddRouteValues(routeValues);	0
22354525	22329146	WCF Data Service set access rule for table columns instead of the whole table	[ChangeInterceptor("Customers")] // table to query intercept\npublic void WindowsServiceChange(Customer customerEntity, UpdateOperations operations)\n{            \n        // make sure following colums are not changed\n        if (this.CurrentDataSource.Entry(customerEntity).Property("Password").IsModified)\n        {\n            // client attempted to update a column he was not supposed to update\n            throw new DataServiceException(400, "Access to update column denied");\n        }\n\n        // else do nothing\n}	0
15166104	15164918	How to display a user control source code on an .aspx page?	FileInfo myControl = new FileInfo(Server.MapPath(@"~\test.aspx.cs"));\nStreamReader myControlSource = myControl.OpenText();\nstring myControlSourceHtml = Server.HtmlEncode(myControlSource.ReadToEnd());	0
27010510	27009243	How to bind MediaElement source in C# windows store 8.1	set\n        {\n            if (this._media != value)\n            {\n                this._media = value;\n                this.OnPropertyChanged("Media");\n            }\n        }\n    }\n\n    public void SetMedia(Uri baseUri, String path)\n    {\n       Media = new Uri(baseUri,path);\n    }	0
21490656	21489167	ServiceStack iterate through all request/response DTO	/resources	0
23264383	23264179	How to check first textbox value is in second textbox textmode	private void txtDateFrom_TextChanged(object sender, EventArgs e)\n{\n    var styles = DateTimeStyles.None;\n    DateTime dateValue;\n    if(DateTime.TryParse(txtDateFrom.Text, System.Globalization.CultureInfo.InvariantCulture, styles, out dateValue))\n    {\n        TextBox2.Text = Convert.ToString(dateValue.AddDays(7));\n    }\n    else\n    {\n        TextBox2.Text = "Invalid DateTime inserted in txtDateFrom;";\n    }\n}	0
875090	875048	Moq with Action argument	It.IsAny<Action<string, string>>()	0
2773654	505175	C# - What is the best way to get a list of the weeks in a month, given a starting weekday?	// Get the weeks in a month\n\n DateTime date = DateTime.Today;\n // first generate all dates in the month of 'date'\n var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));\n // then filter the only the start of weeks\n var weekends = from d in dates\n                where d.DayOfWeek == DayOfWeek.Monday\n                select d;	0
8150477	8150079	Drawing with brush on UserControl	public override void Draw(Graphics graphics)\n{\n    if (this.bitmap != null)\n    {\n        Graphics g = Graphics.FromImage(this.bitmap);\n        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n        g.DrawEllipse(new Pen(this.Color, this.PenSize), startPoint.X, startPoint.Y, this.PenSize, this.PenSize);\n        graphics.DrawImage(this.bitmap, 0, 0);\n    }\n}	0
29804573	29801559	C# Windows Form Chart control - binding multiple y values from csv file	string mySelectQuery = "Select * from " + file;\nstring ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +\n";Extended Properties=\"Text;HDR=No;FMT=Delimited\"";\n\nOleDbConnection myConnection = new OleDbConnection(ConStr);\nOleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);\n\nchart1.DataSource = myCommand;\n\nfor (int i = 0; i < chart1.Series.Count; i++) {\n    chart1.Series[i].XValueMember = "1";\n    chart1.Series[i].YValueMembers = (i+2).ToString();\n}\nchart1.DataBind();	0
29356575	29241788	Ignoring Properties inside Composite Property with BsonIgnore	BsonClassMap.RegisterClassMap<Role>(cm =>\n  {\n     cm.AutoMap();// Automap the Role class\n     cm.UnmapProperty(c => c.RoleId); //Ignore RoleId property\n     cm.UnmapProperty(c => c.CreateDate);//Ignore CreateDate property\n  });	0
33442546	33442503	Sorting a list in C# with special characters	var sorted  = input.OrderBy(a=>int.Parse(a.Split('/')[0]));	0
9762078	9761950	Adding custom colors to Color struct?	public struct MoreColors // or public static class\n{\n    public static Color SomeNiceColor { get { return Color.FromArgb(12,136,20); } }\n    public static Color MyPreferredColor { get { return Color.FromArgb(209,80,0); } }\n}	0
18009903	17982632	How to assign a value to an Orchard ContentPickerField from code?	var submittedByField = ((dynamic)q.ContentItem).Question.SubmittedBy;\nsbmittedByField.Ids = new[] { submittedById };	0
15614065	15613999	Reduce 2 foreach loops into a linq query	var deleteList = currentWhiteListApps.Where(x =>\n                     clientSideWhiteLists.All(y => !x.appID.Equals(y.appID)))\n                                     .ToList();	0
8288413	8288401	C# - FileStream: both lock a file and at the same time be able to read it without truncating it and write it with truncating it	private void button2_Click(object sender, EventArgs e)\n{\n    fs.Seek(0,0);\n    fs.SetLength(Encoding.UTF8.GetBytes(textbox.Text).Length));\n    StreamWriter sw = new StreamWriter(fs);\n    sw.Write(textbox.Text);\n    sw.Flush();\n}	0
29227706	29226694	Is there any way to extract song's info (artist and track name) from the iTunes window	IiTunes::get_CurrentTrack()	0
7656652	7656294	How to make Treeview check only one option	void node_AfterCheck(object sender, TreeViewEventArgs e) {\n    // only do it if the node became checked:\n    if (e.Node.Checked) {\n        // for all the nodes in the tree...\n        foreach (TreeNode cur_node in e.Node.TreeView.Nodes) {\n            // ... which are not the freshly checked one...\n            if (cur_node != e.Node) {\n                // ... uncheck them\n                cur_node.Checked = false;\n            }\n        }\n    }\n}	0
2400631	2400490	Check if a dataGridView has errorText set on any of it's cells	private bool HasErrorText()\n    {\n        bool hasErrorText = false;\n        //replace this.dataGridView1 with the name of your datagridview control\n        foreach (DataGridViewRow row in this.dataGridView1.Rows)\n        {\n            foreach (DataGridViewCell cell in row.Cells)\n            {\n                if (cell.ErrorText.Length > 0)\n                {\n                    hasErrorText = true;\n                    break;\n                }\n            }\n            if (hasErrorText)\n                break;\n        }\n\n        return hasErrorText;\n    }	0
14143616	14143504	Changes entire array instead of one cell	for(int i = 0; i <= board.GetUpperBound(0); i++)\n    for (int j = 0; j < board.GetUpperBound(1); j++)\n        board[i, j] = new PictureBox(); // create new picture box for each cell	0
19072493	19060166	Set background image from picture library	MediaLibrary library = new MediaLibrary();\nPicture picture = library.Pictures[rnd.Next(0, library.Pictures.Count - 1)];\n\nBitmapImage bitmapimage = new BitmapImage();\nbitmapimage.SetSource(picture.GetImage());\nBackgroundImg.ImageSource = bitmapimage;	0
443656	442235	What's the best way to synchronize XmlWriter access to a file to prevent IOExceptions?	private static readonly object syncLock = new object();\n\npublic void SaveToDisk()\n{\n     lock(syncLock)\n     {\n          ... write code ...\n     }\n}\n\npublic void ReadFromDisk()\n{\n     lock(syncLock)\n     {\n          ... read code ...\n     }\n}	0
9919102	9919060	button click check?	//Checks if any button has Text = ""\nif (this.Controls.OfType<Button>().Any(b => b.Text == string.Empty))\n{\n\n}	0
6072215	6071473	Winform: Binding a custom control property to a BindingList	customControl.DataBindings.Add("CustomProperty", list, "BoundObjectProperty", \n    false, DataSourceUpdateMode.OnPropertyChanged);	0
21781062	21780154	Linq query with wildchar in field value	var dataSource = new List<string>() { "100-50-*" };\n   var filteredData = dataSource.Where(l => "100-50-10".StartsWith(l.Replace("*",string.Empty))).ToList();	0
11294541	11292755	Calculating area between two curves	class Program\n{\n    /// <summary>\n    /// Calculate integral with trapezoidal rule\n    /// </summary>\n    /// <param name="h">The step size in x-axis</param>\n    /// <param name="y">The array of values to integrate</param>\n    /// <returns>The area under the curve y[i,0]</returns>\n    public static double Integrate(double h, double[,] y)\n    {\n        int N=y.GetLength(0);\n\n        double sum=(y[0, 0]+y[N-1, 0])/2;\n\n        for(int i=1; i<N-1; i++)\n        {\n            sum+=y[i, 0];\n        }\n\n        return h*sum;\n    }\n\n    static void Main(string[] args)\n    {\n        int N = 100;\n        double[,] y=new double[N, 1];\n\n        for(int i=0; i<y.GetLength(0); i++)\n        {\n            y[i, 0]=5+5*Math.Sin(2*Math.PI*i/(N-1));\n        }\n\n        double x_min=0.5;\n        double x_max=3.5;\n        double h = (x_max-x_min)/N;\n\n        double area=Integrate(h, y);\n        // expected answer is   area = 15.00\n        // actual answer is     area = 14.85\n    }\n}	0
9451691	9451678	Is it possible to have same property with two different names in .NET	public int Product_Id { get { return ProductID; } set { ProductID = value; } }	0
6785581	6785525	How to take zero from the decimal part?	var parts = ("10.0").Split('.'); //or context.NumberToTranslate\n\nparts[0] //"10"\nparts[1] //"0"\n\n//Convert\nstring[] number = Convert.ToString(parts);	0
28992877	23262133	Problems with adding attachments to a workItem (changing dates)	var attachInfo = new AttachmentInfo(tempFile);\nattachInfo.AddedDate = attach.AddedDate;\nattachInfo.CreationDate = attach.CreationDate;\nattachInfo.Comment = string.Format(@"{0} (from attachId={1})", attach.Comment, attach.Id);                        \nattachInfo.RemovedDate = attach.RemovedDate;\nattachInfo.FieldId = 50;\nitemTo.LinkData.AddLinkInfo(attachInfo, itemTo);	0
16718513	16702616	Payment method in nopcommerce	webClient.UploadValues(GetPaypalUrl(), "POST", form);	0
18059113	18058879	Unable to find workaround for color conversion	Console.WriteLine(8689404.ToString("X6"));	0
1029205	1029189	Insert current datetime in Visual Studio Snippet	Sub PrintDateTime()\n    If (Not IsNothing(DTE.ActiveDocument)) Then\n        Dim selection As TextSelection = DTE.ActiveDocument.Selection\n        selection.Insert(DateTime.Now.ToString())\n    End If\nEnd Sub	0
24410893	24410809	Change a gridview's datasource dynamically	DataGridView.AutoGenerateColumns	0
10019982	10019533	Memory-wise, is it better to store a long non-dynamic string as a single string object or to have the program build it out of it's repetitive parts?	Regex checkIP = new Regex(\n   "\\d\\d?\\d?\\.\\d\\d?\\d?\\.\\d\\d?\\d?\\.\\d\\d?\\d?");\n\n private bool isValidIP(string ip)\n {\n   return checkIP.IsMatch(ip);\n }	0
5968726	5968597	Add soap header to a webservice in .net	using (var service = new YourWebService())\n{\n    service.PreAuthenticate = true;\n    service.UseDefaultCredentials = false;\n    service.Credentials = new NetworkCredential(UserName, Password);\n    var response = service.SomeMethod();\n}	0
5200097	5189139	How to render a WPF UserControl to a bitmap without creating a window	void cwind()\n    {\n        Application myapp = new Application();\n        mrenderer = new WPFRenderer();\n        mrenderer.Width = 256;\n        mrenderer.Height = 256;\n\n        HwndSourceParameters myparms = new HwndSourceParameters();\n        HwndSource msrc = new HwndSource(myparms);\n        myparms.HwndSourceHook = new HwndSourceHook(ApplicationMessageFilter);\n\n        msrc.RootVisual = mrenderer;\n        myapp.Run();\n    }\n    static IntPtr ApplicationMessageFilter(\nIntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)\n    {\n        return IntPtr.Zero;\n    }	0
14751741	14751659	Moq verify that the same method is called with different arguments in specified order	[Test]\npublic void Test(){\n    var arguments = new[]{"aa", "bb", "cc"};\n    var mock = new Mock<TextWriter>();\n    int index = 0;\n    mock.Setup(tw => tw.WriteLine(It.IsAny<string>()))\n        .Callback((string s) => Assert.That(s, Is.EqualTo(arguments[index++])));\n\n    Do(arguments, mock.Object);\n    mock.Verify();\n    // check all arguments where passed\n    Assert.That(index, Is.EqualTo(arguments.Length));\n}	0
13551810	13551697	How to pause a video and play it from another position in WPF and C#	MediaElement.Position += TimeSpan.FromSeconds(10);	0
30917914	30917736	A list of string tables c#	List<string[]> Signals = new List<string[]>(); \nstring[] Communication  =  new string[3];\n\nCommunication[0] = "a";\nCommunication[1] = "b";\nCommunication[2] = "c";\n\nSignals.Add(Communication);\n\nCommunication = new string[3];\n\nCommunication[0] = "d";\nCommunication[1] = "e";\nCommunication[2] = "f";\n\nSignals.Add(Communication);\n\nforeach (string[] Signal in Signals)\n{\n    foreach (string CommunicationUnit in Signal)\n    {\n        Console.WriteLine(CommunicationUnit);\n    }\n}	0
31203550	31189931	Create Resource Group with Azure Management C# API	var credentials = new TokenCloudCredentials("", "");\nvar client = new Microsoft.Azure.Management.Resources.ResourceManagementClient(credentials);            \nvar result = c.ResourceGroups.CreateOrUpdateAsync("MyResourceGroup", new Microsoft.Azure.Management.Resources.Models.ResourceGroup("West US"), new System.Threading.CancellationToken()).Result;	0
19954038	19953945	Sort on List with KeyValuePair	aux.OrderBy(x=>x.Key).ToList().ForEach(x=>ret.Add(x.Key,x.Value));	0
2254352	2032415	Render a content control in another tab of TabControl	public static class ExtensionMethods\n{\n   private static Action EmptyDelegate = delegate() { };\n\n   public static void Refresh(this UIElement uiElement)\n   {\n      uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);\n   }\n}\n\nvoid Page_Loaded(object sender, RoutedEventArgs e)\n{\n    // irrelevant code\n    foreach (// iterate over content that is added to each tab)\n    {\n        TabItem tabItem = new TabItem();\n        // load content\n        tabPanel.Items.Add(tabItem);\n        tabItem.IsSelected = true;\n        tabItem.Refresh();\n    }\n    // tabPanel.SelectedIndex = 0;\n}	0
10417114	10417037	Getting property name and distinct values of a type T from a List<T> with reflection	private static Dictionary<string, Dictionary<object, int>> \n    getDistinctValues<T>(List<T> list)\n{\n    var properties = typeof(T).GetProperties();\n\n    var result = properties\n        //The key of the first dictionary is the property name\n        .ToDictionary(prop => prop.Name,\n            //the value is another dictionary\n            prop => list.GroupBy(item => prop.GetValue(item, null))\n                //The key of the inner dictionary is the unique property value\n                //the value if the inner dictionary is the count of that group.\n                .ToDictionary(group => group.Key, group => group.Count()));\n\n    return result;\n}	0
26530889	26530439	Selecting everything but Specific item in string	var x = curStr\n         .Split(',')\n         .Select(y => y.Contains('[') ? y.Split('[').Skip(1).First() : y )\n         .Select(z => z.Replace("]",string.Empty));	0
22796392	22782474	Initilize var by if - else	var result = IsByDescending ? \n               listModelElements.OrderByDescending(x => sort(x)).ToList() :\n               listModelElements.OrderBy(x => sort(x)).ToList();	0
12985077	12984856	C# When using a KeyPress event on a text box, why cant i enter a minus sign?	private void MyButton_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar >= '0' && e.KeyChar <= '9') return;\n    if (e.KeyChar == '+' || e.KeyChar == '-') return;\n    e.Handled = true;\n}	0
1966564	1966427	Best practice for my solution	public partial class DataClassesDataContext\n    {\n        public DataClassesDataContext()\n            : base(StaticMethodThatYouDoLogicForConnStringDecision(), mappingSource)\n        {\n\n        }\n    }	0
2005102	2005054	How to salt and hash a password value using c#?	System.Cryptography	0
21849863	21849228	insert xml string to xml element using LINQ	var content = XDocument.Load("content.xml")\n                       .Root.Elements("page")\n                       .ToDictionary(p => (int)p.Attribute("no"));\n\nvar xdoc = XDocument.Load("template.xml");\n\nforeach (var page in xdoc.Descendants("page"))\n{\n    XElement data;\n    if (!content.TryGetValue((int)page.Attribute("no"), out data))\n        continue;\n\n    page.ReplaceNodes(data.Nodes());\n}	0
6132417	5918577	Can I obtain the ClickOnce published Product Name from inside the application?	var inPlaceHostingManager = new InPlaceHostingManager(ApplicationDeployment.CurrentDeployment.UpdateLocation, false);\ninPlaceHostingManager.GetManifestCompleted += ((sender, e) =>\n{\n    try\n    {\n        var deploymentDescription = new DeploymentDescription(e.DeploymentManifest);\n        string productName = deploymentDescription.Product;\n        ***DoSomethingToYour(productName);***\n\n        // - use this later - \n        //var commandBuilder = new StartMenuCommandBuilder(deploymentDescription);\n        //string startMenuCommand = commandBuilder.Command;\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);\n    }\n});	0
8901632	8901523	Encrypt data prior to Serialization	[XmlRootAttribute("FooClass")] \npublic class FooClass\n{\n    private string _personalData;\n\n    [NonSerialized()]\n    public string PersonalData\n    {\n        set { _personalData = value;}\n        get { return _personalData; }\n    }\n\n    [XmlAttribute("PersonalData")]\n    public string PersonalDataEncrypted\n    {\n        set { _personalData = DecryptData(value);}\n        get { return EncryptData(_personalData); }\n    }\n}	0
20594164	20594140	How to access private function of a class in another class in c#?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace ExposePrivateVariablesUsingReflection\n{\n    class Program\n    {\n        private class MyPrivateClass\n        {\n            private string MyPrivateFunc(string message)\n            {\n                return message + "Yes";\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            var mpc = new MyPrivateClass();\n            Type type = mpc.GetType();\n\n            var output = (string)type.InvokeMember("MyPrivateFunc",\n                                    BindingFlags.Instance | BindingFlags.InvokeMethod |\n                                    BindingFlags.NonPublic, null, mpc,\n                                    new object[] {"Is Exposed private Member ? "});\n\n            Console.WriteLine("Output : " + output);\n            Console.ReadLine();\n        }\n    }\n}	0
22665128	22643132	Difficulty processing Swiss keyboard '+'	[DllImport("user32.dll")]\n  public static extern int ToUnicode(\n      uint wVirtKey,\n      uint wScanCode,\n      byte[] lpKeyState,\n      [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] \n        StringBuilder pwszBuff,\n      int cchBuff,\n      uint wFlags);\n\n  static string GetCharsFromKeys(Keys keys, bool shift, bool altGr)\n  {\n     var buf = new StringBuilder(256);\n     var keyboardState = new byte[256];\n     if (shift)\n        keyboardState[(int)Keys.ShiftKey] = 0xff;\n     if (altGr)\n     {\n        keyboardState[(int)Keys.ControlKey] = 0xff;\n        keyboardState[(int)Keys.Menu] = 0xff;\n     }\n     ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0);\n     return buf.ToString();\n  }	0
7432263	7432182	Help with basic structuremap wiring	container.GetInstance<ICar>();	0
27137743	27137589	C# How to change FileAttributes from Normal to Directory	File.SetAttributes	0
21831418	21829858	How to search in Data gridview in C# Windows Form application?	BindingSource bs = new BindingSource();\nbs.DataSource = dataGridView1.DataSource;\nbs.Filter = columnNameToSearch + " like '%" + textBox1.Text + "%'";\ndataGridView1.DataSource = bs;	0
14092706	14092488	How to append array of bytes to the existed StorageFile?	String s = "hello";\nByte[] bytes = Encoding.UTF8.GetBytes(s);\n\nusing (Stream f = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync\n    ("hello.txt", CreationCollisionOption.OpenIfExists))\n{\n    f.Seek(0, SeekOrigin.End);\n    await f.WriteAsync(bytes, 0, bytes.Length);\n}	0
14387803	14387597	EF Code First Duplicate Foreign Key for same table	HasRequired(a => a.Schedule).WithMany(x=> x.Appointment).Map(x => x.MapKey("SCHEDULEID"));	0
9565225	9565173	Change color of specific rows (TELERIK)	protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)\n{\n    //Is it a GridDataItem\n    if (e.Item is GridDataItem)\n    {\n        //Get the instance of the right type\n        GridDataItem dataBoundItem = e.Item as GridDataItem;\n\n        //Check the formatting condition\n        if (int.Parse(dataBoundItem["typedestickets"].Text) =="INDEF")\n        {\n            dataBoundItem["typedestickets"].ForeColor = Color.Red;\n            dataBoundItem["typedestickets"].Font.Bold = true;\n            //Customize more...\n        }\n    }\n}	0
23543883	23539872	How to get all visible local variable names within a scope with Roslyn (Microsoft CodeAnalysis)	SemanticModel.LookupSymbols()	0
5236156	5236131	filling a Dictionary<> with an IEnumerable<> source	return source.ToDictionary(item => item.ID, item => item.Text);	0
28717015	28714740	Using NPOI, how do I return a cell value as it has been formatted by Excel?	using NPOI.SS.UserModel;\n\nDataFormatter dataFormatter = new DataFormatter(CultureInfo.CurrentCulture);\nICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0);\n\nstring value = dataFormatter.FormatCellValue(cell);	0
16620210	16620155	Getting XML Elements By ID in C#	where ab.Attribute("id").Value.Equals(id)	0
25703542	25702722	Get all subarrays from an array using a single loop	#include <stdio.h>\n\nint main() {\n    int myArray[] = {0,1,2,3};\n    int myArrayLength = sizeof(myArray)/sizeof(*myArray);\n    int i, j;\n    for(j=i=0;i<myArrayLength;++i){\n        printf("(%d,%d)", myArray[j], myArray[i]);\n        if(i == myArrayLength -1){\n            i = j++;//++j - 1;\n            printf("\n");\n        }\n    }\n    return 0;\n}	0
15092354	15092180	How can I replicate FileSystemWatcher Filter functionality with Regex in C#	public static string WildcardPatternToRegexPattern(string pattern)\n{\n    return string.Format("^{0}$", Regex.Escape(pattern.Replace('/', Path.DirectorySeparatorChar)).Replace(@"\*", ".*").Replace(@"\?", "."));\n}	0
5898102	5897985	GridView template Column conditionally set to readonly	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)\n    {\n        TextBox txt = (TextBox)e.Row.FindControl("ControlID");\n        txt.ReadOnly = true;\n    }\n}	0
5649878	5649791	Task with Timer crashing a program	public class MyTimerClass\n{\n    private bool isParsing;\n\n    // Other methods here which initiate the log file parsing.\n\n    private void OnTimedEvent(object sender, ElapsedEventArgs e)\n    {\n        if (!isParsing)\n        {\n            isParsing = true;\n            ParseLogFiles();\n            isParsing = false;\n        }\n    }\n}	0
7015118	6363258	SSRS Report Multiparameter from WinForm ListBox C#	testData chaos = new testData();\n\n...\n\nforeach ( Passenger victim in showMe.Passengers )\n        {\n            // msdn.microsoft.com/en-us/library/5ycd1034(v=VS.100).aspx\n            DataRow skeez = chaos.Tables["Victims"].NewRow();\n\n            skeez["Name"] = victim.ToString();\n\n            chaos.Tables["Victims"].Rows.Add( skeez );\n        }\n\n        this.victimsBindingSource.DataSource = chaos.Tables["Victims"];	0
14424374	14424329	How insert element in last list?	m.Add(7);	0
21417259	21417091	How to download file with asp.net on buttton's onClick event?	private void Button1_click(object sender, System.EventArgs e)\n{\n    Response.ContentType = "Application/pdf";\n    Response.AppendHeader("Content-Disposition", "attachment; filename=help.pdf");\n    Response.TransmitFile(Server.MapPath("~/doc/help.pdf"));\n    Response.End();\n}	0
11395541	11395458	lock-less technique to pass double update from one thread to another	System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false);\n    double d = 0;\n    public void ThreadA(object state)\n    {\n        while (true)\n        {\n            d++;\n            are.Set();\n        }\n    }\n\n    public void ThreadB(object state)\n    {\n        while (true)\n        {\n            are.WaitOne();\n            double current = d;\n        }\n    }	0
8326646	8325090	Newtonsoft JSON.NET deserializing to a typed object	**public** Photoset photoset {get;set;}\n    **public** string stat{get;set;}\n}\nclass Photoset\n{\n\n    public string id { get; set; }\n    public string primary { get; set; }\n    public string owner { get; set; }\n    public string ownername { get; set; }\n    public **Photo[]** photo { get; set; }\n    public int page { get; set; }\n    public int per_page { get; set; }\n    public int perpage { get; set; }\n    public int pages { get; set; }\n    public string total { get; set; }\n}\n\nclass Photo\n{\n    public string id { get; set; }\n    public string secret { get; set; }\n    public string server { get; set; }\n    public int farm { get; set; }\n    public string title { get; set; }\n    public string isprimary { get; set; }\n\n\n}	0
31830840	31830824	How can I delete a single entry from a table	var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();\n string sql = @"DELETE FROM staff1 WHERE Username = @UserName;";\n\n SqlCommand cmd = new SqlCommand(sql, con);\n cmd.Parameters.AddWithValue("@UserName",useName);\n\n cmd.ExecuteNonQuery();\n con.Close();	0
26896267	26884331	Xamarin Parse Component refresh current user	ParseUser currentUser = ParseUser.getCurrentUser();\n\ncurrentUser.fetchInBackground(new GetCallback<ParseObject>() {\n    public void done(ParseObject object, ParseException e) {\n        if (e == null) {\n            ParseUser currUser = (ParseUser) object;\n            // Do Stuff with currUSer\n        } else {\n            // Failure!\n        }\n    }\n});	0
21943496	21943090	How to Get a Tapped Item via DataContext from the View	var selectedItem1 = (sender as StackPanel).DataContext as TestApp.Common.Theme;	0
19348826	19348798	Get total days (int) between DateTime.Now and a certain DateTime	DateTime a = ;//some datetime\nDateTime now = DateTime.Now;\nTimeSpan ts = now-a;\nint days = Math.Abs(ts.Days);	0
2365317	2365200	How can I use a condition based on the queried data in an anonymous class in LINQ to DataSet?	class Program\n    {\n        static void Main(string[] args)\n        {\n            List<Person> persons= new List<Person>();\n            var result = from p in persons\n            select new\n             {\n              Name = (s.IsMarried ? s.X : s.Y)\n             };\n        }\n    }\n    class Person\n    {\n        public bool IsMarried { get; set; }\n        public string X { get; set; }\n        public string Y { get; set; }\n    }	0
4418336	4418319	C# How to skip number of lines while reading text file using Stream Reader?	// Skip 5 lines\nfor(var i = 0; i < 5; i++) {\n  tr.ReadLine();\n}\n\n// Read the rest\nstring remainingText = tr.ReadToEnd();	0
18245691	18245654	XMLSerialization with no root element	[System.Xml.Serialization.XmlRoot("email-address")]\npublic class email\n{\n    [System.Xml.Serialization.XmlText()]\n    public string emailAddress { get; set; }\n\n}	0
30205488	30205423	CSV file into two arrays	var lineValues = line.Trim().Split(',');\nstudentID = lineValues[0];\nstudentMarks = lineValues[1];	0
4173476	4173358	How to fix this route configuration? Configured route returns 404	routes.MapRoute(\n    "Region",\n    "{region}/{controller}",\n    new { controller = "Home", action = "Index" },\n    new { region = "^UK|US$" }\n);\n\nroutes.MapRoute(\n    "Default",\n    "",\n    new { controller = "Home", action = "Index", region = "UK" }\n);	0
28590660	28588919	How to validate constructor arguments without ca1804	[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals",\n            Justification = "Testing parameters only")]	0
25794743	25478631	Dependency injection based on configuration?	#if DEBUG\n// register fake repository\n#else\n// register AD repository\n#endif	0
10614929	10614793	Updating multiple columns in Mysql using C# Textboxes	string query = " update orderform set enrolmentexpected = " +\ntextBox2.Text + ", stockonhand=" + textBox3.Text + ", numberrequired = "\n+ textBox4.Text +  " where name = '" + textBox1.Text + "';"	0
8153180	8152225	Fetching a form associated with a known string literal from a neighbour project using C# windowsforms application	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Assembly prjB = Assembly.LoadFile(@"C:\...\PrjB.exe");\n            foreach (Type t in prjB.GetTypes())\n                if (t.IsSubclassOf(typeof(Form)))\n                {\n                    Console.WriteLine(t.Name);\n                    Form frm = (Form)Activator.CreateInstance(t);\n                    frm.ShowDialog();\n                }\n            Console.ReadLine();\n        }\n    }\n}	0
2504358	2504333	Problem in sort by date in multi array?	Array.Sort (A, B, comparer); // comparer can be null here to use the default	0
9623399	8748022	Using reflection how to find a class in an assembly which implements a generic base class and create its instance	var genericType = typeof (PresenterBase<>).MakeGenericType(new[] { view.GetType() });\nvar allTypes = GetType().Assembly.GetTypes(); // I assume the class is in the same assembly.\nvar typeToImplement = allTypes.Single(t => t.IsSubclassOf(genericType)); // I assume there is only one implementation for the given type\nvar constructorToCall = typeToImplement.GetConstructors().First(); // I assume there is one constructor\nvar presenter = constructorToCall.Invoke(new object[0]); // I assume there is no parameter	0
13461357	13461326	How do I change phone number in Active Directory using C#	public static void SetUserInfo(string userName)\n    {\n        var dsDirectoryEntry = new DirectoryEntry("LDAP://xxxx/DC=xx,DC=xxx", "ADusername", "ADpassword");\n\n        var dsSearch = new DirectorySearcher(dsDirectoryEntry) { Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))" };\n\n        var dsResults = dsSearch.FindOne();\n        var myEntry = dsResults.GetDirectoryEntry();\n        //myEntry.Properties[property].Value = value;\n        myEntry.Properties["telephoneNumber"].Value = "222-222-2222";\n        myEntry.CommitChanges();\n    }	0
31330635	31330515	Parsing XML File To Strings in C#	string driver = xmlNode.SelectSingleNode("database").Attributes["Name"] ;	0
3297922	3253275	How to know on which letter the user clicked in a WPF TextBlock	private int GetMouseClickPosition(MouseButtonEventArgs mouseButtonEventArgs, \n                                  TextBox textBox1)\n    {\n        Point mouseDownPoint = mouseButtonEventArgs.GetPosition(textBox1);\n        return textBox1.GetCharacterIndexFromPoint(mouseDownPoint, true);\n    }	0
13157433	13157297	How can i retrieve the version of Entity Framework in a WinForms application	Assembly assembly = Assembly.LoadFrom("System.Data.Entity.dll");\nVersion ver = assembly.GetName().Version;	0
23821464	23821205	LINQ Query with multiple joins on fk tables	using(EntityClass entities = new EntityClass())\n{\nvar email = \n      (from biz in entities.BusinessContacts\n      where biz.businessid = bid\n      from codes in entities.ContactsContactCodes\n      where codes.contactcodesid = cid\n      from c in entites.Contacts\n      where c.contactsid == codes.contactsid && c.contactsid == biz.contactsid\n      select c.email).FirstOrDefault();     \n}	0
17774623	17774438	Use a char to display a word	Console.WriteLine("How many words are you going to enter?");\nint wordCount = int.Parse(Console.ReadLine());\n\nstring[] words = new string[wordCount];\nfor (int i = 0; i < words.Length; i++)\n{\n  Console.WriteLine("Please enter your word");\n  words[i] = Console.ReadLine();\n}\n\nConsole.WriteLine("Please enter a letter: ");\nstring searchChar = Console.ReadLine();\n\nfor (int i = 0; i < words.Length; i++)\n{\n  string word = words[i];\n  if (word.Contains(searchChar) == true)\n  {\n     Console.WriteLine(word);\n  }\n}	0
29485373	29484606	Flatten a hierarchy as specifically sorted list	var sortedPeople = \n    from p in people\n    orderby (p.Parent == null ? p.Name : p.Parent.Name),\n      p.Parent == null ? 1 : 2, // this ensures parents appear before children\n      p.Name\n    select p;	0
22510382	22486775	Trouble with barcode rotation using Lesinowsky plugin	string barCode = barCodeTrans + barCodeSeq + barCodeIndex + rotationindex.ToString();\n  Lesnikowski.Barcode.Barcode128 bc = new Lesnikowski.Barcode.Barcode128();\n  bc.Rotation = Lesnikowski.Barcode.RotationType.Degrees90\n  bc.Number = barCode;\n  bc.CustomText = "";\n  bc.Height = 28;\n  bc.NarrowBarWidth = 2;\n  Bitmap bcBitMap = bc.GenerateBitmap();\n  string fileName = barCode + ".jpg";\n  bcBitMap.Save(outputDir + "/" + fileName, ImageFormat.Jpeg);\n  return fileName;	0
24768886	24767976	Download A Non-Directed File With C# In WPF	static void Main()\n{\n    var task = DownloadFileAsync("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");\n    task.Wait();\n\n}\n\nstatic async Task DownloadFileAsync(string url)\n{\n    HttpClient client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip });\n\n    HttpResponseMessage response = await client.GetAsync(url);\n\n    // Get the file name from the content-disposition header.\n    // This is nasty because of bug in .net: http://stackoverflow.com/questions/21008499/httpresponsemessage-content-headers-contentdisposition-is-null\n    string fileName = response.Content.Headers.GetValues("Content-Disposition")\n        .Select(h => Regex.Match(h, @"(?<=filename=).+$").Value)\n        .FirstOrDefault()\n        .Replace('/', '_');\n\n    using (FileStream file = File.Create(fileName))\n    {\n        await response.Content.CopyToAsync(file);\n    }\n}	0
20120197	20118489	Setting Data context	public class Person : INotifyPropertyChanged\n{\nprivate string _name;\nprivate int? _version;\npublic event PropertyChangedEventHandler PropertyChanged;\npublic int? version \n    {\n        get { return _version; }\n        set { SetField(ref _version, value, "version"); }\n    }\npublic int? id { get; set; }\npublic string name \n    {\n        get { return _name; }\n        set { SetField(ref _name, value, "name"); }\n\n    }\npublic bool? isNeeded { get; set; }\n\nprotected virtual void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));\n    }\n    protected bool SetField<T>(ref T field, T value, string propertyName)\n    {\n        if (EqualityComparer<T>.Default.Equals(field, value)) return false;\n        field = value;\n        OnPropertyChanged(propertyName);\n        return true;\n    }\n\n}	0
19753595	19753500	How to make optional parameter in parameterizaed query	var sql = new StringBuilder();\nsql.Append(@"UPDATE UserProfile\n               SET "); \n\nif(addFirstName) // <-- some boolean condition here\n  sql.Append("FirstName = @p_FirstName, ");\n\n// ... etc...\n\nsql.Append(" WHERE UserId = @p_UserId");	0
14020140	13932030	How to know which classes inherit from another one in Visual Studio 2010?	Derived Types	0
18665527	18665489	Improving processing speed of a large SQL table in C#	var sb = new StringBuilder();\nfor(int i=0; i<10000; i++)\n{\n    sb.Append("somestring");\n}\nstring myString = sb.ToString();	0
18106856	18106576	How to use a Variable Name which was Obtained at Run-Time	// get the property from object\nPropertyInfo Property = [Object].GetType().GetProperty("PropertyName");\n\n// get the value\nint value = (int)Property.GetValue([Object], null);	0
4485846	4480527	Send multiple messages between a native named pipe and a System.IO named pipe	// Receive a request from client.\n\nstring message = string.Empty;\nbool finishRead = false;\ndo\n{\n    byte[] bRequest = new byte[1024];\n    int cbRequest = bRequest.Length, cbRead;\n\n    finishRead = NativeMethod.ReadFile(\n        hNamedPipe,             // Handle of the pipe\n        bRequest,               // Buffer to receive data\n        cbRequest,              // Size of buffer in bytes\n        out cbRead,             // Number of bytes read \n        IntPtr.Zero             // Not overlapped \n        );\n\n    if (!finishRead &&\n        Marshal.GetLastWin32Error() != ERROR_MORE_DATA)\n    {\n        throw new Win32Exception();\n    }\n\n    // Unicode-encode the received byte array and trim all the \n    // '\0' characters at the end.\n    message += Encoding.Unicode.GetString(bRequest).TrimEnd('\0');\n}\nwhile (!finishRead);  // Repeat loop if ERROR_MORE_DATA\n\nConsole.WriteLine( "Message received from client: \"{0}\"", message );	0
29513872	29513828	How to force only anonymous access to controller action?	public class AllowAnonymousOnlyAttribute : AuthorizeAttribute\n{    \n    protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        // make sure the user is not authenticated. If it's not, return true. Otherwise, return false\n    }\n}	0
4234389	4234367	php continue X - equivalent in c#	for (int i = 0; i < 10; i++)\n        {\n            Level1:\n\n            for (int j = 0; j < 10; j++)\n            {\n\n            Level2:\n\n                for (int k = 0; k < 10; k++)\n                {\n                    if (k < 5)\n                    {\n                        goto Level1;\n                    }\n\n                    if ( k == 7)\n                    {\n                        goto Level2;\n                    }\n                }\n            }\n        }	0
25540953	24967710	Formatting removed when replacing text from word document header part	Microsoft.Office.Interop.Word.HeadersFooters headers = section.Headers;\nforeach (Microsoft.Office.Interop.Word.HeaderFooter header in headers)\n{\n    Word.Fields fields = header.Range.Fields;\n    foreach (Word.Field field in fields)\n    {\n        //I can check also the field text which i want to replace \n        //if there are multiple fields created with different value\n        if (field.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldUserName)\n        {\n            field.Select();\n            field.Delete();\n            wordApp.Selection.TypeText("Company Name");\n        }\n    }\n}	0
29205732	29205646	How to set many conditions in Func as argument in extesion method?	myOC.Insert(myNewElement, (x=> x.ID != 1 && (x.Name.CompareTo(myString) > 0)))	0
3985547	3985502	Interface implementation and inheritance in C#	public interface Intfc { void xyz();}\n\npublic class BaseClass : Intfc\n{\n    public void xyz()\n    {\n        Console.WriteLine("In Base Class");\n    }\n}\n\npublic class Derived : BaseClass\n{\n    new public void xyz()\n    {\n        Console.WriteLine("In Derived Class");\n    }\n}\n\nstatic void Main(string[] args)\n{\n    Derived mc = new Derived();\n    mc.xyz(); //In Derived Class\n    ((BaseClass)mc).xyz(); //In Base Class\n    ((Intfc)mc).xyz(); //In Derived Class\n\n    Console.ReadKey();\n\n}	0
30902907	30900372	Distribute entity framework models over different assemblies	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");\n\n    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n    {\n      var entityTypes = assembly\n        .GetTypes()\n        .Where(t =>\n          t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true)\n          .Any());\n\n      foreach (var type in entityTypes)\n      {\n        entityMethod.MakeGenericMethod(type)\n          .Invoke(modelBuilder, new object[] { });\n      }\n    }\n}	0
2425797	2425738	making a synchronous calls for other applications	Process p = new Process();\n // Redirect the error stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardError = true;\n p.StartInfo.FileName = "OtherProgram.exe";\n p.StartInfo.Arguments = "My Arguments";\n p.Start();\n // Wait for the child process to exit.\n p.WaitForExit();	0
23507085	23507029	need some advice on comboboxes in c# without using databases	comboBox2.Items.Clear();\nswitch (comboBox1.SelectedItem.ToString()) {\n    case "ProductA":\n        comboBox2.Items.AddRange(new string[]{"1", "2", "3"});\n        break;\n    case "ProductB":\n        comboBox2.Items.AddRange(new string[]{"2.1", "2.2", "2.3"});\n        break;\n}	0
1006651	1006593	Fluent NHibernate column name conventions	ConventionBuilder.Property.Always(s => s.ColumnNames.Add(s.Property.Name + "Num"))	0
32887008	32886827	Randomly generate specific strings in C#	string[] s1 = new string[4] { "00000041", "0000424E", "00004244", "00004D53" };\nRandom rnd = new Random();\nint randIndex = rnd.Next(0,4);\nvar randomString = s1[randIndex];	0
4151116	4150958	How to uncheck a checkbox of a parent form from a child form in C#?	//Form2\nprivate Form refToForm1;\npublic Form RefToForm1\n{\n   get { return refToForm1; }\n   set { refToForm1 = value; }\n}\n\n\n // On buttonClick\n       CheckBox cb=(CheckBox)this.RefToForm1.Controls["checkBox1"];\n       cb.Checked = !cb.Checked;\n\n\n//Form1\n\n Form2 obj2 = new Form2();\n obj2.RefToForm1 = this;\n obj2.Show();	0
11865154	11864980	?omparing against list of dates	public bool DateFallsInRange(IEnumerable<DateTime> startDates, IEnumerable<DateTime> endDates)\n{\n    for (int index = 0; index < startDates.Count; index++)\n    {\n        if ((startDates[index] <= compareDate) && (compareDate <= endDates[index])) return true;\n    }\n    return false;\n}	0
7218137	7218115	Array to string	var fb = new FacebookWebClient();\ndynamic myFriends = fb.Get("me/friends");\nforeach (var friend in myFriends.data)\n{\n    // u can get friend.name here\n}	0
8489538	8488030	How can i link a canvas on a grid, to the mainwindow.xaml?	var gesturesCanvas = YourContentPage.FindName("gesturesCanvas") as Canvas;\nif (gesturesCanvas != null) {\n  // do something\n}	0
2026329	2026087	Maintain value in Fileupload control in asp.net,C#	Sys.WebForms.PageRequestManager.instance.add_beginRequest(BeginRequestHandler)\nSys.WebForms.PageRequestManager.instance.add_endRequest(EndRequestHandler)\n\nfunction BeginRequestHandler(sender, args) {\n  var fileUpload = document.getElementById('fileUpload');\n  var hiddenUpload = document.getElementById('hiddenUpload');\n  hiddenUpload.value = fileUpload.value;\n}\n\nfunction EndRequestHandler(sender, args) {\n  var fileUpload = document.getElementById('fileUpload');\n  var hiddenUpload = document.getElementById('hiddenUpload');\n  fileUpload.value = hiddenUpload.value;\n}	0
28311013	28310954	Read Lines from textfile in assets to array	System.IO.File.ReadLines(filepath)	0
19481691	19481430	Saving values from arraylist to txt C#	static void SaveArray()\n    {\n        ArrayList myArray = new ArrayList();\n        myArray.Add("First");\n        myArray.Add("Second");\n        myArray.Add("Third");\n        myArray.Add("and more");\n\n        StreamWriter sw= File.CreateText(@"C:\file.txt");\n        foreach (string item in myArray)\n        {\n            sw.WriteLine(item);\n        }\n        sw.Close();\n    }	0
19876705	19876267	How to Change text of Text Object in Crystal Report Programmatically	TextObject textObj = (TextObject)MyReport.Sections[2].ReportObjects[3];\nstring newString = "any thing which you want write as your text";\nTextObject newTextObj = MyReport.Sections[2].AddTextObject(newString, textObj.Left, textObj.Top);\nnewTextObj.Height = textObj.Height;\nnewTextObj.Width = textObj.Width;\nnewTextObj.Font = textObj.Font;\nMyReport.Sections[2].DeleteObject(textObj);	0
14213478	14213298	Splitting numeric string into array	int[] nums = myNumber.Replace("10", "A")\n                     .Select(c => Convert.ToInt32(c.ToString(), 16))\n                     .ToArray();	0
24063811	24063130	How can I write a simple LINQ report for a many to many relationship?	public class User\n{\n   public string Id { get; set; }\n   public string UserName { get; set; }\n   public virtual List<Role> Roles { get; set; }\n}\npublic class Role\n{\n    public string Id { get; set; }\n    public string Name { get; set; }\n}	0
30730674	30730594	Switch not entering cases but values match	propType.Trim().ToLower()	0
28019210	28019103	How can I speed up this IronPython code that generates a string of arbitrary size	file.write('0'.zfill(size))	0
22044779	22044658	If/else selected count from sql database	.Where(m => m.ActivityID == id && m.results=="yes")	0
7958544	7957763	From Silverlight OOB application how to check if a process is running	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        using (dynamic SWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWbemLocator"))\n        {\n            SWbemLocator.Security_.ImpersonationLevel = 3;\n            SWbemLocator.Security_.AuthenticationLevel = 4;\n            dynamic IService = SWbemLocator.ConnectServer(".", @"root\cimv2");\n            dynamic QueryResults = IService.ExecQuery(@"SELECT * FROM Win32_Process");\n            dynamic t = QueryResults.Count;\n            for (int i = 0; i < t; i++)\n            {\n                dynamic p = QueryResults.ItemIndex(i);\n                MessageBox.Show(p.name );\n            }\n        } \n    }	0
26733881	26733822	Most efficient way to retrieve one file path from a list of folders	var Files = Directories.SelectMany(x => Directory.EnumerateFiles(x).FirstOrDefault()).ToList();	0
22536217	22536158	Get the same password for the same string	public string GeneratePasswordHash(string thisPassword)\n{\n    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();\n    byte[] tmpSource;\n    byte[] tmpHash\n\n    tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array\n    tmpHash = md5.ComputeHash(tmpSource);\n\n    StringBuilder sOuput = new StringBuilder(tmpHash.Length);\n    for (int i = 0; i < tmpHash.Lenth; i++)\n    {\n        sOutput.Append(tmpHash[i].ToString(?X2?));  // X2 formats to hexadecimal\n    }\n    return sOutput.ToString();\n}	0
16302931	16302901	How to sort DataTable by two columns in c#	var newDataTable = yourtable.AsEnumerable()\n                   .OrderBy(r=> r.Field<int>("ItemIndex"))\n                   .ThenBy(r=> r.Field<int>("ItemValue"))  \n                   .CopyToDataTable();	0
19396287	19396074	How can I convert PropertyInfo[] to Dictionary<string,string>?	public static Dictionary<string, string> GetProperties<T>(params string[] propNames)\n    {\n        PropertyInfo[] resultcontactproperties  = null;\n        if(propNames.Length > 0)\n        {\n            resultcontactproperties = typeof(T).GetProperties().Where(p => propNames.Contains(p.Name)).ToArray();\n        }\n        else\n        {\n            resultcontactproperties = typeof(T).GetProperties();\n        }\n        var dict = resultcontactproperties.ToDictionary(propInfo => propInfo.Name, propInfo => propInfo.Name);\n        return dict;\n    }  \n\n @Html.DropDownListFor(m=>m.properties, new SelectList(\n Entity.Data.ContactManager.GetProperties<Contact>(),"Key","Value"), \n "Select a Property")	0
29928883	29928795	Styles not applying to headless wpf control	var groupControl = ...;\ngroupControl.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));\ngroupControl.Arrange(new Rect(groupControl.DesiredSize));	0
19513726	19513542	Parse and add Elements to XAML using XDocument	XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";\n\nforeach (XElement brush in xdoc.Root.Elements(ns + "SolidColorBrush")) { ... }	0
5659713	5659664	c# how to thread a windows form	namespace UIThreadMarshalling {\n    static class Program {\n        [STAThread]\n        static void Main() {\n                Application.EnableVisualStyles();\n                Application.SetCompatibleTextRenderingDefault(false);\n                var tt = new ThreadTest();\n                ThreadStart ts = new ThreadStart(tt.StartUiThread);\n                Thread t = new Thread(ts);\n                t.Name = "UI Thread";\n                t.Start();\n                Thread.Sleep(new TimeSpan(0, 0, 10));\n        }\n\n    }\n\n public class ThreadTest {\n        Form _form;\n        public ThreadTest() {\n        }\n\n     public void StartUiThread()\n     {\n        using (Form1 _form = new Form1())\n        {\n            Application.Run(_form);\n        }\n     }\n  }\n}	0
20149080	20148024	Generically retrieving different numeric data types from byte array	public T ReadData<T>(int startIndex)\n{\n  Type t = typeof(T);\n\n  if (t == typeof(int))\n  {\n    return (T)(object)ReadInt(startIndex);\n  }\n  else if(t == typeof(byte))\n  {\n    return (T)(object)ReadByte(startIndex);\n  }\n  else\n  {\n    string err = string.Format("Please support the type {0}", t);\n    throw new NotSupportedException(err);\n  }\n}	0
3989577	3989304	Dynamic Text into an Image	Bitmap bmp = new Bitmap(1000,1000);\n\n        using (Graphics g = Graphics.FromImage(bmp))\n        {\n\n          string s = "This string will be wrapped in the output rectangle";\n          RectangleF rectf = new RectangleF (10, 100, 200, 200);\n\n          g.DrawString(s, DefaultFont, Brushes.Red, rectf);\n\n          this.BackgroundImage = bmp; //For testing purposes set the form's background to the image\n\n\n        }	0
585333	585320	Trying to store password to database	public bool ValidateApplicationUser(string userName, string password)\n{\n  DataClasses1DataContext dc = new DataClasses1DataContext();\n\n  var saltValue = dc.ProvaHs.Where(c => c.UserName == userName)\n                            .Select(c => c.Salt)\n                            .SingleOrDefault();\n\n  if (saltValue == null) return false;\n\n  password = PasswordCrypto.HashEncryptStringWithSalt(passwordTextBox.Password, saltValue.ToString());\n\n  return dc.ProvaHs.Any(c => c.UserName == userName && c.Password == password);\n}	0
22732349	22732313	Pass a value to an action in controller	return RedirectToAction("Index", "Score", new { id = score.Id });	0
24851894	24851806	Passing type to a base class from a derived class	public class bar<T> : foo<T>\n{\n    public bar() { ... }\n}	0
16152623	16151658	How to read devices and driver versions	public class Program\n{\n    public static void Main()\n    {\n        ManagementObjectSearcher objSearcher = new ManagementObjectSearcher("Select * from Win32_PnPSignedDriver");\n\n        ManagementObjectCollection objCollection = objSearcher.Get();\n\n        foreach (ManagementObject obj in objCollection)\n        {\n            string info = String.Format("Device='{0}',Manufacturer='{1}',DriverVersion='{2}' ", obj["DeviceName"], obj["Manufacturer"], obj["DriverVersion"]);\n            Console.Out.WriteLine(info);\n        }\n\n        Console.Write("\n\nAny key...");\n        Console.ReadKey();\n    }\n}	0
9977501	9977393	How do I pass an object into a timer event?	string theString = ...;\ntimer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, theString);\n\nstatic void MyElapsedMethod(object sender, ElapsedEventArgs e, string theString) {\n  ...\n}	0
29034075	29031689	Serialize root element in a namespace, not without a namespace	**[System.Xml.Serialization.XmlRoot("GetProfileRequest", Namespace = "urn:veloconnect:profile-1.1", IsNullable = false)**]	0
9279278	9278466	html elements hiding after asp button click	ScriptManager.RegisterStartupScript(this, this.GetType(), this.ID, "$('#back_drop, #login_container').css('display', 'block');", true);	0
33310810	33310398	Startup Sequence for C# WPF MVVM Applications	Model m = null;\n    IViewCallbacks cb;\n    public MainViewModel(IViewCallbacks mainViewCallbacks)\n    {\n         this.cb = mainViewCallbacks;\n         m = new Model();\n    }	0
29075676	29071233	Entity framework exclude fields from insert	public class PositionsContext:DbContext\n{\n    public DbSet<Position> Type { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        base.OnModelCreating(modelBuilder);\n        //define ignores here\n        modelBuilder.Entity<Position>().Ignore(t => t.big5);\n    }\n}	0
10988249	10988204	Open file by URL from WPF	wordProcess.StartInfo.FileName = "winword.exe";\nwordProcess.StartInfo.Arguments = "\"http://sharepoint/blank_site_1/document_library_1/word document file.docx\"";	0
12802070	12794550	identify workstation in a network c#	using System;\nusing System.Management;\nusing System.Windows.Forms;\n\nnamespace WMISample\n{\n    public class MyWMIQuery\n    {\n        public static void Main()\n        {\n            try\n            {\n                ManagementObjectSearcher searcher = \n                    new ManagementObjectSearcher("root\\CIMV2", \n                    "SELECT * FROM Win32_OperatingSystem WHERE ProductType = 2"); \n\n\n            foreach (ManagementObject queryObj in searcher.Get())\n            {\n                Console.WriteLine("-----------------------------------");\n                Console.WriteLine("Win32_OperatingSystem instance");\n                Console.WriteLine("-----------------------------------");\n                Console.WriteLine("ProductType: {0}", queryObj["ProductType"]);\n            }\n        }\n        catch (ManagementException e)\n        {\n            MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);\n        }\n    }\n}	0
11928941	11928919	add server side table content to div of aspx page	// aspx code\n<asp:Label ID ="lbReport" runat="server" />\n\n// Code Behind\nStringBuilder sbreport=new StringBuilder();\nsbreport.Append("<table width='95%' border='0' cellpadding='0' cellspacing='0' align='center'>");\nsbreport.Append("<tr class='tdcolbg'>");\nsbreport.Append("<td>");***SOME CONTENT***\nsbreport.Append("</td>");\nsbreport.Append("</tr>");\nsbreport.Append("</table>");\n\n\nlbReport.Text = sb.ToString();	0
7390476	7390196	load flash page dynamically in C#	var flashvars = {};;\nflashvars.basePath = "/";\n\nvar params = {};\nparams.allowScriptAccess = "always";\nparams.base = "/";\nparams.bgcolor = "#000000";             \nparams.wmode = "transparent";\nparams.scale = "noscale";\nparams.salign = 'tr';\n\nswfobject.embedSWF("<%= GetRandomFlashMove() %>", \n                   "BaseLoader",\n                   "976",\n                   "561",\n                   "10.0.0",\n                   "/expressInstall.swf",\n                   flashvars, params);	0
2206168	2206160	How to create a list inside the another list?	var listOfList = new List<List<int>>(); \nlistOfList.Add(new List<int>());\nlistOfList[0].Add(42);	0
8672123	8672007	where in clause in entity famework	public static Func<DBEntities, string, IQueryable<IV00102>> compiledMemphisQuery =\n    CompiledQuery.Compile((DBEntities ctx, string bomNumber) =>\n        from items in ctx.IV00102\n        where   (\n                                    from orders in ctx.bm00111\n                                    where orders.itemnmbr == bomItem\n                                    select orders.cmpitnm)\n        and items.locncode == "Memphis"\n        select items).Contains(items.ITEMNMBR);	0
2435949	2435895	Any Way to Use a Join in a Lambda Where() on a Table<>?	if (db.TableA.Where( a => a.UserID == CurrentUser )\n      .Join( db.TableB.Where( b => b.MyField == Convert.ToInt32(MyDDL.SelectedValue) ),\n             o => o.someFieldID,\n             i => i.someFieldID,\n             (o,i) => o )\n      .Any()) {\n    ...\n}	0
11338749	11338576	Executing query by reading from excel cell	public void UpdateDatabase()\n        {\n            System.Data.OracleClient.OracleConnection conn = new System.Data.OracleClient.OracleConnection();\n            conn.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.144)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));UID=mwm;PWD=mwm";\n            conn.Open();\n            OracleCommand command = conn.CreateCommand();\n            command.CommandText = strParam1;\n            command.ExecuteNonQuery();\n            command.Dispose();\n        }	0
3295319	3295309	Simple C# Screen sharing application	JpegBitmapEncoder encoder = new JpegBitmapEncoder();\nencoder.QualityLevel = 40;	0
7180531	7180450	how to set system properties in C#	System.Environment.SetEnvironmentVariable("webdriver.chrome.driver",@"/path/to/where/you/ve/put/chromedriver.exe")	0
2022892	2022837	How can I implement a constructor with inline initialization for a custom map class?	public void Add(People p, string name)\n{\n    ....\n}	0
10635315	10635224	C# technique for deleting a file from web server immediately after closing	/// <summary>\n/// FileStream that automatically delete the file when closing\n/// </summary>\npublic class AutoDeleteFileStream : FileStream\n{\n    private string _fileName;\n\n    public AutoDeleteFileStream(string fileName, FileMode fileMode, FileAccess fileAccess)\n        : base(fileName, fileMode, fileAccess)\n    {\n        this._fileName = fileName;\n    }\n\n    public AutoDeleteFileStream(string fileName, FileMode fileMode)\n        : base(fileName, fileMode)\n    {\n        this._fileName = fileName;\n    }\n\n    public override void Close()\n    {\n        base.Close();\n        if (!string.IsNullOrEmpty(_fileName))\n            File.Delete(_fileName);\n    }\n}	0
12928702	12928646	How to pass querystring value in @Url.Action in MVC4	Public ActionResult Delete(string id){\n     //delete the Request.QueryString line\n}	0
1288919	1288886	How to save a table(DataTable) into a single cell in a database?	protected bool LoadXml(SqlConnection cn, XmlDocument doc)\n   {\n    //Reading the xml from the database\n    string sql =  @"SELECT Id, XmlField  FROM TABLE_WITH_XML_FIELD WHERE Id = @Id";\n    SqlCommand cm = new SqlCommand(sql, cn);\n    cm.Parameters.Add(new SqlParameter("@Id",1));\n    using (SqlDataReader dr = cm.ExecuteReader())\n    {\n             if (dr.Read())\n            {\n                      SqlXml MyXml= dr.GetSqlXml(dr.GetOrdinal("XmlField"));\n                      doc.LoadXml( MyXml.Value);\n                      return true;\n            }\n            else\n            {\n                      return false;\n            }\n     }\n    }	0
20494403	20403858	Fluent NHibernate inheritance mapping	public class SomeAnimal : Animal\n{\n\n}\n\npublic class AnimalMap : ClassMap<Animal>\n{\n    public AnimalMap()\n    {\n      Schema("dbo");\n      Table("Animals");   \n\n      Id(x => x.Id).Column("ID").GeneratedBy.Identity();\n      Map(x => x.FoodClassification).Column("FoodClassification");\n      Map(x => x.BirthDate).Column("BirthDate");\n      Map(x => x.Family).Column("Family");\n\n      DiscriminateSubClassesOnColumn().Formula("IIF(classtype = 'dog', 'dog', 'someAnimal')");\n    }\n}\n\npublic class SomeAnimalMap : SubclassMap<SomeAnimal>\n{\n    public SomeAnimalMap()\n    {\n          ReadOnly();\n\n          DiscriminatorValue("someAnimal");\n          Map(x => x.ClassType).Column("classtype");\n    }\n}	0
32001252	32000974	how to limit GET api call based on user properties	db.Documents\n        .Where(j => user.Companies.Any(uc=>uc.Name == j.Company.Name));\n        .ToResults();	0
26885806	26885503	String Format Specifier in C# for with fixed length of strings in Gridview	notes.Substring(0, Math.Min(notes.Length, 10))	0
3745951	3745934	Read random line from a file? c#	string[] lines = File.ReadAllLines(...); //i hope that the file is not too big\nRandom rand = new Random();\nreturn lines[rand.Next(lines.Length)];	0
9241227	9241192	How to add EventHandler to DoubleAnimation end?	da = new DoubleAnimation(40,20,  new Duration(TimeSpan.FromSeconds(2)));\n\nda.Completed += new EventHandler(Story_Completed);\n\n((PerspectiveCamera)_Main3D.Camera).\n    BeginAnimation(PerspectiveCamera.FieldOfViewProperty, da);	0
14376989	14376745	Creating Custom Generic List in C#	protected void btnsearch_Click(object sender, EventArgs e)\n    {\n\n        DateTime start = new DateTime(2013,1,5);\n        DateTime end = new DateTime(2013,2,2);\n\n        string dayName = drpday.SelectedItem.ToString().ToLower();\n\n         Dates dt = new Dates();\n        List<Dates> list = new List<Dates>();\n        int i = 0;\n\n       for (DateTime runDate = start; runDate <= end; runDate = runDate.AddDays(1))\n        {\n            if (runDate.DayOfWeek.ToString().ToLower() == dayName)\n            {\n\n                list.Add(new Dates{\n                      FromDate=runDate.ToShortDateString();\n                      ToDate=(runDate.AddDays(double.Parse(hd_tourdays.Value)).ToShortDateString());\n    });\n\n            }\n        }\n         grd_TourDates.DataSource = list;\n         grd_TourDates.DataBind();\n     }	0
8220828	8220809	Orientation in OpenGL MonoTouch game	// Override to allow orientations other than the default portrait orientation.\n- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {\n    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);\n}	0
12675720	12675421	DateTime.ParseExact format string	var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\nvar dt =  epoch.AddMilliseconds(Convert.ToInt64(Request.QueryString["start"]));	0
3856214	3855998	How to construct unit test	bool foundOne = false;\nforeach (EventLogEntry entry in log.Entries)\n    {\n        if (entry.Message.ToUpper().Contains(logValue))\n        {\n          foundOne = true;\n        }\n    }\n\nAssert(foundOne);	0
14754454	14754067	Direct user to different page based on network connection	System.Web.HttpContext.Current.Request.UserHostAddress	0
13473517	13473342	Merge XML nodes based on attribute value (c#)	var xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)\n\nvar newXDoc = new XElement("profiles",\n                                xDoc.Descendants("profile")\n                                .GroupBy(p => p.Attribute("id").Value)\n                                .Select(p => new XElement("profile", \n                                                    new XAttribute(p.First().Attribute("id")), \n                                                    p.Elements())));\n\nstring newxml = newXDoc.ToString();	0
5635153	5634784	C# MS Chart Control - highlight today's date in Gantt Chart	StripLine strpToday = new StripLine();\n        strpToday.IntervalOffset = DateTime.Today.ToOADate();\n        strpToday.StripWidth = 1;\n        strpToday.BackColor = Color.ForestGreen;\n        chtHC.ChartAreas[0].AxisY.StripLines.Add(strpToday);	0
30142629	30142580	C# Determining value in dictionary	var second = first.OrderByDescending(kvp => Math.Abs(kvp.Value - 0.5))\n                  .Take(10)\n                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);	0
10292292	10291584	Populate CheckedBoxList1 from previous dialog	//CONSTRUCTOR IN TEXTSELECTORFORM\npublic TextSelectorForm(ListBox.ObjectCollection dataFromOtherForm) {\n    InitializeComponents();\n    //Add this code after InitializeComponents();\n    if (dataFromOtherForm != null) {\n        this.listBoxInThisForm.AddRange(dataFromOtherForm);\n    }\n}\n\n\n//CODE FOR BUTTON IN OTHER FORM\nprivate void button3_Click(object sender, EventArgs e) {\n    //Stores the values ??to display in the ListBox\n    ListBox.ObjectCollection data = null;\n\n    //Your code from retrieve data\n    string line;\n    StreamReader file = new StreamReader("test.txt");\n    while ((line = file.ReadLine()) != null) {\n        data.Add(line);\n    }\n    file.Close();\n\n    //Form to send the data\n    TextSelectorForm textSelectionForm = new TextSelectorForm(data);\n    textSelectionForm.Show();\n}	0
1072386	1072327	How do I unit test an implementation detail like caching	depend.Expect(d => d.GrabValue()).Repeat.Once().Return(1);\ndepend.Expect(d => d.GrabValue()).Repeat.Never();	0
6001683	6001576	Saving Panel as JPEG, only saving visible areas c#	public void DrawControl(Control control,Bitmap bitmap)\n    {\n        control.DrawToBitmap(bitmap,control.Bounds);\n        foreach (Control childControl in control.Controls)\n        {\n            DrawControl(childControl,bitmap);\n        }\n    }\n\n    public void SaveBitmap()\n    {\n        Bitmap bmp = new Bitmap(this.panel1.Width, this.panel.Height);\n\n        this.panel.DrawToBitmap(bmp, new Rectangle(0, 0, this.panel.Width, this.panel.Height));\n        foreach (Control control in panel1.Controls)\n        {\n            DrawControl(control, bmp);\n        }\n\n        bmp.Save("d:\\panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);\n    }	0
28169990	28169439	How can I group by a distinct list?	posts\n    .SelectMany(p => p.Tags.Select(t => new {Tag = t, Post = p}))\n    .GroupBy(_ => _.Tag)\n    .ToDictionary(_ => _.Key, _ => _.Select(p => p.Post.Title).ToArray());	0
22411735	22411656	how to use byte array as parameter when calling a WindowsPhoneRuntimeComponent?	public ref class Base64Encoding sealed\n{\n  public:\n    Platform::String^ EncodeData(Platform::String^ data); \n    Platform::String^ DecodeString(Platform::String^ data);\n};	0
20260515	20259371	how to retriving textbox data from database table automatically?	string selectQuery = "SELECT EmployeeID, Weight, Amount FROM Supplier where  EmployeeName=@EmployeeName";\n            SqlCommand cmd = new SqlCommand(selectQuery, conn);\n            SqlDataReader dataReader;\n            conn.Open();\n            dataReader = cmd.ExecuteReader();\n            if (dataReader != null)\n            {\n                while (dataReader.Read())\n                {\n                    //Retrieving data vales from select query in variables\n                   txtboxid.Text = dataReader["EmployeeID"].ToString();\n                     txtboxw.Text = dataReader["Weight"].ToString();\n                     txtboxam.Text = dataReader["Amount"].ToString();\n\n\n                }\n            }	0
27893349	27892154	Save xml file by path from user select	OpenFileDialog theDialog = new OpenFileDialog();\ntheDialog.Title = "Open Text File";\ntheDialog.Filter = "TXT files|*.txt";\ntheDialog.InitialDirectory = @"C:\";\nif (theDialog.ShowDialog() == DialogResult.OK)\n{\n    // if user selected a file, show it's name\n    MessageBox.Show(theDialog.FileName.ToString());\n}	0
3353232	3353113	Lambda expression weirdness in a LINQ to SQL 'where' condition	repository<User>.Find(u => string.IsNullOrEmpty(search) || \n                           u.UserName.Contains(search));	0
6278798	6278637	Quotes in between a csv column text cause skipping of remaining columns while importing csv data	Row1-> col1,"""cdwdf"" dsdfs",col2,col3	0
24767589	24765557	LINQ that groups data and returns series for chart	var months = Enumerable.Range(1, 12);\n var max = DateTime.Now.AddYears(-1);\n var result = data.Where(d => d.OrderDate >= max)\n                .GroupBy(d => d.ProductCategory)\n                .Select(g =>\n                        new\n                        {\n                            Name = g.Key,\n                            Data =( \n                            from m in months\n                            join  d in\n                                g.OrderBy(gg => gg.OrderDate.Year)\n                                .ThenBy(gg => gg.OrderDate.Month)\n                                .GroupBy(gg => gg.OrderDate.Month)\n                                on m equals d.Key into gj\n                                from j in gj.DefaultIfEmpty()\n                                    select j.Key != null ? j.Count() : 0)\n                        }).ToArray();	0
19554607	19554527	Determine type of value of SqlReader field	reader.GetFieldType(i).FullName or reader.GetDataTypeName(i)	0
27287474	27287349	C# DateTime.Now to find yesterday	DateTime today = DateTime.Now.Date;\ntoday = today.AddHours(7);\nDateTime yesterday = today.Subtract(TimeSpan.FromHours(24));\n\n\nSELECT * FROM ExcelOutput WHERE ADateTime >= 'yesterday' AND ADateTime < 'today'	0
29542124	29541885	Saving Image from Panel	int width = Convert.ToInt32(pnlRightThumb.Width);\nint height = Convert.ToInt32(pnlRightThumb.Height);\nBitmap left_thumb = new Bitmap(width1, height);\n\nGraphics g = Graphics.FromImage(left_thumb);\nPoint panel_location;\npanel_location=pnlRightThumb.PointToScreen(Point.Empty);\ng.CopyFromScreen(panel_location.X, panel_location.Y, 0, 0, left_thumb.Size, CopyPixelOperation.SourceCopy);\n\nleft_thumb.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Fingerprints", "left.bmp"), ImageFormat.Bmp);	0
8615339	8615312	How can I get the value from string name?	string myString = "I1P706.jpg"\nint iIndex = myString.IndexOf("I");\nint pIndex = myString.IndexOf("P");\n\nstring betweenIAndP = myString.Substring(iIndex + 1, pIndex - iIndex - 1);	0
19171566	19153424	Sending POST in JSON to ApiController	public void Post(string dataPath, JObject obj)\n{\n    Type myClass = figureOutMyTypeByParsingThePath(dataPath);\n    _dataDict[dataPath] = obj.ToObject(myClass);\n}	0
17654613	17654489	Label change color of a word dynamically	TextBlock tb = new TextBlock();\ntb.Inlines.Add(new Run("Hello"));\ntb.Inlines.Add(new Run("cruel") { Foreground = Brushes.Tomato });\ntb.Inlines.Add(new Run("world !"));	0
10437595	10437416	c# Decimal to string for currency	(5.00).ToString("0.00").Replace(".00","");  // returns 5\n(5.90).ToString("0.00").Replace(".00", ""); // returns 5.90\n(5.99).ToString("0.00").Replace(".00", ""); // returns 5.99	0
4197463	4197284	Parallelizing massive inserts in SQL Server from C# (for better time performance)	BEGIN TRANSACTION;\n\n...<various SQL statements>...\n\nCOMMIT TRANSACTION;	0
12176531	12170166	How to create a projection of private/protected properties with RavenDb	public class Foo_LineItems : AbstractIndexCreationTask\n{\n    public override IndexDefinition CreateIndexDefinition()\n    {\n        return new IndexDefinition\n        {\n            Map = @"\n                    from foo in docs.Foos\n                    where foo.Baz == null\n                    select new { foo.Id, foo.Bar }\n"\n        };\n    }\n}	0
19568773	19568707	How to access an object in c#?	names data= new names();\ndata.values = new values();	0
31720853	31719022	Searching in text files for a keyword until a string is encountered	var searchResults = files.Where(file => File.ReadLines(file.FullName)\n                                            .TakeWhile(line => line != "STOP")\n                                            .Any(line => line.Contains(keyWord)))\n                                            .Select(file => file.FullName);	0
18740944	18739668	Re sizing DataGridView according to its content	private void Form1_Load(object sender, EventArgs e)\n    {\n        int totalWidth = 0;\n        foreach (DataGridViewColumn col in dataGridView1.Columns)\n            totalWidth += col.Width;\n\n        //assign Form1.width (add 100 extra pixels for borders etc.)\n        this.Width = totalWidth + groupBox1.Width + 100;\n    }	0
26327321	26327221	How do you clip an image from the bottom left in WPF?	CroppedBitmap cb = new CroppedBitmap(\n                           bitmapImage,\n                           new Int32Rect(0, (int)(bitmapImage.Height/2),\n                           (int)bitmapImage.Width, (int)(bitmapImage.Height/2));	0
12259265	12258750	Empty response from form in MVC3 using a dynamically built Dictionary to build form	[HttpPost]\npublic ActionResult Edit(int id, FormCollection form)\n{\n    try\n    {\n        foreach(var field in form.Keys)\n        {\n            switch (fieldToUpper().Trim())\n            {\n                case "FIELDNAME":\n                    // assign value to your model property\n                    break;\n            }\n        }\n\n        return RedirectToAction("Index");\n    }\n    catch\n    {\n        return View();\n    }\n}	0
29735757	29735697	How to Sum data by every month in LINQ?	var query = from t in ctx.SomeDataEntity\n                    group t by new \n                    { \n                        Year = t.DateAdded.Year, \n                        Month = t.DateAdded.Month \n                    } into g\n                    select new\n                    {\n                        MonthAndYear = g.Key.Year + "-" + g.Key.Month,\n                        Total = g.Sum(t => t.SomeColumn1) +\n                        g.Sum(t => t.SomeColumn2) +\n                        g.Sum(t => t.SomeColumn3) +\n                        g.Sum(t => t.SomeColumn4)\n                    };	0
10877535	10877430	Encoding issue with Portuguese characters	string s = System.Web.HttpUtility.HtmlDecode("PRA&#199;A DOS OMAGU&#193;S");	0
576520	576476	Get DeviceContext of Entire Screen with Multiple Montiors	CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL)	0
22534069	22516818	How to reset password with UserManager of ASP.NET MVC 5	UserManager<IdentityUser> userManager = \n    new UserManager<IdentityUser>(new UserStore<IdentityUser>());\n\nuserManager.RemovePassword(userId);\n\nuserManager.AddPassword(userId, newPassword);	0
1344751	1344745	How to generate all possible 3-chars strings in c#?	IEnumerable<string> GetAllStrings(params char[] inputCharacterSet) {\n    return from n in inputCharacterSet\n           from m in inputCharacterSet\n           from k in inputCharacterSet\n           select new string(new [] { n, m, k });\n}	0
24403862	24400992	How to unsubscribe from WCF service	try\n{\n    channel.Close();\n}\ncatch\n{\n    channel.Abort();\n    throw;\n}	0
19499392	19499351	Regex to remove characters and supplied words	new Regex(@"\b(this|is|grand)\b-?|[^a-z0-9-]");	0
28239203	28202567	length of the string exceeds the value set on the maxJsonLength property	[WebMethod]\n        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]\n        public void GetData(string login)\n        {\n\n            // when the amount of data return is huge\n            var serializer = new JavaScriptSerializer();\n\n            // we need to do this.\n            serializer.MaxJsonLength = Int32.MaxValue;\n\n\n            var result = serializer.Serialize(service.GetData(login));\n\n\n            Context.Response.Write(result);\n        }	0
9626734	9626000	Getting the subsite an item came from after performing spsitedataquery	query.ViewFields += "<ProjectProperty Name=\"Title\" />";	0
12371796	12371089	Outputing data from a Dictionary<string, int> to a table in Visual Studio c#	Dictionary<string, int> itemsSource = new Dictionary<string, int>() { { "Board", 1 }, { "Messages Transmitted", 75877814 }, {"ISR Count", 682900312}, {"Bus Errors", 0}, {"Data Errors", 0}};\n\n    foreach (var item in itemsSource)\n    { \n        ListViewItem listItem = new ListViewItem(item.Key);\n        listItem.SubItems.Add(item.Value.ToString());\n\n        listView1.Items.Add(listItem);\n    }	0
3507029	3506446	How to prevent cursor from "jumping" into textbox when you type	Cursor.Position = new Point( oldX, oldY );	0
31451932	31451650	Write to a text file after specified string?	Dictionary<string, string> members = new Dictionary<string, string>();\n\nString lineToFind = "testString";\n\n// Let's read the file up in order to avoid read/write conflicts\nvar data = File\n  .ReadLines(pathToFile)\n  .ToList();\n\nvar before = data\n  .TakeWhile(line => line != lineToFind)\n  .Concat(new String[] {lineToFind}); // add lineToFind\n\nvar after = data\n  .SkipWhile(line => line != lineToFind)\n  .Skip(1); // skip lineToFind\n\nvar stuff = members\n  .Select(entry => String.Format("[{0} {1}]", entry.Key, entry.Value));\n\nFile.WriteAllLines(pathToFile, before\n  .Concat(stuff)\n  .Concat(after));	0
9174244	9174131	Implementing IFormatter recursively	public class A {\n    public object SomeProperty { get; set; }\n}\nvar a = new A();\na.SomeProperty = a;	0
16688261	16688224	How to know what obsolete methods/API's are replaced with	[ObsoleteAttribute("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]	0
17332188	17331752	Get raw string from Rss20FeedFormatter for RSS/XML?	var rssFormatter = new Rss20FeedFormatter(feed, false);\nvar output = new StringBuilder();\nusing (var writer = XmlWriter.Create(output, new XmlWriterSettings { Indent = true }))\n{\n    rssFormatter.WriteTo(writer);\n    writer.Flush();\n    return output;\n}	0
31278536	31278143	How to get Gmail threadid from an Outlook Add-in (when using Google Outlook Sync)?	threads.list(userId='me', q='rfc822msgid:abc123')	0
11632756	11611555	Mongodb Array ElemMatch	Query.EQ("Keywords", "Keyword003")	0
22205397	22200648	How can I add profile preferences to Chrome for Selenium Grid 2 in C#?	var chromeOptions = new ChromeOptions();\nchromeOptions.AddUserProfilePreference("download.default_directory", DownloadPath);\nchromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");\nchromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");\n\nIWebDriver driver = new RemoteWebDriver(new Uri("http://path/to/selenium/server"), chromeOptions.ToCapabilities());	0
23439454	23439272	Passing a class value from listbox in form1 to textbox in form2	private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)\n{\n    frmProperties editProperties = new frmProperties();\n    Employee person =   (Employee)lstBoxEmployees.Items[lstBoxEmployees.SelectedIndex];\n    editProperties.TextFirstName = person.EmployeeFirstName;\n    editProperties.ShowDialog();    \n}	0
3104358	3104324	Editing a text file in place through C#	static void Main(string[] args)\n    {\n        string inputFilename = args[0];\n        int startIndex = int.Parse(args[1]);\n        string newText = args[2];\n\n        using (FileStream fs = new FileStream(inputFilename, FileMode.Open, FileAccess.Write))\n        {\n            fs.Position = startIndex;\n            byte[] newTextBytes = Encoding.ASCII.GetBytes(newText);\n            fs.Write(newTextBytes, 0, newTextBytes.Length);\n        }\n    }	0
16022557	16022233	Writing to incidents in C#	Case c = new Case();\nc.ID = id;\nc.Title = title;\nsvc.Update(c);	0
18480895	18463952	Microsoft Office Interop Excel doesn't saving in Windows server 2008	xlWorkSheet.Cells[rowNumber, 4].NumberFormat = "0.00";	0
20187894	20187737	How to use textbox lost-focus event	private void textBox1_Leave(object sender, EventArgs e)\n    {\n        //Put the value to be checked with the Database in a Variable.\n        var valueToCheck = textBox1.Text;\n\n        //Create connection with the database.\n        var sqlConn = new SqlConnection("Connection String to Database");\n\n        //Create dataset instance to fill with the return results from the Database.\n        var ds = new DataSet();\n        //Create SqlCommand to be execute on the database.\n        var cmd = new SqlCommand("SELECT * FROM TABLE WHERE 'field to be checked' = " + valueToCheck, sqlConn);\n        //Create SqlDataAdapter\n        var da = new SqlDataAdapter(cmd);\n        ds.Clear();\n        try\n        {\n            da.Fill(ds);\n        }\n        catch (Exception ex)\n        {\n        }\n\n\n        foreach (DataRow row in ds.Tables[0].Rows)\n        {\n            //do you stuff here.\n        }\n    }	0
15797552	15773417	Custom ObservableLinkedList would not bind in my Windows store app	public class ObservableLinkedList<T> : Collection<T>, INotifyPropertyChanged, INotifyCollectionChanged\n{\n    public event NotifyCollectionChangedEventHandler CollectionChanged;\n    public event PropertyChangedEventHandler PropertyChanged;\n    private LinkedList<T> _list = new LinkedList<T>();\n\n    public ObservableLinkedList()\n    {\n\n    }\n\n    public void Clear()\n    {\n        _list.Clear();\n    }\n\n    public int Count()\n    {\n        return _list.Count();\n    }\n\n    public void Add(T artist)\n    {\n        _list.AddLast(artist);\n    }\n\n    public Model.Artist Find(string p)\n    {\n        return null;\n    }\n}	0
21436727	21436400	c# ComboBox, save item with value and text	public Form1()\n    {\n        InitializeComponent();\n        comboBox1.DisplayMember="Text";\n        comboBox1.ValueMember ="Value";\n        comboBox1.Items.Add(new ComboboxItem("Dormir", 12));\n    }	0
23752788	23695968	Login submit button unable to Reach [httpost]	[HttpPost]\npublic ActionResult Login(Models.user_master model, string returnUrl = "")\n{\n\n        if (ValidateUser(model.UserID,model.Password))\n        {\n            FormsAuthentication.RedirectFromLoginPage(model.UserID,false);\n            return RedirectToAction("Index", "Login");\n        }\n        else\n        {\n            ModelState.AddModelError("", "Login details are wrong.");\n        }\n        return View(model);\n\n}	0
2669568	2110582	Loop through all cells in Xceed DataGrid for WPF?	foreach (object item in this.DataGrid1.Items)\n{\n    Dispatcher.BeginInvoke(new Action<object>(RemoveRowHighlights), DispatcherPriority.ApplicationIdle, item);\n}\n...\nprivate void RemoveRowHighlights(object item)\n{\n    Xceed.Wpf.DataGrid.DataRow row = this.DataGrid1.GetContainerFromItem(item) as Xceed.Wpf.DataGrid.DataRow;\n    if (row != null) foreach (Xceed.Wpf.DataGrid.DataCell c in row.Cells)\n    {\n        if (c != null) c.Background = row.Background;\n    }\n}	0
27643244	27643133	Trying to get the Button Value for a List View and Insert Into a Database	var button = sender as Button;\nvar text = button.Text;	0
14229796	14229744	Applying Substring in LINQ to SQL	List<DocumentDTO> lstDocs = objService.SelectDocumentInfo()\n    .Where(l => l.FileName.StartsWith(string.Concat(docID, @"\"))\n    .ToList();	0
17466720	17465889	Create a DropDownList in GridView Asp.NET	private void BindGrid()\n      {\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Test DropDown");\n\n        Control container = new Control();\n        TemplateField tf = new TemplateField();\n        string chkRole = "ddlTest";\n\n\n        tf.ItemTemplate = new CreateDropDownList(chkRole);\n        //tf.HeaderText = dt.Columns[i].ColumnName;\n        this.gvDDL.Columns.Add(tf);\n        gvDDL.DataSource = dt;\n        gvDDL.DataBind();\n    }\n\n}\npublic class CreateDropDownList:ITemplate\n {\n    string checkboxID;\n    public CreateDropDownList(string id)\n    {\n        this.checkboxID = id;\n        //\n        // TODO: Add constructor logic here\n        //\n    }\n    public void InstantiateIn(Control container)\n    {\n        DropDownList ddl = new DropDownList();\n        ddl.ID = checkboxID;\n        container.Controls.Add(ddl);\n    }\n }	0
15283463	15283414	How to the get of a path without file:\\ being at the beginning	string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);	0
24782700	24781023	Setting text on DataGridViewButtonColumn - bug?	void dataGridView1_CellFormatting(object sender, \n                                  DataGridViewCellFormattingEventArgs e) {\n  if (e.RowIndex == dataGridView1.Rows.Count - 1) {\n    if (e.ColumnIndex == 1) {  // Your Button Column\n      e.Value = "Add Row";\n    }\n  }\n}	0
11059607	11059529	How to get data from a class to the windows form when something happens in the class?	class CountArgs:EventArgs\n{\n   public int Count{get;set;} \n\n    public CountArgs(int c) { \n        Count = c; \n    }\n}\n\nclass Game\n{\n\n   public event EventHandler<CountArgs> CountChanged; // it is possible to define your own delegate here.\n   int count;\n   public int Count\n   {\n      get { return count;}\n      set { \n            if (count != value) // Only raise the event if the value changes\n            {\n                 count = value;\n                 RaiseCountChangedEvent(value);\n            }\n   }  \n   void RaiseCountChangedEvent(int c)\n   {\n      if (CountChanged != null) // Check that at least one object is listening to the event\n      {\n          CountChanged(this,new CountArgs(c));\n      }\n   }\n}	0
24635308	24635232	Random value to each single argument of array	Random rand = new Random();\n\nfor (int i = 0; i < mineArray.Length; i++)\n{           \n    mineArray[i] = rand.Next(0, 100);\n    Console.WriteLine(mineArray[i]); // you don't need to convert to string\n}	0
1658811	1658795	Adding GUI components to a precompiled application	Controls.Add	0
27727211	27727193	Inserting ListBox Items to .accdb with C#	commandEmployee.Parameters.Clear();\ncommandEmployee.Parameters.AddWithValue("@TestTable", item);	0
2718362	2718350	How to convert a string into a Point?	string[] coords = str.Split(',');\n\nPoint point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));	0
16130950	16130409	Custom print text file in richedTextBox	var writer = new StringBuilder();\n\nforeach (var line in File.ReadAllLines("mytext.txt"))\n{\n   writer.AppendLine(!line.StartsWith("<") ? string.Format("  -{0}", line) : line);\n}\n\nrichTextBox1.Text = writer.ToString();	0
24182921	24178576	Telerik reporting. VS. How to convert DateTime paremeter to ShortDateString in textbox?	var textBox = new TextBox();\ntextBox.Value = "=Format('{0:dd.mm.yyyy}', Parameters.dtFrom) - Format('{0:dd.mm.yyyy}', Parameters.dtTo)";	0
1395007	1394906	ASP .NET - Set default values of ListView InsertItemTemplate	((TextBox)myDetailsView.InsertItem.FindControl("TextBox1")).Text =\n    DateTime.Now.ToString("M/d/yyyy HH:mm");	0
30546450	30544529	Speech recognition result handler always runs a single action	if (e.Result.Text.StartsWith("google")) ;	0
15920570	15918920	"How to detect Session Timeout And Redirect To Login Page In ASP.NET "	if (Session["Username"] != null)\n     { \n           // Code here \n     }\n     else\n     {\n         Response.Redirect("login.aspx");\n     }	0
7727642	7727597	How to split the two strings using filetype.split?	string name = "C:\folder\back-201190082233.zip";\nstring filetype = name;\nstring[] getfiledate = filetype.Split(new[] {'.', '-'});\nstring datepart = getfiledate[1];	0
8817249	8816752	How to deserialzie List of KeyValuePair	public void ReadXml(XmlReader reader)\n{\n    var document = XDocument.Load(reader);\n    this._exportList = document\n        .Descendants("KeyValuePairThatSerializesProperlyOfInt32Boolean")\n        .Select(e => new KeyValuePair<int, bool>(\n            Int32.Parse(e.Element("Key").Value),\n            Boolean.Parse(e.Element("Value").Value)\n        )).ToList();\n\n}	0
6041331	6041245	WatiN RunScript fails in FireFox	browser.RunScript("window.alert('hello');");	0
15747671	15747604	do httpwebrequest but without waiting for response	BeginGetRequestStream()	0
30202594	30202547	How to terminate a recursive function and return a value	if (control.HasControls())\n{\n    var result = GetTextBoxByID(control.Controls, id);\n    if (result != null)\n        return result;\n}	0
6434860	6434813	String Search & replacement	string data = "JohnMarkMarkMark";\nstring resultOne = new Regex("Mark").Replace(data,  "Tom", 1);\nstring resultAll = data.Replace("Mark", "Tom");	0
7664041	7652365	Extraneous newline on data copied from WPF DataGrid	private RelayCommand _resultsGridCopyCommand;\n    public RelayCommand ResultsGridCopyCommand {\n        get {\n            if (_resultsGridCopyCommand == null) {\n                _resultsGridCopyCommand = new RelayCommand(this.CopyFromResultsGrid);\n            }\n\n            return _resultsGridCopyCommand;\n        }\n    }\n\n    private void CopyFromResultsGrid(object grid) {\n        var resultsGrid = (DataGrid)grid;\n        ApplicationCommands.Copy.Execute(null, resultsGrid);\n\n        var oldData = Clipboard.GetDataObject();\n        var newData = new DataObject();\n\n        foreach (var format in oldData.GetFormats()) {\n            if (format.Equals("UnicodeText") || format.Equals("Text")) {\n                newData.SetData(format, Regex.Replace(((String)oldData.GetData(format)), "\r\n$", ""));\n            } else {\n                newData.SetData(format, oldData.GetData(format));\n            }\n        }\n\n        Clipboard.SetDataObject(newData);\n    }	0
11264871	11243752	Check what field was clicked in MS Word	public static IEnumerable<Field> GetAllFieldsInSelection(this Selection selection)\n    {\n        foreach (Field f in selection.Document.Fields)\n        {\n            int fieldStart = f.Code.FormattedText.Start;\n            int fieldEnd = f.Code.FormattedText.End + f.Result.Text.Count();//field code + displayed text lenght\n\n            if (!((fieldStart < selection.Start) & (fieldEnd < selection.Start) |\n                  (fieldStart > selection.End) & (fieldEnd > selection.End)))\n            {\n                yield return f;\n            }\n        }\n    }	0
20007432	20006864	How to serialize object's property to XML element's attribute?	[Serializable]\npublic class ProgramInfo\n{\n    [XmlAttribute]\n    public string Name { get; set; }\n\n    [XmlIgnore]\n    public Version Version { get; set; }\n\n    [XmlAttribute("Version")\n    public string VersionString \n    { \n      get { return this.Version.ToString(); } \n      set{ this.Version = Parse(value);}\n    }\n}	0
2538924	2538263	how to use a tree data structure in C#	NTree<tTable> tree = new NTree<tTable>(table);\n\nstring nameToMatch = "SomeName";\nLinkedList<tTable> matches = new LinkedList<tTable>();\n\ntree.Traverse(tree, data => {\n  if (data.Name == nameToMatch) {\n    matches.AddLast(data);\n  }\n});	0
1733987	1733980	Bring window to foreground after Mutex fails	[DllImport("user32.dll")] private static extern \n              int EnumWindows(EnumWindowsProc ewp, int lParam); \n\npublic delegate bool EnumWindowsProc(int hWnd, int lParam);\n\npublic void EnumerateAllWindows()\n{\n   EnumWindowsProc ewp = new EnumWindowsProc(EvalWindow);\n   EnumWindows(ewp, 0);\n }\n\nprivate bool EvalWindow(int hWnd, int lParam)\n{\n    //this will be called for each window..         \n    // use GetWindowThreadProcessId to get the PID for each window\n    // and use Process.GetProcessById to get the PID you are looking for\n    // then bring it to foregroun using of these calls below:\n\n}\n\n    [DllImport("user32.dll")]\n    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n    [DllImport("user32.dll")]\n    public static extern bool BringWindowToTop(IntPtr hWnd);\n\n    DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd	0
12872449	12872171	Option for VB.Net in Visual Studio to directly jump to variable's datatype after new operator in intellisense list missing	Dim d As New ...	0
19508865	19508832	How do I add my PC's current date and time into SQL Server Database column?	using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y, dt) VALUES(@x, @y, @dt)", con))\n{\n    cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));\n    cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));\n    cmd.Parameters.Add(new SqlParameter("dt", DateTime.Now));\n    cmd.ExecuteNonQuery();\n}	0
11144798	11144754	C# Reverse all numbers in string?	var replacedString = \n    Regex.Replace(//finds all matches and replaces them\n    myString, //string we're working with\n    @"\d+", //the regular expression to match to do a replace\n    m => new string(m.Value.Reverse().ToArray())); //a Lambda expression which\n        //is cast to the MatchEvaluator delegate, so once the match is found, it  \n        //is replaced with the output of this method.	0
30423122	30423102	How to Browse files from folder without open it	var files = Directory.GetFiles("C:\\");\n\nforeach (var file in files)\n{\n    var fileInfo = new FileInfo(file);\n    Console.WriteLine(fileInfo.Name);\n}	0
20219952	20219754	asp.net Passing name of method as parameter to another method	public bool someDBMethod(Func<bool> callDalMethod, string message)\n{\nlogDTO ldto = new logDTO(message);\ntry\n{\n  if (callDallMethod()) //DB operation is successfull\n  {\n    Log.insertLog(ldto); //inserrt log to DB\n    return true;\n  }\n  catch (System.Data.SqlClient.SqlException ex)\n  {\n    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));\n    throw new Exception (ex.Message);\n  }\n catch (Exception ex)\n {\n    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));\n    throw new Exception (ex.Message);\n }	0
7036555	7036308	Checking for shared folder write access for current user	FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, this.GetFileServerRootPath);\n\ntry\n{\n    writePermission.Demand();\n    return true;\n}\ncatch (SecurityException s)\n{\n    return false;\n}	0
18240334	18239185	Creating controls dynamically	Button btnView = new Button();\nbtnView.ID = CarID;\nbtnView.Text = "View Car";\nbtnView.ForeColor = System.Drawing.Color.DeepSkyBlue;\nbtnView.BackColor = System.Drawing.Color.Gray;\nbtnView.BorderColor = System.Drawing.Color.Violet;\nbtnView.Style["top"] = "110px";\nbtnView.Style["left"] = "800px";\nbtnView.Style["Height"] = "20px";\nbtnView.Style["position"] = "absolute";\nbtnView.BorderStyle = BorderStyle.Outset;\nbtnView.Command += btnView_Command; // Note: Command event is used instead of Click.\nbtnView.CommandArgument = CarID; // Note: CarID is stored in CommandArgument.\nPanel1.Controls.Add(btnView);\n\nvoid btnView_Command(object sender, CommandEventArgs e)\n{\n    string carID = e.CommandArgument.ToString();\n    Session["CarID"] = carID;\n    Response.Redirect("View.aspx");\n}	0
24381566	24381405	How do i pass a string variable to another page without using Uri in Windows Phone 7?	NavigationService.Navigate(new Uri("/Home.xaml?jsonData=" + Uri.EscapeDataString(text), UriKind.Relative));	0
1535041	1535023	C# - Append Number To File Being Saved	private string GetUniqueName(string name, string folderPath)\n{\n    string validatedName = name;\n    int tries = 1;\n    while (File.Exists(folderPath + validatedName))\n    {\n        validatedName = string.Format("{0} [{1}]", name, tries++);\n    }\n    return validatedName;\n}	0
19932631	19930578	Fluent configuration for a collection and single property of same type	public SweepstakesConfiguration()\n    {\n        Property(c => c.Id).HasColumnName("SweepstakesId");\n\n        HasOptional(c => c.WinningApplicant)\n            .WithMany()\n            .HasForeignKey(c => c.WinnerId);\n    }\n\n    public SweepstakesApplicantConfiguration()\n    {\n        Property(a => a.Id).HasColumnName("SweepstakesApplicantId");\n\n        HasRequired(a => a.Sweepstakes)\n            .WithMany(s => s.Applicants)\n            .HasForeignKey(a => a.SweepstakesId)\n            .WillCascadeOnDelete();\n\n        HasRequired(a => a.Buyer)\n            .WithMany(b => b.SweepstakesApplications)\n            .HasForeignKey(a => a.BuyerId);\n\n        HasRequired(a => a.Agent)\n            .WithMany()\n            .HasForeignKey(a => a.AgentId);\n    }	0
1303530	1300196	how to create a fresh database before tests run?	var schema = new SchemaExport(config);\nschema.Drop(true, true);\nschema.Execute(true, true, false);	0
344329	344210	How to determine total size of ASP.Net cache?	Cache.EffectivePrivateBytesLimit	0
1755633	1755597	C#: Do I need to dispose a BackgroundWorker created at runtime?	ThreadPool.QueueUserWorkItem(...)	0
26303420	26303298	Get part of a URL after domain using Regex	var uri = new Uri("http://www.di.fm/calendar/event/40351#123");\nvar result = uri.PathAndQuery + uri.Fragment;	0
10898811	10898775	C# how to create a subarray or filtered array based on integers that are above a specific value?	var filteredArray = existingArray.Where(x => x > 8).ToArray();	0
23776490	23776388	When overriding a method	protected virtual void OnNavigatedTo(NavigationEventArgs e) { }	0
31043976	30999109	Identifying a message's origin on an ESB	var queueClient = QueueClient.CreateFromConnectionString(ConnectionString, path);\n                var msg = new BrokeredMessage("Message Content");\n                msg.Properties.Add("Source", "Message Source");\n                await queueClient.SendAsync(msg);	0
24936381	24927183	Get comma separated values of checked items values of CheckedListBox	StringBuilder items = new StringBuilder();\nforeach (object checkedItem in clSiparisTipi.CheckedItems)\n{\n    DataRowView dr = (DataRowView)checkedItem;\n    items.Append(dr["tanimId"]).Append(",");\n}\n\nMessageBox.Show(items.ToString().TrimEnd(','));	0
22677096	22677030	How can I reset the i variable inside my for loop?	for (var k = 0; k < 5; k++)\n   {\n        for (var j = k + 1; j < 5; j++)\n        {\n            ....\n            // if you need the complete set, you can store both\n            rating[j][k] = ...\n            rating[k][j] = ...\n        }\n   }	0
17212362	17211917	How to combine 2 lists containing csv strings and compare the result with another csv	var items = new[] { l1, l2 }\n            .SelectMany(x => x.SelectMany(y => y.Split(',')))\n            .OrderBy(y => y);\n\nvar allItems = new List<string> \n                        { "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8" };\n\nvar result = allItems.SequenceEqual(items);	0
11845787	11838605	Draw image in specific coordinate	Image<Gray,Byte> result = new Image<Gray,Byte>(source.Size);\n    CvInvoke.cvAddWeighted(source, movementFactor, overlay, 1.0-movementFactor, 0.0, result);	0
18029934	18029843	How to show the currency sign after the value in .net?	var cultureInfo = new CultureInfo("fa-Ir");\ncultureInfo.NumberFormat.CurrencyPositivePattern = 3;\ncultureInfo.NumberFormat.CurrencyNegativePattern = 3;\n\nvar result = string.Format(cultureInfo, "{0:C0}", 12000);\n\nConsole.WriteLine(result);\n//Result\n//12,000 ????	0
4626324	4626153	ANSI-encode string for saving in database	public static bool CanBeRoundTripped(Encoding encoding, string text)\n{\n    byte[] bytes = encoding.GetBytes(text);\n    string decoded = encoding.GetString(bytes);\n    return text == decoded;\n}	0
4351889	4351876	C# List of objects, how do I get the sum of a property	double total = myList.Sum(item => item.Amount);	0
13393101	13393094	LINQ - Selecting the count of rows where a column begins with "ABCD"	var resultCount = yourContext.Orders.Count(r=> r.OrderNumber.StartsWith("ABCD"));	0
7242564	7191821	GridView with DropDownList in EditItemTemplate	protected void gvClients_RowUpdating(object sender, GridViewUpdateEventArgs e)\n    {\n\n        GridViewRow row = gvClients.Rows[e.RowIndex];\n\n        if (ViewState["CitySelect"] != null)\n        {\n            e.NewValues.Remove("city");\n            string tempCity = (string)ViewState["CitySelect"];\n            e.NewValues.Add("city",tempCity);\n            row.Cells[7].Text = (string)e.NewValues["city"];\n        }\n        else\n            row.Cells[7].Text = (string)e.OldValues["city"];\n    }	0
32145142	32107241	How to reload security principal user info or a partial view	// Add to role, save changes\nawait _userManager.AddToRoleAsync(userInSession.Id, roleHaveClients.Name);\nawait _userManager.UpdateAsync(userInSession);\n// Sign out / Sing in\n_registerManager.AuthenticationManager.SignOut();\nawait __registerManager.SignInAsync(userInSession, false, false);\n// Redirect to another action\nreturn RedirectToAction("someAction","someController");	0
10387155	10387086	Retrieve value from one XAML page and use it in another	ChildWindow child = new ChildWindow();\nchild.PropertyName = this.textBox1.Text;\nchild.Show();	0
34074363	34073856	How to use join in Entity Framework to make output Json objects in levels - not the same level	var result = \n     from m in db.HALAQATI_VIEW_GetAllMosques\n     where && m.Emp_ID == id\n     select new {\n         MsqID = m.MSQ_ID,\n         MsqName = m.MSQ_Name, \n         Rings = from r in db.HALAQATI_VIEW_GetAllRings\n             where m.MSQ_ID == r.MSQ_ID\n             where m.Emp_ID == r.Emp_ID  // is this even necessary?\n             select new {\n                 r.Ring_ID,\n                 ...\n                 Students = from s in db.HALAQATI_VIEW_GetAllStudents\n                     where r.Ring_ID == s.Ring_ID\n                     select s\n             }\n     };\nreturn new { Mosques = result };	0
11820576	11820450	Is there any extension to visual studio that allows to run functions as tasks?	?Program.Test1()	0
12508213	12507935	How to pass instance method as a delegate	RetryGetWithExpression<ObjectResult<retrieveMedia_Result>>(u => u.retrieveMedia(1));\n\npublic static TValue RetryGetWithExpression<TValue>(Func<Entities, TValue> func)\n{\n    return func(entitiesContext);\n}	0
23118303	23118198	String to Textbox	public TextBox CheckBox() {   \n        var itemBoxArray = new TextBox[] { itemBox0, itemBox1, itemBox2, itemBox3, itemBox4, itemBox5, itemBox6, itemBox7,\n            itemBox8, itemBox9,itemBox10,itemBox11,itemBox12,itemBox13,itemBox14,itemBox15,};\n        return itemBoxArray.First(m => string.IsNullOrEmpty(m.Text));//or  FirstOrDefault\n    }	0
20758127	20758017	How to retrieve all users of Active Directory?	DirectoryEntry entry = new DirectoryEntry("LDAP://" + Bous.DomainName, Bous.UserName, Bous.Password);\nDirectorySearcher mySearcher = new DirectorySearcher(entry);\nmySearcher.PageSize = 1000;   // <--- Important!\nmySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");\n\nforeach (SearchResult result in mySearcher.FindAll())\n{\n     dr = dt.NewRow();\n     ResultPropertyCollection myResultPropColl = result.Properties;\n     dr[0] = myResultPropColl["samaccountname"][0].ToString() + "@" + Bous.DomainName;\n     dt.Rows.Add(dr);\n}	0
25252806	25185121	Generic Vector class inheriting from non generic LineSegmentClass	public class Load:Vector\n{\n\n    private ForceUnit _magnitude;\n\n    public ForceUnit Magnitude\n    {\n        get\n        {\n                return this._magnitude;          \n        }\n    }\n\n\n\n    public PointLoad(ForceUnit magnitudeOfLoad, Vector directionVector)\n        : base(...)\n    {\n        _magnitude = magnitudeOfLoad;\n    }\n\n}	0
12610929	12583208	Custom Workflow Step - Retrieve Field From Entity	QueryExpression query = new QueryExpression("supplier");\n    query.ColumnSet = new ColumnSet("sendsalesrequest", "noreply", "nofollowupreply");\n\n    EntityCollection entities = service.RetrieveMultiple(query);\n    entities.Entities.ToList().ForEach(entity => \n        {\n            if(entity["sendsalesrequest"] == "Yes")\n            {\n                StartWorkflow(entity.Id, "Send Initial E Mail Workflow Name");\n            }\n            //etc\n        }	0
20558578	20558499	How to get array data from one Click Method to another one	int[] Zahlenarray;\npublic void Button_Anzeigen_Click(Object sender, EventArgs e)\n    {            \n        label1.Text = "";            \n        Zahlenarray = new int[Int32.Parse(textBox1.Text)];\n        ...\n    }	0
1817298	1817268	How can I determine programmatically whether on multi-core, hyperthreading or multi-processor?	Win32_ComputerSystem.NumberOfProcessors returns physical count\n\nWin32_ComputerSystem.NumberOfLogicalProcessors returns logical count	0
2685797	2685651	How to detect the vertical scrollbar in a DataGridView control	using System;\nusing System.Windows.Forms;\n\nclass MyDgv : DataGridView {\n    public event EventHandler ScrollbarVisibleChanged;\n    public MyDgv() {\n        this.VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged);\n    }\n    public bool VerticalScrollbarVisible {\n        get { return VerticalScrollBar.Visible; }\n    }\n    private void VerticalScrollBar_VisibleChanged(object sender, EventArgs e) {\n        EventHandler handler = ScrollbarVisibleChanged;\n        if (handler != null) handler(this, e);\n    } \n}	0
19851795	19851770	How do I change the page size for a WkHtmlToXSharp PDF to letter?	MultiplexingConverter mc = new MultiplexingConverter();\n    mc.GlobalSettings.Dpi = 300;\n    mc.GlobalSettings.Size.PageSize = PdfPageSize.Letter;\n    PdfMarginSettings pms = new PdfMarginSettings();\n    string halfInch = ".5in";\n    mc.GlobalSettings.Margin.Bottom = halfInch;\n    mc.GlobalSettings.Margin.Left = halfInch;\n    mc.GlobalSettings.Margin.Right = halfInch;\n    mc.GlobalSettings.Margin.Top = halfInch;	0
3606321	3606301	C# 4.0 - How to Handle Optional String Parameters	const int Zero = 0;\n\nvoid SomeMethod(int optional = Zero) { }	0
31264627	31261216	How to get even columns from table in dataset through while loop without using IEnumerator	string[] columnNames = (from dc in table.Columns.Cast<DataColumn>()\n                        select dc.ColumnName).ToArray();\n\n\ndo\n    {\n       if (i%2==0)\n           //do something here\n        i++;\n    } while (i < columnNames.Length);	0
10455291	10451199	getting URLs from PDF using PDFNet	Page page = doc.GetPage(1);\nfor (int i = 1; j < page.GetNumAnnots(); j++) {\n    Annot annot = page.GetAnnot(i);\n    if (!annot.IsValid())\n        continue;\n    var sdf = annot.GetSDFObj();\n    string uri = ParseURI(sdf);\n    Console.WriteLine(uri);\n}\n\n\nprivate string ParseURI(pdftron.SDF.Obj obj) {\n    try {\n        if (obj.IsDict()) {\n            var aDictionary = obj.Find("A").Value();\n            var uri = aDictionary.Find("URI").Value();\n            return uri.GetAsPDFText();\n        }\n    } catch (Exception ) {\n        return null;\n    }\n    return null;\n}	0
14501200	14499778	Best way to store an AES-encrypted byte and IV to an XML?	byte[] ciphertext = iv + Encrypt(key, m);\nbyte[] ciphertextWithMAC = ciphertext + HMAC(key, ciphertext)\nstring encodedCiphertext = Base64Encode(cipherText)	0
29699970	29699549	WPF - Metro Dialog Settings (mahapps) on the top of the screen?	try\n{\n     var mySettings = new MetroDialogSettings\n     {\n         AffirmativeButtonText = "Yes"\n     };\n\n     var cd = new CustomDialog\n     {\n         VerticalAlignment = VerticalAlignment.Top,\n         VerticalContentAlignment = VerticalAlignment.Top\n     };\n\n     await DialogManager.ShowMetroDialogAsync(this, cd, mySettings);\n}\ncatch (Exception ex)\n{\n}	0
30804404	30804003	How can i add to the timer control a propert to display only hours minutes seconds without milliseconds?	ShowWhatIWant(true, false, false);\n\nprivate string ShowWhatIWant(bool showMinutes, bool showSeconds, bool showMiliSeconds)\n{\n    string text = string.Format("{0:00}", Math.Floor(elapsed.TotalHours));\n\n    if(showMinutes)\n    {\n        text += string.Format(":{0:00}", elapsed.Minutes);\n    }\n\n    if(showSeconds)\n    {\n        text += string.Format(":{0:00}", elapsed.Seconds);\n    }\n\n    if(showMiliSeconds)\n    {\n        text += string.Format(":{0:00}", elapsed.Milliseconds);\n    }\n\n    return text;\n}	0
4348267	4348136	Serialize array of objects as one object with a named property for each object in C# with JSON serializer	var dict = list.ToDictionary(\n    item => "item" + item.id);	0
15927997	15927085	How to delete one row in GridView with DropDownList in ASP.NET	gvYourGrid.DeleteRow(index);	0
21712961	21712891	Returning multiple fields with LINQ GroupBy on a datatable	var query = ds.Tables[0].AsEnumerable()\n            .GroupBy(r => new\n            {\n                state = r.Field<string>("state"),\n                name = r.Field<string>("name"),\n            })\n            .Select(grp => new\n            {\n                name = grp.Key.name,\n                state = grp.Key.state,\n                Count = grp.Count()\n            })\n            .OrderBy(o => o.state)\n            .ToList();	0
16983197	16982970	Multiple controls with the same ID	*[id*="_MyButtonID"].red {\n    background-color: red;\n}	0
22243362	22243290	Show remain of free host space in asp.net	long totoalSpace = long.MaxValue; // as example\n        long size = 0;\n        string folderPath = @"d:/hostingpace/yourwebsite/files"; //sample path\n\n        foreach (var item in Directory.GetFiles(folderPath))\n        {\n            size += new FileInfo(item).Length;\n        }\n\n        long remainingSpace = totoalSpace - size;	0
11365306	11365258	StackPanel reverse order - WPF	stackPanel.Children.Insert(0, uiElement);	0
6360587	6360539	How to read data from other form?	TextBox.Text=settings.Property	0
5135975	5132801	Sending Mails with attachment in C#	namespace SendAttachmentMail\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var myAddress = new MailAddress("jhered@yahoo.com","James Peckham");\n            MailMessage message = new MailMessage(myAddress, myAddress);\n            message.Body = "Hello";\n            message.Attachments.Add(new Attachment(@"Test.txt"));\n            var client = new YahooMailClient();\n            client.Send(message);\n        }\n    }\n    public class YahooMailClient : SmtpClient\n    {\n        public YahooMailClient()\n            : base("smtp.mail.yahoo.com", 25)\n        {\n            Credentials = new YahooCredentials();\n        }\n    }\n    public class YahooCredentials : ICredentialsByHost\n    {\n        public NetworkCredential GetCredential(string host, int port, string authenticationType)\n        {\n            return new NetworkCredential("jhered@yahoo.com", "mypwd");\n        }\n    }\n}	0
14791339	14791242	How to chain sorters with IEnumerable, with each sorter respecting the ordering produced by the previous one?	return people.OrderBy(p => p.Name).ThenBy(p => p.Age);	0
2514238	2513968	How to focus a cell in Excel VSTO using C#? How to select first cell using C# in VSTO?	Excel.Worksheet activeSheet = ThisAddIn.ExcelApplication.ActiveSheet;\nvar range = activeSheet.get_Range("A1", "A1");\nrange.Select();	0
15224403	15223151	How does CLR match C++ file access constants with C# enums?	int fAccess;\n    ...\n    fAccess = access == FileAccess.Read? GENERIC_READ:\n    access == FileAccess.Write? GENERIC_WRITE:\n    GENERIC_READ | GENERIC_WRITE;\n    ...\n    _handle = Win32Native.SafeCreateFile(tempPath, fAccess, ...etc)	0
5170154	5168315	Insert new parent/child via WCF Data Services	context.AddToContact(contact);\ncacheAddressList.ForEach(a => \n    {\n        address.Contact = contact;\n        context.SetLink(address, "Contact", contact);\n    });\n\ncontext.SaveChanges(SaveChangesOptions.Batch);	0
25854971	25854887	copy like columns from one table to another and text from textbox	INSERT INTO table2 (A,B,C,D,E,Statement)\n    select (A,B,C,D,E, @Statement)\n    from table1	0
9918611	9918569	Issue with column sizes using TableLayoutPanel	tlp.RowCount = 3;\ntlp.ColumnCount = 2;	0
4677235	4677125	WPF : Disable Undo in an editable ComboBox	public Window1()\n{\n    this.InitializeComponent();\n\n    comboBox1.Loaded += new RoutedEventHandler(comboBox1_Loaded);\n}\n\nvoid comboBox1_Loaded(object sender, RoutedEventArgs e)\n{\n    var textBox = comboBox1.Template.FindName("PART_EditableTextBox", comboBox1) as TextBox;\n}	0
962868	962557	Retrieving items from --- DataGridViewComboBoxColumn	private Dictionary<int, ComboBox> comboBoxes;\n    public Form1()\n    {\n        InitializeComponent();\n        this.comboBoxes = new Dictionary<int, ComboBox>();\n        this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);\n    }\n\n    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        var cb = e.Control as ComboBox;\n        if (!(this.comboBoxes.ContainsKey(this.dataGridView1.CurrentRow.Index)))\n        {\n            this.comboBoxes.Add(this.dataGridView1.CurrentRow.Index, cb);\n        }\n    }	0
3220760	3218208	Entity Framework v4 Code-Only Connection String	var builder = new ContextBuilder<YourContext>();\n\nusing (YourContext context = builder.Create(new SqlConnection(ConfigurationManager.ConnectionStrings["yourConenctionKeyInWebConfig"].ConnectionString)))\n{\n     ...\n}	0
14864097	14863970	I'm trying to simplify with linq a statement that takes 2 lists of numbers and subtracts the first one from the second one	return _mainPower.Zip(_referencePower,(v1, v2) => v1-v2)	0
611104	611074	LINQ joining two tables	var itemColl = from p in db.A\n               where p.CardID == "some GUID"\n               select new {\n                   p.CardID,\n                   p.secondCol,\n                   p.ThirdCol,\n                   Items = db.B.Where(b=>b.CardID==p.CardID)\n                      //.Select(b=>b.ItemNo) [see comments]\n               }	0
26346456	26346037	Invalid attempt to read data when no data is present when getting all values from a row in a SQL Server table	if (reader.HasRows)\n{\n     while (reader.Read())\n     {\n          // Read all column data from row here, one row at a time\n     }\n}	0
22198268	22197448	Mapping between child and root aggregate	public class SubscriberContext : DbContext\n{\n    public DbSet<Subscriber> Subscribers { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        //modelBuilder.Entity<Subscriber>().HasRequired(x => x.Address).WithRequiredPrincipal(x => x.Subscriber);\n        modelBuilder.Entity<Subscriber>().HasOptional(x => x.Address).WithRequired(x => x.Subscriber);\n        modelBuilder.Entity<SubscriberAddress>().Property(x => x.Id).HasColumnName("SubscriberId");\n        base.OnModelCreating(modelBuilder);\n    }\n}\n\npublic class Subscriber\n{\n    public Guid Id { get; set; }\n    public virtual SubscriberAddress Address { get; set; }\n}\n\npublic class SubscriberAddress\n{\n    public Guid Id { get; set; }\n    public virtual Subscriber Subscriber { get; set; }\n}	0
8633032	8632974	C# equivalent of fread	reader.ReadInt32	0
8504226	8503814	custom xml serialization with attributes	public class Mail : IXmlSerializable\n{\n    public string Subject;\n\n    public System.Xml.Schema.XmlSchema GetSchema()\n    {\n        return null;\n    }\n\n    public void ReadXml(System.Xml.XmlReader reader)\n    {\n        bool isEmpty = reader.IsEmptyElement;\n\n        reader.ReadStartElement();  \n        if (isEmpty) return;\n\n        isEmpty = reader.IsEmptyElement;\n        reader.ReadStartElement();\n        if (isEmpty)\n        {\n            reader.ReadEndElement();\n            return;\n        }\n\n        Subject = reader.ReadString();\n\n        reader.ReadEndElement();\n        reader.ReadEndElement();\n    }\n\n    public void WriteXml(System.Xml.XmlWriter writer)\n    {\n        writer.WriteStartElement("MailSubject");\n        writer.WriteElementString("Subject", Subject);\n        writer.WriteEndElement();\n    }\n}	0
23218725	23218674	ORM which can insert entity into more than one table	using (var db = new TestContext()){\n  db.Managers.Add(new Manager { Name = "a", ... });\n  db.SaveChanges();\n}	0
4945981	4945794	.NET implementation of the active object pattern	System.Threading.Tasks.Task	0
6751486	6745628	Exchange Managed API: How do I search all appointments that have been created since a defined date?	var items = service.FindItems(WellKnownFolderName.Calendar, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeCreated, DateTime.Today), new ItemView(100));	0
21615182	21614141	how to iterate through a folder writing each folder name into a string array	var path = @"C:\\Katas"; \n\n        var folders = Directory.GetDirectories(path);  //Your string array of folders\n\n        var files = new List<string>();\n\n        foreach (String s in folders)\n        {\n            var fileList = Directory.GetFiles(s).ToList();\n\n            files.AddRange(fileList);\n\n        }\n\n        files.ToArray();   //Your string array of files	0
32433116	32432281	Find the longest repetition character in String	string text = "hello dear";\nstring longestRun = new string(text.Select((c, index) => text.Substring(index).TakeWhile(e => e == c))\n                                   .OrderByDescending(e => e.Count())\n                                   .First().ToArray());\n\nConsole.WriteLine(longestRun); // ll	0
2684877	2682392	UDDI - find service which name matches exactly name specified in request	findService.FindQualifiers = FindQualifier.ExactNameMatch;	0
27893316	27893207	How to redefine a class in c#	namespace DLLNamespace\n{\n    public struct TestStruct\n    {\n        public string Name { get; set; }\n        public void SetName(string name) { this.Name = name; }\n    }\n}\n\nnamespace ProgramNamespace\n{\n    public static class ExtensionMethods\n    {\n        public static void ReverseName(this DLLNamespace.TestStruct target)\n        {\n            target.Name = new string(target.Name.ToArray().Reverse().ToArray());\n        }\n    }\n\n    public class Program\n    {\n        static void Main(string[] args)\n        {\n            DLLNamespace.TestStruct ts;\n            ts.SetName("John");\n            ts.ReverseName();\n            Console.WriteLine(ts.Name);\n        }\n    }\n}	0
12627289	12626903	accessing dynamically created control variables from event handler c#	// create combobox for row N...\nComboBox cmbBuilding = new ComboBox();\nComboBox cmbRooms = new ComboBox();\n\n// store rooms combobox in building combobox\ncmbBuilding.Tag = cmbRooms;\n\n// ...\n\nprivate void comboBox_SelectedIndexChanged(object sender, EventArgs e)\n{\n  ComboBox comboBox = sender as ComboBox;\n\n  // get the room combobox\n  ComboBox cmbRooms = comboBox.Tag as ComboBox;\n\n  if (comboBox.SelectedItem.Equals("ATLC"))\n  {\n    foreach (int x in row.ATLC)\n    {\n      cmbRooms.Items.Add(x);\n    }\n  }	0
3273553	3273536	How to customize serialization of List<string> in C#	public class FinalConcentrations {\n    private readonly List<string> items = new List<string>();\n    [XmlElement("FinalConcentration")]\n    public List<string> Items {get {return items;}}\n}	0
22617124	22616717	MouseDown event moves cursor to upper left of control	public partial class UserControl2 : UserControl\n{\n    bool _pinned;\n    Point _offset;\n\n    public UserControl2()\n    {\n        InitializeComponent();\n    }\n\n    private void B2_OnMouseDown(object sender, MouseButtonEventArgs e)\n    {\n        var control = (UIElement)sender;\n        control.CaptureMouse();\n\n        _offset = e.GetPosition(control);\n        _pinned = true;\n    }\n\n    private void ui2_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (!_pinned)\n            return;\n\n        var control = (FrameworkElement)sender;\n        var parent = (FrameworkElement)control.Parent;\n\n        Canvas.SetLeft(control, e.GetPosition(parent).X - _offset.X);\n        Canvas.SetTop(control, e.GetPosition(parent).Y - _offset.Y);\n        e.Handled = true;\n    }\n\n    private void B2_OnMouseUp(object sender, MouseButtonEventArgs e)\n    {\n        _pinned = false;\n        var control = (UIElement)sender;\n        control.ReleaseMouseCapture();\n        e.Handled = true;\n    }\n}	0
11298095	11298079	what to do with long queries with parameters in .net web apps	...\ncmd.CommandText = "sprocname";\ncmd.CommandType = CommandType.StoredProcedure\n...	0
8736120	8736004	Custom Control & Toolbox Tab	[ProvideToolboxControl("General", false)]\npublic partial class Counter : UserControl	0
18784255	18783278	How to access row data from a MouseLeftButtonDown event on a textblock, in a gridview	private void TextBlock_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)\n    {\n        TextBlock textBlock = (sender as TextBlock);\n        string text = textBlock.Text;// Text in the TextBlock\n        object datacontext = textBlock.DataContext; // datacontext, Entire row info\n    }	0
24053617	24053184	Read two columns from Excel book to Dictionary<ID,string>?	using System.Data.OleDb;\n\n    static void Main()\n    {\n        string excl_connection_string = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\CountryCode.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""";\n\n        string sql = "SELECT * FROM [Country$]";\n\n        OleDbConnection con = new OleDbConnection(excl_connection_string);\n        OleDbCommand cmd = new OleDbCommand(sql, con);\n\n        try\n        {\n            con.Open();\n            OleDbDataReader reader = cmd.ExecuteReader();\n            while (reader.Read())\n            {\n                Console.WriteLine("Country Code = {0}, Name= {1}", reader.GetString(0), reader.GetString(1));\n            }\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }\n        finally\n        {\n            con.Dispose();\n        }\n    }	0
1817360	1817333	How do I rename a folder/directory in C#?	Directory.Move(@"C:\Temp\Dir1", @"C:\Temp\dir1_temp");\nDirectory.Move(@"C:\Temp\dir1_temp", @"C:\Temp\dir1");	0
28146060	28145647	folder picker crash in windows 8.1 app	FolderPicker openFP = new FolderPicker();\nopenFP.ViewMode = PickerViewMode.Thumbnail;\nopenFP.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\nopenFP.FileTypeFilter.Add(".jpeg");\nopenFP.FileTypeFilter.Add(".gif");\nopenFP.FileTypeFilter.Add(".png");\nStorageFolder SF = await openFP.PickSingleFolderAsync();    StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", SF);\nthis.Frame.Navigate(typeof(MainPage), SF.Name);	0
13883906	13478554	Explicitly retrieving contents of XML element as string	public class StoryImage\n{\n    [XmlElement("img")]\n    public Image Img { get; set; }\n}\n\npublic class Image\n{\n    [XmlAttribute("src")]\n    public string Source { get; set; }\n}\n\n[Serializable]\n[XmlRoot("entry", Namespace = "http://www.w3.org/2005/Atom")]\npublic class NewsItem\n{\n    [XmlElement("fullstoryimage")]\n    public StoryImage FullStoryImage { get; set; }\n}	0
18387177	18386146	Set focus to texbox in repeater	protected void rptExclPBSA_ItemCommand(object source, RepeaterCommandEventArgs e)\n{\n  TextBox tbExclBox = (TextBox)rptExclPBSA.Controls[0].Controls[0].FindControl("tbExclBox");\n  do_whatever()\n\n  tbExclBox = (TextBox)rptExclPBSA.Controls[0].Controls[0].FindControl("tbExclBox");\n  tbExclBox.Focus();\n}	0
3785131	3785087	How to insert a new item in a listbox and then setfocus on the listbox new item on a button click event in C#	listBox1.Items.Add("");\nlistBox1.SelectedIndex = listBox1.Items.Count - 1;	0
12330077	12329894	Retrieve Id from ResponseUri in c#	string iduri = System.Web.HttpUtility.ParseQueryString(res.ResponseUri.Query).Get("id");	0
22429817	22429622	Is there a way to trim a Dictionary's capacity once it is known to be fixed size?	void Resize()	0
13972632	13972621	check whether the list contains item greater than a value in C#	bool contains = yourList.Any(z => z.YouProperty > yourValue);	0
8828323	8828276	How can I get an instantiated generic's parameter type?	var myList = new List<String>();\nvar shouldBeString = myList.GetType().GetGenericArguments().FirstOrNull();\nvar shouldBeGenericList = myList.GetType().GetGenericTypeDefinition();	0
7367400	7367216	How to read variant type in Visual C# 2010 from COM object (VB)	object objIDs = objFaxDocument.ConnectedSubmit(objFaxServer);\nstring[] IDs = (string[])objID;	0
15787087	15787048	C# Naming Suggestion needed	this.variable = variable;	0
3705684	3705648	How to bind one control to another?	cbo.DataBindings.Add("Enabled", chk, "Checked");	0
21263588	21262118	How to change soap:address location on a C# web-service accessed via Apigee	wsdl = context.getVariable("message.content");\nwsdl = wsdl.replace("api.mydomain.com", "new-server.com", "g");\n\ncontext.setVariable("message.content", wsdl);	0
10657312	10657188	set combobox text from textbox	foreach (string item in ddlReferring.Items)\n{\n    if (item.StartsWith(firstStart))\n    {\n        ddlReferring.SelectedText = item;\n        break;\n    }\n}	0
1777234	1777203	C#: Writing a CookieContainer to Disk and Loading Back In For Use	var formatter = new SoapFormatter();\nstring file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "cookies.dat"); \n\nusing (Stream s = File.Create (file))\n    formatter.Serialize(s, cookies);                            \n...\nCookieContainer retrievedCookies = null;\nusing (Stream s = File.OpenRead (file))\n    retrievedCookies = (CookieContainer) formatter.Deserialize(s);	0
12745668	12745502	How to write data to XML in C#	XmlDocument xDoc = new XmlDocument(); \nxDoc.Load("XMLFile.xml")");  \nXmlNodeList nodeList; \nnodeList = xDoc.DocumentElement.SelectNodes("Bathing");\n\nforeach (XmlNode node in nodeList)\n\n{\n\nXmlNode child = node.SelectSingleNode("Id");\n\nchild.InnerText = "NewValue";\n\n..write for other child nodes...\n\n}	0
17963678	17963286	run application in system tray and set hotkey for copy in clipboard	System.Windows.Forms.Clipboard.SetText("Hello, clipboard");	0
15877437	15876406	Display the lastest entry from Detail Table- using Linq to entities	//In this query i am grouping the record by ServerID and Selecting ServerID+ Max(Ram_ID )\n\n     using (DB_Entities db = new DB_Entities())\n     {\n        var lstRamList = (from usgRam in DB.UsageRAMs \n           group usgRam  by new { usgRam.ServerID} \n           into grp\n           select\n           new\n           {\n           TMP_ID_ServerID = grp.Key.ServerID,\n           TMP_MAX_RAM_ID= grp.Max(x => x.Ram_ID)}); \n\n\n //in this lower list we save all the record from the Db.UsageRAMs where k.ServerID(from above list) == d.ServerID(from Your DB Context) && k.TMP_MAX_RAM_ID == d.Ram_ID\n    var lstRAMListFinal = from d in db.UsageRAMs\n    where lstRamList.Any(k =>\n                        k.TMP_ID_ServerID== d.ServerID  &&\n                        k.TMP_MAX_RAM_ID == d.Ram_ID)\n   select d;\n}	0
27491500	27490323	Retry Entity Framwork DbContext.SaveChanges after double inserting a key	using (var context = new BloggingContext()) \n{ \n    var blog = context.Blogs.Find(1); \n    blog.Name = "The New ADO.NET Blog"; \n\n    bool saveFailed; \n    do \n    { \n        saveFailed = false; \n\n        try \n        { \n            context.SaveChanges(); \n        } \n        catch (DbUpdateConcurrencyException ex) \n        { \n            saveFailed = true; \n\n            // Update the values of the entity that \n            //failed to save from the store \n            ex.Entries.Single().Reload(); \n        } \n\n    } while (saveFailed); \n}	0
734756	734715	pass a reference to 'this' in the constructor	this.parent = parent;	0
1904663	1904617	regex for removing curly brackets with nested curly brackets	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string s = "This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result";\n\n        Regex regex = new Regex("{{({?}?[^{}])*}}");\n        int length;\n        do\n        {\n            length = s.Length;\n            s = regex.Replace(s, "");\n        } while (s.Length != length);\n\n        Console.WriteLine(s);\n     }\n}	0
30649316	30648222	How to pass a URL as a query string parameter in MVC	[Route("api/[controller]")]\npublic class UrlController : Controller\n{\n    [HttpGet("{*longUrl}")]\n    public string ShortUrl(string longUrl)\n    {\n        var test = longUrl + Request.QueryString;\n\n        return JsonConvert.SerializeObject(GetUrlToken(test));\n    }	0
12680700	12680640	How to read from a file a number which has 1 or 2 characters length	string lines = File.ReadAllText(ls.FileName);\nstring[] words = lines.Split(new[] {' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);\nstring result = String.Join(" ", words.Where(w => w.Length < 3));\n\n// result == "32 40 1" given above input	0
18828483	18763843	Ninject v2+ injection dependent on parametername	Bind<ISomething >().To<LeftSomething>().When(a => a.Target.Name == "left");	0
25213568	25213522	How to get a datatype of class by name?	Type test = typeof(InputData).GetProperties().Where(prop => prop.Name == item).ElementAt(0).PropertyType;	0
32956047	32955024	Get one image from each album using linq expression	var results = images.GroupBy(i => i.AlbumId).Select(albumGroup => new { AlbumId = albumGroup.Key, Image = albumGroup.First() })	0
27467990	27452158	How to make a slightly modified AutoResetEvent class?	public sealed class Signaller\n{\n    public void PulseAll()\n    {\n        lock (_lock)\n        {\n            Monitor.PulseAll(_lock);\n        }\n    }\n\n    public bool Wait(TimeSpan maxWaitTime)\n    {\n        lock (_lock)\n        {\n            return Monitor.Wait(_lock, maxWaitTime);\n        }\n    }\n\n    private readonly object _lock = new object();\n}	0
30967948	30967867	Sort 2 Arrays in Reverse in C#	public void Print()\n    {\n        Array.Sort(nScore, nPlayer);\n        Array.Reverse(nScore);\n        Array.Reverse(nPlayer);\n        PrintKeysAndValues(nPlayer, nScore);\n    }	0
18224129	18215243	How to get the MediaPlayer Queue	MediaPlayer.Queue[n]	0
20104357	20102328	Excel returns dates instead of computed value	OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + @";Extended Properties=""Excel 12.0;HDR=NO;IMEX=1""");	0
19000700	19000597	c# combobox displaying arraylist items	public void PopulateActors()\n{\n    cboActor.Items.Clear(); \n    cboActor.Items.AddRange(ActorArrayList.Cast<string>());\n}	0
5806708	5806510	Finding the Changeset in Entity Framework	public void UpdateTrackedEntity<T>(T modifiedEntity) where T : class\n{\n    var set = CreateObjectSet<T>();\n    set.ApplyCurrentValues(modifiedEntity);\n    var entry = ObjectStateManager.GetObjectStateEntry(modifiedEntity);\n    // entry has two collections: CurrentValues (those you applied) and \n    // OriginalValues (those loaded from DB)\n    // It also have method GetModifiedProperties to get collection of modified \n    // property names.\n}	0
10618474	10618351	Finding an index in an ObservableCollection	var x = _collection[(_collection.IndexOf(ProcessItem) + 1)];	0
9969332	9969235	Databinding to type double - decimal mark lost	binding.ConverterCulture=Globalization.CultureInfo.NeutralCulture	0
32553566	32552944	How to make this base class work with Entity Framework 6.1 code first	public class MyDbContext : DbContext\n    {\n        DbSet<User> Users { get; set; }\n\n        protected override void OnModelCreating(DbModelBuilder modelBuilder)\n        {\n            modelBuilder.Entity<User>()\n                .HasRequired<User>(x => x.CreatedBy)\n                .WithMany();\n\n            modelBuilder.Entity<User>()\n                .HasRequired<User>(x => x.ModifiedBy)\n                .WithMany();\n        }\n    }	0
14491490	14491144	How can I make an animated button?	State List	0
16254369	16254298	I have multiple text blocks that will be filled with numbers. I need them to totaled up together and then put into another text block	textBlock1.OnTextChanged += textChanged();\n    textBlock2.OnTextChanged += textChanged();\n    ...\n    textBlock9.OnTextChanged += textChanged();\n\n    public void textChanged(object sender, EventArgs e){\n        int result = Convert.ToInt32(textBlock1.Text) + ... + Convert.ToInt32(textBlock9.Text);\n        finalTextBlock.Text = result.ToString();\n    }	0
27697150	27695375	Dynamically set asp:TableRow positions based on dropdown selection	[object id].Attributes.Add("style", "someCssClass;");	0
8058014	8057814	How check if letters are in string?	public static bool CanBeMadeFrom(string word, string letters)\n    {\n        foreach (var i in word.Select(c => letters.IndexOf(c, 0)))\n        {\n            if (i == -1) return false;\n            letters = letters.Remove(i, 1);\n        }\n        return true;\n    }	0
9341737	9341677	send fax with C# and FAXCOMLIb	faxDoc.Send()	0
19243210	19243106	How to copy some fields of a List To some fields of another List without a foreach loop?	targetlist.AddRange(sourceList.ConvertAll(x => new targetItem(){prop1 = x.prop1, prop2 = x.prop2}));	0
8856084	8855494	How do I parse a JSON object in C# when I don't know the key in advance?	var o = JObject.Parse(yourJsonString);\n\nforeach (JToken child in o.Children())\n{\n    foreach (JToken grandChild in child)\n    {\n        foreach (JToken grandGrandChild in grandChild)\n        {\n            var property = grandGrandChild as JProperty;\n\n            if (property != null)\n            {\n                Console.WriteLine(property.Name + ":" + property.Value);\n            }\n        }\n    }\n}	0
26175861	26175258	Decode Large base64 text string in C#	var data = new byte[10000000];\n    var watch = Stopwatch.StartNew();\n    string s = Convert.ToBase64String(data);\n    watch.Stop();\n    Console.WriteLine(watch.ElapsedMilliseconds);\n    watch.Reset();\n    watch.Start();\n    byte[] b = Convert.FromBase64String(s);\n    watch.Stop();\n    Console.WriteLine(watch.ElapsedMilliseconds);	0
13389546	13389467	How to to shrink(scale) an entire graphics structure?	using (Graphics GR = Graphics.FromImage(BM))\n {\n     // ....\n\n     GR.ScaleTransform(.6F, .6F);\n     GR.DrawRectangle(PenTest, new Rectangle(0,0,500,500));\n\n\n }	0
33339879	33334344	Get Value for selected Item in ListPicker Windows Phone 8.1 Silverlight	var content = ((ListPickerItem)CursoLista.SelectedItem).Content;	0
29647225	29646239	How to start a process from within another process that isn't a child process?	ProcessStartInfo processInfo;\n\n            processInfo = new ProcessStartInfo("explorer.exe", Constants.ApplicationUndertestPath);\n            processInfo.UseShellExecute = false;\n            processInfo.RedirectStandardError = false;\n            processInfo.RedirectStandardOutput = false;\n\n            Process.Start(processInfo);	0
3477679	3477615	How to retrieve the name of the attribute dynamically without specifying the name of the attribute ?	// ...\nselect new\n{\n    SlotName = SLT.Attributes().First().Name,\n    SlotValue = SLT.Attributes().First().Value\n};	0
1369586	1367967	log4net log all unhandled application errors	public class MvcApplication : System.Web.HttpApplication\n    {\n\n        private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));\n\n        void Application_Error(Object sender, EventArgs e)\n        {\n            Exception ex = Server.GetLastError().GetBaseException();\n\n            log.Error("App_Error", ex);\n        }\n\n\n        public static void RegisterRoutes(RouteCollection routes)\n        {\n            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n            routes.MapRoute(\n                "Default",\n                "{controller}/{action}/{id}",\n                new { controller = "Home", action = "Index", id = "" }\n            );\n\n        }\n\n        protected void Application_Start()\n        {\n            RegisterRoutes(RouteTable.Routes);\n            log4net.Config.XmlConfigurator.Configure();\n\n        }\n\n    }	0
11483079	11474205	how to print .htm files in c#?	Hashtable values = new Hashtable();\n\n            values.Add("margin_left", "0.1");\n            values.Add("margin_right", "0.1");\n            values.Add("margin_top", "0.1");\n            values.Add("margin_bottom", "0.1");\n            values.Add("Print_Background", "yes");\n\n            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true))\n            {\n                if (key == null)\n                    return;\n\n                foreach (DictionaryEntry item in values)\n                {\n                    string value = (string)key.GetValue(item.Key.ToString());\n\n                    if (value != item.Value.ToString())\n                    {\n                        key.SetValue(item.Key.ToString(), item.Value);\n                    }\n                }\n            }	0
5161537	5161459	How to add a value to a dictionary using reflection in c#?	MyObject obj = new MyObject();\nPrivateObject privateAccessor = new PrivateObject(obj);\nDictionary<string, double> dict = privateAccessor.GetFieldOrProperty("averages") as Dictionary<string, double>;	0
17685791	17685253	Reuse Previous Serialization in File with System.Xml.Serialization	XmlReader/XmlWriter	0
15914536	15914513	Finding matching list item index number c#	int pos = arrayLanguages.IndexOf("EN");	0
10543582	10543560	Find the control that an Attached Property is attached to in the OnChange Event	e.NewValue	0
24591892	24587414	How to update a claim in ASP.NET Identity?	set\n        {\n            var AuthenticationManager = HttpContext.GetOwinContext().Authentication;\n            var Identity = new ClaimsIdentity(User.Identity);\n            Identity.RemoveClaim(Identity.FindFirst("AccountNo"));\n            Identity.AddClaim(new Claim("AccountNo", value));\n            AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant\n(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });\n\n\n        }	0
7805102	7804800	Setting security on a single file?	FileStream oFileStreamDec = new FileStream(@"C:\Decrypted_AMS.cfg", FileMode.Create, FileAccess.ReadWrite, FileShare.None);\noFileStreamDec.Write(DecryptedXML, 0, DecryptedXML.Length);\n// Close the File first\noFileStreamDec.Close();\n//Create file security and apply rules to it\nFileSecurity oFileSecurity = new FileSecurity();\noFileSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));\nSystem.IO.File.SetAccessControl(@"C:\Decrypted_AMS.cfg", oFileSecurity);	0
32195862	32195449	Conversion failed when converting nvarchar value to data type int	private void listEstimateID_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        try\n        {\n            if (isloaded)\n            {\n                SqlCommand cmd = new SqlCommand("Select distinct (stage) from tblStatus where EstimateID=@EstimateID", con);\n                cmd.Parameters.AddWithValue("EstimateID", Convert.ToInt32(listEstimateID.Text));\n                lblStage.Text = cmd.ExecuteScalar().ToString(); \n            }\n\n        }\n        catch (Exception exc)\n        {\n            MessageBox.Show(exc.Message);\n        }\n    }	0
17220212	17185817	C# webbrowser applition,how to click hyper link inside TextArea	HtmlElement textArea = webBrowser1.Document.All["textareaid"];\nif (textArea != null)\n{\n    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n    doc.Load(textArea.InnerText);\n    foreach(HtmlAgilityPack.HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n    {\n       HtmlAgilityPack.HtmlAttribute att = link["href"];\n       webBrowser1.Navigate(att.Value);\n    }\n}	0
11442848	11442768	Emulate double click event in Datagrid with touchDown	using System.Runtime.InteropServices;\n\nnamespace WpfApplication1\n{\n/// <summary>\n/// Interaction logic for MainWindow.xaml\n/// </summary>\npublic partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n    }\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]\n    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);\n\n    private const int MOUSEEVENTF_LEFTDOWN = 0x02;\n    private const int MOUSEEVENTF_LEFTUP = 0x04;\n    private const int MOUSEEVENTF_RIGHTDOWN = 0x08;\n    private const int MOUSEEVENTF_RIGHTUP = 0x10;\n\n    public void DoMouseClick()\n    {\n         //Call the imported function with the cursor's current position\n        int X = //however you get the touch coordinates;\n        int Y = //however you get the touch coordinates;\n        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);\n    }\n}\n}	0
2087067	2087005	How can I "detach" a SqlDataReader from its SqlConnection object?	.Close()	0
31081020	31080933	How to remove an element from an array WITHOUT removing duplicates. in C#	input = input.Skip(1).ToArray();	0
4337162	4337064	No tables returned from a SQL query. How could that happen?	_Articulos = DSet.Tables[0];	0
3689030	3689010	How to keep a reference to a class property updated?	public Class1\n{\n    private Class2 myClass2;\n\n    public Class1()\n    {\n        myClass2 = new Class2();\n    }\n\n    public SomeObject anObject\n    {\n        get { return myClass2.MyObject; }\n        set { myClass2.MyObject = value; }\n    }\n}	0
20244486	20243241	Read javascript from pdf using iTextSharp	var pdfReader = new PdfReader(infilename);\nusing (MemoryStream memoryStream = new MemoryStream())\n{\n    PdfStamper stamper = new PdfStamper(pdfReader, memoryStream);\n    for (int i = 0; i <= pdfReader.XrefSize; i++)\n    {\n        PdfDictionary pd = pdfReader.GetPdfObject(i) as PdfDictionary;\n        if (pd != null)\n        {\n            PdfObject poAA = pd.Get(PdfName.AA); //Gets automatic execution objects\n            PdfObject poJS = pd.Get(PdfName.JS); // Gets javascript objects\n            PdfObject poJavaScript = pd.Get(PdfName.JAVASCRIPT); // Gets other javascript objects\n            //use poJS.GetBytes(), poJS.ToString() etc to inspect details...\n        }\n    }\n    stamper.Close();\n    pdfReader.Close();\n    File.WriteAllBytes(rawfile, memoryStream.ToArray());\n}	0
5021489	5021425	Inserting record in to MySQL Database using C#	cmd.Parameters.Add(new OdbcParameter("@softwareID", softwareID));	0
31486148	31486068	How can I strip any and all HTML tags from a string?	var pattern = @"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>";\n        var source = "<pre> (Refer to business office for guidance and explain below the circumstances for exception to policy or attach a copy of request)</pre>";\n        Regex.Replace(source, pattern, string.Empty);	0
21748612	21748425	how to use left join in entity framework query?	from I in db.Invoices\n      join O in db.Orders on I.InvoiceId equals O.InvoiceId\n      join C in db.Customers on I.CustId equals C.CustId\n      from OD in db.OrderDriverExtraCharges\n        .Where(w=>w.OrderNumberId==O.OrderNumberId).DefaultIfEmpty()\n      from AC in db.AccessorialCharges \n        .Where(w=>w.AccessorialChargeId==OD.AccessorialChargeId).DefaultIfEmpty()\n      where I.InvoiceId == invoice.InvoiceId\n      select new PrintInvoiceViewModel()	0
31091786	28679003	How to change AssemblyName after compilation to load as a mod in Unity3d	// Have Mono.Cecil load the assembly\n     var assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(assemblyFile.FullName);\n\n     // Tell Mono.Cecil to actually change the name\n     assemblyDefinition.Name.Name = newAssemblyNameNoExtension;\n     assemblyDefinition.MainModule.Name = newAssemblyNameNoExtension;\n\n     // We also need to rename any references to project assemblies (first pass assemblies)\n     foreach (var reference in assemblyDefinition.MainModule.AssemblyReferences)\n     {\n        if (Utilities.IsProjectAssembly(reference.Name))\n        {\n           reference.Name = Utilities.GetModAssemblyName(reference.Name, this._modName);\n        }\n     }\n\n     // Build the new assembly\n     byte[] bytes;\n     using (var ms = new MemoryStream())\n     {\n        assemblyDefinition.Write(ms, new Mono.Cecil.WriterParameters() { WriteSymbols = true });\n        bytes = ms.ToArray();\n     }	0
3249346	3237605	PDF with iText - Center Align Strings	int y_offset = 20;\nPhrase fullTitle = new Phrase("Some string", myFont);\nColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, fullTitle, center, y_offset, 0);	0
686113	685285	Change Location Folder?	public static string GetFolderForTime(DateTime time)\n{\n  if (time.Hour > 8 && time.Hour < 10)\n    return @"D:\Morning\";\n  if (time.Hour > 10 && time.Hour < 18)\n    return @"D:\Afternoon\";\n  return @"D:\Night\";\n}	0
10232936	10232828	Linq to XML, creating a new custom class for each distinct element of a certain form	from n in doc.Root.Elements("Parent") select \n{\nClassName = n.Element("ClassName").First().Attribute("ATTRNAME").Value,\nclassAttributes = from a in n.Elements("ClassAttribute") select a.Value,\nmoreAttributes  = from a in n.Elements("ClassName") select a.Value\n}	0
13160312	13160183	How can I remove a item from my session["cart"] on a button click in my view?	public ActionResult DeleteProductFromCart(int ProductImageId)\n{\n    List<int> cart = (List<int>)Session["cart"];\n    if (cart == null)\n    {\n        return new JsonResult() { Data = new { Status = "ERROR" } };\n    }\n    cart.Remove(ProductImageId);\n\n    return new JsonResult() { Data = new { Status = "Success" } };\n}	0
1888991	1883450	xml- Deserialize	public T XmlDeserialize<T>(string xml)\n    {\n        var textReader = new XmlTextReader(new StringReader(xml));\n        var xmlSerializer = new XmlSerializer(typeof(T), xmlAttributeOverrides); <--this\n\n        var result = xmlSerializer.Deserialize(textReader);\n        return (T)result;\n    }	0
22681820	22681762	C# array with a specific format	var sampledata = new[] {\n    new { Day = "Sunday",  Quantity = 15 },\n    new { Day = "Monday",  Quantity = 20 },\n    new { Day = "Tuesday", Quantity = 80 }\n};	0
8166836	8160801	How to pass state information to the GetAsync completion handler?	fb.GetAsync(path, parameters, state)	0
23225593	23171625	Get coordinates from map	MyMap.Tap += (s, e) =>\n{\n    var loc = MyMap.ConvertViewportPointToGeoCoordinate(e.GetPosition(MyMap));\n\n    //Do something with the selected location\n};	0
32434535	32404755	Check platform on Windows 10 Universal App	var str = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;\n    if (str == "Windows.Desktop")\n    {\n      //...\n    }\n    else if (str == "Windows.Mobile")\n    {\n      //...\n    }	0
8239738	8239237	how to open *.dbf spreadsheet file in C#	dataGridView1.DataSource = dt;	0
2985934	2985826	Need help with output custom shape in ConsoleApplication - C#	int n = 6;\n\nvar result = string.Join("\r\n", from i in Enumerable.Range(1, n)\n                                 where i != 2\n                                 let stars = Enumerable.Repeat('*', i)\n                                 let indent = new string(' ', n - i)\n                                 select indent + string.Join(" ", stars));\n\nConsole.WriteLine(result);	0
25782874	25782856	Garbage Values concatenated with table name in Entity Framework	db.Configuration.ProxyCreationEnabled = false;	0
31781369	31775608	how to make gameobject jump forward?	public float thrust;\n        public Rigidbody rb;\n        void Start() {\n            rb = GetComponent<Rigidbody>();\n        }\n        void FixedUpdate() {\n            rb.AddForce(transform.up * thrust);\n        }\n//This will add a force to the rigidbody upwards.	0
506325	506246	Adding Comments [Meta Data ] to a File	try\n{\n    DSOFile.OleDocumentPropertiesClass doc = new DSOFile.OleDocumentPropertiesClass();\n    doc.Open(filename, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);\n\n    doc.SummaryProperties.Author = author;\n    doc.SummaryProperties.Comments = comments;\n\n    doc.Close(true);\n}\ncatch (Exception ex)\n{\n    throw new Exception("Could not update the file properties: " + filename, ex);\n}	0
24902642	24670087	Using WPF Resources in newly loaded components	Loaded = PluginManager.CreateInstance(plugin.LoadPath, plugin.ClassName)\nLoaded.Resources.MergedDictionaries.Add(Me.Resources)	0
25683633	25675866	Autofac - resolve by argument name	public class AppSettingsModule : Module\n{\n    protected override void AttachToComponentRegistration(\n      IComponentRegistry componentRegistry,\n      IComponentRegistration registration)\n    {\n        // Any time a component is resolved, it goes through Preparing\n        registration.Preparing += InjectAppSettingParameters;\n    }\n\n    private void InjectAppSettingParameters(object sender, PreparingEventArgs e)\n    {\n        // check if parameter is of type AppSetting and if it is return AppSetting using the parameter name\n        var appSettingParameter = new ResolvedParameter((par, ctx) => par.ParameterType == typeof(AppSetting), (par, ctx) => new AppSetting(ConfigurationManager.AppSettings[par.Name]));\n        e.Parameters = e.Parameters.Union(new List<Parameter>{ appSettingParameter});\n    }\n}	0
12040194	12039995	RestFul Wcf Video Streaming to iPhone Client	FileStream stream = new FileStream(video_path, FileMode.Open, FileAccess.Read);\n\n                    WebOperationContext.Current.OutgoingResponse.ContentType = "video/quicktime";\n                    return stream;	0
7249335	7246279	How do I programmatically remove a known password from an Access DB?	Private Function CreateDBPassword(ByVal Password As String, _\n    ByVal Path As String) As Boolean\nDim objConn as ADODB.Connection\nDim strAlterPassword as String\nOn Error GoTo CreateDBPassword_Err\n' Create the SQL string to initialize a database password.\nstrAlterPassword = "ALTER DATABASE PASSWORD [Your Password] NULL;"\n\n' Open the unsecured database.\nSet objConn = New ADODB.Connection\nWith objConn\n    .Mode = adModeShareExclusive\n    .Open "Provider=Microsoft.Jet.OLEDB.4.0;Data " & _\n        "Source=[Your Path];" \n\n ' Execute the SQL statement to secure the database.\n .Execute (strAlterPassword)\nEnd With\n\n' Clean up objects.\nobjConn.Close\nSet objConn = Nothing\n\n' Return true if successful.\nCreateDBPassword = True\n\nCreateDBPassword_Err:\nMsgbox Err.Number & ":" & Err.Description\nCreateDBPassword = False \nEnd Function	0
31541632	31515918	Retrieving custom element values from xml using SyndicationFeed	XElement ele = extension.GetObject<XElement>();\nif (ele.ToString().StartsWith("<itunes:image"))\n    {\n      int index = ele.ToString().IndexOf("\" xmlns:itunes");\n      if (index > 0)\n        image = ele.ToString().Substring(0, index).Replace("<itunes:image href=\"", "");\n    }	0
25030673	25030622	Import Excel data to sql database using asp.net	Just Remove the "integrated security" part from your strConnection . Here your connection will use the windows authentication instead of the sql authentication.	0
22805553	22802850	Change null value appearance on DataGrid when binding to DataTable	private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n    {\n        DataGridTextColumn textColumn;\n        if ((textColumn = e.Column as DataGridTextColumn) != null)\n        {\n            var binding = textColumn.Binding;\n            var clone = binding.CloneBinding();\n            clone.FallbackValue = "-----";\n            clone.TargetNullValue = "-----";\n            textColumn.Binding = clone;\n        }\n    }	0
23502628	23497474	How to know the original type of a class Exported as an interface in MEF	private static IEnumerable<Type> GetExportTypes(ComposablePartCatalog catalog, Type type, string contractName)\n    {\n        return catalog.Parts.Where(\n            part =>\n            part.ExportDefinitions.Any(\n                e =>\n                e.ContractName == contractName && e.Metadata.ContainsKey("ExportTypeIdentity") &&\n                e.Metadata["ExportTypeIdentity"].Equals(\n                    type.FullName))).Select(part => ReflectionModelServices.GetPartType(part).Value);\n    }	0
2178698	2178660	Selecting and building a Control from a control library dynamically, using the control name from a table	Type type = Type.GetType(ControlName); \nobject control = Activator.CreateInstance(type);	0
2228056	2227979	WCF get Group of a User	bool hasAccess = HttpContext.Current.User.IsInRole("Administrators");	0
17542139	17542030	One object for all wcf customers	[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]\npublic class ConfigurationService : IConfigurationService	0
13903259	13901691	CallbackOnCollectedDelegate was detected even with static delegate	public void hook()\n{\n    if (callbackDelegate != null) \n        throw new InvalidOperationException("Cannot hook more than once");\n    // etc..\n}	0
3158381	3158340	C# equivalent of ccDebug in VB6	#if DEBUG\n        //do special stuff \n#endif	0
9294080	9293799	adding rows to a datatable #2	List<Info> infoList = new List<Info>();\ninfoList.Add(...); //Add item here.\n\nforeach(Info info in infoList)\n{\n   DataRow row = dataTable.NewRow(); \n   row["item1"] = info.Item1; //where Item1 could be a string \n   row["Item2"] = info.Item2; //where Item2 could be an int\n   row["item3"] = info.Item3; //Where Item3 could be a DateTime\n   row["Item4"] = info.Item4; //Where Item4 could be a Decimal\n}	0
1210695	1210652	Linq to SQL with Group by	var qry = from x in someSource\n              group x by new { x.ClientID, x.GivenName, x.Surname } into grp\n              select new { grp.Key, Address = grp.Max(x => x.Address),\n                  Value = grp.Max(x => x.Value) };	0
10429377	10429324	Getting the field names from a Linq To Sql object	var result = from item in context.table\n    select new {\n         field1 = ... ,\n         field2 = ... ,\n         field3 = ... };\n\nif (result.Any())\n{\n    Type t = result.First().GetType();\n    foreach (PropertyInfo p in t.GetProperties())\n    {\n        // Get the name of the prperty\n        Console.WriteLine(p.Name);\n    }\n}	0
7790266	7790214	How to modify an xml attribute's value?	project.ProjectData = doc.InnerXml	0
19184000	19183095	Download folder with all content recursively, Sharpbox	string remoteDirName = @"/Public/WS";\nstring targetDir = @"C:\Users\Michael\";\nvar remoteDir = dropBoxStorage.GetFolder(remoteDirName);\n\npublic static DownloadFolder(CloudStorage dropBoxStorage,ICloudDirectoryEntry remoteDir, string targetDir)\n{\n\n    foreach (ICloudFileSystemEntry fsentry in remoteDir)\n    {\n        if (fsentry is ICloudDirectoryEntry)\n        {\n            DownloadFolder(dropBoxStorage, fsentry, Path.Combine(targetDir, fsentry.Name));\n        }\n        else\n        {\n            dropBoxStorage.DownloadFile(remoteDir,fsentry.Name,Path.Combine(targetDir, fsentry.Name));\n        }\n    }\n}	0
18992805	18992756	Exit my while loop at a specific day and time	DateTime currentDate = DateTime.Now;\nif (currentDate.DayOfWeek == DayOfWeek.Monday && currentDate.Hour >= 8)\n{\n     runLoop = false;\n}	0
8622918	8622840	I'm trying to have 2 check box columns before other columns in DataGrid	dataGridView1.Rows.Add(new object[] { true, false, "user", "password" });	0
11651620	11650222	Minimum number of bytes that can contain an integer value	public static int GetMinByteSize(long value, bool signed)\n{\n    ulong v = (ulong)value;\n    // Invert the value when it is negative.\n    if (signed && value < 0)\n        v = ~v;\n    // The minimum length is 1.\n    int length = 1;\n    // Is there any bit set in the upper half?\n    // Move them to the lower half and try again.\n    if ((v & 0xFFFFFFFF00000000) != 0)\n    {\n        length += 4;\n        v >>= 32;\n    }\n    if ((v & 0xFFFF0000) != 0)\n    {\n        length += 2;\n        v >>= 16;\n    }\n    if ((v & 0xFF00) != 0)\n    {\n        length += 1;\n        v >>= 8;\n    }\n    // We have at most 8 bits left.\n    // Is the most significant bit set (or cleared for a negative number),\n    // then we need an extra byte for the sign bit.\n    if (signed && (v & 0x80) != 0)\n        length++;\n    return length;\n}	0
11206827	11206795	How to remove node from xml with XDocument class in c#?	LoadXmlFile.Descendants("NewElementName").Remove();         \n LoadXmlFile.Save(@"D:\yyy_RemoveElement.xml");	0
19927598	19926671	Access to HTML Elements on Windows Phone APP using C#	function test(foo){\nalert(foo);\n}\n\nprivate void TestButton_OnClick(object sender, EventArgs e)\n{\n    webBrowser.InvokeScript("test", 1234);\n}	0
19252517	19252418	Updating a single row in linq	var mytab = db.Customers.First(g=>g.CustomerId == mymodel.CustomerId);\n mytab.FirstName = mymodel.FirstName;\n mytab.LastName = mymodel.LastName;\n db.SaveChanges()	0
28108579	28107774	Passing Strings to a Class Method that passes information to stored SQL procedure	using (var command = new SqlCommand("Submit_Data", connect) { CommandType = CommandType.StoredProcedure }) \n{\n   connect.Open();\n\n   command.Parameters.Add(new SqlParameter("@Firstname", datFirstname));\n   command.Parameters.Add(new SqlParameter("@Surname", datSurname));\n   command.Parameters.Add(new SqlParameter("@Visiting", datVisiting));\n   command.Parameters.Add(new SqlParameter("@Car_Reg", datReg));\n\n   command.ExecuteNonQuery();\n   connect.Close();\n}	0
24506023	24505901	Convert Hex string to normal String in C#	.Where(x => x % 2 == 0)	0
15945393	15945358	Adding and displaying new stats from a high score board	"&accuracy"	0
23885344	23885160	dynamically add IEnumerable<int?> on group by result set in c#	var enableIds = context.items.Where(tble => tble.Date == null)\n                     .GroupBy(a => a.Id)\n                     .Select(g => new\n    {\n        Id = g.Key,\n        EId = g.Select(c => c.EId).Distinct()).ToList().Concat(new[] { -1 })\n    });	0
26506997	26505744	Grouping in a ListBox bound to a Dictionary	view.GroupDescriptions.Add(new PropertyGroupDescription("Value.State"));	0
33126838	33106032	Regex expression for extracting SQL Server function value	\((getdate\(\))(\+|\-)\(?(\d+)\)?\)	0
18308888	18308822	Regular Expression To Match XML String is having start and end tags in C#	var iq = XElement.Parse(xml).DescendantsAndSelf("iq").FirstOrDefault();\nif (iq != null)\n{\n}	0
15023184	15023103	How can I combine two onclient click for javascripts in c#?	imgBtn_mail.OnClientClick = \n    String.Format(\n      "javascript:DisableButtons(true); NewEmailMessageWindow({0}, {1});return false;",\n      invoice.Id, \n      FindPage.ToString().ToLower()\n      );	0
4431604	4431567	Connecting to MS Access 2010 using C#	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;	0
15214498	15214452	How to update label after submitting mutually exclusive check boxes?	var color = System.Drawing.Color.Red; //assume incorrect answer\nvar label = "Incorrect";\n\nif (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)\n{\n  //only the 2 correct answers have been checked\n  color = System.Drawing.Color.Green;\n  label = "Correct";\n}\n\n// set the controls\nlblQuestionResult4.ForeColor = color;\nlblQuestionResult4.Text = label;	0
27541195	27308276	populating GridView with sql data	protected void Button2_Click(object sender, EventArgs e)\n{\n    string cs = ConfigurationManager.ConnectionStrings["roleDB"].ConnectionString;\n    SqlConnection con = new SqlConnection(cs);\n    con.Open();\n    SqlCommand cmd = con.CreateCommand();\n    cmd.CommandType = CommandType.Text;\n    cmd.CommandText = "select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'";\n    SqlDataAdapter da = new SqlDataAdapter(cmd);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n    GridView2.DataSource = dt;\n    GridView2.DataBind();\n    con.Close();\n}	0
34176850	34176798	Transform between datetime formats	DateTime parsedDate = DateTime.ParseExact("2015.12.9", "yyyy.MM.d", CultureInfo.InvariantCulture);	0
1192138	1191900	Invoking a .exe referenced to the c# windows application	namespace test\n{\n   using BlockShortcuts;\n   class MyTest\n   {\n        public static void Main(string[] args)\n        {\n           DisableKeys dk = new DisableKeys();\n           dk.DisableKeyboardHook();\n        }\n\n   }\n }	0
18847236	18847150	How Can a Class Can Implement Interface without implement one Of the Functions?	public class Implementation : IInterface\n{\n    void IInterface.SomeMethod()\n    {\n        throw new NotSupportedException();\n    }\n}\n\nvar instance = new Implementation();\ninstance.SomeMethod(); // Doesn't compile\n\nvar interfaceInstance = (IInterface)instance;\ninterfaceInstance.SomeMethod(); // Compiles and results in the\n                                // NotSupportedException being thrown	0
31205421	31205357	Setting out parameters with Microsoft Fakes	[TestFixture]\npublic class MyTestTests\n{\n    [Test]\n    public void MyTest()\n    {\n        using (ShimsContext.Create())\n        {\n            ShimFoo.TryBarStringStringOut = (string input, out string output) =>\n            {\n                output = "Yada yada yada";\n\n                return false;\n            };\n        }\n    }\n}	0
34341207	34340691	How to switch user entered search string between RegEx and plain Text	string filter = sometextbox.Text;\nRegex rgx = new Regex(filter);\nbool IsRegEx = RegExCheckBox.Checked;\n\nList<string> Matches = new List<string>();\n\nfor (int i = 0; i < data.Count; i++)\n{\n    if (IsRegEx && rgx.IsMatch(data[i].Content))\n        Matches.Add(data[i].Content);\n    else if (!IsRegEx && data[i].Content.ToLower().Contains(filter.ToLower())) \n        Matches.Add(data[i].Content);\n}\n\n//Do something with your list of Matches	0
8242280	8242147	How to get task priority	Item.Importance	0
17990142	17989964	Ordering a list by suming several rows	UserDataPoint[] myArray =\n    myList.GroupBy(udp => udp.User)\n            .OrderByDescending(g => g.Sum(udp => udp.Spend))\n            .SelectMany(g => g)\n            .ToArray();	0
10895684	10894031	PrincipalServerDownException on Windows XP but not on Windows 7	PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null);	0
20978199	20977825	How to bind two arrays to datagrid in WPF C#	double[,] combined = new double[2, acce.Length];\nfor (int i = 0; i < acce.Length; i++)\n{\n    combined[0, i] = acce[i];\n    combined[1, i] = peri[i];\n}	0
12790762	12790636	Custom control with type parameters	interface IMyControl<A, B> { }\npublic partial abstract class MyControlBase<A, B> : DataGridView, IMyControl<A, B>\n{\n    // Generic code goes here\n}\n\n// Create non-generic wrappers for the generic base class\npublic partial class MyControl_One : DataGridView, MyControlBase<SomeType, OtherType>\n{\n     // Type-specific (if any) code goes here\n}\npublic partial class MyControl_Two : DataGridView, MyControlBase<MyType, YourType>\n{\n     // Type-specific (if any) code goes here\n}	0
19864313	19863944	How do I reissue a webrequest? Must I recreate Webclient?	string result ="";\n\n    bool callComplete = false;\n    while (callComplete != true)\n    {\n        var request = (HttpWebRequest)WebRequest.Create(target);\n        request.ContentType = "application/json";\n        request.Headers.Add("Authorization", "Bearer " + oAuthKey);\n        request.AllowAutoRedirect = false;\n                    //...	0
12985546	12985510	Can't create a file when users generate at a same time	string name = modDetail.order_detail_id.ToString() + ".xml";\nstring path = ArgenXmlOrderPath + "/" + name;\nXDoc.Save(path);	0
14055532	14053997	Dynamic generate method value	private void label_Click(object sender, EventArgs e)\n        {\n            if (((Label)sender).Tag.Equals("1"))\n            {\n                MessageBox.Show("Label 1 clicked!");\n            }\n        }	0
4888429	4887955	How to Merge two Observables so the result completes when the any of the Observables completes?	public static class Ext\n{\n    public static IObservable<T> MergeWithCompleteOnEither<T>(this IObservable<T> source, IObservable<T> right)\n    {\n        return Observable.CreateWithDisposable<T>(obs =>\n        {\n            var compositeDisposable = new CompositeDisposable();\n            var subject = new Subject<T>();\n\n            compositeDisposable.Add(subject.Subscribe(obs));\n            compositeDisposable.Add(source.Subscribe(subject));\n            compositeDisposable.Add(right.Subscribe(subject));\n\n\n            return compositeDisposable;\n\n        });     \n    }\n}	0
27968258	27968198	How to trim an SSN that generates from a model	var lastFour = primarySsn.Substring(primarySsn.Length-4,4);	0
249378	249375	Setting DataContext with SelectedItem Programatically	Binding binding = new Binding();\nbinding.ElementName = "listBox1";\nbinding.Path = new PropertyPath("SelectedItem");\nbinding.Mode = BindingMode.OneWay;\ntxtMyTextBox.SetBinding(TextBox.TextProperty, binding);	0
9334239	9334213	How can I swallow an exception that is thrown inside a catch block?	try {\n    // ...\n}\ncatch (Exception exception) {\n    try {\n        // Attempt to write to event log.\n    }\n    catch {\n    }\n}	0
13145956	13145924	How do I strip \n characters from a file?	static void Main( string[] args )\n{\n    using( var inFs = File.OpenRead( @"C:\input.txt" ) )\n    using( var reader = new StreamReader( inFs ) )\n    using( var outFs = File.Create( @"C:\output.txt" ) )\n    using( var writer = new StreamWriter( outFs ) )\n    {\n        int cur;\n        char last = '0';\n        while( ( cur = reader.Read() ) != -1 )\n        {\n            char next = (char)reader.Peek();\n            char c = (char)cur;\n            if( c != '\n' || last == '\r' )\n                writer.Write( c );\n\n            last = c;\n        }\n    }\n}	0
6486727	6486706	Contains with Linq	List<EstimationItem> items = new List<EstimationItem>();\n// Add items\n\nint searchedCode = 1\n\nif(items.Any(i => i.Product.Code == searchedCode))\n{\n    // Contained\n}	0
3563408	3563328	Piglatin using Arrays	string UnPigLatinify(string word)\n{\n    if ((word == null) || !Regex.IsMatch(word, @"^\w+ay$", RegexOptions.IgnoreCase))\n        return word;\n\n    return word[word.Length - 3] + word.Substring(0, word.Length - 3);\n}	0
14814611	14814544	How to get Uri of view returned by action method?	Url.Action(actionName, controllerName)	0
7745073	7744706	Set line and page size for ScrollViewer	ScrollBar verticalScrollBar = scrollViewer.Template.FindName("PART_VerticalScrollBar", scrollViewer) as ScrollBar;\nverticalScrollBar.SmallChange = 5;	0
30986407	30959980	3DES encrypt from C# to JAVA	private byte[] genTwoKey3DES(byte[] key) {\n    byte[] keyAux;\n    if (key.length == 16) {\n        keyAux = new byte[24];\n        System.arraycopy(key, 0, keyAux, 0, 16);\n        System.arraycopy(key, 0, keyAux, 16, 8);\n    } else {\n        keyAux = key;\n    }\n    return keyAux;\n}	0
3969575	3968198	finding schemaLocation in c# XmlSchema	schema.Includes[0] as XmlSchemaImport;\nvar wsdlId = schemaImport.SchemaLocation;	0
18136960	18134149	How can I use data repeater correctly here	protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    _connection.Open();\n    try\n    {\n        DataItemTypeName data = (DataItemTypeName)e.Item.DataItem;\n        if (data == null)\n            // This is more of a debugging check, since I'm a little in the dark about data types and such here.\n            throw new Exception("No data.");\n\n        OdbcCommand findempros = new OdbcCommand("SELECT p.projName from projects p INNER JOIN assigns a ON p.projID = a.projname WHERE a.employeeID LIKE '" + data.ID + "'", _connection);\n        OdbcDataReader readit = findempros.ExecuteReader();\n\n        while (readit.Read())\n        {\n            DropDownList mydblist = (DropDownList)e.Item.FindControl("DropDownList1");\n            mydblist.Items.Add(readit["projName"].ToString());\n        }\n    }\n    finally\n    { _connection.Close(); }\n}	0
3396483	3396220	how to enumerate the response set from FQL	var response = _facebookAPI.Fql.Query(String.Format("SELECT uid FROM event_member WHERE eid={0}", myevent));\nXmlDocument doc = new XmlDocument(); \ndoc.LoadXml(response); \nXmlNodeList uids = doc.GetElementsByTagName("uid"); \n\nvar uids = new List<long>();\nforeach (XmlNode node in uids)\n{\n      long id;\n      if (long.TryParse(node.InnerText, out id))\n      {\n           uids.Add(id);\n      }\n }	0
29690269	29666074	How to apply cell style to each cell in new row from previous row	workSheet.Cells[nRows + 1, 3] = DateTime.Today;\n            Range sourceRange = workSheet.Cells[nRows, 3];\n            sourceRange.Copy(Type.Missing);\n            Range destinationRange = workSheet.Cells[nRows + 1, 3];\n            destinationRange.PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);\n            destinationRange.PasteSpecial(XlPasteType.xlPasteFormulas, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);	0
6614764	6614714	How to handle missing node in LINQ to XML query	IEnumerable<Person> persons =\n    from e in x.Descendants("Person")\n    select new Person { \n        Name = e.Value,\n        Age = (int?) e.Attribute("Age") ?? 21,\n        ParentAge = e.Parent != null ? (int) e.Parent.Attribute("Age") : 42\n    };	0
4545327	4545273	Convert Bitmap to Thumbnail	var filename = "fb.png";\n\nusing(var image = Image.FromFile(filename))\n{\n    using(var thumbnail = image.GetThumbnailImage(20/*width*/, 40/*height*/, null, IntPtr.Zero))\n    {\n        thumbnail.Save("thumb.png");\n    }\n}	0
16999634	16990939	I Can't recover query string parameter on my custom route - MVC4	public class LocalizationFilter : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        base.OnActionExecuting(filterContext);\n        string culture = filterContext.HttpContext.Request.RequestContext.RouteData.Values["culture"].ToString();\n        string subUser = filterContext.HttpContext.Request.RequestContext.RouteData.Values["subUser"].ToString();       \n    }\n}	0
19490654	19490005	How to model this as a LINQ query?	list.Select(a => new { a.P1, a.P2 })\n    .Distinct()\n    .Select(x => new Id { Main = x.P1, SubMain = x.P2 });	0
1108579	1108565	How to tell C# to look in an object's base class for a property?	public abstract class Items<T> : ItemBase where T : Item\n{\n//....\n}	0
32857326	32845215	StaleElementReferenceException while waiting	WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));\nIWebElement loaderGif = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@src='/loader.gif']")));	0
12494766	12494660	Security of launching files from program	public static string ComputeHash(string fileName)\n{\n    using(FileStream st = File.OpenRead(fileName))\n    {\n         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider());\n         byte[] hash = sha1.ComputeHash(st);\n         return BitConverter.ToString(hash).Replace("-", "");\n    }\n}	0
4030760	4030735	how to export gridview to pdf in c#	no build in class in .Net	0
7370727	7370648	How to close all dynamically created forms?	List<frmForm1> _forms = new List<frmForm1>();\n\nvoid OpenForms()\n{\n    var f1 = new frmForm1();\n    _forms.Add(f1);\n\n    var f2 = new frmForm1();\n    _forms.Add(f2);\n\n }\n\nvoid CloseForms()\n{\n    foreach (var form in _forms)\n    {\n        form.Close();\n    }\n}	0
6315021	6314988	Need help with logic on a weird loop	int count = 0;\nbyte previous = byteArray[0];\nList<int> list = new List<int>();\n\nfor (int i = 1; i < byteArray.Length; i++)\n{\n    byte current = byteArray[i];\n    if (previous == current)\n    {\n        count++;\n    }\n    else\n    {\n        list.Add(count);\n        list.Add(Convert.ToInt32(current));\n    }\n\n    previous = current;\n}	0
8106790	8105331	compare same data into table and delete different data by : Linq	A.Union(B).Except(A.Intersect(B))	0
31033666	31033608	In C#, how can I replace\u0026 with &?	results.Replace(@"\u0026", "&");	0
25243473	25243154	How to get every other element in xml(iconCode)	foreach (XElement element in scan.Descendants("iconCode"))\n{\n     string iconCode1 = element.Value;\n     Int32 result;                             \n     Int32.TryParse(iconCode1, out result);\n     string iconFilename2 = "cond" + string.Format("{0:00#}", result) + ".png";\n\n     xFore.Root.Add(new XElement("img_small", weatherImages + @"Small/" + iconFilename2),\n     new XElement("img_large", weatherImages + @"Large/" + iconFilename2));\n}	0
27912788	27911324	Play continuous music when swapping between multiple scene in Unity3d	public class MusicManager : MonoBehaviour \n{\n    private static MusicManager _instance;\n\n    public static MusicManager instance\n    {\n        get\n        {\n            if(_instance == null)\n            {\n                _instance = GameObject.FindObjectOfType<MusicManager>();\n\n                //Tell unity not to destroy this object when loading a new scene!\n                DontDestroyOnLoad(_instance.gameObject);\n            }\n\n            return _instance;\n        }\n    }\n\n    void Awake() \n    {\n        if(_instance == null)\n        {\n            //If I am the first instance, make me the Singleton\n            _instance = this;\n            DontDestroyOnLoad(this);\n        }\n        else\n        {\n            //If a Singleton already exists and you find\n            //another reference in scene, destroy it!\n            if(this != _instance)\n                Destroy(this.gameObject);\n        }\n    }\n\n    public void Play()\n    {\n        //Play some audio!\n    }\n}	0
2202430	2202381	Reflection: How to Invoke Method with parameters	result = methodInfo.Invoke(classInstance, parametersArray);	0
14038386	14038350	Need to find last day of previous month and previous to previous month	DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);\nDateTime endOfPreviousMonth = startOfMonth.AddDays(-1);\nDateTime endOfPreviousPreviousMonth = startOfMonth.AddMonths(-1).AddDays(-1);	0
1579114	1579074	Redirect stdout+stderr on a C# Windows service	[DllImport("Kernel32.dll", SetLastError = true) ]\npublic static extern int SetStdHandle(int device, IntPtr handle); \n\n// in your service, dispose on shutdown..\nFileStream filestream;\nStreamWriter streamwriter;\n\nvoid Redirect()\n{   \n    int status;\n    IntPtr handle;\n    filestream = new FileStream("logfile.txt", FileMode.Create);\n    streamwriter = new StreamWriter(filestream);\n    streamwriter.AutoFlush = true;\n    Console.SetOut(streamwriter);\n    Console.SetError(streamwriter);\n\n    handle = filestream.Handle;\n    status = SetStdHandle(-11, handle); // set stdout\n    // Check status as needed\n    status = SetStdHandle(-12, handle); // set stderr\n    // Check status as needed\n}	0
2263809	2263658	Dictionary using generics	public class ResourceMap<T> extends Dictionary<string, T> { }\n\npublic static class ResourceManager\n{\n    public static ResourceMap<Font> Fonts { get; private set; }\n    public static ResourceMap<Image> Images { get; private set; }\n    public static ResourceMap<Sound> Sounds { get; private set; }\n\n    public static void LoadResources()\n    {\n        Fonts = new ResourceMap<Font>();\n        Images = new ResourceMap<Image>();\n        Sounds = new ResourceMap<Sound>();\n\n        Fonts.Add("Helvetica", new Font("Helvetica", 12, FontStyle.Regular));\n        Images.Add("Example", Image.FromFile("example.png"));\n    }\n}	0
4036641	4036561	Showing current/selected item in ListView in WinForms	item.EnsureVisible();	0
7107479	7107026	Converting an Int to a BCD byte array	public static byte[] ToBcd(int value){\n        if(value<0 || value>99999999)\n            throw new ArgumentOutOfRangeException("value");\n        byte[] ret=new byte[4];\n        for(int i=0;i<4;i++){\n            ret[i]=(byte)(value%10);\n            value/=10;\n            ret[i]|=(byte)((value%10)<<4);\n            value/=10;\n        }\n        return ret;\n    }	0
33803192	33802469	Click on Anchor tag automatically via C# Code(Windows desktop application)	using (var browser = new IE("Your URI)")\n{\n    browser.Link(linkId).Click();\n    var div = browser.Div(divId);\n}	0
1420529	1420514	listbox selected items in winform	string text = "";\n\nforeach (System.Data.DataRowView item in listBox1.SelectedItems) {\n    text += item.Row.Field<String>(0) + ", ";\n}\ntextBox1.Text = text;	0
18941323	18940554	Add StackPanel and more than one TextBlock inside Button	public partial class MainWindow : Window {\n    public MainWindow() {\n        InitializeComponent();\n\n        var tb1 = new TextBlock() { Text = "TextBlock 1" };\n        var tb2 = new TextBlock() { Text = "TextBlock 2" };\n\n        var stackPanel = new StackPanel();\n        stackPanel.Children.Add(tb1);\n        stackPanel.Children.Add(tb2);\n\n        var button = new Button() { Content = stackPanel };\n\n        this.Content = button;\n    }\n}	0
28034862	28034836	Setting connection strings in ASP.net	Web.*.config	0
1848526	1848438	Using Reflection to get a variable's name	if (IsPropertyName(() => this.IsEditable, propertyRefreshName))\n{ ... }	0
4681722	4680606	C# : How to open configuration Pin Dialog?	System.Diagnostics.Process.Start	0
32245373	32245145	Dependency Injection in ViewModelBase - Best practice	protected readonly ILoggerService _loggerService;	0
26311902	25058813	How to make GameObject jump in Unity3D	player.transform.position += player.transform.right * speed * time.deltaTime;	0
4328437	4328411	Loop through attribute of a class and get a count of how many properties that are not null	public int NonNullPropertiesCount(object entity)\n{\n    return entity.GetType()\n                 .GetProperties()\n                 .Select(x => x.GetValue(entity, null))\n                 .Count(v => v != null);\n}	0
2326846	2326827	Convert String to DateTime	DateTime result =\n    DateTime.ParseExact("20090212", "yyyyMMdd", CultureInfo.InvariantCulture);	0
7469325	7469298	Problem running a function with ref vars	monF(monArray, arraySize, ref monMin, ref monMax);	0
11474760	11474377	Generate all combinations up to X length from List<string> of words	static void Main()\n{\n    var words = new List<string> {"w1", "w2", "w3", "w4", "w5", "w6", "w7"};\n\n    foreach (var list in Generate(words, 3))\n    {\n        Console.WriteLine(string.Join(", ", list));\n    }\n}\n\nstatic IEnumerable<List<string>> Generate(List<string> words, int length, int ix = 0, int[] indexes = null)\n{\n    indexes = indexes ?? Enumerable.Range(0, length).ToArray();\n\n    if (ix > 0)\n        yield return indexes.Take(ix).Select(x => words[x]).ToList();\n\n    if (ix > length)\n        yield break;\n\n    if (ix == length)\n    {\n        yield return indexes.Select(x => words[x]).ToList();\n    }\n    else\n    {\n        for (int jx = ix > 0 ? indexes[ix-1]+1 : 0; jx < words.Count; jx++)\n        {\n            indexes[ix] = jx;\n            foreach (var list in Generate(words, length, ix + 1, indexes))\n                yield return list;\n        }\n    }\n}	0
30602673	30602500	asp.Net how to set left side of a button?	Button buttonb = new Button();\nbuttonb.Attributes.Add("Style", "margin-left:10px");	0
24099218	24095634	Deserialization of not so well formated json	public class Payload\n{\n    [JsonProperty("solarforecast")]\n    public Dictionary<int, Dictionary<DateTime, SolarForecastTimeSet>> SolarForecast;\n}\n\npublic class SolarForecastTimeSet\n{\n    [JsonProperty("dh")]\n    public decimal DiffusRadiationHorizontal;\n\n    [JsonProperty("bh")]\n    public decimal DirectRadiationHorizontal;\n}	0
3343952	3343892	Problem displaying a linq query in a datagridview	EnumerableRowCollection<DataRow> myFooQuery = from t in myLists.SelectMany( l => l.bar)\n                              orderby t.StartTime descending\n                              select t;\n\nDataView myDataView = myFooQuery.AsDataView();\n\ndataGridView1.DataSource = myDataView;	0
6491381	6468488	Retain the user defined sort order in WPF DataGrid	string sortHeader;\nstring prevSortHeader;\nSortDescription sd;\n\nprivate void dgInvoiceHeads_Sorting(object sender, DataGridSortingEventArgs e) {\n  sortHeader = e.Column.Header.ToString();\n\n  if (sortHeader == prevSortHeader) {\n    sd = new SortDescription(sortHeader, ListSortDirection.Descending);\n  }\n  else {\n    sd = new SortDescription(sortHeader, ListSortDirection.Ascending);\n  }\n  prevSortHeader = sortHeader;\n}	0
19328725	19328590	Can I detect a hung process with another thread and recover from it?	var triesLeft = 5;\nwhile (triesLeft > 0) \n{\n    var mre = new ManualResetEvent(false);\n\n    ThreadPool.QueueUserWorkItem(_ => {\n                           MethodThatHangsForever10PercentOfTheTime();\n                           mre.Set();\n                     });\n\n    if (mre.WaitOne(TimeSpan.FromMinutes(20)))\n    {\n          break; // Success!\n    }\n    triesLeft--;\n  }\n}	0
12320870	12320650	Linq - group a list into pairs based on a property	var shoesByBrand = shoes.GroupBy(s => s.Brand);\nforeach (var byBrand in shoesByBrand)\n{\n    var lefts = byBrand.Where(s => s.LeftOrRight == LeftOrRight.L);\n    var rights = byBrand.Where(s => s.LeftOrRight == LeftOrRight.R);\n    var pairs = lefts.Zip(rights,(l, r) => new {Left = l, Right = r});\n\n    foreach(var p in pairs)\n    {\n        Console.WriteLine("Pair:  {{{0}, {1}}}", p.Left.Id, p.Right.Id);\n    }\n\n    Console.WriteLine();\n}	0
13331685	13331668	retweet with oauth c#	webRequest.GetResponse()	0
1865798	1865667	"FormatException was unhandled" Input string was not in a correct format	return Convert.ChangeType(IsThisObjectANull, DataTypeCode);	0
4804799	4804767	Compulsory option of jQuery plugin	if (!options.item4) {\n    alert('Give me an item 4!');\n    console.log('Item 4!');\n    return false;\n}	0
4920678	4920236	Winforms, Invokes and a problematic button	private bool mbIsRunning = true;\n\n   private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n   {\n      lock (this)\n      {\n         mbIsRunning= false;\n      }\n   }\n\n   private bool IsRunning\n   {\n        get\n        { \n            lock(this)\n            {\n                return mbIsRunning;\n            }\n        }\n    }\n\n\n    string msg;\n    public void Reader(object o)\n    {\n\n        TcpClient con = o as TcpClient;\n        if (con == null)\n            return;\n        while (IsRunning)\n        {\n             msg = reader.ReadLine(); \n             string line;\n             while( (line = reader.ReadLine()) != null )\n             {\n                msg = msg + Enviroment.NewLine + line;\n             }\n\n             Invoke(new Action(Output));\n        }\n    }	0
5739965	5739799	how to get the All the Checkbox values in TreeView control in C#.net(2010) Windows Forms Application?	protected string getCheckedNodes(TreeNodeCollection tnc)\n    {\n        StringBuilder sb = new StringBuilder();\n\n        foreach (TreeNode tn in tnc)\n        {\n            if (tn.Checked)\n            {\n                string res = tn.FullPath;\n                if (res.Length > 0)\n                    sb.AppendLine(res);\n            }\n            string childRes = getCheckedNodes(tn.Nodes);\n            if (childRes.Length > 0)\n                sb.AppendLine(childRes);\n        }\n\n        return sb.ToString();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show(getCheckedNodes(treeView1.Nodes));\n    }	0
5586578	5585770	Regular expression simplification - too many groups	foreach(var match in Regex.Matches(s, @"(?<=#if\s*!?\s*defined\s*)(?<macro_name>\w+)")) {\n  Console.WriteLine(match);\n}	0
26591138	26590934	Best practice to parse date from string	DateTime.ParseExact(date, CultureInfo.CurrentCulture.DateTimeFormat.RFC1123Pattern, CultureInfo.InvariantCulture)	0
31740295	31739853	Split string by ',' into array except ',' within ()	",(?=[^\)]*(?:\(|$))"	0
13183905	13183634	Deserializing an object containing a list of int's	var xDoc = XDocument.Parse(xmlstring); //or XDocument.Load(fileName)\nXNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";\n\nvar a = xDoc.Descendants(ns + "int")\n            .Select(x => (int)x)\n            .ToList();	0
9420064	9419987	Can i get a specific user by some attribute without knowing the OU's in Active Directory (AD)?	using (var identity = new WindowsIdentity(username))\n{\n    var user = new WindowsPrincipal(identity);\n\n    if (user.IsInRole("Some Role Name"))\n        return true;\n\n    return false;\n}	0
1083699	1083691	How to detect mouse wheel tilt?	protected override void WndProc(ref Message m)\n    {\n        base.WndProc(ref m);\n        if (m.HWnd != this.Handle)\n        {\n            return;\n        }\n        switch (m.Msg)\n        {\n            case Win32Messages.WM_MOUSEHWHEEL:\n                FireMouseHWheel(m.WParam, m.LParam);\n                m.Result = (IntPtr)1;\n                break;\n            default:\n                break; \n        }\n    }\n    ...\n    abstract class Win32Messages\n    {\n        public const int WM_MOUSEHWHEEL = 0x020E;//discovered via Spy++\n    }	0
23994971	23994918	What's the lambda expression to check to see if one property in any of a group of objects matches any of a group of strings?	myObjects.Any(x => myStrings.Contains(x.Status))	0
27501044	27500917	Get specific Value as String c#	private string ExtractBetweenBodyTags(string str1)\n    {\n\n        if ( ! string.IsNullOrEmpty(str1))\n        {\n            int p1 = str1.IndexOf("<body>\r\n");\n                if (p1 >-1)\n                {\n                    string str2 = str1.Substring(p1 + "<body>\r\n".Length);\n                    int p2= str2.IndexOf("\r\n</body>");\n                    if (p2 > -1)\n                    {\n                        str2 = str2.Substring(0,p2-1 );\n                        return str2;\n                    }\n                }\n        }\n        return "";\n    }	0
32251965	32251705	How to call a method into a constructor in the same class and pass user input into this?	public class Circle\n{\n    private readonly int Radius;\n\n    public static int MyValue()\n    {\n        Console.WriteLine("Please enter radius value: ");\n        return Convert.ToInt32(Console.ReadLine());\n    }\n\n    public Circle()\n    {\n        Radius = MyValue();\n    }\n\n...\n\n}	0
6147657	6147575	Getting Path from <input type="file"> & Attach to Email	var destination = Path.GetTempFileName(); // you should probably replace this with a directory the IIS Worker Process has write permission to\ntry {\nRequest.Files[0].SaveAs(destination);\n\nAttachment.Add(new Attachment(destination));\n// Send attachment\n} finally {\nFile.Delete(destination);\n}	0
8097987	8097841	Get source control in OnServerValidate method	protected void CustomValidator1_ServerValidate (object source, ServerValidateEventArgs args)\n{\n   var validationControl = source as CustomValidator;\n\n   var textBox = FindControl(validationControl.ControlToValidate) as TextBox;\n\n   if (textBox != null)\n   {\n      // Do something\n   }\n}	0
10522496	10522365	How to pull text from this string of data	string str = "8 mi SSW of Newtown, PA";\nvar parts = str.Split(new[] {' '}, 5);	0
13288561	13288456	How to execute different statements based on the file version of a referenced dll?	var methodX = assembly.GetType("sometype").GetMethod("X");\nif (methodX != null)\n{\n    methodX.Invoke(params);\n}\nelse\n{\n    assembly.GetType("sometype").GetMethod("Y").Invoke(otherParams);\n}	0
18532910	18532707	generate sha256 hash for a string in objective C equivalent to C# without using key	- (NSData *)sha256:(NSData *)data\n{\n    unsigned char hash[CC_SHA256_DIGEST_LENGTH];\n    if ( CC_SHA256([data bytes], [data length], hash) )\n    {\n        NSData *hashData = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH];\n        return hashData;\n    }\n    return nil;\n}	0
23891831	23891340	How to Parse using Regex in C#	string input =@"""POST /trusted HTTP/1.1"" ""000.00.00.0"" 200 9 ""42"" 123456 A3rTW6ecEIcBACvMEbAACAJA"; \n   var r = \n        Regex.Matches(\n            input,\n            "((\"[^\"]+\")|([^\" ]+))"\n        );\n    foreach (var s in r)\n    {\n      System.Console.WriteLine(s);\n    }           \n\n    System.Console.ReadLine();	0
23784346	23783272	Closing 'option' tags with HTML Agility Pack while preserving innertext	// Get all option elements\n        HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("//option");\n        foreach (HtmlNode node in nodes)\n        {\n            // Get the outer position of the NextSibling (which would be the text we want to surround with </option>)\n            int nextPosition = rawProvinces.IndexOf(node.NextSibling.OuterHtml) + node.NextSibling.OuterHtml.Trim().Length;\n            // Check if there isn't already a </option> element\n            if (!rawProvinces.Substring(nextPosition, 8).StartsWith("</option"))\n            {\n                // Add the element\n                rawProvinces = rawProvinces.Insert(nextPosition, "</option>");\n            }\n        }	0
26988107	26988035	WPF DataBinding ListBox in MVVM Pattern	var users = allusersList.Where(a => a.FirstName =="some value").ToList();\nforeach (var item in users)\n{\n      ListBoxDS.Add(new Users { UserID = item.Id, UserName = item.Username,FirstName=item.firstname });\n }	0
10539284	10539057	Binding source to image in button WP7	ContentTemplate="{StaticResource FeaturedBig}"	0
12921001	12920792	C# and sqlite dates, issue with format	public DateTime YourDateTimeProperty\n{\n    get { return _dateTime; }\n    set { _dateTime = value.ToLocalTime(); }\n}	0
1338058	1337109	How do I drive pagination for an infragistics grid in a webpage via watin?	if (Browser.SelectLists.Count > 0)\n    {\n        Browser.SelectLists[0].Select(_rand.Next(1, Browser.SelectLists[0].Options.Count).ToString());\n    }	0
23572166	23571692	Filter a datagrid to a value returned from a bindingNavigator bound to another datasource	private void xBindingSource_CurrentChanged(object sender, EventArgs e)\n    {\n            DataRow dr = (xBindingSource.Current as DataRowView).Row;\n            int id=dr["id"]\n            FilterOtherDataSource(id); //? \n    }	0
25868453	25867926	Accessing generic object in generic list in C#	string s = "";\nfor (int i = 0; i < ListOfGenericClasses.Count; i++)\n{\n    Type type = ListOfGenericClasses[i].GetType();          \n    dynamic d = Convert.ChangeType(ListOfGenericClasses[i], type);\n    s += d.doSomething() + " # ";               \n}	0
31718734	31718586	ObservableCollection Enumerator with filter	var collection = new ObservableCollection<Type>();\npublic IEnumerator<Type> GetEnumerator() {\n    return collection\n        .Where(i => i.Property.State != States.NeedsDelete)\n        .GetEnumerator();\n}	0
19279747	19279554	get the id of the last inserted row in	CREATE PROCEDURE [dbo].[uploadVid]\n    @video varbinary(MAx),\n    @vidTitle varchar(50),\n    @vidCategory varchar(50),\n    @vidDate date,\n    @vidDescription varchar(Max),\n    @vidName varchar(50),\n    @vidSize bigint\nAS\nbegin\n\ndeclare @id as int --assuming your identity column is int\n\nINSERT INTO Video(video, vidTitle, vidCategory, vidDate, vidDescription, vidName, vidSize)\nVALUES (@video, @vidTitle, @vidCategory, @vidDate, @vidDescription, @vidName, @vidSize)\n\nset @id = scope_identity()\nselect @id --return the value for executescaler to catch it\nend	0
31946745	31942753	Calling a stored procedure results in an incorrectly empty DataTable	string ConnectionString = "<Your connection string here>";\nstring procedureName = "<your stored procedure name here>";\nstring ParamName = "@<Parameter name>"; // NOTE: the '@' is INSIDE the string!\nDataSet ds = new DataSet();\n\nusing (var connection = new SqlConnection(ConnectionString))\n{\n    var cmd = new SqlCommand(procedureName, connection);\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.Parameters.Add(ParamName, SqlDbType.Int).Value = 5;\n\n    using (var adapter = new SqlDataAdapter(cmd))\n    { \n        adapter.Fill(ds);\n    }\n}	0
1685496	1685489	get ip address of web user	Request.ServerVariables["REMOTE_ADDR"]	0
16466409	16465960	C# 2D array with string keys and int values	d = new Dictionary<string, Dictionary<string, int>>();	0
1815164	1815148	Need an advice regarding accessing the database	public IQueryable<Comment> GetCommentsByAuthor(Author author) {\n    return GetComments().Where(comment => comment.Author.Id == author.Id);\n}	0
30125345	30124816	WPF - Need to drag in text from notepad and then call a method	string itemID = e.Data.GetData(DataFormats.Text).ToString().Trim();	0
7910334	7910005	How do I return a conditional list from a web service in ASP.NET?	public class Pair\n{\n     public string ID { get; set; }\n     public string Name { get; set; }\n}\n\n[WebMethod]\npublic IList<Pair> SkillsList(string like)\n{\n    IList<Skills> mySkills = new List<Skills>();\n    IList<Pair> output = new List<Pair>();\n    mySkills = Skills.GetSkillsList(like);\n\n    foreach(Skills currentSkill in mySkills)\n    {\n        Pair p = new Pair();\n        p.ID = currentSkill.ID;\n        p.Name = currentSkill.Name;\n\n        output.Add(p);\n    }\n\n    return output;\n}	0
8004778	8004728	how many webservices	the notion that "many client specific interfaces are better than one general purpose interface."	0
28749915	28749222	How to parse this specific XML to grab the FULLNAME node, in C#?	void Main()\n{\n    var data = @"<ns1:MT_Get_Name_Res xmlns:ns1=""http://hse.pd.com"">\n    <fullname>Gandalf Elizabeth Cfieulle02</fullname>\n    <error>Success</error>\n</ns1:MT_Get_Name_Res>";\n\n    var xdoc = XDocument.Parse(data);\n    Console.WriteLine(xdoc.ToString());\n\n    XNamespace ns = "http://hse.pd.com";\n    var result = xdoc.Element(ns + "MT_Get_Name_Res").Element("fullname").Value;\n    Console.WriteLine(result);\n\n    Console.ReadLine();\n}	0
15582499	15582441	How to get INDEX of word inside a string	static void Main(string[] args)\n    {\n        String testing = "text that i am looking for";\n        Console.Write(testing.IndexOf("looking") + Environment.NewLine);\n        Console.WriteLine(testing.Substring(testing.IndexOf("looking")));\n\n        Console.ReadKey();\n\n    }	0
29289827	29289794	List Orderby property from nullable object	data.OrderBy(c => c.obj != null? c.obj.Name : "");	0
8615684	8615622	Double serialization customization	public class SomeClass \n{ \n   private double _someValue;\n\n   [XmlIgnore()]\n   public double SomeValue {\n     get { return _someValue; }\n     set {_someValue = value;}\n   } \n\n   [XmlElement("SomeValue")]\n   public double SomeValueSerialised\n   {\n      get { return _someValue * 10; }\n      set { _someValue = value/10; }\n   }\n}	0
15427838	15427777	date setting in datetime picker	dtpSaudaDate.value.Date.ToString("dd MMM yyyy");	0
10357167	10357150	Exception while converting String to integer in C#	int.TryParse	0
3710573	3710397	Splitting up a .NET solution/Git repo for multiple apps	mainapp\n \mainappdir\n   \somefiles\n    ...\n|\n|\n \library1\n|\n \library2	0
11960853	11960811	Update value in c# dictionary object if value is something	var itemsToEdit = Section.Where(kvp => kvp.Value == 2).Select(kvp => kvp.Key).ToList();\nforeach(var item in itemsToEdit)\n     Section[item] = 1;	0
19574168	19573958	What's the best way to strip a href from a fragment of html code?	string s = "<p>???<a href=\"/es-es/Documents/test.txt\"><img class=\"ms-asset-icon ms-rtePosition-4\" src=\"/_layouts/15/images/ictxt.gif\" alt=\"\" />test.txt</a><a href=\"/es-es/Documents/test%20-%20Copy.txt\"><img width=\"16\" height=\"16\" class=\"ms-asset-icon ms-rtePosition-4\" src=\"/_layouts/15/images/ictxt.gif\" alt=\"\" />test - Copy.txt</a><a href=\"/es-es/Documents/test%20-%20Copy%20(2).txt\"><img width=\"16\" height=\"16\" class=\"ms-asset-icon ms-rtePosition-4\" src=\"/_layouts/15/images/ictxt.gif\" alt=\"\" />test - Copy (2).txt</a></p>";\nvar xdoc = XDocument.Parse(s);\n            xdoc.Descendants("a")\n            .Attributes("href")\n            .Remove();\n        Console.WriteLine(xdoc.ToString());	0
5185449	5185402	linq where statement with OR	using (MyDataContext TheDC = new MylDataContext())\n{\n   var TheOutput = from a in TheDC.MyTable\n     where a.UserID == TheUserID &&   \n     (a.Date1.Month == TheDate.Month && a.Date1.Year == TheDate.Year)\n     ||\n     ( a.Date2.Month == TheDate.Month && a.Date2.Year == TheDate.Year)\n     group a by a.Date1.Date AND by a.Date2.Date into daygroups\n     select new MyModel{...};	0
3429847	3429788	How to remove a custom item from a listBox and ObservableCollection when click on a button	private void removeError_Click(object sender, RoutedEventArgs e) {\n    FrameworkElement fe = sender as FrameworkElement;\n    if (null != fe) {\n        _observableCollection.Remove((YourType)fe.DataContext);\n\n    }\n}	0
9559555	9559499	string.split for alternating characters in c#	var a = new string(source.Where((c,i) => i % 2 == 0).ToArray());\nvar b = new string(source.Where((c,i) => i % 2 != 0).ToArray());	0
30638326	30637070	Data type Mismatch in criteria expression in MS Accss2010	dateOfMove = Convert.ToDateTime(dateTimePickerDateOfMove.Text);	0
13784373	13784326	Tasks in array -- only last one runs	public static void StartTasks()\n{\n    Task[] tasks = new Task[10];\n    for (int i = 0; i < 10; i++) {\n        int j = i;\n        tasks[i] = new Task(() => Console.WriteLine(j));\n    }\n\n    foreach (Task task in tasks)\n    {\n        task.Start();                       \n    }       \n}	0
8571075	8570766	How to get alert message before redirect a page	ScriptManager.RegisterStartupScript(this, this.GetType(), \n"alert", \n"alert('User details saved sucessfully');window.location ='frmDisplayUsers.aspx';", \ntrue);	0
5334707	5334678	Get windows explorer font size of current user using C#	string name = SystemFonts.IconTitleFont.FontFamily.Name;\nfloat size = SystemFonts.IconTitleFont.Size;	0
26275641	26275440	How to get a comma separated double value in a string with Regex?	Match m = Regex.Match(xml, @"LatLng\(([\d\.]+)\,\s*([\d\.]+)\)");\n    if(m.Success)\n    {\n        Trace.WriteLine(string.Format("Lat:{0} - Lng:{1}", m.Groups[1].Value, m.Groups[2].Value));\n    }	0
4044839	4044796	Explicitly implementing an interface with an abstract method	bool MyInterface.Foo() {\n    return FooImpl();\n}\n\nprotected abstract bool FooImpl();	0
8744822	8744762	How to parse a string to DateTime	var str = "Thu Jan 5 19:58:58 2012";\nDateTime date;\nif (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))\n{\n    // the date was successfully parsed, you could use the date variable here\n    Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);\n}	0
9159810	9158447	Issue related to getting data from persistance class in XPO	// change typelist index as needed \nType xpQueryGenericType = typeof (XPQuery<>).MakeGenericType(typelist[0]);\nvar xpQueryInstance = Activator.CreateInstance(xpQueryGenericType, new object[]{xpoSession});	0
14018450	14001499	Devexpress SearchLookUpEdit get column value	object marketId = this.searchLookUpEdit1.Properties.View.GetFocusedRowCellValue("MarketId");	0
20647989	20588293	FluentNhibernate + private set	private string name;\n\npublic string Name\n{\n  get { return name; }\n}	0
23963083	23962988	making thread safe calls to controls	Action task = () => {\n    gvTaskCases.DataSource = null;\n\n    if (gvTaskCases.Rows.Count != 0) // EXCEPTION IS THROWN HERE!\n    {\n        gvTaskCases.Rows.Clear(); // .Update();\n    }\n};\n\nif(gvTaskCases.InvokeRequired) {\n    gvTaskCases.Invoke(task);        \n}\nelse {\n    task();\n}	0
4309131	4308995	Generic function to create controls at runtime	T AddControl<T>() where T : WebControl, new()\n{\n    T ctrl = new T();\n    ...\n    return ctrl;\n}	0
11308794	11308749	Convert Generic List<string> to byte[ ]	byte[] dataAsBytes = lines.SelectMany(s => Text.Encoding.UTF8.GetBytes(s))\n  .ToArray();	0
11535150	11396975	Set the highlighted item in the comboBox's dropdown list as the current value on cell exit or cell leave	private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n        {\n            if (dataGridView1.IsCurrentCellDirty)\n            {\n                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n            }\n        }	0
14955976	14955885	Contra variance with interfaces	List<IExportColumn> list= new List<IExportColumn>();\n// you may add to the collection any class which implements IExportColumn\nlist.Add(new ExportColumn1() { ColumnName = "Id" });\nlist.Add(new ExportColumn2() { ColumnName = "Value" });\n\nExportColumnCollection<IExportColumn> collection = new \n    ExportColumnCollection<IExportColumn>(list);\nvar colInfo = collection.ColumnInfo("Id");	0
18113315	18113231	Select XML Nodes by Attribute Value	XDocument doc = XDocument.Parse(crtCommand.ExecuteScalar().ToString());\nXNamespace ns = "http://xmlns.oracle.com/ku";\n\nif (doc.Descendants(ns + "COL_LIST_ITEM").Any(c => c.Attributes().Any()))\n    Console.WriteLine("COL_LIST has value");	0
9065677	9065315	Exception in one DNN module prevents processing all other modules on page	try\n{\n    //BLAH\n}\ncatch (Exception exc) //Module failed to load\n{\n    Exceptions.ProcessModuleLoadException(this, exc);\n}	0
5698581	5698229	design pattern so that a static init method is always called before a call to static method	class StaticClass {\n    public static void m1 () {\n      new Worker().m1();\n    }\n    public static void m2 () {\n      new Worker().m2();\n    }\n}\n\nclass Worker {\n   public Worker() {\n     intialize();\n   }\n   public void m1() {\n     // Real m1 work\n   }\n   public void m2() {\n     // Real m2 work\n   }\n}	0
5901175	5901117	Turning a single radian value into a Vector Direction	( Math.Cos(rotation), Math.Sin(rotation) )	0
1422993	1422968	How to retrieve the source property from a table?	var tableType = db.MyTable.GetType().GetGenericArguments().First();\n        foreach (TableAttribute attrib in tableType.GetCustomAttributes(false))\n        {\n            Console.WriteLine(attrib.Name);\n        }	0
627931	627428	How can I overcome late binding in Active Directory search	// create a principal object representation to describe\n// what will be searched \nUserPrincipal user = new UserPrincipal(adPrincipalContext);\n\n// define the properties of the search (this can use wildcards)\nuser.Enabled = false;\nuser.Name = "user*";\n\n// create a principal searcher for running a search operation\nPrincipalSearcher pS = new PrincipalSearcher();\n\n// assign the query filter property for the principal object \n// you created\n// you can also pass the user principal in the \n// PrincipalSearcher constructor\npS.QueryFilter = user;\n\n// run the query\nPrincipalSearchResult<Principal> results = pS.FindAll();\n\nConsole.WriteLine("Disabled accounts starting with a name of 'user':");\nforeach (Principal result in results)\n{\n    Console.WriteLine("name: {0}", result.Name);\n}	0
13561836	13561789	C# arranging string variables in some container	string[] texts = { textbox1.Text, textbox2.Text, textbox3.Text, textbox4.Text };\n\nbool[] checks = { checkBox1.Checked, checkBox2.Checked, checkBox3.Checked };	0
21432268	21431732	Export a list of methods & params in library to a text file	StringBuilder sb = new StringBuilder();\nvar type = typeof (MyMath);\nsb.AppendFormat("Class Name: {0}", type.Name);\nsb.AppendLine();\nsb.Append("Methods: ");\nsb.AppendLine();\nforeach (var method in type.GetMethods())\n{\n     sb.AppendFormat("{0} {1}.{2}( ", method.ReturnType.Name, type.Name, method.Name);\n     foreach (var param in method.GetParameters())\n     {\n         sb.AppendFormat("{0} {1},", param.GetType().Name, param.Name);\n     }\n     sb.Remove(sb.ToString().Length - 1, 1);\n     sb.Append(")");\n     sb.AppendLine();\n}\n\n var content = sb.ToString();\n File.WriteAllText("deneme.txt",content);	0
5897114	5895952	How do I parse this xml?	List<string> returnList = new List<string>();\nXmlNodeList node = xmlDocument.GetElementsByTagName("DebugUsersMail");\nXmlNodeList childNodes = node[0].ChildNodes;\nfor(int i = 0; i < childNodes.Count; i++)\n{\n   returnList.Add(childNodes[i].InnerText);\n}\nreturn returnList;	0
20109357	20108751	Verifying that a multidimensional array contains a pair of values	string[,] UserPass = new string[,] {{"user1","pwd1"}, {"user2.edu", "pwd2"}, {"user3","pwd3"}};\n   ...\n    bool isFound = false;\n    for (int i=0;  i< UserPass.GetLength(0); i++)\n    {\n        //search users row by row\n        if (UserPass[i, 0] == yourSearchUserid && UserPass[i, 1] == yourSearchPassword)\n        {\n            isFound = true;\n            break;\n        }   \n    }\n    //isFound holds the search result.	0
15601276	15601168	read number from a text file and replace with a something else	// assume that System.IO is included (in a using statement)\n// reads the file, changes all leading integers to "Number", and writes the changes\nvoid rewriteNumbers(string file)\n{\n    // get the lines from the file\n    string[] lines = File.ReadAllLines(file);\n    // for each line, do:\n    for (int i = 0; i < lines.Length; i++)\n    {\n        // trim all number characters from the beginning of the line, and\n        // write "Number" to the beginning\n        lines[i] = "Number" + lines[i].TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');\n    }\n    // write the changes back to the file\n    File.WriteAllLines(file, lines);\n}	0
29375535	29373185	How can I use my class properties in my Linq query with group by statement?	Name = (from gx in g select gx.Name).FirstorDefault();	0
27472302	27468257	How to convert/cast IQueryable<AnonymousType> to IQueriable<Strong Typed Object> with lambda expressions	int id = 1;\n    var db = new Project.Models.Context();\n    var query1 = db.Users.Where(t => t.id == id);\n    //here is where the problem starts\n    IQueryable<Project.Models.test> test = query1.Join(db.Table2,\n                users => users.id,\n                table2 => table2.userId,\n                (users, table2) => new Project.Models.test()\n                {\n                    columName1 = users.UserName,\n                    columName2 = table2.SomeValue\n                });	0
20303302	20302776	How to get route parameter in JavaScript?	function getValueAtIndex(index){\n    var str = "http://www.sample.com/234/Fiddle/test"; //window.location.href; \n    return str.split("/")[index];\n}\nconsole.log(getValueAtIndex(3));	0
8770832	8770577	How To Cast Ilist To ArrayList?	IList iList = new ArrayList();	0
4764377	4764335	Need SQL help with copying rows	INSERT INTO table1 (col1, col2, col3)\nSELECT (col1, col2, col3) FROM table1\nWHERE ....	0
541815	541797	Need to implement a finalizer on a class that uses TcpClient?	protected virtual void Dispose(bool disposing)\n{\n   if (disposing)\n   { \n      // dispose managed resources (here your TcpClient)\n   }\n\n   // dispose your unmanaged resources \n   // handles etc using static interop methods.\n}	0
9086027	9083802	Entity Framework, get ConcurrencyMode of Properties from MetadataWorkspace, how?	[EntityContext] etContext = new [EntityContext]();\nvar csdl = etContext.MetadataWorkspace.GetItemCollection(DataSpace.CSpace);\nvar entity = csdl.GetItems<EntityType>().Where(e => e.Name = [EntityType]).SingleOrDefault();\nvar edmProperty = entity.Properties.Where(p => p.Name == [PropertyName]).SingleOrDefault();\nvar mode = edmProperty.TypeUsage.Facets.Where(f => f.Name ==     "ConcurrencyMode").SingleOrDefault();	0
8430330	8430165	how to get DataGridViewColumns out of IOrderedEnumerable with DataGridviewCell's?	var firstColumnIndex = q.Min(c => c.ColumnIndex);\nvar lastColumnIndex = q.Max(c => c.ColumnIndex);	0
24385313	24328918	MSChart how to change spacing between dashes of a series	private void SetChartTransparency(Chart chart, string Seriesname)\n    {\n        bool setTransparent = true;\n        int numberOfPoints = 3;          \n        chart.ApplyPaletteColors();\n        foreach (DataPoint point in chart.Series[Seriesname].Points)\n        {\n            if (setTransparent)\n                point.Color = Color.FromArgb(0, point.Color);\n            else\n                point.Color = Color.FromArgb(255, point.Color);\n            numberOfPoints = numberOfPoints - 1;\n            if (numberOfPoints == 0)\n            {\n                numberOfPoints = 3;\n                setTransparent = !setTransparent;\n            }         \n        }     \n    }	0
9772237	9588805	FBA login page issue in SharePoint	FormsAuthentication.SignOut();\nFormsAuthentication.RedirectToLoginPage();	0
29216577	29196340	How to call a Gridview cell click Event from button Click	public static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs\n    {\n        var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);\n        if (eventDelegate != null)\n        {\n            foreach (var handler in eventDelegate.GetInvocationList())\n            {\n                handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });\n            }\n        }\n    }	0
9302832	9302759	How to find the checked radio button in a subset container?	foreach (Control c in TypeStep.Controls)\n{\n    foreach (RadioButton rb in c.Controls.OfType<RadioButton>())\n    { \n          ... \n    }     \n}	0
20262001	20261523	Detect number of display monitor	"SELECT * FROM Win32_PnPEntity WHERE Service = 'monitor'"	0
12116529	12116098	using c# to select a worksheet in excel	Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);\nxlWorkSheetFocus.Activate();	0
8497588	8497573	How to use LINQ to only select if no results exist in related table?	ddNewApiUserParentUser.DataSource = \n    from u in dbc.aspnet_UsersInRoles\n    where u.aspnet_Role.RoleName == "ProductOwner" &&\n        !u.aspnet_User.ApiUsers.Any()\n    select new { u.aspnet_User.UserId, u.aspnet_User.UserName };	0
29512761	29512573	How to left join to another left join	var result = from item in db.Items\n          group item by new { item.BrandId, item.ModelId, item.TotalPrice }\n          into gr\n          select new \n          {\n              gr.Key.BrandId,\n              gr.Key.ModelId,\n              gr.Key.TotalPrice,\n              CountA = gr.Count(it => it.StoreId == 1),\n              CountB = gr.Count(it => it.StoreId == 2),\n          }	0
7959756	7944466	strange behaviour with a tableviewcontroller	enabled=false	0
4168472	4168286	How to bind SelectedItem (from a ListBox) to a Variable?	SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"	0
28965641	28945802	Get PDF be written in the center of the page itextsharp	// loop over document pages\nfor (int i = 1; i <= pages; i++)\n{\n    doc.NewPage();\n    page = writer.GetImportedPage(reader, i);\n\n    if (i == 1)\n    {\n        cb.AddTemplate(page, 0, 0);\n    }\n    else\n    {\n        float page1Height, page1Width, page2Height, page2Width;\n        page1Height = reader.GetPageSizeWithRotation(i - 1).Height;\n        page1Width = reader.GetPageSizeWithRotation(i - 1).Width;\n        page2Height = reader.GetPageSizeWithRotation(i).Height;\n        page2Width = reader.GetPageSizeWithRotation(i).Width;\n        cb.AddTemplate(page, (page1Width - page2Width) / 2, (page1Height - page2Height) / 2);\n    }\n}	0
1411310	1411286	How to Unit test BackgroundWorker C#	[TestMethod]\npublic void Test()\n{   \n    bool running = true;\n    string result = null;\n\n    Action<string> cb = name =>\n    {\n        result = name;\n        running = false;\n    };\n\n    var d = new MyClass();\n    d.Get("test", cb);\n\n    while(running)\n    {\n        Thread.Sleep(100);\n    }\n\n    Assert.IsNotNull(result);\n}	0
30319552	30319070	REST WCF service - differences data input format (JSON/XML)	[OperationContract]\n    [WebInvoke(Method = "POST",\n        RequestFormat = WebMessageFormat.Json,\n        ResponseFormat = WebMessageFormat.Json,\n        UriTemplate = "json")]\n    void AddUsefulLinkJson(UsefulLinksWCF.Models.UsefulLink link);\n\n    [OperationContract]\n    [WebInvoke(Method = "POST",\n        RequestFormat = WebMessageFormat.Xml,\n        ResponseFormat = WebMessageFormat.Xml,\n        UriTemplate = "xml")]\n    void AddUsefulLinkXml(UsefulLinksWCF.Models.UsefulLink link);	0
22666725	22666138	Compare 2 Datatables to find difference/accuracy between the columns	var tableC = new DataTable();\ntableC.Columns.Add(new DataColumn("ID"));\ntableC.Columns.Add(new DataColumn("Name"));\ntableC.Columns.Add(new DataColumn("TableAValue1"));\ntableC.Columns.Add(new DataColumn("TableBValue1"));\ntableC.Columns.Add(new DataColumn("DiffValue1"));\nforeach (DataRow rowA in tableA.Rows)\n{\n    foreach (DataRow rowB in tableB.Rows)\n    {\n        if (Convert.ToInt32(rowA["ID"]) == Convert.ToInt32(rowB["ID"]) &&\n            rowA["Name"].ToString() == rowB["Name"].ToString() &&\n            Convert.ToInt32(rowA["Value1"]) != Convert.ToInt32(rowB["Value1"]))\n        {\n            var newRow = tableC.NewRow();\n            newRow["ID"] = rowA["ID"];\n            newRow["Name"] = rowA["Name"];\n            newRow["TableAValue1"] = rowA["Value1"];\n            newRow["TableBValue1"] = rowB["Value1"];\n            newRow["DiffValue1"] = Convert.ToInt32(rowA["Value1"]) - Convert.ToInt32(rowB["Value1"]);\n            tableC.Rows.Add(newRow);\n        }\n    }\n}	0
11816820	11816728	draw and remove a line with gdi+	Bitmap bmp;\nbool isDrawing;\nPoint previous;\n\nvoid pictureBox1_MouseDown(object sender, MouseEventArgs e)\n{\n    isDrawing = true;\n    previous = e.Location;\n}\n\nvoid pictureBox1_MouseUp(object sender, MouseEventArgs e)\n{\n    isDrawing = false;\n}\n\nvoid pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    if (isDrawing)\n    {\n        using (Graphics g = Graphics.FromImage(bmp))\n        {\n            double wf = (double)bmp.Width / (double)pictureBox1.Width;\n            double hf = (double)bmp.Height / (double)pictureBox1.Height;\n            g.ScaleTransform((float)wf, (float)hf);\n            g.DrawLine(Pens.Black, e.Location, previous);\n        }\n\n        pictureBox1.Refresh();\n        previous = e.Location;\n    }\n}	0
10708732	10704621	Comparing values from dataGridView tables in VS2010 - C#	private void button7_Click(object sender, EventArgs e)\n{\n    double s = double.Parse(dataGridView1.Rows[1].Cells[1].Value.ToString());\n    double t = double.Parse(dataGridView2.Rows[0].Cells[6].Value.ToString());\n    double k = double.Parse(dataGridView3.Rows[0].Cells[1].Value.ToString());\n    double l = double.Parse(dataGridView4.Rows[0].Cells[4].Value.ToString());\n    double m = double.Parse(dataGridView5.Rows[0].Cells[2].Value.ToString());\n    double n = double.Parse(dataGridView6.Rows[0].Cells[3].Value.ToString());\n\n    double[] kupoven = new double[] { s,t,k,l,m,n};\n    double max = kupoven.Max();\n}	0
11879485	11879153	translate xml file to text	//inform the user\n            string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty);\n            textboxError.Text = Server.HtmlEncode( result);	0
14283564	14283430	Render Properties as XMLAttributes in ASP.NET Web API response	public class Foo<T>\n{\n    [XmlText]\n    public T Value;\n    [XmlAttribute]\n    public int LastModified;\n}\n\npublic class User\n{\n    public Foo<string> FirstName;\n    public Foo<string> LastName;\n}	0
27126678	27125732	Updating cache object that contains collection of employees	var empToUpdate = AllEmployees.FirstOrDefault(i => i.EmpId== Employee.EmpId);\n   if (empToUpdate != null)\n   {\n      AllEmployees = AllEmployees.Except(new[]{empToUpdate}).Concat(new[] { empToUpdate});\n  }	0
246700	246520	How do I find a user's Active Directory display name in a C# web application?	private static string GetFullName()\n    {\n        try\n        {\n            DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);\n            return de.Properties["fullName"].Value.ToString();\n        }\n        catch { return null; }\n    }	0
8018432	8018174	How to store entities context query object into generic list?	contexti.Load<tblAdmin>(query).Completed += (sender, args) =>\n{\n    List<AdminInfo> list = new List<AdminInfo>();\n\n    //for each entity returned, create a new AdminInfo and add it to the list\n    foreach (var item in ((LoadOperation<Car>)sd).Entities)\n    {\n        list.Add(new AdminInfo(){ AdminId = item.AdminId, AFirtsName = item.FirstName /*other properties*/});\n    }\n\n}	0
14049488	14049469	Convert If Statement into Switch	if (rResponse.ErrorCode[0] == 0x20) {\n  switch(rResponse.ErrorCode[1]) {\n    case 0x03:\n      ErrorMsg = "COMM_FRAME_ERROR";\n      break;\n    case 0x04:\n      ErrorMsg = "JAM";\n      break;\n    case 0x05:\n      ErrorMsg = "NO_CARD";\n      break;\n  }\n}	0
3802365	3802301	Programmatically change Windows power settings	Application.SetSuspendState	0
31769065	31768739	WPF enlarge a rectangle using storyboard	DoubleAnimation widthAnimation = new DoubleAnimation\n        {\n            From = 0,\n            To = rect1.ActualWidth*2,\n            Duration = TimeSpan.FromSeconds(5)\n        };\n\n        DoubleAnimation heightAnimation = new DoubleAnimation\n        {\n            From = 0,\n            To = rect1.ActualHeight*2,\n            Duration = TimeSpan.FromSeconds(5)\n        };\n\n        Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(Rectangle.WidthProperty));\n        Storyboard.SetTarget(widthAnimation, rect1);\n\n        Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(Rectangle.HeightProperty));\n        Storyboard.SetTarget(heightAnimation, rect1);\n\n        Storyboard buttonEnlargeStoryboard = new Storyboard();\n        buttonEnlargeStoryboard.SpeedRatio = 1;\n        buttonEnlargeStoryboard.Children.Add(widthAnimation);\n        buttonEnlargeStoryboard.Children.Add(heightAnimation);\n        buttonEnlargeStoryboard.Begin();	0
34295368	34295174	Insert rows into table based on checkboxes in a Repeater	sqlCmd2.Parameters.Clear(); // Add This line\nsqlCmd2.Parameters.Add("@EventId", SqlDbType.Int).Value = 2;\nsqlCmd2.Parameters.Add("@FormId", SqlDbType.Int).Value = 2;\nsqlCmd2.Parameters.Add("@ColumnName", SqlDbType.NVarChar).Value = lbl.Text;\nsqlCmd2.Parameters.Add("@DisplayName", SqlDbType.NVarChar).Value = lbl.Text;\nsqlCmd2.Parameters.Add("@Visible", SqlDbType.Bit).Value = 1;\nsqlCmd2.Parameters.Add("@ColumnOrder", SqlDbType.NVarChar).Value = i;\nsqlCmd2.ExecuteNonQuery(); // Add This line	0
31816946	31816891	Creating a radiobutton list for Enums that can be nullable	var myEnum = Nullable.GetUnderlyingType(metaData.ModelType) ?? metaData.ModelType;\nvar listOfValues = Enum.GetNames(myEnum);	0
26388583	26388263	Randomly choose uniformly distributed numbers in c#	Random r = new Random();\n        int N = 10;\n        Dictionary<string, string> d = new Dictionary<string,string>();\n        while (true) {\n            int x = r.Next(0, N - 1);\n            int y = r.Next(0, N - 1);\n            string s = x + "." + y;\n            if (!d.ContainsKey(s)) {\n                d[s] = s;\n                Console.WriteLine("Keys = " + d.Keys.Count);\n            }\n        }	0
2296876	2296850	Get the implemented type from a Generic Base Class	this.GetType()	0
23320086	23319961	how can i declare varchar column value in database to be readed by Double array?	double[] tmpArray = StringToDoubleArray("12,13,14");\n\n private static double[] StringToDoubleArray(string strNumbers)\n        {\n            List<double> dblValues = new List<double>();\n            Array.ForEach(strNumbers.Split(",".ToCharArray()), s =>\n            {\n                double currentDouble;\n                if (Double.TryParse(s, out currentDouble))\n                    dblValues.Add(currentDouble);\n            });\n            return dblValues.ToArray();\n        }	0
12156642	12143935	Using Mono packages from badgerports, getting an exception on runtime	MONO_LOG_LEVEL="debug" mono your_software.exe	0
20613399	20545931	TeeChart - Pie or Donut labelling the inside pie of a donut	private void InitializeChart()\n{\n  Donut series = new Donut(tChart1.Chart);\n  series.FillSampleValues();\n  series.Marks.Visible = true;\n  series.Marks.Transparent = true;\n  series.Marks.Arrow.Visible = false;\n  series.Marks.ArrowLength = -10;\n}	0
16894762	16894684	Randomly generating @param names for inserting into sql query	int counter=0;\nWhile(blah blah)\n{\n  if (bVisitorPhoto != null)\n  {\n    string Picture = photo+counter.ToString();\n    SqlParameter picparameter = new SqlParameter();\n    picparameter.SqlDbType = SqlDbType.Image;\n    picparameter.ParameterName = Picture;\n    picparameter.Value = bVisitorPhoto;\n    command.Parameters.Add(picparameter);\n    VisitorPhoto = "@"+Picture;\n  }\n  string query = "insert into table Values (Picture, "PersonName");       \n  counter++;\n}	0
18393758	18393707	Regex, start with capital letters in Xpath	SelectNodes("//*[matches(text(), '^[A-Z]')]");	0
8806274	8806021	How to handle Nullable<T> types returned from stored proc?	default(type)	0
14495797	14495679	How to convert DataTable to List<KeyValuePair<string, int>>	List<KeyValuePair<String, int>> test = new List<KeyValuePair<string, int>>();\n    foreach (DataRow dr in dt.Rows)\n    {\n        test.Add(new KeyValuePair<string, int>(dr[0].ToString(), Convert.ToInt16(dr[3])));\n    }	0
28656046	28656034	Get a list of unique strings from duplicate entries	var foo = list.Select(p => p.name).Distinct().ToList();	0
16227839	16227778	C# - XML serialize a complex class as only its primitive type	public class B {\n  private A<int> intVal;\n  public int IntVal{\n    get{\n      return intVal.obj;\n    }\n    set{\n      intVal.obj = value;\n    }\n  }\n\n  // same for stringval\n}	0
6325448	6325354	How to determine if the current application is Medium Trust	AspNetHostingPermissionLevel GetCurrentTrustLevel() {\n  foreach (AspNetHostingPermissionLevel trustLevel in\n      new AspNetHostingPermissionLevel [] {\n        AspNetHostingPermissionLevel.Unrestricted,\n        AspNetHostingPermissionLevel.High,\n        AspNetHostingPermissionLevel.Medium,\n        AspNetHostingPermissionLevel.Low,\n        AspNetHostingPermissionLevel.Minimal \n      } ) {\n    try {\n      new AspNetHostingPermission(trustLevel).Demand();\n    }\n    catch (System.Security.SecurityException ) {\n      continue;\n    }\n\n    return trustLevel;\n   }\n\n   return AspNetHostingPermissionLevel.None;\n}	0
30706576	30706387	C# Apply regex only if property has value	// Define other methods and classes here\npublic static ProjectListItemViewModel CreateViewModel(P.Project project)\n{\n    var rex = new Regex(@"<[^>]+>|&nbsp;");\n    var expected = rex.Replace(project.ExpectedResult ?? string.Empty, string.Empty).Trim();\n\n    return new ProjectListItemViewModel\n    {\n        Id = project.Id,\n        ExpectedResult = expected.Length > 100 ? expected.Length.Substring(0, 100) : expected,\n        Initiator = project.Initiator.FullName,\n        Status = project.Status.Name,\n        ProjectManager = project.ProjectManager != null ? project.ProjectManager.FullName : "",\n    };\n}	0
6275945	6275837	add namespace using xmlnamespacemanager in C#	var doc = new XmlDocument();\ndoc.Load(source);\nvar nsmgr = new XmlNamespaceManager(doc.NameTable);\nnsmgr.AddNamespace("app", "http://www.weather.gov/forecasts/xml/OGC_services");\nvar firstPoint = doc.SelectSingleNode("//app:Forecast_Gml2Point", nsmgr);	0
6846863	6692208	Linq to xml select most frequent value	var code = btCheck.Descendants("ADSL_CHECKER").Elements("ADDRESS_DETAILS")\n            .Elements("ADDRESS_DETAIL").Elements("ADDRESS").Elements("DISTRICTID")\n            .GroupBy(z => z.Value).Select(group => new\n            {\n                value = group.Key,\n                Count = group.Count()\n            })\n            .OrderByDescending(z => z.Count).FirstOrDefault();	0
5432095	5428861	Clear MenuItem, with clear command	private void ClearCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)\n    {\n        // e.Source is the element that is active,\n        if (e.Source is TextBox) // and whatever other logic you need.\n        {\n            e.CanExecute = true;\n            e.Handled = true;\n        }\n    }\n\n    private void ClearCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)\n    {\n        var textBox = e.Source as TextBox;\n        if (textBox != null)\n        {\n            textBox.Clear();\n            e.Handled = true;\n        } \n    }	0
9354580	9354561	Cannot combine strings when they contain '{}' chars	string test = string.Format("{{img: \"{0}\", html: \"{1}\"}}", "images/a.png", "<div></div>");	0
18190642	18190522	Add radio button list items programmatically in asp.net	protected void Page_Load(object sender, EventArgs e)\n{\n    radio1.Items.Add(new ListItem("Apple", "1"));\n}	0
4233375	4232616	Add Row To Bound DGV By Textbox	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if ((Keys)e.KeyChar == Keys.Enter) \n        {\n\n                bindingsource2.ResumeBinding (); // OR bindingsource2.SuspendBinding();       \n                int i = dataGridView1.CurrentCell.RowIndex;\n                dataGridView1[1, i].Value = textBox1.Text;\n                dataGridView1.Focus();\n\n        }\n\n    }	0
15131888	15131687	A view that was not created gets displayed	return View("Index", m)	0
29304059	29303725	Insert Statement Using Same Variable Multiple Times	var teacher = "Mrs Hart";\nvar grades = new[]{ "1st", "2nd", "3rd", "4th", "5th" };\nvar sql = "INSERT INTO tbl_TeacherInfo (Teacher,Grade) "\n        + "VALUES (@Teacher, @Grade)";\n\nusing (var conn = new SqlConnection(/* connectionString */))\n{\n  conn.Open(); // Open once and share it\n\n  // share the command\n  using (var cmd = new SqlCommand(sql, conn))\n  {\n    // assign the shared value across all queries, and\n    // add a placeholder for the revolving parameter\n    cmd.Parameters.AddWithValue("@Teacher", teacher);\n    cmd.Parameters.AddWithValue("@Grade", String.Empty); // placeholder\n\n    // iterate over the grades (1st, 2nd, etc.)\n    foreach (var grade in grades)\n    {\n      cmd.Parameters["@Grade"].Value = grade; // change @Grade\n      cmd.ExecuteNonQuery(); // Execute with these two values\n    }\n  }\n\n  conn.Close(); // cleanup\n}	0
17155697	17155028	Can i use LINQ to populate an ObservableCollection of ObservableCollection	var child3 = observableOfClassA\n            .SelectMany(a => a.classBItems) // flattens list to all classBItems\n            .SelectMany(b => b.classBSubItems) // flattens list to classBItems.classBSubItems\n            .Where(bSub => bSub.name == "child3s Name goes here")  // replace with your where clause\n            .FirstOrDefault();	0
2905095	2905080	How to return string from a button click handler?	private void folderPathButton_Click(object sender, EventArgs e)\n{\n    browseAndStuff();\n}\n\nprivate string browseAndStuff()\n{\n    FolderBrowserDialog folderBrowser = new FolderBrowserDialog();\n    folderBrowser.ShowDialog();\n    string folderPath = folderBrowser.SelectedPath;                 \n    return folderPath;           \n}	0
16281691	16281621	How to check for default DateTime value?	// Or private, or maybe even public\ninternal static readonly DateTime MagicValueForNullDateTimeInNonNullableColumns\n    = DateTime.MinValue;	0
26750106	26744967	FileSystemWatcher missing file changes from other program	// Tried FileSystemWatcher, but it was far too unreliable.	0
6498287	6498251	Query a table that has spaces in its name	[Common station]	0
6444382	3960659	XML Serialization of an Interface	[Serializable]\npublic class Prototype\n{\n    public virtual long Id { get; private set; }\n    public virtual string Name { get; set; }   \n    [XMLIgnore]\n    public virtual IList<AttributeGroup> AttributeGroups { \n        get { return this.AttributeGroupsList; } \n    }\n    public virtual List<AttributeGroup> AttributeGroupsList { get; private set;}\n}	0
6524955	6524934	Deleting items in a list at once by index in c#	foreach (var index in indexesToDelete.OrderByDescending(x => x))\n{\n    list.RemoveAt(index);\n}	0
21452303	16518858	Devexpress FindPanel background color	gridView.ApplyFindFilter(string.Empty);	0
28456384	28455421	Remove tab page from a tab control and display the page as a new Window	private void tabMain_MouseDoubleClick(object sender, MouseEventArgs e)\n{\n    if (tabMain.TabPages.Count > 0)\n    {\n        TabPage CurrentTab = tabMain.SelectedTab;\n        tabMain.TabPages.Remove(CurrentTab);\n        Form newWindow = new Form();\n\n        foreach (Control ctrl in CurrentTab.Controls)\n        {\n            newWindow.Controls.Add(ctrl);\n        }\n\n        newWindow.Show();\n    }\n}	0
8232503	8226877	Trying to get Facebook Cookie from codebehind, but is getting (OAuthException)	var auth = new CanvasAuthorizer { Permissions = new string[] {"user_about_me"} };\nif (auth.Authorize()) {\n    var client = new FacebookClient([App ID], [App Secret]);\n    dynamic me = client.Get("me"); \n    string firstName = me.first_name;\n    Response.Write(firstName);\n}	0
4104138	4104080	How to add reference to a COM component in my project in C#.NET in Visual Studio 2005?	[DllImport("user32.dll", CharSet = CharSet.Auto)]\nstatic extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);	0
20298260	20297973	How to decrypt an AES-256-CBC encrypted string	// Decrypt a string into a string using a key and an IV \npublic static string Decrypt(string cipherData, string keyString, string ivString)\n{\n    byte[] key = Encoding.UTF8.GetBytes(keyString);\n    byte[] iv  = Encoding.UTF8.GetBytes(ivString);\n\n    try\n    {\n        using (var rijndaelManaged =\n               new RijndaelManaged {Key = key, IV = iv, Mode = CipherMode.CBC})\n        using (var memoryStream = \n               new MemoryStream(Convert.FromBase64String(cipherData)))\n        using (var cryptoStream =\n               new CryptoStream(memoryStream,\n                   rijndaelManaged.CreateDecryptor(key, iv),\n                   CryptoStreamMode.Read))\n        {\n            return new StreamReader(cryptoStream).ReadToEnd();\n        }\n    }\n    catch (CryptographicException e)\n    {\n        Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);\n        return null;\n    }\n    // You may want to catch more exceptions here...\n}	0
11797292	11740932	SSRS check if user in group using Custom Assembly	using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Security.Principal;\n\nnamespace SSRS_Custom_Fuctions\n{\n    public class Class1\n    {\n\n        public static bool IsInGroup(string user, string group)\n        {\n\n        System.Security.Permissions.SecurityPermission sp = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted);\n        sp.Assert();\n\n            using (var identity = new WindowsIdentity(user))\n            {\n                var principal = new WindowsPrincipal(identity);\n                return principal.IsInRole(group);\n            }\n        }\n\n        public static string MyTest()\n        {\n            return "Hello World";\n        }\n    }\n}	0
20954436	20953924	Data Table formatting	var q = dt.AsEnumerable().SelectMany(row => row.Field<string>(1).Split(',').Select(col2 => new object[] {row[0],  col2}));\nvar newDt = new DataTable();\n\nforeach (var item in q)\n{\n    newDt.Rows.Add(item);\n}	0
31436764	31436542	Adding a column with empty/null values to an anonymous list	res => new { res.Item1, res.Item2, res.Item3, extraProperty = "" }	0
6016431	6016374	How to maintain tab order after postback	protected void Page_Load(object sender, EventArgs e)\n{\nif (Page.IsPostBack)\n{\nWebControl wcICausedPostBack = (WebControl)GetControlThatCausedPostBack(sender as Page);\nint indx = wcICausedPostBack.TabIndex;\nvar ctrl = from control in wcICausedPostBack.Parent.Controls.OfType<WebControl>()\nwhere control.TabIndex > indx\nselect control;\nctrl.DefaultIfEmpty(wcICausedPostBack).First().Focus();\n}\n}\nprotected Control GetControlThatCausedPostBack(Page page)\n{\nControl control = null;\nstring ctrlname = page.Request.Params.Get("__EVENTTARGET");\nif (ctrlname != null && ctrlname != string.Empty)\n{\ncontrol = page.FindControl(ctrlname);\n}\nelse\n{\nforeach (string ctl in page.Request.Form)\n{\nControl c = page.FindControl(ctl);\nif (c is System.Web.UI.WebControls.Button || c is System.Web.UI.WebControls.ImageButton)\n{\ncontrol = c;\nbreak;\n}\n}\n}\nreturn control;\n}	0
21318924	21318741	Selecting text in a string	string url = textBox2.Text + "&";\n\nint startPos = url.LastIndexOf(textBox1.Text) + textBox1.Text.Length + 1;\nstring firstPartRemoved = url.Substring(startPos, url.Length - startPos);\nint locationOfAnd = firstPartRemoved.IndexOf("&");\nstring sub = firstPartRemoved.Substring(0,locationOfAnd)\n\nClipboard.SetText(sub);	0
12383479	12383351	Enter data to particular column in sql	SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);\nSqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET email = @newEmail WHERE UserID = @userID");\n\ncmd.Connection = conn;\ncmd.CommandType = CommandType.Text;\ncmd.Parameters.AddWithValue("@email", Textbox2.Text);\ncmd.Parameters.AddWithValues("@UserId", YourUserId);\n\nconn.open();\ncmd.ExecuteNonQuery();\nconn.close();	0
626789	626765	Calling base constructor in C#	class Derived : Base\n{\n  public Derived(string someParams)\n    : base("Blah " + someParams)\n  {\n\n  }\n\n}	0
15998634	15998611	need a Regular expression to split string	([a-zA-Z]+)(?:-([a-zA-Z]+)){0,3}	0
1752761	1752494	Detect if any key is pressed in C# (not A, B, but any)	[DllImport("user32.dll", EntryPoint = "GetKeyboardState", SetLastError = true)]\nprivate static extern bool NativeGetKeyboardState([Out] byte[] keyStates);\n\nprivate static bool GetKeyboardState(byte[] keyStates)\n{\n    if (keyStates == null)\n        throw new ArgumentNullException("keyState");\n    if (keyStates.Length != 256)\n        throw new ArgumentException("The buffer must be 256 bytes long.", "keyState");\n    return NativeGetKeyboardState(keyStates);\n}\n\nprivate static byte[] GetKeyboardState()\n{\n    byte[] keyStates = new byte[256];\n    if (!GetKeyboardState(keyStates))\n        throw new Win32Exception(Marshal.GetLastWin32Error());\n    return keyStates;\n}\n\nprivate static bool AnyKeyPressed()\n{\n    byte[] keyState = GetKeyboardState();\n    // skip the mouse buttons\n    return keyState.Skip(8).Any(state => (state & 0x80) != 0);\n}	0
24131860	24129919	Web API complex parameter properties are all null	public HttpResponseMessage Post(Object model)\n        {\n            var jsonString = model.ToString();\n            PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString);\n        }	0
22182851	22181121	Trouble With Executing Stored Procedure for Each CheckBoxList Item Checked	protected void AddDuesbtn_Click(object sender, EventArgs e)\n{\n\n   for (int i = 0; i < StdDueNmcklist.Items.Count; i++)\n   {\n       if (StdDueNmcklist.Items[i].Selected)\n       {\n\n\n           InsertStudDuesdatcon.Insert();\n           AddDuesbtn.Visible = false;\n           CnfrmStudDueAddlbl.Visible = true;\n           CnfrmStudDueAddbtn.Visible = true;\n           StdDueNmcklist.Items[i].Selected = false;\n\n       }\n\n\n     }	0
23523827	23523474	How to Send Instance from Main Windows to User Control	namespace UserControlPassReference\n{\n    public partial class MainWindow : Window\n    {\n        public MainWindow()\n        {\n            InitializeComponent();\n            UserControl1 uc1 = new UserControl1(this);\n        }\n    }\n}\n\nnamespace UserControlPassReference\n{\n    public partial class UserControl1 : UserControl\n    {\n        private Window main;\n        public UserControl1()\n        {\n            InitializeComponent();\n        }\n        public UserControl1(Window Main)\n        {\n            InitializeComponent();\n            main = Main;\n        }\n    }\n}	0
27329337	27329297	Return short date string from property C#	private DateTime _pickdt;\npublic string PICKDT\n{\n    get {return _pickdt.ToShortDateString();}\n}	0
27762617	27602825	performance at arcgis silverlight api	var myPolyline = new ESRI.ArcGIS.Client.Geometry.Polyline();\n\n        for (int i = 0; i < 200000; i++)\n        {\n            myPolyline.Paths.Add(((ESRI.ArcGIS.Client.Geometry.Polyline)myGraphicsLayer.Graphics[i].Geometry).Paths[0]);\n        }\n\n        Graphic myGraph = new Graphic();\n\n        myGraph.Geometry = myPolyline;\n\n        ESRI.ArcGIS.Client.Symbols.SimpleLineSymbol sym = new ESRI.ArcGIS.Client.Symbols.SimpleLineSymbol();\n\n        sym.Color = new SolidColorBrush(Colors.Red);\n\n        sym.Width = 2;\n\n        myGraph.Symbol = sym;\n\n        myGraphicsLayer.Graphics.Add(myGraph);	0
23545744	23545639	Formatting a Phone number	string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");	0
2979938	2979922	How to convert datatable to json string using json.net?	string json = JsonConvert.SerializeObject(table, Formatting.Indented);	0
30046653	29819458	How to get a System.__ComObject value from Active Directory in C#	compte.Properties["ENTPersonDateNaissance"][0].ToString()	0
28303142	28301206	How to encode special characters in HTML but exclude tags	using HtmlAgilityPack;\nhtml = HtmlEntity.Entitize(html);	0
19249798	19249494	Get the value of the last parameter of urlreferrer wich can be present twice (same key twice)	string url1 = "http://mysite.fr?test=sfdfsdfsd&code=code1";\nstring url2 = "http://mysite.fr?test=sfdfsdfsd&code=code1&code=code2";\nstring code1 = HttpUtility.ParseQueryString(url1).GetValues("code").LastOrDefault();\nstring code2 = HttpUtility.ParseQueryString(url2).GetValues("code").LastOrDefault();	0
8119714	8110152	C#. Selenium. Regex in Find Element	//html//body//form//table//tbody//tr//td//a[contains(@href,'view.php?id=')]	0
655498	655488	How do I tell if a class can be serialized?	[Serializable]\npublic class Foo {\n  public Object Field1;\n}	0
916515	916454	How can I set the binding of a DataGridTextColumn in code?	dgtc.Binding = new Binding("FirstName");	0
14654202	13568936	Listbox not displaying items?	listbox1.Hide();\nlistbox1.Show();	0
22704767	22704517	How to set database SqlCe path in wpf windowes application?	string path =Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "MyDatabase#1.sdf");\n_connection =new SqlCeConnection(string.Format(@"Data Source={0};Password=xxxxxx;",path));	0
33100599	33099807	How can i select string from constants in c#?	// Just for simplicity.. in the real world you'd maybe use a property!\nDictionary<string, string> TablenamesDict = new Dictionary(string, string>();\n\n\n// In your consturctor: Initialize dictionary\nTablenamesDict.add('AC','V2_AC');\nTablenamesDict.add('DG','V2_DG');\nTablenamesDict.add('somekey','somevalue');\n...\n\n\n// You can use the dictionary like this:\nstring keyName = Getname();\nstring tableName = TablenamesDict[keyName];	0
31577064	31565668	How to customize a specific code for pagination when working with datagridview virtual mode on	query = query.Skip(lowerPageBoundary).Take(rowsPerPage);	0
11365699	11365527	Find an item from collection based on the minimum value of a property	int lowestValue = groups.SelectMany(group => group.Items)\n                  .Min(item => item.Val);\n\nIEnumerable<MyGroup> result = groups.Where(group => \n    group.Items.Select(item => item.Val).Contains(lowestValue));	0
3419484	3419328	Get more error detail info from WCF in Silverlight client	catch (Exception ex)\n{\n    System.Windows.Browser.HtmlPage.Window.Alert(ex.Reason.ToString())\n}	0
29946926	29946785	Clean way to truncate QueryString from a relative Uri c#	string clearnUri = myRelativeUri.Split('?')[0];	0
18406046	18405884	How to restart service remotely?	ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22");\n\nsc.Start();\nsc.Stop();	0
30962646	30961971	C# - Creating 2 dimensional array from multiple datagridviews	var dgvs = new [] { dgv1, dgv2, dgv3, dgv4, dgv5, dgv6, dgv7, };\n\nfor (var i = 0; i < dgvs.Length; i++)\n{\n    for (int rows = 0; rows < 7; rows++)\n    {\n        for (int col = 0; col < 5; col++)\n        {\n            myGridData[rows + i * 7, col] = dgv1[i].Rows[rows].Cells[col].Value.ToString();\n        }\n    }\n}	0
4538550	4538334	How to create Expression	IQueryable<T> queryableData = (Items as IList<T>).AsQueryable<T>();\n\nPropertyInfo propInfo = typeof(T).GetProperty("Title");\nParameterExpression pe = Expression.Parameter(typeof(T), "Title");\nExpression left = Expression.Property(pe, propInfo);\nExpression right = Expression.Constant("Bob", propInfo.PropertyType);\nExpression predicateBody = Expression.Equal(left, right);\n\n// Create an expression tree that represents the expression            \nMethodCallExpression whereCallExpression = Expression.Call(\n    typeof(Queryable),\n    "Where",\n    new Type[] { queryableData.ElementType },\n    queryableData.Expression,\n    Expression.Lambda<Func<T, bool>>(predicateBody, new ParameterExpression[] { pe }));\n\nT[] filtered = queryableData.Provider.CreateQuery<T>(whereCallExpression).Cast<T>().ToArray();	0
4405362	4405234	In nhibernate, not able to update list of child objects	x.ListOfObjectYs.Clear();\nforeach (ObjectY y in newObjectYList)\n{\n    x.ListOfObjectYs.Add(y);\n}\n_session.Flush();	0
13624229	13622308	Retrieving rating scale values in code	foreach (SPField field in item.Fields)\n  {\n        if (field.Type == SPFieldType.GridChoice)\n        {\n\n        SPFieldRatingScale srsc = (SPFieldRatingScale)field;\n        Debug.WriteLine(srsc.GetFieldValueAsText(item[field.Title]));\n\n          }\n      }	0
6221261	6221251	String.Format DateTime value in decreasing number format c#?	DateTime.Now.ToString("yyyyMMddHHmmss");	0
14757894	14757071	DataSource to ListItemCollection	// Setting up a dataset.  This dataset has no data; in real life you'd get the\n// data from somewhere else, such as a database, and wouldn't need to build it.\n\nDataSet ds = new DataSet();\nDataTable dt = new DataTable();\ndt.Columns.Add(new DataColumn("ID"));\ndt.Columns.Add(new DataColumn("Description"));\nds.Tables.Add(dt);\n\n// Creating a list box. You'd probably have this declared in your HTML and wouldn't need to\n// create it.  \n\nListBox listBox1 = new ListBox();\n\nlistBox1.DataSource = ds.Tables[0];\nlistBox1.DataValueField = "ID";\nlistBox1.DataTextField = "Description";\nlistBox1.DataBind();	0
23429160	23428858	Datagrid formatting rows	var dr = e.Row.Item as yourItem\n        // Other stuff....\n        if (difference.Days <= 0)\n        {\n            e.Row.Background = new SolidColorBrush(Colors.ForestGreen);\n            e.Row.Foreground = new SolidColorBrush(Colors.White);\n        }\n        else if (difference.Days > 0 && difference.Days <= 60)\n        {\n            e.Row.Background = new SolidColorBrush(Colors.Orange);\n            e.Row.Foreground = new SolidColorBrush(Colors.Black);\n        }\n        else if (difference.Days > 60)\n        {\n            e.Row.Background = new SolidColorBrush(Colors.Red);\n            e.Row.Foreground = new SolidColorBrush(Colors.White);\n        }	0
3718903	3718847	LinqToExcel syntax	var names = from c in excel.WorksheetRange("A1", "AI1", headerName) \n            where c[0] == "IN" \n            select c;	0
25663752	25663186	Create a Method with Dynamic Action parameter	SampleMethod(this.GetType().GetMethod("WriteHello"), "Hello");\n\n    public void WriteHello(string param)\n    {\n        Debug.WriteLine(param);\n    }\n\n    public void SampleMethod(MethodInfo mi, params object[] arguments)\n    {\n        mi.Invoke(this,arguments);           \n    }	0
5334472	5334096	Dynamically write table to file and allow download via link	public class MyData : IHttpHandler\n{\n    public void ProcessRequest (HttpContext context)\n    {   \n\n        context.Response.ContentType = "text/plain";\n        context.Response.AddHeader("Content-Disposition", "filename=\"myData.txt\"");   \n\n        using(var db = new DbDataContext) {\n\n            var data = db.Table.ToList(); //add Where(), OrderBy(), etc to filter and sort your data\n\n            string fieldDelimeter = "\t";\n            foreach(var item in data) {\n\n                context.Response.Write(item.Field1 + fieldDelimeter);\n                context.Response.Write(item.Field2 + fieldDelimeter);\n                context.Response.Write(item.Field3 + fieldDelimeter);\n                context.Response.Write(item.Field3 + fieldDelimeter);\n                context.Response.Write(Environment.NewLine);\n            }\n        }\n    }\n}	0
26967279	26967208	Add Property values to Object from Dictionary	PaypalTransaction trans = new PaypalTransaction();\n\n            PropertyInfo[] properties = trans.GetType().GetProperties();\n\n            foreach (string key in keys)\n            {\n                properties.Where(x => x.Name == key).First().SetValue(trans, "SetValueHere");\n\n            }	0
22225960	22225452	Call WebPage without display it Asp.Net	Server.Transfer("~/NewPage.aspx");	0
21574603	21574442	How do I detect hold event for a button?	Button button = new Button();\nbutton.VerticalAlignment = System.Windows.VerticalAlignment.Top;\nbutton.Height = 75;\nbutton.Tag = tag;\nbutton.Background = new SolidColorBrush(colore);\nbutton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;\nbutton.Click += button_Click;\nbutton.Hold += button_Hold;\n\nvoid button_Hold(object sender, System.Windows.Input.GestureEventArgs e)\n   {\n      MessageBox.Show("Hold");\n   }\n\nprivate void button_Click(object sender, RoutedEventArgs e)\n  {\n     MessageBox.Show("Click");\n  }	0
16389429	16389340	How to check if a named capture group exists?	var regex = new Regex(@"Something\(\d+, ""(.+)""(, .{1,5}, \d+, (?<somename>\d+)?\),");\nvar match = regex.Match(input);\nvar group = match.Groups["somename"];\nbool exists = group.Success;	0
19093152	19049433	Upload video file to server with BackgroundUploader	StorageFile VideoFileStream = await ApplicationData.Current.LocalFolder.CreateFileAsync("tempStream", CreationCollisionOption.OpenIfExists);\nvar fs2 = await VideoFileStream.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);\nIInputStream aaaa= fs2.GetInputStreamAt(0);\n\nBackgroundUploader backgroundUploader = new BackgroundUploader();\nbackgroundUploader.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundray);\nbackgroundUploader.Method = "POST";\n\nUploadOperation uploadOpration = await backgroundUploader.CreateUploadFromStreamAsync(new Uri(url),aaaa);\nawait HandleUploadAsync(uploadOpration, true);	0
320164	319422	ASP.NET - controls generated by xslt transformation	protected void Page_Load(object sender, EventArgs e)\n{\n    // Fetch your XML here and transform it.  This string represents\n    // the transformed output\n    string content = @"\n        <asp:Button runat=""server"" Text=""Hello"" />\n        <asp:Button runat=""server"" Text=""World"" />";\n\n    var controls = ParseControl(content);\n\n    foreach (var control in controls)\n    {\n        // Wire up events, change settings etc here\n    }\n\n    // placeHolder is simply an ASP.Net PlaceHolder control on the page\n    // where I would like the controls to end up\n    placeHolder.Controls.Add(controls);\n}	0
24360433	24359657	How to zoom In and Zoom Out the image using Mouse Position on that image	public Form1()\n{\n    InitializeComponent();\n\n    pictureBox1.MouseWheel += pictureBox1_MouseWheel;\n}\n\nvoid pictureBox1_MouseWheel(object sender, MouseEventArgs e)\n{\n  if(e.Delta > 0)\n  {\n      //up\n  }\n  else\n  {\n      //down\n  }\n}\n\nprivate void pictureBox1_MouseDown(object sender, MouseEventArgs e)\n{\n    pictureBox1.Focus();\n}	0
24199743	24199702	Using Serial port control in another class	SerialPort serialPort1 = new SerialPort();	0
12137901	12137853	Rename an attribute of html file in c#	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(@"<img src=""Hello.jpg"" />");\n\nforeach (var img in doc.DocumentNode.Descendants("img"))\n{\n    var realSource = img.Attributes["data-realsrc"];\n\n    if (realSource != null)\n        realSource.Value = img.Attributes["src"].Value;\n    else\n        img.Attributes.Add("data-realsrc", img.Attributes["src"].Value);\n\n    img.Attributes["src"].Value = "loading.gif";\n}	0
26021054	26020739	Entity set connection timeout	string normalConnectionString = RepositoryDbContext.Database.Connection.ConnectionString;\nvar connectionBuilder = new SqlConnectionStringBuilder(normalConnectionString);\nconnectionBuilder.ConnectTimeout = 10;\nstring testConnectionString = connectionBuilder.ConnectionString;\n\nusing (var testRepositoryDbContext = new RepositoryDbContextType(testConnectionString))\n{\n    try\n    {\n        testRepositoryDbContext.Database.Connection.Open();    \n        testRepositoryDbContext.Database.Connection.Close();\n        return true;\n    }\n    catch\n    {\n        return false;\n    }\n}	0
11207038	11206737	Getting events from a dynamically created rectangle object c#	for(int a = 0;  a < array.getlength(0); a++)\n{\n   //draw rectangle on each iteration\n   rectangle shape = new rectangle();\n\n   shape.width(200);\n   shape.height(50);\n\n   shape.posTop(posx);\n   shape.posLeft(posy);\n\n   posx = posx + 20;\n   posy = posy + 50;\n\n   shape.click.MouseDown += new MouseButtonEventHandler(shape_MouseDown);\n\n   //code to draw onto Canvas object etc...\n}	0
4348811	4348520	Html Agility Pack - Get html fragment from an html document	doc.DocumentNode.SelectSingleNode("//body") // returns body with entire contents :)	0
33231960	33231720	Pooled read-only SQLite connection is used for read-write access	internal static void Add(\n    string fileName,\n    SQLiteConnectionHandle handle,\n    int version	0
2432341	2432076	Trying to make a zoom effect	var i = 5;\nvar zoomfactor = new[] {.25, .33, .50, .66, .80, 1, 1.25, 1.5, 2.0, 2.5, 3.0};\nvar origin = new Point(100, 100);\nvar image = Image.FromFile(@"c:\example.png");\nvar imgBox = new PictureBox {\n        Location = origin,\n        Size = image.Size,\n        Image = image,\n        SizeMode = PictureBoxSizeMode.StretchImage\n    };\nvar form = new Form {\n        Size = new Size(800, 600),\n        Controls = {imgBox}\n    };\nform.MouseWheel += (sender, e) => {\n        i += e.Delta/120;\n        if (i < 0) {\n            i = 0;\n        }\n        if (i >= zoomfactor.Length) {\n            i = zoomfactor.Length - 1;\n        }\n        var newZoom = zoomfactor[i];\n        imgBox.Width = (int) (imgBox.Image.Width*newZoom);\n        imgBox.Height = (int) (imgBox.Image.Height*newZoom);\n        imgBox.Left = (int) (e.X - newZoom*(e.X - origin.X));\n        imgBox.Top = (int) (e.Y - newZoom*(e.Y - origin.Y));\n    };\nform.ShowDialog();	0
34498129	34497872	How can I verify the Dictionary values I've assigned to a combobox are what I think they are?	foreach (KeyValuePair<string,string> v in comboBoxReportRunners.Items)\n{\n    MessageBox.Show(v.Key.ToString());\n    MessageBox.Show(v.Value.ToString());\n}	0
20093114	20093042	C# IDictionary with ICollection values without exposing implementation details	IDictionary<string, ICollection<decimal>> goodPrices = new Dictionary<string, ICollection<decimal>>();\ngoodPrices.Add("myString", new List<decimal>() { /* my values */ });	0
23234078	23233992	How do I return a JSON object from controller in ASP.NET MVC 4?	public JsonResult AddToPreRank(int id){\n        Player player= new Player();\n        player = db.Players.Find(id);\n\n        return Json(player);\n    }	0
19665472	19665295	how to fix SystemArgumentNullException in Visual Studio 2010 based on connectionString	return SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["ConnectionString"].ConnectionString, CommandType.StoredProcedure, "spHouses_GetNearZipcode", arParms).Tables[0];	0
11459930	11455492	How to find the Name of the Subfolder in a Directory	string rootDir = folderBrowserDialog.SelectedPath;\n            string fileDir = Path.GetDirectoryName(fileName);\n            if (rootDir.Length < fileDir.Length)\n                row.FOLDER = fileDir.Substring(rootDir.Length + 1);	0
23641493	23640911	Regex expression to match line with two specific words in it	String s = "nonsense nonsense nonsense nonsense nonsense\n" +\n           "nonsense item 1 nonsense nonsense gold nugget\n" +\n           "nonsense nonsense nonsense nonsense nonsense\n" +\n           "item 1 nonsense nonsense nonsense nonsense\n" +\n           "nonsense nonsense nonsense nonsense nonsense";\n\nMatch m  = Regex.Match(s, @"(?m)^.*item 1.*gold nugget.*$");\n\nif (m.Success) {\n   Console.WriteLine(m.Value); // "nonsense item 1 nonsense nonsense gold nugget"\n}	0
26299846	26299575	RowSpan and alternate row color at the same time using c#	protected void OnDataBound(object sender, EventArgs e)\n{\n    int RowSpan = 2;\n    // actual row counter, spanned rows count as one\n    int rowCount = 0;\n    for (int i = visualisation.Rows.Count - 2; i >= 0; i--)\n    {\n        GridViewRow currRow = visualisation.Rows[i];\n        GridViewRow prevRow = visualisation.Rows[i + 1];\n\n        if (currRow.Cells[0].Text == prevRow.Cells[0].Text)\n        {\n            currRow.Cells[0].RowSpan = RowSpan;\n            prevRow.Cells[0].Visible = false;\n            RowSpan += 1;\n        }\n        else\n        {\n            RowSpan = 2;\n            //it was a new row\n            rowCount++;\n        }\n\n        if (rowCount % 2 == 0)\n        {\n            currRow.BackColor = Color.FromName("#7AA5D6");            \n        }\n    }\n}	0
13262641	13262551	Generic type serialization with two similarly named generic arguments	var entityA = new GenericThing<MyApp.Entity>();\nvar entityB = new GenericThing<MyAppB.Entity>();\nvar serializer1 = new XmlSerializer(entityA.GetType(), "aaa");\nvar serializer2 = new XmlSerializer(entityB.GetType(), "bbb");	0
6446639	6446525	C# HTML from WebBrowser to valid XHTML	var sb = new StringBuilder(); \nvar stringWriter = new StringWriter(sb);\n\nstring input = "<html><body><p>This is some test test<ul><li>item 1<li>item2<</ul></body>";\n\nvar test = new HtmlAgilityPack.HtmlDocument();\ntest.LoadHtml(input);\ntest.OptionOutputAsXml = true;\ntest.OptionCheckSyntax = true;\ntest.OptionFixNestedTags = true;\n\ntest.Save(stringWriter);\n\nConsole.WriteLine(sb.ToString());	0
4243551	4243541	Find out if a property is declared virtual	var isVirtual = typeof(Cat).GetProperty("Age").GetGetMethod().IsVirtual;	0
1265627	1265610	Programmatically add a strong named assembly to the GAC	System.Diagnostics.Process	0
4417214	4416934	C#, how to make a picture background transparent?	//If added your image in project's resources get from there OR your Image location\n  Image img = yourNamespace.Properties.Resources.yourPicture;   \n  e.Graphics.DrawImage(img,50,50,100,100);	0
2811039	2810065	c# find mail by from mail	inbox.Items.Restrict("[SenderEmailAddress]='mymail@mydomain.com'");	0
11208473	11208369	C# Recursive Folder/File scan with Size,Path,Creation,FileVersion to txt	GetFileInfo(string dir)\n{\n try\n       {\n           FileInfo info = null;\n           foreach (string d in Directory.GetDirectories(sDir))\n           {\n               foreach (string file in Directory.GetFiles(d))\n               {\n                info =  new FileInfo(file);\n                //get all information using info here\n               }\n               GetFileInfo(d);\n           }\n       }\n       catch (System.Exception excpt)\n       {\n           Console.WriteLine(excpt.Message);\n       }\n}	0
32768759	32768446	exploding List<T> into multiple groups	public static List<List<T>> GroupItems<T>(this List<T> items, int totalGroups)\n    {\n        if (items == null || totalGroups == 0) return null;\n        var ret = new List<List<T>>();\n\n        var avg = items.Count / totalGroups; //int  rounds towards 0\n        var extras = items.Count - (avg * totalGroups);\n        for (var i = 0; i < totalGroups; ++i)\n            ret.Add(items.Skip((avg * i) + (i < extras ? i : extras)).Take(avg + (i >= extras ? 0 : 1)).ToList());\n        return ret;\n    }	0
29439920	29439707	c# Api Json deserializes when 404, values are wrong	RootObject rootObject = serializer.Deserialize<RootObject>(jsonReader);\n\nif (rootObject.count > 0)\n    return rootObject;\nelse\n    return null; //or any other program flow you need to execute.	0
18637030	18636661	Can I use use Hashcode to directly lookup a value in a C# Dictionary	public sealed class StringKey: IEquatable<StringKey>\n{\n    public StringKey(string key)\n    {\n        Contract.Requires(key != null);\n\n        _key = key;\n        _hashCode = key.GetHashCode();\n    }\n\n    public override int GetHashCode()\n    {\n        return _hashCode;\n    }\n\n    public bool Equals(StringKey other)\n    {\n        if (ReferenceEquals(null, other))\n            return false;\n\n        if (ReferenceEquals(this, other))\n            return true;\n\n        return (_hashCode == other._hashCode) && string.Equals(_key, other._key);\n    }\n\n    public override bool Equals(object obj)\n    {\n        if (ReferenceEquals(null, obj))\n            return false;\n\n        if (ReferenceEquals(this, obj))\n            return true;\n\n        return obj is StringKey && Equals((StringKey) obj);\n    }\n\n    public string Key\n    {\n        get\n        {\n            return _key;\n        }\n    }\n\n    private readonly string _key;\n    private readonly int    _hashCode;\n}	0
27577925	27576989	Textbox data to xml in asp.net	XmlDocument xdoc = new XmlDocument();       \nxdoc.LoadXml(txtBox.Text);	0
19738508	19738433	Declare an interface as being implemented by a class	public class CompatibleStack<T> : System.Collections.Generic.Stack<T>, IYourStackInterface<T>\n{\n}	0
34067606	34066955	C# Member expression Func<T,object> to a Func<T,bool> MethodBinaryExpression	model=>model.property == object.property\n\npublic static void SaveBy<T, TProp>(this IDbConnection db, T obj, Expression<Func<T, TProp>> exp) where T : new()\n{\n    var memberExp = (MemberExpression)exp.Body;\n    var objPropExp = Expression.PropertyOrField(Expression.Constant(obj), memberExp.Member.Name);\n    var equalExp = Expression.Equal(exp.Body, objPropExp);\n    var exp2 = Expression.Lambda<Func<T, bool>>(equalExp, exp.Parameters);\n    //exp2 = {model => (model.prop == value(object).prop)}\n\n    if (db.Update(obj, exp2) <= 0)\n    {\n        db.Insert(obj);\n    }\n}	0
18814026	18810694	How to create multiple nested conditions against joined tables in linq to entities?	var tableBPredicate = PredicateBuilder.True<tableB>();\nforeach (var filter in filters)\n{\n    /* build up tableB conditions here */\n    tableBPredicate = tableBPredicate.And(p => p.Column1 == filter.Column1);\n    tableBPredicate = tableBPredicate.And(p => p.Column2 => filter.Column2);\n}\n\nvar tableBQuery = tableB.AsExpandable().Where(tableBPredicate);\n\nvar query = from b in tableBQuery\n    join a in tableA\n    on new\n    {\n        ProductId = b.ProductId,\n        UserId = b.UserId\n    }\n    equals\n    new\n    {\n        ProductId = a.ProductId,\n        UserId = a.UserId\n    }\n    where a.ProductId == 6544\n    select a;\n\nreturn query.ToList();	0
13821278	13820543	How to change the names of the url action	**EDIT:**\n\n\n\n routes.MapRoute(\n                "Can Be anything", // Route name\n                "yourpath/{para1}", // URL with parameters[if you want to have any]\n                new { controller = "Quote", action = "Index" }, // Parameter defaults\n                new { httpMethod = new HttpMethodConstraint("GET") }\n                );	0
2767696	2767557	WPF: Get Property that a control is Bound to in code behind	BindingExpression be = BindingOperations.GetBindingExpression((FrameworkElement)yourComboBox, ((DependencyProperty)Button.SelectedItemProperty));\nstring Name = be.ParentBinding.Path.Path;	0
17042787	17041351	How to open a new window form within another form in c#	this.Hide();\nMain.ShowDialog();\nthis.Close();	0
19360027	19359745	Need to split string(formula) with specified pattern	var str = "([myString1 - L]*[myString2 - L])/([myString3 - D]+[myString4 - N])";\nvar result = Regex.Split(str, @"(\[[^]]+\]|[/\*\+\(\)])").Where(r => r != "").ToList();	0
26503880	26503863	How to use Server.MapPath for Excel File	Server.MapPath(@"C:\MyExcel.xlsx");	0
4658730	4658684	Avoid MouseOver Event in Silverlight on specific control	e.Handled = true;	0
22115657	22100715	How to open android app using custom protocol in xamarin	[Activity (Label = "MainActivity", MainLauncher = true)]\n[IntentFilter (new[]{Intent.ActionMain},\n    Categories=new[]{Intent.CategoryLauncher, Intent.CategorySampleCode},\n    Icon="@drawable/myicon",\n    DataScheme="something",\n    DataHost="project.example.com")]\npublic class MainActivity : Activity\n{\n}	0
21241229	21240982	How to modify some elements of a list using linq in C#?	var list = Enumerable.Range(1, 10)\n                     .Select(i => new Document\n                     {\n                         ID = i.ToString(),\n                         Type = "someType",\n                         Checked = (i > 5)\n                     }).ToList();	0
15665178	15664734	how to display a Save Dialogbox	string filepath = AppPath + @"\Test.edd";\n     HttpContext.Current.Response.ContentType = "application/octet-stream";\n     HttpContext.Current.Response.AddHeader("Content-Disposition",\n              "attachment; filename=" + "Test.edd");\n     HttpContext.Current.Response.Clear();\n     HttpContext.Current.Response.WriteFile(filepath);\n     HttpContext.Current.Response.End();	0
16274844	16274050	Sending data from server	protected void ProcessData(int x, string data, Socket so)\n{\n    if (x < mybuffersize)\n    {\n        data = data.Trim();\n        SendData(so, data);\n        string sendData = "Testing send string\0";\n        SendData(so, sendData);\n    }\n}	0
10928699	10926323	C# print number from for loop	static int count = 0;\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        bind();\n    }\n}\n\nprivate void bind()\n{\n    ArrayList ar = new ArrayList();\n    ar.Add("first");\n    ar.Add("Second");\n    ar.Add("Third");\n    ar.Add("Four");\n    ar.Add("Five");\n    ar.Add("Six");\n    ar.Add("Seven");\n    DropDownList1.DataSource = ar;\n    DropDownList1.DataBind();\n}\nprotected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    //string str = DropDownList1.SelectedValue;\n    if (count == 0)\n        count = 1;\n    Label1.Text = count++.ToString();\n}	0
25059480	25055637	Collapse Control under a GridSplitter - Unwanted White space appears	public MainWindow()\n{\n    InitializeComponent();\n    //gr is the name of the Grid\n    basepr1 = gr.RowDefinitions[0].Height;\n    basepr2 = gr.RowDefinitions[2].Height;\n}\nstatic GridLength zero = new GridLength(0);\nGridLength basepr1;\nGridLength basepr2;\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    if (this.LowerPanel.Visibility == Visibility.Visible)\n    {\n        this.LowerPanel.Visibility = Visibility.Collapsed;\n        basepr2 = gr.RowDefinitions[2].Height; // remember previos height\n        gr.RowDefinitions[2].Height = zero;\n    }\n    else\n    {\n        this.LowerPanel.Visibility = Visibility.Visible;\n        gr.RowDefinitions[2].Height = basepr2;\n    }\n}	0
3100372	3100314	Macro-like structures in C# ==OR== How to factor out a function containing 'return'	object Function()\n{ \n    this.Blah = this.Blah.Resolve(...);\n    object rc;\n    if (!VerifyResolve(out rc)\n       return rc;\n\n    // continue processing... \n} \n\nbool VerifyResolve(out object rc)\n{\n    if(this.Blah == null)      \n    {\n        rc = null;\n        return true;\n    }\n    if(this.Blah.SomeFlag)      \n    {\n        rc = this.OtherFunction();\n        return true;\n    }\n    rc = null;\n    return false;\n}	0
16910508	16910390	How to convert a multi dimensional array into json format in C# asp.net?	JavaScriptSerializer js = new JavaScriptSerializer();\nstring json = js.Serialize(array_questions);	0
30541025	30540859	PayPal 400 Bad Request, more specific?	example.com	0
23814658	23814640	How to ignore case sensitive in StartWith for LINQ FindAll?	StartsWith(optAlpha.SelectedItem.Value, StringComparison.InvariantCultureIgnoreCase);	0
7636534	7636365	How to make Object bound to WPF control thread safe	Dispatcher.BeginInvoke()	0
13552857	13552804	How to find out which DataGridView is clicked?	protected void altGridView_Click(object sender, DataGridViewCellEventArgs e)\n{\n    int colIndex = e.ColumnIndex;\n    int rowIndex = e.RowIndex;\n    var currentDataGridView = sender as DataGridView; //your grid\n    currentDataGridView.Rows[colIndex].Cells[rowIndex].Value="something";\n}	0
3101541	3101479	How to get the bound item from within an ASP.NET repeater	this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;\n\nvoid Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    var dataItem = e.Item.DataItem;\n}	0
12899915	12898680	how to disable alt+F4 for the application?	namespace WindowsFormsApplication1\n{\n    static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.AddMessageFilter(new AltF4Filter()); // Add a message filter\n            Application.Run(new Form1());\n        }\n    }\n\n    public class AltF4Filter : IMessageFilter\n    {\n        public bool PreFilterMessage(ref Message m)\n        {\n            const int WM_SYSKEYDOWN = 0x0104;\n            if (m.Msg == WM_SYSKEYDOWN)\n            {\n                bool alt = ((int)m.LParam & 0x20000000) != 0;\n                if (alt && (m.WParam == new IntPtr((int)Keys.F4)))\n                return true; // eat it!                \n            }\n            return false;\n        }\n    }\n}	0
589001	588990	How do you detect the main hard drive letter such as C: drive?	Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));	0
28056813	28056721	DateTime integer value in C# and JavaScript	public DateTime ConvertDate(long unixTime)\n{\n    var date= new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n    return date.AddSeconds(unixTime);\n}	0
3353016	3352946	Filtering a graph of entity framework objects	var x = from hp in _entities.PEOPLE\n        let ho = hp.ORDERS.Where(o => o.ORDER_KEY == filtOrder\n                                      && o.ORDERLINES.Any(ol => ol.SERVICE_YEAR == formattedYear))\n        where ho.Any()\n        select new \n        {\n            Id = hp.ID,\n            Name = hp.Name, // etc.\n            Orders = from o in ho\n                     select new { // whatever \n        };	0
22779286	22779254	How do I display a date format in dd/MM/yyyy to ddd, dd/MM/yyyy (Mon, 1/4/2014) format with this logic?	calSMAlerted.SelectedDate.ToString("ddd, dd/MM/yyyy");	0
21275167	21265237	How can I use methods in the SO files produced by mono AOT in my C program?	--aot=full	0
5895591	5895097	How to close MDIChild C# VS2010?	private void toolStripButton1_Click(object sender, EventArgs e)\n{\n    Form3 NwMdiChild2 = new Form3();    //don't forget ()\n    NwMdiChild2.MdiParent = this;\n    NwMdiChild2.Dock = System.Windows.Forms.DockStyle.Fill;\n    NwMdiChild2.Show();\n}\n\nprivate void Form2_FormClosing(object sender, FormClosingEventArgs e)\n{\n    //if no MDI child - this is going to be skipped and norlmal Form2 close takes place\n    if (this.MdiChildren.Length > 0)    //close childrens only when there are some\n    {\n        foreach (Form childForm in this.MdiChildren)\n            childForm.Close();\n\n        e.Cancel = true;  //cancel Form2 closing\n    }\n}	0
15267334	15267168	Saving a file with current date & time for the file name Winform C#	String fileName = "C:\\ScreenCap_" +  Date.Now.ToString("yyyyMMdd_hhss") + ".jpg";\n_tempVLCWindow.TakeSnapshot(fileName , 1280, 720);	0
15250473	15236339	Select each item in dropdown list using Watin	int numberOfItems = browser.SelectList(Find.ById("ctl00$Header1$ddlPropertyList")).count;\n\nfor(int i = 0; i < numberOfItems; i++)\n{\n    //this is one the "search" page\n    browser.SelectList(Find.ById("ctl00$Header1$ddlPropertyList")).Options[i].Select;\n    browser.yourGoAction();   <- assumes navigation isn't automatic when an item is selected.  EG:  button.Click() or something.\n\n    //this is on the "results" page.\n    do stuff\n\n    //go back to the "search" page.\n    browser.Back();\n}	0
22181964	21764139	How to change the way solr assigns relevance score to documents?	SolrQueryByField query = new SolrQueryByField("body", @"\\123.45.67.89\Lists\PLAYLIST\EAST");\nquery.Boost(100);	0
25639760	25639651	Getting JSON from CURL in C#	string json;\nusing(var client = new WebClient())\n{\n    client.Credentials = new NetworkCredential("{email_address}", "{password}");\n    json = client.DownloadString(\n        "https://{subdomain}.zendesk.com/api/v2/ticket_fields/{id}.json");\n}\n// use json...	0
19734437	16347249	Stream rtsp video using axvlcplugin to a file	Process.Start("C://Program Files//Videolan//VLC//VLC.exe","\"rtsp://xxx.xxx.xxx.xxx:554/h264\" --qt-start-minimized --sout=#transcode{vcodec=theo,vb=800,acodec=flac,ab=128,channels=2,samplerate=44100}:file{dst=C:\\123.ogg,no-overwrite}");	0
8358042	8357983	Using XDocument with namespaces	XNamespace ns = "urn:schemas-rcsworks-com:SongSchema";\nfor (var songElement = doc.Descendants(ns + "Song"))\n{\n    ...\n}	0
29578102	29578062	split string c# based on math operator	var reg = new System.Text.RegularExpressions.Regex(@"\d\+(\d)\*(\d)");\nvar result = reg.Match("5+2*6/9");\nvar first = result.Groups[1];\nvar second = result.Groups[2];	0
1595930	1595838	In C#, how to determine the XSD-defined MaxLength for an element	Accessing XML Schema Information During Document Validation	0
16579951	14247081	Return Values from Dapper.net query with stored procedure	var incidentId = retResults.ToList()[0].INCIDENT_ID;	0
1699928	1699897	Retrieve List of Tables in MS Access File	// Microsoft Access provider factory\nDbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");\n\nDataTable userTables = null;\nusing (DbConnection connection = factory.CreateConnection()) {\n  // c:\test\test.mdb\n  connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\test\\test.mdb";\n  // We only want user tables, not system tables\n  string[] restrictions = new string[4];\n  restrictions[3] = "Table";\n\n  connection.Open();\n\n  // Get list of user tables\n  userTables = connection.GetSchema("Tables", restrictions);\n}\n\nList<string> tableNames = new List<string>();\nfor (int i=0; i < userTables.Rows.Count; i++)\n    tableNames.Add(userTables.Rows[i][2].ToString());	0
34418284	34417969	Loop Listbox SQL Insert with DateTime (incremented every 15 minutes)	DateTime somedate = DateTime.Today;\n\nfor (int i = 0; i < myListBox.Count; i++)\n{\n    var increasedDate = somedate.AddMinutes(i*15);\n    // and then insert myListBox.Items[i] with increasedDate \n}	0
20296863	20296829	Replace datagridviewtextcolumn to datagridviewcombo	Dim comboBoxColumn As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()\ncomboBoxColumn.HeaderText = "Location"\ncomboBoxColumn.DataPropertyName = "Location"\ncomboBoxColumn.DataSource = dtLocations\n\ncomboBoxColumn.ValueMember = dtLocations.Columns(0).ColumnName\n\ncomboBoxColumn.DisplayMember = dtLocations.Columns(1).ColumnName\n\ndgvPickList.Columns.RemoveAt(1)\n\ndgvPickList.Columns.Insert(1, comboBoxColumn)	0
8567719	8567594	How to create a non-modal form but blocking?	public void ShowMe() {\n    Show();\n    while (!_receivedDeactivateEvent)\n        Application.DoEvents();\n}	0
18332608	18332059	adding Control to form but gap keeps doubling when added at Bottom of previous control	sharpUserX.Size = sharpUserSize\nPnlSharpUsers.Controls.Add(sharpUserX)\nsharpUserX.Location = pnlAddBtn.Location	0
25640997	25640868	How to call cmd from C# application to generate nsis installer?	startInfo.FileName = @"C:\Program Files (x86)\NSIS\makensis.exe";\nstartInfo.Arguments = @"Z:\Project\BuildArea\workspace\installer\Setup_PRO.nsi";\nprocess.StartInfo = startInfo;\nprocess.Start();	0
8742598	8587525	Data Bind to Custom Control Parameter Collection	public override void DataBind()\n    {\n        base.DataBind();\n        foreach (LinkParameter param in Parameters)\n        {\n            param.DataBind();\n        }\n    }	0
24789673	24370834	Insert more than one item from checkedlistbox to AccessDB	foreach (string s in checkedListBox1.CheckedItems)\n{\n  using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))\n  {\n    cmd.Parameters.AddWithValue("@principle", comboBox12.Text);\n    cmd.Parameters.AddWithValue("@comments", textBox3.Text);\n    cmd.Parameters.AddWithValue("@date", dateTimePicker1.Value);\n    cmd.Parameters.AddWithValue("@session", comboBox1.Text);\n    cmd.Parameters.AddWithValue("@teller", s);\n    cmd.ExecuteNonQuery();\n  }\n}	0
31595488	31593774	LINQ to Entities, Where Any In	var myCategoriesIds = myCategories.Select(c => c.Id).ToArray();\n\nvar result =\n    context.Chairs\n        .Where(\n            x => x.Table.Categories.Any(\n                y => myCategoriesIds.Contains(y.Id)))\n        .ToList();	0
20471896	20471663	windows azure QueueClient recommended cache?	//don't this\npublic class WorkerRole : RoleEntryPoint\n{\n    public override void Run()\n    {\n        // This is a sample worker implementation. Replace with your logic.\n        Trace.TraceInformation("WorkerRole1 entry point called", "Information");\n\n        while (true)\n        {\n            QueueClient Client = new QueueClient();\n            Thread.Sleep(10000);\n            Trace.TraceInformation("Working", "Information");\n        }\n    }\n}\n\n//use this\npublic class WorkerRole : RoleEntryPoint\n{\n    public override void Run()\n    {\n        // This is a sample worker implementation. Replace with your logic.\n        Trace.TraceInformation("WorkerRole1 entry point called", "Information");\n\n        QueueClient client = new QueueClient();\n\n        while (true)\n        {\n            //client....\n            Thread.Sleep(10000);\n            Trace.TraceInformation("Working", "Information");\n        }\n    }\n}	0
1388857	1388787	information in registry	RegistryKey key= Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("leaf").OpenSubKey("monitor ");\nstring version = key.GetValue("version");	0
18358587	18355341	Bind list of string to listbox with datatemplate	foreach (var myVar in Vydajna1Menus)\n                {  \n                _myDataForLunchGrid.Add(new BindingData\n                {\n                    vydajnaMenus = myVar,\n                    vydajnaNumber ="0"+numberOfFood.ToString()\n                });\n                }\n                OnPropertyChanged("MyDataForLunchGrid");	0
19257905	19257853	Using try/catch makes it so I can't use the variable outside of the try/catch block	Product product;\ntry\n{\n    product = catalogContext.GetProduct("CatalogName", "ProductId");\n}\ncatch (EntityDoesNotExist e)\n{\n    product = null;\n}\n\nif (dataGridView1.InvokeRequired)\n{\n    // use product here\n}	0
7588553	7588367	How to make AutoMapper create an instance of class	Mapper.CreateMap<Source, Destination>()\n                .AfterMap((src, dest) =>\n                              {\n                                  dest.HomeAddress = new Address {PostalCode = src.ZipCode};\n                              }\n            );	0
19857318	19857063	Accessing property of root master page	this.Master.Master.PropertyName	0
13818200	13817737	How to sort the date column in gridview?	accTable.Columns.Add("Date",typeof(DateTime));	0
4311870	4311851	i converted a bitmap picture to byte arraye and string .how can i convert this string to that bitmap picture again?	public static byte[] ImageToByteArray(System.Drawing.Image imageIn) {\n  MemoryStream ms = new MemoryStream();\n  Bitmap image = new Bitmap(imageIn);\n  image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);\n  return ms.ToArray();\n}\n\npublic static Image ByteArrayToImage(byte[] byteArray) {\n  MemoryStream ms = new MemoryStream(byteArray);\n  Image returnImage = Image.FromStream(ms);\n  return returnImage;\n}	0
19479274	19479239	Incorrect syntax inserting data into table	string connstr = "....";     \n  string query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) " + \n          "values (@name, @pic, @ing, @instr)";\n  using(SqlConnection conn = new SqlConnection(connstr))\n  using(SqlCommand cmd = new SqlCommand(query, conn))\n  {\n    conn.Open();\n    SqlParameter picparameter = new SqlParameter();\n    picparameter.SqlDbType = SqlDbType.Image;\n    picparameter.ParameterName = "@pic";\n    picparameter.Value = picbyte;\n    cmd.Parameters.Add(picparameter);\n    cmd.Parameters.AddWithValue("@name", textbox1.Text);\n    cmd.Parameters.AddWithValue("@ing", textbox2.Text);\n    cmd.Parameters.AddWithValue("@instr", textbox3.Text);\n    cmd.ExecuteNonQuery();\n    MessageBox.Show("Image successfully saved");\n  }	0
14190753	14190730	function returning a const value	public int Testfunction(TESTENUM TestEnum)\n{\n    ...	0
22733318	22732998	Add same value to Dictionary for both key and value in C#	SomeDictionary.Add(Value2, GetFrom.Asset != null ? Value1 : Value2)	0
15000899	14999984	Windows color to single integer	// set the edges of the color range\nvar firstColor = Color.Red;\nvar secondColor = Color.Green;\n\nint rMin = firstColor.R;\nint rMax = secondColor.R;\nint bMin = firstColor.B;\nint bMax = secondColor.B;\nint gMin = firstColor.G;\nint gMax = secondColor.G;\n\nint size = 10;\n\nfor (int i = 0; i < size; i++)\n{\n    var rAverage = rMin + (int)((rMax - rMin) * i / size);\n    var gAverage = gMin + (int)((gMax - gMin) * i / size);\n    var bAverage = bMin + (int)((bMax - bMin) * i / size);\n    var currentColor = Color.FromArgb(rAverage, gAverage, bAverage);\n    // TODO: use the currentColor\n}	0
6635577	6630905	C# - Concat to end if matches the front of file	using (StreamReader sr1 = new StreamReader(@"C:\Temp\Content.txt"))\nusing (StreamReader sr2 = new StreamReader(@"C:\Temp\Numbers.txt"))\nusing (StreamWriter sw = new StreamWriter(@"C:\Temp\Combined.txt"))\n{\n    string curLine;\n    while ((curLine = sr1.ReadLine()) != null)\n    {\n        if (Regex.IsMatch(curLine, "^[1-9][0-9]*\s"))\n        {\n            sw.WriteLine(curLine + "    " + sr2.ReadLine());\n        }\n        else\n        {\n            sw.WriteLine(curLine);\n        }\n    }\n}	0
30051849	30051560	How to get declaring type of an atrribute from sub types tree in C#	static string GetTableNameFromType(Type type)\n    {\n        // what go here to get string of "Customer" for type = CustomerProxy\n        //              to get string of "_USER" for type = UserRBACProxy\n\n        TableBaseAttribute tableBaseA = (TableBaseAttribute)type.GetCustomAttributes(typeof(TableBaseAttribute), true)[0];\n\n        string ret = null;\n        if (string.IsNullOrEmpty(tableBaseA.Name))\n        {\n            do\n            {\n                var attr = type.GetCustomAttributes(typeof(TableBaseAttribute), false);\n                if (attr.Length > 0)\n                {\n                    return type.Name;\n                }\n                else\n                {\n                    type = type.BaseType;\n                }\n            } while (type != typeof(object));\n        }\n        else\n        {\n            ret = tableBaseA.Name;\n        }\n\n        return ret;\n    }	0
24664384	24663627	How to display Thread.Sleep countdown in console - C#	private void CountDown() {\n    for (int i = 60; i >= 0; --i) {\n        Console.Write("Time: {0}",i);\n        Thread.Sleep(1000);\n        Console.Clear();\n    }\n}	0
16511098	16511073	Linking 2 variables to one object	theta t = new theta();\nlayers[1][i].source[j] = t;\nlayers[0][j].destination[i] = t;	0
25279014	25278971	Unable to find and click the button	By.XPath("//input[contains(@src,'www.sandbox.paypal.com')]")	0
24817882	24817558	C# to Send Mail using Outlook	using Microsoft.Office.Interop.Outlook;\n//C:\Program Files\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Outlook.dll\n//14.0.0.0 or 12.0.0.0 - it works from Outlook 2007 and higher\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        public void SendMail()\n        {\n            //// Create the Outlook application by using inline initialization.\n            Application oApp = new Application();\n            ////Create the new message by using the simplest approach.\n            MailItem oMsg = (MailItem)oApp.CreateItem(OlItemType.olMailItem);\n            oMsg.SendUsingAccount = oApp.Session.Accounts[2]; // it starts at 1\n\n...	0
21615526	21613632	Differentiating between MinValue of double and Minimum of NumericUpDown	if (this.Value == null) // if value is cleared by user.\n{\n    this.Value = (this.Minimum == double.MinValue) ? 0 : this.Minimum;\n}	0
17997386	17997343	Implicit array length with C# PInvoke	private static extern void foo(string[] stringArray, int arrayCount);\n\npublic static void foo(string[] stringArray) {\n    foo(stringArray, stringArray.Length);\n}	0
28985239	28985156	Splitting string on multi-character delimeter	result = IdStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)\n    .Select(x => stringSeparators[0] + x).ToArray();	0
9823302	9823237	how to calculate total time taken by for loop	using System;\nusing System.Diagnostics;\nusing System.Threading;\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Stopwatch stopWatch = new Stopwatch();\n        stopWatch.Start();\n        for (long d = 0; d<= K; d++)   \n        {      \n        //do something  \n        }         \n        stopWatch.Stop();\n        // Get the elapsed time as a TimeSpan value.\n        TimeSpan ts = stopWatch.Elapsed;\n\n        // Format and display the TimeSpan value.\n        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n            ts.Hours, ts.Minutes, ts.Seconds,\n            ts.Milliseconds / 10);\n        Console.WriteLine("RunTime " + elapsedTime);\n    }\n}	0
24205400	24205060	window.onbeforeunload losing values in text box	console.log('#<%=txtForeName.ClientID%>').val());	0
8235212	8191586	Linq-to-SQL - Grouping and joins	var q =\n    from c in db.Categorie\n    where (from pic in db.ProductsInCategories\n          join p in db.Products on pic.ProductId equals p.ProductId\n          where p.OwnerId == ownerId && pic.CategoryId == c.CategoryId\n          select pic).Any()\n    select c;	0
5895785	5895701	XML serialization of objects with envelope in C#	XmlAttributes attributes = new XmlAttributes();\nXmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();\nattributes.XmlElements.Add(new XmlElementAttribute("Person", t));\nxmlAttributeOverrides.Add(typeof(Person), "WrappedObject", attributes);\nXmlSerializer myserialiser = new XmlSerializer(typeof(Envelope), xmlAttributeOverrides);	0
32587689	32587517	How to use constant value in Linq left join?	var list = (from alert in ctx.Set<S1AlertLog>()\n              join smManualChapter in ctx.Set<SmManualChapter>() \n                  on new { d = alert.MwEventDetailKey, t = alert.MwEventTypeKey } \n              equals new { d = smManualChapter.ID    , t = 300 }\n                  into temp1 \n              from tempChapter in temp1.DefaultIfEmpty()\n              select  alert\n        );	0
29314062	29313977	Sort a string property like Integer LINQ	var firstPart = originalItems.Where(x => !String.IsNullOrEmpty(x) && x.Page.All(char.IsDigit)).OrderBy(x => Convert.ToInt32(x.Page));\nvar secondPart = originalItems.Where(x => !String.IsNullOrEmpty(x) && !x.Page.All(char.IsDigit)).OrderBy(x => x.Page);\nvar thirdPart = originalItems.Where(x => String.IsNullOrEmpty(x)).ToList();\n\nvar result = firstPart.Union(secondPart).Union(thirdPart).ToList();	0
20211969	20211622	Composite pattern with generic leafs	public static class INodeExtensions\n{\n    public static void SetValue<T>(this INode node, string key, T v)\n    {\n        if(v is INode)\n        {\n            // category node set value\n            if(node is CategoryNode)\n            {\n                // convert and set value\n            }\n            else\n            {\n                throw new Exception("No children found.");\n            }\n        }\n        else\n        {\n            // value node set value\n        }\n    }\n}	0
12194501	12189673	Resolving interface with generic type using Castle Windsor	return queryHandler.Handle((dynamic)query);	0
17239636	17236965	Initialize log4net settings from database	string config = GetConfigFromDb();\nusing (var MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(config))\n{ \n     log4net.Config.XmlConfigurator.Configure(ms);\n}	0
15742834	15742714	How to sort a list by a specific property in .NET 2.0?	list.Sort(delegate(Point p1, Point p2){\n        return p1.X.CompareTo(p2.X);\n});	0
7729879	7722868	using legacy assemblies in metro style app	The project 'EmptyLib' cannot be referenced.	0
1016680	1016669	Mapping of some Data in c#	Dictionary< double, char> dic = new Dictionary< double, char>();\n//Adding a new item\nvoid AddItem(char c, double angle)\n{\n    if (!dic.ContainsKey(angle))\n        dic.Add(angle,c);\n}\n//Retreiving an item\nchar GetItem(double angle)\n {\n    char c;\n    if (!dic.TryGetValue(angle, out c))\n        return '';\n    else\n        return c;   \n }	0
15069451	15068982	Display table names of dataset in combox using LINQ	cboTables.ItemsSource = objDataset.Tables.OfType<DataTable>().Select(dt => dt.TableName);	0
23953049	23950333	Nhibernate, after insert, selecting the table results are old	var addQuestion = new Question()\n        {\n            Text = model.Question,\n            QuestionType = model.QuestionType,\n            Published = model.Published,\n            Country = module.Country,\n            Module = module\n        };\n\n        module.Questions.Add(addQuestion);\n        _moduleService.UpdateModule(module);	0
13518717	13436291	How do you write an Outlook Add-in that displays the sender's E-mail Address in a message box each time the user views an item?	public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)\n    {\n        applicationObject = (Outlook.Application)application;\n        this.applicationObject.ActiveExplorer().SelectionChange += new Microsoft.Office.Interop.Outlook.ExplorerEvents_10_SelectionChangeEventHandler(Explorer_SelectionChange);\n    }\n    void Explorer_SelectionChange()\n    {\n        if (applicationObject.ActiveExplorer().Selection.Count == 1)\n        {\n            Outlook.MailItem item = applicationObject.ActiveExplorer().Selection[1] as Outlook.MailItem;\n\n            if (item != null)\n            {\n               string address = item.SenderEmailAddress;\n               //do something\n            }\n        }\n    }	0
5602543	5602522	Using the Stopwatch to mesaure abstract method run time	public abstract class Monitor\n{\n    private readonly Stopwatch Timer = new Stopwatch(); \n    public void Run()\n    {\n        Timer.Start();\n        DoRun();\n        Timer.Stop();\n    }\n\n    protected abstract void DoRun();\n}	0
1188036	1188026	Source control for Visual Studio that doesn't require a server?	file:///D:/Projects/MyRepository	0
26741618	26741525	need to convert sql join query with count into linq and pass it to view	var countUser = (from u in db.Users\n                            join t in db.Teams\n                            on u.TeamId equals t.TeamId\n                            where (u.TeamId == 11)\n                            select new\n                            {\n                              u.UserId  \n                            }).Count();	0
17215312	17215218	built-in method for a nice HashSet representation as a string?	String.Join(", ", anyCollection)	0
24475068	23991658	How to click on all elements with the same class/parametr WatiN	Frame frameBODY = browser.Frame(Find.ByName("BODY"));\nLinkCollection links = frameBODY.Link;\n\nforeach(Link link in links)\n{\n  if(link.GetAttributeValue("href").Contains("javascript:void(0)"))\n  {\n    link.Click();\n\n    // TODO - Add logic here for saving the file.        \n  }\n}	0
480050	480033	Check two List<int>'s for the same numbers	List<int> a = new List<int>() { 1, 2, 3, 4, 5 };\nList<int> b = new List<int>() { 0, 4, 8, 12 };\n\nList<int> common = a.Intersect(b).ToList();	0
21189482	21189252	Secure connection string from winforms app to Azure SQL	string connectionString = myconnectionstringReadedFromFile;\n\n//\n// In a using statement, acquire the SqlConnection as a resource.\n//\nusing (SqlConnection con = new SqlConnection(myconnectionstringReadedFromFile))\n{\n    //\n    // Open the SqlConnection.\n    //\n    con.Open();\n\n    //.... your stuff\n\n}	0
32716408	32716281	How to place search pattern in app.config in C#	string FilePath = ConfigurationManager.AppSettings["myFile"].ToString();	0
14284314	14284216	How to use MemoryStream Instead of FileStream	using (MemoryStream m = new MemoryStream()) {\n  caf_doc.Save(m);\n  m.Position = 0;\n  // here you can read from the stream m\n}	0
27155003	27154760	How to access a variable outside an event handler when it is defined within the event handler in c#?	public class MyClass\n    {\n            private int handle;\n\n            private void button1_Click(object sender, EventArgs e)\n            {\n                handle = 0;\n            }\n\n            private void button2_Click(object sender, EventArgs e)\n            {\n                GetHandle();\n            }\n\n            private int GetHandle()\n            {\n                return handle;\n            }\n    }	0
20575427	20575277	WPF - Cannot change a GUI property inside the OnChanged method (fired from FileSystemWatcher)	// do stuff here                    \nConsole.WriteLine("top");\nthis.Dispatcher.BeginInvoke(new Action( () =>\n{\n    // This runs on the UI thread\n    BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get("blue ban 1"), "avatar");\n    Test_Button.Width = 500;\n}));\nConsole.WriteLine("bottom");	0
4351158	4350951	Strategies for automatic parallelization	var t1 = Task.Factory.StartNew<int>(() => 42);\n\nvar t2a = t1.ContinueWith<int>(t => t.Result + 1);\nvar t2b = t1.ContinueWith<int>(t => t.Result + 1);\n\nvar t3a = t2a.ContinueWith<int>(t => t.Result * 2);\nvar t3b = t2b.ContinueWith<int>(t => t.Result * 3);\n\nvar t4 = TaskEx.WhenAll<int>(t3a, t3b)\n               .ContinueWith<int>(t => t.Result[0] + t.Result[1]);\n\nt4.ContinueWith(t => { Console.WriteLine(t.Result); });\n\nConsole.ReadKey();	0
11080805	11080196	Save Xml Nodes Ordered by its Attribute	XElement El = XElement.Load(FilePath);\nEl.Descendants("banner").Where(b => b.Attribute("type").Value == "search-bar").First().ReplaceNodes(\n                El.Descendants("banner").Where(b => b.Attribute("type").Value == "search-bar").First().Descendants("item").OrderBy(o => int.Parse(o.Attribute("categoryid").Value)));\n            El.Save(FilePath);	0
24659444	24659372	Download files in pdf format no matter in what format they are uploaded	Response.AppendHeader("Content-Disposition", "attachment;filename=" + e.CommandArgument);	0
12912400	12897373	Best practices to avoid pross-thread/process database accessment	int GetTicketNumber(bool shouldIncrement)\n{\n\n   if(shouldIncrement)\n   {\n     // use transaction with serilizable isolation level\n     select and update\n   }\n   else\n   {\n     //just select\n   }\n\n}	0
3709704	3709645	How do I access the userid and password of a page using HTML Agility Pack?	HtmlDocument doc = new HtmlDocument();\ndoc.Load("file.htm");\ndoc.DocumentElement.SelectNodes("//input[@id=user1]");\ndoc.DocumentElement.SelectNodes("//input[@id=password1]");	0
6438062	6438015	C# object to array	object anArray = propInfo.GetValue(instance, null);\nIEnumerable enumerable = anArray as IEnumerable;\nif (enumerable != null)\n{\n    foreach(object element in enumerable)\n    {\n        // etc...\n    }\n}	0
31828162	31827587	Wpf change property action from xaml	public class TriggerActionClick : TriggerAction<Button>\n{\n    public string Value { get; set; }\n    public string TargetName { get; set; }\n\n    protected override void Invoke(object parameter)\n    {\n        if (AssociatedObject.DataContext != null && !string.IsNullOrEmpty(TargetName))\n        {\n            var type=AssociatedObject.DataContext.GetType();\n            var prop = type.GetProperty(TargetName);\n            if (prop != null)\n                prop.SetValue(AssociatedObject.DataContext,Value);\n        }\n\n    }\n}	0
19964740	19964305	Regex needed in C# to determine if multiple words are within N words	Regex monkey = new Regex(@".*[severe ][\b\w*\b ]{0,3}[aortic stenosis].*");	0
30379988	30361524	SignalR - Send message OnConnected	private async Task ConnectToSignalR()\n    {\n        var hubConnection = new HubConnection("url");\n        hubConnection.Headers["x-zumo-application"] = "clientapikey";\n\n        IHubProxy proxy = hubConnection.CreateHubProxy("ChatHub");\n\n        proxy.On<string>("hello", async (msg) =>\n        {\n            Console.WriteLine(msg);\n        });\n\n        await hubConnection.Start();\n    }	0
24516062	24387354	Invalid method parameters when trying to call RequestRefresh from C# to SCCM server	public void RefreshCollection(WqlConnectionManager connection, string collectionID)\n{\n   IResultObject collection = connection.GetInstance(string.Format("SMS_Collection.CollectionID='{0}'", collectionID));\n   collection.ExecuteMethod("RequestRefresh", null);\n}	0
18814939	18814734	How to check datareader and compare it with another value?	ol_com.CommandText = "select [card_id] from student_info where [card_id] = '" + card_No.Text + "'";\nreader = ol_com.ExecuteReader();\nif(reader.Read())\n{\n  if (reader.IsDBNull(0) || reader["card_id"].ToString() == "-")\n  {\n   //do my work here\n  }//end if\n\n  else\n  {\n    //give a message\n  }//end else\n}\n\nelse\n{\n  //give message that given value does not exist in database\n}	0
18192363	18191837	how to write this sql query using linq and lambda	var result = Inventory.Join(StockTransactions, x=>x.Id, x=>x.ItemId,(x,y)=>new {x,y})\n                      .GroupBy(a=>new {a.x.Id, a.x.Title})\n                      .SelectMany(a=>\n                         new {\n                                a.Key.Id,\n                                a.Key.Title,\n                                sold = a.Sum(b=> b.y.transactiontype == 1 ? b.y.MovedQuantity : 0),\n                                Revenue = a.Sum(b=>b.y.transactiontype == 1 ? b.y.MovedQuantity * b.y.UnitPrice : 0),\n                                distributed = a.Sum(b=> b.y.transactiontype == 0 ? b.y.MovedQuantity : 0)                       \n                             });	0
22276628	22276401	How a can split file line with many spaces in C# asp?	String.Substring	0
21107709	21095892	ActiveReports 7 - How to format data on multiples columns with a subreport	int i = 0;\npublic void Detail_Format()\n{\n    i = i + 1;\n    if(i > 9)\n      {\n         this.Detail.NewPage = GrapeCity.ActiveReports.SectionReportModel.NewPage.After;\n         i = 0;\n          }\n    else\n      {\n         this.Detail.NewPage = GrapeCity.ActiveReports.SectionReportModel.NewPage.None;\n          }\n}	0
12480479	12479771	TransformToVisual values change after pivot events	double x = ((MatrixTransform)gt).Matrix.OffsetX\nif (x < 0)\n{\n    // modding a negative number is equal to the negative modding of the positive number\n    x = 480 + (x % 480);\n}\nelse\n{\n    x = x % 480;\n}	0
8394886	8394839	Is it possible to run a Windows app within a console window?	static class Program\n{\n    static void Main(params string[] args)\n    {\n        if (args.Length > 0)\n        {\n           //do stuff here\n            return;\n        }\n          Window1 window = new Window1();\n          window.ShowDialog();\n    }\n}	0
9192626	9192011	How to write search query with multiple filter inputs in asp.net web form for ms sql	strSql = "SELECT ArticleID, ArticleTitle, ArticleDesc, ArticlePublishDate FROM \n\nart_Articles WHERE ";\nstrSql += "( ArticleVisible = 1 AND ArticleActive =1 AND LanguageID =" + LangID +" )";\nstrSql += " AND ";\nstrSql += " ( 0 = 1 ";\n\nif (cbArchiveTitle.Checked)\n{ strSql += " OR ArticleTitle LIKE N'%" + search + "%'  "; }\nif (cbArchiveDesc.Checked)\n{ strSql += " OR ArticleDesc LIKE N'%" + search + "%'  "; }\nif (cbArchiveSummary.Checked)\n{ strSql += " OR ArticleBodyDesc LIKE N'%" + search + "%'  "; }\n\nstrSql += ")";	0
13154512	13154424	C# how to populate a crystal report using LINQ	CrystalReport1 cr = new CrystalReport1();\n\n    var results = (from supp in dbdata.tSamples\n                  where supp.ID == IDNUMBER\n                  select new { supp.Name, supp.Model, supp.Producer }).ToList();\n\n    cr.SetDataSource(results);\n    crystalReportsViewer1.ReportSource = cr;	0
14851565	14851525	Compare hash encoded passwords	Encoding.UTF8.GetString(md5.ComputeHash(pass))	0
16544398	16543971	How to set height and width of a new window from code behind	function OpenWindow() {\n        window.open('../ReportWebForm.aspx?ReportType=Report','', 'width = 100, height = 100');\n    }	0
10555113	10554900	Standard method to unsubscribe from an event in a user control	protected override void Dispose(bool disposing)\n        {\n            if (disposing && (components != null))\n            {\n                components.Dispose();\n            }\n            base.Dispose(disposing);\n\n            Observatory.DataUpdated -= OnDataUpdate;\n\n        }	0
19414886	19414829	Removing <script> tags from HTML pages using C#	Regex rRemScript = new Regex(@"<script[^>]*>[\s\S]*?</script>");\noutput = rRemScript.Replace(input, "");	0
1484846	1484728	Verify a Loosely Defined File	const String fileName = @"foo.ini";\n\nconst String entryExpression = @"^\s*(?<key>[a-zA-Z][a-zA-Z0-9]*)\s*=" + \n                               @"\s*(?<value>[a-zA-Z][a-zA-Z0-9]*)\s*$";\n\nDictionary<String,String> entries = new Dictionary<String, String>();\n\nforeach (String line in File.ReadAllLines(fileName))\n{\n    Match match = Regex.Match(line, entryExpression);\n\n    if (match.Success)\n    {\n        String key = match.Groups["key"].Value;\n        String value = match.Groups["value"].Value;\n\n        if (entries.ContainsKey(key))\n        {\n            Console.WriteLine("Overwriting the key '{0}'.", key);\n        }\n\n        entries[key] = value;\n    }\n    else\n    {\n        Console.WriteLine("Detected malformed entry '{0}'.", line);\n    }\n}	0
5684743	5684580	Menu item fail to show what is in CSS	.menu\n{\n    padding: 4px 0px 4px 8px;\n}\n\n.menu ul\n{\n    list-style: none;\n    margin: 0px;\n    padding: 0px;\n    width: auto;\n}\n\n.menu ul li a, .menu ul li a:visited\n{\n    background-color: #465c71;\n    border: 1px #4e667d solid;\n    color: #dde4ec;\n    display: block;\n    line-height: 1.35em;\n    padding: 4px 20px;\n    text-decoration: none;\n    white-space: nowrap;\n}\n\n.menu ul li a:hover\n{\n    background-color: #bfcbd6;\n    color: #465c71;\n    text-decoration: none;\n}\n\n.menu ul li a:active\n{\n    background-color: #465c71;\n    color: #cfdbe6;\n    text-decoration: none;\n}	0
4430886	4429995	How do you remove repeated characters in a string	Regex r = new Regex("(.)(?<=\\1\\1\\1)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);\n\nvar x = r.Replace("YOU SUCCCCCCCCCCCCCCCCCKKKKKKKKKKKKKKKKKK", String.Empty);\n// x = "YOU SUCCKK"\n\nvar y = r.Replace("OMGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG!!!!!!!!!!!!!!!", String.Empty);\n// y = "OMGG!!"	0
5178752	5131649	About XML Data Binding to the Datagridview	XDocument oDoc = XDocument.Load("File.xml");\n var myData = from info in oDoc.Descendants("item")\n select new Person\n {\n     FirstName = Convert.ToString(info.Element("FirstName").Value),\n     LastName = Convert.ToString(info.Element("LastName").Value),\n     Age = Convert.ToString(info.Element("Age").Value),\n     IsMale = Convert.ToString(info.Element("IsMale").Value)\n };\n oGrid = this.FindName("myDataGrid") as DataGrid;\n oGrid.ItemsSource = myData;	0
11143682	11143450	C# Visual Web Developer: Listing All Files In A Directory As A DropDownList	var fileList = Directory.GetFiles("path to your dir");\nDropDownList ddl = new DropDownList();\nddl.DataSource = fileList;\nddl.DataBind();	0
7749541	7749496	Regular Expression: match word at start of sentence	(?<=[.:?!]\s)Jill\b	0
24197360	24196988	How can i draw string in paint event each line in a different color?	Random r = new Random();\nfor (int i = m_text.Length - 1; i >= 0; i--)\n{\n\n    Point pt = new Point((int)((this.ClientSize.Width - e.Graphics.MeasureString(m_text[i], m_font).Width) / 2),\n        (int)(m_scrollingOffset + this.ClientSize.Height - (m_text.Length - i) * m_font.Size));\n\n    // Adds visible lines to path.\n    if ((pt.Y + this.Font.Size > 0) && (pt.Y < this.Height))\n    {\n        path.AddString(m_text[i], m_font.FontFamily, (int)m_font.Style, m_font.Size,\n            pt, StringFormat.GenericTypographic);\n\n        visibleLines++;\n    }\n\n\n    Color c = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));\n    Font drawFont = new Font("Arial", 16);  \n    e.Graphics.DrawString( m_text[i], drawFont, new SolidBrush(c), pt);\n}	0
578242	578231	Issues Doing a String Comparison in LINQ	var zipLinqQuery =\n    from z in db.ZIPMASTERs\n    where z.CORP == 12\n    && z.ZIPBEG.CompareTo("85546 ") <= 0\n    && z.ZIPEND.CompareTo("85546 ") >= 0\n    select z;	0
5701964	5701742	howto sort a asp:Table?	YourTableName.DefaultView.Sort = "YourColumnName ASC";\nYourTableName.DefaultView.Sort = "YourColumnName DESC";	0
3617335	3617193	How can I test if the current request is an ajax request in a Controller?	if (Request.IsAjaxRequest())	0
32245857	32242963	Win Form change its size when I create a WPF Window	[assembly: System.Windows.Media.DisableDpiAwareness]	0
23669951	23669502	Unity Container Multiple Implementations of same interface	new Canvas(container.Resolve<IRenderer>("GL"));	0
29213655	29213519	How do I create a copy of a picture to a specific path in winform	string picloc;\nstring new_loc;\nprivate void UpdBtn_Click(object sender, EventArgs e)\n{\n    dlg.Filter = "JPG Files(*.jpg)|*.jpg|PNG Files(*.png)|*.png|ALL Files(*.*)|*.*";\n    dlg.Title = "Select Thumbnail";\n    if (dlg.ShowDialog() == DialogResult.OK)\n    {\n        // Result();\n        picloc = dlg.FileName.ToString();\n        pic1.ImageLocation = picloc;\n        File.Copy(picloc, new_loc); // new_loc being the new location for the file.\n    }\n\n}	0
2772196	2772166	How to set Border.BorderBrush from string	BrushConverter converter = new BrushConverter();\nBorderBrush brush = converter.ConvertFromString("#FFBCC7D8") as Brush;\n((Border)((Image)sender).Parent).BorderBrush = brush;	0
20041624	20041594	find list of one item not in second list	var items = _strImportFields.Except(_strImportFields2);	0
20188152	20187985	Form will add a labels based on how many data are in the database in C#	//your code to retrieve data from database\n\nfor(int i=0;i<N;i++)\n    {\n        Label l = new Label();\n        l.ID = "lbl" + i.ToString();\n        l.Visible = true;\n        l.Text = "Your text here";\n        this.Page.Controls.Add(l);\n    }	0
23434765	23373411	How to send email from a TFS plugin?	string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];	0
8481676	8481640	Adding blank spaces into a string in C#	String coNum = customerOrderLine.coNum.PadLeft(10);	0
28035500	28035082	C#: How to minimize IE to get a screenshot of background	//this will maximize the browser and also helps you to set focus on actual browser not on IEDriverServer exe\nIWebDriver driver = new InternetExplorerDriver(@"C:\myCSharp\mySelenium\mySelenium\");\ndriver.Navigate().GoToUrl("some url");\ndriver.Manage().Window.Maximize();	0
10929167	10929037	How to save data from datagridview to SQL Server 2008 R2	using (SqlConnection connect = new SqlConnection(connectionString))\n? ? {\n? ? ? using(SqlCommand command = new SqlCommand())\n       {\n? ? ? ? command.Connection = connect;\n? ? ? ? command.CommandText = "insert into customer(name, address) values(@name, @address)";\n\n? ? ? ? command.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar));\n? ? ? ? command.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar));\n        connect.Open();\n        foreach (DataGridViewRow row in dataGridView1.Rows)\n         {\n          if(!row.IsNewRow)\n           {\n             command.Parameters["@name"].Value = row.Cells[0].Value;\n? ? ? ?      command.Parameters["@address"].Value = row.Cells[1].Value;\n             command.ExecuteNonQuery();\n           }\n         }\n      }\n? ? }	0
3439735	3439600	DataGridView: Format values without actually changing the bounded data?	private void dataGridView1_CellFormatting(object sender, \n    DataGridViewCellFormattingEventArgs e)\n{\n    if (e.ColumnIndex == 0) // Check for the column you want\n    {\n        e.Value = Path.GetFileName(e.Value.ToString());\n        e.FormattingApplied = true;\n    }\n}	0
9178251	9177852	merging the content of a directory using cmd shell	Process.Start("cmd", "copy " + command);	0
32361302	31844226	Skybrud social Log in via Facebook?	// Declare the options for the call to the API\nFacebookGetUserOptions options = new FacebookGetUserOptions("me") {\n    Fields = "name,email,gender"\n};\n\n// Make the call to the API\nFacebookUserResponse response = service.Users.GetUser(options);	0
10453338	10453297	Iteration bound variable?	var combination = aList\n      .Select(x => new { Initial = x, Addition = AProcedureToGenerateNewUniqueStr() })\n      .ToList()\n      .ForEach(x =>\n           { \n               print(x.Initial + x.Addition);\n           });	0
21365087	21364947	Format string placeholders	Format Item	0
12981654	12981633	Unit tests with GUID	var guid = new Guid("62FA647C-AD54-4BCC-A860-E5A2664B019D");	0
8649585	8649540	Regex help, words that contain numbers without a space	(?<aMatch>[a-zA-Z]+[0-9]+)	0
6915034	6900747	How to make discriminator table more useful	public class StatusMap : ClassMap<Status>\n{\n    public StatusMap()\n    {\n        Id(x => x.Id, "ItemStatus").GeneratedBy.Assigned();\n\n        DiscriminateSubClassesOnColumn<int>("ItemStatus", 0);\n    }\n}	0
12579411	12579364	Case-insensitive regex to change html <br> tag	result = Regex.Replace(subject, @"<br\s*/>", "<br>", RegexOptions.IgnoreCase);	0
24089810	24089506	how to combine same elements and sum their values in lists in C#	private void hereIsYourAnswer()\n    {\n        string [] first = { "1", "saka", "2", "1", "1", "3", "saka", "1", "stack", "3" };\n        int [] second = { 20, 23, 25, 30, 20, 15, 16, 61, 34, 35 };\n\n        List<String> F = new List<string>();\n        List<int> S = new List<int>();\n\n        for (int i = 0; i < first.Length; i++)\n        {\n            if (F.Contains(first[i]))\n                S[F.IndexOf(first[i])] += second[i];\n            else\n            {\n                F.Add(first[i]);\n                S.Add(second[i]);\n            }\n\n        }\n\n        for (int i = 0; i < S.Count; i++)\n            MessageBox.Show(F[i] + " = " + S[i].ToString());\n\n                //Output\n                //1=131\n                //saka=39\n                //2=25\n                //3=50\n                //stack=34\n\n\n    }	0
22472000	22453832	Close Popup Window after insert	ScriptManager.RegisterStartupScript(this, this.GetType(), "onclick", "window.close()", true);	0
3711318	3711279	LINQ Comparing Two Lists - Add new, remove old, leave the ones in common	L1.AddRange(L2.Except(L1));\nL1.RemoveAll(item => !L2.Contains(item));	0
10642701	10642590	Parsing JSON page	dynamic jObj = JsonConvert.DeserializeObject(new WebClient().DownloadString("your url"));\nforeach (var item in jObj.statuses)\n{\n    Console.WriteLine("{0} {1}", item.in_reply_to_status_id_str, item.id_str);\n}	0
13581273	13580923	hyperlink in datagrid not getting disabled in firefox	href="javascript:void(0)"\n\n Hlnk.Attributes.Add("href","javascript:void(0)");	0
32572356	32548355	How to upload image file in gridview?	if (fileUpload.HasFile)\n{\n       fileUpload.SaveAs(Server.MapPath("uploadedimages/" + fileUpload.FileName));\n}	0
18122689	18122484	Validating if a combobox it's SelectedText property is empty always fails	if (comboBox1.SelectedIndex == -1)//Nothing selected\n{\n    MessageBox.Show("You must select a conversion type", "Error");\n}\nelse\n{\n    //Do Magic   \n}	0
16369821	16369455	Why cant I fill my list variable with the xml values?	var url = @"http://www.technewsworld.com/perl/syndication/rssfull.pl";\nvar xdoc = XDocument.Load(url);\nvar v = xdoc.Descendants().Where(e => e.Name.LocalName == "item");\nvar items = v.Select(item => new\n            {\n                Title = item.Descendants().Where(e => e.Name.LocalName == "title").First().Value,\n                Description = item.Descendants().Where(e => e.Name.LocalName == "description").First().Value,\n                Link = item.Descendants().Where(e => e.Name.LocalName == "link").First().Value,\n                //PubDate = item.Descendants().Where(e => e.Name.LocalName == "dc:date").First().Value,\n                //MyImage = item.Descendants().Where(e => e.Name.LocalName == "content:encoded").First().Value,\n            })\n            .ToList();	0
20153514	20153231	DataBinding in to object in List	Text="{Binding Path=name, UpdateSourceTrigger=PropertyChanged}"	0
31661105	31660978	Set an Environment Variable Programatically in the Machine Scope and send SettingsChange Message	Environment.SetEnvironmentVariable	0
13011381	13011334	If label's text width is greater than total width of its container then show sub-string using intelligence of pixels	overflow:hidden;\ntext-overflow: ellipsis;	0
20432421	20432379	Remove last line from a string	str = str.Remove(str.LastIndexOf(Environment.NewLine));	0
24982399	24981300	Assign JSON value to property in C#	TheJSON.main.temp.ToString()	0
22666765	22666604	Database for customer and it family members	using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))\n{\n    SqlCommand addvalues = new SqlCommand(@"INSERT INTO customer (id,name,age,occupation) VALUES (@id,@name,@age,@occupation)", conn);\n    addvalues.Parameters.AddWithValue("@bla", "bla");\n    addvalues.Connection.Open();\n    addvalues.ExecuteNonQuery();\n    addvalues.Connection.Close();\n}	0
17805866	17805765	How to connect to local SQL database?	Provider=SQLNCLI10;Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;\nDatabase=dbname;Trusted_Connection=Yes;	0
11740035	11738917	get value from object data source	DataTable dt1 = new DataTable();  // for temporary storage\nDataSet1TableAdapters.sp_Units_GetUnitState  objAda = new DataSet1TableAdapters.sp_Units_GetUnitState();\ndt1 = objAda.GetData(txtPadidehOrAtkinsCode.Text);\n\n// Now get the state from the datatable\nstring state = dt1.Rows[0][0].ToString();	0
767827	767767	Finding multiple indexes from source string	var indexs = "Prashant".MultipleIndex('a');\n\n//Extension Method's Class\n    public static class Extensions\n    {\n         static int i = 0;\n\n         public static int[] MultipleIndex(this string StringValue, char chChar)\n         {\n\n           var indexs = from rgChar in StringValue\n                        where rgChar == chChar && i != StringValue.IndexOf(rgChar, i + 1)\n                        select new { Index = StringValue.IndexOf(rgChar, i + 1), Increament = (i = i + StringValue.IndexOf(rgChar)) };\n            i = 0;\n            return indexs.Select(p => p.Index).ToArray<int>();\n          }\n    }	0
4106212	3992110	HTTP Post XML document - server receives only first line	loHttp.SendChunked = true;\n loHttp.TransferEncoding = "7bit";	0
5512126	5511974	Gridview dynamically add new row	protected void Button1_Click(object sender, EventArgs e)\n{\n    if (FileUpload1.HasFile)\n    {\n        if (Session["dtbl"] == null)\n        {\n            DataTable dtbl = new DataTable();\n            DataColumn FileName = new DataColumn("FileName", System.Type.GetType("System.String"));\n            dtbl.Columns.Add(FileName);\n            Session["dtbl"] = dtbl;\n        }\n\n        DataTable dtbl = (DataTable)Session["dtbl"];\n        DataRow myRow;\n        myRow = dt.NewRow();\n        myRow["FileName"] = FileUpload1.FileName;\n        dtbl.Rows.Add(myRow);\n\n        gridView1.DataSource = dtbl.DefaultView;\n        gridView1.DataBind();\n\n        Session["dtbl"] = dtbl;\n    }\n}	0
1175903	1175873	C#: parametrized string with spaces only between "full" parameters?	string.Format("{0} {1} {2}", first, middle, last).Replace("  "," ")	0
4978186	4978137	C# SQL SUM value to a label	string query = "SELECT SUM (Price) FROM Bill";\nusing (System.Data.IDbCommand command = new System.Data.OleDb.OleDbCommand(query, DBconn))\n{\n   object result = command.ExecuteScalar();\n   TotalValueLabel.Text = Convert.ToString(result);;\n}	0
13211810	13211703	How to check for FtpWebRequest timeout	Try\n    //your code for request/response\n  Catch ex As WebException\n    MsgBox("Exception reason "&ex.State)\n  End Try	0
4678347	4678282	How to add a child node to a dynamically added child node	public void loadFromForm(string strNode, bool bResult, string strStandardClsCode)\n    {\n        if (Append.oldbatchcontrol != strNode)\n        {\n            if (tvwACH.SelectedNode.Text == "FileHeader")\n            {\n                tvwACH.SelectedNode.Nodes.Add(strNode);\n            }\n            if (tvwACH.SelectedNode.Text == "BatchHeader")\n            {\n                TreeNode node = tvwACH.SelectedNode.Nodes.Add(strNode,strNode);// After this i have to add another node as a child to that added node and also if a node with particular name exists i would like to write the text with a count value appended\n                node.Nodes.Add(...);\n            }\n  }\n}	0
3981461	3981382	C# word boundary regex instead of .Contains() needed	var myList = new List<string> { "red", "blue", "green" };\n        Regex r = new Regex("\\b(" + string.Join("|", myList.ToArray()) + ")\\b");\n        MatchCollection m = r.Matches("Alfred has a red and blue tie");	0
1593329	1593303	Link SQL Database to Date	DataTime.Parse(dateStr).DayOfWeek	0
27235470	27235334	Unable to combine two linq results in one var	var xAxisconceptIdsAndName = _analysisResult.Select(x => new \n    { \n        ConceptId = x.ConceptId1, \n        ConceptDisplay = x.ConceptDisplay1 \n    }).Distinct();\nvar yAxisconceptIdsAndName = _analysisResult.Select(x => new \n    { \n        ConceptId = x.ConceptId2, \n        ConceptDisplay = x.ConceptDisplay2 \n    }).Distinct();\nvar combined = xAxisconceptIdsAndName.Concat(yAxisconceptIdsAndName);	0
12693592	12688805	Reading pivot table with c#	Provider=Microsoft.ACE.OLEDB.12.0	0
15637575	15632644	ReshSharp / ASP.NET WebAPI - Using POST with url parameters	[RequireUserToken(ApprovedDeviceToken = true, ValidUserToken = true)]\n[HttpPost]\npublic IEnumerable<SynchronizeItem<IReferenceDataItem>> Sync(IEnumerable<SynchronizeItem<IReferenceDataItem>> clientSyncItems, int referenceDataType)\n{\n    // my code\n}	0
5037566	5037531	How can I set a DateTimePicker value as today's date+1	var myDate = DateTime.Now.AddDays(1);	0
1711126	1711096	Processing XML from a Table (with one line in one record each)	XDocument.Parse(string text)	0
3462564	3462491	LINQ query on a list of Object[] arrays	int textBoxCount = controlsList.Count(o => (int)o[0] == 1);\nint checkBoxCount = controlsList.Count(o => (int)o[0] == 2);	0
11832769	11832684	Order collection of items with multiple date fields	var newList = \n      list.OrderByDescending(s=>Math.Max(s.DateCreated.Ticks,s.DateUpdated.Ticks));	0
3314505	3314443	Creating an IronPython (dynamic) object from a string	var engine = Python.CreateEngine();\ndynamic calculator = engine.CreateScope();\nengine.Execute(GetPythonScript(), calculator);	0
2759862	2759844	How to change the type return by DataGridViewCellCollection to fit Custom DatagridViewCell	MonthCalendarCell cell = this.Rows[i].Cells[j] as MonthCalendarCell;\nif(cell != null)\n{\n   cell.date = this.jourDuMois.ElementAt(i * 7 + j);\n}	0
5398550	5398244	Change Binding of ContentControl Based on Selection in one of two ListBoxes	this.ExpandedAllergyDetails.SetResourceReference(ContentControl.ContentProperty, "InsideAllergiesSource");	0
18959300	18956558	Image opacity binding in windows phone apps	Binding b = new Binding();\nb.Source = opacityslider;\nb.Path = new PropertyPath("Value");\nsampleimg.SetBinding(Image.OpacityProperty, b);	0
2270816	2270528	How can I set a value on a Linq object during the query?	Trip SetProperty(Trip t)\n{\n    t.property = "value";\n    return t;\n}\nvar trips = from t in ctx.Trips select SetProperty(t);	0
5406890	5405895	How to check internet connection with .NET, C#, WPF	private bool CheckConnection(String URL)\n    {\n        try\n        {\n            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);\n            request.Timeout = 5000;\n            request.Credentials = CredentialCache.DefaultNetworkCredentials;\n            HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n            if (response.StatusCode == HttpStatusCode.OK) return true;\n            else return false;\n        }\n        catch\n        {\n            return false;\n        }\n    }	0
10023468	9963416	DataGridView is blank after Changing DataSource at Runtime	dgvMyPatients.Columns.Clear(); and dgvMyPatients.Refresh();	0
10808050	10807461	Getting content between two HTML tags using Html Agility Pack	private List<HtmlNode> GetSection(HtmlDocument helpDocument, string SectionName)\n{\n    HtmlNode startNode = helpDocument.DocumentNode.Descendants("div").Where(d => d.InnerText.Equals(SectionName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();\n    if (startNode == null)\n        return null; // section not found\n\n    List<HtmlNode> section = new List<HtmlNode>();\n    HtmlNode sibling = startNode.NextSibling;\n    while (sibling != null && sibling.Descendants("h1").Count() <= 0)\n    {\n        section.Add(sibling);\n        sibling = sibling.NextSibling;\n    }\n\n    return section;\n}	0
20535420	20535297	How to prevent MessageBox on Exception in C#?	db.Insert();	0
814674	814655	How to copy all different elements from an array in c#	List<double> uniques = new List<double>;\nforeach (double num in numbers)\n{\n  if (!uniques.Contains(num)) uniques.Add(num);\n}\n\ndouble[] uniquearray = uniques.ToArray();	0
28639890	28638666	Define Next Start Point When Number of Items Unknown	private int _index = -1; // -1 so first request starts at 0\n    private bool _shouldContinue = true;\n\n    public IEnumerable<RequestStuff> GetAllData()\n    {\n        var tasks = new List<Task<RequestStuff>>();\n\n        while (_shouldContinue)\n        {\n            tasks.Add(new Task<RequestStuff>(() => GetDataFromService(GetNextIndex())));\n        }\n\n        Task.WaitAll(tasks.ToArray());\n\n        return tasks.Select(t => t.Result).ToList();\n    }\n\n    private RequestStuff GetDataFromService(int id)\n    {\n        // Get the data\n\n        // If there's no data returned set _shouldContinue to false\n\n        // return the RequestStuff;\n    }\n\n    private int GetNextIndex()\n    {\n        return Interlocked.Increment(ref _index);\n    }	0
11972507	11972166	Valid JSON to Object in C#	var obj = (JObject)JsonConvert.DeserializeObject(json);\n\nforeach (JProperty item in obj["ABCXYZ"].Children())\n{\n    Console.WriteLine(item.Name);\n    foreach (var x in item)\n    {\n        foreach (var y in x)\n        {\n            Console.WriteLine("\t==> " + y[0]);\n        }\n    }\n}	0
26258976	26258845	Anonymous Types - How to dynamically create?	var data2 = myList.Select(x => new { Name = x.Stat, Value = x.Total }).ToArray();\n\nreturn Json(data2);	0
3234632	3234605	Instantiation in a loop: Verbosity vs. Performance	new ProductCategoryModel.ProductCategoryModelConverter(currentContext)	0
30541300	30541264	Count how many times a character changes in a string	string value = "fffeefef";    // Set some value to use in the example\nint counter = 0;              // Initialize the counter, still zero changes found\nfor (int i = 1; i < value.Length; i++)    // Make a loop, iterating for every char in the string\n{\n    if (value[i - 1] != value[i])    // Compare every char with the previous char, starting at char 1 (the second char, as first position is zero).\n        counter++;            // If the chars are different, increase our counter\n}	0
23364534	23364395	Regex for Azure blob containers	Regex regEx = new Regex("^[a-z0-9](?:[a-z0-9]|(\\-(?!\\-))){1,61}[a-z0-9]$|^\\$root$");\n        var isContainerNameValid = regEx.IsMatch(containerName);	0
18992390	18992292	Split alphanumeric string to array containing the alphabet and numeric characters separately	string input = "Foo123Bar";\nvar array = Regex.Matches(input, @"\D+|\d+")\n                 .Cast<Match>()\n                 .Select(m => m.Value)\n                 .ToArray();	0
17096919	17096761	Overloading Index method of Controller	routes.MapRoute(\n     name: "CategoriesMapping",\n     url: "Category/{categoryName}",\n     defaults: \n         new { controller = "Categoria", action = "Index", \n                     categoryName = URLParameters.Optional \n             }\n );\n\nroutes.MapRoute(\n     name: "Default",\n     url: "{controller}/{action}/{id}",\n     defaults: \n         new { controller = "Home", action = "Index", \n                     id = URLParameters.Optional \n             }\n );	0
12656554	12656526	Find a row in a DataTable	void Demo(DataSet ds)\n{\n    DataTable dt = ds.Tables[0]; // refer to your table of interest within the DataSet\n\n    dt.Select("Field = 1"); // replace with your criteria as appropriate\n}	0
26284676	26284226	Apply custom ascx attribute to underlying html	Dim keys As IEnumerator = Me.Attributes.Keys.GetEnumerator()\n\n    While keys.MoveNext\n\n        Dim key As String = keys.Current.ToString\n\n        If key.Contains("data-") Then\n\n            TextBox1.Attributes.Add(key, Me.Attributes(key))\n\n        End If\n\n    End While	0
21101276	21100917	Type in two text boxes simulatenously	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    protected override void OnLoad(EventArgs e)\n    {\n        base.OnLoad(e);\n        textBox1.TextChanged+=new EventHandler(textBox_TextChanged);\n        textBox2.TextChanged+=new EventHandler(textBox_TextChanged);            \n    }\n\n    void textBox_TextChanged(object sender, EventArgs e)\n    {\n        string text=(sender as TextBox).Text;\n        if(!textBox1.Text.Equals(text)) { textBox1.Text=text; }\n        if(!textBox2.Text.Equals(text)) { textBox2.Text=text; }\n    }\n\n}	0
31783316	31740941	Method parameters are being separated into new lines	Code Editing | C# | Line Breaks and Wrapping | Line Wrapping -> Wrap long lines	0
31716607	31715361	Create a User-Defined Convertion for Generic Type	return ((YourPrincipal)principal).Identity.Name;	0
3433142	3432890	Online highscore for my game	WebRequest req = WebRequest.Create("http://my.site.com/reportscore");\nreq.Method = "POST";\nreq.ContentType = "application/x-www-form-urlencoded"; // or something like that\n\nStream reqStream = req.GetRequestStream();\nbyte[] encoded = Encoding.UTF8.GetBytes("score=12345&name=Somebody");\nreqStream.Write(encoded, 0, encoded.Length);\nreqStream.Close();\n\nWebResponse resp = req.GetResponse();	0
8240864	8229078	Customizing the xmlns:a= tag in a soapresponse from WCF	[DataContract(Namespace = "http://correctnamespace.com")]\npublic class Amount\n{	0
9720821	9720770	how to execute shell command with arguments?	p.StartupInfo.FileName = Path.Combine(Directory.GetCurrentDirectory(), "timesync\\NistClock.exe");\np.StartupInfo.Arguments = "sync";	0
3183735	3183712	CheckBox Grouping	chkboxes1.CheckedChanged += new EventHandler(chkboxes_CheckedChanged);\nchkboxes2.CheckedChanged += new EventHandler(chkboxes_CheckedChanged);\nchkboxes3.CheckedChanged += new EventHandler(chkboxes_CheckedChanged);	0
31269572	31269417	How to get the values from a column in Excel in uppercase after putting them into a DataTable	foreach (DataRow row in dataTable.Rows)\n{\n    row["Test"] = row["Test"].ToString().ToUpper();\n}	0
10733651	10733590	Game Development - Avoiding Flickers	Double Buffering	0
25494747	25494344	Building C# Solution in Release mode using MsBuild.exe	MsBuild.exe [Path to your solution(*.sln)] /t:Build /p:Configuration=Release /p:TargetFramework=v4.0	0
2417586	2417550	how to find a string pattern and print it from my text file using C#	string s = "abcde";\nint index = s.IndexOf("abc");\nif (index > -1 && index < s.Length - 4)\n    Console.WriteLine(s.SubString(index + 3, 2));	0
21160940	21160913	Avoiding escaped values in closures	for(int i=0; i<10; i++)\n{\n    int number = i;\n    MyApi.AddLazyCreate(() => new foo(/*other params*/ number)); \n}	0
5956386	5956364	AutoCompleteExtender help needed	public string[] GetVendor(string prefixText, int count)	0
8108124	8107823	How do I get the associated form object of data from SQL data	// here goes fully qualified name,\n// format: TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly\nstring typeName = "WindowsFormsApplication4.frmStore,WindowsFormsApplication4";\nType frm = Type.GetType(typeName);\nForm f = Activator.CreateInstance(frm) as Form;\nif (f != null)\n    f.Show();	0
9635628	9635418	Function that returns a Generic List	public static List<T> GenericFunc<T>(string myfield, string TABLENAME)\n{\n   return nwModel.ExecuteQuery<T>("SELECT " + myfield + " FROM " + TABLENAME).ToList();\n}	0
7930289	7927538	Group by two columns in DataTable Column sum	var result = from r in dt.AsEnumerable()\n             group r by new { Group = r["Group"], Type = r["Type"] } into g\n             select new { Group = g.Key.Group, \n                          Type = g.Key.Type, \n                          Sum = g.Sum(x => Convert.ToInt32(x["Rate"])) };\n\nforeach (var r in result)\n{\n    Console.WriteLine("Group {0}, Type {1}, Sum {2}", r.Group, r.Type, r.Sum);\n}	0
8733957	8733889	Deserialize binary data without knowing the exact type written	ISerializable.GetObjectData	0
19810657	19810619	String comparison with several character match	Regex.IsMatch("test","te[smf]t");	0
24422709	24422684	How do I grab the last string from a index by detecting the comma?	string last = str.Substring(str.LastIndexOf(',')+1)	0
15007418	15007152	How to Disable Converter Under Certain Situations	Binding.DoNothing	0
14168643	14168525	How to copy an array using reflection?	if(property.PropertyType == typeof(System.Byte[]))\n{\n    property.SetValue(this, someArray.Clone(), null); \n}	0
14748990	14748105	Parse Byte[] to File without saving it	public void HandleMycontent(byte[] content)\n    {\n        using (var stream = new System.IO.MemoryStream(content))\n        {\n            using (var reader = new StreamReader(stream))\n            {\n                using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))\n                {\n                    //parse my csv here\n                }\n            }\n        }\n    }	0
9455878	9454756	Draw Oval to array	DrawingVisual drawingVisual = new DrawingVisual();\n\nusing (DrawingContext drawingContext = drawingVisual.RenderOpen())\n{\n    drawingContext.DrawEllipse(null, new Pen(Brushes.Black, 1), new Point(100, 100), 50, 50);\n}\n\nDrawing drawing = drawingVisual.Drawing;\n\nusing (DrawingContext drawingContext = drawingVisual.RenderOpen())\n{\n    drawingContext.DrawDrawing(drawing);\n    drawingContext.DrawEllipse(null, new Pen(Brushes.Black, 1), new Point(100, 100), 60, 60);\n}\n\nRenderTargetBitmap bitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Default);\nbitmap.Render(drawingVisual);	0
21318788	21318671	Watch a variable from another thread?	using System;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n    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            var logChecker = new LogChecker();\n            logChecker.FinishedExvent += () => MessageBox.Show( "Finished" );\n            logChecker.Start();\n        }\n    }\n\n    internal class LogChecker\n    {\n        public void Start()\n        {\n            var thread = new Thread( CheckLog );\n            thread.Start();\n        }\n\n        private void CheckLog()\n        {\n            var progress = 0;\n            while ( progress < 3000 )\n            {\n                Thread.Sleep( 250 );\n                progress += 250;\n            }\n            FinishedExvent();\n        }\n\n        public event TestEventHandler FinishedExvent;\n    }\n\n    internal delegate void TestEventHandler();\n}	0
21131308	21123956	Not Recieving data into text file on sending Machine Credentials in TCP/IP protocol	buf = String.Format("{0}\r\n{1}\r\n", "SMDR", "PCCSMDR");	0
24081416	23707475	DCOM Config settings for Microsoft Interop Word Automation	public void HelloWorld(string docName) \n{\n  // Create a Wordprocessing document. \n  using (WordprocessingDocument package = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document)) \n  {\n    // Add a new main document part. \n    package.AddMainDocumentPart(); \n\n    // Create the Document DOM. \n    package.MainDocumentPart.Document = \n      new Document( \n        new Body( \n          new Paragraph( \n            new Run( \n              new Text("Hello World!"))))); \n\n    // Save changes to the main document part. \n    package.MainDocumentPart.Document.Save(); \n  } \n}	0
2414685	2286827	Using Pragma-s of SQLite in C#	String conString = "Data Source=filename;Version=3;PRAGMA locking_mode = NORMAL;"	0
1507741	1507452	Issues overwriting a cookie	if (Request.Cookies["cookie"] != null)\n{\n  HttpCookie myCookie = new HttpCookie("cookie");\n  myCookie.Domain = ".url.com";\n  myCookie.Expires = DateTime.Now.AddDays(-1d);\n  Response.Cookies.Add(myCookie);\n}	0
4707178	4707138	How can I get ConnectionString Name for config file	ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;\n\nif (connections.Count != 0)\n{\n    foreach (ConnectionStringSettings connection in connections)\n    {\n        string name = connection.Name;\n    }\n}	0
20859327	20859247	Passing a CheckBox or RadioButton to a method	if (x is System.Windows.Forms.RadioButton)\n    (x as System.Windows.Forms.RadioButton).Checked = enabled;\nelse if (x is System.Windows.Forms.CheckBox)\n    (x as System.Windows.Forms.CheckBox).Checked = enabled;	0
15040551	15040533	Difference between comparing string length and string value	if (int.Parse(input1) < 4) {\n    ...\n}	0
15987581	15986473	How do I implement word wrap?	public string WrapText(SpriteFont spriteFont, string text, float maxLineWidth)\n{\n    string[] words = text.Split(' ');\n    StringBuilder sb = new StringBuilder();\n    float lineWidth = 0f;\n    float spaceWidth = spriteFont.MeasureString(" ").X;\n\n    foreach (string word in words)\n    {\n        Vector2 size = spriteFont.MeasureString(word);\n\n        if (lineWidth + size.X < maxLineWidth)\n        {\n            sb.Append(word + " ");\n            lineWidth += size.X + spaceWidth;\n        }\n        else\n        {\n            sb.Append("\n" + word + " ");\n            lineWidth = size.X + spaceWidth;\n        }\n    }\n\n    return sb.ToString();\n}	0
25294983	25294947	Combining Multiple LINQ Queries as OR statements in each query	query = query.Where(t => userClubs.Contains(t.Club));	0
5466221	5466187	Update one to many relationship data in database	delete many_table\nwhere studentid=@studentid and someid not in (select someid from @tableparam p)\n\ninsert many_table(studentid, someid)\nselect @studentid, p.someid\nfrom @tableparam p left join many_table t on p.someid=t.someid and t.studentid=@studentid\nwhere t.someid is null	0
29229213	29228751	Deserialize json response	JObject.Parse(response)["enrollDeviceErrorResponse"].Type	0
15227412	15227339	Deleting an item with entity framework	public void DeleteBook(int bookId)\n    {\n        Book book = (Book)bookContext.Books.Where(b => b.Id == bookId).First();\n        bookContext.Books.Remove(book);\n    }	0
32501696	32501642	Work with interface but keep concrete values	static List<G> FilterGuidObjects<G>(List<G> objects) where G: GUID_OBJECT\n{\n    return objects.Where(x => x.GUID == "1").ToList();\n}	0
18121929	18084657	How to get all PowerPoint files from Skydrive?	LiveConnectClient client = new LiveConnectClient(App.Session);\n            LiveOperationResult liveOperationResult = await client.GetAsync("me/skydrive/search?q=.ppt");\n            dynamic searchResult = liveOperationResult.Result;	0
19676640	19676265	using ipv6 address to connect to a server using HttpClient (using ipv6 address to define URI) Fixing - Invalid URI: Invalid port specified)	this.Client.BaseAddress = new Uri(@"http://[ef08::83e7:71e8:1364:0dff]:54502/");	0
31715155	31582659	How can I share a 'unit of work' between multiple service methods?	private async Task<bool> AddCustomerToGroupInternalAsync(int customerId, int groupId, UnitOfWork uow)\n   { ../* All the code in the AddCustomerToGroupAsync inside the unitOfWork */. }	0
1829068	1829044	How do I Change the Sheet Name from C# on an Excel Spreadsheet	Microsoft.Office.Interop.Excel.Worksheet worksheet = (Worksheet)xlApp.Worksheets["Sheet1"];\n  worksheet.Name = ?NewTabName?;	0
2280843	2280744	WPF How can I apply global configuration file for solution with couple projetcs	AssemblyInfo.cs	0
10280257	10279723	C# Find duplicate Values in Datagridview	public bool allUniqueRows()\n    {\n        var distinctCount =  from r in ParetoGrid.Rows\nselect r.whateverElement.Distinct().Count();\n     if(distinctCount == ParetoGrid.Rows.Count())\n    {\n    return true;\n    }\n    else\n    {\n    return false;\n    }\n    }	0
2010858	2010826	Is it possible to click a Button without ever losing focus on a TextBox?	Focusable="False"	0
13316756	13316723	selecting item from listview in C#	private void listView1_SelectedIndexChanged(object sender, EventArgs e)\n {\n   if(listView1.SelectedItems.Count > 0)\n     textBox1.Text = people[listView1.SelectedItems[0].Index].Name;\n }	0
27741086	27740792	C# Mono Linux - Grab contents of global clipboard -	Gtk.Clipboard clipboard = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false));\nvar text = clipboard.WaitForText();	0
11978832	11978797	How to avoid OutOfMemoryException while loading large chunks of data from a database?	_dc.ObjectTrackingEnabled = false;	0
11479761	11479690	Algorithm to populate Dictionary<string,Dictionary<string,string>> type object	if (!roomfurnitures.ContainsKey(roomtype))\n    roomfurnitures[roomtype] = new Dictionary<string, string>(); // the first time we've seen this\n\n// get the dictionary for the specific room\nvar room = roomfurnitures[roomtype];\n\n// now we can add the furniture to the room\nroom[item] = description;	0
32023372	31964787	How to define DDD Aggregate root for hierarchical data structure?	public void RegisterTime(TimeSpan time)\n{\n    TimeSpent += time;\n    // maybe more stuff here\n    Parent.RegisterTime(time)\n}	0
2722652	2722598	compare two ip with C#	IPAddress ip1 = IPAddress.Parse("123.123.123.123");\nIPAddress ip2 = IPAddress.Parse("124.124.124.124");\n\nif(ip1.Equals(ip2))\n{\n    //...\n}	0
12859500	12856912	Reading from a text file resource which is compiled into a .NET assembly	class Program\n{\n    static void Main(string[] args)\n    {\n        Stream stream = typeof(Program).Assembly.GetManifestResourceStream("TheNameOfMyProject.TheNameOfSubFolder.file.txt");\n        StreamReader sr = new StreamReader(stream);\n        var content = sr.ReadToEnd();\n        Console.WriteLine(content);\n        Console.ReadLine();\n    }\n}	0
6009286	6009171	Reading XMLDocument Into An Object	public object LoadFromXmlDocument(string xmlDocument, XmlSerializer serializer)\n{\n    if (StringUtil.IsEmpty(xmlDocument))\n       throw new ArgumentNullException("xmlDocument");\n    else if (serializer == null)\n       throw new ArgumentNullException("serializer");\n\n//Initializing instance for textreader\nTextReader reader = new StringReader(xmlDocument);\n\n//Serializing a textreader content\nobject obj = serializer.Deserialize(reader);\nreader.Close();\nreader = null;\nreturn obj;\n}	0
16134878	16132959	Base64 from e.ChosenPhoto apparently corrupted	Uri.EscapeDataString	0
23074295	23073347	Does an enum ALWAYS need to be cast in c# if used as a method parameter?	int x = (int)Days.Sun;	0
10895555	10895330	How do I make DRY code using generated WCF proxies from overlapping WSDLs	class ProxyOperations\n{\n    addOperation(string opName, string namespace, OperationBase op);\n    // You'll have to figure out what to do with the operation parameters,\n    // maybe wrap them in a parameter context\n    void doOperation(string opName, string namespace) {\n        // lookup operation object and execute it\n    }\n    typedef map<string, OperationsBase> OperMap;\n    typedef map<string, operMap> NamespaceMap;\n    NamespaceMap namespaceOperationMap_;\n};\n\n{\n    ProxyOperations po;\n\n    // Populate it\n    po.addOperation("Op1", "ns1", oper1ObjectNs1);\n    po.addOperation("Op1", "ns2", oper1ObjectNs2);\n    po.addOperation("Op1", "ns3", oper1ObjectNs3);\n\n    po.addOperation("Op2", "ns1", oper2ObjectNs1);\n    po.addOperation("Op2", "ns2", oper2ObjectNs2);\n\n    // now use it\n    po.doOperation("Op1", "ns2");\n}	0
1238546	1238178	how to color listitem in list	for (int count = 0; count < 10; count++)\n    {\n        ListItem li = new ListItem();\n        li.Text = count.ToString();\n        li.Value = count.ToString();\n        if (count == 4 || count == 8)\n        {\n            li.Attributes.Add("style", "Color: Red");\n        }\n        lst.Items.Add(li);\n    }	0
6002447	6002439	Clean way to return array indices matching a condition using LINQ	myarray\n    .Select((p, i) => new { Item = p, Index = i })\n    .Where(p => SomeCondition(p.Item))\n    .Select(p => p.Index);	0
19612596	19612377	Get User IP in a BaseController?	public class IpCheckFilter : ActionFilterAttribute\n    {\n        public override void OnActionExecuting(ActionExecutingContext filterContext) {\n        if (filterContext.HttpContext.Request.ServerVariables["REMOTE_HOST"] != "ValidIP")\n        {\n            filterContext.Result = new RedirectToRouteResult(\n                new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" } });\n        }\n    }\n\n    [IpCheckFilter]\n    public class HomeController : AdminBaseController\n    {\n         public HomeController() : base()\n         {            \n         }\n    }	0
16268757	16268696	Parsing a json formatted string into json and creating a jsonresult type object with c#	string result = @"[{ ""TagGroupName"": ""group1"", ""Tags"": [{""TagName"":""G1tag1""},{""TagName"":""G1tag2""},{""TagName"":""G1tag3""}]}, { ""TagGroupName"": ""group2"", ""Tags"": [{""TagName"":""G2tag1""},{""TagName"":""G2tag2""}]}]";\n\nreturn new ContentResult { Content = result, ContentType = "application/json" };	0
8582135	8581592	Create ToolTip for Custom UserControl	public string TextBoxHint\n    {\n        get \n        { \n            return toolTip1.GetToolTip(textBox1); \n        }\n        set\n        {\n            toolTip1.SetToolTip(textBox1, value);                \n        }\n    }	0
20256791	20256402	Get Attention Of Chatbot	private bool _isActive = false;\n\npublic void YourMethod()\n{\n    if (!_isActive)\n    {\n        if (KeyCode == Keys.Enter && InputTextbox.Text.Contains("penny"))\n        {\n            _isActive = true;\n        }\n    }\n    else\n    {\n        if (e.KeyCode == Keys.Enter && InputputTextbox.Text.Contains("hello"))\n        {\n            OutputTextbox.Text = "hi there";\n        }\n\n        // other if's\n    }\n}	0
25263539	25263469	Dynamically select which table to insert data into with entity framework	var set = db.Set(myObject.GetType());\nset.Add(myObject);\ndb.SaveChanges();	0
6160993	6160775	Model binding for many to many relationship	DriversLicence\n----------------\nLicenceId\nDriverId	0
7164134	7163206	Finding duplicate elements in Excel Column and displaying its cell number	var myDictionary = new Dictionary<string,int>();\nstring col="C";\nfor(int row = 1; row<numberOfRows; ++row)\n{\n     string elemValue = myWorkSheet.Range[col + row].Text;\n     if(myDictionary.ContainsKey(elemValue))\n     {\n          Console.WriteLine(col + myDictionary[elemValue] + " = " + col + row);\n     }\n     else\n     {\n          myDictionary[elemValue]=row;\n     }\n}	0
22186484	22181973	How to assign names to new objects at runtime?	public class Rtb\n{\n    private static int _NextID = -1;\n    public static int NextID\n    {\n        get\n        {\n            _NextID++;\n            return _NextID;\n        }\n    }        \n    public RichTextBox newRTB;\n\n    public Rtb()\n    {\n        newRTB = new RichTextBox();\n        newRTB.IsReadOnly = true;\n        newRTB.MouseDoubleClick += new MouseButtonEventHandler(newRTB_MouseDoubleClick);\n        newRTB.Name = "Box" + NextID.ToString();\n    }\n}	0
30007178	30007138	Unit Test: Assert range of a list with greater or lesser than	Assert.IsTrue(myCollection.Any(a => a > min));	0
8924909	8924869	How to convert ArrayList into string array(string[]) in c#	string[] myArray = (string[])myarrayList.ToArray(typeof(string));	0
12359673	12333826	Trigger dialog buttons on IWebMatrixHost ShowDialog method	// Bound to TextBlock, part of a ListBox on a UserControl\n    private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)\n    {\n        if (e.ClickCount == 2)\n        {\n            CloseDialog(this, EventArgs.Empty);\n        }\n    }	0
31594236	31593476	WPF Magic Strings	public class MyParts {\n    public static const string MyFoo = "PART_Foo";\n}\n\n[TemplatePart(Name = MyParts.MyFoo)]\n\n<Button x:Name="{x:Static parts:MyParts.MyFoo}" ... >	0
25939652	25932713	Passing object from dll to exe	var app = new App();\napp.InitializeComponent();\napp.Run();\nWindow1.Repository = _repository; //I know static field is bad, but this is only example	0
13013268	12855681	C# Remote Performance Counters with multiple Counters	creates a byte array	0
7933459	7933387	string expression for html tag value	protected void Page_Load(object sender, EventArgs e)\n{\n    string t = "X"; // calculate t here\n    myDataSource.SelectCommand = "SELECT [aField], [bField] FROM Suggestions WHERE stype = " + t;\n    // other actions\n}	0
5383519	5383498	shuffle (rearrange randomly) a List<string>	List<Foo> source = ...\nvar rnd = new Random();\nvar result = source.OrderBy(item => rnd.Next());	0
30898323	30898230	Logging DateTime in SQL Table When Users Session Ends	protected void Session_End(object sender, EventArgs e)\n    {\n\n    }	0
26234441	26220071	Castle windsor registering open generics	Classes\n    .FromThisAssembly()\n    .Where(type => \n        type.Name.EndsWith("Wrapper") || \n        type.Name.EndsWith("Provider") ||\n        type.Name.EndsWith("Factory") ||\n        type.Name.EndsWith("Reader") ||\n        type.Name.EndsWith("Writer") ||\n        type.Name.EndsWith("Destroyer") ||\n        type.Name.EndsWith("Helper")\n    )\n    .WithService\n    .DefaultInterfaces()\n    .Configure(c => c.LifeStyle.Is(scope))	0
19776610	19775724	Setting Windows file security	[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] \nprivate static extern SafeFileHandle CreateFile(\nstring name, FileAccess access, FileShare share,\nIntPtr security,\nFileMode mode, FileAttributes flags,\nIntPtr template);\n\n    public static void Main()\n    {\n        // Opens the ":Zone.Identifier" alternate data stream that blocks the file\n        using (SafeFileHandle handle = CreateFile(@"\\?\C:\Temp\a.txt:Zone.Identifier", FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.OpenOrCreate, FileAttributes.Normal, IntPtr.Zero))\n        {\n            // Here add test of CreateFile return code\n            // Then :\n\n            using (StreamWriter writer = new StreamWriter(new FileStream(handle, FileAccess.ReadWrite), Encoding.ASCII))\n            {\n                writer.WriteLine("[ZoneTransfer]");\n                writer.WriteLine("ZoneId=3");\n            }\n        }	0
10390565	10390428	Listview pictures with text and indexes	// Class-level variable\nvar _imageDictionary = new Dictionary<string,Image>();\n\n\n// Logic in method\nImage image;\nif(_imageDictionary.ContainsKey(textBox1.Text))\n image = _imageDictionary[textBox1.Text];\nelse {\n   image = // code to retrieve image from web\n   _imageDictionary[textBox1.Text] = image;\n}\n\n// ... add it to your image list	0
5044116	5044056	How can I use this stack trace to tell what is causing my controller's action to break?	Html.Action	0
3888750	3888683	How to filter a sub list which is part of another list in C#	List<MainClass> mainList = ...\nforeach(MainClass main in mainList)\n{\n    ICollectionView view = CollectionViewSource.GetDefaultView(main.ExtraInfo);\n    view.Filter = ExtraInfoFilter;\n}\n\nbool ExtraInfoFilter(object obj)\n{\n    ExtraInfo item = (ExtraInfo)obj;\n\n    return item.City == "New York";\n}	0
10393466	10374388	Deserialize XML into C# Windows Form	public void SomeMethod()\n{\n    Values v = LoadValues();\n    this.task1_name.Text = v.task1_name;\n    this.task1_desc.Text = v.task1_desc;\n    this.task1_date.Value = v.task1_date;\n    this.task1_time.Value = v.task1_time;\n}\n\npublic Values LoadValues()\n{\n    XmlSerializer serializer = new XmlSerializer(typeof(Values));\n    using (TextReader textReader = new StreamReader(@"E:\TheFile.xml"))\n    {\n        return (Values)serializer.Deserialize(textReader);\n    }\n}	0
32753536	32741104	Convert dataRowview to dataTable in c#	DataTable dt = rowBeingEdited.DataView.ToTable();	0
25566606	25566487	asp MVC - Add a model representing user to a Partial displayed via layout	Html.RenderAction("ActionName", "ControllerName")	0
23789125	23788787	C# MVC: Dynamically Add Object To ViewModel From View	[HttpPost] \n    [ValidateInput(false)]\n    public virtual ActionResult EditBrandItems(List < BrandViewModel > model, FormCollection formValues)\n    {\n        //DO SOMETHING WITH DATA\n        return View(model);\n    }	0
24474686	24407462	How to detect new window in watIn	using (IE browser = new IE("https://login.com"))\n{\ntry\n{\n    if (linkExist) browser.Image(Find.ById("inputSend")).ClickNoWait();            \n        linkExist = false;\n\n        IE poppedUpBrowser = IE.AttachTo<IE>(Find.ByUrl(url => url.Contains("https://login.123.com")));\n}\ncatch (Exception ex)\n{\n    successful = false;\n}	0
13410375	13410263	how to compare two listbox items and add common items to another combo box?	cmbJoinColumn.Items.Clear() //If you want to remove previous Items.\nfor(int intCount = 0; intCount < lbFirstTableColumns.Items.Count;intCount++)\n  {\n       for(int intSubCount = 0;intSubCount < lbSecondTableColumns.Items.Count; intSubCount++)\n       {\n            if (lbSecondTableColumns.Items[intCount].ToString() == lbSecondTableColumns.Items[intSubCount].ToString())\n             {\n                  cmbJoinColumn.Items.Add(lbSecondTableColumns.Items[intCount].ToString());\n             }\n       }\n }	0
20219868	20219354	How merge two sequences into one?	var customerQuery = context.CustomerTable.Select( ct => \n    new { \n        ct.ID, \n        ct.CustomerTitle, \n        // use nav property to get customer payments\n        CustomerPayments = ct.CustomerPayments.Select( cp => \n            new { \n                Range = cp.Range, \n                Values = cp.Values } ) } );\n\nreturn customerQuery.ToArray()\n    .Select( cq => \n        {\n            var retVal = new SCustomerInfo( CreateCustomerTable(), cq.ID, cq.CustomerTitle ); \n\n            foreach( var customerPayment in cq.CustomerPayments )\n            {\n                var dtRow = cq.PaymentTable.NewRow();\n\n                dtRow.ItemArray = new object[] { customerPayment.Range, customerPayment.Values };\n\n                retVal.PaymentTable.Rows.Add( dtRow );\n            }\n\n            return retVal;\n        } );	0
23378940	23378874	Date format when importing from MySQL Date into the Textbox C#.NET	tbDate.Text = ((DateTime)dt.Rows[0][14]).ToString("dd.M.yyyy");	0
10389537	10389479	How to check if users visiting the site are on root page or any other page?	if(Request.Url.PathAndQuery == "/") // root;	0
28231297	28216084	Thinktecture ResourcAuthorization, no AuthorizationManager set	app.UseResourceAuthorization(new MyAuthorizationManager());	0
3035219	3035172	how to add values in array	private void getrowvalues()\n{\n    string combinedvalues;\n    List<string> combinedValuesList = new List<string>();\n\n    foreach (GridViewRow row in gvOrderProducts.Rows)\n    {\n        string prodname = ((Label)row.FindControl("lblProductName")).Text;\n        string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text;\n\n        combinedvalues = prodname + "|" + txtvalues;\n        combinedValuesList.Add(combinedvalues);\n    }\n    // use combinedValuesList or combinedValuesList.ToArray()\n}	0
23695146	23695123	Equivalent of Timer in C# in Java?	TimerTask task = new RunMeTask();\nTimer timer = new Timer();\ntimer.schedule(task, 1000, 60000);	0
23151087	23148939	Export datagrid to a excel window which is opening c#	Microsoft.Office.Interop.Excel.Application oExcel	0
4983672	4983625	login asp.net redirect with parameters	//I assume a bool variable UserIsValid which you set after validating the user\nif (UserIsValid)\n{\n    //If user was redirected back to login page then go back to requested page\n    if (Request.QueryString["ReturnUrl"] != null)\n    {\n        FormsAuthentication.RedirectFromLoginPage("User_name", false);\n    }\n    else\n    {\n        //Set an Auth cookie\n        FormsAuthentication.SetAuthCookie("User_name", false);\n        //And then redirect to main page with you parameters if any\n        Response.Redirect("mainPage.aspx?prameter1={0}&parameter2={1}", param1, param2);\n    }\n}    \nelse\n{\n    //User was not valid, do processing\n}	0
4401412	4399751	Get internal item no from ListCollectionView	public override object GetItemAt(int index)\n{\n    object rc = base.GetItemAt(index);\n    // do something\n\n    int internalIndex = -1;\n    IList sourceCollection = SourceCollection as IList;\n    if (sourceCollection != null)\n    {\n        internalIndex = sourceCollection.IndexOf(rc);\n    }\n    else\n    {\n        // See\n        // http://stackoverflow.com/questions/2718139\n    }\n    return rc;\n}	0
3821108	3821050	Include a batch file in a batch file	cd %~dp0	0
15599563	15599550	Check if List<List<string>> contains a string	if (lists.Any(sublist => sublist.Contains(str)))	0
26658735	26658668	method only adding to list if declared inside method	this._machineName = new List<string();	0
3999757	3999743	C# explicit declare member interface	public class ComentariosPerfil : BaseComentarios, IPerfil \n{ \n    int IPerfil.IDFilial \n    { \n        get; \n        set; \n    }	0
13938437	13936689	How to redirect percentage of users to a beta test web site?	protected void Application_PreRequestHandlerExecute(object sender, EventArgs\ne)\n{\n\nif(Request.Cookies["BetaResult"] == null)\n{\n   var  cookie = new HttpCookie("BetaResult");\n   cookie.Expires = DateTime.Now.AddDays(1d);\n   if(whatever logic to redirect to beta)\n   {\n       cookie["BetaResult"] = "Beta";\n       Response.Cookies.Add(cookie);\n       Response.Redirect("your beta site");\n   }\n   else\n   {\n       cookie["BetaResult"] = "Main";\n       Response.Cookies.Add(cookie);\n   }\n\n}\nelse\n{\n  //if cookie value is beta, redirect to beta site, they 'are a chosen one'\n}  \n\n}	0
7147826	6871602	Extending Checked event in derived TreeView control - how to temporarily remove event handlers?	RadTreeViewCheckEventArgs.IsUserInitiated	0
19171262	19171213	Regex match text on multiple lines	Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);	0
6964671	6962423	Using reactive to resubscribe each time another event occurs	obj\n    .CompletedObservable\n    .StartWith(/* value of suitable type for CompletedObservable */)\n    .Select(x => obj.Observable1.Take(1))\n    .Switch()\n    .Subscribe(x => DoThis());	0
10588338	10588224	How do I call a second project from the startup one in visual studio?	\MySolution\n    \ProjectOne\n        \bin\n            ProjectOne.exe\n    \ProjectTwo\n        \bin\n            ProjectTwo.exe	0
8756390	8756202	Java ZIP File copy and paste from one zip to another	void substitute(ZipInputStream zis, ZipOutputStream zos) {\n  for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {\n    if (ze.getName() is what you want to copy) {\n      zos.putNextEntry(ze)\n      Array[Byte] buffer = new Array[Byte](1024)\n      for (int read = zis.read(buffer); read != -1; read = zis.read(buffer)) {\n        zos.write(buffer, 0, read)\n      }\n      zos.closeEntry\n    }\n  }\n  zos.close()\n  zis.close()\n}	0
19243677	19243222	How to deserialize JSON in C#	class Employer\n{\n    [JsonProperty("nome")]\n    public string Nome { get; set; }\n\n    [JsonProperty("id")]\n    public string Id { get; set; }\n\n    [JsonProperty("setor")]\n    public string Setor { get; set; }\n}\n\nclass Employers : List<Employer>\n{\n}\n\nEmployers employers = JObject.Parse(json)["result"]["employers"].ToObject<Employers>();	0
28449277	10990612	Folder browser dialog like open file dialog	Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();\nMicrosoft.Office.Core.FileDialog fileDialog = app.get_FileDialog(Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFolderPicker);\nfileDialog.InitialFileName = "c:\\Temp\\"; //something you want\nint nres = fileDialog.Show();\nif (nres == -1) //ok\n{\n    Microsoft.Office.Core.FileDialogSelectedItems selectedItems = fileDialog.SelectedItems;\n\n    string[] selectedFolders = selectedItems.Cast<string>().ToArray();\n\n    if (selectedFolders.Length > 0)\n    {\n        string selectedFolder = selectedFolders[0];\n    }\n}	0
9380831	9380799	In C#, how can a derived manager class return instances of a derived class without re-implementing everything?	public class ThingDB<T> where T: Thing\n{\n    public List<T> GetByColor(string color)\n    {\n        var things = new List<T>();\n        // Get things from the database's Thing table\n        return things;\n    }\n\n    public List<T> GetByWeight(int weight)\n    {\n        var things = new List<T>();\n        // Get things from the database's Thing table\n        return things;\n    }\n}	0
29314557	29314515	C# Json.NET - json to c# object	if(ds != null)\n{\n   if(ds.count > 0 )\n    { \n      if(ds.Torrents.count > 0)\n       {\n      MessageBox.Show(ds.Torrents[0].Name);\n       }\n   }\n}	0
1434445	1434402	What's wrong with output parameters?	output = someMethod(input)	0
575071	575063	User Controls in Repeater	public string Id{\n    get\n    {\n        return this.ViewState["Value"] == null ?\n            0 :\n            (int)this.ViewState["Value"];\n    }\n    set { this.ViewState["Value"] = value; }\n}	0
12219621	12219524	Custom authorize attribute only works on localhost	filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;	0
742056	742015	How Do I Edit Database Records In A DataGridView Using LINQ to SQL?	private void DataGridView1_UserDeletingRow(object sender,\n                                           DataGridViewRowCancelEventArgs e)\n{\n    DataGridViewRow row = sender as DataGridViewRow;\n\n    int id = ...get id from row column...\n\n    using (var dc = new SiteDataDataContext())\n    {\n         var site = dc.Sites.Where( s => s.ID == id ).SingleOrDefault();\n\n         if (site != null)\n         {\n             try\n             {\n                dc.Sites.DeleteOnSubmit( site );\n                dc.SubmitChanges();\n                dataGridView1.Bind();\n             }\n             catch (SqlException)\n             {\n                e.Cancel = true;\n             }\n         }\n     }\n}	0
4507807	4431077	c# TcpClient can not read valid response from successfully connected telnet server / device	byte[] sendBuffer = new ASCIIEncoding().GetBytes(str + strNewLine);\n            tcpClient.GetStream().Write(sendBuffer, 0, sendBuffer.Length);	0
33800778	33800584	Is it possible to assign set the default value of a class property based on another property?	public class HeaderTypeEnq<T> : HeaderType<T>\n{\n    public string Mandatory { get; set; }\n    public string CharacterType { get; set; }\n    public string FixedLength { get; set; }\n    public int Position { get; set; }\n    public int MaxLength { get; set; }\n    public int CharToRead\n    {\n        get\n        {\n            if (string.IsNullOrEmpty(Value))\n            {\n                return 0;\n            }\n            return Value.Length;\n        }\n    }\n}	0
17410540	17410492	Changing order that private readonly properties are evaluated	public class MyClass {\n    private static readonly MyObject obj;\n    private static readonly List<MyObject> listObject;\n\n    static MyClass()\n    {\n        listObject = new List<MyObject> { new MyObject() };\n        obj = new MyObject { parent = listObject[0] };\n    }\n}	0
27057821	21384973	how to use $currentdate in mongodb using C# drivers	var query = Query.EQ("_id", 1);\nvar update = Update\n   .Set("field_timestamp_local", DateTime.Now)\n   .CurrentDate("field_timestamp_mongo");\ncollection.Update(query, update);	0
2664959	2664951	Print expression as is without evaluating it	string Xmin = String.Format("({0} - 1)*{1} + ({0} - 1)*{2}", I, a, g);	0
18347807	18346875	How to Keep Ace from Looking for Themes and Modes in Current Directory?	ace.config.set("basePath", "/Scripts/FullPathToMy/AceEditorDirectory");	0
2648981	2326590	Creating a KeyDown Event Handler for the Label Control	protected override void OnMouseDown(MouseEventArgs e)\n{\n  base.OnMouseDown(e);\n  if (this.CanSelect) this.Select();\n}	0
21571218	21571034	Timeout expired in windows phone 7 application development	SqlConnection.Dispose	0
23824214	23823860	finding peak intervals from column data	public List<Tuple<int, int>> getPeaks(int[] values)\n{\n    List<Tuple<int, int>> results = new List<Tuple<int, int>>();\n\n    List<int> curInterval = new List<int>();\n\n    bool decreasing = false;\n    for (int i = 0; i < values.Length; i++)\n    {\n        if (curInterval.Count > 0)\n        {\n            if (values[i] < curInterval.Last() && !decreasing)\n            {\n                results.Add(new Tuple<int, int>(i - 1, curInterval.Last()));\n                curInterval.Clear();\n                decreasing = true;\n            }\n            else if (values[i] >= curInterval.Last() && decreasing)\n            {\n                decreasing = false;\n            }\n        }\n        curInterval.Add(values[i]);\n    }\n    return results;\n}	0
14867916	14861492	get the clicked item from a IsItemClickEnabled ListView in C# and WinRT	private void lv_ItemClick_1(object sender, ItemClickEventArgs e)\n{\n    var item = e.ClickedItem as String;\n}	0
27446954	27446297	On property change kickoff long running task to populate another property	private ProductFamily _selectedProduct;\npublic ProductFamily SelectedProduct\n{\n    get { return _selectedProduct; }\n    set\n    {\n        this.SetPropertyChanged(ref _selectedProduct, value)\n        Limits.Clear(); // or Limits = new ...\n        Task.Run(() => LongTask());\n    }\n}\n\nprivate void LongTask()\n{\n    var list = new List<BindedLimit>();\n    ...\n    App.Current.Dispatcher.Invoke(() => Limits = new ObservableCollection<BindedItems>(list));\n}	0
16027996	16026384	How to get the sum of a numeric list from SharePoint?	double total = 0;\nforeach(item in list){\n  if(item["field"] == null)\n     continue;\n\n  total += item["field"];\n  str.AppendLine("<td bgcolor='#FFFFFF';align='right';> " + Convert.ToDecimal(item["field"]).ToString("N0") + "</td>");\n}\nstr.AppendLine(" <tr style='color:#ffffff; font-weight:bold'><td bgcolor='#0096D6'>Forecast USD:" + total.toString() + "</td></tr>");	0
29674285	29674176	How to split a string into individual letters	var x = "1234567";\nforeach(var digit in x)\n{\n    <li>@digit</li>\n}	0
25390103	25389524	Selecting two other datagridview rows after selecting first, related on 'rptId' field	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        var rptIdValue1 = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;\n        foreach (DataGridViewRow r in dataGridView2.Rows)\n        {\n            if ((int)r.Cells[0].Value != rptIdValue1) continue;\n\n            dataGridView2.Rows[r.Index].Selected = true;\n            break;\n        }\n    }	0
27737866	27737799	Trying to get a StatusBar in app that could be accessible from various pages	public Page1(ISBView sb) : this() \n    {\n        this.statusBar = sb;\n        sb.UpdateMessage("now on page1");\n    }	0
23472849	23387121	Centering specific column in RadListView (Telerik, Winforms)	private void radListView1_CellFormatting(object sender, ListViewCellFormattingEventArgs e)\n   {\n    if ((e.CellElement).Data.HeaderText == "ID")\n    {\n        if ((e.CellElement is DetailListViewDataCellElement))\n        {\n            e.CellElement.TextAlignment = ContentAlignment.TopRight;\n        }\n    }\n    if ((e.CellElement).Data.HeaderText == "Name")\n    {\n        if ((e.CellElement is DetailListViewDataCellElement))\n        {\n            e.CellElement.TextAlignment = ContentAlignment.MiddleCenter;\n        }\n\n    //end so on\n    }\n}	0
26961948	25523013	Decryption of clob data (in string form) to actual string in C#	using (ODC.OracleDataReader rdr = cmd.ExecuteReader())\n{\n   if (rdr.Read())\n   {\n       var clob = rdr.GetOracleClob(0);\n       // Can not simply use clob.Value - throws ORA-03113\n       // Need to read input in chunks\n       long length = clob.Length;\n       List<byte> bytes = new List<byte>();\n       int offset = 0;\n       while (offset < length)\n       {\n          int readLength = (int)Math.Min(1024, length - offset);\n          byte[] tmp = new byte[readLength];\n          int readBytes = clob.Read(tmp, 0, readLength);\n          offset += readLength;\n          bytes.AddRange(tmp);\n       }\n    string xml = System.Text.Encoding.Unicode.GetString(bytes.ToArray()); \n    return DecodeXmlString(xml);\n}\nelse\n    return null;\n}	0
8007790	8007399	ldap query to find all computers in a security groups	(&(objectClass=computer)(primaryGroupID=515))	0
24280896	24280277	Skip the element of the loop	for (int i = 0; i < length; i++)\n{\n    try\n    {\n        string img = dataGridView1.Rows[i].Cells[1].Value.ToString();\n        using (WebClient client = new WebClient())\n        {\n            client.DownloadFile(img, localFilename);\n        }\n    }\n    catch (Exception ex)\n    {\n        Debug.WriteLine(ex.Message);\n    } \n}	0
21587467	21587085	LINQ to XML aggregates and group by	private decimal GetTaxRate(XElement code)\n{\n    XAttribute rateAttribute = code.Attribute("taxRate");\n    return (string) rateAttribute == "" ? 0m : (decimal) rateAttribute;\n}\n\n...\n\nvar query = from code in TaxRates.Descendants("Code")\n            where (int?) code.Attribute("taxyear") == TaxYear\n               && code.Attribute("taxRate") != null\n            group code by (string) code.Attribute("taxunitid") into g\n            select new {\n                ID = g.Key,\n                rate = g.Sum(code => GetTaxRate(code))\n            };\nquery.Dump();	0
19328938	19328354	How Can I Programmatically Override the Auto_Increment Value When Inserting Into a DB	SET IDENTITY_INSERT dbo.sometable ON ;\n\nINSERT INTO dbo.sometable (id,.......) VALUES (456,.......) ;\nINSERT INTO dbo.sometable (id,.......) VALUES (276,.......) ;\nINSERT INTO dbo.sometable (id,.......) VALUES (387,.......) ;\n\nSET IDENTITY_INSERT dbo.sometable OFF ;	0
15939174	15938951	How to delete a registrykey when selecting on listbox?	private void DisableBtn_Click(object sender, RoutedEventArgs e)\n{\n    if (startupinfo.SelectedItem != null)\n    {\n        string s = startupinfo.SelectedItem.ToString();\n\n        if (startupinfoDict.ContainsKey(s))\n        {\n            try\n            {\n                File.Delete(startupinfoDict[s]);\n            }\n            catch\n            {\n                //errors are here\n            }\n        }\n\n        string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";\n        using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyName, true))\n        {\n            if (key != null)\n            {\n                try\n                {\n                    key.DeleteValue(startupinfo.SelectedItem.ToString());\n                }\n                catch\n                {\n                    //errors are here\n                }\n            }\n        }\n    }\n}	0
25610025	25609917	Multi-Threading in c# issue with returning value	var thread1 = new Thread(() => { val1 = Process(left, right - 1, array, level - 1); });\nvar thread2 = new Thread(() => { val2 = Process(left - 1, right, array, level - 1); });\nthread1.Start();\nthread2.Start();	0
32231797	32231655	Use variable value as x:Name	public Button buttonName;\n\nprivate void method ()\n{\n   buttonName = this.FindName("myBtn") as Button;\n   buttonName.Background = new SolidColorBrush(Color.FromRgb(255, 0, 255));\n}	0
5020542	5019205	Umbraco 4.6+ - How to get all nodes by doctype in C#?	private void DoSomethingWithAllNodesByType(int NodeId, string typeName)\n{\n    var node = new Node(nodeId);\n    foreach (Node childNode in node.Children)\n    {\n        var child = childNode;\n        if (child.NodeTypeAlias == typeName)\n        {\n            //Do something\n        }\n\n        if (child.Children.Count > 0)\n            GetAllNodesByType(child, typeName);\n    }\n}	0
33180559	33180443	Create multiple ListBoxes - Windows applications forms	for (int i = 0; i < 10; i++)\n{\n    // Create the listbox\n    ListBox lb = new ListBox();\n\n    // Give it a unique name\n    lb.Name = "ListBox" + i.ToString();\n\n    // Try to define a position on the form where the listbox will be displayed\n    lb.Location = new Point(i * 50,0);\n\n    // Try to define a size for the listbox\n    lb.Size = new Size(50, 100);\n\n    // Add it to the Form controls collection\n    // this is the reference to your form where code is executing\n    this.Controls.Add(lb);\n}\n\n// Arrange a size of your form to be sure your listboxes are visible\nthis.Size = new Size(600, 200);	0
29947546	29947419	How to get distinct keys when a Dictionary's key is a string array	var result=data.Keys.Select(k=>k[0]).Distinct();	0
12513640	12513621	Linq query, how to check for a null value and use the value 0 in place of a null?	(order.Promo.PercentOff ?? 0)	0
16397003	16396936	How to decode encoded URL in google chrome?	Console.WriteLine(System.Web.HttpUtility.UrlDecode("http://www.google.com/search?q=??????"));\nConsole.WriteLine(System.Web.HttpUtility.UrlEncode("http://www.google.com/search?q=%D9%85%D9%82%D8%A7%D9%84%D8%A7%D8%AA"));	0
21170593	21170371	hw to hide query string in url	window.open	0
606646	606595	is it legal to recreate a rooted reference to 'this' in a .net destructor?	GC.ReRegisterForFinalize	0
17711093	17709638	C# mvc get active menu item with menu items from partial controller	string currentController = htmlHelper.ViewContext.ParentActionViewContext.RouteData.GetRequiredString("controller");	0
33933078	33920914	Change text of label in PDF	fields.GenerateAppearances = true;	0
6468987	5910581	Storing Microsoft Word 97 documents in SQL Server column	Const adOpenKeyset                  = 1\nConst adLockOptimistic              = 3\nConst adTypeBinary                  = 1\nConst adSaveCreateOverWrite         = 2\n\nstrSQLServer = "YOURSERVER"\nstrSQLDatabase = "YOURDB"\nstrRecordID = "123"\nstrTempFileName = "c:\output.doc"\n\nSet objConn = CreateObject("ADODB.Connection")\nSet objRS = CreateObject("ADODB.RecordSet")\nSet objStream = CreateObject("ADODB.Stream")\n\nobjConn.Open "Provider=SQLOLEDB;data Source=" & strSQLServer & ";Initial Catalog=" & strSQLDatabase & "; Trusted_Connection=yes;"\nobjRS.Open "Select * from AllDocStreams WHERE ID='" & strRecordID & "'", objConn, adOpenKeyset, adLockOptimistic\n\nobjStream.Type = adTypeBinary\nobjStream.Open\nobjStream.Write objRS.Fields("Content").Value\nobjStream.SaveToFile strTempFileName, adSaveCreateOverWrite\n\nobjRS.Close\nobjConn.Close	0
19900689	19654852	Display data using ListView in ASP.NET	protected void Page_Load(object sender, EventArgs e)\n        {\n            ListView1.DataSource = this.GetData();\n            ListView1.DataBind();\n        }\n\n        private DataSet GetData()\n        {\n            string conString = ConfigurationManager.ConnectionStrings["Connectionstr"].ConnectionString;\n            string query = "SELECT * FROM Registration";\n            SqlCommand cmd = new SqlCommand(query);\n            using (SqlConnection con = new SqlConnection(conString))\n            {\n                using (SqlDataAdapter sda = new SqlDataAdapter())\n                {\n                    cmd.Connection = con;\n                    sda.SelectCommand = cmd;\n                    using (DataSet ds = new DataSet())\n                    {\n                        sda.Fill(ds);\n                        return ds;\n                    }\n                }\n            }\n        }	0
5254016	5251311	How to add elements or nodes, to existing XML, given an input string to compare with - using a LINQ query	listOfChild.Root.Descendants( "set" ).FirstOrDefault().Add(\n    listOfChild.Descendants( "Val" ).Where( v => v.Value.ToLower() == ipString.ToLower() ).\n                                     Select( v => ( XElement ) null ).\n                                     DefaultIfEmpty( new XElement("Person",\n                                                     new XElement( "PID", -1 ),\n                                                     new XElement( "Val", ipString ) ) ).\n                                     First() );	0
8441047	8434379	Start new process, without being a child of the spawning process	Module Module1\n\n    Sub Main()\n        Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs\n        If CommandLineArgs.Count = 1 Then\n            Try\n                Dim path As String = FromBase64(CommandLineArgs(0))\n                Diagnostics.Process.Start(path)\n            Catch\n            End Try\n            End\n        End If\n    End Sub\n\n    Function FromBase64(ByVal base64 As String) As String\n        Dim b As Byte() = Convert.FromBase64String(base64)\n        Return System.Text.Encoding.UTF8.GetString(b)\n    End Function\n\nEnd Module	0
16857828	16856846	Deserialize a JSON array in C#	var records = new ser.Deserialize<List<Record>>(jsonData);\n\npublic class Person\n{\n    public string Name;\n    public int Age;\n    public string Location;\n}\npublic class Record\n{\n    public Person record;\n}	0
7075749	6378333	How do I make changing row style in a DataGridView control faster (C#)?	dataGridView.Row[index].DefaultCellStyle.BackColor = Color.Yellow	0
9345425	9345351	Accessing type of interface implementer in interface methods	public interface IMy\n{\n    ImplicitImplementerType SomeProperty\n    {\n        get;\n    }\n}	0
26983491	26983037	Delete Post of Wall Facebook using SDK C#	dynamic result = client.Post("me/feed", parameters);\n\n client.Delete(result.id);	0
3605843	1062914	Entity SQL compare datetime without milliseconds	foos.SingleOrDefault(f => f.EntryDate.Year == bar.EntryDate.Year &&\n                          f.EntryDate.Month == bar.EntryDate.Month &&\n                          f.EntryDate.Day == bar.EntryDate.Day &&\n                          f.EntryDate.Hour == bar.EntryDate.Hour &&\n                          f.EntryDate.Minute == bar.EntryDate.Minute &&\n                          f.EntryDate.Second == bar.EntryDate.Second);	0
2436757	2436586	Databind List Of Objects To A WinForms DataGridView, But Not Show Certain Public Properties	[Browsable(false)]	0
31517765	31517658	How to force Regex.Replace to match the '/s' (treat string as single line) regex modifier	html = Regex.Replace(html, @"(?<=<strong>CNPJ:)(.*?)(?=hddServidorCaptcha)\s*", string.Empty, RegexOptions.SingleLine);	0
24602906	24594803	Windows 8 phone app linking to other downloaded applications and store	Windows.System.Launcher.LaunchUriAsync(new Uri("fb:"));	0
28641677	28641576	Is there performance gain or another reason for declaring all local variables before?	int f() { \n    int x;   // allowed\n\n    x = 1;\n    int y;   // allowed in C++, but not C89\n\n    {\n       int z=0;    // beginning of new block, so allowed even in C89\n\n       // code that uses `z` here\n    }\n}	0
16857865	16857747	update a number automatically	List<Address>	0
12292888	12292830	Changing path to upload file in FTP	FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" \n                         + ddcdao.ddcAddress + "/" + someDirectory \n                         + "/" someFile);	0
7100847	7086054	how to move two Devex gridview columns together?	private void gridView1_ColumnPositionChanged(object sender, EventArgs e)\n    {\n        if ((colMail1Check.VisibleIndex - colMail1.VisibleIndex) != 1)\n        {\n            colMail1Check.VisibleIndex = colMail1.VisibleIndex + 1;\n        }\n        if ((colMail2Check.VisibleIndex - colMail2.VisibleIndex) != 1)\n        {\n            colMail2Check.VisibleIndex = colMail2.VisibleIndex + 1;\n        }\n    }	0
1198760	1198751	How can i cast into a ObservableCollection<object>	return new ObservableCollection<object>(myTabItemObservableCollection);	0
4326631	4326348	Listing all nested user controls from a master page on page load	void ProcessControls(Control control)\n{\n    if(control is IMyInterface) //whatever your interface name is\n    {\n        (control as IMyInterface).MethodName();\n    }\n\n    foreach(Control child in control.Controls)\n    {\n        ProcessControls(child);\n    }\n}	0
1227957	1227897	Wrapping Serialized Array Elements with the Name of the Array	[XmlArray("MyInnerObjectProperties")]     \n[XmlArrayItemAttribute("MyInnerObjectProperty", typeof(MyInnerObject),  IsNullable = false)]\npublic MyInnerObject[] MyInnerObjectProperty\n{\n   get\n     {\n         return _myInnerObjectProperty;\n     }\n   set\n     {\n        _myInnerObjectProperty = value;\n     }\n}	0
18529507	18529420	Cancel a file upload using .Net client for Amazon S3	Thread.Abort()	0
18546011	18545988	Arrange List<> in ascending order	listCustomFields.sort();	0
6634923	6634870	Help needed with LINQ to SQL Syntax	var qry =   from s in _db.Sites\n            join i in _db.Incidents on s.SiteId equals i.SiteId\n            group s by s.SiteDescription into grp\n            select new\n            {\n                Site = grp.Key,\n                Count =  grp.Count()\n            };	0
33862101	33845773	Reading XML working in my computer but not in my Android phone	TextAsset asset = Resources.Load("file" + select.ToString()) as TextAsset;\n    Stream s = new MemoryStream(asset.bytes);\n    BinaryReader br = new BinaryReader(s);\n\n    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Name>));\n    StreamReader sr = new StreamReader(s);\n    List<Name> listnames = (List<Name>)xmlSerializer.Deserialize(sr);	0
28452708	28452632	Reuse parameters when calling base constructor c#	public class FooFoo : Foo\n{\n    public FooFoo() : this(new Bar()) \n    {\n    }\n\n    public FooFoo(Bar bar) : base(bar, new Qux(bar)) \n    {\n    }\n}	0
10606357	10606277	Combination of two characters	int places = 4;\n        Double totalpossibilities = Math.Pow(2, places);\n\n        for (int i = 0; i < totalpossibilities; i++)\n        {\n            string CurrentNumberBinary = Convert.ToString(i, 2).PadLeft(places, '0');\n\n            CurrentNumberBinary = CurrentNumberBinary.Replace('0', 'x');\n            CurrentNumberBinary = CurrentNumberBinary.Replace('1', 'y');\n            Debug.WriteLine(CurrentNumberBinary);\n        }	0
2737199	2737091	Accept any certificate for SSL	public static bool RemoteCertificateValidationCallback(object sender, \n    X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) \n{\n    return true;\n}	0
1244809	1244000	Find out the current user's username - when multiple users are logged on	ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT UserName FROM Win32_ComputerSystem");\n\n            foreach (ManagementObject queryObj in searcher.Get())\n            {\n                loggedOnUserName = queryObj["UserName"].ToString();\n                loggedOnUserName = loggedOnUserName.Substring(loggedOnUserName.LastIndexOf('\\') + 1);\n            }	0
23792101	23698981	How to pass multiple list types as a parameter using the same method variable	foreach (var value in ReportData)\n{\n    //Reflection can be used\n    string TA01 = value.GetType().GetProperty("TA01").GetValue(value).ToString();\n    //...\n    //...\n    //do more stuff/coding...\n}	0
12820320	12820188	Javascript within a user control in an UpdatePanel not running	ScriptManager.RegisterStartupScript	0
8476144	8476103	Accessing database connection string using app.config in C# winform	System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;	0
17341874	17316330	Revert to the old value at run time if the certain string is present in datagridview c#	int row = dataGridView1.RowCount;\n        string tr="Do not Change";\n        for (int i = 0; i < row-1; i++)\n        {\n            if(dataGridView1[2,i].Value.ToString().Contains(tr))\n            {\n                dataGridView1[2, i].ReadOnly = true;\n            }\n        }	0
10484224	10473997	Handle button click event of button list inside UIScrollView Monotouch	button.TouchUpInside += (s, e) => \n{\n   //play i.mp3\n};	0
6925062	6925005	multiple Eval statements in one control	foreach (Google.GData.Calendar.EventEntry ev in calFeed.Entries)\n        {\n            ExtensionCollection<When> v = ev.Times;\n            DataRow dr = dt.NewRow();\n\n            dr["title"] = ev.Title.Text;\n            dr["url"] = ev.Content.Content;\n            dt.Rows.Add(dr);\n            dt.AcceptChanges();\n        }	0
27026350	27025898	How can I rotate an array of images by 90 degrees?	int[,] array = new int[4,4] {\n    { 1,2,3,4 },\n    { 5,6,7,8 },\n    { 9,0,1,2 },\n    { 3,4,5,6 }\n};\n\nint[,] rotated = RotateMatrix(array, 4);\n\nstatic int[,] RotateMatrix(int[,] matrix, int n) {\n    int[,] ret = new int[n, n];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            ret[i, j] = matrix[n - j - 1, i];\n        }\n    }\n\n    return ret;\n}	0
10797087	10791043	Optimally and elegantly performing certain behaviors based on types in a hierarchy	interface IVisitor\n{\n   void DoBehavior(B item);\n   void DoBehavior(C item);\n}\n\nabstract class A\n{\n    abstract void DoBehavior(IVisitor visitor);\n}\n\nclass B : A\n{\n    override void DoBehavior(IVisitor visitor)\n    {\n       //can do some internal behavior here    \n       visitor.DoBehavior(this); //external processing\n    }\n}\n\nclass C : A\n{\n    override void DoBehavior(IVisitor visitor)\n    {\n       //can do some internal behavior here   \n       visitor.DoBehavior(this); //external processing\n    }\n}\n\n\nclass Manager: IVisitor //(or executor or whatever. The external processing class)\n{\n\n    public static void ProcessAll(List<A> items)\n    {\n        foreach(A item in items)\n        {\n            item.DoBehavior(this);\n        }\n    }\n\n   void DoBehavior(B item)\n   {\n\n   }\n\n   void DoBehavior(C item);\n   { \n\n   }\n\n}	0
5205313	5178497	Optional Parameter in Unittest	using Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace TestProject1\n{\n    public class Someclass\n    {\n        public double CalcSomthing(double valueone, double valuetwo = 10)\n        {\n            Assert.IsTrue(valuetwo == 10);\n            return valueone + valuetwo;\n        }\n    }\n\n    [TestClass]\n    public class UnitTest1\n    {\n        [TestMethod]\n        public void CalcSomthingTest()\n        {\n            var someclass = new Someclass();\n            someclass.CalcSomthing(10);\n        } \n    }\n}	0
12341558	12316720	How to not bind the values at grid load	var isFirst = true;\n\nfunction onGridDataBinding(e){\n   if(isFrist)\n   {\n       isFirst=false;\n       e.preventDefault();\n   }\n}	0
19290807	18457794	Copying Data with Skipped Columns From Excel and Pasting into DataGridView	1,2,3,4,5,6\n1,2,3,4,5,6\n1,2,3,4,5,6\n1,2,3,4,5,6	0
10456359	10456244	c# xml special character encoding	WebClient cln = new WebClient();\nvar str = cln.DownloadString("http://www.google.com/ig/api?weather=vilnius&hl=ru");\nXDocument xDoc = XDocument.Load(new StringReader(str));	0
8618745	8618521	How to create more than 1 check box in ListView object?	dataGridView1.ColumnCount = 3;\n            dataGridView1.Columns[0].Name = "Product ID";\n            dataGridView1.Columns[1].Name = "Product Name";\n            dataGridView1.Columns[2].Name = "Product Price";\n\n            string[] row = new string[] { "1", "Product 1", "1000" };\n            dataGridView1.Rows.Add(row);\n            row = new string[] { "2", "Product 2", "2000" };\n            dataGridView1.Rows.Add(row);\n            row = new string[] { "3", "Product 3", "3000" };\n            dataGridView1.Rows.Add(row);\n            row = new string[] { "4", "Product 4", "4000" };\n            dataGridView1.Rows.Add(row);\n\n            DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();\n            dataGridView1.Columns.Add(chk);\n            chk.HeaderText = "Check Data";\n            chk.Name = "chk";\n            dataGridView1.Rows[2].Cells[3].Value = true;	0
23986043	23985913	Sorting a query based on a category preference using LINQ/Lambda in asp MVC	var preferredCategory = "CategoryC";\nvar result = Products.OrderBy(x => x.Category.Name == preferredCategory ? 0 : 1).\n                      ThenBy(x => <Your previous ordering>);	0
4522310	4522221	Linq to SQL - Update object without selecting it first	UserDataContext db = new UserDataContext();\n[HttpPost]\npublic ViewResult Edit(int userID, FormCollection collection) \n{\n    var user = db.Users.SingleOrDefault(o => o.ID == userID);\n\n    // make sure user or collection isn't null.\n    if (!TryUpdateModel(user, collection)) \n    {\n        ViewBag.UpdateError = "Update Failure";\n\n        return View("Details", um);\n    }\n\n    db.SubmitChanges();\n\n    return View("Details", um); \n}	0
14639075	14542470	Numeric TextBox in DataGridView column	private void dataGridViewItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n        {\n            e.Control.KeyPress -= new KeyPressEventHandler(itemID_KeyPress);//This line of code resolved my issue\n            if (dataGridViewItems.CurrentCell.ColumnIndex == dataGridViewItems.Columns["itemID"].Index)\n            {\n                TextBox itemID = e.Control as TextBox;\n                if (itemID != null)\n                {\n                    itemID.KeyPress += new KeyPressEventHandler(itemID_KeyPress);\n                }\n            }\n        }\n\nprivate void itemID_KeyPress(object sender, KeyPressEventArgs e)\n        {\n            if (!char.IsControl(e.KeyChar)\n                && !char.IsDigit(e.KeyChar))\n            {\n                e.Handled = true;\n            }\n        }	0
1493206	1493189	How to traverse through Request.Form without knowing any details?	StringBuilder s = new StringBuilder();\nforeach (string key in Request.Form.Keys)\n{\n    s.AppendLine(key + ": " + Request.Form[key]);\n}\nstring formData = s.ToString();	0
4491657	4491599	Variable not taking on values in C#	rec = new Record(name, age, dob, sex, country );\nwebservicename.singlesummary[] test = new webservicename.singlesummary[1];\nwebservicename.singlesummary result = new webservicename.singlesummary();\nresult.account = rec.name;\nresult.actualy = rec.age;\nresult.commitment = dob;\nresult.costCentre = sex;\nresult.internalCostCentre = country;\ntest[0] = result;	0
12366343	12365214	How to pass the Classic ASP Response Object to a C# DLL	ASPTypeLibrary.Response	0
1518063	1518002	How to check incoming bool and set private field to then be sent to Base Constructor	public class DatabaseBase\n{\n    private readonly string connectionString;\n    private bool useCounters;\n\n    public DatabaseBase(string connectionString)\n    {\n        this.connectionString = connectionString;\n    }\n\n    public string ConnectionString\n    {\n        get { return connectionString; }\n    }\n}\n\npublic class ProjectDB : DatabaseBase\n{\n    private bool useWebServiceConnection;\n    private bool isWebServiceCall;\n\n    public ProjectDB(bool useWebServiceConnection)\n        : base(\n            useWebServiceConnection\n                ? ConfigurationManager.AppSettings["ServiceConnectionString"]\n                : ConfigurationManager.AppSettings["SomeOtherConnectionString"])\n    {\n        this.useWebServiceConnection = useWebServiceConnection;\n    }\n\n    private SqlConnection CreateConnection()\n    {\n        return new SqlConnection(ConnectionString);\n    }\n}	0
17709880	17709815	C# - How can I do a simple query in Entity Framework using lambda?	var email = User.Email\ndb.BlackstoneUsers.Where(u => u.Email == email);	0
29606951	29606945	How to build batches/buckets with linq	public static IEnumerable<IEnumerable<T>> Bucketize<T>(this IEnumerable<T> items, int bucketSize)\n{\n    var enumerator = items.GetEnumerator();\n    while (enumerator.MoveNext())\n        yield return GetNextBucket(enumerator, bucketSize);\n}\n\nprivate static IEnumerable<T> GetNextBucket<T>(IEnumerator<T> enumerator, int maxItems)\n{\n    int count = 0;\n    do\n    {\n        yield return enumerator.Current;\n\n        count++;\n        if (count == maxItems)\n            yield break;\n\n    } while (enumerator.MoveNext());\n}	0
23904006	23903946	How to do if dont want to read the whole string?	var input = "626120524133452_1400231752";\n\nvar firstNumber = new string(input.TakeWhile(Char.IsDigit).ToArray());	0
23445470	23445380	NullReferenceException while accessing LongListSelector Item	private void playersLongList_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    if (e.AddedItems.Count > 0)\n    {\n        Player p = e.AddedItems[0] as Player;\n        string fname = p.FirstName;\n        MessageBox.Show("hello"+fname);\n    }\n}	0
16100145	16099995	How to create a custom ToolTip with an image?	protected override void OnPaint(PaintEventArgs e)\n{\n    base.OnPaint(e);\n    Image img = Image.FromFile("C:\filepath\filename.jpg");\n    e.Graphics.DrawImage(img, 0, 0);\n    var YourTipTextPoint = new Point(0,0);\n    e.Graphics.DrawString("Hello World", SystemFonts.DefaultFont, Brushes.Black, YourTipTextPoint); \n}	0
7118506	7118449	pass value into 'create view'	Html.ActionLink("create new post", "Create", new { ThreadId = Thread_ID })	0
17481302	17481220	String To Datetime 5/7/2013 07:42 53 AM C#	DateTime dtCurrentFile =  DateTime.ParseExact("5/7/2013 07:42 53 AM","d/M/yyyy hh:mm ss tt",null);	0
25084917	25070743	What Zebra QLn220 settings do I need to set (and to what value[s]) to get a setting to "stick"?	! U1 getvar "appl.name"	0
24238765	24237944	OleDbDataAdapter string concatenation	public void auth_st(string group)\n{\n    conexiuneBD.Open();\n    DataSet ds = new DataSet();\n    OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT Notif FROM teams WHERE ID=?", conexiuneBD);\n    adapter.SelectCommand.Parameters.AddWithValue("p1", group);\n    adapter.Fill(ds);\n    conexiuneBD.Close();\n\n    DataTable dt = ds.Tables[0];\n    foreach (DataRow dr in dt.Rows)\n    {\n        listBoxCerer.Items.Add(dr["Notif"].ToString());\n    }\n}	0
8443215	8443163	Getting parts of a string and combine them in C#?	String toSplit = "C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";\nString[] parts = toSplit.Split(new String[] { @"\" });\n\nString result = String.Empty;\nfor (int i = 5, i > 1; i--)\n{\n   result += parts[parts.Length - i];\n}\n\n// Gives the result 10000080	0
13407208	13407037	Parsing a CSV file	for (int i = 0; i < lines.Count; i++)\n{\n    var fields = lines[i].Split(',').ToList();\n    while (fields.Count < numFields)//here be dragons amonst us\n    {\n        i++;//include next line in this line\n        //check to make sure we haven't run out of lines.\n\n        //combine end of previous field with start of the next one, \n        //and add the line break back in.\n        var innerFields = lines[i].Split(',');\n        fields[fields.Count - 1] += "\n" + innerFields[0];\n\n        fields.AddRange(innerFields.Skip(1));\n    }\n\n    //we now know we have a "real" full line\n    processFields(fields);\n}	0
27568620	27568428	Automapper: Map to Protected Property	Mapper.CreateMap<PolicyDetail, Policy>()    \n.AfterMap((src, dest) => dest.SetBilling(src.Billing));	0
2250721	2250694	Worth having a StringBuilder for 5 concatenations?	cmd2.CommandText = string.Format("insert into {0} values ({1});", TableName, string.Join(",", insertvalues));	0
8791455	8790258	how to update a ADO.NET DataRow in DataTable with another DataRow?	datarow.SetModified()	0
10243405	10243382	How to prevent division by zero?	ads = ads.Where(x => x.Amount != 0 &&\n                    (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);	0
31973387	31884569	Two Reordering ListBoxes on Same page, prevent user from dragging and dropping between	private void Move(Item source, int sourceIndex, int targetIndex)\n        {\n            IList<Item> prevItems = _items;\n\n            try\n            {\n                _items.RemoveAt(sourceIndex);\n                _items.Insert(targetIndex, source);\n\n            }\n            catch(ArgumentOutOfRangeException)\n            {\n                //User doesn't need to be notified about this. It just means that they dragged out of the box they were ordering. \n                //The application does not need to be stopped when this happens.\n                _items = prevItems;\n                Debug.WriteLine("User tried to drag between boxes.. Order of boxes were not changed. ");\n\n            }\n        }	0
12956615	12956454	How to replace elements in one XDocument with elements from another XDocument?	var xDocBig = XDocument.Parse(xmlBig);\nvar xDocSmall = XDocument.Parse(xmlSmall);\n\nvar eBig = xDocBig.XPathSelectElement("/Rootelement/Desktop/C");\nvar eSmall = xDocSmall.XPathSelectElement("/Rootelement/Desktop/C");\n\neBig.ReplaceWith(eSmall);\n\nvar newXml = xDocBig.ToString();	0
33903111	33903072	Attached file contains page's content	Response.End();	0
31218301	31218084	splitting words from a text box using in asp.net	string[] recipients = txtTo.Split(',');\nforeach (string recipient in recipients)\n{\n     mailMsg.To.Add(recipient );\n}	0
4884825	4884749	format a double to 8 decimal places	double d = 0.123456789;\nstring sDisplayValue = d.ToString("0.00000000");	0
1157951	1157943	Retreive Header row for DataGridView control	foreach(DataGridViewColumn col in dataGridView.Columns)\n Console.Out.WriteLine(col.Name);	0
3724554	3724355	.NET DateTime, different resolution when converting to and from OADate?	private static double TicksToOADate(long value)\n    {\n        if (value == 0L)\n        {\n            return 0.0;\n        }\n        if (value < 0xc92a69c000L)\n        {\n            value += 0x85103c0cb83c000L;\n        }\n        if (value < 0x6efdddaec64000L)\n        {\n            throw new OverflowException(Environment.GetResourceString("Arg_OleAutDateInvalid"));\n        }\n        long num = (value - 0x85103c0cb83c000L) / 0x2710L;\n        if (num < 0L)\n        {\n            long num2 = num % 0x5265c00L;\n            if (num2 != 0L)\n            {\n                num -= (0x5265c00L + num2) * 2L;\n            }\n        }\n        return (((double)num) / 86400000.0);\n    }	0
24053926	24053815	Custom Razor ForEach View	// books is your original model data\nvar bookListViewModel = books.GroupBy(b => b.typeBook)\n                                .Select(b => new BookViewModel()\n                                {\n                                    type = b.Key, \n                                    name = string.Join(",", b.Select(book => book.bookName))\n                                });	0
1507008	1506987	How to bind Dictionary to ListBox in winforms	var choices = new Dictionary<string, string>(); \nchoices["A"] = "Arthur"; \nchoices["F"] = "Ford"; \nchoices["T"] = "Trillian"; \nchoices["Z"] = "Zaphod"; \nlistBox1.DataSource = new BindingSource(choices, null); \nlistBox1.DisplayMember = "Value"; \nlistBox1.ValueMember = "Key";	0
2027482	2027458	extracting string data - from the right-hand side?	string test = @"./subfolder/default.aspx";\ntest = test.Substring(test.LastIndexOf(@"/") + 1)	0
7001381	6999079	Access property of UserControl on MasterPage from content page	protected override void OnLoadComplete(EventArgs e)\n        {\n            bool _value = Master.SessionSummaryControl.RejectedBatches;\n            base.OnLoadComplete(e);\n\n        }	0
17003175	17002479	Clicking on a datagrid row and displaying its contents in textboxes	private void dgvSuppliers_CellContentClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if (e.RowIndex >= 0)\n        {\n\n            DataGridViewRow row = this.dgvSuppliers.Rows[e.RowIndex];\n\n            txtID.Text = row.Cells["Supplier ID"].Value.ToString();\n            txtName.Text = row.Cells["Supplier Name"].Value.ToString();\n            txtTelNo.Text = row.Cells["Telephone No"].Value.ToString();\n            txtAddress.Text = row.Cells["Supplier Address"].Value.ToString();\n            txtContactName.Text = row.Cells["Contact Name"].Value.ToString();\n\n        }\n\n    }	0
13765344	13764968	Optimizing a endless list of blocks?	public override Update(GameTime gameTime)\n{\n  var parallelQuery = from b in masterblocklist.AsParallel()\n                            where screenRect.Contains(b.Rect) \n                            select b;\n\n // Process result sequence in parallel\n parallelQuery.ForAll(p => p.Update(gameTime));\n}	0
26547729	26547296	TPL parallelism degree heuristic	var items =\n from o1 in collection1\n from o2 in collection2\n select new { o1, o2 };\n\nParallel.ForEach(items, ...);	0
13433928	13433870	remove alpha characters and white space from string	presaleEstimateHigh = Regex.Replace(presaleEstimateHigh, @"[A-Za-z\s]", string.Empty);	0
1752831	1752823	How do you get the name of a generic class using reflection?	test.GetType().Name.Split('\'')[0]	0
15850620	15848578	Connect to SQL Server Express database via HTTP handler	conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);	0
6697160	6696493	Speeding up converting rtf to plain-text	static ThreadLocal<RichTextBox> rtfBox = new ThreadLocal<RichTextBox>(() => new RichTextBox());\n//convert RTF text to plain text\npublic static string RtfTextToPlainText(string FormatObject )\n{\n     rtfBox.Value.Rtf = FormatObject;\n     FormatObject = rtfBox.Value.Text;\n     rtfBox.Value.Clear();\n\n     return FormatObject;\n}	0
11141306	11141226	Passing in extra parameters in a URL	NavigateUrl='<%# string.Format("/documents/Q-Sheet.aspx?LeadID={0}&isHappyCallReferral=yes&isHappyName={1}", Eval("ID"), Eval("HappyName"))%>'	0
1250918	1250915	Interface declaration together with generic constraints	public class BrandQuery<T> : Query<T>, IDisposable\n    where T : Ad\n{\n  //...\n}	0
10262287	10262173	How to avoid using a number or enum when implementing business logic	Func<Country> GetCountry = () => country ?? (country = new Country(Project, "Unnamed Country"));\nFunc<Region> GetRegion = () => region ?? (region = new Region(GetCountry(), "Unnamed Region", Region.DefaultRegionSettings));\nFunc<City> GetCity = () => city ?? (city = new City(GetRegion(), "Unnamed City", 0));\n\nIDataEntryTarget target = null;\n\nif (!IsCityInfoAvailable())\n{\n    // we have to make a new country, region and city\n     target = GetCity();\n}\nelse if (!IsRegionInfoAvailable())\n{\n    // we have to make a new country and region\n    target = GetRegion();\n}\nelse if (!IsCountryRegionAvailable())\n{\n    // we have to make a new country\n    target = GetCountry();\n}	0
6208840	6207318	C# Sorting a DataTableCollection by a common column in each table	DataTableCollection col;\n\n  foreach(DataTable tbl in col)\n  {\n    // Get the DefaultViewManager of a DataTable and sort it.\n    DataTable1.DefaultView.Sort = "JobNumber";\n  }	0
2256711	2256632	Hacker News style ordering algorithm in Linq-To-SQL	var votesQuery =\n    from i in items\n    join v in votes on i.Id equals v.ItemId\n    orderby\n        (v.Value - 1) / \n                Math.Pow( \n                    (DateTime.Now - i.Posted).Add(new TimeSpan(2,0,0)).Hours, \n                1.5 )\n    select new\n    {\n        Item = i,\n        Vote = v\n    };	0
33011826	33011345	Json object with array for datasource binding	class SampleResponse1\n{\n    [JsonProperty("openingDate")]\n    public int[] Opening{ get; set; }\n\n    public DateTime OpeningDate\n    {\n        get\n        {\n            return new DateTime(Opening[0], Opening[1], Opening[2]);\n        }\n    }\n}	0
13002047	13001598	How to write a function that determines if a key is down and a delay passed?	Dictionary<Keys, DateTime> keytimes = new Dictionary<Keys, DateTime>();\n\npublic bool IsKeyDownWithDelayPassed(Keys key, long delay)\n{\n    if(!keytimes.Keys.Contains(key) || keytimes[key] == DateTime.MinValue)\n        return false;\n    long elapsed = DateTime.Now.Ticks - keytimes[key].Ticks;    \n    return delay < elapsed;\n}\n\nprivate void KeyDownEvent(object sender, KeyEventArgs e)\n{\n    keytimes[e.KeyData] = DateTime.Now;\n}\n\nprivate void KeyUpEvent(object sender, KeyEventArgs e)\n{\n    keytimes[e.KeyData] = DateTime.MinValue;\n}	0
1596451	1595203	how to make line after 2 rows in crystal report?	remainder(recordnumber, 3) <> 0	0
9947357	9938670	Replace xml node in c#	XmlDocument xmlDoc = new XmlDocument();\n        XmlDocument xmlDoc2 = new XmlDocument();\n\n        xmlDoc.Load(xmlFile);\n        xmlDoc2.Load(xmlFile2);\n\n\n        XmlNode node = xmlDoc.SelectSingleNode("Root/RuleDTO/RuleID");\n        XmlNode node2 = xmlDoc2.SelectSingleNode("Root/RuleDTO[1]/RuleID");\n        XmlNode node3 = xmlDoc2.SelectSingleNode("Root/RuleDTO[2]/RuleID");\n\n        if (node != null && node2 != null && node3 != null)\n            node3.InnerText = node2.InnerText = node.InnerText;\n\n        xmlDoc2.Save(xmlFile2);	0
13733571	10208945	How to remove element if self closing tag is found	var file = "C:\\YourPath\\data.xml";\nvar doc = new XmlDocument();\ndoc.Load(file);\nvar nodes = doc.SelectNodes("/rounds/round");\nforeach (XmlNode item in nodes)\n{\n    if (item.InnerXml == String.Empty)\n    {\n        item.ParentNode.RemoveChild(item);\n    }\n}\ndoc.Save(file);	0
16007417	16007003	Adding controls to a Panel in an UpdatePanel	List<Literal> persistControls = new List<Literal>();\nprotected void Page_Load(object sender, EventArgs e)\n{\n    // if you already have some literal populated\n    if (Session["persistControls"] != null)\n    {\n        // pull them out of the session\n        persistControls = (List<Literal>)Session["persistControls"];\n        foreach (Literal ltrls in persistControls)\n            commentPanel.Controls.Add(ltrls); // and push them back into the page\n    }\n}\n\nprotected void commentButton_Click(object sender, EventArgs e)\n{\n    Literal myComment = new Literal();\n    myComment.Text = "<p>" + commentBox.Text + "</p><br />";\n    commentPanel.Controls.Add(myComment);\n    persistControls.Add(myComment);// add it to the list\n    Session["persistControls"] = persistControls; // put it in the session\n}	0
8297875	8286881	How can send bytes for arduino?	// ...   \nprivate void button1_Click(object sender, System.EventArgs e)\n{\n    SendByte(1); // Send byte '1' to the Arduino\n}\n\nprivate void SendByte(byte byteToSend) {\n    byte[] bytes = new byte[] { byteToSend };\n    serialPort1.Write(bytes, 0, bytes.Length);\n}\n// ...	0
5717472	5715338	CSV string to DataTable	string s = "Id,Name ,Dept\r\n1,Mike,IT\r\n2,Joe,HR\r\n3,Peter,IT\r\n";\n        DataTable dt = new DataTable();\n\n        string[] tableData = s.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n        var col = from cl in tableData[0].Split(",".ToCharArray())\n                  select new DataColumn(cl);\n        dt.Columns.AddRange(col.ToArray());\n\n        (from st in tableData.Skip(1)\n         select dt.Rows.Add(st.Split(",".ToCharArray()))).ToList();	0
10223907	10223852	Calculate value to Percentage, and base other values based on this value	Double max = 200d;\nDouble current = 23d;\n\nDouble percent = current / max * 100;	0
12943875	12938294	Retrieving Managed Properties from a SharePoint site	foreach (SPService service in SPFarm.Local.Services)\n{\n    if (service is SearchService)\n    {\n        SearchService searchService = (SearchService)service;\n\n        foreach (SearchServiceApplication ssa in searchService.SearchApplications)\n        {\n            Schema schema = new Schema(ssa);\n\n            foreach (ManagedProperty property in schema.AllManagedProperties)\n            {\n                if (property.Name == "ContentType")\n                {\n                    //Handle here\n                }\n            }\n        }\n    }\n}	0
13343666	13342766	how to avoid duplicates of attributes in xml c#?	List<string> values = new List<string>();\n\nusing (XmlReader reader = XmlReader.Create("your path", settings)) \n{\n    while (reader.Read()) \n    {\n        if (reader.NodeType == XmlNodeType.Element) \n        {\n            if (reader.HasAttributes) \n            {\n                if (reader.GetAttribute("UnityName") != null) \n                {\n                    signalsa = reader.GetAttribute("UnityName");\n                    if (!values.Contains(signalsa))\n                    {\n                        values.Add(signalsa);\n                        //rest of your code goes here...\n                    }\n                }\n            }\n        }\n    }\n}	0
24155220	24155188	Nullable DateTime to String	string strdatetime = datetime.HasValue ? datetime.Value.ToString("MM/dd/yyyy") : string.Empty;	0
27773145	27773077	Comparing cells in a dataset and prepending information	for (int j = 0; j <= dsDHS.Tables[0].Columns.Count - 1; j++)\n{\n    var originalValue = dsDHS.Tables[0].Rows[i][j].ToString();\n    var padded = originalValue.PadLeft(6, '0');\n\n    str.Append(padded);\n}	0
4208604	4208529	Communicate Between two threads	void MainGragfik_ProgressUpdate(double progress)\n{\n    if (InvokeRequired)\n    {\n         BeginInvoke((MethodIvoker)(() =>\n         {\n             MainGragfik_ProgressUpdate(progress);\n         }));\n\n         return;\n    }\n\n    ProgressBar = progress;\n}	0
17789458	17789265	c# assigning different values to an array with random generator	string[] numbers ={ "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"};\n\nList<string> remaining = new List<string>(numbers);\n\nRandom r = new Random();\n\nfor (int i = 0; i < 3; ++i)\n{\n    int n = r.Next(0, remaining.Count);\n    sounds[i] = remaining[n];\n    remaining.RemoveAt(n);\n}	0
17980425	17980391	Determine if list of strings is in another list of strings	var allIn = !l2.Except(l1).Any();	0
881739	881679	Parse the number with Regex with non capturing group	// pattern for matching anything that is not '+' or a decimal digit\nstring replaceRegex = @"[^+\d]";\nstring formated = Regex.Replace("+48 123 234 344", replaceRegex, string.Empty);	0
30219433	30218457	How access to persistentDataPath child folders on IOS (Unity Deployment)?	string dir = Application.persistentDataPath + "/Config";\nif (!Directory.Exists (dir)) {\n    Directory.CreateDirectory (dir);\n}\nstring configFile = dir + "/config.ini";\nif (!File.Exists (configFile)) {\n    File.Create (qcarFile);\n}	0
15996256	15995799	How Use PublicApp.Config In All Of My Project	namespace ClassLibrary1\n{\n\npublic static class GetConfiguration\n{\n\npublic static string ComputerName\n{\n    get\n    {\n\n        return System.Configuration.ConfigurationManager.AppSettings["ComputerName"];\n    }\n}\n\n}\n\n}	0
22058489	22058340	Trying to pin image on map with onclick event to page, based on binding.	var id = ((sender as Pushpin).DataContext as Location).ID;	0
3150535	3150458	Aggregate lambda expressions	( x = [value of last lambda expression], y = [next value] ) => x+y	0
13682370	13682214	C# Search for a word occurances within a string	string searchString = "TEST";\nstring completeText = "Some sentence TEST with other words incluing TEST";\nint count = completeText.Split(new string[]{"TEST"},StringSplitOptions.None)\n                        .Count() - 1;\nMessageBox.Show(count.ToString() + " Matches Found");	0
5802151	5801165	MongoDB server connection	MongoServer mongo  = MongoServer.Create("mongodb://192.168.11.237:27017")	0
16405797	16405709	RegEx extract values from string using C#	Match match = Regex.Match(str, @"\[(\d+)-(\d+)\]");\nif (match.Success) {\n    //match.Groups[1].Value is the first number\n}	0
18715036	18714988	Maximum size of image column in db while configuring database	VARBINARY(MAX)	0
15893774	15893755	Adding a Vector2 to List	public List<Vector2> alienPosition = new List<Vector2>();\n    int someCount = 10;\n        for (int x = 0; x < someCount; x++)\n            {\n                alienPosition.Add(new Vector2((x * 20) + 50, 20));\n            }	0
32516963	32516282	How can I find the sum of the elements within a ListBox in WPF	private void YesButton_Click(object sender, RoutedEventArgs e)\n    {\n      int sum = 0;\n      int i = 0;\n      // YesButton Clicked! Let's hide our InputBox and handle the input text.\n      InputBox.Visibility = System.Windows.Visibility.Collapsed;\n\n    // Do something with the Input\n    String input = InputTextBox.Text;\n    int result = 0;\n    if (int.TryParse(input, out result))\n    {\n        MyListBox.Items.Add(result); // Add Input to our ListBox.\n    }\n    else \n    {\n       sum = MyListBox.Items.Cast<int>().Sum(x => Convert.ToInt32(x));\n       MessageBox.Show("Sum is: " +sum);\n    }\n    // Clear InputBox.\n    InputTextBox.Text = String.Empty;\n}	0
15107879	15107789	How to enter a folder without knowing its name?	string unknownPath = Directory.GetDirectories(path)[0];\n//Now instead of this: [ string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName) ], do this:\nstring readText = File.ReadAllText(unknownPath + "\\" + itemName);	0
17260166	17256603	XML Parser gets stuck on special characters, despite encoding	WebClient myWebClient = new WebClient();\nbyte[] data = myWebClient.DownloadData(uri);\n\nstring xmlContents = Encoding.UTF8.GetString(data);	0
21730443	21730252	how to remove Xelement without its children node using LINQ?	var x = doc.Root.Element("X");\nx.Remove();\ndoc.Root.Add(x.Elements());	0
31405059	31404923	Syntax error in INSERT INTO statement c#	"insert into OrderForm ([Customer Name], Address, [Telephone Number], [Post Code]) values('" + customerName.Text + "', '" + addrBox.Text + "', '" + telephoneNumber.Text + "', '" + postCode.Text + "')";	0
7657483	7657201	Selenium webdriver with C#	SelectElement select = new SelectElement(dropdownobject);\nselect.SelectByText("ItemText");	0
3258990	3258953	How to have a program know where it has been launched?	// Should check to make sure there is at least one filename passed first...\n  string imageFilename = Environment.GetCommandLineArgs[1];\n  string directory = System.IO.Path.GetDirectoryName(imageFilename);	0
8504390	8504300	assigning string to a property of string type C#	data.lastName = actual;	0
21361937	21308766	ASP.net How can I invalidate in textchanged event	protected void btnIssueItem_Click(object sender, EventArgs e)\n    {\n        Page.Validate();\n        if (!Page.IsValid)\n            return;\n....\n}\n\n\nprotected void tbRoomID_CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)\n    {\n        BAL bal = new BAL();\n        args.IsValid = bal.GetRoomByRoomID(Int32.Parse(args.Value)).Count == 0 ? false : true;\n    }	0
24916633	24871014	HttpClient / WebClient - Trouble Interacting With Websites via Proxy	_client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0");	0
2507254	2506381	Transferring files from one PC to another using C#?	File.Copy(@"\\server\folder$\test.txt", "test.txt");	0
12497202	12495519	Implementing activeX control to view PowerPoint slides in Windows forms using c#, not showing control	private void Form1_Load(object sender, EventArgs e)\n    {\n        this.axPowerPointViewer1.InitControl();\n    }	0
29663640	29663360	Display listbox.items in foreach	foreach (Namespace.ClassName item in ListBox.Items)\n{\n    Message.Box(item.Symbol);\n}	0
19059266	19014953	Accented Chars in HTML email	protected override void OnMailSending(MailSendingContext context)\n{\n    for (var i = 0; i < context.Mail.AlternateViews.Count; i++)\n    {\n        var av = context.Mail.AlternateViews[i];\n        if (av.ContentType.MediaType == MediaTypeNames.Text.Html)\n        {\n            av.ContentStream.Position = 0;\n            var content = new StreamReader(av.ContentStream).ReadToEnd();\n            content = content.Replace("F?sica", "F??sica");\n            context.Mail.AlternateViews[i] = AlternateView.CreateAlternateViewFromString(content, av.ContentType);\n        }\n    }            \n    base.OnMailSending(context);\n}	0
18612218	18594274	C# delegates from C++	public delegate void OnInputDownDelegate(int input);\nprivate OnInputDownDelegate mDelegate;\n\n[DllImport("mylib.dll", CallingConvention = CallingConvention.Cdecl)]\ninternal static extern void libRegisterInput( OnInputDownDelegate f );\n\npublic void RegisterOnInput(OnButtonDownDel f)\n{\n    mDelegate = f;\n    libRegisterInput( mDelegate );\n}	0
17730637	17730529	Understanding connection string atrributes	Integrated Security=True	0
8847786	8847699	c# windows authentication for a asp.net web interface	(WindowsIdentity)HttpContext.Current.User.Identity;	0
17995502	17994674	c# WPF Line and Column number from RichTextBox	TextPointer tp1 = rtb.Selection.Start.GetLineStartPosition(0);\nTextPointer tp2 = rtb.Selection.Start;\n\nint column = tp1.GetOffsetToPosition(tp2);\n\nint someBigNumber = int.MaxValue;\nint lineMoved, currentLineNumber;\nrtb.Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved);\ncurrentLineNumber = -lineMoved;\n\nLineColumnLabel.Content = "Line: " + currentLineNumber.ToString() + " Column: " + column.ToString();	0
14633591	14632641	selecting files and saving it to the defined location using folder browse dialog	string destination = @"c:\programfiles\myfolder";\nOpenFileDialog ofd = new OpenFileDialog();\nofd.Multiselect = true;\nif (DialogResult.OK == ofd.ShowDialog()) {\n    foreach (string file in ofd.FileNames)  {\n        File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));\n    }\n}	0
19411901	19350262	WP8 WriteableBitmap constructor keeps a lot of memory	WriteableBitmap picture = new WriteableBitmap(PictureCanvas, null);\n    using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())\n    using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(Globals.OVERLAY_FILE_NAME, FileMode.Create, myIsolatedStorage))\n    {\n        picture.SaveJpeg(fileStream, picture.PixelWidth, picture.PixelHeight, 0, 100)\n    }	0
13020396	13020355	How to set an enum that I can use throughout my app	class Foo {\n    private EmploymentStatus Status;\n\n    void Operation() {\n        this.Status = EmploymentStatus.FullTime;\n    }\n}	0
12334883	12334226	Open an URL in the Default Web Browser in WinRT	Windows.System.Launcher.LaunchUriAsync	0
7382239	7377630	Extract values from JSON string c#	for(i=0;i<r['data'].length,i++) {\n    newObject[i] = r['data'][i][0];\n}\nreturn JSON.stringify(newObject);	0
23092506	23092254	How to Convert this WIF 3.5 code to WIF 4.5	var cp = HttpContext.Current.User as System.Security.Claims.ClaimsPrincipal;\nIEnumerable<Claim> claims = cp.FindAll("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn");	0
3923557	3923524	Complement List of a sub List	listSub_B.AddRange(listSuper.Except(listSub_A));	0
605186	603677	networking design ; socket communication using polling	if (_socket.IsAvailable > 0) {\n      ProcessSocket(socket);\n  } else {\n      Console.WriteLine("Poll() returned true but there is no data");\n  }	0
12416235	12416038	Thread makes application halt	// this is your thread method\n// it touches no UI elements, just loads files and passes them to the main thread\nprivate void LoadFiles(List<string> filenames) {\n   foreach (var file in filenames) {\n      var key = filename.Replace(...);\n      var largeBmp = Image.FromFile(...);\n      var smallBmp = Image.FromFile(...);\n      this.Invoke(new AddImagesDelegate(AddImages), key, largeBmp, smallBmp);\n   }\n}\n\n// this executes on the main (UI) thread    \nprivate void AddImages(string key, Bitmap large, Bitmap small) {\n   // add bitmaps to listview\n   files.SmallImageList.Images.Add(key, small);\n   files.LargeImageList.Images.Add(key, large);\n}\n\nprivate delegate AddImagesDelegate(string key, Bitmap large, Bitmap small);	0
3720620	3720600	converting decimal to int in c#	int percentage = (int)(rate*100);	0
5467940	5467860	How to calculate an expression for each row of a datatable and add new column to the datatable based on the result got	DataTable dt = new DataTable();\ndt.Columns.AddRange(new[] { new DataColumn("ID", typeof(decimal)), new DataColumn("DepartmentID", typeof(decimal)) });\n\nfor (int iRow = 0; iRow < 10 ; iRow++)\n{\n    DataRow dr = dt.NewRow();\n    dr["ID"] = iRow;\n    dr["DepartmentID"] = iRow;\n    dt.Rows.Add(dr);\n}\ndt.Columns.Add(new DataColumn("Test", typeof (decimal), "((ID + DepartmentID)*ID)"));	0
7235751	7235499	Trying to use a reference to my mainform	// in your MainForm\nNewForm nwForm = new NewForm();\nnwForm.ShowDialog(this);\n\n// inside your NewForm object, after loading\n(this.Owner as MainForm).Foo();	0
14934363	11674315	How add TreeNode to TreeNodeCollection with more than name and text in C#	void add_tooltiptext(DataTable mytab)\n    {\n        try\n        {\n\n            foreach (DataRow nodes in mytab.Rows)\n            {\n                TreeNode[] found = treeView1.Nodes.Find(nodes["id"].ToString(), true);\n                for (int i = 0; i < found.Length; i++)\n                {\n                    treeView1.SelectedNode = found[i];\n\n                    treeView1.SelectedNode.ToolTipText = nodes["description"].ToString();\n                }\n            }\n\n        }\n        catch\n        { }\n    }	0
18608040	18607917	how to pass a datatable to a new form in windowsce	public cariSelection(DataTable dt) {\n    InitializeComponent() \n    dataGrid1.DataSource = dt;   // I am getting the null reference exception here\n}	0
21120101	21119975	one button click creates two events	bool clockedIn = false;\n\npublic void button1_Click(object sender, EventArgs e)\n{\n    if (!clockedIn)\n    {\n        // employee just arrived - log arrival time\n    }\n    else\n    {\n        // employee leaving - log departure time\n    }\n\n    clockedIn = !clockedIn;\n}	0
16228435	16226743	Access pixels in a 16-bit TIFF	using FreeImageAPI;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // load image, this can by your 16-bit tif\n            FIBITMAP dib = FreeImage.LoadEx("myfile.tif");\n            // convert to 8-bits\n            dib = FreeImage.ConvertToGreyscale(dib);\n            // rotate image by 90 degrees\n            dib = FreeImage.Rotate(dib, 90);\n            // save image\n            FreeImage.SaveEx(dib, "newfile.png");\n            // unload bitmap\n            FreeImage.UnloadEx(ref dib);\n       }\n    }	0
24034824	24003275	How to get a collection with linq but leave out some entities from a nested collection?	List<Group> groups = context.Groups\n                            .Where(group => group.Station.Id == stationId \n                                            && group.Users.Where(u => u.Account.IsActive == true).Count() > 0).ToList();	0
4229740	4229662	Convert numbers within a range to numbers within another range	int Adjust( int num )\n{\n    return num * 2 - 255;\n}	0
18621531	18621231	Writing SQL query to read data from CRM 2011	Metadata Document Generator	0
21848198	21830558	Add padding to edges of MKMapView in Xamarin C#	_map.SetVisibleMapRect (_routeOverlay.BoundingMapRect, new UIEdgeInsets(20, 20, 20, 20), true);	0
31866401	30068286	Converting a BITMAP structure to a BitmapImage/BitmapSource compatible byte array?	bitmap.WidthBytes * bitmap.Height	0
1092957	1092948	How can i put just the date from a dateTimePicker into a variable?	varDate = dateTimePicker1.Value.Date;	0
6740152	6449832	Get list of DataField in gridview	String boundFields = String.Empty;\n\nfor (int i = 0; i < grd.Columns.Count; i++)\n{\n    DataControlField field = grd.Columns[i];\n    BoundField bfield = field as BoundField;\n\n    if (bfield != null)\n        boundFields += bfield.DataField + ",";\n}\nboundFields = boundFields.TrimEnd(',');	0
6770766	6770597	Entity Framework in n-Tier	IRepository<T>\n{\n   IEnumerable<T> GetAll();\n   T GetById(int id);\n   void Save(T saveThis);\n   void Delete(T deleteThis);\n}	0
7073589	7073564	How to Search for a file in the drive with asp.net and C#	DirectoryInfo folder = new DirectoryInfo(@"C:\Examples");\nFileInfo[] files = folder.GetFiles("MyFile*.txt", SearchOption.AllDirectories);	0
27359131	27359102	How do I set two class properties from one SET method c#	private string _title;  \npublic Title \n{\n    get\n    {\n        return _title;\n    }\n    set\n    {\n        _title = value;\n        UrlTitle = HttpUtility.UrlEncode(value.Replace(" ", "-").Trim());\n    }\n}\n\npublic UrlTitle { get; private set; }	0
32288458	32286358	How to get Selected TreeViewItems in TreeView WPF	ParentNode.Selected += new RoutedEventHandler(SelectedNodeItem);\n\nvoid SelectedNodeItem(object sender, RoutedEventArgs e)\n {\n    TreeViewItem SelectedTreeViewItem = ((TreeViewItem)e.Source);\n }	0
15276130	15276064	Return value in stored procedure MYSQL	var returnValue = new SqlParameter("returnVal", SqlDbType.Int);\nreturnValue.Direction = ParameterDirection.ReturnValue;\ncommand.Parameters.Add(returnValue);	0
14304102	14303992	Input field to populate GridView	protected void submit_Click(object sender, EventArgs e)\n{\n   String keyword = input.Text;            // Gets text inputed\n   var v= service.getTitles(keyword);   \n   grd.dataSource=v;\n   grd.dataBind();\n}	0
28830760	28830341	Listitem added in to second row in c#	SessionList.Items.Clear();	0
10184613	10184152	Orderby datetime query in a foreach loop	var temp = from feed in xDoc.Descendants("Students")\norderby Convert.ToDateTime(feed.Element("CreatDate").Value) descending\nselect new Student\n{\n    ID = Convert.ToInt32(feed.Element("ID").Value),\n    //rest of the properties\n};	0
13928851	13928327	Sum, Subtract and Multiply arrays	int[,] a3 = new int[2,3];\n\nfor(int i = 0; i < myArray1.GetLength(0); i++)\n{\nfor(int j = 0; j < myArray1.GetLength(1); j++)\n{\na3[i,j] = myArray1[i,j] + myArray2[i,j];\na3[i,j] = myArray1[i,j] - myArray2[i,j];\na3[i,j] = myArray1[i,j] * myArray2[i,j];\n}\n}	0
7850260	7850246	Create TreeNodes with key in a Linq expression	TreeNode tn = new TreeNode("text node") {Name = "keynode"} ;	0
26165119	26164669	EWS Search Appointments by Subject	SearchFilter.SearchFilterCollection coll = new SearchFilter.SearchFilterCollection(LogicalOperator.And);            \n        SearchFilter subjectFilter = new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "test");\n        SearchFilter dateFilter = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, DateTime.Today);\n        coll.Add(subjectFilter);\n        coll.Add(dateFilter);\n\n        FindItemsResults<Item> findResults = svc().FindItems(fId, coll, view);	0
2667096	2666645	InvalidCastException Object[*] to Object[]	public static object[] ConvertFoxArray(Array arr) {\n  if (arr.Rank != 1) throw new ArgumentException();\n  object[] retval = new object[arr.GetLength(0)];\n  for (int ix = arr.GetLowerBound(0); ix <= arr.GetUpperBound(0); ++ix)\n    retval[ix - arr.GetLowerBound(0)] = arr.GetValue(ix);\n  return retval;\n}	0
1030772	1030765	How do I extract a value from inside of a formatted string?	var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");\nvar ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));	0
10784363	10783390	How to create a Must Not Match attribute for email address	public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n{\n      List<ValidationResult> validationResults = new List<ValidationResult>();\n\n      if (string.Equals(this.Email1,this.Email2,StringComparison.OrdinalIgnoreCase))\n      {\n          validationResults.Add(new ValidationResult(ErrorMessage.EmailError, new string[] { "Email ID" }));\n      }\n\n      return validationResults;\n}	0
5597490	5597199	Getting a specific branch and all its values in the registry	Dictionary<string, object> keyValuePairs;\nusing (var settingsRegKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Printers\\DevModes2\\Settings"))\n{\n       var valueNames = settingsRegKey.GetValueNames();\n       keyValuePairs = valueNames.ToDictionary(name => name, settingsRegKey.GetValue);\n}	0
682548	682360	Getting Local Windows User login session timestamp in C#	using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.DirectoryServices;\n\nnamespace ADMadness\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            DirectorySearcher search = new DirectorySearcher("LDAP://DC=my,DC=domain,DC=com");\n            search.Filter = "(SAMAccountName=MyAccount)";\n            search.PropertiesToLoad.Add("lastLogonTimeStamp");\n\n\n            SearchResult searchResult = search.FindOne();\n\n\n            long lastLogonTimeStamp = long.Parse(searchResult.Properties["lastLogonTimeStamp"][0].ToString());\n            DateTime lastLogon = DateTime.FromFileTime(lastLogonTimeStamp);\n\n\n            Console.WriteLine("The user last logged on at {0}.", lastLogon);\n            Console.ReadLine();\n        }\n    }\n}	0
7982719	7982607	Unnecessary cast to IComparer?	public class StringEnumerable : IEnumerable, IEnumerable<String>\n{\n    IEnumerator<String> IEnumerable<String>.GetEnumerator()\n    {\n        yield return "TEST";\n    }\n\n    public IEnumerator GetEnumerator()\n    {\n        // without the explicit cast of `this` to the generic interface the \n        // method would call itself infinitely until a StackOverflowException occurs\n        return ((IEnumerable<String>)this).GetEnumerator();\n    }\n}	0
7265154	7260280	Cannot Switch TabItem from DoubleClick Event	e.handled = true;	0
10954498	10954142	How to convert a jagged double array to a string and back again?	var doubleAR = new List<List<Double>>()\n{\n   new List<double>(){ 12.5, 12.6, 12.7 },\n   new List<double>(){ .06 },\n   new List<double>(){ 1.0, 2.0 }\n};\n\n   var asXml = new XElement("Data",\n                            doubleAR.Select(sList => new XElement("Doubles", sList.Select (sl => new XElement("Double", sl) )))\n                           );\n\n    Console.WriteLine ( asXml );\n/* Output\n<Data>\n  <Doubles>\n    <Double>12.5</Double>\n    <Double>12.6</Double>\n    <Double>12.7</Double>\n  </Doubles>\n  <Doubles>\n    <Double>0.06</Double>\n  </Doubles>\n  <Doubles>\n    <Double>1</Double>\n    <Double>2</Double>\n  </Doubles>\n</Data> */\n\n// Then back\n   List<List<Double>> asDoubleArray =\n         XDocument.Parse( asXml.ToString() )\n                  .Descendants("Doubles")\n                  .Select (eDL => eDL.Descendants("Double")\n                                     .Select (dl => (double) dl))\n                                      .ToList())\n                  .ToList();	0
3445690	3445678	Cannot remove items from ListBox	while(lstPhotos.SelectedItems.Count != 0)\n{\n    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);\n}	0
21877170	21876570	Trying to convert a json object to DataTable	String json="....some json string...";\n\nDataTable tester = (DataTable) JsonConvert.DeserializeObject(json, (typeof(DataTable)));	0
28738360	28738287	WPF Datagrid focus and highlighting last row	private void CommitRow(object sender, DataGridRowEditEndingEventArgs e )\n    {\n       //FIRE WHEN ROW IS DONE EDIT\n       /*\n       STORING DATA TO DATABASE\n       */\n\n    Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>\n    {\n        SelectRowByIndex(Datagrid, Datagrid.Items.Count - 1);\n    }));\n }	0
7808860	7808633	How to set Owner property of a Modal form?	class Form1: Form\n{\n.\n.\n.\n    public void showNewDialog()\n    {\n        Form2 diagForm = new Form2(){ Owner = this };\n        diagForm .showDialog();\n        diagForm .Dispose();\n    }\n}	0
5449882	5449863	How to get the count from IQueryable	public IQueryable BindEmployees(int startRowIndex, int maximumRows, out int count)\n{\n    EmployeeInfoDataContext dbEmp = new EmployeeInfoDataContext();\n    var query = from emp in dbEmp.Employees\n                join dept in dbEmp.Departments\n                    on emp.DeptID equals dept.DeptID\n                select new\n                {\n                    EmpID = emp.EmpID,\n                    EmpName = emp.EmpName,\n                    Age = emp.Age,\n                    Address = emp.Address,\n                    DeptName = dept.DepartmentName\n                };\n\n    count = query.Count();\n    return query.Skip(startRowIndex).Take(maximumRows);\n}	0
1174784	1174715	Finding File data from POST in C#	Request.Files["file"]	0
32457886	32457621	How to find in store the certificate I need?	foreach (X509Certificate2 mCert in store.Certificates)\n{\n    if(mCert.Thumbprint.ToLower()=="Your Certificat hash")\n    {\n        //TODO\n    }\n}	0
914155	914109	How to use LINQ to select object with minimum or maximum property value	People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) < curMin.DateOfBirth ? x : curMin))	0
7724520	7723999	How to read values from boxes like messagebox or any other?	form.ShowDialog()	0
1990591	1989974	How to iterate through Dictionary without using foreach	static LinkedList<LeafItem> TreeList = new LinkedList<LeafItem>( );\nforeach (LeafItem li in TreeList) {\n    Thread newThread = new Thread(\n                new ParameterizedThreadStart(Work.DoWork));\n    newThread.Start(li);\n    }	0
11980195	11976418	What's the best way to asynchronously load data into a Data Grid View?	void Form1_Load(object sender, EventArgs e)\n    {\n        this.BeginInvoke(new MyDelegate(delegate()\n        {\n            ReadXml(path);\n            Bind();\n        }));\n    }	0
22179013	22178955	Whats wrong with my switch statement?	IEnumerable<ProductActiveResponse> sortedProducts;\n\n...\n\nsortedProducts = product.OrderBy(m => m.OrderDate);\n\n...\n\nvar trimmedProducts = sortedProducts.Skip((request.Page - 1) * request.ProductsPerPage).Take(request.ProductsPerPage);	0
14161567	14161484	DataContract Parent reference in child property - how to avoid infinite serialization loop	[DataContract(IsReference = true)]	0
32651840	32651263	Reverse result of a partion from a list using Entity Framework and ASP.NET MVC	void Main()\n{\n    var hobbies = new List<Hobby>()\n    {\n        new Hobby { ID = 1, Name = "Test 1" },\n        new Hobby { ID = 2, Name = "Test 2" },\n        new Hobby { ID = 3, Name = "Test 3" },\n        new Hobby { ID = 4, Name = "Test 4" }\n    };\n\n    var ids = new[] { 2, 3 };\n\n    var rest = hobbies.Where(x => !ids.Contains(x.ID)).ToList();\n    rest.Dump();\n}\n\npublic class Hobby\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n}\n\n\nID  Name\n1   Test 1 \n4   Test 4	0
15018001	14907597	How to make sure button click animations are shown when event raised via code?	private void changeButtonState()\n    {\n        if (_isPressed)\n        {\n            _state = "Pressed";\n            _isPressed = false;\n        }\n        else\n        {\n            _state = "Normal";\n            _isPressed = true;\n        }\n\n        VisualStateManager.GoToState(btnClick, _state, true);\n    }	0
23776730	23776520	convert ViewBag value into integer type	ViewBag.test = 13;\n                if (ViewBag.test is string)\n                { \n                  //This is string\n                }\n                else if (ViewBag.test is Int32)\n                {\n                   //this is integer\n                }	0
22937355	22936600	json.net, JsonReaderException: After parsing a value an unexpected character was encountered	public static void Main()\n{\n      const string jsonString = "{ \"id\":15, \"username\":\"patrick\" }";\n      User u = JsonConvert.DeserializeObject<User>(jsonString);\n}	0
28242530	28239214	Creating HTTP Header parameters in a SOAP interface in .Net	public partial class MyService\n{\n    private ConcurrentDictionary<string, string> requestHeaders = new ConcurrentDictionary<string, string>();\n\n    public void SetRequestHeader(string headerName, string headerValue)\n    {\n        this.requestHeaders.AddOrUpdate(headerName, headerValue, (key, oldValue) => headerValue);\n    }\n\n    protected override WebRequest GetWebRequest(Uri uri)\n    {\n        var request = base.GetWebRequest(uri);\n\n        var httpRequest = request as HttpWebRequest;\n        if (httpRequest != null)\n        {\n            foreach (string headerName in this.requestHeaders.Keys)\n            {\n                httpRequest.Headers[headerName] = this.requestHeaders[headerName];\n            }\n        }\n\n        return request;\n    }\n}	0
9292096	9291978	How to implement the following as in the image using asp.net c# GridView	Nested GridView Control to Display Related Data	0
30029475	30027364	Treeview get full path to HDD	string fullPath = Path.Combine(basePath, nodeValue);	0
2128301	2128259	Removing border from WebBrowser control	border:0px	0
5574690	5574638	Is there a way to set the width of a GridViewColumn to Auto?	col.Width = Double.NaN;	0
3708678	3708664	C# System.Diagnostics.Process: how to exit a process if it takes more than, say, 10 seconds?	if (!p.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))\n{\n    // timeout exceeded while waiting for the process to exit\n}	0
33760398	33756851	C# Download File from FTP AS400	request.UseBinary = false;	0
16992498	16992430	Multiple calls (at once) to a method that can only run one at a time	private static Object lockGuard = new Object();\n   public void DoSomething()\n   {\n     lock (lockGuard) \n      {\n          //logic gere\n      }\n    }	0
19117666	19115516	Enable [save & save as] only If there is an open file	var newChild = new Form() { MdiParent = this };\n menuItem.Enabled = true;\n newChild.FormClosing += (s, o) => menuItem.Enabled = (this.MdiChildren.Length  == 1) ? false : true;\n newChild.Show();	0
7428613	7394423	Run a command line from a running application through c#	System.Diagnostics.Process process = Process.GetProcessesByName("OpenSim.32BitLaunch")[0];\n\n        Process[] processes = Process.GetProcessesByName("OpenSim.32BitLaunch");\n\n        foreach (Process p in processes)\n          {\n\n\n              SetForegroundWindow(p.MainWindowHandle);\n              Thread.Sleep(1000);\n              SendKeys.SendWait("quit");\n              Thread.Sleep(1000);\n              SendKeys.SendWait("{ENTER}");\n\n          }	0
22091720	22091548	Get the value of selected_item in longlistselector	string name = (listFavs.SelectedItem as Favs).Name;	0
1882239	1882231	String comparison equivalents	bool areSame = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);	0
27127121	27126754	Window closes immediately after being created (and shown) in a sepatarted thread	var thread = new Thread(() =>\n{\n    notificationPopUp = new NotificationPopUpView(unreadNotifications.First().session_s,unreadNotifications.First().secondry_msg);\n    notificationPopUp.Show();\n    Dispatcher.Run();\n});\nthread.SetApartmentState(ApartmentState.STA);\nthread.IsBackground = true;\nthread.Start();	0
3822913	58744	Best way to copy the entire contents of a directory in C#	//Now Create all of the directories\nforeach (string dirPath in Directory.GetDirectories(SourcePath, "*", \n    SearchOption.AllDirectories))\n    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));\n\n//Copy all the files & Replaces any files with the same name\nforeach (string newPath in Directory.GetFiles(SourcePath, "*.*", \n    SearchOption.AllDirectories))\n    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);	0
4580283	4573394	Change URL of WebBrowser in C#	Browser.Url = new System.Uri("https://www.pandora.com/", System.UriKind.Absolute);	0
9601314	9600309	xml elements in C# windows Phone 7	var urls =  xmlMovie\n    .Descendants("image")\n    .Where(x=>x.Attribute("size").Value=="cover")\n    .Select(x=>x.Attribute("url").Value)\n    .ToArray();	0
6446704	6443448	WPF Treeview in MVVM	public EquipmentViewModel(Services.IEquipmentService equipmentService)\n    {\n        EquipmentService = equipmentService;\n        LoadData();\n    }	0
14800153	14800120	How do you make an array of 1000 random integers between 1-100	int[] iArray = new int[1000];\nint counter = 0;\nRandom random = new Random();\nfor(int i = 0; i < 1000; i++){\n   iArray[i] = random.Next(1, 101); //1 - 100, including 100\n}\nint number = Convert.ToInt32(Console.ReadLine());\nforeach(int i in iArray){\n  if(i == number)count++;\n}\nConsole.WriteLine("The number "+ number+" appears "+count+" times!");	0
33762150	33641369	How can I add a bottom border to an Excel range in C#?	private void AddBottomBorder(int rowToBottomBorderize)\n{\n    var rowToBottomBorderizeRange = _xlSheet.Range[_xlSheet.Cells[rowToBottomBorderize, ITEMDESC_COL], _xlSheet.Cells[rowToBottomBorderize, TOTALS_COL]];\n    Borders border = rowToBottomBorderizeRange.Borders;\n    border[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;\n}	0
15038658	13178393	Selection of Points or Series in MS Chart	ChartArea _chartarea;\nSeries _data;\n\nprivate void Plot_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)\n    HitTestResult result = _plot.HitTest(e.X, e.Y);\n\n    if (result.ChartElementType == ChartElementType.DataPoint && result.ChartArea == _chartarea && result.Series == _data)\n    {\n        // A point is selected.\n    }\n}	0
1009880	1009857	c# Help joining textbox value, LIKE and a string variable	table.DefaultView.RowFilter = cmbBox.Text + " LIKE '%" + strName + "%'";	0
453398	190045	What's the best way to copy/fill a large array with a smaller array in C#?	for (int i = 0; i < destArray.Length; i++)\n{\n    destArray[i] = sourceArray[i%sourceArray.Length];\n}	0
11617220	11617117	Linq ordering by number on file name	if (Directory.Exists(path))\n{\n    var directoryInfo = new DirectoryInfo(path);\n    var files = from file in directoryInfo.EnumerateFiles()\n\n    .Where(f => f.Extension == PAGE_FILE_EXTENSION)\n                orderby int.Parse(file.Name.Substring(1, file.Name.IndexOf('.')-1)) ascending\n                select file.FullName;\n\n    return files.ToArray<string>();\n}	0
1622513	1622502	How do I access an Access database protected by a username/password in Access workgroups via Jet?	"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbFile +\n";Jet OLEDB:System Database=" + Path.GetDirectoryName(mdbFile) + "\\system.mdw;" +\n"User ID=***;Password=***";	0
3111896	3111868	How can I obtain the group of "dirty" rows or cells from a DataGridview?	DataTable.GetChanges()	0
17894042	17894036	C# switch statement validation	bool condition = false;\n\nConsole.WriteLine("Please enter a or b");\nstring str = string.Empty;\nwhile (!condition)\n{\n     str = Console.ReadLine().ToLower();\n     switch (str)\n     {\n         case "a":\n             //some code here\n             condition = true;\n             break;\n         case "b":\n             //some code here\n             condition = true;\n             break;\n         default:\n             Console.WriteLine("Error, enter a or b");\n             break;\n     }\n }\n Console.WriteLine("You have entered {0} ", str);\n Console.ReadLine();	0
8170810	8170739	Dealing with invalid XML hexadecimal characters	byte[] toEncodeAsBytes\n            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);\n      string returnValue\n            = System.Convert.ToBase64String(toEncodeAsBytes);	0
6807903	6807834	c# Get all enum values greater than a given value?	private IEnumerable<RoleName> AllAllowedRoles(RoleName level)\n    {\n        return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);\n    }	0
20239672	20236418	sql case statement in where clause in linq	string[] arr = new string[] {"008","-1"};\n\nstring ClientID = HttpContext.Current.Session["ClientID"].ToString();\n\n&& (\n                                ClientID == "008"\n                             ? (t.external_org == null \n                                               ? d.clientid =="008" : 1 == 1)\n                                               || (arr.Contains(t.external_org))\n\n\n                                : ClientID == "006"\n                             ? (t.external_org == null\n                                               ? d.clientid == ClientID : 1 == 1)\n                                               || (t.external_org != "008")\n\n                        : d.clientid == ClientID\n                            )	0
12791164	12791141	Regex to Replace the end of the Url	var regex = new Regex(@"_\d+\.JPG");\nvar newUrl = regex.Replace(url, "_14.JPG");	0
13280318	13280294	Retrieving the unclosed type of a generic type closing a generic type	var unclosedTyped = type.GetGenericTypeDefinition();	0
793669	793634	Globalization with NHibernate	class Product\n{\n  string LocalizedName \n  { \n    get { return AllProductNames[Thread.CurrentThread.CurrentCulture.LCID]; }\n  }\n\n  IDictionary<int, string> AllProductNames { get; private set; }\n}	0
5180779	5180685	Get coordinates after rotation	public Point RotatePoint(float angle, Point pt) { \n   var a = angle * System.Math.PI / 180.0;\n   float cosa = Math.Cos(a), sina = Math.Sin(a);\n   return new Point(pt.X * cosa - pt.Y * sina, pt.X * sina + pt.Y * cosa);\n}	0
20212749	20212457	Encoding from Arabic to Western European	//Assuming that the value existing in string. \nstring _Value=string.Empty;\nbyte[] enBuff= Encoding.GetEncoding("windows-1256").GetBytes(_Value);\n_Value= Encoding.GetEncoding("windows-1252").GetString(enBuff);	0
4644729	4644703	Single quote handling in a SQL string	var command = new SqlCommand("select * from person where firstname = @firstname");\nSqlParameter param  = new SqlParameter();\nparam.ParameterName = "@firstname";\nparam.Value         = "testing12'3";\ncommand.Parameters.Add(param);	0
9970323	9970207	how to let a minimized form to notify user to open it from taskbar?	[DllImport("user32.dll")]\nprivate static extern bool FlashWindowEx(ref FLASHWINFO pwfi);	0
12603132	12601426	MDI children show the ContextMenu assigned to their MDI parent	void button1_Click(object sender, EventArgs e) {\n  Form2 f2 = new Form2();\n  f2.MdiParent = this;\n  f2.ContextMenuStrip = new ContextMenuStrip();\n  f2.Show();\n}	0
24271024	24270422	Deleting multiple rows based on where clause using FluentMigrator	const string cascadeDeleteScript = \n@"DELETE FROM PaymentHistory WHERE PaymentId IN \n              (SELECT Id FROM Payment WHERE PaymentStatusCode = 'Processing') ";\nExecute.Sql(cascadeDeleteScript);	0
19131490	19125529	Office 365 Sharepoint Upload Files to Documents Library	using(ClientContext context = new ClientContext("http://yourURL"))\n{\nWeb web = context.Web;\nFileCreationInformation newFile = new FileCreationInformation();\nnewFile.Content = System.IO.File.ReadAllBytes(@"C:\myfile.txt");\nnewFile.Url = "file uploaded via client OM.txt";\nList docs = web.Lists.GetByTitle("Documents");\nMicrosoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);   \ncontext.ExecuteQuery();\n}	0
9025784	9025511	XmlSerializer - linq-to-sql - A circular reference was detected while serializing an object of type	public class Object1\n{\n    public Object2 SecondObject { get; set; } \n}\n\n\npublic class Object2\n{\n    public Object1 FirstObject { get; set; } \n}	0
34153594	34148896	Creating Xml Dynamically From Object	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string name = "gopi";\n            string lastname = "ch";\n            string graduation = "b.tech";\n            string designation = "Engineer";\n\n            XElement personalData = new XElement("person", new XElement[] {\n                new XElement("personaldata", new XElement[] {\n                    new XElement("name", name),\n                    new XElement("lastname", lastname)\n                }),\n                new XElement("Educationadata", new XElement[] {\n                    new XElement("Graduation", graduation),\n                    new XElement("designation", designation)\n                })\n            });\n\n        }\n    }\n}\n???	0
2305871	2305857	Creating Active Directory user with password in C#	using(var pc = new PrincipalContext(ContextType.Domain))\n{\n  using(var up = new UserPrincipal(pc))\n  {\n    up.SamAccountName = username;\n    up.EmailAddress = email;\n    up.SetPassword(password);\n    up.Enabled = true;\n    up.ExpirePasswordNow();\n    up.Save();\n  }\n}	0
222935	222897	Extend a LINQ entity-class with constructor methods and make that entity-class inherit from it's DataContext class	namespace Xxx.Entities\n{\n  public partial class User : IDisposable\n   { DataContext ctx;\n\n     public static GetUserByID(int userID)\n      {  var ctx  = new DataContext();\n         var user = ctx.Users.FirstOrDefault(u=>u.UsersID == userID);\n\n         if (user == null)\n          {\n             user = new User();\n             ctx.Users.InsertOnSubmit(user);\n          }\n\n         user.ctx = ctx;\n         return user;          \n      }      \n\n     public void Dispose() { if (ctx != null) ctx.Dispose(); }\n   }\n}	0
4527129	4527098	How to access a web service using a proxy in c#	var proxy = new WebProxy("proxy.example.com", 8080)\n{\n    Credentials = new NetworkCredential("login", "password") // optional\n};\n\nvar request = new WebRequest\n{\n    Proxy = proxy // optional. if null - request goes without proxy, obviously\n};\n\nvar response = request.GetResponse();	0
1234155	1234089	How can I use ?? to combine these two lines into one?	string lastNameDisplay = (string)xml.Element("lastName").Attribute("display") ?? "NONE";	0
5599409	5598829	How to properly parse this xml response	select\n    exprn.val\n,   exchn.val\n,   askn.val\nFROM \n(select expr.e.value('.', 'VARCHAR(3)') as val, row_number() over(order by expr.e) n from @xml.nodes('/RESPONSE/EXPR') expr(e)) exprn\n\njoin (select exch.e.value('.', 'VARCHAR(3)') as val, row_number() over(order by exch.e) n from @xml.nodes('/RESPONSE/EXCH') exch(e)) exchn on exchn.n = exprn.n\n\njoin (select ask.a.value('.', 'MONEY') as val, row_number() over(order by ask.a) n from @xml.nodes('/RESPONSE/CONVERSION/ASK') ask(a)) askn on askn.n = exprn.n	0
20646849	20646715	How can I call a Web API Post method?	var webResponse = (HttpWebResponse)webRequest.GetResponse();	0
7461848	5868493	How can I send an ASP.NET table as an Email message not as an attachment?	//Here I extract html of the control to be sent\nStringWriter stringWrite = new StringWriter();\nSystem.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);\n//pnlRpt is an asp.net panel containing the controls to be sent\npnlRpt.RenderControl(htmlWrite);\nstring htmlStr = stringWrite.ToString();\n\n//Here I send the message whith the html of the table\nMailMessage msg = new MailMessage();\nmsg.From = new MailAddress("EmailOfSender");\nmsg.To.Add("emailOfReceiver");\nmsg.Subject = "your subject";\nmsg.Body = htmlStr;\nmsg.IsBodyHtml = true;\nSmtpClient smtp = new SmtpClient(mailServer);\nsmtp.Credentials = new System.Net.NetworkCredential(userName, usePass);\nsmtp.Send(msg);\nmsg.Dispose();	0
32123049	32122418	Find Dynamics Contact Entity by value of field in C#	QueryByAttribute query = new QueryByAttribute("contact");\nquery.ColumnSet = new ColumnSet("fullname", "emailaddress1");\nquery.Attributes.AddRange("emailaddress1");\nquery.Values.AddRange("test@test.com");\nEntityCollection retrieved = service.RetrieveMultiple(query);	0
16501028	16500868	Disabling a button in C# WITHOUT setting btn.Enabled = false;?	void HandleClick(object sender, EventArgs e)\n{\n    ((Button)sender).Click -= HandleClick;\n\n    // Handle the click  \n}	0
12912751	12912632	Need to replace href of anchor tags in a string	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(content);\nforeach (var a in doc.DocumentNode.Descendants("a"))\n{\n    a.Attributes["href"].Value = "http://a.com?url=" + HttpUtility.UrlEncode(a.Attributes["href"].Value);\n}\n\nvar newContent = doc.DocumentNode.OuterHtml;	0
9032705	9023422	Getting OAuth access token for Google Plus API	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        string address =\n            "https://foursquare.com/oauth2/authenticate" +\n            "?client_id=" + CLIENT_ID +\n            "&response_type=token" +\n            "&redirect_uri=" + CALLBACK_URI;\n        webBrowser1.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser1_Navigated);\n        webBrowser1.Navigate(new Uri(address, UriKind.Absolute));\n    }\n\n    void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)\n    {\n        response = e.Uri.ToString();\n        System.Diagnostics.Debug.WriteLine(e.Uri.ToString());\n        if (response.LastIndexOf("access_token=") != -1)\n        {\n            string token = response.Substring(response.LastIndexOf("#access_token=") + "#access_token=".Length);\n            System.Diagnostics.Debug.WriteLine("TOKEN: " + token);\n        }\n    }	0
17727596	17679764	How to create a "non-dynamic" Guid as value for a database entry?	public class MyModel\n{\n    private Guid myGuid;\n\n    public MyModel()\n    {\n        myGuid = Guid.NewGuid();\n    }\n\n    public MyModel(Guid guid)\n    {\n        myGuid = guid;\n    }\n\n    public Guid MyGuid\n    {\n        get { return myGuid; }\n        set { myGuid = value; }\n    }\n}	0
21476539	21476240	how to display an image from web service	public class Newss\n        {\n            public string News_Title { get; set; }\n            public string News_Description { get; set; }\n            public string Date_Start { get; set; }\n            **//Edits**\n            public string image_path {get;set}\n            public BitmapImage ImageBind{get;set;}\n        }\n     foreach (var location in doc.Descendants("UserDetails"))\n           {\n                Newss data = new Newss();\n                data.News_Title = location.Element("News_Title").Value;\n                data.Date_Start = location.Element("Date_Start").Value;\n                **//Edits**\n                data.image_path = location.Element("Image_Path").Value;\n                data.ImageBind = new BitmapImage(new Uri( @"http://political-leader.vzons.com/ArvindKejriwal/images/uploaded/"+data.image_path, UriKind.Absolute)\n                listData.Add(data);\n            }\n\n**Your xaml changes**\n\n    <Image Source="{Binding ImageBind }" />	0
18696504	18696363	How to get number of properties in System.Tuple, c#?	var v = new Tuple<int, int, int>(1, 2, 3);\nvar count = v.GetType().GenericTypeArguments.Length;	0
1479773	1479765	Should I put validation logic in a POCO?	public class Name\n{\n    [Required]\n    public string FirstName { get; set; }\n    [Required]\n    public string LastName { get; set; }\n}	0
17614611	17613494	Load another window in background; when rendered, close the parent window	InitWindow I = null;\n    Thread C = null;  \n\n    public InitWindow()\n    {\n        InitializeComponent();\n        I = this;\n        C = Thread.CurrentThread;  \n\n        Thread T = new Thread(() =>\n        {\n            MainWindow M = new MainWindow();\n            M.Show();\n            M.ContentRendered += M_ContentRendered;\n            System.Windows.Threading.Dispatcher.Run();\n            M.Closed += (s, e) => M.Dispatcher.InvokeShutdown();\n\n        }) { IsBackground = true, Priority = ThreadPriority.Lowest };\n\n        T.SetApartmentState(ApartmentState.STA);\n        T.Start();\n    }\n\n    void M_ContentRendered(object sender, EventArgs e)\n    {\n        // Making the parent thread background\n        C.IsBackground = true; \n        // foreground the current thread\n        Thread.CurrentThread.IsBackground = false;\n        // Abort the parent thread\n        C.Abort();\n    }	0
7555010	7553919	Clear hash and parameters from Redirect in aspnet mvc?	#/?tab=Foo	0
16652775	16652306	C# Update Database for every Item in listBox	string kat1 = "aaaaa";\n    cmd.CommandText = "UPDATE Table2 SET kat_aitisis=@kat WHERE aitisi_ID=@id";\n    cmd.Parameters.AddWithValue("@kat", kat1);\n    cmd.Parameters.AddWithValue("@id", 0);\n    cn.Open();\n    for (int i = 0; i < listBox1.Items.Count; i++)\n    {\n        cmd.Parameters["@id"].Value = Convert.ToInt32(listBox1.Items[i]));\n        cmd.ExecuteNonQuery();\n    }  \n    cn.Close();	0
20741457	20706162	Interop - put a blank line between pasted tables in Word	oWord.Selection.TypeParagraph();	0
2290653	2273322	Easiest way to find free IPAddress in current subnet?	public static IPAddress FindNextFree(this IPAddress address)\n    {\n        IPAddress workingAddress = address;\n        Ping pingSender = new Ping();\n\n        while (true)\n        {\n            byte[] localBytes = workingAddress.GetAddressBytes();\n\n            localBytes[3]++;\n            if (localBytes[3] > 254)\n                localBytes[3] = 1;\n\n            workingAddress = new IPAddress(localBytes);\n\n            if (workingAddress.Equals(address))\n                throw new TimeoutException("Could not find free IP address");\n\n            PingReply reply = pingSender.Send(workingAddress, 1000);\n            if (reply.Status != IPStatus.Success)\n            {\n                return workingAddress;\n            }\n        }\n    }	0
2700492	2700450	C# property exactly the same, defined in two places	public static DateTime GetSubmitDateAsDate(this IDefectProperties defectProperties) {\n    return DateTime.Parse(defectProperties.SubmitDate);\n}\n\npublic static void SetSubmitDateAsDate(this IDefectProperties defectProperties, DateTime dateTime) {\n    defectProperties.SubmitDate = dateTime.ToString();\n}	0
18214680	18214491	c# loop with httpclientconnection	string reportfilename = @"D:\Reports\AllActiveAccounts_" + month.ToString("MMyyyy") + "_" + cust[i, 0] + "." + cust[i, 4];	0
16577833	16577721	How can I add to a predefined method?	public static class ClassNameExtension\n{\n    // must have different signature to prevent memory exception\n    public static string MethodToOverid(this ClassName class, List<T> tochange)\n    {\n        tochange.add(class)\n        class.originalmethod()\n    }\n}	0
17707648	17707357	post JSON to asp.net page	function encode_utf8(s) {\n  return unescape(encodeURIComponent(s));\n}	0
1198480	1198457	c# dragdrop from listview control	string MyFilePath = @"C:\Documents and Settings\All Users\Temp\TempFile.txt";\n\nlistView.DoDragDrop(new DataObject(DataFormats.FileDrop, MyFilePath) , DragDropEffects.Copy);	0
13324264	13323643	Invalid object name 'Users' when reading from Users table	Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db_74.mdf;Integrated Security=True;User Instance=True	0
10244265	10243814	How to get complete URL of browser in UrlRewriting using C#	Request.Url.GetLeftPart(UriPartial.Authority)	0
11680974	11680912	How to find the location of a string in a text file	string[] lines = System.IO.File.ReadAllLines(@"C:\file.txt");\n\nint count = 0;\nforeach (string line in lines)\n{\n    count++;\n    if (line.indexOf("I'm a string") > -1) {\n       // found it\n    }    \n\n}	0
5559487	5559127	CSV column data is being truncated	Jet OLEDB 4.0	0
24868645	24868230	Update Sql Table from a Dataset using C#	private static bool UploadDataSet(DataSet ds)\n    {\n        try\n        {\n            SqlBulkCopy bulkCopy = new SqlBulkCopy(AzureSqlConnection, SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.UseInternalTransaction, null);\n            bulkCopy.DestinationTableName = ds.Tables[0].TableName;\n            bulkCopy.WriteToServer(ds.Tables[0]);\n            Log.LogWriter(string.Format("Updating data in table {0}", ds.Tables[0].TableName), "Success");\n            return true;\n        }\n        catch (Exception ex)\n        {\n            Log.LogWriter(string.Format("Failed to update table {0}. Error {1}", ds.Tables[0].TableName, ex), "Failed");\n            throw;\n        }\n    }	0
29427606	29207028	EF code generation: How to get a System enum to work as an EdmEnumType?	namespace Model {\n  [System.Data.Objects.DataClasses.EdmEnumTypeAttribute(Name = "Enum1", NamespaceName = "Model")]\n  [System.Runtime.Serialization.DataContract()]\n  public enum Enum1 {\n    [System.Runtime.Serialization.EnumMember()]\n    a,\n    [System.Runtime.Serialization.EnumMember()]\n    b\n  };\n}	0
21675750	21675403	How to add date in dd/MM/yyyy to mysql in asp.net?	string strText=TextBox1.Text\nstring qryStr = string.Format("{0:yyyy/MM/dd HH:mm:ss}", Convert.ToDateTime(strText));\nstring cmdText = "INSERT INTO trydate(Dob) VALUES ('" + qryStr + "')";	0
20302087	20302048	Difficulty comparing differences in DateTimes	if (!lastActivate.HasValue || (DateTime.Now - lastActivate.Value).TotalSeconds > 1)\n{\n    //stuff\n}	0
8948089	8947410	Using Settings.settings in a windows WPF app (vs2010)	public partial class App : Application \n{\n    public App()\n    { \n        string userName= StrainTracker.Properties.Settings.Default.User;\n        StrainTracker.Properties.Settings.Default.User = "SomethingSilly";\n        StrainTracker.Properties.Settings.Default.Save();\n    }\n}	0
22430290	22429969	Create an instance of a custom generic class and a type stored in file as String	Type typeArgument = Type.GetType(typestring);\nType constructed = typeof(MyClass<>).MakeGenericType(typeArgument);\nobject instance = Activator.CreateInstance(constructed);	0
8565442	8565413	How to access a private base class field using Reflection	class B\n    {\n        public int MyProperty { get; set; }\n    }\n\n    class C : B\n    {\n        public string MyProperty2 { get; set; }\n    }\n\n    static void Main(string[] args)\n    {\n        PropertyInfo[] info = new C().GetType().GetProperties();\n        foreach (PropertyInfo pi in info)\n        {\n            Console.WriteLine(pi.Name);\n        }\n    }	0
6984742	6979520	Is there a Monotouch port available for the C# Facebook Sdk?	var client = new FacebookClient();\nvar me = (IDictionary<string,object>)client.Get("me");\nstring firstName = (string)me["first_name"];\nstring lastName = (string)me["last_name"];\nstring email = (string)me["email"];	0
33983624	33983320	Select from a table with Entity Framework	List<int> groupIds = ...;\nvar query = db.Persons\n    .Where(p => p.PersonGroups.Any(pg => groupIds.Contains(pg.GroupID.Value));	0
5534654	5534602	WPF: Convert ImageSource to Stream	var uri = new Uri("/ReferencedAssembly;component/default.png", UriKind.Relative);\nvar streamInfo = System.Windows.Application.GetResourceStream(uri);\nvar stream = streamInfo.Stream;	0
23567900	23560089	How to prevent _loosing_ indentation (WhiteSpaceTrivia) when rewriting identifier name with CSharpSyntaxRewriter using Roslyn	name = name\n       .WithIdentifier(SyntaxFactory.Identifier(GetChangedName(name.Identifier.ValueText)))\n       .WithLeadingTrivia(name.GetLeadingTrivia())\n       .WithTrailingTrivia(name.GetTrailingTrivia());	0
15678814	15656112	How do I get tweets based on location only?	GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fsearch%2Ftweets.json\n&geocode%3D37.781157%252C-122.398720%252C1mi\n%26oauth_consumer_key%3D...\n%26oauth_nonce%3DToul8\n%26oauth_signature_method%3DHMAC-SHA1\n%26oauth_timestamp%3D1364420628\n%26oauth_token%3D...\n%26oauth_version%3D1.0\n%26q%3D	0
9135603	9135259	TabControl tab buttons location	foreach (thing in your ArrayList)\n{\n     TabPage tabPage = new TabPage("Name of tab");            // Add a new tab page\n     RichTextBox rtb = new System.Windows.Forms.RichTextBox();//RTF box\n     TextBox tb = new System.Windows.Forms.TextBox();         //Text box\n\n     //Set up size, position and properties\n     rtb.LoadFile("some/Path/to/a/file");\n\n     //set up size, position of properties\n     tb.Text = "Some text I want to display";\n\n     tabPage.Controls.Add(rtb); //Add both boxes to that tab\n     tabPage.Controls.Add(tb);\n\n     tabControl1.TabPages.Add(tabPage); //Add that page to the tab control\n}	0
30022249	30020928	DataRowView object getting null value at time of getting value from DataGrid	private void _gvDoctorVisit_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n{\n    int visitid = ((dynamic)_gvDoctorVisit.SelectedItem).visit_id;\n    MessageBox.Show(visitid.ToString());\n}	0
22434376	22434211	How to replace characters from one file with characters from another	class Program\n{\n    static void Main(string[] args)\n    {\n\n        string[] words = new string[] { "WordOne", "WordTwo", "WordThree", "WordFour" };\n        string[] clues = new string[] { "ClueOne", "ClueTwo", "ClueThree", "ClueFour" };\n\n        foreach (string word in words)\n        {\n            Console.WriteLine("Current word is " + word);\n        }\n\n        Console.WriteLine();\n\n        foreach (string clue in clues)\n        {\n            Console.WriteLine("Current clue is " + clue);\n        }\n\n        Console.WriteLine();\n\n        for (int i = 0; i < words.Length; i++)\n        {\n            for (int j = 0; j < clues.Length; j++)\n            {\n                words[i] = words[i].Replace(words[i], clues[j]);\n            }\n        }\n\n        foreach (string newWord in words)\n        {\n            Console.WriteLine("New Word is now " + newWord);\n        }\n\n        Console.Read();\n    }\n}	0
19600990	19552213	How do I add multiple email addresses?	string[] smtp = { "SMTP:" + textBox6.Text, 9 + "smtp:" + textBox4.Text + "@sscincorporated.com" };\n     command2.AddParameter("EmailAddresses", smtp);	0
12680454	12680341	how to get both fields and properties in single call via reflection?	const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;\nMemberInfo[] members = type.GetFields(bindingFlags).Cast<MemberInfo>()\n    .Concat(type.GetProperties(bindingFlags)).ToArray();	0
5234067	5233886	Show data sent to WCF in windows form	public class MonitoringData : IMonitoringData\n{\n   public void DoWork(string message)\n   {\n\n       Form1 monitorForm = (Form1)System.Windows.Forms.Application.OpenForms[0];\n       monitorForm.WriteMessage(message);            \n   }\n}	0
14356355	14356127	How to convert a List<string>() to Dictionary<string,string>() using LINQ in C#	List<string> lines = File.ReadAllLines(@"C:\Text.txt").ToList();\nlines =\n  lines.Select(x => x.Split('='))\n  .GroupBy(a => a[0])\n  .OrderBy(g => g.Key)\n  .Select(g => g.Key + "=" + g.First()[1])\n  .ToList();	0
8754747	8733846	How to show a view in a datagrid?	public IEnumerable<Object> Query { get { return query; } }	0
24734123	24732549	How to Give back a DataGridView in Winforms	public partial class ManualEntry : Form\n{\n    private Data DataViewData;\n    private DataGridView DataView;\n    private Point DataViewLocation;\n    private Control DataViewParent;\n\n    public ManualEntry(DataGridView ExcelDisplay, Data data)\n    {\n        InitializeComponent();\n        this.DataViewData = data;\n        this.DataView = ExcelDisplay;\n        this.DataViewLocation = ExcelDisplay.Location;\n        this.DataViewParent = ExcelDisplay.Parent;\n        this.DataView.Parent = this;\n        // etc...\n    }\n\n    protected override void OnFormClosing(FormClosingEventArgs e) {\n        base.OnFormClosing(e);\n        if (!e.Cancel) {\n            DataView.Parent = this.DataViewParent;\n            DataView.Location = this.DataViewLocation;\n            // etc..\n        }\n    }\n}	0
13103558	13103270	Issue parsing JSON with ServiceStack.Text	var weather = ServiceStack.Text.JsonSerializer.DeserializeFromString<RootWeather>(content);\n\n\npublic class RootWeather\n{\n    public Weather data { get; set; }\n\n}\n\npublic class Weather\n{\n    public List<NearestArea> nearest_area { get; set; }\n\n}\n\npublic class NearestArea\n{\n    public string latitude { get; set; }\n    public string longitude { get; set; }\n    public string distance_miles { get; set; }\n}	0
1197050	1196714	Empty a DataGridView	custDataGridView.DataSource = null;	0
30764179	30763898	Removing a node from a LinkedList (C#)	public void Delete(string value)\n{\n    if (head == null) return;\n\n    if (head.Value == value)\n    {\n        head = head.Next;\n        return;\n    }\n\n    var n = head;\n    while (n.Next != null)\n    {\n        if (n.Next.Value == value)\n        {\n            n.Next = n.Next.Next;\n            return;\n        }\n\n        n = n.Next;\n    }\n}	0
24448276	24447469	How to draw only selected borders on a control	protected override void OnPaint(PaintEventArgs e)\n{\n  base.OnPaint(e);\n  ControlPaint.DrawBorder(e.Graphics, ClientRectangle,\n                            Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,\n                            Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,\n                            Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset,\n                            Color.Black, BORDER_SIZE, ButtonBorderStyle.Inset);\n}	0
18211655	18210941	How to Get WebGetAttribute from MethodInfo Using Reflection	IEnumerable<object> attrs = \n     typeof(Data).GetMethods(BindingFlags.Public|BindingFlags.NonPublic)\n      .SelectMany(a => a.GetCustomAttributes(typeof(WebInvokeAttribute),true));  \n\nWebInvokeAttribute wi = attrs.First() as WebInvokeAttribute ;	0
3546201	3544877	How do I send email to a dropfolder in asp.net?	SmtpClient client = new SmtpClient();\nclient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;\nclient.PickupDirectoryLocation = "C:\DropFolder";	0
16035084	16034985	How to remove spaces from string?	var result = new Regex("\s{2,}").Replace(text,constForWhiteSpace)	0
4046976	4046769	How to programatically create button on Excel worksheet in C#?	Public Sub Test()\n\nDim btn As Shape\n\nSet btn = Sheets("Sheet1").Shapes.AddOLEObject("Forms.CommandButton.1", , , , , , , 1, 1, 100, 100)\n\nEnd Sub	0
5356889	5356862	SqlParameter with default value set to 0 doesn't work as expected	Parameter = new SqlParameter("@pname", Convert.ToInt32(0));	0
20878705	20878483	Confusion about lambda syntax	IEnumerable<product> result = p.Where((item) => item.fiyat > 1000);	0
20441913	20441884	how do i clear a whole column of records in Microsoft access?	string myQuery1 = "Update AnswerTable SET Points=0";	0
10317505	10317349	Handle many tasks, many times with Task Parallel	Task.Factory.StartNew(() => DoSomeWork());	0
16033146	16017392	Select parameter less constructor with MEF conventions	registration.ForTypesDerivedFrom<TestStepResult>()\n   .Export<TestStepResult>()\n   .SelectConstructor(ctorInfos => \n                      {\n                          var parameterLessCtor = ctorInfos.FirstOrDefault(ci => ci.GetParameters().Length == 0);\n                          if (parameterLessCtor != null)\n                              return parameterLessCtor;\n                          else\n                              return ctorInfos.First();\n                      });	0
2337192	2336991	In Winforms, how do you pass the datagridview row right-clicked on to the ContextMenuStrip?	int id = (int)YourGridViewName.SelectedCells[0].Value;	0
24887318	24886947	Workaround for new() constraint with parameters in generics	new T()	0
17138972	17138749	How to manually validate a model with attributes?	var context = new ValidationContext(u, serviceProvider: null, items: null);\nvar validationResults = new List<ValidationResult>();\n\nbool isValid = Validator.TryValidateObject(u, context, validationResults, true);	0
10421935	10402770	Observable Network IO Parsing	messages\n    .Scan(String.Empty, (a, b) => (a.EndsWith("\r\n") ? "" : a) + b)\n    .Where(x => x.EndsWith("\r\n"))	0
9040754	9040620	How to marshal an Exception to an IntPtr in C#	Dictionary<int, Exception>	0
28488314	28455040	Get Current Value of RibbonSpinEditItem	spin.PropertiesSpinEdit.ClientSideEvents.ValueChanged = "function(s,e) { alert(s.GetValue()); }";	0
6690548	6690501	How do write a generic function that takes a datarow and fill an object's properties?	namespace MyNamespace.Data\n{\n    class Converter\n    {\n        public static void Fill(object LogicObject, DataRow Row)\n        {\n            Dictionary<string, PropertyInfo> props = new Dictionary<string,PropertyInfo>();\n            foreach (PropertyInfo p in LogicObject.GetType().GetProperties())\n                props.Add(p.Name, p);\n            foreach (DataColumn col in Row.Table.Columns)\n            {\n                string name = col.ColumnName;\n                if (Row[name] != DBNull.Value && props.ContainsKey(name))\n                {\n                    object item = Row[name];\n                    PropertyInfo p = props[name];\n                    if (p.PropertyType != col.DataType)\n                        item = Convert.ChangeType(item, p.PropertyType);\n                    p.SetValue(LogicObject, item, null);\n                }\n            }\n\n        }\n    }\n}	0
8068258	8065363	sending email from app do domain different from com	System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry("noncom.de");\nif(host.AddressList.Length > 0)\n    Response.Write(host.AddressList[0].ToString());\nelse\n    Response.Write("Nope");	0
10241148	10240957	how to copy a file from any directory to c drive using cmd in c#	Process p = new Process();\n        p.StartInfo.FileName = "cmd.exe";\n        p.StartInfo.Verb = "runas";\n        p.StartInfo.UseShellExecute = false;\n        p.StartInfo.RedirectStandardInput = true;\n        p.Start();\n\n        p.StandardInput.WriteLine(@"/c xcopy d:\123.png C:\windows\system32");	0
28482315	28480979	Concatenate all of the items under `JobDestination` in list produced	List<JobComponent.JobList> waypoints = JobComponent.GetWaypoints(jobId);\nstring s = string.Join(",", waypoints.Select(i => i.JobWaypoints));	0
30110180	30038449	Set Timeout in WCF via Reflection	var timeOut=new TimeSpan(0, 10, 0);\n            int timeOutInt = 2147483647;\n            PropertyInfo channelFactoryProperty = proxyInstance.GetType().GetProperty("ChannelFactory");\n\n        if (channelFactoryProperty == null)\n        {\n            throw new InvalidOperationException("There is no ''ChannelFactory'' property on the DomainClient.");\n        }\n        ChannelFactory factory = (ChannelFactory)channelFactoryProperty.GetValue(proxyInstance, null);\n        factory.Endpoint.Binding.SendTimeout = timeOut;\n        factory.Endpoint.Binding.OpenTimeout =  timeOut;\n        factory.Endpoint.Binding.ReceiveTimeout = timeOut;\n        factory.Endpoint.Binding.CloseTimeout = timeOut;\n\n        BasicHttpBinding _binding = (BasicHttpBinding)factory.Endpoint.Binding;\n        _binding.MaxBufferPoolSize = timeOutInt;\n        _binding.MaxBufferSize = timeOutInt;\n        _binding.MaxReceivedMessageSize = timeOutInt;\n        _binding.OpenTimeout = timeOut;	0
16920197	16920027	Looping over XAML defined labels	var numberOfLabels = 40;\n\nfor(int i = 1; i <= numberOfLabels; i++)\n{\n    var labelName = string.Format("label{0}", i);\n    var label = (Label) this.FindName(labelName);\n    label.Content = i * 10;\n}	0
32881739	32878179	Unable to upload a file SFTP using SSH.NET in C# - Permission Denied	client.UploadFile(fileStream, "/home/user/" + f.Name, null);	0
21365165	21365038	C# Check all items except the first one in all listview groups	int i;\nforeach (ListViewGroup grp in listFiles.Groups)\n{\n   i = 0;\n   foreach (ListViewItem item in grp.Items)\n   {\n      if (i != 0)\n         item.Checked = true;\n\n      i++;\n   }\n}	0
22439620	22439515	Getting data from textboxes and multiply	double.TryParse(textBox1,NumberStyles.AllowDecimalPoint,\n                                 CultureInfo.InvariantCulture, out curr);\ndouble.TryParse(textBox2.Text,NumberStyles.AllowDecimalPoint,\n                                 CultureInfo.InvariantCulture, out price);\nmultiply = curr * price;	0
11297007	11296938	How to pass a variable in the query below	in order to initialize your value request.Title\n\nlet request = your treatment... (request is local variable of your query)	0
3594305	3592992	How do I determine an MDI child form's screen location?	private void button1_Click(object sender, EventArgs e) {\n        if (this.MdiParent != null) {\n            MdiClient client = null;\n            foreach (Control ctl in this.MdiParent.Controls) {\n                if (ctl is MdiClient) { client = ctl as MdiClient; break; }\n            }\n            this.WindowState = FormWindowState.Normal;\n            Point loc = client.PointToScreen(this.Location);\n            this.MdiParent = null;\n            this.Location = loc;\n        }\n    }	0
12102333	12101895	Sorting a number without the first character using OrderBy query while performing a database search	customerlist = db.Customers\n    .Where(u => (u.Cust_ID+u.Given_Name+u.Surname).Contains(searchstring))\n    .AsEnumerable()  //EDIT: was ToArray()\n    .OrderBy(u => Int32.Parse(u.Cust_ID.SubString(1)))\n    .ToList();	0
20611362	20609849	How to get the data from one gridview to another gridview in windows form application?	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n        {\n            int selectedIndex=dataGridView1.SelectedRows[0].Index;\n            CopyColumns();          \n            for (int i = 0; i < dataGridView1.Columns.Count; i++)\n                dataGridView2.Rows[0].Cells[i].Value = dataGridView1.Rows[selectedIndex].Cells[i].Value;\n        }\n\n        void CopyColumns()\n        {\n            for (int i = 0; i < dataGridView1.Columns.Count; i++)\n                dataGridView2.Columns.Add(i.ToString(),dataGridView1.Columns[i].HeaderText);\n        }	0
10502424	10502217	Getting attributes values in another class	MemberInfo[] members = builder.GetType().GetProperties();\n        foreach (MemberInfo m in members)\n        {\n            if (m.MemberType == MemberTypes.Property)\n            {\n                PropertyInfo p = m as PropertyInfo;\n                object[] attribs = p.GetCustomAttributes(false);\n                foreach (object attr in attribs)\n                {\n                    IssuerDesigner d = attr as IssuerDesigner;\n                    if (d != null)\n                    {\n\n                        foreach(object obj in d.Issuer)\n                        {\n                             DoSomething(obj);\n                        }\n                    }\n                }\n            }\n        }	0
1767441	1767418	Change text of a linkbutton in a repeater	protected void MyLinkButton_OnClick(object sender, EventArgs e)\n{\n    LinkButton b = sender as LinkButton;\n    b.Text = "Some Text";\n}	0
13023360	13023298	Inability to create a database in C# Visual Studio	"is on a network path that is not supported for database files"	0
3562590	3561610	is a background worker in a controller async?	public virtual void BlahAsync()\n{\n    AsyncManager.OutstandingOperations.Increment();\n    var service = new SomeWebService();\n    service.GetBlahCompleted += (sender, e) =>\n        {\n            AsyncManager.Parameters["blahs"] = e.Result;\n            AsyncManager.OutstandingOperations.Decrement();\n        };\n    service.GetBlahAsync();\n}\n\npublic virtual ActionResult BlahCompleted(Blah[] blahs)\n{\n    this.ViewData.Model = blahs;\n    return this.View();\n}	0
898279	898247	How to open a different project from current project using threads or processes in C#.?	System.Diagnostics.Process.Start(filename);	0
5591718	5591673	How to make a Close button in a form disabled	[DllImport("user32.dll")]\nprivate static extern int GetSystemMenu(int hwnd, int revert);\n\n[DllImport("user32.dll")]\nprivate static extern int GetMenuItemCount(int menu);\n\n[DllImport("user32.dll")]\nprivate static extern int RemoveMenu(int menu, int position, int flags);\n\nprivate void DisableCloseButton()\n{\n   int menu = GetSystemMenu(Handle.ToInt32(), 0);\n   int count = GetMenuItemCount(menu);\n   RemoveMenu(menu, count - 1, MF_DISABLED | MF_BYPOSITION);\n}	0
14739416	14739282	c# print function hide window	PrintDocument printDocument = new PrintDocument();\nPrintController printController = new StandardPrintController();\nprintDocument.PrintController = printController;	0
4813703	4813634	Getting one data from another table in DropownList with AutoPostBack	string selectedName = DropDownList1.SelectedValue;\n\n string sqlQuery = "select A.CustomerNumber from Customer A, Sales B where B.CustomerName = '" + DropDownList1.SelectedValue + "'";\n // pass you sql query to command object and call execute scalar method\n label1.Text = dbCommand.ExecuteScalar().ToString();	0
34479673	34479655	Modifying an IEnumerator after declaration	IEnumerable<>	0
18283662	18283255	How to implement User.Identity.Name in Global.asax on a new web application	void Session_Start(object sender, EventArgs e) \n{\n    string myself = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\n    string me = User.Identity.Name;\n    Response.Write("myself:" + myself + "<br>me:" + me);\n}	0
33611827	33611395	How to convert a string of bytes and a format to Audio in C# Xamamrin	byte[] bytes = Convert.FromBase64String(base64);\nFile.WriteAllBytes("Message1.wav", bytes);	0
1854468	1854450	Adding DateTime to ListView?	Time.Value.ToString("T")	0
1923950	1923909	Validating C# base class constructor parameter	public Identity(WindowsIdentity windowsIdentity)\n         : base(GetToken(windowsIdentity))\n{\n         init();\n}\n\nstatic Token GetToken(WindowsIdentity ident)\n{\n    if(ident == null)\n        throw new ArgumentNullException("ident");\n\n    return ident.Token;\n}	0
34512991	34512913	Generate random number from two List<>	var result = \n    integers.Concat(value2)\n    .OrderBy(x => random.Next())\n    .Take(count)\n    .ToList();	0
1165832	1165576	C# How to get SQL Server installation path programatically?	using(RegistryKey sqlServerKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"))\n{\n    foreach (string subKeyName in sqlServerKey.GetSubKeyNames())\n    {\n        if(subKeyName.StartsWith("MSSQL."))\n        {\n            using(RegistryKey instanceKey = sqlServerKey.OpenSubKey(subKeyName))\n            {\n                string instanceName = instanceKey.GetValue("").ToString();\n\n                if (instanceName == "MSSQLSERVER")//say\n                {\n                    string path = instanceKey.OpenSubKey(@"Setup").GetValue("SQLBinRoot").ToString();\n                    path = Path.Combine(path, "sqlserver.exe");\n                    return path;\n                }\n            }\n        }\n    }\n}	0
33210303	33210115	Put bool comparison operator in variable	public static bool Compare<T>(T value1, T value2, string str) where T : IComparable<T>\n{\n    Func<T, T, bool> op = null;\n\n    switch (str)\n    {\n        case "<":\n            op = (a, b) => a.CompareTo(b) < 0;\n            break;\n        case ">":\n            op = (a, b) => a.CompareTo(b) > 0;\n            break;\n        case "<=":\n            op = (a, b) => a.CompareTo(b) <= 0;\n            break;\n        case ">=":\n            op = (a, b) => a.CompareTo(b) >= 0;\n            break;\n        case "==":\n            op = (a, b) => a.CompareTo(b) == 0;\n            break;\n        case "!=":\n            op = (a, b) => a.CompareTo(b) != 0;\n            break;\n        default:\n            throw new ArgumentException();\n    }\n\n    return op(value1, value2);\n}	0
4091004	4090929	LINQ to SQL - Delete Many to Many if no relations	var tags =    from t in dataContext.Tags\n    where t.ProductTags.Count() == 0\n    select t;\ndataContext.Tags.DeleteAllOnSubmit(tags);	0
11015511	10986966	MEF load plugin from directory	public void AssembleCalculatorComponents()\n        {\n\n\n            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");\n            Console.WriteLine(path);\n            //Check the directory exists\n            if (!Directory.Exists(path))\n            {\n                Directory.CreateDirectory(path);\n            }\n            Console.WriteLine(path);\n            string assemblyName = Assembly.GetEntryAssembly().FullName;\n            Console.WriteLine(assemblyName);\n            //Create an assembly catalog of the assemblies with exports\n            var catalog = new AggregateCatalog(\n                new AssemblyCatalog(Assembly.GetExecutingAssembly().Location),\n                new AssemblyCatalog(Assembly.Load(assemblyName)),\n                new DirectoryCatalog(path, "*.dll"));\n\n            //Create a composition container\n            var container = new CompositionContainer(catalog);\n            container.ComposeParts(this);	0
8107383	8107243	How can I submit a webrequest using POST based on name values in C#?	WebClient.UploadValues()	0
1509482	1509471	how to export dat in .iif format from asp.net application?	Response.ContentType = "image/jpeg";	0
10037278	10037178	How to inherit events between objects	public class MovablePictureBox : PictureBox\n{\n    private int x;\n    private int y;\n\n    protected override void OnMouseDown(MouseEventArgs e)\n    {\n        base.OnMouseDown(e);\n\n        if (e.Button == MouseButtons.Left)\n        {\n            x = e.X;\n            y = e.Y;\n        }\n    }\n\n    protected override void OnMouseMove(MouseEventArgs e)\n    {\n        base.OnMouseMove(e);\n\n        if (e.Button == MouseButtons.Left)\n        {\n            Left += (e.X - x);\n            Top += (e.Y - y);\n        }\n    }\n}	0
27283073	27283010	Unwieldy LINQ statement with multiple search criteria	IQueryable<Employee> employees = DB.Employees;\n\nif (!string.IsNullOrEmpty(FirstName))\n{\n    employees = employees \n        .Where(emp => emp.FirstName.Contains(fName));\n}\nif (!string.IsNullOrEmpty(LastName))\n{\n    employees = employees \n        .Where(emp => emp.Last.Contains(lName));\n}	0
24948599	24948156	Can we use HttpHandler and HttpModule to change the content page div from the Master page?	document.onload = function()\n{\n    var titleDiv = document.getElementById("titleDiv");\n    titleDiv.innerText = window.url;\n}	0
5393902	5393803	Can someone explain how BCrypt verifies a hash?	StringBuilder rs = new StringBuilder();\n    rs.Append("$2");\n    if (minor >= 'a') {\n        rs.Append(minor);\n    }\n    rs.Append('$');\n    if (rounds < 10) {\n        rs.Append('0');\n    }\n    rs.Append(rounds);\n    rs.Append('$');\n    rs.Append(EncodeBase64(saltBytes, saltBytes.Length));\n    rs.Append(EncodeBase64(hashed,(bf_crypt_ciphertext.Length * 4) - 1));\n    return rs.ToString();	0
26577872	26577711	Entity Framework C# convert int to bool	[Column("VATInclusive")]\n    public int _VATInclusive { get; set; }\n\n    [NotMapped]\n    public bool VATInclusive\n    {\n        get\n        {\n            return _VATInclusive != 0;\n        }\n        set \n        {\n            _VATInclusive = value ? 1 : 0;\n        }\n    }	0
1047831	1045966	Serialize nullable fields from an object c#	[XmlElement(IsNullable = true)]\npublic string DummyField { get; set; }	0
12554431	12554406	Iterating duplicate xml elements	value.Elements("category")	0
12577343	12526847	Read Gridview header value of a dynamically added header	int current = 0;\n        int headerCount = grdTransactions.HeaderRow.Cells.Count;\n\n        for (current = 0; current < headerCount; current++)\n        {\n            TableHeaderCell cell = new TableHeaderCell();\n            cell.Text = grdTransactions.HeaderRow.Cells[current].Text;\n            originalHeaderRow.Cells.Add(cell);\n        }	0
15530764	15512181	ControlTemplates share the same color	...     <Path x:Name="Element"\n                            Fill="{Binding Symbol.Fill, Mode=OneTime}" Stroke="{Binding Symbol.BorderBrush, Mode=OneTime}"\n                            StrokeStartLineCap="Round" StrokeThickness="1" \n                            StrokeLineJoin="Round" StrokeEndLineCap="Round"/>   ...	0
9336956	9336851	How to map XML file content to C# object(s)	XmlSerializer deserializer = new XmlSerializer(typeof(List<Movie>));\nTextReader textReader = new StreamReader(@"C:\movie.xml");\nList<Movie> movies; \nmovies = (List<Movie>)deserializer.Deserialize(textReader);\ntextReader.Close();	0
1349519	1101147	Code demonstrating the importance of a Constrained Execution Region	using System;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.ConstrainedExecution;\n\nclass Program {\n    static bool cerWorked;\n\n    static void Main( string[] args ) {\n        try {\n            cerWorked = true;\n            MyFn();\n        }\n        catch( OutOfMemoryException ) {\n            Console.WriteLine( cerWorked );\n        }\n        Console.ReadLine();\n    }\n\n    unsafe struct Big {\n        public fixed byte Bytes[int.MaxValue];\n    }\n\n    //results depends on the existance of this attribute\n    [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] \n    unsafe static void StackOverflow() {\n        Big big;\n        big.Bytes[ int.MaxValue - 1 ] = 1;\n    }\n\n    static void MyFn() {\n        RuntimeHelpers.PrepareConstrainedRegions();\n        try {\n            cerWorked = false;\n        }\n        finally {\n            StackOverflow();\n        }\n    }\n}	0
321751	321719	Forcing a tab to the next control in an extended .net control	form1.SelectNextControl(textBox1, true, true, true, true);	0
11723294	11723037	Add XML element if it doesn't exist	Check parenthesis in your code\n\nXElement xElem = new XElement("root");\nxElem.Add( new XElement("CloseDisconnected", "123") ); // generates what you expect\nxElem.Add( new XElement("CloseDisconnected"), "123"); // generates what you see	0
13954232	13879451	Add excel vba code to button using c#	String updateBT "...// macro code for button";   \nVBA.VBComponent oModule1 = xlWorkBook.VBProject.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_StdModule);\noModule1.Name = "Update";\noModule1.CodeModule.AddFromString(updateBT);\n\nExcel.Shape btn2 = xlWorkSheet1.Shapes.AddFormControl(Excel.XlFormControl.xlButtonControl, 150, 5, 150, 22);\nbtn2.Name = "Update";\nbtn2.OnAction = "... // name of your macro code";\nbtn2.OLEFormat.Object.Caption = "... // Button name";	0
16544133	16544034	I need to swap 2 files with each other C#	File.Move("file1.txt", "temp.txt");\nFile.Move("file2.txt", "file1.txt");\nFile.Move("temp.txt", "file2.txt");	0
29392528	29387289	C# XML Descending order with elements and attributes	Name = r.XPathSelectElement("ancestor::Professor[1]").Attribute("id").Value + "   ",	0
8537675	8537521	Searching for all folders in c#, without dieing on one I don't have access too	List<string> dirs = new List<string>(Directory.GetFiles(@"C:\").ToList());	0
11153420	11152608	How to calculate mouse coordinate based on resolution c#	//First Normalize the clickPosition using the current resolution\n//clickPos(200,300) and resolution(800,600) => normalized(0.25,0.5)\nvar normalized = clickPos/resolution;\n\n//Now you can send this information to the other device\n//The other device uses the normalized parameter to calculate the mouseClick with his  resolution\n//normalized(0.25,0.5) and otherResolution(1280,720) => otherDeviceClickPos(320, 360)\nvar otherDeviceClickPos = normalized * otherResolution;	0
28571118	28570883	Perform a double sort on in Grid.MVC	Columns.Add(x=>x.Date).Sortable(true).ThenSortBy(x=>x.Time);	0
365093	365087	How to set dropdown's firsl Item -Select- and remaining Items from a column of table?	ddlLocationName.Items.Clear();\nddlLocationName.DataSource = _section.GetLocations();\nddlLocationName.DataBind();\nddlLocationName.Items.Insert(0, "Select Location"); // Adds the item in the first position	0
15289217	15289195	Grouping in linq	var results = list1.GroupBy(i => i.Name)\n                   .Select(g => new\n                                {\n                                    Name = g.Key,\n                                    DocCount = g.Sum(i => i.DocCount)\n                                });	0
11702253	11652229	How do I use a custom Certificate Authority in SharpSvn without installing the certificate	SvnClient _svnClient = new SvnClient();\n_svnClient.Configuration.SetOption("servers", "global", "ssl-authority-files", "/path/to/cacert.crt");\n_svnClient.Configuration.SetOption("servers", "groups", "myhost", "myhostsdns.com");	0
22170916	22169936	Casting double to string	NET_DEPOSIT = Convert.ToString(x.Field<double?>("NET_DEPOSIT")),	0
16629051	16629042	What's the best way to add an item to a C# array?	List<int> numbers	0
20286015	2431541	how to test asynchronous methods using nunit	[TestFixture]\nclass SomeTests\n{\n    [Test]\n    public void AsyncTest()\n    {\n        var autoEvent = new AutoResetEvent(false); // initialize to false\n\n        var Some = new Some();\n        Some.AsyncFunction(e =>\n        {\n            Assert.True(e.Result);\n            autoEvent.Set(); // event set\n        });\n        autoEvent.WaitOne(); // wait until event set\n    }\n\n}	0
5928790	5928769	choosing items based on random numbers	var prizes = new Prize[500];\n//fill prizes\n//randomly select index within prize array	0
22922903	22922598	How to write all keys and values within Dictionary<string, object> to a text file?	var jsonString = JsonConvert.SerializeObject(advertiserResponse, Formatting.Indented)	0
3558102	3557882	Stored procedure: pass XML as an argument and INSERT (key/value pairs)	/* Create the stored procedure */\ncreate procedure ParseXML (@InputXML xml)\nas\nbegin\n    declare @MyTable table (\n        id int,\n        value int\n    )\n\n    insert into @MyTable \n        (id, value)\n        select Row.id.value('@id','int'), Row.id.value('@value','int') \n            from @InputXML.nodes('/Rows/Row') as Row(id)        \n\n    select id, value\n        from @MyTable\nend\ngo\n\n/* Create the XML Parameter */\ndeclare @XMLParam xml\nset @XMLParam = '<Rows>\n                     <Row id="1" value="100" />\n                     <Row id="2" value="200" />\n                     <Row id="3" value="300" />\n                 </Rows>'\n\n/* Call the stored procedure with the XML Parameter */\nexec ParseXML @InputXML = @XMLParam\n\n/* Clean up - Drop the procedure */\ndrop procedure ParseXML\ngo	0
4416315	4416310	C# : How to download a file into specific file path with out using web browser	WebClient.DownloadFile(Uri,String)	0
7748135	7748121	Looking for regex to allow spaces but doesn't allow special characters?	bool isValid = Regex.IsMatch(name, "^[a-z0-9 ]+$", RegexOptions.IgnoreCase);	0
16664721	16663319	go to a page index corresponding to a specific record in a gridview	if (obj.ToString() != "0")\n{\n    grdSchedulerApplications.PageIndex = Int32.Parse(obj) / 5;\n    // TODO: Rebind your grid (set the data source and call DataBind())\n}	0
23084960	23084751	Web Api routing to action with string paramater	[Route("api/Societe/libelle/{name}")]\npublic IHttpActionResult GetSocieteByLibelle(string name)\n{\n\n}	0
11071697	11071682	Unassigned local variable mystery	if (false)\n        Console.WriteLine(x); // legal!!	0
1949055	1949023	extract data from rss feed in c#	XDocument doc = XDocument.Parse(xml);\nstring s = doc.Descendants()\n              .Where(element => element.Name == "woeid")\n              .FirstOrDefault().Value;	0
12727028	12726876	Using LINQ how can I check for an instance of a number in one array, in another array?	var filtered = myItems.Where(x => x.category_ids.Intersect(filter)\n                                          .Any());	0
2798663	2662041	Can I configure NUnit so that Debug.Fail doesn't show a message box when I run my tests?	[NUnitAddin]\npublic class NUnitAssertionHandler : IAddin\n{\n    public bool Install(IExtensionHost host)\n    {\n        Debug.Listeners.Clear();\n        Debug.Listeners.Add(new AssertFailTraceListener());\n        return true;\n    }\n\n    private class AssertFailTraceListener : DefaultTraceListener\n    {\n        public override void Fail(string message, string detailMessage)\n        {\n            Assert.Fail("Assertion failure: " + message);\n        }\n\n        public override void Fail(string message)\n        {\n            Assert.Fail("Assertion failure: " + message);\n        }\n    }\n}	0
24218461	24218335	Assign string into multidimensional array	string input ="[[\"Fri, 28 Mar 2014 01:00:00 +0000\",0.402053266764,\"1 sold\"],[\"Thu, 03 Apr 2014 01:00:00 +0000\",6.5,\"1 sold\"]]"; \nstring temp = input.Replace("[", "");\nstring[] records = temp.Split(new char[] {']'}, StringSplitOptions.RemoveEmptyEntries);\n\nstring[,] output = new string[records.Length, 3];\nint recno = 0;\nforeach(string record in records)\n{\n    Console.WriteLine(record);\n    string[] fields = record.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);\n    output[recno,0] = string.Join(",", fields[0], fields[1]);    \n    output[recno,1] = fields[2];    \n    output[recno,2] = fields[3];    \n    recno++;\n}\n\nfor(int x = 0; x <= output.GetUpperBound(0); x++)\n{\n    for(int y = 0; y <= output.GetUpperBound(1); y++)\n        Console.Write("INDEX[" +x + "," + y +"]=" + output[x, y] + ";");\n    Console.WriteLine();                            \n}	0
17278142	17277662	Selecting table from database with combobox and populating datagridview-can't get it to work	private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)\n{\n    // Better to be safe here.....\n    if (this.comboBox1.SelectedValue == null)\n        return;\n\n    using(OleDbConnection con = new OleDbConnection(connectionString))\n    using(OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT * FROM ["     +this.comboBox1.SelectedValue.ToString() +"]", con))\n    {\n        DataSet ds = new DataSet();\n        DataTable dt = new DataTable();\n        da2.MissingSchemaAction = MissingSchemaAction.AddWithKey;\n        da2.Fill(dt);\n        this.dataGridView1.DataSource = dt; \n    }\n}	0
8306061	8305955	How can I create a summary report using LINQ	from page in pages\ngroup page by new { \n                    page.subjectId\n                    , page.bookId\n                    , page.chapterId \n                 } into group\nselect new {\n             group.key.SubjectId\n             , group.key.bookId\n             , group.Key.chapterId\n             , total = pages.sum(s => s.Page)\n}	0
16227342	16227034	TopMost window going behind non-TopMost fullscreen window sometimes	var topMostHandle = WindowFromPoint((int)(Left + ActualWidth / 2), (int)ActualHeight / 2);\n\nif (topMostHandle != new WindowInteropHelper(this).Handle)\n{\n    Topmost = false;\n    Topmost = true;\n}	0
7501951	7501820	Determine if a value pulled from a file falls within a range	XMaxResult = (TryParseWithDefault(item.XMax, double.NaN) <= averageMaxX + stdDevMaximumX \n             && TryParseWithDefault(item.XMax, double.NaN) >= averageMaxX - stdDevMaximumX)  \n             ? "pass" : "FAIL"	0
13046058	13045958	Unable read App.config values from Class Library	web.config	0
15031946	9715551	How to Execute the Stored Procedure on Javascript Confirmbutton Click in ASP.NET	btnSubmitRequest.Attributes.Add("onclick", "return window.confirm('Submit Request?');");	0
13072299	13069803	Tabbing in a loop through a winform	private void timer1_Tick(object sender, EventArgs e) {\n    if (this.ActiveControl != null) label1.Text = this.ActiveControl.Name;\n}	0
7637859	7637829	Removing a list of objects from another list	listA.RemoveAll(x => !listB.Any(y => y.ID == x.ID));	0
20384933	20384764	For int i = value	while (randBuff < 144705) \n{\n  listBox1.Items.Add(randBuff.ToString("x8"));\n  randBuff += 4;\n}	0
20107007	20106863	Format Large Block of Text in C#	private string _description = string.Empty;\n  public string Description\n  {\n     get\n     {\n        return _description;\n     }\n     set\n     {\n        var description = string.Empty;\n        var substrings = value.Split( new[] { '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries );\n        for ( var i = 0; i < substrings.Length; i++ )\n        {\n           description += substrings[i] + ".";\n           if ( i % 5 == 0 && i != 0 )\n           {\n              description += Environment.NewLine + Environment.NewLine;\n           }\n        }\n        _description = description;\n     }\n  }	0
20677158	20677001	Count positive values in datatable	dt.AsEnumerable().Select(row1 => dt.Columns.Cast<DataColumn>()\n                                   .ToDictionary(column => column.ColumnName, column => row1[column.ColumnName]))\n                 .SelectMany(f=>f.Values)\n                 .Count(f=>decimal.Parse(f.ToString())>0);	0
7655723	7655615	How to call WebUserControls based on users request?	protected void userclick_click(object sender, EventArgs e)\n{\n    if(textbox1.Text == "2")\n    {\n        Control c1 = LoadControl("MyUserControl.ascx");\n        //page or whatever control you want to add to\n        Page.Controls.Add(c1);\n    }\n    else\n    {\n      /*do nothing*/\n    }\n}	0
34209870	34209750	Listview Delete Item Index source is in use wpf	if(SelectedListViewItem != null)\n{\n    // EDIT: Typo in the lambda for FirstOrDefault\n    var delete = showList.FirstOrDefault(x => SelectedListViewItem.ShowName == x.ShowName);\n    if(delete != null)\n    {\n        ((ObservableCollection<GetterSetter>)listView.ItemsSource).Remove(delete);\n    }\n}	0
18849377	18849170	Simple left shifting with C#	fullAddress = (address[0] << 4);\nfullAddress |= address[1];	0
20238141	20222611	How can i change a folder background via shell extension	[.ShellClassInfo]    \nIconFile=%SystemRoot%\system32\SHELL32.dll    \nIconIndex=127    \nConfirmFileOp=0    \n\n[{BE098140-A513-11D0-A3A4-00C04FD706EC}]    \nAttributes=1    \nIconArea_Image="your_picture.jpg"    \nIconArea_Text="0xFFFFFF"    \nVeBRA sources - don't delete the tag above, it's there for XXXXX purposes -    \n[ExtShellFolderViews]    \n{BE098140-A513-11D0-A3A4-00C04FD706EC}={BE098140-A513-11D0-A3A4-00C04FD706EC}    \n{5984FFE0-28D4-11CF-AE66-08002B2E1262}={5984FFE0-28D4-11CF-AE66-08002B2E1262}    \n\n[{5984FFE0-28D4-11CF-AE66-08002B2E1262}]    \nPersistMoniker=Folder.htt    \nPersistMonikerPreview=%WebDir%\folder.bmp	0
18233117	18233019	How to save UIElements in a Database and restore them later?	UIElement cXamlElements = (UIElement)XamlReader.Parse("MY XAML CODE");	0
22755391	22754935	ListBox selection issue in Windows Phone	private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        if(listBox1.SelectedIndex==-1)\n           return;\n        if (listBox1.SelectedItem == null)\n            return;\n\n        LIST data = (sender as ListBox).SelectedItem as LIST;\n        string result = data.item.ToString();\n          listBox1.SelectedIndex = -1;\n    }	0
13359751	13353211	Refresing the C# DataGrid from a background thread	/* Check the files. */\n        foreach(var file in allFiles)\n        {\n            var fileTmp = file; // avoid access to modified closure\n            this.Dispatcher.Invoke(new Action(delegate\n            {\n                int occurences;\n                bool result = FileSearcher.searchFile(fileTmp, searchTermTextBox.Text, out occurences);\n\n                fileso.AddOccurrences(fileTmp, occurences);  // This is an extension method that alters the collection by finding the relevant item and changing it.\n            }));\n        }	0
7225173	7225146	how to set masterpage dom element in contentpage with javascript	document.getElementById('sitemap').style.display = "none";	0
7693637	7693045	Noob Concern: Assigning a value to variable from new class object. C#	private void btnCalc_Click(object sender, EventArgs e)\n    {\n        DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };\n        dinnerFun.CalcDrinks(cbxHealthy.Checked);\n        dinnerFun.CalcDrinks(cbxFancy.Checked);\n        DisplayCost(dinnerFun); \n    }\n\n    public void DisplayCost(DinnerFun dinnerFun)\n    {\n        tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c"); \n    }	0
2729866	2729751	How do I draw a circle and line in the picturebox?	MyImage = new Bitmap(fileToDisplay);\npictureBox1.ClientSize = new Size(xSize, ySize);\npictureBox1.Image = MyImage;	0
26062858	26059654	How to get HomeController to call ImageController	/Images/Show/ImageName.png	0
583909	583897	C# how to wait for a webpage to finish loading before continuing	webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);\n\nvoid webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    webBrowser.Document.GetElementById("product").SetAttribute("value", product);\n    webBrowser.Document.GetElementById("version").SetAttribute("value", version);\n    webBrowser.Document.GetElementById("commit").InvokeMember("click");\n}	0
2182170	2166900	Finding the Location in the User Control	private Rectangle GetCellBounds(TreeList tree, TreeListNode node, int cellIndex)\n{\n    RowInfo ri = tree.ViewInfo.RowsInfo[node];\n    if (ri == null) return Rectangle.Empty;\n\n    CellInfo ci = tree.ViewInfo.RowsInfo[node].Cells[cellIndex] as CellInfo;\n    return ci.Bounds\n}	0
5772692	5744506	A curious case of Visual Studio 2010 debugger(it can not hit a break point)	bool b = false;\nif (b)\n{\n    try\n    {\n        b = true;\n    }\n    finally\n    {\n        b = true;\n    }\n}\nelse\n{\n    b = true;\n}\nb = true;	0
4290863	4290839	How to ensure that the serialization and deserialization with WebServices is symmetric?	public class Parent\n{\n    public string ParentProp { get; set; }\n}\n\npublic class Child: Parent\n{\n    public string ChildProp { get; set; }\n}\n\npublic class CustomResolver : JavaScriptTypeResolver\n{\n    public override Type ResolveType(string id)\n    {\n        return Type.GetType(id);\n    }\n\n    public override string ResolveTypeId(Type type)\n    {\n        return type.ToString();\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var o = new Child\n        {\n            ParentProp = "parent prop",\n            ChildProp = "child prop",\n        };\n\n        var serializer = new JavaScriptSerializer(new CustomResolver());\n        var s = serializer.Serialize(o);\n        Console.WriteLine(s);\n    }\n}	0
12267872	12267814	C# - splitting string of each value in an array	foreach (set.row officeJoin in officeJoinMeta)\n        {\n            foreach (set.somethingRow confRow in myData.something.Rows)\n            {\n                string dep = confRow["columnName"].ToString();\n                depts.AddRange(dep.Split(','));\n            }\n        }	0
29528243	29528208	Cannot assign to 'writeline' because it is a 'method group'	Console.WriteLine("This string goes to console.");	0
17329210	17329122	How to filter ListBox	private List<HubTiles> myTiles;    \nprivate void textBoxSearch_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.Key == Key.Enter)\n    {\n       myList.ItemsSource = myTiles.Where(t => t.Title.Contains(textBoxSearch.Text));\n    }\n}	0
17436885	17436867	How do I include quotation marks in a string?	writer.WriteLine("  \"profiles\": {  ");	0
1560501	1560142	C# .NET DataGridView enable cell click only to certain columns	public class MyDataGridView : DataGridView\n{\n     public MyDataGridView()\n     {\n     }\n\n     protected override void OnCellClick(DataGridViewCellEventArgs e)\n     {\n          if (!Columns[e.ColumnIndex].ReadOnly)\n          {\n               base.OnCellClick(e);\n          }\n     }\n}	0
14193478	14193133	display images in asp.net dynamically from c#	File.WriteAllBytes(@"C:\test.jpg", BYTE_ARRAY_OF_IMAGE);	0
11895012	11894783	C# How to change Form1 background after each 1 second?	var timer = new Timer() { Interval = 1000, Enabled = true, };\n        timer.Tick += (s, e) =>\n            this.BackColor =\n                    this.BackColor == Color.Green ? Color.Yellow : Color.Green;	0
6640201	6639569	Syntax problems using a viewModel with my view	var homeIndex = new HomeIndexViewModel \n{\n    PageMeta = new PageMeta \n    {\n        Title = "ABC",\n        User = "DEF"\n    }\n};	0
22656871	22656049	How to set User-Agent in WebClient	using (WebClient web = new WebClient())\n    {\n    web.Headers["User-Agent"] =\n    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +\n    "(compatible; MSIE 6.0; Windows NT 5.1; " +\n    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";\n      }	0
12970442	12970353	C# dynamically set property	objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)	0
3491384	3491347	load xml into dataset with column filtering	dataGridView1.AutoGenerateColumns	0
2384414	2373328	How can I sum a field from a grandchild table in a LINQ to DataSet where clause?	DataRelation relationToProducts;\nDataRelation relationToTransactions;    \nvar query = from x in ds.tables[0].AsEnumerable()\norderby x.Field<int>("Priority")\nselect new {\n    Name = x.Field<string>("Text"),\n    Amount = x.GetChildRows(relationToProducts)\n            .Sum(product => product.GetChildRows(relationToTransactions)\n                    .Sum(tx => tx.Field<decimal>("Amount")))\n};	0
32781397	32781217	C# Sql client - can't Insert parametrized column whose name starts with number	string query = "INSERT INTO " + table + " (";\n\n  foreach (KeyValuePair<string, object> pair in values)\n        query += "[" + pair.Key + "],";	0
11402132	11401914	How to retrieve executable program path remotely	ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM  Win32_Product");\nforeach(ManagementObject mo in mos.Get())\n{\n  Console.WriteLine(mo["Name"]);\n  Console.WriteLine(mo["InstallState"]);\n}	0
9931834	9931651	Share Class/Methods Between Windows Forms Application and Console Application	Console Project\n...Properties    \n...Refernces <including CommonCode Class Library>\n...Program.cs\n...class1.cs\n...etc\nCommonCode Class Library\n...classA.cs\n...classB.cs\n...etc\n\n\n\n\nWinforms Project\n...Properties\n...Refernces <including CommonCode Class Library>\n...Form1    \n...Program.cs\nCommonCode Class Library\n...classA.cs\n...classB.cs\n...etc	0
3788183	3783308	C# Powershell setting the Console File	public static RunspaceConfiguration Create (\n    string consoleFilePath,\n    out PSConsoleLoadException warnings\n)	0
30208813	30208662	Trying to add non-.NET libraries to NuGet package	xcopy /y /f "$(ProjectDir)..\packages\NonNet.dll" "$(TargetDir)"	0
9878054	9877987	Hold Poco Model (Domain Model) in Session	MyModel mm;\n\nSession["MyModel"] = mm; \nMyModel mm = (MyModel)Session["MyModel"];	0
2974306	491628	How do I combine two interfaces when creating mocks?	var mocker = new MockRepository();\nvar mock = mocker.CreateMultiMock<IPrimaryInterface>(typeof(IFoo), typeof(IBar));\nmocker.ReplayAll();	0
3255614	3255514	linq to xml - display results based on array or list	var ids = new HashSet<string>();\nids.Add("1");\nids.Add("2");\n\nvar mylinks =\n  from item in relatedLinks.Descendants("link") \n  where ids.Contains(item.Attribute("linkID").Value)\n  select new { testlink = item.Value };	0
10727351	10625005	How to get HttpResponse size	int bufferedLength1 = httpContext.Response.GetBufferedLength();\nthis.RenderControlInternal(writer, adapter);\nint bufferedLength2 = httpContext.Response.GetBufferedLength();	0
7318013	7317941	How to I expose a type as a different name in WCF?	[DataContract(Name = "MyMediaItem")]	0
10798063	10797995	Send HTTP Post Request through ASP.net	string url = "http://revtr.cs.washington.edu/measure.php";	0
16649309	16647651	Find Cycles in Organic Graphs	function DFSFindCycle(Start, Goal)\npush(Stack,Start)\nwhile Stack is not empty\n    var Node := Pop(Stack)\n    Color(Node, Grey)\n    for Child in ExpandNotExploredEdges(Node)\n        if Node.color != White\n    return true \n        if Node.color = White\n           push(Stack, Child)\n           label edge e, Node:Child as explored\n    Color(Node, Black)\nretrun false	0
13046090	13046052	how to view master page in browser	not an actual page	0
33665134	33664228	ASP.NET: Getting the Current URL via a Web Method?	//To get the Absolute path of the URI use this\nstring myPreviousAbsolutePath = Page.Request.UrlReferrer.AbsolutePath;\n\n//To get the Path and Query of the URI use this\nstring myPreviousPathAndQuery = Page.Request.UrlReferrer.PathAndQuery;	0
34280500	34280433	How to remove a specific string from WPF RichTextBox?	TextRange textRange = new TextRange(\n    richTextBox.Document.ContentStart,\n    richTextBox.Document.ContentEnd\n);\n\ntextRange.Text = textRange.Text.Replace("Text", "Document");	0
3698697	3624858	How to hide button in last("fake") row of Datagridview?	dgv.AllowUserToAddRows = false	0
22684296	22683455	Increment Dictionary Value in MongoDB C# Driver	Update.Inc(string.Format("Actions.{0}.Count", action.ToLower()), 1);	0
8813945	8813887	How to close-without-save an Excel /xlsm workbook, w/ a custom function, from C#	Excel.Application xlApp ;\n        Excel.Workbook xlWorkBook ;\n        Excel.Worksheet xlWorkSheet ;\n        object misValue = System.Reflection.Missing.Value;\n\n        xlApp = new Excel.ApplicationClass();\n        xlWorkBook = xlApp.Workbooks.Add("Yourworkbook");\n\n        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n\n        ....do your stuff\n\n        xlWorkBook.Close(false, misValue, misValue);\n\n        xlApp.Quit();	0
18019421	18019100	retrieve settings based on enum	if(route2Type == Route2Type.publicMade)\n      OtherClass= new OtherClass.OneWay();\n else\n      OtherClass= new OtherClass.TwoWay();	0
11407964	11407871	Custom password Winform	button1.DialogResult = DialogResult.OK;	0
21365052	21364825	Checking what control ContextMenu was opened on	private void contextMenu1_Opening(object sender, CancelEventArgs e)\n{\n     MessageBox.Show(contextMenu1.SourceControl.Name);\n}	0
5772683	5772651	How to databind with LIST	List<Customer> lst = new List<Customer>;\nlst.add(new Customer(id=1,name="jhon"));\nlst.add(new Customer(id=2,name="keith"));\n\n\nmyGridView.DataSource = lst;\nmyGridView.DataBind();	0
24389065	22747224	Multi-level derived EF DataContext	// make it generic\npublic class BaseContextInitializer<T> : IDatabaseInitializer<T>\n{\n   // ...\n   public void InitializeDatabase(T context) \n   {\n        // ...\n   }\n}\n\n    // now pass the derivedcontext in the derived initializer\npublic class DerivedContextInitializer : BaseContextInitializer<DerivedContext>\n{\n    // overrides etc. etc.  \n} \n\n\n    // set the initializer to be the derived one\npublic class DerivedContext : BaseContext {\n    public DbSet<Admin> Admins { get; set; }\n\n    public DerivedContext(): base("default")\n    {\n        Database.SetInitializer(new DerivedContextInitializer());\n    }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        base.OnModelCreating(modelBuilder);\n\n        modelBuilder.Configurations.Add(new AdminConfiguration());\n    }\n}	0
919721	919699	How do I access an object property with a string variable that has the name of that property?	using System.Reflection;\n\n...\n\nPropertyInfo prop = typeof(Customer).GetProperty(propertyName);\nobject value = prop.GetValue(customer, null);	0
4155500	4155382	A faster way of doing multiple string replacements	static Dictionary<char, char> repl = new Dictionary<char, char>() { { '?', 'a' }, { '?', 'o' } }; // etc...\npublic string DoRepl(string Inp)\n{\n    var tmp = Inp.Select(c =>\n    {\n        char r;\n        if (repl.TryGetValue(c, out r))\n            return r;\n        return c;\n    });\n    return new string(tmp.ToArray());\n}	0
1029526	1029379	How to use the new Subsonic 3.0 IRepository pattern	_StaffingPositionsRepository = new SubSonicRepository<StaffingPosition>(new StaffingDB());	0
20269161	20198124	Read Private Key from PFX-file	X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);\nstore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);\nX509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByThumbprint, CERTIFICATE_THUMB_PRINT, false);\nif (certificates.Count == 0)\n{\n    // "Certificate not installed."\n}\nelse\n{\n    certificate = certificates[0];\n}\nstore.Close();	0
34149739	33734125	How to remove <p> like tags from xml using c#	var product = from a in cruiseDoc.Descendants("CruiseProduct")\n                  select new CProducts\n                  {\n                      cId = a.Element("ID").Value,\n                      cName = a.Element("Name").Value,\n                      cDescription= Regex.Replace(a.Element("Description").Value, "<.*?>", string.Empty)\n                  };	0
4307212	4307148	Creating an object from a hash table C#	PropertyInfo property = description.GetProperty((string) d.Key);\n\nobject value = property.GetValue(p, null);	0
5329182	5329119	Windows 7 forms effect - how to switch it off?	Application.EnableVisualStyles	0
17533142	17533093	How do I add gridView rows to a dataTable?	DataTable finalShowsTable = new DataTable();\n\n    finalShowsTable = originalFinalShowsTable.Clone();\n\n    foreach (GridViewRow gvr in gvShows.Rows)\n    {\n        if (gvr.RowType == DataControlRowType.DataRow)\n        {\n             if (((CheckBox) gvr.FindControl("cbSelect")).Checked)\n             {\n                    DataRow dr= finalShowsTable.NewRow();\n                     for (int i = 0; i < gvr.Cells.Count - 1; i++)\n                     {\n                         dr[i] = row.Cells[i].Text;\n                     }\n\n                     finalShowsTable.Rows.Add(dr);\n             }\n         }\n    }	0
18355708	18355663	Make a list distinct list of a list	string[] list = {"a","b","a","f","a",null,"a","e","a","e"};\nvar distinctList = list.Distinct();\n\nforeach (var str in distinctList)//Distinct list of values\n{\n    Console.Write(str); \n}	0
13609887	13609783	Prevent user from entering a from date greater than to date c#	if (InvoiceDateTo < InvoiceDateFrom)\n    MessageBox.Show("Please select a valid date range.");	0
1751557	1749278	Getting blank rows after setting DataGridView.DataSource. How to solve this problem?	// Example\nDataAdapter = new SqlDataAdapter();\nDataAdapter = CreateInventoryAdapter();\nDataAdapter.TableMappings.Add("Table", "GARAGE");\n\nDataAdapter.Fill(myDataSet);\nmyDataView = myDataSet.Tables[0].DefaultView;\ndataGridView1.DataSource = myDataView	0
20965666	20965647	Is there a way I can select only certain fields from a .Include( in a LINQ Query?	var problems = _questionsRepository\n            .GetAll()\n            .Where(q => q.Problem.SubTopicId == subTopicId || subTopicId == 0)\n            .Where(q => q.QuestionStatusId == questionStatusId || questionStatusId == 0)\n            .Where(q => q.AssignedTo == assignedTo || assignedTo == "0")\n            .Where(q => q.ModifiedBy == modifiedBy || modifiedBy == "0")\n            .Include(q => q.Problem)\n            .Include(q => q.Answers)\n            .Select(x=>new \n               {\n                   SubTopicId = x.Problem.SubTopicId, \n                   ProblemId = x.Problem.ProblemId \n               }).ToList();	0
32389126	32387164	C# SQLDataAdapter - Issues with INSERT	sqlComm = new SqlCommand(strInsertSQL, sqlConnArchive);\nvar tableIdParam = new SqlParameter("@TableId", SqlDbType.Int, 4);\ntableIdParam.Value = 99; //whatever id value you want to set here\nsqlComm.Parameters.Add(tableIdParam);	0
267053	267033	Getting odd/even part of a sequence with LINQ	var oddCategories  = projectsByCat.ToList().Where((c,i) => i % 2 != 0);\nvar evenCategories = projectsByCat.ToList().Where((c,i) => i % 2 == 0);	0
4048440	4045915	What technologies to use for a particle system with enormous calculation demand?	Mono.Simd	0
28600413	28597551	How do I make sure that my windows impersonation level is valid?	A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll	0
1939697	1939681	Is it possible to compile a dll with subset of classes from the class library project?	#define ClassA\n#if ClassA\nclass A\n{\n}\n#endif\n\n#undef ClassB\n#if ClassB\nclass B\n{\n}\n#endif	0
8872280	8872265	View model event bind to button click	Button.Command	0
2344594	2344431	C#: Getting lowest valued key in a bitwise Enum	Keys key = Keys.b | Keys.c;\n\nvar lowest = Enum.GetValues(typeof(Keys))\n    .Cast<Keys>()\n    .OrderBy(x => x)\n    .FirstOrDefault(x => key.HasFlag(x));	0
6004375	6004354	How to ensure the GUI elements and loaded before proceeding in C#	public Form1()\n{\n    InitializeComponent();\n    backgroundWorker1.RunWorkerAsync();\n}\n\nprivate void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n    for(var i = 0; i < 1000; i++)\n    {\n        var newElement = BuildMyElement(i);\n        backgroundWorker1.ReportProgress(0, newElement);\n    }\n}\n\nprivate void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    var newElement = (MyType)e.UserState;\n    listBox1.Items.Add(newElement);\n}	0
11112301	11112176	Restricting Member Access to Multiple Specific Classes	interface IPumpable \n    {\n        void Pump();\n    }\n    interface IPoppable\n    {\n        void Pop();\n    }\n\n    class Balloon :IPumpable, IPoppable\n    {\n        private void IPumpable.Pump()\n        {\n            throw new NotImplementedException();\n        }   \n        private void IPoppable.Pop()\n        {\n            throw new NotImplementedException();\n        }\n    }\n\n    public static void PopMethod(IPoppable poppable)\n    {\n        poppable.Pop();\n    }\n    public static void PumpMethod(IPumpable pumpable)\n    {\n        pumpable.Pump();\n    }\n\n    static void Main(string[] args)\n    {\n        Balloon balloon = new Balloon();\n\n        PumpMethod((IPumpable)balloon);\n        PopMethod((IPoppable)balloon);\n    }	0
11515102	11514553	Best way to reference a certain variable throughout the namespace?	using Bar = ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot.TestClass;\n\nnamespace ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot\n{\n  public static class TestClass\n  {\n    public static int TestFoo { get; set; }\n  }\n}\n\nnamespace Foo.SomeOtherNamespace\n{\n  class MyClassThatDoesStuff\n  {\n    public void DoStuff()\n    {\n      Bar.TestFoo = 123;\n    }\n  }\n}	0
31078079	31077412	cs1690 defining a member for object c#	private state set2;    \npublic void set1()     \n{    \nset2 = main.info;    \n}	0
12495590	12459889	Fluent NHibernate mapping to Oracle 11G and SQLite	class CreationDateConvention  : IPropertyConvention\n{\n    public CreationDateConvention(string default)\n    {\n        _default = default;\n    }\n\n    public void Apply(... instance)\n    {\n        if (instance.Name == "CreationDate")\n            instance.Default(_default)\n    }\n}\n\n\n// and while configuring\n...FluentMappings.AddFromAssemblyOf<>().Conventions.Add(new CreationDateConvention(isOracle ? "to_date..." : Datetime.Minvalue.ToString())	0
15632218	15618918	Display pictures of sd card in GridView	BitmapFactory.DecodeFile(String path, BitmapFactory.Options opts)	0
24826543	24826283	Missing directive or assembly on build time	using XXX	0
21422592	21422559	How to Read a text file continuosuly	private int ReadLinesCount?= 0;\npublic static void RunWatcher()\n{\n    FileSystemWatcher watcher = new FileSystemWatcher();\n? ? watcher.Path = "c:\folder";? ?\n? ? watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite\n? ? ? ? ? ?| NotifyFilters.FileName | NotifyFilters.DirectoryName;? ?\n? ? watcher.Filter = "*.txt";? ? \n? ? watcher.Changed += new FileSystemEventHandler(OnChanged);\n    watcher.EnableRaisingEvents = true;\n\n}\n\nprivate static void OnChanged(object source, FileSystemEventArgs e)\n{\n      int totalLines - File.ReadLines(path).Count();\n      int newLinesCount = totalLines - ReadLinesCount;\n      File.ReadLines(path).Skip(ReadLinesCount).Take(newLinesCount );\n      ReadLinesCount = totalLines;\n}	0
29075021	28451410	How to enable/disable Encryption/Decryption of Query String from Web Config?	we can have key/value pair settings in appsettings in web.config.\n  <appSettings>\n    <add key="EnableURLEncryption" value="false"/>\n   </appSettings>	0
25374689	25374661	In C#, how can I order a list after its grouped by size of the list?	var result = cars.GroupBy(r=>r.Color).OrderByDescending(g => g.Count());	0
4619507	4619464	Is there a way to compose an anonymous type object from JSON without knowing about the object's structure before-hand?	Reflection.Emit	0
13637209	13467153	Removing NULs from bytearray / blobColumn c#	byte[] blobdata = Encoding.UTF8.GetBytes(strNotes);	0
5913519	5706766	Webservice XML response deserialization	XmlSerializer xml = new XmlSerializer(typeof(CommandResult),"XMLNamespaceFromWSDL");\nCommandResult cr;\nusing (Stream stream = new FileStream("CommandResult.xml", FileMode.Open))\n     cr = (CommandResult)xml.Deserialize(stream);	0
13401337	13401294	Can a DLL launch a word file?	Process.Start()	0
19522824	19521004	Gridview row width shrinking when a control is not visible	ItemStyle-Width="60px"	0
18630763	18628561	How to get Metro in-app purchases to work?	await CurrentAppSimulator.RequestProductPurchaseAsync("product1");	0
3621060	3621032	Silverlight Togglebutton Set IsPressed state	btButton.IsChecked = true;	0
1448279	1445374	Spring.NET Creation of Object with Parameters	string userName = "Test";\nstring password = "Test";\nobject[] arguments = new object[] { userName, password };\n\nContextRegister.GetContext().GetObject("WinFormApplicationWorkflow", arguments);	0
22159474	21730515	Asynchronous toggle button using a semaphore to avoid service load	async  Task  Button1Click()\n {\n     // Assume we're being called on UI thread... if not, the two assignments must be made atomic.\n     // Note: we factor out "FooHelperAsync" to avoid an await between the two assignments. \n     // without an intervening await. \n      if  (FooAsyncCancellation !=  null ) FooAsyncCancellation.Cancel();\n      FooAsyncCancellation  =  new  CancellationTokenSource ();\n      FooAsyncTask  = FooHelperAsync(FooAsyncCancellation.Token);\n\n      await  FooAsyncTask;\n }\n\n Task  FooAsyncTask;\n CancellationTokenSource  FooAsyncCancellation;\n\n async  Task  FooHelperAsync( CancellationToken  cancel)\n {\n      try  {  if  (FooAsyncTask !=  null )  await  FooAsyncTask; }\n      catch  ( OperationCanceledException ) { }\n     cancel.ThrowIfCancellationRequested();\n      await  FooAsync(cancel);\n }\n\n async  Task  FooAsync( CancellationToken  cancel)\n {\n     ...\n }	0
4025700	4022589	How to programmatically iterate through pages of a GridView	if(GridView1.PageIndex == GridView1.PageCount)\n{\n   GridView1.PageIndex = 0;\n}\nelse\n{\n   GridView.PageIndex = GridView.PageIndex + 1;\n}	0
26859497	26859147	Compare to strings and get the distinct in c#	string[] assets, allassets = null;\nint[] list1, list2, removed_list, added_list = null;\n\nassets = a.Split(',');\nlist1 = Array.ConvertAll(assets, x => int.Parse(x))\n\nallassets = b.Split(',');\nlist2 = Array.ConvertAll(allassets, x => int.Parse(x));\n\nremoved_list = list2.Where(x => !list1.Contains(x)).ToArray(); // which gives =>a\nadded_list = list1.Where(x => !list2.Contains(x)).ToArray(); // which gives =>b	0
20268383	20268320	How to find a control in a repeater with IndexOf C#	foreach(RepeaterItem item in repeater1.Items)\n{\n  foreach (var control in item.Controls)\n  {\n     if(control.ID.EndsWith("EditMode"))\n     {\n          control.Visible = false;\n     }\n  }\n}	0
4608566	4608529	How to delete records permanently in case of linked tables?	ON DELETE CASCADE	0
17461281	17384603	How can I use my abstract base class in a One to Many in a TPH using Fluent NHibernate automapping?	public class AppMappingOverride : IAutoMappingOverride<App>\n        {\n            public void Override(AutoMapping<App> mapping)\n            {\n                mapping.DynamicUpdate();\n                mapping.DynamicInsert();\n                mapping.HasManyToMany(x => x.Subscriptions).Inverse();\n                mapping.HasManyToMany(x => x.Users).Inverse();\n            }\n        }\n\n        public class SubscriptionMappingOverride : IAutoMappingOverride<Subscription>\n        {\n            public void Override(AutoMapping<Subscription> mapping)\n            {\n                mapping.DynamicInsert();\n                mapping.DynamicUpdate();\n                mapping.HasManyToMany(x => x.Apps);\n            }\n        }	0
20861761	20861463	SQLException With Character from Database	where ColOne = 'DATATWO-Test	0
23598282	23598192	Changing font size in itextsharp table	for (int j = 0; j < dataGridView1.Columns.Count; j++)\n{\n    table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText,fontTable));\n\n}\n\n//..\n\nfor (int i = 0; i < dataGridView1.Rows.Count; i++)\n{\n    for (int k = 0; k < dataGridView1.Columns.Count; k++)\n    {\n         if (dataGridView1[k, i].Value != null)\n         {\n              table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(),fontTable));\n         }\n     }\n}	0
2935531	2918374	How to list all classes with a specific Atttribute within an assembly?	static class ClassLoader\n{\n    public static IEnumerable<MethodInfo> GetMethodsWithAttribute(Type attributeType, Type type)\n    {\n        List<MethodInfo> list = new List<MethodInfo>();\n\n        foreach (MethodInfo m in type.GetMethods())\n        {\n            if (m.IsDefined(attributeType, false))\n            {\n                list.Add(m);\n            }\n        }\n\n        return list;\n    }\n\n    public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, string assemblyName)\n    {\n        Assembly assembly = Assembly.LoadFrom(assemblyName);\n        return GetTypesWithAttribute(attributeType, assembly);\n    }\n\n    public static IEnumerable<Type> GetTypesWithAttribute(Type attributeType, Assembly assembly)\n    {\n        List<Type> list = new List<Type>();\n        foreach (Type type in assembly.GetTypes())\n        {\n            if (type.IsDefined(attributeType, false))\n                list.Add(type);\n        }\n\n        return list;\n    }\n}	0
18282441	18282302	Using Linq to return a list of attributes in a node	XNamespace z = "#RowsetSchema";\n\nvar alerts = xDocument.Descendants(z + "row")\n                    .Select(row => (string)row.Attribute("ows_Alert"))\n                    .ToList();	0
2422360	2422334	how to convert lambda expression to object directly?	object o = (Action) (() => { ... });	0
7665161	7665132	Inheritance constructors: Converting from C# to C++	class Grunt : public GameObject\n{\n    Grunt()\n        : GameObject()  // Since there are no parameters to the base, this line is actually optional.\n    {\n         // do stuff\n    }\n}	0
12889907	12889644	paging gridview rebinding for each result	protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n    GridView1.PageIndex = e.NewPageIndex;\n    BindGridView();\n}	0
32346112	32346022	How to fill in a string "hangman style"?	guessChar = string.Empty;\nfor (int i = 0; i < random.Length; i++) \n{\n    if (guessBool [i])\n        guessChar += random[i] + " ";\n    else\n        guessChar += "_ ";\n}\nGetComponent<TextMesh> ().text = guessChar;	0
254455	254099	Can take be used in a query expression in c# linq instead of using .Take(x)?	var subquery =\n  dc.Groups\n  .OrderBy(g => g.TotalMembers)\n  .Take(5);\n\nvar query =\n  dc.Themes\n  .Join(subquery, t => t.K, g => g.ThemeK, (t, g) => new\n  {\n    ThemeName = t.Name, GroupName = g.Name\n  }\n  );	0
3061140	3061103	how to add the checkbox to the datagridview from coding	DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();\ncheckColumn.Name = "X";\ncheckColumn.HeaderText = "X";\ncheckColumn.Width = 50;\ncheckColumn.ReadOnly = false;\ncheckColumn.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\ndataGridView1.Columns.Add(checkColumn);	0
16491941	16491811	C# extracting data from XML	XDocument X = XDocument.Load("http://www.yr.no/place/Norway/Oslo/Oslo/Oslo/forecast.xml");\n\nvar forecast = X.Element("weatherdata").Element("forecast");\nvar location = forecast.Descendants("location").Attributes("name").FirstOrDefault().Value;\nvar tempData = forecast.Element("tabular").Elements("time");\n\n//This is what you need\nvar data = tempData.Select(item=>\n            new{\n                from = Convert.ToDateTime(item.Attribute("from").Value),\n                to = Convert.ToDateTime(item.Attribute("to").Value),\n                temp = item.Element("temperature").Attribute("value").Value\n            });\n\n\n//Or you can do a foreach if you need to\nforeach (var item in tempData)\n{\n        DateTime from = Convert.ToDateTime(item.Attribute("from").Value);\n        var temp = item.Element("temperature").Attribute("value").Value;\n}	0
19152868	19152717	How do I compare a list of dictionaries for equality in C#	Equals()	0
32362798	32362370	I need to deduct a year (lets say 1991) from 2015, using c#	// get current time\n    DateTime now = DateTime.Now;\n\n    // get year of birth from user\n    String myYear = Console.ReadLine();\n\n    // construct a DateTime from that year\n    DateTime my = new DateTime(Convert.ToInt16(myYear), 1, 1);\n\n    // devide by 365 and convert to int\n    Console.Write(Convert.ToInt16((now - my).TotalDays) / 365);	0
10560316	10549654	RenderTarget2D tints all alpha purple	GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;\nGraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;\nGraphicsDevice.RenderState.AlphaSourceBlend = Blend.SourceAlpha;\nGraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;\nGraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;	0
23459327	23458702	making my own PointD struct (like Point, but with double) : using X and Y without define them first?	public Form1()\n    {\n        InitializeComponent();\n\n        MyStruct ms = new MyStruct();\n        this.Text = ms.p.X.ToString() + ms.d.X.ToString();\n\n    }\n\n    public struct PointD\n    {\n        public double X;\n        public double Y;\n    }\n\n    public struct MyStruct\n    {\n        public PointF p;\n        public PointD d;\n    }	0
25165225	24973248	How to stub DbSet.Find	public class FakePostsDbSet : FakeDbSet<Post>\n{\n    public override Post Find(params object[] keyValues)\n    {\n        return this.SingleOrDefault(\n            post => post.Slug == (string) keyValues.Single());\n    }\n}	0
4681888	4681864	Data Reader trimming the leading zeros	basePage.GroupNum = Convert.ToInt32(accReader.GetValue(0)).ToString("000000000")	0
10414526	10414499	Index was outside the bounds of the array	foreach (DeArtIzm izm in colRindas)\n     {\n         objectData[i, 0] = izm.ArtCode;\n         objectData[i, 1] = izm.ArtName;\n         objectData[i, 2] = izm.Price;\n         objectData[i, 3] = izm.RefPrice;\n         i++;//Place where I get that error\n     }	0
31572081	31571227	LinqToSQL needs explicity?	using (db_era.era_entities _ee = new db_era.era_entities())	0
4749490	4749415	Unable to load executing assembly into new AppDomain, FileNotFoundException	AppDomain.CreateDomain(templateDomainFriendlyName, null,\n            new AppDomainSetup\n            {\n                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase\n            });	0
21897556	21879204	How to get Title from Browser Tab?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.IO;\nusing System.Text.RegularExpressions;\nusing System.Web.Http;\nusing System.Web;\n\n\n namespace HTMLConsoleRead1._0\n\n{\n\nclass Program\n\n\n\n\n { \n\n    static void Main(string[] args)\n\n     {\n\n        string htmlTitle = File.ReadAllText("masterHTML.html");\n\n        Console.WriteLine(GetTitle(htmlTitle));\n\n        Console.ReadLine();\n\n    }\n\n    static string GetTitle(string file)\n    {\n        Match match = Regex.Match(file, @"<title>\s*(.+?)\s*</title>");\n        if (match.Success)\n        {\n            return match.Groups[1].Value;\n        }\n        else\n        {\n            return "";\n        }\n    }\n}	0
25036348	25036191	How to add a new visitortag to the current user (Sitecore)?	Sitecore.Analytics.Tracker.Visitor.Tags.Add("MyTagName", "content of my tag");	0
29788228	29787271	Using Linear search	static void Main()\n{\n    string text = File.ReadAllText(@"e:\1.txt");\n    Regex regex = new Regex("Monday", RegexOptions.IgnoreCase);\n    Match match = regex.Match(text);\n\n    while (match.Success)\n    {\n        Console.WriteLine("'{0}' found at index {1}", match.Value, match.Index);\n        match = match.NextMatch();\n    }\n}	0
4761791	4761521	Get the email address of the current user in Outlook 2007	Namespace.CurrentUser	0
7736051	7736036	Select Items from List<object> by conitaining List<guid> in C#	var selectedUsers = allUsers.Where(user => selectedUserIds.Contains(user.Id));	0
11150944	11150872	C# - WPF - Determining mouse position in canvas only works on top of shapes	HitTestCore(PointHitTestParameters)	0
23645723	23645629	How to implement DateTime	public DateTime CalcLastCouponDate(DateTime dtmBaseDate, DateTime dtmLastDate, int intCouponTermMonths, int intFixedCouponDay, string strOddLastCouponType)\n{\n    return (strOddLastCouponType == "S") ?\n        dtmLastDate.AddMonths(-intCouponTermMonths) :\n        dtmLastDate.AddMonths(-2 * intCouponTermMonths);\n}\n\npublic bool IsLastDayOfMonth(DateTime dateIn)\n{\n    return dateIn.Day == DateTime.DaysInMonth(dateIn.Year, dateIn.Month);\n}	0
8042502	8042474	C# How to check if a string contains any of the elements in an string array?	Search.Any(p => name.Contains(p))	0
32372587	32372442	How to Get Callback message to my Backend side of my site	[HttpGet]\n[RouteUrl("callback")]\npublic ActionResult Callback(){\nReturn Ok();\n}	0
29143438	29142763	Grouping a list by the results of a split	foreach (var groupedFiles in files.GroupBy(s => s.Split('\\')[0]))\n{\n     if (Path.GetExtension(groupedFiles.Key) == string.Empty)\n     {\n          //this is a folder\n          var folder = groupedFiles.Key;\n          var folderFiles = groupedFiles.ToList();\n     }\n     else\n     {\n          //this is a file\n          var file = groupedFiles.First();\n     }\n}	0
11481026	11481015	expected } for some reason	private void button1_Click(object sender, EventArgs e)\n{\n    ...\n    void herp(object sender, EventArgs e)\n    {\n\n    }\n}	0
6452751	6452713	best way to receive a list of objects from list of KeyValuePair?	var values = list.Where(x => x.Key == "whatever").Select(x => x.Value);	0
6443146	6443131	Grouping Key Value pairs with Linq and List	_noteGroup.First()	0
2674144	2630383	FluentNHibernate: returning an enum from a derived property	public virtual MyEnum MyDerivedProperty() \n{\n       MyEnum retval;\n       // do some calculations\n       return retval;\n}	0
18336734	18327106	ASP.NET DES encryption with encrypted text length equal to plain text length	public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)\n{\n    BufferedBlockCipher cipher = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));\n    ICipherParameters keyParam = new ParametersWithIV(new KeyParameter(key), iv);\n    cipher.Init(true, keyParam);\n    return cipher.DoFinal(data, 0, data.Length);\n}\n\npublic static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)\n{\n    BufferedBlockCipher cipher = new CtsBlockCipher(new CbcBlockCipher(new AesEngine()));\n    ICipherParameters keyParam = new ParametersWithIV(new KeyParameter(key), iv);\n    cipher.Init(false, keyParam);\n    return cipher.DoFinal(data, 0, data.Length);\n}	0
16430863	16430833	c# sort a list by a column alphabetically	List1 = List1.OrderBy( x => x.finderror ).ToList();	0
12520600	12520532	Writing data to text file	static void WriteOutputToTextFile(string _data)\n    {\n        string FolderName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);   //set destination as your desktop\n        using (StreamWriter SW = new StreamWriter(FolderName + "\\test.txt", true))   //true makes it append to the file instead of overwrite\n        {\n            SW.WriteLine(_data);\n            SW.Close();\n        }\n    }	0
26528281	26527783	Changing rectangle margin with code	private void Window_KeyDown(object sender, KeyEventArgs e)\n    {\n        double x = rect.Margin.Left;\n        double y = rect.Margin.Top;\n        if (e.Key == Key.D)\n        {\n            rect.Margin = new Thickness(x+5, y, 0, 0);\n        }\n        else if (e.Key == Key.A)\n        {\n            rect.Margin = new Thickness(x-5, y, 0, 0);\n        }\n        Thread.Sleep(100);\n    }\n}	0
15355343	15355240	Removing .aspx from pages using URL Rewrite in iis in asp.net	U can do this in your web.config file itself\n\n <system.web>\n\n    <urlMappings enabled="true">\n\n        <add url="~/marutisuzuki-Alto" mappedUrl="~/Carmodel.aspx?carname=Alto&amp;carid=6"/>\n</urlMappings>\n</system.web>\n\nIf you add this if any page with this "~/Carmodel.aspx?carname=Alto&amp;carid=6" is replaced by "~/marutisuzuki-Alto".	0
3694722	3694676	How do I retrieve all filenames in a directory?	foreach (string s in Directory.GetFiles(path, "*.txt").Select(Path.GetFileName))\n       Console.WriteLine(s);	0
24229516	22891832	When calling a WCF channel from multiple threads some threads might get stuck for a long time	Parallel.For(0, 10, new ParallelOptions{MaxDegreeOfParallelism = 10}, i =>\n{\n     try\n    {\n        var result = channel.BeginSomeOperation();\n        channel.EndSomeOperation(result);\n    }\n    catch\n    {\n\n    }\n});	0
3802720	3802700	Get directory name based on current date	date.ToString("yyMM");	0
30630209	30624938	How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?	var poContent = ((object[])responseContent).Select(x => new PrivateObject(x)).ToArray();\n\nAssert.AreEqual("123", poContent[0].GetProperty("Thing1"));\nAssert.AreEqual("unit test", poContent[0].GetProperty("Thing2"));	0
19105444	19105417	Create new label on location of mouse position	private void form_MouseMove(object sender, MouseEventArgs e)\n    {\n        mouseY = e.Location.Y;\n        mouseX = e.Location.X;\n    }	0
30889423	30889197	Convert string value to english word	double value = 125.23;\nint dollars = (int)value;\nint cents = (int)((value - (int)value) * 100);\nConsole.WriteLine("{0} dollars and {1} cents", wordify(dollars), wordify(cents));	0
5908908	5908878	pass in filename into controller	data: { filename: "c:\\somefile.txt" }	0
1043846	1043802	Query Db from within a Linq Query - C#	var q = from c in recentOrdersXDoc.Descendants("prop")\n        let handle = c.Element("handle")\n        let clientTemplateID = (string)c.Element("TemplateID")\n        let client = DataContext.Clients\n            .Where(x=>x.ClientTemplateID == clientTemplateID)\n            .Select(x=>new {x.ClientID, x.ClientName}).Single()\n        select new ReturnResult()\n        {\n            ClientTemplateID = clientTemplateID,\n            Handle = resultref != null ?\n                   (string)resultref.Attribute("handle") : null,\n            ClientID = client.ClientID,\n            ClientName = client.ClientName\n        };	0
24071690	24071671	How to create (n) objects in c# based on loop	int n=99;\nDataTable[] DT = new DataTable[99];\n\nfor (int i = 0; i < n; i++)\n{\n    DT[i] = new DataTable();\n}	0
13721541	13706636	How to identify a Method in fxcop	// <Name>Method name MUST start with CAPITAL</Name>\nwarnif count > 0 \nfrom m in Application.Assemblies.WithName("TargetAssemblyName").ChildMethods()\nwhere \n  !m.IsSpecialName &&         // Remove getter and setter\n  !m.IsGeneratedByCompiler && // Discard methods generated by compiler\n  !m.ParentType.IsDelegate &&\n  !m.NameLike("^btn") &&      // Use regex here to discard btnOk_Click like method\n  !char.IsUpper(m.SimpleName[0])\nselect m	0
29124596	29121180	Manual set cookies using accesstoken/AuthenticationResult -like UseCookieAuthentication() owin middleware	result = await authContext.AcquireTokenAsync(resource, clientId, uc);\n\n                var principal = await new TokenHelper().GetValidatedClaimsPrincipalAsync(result.AccessToken);\n\n                var claimsIdentity = new ClaimsIdentity(principal.Claims, CookieAuthenticationDefaults.AuthenticationType);\n\n                var properties = new AuthenticationProperties();\n\n                HttpContext.GetOwinContext().Authentication.AuthenticationResponseGrant =\n                    new AuthenticationResponseGrant(claimsIdentity, properties);	0
9502788	9502544	Generate repeaters according to user inputs	var selectedChkboxCount = DataList1.Items.Cast<DataListItem>().\n                          Where(s => ((CheckBox)s.FindControl("checkboxName")).Checked).Count();	0
28682122	28681900	Parsing JSON rounds Negative Values	var settings = new JsonSerializerSettings();\nsettings.FloatParseHandling = FloatParseHandling.Decimal;\nstring json = @"{ ""rings"" : [  -9221300.3411999997, 4120326.8838  ] }";\nvar rss = JsonConvert.DeserializeObject(json, settings);	0
8070640	8070467	How do I do a linq query to find fields in a dataset that are present in every record of a set?	XDocument doc = XDocument.Parse("<set><item><a/><foo /><b/><c/></item><item><a/><foo /><b/><c/></item></set>");\nvar items = \n          doc.Descendants("item")\n          .Select(x=>x.Descendants().Select(y=>y.Name).ToList()).ToList();\n var selectValue = items[0];\n foreach (var item in items)\n {\n    selectValue = selectValue.Intersect(item).ToList();\n }	0
2549660	2549624	C# - Take Screenshot based on a Timer	bmpScreenshot.Save(Environment.GetFolderPath\n    (Environment.SpecialFolder.DesktopDirectory) \n    + @"\ScreenCaptures\newfile.bmp", ImageFormat.Png);	0
12590836	12585430	Can the picturebox be used to display vector based images?	Public Class Form1\n    Public Sub New()\n        InitializeComponent()\n        PictureBox1.Dock = DockStyle.Fill\n        image = New System.Drawing.Imaging.Metafile(New System.IO.MemoryStream(My.Resources.schoolbus))\n    End Sub\n\n    Private Sub PictureBox1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint\n        e.Graphics.DrawImage(image, New Rectangle(Point.Empty, PictureBox1.ClientSize))\n    End Sub\n\n    Private Sub PictureBox1_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Resize\n        PictureBox1.Invalidate()\n    End Sub\n\n    Private image As System.Drawing.Imaging.Metafile\n\nEnd Class	0
18157756	18156782	Upload XML file by Web Service	public string UploadXml(string xmlString) {\n  using (var connection = new SqlConnection(myConnectionString)) {\n    using (var command = connection.CreateCommand()) {\n      command.CommandText = "INSERT INTO MyTable (xmlColumn) VALUES (@xmlText)";\n      command.Parameters.AddWithValue("@xmlText", xmlString);\n      // etc.\n    }\n  }\n}	0
2619902	2619535	How do you disable a DataGridView's keyboard shorcuts?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{     \n  if (keyData == (Keys.Control | Keys.H))\n  {\n    //ShowReplaceDialog() or whatever it is you want to do here.\n    return true; //we handled the key\n  }\n\n  return base.ProcessCmdKey(ref msg, keyData); //we didn't handle it\n}	0
3447401	3030106	haw to get wan ip for my machine programatically with vs 2008 c#	public string getdata()\n{ \n    UTF8Encoding utf8 = new UTF8Encoding();\n    WebClient webClient = new WebClient();\n    String externalIp = utf8.GetString(webClient.DownloadData("http://automation.whatismyip.com/n09230945.asp"));\n    return externalIp;\n}	0
33119890	33118632	How to add and show images in a WPF TreeView?	var bitmapImage = new BitmapImage(new Uri("pack://application:,,,/Resources/ok-01.png"));	0
15113389	15113352	Find out dependencies of all DLLs?	Assembly.GetReferencedAssemblies	0
34055486	34054662	Get a file url without webbrowser - C#	static void Main()\n{\n    var fileUrls = GetFileUrl(@"http://stackoverflow.com/questions/34054662/get-a-file-url-without-webbrowser-c-sharp", @"https://www.gravatar.com/");\n\n    foreach (string url in fileUrls)\n    {\n        Console.WriteLine(url);\n    }\n\n    Console.ReadKey();\n}\n\npublic static IEnumerable<string> GetFileUrls(string url)\n{\n    var document = new HtmlWeb().Load(url);\n    var urls = document.DocumentNode.Descendants("img")\n                                    .Select(e => e.GetAttributeValue("src", null))\n                                    .Where(s => s.ToLower().StartsWith(pattern));\n\n    return urls;\n}	0
5038134	5038018	How to check a particular user has log on as service right programmatically	TokenInformationClass == TokenPrivileges	0
11134582	11134312	WPF DataGrid and multithreading	public class DelayedDataGridTextColumn : DataGridTextColumn\n{\n    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)\n    {\n        var textBlock = new TextBlock();\n        textBlock.SetValue(FrameworkElement.StyleProperty, ElementStyle);\n\n        Dispatcher.BeginInvoke(\n            DispatcherPriority.Loaded,\n            new Action<TextBlock>(x => x.SetBinding(TextBlock.TextProperty, Binding)),\n        textBlock);\n        return textBlock;\n    }\n}	0
9944190	9943929	How to append ChildNodes of a xml documents into root of another (web services)?	xmlDom1.DocumentElement.importNode(xmlNode, true);	0
5247873	5247798	Get list of local computer usernames in Windows	using System.Management;\n\nSelectQuery query = new SelectQuery("Win32_UserAccount");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\nforeach (ManagementObject envVar in searcher.Get())\n{\n     Console.WriteLine("Username : {0}", envVar["Name"]);\n}	0
29245137	29245115	Regular Expression to find a GUID string in a txt file with "id=" attached to it	MatchCollection guids = Regex.Matches(s, @"id=""(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}""");	0
24572559	24572420	labels color change in a loop. C#	private void Form1_Load(System.Object sender, System.EventArgs e)\n{\nUpdateLabelFG(this.Controls, Color.Red);\n}\n\n\nprivate void UpdateLabelFG(ControlCollection controls, Color fgColor)\n{\nif (controls == null)\n    return;\nforeach (Control C in controls) {\n    if (C is Label)\n        ((Label)C).ForeColor = fgColor;\n    if (C.HasChildren)\n        UpdateLabelFG(C.Controls, fgColor);\n}\n}	0
21174013	21173893	Split String with more Symbols	var res = string.Join(", ", data.Substring(data.IndexOf("@") + 1).Replace("$", " ").Split('&'));	0
31121183	31120978	Data from SQL reader to datatable - Invalid attempt to call Read when reader is closed	DataTable myDataTable = new DataTable();\n\n\n        using (SqlConnection myConnection = new SqlConnection(yourDBconn)\n        {\n                yourDBconn.Open();\n                using (SqlDataAdapter myAdapter = new SqlDataAdapter(strYourQuery, yourDBconn))\n                {\n                    myAdapter.Fill(myDataTable);\n                }\n            }\n        }	0
6409079	6409051	Use substring function or a regular expression	Substring()	0
14318605	14318461	How to show hide a column of GridView?	protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)\n    {\n\n        try\n        {\n            DataTable dt = (DataTable ) GridView1.DataSource;\n            if (!dt.Columns.Contains("COLLUMN_YOU_WANNA_HIDE")) return;\n            int j = dt.Columns.IndexOf("COLLUMN_YOU_WANNA_HIDE");\n            e.Row.Cells[j].Visible = false;\n            e.Row.Cells[j].Width = 0;\n        }\n        catch (Exception)\n        {\n\n\n        }\n\n    }	0
22899508	22899324	WPF putting message	lbStatus.Content = "Synchronizing Customers";\nlbStatus.Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);\nThread.Sleep(1000);\nlbStatus.Content = "Synchronizing Estimates";	0
5461308	5461229	use dateTimePIcker to set timer interval	timer.Interval = dateTimePicker.Value.TimeOfDay.TotalMilliseconds	0
30290576	30289983	Opening Python files via Visual Basic 2010	System.Diagnostics.Process.Start("C:\Users\Seth Connell\Desktop\J.A.R.V.I.S\Jarvis.py")	0
26888496	26886850	Trying to get all entity fields from a CRM record. C#	query.ColumnSet = new ColumnSet(true);	0
13953761	13953724	How to get files from exact subdirectories	var filesInDirectSubDirs = Directory.GetDirectories(RootDirectory)\n    .SelectMany(d=>Directory.GetFiles(d));\n\nforeach(var file in filesInDirectSubDirs)\n{\n    // Do something with the file\n    var fi = new FileInfo(file);\n    ProcessFile(fi);\n}	0
23735012	23734904	How to fix windows phone page navigation failed?	NavigationService.Navigate(new Uri("/Timetable.xaml", UriKind.Relative));	0
4873035	4873008	How to implement this C# class hierarchy	new static	0
20211190	20211050	c# to split Dynamic arrays	string [] emailList = sourceEmail.Split(';');\n\nfor (int i = 0; i < emailList.Length; i++)\n{\n    switch (i)\n    {\n        case 0:\n            this.email0 = emailList[i];\n            break;\n        case 1:\n            this.email1 = emailList[i];\n            break;\n       ....//Do it for all variables\n    }\n}	0
9883689	9821755	Messagebox from master page	linkbutton1.OnClientClick ="javascript:alert('Hello')"	0
14476128	14460649	MS Project 2010 AddIn: Get/Edit Custom Enterprise Field-Entries in Client without PSI	task.GetField(ThisApplication.FieldNameToFieldConstant("MYCOMPANY_project_technicalSupervisor")) does the trick.	0
15093292	15093261	How can i remove \n\r from a string?	myString = myString.Replace("\n", string.Empty).Replace("\r", string.Empty);	0
23302388	23302306	how to disable datagridview mouse click event for headers in c#	private void dataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)\n{\n    if (e.RowIndex != -1)\n    {\n        textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();\n    }\n    else\n    {\n        textBox1.Text = "";\n    }\n}	0
1967448	1967434	Converting wav to mp3 - ASP.NET	public void mciConvertWavMP3(string fileName, bool waitFlag) {\n        string outfile= "-b 32 --resample 22.05 -m m \""+pworkingDir+fileName + "\" \"" + pworkingDir+fileName.Replace(".wav",".mp3")+"\"";\n        System.Diagnostics.ProcessStartInfo psi=new System.Diagnostics.ProcessStartInfo();\n        psi.FileName="\""+pworkingDir+"lame.exe"+"\"";\n        psi.Arguments=outfile;\n        psi.WindowStyle=System.Diagnostics.ProcessWindowStyle.Minimized;\n        System.Diagnostics.Process p=System.Diagnostics.Process.Start(psi);\n        if (waitFlag)\n        {\n        p.WaitForExit();\n        }\n }	0
24238454	24216895	Decrypt Querystring Parameters and Map it to controller	public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n     var queryStringQ =  Server.UrlDecode(filterContext.HttpContext.Request.QueryString["q"]);\n if (!string.IsNullOrEmpty(queryStringQ))\n        {\n            // Decrypt query string value\n            var queryParams = DecryptionMethod(queryStringQ);\n        }\n }	0
6456301	6455568	How to bind two cloumns values in dropdown with separate comma(,)	var ddlclientnames = (from ddl in mortgageentity.Clients \n                select new { id = ..., FullName = FirstName + Lastname}.ToList();	0
3737259	3737123	How to Dynamically Create Tabs	var page = new TabPage(textBox1.Text);\n        var browser = new WebBrowser();\n        browser.Dock = DockStyle.Fill;\n        page.Controls.Add(browser);\n        tabControl1.TabPages.Add(page);\n        browser.Navigate("http://stackoverflow.com");\n        page.Select();	0
31196929	31196690	Exit original function from another procedure	void myFunction()\n{\n    if(!checkLogin())\n       return;    //make sure a user is logged in\n    doOtherStuff();  //continue with other stuff\n}\nvoid checkLogin()\n{\n    if(loggedIn==false)\n    {\n        return false; // exit myFunction\n    }\n    return true;\n}	0
5813484	5742210	text between any tag	while (reader.Read()){\n   if(reader.NodeType == XmlNodeType.Element && reader.Name == "name"){                               \n       this.tagXml.Append("<").Append(reader.Name).Append(">");\n       currentTag = reader.Name.Trim();\n       //first loop go through this\n   }                   \n   if(reader.NodeType== XmlNodeType.Text){\n      //second loop go through this\n      if (currentTag == "name"){\n        this.tagXml.Append(reader.Value);\n      }\n   }\n}	0
26764995	26764948	How initialize an event	public void Calling()\n{\n    if (Message != null)\n        Message("Hello World!");\n}	0
12710042	12709348	How to deserialize a json array with unfixed name in JSON.NET	var result = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);\n\nforeach (var item in result)\n{\n    foreach (var kv in item)\n    {\n        Console.WriteLine(kv.Key + ": " + kv.Value);\n    }\n}	0
27087101	27086741	How do I deserialize the bytes I've sent?	public override BaseMassage DeSerialize(byte[] data)\n{\n        MemoryStream stream = new MemoryStream(data, 3, data.Length - 3);\n        BinaryFormatter formatter = new BinaryFormatter();\n        formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;\n        formatter.Binder = new VersionConfigToNamespaceAssemblyObjectBinder();\n        RadarMassage obj = (RadarMassage)formatter.Deserialize(stream);\n        return obj;\n}	0
31391340	31390176	C# removing duplicate HTML rows	List<string>	0
7798869	7798840	Regex, match text inside a tag, then match all text not in that tag both from same string?	calledregex.Match(text).Groups[1].Value	0
18275807	18275530	How to check if the tape starts with special characters	// [drive_letter]:\ or  \\[server]\ or [drive name]:\\nprivate const string PathPattern = "^[A-z]:[\\\\/]|^\\\\|^.*[A-z]:[\\\\/]";\nvar matchMaker = new Regex(PathPattern);\nvar success = matchMaker.Matches(inputPath);	0
14944725	14944639	How do I check a not-null query string against a sql database in c# for ASP.NET?	protected void Page_Load(object sender, EventArgs e)\n{\n    using (KidsEntities detailEntities = new KidsEntities())\n    {\n        string imgPath = ConfigurationManager.AppSettings["imagePath"];\n        string KidNum = Request.QueryString["ChildNum"].ToString();\n\n        var KidSpecific = from Kid in detailEntities.Kids\n                          where Kid.Number == KidNum\n                          ... ;\n\n        var KidSpecificList = KidSpecific.ToList();\n\n        //Redirect if there are no results!\n        if (KidSpecificList.Count() < 1)\n            Response.Redirect("RedirectPage.aspx");\n\n        DescRepeater.DataSource = KidSpecificList;\n        DescRepeater.DataBind();\n    }\n}	0
12994996	12994833	BackgroundWorker ProgressChanged in a form being triggered from a separate class	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n     ConnectClass conObject= new ConnectClass();\n     backgroundWorker.ReportProgress(30, "Connecting ...");\n     conObject.Connect();\n     backgroundWorker.ReportProgress(30, "Connected."+"\n Executing query");\n     conObject.Execute();\n     backgroundWorker.ReportProgress(40, "Execution completed.");\n}	0
16158141	16157773	Calculating ticks of TimeSpan	var tickOffset = clip.Keyframes[beginFrame].Time.Ticks;\n// this is your 'region' variable\nvar adjustedFrames = clip.Keyframes\n    .Skip(beginFrame)\n    .Take(endFrame - beginFrame)\n    .Select(kf => new Keyframe { \n        Time = TimeSpan.FromTicks(kf.Time.Ticks - tickOffset),\n        OtherProperty = kf.OtherProperty            \n    })\n    .ToList();\nvar durationTicks = adjustedFrames.Max(k => k.Time.Ticks);	0
3038787	3038733	How can I display more info in an error message when using NUnit Assert in a loop?	Assert.AreEqual(0, widget.SomeValue,\n                "Widget " + widget + " should have SomeValue of 0");	0
5981753	5980644	Put transient entity in cache without persisting it	public EntityEntry AddEntry(object entity, Status status, object[] loadedState, \n                            object rowId, object id, object version, \n                            LockMode lockMode, bool existsInDatabase, \n                            IEntityPersister persister, \n                            bool disableVersionIncrement, \n                            bool lazyPropertiesAreUnfetched)	0
16866947	16862100	Selenium - Get elements html rather Text Value	var element = driver.FindElements(By.ClassName("sa_wr"));\nIJavaScriptExecutor js = driver as IJavaScriptExecutor;\nif (js != null) {\n    string innerHtml = (string)js.ExecuteScript("return arguments[0].innerHTML;", element);\n}	0
8172305	8171830	How to set Foreground Color in a ListBox single element?	private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e)\n{\n    if (e.Index >= 0 && e.Index < listaJogadores.Items.Count) {\n        e.DrawBackground();\n        Brush textBrush = SystemBrushes.ControlText;\n        Font drawFont = e.Font;\n        bool playerFound = false;\n        string nick = (string)listaJogadores.Items[e.Index];\n        foreach (Game game in games) {\n            if (game.players.Any(p => p.getNick() == nick)) {\n                playerFound = true;\n                break;\n            }\n        }\n        if (playerFound) {\n            textBrush = Brushes.Red;  //RED....  \n            if ((e.State & DrawItemState.Selected) > 0)\n                drawFont = new Font(drawFont.FontFamily, drawFont.Size, FontStyle.Bold);\n        } else if ((e.State & DrawItemState.Selected) > 0) {\n            textBrush = SystemBrushes.HighlightText;\n        }\n        e.Graphics.DrawString(nick, drawFont, textBrush, e.Bounds);\n        e.DrawFocusRectangle();\n    }\n}	0
24513613	24509485	Creating buttons with PayPal	protected void BuyButton_Click(object sender, EventArgs e)\n{\n   string url = TestMode ? \n      "https://www.sandbox.paypal.com/us/cgi-bin/webscr" : \n      "https://www.paypal.com/us/cgi-bin/webscr";\n\n   var builder = new StringBuilder();\n   builder.Append(url);\n   builder.AppendFormat("?cmd=_xclick&business={0}", HttpUtility.UrlEncode(Email));\n   builder.Append("&lc=US&no_note=0&currency_code=USD");\n   builder.AppendFormat("&item_name={0}", HttpUtility.UrlEncode(ItemName));\n   builder.AppendFormat("&invoice={0}", TransactionId);\n   builder.AppendFormat("&amount={0}", Amount);\n   builder.AppendFormat("&return={0}", HttpUtility.UrlEncode(ReturnUrl));\n   builder.AppendFormat("&cancel_return={0}", HttpUtility.UrlEncode(CancelUrl));\n   builder.AppendFormat("&undefined_quantity={0}", Quantity);\n   builder.AppendFormat("&item_number={0}", HttpUtility.UrlEncode(ItemNumber));\n\n   Response.Redirect(builder.ToString());\n}	0
19239407	19239214	how to get values of particular xml node in c# loop and replace it with other value	XmlDocument doc = new XmlDocument();\n        doc.Load(Server.MapPath("~/temp.xml"));\n\n        //Selecting node with number='3'\n        XmlNodeList fromselectors;\n        XmlElement root = doc.DocumentElement;\n        fromselectors = root.SelectNodes("SearchResults/FlightSegments/Flights/LegDetails/Leg/FromSector");\n\n        con.Open();\n        cmd.Connection = con;\n        foreach (XmlNode n in fromselectors)\n        {                                   \n           string xmls = n.InnerXml;\n           cmd.CommandText = "select City from CCode where Code='" + xmls + "'";\n           string city = cmd.ExecuteScalar().ToString();\n           n.InnerText = city;\n        }\n        con.Close();\n        doc.Save(Server.MapPath("~/temp.xml"));	0
26657925	26657819	Finding Dictionary values based on object/type members	var nulls = test.Count(c => c.Value == null);\nvar ones = test.Count(c => c.Value != null && c.Value.ID == "1");	0
33950863	33950781	Add <li> to <ul> tag from code behind C# ASP NET	private void AddMenuItem(string text, string link)\n    {\n        HtmlGenericControl li = new HtmlGenericControl("li");\n        menu.Controls.Add(li);\n\n        HtmlGenericControl anchor = new HtmlGenericControl("a");\n        anchor.Attributes.Add("href", link);\n        anchor.InnerText = text;\n\n\n\n        li.Controls.Add(anchor);\n    }\n\n    AddMenuItem("text","link");\n    AddMenuItem("text2","link2");\n    AddMenuItem("text3","link3");	0
13099578	13098702	Cancel/Clear button event Post Back And Trying To Validate Fields	if (txtPhone.Text != "")\n            {\n                lblErrorIndicator.Visible = true;\n                lblErrorIndicator.Text = "*Valid 10 digit phone number required";\n            }\n        }	0
8574163	8561825	Call JavaScript from Silverlight hosted in IFrame	ScriptObject parent = HtmlPage.Window.GetProperty("parent") as ScriptObject;\nif (parent != null)\n{\n     parent.Invoke("testMethod");\n}	0
30710104	30709145	Controlling/moving an object in a circular motion in Unity	float timeCounter = 0;\n\nvoid Update () {\n    timeCounter += Input.GetAxis("Horizontal") * Time.deltaTime; // multiply all this with some speed variable (* speed);\n    float x = Mathf.Cos (timeCounter);\n    float y = Mathf.Sin (timeCounter);\n    float z = 0;\n    transform.position = new Vector3 (x, y, z);\n}	0
28147161	28147080	How to write Javascript from code behind at the end of HTML page	ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:someFunction();", true);	0
8662307	8662194	Using LINQ in an Update Method - trouble with where clause	where updatedObjects.Any(uo => uo.ID == o.ID)	0
6875614	6873822	AutoMapper with a list data from IDataReader	using (IDataReader dr = DatabaseContext.ExecuteReader(command))\n    {\n        if (dr.HasRows)\n        {\n            AutoMapper.Mapper.CreateMap<IDataReader, ProductModel>();\n            return AutoMapper.Mapper.Map<IDataReader, IList<ProductModel>>(dr);\n        }\n\n        return null;\n    }	0
10530228	10529997	Load data from datareader	DataTable dt = dr.GetSchemaTable();\nforeach (DataRow myField in dt.Rows) \n{\n    var name = myField["ColumnName"];\n    var type = myField["DataTypeName"];\n    Console.WriteLine("{0} {1}", name, type);\n}	0
1869803	1869784	Grab HTML code from web	WebClient client = new WebClient();\nString htmlCode = client.DownloadString("http://born2code.net");	0
137675	137661	How do you do polymorphism in Ruby?	class Animal\n    def MakeNoise\n        return ""\n    end\n    def Sleep\n        print self.class.name + " is sleeping.\n"\n    end\nend\n\nclass Dog < Animal\n    def MakeNoise\n        return "Woof!"\n    end\nend\n\nclass Cat < Animal\n    def MakeNoise\n        return "Meow!"\n    end\nend\n\nanimals = [Dog.new, Cat.new]\nanimals.each {|a|\n    print a.MakeNoise + "\n"\n    a.Sleep\n}	0
16002436	16002313	How to get list of ALL network adapters?	[LTE]\nEncoding=1\nPBVersion=1\nType=1\nAutoLogon=0\n...\n\n[PPPoE]\nEncoding=1\nPBVersion=1\nType=5\nAutoLogon=0	0
27671048	27670811	How do I allocate GCHandle to structure when structure contains bool	[StructLayout(LayoutKind.Sequential)]\npublic class MyStruct\n{\n    private byte _test;\n    public bool Test {\n       get { return _test != 0; }\n       set { _test = value ? 1 : 0; }\n    }\n}	0
25347251	25346542	How end user select Dock, Anchor, Location,	dockStyleComboBox.DataSource = Enum.GetValues(typeof (DockStyle));\ndockStyleComboBox.SelectedIndexChanged += OnDockStyleChanged;\n\nanchorStyleComboBox.DataSource = Enum.GetValues(typeof (AnchorStyles));\n\nprivate void OnDockStyleChanged(object sender, EventArgs eventArgs)\n{\n   dockStyleComboBox.Dock = (DockStyle)dockStyleComboBox.SelectedItem;\n}	0
5193031	5192983	calculating X Y movement based on rotation angle?	X += Speed * Math.Cos(angle);\nY += speed * Math.Sin(angle);	0
2885743	2885707	How can I switch between 2 Connection Strings in my Web.Config (Activate one for DBML)	string connectionString = HttpContext.Current.Request.IsLocal ? \n    ConfigurationManager.ConnectionStrings["CS_Local"].ConnectionString :\n    ConfigurationManager.ConnectionStrings["CS_Production"].ConnectionString;\nyourDataContext = new YourApplicationDataContext(connectionString);	0
13354292	13350171	How to Leave ToolStripMenu Open After Clicking an Item	ParentMenu.DropDown.AutoClose = false;	0
31308943	31305898	Three table query using Linq/Lambda in EF	var te = DbContext.Set<start>().Where(a => a.acctId == id).Select(s => new\n     {\n         name = s.detail.name,\n         descs = s.detail.items.Select(i => i.desc).ToList()\n     });	0
12282755	12239119	Disable selection and drop down symbol of a tool strip drop down button	toolStripDropDownButton1.ShowDropDownArrow = false;	0
19975560	19974763	Get values and keys in json object using Json.Net C#	string key = null;\nstring value = null;\n\nforeach(var item in inner)\n{\n    JProperty questionAnswerDetails = item.First.Value<JProperty>();\n\n    var questionAnswerSchemaReference = questionAnswerDetails.Name;\n\n    var propertyList = (JObject)item[questionAnswerSchemaReference];\n\n    questionDetails = new Dictionary<string, object>();\n\n    foreach (var property in propertyList)\n    {\n         key = property.Key;\n         value = property.Value.ToString();\n    }\n\n    questionDetails.Add(key, value);               \n}	0
29864455	29863012	Mapping joined Domain Model to View Model using Automapper	public static List<TDestination> ToEntity<TDestination>(this List<object> OBJSource)\n    {\n        List<TDestination> destination = new List<TDestination>();//Handling the null destination\n\n        foreach (object source in OBJSource)\n            destination.Add(AutoMapper.Mapper.DynamicMap<TDestination>(source));\n\n        return destination;\n    }	0
2804853	2804818	Ways to access a 32bit DLL from a 64bit exe	class Program\n{\n    static void Main(string[] args)\n    {\n        using(ServiceHost host = new ServiceHost(typeof(MyService), new Uri[0]))\n        {\n            host.Open();\n            Console.ReadKey();    \n        }\n    }\n}	0
3150817	3150782	Find out if a object has a specific class as an ancestor	if (form is MyCustomFormType) {\n    // form is an instance of MyCustomFormType!\n}	0
15916992	15916941	Collision through for loop	if (bulletBounds[x].Intersects(alienBounds[y]))\n {\n     alienPosition.RemoveAt(y);\n     alienBounds.RemoveAt(y);\n     bulletBounds.RemoveAt(x);\n     hit++;\n     break;\n }	0
22299324	22295590	Combining data from different tables in one Datagridview	public class ProductsRecipes\n{\n    public virtual int Id { get; set; }\n    public virtual int ProductId { get; set; }\n    public virtual string ProductName { get; set; }\n    public virtual Double ProductCost { get; set; }\n    public virtual double Weight { get; set; }\n}	0
31331023	31318055	Find NaN in list of floats and set previous and next element to NaN	var theNewNanIndexes = Enumerable.Range( 0, l.Count )\n        .Where( num => float.IsNaN(l[num]))\n        .SelectMany( num => new[]{ num - 1, num + 1  } )\n        .Where( num => num >= 0 && num < l.Count) ;\n\n\nll = new List<float>(l);\ntheNewNanIndexes.ToList().ForEach( num => ll[num] = float.NaN );	0
26931522	26876465	Using migrations with separate contexts for regular model and Identity	enable-migrations	0
33625521	33547279	How to open "Microsoft Edge" from c# and wait for it to be closed?	//Edge process is "recycled", therefore no new process is returned.\n            Process.Start("microsoft-edge:www.mysite.com");\n\n            //We need to find the most recent MicrosoftEdgeCP process that is active\n            Process[] edgeProcessList = Process.GetProcessesByName("MicrosoftEdgeCP");\n            Process newestEdgeProcess = null;\n\n            foreach (Process theprocess in edgeProcessList)\n            {\n                if (newestEdgeProcess == null || theprocess.StartTime > newestEdgeProcess.StartTime)\n                {\n                    newestEdgeProcess = theprocess;\n                }\n            }\n\n            newestEdgeProcess.WaitForExit();	0
15500129	15500033	How to circumvent unused out parameters values?	public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dictionary, TKey key)\n{\n    TValue dummy;\n    return dictionary.TryRemove(key, out dummy);\n}	0
21173933	21173769	Get Selected Item from Windows Phone listbox in Hold event	private void favouriteSelectionHold(object sender, System.Windows.Input.GestureEventArgs e)\n{\n    string n = (e.OriginalSource as TextBlock).Text;\n}	0
31003664	30994154	unable to display application icon for c# project(Vs10 windows application)	this.Icon = new System.Drawing.Icon(ZebraAES256EncryptionUtility.Properties.Resources.icon,Size);	0
10012665	9830679	Render a UserControl to an Image with a different size then the one at which it is displayed?	UserControl userControl = pane.Content;\n        ContentPresenter visualParent = (VisualTreeHelper.GetParent(userControl) as ContentPresenter);\n\n        double oldWidth = visualParent.Width;\n        double oldHeight = visualParent.Height;\n\n        visualParent.Width = BitmapImageWidth;\n        visualParent.Height = BitmapImageHeight;\n        visualParent.UpdateLayout(); // This is required! To apply the change in Width and Height\n\n        WriteableBitmap bmp = new WriteableBitmap(BitmapImageWidth, BitmapImageHeight);\n        bmp.Render(userControl, null);\n        bmp.Invalidate(); // Only once you Invalidate is the Control actually rendered to the bmp\n        RadBitmap radImage = new RadBitmap(bmp);\n\n        visualParent.Width = oldWidth; // Revert back to original size\n        visualParent.Height = oldHeight; // Revert back to original size\n\n        return new PngFormatProvider().Export(radImage); // returns the Image as a png encoded Byte Array	0
4562837	4562067	SQL table referencing multiple foreign keys, while defining order and guaranteeing referential integrity	create table OutputTable (\n  OutputID <datatype> <nullability>,\n LogicID <datatype> <nullability>,\n ActionID <datatype> <nullability>,\n ActionTypeID <datatype> <nullability>,\n Sequence <datatype> <nullability>,\n  CommandActionID as CASE WHEN ActionTypeID = <Command Action> then ActionID END PERSISTED,\n  WVActionID as CASE WHEN ActionTypeID = <Write Variable Action> then ActionID END PERSISTED,\n    constraint FK_Output_CommandActions FOREIGN KEY (CommandActionID) references CommandTable (CommandID)\n)	0
3984707	3984688	is there any way to know the position of my cursor - in TextBox control?	TextBox.SelectionStart	0
23510320	23426711	How to get processID from Process.start()	try\n{\n    Process[] javaProcList = Process.GetProcessesByName("java");\n    foreach (Process javaProc in javaProcList)\n    {\n        javaProc.Kill();\n        javaProc.Close();\n        javaProc.Dispose();\n\n        Console.WriteLine("StopJar -Java Process Stopped ");\n        log.Debug("StopJar -Java Process Stopped ");\n     }\n }\n catch (Exception exp)\n {\n     log.Error("StopJar - Unable to kill Java Process", exp);\n     Console.WriteLine("Error while closing: " + exp.Message);\n  }	0
16533536	16533186	Using Binding converter to display and update a property in silverlight	public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n      {\n           if (value == null)\n              return false;\n          else\n          {\n              // Assumes a RowType has been passed as the bound value\n              string val = (string)value;\n              double doubleValue = double.TryParse(val, out doubleValue) ? doubleValue : 0;\n              return doubleValue * 40;\n              }\n          }\n      }	0
5851372	5851004	Join LINQ with a List<> in select new	var query1 = from a in db.Cabinets\n  from b in db.Commodities\n  from e in db.sArticleNumbers\n  from d in KurvInnhold\n  where\n  KurvInnhold.Select(k => k.VareKj?pt).Contains(e.ArtNum) &&\n  a.ArticleNumberID == e.ID &&\n  a.ArticleNumberID == b.ArticleNumberID\n\n select new\n  {\n       ArtNum = e.ArtNum,\n       Price = b.Price,\n       ModelName = a.ModelName,\n  }.ToList();\n\nvar query2 = \n  from a in query1\n  join b in KurvInnhold on a.ArtNum equals b.VareKj?pt\n  select new\n  {\n       BestiltAntall = b.AntallValgt,\n       Price = a.Price,\n       ModelName = a.ModelName,\n  };\n\nHandlekurv1.DataSource = query2;\nHandlekurv1.DataBind();	0
8286504	8286476	how to paste text to a Form's RichTextBox from another Form's Thread?	mainForm.BeginInvoke(mainForm.logDelegate,destination,fileName,bytesSent, true);	0
18648355	18648290	How can I make a text box that changes it's fore color based on what's entered in c#?	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        int valueCheck = 0;\n        if (textBox1.TextLength >= 1)\n        {\n            Int32.TryParse(textBox1.Text, out valueCheck);\n        }\n        if (valueCheck < 1)\n        {\n            textBox1.ForeColor = Color.Red;\n        }\n        else if (valueCheck > 0)\n        {\n            textBox1.ForeColor = Color.Black;\n        }\n        valueCheck = 0;\n    }	0
3719636	3719562	How to prevent a WPF app from loading?	protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n        if (MyCondition)\n        {\n            ShowSomeDialog("Hey, I Can't start because...");\n            this.Shutdown();\n        }\n    }	0
310179	310160	Passing Interface in a WCF Service?	[ServiceKnownType(typeof(ConcreteDeviceType)]	0
16169036	16168844	Get a list of all the items based on the latest entry	var result = m_Db.PriceList.GroupBy(r => r.m_BookID)\n                 .Select(r=> new \n                 { \n                     BookID = r.OrderByDescending(t=> t.m_PriceListDate).First().m_BookID,\n                     Date = r.OrderByDescending(t=> t.m_PriceListDate).First().m_PriceListDate,\n                 });	0
27824009	27823817	Set field DateTime to show the date and time in the format dd/mm/yyyy hh:mm:ss	var dt = DateTime.Now;\nstring str = dt.ToString("yyyy-MM-dd hh:mm:ss"); //(For month use caps 'MM')	0
8566249	8565622	Checking if an e-mail had already been added to a database	bool alreadyRegistered = (ReturnIntegerFromDatabase("select count(*) from table where email=\"emailAddress\"") > 0)\nif(alreadyRegistered)\n    alert();\nelse\n    register();	0
15850761	15850704	How can I use text property of dynamic created textfield?	List<string> TextBoxesName=new List<string>();\n            foreach (Control item in groupBox1.Controls)\n            {\n                if (item is TextBox)\n                {\n                    TextBoxesName.Add((item as TextBox).Text);\n                }\n            }	0
23176314	23174759	Parsing a JSON array with a Dictionary.ValueCollection	public class RootJson\n    {\n        public List<Circle> CircleList { get; set; }\n    }\n\n    public class Circle\n    {\n        public int Density { get; set; }\n        public int Friction { get; set; }\n        public int Bounce { get; set; }\n        public Filter CategoryBits { get; set; }\n        public List<double> Shape { get; set; }\n    }\n\n    public class Filter\n    {\n        public int CategoryBits { get; set; }\n        public int MaskBits { get; set; }\n    }\n\n    private void button4_Click(object sender, EventArgs e)\n    {\n        string Json = System.IO.File.ReadAllText(@"JsonFilePath");\n        RootJson JCircle = JsonConvert.DeserializeObject<RootJson>(Json);\n        Debug.Print(JCircle.CircleList.Count.ToString());\n    }	0
27828534	27803575	C# Reference Excel Worksheet index in a select statement	OleDbConnection MyConnection;\nDataSet DtSet;\nOleDbDataAdapter MyCommand;\nMyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tbFileName.Text + ";Extended Properties=Excel 12.0;");\n\nMicrosoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); \n\n//get the workbook\nMicrosoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(tbFileName.Text); \n\n//get the first worksheet\nMicrosoft.Office.Interop.Excel.Worksheet wSheet = excelBook.Sheets.Item[1]; \n\n//reference the name of the worksheet from the identified spreadsheet item\nMyCommand = new OleDbDataAdapter("select * from [" + wSheet.Name + "$]", MyConnection);	0
11980330	11716932	Multi Level Tree in Umbraco Custom Section	const string PARENT_ID = "10"; // The ID of the node that has child nodes\n\npublic override void Render(ref XmlTree tree)\n{\n  if (this.NodeKey == PARENT_ID) // Rendering the child nodes of the parent folder\n  {\n    // Render a child node\n    XmlTreeNode node = XmlTreeNode.Create(this);\n    node.NodeID = "11";\n    node.Text = "child";\n    node.Icon = "doc.gif";\n    node.Action = ...\n    tree.Add(node);\n  }\n  else // Default (Rendering the root)\n  {\n    // Render the parent folder\n    XmlTreeNode node = XmlTreeNode.Create(this);\n    node.NodeID = PARENT_ID;\n    node.Source = this.GetTreeServiceUrl(node.NodeID);\n    node.Text = "parent";\n    node.Icon = "folder.gif";\n    tree.Add(node);\n  }\n}	0
9506652	9505681	Compare 2 XML Files	var doc1 = XDocument.Load(infile1);\nvar doc2 = XDocument.Load(infile2);\nvar dict =  doc1.Root.Elements("Event").ToDictionary(el => \n    el.Attribute("id").Value);\ndoc2.Root.Elements("Event").ToList().ForEach(el => {\n    XElement el2;\n    if (dict.TryGetValue(el.Attribute("id").Value, out el2) &&\n        !el.Attributes().Select(a => new { a.Name, a.Value }).Except(\n        el2.Attributes().Select(a => new { a.Name, a.Value })).Any()) \n            el.Remove(); \n});\ndoc2.Save(outfile);	0
26576161	26576111	Compare two int arrays	class Test\n{\n    public bool theSameInBoth(int[] a, int[] b)\n    {\n        if (a.Length == b.Length)\n        {\n            for (int i = 0; i < a.Length; i++)\n            {\n                if (a[i] != b[i])\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        return false;\n    }\n}	0
2643445	2643413	How to increment the string value during run time without using dr.read() and store it in the oledb db?	private string jid  = string.Empty;	0
28860912	28860860	Getting a count from Linq query with group by	source = grp.Key.INPUT_SOURCE,	0
32357126	32356871	Surround string elements with " not using any loops	String source = "ololo with=1 dddd with=2 blablabla";\n  // surround numbers by apostrophes: 1 -> '1', 123 -> '123'\n  String result = Regex.Replace(source, @"\d+", \n    (MatchEvaluator) ((match) => "'" + match.Value + "'"));	0
12349385	12349174	How to monitor when user launches a windows application like Excel in c#	private static void lookForExcel()\n{\n    WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");\n    ManagementEventWatcher watcher = new ManagementEventWatcher(query);\n    watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);\n    watcher.Start();\n    Console.ReadLine();\n    watcher.Stop();\n}\n\nstatic void watcher_EventArrived(object sender, EventArrivedEventArgs e)\n{\n    string instanceName = ((ManagementBaseObject)e.NewEvent["TargetInstance"])["Name"].ToString();\n    if (instanceName.ToLower()=="excel.exe")\n    {\n        Debug.WriteLine("Excel has been started ...");    \n    }            \n}	0
13746113	13740443	Device Orientation in Windows Phone 8	angle = Math.Atan2(-x,y) * 180.0 / Math.PI;	0
12997700	12997658	c# how to make periodic events in a class?	private System.Threading.Timer timer;\n\npublic YourClass()\n{\n    timer = new System.Threading.Timer(UpdateProperty, null, 1000, 1000);\n}\n\nprivate void UpdateProperty(object state)\n{\n    lock(this)\n    {\n        // Update property here.\n    }\n}	0
8308254	896574	Forcing a WPF tooltip to stay on the screen	ToolTipService.ShowDurationProperty.OverrideMetadata(\n    typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));	0
4926366	4926362	Easier way to populate a list with integers in .NET	var numberList = Enumerable.Range(1, 10).ToList();	0
17888962	17888856	How do I construct a JSON from dynamic data?	using Newtonsoft.Json;\n\nstring json = JsonConvert.SerializeObject(yourlist);	0
623794	623787	Simple regex pattern	string regex = @"^[A-Za-z\s]{1,40}$";	0
32386529	32386491	Converting hexadecimal to binary	var value = 0xFFFF; \nvalue = Convert.ToString(Convert.ToInt32(value.ToString(), 16), 2);\nConsole.WriteLine(value);\n// 1100101010100110101	0
29950842	29950739	C# how to dynamically cast object	public class TriggerableObject \n{\n    public virtual Trigger(){\n        DoSomething();\n    }\n}\npublic class X : TriggerableObject\n{\n    public override Trigger(){\n        DoSomethingElse();\n    }\n}\npublic class X2 : TriggerableObject\n{\n    public override Trigger(){\n        DoSomethingOther();\n    }\n}\npublic class Trigger\n{\n    TriggerableObject obj = FindMyObject();\n    obj.Trigger();\n}	0
19152889	19152764	How to parse nullable DateTime object in C#	DateTime.Parse(EndDate.GetValueOrDefault().ToShortDateString() + " " + EndTime);	0
25627152	25626770	Is it possible to convert a byte[] to a bitmapsource?	using (MemoryStream ms = new MemoryStream(imageData))\n{\n    BitmapDecoder bitmapDecoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);\n    BitmapSource photo = new WriteableBitmap(bitmapDecoder.Frames.Single());\n}	0
26670010	26666828	Make web user control background transparent	border-radius:4px;	0
3916869	3827126	How to delete a DNS Zone with WMI	internal static bool DeleteZoneFromDns(string ZoneName)\n    {\n        try\n        {\n            string Query = "SELECT * FROM MicrosoftDNS_Zone WHERE ContainerName = '" + ZoneName + "'";\n            ObjectQuery qry = new ObjectQuery(Query);\n            DnsProvider dns = new DnsProvider();\n            ManagementObjectSearcher s = new ManagementObjectSearcher(dns.Session, qry);\n            ManagementObjectCollection col = s.Get();\n            dns.Dispose();\n\n            foreach (ManagementObject obj in col)\n            {\n                obj.Delete();\n            }\n            return true;\n        }\n        catch (Exception)\n        {\n            return false;\n        }\n    }	0
12787899	12787721	Read specific cell in sql, using the rows id to choose it with	string OutputToLabel = string.Empty;\n\nif(!string.IsNullOrEmpty(Request.QueryString["id"]))\n{\n    int ThreadID = 0;\n    int.TryParse(Request.QueryString["id"], out ThreadID);\n    if(ThreadID > 0)\n    {\n        string Sql = "SELECT Topic FROM <tablename> WHERE ThreadID = @ThreadID;";\n        using (SqlConnection conn = new SqlConnection(connString))\n        {\n            SqlCommand cmd = new SqlCommand(Sql, conn);\n            cmd.Parameters.Add("@ThreadID", ThreadID);\n            try\n            {\n                conn.Open();\n                OutputToLabel = cmd.ExecuteScalar().ToString();\n            }\n            catch (Exception ex)\n            {\n                Response.Write(ex.Message);\n            }\n        }\n    }\n}	0
12673058	12050451	Programmatically clean windows 8 search charm suggestions	Settings Charm > Change PC Settings (Windows 8 metro style control panel)) > Search > Erase History	0
23927568	23927401	How to find an item from SelectedItems back in the main DataGrid.Items	for(int i = 0; i < myDataGrid.Items.Count; i++)\n{\n    if (((IList)myDataGrid.Items[i]) == myitem)\n    {\n      //Found Item\n    }\n}	0
5077237	5077224	ASP.NET MVC: Securing actions based on parameter values	public class MyCustomAuthorizeAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        base.OnAuthorization(filterContext);\n\n        if (!(filterContext.Result is HttpUnauthorizedResult))\n        {\n            var currentUser = filterContext.HttpContext.User.Identity.Name;\n            var currentAction = filterContext.RouteData.GetRequiredString("action");\n            var id = filterContext.RouteData.Values["id"];\n            if (!HasAccess(currentAction, currentUser, id))\n            {\n                HandleUnauthorizedRequest(filterContext);\n            }\n        }\n    }\n\n    private bool HasAccess(string currentAction, string currentUser, object id)\n    {\n        // TODO: decide whether this user is allowed to access this id on this action\n        throw new NotImplementedException();\n    }\n}	0
15364162	15364159	Prevent Y2Axis from changing when user zooms ZedGraph	private bool resizingAxis = false;\n\n    void GraphPane_AxisChangeEvent(ZedGraph.GraphPane pane)\n    {\n        if (!resizingAxis)\n        {\n            resizingAxis = true;\n            this.zedGraphControl1.GraphPane.Y2Axis.ResetAutoScale(pane, this.CreateGraphics());\n            resizingAxis = false;\n        }\n    }	0
13636994	13557590	How can I show image in ListView element?	Image image = new Image();\nimage.Source = new BitmapImage(new Uri(@"ms-appx:/Assets/Logos/x.png"));\n\n<Image Source="{Binding Path=image.Source.UriSource.AbsolutePath}" Width="55" Height="40"/>	0
11282556	11282340	App crashes when reading from text file	IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();\nIsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("ItemFile.txt", FileMode.Open, FileAccess.Read);\nusing (StreamReader reader = new StreamReader(fileStream))\n{    //Visualize the text data in a TextBlock text\n    while ((line = reader .ReadLine()) != null)\n    {\n         imageCollection.Add(new Image());\n         imageCollection[counter].Source = new BitmapImage(new Uri("Images/" + line + ".png", UriKind.Relative));\n    }\n}	0
24510366	24510250	How to declare enums in C#	enum cardValue { Val2 = "2", Val3 = "3", Val4 = "4", ValA = "A" };	0
5633246	5474578	How to compare SQL Server CDC LSN values in C#?	SqlExecutor.ExecuteReader(cnn,\nstring.Format("SELECT {0} , __$start_lsn, __$seqval , __$update_mask " +\n    "FROM cdc.fn_cdc_get_all_changes_{1}(@startLsn,@endLsn,'all update old') cdc {2} " +\n    "where __$operation = {3} ORDER BY __$start_lsn, __$seqval", columns,\n    captureInstance, joins, (int)operation), \n    reader =>\n    {\n        if (reader != null)\n            items.Add(createEntity(reader));\n    }, 5, 60, new SqlParameter("@startLsn", lsn), \n              new SqlParameter("@endLsn", endLsn));\n});\nstartLsn = lsn;\nseqVal = sequence;\nvar startIndex = sequence == null ? 0 : \n  items.FindIndex(0, item => item.Lsn.SequenceEqual(lsn)\n    && item.Seqval.SequenceEqual(sequence)) + 1; // <---- Look here. See the +1\nreturn items.Skip(startIndex).ToList();	0
17572613	17571616	Getting the class name of a generic class in a static variable	class Program\n{\n    static void Main(string[] args)\n    {\n        Derived d = new Derived();\n\n        Console.WriteLine(d.ConfigField); // Derived.String\n\n        Console.ReadLine();\n    }\n}\n\nabstract class Base<T>\n{\n    public string ConfigField { get; private set; }\n\n    public Base()\n    {\n        ConfigField = string.Format("{0}.{1}", this.GetType().Name, this.GetType().BaseType.GenericTypeArguments[0].Name);\n    }\n\n}\n\nclass Derived : Base<string>\n{\n\n}	0
711290	711242	Access Version Info for Project	Assembly.GetExecutingAssembly().GetName().Version.ToString();	0
22975383	22975298	Using Code First can I set a default parameter in a table/model?	AddColumn("dbo.MyTable", "DateCreated", c => c.DateTime(nullable: false, defaultValueSql: "GetDate()"));	0
643733	643655	Creating a simple name value mapper class in C#	public static class FieldMapper {\n\n   public static string GetValue(string name) {\n      switch (name) {\n         case "abc": return "Value1";\n         case "def": return "Value2";\n      }\n      throw new ArgumentException("Unknown name.", "name");\n   }\n}	0
30080670	30080396	Format string into Time from datatable C#	.ToString("hh-mm")	0
19872821	19872742	How to store pieces of Linq expression in variables and use those variables in a query?	Expression<Func<BAL.Receipt, bool>> a =\n    x => x.InvoiceNo.StartsWith(txtSearch.Text);\n\nExpression<Func<BAL.Receipt, bool>> b =\n    x => x.Alias.StartsWIth(txtSearch.Text);\n\nList<BAL.Receipt> ac =\n    BAL.ApplicationInfo.db.Receipts\n        .Where(a)\n        .Where(b);	0
6768349	6768013	How to retrieve the data out of a Silverlight DataContext Object	private void someTextField_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)\n    {\n\n        var dataContext = (TextBlock) sender;\n        var assetGUID = ((YourObject)dataContext.DataContext).getGuid()  /\n        // intellsense does not show any fields, indexers, or getters - Just says "Get or Set datacontext fields in a datacontext".\n\n    }	0
13850621	13814382	How does ServerManager finds the states of an given site	ServerManager manager= ServerManager.OpenRemote("testserver");\nvar site = manager.Sites.First();\nvar status = site.State.ToString() ;	0
6225794	6225657	Please explain this pattern when using abstract method	object Create(IContext context);	0
10672721	10672482	insert object in selected linq array	var first = new[] { new { DisplayText = "Choose", Value = 0 } };\n    return first.Concat(departments).ToArray();	0
19954594	19954498	Strange lambda Expression breaks down IIS	var querycopy = query;\nquery = query.Where(x => x.VersionInt == querycopy.Max(y => y.VersionInt))	0
19393000	19391321	How to transition from individual repositories to a service layer?	Internal class AccountService\n{\n    Public Account GetAccount(string firstName)\n    {\n        var results = Enumerable.Empty<Account>();\n\n        try\n        {\n             var repository = new Repository<Account>(); // I use and interface here and                    \n                                                         // then a factory class. I just\n                                                         // was trying to keep it simple.\n             results = repository.FindAll()\n                 .Where(a => a.FirstName == firstName)\n                 .ToList();\n        }\n        catch()... etc.\n\n        return results;\n    }\n}\n\nPublic interface IAccountService\n{\n    Account GetAccount(string accountNumber);\n}	0
32764645	32759418	Edit the DataGrid after filter in WPF	// new employee to add\n            Employee empNew = new Employee() { Name = "New1", Address = "NewAdd1" };\n\n// get corresponding item  in filtered view after which you want to insert\n            Employee emp = (Employee)DgrdEmployees.SelectedItem;\n\n// get true collection which is datasource\n            ObservableCollection<Employee> sourceCol = (ObservableCollection<Employee>)(CollectionViewSource.GetDefaultView(DgrdEmployees.ItemsSource).SourceCollection);\n\n// find index of selected item after which we are inserting/pasting\n            int trueIndex = sourceCol.IndexOf(emp);\n\n// insert it at exact location in true unfiltered source collection\n            sourceCol.Insert(trueIndex + 1, empNew);	0
28930484	28930220	Dictionary<string, string> Value lookup performance	// some values\nvar dictionary = new Dictionary<string, string>();\nvar fields = new string[]{};\n\n\nstring[] modifiedFields = new string[fields.Length];\nfor(var i =0; i < fields.Length; i++)\n{\n  modifiedFields[i] = new string(fields[i].ToCharArray().OrderBy(x =>x).ToArray());\n}\nvar set = new HashSet<string>(modifiedFields);\nvar results = new List<string>();\nforeach(var pair in dictionary)\n{\n  string key = new string(pair.Value.ToCharArray().OrderBy(x =>x).ToArray());\n  if (set.Contains(key))\n  {\n    results.Add(pair.Key);\n  }\n}	0
10060249	9855230	how to get the network interface and its right ipv4 address?	foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())\n{\n   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)\n   {\n       Console.WriteLine(ni.Name);\n       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)\n       {\n           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)\n           {\n               Console.WriteLine(ip.Address.ToString());\n           }\n       }\n   }  \n}	0
4655207	4655143	How can I get the last day of the month in C#?	DateTime today = DateTime.Today;\nDateTime endOfMonth = new DateTime(today.Year, \n                                   today.Month, \n                                   DateTime.DaysInMonth(today.Year, \n                                                        today.Month));	0
2438573	2438267	What regex should I use to remove links from HTML code in C#?	var html = "<a ....>some text</a>";\nvar ripper = new Regex("<a.*?>(?<anchortext>.*?)</a>", RegexOptions.IgnoreCase);\nhtml = ripper.Match(html).Groups["anchortext"].Value;\n//html = "some text"	0
3927191	3927171	Conditional Lambda Expression?	Action<ItemType> action = item => { if(!Reports.Contains(item)) Reports.Add(item);};	0
11773644	11773590	Option in drop down list calculation	string IsChauffeurUsed = Session["IsChauffeurUsed"].ToString();\ntotalValue += IsChauffeurUsed.Equals("Yes", StringComparison.CurrentCultureIgnoreCase) ? 80 : 0;	0
14557180	14557058	How to run windows form's from Console?	cd %ProgramFiles%/Path/To/App\n\nMyApp -Console whatever	0
20421299	20177633	Geta data from DB by EntityFramework by TPC strategy	using (var db = new AnimalDbContext)\n{\n    var cats = db.Animals.OfType<Cat>().ToArray();\n\n    // Or when you want to get animals of multiple types\n    var catsAndDogs = db.Animals.Where(a => a is Cat|| a is Dog).ToArray();\n}	0
1775000	1774927	how to set pagesize in special pages that i want to rotate just these pages!	class Program\n{\n    static void Main(string[] args)\n    {\n        Document doc = new Document(PageSize.A4);\n        using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))\n        {\n            var writer = PdfWriter.GetInstance(doc, stream);\n            doc.Open();\n\n            doc.NewPage();\n            doc.Add(new Paragraph("Page1 (portrait A4)"));\n\n            doc.NewPage();\n            doc.Add(new Paragraph("Page2 (portrait  A4)"));\n\n            // Set page size before calling NewPage\n            doc.SetPageSize(PageSize.A4.Rotate());\n            doc.NewPage();\n            doc.Add(new Paragraph("Page3 (landscape A4)"));\n            // Revert to the original page size before adding new pages\n            doc.SetPageSize(PageSize.A4);\n\n            doc.NewPage();\n            doc.Add(new Paragraph("Page4 (portrait A4)"));\n\n            doc.Close();\n        }\n    }	0
9282645	9282460	How do I close a stream after a file transfer over WCF?	var myStream = new FileStream("blah.txt", FileMode.Read, FileAccess.Read);	0
10352849	10352574	Stream that has separate write and read positions	public class QueueStream : MemoryStream\n{\n    long ReadPosition;\n    long WritePosition;\n\n    public QueueStream() : base() { }\n\n    public override int Read(byte[] buffer, int offset, int count)\n    {\n        Position = ReadPosition;\n\n        var temp = base.Read(buffer, offset, count);\n\n        ReadPosition = Position;\n\n        return temp;\n    }\n\n    public override void Write(byte[] buffer, int offset, int count)\n    {\n        Position = WritePosition;\n\n        base.Write(buffer, offset, count);\n\n        WritePosition = Position;\n    }\n}	0
31320252	31320081	Best way to intercept closing of window?	protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n    {\n        if(dontClose)\n        {\n            e.Cancel = true;\n        }\n        base.OnClosing(e);\n    }	0
23505599	23413950	multivariate normal random numbers from Matlab to C#	Matrix covariance = new Matrix( [some numbers]) // basically just copy the covariance values\nMatrix rowCov = covariance.getRowCovariance()\nMatrix colCov = covariance.getColumnCovariance()	0
8265116	8256736	Retrieve value of Dynamic radio button controls in asp:table	RadioButton rb = new RadioButton();            \n        foreach (TableRow tr in QuestionTable.Controls)\n        {\n            foreach (TableCell tc in tr.Controls)\n            {\n                if (tc.Controls[0] is RadioButton)\n                {\n                    rb = (RadioButton)tc.Controls[0];\n                    if (rb.Checked)\n                    {\n                        string aa = rb.ID;\n                    }\n                    break;\n                }\n            }               \n        }	0
1368698	1368643	How do I create clone of object in base class?	//In parent class\npublic ParentClass CreateEmpty()\n{\n    return (ParentClass)Activator.CreateInstance(this.GetType());\n}	0
14545478	14544823	how to remove the extra AND from the loop	string[] allTheseWords = { "try", "test", "let" };\n        string whereLine = string.Empty;\n        foreach (var item in allTheseWords)\n                whereLine += "report = " + item.ToString() + " and ";\n        string final = whereLine.Remove(whereLine.Length - 5);\n        Console.WriteLine(final);\n        Console.ReadLine();	0
14939052	14901866	Format to show day of week in month using C# or MonoTouch	int dowin = (SelectedDate.Day - 1) / 7 + 1;\nswitch(dowin){\n    case 1:{\n        return "1st" + dateString;\n    }\n    case 2:{\n        return "2nd" + dateString;\n    }\n    case 3:{\n        return "3rd" + dateString;\n    }\n    case 4:{\n        return "4th" + dateString;\n    }\n    case 5:{\n        return "5th" + dateString;\n    }\n}	0
15055518	15052899	How can I the see actual raw request that gets sent	request.RequestFormat = DataFormat.Json;\nrequest.AddHeader("Accept", "application/json");\nrequest.OnBeforeDeserialization = resp => { cnt = resp.Content; };\n\nGitModels.IssuePost toPostIssue = Git2Bit.GitModels.Bit2GitTranslator.translate(bitIssue);\n\nrequest.AddBody(toPostIssue);	0
10420904	10419885	XNA - HeightData to heightMap img	heightMapColors[x + y * heightData.GetLength(0)].R = colorData;\n     heightMapColors[x + y * heightData.GetLength(0)].G = colorData;\n     heightMapColors[x + y * heightData.GetLength(0)].B = colorData;\n     heightMapColors[x + y * heightData.GetLength(0)].A = 255;	0
6008175	6008159	Disabling auto-recovery in word	Sub DisableAutoRecover()\n  Options.SaveInterval = 0\nEnd Sub	0
19298596	19298413	Load form's controls to panel in C#	var formObj = new Form2();    //???\nfor (int ix = formObj.Controls.Count-1; ix >= 0; --ix) {\n    panels[panelsCounter].Controls.Add(formObj.Controls[ix]);\n}	0
8827118	8827032	How do I overload this code to make it accept my entry?	int[] bottles = new int[4];\n\nwhile (true)\n{\n    Console.Write("Enter the room you're in: ");\n    string inputString = Console.ReadLine();\n    if (inputString == "quit")\n        break;\n    int room = int.Parse(inputString);\n\n    Console.Write("Bottles collected in room {0}: ", room);\n    bottles[room - 1] = int.Parse(Console.ReadLine());\n}\n\nfor (int i = 0; i < bottles.Length; ++i)\n    Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, bottles[i]);	0
3280811	3279000	Specify LoaderOptimization's for Windows Services	static class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    static void Main()\n    {\n        ServiceBase[] ServicesToRun;\n        ServicesToRun = new ServiceBase[] \n        { \n            new Service1() \n        };\n        ServiceBase.Run(ServicesToRun);\n    }\n}	0
30401762	30401158	Linq to Entity Framework: Select with only subset of child elements	var set = _context.Set<A>()\n    .Include("B.X")\n    .Include("C.X")\n    .Where(a => a.B.Any(b => b.X.Any(x => x.EndDate == date)) ||\n                a.C.Any(c => c.X.Any(x => x.EndDate == date)))\n    .Select(a => new A() \n    {\n        B = a.B\n            .Where(b => b.X.Any(x => x.EndDate == DatePicker))\n            .Select(b => new B()\n                {\n                    X = b.X.Where(x => x.EndDate == DatePicker) \n                }),\n        C = a.C\n            .Where(c => c.X.Any(x => x.EndDate == DatePicker))\n            .Select(c => new C()\n                {\n                    X = c.X.Where(x => x.EndDate == DatePicker) \n                })\n    });	0
12300967	12300901	Returning a Static Readonly List	List<T>	0
18725087	18725049	Replacing string in a list doesn't work	newFile[3] = newFile[3].Replace(newFile[3], "Replace it with this!");	0
18634311	18634222	How do I make a string variable (in c#) bold when converting to html?	foreach (String projectType in ProjectsByProjectType.Keys)\n{\n    HtmlTableRow trh = new HtmlTableRow();\n    HtmlTableCell tdProjectType = new HtmlTableCell();\n    tdProjectType.InnerHtml = "<b>"+projectType+"</b>";\n    trh.Controls.Add(tdProjectType);\n    tableLocal.Controls.Add(trh);\n}	0
26590777	26590486	Correctly open and close multiple windows forms in C#	static class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    [STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n\n        // Show the login form\n        LoginForm loginForm = new LoginForm();\n        loginForm.ShowDialog();\n\n        // Show the main form\n        Application.Run(new MainForm());\n    }\n}\n\nclass LoginForm : Form\n{\n    public LoginForm()\n    {\n        BackColor = Color.Blue;\n        Text = "Login Form";\n    }\n}\n\nclass MainForm : Form\n{\n    public MainForm()\n    {\n        BackColor = Color.Red;\n        Text = "Main Form";\n    }\n}	0
30774213	30774131	Filter text between two special characters	string s = "qwe/qwe/q//we/qwe//qwe/somethingother_here_blabla.exe";\nint last_ = s.LastIndexOf('_');\nif (last_ < 0) // _ not found, take the tail of string\n    last_ = s.Length;\nint lastSlash = s.LastIndexOf('/');\nstring part = s.Substring(lastSlash + 1, last_ - lastSlash - 1);	0
11658516	11658098	How can I remove a value from a combox after setting its datasource?	comboBoxCurrently.Items.AddRange(PlatypusData.getCurrentlyVals().ToArray());\ncomboBoxCurrently.Items.Remove("Surrounded by purplish-blue Penguins");	0
32579262	32577447	C# Removing Submenu Item Image Margins	private void Form1_Load(object sender, EventArgs e)\n{\n    SetValuesOnSubItems(this.menuStrip1.Items.OfType<ToolStripMenuItem>().ToList());\n}\n\nprivate void SetValuesOnSubItems(List<ToolStripMenuItem> items)\n{\n    items.ForEach(item =>\n            {\n                var dropdown = (ToolStripDropDownMenu)item.DropDown;\n                if (dropdown != null)\n                {\n                    dropdown.ShowImageMargin = false;\n                    SetValuesOnSubItems(item.DropDownItems.OfType<ToolStripMenuItem>().ToList());\n                }\n            });\n}	0
12197037	12195227	Splitting two strings and rejoining	StringBuilder fullName = new StringBuilder();\n\n            List<string> lines = new List<string>();\n            if (!string.IsNullOrEmpty(address.Name))\n                fullName.AppendFormat("{0} ", address.Name);\n            if (!string.IsNullOrEmpty(address.Name1))\n                fullName.AppendFormat("{0} ", address.Name1);\n            if (!string.IsNullOrEmpty(address.Name2))\n                fullName.Append(address.Name2);\n\n            if (!string.IsNullOrEmpty(fullName.ToString()))\n                lines.Add(fullName.ToString());	0
28502401	28502171	How to move items from a checkedListBox to another checkedListBox	if you populate listboxes properly there will be no need to move items\n\nprivate void button8_Click(object sender, EventArgs e)\n{\n   int limit = 10;\n   string[] fileData = File.ReadAllText(@" To-Do References .txt").Split(new string[] { "\r\n" },    StringSplitOptions.RemoveEmptyEntries);\n   // this loop adds items to the 1st list until limit is reached\n   for(int i =0; i<limit && i<fileData.Length; i++)\n      checkedListBox1.Items.Add(fileData[i]);\n   // if there extra items, 2nd loop adds them to list ???2\n   for(int i =limit; i<fileData.Length; i++)\n      checkedListBox2.Items.Add(fileData[i]);\n}	0
34386182	34385660	Loading image from SQLite c# Windows App	var filestream = await Windows.Storage.KnownFolders.PicturesLibrary.OpenStreamForReadAsync("Screenshots\\Screenshot (1).png");\nInMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();\nawait filestream.CopyToAsync(ras.AsStreamForWrite());\n\nBitmapImage bmpImage = new BitmapImage();\nbmpImage.SetSource(ras);\n\nimage.Source = bmpImage;	0
6187400	6186745	WPF UI Style partially frozen in a wrong state after Command Execution	CommandManager.InvalidateRequerySuggested()	0
32852577	32838213	Assigning Outlook Appointment recurrence type from code	Outlook.RecurrencePattern pattern = oMeet.GetRecurrencePattern();\n pattern.RecurrenceType = OlRecurrenceType.olRecursDaily;\n    OlRecurrenceType pattern2 = pattern.RecurrenceType;\n     string rectype = pattern2.ToString();\n     pattern.Interval = Convert.ToInt32(htrecc["Interval"]);\n     if (string.Equals("no", htrecc["Occurence"]))\n         pattern.NoEndDate = true;\n     else\n          if (!string.IsNullOrEmpty(Convert.ToString(htrecc["Occurence"])))\n              pattern.Occurrences = Convert.ToInt32(htrecc["Occurence"]);\n          else\n              pattern.PatternEndDate = Meet.EndTime;	0
19356542	19356413	Adding user input number of rows=columns in a matrix C#	int n = int.Parse(Console.ReadLine()); // use TryParse to be sure the value is correct\ndouble[,] M = new double[n, n];	0
7278062	7277893	Slow, sweeping turns instead of instantly facing the target	// Find the difference in angles, always going in the direction of least movement\nvar target = Math.atan2(x, y);\nvar difference = target - _angle.value;\nif (difference > Math.PI)\n{\n    difference = ((2 * Math.PI) - difference);\n}\nif (difference < -Math.PI)\n{\n    difference = ((2 * Math.PI) + difference);\n}\n// Move the character's rotation a set amount per unit time\nvar delta = (difference < 0) ? -RotationChangePerSecond : RotationChangePerSecond;\n_angle.value += delta * gameTime.ElapsedGameTime.TotalSeconds;	0
20153835	20152104	CheckBox in GridView failing	protected void submit_CheckedChanged(object sender, EventArgs e)\n{\n    CheckBox submitChk = (CheckBox)sender;\n    GridViewRow row = (GridViewRow)submitChk.NamingContainer;\n    String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;\n\n    SqlConnection conn = new SqlConnection("your connection string here");\n    string updateQuery = "UPDATE DRPprovders SET submit = @submit WHERE npi = @npi";\n    SqlCommand cmd = new SqlCommand(updateQuery, conn);\n\n    // If it's checked, pass 1, else pass 0\n    cmd.Parameters.AddWithValue("@submit", submitChk.Checked ? 1 : 0);\n    cmd.Parameters.AddWithValue("@npi", npi);\n\n    conn.Open();\n    cmd.ExecuteNonQuery();\n    conn.Close();\n}	0
15641743	15641574	extract substrings from a strings	void Main()\n{\n    string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBB1</t></ABCMSG>"; \n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(str);\n    var t = doc.GetElementsByTagName("t");\n    Console.WriteLine(t[1].InnerText);\n    Console.WriteLine(t[2].InnerText);\n}	0
6616339	6616283	How do you span columns in C#?	Grid1.Children.Add(UserControl01);\nGrid.SetColumnSpan(UserControl01, 3);	0
11646162	11633054	Working with Fragments in Monodroid	View fragment = inflater.Inflate(Resource.Layout.dialer, null);	0
11456032	11455902	WebService check if there is data in SQL table	if (Datos.Tables[0].Rows.Count() > 0)	0
27890926	27889664	How to delete carriage return in every cell in excel?	Microsoft.Office.Interop.Excel.Range cells = reportSheet.Cells;\n// Cycle through each newline code and replace.\nforeach (var newline in new string[] { "\r\n", "\r", "\n" })\n{\n    cells.Replace(newline, "",\n                  Microsoft.Office.Interop.Excel.XlLookAt.xlPart, // Use xlPart instead of xlWhole.\n                  Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, false,\n                  false, true, false);\n}	0
18912587	18912368	How to find byte-offset in .mp4-file from timecode or framenumber?	length (4 bytes), type (4 bytes), *body*	0
817964	817807	C#: How to remove all null properties from a generic object using reflection?	public override IEnumerable<Type> SupportedTypes\n{ \n    get\n    {\n        var list = new List<Type>{ typeof(Foo), typeof(Bar)...};\n        return list.AsReadOnly();\n    }\n}	0
20545526	20543447	Windows Phone Tapping an alarm or Reminder launched Application	Uri navigationUri = new Uri("/ShowDetails.xaml", UriKind.Relative);\n                Reminder reminder = new Reminder(name);\n                reminder.Title = titleTextBox.Text;\n                reminder.Content = contentTextBox.Text;\n                reminder.BeginTime = beginTime;\n                reminder.ExpirationTime = expirationTime;\n                reminder.RecurrenceType = recurrence;\n                reminder.NavigationUri = navigationUri;\n\n              //   Register the reminder with the system.\n                ScheduledActionService.Add(reminder);	0
25743059	25741819	Is Android's construction with listeners available in Windows Phone?	public class Class1\n{\n    public Class1()\n    {\n        var c = new Class2();\n\n        c.OnFinish += result => \n        {\n            // My result handling here\n        };\n    }\n}\n\npublic class Class2\n{\n    public event Action<string> OnFinish;\n\n    private void SomeMethod()\n    {\n        string result = "Result here";\n\n        var eventHandler = this.OnFinish;\n\n        if (eventHandler != null)\n        {\n            eventHandler(result);\n        }       \n    }\n}	0
9592484	9592235	How to change the value of an XML node based on another node on the same level?	XDocument xDoc = XDocument.Load(new StringReader(xmlstr));\nstring url="images/SickIcon.jpg";\n\nvar image = xDoc.Descendants("image")\n                .Where(x => x.Element("url").Value == url)\n                .First();\nimage.Element("title").Value = "Renamed Value";	0
12944552	12926005	Dispose Timer inside of anonymous method	public static async Task WithTimeout(this Task task, int timeout, string timeoutMessage = null, params object[] args)\n    {\n        var timeoutTask = Task.Delay(timeout);\n        if (await Task.WhenAny(task, timeoutTask) == timeoutTask)\n            throw new TimeoutException(timeoutMessage == null ? "Operation timed out" : string.Format(timeoutMessage, args));\n\n        await task;\n    }	0
7326853	7325945	Rethrowing socket exceptions from device driver	try {\n   tcpClient = new TcpClient(address.ToString(), port);\n} catch (SocketException SE) {\n   throw new MyDriverException("Failed to connect to remote device");\n}	0
6099680	6099298	Set operations in RavenDB	documentStore.DatabaseCommands.UpdateByIndex("DataByColor",\n    new IndexQuery\n    {\n        Query = "Color:red"\n    }, new[]\n    {\n            new PatchRequest\n            {\n                Type = PatchCommandType.Set,\n                Name = "Color",\n                Value = "Green"\n            }\n    },\n    allowStale: false);	0
14024089	14024024	Regex matching numbers without letters in front of it	(?<![A-Za-z0-9.])[0-9.]+	0
21556639	21530627	Get all <td> title of a table column with coded ui	static public List<string> GetTdTitles(string htmlCode, string TdSearchPattern)\n{\n    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n    doc.LoadHtml(htmlCode);\n    HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//td[@" + TdSearchPattern + "]");\n    List<string> Results = new List<string>();\n    foreach (HtmlNode node in collection)\n    {\n        Results.Add(node.InnerText);\n    }\n\n    return Results;\n}	0
1728551	1728046	how to filter out DateTime type of values from all hashtable value?	public static void ProcessHT(Hashtable ht)\n{\nHashtable dates = new Hashtable();\n\nforeach(DictionaryEntry de in ht)\n{\nif (de.Value is DateTime)\ndates.Add(de.Key, de.Value);\n}\n\nforeach(DictionaryEntry de in dates)\n{\nht.Remove(de.Key);\nht.Add(de.Key, ((DateTime)de.Value).ToString("s"));\n}\n}\n\npublic static void RunSnippet()\n{\nHashtable ht = new Hashtable();\n\nht.Add("1", "one");\nht.Add("date", DateTime.Today);\nht.Add("num", 1);\nPrint(ht);\nWL("---");\nProcessHT(ht);\nPrint(ht);\n}\n\nprivate static void Print(Hashtable ht)\n{\nforeach (DictionaryEntry de in ht)\n{\nWL("{0} = {1}", de.Key, de.Value);\n}\n}	0
709387	709187	Accessing UI in a thread	control.Invoke((MethodInvoker)delegate {\n    control.Enabled = true;\n});	0
14961248	14960709	How to print each element with root attribute of the node of an XML file in c#	foreach (XmlNode element in xmlDocument.GetElementsByTagName("Identity"))\n        {\n            string output = element.Attributes[0].Value;\n            foreach (XmlNode xmlNode in element.ChildNodes)\n            {\n                foreach (XmlNode reference in xmlNode.ChildNodes)\n                {\n                    output += reference.InnerText;\n                }\n            }\n            //Output here should be onelined.. \n        }	0
31449396	31448776	How to save sort stage of datagridview inform c#	DataGridViewColumn oldColumn = dataGridView1.SortedColumn;\nListSortDirection direction = ListSortDirection.Ascending;\ndataGridView1.Sort(newColumn, direction); //give column in place of newColumn for sorting\nnewColumn.HeaderCell.SortGlyphDirection = direction == ListSortDirection.Ascending ? SortOrder.Ascending : SortOrder.Descending;	0
16613487	16606488	Creating a static model from dynamic data in a WebApi model binder	public class EmailModelBinder : IModelBinder\n{\n    public bool BindModel(\n        HttpActionContext actionContext, \n        ModelBindingContext bindingContext)\n    {\n        string body = actionContext.Request.Content\n                       .ReadAsStringAsync().Result;\n\n        Dictionary<string, string> values = \n            JsonConvert.DeserializeObject<Dictionary<string, string>>(body);\n\n        var entity = Activator.CreateInstance(\n            typeof(IEmail).Assembly.FullName, \n            values.FirstOrDefault(x => x.Key == "ObjectType").Value\n            ).Unwrap();\n\n        JsonConvert.PopulateObject(body, entity);\n\n        bindingContext.Model = (IEmail)entity;\n\n        return true;\n    }\n}	0
11221221	11221169	How to getType from a reference dll when copylocal property is false	Type customType = Type.GetType("namespace.typename, assembly");	0
15247861	15246960	InvalidCastException getting value from DataBoundItem	var obj = dataGridView1.CurrentRow.DataBoundItem;\n\n        if (obj != null)\n        {\n            var item = ((DataRowView)obj).Row;\n        }	0
15987509	15984154	Open A PDF file on button click	private async void Button_Click(object sender, RoutedEventArgs e)\n    {\n        string imageFile = @"images\somepdffile.pdf";\n\n        // Get the image file from the package's image directory\n        var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);\n        if (file != null)\n        {\n            bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);\n            if (success)\n            {\n                // File launched\n            }\n            else\n            {\n                // File launch failed\n            }\n        }\n        else\n        {\n            // Could not find file\n        }\n    }	0
7242603	7242579	How to send Cache-Control: no-cache in HTTP header?	Response.AppendHeader("Cache-Control", "no-cache");	0
32154086	32153974	Html Agility Pack c#	var html = new HtmlDocument();\nhtml.LoadHtml(input);\nvar root = html.DocumentNode;\nvar list = new List<Data>();\nforeach (var node in root.SelectNodes("//tr//td[5]"))\n{\n    var price = node.InnerText.IsNullOrWhiteSpace() ? "no price" : node.InnerText;\n}	0
23448982	23431071	c# Bluetooth Mac Address of our Adapter	BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;\nif (myRadio == null) {\n    Console.WriteLine("No radio hardware or unsupported software stack");\n    return;\n}\nRadioMode mode = myRadio.Mode;\n// Warning: LocalAddress is null if the radio is powered-off.\nConsole.WriteLine("* Radio, address: {0:C}", myRadio.LocalAddress);	0
14075286	14075029	Have a set of Tasks with only X running at a time	SemaphoreSlim maxThread = new SemaphoreSlim(10);\n\nfor (int i = 0; i < 115; i++)\n{\n    maxThread.Wait();\n    Task.Factory.StartNew(() =>\n        {\n            //Your Works\n        }\n        , TaskCreationOptions.LongRunning)\n    .ContinueWith( (task) => maxThread.Release() );\n}	0
17861527	17861427	How do I go about adding records into TWO tables into Access Database?	cmd1.ExecuteNonQuery()	0
6333030	6332987	Get non-over lapping area of two rectangles	Rectangle a, b;\n\nvar region = new Region(a);\nregion.Exclude(b);	0
11291396	11291352	Shutdown event for console application C#	class Program\n    {\n        static void Main(string[] args)\n        {\n            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           \n\n\n        }\n\n        static void CurrentDomain_ProcessExit(object sender, EventArgs e)\n        {\n            Console.WriteLine("exit");\n        }\n    }	0
1428360	1428231	C# Reordering the Tables in a Dataset	public class ThisThing\n{\n    private DataSet myDS = new DataSet();\n\n    //Populate your DataSet as normal\n\n    public DataSet ChangeLocation(int CurrentSectionNumber)\n    {    \n        myDS.Table[0] = myDS.Table[CurrentSectionNumber]\n    }\n}	0
12093705	12093368	Display date on the basis of culture	function SetTime() {\n    var date = new Date();\n    var dateFormat = '<%=System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern%>';\n    var timeFormat = '<%=System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern%>';\n     var datetimeFormat = dateFormat + " " + timeFormat;\n     var cultureSpecificValue= date.toString(datetimeFormat);\n    alert(cultureSpecificValue);\n\n   //Your Code\n\n}	0
19524623	19523500	Implementing an Interface on Client and Server Sides	public class Param //at server side\n{\n   public int recordId { get; set; }\n   public int transToPropId { get; set; }\n   public int receivedViaTypeId { get; set; }\n   public string recordNumber { get; set; }\n}\n\npublic interface IParamParser //at client\n{\n   //I do not know what object[] paramz is; I leave that to you; \n   //may be it needs encapsulation as well\n   bool Parse(object[] paramz, Param p);\n}\n\npublic interface IParamCreator //at server\n{\n   Param CreateParams(int recordId, int transToPropId, int receivedViaTypeId, \n                      string recordNumber);\n}	0
12663518	12633378	Running a mini-program in Mono.Csharp	var reportWriter = new StringWriter();\nvar settings = new CompilerSettings();\nvar printer = new ConsoleReportPrinter(reportWriter);\nvar reports = new Report(printer);\nvar eval = new Evaluator(settings, reports);\n\neval.Run(code);\n\neval.Run(@"\n    var output = new System.IO.StringWriter(); \n    Console.SetOut(output);\n    new MyClass().DoSomething();");\n\nvar model = new CodeViewModel();\nmodel.Code = code;\n\nif (reports.Errors > 0)\n   model.Result = reportWriter.ToString();\nelse\n   model.Result = (string) eval.Evaluate("output.ToString();");\n\nreturn View("Index", model);	0
4630468	4630444	How to skip optional parameters in C#?	foo(x: 5, optionalZ: 8);	0
9223145	9223093	is there a way to search each element in a collection c#	var count = list.Count(x => x.boolValue);	0
30160100	30159936	Need to parse this data with Json.NET	var json = JObject.Parse(responseString);\nConsole.WriteLine(json["data"]["authentication_token"]);	0
5336499	5327518	How to create meaningful unit tests for fakes	[Test]\npublic void SubscribesToExchange()\n{\n  var exchange = MockRepository.GenerateMock<IExchangeService>(); //this is the stub\n  var service = StreamingNotificationService(exchange); //this is the object we are testing\n\n  service.Subscribe();\n  service.AssertWasCalled(x => x.Subscribe(););\n}	0
31403789	31403350	How to call a C# Class from a C# Form	public partial class Form1 : Form\n    {\n        NumberToEnglish neObj = new NumberToEnglish();\n        public Form1()\n        {\n            InitializeComponent();\n\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            textBox2.Text = neObj.changeCurrencyToWords(Convert.ToDouble(textBox1.Text));\n        }\n    }	0
6275088	6275022	Is there google translate API for iPhone application?	[1]: http://code.google.com/apis/language/translate/v2/getting_started.html#translate \n\n    https://www.googleapis.com/language/translate/v2?parameters\n\n    https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de\nhttps://www.googleapis.com/language/translate/v2/languages?parameters	0
10499402	10499325	Iterate Between Enum Values in C#	for(Cars car=Cars.Opel; car<=Cars.Citroen; car++)\n{\n  Console.WriteLine(car);\n}	0
1780485	1780469	How do I set cookie expiration to "session" in C#?	cookie.Expires = DateTime.MinValue	0
5375796	5375438	Replace colors in indexed image using C#	var colorMaps = new[]{\n   new ColorMap {OldColor = Color.FromArgb(255, 0, 0, 0), NewColor =  Color.Transparent}\n};\n\nvar attr = new ImageAttributes();\nattr.SetRemapTable(colorMaps);	0
32644107	32643396	Changing ClientRowTemplate in KendoUi Grid	if (window.innerWidth > 860)\n    {\n        // Set Normal template             \n\n        grid.options.rowTemplate = Install.webClientRowTemplate;\n        grid.options.altRowTemplate = Install.webClientAltRowTemplate;\n        grid.setOptions('rowTemplate', '');\n        grid.setOptions('altRowTemplate', '');\n        grid.refresh();\n    }\n    else\n    {\n        // set mobile template\n        grid.options.rowTemplate = Install.mobileClientRowTemplate;\n        grid.options.altRowTemplate = Install.mobileClientAltRowTemplate;\n        grid.setOptions('rowTemplate', '');\n        grid.setOptions('altRowTemplate', '');\n        grid.refresh();\n    }	0
19740220	19739968	How to get the Element value from returned Soap based XML Message	XDocument doc = XDocument.Load("XMLFile1.xml");\nvar result = doc.Descendants(XNamespace.Get("http://tempuri.org/")+"NAME").First();\nConsole.WriteLine(result.Value);	0
29234294	29233545	How to download file with correct timestamp?	public static void GetDateTimestampOnServer (Uri serverUri)\n    {\n        if (serverUri.Scheme != Uri.UriSchemeFtp)\n        {\n            throw new ArgumentException("Scheme Must match Ftp Uri Scheme");\n        }\n\n        FtpWebRequest request = (FtpWebRequest)WebRequest.Create (serverUri);\n        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;\n        FtpWebResponse response = (FtpWebResponse)request.GetResponse ();\n        Console.WriteLine ("{0} {1}",serverUri,response.LastModified);\n    }	0
9209101	9208957	How to get blob size without getting the value itself with Entity Framework	using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM))\n{\n    Settings.WybraneSzkolenie = context.Szkolenies\n       .Where(d => d.SzkolenieID == szkolenieId)\n       .Select(d => SqlFunctions.DataLength(d.DataField))\n       .FirstOrDefault();\n\n}	0
33647308	33647218	Avoid duplicates in linq based on single column	var select = (from ab in dt.AsEnumerable()\n                                   select new { c1 = ab["PROJECTNAME"], c2 = ab["COMPANY"], c3 = ab["PROJECTSTATUS"], c4 = ab["STARTEDIN"], c5 = ab["COMPLETEDIN"] }).Distinct().ToList();\n                    dt.Clear();\n                    var DistinctItems = select.GroupBy(x => x.c1).Select(y => y.First());\n                    foreach (var item in DistinctItems)\n                 dt.Rows.Add(item.c1, item.c2, item.c3, item.c4, item.c4);\n                 return dt;	0
18508163	18498955	mySQL connection string through SSH tunnel without password	var connection = new MySqlConnection(\n       "server=localhost;database=[database];uid=ubuntu;"\n  );	0
27412200	27404956	Xamarin IOS navigate to another view controller without button on xamarin	AssignCaseController assignCaseController = this.Storyboard.InstantiateViewController("AssignCaseController") as AssignCaseController;\nif (assignCaseController != null)\n{\n    assignCaseController.CaseID = GetCurrentCaseID();\n    this.NavigationController.PushViewController(assignCaseController, true);\n}	0
1559208	1559185	Formatting Numbers as Strings with Commas in place of Decimals	string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:0.0}", 4.3);	0
4462903	4462874	how to switch on a nullable variable	var type = xn.SelectSingleNode("@type");\nif (type == null)\n{\n    // Handle the case\n}\nelse\n{\n    switch (type.InnerText)\n    {\n        case "int":\n        case "int16":\n        case "int32":v=int.Parse(xn.InnerText);break;\n        default:v=xn.InnerText; break;\n    }\n}	0
19371572	16609823	How to get last modified user information using google drive API?	File file; // start with your file\nUser user = file.getLastModifyingUser();\nPermission permission = service.permissions().get(file.getId(), user.getPermissionId()).execute();\nString email = permission.getEmailAddress();	0
7718146	7718054	Validating Syntax of a Sentence	Colorless green ideas slept furiously.	0
15448897	15448788	Send email via Hotmail to gmail	SmtpClient SmtpServer = new SmtpClient("smtp.live.com");\n        var mail = new MailMessage();\n        mail.From = new MailAddress("email@hotmail.com");\n        mail.To.Add("ToGmail.com");\n        mail.Subject = "Your Sub";\n        mail.IsBodyHtml = true;\n        string htmlBody;\n        htmlBody = "HTML code";\n        mail.Body = htmlBody;\n        SmtpServer.Port = 587;\n        SmtpServer.UseDefaultCredentials = false;\n        SmtpServer.Credentials = new System.Net.NetworkCredential("email@hotmail.com", "YourPassword");\n        SmtpServer.EnableSsl = true;\n        SmtpServer.Send(mail);	0
21291644	21291258	How to determine that a form has finished opening in C#	InitializeComponent();\n    new Thread(testConnection).Start();	0
27405949	27402958	Slider size changing	private void Slider1_OnSizeChanged(object sender, SizeChangedEventArgs e)\n{\n    var value = this.slider1.Value;\n    this.slider1.Value = 0;\n\n    this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>\n    {\n        this.slider1.Value = value;\n    });\n}	0
15140441	15140212	copy files from one location to another	if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir");	0
28314325	28313137	Low quality image in TabPage header using TabControl ImageList	imageList1.ColorDepth = ColorDepth.Depth32Bit;	0
17928081	17927939	How to get specific words from Word document?*.doc? using C#?	using (StreamReader sr = new StreamReader(path)) \n{\n    while (sr.Peek() >= 0) \n    {\n        string line = sr.ReadLine();\n        string[] words = line.Split();\n        foreach(string word in words)\n        {\n            foreach(Char c in word)\n            {\n                // ...\n            }\n        }\n    }\n}	0
847237	847210	Disable key input in TreeView	if(Char.IsDigit(e.KeyChar) || Char.IsLetter(e.KeyChar))\n  {\n       e.Handled = true;\n  }	0
19588459	19588386	MVC4 MapRoute for CMS	routes.MapRoute(\n            name: "Default",\n            url: "{*p}",\n            defaults: new { controller = "Home", action = "Index", p = UrlParameter.Optional }\n        );	0
15175317	15168807	MovieTexture in Unity3D is never ready to play	if(m_MovieTexture!=null && !m.isPlaying && m.isReadyToPlay) m_MovieTexture.play();	0
24542544	24541447	How do i parse specific text from long content?	HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();\nvar doc = web.Load(your url);\nvar imgUrls = doc.DocumentNode.SelectNodes("//img[@border and @src]")\n                    .Select(i => i.Attributes["src"].Value)\n                    .ToList();	0
32745599	32742572	Login using different user in a different page?	protected void Button1_Click(object sender, EventArgs e)\n    {\n        if (dropdownrole.SelectedItem.Text == "Admin")\n        {\n            Admin();\n        }\n        else if (dropdownrole.SelectedItem.Text == "Student")\n        {\n            Student();\n        }\n        else if (dropdownrole.SelectedItem.Text == "Teacher")\n        {\n            Teacher();\n        }\n    }	0
33871947	33871873	How to delete file in folder	string newfilename = txtname.Text + "Resume" + fileExtension;\nstring[] pathOfFiles =  System.IO.Directory.GetFiles(Server.MapPath("/tmp/jobres/" + uId));\n\nforeach (string filePath in pathOfFiles)\n{\n    System.IO.File.Delete(filePath);\n}\n\nAsyncFileUpload1.SaveAs(Server.MapPath("/tmp/jobres/" + uId) + "\\" + newfilename;	0
21076506	21075840	Getting blank InstallDate for few installed softwares, even if date is there in registry	string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";\nusing (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))\n{\n    RegistryKey subkey = null;\n    try\n    {\n        foreach (string subkey_name in key.GetSubKeyNames())\n        {\n            subkey = key.OpenSubKey(subkey_name);\n\n        string[] columns = subkey.GetValueNames();\n        string appname = subkey.GetValue("DisplayName") as string;\n        string Vendor_Publisher = Convert.ToString(subkey.GetValue("Publisher"));\n        string Version = Convert.ToString(subkey.GetValue("DisplayVersion"));\n        if (columns.Contains("InstallDate"))\n        {\n            string InstallDate = Convert.ToString(subkey.GetValue("InstallDate"));\n        }\n\n    }\n }\ncatch (Exception ex)\n {\n    throw ex;\n }\n}	0
22561194	22560882	conversion of a varchar data type to a datetime data type resulted in an out-of-range value executing stored procedure	SET @query = 'INSERT INTO [' +@tableName+'] (timeStamp) VALUES (''' +\n             CONVERT(nvarchar, @timeStamp, 126) + ''')'\nEXEC (@query)	0
5596505	5591269	.Net: Inserting with index in a ListView in LargeIcon mode don't display inserted items in right position	ListView1.Alignment = ListViewAlignment.Default\n        ListView1.Alignment = ListViewAlignment.Top	0
15185384	15184495	Parsing windows 'ipconfig /all' output	foreach (var line in lines)\n{\n   var index  = line.IndexOf (':') ;\n   if (index <= 0) continue ; // skip empty lines\n\n   var key   = line.Substring (0,  index).TrimEnd (' ', '.') ;\n   var value = line.Substring (index + 1).Replace ("(Preferred)", "").Trim () ;\n}	0
32426371	32425423	Reverse the words in a string without using builtin functions like split and substring in C#	String name = "Hello World";\nStringBuilder builder = new StringBuilder();\n\nfor (int i = 0; i < name.length(); i++)\n{\n    char tmp = name.charAt(i);\n    if(tmp == ' ' || i == name.length() - 1) {\n        // Found a whitespace, what is preceding must be a word\n        builder.insert(0,  ' ');\n        for(int j = i - 1; j >= 0; j--) {\n            if(i == name.length() - 1 && j == i - 1) {\n                // Exceptional case (necessary because after the last word there is no whitespace)\n                builder.insert(0, name.charAt(i));\n            } \n\n            char curr = name.charAt(j);\n\n            if(curr == ' ') {\n                // We passed the beginning of the word\n                break;\n            }\n            else if(j == 0) {\n                builder.insert(0,  curr);\n                break;\n            }\n\n            //builder.append(curr);\n            builder.insert(0, curr);\n        }\n    }\n}\n\nString newName = builder.toString();\nSystem.out.println(newName);	0
8385617	8385563	Store array into a data table	var reader = new StreamReader(File.OpenRead(@"d:\er.txt"));\nvar table = new DataTable("SampleTable");\nint columnCount = 0;\nwhile (!reader.EndOfStream)\n{\n  var line = reader.ReadLine().Trim();\n  var values = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);\n  string[] ee = values;\n  while (columnCount < ee.Length) \n  {\n    // Only add a new column if it's required.\n    table.Columns.Add();\n    columnCount++;\n  }\n  var newRow = table.NewRow();\n  for (int i = 0; i < ee.Length; i++)\n  {\n      newRow[i] = ee[i].Trim().ToString(); // like sample [0,0]\n  }\n  table.Rows.Add(newRow);\n}	0
32550249	32545970	after adding querystring parameter to web application method fails	protected void Page_Load(object sender, EventArgs e)\n{\n\n    if (!Page.IsPostBack)\n    {\n        PopulateRootLevel();\n        string GetStructure = Request.QueryString["Structure"];\n        if (String.IsNullOrEmpty(GetStructure))\n        {\n        }\n        else\n        {\n            InputNodeToOpen.Text = GetStructure;\n            ButtonClick_transmit(button1, EventArgs.Empty);\n            InputNodeToOpen.Text = "";\n            IDNodesToBeOpened.Text = "";\n\n        }\n    }\n}	0
3613123	3607571	C# - DevExpress XtraGrid - Master/Detail - Display Format	private void gridView1_MasterRowExpanded_1(object sender, CustomMasterRowEventArgs e) {\n    GridView master = sender as GridView;\n    GridView detail = master.GetDetailView(e.RowHandle, e.RelationIndex) as GridView;\n    detail.Columns["SomeColumn"].DisplayFormat = ....\n}	0
2570002	2569538	Detecting if a PNG image file is a Transparent image?	bool ContainsTransparent(Bitmap image)\n    {\n        for (int y = 0; y < image.Height; ++y)\n        {\n            for (int x = 0; x < image.Width; ++x)\n            {\n                if (image.GetPixel(x, y).A != 255)\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }	0
18235638	18235472	Contains method for compare string array in C#	string[] keys = key.Split('+');\nvar pages = context.Pages.Where(x => keys.Any(key => x.Title.Contains(key)));	0
31592722	31592504	Populate dropdown box from SQL Server using a function	Private Function getallproducts() As List(Of product)\n\nTry\n    Using db As New PropSolWebDBEntities\n        Dim products As list(Of product) = (From x In db.product Select x).ToList()\n        Return products\n    End Using\n\nCatch ex As Exception\n    Return Nothing\nEnd Try	0
4994867	4994690	How can I transform XY coordinates and height/width on a scaled image to an original sized image?	NewTop    = ((   OldTop    ) * NewHeight / OldHeight);\nNewLeft   = ((   OldLeft   ) * NewWidth  / OldWidth );\n\nNewBottom = ((OldBottom + 1) * NewHeight / OldHeight) - 1;\nNewRight  = ((OldRight  + 1) * NewWidth  / OldWidth ) - 1;	0
24772580	24772509	Parse Json using Windows.Data.Json in Windows 8 C#	JsonObject settingsVal = test1.GetNamedValue( "settings" ).GetObject();	0
684921	684873	Lost in .Net SDK with C# due finding the documentation	site:msdn.microsoft.com	0
22683248	22682056	Give dynamic name in Report Header in crystal report	dt.columns.Add("ReportHeader");\nfor(int i=0;i<dt.rows.count;i++)\n{\ndt.rows[i]["ReportHeader"]=comboReportHeader.Text;\n}	0
30649095	30648783	How to maintain Start and End index of DataTable	DataTable dt = new DataTable();\n            dt.Columns.Add("Index", typeof(int));\n            dt.Rows.Add(new object[]{1});\n            dt.Rows.Add(new object[]{2});\n            dt.Rows.Add(new object[]{3});\n            dt.Rows.Add(new object[]{4});\n            dt.Rows.Add(new object[]{5});\n            dt.Rows.Add(new object[]{6});\n            dt.Rows.Add(new object[]{7});\n            dt.Rows.Add(new object[]{8});\n            dt.Rows.Add(new object[]{9});\n            dt.Rows.Add(new object[]{10});\n            dt.Rows.Add(new object[]{11});\n            dt.Rows.Add(new object[]{12});\n            dt.Rows.Add(new object[]{13});\n            dt.Rows.Add(new object[]{14});\n            dt.Rows.Add(new object[]{15});\n            dt.Rows.Add(new object[]{16});\n\n\n            var results = dt.AsEnumerable()\n                .Select((x,i) => new {index = i, row = x})\n                .GroupBy(y => (int)(y.index/5))\n                .Select(z => z.Select(a => a.row).ToList()).ToList();	0
5895818	5895682	What's an algorithm to retrieve values for a week to date calculation	static IEnumerable<DateTime> DaysFromMonday(DateTime d)\n    {\n        var diff = d.DayOfWeek - DayOfWeek.Monday;\n        var monday = d.AddDays(-diff).Date;\n        for (var day = monday; day < d; day = day.AddDays(1))\n            yield return day;\n    }	0
13623716	13623651	Analysing line by line and storing if meets criteria, else ignore	while ((line = reader.ReadLine()) != null)\n{\n    var beginning = line.Substring(0, 3);\n    if(beginning != "100" && beginning != "200" && beginning != "300")\n        continue;\n    list.Add(line); // Add to list.\n    Console.WriteLine(line); // Write to console.\n}	0
24118099	24118048	Creating new AD-LDS user with UserPrincipal-class always fails	using (UserPrincipal user = new UserPrincipal(ctx)) {\n    user.Name = userName;\n    user.UserPrincipalName = userName;\n    user.SetPassword(password);\n    user.Save();\n    user.Enabled = true;\n    user.Save();\n}	0
641669	641660	Will a using statement rollback a database transaction if an error occurs?	private void Dispose(bool disposing)\n{\n    // ...\n    if (disposing && (this._innerConnection != null))\n    {\n        this._disposing = true;\n        this.Rollback(); // there you go\n    }\n}	0
29594161	29593919	Bitmasking small numeric values over a byte array without wasting space in c#?	public class FiveBit {\n\n  private byte[] _data;\n\n  public FiveBit(int len) {\n    _data = new byte[(len * 5 + 7) / 8];\n  }\n\n  public int this[int index] {\n    get {\n      int i = index * 5 / 8;\n      int ofs = index * 5 % 8;\n      if (ofs > 3) {\n        return ((_data[i] + _data[i + 1] * 256) >> ofs) & 31;\n      } else {\n        return (_data[i] >> ofs) & 31;\n      }\n    }\n    set {\n      int i = index * 5 / 8;\n      int ofs = index * 5 % 8;\n      int mask = 31 << ofs;\n      _data[i] = (byte)((_data[i] & ~mask) | (value << ofs));\n      if (ofs > 3) {\n        _data[i + 1] = (byte)((_data[i + 1] & ~(mask >> 8)) | (value >> (8 - ofs)));\n      }\n    }\n  }\n\n}	0
23661613	23659301	Storing image as stream in database - WPF	Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();\n        if (fd.ShowDialog() == true)\n        {\n            ILogo.Source = new BitmapImage(new Uri(fd.FileName));\n\n            Stream stream = File.OpenRead(fd.FileName);\n            binaryImage = new byte[stream.Length];\n            stream.Read(binaryImage, 0, (int)stream.Length);\n        }\n\n        _merchantInfo.Logo = binaryImage;\n        _context.SaveChanges();	0
5964651	5964557	How can I make word visible when opening a document through interop?	word.Visible = true;	0
25932148	25931688	Remove node from xmlDocument	child.ParentNode.RemoveChild(child)	0
1866558	1866533	Returning items randomly from a collection	public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> source, int count)\n{\n    var array = source.ToArray();\n    return ShuffleInternal(array, Math.Min(count, array.Length)).Take(count);\n}\n\nprivate static IEnumerable<T> ShuffleInternal<T>(T[] array, int count)\n{\n    for (var n = 0; n < count; n++)\n    {\n        var k = ThreadSafeRandom.Next(n, array.Length);\n        var temp = array[n];\n        array[n] = array[k];\n        array[k] = temp;\n    }\n\n    return array;\n}	0
23194794	23194590	Getting values of items in IList?	public class CustomClass\n    {\n        public string GroupName { get; set; }\n        public int GroupID { get; set; }\n    }\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        List<CustomClass> list = new List<CustomClass>();\n        foreach (var x in list) {\n            Console.WriteLine(x.GroupName);\n        }\n\n    }	0
1890194	1890178	Limit RemoveAll to a certain number of objects	var matches = myList.Where(item => item.Child && "Foo".Equals(item.Parent.SpecialType)).Take(someNumber).ToList();\nmatches.ForEach(m => myList.Remove(m));	0
17025114	17025066	Sort a Dictionary by Its Value in Human Sort Order	List<KeyValuePair<string, string>> myList = aDictionary.ToList();\n\nmyList.Sort(\n    delegate(KeyValuePair<string, string> firstPair,\n    KeyValuePair<string, string> nextPair)\n    {\n        return firstPair.Value.CompareTo(nextPair.Value);\n    }\n);	0
16791057	16790695	connect to sql server database hosted on pc from windows ce through network	[WebMethod]\n    public void ExecuteSql(string query)\n    {\n       SqlCommand cmd  = new SqlCommand();\n       cmd.Connection = new SqlConnection("connectionstring");\n       cmd.CommandType = CommandType.Text;\n       cmd.CommandText = query;\n       cmd.Connection.Open();\n       cmd.ExecuteScalar();\n       cmd.Connection.Close();\n    }	0
6013386	6013305	How to optimize this Code	var type = typeof(TInterface);\nvar types = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.GlobalAssemblyCache)\n    .SelectMany(s => s.GetTypes())\n    .Where(t => type.IsAssignableFrom(t));	0
2418479	2418448	How do I apply a String extension to a Func<String>	GetName = () => getName().CapitalizeWords();	0
19498301	19497941	How to determine if a date it was yesterday, in the last month, in the last year using c#?	bool IsYesterday(DateTime dt)\n{\n    DateTime yesterday = DateTime.Today.AddDays(-1);\n    if (dt >= yesterday && dt < DateTime.Today)\n        return true;\n    return false;\n}\n\nbool IsInLastMonth(DateTime dt)\n{\n    DateTime lastMonth = DateTime.Today.AddMonths(-1);\n    return dt.Month == lastMonth.Month && dt.Year == lastMonth.Year;\n}\n\nbool IsInLastYear(DateTime dt)\n{\n    return dt.Year == DateTime.Now.Year - 1;\n}	0
32269706	32269656	How do I get the second element in a collection, using LINQ?	var source = _context.SourceLogs.Where(...).Skip(1).First();	0
29606615	29606428	cannot get a timespan to add to a datetime	var allNewStops = (from stops in rDb.DistributionStopInformations\n                       where stops.CustomerNo == 91000 && stops.StopSignature != "" && stops.ActualServiceDate == dateToCheck select stops)\n                       .AsEnumerable().Select(stops => new {     \n                           stopName = stops.StopName,\n                           signature = stops.StopSignature,\n                           customerRefNumber = stops.CustomerReference,\n                           dateOfStop = stops.ActualServiceDate,\n                           timeOfStop = stops.ActualArrivalTime,\n                           combinedStop = ((DateTime)stops.ActualServiceDate).Add((TimeSpan)stops.ActualArrivalTime)\n\n                       }).Distinct();	0
12723033	12722959	Converting RBG to hex	int number = 111000111;\nColor c = Color.FromArgb(number);\nstring hex = string.Format("{0:x}{1:x}{2:x}", c.R, c.G, c.B);	0
8801671	8801616	Replace with pattern matching	newTextBox.Text =\n    Regex.Replace(\n        newTextBox.Text,\n        @"<Value>[^\<]+</Value>",\n        "<Value>" + textBoxName.Text + "</Value>");	0
20429029	20428140	How to compare the difference between two periods of time using DateTime?	public static bool IsValid(ClassTest current, ClassTest other)\n{\n    if (!other.Primal || !current.Primal)\n        return true;\n    if (current.End.HasValue \n        && other.End.HasValue\n        && (other.End.Value <= current.Begin || other.Begin >= current.End.Value))\n        return true;\n    if (!current.End.HasValue \n        && other.End.HasValue\n        && other.End.Value <= current.Begin)\n        return true;\n    if (current.End.HasValue \n        && !other.End.HasValue\n        && other.Begin >= current.End.Value)\n        return true;\n\n    return false;\n}\n\nvar isUnique = existing.All(item => IsValid(item, newItem));	0
17067768	17067037	I have a code to generate cycles in a graph but it gets slow when the points are more	int[,] graph =\n            {\n                {1, 2}, {1, 3}, {1, 4}, {2, 3},\n                {3, 4}, {2, 6}, {4, 6}, {7, 8},\n                {8, 9}, {9, 7}, {2, 3}, {1, 5}, {2, 4}, {4, 6},\n                {7, 4}, {3, 5}, {4, 5}, {2, 8},\n                {8, 1}, {9, 1}, {14,1}, {2,14}, {5, 1}, {7, 3}, {6, 2}, {10,1},\n                {10, 4}, {10, 6}, {10, 3}, {10,2},\n                {8, 3}, {1, 7}\n            };\nvar g = graph.Cast<int>().ToArray();\nvar edges = Enumerable.Range(0, g.Length / 2) \n      .Select(i => Tuple.Create(g[i * 2], g[i * 2 + 1]));\nvar edgeLookup = edges.ToLookup(x => x.Item1);\nvar stack = new Stack<Tuple<int, int>>(edgeLookup.First());\nvar visited = new HashSet<Tuple<int, int>>();\n\nwhile(stack.Count > 0)\n{\n    var current = stack.Pop();\n    if(!visited.Add(current)) throw new Exception("cycle!!!");\n    var newNodes = edgeLookup[current.Item2];\n    foreach(var newNode in newNodes)\n    {\n        stack.Push(newNode);\n    }\n}	0
6217688	6186861	Using UIHint in combination with LINQ to SQL generated class	using System.ComponentModel.DataAnnotations;\n\nnamespace Project.Models\n{\n  [MetadataType(typeof(ProductsMeta))]\n  public partial class Products\n  {\n    // You can extend the products class here if desired.\n\n    public class ProductsMeta\n    {\n      // This is a Linq-to-Sql Buddy Class      \n      // In here you can add DataAnnotations to the auto-generated partial class\n\n      [Key]\n      public int ProductKey { get; set; }\n\n      [Display (Name = "Product Name")]\n      [Required(ErrorMessage = "Product Name Required")]\n      [StringLength(255, ErrorMessage = "Must be under 255 characters")]\n      public string ProductName { get; set; }\n\n      [UIHint("MultilineText")]\n      public string Description { get; set; }\n    }\n  }\n}	0
31192049	31192000	Lambda Expression with OR expression	List<MyClass> myData = Db.Select<MyClass>(q => \n   q.Where(n => n.thisfield.StartsWith("d1") || n.thisfield.StartsWith("d2"));	0
9219482	9219358	Can a file be read and written right back with small changes without knowing its encoding in C#?	Encoding.Default	0
14451379	14376976	JSON byte array value changed in webservice	byte [] image = array;\nString stringToStore = new String(Base64.encode(image));	0
2196571	2195684	App doesn't exit when main window is closed	Application.Current.Shutdown();	0
6564625	6564606	C#: Use of unassigned local variable, using a foreach and if	public string return_Result(String[,] RssData, int marketId)\n{\n    string result = "";\n    foreach (var item in RssData)\n    {\n        if (item.ToString() == marketId.ToString())\n        {\n            result = item.ToString();\n        }\n    }\n    return result;\n}	0
12827914	12826872	passing a variable through querystring	int mediaID =\n    int.Parse(((Hashtable)grd_AllMedia.SelectedRecords[0])["MediaID"].ToString());\n\nResponse.Redirect(string.Format("EditMedia.aspx?MediaID={0}", mediaID));	0
30160983	30160733	I need to create an interface in c# and a method to load a list of the interface	public static class TeamSelectHeleper\n{\n    public static double GetTotalByTeam(this List<ITotal> myList)\n    {\n        // TODO Sum wont work this way - fix it\n        //return myList.GroupBy(x => x.Team.Id).Sum(s => s.Total);\n\n        // If you need just a sum, then just sum it.\n        // but if you need group results,\n        // then you can just return on number when there is a list\n        return myList.Sum(s => s.Total);\n    }\n}	0
9216471	9216389	DateTime Conversion with Different Cultures	d.getUTCFullYear()+"-" + d.getUTCMonth() + "-" + d.getUTCDate()	0
32501900	32499357	WriteableBitmap from Uri Windows phone 8.1	var uri = new Uri("ms-appx:///Images/imageName.png");\nvar storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);\nvar writeableBitmap = new WriteableBitmap(pixelHeight, pixelWidth);\nusing (var stream = await storageFile.OpenReadAsync())\n{\n    await writeableBitmap.SetSourceAsync(stream);\n}	0
28817088	28809343	Using recordset values in SQL Server 2008 R2	...\nOdbcDataAdapter d;\nDataTable dt;\nd = new OdbcDataAdapter(cmd);\nd.Fill(dt);\n... \nforeach (DataRow row in dt.Rows)\n{\n   foreach (DataColumn column in dt.Columns)\n   { // fill the column header for the first time by column.ColumnName.\n   }\n   foreach (DataColumn column in dt.Columns)\n   { // fill the colum values using row[column] combination.\n   }\n}	0
24133426	24132775	Sendkeys for Windows Start key	private const int KEYEVENTF_EXTENDEDKEY = 0x1;\nprivate const int KEYEVENTF_KEYUP = 0x2;\n\n[DllImport("user32.dll")]\nstatic extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);\n\nprivate static void PressKey(byte keyCode)\n{\n    keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);\n    keybd_event(keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);\n}	0
24529798	24527641	Get "Log on as" value of a service with c#	"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{ServiceName}\ObjectName"	0
14481644	14481553	create a random loop until a statement is true	private void button1_Click(object sender, EventArgs e)\n{\n      var rc = new Random();\n      do\n      {\n        storeRI = rc.Next(1, 9);\n\n        if (storeRI == 1)\n        {\n            if (button1.Text == "")\n            {\n                button1.Text = "X";\n            }\n        }\n\n        else if (storeRI == 2)\n        {\n            if (button1.Text == "")\n            {\n                button1.Text = "X";\n            }\n        }\n      } while (button1.Text == "");\n }	0
1043530	1043149	How to use the C# Generics in delphi 2009/2010?	function TReader.Read <T>: T;\nbegin\n  if FIndex + SizeOf (T) > Length (FDataRead) then\n    raise Exception.Create ('Error 101 Celebrity');\n  Move (FDataRead[FIndex], Result, SizeOf (T));\n  Inc (FIndex, SizeOf (T));\nend;	0
12056578	12056255	How to deal with deprecated values in (country-)code lists	protected void LoadSourceDropdownList(bool AddingNewRecord, int ExistingCode)\n    {\n        using (Entities db = new Entities())\n        {\n            if (AddingNewRecord) // when we are adding a new record, only show 'active' items in the drop-downlist.\n                ddlSource.DataSource = (from q in db.zLeadSources where (q.Active == true) select q);\n\n            else // for existing records, show all active items AND the current value.\n                ddlSource.DataSource = (from q in db.zLeadSources where ((q.Active == true) || (q.Code == ExistingCode)) select q);\n\n            ddlSource.DataValueField = "Code";\n            ddlSource.DataTextField = "Description";\n            ddlSource.DataBind();\n\n            ddlSource.Items.Insert(0, "--Select--");\n            ddlSource.Items[0].Value = "0";\n        }\n    }	0
12657349	12657307	Using a WCFService to kick off a program on different machine	[ServiceContract]\npublic interface IMyService\n{\n    [OperationContract(IsOneWay=true)]\n    void IAmALongRunningMethodAndIDontCareToReturnAnything();\n}	0
12939543	12938940	Efficient insert statement	Insert Into Journeys(DepartureID, ArrivalID, ProviderID, JourneyNumber, Active)\nSelect \n    dbo.GetHubIDFromName(StartHubName), \n    dbo.GetHubIDFromName(EndHubName), \n    dbo.GetBusIDFromName(CompanyName), \n    JourneyNo, 1\nFrom Holding\nORDER BY HoldingID ASC	0
4152767	4152733	How to Implement Clone and Copy method inside a Class?	public MyClass Clone()\n    {\n        MemoryStream ms = new MemoryStream();\n        BinaryFormatter bf = new BinaryFormatter();\n\n        bf.Serialize(ms, this);\n\n        ms.Position = 0;\n        object obj = bf.Deserialize(ms);\n        ms.Close();\n\n        return obj as MyClass;\n    }	0
26759607	26756201	Decode hex chars in string	public static string RemoveInvalidXmlChars(string str)\n{\n\n    var sb = new StringBuilder();\n    var decodedString = HttpUtility.HtmlDecode(str);\n\n    foreach (var c in decodedString)\n    {\n        if (XmlConvert.IsXmlChar(c))\n            sb.Append(c);\n    }\n\n    return sb.ToString();\n}	0
9904293	9818826	Any way to programmatically get the FPS of a video?	ShellFile shellFile = ShellFile.FromFilePath(sourceFile);\n        return (shellFile.Properties.System.Video.FrameRate.Value / 1000).ToString();	0
31202092	31201982	How to Parse a nullable DateTime during a LINQ group operation?	group x \nby string.IsNullOrEmpty(x.MyDate) ? (int?)null : DateTime.Parse(x.MyDate).Year\ninto g	0
25760509	25758930	c# Excel How to Change from [,] [.] to [.][,]	using System;\nusing System.Windows.Forms;\nusing Microsoft.Office.Interop.Excel;\nusing Application = Microsoft.Office.Interop.Excel.Application;\nusing Excel = Microsoft.Office.Interop.Excel;\n\npublic partial class Form1 : Form\n{   \n    private void button1_Click(object sender, EventArgs e)\n    {\n        Application excelApplication = new Excel.Application\n        {\n            Visible = true,\n            ScreenUpdating = true,\n            DecimalSeparator = ".",\n            ThousandsSeparator = ",",\n            UseSystemSeparators = false\n        };\n\n        _Workbook workbook = excelApplication.Workbooks.Add();\n        _Worksheet sheet = workbook.Worksheets[1];\n        Range range = sheet.Range["A1"];\n        range.Formula = "1,234,567.89";\n\n        // re-set\n        excelApplication.UseSystemSeparators = true;\n\n        excelApplication.Quit();\n    }\n}	0
707796	705596	C#: Blowfish Encipher a single dword	(DWORD *)(pInput + 4)	0
11983990	11983925	generating rtf from template in c# winforms app	StringBuilder sb = new StringBuilder(yourTemplate);\nsb.Replace("[text]", "car");\nsb.Replace("[replaced]", "washed");	0
3942990	3942218	How to Use compare validator	[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]\npublic class ChangePasswordModel\n{\n    [Required]\n    [DataType(DataType.Password)]\n    [DisplayName("Current password")]\n    public string OldPassword { get; set; }\n\n    [Required]\n    [ValidatePasswordLength]\n    [DataType(DataType.Password)]\n    [DisplayName("New password")]\n    public string NewPassword { get; set; }\n\n    [Required]\n    [DataType(DataType.Password)]\n    [DisplayName("Confirm new password")]\n    public string ConfirmPassword { get; set; }\n}	0
18324522	18324236	pass data to constructor	public abstract class ViewModelBase : INotifyPropertyChanged\n{\n    bool _isCurrentPage;\n\n    protected MyData MyData { get; private set; }\n\n    public ViewModelBase(MyData myData)\n    {\n        MyData = myData;\n    }\n}\n\npublic class WelcomePageViewModel : ViewModelBase\n{  \n    public WelcomePageViewModel(MyData myData)\n        : base(myData)\n    {\n       // Access the protected property\n       MyLogger.WriteLine("Grabbed an instance of myData: " + MyData.ToString());\n    }\n}	0
15294522	15294479	Display currency format	[DisplayFormat(DataFormatString="{0:C}")]\npublic decimal Price { get; set; }	0
26056043	25888558	System.FormatException: Invalid format. While trying to add a Header Key	_httpClient.DefaultRequestHeaders.Clear();	0
16349137	16342476	How to create index in SQL from c#	CREATE INDEX	0
24973003	24972853	How to check if OnNavigatedTo was triggered by back button in Windows Phone 8.1 Universal app?	if (e.NavigationMode == NavigationMode.Back)\n{\n\n // navigation is going backward in the stack\n\n}	0
6959414	6959299	OnRowClick in a GridView not taking over button clicks?	GridView1.OnRowCommand += _gridView_RowCommand	0
20722381	20721780	Checking value of DataGridViewCheckBoxColumn	bool status=(bool)dataGridView3.Rows[0].Cells[0].Value;\n        if (status)\n        {\n            MessageBox.Show("Checked");\n        }\n        else\n        {\n            MessageBox.Show("Not Checked");\n        }	0
20157167	20157141	Method naming GetX by multiple parameters	public FooClass GetByProperties(params string[] list)	0
6996852	6996803	How can I make my C# code check each file in a directory?	string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);\nforeach(string file in files)\n{\n    string[] lines = File.ReadAllLines(file);\n    foreach (string line in lines)\n    {\n        process(line);\n    }        \n}	0
13606576	13605980	access global javascript variable in c# webbrowser	mapWebBrowser.Document.GetElementById("distance").InnerHtml	0
14007576	13999884	WPF Treeview using linq to entities multiple relations	Categories = query.ToList<Category>();\n        foreach (Category c in Categories)\n        {\n            TreeViewItem TVP = new TreeViewItem() { Header = c.CategoryName.ToString() };\n\n            var query2 = from xx in ctx.RecipeCategories.Where(o => o.CategoryId == c.CategoryId) select xx;\n            foreach (var rc in query2)\n            {\n\n                TreeViewItem TVC = new TreeViewItem() { Header = rc.Recipe.RecipeName.ToString() };\n                TVP.Items.Add(TVC);\n\n            }\n            tvwRecipe.Items.Add(TVP);\n        }	0
24546592	24546136	Creating SQL Server Table in C#	string table = @"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'details') AND type in (N'U'))\nCREATE TABLE  details( Admission_no  char(50),First_Name char(50),Father_name char(50),recepit_no char(50),selectdate  datetime,acedemic_year char(50),class1 char(50),section char(50), roll_no char(50))\n";\n\nstring fee_table = @"\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'fees') AND type in (N'U'))\nCREATE TABLE fees(Admission_no char(50),  prospectues_fee float, registration_fee float,admission_fee float,security_money float,misslaneous_fee float,development_fee float,transport_fair float,computer_fee float,activity float,hostel_fee float,dely_fine float,back_dues float,tution_fee float,other_fee float,total float) \n";	0
12527803	12525480	use a ListBox to Filter Datagrid	public IEnumerable<Quote> FilteredQuotes { get {\n  return from x in Quotes where x.Supplier.IsChecked select x; } }	0
929277	929276	How to recursively list all the files in a directory in C#?	static void DirSearch(string sDir)\n   {\n       try\n       {\n           foreach (string d in Directory.GetDirectories(sDir))\n           {\n               foreach (string f in Directory.GetFiles(d))\n               {\n                   Console.WriteLine(f);\n               }\n               DirSearch(d);\n           }\n       }\n       catch (System.Exception excpt)\n       {\n           Console.WriteLine(excpt.Message);\n       }\n   }	0
4610247	4610062	How to cast a built-in struct to a parameter type T on C#?	public static T Query<T>() {\n    var converter = TypeDescriptor.GetConverter(typeof (T));\n    if (!converter.CanConvertFrom(typeof(String)))\n        throw new NotSupportedException("Can not parse " + typeof(T).Name + "from String.");\n\n    var input = Console.ReadLine();\n\n    while (true) {\n        try {\n            // TODO: Use ConvertFromInvariantString depending on culture.\n            return (T)converter.ConvertFromString(input);\n        } catch (Exception ex) {\n            // ...\n        }\n    }\n}	0
26241396	26241319	C#, How to sort DataTable in a customised order?	DataTable dt =  YOURTABLE.Select("Animals == 'Hamster'").CopyToDataTable();\nDataTable dt2 = YOURTABLE.Select("Animals != 'Hamster'").CopyToDataTable();\n\ndt2 = dt2.Sort = "Animals + " " + "Asc";\ndt.Merge(dt2);\nYOURTABLE = dt;	0
30803630	30786597	Inserting alot of data in table with EF	INSERT INTO MyTable (col1 col2, UserID)\nSELECT @Param1, @Param2, [ID] FROM [User]	0
24405029	24404677	How do I write data column b y column to a csv file	int iWantedStringLength = 20;\n\n// Edited here:\nstring sFormatInstruction = "{0,-" + iWantedStringLength.ToString() + "}";\n\nfor (int i = 0; i < RowCount; i++)\n    {\n        for (int j = 0; j < ColumnCount; j++)\n        {\n            sw.Write(String.Format(sFormatInstruction, Transfer_2D[i][j]));//write one row separated by columns\n            if (j < ColumnCount)\n            {\n                sw.Write(";");//use ; as separator between columns\n            }\n        }\n        if (i < RowCount)\n        {\n            sw.Write("\n");//use \n to separate between rows\n        }\n    }	0
11490464	11490426	Implementing properties with help of enum operator	public object GetKye(KyeType type)\n{\n    switch (type)\n    {\n        case KyeType.String:\n            return this.kye;\n        case KyeType.Int32:\n            return Int32.Parse(this.kye);\n        case KyeType.Bool:\n            return this.kye.ToLower().Equals("true");\n    }\n    return null;\n}	0
5625559	5623209	C# (outlook add-in) context menu on folders	// where Folder is a local variable in scope, such as code in post\ncontextButton.Click += (CommandBarButton ctrl, ref bool cancel) => {\n   DoReallStuff(ctrl, Folder, ref cancel);\n};	0
13682441	13681769	selected index of datalist contains checkboxlist	Protected void dtlstfilter_SelectedIndexChanged(object sender, EventArgs e)\n {\n   var control= ((Control)sender).Parent;\n    if(control is DataListItem)\n    {\n       int index=((DataListItem)control).ItemIndex;\n    }\n}	0
30856173	30855875	Getting a JavaScript object into my controller: What am I missing here?	{'org': 'string1', 'cat': 'string2', 'fileName': 'string3'}	0
696355	696331	split string based on regexp	string example = "a : b : \"c:d\"";\nstring[] splits = Regex.Split(example, @"\s:\s");	0
3360098	3092101	How to fill a list view with the contents of Dictonary<string,List<String>> in C#	int Index=0;\n        foreach(KeyValuePair<String,List<String>>KVP in Dict)\n        {\n            ListViewItem LVI = listView1.Items.Add((Index + 1).ToString());\n            LVI.SubItems.Add(KVP.Key);\n            LVI.SubItems.Add(KVP.Value.Select(X => X).Aggregate((X1, X2) => X1 + "," + X2));\n            Index++;\n\n        }	0
9636517	9636438	Expression Lambda versus Statement Lambda	Action myDelegate1 = () => Console.WriteLine("Test 1");\nExpression<Action> myExpression = () => { Console.WriteLine("Test 2") }; //compile error unless you remove the { }\nmyDelegate1();\nAction myDelegate2 = myExpression.Compile();\nmyDelegate2();	0
15077272	15077015	How to know rows values sql server asp.net?	comando = new SqlCommand("SELECT user_name, user_id FROM login WHERE user_name=@user AND pass=@pass", conexion);\ncomando.Parameters.AddWithValue("@pass", Upass);\ncomando.Parameters.AddWithValue("@user", user);\n\n SqlDataReader reader = commando.ExecuteReader();\n        while (reader.Read())\n        {\n            var userName = Convert.ToString(reader["user_name"]);\n            var userId = Convert.ToInt32(reader["user_id"]); \n        }	0
27223874	27223850	show items of an array in MessageBox	private void button1_Click(object sender, EventArgs e)\n{\n   int tid;\n   tid = Convert.ToInt32(textBox1.Text);\n\n   foreach (var item in sekunder(tid))\n   {\n        MessageBox.Show(Convert.ToString(item));\n   }\n   // for comma separated \n   //use this : MessageBox.Show(string.Join(",",sekunder(tid)))\n}	0
3058080	3057980	WPF RichTextBox - Parent element from caret position	RichTextBox.CaretPosition.Parent	0
643286	643254	url building	StringBuilder sb = new StringBuilder();\nforeach(KeyValuePair<string,string> q in theList)\n{\n // build the query string here.\n    sb.Append(string.format("{0}={1}&", q.Key, q.Value);\n}	0
16596697	16592424	C# Launch default browser with a default search query	Process.Start("browser\path.exe", "\"? searchterm\"");	0
7718055	7717801	How to parse a simple page using html agility pack?	HtmlAgilityPack.HtmlWeb web = new HtmlWeb();\n        HtmlAgilityPack.HtmlDocument doc = web.Load("http://www.bodybuilding.com/exercises/detail/view/name/alternating-floor-press");\n        IEnumerable<HtmlNode> threadLinks = doc.DocumentNode.SelectNodes("//*[@id=\"exerciseDetails\"]");\n\n        foreach (var link in threadLinks)\n        {\n            string str = link.InnerText;\n            Console.WriteLine(str);\n        }\n        Console.ReadKey();	0
22998295	22998110	Don't apply ActionFilterAttribute to a specific route?	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\npublic sealed class HanlleyDisable : Attribute { }\n\npublic class SessionFilter : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        bool disabled = filterContext.ActionDescriptor.IsDefined(typeof(HanlleyDisable ), true) ||\n                        filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(HanlleyDisable), true);\n        if (disabled)\n            return;    \n\n        // action filter logic here...\n    }\n}\n\nclass FooController  {  \n\n    [HanlleyDisable]\n    MyMethod() { ... } \n\n}	0
13976418	13976253	CopyFileEx wrapper parameters	CopyFileCallbackAction myCallback(FileInfo source, FileInfo destination, object state, long totalFileSize, long totalBytesTransferred)\n{\n    double dProgress = (totalBytesTransferred / (double)totalFileSize) * 100.0;\n    progressBar1.Value = (int)dProgress;\n    return CopyFileCallbackAction.Continue;\n}\n\nFileRoutines.CopyFile(new FileInfo("source.txt"), new FileInfo("dest.txt"), myCallback);	0
5571721	5571309	join for insert statement mysql syntax	("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "') "+\n"GO UPDATE user SET flag = 1 WHERE UserID = "+theUserId+" GO", cn);	0
3427229	3427201	How to condense a bunch of IF statements using a List - is it possible?	var nullProps = doc1.SelectMany(d => d.Props).Where(prop => prop == null); \n//Assign\nforeach(var prop in nullProps)\n     doc1.Prop[prop.Name] = doc2.Prop[prop.Name];	0
8570514	8570452	How to return 2 value in c# method	public static Tuple<decimal?, decimal?> SpecialPrice(decimal w, decimal p)\n{\n   if (w < p)\n   {\n      return new Tuple<decimal?, decimal?>(p, null);\n   }\n   else if(w > p && p>0)\n   {\n      return new Tuple<decimal?, decimal?>(p, w);\n   }\n   else\n   {\n      return new Tuple<decimal?, decimal?>(w, null);\n   }\n}	0
24094704	24094604	Convert long string into multiple short strings	using Newtonsoft.Json; // This is the namespace of Newtonsoft. \n\n// this are the lines\ndynamic gameDataObj = JsonConvert.DeserializeObject(AllGameData);\n\nvar newStr = string.Format("{{\"mapId\":\"{0}\", \"gameMode\":\"{1}\", \"gameType\":\"{2}\"}}", gameDataObj.mapId, gameDataObj.gameMode, gameDataObj.gameType);	0
11135212	11127569	How can I make a WCF Data Service Query Interceptor return results in JSON?	[QueryInterceptor("Entities")]\npublic Expression<Func<Entity,bool>> OnQueryFares()\n{\n    return e => DataCheck(e);\n}	0
8435014	8434920	Using Directive to declare a pseudo-type in C#	List<List<string>>	0
8602287	8602229	Windows Service application app.config	app.config	0
15851382	15851277	Get list of items of type T from a class entity	A a = new A();\n// Populate a's `Items` property...\n....\n\nvar allC = a.Items.SelectMany(b => b.Items.Select( c => c)).ToList();	0
7579298	7569112	Storing a Dictionary<TKey, TValue> in isolated storage	using System.Runtime.Serialization;\n[DataContact]\npublic class classname()\n{\n[datamember]\npublic int propertyname;\n}	0
13533120	13532955	How To count how many times is clicked one Row in a GridView	static Dictionary <int, int> list = new Dictionary <int, int>();\n\nstatic YourClassName\n{\n  for(int i=0 ; i < 100 ; i++)\n  {\n     list.add(i,0);\n  }\n}\n\nprotected void SelectedIndexChanged (object sender, EventArgs e)\n{ \n  list.[gridview1.GridView1.SelectedRow.DataItemIndex]++;\n}	0
25192978	25192951	accessing variables from another class without instantiating	ErrorLib.ERR_FILE_NOT_FOUND	0
26477843	26468164	how to multiple select programmatically in PowerPoint	Sub SelectShapes()\n\n    With ActivePresentation.Slides(1)\n        .Shapes(1).Select msoTrue  ' Start a new selection\n        .Shapes(3).Select msoFalse ' Add to current selection\n    End With\n\n    ' and cut\n    ActiveWindow.Selection.Cut\n\nEnd Sub	0
2487489	2478636	How to start new browser window in cpecified location whith cpecified size	while (browserProc.MainWindowHandle == IntPtr.Zero)//???? ????? ?? ????????????? ???? ? ?????????\n            {\n                Thread.Sleep(50);// ???? 50 ??\n                browserProc.Refresh();// ????????? ???????\n            }	0
25581621	25581433	Changing the background color of winform using ColorDialog	Color.FromArgb()	0
14337327	14337252	Adding items to List<> of object which already contain data, add duplicate item in the List	proxy.SelectNextItemsCompleted += new EventHandler<ServiceReference1.SelectNextItemsCompletedEventArgs>(proxy_SelectNextItemsCompleted);	0
8982395	8982366	C# - Fastest way to get resource string from assembly	Assembly assembly = this.GetType().Assembly;\nResourceManager resourceManager = new ResourceManager("Resources.Strings", assembly);\nstring myString = resourceManager.GetString("value");	0
3242726	3242449	Linking Multiple Tables in LINQ to SQL	var albums = from singer in artist\n      from sb in singby\n      from t in track\n      from a in album\n    where singer.artistId == 1 && \n      sb.artistId == 1 && \n      sb.trackId == t.trackId && \n      a.albumId == track.albumId\n    select a;	0
32328991	32328471	How to fix standard control property at desired value?	[Browsable(false)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new bool TabStop {\n    get { return false; }\n    set { base.TabStop = false; }\n}	0
2477719	2477704	Regular expression for a list of numbers without other characters	"^(\d*\r\n)*$"	0
12635374	12635170	How to byte array received from socket, to C# structure	[StructLayout(LayoutKind.Sequential, Pack = 1)]\nstruct TREC_DATA\n{\n      public byte ID;\n      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]\n      public byte[] MAC_ADDRESS;\n      public uint fieldCard;\n      public short fieldSI;\n      public ushort fieldW;\n      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]\n      public byte[] SERIAL_NUMBER;\n      public float fieldSingle;\n      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]\n      public byte[] fieldArrOfB;    \n}	0
6516577	6516528	How to avoid anonymous methods in "dynamic" event subscription?	private void ListenToPropertyChangedEvent(INotifyPropertyChanged source,\n                                          string propertyName)\n{\n    var listener = new MyPropertyChangedListener(propertyName);\n    source.PropertyChanged += listener.Handle;\n}\n\nclass MyPropertyChangedListener\n{\n    private readonly string propertyName;\n\n    public MyPropertyChangedListener(string propertyName)\n    {\n        this.propertyName = propertyName;\n    }\n\n    public void Handle(object sender, PropertyChangedEventArgs e)\n    {\n        if (e.PropertyName == this.propertyName)\n        {\n            // do something\n        }\n    }\n}	0
20707979	18339706	How to create self-signed certificate programmatically for WCF service?	X509KeyStorageFlags.PersistKeySet	0
2629005	2628977	Getting Dictionary<string,string> from List<Control>	controls.ToDictionary(\n    c => c.Name,       // Key selector\n    c => c.Text);      // Element selector.	0
12689027	12688713	How to Refresh Combox After Deleting a Item From It C#	typeCb.Items.Clear();\n for (int i = 0; i < DataTable.Rows.Count; i++)\n typeCb.Items.Add(nTable.Rows[i][1].ToString());	0
12533528	12533037	I want to pass a parameter in C# method where it will accept for SQL query	public int ColumnCountinFailedQueue(long QueueNo)\n{\n    string query = "select count(QueueNo)\n                    from NS_FailedQueue\n                    where queueid = @QueueNo"; \n\n    int queueCount = 0;\n\n    using (SqlConnection connection = new SqlConnection("connectionString"))\n    using (SqlCommand getQueueCountCommand = new SqlCommand(query, connection))\n    {\n        getQueueCountCommand.Parameters.AddWithValue("@QueueNo", QueueNo);\n\n        connection.Open();\n        queueCount = (int)getQueueCountCommand.ExecuteScalar();\n    }\n\n    return queueCount;\n}	0
11086240	11086042	combobox with changing directory in c#	private void button1_Click(object sender, EventArgs e) {\n  using (FolderBrowserDialog fbd = new FolderBrowserDialog()) {\n    if (fbd.ShowDialog() == DialogResult.OK) {\n      UpdateComboBox(fbd.SelectedPath);\n    }\n  }\n}\n\nprivate void UpdateComboBox(string folderPath) {\n  comboBox1.Items.Clear();\n  foreach (string fileName in Directory.GetFiles(folderPath)) {\n    comboBox1.Items.Add(Path.GetFileName(fileName));\n  }\n}	0
15999171	15998576	Removing a controller name from a URL in MVC4	var url = "/Tenants/ViewProfile";	0
7716478	7716448	Format String Numeric to Currency	public String FormatValue( int valueAsCents ){\n  Decimal.Divide( (decimal)valueAsCents , 100.0 ).ToString("C");\n}	0
23715685	23715452	Send keyboard input to a specific child control	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n    if (msg.HWnd != dataGridView1.Handle && (keyData == Keys.Up || keyData == Keys.Down)) {\n        PostMessage(dataGridView1.Handle, msg.Msg, msg.WParam, msg.LParam);\n        return true;\n    } \n    return base.ProcessCmdKey(ref msg, keyData);\n}\n\n[System.Runtime.InteropServices.DllImport("user32.dll")]\nprivate static extern IntPtr PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);	0
31748092	31748016	How can I check if a string contains two other strings	ex.message.Contains("Cannot open server") && ex.message.Contains("requested by the login")	0
3387393	3387349	Create a WPF window from command prompt application	class Program\n{\n    [STAThread]\n    static void Main(string[] args)\n    {\n         MainWindow main = new MainWindow();\n         main.Show();\n         new Application().Run();\n    }\n}	0
29371259	29369277	List of a type that is defined at runtime	var type = MyExtensions.GetDataType(column as Enum);\n\n        DataTable dtAscen; //=logic to read table;\n        List<object> listBeforeSort = (from x in dtAscen.AsEnumerable()\n                            select (object)Convert.ChangeType(x.Field<string>(column.ToString()), type)).ToList();\n        var temp = listBeforeSort.OrderBy(s => s);\n        if(!listBeforeSort.SequenceEqual(temp))            \n            Utilities.log("Issue with ascending sort on column " + column.ToString(), LogType.ErrorEntry);	0
31186784	31179294	Build, pack up and deploy for multiple platform targets	NuGet pack YourProject.csproj	0
11451666	11341090	How to refresh row of DataGrid when DataGrid is binded to DataTable?	dataView.ListChanged += (o, e) =>\n{\n    if (e.ListChangedType == ListChangedType.ItemChanged)\n    {\n        DataRowView row = ((DataView)o)[e.NewIndex];\n        if(row != null)\n        {\n            MethodInfo method = typeof(DataRowView).GetMethod("RaisePropertyChangedEvent", BindingFlags.Instance | BindingFlags.NonPublic);\n            method.Invoke(row, new object[] { "Row" });\n        }\n    }\n};	0
8590343	8589392	Getting ip address from user name in VB.net	string name = "somename";\nIPAddress[] addresslist = Dns.GetHostAddresses(name);\n\nforeach (IPAddress theaddress in addresslist)\n{\n   Console.WriteLine(theaddress.ToString());\n}	0
23279014	23276851	Creating a Key Table and Domain Models	[Key]\npublic int NewClubEmail_Id    {get; set;}\n\n[Key]\npublic int NewClubProspect_Id {get; set;}	0
3157032	3156862	How to show only month and year of date in DataColumn of Datatable?	// Set the Format property on the "Last Prepared" column to cause\n// the DateTime to be formatted as "Month, Year".\ndataGridView1.Columns["Last Prepared"].DefaultCellStyle.Format = "y";	0
14022109	14020430	How To Get PPID	private static int GetParentProcess(int Id)\n    {\n        int parentPid = 0;\n        using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))\n        {\n            mo.Get();\n            parentPid = Convert.ToInt32(mo["ParentProcessId"]);\n        }\n        return parentPid;\n    }	0
17364865	17362333	Convert PDF to Image Batch	public void ConvertPdfPageToImage(string outputFileName, int pageNumber)\n{\n  if (pageNumber < 1 || pageNumber > this.PageCount)\n    throw new ArgumentException("Page number is out of bounds", "pageNumber");\n\n  using (GhostScriptAPI api = new GhostScriptAPI())\n    api.Execute(this.GetConversionArguments(this._pdfFileName, outputFileName, pageNumber, this.PdfPassword, this.Settings));\n}	0
1830717	1828878	Mocking an NHibernate ISession with Moq	[Test]\n        public void DummyTest()\n        {\n            var userList = new List<User>() { new User() { ID = 2, FirstName = "John", LastName = "Peterson" } };\n            var sessionMock = new Mock<ISession>();\n            var queryMock = new Mock<IQuery>();\n            var transactionMock = new Mock<ITransaction>();\n\n            sessionMock.SetupGet(x => x.Transaction).Returns(transactionMock.Object);\n            sessionMock.Setup(session => session.CreateQuery("from User")).Returns(queryMock.Object);\n            queryMock.Setup(x => x.List<User>()).Returns(userList);\n\n            var controller = new UsersController(sessionMock.Object);\n            var result = controller.Index() as ViewResult;\n            Assert.IsNotNull(result.ViewData);\n        }	0
4265882	4260432	How do I use Fluent NHibernate to map a self-referencing folder hierarchy?	mapping.HasMany(x => x.SubFolders).KeyColumn("ParentFolder_id");	0
14059742	354354	How can I dispose every instance object in StructureMap's ObjectFactory?	ObjectFactory.Container.Dispose();	0
32025030	32024983	How can I TryParse() a string inputted by the user?	if (!Double.TryParse(Console.ReadLine(), out my_number))\n   Console.WriteLine("not a double.");	0
24804953	24804871	C# start program with arguments containing strings	startInfo.Arguments = @"-Xmx1024-jar ""D:\Log4-cg.jar""";	0
8327855	8327782	Checking a files version from an external source?	var version = AssemblyName.GetAssemblyName("yourAssembly.dll").Version;	0
17789588	17789548	How can i set first day of first month of current year in datetimepicker	picker.Value = new DateTime(picker.Value.Year, 1, 1);	0
12332420	12332221	Open window (or dialog) to block main window without stopping further instructions	Form2 f = new Form2();\n        f.Show(this);\n        this.Enabled = false;\n\n        //do your stuff here\n\n        f.Hide();\n        this.Enabled = true;\n        f.Dispose();\n        f = null;	0
21452912	21452739	how can check the username and password in c#?	protected void loginButton_Click(object sender, EventArgs e)\n{\n\n    SqlConnection con = new SqlConnection();\n    con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=University;Integrated Security=True;Pooling=False";\n\n\n    Int32 verify;\n    string query1 = "Select count(*) from Login where ID='" + idBox.Text + "' and Password='" + passwordBox.Text + "' ";\n    SqlCommand cmd1 = new SqlCommand(query1, con);\n    con.Open();\n    verify = Convert.ToInt32(cmd1.ExecuteScalar());\n    con.Close();\n    if (verify > 0)\n    {\n        Response.Redirect("succesful.aspx");\n    }\n    else\n    {\n        Response.Redirect("unsuccesful.aspx",true);\n    }\n\n}	0
5841881	5832945	How do you put your design time view model in a separate assembly?	xmlns:designTime="clr-namespace:MyDesignTimeNS;assembly=MyBinaryName"\nd:DataContext="{d:DesignInstance designTime:DesignTimeObjectNameViewModel, IsDesignTimeCreatable=True}	0
5749858	5749801	Converting 2 bytes to Short in C#	int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);	0
33449228	33449149	Filtering list of objects based on string and bool in C#	public List<Node> FilterNodes(bool seachFavorite, string searchString)\n{\n     return initialnodesList.Where(l => (string.IsNullOrEmpty(searchString) || l.name.StartWith(searchString, StringComparison.OrdinalIgnoreCase)) && l.favorite == seachFavorite).ToList();\n}	0
25448245	25426005	Accessing VS' ITextTemplatingEngineHost in Preprocessed T4 Template in a VS Extension	STextTemplating vsHost = (STextTemplating)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(STextTemplating));\nvar vsHostEngine = vsHost as ITextTemplatingEngineHost;	0
13594631	12662426	How to click on a "pane" using UI automation library?	private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;\nprivate const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;\n\n[DllImport("user32.dll")]\nprivate static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo);\n\n...\n...\n\nAutomationElement paneToClick;\n\n...\n...\n\nCursor.Position = paneToClick.GetClickablePoint();\nmouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, new IntPtr());\nmouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, new IntPtr());	0
14200614	14191995	Removing Stencils from Visio Document	VisioDrawing.Document.Application.Documents.Item("BASFLO_M.vss").Close();	0
20948376	20948311	How to delete a file from App_Data folder in asp.net mvc 3 application?	File.Delete("~/App_Data/uploads/myfile.xls");	0
23207385	23103637	Using JSON.NET to deserialize to a derived class	private BaseFile Create(Type objectType, JObject jObject)\n{\n    var type = (string)jObject.Property("content_type");\n    switch (type)\n    {\n        case "application/x-directory":\n            return new Directory();\n        case "video/x-matroska":\n            return new Video();\n        default:\n            return new BaseFile();\n    }\n}	0
15081089	15080955	Keep track of pages visited	protected void newWindow(object sender, EventArgs e)\n{\n    List<int> questions = (List<int>)Session["Questions"];\n    if (questions == null)\n    {\n        questions = new List<int>(new int[] { 1, 2, 3, 4, 5 });\n    }\n\n    int nextIndex = new Random().Next(questions.Count());\n    int next = questions[nextIndex];\n    questions.RemoveAt(nextIndex);\n    Session["Questions"] = questions;\n\n    Response.Redirect(string.Format( "Question{0}.aspx", next ));\n}	0
19655311	19654679	How to Handle Routed Event From a Child Window	public static readonly RoutedEvent ButtonClickedEvent = EventManager.RegisterCrossWindowRoutedEvent(\n    "ButtonClicked",\n    RoutingStrategy.Bubble,\n    typeof(RoutedEventHandler),\n    typeof(ChildWindow));\n\npublic static void AddButtonClickedHandler(UIElement target, RoutedEventHandler handler)\n{\n    target.AddHandler(ButtonClickedEvent, handler);\n}\n\npublic static void RemoveButtonClickedHandler(UIElement target, RoutedEventHandler handler)\n{\n    target.RemoveHandler(ButtonClickedEvent, handler);\n}	0
2743221	2743154	Go to new site when a button is clicked 	System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(YourNewPageURL), "_blank", "toolbar=no,location=no,status=no,menubar=no,resizable=yes");	0
29840427	29840176	How to sort list of object based on list of object in another list/master list in C#?	var orderedSubList = subList.OrderBy (\n    s => masterList.IndexOf(masterList.FirstOrDefault(m => m.RollNumber == s.RollNumber))\n);	0
3431731	3431616	Get a MYSQL Date into a c# String exception	DateTime? date = null;\nif (!reader.IsDBNull(COLUM_INDEX))\n{\n    date = reader.GetDateTime(COLUM_INDEX);\n}	0
3063203	3059260	C# Detect Localhost Port Usage	bool IsBusy(int port)\n{\n    IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();\n    IPEndPoint[] endpoints = ipGlobalProperties.GetActiveTcpListeners();\n    if ( endpoints == null || endpoints.Length == 0 ) return false;\n    for(int i = 0; i < endpoints.Length; i++)\n        if ( endpoints[i].Port == port )\n            return true;\n    return false;          \n}	0
30435079	30432789	Determine amplitude of low frequency signals using FFT	/// <summary>\n    /// Returns a low-pass filter of the data\n    /// </summary>\n    /// <param name="data">Data to filter</param>\n    /// <param name="cutoff_freq">The frequency below which data will be preserved</param>\n    private float[] lowPassFilter(ref float[] data, float cutoff_freq, int sample_rate, float quality_factor=1.0f)\n    {\n        // Calculate filter parameters\n        float O = (float)(2.0 * Math.PI * cutoff_freq / sample_rate);\n        float C = quality_factor / O;\n        float L = 1 / quality_factor / O;\n\n        // Loop through and apply the filter\n        float[] output = new float[data.Length];\n        float V = 0, I = 0, T;\n        for (int s = 0; s < data.Length; s++)\n        {\n            T = (I - V) / C;\n            I += (data[s] * O - V) / L;\n            V += T;\n            output[s] = V / O;\n        }\n\n        return output;\n    }	0
1519239	1519203	Injecting a resource into an abstract class	private readonly Canvas canvas;\n\nprotected Shape(Canvas canvas)\n{\n    if(canvas == null)\n    {\n        throw new ArgumentNullException("canvas");\n    }\n    this.canvas = canvas;\n}	0
19546305	19434762	Balancing a Jagged array/List while mainting order in C#	double targetLength = System.Math.Round(totalLinecount / (double)displayColumnCount);\n\nwhile (result.Count != displayColumnCount)\n{\n    result = new List<List<MenuItem>>();\n    result.Add(new List<MenuItem>());\n    foreach (MenuItem menuItem in menuItems)\n    {\n        int currentLength = result.Last().Count == 0 ? 0 : result.Last().Sum(s => s.TotalLength);\n        if (result.Last().Count == 0 || (currentLength + menuItem.TotalLength) <= targetLength)\n        {\n            result.Last().Add(menuItem);\n        }\n        else\n            result.Add(new List<MenuItem> { menuItem });\n        }\n        targetLength++;\n        if (result.Count <= displayColumnCount) \n        break;\n    }\n}	0
2429768	2429719	what's a good way to implement something that looks like Dictionary<string, string, Dictionary<string, string>>?	Dictionary<string, KeyValuePair<string,Dictionary<string,string>>>	0
3157865	3157600	Correct way to implement web part personalisation for listboxes	WebPart.SetPersonalizationDirty(this);	0
17769466	17769148	Combo Box Size Issue After All Items Are Removed	if (versionComboBox.Items.Count == 0)\n{\n    versionComboBox.Text = string.Empty;\n    versionComboBox.Items.Clear();\n    versionComboBox.SelectedIndex = -1;\n}	0
5996286	5994431	C# Excel Reader turns Timestamps into a decimal number	DateTime.FromOADate	0
16087836	16087740	C# parameters in interface	Interface ITest\n{\n   void AddPerson(string name, string age);\n}\n\nInterface IPerson\n{\n    string ReturnPersonsAge(string name);\n}\n\n/// This must expose the AddPerson method\n/// This must also expose the ReturnPersonByAge method\nclass Example : ITest, IPerson\n{\n   Dictionary<string, string> people = new Dictionary<string, string>();\n\n   void AddPerson(string name, string age)\n   {\n      people.Add(name, age);\n   }\n\n   string ReturnPersonsAge(string name)\n   {\n      return people[name];\n   }\n}	0
12810496	12810384	How to tell EF Code First Migration system that database is updated	update-database -v -f -script	0
8565283	8564640	How to extend the HtmlHelper with the IDictionary<string, object> overload?	public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)\n{\n    return EnumDropDownListFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n}\n\npublic static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, IDictionary<string, object> htmlAttributes)\n{\n    var items = DoSomething();\n\n    return htmlHelper.DropDownListFor(expression, items, htmlAttributes);\n}	0
16236570	16236428	Set max length of a string c# but end with whole word	string mktText = model.Product.MarketingText;\nif (mktText.Length > 180) {\n  int pos = mktText.LastIndexOf(" ", 180);\n  if (pos < 150) {\n    pos = 180;\n  }\n  mktText = mktText.Substring(0, pos) + "...";\n}	0
943108	942717	Allowing user to edit / add / move items in an image	s by most modern  browsers. Store positions in database. Store png	0
12287587	12287549	How to easily remove part of string from string array in c#	ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(a => a.Replace("name",""));	0
5127250	5127150	How can I get a substring from a file path in C#?	string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";\n\nstring folder = path.Substring(0,path.LastIndexOf(("\\")));\n                // this should be "c:\inetpub\wwwrroot\images\pdf"\n\nvar fileName = path.Substring(path.LastIndexOf(("\\"))+1);\n                // this should be admin.pdf	0
15618532	15584214	How to reuse Auth Tokens for Social Api's on app restart	AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, pinCode);	0
12434159	12433829	How do i download all images from a List<string> with many links for images inside?	string URL="http://www.yourdomain.com/file1.zip";\nstring DestinationPath="C:\file1.jpg";\nSystem.Net.WebClient Client = new WebClient();\nClient.DownloadFile(URL,DestinationPath);	0
32395205	32386700	datetime not parsed from json-date to js date object automatically	//service:\nRestangular.all('').customGET('PeekCustomer').then(function (result){\n    data.customers = angular.copy(result);\n    data.customers = data.customers.data;\n\n    for(var i = 0; i <= data.customers.length - 1; i++) {\n        data.customers[i].Created = new Date(parseInt(data.customers[i].Created.substr(6)));\n    }\n})\n\n//markup:\n{{customer.Created | date:"yyyy-MM-dd HH:mm"}}	0
29521237	29520900	Assign 'flight' to a logged-in/ registered user?	availableSeats = Flight.NumberOfSeats - bookings.Where(b => b.FlightId == Flight.FlightId).Select(b => b.NumberOfSeats).Sum();	0
7330710	7330637	How to create *.docx files from a template in C#	System.IO.Packaging	0
33126378	33126065	C# Object Method Parameters representing 2 radio buttons	public void CalcDecorCost(bool radio1, bool radio2)\n{\n    if(radio1)\n        do something;\n    else if(radio2)\n        do something;\n    else\n        do something;\n}	0
17603659	17551556	Get sender email address from attachment	var results = _ewsService.FindItems(WellKnownFolderName.Inbox, new ItemView(100)); //fetch 100 random emails from inbox\n\nforeach (var entry in results.Items)\n{\n    if (entry is EmailMessage)\n    {\n        var temp = EmailMessage.Bind(_service, entry.Id);\n\n        if (entry.HasAttachments)\n        {\n            temp.Load(new PropertySet(EmailMessageSchema.Attachments));\n\n            foreach (var singleItem in temp.Attachments)\n            {\n                if (singleItem is ItemAttachment)\n                {\n                    var attachedMail = singleItem as ItemAttachment;\n\n                    attachedMail.Load();\n\n                    Console.WriteLine(attachedMail.Item is EmailMessage);\n\n                    var workingMessage = attachedMail.Item as EmailMessage; //this should give you from, subject, body etc etc.\n                }\n            }\n        }\n    }\n}	0
4398088	4398051	Get Control from FooterTemplate of Repeater	siteMapAsBulletedList.ItemDataBound += new RepeaterItemEventHandler(siteMapAsBulletedList_ItemDataBound);\n\n...\n\nvoid siteMapAsBulletedList_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.Footer)\n    {\n        DropDownList ddlChangeUser = (DropDownList)e.Item.FindControl("ddlChangeUser");\n        if (ddlChangeUser != null) {\n                   ...\n        }\n    }\n}	0
9824681	9823304	Is it possible to hide a callback mechanism in a single method?	private AuthenticationResult Authenticate(string user, string pwhash)\n{            \n    IAuthentication auth = GetIAuthenticator();\n    AuthenticationResult result = null;\n    AutoResetEvent waitHangle = new AutoResetEvent(false);\n\n    auth.AuthenticationDone += (o, e) =>\n        {\n            result = e;\n            waitHangle.Set();\n        };\n\n    auth.AuthenticateAsync(user, pwhash);\n    waitHangle.WaitOne(); // or waitHangle.WaitOne(interval);\n    return result;\n}	0
1811755	1811744	how to set the http headers when sending http request to a server so that the server thinks the requests are coming from firefox	using (WebClient myBrowser= new WebClient())\n{\n    myBrowser.Headers["User-Agent"] = some_string_like_the_one_above;\n\n    // Download data.\n    byte[] httpResp = myBrowser.DownloadData(some_url);\n\n    // Here to exploit the data returned from the server\n}	0
20154258	20154110	Connect to SQL Server Stored procedure with ADO.NET	int result; \n\nusing (SqlConnection conn = new SqlConnection("hereYourConnectionString"))\n{\n    conn.Open();\n    using (SqlCommand cmd = new SqlCommand("StoredProcedureName", conn))\n    {\n        cmd.CommandType = CommandType.StoredProcedure;\n\n        // input parameters \n        cmd.Parameters.Add(new SqlParameter("@paramName", paramValue));\n\n        // output parameters\n        SqlParameter retval = cmd.Parameters.Add("@returnValue", SqlDbType.Int); // assiming that the return type is an int\n        retval.Direction = ParameterDirection.ReturnValue;\n\n       cmd.ExecuteNonQuery();\n       result = (int)cmd.Parameters["@returnValue"].Value; // assuming is an int\n    }               \n}	0
18977915	18977863	How to filter a list based on another list using Linq?	var filtered = listOfAllVenuses\n                   .Where(x=>!listOfBlockedVenues.Any(y=>y.VenueId == x.Id));	0
20553470	20553207	Access Windows Azure Storage using class library	Install-Package WindowsAzure.Storage -Version 2.1.0.4	0
14325042	14324956	Setting a relative file reference for XmlReader	Server.MapPath("/data/xml/foo/bar.xml")	0
1129624	1129604	Display data on a text box	textBox1.Text = dt.Rows[0].ItemArray[0].ToString();	0
25885029	25878668	Is there a way to find out what the implicit wait time is set to in selenium?	class PageBase { \n    private WebDriver driver;\n    private long implicitlyWaitTimeInSeconds;\n    public PageBase(WebDriver driver, long timeout) {       \n        driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);\n        implicitlyWaitTimeInSeconds = timeout;\n        this.driver = driver;\n    }\n    public void setImplicitlyWaitTime(long timeout) {\n        driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);\n    }\n    public long getImplicitlyWaitTime() {\n        return implicitlyWaitTimeInSeconds;\n    }\n    ...\n}\n\nclass HomePage extends PageBase {\n    ...\n}	0
10540084	10539902	How do I check/grant logon as service rights in a 64bit environment	try{\n   DoThePInvokeMagic();\n}\ncatch(Exception){\n    // Sometimes the first invocation fails, but the second time it seems to work       \n    DoThePInvokeMagic();\n}	0
25510459	25510430	How to select items from IEnumerable?	var s = ordersInfo.Select(x => x.Customer.Email == user.Email \n  && x.Status == OrderStatus.Paid).ToList();	0
9375647	9375585	Find and remove items from array in c#	string[] arr = {" ", "a", "b", " ", "c", " ", "d", " ", "e", "f", " ", " "};\n  arr = arr.Where(s => s != " ").ToArray();	0
17572507	1272153	Xml Serialization inside a collection	[XmlType("car")]\npublic class Car\n{\n\n}	0
5844112	5833808	How do you instantiate an IDispatchEx in C#?	Type t = System.Type.GetTypeFromProgID("Scripting.FileSystemObject");\n        var obj = Activator.CreateInstance(t);\n        var iobj = (stdole.IDispatch)obj;	0
326774	326757	How to update C# hashtable in a loop?	System.Collections.Hashtable ht = new System.Collections.Hashtable();\n\n        ht.Add("test1", "test2");\n        ht.Add("test3", "test4");\n\n        List<string> keys = new List<string>();\n        foreach (System.Collections.DictionaryEntry de in ht)\n            keys.Add(de.Key.ToString());\n\n        foreach(string key in keys)\n        {\n            ht[key] = DateTime.Now;\n            Console.WriteLine(ht[key]);\n        }	0
6533691	6533583	Radio Button Value from Database C#	var de = new List<string>();\n        de.Add("1");\n        de.Add("2");\n        de.Add("3");\n\n        RadioButtonList1.DataSource = de;\n        RadioButtonList1.DataBind();	0
34191853	34191813	For loop running slow	distributionLists.AddRange(oGal.AddressEntries\n  .Cast<Outlook.AddressEntry>()\n  .Select(\n    x => new DistributionListDetails \n    { \n        DistributionListId = val, \n        DiestributionListEmail = x.Name\n    }));	0
2927345	2926244	How do I detect a change of tab page in TabControl prior to SelectedIndexChanged event?	tabControl1.Selecting += new TabControlCancelEventHandler(tabControl1_Selecting);\n\n   void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)\n    {\n        TabPage current = (sender as TabControl).SelectedTab;\n        //validate the current page, to cancel the select use:\n        e.Cancel = true;\n    }	0
888528	888198	Limiting access to inherited properties C#	public partial class CustomListView : ListView\n{\n    public CustomListView()\n    {\n        InitializeComponent();\n    }\n\n    public System.Windows.Forms.ListView.ListViewItemCollection CustomExposedItems\n    {\n        get\n        {\n            return base.Items;\n        }\n\n    }\n\n    [EditorBrowsable(EditorBrowsableState.Never)]    \n    [Browsable(false)]    \n    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n    [Obsolete("Use the new custom way of adding items xyz")]\n    public new System.Windows.Forms.ListView.ListViewItemCollection Items    \n    { \n        get { throw new NotSupportedException(); }    \n    }\n\n}	0
28327192	28327046	How to edit a property that is deep within an object	var positions = PersonData\n                .SelectMany(p => p.Staffs)\n                .SelectMany(s => s.Employees)\n                .SelectMany(e => e.EmployeePositions);\nforeach (var position in positions)\n{\n   position.PP = "test";\n}	0
11970260	11903313	Sending/Setting a value to a Password Field on a Website	WebBrowser.Document.GetElementById("field-loginFormPassword").SetAttribute("maxLength", "20")\nWebBrowser.Document.GetElementById("field-loginFormPassword").SetAttribute("value", "yourpassword")	0
8657453	8656737	TemplateBinding to DependencyProperty on a custom control is not working	{Binding MyProperty, RelativeSource={RelativeSource TemplatedParent}}	0
13039622	7009072	Multiple AJAX asyncfileupload created from c# code behind	protected void AsyncFileUploadComplete(object oSender, AsyncFileUploadEventArgs e)\n{\n    try\n    {   \n        AsyncFileUpload oFileUploadControl = GetFileUploadInstance(ContainerId, (AsyncFileUpload)oSender);\n    }\n    catch (exception ex)\n    {\n    }\n}\n\nprivate AsyncFileUpload GetFileUploadInstance(Control oContainer, AsyncFileUpload oSender)\n{\n\n    // Place all of your popup controls in a global container, look for the sender as a child control\n    foreach (Control oControl in oContainer.Controls)\n        if (oControl.Controls.Count != 0 && oControl.FindControl("m_afuFileUpload") == oSender)\n            return (AsyncFileUpload)oControl;\n\n    return new AsyncFileUpload(); // || throw new Exception("Could not find ASyncFileUpload Instance");\n}	0
5866654	5646419	How to serialize class type but not the namespace to a Json string using DataContractJsonSerializer	[DataContract(Namespace = "")]	0
29750751	29750453	Removing illegal characters from XML String c#	public static string stripNonValidXMLCharacters(string textIn)\n{\n    if (String.IsNullOrEmpty(textIn))\n        return textIn;\n\n    StringBuilder textOut = new StringBuilder(textIn.Length);\n\n    foreach (Char current in textIn) \n        if ((current == 0x9 || current == 0xA || current == 0xB || current == 0xD) ||\n           ((current >= 0x20) && (current <= 0xD7FF)) ||\n           ((current >= 0xE000) && (current <= 0xFFFD)) ||\n           ((current >= 0x10000) && (current <= 0x10FFFF))) \n          textOut.Append(current);\n\n    return textOut.ToString();\n}	0
25848932	25847806	entity framework SaveChanges conflicting changes to the role of the relationship have been detected	public void SomeMethod(int orderId)\n{\n   using (var db = new MyDbContext())\n   {\n      var order = db.Orders.FirstOrDefault(x=>x.Id==orderId);\n      if (order!=null) //order.TaxisId = 1\n      {        \n        if (SettingsModel.AutoSetToTheNextTaxi)\n        {\n          order.TaxisId = 2;\n        }\n        else\n        {\n          order.TaxisId = null;\n        }\n        db.SaveChanges(); \n      }\n   }\n}	0
15941621	15941564	How to pass a server side property value to other htm page loaded in frame withing aspx page	window.parent.SomeFunctionDefinedInDefaultAspx(valueToSet);	0
5077335	5077308	How to produce XML with attributes rather than nodes, using MvcContrib's XmlResult?	public class TopTenShareClass\n{\n    [XmlAttribute]\n    public int Id { get; set; }\n\n    [XmlAttribute]\n    public string Name { get; set; }\n}	0
3947870	3947844	Search in LinkedList<T>	public override bool Equals(object obj)\n    {\n        return this.CompareTo(((IComparable)obj)) == 0;\n    }	0
24997018	24996536	regex for extracting a number	List<string> words = new List<string> { "PlusContent", "PlusArchieve", "PlusContent1", "PlusArchieve1" };\nforeach (string tester in words)\n{\n    Regex r1 = new Regex(@"\bPlus\D*(\d*)\b", RegexOptions.IgnoreCase);\n    foreach (Match m in r1.Matches(tester)) Console.WriteLine(m.Groups[1]);\n}	0
29763684	29762680	Compare two Clipboard IDataObject in C#	if (Clipboard.ContainsData(System.Windows.Forms.DataFormats.Text))\n        {\n            //do something\n        }	0
13211673	13211554	parsing json response is null	var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";\nusing (WebClient wc = new WebClient())\n{\n    string json = wc.DownloadString(url);\n\n    dynamic dynobj = JsonConvert.DeserializeObject(json);\n\n    foreach (var engine in dynobj.serviceResponse.engines.engine)\n    {\n        Console.WriteLine("{0} {1}", engine.FMEInstanceName, engine.transactionPort);\n    }\n}	0
31346967	31338389	Save Several Images to a Jagged Array	Image<Gray, UINT16>[] rawCaptures = new Image<Gray, UINT16>[10];\n// some other code...\nwhile(cameraIsRunning && iWantMoreImages)\n{\n    // more code here...\n    Image<Gray, UInt16> IMA = new Image<Gray, UInt16>(m_bitmap);\n    rawCaptures[indexOfCapture] = IMA;\n}	0
22368809	22368434	Best way to split string into lines with maximum length, without breaking words	IEnumerable<string> SplitToLines(string stringToSplit, int maximumLineLength)\n{\n    var words = stringToSplit.Split(' ').Concat(new [] { "" });\n    return\n        words\n            .Skip(1)\n            .Aggregate(\n                words.Take(1).ToList(),\n                (a, w) =>\n                {\n                    var last = a.Last();\n                    while (last.Length > maximumLineLength)\n                    {\n                        a[a.Count() - 1] = last.Substring(0, maximumLineLength);\n                        last = last.Substring(maximumLineLength);\n                        a.Add(last);\n                    }\n                    var test = last + " " + w;\n                    if (test.Length > maximumLineLength)\n                    {\n                        a.Add(w);\n                    }\n                    else\n                    {\n                        a[a.Count() - 1] = test;\n                    }\n                    return a;\n                });\n}	0
9971237	9971165	Select bottom N from Generic List	var count = myList.Count;\n\nmyList.Skip(count-n)	0
8118637	8118607	Filtering DataTable with LINQ	var query =\n    from result in Results.AsEnumerable()\n    join company in Companies.AsEnumerable()\n    on result .Field<int>("....") equals\n        company .Field<int>("....")\nselect new { .... }	0
7133017	7132880	How to Use 'IN' on a DataTable	table.Select(string.Format("CITY in '{0}'",string.Join("','",table.Rows.OfType<DataRow>().Select(r=>r["COUNTRY"].ToString()).Distinct())))	0
31541383	31531831	C# app to pass data to windows service	ServiceController sc = new ServiceController("ServiceName", Environment.MachineName);\nstring[] args = new string[2];\nargs[0] = txtBox1.Text;\nargs[1] = txtBox2.Text;\n\nsc.Start(args);	0
2855458	2853313	Moq how to correctly mock set only properties	public class Xyz\n{\n    public virtual string AA { set{} }\n}\npublic class VerifySyntax\n{\n    [Fact]\n    public void ThisIsHow()\n    {\n        var xyz = new Mock<Xyz>();\n        xyz.Object.AA = "bb";\n        // Throws:\n        xyz.VerifySet( s => s.AA = It.IsAny<string>(), Times.Never() );\n    }\n}\npublic class SetupSyntax\n{\n    [Fact]\n    public void ThisIsHow()\n    {\n        var xyz = new Mock<Xyz>();\n        xyz.SetupSet( s => s.AA = It.IsAny<string>() ).Throws( new InvalidOperationException(  ) );\n        Assert.Throws<InvalidOperationException>( () => xyz.Object.AA = "bb" );\n    }\n}	0
25863570	25606994	EF ef Database.SqlQuery internal rollback into executed stored procedure	using (INotificationDataContext context = DataContextFactory.Create<INotificationDataContext>())\n        {\n            result = (context as IObjectContextAdapter).ObjectContext.ExecuteStoreCommand(TransactionalBehavior.DoNotEnsureTransaction, sql, parameters);\n        }	0
16722979	16722873	Linq equivalent of for in foreach	var flattened = tuples.SelectMany(t => Enumerable.Repeat(t.Name, t.Count));\n\nforeach(var word in flattened)\n{\n    Console.WriteLine(word);\n}	0
3796102	3796069	Is there a way to see a selected part of a web page's source using c#	elm[2].innerhtml	0
27114448	27114179	Parsing syntactic string in C#	String.Format(@"HRESULT __stdcall WrapIDirect3DCubeTexture9::{0}({1}) \n{{\n\n}}", "methodName", "arguments");	0
17284532	17284350	Get a rotated texture width and height	newWidth = textureHeight * Math.Sin(angle) + textureWidth * Math.Cos(angle);\nnewHeight = textureHeight * Math.Cos(angle) + textureWidth * Math.Sin(angle);	0
11645619	11645546	Pause update of progress bar	progressBar.Maximum = 100;\n\nvar stepPercentage = 50 / step1Objects.Count;\nforeach(SomeObject step1Object in step1Objects)\n{\n    progressBar.Progress += stepPercentage;\n}\n\nprogressBar.Progress = 50;\nstepPercentage = 50 / step2Objects.Count;\nforeach(SomeObject step2Object in step2Objects)\n{\n    progressBar.Progress += (stepPercentage + 50);\n}	0
12769747	12765470	Unable to get DisplayMemberPath to show bound object data in listbox	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        MegaWidget MWidget = (MegaWidget)value;\n        Location loc = MWidget.Locations[(string)parameter];\n        List<ListBoxItem> displayContent = new List<ListBoxItem>();\n        foreach (Part item in loc.Contents)\n        {\n            ListBoxItem lbi = new ListBoxItem();\n            lbi.Content = item.Name;\n            displayContent.Add(lbi);\n        }\n        return displayContent;\n    }	0
800176	695678	Performing part of a IQueryable query and deferring the rest to Linq for Objects	using System;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nnamespace LinqToTerraServerProvider\n{\n    internal class ExpressionTreeModifier : ExpressionVisitor\n    {\n        private IQueryable<Place> queryablePlaces;\n\n        internal ExpressionTreeModifier(IQueryable<Place> places)\n        {\n            this.queryablePlaces = places;\n        }\n\n        internal Expression CopyAndModify(Expression expression)\n        {\n            return this.Visit(expression);\n        }\n\n        protected override Expression VisitConstant(ConstantExpression c)\n        {\n            // Replace the constant QueryableTerraServerData arg with the queryable Place collection.\n            if (c.Type == typeof(QueryableTerraServerData<Place>))\n                return Expression.Constant(this.queryablePlaces);\n            else\n                return c;\n        }\n    }\n}	0
16142821	16142626	WPF Cancel Button	void Window_Closing(object sender, CancelEventArgs e)\n{\n     MessageBoxResult result = MessageBox.Show(\n            "msg", \n            "title", \n            MessageBoxButton.YesNo, \n            MessageBoxImage.Warning);\n        if (result == MessageBoxResult.No)\n        {\n            // If user doesn't want to close, cancel closure\n            e.Cancel = true;\n        }        \n}	0
8532213	8532196	How to deserialise using JSON.NET C#?	Product product = new Product();\n\nproduct.Name = "Apple";\nproduct.Expiry = new DateTime(2008, 12, 28);\nproduct.Price = 3.99M;\nproduct.Sizes = new string[] { "Small", "Medium", "Large" };\n\nstring output = JsonConvert.SerializeObject(product);\n//{\n//  "Name": "Apple",\n//  "Expiry": "\/Date(1230375600000+1300)\/",\n//  "Price": 3.99,\n//  "Sizes": [\n//    "Small",\n//    "Medium",\n//    "Large"\n//  ]\n//}\n\nProduct deserializedProduct = JsonConvert.DeserializeObject<Product>(output);	0
9004821	9003770	How to get the key of a deserialized json with JSON.Net	((JProperty)token).Name.ToString()	0
2761988	2759108	Populate a combo box with one data tabel and save the choice in another	bsServers.DataMember = "Servers";\nbsServers.DataSource = new[]\n    {\n       new Servers {Server = "1", Ip = "1.1.1.1"},\n       new Servers {Server = "2", Ip = "2.2.2.2"},\n       new Servers {Server = "3", Ip = "3.3.3.3"},\n       new Servers {Server = "4", Ip = "4.4.4.4"}\n    };\nbsUsers.DataSource = new[]\n     {\n         new Users {Server = "1", Username = "aaa", Password="kjkhkhk"},\n         new Users {Server = "1", Username = "bbb", Password="3534564"},\n         new Users {Server = "3", Username = "ccc", Password="egrhtyj"},\n         new Users {Server = "2", Username = "ddd", Password="6576878"}\n     };\nserverComboBox.DataBindings.Add("SelectedValue", bsUsers, "Server", true);\nserverComboBox.DataSource = bsServers;\nserverComboBox.DisplayMember = "Server";	0
991408	991383	Call a C++ function from C#	[DllImport("yourdllName.dll")]\npublic static extern void init(IntPtr initData, IntPtr key);\n\n[DllImport("yourdllName.dll")]\npublic static extern IntPtr encrpyt(IntPtr inout, unsigned inuputSize, IntPtr key, unsigned secretKeySize);	0
23261475	23261343	Grouping strings based on two keys	void Main()\n{\n    var list = new string[] {"1#2","1#2","2#1"};\n    var result = list.GroupBy(x => x.Split('#').OrderBy(y => y).Aggregate((a,b)=>a + "#" + b));\n\n    //should output only one key - 1#2\n    foreach(var key in result)\n    {\n         Console.WriteLine(key);\n    }\n}	0
14787703	14787566	Select and display Image files from ListBox, to be display within PictureBox? C#	private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)\n{\n  pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);\n}	0
3907722	3907679	How can I update the current line in a C# Windows Console App while waiting for ReadLine?	namespace ConsoleApplication1\n{\n    using System;\n    using System.Threading;\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine("Starting");\n\n            ThreadPool.QueueUserWorkItem(\n                cb =>\n                    {\n                        int i = 1;\n                        while (true)\n                        {\n                            Console.WriteLine("Background {0}", i++);\n                            Thread.Sleep(1000);\n                        }\n                    });\n            Console.WriteLine("Blocking");\n            Console.WriteLine("Press Enter to exit...");\n            Console.ReadLine();\n        }\n    }\n}	0
20059206	20059083	How can I generate random dates within a range?	void Main()\n{   \n    Console.WriteLine(DateTime.UtcNow.AddDays(new Random().Next(90)));\n}	0
20494843	20494740	CollapseAll items of a treeview within Wpf application	private void cmdCollapse_Click(object sender, RoutedEventArgs e)\n{\n    foreach (TreeViewItem item in treeview.Items)\n        CollpaseTreeviewItems(item);\n}\n\nvoid CollapseTreeviewItems(TreeViewItem Item)\n{\n    Item.IsExpanded = false;\n\n    foreach (TreeViewItem item in Item.Items)\n    {\n        item.IsExpanded = false;\n\n        if (item.HasItems)\n            CollapseTreeviewItems(item);\n    }\n}	0
9541899	9540898	Cast Object Type value into a Type and get Values out of it by Reflection	obj.GetType().GetProperties()\n   .Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) })	0
10203292	10203105	Convert int to  little-endian formated bytes in C++ for blobId in Azure	QByteArray temp;\nint blockId = 5000;\n\nfor(int i = 0; i != sizeof(blockId); i++) {\n  temp.append((char)(blockId >> (i * 8)));\n}\n\nqDebug() << temp.toBase64(); // "iBMAAA==" which is correct	0
13088560	13088511	Detecting Ctrl + click button and click button	Form Form1;\nbutton.Click += click;\n\nprivate void click(object s, EventArgs e)\n{\n    if(Form1.ModifierKeys == Keys.Control)\n    ... // Whatever you need here\n}	0
8471961	8471422	Minimize the performance cost of reading a XML	var elements = xml.Elements("Control").Where(\n    e => e.Attribute("ToValidate") != null \n    && e.Attribute("ToValidate").Value == "1"\n);	0
19150514	19150309	How to search for a number in a list of arrays of numbers based on the first index of each array using LINQ?	int found = list.Zip(list.Skip(1), (x, y) => x[0]<=searchFor&&y[0]>=searchFor?y[1]:0).FirstOrDefault(o=>o!=0);	0
6836546	6836247	How to create a minimal dummy X509Certificate2?	byte[] embeddedCert;\nAssembly thisAssembly = Assembly.GetAssembly(typeof(MyType));\nusing (Stream certStream = thisAssembly.GetManifestResourceStream("YourProjectName.localhost.pfx"))\n{\n  embeddedCert = new byte[certStream.Length];\n  certStream.Read(embeddedCert, 0, (int)certStream.Length);\n}\n\n_signingCert = new X509Certificate2(embeddedCert, "password");	0
28933673	28932203	Take N values from observable on each interval	// flatten stream\nvar fs = input.SelectMany(x => x);\n\n// buffer 8 values and release every 33 milliseconds\nvar xs = Observable.Interval(TimeSpan.FromMilliseconds(33))\n                   .Zip(fs.Buffer(8), (_,buffer) => buffer);	0
10868575	10868517	Split string and get first value only	string valueStr = "title, genre, director, actor";\nvar vals = valueStr.Split(',')[0];	0
34266735	34264653	System.Byte[] displaying in Datagrid column	string query = @"SELECT c.*,cc.CountryName ,(Select UserName FROM users WHERE User_ID = c.CreatedByUser) AS CreatedBy,\n                      (select GROUP_CONCAT(AreaDescription) from pxpcountycodes where countyid=c.id) as AreaDescription, \n                      CAST(GROUP_CONCAT(cmr.AccountCode) As CHAR) as Member  " +\n                    " FROM counties c " +\n                    " LEFT JOIN Countries cc ON c.CountryID = cc.ID " +\n                    " LEFT JOIN PXPCountyCodes PXPc on c.ID = PXPc.CountyID" +\n                    " LEFT JOIN customer cmr ON PXPc.MemberID = cmr.ID  " +\n                    " WHERE c.Company_ID = ?companyID ";	0
9765117	9765068	Downloading file using webclient with a save dialogue box	Content-Disposition: Attachment;	0
32219524	32218248	How to Group Datatable rows with 6 columns with c#.net	//Group by distinct 4 column\n      var GroupBy4ColumnDistinct =  dt.Rows.Cast<DataRow>()\n        .ToLookup(x => (Convert.ToString(x["Length"]) + Convert.ToString(x["Radius"]) + Convert.ToString(x["Delta"]) + Convert.ToString(x["Tangent"])).GetHashCode())\n        .Select(x => new { key = x.Key, values = x.Select(y => Convert.ToString(y["CurveNumber"])).ToList() }).ToList();\n\n        // add new table to dataset. dataset contain 3 table as shown in our sample output\n      DataSet ds = new DataSet();\n      foreach (var item in GroupBy4ColumnDistinct)\n      {\n          DataView dv = new DataView(dt);\n          dv.RowFilter = " CurveNumber in ( " + string.Join(",", item.values) + " )";\n          ds.Tables.Add(dv.ToTable());\n      }</pre>	0
25531899	25531837	Converting a Predicate<T> to a Func<T, bool>	public bool DoAllHaveSomeProperty()\n{\n    return m_instrumentList.All(i => m_filterExpression(i));\n}	0
27886773	27885580	Windows Phone Universal RichEditBox Italic Formatting	FontFamily="Segoe UI"	0
9771513	9741050	Changing fields from a different database table in controller	public ActionResult Edit(int id)\n{\n    User user = db.Users.Single(u => u.UserID == id);\n    UserViewModel model = new UserViewModel()\n    {\n        UserID = user.UserID,\n        //etc.\n    }\n\n    ViewBag.UserGUID = new SelectList(db.Memberships, "UserId", "Password", user.UserGUID);\n    ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "CompanyName", user.CompanyID);\n\n    return View(model);\n} \n\npublic ActionResult Edit(UserViewModel userModel)\n{\n    if (ModelState.IsValid)\n    {\n        // Update user properties\n        User user = db.Users.Single(u => u.UserID == userModel.UserID);\n        // etc.\n\n        // If you need to update the membership value, do that next\n\n        db.SaveChanges();\n    }\n\n    ViewBag.UserGUID = new SelectList(db.Memberships, "UserId", "Password", user.UserGUID);\n    ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "CompanyName", user.CompanyID);\n\n    return View(user);\n}	0
8541123	7911228	using webrequest to issue a rename command that moves FTP folders	data/previous/1/	0
26520146	26519893	How do I remove url from text	string text = "EA SPORTS UFC  (Microsoft Xbox One, 2014) $40.00 via eBay http://t.co/Wpwj0R1EQm Tibet snake.... http://t.co/yPZXvNnugL";\n\nstring cleanedText = Regex.Replace(text, @"http[^\s]+", "");\n\n//cleanedText is now "EA SPORTS UFC  (Microsoft Xbox One, 2014) $40.00 via eBay  Tibet snake.... "	0
28422653	28422353	How to find successive numbers in a List<int> with duplicates?	var count = dList.Count; //6\nvar straights = dList.Select(dice => dice.Value)\n    .Distinct() //5,3,1,6,4\n    .OrderBy(dice => dice.Value) //1,3,4,5,6\n    .Select(dice => dice.Value + (count--)) //7,8,8,8,8\n    .GroupBy(n => n) //[7,{7}],[8,{8,8,8,8}]\n    .OrderByDecending(group => group.Count());\n\nvar longestStraight = straights.First().Count(); //4	0
10504992	10504887	Application Close on DialogResult	private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n    {\n        DialogResult dialog = dialog = MessageBox.Show("Do you really want to close the program?", "SomeTitle", MessageBoxButtons.YesNo);\n        if (dialog == DialogResult.No)\n        {\n            e.Cancel = true;\n        }\n    }	0
29627075	29564217	How to programatically summarize existing documents in Sharepoint	ClientContext context = new ClientContext("<websiteurl>");\nWeb web = context.Web;\ncontext.Load(web);\ncontext.ExecuteQuery();\nvar q = from list in web.Lists\n                where <put condition here>\n                select list;\nvar r = context.LoadQuery(q);\ncontext.ExecuteQuery();\n\nforeach (var list in r)\n{\n   context.Load(list.RootFolder);\n   context.ExecuteQuery();\n   ...\n   //To get folders\n   GetFolders(context, list.Root.Folders);\n   //To get files\n   GetFiles(context, list.RootFolder.Files);\n }	0
3482507	3482261	How to convert c# generic list to json using json.net?	using System;\nusing System.Data;\nusing Newtonsoft.Json.Linq;\n\nclass Test\n{\n    static void Main()\n    {\n        DataTable table = new DataTable();\n        table.Columns.Add("userid");\n        table.Columns.Add("phone");\n        table.Columns.Add("email");\n\n        table.Rows.Add(new[] { "1", "9999999", "test@test.com" });\n        table.Rows.Add(new[] { "2", "1234567", "foo@test.com" });\n        table.Rows.Add(new[] { "3", "7654321", "bar@test.com" });\n\n        var query = from row in table.AsEnumerable()\n                    select new {\n                        userid = (string) row["userid"],\n                        phone = (string) row["phone"],\n                        email = (string) row["email"]            \n                    };\n\n        JObject o = JObject.FromObject(new\n        {\n            Table = query\n        });\n\n        Console.WriteLine(o);\n    }\n}	0
12373959	12200857	MSBuild appending MSDEPLOYAGENTSERVICE to the end of my URL	/p:DeployOnBuild=True \n/p:DeployTarget=MSDeployPublish \n/p:MsDeployServiceUrl=[ip address]/MsDeploy.axd \n/p:MSDeployPublishMethod=WMSVC \n/p:CreatePackageOnPublish=True \n/p:DeployIisAppPath=[name of website in iis]\n/p:AllowUntrustedCertificate=True	0
15951875	15951621	Download a file and read from it in the same time	var req = (HttpWebRequest)HttpWebRequest.Create(url);\nusing (var resp = req.GetResponse())\n{\n    using (var stream = resp.GetResponseStream())\n    {\n        byte[] buffer = new byte[0x10000];\n        int len;\n        while ((len = stream.Read(buffer, 0, buffer.Length))>0)\n        {\n            //Do with the content whatever you want\n            // ***YOUR CODE*** \n            fileStream.Write(buffer, 0, len);\n        }\n    }\n}	0
31489855	31477610	Entity Framework - concurrent use of containers	builder\n    .RegisterType<MyDbContext>()\n    .InstancePerHttpRequest();	0
14408858	14408738	Relationships between custom tables and membership	public class Employee\n        {\n            [Key]\n            public int EmployeeId { get; set; }\n\n            public string FirstName { get; set; }\n\n            public string LastName { get; set; }\n\n            // the rest..\n\n            [ForeignKey("Office")]\n            public int OfficeId { get; set; }\n\n            [ForeignKey("EmployeeType")]\n            public int EmployeeTypeId { get; set; }\n\n            public virtual aspnet_Users User { get; set; }\n\n            public virtual Office Office { get; set; }\n        }\n\n\npublic class EmployeeType\n{ \n  [Key]\n  public int EmployeeTypeId {get; set;}\n  public string EmployeeTypeDescription {get; set;} // Doctor or whatever\n}	0
13016151	13016054	Querying a XML FIle and creating a text file	File.WriteAllLines("TableDoc.txt", XDocument.Load("TableList.xml")\n         .Descendants("Table")\n         .Select(t => string.Format("The table - {0} - has columns {1}.",\n                                    t.Element("TableName").Value,\n                                    t.Element("Columns").Value)));	0
30940975	30940478	Serialize list objects to JSON using C#	public List<Student> GetStudentData()\n{\n    List<Student> dataStudent;\n    using (IDbConnection connection = RepositoryHelper.OpenConnection())\n    {\n        dataStudent = connection.Query<dynamic>(\n            "mystoredprocedure", \n            commandType: CommandType.StoredProcedure)\n                .GroupBy(x => x.StudentId)\n                .Select(x => new Student \n                    { \n                        StudentId = x.First().StudentId, \n                        Gender = x.First().Gender,\n                        emailAddresses = x.Select(ea => new EmailAddresses \n                            { \n                                EmailAddress = ea.emailAddresses \n                            }).ToList()\n                    }).ToList();\n\n        return dataStudent;\n    }\n}	0
14375137	14375028	How to make an application run in both win xp and win 7-x86?	private void MyMenuItem_Click(object sender, EventArgs e)\n{\n   MyMenuItem.Enabled = false;   \n   String helpFileName = "IDoNotKnow.ext";\n   string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),Path.Combine("MyApp",helpfileName));\n   if (System.IO.File.Exists(fileName))\n   {\n      System.Windows.Forms.Help.ShowHelp(new System.Windows.Forms.Control(),fileName,System.Windows.Forms.HelpNavigator.TableOfContents);\n   }\n}	0
6095735	6095718	Displaying number of elements inside an array list with a messagebox	MessageBox.Show(str.Count.ToString());	0
11159096	11156033	Getting friends status updates and comments using facebook api	{\n  'status': 'SELECT status_id, uid , message FROM status \n         WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())',\n  'comments': 'SELECT post_id, fromid, time, text FROM comment \n         WHERE post_id IN (SELECT status_id from #status)'\n}	0
22584429	22557376	Request additional claims Owin Security	var fb = new FacebookAuthenticationOptions\n{\n    AppId = "...",\n    AppSecret = "...",\n    AuthenticationType = "Facebook",\n    SignInAsAuthenticationType = "ExternalCookie",\n    Provider = new FacebookAuthenticationProvider\n    {\n        OnAuthenticated = async ctx =>\n        {\n            if (ctx.User["birthday"] != null)\n            {\n                ctx.Identity.AddClaim(new Claim(ClaimTypes.DateOfBirth, ctx.User["birthday"].ToString()));\n            }\n        }\n    }\n};\nfb.Scope.Add("user_birthday");\napp.UseFacebookAuthentication(fb);	0
16851702	16848736	Unable to connect MySQL hosts with MySQL-Front	"Server = myServer; Database = myDB; Uid = myUsername; Pwd = myPassword"	0
14225169	14105175	Efficiently run hundreds thousands of functions at a predefined time	public void DoStuff(DateTime now)\n{\n    if (NeedToWork(now))\n    {\n        // do some complex stuff on a 2nd thread.\n        NextTime = now.AddSeconds(rand.Next(60, 3600));\n    }\n}	0
26141904	26141811	DialogResult Filter multiple extensions	dialog.Filter = "Plain text files (*.csv;*.txt)|*.csv;*.txt";	0
15094687	15094384	C# Dictionaries - Custom Objects	class Car : IEquatable<Car>\n    {\n        public Car(int id, string model)\n        {\n            ID = id;\n            Model = model;\n        }\n\n        public int ID { get; private set; }\n        public string Model { get; private set; }\n\n        public bool Equals(Car other)\n        {\n            return !ReferenceEquals(null, other) && ID == other.ID;\n        }\n// This is a must if you like to correctly use your object as a key in dictionary\n        public override int GetHashCode()\n        {\n            return ID.GetHashCode();\n        }\n    }	0
12458861	12458757	Coding practice - using abstract or a private constructor	var workflow = Workflow.Begin(complexObject); \n\npublic class WorkFlow  \n{ \n    private WorkFlow() \n    { \n        //private to prevent initialization but this feels wrong!  \n    } \n\n    public static WorkFlow Begin(ComplexObject co) \n    { \n        return new Workflow(co);\n    } \n}	0
26151194	26150937	Can't parse XML data with C#	string idValue = xDocument.XPathSelectElement("//EnvioDTE/SetDTE")\n     .Attributes().SingleOrDefault(a => a.Name == "ID").Value;	0
24191394	24191234	MySQL select query with parameter	c = new MySqlCommand("select * from catalog_product_entity where column_nam = @Value;", conn);\nc.Parameters.AddWithValue("@Value", your string);\nMySqlDataReader r = c.ExecuteReader();	0
5926559	5790343	How to detect programmatically if the user proxy is blocking access to Facebook	var img = new Image();\nimg.onerror = function () {\n alert("It seems Facebook is blocked!"); \n}\nimg.src = "http://facebook.com/favicon.ico";	0
3983060	3983014	Call a delegate without specifying delegate's parameter	var byMonths = GetTotal(123, yourDate, (d, i) => d.AddMonths(i));\n\nvar byDays = GetTotal(456, anotherDate, (d, i) => d.AddDays(i));\n\n// ...\n\nIEnumerable<TotalType> GetTotal(\n    string id, DateTime lastTotalDate, Func<DateTime, int, DateTime> adder)\n{\n    for (int i = 0; adder(lastTotalDate, i + 1) <= DateTime.Now; i++)\n    {\n        var temp = adder(lastTotalDate, i);\n        var totalStartDate = new DateTime(temp.Year, temp.Month, 1);\n        var totalEndDate = adder(totalStartDate, 1);\n        var total = this.GetTotal(id, totalStartDate, totalEndDate);\n        var interval = new TimeInterval(totalStartDate, totalEndDate);\n\n        yield return new TotalType(id, total, interval);\n    }\n}	0
22932605	22293491	Unmanaged DLL doesn't work in Windows 7	[DllImport("MyTest.dll", CharSet = CharSet.Ansi)]\nprivate static extern IntPtr DoSomething();\npublic static string Do_Something()\n{\n   IntPtr tempPointer = DoSomething();\n   string tempSomething = Marshal.PtrToStringAnsi(tempPointer);\n   return tempSomething ;\n}	0
24105820	24105792	Change button color for a short time	private void button1_Click(object sender, EventArgs e)\n    {\n        button1.BackColor = Color.Lime;\n        //Set time between ticks in miliseconds.\n        timer1.Tick=2000;\n        //Start timer, your program continues execution normaly\n        timer1.Start;\n        //If you use sleep(2000) your program stop working for two seconds.\n\n    }\n        //this event will rise every time set in Tick (from start to stop)\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n          //When execution reach here, it meas 2 secons have past. Stop Timer and change color\n          timer1.Stop;\n          button1.BackColor = SystemColors.Control;\n        }	0
21687598	21687545	How to pass in a list of generic objects into a method?	public class ValidationManager<T>\n{\n     // Change methods to accept T instead of object\n     public static void CheckModelListValidation(List<T> model)\n     {\n\n     //...\n\n     public static void CheckModelValidation(T model)\n     {\n      // etc	0
15982041	15981840	How to draw and move shapes using mouse in C#	protected override void OnMouseMove(MouseEventArgs e)\n    {\n\n\n        if (e.Button == MouseButtons.Left)\n        {\n            rec.Width = e.X - rec.X;\n            rec.Height = e.Y - rec.Y;\n            this.Invalidate();\n        }\n\n        if (e.Button == MouseButtons.Right)\n        {\n            rec.Location = new Point((e.X-MouseDownLocation.X) + rec.Left, (e.Y-MouseDownLocation.Y) + rec.Top);\n            MouseDownLocation = e.Location;\n            this.Invalidate();\n        }\n    }	0
12867904	12802966	How to add style information to single line xml file	xmlDoc.Save(fileName);	0
8088701	8078380	What's the best way to invoke Observable method at a specific time?	Scheduler.ThreadPool\n    .Schedule(\n        DateTimeOffset.Now.AddHours(1.0),\n        () => { /* Do web request */ });	0
24537241	24536953	WinRT - caching StorageFolder picked by user	// Process picked folder\nif (folder != null)\n{\n    // Store folder for future access\n    folderToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder);\n}\nelse\n{\n    // The user didn't pick a folder\n}	0
24549985	24548069	Inserting data in database using c#	try{ \n    SqlCommand cmd = new SqlCommand(query,conn);\n    cmd.Parameters.Add("@admission_no" , SqlDbType.Varchar,20).Value=txtAddmissionNo.Text;\n    cmd.Parameters.Add("@student_name" , SqlDbType.Varchar,50).Value=txtStudentName.Text;\n    cmd.Parameters.Add("@father_name" , SqlDbType.Varchar,50).Value=txtSDof.Text;\n    cmd.Parameters.Add("@receipt_no" , SqlDbType.Varchar,20).Value=txtReceiptNo.Text;\n\n    .... add other parameters and its value\n\n    cmd.ExecuteNonQuery();\n}\ncatch(Exception ex)\n{\n    MessageBox.Show(ex.ToString());\n}	0
23983054	23983029	How to build an anonymous object with expression trees	Tuple<T1, T2>	0
745994	745970	How do I bind to a List<T> using DataContext?	public class AClass\n{\n    private List<int> _ints = new List<int>();\n\n    public string Name { get; set; }\n    public List<int> MyIntegers\n    {\n        get { return _ints; }\n    }\n}	0
22964107	22964059	How to copy a Object<T> to an array	string[] fruitTitles = fruits.Select(fruit => fruit.FruitTitle)\n                             .ToArray();	0
26830859	26830835	How to parse and round a string value to the nearest whole number?	Convert.ToInt32	0
2449489	2449449	How to update an element with a List using LINQ and C#	(from trade in CrudeBalancedList\n    where trade.Date.Month == monthIndex\n    select trade).ToList().ForEach( trade => trade.Buy += optionQty);	0
3721817	3721791	How to download multi files in c#	WebClient client = new WebClient();\n        client.DownloadFileAsync(new Uri("http://test.com/file1"), "C:/Localfile1");\n        client.DownloadFileAsync(new Uri("http://test.com/file2"), "C:/Localfile2");	0
28298408	28297770	Loop without resetting vars	private string[] _allLines;\nprivate int _linesRead;\nvoid Start() { \n    _linesRead = 0;\n    var savedDoc = File.OpenText("C:/KleindierparkAdministratie/voer/voer.txt");\n    _allLines = savedDoc.ReadAllLines();\n}\nvoid OnGUI() {\n    if (/* Button pressed*/) {\n    // read next line and do stuff\n    }\n}	0
19588850	19587969	convert Date from "/Date(xxxxxxxxxxxx)/" to datetime in c#	public static string ParseFromString(string dateTime){\n    return new DateTime(1970,1,1).AddMilliseconds(double.Parse(Regex.Match ("/Date(1330540200000)/", @"(\d+)").Value)).ToString("MM:dd:yyyy");\n}	0
22274771	22274663	Windows Mobile 5 Error reading XML	// untested, from memory\nXDocument x = XDocument.Load(xmlReader);\nvar ns = x.Root.GetDefaultnamespace();\n\nvar EmpData = from emp in x.Descendants(ns + "V")\n              select new M\n              ...\n                Descendants(ns + "I")	0
4576315	4576114	C# custom string split library, 	string[] lines =  Regex.Split(inputString, @"(?<=\r\n)(?!$)");	0
32297679	32291366	Loading TreeView and XML control from XML in C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string input =\n            "<book time=\"\" title=\"\">" +\n              "<page time=\"\">" +\n                "<title></title>" +\n                "<content>" +\n\n                "</content>" +\n                "<pgno></pgno>" +\n              "</page>" +\n            "</book>";\n\n\n            XDocument doc = XDocument.Parse(input);\n            // or from a file\n            //XDocument doc = XDocument.Load(filename);\n\n            XElement title = doc.Descendants("title").FirstOrDefault();\n        }\n\n    }\n}\n???	0
12930115	12929889	two Listboxes, One selection in javascript	document.getElementById("lstFilter").selectedIndex = -1;	0
20090791	20077736	How to access OLVColumn sender inside of the ImageGetterDelegate	foreach (DirectoryInfo dir in directoryList.GetDirectories())\n{\n    BrightIdeasSoftware.OLVColumn myOLVColumn = new BrightIdeasSoftware.OLVColumn();\n    myOLVColumn.ImageGetter = delegate(Object x) {\n        /*I CAN access myOLVColumn here, \nas far as I don't mess with that object in the other code, \nand even if the for loop changes myOLVColumn, as far as it makes a new one and don't destroy it\nthe delegate will still have the pointer to the object the variable pointed to \nduring the generation of the delegate*/\n        return getImage(x, myOLVColumn);\n    };\n    //...\n}	0
5017939	5017697	EF4 CTP5 How To? Map an inherited Property to a field in a related table	[NotMapped]\npublic double HighLimit\n{\n  get\n  {\n    var current = propertyValues.SingleOrDefault(p => p.Key == "HighLimit");\n    return current != null ? current.Value : 0.0;\n  }\n  set \n  {\n    var current = propertyValues.SingleOrDefault(p => p.Key == "HighLimit");\n    if (current != null)\n    {\n      current.Value = value;\n    }\n    else\n    {\n      propertyValues.Add(new PropertyValue { Key = "HighLimit", Value = value });\n    }\n  }\n}	0
10762758	10762715	C# Parsing specific xml	using System.Xml.Linq;\n\nvar doc = XDocument.Parse(@"...");\nvar element = doc.XPathSelectElement("/users/user[@id='John']");\nvar website = element.XPathSelectElement("website").Value;\nvar type = int.Parse(element.XPathSelectElement("type").Value);	0
1059370	1058485	In Visual Studio, how do you make a specific window open during a build?	Private Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin\n  DTE.Windows.Item("{43CD29AA-0CA4-4F1C-8265-219788EF4908}").Activate() 'Build Status\nEnd Sub	0
23260010	23259209	Get all the number between two numbers random	var rnd = new Random();\n\nvar numbers =\n    Enumerable\n        .Range(1, 9)\n        .OrderBy(x => rnd.Next())\n        .ToArray();	0
24481828	24481752	How can i make mouse click on form1 over an image rectangle/area?	public partial class Form1 : Form\n    {\n        Rectangle rec;\n        Bitmap bmp;\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            bmp = new Bitmap(@"YourImageUrlHere");\n            rec = new Rectangle(0, 0, 100, 100);\n        }\n\n        private void Form1_Paint(object sender, PaintEventArgs e)\n        {\n            if (bmp != null)\n                e.Graphics.DrawImage(bmp, rec);\n        }\n\n        //private void Form1_Click(object sender, EventArgs e)\n        //{\n        //    dont use this....\n        //}\n\n        private void Form1_MouseClick(object sender, MouseEventArgs e)\n        {\n            if(rec.Contains(e.Location))\n                MessageBox.Show("Test");\n        }\n    }	0
16040381	16039876	Is there a way to get type-metadata from an object during debugging	list[0].GetType()	0
8519609	8508321	How to generate .resx and .properties files from the same XLIFF translation file	resgen foo.resx foo.txt	0
3682070	3682052	c# - how do square brackets in a method declaration fit in with c#?	public class Foo {\n    private List<int> m_Numbers = new List<int>();\n\n    public int this[int index] {\n        get {\n            return m_Numbers[index];\n        }\n        set {\n            m_Numbers[index] = value;\n        }\n    }\n}\n\nclass Program {\n    static void Main() {\n        Foo foo = new Foo();\n        foo[0] = 1;\n    }\n}	0
12298933	12298883	multiple strings in one arraylist in ASP.NET 1.1	list.Add(new string[]{"ccc", "sss", "34d"});	0
32436561	32436464	Prevent WPF controls from inheriting windowstyle	this.InheritanceBehavior = InheritanceBehavior.SkipAllNow;	0
28587007	28586935	Using LINQ to build a cascading list in C#	var selectedDepartmentSubDepartments = \n    from dep in departments \n    join subDep in subDepartmentList\n    on dep.Value equals subDep.Id.ToString()\n    where dep.IsSelected\n    select new ListItem {\n        Text = subDep.Name,\n        Value = subDep.Id.ToString(),\n        IsSelected = false\n    };\nvar subdepartments = new List<ListItem>(selectedDepartmentSubDepartments);	0
18342731	18342090	How to calculate time complexity of this function which checks if a string has all unique characters?	for (each item in input)\n  for (each item in input)\n    // do something	0
23613483	23612612	Automapper two level mapping	Mapper.CreateMap<DatabaseA, A>()\n  .ForMember(dest => dest.Bprop , opt => opt.MapFrom(src => src.Bprop));\n\nMapper.CreateMap<DatabaseB,B>()\n  .ForMember(dest => dest.Cprop , opt => opt.MapFrom(src => src.Cprop));\n\nMapper.CreateMap<DatabaseC, C>();	0
9296364	9295629	Round Up a double to int	Math.Ceiling(0.2) == 1\nMath.Ceiling(0.8) == 1\nMath.Ceiling(2.6) == 3\nMath.Ceiling(-1.4) == -1	0
15151131	15150934	Lambda to compare two Lists	foreach (var bItem in listB)\n{\n    if (listA.Any(aItem => bItem.Car_number == aItem.Car_number || bItem.status == aItem.status))\n        listC.Add(bItem);\n    else\n        listA.Add(bItem);\n}	0
30229228	30229106	Trying to access a SQL Server database to display a single row in c#	public Form1()\n{\n    InitializeComponent();\n\n    string connectionString = "Data Source=localhost \\SqlExpress;Initial Catalog=MMABooks;" + "Integrated Security=True";\n    Object returnValue;\n    SqlConnection connection = new SqlConnection(connectionString);\n\n    string selectStatement = "SELECT Top 1 ProductCode " + "FROM Products " + "WHERE ProductCode = @ProductCode";\n    SqlCommand selectCommand = new SqlCommand(selectStatement, connection);\n\n    selectCommand.Commandtype = CommandType.Text;\n    connection.Open();\n\n    returnValue = selectCommand.ExecuteScalar();\n    connection.Close();\n    txtDisplay.Text = returnValue.ToString();\n\n}	0
30790809	30790674	Create a new excel sheet and naming it	Dim WS As Worksheet \nSet WS =Sheets.Add(After:=Sheets(Worksheets.count)) \nWS.name = "xxx"	0
17432529	17432415	generating xml string and passing in namespace	XDocument xdoc = new XDocument(\n    new XElement("Feedback",\n        new XAttribute(XNamespace.Xmlns + "i", "http://www.w3.org/2001/XMLSchema-instance"),\n        new XAttribute(XNamespace.Xmlns + "j", "http://schemas.sitename.com/2013/03/Project.Models"),\n        new XElement("Record",\n            new XElement("ID", idGuid),\n            new XElement("SubID", subGuid),\n            new XElement("UserID", 2),\n            new XElement("Page", pages)\n        )\n    )\n);	0
3522119	3522105	How to convert this C# code to Visual basic	Dim matchingUsers As List(Of XmlUser) = Me.Store.Users.FindAll( _\n    Function(user As XmlUser) user.Email.Equals(emailToMatch, StringComparison.OrdinalIgnoreCase) _\n)	0
2589491	2588808	Castle Windsor Dynamic Property in XML config	inspectionBehavior="none"	0
9463679	9463620	Upon creating of new data lead to posting on Facebook User/Group's Wall	Dictionary<string, string> postArgs = new Dictionary<string, string>();\npostArgs["message"] = "Hello, world!";\napi.Post("/userid/feed", postArgs);	0
11753496	11753085	Scope of variables in aspx.cs file	protected void Button1_Click(object sender, EventArgs e)\n    {\n        OleDbConnection con = new OleDbConnection();\n        con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jayant\Documents\User_Details.accdb";\n        con.Open();\n        adapter = new OleDbDataAdapter("Select * from User_Details",con);\n        adapter.Fill(ds);\n        GridView1.DataSource = ds;\n        Session.Add("Dataset", ds); //Adding Session here\n        GridView1.DataBind();\n        con.Close();\n    }\n\n    protected void Button2_Click(object sender, EventArgs e)\n    {\n        DataSet ds = (DataSet)Session["Dataset"]; //Retrieving Value from session\n        ds.WriteXml("C:\\MyUser_Details.xml");\n    }	0
9694387	9693943	How to use string keys in (fluent) NHibernate	public class EntityMap : ClassMap<Entity>\n{\n    public EntityMap()\n    {\n        Id(x => x.Name).GeneratedBy.Assigned();\n        Map(x => x.TimeStamp);\n    }\n}	0
19632218	19632069	How to convert number of days to years,months and days	DateTime startDate = new DateTime(2010, 1, 1);\nDateTime endDate = new DateTime(2013, 1, 10);\nvar totalDays = (endDate - startDate).TotalDays;\nvar totalYears = Math.Truncate(totalDays / 365);\nvar totalMonths = Math.Truncate((totalDays % 365) / 30);\nvar remainingDays = Math.Truncate((totalDays % 365) % 30);\nConsole.WriteLine("Estimated duration is {0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);	0
15275539	15273665	While loop in C# going infinite	namespace ProgrammingTesting\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine("GUESS THE ANSWER");\n        Console.WriteLine("Please enter the input");\n        int input1 = 0;\n        while (input1 != 4)\n        {\n            input1 = (int.Parse(Console.ReadLine()));\n\n\n            if (input1 == 4)\n            {\n                Console.WriteLine("You are a winner");\n                Console.ReadLine();\n            }\n            else if (input1 < 4)\n            {\n                Console.WriteLine("TOOOOO low");\n\n\n            }\n            else if (input1 > 4)\n            {\n                Console.WriteLine("TOOOO high");\n\n            }\n        }\n    }\n}	0
1803249	1803191	How can I cause a panel to scroll programatically to expose its AutoSized picture box	private void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    if (dragging)\n    {\n        if (e.Button == MouseButtons.Left)\n        {\n            int horizontalChange = (e.X - startingX) * -1;  // move the image inverse to direction dragged\n\n            int verticalChange = (e.Y - startingY);\n\n            pictureBox1.Left += horizontalChange;\n            pictureBox1.Top += verticalChange;\n        }\n    }\n\n    startingX = e.X;\n    startingY = e.Y;\n}	0
13486297	13485693	Calling a timer tick event from Windows Form Application from another class with no GUI	static void threadcal()\n    {\n        while (true)\n        {\n            Thread.Sleep(1000);\n            Class1 c = new Class1();\n            c.test("192.168.1.188", 9999);\n        }\n    }	0
3282911	3282384	RichTextBox syntax highlighting in real time--Disabling the repaint	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass MyRichTextBox : RichTextBox {\n    public void BeginUpdate() {\n        SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);\n    }\n    public void EndUpdate() {\n        SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); \n        this.Invalidate();\n    }\n    [DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n    private const int WM_SETREDRAW = 0x0b;\n}	0
7669231	7669167	Getting the Authorization header from an http request	string value = Request.Headers["Authorization"]	0
6601958	6601933	Setting ASP.NET update panel to be 100% of its parent container?	height: 100%	0
2507673	2490765	Which is the best HTML tidy pack? Is there any option in HTML agility pack to make HTML webpage tidy?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n      doc.OptionFixNestedTags=true;	0
14774875	14753642	Determine the objectClass of a given id from LDAP	SearchResult result = directorySearcher.FindOne();\n        if (result == null)\n            return new LocalPermissionEntry(accessRule);\n\n        ResultPropertyValueCollection userValueCollection = result.Properties["objectClass"];\n\n        // check if the entry is a group or a user.\n        if (userValueCollection.Contains("group"))\n            return new GroupPermissionEntry(accessRule);\n        if (userValueCollection.Contains("person") || userValueCollection.Contains("user"))\n            return new UserPermissionEntry(accessRule);\n\n        return new LocalPermissionEntry(accessRule);	0
15288564	15288422	How do i add to the listBox another item?	private void timer2_Tick(object sender, EventArgs e)\n        {\n            if (tempCpuValue >= (float?)nud1.Value || tempGpuValue >= (float?)nud1.Value)\n            {\n                soundPlay = true;\n                blinking_label();\n                NudgeMe();\n            }\n            else\n            {\n                soundPlay = false;\n                stop_alarm = true;\n\n            }\n            data = new List<string>();\n            cpuView();\n            gpuView();\n            listBox1.DataSource = data;\n            listBox1.Invalidate();\n        }	0
20736320	20736296	ASP.NET C# How to get user language from header?	var userLanguages = Request.UserLanguages;\nvar ci = userLanguages.Count() > 0 \n    ? new CultureInfo(userLanguages[0])\n    : CultureInfo.InvariantCulture;	0
9230283	9230053	Stop Entity Framework from modifying database	public class SchoolDBContext: DbContext \n{\n    public SchoolDBContext() : base("SchoolDBConnectionString")\n    {            \n        //Disable initializer\n        Database.SetInitializer<SchoolDBContext>(null);\n    }\n    public DbSet<Student> Students { get; set; }\n    public DbSet<Standard> Standards { get; set; }\n}	0
9481610	9481494	How to extract the URL from this XML string using C# Asp.net	XmlDocument xml = new XmlDocument();\nxml.LoadXml(myXmlString); // your XML String\n\nXmlNodeList xnList = xml.SelectNodes("/upload/links");\nforeach (XmlNode xn in xnList)\n{\n  string original= xn["original"].InnerText;\n  string imgur_page = xn["imgur_page"].InnerText;\n  string delete_page = xn["delete_page"].InnerText;\n  string small_square = xn["small_square"].InnerText;\n  string large_thumbnail= xn["large_thumbnail"].InnerText;\n\n\n}	0
7839007	7838765	C# reading text file from certain location to EOF	using(TextReader tr = new StreamReader(filePath))\n{\n    StringBuilder sb = new StringBuilder();\n    for(string line = tr.ReadLine(); line != null; line = tr.ReadLine())\n        if(line == "[new]")\n            sb = new StringBuilder("[new]");//flush last chunk read.\n        else\n            sb.Append('\n').Append(line);\n    return sb.ToString();\n}	0
15437492	15434139	How to access continuation token for ListBlobSegmented	BlobRequestOptions options = new BlobRequestOptions();\n    options.UseFlatBlobListing = true;\n    ResultSegment<IListBlobItem> list = Global.ContainerTools.ListBlobsSegmented(5, null, options);\n\n    foreach (CloudBlob b in list.Results)\n    {\n        System.Diagnostics.Debug.WriteLine(b.Uri);\n    }\n\n    while (list.ContinuationToken != null)\n    {\n        list = Global.ContainerTools.ListBlobsSegmented(5, list.ContinuationToken, options);\n        foreach (CloudBlob b in list.Results)\n        {\n            System.Diagnostics.Debug.WriteLine(b.Uri);\n        }\n    }	0
33983879	33983862	How to populate a GridView with singe object from LINQ query?	var newReviews = (from r in myEntities.Reviews\n                  orderby r.Id\n                  select r).Single();\n\nGridView1.DataSource = new[]{ newReviews;}\nGridView1.DataBind();	0
6675741	6675676	How HttpContext.Current is visible for the whole application if it isn't static?	public static HttpContext Current { get; set; }	0
11737271	11736507	How can we drag a image from folder to form at run time?	private void pictureBox1_DragEnter(object sender, DragEventArgs e)\n    {\n\n        try\n        {\n            pictureBox1.Image = null;\n            string[] filename = (string[])e.Data.GetData(DataFormats.FileDrop);\n            pictureBox1.Image = Image.FromFile(filename[0]);\n        }\n        catch (Exception expr)\n        { }\n    }	0
27677702	27677615	How to disable event temporarily	bool isRowEmpty = dataGridView1.CurrentRow.Cells\n    .Cast<Cell>()\n    .All(cell => IsNullOrWhiteSpace(cell.FormattedValue.ToString()));\nif (isRowEmpty) {\n    // validate\n}	0
26421850	26421252	Save Outlook mailitem body as PDF	MailItem.BodyFormat = OlBodyFormat.olFormatRichText;\nMailItem.SaveAs("FilePath", OlSaveAsType.olRTF)	0
1706545	1706504	How to communicate between a user control and my main form?	protected void Button_Click(object sender, EventArgs e)\n{\n   UserControl1.DoMethod();\n   UserControl2.DoMethod();\n   UserControl3.DoMethod();\n}\n\npublic class YourUserControl : UserControl\n{ \n   public void DoMethod()\n   {\n      // Show your ListBoxes\n   }\n}	0
9568309	9568277	Display whole number decimal data type to 1dp	Console.WriteLine(item.ToString("F1"));	0
15575512	15574959	Need help understanding MEF	PRISM WPF Development With MEF	0
13650830	13650788	WP8 LongListSelector - re-assigning ItemsSource has no effect	ObservableCollection<Group<PlacePoint>> searchResults = new ObservableCollection<Group<PlacePoint>>();\n\n\n    public SearchPage()\n    {\n        InitializeComponent();\n\n        longList.ItemsSource = this.searchResults;\n    }\n\n    async void doSearch()\n    {\n        List<Group<PlacePoint>> tempResults = await SearchHelper.Instance.getSearchResults(txtSearchTerm.Text);\n\n        // Clear existing collection and re-add new results\n        this.searchResults.Clear();\n        foreach (Group<PlacePoint> grp in tempResults )\n        {\n            this.searchResults.Add(grp);\n        }\n    }	0
33446004	33445729	3D rotation, given two specified directions	M.M'.M.inv(M) = M.inv(M)\n=> M.M'.(M.inv(M)) = M.inv(M) = I\n=> M.M' = I	0
6519292	6519125	ERD Multi-user level access under a single account	USER\nUserId\nBusinessInfoId (FK)\nName\nUsername\nPassword\nFirstName\nMiddleName\nLastName\n...\n\nBUSINESS_INFO\nBusinessInfoId (PK)\nBusinessName\n....	0
11025002	11024349	edit specific pixels in an in buffer for a raw data image file	for(int i = 0; i < this.pixelBuffer.Length; i++) \n  this.pixelBuffer[i] *= 42;	0
155851	155848	How do I create a Microsoft Jet (Access) database without an interop assembly?	if (!File.Exists(DB_FILENAME))\n{\n    var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME;\n\n    // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. \n    var catType = Type.GetTypeFromProgID("ADOX.Catalog");\n    object o = Activator.CreateInstance(catType);\n    catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});\n\n    OleDbConnection cnn = new OleDbConnection(cnnStr);\n    cnn.Open();\n    var cmd = cnn.CreateCommand();\n    cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)";\n    cmd.ExecuteNonQuery();\n\n}	0
27029697	27028294	Convert to JSON Array, not regular object	public static string fromListToJSONArray(IEnumerable<dynamic> listToUse)\n    {\n        string JSONString = "[";\n        foreach (var item in listToUse)\n        {\n            if(isFirst == false)\n                JSONString += ",";\n            else\n                isFirst = false;\n            JSONString += "\"" + item[0] + "\"";\n        }\n        JSONString += "]";\n        return JSONString;\n        JSONString += "]";\n        return JSONString;\n    }	0
12574934	12574927	Where Clause in LINQ with IN operator	private DataTable CreateSummaryFocusOfEffortData(List<int> yourList)\n{\n    var result = ReportData.AsEnumerable()\n        .GroupBy(row => new\n                            {\n                                Value = row.Field<string>("Value"),\n                                Description = row.Field<string>("Description")\n\n                            })\n        .Select(g =>\n                    {\n                        var row = g.First();\n                        row.SetField("Hours", \n                                     g.Where(r=>yourList.Contains(r.Field<int>("Id")))\n                                      .Sum(r => r.Field<double>("Hours")));\n\n                        return row;\n                    });\n\n  return result.CopyToDataTable();\n}	0
357570	357465	Can I Add ConnectionStrings to the ConnectionStringCollection at Runtime?	var cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(@"/");\ncfg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(params));\n\ncfg.Save();	0
15565225	15565054	How to display double as DateTime format (HH:mm:ss)?	private static string Get_now(int minus)\n    {\n        return DateTime.Now.AddMinutes(-minus)\n            .ToString("HH:mm:ss");\n    }	0
26017099	26014614	Unity3d from a list, get only entities of specific component type	public static IEnumerable<T> GetItemsAsT<T>(this GameObject[] objects) \n    where T:UnityEngine.Component\n    {\n        foreach(var obj in objects)\n        {\n            var t = obj.GetComponent<T>();\n            if(t != null)\n                yield return t;\n        }\n        yield break;\n    }	0
3667107	3667088	Sorting a list of items in a list box	ArrayList q = new ArrayList(); \nforeach (object o in listBox4.Items) \n        q.Add(o);\n} \nq.Sort(); \nlistBox5.Items.Clear();\nforeach(object o in q){\n    listBox5.Items.Add(o); \n}	0
13243007	13242646	Parsing a MIDI file for Note On only	byte[] MIDI = File.ReadAllBytes("TestMIDI5.mid");\nfor(int i=0;i<MIDI.Length;i++){\n    if(MIDI[i]==144) {\n        Debug.WriteLine(MIDI[i+1]);  //This is the note value\n    }\n}	0
8296509	8274049	How to free clipboard locked by another process?	Success := false;\nAttempts := 0;\nWhile (Attempts < 3) and (Success = false) do\nbegin\n  Try\n    inc(Attempts);\n    OpenClipboard;\n    Success := true;\n  except\n    sleep(attempts * 1000);\n  end\nend;	0
1798358	1798348	c# stack queue combination	LinkedList<int> list = new LinkedList<int>();\n\nlist.AddFirst(1);\nlist.AddLast(2);\nlist.AddFirst(0);	0
3335447	1645247	Creating a DataTable object with dummy data	DataSet ds = new DataSet();\n\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Name");\n        dt.Columns.Add("Branch");\n        dt.Columns.Add("Officer");\n        dt.Columns.Add("CustAcct");\n        dt.Columns.Add("Grade");\n        dt.Columns.Add("Rate");\n        dt.Columns.Add("OrigBal");\n        dt.Columns.Add("BookBal");\n        dt.Columns.Add("Available");\n        dt.Columns.Add("Effective");\n        dt.Columns.Add("Maturity");\n        dt.Columns.Add("Collateral");\n        dt.Columns.Add("LoanSource");\n        dt.Columns.Add("RBCCode");\n\n        dt.Rows.Add(new object[] { "James Bond, LLC", 120, "Garrison Neely", "123 3428749020", 35, "6.000", "$24,590", "$13,432",\n            "$12,659", "12/13/21", "1/30/27", 55, "ILS", "R"});\n\n        ds.Tables.Add(dt);\n\n        accReportData.DataSourceID = null;\n        accReportData.DataSource = ds.Tables[0].DefaultView;\n        accReportData.DataBind();	0
20188406	20187878	Convert String to OpCode	var opCodes = typeof(OpCodes)\n                    .GetFields(BindingFlags.Static | BindingFlags.Public)\n                    .Where(x=> x.FieldType == typeof(OpCode))\n                    .Select(x=> (OpCode)x.GetValue(null))\n                    .ToArray();\n\nforeach(var opcode in opCodes)\n{\n   //Do whatever with opcode\n}	0
18469137	18468838	Showing records of added or removed items from file comparison	foreach (ExcelCell cell in excelRow.AllocatedCells)\n    {\n        if (cell.Value != null)\n            Console.Write("{0}({1})", cell.Value, cell.Value.GetType().Name);\n\n        Console.Write("\t");\n    }	0
33471478	33471024	Not able to Parse DataTime From String to DATETIME	var dateTime = "01-07-2015";\nvar date = DateTime.ParseExact(dateTime, "mm-dd-yyyy", CultureInfo.InvariantCulture);	0
13456433	13453409	Updating a lookup field from a Silverlight app - CRM 2011	private string serverUrl = "";\nScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");\nScriptObject page = (ScriptObject)xrm.GetProperty("Page");\nScriptObject pageContext = (ScriptObject)page.GetProperty("context");\nserverUrl = (string)pageContext.Invoke("getServerUrl");	0
10624012	10623850	Text from Code Code Behind into Textblock with Different Font Style	textBlock.Inlines.Add(new Run\n                           {\n                               FontFamily = new FontFamily("Comic Sans"),\n                               Text = "Your text"\n                           });\n        textBlock.Inlines.Add(new Run\n        {\n            FontFamily = new FontFamily("Tahoma"),\n            Text = " is different"\n        });	0
31560626	31560375	how to pass a substring or single character within datagridview	string test = "animal?species";\nstring [] splittedtest = string.Split(new Char[] { '?', '\' },\n                             StringSplitOptions.RemoveEmptyEntries);\n//string[] splittedtest = test.Split('?');\nfor(int i = 0;i<splittedtest.length;i++)\n{\n   // do your stuffs like below,  \n   // DataGridView1.Rows[DataGridView.SelectedRows[0].Index].Cells[X].Text = splittedtest[i];\n   // where X is the column you want to read. \n}	0
12572504	12567559	changing absolute Path to relative Path	files.Select(f => f.Substring(activeDirectory.Length))	0
12508183	12507132	Copying a collection of entites	var copyToUser = this.GetUser(copyToUserId);\n            List<UserApplicationRole> userApplicationRoles = new List<UserApplicationRole>();\n            int startingId = Convert.ToInt32(isignonContext.UserApplicationRoles.OrderByDescending(u => u.UserApplicationRoleId).FirstOrDefault().UserApplicationRoleId) + 1;\n\n            foreach (var u in userApplicationRolesToAdd)\n            {\n                UserApplicationRole userApplicationRole = new UserApplicationRole\n                {\n                    UserApplicationRoleId = startingId,\n                    UserID = copyToUser.UserId,\n                    UserGroupId = copyToUser.ParentId.Value,\n                    ApplicationRoleId = u.ApplicationRoleId,\n                    ExpiryDate = u.ExpiryDate,\n                    IsEnabled = u.IsEnabled\n                };\n\n                userApplicationRoles.Add(userApplicationRole);\n                startingId++;\n            }	0
17654462	17651830	Add/Remove Class in header column in GridView ASP.NET from code behind file	if (gvName.Rows.Count > sortingLimit)  //Check for rowcount for limit before sorting\n        {\n            gvName.HeaderRow.Cells[0].CssClass = "noSort fieldAlignCenter";\n            gvName.HeaderRow.Cells[1].CssClass = "noSort";\n            gvName.HeaderRow.Cells[2].CssClass = "noSort";\n            gvName.HeaderRow.Cells[3].CssClass = "noSort";\n            gvName.HeaderRow.Cells[4].CssClass = "noSort";\n            gvName.HeaderRow.Cells[5].CssClass = "noSort";\n            gvName.HeaderRow.Cells[7].CssClass = "noSort";\n        }	0
10182440	10182395	How to call a stored procedure from MVC that requires datetimes	var startDate = new SqlParameter("FinancialYearStartDate", dateTimeValueHere);\nvar endDate = new SqlParameter("FinancialYearEndDate", dateTimeValueHere);\n\nreturn _db.Database.SqlQuery<HomePageInvoice>("Invoice_GetHomePageInvoices", startDate, endDate);	0
33674438	33669483	c# regex - all white space before <pre>	(?s)([\s\r\n]*(?<value></?.*?>)[\s\r\n]*|(?<=</?.*?>)[\s\r\n]*(?<value>.*?)[\s\r\n]*(?=</?.*?>))(?=.*\n<pre>)	0
17199330	17184435	Entity Framework 5 doesn't update Many to Many relation	accomodation.Attrbutes.Add(attribute);	0
30733469	30732841	CSV, add column in first position and fill the first Column with filename	// #1 Read CSV File\nstring[] CSVDump = File.ReadAllLines(@"c:\temp.csv");\n\n// #2 Split Data\nList<List<string>> CSV = CSVDump.Select(x => x.Split(';').ToList()).ToList();\n\n//#3 Update Data\nfor (int i = 0; i < CSV.Count; i++)\n{\n    CSV[i].Insert(0, i == 0 ? "Headername" : "Filename");\n}\n\n//#4 Write CSV File\nFile.WriteAllLines(@"c:\temp2.csv", CSV.Select(x => string.Join(";", x)));	0
12128581	12128551	How can I combine .Select from two LINQ expressions into one?	protected IEnumerable<string> GetErrorsAndExceptionsFromModelState()\n{\n    var errors = ModelState\n                    .SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage)\n                    .Union(x.Value.Errors.Select(error => error.Exception.Message)));\n    return errors;\n}	0
6215792	6215638	C# connecting to a database	Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;	0
24898226	24898200	How to write a variable value to a file	File.WriteAllText(@"C:\WhatFound.txt", k);	0
5921038	5921005	Database for C# application	a couple	0
22524974	22524657	How to get all urls from a webpage belonging to same Domain	domain = baseUri.Host.Replace("www.", string.Empty);	0
33248924	33248889	c# - Linq Query to retrieve all objects with a max value	var res = list\n    .GroupBy(item => item.A)\n    .OrderByDescending(g => g.Key)\n    .First()\n    .ToList();	0
11434378	11434338	Getting control ids in a repeater	foreach (ListViewItem item in lvData.Items)\n{\n    Control ctrl = item.FindControl("lbUnattend");\n    ctrl.Visible = false;\n}	0
16293301	15542759	How to use Partials with Nustache in c# application?	var tpl = "{{employee}}<li>{{firstName}} {{lastName}}</li>{{/employee}}{{#depts}}<h1>{{name}}</h1>" +\n      "<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";	0
17818870	17818829	Multi threading console app issue c#	Parallel.ForEach	0
9688654	9688551	Convert a binary number to ascii characters	int i = 26990;\nchar c1 = (char)(i & 0xff);\nchar c2 = (char)(i >> 8);\n\nConsole.WriteLine("{0}{1}", c1, c2);	0
14365063	14364939	Getting connection refused when calling a web service from a web app works fine from localhost	netstat -anb	0
16243335	16243261	initialize array with default constructor	Enumerable.Range(0,10).Select(i=>new Person()).ToArray();	0
27422199	27421608	Serialization and Deserialization of XML Document using threads	new XmlSerializer()	0
18074935	18074764	Windows Phone 8 - Saving a List to IsolatedStorage	public class Lekarna	0
9442337	9442097	How to replace characters in a text box as a user is typing in it? (in c#)	public void OnKeyDown(Object sender, KeyEventArgs e)\n{\n   char[] text = textBox.Text.ToCharArray();\n   int pos = textBox.SelectionStart;\n\n   switch (e.KeyCode)\n   {\n       case Keys.Back: if (pos == 0) return; pos --; break;\n       case Keys.Delete: if (pos == text.Length) return; break;\n       default: return;\n   }\n\n   switch (text[pos])\n   {\n       case '?': text[pos] = '*'; break;\n       case '*': text[pos] = '?'; break;\n       default: return;\n   }\n   textBox.Text = new String(text);\n   e.Handled = true;\n}	0
30510659	30510475	Passing URI Parameters to Sevice	public HttpResponseMessage Get(string test1, string test2)\n{\n    ...\n}	0
23269845	23269616	Loading XAML Resource File in ClassLibrary dll	System.Reflection.Assembly\n   .GetExecutingAssembly()\n   .GetManifestResourceStream("mycompany.myproduct.some.xaml");	0
26792829	26792426	Copy directory with all files and folders	string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");\n\nfolderDialog.SelectedPath = Path.Combine(folderDialog.SelectedPath,\n    Path.GetFileName(sourcedirectory));\n\nforeach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))\n{\n    Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));\n}\nforeach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))\n{\n    File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);\n}	0
22450685	22450424	Users permission to files	Response.Redirect(@"/GetFile.ashx?Timestamp=[Symmetrically Encrypted Current Date and Time]&FileName=Example.doc");	0
13810220	13770666	Unit testing with and without private Accessor	private void OnCopyClick(object sender, EventArgs args)\n{\n    var cmd = new MyCopyCommand(this.FolderPath, this.txtTargetFolderPath.Text);\n    new ErrorHandler(this).Perform(cmd);\n}	0
14446892	14433364	How to create child process to execute a method in c#?	pcap_close()	0
9258622	9258580	How to call a PUT REST WCF method from C#	var request = WebRequest.Create("http://example.com/profile/190/updateprofile");\nrequest.Method = "PUT";\nrequest.ContentType = "application/json; charset=utf-8";\nusing (var writer = new StreamWriter(request.GetRequestStream()))\n{\n    var serializer = new JavaScriptSerializer();\n    var payload = serializer.Serialize(new \n    {\n        UserId = "9769595975",\n        Passold = "qwert1",\n        Passnew = "qwert2"\n    });\n    writer.Write(payload);\n}\n\nusing (var response = request.GetResponse())\nusing (var reader = new StreamReader(response.GetResponseStream()))\n{\n    string result = reader.ReadToEnd();\n    // do something with the results\n}	0
14109420	14109363	How to convert SQL select Count with group by clauses into LINQ?	ProcessedCPLeaves\n.GroupBy(item => new { \n                 LeaveTypeName = item.LeaveTypeName,\n                 EmpUserName = item.EmpUserName,\n                 ProcessingDate = item.ProcessingDate\n}).Select (grouping => new {\n                 EmpUserName =grouping.Key.EmpUserName,\n                 LeaveTypeName = grouping.Key.LeaveTypeName,\n                 TotalCount= grouping.Count()\n});	0
20044767	20044730	Convert character to its alphabet integer position?	char c = 'A';\n//char c = 'b'; you may use lower case character.\nint index = char.ToUpper(c) - 64;//index == 1	0
19787820	19787747	Insert a date into a textbox and then that date would be selected in the calendar asp.net c#	protected void TextBox1_TextChanged(object sender, EventArgs e)\n{\n    Calendar1.SelectedDate = Convert.ToDateTime(TextBox1.Text);\n}	0
8342119	3778623	List of computers in Active Directory that are online	Friend Shared Function DomainComputers() As Generic.List(Of String)\n\n    ' Add a Reference to System.DirectoryServices\n\n    Dim Result As New Generic.List(Of String)\n\n    Dim ComputerName As String = Nothing\n    Dim SRC As SearchResultCollection = Nothing\n    Dim Searcher As DirectorySearcher = Nothing\n\n    Try\n\n        Searcher = New DirectorySearcher("(objectCategory=computer)", {"Name"})\n\n        Searcher.Sort = New SortOption("Name", SortDirection.Ascending)\n        Searcher.Tombstone = False\n\n        SRC = Searcher.FindAll\n\n        For Each Item As SearchResult In SRC\n            ComputerName = Item.Properties("Name")(0)\n            Result.Add(ComputerName)\n        Next\n\n    Catch ex As Exception\n\n    End Try\n\n    Return Result\n\nEnd Function	0
34302937	34288689	Fluent Validation only if value is supplied	RuleFor(customer => customer.CustomerDiscount).GreaterThan(0).When(customer => customer.IsPreferredCustomer);	0
23950021	23522294	How to scroll a FlowLayout parent container to keep visible a portion of a children control?	public partial class Form1 : Form\n{\n    public Point InitialTextBoxLoc ;\n\n    public Form1()\n    {\n        InitializeComponent();\n        InitialTextBoxLoc = textBox1.Location;\n    }\n\n    private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        Point caretLocalLoc = textBox1.GetPositionFromCharIndex(textBox1.Text.Length-1);\n        Point caretLoc = new Point(caretLocalLoc.X + InitialTextBoxLoc.X,\n                                   caretLocalLoc.Y + InitialTextBoxLoc.Y);\n\n        Point scrollLoc = flowLayoutPanel1.AutoScrollPosition;\n        if (caretLoc.X >= flowLayoutPanel1.Size.Width-10)\n        {\n            scrollLoc.X = caretLoc.X;\n\n        }\n\n        if (caretLoc.Y >= flowLayoutPanel1.Size.Height-10)\n        {\n            scrollLoc.Y = caretLoc.Y;\n        }\n\n        flowLayoutPanel1.AutoScrollPosition = scrollLoc;\n\n    }\n}	0
3284245	3240094	How do I pull data from a javascript populated table?	var row = table.rows.item(i).cells;\nvar cellLength = row.length;\nvar cellVal = row.item(5).innerHTML;	0
14502763	14502665	Using SQLite with C#	dbConnection.Open();  //Initiate connection to the db	0
25496094	25490808	Windows Store App: prevent duplicate code in two almost identical User Controls	public PasswordInputBox(bool isForImage)\n    {\n        this.InitializeComponent();\n        if (isForImage)\n            //initialize actions for that part of the EmbedTypePanel;\n        else\n            EmbedTypePanel.Visibility = Visibility.Collapsed;\n    }	0
8717761	8709951	How to get HTTP stack type of HttpWebRequest for a rest request in Silverlight	if (webRequest.GetType().Name == "BrowserHttpWebRequest")\n {\n\n }\n else\n {\n\n }	0
1060741	1060254	How to set the text of a ListBox in code-behind design	public MyWindow()\n{\n    InitializeComponent();\n    yourListBox.SelectedIndex = indexOfRed;\n}	0
3413691	3413658	how to parse this text in c#	// Split at an = sign. Take at most two parts (word and definition); \n//    ignore any = signs in the definition\nstring[] parts = line.Split(new[] { '=' }, 2);\n\nword w = new word();\nw.Word = parts[0].Trim();\n\n// If the definition is missing then parts.Length == 1\nif (parts.Length == 1)\n    w.Definition = string.Empty;\nelse\n    w.Definition = parts[1].Trim();\n\nwords.Add(w);	0
3087754	3087682	What is the best-practice way to use Linq-to-SQL in a C# application? [Design-pattern]	GetPeople().StatusEnabled().BornInJuly().AgeIsGreaterThan( 57 );	0
768860	768841	Correct use of Object Properties	public DateTime DeathDate\n{\n    get;\n    private set;\n}	0
5635527	5635454	Find parent with defined attribute wuth LINQ	string secretId = element.Ancestors()\n                         .Where(x => (string) x.Attribute("segment") == "1")\n                         .Select(x => (string) x.Attribute("secret-id"))\n                         .FirstOrDefault();	0
5873827	5873757	Using abstract factory as injectionfactory in Unity?	RegisterType<Levels>(new InjectionFactory((c) => c.Resolve<ILevelFactory>().GetLevels()))	0
29133523	29133195	How to access a key named with asterisk?	string content;\n    using (var webClient = new WebClient())\n    {\n        const string url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=Cloud&prop=langlinks&lllimit=500&lllang=ru&continue=";\n        content = webClient.DownloadString(url);\n    }\n\n    var obj = JObject.Parse(content);\n    var query = obj["query"];\n    var pages = query["pages"].Value<JObject>();\n    var page = pages.PropertyValues().First();\n    var langLinks = page["langlinks"].Values<JObject>();\n    var firstLangLink = langLinks.First();\n    var localizedName = firstLangLink["*"];	0
10634454	10634327	Single column DGV to accept clipboard data	private void gridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) \n{\n    gridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Clipboard.GetText();\n}	0
3330569	3330447	Working with URL query Strings in ASP.NET	string redirect = "www.mysite.com?mykey=" + MyValue.ToString();\nResponse.Redirect(redirect);	0
11628752	11628644	How to add tooltip to all controls in a form programmatically - WPF, C#?	try with this code\n\nvar controls = grd.Children.OfType<TextBox>();\n\nforeach(var control in controls)\n{\n   Point point = Mouse.GetPosition(control);\n   control.ToolTip = point.X + " " + point.Y + " \n " + control.TabIndex ;\n}	0
2088773	2075649	DynamicObject implicit casting	int sum = myDynamicObject + 1;	0
24383391	24383256	How can I convert a jpg file into a bitmap, using C#?	public Bitmap ConvertToBitmap(string fileName)\n{\n    Bitmap bitmap;\n    using(Stream bmpStream = System.IO.File.Open(fileName, System.IO.FileMode.Open ))\n    {\n         Image image = Image.FromStream(bmpStream);\n\n         bitmap = new Bitmap(image);\n\n    }\n    return bitmap;\n}	0
30204252	30202675	Is this valid JSON for reading/parsing multiple objects?	{\n    "books": [\n        {\n            "id": "001",\n            "title": "Title 1",\n            "author": "Author 1",\n            "dimension": {\n                "height": "#cm",\n                "width": "#cm"\n            }\n        },\n        {\n            "id": "002",\n            "title": "Title 2",\n            "author": "Author 2",\n            "dimension": {\n                "height": "#cm",\n                "width": "#cm"\n            }\n        }\n    ]\n}	0
7567515	7567202	How to check for installed browsers using C# for newbies	RegistryKey browserKeys;\n//on 64bit the browsers are in a different location\nbrowserKeys =   Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");\nif (browserKeys == null)\n    browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet");\n\nstring[] browserNames = browserKeys.GetSubKeyNames();	0
1131245	920753	Building a MVVM 3D Editor Application -> Getting Mouse Position?	b:MouseBehavior.LeftClick="{Binding DoSomeActionCommand}"	0
16592144	16591733	User control property fails on set	public string SubjectTextBoxText\n{\n     get { return TextBox1.Text; }\n     set { Textbox1.Text = value; }\n}	0
14351348	14351164	Building a multilevel hierarchy tree that is dynamic and not symmetric	class ValidationNode\n{\n    bool IsValid { get; }\n    object EntityToValidatate { get; set; }\n    string ErrorMessage { get; set; }\n\n    ValidationNode Parent { get; set; } \n\n    IList<ValidationNode> Children { get; set; }\n}	0
4019647	4019552	How to loop through a set of XElements?	XDocument xml = XDocument.Parse(xmlString);\nvar visitors = (from visitor in xml.Descendants("latestvisitors").Descendants("user")\n                select new Visitor() {\n                  ID = visitor.Element("id").Value,\n                  Name = visitor.Element("name").Value,\n                  Url = visitor.Element("url").Value,\n                  Photo = visitor.Element("photo").Value,\n                  Visited = visitor.Element("visited").Value\n                });	0
9574451	9573838	Serializing JSON in .NET	var obj = new { pois = new List<object>() };\nobj.pois.Add(new { poi = new {title = "Test title", latitude = "-2.4857856", longitude = "54.585656" } });\nobj.pois.Add(new { poi = new {title = "Halfords"  , latitude = "-2.4857856", longitude = "53.5867856" } });\n\nstring json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);\n\nConsole.WriteLine(json);	0
14592415	14592375	Get an array of all alpha characters	string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nchar [] alphas = (alphabet + alphabet.ToLower()).ToCharArray();	0
5118886	5118761	Create XML string for Web Service	public static string SerializeToString(object o)\n{\n    string serialized = "";\n    System.Text.StringBuilder sb = new System.Text.StringBuilder();\n\n    //Serialize to memory stream\n    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(o.GetType());\n    System.IO.TextWriter w = new System.IO.StringWriter(sb);\n    ser.Serialize(w, o);\n    w.Close();\n\n    //Read to string\n    serialized = sb.ToString();\n    return serialized;\n}	0
1971262	1971246	explicit cast on XAttribute value	public static explicit operator int(XAttribute attribute);	0
7737032	7735376	Keeping configuration data external from Class Libraries	public interface IDataAccessConfiguration\n{\n    string Assembly { get; }\n    string Type { get; }\n}\n\npublic sealed class DataAccessfactory\n{\n    private IDataAccessConfiguration Config { get; set; }\n\n    public DataAccessfactory(IDataAccessConfiguration config)\n    {\n        this.Config = config;\n    }\n\n    public ISomeDataContext GetSomeDataContext()\n    {\n        return new SomeDataContext(this.Config);\n    }\n}\n\npublic class SomeDataContext : ISomeDataContext\n{\n    private IDataAccessConfiguration Config { get; set;}\n\n    public SomeDataContext(IDataAccessConfiguration config)\n    {\n        this.Config = config;\n    }\n\n    private DataContext GetDataContext()\n    {\n        Assembly a = Assembly.Load(this.Config.Assembly);       \n        return (DataContext)a.CreateInstance(this.Config.Type);  \n    }\n}	0
19198675	19198644	Finding the minimum value in c#	int i, pcm, maxm = 0, minm = Int32.MaxValue;\n    for (i = 1; i <= 3; i++)\n    {\n      Console.WriteLine("Please enter your computer marks");\n        pcm = int.Parse(Console.ReadLine());\n\n       if (pcm > maxm)\n        {\n           maxm = pcm;\n        }\n\n        if (pcm < minm)\n        {\n           minm = pcm;\n        }\n\n    }\n    Console.ReadKey();\n}	0
18485359	18485332	how to continue a foreach loop	foreach (string s in namearry)\n{\n    try\n    {\n        var timelineData = oAuthTwitterWrapper.GetMyTimeline(s);\n        if(timelineData!=null)\n        {\n             int clientID;\n             if(int.TryParse(dr["ClientId"].ToString(), out clientID))\n             {\n                  TwitterData.TimeLineData(timelineData, s, clientID);            \n             }\n        }\n    }\n    catch(Exception exp)\n    {\n        //do logging here.\n    }\n}	0
16738606	16737372	ASP Gridview drop down list selection changed, how to fill a dropdown list other than in rowDataBound()	protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)\n{\n    GridViewRow row = (GridViewRow)((DropDownList)sender).Parent.Parent;\n    DropDownList ddlSubCategory = (DropDownList)row.FindControl("ddlSubCategory");\n    ddlSubCategory.DataSource = //whatever you want to bind, e.g. based on the selected value, using((DropDownList)sender).SelectedValue;\n    ddlSubCategory.DataBind();\n}	0
790594	790592	How to solidly protect web.config	web.config	0
21444124	12809284	How to implement Casle Windsor installer to install different modules for debug and release?	#if DEBUG\n    container.Register(Component.For<INavigationStrategy>()\n                           .ImplementedBy<NavigationStrategy>()\n                           .LifestylePerWebRequest());\n#else\n    container.Register(Component.For<INavigationStrategy>()\n                           .ImplementedBy<DebugNavigationStrategy>()\n                           .LifestylePerWebRequest());        \n#endif	0
2640832	2640822	How do I simulate "In" using Linq2Sql	var items = _Db.Items.Where(i => idsToValidate.Contains(i.Key));	0
538751	538729	Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?	public static TValue GetValueOrDefault<TKey,TValue>\n    (this IDictionary<TKey, TValue> dictionary, TKey key)\n{\n    TValue ret;\n    // Ignore return value\n    dictionary.TryGetValue(key, out ret);\n    return ret;\n}	0
28355368	28355048	How to check if an object is numeric in C#	isNum = Double.TryParse(Convert.ToString(Expression), out retNum) && !Double.IsNaN(retNum);	0
26210569	26210430	How to copy 2D arraylist to another	List<string> tempList=new List<string>();\nforeach (List<String> lst in class_lables)\n{\n    foreach (string str in lst)\n            tempList.Add(str);\n    lables1.Add(tempList);\n    tempList.Clear();\n}	0
1184962	1184944	LINQ: From a list of type T, retrieve only objects of a certain subclass S	IList<Person> persons = new List<Person>();\n\npublic IList<T> GetPersons<T>() where T : Person\n{\n    return persons.OfType<T>().ToList();\n}\n\nIList<Student> students = GetPersons<Student>();\nIList<Teacher> teacher = GetPersons<Teacher>();	0
8677931	8677875	Open and read txt file in ASP	string path = Server.MapPath("TrackData/vehicle_points.txt");\n StreamReader reader = File.OpenText(path);	0
17610363	17610260	How to implement a comparer on a dictionary value	public Dictionary(IEqualityComparer<TKey> comparer);	0
11518685	11518680	For-Statement, Each 1000th Walkthrough, do something	if(i % 1000 == 0)\n{\n    //Do something\n}	0
607366	606943	Accessing styles programmatically to get values	DataTable dt = LookupStyles();\ndg.Styles.Clear();\nforeach (DataRow dr in dt.Rows)\n  dg.Styles.Add(dr["StyleName"].ToString(), dr["StyleValue"].ToString());	0
21260642	21260573	select all records between two dates using calendar	public List<Staff> GetStaff(DateTime DateOne, DateTime DateTwo,string color)\n{\n    //Some connection stuff\n    SqlCommand command = new SqlCommand(@"SELECT * FROM TableName \n                                          WHERE CAST(Time AS date)> @Time \n                                          and CAST(Time AS date)< @Time2\n                                          and staffColorCode = @color", conn);\n    command.Parameters.AddWithValue("Time", DateOne);\n    command.Parameters.AddWithValue("Time2", DateTwo);\n    command.Parameters.AddWithValue("color", color);\n\n    //retrieve data\n}	0
1961979	1961967	how can this happen?	Byte b = 255;\nb++;\nConsole.Out.WriteLine("b=" + b);	0
21429779	21429548	Trying to read text file	if (File.Exists(file))\n{\n    string[] lines = File.ReadAllLines(file);\n}	0
4772331	4765328	How to tweet with Twitterizer by using C#	using Twitterizer;	0
20531586	20531518	Randomizing order of IEnumerator	Random rand = new Random();\nvar models = garage.OrderBy(c => rand.Next()).Select(c => c.Model).ToList();	0
31934014	31930179	Using DbContextScopeFactory with Unity	var resolver = new Microsoft.Practices.Unity.WebApi.UnityDependencyResolver(UnityConfig.GetConfiguredContainer());\n\nGlobalConfiguration.Configuration.DependencyResolver = resolver;	0
15632603	15632363	<CLOSED(Reason: JSON String Error)>Unable to Deserialize List<myObject> from Valid JSON	public class Employee\n{\n    public int Employee_OID { get; set; }\n    public string First_Name { get; set; }\n    public string Last_Name { get; set; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string json = @"[{""Employee_OID"": 18450,""First_Name"": ""ABDUL"",""Last_Name"": ""RAJPUT""},{""Employee_OID"": 22446,""First_Name"": ""ABDUL"",""Last_Name"": ""KHAN""}]";\n        List<Employee> emp = (new JavaScriptSerializer()).Deserialize<List<Employee>>(json);\n        Console.WriteLine(emp.First().First_Name);\n    }\n}	0
3150062	3149896	how to access shared resource between 2 threads?	while(!isDone)	0
9991291	9991250	Obtaining a string from a JSON GET Request	private void DownloadString()\n{\n    var wc = new WebClient();\n    wc.DownloadStringCompleted += MyHandler;\n    wc.DownloadStringAsync(carUrl);\n}\n\nvoid MyHandler(object sender, DownloadStringCompletedEventArgs e)\n{\n    var result = e.Result;\n}	0
29845683	29845566	checking list contains string	return Json(!userlist.Any(x => x.Text == Forename));	0
29678840	29678809	How to calculate total of all properties within the object in C#?	public decimal Total { get { return A + B + C } };	0
11700858	11700358	Trying to make my windows form lighter	public Form1() {\n        InitializeComponent();\n        Application.Idle += new EventHandler((s, ea) => this.Invalidate());\n    }	0
34024761	34024407	how to display list<> in drop down list?	DropDownListPXPUsers.DataSource = GetPXPUsers();\nDropDownListPXPUsers.DateTextField = "PropertyOne"; // name of 'ChatUserDetails' property\nDropDownListPXPUsers.DataValueField = "PropertyTwo"; // name of 'ChatUserDetails' property\nDropDownListPXPUsers.DataBind();	0
19903820	19903408	Adding a control to repeater item template programmatically	parentRepeater.ItemTemplate = new NestedRepeaterItemTemplate(childRepeater);	0
12618678	12618575	Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on	// On worker thread so do our thing! \n void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) \n { \n     // Your background task goes here \n     for (int i = 0; i <= 100; i++) \n     { \n         // Report progress to 'UI' thread \n         backgroundWorker1.ReportProgress(i); \n         // Simulate long task \n         System.Threading.Thread.Sleep(100); \n     } \n } \n // Back on the 'UI' thread so we can update the progress bar - and our label :)\n void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) \n { \n     // The progress percentage is a property of e \n     progressBar1.Value = e.ProgressPercentage; \n     label1.Text = String.Format("Trade{0}",e.ProgressPercentage);\n }	0
24777348	24763079	Datagridview Sends Text Instead of Value to Update for Combobox	DataGridViewComboBoxColumn cb = ((DataGridViewComboBoxColumn)dataGridView1.Columns[2]);\ncb.DataSource = dataSet1.Lookup;\ncb.ValueMember = "Id";\ncb.DisplayMember = "Name";	0
14237303	14235730	Passing the variable through delegate with ref parameter	public delegate void DGraphInit(ref DataMedia media);\n        ...\n        if (obj_mdata.state == GraphState.Running)\n        {\n            object[] data = { obj_mdata };\n            DGraphInit delegate2call = new DGraphInit(GraphInit);\n            this.Dispatcher.Invoke(delegate2call, data);\n        }	0
9377207	9377138	Make a class dependency appear in interface without it being a property	public abstract class AMyClass\n{\n  protected ITimer MyTimer;\n\n  public AMyClass(ITimer timer)\n  {\n    MyTimer = timer;\n  }\n\n  public abstract void DoSomething();\n}\n\npublic class MyClass : AMyClass\n{\n  public override void DoSomething()\n  {\n\n  }\n}	0
7536257	7536204	How to remove an item from listbox with datasource set, using string in C#	BindingList<USState> USStates;\n    public Form1()\n    {\n        InitializeComponent();\n\n        USStates = new BindingList<USState>();\n        USStates.Add(new USState("Alabama", "AL"));\n        USStates.Add(new USState("Washington", "WA"));\n        USStates.Add(new USState("West Virginia", "WV"));\n        USStates.Add(new USState("Wisconsin", "WI"));\n        USStates.Add(new USState("Wyoming", "WY"));\n\n        listBox1.DataSource = USStates;\n        listBox1.DisplayMember = "LongName";\n        listBox1.ValueMember = "ShortName";\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        var removeStates = (from state in USStates\n                            where state.ShortName == "AL"\n                            select state).ToList();\n        removeStates.ForEach( state => USStates.Remove(state) );\n    }	0
27358412	27348387	Button color totally transparent	button1.FlatStyle = FlatStyle.Flat;\nbutton1.FlatAppearance.BorderSize = 0;\nbutton1.FlatAppearance.BorderColor = //Set your Background color here	0
4215790	4215686	Changing Margin/Padding of ButtonText	ControlPaint.DrawButton(...)	0
7856864	7748838	How to detect changes of bindingsource bound to entity?	bool changesMade = context.\n                   ObjectStateManager.\n                   GetObjectStateEntries(EntityState.Added | \n                                         EntityState.Deleted | \n                                         EntityState.Modified\n                                        ).Any();	0
15974578	15960725	Add rows to dataTable to fill when it needs	//create you context\nYourContext dbContext = new YourContext();\n\nString[] firstCategory = dbContext.Categories.Where(x => x.categoryType == "YourFirstCategoryType").ToArray();\nString[] secondCategory = dbContext.Categories.Where(x => x.categoryType == "YourSecondCategoryType").ToArray();\n\nDataTable dt = new DataTable();\ndt.Columns.Add("Category1");\ndt.Columns.Add("Category2");\ndt.Columns.Add("Total");\n\nforeach(var c1 in firstCategory)\n   foreach(var c2 in firstCategory)\n   {\n      //create a new row object \n      DataRow R = dt.NewRow();\n\n      //set value to the colums\n      R[0] = c1;\n      R[1] = c2;\n      R[2] = GetTotal(c1,c2);//GetTotal is some function that query database and returns total when you have c1 and c2 parameter, you should check is this combination doesn't exist you returns 0\n      dt.Rows.Add(R);\n   }	0
9875995	9875946	How do I limit the number of records shown in an XML feed in asp.net?	xPathRepeater.DataSource = x.Data.Take(4);\nxPathRepeater.DataBind();	0
23464814	23464775	Switching to a different controller based upon a condition	return RedirectToAction("Main", "Admin", new { name = username });	0
25797928	25797622	String Array, increase chances of a certain string being picked?	public class NameOption\n{\n     public string Name { get; set; }\n     public int Weight { get; set; }\n\n     public NameOption(string name, int weight)\n     {\n         Name = name;\n         Weight = weight;\n     }\n}\n\n// Will need the System.Linq namespace declared in order to use the LINQ statements\npublic string PickName()\n{\n    var nameOptions = new List<NameOption> \n                {\n                    new NameOption("Bob",5),\n                    new NameOption("John", 1),\n                    etc...\n                };\n    // FYI - following won't work if Weight was a negative value or 0.\n    var namesToPickFrom = new string[nameOptions.Sum(x => x.Weight)];\n    var nameIndex = 0;\n    foreach (var option in nameOptions)\n    {\n       for (var i = 0; i < option.Weight; i++)\n           namesToPickFrom[nameIndex++] = option.Name;\n    }\n    var random = new Random();\n    return namesToPickFrom[random.Next(0, namesToPickFrom.Length-1)];\n}	0
24644297	24644177	Converting Data in a C# List from one type to another.	var newData =\n    formData.GroupBy(g1 => g1.CustomerId)\n        .Select(\n            s1 =>\n                new CustomerDetails\n                {\n                    CustomerId = s1.Key.ToString(),\n                    Fields =\n                        s1.Select(s2 => new FormField {\n                                FieldId = s2.FieldId, \n                                FieldValue = s2.FieldValue})\n                            .ToArray()\n                });	0
2805831	2805775	DateTimePicker control, how to set time?	DateTimePicker1.Value = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 5, 30, 0 )	0
7409849	7170677	Using Html Agility Pack to Parse WebResponse	var thingie = document.Load(reader2.ReadToEnd());\n       var collection = thingie.DocumentNode.SelectNode("//etc");	0
6467125	6467112	Use Func<> type to assign/change variables	string s = someIEnumerable.Aggregate((acc, next) => acc + next);	0
19698263	19698081	RichTextBox getting literal text	StreamWriter sw = File.CreateText(currentFile);\nfor (int i = 0; i < richTextBox1.Lines.Length; i++)\n{\n    sw.WriteLine(richTextBox1.Lines[i]);\n}\nsw.Flush();\nsw.Close();	0
6600437	6599501	Validation strategies	public interface IValidate<T>\n{\n    IEnumerable<ValidationError> GetErrors(T instance, string path);\n}\n\npublic sealed class InvariantEntityValidator : IValidate<Entity>\n{\n    public IEnumerable<ValidationError> GetErrors(Entity entity, string path)\n    {\n        //Do simple (invariant) validation...\n    }\n}\n\npublic sealed class ComplexEntityValidator : IValidate<Entity>\n{\n    public IEnumerable<ValidationError> GetErrors(Entity entity, string path)\n    {\n        var validator = new InvariantEntityValidator();\n        foreach (var error in validator.GetErrors(entity, path))\n            yield return error;\n\n        //Do additional validation for this complex case\n    }\n}	0
20375466	20375437	Convert string to int for sum in linq	int? sum = q.Sum(g => Int32.Parse(g.requestAmount));	0
22408595	22210299	add username in mutualcertificate ws-security header wcf	using (new OperationContextScope(test.InnerChannel))\n{\n    // Add a SOAP Header to an outgoing request\n    //can't send username using mutualcertificate instead of using that way\n    //can be better : see http://blogs.msdn.com/b/wsdevsol/archive/2014/02/07/adding-custom-messageheader-and-http-header-to-a-wcf-method-call.aspx\n    MessageHeader aMessageHeader = MessageHeader.CreateHeader("UsernameToken", "http://tempuri.org", "TOTOTO");\n    OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);\n\n    getGreeting test2 = new getGreeting();\n    MessageBox.Show(test.getGreeting(test2).greeting);\n}	0
28605166	28604582	How to get values of DataGridView.Rows.Columns from Form 2 to Form 1	Form2 f2 = new Form2();\nForm2.Show();\nForm2.Hide();\n\nForm2 f = Application.OpenForms.OfType<Form2>().ElementAt<Form2>(0); //Get current open Form2\nDataGridView data = f.qualitySetupDataGridView;\nMessageBox.Show(data.Rows[0].Cells[1].Value.ToString());	0
23673843	23673806	Client side deserialise into array serialised dictionary<string,string> data	var arr_from_json = JSON.parse( json_string );	0
11501259	11499940	Set dynamic ConnectionString Entity Framework	protected void EntityDataSource1_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)\n    {\n        var dp=new DBContext();\n        e.Context = dp;\n    }	0
12504233	12504123	How to correctly use the Contains method on an ArrayList of controls?	object[] items = al.ToArray();\n\nbool result = items.Any(c => c.Id == ctrl.Id );\n\nif ( !result )\n{\n   al.Add(ctrl);\n   Session["MyControls"] = al;\n}	0
28431618	28431313	Need to create a new table from existing table	DECLARE @oldTableName nvarchar(50)\nDECLARE @newStagingTableName nvarchar(50)\n\nSET @oldTableName='OldTableName'\nSET @newStagingTableName ='NewTableName'\n\nDECLARE @sqlquery nvarchar(100) = 'SELECT * INTO ' + @newStagingTableName + ' FROM ' + @oldTableName\nexec(@sqlquery)	0
5928603	5928532	Using a timer to display text for 3 seconds?	public partial class Form1 : Form\n{\n    //Create the timer\n    System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();\n\n    public Form1()\n    {\n        InitializeComponent();\n        //Set the timer tick event\n        myTimer.Tick += new System.EventHandler(myTimer_Tick);\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        //Set the timer tick interval time in milliseconds\n        myTimer.Interval = 1000;\n        //Start timer\n        myTimer.Start();\n    }\n\n    //Timer tick event handler\n    private void myTimer_Tick(object sender, System.EventArgs e)\n    {\n        this.label1.Text = "Successful";\n        //Stop the timer - if required\n        myTimer.Stop();\n    }\n}	0
11672460	11637208	simulating mouse click on the warcraft3 button using win api	IntPtr parentWindow = (IntPtr)WinApi.FindWindow("Warcraft III", "Warcraft III");\n        int X = 770;\n        int Y = 127;\n        Point temp = new Point(X, Y);\n        IntPtr lParam = (IntPtr)((temp.Y << 16) | temp.X);\n        IntPtr wParam = IntPtr.Zero;\n        WinApi.PostMessage(parentWindow, WM_LBUTTONDOWN, (IntPtr)MK_LBUTTON, lParam);\n        WinApi.PostMessage(parentWindow, WM_LBUTTONUP, wParam, lParam);	0
13598515	13582873	Storing values from TextBox in GridView to DataBase?	protected void Button1_Click(object sender, EventArgs e)\n{\nGridView1.Visible = true;\nDataTable dt = new DataTable();\nDataRow row = dt.NewRow();\nfor (int i = 0; i < GridView1.Rows.Count; i++)\n{\n   ## add below code ##\n    TextBox txtUsrId=(TextBox)GridView1.Rows[i].FindControl("Your textbox id");\n    string UserID = txtUsrId.Text;\n\n    string q="insert into details (name) values('"+UserID+"')";\n\n    SqlCommand cmd = new SqlCommand(q, con);\n    SqlDataAdapter da = new SqlDataAdapter(cmd);\n    da.Fill(dt);\n}	0
8534930	8534701	String.Split cut separator	Regex regEx = new Regex(@"((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)");\nMatch match= regEx.Match("http://www.domain.com http://www.domain1.com");\n\nIList<string> values = new List<string>();\nwhile (match.Success)\n{\n     values.Add(match.Value);\n     match = match.NextMatch();\n}	0
20769987	20769281	Datagrid horizontal scroll automatically changes when keydown event happens	if (mainDataGrid.Items.Count > 0)\n        {\n            var border = VisualTreeHelper.GetChild(mainDataGrid, 0) as Decorator;\n            if (border != null)\n            {\n                var scroll = border.Child as ScrollViewer;\n                if (scroll != null) scroll.ScrollToEnd();\n            }\n        }	0
9103437	9103387	Casting items of a collection with code generation	return Enumerable.ToList<Potato>(Enumerable.Cast<Potato>(_proxyPotatoes));	0
12846416	12846380	Retrieving Only File Name from a Directory	using System.IO;\n\n...\n\nprivate void button1_Click(object sender, EventArgs e) \n{ \n    string[] filePaths = Directory.GetFiles(@"d:\Images\", "*.png"); \n    foreach (string img in filePaths) \n    { \n        listBox1.Items.Add(Path.GetFileName(img)); \n    } \n}	0
3553687	3553635	linq to XML as a gridview datasource	var query = from result in xml.Descendants("customer")\nselect new { email = result.Element("email").Value };	0
25597549	25482588	How do timers in a windows service behave when the system is asleep?	static int counter = 0;\nstatic System.Timers.Timer my_timer;\n\nvoid Main()\n{\n    // Set up a timer to trigger every minute.\n    my_timer = new System.Timers.Timer();\n\n    DateTime now = DateTime.Now;\n    my_timer.Interval = (60 - now.Second) * 1000; // Fire at beginning of minute\n    string.Format("First tick in {0} seconds", my_timer.Interval/1000).Dump();\n\n    my_timer.Elapsed += OnTimer;\n    my_timer.Start();\n\n    while (counter < 5) {    // sleep away until 5 ticks happen\n        Thread.Sleep(5000);\n    }\n\n    // stop timer and say goodbye\n    my_timer.Stop();\n    DateTime.Now.Dump("Finished running, shutting down");\n}\n\n// Print time and counter every timer tick\nvoid OnTimer(object sender, System.Timers.ElapsedEventArgs args)\n{\n    if (my_timer.Interval != 60000) // set to one minute after first time\n        my_timer.Interval = 60000; \n\n    DateTime.Now.ToString("HH:mm:ss.fff").Dump("On Timer fired:");\n    (counter++).Dump("Static counter :");\n}	0
9304025	9303919	pack empty directory with SharpZipLib	FastZip fastZip = new FastZip();\n\n fastZip.CreateEmptyDirectories = true;\n // Include all files by recursing through the directory structure\n bool recurse = true; \n // Dont filter any files at all \n string filter = null;\n fastZip.CreateZip("fileName.zip", @"C:\SourceDirectory", recurse, filter);	0
16990102	16989797	Get value of Excel Cell still being edited	public bool IsInEditMode()\n{\n    const int menuItemType = 1;\n    const int newMenuId = 18;\n\n    CommandBarControl newMenu =\n        Application.CommandBars["Worksheet Menu Bar"].FindControl(menuItemType, newMenuId, Type.Missing, Type.Missing, true);\n\n    return newMenu != null && !newMenu.Enabled;\n}	0
12852575	12852529	Verify node exists before getting its value	XElement c = xElem.Element("c");\nif(null != c)\n{\n   // do something with c because it exists, like...\n   string cValue = c.Value;\n}	0
19710657	19709870	display details using entity framework	private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        var comboBox = sender as ComboBox;\n        if (comboBox != null)\n        {\n            var item = comboBox.SelectedItem as EntityType;\n            //EntityType == the table you are loading into combobox (I guess it supposed to be UserProfile)\n            if (item != null)\n            {\n                txtFirst.Text = item.First.ToString();\n                txtSecond.Text = item.Last.ToString();\n            }\n        }\n    }	0
23317594	23317570	Not entering data into table	db.ViewWorkout.Add(new ConfirmedWorkoutModel() { WorkoutId = Id,  UsersName = User.Identity.Name});\n    db.SaveChanges();\n    return View(db.ViewWorkout.ToList());	0
789447	789438	Getting rid of spaces in a string	String.Replace(" ", "");	0
11669320	11669275	Casting int to double and rounding off to last whole number	whole = (int)Math.Floor(decimal / 1.5);	0
23173716	23173600	Reading numbers from text file and seperating white spaces	string [] numbers = file.ReadLine().Split(new char[]{' '},\n                                       StringSplitOptions.RemoveEmptyEntries);	0
14536161	14535934	Autocopy user selected text in MS word	ActiveDocument.ActiveWindow.Selection.Copy	0
10262225	10261674	Entity framework - select by multiple conditions in same column - Many to Many	foreach(int value in values)\n{    \n      int tmpValue = value;\n      orders = orders.Where(x => (from oi in kontextdbs.order_item\n                                 join i in kontextdbs.items on oi.item_id equals i.id\n                                 where x.id == oi.order_id\n                                 select i).Any(y => y.price == tmpValue));    \n}	0
12531402	12531311	How to convert an array to a double so big array?	string[] wantThatArray = infos\n    .SelectMany(f => new[] {f.Label, f.Value})\n    .ToArray();	0
3083554	3083529	convert string[] to int[]	var values = new string[] { "1", "2", "3" };\nvalues.Select(x => Int32.Parse(x)).ToArray();	0
13568679	13514439	Can I use Linfu dynamic proxy to proxy an interface with generic parameters?	Type myGenericParam1 = myParam1.GetType();\n        Type myGenericParam2 = myParam2.GetType();\n        Type myGenericInterfaceType = typeof(IMyInterface<,>);\n        Type myActualInterfaceType = myGenericInterfaceType.MakeGenericType(myGenericParam1, myGenericParam2);\n        var proxyObjectContainer = typeof(MyProxyFactory).GetMethod("CreateProxy", new Type[] { }).MakeGenericMethod(new[] { myActualInterfaceType }).Invoke(null, new object[] { });\n\n        var proxyObject = proxyObjectContainer.GetType().GetProperty("Proxy").GetValue(proxyObjectContainer, null);	0
13709389	13709088	How can I display animated text in C#	Graphics g = this.CreateGraphics();\ng.DrawString("Game Won!", DefaultFont, Brushes.Red, x,y);	0
1154883	1154879	c# Fastest way to randomly index into an array	Random random = new Random();\nint randomNumber = random.Next(0, vals.Length);\nreturn vals[randomNumber];	0
18852643	18852166	How to return an empty ReadOnlyCollection	private IList<PName> _property = new IList<PName>();\npublic ReadOnlyCollection<PName> Property\n{\n    get\n    {\n        return _property\n    }\n}	0
9286386	9286269	Javascript Queue function how to convert to c#	var worker = new Action<IEnumerable<string>>(collection =>\n{\n    Console.WriteLine(string.Join(" ", collection));\n});\n\nvar args = new List<string>();\nvar timer = new Timer(state =>\n{\n    worker(args);\n    //Reset args\n    args.Clear();\n});\n\nvar queueWorkRunOnce = new Action<string>(arg =>\n{\n    args.Add(arg);\n    timer.Change(/*Delay in ms*/ 1000, Timeout.Infinite);\n});\n\nqueueWorkRunOnce("Hi");\n//Some other stuff\nqueueWorkRunOnce("There");\n//Some other stuff\nqueueWorkRunOnce("Hello");\nqueueWorkRunOnce("World");\n\nConsole.ReadKey();	0
14136420	14136002	Send Password / String to External Console Application C#	Process myProcess = new Process();\n\n     myProcess.StartInfo.FileName = "someconsoleapp.exe";\n     myProcess.StartInfo.UseShellExecute = false;\n     myProcess.StartInfo.RedirectStandardInput = true;\n     myProcess.StartInfo.RedirectStandardOutput = true;\n     myProcess.StartInfo.ErrorDialog = false;\n\n     myProcess.Start();\n\n     StreamWriter stdInputWriter  = myProcess.StandardInput;\n     StreamReader stdOutputReader  = myProcess.StandardOutput;\n\n     stdInputWriter.WriteLine(password);\n\n     var op = stdOutputReader.ReadLine();\n\n     // close this - sending EOF to the console application - hopefully well written\n     // to handle this properly.\n     stdInputWriter.Close();\n\n\n     // Wait for the process to finish.\n     myProcess.WaitForExit();\n     myProcess.Close();	0
21185341	21185123	C# DataTable edit cell in specific row with Linq	DataRow dr = table.Select("ID=myId").FirstOrDefault(); \ndr["Value"] = "your value";	0
15931975	15931639	Reading a file one byte at a time in reverse order	string fileName = Console.ReadLine();\n    using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))\n    {\n        byte[] output = new byte[file.Length]; // reversed file \n\n        // read the file backwards using SeekOrigin.Current\n        //\n        long offset;\n        file.Seek(0, SeekOrigin.End);        \n        for (offset = 0; offset < fs.Length; offset++)\n        {\n           file.Seek(-1, SeekOrigin.Current);\n           output[offset] = (byte)file.ReadByte();\n           file.Seek(-1, SeekOrigin.Current);\n        }\n\n        // write entire reversed file array to new file\n        //\n        File.WriteAllBytes("newsFile.txt", output);\n    }	0
19415345	19415209	Rotate a number 180 degrees and get the same number	map['0'] = '0';\nmap['1'] = '1';\nmap['2'] = '2';\nmap['5'] = '5';\nmap['6'] = '9';\nmap['8'] = '8';\nmap['9'] = '6';\n\nfor each position i in input_string :\n    if map index exists for input_string[i] :\n        rotated_string[i] = map[input_string[i]]\n    else\n        exit for\n\nrotated_string = reverse(rotated_string)\n\nif input_string = rotated_string :\n    has_rotational_symmetry = true\nelse\n    has_rotational_symmetry = false	0
21148215	21148175	Compare two List<string> and print the duplicates	List<string> duplicates = list1.Intersect(list2).ToList();	0
1636064	1635821	"Intelligent" cast of double to two differently formatted strings?	public static string DoubleToStringFormat(double dval)\n{\n    long lval = (long)dval;\n    if ((double)lval == dval)\n    {\n        // has no decimals: format as integer\n        return dval.ToString("#.", CultureInfo.InvariantCulture);\n    }\n    else\n    {\n        // has decimals: keep them all\n        return dval.ToString("0.##################", CultureInfo.InvariantCulture);\n    }\n}	0
28521363	28521338	How to disable option of typing user values to Windows Forms Combobox?	comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;	0
16944475	16940185	c# WCF HTTP rest client with WebHttpBinding/Behavior for POSTing RAW data in request body	public class HttpXmlClient : ClientBase<IHttpXmlClient>, IHttpXmlClient\n{\n  public void Send(Stream data)\n  {\n    using (new OperationContextScope((IContextChannel) Channel))\n    {\n      var request = WebOperationContext.Current.OutgoingRequest;\n      request.ContentType = "text/xml;charset=UTF-8";\n      Channel.Send(data);\n    }\n  }\n}	0
19211688	19211597	Add comma between values by using Linq	var result = string.Join(",", item.Split(new string[] { "2|" }, StringSplitOptions.RemoveEmptyEntries));	0
9166691	9166649	How to ignore a specific with a LINQ where clause?	PubDate = (string)(item.Element("created") ?? ""),\nIsbn = (string)(item.Element("isbn") ?? ""),\nSummary = (string)(item.Element("review") ?? "")	0
14980107	14852589	To get exact position in unity 3d	floorPosition = new Vector3(0.0f,0.5f,-8.250f);\n    transform.position = floorPosition;	0
31887171	31868163	C# HttpClient PostAsync with JSON parameter for VSO git API	StringContent stringContent = new StringContent(content, Encoding.UTF8, "application/json");	0
967610	967516	Best way to determine if a domain name would be a valid in a "hosts" file?	private static bool IsValidDomainName(string name)\n{\n    return Uri.CheckHostName(name) != UriHostNameType.Unknown;\n}	0
27524096	27484276	Scaffold migration with context key change	public class MyMigrationConfiguration : DbMigrationsConfiguration<MyMigrationContext>\n{\n    public MyMigrationConfiguration ()\n    {\n        AutomaticMigrationsEnabled = false;\n        AutomaticMigrationDataLossAllowed = false;\n        MigrationsNamespace = "My.Migrations.Assembly";\n        MigrationsDirectory = "My/Migrations/Directory";\n        ContextKey = "MyContexKey"; // You MUST set this for every migration context\n    }\n}	0
4630091	4620609	How do I manage threads in a C# web app?	//code behind\nprotected void butRefreshData_Click(object sender, EventArgs e)\n{\n    Thread t = new Thread(new ThreadStart(DataRepopulater.DataRepopulater.RepopulateDatabase));\n    t.Start();       \n}\n\n//DataRepopulater.cs\nnamespace DataRepopulater\n{\n    public static class DataRepopulater\n    {\n    private static string myLock = "My Lock";\n    public static void RepopulateDatabase()\n    {\n        if(Monitor.TryEnter(myLock))\n        {\n            DoWork();\n            Monitor.Exit(myLock);\n        }\n    }\n}	0
10531951	10531894	How to Clear Adobe reader history programatically using C#	[-HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\10.0\AVGeneral\cRecentFiles]\n\n\nvar registrykeyHKLM = Registry.CurrentUser;\nstring keyPath = @"Software\Adobe\Acrobat Reader\10.0\AVGeneral\cRecentFiles";\nregistrykeyHKLM.DeleteValue(keyPath);\nregistrykeyHKLM.Close();	0
17156146	17155440	struct to byte array [SafeArrayTypeMismatchException]	byte[] getBytes<T>(T str) where T:struct\n{\n    int size = Marshal.SizeOf(str);\n    byte[] arr = new byte[size];\n    IntPtr ptr = Marshal.AllocHGlobal(size);\n    Marshal.StructureToPtr(str, ptr, true);\n    Marshal.Copy(ptr, arr, 0, size);\n    Marshal.FreeHGlobal(ptr);\n    return arr;\n}	0
12198944	12015487	Uploading string as text file to SkyDrive?	var tmpFile= await ApplicationData.Current.\n                       LocalFolder.CreateFileAsync\n                         ("tmp.txt", CreationCollisionOption.ReplaceExisting);\n\nusing (var writer = new StreamWriter(await tmpFile.OpenStreamForWriteAsync()))\n{\n    await writer.WriteAsync("File content");\n}\nvar operationResult = \n      await client.BackgroundUploadAsync(folderId, tmpFile.Name, tmpFile,\n                                          OverwriteOption.Overwrite);	0
33089617	33089360	Index a column based on user input in C#	var rseult= this.dataGridView1.Rows.Cast<DataGridViewRow>()\n                .Where(r=>(float)r.Cells[0].Value==float.Parse(textBox1.Text))\n                .Select(r=>(float)r.Cells[1].Value)\n                .FirstOrDefault();	0
9298764	9298708	Combine 5 List<object> into one List<object>	var result = ObjectList1.Concat(ObjectList2).Concat(ObjectList3).\n                         Concat(ObjectList4).Concat(ObjectList5).ToList()	0
21508613	21508490	Copy from clipboard to form in VB	WebBrowser1.Document.GetElementById("input-xxxxxxx").SetAttribute("value", TextBox1.Text)	0
15110846	15109773	How to set position of image in silverlight	Image rs = (Image)sender;\nGeneralTransform gt = rs.TransformToVisual(ContentPanel);\nPoint offset = gt.Transform(new Point(0, 0));\n\n//create a translate transform \nTranslateTransform tt = new TranslateTransform();\n\n//apply the required offset\ntt.X = offset.X;\ntt.Y = offset.Y;\n\n//apply the transform to the image\nrs.RenderTransform = tt;\n\ndouble controlTop = offset.Y;\ndouble controlLeft = offset.X;\ntb.Text = Convert.ToInt16(controlLeft / 40).ToString();\ntb2.Text = Convert.ToInt16(controlTop / 40).ToString();\ndouble newLeft = Convert.ToInt16(controlLeft / 40) * 40;\ndouble newTop = Convert.ToInt16(controlTop / 40) * 40;	0
14497576	14497537	Check if some decimal values are equal	if (ProgramVariables.MSR_AR_System == ProgramVariables.MSR_AR_EB_1 \n && ProgramVariables.MSR_AR_EB_1 == ProgramVariables.MSR_AR_EB_2 \n && ProgramVariables.MSR_AR_EB_2 == ProgramVariables.MSR_AR_EB_3)	0
18079978	18077262	How to retrieve HTTP header information from a C# RESTful Service Method	public string MethodRequiringAuthorization()\n    {\n        HttpContext httpContext = HttpContext.Current;\n        NameValueCollection headerList = httpContext.Request.Headers;\n        var authorizationField = headerList.Get("Authorization");            \n        return "{Message" + ":" + "You-accessed-this-message-with-authorization" + "}";\n    }	0
24681487	24680913	How do I upload csv file from FTP directly which will be as input in c#?	FTPHelper FTP = new FTPHelper();\nFTP.DownloadloadFile("TestFTP.com etc etc etc......);	0
34470570	34468599	How to select values in for loop?	string[] proxy_l = prx.FindElementById("proxylisttable").Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);\n\nvar proxyInfos = proxy_l\n    .Where(l => l.Contains(" US "))\n    .Select(l => l.Split(' '))\n    .Select(tokens => new\n    {\n        IP = tokens[0],\n        Port = tokens[1]\n    })\n    .ToList();\n\nusing (MySqlConnection cn = new MySqlConnection())\n{\n    foreach (var proxyInfo in proxyInfos) {\n        using (MySqlCommand cm = cn.CreateCommand())\n        {\n            cm.CommandText = "insert into proxy_list(ip, port) values(@ip, @port);";\n            cm.Parameters.AddWithValue("@ip", proxyInfo.IP);\n            cm.Parameters.AddWithValue("@port", proxyInfo.Port);\n            cm.ExecuteNonQuery();\n        }\n    }\n}	0
20194746	20194668	Inserting data from Windows form results in duplication into SQL Server database	cmd.ExecuteNonQuery();\nreader = cmd.ExecuteReader();	0
180332	180330	Obtain file path of C# save dialog box	SaveFileDialog saveFileDialog1 = new SaveFileDialog(); \nsaveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); \nsaveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ; \nsaveFileDialog1.FilterIndex = 1; \n\nif(saveFileDialog1.ShowDialog() == DialogResult.OK) \n{ \n    Console.WriteLine(saveFileDialog1.FileName);//Do what you want here\n}	0
6670664	6670525	Deciding what string to display depending on width of control	string EllipsisString = "..."; // you could also just set this as the unicode ellipsis char if that displays properly\n\nprivate string FitText(string s)\n{\n    bool WidthFound = true;\n    string TestString = s;\n    string StringToReturn = s;\n\n    int width = (TextRenderer.MeasureText(s, titleFont)).Width;\n\n    if (width > mailList.Width)\n    {\n        WidthFound = false;\n\n        for (int i=1; i < s.Length; ++i)\n        {\n           TestString = s.Substring(0, s.Length - i) + EllipsisString;\n           width = (TextRenderer.MeasureText(TestString, titleFont)).Width;\n\n           if (width <= mailList.Width)\n           {\n              StringToReturn = TestString;\n              WidthFound = true;\n              break;\n           }\n        }\n    }\n\n    if (WidthFound)\n        return StringToReturn;\n    else\n        return EllipsisString;\n}	0
3748656	3475225	How to make sure a batch file is executed properly through a CMD from a c# applicaiton?	System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(filename);\n                    psi.RedirectStandardOutput = true;\n                    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n                    psi.UseShellExecute = false;\n                    System.Diagnostics.Process listFiles;\n                    listFiles = System.Diagnostics.Process.Start(psi);\n                    System.IO.StreamReader myOutput = listFiles.StandardOutput;\n                    listFiles.WaitForExit(2000);\n                    if (listFiles.HasExited)\n                    {\n                        string output = myOutput.ReadToEnd();\n                        MessageBox.Show(output);\n                    }	0
17119682	17119643	calling application variable from asp.net class and webservice	If HttpContext.Current.Application("sesame") Is Nothing Then\n   HttpContext.Current.Application("sesame") = password\nEnd If	0
2664012	2663965	Is there a way to specify a custom dependency property's default binding mode and update trigger?	new FrameworkPropertyMetadata\n{\n    BindsTwoWayByDefault = true,\n    DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged\n}	0
18049665	18049573	Aligning text in a c# list control	output_text = String.Format("Total pay on day {0} is {1,10:c}", day, total_running_pay)	0
5143527	5143385	Saving DateTime with WebMatrix and Razor	DateTime? dtForecastComplete = null;	0
4166994	4161246	Get domain name	System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;	0
23117227	23116995	object to deserialize has a C# keyword	[DataContract(Name = "@event")]	0
32667437	32667277	c# - deciding between using a single interface vs two similar ones	public interface IAnalyzer\n{\n    AnalysisResult Analyze(string filePath);\n}\n\npublic static class AnalyzerExtensions\n{\n    public static IEnumerable<FileBatch> ProcessBatch(this IAnalyzer analyzer, IEnumerable<FileBatch> batches)\n    {\n        foreach (var batch in batches)\n        {\n            batch.Result = analyzer.Analyze(batch.Path);\n            yield return batch;\n        }\n    }\n}	0
8721302	8721210	Finding a repeating pattern in a given string	string str="&%       68 kg      K    A&%       23 kg      K    A&%      174 kg";\n string []ar=Regex.Split(str,@"[^0-9]").Where(p=> p!=string.Empty).ToArray();	0
3975922	3975887	Reading large text files to datagridview a filtering	public IEnumerable<string> ReadFile(int page, int linesPerPage, out totalLines)\n{\n    ...\n}	0
11097452	11097349	C# - how to check if a process was successfully started	Process B= new Process();\n\n        try\n        {\n            B.StartInfo.UseShellExecute = false;\n            B.StartInfo.FileName = "C:\\B.exe";\n            B.StartInfo.CreateNoWindow = true;\n            if (B.Start())\n            {\n              // Kill process A \n            }\n            else\n            {\n               // Handle incorrect start of process B and do NOT stop A\n            }\n\n        }\n        catch (Exception e)\n        {\n            // Handle exception and do NOT stop A\n        }	0
4938579	4938300	Adding button column to DataGridView but it won't show	btnDelete.UseColumnTextForButtonValue = true;	0
21416712	21416692	How to convert from a Label to a string using FindControl?	Label myDentistName = (Label)item.FindControl("dentistNameLabel");	0
2665620	2665588	how to do validations when composing object of a class in other class?	public IPAddress userIpAddress;\n// Other fields and properties\n\n\npublic UserCLass(IPAddress ipAddress, .... other fields)\n{\n    userIpAddress = ipAddress; // here validation for IPAddress will be called\n}	0
4359644	4359629	Is there anything wrong with using lambda for winforms event?	// Subscribe lambda as event handler\ncomboBox1.MouseEnter += (a, b) => comboBox1.Focus(); \n\n// Try to unsubscribe a _different_ lambda with identical syntax. \n// The first lambda is still subscribed\ncomboBox1.MouseEnter -= (a, b) => comboBox1.Focus();	0
28258036	28257978	WPF DataGrid calculations	private void UpdateValue()\n{\n    _multiply = GetMultiply();\n    OnPropertyChanged("One");\n    OnPropertyChanged("Two");\n    OnPropertyChanged("Multiply");\n}	0
14671827	14555255	How to get the data from aspnet_Membership, aspnet_Users and aspnet_UsersInRoles in aspnetDB?	public class UsersContext : DbContext\n{\n    public UsersContext()\n        : base("DefaultConnection")  // web.config\n    {\n    }\n\n    public DbSet<UserProfile> UserProfiles { get; set; }\n}\n\n[Table("UserProfile")]\npublic class UserProfile\n{\n    [Key]\n    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]\n    public int UserId { get; set; }\n    public string UserName { get; set; }\n}\n\npublic class UserData\n{\n    private static List<UserProfile> _userList;\n\n    public static List<UserProfile> userList\n    {\n        get\n        {\n            if (_userList == null)\n            {\n                UsersContext db = new UsersContext();\n                _userList = db.UserProfiles.SqlQuery("select * from dbo.UserProfile").ToList();\n            }\n            return _userList;\n        }\n        set\n        {\n            _userList = value;\n        }\n    }\n}	0
10650670	10650595	How to know which file is selected in open dialog in c#	string fileName = OpenFileDialog.Filename;\n\n    if(fileName.EndsWith(".xml"))\n    {\n    //\n    }\n    else if(fileName.EndsWith(".map"))\n    {\n     //\n    }	0
5433454	5433318	How do I allow the EF4 CodeFirst database initializer to run under development, but not run in production	#if LOCALDEBUG\n  //do database stuff\n#endif	0
6764159	6764013	Query a table by using foreign key navigation properties in LINQ with C#	var sessions = _webinarRecordingsDB.WebinarSessions.Where(w => w.SessionSubjects.Any(s => s.ProductLine == productLine));	0
16805249	16805176	Format text to date/time format c#	Time.Text = string.Format("{0}:{1}", (counter / 60), (counter % 60).ToString().PadLeft(2,'0'));	0
21651253	21651108	Converting string to double exception	var s="0.5";\nvar culture = CultureInfo.CurrentCulture.Clone();\nculture.NumberFormat.NumberDecimalSeparator = ".";\nvar b = double.Parse(s, culture);\n\nConsole.WriteLine("double.Parse() - {0}",b);	0
11844749	11844588	How to Download a xml content to a file	return File(Encoding.UTF8.GetBytes(definition), contentType, "somefilename.xml");	0
638468	638325	multi line text box in sharepoint web part	var textBox = new TextBox();\ntextBox.TextMode = TextBoxMode.MultiLine;	0
8766961	8766897	how to exclude null from JSON? (after converting from XML)	jsonText = jsonText.Replace("null", "\"\"");	0
1405065	1405048	How do I decode a URL parameter using C#?	Server.UrlDecode(xxxxxxxx)	0
21193627	21192691	After applying CCITT compression on my Tiff File, it produces an image with a solid black background	System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(800, 1000); \nGraphics g = Graphics.FromImage(bitmap);\n/* Add this */ g.FillRectangle(Brushes.White, new Rectangle(0,0, 800, 1000));\ng.DrawString("Name: " + Name.Text, outputFont, Brushes.Black, new PointF(0, 20));\ng.DrawString("Date Of Birth: " + Date_Of_Birth.Text, outputFont, Brushes.Black, new PointF(0, 40));\ng.DrawString("Address: " + Address.Text, outputFont, Brushes.Black, new PointF(0, 60));\ng.DrawString("City: " + City.Text, outputFont, Brushes.Black, new PointF(0, 80));\ng.DrawString("State: " + State.Text, outputFont, Brushes.Black, new PointF(0, 100));\ng.DrawString("Zip Code: " + Zip_Code.Text, outputFont, Brushes.Black, new PointF(0, 120));\ng.DrawString("Phone: " + Phone.Text, outputFont, Brushes.Black, new PointF(0, 140));\ng.DrawString(" ID: " + ID.Text, outputFont, Brushes.Black, new PointF(0, 160));\nfileName = saveDirectory + id + ".tif";\nbitmap.Save(fileName, ImageFormat.Tiff);	0
29206810	29205746	How to verify that a new tab is opened in a browser with TestComplete using C#	function Test1()\n{\n  var browser = Sys.Browser("firefox");\n  var numOfTabs = browser.FindAllChildren("ObjectType", "Page").toArray().length;\n  var page = browser.ToUrl("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_links_target");\n\n  var pageUrl = page.Url; \n  frame = page.Panel(0).Panel(1).Panel(0).Panel(1).Frame("iframeResult");\n  frame.Link(0).Click();\n\n  if (page.Url != pageUrl)\n    Log.Error("The page's URL has been changed!");\n\n  if (browser.FindAllChildren("ObjectType", "Page").toArray().length == numOfTabs)\n    Log.Error("A new tab has not been opened!");\n}	0
7918016	7917949	C# when trying to add a next button geting negative value error	private int _counter; //It defaults to 0, setting it to 0 is redundant.\n    public int Counter\n    {\n        get { return _counter; }\n        set\n        {\n            if (Equals(_counter, value)) return;\n\n            if (value < 0) return;\n\n            if ((loadedHouses != null) && (value > loadedHouses.Count) return;\n\n            _counter = value;\n\n            GetHouse();\n        }\n    }\n    ...\n\n    private void GetFirst()\n    {\n        Counter = 0;\n    }\n    private void Getprevious()\n    {\n        Counter--;\n    }\n    private void Getnext()\n    {\n        Counter++;\n    }\n    private void Getlast()\n    {\n        //Counter = results.Count(); //WTF? Why results.Count() when results is a string??\n        Counter = ((loadedHouses == null) ? 0 : loadedHouses.Count);\n    }	0
25447283	25430763	Formatting an Excel file for correct date format	foreach(var item in SourceList)\n    {\n        int newYear = Convert.ToInt32(item.Year.ToString().Substring(0,2) + item.Day.ToString());\n        DateTime result = new DateTime(newYear, item.Month, 10);\n        ResultList.Add(result);\n    }	0
5666530	5666413	IPFIX data over UDP to C# - can I decode the data?	The format of the IPFIX Message Header is shown in Figure F.\n\n    0                   1                   2                   3\n    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   |       Version Number          |            Length             |\n   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   |                           Export Time                         |\n   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   |                       Sequence Number                         |\n   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n   |                    Observation Domain ID                      |\n   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+	0
868821	868800	c# to vb conversion object initalization	Dim cp As New CustomerParameters() With { _\n     .FirstName = "C First Name", _\n     .LastName = "C Last Name" _\n}	0
25807153	25807006	sending email in asp.net sends password instead of email	string name=txtfirstname.Text;\n        string fileName = Server.MapPath("~/App_Data/TextFile.txt");\n        string mailBody = File.ReadAllText(fileName);\n        mailBody = mailBody.Replace("##Name##", txtfirstname.Text);\n        mailBody = mailBody.Replace("##Email##", email);\n        mailBody = mailBody.Replace("##Phone##", txtphone.Text);\n        MailMessage myMessage = new MailMessage();\n        myMessage.Subject = "Re: Activate your account for AIS FORUM";\n        myMessage.Body = mailBody;\n        myMessage.From = new MailAddress("abc@gmail.com", "abc@gmail.com");\n        myMessage.To.Add(new MailAddress(txtemail.Text, email));\n        SmtpClient mySmtpClient = new SmtpClient();\n        mySmtpClient.EnableSsl = true;  \n        mySmtpClient.Send(myMessage);	0
10704080	10703942	Listview items text is trucncated and doesn't show it all	ColumnHeader header = new ColumnHeader();\n header.Text = "MyHeader";\n header.Name = "MyColumn1";\n header.Width = listView1.Width //Same Width as Entire List Control\n listView1.Columns.Add(header);	0
15498897	15491088	Windows phone: calling eventhandlers from backgroundagent notify	protected override void OnInvoke(ScheduledTask task)\n{\n   Deployment.Current.Dispatcher.BeginInvoke(() =>\n      {\n          img = new BitmapImage(new Uri(imgLoc, UriKind.Absolute));\n          img.CreateOptions = BitmapCreateOptions.None;\n          img.ImageOpened += img_ImageOpened;\n      });\n}	0
2245708	2245166	How do I populate a listview based on 2 boolean table columns?	if (Request.QueryString["type"]=="theatre")\n    {\n      s="select * from scripts where theatreAndEducation = 1";\n    }\nelse\n    if (Request.QueryString["type"]=="plays")\n    {\n      s = "select * scripts where playsForYoungPeople = 1";\n    }\n    SqlDataSource1.SelectCommand = s;	0
15873571	15873407	Comparing two strings string builder	sb.ToString().Compare(string.Join("",last2Lines.ToArray()))	0
2615242	2615218	How to do a search from a list with non-prefix keywords	var resultSet = products\n\n    // filter products by category\n    .Where(product => product.Category == "strings")\n\n    // filter products by origin\n    .Where(product => product.Origin == "italy")\n\n    // filter products whose name contains a word starting with "guit"\n    .Where(product => (" " + product.Name).Contains(" guit"))\n\n    // limit the result set to the first 30 matching products\n    .Take(30);	0
30206342	30205349	Is it possible to search thru an array of objects in one line without predicates?	var dynamicExpression = "SomeProperty > 100"\narray.Any(n=> EvaluateExpression(dynamicExpression, v));\n\nbool EvaluateExpression(string expression, double value){\n    ...\n}	0
3852797	3850913	Combine two objects into one	public Dictionary<string, string> GetParameters(object data)\n    {\n        if (data == null)\n            return null;\n\n        Dictionary<string, string> parameters = new Dictionary<string, string>();\n        foreach (PropertyInfo property in data.GetType().GetProperties())\n            parameters.Add(property.Name, property.GetValue(data, null).ToString());\n        return parameters;\n    }	0
26736046	26715276	Read File (not string) from Websphere MQ and save in to local drive	MQMessage msg = new MQMessage();\n\n            queue.Get(msg, mqGetMsgOpts);\n            MQGetMessageOptions mqGetNextMsgOpts = new MQGetMessageOptions();\n            mqGetNextMsgOpts.Options = MQC.MQGMO_BROWSE_NEXT;\n            try\n            {\n                while (true)\n                {\n                    string messageText = msg.ReadString(msg.MessageLength);\n                    //Write to File\n                    byte[] byteConent = new byte[msg.MessageLength];\n                    msg.ReadFully(ref byteConent, 0, msg.MessageLength);\n                    File.WriteAllBytes("sample.eff", byteConent);\n                    //\n                    msg = new MQMessage();\n                    queue.Get(msg, mqGetNextMsgOpts);\n                }\n            }\n            catch (MQException ex)\n            {\n                // Handle it\n            }	0
18315331	18314624	Filtering with Let	var records = from t in query\n    let maxversion =\n            (from v in _context.tblTradeSpends\n            where v.Customer == t.Customer\n            && v.LineOfBusiness == t.LineOfBusiness\n            && v.DealYear == t.DealYear\n            select v.VersionDate).Max()\n    where t.PlanType == "Planner" &&\n    t.VersionDate == maxversion\n    select t	0
2061652	2061620	Get SelectedItem from listbox in code behind	// Put the class that you're binding to here...\nMyClass instance = listBoxImages.SelectedItem as MyClass;\nstring url = instance.ImageName; // url is an odd variable name for this...\nbi.UriSource = new Uri(string.Format("images/{0}", url), UriKind.Relative);	0
11488311	11488249	Use querystring variables in MVC controller	string start = Request.QueryString["start"];\n\nstring end = Request.QueryString["end"];	0
29541861	29541791	add a condition to the lambda for each expression in C#	TheToAddresses.Where(address => address.ToLower() != "a@a.com").ToList().ForEach(TA => _message.ToRecipients.Add(TA));	0
958610	958606	Storing string values as constants in the same manner as Enum	public static class SessionKeys\n{\n    public const string Value1 = "Value1";\n    public const string Value2 = "Value2";\n    ...\n}	0
5812775	5812738	How to get the 30th of the month after a given date	var nextMonth = varFinishDate.AddMonths(1);\nvar targetDate = new DateTime(\n    nextMonth.Year,\n    nextMonth.Month,\n    nextMonth.Month == 2 ? 28 : 30);	0
20633918	20633521	Filtering elements of an array	for (int i = 1; i < statsname.Length; i += 2)\n{\n    //only number type stats are added to the comboboxes.\n    if ((statsname[i].ToUpperInvariant()==("TOTALNUMBER")) || ((statsname[i].ToUpperInvariant()==("CURRENTNUMBER"))))\n        comboBox1.Items.Add(statsname[i-1]);\n}	0
13644743	13644366	C# dictionary key as dictionary	Games\n    ChatRooms	0
26138966	26132792	Session Storing Images for Temporary and retrive and store into model	if (model.File != null && model.File.ContentLength > 0)\n        {\n            Byte[] destination1 = new Byte[model.File.ContentLength];\n            model.File.InputStream.Position = 0;\n            model.File.InputStream.Read(destination1, 0, model.File.ContentLength);\n            model.BankSlip = destination1;\n            Session["info.file"]= model.File;//storing session.\n        }\n        else\n        {\n            //retrieving session\n            var myImg1 = Session["info.file"] as HttpPostedFileBase;\n            model.File = myImg1;\n            Byte[] data=new Byte[myImg1.ContentLength];\n            myImg1.InputStream.Position = 0;\n            myImg1.InputStream.Read(data, 0, myImg1.ContentLength);\n            model.BankSlip = data;\n        }\n        }\n        catch (Exception ex)\n        {                   \n            DepositControllerLog.ErrorException("DepositController - LocalBank(Post) - AddAttachment(refreshed) - ", ex);\n        }\n        }	0
9960796	9960753	How to minimize/restore a window in c#	foreach (Process proc in Process.GetProcesses()) \n{ \n    if (proc.MainWindowTitle.Contains(p)) \n    { \n        IntPtr handle = proc.Handle; \n        Program.WINDOWPLACEMENT wp = new Program.WINDOWPLACEMENT(); \n        Program.GetWindowPlacement(handle, ref wp); \n        if ((wp.showCmd & 2) == 2) \n        { \n            wp.showCmd = 9; \n            MessageBox.Show("Restoring"); \n        } \n        else \n        { \n            wp.showCmd = 2; \n            MessageBox.Show("Minimizing"); \n        } \n        wp.length = Marshal.SizeOf(wp); \n        Program.SetWindowPlacement(handle, ref wp); \n        break; \n    } \n}	0
15779395	15779187	Boss Battle State Machine in Unity	private TimeSpan timeToWait = TimeSpan.FromMilliseconds(5000); // 5 seconds\nprivate TimeSpan lastStateCheck;\n\npublic void Update(GameTime gameTime) {\n    if (lastStateCheck + timeToWait < gameTime.TotalGameTime) {\n        // switch states after 5 seconds..\n        /* Switch state code here */\n        lastStateCheck = gameTime.TotalGameTime;\n    }\n}	0
4279362	4275522	Unit Testing a class with a call to a Static class wrapping an HttpContext	StaticClass.ClearSessionState()	0
33087738	33087457	Updating Excel 2003/ 2007 Cell value from C#	sql = "UPDATE [Sheet1$A1:A1]  SET F1='FOO'";	0
33086675	33067585	How to get MapElement tapped type (MapControl) (Windows 10 universal app)	private void MapControl1_MapElementClick(MapControl sender, MapElementClickEventArgs args)\n{\n    foreach (var e in args.MapElements)\n    {\n        if (e is MapPolygon)\n        {\n            var poly = e as MapPolygon;\n            //Is MapPolygon\n        }\n        else if (e is MapPolyline)\n        {\n            var poly = e as MapPolyline;\n            //Is MapPolyline\n        }\n        else if (e is MapIcon)\n        {\n            var icon = e as MapIcon;\n            //Is MapIcon\n        }\n    }\n}	0
12015987	12015792	How to use Model Validation in a Partial View	return View("~/Views/Home/Index.cshtml")	0
29988921	29985069	Take the greater of two nullable values	Nullable.Compare(a, b) > 0? a: b;	0
4663580	4662765	Best method to print using wpf 4	System.Windows.Controls.PrintDialog printDlg = new System.Windows.Controls.PrintDialog();\nif (printDlg.ShowDialog() == true)\n{\n    System.Printing.PrintCapabilities capabilities = \n       printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);\n\n    double scale = Math.Min(\n                     capabilities.PageImageableArea.ExtentWidth / control.ActualWidth, \n                     capabilities.PageImageableArea.ExtentHeight / control.ActualHeight);\n\n    control.LayoutTransform = new System.Windows.Media.ScaleTransform(scale, scale);\n\n    Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, \n                       capabilities.PageImageableArea.ExtentHeight);\n\n    control.Measure(sz);\n    control.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, \n       capabilities.PageImageableArea.OriginHeight), sz));\n\n    printDlg.PrintVisual(control, "My App");\n}	0
3836713	3834647	Cannot get values in OnInit event	public void OnInit(object sender, EventArgs e)\n{\n    GatherForms();\n    CreateWizardForm(); // creates a wizard and adds controls it will need\n}\n\nprivate void Checkbox_Checked(object sender, EventArgs e)\n{\n    var checkBox = (CheckBox)sender;\n    // append checkBox.SelectedValue to session state object of checkboxes\n}\n\nprotected override void OnPreRender(object sender, EventArgs e)\n{\n    if (/* Session checkboxes contain values */)\n    {\n        this.WizardForm.Visible = true;\n        this.CheckboxList.Visible = false;\n    }\n}	0
18469499	18432173	Auto mapper mapping of nested object within a collection	Mapper.CreateMap<IDataReader, Question>()\n            .ForMember(question => question.PostedBy,\n                       o =>\n                       o.MapFrom(\n                           reader =>\n                           new User\n                               {\n                                   Username = reader["Firstname"].ToString(),\n                                   EmailAddress = reader["Lastname"].ToString()\n                               }));\n        Mapper.AssertConfigurationIsValid();\n\n        IEnumerable<Question> mappedQuestions = Mapper.Map<IDataReader, IEnumerable<Question>>(reader);	0
26725195	26725060	Hashtable new entries permanent loop and finding key with lowest value	var minValue = Int32.MaxValue;\nstring minKey = null;\nforeach (DictionaryEntry item in ht)\n{\n    if ((int) item.Value < minValue)\n    {\n        minValue = (int) item.Value;\n        minKey = (string) item.Key;\n    }\n}	0
6096915	6095878	crystal reports using parameters	protected void Btn_DisplayReport(object sender, EventArgs e)\n{\n   int idno = Convert.ToInt32(DropDownList1.SelectedValue);\n   report.SetParameterValue(0, idno);\n   CrystalReportViewer1.ReportSource = report;\n}	0
16238158	16237844	Connection of SQLServer from C#	string cmdText = "INSERT INTO Customers (Name, Address) VALUES (@name, @address)"\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n    SqlCommand command = new SqlCommand(queryString, connection);\n    command.Parameters.AddWithValue("@name", "Steve");\n    command.Parameters.AddWithValue("@address", "Stackoverflow Street, 42");\n    command.Connection.Open();\n    command.ExecuteNonQuery();\n}	0
7482073	7481964	How to convert IEnumerable<string> to one comma separated string?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass C\n{\n    public static void Main()\n    {\n        var a = new []{\n            "First", "Second", "Third"\n        };\n\n        System.Console.Write(string.Join(",", a));\n\n    }\n}	0
7487891	7162909	Delaying Window for Splash Screen	Thread.Sleep(int miliSeconds)	0
5035135	5035035	Storing related timed-based data with variable logging frequencies	Channel, Timestamp, Measurement	0
28227975	28211429	Programmatically read MS DTC Transaction Component Services Timeout in C#	var catalog = new COMAdmin.COMAdminCatalog();\ncatalog.Connect(System.Environment.MachineName);\nvar coll = catalog.GetCollection("LocalComputer");\ncoll.Populate();\nvar timout = coll.Item[0].Value["TransactionTimeout"];	0
21156822	21155001	how to join multiple tables in linq using flag field	var Query = (from invoice in _godownEntity.TblInvoices\n             join client in _godownEntity.TblClients on invoice.ReceiverCode equals client.ClientCode\n             join customer in _godownEntity.TblCustomers on invoice.**X** equals customer.**Y**\n             select *WHAT U WANT*	0
5650695	5650317	ListBox and WinForms application	Dictionary<string,From2> myForm2s = new Dictionary<string,Form2>();\n\npublic void Send(string body, string name)\n{\n   Form2 frm = null;\n   if(!myForm2s.tryGetValue(name,out frm))\n   {\n      frm = new Form2(body);\n      myForm2s[name] = frm;\n      frm.Text = name;\n      frm.FormClosing += new FormClosingEventHandler(Form2_FormClosing);\n      frm.Show();\n   }\n   else\n   {\n      frm.listBox1.Items.Add(body); // assuming listBox1 is public\n      frm.Show();\n      frm.BringToFront();\n   }\n}\nvoid Form2_FormClosing(object sender, FormClosingEventArgs e)\n{\n   e.Cancel = true;\n   ((Form2)sender).Hide();\n}	0
26832977	26830174	How to Set Index of ListPicker without Executing ValueChanged Event	private void BuildControl(PhotoThumbnail pp)\n{\n    switch(pp.NName)\n    {\n        case "flip":\n\n            // unhook event\n            lp.SelectionChanged -= lp_SelectionChanged;\n\n            List<ListPickerItem> l = new List<ListPickerItem>();                    \n            l.Add(new ListPickerItem { Name = "Flip_Vertical", Content = AppResources.App_Flip_Vertical });\n            l.Add(new ListPickerItem { Name = "Flip_Horizontal", Content = AppResources.App_Flip_Horizontal });\n            l.Add(new ListPickerItem { Name = "Flip_Both", Content = AppResources.App_Flip_Both });\n            lp.ItemsSource = l;  //Code execution jumps from here to ValueChanged event immediately                  \n            lp.Visibility = Visibility.Visible;\n            lp.SelectedIndex = Settings.Flip.Value - 1;\n\n            // after setting the index, rehook the event\n            lp.SelectionChanged += lp_SelectionChanged;\n\n            break;\n    ..\n    }\n}	0
2224867	2224374	How to vary connection string for different work locations	configfiles\app.config.mikeb_home\nconfigfiles\app.config.local\nconfigfiles\app.config.development\nconfigfiles\app.config.staging\nconfigfiles\app.config.production	0
3942748	3942653	grant program more access	//Use this if you want different folder per user\nPath.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData),"Your Application Name");\n\n//Use this if you want the same folder per user\nPath.Combine(Environment.GetFolderPath( Environment.SpecialFolder.CommonApplicationData),"Your Application Name");	0
24843299	24843264	How to add custom methods to ASP.NET WebAPI controller?	[Route("ChangePassword")]\n[HttpPost] // There are HttpGet, HttpPost, HttpPut, HttpDelete.\npublic async Task<IHttpActionResult> ChangePassword(ChangePasswordModel model)\n{        \n}	0
18944500	18944323	custom lock with spinlock	public override void LockIt()\n{\n    bool locked = false;\n    try\n    {\n        spinLock.Enter(ref locked);\n    }\n    finally\n    {\n        if(locked)\n            spinLock.Exit();\n    }\n}	0
27892862	27870077	c# web service client: how to add custom header to request?	using(new OperationContextScope(client.InnerChannel)) {\n\n// We will use a custom class called UserInfo to be passed in as a MessageHeader\n\nUserInfo userInfo = new UserInfo();\n\nuserInfo.FirstName = "John";\n\nuserInfo.LastName = "Doe";\n\nuserInfo.Age = 30;\n\n\n\n// Add a SOAP Header to an outgoing request\n\nMessageHeader aMessageHeader = MessageHeader.CreateHeader("UserInfo", "http://tempuri.org", userInfo);\n\nOperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);	0
26738115	26737164	double value calculation	var something = (int)result * 5;                 //equals 90 (int)\nvar somethingElse = Math.Truncate(result) * 5;   //equals 90.0 (double)	0
32054453	32054396	Add Page_Init event for Master Page	protected void Page_Init(object sender, EventArgs e)\n {\n\n }	0
4609200	4609171	LINQ to XML - Querying Elements	var result = _configDoc.Descendants("Content")\n   .Where(c => c.Attribute("Book").Value == "ABC")\n   .Descendants("Item").Single(e => e.Attribute("id").Value == "1").Value;	0
18640696	18618019	Update dynamic column in datagrid	public DataTemplate CreateDataTemplate(Type type, int aNumber)\n    {\n        StringReader stringReader = new StringReader(\n        @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> \n        <" + type.Name + @" Text=""{Binding WrapperCollection[" + aNumber.ToString() + @"].Value}""/> \n    </DataTemplate>");\n        XmlReader xmlReader = XmlReader.Create(stringReader);\n        return XamlReader.Load(xmlReader) as DataTemplate;\n    }\n\n{\n    ...\n    TextBlock textBlock = new TextBlock();\n    var lMyCellTemplate = CreateDataTemplate(textBlock.GetType(), Counter);\n}	0
17445621	17423489	adding header row to gridview won't allow you to save the last item row	protected void gvStatusReport_RowCreated(object sender, GridViewRowEventArgs e)\n   {\n      if (e.Row.RowType == DataControlRowType.Header)\n      {\n         GridView HeaderGrid = (GridView)sender;\n         GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);\n         TableCell HeaderCell = new TableCell();\n         HeaderCell.ColumnSpan = 6;\n         HeaderGridRow.Cells.Add(HeaderCell);\n\n         HeaderCell = new TableCell();\n         HeaderCell.Text = "Time Spent";\n         HeaderCell.ColumnSpan = 7;\n         HeaderGridRow.Cells.Add(HeaderCell);\n\n         HeaderCell = new TableCell();\n         HeaderCell.Text = "Total";\n         HeaderCell.ColumnSpan = 2;\n         HeaderGridRow.Cells.Add(HeaderCell);\n\n         HeaderCell = new TableCell();\n         HeaderCell.ColumnSpan = 6;\n         HeaderGridRow.Cells.Add(HeaderCell);\n\n         gvStatusReport.Controls[0].Controls.AddAt(0, HeaderGridRow);\n      }\n   }	0
27952954	27928691	How to test that NavigationService is configured?	public class DefaultNavigationService : NavigationService\n{\n    public Dictionary<string, Type> Configuration\n    {\n        get;\n        private set;\n    }    \n    public DefaultNavigationService() : base()\n    {\n        Configuration = new Dictionary<string, Type>();            \n    }\n    public new void Configure(string key, Type pageType)\n    {\n        Configuration.Add(key, pageType);\n        base.Configure(key, pageType);\n    }\n}	0
19954000	19953613	Split string in three parts by character length c#	string i_clob1 = "";\nstring i_clob2 = "";\nstring i_clob3 = "";\nif (message.Length >= 3 && message.Length <= 32000 * 3)\n{\n    int lastStart = 2 * message.Length / 3;\n    int lastLength = message.Length - lastStart;\n    i_clob1 = message.Substring(0, message.Length / 3);\n    i_clob2 = message.Substring(message.Length / 3, message.Length / 3);\n    i_clob3 = message.Substring(lastStart, lastLength);\n}\nelse if (message.Length < 3)\n{\n    i_clob1 = message;\n}	0
18457155	18457073	How do I search user input for specific characters?	if(userValue.Contains("T") ||userValue.Contains("t") ||userValue.Contains("?"))\n    {\n        Console.WriteLine("Invalid");\n        Console.ReadLine();\n    }	0
19867562	19864559	How can I update my SQL table in C#?	var thisConnection = new SqlConnection("Server=ServerIP/Name;Data Source=Database;Initial Catalog=Database;User ID=User;Password=Pass;Trusted_Connection=False");\n    thisConnection.Open();\n\n    var updateSql1 = "UPDATE dbo.Customer " +\n                         "SET barber = 'I Barber People !' " +\n                         "WHERE customerID = 5";\n\n    var UpdateCmd1 = new SqlCommand(updateSql1, thisConnection);\n    UpdateCmd1.ExecuteNonQuery();	0
3004475	2873325	.net - how to connect windows service with systray application	System.Diagnostics.Process.GetCurrentProcess().MaxWorkingSet =\n                System.Diagnostics.Process.GetCurrentProcess().MinWorkingSet;	0
12108929	12108848	Loop through xml	XDocument xdoc = new XDocument();\nxdoc = XDocument.Load(fileName);\nvar songlist = from c in xdoc.Element("Result").Elements("email")\n                           select new eMail{ \n                               ID = c.Element("ID").Value, \n                               Subject = c.Element("Subject").Value };	0
11525032	11524204	How to assign unit quantities for datagrid cell	Anndiameter (inches)	0
7454289	7454277	Set background image for a master page that use in sub directories	body\n{\n     background-image:url('/images/background.jpg');\n}	0
2496300	2495890	Need Help with Page Life Cycle(I think it is screwing me up)	OnPageLoad() {\n  get data;\n  build controls;\n  bind data; \n}\n\nOnButtonClick() {\n  save data();\n  build controls; // if changed by 'remove' or 'add'\n  bind data;\n}	0
27448162	27447603	How to design the sql query for intersection between 2 sets of data	declare @program int\nset @program=1\n\nselect * \nfrom Items i, Programs p\nwhere not exists(select 1 from ProgramItems where p.Id=ProgramId and i.Id=ItemId) and\n      ((p.Monday=1 and i.Monday=p.Monday) or\n      (p.Tuesday=1 and i.Tuesday=p.Tuesday) or\n      (p.Wednesday=1 and i.Wednesday=p.Wednesday) or\n      (p.Thursday=1 and i.Thursday=p.Thursday) or\n      (p.Friday=1 and i.Friday=p.Friday) or\n      (p.Saturday=1 and i.Saturday=p.Saturday) or\n      (p.Sunday=1 and i.Sunday=p.Sunday))\nwhere p.Program=@program	0
25412779	25193465	How to manage connection string in a report	Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nconfig.ConnectionStrings.ConnectionStrings["<project_name>.Properties.Settings.<my connection string>"].ConnectionString = "data source=" + Application.StartupPath + "\\database.db";\nconfig.Save(ConfigurationSaveMode.Modified, true);\nConfigurationManager.RefreshSection("connectionStrings");	0
7676809	7676773	How to print html in C#	private void PrintHelpPage()\n{\n    // Create a WebBrowser instance. \n    WebBrowser webBrowserForPrinting = new WebBrowser();\n\n    // Add an event handler that prints the document after it loads.\n    webBrowserForPrinting.DocumentCompleted +=\n        new WebBrowserDocumentCompletedEventHandler(PrintDocument);\n\n    // Set the Url property to load the document.\n    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");\n}\n\nprivate void PrintDocument(object sender,\n    WebBrowserDocumentCompletedEventArgs e)\n{\n    // Print the document now that it is fully loaded.\n    ((WebBrowser)sender).Print();\n\n    // Dispose the WebBrowser now that the task is complete. \n    ((WebBrowser)sender).Dispose();\n}	0
29984216	29984123	Changing cell Backcolor on DataGridView CellMouseClick	dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = false;	0
6299121	6299029	Can C# convert these badly formated month/year tags into a set of datetime objects?	static DateTime Parse(string dateString)\n{\n string[] formats = new [] {"MMMYY\A\u\c", "MMMM YYYY"};\n DateTime parsedDate = new DateTime();\n foreach (string fmt in formats)\n {\n    if (DateTime.TryParseExact (dateString, fmt, null, DateTimeStyles.Default, out parsedDate)\n       return parsedDate;\n }\n throw new FormatException ();\n}	0
19575924	19575853	C#, how to validate JSON using Regex	{("\w+":(\d+|"\w+"|true|false|null))+}\]	0
10298697	10298559	listbox Multiple select items go to top	ListBox.AutoPostback	0
8795398	5857979	Max edit distance and suggestion based on word frequency	Apache Solr	0
20198123	20197918	How to close the current tab in the server side button click?	string jScript = "<script>window.close();</script>";\nClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jScript);	0
5576195	5575620	How to create a Task with TaskFactory.FromAsync and custom Async procedures	[TestMethod]\npublic void TaskCompletionSource_WorksALotBetterThanMyOverEngineeredCustomStuff()\n{\n    int result = 0;\n\n    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();\n\n    Task<int> myTask = tcs.Task;\n\n    // Pretend this is the class under test and that we've\n    // passed in myTask\n    myTask.ContinueWith(t => { result = t.Result; },\n        TaskContinuationOptions.ExecuteSynchronously);\n\n    Assert.AreEqual(0, result);\n\n    tcs.SetResult(54);\n\n    Assert.AreEqual(54, result);\n}	0
3947703	3947693	How to rewrite this foreach looping using linq?	var allOrderIds = thisCustomer.Orders.Select(o => o.OrderId).ToList();	0
2176044	2176011	IQueryable to string[] array?	group r by r.RoleID	0
15252315	15252196	Setting Variable Values During Testing	Private Function processStartedByVisualStudioDebugger() As Boolean\n    Dim result As Boolean = False\n    Try\n        If AppDomain.CurrentDomain.DomainManager.ToString().IndexOf("vshost", StringComparison.OrdinalIgnoreCase) >= 0 Then\n            result = True\n        End If\n    Catch\n    End Try\n    Return result\nEnd Function	0
1393905	1393814	WPF Application moves offscreen during remote access session	bool isWithin = false;\nforeach (Screen screen in Screen.AllScreens)\n{\n    if (screen.Bounds.Contains(windowLocation))\n        isWithin = true;\n}\n\n// if !isWithin, move to 0,0	0
5894983	5894803	How to add namespace dynamically and xml serialization	System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(<my class>.GetType());\n        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n\n        if(<condition>)\n        {\n        ns.Add(string.Empty, @"x-schema:C:\UPSLabel\OpenShipments.xdr");\n        } \n        else\n        {\n        ns.Add(string.Empty, @"x-schema:D:\UPSLabel\OpenShipments.xdr");\n        }\n\n        xs.Serialize(<stream>, <your class instance>,ns);	0
5619157	5619121	Using DESC as column name in DBF	INSERT INTO MyTable ([DESC]) VALUES ('My Description')	0
6745667	6745361	How to find and remove control characters in a text file	StreamReader sr = new StreamReader(@"c:\temp.data\big_file_with_unwanted_chars.txt", Encoding.Default);\nStreamWriter sw = new StreamWriter(@"c:\temp.data\big_file_without_any_evil_chars.txt", false, Encoding.Default);\n\nstring al;\n\nwhile (!sr.EndOfStream)\n{\n  al = sr.ReadLine();\n  al = al.Replace("?", "");\n  al = al.Replace("#", "");\n  sw.WriteLine(al);\n}\nsw.Close();\nsr.Close();	0
4326618	4326156	Changed Database Name -- Datatable Adapters broke	Settings.Designer.cs	0
12331387	12331205	Comparing two PDF file in C#	Dim str1 = New String() {"I", "love", "stackoverflow"}\n    Dim str2 = New String() {"I", "stackoverflow"}\n    Dim Diff = str1.Where(Function(x) Not str2.Contains(x)).ToArray()	0
15127859	15127483	How to append a FlowDocument to RichTextBox?	using System.Text.RegularExpressions;\nusing System.Windows.Markup;\n\n    richTextBox1.Document = Joint_FlowDocument(richTextBox1.Document, richTextBox2.Document);\n\n    //Joint flowDocument_2 to the end of flowDocument_1\n    private FlowDocument Joint_FlowDocument(FlowDocument flowDocument_1, FlowDocument flowDocument_2)\n    {\n        StringWriter wr_f1 = new StringWriter();\n        XamlWriter.Save(flowDocument_1, wr_f1);\n        string str_f1 = wr_f1.ToString().Replace("</FlowDocument>", "");\n        StringWriter wr_f2 = new StringWriter();\n        XamlWriter.Save(flowDocument_2, wr_f2);\n        string str_f2 = wr_f2.ToString();\n        str_f2 = Regex.Replace(str_f2, "<FlowDocument.*?>", "");\n        return XamlReader.Parse(str_f1 + str_f2) as FlowDocument;\n    }	0
15908785	15622767	Update a varchar field with null value	cmd.Parameters.Add(new MySqlParameter("@nomeclube", MySqlDbType.VarChar)).Value = !String.IsNullOrEmpty(usr.Nome_Clube) ? (object)usr.Nome_Clube : DBNull.Value;	0
18216833	18212675	adding parameter to parent node on mvcsitemap	preservedRouteParameters="id"	0
5280424	5280391	How do I use a variable to identify another variable in C#?	class MyClass\n{\n\n  public int x {get;set;}\n  MyClass()\n  {\n      x = 3;\n  }\n\n  void Foo()\n  {\n      Type type = GetType();\n      PropertyInfo pInfo = type.GetProperty("x");\n\n      object xValue= pInfo.GetValue(this, null);\n      Console.Writeln(xValue); \n  }\n\n\n}	0
14780523	14780455	Allow mousepointer to be outside of screen boundaries	// Center of the window\nvar resetPosition = new Point(WindowWidth / 2, WindowHeight / 2);\n\n// Get the movement since the last frame\nvar mouseState = Mouse.GetState();\nvar mousePosition = new Point(mouseState.X, mouseState.Y);\nvar delta = mousePosition - resetPosition;\n\n// Reset the mouse position\nMouse.SetPosition(resetPosition.X, resetPosition.Y);\n\n// Use the delta\nRotateCamera(delta);	0
32685085	32649457	How to get X, Y coordinates of the pixel depths in Kinect?	var x = i % (int)desc.Width;\nvar y = i / (int)desc.Width;	0
30085974	30060127	Access Login Control from Different Page	if (User.Identity.IsAuthenticated == true)	0
10347941	10335058	How to set the target framework to v2.0 or v3.5 instead of 4.0 when compiling a program from a source file?	var providerOptions = new Dictionary<string, string>();\nproviderOptions.Add("CompilerVersion", "v4.0");\nvar compiler = new CSharpCodeProvider(providerOptions);	0
30206809	30021650	How to create a new instance of Azure Application Insights through the REST API	// initialize resource management client\nvar resourceManagement = new ResourceManagementClient(this.Credentials);\nresourceManagement.Providers.RegisterAsync("microsoft.insights").Result;\n\n// create identity & parameters for create call\nvar resourceIdentity = new ResourceIdentity(\n    "SomeResourceName", // ResourceName\n    "microsoft.insights/components", // ResourceType\n    "2014-04-01" // Api Version\n);\nvar parameters = new GenericResource {\n    Location = 'centralus'\n};\n\n// send call off and hope for the best\nvar result = this.ManagementContext.ResourceManagement.Resources.CreateOrUpdateAsync(\n    "SomeResourceGroupName",\n    resourceIdentity,\n    parameters,\n    CancellationToken.None).Result;	0
28705406	28702033	How to accomplish FIFO with Azure service bus topics	// Configure Topic Settings\n    TopicDescription td = new TopicDescription("TestTopic");\n    td.SupportOrdering = true;\n\n    // Create a new Topic with custom settings\n    string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");\n\n    var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);\n    namespaceManager.CreateTopic(td);	0
14121811	14117316	Cannot bind a SelectedValue to a combobox for WPF in xaml from property	SelectedValue="{Binding Path=CurrentUser, Mode=OneWay}"	0
4256124	4256097	creating a folder without giving hardcore path in the code	var _logFolderPath = Path.Combine(textboxPath.Text.Trim(), "log");	0
16491274	16491136	How to deserialize a JSON array containing an object that contains an array of arrays with Json.NET and C#?	var result = JsonConvert.DeserializeObject<List<MyObject>>(str);\n\npublic class MyObject\n{\n    public List<List<string>> data { get; set; }\n    public string error { get; set; }\n    public double statement_time { get; set; }\n    public double total_time { get; set; }\n}	0
5230108	5230061	Delete application files after it runs	internal enum MoveFileFlags\n{\n    MOVEFILE_REPLACE_EXISTING = 1,\n    MOVEFILE_COPY_ALLOWED = 2,\n    MOVEFILE_DELAY_UNTIL_REBOOT = 4,\n    MOVEFILE_WRITE_THROUGH  = 8\n}\n\n[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",EntryPoint="MoveFileEx")]\ninternal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName,\nMoveFileFlags dwFlags);\n\nMoveFileEx(fileToDelete, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);	0
27130244	27129899	How to work around EF generating SQL statement nested too deeply	public static List<Hierarchy> Select(List<int> selection)\n{\n    var result = context.Hierarchy\n        .Where(sub => sub.Children.Any(csub => selection.Contains(csub.Id)));\n}	0
21259742	21259453	Display image from Uri	Image i = new Image();\ni.Source = new BitmapImage(new Uri("/yourProjectName;component/Assets/YourImageName", UriKind.RelativeOrAbsolute));       \nLayoutRoot.Children.Add(i);	0
8360729	8360678	How to run a predicate on ObjectInstance property of DataTrigger	Binding.Converter	0
1548304	1548242	The use of global:: for conflicting namespaces	global::	0
5187744	5187120	How can log4net be configured using a System.Configuration.Configuration	if (configuration.HasFile)\n{\n        System.IO.FileInfo configFileInfo = new System.IO.FileInfo(configuration.FilePath);\n        log4net.Config.XmlConfigurator.Configure(configFileInfo);\n}	0
4599708	4599686	Image to byte array from a url	var webClient = new WebClient();\nbyte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");	0
652113	651982	How to trim values using Linq to Sql?	public partial class Contact\n{\n    partial void OnLoaded()\n    {\n        FirstName = FirstName.Trim();\n    }\n}	0
24981334	24981229	Generate a random image from a group of images in C# Windows Store App Development	private Random rnd = new Random();\n\nprivate void showRandomOrb()\n{\n    switch(rnd.Next(2,19)) // selects random integer from 2 to 18\n    {\n        case 2:\n            orb2.Visibility = Visibility.Visible;\n            break;\n        case 3:\n            orb3.Visibility = Visibility.Visible;\n            break;\n        case 4:\n            orb4.Visibility = Visibility.Visible;\n            break;\n        // etc..\n        case 18:\n            orb18.Visibility = Visibility.Visible;\n            break;\n    }\n}\n\nprivate void o1(object sender, PointerRoutedEventArgs e)\n{\n    showRandomOrb();\n}	0
7338331	7338012	Cell/Row Counting	private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n  {\n     lineCounter();\n  }	0
10756155	10756117	How to do this C# thing in VB?	td.Triggers.Add(New DailyTrigger() With { _\n    Key .DaysInterval = 2 })	0
3502349	3496958	With entity framework's self tracking entities, can I perform an explicit load?	var biz = ctx.Business.Where(b => b.BusinessID == id).Single(); \nvar contacts = ctx.Contacts.Where(c => c.BusinessID==id && c.ContactTypeID==6);\nforeach (var contact in contacts)\n{\n   biz.Contacts.Add(contact);\n}	0
30451145	30443829	Hold and get ListView Item index	private void ListViewItem_Holding(object sender, HoldingRoutedEventArgs e)\n{  \n    var item = (sender as FrameWorkElement).DataContext;\n    //find index\n    // index= yourItemSource.IndexOf(item );\n}	0
7671626	7671449	.NET Web Service - How to make properties invisible	public class Data\n{\n  public int Id{get;set;}\n\n  [XmlIgnore()]\n  public string Name{get;set;}\n}	0
29852150	29851327	Quartz-schedule.net getting schedule from trigger	var triggerKey = new TriggerKey("trigger3", "group2");\nvar trigger = scheduler.GetTrigger(triggerKey);	0
23175642	23175530	Return json without binding it to object using web client	public string Index()\n{\n    using (var client = new WebClient())\n    {\n        return client.DownloadString("https://itunes.apple.com/lookup?id=909253");\n    }\n}	0
5515515	5514999	Binding colors of shapes with variables c#	Binding binding = new Binding("State");\n    binding.Converter = new BooleanToBrushConverter();\n    _rectangle.SetBinding(Rectangle.FillProperty, binding);	0
5835558	5835528	Constant based on variable?	public static readonly int	0
9809476	9801201	XmlWriter leave element open	stream:stream	0
17165985	17165057	getting a outlook contact of a contact group in c#	foreach (var item in OutlookItems) {\n    var contact = item as ContactItem;\n    if (contact != null) {\n      Console.WriteLine("FirstName " + contact.FirstName);\n    }\n  }	0
33163212	33159730	Check If file exists inside a folder of a Console Application	string imagePath = Path.Combine(Environment.CurrentDirectory, "Images");	0
5608704	5608684	How to use relative path to Resources folder in C# Window Form application?	Properties.Resources.String1;	0
33514770	33511874	i want to show the row which it,s checkbox was checked in datagridview and hide the others rows unchecked	foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n         if (!Convert.ToBoolean(row.Cells[0].Value))\n         {\n             dataGridView1.CurrentCell = null;\n             row.Visible = false;\n         }\n    }	0
173800	173579	How to pass mouse events to applications behind mine in C#/Vista?	protected override CreateParams CreateParams\n{\n    get\n    {\n        CreateParams createParams = base.CreateParams;\n        createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT\n\n        return createParams;\n    }\n}	0
13725697	13725314	Regexp issue on group splitting	// Unescaped regular expression is (?<=")[^"]*(?=")|(?<=^|;)[^;]*(?=$|;)\nRegex r = new Regex(@"(?<="")[^""]*(?="")|(?<=^|;)[^;]*(?=$|;)");\nforeach (Match field in r.Matches(csvLine))\n   ... // do something with field.Value	0
25613470	25613377	How to create method without returning any value	public static void GetGrade(float wp)\n{\n    if (wp >= 100)\n        grade_current.Text = "A";\n    else if (wp >= 90)\n        grade_current.Text = "A";\n    else if (wp >= 75)\n        grade_current.Text = "B";\n    else if (wp >= 60)\n        grade_current.Text = "C";\n    else if (wp >= 50)\n        grade_current.Text = "D";\n    else\n        grade_current.Text = "F";\n}	0
12999889	12999878	linq union of two lists	var MyCombinedList = TheObject1.ListOfLongs.Concat(TheObject2.ListOfLongs);	0
3393667	3393642	Is there any control drivelistbox in Dot Net?	Environment.GetLogicalDrives()	0
12431435	12431286	calculate result from a string expression dynamically	Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));\n\ndynamic obj = Activator.CreateInstance(scriptType, false);\nobj.Language = "javascript";\n\nvar res = obj.Eval("a=3; 2*a+32-Math.sin(6)");	0
10358093	10358028	How to properly split a website into different regions?	public Region RegionContext\n{\n    get\n    {\n        if (this.user != null &&\n            this.user.Region!= null)\n            return this.user.Region;\n\n        var region= _region.GetAllRegions().FirstOrDefault();\n        return region;\n    }\n    set\n    {\n        if (this.user == null)\n            return;\n\n        this.user.region = value;\n        _user.UpdateUser(this.User);\n    }\n}	0
21620827	21605494	Linq query to remove duplicate rows from two tables	var userAccessInsert = (from r in TBL_Access2\n                                where !(from uA in TBL_Access1\n                                       where uA.Entity_LookupID == r.Entity_LookupID\n                                       select uA.Entity_LookupID).Contains(r.Entity_LookupID)\n                                       select r);	0
7852411	7852161	C# convert XML to string in order to search it	string xmlString =  System.IO.File.ReadAllText(fileName);	0
28441031	28440650	Get timezone by current culture info with c#	MX (Spanish Mexico), es-CO (Spanish Columbia), and fr-CA (French Canada)	0
32076680	32055164	Implementing Logic in Base Controller MVC	protected override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        _max = Helpers.GetSource(Request.QueryString["source"]);\n\n        if (_max == null)\n        {\n            filterContext.Result =\n                Content("Please check your request URL format, there is no source defined for your input");\n            return;\n        }\n\n        base.OnActionExecuting(filterContext);\n    }	0
3313197	3313184	Private 'set' in C# - having trouble wrapping my brain around it	public class Test\n{\n   private object thingy;\n   public object Thingy\n   {\n      get { return thingy; }\n   }\n}	0
25033827	25032916	Display image if present in datagrid	public class EmptyStringToCollapsedConverter : IValueConverter\n{\n    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        var s = (value as string);\n        return String.IsNullOrWhiteSpace(s)? Visibility.Collapsed : Visibility.Visible;\n    }\n\n    public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new NotSupportedException();\n    }\n}	0
17991110	17990992	SSIS display variable values in script task	string Variables = String.Format("{0},{1},...",Dts.Variables["User::ClientID"],Dts.Variables["User::Passphrase"],...)	0
8838390	8838371	How to set input type="number" on dynamic textbox in c# codebehind	qtybox.Attributes.Add("type", "number");	0
10378128	9718375	How to retrieve data from CURL.exe?	ProcessStartInfo start = new ProcessStartInfo();\nstart.FileName = @"D:\curl.exe";  // Specify exe name.\nstart.Arguments = "-u agentemail:password -k https://fantasia.zendesk.com/api/v1/tickets/1.xml";\nstart.UseShellExecute = false;\nstart.RedirectStandardOutput = true;\n\n// Start the process.\nusing (Process p = Process.Start(start)) {\n    // Read in all the text from the process with the StreamReader\n    using (StreamReader reader = p.StandardOutput) {\n        string result = reader.ReadToEnd();\n        Console.Write(result);\n    }\n}	0
17612677	17611886	Add namespace with colon to xml file	XNamespace ns = XNamespace.Get("http://namespace");\n\nvar xDocument = new XDocument(\n                new XElement(ns + "Root",\n                    new XAttribute(XNamespace.Xmlns + "ns0", ns),\n                    new XElement("Node1",\n                        new XElement("A", "ValueA"),\n                        new XElement("B", "ValueB")\n                        )));	0
17446031	17445547	How to display first element of DataGridViewComboBoxCell inside dynamic Gridview in c#?	global_inhibits.Value = global_inhibits.Items[0];	0
27543790	27504654	Add and bind a new tabpage within c# application	var firstTabPage = new XtraTabPage();\n        firstTabPage.Text = "first";\n        var secondTabPage = new XtraTabPage();\n        secondTabPage.Text = "second";\n\n        xtraTabControl1.TabPages.Add(firstTabPage);\n        xtraTabControl1.TabPages.Add(secondTabPage);\n        xtraTabControl1.TabPages[0].PageVisible = false;	0
7005297	7005130	Linq to entities to join two tables	[MetadataTypeAttribute(typeof(Part_Stock.Metadata))]\npublic partial class Part_Stock\n{\n\n    internal sealed class Metadata\n    {\n        // Metadata classes are not meant to be instantiated.\n        private Metadata()\n        {\n        }\n\n        [Include]\n        public EntityCollection<Stock_Table> Stock_Table { get; set; }\n    }\n}	0
7685854	7685816	Enums, overlapping values, C#	enum PrivilegeLevel\n{\n    None,\n    Reporter,\n    Reviewer,\n    Admin,\n    DefaultForNewUser = None,\n    DefaultForProjectOwner = Reviewer,\n};	0
24618442	24618375	Create a Dictionary from a list with duplicates	var myDic = MyList.ToLookup(x => x.ID)\n                  .ToDictionary(x => x.Key, x => x.First());	0
21806278	21805210	How can i parse/extract the text of date and time between two tags?	var client = new System.Net.WebClient();\n\nclient.Encoding = System.Text.Encoding.GetEncoding(1255);\n\nvar page = client.DownloadString("http://rotter.net/scoopscache.html");\n\nvar re = new Regex(@"<span style=color:#000099;>(.+?)</span>");\n\nvar matches = re.Matches(page)\n                .Cast<Match>()\n                .Select(_ => _.Groups[1].Value)\n                .ToArray();\n\n/*\n    'matches' contains the matched strings \n*/	0
10077476	10076202	Keeping the parent DialogButton open after the child DialogButton is closed	if(validationOK == false)\n{\n    // Ask retry or cancel to the user\n    if(DialogResult.Cancel == MessageBox.Show("Validation Fail", "Validation failed, press retry to do it againg", MessageBoxButtons.RetryCancel))\n        this.DialogResult.Cancel; // Set the dialog result on form2. This will close the form.\n\n    // if you have the validation done in a button_click event and that button has its\n    // property DialogResult set to something different than DialogResult.None, we need\n    // to block the form2 from closing itself.\n\n    // uncomment this code if the above comment is true\n    // else\n    //    this.DialogResult = DialogResult.None;\n}	0
5948943	5948889	Create array of property values from list based on condition	plan.Components.Where(c => c.active).Select (c => c.qty.HasValue ? (int)c.qty.Value : 0 )	0
8738616	8738556	How to add editable first child node in winforms	public Form1()\n{\n   InitializeComponent();\n   tree.SelectedNode = tree.Nodes.Add("Hello", "Hello");\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    tree.LabelEdit = true;\n    TreeNode node = new TreeNode("New Folder");\n    tree.SelectedNode.Nodes.Add(node);\n    tree.SelectedNode.Expand();\n    node.BeginEdit();\n}	0
26417165	26416900	An item with the same key has already been added in LinqToTwitter search	var foundTweets =\n(from tweet in ctx.Status\n where tweet.Type == StatusType.Lookup &&\n       tweet.TweetIDs == "522564774706831362,522922846293884929"\n select tweet).ToList();	0
8893326	8892963	Access Queue<T> from two delegate.BeginInvoke Async Methods Simultaneously	ConcurrentQueue<T>	0
2969818	2969573	EnvDTE Retrieving the data type from a CodeElement	Public Sub DisplayStuff()\n\n    Dim objTextSel As TextSelection\n    Dim objCodeCls As CodeClass\n    objTextSel = CType(DTE.ActiveDocument.Selection, TextSelection)\n    objCodeCls = CType(objTextSel.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)\n\n    If objCodeCls Is Nothing Then\n        MsgBox("Please launch this macro when the cursor is within a class")\n        Exit Sub\n    End If\n\n    For Each elt As CodeElement2 In objCodeCls.Members\n\n        Select Case elt.Kind\n\n            Case vsCMElement.vsCMElementVariable\n\n                Dim v As CodeVariable2 = CType(elt, CodeVariable2)\n\n                MsgBox(v.Name & " is a variable of type " & v.Type.AsString)\n\n            Case vsCMElement.vsCMElementProperty\n\n                Dim p As CodeProperty2 = CType(elt, CodeProperty2)\n\n                MsgBox(p.Name & " is of type " & p.Type.AsString)\n        End Select\n\n\n    Next\nEnd Sub	0
8257027	8256996	how do I add parameter comments for a method in c#	/// <summary>\n/// this will be the tooltip\n/// </summary>\n/// <param name="args">args will be passed when starting this program</param>\nstatic void Main(string[] args)\n{\n\n}	0
18213589	18213466	Using variables in the lambda	var filtered = properties.Where(p => \n        {\n            if(!p.PropertyType is MyMetaData)\n            {\n                return false;\n            }\n            var item = (MyType) p.GetValue(obj);\n            return item.Name == "name"\n                && item.Length == 10\n        }\n    ).ToList();	0
7350483	7350448	Adding up a sum of 2 numbers into A Masked Textbox	private void button11_Click(object sender, EventArgs e)\n{\n   maskedTextBox2.Text = (350 + 400).ToString();\n}	0
11179033	11178727	Matching Two Array Indexes - c# / Windows Phone 7	class Program\n{\n    static void Main(string[] args)\n    {\n        var subs = new Substitutes {{'a', 'b'}, {'c', 'd'}};\n\n        Console.WriteLine(subs['a']); //Prints b\n        Console.WriteLine(subs['b']); //Prints a\n    }\n\n    class Substitutes : Dictionary<char, char>\n    {\n         public new void Add(char item, char substitute)\n         {\n             base.Add(item, substitute);\n             base.Add(substitute, item);\n         }\n    }\n}	0
4821	4816	How do you resolve a domain name to an IP address with .NET/C#?	using System.Net;\n\nforeach (IPAddress address in Dns.GetHostAddresses("www.google.com"))\n{\n   Console.WriteLine(address.ToString());\n}	0
22149113	22149096	How can I stop executing the rest of a method at some point inside the method?	return;	0
32061466	32060722	How to do smooth Random in C# with step?	Random rand = new Random();\nfloat randomInSet = ((float)rand.Next(0,12)*.4)+5;	0
11212722	11206746	Alchemy-Websockets - WebSocketClient Path	var aClient = new WebSocketClient("ws://172.28.1.103:8100/channel");	0
7507288	7502690	How to duplicate .doc page	object missing = System.Reflection.Missing.Value;\nobject StartPoint = 0;\n\nApplicationClass WordApp = new ApplicationClass();\nDocument WordDoc = WordApp.Documents.Add(ref missing, ref missing, \n                                         ref missing, ref missing);\nRange MyRange = WordDoc.Range(ref StartPoint, ref missing);	0
87312	87222	representing CRLF using Hex in C#	"\x0d\x0a"	0
10921472	10918138	How can I remove the "Today" button from DateTimePicker control (of Windows form Control)	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass MyDateTimePicker : DateTimePicker {\n    protected override void OnHandleCreated(EventArgs e) {\n        int style = (int)SendMessage(this.Handle, DTM_GETMCSTYLE, IntPtr.Zero, IntPtr.Zero);\n        style |= MCS_NOTODAY | MCS_NOTODAYCIRCLE;\n        SendMessage(this.Handle, DTM_SETMCSTYLE, IntPtr.Zero, (IntPtr)style);\n        base.OnHandleCreated(e);\n    }\n    //pinvoke:\n    private const int DTM_FIRST = 0x1000;\n    private const int DTM_SETMCSTYLE = DTM_FIRST + 11;\n    private const int DTM_GETMCSTYLE = DTM_FIRST + 12;\n    private const int MCS_NOTODAYCIRCLE = 0x0008;\n    private const int MCS_NOTODAY = 0x0010;\n\n    [DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}	0
32646028	32645691	How to convert string to timeStamp for insert into mysql in C#	DateTime date = DateTime.ParseExact("28.9.2015 05:50:00", "dd.M.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);	0
6079155	6079070	How to create an Xml with multiple namescapes using XDocument	XNamespace a="http://www.w3.org/2005/Atom";\n XNamespace os = "http://a9.com/-/spec/opensearch/1.1/";\n XNamespace def = "http://schemas.zune.net/catalog/apps/2008/02";\n\n var doc =\n     new XDocument(new XElement(a + "feed", \n                         new XAttribute(XNamespace.Xmlns + "a", a),\n                         new XAttribute(XNamespace.Xmlns + "os", os),\n                         new XAttribute("xmlns", def)));	0
13878232	13877947	Overwriting a DLL after using RegAsm	taskkill /F /IM EXCEL.EXE	0
25574159	25574043	Using a conditional if statement in a Linq query	(n.ReportingPeriod == "Oct1" && (FiscalYear - aprYearDiff) == sau.SAUYearCode)  \n|| (n.ReportingPeriod != "Oct1" && (FiscalYear - octYearDiff) == sau.SAUYearCode)	0
9124450	9113579	Command line with parameters	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.WorkingDirectory = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH");\nstartInfo.FileName = ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH");\nstartInfo.Arguments = string.Format("\"{0}\" /EXPORT:{1} /SEPTAB", filePath, newFilePath);\nusing (Process exeProcess = Process.Start(startInfo))\n{\n    exeProcess.WaitForExit();\n}	0
3062426	3062408	How to Sort IEnumerable List?	var sortedCars = cars.OrderBy(c => c.Model).ThenBy(c => c.Year);	0
2211732	2188870	Problem retreiving cookies from HttpResponse	Response.Cookies["Notifications"].Secure = true;	0
4247344	4247326	Input string incorrect format	using System.Globalization;\n\nshort.Parse(f1.returnTBOX4().Text, CultureInfo.InvariantCulture);	0
1379123	1379044	C# - readin from serial port buffer	using System.IO.Ports;\n...\n\nprivate SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);\n\nConsole.WriteLine(port.ReadExisting());	0
1586097	1586088	Can you insert at position 0 in a List<MyObject>?	List<string> values = new List<string>();\nvalues.Insert(0, "NewString");	0
11446518	11382429	How to clear panel's graphics in c#?	Panel1.Invalidate();	0
6253824	6253211	How do I check a check box in a pdf template	formFields.SetField("checkBoxId", "Yes");	0
16635472	16631122	Prevent Range Validator to show error message with regular expression validator in asp.net	function clearRangeMessagePosition() {\n            if (document.getElementById('<%=RegularExpressionValidator1.ClientID %>').getAttribute('isValid') != true.toString()) {\n                document.getElementById('<%=RangeValidator1.ClientID %>').innerText = "";\n            }\n            else {\n                document.getElementById('<%=RangeValidator1.ClientID %>').innerText = "Please enter number of books in range 1-100";\n            }\n        }	0
30230237	30230118	Copy between variable length arrays c#	public string[] Replace(string[] page, string[] notes, int start, int length)\n{\n  for(var i = 0; i + start < page.Length && i < length; i++)\n  {\n    if(notes != null && notes.Length > (i))\n      page[i+start] = notes[i];\n    else\n      page[i+start] = Enviroment.NewLine;\n  }\n\n  return page;\n}	0
27310714	27310201	Async requests in Unity	void Start(){\n    StartCoroutine(AskServerSomething());\n}\n\nIEnumerator AskServerSomething() {\n    WWW www = new WWW("http://stackoverflow.com/");\n    yield return www;       \n    if(www.error == null){\n        print("success: " + www.text);\n    } else {\n        print("something wrong: " + www.text);\n    }\n}	0
34102045	34099979	C# automatic login to gmail/hotmail via web browser	using OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium;\n\nclass Test\n{\n    static void Main(string[] args)\n    {\n        IWebDriver driver = new FirefoxDriver();\n        driver.Navigate().GoToUrl("https://www.gmail.com/");\n        IWebElement query = driver.FindElement(By.Id("Email"));\n        query.SendKeys("my.email@gmail.com");\n        query = driver.FindElement(By.Id("next"));\n        query.Click();\n        // now you just have to do the same for the password page\n\n        driver.Quit();\n    }\n}	0
23926996	23926294	Creating Listbox dynamically in Grid WPF	var panelTemplate = new ItemsPanelTemplate();\nvar stackPanel = new FrameworkElementFactory(typeof(StackPanel));\nstackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);\npanelTemplate.VisualTree = stackPanel;\n\nListBox listBox = new ListBox();\nlistBox.ItemsPanel = panelTemplate;\nlistBox.Items.Add("Mon");\nlistBox.Items.Add("Tue");\nlistBox.Items.Add("Wed");\nlistBox.Items.Add("Thu");\nlistBox.Items.Add("Fri");\n\nthis.grid.Children.Add(listBox);\nlistBox.SetValue(Grid.RowProperty, 0);\nlistBox.SetValue(Grid.ColumnProperty, 0);	0
2437511	2426263	How do I get the IVsTextView of a specific OutputWindowPane?	IVsOutputWindow outWindow = GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;\n// Give me the Debug pane\nGuid debugPaneGuid = VSConstants.GUID_OutWindowDebugPane;\nIVsOutputWindowPane pane;\noutWindow.GetPane(ref debugPaneGuid, out pane);\n// Get text view and process it\nIVsTextView view = pane as IVsTextView;	0
6916690	6916539	extracting a substring from a huge string	string input = "This is a test, again I am test TECHNICAL: I need to extract this substring starting with testing. 8. This is test again and again and again and again";\nstring pattern = @"(TECHNICAL|JUSTIFY).*?(10|[1-9])";\n\nSystem.Text.RegularExpressions.Regex myTextRegex = new Regex(pattern);\n\nMatch match = myTextRegex.Match(input );\nstring matched = null;\nif (match.Groups.Count > 0)\n{\n   matched = match.Groups[0].Value;\n}\n\n//Result: matched = TECHNICAL: I need to extract this substring starting with testing. 8	0
18263533	18262346	Populating multiple user controls from a database	int i = 0;\nforeach (TextBox txtBox in (from Control control in groupBox1.Controls\n                            where control is TextBox && ((TextBox)control).ReadOnly\n                            select control))\n    safeString(dr, txtBox, i++);	0
7906865	7906517	Move sqlite database in IsolatedStorage	IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();\n\nif (!isf.FileExists("my.db"))\n{\n    StreamResourceInfo sri = App.GetResourceStream(new Uri("my.db", UriKind.Relative));\n\n    IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("my.db", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());\n\n    long FileLength = (long)sri.Stream.Length;\n    byte[] byteInput = new byte[FileLength];\n    sri.Stream.Read(byteInput, 0, byteInput.Length);\n    isfs.Write(byteInput, 0, byteInput.Length);\n\n    sri.Stream.Close();\n    isfs.Close();\n}	0
22513338	22513299	Handling dummy items in ObservableCollection	ObservableCollection<T>	0
14989529	14988856	Create IQueryable of Unknown Type from IList at Runtime	var queryable = new List<dynamic>();\nforeach(var entity in IList<Entity>)\n{\n    dynamic companyProfile = Convert.ChangeType(entity, Type.GetType(typeString));\n    if (companyProfile.CompanyProfileId == "something")\n        queryable.Add(companyProfile);\n    // Do Stuff\n}\n// Do Stuff	0
7032019	7028745	how to get next 50 items from a WellKnownFolderName in Exchange?	var items = service.FindItems(WellKnownFolderName.Inbox, new ItemView(50, 50));	0
14161362	13883082	How discover the binding configuration to authenticate in web service	Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)\n    Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://site.customer/ens/qa/customer.bs.ws.service.cls"), HttpWebRequest)\n    req.Method() = "POST"\n    req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)"\n    req.ContentType = "text/xml;charset=UTF-8"\n    req.ContentLength = byteArray.Length\n    req.KeepAlive = True\n    req.Host = "site.customer"\n    req.AutomaticDecompression = 3\n    req.Headers.Add("SOAPAction", "http://www.tempuri.org/customer.bs.ws.service.function")	0
17546053	17543799	C# parse iTunes XML	XDocument xml = XDocument.Parse(html);\n\nforeach (XElement entryElement in xml.Descendants(XName.Get("entry", "http://www.w3.org/2005/Atom")))\n{\n\n}	0
11126982	11122312	Interface Marshalled for a Different Thread in C# on Windows 8	NetworkInformation.NetworkStatusChanged += (sender) =>\n    {\n        Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Update);\n    };	0
21103290	21094261	Windows 8 Custom Message Dialog without XAML	Popup popup = new Popup { Child = CreateXamlControlInCode() };\npopup.IsOpen = true;	0
566550	566539	Algorithm for finding the difference between two arrays	var diff = oldKeys.Except(currKeys);	0
12174032	12174004	How do I release a file held by BitMap class	using(var image = new Bitmap(filepath))\n{\n    image.Save(someOtherPath);\n}\n\n\nFile.Delete(filePath);\nFile.Move(someOtherPath, filePath);	0
18742442	18742200	How to read all data from .lbl file	byte[] allData = binaryreader1.ReadBytes(int.MaxValue);	0
21454095	21453851	Clear Only a Field After Postback	if (!ModelState.IsValidField(key))\n{\n    var emptyValue = new ValueProviderResult(\n        string.Empty,\n        string.Empty,\n        CultureInfo.CurrentCulture);\n\n    ModelState.SetModelValue(\n        key,\n        emptyValue);\n}	0
23979813	23059909	How do you use a projection buffer to support embedded languages in the Visual Studio editor	// Abandon all hope ye who enters here.\n// https://twitter.com/Schabse/status/393092191356076032\n// https://twitter.com/jasonmalinowski/status/393094145398407168\n\n// Based on decompiled code from Microsoft.VisualStudio.Html.ContainedLanguage.Server\n// Thanks to Jason Malinowski for helping me navigate this mess.\n// All of this can go away when the Roslyn editor ships.	0
18825185	18824169	Dynamic List of Messages	var me = (from m in chat.Messages\n                  orderby m.MessageTime descending\n                  select new MessageByUser() { MessageText = m.MessageText }).ToList();\n        return me;	0
24654769	24654575	Recursive function to split list into list	var List<Data> myData;\nvar List<List<Data>> mySplittedData;\n\nmySplittedData.Add(new List<Data>());\nforeach(var item in myData)\n{\n  mySplittedData.Last().Add(item);\n  if(item.FinalValue == 0)\n    mySplittedData.Add(new List<Data>());\n}	0
32876481	32876313	A patterned irregular splitting of a number into many parts of its digits in C#?	private string getMySubString(long value, int splitPart)\n  {\n     string str = value.ToString();\n\n     if (str.Length != 11) return "invalid number lenght";\n\n     string sub1 = str.Substring(0, 5);\n     string sub2 = str.Substring(5, 4);\n     string sub3 = str.Substring(9, 1);\n     string sub4 = str.Substring(10, 1);\n\n     switch (splitPart)\n     {\n        case 1:\n           return sub1;\n        case 2:\n           return sub2;\n        case 3:\n           return sub3;\n        case 4:\n           return sub4;\n        default:\n           return "Invalid part number";\n     }\n  }	0
28812494	28808201	Unable to find an element in Browser of the Android emulator using Appium and C#	var element = _driver\n            .findElementByXPath("//input[@id='lst-ib']");	0
31724645	31722110	Selecting Data in my sdf file is very slow	string command = "Create NONCLUSTERED INDEX BARCODE_INDEX ON MainInputFile(BARCODE)";\nSqlCeCommand cmd = new SqlCeCommand(command, GetConnection());\ncmd.ExecuteNonQuery();	0
12363086	12321420	C# - using a Spline Chart to map values	for (Double t = 0; t<=1; t += 0.01)\n  {\n      s = (1 - t) / 2;\nP(t)x = s(-t3 + 2t2 ? t)P1X + s(-t3 + t2)P2X + (2t3 ? 3t2 + 1)P2X + s(t3 ? 2t2 + t)P3X + (-2t3 + 3t2)P3X + s(t3 ? t2)P4X\n\nP(t)y = s(-t3 + 2t2 ? t)P1Y + s(-t3 + t2)P2Y + (2t3 ? 3t2 + 1)P2Y + s(t3 ? 2t2 + t)P3Y+ (-2t3 + 3t2)P3Y + s(t3 ? t2)P4Y\n\nif(P(t)x=>xtarget)\n{\nreturn P(t)y;\n}\n}	0
21727972	21687084	Auto-scoll/pan in OxyPlot real-time data series plotting	double panStep = xAxis.Transform(-1 + xAxis.Offset);\nxAxis.Pan(panStep);	0
24775716	24761146	C# socket blocking with zero data	if (iRx == 0)\n   throw new SocketException(Convert.ToInt16(SocketError.HostDown));	0
3281598	3281508	Check 3 enum values in one go?	switch (myVar)\n{\n    case 1:\n        // do stuff\n        break;\n    case 2:\n        // do stuff\n        break;\n    case 3:\n        // do stuff\n        break;\n}	0
3413988	3248267	Parsing Facebook Open Graph API JSON Response in C#	var json = JObject.Parse(result);\nvar array = json["325475509465"]["data"];	0
32438426	32438258	match optional special characters	create function\s+\[?\w+\]?\.\[?\w+\]?\n\nval regExp = "create function" + //required string literal\n  "\s+" +  //allow to have several spaces before the function name\n  "\[?" +  // '[' is special character, so we quote it and make it optional using - '?'\n  "\w+" +  // only letters or digits for the function name\n  "\]?" +  // optional close bracket\n  "\." +  // require to have point, quote it with '\' because it is a special character\n  "\[?" + //the same as before for the second function name\n  "\w+" + \n  "\]?"	0
1034510	1034490	What's the equivalence of an SQL WHERE in Lambda expressions?	decimal sum = _myDB.Products\n                   .Where(p => (p.Date >= start) && (p.Date <= end) )\n                   .Sum(p => p.Price)\n                   .GetValueOrDefault();	0
8577995	8577937	Unable to output text from console to a text file	byte[] b = new byte[100];\nint k = s.Receive(b);\nConsole.WriteLine("Recieved...");\nusing (var sw = new StreamWriter("output.txt"))\n{\n    for (int i = 0; i < k; i++)\n    {\n        Console.Write(Convert.ToChar(b[i]));\n        sw.Write(Convert.ToChar(b[i]));\n    }\n}	0
6094092	6020406	Travel through pixels in BMP	Bitmap bmp = new Bitmap("SomeImage");\n\n// Lock the bitmap's bits.  \nRectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\nBitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);\n\n// Get the address of the first line.\nIntPtr ptr = bmpData.Scan0;\n\n// Declare an array to hold the bytes of the bitmap.\nint bytes = bmpData.Stride * bmp.Height;\nbyte[] rgbValues = new byte[bytes];\nbyte[] r = new byte[bytes / 3];\nbyte[] g = new byte[bytes / 3];\nbyte[] b = new byte[bytes / 3];\n\n// Copy the RGB values into the array.\nMarshal.Copy(ptr, rgbValues, 0, bytes);\n\nint count = 0;\nint stride = bmpData.Stride;\n\nfor (int column = 0; column < bmpData.Height; column++)\n{\n    for (int row = 0; row < bmpData.Width; row++)\n    {\n        b[count] = (byte)(rgbValues[(column * stride) + (row * 3)]);\n        g[count] = (byte)(rgbValues[(column * stride) + (row * 3) + 1]);\n        r[count++] = (byte)(rgbValues[(column * stride) + (row * 3) + 2]);\n    }\n}	0
19804534	19804508	How can I read single xml node	//value[text()='Username']/preceding-sibling::id	0
6857597	6857379	how to use the round maths function in asp.net?	int number;\nbool result = Int32.TryParse(rounded, out number);\nif (result)\n{\n    // Your number will contain the number with no leading 0\n}\nelse\n{\n    // Then you have a float.\n}	0
24156717	24156385	Global Configuration in Windows Forms	public static final class Configuration\n{\n    private static string m_setting1;\n    private static bool m_setting2;\n\n    static Configuration()\n    {\n        // Read all settings\n        ...\n    }\n\n    public static string Setting1\n    {\n        get { return m_setting1; }\n        set\n        {\n            if (!m_setting1.Equals(value))\n            {\n                m_setting1 = value;\n                StoreSettings();\n            }\n        }\n    }\n\n    public static bool Setting2\n    {\n        get { rteurn m_setting2; }\n        set\n        {\n            if (!m_setting2 == value)\n            {\n                m_setting2 = value;\n                StoreSettings();\n            }\n        }\n    }	0
8413713	8413649	XDocument Decendants with Namespaces	XNamespace ns = "urn:CueListSchema.xml";\nvar events = doc.Descendants(ns + "Event");	0
22436824	22436690	String to Same Byte Array	s\n.Split('-')\n.Select(part => byte.Parse(part, System.Globalization.NumberStyles.HexNumber))\n.ToArray();	0
21182313	20743256	How to decrypt raw soap response encrypted with x509	try\n{\n    // http://msdn.microsoft.com/en-us/library/aa529137.aspx\n    XmlDocument response = new XmlDocument();\n    response.Load("Response.xml");\n    var encryptedKeyElement = response.GetElementsByTagName("xenc:EncryptedKey")[0] as XmlElement;\n    var encryptedDataElement = response.GetElementsByTagName("xenc:EncryptedData")[0] as XmlElement;\n\n    EncryptedKey encryptedKey = new EncryptedKey(encryptedKeyElement);\n    EncryptedData data = new EncryptedData(encryptedDataElement, encryptedKey);\n\n    var decryptedData = data.Decrypt();\n}\ncatch (Exception ex)\n{\n    Console.WriteLine(ex.ToString());\n    Console.WriteLine("Press any key to exit");\n    Console.Read();\n}	0
11956892	11956780	Convert numeric sequences to ranges	IEnumerable<string> Rangify(IList<int> input) {\n    for (int i = 0; i < input.Count; ) {\n        var start = input[i];\n        int size = 1;\n        while (++i < input.Count && input[i] == start + size)\n            size++;\n\n        if (size == 1)\n            yield return start.ToString();\n        else if (size == 2) {\n            yield return start.ToString();\n            yield return (start + 1).ToString();\n        } else if (size > 2)\n            yield return start + " - " + (start + size - 1);\n    }\n}	0
13410829	13410785	Count the no of keys in appconfig in a class file	var appSettings = System.Configuration.ConfigurationManager.AppSettings;\n int cntAppSettingKeys = appSettings.Count;	0
33262812	33262657	Modify text box without moving cursor	private void txtWeight_TextChanged(object sender, EventArgs e)\n{\n    decimal enteredWeight;\n    if (Decimal.TryParse(txtWeight.Text, out enteredWeight))\n    {\n        decimal roundedWeight = RoundDown(enteredWeight, 1);\n        if (enteredWeight != roundedWeight)\n        {\n            int caretPos = txtWeight.SelectionStart;\n            txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");\n            txtWeight.SelectionStart = caretPos;\n        }\n    }\n}	0
6534124	6512228	MongoDBRef how to write a query	var refDocument = new BsonDocument { \n            {"$ref", "userdata"}, \n            {"$id", usr._id} \n        }; \nvar query = Query.EQ("usr", refDocument); \nvar result = userDataCollection.FindOne(query);	0
28440021	28419211	Semantic zoom - tap item to navigate to specific page	void GridView_ItemClicked(object sender, ItemClickEventArgs args)\n{\n    var item = (Item)args.ClickedItem;\n\n    if (item.Link == "/Page_1.xaml")\n        ((Frame)Window.Current.Content).Navigate(typeof (Page_1));\n    else if (item.Link == "/Page_2.xaml")\n        ((Frame)Window.Current.Content).Navigate(typeof (Page_2));\n    else if (item.Link == "/Page_3.xaml")\n        ((Frame)Window.Current.Content).Navigate(typeof (Page_3));\n}	0
3068777	3068628	How to find the data key on CheckedChanged event of checkbox in ListView in ASP.NET?	protected void chkFocusArea_CheckedChanged(object sender, EventArgs e)  \n{  \n    CheckBox cb = (CheckBox)sender;  \n    ListViewItem item = (ListViewItem)cb.NamingContainer; \n    ListViewDataItem dataItem = (ListViewDataItem)item ;\n    string code = ListView1.DataKeys[dataItem.DisplayIndex].Value.ToString();\n}	0
18358680	18358534	Send inline image in email	string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";\n AlternateView avHtml = AlternateView.CreateAlternateViewFromString\n    (htmlBody, null, MediaTypeNames.Text.Html);\n\n LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);\n inline.ContentId = Guid.NewGuid().ToString();\n avHtml.LinkedResources.Add(inline);\n\n MailMessage mail = new MailMessage();\n mail.AlternateViews.Add(avHtml);\n\n Attachment att = new Attachment(filePath);\n att.ContentDisposition.Inline = true;\n\n mail.From = from_email;\n mail.To.Add(data.email);\n mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";\n mail.Body = String.Format(\n            "<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +\n            @"<img src=""cid:{0}"" />", inline.ContentId);\n\n mail.IsBodyHtml = true;\n mail.Attachments.Add(att);	0
17526087	17526015	Downloading a large table of data from a MySQL Database to text file in C#	for (int i=0; i<=numberOfRowsInYourTable ; i=i+1000){\n      command.CommandText = "SELECT * FROM `DB`.`TABLE` LIMIT " + i + " " + new String(i + 1000);\n      // Do what you want\n }	0
8590869	8590778	Getting actual text in freetextbox control	Your_FreeTextBox.HtmlStrippedText	0
29872650	29872522	How to customize CreateUserWizard to get UserId and UserName values?	MembershipUser newUser = Membership.GetUser(NewUserWizard.UserName);\n    Guid newUserId = (Guid)newUser.ProviderUserKey;	0
28025361	28025182	how to correctly download multiple file faster and asynchronous?	ServicePointManager.DefaultConnectionLimit	0
1973001	1972964	Run a code in given time interval	int startin = 60 - DateTime.Now.Second;\nvar t = new System.Threading.Timer(o => Console.WriteLine("Hello"), \n     null, startin * 1000, 60000);	0
11485774	11485377	Linking Textboxes to a dataset using a BindingSource	uxDescriptionTextBox.DataBindings.Add("Text", \n                                      definitionsBindingSource,\n                                      fieldInTable);	0
24222663	24221964	How do I add all EntityTypeConfiguration<> from current assembly automatically?	modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);	0
1524388	1524367	N-layered database application without using an ORM, how does the UI specify what it needs of data to display?	UI <-- (viewmodel) ---> BLL <-- (model) --> Peristence/Data layers	0
14004390	14004252	Determine if one of three fields has any of a list of keywords	var entriesSet = new HashSet<string>(foo.Something.Split());\nentriesSet.UnionWith(foo.SomethingElse.Split());\nentriesSet.UnionWith(foo.AnotherThing.Split());\n\nif (entriesSet.Overlaps(keywords)) {\n    ...\n}	0
15291470	15291297	Regex - Improve search and add third group	\[(?<type>[Ccds])(:(?<a>[\d]+)(-(?<b>[\d]+))?)?\]	0
2656971	2656921	How to convert SPFieldNumber into an int	Convert.ToInt32(MySPFieldNumber.GetFieldValue());\nConvert.ToInt32(MySPFieldNumber.GetFieldValueAsText());	0
760424	760395	C#: How to add a line to a memo?	RichBox1.AppendText( "the line I'd like to add" + Environment.NewLine );	0
3211190	3211158	how to connect my combox with textbox	if (comboBox.SelectedItem == null) \n{\n   textBox.Text = string.Empty; //or any default value\n   return;\n}\ntextBox.Text = comboBox.SelectedValue.ToString();	0
27763861	27763724	WPF BackgroundWorker while main window loading	this.Dispatcher.Invoke	0
447440	447199	Generic method for reading config sections	Configuration configFile = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);\n    XmlDocument document = new XmlDocument();\n    document.Load(configFile.FilePath);\n    foreach (XmlNode node in document.SelectNodes("//add"))\n    {\n        string key = node.SelectSingleNode("@key").Value;\n        string value = node.SelectSingleNode("@value").Value;\n        Console.WriteLine("{0} = {1}", key, value);\n    }	0
28748610	28748185	Custom DateTime serialization/deserialization using DataContractJsonSerializer	var serializer = new DataContractJsonSerializer(\n    typeof(Client),\n    new DataContractJsonSerializerSettings {\n        DateTimeFormat = new DateTimeFormat("yyyy-mm-dd hh:MM:ss"),\n    });	0
6236396	6236341	dynamically set value of DataKeyNames in gridview	protected void Page_Load(object sender, EventArgs e)\n\n{\n    d = new GridView();\n\n    d.DataKeyNames = new string[] { "Column1", "Column2" };\n    form1.Controls.Add(d);\n}	0
22312411	22312348	tsql in lambda - select count group by	var result = ctx.tbl_usuarios_online.GroupBy(x => x.int_page)\n                                    .Select(group => new { total = group.count(), \n                                                           int_page = group.Key })\n                                    .OrderByDescending(y => y.total);	0
13670342	13669657	Image fading while using custom method for rotation	static int someInt = 5;\nBitmap bmp = new Bitmap(@"someImage.jpg");\nprivate void button2_Click(object sender, EventArgs e)\n{\n      pictureBox1.Image = RotateImage(bmp, someInt);\n      someInt = (someInt + 5) % 360;\n}	0
22071261	22071144	How effective get n bits, starting from startPos from the UInt64 Number	// assuming bit numbers start with 0, and that\n// startPos is the position of the desired\n// least-significant (lowest numbered) bit\n\npublic static ulong GetBits( ulong value, int startPos, int bits )\n{\n    ulong mask = ( ( 1UL << bits ) - 1 ) << startPos;\n    return ( value & mask ) >> startPos;\n}	0
24930973	24930510	Insert HTML tags in TextBlock	RTBOX.Inlines.Add("hello ");\n        Run run = new Run("my ");         \n        run.FontWeight = FontWeights.Bold;\n        Run run1 = new Run("faithfull\n ");\n        Run run2 = new Run("sdsf ");\n        Run run3 = new Run("Computer");           \n        run3.TextDecorations = TextDecorations.Underline;\n\n        Run run4 = new Run(" You rock !");\n        run4.FontStyle = FontStyles.Italic;\n\n        RTBOX.Inlines.Add(run);\n        RTBOX.Inlines.Add(run1);\n        RTBOX.Inlines.Add(run2);\n        RTBOX.Inlines.Add(run3);\n        RTBOX.Inlines.Add(run4);	0
15811930	15549593	How to work reliably with XmlReader	if (xml.IsStartElement("Results"))\n{\n    // Be careful so that the cursor will be left after the closing tag of the 'Results' element, even if Results.FromXml throws.\n\n    using (XmlReader resultsElement = xml.ReadSubtree())\n    {\n        resultsElement.Read();\n        try \n        {\n            results = Results.FromXml(resultsElement);\n        }\n        catch (Exception e)\n        {\n            Console.Error.WriteLine("Reading results xml went wrong {0}", e.Message);\n        }\n    }\n\n    xml.ReadEndElement("Results");\n}	0
9091385	9091336	get sum of the same element from the list	List<KeyValuePair<string, int>> test = new List<KeyValuePair<string, int>>();\ntest.Add(new KeyValuePair<string,int>("One",5));\ntest.Add(new KeyValuePair<string,int>("Second",5));\ntest.Add(new KeyValuePair<string,int>("Third",5));\ntest.Add(new KeyValuePair<string,int>("One",5));\ntest.Add(new KeyValuePair<string,int>("One",5));\ntest.Add(new KeyValuePair<string,int>("Second",5));\n\nvar result = test.GroupBy(r => r.Key).Select(r => new KeyValuePair<string, int>(r.Key, r.Sum(p => p.Value))).ToList();	0
20290242	19926870	EntityFramework Insert into Oracle table with a sequence as PK	create or replace \ntrigger SEQ_ADDRESS_RESOLVER_ID  \n   before insert on "MY_DB"."ADDRESS_RESOLVER" \n   for each row \nbegin  \n   if inserting then \n      if NVL(:NEW."ID", 0) = 0 then \n         select SEQ_ADDRESS_RESOLVER.nextval into :NEW."ID" from dual; \n      end if; \n   end if; \nend;	0
3964104	3964075	How can I condense the following Linq query into one IQueryable	orgNames = context.Users.Where(u => u.LoweredUserName == userName.ToLower())\n                .Take(1)\n                .SelectMany(u => u.Organisations)\n                .Select(o => o.Name);	0
26393248	26389147	c# Bring Folder Browser Dialog to Foreground	protected override void OnLoad(EventArgs e) {\n        folderBrowserDialog1.ShowDialog();\n        folderBrowserDialog2.ShowDialog();   // can't see this one\n        base.OnLoad(e);\n    }	0
29259147	29258752	How to remove highlight of a selected row (or cell) in a wpf datagrid using code behind	dataGrid.Resources.Add(SystemColors.HighlightBrushKey, "#FF0000");	0
13619189	13619056	data binding for gridview	string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString;	0
21447443	21447136	Download from byte array from CRM	Response.OutputStream..Write(fileContent , 0, fileContent .Length);	0
6431031	6430944	Use reflection to get the value of a property by name in a class instance	var myPropInfo = myType.GetProperty("MyProperty");\nvar myValue = myPropInfo.GetValue(myInstance, null);	0
18049220	18049170	Pass name of button to click event	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    var button = sender as Button;\n    button.Name\n}	0
14268841	14268511	Transforming a sequence of events into a more granular sequence of values	SelectMany(lines => lines)\n.Subscribe(Observer.Create<string>(line => { Console.WriteLine("new line = {0}", line); });	0
739136	739101	Launching process in C# Without Distracting Console Window	Process process = new Process();\n\n// Stop the process from opening a new window\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.CreateNoWindow = true;\n\n// Setup executable and parameters\nprocess.StartInfo.FileName = @"c:\test.exe"\nprocess.StartInfo.Arguments = "--test";\n\n// Go\nprocess.Start();	0
10092950	10092093	Upload string contents into google doc	DocumentsService service = new DocumentsService("MyApp");\n\n// TODO: Authorize the service object\n\nStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes("This is the document content"));\n\nDocumentEntry entry = service.Insert(new Uri(DocumentsListQuery.documentsBaseUri), stream, "text/plain", "Document title") as DocumentEntry;	0
31478435	31477686	How to select items in a ListView?	FileListView.Select()	0
22645737	22645723	convert Dictionary<String, double> to Dictionary<String, float> using Linq	var newdict = original.ToDictionary(kvp => kvp.Key, kvp => (float)kvp.Value);	0
3132321	3094191	How to add "Privacy" details in Google Calendar using Google API Version 2	EventEntry.EventVisibility	0
16891785	16734299	Dynamically change log target file using Enterprise Logging	Attribute["filename"]	0
22669215	22669044	C# how to get the Index of second comma in a string	int index = s.IndexOf(',', s.IndexOf(',') + 1);	0
16662273	16660330	Trying to launch a file in an anonymous delegate tied to a toast event fails (C# Winrt)	TypedEventHandler<ToastNotification, object> openPic =\n    async delegate(ToastNotification toastSender, object toastArgs)\n    {\n        Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, \n            () => var success = await Launcher.LaunchFileAsync(destinationFile);\n    };	0
9705230	9705188	Programmatically add file association without admin rights in C#	HKCU\Software\Classes	0
5692728	5692717	Get size of MySqlDbType	int x = sizeof(MySqlDbType);	0
10544995	10539189	Merging two datatable in memory and grouping them to get sum of columns.Using linq but kind of lost here	table1.Merge(table2, true, MissingSchemaAction.Add);\nfinalTable = table1.Clone();\nfinalTable.PrimaryKey = new DataColumn[] { finalTable.Columns["ID"], finalTable.Columns["Name"] };\nList<string> columnNames = new List<string>();\nfor (int colIndex = 2; colIndex < finalTable.Columns.Count; colIndex++)\n{\ncolumnNames.Add(finalTable.Columns[colIndex].ColumnName);\n}\nforeach (string cols in columnNames)\n{\nvar temTable = new DataTable();\ntemTable.Columns.Add("ID", typeof(int));\ntemTable.Columns.Add("Name", typeof(string));\ntemTable.Columns.Add(cols, typeof(decimal));\n\n(from row in table1.AsEnumerable()\ngroup row by new { ID = row.Field<int>("ID"), Team = row.Field<string>("Team") } into grp\norderby grp.Key.ID\nselect new\n{\nID = grp.Key.ID,\nName = grp.Key.Team,\ncols = grp.Sum(r =>  r.Field<decimal?>(cols)),\n})\n.Aggregate(temTable, (dt, r) => { dt.Rows.Add(r.ID, r.Team, r.cols); return dt; });\n\nfinalTable.Merge(temTable, false, MissingSchemaAction.Ignore);\n}	0
12708146	12707763	Get indexes for intersection	var intersectedIndices =\n    from x in Enumerable.Range(0, tilesCountX)\n    from y in Enumerable.Range(0, tilesCountY)\n    where EnvIntersects(extents[x, y], bounds)\n    select new { x, y };	0
5018493	5015678	301 Redirect with unicode characters - C#	Response.Clear();\nResponse.Status = "301 Moved Permanently";\nResponse.AddHeader("Location", uri.Scheme + "://" + uri.DnsSafeHost + uri.PathAndQuery + uri.Fragment);\nResponse.End();	0
13107261	13107128	Easiest Way to Store Scraped Data	[Serializable]\npublic class MyDataStorage\n{\n    // some members\n\n    public void Store( String filename )\n    {\n        XmlSerializer serializer = new XmlSerializer( typeof( MyDataStorage ) );\n        using ( FileStream stream = File.OpenWrite( filename ) )\n        {\n            serializer.Serialize( stream, this );\n        }\n    }\n\n    public static MyDataStorage Load(String filename )\n    {\n        XmlSerializer serializer = new XmlSerializer( typeof( MyDataStorage ) );\n        object deserialized;\n        using ( FileStream stream = File.OpenRead( filename ) )\n        {\n            deserialized = serializer.Deserialize( stream );\n        }\n\n        return (MyDataStorage) deserialized;\n    }\n}	0
12872052	12871997	Getting sub elements using LINQ and XML in C#	var placemarks = xdoc.Descendants(ns + "Placemark")\n                            .Select(p => new\n                            {\n                                Name = p.Element(ns + "name").Value,\n                                Desc = p.Element(ns + "description").Value,\n                                Coord = p.Descendants(ns + "coordinates")\n                                         .First().Value\n                            })\n                            .ToList();	0
11307372	11296498	XML Encoding for French and german characters	encoding="Windows-1252"	0
8627588	8627519	How to eliminate items from listbox when textbox changed	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        for (int i = 0; i < listBox1.Items.Count; i++)\n        {\n            string item = listBox1.Items[i].ToString();\n            foreach(char theChar in textBox1.Text)\n            {\n                if(item.Contains(theChar))\n                {\n                    //remove the item, consider the next list box item\n                    //the new list box item index would still be i\n                    listBox1.Items.Remove(item);\n                    i--;\n                    break;\n                }\n            }\n        }\n    }	0
2411958	2411894	Handling null values in where clause using LINQ-to-SQL	where object.Equals(t.IdRole, access.IdRole)	0
4434789	3853931	binding two different transforms together in silverlight 4	TranslateTransform trans = new TranslateTransform();\nline.TextChannelName.RenderTransform = trans; \n\nBinding transBind = new Binding("Value"); \ntransBind.Source = ((CompositeTransform)SchedulePanel.RenderTransform); \nBindingOperations.SetBinding(trans, TranslateTransform.XProperty, transBind);	0
10299625	10299013	Change Xml Declaration, or select xml without declaration section	XmlElement element = doc.DocumentElement;\n            XmlDeclaration xmlDeclaration;\n            xmlDeclaration = doc.CreateXmlDeclaration("1.0", "iso-8859-1", null);\n            doc.ReplaceChild(xmlDeclaration, doc.FirstChild);	0
2780087	2780023	Find and Replace a section of a string with wildcard type search	content = Regex.Replace(content, @"M9(S\d{4})\.\d", "$1");	0
5096556	5096508	IQueryable<T> cast to IList<SpecificInterface>	return new GridModel(table.ToList().ConvertAll(x => (ITable)x));	0
1247131	1246938	.NET TreeView control with checkboxes	private Image CreateCheckBoxGlyph(CheckBoxState state)\n{\n    Bitmap Result = new Bitmap(imlCheck.ImageSize.Width, imlCheck.ImageSize.Height);\n    using (Graphics g = Graphics.FromImage(Result))\n    {\n        Size GlyphSize = CheckBoxRenderer.GetGlyphSize(g, state);\n        CheckBoxRenderer.DrawCheckBox(g,\n          new Point((Result.Width - GlyphSize.Width) / 2, (Result.Height - GlyphSize.Height) / 2), state);\n    }\n    return Result;\n}	0
31453412	31453195	How to compare two connectingstrings in C#	var zipcodeConnection = (ConfigurationManager.ConnectionStrings["BAG_Zipcodes"])\n                      ?? ConfigurationManager.ConnectionStrings[DbSchema.DefaultConnectionName];	0
3143682	3143626	How can I check if two different URL's point to the same resource?	URI.Host	0
2559713	2559665	Can't send smtp email from network using C#, asp.net website	private void SendEmail(string from, string to, string subject, string body)\n    {\n      MailMessage mail = new MailMessage(new MailAddress(from), new MailAddress(to));\n\n      mail.Subject = subject;\n      mail.Body = body; \n\n      SmtpClient smtpMail = new SmtpClient("smtp.gmail.com");\n      smtpMail.Port = 587;\n      smtpMail.EnableSsl = true;\n      smtpMail.Credentials = new NetworkCredential("xxx@gmail.com", "xxx");\n      // and then send the mail\n      smtpMail.Send(mail);\n    }	0
14885049	14867114	Unable to SetFocus on a dynamically created text box	window.onload = function () {\n                                      FindWhichTextBoxIsEmpty();\n                                    }\n    function FindWhichTextBoxIsEmpty() {\n        var tableSerial = document.getElementById('tbl_Serial');\n\n        for (var i = 0; i < tableSerial.rows.length-1; i++) {\n\n            var ID = i.toString() + "_RowTbx";\n            if (document.getElementById(ID).value!="") {\n                var tb = document.getElementById(ID).value;\n                if (tb != "") {\n                              if (i + 1 < tableSerial.rows.length-1) {\n                             var nextID = (i + 1).toString() + "_RowTbx";\n                             document.getElementById(nextID).focus();\n                    }\n                }\n            }\n        }\n\n    }	0
2403126	2403062	Finding the best folder for all users on a Windows machine	Environment.SpecialFolder.CommonDocuments	0
3789806	3789768	Help with mapping ActionLinks to Methods in Controllers (ASP.NET MVC2)	[AcceptVerbs(HttpVerbs.Post)]	0
7873050	7872516	How can i use SetLocaleinfo()	// Put the using statements at the beginning of the code module\nusing System.Threading;\nusing System.Globalization;\n// Put the following code before InitializeComponent()\n// Sets the culture to French (France)\nThread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");\n// Sets the UI culture to French (France)\nThread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");	0
15636791	14624964	how to get month wise data in datagridview with local datatable in c#	var formatPattern = "dd MMM yyyy hh mm ss";\nDateTime parsedDate;\nvar culture = System.Globalization.CultureInfo.InvariantCulture; // use CurentCulture if you want to use the current culture instead which might change\nbool success = DateTime.TryParseExact(dtmDate.Text, formatPattern, culture, DateTimeStyles.None, out parsedDate);\nif (success)	0
9576292	9575953	returning custom error message for multiple variables	public ActionResult Validate(string fName, string lName, string sId)\n{    \n     string result = "";\n\n     if (fName <> Data.GetFristName(fName))\n     {\n        result = result + fName;\n     }\n     if (lName <> Data.GetFristName(lName))\n     {         \n       result = result + lName );\n     }\n     if (sId <> Data.GetFristName(sId))\n     {\n        result = result + sId;\n     }\n\n    return "Following Items were not found: " + result;\n}	0
20570426	20570148	WPF MVVM hiding button using BooleanToVisibilityConverter	Visibility="{Binding ButtCancel, Converter={StaticResource BoolToVis}, FallbackValue=Hidden}"	0
23944442	23941768	how do I append a cdn url to image tags?	using HtmlAgilityPack;\n...\nprivate string AppendCdnToImgSrc(string htmlString)\n{\n    HtmlDocument htmlDoc = new HtmlDocument();\n    htmlDoc.LoadHtml(htmlString); // or htmlDoc.Load(htmlFileName) if a file\n\n    foreach(HtmlNode img in doc.DocumentElement.SelectNodes("//img[@src]")\n    {\n        HtmlAttribute attribute = img["src"];\n        attribute.Value = attribute.Value + ".cdn";\n    }\n\n    // return string output...\n    MemoryStream memStream = new MemoryStream();\n    htmlDoc.Save(memStream)\n    memStream.Seek(0, System.IO.SeekOrigin.Begin);\n    StreamReader reader = new StreamReader(memStream);\n    return reader.ReadToEnd();\n}	0
25026287	25026239	Delete row in DGV if int is incremented?	for (rows = CView.dgvCreate.Rows.Count - 1; rows >= 0 ; rows--)	0
9910759	9910580	C# WCF using messages from client	client.RegisterUser(ref message.time, ref message.user)	0
4253318	4253270	C# How to convert String into Time format used for Time Range?	//System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("C:\\Test\\ntfs2.txt");\n    String value = "Thu Mar 02 1995 21:31:00,2245107,m...,r/rrwxrwxrwx,0,0,8349-128-3,C:/Program Files/AccessData/AccessData Forensic Toolkit/Program/wordnet/Adj.dat";\n\n    String[] token = value.Split(',');\n\n    String[] datetime = token[0].Split(' ');\n\n    String timeText = datetime[4]; // The String array contans 21:31:00\n\n    DateTime time = Convert.ToDateTime(timeText); // Converts only the time\n\n    Console.WriteLine(time.ToString("HH:mm:ss"));	0
12598830	12598766	C# Winform How to Generate fix character?	// automatically pads the number with up to 8 leading zeros\ncTag = numTag.ToString("X8");	0
25414601	25414399	Convert Bitmap to OpenCvSharp IplImage	var frm = cap.QueryFrame(); // this is an Emgu.CV.Image object\n            var frameBmp = frm.Bitmap; // this is the bitmap from that object\n\n            Frame = new IplImage(frameBmp.Width, frameBmp.Height, BitDepth.U8, 3);  //creates the OpenCvSharp IplImage;\n            Frame.CopyFrom(frameBmp); // copies the bitmap data to the IplImage	0
25932711	25932454	How do I do simple Many To Many in EF 5	var result = from a in db.TableA\n             join ab in db.TableAB on a.AID equals ab.AID\n             join b in db.TableB on ab.BID equals b.BID\n             where a.AID == 5\n             select b;	0
16039458	16035906	Monitoring app in c#	var si = new STARTUPINFO();\nsi.cb = Marshal.SizeOf(si);\nsi.lpDesktop = "Winsta0\\default";//this is the user's desktop.	0
7622830	7622818	How do I convert a DateTime object to a string with just the date using C#?	string startdate = beginningDate.ToShortDateString ();	0
10836449	10836260	Starting a Windows Service programmatically	System.ServiceProcess.ServiceController	0
17653719	17653633	Uninstall EntityFramework using the Package Manager Console	packages.config	0
9438513	9412781	How to disable Chart axis autosize	chart.ChartAreas[0].AxisY.Minimum = 0;\nchart.ChartAreas[0].AxisY.Maximum = 10;	0
13414825	13414675	C# Windows Store App - Find resource on xaml	FindName("cellText_" + identifier);	0
23861229	23860904	How to access code generated child elements?	private void myStackPanel_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    StackPanel myPanel = sender as StackPanel;\n    Label myLabel;\n    foreach(object o in myPanel.Children)\n    {\n        if (child is Label)\n        {\n            myLabel = o as Label;\n            //do something with label\n        }\n    }\n}	0
22825052	22824210	How can I create a unique activation code?	private string CreateActivationKey()\n{\n    string activationKey = Guid.NewGuid().ToString();\n\n    bool activationKeyAlreadyExists = \n     mobileDeviceService.GetActivationKeys().Any(key => key == activationKey);\n\n    if (activationKeyAlreadyExists)\n    {\n        activationKey = CreateActivationKey();\n    }\n\n    return activationKey;\n}	0
6926838	6926752	Retrieve rows, return only user selected columns from the list	var result = datacontext.ExecuteQuery(myQuery);	0
811839	811693	How can I display text beside each radiobutton when loading a radiobutton list from an enumeration?	public enum AutomotiveTypes\n{\n    Car,\n    Truck,\n    Van,\n    Train,\n    Plane\n}\n\npublic partial class _Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        string[] automotiveTypeNames = Enum.GetNames(typeof(AutomotiveTypes));\n\n        RadioButtonList1.RepeatDirection = RepeatDirection.Vertical;\n\n        RadioButtonList1.DataSource = automotiveTypeNames;\n        RadioButtonList1.DataBind();\n    }\n}	0
10563676	10563650	Simplest way to pass an xml file as  a store procedure parameter using  c#	System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(string);	0
10640408	10640380	How to do this on one line?	var pagedResponsesList = responseService.ListSurveyResponses(1000).ResultData;	0
14667257	14667234	How can I enter multiple doubles into a textbox separated by commas and store in an Array which holds doubles?	var yArray = textBox1.Text\n                     .Split(',')\n                     .Select(m => Double.Parse(m.Trim()))\n                     .ToArray();	0
917003	916904	How to I get the property belonging to a custom attribute?	PropertyInfo propertyInfo = typeof(MyType).GetProperty("MyProperty");\n\nObject[] attribute = propertyInfo.GetCustomAttributes(typeof(MyAttribute), true);\n\nif (attribute.Length > 0)\n{\n    MyAttribute myAttribute = (MyAttribute) attributes[0];\n\n    // Inject the type of the property.\n    myAttribute.PropertyType = propertyInfo.PropertyType;\n\n    // Or inject the complete property info.\n    myAttribute.PropertyInfo = propertyInfo;\n}	0
14097791	14063191	checking a color of a button and changing it using a 2D array	Button b = sender as Button;\n        string[] btnData = b.Name.Split('_');\n        int x = int.Parse(btnData[1]);\n        int y = int.Parse(btnData[2]);\n\n        //check for possible combinations \n        int top = y - 2;\n        int botton = y + 2;\n\n        int left = x - 2;\n        int right = x + 2;\n\n        if (top >= 0 && squares[top, y].Background == Color.Black)\n        {\n            squares[top+1, y].Background = Color.Black;\n        }  \n        ...  \n        ...	0
4427908	4427861	enumerate all of property and its value	PropertyInfo[] info = strList.GetType().GetProperties();\n\n        Dictionary<string, object> propNamesAndValues = new Dictionary<string, object>();\n\n        foreach (PropertyInfo pinfo in info)\n        {\n            propNamesAndValues.Add(pinfo.Name, pinfo.GetValue(strList, null));\n        }	0
11724340	11724110	Trying to pass calculated values to a view without a controller	public virtual MailMessage EMailQuote(QuoteData model)\n{\n    var mailMessage = new MailMessage { Subject = "..." };\n\n    mailMessage.To.Add(model.Step.EMail);\n    mailMessage.To.Add("web@site.com");\n\n    ViewData.Model = model;\n    PopulateBody(mailMessage, viewName: "EMailQuote");\n\n    return mailMessage;\n}	0
15839754	15839734	Is there a way to read the command line parameters from a library?	string[] args = Environment.GetCommandLineArgs();	0
13803137	13802916	How do I only show data by filtering the properties in a WPF ListView?	ICollectionView view = CollectionViewSource.GetDefaultView(lstMovies.ItemsSource);  \nview.Filter = null;  \nview.Filter = new Predicate<object>(FilterMovieItem);  \n\n\nprivate bool FilterMovieItem(object obj)  \n{  \n    MovieItem item = obj as MovieItem;  \n    if (item == null) return false;  \n\n    string textFilter = txtFilter.Text;  \n\n    if (textFilter.Trim().Length == 0) return true; // the filter is empty - pass all items  \n\n    // apply the filter  \n    if (item.MovieName.ToLower().Contains(textFilter.ToLower())) return true;  \n    return false;  \n}	0
3840727	3840616	Conversion of Inteface from vb.net to c#	class MyControl : Control, IServiceProvider\n{\n     object IServiceProvider.GetService(Type t)\n     {\n         ...\n     }\n}	0
6516246	6516222	How to write data on multiple lines BUT within the same cell of csv?	1997,Ford,E350,"Go get one now\nthey are going fast"	0
26530645	13005112	How to activate combobox on first click (Datagridview)	private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        bool validRow = (e.RowIndex != -1); //Make sure the clicked row isn't the header.\n        var datagridview = sender as DataGridView;\n\n        // Check to make sure the cell clicked is the cell containing the combobox \n        if(datagridview.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && validRow)\n        {\n            datagridview.BeginEdit(true);\n            ((ComboBox)datagridview.EditingControl).DroppedDown = true;\n        }\n    }	0
3648298	3648280	C# - Suggestions of control statement needed	for (int i = 0; i < x; i++)\n{\n  for ( int j = 0; j < x; j++ )\n  {\n    Console.Write("*");\n  }\n  Console.WriteLine();\n}	0
8647960	8647465	Resolving generics with interface as type parameter in Autofac	public interface ITestService<T>\n{\n}\n\npublic class TestService<T> : ITestService<T>\n{\n}\n\npublic interface ITest<T>\n{\n  ITestService<T> TestService { get; }\n}\n\npublic class Test<T> : ITest<T>\n{\n  readonly ITestService<T> _TestService;\n\n  public Test(ITestService<T> testService)\n  {\n    _TestService = testService;\n  }\n\n  public ITestService<T>\n  {\n    get\n    {\n      return this._TestService;\n    }\n  }\n}\n\nbuilder.RegisterGeneric(typeof(TestService<>)).As(typeof(ITestService<>)).InstancePerLifetimeScope();\nbuilder.RegisterGeneric(typeof(Test<>)).As(typeof(ITest<>)).InstancePerLifetimeScope();\n...\n\n_componentContext.Resolve<ITest<TNodeToNodeConnectorRecord>>();\n\n// if you need to specify the ITestService type to use:\nvar testService = _componentContext.Resolve<TestService<TNodeToNodeConnectorRecord>>();\nvar test = _componentContext.Resolve<Func<ITestService<TNodeToNodeConnectorRecord>, ITest<TNodeToNodeConnectorRecord>>>()(testService);	0
22486527	22486048	Drawing a rectangle around a toolStripMenuItem	void toolStripButton1_Paint(object sender, PaintEventArgs e) {\n  e.Graphics.DrawRectangle(Pens.Red, toolStripButton1.ContentRectangle);\n}	0
141032	141007	Creating a XAML Resource from Code Without a Key	HierarchicalDataTemplate fieldPropertyTemplate = new \n    HierarchicalDataTemplate("FieldProperyInfo");\n\nfieldPropertyTemplate.SetBinding(\n   HierarchialDataTemplate.ItemSourceProperty, \n   new Binding("Value.Values");\nthis.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);	0
17894983	17892249	How to double-decode UTF-8 bytes C#	using System;\nusing System.Text;\n\nclass Test\n{\n    static void Main()\n    {\n        // Avoid encoding issues in the source file itself...\n        string firstLevel = "\u00c3\u00a2\u00c2\u0080\u00c2\u0099";\n        string secondLevel = HackDecode(firstLevel);\n        string thirdLevel = HackDecode(secondLevel);\n        Console.WriteLine("{0:x}", (int) thirdLevel[0]); // 2019\n    }\n\n    // Converts a string to a byte array using ISO-8859-1, then *decodes*\n    // it using UTF-8. Any use of this method indicates broken data to start\n    // with. Ideally, the source of the error should be fixed.\n    static string HackDecode(string input)\n    {\n        byte[] bytes = Encoding.GetEncoding(28591)\n                               .GetBytes(input);\n        return Encoding.UTF8.GetString(bytes);\n    }\n}	0
25148410	25099489	How to Update a Row with Nhibernate	.hbm.xml	0
20963140	20943469	How to get Microphone volume in Windows Phone 8	/// <summary>\n/// Detecting volume changes, the RMS Mothod.\n/// \n/// RMS(Root mean square)\n/// </summary>\n/// <param name="data">RAW datas</param>\n/// <returns></returns>\npublic static void MicrophoneVolume(byte[] data)\n{\n    //RMS Method\n    double rms = 0;\n    ushort byte1 = 0;\n    ushort byte2 = 0;\n    short value = 0;\n    int volume = 0;\n    rms = (short)(byte1 | (byte2 << 8));\n\n    for (int i = 0; i < data.Length - 1; i += 2)\n    {\n        byte1 = data[i];\n        byte2 = data[i + 1];\n\n        value = (short)(byte1 | (byte2 << 8));\n        rms += Math.Pow(value, 2);\n    }\n\n    rms /= (double)(data.Length / 2);\n    volume = (int)Math.Floor(Math.Sqrt(rms));\n}	0
8544712	8544702	OleDbDataReader to ArrayList in C#	while (myReader.Read())\n{\n  list.Add(myReader.GetString(0));\n}	0
1614809	1614072	List of Shapes to Database	/// <summary>use reflection to serialize all properties and type into an xml string</summary>\n/// <param name="s">shape object to be serialized</param>\n/// <return>the serialized xml string</return>\npublic static string SerializeShape(Shape s);\n\n/// <summary>create a new Shape object with given xml data</summary>\n/// <param name="s">xml serialization generated by SerializeShape(Shape s)</param>\n/// <return>the constructed shape</return>\npublic static Shape DeserializeShape(string s);	0
15153928	15153834	How to generalize Removal of " " or ' ' from comma separated values	char[] ch = { '\'', '"'};\norderArray = orderValue.Split(',').Select(x => x.Trim(ch)).ToArray();	0
7268375	7268302	get the titles of all open windows	using System.Diagnostics;\n\nProcess[] processlist = Process.GetProcesses();\n\nforeach (Process process in processlist)\n{\n    if (!String.IsNullOrEmpty(process.MainWindowTitle))\n    {\n        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);\n    }\n}	0
26139627	26139465	How do I set up a nested repetition?	for (int i = n; i > 0; i--)\n{\n    for (int j = 1; j <= i; j = j + 1)\n        Console.Write("+");\n\n    Console.WriteLine();\n}	0
32248471	32248216	How to smoothly transition a panel in WinForms?	protected override CreateParams CreateParams\n{\n    get\n    {\n        const int WS_EX_COMPOSITED = 0x02000000;\n        var cp = base.CreateParams;\n        cp.ExStyle |= WS_EX_COMPOSITED;\n        return cp;\n    }\n}	0
1809350	1809243	How do I install a Windows Service programatically with additional args?	Process.Start("my_service", "-install MY_SERVICE_NAME cmdLine=\"commands in here\"" auxCommands=\"aux commands in here\");\nProcess.Start("net", "start \"My Service (MY_SERVICE_NAME)\"");	0
7333244	7332981	Read from a txt file only lines which starts with a specific string and display them in a form textbox. (C#)	using (var reader = new System.IO.StreamReader(@"C:\file.txt"))\n{\n    while (!reader.EndOfStream)\n    {\n        var line = reader.ReadLine();\n\n        if (line.StartsWith("info"))\n        {\n            // do something\n        }\n    }\n\n    reader.Close();\n}	0
5552213	5552112	C#: Line number on stacktrace points to line with a }	throw new exception(...)	0
24835684	24835654	Assign variable from text	using System;\nusing System.IO;\n\nclass Test \n{\n\n    public static void Main() \n    {\n        string path = @"c:\temp\MyTest.txt";\n        try \n        {\n            using (StreamReader sr = new StreamReader(path)) \n            {\n                while (sr.Peek() >= 0) \n                {\n                    Console.WriteLine(sr.ReadLine());\n\n                }\n            }\n        } \n        catch (Exception e) \n        {\n            Console.WriteLine("The process failed: {0}", e.ToString());\n        }\n    }\n}	0
9531499	9531245	Curious Visual Studio 2010 Debugging Behavior in Windows 7 x64	static void Main()\n{\n    Application.EnableVisualStyles();\n    Application.SetCompatibleTextRenderingDefault(false);\n    ETKSession.DebugMode = false;\n    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);\n    Application.Run(new frmLogin());\n}\n\nstatic void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n{\n    AErrorLogging.Log(ex); //This is a tested error log writer of mine which usually worked.\n    if (ETKSession.DebugMode) throw new Exception(ex.Message, ex);\n}	0
13928321	13928296	Select a specific Item from a list<generic> by one of its variable	GenericClass item = yourList.FirstOrDefault(r=> r.variable3 == "somevalues");	0
26779110	26776948	Display message on button_click	Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted\n\n    Dim htmlBtn As HtmlElement = WebBrowser1.Document.GetElementById("BtnID")\n\n    If htmlBtn IsNot Nothing Then \n        AddHandler htmlBtn.click, AddressOf YourSub\n    End If\n\nEnd Sub\n\nPrivate Sub YourSub()\n    messagebox.show("clicked!")\nEnd Sub	0
30708326	30707887	Create Controls by click Button in runtime in c#	int number;\n    int locationX;\n    int locationY;\n\n    public void CreateRuntimeControl(PictureBox pic)\n    {\n        Label lbl = new Label();\n        number++;\n        locationX++;\n        locationY = locationY + 100;\n        lbl.Name = "lbl" + number.ToString();\n        lbl.Size = new System.Drawing.Size(100, 50);\n        lbl.Location = new System.Drawing.Point(10 + locationX, 10 + locationY);\n        lbl.Text = number.ToString();\n        lbl.BackColor = Color.Gray;\n        pic.Controls.Add(lbl);\n    }	0
5770411	5770162	Changing logging level in log4net xml	log4net.Config.XmlConfigurator.ConfigureAndWatch	0
8245004	8244871	HTMLTextWriter to render elements in the middle of the page	asp:panel	0
8537662	8537439	Unable to get xml node from XElement	List<XElement> xElements = xmlDocument.Descendants(Aw + "name")\n                .Descendants(Aw + "partname")\n                .Descendants(Aw + "typename")\n                .Descendants(Aw + "tyvalue")\n                .Where(x => x.Value == "Last")\n                .ToList();	0
23861174	23861116	Determine the most common elements in an int array	int temp = -1;\nvar mode = numArray.GroupBy(v => v)\n                   .OrderByDescending(g => g.Count())\n                   .TakeWhile(g => {\n                         if(temp == -1)\n                             temp = g.Count();\n                         return temp == g.Count(); })\n                   .Select(g => g.Key)\n                   .ToArray();	0
3916819	3916737	Reading an XML in C#	if (title.ParentNode.LocalName == "entry") { ... }	0
29963652	29963315	html5 multiple select import post to controller one file ASP.NET	[HttpPost]\npublic ActionResult Upload(HttpContext context)\n{\n  for (int files = 0; files < context.Request.Files.Count; files++)\n {\n // Code here\n }\n}	0
17840605	17838494	ListView ContextMenuStrip for column headers	protected override void WndProc(ref System.Windows.Forms.Message m)\n{\n    base.WndProc(ref m);\n    if (m.Msg == 0x7b) {  //WM_CONTEXTMENU\n        if (m.WParam != this.Handle) HeaderContextMenu.Show(Control.MousePosition);\n    }\n}	0
628541	628261	How to draw rounded rectangle with variable width border inside of specific bounds	private void DrawRoundedRectangle(Graphics gfx, Rectangle Bounds, int CornerRadius, Pen DrawPen, Color FillColor)\n{\n    int strokeOffset = Convert.ToInt32(Math.Ceiling(DrawPen.Width));\n    Bounds = Rectangle.Inflate(Bounds, -strokeOffset, -strokeOffset);\n\n    DrawPen.EndCap = DrawPen.StartCap = LineCap.Round;\n\n    GraphicsPath gfxPath = new GraphicsPath();\n    gfxPath.AddArc(Bounds.X, Bounds.Y, CornerRadius, CornerRadius, 180, 90);\n    gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y, CornerRadius, CornerRadius, 270, 90);\n    gfxPath.AddArc(Bounds.X + Bounds.Width - CornerRadius, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 0, 90);\n    gfxPath.AddArc(Bounds.X, Bounds.Y + Bounds.Height - CornerRadius, CornerRadius, CornerRadius, 90, 90);\n    gfxPath.CloseAllFigures();\n\n    gfx.FillPath(new SolidBrush(FillColor), gfxPath);\n    gfx.DrawPath(DrawPen, gfxPath);\n}	0
22105184	22105030	Sum of total hours in decimal	private TimeSpan CalculateDay(TextBox txtIn, TextBox txtOut, Label lbl) {\n    TimeSpan timein, timeout;\n    if (!TimeSpan.TryParse(txtIn.Text, out timein)) \n        timein = default(TimeSpan);\n    if (!TimeSpan.TryParse(txtOut.Text, out timeout)) \n        timeout = default(TimeSpan);\n    lbl.Text = (timeout - timein).TotalHours.ToString("f2");\n    return timeout-timein;\n} \n\nTimeSpan total = CalculateDay(TextBoxInSat1, TextBoxOutSat1, SatLabel1) +  CalculateDay(TextBoxInSun1, TextBoxOutSun1, SunLabel1) +  ...	0
27737956	27729881	Which event fires after all items are loaded and shown in a ListView?	private void Work(){\n    List<Artist> selectedArtistsList;\n    //Code to fill selectedArtistsList with about 6,000 items not shown here\n    CollectionViewSource selection1ViewSource = ((CollectionViewSource)(this.FindResource("selection1Source")));\n    stopWatch1.Reset();\n    stopWatch1.Start();\n    selection1ViewSource.Source = selectedArtistsList;\n    Debug.Print("After setting Source: {0}ms", stopWatch1.ElapsedMilliseconds.ToString());\n\n    //New:\n    Dispatcher.BeginInvoke(new Action(RenderingDone), System.Windows.Threading.DispatcherPriority.ContextIdle, null);\n}\n\n//New\nStopwatch stopWatch1 = new Stopwatch();\nprivate void RenderingDone() {\n    Debug.Print("After rendering is done: {0}ms", stopWatch1.ElapsedMilliseconds.ToString());\n}	0
4108187	4108146	How to show a MessageBox message containing some label content?	MessageBox.Show("Sorry - You Lose, The number is " + label1.Text);	0
21349319	21349197	Get all files from Assets Windows Store Application	ResourceManager.Current.MainResourceMap	0
2449536	2449387	How to get the current open documents in Excel using C#?	//Excel Application Object\nMicrosoft.Office.Interop.Excel.Application oExcelApp;\n\nthis.Activate ( );\n\n//Get reference to Excel.Application from the ROT.\noExcelApp = ( Microsoft.Office.Interop.Excel.Application ) System.Runtime.InteropServices.Marshal.GetActiveObject ( "Excel.Application" );\n\n//Display the name of the object.\nMessageBox.Show ( oExcelApp.ActiveWorkbook.FullName );\n\n//Release the reference.\noExcelApp = null;	0
22453282	22452975	How to make an incremental dynamic code that contains alphabets and numerics	string start = "A9ZZ";\n\n int add = 1;\n string next = String.Concat(start.Reverse().Select((x,i) =>\n {\n      char first = i == 2 ? '0' : 'A';\n      char last  = i == 2 ? '9' : 'Z';\n\n      if ((x += (char)add) > last)\n      {\n          return first;\n      }\n      else\n      {\n          add = 0;\n          return x;\n      }\n })\n .Reverse());	0
21113725	21113589	Pass field of dynamic object as param	var minDate = DateTime.MinValue;\n        var maxDate = DateTime.MaxValue;\n        foreach (var item in data)\n        {\n            switch (item.name)\n            {\n                case CustomFieldConstants.MinDate:\n                    DateTime.TryParse((string)item.value, out minDate);\n                    break;\n                case CustomFieldConstants.MaxDate:\n                    DateTime.TryParse((string)item.value, out maxDate);\n                    break;\n            }\n        }	0
34108994	34108930	How to get specific columnar maximums in List of arrays?	var result = Enumerable.Range(0, XYZarr.Count)\n    .OrderByDescending(i => XYZarr[i][2])\n    .Take(3)\n    .ToList();	0
5652484	5639473	Using Selenium RemoteWebDriver in C#	WebDriver driver = new ChromeDriver();	0
18209153	18209102	Formatting date (time) in a string	lblStartDatePlanned.Content = String.Format("Planned Start Date - {0:HH:mm}", date);	0
466574	466565	switch statement in C# and "a constant value is expected"	Properties.Settings.Default.OU_HomeOffice	0
731613	731589	Value equality comparisons on new objects	10.3. Considering object identity	0
4268544	4268512	Base class with virtual method and only implementing a guard clause	public abstract class BaseMessageObject<T> where T : Entity\n{        \n   public string Message { get; set; }        \n\n   public BaseMessageObject<T> BuildMessage(T entity)\n   {\n        if (null == entity)\n               throw new ArgumentNullException(entity)\n        BuildMessageCore (entity);\n   }\n\n   protected abstract BaseMessageObject<T> BuildMessageCore(T entity);\n}	0
19083744	19058212	How to save images from web in Isolated Storage?	foreach (var item in MyList)\n{\n    Uri uri = new Uri(item.url, UriKind.Absolute);\n    HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;\n    request.BeginGetResponse((ar) =>\n    {\n        var response = request.EndGetResponse(ar);\n        Deployment.Current.Dispatcher.BeginInvoke(() =>\n        {\n            using (var stream = response.GetResponseStream())\n            {\n                var name = GetFileName(item.url);\n                if (localFile.FileExists(name))\n                {\n                    localFile.DeleteFile(name);\n                }\n                using (IsolatedStorageFileStream fs = localFile.CreateFile(name))\n                {\n                    stream.CopyTo(fs);\n                }\n            }\n        });\n    }, null);\n}	0
29708253	29708065	Controlling values in boolean array	void Main()\n{\n    ShowArray();        //[True, True, True, True, True]\n    ChangeValue(1);\n    ShowArray();        //[True, False, True, True, True]\n    ChangeValue(4);\n    ShowArray();        //[True, False, True, True, False]\n    ChangeValue(3);\n    ShowArray();        //[True, False, True, False, False]\n    ChangeValue(0);\n    ShowArray();        //[False, True, True, False, False]\n}\n\nbool[] _array = {true,true,true,true,true};\nQueue<int> _changed = new Queue<int>();\nvoid ChangeValue(int index)\n{\n    if(_array[index]) // do nothing if it was already false\n    {\n        _array[index] = false;\n        _changed.Enqueue(index);\n        if(_changed.Count() > 3)\n        {\n            _array[_changed.Dequeue()] = true;\n        }\n    }\n}\n\nvoid ShowArray()\n{\n    Console.WriteLine("[" + string.Join(", ", _array) + "]");\n}	0
33978959	33978889	Threadlocal values iList ordering	var sema = new Semaphore(1, 1);\n\nThread firstThread = new Thread(new ThreadStart(() =>\n{\n        field.Value = 999;\n        sema.Release();\n}));\n\nThread secondThread = new Thread(new ThreadStart(() =>\n{\n        sema.WaitOne();\n        field.Value = 1000;\n}));	0
15405950	15404612	Get method name with class name by regex expression	\s*(static)?\s*(public|private)\s*\w+\s*(\w+)\s*(\(\s*\w*(,?\s*\w+)*\))?	0
14738683	14738292	C# Interop Excel format like Excel's format as table	Range range = ws.get_Range("A1:D5");\nwrksheet.ListObjects.AddEx(XlListObjectSourceType.xlSrcRange, range, missing, Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, missing).Name = "MyTableStyle";\nwrksheet.ListObjects.get_Item("MyTableStyle").TableStyle = "TableStyleMedium1";	0
21122221	21122079	c# cant insert row but can select	SqlDataAdapter lcDataAdapter = new SqlDataAdapter()\nlcDataAdapter.InsertCommand = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (@NAM)", con);\nlcDataAdapter.InsertCommand.Parameters.Add("@NAM", SqlDbType.VarChar, 255).Value="sadName";\nlcDataAdapter.InsertCommand.ExecuteNonQuery();	0
3150730	3150260	How do you connect to a TFS server in C# using specific credentials?	NetworkCredential cred = new NetworkCredential("Username", "Password", "Domain");\ntfs = new TeamFoundationServer("http://tfs:8080/tfs", cred);\ntfs.EnsureAuthenticated();	0
12831886	12831355	How limit size of file upload but show a meaningful response?	void Application_Error(object sender, EventArgs e)\n{\n    if (Request.TotalBytes > 40960 * 1024)\n    {\n        Server.ClearError();\n        Response.Clear();\n        Response.Write("File uploaded is greater than 40 MB");\n    }\n\n}	0
7180208	7180185	How to get identity from database using Linq?	Customer cust = new Customer();\n cust.Company = "blah";\ncontext.Customers.Add( cust );\ncontext.SubmitChanges();\nint NewPk = cust.Pk;	0
12451679	12451626	Why are there local variables in stack-based IL bytecode	bool TryGet(int key, out string value) {}	0
16816870	16816809	send email to multiple contacts	for (int i = 0; i < address_l.Count; i++)\n{\n   message.Bcc.Add(new MailAddress(address_l[i], names[i]));\n}	0
3997296	3997277	Opening file through Browser	Response.End()	0
7959225	7959188	copy all the files form folder to another folder without permission limit	for file in folder {\n    try {\n        operation\n    } catch (UnauthorizedAccessException ){\n    continue; //Probably should log here\n    }\n}	0
3574397	3573864	how to fetch return values between jquery functions and post ajax jquery request to webservice	codeAddress(state, \n    function(v2) {\n        var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;\n        $.ajax({\n            type: "POST",\n            url: "/BlockSeek/jsonwebservice.asmx/SubmitList",\n            data: jsonobject,\n            contentType: "application/json; charset=utf-8",\n            success: ajaxCallSucceed,\n            dataType: "json",\n            failure: ajaxCallFailed\n        });\n    }\n);\n\nfunction codeAddress(state, callback) {\n    var address = document.getElementById("state").value;\n    geocoder.geocode(...);\n    // ...\n    var v2=results[0].geometry.location;\n    callback(v2);\n}	0
10762054	10761968	Setting text Flow Direction for WPF Localization	FrameworkElement.FlowDirection="{lex:LocFlowDirection Key=FlowDirection, Dict=Strings, Assembly=LocalizationManager}"	0
33889827	33825090	Umbraco: Detect country origin	public class HomePageController : Umbraco.Web.Mvc.RenderMvcController\n{\n    // GET: HomePage\n    public override ActionResult Index(RenderModel model)\n    {\n        //Check country and redirect\n        string country = RegionInfo.CurrentRegion.DisplayName;\n        if (country == "France")\n        {\n            Response.Redirect("http://fr.mySite.org");\n        }\n\n        return base.Index(model);\n    }\n    public ActionResult Index()\n    {\n        return View();\n    }\n}	0
1232037	1232021	How to check Array of strings contains a particular string?	string []test_arr= new string[]{"key1","key2","key3"};\nbool testCondition = Array.Exists\n(\n    test_arr,\n    delegate(string s) { return s == "key3";}\n);	0
3636452	3636338	how to refer xml file from client side application which is generated by webservice	var searchUrl ="http://yourdomain/Block3.xml"	0
27498220	27498150	ViewState values for string array in C#	List<string> successBenefitCodes = new List<string>();\n    foreach(var ben in youritems)\n    {\n    successBenefitCodes.Add(ben.BenefitCode.ToString());\n    }\n    ViewState["successBenefitCodes"] = successBenefitCodes.ToArray();	0
4479277	4478000	How to show a TIF image full screen on secondary monitor in C#?	public static Form ShowImage(Image image) {\n        Form frm = new Form();\n        frm.ControlBox = false;\n        frm.FormBorderStyle = FormBorderStyle.None;\n        frm.BackgroundImage = image;\n        frm.BackgroundImageLayout = ImageLayout.Zoom;\n        Screen scr = Screen.AllScreens.Length > 1 ? Screen.AllScreens[1] : Screen.PrimaryScreen;\n        frm.Location = new Point(scr.Bounds.Left, scr.Bounds.Top);\n        frm.Size = scr.Bounds.Size;\n        frm.BackColor = Color.Black;\n        frm.Show();\n        return frm;\n    }	0
6524156	6524097	I need to search through a list of classes to find the first that matches what I need	var anonymousType = a.TestClassDetails.Select((item, index) => new { Item = item, Index = index + 1 })\n                                      .FirstOrDefault(x => x.Item.Q == "xx");\n\nint indexOfXX = 0;\n// If found\nif(anonymousType != null)\n{\n    indexOfXX = anonymousType.Index;\n}	0
32164808	32164569	Calling client methods with a name set at runtime	string myFunction = "helloWorld";\nClients.Client(connectionId).Invoke(myFunction, params);	0
8461878	8461643	How to mock a property with no setter?	var thirdParty = Rhino.Mocks.MockRepository.GenerateStub<IThirdPartyInterface>();\nthirdParty.Stub(x => x.MockThisProperty).Return("bar");\nstring mockPropertyValue = thirdParty.MockThisProperty; //returns "bar"	0
20457033	20453095	How to access pixels behind IImageProvider (Nokia Imaging SDK on WP8)	var bitmap = await imageSource.GetBitmapAsync(null, OutputOption.PreserveAspectRatio);\nvar pixels = bitmap.Buffers[0];\nfor (uint i = 0; i < pixels.Buffer.Length; i++)\n    {\n        var val = pixels.Buffer.GetByte(i);\n    }	0
5054467	5054452	C#: How to tell architecture of machine	Environment.Is64BitOperatingSystem	0
28982636	28981814	Web API controller with two PUT methods throw an InvalidOperationException	[HttpPut]\n[Route("api/ExternalCodes/SetCodesAsUnUsed")]\npublic HttpResponseMessage SetCodesAsUnUsed(List<string> codes)\n\n[HttpPut]\n[Route("api/ExternalCodes/SetCodesAsUsed")]\npublic HttpResponseMessage SetCodesAsUsed(List<string> codes)	0
1335943	1335909	Generate table(html table) through C# - how to generate 'th' tags?	HtmlTableCell cell1 = new HtmlTableCell("th");	0
7979590	7972443	How to map composite PK with FK NHibernate	class Foo\n{\n    public virtual int Id { get; set; }\n    public virtual Foo1 Foo1 { get; set; }\n    public virtual Foo2 Foo2 { get; set; }\n}\n\nclass Foo1\n{\n    public virtual int Id { get; set; }\n}\n\nclass Foo2\n{\n    public virtual int Id { get; set; }\n}\n\n<composite-id>\n  <key-property name="id" column="ID_FOO"/>\n  <key-many-to-one name="Foo1" column="ID_OTHERFOOFK1"/>\n  <key-many-to-one name="Foo2" column="ID_OTHERFOOFK2"/>\n</composite-id>	0
22914407	22912381	Write blob sequentially in varbinary column	byte[] buffer = new byte[8388608];	0
11564695	11564173	How do I convert several web pages into one pdf document?	public FileResult Download()\n{\n    var urls = new List<string>\n    { // Populate list with urls\n        "C:\\1.html",\n        "C:\\2.html"\n    };\n\n    var documents = new List<EO.Pdf.PdfDocument>();\n    foreach(var url in urls)\n    {\n        var doc = new EO.Pdf.PdfDocument();\n        EO.Pdf.HtmlToPdf.ConvertUrl(url, doc);\n        documents.Add(doc);\n    }\n\n    EO.Pdf.PdfDocument mergedDocument = EO.Pdf.PdfDocument.Merge(documents.ToArray());\n\n    var ms = new MemoryStream();\n    mergedDocument.Save(ms);\n    ms.Position = 0;\n\n    return new FileStreamResult(ms, "application/pdf") { FileDownloadName = "download.pdf" };\n}	0
30894890	30893086	Deserialize JSON into Models that render in partial view (restsharp or any other method)	public ActionResult GetImageOffer(string oid, string otr)\n{\n    var client = new RestClient("valid url");\n\n    var request = new RestRequest("/Offer/OfferDirect", Method.POST);\n    request.AddQueryParameter("oid", oid);\n    request.AddQueryParameter("otr", otr);\n\n    request.AddHeader("apikey", "secretkeyhere");\n    request.RequestFormat = DataFormat.Json;\n\n    RestResponse<RootObject> response = client.Execute<RootObject>(request);\n\n    return PartialView("_pImageOfferModel", response.Data);\n}	0
1596260	1596251	Parse integer from string containing letters and spaces - C#	string input = "RC 272";\nint result = int.Parse(input.Substring(input.IndexOf(" ")));	0
1510341	1510134	Need help with a regular expression parser - C#	var buffer=new List<byte>();\nvar endCode=new byte[] {3, '>', 0x17};\n\n// In a loop:\n\nbyte? received=ReceiveByte(); //Return null if no new byte available\nif(byte.HasValue) {\n  buffer.Add(received);\n  if(buffer.Skip(buffer.Count()-endCode.Length).Take(endCode.Length).SequenceEqual(endCode){\n    //Process the received data in buffer\n    buffer.Clear();\n  }\n}	0
13761452	13751228	Is there a way I can set Font Height in Steema Teechart Graphics 3D?	public Form1()\n        {\n            InitializeComponent();\n            InitializeChart();\n        }\n        private void InitializeChart()\n        {\n            tChart1.AfterDraw += new PaintChartEventHandler(tChart1_AfterDraw);\n        }\n\n        void tChart1_AfterDraw(object sender, Steema.TeeChart.Drawing.Graphics3D g)\n        {\n            g.Font.Size = 25; \n            g.TextOut(100, 150, "TeeChartFor.Net");\n        }	0
16185726	16184811	Unable to get the cell value in rowdeleting event in grid view	GridViewRow row = GridView1.Rows[e.RowIndex];\nLabel usernamelable = (Label)row.FindControl("lblUserNameValue");\nstring username = usernamelable.Text;	0
12412456	12412166	Retrieve data from different column from different table and display onto textbox	var connetionString = "..";\n    using (var connection = new SqlConnection(connetionString))\n    {       \n\n     using(var command = new SqlCommand("SELECT COLUMN1, COLUMN2 FROM YOURTABLE", connection))\n     { \n       connection.Open();\n       var  dr = cmmand.ExecuteReader();\n       if (dr.HasRows == false)\n       {\n         throw new Exception();\n       }\n       if (dr.Read())\n       {\n\n           textBox1.Text = dr[0].ToString();\n           textBox2.Text = dr[1].ToString();\n       }\n\n     } \n\n}	0
9739466	9739379	How to have onClick() on XML nodes	private void listView1_ItemActivate(object sender, EventArgs e)\n{ \n //Your code\n}	0
32589315	32589177	Find 4 sequence numbers in String Using C#	var regex = new Regex(@"\d{4}");            \nstring a=@"I(1946) am a string and I have some character and number and some sign like 4412 but I must find 4 sequence numbers in this.";\nforeach(Match match in regex.Matches(a))\n    Console.WriteLine(match.Value);	0
1309356	1309142	Determine 3rd Party Application Installation Directory	Type type = Type.GetTypeFromProgID("WindowsInstaller.Installer");\n        Installer msi = (Installer)Activator.CreateInstance(type);\n        foreach (string productcode in msi.Products)\n        {\n            string productname = msi.get_ProductInfo(productcode, "InstalledProductName");\n            if (productname.Contains("<APPLICATION NAME>"))\n            {\n                string installdir = msi.get_ProductInfo(productcode, "InstallLocation");\n            }\n        }	0
14137216	14137139	Usage of JSON for a daily activity journal	System.Xml	0
25485769	25485707	c# deserializing JSON web api response	MyData tmp = JsonConvert.DeserializeObject<MyData>((JObject.Parse(responseFromServer)["block4o"]).ToString());	0
26358572	26355725	Saving data to multiple tables	public partial class NorthwindEntities\n{\npublic override int SaveChanges()\n{\n    try\n    {\n        return base.SaveChanges();\n    }\n    catch (DbEntityValidationException ex)\n    {\n        // Retrieve the error messages as a list of strings.\n        var errorMessages = ex.EntityValidationErrors\n                .SelectMany(x => x.ValidationErrors)\n                .Select(x => x.ErrorMessage);\n\n        // Join the list to a single string.\n        var fullErrorMessage = string.Join("; ", errorMessages);\n\n        // Combine the original exception message with the new one.\n        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);\n\n        // Throw a new DbEntityValidationException with the improved exception message.\n        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);\n    }\n}\n}	0
8917337	8917303	LINQ - Summing numbers stored as string	TotalQtyForThisOrder = orders.Sum( w = > {\n            int result;\n            Int32.TryParse(w.UserDefField, out result);\n            return result;\n});	0
8464970	8464921	How to add a HTML attribute from an aspx.cs	Graph1.Width = 500;	0
27636826	27634815	Unable to get user by email from Sharepoint	public User GetUserByEmail(ClientContext clientContext, string email)\n{\n try\n   {\n     ClientResult<Microsoft.SharePoint.Client.Utilities.PrincipalInfo> persons =\n     Microsoft.SharePoint.Client.Utilities.Utility.ResolvePrincipal(clientContext,                         clientContext.Web, email,\n     Microsoft.SharePoint.Client.Utilities.PrincipalType.User,Microsoft.SharePoint.Client.Utilities.PrincipalSource.All, null, true);\n     clientContext.ExecuteQuery();\n     Microsoft.SharePoint.Client.Utilities.PrincipalInfo person = persons.Value;\n     User user = clientContext.Web.SiteUsers.GetByLoginName(person.LoginName);\n     clientContext.ExecuteQuery();\n     return user;\n   }\n   catch\n   {\n     return null;\n   }\n\n}	0
20769686	20769650	How to add all integers to an array	int sum = arr1.Sum();	0
27182415	27182301	Remove items that match memory objects with RemoveRange	var t = users.Select(x => x.ColumnName); \nvar t1 = db.TableName.Where(x => t.Contains(x.ColumnName)).ToList(); \n//then call RemoveRange() \ndb.Ranges.RemoveRange(t1);	0
12954513	12954398	I want to turn a percentage value string to double?	double value = double.Parse(p.TrimEnd(new[] {'%'}))/100;	0
12807007	12750791	DNN 6 Hide Retrieve password in Login page	.dnnLoginActions {display:none;}	0
2223452	2208722	How to get friendly device name from DEV_BROADCAST_DEVICEINTERFACE and Device Instance ID	private static string GetDeviceName(DEV_BROADCAST_DEVICEINTERFACE dvi)\n{\n    string[] Parts = dvi.dbcc_name.Split('#');\n    if (Parts.Length >= 3)\n    {\n        string DevType = Parts[0].Substring(Parts[0].IndexOf(@"?\") + 2);\n        string DeviceInstanceId = Parts[1];\n        string DeviceUniqueID = Parts[2];\n        string RegPath = @"SYSTEM\CurrentControlSet\Enum\" + DevType + "\\" + DeviceInstanceId + "\\" + DeviceUniqueID;\n        RegistryKey key = Registry.LocalMachine.OpenSubKey(RegPath);\n        if (key != null)\n        {\n            object result = key.GetValue("FriendlyName");\n            if (result != null)\n                return result.ToString();\n            result = key.GetValue("DeviceDesc");\n            if (result != null)\n                return result.ToString();\n        }\n    }\n    return String.Empty;\n}	0
29787637	29787526	How to include total Count in JSON service Side Paging with MVC C# Controller	public ActionResult GetPage(int page, int pageSize)\n{\n    var dbContext = new DbContext();\n    int count=(from j in dbContext.Jobs select j).Count();\n    var jobs = dbContext.Jobs.OrderBy(job=>job.Id).skip(page * pageSize).Take(pageSize);\n    return Json(new { jobs = jobs, total = count },JsonRequestBehavior.AllowGet );\n}	0
1088363	1088348	Displaying a form from a dynamically loaded DLL	Assembly assembly = Assembly.LoadFile("C:\\test.dll");\nType type = assembly.GetType("test.dllTest");\nForm form = (Form)Activator.CreateInstance(type);\nform.ShowDialog(); // Or Application.Run(form)	0
11654035	11653941	How can I serialize a base object if the implementing object is not Serializable?	[Serializable]\npublic class UsersVm : ViewModelBase {}	0
27927589	27926582	How to make available in a usercontrol a inner control collection in Wpf?	this.ItemsControlInnerControl.ItemsSource = this.Pages;	0
33392798	33392575	How to assign to all class data members at once	var result = QueryResultRecords.First();\nthis.UserId  = result.UserId;	0
11164102	11164078	Rounding value to .5	Math.Ceiling	0
17565810	16687070	Using Contains as 'IN' cluase with LINQ in Entity Framework in Silverlight	var data = wtps.GetVwProposedMIgrationsQuery().Where(x=>result.Any(z=>z.DepartmentCode == x.DepartmentCode))	0
3342087	3342011	Replace Bad words using Regex	const string CensoredText = "[Censored]";\nconst string PatternTemplate = @"\b({0})(s?)\b";\nconst RegexOptions Options = RegexOptions.IgnoreCase;\n\nstring[] badWords = new[] { "cranberrying", "chuffing", "ass" };\n\nIEnumerable<Regex> badWordMatchers = badWords.\n    Select(x => new Regex(string.Format(PatternTemplate, x), Options));\n\nstring input = "I've had no cranberrying sleep for chuffing chuffings days -\n    the next door neighbour is playing classical music at full tilt!";\n\nstring output = badWordMatchers.\n   Aggregate(input, (current, matcher) => matcher.Replace(current, CensoredText));\n\nConsole.WriteLine(output);	0
28321716	28321396	How to check value of same variable in recursion Method?	private static void myMethod(/*variables*/, myMethodVariableFromBefore){\n    while (/* condition */) {\n        foreach (/* condition */) {\n            if (/* condition */) {\n                foreach (/*condition */) {\n                    myMethod(/*variables*/, myMethodVariable);\n                        }\n            } else {\n            /* THIS IS THE PART I AM ASKING FOR:\n             The if statement should ask if the Variable is NOT the same as before.*/\n\n                    if (myMethodVariable != myMethodVariableFromBefore){\n                    // stuff to do.\n}	0
9463965	9410732	How to determine which control was Clicked and contextMenuStrp appeared?	private void copyNotesToClipboardStripMenu_Click(object sender, EventArgs e)\n        {\n            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;\n            if (menuItem != null)\n            {\n                ContextMenuStrip calendarMenu = menuItem.Owner as ContextMenuStrip;\n                if (calendarMenu != null)\n                {\n                    Control controlSelected = calendarMenu.SourceControl;\n                }\n            }\n        }	0
5903505	5903448	Decimal Formatting in C#	// max. two decimal places\nString.Format("{0:0.##}", 123.4567);      // "123.46"\nString.Format("{0:0.##}", 123.4);         // "123.4"\nString.Format("{0:0.##}", 123.0);         // "123"	0
7663166	7055633	How to search in a Arraylist	public int search(object sender, List<albums> al)\n    {\n        int i = -1;\n        TextBox txt = (TextBox)sender;\n        foreach (albums dc in al)\n        {\n            if ((dc.artist == txt) ||(dc.tag == txt))\n            {\n                i = (al.IndexOf(dc));\n            }\n        }\n        return i;\n    }	0
30188073	30177160	RavenDB count index including zero values	public class Category_Items : AbstractMultiMapIndexCreationTask<Category_Items.ReduceResult>\n{\n    public class ReduceResult\n    {\n        public string CategoryId { get; set; }\n        public int Count { get; set; }\n    }\n\n    public Category_Items()\n    {\n        AddMap<Item>(items =>\n            from item in items\n            select new \n            {\n                CategoryId = item.CategoryId,\n                Count = 1\n            });\n\n        AddMap<Category>(categories =>\n            from category in categories\n            select new \n            {\n                CategoryId = category.Id,\n                Count = 0\n            });\n\n\n        Reduce = results =>\n            from result in results\n            group result by result.CategoryId into g\n            select new ReduceResult\n            {\n                CategoryId = g.Key,\n                Count = g.Sum(x => x.Count)\n            };\n    }\n}	0
8072197	8072085	ASP.NET GridView - Control Moves around in Content Page	div {\n   left: 0px;\n   position:absolute;\n   top: 0px;\n   width:100%;\n   z-index:0;\n}	0
2535652	2535613	How to get current Checked Item in a checkedlistbox	private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)\n    {\n        //Note: MessageBox is for demo use only \n        MessageBox.Show("Selected Index: " + e.Index.ToString());\n        MessageBox.Show("Current Value: " + e.CurrentValue.ToString());\n        MessageBox.Show("New Value: " + e.NewValue.ToString());\n        //Getting the item would be:\n        string currentItem = (string)this.checkedListBox1.Items[e.Index];\n        MessageBox.Show("Current Item: " + currentItem);\n    }	0
5347515	5343222	Removing a database row via the C# DataGridView?	private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)\n{\n    // It is a cancellable event, you could cancel the delete on certain conditions.\n    e.Cancel = true;\n\n}	0
15974603	15973700	visibility of frame/pages	private Page1 page1;\nprivate void btnShowFrame(object sender, RoutedEventArgs e)\n{\n    if (page1 == null)\n    {\n        page1 = new Page1();\n        frame1.Navigate(page1);\n    }\n    if (page1.Visibility != System.Windows.Visibility.Visible) page1.Visibility = System.Windows.Visibility.Visible;\n}	0
5402802	5402757	How to dispose or close an instance of XML Document in ASP.NET	using (Stream stream = ...)\n{\n    doc.Save(stream);\n}	0
13664761	13664748	Select values for a range of given indexes using Linq C#	var results = indexList.Select(index => mainList[index]);	0
9879474	9879438	How to test a swallowed exception	ClassContainingInternalMethod cl = new ClassContainingInternalMethod ();\n\n//any private or internal method you want here.\nMethodInfo dynMethod = \ncl.GetType().GetMethod("DoSomeStuff", BindingFlags.NonPublic | BindingFlags.Instance);\n\ndynMethod.Invoke(cl, new object[] {});	0
9936270	9935811	Custom BlendState to avoid AlphaBlending artifacts	byte alpha = 255 - (currentAlphaState * 255);\nspriteBatch.Draw(...., new Color( 255, 255, 255, alpha) ...); // assuming white is your default tint color	0
1990724	1990716	C# How to know the size of file on a website	Content-length	0
11118588	11117645	I need to select into a parameter through the Oracle .NET connector	// without voodoo\n\n        OracleCommand ncmd = new OracleCommand("select nvl(max(MYFIELD),0) from mytable", conn);\n\n        ncmd.CommandType = CommandType.Text;\n\n        object r = ncmd.ExecuteScalar();\n\n        Console.WriteLine("a: " + r);\n        Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");\n\n        // with the voodoo\n\n        ncmd.CommandText = "begin select nvl(max(MYFIELD),0) into :maxvalue from mytable; end;";\n        ncmd.CommandType = CommandType.Text;\n\n        OracleParameter res = new OracleParameter(":res", OracleDbType.Double);\n        res.Direction = ParameterDirection.ReturnValue;\n        ncmd.Parameters.Add(res);\n\n        ncmd.ExecuteNonQuery();\n\n        Console.WriteLine("b: " + res.Value);\n        Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");	0
18322576	18322218	EF 5 Connection Management	public void UpdateCategory(Models.Category catData)\n{\n    if (catData == null) return;\n    using (var cntx = new DataContext())\n    {\n        //IN THE LINE BELOW A CONNECTION IS DEFINITELY OPENED BUT IS IT \n        //IMMEDIATELY CLOSE? => YES!\n        var cat = cntx.Set<Category>()\n                          .FirstOrDefault(c => c.CategoryId == catData.CategoryId);\n\n        if (cat == null) return;\n\n        if (!cat.LastChanged.Matches(catData.LastChanged))\n            throw new ConcurrencyException(cat.GetType().ToString());\n\n        cat.CategoryName = catData.CategoryName;\n\n        cntx.DbContext.Entry<Category>(cat).State = System.Data.EntityState.Modified;\n\n        //AFTER THE NEXT LINE DO I HAVE 2 CONNECTIONS OPENED? => NO\n        cntx.SaveChanges();\n\n\n        catData.LastChanged = cat.LastChanged;\n    }\n\n}	0
1097516	1097270	How should I store data inside custom exceptions?	public static void TestCustomException<T>() where T : Exception\n{\n    var t = typeof(T);\n\n    //Custom exceptions should have the following 3 constructors\n    var e1 = (T)Activator.CreateInstance(t, null);\n\n    const string message = "message";\n    var e2 = (T)Activator.CreateInstance(t, message);\n    Assert.AreEqual(message, e2.Message);\n\n    var innerEx = new Exception("inner Exception");\n    var e3 = (T)Activator.CreateInstance(t, message, innerEx);\n    Assert.AreEqual(message, e3.Message);\n    Assert.AreEqual(innerEx, e3.InnerException);\n\n    //They should also be serializable\n    var stream = new MemoryStream();\n    var formatter = new BinaryFormatter();\n    formatter.Serialize(stream, e3);\n    stream.Flush();\n    stream.Position = 0;\n    var e4 = (T)formatter.Deserialize(stream);\n    Assert.AreEqual(message, e4.Message);\n    Assert.AreEqual(innerEx.ToString(), e4.InnerException.ToString());\n}	0
33787596	33181504	How to use Semantic Logging Application Block (SLAB) to configure multiple sinks based on level in C# (in-process)	[Event(100, Level = EventLevel.Verbose, Keywords = Keywords.Application, Task = Tasks.Initialize, Opcode = Opcodes.Starting, Version = 1)]\npublic void ApplicationStarting()\n{\n    this.WriteEvent(100);\n}	0
14742419	14692456	how to make crystal reports find database on client pc	Data Source=Servername\SQLEXPRESS	0
6458535	6458282	C# WinForms: How to restrict MDI child windows to always be within the bounds of the MDIParent?	private void Form1_Resize(object sender, EventArgs e)\n{\n    Size pSize = this.ParentForm.ClientSize;\n\n    Size maxAllowed = new Size(pSize.Width - this.Left, pSize.Height - this.Top);\n\n    // Resize the child if it goes out of bounds\n    if (this.Height > maxAllowed.Height)\n        this.Height = maxAllowed.Height;\n\n    if (this.Width > maxAllowed.Width)\n        this.Width = maxAllowed.Width;\n}	0
20569424	20564505	Writing text on screen affecting models	void prepare3d()\n{\n    //set the depth buffer state\n    DepthStencilState depthBufferState = new DepthStencilState();         \n    depthBufferState.DepthBufferEnable = true; \n    GraphicsDevice.DepthStencilState = depthBufferState;\n\n    //set the BlendState\n    GraphicsDevice.BlendState = BlendState.Opaque;\n    GraphicsDevice.DepthStencilState = DepthStencilState.Default;\n\n    GraphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;\n    GraphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;\n}	0
457740	457671	C# How do I save runtime font settings	Font font1 = new Font("Arial", 12, FontStyle.Italic);\nTypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));\n// Saving Font object as a string\nstring fontString = converter.ConvertToString(font1);\n// Load an instance of Font from a string\nFont font = (Font)converter.ConvertFromString(fontString);	0
7010820	6995329	Using JavaScriptSerializer Deserialze array of generic object in C#	foreach (CloudDBTableList table in cloudDBTableList)\n            {                \n               string uri = string.Format(table.URI, "1-Jan-2011");\n               string result  = _dataPullSvcAgent.GetData (baseURI + uri);\n\n\n               string tableClassType = namespacePrefix + "." + table.SchemaName + "." + table.TableName + ", " + namespacePrefix;//namespacePrefix is same as assembly name.\n               Type t = Type.GetType(tableClassType);\n               JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();\n               var L1 = typeof(List<>);\n               Type listOfT = L1.MakeGenericType(t);\n               var objectList = jsonDeserializer.Deserialize(result, listOfT);\n\n\n            }	0
23276883	23274950	Issues in linking Files between Projects in a Visual Studio Solution	namespace SharedNS\n{\n    public class Globals\n    {\n        public const int MyGlobalVar = 0;\n    }\n}	0
10720156	10700113	How to load a permission set from configuration	PermissionSet.FromXml(SecurityElement.FromString(yourXmlRepresentation))	0
3144426	3144393	Querying a database or a datatable for duplicate records in one column	SELECT\n    id,\n    my_data\nFROM\n    My_Table\nWHERE\n    my_data IN\n    (\n        SELECT\n            my_data\n        FROM\n            My_Table\n        GROUP BY\n            my_data\n        HAVING\n            COUNT(*) > 1\n    )	0
1709687	1709443	C# riddle : implement interface	public Number : INumber\n{\n    private decimal value = 0m;\n    private int thousands = 0;\n\n    public void Add1000()\n    {\n        thousands++;\n    }\n\n    void SetValue(decimal d)\n    {\n        value = d;\n        thousands = 0;\n    }\n\n    decimal GetValue()\n    {\n        // Careful of the overflow... (do multiplication in decimal)\n        value += thousands * 1000m;\n        thousands = 0;\n        return value;\n    }\n}	0
23490410	23489814	Visual C# missing app.config file after build	[exe_name].config	0
19032043	19031527	Login system using Oledb Access	private void Validate(object sender, RoutedEventArgs e)\n    {\n\n    using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Users\\Baladi\\documents\\visual studio 2012\\Projects\\CalUnderFoot\\CalUnderFoot\\UserPerm.mdb"))\n    {\n        OleDbCommand command = new OleDbCommand("select * from UserPermT where EmpEmail='"+EmpEmail.Text+"' and EmpPIN='"+EmpPIN.PasswordChar+"'", connection);\n        connection.Open();\n        OleDbDataReader dr= command.ExecuteReader();\n\n        if (dr.Read())\n        {\n            MessageBox.Show("success");\n        }\n\n        else\n        {\n            MessageBox.Show("fail");\n        }\n        dr.Close();\n    }\n    }	0
16758577	16758448	How to read the attribute of a child node within a node?	string xpath = string.Format("//vegetable[@name='{0}']/recipe",comboboxSelectedItem);\nvar selectedVegetableRecipe = xdoc.SelectSingleNode(xpath);	0
6714121	6714049	Permission in website	RecoverPassword.aspx	0
34460013	34459665	How to pass an object to a ViewModel using dependency injection?	public class MainViewModel : ViewModelBase\n{\n    public MainViewModel()\n    {\n        ProductsViewModel = new ProductsVM();\n        OrdersViewModel = new CustomerOrdersVM(ProductsViewModel);\n    }\n    public CustomerOrdersVM OrdersViewModel { get; private set; }\n\n    public ProductsVM ProductsViewModel { get; private set; }\n}	0
29977837	29975941	Select attribute value of parent element in Linq to XML of C#	var xpath = @"//*[@name='productCode'][@value='Data']//..//..";\nvar s = xdoc.XPathSelectElement(xpath). ...	0
27011301	27007730	How to use default functionality for delete key while in edit mode for DataGridView?	private void deleteToolStripMenuItem_Click(object sender, EventArgs e)\n{\n    DeleteCellsIfNotInEditMode();\n}\n\nprivate void dataGridView1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Delete)\n    {\n        DeleteCellsIfNotInEditMode();\n    }\n}\n\nprivate void DeleteCellsIfNotInEditMode()\n{\n    if (!dataGridView1.CurrentCell.IsInEditMode)\n    {\n        foreach (DataGridViewCell selected_cell in dataGridView1.SelectedCells)\n        {\n            selected_cell.Value = "";\n        }\n    }\n}	0
26256629	26255980	How to create and save ics file using save dialog box?	string fileName = "Test.ics";\nInternetCalendaring.ICSBuilder icsbBuilder = new InternetCalendaring.ICSBuilder(vecVEvents);\nsRes = icsbBuilder.ICSBuildProcess();\n\nbyte[] Buffer = Encoding.Unicode.GetBytes(sRes);\n\nSystem.Web.HttpContext.Current.Response.AddHeader("content-type", "text/Calendar");\nSystem.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);\nSystem.Web.HttpContext.Current.Response.BinaryWrite(Buffer);\n//System.Web.HttpContext.Current.Response.Clear();\nHttpContext.Current.Response.End();	0
27960699	27960505	Casting to another property in MVVM	dynamic searchQuery = Convert.ChangeType(SearchQuery, \n                           SelectedSearchQueryParameter.DataType);	0
13818928	13817702	Change Border in Excel left,right,bottom and top	xlWorkSheet5.Cells[7,1].Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = 1d;\nxlWorkSheet5.Cells[7, 1].Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 1d;\nxlWorkSheet5.Cells[7,1].Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = 1d;\nxlWorkSheet5.Cells[7,1].Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = 1d;	0
4936077	2837683	Can you select which column to sync with Sync Framework	DbSyncTableDescription tableDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(tableName, Collection<Columns>, server Connection)	0
14102032	14101994	How can i verify that one string appears before a nother string in a file in C#?	if(str.indexOf("str1") != -1 && str.indexOf("str2") != -1 && str.indexOf("str1") < str.indexOf("str2"))\n    return true;	0
7147244	7147147	Having a problem updating table in Linq to Entities with update statement but not updating the table 	public bool UpdateCustomer(Customer customer){   \n    Customer cust = entities.Customers.FirstOrDefault(c => c.ID == customer.ID);  \n    cust.Forname = customer.Forename;   \n    cust.Surname = customer.Surname   \n    entities.SaveChanges(); \n}	0
25951191	25950803	Delete specific files in directory	if (File.Exists(Server.MapPath(PDFUrl))\n{\n    File.Delete(Server.MapPath(PdfUrl));\n}	0
8944631	8755740	Dynamically set x509 to use for WCF duplex comms	var binding = new NetTcpBinding();\n binding.Security.Mode = SecurityMode.Transport;\n binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;\n binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;\n binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;\n\n var identity = new DnsEndpointIdentity("localhost");\n Uri uri = new Uri("tcp:URI goes here");\n var address = new EndpointAddress(uri, identity, new AddressHeaderCollection());\n\n _smFactory = new DuplexChannelFactory<IScannerManager>(instanceContext, binding, address);\n\n _smFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "CustomCertificateNameHere");\n _commsChannel = _smFactory.CreateChannel();	0
17853278	17853195	mvc4 Automatically log in user during email-confirmation	FormsAuthentication.SetAuthCookie("username", true);	0
25468731	25468689	other name instead of variable name in c#	foreach (TextBox item in this.Controls.OfType<TextBox>()) {\n    if (item.Text.Trim() == "") {\n       MessageBox.Show(item.Tag.ToString());\n    }\n}	0
24154622	24154487	how to seperate the files according to album in mp3	SongList.GroupBy(t => t.Tag.Album);	0
8243876	8243154	How can you append text to the onClick attribute in an anchor tag using RegEx	void Main()\n{\n    //var link = "";\n    var link = @"<a href=""#"" name=""xy"" onclick=""alert('hello');alert('goodbye');"">test</a>";\n    var link2 = @"<a href=""#"" name=""xy"">test</a>";\n\n    string s = AddJS(link,"alert('inserted');");\n    string s2 = AddJS(link2,"alert('inserted');");\n\n    Console.WriteLine(s);\n    Console.WriteLine(s2);\n\n}\n\nstring AddJS(string link,string js) {\n    if (link.IndexOf("onclick") > -1) return Regex.Replace(link, "(onclick=\".*)?(\")(>)", @"$1" + js  + @""">");\n    else return Regex.Replace(link, "(onclick=\".*)?(\")(>)", @""" onclick=""" + js + @""">");\n}	0
32238425	32238295	Pivot multiple tables using Linq	var query = tblUsername.Select(u => new {\n    Name = u.username,\n    Monday = u.tblSchedule.Where(sch => sch.colId == 2).Sum(sch => sch.hrs),\n    Tuesday = u.tblSchedule.Where(sch => sch.colId == 3).Sum(sch => sch.hrs),\n    Wednesday = u.tblSchedule.Where(sch => sch.colId == 4).Sum(sch => sch.hrs),\n    Thursday = u.tblSchedule.Where(sch => sch.colId == 5).Sum(sch => sch.hrs),\n    Friday = u.tblSchedule.Where(sch => sch.colId == 6).Sum(sch => sch.hrs),\n    Saturday = u.tblSchedule.Where(sch => sch.colId == 7).Sum(sch => sch.hrs),\n    Sunday = u.tblSchedule.Where(sch => sch.colId == 8).Sum(sch => sch.hrs),\n});	0
28214963	28214791	Selecting multiple columns from each row and removing duplicates	var listOfPhone1 = (from x in table select x.Select(z => z.Phone1);\nvar listOfPhone2 = (from x in table select x.Select(z => z.Phone2);\nvar listOfResults = (listOfPhone1.AddRange(listOfPhone2)).Distinct();	0
18206418	18206183	Event to detect System wake up from sleep in C#	SystemEvents.PowerModeChanged += OnPowerChange;\n\nprivate void OnPowerChange(object s, PowerModeChangedEventArgs e) \n{\n    switch ( e.Mode ) \n    {\n        case PowerModes.Resume: \n        break;\n        case PowerModes.Suspend:\n        break;\n    }\n}	0
2056274	2055652	Visual State Manager on Custom Control	ExtendedVisualStateManager.GoToElementState(this.LayoutRoot as FrameworkElement, "OffScreen", true);	0
6948010	6946231	How to specify the implementation you want to inject	public struct NotificaitonSettings<T>\n{\n    public Predicate<T> Predicate;\n    public NotificationService Service;\n}\n\npublic class NotificationServiceFactory<T> : INotificationServiceFactory<T>\n{\n    protected static List<NotificaitonSettings<T>> settings = new List<NotificaitonSettings<T>>();\n\n    static NotificationServiceFactory()\n    {\n        settings.Add(new NotificaitonSettings<T>\n        {\n            Predicate = m => !String.IsNullOrEmpty(m.Email),\n            Service = new NotificationService(new EmailNotification(), new EmailFormatter())\n        });\n        settings.Add(new NotificaitonSettings<T>\n        {\n            Predicate = m => !String.IsNullOrEmpty(m.Fax),\n            Service = new NotificationService(new FaxNotification(), new FaxFormatter())\n        });\n    }\n\n    public NotificationService Create(T model)\n    {\n        return settings.FirstOrDefault(s => s.Predicate(model)).Service;\n    }\n}	0
9737095	9737061	C# convert a list of numbers to negative	List<double> reversed = yList.Select(x => -x).ToList();	0
23310704	23310439	How to create shortcut to specific phone settings from my app?	var page = new Microsoft.Phone.Tasks.ConnectionSettingsTask();\npage.ConnectionSettingsType = Microsoft.Phone.Tasks.ConnectionSettingsType.WiFi;\npage.Show();	0
4891900	2078088	Creating a new Outlook store	Outlook.Folders olFolders = olNamespace.Folders;\n        foreach (Outlook.MAPIFolder olTmpFolder in (IEnumerable) olFolders)\n        {\n            if(olTmpFolder.Name == "My Inbox")\n            {\n\n                olTmpFolder.Folders.Add("Inbox", missing) as Outlook.Folder;\n                olTmpFolder.Folders.Add("Sent", missing) as Outlook.Folder\n                olTmpFolder.Folders.Add("Outbox", missing) as Outlook.Folder\n            }\n        }	0
21277831	21277679	Load data from SQL to combo and save selected value	var Value1 = comboBox1.SelectedValue;	0
12055317	12044620	Saving Word DOCX files as PDF	var TheDocument = TheWordApp.Documents.Open(docName);\n\nTheDocument.ExportAsFixedFormat(\n            docName.Replace(".docx", ".pdf"),\n            Word.WdExportFormat.wdExportFormatPDF, \n            OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, \n            BitmapMissingFonts: true, DocStructureTags: false);\n\n((Word._Document)TheDocument).Close();	0
28842030	28842020	How to get Text-property from an argument with Object-type in C#?	var control = sender as Control;\nif(control != null)\n{\n    MessageBox.Show(control.Text);\n}	0
17739725	17739055	Get name of image on click of image in datalist	If Not Page.IsPostback Then\n\n...Code for binding datalist.......\n\nEnd IF	0
27746267	27746085	How can I possibly iterate through data after n:th row in a text file?	var lines = File.ReadAllLines( file );          \n// check number of lines here, make sure there are at least nine and\n// that the count is a multiple of three\nfor( int i = 9; i < lines.Length; i += 3 )\n{\n    string desc = lines[i + 0],\n           qty = lines[i + 1],\n           price = lines[i + 2];\n    // do work here (step 5)\n}	0
12073438	12073416	Convert string to 2 decimal place	var probablyDecimalString = "0.4351242134";\ndecimal value;\nif (Decimal.TryParse(probablyDecimalString , out value))\n    Console.WriteLine ( value.ToString("0.##") );\nelse\n    Console.WriteLine ("not a Decimal");	0
22652356	22609757	how we can set only outer border for pdfptable using c#.net?	PdfPCell cell = new PdfPCell();\n            cell.AddElement(t);\n            cell.BorderWidthBottom=1f;\n            cell.BorderWidthLeft=1f;\n            cell.BorderWidthTop=1f;\n            cell.BorderWidthRight = 1f;\n            PdfPTable t1 = new PdfPTable(1);\n            t1.AddCell(cell);	0
23555200	23505620	Making a call to a Web Api with a JObject in the body	using System.Net.Http;\nusing System.Net.Http.Headers;\n\n        var userData = new User()\n        {\n            firstName = txtFirstName.Text,\n            lastName = txtLastName.Text,\n            companyName = txtCompanyName.Text,\n            email = txtEmail.Text,\n            phone = txtPhone.Text\n        };\n            client.BaseAddress = new Uri("http://yourBaseUrlHere");\n            client.DefaultRequestHeaders.Accept.Clear();\n            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));\n\n            HttpResponseMessage response = await client.PostAsJsonAsync("requestUrlHere", user);\n            if (response.IsSuccessStatusCode)\n            {\n                //Success code\n            }	0
26999394	26995467	Programmatically format a cell as a checkbox	Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)\n    Dim B9 As Range\n    Set B9 = Range("B9")\n    If Intersect(B9, Target) Is Nothing Then Exit Sub\n    B9.Font.Name = "Marlett"\n    Cancel = True\n    If B9.Value = 1 Then\n        B9.Value = 0\n        B9.NumberFormat = ";;;"\n    Else\n        B9.Value = 1\n        B9.NumberFormat = Chr(34) & "a" & Chr(34) & ";;;"\n    End If\nEnd Sub	0
2942321	2942294	i want to multiply a character L to identity matrix in c#	identity[row, col] = (row == col) ? "L" : "0";	0
13491483	13490063	Results from LINQ with SUM for TimeSpan, GROUP and JOIN	var query = ctx.data.ToList().OrderBy(d => d.Time).\n            GroupBy(d => d.Members.StepId).\n            SelectMany(g => g.Select((d, place) => new { Time = d.Time, Members = d.Members, PlaceInStep = place + 1 })).\n            GroupBy(d => d.Members.TeamId).\n            Select(g => new \n            {\n               TeamId = g.Key, \n               Name = g.Select(d => d.Members.Teams.TeamName).First(),  \n               Members = g.Select(d => new {Time = d.Time, PlaceInStep = d.PlaceInStep, MemberName = d.Members.MemberName}),                    \n               TotalTime = g.Aggregate(new TimeSpan(), (sum, nextData) => sum.Add(nextData.Time))\n            });	0
9215898	9215855	Search files based on date created in c#	var files = from c in directoryInfo.GetFiles() \n            where c.CreationTime >somedate\n            select c;	0
9588481	9588347	How can I format a MVC3 WebGrid date column for local timezone?	grid.Column("DueDate", "Due Date", format: (item) => String.Format("{0:yyyy-MM-dd}", item.DueDate))	0
1869619	1869567	C# Regex: How Can I Replace Tokens With Strings Generated at Run-time?	Regex.Replace(inputString,\n              tokenMatchRegexString,\n              match => TokenReplacement(match.Groups[1].Value));	0
8724880	8724719	Group Multiple Tables in LINQ	group new { r,s } by new { r.SpaceID, s.SpaceCode }	0
9753572	9674704	How can I string format a decimal (multiple of 0.5) as a whole or mixed number?	public static string ToMixedNumber(this decimal d)\n{\n    if (d == 0) return "";\n    var s = d.ToString().TrimEnd('0');\n    if (s.EndsWith(".")) return s.TrimEnd('.');\n    return s.Split('.')[0] + " 1/2";\n}	0
2885996	2884344	How to programmatically(C#) go to a certain keyframe in a silverlight animation?	myStoryboard.Begin();\nmyStoryboard.Seek(new TimeSpan(0, 0, 3));	0
6238239	6238232	How to clear the entire console window?	Console.Clear();	0
5211837	5211814	Getting the value of an XML Element that also has attributes	[XmlText]\npublic string Value { get; set; }	0
10010882	10009218	ASP.NET MVC3 Best way to customize converting input parameters	BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);	0
29753658	29753380	Add dynamic json to static json	public string getJson() {\n    var publicationTable = new[] {\n        new[] { 1, 2, 3, 4, 5 },\n        new[] { 6, 7, 8, 9, 10 }\n    };\n    return (new JavaScriptSerializer()).Serialize(publicationTable);\n}	0
5240041	5239823	Simplest way to  deserialize an Array/Sequence of objects from XML with C#?	namespace Example\n{\n    [XmlRoot("foos")]    \n    class Foos\n    {\n        public Foos() {}\n\n        [XmlElement("foo")]\n        public List<Foo> FooList {get; set;}\n    }\n}	0
5882328	5882291	Asp.net, C# Selecting radiobuttons and labels from a panel	foreach (Control RBL in pnlMain.Controls)\n{\n    if (RBL is RadioButtonList)\n    {\n        foreach (ListItem LI in (RBL as RadioButtonList).Items)\n        {\n            if (LI.Text.EndsWith("5") && LI.Selected)\n            {\n                // Do something with the radiobutton\n            }\n        }\n    }\n}	0
6109214	6109159	Create a Windows Form from a background Thread	GuiContext.Send(_ => {\n                        Form2 frm2=new Form2();\n                        frm2.ShowDialog();\n                       }, null);	0
9282813	9282704	Stale data in MVVM ViewModels with dependency injection	ExportFactory<T>	0
14188113	14187461	Reading POST Request XML - Boolean value always read as false	[DataContract(Namespace = "http://myWebService.com/endpoint")]\npublic class StockListRequestData\n{\n    [DataMember(Order = 0)]\n    public string UserID { get; set; }\n\n    [DataMember(Order = 1)]\n    public string StockDatabase { get; set; }\n\n    [DataMember(Order = 2)]\n    public bool InStockOnly { get; set; }\n}	0
15577947	15577909	How can I change the sort order using an IComparer in .NET	public int Compare(string x, string y)\n{\n    if (x == y)\n    {\n        return 0;\n    }\n    if (x == "D")\n    {\n        // Unless y is *actually* "B", we can just\n        // pretend that x is "B". (So it will be after any "A", but before\n        // any other "Bxyz".)\n        if (y == "B")\n        {\n            return -1;\n        }\n        return "B".CompareTo(y);\n    }\n    // Ditto, basically. Alternatively you could call Compare(y, x)\n    // and invert the result, but *don't* just negate it, as it does the\n    // wrong thing with int.MinValue...\n    if (x == "D")\n    {\n        if (x == "B")\n        {\n            return 1;\n        }\n        return x.CompareTo("B");\n    }\n    return x.CompareTo(y);\n}	0
17728171	17728009	Changing datagridview cell color dynamically	dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;	0
11668455	11668283	datetime asp mvc 4 razor	System.Globalization.CultureInfo.CurrentCulture.Name	0
20165645	20165364	Show total of every column in footer within a gridview	int[] TotalStats = new int[12] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};\n\nprotected void GridViewHomeTeamStats_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    for (int i = 7; i <= 18; i++)\n    {\n        // check row type\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        // if row type is DataRow, add ...                \n        {\n            TotalStats[i-7] += Convert.ToInt32(e.Row.Cells[i].Text);\n        }\n        else if (e.Row.RowType == DataControlRowType.Footer)\n            // If row type is footer, show calculated total value\n            e.Row.Cells[i].Text = String.Format("{0:0.##}", TotalStats[i-7]);\n    }\n}	0
268832	268796	Control key plus mouse wheel	System.Windows.Forms.Control.ModifierKeys	0
6180442	6180258	binding to items self (this) for a button in a itemtemplate/datatemplate?	Tag="{Binding BindsDirectlyToSource=True}"	0
1884471	1884253	How do I get reference to a control on a Datalist's OnItemBound?	(e.Item.FindControl("yourControlName") as YourControlType).Attributes.Add("onClick","DoSomethingHere()");	0
16737253	16737179	Trying to delete file in ProgramData. Access is Denied, even as Admin	The caller does not have the required permission.\n-or-\npath is a directory.\n-or-\npath specified a read-only file.	0
25183132	25174381	Convert code from c# to vb.net	Dim StrInputParam As String = "TYPE:5#MOBILE:" & Mobile & "#PASS:" & Password & ""\nDim StrSPName As String = ConfigurationManager.AppSettings("SP_RED_USER_DETAILS")\nDim ArrayVal() As String = StrInputParam.Split("#"c)\n\nStrSPName = Regex.Replace(StrSPName, "\[(.+?)\]", Function(m) ' "0" instead of m.Value\n      Dim StrParamName As String = m.Groups(1).Value\n      Dim StrParamValue As String = ArrayVal.Select(Function(s) s.Split( { ":"c }, 2)).Where(Function(p) p.Length = 2).Where(Function(p) p(0) = StrParamName).Select(Function(p) p(1)).FirstOrDefault()\n      Return If(StrParamValue, "0")\nEnd Function)	0
28606693	28606511	How does ObservableCollection<T> implement INotifyPropertyChanged as protected?	public class Test : INotifyPropertyChanged\n{\n   // explicit interface implementation\n    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged\n    {\n        add\n        {\n            PropertyChanged += value;\n        }\n        remove\n        {\n            PropertyChanged -= value;\n        }\n    }\n\n    // protected virtual (for derived classes to override)   \n    protected virtual event PropertyChangedEventHandler PropertyChanged;\n}	0
11785521	11785079	Union of Two Objects Based on Equality of Their Members	public static T UnionCombine<T>(this IEnumerable<T> values) where T : new() {\n    var newItem = new T();\n    var properties = typeof(T).GetProperties();\n    for (var prop in properties) {\n        var pValueFirst = prop.GetValue(values.First(), null);\n        var useDefaultValue = values.Skip(1).Any(v=>!(Object.Equals(pValueFirst, prop.GetValue(v, null))));\n        if (!useDefaultValue) prop.SetValue(newItem, pValueFirst, null);\n    }\n    return newItem;\n}	0
13014945	12919334	Trying to secure a directory on windows using .Net	directorySecurity.SetAccessRuleProtection(true, false);	0
1501735	1501719	C# issue with mutiple users trying to access cached object	public class UpdateCache\n{\n   private static object _myLockObject;\n\n   public static void UpdateCache()\n   {\n     lock(_myLockObject)\n     {\n        .. Update cache object\n     }\n   }\n\n   public static void LoadFromCache(string key)\n   {\n     lock(_myLockObject)\n     {\n       .. retrieve data from cache\n     }   \n\n   }\n}	0
15787473	15599682	Strange Behavior in Language usage in WPF application	latha.ttf	0
8400525	8400248	How do I declare a var variable with Roslyn?	Syntax.LocalDeclarationStatement(\n    declaration: Syntax.VariableDeclaration(\n        type: Syntax.IdentifierName(Syntax.Token(SyntaxKind.VarKeyword)),\n        variables: Syntax.SeparatedList(\n            Syntax.VariableDeclarator(\n                identifier: Syntax.Identifier(name)))));	0
2819747	2817707	Find and activate an application's window	using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nclass Program {\n    static void Main(string[] args) {\n        var prc = Process.GetProcessesByName("notepad");\n        if (prc.Length > 0) {\n            SetForegroundWindow(prc[0].MainWindowHandle);\n        }\n    }\n    [DllImport("user32.dll")]\n    private static extern bool SetForegroundWindow(IntPtr hWnd);\n}	0
19356665	19355953	How to disable zoom in chart control in C#?	chart.ChartAreas["ChartAreaName"].AxisX.ScaleView.Zoomable = false;\nchart.ChartAreas["ChartAreaName"].AxisY.ScaleView.Zoomable = false;	0
20185608	19858754	remove images while exporting excel from gridview	protected void Export_to_Excel(object sender, EventArgs e)\n    {\n        //System.Diagnostics.Debugger.Break();\n        Response.Clear();\n        Response.AddHeader("content-disposition", "attachment;filename=PatientSearchReport.xls");\n        Response.ContentType = "application/vnd.xlsx";\n        System.IO.StringWriter stringWrite = new System.IO.StringWriter();\n        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);  \n        GridView1.RenderControl(htmlWrite);\n        string html2 = Regex.Replace(stringWrite.ToString(), @"(<input type=""image""\/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        html2 = Regex.Replace(html2, @"(<input class=""checkbox""\/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        html2 = Regex.Replace(html2, @"(<a \/?[^>]+>)", @"", RegexOptions.IgnoreCase);\n        Response.Write(html2.ToString());\n        Response.End();\n    }	0
18664478	18664313	Use LinkButton to Update data and label	switch (e.CommandName)\n{\n    case "Helpful":\n        ((sender as LinkButton).FindControl("HelpfulLbl") as Label).Text = "Helpful (" + newamt.ToString() + ")" ;\n        break;\n    case "Not Helpful":\n        // The "Not Helpful" is not part of the LinkButton.\n        break;\n}	0
15752412	15752373	RegEx matching double quotes	var doc = XDocument.Parse(xml)\nvar root = doc.Root\nvar osisId = root.Attribute("osisID").Value;	0
8571811	8571066	How to take screenshot using Selenium RC using c# in IE8?	IWebDriver driver = new InternetExplorerDriver();\ndriver.Navigate().GoToUrl("http://www.google.com");\nTakeScreenshot(driver, @"C:\screenshot.png");	0
20101959	20101905	Error when insert data from textbox to database	cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = @text1)",con);	0
16058935	14727510	Getting WPF to update a bound list of DataTables	public class DataTableWithNotification : INotifyPropertyChanged\n{\n    private DataTable _theTable = new DataTable();\n\n    public DataTableWithNotification()\n    {\n    }\n\n    public DataTableWithNotification(DataTable dt)\n    {\n        _theTable = dt;\n    }\n\n    public DataTable Table\n    {\n        get { return _theTable; }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    public void ChangeTableAndNotify(DataTable newTable)\n    {\n        _theTable = newTable;\n\n        OnPropertyChanged("Table");\n    }\n\n    protected void OnPropertyChanged(string name)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(name));\n        }\n    }\n}	0
1837966	1837933	How can I assert that a particular method was called using NUnit?	pubilc class Calc {\n    public int DoubleIt(string a) {\n        return ToInt(a)*2;\n    }\n\n    public virtual int ToInt(string s) {\n        return int.Parse(s);\n    }\n}\n\n// The test:\nvar mock = new Mock<Calc>();\nstring parameterPassed = null;\nmock.Setup(c => x.ToInt(It.Is.Any<int>())).Returns(3).Callback(s => parameterPassed = s);\n\nmock.Object.DoubleIt("3");\nAssert.AreEqual("3", parameterPassed);	0
9565254	9565159	Right-align a currency string (with no symbol)?	String.Format("{0,20:#,##0}", value);	0
28445691	28444812	Introduce page break for columns of horizontal table	span:nth-child(5) {padding-bottom:10px;}	0
122361	122273	Constructor parameters for controllers without a DI container for ASP.NET MVC	public ProductController() : this( new Foo() )\n{\n  //the framework calls this\n}\n\npublic ProductController(IFoo foo)\n{\n  _foo = foo;\n}	0
6451759	6451658	Check if end user certificate installed in windows keystore?	System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.CurrentUser);\nstore.Open(); // Dont forget. otherwise u will get an exception.\nX509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName,"XYZ",true);\nif(certs.Count > 0)\n{\n    // Certificate is found.\n}\nelse\n{\n    // No Certificate found by that subject name.\n}	0
747756	747722	How can I find the current time as a long in C#?	static readonly DateTime epoch=new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);\n...\nlong ms = (long)(DateTime.UtcNow - epoch).TotalMilliseconds;\nlong result = ms / 1000;	0
710197	710182	MySqlConversionException when accessing DateTime field from DataReader	Allow Zero Datetime=true	0
26853930	26853593	How can I read data from a table in Microsoft Azure Mobile Services and put it in my application?	async private void GetUsers() {\n\n    var users = await usersTable.Where (u => u.Name == "Bob").ToListAsync();\n\n}	0
14457662	14457575	Card Game Algorithm for Unique Combinations	def bubble(part, i=0): #add one to the list whilst keeping lexicographic order\n    if i == (len(part)-1) or part[i] < part[i+1]:\n        part[i] += 1\n        return part\n    else:\n        return bubble(part, i+1)\n\ndef partitions(n):\n    if n == 1:\n        yield [1]\n        return\n    for p in partitions(n-1):\n        yield [1] + p\n        yield bubble(p)	0
3733833	3733755	Getting the String Text of SelectedItem in Silverlight Listbox (C#)	CustomObject obj = lstName.SelectedItem as CustomObject\n\n\nif(obj!=null)\n\n{\n   string name = obj.Name;\n}	0
3069500	3069484	Displaying currency in C#	string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:C}", decimalValue)	0
5192538	5190074	C# MVVM - Is a model required here?	class CustomerViewModel(Customer customer, CustomerDao){...}	0
24157661	24157559	Xml Serialization - Render list of objects directly under Root - Xml - Element	[XmlRoot]\npublic class A\n{\n    [XmlAttribute]\n    public string Period { get; set; }\n\n    [XmlElement("C")]\n    public List<C> B { get; set; }\n\n}	0
16293050	16292987	Make a class field read only after the fact	Period period = new PeriodBuilder { Days = 1, Hours = 22 }.Build();	0
6414656	6414259	How to Bind a ReportViewer to an IEnumerable<T>	ReportDataSource reportDataSource = New ReportDataSource("test", listofclients);\nlocalreport.DataSources.Add(reportDataSource);	0
28190725	28188918	passing an argument from an aspx page to a UserControl	navigationMenu.operate = false;	0
28532855	28531799	Response of "Faulted" when sending a tweet using linqtotwitter	Status tweet = await ctx.TweetAsync(text);	0
3531376	3531234	How do I produce a collection of game entities from another collection without producing garbage?	public void Query(Vector2 center, float radius, List<SampleEntity> result)\n {\n     result.Clear();\n     result.Add(/*...*/);\n     // ...\n }	0
18025316	18025186	Uploading zip file with POST/httpwebrequest in C#	FileInfo fInfo = new FileInfo(file.FullName);\n// \nlong numBytes = fInfo.Length;\n\nFileStream fStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);\n\nBinaryReader br = new BinaryReader(fStream);\n\nbyte[] bdata = br.ReadBytes((int)numBytes);\n\nbr.Close();\n\nfStream.Close();\n\n// Write bdata to the HttpStream\nHttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("url-here");\n// Additional webRequest parameters settings.\nHttpStream stream = (Stream)webRequest.GetRequestStream();\nstream .Write(bdata, 0, bdata.Length);\nstream.Close();\n\nHttpWebResponse response = (HttpWebRewponse)webRequest.GetResponse();	0
8622207	8622073	How to prevent balloon tips from accumulating?	ShowBalloonTip()	0
2253109	2253096	How can I get a NullReferenceException in this code sample?	Nullable<T>	0
929960	929179	Get the item doubleclick event of listview	private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n{\n    DependencyObject obj = (DependencyObject)e.OriginalSource;\n\n    while (obj != null && obj != myListView)\n    {\n        if (obj.GetType() == typeof(ListViewItem))\n        {\n            // Do something here\n            MessageBox.Show("A ListViewItem was double clicked!");\n\n            break;\n        }\n        obj = VisualTreeHelper.GetParent(obj);\n    }\n}	0
2878729	2878696	How do I determine if a process is associated with a System.Diagnostics.Process object?	Process.Id	0
31123161	31057076	How do I sort a combobox after a user inputs text	int newItemIndex = 0;\n            foreach (ListItem li in cmbOutputRating.Items)\n            {\n\n                if (Convert.ToDouble(li.Value) < curLoad.Size)\n                {\n                    newItemIndex++;\n                }\n            }\n\n            cmbOutputRating.Items.Insert(newItemIndex, curLoad.Size.ToString());	0
17718736	17718621	SqlDataReader filling column in datagridview	for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)\n        {\n            var row = dtg_ksluzby.Rows[i];\n            using(var novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE text LIKE @t AND subkey=@s", spojeni))\n            {\n                novyprikaz2.Parameters.AddWithValue("@t", row.Cells["text"].Value.ToString());\n                novyprikaz2.Parameters.AddWithValue("@s", vyberradek);\n                spojeni.Open();\n                SqlDataReader precti2 = novyprikaz2.ExecuteReader();\n                if (precti2.Read())\n                {\n                    row.Cells["pocet"].Value = precti2["pocet"];\n                }\n            }\n        }	0
7214395	7214253	Capturing TAB in a Gtk# TreeView widget	/* ... */\ncell.KeyPressEvent += onCellKeyPress;\n\n[GLib.ConnectBefore]\nvoid onCellKeyPress(object sender, EventArgs e)\n{\n/* ... */\n}	0
9285367	9284097	How to step frame back in DirectShow.NET?	IMediaSeeking::SetPositions	0
11216377	11215637	How do I get Image.Source from QRCodeWriter?	QRCodeWriter writer = new QRCodeWriter();\n    com.google.zxing.common.ByteMatrix matrix;\n\n    int size = 180;\n    matrix = writer.encode("MECARD:N:Owen,Sean;ADR:76 9th Avenue, 4th Floor, New York, NY 10011;TEL:+12125551212;EMAIL:srowen@example.com;; ", BarcodeFormat.QR_CODE, size, size, null);\n\n\n    Bitmap img = new Bitmap(size, size);\n    Color Color = Color.FromArgb(0, 0, 0);\n\n    for (int y = 0; y < matrix.Height; ++y)\n    {\n        for (int x = 0; x < matrix.Width; ++x)\n        {\n            Color pixelColor = img.GetPixel(x, y);\n\n            //Find the colour of the dot\n            if (matrix.get_Renamed(x, y) == -1)\n            {\n                img.SetPixel(x, y, Color.White );\n            }\n            else\n            {\n                img.SetPixel(x, y, Color.Black);\n            }\n        }\n    }\n\n\n    img.Save(@"c:test.bmp",ImageFormat.Bmp);	0
8811889	8811834	Fixed Point Generator in C# Generics	public Func<T, T> Fix<T>(Func<Func<T,T>, Func<T,T>> F) {\n  return t => F(Fix(F))(t);\n}	0
29299655	29298553	How to excecute a function for a specific time?	//Below code will excecute the code for 10 sec \nStopwatch stopWatch = new Stopwatch();\n\n\n\n do\n {\n  stopWatch.Start();\n\n//perform your Function\n\n    if (result = true)\n    {\n    stopwatch.reset();\n    break;\n    } \n\n    }While (stopWatch.Elapsed.Seconds <= 10));	0
27090608	27090179	Convert string array to int array 'System.FormatException'	static int[] data()\n            {\n                List<int> database = new List<int>();\n                StreamReader house = new StreamReader("text.txt");\n                while (!house.EndOfStream)\n                {\n                    s = house.ReadLine();\n                    Console.WriteLine(s);\n\n                    string[] data1 = s.Split(' ');\n                    for (int j = 0; j < data1.Length; j++)\n                    {    \n                        int value;\n                        if (Int32.TryParse(data1[j], out value))\n                            database.Add(value));\n                    }       \n                }\n                house.Dispose();\n                return database.ToArray();\n            }	0
1105998	1102611	Restricting results from a repository	var rep = new Repository<Product>();\nvar specification = new MarketSpecification("xy") && new CategorySpecification("shirts");\nvar list = rep.Find(specification);	0
1817041	1816957	C#: How can I create a header in a table for each new page with Word interop?	Microsoft.Office.Interop.Word.Table table;\n/* ... */\ntable.Rows[1].HeadingFormat = -1;	0
22276674	22276247	Linq from list objects into one object with a list property	destinationObject = MyObjectList.Select(x =>\n        new ObjectToSelectInto()\n        {\n           AllProductColors = MyObjectList.Select(y => y.ProductName).ToList(),\n           ImgUrl = x.ImgUrl,\n           ProductName = x.ProductName\n       }).First();	0
6369318	6369187	How do I start/stop/restart a windows service on a remote machine using .net	ServiceController service = new ServiceController(serviceName, machineName);	0
7598196	7598172	error insert DateTime c# type to SQL DateTime column	SqlCommand cmd = new SqlCommand("Insert into Books (Name,PublishDate,IsInternal) Values (@Name,@PublishDate,@IsInternal)");\ncmd.Parameters.Add(new SqlParameter("@Name", System.Data.SqlDbType.VarChar, 50));\ncmd.Parameters.Add(new SqlParameter("@PublishDate", System.Data.SqlDbType.DateTime));\ncmd.Parameters.Add(new SqlParameter("@IsInternal", System.Data.SqlDbType.Bit));\n\ncmd.Parameters["@Name"].Value = book.Name;\ncmd.Parameters["@PublishDate"].Value = book.PublishedDate;\ncmd.Parameters["@IsInternal"].Value = book.IsInternal;	0
21968837	21968684	How to fix a DirectoryNotFoundException?	var overlayImage\n  = new BitmapImage(new Uri("pack://application:,,,/KinectKickboxingBVversion1;component/Images/boxbag.png"));	0
20467191	20465654	Passing a ref to a collection element	MessageStruct[] messages = new MessageStruct[64];\n\nmessages[0] = new MessageStruct();\n\nUpdateMessage(ref messages[0]);\n\nConsole.writeline(message[0]);	0
21123024	21122957	Populating gridview based off a query	using System.Text;	0
16548420	16538042	Not setting the property of incoming mails in MS Outlook 2010	int i = myInbox.Items.Count;\nMailItem msg = (Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i];\nmsg.UnRead = false;\nmsg.Importance = OlImportance.\nmsg.Save();	0
2073986	2073922	Conditional image in datagrid	protected void Page_Init(object sender, EventArgs e)\n{\n  // first you have to hook up the event\n  datagrid.ItemDataBound += datagrid_ItemDataBound;\n}\n\n// once the grid is being bound, you have to set the status image you want to use\nprivate void datagrid_ItemDataBound(object sender, DataGridItemEventArgs e)\n{\n  if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {\n    Image img = (Image)e.Item.FindControl("ImageControlName");\n    if( ValidationFunction() ) {\n      img.ImageUrl = "first_status_image.jpg";\n    } \n    else \n    {\n      img.ImageUrl = "second_status_image.jpg";\n    }\n  }\n}	0
11002548	11002532	The recreated columns in a DataGridView	dgv.AutoGenerateColumns=false;	0
93045	88717	Loading DLLs into a separate AppDomain	AppDomain domain = AppDomain.CreateDomain("New domain name");\n//Do other things to the domain like set the security policy\n\nstring pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load\nType t = typeof(TypeIWantToLoad);\nTypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);	0
5129138	5129116	How to bind a single object instance in WPF?	public SettingsDialog(SettingsObject settings)\n{\n\n    InitializeComponent();\n\n    //While this line should work above InitializeComponent,\n    // it's a good idea to put your code afterwards.\n    this.AppSettings = settings;\n\n    //This hooks up the windows data source to your object.\n    this.DataContext = settings;\n}	0
14646801	14646662	Insert values in separate table rows	string str = string.Empty;\n try\n {\n    var sb = new StringBuilder();\n    SqlConnection con = new SqlConnection();\n    con.ConnectionString = connString;\n\n    SqlCommand com = new SqlCommand();\n    com.Connection = con;\n    var collection = ListLawCat.CheckedItems;\n    foreach (var item in collection)\n    {\n\n    com.CommandText = "Insert into TABLE (COL1, COL2) values ('" +  item.Value+ "','" + DocID + "') ";\n    com.CommandType = CommandType.Text;\n\n    con.Open();\n\n    int j = com.ExecuteNonQuery();\n    if (j > 0)\n    {\n        Response.Write("insert successfully");\n        Response.Write( item.Value);\n    }\n    else\n    {\n        Response.Write("Not Inserted");\n    }\n    con.Close();\n    }\n}\ncatch (Exception ex)\n{\n    Response.Write(ex.Message);\n}	0
8866453	8866414	How to Sort 2D Array in C#	char[] symbols = ...\nint[] counts = ...\n...load the data...\nArray.Sort(counts, symbols);\n// all done!	0
1330504	1330473	Generic return types from abstract/virtual methods	public abstract class RecruiterBase<T, C> where C : CandidateBase\n{\n  // Properties declare here\n  // Constructors declared here\n\n  public abstract IQueryable<C> GetCandidates();\n}\n\npublic abstract class CandidateBase<T>\n{\n  // Properties declare here\n  // Constructors declared here\n}\n\npublic class CandidateA : CandidateBase<CandidateA>\n{\n  // Constructors declared here\n}\n\npublic class RecruiterA : RecruiterBase<RecruiterA, CandidateA>\n{\n  public override IQueryable<CandidateA> GetCandidates()\n  {\n return from c in db.Candidates\nwhere c.RecruiterId == this.RecruiterId\nselect new CandidateA\n{\n  CandidateId = c.CandidateId,\n  CandidateName = c.CandidateName,\n  RecruiterId = c.RecruiterId\n};\n  }\n}	0
1640002	1639976	Understanding a factorial function in python	iProduct = 1\nfor iFactor in xrange(1, i+1):\n    iProduct *= iFactor	0
8568258	8568230	Create Image array in Windows Phone 7	MyGrid.Children.Add(stone[0]);	0
30350759	30350417	How to filter XDocument based on children attributes and keeping parent structure?	// first make a list of elements that are to be removed\nvar forRemoval = new List<XElement>();\nforeach (var element in xmlDoc.Descendants())\n{\n    if (!element.DescendantsAndSelf().Any(e => e.Attribute("attr") != null && e.Attribute("attr").Value.Contains("xyz")))\n    {\n        forRemoval.Add(element);\n    }\n}\n\n// then remove the elements\nforeach (var xElement in forRemoval)\n{\n    xElement.Remove();\n}	0
16330046	16329589	Add binding to json using JavaScriptSerializer with list asp.net c#	return Serialize( new { response = samp });	0
7985329	7985298	Get value from dictionary key while for each and its element is string	dictionaryFrquencyLetter = frequency[letter];	0
24282737	24282172	WPF bind data to user control inside another user control dynamically	private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n    Day day = e.NewValue as Day;\n    foreach (var item in day.Shifts)\n    {\n         ShiftControl ctrl = new ShiftControl();\n        // here I somehow want to bind item.StartTime to ctrl.StartTime\n\n         Binding myBinding = new Binding("StartTime");\n         myBinding.Source = item;\n         ctrl.SetBinding(ShiftControl.StartTimeProperty, myBinding);\n\n         _shifts.Children.Add(ctrl);\n }\n}	0
32895236	32893188	Populate TreeView with non-Empty Folders	foreach (var directory in directoryInfo.GetDirectories())\n{\n    TreeNode subNode = CreateDirectoryNode(directory);\n    if (subNode.Nodes.Count > 0)\n        directoryNode.Nodes.Add(CreateDirectoryNode(directory));\n}	0
7844895	7844355	How to detect EOF on DataReader in C# without executing Read()	public class DataReaderWithEOF\n{\n     public bool EOF { public get; private set; }\n     private IDataReader reader;\n\n     public DataReaderWithEOF(IDataReader reader)\n     {\n          this.reader = reader;\n     }\n\n     public bool Read()\n     {\n           bool result = reader.Read();\n           this.EOF = !result;\n           return result;\n     }\n}	0
13767967	13767732	DropDownList duplicate items	protected void Button6_Click( object sender , EventArgs e )\n{\n    string categoryToCreate = CreateCategory.Text;\n\n    if(categoryToCreate != string.Empty)\n    {\n        CategoryCreateName.Visible = false;\n        DataAccess.insertDataItem(categoryToCreate);\n        CategoryList.Items.Clear();\n        CategoryList.DataBind(); \n    }else\n    {\n        CategoryCreateName.Visible = true;\n    }\n}	0
9771284	9770956	Get all contacts from a group in gmail	public void PrintDateMinQueryResults(ContactsRequest cr)\n{\n  ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));\n  query.Group = //The group atom id\n}	0
16116932	16115985	How to populate gridview with mysql?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing MySql.Data.Common;\nusing MySql.Data.MySqlClient;\nusing System.Data.SqlClient;\nusing System.Windows.Forms;\nusing System.Data;\n\npublic partial class viewAdmin : System.Web.UI.Page\n{\n    String MyConString = "SERVER=localhost;" +\n                "DATABASE=databasename;" +\n                "UID=root;" +\n                "PASSWORD=;";\nprotected void Page_Load(object sender, EventArgs e)\n{\n\n        MySqlConnection conn = new MySqlConnection(MyConString);\n        MySqlCommand cmd = new MySqlCommand("SELECT * FROM tablename;", conn);\n        conn.Open();\n        DataTable dataTable = new DataTable();\n        MySqlDataAdapter da = new MySqlDataAdapter(cmd);\n\n        da.Fill(dataTable);\n\n\n        GridVIew.DataSource = dataTable;\n        GridVIew.DataBind();\n}\n\n}	0
24918094	24917893	Audit Table from Datagridview C#	DataGridView.CellValueChanged	0
11590982	11590853	Binary deserialization: get object data	object yourData;\n            var SerializeBinaryFileName = @"C:\Temp\binary.bf";\n\n            using (Stream stream = File.Open(SerializeBinaryFileName, FileMode.Open))\n            {\n                BinaryFormatter bformatter = new BinaryFormatter();\n                yourData = bformatter.Deserialize(stream);\n                stream.Close();\n            }	0
14707015	14706971	How to access a method of a form from another class ensuring it is the same Form instance - C#	// on Form1\nClass1 c1 = new Class1();\nc1.DoSomething(this);\n\n// Class1\npublic void DoSomething(Form1 form)\n{\n    form.updateDataGUI(row, url, result, time);\n}	0
10059084	10058890	Convert mp4 to mp3	Dim _out As String = ""\n Dim _process As New Process()\n _process.StartInfo.UseShellExecute = False\n _process.StartInfo.RedirectStandardInput = True\n _process.StartInfo.RedirectStandardOutput = True\n _process.StartInfo.RedirectStandardError = True\n _process.StartInfo.CreateNoWindow = True\n _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden\n _process.StartInfo.FileName = "ffmpeg";\n _process.StartInfo.Arguments = " -i input.mp4 -vn -f mp3 -ab 192k output.mp3";\n _process.Start()\n _process.StandardOutput.ReadToEnd()\n _out = _process.StandardError.ReadToEnd()\n _process.WaitForExit()\n If Not _process.HasExited Then\n    _process.Kill()\n End If\n Return _out	0
15633708	15633665	Get distinct dates in datatable	dt.AsEnumerable().Distinct(r => row.Field<DateTime>("TimeStamp").Date);	0
31765145	31765089	Indirect reference to a button	private void OnClick(object sender, EventArgs e)\n{\n    if( sender is Button )\n    {\n        Button button = (Button)sender;\n        button.Enabled = false;\n    }\n}	0
13581206	13580945	How to Select XML Nodes with XML Namespaces with C#	string xmlNamespace = String.Empty;\nXmlNamespaceManager nsmgr;\nXmlNodeList nodeInfo = FABRequestXML.GetElementsByTagName("RootNodeName");\nxmlNamespace = Convert.ToString(nodeInfo[0].Attributes["xmlns"].Value);\nnsmgr = new XmlNamespaceManager(MyXml.NameTable);\nnsmgr.AddNamespace("AB", xmlNamespace);\n\nXmlNode myNode = MyXml.DocumentElement.SelectSingleNode("AB:NodeName", nsmgr);	0
555095	555073	Enable multiple HTTP Methods on a single operation?	[OperationContract,\nWebInvoke(Method="POST",\n    BodyStyle = WebMessageBodyStyle.Bare,\n    RequestFormat = WebMessageFormat.Xml,\n    ResponseFormat = WebMessageFormat.Xml,\n    UriTemplate = "query")]\nXElement Query_Post(string qry);\n\n[OperationContract,\nWebInvoke(Method="GET",\n    BodyStyle = WebMessageBodyStyle.Bare,\n    RequestFormat = WebMessageFormat.Xml,\n    ResponseFormat = WebMessageFormat.Xml,\n    UriTemplate = "query?query={qry}")]\nXElement Query_Get(string qry);	0
19114624	19112689	C# Using StreamReader, Disposing of Response Stream	using (var response = request.GetResponse())\nusing (var reader = new StreamReader(response.GetResponseStream()))\n{\n   x = reader.ReadToEnd();\n}	0
2000013	1999785	entity framework multiple many to many queries	var predicate = PredicateBuilder.False<WebPath>();\nforeach (var role in from roles in rolesForUser \n                     from r in roles.Role\n                     select r)\n{\n  predicate = predicate.Or (p => p.roles.Any(r => r.Id == role.Id));\n}\n\nvar authentications = _entities.WebPaths.AsExpandable()\n         .Where(p => p.Path == path)\n         .Where(predicate);\nreturn (authentications.Count() > 0);	0
30736707	30736359	Allow console application to access Windows Authenticated web app	var client = new WebClient\n                     {\n                         UseDefaultCredentials = true\n                     };\n        client.DownloadString(address);	0
803044	803027	Finding the referring url that brought a user to my site	Request.UrlReferrer	0
13067533	13067306	Enter character every 4(th) character in string	string s = "XXX1XXX2XXX3XXX4";\nStringBuilder sb = new StringBuilder();\n\nfor (int i = 0; i < s.Length; ++i)\n{\n    sb.Append(s[i]);\n\n    if ((i < s.Length-1) && ((i+1) % 4) == 0)\n    {\n        sb.Append('-');\n    }\n}\n\ns = sb.ToString();\nConsole.WriteLine(s);	0
12245923	12245864	Maintain DataTable & Variables throughout Session	DataTable dt = new DataTable();\n// I assumed that dt has some data\n\nSession["dataTable"] = dt; // Saving datatable to Session\n// Retrieving \nDataTable dtt = (DataTable) Session["dataTable"]; // Cast it to DataTable\n\nint a = 43432;\nSession["a"] = a;\n// Retrieving \nint aa = (int) Session["a"];\n\n// classes\n  class MyClass\n  {\n    public int a { get; set; }\n    public int b { get; set; }\n  }\n\n  protected void Page_Load(object sender, EventArgs e)\n  {\n\n    MyClass obj = new MyClass();\n    obj.a = 5;\n    obj.b = 20;\n\n    Session["myclass"] = obj;  // Save the class object in Session\n    ?// Retrieving?\n      MyClass obj1 = new MyClass();\n       obj1 = (MyClass) Session["myclass"]; // Remember casting the object\n   }	0
21446135	21444299	Unit of work/Transaction within an application service method?	CreateUser(...)\n{\n   //1.) New up user object\n   //2.) Add newly created object to database\n   //3.) Publish user setup event by messaging\n\n   //4.) Commit transaction ( ensures message is successfully sent AND object is created  in database, else transaction fails\n   }	0
5593583	5593259	How to observe dependent events in Reactive Extensions (Rx)?	initResult.SelectMany(ir =>\n       {   \n           if (ir != null)\n           {\n             return connectResult;\n           }\n\n           Console.WriteLine("Initialization failed thus connection failed.");\n\n           return Observable.Throw(new Exception("Some Exception"));\n       })\n       .Subscribe(cr =>\n           {\n              Console.WriteLine(cr != null\n                 ? "Connection succeeded." \n                 : "Connection failed.");\n           })	0
1205027	1204930	POST data from a text file (read by a desktop client) to an ASP .NET based server	string textFileContents = System.IO.File.ReadAllText( @"C:\MyFolder\MyFile.txt" );\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://www.myserver.com/myurl.aspx" );\nrequest.Method = "POST";\n\nASCIIEncoding encoding = new ASCIIEncoding();\n\nstring postData = "fileContents=" + System.Web.HttpUtility.UrlEncode( textFileContents );\n\nbyte[] data = encoding.GetBytes( postData );\n\nrequest.ContentType = "application/x-www-form-urlencoded";\nrequest.ContentLength = data.Length;\n\nStream dataStream = request.GetRequestStream();\n\ndataStream.Write( data, 0, data.Length );\n\ndataStream.Close();\n\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n// do something with the response if required	0
8196121	8195874	how to get an ordered list with default values using linq	var records = new int[][] { new int[] { 1, 1, 2 }, new int[] { 1, 2, 3 }, new int[] { 2, 3, 1 } };\n        var items = new int[] { 3, 1 };\n\n        var userId = 1;\n\n        var result = items.Select(i =>\n        {\n            // When there's a match\n            if (records.Any(r => r[0] == userId && r[1] == i))\n            {\n                // Return all numbers\n                return records.Where(r => r[0] == userId && r[1] == i).Select(r => r[2]);\n            }\n            else\n            {\n               // Just return 0\n                return new int[] { 0 };\n            }\n        }).SelectMany(r => r); // flatten the int[][] to int[]\n\n        // output\n        result.ToList().ForEach(i => Console.Write("{0} ", i));\n        Console.ReadKey(true);	0
25155074	25134766	Start CS-Script as administrator	//css_inc Elevate.cs;\n//css_pre elevate();	0
9599038	9598850	Read data in string from begin to end	HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();\nhtmlDoc.LoadHtml(html);\nvar str = htmlDoc.DocumentNode\n    .Descendants("td")\n    .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "m92_h_bigimg")\n    .Select(x => x.InnerHtml)\n    .First();	0
1378823	1378801	Convert linq query to string array - C#	private string[] WordList()\n{\n    using (DataContext db = new DataContext())\n    {\n       return db.Words.Select( x => x.Word ).OrderBy( x => x ).ToArray();\n    }\n}	0
7475327	7475200	SQL Server connection management with C#	using (SqlConnection conn = new SqlConnection("connection string here"))\nusing (SqlCommand cmd = new SqlCommand("sql query", conn))\n{\n    // execute it blah blah\n}	0
16294231	16294170	order column in DataTable before binding to grid	// Create DataView\nDataView view = myDataTable.defaultview;\n// Sort by PROVIDER_ID and PROVIDER_NAME column in descending order\nview.Sort = "PROVIDER_ID ASC, PROVIDER_NAME ASC";\nProductRanges_Grd.DataSource = view.ToTable();	0
32302755	32302386	How to handle packages such as EF, MVC4, WebPages and friends in my project repository	Tools -> Options -> NuGetPackage Manager	0
752825	752806	Getting index of a gridview when hyperlinkfield is clicked	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            if(Request.QueryString["id"] != null &&\n                Request.QueryString["id"] == DataBinder.Eval(e.Row.DataItem, "id").ToString())\n            {\n                e.Row.Style.Add("font-weight", "bold");\n            }\n        }\n    }	0
9133913	9133880	Getting buttonbackground image from dynamically added button	protected void buttonClick(object sender, EventArgs args)\n{\n     Button myButton = (Button)sender;\n     ImageProcessMethod(myButton.BackgroundImage);\n}	0
13950382	13949983	Change button color when clicked (multiple clicks/colors)	void btnEvent_click(object sender, EventArgs e)\n        {\n            Control ctrl = ((Control)sender);\n            switch (ctrl.BackColor.Name)\n            { \n                case "Red":\n                    ctrl.BackColor = Color.Yellow;\n                    break;\n                case "Black":\n                    ctrl.BackColor = Color.White;\n                    break;\n                case "White":\n                    ctrl.BackColor = Color.Red;\n                    break;\n                case "Yellow":\n                    ctrl.BackColor = Color.Purple;\n                    break;\n                default:\n                    ctrl.BackColor = Color.Red;\n                    break;\n            }\n        }	0
1217697	1217634	How do you create columns programmatically in C# for a WPF toolkit datagrid?	MyDataGrid.Columns.Add(new DataGridTextColumn()\n{\n    Header="MyHeader", \n    Binding=new Binding("MyProperty")\n});	0
1291087	1291076	How do I convert a c# two-dimensional array to a JSON object?	int[][] numbers = new int[8][];\n\nfor (int i = 0; i <= 7; i++) {\n   numbers[i] = new int[4];\n   for (int j = 0; j <= 3; j++) {\n      numbers[i][j] =i*j;\n   }\n}	0
6005670	6005659	C# How do you calculate number of days using Month Calendar in Windows Forms?	NumberDays = (Calendar.SelectionEnd - Calendar.SelectionStart).TotalDays;	0
24330392	24310674	How to get the path of the installed Excel.exe programmatically?	string path = string.Empty;\n\n            Process[] processlist = Process.GetProcesses();\n            foreach (Process theprocess in processlist)\n            {\n                if (theprocess.ProcessName == "EXCEL")\n                {\n                    path = theprocess.MainModule.FileName;\n                    break;\n                }\n            }\n\n            if (path == string.Empty)\n            {\n                Type officeType = Type.GetTypeFromProgID("Excel.Application");\n                dynamic xlApp = Activator.CreateInstance(officeType);\n                xlApp.Visible = false;\n                path = xlApp.Path + @"\Excel.exe";\n                xlApp.Quit();\n            }	0
3908706	3908631	How to draw text onto a jpg and resave it using system.drawing in c#	Bitmap bmp = new Bitmap("C:\\test.jpg");\nGraphics gra = Graphics.FromImage(bmp);\nstring text = "Hello\nWorld";\n\ngra.DrawString(text, new Font("Verdana", 24), Brushes.Black, new PointF(0, 0));\nbmp.Save("C:\\test_out.jpg");	0
1738136	1738108	How to use linq2Xml without the possibility of a null exception?	var userData = queryUserResponseData.Elements("user").Single(u => (string)u.Element("username") == userName);	0
28297414	28297373	C# reading from a CSV file	...\nwhile (!parser.EndOfData)\n{\n    // Loading the fields of a Person \n    string[] fields = parser.ReadFields();\n\n    // Starting the process that creates a new Person \n    Person personToAdd = new Person();\n    personToAdd.username = fields[0];\n    personToAdd.firstName = fields[1];\n    personToAdd.lastName = fields[2];\n    personToAdd.email = fields[3];\n    personToAdd.password = fields[4];\n    personToAdd.role = fields[5];\n\n    // Adding the new person to the list\n    people.Add(personToAdd);	0
4988516	4987505	Can you dynamically fill in a db value on commit in nhibernate/fluent nhibernate?	var repeatingId = session.Save(firstAppointmentOfTheGroup)\nforeach (var appointment in repeating)\n{\n    appointment.RepeatingId = repeatingId;\n    session.Save(appointment);\n}	0
20603820	20603775	Using windows forms controls on a WPF page	this.Children.Add(HOST);	0
32310608	32309950	How to add two users in one role in "aspnet_usersinroles"?	var user = UserManager.FindByName("YourUserName");\n           UserManager.AddToRole(user.Id, "Administrator");\n           context.SaveChanges();	0
27614672	27614564	cannot add XAttribute into an XElement	XElement xmlTree = new XElement("Root",\n                                new XAttribute("Att1", "content1"),\n                                new XAttribute("Att2", "content2")\n                            );\n            var attributes = xmlTree.Attributes().ToList();\n            attributes.Insert(0, new XAttribute("test", "testAttr"));\n            xmlTree.ReplaceAttributes(attributes);	0
33239327	33239136	linq help to exclude null items	var emailNodes =\n    _htmlDocument.Value.DocumentNode.SelectNodes("//a[@href]")\n                 .Where(a => a.Attributes["href"] != null)\n                 .Select(a => a.Attributes["href"].Value)\n                 .Where(href => !String.IsNullOrEmpty(href) && href.StartsWith("mailto:")) // keep emails, skipp links\n                 .ToList();	0
28282456	28282340	Button with codebehind	Button b = new Button();\nb.Content = "Table 1";\nGrid.SetColumn(b, 1);\nb.Click += button_Click;\nb.CommandParameter = 1;\nb.HorizontalAlignment = HorizontalAlignment.Left;\nb.Margin = new Thickness(34, 31, 0, 0);\nGrid.SetRowSpan(b, 2);\nb.VerticalAlignment = VerticalAlignment.Top;\nb.Width = 118;\nb.Height = 39;	0
11773490	11759278	Returning a value from store procedure and outputing in XML	Create PROCEDURE [dbo].[updateGamePlay]\n    @GamePlayID int,\n    @ParticipantID int,\n    @GameVersionID int,\n    @GameID int,\n    @GameScenarioID int,\n    @Start DateTime,\n    @End DateTime,\n    @Success varchar(10)\nAS\n    UPDATE GamePlay\n    OUTPUT INSERTED.GamePlayID\n    SET \n    ParticipantID = @ParticipantID,GameVersionID = @GameVersionID,GameID = @GameID,GameScenarioID = @GameScenarioID,StartDateTime = @Start,EndDateTime = @End,Success = @Success\nWHERE GamePlayID = @GamePlayID	0
489208	489173	Writing XML with C#	XDocument document = new XDocument();\ndocument.Add(new XComment("Config generated on 01/01/01"));\ndocument.Add(new XElement("Config", new XElement("GuiPath", guiPath)));\n\n// var xmlWriter = new XmlTextWriter("client_settings.xml", null);\n// document.WriteTo(xmlWriter);\n\n// thanks to Barry Kelly for pointing out XDocument.Save()\ndocument.Save("client_settings.xml");	0
17840198	17839967	How do I check that a string doesn't include any characters other than letters and numbers?	char[] invalidChars = Path.GetInvalidPathChars();\nif (!input.All(c => !invalidChars.Contains(c)))\n{\n    //invalid file name	0
15034761	15034528	Easier way to get one of two variables to have one of two options randomly?	Random random = new Random();\nint x, y;\nswitch (random.Next(2))\n{\n    case 1:\n        x = random.Next(721 - Width);\n        y = random.Next(2) == 1 ? 721 - Height : 0;\n        break;\n    default:\n        y = random.Next(721 - Height);\n        x = random.Next(2) == 1 ? 721 - Width : 0;\n        break;\n}	0
10198391	10198370	Execute lambda expression immediately after its definition?	new Action(() => { Console.WriteLine("Hello World"); })();	0
3060335	3060299	Dynamically find the parameter to be passed as <T> to a generic method	MethodInfo method = typeof(YourClass).GetMethod("GetComparisonObject");\nMethodInfo generic = method.MakeGenericMethod(GenericArgumentType);\nObject retVal = generic.Invoke(this, new object[] { attribute, parseObject });	0
24807608	24806697	Is there any way to activate a window with White?	[DllImport("user32.dll", SetLastError = true)]\n    internal static extern bool SetForegroundWindow(IntPtr windowHandle);\n\n\n    public bool SearchTest(string file) {\n        try\n        {\n            // White stuff, not relevant to problem\n            //var application = Application.Attach("SearchApp"); \n            //var searchWindow = application.GetWindows()[0];\n\n            Process p = Process.GetProcessesByName("SearchApp")[0];\n            SetForegroundWindow(p.MainWindowHandle);	0
1937126	1937080	Receiving binary data from HTTP POST Request in ASP.NET C#	Request.Files	0
12062166	12062045	Using configurationmanager to read from multiple web.config files	System.Configuration.KeyValueConfigurationCollection settings;\n        System.Configuration.Configuration config;\n\n        System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();\n        configFile.ExeConfigFilename = "my_file.config";\n        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);\n        settings = config.AppSettings.Settings;	0
30078689	30078642	How to create binding from Expression instead of string?	public static string GetPropertyName<T>(Expression<Func<T>> expression)\n{\n    MemberExpression body = (MemberExpression)expression.Body;\n    return body.Member.Name;\n}	0
24802927	24802575	In .NET, is there a concept of global variables?	Module UserDetails\n\nPublic SqlCon as SqlConnection\nPublic DataSet as DataSet\nPublic dataAdaptr as SqlDataAdapter\n\nEnd Module	0
4072859	4072490	Is there a way to programmatically convert VB6 Formatting strings to .NET Formatting strings?	using System;\nusing System.Runtime.InteropServices;\n\nclass Program {\n    static void Main(string[] args) {\n        Console.WriteLine(Vb6Format("hi there", ">"));\n        Console.WriteLine(Vb6Format("hI tHeRe", "<"));\n        Console.WriteLine(Vb6Format("hi there", ">!@@@... not @@@@@"));\n        Console.ReadLine();\n    }\n\n    public static string Vb6Format(object expr, string format) {\n        string result;\n        int hr = VarFormat(ref expr, format, 0, 0, 0, out result);\n        if (hr != 0) throw new COMException("Format error", hr);\n        return result;\n    }\n    [DllImport("oleaut32.dll", CharSet = CharSet.Unicode)]\n    private static extern int VarFormat(ref object expr, string format, int firstDay, int firstWeek, int flags,\n        [MarshalAs(UnmanagedType.BStr)] out string result);\n}	0
25500901	25482232	In-App Purchase Receipt Parsing In WP8	XDocument xml = XDocument.Parse(receipt);\nXElement productReceipt = xml.Root.Elements().FirstOrDefault();\nstring orderId = productReceipt.Attribute("Id").Value;	0
7151379	7142941	How to Find ListBox1.SelectedItem in other ListBox2 Items	//setting the selected item in the second list\n if (selectedItem != null)\n  listBox2.SelectedItem = (\n    from item in listBox2.Items.Cast<DataRowView>()\n    where item[listBox2.ValueMember].ToString() == ((DataRowView)selectedItem)[listBox1.ValueMember].ToString()\n    select item).FirstOrDefault();	0
30667181	30666667	Elasticsearch Date Histogram report with Terms aggregation	var dateHistogram = searchResponse.Aggs.DateHistogram("jobcounts_by_year");\n\nforeach (var item in dateHistogram.Items)\n{\n    var bucket = item.Terms("top_agg");\n}	0
28114233	28114052	RichTextbox Find	int max = this.TextLength;\n    while (startSearch < max && \n           (index = this.Find(findWhat, startSearch, findoptions)) > -1) {\n        isFind = true;\n        this.SelectionBackColor = highlightColor; \n        startSearch = index + 1;\n    }	0
16710056	16709997	Regex to contain only first two digit c#	^[0-9]{2}	0
4651134	4651114	Convert Text with newlines to a List<String>	List<string> idList = ids.Split(new[] { "\r\n" }, StringSplitOptions.None)\n                         .ToList();	0
2314690	2268175	Using Linq to SQL, how do I find min and max of a column in a table?	from row in MyTable  \ngroup row by true into r  \nselect new {  \n    min = r.Min(z => z.FavoriteNumber),  \n    max = r.Max(z => z.FavoriteNumber)  \n}	0
32304796	32304428	Calling Form2's function from Form1 with Form1's public variables	private void cpanel_btn_Click(object sender, EventArgs e)\n{\n    Form2 cPanel = new Form2(this);\n    cPanel.Show();\n}\n\nnamespace WindowsFormsApplication2\n{\n    public partial class Form2 : Form\n    {\n        public Form1 Main;\n\n        public Form2(Form1 main)\n        {\n            this.FormBorderStyle = FormBorderStyle.FixedSingle;\n            InitializeComponent();\n            this.Main = main;\n        }\n\n        private void Form2_Load(object sender, EventArgs e)\n        {\n\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            this.Main.sendGameData("Hello world!");\n        }\n    }\n}	0
15500715	15500438	How to check if XmlDocument has changed?	var doc = new XmlDocument();\ndoc.Load(file);\n\nbool changed = false;\n\nXmlNodeChangedEventHandler handler = (sender, e) => changed = true;\ndoc.NodeChanged += handler;\ndoc.NodeInserted += handler;\ndoc.NodeRemoved += handler;\n\n// do some work\n\nif (changed)\n    doc.Save(file);	0
3463390	3463116	Wpf Bring to Front	private static int Zindex = 0;\n\nprivate void MyControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n{\n    if(((FrameworkElement)sender).TemplatedParent==null) return;\n    ContentPresenter presenter = (ContentPresenter)((FrameworkElement) sender).TemplatedParent;\n\n    int currentValue = Panel.GetZIndex(presenter);\n    Console.WriteLine(currentValue);\n    Panel.SetZIndex(presenter, Int32.MaxValue);\n}\n\nprivate void MyControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)\n{\n    if(((FrameworkElement)sender).TemplatedParent==null) return;\n    ContentPresenter presenter = (ContentPresenter)((FrameworkElement) sender).TemplatedParent;\n\n    int currentValue = Panel.GetZIndex(presenter);\n    Console.WriteLine(currentValue);\n    Panel.SetZIndex(presenter, Zindex++);\n}	0
4012634	4012143	make a folder on remote machine as writable	// Create a new DirectoryInfo object corresponding to the remote folder.\n        DirectoryInfo dirInfo = new DirectoryInfo("remoteDirectoryPath");\n\n        // Get a DirectorySecurity object that represents the current security settings.\n        DirectorySecurity dirSecurity = dirInfo.GetAccessControl();\n\n        string user = "domain\\userForWhichTheRightsAreChanged";\n\n        // add the write rule for the remote directory\n        dirSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Write, AccessControlType.Allow));\n\n        // Set the new access settings.\n        dirInfo.SetAccessControl(dirSecurity);	0
17852544	17834334	Entity Framework 5 - Loads all rows on count	ct.Country.Select(v => new { Country = v, TotalStreets = v.Streets.Count() });	0
10720451	10720346	How to ensure all class fields have been initialized before first use	public class CalculatorConfig \n{ \n  public double param1; \n  public double param2; \n  ... \n  internal void Check()\n  {\n       if(param1 == 0.0)\n           throw new ArgumentException("Configuration error: param1 is not valid!");\n       if(param2 == 0.0)\n           throw new ArgumentException("Configuration error: param2 is not valid!");\n       .... // other internal checks\n  }\n} \n\n\npublic class Calculator \n{ \n    private CalculatorConfig _config; \n    public Calculator(CalculatorConfig config) \n    { \n        _config = config; \n    } \n\n    public Result Calculate(object obj)\n    {\n        // Throw ArgumentException if the configuration is not valid\n        // Will be responsability of our caller to catch the exception\n        _config.Check();\n\n        // Do your calcs\n        .....\n    } \n}	0
16992647	16992596	Adding Controls to View Without IG	this.View.AddSubview(btnSubmit);	0
6603025	6602990	Dotnet webclient timesout but browser works file for json webservice	class Program\n{\n    static void Main()\n    {\n        using (var client = new WebClient())\n        {\n            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";\n            var result = client.DownloadString("https://mtgox.com/code/data/getDepth.php");\n            Console.WriteLine(result);\n        }\n    }\n}	0
5900516	5900428	LINQ OrderByDescending passing a string value	results.OrderByDescending("Surname");	0
8746388	8746177	Modifying a substring using C#	String text = "SMITH 9-2 #3-10H13";\n\n        String[] values = text.Split(' ');\n\n        String v = values[1];\n\n        String[] numbers = v.Split('-');\n\n        String newValue = numbers[0].PadLeft(2, '0') + '-' + numbers[1].PadLeft(2, '0');\n\n        String newText = text.Replace(" " + values[1] + " ", " " + newValue + " ");	0
4127851	4127754	Shortest path in Directed Acyclic Graph	class AdjacencyMatrix\n{\n    // representation of the adjacency matrix (AM)\n    private readonly int[,] m_Matrix;\n    // mapping of character codes to indices in the AM\n    private readonly Dictionary<char,int> m_Mapping;\n\n    public AdjacencyMatrix( string edgeVector )\n    {\n        // using LINQ we can identify and order the distinct characters\n        char[] distinctChars = edgeVector.Distinct().OrderBy(x => x);\n\n        m_Mapping = distinctChars.Select((c,i)=>new { Vertex = c, Index = i })\n                                 .ToDictionary(x=>x.Vertex, x=>x.Index);\n\n        // build the adjacency cost matrix here...\n        // TODO: I leave this up to the reader to complete ... :-D\n    }\n\n    // retrieves an entry from within the adjacency matrix given two characters\n    public int this[char v1, char v2]\n    {\n        get { return m_Matrix[m_Mapping[v1], m_Mapping[v2]];\n        private set { m_Matrix[m_Mapping[v1], m_Mapping[v2]] = value; }\n    }\n}	0
20355804	20350510	Is it possible to insert VBA macros into word 2010 with C# (with an exe)?	//creating a new VBA module (must be a reference to Microsoft.Vbe.Interop)\nMicrosoft.Vbe.Interop.VBComponent vbaModule = \n     docComp.VBProject.VBComponents.Add(\n     Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule); \n\n//insert VBA macro code\nvbaModule.CodeModule.AddFromString(string_with_your_vba_code);\n\n//run the macro\nMicrosoft.Office.Interop.Word.Application.GetType().InvokeMember("Run", \n     BindingFlags.Default | BindingFlags.InvokeMethod,\n     null,\n     Microsoft.Office.Interop.Word.Application,\n     new Object[] { "name_of_your_main_sub" });	0
11882515	11882387	Group Properties of a class	System.ComponentModel.CategoryAttribute	0
28458265	28457953	Adding rows to top of TableLayoutPanel	panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 16F));\npanel.RowCount++;\nforeach (Control c in panel.Controls) {\n  panel.SetRow(c, panel.GetRow(c) + 1);\n}\npanel.Controls.Add(new Label() { Text = text }, 0, 0);	0
16214958	16214661	Mediaelement Playlist repeat how to?	private void ShowNextImage()\n{\n    if (currentSongIndex == -1)\n    {\n        currentSongIndex = Listbox1.SelectedIndex;\n    }\n    if (currentSongIndex == ListBox1.Items.Count)\n    {\n        currentSongIndex = 0;\n    }\n    currentSongIndex++;\n    ....\n}	0
27630075	27630028	NetworkStream truncates my data?	int remaining = d.Length;\nint pos = 0;\nwhile (remaining != 0) {\n    int add = networkStream.Read(d, pos, remaining);\n    pos += add;\n    remaining -= add;\n}	0
6141004	6140956	connection string issue with SQL EXPRESS 2008	SqlConnection cn = new \n    SqlConnection(@"Server=.\SQLExpress;Database=test;"\n    +"Connection Timeout=300;User ID=test;Password=test;Pooling=false")	0
2720909	2720889	How to link a property setter to a delegate?	ChangeCountDelegate dlg = (int x) => a.Count = x;\n\n// or\nChangeCountDelegate dlg = x => a.Count = x;\n\n// or \nChangeCountDelegate dlg = new ChangeCountDelegate(delegate(int x) { a.Count = x; } );\n\n// or \nChangeCountDelegate dlg = new ChangeCountDelegate(int x => a.Count = x);	0
18382198	18382080	TCP Connection in a Winform	var address = Dns.GetHostAddresses("server.myaddress.com")[0];\nIPAddress address = IPAddress.Parse(address);	0
24860353	24860339	Access digits from integer value	int[] array1 =  95478.ToString()\n                .Select(x => int.Parse(x.ToString()))\n                .ToArray();	0
25174240	25174221	How to get inherited attributes from base class	GetCustomAttributes(typeof(MyAttribute), true)	0
768163	757232	jQuery UI Dialog with ASP.NET button postback	jQuery(function() {\n    var dlg = jQuery("#dialog").dialog({\n                         draggable: true,\n                         resizable: true,\n                         show: 'Transfer',\n                         hide: 'Transfer',\n                         width: 320,\n                         autoOpen: false,\n                         minHeight: 10,\n                         minwidth: 10\n                     });\n    dlg.parent().appendTo(jQuery("form:first"));\n});	0
158005	157933	What's the best way of implementing a thread-safe Dictionary?	public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue>\n{\n    private readonly object syncRoot = new object();\n    private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValue>();\n\n    public void Add(TKey key, TValue value)\n    {\n        lock (syncRoot)\n        {\n            d.Add(key, value);\n        }\n        OnItemAdded(EventArgs.Empty);\n    }\n\n    public event EventHandler ItemAdded;\n\n    protected virtual void OnItemAdded(EventArgs e)\n    {\n        EventHandler handler = ItemAdded;\n        if (handler != null)\n            handler(this, e);\n    }\n\n    // more IDictionary members...\n}	0
18634358	18634273	How do I refresh combobox item after selecting one item?	private void frmTableAllotment_Load(object sender, EventArgs e)\n{\n   dtTmPkr.Value = System.DateTime.Now;\n   LoadComboBox();\n}\n\nprivate void btnAllocate_Click(object sender, EventArgs e)\n{\n    cmd = new SqlCommand("update  waiterentry2 set status='true'  where name=@name", con);\n    cmd.Parameters.AddWithValue("name", dgvDetails.Rows[i].Cells[0].Value);\n    cmd.ExecuteNonQuery();\n    con.Close();\n    LoadComboBox();\n}\n\nprivate void LoadComboBox()\n{\n    while(cmbWaiter.Items.Count >0)\n         cmbWaiter.Items.RemoveAt(0);\n\n    cmd = new SqlCommand("Select name from waiterentry2 where status='false'", con);\n    con.Open();\n    dr = cmd.ExecuteReader();\n    while (dr.Read())\n    {\n        cmbWaiter.Items.Add(dr["name"]);\n    }\n\n    dr.Close();\n    cmd = null;\n    con.Close();\n}	0
3159599	3158677	How to find out the ProductName property of another assembly?	private void button1_Click(object sender, EventArgs e) {\n        var info = System.Diagnostics.FileVersionInfo.GetVersionInfo(@"c:\windows\notepad.exe");\n        MessageBox.Show(info.ProductName);\n    }	0
16483738	16481795	Styling controls in a single table cell from the code behind	tabCell.Wrap = false	0
8945663	8945635	How do I generate a return URL in an action?	public ActionResult Action(LogggedInCustomer logIn, string id)\n{\n    if (logIn == null)\n    {\n        var returnUrl = Url.Action("Print", "Invoice", new { area = "AR", id = id });\n        return RedirectToAction("Index", "Home", new { returnUrl = returnUrl });\n    }\n\n    ...\n}	0
6317318	5687736	How to change drop down button in combobox control?	private void button1_Click(object sender, EventArgs e)\n    {\n        this.comboBox1.DroppedDown = true;\n    }	0
30925691	30925009	How do I remove elements from a table?	DateTime currentDateTime = DateTime.Now;\nTimeSpan thisTimeSpan = new TimeSpan(Convert.ToInt16(numDaysOld), 0, 0, 0);\nvar delete_list = PD.dates.Where(x => (currentDateTime - x.dtime) > thisTimeSpan)\nPD.dates.RemoveRange(delete_list);	0
2221733	2219760	AutoMapper - Adding Custom Formatters	Mapper.ForSourceType<DateTime>().AddFormatter<DateStringFormatter>();	0
19107675	19087186	How to acquire DTE object instance in a VS package project?	EnvDTE80.DTE2 dte = this.GetService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE)) as EnvDTE80.DTE2;	0
31044926	31044801	Entity framework 6 transaction	foreach (var item in itemList)\n{\n    context.MyFirstEntity.Add(item);\n    mySecondEntity.MyFirstEntity = item;\n    context.MySecondEntity.Add(mySecondEntity);\n}\ncontext.SaveChanges();	0
27204343	26323475	Lucene.Net sorting results on distance from a point	string name = "__Location";\nvar strategy = new PointVectorStrategy(ctx, name);\n\nvar indexSearcher = new IndexSearcher(_dir, true);\n\ndouble radious = Double.Parse(rad);\n\ndouble lat = 33.8886290;\ndouble lng = 35.4954790;\n\nvar distance = DistanceUtils.Dist2Degrees(radious, DistanceUtils.EARTH_MEAN_RADIUS_MI);\n\nvar spatialArgs = new SpatialArgs(SpatialOperation.Intersects, ctx.MakeCircle(lng, lat, distance));\nvar spatialQuery = strategy.MakeQuery(spatialArgs);\nPoint pt = ctx.MakePoint(lng, lat);\nDistanceReverseValueSource valueSource = new DistanceReverseValueSource(strategy, pt, distance);\n\n\nValueSourceFilter vsf = new ValueSourceFilter(new QueryWrapperFilter(spatialQuery ), valueSource, 0, distance);\nvar filteredSpatial = new FilteredQuery(new MatchAllDocsQuery(), vsf);\nvar spatialRankingQuery = new FunctionQuery(valueSource);\nBooleanQuery bq = new BooleanQuery();\nbq.Add(filteredSpatial,Occur.MUST);\nbq.Add(spatialRankingQuery,Occur.MUST);\n\nTopDocs hits = indexSearcher.Search(bq, 10);	0
20967032	20966971	create nested xml document in c#	var doc = \n    new XElement("FIXML",        // you can optionally add an XDocument as outer element\n      new XElement ("Header", \n          .... // more child elements, values and/or attributes\n          new XElement("RequestUUID", 938692349)\n      ));\n\n\ndoc.Save(fileName);	0
5114653	5114554	Parallelizing some LINQ to XML	var crops =\n    ParallelEnumerable.Range(1, 9)\n        .SelectMany(i =>\n            XDocument.Load(string.Format(url, i))\n                     .Descendants("CropType")\n                     .Select(c => new Crop\n                      {\n                          // The data here\n                      })\n         )\n        .ToList();	0
1393427	1393423	How do I bind a List<string> to an ItemsControl?	{Binding}	0
13270143	13269985	Twitter API get user feed	{"errors":[{"message":"Bad Authentication data","code":215}]}	0
22871704	22871675	How to use float.Parse to get decimal from string like "5/2"	string[] tokens = input.Split('/');\nfloat result = float.Parse(tokens[0])/float.Parse(tokens[1]);	0
1141889	1141820	how to swap the visibility of applications using c#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n    InitializeComponent();\n\n    tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);\n    }\n\n    void tabControl1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n    ProcessStartInfo psi = null;\n\n    if (tabControl1.SelectedTab == tabPage1)\n    {\n    psi = new ProcessStartInfo("notepad.exe");\n    }\n    else if (tabControl1.SelectedTab == tabPage2)\n    {\n    psi = new ProcessStartInfo("calc.exe");\n    }\n\n    if (psi != null)\n    {\n    psi.ErrorDialog = true;\n    psi.ErrorDialogParentHandle = Handle;\n    Process.Start(psi);\n    }\n    }\n}	0
30875856	30875775	How improve add items under the List, when i have more than 2 elements	.Select(s => new ProposalItems { \n    Row = (int)s.ES_SC_CatalogoConceptos.renglon,, \n    Price = (double)s.ES_SC_PropuestasPrecios.preciounitario, \n    Quantity = (double)s.ES_SC_CatalogoConceptos.cantidad, \n    Total = (double)s.ES_SC_PropuestasPrecios.importe \n}).ToList();	0
17251492	17251177	about having rows with different datatype to be shown in datagridview in application form	dataGridView1.ColumnCount = 2; // Create 2 text box columns\n                    dataGridView1.Columns[0].HeaderText = "Name";\n                    dataGridView1.Columns[0].Width = 350;\n                    dataGridView1.Columns[1].HeaderText = "Value";\n                    dataGridView1.Columns[1].Width = 150;\n\n                    DataGridViewRow heterow0 = new DataGridViewRow();\n                    DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();\n                    textBoxCell.Value = "Turn Over Based On";\n                    DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell();\n                    comboCell.Items.Add("Chip Transaction");\n                    comboCell.Items.Add("Win/Loss");\n\n                    heterow0.Cells.Add(textBoxCell);\n                    heterow0.Cells.Add(comboCell);\n                    dataGridView1.Rows.Add(heterow0); // this row has a combo in first cell	0
32889550	32889182	Have x number of classes only accessible to each other?	public class O\n{\n    private class A { private void Test() {B b = new B(); C c = new C(); }}\n    private class B { private void Test() {A a = new A(); C c = new C(); }}\n    private class C { private void Test() {B b = new B(); A a = new A(); }}\n}\n\npublic class Hacker\n{\n    O.A a = new O.A();  // fail\n}	0
5836643	5836227	Whats wrong with this group join	var groupJoin = profiles.GroupJoin(fathers,\n                                    p => p.FatherID, \n                                    f => f.ID, \n                                    (p, fathers) => new Result() {Profile = p, Fathers = father.DefaultIfEmpty()}).ToList();	0
12525810	12471136	How to Create PDF file with Tamil Font by using itextsharp in C#?	string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\ARIALUNI.TTF"; \nBaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);\nFont font = new iTextSharp.text.Font(basefont, 24, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLUE);\nParagraph pr1 = new Paragraph("??? ????? ????", AVVAIYARFont);	0
16542510	16542317	How to load XML items to List of items	var items = XDocument.Load(filename)\n            .Descendants("Item")\n            .Select(i => new Item\n            {\n                Id = (int)i.Element("Id"),\n                Title = (string)i.Element("Title"),\n                ImageUrl = (string)i.Element("ImageUrl"),\n            })\n            .ToList();	0
17505791	17472504	Routing, matching a specific url if it contains a word	var subCategories = new[] { "Soccer", "BasketBall", "Golf" };\nforeach (var subcat in subCategories)\n{\n    routes.MapRoute(subcat, "{subcat}/{title}",\n                        new {controller = "Routing", action = "Redirect", category = subcat},\n                        new { subcat = @".*\b" + subcat + @"\b.*" });\n}	0
19051095	19050943	Invoke failed in a task	await task;	0
7781899	7781893	EF Code First: How to get random rows	something.OrderBy(r => Guid.NewGuid()).Take(5)	0
2674278	2674218	Document key usage in Dictionary	public class SpecialNameDictionary : Dictionary<string, string>\n{\n    /// <param name="specialName">That Special Name</param>\n    public new string this[string specialName]\n    {\n        get\n        {\n            return base[specialName];\n        }\n    }\n}	0
31981740	31981255	Converting SQL group by and order by to Linq using case	orderby bd.bandcharge_desc.Contains("above")?1:0 descending ,\n               bd.bandcharge_desc,bd.rate	0
2533731	2533718	How do I get the path of a random folder?	System.IO.DirectoryInfo[] subDirs;\nSystem.IO.DirectoryInfo root;\n// assign the value of your root here\nsubDirs = root.GetDirectories();\nRandom random = new Random();\nint directory = random.Next(subDirs.Length);\nSystem.IO.DirectoryInfo randomDirectory = subDirs[directory];	0
5234472	5234441	How to display the first 100 characters in a gridview?	protected void gvNotes_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowIndex < 0)\n        return;\n\n    int _myColumnIndex = 0;   // Substitute your value here\n\n    string text = e.Row.Cells[_myColumnIndex].Text;\n\n    if (text.Length > 100)\n    {\n        e.Row.Cells[_myColumnIndex].Text = text.Substring(0, 100);\n    }\n}	0
31786227	31786190	byte[] array from unmanaged memory	[DllImport("libPylonInterface.so")]\nprivate static extern void GetImage([Out] byte[] arr);\n\n....\n\narr = new byte[_width * _height];\nGetImage(arr);	0
10539136	10538714	Delete Cookies from a Different Domain	[DllImport (@"wininet", SetLastError = true, CharSet = CharSet.Auto)]\nprivate static extern IntPtr FindFirstUrlCacheEntry ([MarshalAs (UnmanagedType.LPTStr)] string searchPattern, IntPtr ptrCacheEntryInfo, ref int cacheEntryInfoSize);\n\n[DllImport (@"wininet", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]\nprivate static extern bool FindNextUrlCacheEntry (IntPtr ptrCacheHandler, IntPtr ptrCacheEntryInfo, ref int cacheEntryInfoSize);\n\n[DllImport (@"wininet", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\nprivate static extern bool FindCloseUrlCache (IntPtr ptrCacheEntryInfo);\n\n[DllImport ("wininet.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]\nprivate static extern bool DeleteUrlCacheEntry (IntPtr lpszUrlName);	0
29909388	29909237	Invoking a method from the parent page after user control has been loaded?	protected override void OnLoadComplete(EventArgs e) {\n   x = getValueFromUserControl();\n}	0
5817028	5811073	LINQ & Many to Many Relationships	var query = \n    from car in ctx.Cars \n    where options.Colors.Count <= 0 || car.CarsXColors.Any(y => options.Colors.Contains(y.Id))\n    select car;	0
618226	618216	Rules for finding / avoiding shared data in a multithreaded application	String.Replace	0
25866101	25865695	How to parse web service data to windows phone 8.0 pivot app MainViewModel?	public async void LoadData()\n{\n    var response = await GetWebserviceData();\n    foreach(var item in response)\n    {\n     this.Items.Add(item);\n    }\n}	0
2539901	2536137	How to cast a Linq Dynamic Query result as a custom class?	var a = Products\n        .Where("ProductType == @0", "Tee Shirt")\n        .GroupBy("ProductColor", "it")\n        .Select(c => new Category { \n            PropertyType = g.Key, Count = g.Count() \n        });	0
26410244	26408726	Edge + Express + SQL Server unexplainable StackOverflow	app.get('/tickets', function (request, response) {\n    ticketRepository.getTickets({}, function (error, result){\n        response.json(result);\n    });\n});	0
20274892	20262333	Redis MSET equivalent for a SET or LIST?	Dictionary<string, List<string>>	0
7286137	7286045	How to determine reference equality of two variables in different scope?	Make Object ID	0
4312764	4312714	Writing into a text file line by line	dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine));	0
15061633	15052684	Image upload require to include image into solution each time	string filename = "";\n            string FilePath = "";\n            filename = Path.GetFileName(FileUpload1.FileName);\n            FilePath = Server.MapPath("./JQueryImages");\n            string destPath = Path.Combine(FilePath, filename);\n            FileUpload1.PostedFile.SaveAs(destPath);\n            ViewState["ImagePath"] = destPath.ToString();\n            Image1.ImageUrl = "~/JQueryImages/" + filename;\n            Label1.Text = "Image uploaded successfully";\n            Label1.ForeColor = Color.Green;	0
436967	436956	How do I hide a console application user interface when using Process.Start?	Process p = new Process();\n        StreamReader sr;\n        StreamReader se;\n        StreamWriter sw;\n\n        ProcessStartInfo psi = new ProcessStartInfo(@"bar.exe");\n        psi.UseShellExecute = false;\n        psi.RedirectStandardOutput = true;\n        psi.RedirectStandardError = true;\n        psi.RedirectStandardInput = true;\n        psi.CreateNoWindow = true;\n        p.StartInfo = psi;\n        p.Start();	0
4412610	4412596	C# arrays minimal value in specific range	array.Skip(2).Take(5).Min();	0
13030897	13030814	Reading value from registry	using Microsoft.Win32;\n    public static string GetRegistry()\n    {\n        string registryValue = string.Empty;\n        RegistryKey localKey = null;\n        if (Environment.Is64BitOperatingSystem)\n        {\n            localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);\n        }\n        else\n        {\n            localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32);\n        }\n\n        try\n        {\n            localKey = localKey.OpenSubKey(@"Software\\MyKey");\n            registryValue = localKey.GetValue("TestKey").ToString();\n        }\n        catch (NullReferenceException nre)\n        {\n\n        }\n        return registryValue;\n    }	0
26716017	26715978	Use Linq to get items in a list using a second list	var items = products.Where(p => idList.Contains(p.ID));	0
7246669	7246568	Retrieve data from dynamically created controls	runat="server"	0
27166750	27166646	Getting digits of number in c#	static int GetDigit(int number, int k)\n    {\n        // k is the positiong of the digit I want to get from the number\n        // I want to divide integer number to 10....0 (number of 0s is k) and then % 10\n        // to get the last digit of the new number\n        return (int)(number / Math.Pow(10, k)) % 10;\n    }\n}	0
12672339	12672035	How to get intersection of objects as lists in lists contain these objects of class?	List<ArtistAndTags> List1 = new List<ArtistAndTags>(); \n        List<ArtistAndTags> List2 = new List<ArtistAndTags>();\n\n        var intersectedList = new List<ArtistAndTags>();\n\n        foreach (var item1 in List1)\n        {\n            foreach (var item2 in List2)\n            {\n                if (item2.Tags.Intersect(item1.Tags).Any()))\n                {\n                    intersectedList.Add(item1);\n                    intersectedList.Add(item2);\n                }\n            }\n        }\n\n        var result = intersectedList.Select(x => x.ArtistName).ToList();	0
34503977	34503084	Best way to randomize two identical arrays without overlap?	var source = new [] { "A", "B", "C", "D", "E", "F" };\n\nvar output1 = (string[])null;\nvar output2 = (string[])null;\n\nvar rnd = new Random();\nAction shuffle = () =>\n{\n    output1 = source.OrderBy(x => rnd.Next()).ToArray();\n    output2 = source.OrderBy(x => rnd.Next()).ToArray();\n};\n\nshuffle();\nwhile (output1.Zip(output2, (o1, o2) => new { o1, o2 })\n    .Where(x => x.o1 == x.o2)\n    .Any())\n{\n    shuffle();\n}	0
11634040	11633919	open Windows Form with opcv From wpf windows	private void Window_Loaded(object sender, RoutedEventArgs e) \n{\n// Create the interop host control.\nSystem.Windows.Forms.Integration.WindowsFormsHost host =\n    new System.Windows.Forms.Integration.WindowsFormsHost();\n\n// Create the MaskedTextBox control.\nMaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");\n\n// Assign the MaskedTextBox control as the host control's child.\nhost.Child = mtbDate;\n\n// Add the interop host control to the Grid\n// control's collection of child controls.\nthis.grid1.Children.Add(host);\n}	0
11540146	11539284	Create a Combobox User Control and pass the items from the mainwindow	public MyCombobox() \n{ \n    InitializeComponent(); \n\n    MyItems = new List<ComboBoxItem>(); \n    this.DataContext = this;\n}	0
728382	697720	WCF client in ASP.net Page	void Page_Load(object sender, EventArgs e)\n{\n  if(!IsPostBack)\n  {\n      RemoteCall();\n  }\n}\n\nvoid RemoteCall()\n{\n var client = new SearchClient();\n try\n {\n     var results = client.Search(params);\n     clients.Close();\n }\n catch(CommunicationException cex)\n {\n   //handle\n }\n catch(Exception ex)\n {\n   //handle\n }\n finally\n {\n     ((IDisposable)client).Dispose();\n }\n\n}	0
21516358	21467531	How to change the "Repeat Group Header On Each Page" option of the Crystal Report group via C# code?	var formulaField = mainSubreport.DataDefinition.FormulaFields["RepeatHeader"];\nformulaField.Text = "if inrepeatedgroupheader then TRUE ELSE FALSE";	0
3649182	3649174	"new" keyword in property declaration in c#	BaseClass.navUrl	0
21563598	21563476	datarow not showing all data	Console.WriteLine(DataRow_[0]["username"]);	0
10236160	10236028	How to add an empty option to a dropdown list	return new[] { new SelectListItem { Text = "", Value = "" } }.Concat(\n       visitTypes\n.Where(a=>a.IsActive ?? false)\n.ToSelectList("VisitTypeId", "Description", viewModel.VisitTypeId.ToString()));	0
5921070	5908206	InvalidOperationException when DataGrid loses focus to a HyperLink	public string BodyXamlWithOutHyperLink\n        {\n            get\n            {\n                const string RegExPattern1 = @"<Hyperlink \S*"">";\n                const string RegExPattern2 = @"</Hyperlink>";\n\n                string body = this.BodyXaml;\n\n                if (string.IsNullOrEmpty(body))\n                {\n                    return string.Empty;\n                }\n\n                Regex bodyRegEx = new Regex(RegExPattern1);\n                body = bodyRegEx.Replace(body, "<Bold>");\n                bodylRegEx = new Regex(RegExPattern2);\n                body= bodyRegEx.Replace(mail, "</Bold>");\n\n                return body;\n            }\n\n            set\n            {\n               // can be ignored, we are read-only anyway\n            }\n        }	0
9113215	9113137	Making ItemsSource treat a collection as a single item, rather than iterating over it?	public class ByteArrayValueConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        if (value != null && value is IEnumerable<byte>)\n            return string.Join(", ", (IEnumerable<byte>)value);\n        return value;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new NotSupportedException();\n    }\n}	0
11375351	11375139	Regex Counting Characters in a text field	string input = "LA-FG4-DETF-DJJJTHD-S@T-JHF-F1-F2";\n        int atIndex = input.IndexOf('@');\n        int count1 = Regex.Matches(input.Substring(0, atIndex), "[0-9A-Z#-]").Count;\n        int count2 = Regex.Matches(input.Substring(atIndex, input.Length - atIndex), "[0-9A-Z#@-]").Count;	0
1043997	1043661	How can I force a DropDownList style ComboBox to only open when the user clicks the drop-down button?	public class MyComboBox : ComboBox\n{\n    public MyComboBox()\n    {\n        FlatStyle = FlatStyle.Popup;\n        DropDownStyle = ComboBoxStyle.DropDownList;\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n        if (m.Msg == 0x0201 /* WM_LBUTTONDOWN */ || m.Msg == 0x0203 /* WM_LBUTTONDBLCLK */)\n        {\n            int x = m.LParam.ToInt32() & 0xFFFF;\n            if (x >= Width - SystemInformation.VerticalScrollBarWidth)\n                base.WndProc(ref m);\n            else\n            {\n                Focus();\n                Invalidate();\n            }\n        }\n        else\n            base.WndProc(ref m);\n    }\n}	0
11194409	11178744	MSChart Callout horizontal alignment to datapoint WinForms	Chart1.Series["Series1"].SmartLabels.MovingDirection =  \nLabelAlignment.Bottom | LabelAlignment.Top;	0
16452663	16412478	ServiceStack Authentication validation with Captcha	public ExtDeskResponse Post(MyAuth req) {\n        //Captcha Validation\n        var valid = req.Captcha == base.Session.Get<Captcha>("Captcha").result;\n        //SS Authentication\n        var authService = AppHostBase.Instance.TryResolve<AuthService>();\n        authService.RequestContext = new HttpRequestContext(\n            System.Web.HttpContext.Current.Request.ToRequest(),\n            System.Web.HttpContext.Current.Response.ToResponse(),\n            null);\n        var auth = string.IsNullOrWhiteSpace(\n            authService.Authenticate(new Auth {\n                UserName = req.UserName,\n                Password = req.Password,\n                RememberMe = req.RememberMe,   \n            }).UserName);\n        if (valid && auth) { \n            //...logic\n        }\n        return new MyAuthResponse() {\n            //...data\n        }; \n    }	0
6020422	6019976	Entity framework: check if there are changes to be saved from a specific Entity	var objectStateEntries = Database.LabelTAB\n                                 .Context\n                                 .ObjectStateManager\n                                 .GetObjectStateEntries(ModifiedID)\n                                 .Where(e => e.Entity is LabelTAB);\n\nreturn objectStateEntries.Any();	0
10725103	10724913	Refresh button for web browser control	private void Refresh_Click(object sender, EventArgs e){\n    browsers.Navigate(browsers.Source.AbsoluteUri);\n}	0
13475003	13474969	Better way of finding longest string length in multiple lists	int ma = new[] {svar1, svar2, svar3, svar4, svar5}\n             .Max(lst => lst.Max(str => str.Length));	0
8396185	8396145	Is there a way to generate getters and setters in C# for a sql database?	public void InsertAccountData(string Usrname, string passwd)\n{\n\n    string qry = string.format("INSERT INTO Account(Username, password) VALUES('{0}','{1}')", Usrname, password);\n   using (SqlConnection connection = new SqlConnection(connectionString))\n   {\n    SqlCommand command = new SqlCommand(qry, connection);\n        connection.Open();\n        SqlDataReader reader = command.ExecuteReader();\n        while (reader.Read())\n        {\n            Console.WriteLine(String.Format("{0}, {1}",\n                reader[0], reader[1]));\n        }\n    }\n}	0
8661274	8630147	Windows 8 - Animation in c#?	d.Duration = DurationHelper.FromTimeSpan(TimeSpan.FromSeconds(1));	0
6321730	6321724	ComboBox SelectedItem is not showing its value	MessageBox.Show((cb2.SelectedItem as ComboBoxItem).Content.ToString());	0
26071900	26056775	Visual Studio Command for going to a specific item in source control explorer	public void SelectFolder(string path)\n    {\n        dte.ExecuteCommand("View.TfsSourceControlExplorer");\n\n        Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt explorer =\n            GetSourceControlExplorer();\n        if (explorer != null)\n            explorer.Navigate(path);\n    }\n\n    private Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt GetSourceControlExplorer()\n    {\n        Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt versionControl =\n            dte.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt") as\n                Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt;\n        if (versionControl == null)\n            return null;\n\n        return versionControl.Explorer;\n    }	0
14881649	14881052	Summing similar values with a list using Linq	decimal runningTotal = 0;\nvar result = from item in items\n             orderby item.Date\n             group items by item.Date into grp\n             let sum = items.Where(x => x.Date == grp.Key).Sum(x => x.Amount)\n             select new\n             {\n                 Date = grp.Key,\n                 Sum = runningTotal += sum,\n             };	0
11226955	11225806	Sending formatted error message to client from catch block	catch (Exception)\n{\n    var response = context.Request.CreateResponse(HttpStatusCode.NotFound, \n                        new Error { Message = "User with api key is not valid"});\n    context.Response = response; \n}	0
18759309	18658045	Accessing random SQL server	this.Factory = DbProviderFactories.GetFactory(connexionStringBuilder.InvariantName);\n this.Connection = Factory.CreateConnection();\n Connection.ConnectionString = connexionStringBuilder.ConnexionString;	0
24255090	24251336	Import a Public key from somewhere else to CngKey?	CngKey.Import(key,CngKeyBlobFormat.EccPrivateBlob);	0
6989092	6988431	How can I do a good design for this model?	interface Problem {\n    void OutputProblem(OutputStream stream);\n    void AcceptAnswer(InputStream stream);\n    bool IsAnswerCorrect();\n}	0
1079490	1079418	Calling a method for a user control in a repeater?	UserControl uc = repit.FindControl("ucontrol") as MyUserControl;\nif (uc != null)\n{\n    uc.MyMethod("var1", "var2", "var3", "var4");\n}	0
13933389	13933352	C# WebForm - Set focus of textbox with Javascript	function SelectValue(source, eventArgs) {\n    document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();\n    setTimeout( function(){\n            document.getElementById('<%= txtQuantity.ClientID %>').focus();\n        }, 0);\n}	0
8702359	8698811	generate 6 digit number which will expire after 5 second	public static int GetTimestamp()\n{\n    // 10m ticks in a second, so 50m in 5 seconds\n    const int ticksIn5Seconds = 50000000;\n    return (int)((DateTime.Now.Ticks / ticksIn5Seconds) % 1000000);\n}	0
15201521	15197753	connection string for c#.net to mysql database connectivity	string myConnectionString = "SERVER=50.62.82.38;" +\n                            "DATABASE=admin_urja;" +\n                            "UID=welcome" +\n                            "PASSWORD=hello;";\nMySqlConnection connection = new MySqlConnection(myConnectionString);	0
16345187	16345115	Return multiple values from a method in C#	public static List<string> GetData(string ORDNUM_10)\n{\n    //snip...\n\n    return new List<string> { PMDES1_01, PRTNUM_10, DESCRPTN_104, ORDREF_10, TNXDTE_01 };\n}	0
30467091	30464584	Add "Please Select" to Drop-down list that retrieves values from Data base	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!Page.IsPostBack)\n        { \n           NameDropDownList.Items.Insert(0, new ListItem("Please Select a Product", "Please Select a Product"));\n        }\n\n   }	0
9618029	9615803	Converting Visual Studio 6 Libraries To Visual Studio 10	unmanaged C++	0
11849875	11849386	Windows phone7: Restrict inserting certain keys for textbox	private void bla_TextChanged(object sender, TextChangedEventArgs e)\n{\n    bla.Text = Regex.Replace(bla.Text, @"[^\w\s]", string.Empty);\n}	0
13506548	13506495	Using of backgroundworker issues need help to fix this	private void btnConnect_Click(object sender, EventArgs e)\n    {\n        progressBar.Visible = true;\n        backgroundWorker.WorkerReportsProgress = true;\n        backgroundWorker.WorkerSupportsCancellation = true;\n        backgroundWorker.ProgressChanged -= backgroundWorker_ProgressChanged;\n        backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;\n\n        backgroundWorker.DoWork -= backgroundWorker_DoWork;\n        backgroundWorker.DoWork += backgroundWorker_DoWork;\n\n        backgroundWorker.RunWorkerAsync();\n    }	0
9900883	9900106	ComboBox.ObjectCollection property for a user control?	[Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",\n    typeof(UITypeEditor))]\npublic ComboBox.ObjectCollection Items\n{\n    get{ return this.comboBox1.Items; }\n}	0
1518838	1518824	Comparing two arraylist in c# windows application	List<string> myprocs; // populated with process names\nProcess[] Procs = Process.GetProcesses();\nforeach(Process proc in Procs)\n{\n  if(myprocs.Contains(proc.ProcessName))\n  {\n     myprocs.Remove(proc.ProcessName);\n  }\n}\n// whatever that is left over in myprocs at this point is your remainder process names.	0
19158460	19158295	Writing to a text file C#	string a=string.Empty;\n    StreamWriter yourStream = null;\n    protected void Page_Load(object sender, EventArgs e)\n    {\n            yourStream = File.CreateText("D:\\test1.txt"); // creating file\n            a = String.Format("|{0,1}|{1,2}|{2,7}|......", "A", "B", "",......); //formatting text based on poeition\n            yourStream.Write(a+"\r\n");                        \n            yourStream.Close();\n        }	0
16018261	16018231	C#: Sort a list of an array	list.OrderBy(input=>input[columnIndex])	0
7700640	7700601	Editing specific lines in a text file using c#	string[] lines = File.ReadAllLines(fileName);\n\n// modify the lines\n\nFile.WriteAllLines(fileName, lines);	0
11511176	11510923	Find address using pointer and offset C#	"client.dll"+0065F38	0
14038816	14038707	How to replace the row command event for a gridview with clickable manner?	protected void gv_Details1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            e.Row.Attributes.Add("style", "cursor:pointer;");\n            string abc = ((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString();\n            e.Row.Attributes["onClick"] = "location.href='pagename.aspx?Rumid=" + abc + "'";\n        }\n    }	0
25847311	25847160	How can I make timer2 and timer3 to work at the same time but asynchrony?	private System.Timers.Timer timer2 = new System.Timers.Timer(1000),\n                            timer3 = new System.Timers.Timer(10);\npublic void Init()\n{\n    timer3.Elapsed += (sender, args) =>\n    {\n        // update your UI from the timer's thread\n        pictureBox1.Invoke(\n            new Action( \n                () =>\n                {\n                    pictureBox1.Invalidate();\n                }\n            )\n        );\n    };\n\n    timer2.Elapsed += (sender, args) =>\n    {\n        // Do other stuff with the UI by calling \n        // the appropriate Control invoke methods\n    };\n\n    timer2.Enabled = timer3.Enabled = true;\n}	0
4764619	4764152	IUserType Corresponding to Int64 With ODP.net	INSERT INTO my_entity (id, name) \nVALUES (hibernate_sequence.nextval, :p0) \nreturning id into :nhIdOutParam	0
14524571	14524427	Casting IQueryable to IOrderedQueryable generically	input.OrderBy(p => 0);	0
8380841	8380768	Retrieve the name on a website?	HtmlElementCollection oHtmlElementCollection;\n        public List<string> lstDetailsUrl = new List<string>();\n                            oHtmlElementCollection = webBrowser1.Document.GetElementsByTagName("div");\n                            lstDetailsUrl.Clear();\n                            for (int i = 0; i < oHtmlElementCollection.Count; i++)\n                            {\n                                if (oHtmlElementCollection[i].GetAttribute("id") != null)\n                                {\n                                    if (oHtmlElementCollection[i].GetAttribute("id").Contains("title"))\n                                    {\n                                        lstDetailsUrl.Add(oHtmlElementCollection[i].InnerText);\n                                    }\n                                }\n                            }	0
7857253	7857233	c# How to read the content of a website as text?	using(System.Net.WebClient wc = new System.Net.WebClient()) {\n    MessageBox.Show(wc.DownloadString("http://thewebsite.com/thepage.html")); // Or whatever\n}	0
12939001	12938937	add to array from a loop C#	String[] mylist = list.Select(I => Convert.ToString(I.ip)).ToArray();	0
13193327	13192080	Devexpress ListBoxControl Add Item with multiple Colors	listBoxControl.AllowHtmlDraw = DevExpress.Utils.DefaultBoolean.True;\nlistBoxControl.Items.AddRange(new object[] {\n    "Color <color=Red>Red</color>",\n    "Color <color=Green>Green</color>",\n    "Color <color=Blue>Blue</color>"\n});	0
6710960	6710925	Need help saving map	file.Write(MapTiles[i2].ID + ", ");	0
8320139	8320078	Only get the value if a condition is true	var finalData = from x in loaded.Descendants("Node")\n                select new\n                {\n                   Element1 = (string)x.Descendants("Element1").FirstOrDefault(),\n                   Element2 = (string)x.Descendants("Element2").FirstOrDefault(),\n                   Element3 = (string)x.Descendants("Element3").FirstOrDefault(),\n                };	0
5164634	5153816	Get points enclosed by a 3d polygon	ax+by<d	0
32522641	32497714	Upload excel file from using angular js and WebAPI	File.WriteAllBytes(path, Convert.FromBase64String(document.DocumentContent.Split((",").ToCharArray())[1]));	0
25263717	25263640	Group List<T> by Column and a count on multiple columns	var categories = GetCategories().GroupBy(x => x.Description)\n                                .Select(group => new { \n                                    Categories = group.Key, \n                                    ParentCount = group.Count(x => x.ParentCount!=null),      \n                                    ChildCount = group.Count(x => x.ChildCount!=null) \n                                });	0
2615540	2615527	Is this a valid, lazy, thread-safe Singleton implementation for C#?	public sealed class Singleton\n{\n    Singleton()\n    {\n    }\n\n    public static Singleton Instance\n    {\n        get\n        {\n            return Nested.instance;\n        }\n    }\n\n    class Nested\n    {\n        // Explicit static constructor to tell C# compiler\n        // not to mark type as beforefieldinit\n        static Nested()\n        {\n        }\n\n        internal static readonly Singleton instance = new Singleton();\n    }\n}	0
7018937	7018884	How can I create temporary objects to pass around without explicitly creating a class?	public void DoSomething() \n{\n    var temp = Tuple.Create("test", "blah blah blah", DateTime.Now);\n    DoSomethingElse(temp);\n}\n\npublic void DoSomethingElse(Tuple<string, string, DateTime> data)\n{\n    // ...\n}	0
23357637	23357537	Dynamically create a class in my project solution	"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\XSD.exe" AppSettings.xsd /c /l:CS /n:"MyProgram.SomeNamespace.AppServices.Settings"	0
28695752	28692963	how to get selected item in listbox in asp?	if(!Page.IsPostBack)\n{\n     UpdateListeView();\n}	0
18802813	18802635	Linq-to-SQL strange behaviour	public static void f3(DB.Group group, string name)\n{\n    DB.DataContext dc = new DB.DataContext();\n    dc.Groups.Attach(group);\n    DB.User user = new DB.User() { Name = name, Group = group, };\n    dc.Users.InsertOnSubmit(user);\n    dc.SubmitChanges();\n}	0
4625850	4625766	XML - help with RSS UTF-8 support	System.IO.StreamReader stream = new System.IO.StreamReader\n                    (response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));	0
3676762	3676713	Truth table as the keys for a dictionary	[Flags]\nenum MyFlagSet : byte\n{\n    NoFlags = 0,\n    Flag1 = 1 << 0,\n    Flag2 = 1 << 1,\n    Flag3 = 1 << 2,\n    Flag4 = 1 << 3,\n    Flag5 = 1 << 4,\n    Flag6 = 1 << 5\n};\n\nDictionary MyDictionary = new Dictionary<MyFlagSet, string>()\n                          {\n                              {MyFlagSet.NoFlags, "Q"},\n                              {MyFlagSet.Flag1 | MyFlagSet.Flag2, "A"},\n                              {MyFlagSet.Flag3 | MyFlagSet.Flag5 | MyFlagSet.Flag6, "B"}\n                          };	0
4800161	4800111	Using await for non CPU intensive task	ThreadPool.QueueUserWorkItem	0
13192894	13184388	Windows Phone 8 Map control - how to get map bounds	GeoCoordinate topLeft = yourMapInstance.ConvertViewportPointToGeoCoordinate(new Point(0, 0));\nGeoCoordinate bottomRight = \nyourMapInstance.ConvertViewportPointToGeoCoordinate(new Point(mapSize.Width, mapSize.Height));\n\nreturn LocationRectangle.CreateBoundingRectangle(new[] { topLeft, bottomRight });	0
27499041	27498351	Rename a checkbox by implementing ContextMenu c# winforms	private void MenuViewDetails_Click(object sender, EventArgs e)    \n{    \n    // Try to cast the sender to a MenuItem    \n    MenuItem menuItem = sender as MenuItem;    \n    if (menuItem != null)    \n    {    \n        // Retrieve the ContextMenu that contains this MenuItem    \n        ContextMenu menu = menuItem.GetContextMenu();    \n\n        // Get the control that is displaying this context menu    \n        Control sourceControl = menu.SourceControl;    \n    }\n}	0
22297821	22281187	Change SQLiteConnectionStringBuilder parameters make write to database faster in C#	SQLiteConnectionStringBuilder conString = new SQLiteConnectionStringBuilder();\nconString.DataSource = databaseFilePath;\nconString.DefaultTimeout = 5000;\nconString.SyncMode = SynchronizationModes.Off;\nconString.JournalMode = SQLiteJournalModeEnum.Memory;\nconString.PageSize = 65536;\nconString.CacheSize = 16777216;\nconString.FailIfMissing = false;\nconString.ReadOnly = false;	0
21140299	21139861	Access property on locked object, without lock statement	public class FooBar\n{\n    public int Var1 { get; set; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var foo = new FooBar();\n        foo.Var1 = 0;\n        Thread t = new Thread(new ParameterizedThreadStart(NewThread));\n        t.Start(foo);\n\n        lock (foo)\n        {\n            foo.Var1 = 1;\n            Thread.Sleep(10000);\n            foo.Var1 = 2;\n        }\n    }\n    public static void NewThread(object foo)\n    {\n        Thread.Sleep(5000);\n        Console.WriteLine((foo as FooBar).Var1);\n    }\n\n}	0
21803470	21776762	get the data that was returned from the stored procedure SQL Server 2008 silvelight C# Linq	InvokeOperation<IEnumerable<Affaire>> LoadAffaire;\n\n    private void IsTheSame(){\n        IsBusy = true;\n        LoadAffaire = Context.IsTheSame(_selectedAffaires, InfoAffaire);\n        LoadAffaire.Completed += new EventHandler(IsTheSame_Completed);\n    }\n\n    private void IsTheSame_Completed(object sender, EventArgs e)\n    {\n        IsBusy = false;\n        TexteInfo = "Succ?s : les donn?es des affaires s?lectionn?es ont ?t? charg?e.";\n        IEnumerable<Affaire> affaire = LoadAffaire.Value.AsEnumerable();\n        MessageBox.Show(affaire.ElementAt(0).nom_fichier_pretour);\n    }	0
31375331	31356426	Something wrong with Marquee progress bar	delegate void textChangeDelegate(int x);\n\nprivate void btnRun_Click(object sender, EventArgs e)\n{\n    Thread thread = new Thread(new ThreadStart(new MethodInvoker(threadJob)));\n    thread.IsBackground = true;\n    thread.Start();\n}\n\npublic void threadJob()\n{\n    Invoke(new MethodInvoker(show));\n    for (int i = 0; i < 10; i++)\n    {\n        Invoke(new textChangeDelegate(textChange),new object[]{i});\n        Thread.Sleep(500);\n    }\n    Invoke(new MethodInvoker(hide));\n}\n\npublic void textChange(int x)\n{\n    if (InvokeRequired)\n    {\n        BeginInvoke(new textChangeDelegate(textChange),new object[] {x});\n        return;\n    }\n    x += 1;\n    lblText.Text = "Count: " + x;\n}\n\npublic void show()\n{\n    pgbRun.Visible = true;\n    lblText.Visible = true;\n}\n\npublic void hide()\n{\n    pgbRun.Visible = false;\n    lblText.Text = "";\n    lblText.Visible = false;\n}	0
18826060	18825875	Need to convert Range of number notation into Comma separated values?	List<string> result = new List<string>();\n            string PageRange = "1,2-5,9";\n            var strings = PageRange.Split(',');\n            foreach (var s in strings)\n            {\n                var split = s.Split('-');\n                if (split.Count() == 1)\n                {\n                    result.Add(s);\n                    continue;\n                }\n\n                for (int i = int.Parse(split[0]); i <= int.Parse(split[1]); i++)\n                {\n                    result.Add(i.ToString());\n                }\n            }	0
3871714	3866424	Editing Log4Net messages before they reach the appenders	protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)\n{\n    string msg = loggingEvent.RenderedMessage;\n    // remove the password if there is any\n    writer.Write(msg);\n}	0
20373243	20373032	How to convert HEX data to Datetime	string hexValue = "529CD17C";\nint secondsAfterEpoch = Int32.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);\nDateTime epoch = new DateTime(1970, 1, 1);\nDateTime myDateTime = epoch.AddSeconds(secondsAfterEpoch);\nConsole.WriteLine(myDateTime);	0
17723737	17719587	Give RequiredAttribute a custom message	public class ParameterisedRequiredAttribute : RequiredAttribute\n    {\n        private string[] _replacements { get; set; }\n\n        public ParameterisedRequiredAttribute(params string[] replacements)\n        {\n            _replacements = replacements;\n\n            ErrorMessageResourceName = ErrorMessagesErrors.SpecificFieldRequired;\n            ErrorMessageResourceType = typeof(ErrorMessages);\n        }\n\n        public override string FormatErrorMessage(string name)\n        {\n            return string.Format(ErrorMessageString, (object[])_replacements);\n        }\n    }	0
8549488	8549144	Simple SQL Insert	SQL CE Tools for Visual Studio	0
12133565	12133505	Make GUI.Box stay for 3 seconds	bool shown = false;\n\nvoid OnGUI () {\n    if (car.transform.position.y>=43 && car.transform.position.y<=44)\n    {\n        shown = true;\n    }\n    else if (shown)\n    {\n        StartCoroutine(DisapearBoxAfter(3.0)); \n    }\n    if(shown) {\n        GUI.Box(new Rect((Screen.width/2)-200,0,400,30) , "King of the hill");\n    }\n}\n\nIEnumerator DisapearBoxAfter(float waitTime) {\n    // suspend execution for waitTime seconds\n    return yield WaitForSeconds (waitTime);\n    shown = false;\n}\n\n\nvoid Update () {\n    OnGUI ();\n}	0
4196740	4196630	Adding a Row to a DataTable question	dtCopyResult.ImportRow(dtResult.Rows[i]);	0
6748045	6748021	get data row in var	dc.Table1s.Skip(50).Take(10)	0
23555438	23555154	API decode a Base64 encoded file received via ReadAsMultipartAsync	public class Base64MultiPartFileStreamProvider : MultipartFormDataStreamProvider\n{\n    public Base64MultiPartFileStreamProvider(string path) : base(path)\n    {\n    }\n\n    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n    {\n       var stream = base.GetStream(parent, headers);\n\n      ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;\n      if (contentDisposition != null)\n      {\n          if (!string.IsNullOrEmpty(contentDisposition.FileName))\n          {\n              stream = new CryptoStream(stream, new FromBase64Transform(), CryptoStreamMode.Write);\n          }\n      }\n\n      return stream;\n    }\n}	0
15770209	15770090	Regex, substring htmlstring	string html = Regex.Match(ResultsString,\n                          @"<table.+<\/table>",\n                          RegexOptions.Singleline).Value;	0
3355076	3354937	Testing a method called many times in moq	int count = 0;\nList<string> items = new List<string>();\nvar mock = new Mock<IWriteFile>();\nmock.Setup(m => m.WriteData(It.IsAny<string>()))\n    .Callback((string data) => { items.Add(data); count++; });	0
19787142	19769614	How can I join 2 tables with different time formats?	LEFT OUTER JOIN QS.FB56 ON (KO1007 = FB5601 AND SUBSTR(KO1025, 3, 4) = SUBSTR(FB5605, 1, 4)	0
27556030	27555003	Cross-thread operation in DataReceived CallBack	private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n        int count = 0;\n        char[] buffer_in;\n\n        buffer_in[count] = (char)serialPort1.ReadByte();\n        count++;\n\n        if (count > 10 && buffer_in[count - 1] == '#' && buffer_in[count - 2] == '@')\n        {\n            this.Invoke((MethodInvoker)delegate\n            {\n                this.textBox_CN2.Text = string.Format("{0:F2}", buffer_in[2]);\n            });\n        }\n\n    }	0
16747677	16747257	Edge Detection with Lockbits C#	Bitmap dstBmp = new Bitmap(width, height, original.PixelFormat);\nFastBitmap fastBitmap = new FastBitmap(dstBmp);\nfastBitmap.LockBitmap();\n//...\nvar pixel = fastBitmap.GetPixel(x,y);\n//...\nfastBitmap.UnlockBitmap();	0
7189075	7188302	Adding Elements,Nodes and Text in XMl in .Net	XmlElement db = doc.CreateElement("DB");\n        XmlElement scope = doc.CreateElement("ScopeCleanUp");\n        XmlElement local = doc.CreateElement("LocalDataBase");\n\n        doc.AppendChild(db);\n        db.AppendChild(scope);\n        scope.AppendChild(local);\n\n        for (int i = 0; i < 2; i++)\n        {\n            XmlElement elem = doc.CreateElement("ScopeName");\n            elem.InnerText = i.ToString();\n            local.AppendChild(elem);\n        }	0
2045066	2045035	Listbox is null, when passing a query string and processing data on load	if (CompletedSandwiches.SelectedItem.Text != null)\n ...	0
27933773	27933737	in c#, can't suppress every line of a process	process.StartInfo.RedirectStandardError = true;	0
22789103	22788429	Which design pattern should i use for a dynamic report generator?	public class ReportData{\n}\n\npublic class ReportResult{\n}\n\npublic class ReportOptions{\n}\n\npublic class ReportSubtype{\n}\n\npublic interface IReport{\n  string Name{get;}\n  string[] ReportSubtype{get;}\n  string[] ReportOptions {get;}\n\n  ReportResult GetReport(ReportData data, ReportSubtype subtype, ReportOptions options);\n}\n\npublic class ReportSample: IReport{\n  //.... your implementation\n}\n\npublic static class ReportFactory{  \n\n  private IReport[] _reports = null; // cache the instances - optional\n\n  public static IReport[] GetAvailableReports(){\n    if (_reports==null)  // static definition can be replaced with dynamic loading\n       _reports = new IReport[]{\n                    new ReportSample(),\n                  };\n\n    return _reports;\n  }\n}	0
20175720	20175660	How do i limit the use of these?	if (!textBox2.Text.EndsWith(" Man"))\n   textBox2.Text += " Man";\n\nif (!textBox3.Text.EndsWith(" Women"))\n   textBox3.Text += " Women";	0
18814312	18814104	Regex Match Collection multiple matches	string input = "<tr class=\"row0\"><td>09/08/2013</td><td><a href=\"/teams/nfl/new-england-patriots/results\">New England Patriots</a></td><td><a href=\"/boxscore/2013090803\">L, 23-21</a></td><td align=\"center\">0-1-0</td><td align=\"right\">65,519</td></tr>";\n\nstring pattern = "(<td>)(?<td_inner>.*?)(</td>)";\n\nMatchCollection matches = Regex.Matches(input, pattern);\n\nforeach (Match match in matches) {\n    try {\n        Console.WriteLine(match.Groups["td_inner"].Value);\n    }\n    catch { }\n}	0
12296061	12295994	Passing array of arguments in command line	var arr = new string[] {"Item title", "New task", "22", "High Priority"};\n        const string path = @"C:\Projects\Test\test.exe";\n        const string argsSeparator = " ";\n        string args = string.Join(argsSeparator, arr);\n\n        Process.Start(path, args);	0
12708163	12704540	lookupedit get selected value	public partial class Form1 : Form\n{\n    public class Example\n    {\n        public int Id { get; set; }\n        public string Name { get; set; }\n        public string Description { get; set; }\n    }\n\n    public List<Example> elist = new List<Example>();\n\n    public Form1()\n    {\n        InitializeComponent();\n        for (int i = 0; i < 10; i++)\n        {\n            elist.Add(new Example() { Id = i, Name = "Name" + i, Description = "Description " + i });\n        }\n        lookUpEdit1.Properties.DataSource = elist;\n        lookUpEdit1.Properties.DisplayMember = "Name";\n    }\n\n    private void lookUpEdit1_EditValueChanged(object sender, EventArgs e)\n    {\n        var item = lookUpEdit1.GetSelectedDataRow() as Example;\n    }\n}	0
25199243	25060574	Get mercurial repository info via URL using C#	hg identify	0
14797848	14797834	Store a C# object in an SQL Server column	object yourMysteryObject = (whatever you like it to be);\n\nMemoryStream memStream = new MemoryStream();\nStreamWriter sw = new StreamWriter(memStm);\n\nsw.Write(yourMysteryObject);\n\nSqlCommand sqlCmd = new SqlCommand("INSERT INTO TableName(VarBinaryColumn) VALUES (@VarBinary)", sqlConnection);\n\nsqlCmd.Parameters.Add("@VarBinary", SqlDbType.VarBinary, Int32.MaxValue);\n\nsqlCmd.Parameters["@VarBinary"].Value = memStream.GetBuffer();\n\nsqlCmd.ExecuteNonQuery();	0
30148463	30148347	parent nodes value to be the sum of all its childrens	function initialize(node) {\n    // internal nodes get their total from children\n    if (node.children.length > 0) {\n        node.value = 0;\n        for (var i = 0; i < node.children.length; i++) {\n            node.value += initialize(node.children[i]);\n        }\n    }\n    return node.value;\n}\ninitialize(root);	0
26926133	26925983	Make one cell editable in datagridview c#	foreach (DataGridViewRow row in DataGridView1.Rows)\n        {\n            if (// condition for true)\n            {\n                row.Cells[2].ReadOnly = true;\n            }\n        else// condition for fals)\n            {\n                row.Cells[2].ReadOnly = false;\n            }\n\n        }	0
19174441	19174379	How to Databind in WPF MVVM	class MyViewModel : INotifyPropertyChanged\n{\n  private IModelRepository _repository;\n\n  public MyViewModel(IModelRepository repository)\n  {\n    _repository = repository;\n    Models = repository.GetAllModels();\n  }\n\n  public IEnumerable<DataModel> Models { get; set; }\n}\n\npublic interface IModelRepository\n{\n  IEnumerable<DataModel> GetAllModels();\n}\n\npublic class MyRepository : IModelRepository\n{\n  public IEnumerable<DataModel> GetAllModels()\n  {\n    // obviously nowhere near final code!!!\n    return new List<DataModel> { \n                      new DataModel { \n                             FirstName = MyDS.Tables[0].Rows[0][1].ToString() \n                      } \n               };\n  }\n}	0
7708314	7707987	How can I make this program check for multiple things one-at-a-time?	if (this.cmboBoxJuiceFlav.Text != "Select a flavor")\n{\n    this.lblFinalFlavor.Text = "Flavor: " + this.cmboBoxJuiceFlav.Text;\n    if (this.txtQuantity.Text != "0")\n    {\n        quantityNum = double.Parse(this.txtQuantity.Text);\n        quantityPrice = cost * quantityNum;\n        this.lblFinalCost.Text = "Cost: " + quantityPrice.ToString("c");\n    }\n    else\n    {\n        MessageBox.Show("Please enter a quantity!");\n    }\n}\nelse\n{\n    MessageBox.Show("Please select a flavor!");\n}	0
5816461	5816414	Synonym for ApprovalWorkflow	{True, False, FileNotFound}	0
25511484	25511330	Is there a convenient way to set default values for ApplicationData.Current.LocalSettings using a settings file?	const string DefaultValue1 = "value123";\nobject value = settings.Values["DailyReminderOnOff"] ?? DefaultValue1;	0
19092523	19092398	How to implement extension method yielding two results for each input value?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Demo\n{\n    class Program\n    {\n        void run()\n        {\n            var test = DuplicateOddNumbers(Enumerable.Range(1, 10));\n\n            foreach (var n in test)\n                Console.WriteLine(n);\n        }\n\n        public IEnumerable<int> DuplicateOddNumbers(IEnumerable<int> sequence)\n        {\n            foreach (int n in sequence)\n            {\n                if ((n & 1) == 1)\n                    yield return n;\n\n                yield return n;\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            new Program().run();\n        }\n    }\n}	0
18266343	18228717	how can get the date in this format "31-jun-2013"	string[] arrayData = TextBox.Text.Split('-');\n\nif (arrayData.Length == 3)\n\nOLCMND2 = new OracleCommand("Select VISITORCOUNT,REMARKS,to_date(to_char(TODAYDATE, 'DD-MON-YYYY'),'DD-MON-YYYY') AS TODAYDATE,CARDNUMBER,PHOTO from VMS_VISITOR where TODAYDATE = TO_DATE('" + TypeHereTextBox.Text + "','dd-MON-yyyy')", CON);\n\nOADAP1 = new OracleDataAdapter(OLCMND2);\nOADAP1.Fill(DTBLE2);\n\nDatagridView.DataSource = DTBLE2;	0
25376430	25376334	Filtering a list in c#	var caseDefendantAtt = msg.CaseDocument.Attorneys.Where(o =>\n        msg.CaseDocument.Defendants.SelectMany(d => d.Attorneys).Contains(o.AttorneyId));	0
7954256	7954216	Finding Data in Excel Spreadsheet	if (currentFind == null)\n{\n// Do this if nothing found...\n}\nelse\n{\n// Do this if something found...\n}	0
7331415	7331372	convert vb email send code to c#	using (var client = new SmtpClient("127.0.0.1", 25))\nusing (var message = new MailMessage("from@foo.com", "to@bar.com"))\n{\n    message.Subject = "some subject";\n    message.Body = "test body";\n    client.Send(message);\n}	0
30935539	30933433	How to replace Html Comment <!-- comment --> tags with string.Empty	HtmlNode table = doc5.DocumentNode.SelectSingleNode("//div[@id='div12']");\n\nRemoveComments(table);\n\npublic static void RemoveComments(HtmlNode node)\n{\n    foreach (var n in node.ChildNodes.ToArray())\n        RemoveComments(n);\n    if (node.NodeType == HtmlNodeType.Comment)\n        node.Remove();\n}	0
18952946	18952637	float to string with no decimal value in C#	string currentHighest = DBContext.Employees\n                                 .Select(x => x.EmpID)\n                                 .OrderByDescending(x => x)\n                                 .FirstOrDefault();\n// TODO: Handle currentHighest being null (empty table)\nint nextId = (int.Parse(currentHighest) + 1).ToString("00000");	0
3711433	3711373	Formatting/indentation for using statements (C#)	using (Resource1 res1 = new Resource1())\nusing (Resource2 res2 = new Resource2())\nusing (Resource3 res3 = new Resource3())\n{\n    // Do stuff with res1, res2 and res3\n}	0
27502620	27502461	How to set the datatextfield value instead of the value on a drop down list?	ddlCountry.Items.FindByText(country).Selected = true	0
32918890	32898443	create a c# listBox in run time to select multiple choices (that comes from database)	if (myListBox.SelectionMode == SelectionMode.Multiple)\n{\n    var selected = new List<string>();\n    foreach (var item in myListBox.Items)\n       if (item.Selected)\n            selected.Add(item.Text);\n\n    response = string.Join(",", selected);\n}	0
10980286	10959359	AutoComplete with context key in a Textbox based on two parameters?	txtbox1.Attributes.Add("onchange", "$find('BehaviourIDOftbxAttributeDesc').set_contextKey(tbxAttribute.value);");	0
22457137	22457117	How to use GETUTCDATE() of the database from c#?	INSERT INTO ... VALUES (..., @FirstName, GETUTCDATE())	0
9412551	9410012	Download File From Another Sever With Save as Dialogue Box	WebClient client = new WebClient();\nstring url = @"http://www.agiledeveloper.com/articles/BackgroundWorker.pdf";\nbyte[] data = client.DownloadData(new Uri(url));\n\nResponse.Clear();\nResponse.ContentType = "application/pdf";\nResponse.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", "aspnet.pdf"));\nResponse.OutputStream.Write(data, 0, data.Length);	0
31463405	31463301	Find a CheckBoxList item by its value within many CheckBoxLists - asp.net	protected void Page_Load(object sender, EventArgs e)\n{\n   FindValue(this);\n}\n\nprivate void FindValue(Control ctrls)\n{\n     foreach (Control c in ctrls.Controls)\n     {\n         if (c is CheckBoxList)\n         {\n                CheckBoxList ff = c as CheckBoxList;\n                for (int i = 0; i < ff.Items.Count; i++)\n                {\n                    if ((string)ff.Items[i].Value == "46")\n                    {\n                         ff.Items[i].Selected = true;\n                    }\n                }\n          }\n\n         else FindValue(c);\n     }\n}	0
12969401	12969209	How can i stop a recursive loop?	if (cancel)\n{\n  return new List<string>();\n}	0
16411687	16409663	Application(solution) structure for Model View Presenter(+ Passive View) in WinForms?	/ - solution root\n\n/[App]Core - project that contains the Model - pure business logic\n/[App]Core/Model - data model (lowercase "m"), POCOs\n/[App]Core/Daos - data access layer (all interfaces)\n/[App]Core/Services - business logic classes (interfaces and implementations)\n\n/[App]Ui - project that contains all UI-related code, but is UI-agnostic\n/[App]Ui/Model - contains POCOs that are used by the UI but not the Core\n/[App]Ui/Presenters - contains presenters\n/[App]Ui/Views - contains view interfaces\n\n/[App][Platform] - project that contains all UI-specific code (e.g. WinRT, WinPhone, WinForms, WPF, Silverlight, etc)\n/[App][Platform]/Daos - implementation of DAO interfaces defined in [App]Core\n/[App][Platform]/Services - implementation of business logic interfaces defined in [App]Core\n/[App][Platform]/Views - implementation of view interfaces defined in [App]Ui	0
31819330	31819221	How to restore a minimized window having only its handle	private const int SW_SHOWNORMAL = 1;\nprivate const int SW_SHOWMINIMIZED = 2;\nprivate const int SW_SHOWMAXIMIZED = 3;\n\n[DllImport("user32.dll")]\nprivate static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);\nprivate void restoreWindow(IntPtr hWnd)\n{\n    if (!hWnd.Equals(IntPtr.Zero))\n    {\n        ShowWindowAsync(hWnd, SW_SHOWMAXIMIZED);\n    }\n}	0
8335098	8260262	How to use Ubuntu Unity global menu in GTK#?	mono [myappname].exe	0
10450693	10351147	Change Devexpress export row value	settings.Columns.Add(set =>\n                    {\n                        set.FieldName = "IsSomething";\n                        set.Caption = "Is Something";\n                        set.UnboundType = DevExpress.Data.UnboundColumnType.String;\n                        set.UnboundExpression = "Iif([IsSomething]==True, 'Yes', 'No')";\n                    });	0
1971809	1959700	MS pie chart with 2 querys	protected void Page_Load(object sender, EventArgs e)\n    {\n\n\n        GetFreeSpace();\n        GetTotalData();\n        usedSpace = totalSpace - freeSpace;\n\n        // Display 3D Pie Chart\n\n        Chart1.Series[0].ChartType = SeriesChartType.Pie;\n\n        Chart1.Series[0]["PieLabelStyle"] = "Inside";\n\n        Chart1.ChartAreas[0].Area3DStyle.Enable3D = true;\n\n\n\n        // Display a Title\n\n        Chart1.Titles.Add("Show Space");\n\n\n\n        // Add Data to Display\n\n        string[] xValues = { "Used Space","Free Space" };\n\n        double[] yValues = { usedSpace,freeSpace};\n\n        Chart1.Series[0].Points.DataBindXY(xValues, yValues);\n\n\n\n        // Call Out The Letter "Free Space"\n\n        Chart1.Series[0].Points[1]["Exploded"] = "true";\n\n\n\n        // Display a Legend\n\n        Chart1.Legends.Add(new Legend("Alphabet"));\n\n        Chart1.Legends["Alphabet"].Title = "Letters";\n\n        Chart1.Series[0].Legend = "Alphabet";\n\n\n    }	0
8093282	8093200	DataTable in FlowDocument	// Create the parent FlowDocument...\nflowDoc = new FlowDocument();\n\n// Create the Table...\ntable1 = new Table();\n// ...and add it to the FlowDocument Blocks collection.\nflowDoc.Blocks.Add(table1);\n\n\n// Set some global formatting properties for the table.\ntable1.CellSpacing = 10;\ntable1.Background = Brushes.White;	0
22450889	22450845	How can I compare Two Dates using C#?	string date = "2014-03-17";\nDateTime d1 = DateTime.Parse(date);\nDateTime d2 = DateTime.Now.Date;\nif (d1.Equals(d2))\n{\n    //Do something\n}	0
10243201	10243047	Ninject get target type from IBinding	Bind<IX>().ToMethod(c => RandomBool() ? new Foo() : new Bar());	0
28846314	28846028	How to access linq group results	var query =\n(\n    from br in \n    (\n        from pp in context.ProductPricings\n        join p in productQuery on pp.ProductId equals p.ProductId\n        where organizationRestrictedPartnerLocations.Contains(pp.PartnerLocationId)\n        select new { pp.ProductId, pp.PartnerLocationId }\n    )\n    join pl in context.PartnerLocation on br.PartnerLocationId equals pl.PartnerLocationId into k\n    from l in k.DefaultIfEmpty()\n    select new { br.ProductId, l.DisplayName }\n).ToLookup(x => x.ProductId, x => x.DisplayName);\n\nvar result = query[0].ToList();	0
10751682	10751337	Linq to XML spotify parsing	WebClient wb = new WebClient();\nvar xdoc = XDocument.Parse(wb.DownloadString("http://ws.spotify.com/search/1/track?q=sail+awolnation"));\nXNamespace ns = XNamespace.Get("http://www.spotify.com/ns/music/1");\nvar tracks = from track in xdoc.Root.Elements(ns + "track") \n     select \n       new \n        { \n           Name = track.Element(ns + "name").Value \n        };\nstring s = "";	0
5260779	5260591	Routing without controller and action in the url	routes.MapRoute("Site"\n              , "Site/{controller}/{action}"\n                , new { controller = "Home", action = "Index"});\n\nroutes.MapRoute("Id"\n              , "{id}"\n                , new { controller = "Home", action = "Details"});	0
27011431	26989357	Issue when trying to read files from a sharepoint/network location in C#	System.Diagnostics.Process.Start(@"c:\windows\system32\net.exe", @"use \\intranet.com\DavWWWRoot\Projects\site");	0
22694278	22689984	Convert Double to Datetime including milliseconds	DateTime conv = new DateTime(1, 1, 1).AddDays(734139.045000000040).AddYears(-1)	0
29359419	29359300	Searching one array then get the corresponding data from another array	public class Person\n {\n      public string Name { get; set; }\n      public int Id { get; set; }\n }\n\n\n IEnumerable<string> names = data.Where(x => input.Any(y => y.Id == x.Id)).Select(x => x.Name);	0
3424222	3423912	What's an efficient method of handeling tab pages dynamically with user controls in them?	List<TabPage>	0
3751946	3751929	Save text from rich text box with C#	rtfMain.SaveFile(dlgSave.FileName);	0
23378872	23378599	Split up List<Node> nodes into List<List<nodes>> listofnodes based on parameters associated with nodes	public static void DivideandInsert(List<Node> list)\n   {\n        List<List<Node>> smallList = new List<List<Node>>();\n         //an extra list\n        List<Node> filtered_list = new List<Node>(); \n\n     //This part will get you all the 55 nodes with density > 5\n     foreach(Node n in list) \n     {\n       if(n.Density > 5)\n       {\n           filtered_list.Add(n);\n       }\n    } \n  int count  = filtered_list.Count;\n  int sublist_count  = (count % 10 == 0) ? count / 10 : count / 10 + 1;\n\n       for(int i=0;i<sublist_count;i++)\n        {\n                List<Node> sublist = new List<Node>();\n\n                for (int k = 0; k < 10; k++)\n                {\n                    sublist.Add(filtered_list[k]);\n                }\n            smallList.Add(sublist);\n        }   \n  }	0
16245073	16245031	Retrieve array from string with regular expression in C#	string[] myArray = inputString.Replace("->", ",").Split(',');	0
25868956	25868532	Download multiple files in C# (one at a time only / queue)	void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{ \n   var links = new[] { "link1", "link2" }; \n\n   var percentProgressStep = (100 / links.Length) + 1\n\n   using (var client = new WebClient()) \n   foreach (string l in links) \n     {\n       client.DownloadFile(l, Path.GetTempFileName());\n       backgroundWorker1.ReportProgress(percentProgressStep);\n     } \n}	0
10727955	10727911	Two counters in a for loop for C#	for (int j = mediumNum, k = 0; j < hardNum && k < mediumNum; j++, k++)	0
29005849	29005559	find the node value in xDocument	XDocument doc = XDocument.Parse(xml);\n\n XNamespace xmlNamespace = "www.abc.com";\n var ResultNode = from a in doc.Descendants(xmlNamespace + "VerificationResponse").Descendants(xmlNamespace + "StatusDescription")\n                  select a.Value;	0
22000353	21997520	CascadingDropDown from XML in a Dataset	private void Bind()\n{\n    int jobOrganizationId = 0;\n    DataSet ds = new DataSet();\n    ds.ReadXml(Server.MapPath("App_Data") + "\\XMLFile1.xml");\n    DataRow[]  rows = ds.Tables["job_organization"].Select("name = '" + ddlOrg.SelectedItem.Text + "'");\n    if(rows.Length > 0 && int.TryParse(rows[0]["job_organization_Id"].ToString(), out jobOrganizationId))\n    {\n        ddlJobTitle1.DataTextField = "name";\n        ddlJobTitle1.DataValueField = "value";\n        DataView view = new DataView(ds.Tables["job"]);\n        view.RowFilter = "job_organization_Id='" + jobOrganizationId.ToString() + "'";\n        ddlJobTitle1.Enabled = true;\n        ddlJobTitle1.DataSource = view;\n        ddlJobTitle1.DataBind();\n    }\n}	0
19619373	19619242	LINQ How to group by two lists to one list?	var combinedList = new List<Animal>();\n\ncombinedList.AddRange(people);\ncombinedList.AddRange(animals);\n\nvar grouped = combinedList.GroupBy(y => new {y.ID}).ToList();	0
11442248	11442210	Local variables or direct statements?	bool mustWait = someCommand.ConflictsWith(otherCommand);\nif (mustWait) {\n    ...\n}	0
28849768	28849677	Sorting points in 3D	class CompareDistance\n{\n    public float DistanceToCameraPlane(Vector3 pointInSpace)\n    {\n        var cameraPosition = Camera.main.transform.position;\n        var cameraForward = Camera.main.transform.forward;\n        var deltaToCamera = pointInSpace - cameraPosition;\n        var projection = Vector3.Project(deltaToCamera, cameraForward);\n        return projection.magnitude;\n    }\n}	0
16123813	16117065	SUM of the details in group header Crystal reports	sum({table.field_to_summarize},{table.field_you_are_grouping_on})	0
18278539	18243611	F# Xml TypeProvider for C#	// Modelling RSS feeds - the following types define the structure of the\n// expected XML file. The StructuralXml parser can automatically read\n// XML file into a structure formed by these types.\ntype Title = Title of string\ntype Link = Link of string\ntype Description = Description of string\n\ntype Item = Item of Title * Link * Description\ntype Channel = Channel of Title * Link * Description * list<Item>\ntype Rss = Rss of Channel\n\n// Load data and specify that names in XML are all lowercase\nlet url = "http://feeds.guardian.co.uk/theguardian/world/rss"\nlet doc : StructuralXml<Rss> = \n  StructuralXml.Load(url, LowerCase = true)\n\n// Match the data against a type modeling the RSS feed structure\nlet (Rss(channel)) = doc.Root\nlet (Channel(_, _, _, items)) = channel\nfor (Item(Title t, _, _)) in items do\n  printfn "%s" t	0
5871417	5871338	Selecting image in folder using MonoTouch	UIImage image = UIImage.FromFile("Images/picture.jpeg");	0
41428	41407	Parsing a log file with regular expressions	(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/\n\d{2}))+)	0
10854764	10854745	calculating number of days between 2 dates chosen from calendar(C#)	var days = (Calendar1.SelectedDate - Calendar2.SelectedDate).TotalDays;	0
13280416	13276821	How to insert Page break when creating MS Word document	using Word = Microsoft.Office.interop.Word; \n\n//create a word app\nWord._Application  wordApp = new Word.Application();\n//add a page\nWord.Document doc = wordApp.Documents.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);\n//show word\nwordApp.Visible = true;\n//write some tex\ndoc.Content.Text = "This is some content for the word document.\nI am going to want to place a page break HERE ";\n//inster a page break after the last word\ndoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);\n//add some more text\ndoc.Content.Text += "This line should be on the next page.";\n//clean up\nMarshal.FinalReleaseComObject(wordApp);\nMarshal.FinalReleaseComObject(doc);\nGC.Collect();\nGC.WaitForPendingFinalizers();\nGC.Collect();	0
15060489	15059550	TabControl, TabPage avoid switch statement	public Form1()\n{\n    InitializeComponent();\n\n    // I set tabPage1 & 2 event w/ the designer\n    tabPage3.Enter += tabPage3_Enter;\n}\n\nprivate void tabPage1_Enter(object sender, EventArgs e)\n{\n    Debug.WriteLine("tabPage1_Enter");\n}\n\nprivate void tabPage2_Enter(object sender, EventArgs e)\n{\n    Debug.WriteLine("tabPage2_Enter");\n}\n\nprivate void tabPage3_Enter(object sender, EventArgs e)\n{\n    Debug.WriteLine("tabPage3_Enter");\n}	0
17912111	17912014	How to use systeminfo.exe command lines in a Process?	private void SysInfo32()\n{\n    Process proc = new Process();\n    proc.EnableRaisingEvents = true;\n    proc.StartInfo.UseShellExecute = false;\n    proc.StartInfo.FileName = "cmd.exe";\n    proc.StartInfo.CreateNoWindow = true;\n    proc.StartInfo.WorkingDirectory = contentDirectory;\n    proc.StartInfo.Arguments = "/C systeminfo.exe> sysinfo.txt";\n    proc.Start();\n    proc.WaitForExit();\n    proc.Close();\n}	0
14195339	14194896	Splitting string from FOR XML PATH	string rawInput = "China Incentive Program,50,6,1|India - Q2 Incentive ,50,6,4|China -     Q2 Incentive,50,6,5|India Incentive Program,100,8,3|India - Q2 Incentive ,100,8,4";\nstring[] rawPoints = rawInput.Split(new char[]{'|'});\n\nList<UserTrainingPointsDataModel> points = new List<UserTrainingPointsDataModel>();\n\nforeach(string rawPoint in rawPoints)\n{\n    string[] enrty = rawPoints.Split(new char[]{','});\n    var point = new UserTrainingPointDataModel();\n    point.Name = entry[0];\n    point.Points = entry[1];\n    point.InteractionType = entry[2];\n\n    points.Add(point);  \n}	0
8741553	8741474	Returning a stream from File.OpenRead()	str.CopyTo(data);\ndata.Seek(0, SeekOrigin.Begin); // <-- missing line\nbyte[] buf = new byte[data.Length];\ndata.Read(buf, 0, buf.Length);	0
19424672	19423320	how to make datagridview column as linktype	foreach (DataGridViewRow row in dataGridViewVisits.Rows)\n            {\n                DataGridViewLinkCell linkCell = new DataGridViewLinkCell();\n                linkCell.Value = row.Cells[1].Value;\n                row.Cells[1] = linkCell;\n            }	0
1659278	1659250	Managing a text file in C#	string filePath = ...\nList<string> lines = new List<string>(File.ReadAllLines(filePath ));\nlines.RemoveAt(2);  //Remove the third line; the index is 0 based\nFile.WriteAllLines(filePath, lines.ToArray());	0
12564652	12563627	How to access Columns for DevExpress.XtraGrid.GridControl in C#	var firstColumnName = ((GridView)gridControl.MainView).Columns[0].FieldName;	0
1491269	1491258	Best way to get a static DateTime value	public static DateTime StartOfRecordedHistory = new DateTime(2004, 1, 1)	0
9863139	9863016	Multiple character casing in same TextBox	string[] lines = isv.Text.Split('\n');\nstring finalText = string.Empty;\nfor (int i = 0; i < lines.length; i++)\n    finalText += i%2==0 ? lines[i].ToUpper() : lines[i].ToLower() +  + Environment.NewLine;\nisv.Text = finalText;	0
3395644	3395624	Is it posible to save file with the desired name I choose	SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n\nsaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";\nsaveFileDialog1.FilterIndex = 2;\nsaveFileDialog1.RestoreDirectory = true;\nsaveFileDialog1.InitialDirectory = Environment.CurrentDirectory;\nsaveFileDialog1.FileName = "MyDefaultFileName";	0
21804012	21803760	webresponse from 3rd party, using their given API, C#	var sessionid = XDocument.Parse(s).Descendants("data").First().Value;	0
26404777	26404522	How can i find specific Image Control and set its ImageUrl property (ASP.net - vb)	Dim myImg As System.Web.UI.WebControls.Image = CType(FindControl(mytextbox.Text), System.Web.UI.WebControls.Image)\nmyImg.ImageUrl = "~/ImageFolder/default.jpg"	0
32222289	32184402	Get protected property value of base class using reflections	SubsetController controller = new SubsetController(new CConfigRepository(new FakeDataContextRepository()));\n\nvar myBaseClassProtectedProperty=\n            controller.GetType().BaseType\n                .GetProperty("CCITenderInfo", BindingFlags.NonPublic | BindingFlags.Instance)\n                .GetValue(controller);\n\nvar myProtectedProperty =\n            CCITenderInfo.GetType()\n                .GetProperty("ConfigurationId", BindingFlags.Public |     BindingFlags.Instance)\n                .GetValue(myBaseClassProtectedProperty);	0
14285684	14285652	Invoke method with specific parameters without type unboxing	Func<int, int, int, string> del = yourClassInstance.UserName;\n\n// use three ints directly here...\nstring result = del(user, role, rank);	0
9116338	9114491	How Can I update the Outer Control Height when Running an Animation on the content in that row?	public override OnApplyTemplate()\n{\n    //in the onapplytemplate overried\n    _collapseHeightAnimation = (DoubleAnimation) GetTemplateChild("_collapseHeightAnimation");\n    _expandHeightAnimation = (DoubleAnimation) GetTemplateChild("_expandHeightAnimation");\n\n    //get controls for updating heights and angles once we know what that information will be\n    var contentBorder = (Border) GetTemplateChild("_borderContent");\n\n}\n\npublic void ContentBorderSizeChanged(object sender, SizeChangedEventHandler e)\n{\n    //once the size of my control has been determined\n    // can set to and from values that weren't available before\n    // in this case this happens in the size change event\n    _collapseHeightAnimation.From = contentBorder.ActualHeight;\n    _expandHeightAnimation.To = contentBorder.ActualHeight;\n}	0
4069149	4068375	Where to Trim() incoming request parameters?	public class SearchViewModel\n{\n   ...\n\n   private string search;\n\n   public string Search\n   {\n      get\n      {\n         return search;\n      }\n      set\n      {\n         search = value.Trim();\n      }\n   }\n\n   ...\n}	0
26246917	26246815	Stumped in Dependency Property in VB	lbi.GetVisualAncestors().OfType(Of ListBox).First()	0
21921497	21921137	Encode decoded string with Base64String	public static string Encode(string plainText)\n{\n    byte[] numArray = System.Text.Encoding.Default.GetBytes(plainText);\n    byte[] numArray1 = new byte[(int)numArray.Length + 1];\n    // Generate a random byte as the seed used\n    (new Random()).NextBytes(numArray1);\n    byte num = (byte)(numArray1[0] ^ 188);\n    numArray1[0] = numArray1[0];\n    for (int i = 0; i < (int)numArray.Length; i++)\n    {\n        numArray1[i + 1] = (byte)(num ^ 188 ^ numArray[i]);\n    }\n    return Convert.ToBase64String(numArray1);\n}	0
5658390	5658283	How to use for loop to scan all controls in page in ASP .NET?	protected void buttonClick(object sender, EventArgs e)\n{\n    List<String> errors = new List<String>();\n    ValidateTextboxes(errors, this.Controls);\n    if (errors.Count > 0)\n    {\n        // Validation failed\n    }\n}\n\nprotected void ValidateTextboxes(List<String> errors, ControlCollection controls)\n{\n    foreach (Control control in controls)\n    {\n        if (control is TextBox)\n        {\n            // Validate\n            TextBox tb = control as TextBox;\n            if (tb.Text.Length == 0)\n                errors.Add(tb.ID + ": field is required:");\n        }\n\n        if (control.Controls.Count > 0)\n            ValidateTextboxes(errors, control.Controls);\n    }\n}	0
13749420	13481041	Copy Excel RangeSelection to array in Windows Application	try\n{\n    var data = Clipboard.GetDataObject();\n    var stream = (System.IO.Stream)data.GetData(DataFormats.CommaSeparatedValue);\n    var enc = new System.Text.UTF8Encoding();\n    var reader = new System.IO.StreamReader(stream, enc);\n    string data_csv = reader.ReadToEnd();\n    string[] data_csv_array = data_csv.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);\n    ...\n}\ncatch (Exception e)\n{\n    ErrorHandling.ShowError("There is no data on the Clipboard to paste.");=\n}	0
12421222	12420553	Failing to upload Image in base64 bits via XML-RPC [Wordpress/NGG]	newImage.name = "newImage";	0
5730223	5729571	Add namespace to XAML code	string xamlString = "... get some xaml from somewhere ...";\nint insertPosition = xamlString.IndexOf(">");\nxamlString.Insert(insertPosition, "my new namespace");	0
27508773	27507946	Pass KeyDown event to other control	//Parent Control Visible\nprivate void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    richTextBox1_KeyPress(sender, e);\n}\n//Child Control Hidden\nprivate void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    richTextBox1.Text += e.KeyChar.ToString();\n}	0
643768	643687	Is there a method to swap the left and right hand sides of a set of expressions in Visual Studio?	Imports System\nImports EnvDTE\nImports EnvDTE80\nImports System.Diagnostics\nImports System.Text.RegularExpressions\n\nPublic Module Helpers\n    Sub SwapAssignment()\n        If (Not IsNothing(DTE.ActiveDocument)) Then\n            Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)\n            selection.Text = Regex.Replace(selection.Text, "([^\s]*)\s*=\s*([^\s]*);", "$2 = $1;")\n        End If\n    End Sub\nEnd Module	0
22059902	22059552	How to Unit Test method that uses a Webservice on Windows Phone?	private readonly IClient client;\nprivate readonly ISerializer serializer;\n\npublic YourService(IClient client, ISerializer serializer)\n{\n    _client = client;\n    _serializer = serializer;\n}\n\npublic async Task<List<Song>> FetchSongsAsync(String query)\n{\n    try\n    {\n        var result = await _client.GetStringAsync(new Uri("http://example.com"));\n        return _serializer.DeserializeObject<RootObject>(result);\n    }\n    catch (Exception)\n    {\n        return null;\n    }\n}	0
11655263	11620672	Inserting XML document into SQL column using linq	private string LoadXml(string FileName)\n{\n    try\n    {\n        using (StreamReader reader = new StreamReader(FileName))\n        {\n            return reader.ReadToEnd();\n        }\n    }\n    catch\n    {\n        return string.Empty;\n    }\n}	0
26541888	26540878	WPF Image control masked with a container same as polygon	Stretch=None or Fill or...	0
12916165	12915814	Assigning attributes to a control upon creation?	class MyButton: Button\n{\n    MyButton(MyAttributes atr)\n    {\n       for each (elm in atr)\n       {\n          base.Attributes.Add(elm.Key, elm.Value);\n       }\n    }\n}	0
30642872	28393592	LaunchAdvancedAssociationUI in C# -> Element not found on Windows 8	[assembly: AssemblyCompany("YourCompany")]	0
19683166	19683045	Take result with max count using LINQ	var query = tapesTable.GroupBy(x => x.Tape)\n                      .Select(x => x.OrderByDescending(t => t.Count)\n                                    .First());	0
1061907	1061895	How do you prevent a rich text box from automatic scrolling, when performing syntax highlighting?	Save selstart position. \nDisable updates to the text box.  \nApply syntax highlighting.\nSet selstart to saved value.  \nEnable updates.	0
22906330	22906283	StreamWriter is a 'namespace' but is used like a 'type'	namespace StreamWriter	0
23672345	23672072	How to modify lambda statement to start at lists index position and return that position	public static int? Match(int start_index, string searchTerm)\n    {\n        var wanted = _properties\n            .Select((prop,i) => new { Index = i, Item = prop(_itemType) })\n            .Skip(start_index)\n            .FirstOrDefault(value => value.Item != null && value.Item.ToLower().Contains(searchTerm.ToLower()));\n        return wanted==null ? null : (int?)wanted.Index;\n    }	0
22664493	22560991	How to run a SpecFlow test through a test harness?	TestRunner.TestDLLString = getDLL(project);\n            var TestDLL = Assembly.LoadFrom(TestDLLString);\n\n            Type myClassType = TestDLL.GetType("SeleniumDPS." + testname);\n\n\n            var instance = Activator.CreateInstance(myClassType);\n\n            MethodInfo myInitMethod = myClassType.GetMethod("Initialize");\n\n\n            try\n            {\n                myInitMethod.Invoke(instance, null);\n            }\n            catch (Exception ex)\n            {\n//Error logging etc\n            }	0
29792662	29782401	How to detect if Combobox selection is changed by user	public DataItem FirstDataItem\n   {\n          get \n          { \n          return firstDataItem; \n          }\n          set\n          {\n            firstDataItem= value;\n            if (FirstDataItem!= null)\n              FirstDataItem.PropertyChanged += (x, y) =>\n              {\n                if (y.PropertyName =="Data" )\n                  DoSomething();\n              };\n          }\n    }	0
33773338	33755586	Add values recursively in data table using c#	public DataTable AddingRecursive(DataTable table)\n        {\n            for (int i = table.Rows.Count - 1; i >= 0; i--)\n            {\n                if (Convert.ToInt64(table.Rows[i]["Parent ID"]) != 0)\n                {\n                    Int64 parentNode = Convert.ToInt64(table.Rows[i]["Parent ID"]);\n                    Decimal value = Convert.ToDecimal(table.Rows[i]["Values"]);\n                    foreach (DataRow row in table.Rows)\n                    {\n                        if (parentNode == Convert.ToInt64(row["ID"]))\n                        {\n                            row["Values"] = Convert.ToDecimal(row["Values"]) + value;\n                        }\n                    }\n                }\n            }\n            return table;\n        }	0
27022953	27022294	Passing image into Android ListView ArrayAdapter	List<HashMap<String, Object>> menuItemNames = new ArrayList<HashMap<String,Object>>();\n    HashMap<String, Object> row = new HashMap<String, Object>();\n    row.put("icon", R.drawable.home_icon);\n    row.put("text", "Home");\n    menuItemNames.add(row);\n    row = new HashMap<String, Object>();\n    row.put("icon", android.R.drawable.new_icon);\n    row.put("text", "New");\n    menuItemNames.add(row);\n    row = new HashMap<String, Object>();\n    row.put("icon", android.R.drawable.delete_icon);\n    row.put("text", "Delete");\n    menuItemNames.add(row);\n\n    int[] to = {R.id.sideMenuItemIconsDrawables, R.id.MenuItemText}; //IDs of your text and icon\n    String[] from = {"icon", "text"};\n\n    adapter = new SimpleAdapter(this, menuItemNames, R.layout.item_menu, from, to);\n    listView.setAdapter(adapter);	0
14668394	14668091	Read Registry_binary and convert to string	var valueName = "some binary registry value";\nvar valueKind = registryKey.GetValueKind(valueName);\nif (valueKind == RegistryValueKind.Binary)\n{\n    var value = (byte[])registryKey.GetValue(valueName);\n    var valueAsString = BitConverter.ToString(value);\n}	0
4145944	3565009	WPF windows forms host keyboard events	private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {\n  if (DesignMode) return;\n  if (!e.IsInputKey && e.Control && e.KeyCode == Keys.S) {\n    DoStuff();\n    return;\n  }\n}	0
23140021	23139510	C# Client program console window	p.StartInfo.CreateNoWindow = true;	0
3918466	3918431	how to achieve calling a function dynamically, thats right the function to be called is decided from database values, using c#	// Get the Type on which your method resides:\nType t = typeof(SomeType);\n// Get the method\nMethodInfo m = t.GetMethod("methodNameFromDb");\n// Invoke dynamically\nm.Invoke(instance, null);	0
15579759	15579744	How to get a web service object?	LocationWebService objService = new LocationWebService(); // this is proxy class of web service created when you add web reference\nstring result = objService.GetLocationName(4); //call web method	0
30739967	30739764	Winforms remove controls on click	private void radMenuItem3_Click(object sender, EventArgs e)\n{\n    while (rpvRecord.Controls.Count > 0)\n    {\n        ctrl = rpvRecord.Controls[0];\n        rpvRecord.Controls.Remove(ctrl);\n        ctrl.Dispose();\n    }\n}	0
33400992	33400795	Creating A Soundboard In C# .NET Dim Statement Doesnt Turn Blue	private void button1_Click(object sender, EventArgs e)\n{\n    string sPath; //Declaration pattern: Variable Type followed by Name\n    System.Media.SoundPlayer mySound; //if you're not using namespace full path\n\n    sPath = "Location of where I have the sound file.wmv";\n    mySound = new Media.SoundPlayer(sPath);\n    mySOund.Play();\n}	0
25405962	25404857	Serialize a list of primitives to XML with overrides	[Serializable]\n[XmlRoot("rows")]\npublic class Rows\n{\n    [XmlElement("row")]\n    public List<int> Elements { get; set; } \n}\n\npublic static void SerializeOnScreen()\n{\n    Rows numbers = new Rows();\n    numbers.Elements = new List<int>() { 1, 2, 3, 4, 5 };\n\n    var serializer = new XmlSerializer(typeof(Rows));\n    using (var stringWriter = new StringWriter())\n    {\n        serializer.Serialize(stringWriter, numbers);\n        Console.Write(stringWriter.ToString());\n    }\n}	0
8343371	8343294	Jumping in C# using console application	string begroeting;\n\nwhile(begroeting.ToLower() != "some string you want to stop loop execution")\n{\n   Console.WriteLine("Hi."); \n    string eersteAntwoord = Console.ReadLine(); \n    if (eersteAntwoord == "Hi" || eersteAntwoord == "hi") \n    { \n        Console.WriteLine("How are you doing?"); \n\n        begroeting = Console.ReadLine(); \n        if (begroeting == "I'm good") \n        { \n            Console.WriteLine("Good"); \n            break; // this would be if you want to get out of your loop\n        } \n        else if (begroeting == "hi") \n        { \n            Console.WriteLine(""); \n            continue; // go to the next iteration of the while loop\n        }\n    }\n}	0
3041107	3039296	Castle Windsor - Resolving a generic implementation to a base type	ISpecification<ZImplementation>	0
4853916	4853873	Passing a Variable to an Event in .NET	beeList[ pbList.IndexOf(sender)  ].name	0
29378237	29374698	Regex to parse a duration string "xx'h' yy'mn' zz's'" in c#	(?<VALUE>\d{1,2})(?<TYPE>h|mn|s)	0
9314826	7010997	Programatically set a binding to require client certificate negotiation in iis	ULONG HttpSetServiceConfiguration(\n  __in  HANDLE ServiceHandle,\n  __in  HTTP_SERVICE_CONFIG_ID ConfigId,\n  __in  PVOID pConfigInformation,\n  __in  ULONG ConfigInformationLength,\n  __in  LPOVERLAPPED pOverlapped\n);	0
14314277	14305310	Implement Window Drag and Drop WPF	private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        this.DragMove();\n    }	0
22000827	21993721	ReportViewer IE 11	void Application_BeginRequest(object sender, EventArgs e)\n{\n    // Bug fix for MS SSRS Blank.gif 500 server error missing parameter IterationId\n    // https://connect.microsoft.com/VisualStudio/feedback/details/556989/\n    if (HttpContext.Current.Request.Url.PathAndQuery.StartsWith("/Reserved.ReportViewerWebControl.axd") &&\n     !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ResourceStreamID"]) &&\n        HttpContext.Current.Request.QueryString["ResourceStreamID"].ToLower().Equals("blank.gif"))\n    {\n        Context.RewritePath(String.Concat(HttpContext.Current.Request.Url.PathAndQuery, "&IterationId=0"));\n    }\n}	0
6933593	6933526	Get listview checkbox status in WPF	public class UserData : INotifyPropertyChanged\n    {\n       private bool m_value;\n\n       public bool Value\n       {\n          get { return m_value; }\n          set\n          {\n             if (m_value == value)\n                return;\n             m_value = value;\n             if (PropertyChanged != null)\n                PropertyChanged(this, new PropertyChangedEventArgs("Value"));\n          }\n       }\n\n       public event PropertyChangedEventHandler PropertyChanged;\n   }	0
14847571	14846222	I want to add a search button with a text box and a drop down for showing the resuls in itin my windows application using C#	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n        {\n            btnsearch.Enabled = true;\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            webBrowser1.Navigate("http://in.finance.yahoo.com/actives?e=bo");\n        }\n\n        private void btnsearch_Click(object sender, EventArgs e)\n        {\n            foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("td"))\n            {\n                if (item.GetAttribute("className").Equals("second name"))\n                {\n                    if (item.InnerText.Contains( txtsearch.Text))\n                    {\n                        lstresult.Items.Add(item.InnerText);\n                    }\n                }\n            }\n        }	0
24115121	24115009	How to read row one at a time in Datagrid Wpf c#	var tmplist = (ObservableCollection<YourDataGridObject>)DataGrid.ItemsSource;\n    foreach (YourDataGridObjectitm in tmplist)\n    {\n    ///Access elements\n    }	0
9431260	9429608	How to avoid serialization default values?	[DefaultValue(false)]	0
18086739	18084387	How resize image without losing quality	public static Image GetThumbnailImage(Image OriginalImage, Size ThumbSize)\n{\n    Int32 thWidth = ThumbSize.Width;\n    Int32 thHeight = ThumbSize.Height;\n    Image i = OriginalImage;\n    Int32 w = i.Width;\n    Int32 h = i.Height;\n    Int32 th = thWidth;\n    Int32 tw = thWidth;\n    if (h > w)\n    {\n        Double ratio = (Double)w / (Double)h;\n        th = thHeight < h ? thHeight : h;\n        tw = thWidth < w ? (Int32)(ratio * thWidth) : w;\n    }\n    else\n    {\n        Double ratio = (Double)h / (Double)w;\n        th = thHeight < h ? (Int32)(ratio * thHeight) : h;\n        tw = thWidth < w ? thWidth : w;\n    }\n    Bitmap target = new Bitmap(tw, th);\n    Graphics g = Graphics.FromImage(target);\n    g.SmoothingMode = SmoothingMode.HighQuality;\n    g.CompositingQuality = CompositingQuality.HighQuality;\n    g.InterpolationMode = InterpolationMode.High;\n    Rectangle rect = new Rectangle(0, 0, tw, th);\n    g.DrawImage(i, rect, 0, 0, w, h, GraphicsUnit.Pixel);\n    return (Image)target;\n}	0
14817256	14817061	Transpose a datatable	private DataTable Transpose(DataTable dt)\n{\n    DataTable dtNew = new DataTable();\n\n    //adding columns    \n    for(int i=0; i<=dt.Rows.Count; i++)\n    {\n       dtNew.Columns.Add(i.ToString());\n    }\n\n\n\n    //Changing Column Captions: \n    dtNew.Columns[0].ColumnName = " ";\n\n     for(int i=0; i<dt.Rows.Count; i++) \n     {\n      //For dateTime columns use like below\n       dtNew.Columns[i+1].ColumnName = Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");\n      //Else just assign the ItermArry[0] to the columnName prooperty\n     }\n\n    //Adding Row Data\n    for(int k=1; k<dt.Columns.Count; k++)\n    {\n        DataRow r = dtNew.NewRow();\n        r[0] = dt.Columns[k].ToString(); \n        for(int j=1; j<=dt.Rows.Count; j++)\n        r[j] = dt.Rows[j-1][k];  \n        dtNew.Rows.Add(r);\n    }\n\n return dtNew;\n}	0
11507842	11507769	Having issues using a nested loop to properly load an array	int n = 0;\nint n2 = 0;\nwhile (n2 < 5)\n    {\n        n = 0;\n        while (n < 4)\n        {\n            Rectangles[n2, n] = new Rectangle\n                 (sizeOfEachSpriteX * n2, \n                  sizeOfEachSpriteY * n, \n                  sizeOfEachSpriteX, \n                  sizeOfEachSpriteY);\n            n++;\n        }\n        n2++;\n    }	0
22398292	22398082	Regex: Find and modify multiple matches	Regex rx = new Regex("(?<=<img[^>]*src=\")[^\"]+", RegexOptions.IgnoreCase);\nstring html = "My html string with several img tags...";\nstring newHtml = rx.Replace(html, m => "/newroot/images/" + m.Value);	0
11751677	11751095	Trouble creating a Regex expression	string input = "$00";\n\n        Match m = Regex.Match(input, @"^\$[0-9a-fA-F][0-9a-fA-F]$");\n        if (m.Success)\n        {\n            foreach (Group g in m.Groups)\n                Console.WriteLine(g.Value);\n        }\n        else\n            Console.WriteLine("Didn't match");	0
10909425	10909370	 How to duplicate list members in C#?	int currentCount = list.Count;\n\nfor (int i=0; i<x; ++i)\n{\n     list.Add(list[i%currentCount]);  \n}	0
10220568	10220529	Forcing the execution of a method	List<CheckoutIssues> issues = new List<CheckoutIssues>();\nforeach (IGroceryItem item in itemsToBuy) {\n    issues.Add(item.EnsureFreshness());\n}	0
30281806	30280187	Emit Particle onCollision in Unity 3D	public ParticleSystem collisionParticlePrefab; //Assign the Particle from the Editor (You can do this from code too)\nprivate ParticleSystem tempCollisionParticle;\n\nvoid OnTriggerEnter (Collider _hit)\n{\n    if (_hit.tag == "Coin") {\n        Destroy (_hit.gameObject);\n        coinCount++;\n        coinsText.text = "Coins: " + coinCount.ToString() + "/" + coinTotal.ToString();\n        tempCollisionParticle = Instantiate (collisionParticlePrefab, transform.position, Quaternion.identity) as ParticleSystem;\n        tempCollisionParticle.Play ();\n    }\n}	0
12239766	12239742	How to programmatically add PictureBox control to the tab page control	PictureBox pb = new PictureBox();\npb.Dock = DockStyle.Fill;\ntabPage.Controls.Add(pb);	0
4493328	4493266	RhinoMocks use default implementation for property	var person = MockRepository.GeneratePartialMock<Person>();	0
26492238	26492095	Access DB backup in C#	private void BackupDatabase_Click(object sender, RoutedEventArgs e)\n        {\n            File.Copy("Books_NE.mdb", "Books_NEBak.mdb", true);\n        }	0
7750998	7750841	Dispose of dialogwindow in backgroundworker	public partial class MainForm:Form\n{\n   LoadingScreen ls;\n\n   public MainForm()\n   {\n   }\n\n   public void StartLoad()\n   {\n      ls = new LoadingScreen(this.timerStart);\n      backgroundWorker.RunWorkerAsync();\n      ls.Show();\n   }\n\n   void backgroundWorkerDoWork(object sender, DoWorkEventArgs e)\n   {\n      //Loading code goes here\n   }\n\n   void BackgroundWorkerMainRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n   {\n      if(ls != null)\n         ls.Close();\n   }\n}	0
24307264	24306730	Incorrect value in deserializating Xml to Class	nillable='true'	0
29482469	25853004	How to set table character set using fluent migrator	[Migration(01, TransactionBehavior.Default, "Testing creating a table with charset")]\npublic class _0001_AddTableWithCharsetColumn : Migration\n{\n    public override void Down()\n    {\n        Delete.Table("StackOverflow");\n    }\n\n    public override void Up()\n    {\n        var sql = @"CREATE TABLE StackOverflow\n                    (\n                        foo VARCHAR(5)\n                            CHARACTER SET latin1\n                            COLLATE latin1_german1_ci\n                    );";\n\n        Execute.Sql(sql);\n    }\n}	0
2766305	2766224	Finding a string inside an XmlDocument	xmlDocument.SelectNodes("//*[contains(text(), 'ThisText')]");	0
22686102	22686056	Accessing multiple Values from URI / QueryString	public class MyController\n {\n      public ActionResult MyAction(int id_A, string param1,...)\n      {\n           // your controller logic\n      }\n }	0
19328254	19328198	Creating a recursive method for counting a specific character in C#	public class CountCharacter\n{\n    public static void Main (string[] args)\n    {\n        string s = "most computer students like to play games";\n        Console.WriteLine(countCharacters(s, 's'));\n    }\n\n    public static int countCharacters( string s, char c)\n    {\n        if (s.Length == 0)\n            return 0;\n        else if (s[0] == c)\n            return 1 + countCharacters(s.Substring(1), c);\n        else\n            return countCharacters(s.Substring(1), c);\n    }\n}	0
32162297	32162272	Textbox TextChange event only firing if user hits space button	private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)\n{\n  txtInputID.Attributes.Add("onfocus", "javascript:this.value=this.value;")\n  txtInputID.Focus()\n}\n\n<script type="text/javascript">\n   var MIN_TEXTLENGTH = 3;\n\n   function forcePostback(ctrl) {\n     if (ctrl != null && ctrl.value && ctrl.value.length >= MIN_TEXTLENGTH) {\n         __doPostBack(ctrl.id, '');\n     }\n   }\n</script>\n\n...    \n\n<asp:TextBox ID="txtInputID" OnKeyUp="forcePostback(this);" AutoPostBack="true" \n  OnTextChanged="ReadWriteTB_TextChanged" runat="server"/>	0
321163	321077	Cant Access File because it is being used by another process	WebClient wc = new WebClient();\nwc.DownloadFile("http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png", "Foo.png");\nFileStream fooStream;\nusing (fooStream = new FileStream("foo.png", FileMode.Open))\n{\n// do stuff\n}\nFile.Move("foo.png", "foo2.png");	0
29672363	29672295	Making code loop until multiple parameters succesful	int inValue;\nwhile (!int.TryParse(Console.ReadLine(), out inValue) && (inValue == 1 || inValue ==2))\n{\n    Console.WriteLine("That is not a valid gender");\n    Console.WriteLine("Please, insert a valid gender");\n}	0
20362546	20361991	How do I Change Object Type Assembly in PowerShell	powershell.exe -version 2	0
30826735	30822322	How to click on a text in a Container Column Container Using Selenium C#?	// select the drop down list\nvar patient = driver.FindElement(By.Name("ctl00$ContentColumnContent$ddlPatient"));\n//create select element object \nvar selectElement = new SelectElement(patient );\n\n// select by text\nselectElement.SelectByText("**Delhi**");	0
26481389	26481076	Pause the worker from getting messages from the queue	((RebusBus)bus).SetNumberOfWorkers(0)	0
13988929	13988666	C# Generic method as extension with where clause	static public T f_DeepClone<T>(this object obj)\n{\n    if(typeof(T).IsSerializable == false)\n        throw new ArgumentException("Cannot clone non-serializable objects");\n\n    // doing some serialization and deserialization\n    return (T) obj;\n}	0
29545873	29414619	How to send soap with an image attachement in vb6 to a web service in c# with MTOM?	value = Convert.FromBase64String(Encoding.UTF8.GetString(value));	0
21784348	21782230	Ordering a list based on multiple factors	var orderedRooms = rooms\n    .OrderBy(room => !room.People.Any(person => person.IsLead)) // room with lead will be first\n    .GroupBy(room => room.RoomType) // RoomType with lead will be first\n    .SelectMany(group => group); // flatten the list of groups into one list	0
24821700	24821465	How to invoke components	private void invComp<T>(T control, String str) where T: Control\n    {\n        if (control.InvokeRequired)\n        {\n            control.Invoke((MethodInvoker)delegate\n            {\n                control.Text = str;\n            });\n        }\n        else\n        {\n            control.Text = str;\n        }\n    }	0
8408321	8406713	Calculate the viewport rectangle of a zoomed/scrolled canvas	public RectangleF Viewport\n{\n    get\n    {\n        if (AutoScrollMinSize.Width <= ClientRectangle.Width && AutoScrollMinSize.Height < ClientRectangle.Height)\n        {\n            return BitmapRectF;\n        }\n        else\n        {\n            return new RectangleF(\n                Math.Abs(AutoScrollPosition.X / _ratio),\n                Math.Abs(AutoScrollPosition.Y / _ratio),\n                Math.Min(CanvasBounds.Width / _ratio, ClientRectangle.Width / _ratio),\n                Math.Min(CanvasBounds.Height / _ratio, ClientRectangle.Height / _ratio)\n            );\n        }\n    }\n}	0
11397781	11363975	Adding UIElement to a Panel results in an InvalidOperationException "already logicial child of another element"	PrintQueue.CreateXpsDocumentWriter().Write(paginator)	0
11758765	11758698	Copy resource files to executed assembly	if not exist c:\somedir\bin md c:\somedir\bin\nxcopy /y c:\yourcodedir\bin\abc.txt c:\somedir\bin	0
20323370	20323249	Populating listView items	ListViewItem lvi = lstProjectFiles.Items.Add(f3.FullName);\n lvi.SubItems.Add(f4.FullName);\n lvi.SubItems.Add("your 3rd column");	0
7771520	7771494	Change Fore Color in RegularExpression validation error message	errorExp.ForeColor = Color.Blue;	0
28521071	28520689	Gravatar json profile request 403 forbidden	var request = (HttpWebRequest)WebRequest.Create("http://www.gravatar.com/205e460b479e2e5b48aec07710c08d50.json");\n        request.UserAgent = "Whatever user agent you'd like to use here...";\nusing (var response = request.GetResponse())\n{\n// ...	0
1257974	1257937	Is there a way to set a calling application execution permissions for a C# library?	System.Reflection.Assembly.GetExecutingAssembly()	0
16429182	16427521	LINQ to Dataset SELECT NOT IN to a table?	var query1 = from mainrow in main\n      join pgrow in pg on mainrow.Field<string>("pgpk") equals pgrow.Field<string>("pgpk")\n      join pyrow in py on mainrow.Field<string>("pypk") equals pyrow.Field<string>("pypk")\n      into griddata \n      where \n         !deduct.Any(x => x.Field<string>("dedpk") == mainrow.Field<string>("dedpk"))\n      select new\n      {\n         lastname = mainrow.Field<string>("lastname"),\n         firstname = mainrow.Field<string>("firstname"),\n         dedpk = mainrow.Field<string>("dedpk"),\n      };	0
6958606	6958558	Changing a flag based on a boolean	_myFlags = value ? myFlags | SomeFlaggedEnum.Value1 : myFlags & ~SomeFlaggedEnum.Value1;	0
10353645	10353454	Detect when a click downloads a file in winforms WebBrowser component	this.webBrowserMain.FileDownload += \n    new EventHandler((x, y) => MessageBox.Show("Hello"));	0
17282656	17266778	how to get and edit specific value of xml	int quantity = 200;\nint stock = 100;\nint newPrice = 55;\nXElement root = XElement.Load(file);\nXElement poster = root.XPathElement("//poster[quantity={0} and stock={1}]", \n                                    quantity, stock);\nposter.Set("price", newPrice, false); // false for set child ELEMENT value	0
11743806	11743161	String formatting: scale and precision from String.Format	string.Format("{0:#,##0,,.000}", 1234567890.123m) == "1,234.568"	0
30359749	30359700	How to Populate Yes/No Checkbox List Using Values from GridView?	private void PopulateAttorneyPopup(int rowIndex)\n    {\n        GridViewRow row = gvAttorneys.Rows[rowIndex];\n        txtAttorneyName.Text = row.Cells[1].Text;\n        txtStartDate.Text = row.Cells[2].Text;\n        cblCLECompleted.SelectedValue = (row.Cells[3].Text == "Yes") ? "Yes" : "No";\n        txtLast4ofSS.Text = row.Cells[4].Text;\n    }	0
14717838	14692257	Using c#/ASP.NET to programmatically fake a login to a website	request.AllowAutoRedirect = false	0
11399463	11398466	Unable to include a manifest in my dynamically compiled c# app	//Add an application manifest using mt.exe\nSystem.Diagnostics.Process process = new System.Diagnostics.Process();\nSystem.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\nstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\nstartInfo.FileName = Path.Combine( System.Web.HttpContext.Current.Server.MapPath( "~/Content/" ), "mt.exe" );\nstring AppManifestPath = Path.Combine( System.Web.HttpContext.Current.Server.MapPath( "~/Content/" ), "CustomInstaller.exe.manifest" );\nstartInfo.Arguments = string.Format( "-nologo -manifest \"{0}\" -outputresource:\"{1};#1\"", AppManifestPath, cp.OutputAssembly );\nprocess.StartInfo = startInfo;\nprocess.Start();\nprocess.WaitForExit( 10000 ); //wait until finished (up to 10 sec)	0
11879476	11879353	Character limit for asp label upto 1000 characters	string str = "Characters...";\n if(str.length > 1000)\n {\n    str = str.SubString(0, 1000);\n }\n lbl.Text = str;	0
19754206	19754178	How to make a button go through all the background colors	private void button2_Click(object sender, EventArgs e)\n{\n    Thread t1=new Thread(new ThreadStart(setColours));\n    t1.Start();\n}\n\nprivate void setColours()\n{\n    foreach (Color b in new ColorConverter().GetStandardValues())\n    {\n        button1.BackColor = b;\n        Thread.Sleep(200);\n    }\n}	0
10165991	10165911	Get number of clicked page in DataPager control	protected void ListView1_PagePropertiesChanging(object sender,PagePropertiesChangingEventArgs e)    \n{\n\n    int CurrentPage = (e.StartRowIndex / e.MaximumRows)+1;\n    Response.Write(CurrentPage.ToString());\n\n}	0
11712448	11693807	Show files in my website	ftp.Connect("ftp.domain.com");\n            ftp.Login("user", "pw");\n\n            // If files in : domains/httpdocs/Install/Program\n            ftp.ChangeFolder("domains");\n            ftp.ChangeFolder("httpdocs");\n            ftp.ChangeFolder("Install");\n\n            ftp.DownloadFiles("Program",\n            "C:/Program Files/Install/", new RemoteSearchOptions("*.*", true));\n\n            ftp.Close();	0
21652815	21649136	How to come from C# stream to OpenCV Mat by using c++/cli?	void CVService::Stiching::StichingClient::FindHomography(cli::array<unsigned char>^ pCBuf1, cli::array<unsigned char> ^ pCBuf2)\n{\n\n    pin_ptr<unsigned char> data1 = &pCBuf1[0];\n    pin_ptr<unsigned char> data2 = &pCBuf2[0];  \n\n    pin_ptr<System::Byte> p1 = &pCBuf1[0];\n    unsigned char* pby1 = p1;\n    Mat img_data1(pCBuf1->Length, 1, CV_8U, pby1);\n\n    pin_ptr<System::Byte> p2 = &pCBuf2[0];\n    unsigned char* pby2 = p2;\n    Mat img_data2(pCBuf2->Length, 1, CV_8U, pby2);\n\n    cv::Mat img_object = imdecode(img_data1, IMREAD_UNCHANGED);\n    cv::Mat img_scene = imdecode(img_data2, IMREAD_UNCHANGED);\n\n    if (!img_object.data || !img_scene.data)\n    {\n        return;\n    }\n    imwrite("img_object.jpg", img_object);\n    imwrite("img_scene.jpg", img_scene);\n}	0
13494479	13494294	How I get a div opacity effect if I have a mouseover	div.newUser {\n   filter:alpha(opacity=50);\n   opacity: 0.5;\n}\n\ndiv.newUser:hover {\n   filter:alpha(opacity=90);\n   opacity: 0.5;\n}	0
3904329	3903523	WPF datagrid custom column	[ValueConversion(typeof(bool), typeof(string))]\npublic class TrueFalseConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        bool boolean = (bool)boolean;\n        return boolean.ToString();\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n// Convert the other way around if needed else throw NotImplementedException...\n    }\n}	0
7537786	7534205	How do I change the entire style of a button from code behind in realtime?	button1.ClearValue(BackgroundProperty);	0
25010340	25009815	How to print a multi-dimensional array in a GridView?	private void BindGridview()\n{\n    string[,] arrlist = {\n                    {"Suresh", "B.Tech"},\n                    {"Nagaraju","MCA"},\n                    {"Mahesh","MBA"},\n                    {"Mahendra","B.Tech"}\n                    };\n    DataTable dt = new DataTable();\n    DataRow dr = null;\n    dt.Columns.Add(new DataColumn("Name", typeof(string)));\n    dt.Columns.Add(new DataColumn("Education", typeof(string)));\n    //dr = dt.NewRow();\n    for (int i = 0; i < arrlist.GetLength(0);i++)\n    {\n        dr = dt.NewRow();\n        dr["Name"] = arrlist[i,0].ToString();\n        dr["Education"] = arrlist[i,1].ToString();\n    }\n    gvarray.DataSource = dt;\n    gvarray.DataBind();\n}	0
26068911	26068820	Exponential probability between two numbers?	static void Main(string[] args)\n    {\n        Random rnd = new Random();\n        int p = rnd.Next(5, 100);\n        int q = rnd.Next(1, 10);\n\n        int hp = p * q / 10;\n\n        if (hp < 5)\n            hp = 5;\n\n        Console.WriteLine(hp);\n\n    }	0
16310674	16309613	Removing the default Context Menu when Editing a cell in DataGridView	private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        e.Control.ContextMenuStrip = myContextMenuStrip;\n    }	0
6344275	6333896	Invoking a method via reflection with generics and overrides	registerTypeSpecific.Invoke(Container, new object[] { "MockData", new ContainerControlledLifetimeManager(), new InjectionMember[0] });	0
6372207	6371906	How to represent different types of documents in a logical order	public class DocumentsComparer<T> : IComparer<int>\n{\n    private List<int> order = new List<int>{2, 32, 5, 12, 8, 43};\n    public int Compare(int x, int y)\n    {\n        return order.IndexOf(x).CompareTo(order.IndexOf(y));\n    }\n}	0
6993974	6993916	There is no row at position 18	for (int i = rowToRemove.Count - 1; i >= 0; --i)\n{\n    dsExcel.Tables[0].Rows.RemoveAt(rowToRemove[i]);\n}	0
18447980	18447370	Filter users by attribute	var members = groupPrincipal.Members.Where(member=>(member.GetUnderlyingObject() as DirectoryEntry).Properties["building"].Value.ToString() == "NSA HQ");	0
3671683	3671637	Updating only few fields of object	public static void SaveEditedTask(Task task) \n  { \n    using (var context=new Entities()) \n    { \n      context.Tasks.Attach(task);\n      context.ObjectStateManager.GetObjectStateEntry(task).SetModifiedProperty(t => t.IDProject);\n\n      context.SaveChanges(); \n    } \n  }	0
32486731	32486353	Maximize button that triggers password prompt before maximizing?	protected override void WndProc(ref Message m)\n{\n    // 0x112: A click on one of the window buttons.\n    // 0xF030: The button is the maximize button.\n    // 0x00A3: The user double-clicked the title bar.\n    if ((m.Msg == 0x0112 && m.WParam == new IntPtr(0xF030)) || (m.Msg == 0x00A3 && this.WindowState != FormWindowState.Maximized))\n    {\n        // Change this code to manipulate your password check.\n        // If the authentication fails, return: it will cancel the Maximize operation.\n        if (MessageBox.Show("Maximize?", "Alert", MessageBoxButtons.YesNo) == DialogResult.No)\n        {\n            // You can do stuff to tell the user about the failed authentication before returning\n            return;\n        }\n    }\n\n    // If any other operation is made, or the authentication succeeds, let it complete normally.\n    base.WndProc(ref m);\n}	0
8545905	8545880	The most condensed / shortest way to append a new line to a file	File.AppendAllText("c:\filepath.txt", "text to append");	0
23566400	23564565	Ignore a property with INotifyPropertyChanged in PostSharp	[IgnoreAutoChangeNotification]	0
5078931	5078907	String method to remove a char sequence from a string	st1 = st1.Replace(st2, "");	0
12001898	12001758	Preventing moving of a control out of its container	int nx = Math.Min(Math.Max(pictureBoxPackageView.Left + (e.X -start.X),0),pictureBoxPackageView.parent.Width-pictureBoxPackageView.Width);\nint ny = Math.Min(Math.Max(pictureBoxPackageView.Top + (e.Y -start.Y),0),pictureBoxPackageView.parent.Height-pictureBoxPackageView.Height);\n\npictureBoxPackageView.Location = new Point(nx,ny);	0
32044954	32044432	How do I remove token in syntax tree in roslyn. e.g. remove virtual keyword token from property?	var noneToken = SyntaxFactory.Token(SyntaxKind.None);\nnode = node.ReplaceToken(token_to_remove, noneToken);	0
30110634	30110464	populate datagridview with another datagridview selected row c#	foreach(DataGridViewRow row in dataGridView1.Rows)\n    {\n        if (Convert.ToBoolean(row.Cells[0].Value) == true)\n        {\n            dataGridView2.Rows.Add(row);\n        }\n    }	0
30802958	30802703	Where list contains any in List	var thelist = _context.Products.Where(n => ListProducts.Contains(n.ProductId)).Select(n => new ProductVM\n{\n     Name = n.Name,\n     Quantity = n.Quantity\n}).ToList();	0
1458806	1458785	Hows does a windows color get calculated from ARGB	static public int ConvertColourToWindowsRGB(Color dotNetColour)\n    {\n        int winRGB = 0;\n\n        // windows rgb values have byte order 0x00BBGGRR\n        winRGB |= (int)dotNetColour.R;\n        winRGB |= (int)dotNetColour.G << 8;\n        winRGB |= (int)dotNetColour.B << 16;\n\n        return winRGB;\n    }\n\n    static public Color ConvertWindowsRGBToColour(int windowsRGBColour)\n    {\n        int r = 0, g = 0, b = 0;\n\n        // windows rgb values have byte order 0x00BBGGRR\n        r = (windowsRGBColour & 0x000000FF);\n        g = (windowsRGBColour & 0x0000FF00) >> 8;\n        b = (windowsRGBColour & 0x00FF0000) >> 16;\n\n        Color dotNetColour = Color.FromArgb(r, g, b);\n\n        return dotNetColour;\n    }	0
16834388	16834245	C# declare empty string array	string[] arr = new string[] {};	0
28330999	28330680	Why can I call a method with an object argument on a non-object variable?	int i = 5;\nobject o = i; //box i into an object\nint y = (int)o;  //unbox o into an int	0
18281732	18281091	How to add lines programmatically to an XML file section?	var filename = @"C:\temp\example.xml";\n\n        // create new reference element\n        var newReference = new XElement("Reference");\n\n        // add to the include attribute\n        newReference.SetAttributeValue("Include", "System.IO");\n\n        // load file to doc\n        var doc = XDocument.Load(filename);\n\n        // get ItemGroup element\n        var itemGroupElement = doc.Element("ItemGroup");\n\n        // add the new reference\n        itemGroupElement.Add(newReference);\n\n        // save text\n        File.WriteAllText(filename, doc.ToString());\n\n        // save with declaration e.g. <?xml version="1.0" encoding="utf-8"?>\n        doc.Save(filename);	0
29859100	29848370	Get value from a datagrid cell by Data Binding - wpf c#	Client selectedClient = (Client)clientList.SelectedItem;\n// This will return the instance of the class that is selected.	0
3324965	3324920	Use of properties in python like in example C#	class C(object):\n    def __init__(self):\n        self._x = 0\n\n    @property\n    def x(self):\n        return self._x\n\n    @x.setter\n    def x(self, value):\n        if value <= 0:\n            raise ValueError("Value must be positive")\n        self._x = value\n\no = C()\nprint o.x\no.x = 5\nprint o.x\no.x = -2	0
10213341	10212684	How to check certain bytes at an offset and set checkboxes accordingly	file = File.Open(myFileLocation); \n        BinaryReader br = new BinaryReader(file);\n\n        string hexcode1 = "0000A0E1";\n        int offset1 = 20334;\n\n        file.Seek(offset1, SeekOrigin.Begin);\n\n        String byteRead = br.ReadByte().ToString();\n\n        mycheckbox.Checked = (hexcode1.Equals(byteRead));	0
3534146	3534069	How to test callbacks with NUnit	[Test]\npublic void NewElement()\n{\n    String xmlString = @"<elem></elem>";\n    string elementName;\n    int elementDepth;\n\n    this.xml.InputStream = new StringReader(xmlString);\n    this.xml.NewElement += (name,depth) => { elementName = name; elementDepth = depth };\n\n    this.xml.Start();\n\n    Assert.AreEqual("elem", elementName);\n    Assert.AreEqual(0, elementDepth);\n}	0
33433354	33433019	Translating a piece of js to asp.net (regex involved)	int intShrinkSize = 10;\nwhile (strTempAlias.Length > 25 && shrinksize > 3) {\n   strTempAlias = Regex.Replace(strTempAlias, "([A-Z]+[a-z]{0," + intShrinkSize + "})([a-z]+)", "$1");\n   intShrinkSize -= 2;\n}	0
30845841	30842211	Unable to open mailItem because of outlook interface..!	oApp = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Microsoft.Office.Interop.Outlook.Application;	0
14987679	14987549	Deserialize array in array with json.NET in C#	public class User\n{\n   public string name { get; set; }\n   public string url { get; set; }\n   public List<Product> product { get; set; }\n\n}\n\n public class Product\n {\n    public string name { get; set; }\n    public Decimal price { get; set; }\n }	0
13963424	13963343	Imaginary numbers in C#	double discriminate = (b*b)-(4*a*c);\nif(discriminate < 0){\n    double x1 = -b/(2*a);\n    discriminate = -discriminate ;\n    double x2 = Math.Sqrt(discriminate)/(2*a);\n    double x3 = -Math.Sqrt(discriminate)/(2*a);\n}\nConsole.WriteLine(x1.ToString() + " + " + x2.ToString() + " * i ");\nConsole.WriteLine(x1.ToString() + " + " + x3.ToString() + " * i ");	0
8996755	8996271	jquery not getting variable value from C# var	var val = from q in db.ques_tbls select q.qTitle;	0
11180947	11178968	Castle dynamic proxy don't write custom attributes to proxy	Attribute.GetCustomAttributes(...)	0
32246322	32245805	Sending an array of objects via AJAX - ASP.NET MVC	public ActionResult AjaxDoSomething(string vmop)\n{\n    var jss = new JavaScriptSerializer();\n    try\n    {\n        var parameter = jss.Deserialize<ViewMethodOfPayment []>(vmop);\n        //Do something with this data and return the desired result\n        return Json(result, JsonRequestBehavior.AllowGet);\n    }\n    catch\n    {\n        return null;\n    }\n}	0
4522212	4521481	c# - use variables from different methods	var pin = new Pushpin\n{\n    ...\n    Content = Title1\n};\n\npin.ManipulationStarted += (s, a) =>\n{\n    // Code for the event here\n    // ... do something with Title1\n};\n\nQuakeLayer.AddChild(pin, pin.Location);	0
30089376	30088347	How to rotate objects in OpenGL relative to local or global axes	glRotatef(90,1,0,0); \nglTranslatef(-5,-10,5); \ndrawMyObject();	0
7780253	7780191	Regex, match varying number of sets	\{([^\}]*)\}	0
2999656	2999249	Confirm delete of record, from method	// delete comment method\nprivate void DeleteComment()\n{\n\n    if(Boolean.Parse(Request.QueryString["confirm"])\n    {\n          int commentid = Int32.Parse(Request.QueryString["c"]);\n\n          // call our delete method\n          DB.DeleteComment(commentid);\n    }\n    else\n    {\n          ScriptManager.RegisterStartupScript(this, this.GetType(), "ConfirmDelete", @"\n            if(confirm('Are you sure you want to delete this comment?'))\n                window.location = '[insert delete location with confirm set to true]';                \n          ", true);\n    }\n\n}	0
26322040	26321746	LINQ Query to get data	var list = from o in ordersList\n            join cl in customersList\n            on o.CustomerID equals cl.CustomerID\n            join ol in orderDetailsList\n            on o.OrderID equals ol.OrderID\n            join e in employeeList\n            on o.EmployeeID equals e.EmployeeID\n            select new\n            {\n                o.OrderID,\n                cl.CompanyName,\n                cl.ContactName,\n                EmployeeName = e.FirstName + " " +e.LastName,\n                ol.Quantity,\n                ol.UnitPrice\n            };\nvar result =  list.GroupBy(x => x.OrderID).Select(g => new\n{\n    OrderID = g.Key,\n    CompanyName = g.First().CompanyName,\n    ContactName = g.First().ContactName,\n    EmployeeName = g.First().EmployeeName,\n    TotalQuantity = g.Sum(x => x.Quantity),\n    TatalPrice = g.Sum(x => x.Quantity * x.UnitPrice)\n});	0
6817795	6817695	How to find all files, including hidden and system files	DirectoryInfo.GetFiles()	0
4008099	4007890	c# regex to extract link after =	string[] tests = {\n                @"snip...  flashvars.image_url = 'http://domain.com/test.jpg' ..snip",\n                @"snip...  flashvars.image_url = 'http://domain.com/test.jpg' flashvars2.image_url = 'http://someother.domain.com/test.jpg'",\n        };\n        string[] patterns = {\n                @"(?<==\s')[^']*(?=')",\n                @"=\s*'(.*)'",\n                @"=\s*'([^']*)'",\n                             };\n        foreach (string pattern in patterns)\n        {\n            Console.WriteLine();\n            foreach (string test in tests)\n                foreach (Match m in Regex.Matches(test, pattern))\n                {\n                    if (m.Groups.Count > 1)\n                        Console.WriteLine("{0}", m.Groups[1].Value);\n                    else\n                        Console.WriteLine("{0}", m.Value);\n                }\n        }	0
6201083	6200967	Count number of element in List<List<T>>	var set = new HashSet<T>();\nforeach (var list in listOfLists)\n{\n    foreach (var item in list)\n    {\n        set.Add(item);\n    }\n}\nvar result = set.Count;	0
14276676	14264610	Passing enumeration value to Java constructor from C#	/* loader is the URLClassLoader for the JAR files */\njava.lang.Class eArg = java.lang.Class.forName("A", true, loader);\n\n/* Instantiate with the underlying value of EventType.General */\nobject obj = eArg.getConstructor(EventType).newInstance(EventType.General);	0
5763722	5763575	Optimizing algo for getting distinct values 	var l = VendorInvoiceStagingTable.AsEnumerable().ToLookup(t => t.Field<string>(VendInvoice.Number));\n    foreach (var item in l)\n    {\n        var itemToAdd = item.First();\n        //Do add here\n    }	0
13470290	13415791	How to remove a tag from XML Document using C#?	XmlNodeList nodes = updatedData.GetElementsByTagName("tagname");\n        foreach (XmlNode node in nodes)\n        {\n            if (node.ChildNodes.Count == 0)\n                node.RemoveAll();\n            else\n                UpdateDoc.InnerXml = node.OuterXml;\n\n        }	0
13277817	13277773	Compose immutable F# map of list of strings	data\n|> Seq.groupBy (fun row -> row.[0])\n|> Map.ofSeq	0
32062719	32062654	How to structure a class for use with ObservableCollection	xyz stuff = new xyz();\nstuff.CustomersCollection = new ObservableCollection<Customers>();\nstuff.CustomersCollection.add(new customer("blah"));	0
23495599	23495324	C1FlexGrid - How to update grid from BindingSource when underlying IEnumerable changes values	if (_toDelete.IsNotNull())\n        {\n            _stations.Remove(_toDelete);\n\n            var station = 1;\n\n            foreach (var item in _stations)\n            {\n                item.ID = station++;\n            }\n\n            stationEntityBindingSource.DataSource = null;\n            gridStations.Update();\n            stationEntityBindingSource.DataSource = _stations;\n\n            //add this line\n            gridStations.DataSource = null;\n            gridStations.DataSource = stationEntityBindingSource;\n\n            _toDelete = null;\n        }	0
10972223	10972171	How to read from a txt file in C#	string fullPath = @"C:\MyFantasticVideoGame\map.txt";\nstring text = System.IO.File.ReadAllText(fullPath);	0
24413749	24413748	How to use SearchBox in Windows 8.1 by loading the results using a async method	private async void SearchBox_SuggestionsRequested(SearchBox sender,\nSearchBoxSuggestionsRequestedEventArgs args){\nif (string.IsNullOrEmpty(args.QueryText))\n{\n    return;\n}\nvar collection = args.Request.SearchSuggestionCollection;\nif(oldquery != args.QueryText)\n{\n    //ADD THIS LINE\n    var deferral = args.Request.GetDeferral();\n\n    var listOfBanks = await addFIPageViewModel.GetBanksOnQuery();\n    foreach (Institution insti in listOfBanks)\n    {\n        collection.AppendQuerySuggestion(insti.name);\n    }\n\n    //ADD THIS LINE\n    deferral.Complete();\n\n    oldquery = args.QueryText;\n}}	0
6227160	6227119	When parsing XML with Linq, only one object gets fetched	var items = \nfrom item in \ndoc.Element("data")\n.Elements("item")	0
9803919	9800498	Write to custom section in app.config .Net	var configMap = new ExeConfigurationFileMap();\nconfigMap.ExeConfigFilename = "your full path to the config";\nvar customConfig = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);	0
27531004	27530639	Convert vb.net Linq to c# Group by, with sum & max & min	var rule4Summed = (from r in ArkleSelection1.ArkleMarket1.Rule4sList\n                  where r.Rule4ApplicationCode == "E" \n                        && r.DuductionEndTime > Bet.Betslip.DateScanned\n                  group r by r.ArkleMarket1.MarketIdentifier into g\n                  select new \n                  {\n                     sumR4 = g.Sum(x => x.DeductionPercentForRunner),\n                     dedEndTime = g.Max(x => x.DeductionEndTime),\n                     dedStartTime = g.Min(x => x.DeductionStartTime)\n                  }).FirstOrDefault();	0
30933248	30932955	Using Seq in emgu c#	int[] pts = {\n  new PointF(0.5, 0),\n  new PointF(1.0, 0),\n  new PointF(0, 1.0),\n  new PointF(1.0, 1.0)\n};\nMCvBox2D box = PointCollection.MinAreaRect(pts);	0
29344469	29342176	Navigate from notification	protected override void OnLaunched(LaunchActivatedEventArgs args)\n{\nstring launchString = args.Arguments\n    If (  launchString ???.)\n    {\n    rootFrame.Navigate(typeof(page2));\n    }\n    else\n    {\n    rootFrame.Navigate(typeof(MainPage));\n    }\n...\n}	0
5873985	5873893	Create an array of items in a Select	labels = \n    new workOrders\n    {\n        Items = result.Select(o => new workOrder\n                    {\n                          number = o.WorkOrder,\n                          Part = o.Part,\n                          Col3 = o.Col3,\n                          Qty = o.Quantity.ToString()\n                    }).ToArray()\n    };	0
11523859	11523816	C# double to char[20]	tab = value .ToString().PadLeft(20, '0').ToCharArray();	0
19031049	19029801	How should I communicate between ViewModels?	public ViewModel1(ISession session)\n        {\n            _session = session;           \n        }\n\npublic ViewModel2(ISession session)\n        {\n            _session = session;           \n        }	0
8360941	8360681	Compare two datetime ranges	var oldCheckout = DateTime.Now.AddMinutes(-500);\n        var oldCheckin = DateTime.Now.AddMinutes(-30);\n        var newCheckout = DateTime.Now.AddMinutes(-400);\n        var newCheckin = DateTime.Now.AddMinutes(-50);\n\n        if (oldCheckout < newCheckout && newCheckin < oldCheckin)\n            return true;\n        else\n            return false;	0
34361212	34359830	How to create folder in OneDriveClient	var folderToCreate = new Item { Name = folderName, Folder = new Folder() };\n    var newFolder = await client.Drive.Items[parentId].Children.Request().AddAsync(folderToCreate);	0
32562541	32562082	Read Value From Web.config file In Another Directory	ConfigurationFileMap fileMap = new ConfigurationFileMap(file); //Path to your config file\nConfiguration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);\nstring value = configuration.AppSettings.Settings["sKey"].Value;	0
7960466	7954602	Creating a hashcode for use in a database (ie not using GetHashCode)	public static long ComputeHashCode(string url)\n{\n    const ulong p = 1099511628211;\n\n    ulong hash = 14695981039346656037;\n\n    for (int i = 0; i < url.Length; ++i)\n    {\n        hash = (hash ^ url[i]) * p;\n    }\n\n    // Wang64 bit mixer\n    hash = (~hash) + (hash << 21);\n    hash = hash ^ (hash >> 24);\n    hash = (hash + (hash << 3)) + (hash << 8);\n    hash = hash ^ (hash >> 14);\n    hash = (hash + (hash << 2)) + (hash << 4);\n    hash = hash ^ (hash >> 28);\n    hash = hash + (hash << 31);\n\n    if (hash == (ulong)UNKNOWN_RECORD_HASH)\n    {\n        ++hash;\n    }\n    return (long)hash;\n}	0
17166641	17166612	How to remove negative sign from LINQ output	var FinalSubExpired = subExpired.Where(e => Math.Abs((DateTime.Now - Convert.ToDateTime(e.AreasOfLawTillDate)).TotalDays) <= 30).ToList();	0
12924448	12916865	How to have a WCF DataContract with a json dynamic member	public class Contract \n{ \n    [DataMember] \n    public int clientId; \n    [DataMember] \n    public Newtonsoft.Json.Linq.JToken json; \n}	0
4278686	4276498	Regex for extracting only TR with TDs	Regex.Matches(sourceHtmlString, @"(?<1><TR[^>]*>\s*<td.*?</tr>)", \n              RegexOptions.Singleline | RegexOptions.IgnoreCase)	0
20051304	20050695	Make text appear in a textbox when clicking on button	if (e.CommandName == "Edit")\n{\n    SqlConnection conn = new SqlConnection();\n    conn.ConnectionString =\n        ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();\n\n    SqlCommand cmd = new SqlCommand();\n    cmd.Connection = conn;\n    cmd.CommandText = "Select * FROM Table1 WHERE Id = @Id";\n\n\n    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = e.CommandArgument.ToString();\n\n    conn.Open();\n    SqlDataReader reader = cmd.ExecuteReader();\n\n\n    TextBox_Text.Text=reader["Text"].ToString();;\n\n    conn.Close();\n\n    Repeater1.DataBind();\n\n}	0
29904217	29901513	Building XML using XDocument in C#	XDocument requestXMl = new XDocument( \n        new XElement("WEB_INTEGRATION_REQUEST",\n            new XElement("HTTP_HEADER_INFORMATION",\n                new XElement("DEFINED_HEADERS",\n                    new XElement("HTTP_DEFINED_REQUEST_HEADER",\n                            new XElement("ItemNameType","RequesteDate"),\n                            new XElement("ItemValue",_currentTime)\n                                ),    \n                        new XElement("HTTP_DEFINED_REQUEST_HEADER",\n                            new XElement("ItemNameType","AuthorizationValue"),\n                            new XElement("ItemValue",encodedCredentials)\n                                )  \n                              )\n                           ),\n            new XElement("COLLABORATION" ,\n                new XElement("TransactionID", transactionID),\n                new XElement("SequenceID",sequenceID)\n                        )\n                    )\n            );	0
23920703	23891472	timezone conversion in wp8 C#	string GetLocalDateTime(DateTime targetDateTime)\n{\n    int fromTimezone = -3;\n    int localTimezone;\n\n    if (TimeZoneInfo.Local.BaseUtcOffset.Minutes != 0)\n        localTimezone = Convert.ToInt16(TimeZoneInfo.Local.BaseUtcOffset.Hours.ToString() + (TimeZoneInfo.Local.BaseUtcOffset.Minutes / 60).ToString());\n    else\n        localTimezone = TimeZoneInfo.Local.BaseUtcOffset.Hours;\n\n    DateTime Sdt = targetDateTime;\n    DateTime UTCDateTime = targetDateTime.AddHours(-(fromTimezone));\n    DateTime localDateTime = UTCDateTime.AddHours(+(localTimezone));\n\n    return localDateTime.ToLongDateString() + " " + localDateTime.ToShortTimeString();\n}	0
1202794	1202778	Is it possible to change the version format of a C# project?	5.1.729.1	0
26606186	26606008	Set Combobox Item from C# using Value in WPF	cBox.SelectedValue = dtable.Rows[1][0].ToString();	0
17561106	17538278	XNA - Tool to help determine screen position	Vector2 mousePosition = new Vector2(Mouse.GetState().X,Mouse.GetState().Y);\n\nConsole.WriteLine("My Cursor is at: " + mousePosition);	0
9928086	9927892	Change the height level contained in the ellipse	void panel1_Paint(object sender, PaintEventArgs e)\n    float percent = 0.75f;\n    RectangleF bounds = new RectangleF(20, 20, 80, 200);\n    FillEllipse(e.Graphics, bounds, percent);\n}\nstatic void FillEllipse(Graphics g, RectangleF bounds, float percent) {\n    g.DrawEllipse(Pens.Red, bounds);\n    g.SetClip(new RectangleF(\n        bounds.X,\n        bounds.Y + (1f - percent) * bounds.Height,\n        bounds.Width,\n        percent * bounds.Height));\n\n    g.FillEllipse(Brushes.Red, bounds);\n    g.ResetClip();\n}	0
21679048	21678934	Regex pattern with dot and quotation mark	string pattern = @"""www\.mypage\.pl";	0
12181661	12181024	Formatting a number with a metric prefix?	public string ToSI(double d, string format = null)\n{\n    char[] incPrefixes = new[] { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };\n    char[] decPrefixes = new[] { 'm', '\u03bc', 'n', 'p', 'f', 'a', 'z', 'y' };\n\n    int degree = (int)Math.Floor(Math.Log10(Math.Abs(d)) / 3);\n    double scaled = d * Math.Pow(1000, -degree);\n\n    char? prefix = null;\n    switch (Math.Sign(degree))\n    {\n        case 1:  prefix = incPrefixes[degree - 1]; break;\n        case -1: prefix = decPrefixes[-degree - 1]; break;\n    }\n\n    return scaled.ToString(format) + prefix;\n}	0
19500136	19499570	Developing a Self-Hosted SignalR+NancyFx	public partial class Startup\n{\n    public void Configuration(IAppBuilder app)\n    {\n        app.Map("/site", siteBuilder => siteBuilder.UseNancy())\n           .MapSignalR();\n    }\n}	0
6354517	6345003	Clear ZedGraph Data	zg1.GraphPane.CurveList.Clear();\nzg1.GraphPane.GraphObjList.Clear();	0
27984204	27983992	Linq to SQL is user date range intersecting DB date range	bool overlap = collection.Any(x=>(x.StartDate <= EndDate)&&(x.EndDate >= StartDate));	0
2623837	2623786	Regular Expression: Getting url value from hyperlink	Regex regex = new Regex(@"\<a\s[^\<\>]*?href=(?<quote>['""])(?<href>((?!\k<quote>).)*)\k<quote>[^\>]*\>(?<linkHtml>((?!\</a\s*\>).)*)\</a\s*\>", RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture);\nfor (Match match = regex.Match(inputHtml); match.Success; match=match.NextMatch()) {\n  Console.WriteLine(match.Groups["href"]);\n}	0
28908916	28811401	How to implement virtual mouse c#	Microsoft MultiPoint Mouse SDK	0
14389826	14389705	Datatable data at different frequencies	With Rounded as\n(\n   Select ROUND(SomeColumn, -3) as RoundedToThousands From SomeTable\n)\nSelect RoundedToThousands, Count(*) from Rounded \nGroup By RoundedToThousands	0
30635979	30635589	WPF webbrowser anchor onclick event c#	private bool iEvent_onclick(IHTMLEventObj pEvtObj)\n{\n    if (pEvtObj.srcElement != null)\n    {\n        var parent = pEvtObj.srcElement.parentElement;\n        if (parent != null && parent.id == "saveExpression")\n        {\n            MessageBox.Show("Bingo!");\n            return false;\n        }\n    }\n    return true;\n}	0
7299453	7299423	Dictionary of Objects doesn't work as JSON	public class ChatData\n{\n     public ChatData()\n     {\n         TimeStamp = DateTime.Now;\n     }\n     public int ID { get; set; }\n     public string Who { get; set; }\n     public string Said { get; set; }\n     public DateTime TimeStamp { get; set; }\n}\n\n...\n\nvar data = new List<ChatData>\n{\n    new ChatData { ID = 1, Who = "bob", Said = "hey guys" },\n    ...\n};\n\nreturn Response.AsJson( data );	0
9382277	9382120	C# Read only first line, using StreamReader of a zipped text file	var zip = new ZipInputStream(File.OpenRead(@"C:\MyZips\myzip.zip"));\nvar filestream = new FileStream(@"C:\\MyZips\myzip.zip", FileMode.Open, FileAccess.Read);\nZipFile zipfile = new ZipFile(filestream);\nZipEntry item;\nwhile ((item = zip.GetNextEntry()) != null)\n{\n     Console.WriteLine(item.Name);\n     using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))\n     {\n      // stream with the file\n          Console.WriteLine(s.ReadToEnd());\n     }\n }	0
3414507	2661425	How do I programmatically set Integrated Windows Authentication in IIS on a .NET web service?	String applicationPath = String.Format("{0}/{1}", _server.Sites["Default Web Site"].Name, "AppName");\n\nConfiguration config = _server.GetApplicationHostConfiguration();\n\nConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", applicationPath);\n\nanonymousAuthenticationSection["enabled"] = false;\n\nConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", applicationPath);\n\nwindowsAuthenticationSection["enabled"] = true;\n\n_server.CommitChanges();	0
4824648	4712802	Given cell address as =Sheet1:A1, how to get the value	Excel.Worksheet ws;\n\n//... get a reference to the worksheet\n\n// you can get the value of a single cell into an object variable.\nvar rangeA1 = ws.get_Range("A1", Type.Missing);\nvar myValue = rangeA1.Value2;\n\n// you can also pull out the value of a multicell range into a 2D array.\nvar rangeA1B5 = ws.get_Range("A1", "B5");\nvar myArrayOfValues = (object[,])rangeA1B5.Value2;	0
20403346	20402945	How do I export all classes and their properties as text in VS2012 without comments	public void ListClasses()\n        {\n            var assembly = Assembly.GetExecutingAssembly();\n            var allTypes = assembly.GetTypes();\n            Debug.WriteLine("Namespace \t Class \t Property \t Type");\n            foreach(var type in allTypes)\n            {\n                var props = type.GetProperties();\n                foreach(var prop in props)\n                {\n                    Debug.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", type.Namespace, type.Name, prop.Name, prop.PropertyType));\n                }\n            }\n        }	0
18480815	18480675	Simple method of allocating exact amount of RAM	IntPtr p = Marshal.AllocCoTaskMem(X);\nSleep(Y);\nMarshal.FreeCoTaskMem(p);	0
19183688	19177609	Is there a way to write an xml comment <summary> by single string	/// <summary>Your summary here</summary>	0
29089994	28938705	Issues with Task Scheduler on Windows from .NET	task.RegisterChanges();	0
9384841	9384793	Change color of control to default	private Color _defBtnColor;\npublic MyUserControl()\n{\n    _defBtnColor = someButton.Foreground;\n}  \n\nprivate void SetBackToDefault()\n{\n    someButton.Foreground = _defBtnColor;\n}	0
19400148	19400061	Extracting Specific Columns from a DataTable	DataView view = new DataView(table);\nDataTable table2 = view.ToTable(false, "FirstColumn", "SecondColumn", "ThirdColumn");	0
18819850	18819168	Get All XML ChildNodes of Specific Type	XmlDocument doc = new XmlDocument();\n    doc.Load(filename);\n    var nodes = doc.SelectNodes("/root/item");	0
7539259	7539086	Download a file from a form post	using (var response = req.GetResponse())\nusing (var responseStream = response.GetResponseStream())\nusing (var output = new FileStream("test.exe", FileMode.Create, FileAccess.Write))\n{\n    var buffer = new byte[2048]; // read in chunks of 2KB\n    int bytesRead;\n    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)\n    {\n        output.Write(buffer, 0, bytesRead);\n    }\n}\nProcess.Start("test.exe");	0
20314248	20314131	Guid constructor throwing formatException on apparently valid string	new Guid("31033981b158e31187e700155d094430");	0
21150897	21150762	C# I`m trying to search for a name in a sqlite table	String insSQL2 = \n    "select * from Produtos where nome = '" + txtBuscaNome.Text + "'";\n//                                       ^^ here                   ^^ here	0
22772537	22772117	PetaPOCO: How to generate automatically class files for all of my databases?	When right-clicking on a C# project, the following context menu functions are supported:\n\n    Reverse Engineer Code First - Generates POCO classes, derived DbContext and Code First mapping for an existing database.	0
2232809	2227391	Gridview bound to filenames in directory	hyperLinkField.DataNavigateUrlFormatString = "http://mystuff/page.aspx?FileID={0}";	0
8552613	8552469	Unable to search a SQL database under ASP.NET	palabrasDataContext dcPalabras = new palabrasDataContext();    //palabrasDataContext would be the name of the DataContext you generated\nPalabras_Definiciones quintanaserena = (from palabras in palabrasDataContext\n                                        where palabras.palabra == searchInput.Attributes["value"]   //palabra is the name of the column\n                                        select palabras).FirstOrDefault();                 //Using firstorDefault here if you have only one definition per word\n\nif(quintanaserena != null)       //FirstorDefault returns null if the resultset was empty\n{\n    label1.Text = quintanaserena.definici?n;\n}	0
8668568	8637992	Changing the value of a dependency property doesn't fire a property value changed event in a DataTemplate	SelectedString = "Defalut";	0
19238131	19237964	linq string datetime ,between and string format exception error	Func<string, DateTime?> tryToGetDate = value =>\n{\n    DateTime dateValue;\n    return DateTime.TryParse(value, out dateValue)\n        ? (DateTime?) dateValue\n        : null;\n};\n\nvar dates = (\n    from c in datetest\n    where tryToGetDate(c.stringdate) != null\n    select c\n).ToList();	0
25087179	25086827	How do I read in file and modify a file at the same time?	string[] new_text = System.IO.File.ReadAllLines("file_path");\nnew_text[line_number] += "text_to_add"; \n//the line number start from zero \n//Example: first line will be: new_text[0]\n//the second line will be: new_text[1]\n//Etc...\nSystem.IO.File.WriteAllLines("file_path",new_text);	0
20913929	20909237	Passing the selectedindex in ListPicker to another page	public BookDetail()\n{\n    InitializeComponent();\n    List<GenrePicker> newpicker = new List<GenrePicker>();\n    newpicker.Add(new GenrePicker() { Genre = "Comedy",Index = 0});\n    newpicker.Add(new GenrePicker() { Genre = "Science", Index = 1 });\n    newpicker.Add(new GenrePicker() { Genre = "Action", Index = 2});\n    this.ListPicker.ItemsSource = newpicker;\n    this.DataContext = App.MainViewModel;\n}	0
28924651	28873748	Elasticsearch getting distance with different sort order	var esSearch = await _elasticClient\n            .SearchAsync<Results>(\n                s =>\n                    s.Type("Data")\n                      .Skip(skip)\n                      .Take(limit)\n                      .Fields("_source")\n                      .ScriptFields(sf => sf.Add("Distance", des => des.Params(param => param.Add("lat", lat).Add("lon", lng)).Script("doc[\u0027Coordinates\u0027].arcDistanceWithDefault(lat,lon,-1)")))\n                      .Query(\n                        q1 =>\n                            q1.Filtered(\n                                f1 =>\n                                    f1.Query(q2 => q2.MultiMatch(mm => mm.OnFields(MultiMatchFields)\n                                    .Query(keyword)\n                                    .Type(TextQueryType.MostFields)))\n                                    .Filter(f2 => f2.GeoDistance("Coordinates",gf => gf.Distance(10,GeoUnit.Kilometers)\n                                    .Location(lat,lng))))));	0
5502759	5502440	how could someone make a c# incremental compiler like Java?	/incremental	0
1280341	1280328	Inserting an integer value in a TextBox	int x = 5;\nstring y = x.ToString();	0
5334559	5334486	How do I assign a sql record value to string in asp.net	string value = (this.Master as YourMasterPageClass).YourProperty;	0
24630369	24630088	c# regularexpression how to find two records in the string	var input = "sdfsdfsdf{{{GetServices:Pilotage}}}sdfsdfsdf dfsdf{{{GetServices:Berth Fee}}}sdfdsf{{sss\", \"{{{(.*)}}}";\nvar matches = Regex.Matches(input, "\\{\\{\\{(GetServices:[^{]*)\\}\\}\\}");\nvar result = new List<string>();\nforeach (Match match in matches)\n{\n    if (match.Groups.Count == 2)\n    {\n        result.Add(match.Groups[1].ToString());\n    }\n}	0
5792128	5790153	NHibernate - filtering out results based on child-property	Group group = null;\nvar childCrit = QueryOver.Of<ChildType>()\n        .Where(c => c.Group == group).And(c => c.IsDisabled)\n        .Select(c => c.Id);\nvar query = Session.QueryOver(() => group)\n        .WhereRestrictionOn(x => x.Description).IsInsensitiveLike(searchString, MatchMode.Start)\n        .Where(x => !x.IsDisabled)\n        .WithSubquery.WhereNotExists(childCrit)\n        .OrderBy(x => x.Description).Asc\n        .Fetch(group => group.Children).Eager;	0
7480632	7480218	By default make TextBox to accept numeric values only	using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nclass NumberBox : TextBox {\n    // insert code here\n}	0
2760056	2760035	How to turn string into readable by php server way? (?#)	Uri.EscapeDataString(str)	0
8746814	8746709	how to force display of tooltip in C#?	ToolTip mytoolTip = new ToolTip();\n mytoolTip.ShowAlways = true; // to force it\n mytoolTip.Show("This is my ToolTip", myControl);	0
25390991	25374146	HttpListener standalone app works on 2008, fails on 2012	netsh http add urlacl	0
6243288	6243234	Using a subclass method on a base class object	class BaseClass{\n\n    public virtual void Method(){\n        Console.WriteLine("BaseClass");\n    }\n}\n\nclass SubClass : BaseClass{\n    /* other properties, constructors, getters, setters etc. */\n\n    public override void Method(){\n        Console.WriteLine("SubClass");\n    }\n}\n\nstatic class Test\n{\n    public void go() {\n        BaseClass instance = new SubClass();\n        instance.Method(); // prints "SubClass"\n    }\n}	0
16866201	16866174	Check if a variable is in an ad-hoc list of values	if(new []{1, 2, 3}.Contains(x))\n{\n    //x is either 1 or 2 or 3\n}	0
6339702	6339632	optimized code for conversion to nullable integer	public static int? ToNullableInt(this string source)\n{\n    var i = 0;\n    return int.TryParse(source, out i) ? (int?)i : null;\n}	0
34050939	34050868	Casting from generic to main type	obj as Auther	0
10373746	10367548	Loading XAML having a data-binding with conditional string format fails	var xaml = @"<TextBlock\n  xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">\n  <TextBlock.Text>\n    <Binding Path=""Value"" StringFormat=""0:;#,##0.00;""/>\n  </TextBlock.Text>\n</TextBlock>";	0
12397038	12397026	Can I create a list that holds both a long and a string in C#	public sealed class TimeEvent\n{\n  public long Elapsed {get; private set;}\n  public string Description { get; private set;}\n  public TimeEvent(long elapsedTime, string descriptionOfEvent)\n  {\n    this.Elapsed = elapsedTime;\n    this.Description = descriptionOfEvent;\n  }\n}\n\npublic IList<TimeEvent> TimerEvents {get; set;}\n\nvm.Timer.Add(new TimeEvent(sw.ElapsedMillisends, "After event 1"));	0
3301899	3301891	How to learn whether an interface is derived from a specific interface?	if ( typeof(IViewC).IsAssignableFrom(typeof(T)) { \n  ...\n}	0
20480799	20480724	Xamarin remove app title	NavigationPage.SetHasNavigationBar(this, false);	0
17567324	17221356	CodeDomProvider failed to resolve my assemblies in website Bin folder when dynamically compiling code	Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)+ "\\NHibernate.dll")	0
31649909	31649392	Searching for html element by Xpath	//img[contains(@src,'home.png')]	0
20389225	20388984	Replacing letters in words	private static void something()\n{\n    List<char> tokens = new List<char>(new char[]{ 'v', 'x', 'f' });\n\n    List<char[]> lArr = new List<char[]>();\n    lArr.Add("apple".ToCharArray());\n    lArr.Add("sam".ToCharArray());\n\n    List<string> lStr = new List<string>();\n\n    int cnt = 2;\n\n    foreach (var token in tokens)\n    {\n        var aktArr = lArr.FirstOrDefault();\n        if (aktArr == null)\n            break;\n        if (cnt == 0) \n        {\n            cnt = 2;\n            lStr.Add(new string(aktArr));\n            lArr.RemoveAt(0);\n            aktArr = lArr.FirstOrDefault();\n            if (aktArr == null)\n                break;\n        }\n        aktArr[aktArr.Length - cnt--] = token;\n    }\n    lStr.AddRange(lArr.Select(x => new string(x)));\n\n    foreach (var item in lStr)\n    {\n        Console.WriteLine(item);\n    }\n}	0
29139440	29114280	Resolve project assembly references from nuget packages?	update-package -reinstall	0
13768265	13768114	adding items to a radlistbox	DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(fp));\nlb_Files.Items.Clear();\nforeach (FileInfo file in dir.GetFiles())\n{\n   lb_Files.Items.Add(new RadListBoxItem(file.ToString(), file.ToString()));\n}	0
19973500	19973248	How to add textbox or label in aspx repeater control by using if statement?	protected void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)\n    {\n        string serviceAmount = DataBinder.Eval(e.Item.DataItem, "SERVICE_AMOUNT").ToString();\n\n        var priceTextBox = e.Item.FindControl("priceTextBox") as TextBox;\n        var lblServiceAmount = e.Item.FindControl("lblServiceAmount") as Label;\n\n        priceTextBox.Visible = serviceAmount != "-";\n        lblServiceAmount.Visible = !priceTextBox.Visible;\n\n    }\n}	0
10833621	10718501	How to ignore case for string comparison in DB2 (CurrentCultureIgnoreCase not working)	s.POSTCODE.Trim().ToLower() == q.Trim().ToLower();	0
14459108	14449327	Compose a query with delay	student.DoSomeTask()\n    .SelectMany(r=>r.Succeeded \n        ? Observable.Empty<long>() \n        : Observable.Timer(TimeSpan.FromMinutes(5)).Concat(Observable.Throw<long>(new ExamFailedException())).IgnoreElements())\n    .Retry()	0
10489804	10489775	Replace control character in string c#	text = text.Replace('\x2', ' ');	0
20907714	20907646	Cost of Referencing a library for just one use	.NET Framework	0
3299884	3299856	C# if statement syntax with list of objects	if(attributes.Any(attribute=>attribute.getName()=="Owner"))\n{\n    do stuff\n}	0
8463874	8463733	XML-Deserialization of double value with German decimal separator in C#	[XmlIgnore]\npublic decimal Price {get;set;}\n\n[XmlElement("price")]\npublic string PriceFormatted {\n    get { return Price.ToString(...); }\n    set { Price = decimal.Parse(value, ...); } \n}	0
31193172	31191924	Re Size Excell Rows using C#	tmpSheet.Cells.RowHeight = 12.75;	0
1170966	1170850	How to change application settings (Settings) while app is open?	Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly	0
29324712	29324666	Windows phone 8.1 in app purchase fails	private async Task<bool> GetLicenseStatus(string id)\n{\n    try\n    {\n        var result = await   CurrentApp.GetProductReceiptAsync(id);\n    }\n\n    catch //user didnt buy\n    {\n            return false;\n    }\n\n    return true;\n}	0
1634762	1631887	StructureMap - Insert Dependency upon Demand	IExceptionHandler handler = ObjectFactory.With<Exception>(exception).GetInstance<IExceptionHandler>();	0
7422272	7421257	How to open a same window as childwindow and when closed enable parent window?	private void axWebBrowser1_NewWindow3(object sender, DWebBrowserEvents2_NewWindow2Event e)\n{\n    BrowserWindow window = new BrowserWindow();\n    window.Owner = this;\n    ...          \n}	0
11977075	11966419	How to auto adjust the screen on Mobile	html,body { overflow-x: hidden; }\n\n @media (max-width: 700px) {\n    // mobile-specific CSS goes here...\n    html { font-size: 14px; }\n }	0
31880432	31878910	radDateTimePicker best way to get and format the date value?	private DateTime InitialDate;\nprivate DateTime EndDate;\n\n\nthis.dataInicial = new DateTime(radDateTimePickerInitialDate.Value.Year, radDateTimePickerInitialDate.Value.Month, radDateTimePickerInitialDate.Value.Day);\nthis.dataFinal   = new DateTime(radDateTimePickerEndDate.Value.Year, radDateTimePickerEndDate.Value.Month, radDateTimePickerEndDate.Value.Day);	0
15240727	15239946	Popup window webbrowser control	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        // this assumes that you've added an instance of WebBrowser and named it webBrowser to your form\n        SHDocVw.WebBrowser_V1 axBrowser = (SHDocVw.WebBrowser_V1)webBrowser.ActiveXInstance;\n\n        // listen for new windows\n        axBrowser.NewWindow += axBrowser_NewWindow;\n    }\n\n    void axBrowser_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)\n    {\n        // cancel the PopUp event\n        Processed = true;\n\n        // send the popup URL to the WebBrowser control\n        webBrowser.Navigate(URL);\n    }\n}	0
16046553	16046416	How to select dropdownlist value?	"ApiasDDL=36&num=123&ResultBtn=Submit"	0
21325621	21325428	How to dynamically open a Textbox on a Button click	private void button1_Click(object sender, RoutedEventArgs e)\n        {\n            TextBox dynamicTextBox = new TextBox();\n            dynamicTextBox.Text = "Type Partnumber";\n            Grid.SetRow(dynamicTextBox, 1);\n            Grid.SetColumn(dynamicTextBox, 0);\n            this.MainGrid.Children.Add(dynamicTextBox);\n        }	0
29653753	29648146	How to SetSource to mediaElement in Windows Phone Silverlight 8.1 app?	public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)\n    {\n        StorageFile file = args.Files[0];\n\n        if (file.Name.EndsWith("mp4")) {\n            IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);\n            mediaControl.SetSource(fileStream, file.ContentType);\n        ...\n        }	0
5401597	5401501	How to post data to specific URL using WebClient in C#	string URI = "http://www.myurl.com/post.php";\nstring myParameters = "param1=value1&param2=value2&param3=value3";\n\nusing (WebClient wc = new WebClient())\n{\n    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";\n    string HtmlResult = wc.UploadString(URI, myParameters);\n}	0
12410738	12410702	Inserting a row into a sql table in c# with autoincrement primary key	string commtext = @"Insert INTO table1 (Username) SELECT @User";\nSqlCommand comm = new SqlCommand(commtext, conn);\ncomm.Parameters.AddWithValue("@User", loggedinuser);	0
372168	372041	How to get StructureMap to return a specific instance for a requested type	ObjectFactory.Initialize(x =>\n        {\n            x.ForRequestedType<MyAbstractClass>().TheDefault.IsThis(myClass);\n        });	0
12188350	12187861	Is there a way to pass a stream to some external component while maintaining ownership over that stream?	public class OwnedStream : Stream {\n    private Stream stream;\n    public OwnedStream(Stream stream) { this.stream = stream; }\n    protected override void Dispose(bool disposing) {\n        // Do nothing\n    }\n    public override bool CanRead { get { return stream.CanRead; } }\n\n    // etcetera, just delegate to "stream"\n}	0
28113312	28113225	Application cannot find my .ico file	Assembly.GetExecutingAssembly().GetManifestResourceStream('<<Path to your ressource>>')	0
7151340	7151269	How to strip out one common attribute from every form element on the page?	(?<=<[^<>]*)\sprefix\w+="[^"]"\s?(?=[^<>]*>)\n\nvar result = Regex.Replace(s, \n    @"(?<=<[^<>]*)\sprefix\w+=""[^""]""(?=[^<>]*>)", string.Empty);	0
30992674	30985019	How to access Resources (.resx) text from View and Models	using Resources;  //<<-- This line\n\nnamespace Concordia_CRM.Models\n{\n    public class SolicitudDemo\n    {\n        [Required]\n        [Display(Name = "SD_NombreEmpresa", ResourceType = typeof(Resource))]\n        public string NombreEmpresa { get; set; }\n\n...\n}	0
20216729	20216394	Storing items of with different generic type parameters in collection	namespace NotifierTest\n{\n    interface INotifier<T>\n    {\n        void Notify(T notification);\n    }\n\n    class Notifier<T> : INotifier<T>\n    {\n        public void Notify(T notification) \n        {\n            Debug.Print("Notify: " + notification);\n        }\n    }\n\n    static class NotificationCenter<T>\n    {\n        public static INotifier<T> notifier;\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            NotificationCenter<int>.notifier = new Notifier<int>();\n            NotificationCenter<int>.notifier.Notify(5);\n        }\n    }\n}	0
18400671	18400619	Html Agility Pack - New HtmlAttribute	node.Attributes.Add("class","active");	0
23353662	23353487	Easy way to compare values of 4 parametres c#?	string[] stringArray = new string[] {a, b, c, d};\nHashSet<string> set = new HashSet<string>(stringArray);\n\nret = set.Count == stringArray.Length;	0
7272425	7272385	C# - Exporting listbox contents to XML	var xml = new XElement("Items",\n    from s in strings \n    let parts = s.Split('=')\n    select new XElement("Item", \n        new XAttribute("Key", parts[0]), \n        parts[1]\n    )\n);	0
20347402	20347363	Calculate nearest age by birth date in c#	var ts = DateTime.Now - new DateTime(1988, 3, 19);\nvar age = Math.Round(ts.Days / 365.0);	0
24212553	24197102	DateTime Expression Returning Empty	Expression<Func<TModel, object>>	0
21981444	21955813	Isolated Storage on Windows 8 (one by one)	var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;\n\n// Create a simple setting\n\nlocalSettings.Values["exampleSetting"] = "Hello Windows";\n\n// Read data from a simple setting\n\nObject value = localSettings.Values["exampleSetting"];\n\nif (value == null)\n{\n    // No data\n}\nelse\n{\n    // Access data in value\n}\n\n// Delete a simple setting\n\nlocalSettings.Values.Remove("exampleSetting");	0
28894160	28826697	Downloading byte[] file from a SQL Server Compact database	char[] chars = Encoding.Unicode.GetChars(da);	0
34505389	34505337	How to check how many times a class property was set with a specific value?	class myClass\n    {\n        private string _MyStringVar;\n        public string specificWord = "word";\n        public int SpecificCount = 0;\n        public string MyStringVar\n        {\n            get { return _MyStringVar; }\n            set\n            {\n                bool isChanged = false;\n                if (_MyStringVar != specificWord) { isChanged = true; }\n                // check for old value to confirm value changed\n                _MyStringVar = value;\n                if (value == specificWord && isChanged) { SpecificCount++; }\n            }\n        }    \n    }	0
9260672	9260548	Loading Assemblies in c# application at runtime not present in application working directory	public MainWindow()\n    {\n        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\n\n        InitializeComponent();\n    }\n\n    Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n    {            \n        string assemblyName = args.Name.Remove(args.Name.IndexOf(',')) + ".dll";\n\n        string s = @"C:\dlls\" + assemblyName;\n\n        if (File.Exists(s))\n        {\n            return Assembly.LoadFile(s);\n        }\n\n        return null;\n    }	0
28576619	28576438	How to download a file in c# with a popup asking where to save file	pdfFilePath = pdfFilePath + "/DownloadPastPapers.pdf";\n    Response.Clear();\n    Response.ContentType = "application/pdf";\n    Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");\n    Response.TransmitFile(pdfFilePath);\n    Response.End();	0
30255583	30255516	How do I draw a line between all the drawn points?	if (drawPoints.Count > 1)\n{\n    e.Graphics.DrawLines(pen, drawPoints.ToArray());\n}	0
6036197	6036050	We encrypt a file for a client using BouncyCastle API. He gets a "For your eyes only" message from PGP when trying to decrypt it. Why?	Stream literalOut = literalDataGenerator.Open(\n    compressedOut, \n    PgpLiteralData.Binary,             \n    PgpLiteralDataGenerator.Console,\n    DateTime.Now, \n    new byte[BUFFER_SIZE]);	0
30592814	30592291	Xamarin: How to implement NSDictionary with YES	NSMutableDictionary dict = new NSMutableDictionary();\n\ndict.Add("test", new NSNumber(true));	0
15131031	15130858	How I get a Arraylist with not double values?	using System.Linq;\n\nfor (int i = 0; i < Counter; i++)\n{\n   bool deptExists = list.Exists(ele => ele == result[i].department);\n\n   if(!deptExists){\n    list.Add(result[i].department);\n   }\n}	0
16906361	16906316	Search for pattern in web page links and store results to array	Uri baseUri = new Uri ("http://www.contoso.com/");\nUri myUri = new Uri (baseUri, "catalog/shownew.htm?date=today");\n\nConsole.WriteLine (myUri.Query); //outputs "?date=today"	0
1478233	1468062	Telerik Grid - One Source Multiple Targets	protected void uxSourceGrid_RowDrop(object sender, \n               Telerik.Web.UI.GridDragDropEventArgs e)\n{\n    for (int i = 0; i < e.DraggedItems.Count; i++)\n    {\n        if (e.DestinationGrid.ID == uxRequiredDateGrid.ID)\n        {\n            SqlDataSource3.UpdateCommand = \n                  "UPDATE Orders SET RequiredDate = \n                   current_timestamp WHERE OrderID =" +\n                   e.DraggedItems[i].GetDataKeyValue("OrderID");\n            SqlDataSource3.Update();\n            uxRequiredDateGrid.Rebind();\n        }\n        else\n        {\n            SqlDataSource1.UpdateCommand = \n                  "update orders set shippeddate = \n                   current_timestamp where orderid =" +\n                   e.DraggedItems[i].GetDataKeyValue("OrderID");\n            SqlDataSource1.Update();\n            uxSourceGrid.Rebind();\n        }\n    }\n}	0
28949554	28949349	Median Maintenance Algorithm - Same implementation yields different results depending on Int32 or Int64	new List<int>()\nnew List<long>()	0
24216602	24216368	How can WriteAttributeString in WriteElementString	w.WriteStartElement("CLAFCNO");\nw.WriteAttributeString("verifier", "Non");\nw.WriteString(CLAFCNO);\nw.WriteEndElement();	0
34470236	34469836	send key like Ctrl+A in ssh with SharpSsh	ssh.Write("\u0003");	0
2830867	2830830	Can I create a transaction using ADO NET Entity Data Model?	using (var transaction = db.Connection.BeginTransaction())\n{\n    // your code here\n    ...\n\n\n    transaction.Commit();\n}	0
7351692	7351338	Copy Value to other cells	private void dataGridView1_CellValueChanged( object sender, DataGridViewCellEventArgs e )\n    {\n        dataGridView1.CellValueChanged -= dataGridView1_CellValueChanged;\n        DataGridViewRow row = dataGridView1.Rows[e.RowIndex];\n        string key = row.Cells[1].Value.ToString();\n\n        foreach ( DataGridViewRow affected in dataGridView1.Rows)\n        {\n            if ( affected.Cells[1].Value.ToString( ) == key )\n            {\n                for ( int i=2; i < dataGridView1.Columns.Count; i++ )\n                {\n                    affected.Cells[i].Value = row.Cells[i].Value;\n                }\n            }\n        }\n\n        dataGridView1.CellValueChanged += dataGridView1_CellValueChanged;\n    }	0
31437454	31437097	How to create a sql database in Basic edition programmatically? in Windows Azure	SqlCommand cmd2 = new SqlCommand(string.Format("CREATE DATABASE [{0:S}] (SERVICE_OBJECTIVE = 'basic');", databaseName), conn);	0
18048279	18048053	XDocument search syntax for nodes	var projectName = (string)xdocument.Root.Element("ProjectName");\n\nvar webSites =  xdocument.Root.Element("ProjectToPost")\n                    .Elements("Website")\n                    .Select(w => new\n                    {\n                        ID = (int)w.Element("ID"),\n                        Type = (string)w.Element("Type"),\n                    })\n                    .ToList();	0
12537180	12537135	C# Windows Forms app - Clear ComboBox selected text from another ComboBox	private bool changed = false;\n    private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (!changed)\n        {\n            changed = true;\n            ComboBox2.Text = "";\n            changed = false;\n        }\n    }\n\n    private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (!changed)\n        {\n            changed = true; \n            ComboBox1.Text = "";\n            changed = false;\n        }            \n    }	0
15324328	15324282	populate a dictionary using linq	appTypeMap = allApplicationTypes.ToDictionary(x => x.id, x => x.name);	0
29894417	29891471	C#: How to extend PropertyInfo?	public class PropertyField\n{\n    PropertyField parent;\n    string path;\n    PropertyInfo info;\n    // etc...\n}	0
5926563	5926326	Is it possible to give a temporary name to a thread from the thread pool?	Thread.Name	0
32979279	32978997	Filter to return two Max numbers	var mydb = new[]{\n    new MyType{ MyTypeID = 1, ID = 2},\n    new MyType{ MyTypeID = 1, ID = 3},\n    new MyType{ MyTypeID = 2, ID = 5},\n    new MyType{ MyTypeID = 2, ID = 4},\n};\n\nvar vals = from mt in mydb\n           where mt.MyTypeID == 1 || mt.MyTypeID == 2\n           group mt by mt.MyTypeID into g\n           select new { MyTypeId = g.Key, MaxID = g.Max(x => x.ID)};	0
21251965	21251874	Convert datetime 24 hour format to datetime 12hr format and add GMT 5.30	Convert.ToDateTime("13:12:10").AddHours(-5).AddMinutes(-30).ToString("hh:mm:ss tt");	0
26228875	26228776	use of combobox to appear another combobox C#	public MainWindow()\n    {\n        InitializeComponent();\n        second_ComboBox.Visibility = Visibility.Collapsed;\n    }\n\n    private void first_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        var selecteditem = first_ComboBox.SelectedItem as string;\n        if (selecteditem != null)\n        {\n            second_ComboBox.Visibility = Visibility.Visible;\n        }\n    }	0
2492392	2491808	Searching Outlook Global Address List	if(CantFindAddressesLocally)\n{\n     MailItem email = (MailItem)(oApp.CreateItem(OlItemType.olMailItem));\n     email.Subject = "MY SUBJECT";\n     email.Body = "MY BODY";\n     email.Attachments.Add(myAttachment);\n     email.Display(false) //popup an Outlook "New Email" window\n}	0
9413729	9413716	Writing Dataset to an xml file	string filePath = Server.MapPath("~/Upload/fileExt.xml");	0
8000296	7993246	how to load a xml file in c# windows phone?	private const string filePath = "TimeKeeperData.xml";\n\n    private static XDocument ReadDataFromIsolatedStorageXmlDoc()\n    {\n        using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())\n        {\n            if (!storage.FileExists(filePath))\n            {\n                return new XDocument();\n            }\n\n            using (var isoFileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, storage))\n            {\n                using (XmlReader reader = XmlReader.Create(isoFileStream))\n                {\n                    return XDocument.Load(reader);\n                }\n            }\n        }\n    }	0
1063309	1063189	AsyncCallback for a thread on compact framework	//untested\npublic abstract class BgHelper\n{\n    public System.Exception Error { get; private set; }\n    public System.Object State { get; private set; }\n\n    public void RunMe(object state)\n    {\n        this.State = state;\n        this.Error = null;\n\n        ThreadStart starter = new ThreadStart(Run);\n        Thread t = new Thread(starter);\n        t.Start();            \n    }\n\n    private void Run()\n    {\n        try\n        {\n            DoWork();                \n        }\n        catch (Exception ex)\n        {\n            Error = ex;\n        }\n        Completed(); // should check Error first\n    }\n\n    protected abstract void DoWork() ;\n\n    protected abstract void Completed();\n}	0
1474632	1474602	Possible to convert IQueryable<Derived> to IQueryable<Base>?	var results = queryable.OfType<Base>.Where(...);	0
12755624	12755491	Detecting CTRL + Click for DataGridView cell in the same event handler	private void cellClicked(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        if(e.Button == MouseButtons.Right) // right click\n        {\n            if (Control.ModifierKeys == Keys.Control)\n               System.Diagnostics.Debug.Print("CTRL + Right click!");\n            else\n               System.Diagnostics.Debug.Print("Right click!");\n        }\n        if (e.Button == MouseButtons.Left) // left click\n        {\n            if (Control.ModifierKeys == Keys.Control)\n                System.Diagnostics.Debug.Print("CTRL + Left click!");\n            else\n                System.Diagnostics.Debug.Print("Left click!");\n        }\n    }	0
26530666	26516300	How to check if data source is empty in Crystal Reports	if (ProjectedHours.Count > 0)\n{\n     Report.Subreports["ProjectedHours"].SetDataSource(ProjectedHours);\n}	0
11253507	11252948	NHibernate , how to loop and get results ?	var total = 0;\n var code = "";\n foreach(var result in resultList)\n {\n      total = result[0]; // or result["totalAmount"]\n      code = result[1];  // or result["my_code"]\n      //then do something with em\n }	0
1132689	1132618	LINQ statement that returns rownumber of element with id == something?	using (var dc = new DataClasses1DataContext())\n{\n    var result = dc.Users\n        .AsEnumerable()     // select all users from the database and bring them back to the client\n        .Select((user, index) => new   // project in the index\n        {\n            user.Username,\n            index\n        })\n        .Where(user => user.Username == "sivey");    // filter for your specific record\n\n    foreach (var item in result)\n    {\n        Console.WriteLine(string.Format("{0}:{1}", item.index, item.Username));\n    }\n}	0
11467174	11466462	How to use a separate model class for validation in MVC	public ActionResult Edit(int id)\n{\n     var movie = this.connection.MovieContext.SingleOrDefault(m => m.ID == id);\n     var vm = new MovieCreateViewModel{ Id = movie.Id};\n     return View(vm);\n}\n\n//\n// POST: /Movie/Edit/5\n\n[HttpPost]\npublic ActionResult Edit(MovieCreateViewModel vm)\n{\n    try\n    {\n        if (ModelState.IsValid)\n        {\n            var movie = new Movie{Id = vm.Id};\n            this.connection.MovieContext.Attach(movie);\n            this.connection.MovieContext.Context.SaveChanges();\n            return RedirectToAction("Index");\n        }\n\n    }\n    catch\n    {\n        return View(movieedit);\n    }\n}	0
2983863	2983796	adding a property to an EventArgs	public class SpecificFileWatcher\n{\n  public string FileToTest { get; set; }\n\n  private readonly FileSystemWatcher iWatcher;\n\n\n  public class SpecificFileWatcher(FileSystemWatcher watcher)\n  {\n    iWatcher = watcher;\n    iWatcher.Changed += iWatcher_Changed; //whatever event you need here\n  }\n\n  //eventhandler for watcher\n  public ...\n  {\n    if(e.FileName == FileToTest)\n      Console.WriteLine("file found");\n  }\n}	0
13993576	13992993	How to get string value from an OracleParameter object when using ExecuteNonQuery	new OracleParameter("lastIdParam", OracleDbType.Varchar2, 128)	0
5085549	5085401	Problem to programmatically add rows to GridView with pre-defined columns	....\n      <ItemTemplate>\n        <asp:CheckBox ID="CheckSelect" runat="server" Checked='<%# Eval("CheckSelect")' />\n      </ItemTemplate>\n....	0
30773349	30772913	How to get specific value of an dictionary	foreach (KeyValuePair<string, MYCLASS> entry in MyDic)\n        {\n            // Value is in: entry.Value and key in: entry.Key\n            foreach(string language in ((MYCLASS)entry.Value).Language)\n            {\n                //Do sth with next language...\n            }\n        }	0
27597747	27597601	Compare two comma separated string and find the missing values	var result = variable1.Split(new char[] {','})\n                .Except(variable2.Split(new char[] {','})).ToArray();	0
6595941	6593243	Remove attributes from XElement	XNamespace nameSpace = "http://schemas.microsoft.com/developer/msbuild/2003";\nvar subType = new XElement(nameSpace + "SubType"); // strange but true	0
3464694	3464605	Creating a variable that can store different instances of generic types and calling a given method on the variable, regardless of the type	public interface ISimulationRunner {\n    public int MaxStepCount { get; set; }\n    ...\n    public void Run() {...}\n    public void Step() {...}\n    public void Stop() {...}\n}\n\npublic class SimulationRunner<TSpace, TCell> : ISimulationRunner \n    where TSpace : I2DState<TCell>\n    where TCell : Cell\n{\n    public TSpace InitialState { get; set; }\n    public IStepAlgorithm<TSpace,TCell> StepAlgorithm { get; set; }\n    public IDisplayStateAlgorithm<TSpace,TCell> DisplayStateAlgorithm { get; set; }\n}\n\npublic partial class UI : Window\n{\n  ISimulationRunner simulation = new SimulationRunner<2DSpace, SimpleCell>();\n  private void mnuiSimulate_Click(object sender, RoutedEventArgs e)\n  {\n    if (simulation != null) simulation.RunSimulation();\n  }\n}	0
5210265	5205986	c# - WPF command-line argument for opening file gives infinite loop	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        if (e.Args != null && e.Args.Count() > 0)\n        {\n            this.Properties["ArbitraryArgName"] = e.Args[0];\n        }\n        base.OnStartup(e);\n\n        if (Application.Current.Properties["ArbitraryArgName"] != null)\n        {\n            string fname = Application.Current.Properties["ArbitraryArgName"].ToString();\n\n            MainWindow mw = new MainWindow();\n            mw.readVcard(fname);\n\n        }\n    }\n\n}	0
12672821	12662506	How to get the generic type parameters for a ENVDTE CodeInterface?	CodeInterface @interface;\n\n// FullName = "IQuery<[FullNameOfType]>\nstring firstArgument = @interface.FullName.Split('<', '>')[1];	0
22700072	22699977	Adding an incremental number to duplicate string	var list = new List<string>{"MyItem (2)", "MyItem", "Other thing", "string here", "MyItem (1)"}   ; \n\nstring str = "MyItem";\nstring newStr = str;\n\nint i = 0;\nwhile(list.Contains(newStr))\n{\n   i++;\n   newStr = string.Format("{0} ({1})",str,i);\n}\n\n// newStr = "MyItem (3)"	0
12687914	12687648	C# Parse the following XML, not sure how	XElement doc=XElement.Parse(".......");\n\nvar yourList=doc.Descendants("dict").Descendants("dict").Select(\nx=>new Employee\n{\nId=x.Elements("string").ElementAt(0).Value,\nPrename=x.Elements("string").ElementAt(1).Value,\nName=x.Elements("string").ElementAt(2).Value,\nInitials=x.Elements("string").ElementAt(3).Value\n}\n);	0
3510040	3509831	Reading data from .doc or .docx and inserting into db	Word.ApplicationClass wordApp = new Word.ApplicationClass();\nobject file = filepath;\nobject nullobj = System.Reflection.Missing.Value;\nWord.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);\ndoc.ActiveWindow.Selection.WholeStory();\ndoc.ActiveWindow.Selection.Copy();\nIDataObject data = Clipboard.GetDataObject();\ntxtFileContent.Text = data.GetData(DataFormats.Text).ToString();\ndoc.Close();	0
28021640	27992847	Reading MSMQ Messages in Raw XML	msg.Formatter = new ActiveXMessageFormatter();\nreader = new StreamReader(msg.BodyStream);\n\nvar msgBody = reader.ReadToEnd(); // This gets the actual message as text	0
612142	612088	XmlWriter only escaping one kind of quote	if (!this.inAttribute || (this.quoteChar != ch))\n   this.textWriter.Write('\'');\nelse\n   this.WriteEntityRefImpl("apos");	0
20991506	20991385	windows store application page refresh	private string parameter;\n\nprotected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)\n{\n   parameter = (string)navigationParameter;\n   reloadData();\n}\n\nprivate void reloadData() \n{\n   var sampleDataGroups = SampleDataSource.GetGroups(parameter);\n   this.DefaultViewModel["Groups"] = sampleDataGroups;\n}\n\nprivate void refresh(object sender, RoutedEventArgs e)\n{\n   reloadData() \n}	0
28320802	28320700	How to get event name in event handler	public Mother()\n{\n    Boy son = new Boy();\n    son.Birth += (sender, e) => Handler("Birth", sender, e);\n    son.Die += (sender, e) => Handler("Die", sender, e);\n}\n\nvoid Handler(string description, object sender, EventArgs e)\n{\n    Log("I'm in the {0} event", description);\n    throw new NotImplementedException();\n}	0
25324288	25141186	Custom caliburn.micro splashscreen with shell screen conductor	protected override void OnStartup(object sender, StartupEventArgs e)\n    {\n        var splash = this.container.GetExportedValue<SplashScreenViewModel>();\n        var windowManager = IoC.Get<IWindowManager>();\n        windowManager.ShowDialog(splash);\n\n       // do your background work here using\n        var bw = new BackgroundWorker();\n        bw.DoWork += (s, e) =>\n            {\n                // Do your background process here\n\n            };\n\n        bw.RunWorkerCompleted += (s, e) =>\n            {\n                // close the splash window\n                splash.TryClose();\n                this.DisplayRootViewFor<ShellViewModel>();\n            }; \n\n        bw.RunWorkerAsync();           \n    }\n\n\n    // your ShellViewModel\n    [ImportingConstructor]\n    public ShellViewModel(MainViewModel mainViewModel)\n    {\n        this.DisplayName = "Window Title";\n        // no need to new\n        this.ActivateItem(mainViewModel);\n    }	0
28124357	28124236	Find Missing File Names in directory using c#	for (int pageNum = 0; pageNum <= 20; pageNum++)\n{   \n    //templateFiles is list of files in that directory\n    string expectedTemplateName1 = string.Format("{0}_{1}.txt", directoryName, pageNum.ToString());\n    string expectedTemplateName2 = string.Format("{0}_{1}.txt", directoryName, pageNum.ToString("00"));\n    templateFiles.Any(file => \n        (file.Equals(expectedTemplateName1, StringComparison.OrdinalIgnoreCase) || \n        file.Equals(expectedTemplateName2, StringComparison.OrdinalIgnoreCase)));\n}	0
2345479	2345389	Need help with scrolling to a percentage of richtextbox's maximum scroll amount (the richtextbox is in a scrollviewer)	double d = (e.GetPosition(richtextboxScrollViewer).Y / richtextboxScrollViewer.ViewportHeight);	0
838859	838816	Call C++ code from a C# application or port it?	using System.Runtime.InteropServices;\n    class myDllCaller {\n\n       //call to function in the dll returning an int\n      [DllImport("MyFavorite.dll")]\n      private static extern int dllFunction(//list of parameters to function);\n\n    public static void Main() {\n    int rerult = dllFunction();\n\n    }\n}	0
27090655	27090630	cant insert new data into database table but the other part of the code is working	SqlCommand sqlinsertCmd = new SqlCommand("INSERT TradeRecords(ClientID) \n values(@clientID)";\nsqlinsertCmd.Parameters.Add("@clientID", SqlDbType.Int).Value = clientID;\n            sqlinsertCmd.ExecuteNonQuery();	0
17610907	17609463	How can i export grid data to open office spreadsheet with C#?	SLDocument sl = new SLDocument();\n//Read data from grid and write it in excel\nfor (int rows = 0; rows < dataGrid.Rows.Count; rows++)\n    {\n\n         for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)\n        {\n            sl.SetCellValue(rows, col, dataGrid.Rows[rows].Cells[col].Value.ToString());\n        }\n    }\n\n\nsl.SaveAs("Test.xlsx");	0
9704846	9704598	How to decode JSON in C#	[DataContract]\nclass Tweeter\n{\n    [DataMember]\n    public string geo {get;set;}\n    [DataMember]\n    public User user {get;set;}\n}\n\n[DataContract]\nclass User\n{\n    [DataMember]\n    public string screen_name {get;set;}\n}\n\nclass Converter\n{\n    public Tweeter ConvertJson(string json)\n    {\n        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Tweeter));\n\n        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))\n        {\n            return serializer.ReadObject(ms) as Tweeter;\n        }\n    }\n}	0
15926715	15926551	How to Inject Log4Net Logging through Castle.Windsor in NServiceBus	public class MessageEndpoint : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization\n{\n    public void Init()\n    {\n        var container = new WindsorContainer();\n        var installerFactory = new MyInstallerFactory();\n        container.Install(FromAssembly.This(installerFactory));\n\n        var logger = container.Resolve<ILogger>();\n        logger.Debug("Container bootstrapped");\n\n        Configure.With()\n                 .DisableTimeoutManager()\n                 .CastleWindsorBuilder(container)\n                 .JsonSerializer();\n\n        logger.Debug("Bus configured");\n    }\n}	0
13996206	13987976	two whenany on one object bug	var changedObservable = new Subject<Unit>();\nthis.SizeChanged += (o,e) => changedObservable.OnNext(Unit.Default);	0
6774494	6757323	Binding treeview dynamically using datarelation and xml	DataRelation rel = new DataRelation("ClientCategory", dtTree.Tables[0].Columns["TPAClientGroupId"], dtTree.Tables[1].Columns["TPAClientGroupId"], true);\nrel.Nested = true;\n\ndtTree.Relations.Add(rel);\n\n\nforeach (DataColumn dc in dst.Tables[0].Columns)\n{\n    dc.ColumnMapping = MappingType.Attribute;\n}\nforeach (DataColumn dc in dst.Tables[1].Columns)\n{\n    dc.ColumnMapping = MappingType.Attribute;\n}\n\nXmlDataSource xmlD = new System.Web.UI.WebControls.XmlDataSource();\nxmlD.ID = "clientGroupsxml";\nxmlD.Data = dtTree.GetXml();	0
22637040	22636728	Validate Decimal number with Mathematic Operator using RegEx in C#	var regex = new Regex(@"^([<>]=?)?-?(\d+\.?|\d*\.?\d+)$");\nbool isMatch = regex.IsMatch(testString);	0
26097210	26009280	How can I display the latest value in Chart?	cmd = new SqlCommand("Select Mains_Run_Hrs, DG_Run_Auto_Mode, Battery_Run_Hrs, Solar_Run_hrs from tbl_runtime_report ORDER BY Site_ID DESC", con);	0
5762612	5761202	Is it OK to remove .property statements from ILAsm files for production use?	.property	0
26628527	26628285	Use Catel ServiceLocator in constructor of control	public MyGridControl()\n{\n    if (CatelEnvironment.IsInDesignMode)\n    {\n        return;\n    }\n\n    // TODO: Use service locator and all runtime code\n}	0
23205486	23185884	Plotting Line Chart - from WCF to Silverlight	((LineSeries)Chart1.Series[0]).ItemsSource =\n\n   new KeyValuePair<string, double>[]{\n\n        new KeyValuePair<string, double>("09", masterDraft.SQFT09 ),\n\n         new KeyValuePair<string, double>("10", masterDraft.SQFT10 ),\n         // new KeyValuePair<string, double>("SQFT10", masterDraft. ),\n           new KeyValuePair<string, double>("11", masterDraft.SQFT11 ),\n           new KeyValuePair<string, double>("12", masterDraft.SQFT12 ),\n             new KeyValuePair<string, double>("13", masterDraft.SQFT13 ),\n\n    };	0
2089507	2089487	How to pass all selected files names to C# application?	static void Main(string[] args)\n{\n    if (args.Length == 0)\n    {\n        Console.WriteLine("Program called without arguments");\n    }\n    else\n    {\n        Console.WriteLine("Program received this arguments:");\n        foreach (string arg in args)\n        {\n            Console.WriteLine("\t{0}", arg);\n        }\n    }\n\n    // .. do other stuff\n}	0
11574538	11574474	Linq get sum of data group by date	var result = \n    from s in  meter_readings.Take(10)\n    group s by new { date = new DateTime(s.read_date.Year, s.read_date.Month, 1) } into g\n    select new\n    {\n        read_date = g.Key.date,\n        T1 = g.Sum(x => x.T1),\n        T2 = g.Sum(x => x.T2)\n    };	0
11035950	11035917	data[,] into list<string> or list<object> in c#	List<string> resultsFields = new List<string>(data.GetLength(0));	0
31539029	31531953	How to use a WCF Web Service in VB6	dim SOAPClient\nset SOAPClient = createobject("MSSOAP.SOAPClient")	0
9353452	9353410	How do you prevent an application terminating if you close just one window?	static void Main() \n{ \n    Application.EnableVisualStyles(); \n    Application.SetCompatibleTextRenderingDefault(false); \n    Application.Run(new MainScreen()); \n} \n\npublic MainScreen()\n{\n    Login loginForm = new LoginForm();\n    if(loginForm.ShowDialog() == DialogResult.Cancel)\n        Application.Exit();\n    InitializeComponent();\n}	0
33395410	32841076	How to get the template for a windows event log message	using System;\nusing System.Diagnostics.Eventing.Reader;\nusing System.Globalization;\n\npublic static class Program {\n\n    static void Main(string[] args) {\n        foreach (var providerName in EventLogSession.GlobalSession.GetProviderNames()) {\n            DumpMetadata(providerName);\n        }\n    }\n\n    private static void DumpMetadata(string providerName) {\n        try {\n            ProviderMetadata providerMetadata = new ProviderMetadata(providerName, EventLogSession.GlobalSession, CultureInfo.InvariantCulture);\n            foreach (var eventMetadata in providerMetadata.Events) {\n                if (!string.IsNullOrEmpty(eventMetadata.Description)) {\n                    Console.WriteLine("{0} ({1}): {2}", eventMetadata.Id, eventMetadata.Version, eventMetadata.Description);\n                }\n            }\n        } catch (EventLogException) {\n            Console.WriteLine("Cannot read metadata for provider {0}", providerName);\n        } \n    }\n}	0
31518814	31516509	Modifying static variables from other scripts in Unity	myGameObjectInstance.GetComponent<MyBehaviourWithStatic>().myStatic = value;	0
16623463	16623401	Storing multiple sets of numbers into a byte array	public static uint Read3BE(byte[] data, int index)\n{\n    return data[index]<<16 | data[index+1]<<8 | data[index+2];\n}\n\npublic static void Write3BE(byte[] data, int index, uint value)\n{\n    if((value>>24)!=0)\n      throw new ArgumentException("value too large");\n    data[index]=(byte)(value>>16);\n    data[index+1]=(byte)(value>>8);\n    data[index+2]=(byte)value;\n}	0
10437850	10437741	Using session to get/set object properties everytime	public static Example Instance\n{\n    get\n    {\n        //store the object in session if not already stored\n        if (Session["example"] == null)\n            Session["example"] = new Example();\n\n        //return the object from session\n        return (Example)Session["example"];\n    }\n}	0
2901662	2901040	Replace a word in an XML file through StreamReader in XNA?	string content = "";\n\n// Read the XML file into content\nStreamReader reader = new StreamReader("file.xml");\ncontent = reader.ReadToEnd();\nreader.Close();\n\n// Find the character position just after the <?xml token, and just before the ?> token\nint openIndex = content.IndexOf("<?xml", StringComparison.OrdinalIgnoreCase) + 5;\nint closeIndex = content.IndexOf("?>", openIndex);\n\n// Get the bits between <?xml and ?>    \nstring header = content.Substring(openIndex, closeIndex - openIndex);\n\n// Substitute version string.\nheader = header.Replace("version=\"1.1\"", "version=\"1.0\"");\n\n// Put Humpty Dumpty back together again.\ncontent = string.Concat(content.Substring(0, openIndex), header, content.Substring(closeIndex));\n\n// Feed content into an XMLReader (or equivalent) here.	0
4943469	4943383	How to access user control properties if i load it programatically?	MyControl ctrl = (MyControl)LoadControl("~/Controls.mycontrol.ascx");\nctrl.stuffType = ...;\n// put control somehwere	0
10939449	10939292	how to merge two header file in C#?	using System;\nusing System.IO;\n\nnamespace csharp_station.howto\n{\n    class TextFileReader\n    {\n        static void Main(string[] args)\n        {\n            TextReader tr1 = new StreamReader("file1.txt");\n            TextReader tr2 = new StreamReader("file2.txt");\n            TextWriter tw = new StreamWriter("result.txt");\n\n            int count1 = Convert.ToInt32(tr1.ReadLine());\n            int count2 = Convert.ToInt32(tr2.ReadLine());\n            tw.WriteLine(count1 + count2);\n\n            for(int i = 0; i < count1; i++)\n            {\n                tw.WriteLine(tr1.ReadLine());\n            }\n\n            for(int i = 0; i < count2; i++)\n            {\n                tw.WriteLine(tr2.ReadLine());\n            }\n\n            tr1.Close();\n            tr2.Close();\n            tw.Close();\n        }\n    }\n}	0
33286440	33286262	Modify a control in C#	using System;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n    public class MyMonthCalendar : MonthCalendar\n    {\n        public int MyProperty { get; set; }\n    }\n}	0
23166451	23160054	Force checkbox to be unchecked or checked in datagridview	string yourValue="x";\n           if (dataGridView1.Rows[0].Cells[1].Value.ToString() == yourValue)\n           {\n            dataGridView1.Rows[0].Cells[1].Value = true;\n\n            //or\n            //dataGridView1.Rows[0].Cells[3].Value = false;\n           }	0
16636683	15933972	Send PartialView content as email	protected string RenderPartialViewToString(string viewName, object model)\n{\n    if (string.IsNullOrEmpty(viewName))\n        viewName = ControllerContext.RouteData.GetRequiredString("action");\n\n    ViewData.Model = model;\n\n    using (StringWriter sw = new StringWriter()) {\n        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);\n        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);\n        viewResult.View.Render(viewContext, sw);\n\n        return sw.GetStringBuilder().ToString();\n    }\n}	0
9118385	9118366	How can I see what a winform looks like at runtime?	ShowDialog()	0
19866041	19865742	TransactionScope check if transaction commited ok	var transactionFailed = false;\ntry\n{\n    using (var tx = new TransactionScope())\n    {\n        tx.Complete();\n    }\n}\ncatch (TransactionAbortedException ex)\n{\n    transactionFailed = true;\n    writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);\n\n}\ncatch (ApplicationException ex)\n{\n    transactionFailed = true;\n    writer.WriteLine("ApplicationException Message: {0}", ex.Message);\n}\ncatch (Exception ex)\n{\n    transactionFailed = true;\n    writer.WriteLine("Exception Message: {0}", ex.Message);\n}	0
6037885	6023227	Deserializing XML CDATA into string variable with RestSharp	public class Item \n{\n        public string Title { get; set; }\n        public string Link { get; set; }\n        public string Comments { get; set; }\n        public DateTime PubDate { get; set; }\n        public string Creator { get; set; }\n        public string Category { get; set; }\n        public string Description { get; set; }\n        public string Encoded { get; set; }\n        public string Guid { get; set; }\n        public string CommentRss { get; set; }\n        public int SlashComments { get; set; }\n}	0
26254405	26254257	How to store meta data in a SQL Server database to differentiate it from other databases?	sp_addextendedproperty @name='IsOfInterestToMe', @value=1	0
8189423	8189025	How to download file from http server that requires a referral before allowing the download?	WebClient wc = new WebClient();\nwc.Headers.Add("Referer","http://whatever.com");\nwc.DownloadFile("url of the file","filepath to save the file");	0
5233135	5232117	Linq how to write a JOIN	var result01 = from c in context.CmsContents where c.ModeContent == "NA"\njoin d in context.CmsContentsAssignedToes on c.ContentId equals d.ContentId into g\nwhere !g.Any()\nselect c;	0
19763327	19763246	How to Verticaly Flip an BitmapImage	var transform = new ScaleTransform(1, -1, 0, 0);	0
18462506	18462349	parsing XML content - C#	var result = XDocument.Parse(xml)\n                .Descendants("lst")\n                .Where(e => (string) e.Attribute("name") == "overflow")\n                .Descendants("str")\n                .Select(x => x.Value)\n                .FirstOrDefault();	0
33921603	33921568	Filtering out double quotes from a string array	if (key != "," && key != "{" && key != "}" && key != ":")	0
252682	252656	Does reflection expose if the last argument for a method was marked with 'params'?	class Program\n{\n    public void MethodWithParams(object param1, params int[] param2) \n    {            \n    }\n\n    static void Main(string[] args)\n    {\n        var method = typeof(Program).GetMethod("MethodWithParams");\n        var @params = method.GetParameters();\n        foreach (var param in @params) \n        {\n            Console.WriteLine(param.IsDefined(typeof(ParamArrayAttribute), false));\n        }\n    }\n}	0
31101017	31100892	splitting list and storing contents in an another array	var entities = model.Ids.Select(line => line.Split('_').Last()).Distinct().ToList();\nforeach(var entity in entities) {\n    string entityId = entity;\n    List<string> tstIds = new List<string>{entityId};\n}	0
26735910	26734923	Date conversion	DateTimeOffset localTime = DateTimeOffset.Now;\nstring.Format("{0:ddd MMM d HH:mm:ss} UTC+{1} {0:yyyy}", localTime, localTime.Offset.ToString("hhmm"));	0
29453219	29452671	Can a Multi line text box in c# hide some text elements and show when you click on a text box please see example?	public partial class Form1 : Form\n{\n    string[] LinesWithDetails;\n    string[] LinesWithOutDetails;\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        LinesWithDetails = richTextBox1.Lines;\n        LinesWithOutDetails = richTextBox1.Lines.Where(l => l.Contains("Deposit")).ToArray();\n\n        HideDetails();\n    }\n\n    private void checkBox1_CheckedChanged(object sender, EventArgs e)\n    {\n        if (checkBox1.Checked)\n            ShowDetails();\n        else\n            HideDetails();\n    }\n\n    private void ShowDetails()\n    {\n        richTextBox1.Lines = LinesWithDetails;\n    }\n    private void HideDetails()\n    {\n        richTextBox1.Lines = LinesWithOutDetails;\n    }\n\n\n}	0
27163083	27162746	Refresh datagridview after update data in another form	private void button1_Click(object sender, EventArgs e)\n{\n   Form frm=(Form)this.MdiParent;\n   DataGridView dt = (DataGridView)frm.Controls["dataGridView1"];\n   dt.Rows[0].Cells[0].Value = textBox1.Text;\n\n}	0
8812661	8812531	Calling a function in PageBase from a MasterPage in ASP.NET	(this.Page as PageBase).LoadContext()	0
12957383	12956415	Remove help button from excel data validation	Private Sub Worksheet_Change(ByVal Target As Range)\ndim msg as string\ndim Style as string\ndim Title as string\ndim Response as long\n'Update Cells to be the actuall range you want to validate\nIf Intersect(Target, Cells(1, 2)) Then\n    If Cells(1, 2).Value <> "whatever" Then\n        msg = "Value must be LT 1"\n        Style = vbRetryCancel + vbCritical\n        Title = "Mt Error"\n        Response = MsgBox(msg, Style, Title)\n    End If\nEnd If\nEnd Sub	0
18698900	10556348	How to manage Migrations in a project with multiple branches?	add-migration [the_migration_to_rescaffold_metadata_for]	0
10113034	10112985	Multiple models into a view	public ViewResult Index()\n{\n    return View(db);\n}	0
20250002	20249458	How to calculate round on very large array of double in C#	Parallel.For(0, arr.Length, i => arr[i] = Math.Round(arr[i], 2));	0
933127	933112	Is there a clean way of referencing generic classes in a non-generic context?	public interface ICleanCoder<T> : ICleanCoder\n{\n    void DoSomeCoding(T task);\n}	0
16273874	16273575	How to Get the Control Type in a Gridview Template?	if (this.grdViewDetails.EditIndex != -1)\n{\n CheckBox b = grdViewDetails.Rows[grdViewDetails.EditIndex].FindControl("CheckWeek2") as CheckBox;\n if (b != null)\n  {\n  //do something\n  }\n}	0
4636204	4636164	Convert IP Address into int, (ie inet aton in c#)	public int ToInteger(int A, int B, int C, int D)\n{\n    return Convert.ToInt32((A* Math.Pow(256, 3)) + (B* Math.Pow(256, 2)) + (C* 256) + D);\n}	0
23183925	23183883	Get own base address - multiple processes with the same name	Process.GetCurrentProcess()	0
26951995	26951960	Iterate through a byte array like it's Uint16[]	fixed(byte* p = bytearray)\n{\n    ushort* ptr=(ushort*)p;\n    for(int i = 0; i < bytearray.Length/2; i++)\n    {\n        //...\n    }\n}	0
18489685	18489503	Compare regular expression	var regex = "Full Name:(.*)ID Number:(.*)Mobile Number:(.*)";\nvar match = Regex.Match(string, regex);	0
5320621	5260282	How to query a datable with dynamic columns	public static void SelectRandomColumns(DataTable dataTable, string col1, string col2)\n{\n    // Select into an anonymous type here, but you could\n    // select into a custom class\n    var query = from row in dataTable.AsEnumerable()\n                select new\n                {\n                    p1 = row[col1],\n                    p2 = row[col2]\n                };\n\n    // Do whatever you need to do with the new collection of items\n    foreach (var item in query)\n    {\n        Console.WriteLine("{0}: {1}, {2}: {3}", col1, item.p1, col2, item.p2);\n    }           \n}	0
11901703	11901673	c# how to change the tray icon	newmailIcon.ico	0
5779940	5779871	How to obtain Local IP?	public static String GetIP()\n{\n    String ip = 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
5592297	5592196	mysql bulk insert a text file	LOAD DATA local INFILE 'C:/Documents and Settings/Administrator/Desktop/Merge.txt' \nINTO TABLE tblachmaster\nFIELDS TERMINATED BY ',' ENCLOSED BY '"'\nLINES TERMINATED BY '\r\n'\nIGNORE 1 LINES;	0
30922185	30922050	Fast access to matrix as jagged array in C#	var dm = new double[size][];\nfor (var i = 0; i < size; i++)\n{\n   dm[i] = new double[size];\n   for (var j = 0; j < i+1; j++)\n   {\n      dm[i][j] = distance(data[i], data[j]);\n      dm[j][i] = dm[i][j];\n   }\n }\n\nprivate double GetValueOfDM(int row, int column, double[][] dm)\n{\n    return dm[row][column];\n}	0
12245963	12244553	Update a value in a Dictionary when the TryGetValue method returns true	ToList()	0
10644356	10644301	Does iterating with foreach loop over a dictionary require normal hashtable accesses?	Entry<TKey, TValue>[]	0
22222480	22222259	Replace certain string if it has a matching string after it?	string testString = @"this'is'my'\ntest'\nstring'";\n\nvar split = testString.Split(new[]{"'"}, StringSplitOptions.RemoveEmptyEntries)\n    .Select(s => s.Trim() + "'");\ntestString = string.Join(Environment.NewLine, split);	0
5103633	5103599	combine string.format arguments	string.Format("{0:X4}", number)	0
17866873	17865584	Convert a list of string into json format	string[][] newKeys = keys.Select(x => new string[]{x}).ToArray();\n\nstring json = JsonConvert.SerializeObject(newKeys);	0
12905327	12905174	How To Add Custom ModelValidatorProviders To Web API Project?	GlobalConfiguration.Configuration.Services.Add(typeof(ModelValidatorProvider), new CustomModelValidatorProvider());	0
7916843	7916663	Fluent Nhibernate inner join	var list = session.QueryOver<Master>()\n                        .JoinQueryOver(master => master.imagen)\n                        .Where(imagen => imagen.linea.Id == 5)\n                        .List();	0
26372966	26372889	c# Caesar cipher alphabet enum to strings	public static void cifrar()\n{\n    Console.WriteLine("Escribe el mensaje");\n    string letra = Console.ReadLine();\n    letras l = (letras)Enum.Parse(typeof(letras), letra);\n    Console.WriteLine("Cifrado: " + ((l + 5) % 53)); //Use the modulus operator to prevent going beyond the end of the enum\n    Console.ReadLine();\n}\n\npublic static void descifrar()\n{\n    Console.WriteLine("Escribe el cifrado");\n    string letra = Console.ReadLine(); ;\n\n    letras l = (letras)Enum.Parse(typeof(letras), letra);\n    int di = ((int)l) - 5; //Move back 5 letters\n    if(di < 0) di = 53 + di; //We moved to a negative number, circle back to the end\n\n    Console.WriteLine("Descifrado: " + ((letras)di));\n    Console.ReadLine();\n}	0
24874618	24872613	How can I calculate the average and then the percentage increase in two TimeSpan values in a list	long average_tspan_first_time = Convert.ToInt64(lst_results.Average(t => t.first_time.Ticks));\n        TimeSpan avg_first_time = new TimeSpan(average_tspan_first_time);\n        long average_tspan_second_time = Convert.ToInt64(lst_results.Average(t => t.second_time.Ticks));\n        TimeSpan avg_second_time = new TimeSpan(average_tspan_second_time);\n\n        double p_change = ((double)average_tspan_second_time - (double)average_tspan_first_time) / (double)average_tspan_first_time * 100;	0
5621084	5620903	How do I insert a row into a DataGridView programmatically?	DataGridViewRow dr = new DataGridViewRow();\nDataGridViewCell dcDescription = new DataGridViewTextBoxCell();\n\ndcDescription.Value = "some text";\n\ndr.Cells.Add(dcDescription);\ndataGridViewDoctorEventsAddServices.Rows.Add(dr);	0
9719671	9716145	How to ignore reponse data from when send Post request?	using (Stream requestStream = request.GetRequestStream())\n{\n    // Write the "POST" data to the stream\n    requestStream.Write(byteArray, 0, byteArray.Length);\n}\n\n// now put the get response code in a new thread and immediately return\nThreadPool.QueueUserWorkItem((x) =>\n{\n    using (var objResponse = (HttpWebResponse) request.GetResponse())\n    {\n        responseStream = new MemoryStream();\n        objResponse.GetResponseStream().CopyTo(responseStream);\n        responseStream.Seek(0, SeekOrigin.Begin);\n     }\n});	0
24002157	24002023	Return a tuple from a moqed repository method	mock.Setup(item => item.MethodName(It.IsAny<int>()))\n    .Returns((int i) => new Tuple<int, int>(i, i));	0
4454523	4454493	Avoid "Nullable object must have a value." in Linq-To-Sql	where filterId == null || t.Filter == filterId	0
3702037	3701859	Control positioning & binding	Collection<Push>	0
24530285	24530232	asp.net c# explode string to array	string[] words = s.TrimStart('_').Split('_');	0
25762686	25762550	XPath to select nodes whose name starts with	/detail/address/*[starts-with(name(), 'line')]	0
27059910	27058968	Looks like only a part of the API call is anwered in Ahsay	public void API_HTTP()\n   {\n    string url = "http://URL";\n\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n\n    HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n    Stream resStream = response.GetResponseStream();\n    StreamReader reader = new StreamReader(resStream);\n    String output = reader.ReadToEnd();\n\n            }	0
4245007	4244954	How to make the last added item to a checkedlistbox automatically selected	checkedlistbox1.SelectedIndex = checkedlistbox1.Items.Count-1	0
18830464	18830397	Awaiting a non-async method	await Task.Run(() => YourMethod());	0
14053280	14049078	Extract address from database and put the address into google maps with c#	ScriptManager.RegisterArrayDeclaration	0
21944742	21944677	How to find item within List<T>?	TranslatorScript ts = new TranslatorScript(blah1, blah2, blah3);\nvar match = TranslatorScriptList.Find(x => x.Property == ts.Property);\nif (match != null)\n{\n    // Matches, do stuff\n}	0
29656439	29655198	How to navigate to another Page from a User Control in Windows Phone 8.1	private void lstFoo_ItemClick(object sender, ItemClickEventArgs e)\n{\n    (Window.Current.Content as Frame).Navigate(typeof(BarPage), e.ClickedItem);\n}	0
5337341	5335120	How to query the column description of a table?	SELECT\n    K_Table = FK.TABLE_NAME,\n    FK_Column = CU.COLUMN_NAME,\n    PK_Table = PK.TABLE_NAME,\n    PK_Column = PT.COLUMN_NAME,\n    Constraint_Name = C.CONSTRAINT_NAME\nFROM\n    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK\n    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK\n    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME\nINNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU\n    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME\nINNER JOIN (\n    SELECT\n        i1.TABLE_NAME,\n        i2.COLUMN_NAME\n    FROM\n        INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1\n    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2\n        ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME\n    WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'\n) PT\n    ON PT.TABLE_NAME = PK.TABLE_NAME	0
34445021	34444951	Style object based on binding bool attribute in wpf	BackgroundColor="{Binding Path=IsRound, Converter={StaticResource BoolToFillColorConverter}}"\n\npublic class BoolToFillColorConverter: IValueConverter\n{\n  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n      bool b;\n      if (bool.TryParse(value, out b))\n      {\n        if (b) return Red\n        else return Blue;\n      }\n      else\n      {\n        return SomeDefaultColour;\n      }\n  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n  {\n    return null;\n  }\n}	0
24741307	24741160	Changing text displayed to user as a readable string when SQL data is numeric	OnRowDataBound="GridView1_RowDataBound"	0
29226677	29121699	Retrieving original size image from Facebook Marketing API	using System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n    public static void Main()\n    {\n        string url1 = "https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/s110x80/10156615_6017073002888_1171145694_n.png";\n        string url2 = "https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/10156615_6017073002888_1171145694_n.png";\n\n        Regex reg = new Regex("s\\d+x\\d+/");\n\n        Console.WriteLine(reg.Replace(url1, ""));\n        Console.WriteLine(reg.Replace(url2, ""));\n    }\n}	0
14798759	14798691	Converting an Ascii string to bit stream	byte b = 23;\nvar str = Convert.ToString(b, 2).PadLeft(8,'0');	0
1340698	1340638	Sharepoint adding an item into a Picture Library	private byte [] StreamFile(string filename)\n{\n  FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);\n  // Create a byte array of file stream length\n  byte[] ImageData = new byte[fs.Length];\n  //Read  block of bytes from stream into the byte array\n  fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));\n  //Close the File Stream\n  fs.Close();\n  return ImageData;\n}\n\n// then use the following to add the file to the list\nlist.RootFolder.Files.Add(fileName, StreamFile(fileName));	0
22169176	22169050	Set the UDP/TCP checksum to null on PcapDotNet	//IP\n    IpV4Layer ipLayer = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();\n    ipLayer.HeaderChecksum = null;\n\n    //TCP\n    TransportLayer transportLayer = (TransportLayer)packet.Ethernet.IpV4.Transport.ExtractLayer();\n    transportLayer.Checksum = null;\n\n    //UDP\n    UdpLayer udpLayer = (UdpLayer)packet.Ethernet.IpV4.Udp.ExtractLayer();\n    udpLayer.Checksum = null;	0
14214098	14212017	Drag and Drop items Within a gridview	CanReorderItems="True"\n            AllowDrop="True"\n            CanDragItems="True"	0
19166908	19161949	Can you attach an adorner's position to anywhere other than the upper-left of the adorned element?	// create AdornerPanel and add your adorner content\nAdornerPanel adornerPanel = new AdornerPanel();\nadornerPanel.Children.Add(yourAdornerContent);\n\n// set placements on AdornerPanel\nAdornerPlacementCollection placement = new AdornerPlacementCollection();\nplacement.PositionRelativeToAdornerHeight(-1, 0);\nplacement.PositionRelativeToAdornerWidth(1, 0);\nAdornerPanel.SetPlacements(adornerPanel, placement);\n\n// create Adorner with AdornerPanel inside\nAdorner adorner = new YourAdorner(adornedElement)\n{\n    Child = adornerPanel\n};	0
21294523	21293664	Displaying number of items according to parameters passed xaml windows phone	if (NavigationContext.QueryString.ContainsKey("count"))\n        {\n            var countString = NavigationContext.QueryString["count"];\n            var count = Int32.Parse(countString);\n            // Create list\n            for(int i = 0; i < count; i++) \n            {\n                 MyLLSList.Add(new Item());\n            }\n        }	0
31718513	31718424	linq query group by in a list of strings	var dedupedlist = zipcodes.Distinct().ToList();	0
29416484	29354388	How can I set the date of moment.js object to the server date when parsing MS ASP.NET JSON Date?	"MM/DD/YYYY hh:mm"	0
16096952	16096927	Assign array to class members in order	public string GetVal(int index){\n  if(input.Length > index)\n  {\n    return input[index];\n  }\n  return null;\n} \n\npublic string a\n{\n  get{return GetVal(0);}\n}	0
11414904	11414422	Cannot add a row to Google Spreadsheet	row.Elements.Add(new ListEntry.Custom() { LocalName = "name", Value = "Joe" }); // "Name" changed to "name"\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "my-val1", Value = "Smith" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "my-val2", Value = "26" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "my-val3", Value = "176" });\nrow.Elements.Add(new ListEntry.Custom() { LocalName = "other", Value = "176" }); // "Other" changed to "other"	0
9016700	8904832	Using StartTLS with LDAP from System.DirectoryServices	connection.SessionOptions.VerifyServerCertificate \n    += (conn, cert) => {return true;};	0
18924364	18924307	Missing DLLs for ServiceStack	using ServiceStack.ServiceClient.Web;	0
3893790	3893782	How is GetHashCode() implemented for Int32?	public override int GetHashCode()\n{\n    return this;\n}	0
1638984	1572213	How to get DataGridViewRow from CellFormatting event?	DataTable t = new DataTable(); //your datasource\nint theIndexIWant = 3;\n\nprivate void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{               \n    DataRowView row = dataGridView1.Rows[e.RowIndex].DataBoundItem as DataRowView;      \n\n    if (row != null && t.Rows.IndexOf(row.Row) == theIndexIWant)\n    {\n        e.CellStyle.BackColor = Color.Red;\n    }\n}	0
10014567	10014140	How can I make a validating TextBox with Binding in WPF that switches back to the last valid value after invalid entry?	Application.Current.Dispatcher.BeginInvoke(new Action(() =>\n    {\n        _doubleDisplayValue = originalValue;\n        NotifyPropertyChanged("DoubleDisplayValue");\n    }), DispatcherPriority.ContextIdle, null);	0
5693670	5692700	C# function to convert screen-space coordinates to worldspace coordinates, at specific Z position?	Vector3 3dWorldPosition = GraphicsDevice.Viewport.Unproject(2DscreenVector & desired Z comp, viewMatrix, projectionMatrix);	0
14835048	14834870	Loop through DataAdapter to Generate HTML table	StringBuilder sb = new StringBuilder();\n\nsb.append('<table><tbody>');\n\nforeach(DataRow r in dt.Rows)\n{\n     sb.append('<tr><th>' + r["ColumnHeader"] + '</th></tr>');\n     sb.append('<tr><th>' + r["ColumnData"] + '</th></tr>');\n}\n\n sb.append('</tbody></table>');\n\n\n  return sb.ToString();	0
5918331	5918239	Launching an application, then restoring after closing application	private void button1_Click(object sender, EventArgs e) {\n        var prc = new System.Diagnostics.Process();\n        prc.StartInfo.FileName = "notepad.exe";\n        prc.EnableRaisingEvents = true;\n        prc.SynchronizingObject = this;\n        prc.Exited += delegate { \n            this.WindowState = FormWindowState.Normal;\n            prc.Dispose();\n        };\n        prc.Start();\n        this.WindowState = FormWindowState.Minimized;\n    }	0
13134637	13120562	PDFSharp Insert an image in a pdf using a PdfTextField as the position and size reference	protected int PaginaCampo(string campofirma, PdfDocument document)\n{\n    for (int i = 0; i < document.Pages.Count; i++)\n    {\n        PdfAnnotations anotations = document.Pages[i].Annotations;\n        for (int j = 0; j < anotations.Count; j++)\n        {\n            if (anotations[j].Title != campofirma) continue;\n            return i;\n        }\n    }\n    return -1;\n}	0
18726347	18726257	Running a couple of errors in a form with a button and textbox	public partial class Form1 : Form\n{\n    Random r = new Random();\n    int num; // you cannot use r there\n    int counter = 0;\n\n    public Form1()\n    {\n        InitializeComponent();\n        num = r.Next(0, 100); // you can use r there\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    private void btn1_Click(object sender, EventArgs e)\n    {\n        counter++;\n\n        if (int.Parse(txt1.Text) > num)\n        {\n            lbl1.Text = "the number is too high";\n            BackColor = SystemColors.HotTrack; // Form1 is the class\n\n\n        }\n        else {\n            lbl1.Text = "the number is too low";\n            BackColor = SystemColors.MenuHighlight; // Form1 is the class\n        }\n\n    }\n}	0
28247330	28234052	Finding all class declarations than inherit from another with Roslyn	public class BaseClassRewriter : CSharpSyntaxRewriter\n{\n    private readonly SemanticModel _model;\n\n    public BaseClassRewriter(SemanticModel model)\n    {\n        _model = model;\n    }\n\n    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)\n    {\n        var symbol = _model.GetDeclaredSymbol(node);\n        if (InheritsFrom<BaseClass>(symbol))\n        {\n            // hit!\n        }\n    }\n\n    private bool InheritsFrom<T>(INamedTypeSymbol symbol)\n    {\n        while (true)\n        {\n            if (symbol.ToString() == typeof(T).FullName)\n            {\n                return true;\n            }\n            if (symbol.BaseType != null)\n            {\n                symbol = symbol.BaseType;\n                continue;\n            }\n            break;\n        }\n        return false;\n    }\n}	0
7415068	7414847	open a web page on button click in form	private void button1_Click(object sender, EventArgs e)\n{           \n   //remove this from the constructor else it will be loaded along with the form\n    webBrowser1.Navigate("http://www.google.com");\n}	0
23149556	23112094	Select a file with remoting	public static List<string> getFiles()\n{\n  List<string> listReturn = new List<string>();\n  string[] filePaths = Directory.GetFiles(backupFolder);\n  return filePaths.ToList();\n}	0
29952730	29952605	Calculate the bit depth from the colour count of a gif	/// <summary>\n    /// Returns how many bits are required to store the specified\n    /// number of colors. Performs a Log2() on the value.\n    /// </summary>\n    /// <param name="colors"></param>\n    /// <returns></returns>\n    public static int GetBitsNeededForColorDepth(byte colors) {\n        return (int)Math.Ceiling(Math.Log(colors, 2));\n    }	0
26392320	26375842	How to enter commands in the debugger of Xamarin Studio	using MonoTouch.ObjCRuntime;\n\nvar str = new NSString (Messaging.IntPtr_objc_msgSend (UIApplication.SharedApplication.KeyWindow.Handle, new Selector ("_autolayoutTrace").Handle));	0
21755933	21755757	First Character of String Lowercase - C#	string s = "ConfigService";\n            if (s != string.Empty && char.IsUpper(s[0]))\n            {\n              s=  char.ToLower(s[0]) + s.Substring(1);\n            }\n            Console.WriteLine(s);	0
11560317	11546144	How to postback from jQuery Dialog to the parent page?	dlg.dialog({\n    autoOpen: false,\n    resizable: false,\n    draggable: false,\n    modal: true,\n    close: function (event, ui) {\n           // btnHidden is the id of the hidden button.\n           document.getElementById('<%=btnHidden.ClientID%>').click();\n           // To refresh gridview when user close dialog\n           }\n});	0
10128350	2583347	C# HttpListener without using netsh to register a URI	public static class NetAclChecker\n{\n    public static void AddAddress(string address)\n    {\n        AddAddress(address, Environment.UserDomainName, Environment.UserName);\n    }\n\n    public static void AddAddress(string address, string domain, string user)\n    {\n        string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);\n\n        ProcessStartInfo psi = new ProcessStartInfo("netsh", args);\n        psi.Verb = "runas";\n        psi.CreateNoWindow = true;\n        psi.WindowStyle = ProcessWindowStyle.Hidden;\n        psi.UseShellExecute = true;\n\n        Process.Start(psi).WaitForExit();\n    }\n}	0
4285418	4285386	NHibernate insert generates updates for collection items	HasMany(x => x.ChildNodes)\n           .Inverse()\n           .KeyColumns.Add("Parent_id")\n           .Cascade.All();	0
6569042	6569010	How to decompress GZip in Stream (C#)?	request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;	0
9861290	9861260	Overloading operator== for an interface	IEquatable<T>	0
15620839	15249291	Disable scroll through DataGridViewComboBoxColumn and scroll through datagridview	void DateGridView_CellClick(object sender, DataGridViewCellEventArgs e)\n{            \n    System.Windows.Forms.ComboBox comboBox = dataGridView.EditingControl as System.Windows.Forms.ComboBox;\n    if (comboBox != null)\n    {\n        comboBox.DropDownClosed += comboBox_DropDownClosed;\n    }\n}\n\nvoid comboBox_DropDownClosed(object sender, EventArgs e)\n{\n    (sender as System.Windows.Forms.ComboBox).DropDownClosed -= comboBox_DropDownClosed;\n    (sender as System.Windows.Forms.ComboBox).Parent.Focus();\n}	0
17755760	17748416	Delete empty root node in treeView	if (treeView1.SelectedNode != null)\n{\n    if (treeView1.SelectedNode.Parent == null) treeView1.SelectedNode.Remove();\n    else if (treeView1.SelectedNode.Parent.Nodes.Count == 1) treeView1.SelectedNode.Parent.Remove();\n    else treeView1.SelectedNode.Remove();\n}	0
15796751	15796440	Adding child nodes to a treeview in C#	if(carTree.SelectedNode == null)\n  MessageBox.Show("Please select a node first");    \n\ncarTree.SelectedNode.Nodes.Add(new TreeNode("Child"));	0
25457286	25457069	How to create proxy if you have more than one interface using ClientBase<T>?	public class ServiceProxy : IA, IB\n{\n    private ClientBase<IA> IAProxy {get;set;}\n    private ClientBase<IB> IBProxy {get;set;}    \n\n\n    public void IA.SomeInterfaceMethod(){   \n      IAProxy.SomeInterfaceMethod();\n    }\n\n    public void IB.SomeInterfaceMethod(){   \n      IBProxy.SomeInterfaceMethod();\n    }\n}	0
17296935	17296881	Passthru reading of all files in folder	using ( var mmf = MemoryMappedFile.CreateFromFile( path ) )\n{    \n    for ( long offset = 0 ; offset < file.Size ; offset += block_size )\n    {\n        using ( var acc = accessor = mmf.CreateViewAccessor(offset, 1) )\n        {\n            acc.ReadByte(offset);\n        }\n    }\n}	0
13268945	13267476	Cannot show waiting message while long operation is running in Mono for Android	private void bgWait_DoWork(object sender, DoWorkEventArgs e)\n{\n    Toast toastWait = null;\n    RunOnUIThread (() => \n    {\n        toastWait = Toast.MakeText(this, "Please wait", ToastLength.Long);\n        toastWait.SetGravity(GravityFlags.Top & GravityFlags.Center, 0, 0);\n        toastWait.Show();\n    });\n    TimeConsumingOperation();\n    RunOnUIThread (() =>\n    {\n        toastWait.Cancel(); \n    });\n}	0
2985555	2985534	Can the get of a property be abstract and the set be virtual?	public double Initial\n{\n    get { return GetInitial(); }\n    set { SetInitial(value); }\n}\n\nprotected virtual void SetInitial(double value)\n{\n    Count = 1;\n}\n\nprotected abstract double GetInitial();	0
2279893	2279830	Send url with querystring with SmtpClient	var client = new SmtpClient();\nclient.Host = "smtp.somehost.com";\nvar message = new MailMessage();\nmessage.From = new MailAddress("from@example.com");\nmessage.To.Add(new MailAddress("to@example.com"));\nmessage.IsBodyHtml = true;\nmessage.Subject = "test";\nstring url = HttpUtility.HtmlEncode("http://server.com/page.aspx?var1=foo&var2=bar");\nmessage.Body = "<html><body><a href=\"" + url + "\">Test</a></body></html>";\nclient.Send(message);	0
7481496	7481293	How to parse utc date	DateTime.ParseExact("Sat Aug 22 14:00:00 UTC+0200 2009", \n                    "ddd MMM d HH:mm:ss UTCzzzz yyyy", null);	0
10528169	10528120	Where to parse a large txt file ASP.NET	string fileContent = Cache["SampleFile"] as string;\nif (string.IsNullOrEmpty(fileContent))\n{\n    using (StreamReader sr = File.OpenText(Server.MapPath("~/SampleFile.txt")))\n   {\n       fileContent = sr.ReadToEnd();\n       Cache.Insert("SampleFile", fileContent, new System.Web.Caching.CacheDependency(Server.MapPath("~/SampleFile.txt")));\n   }\n}	0
29677008	29676801	Storing 3 different values in a single byte	int val = 0xBE;  //f.e. 1011 | 1110\nvar IsArrayMask = 0x80;     // 1000 0000\nvar ArrayLengthMask = 0x78; // 0111 1000\nvar DataTypeMask = 0x07;    // 0000 0111\n\nbool isArray = ((val & IsArrayMask) >> 7) == 1;  // output: true\n\n// as pointed out by @PeterSchneider & @knittl \n// you can get isArray in a probably more elegant way:\nisArray = (val & IsArrayMask) == IsArrayMask;\n\n// i keep both ways in my answer, because i think \n// the first one illustrates that you have to shift by 7 to get 1 (true) or 0 (false) \n\nint arrayLength = (val & ArrayLengthMask) >> 3;  // output: 7\nint dataType = (val & DataTypeMask);             // output: 6	0
25823735	25823674	Unable to insert data into MS Access database from Visual C#	OleDbCommand command = new OleDbCommand \n    ("INSERT INTO  TicketAndCottage (Cotumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change) \n                              Values(@Name , @DayorNight , @Adult1 ,@Kid , @Cottage1 , @Room, @Total1 , @Cash1 , @Change1)");	0
6321490	6319256	Culture is set to US in spite of PC region is set to UK	this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);	0
18032861	18032557	Access user control type from a dll?	//well then you can declare the interface as:\npublic interface ITextControl{\n string TextValue{get;set}\n}\n//and in your code:\npublic partical class whateveryourcontrolname:UserControl,ITextControl\n{\n/..../\npublic string TextValue{\n get{\n  return this.Text;\n }\nset{\n this.Text=value;\n }\n}\n}\n//and your method:\nvoid AddMethod(ITextControl txtCtrl){\n txtCtrl.TextValue="Yes";\n}	0
7026658	7026486	How to turn a string to a DateTime object in .NET Micro?	public DateTime(\n    int year,\n    int month,\n    int day,\n    int hour,\n    int minute,\n    int second,\n    int millisecond\n)	0
14701196	14700795	DateTime in SQL Server CE query?	cmd.Parameters.Add("@newTimeStamp", SqlDbType.DateTime).Value = timeStamp;	0
27110532	27110467	Use LINQ to transform single object into IEnumerable via Properties/reflection?	var bars = myFooEnumerable.SelectMany(\n    x => x.GetType().GetProperties().Select(p => new Bar {\n        DurationDescription = p.Name,\n        Value = (int)p.GetValue(x)\n    }));	0
10769608	10769472	How do I traverse three tables and get the maximum of a value	DateTime GetLastExecutionTime(ObjectContext context, string fileName)\n {\n    var query = from file in context.Files\n                    join history in context.FileHistories \n                        on file.FileID equals history.FileID\n                    join job in context.Jobs \n                        on history.JobID equals job.JobID\n                    where file.FileName == fileName\n                    select job.ExecutedOn;\n\n    var result = query.Max();\n }	0
28444340	28444288	Find the top left origin of a GroupBox's inner area	Button button = new Button { Text = "Hello!!!" };\nbutton.Location = groupBox.DisplayRectangle.Location;\ngroupBox.Controls.Add(button);	0
19237522	19236127	Search for string w/delimiter character	var lines= File.ReadAllLines(sPath);\nvar regex = new Regex(String.Format("(?<!-){0}\b", searchVariable));\n\nif (lines.Any())\n{\n using (var streamWriter = File.AppendText(rPath))\n {    \n  foreach (var line in lines) \n  {\n   if (regex.IsMatch(line))\n   {\n    streamWriter.WriteLine(line);\n   }  \n  }\n }\n}	0
22150670	22145984	Linq2Twitter - 401 : bad authentication data	var auth = new SingleUserAuthorizer\n        {\n            CredentialStore = new SingleUserInMemoryCredentialStore\n            {\n                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],\n                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],\n                AccessToken = ConfigurationManager.AppSettings["accessToken"],\n                AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"]\n            }\n        };	0
13783958	13072927	Create an XML from a DataTable	public static string ToXml(this DataTable table, int metaIndex = 0)\n{\n    XDocument xdoc = new XDocument(\n        new XElement(table.TableName,\n            from column in table.Columns.Cast<DataColumn>()\n            where column != table.Columns[metaIndex]\n            select new XElement(column.ColumnName,\n                from row in table.AsEnumerable()\n                select new XElement(row.Field<string>(metaIndex), row[column])\n                )\n            )\n        );\n\n    return xdoc.ToString();\n}	0
2127827	2127778	How to check if the resize is still in progress with OnResize event?	private void UserControl1_Load(object sender, EventArgs e)\n{\n    ((Form)this.Parent).ResizeEnd += new EventHandler(UserControl1_ResizeEnd);\n}\nvoid UserControl1_ResizeEnd(object sender, EventArgs e)\n{\n    MessageBox.Show("Resize end");\n}	0
3169387	3169338	ASP.NET File Upload - > Translation from PHP	protected void Page_Load(object sender, EventArgs e)\n    {\n        string filePath = "uploads/";\n\n        if (Request.Files.Count <= 0)\n        {\n            Response.Write("No file uploaded");\n        }\n        else\n        {\n            for (int i = 0; i < Request.Files.Count; ++i)\n            {\n                HttpPostedFile file = Request.Files[i];\n                file.SaveAs(Server.MapPath(filePath + file.FileName));\n                Response.Write("File uploaded");\n            }\n        }\n\n    }	0
199332	199238	How can I find the position where a string is malformed XML (in C#)?	string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n\ntry\n{\n    doc.LoadXml(s);\n}\ncatch(System.Xml.XmlException ex)\n{\n    MessageBox.Show(ex.LineNumber.ToString());\n    MessageBox.Show(ex.LinePosition.ToString());\n}	0
8116231	8115989	Set private field within constructor using set validation from property	class Account\n{\n    private decimal acctBalance = 0;\n\n    public decimal AcctBalance\n    {\n        get\n        {\n            return acctBalance;\n        }\n        set\n        {\n            //modified to check value instead of acctBalance\n            if (value >= 0)\n                acctBalance = value;\n            else\n            {\n                Console.WriteLine("Invalid balance, balance set to 0");\n                acctBalance = 0;\n            }\n        }\n    }\n\n    public Account(decimal balance)\n    {\n        //redundant! Changing AcctBalance changes acctBalance\n        //acctBalance = balance;\n        AcctBalance = balance; \n    }\n}	0
12158401	12158123	How to achieve desired JSON format using C#.NET HashTable	var list = new ArrayList();\nlist.Add(new { Area = 1000 });\nlist.Add(new { Perimeter = 55 });\nlist.Add(new { Mortgage = 540 });\n\nvar s1 = new JavaScriptSerializer().Serialize(new { DoWorkResult = list });\nvar s2 = JsonConvert.SerializeObject(new { DoWorkResult = list });	0
12004505	11988342	Trouble Reading an entry from a DataGridRow	private void OnFindItem(object sender, RoutedEventArgs e)\n    {\n        ListViewItem output = e.Source as ListViewItem;\n\n        if (output != null)\n        {\n            DataRowView rowView = output.Content as DataRowView;\n            if (rowView != null)\n            {\n                //More code here.\n            }\n         }\n     }	0
7153154	7153095	Adding a line to a file	foreach (string key in ordered)\n{\n    var splitKey = key.Split(' ');\n    if (!splitKey[1].Contains("8")) {\n        sw.WriteLine("( {0} 0 1 1 0 0 0 0 "" "" "" 0 0 0 0 0 )", j);\n        j++;\n    }\n    sw.WriteLine(\n        "( {0} 0 1 1 0 0 0 0 \"{1}\" \"{2}\" \"\" {3} 0 0 0 0 0 )",\n        j, splitKey[0], splitKey[1], dictionary[key]);\n    j++;\n}	0
18633328	18426049	Display Dataset in gridview ( C# windows application)	DataSet ds = new DataSet();\n        ds.ReadXml(strFileName); // strFileName is XML File path\n        dataGridView1.DataSource = ds.Tables[0];	0
30374759	30373639	MapHttpRoute with custom HttpMessageHandler	[Route("getprojects")] // <--- COMMENT/REMOVE THIS LINE	0
6362190	6362088	C# date formatting is losing slash separators	Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy", CultureInfo.InvariantCulture));\n            Console.ReadLine();	0
2798493	2798467	C# code to GZip and upload a string to Amazon S3	MemoryStream ms = new MemoryStream();\n\nusing (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))\n{\n    byte[] buffer = Encoding.UTF8.GetBytes(content);\n    zip.Write(buffer, 0, buffer.Length);\n    zip.Flush();\n}\n\nms.Position = 0;\n\nPutObjectRequest request = new PutObjectRequest();\nrequest.InputStream = ms;\nrequest.Key = AWSS3PrefixPath + "/" + keyName+ ".htm.gz";\nrequest.BucketName = AWSS3BuckenName;\n\nusing (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(\n                             AWSAccessKeyID, AWSSecretAccessKeyID))\nusing (S3Response putResponse = client.PutObject(request))\n{\n    //process response\n}	0
6336953	6336929	Linq XML won't select specified xml elements	var elems = doc.Descendants().Where(e=> e.Name.LocalName == "Link");\nforeach (XElement elem in elems)\n{\n    Console.WriteLine(elem.Name.LocalName);\n}	0
32248295	32230844	Removing Extra WCF namespace from WSDL	ChannelFactory<T>.CreateInstance()	0
4937321	4936051	Is there a standard simple string deserialization interface/pattern for .NET?	var conv = TypeDescriptor.GetConverter(type);\nobject value = conv.ConvertFromInvariantString(s);	0
5452056	5419207	Facebook C# SDK - Using a array in Api calls like in PHP	var parameters = new Dictionary<string, object>() {\n    { "method", "events.invite" },\n    { "eid", IdEvent },\n    { "uids", "100000339376504" }\n};\nvar users = app.Api(parameters);	0
5727168	5727141	C#: In a finalizer, how to find out if the application is shutting down?	System.Environment.HasShutdownStarted	0
1731018	1731006	Can a Type Derive from Itself?	where T : <base class name>	0
29609176	29608964	Group by multiple columns at the same time	IEnumerable<Emlpoyee> grouped= employees.GroupBy(o => new { o.Start, o.End });	0
24041217	23826139	How to generate call to base constructor with VarArgs using ILGenerator	var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Foo"), AssemblyBuilderAccess.RunAndSave);\nvar mb = ab.DefineDynamicModule(ab.GetName().Name, ab.GetName().Name + ".dll", true);\nvar tb = mb.DefineType("Foo", TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.Public, typeof(VarArgTest));\nvar ctor = tb.DefineConstructor(MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.HasThis, Type.EmptyTypes);\nvar il = ctor.GetILGenerator();\nvar token= mb.GetConstructorToken(typeof(VarArgTest).GetConstructors()[0], new[] { typeof(string), typeof(int) });\nil.Emit(OpCodes.Ldarg_0);\nil.Emit(OpCodes.Ldstr, "foo");\nil.Emit(OpCodes.Ldstr, "one");\nil.Emit(OpCodes.Ldc_I4_2);\nil.Emit(OpCodes.Call,token.Token);\nil.Emit(OpCodes.Ret);\nvar v = Activator.CreateInstance(tb.CreateType());\nConsole.WriteLine((v as VarArgTest).CountOfArgs);	0
11736114	11736021	C# How to detect whether there is a '/' character?	string arrStr = "192.168.1.1/192.168.1.12/192.168.1.118";\nchar[] separator = new char[] { '/' };\nstring[] strSplitArr = arrStr.Split(separator);\n\nstring IP1 = strSplitArr[0];\nstring IP2 = strSplitArr[1];\nstring IP3 = strSplitArr[2];	0
6147112	5988558	Securing Crystal Reports using Parameter Fields , Validating Parameter Fields	(your previous record selection) AND {?Password} = "yourpassword"	0
13286289	13285964	Calculate Current Speed in .NET - With GPS	private static double ArcInMeters(double lat0, double lon0, double lat1, double lon1)\n{\n    double earthRadius = 6372797.560856; // m\n    return earthRadius * ArcInRadians(lat0, lon0, lat1, lon1);\n}\n\nprivate static double ArcInRadians(double lat0, double lon0, double lat1, double lon1)\n{\n    double latitudeArc = DegToRad(lat0 - lat1);\n    double longitudeArc = DegToRad(lon0 - lon1);\n    double latitudeH = Math.Sin(latitudeArc * 0.5);\n    latitudeH *= latitudeH;\n    double lontitudeH = Math.Sin(longitudeArc * 0.5);\n    lontitudeH *= lontitudeH;\n    double tmp = Math.Cos(DegToRad(lat0)) * Math.Cos(DegToRad(lat1));\n    return 2.0 * Math.Asin(Math.Sqrt(latitudeH + tmp * lontitudeH));\n}\n\nprivate static double DegToRad(double x)\n{\n    return x * Math.PI / 180;\n}	0
6279271	844467	C# auto detect proxy settings	WebProxy proxy = (WebProxy) WebRequest.DefaultWebProxy;\nif (proxy.Address.AbsoluteUri != string.Empty)\n{\n    Console.WriteLine("Proxy URL: " + proxy.Address.AbsoluteUri);\n    wc.Proxy = proxy;\n}	0
6422950	6414367	Publishing a custom presence message in OCS2007 R2 using UCMA 2.0 (visible in MOC)	string userStateXmlFormat = "<state xmlns=\"http://schemas.microsoft.com/2006/09/sip/state\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" manual=\"true\" xsi:type=\"userState\">\n"\n  + "<availability>{0}</availability>\n"\n  + "<activity>\n" \n    + "<custom LCID=\"1033\" xmlns=\"http://schemas.microsoft.com/2006/09/sip/state\">{1}</custom>\n"\n    + "<custom LCID=\"2057\" xmlns=\"http://schemas.microsoft.com/2006/09/sip/state\">{1}</custom>\n" \n  + "</activity>\n"\n+ "</state>";	0
9500117	9500029	DataContract and custom set/get to set a DateTime from a string	[DataMember(Name="Foo")]\npublic string FormattedFoo {\n    get { return /* apply some custom formatting to 'Foo' */; }\n    set { Foo = /* apply some custom parsing to 'value' */; }\n}\npublic DateTime Foo {get;set;}	0
20711736	20711704	How to create a copy of the items in a domainupdown C#	copiedNUD.Items.Add(this.sentNUD2.Items[i]); //fixed naming	0
17103659	17103572	C# XML several occurrences of a same element	[XmlElement("c")]\npublic List<c> cList { get; set; }	0
9003108	9002834	Finding a value in a MS Access table in c#	string QueryDate = monthCalendar1.SelectionRange.Start.ToString();\nQueryDate = QueryDate.Substring(0, 10);\n\nstring connstr = "Provider=Microsoft.Jet.Oledb.4.0;DataSource=data.mdb";\nstring query = "Select Rezerve from 101 Where Tarih=@QueryDate";\n\nusing (OleDbConnection dc = new OleDbConnection(connstr))\n{\n    OleDbCommand sqlcmd = new OleDbCommand(query, conn);\n    sqlcmd.Parameters.AddWithValue("@QueryDate", QueryDate);\n    bool Rezerve = (bool)sqlcmd.ExecuteScalar();\n}\n\nswitch (Rezerve) \n{ \n    Case true: \n        //true stuff \n        break; \n    Case false: \n        //false stuff \n        Break; \n    Default: \n        //No Return \n        Break; \n}	0
14124688	14118956	Unit Testing Windows 8 Store App UI (Xaml Controls)	[TestMethod]\nasync public Task CreateThumbnail_EmptyLayout_ReturnsEmptyGrid()\n{\n    int count = 0;\n    await ExecuteOnUIThread(() =>\n    {\n        Layout l = new Layout();\n        ThumbnailCreator creator = new ThumbnailCreator();\n        Grid grid = creator.CreateThumbnail(l, 192, 120);\n        count = grid.Children.Count;\n    });\n\n    Assert.AreEqual(count, 0);\n}\n\npublic static IAsyncAction ExecuteOnUIThread(Windows.UI.Core.DispatchedHandler action)\n{\n    return Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action);\n}	0
30777377	30759026	LINQ many to many relationship - get a list of grouped objects	var projects= from p in db.Projects select new{ project_Id = p.Project_Id, projectName = p.ProjectName, userList = p.Projects-Users.Select(pu=>pu.Users.UserName).ToList()};	0
12331610	11731996	String Format Numbers Thousands 123K, Millions 123M, Billions 123B	double value = 1234567890;\n\n  // Displays 1,234,567,890   \n  Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));\n\n  // Displays 1,234,568K\n  Console.WriteLine(value.ToString("#,##0,K", CultureInfo.InvariantCulture));\n\n  // Displays 1,235M\n  Console.WriteLine(value.ToString("#,##0,,M", CultureInfo.InvariantCulture));\n\n  // Displays 1B\n  Console.WriteLine(value.ToString("#,##0,,,B", CultureInfo.InvariantCulture));	0
3008040	3007972	How to check user input for correct formatting	if (!System.Text.RegularExpressions.Regex.IsMatch("your_text", "G[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2} JG[0-9]{2}"))\n    {\n        //Error!\n    }	0
2476933	1985542	TranslatePoint within a Canvas	private static Point GetCanvasChildPosition(FrameworkElement element)\n{\n    var canvas = element.Parent as Canvas;\n\n    double left = Canvas.GetLeft(element);\n    double top = Canvas.GetTop(element);\n\n    bool isLeftAligned = !double.IsNaN(left);\n    bool isTopAligned = !double.IsNaN(top);\n\n    double x;\n    double y;\n\n    if (isLeftAligned)\n    {\n        x = left;\n    }\n    else\n    {\n        x = canvas.Width - Canvas.GetRight(element) - element.Width;\n    }\n\n    if (isTopAligned)\n    {\n        y = top;\n    }\n    else\n    {\n        y = canvas.Height - Canvas.GetBottom(element) - element.Height;\n    }\n\n    return new Point(x, y);\n}	0
8348824	8348779	Typing into a ComboBox in C#	comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;\ncomboBox1.AutoCompleteSource = AutoCompleteSource.HistoryList;	0
32939806	32939769	How to check if type implements ICollection<T>	bool implements = \n    listType.GetInterfaces()\n    .Any(x =>\n        x.IsGenericType &&\n        x.GetGenericTypeDefinition() == typeof (ICollection<>));	0
19657507	19638188	Closing modal window on loaded event	.ShowDialog();	0
16154404	16154359	Accessing a list of class from within another class - null reference exception	txt_out.Text = sort.listofRec.Count().ToString(); //writing out its count to a textbox	0
21020290	21019574	How to create MySql Update Command to work with DataGridView?	private void dtg_contatos_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n        {\n            string query;\n            string name;\n            string cod;\n\n            for (int i = 0; i < dtg_contatos.ColumnCount; i++)\n            {\n                if (i == 0)\n                {\n                    cod = dtg_contatos[i, e.RowIndex].Value.ToString();\n                }\n                if (i == 1)\n                {\n                    name = dtg_contatos[i, e.RowIndex].Value.ToString();\n                }\n            }\n            query = "update table set name = '" + name + "' where cod = '" + cod + "';";\n        }	0
10923017	10920581	Group by on a List And Return Top 1 Row	var items = zebra\n .Where(v => v.Key.StartsWith("alpha"))\n .GroupBy(pair => pair.Value)\n .Select(group => group.First())\n .ToArray();\n\n foreach(var item in items)\n   Console.WriteLine("{0}, {1}", item.Key, item.Value);	0
20424172	20423846	Populating an asp:Image with an image selected within an asp:FileUpload control	var input = document.getElementById('fileUp');\nvar img = document.getElementById('img1');\n\nif (input.files && input.files[0]) {\n    var reader = new FileReader();\n\n    reader.onload = function (e) {\n        img.src =  e.target.result;\n    }\n    reader.readAsDataURL(input.files[0]);\n}	0
5184771	5184702	How do you find an element index in a Collection<T> inherited class?	var index = collectionInstance.Select( (item, index) => new {Item = item, Index = index}).First(i => i.Item == SomeCondition()).Index;	0
13127120	13126673	Is it possible to make the user enter a date in an exact date format using DataAnnotations?	[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:MM/dd/yyyy}")]	0
7273057	7271550	removing RichTextBox lines while keeping the colour of remaining lines in C#	richTextBox1.SelectionStart = 0;\n   richTextBox1.SelectionLength = richTextBox1.GetFirstCharIndexFromLine(200);\n   richTextBox1.SelectedText = "";	0
28894259	28880301	ListView OwnerDraw with AllowColumnReorder don't work correct	private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)\n    {\n        Rectangle bounds = e.Bounds;\n        if (e.ColumnIndex == 0 && listView1.Columns[0].DisplayIndex != 0)\n        {\n            bounds = GetFirstColumnCorrectRectangle(e.Item);\n        }\n        e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, bounds);\n    }\n\n    private Rectangle GetFirstColumnCorrectRectangle(ListViewItem item)\n    {\n        int i;\n        for (i = 0; i < listView1.Columns.Count; i++)\n            if (listView1.Columns[i].DisplayIndex == listView1.Columns[0].DisplayIndex - 1)\n                break;\n        return new Rectangle(item.SubItems[i].Bounds.Right, item.SubItems[i].Bounds.Y, listView1.Columns[0].Width, item.SubItems[i].Bounds.Height);\n    }	0
34419632	34417507	How to edit the row in a GridView and update the values of the row	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)\n {\n      // string s = GridView1.DataKeys[e.RowIndex].Value.ToString();           \n      Label EmployeeID = GridView1.Rows[e.RowIndex].FindControl(?EmployeeID?) as Label;\n      TextBox LastName = GridView1.Rows[e.RowIndex].FindControl(?txtLastName?) as TextBox;\n      TextBox Title = GridView1.Rows[e.RowIndex].FindControl(?txtTitle?) as TextBox;\n      TextBox Country = GridView1.Rows[e.RowIndex].FindControl(?txtCountry?) as TextBox;\n      String UpdateQuery = string.Format(?UPDATE Employees SET LastName='{0}?,\n                    Title='{1}?,Country='{2}? WHERE EmployeeID = {3}?,LastName.Text, Title.Text, Country.Text, Convert.ToInt32(EmployeeID.Text));\n\n       GridView1.EditIndex = -1; //set back to the normalgridview from editview\n       UpdateGrid(UpdateQuery); // updates the table Employees\n       BindGridData(); //binds the data to grid again.\n  }	0
30552420	30548093	DocumentDb - get Json representation of Document	delete doc._rid;\ndelete doc._ts;\ndelete doc._etag;\ngetContext().getResponse().setBody(doc);	0
12485848	12485809	How to generate JSON for dynamic data	using System.Web.Script.Serialization.JavaScriptSerializer;    \nJavaScriptSerializer oSerializer = new JavaScriptSerializer();\nstring JSON = oSerializer.Serialize(yourDict);	0
20292202	20292121	Julian date string to DateTime	string julianDate = "13324";\n\nint jDate = Convert.ToInt32(julianDate);\nint day = jDate % 1000;\nint year = (jDate - day) / 1000;\nvar date1 = new DateTime(year, 1, 1);\nvar result = date1.AddDays(day - 1);	0
12459997	12459725	Correctly disposing user control and its children	class MyClass : IDisposable\n{ \n    internal Grid _grid = new Grid(); \n    internal Image _image = new Image() {Width = Double.NaN, Height = Double.NaN HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Stretch = Stretch.Fill}; \n    //... a lot of variables, data, images and methods... \n\n    public void Dispose()\n    {\n        // your custom disposing \n        _image = null; //or something like that\n    }\n}	0
30661553	30639189	windows phone 8 c# httpclient dosent send request for second time	hc.DefaultRequestHeaders.IfModifiedSince = DateTime.Now;	0
11885927	11885735	FindControl can't find a control	protected void OnCheckedChangedMethod(object sender, EventArgs e)\n{            \n    this.RequiredFieldValidator1.Visible = this.Extern.Checked;\n}	0
12606258	12605847	P/Invoke, trouble finding/declaring function entry point	[DllImport("mgsc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]\npublic static extern Int32 MgScSCardUIDlgSelectCardW(ref ModWinsCard.OPENCARDNAME_EX ocnwex);	0
190308	190299	How to determine the file size from an attachment to a POP3 message	string x = GetBase64DataFromWherever();\nint size = (x.Length *3)/4;\nif (x.EndsWith("="))\n{\n    size--;\n}\nif (x.EndsWith("=="))\n{\n    size--; // 1 will already have been removed by the if statement above\n}	0
7225597	7225575	How to check and display empty columns or rows in GridView?	.Select(columns => new {GuestName = ValueOrErrorMessage(columns[0]), Guest_ID = ValueOrErrorMessage(columns[1]), IC_Number = ValueOrErrorMessage(columns[2])}); \n      ...\n\nprivate string ValueOrErrorMessage(string input){\n   if(!string.IsNullOrEmpty(input))\n      return input;\n   }\n   return "no value"\n}	0
25541653	25541560	Create a List of hours	var hours = Enumerable.Range(00, 24).Select(i => (DateTime.MinValue.AddHours(i)).ToString("hh.mm tt"));	0
13430972	13430926	Check status of the server continuously	return reply.Status == IPStatus.Success;	0
30719075	30718953	How to go one step above in a folder path by using AppDomain.CurrentDomain.BaseDirectory in c#	string dirName = AppDomain.CurrentDomain.BaseDirectory; // Starting Dir\n        FileInfo fileInfo = new FileInfo(dirName);\n        DirectoryInfo parentDir = fileInfo.Directory.Parent;\n        string parentDirName = parentDir.FullName; // Parent of Starting Dir	0
7931867	7909644	Custom AppDomainManager fails to start runtimeHost	hr = clrControl->SetAppDomainManagerType(L"ExceptionThrower, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d3b6b01f2067f563",L"ExceptionThrower.HostAppDomainManager");	0
8777092	8773320	How to get visitor browser type and OS on apache	\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers\	0
6592456	6591135	Extract contents from XML file	string url = @"e:\temp\data.xml";\n\n        XmlDocument doc = new System.Xml.XmlDocument();\n        doc.Load(url);\n        XmlElement docElement = doc.DocumentElement;\n\n        /// loop through all childNodes\n        foreach (XmlNode childNode in docElement.ChildNodes)\n        {\n            Console.WriteLine(childNode.Name + ": " + childNode.InnerText);\n        }\n\n        XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);\n        mgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-05-27T03:57:48");\n\n        /// use the given XmlNamespaceManager to select a specific element\n        XmlNode node = docElement.SelectSingleNode("my:VM_DiskSize", mgr);\n        /// use innerText for node text and value for attributes only\n        Console.WriteLine("\n" + node.Name + ": " + node.InnerText);	0
19382942	19370304	How to decompress MSZIP files with c#?	CabInfo cab = new CabInfo(@"C:\test\image.jp_");\ncab.Unpack(@"C:\test\");	0
26180366	26179973	Create a method to calculate Linear Interpolation in C#	public static DateTime Interpolate(DateTime x0, double y0, DateTime x1, double y1, double target)\n{\n  //this will be your seconds per y\n  double rate = (x1 - x0).TotalSeconds / (y1 - y0);\n  //next you have to compute the distance between one of your points and the target point on the known axis\n  double yDistance = target - y0;\n  //and then return the datetime that goes along with that point\n  return x0.AddSeconds(rate * yDistance);\n}	0
22564680	22564349	Extra new lines in Plain text email via SendGrid	mailMessage.BodyEncoding = Encoding.UTF8;	0
11676834	11676734	How to retrieve the collection defined as a ICollection navigation property for a given entity in EF ASP.NET MVC3	List<B> bs = YourDBContext.Bs.Where(b => b.A.ID == someID).ToList();	0
20260629	20259761	how to make dictionary of a list using dynamic key in c#	public class Tour\n{\n    public int Id{get;set;}\n    public string Name{get;set;}\n    public string City{get;set;}\n}\n\npublic Dictionary<int,object> GetDictionary(string KeyName, List<object> list)\n{\n    var dictionary  = Dictionary<int,object>();\n    foreach(var obj in list>\n    {\n         dictionary.Add(GetPropValue(obj,KeyName);\n    }\n    return dictionary;\n}\n\npublic object GetPropValue(object src, string propName)\n{\n     return src.GetType().GetProperty(propName).GetValue(src, null);\n}	0
23188685	23188656	how to select the highest values of each row of an array?	function int[] GetMaxValues(int[] Arr)\n{\n    int[] Max = new int[Arr.GetLength(0)];\n\n    for (int i = 0; i < Arr.GetLength(0); i++)\n    {\n        Max[i] = int.MinValue;\n        for (int l = 0; l < Arr.GetLength(1); l++)\n            if (Arr[i, l] > Max[i])\n                Max[i] = Arr[i, l];\n    }\n\n    return Max;\n}	0
21558997	21534722	Managing / Hiding Specific Assembly Dependies	[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]\npublic class AppSettingsFromConfigAttribute : Attribute {}	0
150974	138043	Find the next TCP port in .Net	static int FreeTcpPort()\n{\n  TcpListener l = new TcpListener(IPAddress.Loopback, 0);\n  l.Start();\n  int port = ((IPEndPoint)l.LocalEndpoint).Port;\n  l.Stop();\n  return port;\n}	0
23215641	23215352	How to convert linq expression to dictionary<string,string>	var dictionary = bookListRecord\n    .GroupBy(g => g.CourseCode)\n    .Select(g => new { g.Key, \n      AreaList = g.Select(c => c.Area).ToList(), \n      Area = g.Select(c => c.Area).FirstOrDefault() })\n    .ToDictionary(g => g.Key);	0
3814099	3814000	problem sending mail from my website using gmail-mailservers	MailMessage message = new MailMessage(from, to, subject, body);\n            message.IsBodyHtml = true;\n            message.Priority = MailPriority.High;\n            SmtpClient mailClient = new SmtpClient();\n            mailClient.Credentials = new System.Net.NetworkCredential\n                    ("___@gmail.com", "__________");\n            mailClient.Port = 587;\n            mailClient.Host = "smtp.gmail.com";\n            mailClient.EnableSsl = true;\n            mailClient.Send(message);\n            message.Dispose();	0
8905192	6527516	Cannot change date value of MySQL bound text box	dateTimePicker.DataBindings.Add("Value", dataSet.Tables[0], "programsUpdated");	0
5301286	5301201	How to force a sign when formatting an Int in c#	i.ToString("+00;-00;+00");	0
8843541	8841146	How can I use Matlab objects in compiled .NET assemblies?	function CreateMyClass(st)\n    global myClass;\n    myClass = MyClass(st);\nend\n\nfunction DisplayMyClass()\n    global myClass;\n    myClass.display();\nend	0
3094578	3094458	how disable / enable An Ajaxifeid Button From Client Side (JavaScript)	window.onload = function(){\n    document.getElementById("btnSend").disabled = true;\n};	0
32486089	32485606	How to make column font bold in a listview using C#?	using (Font f = new Font(lv1.Items(0).SubItems(0).Font, FontStyle.Bold)) \n {\n\n  foreach (ListViewItem lvi in lvTotalCollateral.Items)\n   {\n\n      lvi.UseItemStyleForSubItems = False;\n      lvi.SubItems[12].Font = f;\n     }\n  }	0
359311	359298	Convert Float that has period instead of comma?	Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat);	0
23286985	23286904	Passing a parameter to a delegate method	private void RequestInfo(string a, string b)\n{\n   var c = a+b;\n   library.FetchInfo(c, obj => dictionaryOfInfo.Add(c, obj));\n}	0
1542577	1542544	C# sort list of strings with specific scandinavian culture in mind	List<string> s = new List<string>();\n            s.Sort(delegate(string item1, string item2) { return String.Compare(item1,item2, false, new CultureInfo("")); });	0
33575279	33484341	C# .Net - How to make application wait until all threads created in Library are finished	/// <summary>\n    /// Makes the current thread Wait until any of the pending messages/Exceptions/Logs are completly written into respective sources.\n    /// Call this method before application is shutdown to make sure all logs are saved properly.\n    /// </summary>\n    public static void WaitForLogComplete()\n    {\n        Task.WaitAll(tasks.Values.ToArray());\n    }	0
20644165	17877854	How to determine order of combination in Rejuicer?	OnRequest.ForJs("~/combined-{0}.js")\n\n  .Combine\n  .File("~/Scripts/orange.js")\n  .File("~/Scripts/apple.js")\n  .File("~/Scripts/banana.js")\n  .Configure();	0
265181	264962	How to search a string in String array	string [] arr = {"One","Two","Three"};\n       var target = "One";\n       var results = Array.FindAll(arr, s => s.Equals(target));	0
15253355	15253313	optional type parameter for constructor	public class MyClass\n{\n    MyClass()\n    {\n       ....\n    }\n    MyClass(SomeOtherObject TheObject)\n    {\n       ....\n    }\n}	0
6241892	6220660	Calculating the length of MP3 Frames in milliseconds	float frameTime = totalTimeMillisec / totalFrames;	0
8991380	8991153	Does a compound key in EF work?	HasKey(x => new { x.AID, x.BID});	0
14480915	14479200	Composer and custom controls	protected PageData CurrentParentPage\n        {\n            get\n            {\n                var currentParentPage = PageReference.ParseUrl(Page.Request.UrlReferrer.AbsoluteUri);\n                if(!PageReference.IsNullOrEmpty(currentParentPage))\n                {\n                    return currentParentPage.GetPageFromReference();\n                }\n                return null;\n            }\n        }	0
9770519	9770460	C# Faster generation of MD5 hashes	static string generateHash(string input)\n{\n  MD5 md5Hasher = MD5.Create();\n  byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));\n  return BitConverter.ToString(data);\n}	0
18128677	18128537	C# How to loop through Progress Bar perfectly	progressBar1.Maximum = files.Length;	0
23559497	23557779	Getting a managed callback from a WRL COM component	[uuid(3FBED04F-EFA7-4D92-B04D-59BD8B1B055E), version(NTDDI_WIN8)]\ndelegate HRESULT WhateverEvent();	0
23946094	23946070	How to trim ',' in a string on c#	string.Replace	0
10576412	10576375	How to map a collection of objects using LINQ to SQL?	public partial class Order\n{\n    public IEnumerable<Product> Products\n    {\n        get\n        {\n            return OrderProducts.Select(op => op.Product);\n        }\n    }\n}	0
32571773	32571728	Can I use a ternary operator to set a generic method parameter?	var result = addressRequest != null\n    ? Utility.Serialize(addressRequest)\n    : Utility.Serialize(billingSiteIDHouseNumberRequest);	0
8507669	8507256	Iterate through TabItems in a TabControl	tabControl.SelectedIndex = i;\n-->        UpdateLayout();\n        Button_Click(null, null);	0
8522593	8511272	SATO USB printing in C#	PrintCommand = "<STX><ESC>A<ESC>IG1<ESC>Z<ETX><STX><ESC>A<ESC>#E3<ESC>Z<ETX><STX><ESC>A<ESC>CS5<ESC>Z<ETX><STX><ESC>A<ESC>EX0<ESC>Z<ETX><STX><ESC>A<ESC>*&<ESC>Z<ETX><STX><ESC>A<ESC>A3H0001V0001<ESC>Z<ETX><STX><ESC>A<ESC>V0000<ESC>H0259<ESC>F001+002<ESC>D202099" + EmployeeNo + YearNumber + FirstTraceCode + "<ESC>L0203<ESC>H0247<ESC>V0114<ESC>F001+002<ESC>U" + EmployeeNo.Substring(0, 2) + "-" + EmployeeNo.Substring(2, 4) + "-" + YearNumber + "-" + FirstTraceCode + "<ESC>V0000<ESC>H0589<ESC>F001+002<ESC>D202099" + EmployeeNo + YearNumber + SecondTraceCode + "<ESC>L0203<ESC>H0577<ESC>V0114<ESC>F001+002<ESC>U" + EmployeeNo.Substring(0, 2) + "-" + EmployeeNo.Substring(2, 4) + "-" + YearNumber + "-" + SecondTraceCode + "<ESC>Q" + LabelQuantity + "<ESC>00<ESC>Z<ETX>";\nPrintCommand = PrintCommand.Replace("<STX>", ((char)02).ToString());\nPrintCommand = PrintCommand.Replace("<ETX>", ((char)03).ToString());\nPrintCommand = PrintCommand.Replace("<ESC>", ((char)27).ToString());	0
31161808	31146540	Is it possible to create a MS Access database using OLEDB?	create table	0
631153	631126	How to bound a DataGridViewComboBoxColumn to a object?	column.DataPropertyName = "Foo";\ncolumn.DisplayMember = "SomeNameField"; \ncolumn.ValueMember = "Bar"; // must do this, empty string causes it to be \n                            // of type string, basically the display value\n                            // probably a bug in .NET\ncolumn.DataSource = from foo in Foo select foo;\ngrid.DataSource = data;	0
30787821	30787580	Updating a property in the viewModel	App.Current.Dispatcher.Invoke(new Action(()=>\n{ \n    //The code I want to run on the UI thread.\n}));	0
22434013	22433983	How to skip several iterations of a for loop	i+= 5;\ncontinue;	0
7164576	7164439	WPF: How to extract Scrollbar From ScrollViewer programmatically?	myScrollViewer.ApplyTemplate();\n\nScrollBar s = myScrollViewer.Template.FindName("PART_VerticalScrollBar", myScrollViewer) as ScrollBar;	0
19677720	19677564	Asp.net method with generic parameter	public void HandleAPIResponse<T>(APIResponse<T> apiResponse)\n{\n    if (apiResponse.HasError)\n        throw new Exception(apiResponse.Error.ErrorMessage);\n}	0
21250075	21249980	open xml sdk read excel formula cell	document.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;\ndocument.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;	0
19223674	19222612	Extract specific subfolder from Zip	using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(path.FullName))\n{\n       var selection = (from e in zip1.Entries\n                      where (e.FileName).StartsWith("Binaries/")\n                                 select e);\n\n\n     Directory.CreateDirectory(_localExtratingPath.FullName);\n\n     foreach (var e in selection)\n     {\n         e.Extract(_localExtratingPath.FullName);\n     }\n}	0
23957013	23956917	How to use multiple parameters in a SQL queries	sqlCode = "SELECT * FROM [db].[dbo].[TablePDFTest] WHERE [name] = @name AND [ssn3] =@ssn3";\n\nusing (SqlCommand command = new SqlCommand(sqlCode, Conn))\n{\n      //command.CommandType = CommandType.Text;\n      command.Parameters.AddWithValue("@name", nameE);\n      command.Parameters.AddWithValue("@ssn3", c);\n\n      using (reader = command.ExecuteReader())\n      {\n        // some action goes here...\n      }\n }	0
4311577	4311537	string.compare and string for comparison	if (string.Compare((string) cmbOperations.SelectedItem, \n        "NonForeignKeyTables", true) == 0) // 0 result means same\n    GetNonForeignKeyTables();	0
21281490	21281302	WCF with transport security via certificates	netsh http add sslcert [Ipaddress:port] certhash=[thumbprint of certifcate] \nappid={unique id for application.you can use GUID for this]\n\n\n[Ipaddress:port] Ipaddress and port\n[thumbprint of certifcate]: thumbprint of certificate without spaces\nappid :unique id you can use guid	0
12138532	12081167	Composing a WM_TOUCH message for SendMessage(), Kinect as a multi-touch device	[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]\npublic struct TOUCHINPUT {\n    /// LONG->int\n    public int x;\n    /// LONG->int\n    public int y;\n    /// HANDLE->void*\n    public System.IntPtr hSource;\n    /// DWORD->unsigned int\n    public uint dwID;\n    /// DWORD->unsigned int\n    public uint dwFlags;\n    /// DWORD->unsigned int\n    public uint dwMask;\n    /// DWORD->unsigned int\n    public uint dwTime;\n    /// ULONG_PTR->unsigned int\n    public uint dwExtraInfo;\n    /// DWORD->unsigned int\n    public uint cxContact;\n    /// DWORD->unsigned int\n    public uint cyContact;\n}	0
22139721	22139166	App_Data folder shadow folder empty	"Could not find the file 'C:\Program Files (x86)\IIS Express\testFile.csv'"	0
18651676	18651320	copying a node and saving it as a new xml file c#	var xDoc = XDocument.Load(fname);\n\nforeach (var item in xDoc.XPathSelectElements("/items/superitem/item[@id!='20']"))\n    item.Remove();\n\nxDoc.Save(fname);	0
21527396	21527214	How to rewrite to Task<T> for performance gain?	//Producer\nTask.Factory.StartNew(() =>\n    {\n        for(int i=0;i<100000000;i++)\n        {\n            sendQueue.Add(new SimpleObject() { Key = "", Value = "" });\n        }\n        sendQueue.CompleteAdding();\n    });\n\n//Consumer\nTask.Factory.StartNew(() =>\n    {\n        foreach(var so in sendQueue.GetConsumingEnumerable())\n        {\n            //do something\n        }\n    });	0
1295537	1294698	Populating HtmlTable Control with HtmlTable object in ASP/C#	foreach (Evaluation eval in theEvaluations)\n{\n    HtmlTableRow anEvaluation = new HtmlTableRow();\n    HtmlTableCell cell1 = new HtmlTableCell();\n    HtmlTableCell cell2 = new HtmlTableCell();\n\n\n    cell1.InnerText = eval.attr1;\n    anEvaluation.Cells.Add(cell1);\n\n    cell2.InnerText = eval.attr2;\n    anEvaluation.Cells.Add(cell2);\n\n    table1.Rows.Add(anEvaluation);  // table1 : the real HTML table in ASP page\n}	0
32687497	32653783	Cannot delete the selected item from listview (values in sqlite)	private async void Button_Click_3(object sender, RoutedEventArgs e)\n    {\n        var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";\n\n        var con = new SQLiteAsyncConnection(dbpath);\n        if (list_view.SelectedItem != null)\n        {\n            list k = (list)list_view.SelectedItem;\n           await con.QueryAsync<list>("delete from list where list1='" + k.list1 + "'");\n\n            update();\n        }\n public async void update()\n    {\n        var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";\n        var con = new SQLiteAsyncConnection(dbpath);\n\n        list_view.ItemsSource = new List<list>();\n        List<list> mylist = await con.QueryAsync<list>("select * from list");\n        if (mylist.Count != 0)\n        {\n            list_view.ItemsSource = mylist;\n            list_view.DisplayMemberPath = "list1";\n        }\n\n    }	0
32872814	32872735	Gridview popup window not opening from RowCommand event corresponding to Linkbutton click	protected void gvKeys_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n\n  if (e.Row.RowType == DataControlRowType.DataRow)\n  {\n\n    System.Text.StringBuilder sb = new System.Text.StringBuilder();\n    sb.Append("window.open('OverwriteConfiguration.aspx', 'PopUp',");\n    sb.Append("'top=0, left=0, width=500, height=500, menubar=no,toolbar=no,status,resizable=yes,addressbar=no');<");\n\n    LinkButton l = (LinkButton)e.Row.FindControl("lnkView");\n\n    l.Attributes.Add("onclick", sb.ToString());\n\n   }\n\n}	0
4290221	4275700	How to use ToString() method to convert an integer to string inside LINQ	string queryTemplate = \n @"select inv.* from invoices as inv where userID = '123' and date like '%abc%'";\nList<invoice> totalSearch = \n context.ExecuteStoreQuery<invoice>(queryTemplate).ToList();	0
34130056	31830197	Ignore Invalid SSL-Certificate Windows 10	var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();\nfilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);\nfilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);\nfilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);\n\nusing (var client = new Windows.Web.Http.HttpClient(filter))\n    {\n        Uri uri = new Uri("https://yourwebsite.com");\n    }	0
3620133	3616620	Access my Views from bound ItemsControl	ObservableCollection<StepViewModel> vmCollection = \n    stkStepContent.DataContext as ObservableCollection<StepViewModel>;\n\nforeach(StepViewModel vm in vmCollection)\n{\n    vm.Refresh();\n}	0
6656590	6656361	Resolving a list of components as a constructor argument	Container.Kernel.Resolver.AddSubResolver(new CollectionResolver(Container.Kernel, true));	0
3543574	3543539	How to turn byte[] into sbyte* in C#?	// Allocate a new buffer (skip this if you already have one)\nbyte[] buffer = new byte[256];\nunsafe\n{\n    // The "fixed" statement tells the runtime to keep the array in the same\n    // place in memory (relocating it would make the pointer invalid)\n    fixed (byte* ptr_byte = &buffer[0])\n    {\n        // Cast the pointer to sbyte*\n        sbyte* ptr_sbyte = (sbyte*) ptr_byte;\n\n        // Do your stuff here\n    }\n\n    // The end of the "fixed" block tells the runtime that the original array\n    // is available for relocation and/or garbage collection again\n}	0
3756435	3756393	How can I access a view property from my ViewModel?	public string TextToTest\n{\n    get { return (string)this.GetValue(TextToTestProperty); }\n    set { this.SetValue(TextToTestProperty, value); } \n}\npublic static readonly DependencyProperty TextToTestProperty = \n    DependencyProperty.Register("TextToTest", typeof(string), \n    typeof(MyControl), new PropertyMetadata(""));	0
8348987	8348879	Decoding all HTML Entities	MessageBox.Show(HttpUtility.HtmlDecode("&amp;&copy;"));	0
14617325	14616868	How to catch doublic click event within HTCAPTION	private const int WM_NCHITTEST = 0x84;\n    private const int WM_SYSCOMMAND = 0x112;\n    private const int SC_MINIMIZE = 0xf020;\n    private const int SC_MAXIMIZE = 0xf030;\n    private const int SC_RESTORE = 0xf120;\n\n    protected override void WndProc(ref Message m) {\n        if (m.Msg == WM_SYSCOMMAND) {\n            switch (m.WParam.ToInt32() & 0xfff0) {\n                case SC_MINIMIZE: Console.WriteLine("Minimize"); break;\n                case SC_MAXIMIZE: Console.WriteLine("Maximize"); break;\n                case SC_RESTORE:  Console.WriteLine("Restore");  break;\n            }\n        }\n        base.WndProc(ref m);\n        if (m.Msg == WM_NCHITTEST && m.Result == (IntPtr)1) m.Result = (IntPtr)2;\n    }	0
1556311	1556243	How to get the body of a predicate?	protected void Require<TValidator, TParam>(\n    TValidator validator, \n    Expression<Func<TValidator, TParam>> property, \n    Expression<Predicate<TParam>> predicateExpression)\n{\n    var propertyValue = property.Compile().Invoke(validator);\n    Predicat<TParam> predicate = predicateExpression.Compile();        \n    if(!predicate.Invoke(propertyValue))\n    {    \n        throw new ValidatorInitializationException(\n            "Error while initializing validator: " + predicateExpression,\n            GetType());\n    }\n}	0
6808734	6808639	Add new record via WCF and LINQ-to-SQL	using System.Linq;\n\n// create context    \nusing(DBDataContext db = new DBDataContext ())\n{\n    // create table entry\n    WF entry= new WF();\n    // set values of the table \n    entry.someColumnName = "something";\n    db.WFs.InsertOnSubmit(entry);\n    db.SubmitChanges();\n}	0
4186629	4186610	How to extract title from .pdf file using c#	class Program\n{\n    static void Main()\n    {\n        PdfReader reader = new PdfReader("test.pdf");\n        var title = reader.Info["Title"];\n        Console.WriteLine(title);\n    }\n}	0
10264118	10264068	How to set the cursor's position in c# XNA	Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);	0
3941640	3941593	LINQ to XML - Get element based on a nested elements value	var detailsOfUserAccount = policySpecificationXml\n    .Descendants("Agent")\n    .Where(agent => agent.Descandants("Product")\n                         .Any(product => (string)product.Attribute("ID")\n                                             == productId))\n    .FirstOrDefault();	0
3146517	3146495	how to copy war file progrmaticaly using c#	DirectoryInfo sourceDirectory = new DirectoryInfo("mySource");\nFileInfo[] warFiles = sourceDirectory.GetFiles("*.war");\n\nforeach(FileInfo file in warFiles)\n{\n    file.CopyTo("myDestination");\n}	0
9744678	9494275	Sorting of XML file by XMLElement's InnerText	XElement root = XElement.Load(xmlfile);\nvar orderedtabs = root.Elements("Tab")\n                      .OrderBy(xtab => (int)xtab.Element("Order"))\n                      .ToArray();\nroot.RemoveAll();\nforeach(XElement tab in orderedtabs)\n    root.Add(tab);\nroot.Save(xmlfile);	0
8629144	8628698	Create Fibonacci series using lambda operator	// Using long just to avoid having to change if we want a higher limit :)\npublic static IEnumerable<long> Fibonacci()\n{\n    long current = 0;\n    long next = 1;\n    while (true)\n    {\n        yield return current;\n        long temp = next;\n        next = current + next;\n        current = temp;\n    }\n}\n\n...\n\nlong evenSum = Fibonacci().TakeWhile(x => x < 4000000L)\n                          .Where(x => x % 2L == 0L)\n                          .Sum();	0
12398493	12398457	How can I modify my class to override a list add?	public abstract class BaseGridViewModel\n{\n\n    protected BaseGridViewModel()\n    {\n        Times = new List<TimeEvent>();\n    }\n    public IList<TimeEvent> Times {get; set;}\n\n    public void Event(StopWatch watch, string message)\n    {\n        Times.Add(new TimeEvent(watch.ElapsedMilliseconds, message));\n    }\n\n}	0
17672055	17671904	NullReference Exception in date Conversion	WhatEver cur = new WhatEver();	0
10986916	10986789	How to replicate a folder structure	public static TotallyNotRecursiveAndCreateDirs(string root, string newRoot)\n    {\n        DirectoryInfo rootDir = new DirectoryInfo(Path.GetPathRoot(root)); \n        DirectoryInfo[] dirs = rootDir.GetDirectories("*", SearchOption.AllDirectories);\n\n        foreach(DirectoryInfo dir in dirs)\n        {\n            Directory.CreateDirectory(dir.FullName.Replace(root, newRoot));\n            FileInfo[] files = dir.GetFiles("*.*", SearchOption.TopDirectoryOnly);\n            foreach(FileInfo file in files)\n            {\n                File.Create(file.FullName.Replace(root, newRoot));\n            }\n        }\n    }	0
8461125	8461089	Dynamically build predicates using linq-to-xml on windows phone	var currentLevelElements = doc.Root.Elements();\nint depth = 0;\nwhile (currentLevelElements != null && depth < nodeDepth)\n{\n    currentLevelElements = currentLevelElements.Elements()\n                                               .Where( x=> (string) x.Attribute("title") == AcmSinglton.GetTitle(depth));\n    depth++;\n}\nvar nodes = from x in currentLevelElements select new Menus.Chapter\n                    {\n                       Title = x.Attribute("title").Value\n                    };	0
27106319	27106090	How to convert xml string to an object using c#	var items = XDocument.Parse(xml)\n              .Descendants("E")\n              .Select(e => new \n                 {\n                    Name = e.Attribute("NAME").Value, \n                    Email = e.Attribute("EMAIL").Value\n                 })\n              .ToList();	0
15916121	15915503	.Net NewtonSoft Json Deserialize map to a different property name	public class TeamScore\n{\n    [JsonProperty("eighty_min_score")]\n    public string EightyMinScore { get; set; }\n    [JsonProperty("home_or_away")]\n    public string HomeOrAway { get; set; }\n    [JsonProperty("score ")]\n    public string Score { get; set; }\n    [JsonProperty("team_id")]\n    public string TeamId { get; set; }\n}\n\npublic class Team\n{\n    public string v1 { get; set; }\n    [JsonProperty("attributes")]\n    public TeamScore TeamScores { get; set; }\n}\n\npublic class RootObject\n{\n    public List<Team> Team { get; set; }\n}	0
25339237	25338797	How to import/use images in Windows Form Application	this.BackgroundImage = new System.Drawing.Bitmap("your image path");	0
4082465	4082364	Using Linq to Entities to find the best match in table	Data def = new Data { prop1 = null, prop2 = null };\n    var result = (from d in datas\n                  where d.prop1 == value1 || d.prop2 == value2\n                  orderby (d.prop1 == value1 ? 8 : 0) + (d.prop2 == value2 ? 4 : 0) + (d.prop1 == null ? 2: 0) + (d.prop2 == null ? 1 : 0) descending\n                  select d).FirstOrDefault() ?? def;	0
27925414	27865033	Bootstrap modal showing multiple times	MyCustom.js	0
8712098	8710527	ASP.NET ListBox with min-width and Horizontal Scroll Bar	min-width	0
14810829	14810637	SQL CLR C# User Defined Function - Get house or flat number from address	char[] KeepArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', '/', '-', ' ' };\n\n\n        foreach (char thischar in theWord) {\n\n            if (KeepArray.Contains(thischar)) {\n\n                newWord += thischar;\n            }\n            else if (Char.IsLetter(thischar) && newWord.Length > 0){\n\n                try {\n                    if (Char.IsDigit((Convert.ToChar(newWord.Substring(newWord.Length - 1, 1))))) {\n                        newWord += thischar;\n\n                    }\n\n                }\n                catch {\n\n                }\n            }\n\n        }	0
20219135	20219068	How do I manually delete a cookie in asp.net MVC 4	if ( Request.Cookies["MyCookie"] != null )\n{\n    var c = new HttpCookie( "MyCookie" );\n    c.Expires = DateTime.Now.AddDays( -1 );\n    Response.Cookies.Add( c );\n}	0
22644540	22644207	Parse multiple XML elements from string, when some of which may be incomplete	using (XmlReader reader = XmlReader.Create(new StringReader("..."))\n{\n   while (reader.Read())\n   {\n      if (reader.NodeType == XmlNodeType.Element)\n      {\n         ...\n      }\n   }\n}	0
21162998	21140982	Writing to excel worksheet from custom object	private void Rebind(myWorksheet currWorksheet, out Excel.Workbook workbook)\n{\n\n  currWorksheet.Application.Calculation = Excel.XlCalculation.xlCalculationManual\n  currWorksheet.Application.ScreenUpdating=False\n\n  foreach (string connectedWorksheet in currWorksheet.Dependencies)\n  {\n    myWorksheet ws = DataHelper.FindWorksheetFromList(connectedWorksheet, this.WorksheetList);\n    Excel.Worksheet sheet = DataHelper.FindWorksheetFromWorkbook(connectedWorksheet,workbook);\n\n    this.LoadData(sheet,ws);\n  }\n\n  Excel.Worksheet sheetMain = DataHelper.FindWorksheetFromWorkbook(currWorksheet.WorksheetName,workbook);\n  this.LoadData(sheetMain,currWorksheet);\n\n  currWorksheet.Application.Calculation = Excel.XlCalculation.xlCalculationAutomatic\n  currWorksheet.Application.ScreenUpdating=True\n }	0
21595721	21545095	Generic method in C# with two generic parametres	private static void LogNormalAudit<TRequest, TResponse>(TRequest request, TResponse response,\n        IRequest objRequest, int memberId, AuditEventType eventType)\n    {\n        bool isNormalSeverityOn = Convert.ToBoolean(ConfigurationSystem.SharedApiConfig["normal"]);\n        if (!isNormalSeverityOn) return;\n        var auditText = string.Format("Req: {0} |Rsp: {1}", Util.Serialize(request), Util.Serialize(response));\n        Audit.Add(eventType, Severity.Normal, memberId, objRequest.TokenId, auditText, GetClientIp(),\n            objRequest.IpAddress);\n    }	0
28053993	28033890	Rejecting bad DLL's with MEF	private void appendToCatalog(DirectoryTreeNode node)\n{\n    DirectoryInfo info = node.Info;\n    FileInfo[] dlls = info.GetFiles("*.dll");\n\n    foreach (FileInfo fileInfo in dlls)\n    {\n        try\n        {\n            var ac = new AssemblyCatalog(Assembly.LoadFile(fileInfo.FullName));\n            ac.Parts.ToArray(); // throws exception if DLL is bad\n            catalog.Catalogs.Add(ac);\n        }\n        catch\n        {\n            // some error handling of your choice\n        }\n    }\n}	0
4036617	4035546	How to debug TreeNodeCollection	categoryNode.OfType<TreeNode>(), results	0
10172181	10172041	How to reference the inner text of a drop down box	var ddlTxt =  ((DropDownList)grdvHandSets.Rows[i].Cells[4].FindControl("ddlName")).SelectedItem.Text;\nid(ddlTxt == "Port" && !String.IsNullOrEmpty(ddlTxt))\n{\n      //your msg\n}	0
18241758	18240143	Custom list, moving stuff up automatically after removal in Windows Phone	Storyboard sb = new Storyboard();\nsb.Children.Add(fadeGrid);\nStoryboard.SetTarget(fadeGrid, myRectangle);\nStoryboard.SetTargetProperty(fadeGrid, new PropertyPath("(UIElement.Opacity)"));\nsb.Begin();	0
26067107	26066053	Redirect to another website with automatic login	Response.Redirect	0
22707881	22707846	Casting and using the result in one line	((WrapPanel)topSP.Children[0]).Children.Add(txtB1);	0
4349258	4349192	Regexp, force text vertical	Regex.Replace("i like stackoverflow", "([^\\s]\\s?)", "$1\n");	0
33740604	33739748	UWP / WinRT: Detect when a popup is about to be closed	this.popup.RegisterPropertyChangedCallback(Popup.IsOpenProperty, (d, e) =>\n{\n    if (!this.popup.IsOpen)\n    {\n        // do something, popup is closing?\n    }\n});	0
16171261	16171144	How to check for database availability	public bool IsServerConnected()\n    {\n        using (var l_oConnection = new SqlConnection(DBConnection.ConnectionString))\n        {\n            try\n            {\n                l_oConnection.Open();\n                return true;\n            }\n            catch (SqlException)\n            {\n                return false;\n            }\n        }\n    }	0
6635572	6634234	No elements found when parsing eBay's api result xml	XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";\n\nvar elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");	0
11396851	11396454	Sending Binary File TcpClient - File Is Larger Than Source	using (Stream stream = new FileStream(@"D:\carry on baggage.PNG", FileMode.Create, FileAccess.ReadWrite))\n{\n    // Buffer for reading data\n    Byte[] bytes = new Byte[1024];\n\n    int length;\n\n    while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0)\n    {\n        stream.Write(bytes, 0, length);\n    }\n}	0
978789	603249	How can I easily revert changes on a DataBound form?	var myLocalObject = DataLayer.GetCurrentState();\nLayoutRoot.DataContext = null;\nLayoutRoot.DataContext = myLocalObject;	0
3083383	3083352	How to close application before its fully loaded?	Environment.Exit	0
27397553	27397209	Centralising application name for display	private void PrintProductName() {\n    textBox1.Text = "The product name is: " +\n       Application.ProductName;\n }	0
29239832	29239692	how to construct filter string in datatable compute() avg?	string dataColumnName = (string)RefdtClone.Columns[firstDataColumn + i].ColumnName;\nComputeAVGColumn = String.Concat("AVG(["+ dataColumnName+ "])");\nstring filter = String.Format("[{0}] <= 9999", dataColumnName);\nAnalysisdt.Rows[i]["Mean 1"] = RefdtClone.Compute(ComputeAVGColumn, filter);	0
32735097	32734921	How to convert string to json in c#?	string toJsonify = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14";\nvar dates = toJsonify.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)\n                .Select(s => DateTime.ParseExact(s, "yyyy-M-d", System.Globalization.CultureInfo.InvariantCulture)\n                                     .ToString("yyyy-MM-dd"));\n\nvar res = "[\"" + string.Join("\",\"", dates) + "\"]";	0
17245532	17218243	EF Many to many relationship with additional properties	public partial class A\n{\n    public IQueryable<B> Bs {\n        get { return this.ABs.AsQueryable().Select(ab => ab.B).Distinct(); }\n    }\n}	0
20236162	20236120	Finding the "mode" of pairs of numbers	var mostCommon = list\n              .GroupBy(x=>new {x.PositionCount, x.Value})\n              .OrderByDescending(x=>x.Count()).First();	0
34402312	34402189	How to get keys and values from Appsettings of Config file in Linq	var dict = \n    ConfigurationManager.AppSettings.AllKeys\n        .ToDictionary(k => k, v => ConfigurationManager.AppSettings[v]);	0
25356788	25356733	How to get the values of all the elements in an XML into an array?	var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>\n    <Test>\n        <Name>TESTRUN</Name>\n        <SyncByte>ff</SyncByte>\n        <SOM>53</SOM>\n        <PDADD>7e</PDADD>\n        <LENLSB>08</LENLSB>\n    </Test>";\n\n    var doc = XDocument.Parse(xml);\n    string[] values = doc.Root.Descendants().Select(x => x.Value).ToArray();	0
23047965	23047531	Deserialization c# object and passing values in windows phone 8	void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n{\n    var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result) as RootObject;\n    tbl_result.Text = rootObject.type;\n}	0
9181727	9180385	Is this a valid float comparison that accounts for a set number of decimal places?	public static bool AlmostEquals(this float float1, float float2, int precision = 2) \n{ \n    float epsilon = Math.Pow(10.0, -precision) \n    return (Math.Abs(float1-float2) <= epsilon);   \n}	0
23696077	23695996	recurisve algorithm for file structure for a single type of file	void DirSearch(string sDir, TreeViewItem parentItem)\n    {\n        ......\n\n        foreach (string d in Directory.GetDirectories(sDir))\n        {\n            TreeViewItem item = new TreeViewItem();\n            item.Header = d;\n            foreach (string f in Directory.GetFiles(d, "*.resx"))\n            {\n                TreeViewItem subitem = new TreeViewItem();\n                subitem.Header = f;\n                subitem.Tag = f;\n                item.Items.Add(subitem);\n            }\n            DirSearch(d, item);\n\n            if (item.Items.Count > 0)\n                parentItem.Items.Add(item);\n        }\n\n        ......\n    }	0
22615657	22612377	Setting SelectedValue of DDL on PageLoad using value saved in Session Variable	foreach (ListItem listItem in advisors.Items)\n{\n      if(listItem.Text.Equals(Session["advisor"].ToString())\n\n DropDownList1.Items.FindByValue(Session["advisor"].ToString()).Selected = true;\n}	0
6814139	6814064	if else condition in windows phone 7	int count = 0;\n\nif (correctAns.Contains(textBlock1.Text)) count++;\nif (correctAns.Contains(textBlock2.Text)) count++;\nif (correctAns.Contains(textBlock3.Text)) count++;\nif (correctAns.Contains(textBlock4.Text)) count++;\nif (correctAns.Contains(textBlock5.Text)) count++;\n\nif (count >= 3)\n{\n   MessageBox.Show("At least 3 correct");\n}	0
29840377	29839957	ProjectGuid (.csproj), how to generate it correctly?	//the projectGuidCollection contains a collection of instances like this:\nProjectGuid proj = new ProjectGuid()\n{\n    FilePath = @"c:\newpath\to\MyLibrary.csproj",\n    OldGuid = "D4BD0EB3-8B59-4A33-B8A3-D549065EEC6D", //<ProjectGuid>{}</ProjectGuid>\n    NewGuid = Guid.NewGuid().ToString("B") // <--- HERE THE SOLUTION!!\n};	0
11394950	11394785	Reverse engineering C# solution build to get source code	using System;\n\nnamespace HW\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine("Foo Bar");\n        }\n    }\n}	0
17523512	17523195	How to clear cookie in windows phone 8	await new WebBrowser().ClearCookiesAsync();	0
21367607	21367581	Very strange issue with String and Double	string TestVarStrg = "3.1";\ndouble TestVarDoub = Convert.ToDouble(TestVarStrg, System.Globalization.CultureInfo.InvariantCulture);\n\nMessageBox.Show(TestVarDoub.ToString());	0
21186439	21186274	DropDownCheckBoxes doesn't bind with DataSet values	DataSet ds = GetTheData("Jan 2014");\nDataTable dt = ds.Tables[0];\n\nvar q = dt.AsEnumerable().Where(a => a.Field<String>("SomeColumn1") == "Jan 2014")\n                         .Select(a => a.Field<String>("SomeColumn2"));\n\nDropDownCheckBoxes1.DataSource = q;\nDropDownCheckBoxes1.DataBind();	0
7742517	7742453	NHibernate QueryOver with sub-query and alias	.Where(shipment => shipment.Subscription.Id == subscription.Id)	0
3059598	3059587	string to float conversion - decimal separator	float lat = Convert.ToSingle("50.09445", CultureInfo.InvariantCulture);	0
13401367	13400328	How to get the value by column name at runtime for a Lookup instead of column index number?	int ColumnIndex = this.dsDevLkp.Tables[dgtbsDevLkp.MappingName].Columns["ColumnName"].Ordinal;\nId = this.dgDevLkp[row, ColumnIndex].ToString().TrimEnd();	0
23349573	23349484	Download file that lives elsewhere on the harddrive	Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", node.Text));\n\nResponse.TransmitFile(Path.Combine(parent.Text, node.Text));\n\nResponse.End();	0
22960995	22960817	press enter key and user control event happen	DT_Navigator.btnNew.Click += new EventHandler(DTnewItem);	0
18077368	18075162	Using regex replace to transform an expression	var st = "{op1 == op2, #} && {op3 > op4, 1, 2} && op5 == op6";\n\nvar regex = "{.*?}";\nfor (var match = Regex.Match(st, regex); match.Success; match = Regex.Match(st, regex))\n{\n    var oldString = match.Value; // {op1 == op2, #} \n\n    var op = oldString.Split(' ').ToList()[1].Trim(); // == \n    var csv = oldString.Split(',').Select(x => x.Trim()).ToList(); // [0] = "{op1 == op2" [1] = "#}"\n\n    var expression = csv[0].Remove(0,1); // op1 == op2\n    csv.RemoveAt(0);\n\n    var extension = "_" + String.Join("_", csv);\n    extension = extension.Remove(extension.Length-1); // _#\n\n    var newString = expression.Replace(op, op + extension);\n\n    st = st.Replace(oldString, newString); \n}	0
12376628	12365352	Remove content control from a word document read from sharepoint	using (WordprocessingDocument wordProcessingDocument = WordprocessingDocument.Open(stream, true))\n            {\n                SdtRun sdtRun = wordProcessingDocument.MainDocumentPart.Document.Body.Descendants<SdtRun>().FirstOrDefault();\n\n                if (sdtRun != null)\n                {\n                    foreach (var elem in sdtRun.SdtContentRun.Elements())\n                    {\n                        sdtRun.Parent.InsertBefore(elem.CloneNode(true), sdtRun);\n                    }\n\n                    sdtRun.Remove();\n\n                    wordProcessingDocument.MainDocumentPart.Document.Save();\n                }                    \n            }	0
11275029	11274727	Add picture boxes dynamically in row	List<PictureBox> pictureBoxList = new List<PictureBox>();\n\nfor (int i = 0; i < dt.Rows.Count; i++)\n{\n    PictureBox picture = new PictureBox\n    {\n        Name = "pictureBox" + i,\n        Size = new Size(316, 320),\n        Location = new Point(i * 316, 1),\n        BorderStyle = BorderStyle.FixedSingle,\n        SizeMode = PictureBoxSizeMode.Zoom\n    };\n    picture.ImageLocation = dt.Rows[i]["FileName"].ToString();\n    pictureBoxList.Add(picture);\n}\n\nforeach (PictureBox p in pictureBoxList)\n{\n    pnlDisplayImage.Controls.Add(p);\n}	0
9392487	9392287	Add parameter issue for fulltext search in C#	sqlCommand.Parameters.AddWithValue("@text", value+"*");	0
26697158	26696169	How to return a specific view based on user input in ASP.NET MVC	public ActionResult Preregister(bool faculty, bool student)	0
4702127	4702051	how to get list of all tree nodes (in all levels) in TreeView Controls	TreeNode oMainNode = oYourTreeView.Nodes[0];\nPrintNodesRecursive(oMainNode);\n\npublic void PrintNodesNodesRecursive(TreeNode oParentNode)\n{\n  Console.WriteLine(oParentNode.Text);\n\n  // Start recursion on all subnodes.\n  foreach(TreeNode oSubNode in oParentNode.Nodes)\n  {\n    PrintNodesRecursive(oSubNode);\n  }\n}	0
11036876	11036838	How to solve the issue of postback through browsers reload button in Asp.Net	protected void Button1_Click(object sender, EventArgs e) \n{\n   // Insert Data\n   ...\n\n   // Redirect to get\n   Response.Redirect("ViewItem.aspx?id=" + insertedItemId);\n}	0
8979766	8979723	How can I add a button to the empty area of a TabControl in Winforms?	private void TabControl1_Selecting(Object sender, TabControlCancelEventArgs e) \n{\n    if (e.TabPage... /* Do check whether some of your special TabPages is being selected */)\n    {\n        e.Cancel = true;\n\n        // All other TabPage-specific actions here\n        ...\n    }\n}	0
16344788	15760786	Configure OAuth creating DefaultConnection database	OpenAuth.ConnectionString	0
21372315	21372245	Please help me to refine code of a simple function	public static string[] GetFiles(\n    string path,\n    string searchPattern,\n    SearchOption searchOption\n)	0
18261966	18261921	How to add an XML file and read key value pair into a dictionary?	var xdoc = XDocument.Load(path_to_xml);\nvar map = xdoc.Root.Elements()\n                   .ToDictionary(a => (string)a.Attribute("keyword"),\n                                 a => (string)a.Attribute("replaceWith"));	0
4782719	4781478	Convert CSV into XLS	using Excel = Microsoft.Office.Interop.Excel;\n\nExcel.Application excel = new Excel.Application();\nExcel.Workbook workBook = excel.Workbooks.Add();\nExcel.Worksheet sheet = workBook.ActiveSheet;\n\nvar CsvContent = new string[][]\n{\n    new string[] {"FirstName", "UserName", "PostCode", "City"},\n    new string[] {"John", "Smith", "4568", "London"},\n    new string[] {"Brian", "May", "9999", "Acapulco"}\n};\n\nfor (int i = 0; i < CsvContent.Length; i++)\n{\n    string[] CsvLine = CsvContent[i];\n    for (int j = 0; j < CsvLine.Length; j++)\n    {\n        sheet.Cells[i + 1, j + 1] = CsvLine[j];\n    }\n}\n\nworkBook.SaveAs(@"C:\Temp\fromCsv.xls");\nworkBook.Close();	0
1528429	1528371	Hiding unwanted properties in custom controls	// about the closest you can do, but not really an answer\n[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]\n[Obsolete("just cast me to avoid all this hiding...", true)]\npublic new ContentAlignment TextAlign { get; set; }	0
1224917	1224291	How to filter C# Winform datagridview that was created with Visual Studio	bindingSource.Filter = "Age < 21";	0
9358467	9358156	Gaining control over process started by an URI in C#	Process p = Process.Start(browserExePath, url);	0
7742263	7742046	Using reflection to get property attributes from a metadata class	var type = Type.GetType(entityType.FullName + "_HiddenProps," + entityType.AssemblyQualifiedName);\ntype.GetProperty("Id").GetCustomAttributes(false);	0
2438081	2438065	c# reflection: How can I invoke a method with an out parameter?	public class MyWebClient : WebClient\n{\n    delegate byte[] DownloadDataInternal(Uri address, out WebRequest request);\n\n    DownloadDataInternal downloadDataInternal;\n\n    public MyWebClient()\n    {\n        downloadDataInternal = (DownloadDataInternal)Delegate.CreateDelegate(\n            typeof(DownloadDataInternal),\n            this,\n            typeof(WebClient).GetMethod(\n                "DownloadDataInternal",\n                BindingFlags.NonPublic | BindingFlags.Instance));\n    }\n\n    public byte[] DownloadDataInternal(Uri address, out WebRequest request)\n    {\n        return downloadDataInternal(address, out request);\n    }\n}	0
2833948	2833900	How are developers using source control, I am trying to find the most efficient way to do source control in a small dev environment	main/release_1.0/release_1.1/release_1.5/release_2.0/release_2.1	0
7772896	7772621	C# Generating random int - mystery	System.Random	0
25915483	25914786	interchanging rows in a datagrid in C#,Gridview,Winforms	DataView view = new DataView(dataTable1);\nview.Sort = "B ASC, C DESC";\nDataTable newTable = view.ToTable();	0
26825078	26824791	How to access c# variable in javascript in selenium	((IJavaScriptExecutor)driver).ExecuteScript("console.log('" + linkLocation + "'); window.open('" + linkLocation + "', 'groupPage')");	0
24499877	24499460	check if a scroll bar is visible in a datagridview	foreach (var scroll in dataGridView1.Controls.OfType<VScrollBar>())\n{\n   //your checking here\n   //like... if(scroll.Visible)\n}	0
17476653	17468390	binding a set of datarows to datagridview	string strFilterOption = "dtcolnPurchaseProductExpProductNo=270";\nDataTable cloneTable;\ncloneTable = dtPurchaseProductExp.Clone();\nforeach (DataRow row in dtPurchaseProductExp.Select(strFilterOption))\n{\n   cloneTable.ImportRow(row);\n}\ndgvProductExp.DataSource = cloneTable;	0
20503970	20503837	Pass each list item to a new thread one by one	foreach (string server in stringList)\n    {\n        string local = server;\n        ThreadStart work = delegate { Threadjob(local); };\n        new Thread(work).Start();\n        //Thread.Sleep(10); // 10 ms delay of main thread\n    }	0
29428867	29428718	Access loops int and use it another function	public int whatSeat;\n    Transform TheObject;\n\n    positions = TheObject.GetComponent<GetInObject>().PosInObect;\n    for (whatSeat = 0; whatSeat < positions.Length; whatSeat++)\n    {\n        if (positions[whatSeat].isOccupied == false)\n        {\n            transform.parent = positions[whatSeat].pos;\n            positions[whatSeat].isOccupied = true;\n            break;   // Adding break here\n        }\n    }	0
3228325	3228307	How to get the difference of two list in C# using LINQ	LISTONE.Except(LISTTWO).Concat(LISTTWO.Except(LISTONE))	0
20210108	20160659	WebService Serialize Request Lost Nullable Property	[System.Xml.Serialization.XmlIgnoreAttribute()]\npublic bool CustomerNumberSpecified	0
1613118	1613089	Overloading of GetEnumerator	IEnumerator<T> MyCustomEnumerator<T>(T[] val1, T[] val2) {\n    // some code\n}	0
7765944	7765861	Finding the implemented Class from an Interface	public bool Create<T>(T entity)\nwhere t : class, IChild\n{            \n    //Is there an existing child record for the key details\n    IChild child = null;\n        child = Session.Query<T>()\n            .Where(x => x.Date == entity.Date)\n            .SingleOrDefault();\n\nreturn child.Parent != null;            \n}	0
6342497	6342231	AutoMapper - how to use type converter on a single property	Mapper.CreateMap<TSource, TDest>().ForMember(dto => dto.DestPrp,\n                                                        e => e.MapFrom(o => ConvertTo(o.SourceProp)))	0
10764151	10759087	How to prevent Crystal Reports from requesting credentials/parameters when setting the datasource directly?	ReportDocument cryReportDocument = .......;\ncryReportDocument.SetDatabaseLogon("userName", "password");\ncryReportDocument.SetParameterValue("parameterName", value);\nCrystalReportViewer1.ReportSource = cryReportDocument;	0
7510247	7510192	dynamic label using timer in c#	int counter = 1;\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    label1.Text = counter + " program running";\n    label1.Refresh();   //not necessarily\n    counter++;\n}	0
22083471	22027349	How can I delay my created service in Windows Server 2003 & Windows XP?	{\n\n        ServiceController service = new ServiceController(serviceName);\n\n        try\n        {\n            int millisec1 = Environment.TickCount;\n            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);\n\n            service.Stop();\n            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);\n\n            // count the rest of the timeout\n            //int millisec2 = Environment.TickCount;\n            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - millisec1);\n\n            service.Start();\n            service.WaitForStatus(ServiceControllerStatus.Running, timeout);\n        }\n\n        catch\n        {\n            // ...\n        }\n\n    }	0
946088	945585	C# automatic property deserialization of JSON	[DataContract]\npublic class Cat\n{\n    [DataMember]\n    public string Name { get; set; }\n\n    [DataMember]\n    public string Breed { get; set; }\n}	0
6148515	6148461	c# Database saving problem from a ListView	using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) { \n    con.Open(); \n    SqlCommand cmd = new SqlCommand(); \n    string expression = "Parameter value"; \n    cmd.CommandType = CommandType.StoredProcedure; \n    cmd.CommandText = "Your Stored Procedure"; \n    cmd.Parameters.Add("Your Parameter Name", \n                SqlDbType.VarChar).Value = expression;    \n    cmd.Connection = con; \n    using (IDataReader dr = cmd.ExecuteReader()) \n    { \n        if (dr.Read()) \n        { \n        } \n    } \n}	0
10341710	10341666	Can I set a property by the property name?	private PropertyInfo GetPropertyByName(string propName)\n{\n  return this.GetType().GetProperty(propName);\n}\n\nprivate void GetPath(string PropertyName) {\n    //show a dialog, get the path they select\n    string newPath = GetPathFromDialog();\n    //what should this look like? Is this possible?\n    var mProp = GetPropertyByName(PropertyName);\n    mPropp.SetValue(this, newPath, null);\n}	0
26308080	26304703	Reading XML file with XmlDocument Nodelist	// First loop through each student\nforeach( XmlElement ndStudent in xd.SelectNodes( "/students/Evening | /students/Day" ) {\n  // Build your object from the data\n  Student tc = new Student(); \n  tc.id = ndStudent.GetAttribute( "id" );       \n  tc.name = ndStudent.GetAttribute( "id" );       \n\n  // Add in the grades\n  foreach( XmlElement ndGrade in ndStudent( "grades/*/grade1" ) ) {\n    tc.grade1 = ndGrade.innerText;\n  }\n\n  // Add in the grades\n  foreach( XmlElement ndGrade in ndStudent( "grades/*/grade2" ) ) {\n    tc.grade2 = ndGrade.innerText;\n  }\n} // end of student loop	0
3343630	3343310	How can i get all USB drives (plugged in)	foreach (DriveInfo drive in DriveInfo.GetDrives())\n {\n     if (drive.DriveType == DriveType.Removable)\n     {\n      ..\n     }\n }	0
20113846	20093519	Unable to get particular value in JSON string using c#	public class SystemComponentFinalResponseWrapper\n{\n    public List<SystemComponentFinalseries> series { get; set; }\n}\n\npublic class SystemComponentFinalseries\n{\n    public string ts { get; set; }\n    public double? prod { get; set; }\n    public double? cons { get; set; }\n    public List<double?> data { get; set; }\n    //public IDictionary<string, string> data { get; set; }\n\n}	0
28435579	28435535	C# - How to get the value instead of id's in a List	var valueList = (from r in reservationList \n                 join m in context.mtas on r.mta_id equals m.mta_id\n                 select r.mta_name).ToList();	0
17136708	17136515	How do I change the icon that goes in the task bar?	Icon and Manifest	0
8804578	8804277	Using xPath in C# to get value of node attribute	xml/data/dataset/@name	0
4474349	4474200	C# / WPF - DataGrid - Update Element Color after timeout	BindingExpression binding = Control.GetBindingExpression(DataRow.BackgroundProperty)\nbinding.UpdateSource;	0
13403630	13403606	How to change Resource Dictionary Color in the runtime	ResourceDictionary resources = this.Resources; // If in a Window/UserControl/etc\nresources["BrushColor1"] = System.Windows.Media.Colors.Black;	0
24366862	24366444	How many hash buckets does a .net Dictionary use?	public static readonly int[] primes = {\n        3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,\n        1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,\n        17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,\n        187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,\n        1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369};	0
23244790	23244741	Get the size of a string	System.Text.Encoding.Unicode.GetByteCount(s);\nSystem.Text.Encoding.ASCII.GetByteCount(s);	0
8630941	8630805	Automatic click like buttons with c#	static IEnumerable<HtmlElement> LikeButtons(HtmlDocument doc)\n    {\n        foreach (HtmlElement e in from HtmlElement e in doc.All where e.GetAttribute("className") == "default_message" &&  e.InnerText =="Like" select e)\n            yield return e;\n    }	0
21323169	21323129	Return object created in a try catch	public static Dictionary<string, string> myFunction()\n{\n    Dictionary<string, string> dict = null;\n    try\n    {\n        dict = new Dictionary<string, string>();\n    }\n    catch\n    {\n\n    }\n\n    return dict;\n}	0
32499734	32499352	How to display a value in a Label	label3.Text = "There is " + toReadableSize(freeSpaceInC) + " free in C: and " + toReadableSize(freeSpaceInD) + " free in D:";	0
8173354	8172879	Odbc connection string format, not finding files	driver={iSeries Access ODBC Driver}; system={0}; uid={1}; pwd={2}; naming=1; DefaultLibraries=,*USRLIBL,LibraryB;	0
2938677	2938537	How to bind a control boolean property to contrary of boolean application setting?	using System;\nusing System.Windows.Forms;\n\nclass MyButton : Button {\n    public bool Invisible {\n        get { return !Visible; }\n        set { Visible = !value; }\n    }\n}	0
15687621	15687547	Extension Methods needing a Unity Resolve	public static class MyExtension\n{\n    public static void Invoke<T>(this IQueryable<T> query) \n    {\n        MyExtensionImplementation.Invoke(query);\n    }\n}\n\ninternal class MyExtensionImplementation\n{\n    public static void Invoke<T>(IQueryable<T> query) \n    {\n        //actual work\n    }\n}	0
28167008	28166933	Drag and drop multiple items between listboxes using windows forms	listBox.SelectionMode = SelectionMode.MultiExtended;	0
8340627	8340522	Call a function from another page in C#	public YourPage: BaseClass\n{\n     public void MyMethod()\n     {\n         base.BaseMethod();\n     }\n}\n\npublic BaseClass: System.Web.UI.Page\n{\n    //.. your shared method goes here\n    protected BaseMethod()\n    {\n         //.. logic here\n    }\n}	0
24759704	24759617	Read cookie in WPF application	CookieContainer cookies = new CookieContainer();\nHttpClientHandler handler = new HttpClientHandler();\nhandler.CookieContainer = cookies;\n\nHttpClient client = new HttpClient(handler);\nvar domain = "http://yourServiceURL.com";\nHttpResponseMessage response = client.GetAsync(domain).Result;\n\nUri uri = new Uri(domain);\nIEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();\nvar cookieWithId =  responseCookies.Single(o => o.Name == "SessionId");	0
25837212	25837184	Where are we supposed to look for C++ constants? (that appear in MSDN documentation)	Shlobj.h	0
20434059	20433768	Formating a File to a listBox 5 lines at a time	int max ;\nint i ;\nint numLine ;\nint set ;\nstring line ;\nvar lines = File.ReadAllLines("DNA.txt");\n\nmax = lines.Count() ;\ni = 0 ;\nnumLine = 1 ;\n\nwhile(i < max)\n{\n    line = string.Format("Line {0}:",numLine.toString("00")) ;\n\n    //logic to handle case where your file does not have multiple of 5 number of lines\n    for(set = 1; (i < max) && (set <= 5); set++)\n    {\n        line += lines[i] + " ";\n        i++ ;\n    }\n    lstOut.Items.Add(line) ;\n    numLine++ ;\n}	0
5517419	5517379	retrieve username and nickname from active directory on local network	public void getUser()\n{\n DirectoryServices.SearchResult myResult;\n string filterString = string.Empty;\n string EntryString = "LDAP:// <Your AD Domain here>";\n DirectoryServices.DirectorySearcher myDirectorySearcher = new DirectoryServices.DirectorySearcher(new DirectoryServices.DirectoryEntry(EntryString, "Username", "Password"));\n string tempStr;\n string[] splStr = new string[3];\n\n filterString = "(sAMAccountName=" + Username + ")";\n myDirectorySearcher.Filter = filterString;\n myDirectorySearcher.PropertiesToLoad.Add("cn");\n myResult = myDirectorySearcher.FindOne();\n splStr = Regex.Split(myResult.Properties("cn").Item(0).ToString, " ");\n tempStr = splStr(1).ToString + " " + splStr(0).ToString;\n Label1.Text = "Hello " + tempStr;\n}	0
2875207	2875127	converting to Fluent NHibernate sessionmanager	private ISessionFactory CreateSessionFactory()\n{\n    return Fluently.Configure()\n        .Database(\n            IfxOdbcConfiguration\n                .Informix1000\n                .ConnectionString("Provider=Ifxoledbc.2;Password=mypass;Persist Security Info=True;User ID=myid;Data Source=mysource")\n                .Driver<OleDbDriver>()\n                .Dialect<InformixDialect1000>()\n                .ProxyFactoryFactory<ProxyFactoryFactory>()\n        )\n        .Mappings(\n            m => m\n                .FluentMappings\n                .AddFromAssemblyOf<SomePersistentType>()\n        )\n        .BuildSessionFactory();\n}	0
28181857	28021220	Drawing image with an angle	Matrix CreateSkewY(float angle)\n{\n    Matrix skew = Matrix.Identity;\n    skew.M21 = (float)Math.Tan((double)angle);\n    return skew;\n}\n\nspriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null,\nCreateSkewX((float)Math.PI / 6));	0
19923933	19923849	How to check whether string contains any element present in the string array	bool Match(string str, string[] strArr)\n{\n    return strArr.Intersect(str.Split(':')).Any();\n}	0
11991444	11989619	How Do I Create A Dynamic Form Of Data Populated With SQL Data Based On App Settings In C#	int size = Properties.Settings.Default.systemsize;\nint height = 0;\nint width = 0;\n\n//check our sizes\nif (size == 5)\n{\n    height = 1;\n    width = 5;   \nelse if (size == 10)\n{\n    height = 2;\n    width = 5;\n}\nelse if (size == 25)\n{\n    height = 5;\n    width = 5;\n}\n\n//build a table\nstring table = "<table>";\n\nfor (int i = 1, i<=height,i++)\n    {\n    table += "<tr>"\n\n    for (int j = 1, j<=width,i++)\n        {\n        table += "<td>"\n        table += "some content"\n        table += "</td>"\n        }\n\n    table += "</tr>"\n    }\n\ntable += "</table>"\n\n//write table to your page	0
30953699	30953543	Swap dynamic amount of lines in text file	var linesInFile = File.ReadAllLines();\n\nvar newLines = new List<string>();\nvar toRandomize = new List<string>();\n\nbool inRegion = false;\n\nfor (int i = 0; i < linesInFile.Count; i++)\n{\n    string line = linesInFile[i];\n\n    if (line == "[RAND]")\n    {\n        inRegion = true;\n        continue;\n    }\n    if (line == "[/RAND]")\n    {\n        inRegion = false;       \n        // End of random block.\n        // Now randomize `toRandomize`, add it to newLines and clear it     \n        newLines.AddRange(toRandomize);\n        toRandomize.Clear();\n        continue;\n    }\n\n    if (inRegion)\n    {\n        toRandomize.Add(line);\n    }\n    else\n    {\n        newLines.Add(line);\n    }\n}\n\nFile.WriteAllLines(newLines, ...);	0
8403165	8403086	Long path with ellipsis in the middle	var truncated = ts.Substring(0, 16) + "..." + ts.Substring((ts.Length - 16), 16);	0
27902982	27902808	Separate array in sub arrays in C#	string[] firstArray=Array.ConvertAll(arrayofArrays,a => a[0]);\nstring[] secondArray=Array.ConvertAll(arrayofArrays,a => a[1]);	0
4338000	4337477	How a Winform custom control can notify another Winform Custom Control?	public interface IListener\n{\nvoid MessageRaised(int messageId, params object[] arguments);\n}\n\npublic class Mediator\n{\npublic void Register(IListener listener, int messageId)\n{\n//... add to dictionary of arrays for each messageId\n}\n\npublic void NotifyListeners(int messageId, params object[] arguments)\n{\n//... loop through listeners for the messageId and call the MessageRaised function for each one\n}\n}	0
28611788	28611299	Inserting New Rows into database from a Text File	var cmd = new     MySqlCommand("insert into p4gradetable_copy (Grade, CoilingTemp ) VALUES(@Grade, @CoilingTemp)";	0
6931998	6931961	Extern C method call from C#	[DllImport("your.dll", EntryPoint="iw")]\npublic static extern UInt32 NiceNameFunc(UInt32 niceNameA, UInt32 niceNameP);	0
27047487	27047165	C# : Retrieve array values from bson document	var queryString = Query.EQ("_id", id);\nvar resultBsons = collection.FindOne(queryString);\nvar arrayOfStrings = resultBsons["loves"].AsBsonArray.Select(p => p.AsString).ToArray();	0
4773639	4773632	How do I restart a WPF application?	System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);\nApplication.Current.Shutdown();	0
9898314	9897986	WCF - Post JSON object containing an array	{\n    "Localization": "en-us",\n    "Transactions": [\n      {\n        "TransactionType": 0,\n        "SubjectLocalPart": "testSubject",\n        "PredicateLocalPart": "testPredicate",\n        "ObjectPart": "1",\n        "Update": "2"\n      },\n      {\n        "TransactionType": 1,\n        "SubjectLocalPart": "testSubject",\n        "PredicateLocalPart": "testPredicate",\n        "ObjectPart": "1"\n      }\n    ]\n  }	0
10553197	10553030	How to modify a property of a resource from the code behind?	var rect = (Rectangle)Button.Template.FindName("Rectangle", Button);\nrect.Visibility = System.Windows.Visibility.Visible;	0
1409462	1409396	How Do I scroll to a string in a Rich Text Box	rText1.SelectionStart = i\nrText1.ScrollToCaret()	0
20060604	20060456	C# count ocurrences of several char in string using regex.Matches.count once	int zeroCount = 0;\nint oneCount = 0;\nint xCount = 0;\nint tCount = 0;\nforeach(var ch in input)\n{\n    switch(ch)\n    {\n        case '0':\n            zeroCount++;\n            break;\n        case '1':\n            oneCount++;\n            break;\n        case 'x':\n            xCount++;\n            break;\n        case 'T':\n            tCount++;\n            break;\n    }\n}	0
31368064	31367980	Changing location of objects for infinite runner using pooling	void Update () {\n\n    lastPosition = pool.startPosition;\n\n    GameObject ObjAltitude = GameObject.Find ("Rocket");\n    startGame startGameScript = ObjAltitude.GetComponent <startGame> ();\n    altitude = startGameScript.altitude;\n\n    int poolIndex = (((int)altitude)/100) % 5/*pool size goes here*/;\n\n        pool.pool [0] [poolIndex].transform.position = lastPosition + new Vector2 (0, 100);\n        Vector2 currentPosition = pool.pool [0] [poolIndex].transform.position = lastPosition + new Vector2 (0, 100);\n        lastPosition = currentPosition;\n  }	0
11019797	11019738	Display a different number than what is in the table?	label.Text = warning.SeverityLevel == 9 ? "U" : warning.SeverityLevel.ToString();	0
11566502	11566450	How to get a row by column name	Workitem Id1	0
22855282	22855178	How to get the ASCII value of a string	byte[]  asciiBytes =Encoding.ASCII.GetBytes(str);	0
3966041	3932131	How to get rid of CA2000 warning when ownership is transferred?	public sealed class Test: IDisposable, ICollection<Item>\n{\n    public void Initialize()\n    {\n        var item1 = new Item(); // no warning\n        itemCollection.Add(item1);\n\n        var item2 = new Item(); // no warning\n        ((ICollection<Item>)this).Add(item2);\n\n        var item3 = new Item(); // no warning\n        AddSomething(item3);\n    }\n\n    //... implement ICollection and Method AddSomething\n}	0
19594442	19594415	Is it possible to add List<string> values dynamically in one line of code?	myList.Add(e.NewValues["value1"].ToString());	0
5403044	5402882	How to configure VS to compile only changed code	[assembly: AssemblyVersion("1.0.*")]	0
27868306	27846810	SSRS Set "Credentials stored securely in the report server" programmatically	var reportItem = report.TargetFolder + "/" + report.Name;\nvar dataSources = new DataSource[0];\n\ndataSources = rs.GetItemDataSources(reportItem);\nif (dataSources.Any())\n{\n     var dataSource = (DataSourceDefinition)dataSources.First().Item;\n     dataSource.CredentialRetrieval = CredentialRetrievalEnum.Store;\n     dataSource.UserName = SsrsUsername;\n     dataSource.Password = SsrsPassword;\n\n     rs.SetItemDataSources(reportItem, dataSources);\n }	0
34253823	34253145	Bind multiple dropdowns from a single list	objStateList = cityList.GroupBy(item => item.StateID, (key, items) => new SelectListItem\n{\n    Text = items.First().State,\n    Value = Convert.ToString(key)\n});\nobjCountryList = cityList.GroupBy(item => item.CountryID, (key, items) => new SelectListItem\n{\n    Text = items.First().Country,\n    Value = Convert.ToString(key)\n});	0
22528710	22528505	return data from Database to View?	There should always be an abstraction between 3 layers such as Presentation (UI), Middle (Business) layer and Data (Access) layer.\n\nDuring a 'GET' from data base, the return type should be a database entity say X. Now, your middle layer convert 'x' into Business object (say 'B') and finally the code behind does convert it to UI object (say 'U').\n\n\nIf you don't have a business layer, create a business object(if its Employee data, then create a class named 'Employee') and return the instance to code behind.\n\nIt is always a well-appreciated practice.	0
7869132	7868662	How to create a flat columnheader button in listview (Windows Forms C#)	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass FlatListView : ListView {\n    public FlatListView() {\n        this.HeaderStyle = ColumnHeaderStyle.Nonclickable;\n    }\n    protected override void OnHandleCreated(EventArgs e) {\n        if (this.View == View.Details) {\n            IntPtr hHeader = SendMessage(this.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);\n            SetWindowTheme(hHeader, "", "");\n        }\n        base.OnHandleCreated(e);\n    }\n\n    private const int LVM_GETHEADER = 0x1000 + 31;\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n    [DllImport("uxtheme.dll")]\n    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);\n}	0
32743126	32742906	Sharing with Windows Phone 8.1	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();\n    dataTransferManager.DataRequested += ShareData;\n}\n\nprivate async void ShareData(DataTransferManager sender, DataRequestedEventArgs e)\n{\n    try\n    {\n        DataRequest request = args.Request;\n        var deferral = request.GetDeferral();\n        request.Data.Properties.Title = "Title";\n        request.Data.Properties.Description = "Description";\n        request.Data.SetText("The text to share");\n        deferral.Complete();\n    }\n    catch (Exception ex)\n    {\n        Debug.WriteLine(ex);\n    }\n}\n\nprivate void btnShareLink_Click(object sender, RoutedEventArgs e)\n{\n    Windows.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();\n}	0
21067561	21067314	Volatile Access to Shared Mutable State	// T1:\nfoo = 5 // non-volatile\nbar = 7 // non-volatile\ndone = True // volatile write\n\n// T2:\nif (done) { // volatile read\n     foo and bar guaranteed to be 5, respectively 7 with non-volatile reads\n}	0
12114686	12114598	How to write a Regex pattern for the following string?	var invalidChars = new HashSet<char>(@"[]*#?/\@()");\nvar output = new string( input.Where(c => !invalidChars.Contains(c)).ToArray() );	0
15154436	15154060	How to make windows user has access to sql server with integrated security?	use master\nGO\n\ncreate login [<YourDomain>\User1] from windows;\nGO\n\nuse [<YourDatabase>]\nGO\n\ncreate user [<YourDomain>\User1] from login [<YourDomain>\User1]\nGO	0
31378634	31378105	map string to entity for using with generic method	Dictionary<string, Func<List<Fruit>>> typeMapper = new Dictionary<string, Func<List<Fruit>>>()\n    {\n        {"Apple", () => { return getFruit<Apple>(); } },\n        {"Orange", () => { return getFruit<Orange>(); } }\n    };\n\n    List<Fruit> fruitList = typeMapper["Apple"]();	0
7886667	7886544	Passing a value from one form to another form	// Code from Form 1\n public partial class Form1 : Form\n{\n    public void PassValue(string strValue)\n    {\n        label1.Text = strValue;\n    }\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Form2 objForm2 = new Form2(this);\n        objForm2.Show();\n    }![Application Screen Shot][1]\n\n}\n\n// Code From Form 2\n\npublic partial class Form2 : Form\n{\n    Form1 ownerForm = null;\n\n    public Form2(Form1 ownerForm)\n    {\n        InitializeComponent();\n        this.ownerForm = ownerForm;\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {       \n        this.ownerForm.PassValue(textBox1.Text);\n        this.Close();\n    }\n}	0
9327743	9327694	value of a checkBox within a Javascript function	var Excludeviv = document.getElementById("ctl00_ctl00_cphMain_cphMainMenu_chkExcludeviv").checked;	0
26348407	26348223	Didn't show data from database	public class NewsRepository  : INewsRepository \n{\n    private YourDbContext db = null;\n\n    public List<NewsList> NewsList\n    {\n        return this.db.NewsList.ToList();\n    }\n\n    public NewsRepository()\n    {\n        this.db = new NewsRepository();\n    }\n}\n\npublic class YourDbContext : DbContext\n{\n    public DbSet<NewsList> NewsList {get; set;}\n}	0
3623869	3623838	Gridview losing row index value	if(Page.IsValid)	0
5606776	5606747	How to get application path	bin\Debug	0
25591543	25591516	c# inline switch in format string	string s = string.Format("There are {0} items, bla bla {1}",\n            itemsCnt,\n            new Func<string>(() =>\n            {\n                switch (itemsCnt)\n                {\n                    case 0:\n                        return "make some...";\n                    case 1:\n                    case 2:\n                        return "try more";\n                    default:\n                        return "enough";\n                }\n            })()\n            );	0
5381863	5381814	Re use of Object Names in a for loop?	var controls = this.Controls.Find("pictureBox"+i, true);\nif (controls.Length > 0)\n{\n    foreach (var control in controls)\n    {\n        control.BackColor = Color.LawnGreen;\n    }\n}	0
34475417	34475079	How to Spawn Two Different Objects Randomly in Two Specified Positions in Unity 2D?	void Start()\n {\n      int firstPosIdx = Random.Range(0, 1);\n\n      Vector2 firstPos = positions[firstPosIdx];\n      Vector2 secondPos = positions[1 - firstPosIdx];\n\n      // instantiate object 1 at firstPos, object 2 as secondPos\n  }	0
3354915	3354893	How can I convert a DateTime to the number of seconds since 1970?	public static DateTime ConvertFromUnixTimestamp(double timestamp)\n{\n    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n    return origin.AddSeconds(timestamp);\n}\n\npublic static double ConvertToUnixTimestamp(DateTime date)\n{\n    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n    TimeSpan diff = date.ToUniversalTime() - origin;\n    return Math.Floor(diff.TotalSeconds);\n}	0
34499417	34499130	How to get number of concrete classes from factory pattern?	static class ShapeFactory\n{\n    private static readonly Type[] _shapes = new Type[] { typeof(Square), typeof(Triangle), typeof(Circle) };\n\n    public static int FactorySize\n    {\n        get\n        {\n            return _shapes.Length;\n        }\n    }\n\n    public static IShape GetShape(int shapeIndex, params object[] ctorParams)\n    {\n        return (IShape)Activator.CreateInstance(_shapes[shapeIndex], ctorParams);\n    }\n}	0
27740038	27739658	How to set default values in dropdown list when the page is loaded- in asp.net c#?	drpJurisdiction.Items.Insert(0, new ListItem("--Please select any state--", "0"));	0
28335049	28335016	String was not recognized as a valid DateTime when parse exact	DateTime.ParseExact("2015-08-05", "yyyy-MM-dd", CultureInfo.InvariantCulture)	0
22167258	22151790	How to substitute table name	context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");	0
8089387	8089357	how to read special character like ?, ? and others in C#	using (StreamReader r = new StreamReader(fileName, Encoding.GetEncoding("iso-8859-1")))\n    r.ReadToEnd();	0
24577922	24577143	Enum.ToObject with "invalid" int value - how to fix it	public Bar(int value)\n        {\n            if (Enum.IsDefined(typeof(Foo), value))\n            {\n                var enumValue = GetEnumValue(typeof(Foo), value);\n            }\n            else\n            {\n                var enumValue = GetEnumValue(typeof(Foo), 1);\n\n                //or like this...\n                var enumValue1 = Enum.GetValues(typeof(Foo)).GetValue(0);\n            }\n        }	0
4071062	4069527	special chars in XML	private string SanitizeXml(string source)\n        {\n            if (string.IsNullOrEmpty(source))\n            {\n                return source;\n            }\n            if (source.IndexOf('&') < 0)\n            {\n                return source;\n            }\n            StringBuilder result = new StringBuilder(source);\n            result = result.Replace("&lt;", "<>lt;")\n                            .Replace("&gt;", "<>gt;")\n                            .Replace("&amp;", "<>amp;")\n                            .Replace("&apos;", "<>apos;")\n                            .Replace("&quot;", "<>quot;");\n            result = result.Replace("&", "&amp;");\n            result = result.Replace("<>lt;", "&lt;")\n                            .Replace("<>gt;", "&gt;")\n                            .Replace("<>amp;", "&amp;")\n                            .Replace("<>apos;", "&apos;")\n                            .Replace("<>quot;", "&quot;");\n\n            return result.ToString();\n        }	0
29051239	29050730	Read specific element from xml using linq	var res = (from el in xmlElm.Descendants("address_component") \n           where el.Element("type").Value == "postal_code"\n           select el).FirstOrDefault();	0
26903119	26881567	DotNetNuke how to add Tab programmatically with null parentId	TabInfo tab;\ntab=new TabInfo()\n//set properties of tab object...\n//..\ntab.ParentId = 38;//38 is my main page tabID\n//...\n//add new tab code\ntabid = controller.AddTab(tab);\n//update parentID code\nDotNetNuke.Data.DataProvider.Instance().ExecuteSQL("update tabs set parentid=null where tabid=" + tabid);	0
17887477	17866116	Stopping the User From Accessing The Application When Using the Back Button	new Microsoft.Xna.Framework.Game().Exit();	0
24031656	24031534	MVC how to pre-populate IEnumerable<string> before attempting to populate with LINQ results	public void Person()\n{\n   var optionsList = new List<string>();\\n//Add your options\n\n   Options = optionsList;\n}	0
1936451	1936431	Custom sort xml bound DataGridView	System.Int32	0
26376025	26375102	How to Map my input data	string str = "VALVE,GATE,SH_NAME:VLV,GATE,VLV_NOM_SIZE:4-1/16IN";\nstring[] Rows = str.Split(',');\ndataGridView1.Columns.Add("Column1", "Column1");\ndataGridView1.Columns.Add("Column2", "Column2");\nforeach (string AddRow in Rows)\n{\n   string[] Row = AddRow.Split(':');\n   dataGridView1.Rows.Add(Row);\n}	0
13104551	13104462	Is there a .net class/namespace for browsing machines on a network	public sealed class ShellNetworkComputers : IEnumerable<string>\n{\n    public IEnumerator<string> GetEnumerator()\n    {\n        ShellItem folder = new ShellItem((Environment.SpecialFolder)CSIDL.NETWORK);\n        IEnumerator<ShellItem> e = folder.GetEnumerator(SHCONTF.FOLDERS);\n\n        while (e.MoveNext())\n        {\n            Debug.Print(e.Current.ParsingName);\n            yield return e.Current.ParsingName;\n        }\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return GetEnumerator();\n    }\n}	0
24625154	24625109	How to use "in" where clause in LINQ where the string set will be supplied by a list?	var records = from _adUserDatas in _adUserDataDBDataContex.ADUserDatas\n              where _inADUserDatas.Contains(_adUserDatas.fan)\n              orderby _adUserDatas.fan\n              select _adUserDatas;	0
6097991	6097861	Excel automation: Any way of knowing how many pages a sheet will be printed out on?	int numberOfPages = xlWorkSheet2.PageSetup.Pages.Count;	0
13793870	13793490	Close dynamically created form with dynamic button	Snapshot snapshot = new Snapshot();\nsnapshot.StartPosition = FormStartPosition.CenterParent;\n\n//Create save button\nButton saveButton = new Button();\nsaveButton.Text = "Save Screenshot";\nsaveButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 130);\nsaveButton.Click += (_,args)=>\n{\n    SaveSnapshot();\n};\n\n//Create exit button\nButton exitButton = new Button();\nexitButton.Text = "Exit";\nexitButton.Location = new Point(snapshot.Width - 100, snapshot.Height - 100);\nexitButton.Click += (_,args)=>\n{\n    snapshot.Close();\n};\n\n//Add all the controls and open the form\nsnapshot.Controls.Add(saveButton);\nsnapshot.Controls.Add(exitButton);\nsnapshot.ShowDialog();	0
29941063	29940914	convert very big exponential to decimal in c#	Console.WriteLine(s.ToString("N0")); //comma separated\nConsole.WriteLine(s.ToString("F0"));	0
3129134	2850374	Can I create a custom roleprovider through a WCF service?	public class WcfRoleProvider: RoleProvider\n{\n    public bool IsUserInRole(string username, roleName)\n    {\n        bool result = false;\n        using(WcfRoleService roleService = new WcfRoleService())\n        {\n            result = roleService.IsUserInRole(username, roleName);\n        }\n\n        return result;\n     }\n}	0
16393096	16291714	Having trouble downloading pictures from a RSS feed?	void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n{\n    if (e.Error != null)\n    {\n        MessageBox.Show("error");\n    }\n    // parsing Flickr \n\n    XElement XmlTweet = XElement.Parse(e.Result);\n    string ns = "http://www.w3.org/2005/Atom";\n\n    XName entry = XName.Get("entry", ns);\n    XName loc = XName.Get("loc", ns);\n    XName title = XName.Get("title", ns);\n    XName published = XName.Get("published", ns);\n    XName link = XName.Get("link", ns);\n    XName content = XName.Get("content", ns);\n    XName url = XName.Get("url", ns);\n\n    listBox1.ItemsSource = \n        from tweet in XmlTweet.Elements(entry)\n        select new FlickrData\n        {\n            ImageSource = tweet.Element(link).Attribute("href").Value,\n            Message = tweet.Element(content).Value,\n            UserName = tweet.Element(title).Value,\n            PubDate = DateTime.Parse(tweet.Element(published).Value)\n        };\n}	0
7486397	7486380	How can I switch that code to use LINQ	IEnumerable<PriorElemSt> priorsElemLst = priorsLstIDs.Select((s,i) => new PriorElemSt(s, priorsLstDates[i]));\nreturn filterStudyPriors(priorsElemLst);	0
9760519	9760452	Compare int with DateTime	String query = "select id, erstelldatum, enddatum, text, erledigt, prioritaet from Aufgaben where loginid = " + loginid + " AND year(erstelldatum) = "+ jahr +";";	0
6114999	6114912	Property grid with optional members best approach	public double? Sigma\n{\n    get\n    {\n        if (XScale == XSCalingType.Sigma)\n            return _sigma;\n        else\n            return null;\n    }\n    set { _sigma = value;}\n}	0
20477542	20476907	WPF Get Selected Value from AutoComplete box	myAutoCompleteBox.SelectedItem	0
3389667	3389649	Usage of named parameters	this.Foo("required argument", bar: 42);	0
7079259	7079206	How to initialize array of struct?	struct MyStruct \n{ \n   int i, j; \n\n   public MyStruct(int a, int b)\n   {\n      i = a;\n      j = b;\n   }\n}\n\nstatic MyStruct[] myTable = new MyStruct[3]\n{\n   new MyStruct(0, 0),\n   new MyStruct(1, 1),\n   new MyStruct(2, 2)\n};	0
4176591	4176586	Get hex values between a range in c#	for (int i = 0x0; i <= 0x1b3; i++) {\n    // Do stuff with i\n\n    // Converts the integer to hex, if that's what you wanted.\n    string str = i.ToString("X");\n}	0
1325632	1325625	How do I display a Windows file icon in WPF?	using System.Windows.Interop;\n\n...\n\nusing (Icon i = Icon.FromHandle(shinfo.hIcon))\n{\n\n    ImageSource img = Imaging.CreateBitmapSourceFromHIcon(\n                            i.Handle,\n                            new Int32Rect(0,0,i.Width, i.Height),\n                            BitmapSizeOptions.FromEmptyOptions());\n}	0
5604387	5517345	Turn New tabPage into New process	Managed Add-in Framework	0
28686222	28685858	Access combobox control from other thread than UI	cableGuageSelect.Invoke(new Action(() =>\n    {\n        cableGuage[0] = (byte)cableGuageSelect.SelectedIndex;\n    }));	0
29590033	29589905	Add axis name into chart c#	var chartArea = new ChartArea("MyChart");\n...\nchartArea.AxisX.Title = "xxx";\nchartArea.AxisY.Title = "yyy";	0
6112436	6112316	Why Locking On a Public Object is a Bad Idea	internal class ImplementationDetail\n{\n    private static readonly object lockme = new object();\n    public static void DoDatabaseQuery(whatever)\n    {\n        lock(lockme)\n             ReallyDoQuery(whatever);\n    }\n}	0
12806824	12806794	How to hide gridview column after databind?	grid1.Columns[columnIndex].Visible= false;	0
7156592	7156578	Separating Comma-Separated Strings	string firstString = "12,13";\nstring[] values = firstString.Split(',');\n\nstring s1 = values[0];\nstring s2 = values[1];	0
25329606	25329339	Eager Loading Many to Many relationship with an Association Entity - Entity Framework	var TesteEntities = UnitOfWork.Set<WorkOrderItem>()\n        .Include("WorkOrderItemLanguages.Language")\n        .FirstOrDefault(x.WorkOrderItemId == id);	0
28225040	28224724	How can I create a method that accepts either double or decimal as a parameter type	public static string SurroundWithQuotes<T>(T amount)\n{\n    if (amount == null)\n    {\n        return String.Empty;\n    }\n    string format = "{0:0,0.00}";\n    string formattedNumber = String.Format(format, amount);\n\n    decimal amnt = Convert.ToDecimal(amount);\n\n    if (amnt < 1000)\n    {\n        return formattedNumber;\n    }\n    else\n    {\n        string quote = "\"";\n        return quote + formattedNumber + quote;\n    }\n}	0
21723214	21723163	How can I read very long string from Console and Parse to numbers in a reasonable way in C#?	var array = Console.ReadLine().Split().Select(int.Parse).ToArray();	0
1314152	1313969	Help with Creating a Recursive Function C#	static void GetNumber(int num, int max) {\n    Console.WriteLine(GetNumber(num, max, ""));\n}\nstatic int GetNumber(int num, int max, string prefix) {\n    if (num < 2) {\n        Console.WriteLine(prefix + max);\n        return 1;\n    }\n    else {\n        int count = 0;\n        for (int i = max; i >= 0; i--)\n            count += GetNumber(num - 1, max - i, prefix + i + " ");\n        return count;\n    }\n}	0
14351943	14351925	Open Windows Form only once in C#	if ((Application.OpenForms["Form1"] as Form1) != null)\n{\n //Form is already open\n}\nelse\n{\n// Form is not open\n}	0
25371082	25370894	How to detect CAPS-Lock and make sure it's always disabled	using System;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\npublic class CapsLockControl\n{\n    [DllImport("user32.dll")]\n    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);\n    const int KEYEVENTF_EXTENDEDKEY = 0x1;\n    const int KEYEVENTF_KEYUP = 0x2;\n\npublic static void Main()\n{\n    if (Control.IsKeyLocked(Keys.CapsLock))\n        {\n            Console.WriteLine("Caps Lock key is ON.  We'll turn it off");\n            keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);\n            keybd_event(0x14, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,\n            (UIntPtr) 0);\n        }\n    else\n        {\n            Console.WriteLine("Caps Lock key is OFF");\n        }\n    }\n}	0
27580333	27580241	Breaking from a loop with button click - C#	private BackgroundWorker _worker = null;\n\nprivate void goButton_Click(object sender, EventArgs e)\n{\n    _worker = new BackgroundWorker();\n    _worker.WorkerSupportsCancellation = true;\n\n    _worker.DoWork += new DoWorkEventHandler((state, args) =>\n    {\n        do\n        {\n            if (_worker.CancellationPending)                \n                break;\n\n            Console.WriteLine("Hello, world");\n\n        } while (true);\n    });\n\n    _worker.RunWorkerAsync();\n    goButton.Enabled = false;\n    stopButton.Enabled = true;\n}\n\nprivate void stopButton_Click(object sender, EventArgs e)\n{\n    stopButton.Enabled = false;\n    goButton.Enabled = true;\n    _worker.CancelAsync();\n}	0
22533588	22533316	No public members in abstract class	public abstract class BaseClass {\n    protected object _member;\n    public object MemberGet { return _member; }\n}\n\npublic class InheritClass : BaseClass {\n    // now the base class can "decide" to set the member or implement its own set rules\n    public static void RoutineThatSetsMember(object value) { _member = value; }\n}	0
2291765	2291738	file weight and how many lines in text file - how ? (C#)	long size = (new FileInfo(myFile)).Length;\nint rows = File.ReadAllLines(myFile).Length; //for smaller files	0
1772554	1770297	How does MEF determine the order of its imports?	public interface IRule { }\n\n[Export(typeof(IRule))]\n[ExportMetadata("Order", 1)]\npublic class Rule1 : IRule { }\n\n[Export(typeof(IRule))]\n[ExportMetadata("Order", 2)]\npublic class Rule2 : IRule { }\n\npublic interface IOrderMetadata\n{\n    [DefaultValue(Int32.MaxValue)]\n    int Order { get; }\n}\n\npublic class Engine\n{\n    public Engine()\n    {\n        Rules = new OrderingCollection<IRule, IOrderMetadata>(\n                           lazyRule => lazyRule.Metadata.Order);\n    }\n\n    [ImportMany]\n    public OrderingCollection<IRule, IOrderMetadata> Rules { get; set; }\n}	0
24197846	24197648	how to convert xml to string including declaration	XElement root = new XElement("qcs");\nXElement goal_Name = new XElement("goal", new System.Xml.Linq.XAttribute("name", "abc"));\nroot.Add(goal_Name);\n\nXDocument doc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", string.Empty), root);\n\nvar wr = new StringWriter();\ndoc.Save(wr);\nConsole.Write(wr.GetStringBuilder().ToString());\nConsole.ReadLine();	0
988862	988848	Predicting that the program will crash	AppDomain.CurrentDomain.UnhandledException	0
3046625	3046599	filter results quarterly	for (int i = startingItem; i < list.Count; i += 3)\n{\n    // show list[i]\n}	0
10389864	10389805	Split string at first space	var myString = "1. top of steel";\nvar newString = myString.Remove(0, myString.IndexOf(' ') + 1);	0
6792306	6791930	Which validator control to use to limit a listbox selections to 2?	Protected Sub myCustomVal(ByVal sender As Object, ByVal e As ServerValidateEventArgs)\n\n   If ListBox1.GetSelectedIndices.Length =2 THEN\n      e.isvalid = true\n   Else\n      e.isvalid = false\n   end if\n\nEnd Sub	0
10581920	10581893	How can a store tag's into a list C# asp.net application?	Dictionary<string, string> a = new Dictionary<string, string>();\na.Add("tag", "url");	0
2109455	2109441	How to show Error & Warning Message Box in .NET/ How to Customize MessageBox	MessageBox.Show("Some text", "Some title", \n    MessageBoxButtons.OK, MessageBoxIcon.Error);	0
29164357	29163665	Resize all the windows of an application	private List<Form> Windows { get; set; }\n\npublic Form1()\n{\n    InitializeComponent();\n\n    this.Text = "Main Window";\n    this.Windows = new List<Form>();\n\n    var defaultSize = new Size(200, 100);\n    for (var i = 0; i < 3; i++)\n    {\n        var form = new Form() { Size = defaultSize, Text = "Resize Me" };\n        var suppressEvent = false;\n\n        form.SizeChanged += (sender, e) =>\n        {\n            if (suppressEvent)\n                return;\n\n            suppressEvent = true;\n\n            defaultSize = (sender as Form).Size;\n            foreach (var otherForm in this.Windows)\n            {\n                if (otherForm != sender as Form)\n                    otherForm.Size = defaultSize;\n            }\n            suppressEvent = false;\n        };\n\n\n        this.Windows.Add(form);\n        form.Show();\n    }\n}	0
21381251	21381036	How to convert an integer to date?	int totalHours = 664; // example from question\nTimeSpan ts = TimeSpan.FromHours(totalHours); // or similar\nint days = (int)ts.TotalDays,\n    hours = ts.Hours,\n    // note the next will always be zero\n    // since we init in an integer\n    // number of hours\n    minutes = ts.Minutes,\n    seconds = ts.Seconds;	0
30654037	30494078	Query Password Max Age Policy in Windows	static bool PasswordComplexityPolicy()\n        {\n\n            var tempFile = Path.GetTempFileName();\n\n            Process p = new Process();\n            p.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\secedit.exe");\n            p.StartInfo.Arguments = String.Format(@"/export /cfg ""{0}"" /quiet", tempFile);\n            p.StartInfo.CreateNoWindow = true;\n            p.StartInfo.UseShellExecute = false;\n            p.Start();\n            p.WaitForExit();\n\n            var file = IniFile.Load(tempFile);\n\n            IniSection systemAccess = null;\n            var MaxPasswordAgeString = "";\n            var MaxPasswordAge = 0;\n\n            return file.Sections.TryGetValue("System Access", out systemAccess)\n                && systemAccess.TryGetValue("MaxPasswordAge", out MaxPasswordAgeString)\n                && Int32.TryParse(MaxPasswordAgeString, out MaxPasswordAge)\n                && MaxPasswordAge <= 90;\n\n        }	0
24962985	24946943	array and operator overloading within a struct ,from c++ to c#?	public struct Gene\n{\n    int[] alleles;\n    int fitness;\n    float likelihood;\n\n    public Gene(int[] alleles) : this()\n    {\n        this.alleles = alleles;\n    }\n\n    // Test for equality.\n    public static bool operator ==(Gene gn1, Gene gn2) \n    {\n        for (int i=0; i < gn1.alleles.Length ;i++)\n        {\n            if (gn1.alleles[i] != gn2.alleles[i]) return false;\n        }\n\n        return true;\n    }\n\n    public static bool operator !=(Gene gn1, Gene gn2)\n    {\n        return !(gn1 == gn2);\n    }\n}	0
15834189	15833833	How to give path of a folder in server to save an image?	string path1 = Server.MapPath("");\npath1.Replace("Application1", "Myapplication"); //Considering "Application1" is the name of your current application\npath1 += "/Images/Landing/bottom_banner/";\nHttpPostedFileBase photo = Request.Files["adup"];\n        if (photo.ContentLength != 0)\n        {\n            string lastPart = photo.FileName.Split('\\').Last();\n            Random random = new Random();\n            int rno = random.Next(0, 1000);\n            photo.SaveAs(path1 + rno + lastPart);\n        }	0
7101393	7061935	NHibernate - how to fluently map id based property to be one way from domain model to database	access="readonly"	0
12765594	12765535	Add data to mssql string to byte error c#	string x = TextBox1.Text;\nbyte[] y = System.Text.Encoding.UTF8.GetBytes(x);\n\nnyMedlem.(something of data type byte[]) = y;	0
14437758	14437635	Connecting 2 dropDownLists with SqlDataSource FilterExpression inside ASP:Repeater	DropDownList ddlcity = (DropDownList)grow.FindControl("ddlcity"); // To get the value of dropdown\n\n        cmd.Parameters.Add("@city", ddlcity.SelectedItem.ToString());  // This will add selected item to database	0
11058321	11058235	read custom config file in asp.net	public static string GetSingleValue(string strXPathExpression, string strAttributeName)\n        {\n            XmlNode node = GetNode(strXPathExpression);\n            if (node != null)\n            {\n                XmlAttribute attribute = node.Attributes[strAttributeName];\n                if (attribute != null)\n                    return attribute.Value;\n            }\n\n            return string.Empty;\n\n\n        }	0
4243057	4242856	How to populate a TreeViewControl with hierarchy level?	using (var conn = new SqlCeConnection(connectionString))\nusing (var cmd = conn.CreateCommand())\n{\n    cmd.CommandType = CommandType.Text;\n    cmd.CommandText = @"\nSELECT T.TABLE_NAME, C.COLUMN_NAME\nFROM INFORMATION_SCHEMA.TABLES T\nINNER JOIN INFORMATION_SCHEMA.COLUMNS C\nON T.TABLE_NAME= C.TABLE_NAME\nWHERE T.TABLE_NAME IN('BASE_TABLE', 'BASE TABLE')\nORDER BY 1, C.ORDINAL_POSITION";\n    conn.Open();\n    cmd.Connection = conn;\n    using (var reader = cmd.ExecuteReader())\n    {\n        string lastTable = null;\n        TreeNode tableNode = null;\n        while (reader.Read()) { \n            if (lastTable != reader.GetString(0)) {\n                lastTable = reader.GetString(0);\n                tableNode = new TreeNode(lastTable);\n                myTree.Nodes.Add(tableNode);\n            }\n            tableNode.ChildNodes.Add(new TreeNode(reader.GetString(1)));\n        }\n    }\n}	0
2653543	2626850	How do I paste richtext into a textbox?	string html = Clipboard.GetData(DataFormats.Html).ToString();	0
20217323	20199136	Unable to find datatemplate by resourcekey	NeededTemplate="{StaticResource {dxscht:SchedulerViewThemeKey ResourceKey=HorizontalAppointmentSameDayContentTemplate}}"	0
6803153	5085023	Screen Region Recognition to Find Field location on Screen	Bitmap ImageSearchingWithin=new Bitmap("Location of image"); //or just load from a screenshot or whatever\nfor (int x = 0; x < ImageSearchingWithin.Width - WidthOfImageSearchingFor; ++x)\n{\n    for (int y = 0; y < ImageSearchingWithin.Height - HeightOfImageSearchingFor; ++y)\n    {\n        Bitmap MySmallViewOfImage = ImageSearchingWithin.Clone(new Rectangle(x, y, WidthOfImageSearchingFor, HeightOfImageSearchingFor), System.Drawing.Imaging.PixelFormat.Format24bppRgb);\n    }\n}	0
8605182	8601442	How to raise OnPropertyChanged only for visible elements?	var rows = grid.FindChildren<DataGridRowsPresenter>().First() as DependencyObject;\nint count = VisualTreeHelper.GetChildrenCount(rows);\nfor (int i = 0; i < count; i++)\n{\n    DataGridRow row = VisualTreeHelper.GetChild(rows, i) as DataGridRow;\n    (row.DataContext as IViewModel).Refresh();//Refresh invokes OnPropertyChanged \n}	0
34263132	34262103	Find controls that break the flow in FlowLayoutPanel	Control prevControl = null;\nforeach (Control control in myFlowLayoutPanel.Controls)\n{\n     if (prevControl == null || prevControl.Left > control.Left)\n     {          \n          // line break\n     }\n     prevControl = control;\n}	0
9722363	9691373	Strange result while writing a number in a textbox	double.Parse("562,3") == 5623\ndouble.Parse("562.3") == 562.3	0
204772	204711	How should I check if a flag is set in a flags enum?	fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set\n\n\n(this.Foo & fooFlag) != 0       // result is true if any bits in fooFlag are set	0
11288263	10102460	How to format numbers as string data-types while exporting to Excel in ASP.NET?	Response.Write("<style> TD { mso-number-format:\@; } </style>");	0
27695165	27691559	Winnovative With Parameters in URL	Response.Cookies.Clear ();\nmyCookie.Expires = DateTime.Now.AddDays (1D);	0
15077736	15077593	Populate dynamic created controls with random number	Random rnd = new Random();\nfor (int i = 0; i < 10; i++)\n{\n    int caseInt = rnd.Next(1, 4), myNum = 0;	0
15464558	15464501	MVC3 accessing Repository in Controllers	private IMovieRepository _Repository;\n\n[Inject]\npublic MovieController(IMovieRepository repository)\n{\n    _Repository = repository;\n}	0
3770036	3769953	How can I take a look at the Unicode normalization algorithm in .Net/C# with Mono?	public string Normalize ()\n{\n    return Normalization.Normalize (this, 0);\n}\n\npublic string Normalize (NormalizationForm normalizationForm)\n{\n    switch (normalizationForm) {\n    default:\n        return Normalization.Normalize (this, 0);\n    case NormalizationForm.FormD:\n        return Normalization.Normalize (this, 1);\n    case NormalizationForm.FormKC:\n        return Normalization.Normalize (this, 2);\n    case NormalizationForm.FormKD:\n        return Normalization.Normalize (this, 3);\n    }\n}	0
21313243	21312969	Sorting a dropdown list in C#	DataTable table = dataSet.Tables["TableName"];\nDataView view = table.DefaultView;\nview.Sort = "Criteria";	0
11862689	11862532	How to compile all files to one exe?	private void Form1_Load(System.Object sender, System.EventArgs e)\n{\n    System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();\n    Stream myStream = myAssembly.GetManifestResourceStream("EmbeddingExample.image1.bmp");\n    Bitmap image = new Bitmap(myStream);\n\n    this.ClientSize = new Size(image.Width, image.Height);\n\n    PictureBox pb = new PictureBox();\n    pb.Image = image;\n    pb.Dock = DockStyle.Fill;\n    this.Controls.Add(pb);\n}	0
21020633	21020284	JSON Deserialization in C# for multiple values	var json = "{\"totalcount\":1,\"files\":[{\"filename\":\"1.txt\",\"fileContent\":\"Dineshkumar\"}]}";\n\nJavaScriptSerializer JSSfile = new JavaScriptSerializer();\nJSSfile.MaxJsonLength = Int32.MaxValue;\nJSONObject Content = JSSfile.Deserialize<JSONObject>(json);\n\nif (Content.totalcount == 1)\n{\n    File file = new File(); //CREATE A NEW FILE OBJECT HERE <------\n    file.filename = Content.files[0].filename;\n    file.fileContent = Content.files[0].fileContent;\n}	0
27689115	27688912	Is it possible to copy the contents of a panel to another panel	foreach(Control c in Panel1.Controls)\n{\n    var control = Panel2.Controls.AsEnumerable().Where(p => p.name = c.name).select();\n    Textbox txt = control as TextBox;\n    c.Text = txt.Text;\n}	0
4564070	4563774	Accessing ViewContext from class library	var httpContext = new HttpContextWrapper(HttpContext.Current);\nvar routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(httpContext);\n\nvar controllerName = routeData.Values["controller"].ToString();\nvar actionName = routeData.Values["action"].ToString();	0
18685303	18685199	Load all documents from RavenDB	session.Query<Model.Category>().Customize(cr => cr.WaitForNonStaleResults()).ToList();	0
10016028	10015998	XML - how to use namespace prefixes	XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);	0
11119074	11118910	How to serialize and deserliaze a Dictionary<string,object> in WinRT (Metro app in C# and XAML)?	[KnownType(typeof(SerializeListWinRT.Cat))]	0
34465111	34464876	Access to a textbox in gridview and set its value	TextBox Password = GridView1.FooterRow.FindControl("txtPassword") as TextBox;\n\nif (Password != null)\n    Password.Text = "Hello";	0
14900294	14900241	retrieve index value after sorting Enum alphabetically	var sorted = (from e in Enum.GetValues(typeof(EnumType)).Cast<EnumType>()\n              orderby e.ToString() select e).ToList();	0
12905320	12904920	Map parameter to ignored property in service stack?	int? Id	0
9760241	9760218	Windows Phone 7 Async Method multiple invocations	Task<T>	0
933193	933180	datetime picker in C#	this.dateTimePicker1.CustomFormat = "MMMM dd, yyyy hh:mm";\nthis.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom;	0
26368277	26367548	Returning from a task without blocking UI thread	/// <summary>\n/// Interaction logic for MainWindow.xaml\n/// </summary>\npublic partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n    }\n\n    private async void Button_Click(object sender, RoutedEventArgs e)\n    {\n        statusText.Text = "Running";\n        statusText.Text = await _ComputeText(true);\n        statusText.Text = await _ComputeText(false);\n    }\n\n    private static async Task<string> _ComputeText(bool initialTask)\n    {\n        string result = await Task.Run(() =>\n            {\n                Thread.Sleep(2000);\n                return initialTask ? "Task is done!" : "Idle";\n            });\n\n        return result;\n    }\n}	0
32763250	32762897	GroupBy a bindingList	list.GroupBy(x => x.Message)\n    .Select(x => new { Message = x.Key, Count = x.Count() })	0
5336587	5336553	C# print screen active window	// Set the bitmap object to the size of the screen\nbmpScreenshot = new Bitmap(this.Bounds.Width, this.Bounds.Height,\n                           PixelFormat.Format32bppArgb);\n// Create a graphics object from the bitmap\ngfxScreenshot = Graphics.FromImage(bmpScreenshot);\n// Take the screenshot from the upper left corner to the right bottom corner\ngfxScreenshot.CopyFromScreen(this.Bounds.X, this.Bounds.Y, 0, 0,\n                             this.Bounds.Size, CopyPixelOperation.SourceCopy);\n\nSaveFileDialog saveImageDialog = new SaveFileDialog();\nsaveImageDialog.Title = "Select output file:";\nsaveImageDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";\n//saveImageDialog.FileName = printFileName;\nif (saveImageDialog.ShowDialog() == DialogResult.OK)\n{\n    // Save the screenshot to the specified path that the user has chosen\n    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png);\n}	0
15078164	15078097	How to get all selected rows if only parts of rows are selected?	var selected = ElementsTableView\n               .SelectedCells\n               .Cast<DataGridViewCell>()\n               .Select(c => c.OwningRow)\n               .Distinct();	0
17615162	17615089	Using static variable in C#	list.Add(a.ToList()); // See Chris Sinclair's example, full credit to him	0
4596641	4596600	Can't detect a Ctrl + Key shortcut on keydown events whenever there's a readonly textbox with focus	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n  if (keyData == (Keys.Control | Keys.F)) {\n    MessageBox.Show("What the Ctrl+F?");\n    return true;\n  }\n  return base.ProcessCmdKey(ref msg, keyData);\n}	0
30364752	30364685	c# Substring doesn't find string	int pTo = St.IndexOf(lastPart, pFrom);	0
19542690	19542569	LINQ Dynamically Select Column From Column Name	var ss = liDeatil.Select(s => new MyClass{ Id = s.Id ,\nMarks = (string)s.GetType().GetProperty("ColumnMarks").GetValue(s,null)}).Tolist();	0
2505813	2505633	How to normalize / refactor e-commerce tables to Pocos when the data is much like EAV	Product.ProductGroups.SelectMany(gp => gp.ProductOptionGroups.SelectMany(pog => pog.ProductOptions))	0
19984461	16484623	Is there a way to know if there is a IWin32Window already created?	System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);	0
5141060	5141018	DateTime comparison, minus certain timeframe? c#	DateTime.Compare(dt1.Date,dt2.Date)	0
8584344	8584310	Is there a Math.PI equivalent that returns a float?	const float PI = (float)Math.PI;	0
12566464	12538367	Using CredEnumerate to pull WebCredentials	Windows.Security.Credentials.PasswordVault	0
19260377	19260105	How to bind a value to a variable in a programmatically generated Linq Expression	// Given this class, which is equivalent to the compiler-generated class\nclass Holder {\n    public int AnInteger;\n}\n\nint id = 1;\n\n// You get the same SQL with a plain lambda function\n\nvar query = db.Items.Where(i => i.Id == id);\n\n// or with a handwritten expression:\n\nvar arg = Expression.Parameter(typeof(Item), "i");\n\nvar paramHolder = new Holder {??AnInteger = id };\n\n// essentially, (i) => i.Id == paramHolder.AnInteger\nvar lambda = Expression.Lambda<Func<Item, bool>>(\n    Expression.Equal(\n        Expression.Property(arg, "Id"),\n        Expression.Field(\n            Expression.Constant(paramHolder), "AnInteger")),\n    arg);\n\n// the SQL this translates to is equivalent to that of the first query\nvar query2 = db.Items.Where(lambda);	0
28572153	28571575	Windows phone WNS notification navigation to specific page	var toast = @"<toast launch=""?page=foo&id=7""><visual><binding template=""ToastText01""><text id=""1"">" + datatoshow + "</text></binding></visual></toast>";	0
30485029	30484286	Serializing a treenode like data structure	var serializer = new XmlSerializer(typeof(MyClass));\n\nusing (var ms = new MemoryStream())\n{\n    var sw = new StreamWriter(ms);\n    serializer.Serialize(sw, _class);\n\n    sw.Flush();\n\n    ms.Position = 0;\n    var sr = new StreamReader(ms);\n    var myStr = sr.ReadToEnd();\n    Console.WriteLine(myStr);\n}	0
28710948	28710837	Using Reflections i need to set value from ENums	if (prop.PropertyType.IsEnum)\n                                {\n                                    Object valueSet = Enum.Parse(prop.PropertyType, childElement.Value, true);\n                                    prop.SetValue(obj, valueSet, null);\n                                }\n                                else\n                                {\n                                    prop.SetValue(obj, Convert.ChangeType(childElement.Value, prop.PropertyType), null);\n                                    break;\n                                }	0
9585387	9580721	How can i set the parentaccountid in dynamic CRM using Main Data Web Service?	Lookup parentAccount = new Lookup();\nparentAccount.type = EntityName.account.ToString();\nparentAccount.Value = new Guid("GUID of The Parent Account");\nnewAccount.parentaccountid = parentAccount;	0
21303971	21303900	Dynamically created href attributes in C#	href.Controls.Add(Image);\nhref.Attributes.Add("href", "http://www.google.com");\nhref.Attributes.Add("target", "_blank");\nhref.Attributes.Add("title", "Click To Follow The Link");	0
11526774	11526636	Grabbing InnerText of a H3 using Html Agility Pack	RemoveChild(...)	0
20667640	20666180	How to split DataTable into multiple DataTables based on value in 1st Column in c#?	// Fill Employee names in each row\nstring fullName = "";\nfor (int i = 0; i < dt.Rows.Count; i++)\n{\n    if (dt.Rows[i][0].ToString() != "")\n    {\n        fullName = dt.Rows[i][0].ToString();\n    }\n    else\n    {\n        dt.Rows[i][0] = fullName;\n    }\n}\n\n// Split into tables by each employee\nList<DataTable> employeesTables = dt.AsEnumerable()\n                        .GroupBy(row => row.Field<string>("F1"))\n                        .Select(g => g.CopyToDataTable())\n                        .ToList();	0
16976849	16976810	remove all numbers from textbox C#	var output = Regex.Replace(textbox.Text, @"[\d-]","");	0
27627367	27627134	Split field when deserializing JSON object	public static MemberList memList()\n{            \n    WebClient atv = new WebClient();\n    var data = atv.DownloadString("https://www.somewebsvc.com/memberships");\n    MemberList m = Newtonsoft.Json.JsonConvert.DeserializeObject<MemberList>(data);\n    foreach (Member mb in m.members)\n        {\n            string[] names = mb.Name.Split(new char[] { ' ' }, 2);\n            mb.FirstName = names[0];\n            mb.LastName = names[1];\n        }\n    return m;\n}	0
19585148	19585048	Strange Behaviour with Ajax	[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]	0
6486341	6486195	Ensuring only one application instance	[STAThread]\n    static void Main()\n    {\n        bool result;\n        var mutex = new System.Threading.Mutex(true, "UniqueAppId", out result);\n\n        if (!result)\n        {\n            MessageBox.Show("Another instance is already running.");\n            return;\n        }\n\n        Application.Run(new Form1());\n\n        GC.KeepAlive(mutex);                // mutex shouldn't be released - important line\n    }	0
1270727	1270584	How to generate a random named text file in C#?	// selected characters\nstring chars = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";\n// create random generator\nRandom rnd = new Random();\nstring name;\ndo {\n   // create name\n   name = string.Empty;\n   while (name.Length < 5) {\n      name += chars.Substring(rnd.Next(chars.Length), 1);\n   }\n   // add extension\n   name += ".txt";\n   // check against files in the folder\n} while (File.Exists(Path.Compbine(folderPath, name)))	0
24315342	24314992	How get the max length value of an array?	Values.OrderByDescending(o => o.Length).First()  //max value\nlist.Max(o => o.Length) //max length	0
1602626	1602247	Execute WPF Element validation in C#?	BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);\nexp.UpdateSource();	0
26886044	26884864	Can I extract binary data that I can inspect while debugging?	[Conditional("DEBUG")]\npublic static void WriteBytesToTempFile(byte[] fileContent)\n{\n    var tempFileName = "c:\temp.pdf";\n\n    if (File.Exists(tempFileName))\n        File.Delete(tempFileName);\n\n    using (var writer = new BinaryWriter(File.Open(tempFileName, FileMode.Create)))\n    {\n       writer.Write(fileContent);\n    }\n }	0
3920190	3920160	Convert street address from string to columns - Regex?	(\D+) ([^-]+) - ([^,]+, \w+) ([\d-]+) ([\d-]+)	0
12647429	12647305	Dispose objects read from BlockingCollection	BlockingCollection<T>	0
6429421	6423082	Oracle Link - updating entity element sent via Web Service	DataContext lContext = new DataContext();\nlContext.InvoiceHeaders.Attach(iHeader, true);\nlContext.SubmitChanges();	0
27662763	27659807	Centering control vertically in relation to chunk of text in textbox	while (m.Success) {\n    string new_s = str.Substring(m.Index);\n    string new_p = "</" + m.Groups["tag"].Value + ">";\n    Match m_end = Regex.Match(new_s, new_p);\n    Point start_p = textBox1.GetPositionFromCharIndex(m.Index);\n    Point end_p = textBox1.GetPositionFromCharIndex(m_end.Index + m.Index);\n    int top = (int)start_p.Y;\n    int bottom = (int)(end_p.Y + textBox1.Font.Size);\n    if (m_end.Success) {\n        int midpoint = (top + bottom) / 2;\n        PictureBox pictureBox = new PictureBox();\n        pictureBox.Name = "pictureBox" + i.ToString();\n        pictureBox.Location = new System.Drawing.Point(15, midpoint + 7 + 2);\n        pictureBox.Image = Image.FromFile("c:\\blob.png");\n        pictureBox.Size = new Size(15, 15);\n        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;\n        this.Controls.Add(pictureBox);\n    }\n    i++;\n    m = r.Match(str, m_end.Index + m.Index);\n}	0
15262544	15262494	Convert from a string to datetime	var input = "2004/01/02 12:01:03";\nDateTime aDate;\nDateTime.TryParse(input, out aDate);\nstring output = aDate.ToString("yyyyMMddHHmmss");	0
5052664	5052627	Prevent loading an assembly in c#	Assembly.GetEntryAssembly	0
22071334	22071237	Foreach while a value is same as previous value	List<string> result = myTuple.GroupBy(t => t.Item1)\n                     .Select(g => String.Join(" ", g.Select(tp=>tp.Item2)))\n                     .ToList();	0
5788416	5788329	Count total rows of gridview with pagination	DataTable.Rows.Count	0
3231979	3231969	Download file from URL to a string	string contents;\nusing (var wc = new System.Net.WebClient())\n    contents = wc.DownloadString(url);	0
31942825	31942662	LINQ Lambda, need to query to a very confuse database, how should I do it?	var absences = from p in db.TimePeriods\n               join a in db,Absences on p.IDTimePeriod = a.Periond\n               where p.StartTime.Year = theYear\n               where a.Employee.ID = theEmployeeId\n               select a;	0
4275079	4274891	Commit DataGridView cell edit only when a certain key is pressed	private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)\n    {\n        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();\n        if(!ValidateData(data))\n            e.Cancel = true;\n    }\n\n    private bool ValidateData(string data)\n    {\n        // do validation which u want to do.\n    }\n\n    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)\n    {\n        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();\n        SaveData(data);\n    }\n\n    private void SaveData(string data)\n    {\n        // save data\n    }	0
21600771	21486397	Accurately Set the MySqlCommand Parameter Size	SqlDbType[] sqlDType = new SqlDbType[] {SqlDbType.Int, SqlDbType.Float, SqlDbType.SmallInt, SqlDbType.TinyInt};\nint[] sqlSize = new int[] { 4, 8, 2, 1 };\nSqlDbType type = SqlDbType.Float;\nint iIndex = Array.IndexOf(sqlDType, type);\nint iSize = -1;\nif (iIndex > -1)\n    iSize = sqlSize[iIndex];	0
14140274	13953020	oracle odp.net SafeMapping conversion if timestamp with timezone - how to get offset instead of zone name	dataAdapter.ReturnProviderSpecificTypes = true;	0
14852783	14850906	Post to a friends wall	var fbApplication = new DefaultFacebookApplication { AppId = fbapp, AppSecret = fbsec };\n            var current = new FacebookWebContext(fbApplication);\n\n            Facebook.Web.FacebookWebClient client = new Facebook.Web.FacebookWebClient(token);\n            //client.AccessToken = current.AccessToken;   \n            dynamic parameters = new ExpandoObject();\n            parameters.message = "";\n            parameters.link = link;\n            parameters.name = name;\n            parameters.caption = caption;\n            parameters.description = desc;\n            parameters.from = fromId;//your fb ID\n//friendId will be the ID of the person,you wants to post on wall\n            object resTest = client.Post("/" + friendId + "/feed", parameters);	0
996943	996848	How to use IPAddress and IPv4Mask to obtain IP address range?	Address:   192.168.127.100       11000000.10101000.01111 111.01100100\nNetmask:   255.255.248.0 = 21    11111111.11111111.11111 000.00000000\nWildcard:  0.0.7.255             00000000.00000000.00000 111.11111111\n=>\nNetwork:   192.168.120.0/21      11000000.10101000.01111 000.00000000\nBroadcast: 192.168.127.255       11000000.10101000.01111 111.11111111\nHostMin:   192.168.120.1         11000000.10101000.01111 000.00000001\nHostMax:   192.168.127.254       11000000.10101000.01111 111.11111110	0
31110531	31110339	Linq to XML - Read/Parse only first lines of the file	using (var xmlReader = XmlReader.Create(pathXmlFile))\n{\n    if (xmlReader.ReadToFollowing("Header"))\n    {\n        XmlReader headerSubtree = xmlReader.ReadSubtree();\n        XElement headerElement = XElement.Load(headerSubtree);\n\n        // process headerElement\n        Console.WriteLine(headerElement.Element("Type").Value);\n        Console.WriteLine(headerElement.Element("Content").Value);\n    }\n}	0
24437307	24437274	string.IndexOf search for whole word match	string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";\nvar indx = Regex.Match(str, @"\WTOTAL\W").Index; // will be 18	0
2853511	2853473	How to use LINQ to query list of strings that do not contain substring entries from another list	var nonJedi = candidates.Where(c => !disregard.Any(d => c.EndsWith(d)));	0
13594576	13594434	Dynamically altering the image source of a canvas object	public static void Clouds(Canvas canvas, int boundry)\n        {\n            var random = new Random();\n            foreach (var image in canvas.Children.OfType<Image>())\n            {\n                if (image.Name.Contains("cloud_"))\n                {\n                    if (Canvas.GetLeft(image) < canvas.ActualWidth + image.Width)\n                    {\n                        Canvas.SetLeft(image, Canvas.GetLeft(image) + 1);\n                    }\n                    else\n                    {\n                        Canvas.SetTop(image, random.Next(0 - ((int)image.Height / 2), Core.GetPercentage((int)canvas.ActualHeight, boundry)));\n                        Canvas.SetLeft(image, 0 - image.Width);\n                    }\n                }\n            }\n        }	0
11109755	11109666	Render image to a page	WebRequest webRequest = WebRequest.Create("http://www.google.com/images/img.png");\nusing(WebResponse response = webRequest.GetResponse())\n{\n    using(MemoryStream stream = new MemoryStream(response.GetResponseStream())\n    {\n         stream.WriteTo(Response.OutputStream);\n    }\n}	0
31060818	31060551	How to get ToDictionary to work in F#?	ToDictionary(id, fun v -> if v % 2 = 1 then "Odd" else "Even")	0
7247545	7247418	Refreshing Windows Forms controls between actions in a 'for' loop	// in for loop\ntbxMyTextBox.Text = "New text!";\ntbxMyTextBox.Refresh();	0
4243338	4243270	How to get full host name + port number in Application_Start of Global.aspx?	void Application_BeginRequest(Object source, EventArgs e)\n    {\n        HttpApplication app = (HttpApplication)source;\n        var host = FirstRequestInitialisation.Initialise(app.Context);\n    }\n\n    static class FirstRequestInitialisation\n    {\n        private static string host = null;\n        private static Object s_lock = new Object();\n\n        // Initialise only on the first request\n        public static string Initialise(HttpContext context)\n        {\n            if (string.IsNullOrEmpty(host))\n            {\n                lock (s_lock)\n                {\n                    if (string.IsNullOrEmpty(host))\n                    {\n                        var uri = context.Request.Url;\n                        host = uri.GetLeftPart(UriPartial.Authority);\n                    }\n                }\n            }\n\n            return host;\n        }\n    }	0
14024029	14023963	Same CPU ID on two Intel machines	using System.Management;\nManagementObjectSearcher searcher = new ManagementObjectSearcher(\n"select * from " + whatever_id);	0
12391197	12391153	How do i loop through two Lists to compare items in both Lists?	IEnumerable<string> notVisitedSites = currentSites.Except(visitedSites);	0
22999413	22999282	Unable to do a query using a textbox input	string query = "SELECT * FROM PERSONS WHERE Name='" + name + "'";	0
10638314	10638256	Finding the least used CPU core with c#	var coreUsages = new PerformanceCounter[Environment.ProcessorCount];\n\nfor (var i = 0; i < coreUsages.Length; i++)\n{\n     coreUsages[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());\n     coreUsages[i].NextValue();\n}\n\nThread.Sleep(1000);\n\nfor (var i = 0; i < coreUsages.Length; i++)\n{\n     //using the status bar as output for now, doesn't really matter\n     Trace.WriteLine("   |   " + coreUsages[i].CounterName + " ~ " + coreUsages[i].NextValue());\n}	0
30059986	30059610	C# listbox array trouble	while (listBox1.SelectedIndex != 0)\n{\n    selectedTeam = listBox1.SelectedItem.ToString();\n}	0
5278614	5278569	Sending My Own Arguments To A Event Handler?	var a = AppDomain.CurrentDomain;\na.AssemblyResolve += (object s,ResolveEventArgs a) => HandleIt(s,a,someArgument);\n\nPrivate Assembly HandleIt(object sender, ResolveEventArgs args, SomeType arg){\n    //Does stuff, returns an assembly\n}	0
16928625	16928550	Using linq on a SharePoint list object	SPWeb   web   = SPContext.Current.Web;\nSPList  list  = web.Lists[LISTNAME];\nSPQuery query = new SPQuery\n{\n    Query = @"<Where>\n                 <Contains>\n                    <FieldRef Name='Field' />\n                    <Value Type='Text'>your value</Value>\n                 </Contains>\n              </Where>"\n};\nSPListItemCollection items = list.GetItems(query);	0
11303524	11302530	Enumerate over each item of listbox to compare internal element values	ListBox l = myListBox;\nfor (int i = 0; i < l.Items.Count; i++)\n{\n    var boundObject = (MyClass)l.Items[i];\n    MessageBox.Show("They are equal? " + (boundObject.A == boundObject.B));\n}	0
8082952	8082822	How to build a LINQ to XML query with a conditional selection	var result = from name in names\n                 select new Person()\n                   {\n                      First = name.Type == PersonType.Fracais ? name.PreNom : name.First,\n                      Last = name.Last\n                   };	0
14708684	14708574	Comparing DataGridView's Cell Value With string	if (dgvPeople.CurrentRow.Cells[6].Value.ToString() == "1")\n        {\n            chkGerman.Checked = true;\n        }\n        else chkGerman.Checked = false;	0
33231392	32964290	Oultook 2013 InlineResponse - Disable Forward button	Private Sub myOlExp_InlineResponse(ByVal Item As Object)\nDim a As MailItem\nSet a = Item\nIf a.To = "" Then\n    a.Close olDiscard ???close the mail item\n    MsgBox "Forward is not supported"\nEnd If\nEnd Sub	0
10146964	9894183	Transferring selenium into nunit	[TestFixture]\nclass MyTestFixture\n{\n    protected IWebDriver driver;\n    protected IWebElement name;\n    protected IWebElement button;\n\n    [TestFixtureSetUp]\n    public void Init()\n    {\n        driver = new FirefoxDriver();\n        driver.Navigate().GoToUrl(urlString);\n        name = driver.FindElement(By.Id("UserName"));\n        button = driver.FindElement(By.ClassName("sign in"));\n    }\n\n    [Test]\n    public void MyTest\n    {\n     // ...\n    }\n}	0
7108976	3885549	WSS3 - setting a default value on a SPFieldType.Boolean after creation	var list = web.Site.RootWeb.Lists["ListWithFieldOnIt"];\n       var field = list.Fields.GetField("booleanfield");\n       field.DefaultValue = "1";\n       field.Update();	0
9336245	9334594	Finding a method's declaring type	MethodSymbol method = ...;\nTypeSymbol type = method.ContainingType;\nMethodSymbol disposeMethod = (MethodSymbol)c.GetSpecialType(SpecialType.System_IDisposable).GetMembers("Dispose").Single();\nbool isDisposeMethod = method.Equals(type.FindImplementationForInterfaceMember(disposeMethod));	0
33274937	33272600	Passing a parameter from a listview to crystal report	report.SetParameterValue("@UserID", ID);	0
20204962	20204927	Should I assert that a dependency's method is called in every unit test for a given method?	_service.AnotherMethod(input)	0
21749004	21748858	How do I ensure full coverage of a localization resource file in Visual Studio?	MessageBox.Show(Resource1.file_not_found)	0
9015169	9015142	Creating a database programmatically in SQL Server	Create database 'Databasename'	0
921994	921970	How do I create a generic DataContext factory?	GetTable<T>()	0
11316771	11316711	Parse Number Data from Letters C#	Range = double.Parse(RxString.Substring(1))	0
625471	623636	.NET TIFF file: RGB to CMYK conversion possible without a third party library?	Stream imageStream = new\n        FileStream(@"C:\temp\mike4.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);\n    BitmapSource myBitmapSource = BitmapFrame.Create(imageStream);\n    FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();\n    newFormatedBitmapSource.BeginInit();\n    newFormatedBitmapSource.Source = myBitmapSource;\n    newFormatedBitmapSource.DestinationFormat = PixelFormats.Cmyk32;\n    newFormatedBitmapSource.EndInit();\n\n    BitmapEncoder encoder = new TiffBitmapEncoder();\n    encoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));\n\n    Stream cmykStream = new FileStream(@"C:\temp\mike4_CMYK.tif",\n\n    FileMode.Create, FileAccess.Write, FileShare.Write);\n    encoder.Save(cmykStream);\n    cmykStream.Close();	0
29325629	29325592	How to set 'mouseover' event for per gridview row?	protected void OnRowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        e.Row.ToolTip = (e.Row.DataItem as DataRowView)["Description"].ToString();\n    }\n}	0
6181948	6181798	c# winform - using timer to animate drop down menu	//This would be your FormLoad event or somewhere else where you initialize your form information\n    private void form_load()\n    {\n        enterTimer.Interval = 10;\n        enterTimer.Tick += new EventHandler(enterTimer_Tick);\n        leaveTimer.Interval = 10;\n        leaveTimer.Tick += new EventHandler(leaveTimer_Tick);\n    }\n\n    private void setForm()\n    {\n        this.Location = new Point(Screen.GetWorkingArea(this).Width - this.Width, Screen.GetWorkingArea(this).Height - this.Height);\n    }\n\n    Timer enterTimer;\n    Timer leaveTimer;\n\n    private void B00nZPictureBox_MouseEnter(object sender, EventArgs e)\n    {\n        enterTimer.Start();\n    }\n\n    private void B00nZ_MouseLeave(object sender, EventArgs e)\n    {\n        leaveTimer.Start();\n    }\n\n    void enterTimer_Tick(object sender, EventArgs e)\n    {\n        //Put your enter logic here\n    }\n\n    void leaveTimer_Tick(object sender, EventArgs e)\n    {\n        //Put your leave logic here\n    }	0
20690493	20669802	query and create objects with a one to many relationship using LINQ	orders = Context.orders\n    .GroupJoin(\n        Context.suborders,\n        o => o.id,\n        so => so.order_id,\n        (o, so) => new { order = o, suborders = so })\n    .ToList()\n    .Select(r => new Order\n    {\n        id = r.order.id,\n        name = r.order.name,\n        suborders = r.suborders.Select(so => new Suborder\n        {\n            id = so.id,\n            name = so.name\n        }.ToList()\n    }).ToList();	0
25814526	25814471	Select second row in a join LINQ statement	var books = from b in db.Books\n            join a in db.Authors on b.Id equals a.BookId\n            into authors\n            select new {\n               Book = b,\n               SecondAuthor = authors.Skip(1).FirstOrDefault(),\n            };	0
21261525	21260831	Write a byte array to text file between existing text	sw.Write("set @FisierNou = 0x");\nfor (int i = 0; i < Fisier.Length; i++) \n  sw.Write(Fisier[i].ToString("x2"));	0
21503206	21503109	How to use EnumWindows to get only actual application windows?	[DllImport("user32.dll", SetLastError = true)]\nprivate static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n\nstatic bool IsAppWindow(IntPtr hWnd)\n{\n    int style = GetWindowLong(hWnd, -16); // GWL_STYLE\n\n    // check for WS_VISIBLE and WS_CAPTION flags\n    // (that the window is visible and has a title bar)\n    return (style & 0x10C00000) == 0x10C00000;\n}	0
15532674	15509306	Joined sub-classes inheriting from unmapped, abstract intermediate classes	class MyInspector : ExplicitlyDeclaredModel {\n    public override bool IsEntity(Type type) {\n        if (type == typeof (BusinessContact))\n            return false;\n        return base.IsEntity(type);\n    }\n}\n\nvar mapper = new ModelMapper(new MyInspector());	0
19865113	19865086	How to run nunit tests iteratively	[Test]\npublic void MyTest([Range(0, 10)] int iteration)\n{\n...\n}	0
13829575	13829116	How can I calculate the time that a specific operation (pre-defined function) needs to finish?	{400, 200, 900, 100, 400 ms}	0
23761862	23754510	How to assign two lists in a linq query with some conditions?	var arr = new int[query.Count];\n    int cnt = query.Count - 1, toappendindex = -1;\n    Func<int,int,int> getval = (ind, val) =>\n    {\n        if (val == 3 || val == 4) return  0;\n        if (val == 2 || val == 1) return  1;\n        if (ind == cnt) return -1;\n        return arr[ind + 1];\n    };   \n    for (int ind = cnt; ind >= 0; ind-- ) \n    {\n        if ((arr[ind] = getval(ind,query[ind])) == -1)\n            toappendindex = ind; //only if there are trailing 0's\n    }\n    if (toappendindex > 0) \n        for (; toappendindex < arr.Length; toappendindex++) arr[toappendindex] = arr[toappendindex - 1];\n\n    //var lst2 = arr.ToList(); if list is needed instead of array, otherwise arr could be used directly	0
33507951	33507899	How deserialize json to object	Fixture fixture = JsonConvert.DeserializeObject<Fixture>(jsonString);	0
29349183	29349015	ASP.NET: how to set security of a file based on the app pool	IIS APPPOOL\AppPoolName	0
26469187	26467480	Trouble with creating export control for Sitefinity widget using MVC	public ActionResult Index()\n{ \n    List<PageNode> pageArray = new List<PageNode>();\n\n    //// Use Sitefinity API get all pages\n    IQueryable<PageNode> pageNodes = App.WorkWith().Pages().Where(pN => (pN.Page != null && pN.Page.Status == ContentLifecycleStatus.Live)).Get();\n    foreach (var page in pageNodes) \n       pageArray.Add(page);\n\n    return Json(pageArray, JsonRequestBehavior.AllowGet);\n}	0
2085041	2084976	DataGridView get current selected object	DataGridViewRow.DataBoundItem	0
33985462	33985423	Best way to prevent parameter tampering and send values with Javascript?	[HttpPost, Authorize] \npublic ActionResult DoSomeStuff (string leagueName, string doSomething)  {\n    var service = new Service(_db);\n    var league = service.GetLeague(leagueName);\n\n    // Now check whether the current user has access/permission \n    // to perform some operation on this league.\n    // Ex : if(!service.IsUserAuthorizedToDoSomething(league))\n    //     {\n    //      return View("NotAuthorized");\n    //     }\n    //to do: Return something\n}	0
10839736	10839597	Refresing a SWF loaded in a c# windows form	axShockwaveFlash.LoadMovie(0, "EmptySwf.swf");\naxShockwaveFlash.LoadMovie(0, "RealProjectSwf.swf");	0
1819305	1819116	problem in linq with comma separation of string	var _products = Enumerable.Range(0, _productId.Count)\n                          .Select(i => new\n                              {\n                                  Id = _productId[i],\n                                  Name = _productName[i],\n                                  Cat = _prodCat[i],\n                                  Quantity = _quantity[i],\n                                  RetailPrice = _retailPrice[i]\n                              });	0
21338036	21291185	Creating a MVC4-Controller using Entity Framework	//\n    // GET: /Report/\n\n    public ActionResult Index()\n    {\n        IQueryable<udf_GetReportsByController_Result> result = db.udf_GetReportsByController(User.Identity.Name);\n        return View(result.ToList());\n    }\n}	0
29493768	29493296	Ordering a list by currency value	Regex r = new Regex(@"(\d+)");\n\nlist.OrderByDescending(x => int.Parse(r.Match(x.Denomination).Groups[1].Value))\n    .ThenBy(x => x.Denomination);	0
8177666	8121506	WCF basicHttpBinding Setting Credential hosted in Windows service	client.ClientCredentials.UserName.UserName = UserId;\nclient.ClientCredentials.UserName.Password = Password;	0
9971768	9971728	Culture-Based String Formatting For Decimal	return (score * Resources.Global.ScoreModifier).ToString(Resources.Global.ScoreFormat);	0
2316534	2316308	Remove readonly attribute from directory	var di = new DirectoryInfo("SomeFolder");\ndi.Attributes &= ~FileAttributes.ReadOnly;	0
15197985	15197904	How to change WebBrowser control User Agent in C#	WebBrowser wc = new WebBrowser();\nwc.Navigate("http://google.com", null, null, "User-Agent: User agent");	0
18050746	18050714	How can I select all the text within a Windows Forms textbox?	textBoxResults.SelectAll();\ntextBoxResults.Focus(); //you need to call this to show selection if it doesn't has focus	0
9006521	9005721	How to keep colors when copy-pasting from datagridview to excel?	if (e.KeyData.ToString() == "C, Control") {  your formatting code goes here  \n}	0
31645778	31645743	How to change color text in button?	if(button.ForeColor == Color.Green)\n    //handle the click event	0
18023358	18023255	Stop Command Prompt from closing so quickly	strCmdText = "/K [enter command stuff here]";	0
5098707	5098632	How can I select all in linq to sql	var filteredLesson = (from l in storeDB.lessons\n                      where\n                          (l.statusID == SUBMITTED || l.statusID == APPROVED)\n                          &&\n                          (!l.projectID.HasValue || l.projectID == lesson.projectID)\n                      select l\n                     ).ToList();	0
18057880	18057665	C# how to iterate over excel columns	foreach (Excel.Range item in col.Cells)\n    {\n        //whatever you want to do with your cells, here- msgbox of cells value\n        MessageBox.Show(Convert.ToString(item.Value));\n    }	0
20651303	20651190	Convert all the character in a string to "*"	var s = "I am a boy";\n\nvar q = new string('*', s.Length);	0
4943634	4941152	How to enable Virtual Space in AvalonEdit?	textEditor.Options.EnableVirtualSpace = true;	0
2231953	2231917	MailMessage setting the Senders Name	MailMessage mail = new MailMessage();\nmail.From = new MailAddress("nerfDeathKnights@mycompany.com", "Bob Jones" );	0
15162552	15128721	Blocking a contact with Skype4com	ISkype skype = _skype;\nvar tbb = skype.Friends.Cast<User>().Where(u => u.FullName.Contains("xxx");\nforeach(User notAFriend in tbb)\n{\n   notAFriend.IsBlocked = true;\n   MessageBox.Show(friend.FullName + " " + friend.IsBlocked);\n}	0
26731664	26517023	Move to Following Date Part on Data Entry in DateTimePicker	(this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Provider as MaskDateTimeProvider).SelectNextEditableItem();	0
27472485	27472321	How can i get from listView1 all the selected items and add them to string[]?	List<String> selected = new List<String>();\n        foreach(ListViewItem lvi in listView1.SelectedItems)\n        {\n            selected.Add(lvi.Text);\n        }\n        AllFiles = selected.ToArray();	0
17348958	17303813	How do I load data into a Crystal Report with Sub Reports in ASP .NET?	var rpDoc = new TVDataSchedule();\n\nrpDoc.SetDataSource(finalSchedulesTable);\n\nReportDocument subShows = rpDoc.Subreports["subShows"];\nsubShows.SetDataSource(finalShowsTable);\n\ncrvSchedules.ReportSource = rpDoc;\n\ncrvSchedules.DataBind();	0
26467249	26461760	Gridview Rows Sorting using DragDrop	gridView_gruphaber.RowLoaded += new EventHandler<RowLoadedEventArgs>(gridView_News_RowLoaded);\n\nvoid gridView_News_RowLoaded(object sender, RowLoadedEventArgs e)\n    {\n        GridViewRow row = e.Row as GridViewRow;\n        if (row != null)\n        {\n            row.PreviewDrop += new DragEventHandler(row_PreviewDrop); \n        }\n    }\n\n    private int droppedRowIndex = -1;\n    void row_PreviewDrop(object sender, DragEventArgs e)\n    {\n        GridViewRow row = sender as GridViewRow;\n\n        if (row != null)\n        {\n            CommonHaber droppedCommonHaber = row.Item as CommonHaber;\n\n            droppedRowIndex = gridView_gruphaber.Items.IndexOf(droppedCommonHaber);\n\n        }\n    }	0
1725248	1725213	How to return an object that implements an interface from a method	class ProductA_User : ICustomer\n{\n    //... implement ICustomer\n}\nclass ProductB_User : ICustomer\n{\n    //... implement ICustomer\n}\nclass ProductC_User : ICustomer\n{\n    //... implement ICustomer\n}\n\nclass MemberFactory \n{\n     ICustomer Create(ProductTypeEnum productType)\n     {\n         switch(productType)\n         {\n             case ProductTypeEnum.ProductA: return new ProductA_User();\n             case ProductTypeEnum.ProductB: return new ProductB_User();\n             case ProductTypeEnum.ProductC: return new ProductC_User();\n             default: return null;\n         }\n     }\n}	0
33451159	33451018	Calling a task-based asynchronous one way callback method from WCF service	public static class Extensions\n{\n    public static void FireAndForget(this Task task)\n    {\n        task.ContinueWith(t => \n        {\n            // log exceptions\n            t.Exception.Handle((ex) =>\n            {\n                Console.WriteLine(ex.Message);\n                return true;\n            });\n\n        }, TaskContinuationOptions.OnlyOnFaulted);\n    }\n}\n\npublic async Task FailingOperation()\n{\n    await Task.Delay(2000);\n\n    throw new Exception("Error");\n}   \n\nvoid Main()\n{\n    FailingOperation().FireAndForget();\n\n    Console.ReadLine();\n}	0
32527915	32511865	Finding a word on a dictionary in a string C# and the value of that word	var key = m.GetString(1);\nstring correction = null;\nif (corList.TryGetValue(key, out correction))\n{\n    conn.Send("say", string.format("Grammar Fixer: {0}, not {1}!", correction, key));\n}	0
4718594	4718576	How to get an array of types from an array of objects?	var types = args.Select(arg => arg.GetType()).ToArray();	0
4482822	4482761	How to test the program on a slow Internet connection?	WAN emulator	0
22374571	21431713	How to pass value in window.location?	window.location = '@Url.Action("ReceivedStatus", "Master", new { Id =  '@EncryptDecryptHelper.EncryptString(id)', SubTypeID = '@EncryptDecryptHelper.EncryptString(subTypeId)'})';	0
30402904	30402336	Compare Listbox item(s) with available exe files in (D:) drive of PC	string path = @"D:\Development\Latest\ConsoleApplication1\ConsoleApplication1\bin\Debug";\nstring files = Directory.GetDirectoryRoot(path);\n\nvar exeNotFoundList = new List<string>();\n\nfor (int i = 0; i < chkListBox.CheckedItems.Count; i++)\n{\n    var exeFilePathWithName = Path.Combine(path, chkListBox.Items[i].ToString() + ".exe");\n    if(!File.Exists(exeFilePathWithName))\n    {\n         exeNotFoundList.Add(exeFilePathWithName);\n         continue;\n    }\n    var process = new Process\n        {\n            StartInfo = new ProcessStartInfo\n               {\n                  FileName = exeFilePathWithName\n                }\n         };\n\n   process.StartInfo.UseShellExecute = false;// Beacuse I  am using Process class\n   process.StartInfo.CreateNoWindow = true;\n   process.Start();\n\n}\n\nif(exeNotFoundList.Count > 0)\n{\n    var errorMessage = String.Join(String.Empty, exeNotFoundList.ToArray());\n    MessageBox.Show(errorMessage);\n}	0
7091197	7091106	Get Values out of xml file	System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();\n xmlDoc.Load(filename);\n\n string sWarningValue = xmlDoc["Sensors"]["ID1"]["warning"].Value;	0
14123192	14123161	Why does my code that adds controls in a loop fail?	public MainPage()\n{\n    InitializeComponent();\n\n    for (int i = 0; i < 2; i++)\n    {\n        CheckBox c = new CheckBox();\n        c.Content = " Value " ;\n        lbox.Items.Add(c);\n    }\n}	0
20075620	20072329	AutoMapper: Build destination from two properties	Mapper.CreateMap<PersonEntry, Person>();\nMapper.CreateMap<PersonEntryWithBookmarks, Person>()\n    .AfterMap((src, dest) => Mapper.Map<PersonEntry, Person>(src.Entry, dest));\n\nvar person = Mapper.Map<PersonEntryWithBookmarks, Person>(personEntryWithBookmarks);	0
4116319	4116311	Windows Phone 7 Hiding the Application Bar	ApplicationBar.IsVisible = true/false;	0
28449062	28447611	Skip an extra line after particular row	PdfPTable third_table = new PdfPTable(3);\nthird_table.TotalWidth = 560f;\nthird_table.LockedWidth = true;\nthird_table.SetWidths(new float[] { 2.4f,0.1f, 6.6f });\n\nthird_table.AddCell(new PdfPCell(new Phrase("Responsibilities Held ", other)) { BorderWidth = 0 });\nthird_table.AddCell(new PdfPCell(new Phrase(": ", other)) { BorderWidth = 0 });\nthird_table.AddCell(new PdfPCell(new Phrase( Responsibilities_held, other)) { BorderWidth = 0 });\n\nPdfPCell cell = new PdfPCell();\ncell.Colspan = 3;\ncell.FixedHeight = 30.0f;\nthird_table.AddCell(cell);\n\nthird_table.AddCell(new PdfPCell(new Phrase("Description of Work Done", other)) { BorderWidth = 0 });\nthird_table.AddCell(new PdfPCell(new Phrase(": ", other)) { BorderWidth = 0 });\nthird_table.AddCell(new PdfPCell(new Phrase( Description_of_work_done, other)) { BorderWidth = 0 });	0
17963488	17963437	Select distinct items with a specific field in an array	ICS.Select(t=>t.Category).Distinct()	0
9111139	9111006	Outlook.MailItem - Is there any way to determine if two mailitems (sent to different recipients) are the same?	var mailHash = String.Format("{0}{1}{2}{3}{4}", mail.To, mail.From, mail.CC, mail.Subject, mail.Body).GetHashCode();	0
12949727	12949333	Message box from another thread	xmlServiceHost = XcelsiusServiceHost.CreateXmlServiceHost("http://localhost:123/naanaa");//Properties.Settings.Default.XmlDataService);\n\nserviceThread = new Thread(_ =>\n{\n  try { xmlServiceHost.Open(); }\n  catch (AddressAccessDeniedException)\n  {\n    CreateRegisterDashboardServiceFile();\n    System.Windows.MessageBox.Show("The dashboard service needs to be registered. Please contact support.");\n  }\n});\n\nserviceThread.Start();	0
5529493	5529439	insert statement wont work	using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + theUserId + ", '" + TextBox1.Text + "', " + friendid  + ")", cn))	0
23462173	23461635	Async socket server with multiple clients connected	private List<Socket> _clients = new List<Socket>();\n\npublic static void AcceptCallback(IAsyncResult ar) {\n    // Signal the main thread to continue.\n    allDone.Set();\n\n    // Get the socket that handles the client request.\n    Socket listener = (Socket) ar.AsyncState;\n    Socket handler = listener.EndAccept(ar);\n\n    // Create the state object.\n    StateObject state = new StateObject();\n    state.workSocket = handler;\n    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,\n        new AsyncCallback(ReadCallback), state);\n\n    _clients.Add(handler); // Maintain connected clients\n}\n\npublic void BroadcastMessage(string message)\n{\n    // Send the message to all clients\n    var bytes = Encoding.ASCII.GetBytes(message);\n    foreach(var c in _clients)\n    {\n        c.BeginSend(bytes, 0, bytes.Length, SocketFlags.Broadcast, OnMessageBroadcast, c);\n    }\n}\n\nprivate void OnMessageBroadcast(IAsyncResult res)\n{\n    Socket client = (Socket)res.AsyncState;\n    client.EndSend(res);\n}	0
15906547	15906424	How to inherit from a list of generic objects	public abstract class GetOptions<EnumT> : List<GetOption<EnumT>>	0
998428	939858	WPF searchbox and databinding to treeview	set\n{\n    if (value != null)\n    {\n        this.searchPhrase = value;\n        FirePropertyChanged<ProjectListPM>(o => o.SearchPhrase);\n        FirePropertyChanged<ProjectListPM>(0 => o.Items);\n    }\n}	0
29256431	29256336	Iterating through a list with a different type	foreach (IHideable hidable in viewable.OfType<IHideable>())\n    hidable.Hide();	0
31573456	31573192	Changing a value before calling another constructor	public class scan\n{\n    public scan(Environment value) { }\n    public scan() : this(Environment.Local) { }\n    public scan(string s) : this(ParseEnum(s)) { }\n\n    private static Environment ParseEnum(string s)\n    {\n        // default to local\n        Environment value = Environment.Local;\n\n        // try parsing the string\n        Enum.TryParse<Environment>(s, out value);\n\n        // if sucessful, the new value will be returned\n        // if not, Environment.Local will be returned\n        return value;\n    }\n    public enum Environment\n    {\n        Local,\n        NotLocal,\n        AnotherOne\n    }\n}	0
14947403	14947360	find out how many bytes have been written to a filestream	Stream.Write()	0
6297387	6297249	remove encoding from xmlserializer	XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");\nusing (XmlWriter writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { OmitXmlDeclaration = true}))\n{\n  new XmlSerializer(typeof (SomeType)).Serialize(writer, new SomeType(), ns);\n}	0
13281160	13281032	Retrieving more post from public fb page using FB graph api	facebookClient.Get("/pageName/posts?limit=100")	0
31394364	31394219	How to Download a PDF file from Azure in ASP.NET MVC via Save Dialog	var fileContent = new System.Net.WebClient().DownloadData(fullPath); //byte[]\n\nreturn File(fileContent, "application/pdf", "my_file.pdf");	0
4456387	4456301	How to check if Dotnet transaction is rolled back?	using(TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)){\n\n    try{\n        //Do something;\n\n        scope.Complete();  //denotes the transaction completed successful.\n    }\n    catch(TransactionAbortedException ex)\n    {\n\n        //scope.Complete(); is never called, the transaction rolls back automatically.\n    }\n    catch(ApplicationException ex)\n    {\n\n    }\n}	0
1746971	1746889	How to make a string length limited to a specific number?	[StringLengthValidator(1, 50, Ruleset = "RuleSetA", \n           MessageTemplate = "Last Name must be between 1 and 50 characters")]\npublic string LastName\n{\n    get { return lastName; }\n    set { lastName = value; }\n}\n\n[RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, \n               DateTimeUnit.Year, Ruleset="RuleSetA", \n               MessageTemplate="Must be 18 years or older.")]\npublic DateTime DateOfBirth\n{\n    get { return dateOfBirth; }\n    set { dateOfBirth = value; }\n}\n\n[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", \n             Ruleset = "RuleSetA")]\npublic string Email\n{\n    get { return email; }\n    set { email = value; }\n}	0
10086546	9757087	using mscomm32.ocx in crystalreports application	private void btnsend_Click(object sender, EventArgs e)\n    {\n        using (var sp = new SerialPort("COM4"))\n        {\n            sp.Open();\n            sp.WriteLine("AT" + Environment.NewLine);\n            sp.WriteLine("AT+CMGF=1" + Environment.NewLine);\n            sp.WriteLine("AT+CMGS=\"" + "phone no" + "\"" + Environment.NewLine);\n            sp.WriteLine("your text message" + (char)26);\n        }\n    }	0
19961006	19960763	Is there a typesafe enum conversion from int in c#?	Enum.TryParse(myInteger.ToString(), out result)	0
21487130	21487019	How to customize MVC url path	routes.MapRoute(\n    name: "Profile",\n    url: "alumcloud/{companyName}",\n    defaults: new { controller = "AlumCloudController", action = "Details" }\n);	0
834598	834527	How do I generate and send a .zip file to a user in C# ASP.NET?	Response.AppendHeader( "content-disposition", "attachment; filename=" + name );\nResponse.ContentType = "application/zip";\nResponse.WriteFile(pathToFile);	0
207203	207157	How do I access the XML data in my column using LINQ to XML?	// IEnumerable sequence with keywords data\nvar keywords = from kw in ga.ArticleKeywords.Elements("keyword")\n               select new {\n                   Name = (string)kw.Attribute("name"),\n                   Value = (string)kw.Attribute("value"),\n                   Display = (string)kw.Attribute("display")\n               };\n\n\nforeach (var keyword in keywords)\n{\n    var kw = "Name: " + keyword.Name + \n             " Value: " + keyword.Value + \n             " Display: " + keyword.Display;\n    Console.WriteLine(kw);\n}	0
13158900	13143353	How to programmatically create editable wiki pages within the Pages library of an Enterprise Wiki site	using (SPSite site = new SPSite(SPContext.Current.Web.Url))\n{\n    SPWeb rootWeb = site.RootWeb;\n    rootWeb.AllowUnsafeUpdates = true;\n    SPList wiki = rootWeb.Lists["Pages"];\n    String url = wiki.RootFolder.ServerRelativeUrl.ToString();\n    PublishingSite pubSite = new PublishingSite(rootWeb.Site);\n    string pageLayoutName = "EnterpriseWiki.aspx"; //Page Layout Name\n    string layoutURL = rootWeb.Url + "/_catalogs/masterpage/" + pageLayoutName;\n    PageLayout layout = pubSite.PageLayouts[layoutURL];\n    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(rootWeb);\n    PublishingPage newWikiPage;\n    string myWikiPage = "MyWikiPage.aspx"; //Page name\n    newWikiPage = publishingWeb.GetPublishingPages().Add(myWikiPage, layout);\n    newWikiPage.Title = "My Wiki Page";\n    newWikiPage.Update();\n    rootWeb.AllowUnsafeUpdates = false;\n}	0
5823258	5464822	Detect change in RadGrid item expand/collapse state	protected void RadGrid_OnItemCommand(object sender, GridCommandEventArgs e)\n{\n    try\n    {\n        if(e.CommandName.Equals("ExpandCollapse"))\n        {\n            string id = ((GridDataItem)e.Item).GetDataKeyValue("ID").ToString();\n            // ... do work on id (i.e. save state, etc.) ...\n        }\n    } catch(Exception ex)\n    {\n        // What could possibly go wrong? :)\n    }\n}	0
10707903	10705563	XNA: Storing lots of Texture2D in an array	for (int i = 1; i < 10; i++)\n{\n  _bCards[i-1] = Content.Load("Images/Common/Black/"+i);\n  _rCards[i-1] = Content.Load("Images/Common/Red/"+i);\n   if(i<6) _sCards[i-1] = Content.Load("Images/Special/Card" + (i-1));\n}	0
5435515	5435460	Console application: How to update the display without flicker?	Console.SetCursorPosition	0
19870673	19870310	Cut and Paste Columns in Excel Range with c#	using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing Excel = Microsoft.Office.Interop.Excel;\n\nnamespace ExcelCutAndInsertColumn\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Excel.Application xlApp = new Excel.Application();\n            Excel.Workbook xlWb = xlApp.Workbooks.Open(@"C:\stackoverflow.xlsx");\n            Excel.Worksheet xlWs = (Excel.Worksheet)xlWb.Sheets[1]; // Sheet1\n\n            xlApp.Visible = true;\n\n            // cut column B and insert into A, shifting columns right\n            Excel.Range copyRange = xlWs.Range["B:B"];\n            Excel.Range insertRange = xlWs.Range["A:A"];\n\n            insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, copyRange.Cut());\n        }\n    }\n}	0
34247213	34247094	Xamarin forms, I have a global int that I try to save in my app, but when I restart it, the int resets	if (Application.Current.Properties.ContainsKey("saveOurNumber"))\n{\n    App.theNumber = (int) Application.Current.Properties ["saveOurNumber"];\n}	0
7118030	7117997	Getting Session Value in Master Page - PageLoad	protected void Page_Load(object sender, EventArgs e)\n{\n\n    if (!IsPostBack)\n    {\n\n        ddlLanguage.SelectedValue = Session["Language"] == null ? "0" : Session["Language"].ToString();\n    }	0
17333366	17332985	Load a few records from database given an array of integers and keep the order as the array without loading all records to memory	var ids = Enumerable.Range(1, 100);\nvar subsetOfIds = ids.OrderByDescending(i => i).Take(15);\nvar dbresults = Albums.Where(a => subsetOfIds.Contains(a.AlbumId)).ToArray();\nvar results = subsetOfIds.Select(id => new { IdFromArray = id, record = dbresults.First(album => album.AlbumId == id) }).ToArray();	0
32079986	32079869	byte type used in a using statement must be implicitly convertible to System.IDisposable	class Class1\n{\n     public void UploadFile()\n     {\n          var v = class2.GetByteStream();\n\n          //rest of code here\n     }\n}\n\nclass Class2\n{\n     public byte[] GetByteStream()\n     {\n          using (MemoryStream ms = new MemoryStream())\n          {\n               //some code here\n               return ms.ToArray();\n          }\n     }     \n}	0
4301274	4301172	Strategy for Incomplete Dates	Year only: 1954 => 19540000\nYear & Month: April 2004 => 20040400\nJanuary 1st, 2011 => 20110101	0
33308274	33306007	C# Windows Form chart control grouping same value elements	chart1.Series[0]["PointWidth"] = "1";	0
13249110	13229468	Zooming into image in Windows Store apps	HorizontalScrollBarVisibility = "Auto"	0
11223560	11222891	Regex.Match double consonants in c#	Regex.IsMatch(f.WordStr, @"^\w*[^aoyieu]+[aoyieu]([^aoyieu])\1(ed|ing|ied)$")	0
26766100	26765979	How to format a string with a value from resources and one value from Binding in XAML?	xmlns:p="clr-namespace:MyApplication.Properties"\n\n   <TextBlock Height="30" >\n        <TextBlock.Text>\n            <MultiBinding  StringFormat="{}{0} -- {2} {1:C}!">\n                <Binding Path="Description"/>\n                <Binding Path="Price"/>\n\n                <Binding Path="{x:Static p:Resources.Nowonly}"/>\n                <!-- Or possibly Source instaed of Path as mentioned by @dkozl -->\n                <Binding Source="{x:Static p:Resources.Nowonly}"/>\n            </MultiBinding>\n        </TextBlock.Text>\n    </TextBlock>	0
14138392	14138375	Get Enum type from value	CreateNew((WeekDays)6);	0
19588802	19587964	Not counting null values from a linq LEFT OUTER JOIN query	var q = from a in odc.AVCs\n        select new AVCListItem\n        {\n            Id = a.Id,\n            Name = a.Name,\n            Address = a.Address,\n            Count = yellows.Where(o => o.AVCId == a.Id).Count()\n        };	0
4551901	4549097	Regarding some Update Stored procedure	IF NOT EXISTS (SELECT 1 from Table1 where TitleId = @TitleID and PageID <> @PageID) -- This makes sure that there is no 'other page' with same title (updated from UI)\n{\n    UPDATE Table1          \n    SET Content = @Content, TitleID = @TitleID          \n    WHERE PAGEID = @PAGEID     \n}	0
21316399	21316192	How to deserialize JSON objects to List<> when the items are not in a Json array? (C#)	public class Results {\n    public bool BoolValue { get; set; }\n    public Dictionary<string, Item> Inventory { get; set; }\n}\n\npublic class Item {\n    public string id { get; set; }\n    public string name { get; set; }\n}	0
11157231	11157178	How to dynamically add items to ListBox in Windows Phone 7/C#	listBox1.Items.Add("Your item");	0
757050	757036	Programmatically detach SQL Server database to copy mdf file	Declare @CustomerID int\ndeclare @FileName nvarchar(40)\ndeclare @ZipFileName nvarchar(40)\ndeclare @ZipComand nvarchar(255)\n\n\nset @CustomerID=20 --Get from database instead in real life application\nSET @FileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.bak'\nSET @ZipFileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.zip'\n\n--Backup database northwind\nbackup database northwind to DISK=@FileName\n\n--Zip the file, I got a commanddriven zip.exe from the net somewhere.\nset @ZipComand= 'zip.exe -r '+@ZipFileName+' '+@FileName\nEXEC xp_cmdshell @zipcomand,NO_output\n\n--Execute the batfile that ftp:s the file to the server\nexec xp_cmdshell 'c:\movetoftp.bat',no_output\n\n--Done!	0
28477209	28475418	Change the color of the selected row of a grid view in asp.net c#	protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n    if(read)\n    {\n         e.Row.BackColor = System.Drawing.Color.Red;\n    }\n    else\n    {\n        e.Row.BackColor = System.Drawing.Color.Blue;\n    }\n}	0
17750148	17749934	combobox with values from multiply tables mathematical operation	if(comboBox1.SelectedValue != null)\n{\n    int textboxValue = 0;\n    double comboxValue = 0;\n     if(double.TryParse(comboBox1.SelectedValue.ToString(),out comboxValue) && int.TryParse(text1.Text.Trim(),out textboxValue))\n\n      {\n        textbox2.Text = (comboxValue * textboxValue).ToString();\n      }	0
14294125	14293908	How can I write a file from a drag'n dropped text within my RichTextbox control to the windows explorer?	private void richTextBox1_MouseLeave(object sender, EventArgs e)\n{\n    // If the left mouse button is down when leaving the rtb\n    if (MouseButtons == MouseButtons.Left)\n    {\n        // Write everything to a temp file.\n        System.IO.File.WriteAllText(@"z:\Temp\helloWorld.rtf", richTextBox1.SelectedRtf);\n        string[] filenames = { @"z:\Temp\helloWorld.rtf" };\n        DataObject obj = new DataObject();\n        // Set the drag drop data with the FileDrop format\n        obj.SetData(DataFormats.FileDrop, filenames);\n        // Start the drag drop effect\n        DoDragDrop(obj, DragDropEffects.All);\n    }\n}	0
11609927	11606417	NHibernate - How to write a criteria query to reflect whether a column has a null value or not	session.QueryOver<Foo>()\n    .Select(Projections.SqlFunction("length", NHibernateUtil.Int32, Projections.Property<Foo>(foo => foo.Name)))\n    .List();\n\nsession.CreateCriteria<Foo>()\n    .SetProjection(Projections.SqlFunction("length", NHibernateUtil.Int32, Projections.Property(Name)))\n    .List<int>();	0
18763496	18757638	Date validation in asp.net with c#	DateTime startDate; \nDateTime endDate;\n\nif (DateTime.TryParse(txtstart.Text, out startDate) && DateTime.TryParse(txtend.Text, out endDate))\n{\n     string n1 = DropDownList2.SelectedItem.Text;\n\n     if (DropDownList1.SelectedItem.Text == "Membership")\n     {\n      SqlConnection con = new \nSqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());\n       con.Open();\n      SqlDataAdapter adapter = new SqlDataAdapter("select p.Name,m.* from Membership_det m INNER JOIN Personal_det p  ON m.FID= p.FID where m.updateDate  between @Start and @End and m.FID =" + n1 + "", con);\n      adapter.SelectCommand.Parameters.Add("@Start", SqlDbType.Date).Value = startDate;\n      adapter.SelectCommand.Parameters.Add("@End", SqlDbType.Date).Value = endDate;\n      DataTable dt = new DataTable();\n      adapter.Fill(dt);\n      con.Close();\n      GridView1.DataSource = dt;\n      GridView1.DataBind();                \n      }\n}\nelse\n{ \n     //Show error message\n}	0
5685358	5685344	Do I need to escape backslash in a config file?	string somePath = @"C:\blah\blih\bluh.txt";	0
10084123	10075246	MVVM and asynchronous data access	Dictionary<int, IObservable<IAsset>> inflightRequests;\n\npublic IObservable<IAsset> GetSomeAsset(int id)\n{\n    // People who ask for an inflight request just get the\n    // existing one\n    lock(inflightRequests) {\n        if inflightRequests.ContainsKey(id) {\n            return inflightRequests[id];\n        }\n    }\n\n    // Create a new IObservable and put in the dictionary\n    lock(inflightRequests) { inflightRequests[id] = ret; }\n\n    // Actually do the request and "play it" onto the Subject. \n    var ret = new AsyncSubject<IAsset>();\n    GetSomeAssetForReals(id, result => {\n        ret.OnNext(id);\n        ret.OnCompleted();\n\n        // We're not inflight anymore, remove the item\n        lock(inflightRequests) { inflightRequests.Remove(id); }\n    })\n\n    return ret;\n}	0
26576856	26576822	Get Smallest and Nearest Number to Zero - C#	double machineEpsilon = 1.0d;\n\n        do {\n           machineEpsilon=  machineEpsilon/ 2.0d;\n        }\n        while ((double)(1.0 + machineEpsilon) != 1.0);	0
11501428	11501290	Html Agility - Get Value by Name Tag	var input= doc.DocumentNode\n              .Descendants("input")\n              .First(n=>n.Attributes["name"].Value=="data[_Token][key]");	0
17531885	17531736	Finding Specific dates in Date range	static IEnumerable<DateTime> SundaysBetween(DateTime startDate, DateTime endDate)\n{\n    DateTime currentDate = startDate;\n\n    while(currentDate <= endDate)\n    {\n        if (currentDate.DayOfWeek == DayOfWeek.Sunday)\n            yield return currentDate;\n\n        currentDate = currentDate.AddDays(1);\n    }         \n}	0
3952038	3952032	C# Regex getting words that start with?	MatchCollection matches = Regex.Matches (inputText, @"^!\w+");\n\n foreach (Match  match in matches)\n {\n      Console.WriteLine (match.Value);\n }	0
10115428	10114841	How to create dynamic lambda based Linq expression from a string in C#?	var myLambda = x => x * x	0
5343825	5343786	LINQ - How to write a query to set a variable bool True or False	bool queryCheck = (from cnt in context.CmsContents\n                  where cnt.ContentId == myContentIdSelected && cnt.CmsSourcesContents.Any()\n                  select cnt).Any();	0
14953625	14953375	How can I make a pointer generic in C#?	public void MethodA(byte[] pPixels) {}\npublic void MethodA(int[] pPixels {}\n//etc...	0
20638198	20638107	convert from BitArray to 16-bit unsigned integer in c#	uint16 res = 0;\nfor (int i = 0 ; i != 16 ; i++) {\n    if (bits[i]) {\n        res |= (uint16)(1 << i);\n    }\n}	0
1980528	425235	How to properly and completely close/reset a TcpClient connection?	tcpClient.GetStream().Close();\ntcpClient.Close();	0
2344437	2344409	Setting the TabIndex value for a dynamically created textbox	System.Convert.ToInt16( value );	0
29083338	29082972	Joining byte arrays using a separator in C#	public static T[] Join<T>(T separator, IEnumerable<T[]> arrays)\n{\n    // Make sure we only iterate over arrays once\n    List<T[]> list = arrays.ToList();\n    if (list.Count == 0)\n    {\n        return new T[0];\n    }\n    int size = list.Sum(x => x.Length) + list.Count - 1;\n    T[] ret = new T[size];\n    int index = 0;\n    bool first = true;\n    foreach (T[] array in list)\n    {\n        if (!first)\n        {\n            ret[index++] = separator;\n        }\n        Array.Copy(array, 0, ret, index, array.Length);\n        index += array.Length;\n        first = false;\n    }\n    return ret;\n}	0
16948160	16948117	Deleting a row from a table seems to fail	Command.CommandText = "DELETE FROM Contacts WHERE [First Name] = @Name;";\nCommand.Parameters.AddWithValue("Name", DropDownList1.SelectedValue);	0
25893445	25893239	c# inheritance override method parameter with a descendant class	public abstract class BaseVehicle<T> where T : BaseShape\n{\n    public void SaveChanges(T shape)\n    {\n        if (!shape.Modified()) return;\n        var errorList = new List<string>();\n        shape.Validate(errorList);\n        if (errorList.Count > 0)\n        {\n            var sb = new StringBuilder();\n            foreach (string s in errorList)\n            {\n                sb.Append(s + Environment.NewLine);\n            }\n            throw new Exception(sb.ToString());\n        }\n\n        WriteToStorage(shape);\n\n        if (!shape.Active)\n            MarkInactive(ref shape);\n    }\n\n    public abstract void WriteToStorage(T shape);\n\n    public abstract void MarkInactive(ref T shape);\n}\n\npublic class DescendantVehicle : BaseVehicle<DescendantShape>\n{\n    public override void WriteToStorage(DescendantShape shape)\n    {\n        //\n    }\n\n    public override void MarkInactive(ref DescendantShape shape)\n    {\n        shape = null;\n    }\n}	0
3010671	2149483	Creating a Dib by only specifying the size with GDI+ and DotNet	var bmp = new Bitmap(width, height, stride, format, scan0)	0
4379340	4378865	Detect Arrow Key - KeyDown for the whole window	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (keyData == Keys.Left) {\n            Console.WriteLine("left");\n            return true;\n        }\n        // etc..\n        return base.ProcessCmdKey(ref msg, keyData);\n    }	0
22012311	22012056	Timer for Windows Phone 8	private DispatcherTimer dispatcherTimer;\n    // Constructor\n    public MainPage()\n    {\n\n        InitializeComponent();\n        dispatcherTimer = new System.Windows.Threading.DispatcherTimer();\n        dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);\n        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);\n        dispatcherTimer.Start();\n\n    }\n\n  private void dispatcherTimer_Tick(object sender, EventArgs e)\n  {\n    //do whatever you want to do here\n  }	0
589062	589048	Setting attributes in an XML document	foreach(XmlElement el in doc.SelectNodes(...)) {\n    el.SetAttribute(...);\n}	0
15226206	15222343	Resharper warning casting enum to UIntPtr, but no compiler warning	using System;\n\nclass A\n{\n    static void Main()\n    {\n        E? x = 0;\n        UIntPtr z = (UIntPtr)x;\n    }\n}\nenum E { }	0
25510593	25510521	How can I convert a long into a list of digits?	long l = ...;\n\nvar list = l.ToString().Select(c => int.Parse(c.ToString())).ToList();	0
34384055	34383922	How can I convert the following code to a Compiled Expression in C#?	private static Dictionary<Type, Func<IList>> funcs;\npublic static IList MakeList(Type listType)\n{\n    Func<IList> f;\n    // checks to ensure listType is a generic list omitted...\n    if(!funcs.TryGetValue(listType, out f)) {\n        // gets the generic argument e.g. string for a List<string>\n        var genericType = listType.GetGenericArguments()[0];\n\n        var ctor = typeof(List<>)\n                   .MakeGenericType(genericType)\n                   .GetConstructor(Type.EmptyTypes);\n        f = Expression.Lambda<Func<IList>>(\n            Expression.New(ctor, new Expression[]{})).Compile();\n        funcs[listType] = f;\n    }\n    return f();\n}	0
13786004	13785598	How to read all email addresses, phone numbers etc stored in a windows phone contact?	foreach (Microsoft.Phone.UserData.ContactEmailAddress ad in result.EmailAddresses)\n{\n    txtBlock.Text += ad.EmailAddress;\n}\nforeach (Microsoft.Phone.UserData.ContactPhoneNumber ph in result.PhoneNumbers)\n{\ntxtBlock.Text += ph.PhoneNumber;\n}	0
15197336	15197218	How to set the "TO" field dynamically in Vcalendar?	ctx.Response.Write("\nATTENDEE;CN=someone@email.com;RSVP=TRUE:mailto:someone@email.com");	0
20314610	20314089	Overriding Inherited Class' Constructor but still calling base afterwards	public class Sprite\n{\n    public Sprite(Texture2D texture, Vector2 position, Rectangle boundry)\n        : this(texture, position, boundry, 1, 1, 1)\n    {\n    }\n\n    public Sprite(Texture2D texture, Vector2 position, Rectangle boundry,\n                  int rows, int cols, double framesPerSecond)\n    {\n        Initialize(texture, position, boundry, rows, cols, framesPerSecond);\n    }\n\n    public Sprite(ContentManager content, Rectangle boundry)\n    {\n         //TODO: Load up texture with content and get position\n         Initialize(texture, position, boundry);\n    }\n\n    private void Initialize(Texture2D texture, Vector2 position, Rectangle boundry,\n                            int rows, int cols, double framesPerSecond)\n    {\n        //TODO: Set a bunch of properties here        \n    }\n\n    private void Initialize(Texture2D texture, Vector2 position, Rectangle boundry)\n    {\n        Initialize(texture, position, boundry, 2, 2, 14);\n    }\n}	0
11001328	11001219	Load Imagesource into Control	ContentControl cc = new ContentControl();\ncc.Content = image;	0
22568896	22568661	How to save the data in array before showing	var array = results.Select((r, index) => new { result = r, Index = index })\n                   .OrderByDescending(r => r.result)\n                   .Take(n)\n                   .ToArray();	0
14371722	14371649	New Window Opens In Background From MouseDoubleClick Event	editFileWindow.ShowDialog();	0
12082917	12082839	How to get only a text from a XML file?	XmlDocument doc = new XmlDocument();\ndoc.Load(@"C:\tt.xml");\nstring xmlString = doc.InnerText;	0
29835736	29835621	Hash and Salt string in Windows Store App	var buffer = CryptographicBuffer.GenerateRandom(saltlength);\nvar string = CryptographicBuffer.EncodeToBase64String(buffer)	0
10149741	10133400	Overriding Methods with no Implementation	public override void Initialize()\n{\n   // no implementation\n}	0
29212134	29211475	How to add data using linq to entities in relational table?	rDatabaseEntities context = new rDatabaseEntities();\n    Delivery del = new Delivery();\n    del.TruckNo = trucknotxt.Text;\n    del.LR_No = Convert.ToInt32(lrnotxt.Text);\n    Transporter transporter = (from t in context.Transporters where t.transporterName == transcombo.SelectedItem select t).FirstOrDefault();\n    if(transporter != null)\n    {\n        del.Transporter = transporter;\n    }\n    context.Deliveries.AddObject(del);	0
11993712	11993530	How to detect unresponsive UI updates?	Queue1 = new BlockingCollection<MyItemType>(MaxItems)	0
25883404	25883385	C# RegEx, first match	(?<=someThing\()({[^{}}]*})	0
4846062	4845406	Reading a SQLite3 database from a simple Mono/C# application?	public static void Main(string[] args) {\n   string connectionString = "URI=file:f-spot.photos.db,version=3"; //<-- version is set to 3\n   IDbConnection dbcon;\n   dbcon = (IDbConnection) new SqliteConnection(connectionString);\n   dbcon.Open();\n   dbcon.Close();\n   dbcon = null;\n}	0
12523487	12523445	How to identify the User running the application	string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;	0
24150455	24147758	Limit objects in a collection from being serialized based on User	A a = null;\n\nif(User.IsInRole("Role")){\n   a = db.A.Find(Id);\n} else {\n   a = (from a in db.A\n        join b in db.B on a.ID equals b.ID\n        join c in db.C on b.ID equals c.ID\n        join d in db.D on b.ID equals d.ID\n        where a.ID == id && b.Published && c.Published && d.Published\n        select a);\n}\n\nif(a == null)\n   return NotFound();\n\nreturn Ok(a);	0
31987517	31987290	set SelectedItem in a Combobox filled with Objects - Entity Framework	foreach (var item in cboRubroPadre.Items)\n    if (((Rubro)item).Nombre == value.Nombre)\n    {\n        cboRubroPadre.SelectedItem = item;\n        break;\n    }	0
20489972	20489743	Merge two datatable in to one datatable and remove duplicate as per single column	var fileNames = t1.Rows.OfType<DataRow>().Select(row => row["FileName"]).ToList();\nvar rowsToAdd = t2.Rows.OfType<DataRow>().Where(row => !fileNames.Contains(row["FileName"])).ToList();\n\nforeach (var dataRow in rowsToAdd)\n{\n    t1.ImportRow(dataRow);\n}	0
13055662	13054245	Reference another sheet in Formula string SpreadSheetGear	MySheet.Cells[add ranges here].Range.ToString();	0
2022684	2022660	How to get the size of a Winforms Form titlebar height?	Rectangle screenRectangle=RectangleToScreen(this.ClientRectangle);\n\nint titleHeight = screenRectangle.Top - this.Top;	0
8444721	8414973	add images after the last image/text in a word document using interop C#	aDoc.Application.ActiveDocument.Shapes.get_Item("Rectangle 6").Select(); //finds the 1st image\n            aDoc.Application.Selection.MoveDown(WdUnits.wdScreen, 2);// adds tow pagedown presses\n            aDoc.Application.Selection.InlineShapes.AddPicture(@"C:\fullImagePath\Image.JPG");//adds image on new page\n            aDoc.Application.Selection.InsertBreak(WdBreakType.wdPageBreak);//adds a page break\n            aDoc.Application.Selection.InlineShapes.AddPicture(@"C:\fullImagePath\Image.gif");//adds image on new page	0
27061261	27060900	Using TimeSpan format for Azure Database using Entity Framework	newShutdownTime = TimeSpan(12, 20,10);	0
15995814	15991276	How to reverse axis in stacked bar?	_p.YAxis.Scale.IsReverse = true;	0
19944728	19944617	Changing values of all decimal fields of a class	var rec = new MyClass();\nvar fields = rec.GetType()\n.GetFields()\n.Where(value => value.GetValue(rec) is decimal)\n.ToList();\n\nforeach(var field in fields) {\n     field.setValue(rec, 1.234) \n}	0
33554921	33553941	How to resize BitmapImage using Writeable Bitmap Extension	using(MemoryStream strmImg = new MemoryStream(profileImage.Image))\n{\n    BitmapImage myBitmapImage = new BitmapImage();               \n    myBitmapImage.BeginInit();\n    myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n    myBitmapImage.StreamSource = strmImg;\n    myBitmapImage.DecodePixelWidth = 200;\n    myBitmapImage.DecodePixelHeight= 250;\n    myBitmapImage.EndInit();\n    EmployeeProfileImage = myBitmapImage;\n}	0
13115624	13115555	How to calculate the percentage between two DateTimes	var start = DateTime.Now;\nvar end = DateTime.Now.AddMinutes(1);\nvar total = (end - start).TotalSeconds;\n\nfor( int i = 0; i < 10; i++)\n{\nThread.Sleep(6000);\n\nvar percentage = (DateTime.Now - start).TotalSeconds*100/total;\nConsole.WriteLine(percentage);\n}	0
21155259	21154236	Cookie encryption oddness	cookie[System.Web.HttpUtility.UrlEncode(encryptedName)] = System.Web.HttpUtility.UrlEncode(encryptedData);	0
14921149	14920649	EF5 Many to Many join table fluent API	HasMany(t => t.NavigationProperty1)\n.WithMany(a => a.ReverseNavigationProperty)\n.Map(c => c.ToTable("TheJoinTable"));\n\n\n\n// rename keys as required, may not be required...\nc.MapLeftKey("ColumnKeyName");\nc.MapRightKey("ABetterName2");	0
6813060	6813021	How to compare two System.Drawing.Icon items	StringBuilder sb = new StringBuilder();\nfor (int i = 0; i < result.Length; i++)\n{\n    sb.Append(result[i].ToString("X2"));\n}	0
16330507	16330388	Display Value in textbox in Window application	// ... in Form1 ...\nForm2 f2 = new Form2();\nf2.ShowDialog(); // code stops here until "f2" is closed\ntextbox1.text = marketclass.nAlgoproperty;	0
539219	539132	How do you include a cursor (caret) in a custom control?	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\npublic class MyWidget : Control {\n  public MyWidget() {\n    this.BackColor = Color.Yellow;\n  }\n  protected override void OnGotFocus(EventArgs e) {\n    CreateCaret(this.Handle, IntPtr.Zero, 2, this.Height - 2);\n    SetCaretPos(2, 1);\n    ShowCaret(this.Handle);\n    base.OnGotFocus(e);\n  }\n  protected override void OnLostFocus(EventArgs e) {\n    DestroyCaret();\n    base.OnLostFocus(e);\n  }\n  [DllImport("user32.dll", SetLastError = true)]\n  private static extern bool CreateCaret(IntPtr hWnd, IntPtr hBmp, int w, int h);\n  [DllImport("user32.dll", SetLastError = true)]\n  private static extern bool SetCaretPos(int x, int y);\n  [DllImport("user32.dll", SetLastError = true)]\n  private static extern bool ShowCaret(IntPtr hWnd);\n  [DllImport("user32.dll", SetLastError = true)]\n  private static extern bool DestroyCaret();\n}	0
12644909	12644882	Do I need to redrop a custom component after changes?	mySuperControl1 = new MySuperControl();	0
29305632	29305599	How do I append to Text in textbox	private void btnclick_Click(object sender, RoutedEventArgs e)\n        {\n            if (cb1.IsArrangeValid == true)\n                if (cb2.IsArrangeValid == true)\n                    txt1.Text = (txt1.Text + "\n" + "Car:" + cb1.Text + "\n" + "state:" + cb2.Text).Trim();\n\n        }	0
12750375	12727962	Creating custom http header for test -	protected void Page_Load(object sender, EventArgs e)\n\n        {\n\n\n            string path = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + "/";\n\n            myRedirect(path + "TestRedirectTo.aspx", "test", "testValue");\n\n        }\n\n        protected void myRedirect(string url, string headerName, string headerValue)\n\n        {\n\n            Response.Clear();\n\n            System.Net.WebRequest request = System.Net.WebRequest.Create(url);\n\n            request.Headers.Add(headerName, headerValue);\n\n            System.Net.WebResponse response = request.GetResponse();\n\n            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);\n\n\n            string content = sr.ReadToEnd();\n\n            sr.Close();\n\n            Response.Write(content);\n\n            sr.Close();\n\n            Response.End();\n\n        }	0
16963750	16963592	Sort XmlElement by Attribute value	var xDoc = XDocument.Load(fname);\nvar applicants = xDoc.Descendants("Applicants")\n                     .OrderBy(a=>(int)a.Element("PersonID"))\n                     .ToList();\napplicants.ForEach(a=>a.Remove());\nxDoc.Root.Element("Application").Add(applicants);\nxDoc.Save(fname);	0
34453900	34453796	How Do I Get the Starting Location of the Client Area in a Form, Relative to the Form's Top-Left Corner?	// -8, -30 at my workstation\n // so 30 is a size of caption and top border\n //     8 is a left border size\n Point leftTopShift = PointToClient(this.Location);	0
4895174	4895074	Question on usage of XML with XPath vs XML as Class	XmlSerializer ser = new XmlSerializer(typeof(MyClass));\nFileStream fstm = new FileStream(@"C:\mysample.xml", FileMode.Open, FileAccess.Read);\n\nMyClass result = ser.Deserialize(fstm) as MyClass;\n\nif(result != null)\n{\n  // do whatever you want with your new class instance!\n}	0
1926754	1926704	More efficient Linq-to-SQL query	Article af1 = (from p in db.Pages\n               join pa in db.PageArticles on p.pageID equals pa.page_art_pageID\n               join a in db.Articles on pa.page_art_articleID equals a.articleID\n               where p.pageID == featurearticles.fk_pageID_item1\n               && pa.page_art_isCurrent == true\n               select a).FirstOrDefault();	0
25645210	25644786	Sitecore - Custom field, add unique value on create	Guid.NewGuid()	0
5485328	5485310	How to convert any string to valid CSV field?	csvCell = "\"" + cell.Replace("\"", "\"\"") + "\"";	0
13689682	13689102	Is there any simple program to generate a class for JSON data binding for Windows 8 app?	public async Task<string>getData()\n       {\n          HttpClient client=new HttpClient();\n    String URL="your string";//url for the JSON response\n    HttpResponseMessage response=await client.GetAsync(URL);\n    Return await response.Content.ReadAsStringAsync();\n    }\n\n   private void async Button1_click ()\n   {\n      string responseText= await getData();\nDataContractJsonSerializer= new DataContractJsonSerializer(typeOf(RootObject));//DataContractJsonSerializer is the class object that u will generate \nRootObject root;\nUsing(MemoryStream stream=new MemoryStream(Encoding.Unicode.GetBytes(responseText)))\n{\n    //access properties here\n}\n}	0
29514558	29513823	paste richtextformat in word without using of the clipboard or creating new word file	Selection.InsertFile([pathtoyourtemprtf], Link:=False)	0
25682783	25667370	Getting 'Compile error in hidden module: SmartTagsMod' while opening a word document in MS Word 2010	wordApplication.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;	0
34264243	34264203	Move item from one listBox to another listBox	private void Button1_Click(object sender, EventArgs e)\n\n    {\n        if (listBox1.SelectedItem != null)\n        {\n            while (listBox1.SelectedItems.Count > 0)\n            {\n                listBox2.Items.Add(listBox1.SelectedItem);\n                listBox1.Items.Remove(listBox1.SelectedItem);\n            }\n        }\n        else\n        {\n            MessageBox.Show("No item selected");\n        }\n    }	0
26320022	26319750	How to prevent going back after the user pressed the GoBack hardware button?	protected override void OnBackKeyPress(CancelEventArgs e)\n{\n    if(MessageBox.Show("Are you sure you want to exit?","Exit?", \n                            MessageBoxButton.OKCancel) != MessageBoxResult.OK)\n    {\n        e.Cancel = true; \n\n    }\n}	0
2132163	2132130	How to get Keypress event in Windows Panel control in C#	public void MyKeyPressEventHandler(Object sender, KeyPressEventArgs e)\n{\n    ... do something when key is pressed.\n}\n\n...\n\n(MyPanel as Control).KeyPress += new KeyPressEventHandler(MyKeyPressEventHandler);	0
14329203	14329162	Timing of static variable declaration	static X()\n{\n   v.Set(1, 1);\n}	0
3921961	3921938	how to select instance from a list in c#	int count = x.list.Count(v => v.Value == 5);	0
3582233	3582217	Add the current time to a DateTime?	string s = "27.08.2010";\n DateTime dt = DateTime.ParseExact(s, "dd.MM.yyyy", CultureInfo.InvariantCulture);\n DateTime result = dt.Add(DateTime.Now.TimeOfDay);	0
2504659	2503316	How do I get a value of a reference type in an Expression?	LambdaExpression lambda = Expression.Lambda(methodCall.Arguments[0]);\nvar compiledExpression = lambda.Compile();\nreturn compiledExpression.DynamicInvoke();	0
27246226	27246163	c# - using % as a text symbol(percent)	WHERE MyCol LIKE '%75[%]%'	0
17316534	17316228	Communication between two pages to allow a popup to select Customer ID	function pick(data) {\n  if (window.opener && !window.opener.closed)\n    window.opener.document.anyForm.anyInput.value = data;\n  window.close();\n}	0
31466880	31466839	C# string replace "," with a linebreak (Enter)	yourString = yourString.Replace(",", System.Environment.NewLine);	0
7427789	7427726	Calculated field in a Dextop C# model	[DextopFormField(anchor="0", readOnly=true, labelAlign = "top")] \n[DextopGridColumn(flex=1)]    \npublic String FullName { get { return String.Format("{0} {1}", FirstName, LastName); } }	0
1287159	1287010	How to use same interface two times with diferrent template parameters, in an interface?	public interface IBase<TM, TPkey> \n    where TM : bType\n    where TPkey : new ()        \n{\n    TM Get(TPkey key);\n}\n\npublic interface IABase<TPK> : IBase<ConcreteTmA, TPK> {}\npublic interface IBBase<TPK> : IBase<ConcreteTmB, TPK> {}\n\npublic class Root <TPK> :\n    IABase<TPK>,\n    IBBase<TPK> \n    where TM : MType \n    where TPM : PMType \n    where TPK : new()\n{\n    ConcreteTmA IABase.Get(TPK key)\n    {\n    }\n\n    ConcreteTmB IBBase.Get(TPK key)\n    {\n    }\n}	0
336797	336781	How to read a Chinese text file from C#?	using (StreamReader sr = new StreamReader(path, appropriateEncoding))\n{\n    string line;\n    while ( (line = sr.ReadLine()) != null)\n    {\n        // ...\n    }\n}	0
2472561	2471863	How can I drop a SqlServer Backup Device using SMO in C#?	Server server = new Server("localhost");\nBackupDevice device = server.BackupDevices["devicename"];\ndevice.Drop();	0
13360286	13360143	Linq To XML - Using XDocument and creating list of objects	XElement doc=XElement.Load(filename);\nList<Result> lstSurvey=doc.DescendantsAndSelf("Survey").Select(x=>\nnew Result\n{\n    uuid=x.Element("Survey").Attribute("uuid").Value,\n    username=x.Element("user").Attribute("name").Value,\n    dob=x.Element("user").Attribute("dob").Value,\n    answer1=x.Elements("answer").First().Value,\n    answer2=x.Elements("answer").Skip(1).First().Value\n}\n).ToList<Result>();	0
6097836	5712877	infopath cascaded dropdown displaying lookup field values in 1;#ABC format. Need to format the value as ABC without id	private void formatValue(string dataSourceName, string xPathSTring)\n    {\n        FileQueryConnection con = (FileQueryConnection)DataConnections[dataSourceName];\n        con.Execute();\n        DataSource ds = this.DataSources[dataSourceName];\n        XPathNavigator nav = ds.CreateNavigator();\n        XPathNavigator root = MainDataSource.CreateNavigator();\n        XPathNodeIterator iterator = nav.Select(xPathSTring, NamespaceManager);\n        while (iterator.MoveNext())\n        {\n\n            string value = iterator.Current.Value;\n            int startFrom = value.IndexOf('#') + 1;\n            iterator.Current.SetValue(value.Substring(startFrom, (value.Length - startFrom)));\n        }\n    }	0
25911974	25911893	Looping over files of folder and add as attachment	// Get all the files in the sourceDir\nstring[] filePaths = Directory.GetFiles(@"sourceDir");\n\n// Get the files that their extension are either pdf of xls. \nvar files = filePaths.Where(x=> Path.GetExtension(x).Contains(".pdf") ||\n                                Path.GetExtension(x).Contains(".xls"));\n\n// Loop through the files enumeration and attach each file in the mail.\nforeach(var file in files)\n{\n    var attachment = new Attachment(file);\n    mail.Attachments.Add(attachment);\n}	0
3582133	3581905	Crystal report shows database login requirement?	private void ConfigureCrystalReports()\n{\n    rpt= new ReportDocument();\n    string reportPath = Server.MapPath("reportname.rpt");\n    rpt.Load(reportPath);\n    ConnectionInfo connectionInfo = new ConnectionInfo();\n    connectionInfo.DatabaseName = "Northwind";\n    connectionInfo.UserID = "sa";\n    connectionInfo.Password="pwd";\n    SetDBLogonForReport(connectionInfo,rpt);\n    CrystalReportViewer1.ReportSource = rpt;\n}	0
19462998	19462923	Removing duplicate items (string) from listBox	private void DisplayCustomerName()\n{\n    foreach (CSVEntry entry in CSVList)\n    {\n          ListItem item = new ListItem(entry.customerName);\n         if ( ! customerNameListBox.Items.Contains(item) )\n         {\n              customerNameListBox.Items.Add(item);\n         }\n    }\n}	0
10667216	10666846	How to verify Azure Load Balancer?	int instanceID = RoleEnvironment.CurrentRoleInstance.Id;	0
6087777	6087726	How to differ between a parameterless and a string-parameter mvc action method?	[HttpPost]\npublic ActionResult Test(string title, TestModel model)	0
4121835	4103504	Get reference to assembly from code generation tool	private static Assembly GetAssembly(Project project, string assemblyName)\n{\n    Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSP = \n        project.DTE as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;\n    ServiceProvider sp = new ServiceProvider(oleSP);\n\n    DynamicTypeService dts = \n        sp.GetService(typeof(DynamicTypeService)) as DynamicTypeService;\n\n    Microsoft.VisualStudio.Shell.Interop.IVsSolution sln = \n        sp.GetService(typeof(SVsSolution)) as IVsSolution;\n\n    Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hier = null;\n    sln.GetProjectOfUniqueName(project.UniqueName, out hier);\n\n    ITypeResolutionService rs = dts.GetTypeResolutionService(hier);\n    return rs.GetAssembly(new AssemblyName(assemblyName), true);\n}	0
17061334	16341204	how to optimize performance of longlistselector with images on windows phone?	BitmapImage bitmapImage = image.Source as BitmapImage;\nbitmapImage.UriSource = null;\nimage.Source = null;	0
8747945	8747910	C# SqlCeException - a parameter is missing	cmd.Parameters.Add(param);	0
8564199	8564146	Error Attempting to Call a WPF Form From Console App	using System.Windows;	0
32708905	32708788	Reading array elements from the same line (C#)	string readLine=Console.ReadLine());\nstring[] stringArray=readLine.split(' ');\nint[] intArray = new int[stringArray.Length];\nfor(int i = 0;i < stringArray.Length;i++)\n{\n// Note that this is assuming valid input\n// If you want to check then add a try/catch \n// and another index for the numbers if to continue adding the others\n    intArray[i] = int.parse(stringArray[i]);\n}	0
9422992	9422969	In C# how does one make a file load in its correct program?	System.Diagnostics.Process.Start("path to document")	0
7364166	7363978	Get a list of weeks for a year - with dates	var jan1 = new DateTime(DateTime.Today.Year , 1, 1);\n//beware different cultures, see other answers\nvar startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));\nvar weeks=\n    Enumerable\n        .Range(0,54)\n        .Select(i => new {\n            weekStart = startOfFirstWeek.AddDays(i * 7)\n        })\n        .TakeWhile(x => x.weekStart.Year <= jan1.Year)\n        .Select(x => new {\n            x.weekStart,\n            weekFinish=x.weekStart.AddDays(4)\n        })\n        .SkipWhile(x => x.weekFinish < jan1.AddDays(1) )\n        .Select((x,i) => new {\n            x.weekStart,\n            x.weekFinish,\n            weekNum=i+1\n        });	0
32961738	32961706	Using LINQ, how do I get rows M through M+N?	IQueryable<Score> table1 = ( from s in this._SD.Scores\n                             orderby s.score1 descending\n                             select s\n                             ).Skip(ScoresController._scoresPerPage * (N-1))\n                             ).Take(ScoresController._scoresPerPage);	0
3257349	3257177	How to convert data into DateTime object	using System.Globalization;\n\nDateTime.ParseExact("20100715", "yyyyMMdd", CultureInfo.InvariantCulture);	0
25536838	25392481	Word document orientation lost after using OpenXML SDK AddAlternativeFormatImportPart	var sourceList = documentPaths.Select(doc => new Source(new WmlDocument(doc), true)).ToList();\nDocumentBuilder.BuildDocument(sourceList, outputPath);	0
23354121	23353836	How Specify columns at list to show in DataSource GridView? C#	myDataGrid.Columns[0].Visible = false;	0
10698060	9826804	How do I localize strings in a custom control in WinForms?	[Category("Appearance"), DefaultValue("Description for the new page."), Description("The subtitle of the page."), Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\n[Localizable(true)]\npublic string Subtitle\n{\n    get { return subtitle; }\n    set\n    {\n        if (subtitle != value)\n        {\n            Region regionToInvalidate = GetTextRegionToInvalidate();\n            subtitle = value;\n            regionToInvalidate.Union(GetTextRegionToInvalidate());\n\n            Invalidate(regionToInvalidate);\n        }\n    }\n}	0
22182780	22182269	GroupBy on Multiple Properties Based on Parameters	public AddressGroupsViewModel GetSearchResults(bool address1, bool address2, bool city, bool state, bool country, bool postalcode)\n{\n   var result = from t in tableName\n   group t by new { \n      FieldA = (address1 ? "" : t.Address1),\n      FieldB = (address2 ? "" : t.Address2),\n      FieldC = (city ? "" : t.City),\n      FieldD = (state ? "" : t.State),\n      FieldE = (country ? "" : t.Country),\n      FieldF = (postalcode ? "" : t.PostalCode)\n   } into g\n   select g;\n   ......\n}	0
15225322	15225263	Getting items from a database between a specific number of values	var books = bookContext.Books.OrderBy(x => x.Id).Skip(pageNo*booksPerPage).Take(booksPerPage);	0
9888792	9887002	Handle POST request from XML HTTP in WCF	POST http://localhost/RestService/RestServiceImpl.svc/auth HTTP/2.0\nContent-Type: application/xml\nContent-Length: 47\n\n<RequestData xmlns="http://www.eysnap.com/mPlayer"xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><details>Ashu|29|7 Years|.NET</details></RequestData>	0
23822972	23822754	How To create a stored procedure for SQL Server from C# code?	command.CommandType = CommandType.StoredProcedure;	0
3468487	3468433	WPF Window Return Value	public class Window1 : Window\n{\n    ...\n\n    private void btnPromptFoo_Click(object sender, RoutedEventArgs e)\n    {\n        var w = new Window2();\n        if (w.ShowDialog() == true)\n        {\n            string foo = w.Foo;\n            ...\n        }\n    }\n}\n\npublic class Window2 : Window\n{\n    ...\n\n    public string Foo\n    {\n        get { return txtFoo.Text; }\n    }\n\n}	0
27213783	27213676	How to get the source Page in OnNavigatedTo method WP 8.1	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n    PageStackEntry lastEntry = Frame.BackStack.LastOrDefault();\n    Type lastPageType = lastEntry != null ? lastEntry.SourcePageType : null;\n}	0
33030894	33029716	unable to delete registry Folder in C#	try\n            {\n                new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();\n                hKey.DeleteSubKeyTree(strPath);\n                flag1 = true;\n            }\n            catch (Exception obj1) //when (?)\n            {\n            }\n            finally\n            {\n                System.Security.Permissions.RegistryPermission.RevertAssert();\n            }	0
11404297	11393007	Implementing lock / edit / unlock with wcf service	public static bool CheckActiveAddIfNew(TimeStep step)\n{\n    //Assumes synchronization logic\n    bool isActive;\n    if(!steps.TryGetValue(step, out isActive)\n    {\n       steps.Add(step, true);\n       isActive = true;\n    }\n    return isActive;\n}\n\npublic static bool ChangeFilter(TimeStep oldSetp, TimeStep newStep)\n{\n   //Synchronization code\n   bool ableToChange;\n   if(!CheckActiveAddIfNew(newStep))\n   {\n       steps[newStep] = true;\n       steps[oldStep] = false;\n       ableToChange = true;\n   }\n\n   return ableToChange;\n}	0
970858	970704	Best practice for adding controls at run-time	/* this code is part of the .NET Framework was decompiled by Reflector and is copyright Microsoft */\n    internal virtual Control ParentInternal\n    {\n        get\n        {\n            return this.parent;\n        }\n        set\n        {\n            if (this.parent != value)\n            {\n                if (value != null)\n                {\n                    value.Controls.Add(this);\n                }\n                else\n                {\n                    this.parent.Controls.Remove(this);\n                }\n            }\n        }\n    }	0
17009079	17008690	Change values row from mysql database instead of adding	var query = (from u in entities.users\n                         where u.user_id== UID\n                         select u).First();\n\n            query.Address = u.Address;\n            query.Company = u.Company;\n            query.Fax = u.Fax;\n            query.Mobile = u.Mobile;\n            query.Name = u.Name;\n            query.Telephone = u.Telephone;\nentites.SubmitChanges();	0
15289785	15289621	Find the greatest right number from the current number in the array algorithm	var output = new int[input.Length];\noutput[input.Length-1] = input[input.Length-1];\n\nfor(int i = input.Length - 2; i >= 0; i--)\n    output[i] = output[i+1] > input[i+1] ? output[i+1] : input[i+1];	0
10323747	10322755	Add Stored Procedure Parameter into sqlDataSource, msSQL	addStaffSql.InsertCommand = "insertNewMember";\naddStaffSql.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;\naddStaffSql.InsertParameters.Add("name", name);\naddStaffSql.InsertParameters.Add("age", age);\naddStaffSql.Insert();	0
22432585	22432564	Can I replace an if / else with two levels of ? :	var result = client.Action == "show" ? "s" : (answersCorrect ? "t" : "f");	0
9309688	9309583	Convert C# DateTime into MongoDB format	var bsonDocument = new BsonDocument();\nbsonDocument["date"] = DateTime.Now;	0
22444211	22444122	How to insert row into table or add value if row already exists	INSERT INTO mytable (col1, col2, col3) VALUES ('a','b','c')\n ON DUPLICATE KEY UPDATE col3 = col3 + 1;	0
11097904	11097478	Getting data from an unknow data model	System.Reflection	0
5370959	5370939	get first element from list in dictionary c#	if (myDictionary.ContainsKey("myKey"))\n   var myItem = myDictionary["myKey"].FirstOrDefault();	0
10411765	10246574	How to read Hashtable key and value in dropdownlist selected indexchanged event	protected void ddlModalityList_SelectedIndexChanged(object sender, EventArgs e)\n        {     \n             ListItem selectedPair = ddlModalityList.SelectedItem;\n        }	0
29342876	29342794	Format function in c#	String.Format(@"D:\my\POC\{0:yyyy}\{0:MM}\{0:dd}\File_{0:yyyy}_{0:MM}_{0:dd}_{0:hh}_{0:mm}_{0:ss}_{0:fff}.ss", DateTime.Now)	0
21373413	21368061	How to retrieve image description title in C#?	Image im = Image.FromFile("image file path");\n        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();            \n        var allPoprItem = im.PropertyItems;\n        const int metTitle = 0x10e;\n        var Title = allPoprItem.FirstOrDefault(x => x.Id == metTitle);\n        Console.WriteLine(encoding.GetString(Title.Value));	0
12249831	11093820	JavaScript error in WebView with Windows 8 Metro	Debug -> Options and Settings -> Debugging -> Just in time	0
25842576	25842473	How to show a counter in linkbutton c#	in Page_Load()	0
23720280	23713470	How to write a stream to a file in Windows Runtime?	public async Task SaveStreamToFile(Stream streamToSave, string fileName, CancellationToken cancelToken)\n{\n    StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);\n    using (Stream fileStram = await file.OpenStreamForWriteAsync())\n    {\n        const int BUFFER_SIZE = 1024;\n        byte[] buf = new byte[BUFFER_SIZE];\n\n        int bytesread = 0;\n        while ((bytesread = await streamToSave.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)\n        {\n            await fileStram.WriteAsync(buf, 0, bytesread);\n            cancelToken.ThrowIfCancellationRequested();\n        }\n    }\n}	0
32798903	32797051	[UWP][C#] App crashes when rotating device after adding option to change GridView Templates	FontIcon fi = new FontIcon();\nFontIcon fi2 = new FontIcon();\n\nfi.Glyph = "\uE80A";\nfi2.Glyph = "\uE80A";\n\nViewItems.Icon = fi;\nViewItemsBottom.Icon = fi2;	0
7378047	7378028	C# Split String Into Separate Variables	string x = dates[0];\nstring y = dates[1];	0
28113612	28113038	How can I deserialize a JSON array into a native .net data structure?	string json = File.ReadAllText("input.txt");\nJavaScriptSerializer jsDes = new JavaScriptSerializer();\nDictionary<string, object> objResp = (Dictionary<string, object>)jsDes.DeserializeObject(json);\nObject[] records =(Object[])objResp["records"];\nDictionary<string,object> results= (Dictionary<string,object>) records[0];\nConsole.WriteLine(result["urgency"]);	0
7753606	7753583	see connectionstring in text format	app.config	0
22866541	22863312	make a structure for generating custom form	class FormInputControl\n{\n     public string Description { get; set; } //Every form input has a description like User, link, what you want that form input control instance to describe\n     public abstract object Value { get; set; }\n}\n\nclass InputBox : FormInputControl\n{\n     public string Text { get; set; }\n     public overwrite object Value\n     {\n         get { return Text; }\n         set { Text = value as string; }\n     }\n}\n\n\nclass Form\n{\n     public IList<FormInputControls> { get; set; }\n}	0
34548107	34547775	Add params array of string to Datagridview	public static void AddNewRow(this DataGridView datagridview, params string[] parameters)\n{\n    datagridview.Rows.Add(new[] { " ", " ", "A" }.Concat(parameters).ToArray());\n}	0
8631959	8631955	Two decimal places lost with subtraction	total_gallons_used = (totalMiles / 46M);	0
6264097	6264006	Find third Sunday of each month occur between given two dates	public List<DateTime> ThirdSundayOfEachMonth( DateTime startdate, DateTime enddate )\n{\n  List<DateTime> result = new List<DateTime>();\n  int sundaymonthcount = 0;\n  for( DateTime traverser = new DateTime(startdate.Year, startdate.Month, 1); traverser <= enddate; traverser = traverser.AddDays(1) ){\n    if( traverser.DayOfWeek == DayOfWeek.Sunday ) sundaymonthcount++;\n    if( sundaymonthcount == 3 && traverser > startdate ){\n      result.Add(traverser);\n      sundaymonthcount = 0;\n      traverser = new DateTime( traverser.Year, traverser.Month, 1 ).AddMonths(1);\n    }\n  }\nreturn result;\n}	0
16521170	16518719	c# flowlayout overlapping of listbox and button	class MyPanel : FlowLayoutPanel\n{\n     public MyPanel()\n\n     {\n        this.BackColor = Color.Red;\n        this.FlowDirection = System.Windows.Forms.FlowDirection.LeftToRight;\n\n        listBox = new ListBox();\n\n        this.WrapContents = false;  // Use this for control not wrapped\n        editButton = new Button();\n\n\n        this.Controls.Add(listBox);\n        this.Controls.Add(editButton);\n     }\n }	0
5897334	5897269	how to pass session variable in href	href="../Profile/Home.aspx?uid=<%= Session["AccountId"] %>"	0
32144353	32143489	Getting values from Oracle DB table into listbox in c# /wpf	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        using (OracleConnection conn = new OracleConnection(ConnectionString))\n        {\n            OracleCommand cmdd = new OracleCommand("select * from employees", conn);\n\n            conn.Open();\n            cmdd.ExecuteNonQuery();\n\n            OracleDataReader dr = cmdd.ExecuteReader();\n\n            OracleDataAdapter da = new OracleDataAdapter(cmdd);\n            DataTable dt = new DataTable();\n            da.Fill(dt);\n\n            listboxReport.ItemsSource = dt.AsDataView();\n            listboxReport.DisplayMemberPath = dt.Columns[1].ToString();\n        }\n    }	0
7735771	7735259	How do I retrieve the binary contents of a longblob column and save as a file?	context.Response.ContentType = ReturnExtension(Extension);\ncontext.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);\n\nbyte[] buffer = (byte[])DB.GetReposFile(id).Rows[0]["FileContent"];\ncontext.Response.OutputStream.Write(buffer, 0, buffer.Length);	0
34432511	34432465	How to check if a textbox has no value	double nInterval;\nif (Double.TryParse(smartTextBox5.Value, out nInterval)\n{\n    if (nInterval > 1)\n    {\n     //do something\n\n    }\n    else \n    {\n     //do something else\n    }\n}	0
27843363	27843181	How to change data type of a column in DataTable	// Create a temporary table\nDataTable dtNew = new DataTable();\nfor(int i=0;dt.Columns.Count;i++)\n{\n    dtNew.Columns.Add(dt.Columns[i].ColumnName,typeof(string));\n}\n\n\n// Add data to new table\nfor(int i=0;dt.Rows.Count;i++)\n{\n   dtNew.Rows.Add();\n   for(int j=0;dt.Columns.Count;j++)\n   {\n      dtNew.Rows[i][j] = dt.Rows[i][j];\n   }        \n}\n\ndt=null;\ndt=dtNew.Copy();	0
7862867	7862825	Not sure how to test a line of code in C#	[TestMethod]\n[ExpectedException(typeof(FormatException))]\npublic void ParseTerm_when_the_last_char_is_not_a_close_parenthesis_should_throw_FormatException()\n{\n    //Call the method here:\n    ParseTerm("(some string without close parenthesis");\n}	0
28943295	28941908	Why ILGenerator inserts Leave instruction into Foreach statement	public virtual void BeginFinallyBlock() \n{\n    if (m_currExcStackCount==0) { \n        throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));\n    }\n    __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];\n    int         state = current.GetCurrentState(); \n    Label       endLabel = current.GetEndLabel();\n    int         catchEndAddr = 0; \n    if (state != __ExceptionInfo.State_Try) \n    {\n        // generate leave for any preceeding catch clause \n        this.Emit(OpCodes.Leave, endLabel);\n        catchEndAddr = m_length;\n    }\n\n    MarkLabel(endLabel);\n\n\n    Label finallyEndLabel = this.DefineLabel();\n    current.SetFinallyEndLabel(finallyEndLabel); \n\n    // generate leave for try clause\n    this.Emit(OpCodes.Leave, finallyEndLabel); HERE'S THE ANSWER\n    if (catchEndAddr == 0) \n        catchEndAddr = m_length;\n    current.MarkFinallyAddr(m_length, catchEndAddr); \n}	0
6918583	6918365	FileUploadControl with no file system access	Stream myStream = MyFileUpload.FileContent;\n\nIExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(myStream);\nDataSet result = excelReader.AsDataSet();\n\nstring r1c1Val = result.Tables[0].Rows[0][0].ToString();	0
13087537	11632409	How to Isolate (detour) constructor of class with Microsoft Fakes Shim?	ShimStreamReader.ConstructorString = (@this, value) =>\n{\n    ConstructorInfo constructor = typeof (StreamReader).GetConstructor(new[] {typeof (Stream)});\n    constructor.Invoke(@this, new object[] {new MemoryStream(Encoding.Default.GetBytes("33\r\n1\r\n16\r\n5\r\n7"))});\n};	0
12213123	12213089	variable object in c#	if(test.component is unit)\n  ((unit)test.component).Draw();	0
18828902	17403300	How do I get the text from sticky notes using iTextSharp?	if (AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.TEXT))\n{\n     string Title = AnnotationDictionary.GetAsString(PdfName.T).ToString();\n     string Content = AnnotationDictionary.GetAsString(PdfName.CONTENTS).ToString();\n}	0
5643145	5643076	How can I get a reference to a property's setter?	public static Action<object, object> CreateSetter(FieldInfo field)\n    {\n        DynamicMethod dm = new DynamicMethod("DynamicSet", typeof(void),\n            new Type[] { typeof(object), typeof(object) }, field.DeclaringType, true);\n\n        ILGenerator generator = dm.GetILGenerator();\n\n        generator.Emit(OpCodes.Ldarg_0);\n        generator.Emit(OpCodes.Ldarg_1);\n        if (field.FieldType.IsValueType)\n            generator.Emit(OpCodes.Unbox_Any, field.FieldType);\n        generator.Emit(OpCodes.Stfld, field);\n        generator.Emit(OpCodes.Ret);\n\n        return (Action<object, object>)dm.CreateDelegate(typeof(Action<object, object>));\n    }	0
10788527	10788119	Enabling/Disabling Moveup/MoveDown buttons on a ListView	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        Application.Idle += Application_Idle;\n        this.FormClosed += delegate { Application.Idle -= Application_Idle; };\n    }\n\n    void Application_Idle(object sender, EventArgs e) {\n        bool focusOk = this.ActiveControl == SelectedLV;\n        bool selectOk = SelectedLV.SelectedIndices.Count == 1;\n        int index = selectOk ? SelectedLV.SelectedIndices[0] : -1;\n        MoveUpBtn.Enabled = focusOk && selectOk && index > 0;\n        MoveDownBtn.Enabled = focusOk && selectOk && index < SelectedLV.Items.Count-1;\n    }\n}	0
19286578	19286439	select properties of T if they match a column name in a datatable and ignore case	List<PropertyInfo> properties = typeof(T).GetProperties().Where(p => dt.Columns.Cast<DataColumn>().Any(c => c.ColumnName.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase))).ToList();	0
17264933	17264651	Build C# Application runtime and get the results	public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args)\n{\n    var asm = BuildAssembly(code);\n    object instance = null;\n    Type type;\n    if(isstatic)\n    {\n        type = asm.GetType(namespacename + "." + classname);\n    }\n    else\n    {\n        instance = asm.CreateInstance(namespacename + "." + classname);\n        type = instance.GetType();\n    }\n    return type.GetMethod(functionname).Invoke(instance, args);\n}	0
15348554	15348449	datagridview row cell value	MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;\nobj.MyProperty = newValue;	0
7167744	7167725	How do I manipulate a RichTextBox in C#?	rtext2.Text = "<code>" + rtext1.Text + "</code>";	0
15110089	15109573	Accessing the Checkbox inside Datagrid on Button click Asp.net	foreach( DataGridItem di in datagrid1.Items )\n    {\n        CheckBox chkBx = (CheckBox)di.FindControl("CheckBox1") ;\n        if( chkBx !=null && chkBx.Checked )\n        {\n            //isChecked\n        }\n    }	0
32739213	32738201	How to modify multiple rows in a text file?	var lin = File.ReadLines(Path.Combine(path,"installer.ini")).ToArray();\n       var license = lin.Select(line =>\n       {\n           line = Regex.Replace(line, @"license=.*", "license=yes");\n           //you can simply add here more regex replacements\n           //line = Regex.Replace(line, @"somethingElse=.*", "somethingElse=yes");\n\n           return Regex.Replace(line, @"lmgr_files=.*", "lmgr_files=true");\n       });\n\n       File.WriteAllLines(installerfilename, license);	0
32516801	32516385	Image is not updating in Image control windows phone 8	imb.ImageSource = new BitmapImage(new Uri(temp.image + "?" + DateTime.UtcNow.Ticks.ToString()));	0
19548135	19548043	Select All distinct values in a column using LINQ	var uniqueCategories =  repository.GetAllProducts()\n                                  .Select(p=>p.Category)\n                                  .Distinct();	0
6927285	6927159	Setting sql server usermapping programmatically using C#	static void CreateLogin\n    (string sqlLoginName,string sqlLoginPassword,string databaseName)\n{\nmyServer=GetServer()\nLogin newLogin = myServer.Logins[sqlLogin];\nif (newLogin != null)\n    newLogin.Drop();\nnewLogin = new Login(myServer, sqlLogin);\nnewLogin.PasswordPolicyEnforced = false;\nnewLogin.LoginType = LoginType.SqlLogin;\nnewLogin.Create(sqlLoginPassword);\n//Create DatabaseUser\nDatabaseMapping mapping = \n    new DatabaseMapping(newLogin.Name, MainDbName, newLogin.Name);\nDatabase currentDb = myServer.Databases[databaseName];\nUser dbUser = new User(currentDb, newLogin.Name);\ndbUser.Login = sqlLogin;\ndbUser.Create();\ndbUser.AddToRole("db_owner");\n}	0
10757825	10757715	Find certificate location on box/server	X509Store store = new X509Store("My");\nstore.Open(OpenFlags.ReadOnly);\n\nforeach (X509Certificate2 mCert in store.Certificates){\n    //TODO's\n}	0
13895681	13895596	Performance of setting DataRow values in a large DataTable	foreach (DataRow row in dt.Rows)\n{\n    for (int j = 0; j < 15; j++)\n    {\n        row[j] = 5;\n    }\n}	0
10235335	10235093	Socket doesn't close after application exits if a launched process is open	ProcessStartInfo.UseShellExecute = true;	0
6506278	6328298	predicate builder with two tables	predicate = predicate.Or(p => p.Contacts.Any(c => c.streetname.Contains(keyword))));	0
17558527	17558310	Calling a method with T where the type is contained in a string	MethodInfo method = this.GetType().GetMethod("method");\nMethodInfo generic = method.MakeGenericMethod(p.GetType());\ngeneric.Invoke(this, p);	0
5573291	5573174	Set viewstate variable at end of page lifecycle	protected override object SaveViewState()\n{\n    if (startAddr != "")\n    {\n        ViewState["startAddress"] = startAddr;\n    }\n    return base.SaveViewState();\n}	0
7891743	7891696	try-catch-finally order of execution	exception caused\ncaught\nanswer variable set\nexception thrown\nfinally block executed\nexception propogated up the stack	0
16878652	16878481	managing accessibility of interface implementation memebers	public interface IHandler\n{\n    void Handle();\n}\n\npublic class HandlerDirector\n{\n    IList<IHandler> Handlers = new List<IHandler>();\n\n    public void AddHandler(IHandler handler)\n    {\n        Handlers.Add(handler);\n    }\n\n    public void RunAllHandlers()\n    {\n        foreach (IHandler handler in Handlers)\n            handler.Handle();\n    }\n}	0
1247782	1242466	MySql Says Column can't be null for a column that is not null! [using named parameters]	INSERT INTO post (ID, content, post_url, blogID, title, addedOn, updatedDate, commentsFeedURL, active, viewCount, commentCount, languageID, authorName, postDate, posRating, negRating, adult)" +\n                            " VALUES(?ID, ?content, ?post_url, ?blogID, ?title, ?addedOn, ?updatedDate, ?commentsFeedURL, ?active, ?viewCount, ?commentCount, ?languageID, ?authorName, ?postDate, ?posRating, ?negRating, ?adult)	0
5766512	5766470	How to go about abstracting away different JSON library implementations	public static class Json\n{\n    public static string Serialize(object o)\n    {\n        // ...  \n    }\n\n    public static T Deserialize<T>(string s)\n    {\n        // ...\n    }\n}	0
4798049	4797508	How can FTPClient delete a directory?	FtpWebRequest reqFTP = FtpWebRequest.Create(uri);\n                // Credentials and login handling...\n\n                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;\n\n                string result = string.Empty;\n                FtpWebResponse response = reqFTP.GetResponse();\n                long size = response.ContentLength;\n                Stream datastream = response.GetResponseStream();\n                StreamReader sr = new StreamReader(datastream);\n                result = sr.ReadToEnd();\n                sr.Close();\n                datastream.Close();\n                response.Close();	0
2550659	2550435	read a file with both text and binary information in .Net	Stream.Read()	0
25543814	25543682	Cannot access non-static field in static context	namespace WebApplication1\n{\n    public partial class Team : System.Web.UI.Page\n    {\n        private readonly CommonFunctions _cf;\n\n        public string CurrentUser;\n\n        public Team() \n        {\n            _cf = new CommonFunctions();\n            CurrentUser = _cf.CurrentUser();\n        }\n\n        protected void Page_Load(object sender, EventArgs e)\n        {\n            if (!string.IsNullOrEmpty(CurrentUser))\n            {\n                // Do stuff here\n            }\n            else\n            {\n                // Do other stuff here\n            }\n        }\n    }\n}	0
27350071	27349956	Finding if single integer is in an array of integers	int[] NorthCliff = {15,14,13,12};\nint Currentroom = 15;  \nif(NorthCliff.Contains(Currentroom))\n{\n//do things \n}	0
2984676	2984643	Convert Text file to XML	File.Move(@"C:\File.txt", @"C:\File.xml");	0
653250	652304	dynamic datatemplate with valueconverter	string assName = Assembly.GetExecutingAssembly().GetName().Name;\n    StringBuilder sb = new StringBuilder();\n    sb.Append("<DataTemplate ");\n    sb.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");\n    sb.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");\n    sb.Append("xmlns:src='clr-namespace:WpfToolkitDataGridTester;assembly=" + assName + "' >");\n    sb.Append("<DataTemplate.Resources>");\n    sb.Append("<src:FooConverter x:Key='fooConverter' />");\n    sb.Append("</DataTemplate.Resources>");\n    sb.Append("<TextBlock ");\n    sb.Append("Foreground='{Binding Candidates[" + i + "].CandidateType,Converter={StaticResource fooConverter}}' ");\n    sb.Append("Text='{Binding Candidates[" + i + @"].Name}' />");\n    sb.Append("</DataTemplate>");\n    var template = (DataTemplate)XamlReader.Parse(sb.ToString());	0
9793090	9792825	Rewrite program from Console to WinForms	private void btnSubmit_Click(object sender, EventArgs e)\n    {\n        string guessedWord = textBoxGuessedWord.Text;\n        if (guessedWord == _secretWord)\n        {\n            _guessedCorrectly = true;\n        }\n        else\n        {\n            _guessedCorrectly = false;\n        }\n    }	0
19556617	19556570	C# Deserializing to a dictionary<string, Object>	Dictionary<string, Object> DictionaryEmployee = (Dictionary<string, Object>) Deserializer(byteArrayEmp);	0
745087	745068	Need help on setting web service proxy dynamically without build?	public Service1() {\n    string urlSetting = System.Configuration.ConfigurationSettings.AppSettings["WebApplication1.localhost.Service1"];\n    if ((urlSetting != null)) {\n        this.Url = string.Concat(urlSetting, "");\n    }\n    else {\n        this.Url = "http://localhost/WebService1/Service1.asmx";\n    }\n}	0
32362561	32362467	Is it possible to populate same user control with different data on aspx?	public BindDropdownDataSource(DataSet dataSource)\n{\n    DropDownList1.DataSource = dataSource;\n    DropDownList1.DataBind();\n}	0
21239795	21239673	Number to array of digits with variable amount of padding zeroes	int[] arr = new int[digits];\nfor (int i = 0; i < digits; i++)\n{\n    arr[digits - i - 1] = number % 10;\n    number /= 10;\n}	0
33124263	33123895	How can I get the Type from a UnaryExpression?	Expression<Func<Kitten, object>> property = c => c.KittenAge;\n    var unaryExpression = property.Body as UnaryExpression;\n    var propertyExpression = unaryExpression.Operand as MemberExpression;\n\n    if (Nullable.GetUnderlyingType(propertyExpression.Type) == null)\n    {\n      // Error, must be nullable\n    }	0
6396259	6396201	How do I generate random dark colors in C#?	random.Next(0x1000000) & 0x7F7F7F	0
27500162	27500129	Sorting List by DateTime	var Result = callResponse.Report.OrderBy( iItem => iItem.CompletedDate );	0
11205139	11204950	retrieve Xml data from database into my page	SqlDataAdapter adpater=new SqlDataAdapter(comm);\nDataSet shop=new DataSet();\nadapter.Fill(shop);\n\nXmlDocument cdoc = new XmlDocument();\ncdoc.LoadXml(shop.GetXml());	0
34331266	34330872	Correct way to add references to C# project such that they are compatible with version control	.csproj	0
15757930	15757645	Bold selective text from string based on start/end position	var result = str.Insert(7, "</b>").Insert(6 - 1, "<b>");	0
8677441	8677413	How to create a polymorphic array with linq to xml?	List<Base> PMList = (from baseNode from xmlDoc.Descendants("nodes") \n                     where baseNode.type == ("Der1") \n                     select (Base) new Der1() {\n                         Attr1 = baseNode.Attribute("attr1").Value\n                     }\n                    ).Union(\n                     from baseNode from xmlDoc.Descendants("baseNode") \n                     where baseNode.type == ("Der2") \n                     select (Base) new Der2() {\n                         Attr2 = baseNode.Attribute("attr2").Value\n                     }\n                    ).ToList();	0
6540142	6540117	How to create a loop for the following case?	for(int i = 1; i < bound; i += 2) {\n    for(int j = 2; j <= 4; j += 2) {\n        Console.WriteLine(\n            String.Format("/html/body/table/tr[{0}]/td[{1}]", i, j)\n        );\n    }\n    Console.WriteLine();\n}	0
4264007	4263589	Hiding certain channel of an image with C#	AForge.Imaging.Filters.ChannelFiltering	0
4012522	4012424	C# - Disable buttons with image	button.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;	0
20123853	20123115	Mapping Parent and Children relationship collections to a single table in EF6	public OrganisationMap()\n{\n    HasMany(n => n.Children)\n        .WithMany( n => n.Parents )\n        .Map(m =>\n            m.ToTable("OrganisationRelationship")\n            .MapLeftKey("ParentId")\n            .MapRightKey("ChildId"));\n}	0
48971	48916	Multi-threaded splash screen in C#?	protected override void OnCreateSplashScreen()\n{\n    this.SplashScreen = new SplashForm();\n    this.SplashScreen.TopMost = true;\n}	0
23592655	23592610	Get informations about files in folder	var listOfFiles = new  List<String>();\n        string [] fileEntries = Directory.GetFiles(targetDirectory);\n        foreach(string fileName in fileEntries)\n            {\n                lisOfFiles.Add(fileName);\n            }	0
16069116	16058521	Temporarily disable/bypass system set proxy during a particular bit of code?	System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName	0
16891077	16890725	Is it possible with regex in C#	\*(?<date>\d{2}/\d{2}/\d{4})[^/]*?BNA CNTRS	0
25139159	25138175	C# property grid, set browsable attribute to enumeration each item on runtime?	object[] browsable;\n\nType type = typeof(xxx);\nFieldInfo[] fieldInfos = type.GetFields();\nforeach (FieldInfo fieldInfo in fieldInfos)\n{\n    browsable = fieldInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);\n\n    if (browsable.Length == 1)\n    {\n\n        System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties(fieldInfo);\n\n        //Get property descriptor for current property\n        System.ComponentModel.PropertyDescriptor descriptor = pdc[24];// custom attribute\n        BrowsableAttribute attrib =\n      (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; \n        FieldInfo isReadOnly =\n         attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);\n        isReadOnly.SetValue(attrib, true);\n    }\n}	0
1022197	997086	Vista style explorer/folder view	[DllImport("uxtheme.dll")]\npublic extern static int SetWindowTheme(\n    IntPtr hWnd,\n    [MarshalAs(UnmanagedType.LPWStr)] string pszSubAppName,\n    [MarshalAs(UnmanagedType.LPWStr)] string pszSubIdList);\n\nSetWindowTheme(listView.Handle, "explorer", null);	0
4818431	4818187	trying to read out xml but getting the html	WebClient wc = new WebClient();\nwc.Headers.Add("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");\nstring resultXML = wc.DownloadString("http://armory.wow-europe.com/guild-info.xml?r=Aegwynn&n=Quite+Tight");\nXDocument doc = XDocument.Parse(resultXML);	0
18563603	18559123	How to block onbeforeload JavaScript in web browser control?	private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)\n    {\n        InjectAlertBlocker();\n    }	0
25206566	25194698	How to return more than one field using a STIntersection query in SQL Server	create procedure findPolygons (\n   @line geography\n)\nas\nbegin\n\n    select ZoneId, Coordinates\n    from SpatialZonePolygons \n    where Coordinates.STIntersects( @line ) = 1\n\nend	0
21511863	21511688	Binding a Dependencyproperty as the Datacontext	ControlItemHost.SetBinding(FrameworkElement.DataContextProperty, new Binding("MyItems") { Source = this });	0
11191599	11191418	How to check Model properties in unit test	// Act\nActionResult result = controller.SaveAndExit(viewModel);\n\n// Assert\nAssert.IsInstanceOfType(result, typeof(ViewResult));\nViewResult viewResult = (ViewResult)result;\n\nAssert.IsInstanceOfType(viewResult.Model, typeof(ViewModel1));\nViewModel1 model = (ViewModel1)viewResult.Model;\n\nAssert.IsNotNull(model.Reg);	0
10521281	10521184	Is it possible to scan for methods with specific attributes within assembly?	this.GetType().GetMethods()	0
26232885	26232510	XAML, Image control, local storage image	private static BitmapImage GetImageFromIsolatedStorage(string imageName)\n{\n    var bimg = new BitmapImage();\n    using (var iso = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n        using (var stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))\n        {\n            bimg.SetSource(stream);\n        }\n    }\n    return bimg;\n}	0
9364532	9364492	Convert this C# template to VB equivalent	Html.TextBox("", [String].Format("{0:d}", Model.ToShortDateString()), New With { _\nKey .[class] = "datefield", _\nKey .type = "date" _\n})	0
8879324	8879082	how to disable compatibility check in excel while automating through c#	ThisWorkBook.DoNotPromptForConvert = true	0
15127685	15127587	Determine a Key Pressed is Numbers in WinRT	int number = -1 ; //invalid value \nif (event.Key >= VirtualKey.Number0 && event.Key <= VirtualKey.Number9)\n{\n   number = event.Key-VirtualKey.Number0;\n}\nif (event.Key >= VirtualKey.NumberPad0 && event.Key <= VirtualKey.NumberPad9)\n{\n   number = event.Key-VirtualKey.NumberPad0 ;\n}\nif(number!=-1)\n{\n     //enter code here\n}	0
19130124	16297596	Select only a text of cell in datagridview c#	DataGridViewCell cellQty = dgvBundle.Rows[dgvBundle.Rows.Count - 1].Cells[1];\n        dgvBundle.CurrentCell = cellQty;            \n        dgvBundle.CurrentRow.Cells[1].Selected = true;\n        dgvBundle.BeginEdit(true);	0
16674473	16673551	value member in textbox and display member in combobox	Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave\n    Dim value As String = TextBox1.Text\n    ComboBox1.SelectedValue = value\nEnd Sub	0
3320540	3320314	How to redirect to pre-defined error page?	string my404Setting;\n\n    // Get the application configuration file.\n    System.Configuration.Configuration config =\n        ConfigurationManager.OpenExeConfiguration(\n        ConfigurationUserLevel.None);\n\n    foreach (ConfigurationSectionGroup sectionGroup in config.SectionGroups)\n    {\n        if (sectionGroup.type == "customErrors" )\n        {\n            foreach (ConfigurationSections section in sectionGroup.Sections)\n            {\n               if (section.StatusCode = "404")\n               {\n                  my404Setting = section.Redirect;\n                  break;\n               }\n            }\n            break; \n        }\n    }\n}	0
14583625	14580507	Printing in Silverlight/Lightswitch using XAML and custom controls	void printArtikels_PrintPage(object sender, PrintPageEventArgs e){\n    MyPrintLayout mpl = new MyPrintLayout();\n    e.PageVisual = mpl;\n}	0
31887410	31886866	Invalid Path while processing Font with MGCB	"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"	0
12550736	12550714	Looping a process in C#	int age;\nwhile(true)\n{\n    Console.WriteLine("Your age:");\n    string line = Console.ReadLine();\n\n    if (!int.TryParse(line, out age))\n       Console.WriteLine("{0} is not an integer", line);\n\n    else break;\n}	0
3296427	3296371	Syntax for LINQ to DataSets Row Filter in C#?	var cities = CityInitials.Rows.Select(x => x.CityInitials).ToList();\nvar _filter = EmployeeTable.Rows.Where(x => cities.Contains(x.City));	0
18249859	18177883	Throwing an HttpResponseException always results in a StatusCode: 500 response in the client	MyController : ApiController	0
10782722	10778984	How to ignore recursive cache data to fully get them on the database storage?	ctx.As.MergeOption = MergeOption.OverwriteChanges;\nctx.Bs.MergeOption = MergeOption.OverwriteChanges;\nvar lst = from a in ctx.As.Include("Bs") select a;	0
17759199	17759183	Auto scrolling ScrollViewer in WPF/Visual C#	ScrollViewer.ScrollToBottom()	0
9018115	9017988	Is it possible to cast a type parameter?	Dictionary<string, object> newDict;\nnewDict = dict.ToDictionary(pair => pair.Key, pair => (object)pair.Value);	0
34346950	34344613	FileSystemWatcher specific files with filename keywords filter	FileSystemWatcher objWatcher = new FileSystemWatcher(); \nobjWatcher.Changed += new FileSystemEventHandler(OnChanged); \n\nstring[] filters = new string[] { "test", "blah", ".exe"}; //this needs to be a member of the class so it can be accessed from the Changed event\n\nprivate static void OnChanged(object source, FileSystemEventArgs e) \n{ \n    if (filters.Any(e.FullPath).Contains))\n    {     \n        string strFileExt = getFileExt(e.FullPath); \n    }\n}	0
24490128	24339224	How to show image in datagridview as thumbnail	dgvEmpInfo.DataSource = ds.Tables[0];\n\n       foreach (DataGridViewRow dgvRow in dgvEmpInfo.Rows)\n       {\n           dgvRow.Height = 100;\n       }	0
19869175	19868880	HTML value in Cookie	StringBuilder str = new StringBuilder;\n\n    str.Append("<p>Please print this form and send it with your repair.<br /><b>INSTRUMENT REPAIR FORM</b><p>");\n\n    str.Append("<table style='width: 800px'>");\n\n...\n\n    HttpCookie myCookie = new HttpCookie("InsRepairFormCookie");\n    myCookie.Value = str.ToString();\n\n    Response.Cookies.Add(myCookie);	0
19803428	19802935	How to get the real path of My Documents	Environment.GetFolderPath	0
33229876	33079078	Failed to convert the downloaded code coverage tool to XML	Downloading coverage file from {0} to {1}	0
920215	920211	How do I get SelectedValue to bother returning the actual selected value	if(!IsPostBack){ ... }	0
504824	504729	How do I cast a List<T> effectively?	List<InputField> list = (from i .... select i).Cast<IDataField>.ToList();	0
9000116	4870267	Converting images from word document into bitmap object	Thread thread = new Thread([Method]);\nthread.SetApartmentState(ApartmentState.STA);\nthread.Start();\nthread.Join();	0
22733611	22733610	How do I programatically change the status of a test in VersionOne?	internal void TestStatusPassed(string str_TestID)\n{\n     var testId = Oid.FromToken(str_TestID, _context.MetaModel);\n     var query = new Query(testId);\n     var testType = _context.MetaModel.GetAssetType("Test");\n     var sourceAttribute = testType.GetAttributeDefinition("Status");\n     query.Selection.Add(sourceAttribute);\n     var result = _context.Services.Retrieve(query);\n     var test = result.Assets[0];\n     var oldSource = GetValue(test.GetAttribute(sourceAttribute).Value);\n     test.SetAttributeValue(sourceAttribute, "TestStatus:9123");\n     _context.Services.Save(test);\n }	0
27842643	27830102	OData: Map inherited key using ODataConventionModelBuilder	builder.EntityType<Base>().HasKey(m => m.ID);\n...\n(in another class far far away)\nbuilder.EntityType<DerivedA>().HasKey(m => m.ID);\nbuilder.EntityType<DerivedB>().HasKey(m => m.ID);	0
6938218	6938002	Outlook interoperability	Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application()	0
6845202	6845064	Extend an application to dual monitors	void showOnMonitor(int showOnMonitor) \n{ \n  Screen[] sc; \n  sc = Screen.AllScreens; \n  //get all the screen width and heights \n  Form2 f = new Form2(); \n  f.FormBorderStyle = FormBorderStyle.None; \n  f.Left = sc[showOnMonitor].Bounds.Width; \n  f.Top = sc[showOnMonitor].Bounds.Height; \n  f.StartPosition = FormStartPosition.Manual; \n  f.Show(); \n}	0
10564678	10564637	Show Button in Table Cell Hover Over/Mouse Over	#buttonBlock input{\n   display:none;\n}\n#bold_cell1:hover #buttonBlock input{\n   display:block;\n}	0
3949066	3949033	List<> Get next or previous element that satisfys a condition	public Player GetNextPlayer()\n{\n    int currentPlayerIndex = Players.FindIndex(o => o.IsThisPlayersTurn);\n    int next = _direction.Equals(Direction.Forwards) ? 1 : -1;\n\n    int nextPlayerIndex = currentPlayerIndex;\n    do\n    {\n      nextPlayerIndex = (nextPlayerIndex + next + Players.Count) % Players.Count;\n    }while(Players[nextPlayerIndex].HasNoCards && nextPlayerIndex != currentPlayerIndex);\n\n    return Players[nextPlayerIndex];\n}	0
13682490	13682226	C# - How to Save IntPtr Buffer Data to File (quickest way)?	private void callback(IntPtr buffer, int length)\n{\n    FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write);\n    int written;\n    WriteFile(file.Handle, buffer, length, out written, IntPtr.Zero);\n    file.Close();\n}\n\n [DllImport("kernel32.dll")]\n private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int NumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);	0
29005405	29005330	How to get connect to core database in sitecore	using Sitecore.SecurityModel;\n\n.....\n\n\nSitecore.Data.Database coredb = Sitecore.Configuration.Factory.GetDatabase("core");\n\nusing (new SecurityDisabler())\n{\n  var a = coredb.GetItem("/sitecore");\n}	0
29597757	29597535	How to skip a column in datagridview when the tab key is pressed	private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)\n    {           \n        if (dataGridView1.Columns[e.ColumnIndex].Name == "col2")\n        {\n            SendKeys.Send("{TAB}");\n        } \n    }	0
14264857	14264777	Coloring text using reflection	Type t = a.GetType("MyPlugIn.colorclass");\nMethodInfo mi = t.GetMethod("color");\nObject obj = Activator.CreateInstance(t);	0
10588723	10587837	How to make REST based WCF service Service file be index?	[WebInvoke(UriTemplate = "", Method = "GET")]\npublic void RedirectToHelp()\n{          \n  WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Redirect;\n  WebOperationContext.Current.OutgoingResponse.Location = "help";\n\n}	0
5794116	5792997	common Settings.settings file for entire solution	Settings.settings	0
22031715	22031306	Entity Framework Many to Many List Table Association	public static bool AddPublishLocation(AppDbContext db, int id, List<TypeLocation> locations)\n{\n    try\n    {\n        Offer Offer = db.Offers\n            .Include("LocationsToPublish")\n            .Where(u => u.Id == id)\n            .FirstOrDefault<Offer>();\n\n        //Add new locations\n        foreach (TypeLocation loc in locations)\n        {\n            Offer.LocationsToPublish.Add(loc);\n        }\n        db.SaveChanges();\n        return true;\n    }\n    catch\n    {\n        return false;\n    }\n}	0
1854177	1832360	Optimising XDocument to XDocument XSLT	XDocument outputDoc = new XDocument();\nprocessor.Transform(sourceDoc, outputDoc.CreateWriter());\nreturn outputDoc;	0
1508925	1508608	Reading views in Oracle using SYSobjects	Sybase/SQL Server: sysobjects\nOracle: ALL_OBJECTS\nNotes: The corresponding Oracle tables is: all_objects (Displays all objects that are accessible\nby the current user.)\nResolution: Query or make views on ALL_OBJECTS table like:\nSelect object_name from all_objects where object_type = 'TABLE';\nSelect object_name from all_objects where object_type = 'PROCEDURE';\nSelect object_name from all_objects where object_type = 'TRIGGER';	0
16961291	16960555	How do I cast generic enum to int?	public void SetOptions<T>()\n{\n    Type genericType = typeof(T);\n    if (genericType.IsEnum)\n    {\n        foreach (T obj in Enum.GetValues(genericType))\n        {\n            Enum test = Enum.Parse(typeof(T), obj.ToString()) as Enum;\n            int x = Convert.ToInt32(test); // x is the integer value of enum\n                        ..........\n                        ..........\n        }\n    }\n}	0
5799984	3326233	C# Uploading files via HTTP	WebClient client = new WebClient();\nbyte[] bret = client.UploadFile(webpath, "POST", filepath);\nstring sret = System.Text.Encoding.ASCII.GetString(bret);	0
31221198	31221123	How to clear the BindingList Comepeltly	myBindingList.Clear()	0
9015658	9015348	Lucene custom analyzer	public sealed class NewWhitespaceAnalyzer : Analyzer\n{\n    public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)\n    {\n        return new LowerCaseFilter(new WhitespaceTokenizer(reader));\n    }\n\n    public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader)\n    {\n        SavedStreams streams = (SavedStreams) GetPreviousTokenStream();\n        if (streams == null)\n        {\n            streams = new SavedStreams();\n            SetPreviousTokenStream(streams);\n            streams.tokenStream = new WhiteSpaceTokenizer(reader);\n            streams.filteredTokenStream = new LowerCaseFilter(streams.tokenStream);\n        }\n        else\n        {\n            streams.tokenStream.Reset(reader);\n        }\n        return streams.filteredTokenStream;\n    }\n}	0
4816970	4816426	Persisting a control's properties	ViewState[@"somekey"] = ...	0
13299264	13299209	Is there a slick way to turn List<int?> into List<int> without a loop?	var values = given.Where(n => n.HasValue).Select(n => n.Value).ToList();	0
31285401	31270098	How can I get "Search Queries" data from Google WMT?	webmasters.searchanalytics.query	0
29129154	29128950	possible unintended reference comparison to get a value comparison when using SqlDataReader	using(SqlDataReader reader = command.ExecuteReader())\n{\n    while (reader.Read())\n    {\n        if (string.Equals(combomedicine.SelectedItem.ToString(), \n                          reader.GetValue(0).ToString(), \n                          StringComparison.InvariantCultureIgnoreCase)\n        {\n            combocompany.Items.Add(reader.GetValue(1).ToString());\n            break;\n        }\n    }\n}	0
30195050	30188890	Change behaviour of Print button in ReportViewer C#	myViewer.Print += new CancelEventHandler(myViewer_Print);\nvoid myViewer_Print(object sender, CancelEventArgs e)\n{\n    e.Cancel = true;\n    MyCustomPrintFunction();\n}	0
25820060	25820040	How to Pass Array From Form Load to Button Click Method	private Label[]  labelsArray = null;\n\nprivate void Form1_Load(object sender, EventArgs e){\n   labelsArray = new Label[]{ label1, label2, label3, label4, label5 };\n}\n\nprivate void button1_Click(object sender, EventArgs e){}	0
15900837	15900723	How to do sorting on the basis of attributes in c#	foreach (Component compCategories in categories.OrderBy(c => c.Title).ToList())\n{\n    GenerateXML(xml, compCategories);\n}	0
9498566	9498509	How to debug the installation of a custom Windows service?	Debugger.Break();	0
13234239	13234164	Searching specific indexes in arrays for specific numbers	var indexes = new int[] {6, 7, 8};\nif (indexes.Any(i => si[i] == 3))\n{\n    MessageBox.Show("3 detected")\n}	0
9623330	8875715	RenderTargetBitmap DPI for drawing application	// Get system DPI\nMatrix m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice;\nif (m.M11 > 0 && m.M22 > 0)\n{\n    dpiXFactor = m.M11;\n    dpiYFactor = m.M22;\n}\nelse\n{\n    // Sometimes this can return a matrix with 0s. Fall back to assuming normal DPI in this case.\n    dpiXFactor = 1;\n    dpiYFactor = 1;\n}	0
6046664	6046623	Passing variables from cs to javascript	ClientScript.RegisterClientScriptBlock(this.GetType(), "variable", "<script language=javascript> var direction = '" + pagFinal + "'; </script>");	0
5999398	5992104	Cannot get no. of photos in a Facebook Album	"name": "Happy Lunar New Year 2011",\n"link": "http://www.facebook.com/album.php?aid=324257&id=20531316728",\n"cover_photo": "10150146072661729",\n"count": 79,\n"type": "normal",	0
28932024	28931956	How to generate Random 26 length character string with no duplicates(characters) in c#?	Random rnd = new Random();\nvar newstr = String.Concat("abcdefghijklmnopqrstuvwxyz".OrderBy(x => rnd.Next()));	0
18608839	18608808	Jump out from Inner-Foreach to Outer-Foreach, Keep Inner-Foreach where you left it	int i = 0;\n int k = 0;\n bool shouldBreak;\n\n var nodes = elements.Nodes();\n var rows = dataSetDB.Tables[0].Rows;\n\n for (i = 0; i < nodes.Count(); i++)\n {\n     for(k = 0; k < rows.Count(); k++)\n     {\n        string itemDB = rows[k][0].ToString().ToUpper();\n        string itemXml = nodes[i].ToString().ToUpper();\n            if (itemDB == itemXml)\n            {   \n                shouldBreak = true;\n                break;\n            }\n            if (itemDB != itemXml)\n            {  \n                shouldBreak = true;\n                break;\n            }\n     }\n     if (toBreak)\n         break;\n }	0
5547028	5546501	ASP.NET MVC3 Routing - Same URL for different areas	- In Controller define 2 function for desktop & iPhone, they have the same ActionName\n\n    [iPhone]\n    [ActionName("Index")] \n    public ActionResult Index_iPhone() { /* Logic for iPhones goes here */ }     \n    [ActionName("Index")]\n    public ActionResult Index_PC() { /* Logic for other devices goes here */ }\n\n- Define [iPhone] action method selector:           \n    public class iPhoneAttribute : ActionMethodSelectorAttribute \n        { \n            public override bool IsValidForRequest(ControllerContext controllerContext,  \n                                                   MethodInfo methodInfo) \n            { \n                var userAgent = controllerContext.HttpContext.Request.UserAgent; \n                return userAgent != null && userAgent.Contains("iPhone"); \n            } \n        }	0
26973286	26971266	Converting Expression<Func<DTO,bool>> to Expression<Func<Domain, bool>>	using System.Linq;\nusing System.Linq.Dynamic;\n\n    public ICollection<UserDto> GetUsersByFilter(string filter)\n    {\n        var addressBooksRepository = new AddressBooksRepository();\n        var addressBookEntries = addressBooksRepository.GetAll().Where(filter);\n                //return data\n    }	0
19136878	19136824	Non-intrusive XML Serialization techniques?	System.Xml.Serialization	0
17158513	17158347	Back button prevents page from authorizing user?	Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);\n Response.Cache.SetNoStore();	0
1604064	1603801	Storing private keys using DSACryptoServiceProvider	ExportParameters(true)	0
473938	473790	Replicating C++'s RAII in C#	public class LogContext: IDisposable\n{\n  private readonly Logger _logger;\n  private readonly string _context;\n\n  public LogContext(Logger logger, string context){\n    _logger = logger;\n    _context = context;\n    _logger.EnterContext(_context);\n  }\n\n  public void Dispose(){\n    _logger.LeaveContext(_context);\n  }\n}\n\n//...\n\npublic void Load(){\n  using(new LogContext(logger, "Loading")){\n    // perform load\n  }\n}	0
29211741	29210039	Getting Redis Master address from Sentinel C#	public string GetMasterFromSentinel(string sentinelAddress)\n    {\n        TcpClient server;\n\n        try\n        {\n            var splittedAddress = sentinelAddress.Split(':');\n            server = new TcpClient(splittedAddress[0], splittedAddress[1].ParseInt());\n        }\n        catch (SocketException)\n        {\n            _log.Error("Unable to connect to server");\n            return string.Empty;\n        }\n        NetworkStream ns = server.GetStream();\n        var payload = new byte[] { 0x2a, 0x32, 0x0d, 0x0a, 0x24, 0x38, 0x0d, 0x0a, 0x73, 0x65, 0x6e, 0x74, 0x69, 0x6e, 0x65, 0x6c, \n                0x0d, 0x0a, 0x24, 0x37, 0x0d, 0x0a, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72, 0x73, 0x0d, 0x0a };\n        ns.Write(payload, 0, payload.Length);\n        ns.Flush();\n        var data = new byte[1024];\n        ns.Read(data, 0, data.Length);\n        var recv = ns.Read(data, 0, data.Length);\n\n        ns.Close();\n        server.Close();\n        return ParseResponse(data);\n    }	0
21918565	21918492	AsNoTracking() Method Is Missing From Context in Entity Framework	AsNoTracking()	0
11302817	11302766	What are the potential hazards of an object removing itself from a list it is in?	List<T>	0
26927714	26927162	Control of parallel foreach flow	var lock = new ReaderWriterLockSlim();\n\n\nParallel.Foreach(items, (item, state) =>\n{\n    lock.EnterReadLock();\n    try {\n        Task1(item);\n    } finally {\n        lock.ExitReadLock()\n    }\n    lock.EnterWriteLock();\n    try {\n        Task2(item);\n    } finally {\n        lock.ExitWriteLock()\n    }\n}	0
28898678	28898463	Remove duplicates from XML and then save as XML file	public static void Main(string[] args)\n{\n    var xelement = XElement.Load("data.xml");\n    var employees = xelement.Elements()\n        .Select(e => new\n        {\n            Element = e,\n            Name = e.Element("Employee").Value,\n            ChangeTimeStamp = DateTime.Parse(e.Element("ChangeTimeStamp").Value)\n        })\n        .GroupBy(e => e.Name)\n        .Select(g => \n        {\n            var maxTimestamp = g.Max(e => e.ChangeTimeStamp);\n            foreach (var e in g)\n            {\n                if (e.ChangeTimeStamp < maxTimestamp)\n                {\n                    e.Element.Remove();\n                }\n            }\n\n            return new\n            {\n                Name = g.Key,\n                ChangeTimeStamp = maxTimestamp\n            };\n        });     \n\n    xelement.Save(yourPathToSave);\n}	0
8566912	8566768	Cant View CheckBoxList from the database	if(!Page.IsPostBack)	0
32956910	32895133	c# ping between two ip addresses	public bool IsPingable(string servA, string servB)\n    {\n        string path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\Resources\\PsExec.exe";\n        Process p = new Process();\n        p.StartInfo.UseShellExecute = false;\n        p.StartInfo.CreateNoWindow = true;\n        p.StartInfo.FileName = path;\n        p.StartInfo.Arguments = @"\\" + servA + " ping " + servB + " -n 1";\n        p.StartInfo.RedirectStandardOutput = true;\n        p.Start();\n        string output = p.StandardOutput.ReadToEnd();\n        if (!output.Contains("100% loss"))\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }	0
12889363	12889194	Mysteriously added quotation mark inside a string	private readonly string BYTE_ORDER_MARK_UTF8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());\n\n...\n\nif (line.StartsWith(BYTE_ORDER_MARK_UTF8))\n                line = line.Remove(0, BYTE_ORDER_MARK_UTF8.Length);	0
30994914	30977810	Removing of UINavigationBar border leads to black status bar	public static class UINavigationBarExtensions\n    {\n        public static void RemoveShadowImage(this UINavigationBar navigationBar)\n        {\n            foreach (var image in \n                from subView in navigationBar.Subviews\n                select subView as UIImageView\n                into imageView\n                where imageView != null && imageView.ToString()\n                    .Contains("BarBackground")\n                from image in imageView.Subviews.OfType<UIImageView>()\n                    .Where(image => Math.Abs(image.Bounds.Height - 0.5) < float.Epsilon)\n                select image)\n                image.RemoveFromSuperview();\n        }\n    }	0
19268478	19268319	How to match string in 2 diff collection and return the collection items that did not match in LINQ	var commonTitles = categoryList.Select(x=>x.Title.Trim())\n                               .Intersect(charityList.Select(x=>x.EntryTitle.Trim()));\nvar titleNotExitsCollection  = categoryList.Where(x=>!commonTitles.Contains(x.Title))\n                                           .ToList();\nvar titleExitsCollection = charityList.Where(x=>commonTitles.Contains(x.EntryTitle))\n                                      .ToList();	0
19800377	19796245	Can a Web API controller GETter for query strings be generic?	public IEnumerable<string> Get()\n{\n    List<string> retval = new List<string>();\n\n    var qryPairs = Request.GetQueryNameValuePairs();\n    foreach (var q in qryPairs)\n    {\n        retval.Add("Key: " + q.Key + " Value: " + q.Value);\n    }\n\n    return retval;\n}	0
2344107	2344098	C# how to create a Guid value?	Guid id = Guid.NewGuid();	0
27606949	27606641	How to update the text a label from another Non UI thread in c#	public class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n\n    [STAThread]\n    static void Main()\n    {\n        //Thread l'affichage de la form\n        Program SecondThread = new Program();\n        Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));\n        th.Start();  \n\n        //Update the label1 text\n        while (SecondThread.TheForm == null) \n        {\n          Thread.Sleep(1);\n        } \n        SecondThread.TheForm.SetTextLabel("foo");\n\n    }\n\n    internal Form1 TheForm {get; private set; }\n\n    public void ThreadForm()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        var form1 = new Form1();\n        Application.Run(form1);\n        TheForm = form1;\n\n    }\n\n\n}	0
2279362	2279341	C#: How to load assembly from GAC?	"ycomp.myassembly.dll, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3"	0
32868854	32860531	Not able to access app.config in class library with window service	var map = new ExeConfigurationFileMap() { ExeConfigFilename = @"path\to\datalayer\app.config" };\nvar config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);\nvar connectionString = config.ConnectionStrings.ConnectionStrings["myDBConn"];	0
1474294	1474235	How to remove "Auth_Password" from ELMAH logs	_serverVariables.Remove(AUTH_PASSWORD);\n//AUTH_PASSWORD = const string = "AUTH_PASSWORD" AND SET ELSEWHERE	0
22592360	22592332	How can I redirect a webpage in C#	Response.Redirect("url");	0
21468195	21452498	Read New Relic json message	WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");\n    wr.ContentType = "application/json";\n    wr.Method = "GET";\n    wr.Headers.Add("X-Api-Key:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");\n\n    using (WebResponse response = wr.GetResponse())\n    {\n        using (Stream stream = response.GetResponseStream())\n        {\n            byte[] bytes = new Byte[10000];\n            int n = stream.Read(bytes, 0, 9999);\n            string s = System.Text.Encoding.ASCII.GetString(bytes);\n        }\n    }	0
10756672	10455703	WP7 - ContextMenu doesn't show on Hyperlink	var inline = new InlineUIContainer { Child = SomeHyperlinkButton }	0
24795381	24794932	Getting the location of a Grid during runtime in codebehind	double xPosition = Canvas.GetLeft(this);\ndouble yPosition = Canvas.GetTop(this);	0
26326796	26326590	Can a double not be less than one, so is .027412133 not able to be stored as a double?	double radians = 0.0d;\ndouble degrees = 45.0d;\n\nradians = degrees * Math.PI / 180.0d;\nradians = 2.00d * radians;\nConsole.WriteLine(radians * 180 / Math.PI); \n\n//returns 90, so sin(radians) == sin(90) which = 1	0
11611086	11523078	Openrasta Validators Issue	ResourceSpace.Uses.CustomDependency<IOperationInterceptor, ResourceValidationInterceptor>(DependencyLifetime.Transient);\n\nResourceSpace.Uses.CustomDependency<IValidator<Customer>, CustomerValidator>(DependencyLifetime.Transient);	0
18552464	18546545	Load xaml viewmodel at run-time with windows phone	xmlns:vm = "clr-namespace:SoundBoard.ViewModels;assembly=SoundBoard">	0
22590430	22590351	How to populate listbox with SQL Database dynamically	using (SqlConnection con = new SqlConnection(YOUR_CONNECTION_STRING))\n        {\n            using (SqlCommand cmd = new SqlCommand("Select ID, txtname, txtcitycode from YOUR_TABLE", con))\n            {\n                SqlDataAdapter da = new SqlDataAdapter(cmd);\n                DataTable dt = new DataTable();\n                da.Fill(dt);\n                DropDownList1.DataTextField = "txtname";\n                DropDownList1.DataValueField = "txtcitycode";\n                DropDownList1.DataSource = dt;\n                DropDownList1.DataBind();\n            }\n        }	0
10254457	10166613	Wait until page loads in webbrowser control 	public void button1_Click(object sender, EventArgs e)\n{\n    webBrowser1.Document.GetElementById("q").SetAttribute("value", "???");\n    webBrowser1.Document.GetElementById("btnK").InvokeMember("Click");\n    int x=0;\n    while (x==0)\n   {\n       System.Windows.Forms.Application.DoEvents();\n        if(webBrowser1.Document.GetElementById("pnnext") != null)\n        break;\n   }\n\n    webBrowser1.Document.GetElementById("pnnext").InvokeMember("Click");\n    webBrowser1.Document.GetElementById("q").Focus();\n}	0
14457347	14457319	Linq to determine if a value occurs more than x number of times	Jobs.GroupBy(j => j.JobCode).Where(g => g.Count() > 4)	0
27607479	27607044	How to set a value from an Expression for nested levels of depthness?	public static TEntity ExecuteMagicSetter<TEntity, TProperty>(\n        this TEntity obj,\n        Expression<Func<TEntity, TProperty>> selector,\n        TProperty value)\n{\n    var setterExpr = CreateSetter(selector);\n    setterExpr.Compile()(obj, value);\n    return obj;\n}\n\nprivate static Expression<Action<TEntity, TProperty>> CreateSetter<TEntity, TProperty>\n        (Expression<Func<TEntity, TProperty>> selector)\n{\n    var valueParam = Expression.Parameter(typeof(TProperty));\n    var body = Expression.Assign(selector.Body, valueParam);\n    return Expression.Lambda<Action<TEntity, TProperty>>(body,\n        selector.Parameters.Single(),\n        valueParam);\n}	0
1804681	1804669	A generic type as a parameter	public static void SomeMethod<T>(List<T> l, T item)\n{\n    l.Add(item);\n}	0
33833992	33832904	Pass parameter to return complex result of stored procedure	print result	0
22498190	22498022	pass photochosen image from one page to another C#	private void photoChooserTask_Completed(object sender, PhotoResult e)\n        {\n            if (e.ChosenPhoto != null)\n            {\n             **//Edits**\n            if (PhoneApplicationService.Current.State.ContainsKey("Image"))\n                    if (PhoneApplicationService.Current.State["Image"] != null)\n                        PhoneApplicationService.Current.State.Remove("Image");\n                BitmapImage image = new BitmapImage();\n                image.SetSource(e.ChosenPhoto);\n                this.img.Source = image;\n     PhoneApplicationService.Current.State["Image"] = image;\n            }\n        }\n\n//On second page\n//I assume you want to image on page load\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n      BitmapImage image = new BitmapImage();\n     image  =(BitmapImage )PhoneApplicationService.Current.State["Image"]\n     PhoneApplicationService.Current.State.Remove("Image");\n     this.img.Source = image;\n    }	0
11196010	11195827	Reading Block of text file	using (var reader = new StreamReader(@"test.txt"))\n{\n    var textInBetween = new List<string>();\n\n    bool startTagFound = false;\n\n    while (!reader.EndOfStream)\n    {\n        var line = reader.ReadLine();\n        if (String.IsNullOrEmpty(line))\n            continue;\n\n        if (!startTagFound)\n        {\n            startTagFound = line.StartsWith("Condition");\n            continue;\n        }\n\n        bool endTagFound = line.StartsWith("Condition");\n        if (endTagFound)\n        {\n            // Do stuff with the text you've read in between here\n            // ...\n\n            textInBetween.Clear();\n            continue;\n        }\n\n        textInBetween.Add(line);\n    }\n}	0
18482798	18480547	How to implement MATLAB 'tansig' Hyperbolic tangent sigmoid transfer function in C#	output = [ 1, 0, 1, 0, 1 ] # output vector from a neuron\n\ndef sqash( n ):\n   return (2 ./ (1 + exp(-2*n)) - 1)\n\nsquashed_output = [ sqash(1), sqash(0), sqash(1), sqash(0), sqash(1) ]\n"""\nYour language probably support sqash( output ) as to apply it to each \nindividual element.\n"""	0
7198518	7198472	How can I show my enum in XAML?	get\n    {\n        return Enum.GetName(typeof(DatatypesInput), value);\n    }	0
24724745	24724582	C# SendMessage click button	[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]\n    private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, \n                                              string className, string windowTitle);\n\n    ...\n    IntPtr hwndChild = FindWindowEx(test.MainWindowHandle, IntPtr.Zero, "Button", "2");\n    if (hwndChild == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();	0
2211557	2211508	How do I search just the children of an XDocument, rather than all of its descendants?	XDocument.Elements()	0
31676431	31675997	How to get treeview control of one form in another form?	string newNodeName = null;\nForm_NewForm.FormClosing += delegate (Object s, FormClosingEventArgs e) {\n    newNodeName = textBox_newName.Text;\n}\nForm_NewForm.ShowDialog();\n\nif(!String.IsNullOrEmpty(newNodeName)) {\n    //add new node to treeview\n}	0
3390337	3390122	Creating a string-array of checked items in checked-list-box in C#	object[] items = lb.CheckedItems.OfType<object>().ToArray();	0
31065559	31065424	Define a KeyValuePair struct like <int,List<string>>	public class Article\n{\n    public Dictionary<int, List<string>> articleComments = new Dictionary<int, List<string>>();\n\n    public void AddComment(int titleNum, string comment)\n    {\n        if (!articleComments.ContainsKey(titleNum))\n        {\n            articleComments.Add(titleNum, new List<string>());\n        }\n        articleComments[titleNum].Add(comment);\n    }\n\n    public List<string> GetComment(int titleNum)\n    {\n        if (articleComments.ContainsKey(titleNum)\n        {\n            return articleComments[titleNum];\n        }\n        return null;\n    }\n}	0
24065175	24065100	Insert characters before and after a char	var string1 = "This is one of my best projects, so I'm going to finish it."\nvar string2 = string1.Replace(",", "%,%").Replace(".","%.%);	0
4196591	4196487	Get Parents for Entity in Hierarchy	List<Entity> graph = new List<Entity>()\nEntity current = this;\n\nwhile (current != null) {\n   graph.Add(current);\n   current = current.Parent;\n}\n\ngraph.Reverse();\n\nreturn graph;	0
244798	243995	Setting Folder permissions on Vista	public static void SetPermissions(string dir)\n        {\n            DirectoryInfo info = new DirectoryInfo(dir);\n            DirectorySecurity ds = info.GetAccessControl();            \n            ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users", \n                             FileSystemRights.FullControl,\n                             InheritanceFlags.ObjectInherit |\n                             InheritanceFlags.ContainerInherit,\n                             PropagationFlags.None,\n                             AccessControlType.Allow));\n            info.SetAccessControl(ds);            \n        }	0
15017253	15017216	Accessing a member of an anonymous type during construction	enumerable.select(i =>\n    {\n        //use a temporary variable to store the calculated value\n        var temp = CalculateValue(i.something); \n        //use it to create the target object\n        return new \n        {\n            a = temp,\n            b = temp + 5\n        };\n    });	0
16101887	16101850	Order of array items after serialization	Contract.Assume(Deserialize(Serialize(object)).Equals(object));	0
30510625	30510490	Comparing Excel Cells to form a While Loop in C#	while  (activesheet.Range["C" + n].Value == activesheet.Range["C" + (n + 1)])	0
9742347	9742211	Applying onClick() ListView showing XML	private void listView1_ItemActivate(object sender, EventArgs e)\n{ \n  testBox1.Text = listView1.SelectedItem.ToString();\n}	0
9972406	9972346	How can i change a specific label's text with a foreach loop	var control = this.FindName("button1");	0
10615450	10615405	How to format string to money	string.Format("{0:#.00}", Convert.ToDecimal(myMoneyString) / 100);	0
13543902	13543718	Process Serial data at a constant frequency	private class Result\n{\n    public double X { get; set; }\n    public double Y { get; set; }\n    public double Z { get; set; }\n}\n\nprivate Result lastResult;\n\nvoid wiimote_WiimoteChanged(object sender, WiimoteChangedEventArgs e)\n{\n    Result newResult = new Result {\n        X = e.WiimoteState.AccelState.Values.X,\n        Y = e.WiimoteState.AccelState.Values.Y,\n        Z = e.WiimoteState.AccelState.Values.Z,\n    } \n\n    lastResult = newResult;\n}\n\nvoid MainLoop()\n{\n    DateTime nextResultTime = DateTime.Now.AddMilliseconds(10);\n\n    while(true)\n    {\n        if (DateTime.Now >= nextResultTime)\n        {\n            AddResult(lastResult);\n            nextResultTime = nextResultTime.AddMilliseconds(10);\n        }\n        else\n        {\n            Thread.Sleep(1);\n        }\n    }\n}	0
1362101	1018183	Access Linq result contained in a dynamic class	string someProperty = "phonenumber";\nPropertyInfo property = typeof(T).GetProperty(propertyName);\nstring id = "1234";\nTable<MyClass> table = context.GetTable<MyClass>();\nExpression<Func<T, Object>> mySelect = DynamicExpression.ParseLambda<T, Object>(property.Name);\nvar query = (from asset in table where asset.Id == id select asset).Select(mySelect);\nreturn query.FirstOrDefault();	0
3746670	3746657	LINQ to Object comparing two lists of integer for different values	List2.Except(List1)	0
16505784	16505614	how to avoid the brackets appearing in the generated method statement	inputmethod.Statements.Add(new CodeAssignStatement(\n    new CodeVariableReferenceExpression("ColA"),\n    new CodeArrayIndexerExpression(\n        new CodeVariableReferenceExpression("inputs"),\n        new CodePrimitiveExpression(0))));	0
6247388	6247368	How do I access Registry from C# for a proxy?	using Microsoft.Win32;	0
10885262	10883872	processing Xnode with Linq efficiently	string data = @"\n<tags>\n  <tag id=""id1""> \n     <tag2> \n       <tag3 id=""id3"">10</tag3> \n       <tag4> \n        <tag5 id=""id5"">20</tag5> \n       </tag4> \n     </tag2> \n     <tag6> \n      <tag7>2010-12-31</tag7> \n     </tag6> \n    </tag> \n</tags>\n    ";\nvar xml = XDocument.Parse(data);\n\n    var classes = xml.Descendants( "tag1" )\n                     .Select( nd => new MyClass( nd ) );	0
19658477	19658405	How to execute a SHOW statement with OleDb, C#?	DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");\n\n           DataTable userTables = null;\n           using (DbConnection connection = factory.CreateConnection())\n           {\n\n               connection.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data  \n               Source=C:\test\testfile.accdb;Jet OLEDB:Database Password=yourrPassword;";\n\n                string[] restrictions = new string[4];\n                restrictions[3] = "Table";\n\n                connection.Open();\n\n                // Get list of user tables\n                userTables = connection.GetSchema("Tables", restrictions);\n\n\n                foreach (DataRow item in userTables.Rows) // You can use simple \n                                                          //looping to retreive the table Name\n                {\n\n\n\n                }\n            }	0
159042	158986	How to relate objects from multiple contexts using the Entity Framework	void MyFunction()\n{\n    using (TCPSEntities model = new TCPSEntities())\n    {\n        EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);\n        er.Roles = GetDefaultRole(model);\n        model.SaveChanges();\n     }\n\n}\n\nprivate static Roles GetDefaultRole(TCPSEntities model)\n{\n    Roles r = null;\n    r = model.Roles.First(p => p.RoleId == 1);\n    return r;\n}	0
9436162	8421242	Custom display dynamic data in WebGrid using MVC3	grid1.Column(columnName : "Process_ID",format:(item.Process_ID == 26)?"<text>Hi</text>":"<text>Bye</text>"}),	0
6335300	6333090	Deal with '#' through regex	(^|[^0-9A-Z&/]+)(#|\uFF03)([0-9A-Z_]*[A-Z_]+[a-z0-9_\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff]*)	0
9722426	9722384	More efficient use of an XMLReader	var xDocument = XDocument.Load(filePath);\nfor (i = 0; i < loopsNeeded; i++)\n{\n  ...  \n  var reader = xDocument.CreateReader();\n  ...\n}	0
32700070	32662592	Setting printer Share name programatically	string query = String.Format("SELECT * FROM Win32_Printer WHERE Name = '{0}'", printerName);\nManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\nManagementObjectCollection collection = searcher.Get();\nManagementObject printer = collection.Cast<ManagementObject>().ElementAt(0);\n\n// The part that changes the printer share name\nprinter.Properties["ShareName"].Value = newName;\nprinter.Put();	0
31079785	31079633	ActionLink inside an if statement inside a webgrid	grid.Column( header: "File",\n     format:(item) => (item.personfile != null)\n     ? Html.ActionLink("Download file", "downloadFile", "Person", new { id = item.id })\n     : Html.Raw("No File Found"))	0
4454228	4453851	WinForms, DataGridView: Filtering XML data using attributes from multiple nodes	DataView firstDataView = new DataView(dataSet.Tables["FirstLevel"]);\n        firstDataView.RowFilter = "Id = 1";\n\n\n        DataView secondDataView  = firstDataView[0].CreateChildView("FirstLevel_SecondLevel");\n        secondDataView.RowFilter = "Id = 2";\n\n        DataView thirdDataView = secondDataView[0].CreateChildView("SecondLevel_ThirdLevel");\n        DataView dataElement = thirdDataView[0].CreateChildView("ThirdLevel_DataElement");\n\n\n\n        BindingSource source = new BindingSource();\n\n        source.DataSource = dataElement;\n\n        dataGridView1.DataSource = source;	0
19032375	19029944	WrapGrid in ListView (without xaml) with C#	ItemsPanelTemplate template=new ItemsPanelTemplate();\nvar str = "<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" \n     +"<WrapGrid Orientation=\"Horizontal\" />" \n     +"</ItemsPanelTemplate>";\nItemsPanelTemplate panelTemplate = (ItemsPanelTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(str);\n\nListView listView=new ListView();    \nlistView.ItemsPanel = panelTemplate ;	0
10714544	10657533	how can be added Mediaelement in WPF in windows form	private void Form1_Load(object sender, EventArgs e)\n{\n    // Create the ElementHost control for hosting the\n    // WPF UserControl.\n    ElementHost host = new ElementHost();\n    host.Dock = DockStyle.Fill;\n\n    // Create the WPF UserControl.\n    HostingWpfUserControlInWf.UserControl1 uc =\n        new HostingWpfUserControlInWf.UserControl1();\n\n    // Assign the WPF UserControl to the ElementHost control's\n    // Child property.\n    host.Child = uc;\n\n    // Add the ElementHost control to the form's\n    // collection of child controls.\n    this.Controls.Add(host);\n}	0
30724733	30724499	How to apply a style of a Button dynamically in WP 8.1?	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n    if (value is bool && (bool)value)\n    {\n        return App.Current.Resources["ComplexProductTypeTemplate"];\n    }\n    return App.Current.Resources["SimpleProductTypeTemplate"];\n}	0
32056254	32056154	C# Regex Capture Substring Without Whitespace	var result = new Regex(@"\D").Replace(phoneStr, string.Empty);	0
5866557	5866391	Populating combobox with XML attribute?	XmlDocument doc = new XmlDocument();\ndoc.Load("abc.xml");\nXmlNodeList colorList = doc.SelectNodes("config/dataSources/dataSource");\nforeach (XmlNode dataSources in colorList)\n{\n    comboBox1.Items.Add(dataSources.Attributes["name"].Value.ToString());\n}	0
13609546	13609238	Filling a List with Objects in C#	private void button1_Click(object sender, EventArgs e)\n{\n    if (radioButton1.Checked == true)\n    {\n        objList1 = loadList();\n        Form2 f2 = new Form2();\n\n        for (int i = 0; i < objList1.Count; i++)\n        {\n            if (objList1[i] is UniversityStudents)\n            {\n                UniversityStudents uStudents = (UniversityStudents)objList1[i];\n\n                if (uStudents != null)\n                {\n                    // do stuff\n                }\n                else\n                {\n                    // do something sensible with the error here\n                }\n            }\n            // if clauses for the other "people" objects\n            // ...\n        }\n        f2.FormClosed += new FormClosedEventHandler(childFormClosed);\n        f2.Show();\n        this.Hide();\n    }\n}	0
4835916	4835808	How to read and write value from registry in Windows CE?	//using Microsoft.Win32;\n\nRegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WJST\WLAN", true); \n\n// set value of "CDInsert" to 1\nreg.SetValue("CDInsert", 1, RegistryValueKind.DWord);\n\n// get value of "CDInsert"; return 0 if value not found\nint value = (int)reg.GetValue("CDInsert", 0);	0
5248985	5238834	iSeries stored procedure calling RPG program doesn't return a value to the program	CREATE PROCEDURE "MPRLIB"."CHECKHOURS" (EMPLOYEEID DECIMAL(10 , 0), \n    INOUT ISMATCH CHAR(1))\n    LANGUAGE RPGLE\n    PARAMETER STYLE GENERAL\n    NOT DETERMINISTIC\n    MODIFIES SQL DATA \n    SPECIFIC CHECKHOURS \n    NEW SAVEPOINT LEVEL\n    EXTERNAL NAME 'MPRLIB/MPRLRCHK';	0
18004568	18003960	Auto scroll to the end of a Textblock in WPF	Window x:Class="textboxscrolltest.MainWindow"\n    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n    Title="MainWindow" Height="350" Width="525">\n    <Grid>\n        <TextBox Width="75" Height="25"/>\n    </Grid>\n</Window>	0
17722234	17721669	Getting property names of a class using expressions, static methods, and a base object	public class BaseClass<T> {\n    public static string GetPropertyName<P>(Expression<Func<T, P>> action) {\n        MemberExpression expression = action.Body as MemberExpression;\n        return expression.Member.Name;\n    }\n}\n\npublic class ClassOne : BaseClass<ClassOne> {\n    public string PropertyOne { get; set; }\n}\npublic static class Test {\n    public static void test() {\n        var displayMember = ClassOne.GetPropertyName(x => x.PropertyOne);\n    }\n}	0
5203029	5203010	get column names to array	var columnNames = myDataTable.Columns.\n         Cast<DataColumn>().\n         Select(c => c.ColumnName).\n         ToArray();	0
32252670	32252280	Most efficient way to update list items with Entity Framework	foreach(var record in profile.EmailRecords)\n{\n    record.IsPrimary = record.EmailRecordId == recordId;\n}	0
33636119	33635852	How do I convert a weakly typed ICollection into an F# List?	let somecoll = ... // Assuming somecoll is ICollection of something\nlet whatever = somecoll \n               |> Seq.cast // Getting F# Seq\n               |> List.ofSeq // or Array.ofSeq	0
8932968	8170236	How to set "run only if logged in" and "run as" with TaskScheduler in C#?	// Create a new task definition and assign properties\nTaskDefinition td = ts.NewTask();\n\ntd.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\ntd.Principal.	0
1159552	1159517	Regex that allows special chars?	Regex.IsMatch(Password, "^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$")	0
4043674	4043527	Need code for addition of 2 numbers	public static string CombineNumbers(string number1, string number2)\n    {\n        int length = number1.Length > number2.Length ? number1.Length : number2.Length;\n        string returnValue = string.Empty;\n\n        for (int i = 0; i < length; i++)\n        {\n            int n1 = i >= number1.Length ? 0 : int.Parse(number1.Substring(i,1));\n            int n2 = i >= number2.Length ? 0 : int.Parse(number2.Substring(i,1));\n            int sum = n1 + n2;\n\n            returnValue += sum < 10 ? sum : sum - 10;\n        }\n        return returnValue;\n    }	0
1645258	1645222	Should a Repository be responsible for "flattening" a domain?	interface CatalogRepository\n{\n    Catalog FindByID(int ID);\n}\n\ninterface CatalogImageRepository\n{\n    CatalogImage FindByID(int ID);\n}	0
10601048	10600775	Calculate coefficient to get normal speed animation	var duration = TimeSpan.FromSeconds((thisHeight - contentControlHeight) / pixelPerSecondSpeed);	0
19027370	19027276	Using Access Database to display text	OleDbDataAdapter da = new OleDbDataAdapter("Select * from Table1 Where <field> = <value>", con);	0
14791615	14791597	Returning an object from a LINQ query without casting it to a list	public IQueryable<Post> GetPostByID(int id)\n {\n        return (from p in _context.Posts\n                       where p.Id == id\n                       select p);\n }	0
10276125	10276070	Compare only DATE in a DATETIME field from ASP.NET code	CONVERT(DATE,GETDATE())	0
10065375	10065361	is it possible to build and new a structure in a loop?	List<Node> nodes = new List<Node>();\nfor (int i = 0; i < 1024; i++)\n{\n    nodes.Add(new Node(i.ToString()));    \n}	0
10286312	10286252	Format string with regex in c#	Regex.Replace(input, @"(\w{4})(\w{4})(\w{4})", @"$1-$2-$3");	0
6625984	6625881	object oriented: is it possible use a static instance like a variable?	public class CustomClass : UiUtils	0
20310389	20310369	Declare a delegate type in Typescript	interface Greeter {\n    (message: string): void;\n}\n\nfunction sayHi(greeter: Greeter) {\n    greeter('Hello!');\n}\n\nsayHi((msg) => console.log(msg)); // msg is inferred as string	0
8835034	8834977	My button needs two clicks instead of one	Application.DoEvents();	0
2789642	2789450	Can Events be declared as Static, if yes how and why	public class MyClass\n{\n    public static event EventHandler MyEvent;\n\n    private static void RaiseEvent()\n    {\n        var handler = MyEvent;\n        if (handler != null)\n            handler(typeof(MyClass), EventArgs.Empty);\n    }\n}	0
25027254	24965742	Override X-UA-Compatible setting in web.config for specific pages and frames	Response.ClearHeaders();\nResponse.AddHeader("X-UA-Compatible", "IE=5");	0
17662109	17661333	WP8 Change the color behind the application bar	private void panoramaMain_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n    Panorama p = (Panorama) sender;\n    if(p.SelectedIndex == 1) {\n       messageList.Margin = new Thickness(0, 0, 0, ApplicationBar.DefaultSize);\n       ApplicationBar.IsVisible = true;\n    } else {\n       messageList.Margin = new Thickness(0, 0, 0, 0);\n       ApplicationBar.IsVisible = false;\n    }\n }	0
13321308	13321285	Get the Substring of a List in C#	DateTime.Parse("2012-11-14T19:05:00").ToString("HH:mm:ss");	0
30430142	30430003	Loop Mutliple JSON objects to get multiple values	foreach (var element in facebook["posts"]["data"])\n{\n    message = element["message"];\n    image = element["image"];\n    //etc\n}	0
20931515	20931327	Reverse any group of numbers in a string	var replacedString = \nRegex.Replace(//finds all matches and replaces them\nmyString, //string we're working with\n@"\d+", //the regular expression to match to do a replace\nm => new string(m.Value.Reverse().ToArray())); //a Lambda expression which\n    //is cast to the MatchEvaluator delegate, so once the match is found, it  \n    //is replaced with the output of this method.	0
21758775	21746183	Switch from databases using the same Context in SQL Server Express 2012 using EF 6.0	public public class MyContext: Database02\n{\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        base.OnModelCreating(modelBuilder);\n\n        modelBuilder.Entity<Client01>().ToTable("Client02");\n    }\n\n    // This static method was missing, it is required to disable the db initializer\n    static MyContext()\n    {\n        Database.SetInitializer<MyContext>(null);\n    }	0
25871243	25870914	how to data bind to dropdownlist when checkbox is checked in asp.net	page_load\n{\n    if(checkbox1.checked)\n    {\n        dropdown.dataitems = items1;\n        dropdown.databind();\n        return;\n    }\n\n    if(checkbox2.checked)\n    {\n        dropdown.dataitems = items2;\n        dropdown.databind();\n        return;\n    }\n\n}	0
11590717	11574002	Upon opening a new instance of a form, a file that should be read, is not	else {}	0
16202541	16202409	Use folder instead of drive letter designation in path	string mapping = null;\n\nvar searcher = new ManagementObjectSearcher("root\\cimv2", "select Caption,ProviderName from Win32_MappedLogicalDisk");\nforeach (ManagementObject drive in searcher.Get())\n{\n    if (drive["Caption"].ToString() == driveLetter)\n    {\n        mapping = drive["ProviderName"].ToString();\n        break;\n    }\n}	0
1849605	1849576	Validate date without using validators?	DateTime dt;\nbool isValid = DateTime.TryParse("03/__/____", out dt); // returns false	0
11824544	11824443	How do I clear the selection of a selected node in a TreeView?	myTreeView.SelectedNode = null;//will deselect it	0
27724413	27723415	How do i get the location of a control with respect to other control	Rectangle PB2Screen = pictureBox2.RectangleToScreen(pictureBox2.ClientRectangle);\n        Rectangle PB2RelativeToPB1 = pictureBox1.RectangleToClient(PB2Screen);\n        Console.WriteLine("pictureBox2 Location Relative to pictureBox1: " + PB2RelativeToPB1.Location.ToString());\n        Console.WriteLine("PB2RelativeToPB1: " + PB2RelativeToPB1.ToString());	0
23840494	23840013	Setting screen size in PhantomJS C# being driven by Selenium	var driverService = PhantomJSDriverService.CreateDefaultService();\ndriverService.HideCommandPromptWindow = true;\ndriverService.LoadImages = false;\ndriverService.ProxyType = "none";\n\nusing (var driver = new PhantomJSDriver(driverService)) {\n    driver.Manage().Window.Size = new Size(1920, 1080); // Size is a type in assembly "System.Drawing"\n    driver.Url = "http://www.stackoverflow.com";\n    driver.TakeScreenshot().SaveAsFile(@"c:\phantomjs_screenshot.png", ImageFormat.Png);\n}	0
30756094	30755956	Starting process from .NET app and Attachment Execution Service	var vlcArgs = string.Format("\"{0}\" --config=\"{1}\" -Incurse --play-and-exit",\n   videoFilePath, vlcConfigPath);\n\nvar psi = new ProcessStartInfo(@"vlc\vlc.exe", vlcArgs);\npsi.UseShellExecute = false;\nVlcProcess = Process.Start(psi);	0
1291863	1291855	Output 2 Fields from Linq Group By	var grps = \n    from emp in Emps\n    group emp by new \n    { \n        GroupID = emp.WorkGroup.GroupID, \n        GroupTitle = emp.WorkGroup.GroupTitle \n    } into g\n    select new \n    { \n        GroupID = g.Key.GroupID, \n        GroupTitle = g.Key.GroupTitle,  \n        Employees = g\n    };	0
16970222	16970052	How do I access the assembly version and name from inside the assembly/WCF service?	return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version	0
8173717	4577944	How to resize WPF DataGrid to fit its content?	SizeToContent="WidthAndHeight"	0
23403526	23399766	How can I store the value of a MySqlCommand in C# to a local variable?	public void WhoLogIn()\n    {\n        _con.Open();\n        MySqlCommand NewCommand = new MySqlCommand("select titleandfullname from users where username ='" + Variables.whologin + "';", _con);\n        //Variables.whologin is a public const string in a class declared in another file.\n        MySqlDataReader result;\n        result = NewCommand.ExecuteReader();\n        string _nameofwhologin;\n\n        while (result.Read())\n        {\n            _nameofwhologin = result.GetString(0);\n        }\n        label2.Text=_nameofwhologin;\n\n    }	0
8256746	8256716	Override a member inherited?	public new string Name\n{\n     get;\n     private set;\n}	0
29034461	28998728	Null binding from POST request body	{"AccountType": "abcdf","AccountKey": "1234567"} \n{"accounttype": "abcdf","accountkey": "1234567"} \n{accounttype: "abcdf",accountkey: "1234567"}	0
13471990	13471543	Wrong result in string comparision in linq	var result = (from Roaster_RequestStatus status in statuses\n                        where status.StatusName.Contains("Draft")\n                        select status).ToList<Roaster_RequestStatus>();	0
15474595	15474475	Linq for sum of distinct addresses	var query = \n    from p in table.AsEnumerable()\n    group p by new {\n         Address1 = p.Field<string>("address1"),\n         Address2 = p.Field<string>("address2"),\n         Address3 = p.Field<string>("address3"),\n         City = p.Field<string>("city"),\n         State = p.Field<string>("state"),\n         Postcode = p.Field<string>("postcode"),\n         Country = p.Field<string>("country")\n    } into g\n    select new { \n        Address = g.Key, \n        TotalWeight = g.Sum(x => x.Field<int>("weight"))\n    };	0
24741400	24724977	How to notify a ViewModel when a new value is assigned to a member in another ViewModel?	class ViewModel1\n{\n    private ViewModel2 model2;\n\n    private double _id;\n    public double Id \n    {\n        get { return _id; }\n        set\n        {\n           _id= value;\n           model2.Modify();           \n        }\n    }\n}	0
28412289	28412235	Add number to the ending of a numerical date value in C#	long.Parse(DateTime.Now.ToString("yyyyMMdd")+ID.ToString());	0
33321304	33321026	Update thermostat result from api every 10 seconds in a C# console application	public static void Main() \n{  \n   System.Threading.Timer t = new System.Threading.Timer(UpdateThermostat, 5, 0, 2000); //10 times 1000 miliseconds\n   Console.ReadLine();\n   t.Dispose(); // dispose the timer\n}\n\n\nprivate static void UpdateThermostat(Object state) \n{ \n   // your code to get your thermostat\n   //option one to print on the same line:\n   //move the cursor to the beginning of the line before printing:\n    Console.SetCursorPosition(0, Console.CursorTop);\n    Console.Write(DateTime.Now);\n\n   //option two to print on the same line:\n   //printing "\r" moves cursor back to the beginning of the line so it's a trick:\n    Console.Write("\r{0}",DateTime.Now);\n}	0
12008938	9812128	How do I grab an Image or bitmap from the android camera using c#	protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\n{\n    if (resultCode == Result.Ok && requestCode == 1001)\n    {\n        Android.Net.Uri _currentImageUri = Android.Net.Uri.Parse(_imageUri);\n        Bitmap bitmap = BitmapFactory.DecodeStream(ContentResolver.OpenInputStream(_currentImageUri));\n\n        byte[] bitmapData = null;\n\n        using (MemoryStream stream = new MemoryStream())\n        {\n            bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);\n            bitmapData = stream.ToArray();\n        }\n\n        bitmap.Dispose();\n    }\n}	0
10029262	10022901	Server refuses to accept requests from clients	public void Run()\n{\n     byte[] data;\n     try\n     {\n        using (var r = new StreamReader("c:/myfile2.txt"))\n        {\n            string line ="";\n            int lineNumber = 0;\n            while (null != (line = r.ReadLine()))\n            {\n                data = Encoding.ASCII.GetBytes(line + "\n");\n                _client.Client.Send(data, data.Length, SocketFlags.None);\n            }\n        }\n     }\n     catch (Exception ex)\n     {\n         Console.Error.WriteLine(ex.ToString());\n     }\n     Console.WriteLine("Closing client");\n     _client.Close();\n}	0
18117133	18116988	How would I add a parameter to entity framework raw sql command	context.Database.ExecuteSqlCommand(@"UPDATE dbo.Customers \n            SET Name = 'Test' WHERE Id = @Id", new SqlParameter("Id", 1));	0
427026	427022	How to determine width of a string when printed?	private void MeasureStringMin(PaintEventArgs e)\n{\n\n    // Set up string.\n    string measureString = "Measure String";\n    Font stringFont = new Font("Arial", 16);\n\n    // Measure string.\n    SizeF stringSize = new SizeF();\n    stringSize = e.Graphics.MeasureString(measureString, stringFont);\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
28277546	28273736	Manually set the properties of new objects created from datagridview	public partial class Office\n{\n   public Office()\n   {\n        guid=Guid.newGuid();\n   }\n}	0
6712171	6712109	Escape string from file	Regex.Unescape(string)	0
3296115	3222840	How to show application version in VS.NET Deployment Project?	The installer will guide you through the steps required to install [ProductName] [ProductVersion] on your computer.	0
31472421	31472058	How to use for loop to update buttons' properties to make the code less duplicated	ToggleButton[] btnArray = new ToggleButton[] {b1, b2, b3};\n\n\n  private void btn1_Click_1(object sender, RoutedEventArgs e)\n    {\n        foreach (ToggleButton item in btnArray)\n        {\n            item.FontWeight = FontWeights.Normal;\n        }\n        ToggleButton tb = sender as ToggleButton;\n        tb.FontWeight = FontWeights.Bold;\n    }	0
18155762	18155731	convert string to int with losing everything but digits	int b = int.Parse(new string(a.Where(char.IsDigit).ToArray()));	0
18808651	18808544	Run a C# program to launch another C# program in mono	Process.Start("mono", "full_path_of_your_exe");	0
34056384	34056160	C# How to adding each element from an array to sub-Node in XML tree?	List<String> list = {"abc","cba","bca"}; \nNameList.Add(new XElement("movie", new XElement("title", this.textBox1.Text), list.Select(l => new XElement("genre", l))));	0
23893511	23893375	Get the focused window name	[DllImport("user32.dll")]\npublic static extern IntPtr GetForegroundWindow();\n\n[DllImport("user32.dll")]\npublic static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);\n\n[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]\npublic static extern int GetWindowTextLength(IntPtr hWnd);\n\nprivate static bool IsFocused(string name)\n{\n    var handle = GetForegroundWindow();\n    var length = GetWindowTextLength(handle);\n    var builder = new StringBuilder(length + 1);\n\n    GetWindowText(handle, builder, (IntPtr)builder.Capacity);\n\n    return builder.ToString() == name;\n}	0
25767849	25767690	Why does Intellisense show a variable as an option on the right side of its declaration?	static class Program {\n  static int f(out int i) {\n    return i = 0;\n  }\n  static void Main() {\n    int i = f(out i); // okay\n  }\n  static int j = j; // okay\n}	0
6253088	6252981	C# Xml Value always getting null	var XmlDoc = new XmlDocument();\nvar nsmgr = new XmlNamespaceManager(XmlDoc.NameTable);\nnsmgr.AddNamespace("x", "http://DFISofft.com/SmartPayments/");\nXmlDoc.LoadXml(yourXml);\nXmlElement NodePath = (XmlElement)XmlDoc.SelectSingleNode("/x:Response", nsmgr);	0
9651631	9625797	SharePoint 2010: How to extract personalized web part property for all users	const string absolutePageUrl = "http://spsite:5000/Pages/SomePage.aspx";\n\nforeach (SPUser user in SPContext.Current.Site.RootWeb.AllUsers.Cast<SPUser>())\n{\n    if (!user.LoginName.StartsWith("DOMAIN NAME"))\n        continue;\n\n    using (SPSite site = new SPSite(absolutePageUrl, user.UserToken))\n    using (SPWeb web = site.OpenWeb())\n    {\n        var mgr = web.GetLimitedWebPartManager(absolutePageUrl, PersonalizationScope.User);\n        var webPart = mgr.WebParts.OfType<MyWebPart>().FirstOrDefault();\n        var prop = webPart.CustomProp;\n    }\n}	0
10920000	10919887	How can I combine these two similar methods into one?	private void ListFixup(object entity, List<Item> addList, List<Item> removeList)\n{\n    LabEntity selectedItem = entity as LabEntity;\n    // don't forget your error checking here\n\n    addList.Add(selectedItem);\n    removeList.Remove(selectedItem);\n}\n\nprivate void btnAdd_Click(object sender, EventArgs e)\n{\n    ListFixup(bindingSource1.Current, selectedLabsData, availableLabsData);\n}\n\nprivate void btnRemove_Click(object sender, EventArgs e)\n{\n    ListFixup(bindingSource2.Current, availableLabsData, selectedLabsData);\n}	0
10532894	10532858	Accessing the Name attribute of an object	var type = (Type)myField["DataType"];\nConsole.WriteLine("type = " + type.Name);	0
3515348	3515338	Why my IEnumerable of dates doesn't contains my date	HolidayDates.Contains(dateTime.Date)	0
29237023	29237022	Why can't Windows 7 extract files from my password protected zip-file created using DotNetZip?	zipFile.Encryption = EncryptionAlgorithm.PkzipWeak;	0
5893097	5884642	How to create a zip file using encoded string in C#	private static void CreateZipFromText(string text)\n    {            \n        byte[] byteArray = ASCIIEncoding.ASCII.GetBytes(text);\n        string encodedText = Convert.ToBase64String(byteArray);\n\n        FileStream destFile = File.Create("C:\\temp\\testCreated.zip");\n\n        byte[] buffer = Encoding.UTF8.GetBytes(encodedText);\n        MemoryStream memoryStream = new MemoryStream();\n\n        using (System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(destFile, System.IO.Compression.CompressionMode.Compress, true))\n        {\n            gZipStream.Write(buffer, 0, buffer.Length);\n        }\n    }	0
23681597	23681224	Custom and Razor view engine mess while combining the two	protected override bool FileExists(ControllerContext controllerContext, string virtualPath)\n        {\n            try\n            {\n                return !virtualPath.EndsWith("cshtml") &&\n                    File.Exists(controllerContext.HttpContext.Server.MapPath(virtualPath));\n            }\n            catch (HttpException exception)\n            {\n                if (exception.GetHttpCode() != 0x194)\n                {\n                    throw;\n                }\n                return false;\n            }\n            catch\n            {\n                return false;\n            }\n        }	0
5903275	5903050	how to search a list for items with a distance lower than F to P without searching the entire list?	The List\n1: (0,1)\n2: (0,2)\n3: (1,0)\n4: (1,1)\n5: (2,1)\n6: (2,3)\n7: (3,1)\n8: (3,5)\n9: (4,2)\n10: (4,5)\n11: (5,1)\n12: (5,2)\n13: (6,1)\n14: (6,2)\n15: (6,3)\n16: (7,1) \n17: (7,2)   \n\nStart Locations\n(0,1)\n(1,3)\n(2,5)\n(3,7)\n(4,9)\n(5,11)\n(6,13)\n(7,16)	0
13058759	13044964	Installing client certificates in Windows Store XAML apps	StorageFolder packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;\nStorageFolder certificateFolder = await packageLocation.GetFolderAsync("Certificates");\nStorageFile certificate = await certificateFolder.GetFileAsync("YourCert.pfx");\n\nIBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(certificate);\nstring encodedString = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);	0
2593218	2593168	C# Combining lines	string[] configLines = File.ReadAllLines("a.txt");\nvar dataLines = from line in File.ReadAllLines("b.txt")\n                let split = line.Split('|')\n                select new { Key = split[0], Value = split[1] };\nvar lookup = dataLines.ToLookup(x => x.Key, x => x.Value);\n\nusing (TextWriter writer = File.CreateText("result.txt"))\n{\n    foreach (string key in configLines)\n    {\n        string[] values = lookup[key].ToArray();\n        if (values.Length > 0)\n        {\n            writer.WriteLine("{0}|{1}", key, string.Join("|", values));\n        }\n    }\n}	0
26805953	26805914	Checking if item is in ConcurrentDictionary without getting back the value	var dict = new ConcurrentDictionary<string, string>();\n\n        if (dict.ContainsKey("KEY"))\n        {\n            //do some work\n        }\n        else\n        {\n            dict["KEY"] = "VALUE";\n        }	0
14264601	14264450	Unable to read HttpResponse from HTTPS	public static void HttpsRequest(string address)\n{\n  string data;\n   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);\n   request.Method = "GET";\n\n   using (WebResponse response = request.GetResponse())\n  {\n    using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n    {\n        data = reader.ReadToEnd();\n    }\n  }\n}	0
24137374	24137290	How to check if first character of a string is a letter c#	string str = " I am a string";\nbool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);	0
34398888	34398441	Show data from Entity Framework into DataGridView	Context db = new Context();\nvar data = (from d in db.tablename select d);\ndataGridView1.DataSource = data.ToList();	0
25055261	25055233	Passing a DataValueField of a nested Drop Down List to an Update SQL command	priorityLanguage_DDL.DataValueField	0
32183942	32183632	How to bind ListBox ItemsSource to a ViewModel property (which is a Collection) programmatically?	myListBox.ItemsSource = myListName;	0
27793570	27792849	Get MethodInfo for a lambda expression	MethodInfo meth = (new Func<int, string>(i => i.ToString())).Method;	0
14095680	14095614	How to deserialize JSON array of objects to c# structure	public class HtmlItem\n{\n   [DataMember(Name = "html")]\n   public string Html { get; set; }\n}\n\nJavaScriptSerializer ser = new JavaScriptSerializer();          \n\n// Serialize\nstring html = ser.Serialize(new List<HtmlItem> {\n   new HtmlItem {  Html = "foo" },\n   new HtmlItem {  Html = "bar" }\n});\n\n// Deserialize and print the html items.        \nList<HtmlItem> htmlList = ser.Deserialize<List<HtmlItem>>(html);\nhtmlList.ForEach((item) => Console.WriteLine(item.Html)); // foo bar	0
1901147	1900886	Add text in textbox that will show only when clicked	RichTextBox.LinkClicked	0
20675735	20673958	How to pass a reference of a class to a function inside of a different class in C#/XNA/monogame?	Public Class Ant\n   public position as vector2\n   public health as integer = 100\n   public isdead ad boolean = false\nEnd class\n\nPublic Class Ants\n   Inherit list (of Ant)\n\n   Public Sub AddAnt(Position)\n   // add new ant to list\n   End Sub\n\n   Public Sub Update()\n    For Each ant As ant In ants\n      If Not(ant.isdead)\n        // update ants\n      End If\n    Next\n\n    Me.RemoveAll(function(c) c.isdead = true)\n\n   End Sub\n\n   Public Sub Draw()\n     For Each ant As ant In ants\n      If not(ant.isdead)\n        // draw ants\n      End If        \n     Next\n   End Sub\n\nEnd class	0
29791276	29791158	Assign values to another position	//You would want to create a custom Player class to store this data as it looks silly here but:\n        string[] objectNames = { "player1", "player2", "player3", "player4" };\n        int[] objectPositionX = { 5, 10, 15, 20 };\n        int[] objectPositionY = { 50, 60, 70, 70 };\n        for (int i = 0; i < objectNames.Length; i++)\n        {\n            //An example of this use would be teleporting a player to another player? Say player 2 to player 4's location.\n            if(objectNames[i] == "player2")\n            {\n                objectPositionX[i] = objectPositionX[3];\n                objectPositionY[i] = objectPositionY[3];\n            }\n        }\n\n        //I'm only taking a stab at what you want as the question was a tad vague. But hope this helps.	0
24547004	24450099	REST seems to reject JSON POST	if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)\n        {\n            if (PostData.Substring(0, 1) != "<")\n                request.ContentType = "application/json";\n            Console.WriteLine("Content type is " + request.ContentType.ToString());\n            request.ContentLength = PostData.Length;\n            using (var postStream = new StreamWriter(request.GetRequestStream()))\n            {\n                postStream.Write(PostData);\n            }\n        }	0
26113391	26112053	Ways to perform a sort for multiple data	' Example products defined as anonymous types\nDim products() = { _\n    New With { Key .Id=759504, .Name="Nike Shoes", .Price=75.5, .Date=#9/29/2014# }, _\n    New With { Key .Id=759505, .Name="Puma Shoes", .Price=69.9, .Date=#9/30/2014# } _\n}\n\n' Sort by id ascending\nDim byId = products.OrderBy(Function(product) product.Id)                 \n' Sort by price descending\nDim byPrice = products.OrderByDescending(Function(product) product.Price)	0
12012508	12012447	how to use SET and COPY in CMD?	process1.StartInfo.Arguments = "copy /b \"" + fi.Name + "\" test.txt";	0
17996271	17994030	Active Directory Underlying Searcher Group Attributes from AccountManagement.Principal	public static class AccountManagementExtensions\n    {\n        public static String GetProperty(this Principal principal, String property)\n        {\n            var directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;\n            return directoryEntry != null && directoryEntry.Properties.Contains(property)\n                       ? directoryEntry.Properties[property].Value.ToString()\n                       : String.Empty;\n        }\n\n        public static String GetCompany(this Principal principal)\n        {\n            return principal.GetProperty("company");\n        }\n\n        public static String GetDepartment(this Principal principal)\n        {\n            return principal.GetProperty("department");\n        }\n    }	0
10089948	10089923	Fill List<> from XML respond	item.Element("locationid").Element("city").Value	0
15431375	15364436	SemWeb - Convert C# object into RDF triples	store.Add( new Statement( subject, predicate, object )	0
8222065	8222035	How can I make it so my field is only set the one time?	private DateTime? created;\npublic DateTime? Created \n{\n    get { return created; }\n    set { if (created == null) created = value; }\n}	0
24418577	24405180	Starting the Bluetooth controller on Windows CE programmatically	var r = BluetoothRadio.PrimaryRadio;\nif (r == null) { blahhhhh....; return; }\nr.Mode = RadioMode.Connectable;	0
1807306	1807285	ODP ADO.NET driver returns decimal with extra zero in string representation	decimal trimmed = ((decimal)((int)(number * 1000))) / 1000	0
4022379	4019831	How do you center your main window in WPF?	private void CenterWindowOnScreen()\n    {\n        double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;\n        double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;\n        double windowWidth = this.Width;\n        double windowHeight = this.Height;\n        this.Left = (screenWidth / 2) - (windowWidth / 2);\n        this.Top = (screenHeight / 2) - (windowHeight / 2);\n    }	0
27441330	27441138	Return result from another apicontroller	currentCategory = new CategoryController().Get(id);	0
2463857	2463021	How do I register a Javascript function to run with every postback?	function pageLoad(sender, args) {\n  Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);\n  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);\n}\n\nfunction beginRequest(sender, args) {\n        // begin request code - i.e. make a "processing" div visible\n}\n\nfunction endRequest(sender, args) {\n        // we are back\n        RestorePosition(); \n}	0
8009383	8007930	Designing a regular expression to exclude non-ASCII	if (!Regex.IsMatch(fieldValue, "[^\x20-\x7E]"))\n            return fieldValue;\n        else\n        {\n            return null;\n        }	0
16787800	16787605	Setting session variable in class that implements IHttpModule error	.ToString()	0
7696474	7696300	How to make the datagridview line text in bold when I pick a row?	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n  var dataGridView = sender as DataGridView;\n  if (dataGridView.Rows[e.RowIndex].Selected)\n  {\n    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);\n    // edit: to change the background color:\n    e.CellStyle.SelectionBackColor = Color.Coral;\n  }\n}	0
6771816	6771769	Refresh icon for button	myButton.Image = new Bitmap(pathToImageFile);	0
629109	629079	debugging with pointers in C#	class foo\n{\n  private static int counter;\n  private int instance_counter;\n\n  public Foo()\n  {\n    instance_counter = counter;\n    counter++;\n  }\n\n  public string toString()\n  {\n    return "Foo "+instance_counter.toString();\n  }\n}	0
3635731	3635659	how to delete a file?	File.Delete(@"C:\Documents and Settings\Vijay.EKO-03\Desktop\blockseek3-9-2010\Block3.xml");	0
26940896	26940813	Pass reflected method as parameter to another reflected method as delegate	miForFunkA.Invoke(sourceOfFunkA, new object[] {\n    methodInfo.Name,\n    Delegate.CreateDelegate(typeof(Action), miForFunkB)\n});	0
2550613	2550512	How to extract innermost table from html file with the help of the html agility pack?	var table = doc.DocumentNode.SelectSingleNode("//table [not(descendant::table) and tr[1]/td[normalize-space()='ADDRESS'] ]");	0
511791	511752	Fixing the position of a form	protected override void SetBoundsCore(\n             int x, int y, int width, int height, BoundsSpecified specified)\n    {\n        x = this.Location.X;\n        y = this.Location.Y;\n        //...etc...\n        base.SetBoundsCore(x, y, width, height, specified);\n    }	0
15668982	15668482	Read Excel all columns as string in C#	ApplicationClass app = new ApplicationClass();\napp.Visible = false;\napp.ScreenUpdating = false;\napp.DisplayAlerts = false;\n\nWorkbook book = app.Workbooks.Open(@"path\Book1.xls", \n    Missing.Value, Missing.Value, Missing.Value, \n    Missing.Value, Missing.Value, Missing.Value, Missing.Value, \n    Missing.Value, Missing.Value, Missing.Value, Missing.Value, \n    Missing.Value, Missing.Value, Missing.Value);\n\nWorksheet sheet = (Worksheet)book.Worksheets[1];\nRange range = sheet.get_Range(...);\n\nstring execPath = Path.GetDirectoryName(\n    Assembly.GetExecutingAssembly().CodeBase);\n\nobject[,] values = (object[,])range.Value2;\n\nfor (int i = 1; i <= values.GetLength(0); i++)\n{\n    for (int j = 1; j <= values.GetLength(1); j++)\n    {\n        string s = values[i, j].ToString();\n    }\n}	0
2956093	2955894	How to assert that a class has an inherited attribute, but excluding the parent class at the same time?	object[] attributes = typeof(MyTestClass).GetCustomAttributes(typeof(MigrationAttribute), true);\n  Assert.IsNotNull(attributes);\n  Assert.IsTrue(attributes.Any(x => x is TestDataMigrationAttribute));\n  Assert.IsFalse(attributes.Any(x => x is MigrationAttribute && !(x is TestDataMigrationAttribute)));	0
4948304	4948194	Using a combination of two fields as key in a dictionary	Dictionary<Tuple<IntPtr, YourEnum>, YourResultType>	0
31314924	31298291	How to improve MongoDB insert performance	await m_Collection.BulkWriteAsync(updates, new BulkWriteOptions() { IsOrdered = false });	0
13341430	13341184	From excel to datatables	for (int row = 0; row < xlRange.Rows.Count; row++)\n    {\n        DataRow dataRow = null;\n        if (row != 0) dataRow = excelTb.NewRow();\n\n        for (int col = 0; col < xlRange.Columns.Count; col++)\n        {\n            if (row == 0) //Headers\n            {\n                excelTb.Columns.Add(xlRange.Cells[row + 1, col + 1].Value2.ToString());\n            }\n            else //Data rows\n            {\n                dataRow[col] = xlRange.Cells[row + 1, col + 1].Value2.ToString();\n\n            }\n        }\n    }	0
2640127	2640104	Default Controller for an Area?	routes.MapRoute(\n    "Default2", // Route name\n    "TestArea/{controller}/{action}/{id}", // URL with parameters\n    new { controller = "Hello", action = "Index",area="TestArea",  id = UrlParameter.Optional } // Parameter defaults\n);\n\nroutes.MapRoute(\n    "Default", // Route name\n    "{controller}/{action}/{id}", // URL with parameters\n    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults\n);	0
18947773	18945939	How to get sound output device ID	for (int deviceId = 0; deviceId < WaveOut.DeviceCount; deviceId++)\n{\n    var capabilities = WaveOut.GetCapabilities(deviceId);\n    comboBoxWaveOutDevice.Items.Add(capabilities.ProductName);\n}	0
6134203	6122027	using vscrollbar to scroll a xtragrid	vScrollBar1.Maximum = gridView1.RowCount - gridView1.RowCount / 17;\n\n    private void vScrollBar1_ValueChanged(object sender, EventArgs e) \n    { \n        gridView1.TopRowIndex = vScrollBar1.Value; \n    } \n\n    private void gridView1_TopRowChanged(object sender, EventArgs e) \n    { \n       vScrollBar1.Value = gridView1.TopRowIndex;\n    } \n\n    gridView.MouseWheel += new MouseEventHandler(gridView1_TopRowChanged);	0
34284623	34275411	Error while authenticating an app with linkedin	var auth = new OAuth2Authenticator (\n                clientId: "**",\n                clientSecret:"**",\n                scope: "r_fullprofile r_contactinfo",\n                authorizeUrl: new Uri ("https://www.linkedin.com/uas/oauth2/authorization"),\n                redirectUrl: new Uri ("http://www.***.co.nz/"),\n                accessTokenUrl:new Uri("https://www.linkedin.com/uas/oauth2/accessToken")    \n            );	0
12816679	12816290	List of all items while adding a new item in VB.NET disappered	devenv /installvstemplates	0
13601038	13600855	Is there a more elegant way to sum multiple properties?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Demo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var test = new MyClass();\n            // ...\n            int sum = test.All().Sum();\n        }\n    }\n\n    public class MyClass\n    {\n        public int C1 { get; set; }\n        public int C2 { get; set; }\n        public int C3 { get; set; }\n        // ...\n        public int Cn { get; set; }\n\n        public IEnumerable<int> All()\n        {\n            yield return C1; \n            yield return C2; \n            yield return C3; \n            // ...\n            yield return Cn; \n        }\n    }\n}	0
2095069	1440597	How to get Dom tree in GeckoFX	GeckoElementCollection links = geckoWebBrowser1.Document.GetElementsByTagName("a");\nforeach (GeckoElement link in links) {\n    Debug.WriteLine(link.GetAttribute("href"));\n}	0
19241311	19241075	How to extract path after IP address?	string ftpAddress = "ftp://192.168.1.1/dir1/dir2/file.txt";\nRegex ip = new Regex(@"ftp://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");\nstring path1 = ip.Split(ftpAddress)[1];\nstring path2 = new Uri(ftpAddress).PathAndQuery;\nstring path3 = ftpAddress.Substring(ftpAddress.IndexOf("/", 6));	0
14800810	14800791	Combo boxes duplicate entries	if (!comboBox.Items.Contains(entry))\n    comboBox.Items.Add(entry);	0
10790127	10789662	In C# clear a UserControl on Unload event	protected override void OnLoad(EventArgs e) {\n          base.OnLoad(e);\n\n          if (_resetOnUnload) {\n                 divMessageBlock.InnerHtml = "";\n                 _resetOnUnload = false;\n          }\n   }\n\n   protected override void LoadViewState(object savedState) {\n          if (savedState != null) {\n                 object[] myState = (object[])savedState;\n                 _resetOnUnload = (bool)myState[0];\n          }\n   }\n\n   protected override object SaveViewState() {\n          object[] allStates = new object[]{ _resetOnUnload };\n          return allStates;\n   }	0
22501616	22499407	How to Display a Bitmap in a WPF Image	BitmapImage BitmapToImageSource(Bitmap bitmap)\n{\n    using (MemoryStream memory = new MemoryStream())\n    {\n        bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);\n        memory.Position = 0;\n        BitmapImage bitmapimage = new BitmapImage();\n        bitmapimage.BeginInit();\n        bitmapimage.StreamSource = memory;\n        bitmapimage.CacheOption = BitmapCacheOption.OnLoad;\n        bitmapimage.EndInit();\n\n        return bitmapimage;\n    }\n}	0
8951212	8951172	C#, using static with const	error CS0504: The constant 'FieldName.Field1' cannot be marked static	0
12582349	12580450	Which algorithm does CreditCardAttribute use for credit card number format validation	return num % 10 == 0;	0
6820122	6820088	insert object into comboBox	List<met>dyo = new List<met>(); dyo=DAL.metpa();\n    foreach(met t in dyo )\n    {\n        comboBox1.DataSource = d;\n        comboBox1.DisplayMember = "last_Name"\n        comboBox1.ValueMember = "id_Metp";\n\n    }	0
2937552	2937544	whats the shortest way of returning an Entity Framework object from one table based on it's name attribute?	context.People.First(m => m.Name == "Tim")	0
11397697	11391006	How to create a log file using selenium webdriver and C#?	// Assumes driver is a WebDriver instance that implements ITakesScreenshot\n// N.B., to be completely correct, you should check for a successful cast\n// by adding a null check for screenshotDriver.\nITakesScreenshot screenshotDriver = driver as ITakesScreenshot;\nScreenshot screenCapture = screenshotDriver.GetScreenshot();\nscreenCapture.SaveAsFile(screenShotDirectory + "\\" + "wrongUserNameAndPassword.png", \n    System.Drawing.Imaging.ImageFormat.Png);	0
30755488	30753588	Sort XML document based on grandchild	var doc = XDocument.Parse(xml);\n\nforeach (var round in doc.Descendants("round"))\n{\n    var sortedActions = round.Elements("action")\n        .OrderBy(e => (int)e.Attribute("no"))\n        .ToList();\n\n    sortedActions.Remove();\n    round.Add(sortedActions);\n}	0
18566167	18565675	How to get radio button checked value in Footer Template DataList?	foreach (DataListItem item in dlDelivery.Items)\n        {\n            if (item.ItemType == ListItemType.Footer)\n            {\n                RadioButton rdoOther = (RadioButton)item.FindControl("rdoOther");\n\n            }\n        }	0
30269109	30269056	Run function if value of variable is not in ignore list	HashSet<string> ignores = new HashSet<string>();\nignores.Add("ANameToIgnore");\nignores.Add("AnotherNameToIgnore");\n\nList<Variance> variancesList = new List<Variance>();\nPropertyInfo[] fieldList = saveModel.GetType().GetProperties();\nforeach (PropertyInfo field in fieldList)\n{\n    if (!ignores.Contains(field.Name))\n    {\n        Variance variance = new Variance();\n        variance.property = field.Name;\n        variance.saveValue = field.GetValue(saveModel, null);\n        variance.loadValue = field.GetValue(loadModel, null);\n        if (!Equals(variance.saveValue, variance.loadValue))\n            variancesList.Add(variance);\n    }\n}	0
14846047	14844980	Generating a URL independant of controllers in ASP.NET MVC 3	var request = new HttpRequest("/", "http://example.com", ""); //hopefully you can hardcode this or pull from config?\nvar response = new HttpResponse(new StringWriter());\nvar httpContext = new HttpContext(request, response);\n\nvar httpContextBase = new HttpContextWrapper(httpContext);\nvar routeData = new RouteData();\nvar requestContext = new RequestContext(httpContextBase, routeData);\n\nvar urlHelper = new UrlHelper(requestContext);\nvar url = urlHelper.Action("ActionName", "ControllerName");	0
31641199	31640846	How to detect if a class uses Linq using Roslyn?	SyntaxKind.QueryExpression	0
6440276	6440244	How to avoid last comma when implementing a collecion ToString	sb.Append("[");\nsb.Append(string.Join(\n    ", ",\n    DateSource.Select(r => string.Format("\"RowKey\" : {0}, \"RowData\" : {1}", r.Key, r.Value))));\nsb.Append("]");	0
15577341	15577306	How do I get the selected value from a stored procedure in C#?	command.ExecuteScalar()	0
3090419	3090311	Different application settings depending on configuration mode	copy "$(ProjectDir)properties\settings.settings.$(ConfigurationName).xml" "$(ProjectDir)properties\settings.settings"\ncopy "$(ProjectDir)properties\settings.designer.$(ConfigurationName).cs" "$(ProjectDir)properties\settings.Designer.cs"	0
26338313	26337400	Create object array in linq using a dynamic identifier	var finished = false;\n\n        List<GamePlay> res = new List<GamePlay>();\n        var currentUser = firstUser;\n        while (!finished)\n        {\n            var nextUser = getBiggestGiveSinceDate(currentUser, res, filterDate);\n            if (nextUser == null)\n            {\n                finished = true;\n            }\n            else\n            {\n                res.Add(nextUser);\n                currentUser = nextUser;\n            }\n        }	0
3179180	3178896	Editing child objects of a combo box using c# and Wpf	Image image = this.itemProductManufacture.ItemTemplate.FindName("itemManufactureImage", this) as Image;	0
794219	794198	How do I check if a given value is a generic list?	if(value is IList && value.GetType().IsGenericType) {\n\n}	0
5955683	5951126	Getting access to IsActive property in Sitecore	System.Web.Security.MembershipUser membershipuser = System.Web.Security.Membership.GetUser(username);	0
11749861	11749812	Write Rows from DataTable to Text File	sw.WriteLine(row["columnname"].ToString());	0
14287565	14287405	How to use a class	Vendor v = new Vendor(VendorID);	0
5412023	5411967	LINQ querying for multiple dates and counting rows	List<Order> ord = (from o in dc.Orders\n                               where o.OrderDate.Value.Year == 2011\n                               select o).ToList();\n\n            int Count = ord.Count;	0
490077	490061	C# String replacement using Regex	result = Regex.Replace(value.ToString().Substring(0, x), oldString, newString, RegexOptions.IgnoreCase);	0
13139516	13124784	Adding a simple header row in Google Spreadsheet API	CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink);\n        CellFeed cellFeed = _SpService.Query(cellQuery);\n\n        CellEntry cellEntry = new CellEntry(1, 1, "name");\n        cellFeed.Insert(cellEntry);\n        cellEntry = new CellEntry(1, 2, "age");\n        cellFeed.Insert(cellEntry);\n        cellEntry = new CellEntry(1, 3, "address");\n        cellFeed.Insert(cellEntry);	0
17248675	17244484	Launch App through SMS (URI-Association)	myapp:param=test	0
11509537	11509294	How we can access the rotation angle from matrix?	0.75329963	0
928156	928122	Using F1 Help (CHM format) With WPF	System.Diagnostics.Process.Start(@"C:\path-to-chm-file.chm");	0
14237403	14236888	Extract heading text from html text using c#	HtmlDocument doc = new HtmlDocument();\n  doc.LoadHtml(txtEditor.InnerText);\n  var h1Elements = doc.DocumentNode.Descendants("h1").Select(nd => nd.InnerText);\n  string h1Text = string.Join(" ", h1Elements);	0
4566167	4565866	Get file path from Visual Studio editor	DTE.ActiveDocument.Path + DTE.ActiveDocument.Name	0
8760233	8760176	access the value of minRequiredNonalphanumericCharacters in the membership config using c#	System.Web.Security.Membership.MinRequiredNonAlphanumericCharacters	0
8630473	8630420	C# : Storing set of non-overlapping ranges and finding whether a value is present in any one of the ranges strictly	public class Range : IComparable\n    {\n        public int start;\n        public int end;\n        public int CompareTo(object obj)\n        {\n            var result = obj as Range;\n            if (result == null)\n                return 1;\n            if (start > result.start)\n                return 1;\n            if (result.start >= start && result.end <= end)\n                return 0;\n            return -1;\n        }\n    }\n    public void findItemInRange(List<Range> ranges, int item)\n    {\n        // ranges.Sort(); I'll assume list is sorted\n        int positionOfItem = ranges.\n                            BinarySearch(new Range { start = item, end = item });\n    }	0
7576856	7576761	How to create objects using a static factory method?	void Main()\n{\n    using (var container = new UnityContainer())\n    {\n        container.RegisterType<IAuthoringRepository>(\n            new InjectionFactory(c => CreateAuthoringRepository()));\n\n        Console.WriteLine("debug - resolving model");\n        var model = container.Resolve<Model>();\n    }\n}\n\npublic IAuthoringRepository CreateAuthoringRepository()\n{\n    Console.WriteLine("debug - calling factory");\n    return new AuthoringRepository\n        { Identity = WindowsIdentity.GetCurrent() };\n}\n\npublic class Model\n{\n    public Model(IAuthoringRepository repository)\n    {\n        Console.WriteLine(\n            "Constructing model with repository identity of "\n            + repository.Identity);\n    }\n}\n\npublic interface IAuthoringRepository\n{\n    IIdentity Identity { get; }\n}\n\npublic class AuthoringRepository : IAuthoringRepository\n{\n    public IIdentity Identity { get; set; }\n}	0
8341510	8341051	Creating a JavascriptConverter for a Generic Type	using System.Linq;\n\n....\n\nvar concreteGenericTypes =\n    (from assembly in AppDomain.CurrentDomain.GetAssemblies()\n     from T in assembly.GetTypes()\n     where T.IsClass && T.GetConstructor(new Type[] { }) != null\n     select typeof(MyClass<>).MakeGenericType(T)).ToList();	0
31029369	31019422	How can I access to UI Text?	public Component[] GetComponentsInChildren(Type type, bool includeInactive = false);	0
23468601	23468188	Accessing resources like array's elements	for(int i = 0; i < 2; i++) \n{\n\n  pictureBox1.Image = (Image)Properties.Resources.ResourceManager.GetObject("Computer" + i);\n\n}	0
22667891	5845512	Prevent user from deselecting an item in a ListBox?	var listbox = ((ListBox)sender);\n        if (listbox.SelectedItem == null)\n        {\n            if (e.RemovedItems.Count > 0)\n            {\n                object itemToReselect = e.RemovedItems[0];\n                if (listbox.Items.Contains(itemToReselect))\n                {\n                    listbox.SelectedItem = itemToReselect;\n                }\n            }\n        }	0
20680684	20679927	WP8 app crashes with exceptions	Deployment.Current.Dispatcher.BeginInvoke(() =>\n            {\n             // your code    \n            });	0
17344252	17326742	C# Excel 2007 RTD Server crashes on exit	Dispose(bool)	0
23853558	23834889	C# Validate xml against multiple schemas xsd	class XmlResolver : XmlUrlResolver\n    {\n        internal const string BaseUri = "schema://";\n\n        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)\n        {\n            if (absoluteUri.Scheme == "schema")\n            {\n                switch (absoluteUri.LocalPath)\n                {\n                    case "/ADDRESS.xsd":\n                        return new MemoryStream(Encoding.UTF8.GetBytes(Resource.ADDRESS));\n                    case "/PERSON.xsd":\n                        return new MemoryStream(Encoding.UTF8.GetBytes(Resource.PERSON));\n                }\n            }\n            return base.GetEntity(absoluteUri, role, ofObjectToReturn);\n        }\n    }	0
7284459	7284407	How to verify that a correct BCL method is called	Step into specific	0
415655	415620	Redirect console output to textbox in separate program	void RunWithRedirect(string cmdPath)\n{\n    var proc = new Process();\n    proc.StartInfo.FileName = cmdPath;\n\n    // set up output redirection\n    proc.StartInfo.RedirectStandardOutput = true;\n    proc.StartInfo.RedirectStandardError = true;    \n    proc.EnableRaisingEvents = true;\n    proc.StartInfo.CreateNoWindow = true;\n    // see below for output handler\n    proc.ErrorDataReceived += proc_DataReceived;\n    proc.OutputDataReceived += proc_DataReceived;\n\n    proc.Start();\n\n    proc.BeginErrorReadLine();\n    proc.BeginOutputReadLine();\n\n    proc.WaitForExit();\n}\n\nvoid proc_DataReceived(object sender, DataReceivedEventArgs e)\n{\n    // output will be in string e.Data\n}	0
26644389	26644359	Compare Datetime	DateTime expirydate = DateTime.Now.Subtract(TimeSpan.FromDays(14));\n\nDirectoryInfo exceptionsDirectory = new DirectoryInfo(pathToSave);\n\nforeach (FileInfo actualFile in exceptionsDirectory.GetFiles())\n{\n    if (actualFile.LastWriteTime < expirydate)\n    {\n        try\n        {\n            File.Delete(actualFile.FullName);\n        }\n        catch (Exception ex)\n        {\n            // do ..\n        }\n    }\n}	0
12548747	12548724	How do I avoid duplication of columns in a Gridview when using code-behind to execute sql query?	AutoGenerateColumns="false"	0
4778962	4745117	How do you map the Accountability pattern to SQL with NHibernate	public class AccountabilityTypeMap : ClassMap<AccountabilityType>\n{\n    public AccountabilityTypeMap()\n    {\n        Id(p => p.Id).GeneratedBy.Assigned();\n    }\n}\n\npublic class AccountabilityMap : ClassMap<Accountability>\n{\n    public AccountabilityMap()\n    {\n        Id(p => p.Id).GeneratedBy.Guid();\n\n        References(p => p.Parent, "ParentId").Cascade.None();\n\n        References(p => p.Child, "ChildId").Cascade.All();\n\n        References(p => p.Type, "AccountabilityTypeId").Cascade.None();\n    }\n}\n\npublic class PartyMap : ClassMap<Party>\n{\n    public PartyMap()\n    {\n        Id(p => p.Id).GeneratedBy.Guid();\n\n        Map(p => p.Name);\n\n        Map(p => p.Type);\n\n        HasMany(p => p.ChildAccountabilities)\n            .KeyColumn("ParentId")\n            .Inverse()\n            .Cascade.All();\n\n        HasMany(p => p.ParentAccountabilities)\n            .KeyColumn("ChildId")\n            .Inverse()\n            .Cascade.All();\n    }\n}	0
6364148	6364120	HashCode as enum values	myList.SelectedIndex = (int)myEnumValue;	0
10804121	10804102	how to check if string value is in the Enum list?	Enum.IsDefined(typeof(Age), youragevariable)	0
2671675	2671634	C# Execute Method (with Parameters) with ThreadPool	var numThreads = 20;\nvar toProcess = numThreads;\n\nvar resetEvent = new ManualResetEvent(false);\n\nfor (var i = 0; i < numThreads; i++)\n{\n    ThreadPool.QueueUserWorkItem (\n        new WaitCallback(delegate(object state) {\n        Do_SomeWork(Parameter1, Parameter2, Parameter3);\n        if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();\n    }), null);\n}\n\nresetEvent.WaitOne();	0
20258375	20258246	How to stop program executing further in C#	Console.WriteLine("Enter a value: ");\nstring str = Console.ReadLine();\n//If pressed enter here without a  value or data, how to stop the  program here without\n//further execution??\nif (string.IsNullOrWhiteSpace(str))\n  return;\nelse\n{\n  Console.WriteLine(string.Format("you have entered: '{0}'", str));\n  Console.Read();\n}	0
22215684	22215492	Add new row on the top of the grid	var dtCurrentTable = (DataTable)ViewState["CurrentTable"];\nvar newRow = dtCurrentTable.NewRow();\ndtCurrentTable.Rows.InsertAt(newRow, 0);	0
2495354	2494812	String chunking algorithm with natural language context	public IList<string> ChunkifyText(string bigString, int maxSize, char[] punctuation)\n    {\n        List<string> results = new List<string>();\n\n        string chunk;\n        int startIndex = 0;\n\n        while (startIndex < bigString.Length)\n        {\n            if (startIndex + maxSize + 1 > bigString.Length)\n                chunk = bigString.Substring(startIndex);\n            else\n                chunk = bigString.Substring(startIndex, maxSize);\n\n            int endIndex = chunk.LastIndexOfAny(punctuation);\n\n            if (endIndex < 0)\n                endIndex = chunk.LastIndexOf(" ");\n\n            if (endIndex < 0)\n                endIndex = Math.Min(maxSize - 1, chunk.Length - 1);\n\n            results.Add(chunk.Substring(0, endIndex + 1));\n\n            startIndex += endIndex + 1;\n        }\n\n        return results;\n    }	0
27638006	27637271	How to get the collection of running packages from SSIS server?	// get all executions for this project that are currently running\nvar runningPackagesBefore = catalog.Executions.Select(operation => operation.Id).ToList();\n\n// [..] logic to execute the package \n\nwhile (true)\n{\n    var integrationServices = new IntegrationServices(sqlConnection);\n    Catalog refreshedCatalog = integrationServices.Catalogs[catalogName];\n\n    // get all packages that are running\n    var runningOperations = refreshedCatalog.Executions.Where(\n        operation => operation.Status == Operation.ServerOperationStatus.Running);\n\n    // get all packages that are new\n    var newRunningOperations = runningOperations.Where(\n        operation => !runningPackagesBefore.Contains(operation.Id));\n\n    if (!newRunningOperations.Any())\n    {\n        break;\n    }\n\n    // [..] sleep and timeout logic here\n}	0
15655132	15655040	How to set visibility to collapsed on image when one is visible	switch (ElementInfoCollection[pos].ArrowDirection)\n{\n    LeftArrow.Visibility = Visibility.Collapsed;\n    RightArrow.Visibility = Visibility.Collapsed;\n    TopArrow.Visibility = Visibility.Collapsed;\n    BottomArrow.Visibility = Visibility.Collapsed;\n\n    case ArrowDirection.Left: LeftArrow.Visibility = Visibility.Visible; break;\n    case ArrowDirection.Right: RightArrow.Visibility = Visibility.Visible; break;\n    case ArrowDirection.Top: TopArrow.Visibility = Visibility.Visible; break;\n    case ArrowDirection.Bottom: BottomArrow.Visibility = Visibility.Visible; break;\n    default: break;\n}	0
18977924	18977740	How to compare difference between two datatable of same format?	var lstResult = (from _old in DataTableOLD.AsEnumerable()\n    join _new in DataTableNew.AsEnumerable() on _old.Field<string>("CODE") \n      equals _new.Field<string>("CODE")\n    where _old.Field<string>("GROUP") != _new.Field<string>("GROUP") ||\n    _old.Field<string>("SUBGROUP") != _new.Field<string>("SUBGROUP")\n    select new\n    {\n        OLDCODE = _old.Field<string>("CODE"),\n        OLDNAME = _old.Field<string>("NAME"),\n        OLDGROUP = _old.Field<string>("GROUP"),\n        OLDSUBGROUP = _old.Field<string>("SUBGROUP"),\n        NEWCODE = _new.Field<string>("CODE"),\n        NEWNAME = _new.Field<string>("NAME"),\n        NEWGROUP = _new.Field<string>("GROUP"),\n        NEWSUBGROUP = _new.Field<string>("SUBGROUP")\n     }\n);	0
22088226	22087959	How to compare the values of listbox with a table values in c#?	while (sqlrdr.Read())\n{\n    string tableValue = sqlrdr[0].ToString();\n    bool found = listBox1.Items.Cast<object>().Any(x=>x.ToString() == tableValue);\n    if(found)\n    {\n        //Search found do whatever\n    }\n    else\n    {\n        //Search not found do whatever\n    }\n}	0
3502816	3502256	How to identify associations flagged as Cascade Delete	using (var context = new AppEntities())\n{\n    var container = context.MetadataWorkspace.GetEntityContainer("AppEntities", System.Data.Metadata.Edm.DataSpace.CSpace);\n\n    foreach (var entitySet in container.BaseEntitySets.OfType<EntitySet>())\n    {\n        var elementType = entitySet.ElementType;\n\n        foreach (var np in elementType.NavigationProperties)\n        {\n            if (np.FromEndMember.DeleteBehavior == OperationAction.Cascade)\n            {\n                var entityType = np.FromEndMember.GetEntityType();\n\n                // do stuff...\n            }\n\n            if (np.ToEndMember.DeleteBehavior == OperationAction.Cascade)\n            {\n                var entityType = np.ToEndMember.GetEntityType();\n\n                // do stuff...\n            }\n        }\n    }\n}	0
18951858	18891448	how to set return type of a stored procedure according to a specific table	CREATE PROCEDURE [dbo].[MyProcedure]\n    @pSelect nvarchar(max)\nAS\nBEGIN\n    SET NOCOUNT ON;\n\n    DECLARE @SQL nvarchar(max)\n\n    SET @SQL = 'select ' + @pSelect + ' from tabel1';\n\n    EXEC (@SQL)\n\n   --Remove the below line once you have added the stored procedure to the dbml file.\n    select * from table1\nEND	0
862927	862749	How to get the primary key of an Ms Access table in C#	public static List<string> getKeyNames(String tableName, DbConnection conn)\n{\nvar returnList = new List<string>();\n\n\nDataTable mySchema = (conn as OleDbConnection).\nGetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys,\n                    new Object[] {null, null, tableName});\n\n\n// following is a lengthy form of the number '3' :-)\nint columnOrdinalForName = mySchema.Columns["COLUMN_NAME"].Ordinal;\n\nforeach (DataRow r in mySchema.Rows)\n{\nreturnList.Add(r.ItemArray[columnOrdinalForName].ToString());\n}\n\nreturn returnList;\n}	0
8829101	8829010	C# interface with internal setters	public class Circle : ICircle{\n   public double Radius{\n      get;set;\n   }\n\n   /* blah blah ... */\n}\n\npublic interface ICircle {\n   /* No properties */\n\n   /* blah blah ...*/\n}	0
30244995	30244460	How to open excel file and rename excel worksheet?	FileInfo finfo = new FileInfo(@"C:\Temp\Book1.xlsx");\nusing (var excelPackage = new ExcelPackage(finfo))\n{\n    ExcelWorksheet ws = excelPackage.Workbook.Worksheets["Sheet1"];\n    ws.Name = "NewWorksheet Name";\n    excelPackage.Save();\n}	0
28558564	28558221	Traverse over a nested Dictionary using the nested dictionary as key in c# via Linq	ExpireDate = expireDates.Where(\n    x => x.Key.Any(\n        y => y.Key == component.ArticleNumber && y.Value == component.SortimentsCode)\n).Select(z => z.Value).FirstOrDefault()	0
25564379	25485521	make https request to wcf service: The remote certificate is invalid according to the validation procedure	ServicePointManager.ServerCertificateValidationCallback +=\n        EasyCertCheck;\n\n bool EasyCertCheck(object sender, X509Certificate cert,\n   X509Chain chain, System.Net.Security.SslPolicyErrors error)\n    {\n        return true;\n    }	0
14988052	14987953	Remove elements from List Box if checkbox gets unchecked in C#	private void cbCheckbox_CheckedChanged(object sender, EventArgs e)\n            {\n                    if (cbCheckbox.Checked)  \n                    {   \n                        testlist.Clear();\n                        ltTestPool.DataSource = null;\n                        testlist.Add("Elemento1");\n                        testlist.Add("Elemento2");\n                        testlist.Add("Elemento3");\n                        ltTestPool.DataSource = testlist;\n                    }\n\n                    else\n                    {   testlist.Clear();  \n                        ltTestPool.DataSource =null;            \n                        testlist.Add("Elemento1");\n                        testlist.Add("Elemento2");\n                        testlist.Add("Elemento3");\n                        ltTestPool.DataSource = testlist;\n                    }\n\n\n}	0
18950977	18950919	Dapper returning a sub set of specific columns directly into DTO	var sql  = @"select c.Name as [Customer], o.Number as [Order], ol.Number as [Line], p.Description as [Product], ol.Qty ...";\n    var result = connection.Query<CustOrders>(query);	0
304860	304847	Is it legal and possible to access the return value in a finally block?	SomeType result = default(SomeType); // for "definite assignment"\ntry {\n   // ...\n   return result;\n}\nfinally {\n    // inspect "result"\n}	0
34001610	34001022	Null encountered when deserializing JSON	{"code":200,\n"description":{\n "15":{"id":"15","name":"US"},\n "25":{"id":"25","name":"Canada"}\n }}\n\n\n    public class RootObject\n    {\n        public int code { get; set; }\n        public Dictionary<string, NewCountry> description { get; set; }\n    }\n\n    public class NewCountry\n    {\n        public string id { get; set; }\n        public string name { get; set; }\n    }	0
10828795	10828179	How to get the resolution of screen? For a WinRT app?	var bounds = Window.Current.Bounds;\n\ndouble height = bounds.Height;\n\ndouble width = bounds.Width;	0
220586	220470	What is the proper way to maintain state in a custom server control?	partial class MyControl : System.Web.UI.UserControl, IStateManager\n{\n    [Serializable()]\n    protected struct MyControlState\n    {\n        public bool someValue;\n        public string name;\n    }\n\n    protected MyControlState state;\n\n    public bool someValue {\n        get { return state.someValue; }\n        set { state.someValue = value; }\n    }\n\n    public bool IsTrackingViewState {\n        get { return true; }\n    }\n\n    protected override void LoadViewState(object state)\n    {\n        if ((state != null) && state is MyControlState) {\n            this.state = state;\n        }\n    }\n\n    protected override object SaveViewState()\n    {\n        return state;\n    }\n\n    protected override void TrackViewState()\n    {\n        base.TrackViewState();\n    }\n}	0
6602282	6602249	C# string trim keeping internal letters	text = text.Substring(2, 3);	0
14217367	14217152	Design- Pattern to prevent unassigned objects	public class Observer\n{\n    private MonitoredClass _monitoredClass;\n    private DataClass _dataClass;\n\n    public static void Observe(MonitoredClass monitoredClass, DataClass dataClass)\n    {\n        new Observer(monitoredClass, dataClass);\n    }\n\n    private Observer(MonitoredClass monitoredClass, DataClass dataClass)\n    {\n        _monitoredClass = monitoredClass;\n        _dataClass = dataClass;\n        _monitoredClass.PropertyChanged+=MonitoredClassPropertyChanged;\n    }\n\n    private void MonitoredClassPropertyChanged(..)\n    {\n        _dataClass.LastProperty1Value = _monitoredClass.Property1;\n    }\n}	0
30098419	30097835	How do I convert Latitude and Longitude value to a map and display it on a page	string latitude = "51.501545070000000";\nstring longitude = "-0.184810405000000";\nstring zoomlevel = "18z";\n\nstring url = "https://www.google.no/maps/@" + latitude + "," + longitude + "," + zoomlevel;\n\nResponse.Redirect(url);	0
33944539	33942042	play wav file in Raspberry Pi with Windows 10 IOT Core	StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/filename.wav"));\nMediaPlayer player = BackgroundMediaPlayer.Current;\nplayer.AutoPlay = false;\nplayer.SetFileSource(file);\nplayer.Play();	0
2160667	826096	C# cancelling DoWork of background worker	public class AbortableBackgroundWorker : BackgroundWorker\n{\n    private Thread workerThread;\n\n    protected override void OnDoWork(DoWorkEventArgs e)\n    {\n        workerThread = Thread.CurrentThread;\n        try\n        {\n            base.OnDoWork(e);\n        }\n        catch (ThreadAbortException)\n        {\n            e.Cancel = true; //We must set Cancel property to true!\n            Thread.ResetAbort(); //Prevents ThreadAbortException propagation\n        }\n    }\n\n\n    public void Abort()\n    {\n        if (workerThread != null)\n        {\n            workerThread.Abort();\n            workerThread = null;\n        }\n    }\n}	0
17596009	17595909	extract values from Xml File	var root = XElement.Parse(xmlText);  // or directly .Load(fileName)\n\nList<string> tifNames = root.Descendants("TIFNAME").Select(e => e.Value);	0
29766284	29766144	Updating a list within a list<class>	public void initializeTouchDataListObject()\n{\n    touchSetList = new List<DataStructure.TouchSet>(DataStructure.maxButtonsActive);\n\n    for (int a = 0; a < DataStructure.maxButtonsActive; a++)\n    {\n        List<DateTime> tempTimeList = new List<DateTime>();\n        List<int> tempTouchList = new List<int>();\n        DataStructure.TouchSet tempTouchSet = new DataStructure.TouchSet();\n        tempTouchSet.timeList = tempTimeList;\n        tempTouchSet.touchList = tempTouchList;\n        touchSetList.Add(tempTouchSet);\n    }\n}	0
1591546	1591474	SqlConnection as a static singleton object	using(var conn = db.OpenConnection())\n{\n  // stuff\n}	0
3275315	3275211	How do I run a query that makes table in Access through C#?	using System.Data;\nusing System.Data.\n\nusing (IDbConnection conn = new OleDbConnection(...)) // <- add connection string\n{\n    conn.Open();\n    try\n    {\n        IDbCommand command = conn.CreateCommand();\n\n        // option 1:\n        command.CommandText = "SELECT ... FROM MyQuery";\n\n        // option 2:\n        command.CommandType = CommandType.TableDirect;\n        command.CommandText = "MyQuery";\n\n        // option 3:\n        command.CommandType = CommandType.StoredProcedure;\n        command.CommandText = "MyQuery";\n\n        using (IDataReader reader = command.ExecuteReader())\n        {\n            // do something with the result set returned by reader...\n        }\n    }\n    finally\n    {\n        conn.Close();\n    }\n}	0
2544465	2514948	WCF custom message security	private static void ApplyChannelProtectionRequirements(BindingContext context)\n    {\n        var cpr = context.BindingParameters.Find<ChannelProtectionRequirements>();\n        if (cpr != null)\n        {\n            XmlQualifiedName qName = new XmlQualifiedName("customHeader", "namespace");\n            MessagePartSpecification part = new MessagePartSpecification(qName);\n            cpr.IncomingEncryptionParts.AddParts(part, "incomingAction");\n            cpr.IncomingSignatureParts.AddParts(part, "incomingAction");\n            cpr.OutgoingEncryptionParts.AddParts(part, "outgoingAction");\n            cpr.OutgoingSignatureParts.AddParts(part, "outgoingAction");\n        }\n    }	0
24163797	24163738	Returning a null value to C#/XAML DatePicker through a converter	if (dt == DateTime.MinValue)\n    return String.Empty;\nelse\n    return dt.ToString("yyyy-MM-dd");	0
5982915	5982006	How to have alternating line colors for a Winforms RichTextBox?	// Update lines to have extra length past length of window\nstring[] linez = new string[richTextBox1.Lines.Length];\nfor (int i = 0; i < richTextBox1.Lines.Length; i++)\n{\n   linez[i] = richTextBox1.Lines[i] + new string(' ', 1000);\n}\nrichTextBox1.Clear();\nrichTextBox1.Lines = linez;\n\nfor(int i = 0; i < richTextBox1.Lines.Length; i++)\n{\n   int first = richTextBox1.GetFirstCharIndexFromLine(i);\n   richTextBox1.Select(first, richTextBox1.Lines[i].Length);\n   richTextBox1.SelectionBackColor = (i % 2 == 0) ? Color.Red : Color.White;\n   richTextBox1.SelectionColor = (i % 2 == 0) ? Color.Black : Color.Green;\n}\nrichTextBox1.Select(0,0);	0
24104747	24104074	Windows phone picturebox	using Microsoft.Phone.Tasks;\n    using System.IO;\n    using System.Windows.Media.Imaging;\n    ...\n    PhotoChooserTask selectphoto = null;\n    private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        selectphoto = new PhotoChooserTask();\n        selectphoto.Completed += new EventHandler(selectphoto_Completed);\n        selectphoto.Show();\n    }\n    void selectphoto_Completed(object sender, PhotoResult e)\n    {\n        if (e.TaskResult == TaskResult.OK)\n        {\n            BinaryReader reader = new BinaryReader(e.ChosenPhoto);\n            image1.Source = new BitmapImage(new Uri(e.OriginalFileName));\n        }\n    }	0
2609436	2609344	How to format individual DropDownlist Items (color, etc.) during onDataBinding event	protected void DropDownList1_DataBound(object sender, EventArgs e)\n{\n    foreach(ListItem myItem in DropDownList1.Items)\n    {\n         //Do some things to determine the color of the item\n         //Set the item background-color like so:\n         myItem.Attributes.Add("style","background-color:#111111");\n    }\n}	0
1561532	1561510	display a particular number from dropdownlist	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    { \n        DropDownList1.SelectedValue = "7"\n    }\n}	0
26157446	26157262	Plain text search in markdown text	var str = "Something ***significant***";\nvar regexp = new Regex("Something.+significant.+");\nConsole.WriteLine(regexp.Match(str).Success);	0
22197055	22196049	Merging tables from different access DB	INSERT INTO aTable \n SELECT * FROM [;DATABASE=Z:\Path\aDB.accdb].bTable	0
15396205	15395887	MS Access Update with addition	OleDbCommand cmd = new OleDbCommand("SELECT * FROM ItemTemp WHERE ITEM=@item", GetConnection());\n cmd.Parameters.AddWithValue("@item", txtItemName.Text);\n OleDbDataReader reader = cmd.ExecuteReader();\n\n //check if this item exist on the table ItemTemp\n if (reader.HasRows == true)\n {\n     OleDbCommand cmde = new OleDbCommand("UPDATE ItemTemp SET QUANTITY=QUANTITY + @QUANTITY," + \n     "PRICE=PRICE + @PRICE WHERE ITEM=@item, GetConnection());\n     cmde.Parameters.AddWithValue("@QUANTITY", Convert.ToInt32(txtItemquantity.Value)); \n     cmde.Parameters.AddWithValue("@PRICE", Convert.ToDecimal(txtItemprice.Text)); \n     cmde.Parameters.AddWithValue("@item", txtItemName.Text);\n     cmde.ExecuteNonQuery();\n }	0
17285156	17284949	Changing the text of a hyperlink in asp.net on click?	Markup:\n<asp:LinkButton id="OpenClose" runat="server" OnClick="OpenClose_Click" AutoPostBack="true" Text="Close"></asp:LinkButton>\n\nCode-Behind:\nprotected void OpenClose_Click(object sender, EventArgs e)\n{\n    if (OpenClose.Text == "Close")\n    {\n        OpenClose.Text = "Open";\n    }\n    else\n    {\n        OpenClose.Text = "Close";\n    }\n}	0
756829	756808	How to get this working example example of delegates to pass lambda syntax as a parameter?	static void Main(string[] args)\n{\n    int[] numbers = { 6, 3, 7, 4, 8 };\n\n    Console.WriteLine("The addition result is {0}.",\n        Tools.ProcessNumbers(p => Tools.AddNumbers(p), numbers));\n\n    Console.WriteLine("The multiplication result is {0}.",\n        Tools.ProcessNumbers(p => Tools.MultiplyNumbers(p), numbers));\n\n    Console.ReadLine();\n}	0
1110357	1110259	How can I read a dynamically created textbox	protected void btnSave_Click(object sender, CommandEventArgs e)\n{\n    var btn = (Button)sender;\n    var container = btn.NamingContainer;\n    var txtBox = (TextBox)container.FindControl("txtComment");\n    firstelement.InnerText = txtBox.text // this gives error on txtComment.text\n}	0
9024330	9023009	dottrace and optimizing method with indexof	public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)\n{\n    string[] result = { "", "" };\n    int iIndexOfBegin = strSource.IndexOf(strBegin, StringComparison.Ordinal);\n\n    if (iIndexOfBegin != -1)\n    {\n        int iEnd = strSource.IndexOf(strEnd, iIndexOfBegin, StringComparison.Ordinal);\n\n        if (iEnd != -1)\n        {\n            result[0] = strSource.Substring(\n                iIndexOfBegin + (includeBegin ? 0 : strBegin.Length), \n                iEnd + (includeEnd ? strEnd.Length : 0) - iIndexOfBegin);\n\n            // advance beyond this segment\n            if (iEnd + strEnd.Length < strSource.Length)\n                result[1] = strSource.Substring(iEnd + strEnd.Length);\n        }\n    }\n\n    return result;\n}	0
22125507	22125234	User login like facebook by email or userid and password in C# using sql data reader?	var sql = "select * from Users_tbl WHERE ((([Email] = @EmailParam) OR ([UserID] = @UserIDParam)]) AND ([Password] = @PasswordParam))";	0
25545280	25531010	need to open chrome native app on click of it, not at the time of enable the exension	if( /* opened by Chrome */ ){\n  // Do not show UI\n  // Listen for command to show UI\n  // Communicate with Chrome\n} else {\n  if( /* there is an open instance of the app */) {\n    // Message that instance to show UI\n    // Terminate\n  } else {\n    // Show error, terminate\n  }\n}	0
5050002	5049964	How to send email from yahoo id from my console application	using (var client = new SmtpClient("smtp.mail.yahoo.com", 587))\n{\n    client.Credentials = new NetworkCredential("youraccount@yahoo.com", "secret");\n    var mail = new MailMessage();\n    mail.From = new MailAddress("youraccount@yahoo.com");\n    mail.To.Add("destaccount@gmail.com");\n    mail.Subject = "Test mail";\n    mail.Body = "test body";\n    client.Send(mail);\n}	0
17040838	17040794	Getting a path of a file. C#	string filePath = @"C:\MyDir\MySubDir\myfile.ext";\nstring directoryName;\nint i = 0;\n\nwhile (filePath != null)\n{\ndirectoryName = Path.GetDirectoryName(filePath);\nConsole.WriteLine("GetDirectoryName('{0}') returns '{1}'",\n    filePath, directoryName);\nfilePath = directoryName;\nif (i == 1)\n{\n    filePath = directoryName + @"\";  // this will preserve the previous path\n}\ni++;\n}	0
25990830	25989827	Data points insertion error. Only 1 Y values can be set for this data series	public partial class chart3 : System.Web.UI.Page\n{\n    SqlConnection con;\n    SqlCommand cmd;\n    SqlDataAdapter da;\n    DataSet ds;\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        con = new SqlConnection(@"connectionString");\n        cmd = new SqlCommand("Select * from GraphChart",con);\n        da = new SqlDataAdapter(cmd);\n        ds = new DataSet();\n        da.Fill(ds);\n        DataView source = new DataView(ds.Tables[0]);\n        Chart1.DataSource = source; \n        Chart1.Series[0].XValueMember = "Name";\n        Chart1.Series[0].YValueMembers = "Age";\n        Chart1.DataBind();\n    }\n}	0
21119746	21119417	How not to print the last separator character in StreamWriter?	private void spremiUDatotekuToolStripMenuItem1_Click(object sender, EventArgs e)\n{\nif (saveFileDialog1.ShowDialog() == DialogResult.OK)\n{\n    System.IO.StreamWriter sw = new\n    System.IO.StreamWriter(saveFileDialog1.FileName);\n\n    for (int x = 0; x < dataGridView1.Rows.Count; x++)\n    {\n\n        for (int y = 0; y < dataGridView1.Columns.Count; y++)\n        {\n            sw.Write(dataGridView1.Rows[x].Cells[y].Value);\n            if (y != dataGridView1.Columns.Count - 1) // Count - 1 is the last value. y will never reach count because you have "<" sign\n            {\n                sw.Write("|");                    \n            }\n        }\n        sw.WriteLine();\n    }\n    sw.Close();\n}	0
21793759	21782412	Error in Querying sqlite-net db based on a date range	String query = "SELECT DISTINCT * FROM Object WHERE (( TransactionAccount = '" + parameter + "') AND (CAST(Amount AS REAL) BETWEEN " + min_amount + " AND " + max_amount + ") AND TDate BETWEEN   Date('2014-01-01 19:45:46')  AND  Date('2014-02-01 19:05:43')  ) ";	0
13774248	10908182	checking crc32 of a file	; Generated by QuickSFV v2.36 on 2012-08-09 at 16:34:25\n; http://www.QuickSFV.org\n;\n;   1684525442  21:45.33 2012-08-05 Video.mkv\nVideo.mkv 9AC44069	0
3007064	2999897	How to handle null return from custom HttpHandler in asp.net?	public static bool CheckImageExistance(string url)\n        {\n            try\n            {\n                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; \n                request.Method = "HEAD";       \n\n                request.Credentials = CredentialCache.DefaultCredentials;\n\n                HttpWebResponse response = request.GetResponse() as HttpWebResponse; \n                response.Close();\n                return (response.StatusCode == HttpStatusCode.OK);\n            }\n            catch (Exception ex)\n            {\n                return false;\n            }	0
16159295	16126889	How to control node names in xml using Request.CreateResponse?	[CollectionDataContract(Name = "Persons")]\npublic class PersonResults : List<PersonSearchDto>\n{\n}	0
28202835	28202784	Sorting MySQL table and then updating the rows	"UPDATE t1 SET t1.operator_id='" +\nbidList[i].OperatorId + "', t1.status='Allocated' " +\n"FROM booking_view T1 "+\n"JOIN bid t2 ON t1.plot_id=t2.plot_id";	0
14195805	14194359	send a file to multiple clients using TCP socket	FileShare.Read	0
3185058	3185023	How to get results that begin with a certain letter?	SqlExpression.Like<CompanyGroupInfo>(g => g.Name, letter, MatchMode.Start)	0
31196723	31196623	Trying to deserialize TheMovieDB JSON	seriesCollection = JObject.Parse(popularJson)["results"]\n    .ToObject<ObservableCollection<SeriesModel>>();	0
5612613	5612463	LINQ: How to get parent types' properties while getting their children collections	from p in parents\nfrom c in p.Children\nselect new MixedType(...)	0
13916716	13916265	Dynamic Facets in Elastic Search using Nest Client	public TermFacetDescriptor<CatalogMapping> FacetBuilder(TermFacetDescriptor<CatalogMapping> termFacet, FacetOptions options)\n    {\n        termFacet.OnField(options.Field);\n        termFacet.Size(options.Size);\n\n        if (options.IncludeAllTerms)\n            termFacet.AllTerms();\n\n        return termFacet;\n    }	0
17738472	17738196	Display currency symbols using currency code culture in windows phone 8	tbCurencysymbol.Text = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol.ToString();	0
25236896	25236874	Override And Call Base Property Set Method	public override Branch this[string attribKey] {\n\n        set\n        {                \n            base[attribKey] = value;    \n\n            if (attribKey.Equals("data_2d"))\n                dimensions = 2;\n        }\n    }	0
24909969	24909762	A regex expression in C# help needed	(?<name>[\w\-"]+)(?<!DOG)[ \n]+MODULE-IDENTITY	0
6796070	6796040	How to count days quantity	var d1 = new DateTime(year1, month1, day1);\nvar d2 = new DateTime(year2, month2, day2);\nTimeSpan t = d2 - d1;\nvar elapsedDays = t.Days;	0
19253674	19251052	GetLastWin32Error() implementation change	catch (IOException ex) {\n            var hr = (uint)Marshal.GetHRForException(ex);\n            if (hr == 0x80070000 + ERROR_SHARING_VIOLATION) {\n                // Report sharing violation\n                //...\n            }\n        }	0
1468206	1461667	C# Com Retrieving binary Image (Tiff) Data from device	[DllImport("mtxmlmcr", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]\nstatic extern Int32 MTMICRGetImages(string DeviceName, ref MagTekImage MagTekGImages, ref Int32 TotalImages);\n\n\n// \n// Allocate memory for image with size of imageSize, because the image\n// data has null characters (which marshalling doesn't like), we must\n// get the memory location of the char* and read bytes directly from memory\n//\nIntPtr ptr = Marshal.AllocHGlobal(imageSize + 1);\nRC = MTMICRGetImage(ExcellaDeviceName, mtValue.ToString(), ptr, ref imageSize);\n\n// Copy the Image bytes from memory into a byte array for storing\nbyte[] imageBytes = new byte[imageSize];\nMarshal.Copy(ptr, imageBytes, 0, imageSize);\nMarshal.FreeHGlobal(ptr);	0
33653397	33653273	How To Reset a Binding from Code Behind	BindingOperations.ClearBinding	0
1111681	1111558	Get index with value in Checked List Box	int index = checkedListBox1.Items.IndexOf("42");\ncheckedListBox1.SetItemChecked(index, true);	0
2902407	2901879	Help need to convert this code to C#	private string GetAppGUID(string sectionId)\n    {\n        string hexString = null;\n        int i = 0;\n        int guidLength = 0;\n\n        guidLength = 16;\n\n        if (sectionId.Length < guidLength)\n        {\n            sectionId = sectionId + new string(" "[0], guidLength - sectionId.Length);\n        }\n\n        foreach (char c in sectionId)\n        {\n            int tmp = c;\n            hexString += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()))\n        }\n\n        return hexString;\n    }	0
12868392	12867989	Windows 8 metro call standardstyle from code behind	var style = Application.Current.Resources["FavoriteAppBarButtonStyle"] as Style	0
11369988	11369950	How to calculate checksum for 3 GB file but first remove the last 28 bytes	public byte[] Sha1ExceptEnd(Stream input, int bytesToOmit)\n{\n    long bytesToRead = input.Length - bytesToOmit;\n    byte[] buffer = new byte[16 * 1024]; // Hash up to 16K at a time\n    using (SHA1 sha1 = SHA1.Create())\n    {\n        while (bytesToRead > 0)\n        {\n            int thisPass = (int) Math.Min(buffer.Length, bytesToRead);\n            int bytesReadThisPass = input.Read(buffer, 0, thisPass);\n            if (bytesReadThisPass <= 0)\n            {\n                throw new IOException("Unexpected end of data");\n            }  \n            sha1.TransformBlock(buffer, 0, bytesReadThisPass, buffer, 0);\n            bytesToRead -= bytesReadThisPass;\n        }\n        // Flush the hash\n        sha1.TransformFinalBlock(buffer, 0, 0);\n        return sha1.Hash;\n    }\n}	0
15196800	15196764	I am having difficulty in parsing logs for a particular field with values having spaces?	string x = @"Elapsed Time: 97ms";\n        int startIndex = x.LastIndexOf("Elapsed Time");\n        int endIndex = x.LastIndexOf("ms");\n        //Here there might be a problem, you might need to change to endIndex - startIndex +1\n        string valueSubString = x.Substring(startIndex, endIndex - startIndex);\n        decimal value = decimal.Parse(valueSubString.Replace(':').Trim());	0
14294142	14287029	How can I create a shared AppBar in a C# windows store app?	protected async override void OnNavigatedTo(NavigationEventArgs e)\n   {\n            rootPage =  e.Parameter as MainPage;\n            bottomAppBarPnl = rootPage.FindName("bottomAppBar") as StackPanel;\n\n            if(bottomAppBarPnl != null)\n            {               \n             // Create the button to add             \n             newCust = new Button();               \n             newCust.Content = "New Customer";              \n             newCust.Click += new RoutedEventHandler(newCust_Click);               \n            // Add the button to the AppBar               \n            bottomAppBarPnl.Children.Add(newCust);\n\n            }\n\n        }	0
15837249	15837180	Replace all non-word characters with a space	var cleaned = Regex.Replace(given, "[^A-Za-z]", " ");	0
4073947	4073611	Send key to active window	SendKeys/SendInput	0
2533809	2533339	Modify a ListBox's item from a button in it's template?	void OnUpdateUser(object sender, RoutedEventArgs e)\n{    \n  object item = ((Button)sender).DataContext;\n  // do stuff with item\n}	0
29867599	29867471	Is String culture info important for comparison if the user will never modify those strings	StringComparison.Ordinal[IgnoreCase]	0
10326012	10086617	Ideal design pattern for contact list/roster download/synchronization in a Messenger library	List<SomethingEventArgs> events;\n\nforeach (SomethingEventArgs e in events)\n    OnSomethingEvent(e);	0
15977081	15435322	Using Selenium to send text to tinymce control not working for IE9	var obj = ((IJavaScriptExecutor)webDriver).ExecuteScript("tinyMCE.activeEditor.setContent('" + text + "');");	0
21599878	21599118	Always Round UP a value in C#	var value2 = 2.524;\nvar result2 = Math.Round(value2, 2); //Expected: 2.53 //Actual: 2.52\nif(result2 < value2)\n    result += 0.01; // actual 2.53	0
20173152	20152103	Extracting Excel workbook name before it actually opens	Wb.Windows[1].Visible = false;	0
15172475	15172342	How to get dates of selected Day for entire month?	DateTime d1 = DateTime.Parse("03/01/2013");\nDateTime d2 = DateTime.Parse("04/01/2013");\n\nint days = (d2 - d1).TotalDays;\n\nfor (i = 0; i <= days; i++) {\n    DateTime d = d1.AddDays(i);\n    if ((d.DayOfWeek == DayOfWeek.Monday)) {\n        Console.WriteLine(d);   //dateList.Add(d);   <------ this could be a List<DateTime> or List<string>\n    }\n}\n\nOutput - M/dd/yyyy format\n-------\n3/04/2013\n3/11/2013\n3/18/2013\n3/25/2013\n4/01/2013	0
11827105	11826936	pass list item from c# to javascript array	var obj = new[] { \n    new object[] { "Bondi Beach", -33.890542, 151.274856, 4 },\n    new object[] { "Coogee Beach", -33.923036, 151.259052, 5 },\n    new object[] { "Cronulla Beach", -34.028249, 151.157507, 3 },\n    new object[] { "Manly Beach", -33.80010128657071, 151.28747820854187, 2 },\n    new object[] { "Maroubra Beach", -33.950198, 151.259302, 1 },\n};\nvar json = JsonConvert.SerializeObject(obj);	0
1005175	1005154	How to use DateTime in WHERE clause (LINQ)?	opp.CreatedDate.Date == Convert.ToDateTime(createdDate).Date	0
892119	892074	Function that creates a timestamp in c#	public static String GetTimestamp(this DateTime value)\n{\n    return value.ToString("yyyyMMddHHmmssfff");\n}	0
1874773	1357574	Is there a good reference for data annotations in regards to how DataType works?	public class EvenNumberAttribute : ValidationAttribute\n{\n    public EvenNumberAttribute() : base(() => Resource1.EvenNumberError) { }\n    public EvenNumberAttribute(string errorMessage) : base(() => errorMessage) { }\n\n    protected override ValidationResult IsValid(object value, \n        ValidationContext validationContext)\n    {\n        if (value == null)\n        {\n            return ValidationResult.Success;\n        }\n\n        int convertedValue;\n        try\n        {\n            convertedValue = Convert.ToInt32(value);\n        }\n        catch (FormatException)\n        {\n            return new ValidationResult(Resource1.ConversionError);\n        }\n\n        if (convertedValue % 2 == 0)\n        {\n            return ValidationResult.Success;\n        }\n        else\n        {\n            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));\n        }\n    }\n}	0
16172500	16172407	C# How to create a file contains 4 fields or more with records?	string path = @"C:\somefile.txt";\nusing (StreamWriter writer = (File.Exists(path) ? File.AppendText(path) : new StreamWriter(path)))\n    writer.WriteLine("whatever you want to write");	0
8612318	8612284	Calling a method on every instance of a type in c#	public class Foo\n{\n    private static readonly HashSet<WeakReference> _trackedFoos = new HashSet<WeakReference>();\n    private static readonly object _foosLocker = new object();\n\n    private readonly WeakReference _weakReferenceToThis;\n\n    public static void DoForAllFoos(Action<Foo> action)\n    {\n        if (action == null)\n            throw new ArgumentNullException("action");\n\n        lock (_foosLocker)\n        {\n            foreach (var foo in _trackedFoos.Select(w => w.Target).OfType<Foo>())\n                action(foo);\n        }\n    }\n\n    public Foo()\n    {\n       _weakReferenceToThis = new WeakReference(this);\n\n        lock (_foosLocker)\n        {\n            _trackedFoos.Add(_weakReferenceToThis);\n        }\n    }\n\n    ~Foo()\n    {\n        lock (_foosLocker)\n        {\n            _trackedFoos.Remove(_weakReferenceToThis);\n        }\n    }\n}	0
14443578	14443489	How to store the rows that have been added to a datagridview to a datarow array in C#?	DataTable changeTable = table.GetChanges(DataRowState.Added);	0
5543858	5542602	C# - Marking base class of custom Form makes Design View display HTML	The designer must create an instance of type 'WinFormsTestApp.FormA' but it cannot because the type is declared as abstract.	0
8655970	8655747	Elegant solution to check if two dates are equal, in Linq (where the second date is NOT a parameter)	var query = from t1 in Table1\n        join t2 in Table2 on t1.Id equals t2.ForeignKeyId\n        where t1.Id = someId\n           && EntityFunctions.DiffDays(t1.Date1, t2.Date2) == 0	0
653616	653540	convert xml to sorted dictionary	string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";\nXmlDocument xml = new XmlDocument();\nxml.LoadXml(s);\nXmlNodeList resources = xml.SelectNodes("data/resource");\nSortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();\nforeach (XmlNode node in resources){\n   dictionary.Add(node.Attributes["key"].Value, node.InnerText);\n}	0
16534565	16534420	Gridview bind to label from database and extra text	Text='<%# Eval("RoleID").ToString() + "more text"%>'>	0
38962	38960	How to find out if a file exists in C# / .NET?	File.Exists(path)	0
2561174	2546001	WCF - Dynamically Change WebResponseFormat	[WebGet(UriTemplate = "objects", BodyStyle = WebMessageBodyStyle.Bare)]\n[OperationContract]\nList<SampleObject> GetObjects();\n\n[WebGet(UriTemplate = "objects?format=json", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]\n[OperationContract]\nList<SampleObject> GetObjectsInJson();	0
28131660	28131649	How to initialize automatic static property inline?	static Car()\n{\n    ID = 0;\n}	0
16354690	16353845	Efficient use of CPU idle time for parallel URL processing	Thread.CurrentThread.ThreadPriority = ThreadPriority.BelowNormal; // Or ThreadPriority.Lowest.	0
15115070	7531445	Omit object property during json serialization	public class jsTreeModel\n{\n    public string Data { get; set; }\n    public JsTreeAttribute Att { get; set; }\n    public string State { get; set; }\n    [JsonIgnore]\n    public List<jsTreeModel> Children { get; set; }\n}	0
1929977	1929802	Porting CDate(long) from VB6 to C#	DateTime.FromOADate((double)recPatient.birthDateByte2 * 256 \n                     + recPatient.birthDateByte1 + 366)	0
4796567	4796554	Making A WinForm Change Background Color While Still Useable	System.Windows.Forms.Timer	0
33667392	33667310	Convert my List<int> into a List<SelectListItem>	List<SelectListItem> item = YearList.ConvertAll(a =>\n                {\n                    return new SelectListItem()\n                    {\n                        Text = a.ToString(),\n                        Value = a.ToString(),\n                        Selected = false\n                    };\n                });	0
10281351	10281259	How to get sum of data in a list using multiple column values	List<int> ids = new List<int>() { 0, 1, 3, 6 };\n\nfilterEntities = (from list in filterEntities \n                  where ids.Contains(list.Id)\n                  group list by list.id into g\n                  orderby g.Key\n                  select new \n                  {\n                    ID = g.Key,\n                    Age = g.Sum(x => x.Age),\n                  }).ToList();	0
3258041	3257974	GroupBy without LINQ	Dictionary<int, List<CenterDetail>> map = new Dictionary<int, List<CenterDetail>>();\nforeach (CenterDetail detail in details)\n{\n    List<CenterDetail> list;\n    if (!map.TryGetValue(detail.AreaID, out list)\n    {\n        list = new List<CenterDetail>();\n        map.Add(detail.AreaID, list);\n    }\n    list.Add(detail);\n}\nreturn map;	0
16105228	16105129	Pressing a button to increment a variable which changes what values are printed to screen..?	int i = 0;\npublic void nextCardButton_Click(object sender, EventArgs e)\n{\n    i++;\n\n    label1.Text = player1[i].cardName;\n    percentageLabel1.Text = player1[i].cardPercentage.ToString();\n    qualityLabel2.Text = player1[i].cardQuality.ToString();\n    quantityLabel2.Text = player1[i].cardQuantity.ToString();\n    tasteLabel2.Text = player1[i].cardTaste.ToString();\n}	0
19218039	19217440	Add new item to auto filter operator on xtragrid column	gridView1.ActiveFilterString = "[YOURCOLUMN] > 0";	0
17841261	17840728	How to add semi-colons and remove line breaks from RichTextBox?	string text = richTextBox1.Text;\nrichTextBox1.Text = "";\n\nstring[] splitted = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);\n\nforeach (string line in splitted)\n{\n    richTextBox1.AppendText(Environment.NewLine + line.Trim() + ";" + Environment.NewLine);\n}	0
6464168	6464049	Can't set DefaultValue for ConfigurationProperty of Custom ConfigurationElement type	[ConfigurationProperty("Type", DefaultValue="something")]\npublic string Type\n{\n    get\n    {\n        var tmp = base[TypePropertyName] as ConfigurationTextElement<string>;\n        return tmp != null ? tmp.Value : "something";\n    }\n}	0
23592259	23591870	C# Regex to replace all anchor tags not including certain href	Regex r = new Regex("(<a [ a-zA-Z0-9]?href=\"http://www.[a-zA-Z0-9]+.com\"[ a-zA-Z0-9]?>+)([a-zA-Z0-9]+)</a>");\n\n    Match mh = r.Match(html);\n\n    Dictionary<string, string> lst = new Dictionary<string,string>();\n    while(mh.Success)\n     {\n      lst.Add(mh.Value, mh.Groups[2].Value);\n      mh = mh.NextMatch();\n     }\n\n    foreach(var l in lst.Keys)\n     {\n      if(!l.Contains("http://www.a.com"))\n       {\n        html = html.Replace(l,lst[l]);\n       }                \n     }	0
10082348	10045011	Microsoft Kinect + Telldus Tellstick	private void KinectAllFramesReady(object sender, AllFramesReadyEventArgs e)\n   {\n    //Checking for Skeleton\n    if (haveSkeletonData)\n    {\n     //Do Stuff Here\n    }\n   }	0
2204710	2204698	Send email with attachment from WinForms app?	MailMessage theMailMessage = new MailMessage("from@email.com", "to@email.com");\ntheMailMessage.Body = "body email message here";\ntheMailMessage.Attachments.Add(new Attachment("pathToEmailAttachment"));\ntheMailMessage.Subject = "Subject here";\n\nSmtpClient theClient = new SmtpClient("IP.Address.Of.Smtp");\ntheClient.UseDefaultCredentials = false;\nSystem.Net.NetworkCredential theCredential = new System.Net.NetworkCredential("user@name.com", "password");\ntheClient.Credentials = theCredential;\ntheClient.Send(theMailMessage);	0
12225866	12225851	Converting String to Datetime of string Type "12-07-2012"	public static DateTime convertDecimal(string strgDate)\n{\n    return DateTime.ParseExact(strgDate, "yyyy-MM-dd",\n                    System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));\n\n}	0
11989024	11988457	Check Session variable and Redirect to login page before page load	protected override void OnInit(EventArgs e)\n{\n    base.OnInit(e);\n\n    // your code goes here\n}	0
23243440	23243336	How to get File Created Date and Modified Date	DateTime creation = File.GetCreationTime(@"C:\test.txt");\nDateTime modification = File.GetLastWriteTime(@"C:\test.txt");	0
25153350	25153220	How to parse this string into tokens using Regular Expression	\{([^\}]*)\}	0
23655577	23655429	Programmatically send contents of text file to email address	// Read the file\nstring body = File.ReadAllText(@"C:\\MyPath\\file.txt");\n\nMailMessage mail = new MailMessage("you@you.com", "them@them.com");\nSmtpClient client = new SmtpClient();\nclient.Port = 25;\nclient.DeliveryMethod = SmtpDeliveryMethod.Network;\nclient.UseDefaultCredentials = false;\nclient.Host = "smtp.google.com";\nmail.Subject = "file";\n\n// Set the read file as the body of the message\nmail.Body = body;\n\n// Send the email\nclient.Send(mail);	0
24637965	24637483	How to search particular values in a datatable?	for (int y = OriginalDataTable.Rows.Count - 1; y >= 0; y--)\n{\n    int count = 0;\n    for (int i = 0; i <= AgentCodeArray.Length - 1; i++)\n    {\n        if (OriginalDataTable.Rows[y]["Agent_Code"].ToString() != AgentCodeArray[i].ToString())\n        {\n            count++;\n            if (count == AgentCodeArray.Length)\n                OriginalDataTable.Rows[y].Delete();\n        }\n    }\n}	0
32165159	32165060	Session state value doesn't appear in my label	protected void Session_Start(object sender, EventArgs e)\n\n???????{\n\n?????????// Your Hits read code goes here\n\n???????}	0
312037	312024	LINQy way to check if any objects in a collection have the same property value	var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1);\n\n foreach (var agent in duplicates)\n {\n         Console.WriteLine(agent.Key.ToString());\n }	0
8851460	8850062	foreach loop to retrieve list items and create a table	int modCounter = 0;\nforeach (SPListItem oListItem in listItemCollection) \n{ \n    modCounter += 1;\n    awardYear = oListItem["Year"].ToString(); \n    awardCategory = oListItem["Category"].ToString(); \n    awardOrganiser = oListItem["Organiser"].ToString(); \n\n    if(modCounter % 2 == 0) // If modCounter is divisible by 2 (ie even)\n    {\n         // Add information that goes in first column\n    }\n    else\n    {\n         // Add information that goes in second column\n    }\n}	0
27519886	27518736	How to access value from a list from an object type using reflection	dynamic collection = serviceResponse.GetType().GetProperty("SummaryList").GetValue(serviceResponse, null);\nforeach (var item in collection)\n{\n    var value = item.Name;\n}	0
31047463	31047216	Filter generic list with generic dictionary	private List<Dictionary<String, Object>> ValidateScenarioProductItemData(List<Dictionary<String, Object>> pList)\n{\n    var tPeriods = new List<dynamic>();\n    var tCycleProductItemSales = new List<dynamic>();\n    foreach (var tItem in pList.Where(x=>!string.IsNullOrEmpty(x["IsInternal"].ToString())))\n    {\n        var i = 0;\n        foreach (var item in tPeriods)\n        {\n            i++;\n            var tHasSails = tCycleProductItemSales.Where(CPIS => CPIS.CycleId == Convert.ToInt32(tItem["CycleId"].ToString()) && CPIS.ProductItemId == Convert.ToInt32(tItem["ProductItemId"].ToString()) && CPIS.PeriodId == Convert.ToInt32(item.Id.ToString()));\n            if (!tHasSails.Any())\n            {\n                tItem[string.Format("Datasource{0}Id", i)] = 0;\n            }\n        }\n    }\n    return pList;\n}	0
33409517	33409157	How to generate MD5 Hash(32/64 Characters) from an integer	int source = 123;\n  String hash;\n\n  // Do not omit "using" - should be disposed\n  using (var md5 = System.Security.Cryptography.MD5.Create()) \n  {\n    hash = String.Concat(md5.ComputeHash(BitConverter\n      .GetBytes(source))\n      .Select(x => x.ToString("x2")));\n  }\n\n  // Test\n  // d119fabe038bc5d0496051658fd205e6\n  Console.Write(hash);	0
2048519	2048261	Storing the data from a parsed CSV file between page requests in ASP .NET MVC	List<Question>	0
31318483	31318087	C# create nested XML from another XML	string xml = @"<authors>\n  <author name=""John"">\n    <books>\n       <book type=""Children"">ABC</book>\n    </books>\n  </author>\n  <author name=""May"">\n    <books>\n       <book type=""Children"">A beautiful day</book>\n    </books>\n  </author>\n  <author name=""John"">\n    <books>\n       <book type=""Fiction"">BBC</book>\n    </books>\n  </author>\n</authors>";\n\nXElement root = XElement.Parse(xml);\nvar query = from e in root.Elements("author")\n            group e by e.Attribute("name").Value into g\n            select new XElement("author", new XAttribute("name", g.Key),\n                   new XElement("books", \n                                 g.Select(x => x.Element("books").Elements("book")).ToArray()));\n\n XElement newRoot = new XElement("authors", query.ToArray());\n Console.WriteLine(newRoot);	0
12909660	12909487	building a tree from database	ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["id"],.Tables[0].Columns["parent_id"], false);	0
32988389	32988192	Update regex to select only some characterss	(?<=;\\"[^;]*)\\r\\n(?=[^;]*\\";)	0
4425403	4424100	Send data over the network C#	string response = "Hello";\nIPAddress ipAddress = IPAddress.Parse("127.0.0.1");\n\nif (ipAddress != null)\n{\n    IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 25);\n    byte[] receiveBuffer = new byte[100];\n\n    try\n    {\n        using (TcpClient client = new TcpClient(serverEndPoint))\n        {\n            using (Socket socket = client.Client)\n            {\n                socket.Connect(serverEndPoint);\n\n                byte[] data = Encoding.ASCII.GetBytes(response);\n\n                socket.Send(data, data.Length, SocketFlags.None);\n\n                socket.Receive(receiveBuffer);\n\n                Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));\n            }\n        }\n    }\n    catch (SocketException socketException)\n    {\n        Console.WriteLine("Socket Exception : ", socketException.Message);\n        throw;\n    }\n}	0
24677647	24632532	Filter a Gridview with a Combo Box Devexpress in mvc razor	settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;	0
2558921	2558787	How to modify existing XML file with XmlDocument and XmlNode in C#	// instantiate XmlDocument and load XML from file\nXmlDocument doc = new XmlDocument();\ndoc.Load(@"D:\test.xml");\n\n// get a list of nodes - in this case, I'm selecting all <AID> nodes under\n// the <GroupAIDs> node - change to suit your needs\nXmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");\n\n// loop through all AID nodes\nforeach (XmlNode aNode in aNodes)\n{\n   // grab the "id" attribute\n   XmlAttribute idAttribute = aNode.Attributes["id"];\n\n   // check if that attribute even exists...\n   if (idAttribute != null)\n   {\n      // if yes - read its current value\n      string currentValue = idAttribute.Value;\n\n      // here, you can now decide what to do - for demo purposes,\n      // I just set the ID value to a fixed value if it was empty before\n      if (string.IsNullOrEmpty(currentValue))\n      {\n         idAttribute.Value = "515";\n      }\n   }\n}\n\n// save the XmlDocument back to disk\ndoc.Save(@"D:\test2.xml");	0
18682300	18679254	Selecting all data from a MySQL database table based on a DateTimePicker value	"SELECT * FROM income_table WHERE income_date > = '" + dateShower.Value.Date.ToString("yyyyMMdd") + " 00:00:00" + "' and income_date <= '" + dateShower.Value.Date.ToString("yyyyMMdd") + " 23:59:59" + "'";	0
9754636	9754604	GetName for enum with duplicate values	Enum.GetName	0
5078383	5078086	Constructor parameter naming for clarity with passing in anonymous methods	var touchListener = new TouchListener();\ntouchListener.OnTouchDown += (v,e) => Console.WriteLine("Hehe, I said touchdown");\ntouchListener.OnTouchUp += (v,e) => Console.WriteLine("Mweh");	0
7470807	7470753	How I change this code to be in linq style	var argsPerCallforserialization = argsPerCall.Select\n     (argument => new object[] { argument[0], \n                                 argument[1],\n                                 argument[2],\n                                 ((McPosition)argument[3]).Station,\n                                 ((McPosition)argument[3]).Slot,\n                                 ((McPosition)argument[3]).Subslot })\n    .ToList();	0
12478671	12478637	Prevent window from snapping to screen edges	ResizeMode="NoResize"	0
13234003	13233088	Normalize a table with a two-column primary key and one other column	DataColumn.Expression	0
2462183	2462170	C#: Get IP Address from Domain Name?	Dns.GetHostAddresses	0
3562487	3562414	How to change the backcolor of a listview subitem using its own value	var item1 = new ListViewItem( "Item 1");\nitem1.SubItems.Add( "Color" );\nitem1.SubItems[1].BackColor = Color.FromArgb( -16711936 );\nitem1.UseItemStyleForSubItems = false;\n\nlistView1.Items.Add( item1 );	0
7177706	7177436	Regex pattern to match and replace a version number in a string c#	string val = "AA.EMEA.BizTalk.GroupNettingIntegrations, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a86ac114137740ef";\nval = Regex.Replace(val, @"Version=[\d\.]+", "Version=2.0.0.0");	0
16943033	16942147	C# PNG image with transparent zones as Button	public class TestControl : Control\n{\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        e.Graphics.Clear(System.Drawing.Color.Transparent);\n    }\n\n    protected override void OnPaintBackground(PaintEventArgs pevent)\n    {\n        pevent.Graphics.Clear(System.Drawing.Color.Transparent);\n    }\n}	0
24775387	24775222	How to get rows from a list containing each couple of value in LINQ?	List<Couple> lstcouple = new List<Couple>();\n            List<Stuff> lstStuff = new List<Stuff>();\n\n            var result = (from s in lstStuff\n                          join c in lstcouple on new { CS = s.CodeStuff, LS = s.LabelStuff } equals new { CS = c.Code, LS = c.Label }\n                          select s).ToList();	0
10090308	10089765	How to increase maximum processing jobs of crystal report in IIS7?	ReportDocument.Close();\nReportDocument.Dispose();	0
15109585	15109371	want to pass string as true is list have value	(.Count() > 0).toString();	0
11430042	11430007	Grabbing the parameters from a pushed URL in ASP.NET C#	string information = Request["information"];	0
612303	612283	How can I compound byte[] buffers into a List<byte>?	list.AddRange(buffer.Take(count));	0
24391952	24389210	LocalDate from month and day of week in NodaTime	public static LocalDate GetDay(int year, int month, IsoDayOfWeek dayOfWeek,\n                                                                    int instance)\n{\n    int daysInMonth = CalendarSystem.Iso.GetDaysInMonth(year, month);\n\n    var ld = new LocalDate(year, month, 1);\n    if (ld.IsoDayOfWeek != dayOfWeek)\n        ld = ld.Next(dayOfWeek);\n    for (int i = 1; i < instance && ld.Day + 7 <= daysInMonth; i++)\n        ld = ld.PlusWeeks(1);\n    return ld;\n}	0
1626261	1626146	How do I ask for an elevation for Registry access to HKLM?	[SecurityPermissionAttribute(SecurityAction.RequestMinimum, Assertion = true)]	0
24488816	24488573	Nested For loop in C#	for (int i= 7; i>=0; i--)\n{\n    if (i == 1)\n    {\n        Console.WriteLine(new string('C', i));\n    }\n    else\n    {\n        Console.WriteLine(new string('*', i));\n    }\n}\n\nfor (int j = 1; j<9; j++)\n{  \n    if (j == 7)\n    {\n        Console.WriteLine(new string('0', j));\n    }\n    else\n    {\n        Console.WriteLine(new string('*', j));\n    }\n}	0
24624334	24624142	xml to linq query where letter starts with a in windows phone	XDocument loadedCustomData = XDocument.Load("accounts.xml");\n    var filteredData =\n       from c in loadedCustomData.Descendants("record")\n       where ((string)c.Element("main")).StartsWith("A")\n       select new words()\n       {\n\n           PON = "Post Office: " + (string)c.Element("main"),\n           PIN = "Pincode (Postal Code): " + (string)c.Element("def"),\n\n       };\n    listBox1.ItemsSource = filteredData;	0
34323352	33900513	C# How to remove XPKeywords (PropertyItem 0x9c9e) from an image	...\nstring new_value = "New title for the image";\nPropertyItem item_title = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));\nitem_title.Id = 0x9c9b; // XPTitle 0x9c9b\nitem_title.Type = 1;\nitem_title.Value = System.Text.Encoding.Unicode.GetBytes(new_value + "\0");\nitem_title.Len = item_title.Value.Length;\nimage.SetPropertyItem(item_title);\nPropertyItem item_title2 = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));\nitem_title2.Id = 0x010e; // ImageDescription 0x010e\nitem_title2.Type = 2;\nitem_title2.Value = System.Text.Encoding.UTF8.GetBytes(new_value + "\0");\nitem_title2.Len = item_title2.Value.Length;\nimage.SetPropertyItem(item_title2);\n\nimage.Save("new_filename.jpg", ImageFormat.Jpeg)\nimage.Dispose();\n...	0
7236722	7236692	How to I change a form's data in ASP.NET/C# code behind on onclick?	Request.Form["keywords"]	0
8933002	8932818	How can HtmlHelper be used to create an external hyperlink?	namespace System.Web.Mvc {\n    public static class HtmlHelperExtensions {\n        public static MvcHtmlString Hyperlink(this HtmlHelper helper, string url, string linkText) {\n            return MvcHtmlString.Create(String.Format("<a href='{0}'>{1}</a>", url, linkText));\n        }\n    }\n}	0
21934326	18326936	How to Use IsolatedStorage to Set Lock Screen Background in Windows Phone 8	const string filePathOfTheImage = "/Shared/ShellContent/shot2.jpg"; //This is where my image is in isostore\n\nvar uri = new Uri("ms-appdata:///local" + filePathOfTheImage, UriKind.Absolute);	0
1862106	1862090	Read/Write compressed binary data	BitArray myBitArray = new BitArray(5);\nmyBitArray[3] = true; // set bit at offset 3 to 1	0
14953799	14953748	Insert space before number in PascalCase string	if (Char.IsLower(s[i - 1]) && (Char.IsUpper(s[i]) || Char.IsDigit(s[i])))	0
30375633	30375477	How to get current country location and possibly the CountryCode from a Windows Phone 8.1	var geolocator = new Geolocator();\n            geolocator.DesiredAccuracyInMeters = 100;\n            Geoposition position = await geolocator.GetGeopositionAsync();\n\n             //reverse geocoding\n            BasicGeoposition myLocation = new BasicGeoposition\n            {\n                Longitude = position.Coordinate.Longitude,\n                Latitude = position.Coordinate.Latitude\n            };\n            Geopoint pointToReverseGeocode = new Geopoint(myLocation);\n\n            MapLocationFinderResult result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);\n\n             //here also it should be checked if there result isn't null and what to do in such a case\n            string country = result.Locations[0].Address.Region;	0
24862204	24862030	returning a text\plain json response from a web api post	public string Post()\n    {\n           var response = GetModel();\n           string jsonRes = JsonConvert.SerializeObject(response);\n\n\n           return jsonRes ;\n    }	0
11730643	11730558	How to get nic card value from list in C#?	var selectedValues = listBox1.SelectedItem.ToString().Split('  ');\n\n    if (selectedValues.Length == 3)\n    {\n       var cardName = selectedValues[0];\n       MessageBox.Show(cardName);\n    }	0
13191231	13189980	Async WCF client calls with custom headers: This OperationContextScope is being disposed out of order	public async void TestMethod()\n{\n    var result = await CallServerAsync();\n}\n\npublic Task<Result> CallServerAsync()\n{\n    var address = new EndpointAddress(url);\n    var client = new AdminServiceClient(endpointConfig, address);\n\n    using (new OperationContextScope(client.InnerChannel))\n    {\n        OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = GetHeader();\n\n        var request = new MyRequest(...); \n        {\n            context = context,\n        };\n\n        return client.GetDataFromServerAsync(request);\n    }\n}	0
5419201	5418973	Variable Used In DataSource C#	"Data Source=" +variblename+ ";Initial Catalog=Northwind;Integrated Security=True"	0
1288747	1288718	How to delete all files and folders in a directory?	System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");\n\nforeach (FileInfo file in di.GetFiles())\n{\n    file.Delete(); \n}\nforeach (DirectoryInfo dir in di.GetDirectories())\n{\n    dir.Delete(true); \n}	0
32039893	32039780	C# combine to list in json object	var result = new List<matrix>();\nvar count = 1;\nforeach (var r in tmpRows)\n    foreach (var c in tmpCols)\n        result.Add(new matrix { id = (count++).ToString(), col = c, row = r });	0
10593535	10593515	Pattern matching in C# to remove series in parenthesis	^\s*(\([^)]*\)[\s-]*)+[\s-]*	0
33129491	33126864	How to transform a JSON array of objects to an object containing arrays	JObject obj = JObject.Parse(json);\n\nobj["data"] = new JObject(obj["data"]\n    .Children<JObject>()\n    .SelectMany(jo => jo.Properties())\n    .GroupBy(jp => jp.Name)\n    .Select(g => new JProperty(g.Key, new JArray(g.Values()))));\n\nConsole.WriteLine(obj.ToString());	0
22796232	22795924	Nodatime calculation of years/months/days in X days	var now = DateTime.Now;\nvar future = now.AddDays(678);\n\nint years = future.Year - now.Year;\nint months = future.Month - now.Month;\nif (months < 0)\n{\n    years--;\n    months += 12;\n}\nint days = future.Day + DateTime.DaysInMonth(now.Year, now.Month) - now.Day;	0
34028379	34026306	An encryption algorithm, allowing decryption of partially downloaded files	public void Crypt(byte[] data, string filepath)\n    {\n        // Define password and salt\n        byte[] pwd = GetBytes("PASSWORD");\n        byte[] salt = GetBytes("SALT");\n\n        // Generate PasswordDeriveBytes from the password and salt.\n        PasswordDeriveBytes pdb = new PasswordDeriveBytes(pwd, salt);\n\n        // Generate key from PasswordDeriveBytes\n        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();\n        tdes.Key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tdes.IV);\n\n        // Encrypt/Decrypt\n        for(int i = 0; i < data.Length; i++)\n        {\n            data[i] = (byte)(data[i] ^ tdes.Key[i % tdes.Key.Length]);\n        }\n\n        // Save File\n        File.WriteAllBytes(filepath, data);   \n    }	0
12291235	12290966	how to travel the multi value of javascript in c# variables dynamicaly	protected void Page_Load(object sender, EventArgs e)\n    {\n        if(Request.Form != null)\n        {\n            // Get username value.\n            string username = Request.Form["username"];\n\n            // Get the dynamic values and put in a list.\n            List<string> dynamicTextValues = new List<string>();\n            foreach (var key in Request.Form.Keys)\n            {\n                if (key.ToString().StartsWith("e"))\n                {\n                    dynamicTextValues.Add(Request.Form[key.ToString()]);\n                }\n            }\n\n            // Do what you need to do with your values.\n\n        }\n    }	0
5653484	5653440	Either of the Properties to be assigned with a value	public class MyClass \n{\nint one = -1;\nint two = -2;\n\npublic int One { get { return this.one; }\n                 set { if (this.two != -1 ) this.one == value; }}\n\npublic int Two { get { return this.two; }\n                 set { if (this.one!= -1 ) this.two== value; }}\n}	0
26845944	26845815	how to pass file as parameter to your program wpf c#	var args = Environment.GetCommandLineArgs();\nif (args.Length > 1)\n{\n    var fileName = args[1];\n    if (File.Exists(fileName))\n    {\n        var extension = Path.GetExtension(fileName);\n        if (extension == ".MyDocumentExtension")\n        {\n             // TODO: Open file from fileName\n        }\n    }\n}	0
1431626	1431614	Compare to list inside lambda expressions	List<MyObjectType> myObjectList = GetObjectValues();\n\nList<ValueType> valueList = GetValues();\n\nList<MyObjectType> filterdObjectList =\n             myObjectList.Where(x => valueList.Contains (x.objectProp))	0
19960046	19959877	how to update element name in a xml column in sql server	DECLARE @StackExample TABLE (\n     Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT(NEWID())\n    ,XmlColumn XML\n)\n\nINSERT INTO @StackExample(XmlColumn) VALUES('<info>\n  <StInfo>\n    <name>William</name>    \n    <address>India</address>    \n  </StInfo>\n</info>')\n\n\nUPDATE T\nSET XmlColumn = XmlColumn.query('<info>\n  <Student>\n  {info/StInfo/*}\n  </Student>\n</info>')\nFROM @StackExample t\n\nSELECT * FROM @StackExample	0
12251890	12251874	When to use a Parallel.ForEach loop instead of a regular foreach?	string[] lines = File.ReadAllLines(txtProxyListPath.Text);\nList<string> list_lines = new List<string>(lines);\nParallel.ForEach(list_lines, line =>\n{\n    //Your stuff\n});	0
8314071	8298337	How can i get the Text data from a Custom List View on Mono for android	var customer = customers[e.Position];	0
34205095	34204683	Removed Slashes in WPF Extended Toolkit DatePicker	var ci = new CultureInfo(CultureInfo.InvariantCulture.Name);\nThread.CurrentThread.CurrentCulture = ci;\nThread.CurrentThread.CurrentUICulture = ci;	0
10881131	10881033	How to access certain part of an XML?	xmldoc.DocumentElement	0
385383	385345	Is there a way to access a cache or session from a static method?	System.Web.HttpContext.Current.Cache	0
16984587	16984386	How to pass parameter to my custom filters	private paramType param;\n\npublic AuditAttribute(paramType param)\n{\n     this.param = param;\n}	0
7388426	7388403	How to keep data through postbacks?	public Dictionary<string, decimal> Results\n{ \n  get { return ViewState["Results"]; }\n  set { ViewState["Results"] = value; }\n}	0
7741548	7741530	exeption while import from excel using openXML	var workBookPart = document.WorkbookPart;\n\nif (workBookPart == null)\n{\n    // do something to report a problem\n}\n\nvar sharedStringTablePart = workBookPart.SharedStringTablePart;\nif (sharedStringTablePart == null)\n{\n    // report a problem\n}\n\nsharedStrings = sharedStringTablePart.SharedStringTable;	0
373797	373153	How do you implement constructor injection in a factory?	public interface IFooFormat\n{\n}\n\npublic class FooFormat<TValue> : IFooFormat\n{\n    private TValue _value;\n\n    public void Init(TValue value)\n    {\n        _value = value;\n    }\n\n    public TValue Value\n    {\n        get { return _value; }\n    }\n}\n\npublic class ArrayFooFormat : FooFormat<IList<string>> { }\n\npublic class BooleanFooFormat : FooFormat<bool> { }\n\npublic class DefaultFooFormat : IFooFormat { }\n\npublic interface IFoo { }\n\npublic class Foo : IFoo\n{\n    private IFooFormat _format;\n\n    internal Foo(IFooFormat format)\n    {\n        _format = format;\n    }\n\n    public IFooFormat Format { get { return _format; } }\n}\n\npublic class FooFactory\n{\n    protected IFoo Build<TFormat, TArg>(TArg arg) where TFormat : FooFormat<TArg>, new()\n    {\n        TFormat format = new TFormat();\n        format.Init(arg);\n        return new Foo(format);\n    }\n\n    protected IFoo Build<TFormat>() where TFormat : IFooFormat, new()\n    {\n        return new Foo(new TFormat());\n    }\n}	0
22697364	22697271	Adding a carriage return after XML ending closing tag?	string result = Regex.Replace(str, "</([^>]*)>", "</$1>" + Environment.NewLine);	0
798923	798913	2-Dimensional Array Reduction	int x = 4, y = 5;\nint[,] array = new int[x,y]; // assume we initialize this with some values\nfor (int i = 0; i < x && i < y; i++ ) {\n    array[i,i] = 0;\n}	0
13139793	13139595	array List Sorting according to the file extension	List<string> fileNames = new List<string>();\n        fileNames.Add("Form.frm");\n        fileNames.Add("Form1.frm");\n        fileNames.Add("Form2.frm");\n        fileNames.Add("Module.bas");\n        fileNames.Add("Module23.bas");\n\n        var ordered = fileNames.OrderBy(p => Path.GetExtension(p));	0
8492645	8492610	c# get property of element in list with mixed types	((Circle)list[index]).Radius = 10; // alternately use is or as if you're unsure	0
30912758	30911746	deserialize a list of Guid c#	List<Guid> guids = new List<Guid>();\nXmlDocument doc = new XmlDocument();\ndoc.Load(@"guids.xml");\nforeach(XmlNode guidNode in doc["content"].ChildNodes) {\n    guids.Add(Guid.Parse(guidNode.Name));\n}	0
2077144	2077122	Search XML doc with LINQ	XDocument doc = XDocument.Load("myxmlfile.xml");\n        XElement mainElement = doc.Element("Root")\n                                    .Elements("MainItem")\n                                    .First(e => (int)e.Attribute("ID") == 2);\n        // additional work	0
13092797	13092555	Creating a custom validation through DataAnnotations?	public class MyValidationAttribute: ValidationAttribute\n{\n   public MyValidationAttribute()\n   { }\n\n    protected override ValidationResult IsValid(\n           object value, ValidationContext validationContext)\n    {\n\n        ...\n        if (somethingWrong)\n        {\n            return new ValidationResult(errorMessage); \n        }\n        return null; // everything OK\n    }\n}	0
11926441	11925730	Bind dictionary of a class to data grid	DataGridColumn.Binding = new Binding(string.Format("[{0}].Data", item.Key));	0
27438872	27438827	Deleting items from a DropDownList in ASP.NET C#	DropDownList1.Items.Clear();	0
6414532	6414181	After creating a wcf service how do I tell whether its restful or soap from the wsdl?	public class StackOverflow_6414181\n{\n    [ServiceContract]\n    public interface ITest\n    {\n        [OperationContract]\n        [WebGet]\n        string Echo(string text);\n    }\n    public class Service : ITest\n    {\n        public string Echo(string text)\n        {\n            return text;\n        }\n    }\n    public static void Test()\n    {\n        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";\n        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));\n        host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });\n        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "soap");\n        host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "rest").Behaviors.Add(new WebHttpBehavior());\n        host.Open();\n        Console.WriteLine("Host opened");\n\n        Console.Write("Press ENTER to close the host");\n        Console.ReadLine();\n        host.Close();\n    }\n}	0
8280676	8280534	An empty Assembly Attribute element	private T GetAttributeByType<T>() where T : Attribute \n{ \n     object[] customAttributes = ActiveAssembly.GetCustomAttributes(typeof(T), false); \n     if ((customAttributes != null) && (customAttributes.Length > 0)) \n         return ((T)customAttributes[0]); \n     return Activator.CreateInstance<T>(); \n}	0
4176038	4170874	How to add an item from one datagrid to another then edit it in WPF	public MainWindow()\n    {\n        InitializeComponent();\n        dataGrid1.ItemsSource = idata;\n        dataGrid2.ItemsSource = dataGrid2Items;\n    }\n\n    private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        foreach (latlongobj item in dataGrid1.SelectedItems)\n        {\n            if( !dataGrid2Items.Contains( item ) )\n                dataGrid2Items.Add(item);\n        }\n\n    }\n\n    private ObservableCollection<latlongobj> idata = new ObservableCollection<latlongobj>\n        {\n            new latlongobj{ name = "n1", Lat = 1, Lon = 2 },\n            new latlongobj{ name = "n2", Lat = 2, Lon = 3 },\n            new latlongobj{ name = "n3", Lat = 4, Lon = 5 },\n        };	0
33109052	33108993	Multiple ComboBox with single DataSource	comboBox1.DataSource = new BindingSource(source, string.Empty);\ncomboBox2.DataSource = new BindingSource(source, string.Empty);	0
24996315	24915621	How to compare two generic objects with nested collections	foreach (var sourceElement in sourceElements) { numOfSourceElements++; }\n\nforeach (var compareToElement in compareToElements) { numOfCompareToElements++; }\n\nif (numOfSourceElements != numOfCompareToElements) isEqual = false;\n\nif (isEqual) \n{ \n    foreach (var sourceElement in sourceElements)\n    {\n        found = false;\n        foreach (var compareToElement in compareToElements) \n        {\n            if (IsSameAsRecursive(sourceElement, compareToElement, sameAsOptions, isEqual))\n            {\n                found = true;\n                break;\n            }\n        }\n        if (!found) break;\n    }\n    isEqual = found;\n}	0
13838829	13838534	Returning value from unkown type using FindControl in ASP.NET WebForms	private string GetControlValue(string controlId)\n{\n    var control = FindControl(controlId);\n    if(control is ITextControl)\n    {\n        return ((ITextControl) control).Text; // works also for the RadComboBox since it returns the currently selected item's text\n    }\n    else if(control is ICheckBoxControl)\n    {\n        return ((ICheckBoxControl)control).Checked.ToString();\n    }\n    else\n    {\n        return null;\n    }\n}	0
16331988	16331822	C# Extension Method to Calculate Position Between a Range	public static decimal ValueBetween(this decimal m, decimal lower, decimal upper = decimal.MaxValue)\n{\n    if (m < lower) return 0M;\n    if (m > upper) return upper - lower;\n    return m - lower;\n}	0
15223869	15223267	Efficient use of 'Directory.GetFiles' with 'StartsWith', 'Contains' and 'EndsWith' to filter file names	Directory.EnumerateFiles()	0
25709337	25709069	The maximum number of characters a TextBox can display	public Form1()\n{\n    InitializeComponent();\n\n    textBox1.Font = new System.Drawing.Font("Consolas", 32f); \n    G = textBox1.CreateGraphics();\n    for (int i = 0; i < 100; i++) textBox1.Text += i.ToString("0123456789");\n}\n\nGraphics G;\n\nprivate void button2_Click(object sender, EventArgs e)\n{   \n   for (int i = 0; i < 10; i++) textBox1.Text += i.ToString("x");\n   Console.WriteLine( textBox1.Text.Length.ToString("#0   ") \n       + G.MeasureString(textBox1.Text, textBox1.Font).Width);\n}	0
32629540	32629449	Unable to split a string using split() method	string data = "CE|2014-2015|ClassA";\nstring[] split = data.Split('|');\nstring Batch=split[1];\nstring Class = split[2];	0
13586297	13586152	Getting the Parent object in nested XML to Linq	foreach (var room in rooms)\n{\n    for (int i = 0; i < room.Employees.Count; i++)\n    {\n        room.Employees[i].Parent = room;\n    }\n}	0
25025174	24725579	How to remove a valueless query string parameter in C#	if (queryString.GetValues(null).Contains("ncr"))\n{\n    queryString.Remove(null);\n}	0
9522514	9522369	How use data annotations for verifying input particular type	[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]\npublic int? Number { get; set; }	0
17802541	17802451	How to open one window and close another on button click	frmLogin loginForm = new frmLogin();\n//Set the dialog result on login form depending on ok and cancel button\n\n//close the application if user wants to cancel\nif(loginForm.DialogResult == DialogResult.Cancel)\n   this.Close();	0
8291154	8291006	Return array values into listbox (C#)	this.listBox1.DataSource = object[];	0
6677615	6677533	How to avoid flickering in TableLayoutPanel in c#.net	TableLayoutPanel panel = new TabelLayoutPanel();\npanel.SuspendLayout();\n\n// add controls\n\npanel.ResumeLayout();	0
12227377	12225182	How to format a string as Vietnamese currency?	CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");   // try with "en-US"\n        string a = double.Parse("12345").ToString("#,###", cul.NumberFormat);	0
32723305	32612521	Set base URL of Windows Phone 8.1 WebView and use NavigateToString()	await wvSecurePay.InvokeScriptAsync("eval", new string[] { "document.getElementsByTagName('html')[0].innerHTML = '" + htmlToLoad + "';"})	0
34535956	34520590	How to Stream string data from a txt file into an array	static string[] ReadCatalogFromFile()\n{\n    var lines = new string[200];\n    using (var reader = new StreamReader("catalog.txt"))\n        for (var i = 0; i < 200 && !reader.EndOfStream; i++)\n            lines[i] = reader.ReadLine();\n    return lines;\n}	0
15073243	14960266	mailmerge with visto how to get each record of MailMerge.DataSource.DataFields	int nRecords = Doc.MailMerge.DataSource.RecordCount;\n\nfor (int i = 1; i <= nRecords; i++)\n{\n    Doc.MailMerge.DataSource.FirstRecord = i; //It doesn't work \n    Doc.MailMerge.DataSource.LastRecord = i; // it doesn't work\n    Doc.MailMerge.DataSource.ActiveRecord = (i == 1 ?   \n    Word.WdMailMergeActiveRecord.wdFirstDataSourceRecord :Word.WdMailMergeActiveRecord.wdNextDataSourceRecord);\n    Doc.MailMerge.DataSource.ActiveRecord = (i == nRecords ? Word.WdMailMergeActiveRecord.wdLastDataSourceRecord : Doc.MailMerge.DataSource.ActiveRecord);\n    dynamic fields = Doc.MailMerge.DataSource.DataFields;\n}	0
2803141	2802861	how can I validate column names and count in an List array? C#	for(int i = 0; i <= twoDeeArr[0].Count-1; i++)\n{\n     for(int j = 0; j <= twoDeeArr.Count-1; j++)\n     {\n          decimal.TryParse((decimal)twoDeeArr[i][j], out currentElections);\n     }\n}	0
12931340	12924748	Relative Path Connection String with NHibernate	var rawStr = Settings.CoreDatabaseConnectionString.ConnectionString;\n// retrieve the original connection string from config file\n\nvar conBuilder = new SqlConnectionStringBuilder(rawStr);\nconBuilder.AttachDBFilename = Path.GetFullPath(\n    Path.Combine(Environment.CurrentDirectory, "CoreDatabase.mdf"));\n// if you're doing this in a web environment, swap Environment.CurrentDirectory \n// for HttpRuntime.AppDomainAppPath\n\n_sessionFactory = Fluently.Configure()\n    .Database(MsSqlConfiguration.MsSql2008\n                  .ConnectionString(conBuilder.ToString())\n                  .ShowSql()\n    )\n// rest of your configuration...	0
24272916	24272757	Using a Repeater to display time punch data by day	SELECT\n  [1] Sun, [2] Mon, [3] Tue, [4] Wed, [5] Thr, [6] Fri, [7] Sat\nFROM (\n   SELECT\n     PunchTime,\n     PunchDay,\n     ROW_NUMBER() OVER(PARTITION BY PunchDay ORDER BY PunchTime) RowNumber\n   FROM @t\n   UNPIVOT(PunchTime for PunchType in (PunchIn,PunchOut) ) t1\n) t2\nPIVOT(MAX(PunchTime) FOR PunchDay IN ([1],[2],[3],[4],[5],[6],[7]) ) t3	0
3050160	3050144	Use Lambda in Attribute constructor to get method's parameters	public ActionResult Index(\n    [Documentation("the identifier...")]\n    int id,\n\n    [Documentation("The filter")]\n    string filter\n  )\n{\n    return ...;\n}	0
18787107	18786982	C# fetch data using Linq to Sql	using(var db = new DataContext())\n{\n    var studentes = db.Students.Where(s => s.FirstName == "MyName").ToList();\n}	0
1547961	1547933	How can I get the offset as a TimeSpan if I only have the time as a string, such as 09:00 AM	public static TimeSpan GetTimeSpanFormString(string strString)\n{\n    strString = strString.Trim();\n    string[] strParts = strString.Split(':', ' ');\n\n    int intHours, intMinutes;\n\n    if (strParts.Length != 3)\n        throw new ArgumentException("The string is not a valid timespan");\n\n    intHours = strParts[2].ToUpper() == "PM" ? Convert.ToInt32(strParts[0]) + 12 : Convert.ToInt32(strParts[0]);\n    intMinutes = Convert.ToInt32(strParts[1]);\n\n    return new TimeSpan(intHours, intMinutes, 0);\n}	0
13762465	13762338	Read files from a Folder present in project	string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt");\nstring[] files = File.ReadAllLines(path);	0
11277440	11277380	Read value from HTML node	This document already has a 'DocumentElement' node.	0
21801674	21794324	How to support both 'regular' and 'readable' urls in Web API attribute rouring?	[Route("api/product/barcode")] //expects values from query string\n[Route("api/product/barcode/{barcodeType}/{barcode}")] //expects value from route\npublic async Task<IHttpActionResult> GetProduct([FromUri] BarcodeSearchCriteria searchCriteria)	0
7583995	7513883	Get max x rows plus all row info per group by in mysql to linq	from a in ((from idsandvalue in db.idsandvalue whereidsandvalue.id1 == 1 &&\n\n    (from helper in db.idsandvalue\n    where\n      helper.id1 == idsandvalue.id1 &&\n      helper.id2 == idsandvalue.id2 &&\n      helper.value > idsandvalue.value\n    select new {\n      helper\n    }).Count() < 1\nselect new {\n  idsandvalue\n}))	0
19175477	19175053	Difficulties with using static functions and variables in C#	public static string NavigationCall(CustomNavigation objCustomNavigation)\n\n//Custom object.\npublic class CustomNavigation\n{\n  public string InputURL {get;set;}\n  public string FBaseURL{get;set;}\n  public string ExcludeParam{get;set;}\n  public string CurrentCategoryID {get;set;}\n  public string NavigationParameters{get;set;}\n}	0
27959097	27959067	taking just two digits of a Number of type double without rounding it	Math.Truncate(Nb * 100) / 100m	0
11969607	11969531	Error converting byte array to string in test	byte[] testArray = new byte[] { 49, 48, 48, 49 };	0
27036457	27012917	resx files - remove default file with no language	Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture	0
29486766	29486632	Look for a value in a DataTable column	if(dt.Rows.Cast<DataRow>().Any( x => (string)x["month"] == "yes"))\nboolMonth = true;	0
25115950	25115850	Filtering a Datatable with List c#	DataView cView = result.DefaultView;\nStringBuilder sb = new StringBuilder();\nbool first = true;\n\nforeach (string items in existingSites)\n{\n    if (first)\n    {\n        first = false;\n    }\n    else\n    {\n        sb.Append(" AND ");\n    }\n\n    sb.AppendFormat("Sites <> '{0}'", items);\n}\n\ncView.RowFilter = sb.ToString();\ndgvResult.DataSource = cView;	0
17544108	17543971	Horizontal Scrollbar in Google PDF Viewer	pdf {\n     overflow-x: hidden;\n}	0
11971780	11971525	Simple query, need help replacing some text	string username = (UserName.Text.Contains("mydomain\\")) ? UserName.Text.Replace("mydomain\\","") : UserName.Text;\nUserData userdata = Usermanager.Login(username, Password.Text, "DC=my,DC=domain,DC=co,DC=uk");	0
17677885	17676133	c++ call a c# DLL with Hashtable parameter	System::Collections::Hashtable	0
11066674	11066176	WPF: Sorting an XMLdataprovider at runtime	Listbox1.Items.SortDescriptions.Clear();\nListbox1.Items.SortDescriptions.Add(new SortDescription("TITLE", ListSortDirection.Descending));	0
31620749	27181125	How to hook Win + Tab using LowLevelKeyboardHook	[DllImport("user32.dll")]\n    static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);\n\n    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)\n    {\n        if (nCode == HC_ACTION)\n        {\n            var keyInfo = (Kbdllhookstruct) Marshal.PtrToStructure(lParam, typeof (Kbdllhookstruct));\n            if ((int) wParam == WM_KEYDOWN\n                && keyInfo.VkCode == VK_TAB\n                && (GetAsyncKeyState(Keys.LWin) < 0 || GetAsyncKeyState(Keys.RWin) < 0))\n            {\n                _mainForm.Text = "Win + Tab was pressed " + (++_winTabPressCounter) + " times";\n                return (IntPtr) 1;\n            }\n        }\n\n        return CallNextHookEx(_hookID, nCode, wParam, lParam);\n    }	0
16056486	16055039	How to Reduce the size of a speccific format string?	// create buffer\n    byte[] buffer = new byte[256];\n\n    // put values you need to send to buffer\n    buffer[0] = 0x0f;\n\n    // ... add another bytes if you need...\n\n    // send them\n    var comPort = new SerialPort();\n    comPort.Write(buffer, 0, 1); // 0 is buffer offset, 1 is number of bytes to write	0
23449641	23449405	Passing values from List to MS-Word table	List<string> YourList = new List<string>();\n//fill your list \n\nobject oMissing = System.Reflection.Missing.Value;        \n// get your table or create a new one like this\n// the number '2' is the rows number \nMicrosoft.Office.Interop.Word.Table myTable = oWordDoc.Add(myRange, 2,numberOfColumns)\nint rowCount = 2; \n//add a row for each item in a collection.\nforeach( var s in YourList)\n{\n   myTable.Rows.Add(ref oMissing)\n   // do somethign to the row here. add strings etc. \n   myTable.Rows.[rowCount].Cells[1].Range.Text = "Content of column 1";\n   myTable.Rows[rowCount].Cells[2].Range.Text = "Content of column 2";\n   myTable.Rows[rowCount].Cells[3].Range.Text = "Content of column 3";\n   //etc\n}	0
13194894	13192959	Transforming/Mapping models	abstract public class WeightUnit\n{\n    abstract public function convertValueToKilo(float value);\n    abstract public function convertValueToPounds(float value);\n}\n\npublic class Kilo extends WeightUnit\n{\n    public function convertValueToKilo(float value) {return value;}\n    public function convertValueToPounds(float value) {return value * 2.20462262;}\n}\n\npublic class Pounds extends WeightUnit\n{\n    public function convertValueToKilo(float value) {return value / 2.20462262;}\n    public function convertValueToPounds(float value) {return value;}\n}\n\npublic class Weight\n{\n    protected WeightUnit unit;\n    protected float value;\n\n    public function Weight(float value, WeightUnit unit)\n    {\n      //set the internal state\n    }\n\n    public function toKilo()\n    {\n       return new Weight(this.unit.convertValueToKilo(this.value), new Kilo());\n    }\n\n    public function toPounds()\n    {\n       return new Weight(this.unit.convertValueToPounds(this.value), new Pounds());\n    }\n}	0
9122545	9106588	detect checkboxlist checked more than 1 item	int numSelected = 0;\n\nforeach (ListItem li in CheckBoxList1.Items)\n{\n    if (li.Selected)\n    {\n        numSelected = numSelected + 1;\n    }\n}\n\nResponse.Write("Total Number Of CheckBoxes Selected:");\n\nResponse.Write(numSelected);	0
17656542	17656447	How to disable sorting in a Dictionary?	List<KeyValuePair<T1,T2>>	0
12280320	12280259	C# running a exe and waiting for it to close	Process proc = new Process();\n\n    private void myProcess_Exited(object sender, System.EventArgs e)\n    {\n        System.Diagnostics.Process proc1 = new System.Diagnostics.Process();\n        proc1.StartInfo.FileName = "C:\\windows\\SysWOW64\\shutdown.exe";\n        proc1.StartInfo.Arguments = "/l";\n        proc1.StartInfo.UseShellExecute = false;\n        proc1.StartInfo.RedirectStandardOutput = false;\n        proc1.Start();\n        Application.Exit();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        System.Diagnostics.ProcessStartInfo p = new System.Diagnostics.ProcessStartInfo(@"K:\App\pc\stub.exe");\n        p.Arguments = "-RunForever";\n        Process proc = new System.Diagnostics.Process();\n        proc.StartInfo = p;\n        proc.StartInfo.CreateNoWindow = true;\n        proc.EnableRaisingEvents = true;\n        proc.Exited += new EventHandler(myProcess_Exited);\n        proc.Start();\n    }	0
9301429	9301163	How to create dynamic ColumnDefinitions with relative width values?	. . .\nColumnDefinition c1 = new ColumnDefinition();\nc1.Width = new GridLength(1, GridUnitType.Star);\nColumnDefinition c2 = new ColumnDefinition();\nc2.Width = new GridLength(4, GridUnitType.Star);\nColumnDefinition c3 = new ColumnDefinition();\nc3.Width = new GridLength(1, GridUnitType.Star);\nColumnDefinition c4 = new ColumnDefinition();\nc4.Width = new GridLength(3, GridUnitType.Star);\nColumnDefinition c5 = new ColumnDefinition();\nc5.Width = new GridLength(1, GridUnitType.Star);\n. . .\ngrd.ColumnDefinitions.Add(c1);\n. . .	0
29414839	29414018	Linq to select rows with all included flags and no excluded flags	Dictionary<int, string> flags = new Dictionary<int, string> { /* ... */ };\nstring[] includes = ["A", "B"];\nstring[] excludes = ["C"];\nflags\n    .GroupBy(f => f.Id)\n    .Where(g =>\n        includes.All(i => g.Any(f => f.Flag == i)) &&\n        !excludes.Any(e => g.Any(f => f.Flag == e)))	0
14859423	14859369	include null check to find index in list	var index = someList.FindIndex(p => (p.Bla1 != null && p.Bla1.Id == Dto.Id) \n                                 || (p.Bla2 != null && p.Bla2.Id == Dto.Id));	0
4857170	4340475	Convert Object Array to another type array using Reflection	var finalType = GetFinalType();\nvar objArr = GetObjectArray();\nvar arr = Array.CreateInstance(finalType, objArr.Length);\nArray.Copy(objArr, arr, objArr.Length);	0
9283434	9283410	Using an array return from a function	creature = hiLow(creature);	0
4869108	4868984	How do you convert an int representing days-from-zero to DateTime?	var myBaseDate = new DateTime(2000,1,1);\n\nvar exampleNrOfDays = 37892;\nvar exampleDate = new DateTime(1970,1,1);\nvar offset = exampleDate - myBaseDate;\nvar offsetInDays = exampleNrOfDays - (int)offset.TotalDays;\n\n// Now I can calculate\n\nvar daysFromErlang = 30000; // <= example\nvar theDate = myBaseDate.AddDays(daysFromErlang - offsetInDays);	0
32883046	32882880	Set unicode encoding on all files in folder with c#	string text = File.ReadAllText("data.txt", Encoding.ASCII);\n        File.WriteAllText("data.txt", text, Encoding.Unicode);	0
23914341	23913840	write compressed xml data to a memory stream using gzipstream	writer.Close();\ngstream.Close();\nms.Close();   \n\nConsole.WriteLine("Data length: " + ms.ToArray().Length);	0
14209389	14206744	Is there a way to use EMail address as the Username?	using System.ComponentModel.DataAnnotations;\n\npublic class AccountCreateViewModel\n{\n    [DataType(DataType.EmailAddress)]\n    public string UserName { get; set; }\n    /* ... */\n}	0
17100925	17100894	How can I modify my code to get data from an array of objects in C#?	var myData = new List<Content>\n            {\n              new Content{Title = "Content 1", Text = "xx", ModifiedDate = DateTime.Now},\n              new Content{Title = "Content 2", Text = "AB", ModifiedDate = DateTime.Now},\n              new Content{Title = "Content 3", Text = "CC", ModifiedDate = DateTime.Now}\n            };	0
1498249	1498226	Formatting my string	string X = string.Format("'{0}','{1}','{2}'", foo, bar, baz);	0
4250983	4250906	StructureMap configure concrete classes whose interface names don't match	Scan(x =>\n  {\n  x.Convention<MyConvention>();\n  }	0
20042733	20041860	Access Rendered HTML from action in console app without making a web request	string template = "Hello @Model.Name! Welcome to Razor!";\n  string result = Razor.Parse(template, new { Name = "World" });	0
29113230	29112616	Error inserting row into MS Access DB programmatically (C#)	Like "%[A-Z]" Or Like "*[A-Z]"	0
15561532	15561420	Counting the number of words from a file	var wordCount = 0;\nvar line = sr.ReadLine();\nwhile( line != null ) {\n  for( var i = 1; i < line.Length; i++ ) {\n    // Count words\n  }\n  line = sr.ReadLine();\n}	0
8414062	8413644	Keeping a HttpHandler alive / flushing intermediate data	byte [] buffer = new byte[1<<16] // 64kb\nint bytesRead = 0;\nusing(var file = File.Open(path))\n{\n   while((bytesRead = file.Read(buffer, 0, buffer.Length)) != 0)\n   {\n        Response.OutputStream.Write(buffer, 0, bytesRead);\n         // can sleep here or whatever\n   }\n}\nResponse.Flush();\nResponse.Close();\nResponse.End();	0
10206643	10206049	Is it possible to bind different interfaces to the same instance of a class implementing all of them?	Bind<I1, I2, I3>().To<Impl>().InSingletonScope();	0
8944283	8944082	Padding value in the QueryString	if (Request.QueryString["Num"] != null)\n{\n    string num = Request.QueryString["Num"];\n    Request.QueryString["Num"] = num.PadLeft((num.Length + 3), '0');\n}	0
5373365	5373356	Shortcut to creating many properties all with default get / set body	public int MyInt { get; set; }	0
10484277	10304997	Moving Focus out of DataGrid on Enter key press on Last row in WPF MVVM?	private void dataGrid1_KeyUp(object sender, KeyEventArgs e)\n        {\n            DependencyObject dep = (DependencyObject)e.OriginalSource;\n            //here we find the Row is selected\n            //then we check is the row last row\n\n            while ((dep != null) && !(dep is DataGridRow) && !(dep is DataGridColumnHeader))\n            {\n                dep = VisualTreeHelper.GetParent(dep);\n            }\n\n            if (dep == null)\n                return;\n\n            if (dep is DataGridRow)\n            {\n                DataGridRow row= dep as DataGridRow;\n                //untill here we find the selected row and here we check if it\n                //the last row our focus go to next control after datagrid\n               if (row.GetIndex() == dataGrid1.Items.Count - 1)\n            {\n                dataGrid1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));\n                dataGrid1.UnselectAll();\n            }\n            }\n        }	0
5911352	5911186	WCF service - support for streaming files with Range: bytes support?	videoStream.Read(myByteArray, 0, myByteArray.Length)	0
18696949	18634795	Add filters from the filter dialog to the view	FilteredElementCollector viewCollector = new FilteredElementCollector(doc);\nviewCollector.OfClass(typeof(FilterElement));	0
19870230	19870191	How do i get the array beginning instead the end of it?	file_indxs = file_indxs + 1;\nif (file_indxs >= file_array.Length)\n{\n    file_indxs = 0;\n}	0
23662766	23662596	How does one make an animation without being forced for it to end in windows forms?	public void AnimateAction(Actions Action, int PositionX, int PositionY)\n        {\n            Thread AnimationThread = null;\n                AnimationThread = new Thread(new ThreadStart(() => AnimateAction(Action, PositionX, PositionY, 1500)));\n                AnimationThread.Start();\n        }\n\n        private void AnimateAction(Actions Action, int PositionX, int PositionY, int AnimationDuration)\n        {\n            if (form.Controls.InvokeRequired)\n            {\n                form.Controls.Invoke(new Action(AnimateAction), Action, PositionX, PositionY);\n             }\n             else\n             {\n                Control ActionAnimation = UiHandler.GetInstance().CreateActionItem(Action, PositionX, PositionY);\n                form.Controls.Add(ActionAnimation);\n                ActionAnimation.BringToFront();\n                form.Controls.Remove(ActionAnimation);\n               }\n\n\n        }	0
25596654	25591886	Google AdMob interstitial ads in windows phone 7	Microsoft PubCenter\nAd Duplex\ninMobi\nLeadbolt\nScoreoid\nMediabrix\nPreApps	0
6561727	6561697	Creating a nullable<T> extension method ,how do you do it?	public static bool IsLessThan<T>(this Nullable<T> t, Nullable<T> other) where T : struct\n{\n    return Nullable.Compare(t, other) < 0;\n}	0
25867320	25866888	How to check an internet connection in a Portable class library	private static ManualResetEvent evt = new ManualResetEvent(false);\n\npublic static bool CheckForInternetConnection()\n{\n  try\n  {\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");\n    request.UseDefaultCredentials = true;\n    request.BeginGetResponse(new AsyncCallback(FinishRequest), request);\n    evt.WaitOne();\n    return request.HaveResponse;\n  }\n  catch\n  {\n    return false;\n  }\n}\n\nprivate static void FinishRequest(IAsyncResult result)\n{\n  HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;\n  evt.Set();\n}	0
11179017	11178991	How do I create a user through membership without being logged into their account after creation?	Roles.AddUserToRole(model.Email, "Client"); \nFormsAuthentication.SetAuthCookie(model.Email, false /*create persistent cookie*/);	0
31798021	31797876	how to add all numbers of a string to array in C#?	string sentence = "there's 10 Apples, 8 Grapes, 120 Oranges, and 6363 Lemons.";\n       string[] words = sentence.Split(' ');\n       List<int> fruits = new List<int>();\n       for (int index = 0; index < words.Count(); index++)\n       {\n            int number;\n            if (int.TryParse(words[index], out number))\n            {\n                fruits.Add(number);\n            }\n        }	0
12798626	12798542	Control Failing To Enter The Method when Dynamically generated Buttons are clicked in WPF	Command="{Binding ElementName=SetButtonList, Path=DataContext.SetFreqCommand}"	0
4341481	4300884	How to get cell value in excel workbook project using c#?	private void ThisWorkbook_Shutdown(object sender, System.EventArgs e)\n{\n    Excel.Range show = Globals.Sheet8.Range["A6"];\n    MessageBox.Show(show.Text);\n}	0
28876800	28876319	Getting wrong array size in picturebox to byte array function	public byte[] imageToByteArray(System.Drawing.Image imageIn)\n        {\n            MemoryStream ms = new MemoryStream();\n            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);\n            return ms.ToArray();\n        }	0
14371073	14370989	How do I select nodes that use a default namespace?	XmlDocument doc= new XmlDocument();\ndoc.Load(filepath);\nXmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);\nm.AddNamespace("myns", "url1");\nXmlNodeList l = doc.SelectNodes("/myns:a/myns:b/myns:c", m);	0
898226	898187	How to use default XML serialization from within custom XML serialization methods	void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)\n{\n    // write xml decl and root elts here\n    var s = new XmlSerializer(typeof(MySerializableType)); \n    s.Serialize(writer, MyList);\n    // continue writing other elts to writer here\n}	0
25605075	25604888	copy first and second rows from table to another ? C#	insert into Table1 (Column1,Column2,..) select Top 2 Column1,Column2 From Table2	0
31028361	31028131	Pass Action<.., .., T > as Parameter without a predefined number of action parameters	Loop(t => doSomething(t, counter));\n\n Loop(t => doSomethingNext(t, Something));	0
22010987	22010089	How To Create New Line In txt File	protected void btn_Click(object sender, EventArgs e)\n    {\n        string text = txt1.Text + "" + txt2.Text+""+System.DateTime.Now;\n        string path=Server.MapPath("date.txt");            \n        File.AppendAllText(path, text + "\n");            \n    }	0
14294884	14294627	Eye and Mouth detection from face using haar-cascades	var faces = grayframe.DetectHaarCascade(\n                            haar, 1.4, 4,\n                            HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,\n                            new Size(nextFrame.Width / 8, nextFrame.Height / 8)\n                            )[0];\n foreach (var f in faces)\n {\n    //draw the face detected in the 0th (gray) channel with blue color\n    image.Draw(f.rect, new Bgr(Color.Blue), 2);\n\n\n     //Set the region of interest on the faces\n     gray.ROI = f.rect;\n     var mouthsDetected = gray.DetectHaarCascade(mouth, \n                              1.1, 10, \n                              Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, \n                              new Size(20, 20));\n     gray.ROI = Rectangle.Empty;\n\n\n     foreach (var m in mouthsDetected [0])\n     {\n          Rectangle mouthRect = m.rect;\n          mouthRect.Offset(f.rect.X, f.rect.Y);\n          image.Draw(mouthRect , new Bgr(Color.Red), 2);\n     }\n   }	0
2697855	2697232	C# How to add an entry to LDAP with multiple object classes	DirectoryEntry newUser = nRoot.Children.Add("CN=" + "test", "person");\nnewUser.Properties["cn"].Add("test");\nnewUser.Properties["sn"].Add("test");\nnewUser.CommitChanges();\n\nnewUser.RefreshCache();\nnewUser.Properties["objectClass"].Add("uidObject");\nnewUser.Properties["uid"].Add("testlogin");\nnewUser.CommitChanges();	0
13242858	13242808	Double an array size by altering its values in C#	string searches = "my test";\n            var split = searches.Split(new Char[] { ' ' });\n            var modifiedArray1 = split.Select(x => x + ":");\n            var modifiedArray2 = split.Select(x => x + ",");\n            split = split.Union(modifiedArray1).ToArray().Union(modifiedArray2).ToArray();\n            foreach (var s in split)\n            {\n                Console.WriteLine(s);\n            }	0
13819026	13818912	Pass Value from Button back to C# Controller from ASP.NET MVC 3 Razor Page	//view\n@using(Html.BeginForm("DoAccept"))\n{\n     <button name="decision" value="agree">I Agree</button>\n     <button name="decision" value="disagree">I disagree</button>\n}\n\n//controller\npublic ActionResult DoAcceptTC(string decision)\n{\n    //decision == "agree"\n}	0
13974216	13974137	How do I use ninject to inject a session object property?	public class PatientDxService\n{\n    private readonly ISessionManager _session;\n\n    public PatientDxService(ISessionManager session)\n    {\n        this._session = session;\n    }\n\n    public void DoStuff()\n    {\n        var patient = _session.GetPatient();\n        ...\n    }\n}	0
22793474	22733283	Twitter OAuth2 - using WinRT	async Task<HttpResponseMessage> GetToken(string key, string secret)\n    {\n        var oAuthConsumerKey = key;\n        var oAuthConsumerSecret = secret;\n        var oAuthUri = new Uri("https://api.twitter.com/oauth2/token");\n\n        HttpClient httpClient = new HttpClient();\n        var authHeader = string.Format("Basic {0}",\n        Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +\n        Uri.EscapeDataString(oAuthConsumerSecret))));\n        httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);\n\n        HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), new Uri("https://api.twitter.com/oauth2/token"));\n        msg.Content = new StringContent("grant_type=client_credentials");\n        msg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");\n\n        HttpResponseMessage response = await httpClient.SendAsync(msg);\n        return response;\n    }	0
20164317	20161918	C# Find string in List<string> in MongoDB	IMongoQuery searchQuery = Query.EQ("Relations.Parents.ParentList", objectID);	0
13342179	13342085	Get DateTime.DayOfWeek for specific culture	DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("ar-EG"))	0
3702065	3701217	stackoverflow exception in DataView row filter	foreach (string id in res)\n                {\n                    sbTheOr.Append(',');\n                    Guid guid = new Guid(id);\n                    sbTheOr.AppendFormat("Convert('{0}','System.Guid')",guid);\n                }\n\n                if (sbTheOr.Length > 0)\n                {\n                    // remove the first ,\n                    sbTheOr.Remove(0, 1);\n                    queryBuilder.AppendFormat(" and ItemID in ({0})",sbTheOr.ToString());\n                }	0
31717344	31716937	Get Number of days in a week	/// <summary> Get days in a week </summary>\n    /// <param name="year">Number of year</param>\n    /// <param name="month">Number of month. From 1 to 12</param>\n    /// <param name="week">Number of week. From 1 to 5</param>\n    /// <returns>Count of days</returns>\n    public static int DaysInWeek(int year, int month, int week)\n    {\n        var weekCounter = 1;\n        var daysCounter = 0;\n        var dayInMonth = DateTime.DaysInMonth(year, month);\n        for (var i = 1; i <= dayInMonth; i++)\n        {\n            ++daysCounter;\n            var date = new DateTime(year, month, i);\n            if (date.DayOfWeek == DayOfWeek.Sunday || i == dayInMonth)\n            {\n                if (weekCounter == week)\n                    return daysCounter;\n\n                weekCounter++;\n                daysCounter = 0;\n            }\n        }\n        return 7;\n    }	0
2541710	2541611	Do controls need to be defined in a web app or will .NET do it for you	Page.aspx.designer.cs	0
12751500	12751476	How to check the equality of two decimals with an acceptable error margin	if (Math.Abs(first - second) <= margin)	0
19288777	19288411	XPATH Needed from HTML Markup	//li[@class='Individual']/ul/li[last()]	0
18412583	18412184	Getting UIElement from Storyboard in Completed event Windows 8 App	sb.Completed += (s,e) => StoryboardCompleted(sb, i);\n\n ....\n\nprivate void StoryboardCompleted(Storyboard storyboard, Image image)\n{\n\n}	0
970584	970523	Generating XSD for serialized XML	[System.Xml.Serialization.XmlAttributeAttribute("schemaLocation",\n    Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]\nprivate string xsiSchemaLocation = "YourSchema.xsd";	0
26697554	26697510	ParseExact not parsing string with day, date with ordinal but no year	"dddd d\"th\" MMMM \"at\" HH:mm"	0
10270581	10224567	Set focus on winform after start	Activate()	0
2257797	2257677	How to identify if .net framework is installed in a system and it version using command prompt	%systemroot%\Assembly	0
14998073	14998038	SQLite database currently in use?	while (continueTrying) {\n   retval = sqlite_exec(db, sqlQuery, callback, 0, &msg);\nswitch (retval) {\n  case SQLITE_BUSY:\n    Log("[%s] SQLITE_BUSY: sleeping fow a while...", threadName);\n    sleep a bit... (use something like sleep(), for example)\n    break;\n  case SQLITE_OK:\n    continueTrying = NO; // We're done\n    break;\n  default:\n    Log("[%s] Can't execute \"%s\": %s\n", threadName, sqlQuery, msg);\n    continueTrying = NO;\n    break;\n}\n}\nreturn retval;	0
21036079	21036053	Select single column data from DataTable to list	claimNos = dtCpt.AsEnumerable()\n                .Select(s => s.Field<long>("CLAIM_NUMBER"))\n                .Distinct()\n                .ToList();	0
8344014	8343919	winforms panel hide and show	bool categorySelected = treeView1.SelectedNode.Name.Contains("cat");\nmenuItemPanel.Visible = !categorySelected;\ncategoryPanel.Visible = categorySelected;	0
21538700	21538588	Sending the current key to a create view in MVC	public ActionResult CreateAsset(int? id)\n{\n    Foo newFoo = new Foo();\n    ViewBag.AreaId = new SelectList(db.areas, "Id", "Name");\n    foo.ProjectId = id;\n    return View(newFoo);\n}	0
30030920	30030480	Downloading Spire.doc document from controller to view	public class WordController : Controller\n        {\n            public void Download()\n            {\n                byte[] toArray = null;\n                Document doc = new Document();\n                Paragraph test = doc.AddSection().AddParagraph();\n                test.AppendText("This is a test");\n                using (MemoryStream ms1 = new MemoryStream())\n                {\n                    doc.SaveToStream(ms1, FileFormat.Doc);\n                    //save to byte array\n                    toArray = ms1.ToArray();\n                }\n                //Write it back to the client\n                Response.ContentType = "application/msword";\n                Response.AddHeader("content-disposition", "attachment;  filename=Doc.doc");\n                Response.BinaryWrite(toArray);\n                Response.Flush();\n                Response.End();\n            }\n        }	0
13824638	13824391	EF5 and Lamba/Linq - how only Include some columns of related tables	public IQueryable<ItemSummary> GetAll()\n    {\n        IQueryable<ItemSummary> items = context.Items\n            .Select(c => new ItemSummary {\n                   FirstProfileName = c.UserProfile.FullName,\n                   SecondProfileName = c.UserProfile1.FullName,\n                   ScalarProp1 = c.ScalarProp1,\n                   ...\n                })\n            .AsQueryable();\n        return items;\n    }	0
10523164	10522879	How to add to array in C# dynamically	public class MyViewModel()\n{\n    private readonly List<string> _values = new List<string>();\n\n    public string[] Values { get { return _values.ToArray(); } }\n\n    public void AddValue(string value)\n    {\n        _values.Add(value);\n    }\n}	0
20141155	20141124	How to represent 0x12345678 in C#	public const uint PARAM_START_ENABLE = 0x2b15d3fa;	0
2670106	2670090	Regex Question to Grab Keys	\b(?<=\{\#)(.*?)(?=\#\})\b	0
13654050	13651404	One foreign key in one table for 2 different fields	CREATE TABLE family (\n    ID INTEGER PRIMARY KEY,\n    bird TEXT,\n    bird_mom INTEGER REFERENCES family(ID),\n    bird_dad INTEGER REFERENCES family(ID)\n)	0
29177237	29177126	LINQ collapse multiple rows into List	db.GroupContacts.GroupBy(r => r.Name)\n                .Select(group => new GroupEmailRecipients() \n                    { GroupName = group.Key, \n                      EmailRecipients = group.Select(x => new EmailRecipient()\n                          { \n                            FirstName = x.FirstName, \n                            LastName = x.LastName, \n                            Email = x.Email \n                          })\n                    });	0
23993337	23993284	Is there a way to tell Visual Studio to show certain member values by default while in debug mode?	[DebuggerDisplay("Name = {Name}, Id = {Id}")]\npublic class MyClass\n{\n    public string Name { get; set; }\n    public int Id { get; set; }\n}	0
29659075	29656933	How to send email using ASP.NET, C# and GMail	smtp.UseDefaultCredentials = false;	0
5825757	5825634	How to replace a page by date	if ((DateTime.Now.DayOfWeek == DayOfWeek.Friday && DateTime.Now.Hour >= 17) || \n                DateTime.Now.DayOfWeek == DayOfWeek.Saturday)\n            {\n                Response.Redirect("ApplicationDown.aspx");\n            }	0
30776207	30775269	ASP.NET Comparing data from Database	int getStartHour = DateTime.Now.Hour;\n        int weekDay= (int)DateTime.Now.DayOfWeek;\n bool value =    db.OpeninghoursSatz.Where(m => getStartHour >= m.Starttime  && getStartHour <= m.EndTime && m.weekday == weekDay).Any()\n\n    /// if everything is in int. or if in string \n     string getStartHour = DateTime.Now.Hour.ToString();\n        string weekDay= DateTime.Now.DayOfWeek.ToString();\n bool value =    db.OpeninghoursSatz.Where(m => getStartHour >= m.Starttime  && getStartHour <= m.EndTime && m.weekday == weekDay).Any();\n\nBut in this case for Thursday , we will get Thursday, but in Int we will get 4.	0
20503887	20503766	How do I do the following using only regex?	\[id={.*?}test6\]	0
29035034	29034902	String takes any value in c# Visual Studio	"class SecLevel \\n { \\n static void Main()\\n{Console.WriteLine(\"Hello World!\");}}"	0
34059612	34059008	Many threads to call same function, only one should make it	private readonly object _lock = new object();\nprivate bool _shuttingDown;\n\npublic void Shutdown()\n{\n    lock (_lock)\n    {\n        if (_shuttingDown) return;\n\n        _shuttingDown = true;\n    }\n\n    // do work here...\n}	0
8990147	8989981	Using recursion to create a path for child elements	public String getPath(Category cat)\n{\n    if (cat.ParentCategory == null) return cat.CategoryName;\n    return getPath(cat.ParentCategory) + "/" + cat.CategoryName;\n}	0
6159271	6159067	Is there a way to override the Json Seralizer for DateTime format in WCF 4.0	[DataContract]\npublic class MyType\n{\n    public DateTime MyDTProp { get; set; }\n    [DataMember(Name = "MyDTProp")]\n    private string strDate\n    {\n        get\n        {\n            return this.MyDTProp.ToString("yyyy/MM/dd");\n        }\n        set\n        {\n            this.MyDTProp = DateTime.Parse(value);\n        }\n    }\n}	0
49153	49147	How do I create a MessageBox in C#?	if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {\n     //some interesting behaviour here\n}	0
7190065	7189799	What is the regular expression in string that I want to parse?	(?<= )\S+/\S+(?= )	0
7530757	7530683	C# interfaces with same method name	TestClientRepository repo = new TestClientRepository();\n\nIRepository<ClientEmailAddress> addrRepo = repo;\nClientEmailAddress address = addrRepo.Find(10);\n\nIRepository<ClientAccount> accountRepo = repo;\nClientAccount accoutn = accountRepo.Find(5);	0
14517911	14517210	Asynchronous add element to list	int itemCount = listItem.Length;\nList<object> objectList = new List<object>();\nManualResetEvent[] resetEvents = new ManualResetEvent[itemCount];\n\nfor (int i = 0; i < itemCount; i++)\n{\n    var item = listItem[i];\n\n    resetEvents[i] = new ManualResetEvent(false);\n    ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>\n    {\n        object obj = getData(item);\n\n        lock (objectList)\n            objectList.add(obj);\n\n        resetEvents[(int)index].Set();\n    }), i);\n}\n\nWaitHandle.WaitAll(resetEvents);\nConsole.Write("Finish all");	0
15280693	15253908	Parse Java Map<string, string> from XML into C# Object	[XmlRoot("ConfigurationMap")]\npublic class ConfigurationMap\n{\n    [XmlArray("mapConfig")]\n    [XmlArrayItem("entry")]\n    public List<Entry> MapConfig { get; set; }\n\n}\n\n[XmlRoot("entry")]\npublic class Entry\n{\n    [XmlElement("string")]\n    public List<string> entry { get; set; }\n}	0
1721304	1721277	Textbox using password mode	txtbox1.Attributes.Add("value", "yourValue");\n\n\nTextBox_admin_password.Attributes.Add("value",showInfo.password);	0
22300411	22300073	File name validation quality	var invalidChars = Path.GetInvalidFileNameChars();\nvar fileNameChars = validFileName.ToCharArray();\n\nfor (int i = 0; i < fileNameChars.Length; ++i)\n    if (invalidChars.Contains(fileNameChars[i]))\n        fileNameChars[i] = '_';\n\nvalidFileName = new string(fileNameChars);	0
30877886	30877838	C# - How I can convert List to JSONObject	JsonConvert.SerializeObject(new { friends = friends });	0
554022	553990	How do I declare a method using Func<T, TResult> as input argument?	public static void Throws<T, TResult, TException>(Func<T, TResult> methodToExecute, T methodArgument) where TException : System.Exception	0
14563910	14563855	Add null values to a datagridview	dataGridView.DataSource = listOfPersons.Select(x => new { ForeName = x.ForeName, SurName = x.Surname, OrganisationName = x.Organisation == null ? "None" : x.Organisation.organName}).ToList();	0
3278346	3278314	How to marshall c++ char* to C# string using P/INVOKE	[DllImport ( @"UnamanagedAssembly.dll", CharSet = CharSet.Ansi)]\npublic static extern int Activate(\n    ref int numActivated, \n    [MarshalAs(UnmanagedType.LPStr)]StringBuilder eventsActivated);	0
22208515	22208413	C# - Random 6 digit number	Random generator = new Random();\n    String r = generator.Next(0, 1000000).ToString("D6");	0
12459380	12459133	converting a project based solution to projectless website asp.net	Default.aspx	0
33377898	33377762	How to give an employee a raise using arrays and loops	decimal[] UniqueSalary = { 30000, 40000, 50000, 55000, 60000 };\n        decimal raise = 0.0M;\n\n        Console.WriteLine("Please enter a raise amount");\n        raise = int.Parse(Console.ReadLine());\n\n        for (int i = 0; i < UniqueSalary.Length; i++)\n            UniqueSalary[i] += raise;\n\n        for(int i = 0; i < UniqueSalary.Length; i++)\n            Console.WriteLine(" {0}", UniqueSalary[i]);\n\n        Console.ReadLine();	0
3728164	3728116	DateTime Picker In WinForm How To Pick Time?	DateTimePicker.ShowUpDown = true;\nDateTimePicker.CustomFormat = "hh:mm";\nDateTimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Custom;	0
21073798	21073744	WPF MVVM Datagrid having Combobox update other column on selectedItem Change	OnPropertyChanged("<property Name>")	0
4324320	4324276	How to move object between dictionaries?	ProcessedDictionary = ProcessedDictionary\n    .Concat(\n        ActiveDictionary.Where(kvp => kvp.Value.Ready)\n    )\n    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);\n\nActiveDictionary = ActiveDictionary.Where(kvp => !kvp.Value.Ready)\n    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);	0
30815422	30814735	Get up-to-date facebook crawler ip list	using Whois.NET;\n...\nvar result = WhoisClient..Query("-i origin AS32934", "whois.radb.net");\n\nConsole.WriteLine("{0} - {1}", result.AddressRange.Begin, result.AddressRange.End);	0
8511496	8511189	AppDomain Shadow Copy Include referenced assemblies	[LoaderOptimization(LoaderOptimization.MultiDomain)]	0
18187409	18185967	Read JSON string as key value	using System;\nusing System.IO;\nusing Newtonsoft.Json;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var json = File.ReadAllText("input.txt");\n        var a = new { serverTime = "", data = new object[] { } };\n        var c = new JsonSerializer();\n        dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());\n        Console.WriteLine(jsonObject.data[0]);\n    }\n}	0
25890169	25889016	Formating programmatically Excel cells from Scientific numeric to Text with C#	cell.EntireColumn.NumberFormat = "@";	0
4429315	4429242	How to generate the unique id dynamically for one of the xml node while inserting data into the XML file?	var uniqueIdentifier = Guid.NewGuid();//Will be generate unique value	0
10100989	10100948	C# - Storing datatable values in an array	private void getData()\n        {\n            SqlCeConnection conn = new SqlCeConnection("data source='c:\\northwind.sdf'; mode=Exclusive;");\n            SqlCeDataAdapter da = new SqlCeDataAdapter("Select [Unit Price] from Products", conn);\n            DataTable dtSource = new DataTable();\n            da.Fill(dtSource);\n            DataRow[] dr = new DataRow[dtSource.Rows.Count];\n            dtSource.Rows.CopyTo(dr, 0);\n            double[] dblPrice= Array.ConvertAll(dr, new Converter<DataRow , Double>(DataRowToDouble));\n\n        }\n\n        public static double DataRowToDouble(DataRow dr)\n        {\n            return Convert.ToDouble(dr["Unit Price"].ToString());\n        }	0
10319951	10319739	How can I drag and drop a picture from Explorer onto a WPF control?	private void ImagePanel_Drop(object sender, DragEventArgs e)\n{\n\n  if (e.Data.GetDataPresent(DataFormats.FileDrop))\n  {\n    // Note that you can have more than one file.\n    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n\n    // Assuming you have one file that you care about, pass it off to whatever\n    // handling code you have defined.\n    HandleFileOpen(files[0]);\n  }\n}	0
8814604	8798671	How do i check if a file is password protected via 7zip?	SevenZipExtractor.SetLibraryPath(@"path\7-Zip\7z.dll");\nusing (var extractor = new SevenZipExtractor(fn1))\n{\n        if(extractor.Check()) { //is not password protected	0
21430846	21430546	Re-write LINQ outer join with method syntax	{\n    b.Title,\n    PublisherName = group.Any()?group.First().Name: "No publisher";\n}	0
20651514	20651457	how to navigate to a web page on a button click in windows phone application development	protected override void OnNavigatedTo(NavigationEventArgs e)\n        {\n           WebBrowserTask webBrowserTask = new WebBrowserTask(); webBrowserTask.Uri = new Uri("http://www.google.com"); webBrowserTask.Show(); \n        }	0
5881127	5880960	Characters Missing	TcpClient client = new TcpClient();\nclient.Connect(IPAddress.Parse("someip"), someport);\nNetworkStream stream = client.GetStream();\nbyte[] myWriteBuffer = Encoding.ASCII.GetBytes("some JSON");\nstream.Write(myWriteBuffer, 0, myWriteBuffer.Length);\n\nbyte[] readBuffer = stream.GetBuffer();\nConsole.WriteLine(Encoding.ASCII.GetString(bytes));	0
4888648	4888616	Assigning Label a value with for statement	Label1.Text = string.Format("My Items: {0}", mylist.Count);	0
25399560	25399045	Create an array from a file read	string filename = "test.txt"; // Use your filename here.\nint n = "text: ".Length;\n\nvar array = \n    File.ReadLines(filename)\n    .Select(item => item.Remove(0, n))\n    .ToArray();	0
28726790	28726347	Place every n-th character in string at n-7 position	var s =  "1110011011010000";\n    var window = 8; // the tail of string which is shoreter than 8 symbols (if any) will be ignored\n    System.Text.StringBuilder sb = new System.Text.StringBuilder(s);\n    for(int i = 0; i <= s.Length-window; i=i+window)\n    {\n        char c = sb[i+window-1];\n        sb.Remove(i+window-1,1);\n        sb.Insert(i,c);         \n    }\n    string result = sb.ToString();	0
15879660	15878373	DateTimePicker WinForm: Set value when validating updates value incorrectly	private void dateTimePicker1_Validating(object sender, CancelEventArgs e) {\n        this.BeginInvoke(new Action(() => dateTimePicker1.Value = DateTime.Now));\n    }	0
25300263	25298635	Any way to run events after clicking stop debugging button ? c# WPF	EnvDTE.DebuggerEvents _dteDebuggerEvents;\n\n_dteDebuggerEvents = VsObject.DTE.Events.DebuggerEvents;\n\n_dteDebuggerEvents.OnEnterDesignMode += _dteDebuggerEvents_OnEnterDesignMode;\n_dteDebuggerEvents.OnContextChanged += _dteDebuggerEvents_OnContextChanged;\n\n\nvoid _dteDebuggerEvents_OnEnterDesignMode(dbgEventReason Reason)\n{\n   switch (Reason)\n   {\n       case dbgEventReason.dbgEventReasonStopDebugging:\n             // do whatever you need here\n       break;\n   }\n}	0
16230629	16230454	Check if a string includes any of the string array elements	string[] words = text.Split();\nbool arraysContains = array1.Concat(array2).Any(w => words.Contains(w));	0
15405178	15405112	Lambda Expressions : Compiler Behaviour	the new value is reflected outside the expression body too. How is this possible considering the expression is actually in a different class.	0
31213559	31213273	how do i calculate number of list of strings from listbox and multiply	string output = "Fizz";\n\n// Loop from 1 to 10 for no reason\nfor (int a = 1; a <= 10; a++)\n{\n    // Add "Fizz" item to listbox 3 times if 'a' equals 3\n    if (a == 3)\n    {\n        for (int b = 1; b <= 3; b++)\n        {\n            listBox1.Items.Add(output);\n        }\n\n        // Multiply number of items in listBox with 3 for no reason and display it in textbox\n        textBox1.Text = (listBox1.Items.Count * 3).ToString();\n    }\n}	0
10923994	10923885	Hashing and keys on webfarms with MD5CryptoServiceProvider	Hash(key + message)	0
12662662	12662593	Adding a controller to NopCommerce	Controller/NOPCommerceController/SomeController.cs	0
904026	904021	How to use Guids in C#?	Guid.NewGuid()	0
2827135	2816073	Looking for a better design: A readonly in-memory cache mechanism	public class TreeNode : ITreeNode\n{\n    private bool _isReadOnly;\n    private List<ITreeNode> _childNodes = new List<ITreeNode>();\n\n    public TreeNode Parent { get; private set; }\n\n    public IEnumerable<ITreeNode> ChildNodes\n    {\n        get\n        {\n            return _isReadOnly ? _childNodes.AsReadOnly() : _childNodes;\n        }\n    }\n}	0
3252043	3251516	How to save image from another website programmatically?	private void GetImage(string url)\n        {\n                    Stream imageStream = new WebClient().OpenRead(url);\n                    Image img = Image.FromStream(imageStream);\n                    img.Save(@"C:\MyImage.jpg");\n        }	0
23779797	23777422	How to map to a destination with a complex type ctor parameter?	CreateProjectModel project = ...\n\nvar model = new Project(project.ProjectName, user);\nMapper.Map(project, model);	0
2864697	2856808	How do I add events to nested server controls? (ASP.Net)	public partial myControl:CompositeControl,INamingContainer\netc...	0
21994230	21994065	how can i do inserting data in sqlserver?	SqlCommand myCommand = new SqlCommand(@"INSERT INTO synreplace (word,syn) Values ('Wgord','Shyn')", myConnection);	0
10031100	10031067	Linq optional parameters	var query = edmxObject.Users.AsQueryable<Users>();\n\nif (! String.IsNullOrEmpty(model.FirstName)) {\n    query = from user in query\n            where user.FirstName.Contains(model.FirstName)\n            select user;\n}\nif (! String.IsNullOrEmpty(model.UserName) {\n    query = from user in query\n            where user.UserName.Contains(model.UserName)\n            select user;\n}\n\n// this will cause the query to execute get the materialized results\nvar result = query.ToList();	0
10263794	10263734	How to align text drawn by SpriteBatch.DrawString?	SpriteFont.MeasureString()	0
9161661	9161464	To align Outer grid and inner grid equally	DataGridViewColumn.GetPreferredWidth()	0
26461053	26460960	Multiple Parallel Threads In Custom Control	Task task1 = Task.Factory.StartNew(() => doStuff(list1));\nTask task2 = Task.Factory.StartNew(() => doStuff(list2)); \nTask.WaitAll(task1, task2);	0
25403217	25403097	Overriding GetHashCode() for value objects without fields	sealed class FirstRequestHeader : RequestHeader\n{\n    public static readonly FirstRequestHeader Value = new FirstRequestHeader();\n\n    private FirstRequestHeader()\n    {\n\n    }\n}	0
17019145	17019108	C# XML 'colon' in root name possible?	"site:"	0
3732864	3732808	Find index of number from a string in C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace IndexOfAny\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine("University of California, 1980-85".IndexOfAny("0123456789".ToCharArray()));\n        }\n    }\n}	0
29060569	29060476	From string to Dictionary key and value	// Your data\nstring values = "1,10,2,20,3,30";\n// Split string by comma\nstring[] splitted = values.split(',');\n\n// declare a new dictionary\nDictionary<int,int> dict = new Dictionary<int,int>();\n\n// for loop on the splitted data, the counter is increased by 2.\nfor(int i;i<splitted.Length,i+=2)\n{\n    //Parse the string data as integer and add it to the dictionary.\n    dict.Add(int.Parse(splitted[i]), int.Parse(splitted[i+1]))\n}	0
16797106	16796978	How to get filepath with Uri without "file:///"	Uri.LocalPath	0
16952449	16952398	Pass arguments from C# objects to SQL	private void button1_Click(object sender, EventArgs e)\n        {\n            sqlConnection1.Open();\n            sqlCommand1.Parameters.AddWithValue("@user",textBox1.Text);\n            sqlCommand1.Parameters.AddWithValue("@pass",textBox2.Text);\n            sqlCommand1.CommandText = "SELECT id,parola FROM ANGAJAT WHERE id='@user' AND    parola='@pass'";\n            if (sqlCommand1.ExecuteNonQuery()!=null)\n                MessageBox.Show("ESTE");\n            sqlConnection1.Close();\n        }	0
28721595	28721409	How do I pass a List from C# angular to Angular controller?	public JsonResult TestList()\n{\n    return this.Json(new List<int> { 1, 2, 3 });\n}	0
22535031	22534925	Using Button throwing a NullReferenceException; am I missing something?	StackPanel stackPanel = sender as StackPanel;\nif(stackPanel != null)\n{\n        if (stackPanel.Background.Equals(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0))))\n        {\n            stackPanel.Background = materiaColor;               \n            stckTeachersGuideClosed.Visibility = Visibility.Visible;\n            stckTeachersGuideOpened.Visibility = Visibility.Collapsed;\n        }\n        else\n        {\n            stackPanel.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));\n        }\n}	0
10500465	10495315	How to format serialization of IDictionary with DataContractSerializer?	[CollectionDataContract(Name = "Kenan", ItemName="Items", KeyName="Row", Namespace="spell", ValueName="Values")]\npublic class CustomRowList : Dictionary<RowXML, List<ColumnXML>>, IXmlSerializable \n{\n\n}	0
5052124	5052060	Maintaining scroll position after postback (possible problem with AJAX Control Toolkit)	Page.SetFocus(Control C)	0
3193379	3193315	How to programatically add a binding converter to a WPF ListView?	new Binding() { Converter = new MyAwesomeConverter() }	0
25520583	25520563	Casting a collection of a specific type to a string array	using System.Linq;\n\nstring[] addresses = items.Select(mailAddress => mailAddress.Address).ToArray();	0
16444595	16430169	Default Authorization role at Controller level and override at method	[MyAuth(Roles = "admin")]\npublic class ValuesController : ApiController\n{\n    [ExemptRoles]\n    public IEnumerable<string> Get()\n    {\n        return new string[] { "value1", "value2" };\n    }\n}\n\npublic class ExemptRolesAttribute : Attribute { }\n\npublic class MyAuthAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)\n    {\n        if (actionContext.ActionDescriptor\n                .GetCustomAttributes<ExemptRolesAttribute>().Any())\n            base.Roles = String.Empty;\n\n        base.OnAuthorization(actionContext);\n    }\n}	0
4856897	4821887	how can i remove the time from the datetime	if ((Request.Form["TARGET_DATE"] != null) && Request.Form["TARGET_DATE"] != "")\n    {\n        TargetDate = Request.Form["TARGET_DATE"];\n\n        IEnumerable<SelectListItem> tarDate =\n            from n in _db.ACTION_PLANs\n            select new SelectListItem\n            {\n                Selected = (TargetDate == n.TARGET_DATE.Date.ToString()),\n                Text = string.Format("{0:MM/dd/yyyy}", n.TARGET_DATE.Date),\n                Value = n.TARGET_DATE.ToString(),\n            };\n\n\n        ViewData["TARGET_DATE"] = tarDate;\n\n        predicate = predicate.And(p => p.TARGET_DATE.ToString() == TargetDate);	0
27919686	27919654	MVC C# - Sending multiple List in Json format	List<Chart> data1 = dashboard.CountbyDep();\nList<Chart> data2 = dashboard.CountbyDes();\nList<Chart> data3 = dashboard.CountbyCat();\nList<List<Chart>> allData = new List<List<Chart>>\n{\n  data1, data2, data3\n};\n\nreturn Json(allData, JsonRequestBehavior.AllowGet);	0
20953667	20943543	Format string of summary column in radGridView	this.radGridView1.SummaryRowsBottom.Add(new GridViewSummaryRowItem(new GridViewSummaryItem[]{\n                new GridViewSummaryItem("DecimalColumn", "{0:R #.##,##}", GridAggregateFunction.Sum)}));	0
30800724	30800234	Selecting driver dynamically from config file in selenium	DesiredCapabilities capability = new DesiredCapabilities();\ncapability.setBrowserName(browserName);  //browser value is dynamically taken\ncapability.setPlatform(platform);\ncapability.setVersion(version);\ndriver = new RemoteWebDriver(new URL(remoteURL),capability);\nreturn driver;	0
5085663	5084630	How to get a list of loaded EF4.0 properties of a disconnected object using reflection	foreach(var i in singleProperties)\n{\n  var reference = value.GetType().GetProperty(i.Name + "Reference");\n  var refValue = reference.GetValue(value, null);\n  var isLoaded = ((System.Data.Objects.DataClasses.EntityReference)(refValue)).IsLoaded;\n  if(isLoaded)\n  {\n  }\n}	0
5399387	5399287	using nhibernate, how would i construct a query that wants the most recent 50 rows	var orders = session.Query<Order>()\n    .OrderByDescending(x => x.LastUpdate)\n    .Take(50);	0
8288505	8288468	Move multiple sub folders to a different directory and keep the folder names	Directory.Move(subCurrentDirectory, \n    Path.Combine(\n        newDirectory, \n        Path.GetFileName(subCurrentDirectory)));	0
25955459	25955163	UI Doesnt update as expected in WPF MVVM application with Caliburn Micro and BusyIndicator control	public void Execute(CoroutineExecutionContext context)\n    {\n        Task.Factory.StartNew(() =>\n        {\n            object screen = null;\n            var shell = IoC.Get<IShell>();\n            if (_viewModel != null)\n            {\n                screen = _viewModel;\n            }\n            else\n            {\n                screen = !String.IsNullOrEmpty(_name)\n                    ? IoC.Get<object>(_name)\n                    : IoC.GetInstance(_screenType, null);\n            }\n            shell.ActivateItem(screen);\n            Completed(this, new ResultCompletionEventArgs());\n        });\n    }	0
6662309	6662082	hide log off link once logged in	FormsAuthentication.SignOut()	0
7387567	7387503	Get html input values in server side in asp.net	string[] vals = Request.Form["value"].Split('-');\nint a = int.Parse(vals[0]);\nint b = int.Parse(vals[1]);	0
13826092	13825485	How can I filter the results of a query using SQLite in a Windows Store Application?	ListaParole.ItemsSource = db.Table<wordlist_it>().Take(3);	0
6449311	6117276	How to skip the teardown section in Gallio/MbUnit from a test case	[Test]\n    public void Folder_GetPropertyType_Valid()\n    {\n        using (var folder = IntegrationUtil.GetFolder())\n        {\n            PropId pid = folder.Properties.ElementAt(FolderMockConstants.FOLDER_FIRST_ELEMENT);\n            Assert.AreEqual(FolderMockConstants.FOLDER_VALID_PROPERTY_TYPE, folder.GetPropertyType(pid));\n        }\n    }	0
13485899	13485856	Count how many words in each sentence	var sentences = "hello how are you. I am good. that's good.";\n\n        foreach (var sentence in sentences.TrimEnd('.').Split('.'))\n            Console.WriteLine(sentence.Trim().Split(' ').Count());	0
23652764	23652593	How to get values of selected Listbox item into Listview	private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        ListBox l = sender as ListBox;\n        var selectedvalue = l.SelectedItem.ToString();\n    }	0
18394299	18394193	Connection string data source path to access files from other projects	using System.Configuration;\n\nstring fileUploadDirectory = ConfigurationManager.AppSettings["FileUploadDirectory"];\n\n// using Substring(1) to skip the ~ that is stored in the database and is returned by GetfileURL()\nstring fullFilePath = Path.Combine(fileUploadDirectory ,daoWordPuzzle.GetfileURL().Substring(1))	0
13066405	13066367	Access each element in a list inside a where clause	var query = customerListWithIdAndName.Where(c =>\n   stringListWith2SemicolonSeparatedStrings.Any(\n       p => p.Split().Last() == c.Name));	0
24100178	24100090	c# how to completely disable a user button	private void button1_Click(object sender, EventArgs e)\n{\n    button1.Enabled = false;\n\n    BackgroundWorker worker = new BackgroundWorker();\n    worker.DoWork += (doWorkSender, doWorkArgs) =>\n    {\n        // You will want to call your external app here...\n        Thread.Sleep(5000);\n    };\n    worker.RunWorkerCompleted += (completedSender, completedArgs) =>\n    {\n        button1.Enabled = true;\n    };\n    worker.RunWorkerAsync();\n}	0
13562216	13562181	Is casting from MyObject[] to Object[] and then back again a bad code smell?	public interface IConnection<T>\n{\n  void Connect(string user, string pw, Action<T[]> onConnect);\n  void Disconnect();\n}	0
19706372	19705600	Eliminate special characters from CSV with C#	var withEncodedChars = "For example in the CSV file the are values such as There&#8217;s which should be There's or John&#8217;s which should be John's. This &#8217; is there instead of an apostrophe.";\n\nConsole.WriteLine(HttpUtility.HtmlDecode(withEncodedChars));	0
8927120	8924728	Fire button click event using a key combination in c#	private bool findShortCut(Control.ControlCollection ctls, Keys keydata) {\n        foreach (Control ctl in ctls) {\n            var btn = ctl as MyButton;\n            if (btn != null && btn.ShortCutKey == keydata) {\n                btn.PerformClick();\n                return true;\n            }\n            if (findShortCut(ctl.Controls, keydata)) return true;\n        }\n        return false;\n    }\n\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (findShortCut(this.Controls, keyData)) return true;\n        return base.ProcessCmdKey(ref msg, keyData);\n    }	0
28252530	28252082	How to change screen saver timeout and screensaverissecure in windows using c#	rundll32.exe user32.dll, UpdatePerUserSystemParameters	0
1947842	1947817	Match string to enumeration?	Enum.Parse(typeof(DaysOfWeek), yourStringValue, true);	0
399073	398871	Update all objects in a collection using Linq	collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();	0
7627228	7627185	How do I make a tooltip point at a specific label in C#?	toolTip.Show(string.Empty, label1, 0);\ntoolTip.Show("message", label1);	0
2570507	2570449	How to get the Time value from datetime picker	yourDate.ToString("t");	0
17357390	17357113	How to display WMI data in a DataGridView	ManagementClass mc = new ManagementClass("Win32_Service");\n\n  grid.Columns.Add(new DataGridViewTextBoxColumn());\n  grid.Columns.Add(new DataGridViewTextBoxColumn());\n  grid.Columns.Add(new DataGridViewTextBoxColumn());\n  grid.Columns.Add(new DataGridViewTextBoxColumn());\n\n  foreach (ManagementObject mo in mc.GetInstances())\n  {\n    object col1 = mo["Name"] != null ? mo["Name"].ToString() : null;\n    object col2 = mo["Description"] != null ? mo["Description"].ToString() : null;\n    object col3 = mo["DisplayName"] != null ? mo["DisplayName"].ToString() : null;\n    object col4 = mo["ServiceType"] != null ? mo["ServiceType"].ToString() : null;\n\n    grid.Rows.Add(new object[] { col1, col2, col3, col4 });\n  }	0
11315334	11314170	Getting a poster frame(thumbnail) with ffmpeg	public bool GetVideoThumbnail(string path, string saveThumbnailTo, int seconds)\n{\n    string parameters = string.Format("-ss {0} -i {1} -f image2 -vframes 1 -y {2}", seconds, path, saveThumbnailTo);\n\n    var processInfo = new ProcessStartInfo();\n    processInfo.FileName = pathToConvertor;\n    processInfo.Arguments = parameters;\n    processInfo.CreateNoWindow = true;\n    processInfo.UseShellExecute = false;\n\n    File.Delete(saveThumbnailTo);\n\n    using(var process = new Process())\n    {\n        process.StartInfo = processInfo;\n        process.Start();\n        process.WaitForExit();\n    }\n\n    return File.Exists(saveThumbnailTo);\n}	0
6231376	6231360	linq query to return distinct field values from a list of objects	objList.Select(o=>o.typeId).Distinct()	0
20395807	20394889	I did zoom in/out of image in a pictureBox but how do i avoid from the image to become distorted ?	double increment = 1.25;   \ndouble factor = 1.0;\nif (e.Delta >  0)\n    factor *= increment;\nelse\n    factor /= increment;	0
34020498	33949014	Two many-to-many relationships for one table	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Bus>().HasMany(b => b.Drivers).WithMany(d => d.Buses).Map(m =>\n            {\n                m.MapLeftKey("BusId");\n                m.MapRightKey("DriverID");\n                m.ToTable("BusDriverJoinTable");\n            });\n        modelBuilder.Entity<Bus>().HasMany(b => b.Lines).WithMany(l=>l.Buses).Map(m =>\n        {\n            m.MapLeftKey("BusId");\n            m.MapRightKey("LineID");\n            m.ToTable("BusLineJoinTable");\n        });\n    }	0
6495665	4008200	WPF DataGrid: Automatically re-sort on a DataGridTemplateColumn	SortDescription sortDescription = grdData.Items.SortDescriptions[0];\ngrdData.ItemsSource = null;\ngrdData.ItemsSource = Data;\ngrdData.Items.SortDescriptions.Add(sortDescription);	0
3445255	3440952	Plotting points for a projectile before a force is applied	s = s? + v?t + ?at?	0
31282883	31282625	How to make join between two entities, if entity framework doesn't map the junction entity?	public class TableAB\n{\n    [Key]\n    [Column(Order = 0)]\n    [ForeignKey("TableA")]\n    public int id_TableA { get; set; }\n\n    [Key]\n    [Column(Order = 1)]\n    [ForeignKey("TableB")]\n    public int id_TableB{ get; set; }	0
30782257	30776609	Simpler alternative for accessing master object from nested listview on XAF	public class NestedViewController : ViewController\n{\n    protected PropertyCollectionSource PropertyCollectionSource\n    {\n        get\n        {\n            return View is ListView ? ((ListView)View).CollectionSource is PropertyCollectionSource ? ((ListView)View).CollectionSource as PropertyCollectionSource : null : null;\n        }\n    }\n\n    protected object MasterObject\n    {\n        get\n        {\n            return PropertyCollectionSource != null ? PropertyCollectionSource.MasterObject : null;\n        }\n    }\n}	0
2700497	2700435	Writing XMLDocument to file with specific newline character (c#)	XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.OmitXmlDeclaration = true;\nsettings.NewLineOnAttributes = true;\n\nwriter = XmlWriter.Create(Console.Out, settings);\n\nwriter.WriteStartElement("order");\nwriter.WriteAttributeString("orderID", "367A54");\nwriter.WriteAttributeString("date", "2001-05-03");\nwriter.WriteElementString("price", "19.95");\nwriter.WriteEndElement();\n\nwriter.Flush();	0
3993779	3993765	maximum value for timer	Int32.MaxValue	0
2982520	2982353	How do I stop the designer from filling in my properties with null values?	[DefaultValue(null)]	0
34177642	34177564	Reading XML with XPath - getting XPathException	XPathNavigator nav;\nXPathDocument docNav;\n\nstring sampleXML = @"C:\\sample.xml";\nstring ThumbnailXpath = @"//ern:NewReleaseMessage/media/asset/thumbnailURL/text()";\n\nXmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());\nnsm.AddNamespace("ern", "http://ddex.net/xml/ern/37");\n\ndocNav = new XPathDocument(sampleXML);\nnav = docNav.CreateNavigator();\nthumbnailURL = nav.SelectSingleNode(ThumbnailXpath, nsm).Value;	0
3486564	3486560	how to find a file is System file or hidden file?	var att = File.GetAttributes(@"c:\file.txt");\nif ((att & FileAttributes.Hidden) == FileAttributes.Hidden) \n{\n    // the file is hidden\n}\n\nif ((att & FileAttributes.System) == FileAttributes.System)\n{\n    // the file is system\n}	0
9767805	9767303	Select 2nd column of stored procedure's output	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    if(row.Cells["Name of the field"].Value != DBNull.Value)\n    {\n        string Myval = row.Cells["Name of the field"].Value;\n    }\n}	0
29741048	29739990	Get token expiration time From ArcGIS Online	var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\nreturn epoch.AddMilliseconds(longValue).ToLocalTime();	0
6227573	6227400	MonoTouch printing a local PDF file	RunOnce.ini	0
18470779	18469945	How to load/unload Word Add-in programatically?	foreach (COMAddIn addin in Globals.ThisAddin.Application.COMAddins)\n{\n  if (**specify your own condition**)\n    {\n        addin.Connect = true;\n    }                       \n}	0
10422733	10418538	I can't seem to populate a Textbox with the Model's property value	ModelState.Clear();	0
17731362	17731058	Is there a way to cast this enum to proper type	void SetOptions()\n{\n    DropDownList.Items.Clear();\n\n    var options = Enum.GetValues(ListType); // need to cast this to type of ListType\n\n    foreach (var o in options)\n    {\n        var item = new ListItem(o.Description(), o.ToString());\n        item.Tag = o;\n\n        DropDownList.Items.Add(item);\n    }\n}	0
28466351	26966882	Can we throw a custom exception from catch block?	throws new ExceptionType(parameter);	0
17682311	17681538	Memory efficient way to add part of an Array to an List	MemoryStream bundleData = new MemoryStream();\nbundleData.Write(fileData, startIndex, endIndex - startIndex + 1);	0
12302773	12302657	Count of flattened parent child association in LINQ	int customerAndOrdersCount = customers.Sum(c => c.Orders==null ? 1 : Math.Max(1, c.Orders.Count()));	0
6106685	6106671	Adding DateTime in C#	DateTime newDate = DateTime.Today.AddDays(10);	0
6560935	6560903	How do I use Color[] Colors in C#?	Bitmap bitmapToColorize = new Bitmap(@"C:\bitmap.bmp");\n        Color[] colors = new Color[2];\n        colors[0] = Color.Blue;\n        colors[1] = Color.Green;\n\n        Colorize(bitmapToColorize, colors);	0
18246902	18237404	How to deserialize JSON with fixed type header and variant type body in C#?	public static dynamic[] Deserialize(Type headerType, Type bodyType, string json)\n    {\n        var root = Newtonsoft.Json.Linq.JObject.Parse(json);\n        var serializer = new Newtonsoft.Json.JsonSerializer();\n\n        dynamic header = serializer.Deserialize(root["Header"].CreateReader(),headerType);\n        dynamic body = serializer.Deserialize(root["Body"].CreateReader(), bodyType);\n\n        return new dynamic[] { header, body };\n    }	0
11594969	11593453	How I get Informations of a ListView Item for a Session	protected void Button1_Command(object sender, CommandEventArgs e)\n    {\n        if (e.CommandName == "Anzeigen")\n        {\n          //Here I need a Session and the Informations about the Selected User in the Line\n            Label lb = (Label) myListView.Items(1).FindControl("Label2"); // give the right index, Label2 contains the email so give its ID but index should be correct\n            string email = lb.Text;\n            Response.Redirect("Benutzer.aspx");\n\n        }\n}	0
19800532	19800356	How to shut down a second UI thread	/// <summary>Show or hide the simulation status window on its own thread.</summary>\nprivate void toggleSimulationStatusWindow(bool show)\n{\n    if (show)\n    {\n        if (statusMonitorThread != null) return;\n        statusMonitorWindow = new AnalysisStatusWindow(ExcelApi.analyisStatusMonitor);\n        statusMonitorThread = new System.Threading.Thread(delegate()\n        {\n            Application.Run(statusMonitorWindow);\n        });\n        statusMonitorThread.Start();\n    }\n    else if (statusMonitorThread != null)\n    {\n        statusMonitorWindow.BeginInvoke((MethodInvoker)delegate { statusMonitorWindow.Close(); });\n        statusMonitorThread.Join();\n        statusMonitorThread = null;\n        statusMonitorWindow = null;\n    }\n}	0
5237602	5237580	casting to int in c#	string s = "36";\nint resultInt;    \nint.TryParse(s, out resultInt);	0
30426965	30426899	C# How to SELECT row n in EF6	var person = context.Persons.Skip(5).Take(10)	0
1624886	1623606	SQLCe local db in temp- path in connectionstring?	string connString = string.Format("Data Source={0}; Persist Security Info=False;",\n    Path.Combine(Application.StartupPath, "database.sdf"));	0
32254433	32254118	How to get a list of all redirected URLs using HttpClient in C#	public static string GetRedirectedUrls(string url)\n{\n    StringBuilder sb = new StringBuilder();\n    while (!string.IsNullOrWhiteSpace(url))\n    {\n        sb.AppendLine(url);\n        HttpWebRequest request = HttpWebRequest.CreateHttp(url);\n        request.AllowAutoRedirect = false;\n        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n        {\n            url = response.GetResponseHeader("Location");\n        }\n    }\n\n    return sb.ToString();\n}	0
11351459	11271057	How to use moq to verify that a similar object was passed in as argument?	_repositoryStub\n    .Setup(x => x.Create(\n        Moq.It.Is<Account>(a => _maskAccount.ToExpectedObject().Equals(a))))\n    .Returns(_account);	0
17273969	17273909	How to get program file location?	Image imageNormal = Image.FromFile("Resources\\button_Image.png");\ncontrolName.Image = imageNormal;	0
18547139	18546919	How to display Object with sub-class in PropertyGrid	private subInfo1 _sub1;        \n    [CategoryAttribute("SubInfo")]\n    [TypeConverter(typeof(ExpandableObjectConverter))]\n    public subInfo1 SubInfo1\n    {\n        get { return _sub1; }\n        set { _sub1 = value; }\n    }\n    private subInfo2 _sub2;\n    [CategoryAttribute("SubInfo2")]\n    [TypeConverter(typeof(ExpandableObjectConverter))]\n    public subInfo2 SubInfo2\n    {\n        get { return _sub2; }\n        set { _sub2 = value; }\n    }	0
13223382	13222998	Calling external HTTP service using HttpClient from a Web API Action	// GET api/values\n    public async Task<IEnumerable<string>> Get()\n    {\n        var result = await GetExternalResponse();\n\n        return new string[] { result, "value2" };\n    }\n\n    private async Task<string> GetExternalResponse()\n    {\n        var client = new HttpClient();\n        HttpResponseMessage response = await client.GetAsync(_address);\n        response.EnsureSuccessStatusCode();\n        var result = await response.Content.ReadAsStringAsync();\n        return result;\n    }	0
3521222	3433888	How to protect the webpage	//In Login.aspx\nContext.Items["userName"] = myValue;\nServer.Transfer("Account.aspx");\n\n//In Account.aspx\nprotected void Page_Load(object sender, EventArgs e)\n{\n   if (!IsPostback)\n   {\n      if (UserName == null)\n      {\n         UserName == Context.Items["userName"];\n      }\n      if (UserName == null)\n      {\n         Server.Transfer("Login.aspx");\n      }\n   }\n}\n\n    private String UserName\n    {\n        get\n        {\n            if (ViewState["UserName"] != null)\n            {\n                return ViewState["UserName"].ToString();\n            }\n            else\n            {\n                return null;\n            }\n        }\n        set\n        {\n            ViewState["UserName"] = value;\n        }\n    }	0
30857635	30857361	Preventing a class method from executing more than once at a time	public class CAImportService: ICAImportService\n{\n\n    // OTHER METHODS AND SECTIONS REMOVED FOR CLARITY\n\n    // Define static object for the lock\n    public static readonly object _lock = new object();\n\n    /// <summary>\n    /// Import products from tab delimited file\n    /// </summary>\n    /// <param name="fileName">String</param>\n    public virtual void ImportProducts(string fileName, bool deleteProducts)\n    {\n        lock (_lock)\n        {\n            //Do stuff to import products\n        }\n    }\n}	0
32436753	32436424	Windows Forms - How to return WMIC output into Textbox	ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS");\n        ManagementObject obj = searcher.Get().Cast<ManagementObject>().FirstOrDefault();          \n\n            textBox.Text =  (string)obj["SerialNumber"];	0
16233111	16232927	Convert control to html	public static string RenderView(string path, object data)\n{\n    Page pageHolder = new Page();\n    UserControl viewControl = (UserControl) pageHolder.LoadControl(path);\n\n    if (data != null)\n    {\n        Type viewControlType = viewControl.GetType();            \n        FieldInfo field = viewControlType.GetField("Data");\n\n        if (field != null)\n        {\n            field.SetValue(viewControl, data);\n        }\n        else\n        {\n            throw new Exception("View file: " + path + " does not have a public Data property");\n        }\n    }\n\n    pageHolder.Controls.Add(viewControl);\n\n    StringWriter output = new StringWriter();\n    HttpContext.Current.Server.Execute(pageHolder, output, false);\n\n    return output.ToString();\n}	0
23405422	23405373	How to run a reminder every Friday only once in wp8	//execute every day only once\n   if (DateTime.Now.DayOfWeek == DayOfWeek.Friday && storedDate <> DateTime.Today)\n   {\n       //How to Launch the reminder or notification only once\n   }	0
3778468	3777893	Regarding scope of some variable	public void processSomeRequest()\n{\n\n   string firstVariable = null;\n   string secondVariable = null;\n   int someInt = 0;\n\n   try\n   {\n       // Initialise variables\n       firstVariable = "test";\n       secondVariable = "blah";\n\n       // Process request code\n   }\n   catch(Exception e)\n   {\n       logException(e);\n       throw;\n   }\n\n}	0
19321073	19318661	View state use for optimization in Asp .Net GridView	if(!Page.IsPostBack)	0
7078694	7078641	ASP NET - C#: Access controls by Id	TextBox tb1 = (TextBox)FindControl(name_id)	0
31854097	31849771	(AutoMapper) How to map an object witch has a list of differents objects?	AutoMapper.CreateMap<LearningElementModel, LearningElement>()\n    .Include<CourseModel, Course>()\n    .Include<MultipleChoiceQuestionModel, MultipleChoiceQuestion>();	0
3427587	3355434	How to split list into LINQ groups and get biggest value in group	var plotsByDegree = plots.ToLookUp(polar => RadToDeg(polar.Bearing));\n\nreturn Enumerable.Range(0,360)\n                 . Select(degree => plotsByDegree.Contains(degree) ? plotsByDegree[degree].Max (polar => polar.SlantRange) : 0);	0
31334183	31333982	Background color in GridView	dataGridView1.Rows.OfType<DataGridViewRow>()\n                  .Where(x => Convert.ToString(x.Cells["Switch"].Value) == "L").ToList()\n                  .ForEach(x => x.DefaultCellStyle.BackColor = Color.Yellow);	0
2721251	2720266	Entity Framework: insert with one-to-one reference	Context.AddTo...	0
14964594	14964502	Is it possible to create a method that returns one of two possible types?	void MethodThatDoesAllTheLogic(Action<string, string> addFunc)\n{\n    // ...\n    addFunc(key, value);\n    // ...\n}\n\npublic Dictionary<...> PopulateDictionary()\n{\n    // ...\n    MethodThatDoesAllTheLogic(result.Add);\n}	0
27612627	27605617	Animate buttons (slide left, slide right, slide down) in unity3d v4.6	static float y0;\nstatic float FadeInOutTime = 1.0f;\n\n//Called in Awake()\ny0 = GameObject.Find("button_home").transform.position.y;\n\npublic static IEnumerator AnimateIn ()\n{\n    int i = 0;\n\n    foreach (var item in ToolbarButtons) {\n        var pos = item.transform.position;\n        iTween.MoveTo(item, new Vector3(pos.x, y0 + 6, pos.z), FadeInOutTime);\n        yield return new WaitForSeconds (i * 0.02f);\n        i++;\n    }\n    yield return null;\n}	0
5674125	5674044	how to bind a datagrid?	Insurance oInsurance = new Insurance();\nList<Value> lstValue = oInsurance.Category.ValueList;\n\ngrdCategory.DataSource = lstValue;\ngrdCategory.AutoGenerateColumns = true; //not sure that's the property\ngrdCategory.DataBind();	0
216550	216538	How do I format to only include decimal if there are any	decimal one = 1000M;\n    decimal two = 12.5M;\n\n    Console.WriteLine(one.ToString("0.##"));\n    Console.WriteLine(two.ToString("0.##"));	0
8354946	8354615	Request[variable] - weird behavior	var value = string.Format("{0}={1}|", channel.Alias, Request[channel.Alias]);\n\nmyProducts = myProducts.Where(p => !string.IsNullOrEmpty(p.Tags) && p.Tags.Contains(value));	0
13534379	13534321	displaying X number of items from a list	int lastPosition;\n\nvoid list(Boolean nextPage) {\n    if(!nextPage) {\n        lastPosition = 0;\n    }\n    Console.WriteLine("Press numbers 1 - 3 to display more info on an item or press 4 for next page...\r\n");\n    foreach (Item item in _items.Skip(lastPosition).Take(3))\n    {\n        Console.WriteLine((count + 1) + ": Name: " + item.itemName + ", ");\n    }\n    lastPosition += 3;\n    Console.WriteLine(("4: Next Page");\n}	0
7146336	7146058	asp mvc action needs to accept parameter with full stop in the name`	public JsonResult TestAction([Bind(Prefix="foo.bar")]string foobar)	0
15706696	15706595	Launching Winform App Using Static Form Variable	[STAThread]\n   static void Main()\n   { \n        MainUI form = new MainUI();\n        AppDomain.CurrentDomain.UnhandledException += (s,e)=> {\n            form.SetBusyState(false);\n        };\n        Application.ThreadException += (s,e)=> {\n            form.SetBusyState(false);\n        };  \n        Application.Run(form);\n    }	0
21375835	21375771	Checking items in two lists	if(!distSPUItem.Any(i => i.ID == prodSubstitute[count].id))\n{\n    // perform something here\n}	0
26023620	26023563	Need Help Fixing A Bug In Snake Game	if (direction != Direction.Right)\n   intendedDirection = Direction.Left;\n\n...\n\nOnTimerTick()\n{\n    ...\n    direction = intendedDirection;\n}	0
17961695	17961288	How to make link button on grid view invisible when I click on it?	protected void gridview__RowCommand(object sender, GridViewRowEventArgs e)\n{\n\n\n        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);\n        LinkButton lnkbtn = (LinkButton)row.FindControl(?lnkbtnActionNames?);\n        lnkbtn .Visible = false;\n\n\n}	0
20352455	20351882	Replacing certain value in a Dataset	for (int i = 0; i < sampleDataSet.Tables[0].Rows.Count; i++) \n{\n    for (int j = 0; j < sampleDataSet.Tables[0].Columns.Count; j++)\n    {\n        if (sampleDataSet.Tables[0].Rows[i][j].ToString() == "01/01/1754 00:00:00") \n        {\n            sampleDataSet.Tables[0].Rows[i][j] = "NULL";\n        }\n    }\n}	0
1099122	1099021	Send XML via HTTP Post to IP:Port	// assume your XML string is returned from GetXmlString()\nstring xml = GetXmlString();\n\n\n// assume port 8080\nstring url = new UriBuilder("http","www.example.com",8080).ToString();     \n\n\n// create a client object\nusing(System.Net.WebClient client = new System.Net.WebClient()) {\n    // performs an HTTP POST\n    client.UploadString(url, xml);  \n\n}	0
2078718	2078616	ValidateRequest per control	MethodInfo _validateMethodInfo = typeof(HttpRequest).GetMethod("ValidateString", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod);\nforeach (string key in Request.Form.AllKeys) {\n  if (key = "< skipped field name >") {\n    continue;\n  }\n  object[] parameters = { Request.Form[key], key, "Request.Form" };\n  _validateMethodInfo.Invoke(Request, parameters);\n}	0
2475651	2471316	SQL Query: How to determine "Seen during N hour" if given two DateTime time stamps?	create table hourlyUseLog (\n    userID text not null,\n    date float, // julian Day\n    hour0 integer default 0,\n    hour1 integer default 0,\n\netc...\n\n    hour23 integer default 0,\n);	0
27927605	27911064	Datagrid Issue With Selecting One Cell Out Of A Row	var grid = FirstGrid.SelectedItems;\nforeach(DataRowView row in grid)\n{\n    if (grid.Count == 1)\n    {\n       MessageBox.Show(row["NameOfTheColumn"].ToString());\n    }\n}	0
2794099	2794069	Regex for date	(\d{1,2})(\/|-|\s*)?((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|\d{2})(\/|-|\s*)?(\d{4})	0
20763995	20763809	Regex for Name text box in registration form	Regex.Match(name, @"^[a-zA-Z]+\s[a-zA-Z]+$");	0
11700663	11700563	How do I display an image from URL in C#?	string remoteUri = "http://www.yourSite.com/library/homepage/images/";\nstring fileName = "YourImagegif", \nmyStringWebResource = null;\n// Create a new WebClient instance.\nWebClient myWebClient = new WebClient();\n// Concatenate the domain with the Web resource filename.\nmyStringWebResource = remoteUri + fileName;\nConsole.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);\n// Download the Web resource and save it into the current filesystem folder.\nmyWebClient.DownloadFile(myStringWebResource,fileName);	0
6107136	6107088	multiply year to date in c#?	DateTime newDate = DateTime.Today.AddDays(10); \n            long xDate = DateTime.Now.Year * newDate.Year;	0
13247068	13247013	Autoscroll to bottom of textarea	var textarea = document.getElementById('textarea_id');\ntextarea.scrollTop = textarea.scrollHeight;	0
26176385	26151023	execute button click inside user control	dialog.parent().appendTo(jQuery("form:first"));	0
30186585	30186264	Keep focus on main window while doing lengthy operations	private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        Task.Factory.StartNew(CallLengthyDllMethod);\n    }\n\n    private void CallLengthyDllMethod()\n    {\n        Thread.Sleep(10000); // simulating lengthy operations\n        MessageBox.Show("Done!");\n    }	0
6365951	6365887	Can you link to a good example of using BackgroundWorker without placing it on a form as a component?	class Program\n{\n  static BackgroundWorker _bw = new BackgroundWorker();\n\n  static void Main()\n  {\n    _bw.DoWork += bw_DoWork;\n    _bw.RunWorkerAsync ("Message to worker");\n    Console.ReadLine();\n  }\n\n  static void bw_DoWork (object sender, DoWorkEventArgs e)\n  {\n    // This is called on the worker thread\n    Console.WriteLine (e.Argument);        // writes "Message to worker"\n    // Perform time-consuming task...\n  }\n}	0
4079134	4078774	Desktop Application C# Global variable	public static class GlobalVariables\n{\n    public static string SomeCommonVar { get { // read this lib app.config } }\n}	0
31513084	31512899	Sort list of objects by list of integers	Dim ordered = L2.\n    Select(Function(obj, index) New With {.Obj = obj, .OldIndex = index, .IndexInL1 = L1.IndexOf(obj.id)}).\n    OrderBy(Function(x) If(x.IndexInL1 >= 0, x.IndexInL1, Int32.MaxValue)).\n    ThenBy(Function(x) x.OldIndex).\n    Select(Function(x) x.Obj).\n    ToArray()	0
2117184	2116890	Size of structure	[StructLayout(LayoutKind.Explicit)]\npublic struct SomeStruct\n{\n    [FieldOffset(0)]\n    public byte b1;\n    [FieldOffset(3)]\n    public byte b2;\n    [FieldOffset(7)]\n    public int i1;\n    [FieldOffset(12)]\n    public int i2;\n}\n\nclass Program\n{\n    static FieldOffsetAttribute GetFieldOffset(string fieldName)\n    {\n        return (FieldOffsetAttribute)typeof(SomeStruct)\n            .GetField(fieldName)\n            .GetCustomAttributes(typeof(FieldOffsetAttribute), false)[0];\n    }\n\n    static void Main(string[] args)\n    {\n        var someStruct = new SomeStruct { b1 = 1, b2 = 2, i1 = 3, i2 = 4 };\n\n        Console.WriteLine("field b1 offset: {0}", GetFieldOffset("b1").Value);\n        Console.WriteLine("field b2 offset: {0}", GetFieldOffset("b2").Value);\n        Console.WriteLine("field i1 offset: {0}", GetFieldOffset("i1").Value);\n        Console.WriteLine("field i2 offset: {0}", GetFieldOffset("i2").Value);\n\n        Console.ReadLine();\n    }\n}	0
18337635	18334264	Will Log writing in text file affect performance of a website?	WriteLog()	0
5151508	5150484	XDocument Descendants of Descendants	var q1 = from c in xmlDoc.Descendants("Ticket")\n    select new\n    {\n        Ticket_Number = (string)c.Element("Ticket_Number"),\n        Reason = (string)c.Element("Status").Element("Reason")\n    };	0
4590541	4590332	Set Column as HyperLink in AutoGenerated GridView	gvoffer.Columns[0].DataFormatString = "<a href=\"http://mywebsite/page.aspx?q={0}\">{0}</a>"\ngvoffer.Columns[0].HtmlEncode = false;	0
8469504	8469454	Union tables of dataset in a single datatable	DataTable t = new DataTable();\nt.Columns.Add("Product", typeof(string));\nt.Columns.Add("Value", typeof(int));\n\nforeach(DataTable table in SampleDS.Tables)\n{\nif(table != null && table.Rows.Count > 0)\n{\nfor(int i = 0; i < table.Rows.Count; i ++)\nt.ImportRow(table.Rows[i]);\n}\n}	0
32935223	32934734	Programmatically open 'Set Associations' in WPF application?	public static void Main()\n    {\n        Process myProcess = new Process();\n\n        try\n        {\n            myProcess.StartInfo.FileName = "c:\\windows\\system32\\control.exe";\n            myProcess.Start();\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(e.Message);\n        }\n    }	0
6827281	6826561	How to get the exact value saved in Excel sheet using C#?	((Excel.Range)xlWorkSheet.Cells[1,5]).EntireColumn.NumberFormat = "@";	0
20895461	20895361	Parsing xml with two identically-named elements	//...\nvar topElement = XmlSneeuw.XPathSelectElement("./weather/top")\n//Create your min/max object\n//...	0
18534816	18534375	Best practice for storing constant stream of data	using (SqlConnection sql = new SqlConnection("...")) {\n    query.Append(string.Format("INSERT INTO {0} ({1}) VALUES ({2})", this._TABLE_, col, val));\n    using (SqlCommand sqlCmd = new SqlCommand(query.ToString(), sql) {\n        sql.Open();\n        sqlCmd.ExecuteNonQuery();\n    }\n}	0
15796303	15796067	Sending Email using SMTP in C#	open smtp.server.com 25\nHelo smtp.server.com \nMail from:yourAdress@server.com\nRcpt to:yourAdress@server.com\n\nData\nSubject:The life\nOMG\n.\nQuit	0
22217345	22217268	How do I swap two characters in a string variable?	int randomNumber= rand.Next(0, word.Length -1 );	0
5283199	5283180	How can I convert BitArray to single int?	private int getIntFromBitArray(BitArray bitArray)\n{\n\n    if (bitArray.Length > 32)\n        throw new ArgumentException("Argument length shall be at most 32 bits.");\n\n    int[] array = new int[1];\n    bitArray.CopyTo(array, 0);\n    return array[0];\n\n}	0
14322874	14322660	Using Reflection to determine which Fields are backing fields of a Property	public string Foo { get; set; }	0
13749098	13748996	trying to expose a class member to be public and readonly or a public constant	public static int CustomersTid { get { return CustomersMeta.TableID; } }\npublic static string CustomersTblName { get { return CustomersMeta.TableName; } }\n\npublic static int TimesTid  { get { return TimesMeta.TableID; } }\npublic static string TimesTblName  { get { return TimesMeta.TableName; } }	0
17935438	11567837	How do I get HTML5 Video to scrub in chrome when delivered via a service?	RangeFileStreamResult(Stream fileStream, string contentType, string fileName, DateTime modificationDate);	0
4778614	4778567	iPhone - Accessing dynamic controls after creation	UITextField *tf=(UITextField *)[self.view viewWithTag:tagValue];	0
20511952	20511014	Showing Font Selection Dialog in GTK#	FontSelectionDialog dialog = null;\ntry {\n    dialog = new FontSelectionDialog("Choose a font");\n    dialog.Run ();\n    var name = dialog.FontName;\n    var pattern = @"^(?<fontName>.*)\s(?<fontSize>\d+(?:\.\d+)?)$";\n    var regex = new Regex(pattern);\n    var match = regex.Match(name);\n    if(match.Success)\n    {\n        var fontName = match.Groups["fontName"].Value;\n        var fontSize = float.Parse(match.Groups["fontSize"].Value);\n        var font = new System.Drawing.Font(fontName, fontSize);\n    }\n} finally {\n    if (dialog != null)\n        dialog.Destroy ();\n}	0
7844560	7844519	Convert pasted text into single line	textBox1.Text = Clipboard.GetText().Replace(Environment.NewLine, " ");	0
13422766	13422714	Phone number regex extraction from formatted string	string s = "(999) 999-9999 Ext.9999";\n   string number = s.Split(" Ext")[0];	0
11449173	6728071	How do I append child node in an Internet Explorer BHO extension?	public void OnDocumentComplete(object pDisp, ref object URL)\n{\n    HTMLDocument document = (HTMLDocument)webBrowser.Document;\n    var fblike = document.getElementById("LikePluginPagelet");\n\n    var button = document.createElement("input");\n    button.setAttribute("value", "myButton");\n    button.setAttribute("onClick", "doSomething()");\n\n    dynamic fbLike = fblike\n    fbLike.appendChild((IHTMLDOMNode)button);\n}	0
22711756	22711599	Crystal Report Viewer Print to Default Printer Programmatically	using (var report = new YourCrystalReport())\n{\n    // Call report.SetDataSource() if necessary\n    // Call report.SetParameterValue() as necessary\n\n    report.PrintToPrinter(...);\n}	0
6679215	6678936	Linq IN statement to exclude from a list	var liveContract = DataContext.Contracts.Where(c => c.ExcludedTransportContracts.Count() == 0 && c.EndDate > DateTime.Now )	0
34271066	34247813	UWP key press event handled too late prevent keyboard focus action	public sealed partial class MyCheckBox : CheckBox\n{\n    public MyCheckBox()\n    {\n        this.InitializeComponent();\n    }\n\n    protected override void OnKeyDown(KeyRoutedEventArgs e)\n    {\n        e.Handled = true;\n        //your logic\n    }\n}	0
3461871	3461865	How do I get Bin Path?	path = System.IO.Path.GetDirectoryName( \n      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );	0
12130345	12130290	How to read text files with ANSI encoding and non-English letters?	var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));	0
30976528	30976304	Regular Expression for whole world	Public\s+Const\s+g(?<Name>[a-zA-Z][a-zA-Z0-9]*)\s+=\s+(?<Value>False|True)	0
12463929	12463747	How to search through Database with entity that matches to part of the string?	albums = db.PhotoAlbums.Where(b => b.NAME.Contains("funny")).ToList();	0
28825138	28821365	How to create a class for a MongoDB collection that is not mine?	public MyClass {\n    // fields and properties\n    [BsonExtraElements]\n    public BsonDocument CatchAll { get; set; }\n}	0
15438515	15435306	dynamic context menus	private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e) {\n  var contextMenu = (sender as ContextMenuStrip);\n  if (contextMenu != null) {\n    var sourceControl = contextMenu.SourceControl;\n    contextMenuStrip1.Items.Clear();\n    //contextMenuStrip1.Items.Add(...);\n  }\n}	0
10505039	10504974	can't generate DB from model code in entity framework	MyDbContext myDbContext = new MyDbContext();\nvar firstItemOfSomething = myDbContext.FirstItemOfSomething.FirstOrDefault();	0
4780726	4779952	Applying Themes in Web Application	Theme="MyTheme"	0
27106869	27101834	Use of AntiForgeryToken and Cached pages	AntiForgeryToken()	0
8617576	8617464	How to get the number of open MDI children	this.MdiChildren.Length	0
9835014	9822424	How to cast an object to UnderlyingSystemType class dynamically?	NDataSeries<T>	0
17342941	17341403	Convert png to high quality ico	GetHIcon()	0
25734363	25734312	How to get control data through the aspx side	document.getElementById('<%=txtConnectionString.ClientID%>').value	0
11681617	11681457	Set start time for Stopwatch program in C#	var offsetTimeSpan = new System.TimeSpan(0,45,0).Add(ss.Elapsed)	0
32416086	32415888	How to parse this JSON in C# (issue with generation execute request for Vk.com Api)	"\n    {\n      "response":\n        [\n           {"id":"id5","array":[1,43,42]},\n           {"id":"id22":,"array":[7,9,10,3]}\n        ]\n    }\n"	0
1130848	1130811	Prevent calling Public constructors except for XML Serializer	public foo() {\n  this.bar = -1;\n}\n\npublic foo(int bar) {\n  this.bar = bar;\n}	0
17799750	17799462	How to prevent database login window in crystal report?	ConnectionInfo connInfo = new ConnectionInfo();\nconnInfo.ServerName = "Driver={Adaptive Server Enterprise};Server=x.x.x.x;Port=x;";\nconnInfo.DatabaseName = "dbname";\nconnInfo.UserID = "username";\nconnInfo.Password = "password";\n\nTableLogOnInfo tableLogOnInfo = new TableLogOnInfo();\ntableLogOnInfo.ConnectionInfo = connInfo;\n\nforeach(Table table in reportDoc.Database.Tables)\n{\n  table.ApplyLogOnInfo(tableLogOnInfo);\n  table.LogOnInfo.ConnectionInfo.ServerName = connInfo.ServerName;\n  table.LogOnInfo.ConnectionInfo.DatabaseName = connInfo.DatabaseName;\n  table.LogOnInfo.ConnectionInfo.UserID = connInfo.UserID;\n  table.LogOnInfo.ConnectionInfo.Password = connInfo.Password;\n\n  // Apply the schema name to the table's location\n  table.Location = "dbo." + table.Location;\n}	0
23274404	23274213	asp.net MVC 4 redirect to details after creating a new item in database?	[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Create(Booking booking)\n{\n    if (ModelState.IsValid)\n    {\n        db.Bookings.Add(booking);\n        db.SaveChanges();\n\n        return RedirectToAction("Details", new { bookingId = booking.Id });\n    }\n\n    return View(booking);\n}\n\npublic ActionResult Details(int bookingId)\n{\n    var details = GetBookingDetails(bookingId); //Load details\n    return View(details);\n}	0
2827537	2827507	Best way to replace XML Text	// It's possible that modifying elements while executing Descendants()\n// would be okay, but I'm not sure\nList<XElement> elements = doc.Descendants().ToList();\nforeach (XElement element in elements)\n{\n    if (ShouldDecrypt(element)) // Whatever this would do\n    {\n        element.Value = Decrypt(element.Value);\n    }\n}	0
12644677	11208354	Use Exchange Recipient Update Service via c# without PowerShell	using (var group = new DirectoryEntry("LDAP://CN=MyGroup,OU=MyOU,DC=company,DC=com"))\n{\n   string baseDN = (string)group.Properties["msExchDynamicDLBaseDN"].Value;\n   string filter = (string)group.Properties["msExchDynamicDLFilter"].Value;\n\n   using (var searchRoot = new DirectoryEntry("LDAP://" + baseDN))\n   using (var searcher = new DirectorySearcher(searchRoot, filter, propertiesToLoad))\n   using (var results = searcher.FindAll())\n   {\n      foreach (SearchResult result in results)\n      {\n         // Use the result\n      }\n   }\n}	0
2656612	2656576	select top 5 in entity framework	context.PersonSet.OrderByDescending(u => u.OnlineAccounts.Count).Take(5);	0
18149163	18149035	Compiler As A Service Execution Context	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Mono.CSharp;\nusing System.Reflection;\n\nnamespace MonoREPLTester\n    {\n    public class Program\n        {\n        public static string mystring = "hello";\n        static void Main(string[] args)\n            {\n            var evaluator = new Evaluator(new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter()));\n            evaluator.ReferenceAssembly(Assembly.GetExecutingAssembly());\n            evaluator.Run("using MonoREPLTester;");\n            object result = evaluator.Evaluate("Program.mystring.IndexOf('l');");\n            Console.WriteLine("Result: " + result);\n            Console.WriteLine("Press any key to exit.");\n            Console.ReadKey();\n            }\n        }\n    }	0
10811624	10811272	How to store PathGeometry?	var pathgeo = new PathGeometry();\n        pathgeo.AddGeometry(new PathGeometry(new PathFigureCollection() { new PathFigure(new Point(10, 50), new List<PathSegment>() { new LineSegment(new Point(200, 70), true) }, false) }));\n\n        // Save\n        var s = XamlWriter.Save(pathgeo);\n\n        byte[] byteArray = Encoding.ASCII.GetBytes(s);\n        var stream = new MemoryStream(byteArray);\n\n        // Load\n        var ob = XamlReader.Load(stream);\n\n        // test beeing a System.Windows.Shapes.Path\n        test.Data = ob as PathGeometry;	0
1294365	1294349	Lambda expression to grab all values inside a Dictionary	var apps = shape.Decorators\n                .Where(x=>x.Value == DecoratorLayoutStyle.App)\n                .Select(x=>x.Key);	0
31994112	31990370	Ignoring identity column when passing value to a table-valued parameter	EXEC [dbo].OpenKeys\n\nINSERT INTO [InfoValues]\n(\n    [InfoID]\n    , [Value]\n    , [UserID]\n    , [DateAdded]\n    , [DateUpdated]\n) \nOUTPUT @EntryID --I assume this is set somewhere else in your code\n    , INSERTED.RetID --or whatever column is your identity in InfoValues\nINTO EVMap(EntryID, ValueID)\nSelect InfoID\n    , [dbo].ENCRYPTDATA(InfoValue)\n    , @UserID --I assume this is set somewhere else in your code\n    , GETDATE()\n    , GETDATE()\nfrom @InfoValues	0
29289484	29289354	Add items to an array with no set size within a "while (reader.Read())"	var myList = new List<int>();\nwhile (reader.Read())\n{\n    if (Int32.Parse(reader["Stock"].ToString()) <=   Int32.Parse(reader["LowStock"].ToString()))\n    {\n        myList.Add(Int32.Parse(reader["Stock"].ToString()));\n    }                        \n}\nvar array = myList.ToArray();	0
8306659	8306614	Extension method and Explicit casting	public static MembershipUser ConvertToMembershipUser(this User user)\n{\n    return new MembershipUser("SimplyMembershipProvider", \n                              user.UserName, \n                              user.UserId, \n                              user.Email, \n                              null, \n                              null, \n                              user.IsApproved, \n                              user.IsLocked,\n                              user.CreateDate, \n                              user.LastLoginDate, \n                              user.LastActivityDate,\n                              user.CreateDate, \n                              DateTime.MinValue);\n}\n\nMembershipUser membershipUser = aUser.ConvertToMembershipUser();	0
33046991	33046928	How do I add custom method to my linq entities without loosing changes when updating DB?	*.dbml.cs	0
22174825	22174016	Styling <asp:Button /> with CSS	.BtnSend {\n  border: none;\n  background: transparent url(../../Images/contact_bt.gif) no-repeat center;\n}	0
23571619	23571272	Comparing array values with each other	var checkingDuplicates = boughttickets.Intersect(winningtickets);\n\nif (!checkingDuplicates.Any())\n {\n   Console.WriteLine("Sorry, You didn't win anything");\n }\n else\n {\n   foreach(TICKET checkingDuplicate in checkingDuplicates)\n   {\n    Console.WriteLine("FETCH AND PRINT YOUR TICKET INFORMATION FROM TICKET OBJECT/CLASS");\n   }\n }	0
9064757	9064636	Sort an ArrayList of Objects in C#	public class Sort : IComparable<Sort>\n{\n    public string Count { get; set; }\n    public string Url { get; set; }\n    public string Title { get; set; }\n\n    public virtual int CompareTo(Sort obj)\n    {\n        return (Count.CompareTo(obj.Count));\n    }\n}	0
14595634	14594193	microsoft azure - get directory full path	Sever.MapPath("../data/")	0
15615493	15615307	How can I make EF insert data into a table that includes a key value from another table?	foreach (string applicationName in applicationNames)\n        {\n            var app = new Application \n                { \n                    Name = applicationName, \n                    ModifiedDate = DateTime.Now \n                });\n            _uow.Applications.Add(app);\n                foreach (string testAccountName in testAccountNames)\n                {\n                   new TestAccount \n                   { \n                       Application = app ,\n                       Name = applicationName, \n                       ModifiedDate = DateTime.Now \n                   });\n                }\n        }	0
15071400	15071319	jqgrid change column sort parameter (sidx) value	index: LastName	0
19843541	19843471	How to make a timer that reload your consoleapplication C#?	class Program\n{\n    static void Main()\n    {\n        Console.WriteLine("Starting timer");             \n        var timer = new System.Timers.Timer(10000);\n\n        // Hook up the Elapsed event for the timer.\n        timer.Elapsed += OnTimer;;\n\n        timer.Enabled = true;\n\n        Console.WriteLine("Press any key to shut down");\n        Console.ReadKey();\n    }\n\n    static void OnTimer(object source, ElapsedEventArgs e)\n    {\n        // This code will run every 10 seconds\n        Console.WriteLine("In timer");\n    }\n}	0
16399850	16399604	How to read Id3v2 tag	0052 - R\n006F - o\n0063 - c\n006B - k	0
33368974	33368426	unitofwork, repositories and disposing of connections	_conn = uow.Connection;	0
16290440	16290175	Linq over InputStream from HttpPostedFileWrapper	foreach (var fileName in wrapper.Select(w => w.FileName))\n{\n    yield return (from csvLine in File.ReadAllLines(fileName)\n                    let x = csvLine.Split(',')\n                    select new ImportedXDock\n                    {\n                        StoreNumber = int.Parse(x[0]),\n                        DCNumber = int.Parse(x[1]),\n                        DeliveryDay = x[2],\n                        Activity = x[3],\n                        ActivityDay = x[4],\n                        Time = TimeSpan.Parse(x[5])\n\n                    }).ToList();\n}	0
28606710	28606567	How can i connect dynamically to different DB with entity framework 6?	//first DbContext\nnamespace MultiDataContextMigrations.Models\n{\npublic class DataContext : DbContext\n{\n public DataContext()\n : base("DefaultConnection")\n {\n\n }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n //TODO:Define mapping\n }\n\n public DbSet Users { get; set; }\n public DbSet Orders { get; set; }\n}\n}\n//second DbContext\nnamespace MultiDataContextMigrations.Models\n{\npublic class UserDataContext : DbContext\n{\n public UserDataContext():base("DefaultConnection")\n {\n }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n //TODO:Define mapping\n }\n\n public DbSet Users { get; set; }\n public DbSet Roles { get; set; }\n}\n}	0
12271271	12271189	DataGrid Showing Blank Lines when bound to an ObservableCollection<Object>	public MainWindow()\n    {\n        InitializeComponent();\n\n        this.dataSource = new ObservableCollection<SomeDataSource>();\n\n        this.dataSource.Add(new SomeDataSource { Field = "123" });\n        this.dataSource.Add(new SomeDataSource { Field = "1234" });\n        this.dataSource.Add(new SomeDataSource { Field = "12345" });\n\n        this.dataGrid1.ItemsSource = this.dataSource;\n    }\n}\n\npublic class SomeDataSource\n{\n    public string Field {get;set;}\n}\n\n\n\n <DataGrid AutoGenerateColumns="False" Height="253" HorizontalAlignment="Left" Margin="27,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="448">\n            <DataGrid.Columns>\n                <DataGridTextColumn Header="First" Binding="{Binding Path=Field, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />\n            </DataGrid.Columns>\n </DataGrid>	0
14450155	14449676	Month Calendar display dates for Monday - Sunday	class Program\n{\n    static void Main(string[] args)\n    {\n        DateTime t = DateTime.Now; //Your selected date from Calendar\n        t -= new TimeSpan((int)t.DayOfWeek, 0, 0, 0);\n        Console.WriteLine("\tstart: " + t.Date.ToShortDateString());\n        Console.WriteLine("\tend: " + t.Date.AddDays(7).ToShortDateString());\n        Console.WriteLine("\t" + new string('-', 25));\n\n        for (int i = 0; i < 7; i++)\n        {\n            var d = t.AddDays(i);\n            if (d.DayOfWeek >= DayOfWeek.Monday && d.DayOfWeek <= DayOfWeek.Friday) //Range: Monday to Friday\n                Console.WriteLine(d.DayOfWeek + " : " + d);\n        }\n        Console.ReadLine();\n    }\n}	0
969434	969414	ASP.NET - How to write some html in the page? With Response.Write?	myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";	0
7836373	7829998	how to remove namespace on datamember?	[DataContract(Namespace = "")]	0
6572855	6572718	Searching a list to get index values in c#	var list1 = new List<string> {\n  {"Student,101256,Active"},\n  {"Professor,597856,Active"}, \n  {"Professor,697843,Inactive"}, \n  {"Student,329741,Active"},\n  {"Student,135679,Inactive"},\n  {"Student,241786,Inactive"}\n};\nvar list2 = new List<string> {{"697843"}, {"241786"}};\n\nvar result = list1\n             .Select((item,i)=> new {index=i,value=item})\n             .Where(item => !item.value.StartsWith("Student"))\n             .Where(item => !item.value.Split(',').Any(j => list2.Contains(j)))\n             .Select(item=>item.index)\n             .ToList();	0
21536959	21536872	Connect [Authorize] with custom database	AuthorizeCore()	0
6333155	5643928	MvcMailer unit test with Rhino Mock, how to?	// arrange\n    var passwordMailer = MockRepository.GeneratePartialMock<PasswordMailer>();\n    passwordMailer.Stub(mailer => mailer.PopulateBody(Arg<MailMessage>.Is.Anything, Arg.Is("ForgotPassword"), Arg<string>.Is.Null, Arg<Dictionary<string, string>>.Is.Null));\n\n    // act\n    var mailMessage = passwordMailer.ForgotPassword("test@example.com", "4454-8838-73773");\n\n    // assert\n    Assert.AreEqual(string.Format(Login.mailBody, "4454-8838-73773"), passwordMailer.ViewBag.Body);\n    Assert.AreEqual(Login.mailSubject, mailMessage.Subject);\n    Assert.AreEqual("test@example.com", mailMessage.To.First().ToString());	0
34223552	34222880	How to show other column on label/textbox from DB when click choose on dropdownlist without valuefield or textfield	protected void dropdown_SelectedIndexChanged(object sender, System.EventArgs e)\n    {\n        try {\n              if (dropdown.SelectedIndex != 0) {\n            SqlStr = "Select Nickname  From tbl_AAA  where ID =@ID";\n           //Execute above query and result text assign to label/textbox\n            SqlConnection connection = new          SqlConnection("Server=ServerNAme;Initial Catalog=DBName; User ID=sa;Password=Password;");\n               SqlCommand command = new SqlCommand(SqlStr, connection);\n\ncommand.Parameters.AddWithValue("@ID", Conversion.Val(dropdown.SelectedValue));\n\nlbl.text = cmd.ExecuteScalar().toString();\n            }\n        } catch (Exception ex) {\n\n        }\n    }	0
12113018	12112898	C# LINQ how to flatten parent list and two nested children lists into a new list	var result = customers\n   .Select(customer => new[]\n   {\n      customer.FirstName,\n      customer.LastName\n   }\n   .Concat(customer.CreditCards.Select(cc => cc.ToString()))\n   .Concat(customer.Addresses.Select(address => address.ToString())));	0
1096754	1096734	C# - Convert a Type Array to a Generic List	ShippingPeriod [] arrShippingPeriods;\n\n//init and populate array\n\nIList<ShippingPeriods> lstShippingPeriods = \n                  arrShippingPeriods.ToList<ShippingPeriods>();	0
6334613	6334398	How to create a recursive association in SQL Server and loop through it in C# with Entity Framework?	public IEnumerable<Category> GetSubCategoriesFor(int catId)\n{\n    var subs = db.Categories.Where(c => c.ParentId == catId);\n\n    foreach (var sub in subs)\n    {\n        yield return sub;\n\n        // Recursive call\n        foreach (var subsub in GetSubCategoriesFor(sub.Id))\n        {\n            yield return subsub;\n        }\n    }\n}	0
10947179	10946994	Store UTF8 data in UTF16 column	encoding="UTF-16"	0
5592620	5592590	Open a file in C# using Process.Start	Process.Start("Notepad.exe", e.FullPath);	0
18387051	18386811	How can I extract a DataTable from a ReportDataSource	queryDatatable = (DataTable)((ReportDataSource)rptViewModel.GetReportDataSources().GetValue(0)).Value;	0
12971037	12971024	how to check the null before splitting string	string cleanedString = orgString ?? "";\nstring[] splittedString = cleanedString.Split(',');	0
14529779	14529305	Get selected user choice from a list of DropDownLists displayed via a Repeater	foreach (RepeaterItem ri in myRepeater.Items)\n{\n     DropDownList dropDownList = (DropDownList)ri.FindControl("dropDownList");\n     string myValue = dropDownList.SelectedValue;\n}	0
13189626	13186983	auto resize application in other computer wpf c#	SizeToContent="WidthAndHeight"	0
11980797	11980779	upload file to https webserver using c# client	WebClient webClient = new WebClient();\n        string webAddress = null;\n        try\n        {\n            webAddress = @"http://myCompany/ShareDoc/";\n\n            webClient.Credentials = CredentialCache.DefaultCredentials;\n\n            WebRequest serverRequest = WebRequest.Create(webAddress);\n            WebResponse serverResponse;\n            serverResponse = serverRequest.GetResponse();\n            serverResponse.Close();\n\n            webClient.UploadFile(webAddress + logFileName, "PUT", logFileName);\n            webClient.Dispose();\n            webClient = null;\n        }\n        catch (Exception error)\n        {\n            MessageBox.Show(error.Message);\n        }	0
13011169	13008818	In Metro, how can I get my instance defined in resource?	MyClass myclass = (MyClass)Application.Current.Resources["keyName"];	0
2853523	2827674	How to set data type property as smalldatetime	customer.Property(c => c.Date).HasStoreType("smalldatetime");	0
6481651	6481528	Allow a new line anywhere in the regex?	(\\.*?)?([\w\[\]]+)(\s+\w+)?(\s*\\.*?)	0
2049744	2043253	c#: how to know whether a 'user account' exists in windows?	public bool IsUserMemberOfGroup(string userName, string groupName)\n    {\n        bool ret = false;\n\n        try\n        {\n            DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);\n            DirectoryEntry userGroup = localMachine.Children.Find(groupName, "group");\n\n            object members = userGroup.Invoke("members", null);\n            foreach (object groupMember in (IEnumerable)members)\n            {\n                DirectoryEntry member = new DirectoryEntry(groupMember);\n                if (member.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))\n                {\n                    ret = true;\n                   break;\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n            ret = false;\n        }\n        return ret;\n    }	0
12137832	12137736	Displaying total number of common and uncommon elements between two arrays?	private void button1_Click(object sender, EventArgs e)\n{\n    string[] testAnswer = new string[20] { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B", "C", "D", "A", "D", "C", "C", "B", "D", "A" };\n    string a = String.Join(", ", testAnswer);\n\n\n\n    //Reads text file line by line. Stores in array, each line of the file is an element in the array\n    string[] inputAnswer = System.IO.File.ReadAllLines(@"C:\Users\Momo\Desktop\UNI\Software tech\test.txt");\n\n    string b = String.Join(", ", inputAnswer);\n\n\n    //Increments through array elements in both arrays and checks for matching elements. \n    //Displays in listBox.\n    for (int i = 0; i < testAnswer.Length; i++)\n    {\n        if (testAnswer[i] == inputAnswer[i])\n            listBox1.Items.Add(inputAnswer[i]); // or testAnswer[i], as appropriate\n        else \n            listBox2.Items.Add(inputAnswer[i]);\n        }\n\n    int correctAns = listbox1.Items.Count;\n    int wringAns = listbox2.Items.Count;\n}	0
10959957	10959636	Unable to Select the First Item in a Listview after Item Removal	if(this.listView1.Items.Count > 0)\n{\n    this.listView1.Focus();\n    this.listView1.Items[0].Focused = true;\n    this.listView1.Items[0].Selected = true;\n}	0
19836517	19836383	Get files of certain extension c#	var exeFiles = Directory.EnumerateFiles(sourceDirectory, \n                                        "*", SearchOption.AllDirectories)\n               .Where(s => s.EndsWith(".exe") && s.Count( c => c == '.') == 2)\n               .ToList();	0
8913356	8912862	Dynamic WPF generation with Linq to XML	var xml = UI.ToString();\nvar reader = XmlReader.Create(new StringReader(xml));\nvar content = XamlReader.Load(reader); // works now.	0
25898688	25866908	All data insert one to another table using C#	SqlCommand com = new SqlCommand("select * from Table_1", con);\nSqlDataReader reader = com.ExecuteReader();\n\nstring test = "";\nwhile (reader.Read())\n{\n    test = reader["col"].ToString();\n\n    SqlCommand com1 = new SqlCommand("insert into Table_2 values(@ID,@col)", con);\n    com1.Parameters.AddWithValue("@ID", TextBox1.Text);\n    com1.Parameters.AddWithValue("@col", test);\n    com1.ExecuteNonQuery();\n}	0
32197683	32197193	Convert GPS data to latitude and longitude c#	0869058A(16) = 141100426(10).\n141100426 / 30000 = 4703.347533333333".\n4703.347533333333 / 60 = 78.38912555555556? -> 78?\n0.38912555555556 * 60 = 23.3475333333336" -> 23"\n0.3475333333336 * 60 = 20.852000000016' -> 20.85'	0
9620559	9620434	Getting datarow values into a string?	StringBuilder output = new StringBuilder();\n        foreach (DataRow rows in results.Tables[0].Rows)\n        {\n            foreach (DataColumn col in results.Tables[0].Columns)\n            {\n                output.AppendFormat("{0} ", rows[col]);\n            }\n\n            output.AppendLine();\n        }	0
223764	223738	.NET - Stream DataSet (of XML data) to ZIP file?	public void WriteFile(string fileName)\n{\n    using (FileStream fs = new FileStream(fileName, FileMode.Create))\n    {\n        Stream s;\n        if (Path.GetExtension(fileName) == ".cmx")\n        {\n            s = new GZipStream(fs, CompressionMode.Compress);\n        }\n        else if (Path.GetExtension(fileName) == ".cmz")\n        {\n            s = new DeflateStream(fs, CompressionMode.Compress);\n        }\n        else\n        {\n            s = fs;\n        }\n        WriteXml(s);\n        s.Close();\n    }\n}	0
23028948	23028929	setting a variable in specific type in dictionary	((ControllerSwipe)mControllerTypes[Type.Swipe]).SwipeLength = 5;	0
19949915	19949744	C# Replace File in System32 Unauthorized Access	Wow64DisableWow64FsRedirection()	0
16590333	16588192	Changing button image with dynamic name	foreach (int roomN in NameRoom)\n        {\n            if (dictionary.ContainsKey(roomN))\n            {\n                string buttonName = dictionary[roomN];\n                Control[] matches = this.Controls.Find(buttonName, true);\n                if (matches.Length > 0 && matches[0] is Button)\n                {\n                    Button button = (Button)matches[0];\n                    button.Image = ((System.Drawing.Image)(Properties.Resources.Merdivan));\n                }\n            }\n        }	0
21871992	21871643	How to inject and execute a javascript function without modifiting document in webbrowser control?	void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    var anyScripts = webBrowser1.Document.GetElementsByTagName("script");\n    if (anyScripts == null || anyScripts.Count == 0)\n    {\n        // at least one <script> element must be present for eval to work\n        var script = webBrowser1.Document.CreateElement("script");\n        webBrowser1.Document.Body.AppendChild(script);\n    }\n\n    // use anonymous functions\n\n    dynamic func = webBrowser1.Document.InvokeScript("eval", new[] { \n        "(function() { return function(elem, color) { elem.style.backgroundColor = color; } })()" });\n\n    var body = this.webBrowser1.Document.Body.DomElement;\n\n    func(body, "red");\n}	0
10952301	10952168	is it possible to add combobox item between two items in wpf?	com_friends.Items.Insert(2,"Bala");	0
25874477	25874091	How can I find all the handlers for a "RaisePropertyChanged" call?	var methodInfo = typeof (MyClass.PropertyChangedDelegate).GetMethod("GetInvocationList");\n        var p = myObject.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(myObject);\n        var subscriberDelegates = (Delegate[])methodInfo.Invoke(p, null);\n        object[] subscriberObjects = subscriberDelegates.Select(sub => sub.Target).ToArray();	0
11952814	11952769	How can I do a LINQ to read XML file	foreach(var element in doc2.Root.Descendants()) {\n    String name = element.Name.LocalName;\n    String value = element.Value;\n}	0
29809181	29809140	return true or false if at least one entity in list A matches an entity in list B	return a.Intersect(b).Any();	0
16485777	16476687	How to add Dispatcher in Background Scheduled Tasks in windows phone application	Deployment.Current.Dispatcher.BeginInvoke(()=> ...)	0
13431020	13430978	add parameters / query string values in action filter. c# mvc3	filterContext.HttpContext.Items.Add("test","test")	0
4515009	4514995	Moving the location and changing size of a external program	[DllImport("user32.dll", SetLastError = true)]\ninternal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);\n\nMoveWindow(ApplicationHandle, 600, 600, 600, 600, True);	0
16159172	16159004	How to a set some text based on the contents of a radiobutton?	private void Btn_Hello(object sender, RoutedEventArgs e)\n  {\n      RadioButton rb = selection.Items.OfType<RadioButton>().FirstOrDefault(o => o.IsChecked==true);\n      if(rb!=null)\n          Hello_box.Text = "hello" + rb.Content.ToString();\n  }	0
27843133	27836007	WPF ComboBox: hide drop-down and focus other control in single mouse click	private void comboBox_DropDownClosed(object sender, EventArgs e)\n    {\n        Point m = Mouse.GetPosition(this);\n        VisualTreeHelper.HitTest(this, new HitTestFilterCallback(FilterCallback),\n            new HitTestResultCallback(ResultCallback), new PointHitTestParameters(m));\n    }\n    private HitTestFilterBehavior FilterCallback(DependencyObject o)\n    {\n        var c = o as Control;\n        if ((c != null) && !(o is MainWindow))\n        {\n            if (c.Focusable)\n            {\n                c.Focus();\n                return HitTestFilterBehavior.Stop;\n            }\n        }\n        return HitTestFilterBehavior.Continue;\n    }\n\n    private HitTestResultBehavior ResultCallback(HitTestResult r)\n    {\n        return HitTestResultBehavior.Continue;\n    }	0
18951070	18946428	average values for given resolution of minutes for datetime value pairs	double resolutionInMins = 30; // In minites\ndouble divisor = to.Now.AddMinutes(resolutionInMins).Ticks - to.Now.Ticks;\n\nFunc<DateTime, double> resolutionLevel = \n    delegate(DateTime timestamp)\n{\n    return Math.Ceiling((to.Now.Ticks - timestamp.Ticks) / divisor);\n};\n\nvar query =\n    Session.Query<SomeEvent>()\n    .Where(p => \n        p.Timestamp >= from.Now && \n        p.Timestamp <= to.Now)\n.GroupBy(x => new\n{\n    ResolutionLevel = resolutionLevel(x.Timestamp)\n})\n.Select(x => new\n{\n    ResolutionLevel = x.Key.ResolutionLevel,\n    ResolutionAvgValue = x.Average(b => b.DisplayValue)\n});	0
1729569	1729368	Creating a Style in code behind	private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    Style style = new Style(typeof (TextBlock));\n    style.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Green));\n    style.Setters.Add(new Setter(TextBlock.TextProperty, "Green"));\n    Resources.Add(typeof (TextBlock), style);\n}	0
18684291	18683968	Packed javascript code, how to unpack?	function _unpack(a) {   // takes a string as argument, we can see that it's a string because strings have the match method, which is used below a.match(...)\n    var x, p = '';      // declare x, declare p and initialize it with the empty string value\n    p = a.match(/%2/);  // match will return ['%2'] (which is an array that contains the string '%2' at index 0) only if %2 is found in the string 'a', else it returns null\n    if (p) {            // if p is thruthy (objects are), but null is falsey. It's like saying, if there was a match\n        x = _uncase(a);\n        return _uncase(x);\n    }\n    return _uncase(a);\n}	0
9173949	9173820	How to create a method that takes a Generic base type	public interface IAnimalShelter<out T> : .....	0
7622753	7622724	C# Replacing value in datatable	for (int i = 0; i < dataTable.Rows.Count; i++)\n{\n    for (int j = 0; j < dataTable.Columns.Count; j++)\n    {\n        dataTable.Rows[i][j] = Crypto.Decrypt(dataTable.Rows[i][j].ToString());\n    }\n}	0
8173531	8173458	winforms detect change of focus within flowlayoutpanel	private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)\n{\n    e.Control.LostFocus += new EventHandler(Control_LostFocus);\n}\n\nvoid Control_LostFocus(object sender, EventArgs e)\n{\n    Control c = (Control)sender;\n    //some code you want write for controls that lost focus\n}	0
2262531	2261911	I'm trying to read data from my SQL Server Compact database, but I keep getting the same error	"SELECT * FROM [User]"	0
18628201	18628146	extract sub string from string within box bracket	Regex regex = new Regex(@"\[[\w ]+\]");    \nstring[] inBrackets = regex.Matches(_sql)\n                           .Cast<Match>()\n                           .Select(m=>m.Value)\n                           .ToArray();	0
24426736	24425624	Entity Framework Concatenated Key in Lookup	public class ABC\n{\n    [Key, ForeignKey("A"), Column(order=0)]\n    public int AId {get;set;}\n    [Key, ForeignKey("B"), Column(order=1)]\n    public int BId {get;set;}\n    [Key, ForeignKey("C"), Column(order=2)]\n    public int CId {get;set;}\n\n    public virtual A A { get; set; }\n    public virtual B B { get; set; }\n    public virtual C C { get; set; }\n}	0
10946430	10946230	Check input to create a valid triangle	a + b > c\na + c > b\nb + c > a	0
32165313	32165221	Reverse a foreach loop action	string encrypt = ""; string decrypt = "";\n\n        string input = Console.ReadLine();\n        var length = input.Length;\n        int[] converted = new int[length];\n        for (int index = 0; index < length; index++)\n        {\n            int x = input[index];\n            string s = x.ToString();\n            encrypt += s;\n            converted[index] = x;\n        }\n\n        Console.WriteLine(encrypt);\n        for (int index = 0; index < converted.Length; index++)\n        {\n            char c = (char)converted[index];\n            string s = c.ToString();\n            decrypt += s;\n        }\n        Console.WriteLine(decrypt);	0
28610906	28454057	Resolving dbcontext per request with Unity in WebApi	container.RegisterType<DbContext, SecurityDbContext>(new PerThreadLifetimeManager());	0
1986242	1985763	how to create a recoverable file uploader console app?	static void UploadFile(string file) {\n  for (int attempt = 0; ; ++attempt) {\n    try {\n      UploadToServer(file);\n      return;\n    }\n    catch (SocketException ex) {\n      if (attempt < 10 && (\n          ex.SocketErrorCode == SocketError.ConnectionAborted ||\n          ex.SocketErrorCode == SocketError.ConnectionReset ||\n          ex.SocketErrorCode == SocketError.Disconnecting ||\n          ex.SocketErrorCode == SocketError.HostDown)) {\n        // Connection failed, retry\n        System.Threading.Thread.Sleep(1000);\n      }\n      else throw;\n    }\n  }\n}	0
15289360	15289356	WinRT ZipArchiv include Folder informations	zipArchive.CreateEntry(@"foo\" + fileToCompress.Name,CompressionLevel.Optimal);	0
31240045	31204906	How to send changed in DataGridView data to data base (Access) by clicking button?	public FormExemple : Form\n{\n    protected string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb";\n    protected OleDbConnection connection;\n    protected OleDbDataAdapter adapter;\n    ....\n\n    Window_Load()\n    {\n        connection = new OleDbConnection(conStr);\n        ...\n        adapter.Fill(dTable);\n\n        cb = new OleDbCommandBuilder(adapter);\n        adapter.InsertCommand = cb.GetInsertCommand();\n        //and other commands\n        ...\n    }\n\n    Button_Click()\n    {\n        ...\n        adapter.Update(dTable)\n        ...\n    }\n}	0
14991008	9162085	Secondary sorting in DevExpress GridView	public void GridView_ExampleSorting(object sender, GridViewSortEventArgs e)\n    {\n        GridView gv = (GridView)sender;\n        DataTable dataTable = gv.DataSource as DataTable;\n        if (dataTable != null)\n        {\n            string sortdirection = GetNextSortDirection(e.SortExpression); \n            DataView dataView = new DataView(dataTable);\n            dataView.Sort = e.SortExpression + " " + sortdirection;\n            if (e.SortExpression.ToString() == "priority")\n                dataView.Sort += " date DESC";\n            gv.DataSource = dataView;\n            gv.PageIndex = 0; \n            gv.DataBind();\n        }\n    }	0
13032530	12997520	Resize MSChart to Fit Pagesize Before Printing	public void PrintPreviewIncompleteJobsByStatus()\n    {\n        // Set new print document with custom page printing event handler\n        chart.Printing.PrintDocument = new PrintDocument();\n        chart.Printing.PrintDocument.PrintPage += new PrintPageEventHandler(ChartGenericFormat_PrintPage);\n\n        chart.Printing.PrintDocument.DefaultPageSettings.Landscape = true;\n\n        // Print preview chart\n        chart.Printing.PrintPreview();\n    }\n\n    private void ChartGenericFormat_PrintPage(object sender, PrintPageEventArgs ev)\n    {\n        // Calculate first chart position rectangle\n        Rectangle chartPosition = new Rectangle(ev.MarginBounds.X, ev.MarginBounds.Y, ev.MarginBounds.Width, ev.MarginBounds.Height);\n\n        // Draw chart on the printer graphics\n        chart.Printing.PrintPaint(ev.Graphics, chartPosition);\n\n    }	0
7528381	7528185	Communications between a C# PC program and an android tablet app	{\n   "a": 42,\n   "b": "Something"\n}	0
13122592	13122485	How to disable MVC 4 model validation?	ModelValidatorProviders.Providers.Clear();	0
16984939	16980987	What symmetric encryption algorithms implemented in both of c# and php do not requires fixed lenght of input data?	try\n{\n    var encryptedFilePath = ShowOpenFileDialog();\n    var decryptedFilePath = TryDecryptFile(encryptedFilePath);\n    ShowMessagePopup("Your file has been decrypted to: " + decryptedFilePath);\n}\ncatch (CryptographicException)\n{\n    ShowErrorPopup("Unable to decrypt file!\n" +\n     "Please make sure the file you selected is valid");\n}	0
8268490	8268273	CMD command not running in console	ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");\n        cmd.RedirectStandardInput = true;\n        cmd.UseShellExecute = false;\n        cmd.CreateNoWindow = false;\n        cmd.WindowStyle = ProcessWindowStyle.Normal;\n        Process console = Process.Start(cmd);\n\n        while(true)\n            console.StandardInput.WriteLine("pause");	0
23634929	23633861	Get index of next same character	public static int getSpecifiedIndexOf(string str,char ch,int index)\n{\n    int i = 0,o=1;\n    while ((i = str.IndexOf(ch, i)) != -1)\n    {\n        if(o==index)return i;\n        o++;\n        i++;\n    }\n    return 0;\n}	0
13378202	13377932	File Upload in C# windows Application	private void button1_Click(object sender, EventArgs e)\n        {\n            DialogResult result = openFileDialog1.ShowDialog();\n            if (result == DialogResult.OK) // Test result.\n            {\n            //Do whatever you want\n            //openFileDialog1.FileName .....\n            }\n        }	0
9553597	9513222	Posting on wall with Mp3 Attachment using Facebook C# SDK	var attachment = new JsonObject();\nvar media = new[]{\n    new{\n        type="mp3",\n        src = filePath,\n        title= "title", \n        artist= "art", \n        album= "album"\n    }\n};\n//var mediaArray = new JsonArray { media };\nattachment.Add("name", "sfs");\nattachment.Add("href", "http://www.google.com");\nattachment.Add("caption", " asdas");\nattachment.Add("description", description);\nattachment.Add("target_id", "1231231");\nattachment.Add("media", media);\n\nvar sb = new StringBuilder("https://api.facebook.com/method/stream.publish?");\nsb.Append("message="); sb.Append(description + "&");\nsb.Append("attachment=");\nsb.Append(attachment);\nsb.Append("&access_token=");\nsb.Append(accessToken);\nvar req = WebRequest.Create(sb.ToString());\nreq.GetResponse();	0
18633087	18632916	posting PHP to URL via WebClient in C#	string url = "http://Example.com/admin"\n             using (WebClient client = new WebClient()) \n             {                    \n                 var data = new NameValueCollection();\n                 data.Add("username","asdsdsad");\n                 data.Add("extension", 123);                    \n\n                 var Bytecode = client.UploadValues(url, data);\n                 string htmlCode = Encoding.UTF8.GetString(Bytecode, 0, Bytecode.Length);\n                 // Or you can get the file content without saving it:\n\n             }	0
9233560	9217484	How do I call a stored procedure with unconventional parameters?	var cmd = String.Format(@"\nDECLARE @exitcode int; \nDECLARE @sqlerrorcode int;\nEXEC master..sqlbackup '-SQL \"BACKUP DATABASE [{0}] TO DISK = [{1}])\"', @exitcode OUTPUT, @sqlerrorcode OUTPUT;\nIF (@exitcode >= 500) OR (@sqlerrorcode <> 0)\nBEGIN\nRAISERROR('SQLBackup failed with exitcode %d and sqlerrorcode %d ', 16, 1, @exitcode, @sqlerrorcode)\nEND\n", myDbName, myBkpPath);\n\nconnection.Execute(cmd, commandTimeout: 0);	0
6294927	4149220	Need to access selected data from a excel addin (Visual C#)	var range = (Range)Globals.ThisAddIn.Application.ActiveWindow.Selection;	0
10761570	10761251	Custom Property doesn't show in Properties winodw of the Custom control	public class MyListView : ListView {\n\n  [Category("Appearance")]\n  public Color InsertionMarkColor { get; set; }\n\n}	0
14468033	14467943	C# List all methods in a control	static void PrintMethods(Object o) {\n\n    Type t = o.GetType();\n    MethodInfo[] methods = t.GetMethods();\n    foreach(MethodInfo method in methods) {\n\n        Print( method.Name );\n    }\n\n\n}	0
27411942	27399381	Getting error "Program failed due to missing install location" by windows app Cert kit	WriteRegStr HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\YourAppnameOrGuid" "InstallLocation" "$InstDir"	0
18687645	18687606	Retrieve data from Task in windows store app	ObservableCollection<Product> collection = await Toolkit<ObservableCollection<Product>>.LoadFromXmlAsync("list1.xml");	0
22329658	22329221	Avoiding string allocations on native-to-managed callbacks	[UnmanagedFunctionPointer(CallingConvention.StdCall)]\npublic delegate void Data(IntPtr data);\n\n\nprivate unsafe static void HandleData(IntPtr data)\n    {\n        byte* charPtr = (byte*)data;\n\n        // work with bytes here (which are single-byte chars).\n\n\n    }	0
20802880	20696167	can I build custom queries in Ormlite at runtime?	SqlExpression<T> expression = new MySqlExpression<T>();\n                expression.WhereExpression = (whereExp.Length > 0 ? "WHERE " + whereExp : "");\n                expression.OrderByExpression = (orderExp.Length > 0 ? "ORDER BY " + orderExp : "");\n                expression = expression.Limit(skip: _pageIndex * _pageSize, rows: _pageSize);	0
8995135	8994933	Call custom constructor with Dapper?	return connection.Query(sql, args).Select(row =>\n     new AnyType((string)row.Foo, (int)row.Bar) {\n         Other = (float)row.Other }).ToList();	0
13703504	13703319	DataTable not being bound to DataContext of a DataGrid	dgProprietarios.DataContext = new ProprietariosViewModel(new Dictionary<string, string>());\ndgProprietarios.Items.Refresh();	0
28919141	28915781	Remove Black Border From Scanned Image c#	using (MagickImage image = new MagickImage(@"path_to_original"))\n{\n    int width = image.Width, height = image.Height;\n    image.Crop(width - 800, height - 800);\n\n    //if the image needs to be brought back up to a standarized size\n    image.BorderColor = new ColorRGB(System.Drawing.Color.White);\n    image.Border(100, 100);\n\n    image.Write(@"path_to_cropped_image_with_no_more_black_border_around_it");\n}	0
6855600	6855514	Deserialize XML file with objects to Array	public void test()\n{ \n    string outfile = @"C:\Folder\Tester.xml";\n\n    SerializeToXml<List<Opgaver>>(arrAktiveOpgaver, outfile);//serialize data\n\n    arrAktiveOpgaver = DeserializeFromXml<List<Opgaver>>(outfile);//deserialize data\n}\n\npublic static T DeserializeFromXml<T>(string inputFile)\n{\n    XmlSerializer s = new XmlSerializer(typeof(T));\n    T deserializedObject = default(T);\n\n    using (TextReader textReader = new StreamReader(inputFile))\n    {\n        deserializedObject = (T)s.Deserialize(textReader);\n        textReader.Close();\n    }\n\n    return deserializedObject;\n}\n\npublic static void SerializeToXml<T>(T objToSerialize, string outputFile)\n{\n\n    XmlSerializer s = new XmlSerializer(objToSerialize.GetType());\n\n    using (TextWriter textWriter = new StreamWriter(outputFile))\n    {\n        s.Serialize(textWriter, objToSerialize);\n        textWriter.Close();\n    }\n}	0
11265856	11265656	Creating Calculator in C#, need help implementing math logic/something else	public Boolean lastCharIsSymbol {get;set;}\n\nprivate void button9_Click(object sender, EventArgs e)\n{\n    textBox1.Text = textBox1.Text + "9";\n    lastCharIsSymbol = false;\n}\n\nprivate void buttonPlus_Click(object sender, EventArgs e)\n{\n    if (textBox1.Text == "" || lastCharIsSymbol)\n        return;\n    else\n    {\n        plus = true;\n        textBox1.Text = textBox1.Text + " + ";\n        lastCharIsSymbol = true;\n    }\n}	0
4757482	4757447	Understanding the behavior of a single ampersand operator (&) on integers	110 &     010 =     010\n   1010 &    0101 =    0000\n  10100 &   11001 =   10000\n1111011 & 0010100 = 0010000	0
15014277	15014236	understand when user closes a window	Mfile.WaitForExit();\n// here you can invoke Notepad.exe with your text file	0
31197178	31197146	How to calculate real number	Double i=0;\ni = Convert.ToDouble(Convert.ToDouble(Datagridview.Rows[x].Cells[0].Value) + Convert.ToDouble(Datagridview.Rows[x+1].Cells[0].Value))\ni=Math.Round(i);	0
31125708	31125127	Library for translating months into integers C# .NET	[System.Globalization.CultureInfo]::CurrentCulture.DateTimeFormat.MonthNames	0
32151618	32151545	Using a nested foreach to group data	int playerIndex=0;\n    int groupIndex=1;\n    foreach (var item in queryResult)\n    {\n         if((playerIndex%TotalNumberOfUsersInGrp)==0){\n               Console.WriteLine("group:" + groupIndex);\n               groupIndex++;\n         }\n         Console.WriteLine("player:" + item.fullName);\n         playerIndex++;\n    }	0
13425559	13424323	how can i focus and move scrollbar in listview	lstvClientes.Items[i].EnsureVisible();	0
3022339	3021877	How to read system.web section from web.config	const string outputCacheSettingsKey = "system.web/caching/outputCacheSettings";           \n\nvar outputCacheSettingsSection = ConfigurationManager.GetSection(outputCacheSettingsKey) as OutputCacheSettingsSection;	0
16855795	16855759	Is there a way to create a list of property values from a list of some type?	lstPersons.Select(x=> x.Name).ToList()	0
25329618	25329498	How to assign to a variable the results of Find	var a = collection.Select(x => x.Property)\n    .FirstOrDefault(value => value == whatever);	0
9721782	9586261	Update user profile throws PropertyNotEditableException in sharepoint 2010	SPSecurity.RunWithElevatedPrivileges(() =>\n                     {\n                         using (var site = new SPSite(CurrentWeb.Site.Url))\n                         {\n                             using (var web = site.OpenWeb(CurrentWeb.ID))\n                             {\n                                 web.AllowUnsafeUpdates = true;\n                                 SPList userInfo = web.Site.RootWeb.Lists["User Information List"];\n                                 SPListItem userItem = userInfo.Items.GetItemById(_SelectedUser.ID);\n                                 userItem["Work phone"] = tbPhone.Text;\n                                 userItem["Work e-mail"] = tbEmail.Text;\n                                 userItem["company"] = tbCompany.Text;\n                                 userItem.Update();\n                             }\n                         }\n                     });	0
19376907	19376748	Test that only a single bit is set in Flags Enum	int intVal = ((int)myEnumFlags);\nbool singleBitIsSet = intVal != 0 && (intVal & (intVal-1)) == 0;	0
29379740	29379317	How to get average of list within lists using linq?	double average = busInCat.Max(b=> b.GetReviews().Average(r => r.getRateing()));\nreturn busInCat.Where(b => b.GetReviews().Average(r => r.getRateing()) == average).T	0
24218894	23711738	Get Number of lines in an image using AForge or OpenCV	private bool CheckLines(Bitmap image, Color filterColor)\n    {\n        EuclideanColorFiltering ColorFilter = new EuclideanColorFiltering();\n        // set center colour and radius\n        AForge.Imaging.RGB color = new RGB(filterColor.R, filterColor.G, filterColor.B, filterColor.A);\n        ColorFilter.CenterColor = color;\n        ColorFilter.Radius = 100;\n        // Apply the filter\n        ColorFilter.ApplyInPlace(image);\n\n        // Define the Blob counter and use it!\n        BlobCounter blobCounter = new BlobCounter();\n        blobCounter.MinWidth = 5;\n        blobCounter.MinHeight = 5;\n        blobCounter.FilterBlobs = true;\n        //blobCounter.ObjectsOrder = ObjectsOrder.Size;\n        blobCounter.ProcessImage(image);\n        System.Drawing.Rectangle[] rects = blobCounter.GetObjectsRectangles();\n        if (rects.Length > 0)\n        {\n            return true;\n        }\n        return false;\n    }	0
564679	562705	How do you disable all table indexes in sql server compact edition via an SqlCeCommand Object?	DROP INDEX [TableName].IndexName	0
11426048	11426029	Copy generic list value to another generic list	foreach (Language objLst in lstAllCultures)\n        {\n            SCultureInfo objInfo = new SCultureInfo();\n            objInfo.LanguageName = objLst.LanguageName;\n            objInfo.LanguageCode = objLst.LanguageCode;\n            lstCulture.Add(objInfo);\n        }	0
5338514	5338253	BitmapSource to BitmapImage	BitmapSource bitmapSource = Clipboard.GetImage();\n\n        JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n        MemoryStream memoryStream = new MemoryStream();\n        BitmapImage bImg = new BitmapImage();\n\n        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));\n        encoder.Save(memoryStream);\n\n        bImg.BeginInit();\n        bImg.StreamSource = new MemoryStream(memoryStream.ToArray());\n        bImg.EndInit();\n\n        memoryStream.Close();\n\n        return bImg;	0
19414554	19414216	Multi Line Regex Issue	var val = Regex.Match(alltext, \n                      @"\[Time\].+?Type\s+=\s+([^\s]+)", \n                      RegexOptions.Singleline)\n              .Groups[1].Value;	0
8916187	8916135	Loop Through Results from a Method	foreach (DataRowView rowView in dv) //where dv is your DataView\n{\n    DataRow row = rowView.Row;\n\n    // Do your stuff here\n}	0
28461646	28461186	Downcasting this in an abstract base-class, is there any way to force it?	public abstract class Base<DerivedType, OtherType> \n      where DerivedType : Base<DerivedType, OtherType>\n{\n    protected abstract OtherType Factory(DerivedType d);\n\n    public bool TryCreate(out OtherType o)\n    {\n       o = Factory ((DerivedType)this);\n       return true;\n    }\n }\n\npublic  class MyClass : Base<MyClass, string>\n{\n   protected override string Factory (MyClass d)\n   {\n      return d.GetType ().Name;\n   }\n}	0
31434964	31434635	Append an XML file to another using LINQ TO XML in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        XNamespace ns = "https://mws.amazonservices.com/Orders/2013-09-01";\n\n        var xml1 = XDocument.Load("Orderlist.xml");\n        var xml2 = XDocument.Load("Orderlist2.xml");\n\n        xml1.Descendants(ns + "ListOrderItemsResult").LastOrDefault().AddAfterSelf(xml2.Descendants(ns + "ListOrderItemsResult"));\n        xml1.Save("Orderlist.xml");\n    }\n}	0
4223989	4223917	C# equivalent of C sscanf	string str = "10 12";\nvar parts = str.Split(' ');\nint a = Convert.ToInt32(parts[0]);\nint b = Convert.ToInt32(parts[1]);	0
33227454	33221434	Raw strings into HttpRequest/HttpResponse using ASP.NET 5?	new DefaultHttpContext()	0
34089480	34087116	Unable to call a step definition within another step with a dynamic object	[Given(@"I add the following users")]\npublic void GivenIAddTheFollowingUsers(IEnumerable<dynamic> people)\n{\n    foreach(var person in people)\n    {\n        var header = new [] {"FirstName", "Surname", "Age"};\n        var personTable = new Table(header);\n        personTable.AddRow(person.FirstName, person.Surname, person.Age);\n\n        When(@"I go to the add person page");\n        Then(@"I enter the details of the person", personTable);\n        When(@"I save the new person");\n        Then(@"I am taken back to the view people page");\n    }\n}	0
1663100	1663050	ASP.NET C# - Removing a column from a datalist	DataList1.Controls.Remove(DataList1.FindControl("WorkLog"));	0
3712890	3712847	How to have an abstract method return an abstract type with concrete implementations?	public interface IKing<T> where T:Result{\n    T Get();\n}\n\npublic class King<T> : IKing<T>\n   public abstract T Get();\n}\n\npublic class KingA : King<ResultB> {\n    public override ResultA Get(){\n        return new ResultA();\n    }\n}\n\npublic class KingB : King<ResultB> {\n    public override ResultB Get(){\n        return new ResultB();\n    }\n}	0
18818806	18818696	EF4 How to clear DbContext internal state?	myDbcontext.Configuration.AutoDetectChangesEnabled = false;\nmyDbcontext.Configuration.ValidateOnSaveEnabled = false;	0
6617634	6617554	Using an extension method on a dictionary	Console.WriteLine(dictioanary.Sum(kvp => kvp.Value));	0
10457205	10457150	How to get the attribute value of a XML node using XPath	XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);\n\nwhile (nodesText.MoveNext())\n{\n    Console.Write(nodesText.Current.Name);\n    Console.WriteLine(nodesText.Current.Value);\n}	0
4032783	4032760	Cycle through int values	((++i - 1) % N + 1	0
14657617	14613816	How do I avoid a GridView's Gridlines changing color when applying a class to a cell on the RowDataBound event?	if (e.Row.Cells[i].Text.Contains("monkey"))\n            {\n                e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("monkey", "<span class=\"monkey\">monkey</span> ");\n            }	0
2516854	2516808	How to Set MediaElement Position Dynamically in Silverlight?	MediaElement musicPlayer = new MediaElement();\nmusicPlayer.MediaOpened += (s, args) =>\n{\n    var player = (MediaElement)s;\n    if (player.CanSeek)\n        player.Position =  new TimeSpan(0, 0, 30);   \n}                     \nmusicPlayer.Source = new Uri(strMediaFileURL, UriKind.RelativeOrAbsolute);\nLayoutRoot.Children.Add(musicPlayer);	0
24958672	24955839	Passing a string parameter to another layout MvvmCross	ShowViewModel<SecondViewModel>(new { val = "hello" })	0
33894074	33893286	Linq to SQL compare two comma delimited strings	string string2 = "G,L";\nvar result = from item in oTable\n             where string2.All(x => item.string1.Contains(x))\n             select item;	0
11781719	11781435	Paging Search Results	var products = database.Products.Where(p =>\n            p.PartNumber.ToLower().Contains(term.ToLower()) ||\n            p.PartNumber.ToLower() == term.ToLower() || p.OProductName.ToLower().Contains(term.ToLower()) || p.OProductName.ToLower() == term.ToLower())\n            .OrderBy(p => p.PartNumber)\n            .Skip((Page - 1) * PageSize).Take(PageSize);	0
12750234	12749990	programatically close win8 app	Application.Current.Exit();	0
10901695	10901017	Custom MembershipProvider with SQL Users Table	Membership.CreateUser	0
6663782	6662381	How to update some COM marshalling code to work on a 64 bit system?	[StructLayout(LayoutKind.Sequential)]\nstruct DNSRecord {\n    public IntPtr pNext;\n    // etc..\n    public Int16 Pad;\n    private int Pad1;\n    private int Pad2;\n    private int Pad3;\n    private int Pad4;\n    private int Pad5;\n    private IntPtr Pad6;\n    private IntPtr Pad7;\n    private IntPtr Pad8;\n}	0
1185866	1185649	Trust Level required for Membership Providers	[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]\n[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]\npublic class SqlMembershipProvider : MembershipProvider	0
19433140	19433120	C# Get specific component from list of Components	var textBoxes = components.OfType<TextBox>();	0
23926412	23926377	Cannot convert null to 'bool' because it is a non-nullable value type	xlWorkSheet.Cells[i, 1] == null	0
26053524	26040349	Is there any other way to convert row fields into column other than pivot	/*Thank you Daniel. J.G for the fiddle. I took it as the basis*/\npublic class Foo\n{\n    public String Place {get; set;}\n    public String CafeName {get; set;}\n}\n\nList<Foo> RawFoos = new List<Foo>()\n{\n    new Foo{Place = "x", CafeName = "cafe red"},\n    new Foo{Place = "x", CafeName = "cafe blue"},\n    new Foo{Place = "y", CafeName = "cafe red"},\n    new Foo{Place = "y", CafeName = "cafe blue"},\n    new Foo{Place = "z", CafeName = "cafe red"},\n};\n\nvar pivot = from f in RawFoos\n            group f.CafeName by f.Place into g\n            //Anonymous object because I'm lazy      \n            select new \n            { \n              Place = g.Key,\n              CafeRed = g.FirstOrDefault(x => x == "cafe red"),\n              CafeBlue = g.FirstOrDefault(x => x == "cafe blue")\n            };\n\npivot.Dump(); // only in Linqpad	0
2061168	2061003	How to represent a hierarchically-organized URL in ASP.NET MVC	"../{topic}/{subtopics*}"	0
24278649	24278225	Extracting name of stored procedures from a file, if a particular table is used in it using regex	// Read content\nstring content = File.ReadAllText(filename);\n// Separate procedures from each other\n// (you might have to use "ToUpper()" before)\nstring[] procs = content.Split(new string[] { "CREATE PROCEDURE" }, StringSplitOptions.None);\n// Check if one of them contains the table name\nstring table = "ucg2.userCompanyId";\nforeach (string proc in procs)\n{\n    // If it does, print the first line (which holds the name of the stored procedure\n    // (Using regex here might be necessary, depending on the source)\n    if (proc.Contains(table))\n    {\n        Console.WriteLine(proc.Split(new string[] { "\r\n" }, StringSplitOptions.None)[0]);\n    }\n}	0
31070728	30853971	Windows Phone. ObservableCollection as a source for ListView in Chat application	collection.CollectionChanged += (s, args) =>\n            {\n                var scrollViewer = behavior.AssociatedObject.GetFirstDescendantOfType<ScrollViewer>();\n                scrollViewer.UpdateLayout();\n                scrollViewer.Measure(scrollViewer.RenderSize);\n                scrollViewer.ChangeView(0, scrollViewer.ScrollableHeight, scrollViewer.ZoomFactor, false);\n            };	0
31955778	31677781	Transferring collection items for collection with two IEnumerable<T> implementations with reflection	var castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);\nvar castGenericMethod = castMethod.MakeGenericMethod(new Type[] {  collectionParamType});\nsecondaryCollection = castGenericMethod.Invoke(null, new object[] {secondaryCollectionObject})	0
11932611	11868757	Displaying an array of images in picturebox?	// For confirm visibility of all images set \n    this.AutoScroll = true;\n\n    string[] list = Directory.GetFiles(@"C:\pictures", "*.jpg");\n    PictureBox[] picturebox= new PictureBox[list.Length];\n    int y = 0;\n    for (int index = 0; index < picturebox.Length; index++)\n    {\n        this.Controls.Add(picturebox[index]);\n        // Following three lines set the images(picture boxes) locations\n        if(index % 3 == 0)\n            y = y + 150; // 3 images per rows, first image will be at (20,150)\n        picturebox[index].Location=new Point(index * 120 + 20, y);\n\n        picturebox[index ].Size = new Size(100,120);\n        picturebox[index].Image = Image.FromFile(list[index]);\n    }	0
7792921	7792555	Sitecore comparing two items	/data/serialization	0
17147186	17146870	Download a file from TFS based on Change Set Number	//for changeset 13    \nVersionSpec versionFrom = VersionSpec.ParseSingleSpec("C13", null);	0
34418341	34388287	Converting from HTML to .NET MVC with Bootstrap	col-sm-9 col-sm-offset-3	0
10914458	10914423	How do I get the age of everyone in my people array	for (int i = 0; i < Person.Length; i++)\n{\n   Person[i].getAge();\n}	0
13687330	13686832	Insertion & Deletion at Specific Position in Single Linked List	public class Node\n{\n    public string Name { get; set; }\n    public Node Next { get; set; }\n\n    public void InsertAt(string name, int index, Node start)\n    {\n        Node current = start;\n        // Skip nodes until you reach the position\n        for (int i = 0; i < index; i++)\n        {\n            current = current.Next;\n        }\n        // Save next node\n        Node next = current.Next;\n        // Link a new Node which next Node is the one you just saved\n        current.Next = new Node () { Name = name, Next = next };\n    }\n}	0
34447624	34447397	Inserting Data Into Db By Entity Framework Throwing Errors	newPersonEntity.UpdateObject(objCredentials);	0
22305453	22305408	How to retrieve the value from HTML	string html = "<a href=\"#\">My Link</a>";\nvar node = HtmlNode.CreateNode(html);\nstring value = node.InnerHtml; // "My Link"	0
20564165	20564000	Compare two collections optimization	foreach (var b in collectionB)\n{\n   var itemToUpdate = collectionA.FirstOrDefault(a => a.Id == b.Id);\n   if (itemToUpdate != null)\n   {\n      collectionA.Remove(itemToUpdate);\n   }\n   collectionA.Add(b);\n}	0
16507280	16507127	Re-enabling a button after few seconds	if (!String.IsNullOrEmpty(txtFirstActual.Text))\n{\n    // clear data\n}	0
5876948	5876906	IDictionary<string, IDictionary<string, ICollection<string>>> To LINQ	var query = from r in Highlights\n            let szKey = r.Key\n            let szValue = r.Value\n            from s in szValue\n            let szCat = s.Key\n            let sr = s.Value\n            from t in sr\n            let szText = t\n            select new { Key = szKey, Category = szCat, Text = szText };\n\n// or, also, you can use this small query\nvar query = from r in Highlights\n            from s in r.Value\n            from t in s.Value\n            select new {Key = r.Key, Category = s.Key, Text = t};    \n\nforeach(var element in query)\n{\n    ProcessUpdate(element.Key, element.Category, element.Text);\n}	0
7775064	7772872	Can't figure how to parse using HTML Agility Pack	var doc = new HtmlDocument();\ndoc.Load(url);\n\nvar table = doc.DocumentNode.SelectSingleNode("//table[@class='tableclass']");\nvar value1 = table.Descendants("tr").Skip(1)\n    .Select(tr => tr.InnerText.Trim())\n    .First();\nvar theRest =\n    from tr in table.Descendants("tr").Skip(2)\n    let values = tr.Elements("td")\n        .Select(td => td.InnerText.Trim())\n        .ToList()\n    select new\n    {\n        Value2 = values[0],\n        Value3 = values[1],\n        Value4 = values[2],\n        Value5 = values[3],\n        Value6 = values[4],\n    };	0
18448404	18446341	REST API Put large data	var httpClient = new HttpClient();\n\n        httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;\n\n        var content = new CompressedContent(new StreamContent(new FileStream("c:\\big-json-file.json",FileMode.Open)),"UTF8");\n\n        var response = httpClient.PostAsync("http://example.org/", content).Result;	0
34279939	34279062	Windows application - Fill textboxes/datetimepicker using dropdownlist	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n          string query = "SELECT Name, DateofBirth FROM TableName Where ID ="+comboBox1.Text;\n\n    SqlConnection sqlConn = new SqlConnection(conSTR);\n    sqlConn.Open();\n    SqlCommand cmd = new SqlCommand(query, sqlConn);\n    SqlDataAdapter da=new SqlDataAdapter(cmd);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n\n   textBox1.Text = dt.Rows[0]["Name"].ToString();\n   datePicker1.Text = dt.Rows[0]["DateOfBirth"].ToString(); \n\n\n    }	0
32425217	32425164	How to split a list into parts in c#?	int alreadyProcessesCount = 0;\nwhile (myList.Any())\n{\n    var emailList = myList.Skip(alreadyProcessesCount).Take(10);\n\n    // code to attach and send here\n    alreadyProcessesCount += 10;\n}	0
378582	378524	How do I create a regex to ensure a word is made up only of given single letters and letter groups?	Regex regex = new Regex(@"\A(?:(a|b|abc)*)\Z");	0
18508193	18487882	How to avoid getting null in c#	SPListItem item = list.Items.Add();\nif (item.Fields.ContainsField("PercentComplete"))\n{\n    item["PercentComplete"] = .45;\n}\nitem.Update();	0
16843628	16826893	Pasting 1d array into 2d array	static void Main(string[] args)\n{\n    int rows = 100, cols = 100;\n    // array has rows in sequence\n    // for example:\n    //  | a11 a12 a13 |    \n    //  | a21 a22 a23 | = [ a11,a12,a13,a21,a22,a23,a31,a32,a33]\n    //  | a31 a32 a33 |    \n    MyClass[] array=new MyClass[rows*cols];\n    // fill it here\n\n    MyClass[] stripe=new MyClass[20];\n    // fill it here\n\n    //insert stripe into row=30, column=10\n    int i=30, j=10;\n    Array.Copy(stripe, 0, array, i*cols+j, stripe.Length);\n\n}	0
18252146	18251969	Classify datasets in C# - how to do it?	House = [1,0,1,0..........] {attributes are bed room, bathroom, Near park, Airconditioning etc }	0
31814438	31035854	MEF composition with multiple interdependent parts	[Export(typeof(IWindow))]\n  class Window2 : IWindow\n  {\n    IEventManager eventMgr;\n\n    [ImportingConstructor]\n    public Window2([Import(typeof(IEventManager))]IEventManager mgr)\n    {\n      this.eventMgr.AnEvent += eventMgr_AnEvent;\n    }\n\n    void eventMgr_AnEvent(object sender, EventArgs e)\n    {\n      Debug.WriteLine("Event from Window 2");\n    }\n\n    public string Name { get { return "Window2"; } }\n  }	0
11702698	11702618	How can i insert NULL values to a database	drow[1] = string.IsNullOrWhitespace(imgData)\n           ? (object) imgData : DBNull.Value;\n\ndrow[2] = string.IsNullOrWhitespace(nom.Text)\n           ? (object) nom.Text.ToUpper : DBNull.Value;	0
5483014	5482898	using hashtable in c sharp extensively	# Interface is a hash-map of interface objects, like text-boxes. 'status' is the key\n# in the map for one of those.\nInterface['status'].setText("New status!")\n# vs:\n# Interface is a proper object with its own class, that handles the interface. It has\n# all our text-boxes "inside" of it.\nInterface.updateStatus("New status!")	0
9284674	9284589	How to define an interface with a method that either takes a IEnumerable<User> or just User	Send(IEnumerable<User> users)\n{...}\n\nvoid Send(params User[] recipients)\n{\n    Send((IEnumerable<User>)recipients); // To IEnumerable overload\n}	0
33392162	33392088	How to create JArray of JObject?	addresses.Add(JObject.Parse(\n            @"{""street"":""" + address.Street + "\", " +\n            @"""city"":""" + address.City + "\", " + \n            @"""postalCode"":""" + address.PostalCode + \n        @"""}"));	0
18955957	18955688	How to prevent reading app.config?	void EncryptConnectionStringsIfNecessary()\n    {\n        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n        ConnectionStringsSection section = configFile.ConnectionStrings;\n        if (section != null)\n        {\n            if (!section.IsReadOnly())\n            {\n                if (!section.SectionInformation.IsProtected)\n                {\n                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");\n                    section.SectionInformation.ForceSave = true;\n                    ConfigFile.Save(ConfigurationSaveMode.Full);\n                }\n            }\n        }\n    }	0
13874793	13874751	Clearing control values in a page without postback from the server ASP.NET	You should to set property CausesValidation="false" for your clear button	0
8453603	8430437	Open XML SDK page margins	PageMargins pageMargins1 = new PageMargins();\npageMargins1.Left = 0.45D;\npageMargins1.Right = 0.45D;\npageMargins1.Top = 0.5D;\npageMargins1.Bottom = 0.5D;\npageMargins1.Header = 0.3D;\npageMargins1.Footer = 0.3D;\nworksheetPart.Worksheet.AppendChild(pageMargins1);\n\nPageSetup pageSetup = new PageSetup();\npageSetup.Orientation = OrientationValues.Landscape;\npageSetup.FitToHeight = 2;\npageSetup.HorizontalDpi = 200;\npageSetup.VerticalDpi = 200;\nworksheetPart.Worksheet.AppendChild(pageSetup);	0
9291796	9291641	How to detect if a bitmap has Alpha channel in .NET	unsafe\n{\n   byte* ptrAlpha = ((byte*)bmpData.Scan0.ToPointer()) + 3;\n   for (int i = bmpData.Width * bmpData.Height; i > 0; --i)  // prefix-- should be faster\n   {\n      if ( *ptrAlpha < 255 )\n          return true;\n\n      ptrAlpha += 4;\n   }\n}	0
28413112	25200508	Autodesk Revit Architecture 2014 .NET API C# find room bounding elements in link	Room rm = new Room();\n            SpatialElementBoundaryOptions sebo = new SpatialElementBoundaryOptions();\n            var boundaryitems = rm.GetBoundarySegments(sebo);	0
30542925	30542896	How to Avoid the string from number(for rupees) in c#?	string OnlyNumbered = Regex.Match(label1.Content.ToString(), @"\d+").Value;	0
11685188	11684897	c# Refunding between date ranges	declare @DateFrom date='10/18/2012'     \n declare @DateTo date='12/14/2012'\n\n select T.BillID,T.AccountID,T.BilledFrom,T.BillTo,\n     case when BilledFrom<@DateFrom then @DateFrom else BilledFrom end [RangeStart], \n     case when BillTo<@DateTo then BillTo else @DateTo end [RangeEnd],DATEDIFF(D,case when BilledFrom<@DateFrom then @DateFrom else BilledFrom end ,case when BillTo<@DateTo then BillTo else @DateTo end ) [Days],Price\n     from t_account  T	0
30822957	30813287	Add Httpheader to selenium chrome webdriver in C#	public static void Start()\n    {\n        FiddlerApplication.RequestHeadersAvailable += FiddlerApplication_RequestHeadersAvailable;\n        FiddlerApplication.Startup(8888, true, true, true);\n    }\n\n    static void FiddlerApplication_RequestHeadersAvailable(Session oSession)\n    {\n        oSession.RequestHeaders.Add("My_Custom_Header", "XXXXXXXXXXXXXXXX");\n    }	0
23399819	23399768	how to set binary file to null if no file has been selected	postedFile = FileUpload.PostedFile;\nbyte[] bin;\nif (postedFile == null)\n  bin = new byte[0];\nelse\n  bin = new byte[FileUpload.PostedFile.ContentLength];	0
2289164	2288999	How can I get a FlowDocument Hyperlink to launch browser and go to URL in a WPF app?	Run run2 = new Run("this is a hyperlink");\nHyperlink hlink = new Hyperlink(run2);\nhlink.NavigateUri = new Uri("http://www.google.com");\nhlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hlink_RequestNavigate);\nparagraph.Inlines.Add(hlink);\n\n\nvoid hlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)\n{\n    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));\n    e.Handled = true;\n}	0
13417336	13415519	How to get all the aspx page list of a given web address	String[] Files = Directory.GetFiles("C:\\YourSorceCodeDirectory", "*.aspx", SearchOption.AllDirectories);	0
32246073	32245777	C# how to modify this method to return only with matching criteria?	public static List<TPPROperatorDetails> GetOperators()\n{\n    return DataHelper.DbTPPRTracer.TPPROperators\n        .Where(op => ParseOperatorType(op.UserType) == "Inactive")\n        .Select(\n          op => new TPPROperatorDetails{\n            Id = op.Id,\n            FullName = op.Name, \n            UserName = op.UserName, \n            Designation = op.Position, \n            OperatorTypes = ParseOperatorType(op.UserType),\n            SignatureImage = op.SignatureImage \n        })\n        .ToList();\n}	0
5332174	5252888	Correct way to detect a new shape in a workbook after completing a paste operation	oldShapes.Count	0
2055976	2055718	C# Returning object from Array leaves pointer to Array item	public MyObj Clone()\n    {\n        BinaryFormatter bFormatter = new BinaryFormatter();\n        MemoryStream stream = new MemoryStream();\n        bFormatter.Serialize(stream, this);\n        stream.Seek(0, SeekOrigin.Begin);\n        MyObj newObj = (MyObj)bFormatter.Deserialize(stream);\n        return newObj;\n    }	0
18589153	18588909	How to find lowest and highest time from list?	var StringList = new[] { "21:25:46.123" };\nList<TimeSpan> time = StringList\n                      .Select(x => TimeSpan.ParseExact(x, @"hh\:mm\:ss\.fff", null))\n                      .ToList();\nvar max = time.Max();\nvar min = time.Min();	0
1217600	1217591	C#: Adding extension methods to a base class so that they appear in derived classes	IEnumerable<T>	0
13806636	13806254	Create a ZIP file without entries touching the disk?	using (ZipFile zip = new ZipFile())\n  {\n    ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);\n    e.Comment = "The content for entry in the zip file was obtained from a stream";\n    zip.AddFile("Readme.txt");\n    zip.Save(zipFileToCreate);\n  }	0
19432274	19431410	Rotate unity button	using UnityEngine;\nusing System.Collections;\n\n    public class RotateButton: MonoBehaviour {\n        private float rotAngle = 0;\n        private Vector2 pivotPoint;\n        void OnGUI() {\n            pivotPoint = new Vector2(Screen.width / 2, Screen.height / 2);\n            GUIUtility.RotateAroundPivot(rotAngle, pivotPoint);\n            if (GUI.Button(new Rect(Screen.width / 2 - 25, Screen.height / 2 - 25, 50, 50), "Rotate"))\n                rotAngle += 10; //This is rotating it 10 degrees.\n\n        }\n    }	0
22618587	22618303	DateTime Parsing "Wed Mar 12 2014 17:50:15 GMT+0000	string value = "Wed Mar 12 2014 17:50:15 GMT+0000 (UTC)";\nvalue = value.Replace("GMT","").Replace("(UTC)","").Trim();\nvalue = value.Insert(value.Length - 2, ":");\nDateTime parsed = DateTime.ParseExact(value, "ddd MMM dd yyyy HH:mm:ss zzz", \n                                      CultureInfo.InvariantCulture);	0
33435817	33434443	Download file at custom path using Selenium WebDriver	var chromeOptions = new ChromeOptions();\n chromeOptions.AddUserProfilePreference("download.default_directory", "Your_Path");\n chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");\n chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");\nvar driver = new ChromeDriver("Driver_Path", chromeOptions);	0
32784391	32784175	Very specific case regarding button click	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Support.UI;\nusing OpenQA.Selenium.Chrome;\n\n\nnamespace WEBDRIVER\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      IWebDriver driver = new ChromeDriver();\n      driver.Navigate().GoToUrl("http://www.google.com/");\n      IWebElement query = driver.FindElement(By.Name("q"));\n      query.SendKeys("banana");\n      query.Submit();\n\n      WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));\n      wait.Until((d) => { return d.Title.ToLower().StartsWith("banana"); });\n\n      System.Console.WriteLine("Page title is: " + driver.Title);\n      driver.Quit();\n    }\n  }\n}	0
20391637	20391504	Convert System Date and time into integer	var timeDiff=DateTime.UtcNow - new DateTime(1970, 1, 1);\n    var totaltime = timeDiff.TotalMilliseconds;	0
7786944	7786876	Increase Menu items distance	.MainMenu ul li\n    {\n        width: 200px;\n    }	0
4558827	4558712	C# Regex: Get group names?	public string[] GetGroupNames(Regex re)\n{\n    var groupNames = re.GetGroupNames();\n    var groupNumbers = re.GetGroupNumbers();\n\n    Contract.Assert(groupNames.Length == groupNumbers.Length);\n\n    return Enumerable.Range(0, groupNames.Length)\n        .Where(i => groupNames[i] != groupNumbers[i].ToString())\n        .Select(i => groupNames[i])\n        .ToArray();\n}	0
24286425	24286076	LINQ update column in table 1 with id from table 2 where emails match?	foreach (Email ema in query)\n{\n    ema.DonorID = join.FirstOrDefault(j => j.Sender == ema.Sender).DID;\n}	0
28090534	28090438	OpenStreetMap XML to Object	way.Tags = doc.Descendants ("tag").Select (c => new OSMTag () {\n        Key = c.Attribute ("k").Value,\n        Value = c.Attribute ("v").Value\n    }).ToList();	0
11922048	11922038	Add Image to C# DataGridView	private void button1_Click(object sender, EventArgs e)\n{\n    dataGridView1.ColumnCount = 3;\n    dataGridView1.Columns[0].Name = "Product ID";\n    dataGridView1.Columns[1].Name = "Product Name";\n    dataGridView1.Columns[2].Name = "Product Price";\n\n    string[] row = new string[] { "1", "Product 1", "1000" };\n    dataGridView1.Rows.Add(row);\n    row = new string[] { "2", "Product 2", "2000" };\n    dataGridView1.Rows.Add(row);\n    row = new string[] { "3", "Product 3", "3000" };\n    dataGridView1.Rows.Add(row);\n    row = new string[] { "4", "Product 4", "4000" };\n    dataGridView1.Rows.Add(row);\n\n    DataGridViewImageColumn img = new DataGridViewImageColumn();\n    Image image = Image.FromFile("Image Path");\n    img.Image = image;\n    dataGridView1.Columns.Add(img);\n    img.HeaderText = "Image";\n    img.Name = "img";\n\n}	0
13017826	13017750	Method to take in any Enum	public static void MyFunction<T>(T en) where T: IComparable, IFormattable, IConvertible\n{\n    if (!typeof(T).IsEnum)\n        throw new ArgumentException("en must be enum type");\n    // implementation\n}	0
7595378	7595339	Getting Sum Of Numbers In Each Line Of File	StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");\nstring s = ar.ReadLine();\nwhile (s != null)\n{\n    //string[] spl = s.Split(' ');\n    // below code seems safer, blatantly copied from one of the other answers..\n    string[] spl = s.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);\n    MessageBox.Show(spl[0]);\n    s = ar.ReadLine();\n }	0
30733245	30732766	how to listen a cell of gridview if its value changed	private void grid_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n{\n    // do something with grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value\n}	0
27798069	27797944	How do I set a DefaultValue of a list property?	[Setting, DefaultValue(default(List<string>)]\npublic List<string> AcceptList { get; set; }	0
5332816	5332546	Binding const member in code behind from xaml in WPF	Uid="{x:Static local:YourClass.ID_foo}"	0
791313	764004	Reset primary key	sharedDS.Clear();\nsharedDS.Table1.Columns[0].AutoIncrementStep = -1;\nsharedDS.Table1.Columns[0].AutoIncrementSeed = -1;\nsharedDS.Table1.Columns[0].AutoIncrementStep = 1;\nsharedDS.Table1.Columns[0].AutoIncrementSeed = 1;	0
926852	926801	Overloading a method that takes a generic list with different types as a parameter	private static List<allocations> GetAllocationList<T>(List<T> allocations) \n   where T : BasePAllocationClass\n{\n\n}	0
26360995	26360881	How to get names of css classes of an element	element.getAttribute("className");	0
17235171	17229880	Indexer with default parameters	Dim obj As New Foo\nobj = Nothing	0
4112748	4112736	C# trim application path	Uri path = new Uri(@"C:\Documents and Settings\david\My Documents\app\stuff\file.txt");\nUri workingDirectory = new Uri(Directory.GetCurrentDirectory());\nstring relativePath = workingDirectory.MakeRelativeUri(path).ToString();	0
31982445	31982078	How Can i get DateArray of current Running Week With Month a Day And Month in Asp.net C#	public static void Main()\n    {\n        DayOfWeek firstWeekDay = DayOfWeek.Monday;\n        DateTime input = DateTime.Now;\n        int delta = firstWeekDay - input.DayOfWeek;\n        DateTime monday = input.AddDays(delta);\n        var array = Enumerable.Range(0, 7).Select(x => monday.AddDays(x).ToString("dd MMM")).ToArray();\n        Console.WriteLine("{0}", string.Join(" | ", array));\n    }	0
9940687	9940646	Creating a string from a list	try\n\n DirectoryPath=""\nforeach (string s in Directory)\n        {\n\n            DirectoryPath = DirectoryPath.equals("")?  s : '/' + DirectoryPath + '/' + s + '/';\n        }	0
5159268	5157448	Adding a prefix to an xml node	String xmlWithoutNamespace =\n                @"<Folio><Node1>Value1</Node1><Node2>Value2</Node2><Node3>Value3</Node3></Folio>";\n            String prefix ="vs";\n            String testNamespace = "http://www.testnamespace/vs/";\n            XmlDocument xmlDocument = new XmlDocument();\n\n            XElement folio = XElement.Parse(xmlWithoutNamespace);\n            XmlElement folioNode = xmlDocument.CreateElement(prefix, folio.Name.LocalName, testNamespace);\n\n            var nodes = from node in folio.Elements()\n                        select node;\n\n            foreach (XElement item in nodes)\n            {\n                var node = xmlDocument.CreateElement(prefix, item.Name.ToString(), testNamespace);\n                node.InnerText = item.Value;\n                folioNode.AppendChild(node);\n            }\n\n            xmlDocument.AppendChild(folioNode);	0
30635879	30635778	How to get the value from listbox?	float val = 0;\nfloat.TryParse(textBox6.Text, out val);	0
133577	133487	How do I remove an element that matches a given criteria from a LinkedList in C#?	list.Remove(list.First(e => e.id == searchId));	0
16374498	16374442	Select from two entities with LINQ	var validation = cx.Validations.Where(v=>v.Code==Code &&\n                                         cx.Users.Any(u=>u.UserID==v.UserID && \n                                                         u.UserGuid==UserGuid)\n                                      ).FirstOrDefault();	0
3080671	3080616	How can i fill 1D array from 2D array and how can i sort 1D array?	int[] UnSortedlist = lengths.SelectMany(x => x).ToArray();\n            int[] sortedListLinq = UnSortedlist.OrderBy(x => x).ToArray();\n            Array.Sort(UnSortedlist);\n            int[] sortedListnonLinq = UnSortedlist;	0
34369538	34369149	Swap opened dialog on top of newly opened modal window	[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool EnableWindow(IntPtr hWnd, bool bEnable);\n\nprivate void ModalDialog_Shown(object sender, EventArgs e)\n{\n    for (int i = 0; i < Application.OpenForms.Count; i++)\n    {\n        var f = Application.OpenForms[i];\n        if (f is OtherDialogWichShouldBeOverModal)\n        {\n            EnableWindow(f.Handle, true);\n            f.Activate();\n            //...\n        }\n    }\n}	0
10699387	10698800	get dictionary from xdocument c#	Dictionary<string, string> dataDictionary = null;\n\n        foreach (XElement elem in doc.Descendants("Person")) \n        { \n            var row = elem.Descendants(); \n            string str = elem.ToString();\n\n            dataDictionary = new Dictionary<string, string>();\n\n            foreach (XElement element in row) \n            { \n                string keyName = element.Name.LocalName; \n                dataDictionary.Add(keyName, element.Value); \n            } \n\n            yield return dataDictionary; \n        }	0
10972905	10972850	How is a Hex Value manipulated bitwise?	#7 = 0x80 = %1000 0000\n#6 = 0x40 = %0100 0000\n#5 = 0x20 = %0010 0000\n#4 = 0x10 = %0001 0000\n\n#3 = 0x08 = %0000 1000\n#2 = 0x04 = %0000 0100\n#1 = 0x02 = %0000 0010\n#0 = 0x01 = %0000 0001	0
9600602	9600496	Remembering fileName after application closes	//get\nvar name = Properties.Settings.Default.FileName;\n\n//set\nProperties.Settings.Default.FileName = "....";\nProperties.Settings.Default.Save();	0
19572435	19570604	AggregateException in release mode	try\n{\n    Task.WaitAll(task1, task2, task3);\n}\ncatch (AggregateException ex)\n{\n    foreach (Exception exx in ex.Flatten().InnerExceptions)\n        Console.WriteLine(exx.Message);\n}	0
16720788	16720642	linq-to-sql SelectMany() troubles	return db.document_library_sitefiles\n         .Where(item => item.SiteID == siteId)\n         .Select(item => item.document_library)\n         .GroupBy(item => item.Filename)\n         .Select(group => group.OrderByDescending(p=>p.Version).First())\n         .Where(item => !item.Filename.Contains("*"))\n         .Select( item => new { filename = item.document_library.filename, \n                               filesize = item.document_library.filesize } ).ToList();	0
2425888	2425835	How would you make a "Favorite Pages" system	FavoritePages\n*************\npageId (pk, int)\ntitle (string)\nurl (string)\n\nFavorites\n*********\nuserId (fk)\npageId (fk)	0
17687030	17686843	Null reference exception after a certain amount of seconds	var form = Form.ActiveForm as Form1;\nif (form != null)\n{\nvar doSave = MessageBox.Show("Would you like to save this measurement?",\n                             "Save Measurement",\n                             MessageBoxButtons.YesNo,\n                             MessageBoxIcon.Question);\n\nif (doSave == DialogResult.Yes) // User wants to save the current measurement.\n{\n    curName = ShowDialog("Measurement Name", "Save Measurement");\n    // ERROR HERE **** \n    int ret = form.databaseClass.GetFirstSoundReadyTestOccurrence(form.testNumber.Text);\n}\n}	0
8212926	8212893	ASP.NET Cross-Page Posting without PreviousPage	Request.Form["someid"];	0
15139292	15139167	Do unimplement partial methods get replaced with null when used as a delegate parameter?	DoSomething(() => DoWorkInForEach());	0
25151092	25149935	How to parse string XML and extract int values	string _xml = "<IDs><ID>1</ID><ID>2</ID><ID>3</ID><ID>4</ID></IDs>";\n\n        XmlTextReader _xtr = new XmlTextReader(new StringReader(_xml));\n        _xtr.WhitespaceHandling = WhitespaceHandling.Significant;\n\n        XmlDocument _xdoc = new XmlDocument();\n        _xdoc.Load(_xtr);\n\n        XmlElement root = _xdoc.DocumentElement;\n        XmlNodeList nodes = root.SelectNodes("/IDs/ID");\n\n        int[] _ids = new int[4];\n        int i = 0;\n\n        foreach (XmlNode node in nodes)\n        {\n            _ids[i] = Convert.ToInt32(node.InnerText);\n            i++;\n        }	0
18109237	18109191	How to find a match with 2 comma separated strings with LINQ	var masterSet = new HashSet<string>(masterFormList.Split(','));\n\nresultsList = resultsList\n                 .Where(r => r.FormCodes.Split(',')\n                              .Any(code => masterSet.Contains(code)))\n                 .ToList();	0
13481583	13481558	Converting a Bitmap image to a matrix	public Color[][] GetBitMapColorMatrix(string bitmapFilePath)\n    {\n        bitmapFilePath = @"C:\9673780.jpg";\n        Bitmap b1 = new Bitmap(bitmapFilePath);\n\n        int hight = b1.Height;\n        int width = b1.Width;\n\n        Color[][] colorMatrix = new Color[width][];\n        for (int i = 0; i < width; i++)\n        {\n            colorMatrix[i] = new Color[hight];\n            for (int j = 0; j < hight; j++)\n            {\n                colorMatrix[i][j] = b1.GetPixel(i, j);\n            }\n        }\n        return colorMatrix;\n    }	0
4757700	4757673	c# save settings	Properties.Settings.Default.SettingName	0
13979530	13979289	Group a List<object[]>	List<object[]> grouped = olst\n    .GroupBy(o => new { Prop1 = o[0].ToString(), Prop2 = o[1].ToString() })\n    .Select(o => new object[] \n    {\n        o.Key.Prop1,\n        o.Key.Prop2,\n        o.Sum(x => (int)x[2]),\n        o.Sum(x => (double)x[3])\n    })\n    .ToList();	0
3665082	3665048	How to disable the last blank line in DatagridView?	myDataGridView1.AllowUserToAddRows = false	0
9748424	9748411	counting numbers in array above a certain level with C#	int count = array.Where(x => x > 15).Distinct().Count();	0
24787851	24787155	How to update a list continuously without freezing the UI	private static string[] processNamesICareAbout =\n    new[] { "notepad", "calc", "cmd" };\nprivate async void process_viewer()\n{\n    while (true)\n    {\n        var processes = Process.GetProcesses()\n            .Select(process => process.ProcessName);\n\n        running.SelectionMode = SelectionMode.None;\n        stopped.SelectionMode = SelectionMode.None;\n        running.DataSource = processNamesICareAbout.Intersect(processes).ToList();\n        stopped.DataSource = processNamesICareAbout.Except(processes).ToList();\n\n        await Task.Delay(500);\n    }\n}	0
7901944	7901918	How do I call a different constructor from within a constructor in the same object?	public DataForm(System.Data.DataSet theData): this(new List<System.Data.DataSet>{theData}){}\n\npublic DataForm(DataSet[] DataArray): this(DataArray.ToList()){}\n\npublic DataForm( List<System.Data.DataSet> DataList )\n{\n    InitializeComponent();\n\n    // Assign the list of datasets to teh member variable\n    this.m_DSList = DataList;\n\n    CreateTabPages();\n}	0
22686638	22686580	Convert date to specific format if I don't know source date format	DateTime.Now.toString("yyyy-MM-dd"); //toString(specify format)	0
1496004	1495988	How can I check if a string contains a number smaller than an integer?	int i;\nif (int.TryParse(theOrder.OrderData, out i))\n{\n    if (i < 10000)\n    {\n       // Do stuff...\n    }\n}	0
21444028	21443843	foreach listview items from another thread	void createMoviesXML()\n{\n    objectListView1.Invoke(new Action(() =>\n    {\n        foreach (var item in objectListView1.Items)\n        {\n            // Do stuff\n        }\n    }));\n}	0
13892496	13890805	How to redirect to login page client side	function redirectme()\n{\n@if(Session["key"]==null)\n{\n<text>window.location.href='/Account/Login';</text>\n}\n}	0
15125649	15125458	Linking C# desktop app with Rails web app	var process = new Process();\nprocess.StartInfo.FileName = "iexplore";\nprocess.StartInfo.Arguments = @"http:\\myreportgenerator.com?customerid=1234";\nprocess.Start();	0
28650464	28649552	Show only 1 image from each group instead of showing all of them from each group	DataSource='<%# MyFilteredImageCollection(Eval("Images")) %>'	0
2610853	2610780	How to use Microsoft Speech Object Library to create a wav file	public void TextToSpeech(string text, string fileName)\n{\n   using (var stream = File.Create(fileName))\n   {\n      SpeechSynthesizer speechEngine = new SpeechSynthesizer();\n      speechEngine.SetOutputToWaveStream(stream);\n      speechEngine.Speak(text);\n      stream.Flush();\n   }\n}	0
13666176	13656243	Row Index provided is out of range, even after check	For each(TreeNode TN in ConTreeView) \n{ \n   ConTreeView.Nodes.Remove(TN); \n}	0
9706218	9705838	ASP.NET - How to find out if the user is a mobile user?	string sUA = Request.UserAgent.Trim().ToLower();\n\n    uaString.InnerText = Request.UserAgent;\n\n    if (sUA.Contains("ipod") || sUA.Contains("iphone"))\n        isMobile = true;\n\n    if (sUA.Contains("android"))\n        isMobile = true;\n\n    if (sUA.Contains("opera mobi"))\n        isMobile = true;\n\n    if (sUA.Contains("windows phone os") && sUA.Contains("iemobile"))\n        isMobile = true;\n\n    if (sUA.Contains("fennec"))\n        isMobile = true;	0
26289663	26289590	C# skipping a part of my code	format = Convert.ToChar(Console.ReadLine());	0
27597174	27597108	Referencing Web Api Locally from serperate MVC Application	public string GetInvoiveNo(int id)\n    {\n        var uri = WebUrl + id;\n        using (var httpClient = new HttpClient())\n        {\n            var response = httpClient.GetStringAsync(uri);\n\n            return JsonConvert.DeserializeObjectAsync<string>(response.Result).Result;\n        }\n    }	0
20372067	20371932	MultiSelectList data binding and Model validation in MVC	else\n    {\nmodel.AuthorList = _Authors.GetAuthors()\n                          .Select(a => new SelectListItem { \n                                     Value = a.Id.ToString(), \n                                     Text = a.Name }\n                                 ).ToList()\n        return View(model);\n    }	0
17451669	11533767	C# Copying a Folder to another destination with Security/Permission Settings	DirectoryInfo dir1 = new DirectoryInfo(@"C:\Temp\Dir1");\nDirectoryInfo dir2 = new DirectoryInfo(@"C:\Temp\Dir2");  \n\n\nDirectorySecurity ds1 = dir1.GetAccessControl();\nDirectorySecurity ds2 = new DirectorySecurity();\nds2.SetSecurityDescriptorBinaryForm(ds1.GetSecurityDescriptorBinaryForm());\ndir2.SetAccessControl(ds2);	0
3720992	3720896	Parse log file and get matching data	StreamReader sr = new StreamReader(@"path_to_log");\n\nint lineNum = 1;\nconst int searchingLineNum = 10;\nstring line = string.Empty;\n\nwhile (sr.Peek() != -1)\n{\n    line = sr.ReadLine();\n\n    if (lineNum == searchingLineNum)\n    {\n        break;\n    }\n    lineNum++;\n}\n\nConsole.WriteLine(line); // do what you want with this line (parse using Regex)	0
25253132	21979274	How to programmatically Submit Hive Queries using C# in HDInsight Emulator?	var creds = new BasicAuthCredential();\n        creds.UserName = "hadoop";\n        creds.Password = "";\n        creds.Server = new Uri("http://localhost:50111");\n        var jobClient = JobSubmissionClientFactory.Connect(creds);\n        var hiveJob = new HiveJobCreateParameters()\n        {\n            Query = "select * from hivesampletable limit 10;",\n            StatusFolder = "/samplequeryoutput"\n        };\n        var jobResults = jobClient.CreateHiveJob(hiveJob);	0
4943004	4942794	TimeSpan for different years substracted from a bigger TimeSpan	var start = new DateTime(2009, 10, 12);\n    var end = new DateTime(2014, 12, 25);\n\n    var s = from j in Enumerable.Range(start.Year, end.Year + 1 - start.Year)\n            let _start = start.Year == j ? start : new DateTime(j, 1, 1)\n            let _end = end.Year == j ? end : new DateTime(j, 12, 31)\n            select new { \n                year = j,\n                days = Convert.ToInt32((_end - _start).TotalDays) + 1                    \n            };	0
30205426	30205401	Want to change JSON Format	public class ContactList {\n    public List<Contact> contacts { get; set; }\n}	0
29934705	29934610	LINQ- to retrieve the third layer list of objects from a list which contains three layers	var data = CategoryA.CategoryB\n    .Where(b => b.CategoryBObjectId == someBid)\n    .SelectMany(b => b.CategoryC)\n    .Where(c => c.CategoryCObjectId == someCid)\n    .ToList();	0
30610002	30609951	How do i make my void comiler read a string and print in the MessageBox what is after it?	namespace WindowsFormsApplication1\n   {\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n\n        }\n\n        private void compiler()\n        {\n            String print = TB.Text;\n            if (print.ToLowerInvariant().StartsWith("print ")\n            {\n              String sP = print.Substring(print.IndexOf(' ') + 1);\n              MessageBox.Show(sP, "Console");\n            }\n        }\n\n        private void TB_TextChanged(object sender, EventArgs e)\n        {\n            compiler();\n        }\n\n        private void runToolStripMenuItem_Click(object sender, EventArgs e)\n        {\n            compiler();\n        }\n    }\n    }	0
11216412	9771459	retrieving X509 certificates from AD Server	DirectoryEntry de = new DirectoryEntry("LDAP://#####");  //Where ##### is the name of your AD server\n        DirectorySearcher dsearch = new DirectorySearcher(de);\n        dsearch.Filter = "(cn=#####)"; //Search how you want.  Google "LDAP Filter" for more.\n        SearchResultCollection rc = dsearch.FindAll();\n        X509Certificate stt = new X509Certificate();\n\n        foreach (SearchResult r in rc)\n        {\n\n            if (r.Properties.Contains("userCertificate"))\n            {\n                Byte[] b = (Byte[])r.Properties["userCertificate"][0];  //This is hard coded to the first element.  Some users may have multiples.  Use ADSI Edit to find out more.\n                X509Certificate cert1 = new X509Certificate(b);\n            }\n        }	0
20428389	20200925	How do I map an Oracle timestamp to a DateTime in Fluent NHibernate?	string sql = @"SELECT CONTAINER_ID,\nPLANT_ID,\nMATERIAL_ID,\nQTY_IN,\nQTY_OUT,\nUNIT_OF_MEASURE,\nTO_CHAR (EXPIRE_DATE, 'YYYY-MON-DD HH24:MI:SS') AS MY_EXPIRE_DATE,\nLOT_ID,\nCONTAINER_STATUS,\nCONTENTS_TYPE\nFROM POMSNET.MM_CONTAINER_ST\nWHERE CONTENTS_TYPE = 'Raw Material'\nAND QTY_IN - QTY_OUT > 0";	0
6415638	6415620	C# - Using regex with if statements	String AllowedChars = @"^[a-zA-Z0-9]*$";	0
3995384	3995295	C# topmost window	formWithoutBorders.AddOwnedForm(borderForm);\nborderForm.Show();	0
20578468	20576458	How can I dynamically build a linq OR query where one of several columns can match the search string?	private static IQueryable<Db.Category> FilterContains(string searchFor, string excludedBrFields, IQueryable<Db.Category> categories)\n{\n    if (searchFor.StartsWith("*") && searchFor.EndsWith("*"))\n    {\n        searchFor = searchFor.Substring(1, searchFor.Length - 2);\n    }\n    searchFor = searchFor.ToLower();\n\n    var predicate = PredicateBuilder.False<Db.Category>();\n    if (!excludedBrFields.Contains("Title"))\n    {\n        predicate = predicate.Or(x => x.Title.ToLower().Contains(searchFor));\n    }\n\n    if (!excludedBrFields.Contains("Description"))\n    {\n        predicate = predicate.Or(x => x.Description != null && x.Description.ToLower().Contains(searchFor));\n    }\n\n    if (!excludedBrFields.Contains("Comments"))\n    {\n        predicate = predicate.Or(x => x.Comments != null && x.Comments.ToLower().Contains(searchFor));\n    }\n    return categories.Where(predicate.Compile()).AsQueryable();\n}	0
2558883	2558791	XML : how to remove all nodes which have no attributes nor child elements	var xmlDocument = new XmlDocument();\nxmlDocument.LoadXml(\n@"<Node1 attrib1=""abc"">\n        <node1_1>\n             <node1_1_1 />\n        </node1_1>\n    </Node1>\n    ");\n\n// select all nodes without attributes and without children\nvar nodes = xmlDocument.SelectNodes("//*[count(@*) = 0 and count(child::*) = 0]");\n\nConsole.WriteLine("Found {0} empty nodes", nodes.Count);\n\n// now remove matched nodes from their parent\nforeach(XmlNode node in nodes)\n    node.ParentNode.RemoveChild(node);\n\nConsole.WriteLine(xmlDocument.OuterXml);\nConsole.ReadLine();	0
6711384	5425047	Overloading Controller methods with custom JSON(POST) binding in MVC3	[HttpPost]\npublic ActionResult GetPet()\n{\nCat catObj;\nDog dogObg;\nif (TryUpdateModel(catObj))\n        return Json(catObj.purr());\nelse\n{\n    ModelState.Clear();\n    if (TryUpdateModel(dogObg))\n        return Json(dogObj.bark());\n    else\n    {\n        ModelState.Clear();\n        ModelState.AddModelError("InvalidInput", "The given input does not match with any of the accepted JSON types");\n        return new HttpBadRequestResult(ModelState);\n    }\n}\n\n}	0
1189893	1189576	DataGridView AutoGenerateColumns is set to true somehow	public override void Initialize(IComponent component)  \n{\n  ...\n  view.AutoGenerateColumns = view.DataSource == null;\n  ...\n}	0
8526811	8526762	a correct way of forcing assembly load into current domain	typeof(AssemblyB.AssemblyB_Type).ToString();	0
7787927	7787921	How to rapdily shift 10-bit intensities to top of 16-bit pixels?	fixed(UInt16* p0=&arr)\n{\n    UInt32* p=(UInt32*)p0;\n    UInt32* p_end=p+1000*1000/(sizeof(UInt32)/sizeof(UInt16));\n    while(p!=p_end)\n    {\n        *p = *p << 6;\n    }\n}	0
10537772	10537628	Obtaining multiple fields with LINQ group statement	let latestNote = latestNoteDate == null ? null : \n                 g.First(x => x.notes.Date == latestNoteDate).NoteText	0
25793167	25792649	Trying to bind DateTime.Now in gridview	GetDate()	0
31249322	29391887	How to update client endpoint binding in code	var binding = new System.ServiceModel.BasicHttpBinding() { Name = "LocalServiceClient", Namespace = "LocalService.SendRequest" };\nvar endPoint = new System.ServiceModel.EndpointAddress("http://localhost/LocalService/SendRequest.asmx");\nvar client = new ServiceClient(binding, endPoint);	0
24881870	24878605	How do I not print a node when it is null	XDocument xmldoc = XDocument.Parse(chkData);\nvar emptyNodes = xmldoc.Descendants().Where(o => o.IsEmpty).ToList();\nforeach (XElement n in emptyNodes)\n{\n    n.Remove();\n}\n//here you can continue with your logic to generate TokenValues\n.....\n.....	0
17398654	17397199	Assembly load XML document from memorystream C#	var _XMLDoc = new XmlDocument();\n_XMLDoc.LoadXml(dataset.GetXml());\nvar byteArray = Encoding.ASCII.GetBytes(_XMLDoc.OuterXml);\nusing (var stream = new MemoryStream(byteArray))\n{\n    // ProcessStream(stream);\n}	0
6344875	6344536	fill dataset with data from SQLDataSource asp.net c#	OdbcCommand cmd = conn.CreateCommand();\ncmd.CommandText = "SELECT NAME, SORG_GP, EXPEND, INV_GP, SRTN_GP FROM MTD_FIGURE_VIEW1";\nnew OdbcDataAdapter(cmd).Fill(ds);	0
20102444	20102320	C# Change color of one character in a text box	var textRange = MyRichTextBox.Selection;\nvar start = MyRichTextBox.Document.ContentStart;\nvar startPos = start.GetPositionAtOffset(0);\nvar endPos = start.GetPositionAtOffset(1);\ntextRange.Select(startPos, endPos);\ntextRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));	0
29726430	29726396	How use the same method for different classes as parameter	public interface IRecord {\n    int Counter { get; set; }\n    int Pressure { get; set; }\n}\n\npublic class GasConsumRecord : IRecord {\n    public int Counter { get; set; }\n    public int Pressure { get; set; }\n}\n\npublic class AirConsumRecord : IRecord {\n    public int Counter { get; set; }\n    public int Pressure { get; set; }\n}\n\nprivate Double CalculateConsumption<T>(List<T> records)\n    where T : IRecord\n{\n    foreach (IRecord record in records){\n        var x = record.Counter;\n        var y = record.Pressure;\n    }\n}	0
1419174	1419096	parse iCalendar date using c#	string strDate = "2009-08-11T10:00+05:0000";\nDateTimeFormatInfo dtfi = new DateTimeFormatInfo();\ndtfi.FullDateTimePattern = "yyyy-MM-ddTHH:mmzzz";\n\nDateTime dt = DateTime.Parse(c.Substring(0, c.Length-2), dtfi);	0
17920024	17521796	right to left support for data Grid	FlowDirection="RightToLeft"	0
3607095	3606922	How can i display item on itemList of devexpress LookupEdit	lkpReference.Properties.DataSource = _lab.selectLabReference() ;\nlkpReference.Properties.DisplayMember = "refernce_name";\nlkpReference.Properties.ValueMember = "lab_ref_id";\nlkpReference.Properties.BestFitMode = BestFitMode.BestFit;\nlkpReference.Properties.SearchMode = SearchMode.AutoComplete;\n\n// the constructor you are using accepts 2 parameters: FieldName (which is the name\n// of the field from the DataTable) and Width (which is the width of the column\n// displayed in the dropdown). You have set both parameters wrong.\n\n//LookUpColumnInfoCollection collns = lkpReference.Properties.Columns;\n//collns.Add(new LookUpColumnInfo("Lab Reference", 0));\n\n// what you intended to do is this\nlkpReference.Properties.Columns.Add(new LookUpColumnInfo("refernce_name", 100, "Lab Reference"));\n\nlkpReference.Properties.AutoSearchColumnIndex = 1;	0
22320767	22320507	Get where is mySaveFileDialog folder	FileInfo fi = new FileInfo(mySaveFileDialog.FileName);\n\n\\Then you can use the properties of the FileInfo object to retrieve the\n\\information you want:\n\nfi.DirectoryName \\ the directory's full path	0
9198888	9198604	How to refactor these locks?	class Parent\n{\n  public void Method1()\n  {\n    using(acquireLock())\n    {\n      Method1Impl();\n    }\n  }\n  protected abstract IDisposable acquireLock();\n  protected abstract void Method1Impl();\n}\nclass Child : Parent\n{\n   protected override IDisposable acquireLock()\n   {\n      // return some class that does appropriate locking \n      // and in Dispose releases the lock.\n      // may even be no-op locking.\n   }\n}	0
17433824	17433745	Make the window always maximized	ResizeMode="CanMinimize" WindowState="Maximized"	0
509344	509305	Is there a predefined class for 3 linked values like the Hashtable?	Dictionary<Key, ThatTinyStructYouHadToCreate>	0
19289831	19289338	xmlwriter as input for xmlreader	MemoryStream stream = new MemoryStream();\nXmlWriter writer = XmlWriter.Create(stream);\n\n// Do some stuff with writer\n\nXmlReader reader = XmlReader.Create(stream);\n\n// Do some stuff with reader	0
29281763	29281127	Visibility binding with list item	public IEnumerable<MyItem> ReportsWithAnwers\n{\n    get\n    {\n       return Reports.Where(x => x.CountAnswers > 0);\n    }\n}\n\n<ListBox Name="QuestionList" ItemsSource="{Binding ReportsWithAnwers}">\n    <ListBox.ItemTemplate>\n        <DataTemplate >            \n             <TextBlock Text="{Binding CountAnswers}"/>                      \n        </DataTemplate>\n    </ListBox.ItemTemplate>\n</ListBox>	0
17586221	17586169	Linq compare 2 lists of arrays	var results = \n    from x in list1.Select((array, index) => new { array, index })\n    from y in list2.Select((array, index) => new { array, index })\n    select new \n    {\n        list1_index = x.index,\n        list2_index = y.index,\n        count = x.array.Intersect(y.array).Count()\n    };\n\nforeach(var r in results)\n{\n    Console.WriteLine("({0}, {1}) have {2} item(s) in common.", r.list1_index, r.list2_index, r.count);\n}\n// (0, 0) have 2 item(s) in common.\n// (0, 1) have 2 item(s) in common.\n// (0, 2) have 1 item(s) in common.\n// (1, 0) have 2 item(s) in common.\n// (1, 1) have 1 item(s) in common.\n// (1, 2) have 2 item(s) in common.	0
3078773	3078743	Convert .NET datetime to SQlite datetime	cmd.CommandText = @"select * from PhieuNhap where NgayNhap=$NgayNhap";\ncmd.Parameters.Add(new SQLiteParameter("$NgayNhap", ngayNhap));	0
10104457	10104403	send JSON request c# mvc3	public JsonResult details(string movieName)\n        {\n            var data = new {\n                               name="Movie name"\n                           };\n\n            return Json(data, JsonRequestBehavior.AllowGet);\n        }	0
10749264	10749151	Session Expiry on clicking Logout	protected void logout_OnClick(object sender, EventArgs e)\n{\nSession.Abandon();\nResponse.Redirect("login.aspx");\n}\n\nprotected void Page_Init(object sender, EventArgs e)\n{\nResponse.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));\nResponse.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.SetNoStore();\n}	0
2191164	2191141	Parse JSON in .NET runtime	var json = @"[[3014887,""string1 string"",""http://num60.webservice.com/u3014887/b_c9c0625b.jpg"",0], \n                      [3061529,""string2 string"",""http://num879.webservice.com/u3061529/b_320d6d36.jpg"",0],\n                      [7317649,""string3 string"",""http://num1233.webservice.com/u7317649/b_a60b3dc2.jpg"",0],\n                      [12851194,""string4 string"",""http://num843.webservice.com/u12851194/b_4e273fa4.jpg"",0],\n                      [15819606,""string5 string"",""http://num9782.webservice.com/u15819606/b_66333a8f.jpg"",0], \n                      [15947248,""string6 string"",""http://num1500.webservice.com/u15947248/b_920c8b64.jpg"",0]]";\nvar array = JArray.Parse(json);\n\nforeach (var token in array)\n{\n    Console.WriteLine(token[0]);\n}	0
19239898	19212829	code indentation in Doxygen using Xml comment	/// \code\n/// public void Method()\n/// {\n///     float x = 10, y = 10 , z = 0;\n///     Vector3 vector = new Vector3 (x, y, z);\n///     if(something)\n///         Other Code\n/// }\n/// \endcode	0
10910469	10907878	Autoincrement Id with transaction in Redis (ServiceStack RedisClient)	var a = new Article { \n   Id = Redis.As<Article>().GetNextSequence(), \n   Name = "I Love Writing Test" \n};\nRedis.Store(a);	0
25175178	25174964	How to fire HTML helper when the button is clicked using Javascript	function Test(){\n//call the code here that will fetch html form server.\n}	0
5540668	5540282	Setting and using MousePosition	private Point Pos;\n\n    protected override void WndProc(ref Message m)\n    {\n        if (m.Msg == 0x0312)   // Trap WM_HOTKEY\n        {\n            switch (m.WParam.ToInt32()) {\n               case 0: Pos = Cursor.Position; break;\n               case 1: Cursor.Position = Pos; break;\n            }\n        }\n        base.WndProc(ref m);\n    }	0
1691923	1686530	How do I create a new VFP (OLEDB) table from an existing one using .NET?	OleDbConnection oConn = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=C:\\SomePath");\nOleDbCommand oCmd = new OleDbCommand();\noCmd.Connection = oConn;\noCmd.Connection.Open();\noCmd.CommandText = "select * from SomeTable where someCondition into table YourNewTable";\noCmd.ExecuteNonQuery();         \noConn.Close();	0
34304915	34288819	Fetching a graph object from my sql DB using Fluent Nhibernate	public class Graph\n{\n    ....\n    public virtual Node RootNode {get;set;}\n}\n\npublic class Node\n{\n    ....\n    public virtual Graph Graph {get;set;}\n    public virtual IList<Link> Links { get; set; }\n}\n\npublic class Link\n{\n    ....\n    public virtual Node SourceNode { get; set; }\n    public virtual Node TargetNode { get; set; }\n}	0
13075809	13075757	Removing some characters from string using Regex	documentText.ToLower().Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)	0
5909323	5909252	How to use join in linq query?	var q = from c in customers\n        join o in orders on c.Key equals o.Key\n        select new {c.Name, o.OrderNumber};	0
4503559	4503542	Check for special characters (/*-+_@&$#%) in a string?	var regexItem = new Regex("^[a-zA-Z0-9 ]*$");\n\nif(regexItem.IsMatch(YOUR_STRING)){..}	0
3127402	3127394	How to remove stuff from a list in C#?	List<Structure> list;\nlist.RemoveAll(structure => structure.ID == 55);	0
10494194	10493831	C# get fsmo roles from ad	System.DirectoryServices.ActiveDirectory.Domain dom = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();\nSystem.DirectoryServices.ActiveDirectory.DomainController pdcdc = dom.PdcRoleOwner;\nforeach (System.DirectoryServices.ActiveDirectory.DomainController dc in dom.DomainControllers)\n                {\n                    foreach (ActiveDirectoryRole role in dc.Roles)\n                    {\n                        Console.WriteLine("dc : {0} role : {1}", dc.Name,role.ToString());\n                    }\n                }	0
8681045	8676167	XmlElement array as Children of specific node	var xDoc = new XmlDocument();\nvar docNode = xDoc.CreateElement("Document");\nforeach (var element in returnDocumentData)\n{\n    if (docNode.OwnerDocument != null)\n    {\n        //need to import the element because it's being generated from a\n        //different xmlDocument context\n        var importElement = docNode.OwnerDocument.ImportNode(element, true);\n        docNode.AppendChild(importElement);\n    }\n}	0
15515204	15502079	Excel Conditional Settings	var c = (Excel.IconSetCondition)excelWorksheet.get_Range(cell).FormatConditions.AddIconSetCondition();\nc.SetFirstPriority();\nc.ShowIconOnly = false;\nc.IconSet = book.IconSets[Excel.XlIconSet.xl3TrafficLights2];\nvar yellowIcon = c.IconCriteria[2];\nyellowIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;\nyellowIcon.Value = Convert.ToDouble(yellow);\nyellowIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;\n\nvar greenIcon = c.IconCriteria[3];\ngreenIcon.Type = Excel.XlConditionValueTypes.xlConditionValueNumber;\ngreenIcon.Value = Convert.ToDouble(green);\ngreenIcon.Operator = (int)Excel.XlFormatConditionOperator.xlGreaterEqual;	0
31935845	31935751	Accessing property	public class SomeClass<TElement>\n    where TElement : YourBaseClass\n{ ... }	0
15164306	15162537	Export data from DataTable into Excel 2007	DataTable dt = new DataTable();\n        dt.Columns.Add("A");\n        dt.Columns.Add("B");\n\n        dt.Rows.Add(new object[] { "Name", "No" });\n        dt.Rows.Add(new object[] { "Stalin", "=\"001\""});\n        dt.Rows.Add(new object[] { "Micheal", "=\"002\"" });	0
21725009	21724913	Adding custom value in a LINQ join	(CashFlow, Trade) => new\n         {\n            Type = "Fx",\n            CashFlow.TradeId,\n            Trade.TradeReference,\n            CashFlow.PaymentAmount,\n            CashFlow.CurrencyCode,\n            CashFlow.PaymentDate,\n            CashFlow.CashflowTypeCode\n         }	0
5369627	5369604	C# - simplifying interface	IBaseFoo (5 methods)\n  IFoo : IBaseFoo  (20 more methods)	0
19944924	19944875	How to add up amount of data from an external file in C# (Stream Reader)	string sName;\ndouble dAmount;\nint sTotalNames = 0;\ndouble dAmountTotal = 0;\ndouble dAmountAverage;\n\nusing (StreamReader sr = new StreamReader("Donations.txt"))\n{\n    while (sr.Peek() != -1)\n    {\n        sName = sr.ReadLine();\n        Console.WriteLine(sName);\n\n        dAmount = Convert.ToDouble(sr.ReadLine());\n        Console.WriteLine(dAmount);\n        dAmountTotal += dAmount;\n        sTotalNames++;\n    }\n    dAmountAverage = dAmountTotal / sTotalNames;\n    Console.WriteLine("Sum = {0}", dAmountTotal );\n    Console.WriteLine("Total Names = {0}", sTotalNames);\n    Console.WriteLine("Average Amount = {0}", dAmountAverage);\n    Console.WriteLine("Press any key to close");\n    Console.ReadKey();\n}	0
32740099	32739950	Display dates attached to events in a database with C#	client.GetEventInstances()\n      .Where(x => x.Details.TypeOfEvent.Contains("Exhibition"))\n      .OrderBy(x => x.StartDate))\n      .First()	0
8486033	8485209	How to fillter the database null values of integer column in C# using if condition?	if (dt.Rows[0]["ToAge"] == DBNull.Value)	0
3110328	3102902	How to get table name of a column from SqlDataReader	reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);	0
33194170	33194073	Escape the quotes in a C# string	private string escapestring(string input, int depth)\n{\n    var numSlashes = (int)(Math.Pow(2, depth)-1);\n    return input.Replace("\"", new string('\\', numSlashes)+"\"");\n}	0
33259860	33259701	Setting a property of an asp control and reloading the page with changes	ListViewTemp.DataBind();	0
31918476	31917601	Is there a way to Wait for a TPL Task without in throwing an exception?	var task = Task.Run(() =>\n        {\n            // ...\n            throw new Exception("Blah");\n        });\n        Task.WaitAny(task);\n        if (task.IsFaulted)\n        {\n            var error = task.Exception;\n            // ...\n        }\n        else if (task.IsCanceled)\n        {\n            // ...\n        }\n        else\n        {\n            // Success\n        }	0
18013301	18012886	MVC - How to check for white space in a text box	public class AlphaSpaceAttribute : RegularExpressionAttribute, IClientValidatable\n{\n    public AlphaSpaceAttribute()\n        : base(@"^([a-zA-Z ]*)\s*")\n    {\n    }\n    public override string FormatErrorMessage(string name)\n    {\n        return Resources.UDynamics.EM_10003;\n    }\n\n    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n    {\n        var rule = new ModelClientValidationRule\n        {\n            ErrorMessage = FormatErrorMessage(this.ErrorMessage),\n            ValidationType = "regex",\n        };\n        rule.ValidationParameters.Add("pattern", @"^([a-zA-Z ]*)\s*");\n        yield return rule;\n    }\n\n\n}	0
21882656	21882235	How to retrieve data using Linq Query	OrderIDwithMaxQuanCount=customergroups.OrderByDescending(x => x.o.Quantity)\n                                       .Select(x => x.o.Orderid).FirstOrDefault()	0
4523510	4516470	lambda expression trying to query one list based on another	var agencySupervisors = (from ap in agency.AgencyPersonnel\n                                    where ap != null\n                                        select ap.AgencyPersonnelId).ToList();\n\n            return \n                (from p in m_PlacementRepository.Linq orderby p.PlacementId select p)\n                .Where(p => p.Agency != agency)\n                .Where(p => p.Supervisors != null && p.Supervisors.Any(s => agencySupervisors.Contains(s.SupervisorId)));	0
2645517	2645319	Count Total Number of XmlNodes in C#	node.SelectNodes("descendant::*").Count	0
6264663	6264459	Send email asynchronously from an WCF 4 REST service	SmtpClient.SendAsync	0
1826375	1822545	How to use LINQ-to-Entity to query by contained objects	List<Location> FindLocationContainingAllItems(List<int> itemIds)\n{\n    var itemQuery = from item in ctx.Items\n                    select item;\n\n    // Workaround the Where In Clause (http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0)\n    itemQuery = itemQuery.Where(BuildContainExpression<Items, int>(i=> i.Id, itemIds));\n\n    int itemCount = itemIds.Count();\n\n    var locQuery = from loc in ctx.Locations\n                   from box in loc.Boxes\n                   where (from items in box.Items select items).Intersect(itemQuery).Count == itemCount\n                   select loc;\n\n    return locQuery.ToList();\n\n }	0
11028238	11028161	How to use Substring function in C#	string[] splitted = str.Split(',');	0
29654959	29654809	How to make constant final variables in a class like module in vb.net but in C#?	public static class Constantes\n{\n  public static readonly string var1 = "variable 1";\n  public static readonly string var2 = "variable 2";\n}	0
7822926	7822479	send xml file to handler using http-post	private string PostData(string url, byte[] postData)\n    {\n        HttpWebRequest request = null;\n        Uri uri = new Uri(url);\n        request = (HttpWebRequest)WebRequest.Create(uri);\n        request.Method = "POST";\n        request.ContentType = "application/x-www-form-urlencoded";\n        request.ContentLength = postData.Length;\n        using (Stream writeStream = request.GetRequestStream())\n        {\n            writeStream.Write(postData, 0, postData.Length);\n        }\n        string result = string.Empty;\n        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n        {\n            using (Stream responseStream = response.GetResponseStream())\n            {\n                using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))\n                {\n                    result = readStream.ReadToEnd();\n                }\n            }\n        }\n        return result;\n    }	0
11400452	11386314	transforming RPC API to Rest API	/Performance/{lineId}?maxNumberOfEntries={max}&ascending={asc}	0
4555090	4555055	LINQ Expression help with Func TEntity,TType	public IEnumerable<TEntity> Get<TEntity, TOrderBy>(Expression<Func<TEntity,TOrderBy>> orderBy)	0
6481396	6481382	How to compare two ordered lists with LINQ?	a.SequenceEqual(b);	0
31273915	31267660	How DbMigrationsConfiguration is related to a DbMigration in EF	public Configuration()\n{\n    AutomaticMigrationsEnabled = true;\n    MigrationsDirectory = @"Migrations\Context1";\n}	0
25115276	25092218	Dynamic Connection String for EF Code First	string entityConnStr = "Data Source=111.111.1.11;Initial Catalog=MyProgram;User Id=admin;Password=12345;Integrated Security=False";	0
3628930	3628908	Getting the value of string variable	string style = "ErrorLabel";\nStyle styItem = LayoutRoot.Resources[style] as Style;\nfld.Settings.CellValuePresenterStyle = styItem;	0
19185559	19185513	Server.MapPath on a remote server	System.IO.Path.Combine	0
30758353	30758210	One row of list view is updating, but duplicate row is also inserted	foreach (ListViewItem lvi in list_view_orderitems.Items)\n{\n    if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)\n    {\n        int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);\n        int AddMe = Convert.ToInt32(txt_quantity.Text);\n        UpdateQunat = UpdateQunat + AddMe;\n        lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);\n        // adding it again. This line is not needed.\n        list_view_orderitems.Items.Add(item);\n     }\n     else if (lvi.SubItems[0].Text != list_Select_Product.SelectedItems[0].Text)\n     {\n         list_view_orderitems.Items.Add(item);\n     }\n}	0
7214898	7212762	Silverlight custom EventTrigger	VisualStateManager.GoToState(this [or some other object with Highlighted state], "Highlighted", false);	0
20955680	20955547	Where to find GetMemberInfo	public static MemberInfo GetMemberInfo(this Expression expression)\n{\n    var lambda = (LambdaExpression)expression;\n\n    MemberExpression memberExpression;\n    if (lambda.Body is UnaryExpression)\n    {\n        var unaryExpression = (UnaryExpression)lambda.Body;\n        memberExpression = (MemberExpression)unaryExpression.Operand;\n    }\n    else\n        memberExpression = (MemberExpression)lambda.Body;\n\n    return memberExpression.Member;\n}	0
7232215	7232126	How do you get the end cap width or height values for line objects?	PenLineCap.Round	0
30222111	30222023	Nlog in a class library project	public class Class1\n{\n  public void SomeMethod()\n  {\n    Console.WriteLine("Greetings, some loggings is about to take place.");\n    Console.WriteLine("");\n\n    Logger logger = LogManager.GetCurrentClassLogger();\n\n    logger.Trace("Trace: The chatter of people on the street");\n    logger.Debug("Debug: Where are you going and why?");\n    logger.Info("Info: What bus station you're at.");\n    logger.Warn("Warn: You're playing on the phone and not looking up for your bus");\n    logger.Error("Error: You get on the wrong bus.");\n    logger.Fatal("Fatal: You are run over by the bus.");\n\n  /*\n   * Closing app\n   */\n   Console.WriteLine("");\n   Console.WriteLine("Done logging.");\n   Console.WriteLine("Hit any key to exit");\n   Console.ReadKey();\n  }\n}	0
31902236	31902175	Access properties of objects in an object	class MetaComposite\n{\n    public MetaAClass MetaA { get; private set; }\n    public MetaBClass MetaB { get; private set; }\n    public MetaCClass MetaC { get; private set; }\n\n    public MetaComposite()\n    {\n         MetaA = new MetaAClass();\n         MetaB = new MetaBClass();\n         MetaC = new MetaCClass();\n    }\n}\n\npublic void Main()\n{\n    var composite = new MetaComposite();\n    composite.MetaA.Field1 = 1;\n    composite.MetaB.Field2 = '2';\n    composite.MetaC.Field3 = new MetaDClass();\n}	0
7238999	7238778	How load multiple values into a multidimensional array in a single line	string[ , ] newLine = new string[src.Count, 4];\n\nfor (int i = 0; i < src.Count; i++)\n{\n    newLine[i, 0] = value1;\n    newLine[i, 1] = value2;\n    newLine[i, 2] = value3;\n    newLine[i, 3] = value4;\n\n}	0
9020312	9019652	One to one with entity framework 4.2	public partial class XpathMappingSetMap : EntityTypeConfiguration<XpathMappingSet>\n{\n    public XpathMappingSetMap()\n    {\n        ToTable("XpathMappingSets");\n\n        HasKey(m => m.XpathMappingSetId);\n\n        Property(m => m.XpathMappingSetId).HasColumnName("MappingSetId");\n    }\n}	0
1193807	1193345	Compare lists and get values with Linq	List< MyClass> listRes = new List< MyClass>();\nforeach ( MyClass item in list1)\n{\n    var exist = list2\n    .Select(x => x.MyClass)\n    .Contains(item);\n\n    if (!exist)\n    listRes.Add(item);\n    else\n    {\n    var totalFromOther = list2\n    .Where(x => x.MyClass.Id == item.Id)\n    .Sum(y => y.HourBy);\n\n    if (item.HourBy != totalFromOther)\n    {        \n    item.HourBy = item.HourBy - totalFromOther;\n    listRes.Add(item);\n    }            \n    }   \n}	0
4563883	4563377	Best practice for parsing and validating mobile number	string CleanPhone(string phone)\n{\n    Regex digitsOnly = new Regex(@"[^\d]");   \n    return digitsOnly.Replace(phone, "");\n}	0
22918612	22918284	How to avoid locking when using a static object	var processingLock = new object();\n        if (!isProcessingMotion)\n        {\n            lock (processingLock)\n            {\n                isProcessingMotion = true;\n                // Do stuff..\n\n                isProcessingMotion = false;\n            }\n        }	0
14853604	14853553	How to connect MySQL running on a web server from c#?	telnet ip 3306	0
2398471	2398418	How append data to a binary file?	private static void AppendData(string filename, int intData, string stringData, byte[] lotsOfData)\n{\n    using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None))\n    using (var bw = new BinaryWriter(fileStream))\n    {\n        bw.Write(intData);\n        bw.Write(stringData);\n        bw.Write(lotsOfData);\n    }\n}	0
12593401	12593345	how do tcp servers work if there is no multicasting?	ServerIP + ServerPort + ClientIP + ClientPort	0
28387580	28370414	Import RSA key from bouncycastle sometimes throws "Bad Data"	public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)\n{\n   RSAParameters rp = new RSAParameters();\n   rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();\n   rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();\n   rp.P = privKey.P.ToByteArrayUnsigned();\n   rp.Q = privKey.Q.ToByteArrayUnsigned();\n   rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);\n   rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);\n   rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);\n   rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);\n   return rp;\n}\n\nprivate static byte[] ConvertRSAParametersField(BigInteger n, int size)\n{\n   byte[] bs = n.ToByteArrayUnsigned();\n   if (bs.Length == size)\n      return bs;\n   if (bs.Length > size)\n      throw new ArgumentException("Specified size too small", "size");\n   byte[] padded = new byte[size];\n   Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);\n   return padded;\n}	0
11642211	11642057	Modify how datetime is presented in a datagrid?	System.Windows.Forms.DataGridViewCellStyle dgvCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();\ndgvCellStyle1.Format = "MM/dd/yyyy";\ndgvCellStyle1.NullValue = null;\nthis.dataGridView1.Columns[0].DefaultCellStyle = dgvCellStyle1;	0
10197349	10197318	LINQ: How to test if value is contained in set	var listOfConditions = new List<int>{50,60,70};\nvar tempTable = (from p in dc.Live_Diffs\n                             where listOfConditions.Contains(p.RowNum)\n                             select new CustomResult\n                             {   RowNum = p.RowNum ,\n                                 ED1 = p.ED1,\n                                 ED2 = p.ED2,\n                                 ED3 = p.ED3,\n                                 ED4 = p.ED4,\n                                 ED5 = p.ED5,\n                                 ED6 = p.ED6,\n                                 ED7 = p.ED7,\n                                 ED8 = p.ED8\n                             }).ToList();	0
27266883	27221574	Difficulty invoking WCF POST service running on localhost in a test project in same solution as service	request.ContentType = "'text/json; charset=utf-8'";	0
2285021	2266194	how do I change the way a DateTime object is displayed in a DataGridView	dataGridView1.Columns[0].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";	0
1913977	1911104	Need an approach for automatically-propagating values in/across hierarchical structures (Faction system for a game)	void propagateStanding(amount)\n{\n    // calculate relative weightings\n    totalWeighting = 0.0;\n    for (relationship in faction.relationships)\n    {\n        totalWeighting += relationship.weight;\n    }\n\n    // propagate value    \n    for (relationship in faction.relationships)\n    {\n        amountToGive = amount * relationship.weight / totalWeighting;\n        relationship.otherFaction.standing += amountToGive;\n    }\n}	0
34397999	34396852	Validate redirection implimentation	using System.Threading;\nusing System.Threading.Tasks;\n\nParallel.For(0, lst.Count, index =>\n{\n          string URL = lst[index].InnerText;\n\n          var request = (HttpWebRequest)WebRequest.Create(URL);\n          HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n          string responseURI = response.ResponseUri.ToString();\n\n});	0
13564654	13562166	How to switch desktop to metro UI by code?	private static extern int keybd_event(Byte bVk, Byte bScan, long dwFlags, long dwExtraInfo);\nprivate const byte UP = 2;\nprivate const byte CTRL = 17;\nprivate const byte ESC = 27;\n\nFinally on the event where you want to open start menu use :\n// Press Ctrl-Esc key to open Start menu\nkeybd_event(CTRL, 0, 0, 0);\nkeybd_event(ESC, 0, 0, 0);\n\n// Need to Release those two keys\nkeybd_event(CTRL, 0, UP, 0);\nkeybd_event(ESC, 0, UP, 0);	0
24329516	24329415	What is an easy way to add n number of spaces to a string?	new string(' ', N)	0
8608441	8608331	How do I find an element in a DataTemplate applied to a ContentPresenter?	Dispatcher.BeginInvoke( new Action(() =>\n{\n    // Call FindName here\n}), System.Windows.Threading.DispatcherPriority.Render );	0
7173120	7173083	How to add a value from variable to asp:ListItem in a asp:RadioButtonList	radInteresse.Items[0].Value = var1;\nradInteresse.Items[2].Value = var2;	0
401579	401561	How to open a multi-frame TIFF imageformat image in .NET 2.0?	private List<Image> GetAllPages(string file)\n{\n    List<Image> images = new List<Image>();\n    Bitmap bitmap = (Bitmap)Image.FromFile(file);\n    int count = bitmap.GetFrameCount(FrameDimension.Page);\n    for (int idx = 0; idx < count; idx++)\n    {\n        // save each frame to a bytestream\n        bitmap.SelectActiveFrame(FrameDimension.Page, idx);\n        MemoryStream byteStream = new MemoryStream();\n        bitmap.Save(byteStream, ImageFormat.Tiff);\n\n        // and then create a new Image from it\n        images.Add(Image.FromStream(byteStream));\n    }\n    return images;\n}	0
33681592	33681446	dt.Rows.Count How to search from the textbox and show in the gridview	dt.Clear();\nda.Fill(dt);\ngvSubDetails.DataSource = dt;\ngvSubDetails.DataBind();\n\nif (gvSubDetails.RowCount > 0)  //Gridview uses RowCount, not Rows.Count\n{\n    //ToDo...\n}	0
1422727	1422701	How to P/Invoke when pointers are involved	[DllImport("USB4.dll")]\npublic static extern int USB4_Initialize(ref short deviceCount);\n\n[DllImport("USB4.dll")]\npublic static extern int USB4_GetCount(short deviceNumber, short encoder, ref uint32 value)	0
31266245	31266200	Split a string by semicolons on new line in c#	String.Join(Environment.NewLine, text.Split(';'));	0
18210755	18210005	Using ProgressBar in WPF, Simple Application	FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment     Sample Layout Proposed - Sample Data.xlsx");\n\nConsoleApplication2.Program.ExcelData data =  ConsoleApplication2.Program.GetExcelData(existingFile);	0
28740085	28740009	C# replace strings in array with LINQ	var yourArray = new string[10];\nvar yourResult = yourArray.Take(9).Select(s => s.Split(',')[0]).ToArray();	0
4145951	4145917	Cannot access the CSS class for a link button from Code behind	LinkButton lb = new LinkButtton();\nlb.cssclass="linkclass";\nlb.text = "foo";\npanel1.Controls.Add(lb);	0
1574184	1574019	How to determine Windows.Diagnostics.Process from ServiceController	using System;\nusing System.Diagnostics;\nusing System.ServiceProcess;\nusing System.Management;\nclass Program\n{\n    static void Main(string[] args)\n    {\n        foreach (ServiceController scTemp in ServiceController.GetServices())\n        {\n            if (scTemp.Status == ServiceControllerStatus.Stopped)\n                continue;    // stopped, so no process ID!\n\n            ManagementObject service = new ManagementObject(@"Win32_service.Name='" + scTemp.ServiceName + "'");\n            object o = service.GetPropertyValue("ProcessId");\n            int processId = (int) ((UInt32) o);\n            Process process = Process.GetProcessById(processId);\n            Console.WriteLine("Service: {0}, Process ID: {1}", scTemp.ServiceName, processId);\n        }\n    }\n}	0
77233	76993	How to double buffer .NET controls on a form?	public static void SetDoubleBuffered(System.Windows.Forms.Control c)\n{\n   //Taxes: Remote Desktop Connection and painting\n   //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n   if (System.Windows.Forms.SystemInformation.TerminalServerSession)\n      return;\n\n   System.Reflection.PropertyInfo aProp = \n         typeof(System.Windows.Forms.Control).GetProperty(\n               "DoubleBuffered", \n               System.Reflection.BindingFlags.NonPublic | \n               System.Reflection.BindingFlags.Instance);\n\n   aProp.SetValue(c, true, null); \n}	0
13970095	13953301	Entity framework with Include method	List<Warehouse> lstObjWarehouse = db.Warehouses.Include("WarehouselnkedEcorder")\n.Where(o => o.invoicePath == "SomeCondition" \n&& o.Deleted == false \n&& o.WarehouselnkedEcorders.Any(p => p.id == o.id \n&& p.Deleted == false)).ToList();	0
10365185	10364606	how to create google contact?	newEntry.IMs.Add(new IMAddress()\n{\n  Address = "email@dot.com",  // untested\n  Primary = true,\n  Rel = ContactsRelationships.IsHome,\n  Protocol = ContactsProtocols.IsGoogleTalk,\n});	0
3026608	3026571	Counting words in a collection using LINQ	var res = from word in col.Cast<string>()\n          group word by word into g\n          select new { Word = g.Key, Count = g.Count() };	0
22725409	22725347	C# - Passing variable type to recursive factory as generic	public static T SpawnObject<T>()\n{\n    return (T)SpawnObject(typeof(T));\n}\n\nprivate static object SpawnObject(Type objType)\n{\n    var parameters = objType.GetConstructors().Single().GetParameters();\n    List<object> paramObjects;\n\n    if (!parameters.Any()) return Activator.CreateInstance(objType);\n\n    paramObjects = new List<object>();\n    foreach (var item in parameters)\n    {\n        //var arg = Activator.CreateInstance(item.ParameterType);\n        var paramType = item.ParameterType;\n        var arg = SpawnObject(paramType);\n        paramObjects.Add(arg);\n    }\n\n    return Activator.CreateInstance(objType, paramObjects.ToArray());\n}	0
12782075	12781809	How to delete selected node from XML in C#?	private void btnDelete_Click(object sender, EventArgs e)\n{\n    var xDoc = XDocument.Load(strFilename);\n\n    foreach (var elem in xDoc.Document.Descendants("product"))\n    {\n        foreach (var attr in elem.Attributes("name"))\n        {\n            if (attr.Value.Equals("Tide"))\n                elem.RemoveAll();\n        }\n    }\n\n    xDoc.Save(destinationFilename);\n    MessageBox.Show("Deleted Successfully");\n}	0
11433544	11433480	Parsing a complicated string as DateTime	string s = "11:50:46 AM on Wednesday, October 19, 2011";\n        DateTime dateTime = DateTime.ParseExact(s, \n            "hh:mm:ss tt on dddd, MMMM dd, yyyy", CultureInfo.InvariantCulture);	0
14826220	14825999	how to insert data from textboxes to datagridview in C#	private void btnAdd_Click(object sender, EventArgs e)\n    {\n        string firstColum = txtUomtyp.Text;\n        string secondColum = txtUomDesc.Text;\n        string[] row = { firstColum, secondColum };\n        dgvUom.Rows.Add(row);\n    }	0
22995210	22994484	How to load a dll with its dependencies with LoadLibrary or any other method	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]\n        private delegate void ingammaextern_(StringBuilder resulfilesparam);\n\n\n\n{\n   var dllName = "SubsCalculator1.dll";\n\n            var interopPath = CreateDllFromResource(dllName);\n            var d1 = CreateDllFromResource("libgcc_s_dw2-1.dll");\n            var d2 = CreateDllFromResource("libgfortran-3.dll");\n            var d3 = CreateDllFromResource("libquadmath-0.dll");\n\n            string folderPath ="C:\folder\\n            SetDllDirectory(folderPath);\n\n            pDll = NativeMethods.LoadLibrary(interopPath);\n}	0
2118732	2118055	How to force overriding a method in a descendant, without having an abstract base class?	override void M() { base.M(); }	0
9092108	9092062	how to get the asp.net drop down list items in javascript	var ddl= document.getElementById("<%=ddl.ClientID%>");\nvar Text = ddl.options[ddl.selectedIndex].text; \nvar Value = ddl.options[ddl.selectedIndex].value;	0
8604093	8603596	How can i define a 8 bit grayscale image directly ?	Private Function GetGrayScalePalette() As ColorPalette  \n    Dim bmp As Bitmap = New Bitmap(1, 1, Imaging.PixelFormat.Format8bppIndexed)  \n\n    Dim monoPalette As ColorPalette = bmp.Palette  \n\n    Dim entries() As Color = monoPalette.Entries  \n\n    Dim i As Integer \n    For i = 0 To 256 - 1 Step i + 1  \n        entries(i) = Color.FromArgb(i, i, i)  \n    Next \n\n    Return monoPalette  \nEnd Function	0
10641714	10641528	How to make handler request that gets back json	IList<MyClass> myClassList = null;\nvar request = WebRequest.Create(url);\nrequest.ContentType = "application/json; charset=utf-8";\n\nstring json;\nusing (var response = request.GetResponse())\n{\n    using (var sr = new StreamReader(response.GetResponseStream()))\n    {\n        json = sr.ReadToEnd();\n        var javaScriptSerializer = new JavaScriptSerializer();\n        myClassList = javaScriptSerializer.Deserialize<List<MyClass>>(json);\n    }\n}	0
26481454	26480975	WPF binding Listbox SelectedItem in ViewModel	message = selectedItem.Content.ToString();	0
2269671	2269625	Using assembly attributes in F#	open System\nopen IronPython.Runtime\n\ntype MyModule = \n    static member hello_world() =\n        Console.WriteLine("hello world")\n\nmodule DummyModuleOnWhichToAttachAssemblyAttribute =\n    [<assembly: PythonModule("my_module", typeof<MyModule>)>] \n    do ()	0
27161322	27161236	Adding items from list to listbox control	for each (string s in urls) {lstUrls.Items.Add(s);}	0
494852	494820	How bad is this pattern?	var asyncResult = request.BeginGetResponse(...\n  asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10))	0
31720973	31697194	How to generate AES/CBC/PKCS5Padding encrypted cipher in angularJs	function hash (){\n       return CryptoJS.SHA256(password);\n    }\n    var cipher = (function(plaintext, password) {\n                        passwordHash = hash(password);\n                        var iv = CryptoJS.enc.Hex.parse('0000000000000000');\n                        var cipher = CryptoJS.AES.encrypt(plaintext, passwordHash, {\n                            iv: iv,\n                            mode: CryptoJS.mode.CBC,\n                            keySize: 256 / 32,\n                            padding: CryptoJS.pad.Pkcs7\n                        });\n                        return cipher;\n    })(plaintext, password);\n\n   cipherBase64 =  cipher.ciphertext.toString().hex2a().base64Encode();	0
18258515	18258333	Using DataGrid ItemDataBound Event to Check Value	e.Item.Cells[index].Text;	0
12741768	12741476	Need to send mail to Extrnal mail ids without having the Internal mail id	private class senderInformation{\n\n private string lastname;\n private string firstname;\n private string email;\n\n}\n\nsenderInformation person = new senderInformation();\n\nperson.lastname = "Smith";\nperson.firstname = "John";\nperson.email= "john@gmail.com";\n\nmail.From = new MailAddress(person.email.toString());	0
34014334	34013957	unable to show a record on fiddler	myConnection.ConnectionString = @"Data Source=PALLAVI-PC\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework";	0
27304192	27303961	Register a default named registration	container.RegisterType<IInterface>( new InjectionFactory(\n   c => c.Resolve<IInterface>( "Named Second" ) ) );	0
199976	199961	Getting full path for Windows Service	System.Reflection.Assembly.GetEntryAssembly().Location	0
17349229	17349179	How can I remove numbers/digits from strings in a List<string>?	_words = _words.Where(w => w.Any(c => !Char.IsDigit(c))).ToList();	0
28887928	28887875	Can a subclass override a method and have different parameters?	public class Parent\n{        \n    public virtual string HelloWorld()\n    {\n        return "Hello world";\n    }\n\n    public string GoodbyeWorld()\n    {\n        return "Goodbye world";\n    }\n}\n\npublic class Child : Parent\n{\n     // override: exact same signature, parent method must be virtual\n    public override string HelloWorld()\n    {\n        return "Hello World from Child";\n    }\n\n     // overload: same name, different order of parameter types\n    public string GoodbyeWorld(string name)\n    {\n        return GoodbyeWorld() + " from " + name;\n    }\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var parent = new Parent();\n        var child = new Child();\n        Console.WriteLine(parent.HelloWorld());\n        Console.WriteLine(child.HelloWorld());\n        Console.WriteLine(child.GoodbyeWorld());\n        Console.WriteLine(child.GoodbyeWorld("Shaun"));\n    }\n}	0
17814399	17814221	Rich Text to Plain Text via C#?	//rtfText is rich text\n//rtBox is rich text box\nrtBox.Rtf = rtfText;\n//get simple text here.\nstring plainText = rtBox.Text;	0
3892129	3891719	MessageBox with exception details immediately disappears if use splash screen in WPF 4.0	public static void Main()\n{\n    SplashScreen splashScreen = new SplashScreen("whatever.jpg");\n    splashScreen.Show(true);\n    string errorMessage;\n    bool dataLoaded = LoadDataFromDatabase(out errorMessage);\n    WpfApplication1.App app = new WpfApplication1.App();\n    Window windowToRun = dataLoaded ? (Window)new MainWindow() : (Window)new ErrorWindow { ErrorMessage = errorMessage };\n    app.Run(windowToRun);\n}	0
17178642	17178542	Deserializing SFDC REST services JSON resopnse	public class ResponseDataList \n{\n    public List<ResponseData> responseDataList { get; set; }\n}	0
12575533	12575429	How to generate shadow under words on an image	public static System.Drawing.Image GenerateGiftCard(String text, Font font, Color    textColor, Color shadowColor, SizeF shadowOffset)\n{\n    System.Drawing.Image img = Bitmap.FromFile(@"G:\xxxx\images\gift-card.jpg");\n    Graphics drawing = Graphics.FromImage(img);\n\n    //measure the string to see how big the image needs to be\n    SizeF textSize = drawing.MeasureString(text, font);\n\n    //create a brush for the text\n    Brush shadowBrush = new SolidBrush(shadowColor); // <-- Here\n    Brush textBrush = new SolidBrush(textColor);\n\n    float x, y;\n\n    x = img.Width / 2 - textSize.Width / 2;\n    y = img.Height / 2 - textSize.Height / 2;\n\n    drawing.DrawString(text, font, shadowBrush, x + shadowOffset.Width, y + shadowOffset.Height); // <-- Here\n    drawing.DrawString(text, font, textBrush, x, y);\n\n    drawing.Save();\n\n    textBrush.Dispose();\n    drawing.Dispose();\n\n    return img;\n}	0
24655333	24653162	parse string from soap and fetch data, c#	XNamespace a = "namespace_a";\nXDocument doc = XDocument.Parse("your xml string here");\nvar header = (string)doc.Root.Descendants(a + "ArticleHeader").FirstOrDefault();\nvar content = (string)doc.Root.Descendants(a + "Content").FirstOrDefault();	0
1770683	1764970	Find index of a value in an array	int keyIndex = Array.FindIndex(words, w => w.IsKey);	0
21148959	21148381	How to create columns with the names from a sqlite table in a dataGridView	m seeing no diference so I	0
14396437	14396377	How to refactor the following code without killing OOPS in C#	public interface IUnified\n{\n    void M1();\n    void M2();\n}\n\npublic class UnifiedAdapter : IUnified\n{\n    private Action m1;\n    private Action m2;\n\n    public UnifiedAdapter(A a)\n    {\n        m1 = () => a.M1();\n        m2 = () => a.M2();\n    }\n\n    public UnifiedAdapter(B b)\n    {\n        m1 = () => b.M1();\n        m2 = () => b.M2();\n    }\n\n    public UnifiedAdapter(C c)\n    {\n        m1 = () => c.M1();\n        m2 = () => c.M2();\n    }\n\n    public M1()\n    {\n        m1();\n    }\n\n    public M2()\n    {\n        m2();\n    }\n}	0
29285852	29269268	How to get all attributes and attributes data of a method using reflection in C#	// method is the MethodInfo reference\n// member is CodeMemberMethod (CodeDom) used to generate the output method; \nforeach (CustomAttributeData attributeData in method.GetCustomAttributesData())\n{\n    var arguments = new List<CodeAttributeArgument>();\n    foreach (var argument in attributeData.ConstructorArguments)\n    {\n        arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));\n    }\n\n    if (attributeData.NamedArguments != null)\n        foreach (var argument in attributeData.NamedArguments)\n        {\n            arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));\n        }\n\n    member.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(attributeData.AttributeType), arguments.ToArray()));\n}	0
10955528	10955451	C# Generic factory return without generic argument	public IManageableEntryDao<T> CreateDao<T>() where T : IManageableEntry\n{\n        Type manageableEntryType = typeof(T);\n\n        // You'll need to modify daoTypes to be a HashSet<Type> (or List<Type>) of allowable types, or something similar, instead of using a dictionary lookup\n        if (daoTypes.Contains(manageableEntryType) {\n            object dao = Activator.CreateInstance(type);                    \n            return dao as IManageableEntryDao<T>;\n        }\n        throw new NotImplementedException("Failed to find DAO for type: " + manageableEntryType);\n    }	0
30220722	30220604	Get the Last day of month in a string	DateTime d = Convert.ToDateTime("2/4/15");\n\nDateTime lastDayOfSameMonth = (new DateTime(d.Year, d.Month, 1)).AddMonths(1).AddDays(-1);	0
26916620	26916531	Verify HTML links in a large directory structure on my local harddrive	System.IO.File.Exists	0
1764978	1764792	Updating Linq to XML element values concatenation issues	var query =  doc.Descendants()\n                .Element("SMTPHost")\n                .DescendantNodes()\n                .OfType<XText>();\n\nforeach (XText textNode in query)\n{\n    textNode.Value = textNode.Value.Replace("mail.mycompany.com", \n                                            "devmail.mycompany.com");\n}	0
20174810	20174760	How to make - if no result, result = 0 C#	if (textBox2.Text == "" && textBox3.Text == "")\n {\n     textBox2.Text = "0";\n     textBox3.Text = "0";\n }	0
26928739	26928618	At runtime, how does a C# delegate access scope in which it is defined?	public MainWindow()\n{\n    CunningCapture capture = new CunningCapture { @this = this };\n    capture.myStoryboard = new Storyboard();\n    ...\n\n    _button.Click += capture.Method;\n    ...\n}\n\nprivate class CunningCapture\n{\n    public Storyboard myStoryboard;\n    public MainWindow @this;\n\n    public void Method()\n    {\n        myStoryboard.Begin(@this._control);\n    }\n}	0
1348090	1348080	Convert a positive number to negative in C#	myInt = myInt * -1	0
24775368	24773266	Return XML content on WebAPI OWIN for Twilio	[HttpGet]\n[Route("menu")]\npublic HttpResponeMessage Menu(string from, string to, string callSid) \n{\n     var response = new TwilioResponse();\n     response.Say("Hello World");\n\n    return new HttpResponseMessage()\n    {\n        Content = new StringContent(\n            response.ToString(), \n            Encoding.UTF8, \n            "text/xml"\n        )\n    };\n}	0
20219300	19899375	How to upload and fetch microsoft access database from server folder in asp.net	string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBpath + "";	0
20276014	20275986	Programatically adding rows in table using loop but just last record gets display	TableRow tr1 = new TableRow();\n    TableCell tc1 = new TableCell();\n    TableCell tc2 = new TableCell();\n    TableCell tc3 = new TableCell();	0
10361883	10361868	How to check for null in nested references	Color color = someOrder?.Customer?.LastOrder?.Product?.Color;	0
23545146	23544322	Holding IO Port open	public void OpenPort()\n{\n     this.sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);\n     this.sp.Open();\n}\n\npublic void ClosePort()\n{\n     this.sp.Close();\n     this.sp.DataReceived -= new SerialDataReceivedEventHandler(sp_DataReceived);\n}	0
11043661	5102982	WinForms equivalent of WPF's IsHitTestVisible	public class HTTransparentLabel : Label\n{\n    private const int WM_NCHITTEST = 0x84; \n    private const int HTTRANSPARENT = -1; \n\n    protected override void WndProc(ref Message message) \n    { \n        if ( message.Msg == (int)WM_NCHITTEST ) \n            message.Result = (IntPtr)HTTRANSPARENT; \n        else \n            base.WndProc( ref message ); \n    }\n}	0
26040785	26038698	C# WCF communication with client certificate	var certificate = new X509Certificate2(rawBytes, password, X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);	0
7528703	7528455	How to get the X509Certificate from a client request	if (OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets == null)\n    throw new SecurityException ("No claimset service configured wrong");\n\nif (OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets.Count <= 0)\n    throw new SecurityException ("No claimset service configured wrong");\n\n\nvar cert = ((X509CertificateClaimSet) OperationContext.Current.ServiceSecurityContext.\n            AuthorizationContext.ClaimSets[0]).X509Certificate;\n\n//this contains the thumbprint\ncert.Thumbprint	0
26322662	26322541	How to change Unix Line feed to Windows Line Feed with C#	string[] filePaths = Directory.GetFiles(@"c:\textfiles\", "*.txt");\n\nforeach (string file in filePaths)\n{\n    string[] lines = File.ReadAllLines(file);\n        List<string> list_of_string = new List<string>();\n    foreach (string line in lines)\n    {\n        list_of_string.Add( line.Replace("\n", "\r\n"));\n    }\n    File.WriteAllLines(file, list_of_string);\n}	0
13389976	13389889	How can i import System.Windows in C#	System.Windows	0
2913035	2913016	How to access Perfmon info?	System.Diagnostics.PerformanceCounter	0
30207690	30163847	How to remove default mapping of index without deleting its data of elasticsearch	IIndicesOperationResponse result = null;\n                    if (!objElasticClient.IndexExists(elastic_indexname).Exists)\n                    {\n                        result = objElasticClient.CreateIndex(elastic_indexname, c => c.AddMapping<dynamic>(m => m.Type("_default_").DynamicTemplates(t => t\n                                                    .Add(f => f.Name("string_fields").Match("*").MatchMappingType("string").Mapping(ma => ma\n                                                        .String(s => s.Index(FieldIndexOption.NotAnalyzed)))))));\n            }	0
10921071	10920926	calculate email hash for email using sha256	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Security.Cryptography;\n\nnamespace TestSHAHash\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string email = "Someone@Example.org";\n            string clientId = "0000000603DB0F";\n\n            string toHash = (email.Trim() + clientId.Trim()).ToLowerInvariant();\n            byte[] data = Encoding.UTF8.GetBytes(toHash);\n            byte[] result;\n            SHA256 shaM = new SHA256Managed();\n            result = shaM.ComputeHash(data);\n            string lowerHexaDecimal = BitConverter.ToString(result).Replace("-","").ToLowerInvariant();\n            Console.WriteLine(lowerHexaDecimal);\n            Console.ReadLine();\n        }\n    }\n}	0
4246005	4245773	c# need to raise event when in scope of LOCK	public XDocument FetchDocument(FUnc<XDocument, bool> cacheNewDocument) {\n    var xdoc;        \n    lock(_lockobject) {\n        // in case prev.thread has done upload will currth read waiting\n        xdoc = Cache[_Key1];\n\n        if (xdoc == null) {\n           xdoc = .... Code to grab from file and add to catch - works great.....\n\n           if (cacheNewDocument(xdoc)){\n               Cache.Add(_Key1, xdoc)\n           }\n           else{\n               return xdoc;\n           }\n        }\n    }\n\n    return xdoc;\n}	0
23331485	23331426	How to use Global Variables in C#	private const string KEY_Book_CategoryName = "Book_CategoryName";\npublic String Book_CategoryName\n{\n    get\n    {\n        return ViewState[KEY_Book_CategoryName] as string;\n    }\n    set\n    {\n        ViewState[KEY_Book_CategoryName] = value;\n    }\n}	0
5353769	5353655	Get rid Of Many Events and Properties in user control windows appilication	[Browsable(false)]\n    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public override Color BackColor\n    {\n        get \n        {\n            //implementattion\n        }\n        set \n        {\n            //implementation\n        }\n    }	0
8364300	8364134	Preventing a TreeView from changing SelectedNode until a ListView getting populated	private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)\n    {\n        if (_loading)\n            e.Cancel = true; \n    }\n\n    bool _loading = false; \n    void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n    {\n        _loading = true;\n        // ListView populating\n        _loading = false; \n    }	0
24084729	24083969	How to use NetTcpBinding in code?	PortSharingEnabled = true	0
16928199	16928063	Replace one Xml tag value with another tag value in C#	XDocument doc = XDocument.Load(Path);\ndoc.Element("MyXmlType")\n   .Element("MyXmlElement12")\n   .Value += DateTime.Now.ToString();\ndoc.Save(Path);	0
27999756	27962459	Unauthorized to list Google spreadsheets with scoped OAuth token	SpreadsheetsService service = new SpreadsheetsService("Ribbon");\nGOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "Ribbon", googleAuth);\nservice.RequestFactory = requestFactory;	0
11206040	10992715	asp.net sql query'ed text rendered with wrong charset	NLS_LANG = German.Germany.Charset.	0
24044483	24044400	Sort dictionary by value - descending THEN alphabetical C#	var items = from pair in Dict \n            orderby pair.Value descending, \n                    pair.Key \n            select pair;	0
13545288	13545263	Serializing a Dictionary<> object with DataContractJsonSerializer	var parameters = new\n{\n    username = "mike",\n    password = "secret",\n    persist = false\n}	0
1105416	1105411	How to update a specific element from List<T> element collections?	// Updates a property or member of the item\nmyList[2].myProperty = something;\n\n// Replaces the item in the list\nmyList[2] = someNewItem;	0
3967334	2915084	WPF custom control problem	public static readonly DependencyProperty EMListProperty =\n   DependencyProperty.Register(\n   "EMList",\n   typeof(ElementCollection),\n   typeof(ListWrapper),\n   new FrameworkPropertyMetadata(new ElementCollection())\n );\n\npublic ElementCollection EMList\n{\n    get { return (ElementCollection)GetValue(EMListProperty); }\n    set { SetValue(EMListProperty, value); }\n}	0
17541300	17525264	adding number of days in calendar extender	protected void Calendar1_ontextchanged(object sender, EventArgs e)\n{\n\n    string numberofdays=   Convert.ToDateTime(this.TextBox1.Text).DayOfWeek.ToString("d");\n    DateTime select = Convert.ToDateTime(TextBox1.Text);\n    lblStartOfWeek.Text = select.AddDays(-Convert.ToInt32(numberofdays)).ToString("dd MMMM yyyy");\n    lblEndOfWeek.Text = select.AddDays(6-Convert.ToInt32(numberofdays)).ToString("dd MMMM yyyy");\n\n\n}	0
13229529	12930908	Detect WIFI connection in Windows Store App	switch (internetConnectionProfile.NetworkAdapter.IanaInterfaceType)\n                {\n                    case 71:\n                        networkStatus = InternetAccess.WLAN;\n                        break;\n\n ect....	0
11800026	1834983	Dynamic Pages From a Database in C#	Type page_type = BuildManager.GetCompiledType ("~/page.aspx");\nPage page = (Page) Activator.CreateInstance (page_type);\npage.ProcessRequest (Context);	0
6745197	6745081	c# winForms how to filter combobox	comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\ncomboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;	0
10331051	6760232	(don't ?) use JavaScriptSerializer to convert xml file (of unknown schema) to json in c#	string xml = @"<?xml version=""1.0"" standalone=""no""?>\n<root>\n  <person id=""1"">\n  <name>Alan</name>\n  <url>http://www.google.com</url>\n  </person>\n  <person id=""2"">\n  <name>Louis</name>\n  <url>http://www.yahoo.com</url>\n  </person>\n</root>";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nstring jsonText = JsonConvert.SerializeXmlNode(doc);\n//{\n//  "?xml": {\n//    "@version": "1.0",\n//    "@standalone": "no"\n//  },\n//  "root": {\n//    "person": [\n//      {\n//        "@id": "1",\n//        "name": "Alan",\n//        "url": "http://www.google.com"\n//      },\n//      {\n//        "@id": "2",\n//        "name": "Louis",\n//        "url": "http://www.yahoo.com"\n//      }\n//    ]\n//  }\n//}	0
1912315	1912192	how to load usercontrols from the assembly using the filename?	LoadControl(filename)	0
18074257	17973652	XamDataGrid - SelectedItems empty on click on editable cell	private void XamDataGrid_EditModeStarting_1(object sender, EditModeStartingEventArgs e)\n    {\n        e.Cell.IsSelected = true;\n    }	0
13559019	13558809	How are users supposed to persist settings in a Windows Phone 8 app?	public static void Session_PersistSession(string ticket)\n{\n   if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionTicket"))\n   {\n      IsolatedStorageSettings.ApplicationSettings["SessionTicket"] = ticket;\n   }\n   else\n   {\n      IsolatedStorageSettings.ApplicationSettings.Add("SessionTicket", ticket);\n   }\n\n   IsolatedStorageSettings.ApplicationSettings.Save();\n}\n\npublic static string Session_LoadSession()\n{\n   string ticket;\n   if (IsolatedStorageSettings.ApplicationSettings.TryGetValue<String>("SessionTicket", out ticket))\n   {\n      return ticket;\n   }\n\n   return null;\n}	0
7327089	7326747	get folder path to the program in winform	Path.GetDirectoryName(Application.ExecutablePath).Replace(@"bin\debug\", string.Empty);	0
7232801	7232721	Use LINQ-to-SQL to return an object that has child objects filtered	var query = (from mg in db.MembershipGroups\n            join m in db.Members.Where(mem => mem.Status == "Active")\n            on mg.ID equals m.MembershipGroups into members\n            select new\n            {\n               MembershipGroup = mg,\n               Members = members\n            }).AsEnumerable()\n              .Select(m => new MembershipGroup  \n                           {\n                             ID = m.MembershipGroup.ID,\n                             Title = m.MembershipGroup.Title,\n                             Members = m.Members \n                           });	0
4089618	4089582	Modelling Parent-Child Relationships with Classes	// actually write it using properties, information hiding etc instead...\npublic class Document {\n    public ICollection<Link> Links;\n}\n\npublic class Link {\n    public ICollection<Document> Documents;\n\n    // this can be on Document as well, depending on what semantics you want...\n    public void Add(Document d) {\n        Documents.Add(d);\n        d.Links.Add(this);\n}	0
3518464	3518375	grouping strings by substring in mysql/python or mysql/.net	>>> from nltk.corpus import stopwords\n>>> stopwords.words('english')\n['a', "a's", 'able', 'about', 'above', 'according', 'accordingly', 'across',\n'actually', 'after', 'afterwards', 'again', 'against', "ain't", 'all', 'allow',\n'allows', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always',\n ...]	0
2872481	2872463	How to iterate through Playlist using foreachLoop?	foreach (PlaylistItem p in playList.Items)\n{ \n  //Code Goes here\n}	0
25002199	24792481	Recursively get all possible permutations from an array	static char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};\n    static bool continuar = true;\n\n    private static void Start(int maxLength)\n    {\n        for (int i = 0; i <= maxLength; i++)\n            Permutations(i, 0, "");\n    }\n\n    private static void Permutations(int keyLength, int position, string baseString)\n    {\n        bool print = true;\n        if (continuar)\n        {\n            for (int i = 0; i < numbers .Length; i++)\n            {\n                string temp = baseString + numbers [i];\n                if (position <= keyLength - 1)\n                {\n                    Permutations(keyLength, position + 1, temp);\n                    print = false;\n                }\n                if (continuar && print)\n                    Console.WriteLine(temp);\n            }\n        }\n    }	0
10488286	10488166	Computed column on a MVC3 razor Webgrid	class MyRecord\n{\n  public DateTime StartDate {get;set;}\n  public int EndOffsetSeconds {get;set;}\n\n  public DateTime CalculatedEndTime\n  {\n    get\n    {\n      return StartDate + TimeSpan.FromSeconds( EndOffsetSeconds );\n    }\n  }\n}	0
23287230	23272872	AutoMapper doesn't map source to a destination	Mapper.CreateMap<User, User>();	0
6869389	6865536	Nullable Parameter used in Lambda Query is being ignored	var cards = new List<Card>();\nvar query = db.Cards.Where(x => x.State_ID == State_ID &&\n                                x.Deleted != 1 &&\n                                x.Archive != 1);\n\nif (Sprint_ID.HasValue) \n    query = query.Where(x => x.Sprint_ID == Sprint_ID);\nelse\n    query = query.Where(x => x.Sprint_ID == null);\n\ncards = query.ToList();	0
19147343	19146958	load image file with fileUpload to server and try to read it	string relPath = String.Format("~/images/{0}", filename);\nstring filePath = Server.MapPath(relPath);\nFileUpload1.SaveAs(filePath);\nListBox1.Items.Add(filename);\nImage1.ImageUrl = relPath;	0
31408904	31232992	Rectangles don't collide correctly	Colliding = false;\nfor (int x = 0; x < Tilemap.MAP_WIDTH; x++)\n{\n    for (int y = 0; y < Tilemap.MAP_HEIGHT; y++)\n    {\n        if (tm.tile[x, y].bounds.Intersects(playerBounds) && tm.tile[x, y].getSolid())\n        {\n            Colliding = true;\n            break;                    \n        }\n    }\n    if(Colliding)\n        break;\n}	0
10596239	10596022	Appropriate data structure for searching in strings (.net)	var myDictionary = new Dictionary<string, ObjectType>();\nwhile(string line = reader.ReadLine())\n{\n    // Parse the possible key out of the line\n    if (myDictionary.ContainsKey(keyFromLine) doSomething(line, myDictionary[keyFromLine]);\n}\n\nvoid doSomething(string line, ObjectType instance)\n{\n  // Unwrap the line and store appropriate values\n}	0
6711688	6709463	Fuzzy Search on a Concatenated Full Name using NHibernate	Session.CreateCriteria<Customer>()\n    .Add(Restrictions.Like(\n    Projections.SqlFunction("concat",\n                            NHibernateUtil.String,\n                            Projections.Property("FirstName"),\n                            Projections.Constant(" "),\n                            Projections.Property("LastName")),\n    "Bob Whiley",\n    MatchMode.Anywhere))	0
2716096	2715710	Creating a custom format string in a dataGridView	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {\n        if (e.ColumnIndex == 0 && e.Value != null) {\n            long value = 0;\n            if (long.TryParse(e.Value.ToString(), out value)) {\n                e.Value = "0x" + value.ToString("X");\n                e.FormattingApplied = true;\n            }\n        }\n    }	0
5343134	5342930	Xml Serialization Sequence Issue	[XmlElement(Order = 1)]\npublic string Prop1{get;set;}\n\n[XmlElement(Order = 2)]\npublic string Prop1{get;set;}	0
25218898	25218665	using Lambda expression for implementing a query in many-to-many relation tables	var context = DataContextFactory.GetDataContext();\n\nvar articles = (from tag in context.Tags\n                join ta in context.ArticleTags on tag.Id equals ta.TagId\n                join article in context.Articles on ta.ArticleId equals article.Id\n                where tag.Title == tagTitle\n                   && tag.IsActive == isActiveTag\n                select article).ToList();	0
11373895	11373749	counting total objects in JSON Response	var input = "[{Name: 'Hello'}, {Name: 'Hi'}]";\ndynamic response = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<dynamic>(input);\nResponse.Write(response.Length);	0
22407627	22407465	List of Generics T using Interface	public class Value<T>: IValue {\n  // Better to name these fields as "min, max, ave" or "m_Min, m_Max, m_Ave"\n  T Min;\n  T Max;\n  T Avg;\n\n  // Do not forget about "set" accessors\n  object IValue.Avg {\n    get { return Avg; }\n    set { Avg = (T) value; }\n  }\n\n  object IValue.Min {\n    get { return Min; }\n    set { Min = (T) value; }\n  }\n\n  object IValue.Max {\n    get { return Max; }\n    set { Max = (T) value; }\n  }\n\n  public Value(T min, T max, T avg) {\n    Min = min;\n    Max = max;\n    Avg = avg;\n  }\n}\n\n...\n\n// "Value<ulong> myValue" instead of "Value myValue "\nValue<ulong> myValue = new Value<ulong>(x, y, z);\nList<IValue> myList = new List<IValue>();\nmyList.Add(myValue);	0
9556314	9508018	How to extract font size of content 	...\nMyRTB.SelectionChanged += OnSelectionChanged;\n...\n\n\nvoid OnSelectionChanged()\n{\n var fontSize = MyRTB.Selection.GetPropertyValue(TextElement.FontSizeProperty);\n if (fontSize == DependencyProperty.UnsetValue)\n {\n  // Selection has text with different font sizes.\n }\n else {\n  // (double)fontSize is the current font size. Update Cmb_Font.. \n }\n}	0
9619452	9619010	Remove data from DGV and XML fileusing checkboxes	private void RemoveButton_Click_1(object sender, EventArgs e) // removes checked tasks.\n{\n    List<int> rowsToRemove = new List<int>();\n    int i = 0;\n\n    for (i = 0; i <= TaskTable.Rows.Count - 1; i++)\n    {\n\n        if (TaskTable.Rows[i].Cells[0].Value != null)\n        {\n\n            if ((bool)TaskTable.Rows[i].Cells[0].Value == true)\n            {\n                rowsToRemove.Add(i);\n            }\n        }\n    }\n\n    if (MessageBox.Show("Are you sure you want to remove the selected tasks?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // confirmation\n    {\n        // delete rows in reverse order of row index so row indexes are preserved\n        foreach (int rowIndex in rowsToRemove.OrderByDescending(x=>x))\n        {\n            TaskTable.Rows.RemoveAt(rowIndex); \n        }\n\n\n    }\n\n    TaskDataSet.WriteXml(fileURL);\n    TaskDataSet.AcceptChanges(); // re writes xml file and removes deleted tasks.\n}	0
20568245	20568184	Passing variable from one button click to another	xmlData myXML = new xmlData();\n\npublic struct xmlData\n{\n     public string xmlAttribute;   \n}\n\nprivate void Show_btn_Click(object sender, EventArgs e)\n{\n            //do something.....\n       myXML.xmlAttributes = "blah"\n}\n\nprivate void Submit_btn_Click(object sender, EventArgs e)\n{\n //I want to call myXML.xmlAttributes retrieving the stored value from Show_btn_Click\n}	0
19724673	19689008	Get the datasource of current tab in an advanced banded gridview	GridView gv = sender as GridView;\nAdvBandedGridView abgv = (AdvBandedGridView)(gv.GetDetailView(e.RowHandle,RelationIndex));	0
24034663	24034413	How to know using deserialized object if any particular node in xml exists	var disableOthers = parameter.Parameter.Component.Attributes.DisableOthers;\nif (disableOther ! = null && disableOthers.Any()) \n{\n    CallToAnyFunctionToDoSomeThing();\n}	0
6130630	6129531	Windows Phone 7's ListPicker control isn't opening up the full selection window	ItemCountThreshold="0"	0
509697	505617	Flags with web services	[Serializable,Flags]\npublic enum AccessLevels\n{\n    Read = 1,\n    Write = 2\n}	0
129956	129917	What is the best way to launch a web browser with a custom url from a C# application?	try\n{\n    var url = new Uri("http://www.example.com/");\n\n    Process.Start(url.AbsoluteUri);\n}\ncatch (UriFormatException)\n{\n    // URL is not parsable\n}	0
23084722	23083822	Create Workbook With 4 Worksheets & Name	Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();\nMicrosoft.Office.Interop.Excel._Workbook workbook = ap.WOrkbooks.Add(Type.Missing);\nMicrosoft.Office.Interop.Excel._Worksheet worksheet = null;\nSheets xlSheets = null\nWorksheet xlNewSheet = null;\nxlSheets = workbook.Sheets as Sheets;\napp.Visible = true;\n//And you can do this as many times as the sheets you want to add\nworksheet = workbook.Worksheets[1];\nworksheet.Name = "Sheet 1";\nworksheet = workbook.Worksheets[2];\nworksheet.Name = "Sheet 2";	0
32715031	32714920	DbContext pluralizing table names on accessing db	[Table("Person")]\npublic class Person { ... }	0
1857661	1857192	Load from Properties.Settings to ArrayList?	ArrayList all = Settings.AlarmList2;\nforeach (ArrayList items in all) {\n     // items [0] -> DateTime\n     // items [1] -> string1\n     // items [2] -> string2\n}	0
26801240	26250912	Syncfusion DoubleTextBox - NegativeColor	class ViewModel\n{\n    Form1 frm = new Form1();\n    Data data = new Data();\n    public ViewModel(Form1 _frm)\n    {\n        frm = _frm;\n        foreach (Control ctrl in frm.Controls)\n            if (ctrl is DoubleTextBox)\n                (ctrl as DoubleTextBox).DataBindings.Add("Text", data, "unit");\n        Application.Run(frm);\n    }\n}\n\npublic class Data\n{\n    private double n_unit = -5;\n\n    public double unit\n    {\n        get { return n_unit; }\n        set { n_unit = value; }\n    }\n}	0
25022204	25022003	Validate on Button1 click, but not Button2	CausesValidation="false"	0
15277666	15277020	Change system tray color in Windows Phone app through c# code	public MainPage()\n{\n    InitializeComponent();\n\n    this.Loaded += MainPage_Loaded;\n}\n\nvoid MainPage_Loaded(object sender, RoutedEventArgs e)\n{\n    Microsoft.Phone.Shell.SystemTray.BackgroundColor = Colors.Cyan;\n    Microsoft.Phone.Shell.SystemTray.ForegroundColor = Colors.Green;\n}	0
1194305	1194066	C# DataView Date Range with LIKE Operator?	public void DisplayRecSmsByDateRange(string date1,string date2, string readDir)\n        {\n        DataSet ds = new DataSet("SMS DataSet");\n        XmlDataDocument xmlDatadoc = new XmlDataDocument();\n        xmlDatadoc.DataSet.ReadXml(readDir);\n        ds = xmlDatadoc.DataSet;\n\n        DataView custDV = new DataView(ds.Tables["SMS"]);\n        custDV.RowFilter = String.Format("(DateTime >= '{0}*' and DateTime <= '{1}*')", EscapeLikeValue(date1), EscapeLikeValue(date2));\n\n        custDV.Sort = "DateTime";\n        this.dataGridView1.DataSource = custDV;\n        }	0
9329757	9329687	Automatic login process in Windows Phone 7.1 application	Important Note:\nIsolated storage is available while the emulator is running. Data in isolated storage does not persist after the emulator closes. This includes files stored in a local database, as these files reside in isolated storage.	0
26998894	26998392	How to access animation parameters in Unity C#?	Animator animator;\n\nvoid Start() {\n    animator = GetComponent<Animator>();\n}\n\nvoid Update() { \n    var attacking = animator.GetBool("Attacking");\n}	0
22620351	22620308	How can I convert it to DateTime without adding a new variable?	startdate.Text = Convert.ToDateTime(start_date).AddDays(1).ToString();	0
12610117	12609707	How to capitalize regex numbered group	var pattern = @"([a-z]+) ([a-z]+)";\nvar format = "[starts-with({0}{1}]";\n\nvar input = "bla bla";\nvar result = ReplacePattern(input, pattern, format);\n\npublic static string ReplacePattern(string input, string pattern, string format)\n{\n   if (Regex.Match(input, pattern).Groups.Count != 3) return input;//or throw, or...\n   return Regex.Replace(input, pattern, x =>\n            string.Format(format,\n                          x.Groups[1].Value.ToUpper(), \n                          x.Groups[2].Value));\n}	0
21926130	21925936	Connect to Oracle database from host running on Virtual Machine	ADO.NET	0
6870932	6870838	Get data from password protected Excel file using OleDB	User ID=UserX;Password=UserXPassword	0
21360153	21360074	Get the items in a ListView in thread via a class	delegate ListView.ListViewItemCollection DelGetItems(ListView lvControl);\n\n    ListView.ListViewItemCollection GetItems(ListView lvControl)\n    {\n        if (lvControl.InvokeRequired)\n        {\n            return (ListView.ListViewItemCollection)lvControl.Invoke(new DelGetItems(GetItems) ,new Object[] { lvControl });\n        }\n        else\n        {\n            return lvControl.Items;\n        }\n    }	0
3416359	3416341	Regular Expression that Matches Any Number or Letter or Dash	Regex rgx = new Regex(@"^[\w-]*$");\nrgx.IsMatch(searchString)	0
5485393	5401912	How to remove wpf grid sort arrow after clearing sort descriptions	foreach (DataGridColumn column in DataGridView.Columns)\n{\n    column.SortDirection = null;\n}	0
33484533	33480824	C# Is there a way to get table object in excel worksheet	Excel.Worksheet activeWorksheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet;\n\n        foreach (Excel.ListObject table in activeWorksheet.ListObjects)\n        {\n            Excel.Range tableRange = table.Range;\n            String[] dataInRows = new string[tableRange.Rows.Count];\n\n            int i = 0;\n\n            foreach (Excel.Range row in tableRange.Rows)\n            {\n\n                for (int j = 0; j < row.Columns.Count; j++)\n                {\n                    if (row.Cells[1, j + 1].Value2 != null)\n                    {\n                        dataInRows[i] = dataInRows[i] + "_" + row.Cells[1, j + 1].Value2.ToString();\n                    }\n                }\n\n                i++;\n            }\n        }	0
29825660	29825208	Remove all tables in Azure Table Storage	var tableClient = storageAccount.CreateCloudTableClient();\nforeach (var table in tableClient.ListTables())\n    table.DeleteIfExists();	0
15998686	14725261	Change font colour of DevComponents AdvTree node	void ChangeNodeStyle(AdvTree tree, int node, int style)\n    {\n        tree.Nodes[node].Style = tree.Styles[style];\n    }	0
26172319	26172253	Regex needed to remove and replace specified html tags in two criteria's using C#	//to remove all h1 tags:\nRegex.Replace(html, @"</?h1[^>]*>", "")\n\n//to replace all div tags with p, keeping the same attributes:\nRegex.Replace(html, @"(</?)div([^>]*>)", "$1p$2")\n\n//to change the attributes of the div tags you will need two regexes:\n//one for the opening tags\nRegex.Replace(html, @"<div[^>]*>", "<p class='content'>")\n//one for the closing tag\nRegex.Replace(html, @"</div>", "</p>")	0
26242507	26242249	Dynamically added labels only show one	fileName.Top = (i + 1) * 22;	0
10341865	10341513	How to Make Top Value of DropDownList Item Bold C#	var item = new ListItem("CustomClock");\nitem.Attributes.Add("style", "font-weight: bold");\n\nddlDefaultSkins.Items.Add(item);	0
8090247	8090107	Can I dynamically apply XmlIgnore to properties of an ArrayItem?	partial class Car {\n    public bool ShouldSerializeEngineSize() { return false; }\n}	0
9476540	9476505	How to make this DropDownList works inside the GridView?	protected void DropDownList_DataBound(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        ((DropDownList)sender).Items.Insert(0, new ListItem("--Select--", ""));\n    }\n}	0
2201988	2190012	C# DataGridView Adding a Row - When validating, how do I know the row is new and not yet committed?	if (this.DATASET.DATATABLE.Rows.Count == e.RowIndex)	0
5911657	5911566	how to enable the RadioButtonList while retriving from database	ui_rblIsActive.Enabled	0
21657080	21657064	ProjectEuler Q1 Program unexpected result	int result = 3 * (999 / 3 * (999 / 3 + 1) / 2) + 5 * (999 / 5 * (999 / 5 + 1) / 2) - 15 * (999 / 15 * (999 / 15 + 1) / 2);	0
26970385	26970112	Using reflection to set List<dynamic> to List<T>	static void SetPropertyValue(object p, string propName, object value)\n{\n    Type t = p.GetType();\n\n    System.Reflection.PropertyInfo info = t.GetProperty(propName);\n\n    if (info == null)\n        return;\n    if (!info.CanWrite)\n        return;\n\n    var elemtype = info.PropertyType.GetElementType();\n    var castmethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elemtype);\n    var tolist = typeof(Enumerable).GetMethod("ToList", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elemtype);\n\n    var collection = castmethod.Invoke(null, new object[] { value });\n    var list = tolist.Invoke(null, new object[] { collection });\n\n    info.SetValue(p, list, null);\n}	0
15942887	15942549	c#: How to replace [ to { but ignore \[?	Regex regexObj = new Regex(\n    @"(?<=     # Make sure that this is true before the start of the match:\n     (?<!\\)   # There is no single backslash,\n     (?:\\\\)* # but if there are backslashes, they need to be an even number.\n    )          # End of lookbehind assertion.\n    \[         # Only then match a bracket", \n    RegexOptions.IgnorePatternWhitespace);	0
15829991	15826874	Export to Excel - Installing Office Customization in MVC4	Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.dll\nMicrosoft.VisualStudio.QualityTools.LoadTestExcelAddIn.dll.manifest\nMicrosoft.VisualStudio.QualityTools.LoadTestExcelAddIn	0
8120399	8120124	How to split data from string?	var input = "Url:http://www.yahoo.com UrlImage:http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png UrlTitle:Yahoo! India UrlDescription:Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information."\n\n// Convert the input string into a format which is easier to split...\ninput = input.Replace("Url=", "")\n             .Replace("UrlImage=", "|")\n             .Replace("UrlTitle=", "|")\n             .Replace("UrlDescription=", "|");\n\nvar splits = input.Split("|");\n\nstring url         = splits[0]; // = http://www.yahoo.com\nstring image       = splits[1]; // = http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png\nstring title       = splits[2]; // = Yahoo! India\nstring description = splits[3]; // = Welcome to Yahoo!, the world's...	0
27851522	27851057	How to write an interface for a generic method	public class PlayersCollection<T> : IWorldCollection<T> where T : PlayerModel\n{\n\n    public Dictionary<Type, T> Collection;\n\n    public PlayersCollection()\n    {\n        Collection = new Dictionary<Type, T>();\n    }\n\n    public T Get(int id)\n    {\n       var t = typeof(T);\n       if (!Collection.ContainsKey(t)) return null;\n       var dict = Collection[t] as Dictionary<int, T>;\n       if (!dict.ContainsKey(id)) return null;\n       return (T)dict[id];\n    }\n  }\n\npublic interface IWorldCollection<T> where T : class\n{\n    T Get(int id);\n}	0
17576034	17573068	Listview with databound CheckBox	If(!Page.IsPostBack)\n{\n    if (Session["IDValue"] != null)\n    {\n        int gen = Convert.ToInt32(Session["IDValue"]);\n        lstPreferences.DataSource = mdb.GetPreferences(gen);\n        lstPreferences.DataBind();          \n    }\n}	0
384626	384610	Singleton with a public (single-instance) constructor	Equals()	0
6523648	6523331	silverlight, C#, adding extra control for XAML	public MC.LocationRect ViewArea {\n    get { return (MC.LocationRect)GetValue(ViewAreaProperty); }\n    set { SetValue(ViewAreaProperty, value); }\n}\n\npublic static readonly DependencyProperty ViewAreaProperty = DependencyProperty.Register("ViewArea", typeof(MC.LocationRect),\n    typeof(Map), new PropertyMetadata(new MC.LocationRect(), OnViewAreaChanged));\n\nprivate static void OnViewAreaChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {\n    var map = d as Map;\n    // Call SetView here\n}	0
29378501	29377588	HTTP POST from Classic ASP to WCF REST Service	set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")    \nxmlhttp.open "POST", url, false ' usage xmlhttp.open method, url, async\nxmlhttp.setRequestHeader "Content-Type", "text/xml"    \nxmlhttp.send payload ' The payload variable containing the XML\nresponsetxt =  xmlhttp.responseText \nhttpstatus = xmlhttp.status \nstatustext = xmlhttp.statustext\nset xmlhttp = nothing	0
2821083	2821035	c# get start-date and last-date based on current date	DateTime baseDate = DateTime.Today;\n\nvar today = baseDate;\nvar yesterday = baseDate.AddDays(-1);\nvar thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);\nvar thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);\nvar lastWeekStart = thisWeekStart.AddDays(-7);\nvar lastWeekEnd = thisWeekStart.AddSeconds(-1);\nvar thisMonthStart = baseDate.AddDays(1 - baseDate.Day);\nvar thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);\nvar lastMonthStart = thisMonthStart.AddMonths(-1);\nvar lastMonthEnd = thisMonthStart.AddSeconds(-1);	0
3014698	3014119	Calculate a set of concatenated sets of n sets	void Main()\n{\n    IEnumerable<IEnumerable<string>> sets = \n          new[] { \n                  /* a */ new[] { "a", "b", "c" },\n                  /* b */ new[] { "1", "2", "3" },\n                  /* c */ new[] { "x", "y", "z" }\n                };\n\n    var setCombinations = from set in sets\n                          select (from itemLength in Enumerable.Range(1, set.Count()).Reverse()\n                                  select string.Concat(set.Take(itemLength).ToArray()));\n\n    IEnumerable<string> result = new[] { string.Empty };\n\n    foreach (var list in setCombinations) {\n        result = GetCombinations(result, list);\n    }\n    // do something with the result\n}\n\nIEnumerable<string> GetCombinations(IEnumerable<string> root, IEnumerable<string> append) {\n    return from baseString in root\n           from combination in ((from str in append select baseString + str).Concat(new [] { baseString }))\n           select combination;\n}	0
20285575	20285478	Combobox issues in Click	Application.EnableVisualStyles();\nApplication.SetCompatibleTextRenderingDefault(false);\nSystem.Threading.Thread.CurrentThread.ApartmentState = System.Threading.ApartmentState.STA;\nApplication.Run(new FlashForm());	0
854555	854476	In C#, how do I add event handlers to an object based on names?	eventInfo.AddEventHandler(this, Delegate.CreateDelegate(typeof(eventInfo.EventHandlerType.FullName), this, "MyEventHandler"));	0
18502930	18502639	Allowing subdomains in Azure	your own domain	0
2787483	2787458	How to select top n rows from a datatable/dataview in ASP.NET	dt.Rows.Cast<System.Data.DataRow>().Take(n)	0
28487107	28462442	IRandomAccessStreamReference to image source	BitmapImage bmp = new BitmapImage(new Uri(((StorageFile)contact.Thumbnail).Path));	0
6231768	6231736	Add message to popup message box C# noob question	catch (Exception)\n{\n    MessageBox.Show(\n         Conversion.ErrorToString(),  // Caption\n         "Error:",                    // Title displayed\n         MessageBoxButtons.OK,        // Only show OK button\n         MessageBoxIcon.Error);       // Show error icon (similar to Critical)\n}	0
26109890	26109637	How to group a list of integers based on moving range?	var l = new[] { 14, 24, 56, 189, 909, 1000 };\n            var groups = new List<List<int>>();\n            groups.Add(new List<int>());\n            groups[0].Add(l[0]);\n            for (int i = 1; i < l.Length; i++)\n            {\n                if (l[i] - l[i - 1] > 100)\n                {\n                    groups.Add(new List<int>());\n                }\n                groups[groups.Count - 1].Add(l[i]);\n            }	0
13578568	13578333	How to wait for a button to be clicked?	public partial class Form1 : Form\n{\n    System.Windows.Forms.Timer timer;\n\n    public Form1()\n    {\n        InitializeComponent();\n\n        //create it\n        timer = new Timer(); \n        // set the interval, so it'll fire every 1 sec. (1000 ms)\n        timer.Interval = 1000; \n        // bind an event handler\n        timer.Tick += new EventHandler(timer_Tick); \n\n        //...\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n        //do what you need\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        timer.Start(); //start the timer\n        // switch buttons\n        button1.Enabled = false;\n        button2.Enabled = true;        \n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        timer.Stop(); //stop the timer\n        // switch buttons back\n        button1.Enabled = true;\n        button2.Enabled = false;\n    }	0
6896309	6895813	How to treat Regular Expression as plain text while using .Net Regex Class?	string pattern = @"a\w";\nRegex regexp = new Regex(Regex.Escape(@"a\w"), RegexOptions.None);\nif (regexp.IsMatch(pattern))\n{\n    MessageBox.Show("Found");\n}	0
25019661	25019582	Open up another asp page	Server.Transfer("Submitted.aspx");	0
4782156	4757104	NInject Singletons - Are they created at application or session level?	public static class NinjectSessionScopingExtention\n{\n    public static void InSessionScope<T>(this IBindingInSyntax<T> parent)\n    {\n        parent.InScope(SessionScopeCallback);\n    }\n\n    private const string _sessionKey = "Ninject Session Scope Sync Root";\n    private static object SessionScopeCallback(IContext context)\n    {\n        if (HttpContext.Current.Session[_sessionKey] == null)\n        {\n            HttpContext.Current.Session[_sessionKey] = new object();\n        }\n\n        return HttpContext.Current.Session[_sessionKey];\n    }\n}	0
15600179	15600099	How to sort in a WPF ListBox?	listBox1.Items.SortDescriptions.Add(\n            new System.ComponentModel.SortDescription("",\n            System.ComponentModel.ListSortDirection.Ascending));	0
22048559	22047858	EF Adding a new item through interface	_db.PostDetails.Add(pd)	0
3057045	3055842	How to access the subject of a compose mail item in Outlook	if (thisMailItem != null)\n{\n    thisMailItem.Save();\n\n    if (thisMailItem.EntryID != null)\n    {\n        thisMailItem.Subject = "prepended text: " + thisMailItem.Subject;\n        thisMailItem.Send();\n    }\n}	0
23409208	23409072	Replace specific part with regex	void Main()\n{\n  Regex regex = new Regex("(<textarea.*>)(.*)(</textarea>)");\n  string s = "<textarea>test</textarea>";\n  string a = regex.Replace(s, "$1abc$3");\n  Console.WriteLine(a);\n}	0
31122052	31121744	Selenium button identification multiples on page	//a[@class='cta-button cta-begin-order'][@store='2']\n//a[@store='2']\n//a[text()='Order'][2] //Index based	0
10563485	10563449	Search in list of objects	foreach (Customer name in m_customers) \n{ \n    if(name.ContactData != null) System.Diagnostics.Debug.WriteLine(name.ContactData.FullName);\n\n    if (name.ContactData.FullName == "Anna")  \n    { \n        MessageBox.Show(string.Format("Yes"), "Test!", MessageBoxButtons.OK, MessageBoxIcon.Information); // Just for testing   \n    } \n}	0
12268746	12268559	Removing substring by length	this.temp = String.Empty;\nforeach (string line in this.txtBox.Lines) {\n    if (line.Length<=Envir.Operations.Length) {\n        this.temp += Environment.NewLine;\n        continue; // adding new line if input is shorter\n    }\n    if (Envir.Operations.Begin)\n        this.temp += line.Substring(Envir.Operations.Length - 1) + Environment.NewLine;\n    else\n        this.temp += line.Substring(0, line.Length - Envir.Operations.Length) + Environment.NewLine;	0
4310140	4301149	Editing a row in DB	[Admin].[sp_Ques]	0
21386292	21386224	Using delimiters to separate string into variables	string[] vars = line.Split(',');\n\nstring id   = vars[0];\nstring slip = vars[1];\nstring Qty  = vars[2];\nstring Item = vars[3];\nstring UOM  = vars[4];\nstring Desc = vars[5];	0
14729092	14729064	Need RegEx to remove all alphabets from string	string filtered = Regex.Replace(input, "[A-Za-z]", "");	0
28334598	28333999	Simplistic Challenge and Response Password	var codeByte = ComputeByteArraySha256(\n      DateTime.Today + AdminName + UserName + SecretSalt)[13];\nvar codeText = codeByte.ToString();	0
3932499	3932391	How to get url from RouteTable.Routes collection by key?	RouteCollection routes = RouteTable.Routes;\nRouteBase route = routes["key"];	0
16219320	16219229	Json formatted string to list	var result = input.Replace(":{", " - ")\n                  .Replace("},", Environment.NewLine)\n                  .Replace("{", string.Empty)\n                  .Replace("}", string.Empty);	0
4230817	4230714	How to visually let the user know that something is selected?	ptbImage1.Click += new System.EventHandler(ptbImage_Click);\nptbImage2.Click += new System.EventHandler(ptbImage_Click);\nptbImage3.Click += new System.EventHandler(ptbImage_Click);	0
11737775	11737711	bind textbox to a field of a query of dataset	textbox.text=DtSet.Tables[0].Rows[0]["database column name"].ToString();	0
3488842	3488820	How do I initialize a C# array with dimensions decided at runtime?	double[,] = new double[50, v];	0
22079100	22078914	Collision detection on Objects in C#	foreach (Apple a in myapples) {\n  LayoutRoot.Children.Add(a);\n}	0
30393277	30364884	How to convert YAML to JSON?	// now convert the object to JSON. Simple!\nvar js = new Serializer(SerializationOptions.JsonCompatible);\n\nvar w = new StringWriter();\njs.Serialize(w, o);\nstring jsonText = w.ToString();	0
19712064	19711675	How to check DBNull value in Linq query results	amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"] == DBNull.Value ? 0 : x["AMOUNT"]));	0
9854478	9854438	Error C#/MySQL multiple select statements in insert statement	command.CommandText = \n@"INSERT INTO personen (Name, Surname, GenderID, BirthplaceID) \n  VALUES (@Name, @Surname, \n             (SELECT GenderID FROM gender WHERE Gender = @GenderID),  \n             (SELECT BirthplaceID FROM place WHERE placename = @BirthplaceID)\n         );";	0
3006214	3006166	Efficient way to fire 2 diff events with the same button on each click?	private void buttonON()\n{\n    // Magic here\n}\n\nprivate void buttonOFF()\n{\n    // Magic here\n}\n\nprotected void button_click(object sender, EventArgs e)\n{\n    if ( button.Text == "ON" )\n    {\n        button.Text = "OFF";\n        this.buttonOFF();\n    }\n    else\n    {\n        button.Text = "ON";\n        this.buttonON();\n    }\n}	0
1399216	1398671	PKCS11 certificate	System.Security.Cryptography.Pkcs	0
3723662	3674440	How do I set a timer XAML.CS which acts like HoverIntent in Javascript	public DispatcherTimer myDispatcherTimer = new DispatcherTimer();\n\nprivate void ViewerTab_MouseLeave(object sender, MouseEventArgs e)\n{\n    myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);\n    myDispatcherTimer.Tick += new EventHandler(functiontocall);\n    myDispatcherTimer.Start();\n}\n\npublic void functiontocall(object o, EventArgs sender)\n{\n    // do something here\n\n    myDispatcherTimer.Stop();\n}\n\nprivate void ViewerTab_MouseEnter(object sender, MouseEventArgs e)\n{\n    myDispatcherTimer.Stop();\n}	0
30142375	30142332	WPF - Cannot convert text from TextBox to Double	double [] Fi = new double [3];	0
32941948	32941805	How to allow number or number/number in regular expression	[0-9]{2}(/[0-9]{2}){0,1}	0
33585698	33585610	ASP datagrid not displaying all items	SqlDataReader basketReader = User.GetBasket(User.GetUserID(Page.User.Identity.Name));\n\nif (basketReader.HasRows)\n{\n    orderDG.DataKeyField = "ItemCode";\n    orderDG.DataSource = basketReader;\n    orderDG.DataBind();\n    basketReader.Close();\n}\nelse\n{\n    Response.Redirect("~/Orders.aspx", false);\n}	0
20443310	20442883	Writing binary data to ftp location	upload.GetResponse()	0
4875755	4868982	Printing a PDF Silently with Adobe Acrobat	Process pdfProcess = new Process();\npdfProcess.StartInfo.FileName = @"C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe";\npdfProcess.StartInfo.Arguments = string.Format(@"-p {0}", fileNameToSave);\npdfProcess.Start();	0
3854828	3854777	Read Variable from Web.Config	System.Configuration.ConfigurationManager.AppSettings	0
28583506	28583404	Web api is sending JSON object in wrong format	public NotificationsResult Get(string machineName)\n{\n    int NotificationsNumber = NotificationsFunctions.CheckForNotifications(machineName);\n    return new NotificationsResult\n    {\n        Result = NotificationsNumber > 0 ? "true" : "false";             \n    };\n}	0
17213221	17211545	SharpSVN - Server certificate verification failed	client.Authentication.SslServerTrustHandlers += new EventHandler<SharpSvn.Security.SvnSslServerTrustEventArgs>(Authentication_SslServerTrustHandlers);\n    void Authentication_SslServerTrustHandlers(object sender, SharpSvn.Security.SvnSslServerTrustEventArgs e)\n    {\n        // Look at the rest of the arguments of E, whether you wish to accept\n\n        // If accept:\n        e.AcceptedFailures = e.Failures;\n        e.Save = true; // Save acceptance to authentication store\n    }	0
13007652	13007092	Getting counts of two items of same column in single table	var isMobile = (from d in _db.UserDeviceDetail \n                        where ((d.CreatedOn.Month >= fromDate.Month && d.CreatedOn.Day >= fromDate.Day && d.CreatedOn.Year >= fromDate.Year) || (d.CreatedOn.Month <= toDate.Month && d.CreatedOn.Day <= toDate.Day && d.CreatedOn.Year <= toDate.Year)) \n                        select d).ToList(); \nreturn new List<IsMobile>(){\n            new IsMobile{ \n                Yes = isMobile.Count(n => n.IsMobile == true), \n                No = isMobile.Count(n => n.IsMobile == false)}\n            };	0
4639368	4639256	C# - Connecting to a FTP Server	public bool IsFtpFileExists(string remoteUri, out long remFileSize)\n        {\n            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(BuildServerUri(remoteUri));\n            FtpWebResponse response;\n\n            request.Method = WebRequestMethods.Ftp.GetFileSize;\n            request.Credentials = new NetworkCredential(Username, Password);\n            try\n            {\n                response = (FtpWebResponse)request.GetResponse();\n                remFileSize = response.ContentLength;\n                return true;\n            }\n            catch (WebException we)\n            {\n                response = we.Response as FtpWebResponse;\n                if (response != null && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)\n                {\n                    remFileSize = 0;\n                    return false;\n                }\n                throw;\n            }\n        }	0
5486153	5486055	SQLSERVER 2008 executing a select statement repeatedly causes High CPU usage	while (x == false) {\nx = SQL STATEMENT\n}	0
5794018	5709710	How do I return a document from a Sharepoint Document library to the user?	FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, reference);\n\n        Stream stream = fileInformation.Stream; \n        if (stream != null)\n        {\n            documentName = Path.GetFileName(reference);\n\n            return new FileStreamResult(stream, "unknown")\n            {\n                FileDownloadName = documentName\n            };\n        }	0
5931153	5931073	Implementing A* on a triangular/hexagonal Grid with negative Coordinates	var nodes = new Dictionary<Point, Vector[]>;	0
27252015	27251844	Display C# DateTime in HTML Text Input	DateTime.Now.Day\nDateTime.Now.Month\nDateTime.Now.Year	0
7901017	7894071	How to make data access layer aware of the current application state?	Settings currentSettings = ContainerService.Instance.Resolve<Settings>();\nSomeType t = new SomeType(currentSettings);	0
11080555	11080445	display part of description in href using c#	optionlist.AppendFormat("<li>\n<a href=\"setlocale.aspx?returnURL=Default.aspx&localesetting={0}\">{1}</a>\n</li>", DB.RSField(rs, "Name").Substring(3), DB.RSField(rs, "Name").Substring(3));	0
15813711	15813651	how to select a weeks amount of dates from a database?	DateTime weekFromNow = DateTime.Now.AddDays(-7);\nvar records = (from r in context.PumpInfoTables\n                           where r.Date < DateTime.Now\n                           && r.Date >= weekFromNow\n                           select r);	0
18121545	18121503	Determining the number of parameters accepted by a method	Type.GetType("MyClassType").GetMethod("foo").GetParameters().Length;	0
5930963	5930938	How can I get the Value of a DataGridViewCell from the Cell_Leave event?	theDataGrid[e.RowIndex, e.ColumnIndex].Value	0
27956041	27912851	How to identify a checkbox in a table if I can find a text string on the same row?	StringBuilder buffer = new StringBuilder();\nbuffer.Append("//a[contains(text(),'").Append(applicationNumber + "')]");\nString id = Generic.Find.ByXPath(buffer.ToString()).IdAttributeValue.Split(new char[] { ':' })[2];\nGeneric.Find.ById<HtmlInputCheckBox>("dashboardForm:applicationTaskTable:" + id + ":application_checkbox").Check(true, true);	0
4577939	4577892	How to By Pass Request Validation	string script = String.Format("var inputs = $get('{0}').getElementsByTagName('input');" + \n  "for(var i = 0; i < inputs.length; i++) " + \n    "inputs[i].value = encodeURIComponent(inputs[i].value);", this.ClientID);\nPage.ClientScript.RegisterOnSubmitStatement(this.GetType(), "onsubmit", script);	0
29268224	29256387	Windows Phone 8 - waiting for HttpWebRequest to finish in Application_Closing method	var http = new HttpSocketConnection();\nvar postBody = new HttpPostBodyBuilder.*Body();\n// Here you set some parameters\nusing (var bodyStream = postBody.PrepareData()) {\n    var req = new HttpMessage.Request(bodyStream, "POST");\n    req.ContentLength = bodyStream.Length;\n    req.ContentType = postBody.GetContentType();\n\n    // send request\n    var response = http.Send(url, req);\n}	0
33620702	33620701	How to load an embedded resource from a base class that is in another VS project from that base class	var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("A.B.C.Schemas.FuzzyTestPlan.xsd")	0
17843338	17843210	Match only a newline character	public int LineCounter()\n    {\n        using (StreamReader myRead = new StreamReader(@"C:\TestFiles\test.txt"))\n        {\n            int lineCount = 0;\n            string line;\n\n            while ((line = myRead.ReadLine()) != null)\n            {\n                if (line.Count() != 0)\n                {\n                    lineCount++;\n                }\n            }\n        }\n\n        return lineCount;\n    }	0
19909296	19906944	How to make window appear on top of all other windows?	var shell = (Shell) Shell;\nApplication.Current.MainWindow = shell;\nshell.Topmost = true;\nshell.Show();\nshell.InjectInitialViews();\nshell.Activate();	0
13433600	13433511	Add two string arrays to one ListView column	string[] k = getBetweenAll(thepage, "<h4 style=\"padding:0 0 0 3px;\"><a href=\"", "\" target=\"_blank\">");\n     string[] q = getBetweenAll(thepage, "<h4><a href=\"", "\" target=\"_blank\">");\n     var items = listViewClickbank.Items;\n\n\n     var z = new int[k.Length + q.Length]; \n     k.CopyTo(z, 0);\n     q.CopyTo(z, k.Length);\n\n     for (int i = 0; i < z.Length; i++)\n     {\n         Items.SubItems.Add(input + z[i]);\n     }	0
30802934	30260474	Is there any way to get all data retrieved between two points in C# code (Linq-to-sql)	MiniProfiler.Current.GetSqlTimings();	0
8056678	8053491	Passing lambda functions as named parameters in C#	class CustomerCollection\n{\n    public IEnumerable<R> Select<R>(Func<Customer, R> projection) {...}\n}\n....\ncustomers.Select( (Customer c)=>c.FristNmae );	0
18312066	18288940	Is there any possibility to invoke managed methods from C in Xamarin.IOS	delegate long GetLengthCallback (IntPtr handle);\n\n// Xamarin.iOS needs to the MonoPInvokeCallback attribute\n// so that the AOT compiler can emit a method\n// that can be called directly from native code.\n[MonoPInvokeCallback (typeof (GetLengthCallback)]\nstatic long GetLengthFromStream (IntPtr handle)\n{\n    var stream = (Stream) GCHandle.FromIntPtr (handle).Target;\n    return stream.Length;\n}\n\nstatic List<object> delegates = new List<object> ();\n\nstatic void SetCallbacks (Stream stream)\n{\n    NativeMethods.SetStreamObject (new GCHandle (stream).ToIntPtr ());\n\n    var delGetLength = new GetLengthCallback (GetLengthFromStream);\n    // This is required so that the GC doesn't free the delegate\n    delegates.Add (delGetLength);\n    NativeMethods.SetStreamGetLengthCallback (delGetLength);\n    // ...\n}	0
17787863	17787767	Unable to connect to remote server	var client = new SmtpClient("smtp.gmail.com", 587)\n {\n    Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),\n    EnableSsl = true\n};\nclient.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");	0
10600654	10600592	Programmatically remove specific class name from HTML element	var classes = myInput.Attributes["class"].Split(' ');\n\nvar updated = classes.Where(x => x != "classtoremove").ToArray();\n\nmyInput.Attributes["class"] = string.Join(" ", updated);	0
958052	958031	Log a message with a variable number of printf-style arguments	static void LogMessage(string format, params object[] args) {\n    File.AppendAllText("log.txt", string.Format(format, args));\n}\n\nLogMessage("Testing {0} {1}", 1, "hi");	0
30186335	30186280	C# threading - resetThread is a 'variable' but is used like a 'method'	reset()	0
26969667	26969360	Render a string only on first iteration of a loop	private static string RenderMenuRecursive(ItemMenu menu, int level, bool firstIteration)\n{\n    [...]\n\n        if (level == 3)\n        {\n            if (firstIteration)\n            {\n                sb.AppendLine("<ul class=\"" + "nav nav-third-level background-white collapse" + "\">");\n                firstIteration++;\n            }\n\n            sb.AppendLine("<li><a href=\"#\">" + menu.name + "</a>");\n        }\n\n    [...]\n\n    var firstIteration = true;\n\n    foreach (ItemMenu subMenu in menu.subMenuItems)\n    {\n        sb.AppendLine(RenderMenuRecursive(subMenu, level, firstIteration));\n        firstIteration = false;\n    }\n\n    return sb.ToString();\n}	0
4495482	4491156	Get the export value of a checkbox using iTextSharp	AcroFields.Item item = acroFields.getFieldItem(fldName);\nPdfDictionary valueDict = item.getValue(0);\n\nPdfDictionary appearanceDict = valueDict .getAsDict(PdfName.AP);\n\nif (appearanceDict != null) {\n  PdfDictionary normalAppearances = appearanceDict.getAsDict(PdfName.N);\n  // /D is for the "down" appearances.\n\n  // if there are normal appearances, one key will be "Off", and the other\n  // will be the export value... there should only be two.\n  if (normalAppearances != null) {\n    Set<PdfName> keys = normalAppearances .getKeys();\n    for (PdfName curKey : keys) {\n      if (!PdfName.OFF.equals(curKey)) {\n        return curKey.toString(); // string will have a leading '/' character\n      }\n    }\n  }\n\n\n}\n// if that doesn't work, there might be an /AS key, whose value is a name with \n// the export value, again with a leading '/'\nPdfName curVal = valueDict.getAsName(PdfName.AS);\nif (curVal != null) {\n  return curVal.toString();\n}	0
8464392	8464326	Datagridview Ordering of Column Headers- Winform C#	private void AdjustColumnOrder()\n{\n    customersDataGridView.Columns["CustomerID"].Visible = false;\n    customersDataGridView.Columns["ContactName"].DisplayIndex = 0;\n    customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;\n    customersDataGridView.Columns["City"].DisplayIndex = 2;\n    customersDataGridView.Columns["Country"].DisplayIndex = 3;\n    customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;\n}	0
9102886	9102527	gzip format streaming	GZIPInputStream stream = new GZIPInputStream(new FileInputStream("some_file.gz"));\nBufferedReader reader = new BufferedReader(stream);\n\n// Now read line by line... till you hit the content you want.	0
7996476	7996306	Get the value of a column name when column name is a variable using EF4	object value = product.GetType().GetProperty(categoryLand).GetValue(product,	0
32769318	32768753	Validating JSON before it gets deserialized in asp.net web api	if (!Model.IsValid(ModelName))\n{\n    //handle error\n}\nelse\n{\n    //continue \n}	0
23897050	23896631	schedule post using facebook c# sdk	client.Post("postId/feeds", new\n        {\n            access_token = "Your access token",\n            scheduled_publish_time = "Time as unix timestamp",\n            message = "Your message",\n            published = "0"\n        });	0
8519842	8519294	How to change the db name dynamically using one db  storedprocedures to another db storedprocedures?	-- assume @dbname has the name of the database where getdetails was created\ndeclare @sql nvarchar(4000), @params nvarchar(4000), @dbname sysname\nset @dbname = 'test'\nset @sql = @dbname + '..getdetails'\nset @params = ''\nexec sp_executesql @sql, @params	0
6700020	6699627	How to change depending on the resource name	public static System.Drawing.Bitmap denis {\n    get {\n        object obj = ResourceManager.GetObject("denis", resourceCulture);\n        return ((System.Drawing.Bitmap)(obj));\n    }\n}	0
33341975	33341923	Access GridView ItemTemplate control ASP.NET	protected void GrdLimitAndUtilization_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        HyperLink lnkExcess = (HyperLink)e.Row.FindControl("lnkExcess");\n        //Access hyperlink's properties here.\n     }\n}	0
25323963	25323863	Separate string from list C#	List<string> output = new List<string>();\n        input.ForEach(x=> output.Add(x.Split(new[] {": "},StringSplitOptions.None).Last()));	0
18421275	18420251	How to iterate through each word, ms-word?	doc = page.Documents.Open(Application.StartupPath + "\\old\\" + fi);\n            if (doc != null)\n            {\n                for (int x = 1; x <= doc.Words.Count - 1; x++)\n                {\n                        if (doc.Words[x].Underline != word.WdUnderline.wdUnderlineNone && doc.Words[x].Underline != word.WdUnderline.wdUnderlineDouble)\n                            doc.Words[x].Font = new word.Font() { Name = "Times New Roman", Bold = 4, Size = 12 };\n                        else\n                            doc.Words[x].Font = new word.Font() { Name = "Times New Roman", Size = 8 };\n                }	0
12055846	12055741	Get bytes after index in byte[]	byte[] bytes = Encoding.UTF8.GetBytes("samebytesDataNeededIsHere");\nbyte[] bytesToUse = bytes.Skip(countOfBytesToSkip).ToArray();	0
15555561	15555389	Sending mail from gmail SMTP C# Connection Timeout	SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);\nsmtp.Credentials = new NetworkCredential("mrbk.writely@gmail.com", "***");\nsmtp.EnableSsl = true;\nsmtp.Send(mail);	0
25934360	25934296	How to call List of methods randomly	Random rnd = new Random();\n// I suppose that you have 5 methods. If you have a greater number of methods\n// just change the 6.\nvar number = rnd.Next(1,6);\nswitch(number)\n{\n    case 1:\n       // call Method1\n    case 2:\n      // call Method2 \n}	0
29991911	29991758	How to subtract dateTimePicker fields in C#	DateTimePicker d1;\nDateTimePicker d2;\n\npublic void ComputeDifference()\n{\n    TimeSpan diff = d2.Value - d1.Value;\n    int days = diff.Days + 1;\n}	0
7770331	7770234	string macro replacement	var str = "%SERIALNUMBER3%";\nvar reg = new Regex(@"%(\w+)(\d+)%");\nvar match = reg.Match( str );\nif( match.Success )\n{\n    string token = match.Groups[1].Value;\n    int numDigits = int.Parse( match.Groups[2].Value );\n}	0
1847800	1847719	Validating a class using DataAnotations	public static IEnumerable<ErrorInfo> GetErrors(object instance)    \n{\n   return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() \n      from attribute in prop.Attributes.OfType<ValidationAttribute>()\n      where !attribute.IsValid(prop.GetValue(instance))\n      select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);    \n}	0
7521629	7521254	new data to observable with each method invocation	Subject<int> _myObservable = new Subject<int>(); \n\nvoid ThingsCallMe(int someImportantNumber)\n{\n    // Current pseudo-code seeking to be replaced with something that would compile?\n    _myObservable.OnNext(someImportantNumber);\n}\n\nvoid ISpyOnThings()\n{\n    _myObservable.Subscribe(\n        i =>\n        Console.WriteLine("stole your number " + i.ToString()));\n}	0
2730615	2728879	Re-Inventing The Label Control	using System;\nusing System.Windows.Forms;\n\nclass MyLabel : Label {\n  private TextBox mEditor;\n  protected override void OnDoubleClick(EventArgs e) {\n    if (mEditor == null) {\n      mEditor = new TextBox();\n      mEditor.Location = this.Location;\n      mEditor.Width = this.Width;\n      mEditor.Font = this.Font;\n      mEditor.Text = this.Text;\n      mEditor.SelectionLength = this.Text.Length;\n      mEditor.Leave += new EventHandler(mEditor_Leave);\n      this.Parent.Controls.Add(mEditor);\n      this.Parent.Controls.SetChildIndex(mEditor, 0);\n      mEditor.Focus();\n    }\n    base.OnDoubleClick(e);\n  }\n  void mEditor_Leave(object sender, EventArgs e) {\n    this.Text = mEditor.Text;\n    mEditor.Dispose();\n    mEditor = null;\n  }\n  protected override void Dispose(bool disposing) {\n    if (disposing && mEditor != null) mEditor.Dispose();\n    base.Dispose(disposing);\n  }\n}	0
1599740	1599575	enumerating assemblies in GAC	// List of all the different types of GAC folders for both 32bit and 64bit\n// environments.\nList<string> gacFolders = new List<string>() { \n    "GAC", "GAC_32", "GAC_64", "GAC_MSIL", \n    "NativeImages_v2.0.50727_32", \n    "NativeImages_v2.0.50727_64",\n    "NativeImages_v4.0.30319_32",\n    "NativeImages_v4.0.30319_64"\n};\n\nforeach (string folder in gacFolders)\n{\n    string path = Path.Combine(\n       Environment.ExpandEnvironmentVariables(@"%systemroot%\assembly"), \n       folder);\n\n    if(Directory.Exists(path))\n    {\n        Response.Write("<hr/>" + folder + "<hr/>");\n\n        string[] assemblyFolders = Directory.GetDirectories(path);\n        foreach (string assemblyFolder in assemblyFolders)\n        {\n            Response.Write(assemblyFolder + "<br/>");\n        }\n    }\n}	0
9983953	9983871	How to get data in ASP.net MVC	public static bool IsAdmin(string iduser, string password)\n{\n    using (var conn = new SqlConnection(ConnectionString))\n    using (var cmd = conn.CreateCommand())\n    {\n        conn.Open();\n        cmd.CommandText = @"\n            SELECT IsAdmin \n            FROM [user] \n            WHERE iduser = @iduser AND mdp = @mdp;\n        ";\n        cmd.Parameters.AddWithValue("@iduser", iduser);\n        cmd.Parameters.AddWithValue("@mdp", password);\n        using (var reader = cmd.ExecuteReader())\n        {\n            return reader.Read() && reader.GetBoolean(reader.GetOrdinal("IsAdmin"));\n        }\n    }\n}	0
18777923	18777860	Find Number of LineBreaks in String and Get Count of the LineBreaks in String C#	var count = Str.Split(new[] { "<br />" }, StringSplitOptions.None).Length - 1;	0
26092052	26092002	Add New Tabs to a C# WinForms application from Templates?	private void button1_Click(object sender, EventArgs e)\n{\n    TabPage t = new TabPage();\n    t.Controls.Add(new UserControl1() { Dock = DockStyle.Fill });\n    tabControl1.TabPages.Add(t);\n}	0
28747309	28746585	Export Pivot Grid as Grid View to Excel	gridSettings.SettingsExport.RenderBrick = (sender, e) =>\n            {\n                foreach (MVCxPivotGridField item in dataFields)\n                {\n                    if (e.RowType == DevExpress.Web.ASPxGridView.GridViewRowType.Data\n                        && !string.IsNullOrEmpty(item.CellFormat.FormatString))\n                        e.TextValueFormatString = item.CellFormat.FormatString;\n                }	0
16584232	15632453	Implementing an OPOS printer service object for capturing printed text	if (PropertyIndexHelper.IsStringPidx(PropIndex))\n    {\n        switch (PropIndex)\n        {\n            case PropertyIndexHelper.PIDX_CheckHealthText:\n                return _physicalPrinter.CheckHealthText;\n\n            case PropertyIndexHelper.PIDX_DeviceDescription:\n                return _physicalPrinter.DeviceDescription;\n\n            case PropertyIndexHelper.PIDX_DeviceName:\n                return _physicalPrinter.DeviceName;\n                                  .\n                                  .\n                                  .\n                                  .\n                                  .	0
20544125	20543962	Share enums between model and view model	.Common	0
2853006	2841893	Do I have to refresh a LINQ object that represents a view/table row after I do a submitchanges operation that may alter it?	try\n{\n_event.someproperty = "that";\nDataContext.SubmitChanges();\n}\n\ncatch (ChangeConflictException e)\n{\n    foreach (ObjectChangeConflict occ in db.ChangeConflicts)\n    {\n        // All database values overwrite current values.\n        occ.Resolve(RefreshMode.OverwriteCurrentValues);\n    }\n}	0
15835707	15834826	Is it possible to override a winform panel's padding in c#?	class MyControl : Control {\n    public new Padding Padding {\n        get { return base.Padding; }\n        set {\n            // override value\n            //...\n            base.Padding = value;\n        }\n    }\n}	0
13263270	13263216	Entity IQueryable with page, search and sort	public class PagingList<T> : List<T>\n{\n    public int PageIndex { get; set; }\n    public int PageSize { get; set; }\n    public int TotalCount { get; set; }\n    public int TotalPages { get; set; }\n    public string pagerange { get; set; }\n    public int pagingrange { get; set; }\n\n    public PagingList(IQueryable<T> data, int page, int pagesize)\n    {\n        PageIndex = page;\n        PageSize = pagesize;\n        TotalCount = data.Count();\n        TotalPages = (int)Math.Ceiling(TotalCount /(double)PageSize);\n\n        this.AddRange(data.Skip(PageIndex * PageSize).Take(PageSize));\n\n    }\n    //public void GeneratePageRange()\n    //{\n    //    for (int i = 1; i <= TotalPages; i++)\n    //    {\n    //        pagingrange = i\n    //    }\n    //}\n    public bool HasPreviousPage\n    {\n        get { return (PageIndex > 0); }\n    }\n\n    public bool HasNextPage\n    {\n        get { return (PageIndex + 1 < TotalPages); }\n    }\n}	0
1230091	1230055	In WPF how do you access an object defined in Window.xaml from a nested user control?	SelectedItem=?{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedValue}?	0
4339232	4339189	Open a WPF Application from a Windows Button click Event	Process process = new Process()	0
1792481	1792459	How can I validate that several textboxes contain data when I click submit?	foreach(Control C in ContainerID.Controls)\n{\n    if ( C is TextBox )\n    {\n      if ( String.IsNullOrEmpty((C as TextBox).Text))\n      {\n          // Do things this way\n      }        \n    }    \n}	0
142819	142813	How do I convert a 12-bit integer to a hexadecimal string in C#?	2748.ToString("X")	0
12431546	12431477	How to compile batch file with resources to exe and run it with its exe in C#?	Process.Create	0
17677164	17677054	how to check if an Input values is empty	if( string.IsNullOrWhiteSpace ( your string; for example : currentusernames[c] ) ) \n {\n    -- do something or throw an exception--\n }   \n\n else\n {\n   -- do something else --\n }	0
12630464	12630429	How can I set default value to size type property of propertyygrid in c#?	[DefaultValue(typeof(Size), "0, 0")]\npublic Size AndaazehPixel { get; set; }	0
10361320	10361246	Download Image file from one URL to another server	WebClient wc = new WebClient;\nwc.DownloadFile("http://www.site.com/image.jpg", \n                 Server.MapPath("~\images\image.jpg"));	0
14172796	14172682	How to call a function that returns an array from a webservice?	public String[] GetAppSections(bool wcoloumn,string coloumn)\n{\nstring[] foo = webs.GetSection(true, "id", false).OfType<object>().Select(o => o.ToString()).ToArray();\nreturn foo\n}	0
16289381	16287838	HtmlAgilityPack - Remove child nodes but retain inner text for the main node without XPath	public static class HtmlHelper\n{\n    public static string InnerText(this HtmlNode node)\n    {\n        var sb = new StringBuilder();\n        foreach (var x in node.ChildNodes)\n        {\n            if (x.NodeType == HtmlNodeType.Text)\n                sb.Append(x.InnerText);\n\n            if (x.NodeType == HtmlNodeType.Element && x.Name == "br")\n                sb.AppendLine();\n        }\n\n        return sb.ToString();\n    }\n}	0
5799519	5799455	page redirection on other website with query string	Response.Redirect("URL",false);\n\nResponse.Redirect(ConfigurationManager.AppSettings["website B"] + "/Content/CaseProps.aspx?CaseId=" + geturl(CaseId.ToString()), false);	0
19416649	19416606	Setting a string equal to the lines of a .txt file	string[] contactInfo = File.ReadAllLines(currentselection);\n\nContactinformation.ContactName = contactInfo[0];\nContactinformation.ContactCell = contactInfo[1];\n.\n.\n.\n.\n.	0
17314993	17314640	Error in comparing DateTime	var searchResult = new PagedData<SAMPLE_STOCK>\n{\n    Data = _db.SAMPLE_STOCK.AsEnumrable().Where(m => m.LAST_UPDATED.Date == lastUpdate.Date)\n};\nreturn PartialView(searcReasult);	0
30937521	30936885	Splitting strings with a regex	var theListOfString = yourInputString.Split(new[] { "  ", ":" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList();\ntheListOfString[0] = theListOfString[0].Substring(0, theListOfString[0].IndexOf("(") - 1);	0
16464669	16460292	Draw on Panel, save as Bitmap	public partial class Form1 : Form {\n  Bitmap bmap;\n\n  public Form1() {\n    InitializeComponent();\n\n    bmap = new Bitmap(panel1.ClientWidth, panel1.ClientHeight);\n    panel1.MouseDown += panel1_MouseDown;\n    panel1.Paint += panel1_Paint;\n  }\n\n  void panel1_Paint(object sender, PaintEventArgs e) {\n    e.Graphics.DrawImage(bmap, Point.Empty);\n  }\n\n  void panel1_MouseDown(object sender, MouseEventArgs e) {\n    using (Graphics g = Graphics.FromImage(bmap)) {\n      g.FillEllipse(Brushes.Black, e.X, e.Y, 10, 10);\n    }\n    panel1.Invalidate();\n  }\n\n  private void clearToolStripMenuItem_Click(object sender, EventArgs e) {\n    using (Graphics g = Graphics.FromImage(bmap)) {\n      g.Clear(Color.White);\n    }\n    panel1.Invalidate();\n  }\n\n  private void saveToolStripMenuItem_Click(object sender, EventArgs e) {\n    bmap.Save(@"c:\temp\bmap.bmp");\n  }\n}	0
8344630	8344345	Programmatically bind an ObservableCollection to a ListBox	public partial class MainWindow : Window\n{\n    public ObservableCollection<string> MyCollection { get; set; }\n\n    public MainWindow()\n    {\n        InitializeComponent();\n        MyCollection = new ObservableCollection<string>();\n\n        Random random = new Random();\n        DispatcherTimer aTimer = new DispatcherTimer();\n        aTimer.Tick += (sender, e) =>\n        {\n            MyCollection.Add(random.Next(0, 100).ToString());\n        };\n        aTimer.Interval = new TimeSpan(0,0,0,0,500);\n        aTimer.Start();\n\n        Binding myBinding2 = new Binding();\n        myBinding2.Source = this;\n        myBinding2.Path = new PropertyPath("MyCollection");\n        ListBoxx.SetBinding(ListBox.ItemsSourceProperty, myBinding2);\n    }\n}	0
13670407	13670399	Is it safe to assume DayOfWeek's numeric value?	public enum DayOfWeek\n{\n    Friday = 5,\n    Monday = 1,\n    Saturday = 6,\n    Sunday = 0,\n    Thursday = 4,\n    Tuesday = 2,\n    Wednesday = 3\n}	0
22681731	22681699	How to hide the Notification Bar on the top of screen in windows phone 8	xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"\nShell:SystemTray.IsVisiable="False" (Or true to display the tray)\nShell:SystemTray.BackgroundColor="Transparent"	0
34103516	34103266	How to insert datagridview record into mysql database using foreach	row.IsNewRow	0
26533712	26533674	How can i make my regular expression work?	"/id/.+"	0
14400365	14359777	Dynamic Fontsize for TextBlock with wrapping	private void MyTextBlock_SizeChanged(object sender, SizeChangedEventArgs e)\n{\n    double desiredHeight = 80; // Here you'll write the height you want the text to use\n\n    if (this.MyTextBlock.ActualHeight > desiredHeight)\n    {\n        // You want to know, how many times bigger the actual height is, than what you want to have.\n        // The reason for Math.Sqrt() is explained below in the text.\n        double fontsizeMultiplier = Math.Sqrt(desiredHeight / this.MyTextBlock.ActualHeight);\n\n        // Math.Floor() can be omitted in the next line if you don't want a very tall and narrow TextBox.\n        this.MyTextBlock.FontSize = Math.Floor(this.MyTextBlock.FontSize * fontsizeMultiplier);\n    }\n\n    this.MyTextBlock.Height = desiredHeight; // ActualHeight will be changed if the text is too big, after the text was resized, but in the end you want the box to be as big as the desiredHeight.\n}	0
29790595	29790413	How to host asp.net application with ms access database?	connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\MyProject\Data\MyDB.accdb;" providerName="System.Data.OleDb"	0
22959080	21576449	How to dismiss all WPF menus, popups, etc. by DevExpress programmatically to get around WindowsFormsHost related issue?	MainWindow.Instance.BarManager.CloseAllPopups();	0
2885475	2885436	Conditionaly strip the last line from a text file	//Delete the last line from the file.  This line could be 8174, 10000, or anything.  This is from SO \n        string tempfile = @"C:\junk_temp.txt"; \n\n        using (StreamReader reader2 = new StreamReader(newfilename)) \n        { \n            using (StreamWriter writer2 = new StreamWriter(tempfile)) \n            { \n                string line = reader2.ReadLine(); \n\n                while (!reader2.EndOfStream) \n                { \n                    writer2.WriteLine(line); \n                    line = reader2.ReadLine(); \n                } // by reading ahead, will not write last line to file  \n\n                // If the last line read does not match your condition\n                // we write it to the new file\n                if (!Regex.IsMatch(line, @"^\d{4,5}$"))\n                {\n                    writer2.WriteLine(line); \n                } \n            } \n        } \n\n        File.Delete(newfilename); \n        File.Move(tempfile, newfilename); \n        File.Delete(tempfile);	0
6272960	6272946	Rectangles in StackPanel	var list = new List<Rectangle>();\nfor (int i = 0; i < 10; i++)\n{\n    list.Add(new Rectangle());\n}\n\nvar panel = new StackPanel();\nforeach (var rectangle in list)\n{\n    panel.Children.Add(rectangle);\n}	0
10327365	10327338	Displaying Data after reading from text file - C#,Visual Studio	DataTable table = new DataTable();\n        table.Columns.Add("Name", typeof(string));\n        table.Columns.Add("Address", typeof(string));\n        table.Columns.Add("Postcode", typeof(string));\n        table.Columns.Add("PhoneNumber", typeof(string));\n        table.Rows.Add("Matt", "15 The", "PO30 78", "088997655");\n        dataGridView1.DataSource = table;\n        dataGridView1.DataBind();	0
19141713	19141612	Parse through XML	var m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";\nstring xmlStr;\nusing(var wc = new WebClient())\n{\n    xmlStr = wc.DownloadString(m_strFilePath);\n}\nvar doc= new XmlDocument();\ndoc.LoadXml(xmlStr);\n\n    XmlNodeList xmllist = doc.SelectNodes("//property");\n       processList( xmllist );\n\n\n    public void processList(XmlNodeList xmllist)\n        {\n            // Loop through each property node and list the information\n            foreach (XmlNode node in xmllist)\n            {\n                XmlElement nodeElement = (XmlElement)node;\n                txtBox.AppendText(nodeElement.SelectSingleNode("name").InnerText);\n                txtBox.AppendText(nodeElement.SelectSingleNode("phone").InnerText);\n            }\n        }	0
22400072	22399895	Saving file from online path in asp.net using C#	static void Main(string[] args)\n{\n    using(WebClient client = new WebClient())\n    {\n        byte[] data = client.DownloadData("http://maps.googleapis.com/maps/api/staticmap?center=34.08326024943277,74.79841209948063&zoom=21&size=550x450&maptype=roadmap&sensor=true");\n        File.WriteAllBytes(@"D:\file.jpg", data);\n    }\n}	0
18559698	18559679	How to add an item to the top of a ListBox	myListbox.Items.Insert(0, myItem);	0
9366598	9366552	Bind a List from a Database to a ComboBox Controls collection?	comboBox1.DataSource	0
20641590	20641511	Naming Convention - Method name for getting data	public DataTable GetCustomerTable() {\npublic List<Customer> GetCustomers() {\npublic DataSet GetCustomerDataSet() {\n\npublic Customer GetCustomer(int id) {\n// I'd question whether these really belong at all...\npublic DataTable GetCustomerAsTable(int id) { \npublic DataSet GetCustomerAsDataSet(int id) {	0
25999180	25869595	Telerik, RadSplitButton ignores BackgroundImage property	radSplitButton1.DropDownButtonElement.ActionButton.ButtonFillElement.Visibility = ElementVisibility.Collapsed;\nradSplitButton1.DropDownButtonElement.ArrowButton.Fill.Visibility = ElementVisibility.Collapsed;\nradSplitButton1.DropDownButtonElement.ButtonSeparator.DrawBorder = false;	0
17433577	17433089	Profile ADO.NET statements without access to SQL Server Profiler	c.CreateCommand	0
2743268	2743260	Is it possible to write to the console in colour in .NET?	Console.BackgroundColor = ConsoleColor.Blue;\nConsole.ForegroundColor = ConsoleColor.White;\nConsole.WriteLine("White on blue.");	0
16381753	16373023	How can I have multiple handlers in same ProcessRequest method?	myipaddress/RestWebService/{entity}?id=1\nThis at run time can cater to both type of request\n\nmyipaddress/RestWebService/employee?id=1\nmyipaddress/RestWebService/company?id=1	0
1941054	1941040	Query with multiple wheres	foreach( var keyword in keywords )\n{\n    var kwd = keyword;\n    stories = from story in stories where story.Name.Contains ( kwd ) );\n}	0
7581854	7581801	How can I hide my password in my C# Connection string?	Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}	0
8925190	8917015	Post JSON data to an asp.net application	Stream s = Request.InputStream; \nStreamReader sr = new StreamReader(s); \nNewtonsoft.Json.Linq.JObject jObj = Newtonsoft.Json.Linq.JObject.Parse(sr.ReadLine()); \nstring name = (string)jObj["name"];	0
11372679	11372644	How can I do take a substring and length of a string in C# if that string might be a null?	int length = (temp ?? "").Length;\nstring subString = "";\nif(length == 8 || length == 10)\n{\n   subString = temp.Substring(length - 4);\n}	0
11288907	11288835	Linq with anonymous methods	listOfStrings.Where(...)	0
9529397	9529183	Assign Short-cut Key(s) to button in WPF	DeleteRow.InputGestures.Add(new KeyGesture(Key.Delete));	0
5868385	5867657	Copying from BitmapSource to WritableBitmap	BitmapSource source = sourceImage.Source as BitmapSource;\n\n// Calculate stride of source\nint stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);\n\n// Create data array to hold source pixel data\nbyte[] data = new byte[stride * source.PixelHeight];\n\n// Copy source image pixels to the data array\nsource.CopyPixels(data, stride, 0);\n\n// Create WriteableBitmap to copy the pixel data to.      \nWriteableBitmap target = new WriteableBitmap(\n  source.PixelWidth, \n  source.PixelHeight, \n  source.DpiX, source.DpiY, \n  source.Format, null);\n\n// Write the pixel data to the WriteableBitmap.\ntarget.WritePixels(\n  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), \n  data, stride, 0);\n\n// Set the WriteableBitmap as the source for the <Image> element \n// in XAML so you can see the result of the copy\ntargetImage.Source = target;	0
11617431	11617377	Getting the difference of two DateTime instances in milliseconds	DateTime a = ...\n        DateTime b = ...\n        var ms = a.Subtract(b).TotalMilliseconds;	0
14957991	14957925	Sending characters and PC number over local network	var tcpClient = new TcpClient();\ntcpClient.Connect("server host", server_port);\nvar streamReader = new StreamReader(tcpClient.GetStream());\nwhile (true)\n{\n    var letter = (char)streamReader.Read();\n    if (letter == 'a')\n    {\n        // ...\n    }\n    else if (letter == 'b')\n    {\n        // ...\n    }\n}	0
666458	666385	How can I convert extended ascii to a System.String?	var e = Encoding.GetEncoding("iso-8859-1");\nvar s = e.GetString(new byte[] { 189 });	0
22052154	22052054	linq2sql - How to use raw SQL to get a count from DB?	string q = @"SELECT COUNT(f.FILE_ID)\n    FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)\n    INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)\n    WHERE l.EntityId = 123";\n\n   return Context.ExecuteQuery<Int32>(q).FirstOrDefault();	0
11842624	11842405	Resizing big arrays	byte[] myOriginalArray = new byte[2GB]; // previously allocated \n\nbyte[] myExtensionArray = new byte[1GB]; // 50% of the original\nfor(... my processing code of the array ...)\n{\n  byte value = read(index);\n  ... process the index and the value here\n  store(index, value);\n}\n\nbyte read(int index)\n{\n  if(index < 2GB) return myOriginalArray[index];\n  return myExtensionArray[index - 2GB];\n}\n\nvoid store(int index, byte value)\n{\n   if(index < 2GB) myOriginalArray[index] = value;\n   myExtensionArray[index - 2GB] = value;\n}	0
28960336	28893745	Moving a sprite body causes jitter	Application.targetFrameRate = 60;	0
14253092	14253075	Splitting an string into a string array.?	string foo = "a,b,c";\n\nstring [] foos = foo.Split(new char [] {','});\n\nforeach(var item in foos)\n{\n   Console.WriteLine(item);\n}	0
17401566	17399909	How do I make a TypeConverter known to an assembly that is called from a COM library?	AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n    {\n        if (args.Name == Assembly.GetAssembly(typeof(ComLib)).FullName) // adapt to your needs\n            return Assembly.GetAssembly(typeof(ComLib));\n\n        return null;\n    };	0
32969182	32968954	Use two Key Events one after another in C#	TextBox target;\nprivate void Form1_KeyUp(object sender, KeyEventArgs e)\n{\n\n    if (e.KeyCode == Keys.A)\n    {\n        target = textBox1;\n    }\n\n    if (e.KeyCode == Keys.B)\n    {\n        target = textBox2;\n    }\n\n    if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)\n    {\n        if(target != null)\n        {\n            int vA = int.Parse(target.Text);\n            vA += 5;\n            target.Text = (String)vA.ToString();\n        }\n    }\n}	0
19716486	19716349	How to write Outer Join using LINQ	var q = from row in TableCCY1.AsEnumerable().Concat(TableCCY2.AsEnumerable())\n        group row by new\n        {\n            CCY1 = row.Field<string>("CCY1"),\n            PCode = row.Field<string>("PCODE")\n        } into matches\n        select new\n        {\n            CCY1 = matches.Key.CCY1,\n            PCODE = matches.Key.PCode,\n            Sum = matches.Sum(match => match.Field<decimal?>("AMT2")),\n        };	0
19379608	19360133	How to serialize object to json with type info using Newtonsoft.Json?	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) \n    var converters = serializer.Converters.Where(x => !(x is TypeInfoConverter)).ToArray();\n\n    var jObject = JObject.FromObject(value);\n    jObject.AddFirst(new JProperty("Type", value.GetType().Name));\n    jObject.WriteTo(writer, converters);\n}	0
25215548	25215518	how to write this in sql query to linq	var res= from c in Category\n                    join\n                        s in SubCategory on c.id equals s.cid\n                    select c;	0
2265429	2265412	Set timeout to an operation	using System.Threading;\n\nclass Program {\n    static void DoSomething() {\n        try {\n            // your call here...\n            obj.PerformInitTransaction();         \n        } catch (ThreadAbortException) {\n            // cleanup code, if needed...\n        }\n    }\n\n    public static void Main(params string[] args) {\n\n        Thread t = new Thread(DoSomething);\n        t.Start();\n        if (!t.Join(TimeSpan.FromSeconds(30))) {\n            t.Abort();\n            throw new Exception("More than 30 secs.");\n        }\n    }\n}	0
10298748	10297830	Generate a workflow service programmatically	Body = new Sequence()\n{\n  Activities = {\n   reserveSeat,\n   flowchar\n  }\n}	0
10517732	10517567	Download Files From Resource Library in c# .net	class ResourceHelper\n    {\n           public static void MakeFileOutOfAStream(string stream, string filePath)\n            {\n                using(var fs = new FileStream(filePath,FileMode.Create,FileAccess.ReadWrite))\n                {\n                    CopyStream(GetStream(stream), fs);\n                }\n            }\n\n            static void CopyStream(Stream input, Stream output)\n            {\n                byte[] buffer = new byte[32768];\n                int read;\n                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n                {\n                    output.Write(buffer, 0, read);\n                }\n            }\n static Stream GetStream(string stream)\n        {\n             return Assembly.GetExecutingAssembly().GetManifestResourceStream(stream));\n\n        }\n    }	0
25087383	25087266	Finding the distinct values of a dictionary	var newDict = dict.ToDictionary(\n                    x=>x.Key, \n                    v=>v.Value.GroupBy(x=>new{x.PayToStr1, x.PayToStr2, x.PayToCity, x.PayToState})\n                              .Select(x=>x.First())\n                              .ToList());	0
4676288	4652600	Silverlight 4, Ria Services, HttpRequestTimedOutWithoutDetail	((WebDomainClient<RealFormsContext.IRealFormsServiceContract>)Context.DomainClient)\n   .ChannelFactory.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 10, 0);	0
30602576	30532308	Castle Windsor / ActiveRecord / NHibernate: How to intercept/modify connection string	ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();\nNHibernate.Cfg.Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));\nconnectionString = ReadConnectionString();\nconfiguration.SetProperty("connection.connection_string", connectionString);	0
4780963	4780881	C# Method that executes a given Method	void Main()\n{\n    Func<int> m1=()=>1;\n    Console.WriteLine(A(m1));\n\n    Func<int,int> m2=i=>i;\n    Console.WriteLine(A(m2,55));\n}\n\nobject A(Delegate B,params object[] args)\n{\n\n    return B.Method.Invoke(B.Target,args);\n}	0
20105511	20105246	Retrieve a float from database and adding to local variable	samplerate = Convert.ToSingle(rdr["samplerate_hz"]);	0
4975343	4975236	How to Convert Twitter Timestamp to DateTime?	const string format = "ddd MMM dd HH:mm:ss zzzz yyyy";\nmy_date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);	0
16574171	16574035	Build simple map to my game c#	carCoordOnMap.x = carWorldPosition.x / (world_screen_width / map_screen_width);\ncarCoordOnMap.y = carWorldPosition.y / (world_screen_height / map_screen_height);	0
1688677	1688603	How can I create an instance of an object defined in my App.Config without having a reference to the assembly in my project?	System.Reflection.Assembly.Load("PrototypePlugins");	0
9704967	9704515	match inside a match	String text = "data1:abc,123,xyz,data2:hello,goodbye";\nRegex reg = new Regex(@"(?<=data1:.*)[^,]+(?=.*data2)");\n\nMatchCollection result = reg.Matches(text);\n\nforeach (var item in result) {\n    Console.WriteLine(item.ToString());\n}	0
22618601	22618417	How to convert string , date, time, byte into bitarray in C#	public static byte[] ToByteArray(object obj)\n{\n    int len = Marshal.SizeOf(obj);\n    byte[] arr = new byte[len];\n    IntPtr ptr = Marshal.AllocHGlobal(len);\n    Marshal.StructureToPtr(obj, ptr, true);\n    Marshal.Copy(ptr, arr, 0, len);\n    Marshal.FreeHGlobal(ptr);\n    return arr;\n}	0
18288056	18285766	Grab inner text from HTML that isn't from a header	string[] tagsToRemove = { "h1", "h2", "h3", h4", "h5", "h6" };\nList<string> tagsToRemoveList = tagsToRemove.ToList();\ndoc.DocumentNode.Descendants()\n    .Where(n => tagsToRemoveList.Contains(n..Name.ToLowerCase()))\n    .ToList()\n    .ForEach(n => n.Remove());	0
10073714	10073644	RegularExpression attribute with Enum	[Range(SomeValue, LastValue)]	0
6417836	6417516	C# - Getting ManagementObjectSearcher to output to a TextBox	var query = new ManagementObjectSearcher("SELECT * FROM Win32_ScheduledJob");\n        var tasks = query.Get();\n        foreach (ManagementObject task in tasks)\n        {\n            richTextBox6.Text += Environment.NewLine + task["Description"]\n        }	0
26473817	26473581	adding button to each row in gridview that has a drop down menu	AutoGenerateDeleteButton="True"\nAutoGenerateEditButton="True"	0
34328869	34327889	2D Vector based Ai movement	GameObject player_tran = GameObject.Find ("player");\ndouble dx = 0;\ndouble dy = 0;\nif (transform.position.x > player_tran.transform.position.x)\n    dx = -1;\n} else {\n    dx = 1;\n}\n\nif (transform.position.y > player_tran.transform.position.y) {\n    dy = -1;\n} else {\n    dy = 1;\n}\ntransform.position += new Vector(dx, dy, 0);	0
18827216	18827081	C# Base64 String to JPEG Image	var bytes = Convert.FromBase64String(resizeImage.Content);\nusing (var imageFile = new FileStream(filePath, FileMode.Create))\n{\n    imageFile.Write(bytes ,0, bytes.Length);\n    imageFile.Flush();\n}	0
27170833	27170682	How do I extract and replace a substring with a different value	string input = "Using the following data [EnvironmentVar][TestAccount] status is connected";\nstring newData = "UKUser";\nstring output = Regex.Replace(input, @"(\[.*\])", newData);\nConsole.WriteLine(output);  // Using the following data UKUser status is connected	0
686620	686601	Constructor chaining with multiple calls	internal WebTestingApp(Result result, BrowserApp browserApp, IRemoteFile remoteFile, IWebServiceGateway webServiceGateway) : base(remoteFile, webServiceGateway)\n{\n    // Set readonly vars here\n}\n\npublic WebTestingApp(Result result, BrowserApp browserApp) : this(result, browserApp, S3File.Instance, WebServiceGateway.Instance)\n{\n}	0
20068821	20068732	String of bytes to byte array c#	public byte[] DownloadReport(string id, string fileName)\n    {\n        var fileAsString = _api.DownloadReport(id, fileName);\n        byte[] report = Convert.FromBase64String(fileAsString);\n        return report;\n    }	0
2767090	2767017	Passing static parameters to a class	class Foo \n{ \n  private int bar; \n  private static Foo _foo;\n\n  private Foo() {}\n\n  static Foo Create(int initialBar) \n  { \n    _foo = new Foo();\n    _foo.bar = initialBar; \n    return _foo;\n  } \n\n  private int quux; \n  public void Fn1() {} \n}	0
26536753	26536417	Text Box Height & Width	float accesswidth = 5.1667f;\nfloat accessheight = 1.667f;\nGraphics graphics = Graphics.FromHwnd(IntPtr.Zero);\nfloat csharpwidth = accesswidth * graphics.DpiX;\nfloat csharpheight = accessheight * graphics.DpiY;\nMessageBox.Show(string.Format("width: {0}, height: {1}", \n                               csharpwidth.ToString(),\n                               csharpheight.ToString()));	0
17731773	17725379	.NET / Oracle: How to execute a script with DDL statements programmatically	execute immediate	0
34374702	34373686	style binding attached property didn't show up	Path=(local:HotButtonAttached.HotStr)	0
24887593	24879961	AutoMapper IDataReader Mapping default value to entity	AutoMapper.Mapper.CreateMap<IDataReader, Booking>().ForMember(d => d.Days, opt => opt.UseValue(2));	0
19440342	19355659	Print a different view as the current one in Infopath GUI, using C# in the VSTA environment	ViewInfos.SwitchView("view name");	0
13405292	13405159	C# Linq To Xml - How do Select collection of elements and modify each using lambda?	xhtml.Root.Descendants()\n            .Where(e => e.Attribute("documentref") != null)\n            .ToList()\n            .ForEach(e => e.Add( new.... ) );	0
8285884	8285862	C# referencing static field with like-named local variable	public Example(String Name, DateTime referenceInstance) {\n this.Name=Name;\n Example.referenceInstance=referenceInstance;\n}	0
9376617	9376462	how to insert data in particular column of table?	create procedure SP_IsBlocked\n(\n@Employee_Id int,\n@IsBlocked varchar (50)\n)\nas \nbegin\n update PTS_Employee \n set Emp_IsBlocked = @IsBlocked \n where id = @Employee_Id\nend	0
24406632	24406141	set datasource for AutoCompleteStringCollection	AutoCompleteStringCollection data = new AutoCompleteStringCollection();\n            data.AddRange(objmemberRepository.GetAll().Select(i => i.username).ToArray());	0
25446674	25384855	How to format the rad grid string column?	public static string SsnInjectDashes(string ssn)\n            {\n                if (ssn == null)\n                {\n                    return String.Empty;\n                }\n                string value = ssn;\n                Regex re = new Regex(@"(\d\d\d)(\d\d)(\d\d\d\d)");\n                if (re.IsMatch(ssn))\n                {\n                    Match match = re.Match(ssn);\n                    value = match.Groups[1] + "-" + match.Groups[2] + "-" + match.Groups[3];\n                }\n                return value;\n            }	0
30328336	30108229	Access objects within a Consumer	x.Subscribe<UpdatedInformationConsumer>(() => \n    new UpdatedInformationConsumer(dependency1, dependency2, etc));	0
6511661	6511181	Intersect method in LINQ with C#	class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>\n    {\n\n        public FileCompare() { }\n\n        public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)\n        {\n            return (f1.Name == f2.Name && f1.Directory.Name == f2.Directory.Name && \n                    f1.Length == f2.Length);\n        }\n\n        // Return a hash that reflects the comparison criteria. According to the \n        // rules for IEqualityComparer<T>, if Equals is true, then the hash codes must\n        // also be equal. Because equality as defined here is a simple value equality, not\n        // reference identity, it is possible that two or more objects will produce the same\n        // hash code.\n        public int GetHashCode(System.IO.FileInfo fi)\n        {\n            string s = String.Format("{0}{1}", fi.Name, fi.Length);\n            return s.GetHashCode();\n        }\n\n    }	0
14795305	14795270	Simple Linq to Xml Queries setting Properties with Elements (instead of IEnumerable)	var serverStatus = (bool?)doc.XPathSelectElement("/eveapi/result/serverOpen");\nvar onlinePlayers = (int?)doc.XPathSelectElement("/eveapi/result/onlinePlayers");	0
25027044	25026999	How to move instantiated prefab in Unity?	GameObject myNewInstance = (GameObject) Instantiate(instance, transform.position, transform.rotation);\n myNewInstance.transform.localPosition = new Vector3(0.0f, 0.0f, 5.0f);	0
18455200	18454917	find duplicate columns and replace matches with count	Regex rgx = new Regex("(?<=\\t|^)(" + fieldName + ")(\\t)+");	0
30191809	30191667	How to fill string with repeating it characters by text length?	private string XorText(string text,string key)\n {\n      string newText = "";\n      for (int i = 0; i < text.Length; i++)\n      {\n          int charValue = Convert.ToInt32(text[i]);\n          int keyValue = Convert.ToInt32(key[i % key.Length]);\n          charValue ^= keyValue % 33;\n          newText += char.ConvertFromUtf32(charValue);\n      }\n      return newText;\n  }	0
11887290	11887113	Any harm in changing a void return type to something else in a commonly used utility function?	Action a = usefulUtility;	0
28075725	28075195	Terminology - does declaring methods in different namespaces count as overloading	public class Math2\n{\n // This one's for squares\n public static double Area(double side)\n {\n  return side * side; \n }\n\n // This one's for rectangles\n public static double Area(double length, double height)\n {\n  return length * height; \n }\n}	0
1253527	1253454	Programmatically generate decision table in C#?	int conditions = 3;\nfor (int c = 0; c < conditions; c++) {\n    Console.WriteLine(\n       "Condition {0} : {1}",\n       (char)('A' + c),\n       new String(\n          Enumerable.Range(0, (1 << conditions))\n          .Select(n => "TF"[(n >> c) & 1])\n          .ToArray()\n       )\n    );\n}	0
22181336	22181286	Genric object return from Interface	interface ITest<T>\n{\n    T GetObject();\n}\n\npublic class Test1 : ITest<Logger>\n{\n    public Logger GetObject()\n    {\n        return new Logger();\n    }\n}	0
12161281	12158897	C# - DataGridView - always display TopLeftHeaderCell	dataGridView1.Columns.Add("dummyheader", "Dummy");\n        dataGridView1.Columns[0].Visible = false;	0
19754758	19754233	Combine two events into IObservable	/* Assume you have an instance of ITask here */\nITask task;\n\nvar updates = Observable.FromEventPattern<UpdateEventArgs>(task, "Update");\nvar completed = Observable.FromEventPattern<EventArgs>(task, "Completed");\n\nvar desiredStream = updates.TakeUntil(completed);\n\n/* example usage */\ndesiredStream.Subscribe(Console.WriteLine,\n                        () => Console.WriteLine("Done"));	0
32839679	32839632	Figuring out this date format	DateTime dateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);\ndateTime = dateTime.AddSeconds(yourUnixTimestampValue).ToLocalTime();	0
29174749	29114870	Get the latest entered word in textbox Windows phone 8	Bool isFirst = false;\nint mytempindex;\n private async void mytxt_KeyUp_1(object sender, KeyRoutedEventArgs e)\n    {  \n      if (e.Key == Windows.System.VirtualKey.Space)\n        {\n          int i = mytxt.SelectionStart;\n          if (i < mytxt.Text.Length)\n          {\n            if (isfirst == false)\n             { \n                mytempindex = mytxt.SelectionStart;\n                isfirst = true;\n             }\n            else\n             {\n                int mycurrent_index = mytxt.SelectionStart;\n                        int templength_index = mycurrent_index - mytempindex;\n                string word = mytxt.Text.Substring(mytempindex, templength_index); //It is the latest entered word.\n               //work with your last word.\n             }\n          }\n       }\n   }	0
8567748	8567496	Implementing inherited abstract member with generic	class B<T>\n{\n  public virtual void M(T t) {}\n  public virtual void M(int x) {}\n}\nclass D : B<int>\n{\n  public override void M(int x) {}\n}	0
15340901	15340791	How to reconstruct return type object in web api	response.Content.ReadAsAsync<GrantAccessResponse>()	0
17656129	17656101	How to generate a unique code in C#?	System.Guid.NewGuid().ToString();	0
15107732	15105914	Displaying data entered in one form to another form	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;\n\nnamespace cities\n{\n    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\n\n\n            StringBuilder message = new StringBuilder();\n\n\n            foreach (object selectedItem in listBox1.SelectedItems)\n            {\n               message.Append(selectedItem.ToString() + Environment.NewLine);\n            }\n            MessageBox.Show("Your Selected Cities :\n" + message.ToString() + "\n");\n\n            Form2 childForm = new Form2();\n            childForm.Controls["richTextBox1"].Text = message.ToString();\n            childForm.Show();\n        }\n\n        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n        {\n        }\n\n    }\n}	0
5760974	5760904	linqToSql + linqToXMl - backup table in xml file	List<XElement> list = new List<XElement>() { new XElement("first"), new XElement("Second") };\n        XElement root = new XElement("root", list);\n        XDocument doc = new XDocument();\n        doc.Add(root);  // add it later to prevent the error mentioned below.\n        doc.Save(Console.Out); // put in here the file name or Console.Out to see the contents directly in your window.	0
1774449	1774291	How do I parse a CREATEPENINDIRECT metafile record out of a byte array?	byte[] buffer;\nint style = BitConverter.ToUInt16(buffer, 0);\nint width = BitConverter.ToUInt16(buffer, 2);\nvar color = Color.FromArgb(buffer[4], buffer[5], buffer[6]);\nvar pen   = new Pen(color, width)\n            {\n                DashStyle = ..., // set style\n                StartCap = ...,\n                EndCap = ...\n            };	0
28880059	28878830	Query with case statement from SQL Server to Linq query c#	var result = fulltableData.Where(x=>x.date_reception > '01-01-2015')\n            .GroupBy(x=> x.mc_owner.Equals("Element1")?"Element1":"others")\n            .Select(x=> new{ nbr = x.Count(), Owner = x.Key})\n            .OrderByDescending(x=>x.nbr);	0
2417400	2417191	Get sequence of selection of items in listbox control in c#	protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n       List<ListItem> list = new List<ListItem>();\n       list.Add(ListBox1.SelectedItem);\n       string testValue = list[0].Value; // this is how you access a listitem in the List\n    }	0
21334859	21334785	Truncating decimal number to one decimal digit	var number = 25.9877;\n var rounded = Convert.ToDouble(Convert.ToInt32(number*10))/10;	0
30770873	30409859	Deserializing to a subclass problems	[XmlRoot("Shape")]\npublic class Rectangle : Shape\n{ .. }	0
25846257	25844791	How to convert XML to nested Dictionary using Linq to XML?	org => org.dep.ToDictionary(dep => dep.Name, dep => dep.DatSet)	0
7168032	7167070	Centering a canvas on a given point	private void UpdateCanvas(Point mousePoint)\n{\n  int canvasWidth = (int)(_bitmap.Width * _zoomRatio);\n  int canvasHeight = (int)(_bitmap.Height * _zoomRatio);\n  int canvasX = (mousePoint.X - (canvasWidth / 2));\n  int canvasY = (mousePoint.Y - (canvasHeight / 2));\n  CanvasBounds = new Rectangle(canvasX, canvasY, canvasWidth, canvasHeight);\n}	0
2098164	2096425	How to check if a exe is accessed from the server	function IsFileInUse(fName: string): boolean;\n  var\n    HFileRes: HFILE;\n  begin\n    Result := false;\n    if not FileExists(fName) then\n      exit;\n    HFileRes := CreateFile(pchar(fName),\n      GENERIC_READ or GENERIC_WRITE,\n      0, nil, OPEN_EXISTING,\n      FILE_ATTRIBUTE_NORMAL,\n      0);\n    Result := (HFileRes = INVALID_HANDLE_VALUE);\n    if not Result then\n      CloseHandle(HFileRes);\n  end;	0
7353832	7353758	How do you publish a C# Windows app with Font Files correctly?	Fonts Folder	0
1003010	1002937	C# Regex Split To Java Pattern split	public String[] split(String text) {\n    if (text == null) {\n        text = "";\n    }\n\n    int last_match = 0;\n    LinkedList<String> splitted = new LinkedList<String>();\n\n    Matcher m = this.pattern.matcher(text);\n\n    // Iterate trough each match\n    while (m.find()) {\n        // Text since last match\n        splitted.add(text.substring(last_match,m.start()));\n\n        // The delimiter itself\n        if (this.keep_delimiters) {\n            splitted.add(m.group());\n        }\n\n        last_match = m.end();\n    }\n    // Trailing text\n    splitted.add(text.substring(last_match));\n\n    return splitted.toArray(new String[splitted.size()]);\n}	0
32956939	32956656	Converting the database 24 hr clock to 12 hr clock	DateTime myDate = new DateTime(2015, 10, 5, 17, 30, 00);\nstring twelveHour = myDate.ToString("h:mm tt"); // 5:30 PM\nstring twentyFourHour = myDate.ToString("HH:mm"); // 17:30	0
3390387	3390288	Getting rid of *consecutive* periods in a filename	string name = "Text...1.txt";   \nRegex r = new Regex("[.][.]+");\nstring result = r.Replace(name, " ");	0
31128910	31128842	EF6 one-to-many fluent api with navigation properties	HasKey(emailTemplate => new { emailTemplate.OperatorId, emailTemplate.MailType, emailTemplate.LanguageId });	0
8414092	8414022	Entring same text to all textboxes while writing in one textbox	private void currencyTextBox_TextChanged(object sender, EventArgs e)\n{\n  textbox1.Text = currencyTextBox.Text;\n  textbox2.Text = currencyTextBox.Text;\n  textbox3.Text = currencyTextBox.Text;\n}	0
714516	714411	Is it possible to create a persistant ODBC connection with C#?	[ODBC]\nDRIVER=SQL Server\nUID=myName\nTrusted_Connection=Yes\nDATABASE=Test\nWSID=ServerName\nAPP=Microsoft Data Access Components\nSERVER=(local)	0
22922094	22921955	Generic Enum parser with some exception rule	return (T)(object)A.AA;	0
7794327	7794181	Find Closest next hour	string result = hours.First(x => TimeSpan.Parse(x) >= TimeSpan.Parse(target));	0
6107304	6106956	How get current CultureInfo in wrapper class?	return (CultureInfo)HttpContext.Current.Session["MyCulture"];	0
4959769	4959715	Parse single XML statement in string	string x = "<Vol Model_Type=\"Flat\">102.14</Vol>";\nXElement element = XElement.Parse(x);\ndecimal value = (decimal) element;	0
3679346	3679287	Updating DataTable bound to ASP.Net DataGrid	DataTable dt = DataGridUsers.DataSource as DataTable;	0
14611288	14611226	Windows Forms - get Text value from object of type button	private void HandleClick(object sender, EventArgs e)\n    {\n        var btn = sender as Button;\n        if (btn != null)\n        {\n            MessageBox.Show(btn.Text);\n        }\n    }	0
2373708	2373680	Recursively finding the lowest level item in C#	public Foo GetLowestLevelFoo(Foo foo)\n    {\n        if (foo.ChildFoo != null)\n        {\n            return GetLowestLevelFoo(foo.ChildFoo);\n        }\n        else\n        {\n            return foo;\n        }\n    }	0
16304327	16304312	How can you retrieve multiple GET variables from a query string?	sampleurl.com/Default.aspx?VariableA=ValueA&VariableB=ValueB	0
4880421	4880236	How can i implement the paging effect in a FlowLayoutPanel control?	FlowPanel.Items.Clear()\nfor(int i = (currentPage-1) * thumbsPerPage; i < (currentPage * thumbsPerPage) - 1; i++)\n   FlowPanel.Controls.Add(Pedits[i])	0
12157764	12153193	Data table to SQL table losing precision	dt= ds.Tables[0].Clone();\nfor (ICol = 0; ICol < ds.Tables[0].Columns.Count; ICol++)\n    dt.Columns[ICol].DataType = typeof(string);\n    foreach (DataRow row in ds.Tables[0].Rows) \n    {\n        dt.ImportRow(row); \n}	0
18752831	18727965	Outlook Redemption With Embedded Image	RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");\n        RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");\n\n\n         Interop.Redemption.RDOSession session1 = RedemptionLoader.new_RDOSession();\n\n\n        var msg1 = session1.GetMessageFromMsgFile(templatePath);\n\n\n        msg1.Subject = String.Format("Report");\n\n        String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;\n        RDOAttachment Attach = msg1.Attachments.Add(ImageString);\n        Attach.ContentID = "image1";\n        String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";\n\n        msg1.HTMLBody = htb;\n        msg1.Save();\n\n        Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();\n\n\n        var msg = session.GetMessageFromMsgFile(templatePath);\n        msg.SaveAs(newPath);	0
3416351	3416293	c# How to reference a dynamically created component?	CheckBox chkTest = (CheckBox)Controls["chkTest"];\nif(chkTest.Checked) {\n    // ...\n}	0
25310321	25310281	unable to bind data to label inside repeater	Text='<%#Eval("CampCode") %>'	0
23268874	23268539	Regular expression to exclude particular pattern match	\b1\s*[-/\.]?\(?\d{3}\)?\s*[-/\.]?\d{3}[-/\.]?\d{4}(\s+(x|ext)\d{4})?\b	0
19297510	19297407	Using gacutil to install a .dll	gacutil /i "C:\File\path\Office.dll"	0
27116332	27116071	C# - How to save many files to the hard disk until it become full without crashing	var image = GetScreenImage();  // or however you're capturing the screen\ntry\n{\n    image.Save(filename);\n}\ncatch (Exception ex)\n{\n    // handle the exception here.\n}	0
10430669	10430578	Retrieving a date/time value from a Microsoft Access Database	timeList.Add(aReader.GetDateTime(0).ToString());	0
5767676	5767643	How to run my app with privileges for access to _every_ directory?	try\n{\n    Directory.GetFiles(path)\n        .ToList()\n        .ForEach(s => files.Add(s));\n\n    Directory.GetDirectories(path)\n        .ToList()\n        .ForEach(s => AddFiles(s, files));\n}\ncatch (UnauthorizedAccessException ex)\n{\n    // ok, so we are not allowed to dig into that directory. Move on.\n}	0
15976103	15975972	Copy data from from IntPtr to IntPtr	class Program\n{\n    [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]\n    public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);\n\n    static void Main()\n    {\n        const int size = 200;\n        IntPtr memorySource = Marshal.AllocHGlobal(size);\n        IntPtr memoryTarget = Marshal.AllocHGlobal(size);\n\n        CopyMemory(memoryTarget,memorySource,size);\n    }\n}	0
3111737	3111687	Setting MimeType in C#	private string GetMimeType (string fileName)\n{\n    string mimeType = "application/unknown";\n    string ext = System.IO.Path.GetExtension(fileName).ToLower();\n    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);\n    if (regKey != null && regKey.GetValue("Content Type") != null)\n    mimeType = regKey.GetValue("Content Type").ToString();\n    return mimeType;\n}	0
20243643	20221775	Serialize a class containing a list<float[]> using SOAP Edit: list<MyClass>	public void saveXML(string filePath)\n    {\n\n        using (FileStream stream = new FileStream(filePath, FileMode.Create))\n        {\n            XmlSerializer format = new XmlSerializer(typeof(List<MyClass>));\n            format.Serialize(stream, this.postList);\n        }\n\n    }\n\n\n\n    private void readXML(string fileLocation)\n    {\n        using (FileStream stream = new FileStream(fileLocation,FileMode.Open))\n        {\n\n            XmlSerializer format = new XmlSerializer(typeof(List<MyClass>));\n\n            postList = format.Deserialize(stream) as List<MyClass>;\n\n        }\n\n    }	0
10818399	10818229	How can I check if a computer on my network is online?	Ping ping = new Ping();\nPingReply pingReply = ping.Send("ip address here");\n\nif(pingReply.Status == IPStatus.Success)\n{\n   //Machine is alive\n}	0
25450857	25450818	Custom .Replace method that replaces with HTML?	Html.Raw(MyString.Replace("chkbox", "<span class=\"glyphicon glyphicon-check\"></span>"))	0
2326241	2326127	DateTime.TryParse all possible type of dates	string testValue = "10.11.12";\n\nDateTime result;\nCultureInfo ci = CultureInfo.GetCultureInfo("sl-SI");\nstring[] fmts = ci.DateTimeFormat.GetAllDateTimePatterns();\nConsole.WriteLine(String.Join("\r\n", fmts));\nif (DateTime.TryParseExact(testValue, fmts, ci,\n   DateTimeStyles.AssumeLocal, out result))\n{\n   Console.WriteLine(result.ToLongDateString());\n}	0
1222004	1221914	Having a List<T>, how can I get other fields from DB?	var orderNumbers = ... your list ...\n\n using (var dataContext = new OrdersDataContext()) // designer-generated context\n {\n     var orderTitles = dataContext.Orders\n                                  .Where( o => orderNumbers.Contains( o.OrderNumber ) )\n                                  .Select( o => o.OrderTitle );\n\n     ... now do something with the collection...\n }	0
16485457	16485394	Variable changes during Task Start	int iTemp = i;\ntasks[i] = Task.Factory.StartNew(() => {\n        ProcessingTask.run(\n                             iTemp,\n                             stack,\n                             collector,\n                             sets,\n                             cts.Token,\n                             LOG\n                            );\n     },\n     cts.Token,\n     TaskCreationOptions.LongRunning,\n     TaskScheduler.Default\n    );	0
12087979	12087536	Analog of VBA`s FillBLOB in c# while inserting large string into ntext	SqlCommand mySqlCommand_new;\nmySqlCommand_new = SQLConnection.CreateCommand();\nmySqlCommand_new.CommandText = "insert table (column) values(@text)";\nmySqlCommand_new.Parameters.Add(new SqlParameter("@text", SqlDbType.NText));\nmySqlCommand_new.Parameters["@code"].Value = text;\nmySqlCommand_new.ExecuteNonQuery();	0
25158594	25158315	Access canvas name through button click	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    Button btn = (Button)sender;\n    Canvas canvas = ((StackPanel)btn.Content).Children\n                                             .OfType<Canvas>()\n                                             .First();\n    canvas.Children.Clear();\n    //at this point you can also get corresponding `Canvas` name \n    //(if you really have to) :\n    //String name = canvas.Name;\n}	0
6675940	6675889	Linq - doesn't start with any prefix in range of prefixes	// Only call ToList if you need to, of course... but I think EF/LINQ To SQL\n// will need it as a list (or array)\nList<string> prefixes = GetListOfPrefixesFromSomewhere().ToList();\n\nIQueryable<Record> query = GetAllRecordsFromRepository()\n             .Where(x => !prefixes.Any(prefix => x.Field.StartsWith(prefix)));	0
19301363	19301311	C#- Get Control text that created at runtime	var b = this.Controls.OfType<Button>().FirstOrDefault(b => b.Name == "mybtn");\nif (b == null) { return; }\n\nConsole.WriteLine(b.Text);	0
10178470	10178299	Get a randomized aberrancy around given value	Random.Next	0
22061070	22060997	compare two datatables with multiple columns with a unique id	DataTable dtinput = new DataTable();\n        DataTable dtquantity = new DataTable();\n\n        dtinput.Columns.Add("id",typeof(int));\n        dtinput.Rows.Add("2");\n        dtinput.Rows.Add("4");\n        dtinput.Rows.Add("7");\n\n        dtquantity.Columns.Add("id", typeof(int));\n        dtquantity.Columns.Add("qty", typeof(int));\n        dtquantity.Rows.Add("1", "12");\n        dtquantity.Rows.Add("2", "13");\n        dtquantity.Rows.Add("3", "5");\n        dtquantity.Rows.Add("4", "6");\n        dtquantity.Rows.Add("7", null);\n\n        var results = from table1 in dtinput.AsEnumerable()\n                      join table2 in dtquantity.AsEnumerable()\n                      on (int)table1["id"] equals (int)table2["id"]\n                      into outer\n                      from row in outer.DefaultIfEmpty<DataRow>()\n                      select row;\n        DataTable dt = results.CopyToDataTable();	0
17116657	17116629	C# - how to put a string in the middle of the string?	var combined = someString.Insert(startIdx, otherString)	0
9337336	9335352	how to run nAudio on Windows XP?	waveOutDevice = new WaveOut();	0
16397750	16397290	implementing iobservable on dictionary object and assigning key values to XAML elements	public class YourNewClass : INotifyPropertyChanged\n{\n    private string _name;\n    public string Name\n    {\n        get { return _name; }\n        set\n        {\n            _name = value;\n            OnPropertyChanged("Name");\n        }\n    }\n    // Same for other two properties\n}	0
17147521	17147083	How to get multiple elements with same name in a node with XDocument?	var datas = from query in loadedData.Descendants("news")\n                                select new News\n                                {\n                                    Title = (string)query.Element("title"),\n                                    Id = (string)query.Element("id"),\n                                    StrDate = (string)query.Element("date"),\n                                    list = (from xele in query.Descendants("machine")\n                                           select xele.Value).ToList<string>();   \n                                };	0
12597759	12596168	SqlDataAdapter returns unexpected rows in SQL Server 2012	("DELETE FROM #tmp WHERE AccountId IN (SELECT TOP {0} AccountId FROM #tmp);", request.PageStart)\n("SELECT DISTINCT TOP {0} ", request.NumRecords);	0
29923334	29923176	method with optional parameter	.Where( g =>\n  (State.HasValue.Equals(false) || g => g.r.uir.InconsistencyStateId == State) && \n  (Type.HasValue.Equals(false) || g.r.uir.InconsistencyTypeId == Type) &&\n  (StartDate.HasValue.Equals(false) || g.r.uir.InsDate >= StartDate) &&\n  (EnDate.HasValue.Equals(false) || EnDate >= g.r.uir.InsDate)\n)	0
2649750	2648700	Constructing an object and calling a method without assignment in VB.Net	Public Sub DoSomething()\n    Call (New MyHelper()).DoIt()\n    Call New MyHelper().DoIt()\nEnd Sub	0
6440453	6440255	Missing Basic HTTP authentication entry in HTTP request header	string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(un + ":" + pw));\nclient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;	0
18533423	18532157	RTF to HTML, change font-family	string memoValue = inboundSet.Fields["MEMO"].Value.ToString();\nif (RtfTags.IsRtfContent(memoValue))\n{     \n  using (RichEditDocumentServer richServer = new RichEditDocumentServer())\n  {\n    string htmlText = string.Empty;\n    richServer.RtfText = memoValue;\n    CharacterProperties cp = richServer.Document.BeginUpdateCharacters(richServer.Document.Range);\n    cp.FontName = "Arial";\n    cp.FontSize = 12;\n    richServer.Document.EndUpdateCharacters(cp);\n    htmlText = richServer.HtmlText;\n    callDetail.Memo = htmlText;\n   }\n}	0
26617822	9695558	How do I get resizable and sortable columns using a NodeView?	myView.AppendColumn ("Genre", new CellRendererText (), "text", 5).Resizable = true;	0
10281412	10281331	Suitable use of Tuple<>, in a unit test?	Dictionary<string, ErrorCodeDetails>	0
2485003	2484994	How to connect my APP to SQL Server?	Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;InitialCatalog=myDataBase;User ID=myUsername;Password=myPassword;	0
28865507	28865259	Use the same lambda parameter across multiple filters	public static Expression Replace(this Expression expression,\n    Expression searchEx, Expression replaceEx)\n{\n    return new ReplaceVisitor(searchEx, replaceEx).Visit(expression);\n}\ninternal class ReplaceVisitor : ExpressionVisitor\n{\n    private readonly Expression from, to;\n    public ReplaceVisitor(Expression from, Expression to)\n    {\n        this.from = from;\n        this.to = to;\n    }\n    public override Expression Visit(Expression node)\n    {\n        return node == from ? to : base.Visit(node);\n    }\n}	0
8660507	8660354	C# Check All from a CheckedListBox without showing the "Check All" entry	private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {\n        if (e.Index == 0) {\n            for (int item = 1; item < checkedListBox1.Items.Count; item++) {\n                checkedListBox1.SetItemChecked(item, true);\n            }\n            e.NewValue = CheckState.Unchecked;  // Prevent "Check All" from getting checked\n        }\n    }	0
21529617	21529438	Bitmap Image from Hex string - extra bytes being added	986 * 4	0
32659652	32659593	Escaping backslash character while splitting a string	Regex.Split(str,"\"")	0
33529951	33529729	Get every indexOf in ArrayList using a String	private static List<int> Find(ArrayList items, string entry)\n{\n    var ret = new List<int>();\n    for (var i = 0; i < items.Count; i++)\n        if ((string) items[i] == entry)\n            ret.Add(i);\n    return ret;\n}	0
17620	17612	How do you place a file in recycle bin instead of delete?	using Microsoft.VisualBasic;\n\nstring path = @"c:\myfile.txt";\nFileIO.FileSystem.DeleteDirectory(path, \n    FileIO.UIOption.OnlyErrorDialogs, \n    RecycleOption.SendToRecycleBin);	0
579973	579301	How to convert a 32bpp image to an indexed format?	ColorMap[] maps = new ColorMap[someNum]\n//  add mappings\nimageAttrs.SetRemapTable(maps);	0
27790633	27790571	Populate a Combobox with another Combobox dynamically	private void Cbx_ManageMedia_SelectedIndexChanged(object sender, EventArgs e)\n    { //Index change for combobox1\n\n    Cbx_ManageImagesImage.Items.Clear() //THIS LINE HAS BEEN ADDED\n    string query = "SELECT image FROM images WHERE type = '" + MIM + "'";\n    .......	0
17776977	17776938	c# copy selected listbox items into a string	string finalStr = "Some text before the values " + \n           String.Join(", ", listboxName.SelectedItems.Cast<YourItemType>());	0
19183266	19182859	Setting checked value for Eval(bool)	//for asp.net checkbox\n <asp:CheckBox  ID="IdCheckBox" runat="server" Checked="<%# Convert.ToBoolean(Eval("AutoRenew")) %>"  />\n\n//for plain html checkbox\n<input type="checkbox" <%# Convert.ToBoolean(Eval("AutoRenew")) ? "checked" : "" %> />	0
14858340	14858247	Trim all text before last Regex match	string str = Regex.Replace(input, @"(.+?)(N\d\.C\d\.R\d:)", "$2");	0
33920220	33765580	verify Digitaly sign an XML always false	xmlDoc.PreserveWhitespace = false;	0
7300454	7300268	Listbox removing Item	for (int x = listId.Items.Count-1; x > 0; x--) {}	0
12846126	12843672	Start IE with no Add-Ons	System.Diagnostics.Process ieProcess;\nieProcess = System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "-extoff");	0
18053262	18053200	c# field with 'properties'	public class Column\n{\n    private Source _Source = new Source();\n    private Destination _Destination = new Destination();\n\n    public Source Source { get { return _Source; } }\n    public Destination Destination { get { return _Destination; } }\n}\n\npublic class Source\n{\n    public string Name { get; set; }\n    public string Type { get; set; }\n}\n\npublic class Destination\n{\n    public string Name { get; set; }\n    public string Type { get; set; }\n}	0
3877051	3877031	WinForm button keeps focus	private void btnOk_Click(object sender, EventArgs e)\n{\n    btnOk.Enable = false;\n    try\n    {\n        // do stuff\n    }\n    finally\n    {\n        btnOk.Enable = true;\n    }\n}	0
5206315	5200805	How should I encrypt the connection string in app.config?	public partial class leDataContext\n{\n    private static DecryptedConnectionString;\n    static leDataContext()\n    {\n        // This code is guaranteed to run only once, by the framework, before any calls to the instance constructor below.\n        DecryptedConnectionString = Cryptography.Decrypt(ConfigurationManager.ConnectionStrings["leConnString"].ToString());\n    }\n\n    public leDataContext()\n        : base("")\n    {           \n        base.Connection.ConnectionString = DecryptedConnectionString;\n    }\n}	0
5417174	5411953	How to load and merge a dataset of XML docs	using (SqlDataReader dsReader = cmd.ExecuteReader())\n        {\n            XElement result = new XElement("root");\n            while (dsReader.Read())\n            {\n                // Read source\n                XDocument srcDoc = XDocument.Parse(dsReader["x"].ToString());\n\n                // Construct result element\n                foreach (XElement baseElement in srcDoc.Descendants("root").Elements())\n                    if (result.Element(baseElement.Name) == null)   // skip already added nodes\n                        result.Add(new XElement(baseElement.Name, baseElement.Value));\n\n            }\n            // Construct result string from sub-elements (to avoid "<root>..</root>" in output)\n            string str = "";\n            foreach (XElement element in result.Elements())\n                str += element.ToString();\n\n            // send the result\n            SqlContext.Pipe.Send("start:" + str);\n        }	0
6145353	6145235	WPF Find window instance	Application.Current.Windows	0
23319872	23319576	how to get taskList of User by providing username and password in C#	UserCredential credential;\n   using (var stream = new FileStream("client_secrets.json", FileMode.Open,   FileAccess.Read))\n    {\n        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(\n            GoogleClientSecrets.Load(stream).Secrets,\n            new[] { TasksService.Scope.Tasks },\n            "shyam.sundar@gmail.com", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;\n    }            \n   //credential=new UserCredential(\n    // Create the service.\n    var service = new TasksService(new BaseClientService.Initializer()\n    {\n        HttpClientInitializer = credential,\n        ApplicationName = "Tasks API Sample",\n    }); \n ListTaskLists(service)	0
13609725	13609428	Get Title from Crystal Report in C#	CrystalDecisions.CrystalReports.Engine.SummaryInfo.ReportTitle	0
11154030	11153685	Linq to Xml - Get a valid xml document after remove operation	var doc = XDocument.Parse(xmlString);\n\n        doc.Element("Folder").Element("Folders").Elements("Folder").Where(f => f.Attribute("ID").Value == "1").Remove();	0
13015389	13015334	How can I clone an existing table schema to create a new empty table with the same structure, using C#?	using (SqlConnection cnn = new SqlConnection(connectionString))\n{\n    using (SqlCommand cmd = cnn.CreateCommand())\n    {\n       cmd.CommandText = "Execute some SQL Select here. Doesn't matter what. We just need a reference to the table.";\n       cmd.CommandType = CommandType.Text;\n       cnn.Open();\n       using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.KeyInfo))\n       {\n          schema = rdr.GetSchemaTable();\n       }\n    cnn.Close();\n    }\n}	0
6691687	6691416	Generalize a method to work with various objects	public static List<T> ToList<T>(string[,] arra) // T can be anything\n    where T : new()                             // as long as it has a default constructor\n{\n\n    List<T> ret = new List<T>();\n    int col = array.GetLength(1);\n    int row = array.GetLength(0);\n\n    PropertyInfo[] props=PropArray(new T());\n    int propslen=props.Length;\n    for (int c = 0; c < col; c++)\n    {\n        T entry=new T();\n// ...	0
2795142	2795021	Trouble converting an MP3 file to a WAV file using Naudio	using (var reader = new Mp3FileReader(@"path\to\MP3")) {\n        using (var writer = new WaveFileWriter(@"C:\test.wav", new WaveFormat())) {\n            var buf = new byte[4096];\n            for (;;) {\n                var cnt = reader.Read(buf, 0, buf.Length);\n                if (cnt == 0) break;\n                writer.WriteData(buf, 0, cnt);\n            }\n        }\n    }	0
2157562	2157461	How do I set the 'always on top' flag/setting on a window that is external to my application?	[DllImport("user32.dll")]\n    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);\n\n    static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);\n\n    const UInt32 SWP_NOSIZE = 0x0001;\n    const UInt32 SWP_NOMOVE = 0x0002;\n    const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;\n\n    public static void MakeTopMost (IntPtr hWnd)\n    {\n        SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);\n    }	0
258495	258481	How can I check whether I am in a debug or release build in a web app?	#if DEBUG\n/* re-throw the exception... */\n#else\n/* write something in the event log... */\n#endif	0
6054593	6052992	how can i disable close button of console window in a visual studio console application?	class Program\n{\n    private const int MF_BYCOMMAND = 0x00000000;\n    public const int SC_CLOSE = 0xF060;\n\n    [DllImport("user32.dll")]\n    public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);\n\n    [DllImport("user32.dll")]\n    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);\n\n    [DllImport("kernel32.dll", ExactSpelling = true)]\n    private static extern IntPtr GetConsoleWindow();\n\n    static void Main(string[] args)\n    {\n        DeleteMenu(GetSystemMenu(GetConsoleWindow(), false),SC_CLOSE, MF_BYCOMMAND);\n        Console.Read();\n    }\n}	0
13949263	13948230	Adding a Banner to my C# App	KEY      |    VALUE\nBannerX  |    ~/Images/Sponsored/BannerX.png\nBannerY  |    ~/Images/Sponsored/BannerY.png\nBannerZ  |    ~/Images/Sponsored/BannerY.png	0
8740142	8739753	Finding case-insensitive key inside of list-view? Disabling empty column in listview?	void AddSetting(string settingName, string value, ListView table) {\n    ListViewItem setting = new ListViewItem(settingName, value);\n    setting.Name = settingName.ToLower();\n    table.Items.Add(setting);\n}\nstring GetSettingValue(string settingName, ListView table) {\n    if (table.Items.ContainsKey(settingName.ToLower())) {\n        return table.Items[settingName.ToLower()].SubItems[1].Text;\n    }\n    return null;\n}	0
13057521	13056698	How to override datagrdiview col cell strings Winforms	yourNewColumn.Expression = "'config' + CONVERT(SUBSTRING(yourOriginalColumn, 7, 1),Int16)+1"	0
23630419	23630076	Format a decimal to correct currency using correct number of decimals (C#)	var price = new Decimal(49.9);\nvar cultureInfo = new CultureInfo("da-DK");\n//var currentCultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);    \n\nvar test = string.Format(cultureInfo, "{0:C2}", price);	0
6383079	6383042	how to change colour of pixels on mouse click event?	int radius = 3; //Set the number of pixel you wan to use here\n //Calculate the numbers based on radius\nint x0 = Math.Max(e.X-(radius/2),0),\n    y0 = Math.Max(e.Y-(radius/2),0),\n    x1 = Math.Min(e.X+(radius/2),pictureBox1.Width),\n    y1 = Math.Min(e.Y+(radius/2),pictureBox1.Height);\nBitmap bm = pictureBox1.Image as BitMap; //Get the bitmap (assuming it is stored that way)\nfor (int ix = x0; ix < x1; ix++)\n{\n   for (int iy = y0; iy < y1; iy++)\n   {\n    bm.SetPixel(ix,iy, Color.Read); //Change the pixel color, maybe should be relative to bitmap\n   }\n}\npictureBox1.Refresh(); //Force refresh	0
12508130	12507191	An efficient way to implement a custom generic list/queue/stack combination	public static class ExtensionMethods    \n{ \n    public static T Pop<T>(this List<T> theList)    \n    {              \n        var local = theList[theList.Count - 1];    \n        theList.RemoveAt(theList.Count - 1);    \n        return local;   \n     }\n\n     public static void Push<T>(this List<T> theList, T item)   \n     {   \n        theList.Add(item);   \n     }   \n}	0
31830169	31826604	How to numerate(?) an indexed element with alphabet letters	Dictionary<string,GeoPoint>	0
3208181	3208114	ASP.Net Detecting if referrer was from a 301 permanent redirect	?from=oldsite	0
23804748	23783114	Making authorization of roles work after installing Ninject?	kernel.Bind<IFilterProvider>().To<FilterAttributeFilterProvider>();	0
11634592	11634440	Get foreign key table with a single query using LINQ	var query = from g in context.Groups\n            join m in context.Members on g.Id equals m.GroupId into members\n            select new \n            {\n              Group = g,\n              MemberCount = members.Count(),\n            };	0
7815105	7812039	How can I determine if StructureMap has loaded the same Registry multiple times?	container.WhatDoIHave();	0
31475937	31475142	Drawing lines to image from a txt file. Pen thickness is too large.	Point a = new Point(int.Parse(points[0]*10), int.Parse(points[1]*10));\n        Point b = new Point(int.Parse(points[2]*10), int.Parse(points[3]*10));	0
30050439	30050225	how to create JSON array in C# using JSON.NET	class Data\n{\n    public int y { get; set; }\n    public string myData { get; set; }\n}\n\nList<Data> list = new List<Data>\n{\n   new Data() { y = 3, myData = "firstPoint"},\n   new Data() { y = 7, myData = "secondPoint"},\n   new Data() { y = 1, myData = "thirdPoint"},\n};\n\nstring json = JsonConvert.SerializeObject(list);	0
28260921	28260697	How to get Enum Key list	List<int> result = Enum.GetValues(typeof(PartyRoleTypeEnum)).\n                   .OfType<PartyRoleTypeEnum>().Select(x=> (int)x)\n                   .ToList();	0
10202705	10202523	Data set relations query with 3 tables and addition	var query = from consumer in Tb_Consumer.AsEnumerable()\n            select new\n            {\n               CityName = consumer.Field<string>("City"),\n               //Name of relationship i.e. relation1 is important here\n               Sales = consumer.GetChildRows("relation1").Sum(tx=> tx.Field<decimal>("Price")) \n            };\n\nvar datatable = new DataTable();\ncol = new DataColumn("City");\ndatatable.Columns.Add(col);\ncol = new DataColumn("TotalSales");\ndatatable.Columns.Add(col);\n\nforeach (var item in query.ToList())\n{\n    var newrow = datatable.NewRow();\n    newrow["City"] = item.CityName;\n    newrow["TotalSales"] = item.Sales;\n    datatable.Rows.Add(newrow);\n}	0
12253338	12249007	Use C++ Component Object Model in C#	//Program2.cpp\nSTDMETHODIMP CProgram2::Test(BSTR* ret)\n{\n   *ret = SysAllocString(L"H");\n   return S_OK;\n}	0
604767	604716	What's the easiest way to rename the columns of a DataGridView showing a List<T>?	[DisplayName("Foo bar")]	0
7716200	7701904	Trouble changing Crystal Report Data Source in Code	public static void ConfigureLogonInfo(ReportDocument _report, ConnectionInfo _conn)\n    {\n        _report.DataSourceConnections.Clear();\n        foreach(Table tbl in _report.Database.Tables)\n        {\n            tbl.LogOnInfo.ConnectionInfo = _conn;\n        }\n\n        for(int i = 0; i < _report.Subreports.Count; i++)\n        {\n            var sub = _report.Subreports[i];\n            sub.DataSourceConnections.Clear();                \n            foreach(Table tbl in sub.Database.Tables)\n            {\n                tbl.LogOnInfo.ConnectionInfo = _conn;\n            }\n        }\n    }	0
31987112	31982637	Access Class Libary from Universal Shared App	var cls = new rtcuw.Class1();\nvar result = cls.doSomething();	0
857511	857489	How I can find all extension methods in solution?	\( this [A-Za-z]	0
7975983	7975935	Is there a LINQ function for getting the longest string in a list of strings?	list.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);	0
3554503	3554069	How to hide image control when it has no URL?	string Sql = "Select Logo From Model where ImageId = @ImageId";\n\n   //Assuming List<ImageModel> is what you are binding to the repeater\n   ImageModel model = e.Item.DataItem as ImageModel; \n   com.Parameters.Add("@ImageId", SqlDbType.Int32, model.ImageId);	0
6489621	6489586	how to retrieve multiple selected value from asp:checkbox .net c#	for (int i=0; i<checkboxlist1.Items.Count; i++)\n{\n    if (checkboxlist1.Items[i].Selected)\n    {\n        Message.Text += checkboxlist1.Items[i].Text + "<br />";\n    }\n}	0
25384692	25374013	Selenium click on coordinates not clicking where expected	Actions action = new Actions(driver);\naction.MoveByOffset(200,100).Perform();\nThread.Sleep(10000);\naction.Click();	0
4648860	4648532	How to unit test attributes with MsTest using C#?	public static bool HasAttribute<TAttribute>(this MemberInfo member) \n    where TAttribute : Attribute\n{\n    var attributes = \n        member.GetCustomAttributes(typeof(TAttribute), true);\n\n    return attributes.Length > 0;\n}	0
20213466	20210926	Making a calculation according to the BODMAS in C#	Expression e = new Expression("2 + 3 * 5");\n  Debug.Assert(17 == e.Evaluate());	0
20344108	20344023	compare a string with lines and remove the line which contains words	string[] domains = { "test69.com", "man.test" };\nstring[] lines = File.ReadLines(fileName)\n                     .Where(l => !domains.Any(d => l.Contains(d)))\n                     .ToArray();\n\n// write lines basck to file, if you need\nFile.WriteAllLines(fileName, lines);	0
7629154	7629138	Store check box value as bit in DB	ClassRegInfo order1 = new ClassRegInfo\n{\n        classID = classID.Text,\n        ObtainedPermission = obtainedPermission.Checked\n}	0
5727535	5232835	Use user.config instead of app.config	ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();\nconfigFile.ExeConfigFilename = exeFilePath; //somewhere in appdata in my case\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);	0
4216184	4213177	update property based on outcome of linq query	var list = (from c in Transactions() \n           group c by c.StoreID into g \n           select new TransactionDetail{  \n               Description = g.FirstOrDefault().Descrip, \n               BusinessName = g.FirstOrDefault().BusinessName, \n               TransactionAmount = g.Where(cr => cr.EntryType == cnCommon.INSERT_ENTRY).Sum(cr=>cr.TransactionAmount).Value, \n               PurchasesRequired = g.FirstOrDefault().PurchasesNeeded  \n                }).ToList();	0
22813908	22795982	Passing interface based property to Web API	public interface ISurvey<T>\n    where T: ISurveyItem \n{\n    List<T> Items { get; set; }\n    int QueueId { get; set; }\n    SurveyType Type { get; set; }\n}\n\npublic class Survey : ISurvey<SurveyItem>\n{\n    public List<SurveyItem> Items { get; set; }\n    public int QueueId { get; set; }\n    public SurveyType Type { get; set; }\n}	0
3045857	3045671	Interface for method that returns its own type	interface IFoo\n{\n    IFoo Bar();\n}\n\nclass Foo : IFoo\n{\n    Foo Bar() // should work since Foo is an IFoo, but it's not supported by C#\n    {\n        return new Foo();\n    }\n}	0
13349216	13348897	Read audio file to stream with MediaPlayer (WPF)	MemoryStream packStream = new MemoryStream()\n  Package pack = Package.Open(packStream, FileMode.Create, FileAccess.ReadWrite);\n  Uri packUri = new Uri("bla:");\n  PackageStore.AddPackage(packUri, pack);\n  Uri packPartUri = new Uri("/MemoryResource", UriKind.Relative);\n  PackagePart packPart = pack.CreatePart(packPartUri, "Media/MemoryResource");\n  packPart.GetStream().Write(bytes, 0, bytes.Length);\n  var inMemoryUri = PackUriHelper.Create(packUri, packPart.Uri);\n\n\n  mediaElement1.LoadedBehavior = MediaState.Manual;\n  mediaElement1.Source = inMemoryUri;\n  mediaElement1.Play();	0
4037663	4037634	How to remove all objects from List<object> where object.variable exists at least once in any other object.variable2?	list.RemoveAll(r => list.Any(o => o != r && r.ID == o.otherID));	0
9260018	9259624	Access String Resource from different Class Library	textBox1.Text = ClassLibrary1.Resource1.ClassLibrary1TestString;	0
855261	855176	Get IIS site id from a website	Request.ServerVariables[ "INSTANCE_ID" ]	0
8371087	8370989	WriteableBitmap Transform to Center?	wp.Render(textBlock1, new TranslateTransform() {Y = topMargin - textBlock1.Height / 2, X = imgWidth / 2 - textBlock1.Width / 2});	0
17723988	17723607	How to Avoid Recreating Object When Using Let with LINQ	var query = \n  from d in Departments\n  from e in d.Employees\n  select new { Employee = e, Department = d };\n\nforeach(var x in query)\n{\n  x.Employee.Department = x.Department;\n}	0
7447226	7447092	Access GUI and method of engaged a lot of time	// From UI thread e.g. button click event handler\nbool result; \n\nTask t = Task.Factory.StartNew(() => \n    {\n        result = Simulation(p1, p2);\n    });	0
9742736	9742724	how to convert a string to a bool	bool b = str == "1";	0
6930277	6928320	How do I pass the UnityContainer as a parameter to a registration in a Unity IOC xml configuration file	public UnityControllerFactory(IUnityContainer unityContainer) \n{\n   this.unityContainer = unityContainer;\n}	0
6364705	6364687	Using a button / event to show a new form and hide the exisiting one in C#	private void button1_Click(object sender, EventArgs e)\n{\n    (new Form3()).Show();\n    this.Hide();\n}	0
22200106	22199763	Mocking concrete object properties with no setter	using (ShimsContext.Create())\n{\n    ShimThing.ConstructorString = (@this, value) => {\n        var shim = new ShimThing(@this) {\n            NameGet = () => "Your Desired Name",\n            DescriptionGet = () => "Your Desired Description"\n        };\n    };\n\n    //do whatever you need to do that creates a Thing object\n}	0
33843779	33834893	Encrypt / Decrypt data with AES between c# and PHP - decrypted data starts with 255,254	Encoding.Unicode	0
6374222	6374120	How to dispose ObjectContext in EF4.0 implementation?	using()	0
3225988	3225986	copy part of an array into another array	string[] myArray = ....\nstring[] copy = new string[10];\nArray.Copy(myArray, 2, copy, 0, 10);	0
9841186	9840810	Convert the Font size in inch	"in is inches; 1in==96px"	0
32708970	32708881	Adding and retrieving Data sets to Redis using StackExchange.Redis	ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");\nIDatabase db = redis.GetDatabase();\ndb.HashSet("user:user1", new HashEntry[] { new HashEntry("12", "13"), new HashEntry("14", "15") });	0
10754786	10747736	Want to search in google	if (!address.Contains("."))\n        {\n            address = " ";\n            browsers[this.currentIndex].Navigate(new Uri("http://www.google.com/search?q=" + UrlTextBox.Text, UriKind.Absolute));\n        }	0
21012676	21012638	Parameters passing error from stored procedure to asp.net	Cmd.CommandType = CommandType.Text;	0
12090794	12090734	quick regex, match with a character but not including that character	(?<=P).*(?!\n)	0
28411601	28411388	Asp.net Post json	data: '{"queryname":"' + queryname + '"}'	0
12135978	12135937	C# for loop changing format DataTable	DataRow row;\n    for(int currentRow=0; currentRow < table.Rows.Count; currentRow++)\n    {\n         row = table.Rows[currentRow];\n\n            for (int currentCol = 0; currentCol < table.Columns.Count; currentCol++ )\n            {\n                if (table.Columns[currentCol].ColumnName == "product")\n                {\n                    excelDoc.setCell(1, 1, currentRow, currentCol, row[currentCol - 1].ToString());\n                }\n\n            }\n\n\n    }	0
801175	801136	how to write this query for this xml data in linq to xml?	var qry = from cls in doc.Root.Elements("class")\n          from student in cls.Elements("student")\n          from question in student.Elements("question")\n          from skill in question.Elements("skill")\n          select new {\n            Student = (int)student.Attribute("id"),\n            Skill = (string)skill.Attribute("id"),\n            Correct = (int)question.Attribute("correct")\n          } into denorm\n          group denorm by new {\n            denorm.Student,\n            denorm.Skill\n          } into grp\n          orderby grp.Key.Student, grp.Key.Skill\n          select new {\n            grp.Key.Student,\n            grp.Key.Skill,\n            Tally = grp.Sum(x => x.Correct)\n          };\n\nforeach (var row in qry)\n{\n  Console.WriteLine("{0}\t{1}\t{2}",\n    row.Student, row.Skill, row.Tally);\n}	0
21002888	21002856	Equivalent of Java's BigInteger in C#	BigInteger number = BigInteger.Pow(UInt64.MaxValue, 3);	0
3410501	3410405	Get x number of unique words on each side of a word in a string?	private static IEnumerable<string> GetUniqueWords(string phrase, string word, int amount)\n    {\n        //Clean up the string and get the words\n        string[] words = Regex.Split(phrase.Replace(".","").Replace(",",""),@"\s+");\n\n        //Find the first occurrence of the desired word (spec allows)\n        int index = Array.IndexOf(words,word);\n\n        //We don't wrap around the edges if the word is the first, \n        //we won't look before if last, we won't look after, again, spec allows\n        int min = (index - amount < 0) ? 0 : index - amount;\n        int max = (index + amount > words.Count() - 1) ? words.Count() - 1 : index + amount;\n\n        //Add all the words to a list except the supplied one\n        List<string> rv = new List<string>();\n        for (int i = min; i <= max; i++)\n        {\n            if (i == index) continue;\n            rv.Add(words[i]);\n        }\n\n        //Unique-ify the resulting list\n        return rv.Distinct();\n    }\n}	0
4989541	4989447	to get the weekdays between 2 dates	DateTime dtFrom = new DateTime(2011, 02, 5);\nDateTime dtTo = new DateTime(2011, 02, 9);\nList<DayOfWeek> days = new List<DayOfWeek>();\nwhile (dtTo != dtFrom)\n{\n   dtFrom = dtFrom.AddDays(1);\n   days.Add(dtFrom.DayOfWeek);\n}	0
18699693	18699643	Escaping RegEx in c#	string pattern = @"<asp:(\w+)\s+.*?id=""(\w+)""";	0
17344351	17344181	Extracting file name from the file path in C#?	if (cmdBrowse.ShowDialog() == DialogResult.OK)\n{\n   if(cmdBrowse.FileName.Length > 0)\n   {\n      string testNameShort = Path.GetFileName(cmdBrowse.FileName);\n      listboxTestsToRun.Items.Add(testNameShort);\n   }\n}	0
34141408	34140754	asp:LinkButton in Grid change link text	private void OnItemCreated(object sender, ItemCreatedEventArgs e)\n{\n    LinkButton btn = (e.Item.FindControl("LinkButtonName") as LinkButton);\n    if(btn != null)\n    {\n        // Logic to determine button text.\n        btn.Text = "Whatever";\n    }\n}	0
8900666	8900584	Working with IComparable.Compare without magic numbers	if (comparer.Compare(a, b) < 0)	0
5981793	5981763	Create a event for when data is aviable on a serial port	using System;\nusing System.IO.Ports;\n\nclass PortDataReceived\n{\n    public static void Main()\n    {\n        SerialPort mySerialPort = new SerialPort("COM1");\n\n        mySerialPort.BaudRate = 9600;\n        mySerialPort.Parity = Parity.None;\n        mySerialPort.StopBits = StopBits.One;\n        mySerialPort.DataBits = 8;\n        mySerialPort.Handshake = Handshake.None;\n\n        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceviedHandler);\n\n        mySerialPort.Open();\n\n        Console.WriteLine("Press any key to continue...");\n        Console.WriteLine();\n        Console.ReadKey();\n        mySerialPort.Close();\n    }\n\n    private static void DataReceviedHandler(\n                        object sender,\n                        SerialDataReceivedEventArgs e)\n    {\n        SerialPort sp = (SerialPort)sender;\n        string indata = sp.ReadExisting();\n        Console.WriteLine("Data Received:");\n        Console.Write(indata);\n    }\n}	0
1466490	1466414	Addin Property To a user_created Component	/// <summary>\n    /// Number Format\n    /// </summary>\n    [Category("Formatting"), DefaultValue("#,##0"), Description("Formatting string for numbers")]\n    public string NumberFormat { get; set; }	0
3221612	3162076	apple push notification with APNS sharp	public void Send()\n    {\n        foreach (NotificationConnection conn in this.notificationConnections)\n        {\n           // Console.Write("Start Sending");\n            conn.start(P12File, P12FilePassword);\n        }\n    }	0
27118624	27118034	How to find out if something will collide with something in Unity (2D)	using UnityEngine;\nusing System.Collections;\n\npublic class ExampleClass : MonoBehaviour {\n    void Update() {\n        Vector3 fwd = transform.TransformDirection(Vector3.forward);\n        if (Physics.Raycast(transform.position, fwd, 10))\n            print("There is something in front of the object!");\n\n    }\n}	0
30457191	30304746	TreeListView programmatically expand node after adding child	treeListView1.Expand(br.Model);	0
2978935	2966800	Remove image solid background with c sharp	bmp.MakeTransparent(bmp.GetPixel(0, 0));	0
11180914	11180798	Checking if dependancies been resolved correctly IOC	Container.Register(Component.For<Foo>().Properties(PropertyFilter.RequireAll));	0
16764267	16763979	Returning Textbox text to the last good value from Settings	private void AllPages_Checked(object sender, RoutedEventArgs e)\n    {\n        if (minBox != null) minBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();\n        if (maxBox != null) maxBox.GetBindingExpression(TextBox.TextProperty).UpdateTarget();\n    }	0
3446121	3446096	How to find double quotes in string in C#	string str = "it is a \"text\"";\n string str_without_quotes = str.Replace("\"", "");	0
20564235	20553914	How to use EF sharing same DbContext for multiple databases	var builder = new ContainerBuilder();\n// will add `HTTP request lifetime scoped` registrations (InstancePerHttpRequest) for the HTTP abstraction classes\nbuilder.RegisterModule(new AutofacWebTypesModule()); \nbuilder.Register<MyType>(ctx =>\n    {\n        var sessionBase = ctx.Resolve<HttpSessionStateBase>();\n        //now use the session value to retrieve the connection string\n    });	0
2069119	2069113	Adding a numerical value to a byte?	for(int k = 0; k < ImagesBytes.Length; k++){\n   ImageBytes[k] = (byte) (ImageBytes[k] + 5); // needs a cast\n}	0
8530988	8529480	how to split the line in the text file	static void Main(string[] args)\n    {\n        string strSample = "$3.00,0.00,0.00,1.00,L55894M8,$3.00,0.00,0.00,2.00,L55894M9";\n        var result = from p in strSample.Split(',').Select((v, i) => new { Index = i, Value = v })\n                     where p.Index % 5 == 4\n                     select p.Value;\n\n        foreach (var r in result)\n        {\n            Console.WriteLine(r);\n        }\n\n        Console.ReadKey();\n    }	0
17842766	17840895	split string by character and add to different columns in DataGridView in c#	DataTable dt = new DataTable("T1");\n        dt.Columns.AddRange(new DataColumn[] { new DataColumn("A"), new DataColumn("B"), new DataColumn("C"), new DataColumn("D")});\n        for (int i = 0; i < assetdata.Length; i += 4)\n        {\n            dt.Rows.Add(new string[]{assetdata[i],assetdata[i+1],assetdata[i+2],assetdata[i+3]});\n        }\n        dataGridView1.DataSource = dt;	0
20388139	20374067	Implementing Class Level inheritance with t4scafolding	[Table("Employee")]\npublic class Employee:Person\n{\n// Remove EmployeeID property\n//Add other properties if exists else leave it as empty class\n}	0
21874380	21870423	C# Check EOF in text file to fix array	string filename = openFileDialog1.FileName;\n        var lineCount = 0;\n        while ((line = reader.ReadLine()) != null)\n        {\n            if (GlobalDataClass.dDataArray.GetLength(0) == lineCount)\n            {                \n                double[,] newTemp = GlobalDataClass.dDataArray;\n                int increaseLenght = newTemp.Length + 1000;\n                GlobalDataClass.dDataArray = new double[increaseLenght, 2];\n                Array.Copy(newTemp, GlobalDataClass.dDataArray, newTemp.LongLength);\n            }\n\n            var data = line.Split(',');\n            GlobalDataClass.dDataArray[lineCount, 0] = double.Parse(data[0]);\n            GlobalDataClass.dDataArray[lineCount, 1] = double.Parse(data[1]);\n            lineCount++;\n        }	0
5708276	5708084	How do I supply credentials to execute a query on a server that's part of another domain?	System.Net.NetworkCredential cred = new System.Net.NetworkCredential("myname", "mypassword"); \n    ClientContext clientContext = new ClientContext(URL);\n\n    clientContext.Credentials = cred;	0
33621184	33470062	How to set the vertical alignment of a System.Windows.Documents.TableCell?	private double getRowHeight(TableRow row)\n    {\n        double maxHeight = 0;\n        foreach (TableCell cell in row.Cells)\n        {\n            Rect startRect = cell.ElementStart.GetCharacterRect(LogicalDirection.Forward);\n            Rect endRect = cell.ElementEnd.GetNextInsertionPosition(LogicalDirection.Backward).GetCharacterRect(LogicalDirection.Forward);\n            double Height = (endRect.Bottom - startRect.Top);\n            maxHeight = maxHeight > Height ? maxHeight : Height;\n        }\n        return maxHeight;\n    }	0
7034066	7033981	Create empty native C++ byte* in C# to PInvoke with	[MarshalAs(UnmanagedType.ByValArray, SizeConst = 99)]\npublic byte[] filler;	0
6378617	6378096	Set SelectedPath as a variable in FolderBrowserDialog	private void button1_Click(object sender, EventArgs e)\n    {\n        FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();\n\n        //Choose the default start up folder\n        string selectedFolder = @"C:\Dev";\n\n        //Set that into the dialog\n        folderBrowserDialog1.SelectedPath = selectedFolder;\n\n        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)\n        {\n            //Grab the folder that was chosen\n            selectedFolder = folderBrowserDialog1.SelectedPath;\n\n            // The user selected a folder and pressed the OK button.\n            // We print the number of files found.                \n            string[] files = Directory.GetFiles(selectedFolder);\n\n            MessageBox.Show("Files found: " + files.Length.ToString(), "Message");\n            MessageBox.Show(selectedFolder);\n        }            \n    }	0
2658888	2656240	How can you determine if Control.Visible is set via property or if the value is inherited	public bool CouldBeVisible { get; set; }\n\nprotected override void SetVisibleCore(bool value) {\n  CouldBeVisible = value;\n  base.SetVisibleCore(value);\n}	0
22586316	22585802	How to retrieve the first value in a multi-column listview	var myModel = (ClassName)jobsListView_manageajob.SelectedItem;\nsearchTextBox_manageajob.Text = myModel.JobNameListView1;	0
21191699	21191219	How to Print more than one page in C#	int stop = counter + amtperpage;\nif (stop >= al.Count)\n    stop = al.Count - 1; // - 1 to prevent index out of range error.\n\nwhile (counter <= stop)\n{\n    textToPrint = al[counter].ToString() + " - test";\n    e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin, topMargin + lineInc);\n\n    lineInc += 12;\n    counter++;\n}\n\npage++;\ne.HasMorePages = counter < al.Count - 1; // pesky zero-based array issue again.	0
16632249	16632062	C#: Json validation from user input	using (var reader = new StreamReader(jsonFile.InputStream))\n{\n    string jsonData = reader.ReadToEnd();\n    var serializer = new JavaScriptSerializer();\n\n    var result = serializer.Deserialize<Dictionary<string, object>>(jsonData);\n    // dragons be here ...\n}	0
16039355	16037136	Defining custom template for kendo ui grid column	columns.Bound(p => p.bid).ClientTemplate("<# if(direction == 1) {#>" +\n                "<img src='~/Images/up.png' alt='up'/>" +\n                "<#} else if(direction == 0) {#>" +\n                "<img src='~/Images/down.png' alt='down'/>" +\n                "<#}#>")              \n                .Title("End").Width(80);	0
16455117	16455032	Mark a field "Read Only" with Data Annotations	[ReadOnly(true)]\npublic decimal BodyMassIndex { get; private set; }	0
29709644	29709616	Getting first name on name string with substring fails [C#]	MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");	0
877869	877851	How to read registry branch HKEY_LOCAL_MACHINE in Vista?	RegistryKey myKey = Registry.LocalMachine.OpenSubKey(\n  @"Software\MyCompany\MyAppName", \n  false);	0
32837335	32837078	How to check if a GridView contains a certain Button asp.net c#	foreach (GridViewRow row in GridViewReview.Rows)\n{\n    Control reviewBtn = row.FindControl("ButtonReview") as Button;\n\n    if (reviewBtn.Visible == true)\n    {\n         btn_reviewAll.Visible = true;\n         break;\n    }\n    else\n    {\n       btn_reviewAll.Visible = false;\n    }\n}	0
11941408	11891168	How to use MonoTouch.Dialog's ActivityElement?	var root = new RootElement("foo");\n      root.Add (new Section("foo", "bar") {\n      new ActivityElement()\n      {\n        Caption = "foo",\n        Animating = true\n      }\n    });\n\n    var dvc = new DialogViewController(root, false);\n\n\n    window.RootViewController = dvc;	0
22504996	22504964	hiding application bar in windows phone	ApplicationBar.IsVisible = false;	0
2634812	2634779	Noob LINQ - reading, filtering XML with XDocument	//from nodes immediately below this one\nIEnumerable<XElement> elem_list = doc.Elements("qa");\n\n//from nodes of all levels below this node.\nIEnumerable<XElement> elem_list = doc.Descendants("qa");	0
27957990	27957925	Adding controls dynamically without it being monotonous	Control control = null;\n\nswitch (controlType)\n{\n   case "TextBox":\n       control = new TextBox(); \n       control.Name = "txt + labelText;\n       break; \n   case "ComboBox":\n       control = new ComboBox(); \n       control.Name = "cbo" + labelText;\n       break;\n}\n\ncontrol.Margin = _controlMargin; \ncontrol.HorizontalAlignment = HorizontalAlighment.Stretch;\ncontrol.FlowDirection = FlowDirection.LeftToRight;\ncontrol.HorizontalContentAlignment = HorizontalAlignment.Left	0
16758387	16756836	Saving an captured image to the local folder	JpegBitmapEncoder encoder = new JpegBitmapEncoder();\nvar image = Capture(true); // Take picture\nencoder.Frames.Add(BitmapFrame.Create(image));\n\n// Save the file to disk\nvar filename = String.Format("...");\nusing (var stream = new FileStream(filename, FileMode.Create))\n{\n  encoder.Save(stream);\n}	0
4271510	4271367	Read cell in each row of datagridview in c#	foreach (DataGridViewRow row in tblCategories.Rows)\n        {\n            string folderPath = row.Cells[5].Value.ToString();\n            string backupIncludes = row.Cells[4].Value.ToString();\n            Console.WriteLine("Folder Path: " + folderPath);\n            Console.WriteLine("Backup Includes: " + backupIncludes);\n        }	0
6448215	6447277	Amazon Product Advertising API - searching for multiple UPCs	ItemLookup itemLookup = new ItemLookup(){\n    AssociateTag = "myaffiliatetag-20"\n};\nitemLookup.AWSAccessKeyId = MY_AWS_ID;\n\nItemLookupRequest itemLookupRequest = new ItemLookupRequest();\nitemLookupRequest.IdTypeSpecified = true;\nitemLookupRequest.IdType = ItemLookupRequestIdType.UPC;\nitemLookupRequest.ItemId = new String[] { "9120031340300", "9120031340270" };\nitemLookupRequest.ResponseGroup = new String[] { "OfferSummary" };\nitemLookup.Request = new ItemLookupRequest[] { itemLookupRequest };\n\nItemLookupResponse response = client.ItemLookup(itemLookup);\nforeach(var item in response.Items[0])\n{\n  //Do something...\n  Console.WriteLine(item.ItemAttributes.Title);\n}	0
3049195	3048379	Linq DateTime expressions wont compare if only one is nullable	Expression.Constant(DateTime.Now, typeof(DateTime?))	0
25894859	25894578	Grouping a flattened LINQ resultset	var test = (from a in _activityNoteService.GetAll()\n    from l in a.ActivityNoteLines\n    where l.POItemId == poItem.Id && a.ActivityTypeId == 1\n    from s in l.StockCatalogueItem.StockInventoryItems\n    where s.OriginalActivityNoteLineID == l.Id\n    group s by new { sci = s.StockCatalogueItem, po = a.PurchaseOrder  } into g\n    select new\n    {\n      ListOfSii = g.Select(s => s.Id),\n      g.Key.sci,\n      g.Key.po\n    }).ToList();	0
670569	670563	LINQ to read XML	//Load xml\nXDocument xdoc = XDocument.Load("data.xml");\n\n//Run query\nvar lv1s = from lv1 in xdoc.Descendants("level1")\n           select new { \n               Header = lv1.Attribute("name").Value,\n               Children = lv1.Descendants("level2")\n           };\n\n//Loop through results\nforeach (var lv1 in lv1s){\n        result.AppendLine(lv1.Header);\n        foreach(var lv2 in lv1.Children)\n             result.AppendLine("     " + lv2.Attribute("name").Value);\n}	0
3017604	3017036	Importing data from third party datasource (open architecture design )	.ToInternalProduct( ThirdPartyClass )	0
12887112	12885287	controller's action parameter doesn't accept /	routes.MapRoute(\n            "Default",\n            "{*id}",\n            new {controller = "Start", action = "Index", id = UrlParameter.Optional}\n            );	0
15334505	15334410	How to add desktop path to app.config file?	string path = Properties.Settings.Default.Path;\nif(string.IsNullOrEmpty(path))\n{\n   path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\n}	0
21666309	21666216	How to use variable dates in an SQL query inside vb.net without syntax 11 error	sql = "select count(sTicket_number) as tickets from tickets where dtcreated between @START_DATE AND @END_DATE"\n\nDim cmd As New SqlCommand(sql, sqlCnn)\n\ncmd.Parameters.AddWithValue("@START_DATE", dtstartdate)\ncmd.Parameters.AddWithValue("@END_DATE", dtenddate )	0
17558836	17558617	DataRow column and string value comparison	foreach (KeyValuePair<String, String> kvp in rowValues)\n{\n    var rowValue = bookingRow[kvp.Key];\n    var passedValue = Convert.ChangeType(kvp.Value.Trim(), bookingRow[kvp.Key].GetType());\n    // or, if your bookingRow comes from a table\n    var passedValue = Convert.ChangeType(kvp.Value.Trim(), table.Columns[kvp.Key].DataType);\n    if (passedValue.Equals(rowValue) == false)\n    {\n        // code here\n    }\n}	0
29232896	29232584	I would like to parse string to objet in c# micro framework	var Source = "+CMGL: 1,\"REC READ\",\"+420731177370\",\"\",\"2015/03/21 11:26:10+04\"";\n\nvar SplitSource = Source.Split(',');\n\nString ID = SplitSource[0].ToString().Remove(0, 6); //good\n\nString Number = SplitSource[2].Replace("\"", ""); //good\n\nString Date = SplitSource[4].Replace("\"", ""); //good	0
11251324	11251005	WPF find a nested menuitem in code	var items = Options.ContextMenu.Items\nforeach(MenuItem item in items)\n{ \n    // do your work with the item \n}	0
29635871	29635754	ref and out with value type variables	static void Method(ref int i) {\n    // doesn't need to set the value\n}\n\nstatic void Main() {\n    int value;\n    value = 42; // needs to be initialised before the call\n    Method(ref value);\n   // value is still 42\n}	0
2905992	2905892	Combobox how to get the selected item to show a theme	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        comboBox1.Items.AddRange(new string[] { "Spring", "Summer", "Fall", "Winter" });\n        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;\n    }\n\n    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n        string folder = Application.StartupPath;\n        string theme = (string)comboBox1.Items[comboBox1.SelectedIndex];\n        string path = System.IO.Path.Combine(folder, theme + ".png");\n        Image newImage = new Bitmap(path);\n        if (this.BackgroundImage != null) this.BackgroundImage.Dispose();\n        this.BackgroundImage = newImage;\n    }\n}	0
12386711	12368872	ASP Menu width not setting to 100%	Menu ul li\n{\n    width:150px !important;\n    padding-bottom: 2px; /*bottom spacing between menu items*/\n}	0
16612487	16612105	Creating a SQL query according to dropdownlist selection	string strq2 = "where '";\nif(!string.IsNullOrEmpty(DropDownList1.SelectedItem.Text))\nstrq2 = strq2 + "[Year 1]='" + DropDownList1.SelectedItem.Text + " and ";\nif(!string.IsNullOrEmpty(DropDownList2.SelectedItem.Text))\nstrq2 = strq2 + "Product='" + DropDownList2.SelectedItem.Text+ " and ";\nif(!string.IsNullOrEmpty(DropDownList3.SelectedItem.Text))\nstrq2 = strq2 + "Media='" + DropDownList3.SelectedItem.Text+ " and ";\nif(!string.IsNullOrEmpty(DropDownList4.SelectedItem.Text))\nstrq2 = strq2 + "Publication='" + DropDownList4.SelectedItem.Text+ " and ";\nif(!string.IsNullOrEmpty(DropDownList5.SelectedItem.Text))\nstrq2 = strq2 + "Genre='" + DropDownList5.SelectedItem.Text+ " and ";\nif(!string.IsNullOrEmpty(DropDownList6.SelectedItem.Value))\nstrq2 = strq2 + "Month='" + DropDownList6.SelectedItem.Value+ " and ";\nif(!string.IsNullOrEmpty(DropDownList7.SelectedItem.Value))\nstrq2 = strq2 + "Section='" + DropDownList7.SelectedItem.Value+ " and ";\nstrq2 = strq2.Remove(strq2.Length - 5);	0
23331116	23326516	Unable to send to SignalR group	Groups.Add(connectionId, room);	0
24027292	24027190	Nested Object from DataTable	ParentContentId == null	0
18780676	18780633	route controller action to just controller	{controller}/{action}/{id}	0
9180621	9088954	ComException while Data Binding in XAML Metro app	PlayListView.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) => \n{ \n    PlayListView.DataContext = Playlists; \n}, PlayListView, null);	0
12647721	12647473	How can I Display UserControl into a form	MyUserControl uc = new MyUserControl();\nuc.Dock = DockStyle.Fill;\nthis.Controls.Add(uc);	0
10524911	10524878	How to find out where my error is coming from?	app.config	0
10746582	10746411	Using C#, LINQ - want to get column names AND data values	//long way\nstring sline=arQuery.GetType().Name + " ";\nforeach (PropertyInfo info in arQuery.GetType().GetProperties())\n{\n   if (info.CanRead)\n   {\n      sline += info.Name+": "+info.GetValue(arQuery, null) + " ";\n   }\n} \n\n//using LINQ without the for loop\nsline += string.Join(" ", arQuery.GetType().GetProperties().Where(i=>i.CanRead).Select(i=> ""+i.Name+": "+i.GetValue(arQuery, null)));	0
26360383	26360338	Copying rows from datagridwiew to datatable	DataTable gridTable = (DataTable)dataGridView1.DataSource;\n\n//you can call AcceptChanges() if you want !\n\n//create data table with the same schema as gridTable !\nDataTable dt = gridTable.Clone();\n\nforeach(DataRow row in gridTable.Rows)\n{\n    if(row.RowState == DataRowState.Deleted)\n       continue;\n\n    //import every row from the gridTable to the new DataTable.\n    dt.ImportRow(row);\n}	0
21955155	21955077	Sharing data from two text file using by 2 application at same time	Mutex m = new Mutex(false, "MyMutex");\nm.WaitOne();\n//File read or writing code goes here.   \nm.ReleaseMutex();	0
7817693	7817630	How much can this be simplified to a select statement in LINQ	var query = from element in mainDiagram.Elements\n            where element.SubType == EElemSubType.BusBar\n            where connPts.Busbars.ContainsKey(element.ConnectionPointId)\n            select element;\n\nforeach (var element in query)\n{\n    // by accessing immidiatly in a dictionary (assuming you are using one), you can either insert or update \n    taAddrList.TAAddressList[element.Key] = connPts.Bushbars[elem.ConnectionPointId];\n}	0
755184	755166	Exclude certain file extensions when get files from a directory	var files = Directory.GetFiles(jobDir).Where(name => !name.EndsWith(".xml"));	0
7155137	7155107	Looping through values from c# array using javascript	var myArray = <% = new JavaScriptSerializer().Serialize(serverSideArray) %>;\nfor(var i = 0; i < myArray.length; i++) {\n    document.write(myArray[i]);\n}	0
3007345	3007289	Convert SQL Binary Data to String in C#	var textFromBinary = System.Text.Encoding.UTF8.GetString(myBinaryData);	0
28243052	28242678	How to Move to next record while building an IEnumerable if the current row has data problems	List<RsvpData> cleanRsvpData = new List<RsvpData>();\n        foreach (RsvpData rsvp in rsvps)\n        {\n            try\n            {\n                RsvpData data = rsvp.ToRsvpData(students[x.RawAgentId]);\n                if (rsvp.Completed)\n                {\n                    data.SignatureUrl = "test";\n                    var cert = certificates.FirstOrDefault(c => c.Rsvp.RsvpId == x.RsvpId);\n                    data.CertificateId = cert != null ? cert.CertId.ToString() : "";\n                }\n                cleanRsvpData.Add(data);\n            }\n            catch (Exception ex)\n            { // handle error here\n            }\n        }	0
6504441	6504338	richtextbox c# auto show	rtb.SelectionLength = 0;\n    rtb.SelectionStart = rtb.Text.Length;\n    rtb.ScrollToCaret();	0
4735528	4735229	getting schema for a table	public DataTable GetScheme4Table(string tableName)\n{\n    DataTable ret = null;\n    IDbCommand command = null;\n\n    using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\" + DdListDatabases4GettingTables.SelectedValue + ".mdb;Persist Security Info=True"))\n    {\n        command = connection.CreateCommand();\n        command.CommandText = string.Format("SELECT TOP 1 * FROM [{0}]", tableName);\n        using (IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))\n        {\n            ret = reader.GetSchemaTable();\n        }\n    }\n\n    return ret;\n}	0
236577	236555	Compare datatables	//This assumes the datatables have the same schema...\n        public bool DatatablesAreSame(DataTable t1, DataTable t2) {         \n            if (t1.Rows.Count != t2.Rows.Count)\n                return false;\n\n            foreach (DataColumn dc in t1.Columns) {\n                for (int i = 0; i < t1.Rows.Count; i++) {\n                    if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }	0
29996571	29996527	Get Roles with UserId	string userName = Membership.GetUser(userGuid).UserName;\nvar roles = Roles.GetRolesForUser(userName);	0
9482874	9482207	how to store types as variables and use them in parameters' type?	class constType<T> where T : struct\n{\n    public T GetT()\n    {\n        return new T();\n    }\n\n    public string[] GetArraySomehow()\n    {\n        var len = Marshal.SizeOf(typeof(T));\n        return new string[len];\n    }\n}\n\nclass testTypeInClass\n{\n    public void test<T>(T message) where T : struct\n    {\n\n    }\n}\n\nclass MyClass\n{\n    void Test()\n    {\n        var constType = new constType<int>();\n\n        var typeInClass = new testTypeInClass();\n\n        var t = constType.GetT();\n\n        typeInClass.test(t);\n\n    }\n}	0
5698676	5688283	custom model binder with T4MVC	return RedirectToAction(MVC.Version.Edit().AddRouteValues(new {contractId = contract.Id.ToString()}));	0
12742424	12742105	how to Best Fit(All Columns) in a GridControl	if (view is GridView)\n{\n   // auto best fit...\n   (view as GridView).BestFitMaxRowCount = 5000;   // just to avoid to many compares\n   (view as GridView).BestFitColumns();\n   foreach (GridColumn item in (view as GridView).Columns) // reduce the width of very wide columns\n   {\n      item.Width = (item.Width > 1000) ? 1000 : item.Width;\n   }\n}	0
18569163	18566124	UtF-8 gives extra string in German character	System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;\n\n        // This is our Unicode string:\n        string s_unicode = "abc??abc";\n\n        // Convert a string to utf-8 bytes.\n        byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(s_unicode);\n\n        // Convert utf-8 bytes to a string.\n        string s_unicode2 = System.Text.Encoding.UTF8.GetString(utf8Bytes);\n\n        MessageBox.Show(s_unicode2);	0
13621429	3437770	How to extract zip file using dotnet framework 4.0 without using third party dlls	System.IO.Compression.ZipFile.ExtractToDirectory(String, String)	0
26564344	26563171	c# - How to print the text of some labels?	public void PrintThemAll()\n{\n    var document = new PrintDocument();\n    document.PrintPage += document_PrintPage;\n    document.Print();\n}\n\nvoid document_PrintPage(object sender, PrintPageEventArgs e)\n{\n    var graphics = e.Graphics;\n    var normalFont = new Font("Calibri", 14); \n\n    var pageBounds = e.MarginBounds;\n    var drawingPoint = new PointF(pageBounds.Left, (pageBounds.Top + normalFont.Height));\n\n    graphics.DrawString("Name: Paul", normalFont, Brushes.Black, drawingPoint);\n\n    drawingPoint.Y += normalFont.Height;\n\n    graphics.DrawString("Bought: bike", normalFont, Brushes.Black, drawingPoint);\n\n    e.HasMorePages = false; // No pages after this page.\n}	0
1904462	1904252	Is there a method in C# to check if a string is a valid identifier	const string start = @"(\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}|\p{Nl})";\nconst string extend = @"(\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}|\p{Cf})";\nRegex ident = new Regex(string.Format("{0}({0}|{1})*", start, extend));\ns = s.Normalize();\nreturn ident.IsMatch(s);	0
17044424	17044329	Return a list of a Entity class	public List<Customer> ConsultCustomerData(string cardID)\n {\n    List<Customer> list = new List<Customer>();\n    string sql = "SELECT name, cash FROM customers WHERE card_id = @cardID";        \n\n    MySqlCommand cmd = new MySqlCommand();\n    cmd.CommandText = sql;\n    cmd.CommandType = CommandType.Text;\n    cmd.Parameters.Add(new MySqlParameter("@cardID", MySqlDbType.VarChar)).Value = cardID;\n\n    using (IDbDataReader reader = cmd.ExecuteReader()) {\n        while (reader.Read()) {\n             list.Add(new Customer { \n                 Name = reader.GetString(0), \n                 Cash = reader.GetDouble(1) \n             });\n        }\n    }\n\n    return list;\n}	0
10161801	10161572	Parse without string split	string l_pos = new string(' ', 100); //don't write to a shared string!\n    unsafe \n    {\n        fixed (char* l_pSrc = l_pos)\n        {               \n              // do some work\n        }\n    }	0
2103115	2103094	Finding HTML strings in document	var doc = new HtmlDocument();\ndoc.Load(...);\n\nvar pTags = doc.DocumentNode.Descendants("p");	0
675244	675105	How do you make a non-modal topmost dialog that is only topmost in regards to the parent form in WinForms?	FindDialog fd = new FindDialog();\nfd.Show(this);	0
31671142	31668781	Get all combinations of k elements with repetion	class Program\n{\n    static void Main(string[] args)\n    {\n        var input = Enumerable.Range(1, 60);\n\n        using (var textWriter = File.AppendText("result.txt"))\n        {\n            foreach (var combination in input.CombinationsWithRepeat(10))\n            {\n                foreach (var digit in combination)\n                {\n                    textWriter.Write(digit);\n                }\n                textWriter.WriteLine();\n            }\n        }\n    }\n}\n\npublic static class Extensions\n{\n    public static IEnumerable<IEnumerable<T>> CombinationsWithRepeat<T>(this IEnumerable<T> elements, int k)\n    {\n        return k == 0 ? new[] { new T[0] } : elements.SelectMany((e, i) => elements.CombinationsWithRepeat(k - 1).Select(c => (new[] { e }).Concat(c)));\n    }\n}	0
13563388	13563161	C# extention method for helper with route value	public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName, object routeValues)\n    {\n\n    //Your code ...\n\n    string url = urlHelper.Action(actionName, routeValues);\n\n    }	0
830979	830824	C# WinForms - How Do i Retrieve Data From A Textbox On One Form Via Another Form?	class formB: Form{\n   private string data;\n   public formB(string data)\n    {\n        InitializeComponent();\n        this.data = data;\n    }\n  //rest of your code for the class\n\n}	0
1079431	1079265	How do I create a C# event handler that can be handled in IronPython?	public class Foo\n{\n   ...   \n\n    public event EventHandler Bar;\n}	0
25170640	25169752	Running a method by default before executing any action in controller automatically	public class AuthenticationAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        base.OnActionExecuting(filterContext);\n\n        if (Condition Not Met)\n        {\n            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new\n            {\n                controller = "Error Message Controller",\n                action = "Error Message Action"\n            }));\n        }\n    }\n}	0
21209010	21208477	Create a key of 3 columns including a relation to another table (code first)	public class ProductAttribute\n{\n    [Key]\n    [Required]\n    public string FieldName { get; set; }\n\n    public string FieldValue { get; set; }\n\n    [Key]\n    [ForeignKey("Item"), Column(Order = 1)]\n    public string ItemNo { get; set; }\n\n    [Key]\n    [ForeignKey("Item"), Column(Order = 2)]\n    public string VariantCode { get; set; }\n\n    public virtual Product Item { get; set; }\n}	0
2653934	2653884	Dynamically Loading a DLL	TestInterface.INeedHelp	0
19663545	19663317	Updating a List, consiting of another List	user.MyWall.Add(reader["WallText"])	0
16656464	16656285	how to change background color of a grid view cell in windows forms by C#	dataGridView1.Rows.Add(3, 2, -3);\n        dataGridView1.Rows.Add(1, -2, 3);\n\n        foreach (DataGridViewRow row in dataGridView1.Rows) \n        {\n            if (!row.IsNewRow && int.Parse(row.Cells[2].Value.ToString()) < 0)\n                row.Cells[2].Style.BackColor = Color.Red;\n        }	0
11554515	11554457	Split Name into First name and Last Name	string fullName = "Visual Studio";\nvar names = fullName.Split(' ');\nstring firstName = names[0];\nstring lastName = names[1];	0
4379289	4379114	Need a better way to wait between send and receive,UDPclient	class UDP {\n  int _lastTime = 0;\n  int MIN_DELAY = 500;\n\n  public void send() {\n    lock(this) {\n      int duration = now() - _lastTime;\n      if (duration < MIN_DELAY) {\n        sleep(MIN_DELAY - duration);  \n      }\n      realSend();\n      _lastTime = now();\n    }\n  }\n}	0
15612191	15611909	How to replace email address with name in text using regular expressions in C#?	Regex regex = new Regex(@"(\.|[a-z]|[A-Z]|[0-9])*@(\.|[a-z]|[A-Z]|[0-9])*");\nforeach (Match match in regex.Matches(inputString))\n{\n    // match.Value == "xx@yahoo.com.my"\n    string name = match.Groups[1]; // "xx"\n    string domain = match.Groups[2]; // "yahoo.com.my"\n}	0
16037636	16037581	C# Action syntax	public void Execute(Action action)\n{\n    Write();\n    action();\n    Clear();\n}	0
10321901	10321583	How to pull information from multiple text files in c#	private void searchButton_Click(object sender, EventArgs e)\n{\n    foreach (string fileName in Directory.GetFiles("C:\\ITRS_equipment_log\\", "*.txt"))\n    {\n        using (StreamReader sw = new StreamReader(fileName))\n        {\n            string Description = sw.ReadLine();\n            bool InStock = sw.ReadLine().Trim() == "1";\n\n            if (Description.Contains(comboBox1.SelectedText))\n            {\n                richTextBox1.AppendText("Item '" + Description + "' is " + (InStock ? "in" : "not in") + " stock.\r\n");\n            }\n        }\n    }\n}	0
3951696	3920315	Ignore Keyboard Input	return EnableKeyboard ? InterceptKeys.CallNextHookEx(hookId, nCode, wParam, lParam) : (IntPtr) 1;	0
15456359	15456178	Have JS code, but need to call it from C#	JintEngine engine = new JintEngine();\n// source should be a string containing the contents of your JavaScript file\nengine.Run(source);\nengine.SetParameter("altitudeKm", altitudeKm);\nengine.SetParameter("latitudeDegrees", latitudeDegrees);\nengine.SetParameter("longitudeDegrees", "longitudeDegrees");\nengine.SetParameter("yearFloat", yearFloat);\nvar result = engine.Run(@"\n    var wmm = new WorldMagneticModel();\n    return wmm.declination(altitudeKm, latitudeDegrees, longitudeDegrees, yearFloat);\n");\nreturn result;	0
4415483	4415476	Make span element visible in ItemBound event of repeater	((HtmlControl)e.Item.FindControl("TickMark")).Visible = false;	0
8128133	8113404	Load XPS to documentviewer from embedded resource	Stream ReadStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("file1.xps");\n        string tempFile = Path.GetTempPath()+"file1.xps"; \n        FileStream WriteStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);\n        ReadStream.CopyTo(WriteStream);\n        WriteStream.Close();\n        ReadStream.Close();\n\n        // Read tempFile INTO memory here and then\n\n        File.Delete(tempFile);	0
9116989	9099849	Named pipes: how server side can know that client has disconnected?	namedPipeServerStream.ReadByte();\nrdr.ReadLine();	0
6840292	6840146	Reading too many rows using WCF 	//service interface\n[ServiceContract]\npublic interface IService1\n{\n    [OperationContract]\n    List<string> DoWork(int page, int pageSize, out int totalRecords);\n}\n\n//service implementation\npublic class Service1 : IService1\n{\n    public List<string> DoWork(int page, int pageSize, out int totalRecords)\n    {\n        var l = new List<string>();\n        totalRecords = l.Count();\n        return l.Skip((page - 1) * pageSize).Take(pageSize).ToList();\n    }\n}	0
32813714	32813650	How to make a mouse popup box in Visual C# form?	toolTip1.SetToolTip(button1, "This button does XYZ");	0
6506481	6506365	Convert Entity Object into IEnumerable	public ContactsDetailsControl(ProActive.Contact contact)\n{\n   InitializeComponent();\n   ItemsListBox.ItemsSource = MakeMeEnumerable<Contact>(contact);\n}\n\nprivate IEnumerable<T> MakeMeEnumerable<T>(T Entity)\n{\n    yield return Entity;\n}	0
21423031	21422186	How to trim the values of x on X-axis in Chart control in Winforms?	chart1.ChartAreas[0].AxisX.LabelStyle.Format = "0";\nchart1.ChartAreas[0].AxisY.LabelStyle.Format = "0";	0
32673861	32673650	Populating List from Multiple Threads	ConcurrentBag<Projections> projectionsList = new ConcurrentBag<Projections>();       \nParallel.For(532, 548 + 1, i => {\n    var doc = webGet.Load("http://myurl.com/projections.php?League=&Position=97&Segment=" + i + "&uid=4");    \n    GetProjection(doc, ref projectionsList, (i));\n    }\n});	0
3126840	3124794	reportviewer control issue	Microsoft.Reporting.WebForms\nMicrosoft.Reporting.WinForms	0
223857	223832	Check a string to see if all characters are hexadecimal values	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
13361521	13361436	How can I manage the way my application closes?	Application.ApplicationExit += (s,e) =>\n{\n   // Your exit code.\n};	0
4727644	4727243	extension method parameter in gridview databind	.ToPhoneFormat((e.Row.DataItem as LeClient).LeCountryCode);	0
25061111	25061020	C# Func: access local variables in a block	static void Main(string[] args)\n{\n    List<Func<int>> fs = new List<Func<int>>();\n\n    for (int i = 0; i < 5; i++)\n    {\n        var copyOfi = i;\n        fs.Add(() => { return copyOfi; });\n    }\n\n    for (int i = 0; i < 5; i++)\n        Console.WriteLine(fs[i]());\n\n    Console.ReadLine();\n}	0
2560579	2560301	C#: How to verify that the constructor of another form called at all?	if(null != ref_name){..}	0
8854311	8766801	List to EntityCollection	entry.Publishers = new EntityCollection<Publisher>();\n\n            foreach (Publisher item in this.publishersLst.SelectedItems)\n            {\n                entry.Publishers.Add(item);\n            }	0
1660126	1660016	How to trap delete row ( from keyboard ) in datagridview?	e.Cancelled = true	0
6157468	6063124	binding a table to a dictionary in telerik reporting c#	var table = new DataTable();            \n\n        //Create table columns\n        _objectInstances.First().Columns.ToList().ForEach(a => table.Columns.Add(a, typeof(string)));\n        //Create table rows\n        _objectInstances.ToList().ForEach(i => table.Rows.Add(i.Dictionary.Values.ToArray()));\n\n\n        table1.DataSource = table;	0
15652129	15651929	Is there any way of knowing the content of an IQueryable object without using Reflection?	object[] objs = new object[3]{ "string", 78, DateTime.Now };\n\nvar q = objs.AsQueryable().Skip(1).Take(2);\n\nforeach( var o in q )\n{\n    var t = o.GetType();\n}	0
18277027	18276750	visual studio c# change button tool tip on click	System.Windows.Forms.ToolTip btnToolTip = new System.Windows.Forms.ToolTip();\nbtnToolTip.SetToolTip(this.button, "your tip");	0
17816162	17804818	Posting attached file to a web service via httpwebrequest	var url = string.Format("https://Site-Address/xml.aspx");\n\n        NameValueCollection nvc = new NameValueCollection();\n        nvc.Add("pcfxml", productSerialized);\n\n        WebClient wc = new WebClient();\n        var response = wc.UploadValues(url, nvc);	0
26769	26760	Parse string to TimeSpan	TimeSpan span;\n\n\nif (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))\n            MessageBox.Show(span.ToString());	0
1533274	1533239	Getting xml from a dataset	foreach(DataColumn dc in dsHR.Tables[0].Columns)\n    dc.ColumnMapping = MappingType.Attribute;	0
29165607	29165373	Searching data from gridview excluding its casing	lstUnAssStudentDTO = lstUnAssStudentDTO\n              .Where(u => u.FirstName.ToLower().Contains(\n                          txtSearchStudent.Text.ToLower().Trim())).ToList();	0
31735224	31735166	Assigning a decimal value to an individual employee c#	string[] employeeID = {"Brian", "Richard"};\ndecimal hourlyPay = 0.0M;\nfor (int i = 0; i < employeeID.Length; i++)\n{\n    if (employeeID[i] == "Brian")\n    {\n        hourlyPay = 8.00M;\n    }\n\n}\nConsole.WriteLine(hourlyPay);	0
26600435	26600150	Get the value of array in multidimensional-array in array	Console.WriteLine("{0}", am[ama].ToString());	0
24057671	24057063	FormatException with TryParseExact	private String CheckTime(String value)\n{\n    // change user input into valid format\n    if(System.Text.RegularExpressions.Regex.IsMatch(value, "(^\\d$)|(^\\d{3}$)"))\n        value = "0"+value;\n\n    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" };\n    DateTime expexteddate;\n    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture,     System.Globalization.DateTimeStyles.None, out expexteddate))\n       return expexteddate.ToString("HH:mm");\n    else\n       throw new Exception(String.Format("Not valid time inserted, enter time like:     {0}HHmm", Environment.NewLine));\n}	0
29691417	29667235	How to get thumbnail from a video in Windows Store app?	bitmap = new BitmapImage();\nbitmap.SetSource(await videoFile.GetThumbnailAsync(ThumbnailMode.SingleItem));	0
13874504	13874122	Running a method in BackGroundWorker and Showing ProgressBar	private void parseButton_Click(object sender, EventArgs e)\n{\n    parseButton.Enabled = false;\n    myBGWorker.RunWorkerAsync();\n}\n\nprivate void myBGWorker_DoWork(object sender, DoWorkEventArgs e)\n{\n   for(int i = 0; i < filesCount; i++)\n   {  \n       ParseSingleFile(); // pass filename here\n       int percentage = (i + 1) * 100 / filesCount;\n       myBGWorker.ReportProgress(percentage);\n   }\n}\n\nvoid myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    myProgressBar.Value = e.ProgressPercentage;\n}\n\nvoid myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    parseButton.Enabled = true;\n    MessageBox.Show("Done");\n}	0
19399813	19399497	Add Title before Export Excel	hw.Write("<table><tr><td colspan='3'>Title</td></tr>")\nhw.Write("<table><tr><td colspan='3'>Author</td></tr>")	0
4303453	4269587	nHibernate to Json	public object GetDTO()\n{\n     object data = new\n     {\n         pageData = new\n         {\n            Id = Post.Id,\n            pageUrl = Post.URL,\n            title = Post.PageTitle,\n            description = Post.PageDescription,\n            user = Post.User.Name\n        }\n    };\n    return data;\n}	0
27903203	27638347	Binding periodically updated data array to DataGridView	private void Form1_Load(object sender, EventArgs e)\n    {\n        Thread ReceiveThread = new Thread(new ThreadStart(ReceiveUDPData));\n        comboBox1.Items.Add("04 : Read Input Registers");\n        ReceiveThread.IsBackground = true;\n        ReceiveThread.Priority = ThreadPriority.Highest;\n        ReceiveThread.Start();\n        Control.CheckForIllegalCrossThreadCalls = false;\n\n        dt.Columns.Add("Index");\n        dt.Columns.Add("Data");\n        for (int j = 0; j < 125; j++)\n        {\n            DataRow row = dt.NewRow();\n            row[0] = j;\n            row[1] = 0;\n            dt.Rows.Add(row);\n        }\n        dataGridView.DataSource = dt;\n    }\n\npublic void UpdateGridView(byte[] valueArray)\n    {\n        for (int j = 0; j < valueArray.Length; j++)\n        {\n            DataRow row = dt.Rows[j];\n            row["Index"] = j+1; \n            row["Data"] = valueArray[j];\n        }\n    }	0
6272050	6271610	Unable to set SelectedValue in Combobox using DataTrigger	public TMod Modulation\n{\n    get { return modulation_; }\n    set\n    {\n        modulation_ = value; \n        NotifyPropertyChanged("Modulation");\n\n        if( modulation == TMod.P25 )\n        {\n            IFBandwith = TBand.Wide;\n        }\n    }\n }	0
27961134	27920146	XAML Templated Control how to write somthing like SelectedItem	public ICommand Process\n{\n    get\n    { \n        return new RelayCommand<object>((arg) => \n        {\n            Student button = arg as Student;\n            ----do something\n        }\n    });\n}	0
2168799	2168783	A Program to Repel Mosquitoes?	using System.Runtime.InteropServices;\n\n[DllImport("KERNEL32.DLL",\nEntryPoint="Beep",SetLastError=true,CharSet=CharSet.Unicode,\nExactSpelling=true,CallingConvention=CallingConvention.StdCall)]\n\npublic static extern bool Beep(int pitch , int duration);\n\nBeep(500,1000);	0
6813289	6813271	how to get all of the implemantations of an Interface using Reflection?	var rules = dll.GetTypes()\n               .Where(x => typeof(IRuleObject).IsAssignableFrom(x));	0
11716967	11716196	Difficulty in Parsing of XML in C#	var xmlStr = @"<UserID>\n  <Total>2</Total>\n  <X1>2</X1>\n  <Y1>4</Y1>\n  <Attached1>2,3,4</Attached1>\n  <X2>7</X2>\n  <Y2>8</Y2>\n  <Attached2>4,5,6</Attached2>\n</UserID>\n";\nvar doc = XDocument.Parse(xmlStr);\nvar users =\n    from user in doc.Descendants("UserID")\n    let total = (int)user.Element("Total")\n    select new\n    {\n        X = Enumerable.Range(1, total)\n                      .Select(i => (int)user.Element("X" + i))\n                      .ToArray(),\n        Y = Enumerable.Range(1, total)\n                      .Select(i => (int)user.Element("Y" + i))\n                      .ToArray(),\n        Attached = Enumerable.Range(1, total)\n                             .Select(i => (string)user.Element("Attached" + i))\n                             .ToArray(),\n    };	0
15631207	15631081	Building Release Version of a C# application	Project Properties>>Application tab	0
11549867	11549184	Scrape HTML for label then value in separate DIV tags	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(yourHtml);\n\nDictionary<string, string> dict = new Dictionary<string, string>();\n\n//This will get all div's with class as label & class value in dictionary\n\nint cnt = 1;\nforeach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='label']"))\n{\n    var val = doc.DocumentNode.SelectSingleNode("//div[@class='value'][" +  cnt + "]").InnerText;\n\n    if(!dict.ContainsKey(node.InnerText))//dictionary takes unique keys only\n    {\n        dict.Add(node.InnerText, val);\n        cnt++;\n    }\n}	0
24552002	24544351	Access originalRouteTemplate and parameters	var rd = request.GetRouteData();\nrd.RouteTemplate // the route template\nrd.Values // dictionary of parameters (including controller and action)	0
13721474	13695699	Writing new Quartz.net jobs to Xml	jobschedulingdataSchedule[] jbSchedule = { new jobschedulingdataSchedule() };\n\njobdetailType[] jobs = {new jobdetailType() { description = "Blah" } };\ntriggerType[] triggers = {new triggerType() { Item = new simpleTriggerType() { description = "Blah" } } };\njbSchedule[0].job = jobs;\njbSchedule[0].trigger = triggers;\n\nvar quartzConfig = new QuartzXmlConfiguration20();\nquartzConfig.version = "2.0";\nquartzConfig.schedule = jbSchedule;\n\nvar quartzJobsXml = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "quartz_jobs.xml");\nusing (TextWriter textWriter = new StreamWriter(quartzJobsXml))\n{\nXmlSerializer serializer = new XmlSerializer(typeof(Quartz.Xml.JobSchedulingData20.QuartzXmlConfiguration20));\nserializer.Serialize(textWriter, quartzConfig);\n}	0
20275606	20275065	fetching a particular column in a combobox from a ms access database using c#	private void button5_Click(object sender, EventArgs e)\n    {\n\n            con.Open();\n            OleDbDataAdapter d = new OleDbDataAdapter("select [Brand name] as BrandName from HUGO_BOSS", con);\n            DataSet dt = new DataSet();\n            d.Fill(dt);\n            comboBox3.DataSource = dt.Tables[0];\n            comboBox3.DisplayMember = "BrandName";\n            con.Close();\n        }	0
680681	424775	Is there a better way to express a parameterless lambda than () =>?	ExternalId.IfNotNullDo( _ => ExternalId=ExternalId.Trim());	0
8774293	8774261	Using an enum and a switch statement c#	Options value;\nif(!Enum.TryParse(volString, out value)) // note implicit <Options>\n    value = Options.SomeDefaultValue;	0
21708831	21708333	Output text from template txt file with dynamic values	type test.txt | sed.exe -e "s/\${value}/test/"	0
26600073	26600050	How to set pointer position on screen	Cursor.Position	0
9802080	9800534	How to optimize this code to create document libraries	string docLibNameBase ="myLibname";\nstring docLibNameTemp = docLibNameBase; //we start with the calculated title\nint iCounter = 1;\n\n//we check if the currently calculated title is OK\nwhile (listExists(docLibNameTemp, yourWeb)) {\n    docLibNameTemp = docLibNameBase + "/" + iCounter.toString();\n}\n//this is where you create the new list using docLibNameTemp as a good title\n\n\nbool listExists(string docLibName, SPWeb web){\n   try {\n      //if there is no list with such name, it will throw an exception\n      return (web.Lists[docLibname]!=null);\n   } catch{\n        return false;\n   }\n}	0
19833560	19833214	Show duplicates from one list with different ID's using linq	var uniqueResult = db.FPTStaticDataRatedFinancialAssetBase.OfType<FPTStaticDataRatedFinancialAssetBase>()\n        .Where(c => c.FORATExcelId == fptexcel || c.FORATExcelId == fptexcelprevious)\n        .GroupBy(x => x.Name)\n        .Where(c => c.Count() == 1)\n        .Select(y => y.FirstOrDefault()).ToList();	0
12285296	12285159	Application Bar items in windows phone 7	var button1 = (ApplicationBarIconButton) ApplicationBar.Buttons[0];\nbutton1.IsEnabled = true;	0
16510985	16510975	How to get directory of selected file?	string fullFilePath = @"C:\Users\Name\Documents\hi.txt";\nstring pathOnly = Path.GetDirectoryName(fullFilePath);\nConsole.WriteLine(pathOnly);	0
9559173	9559014	Gridview sorting doesn't fire in first click	ViewState["MySQL"]	0
2967463	2967429	SubSonic IQueryable To String Array	something.Select(r => r.RoleName).ToArray()	0
16770006	16769961	Equal values in array	var result = array1.GroupBy(i=>i)\n                .Select(g=>new {Value = g.Key, Count = g.Count()})\n                .Where(x=>x.Count>1)\n                .ToList();\n\nforeach (var pair in result)\n{\n     Console.WriteLine("PAIR: " + pair.Value + " COUNT: " + pair.Count);\n}	0
28989433	28989357	Unable to click radio button in Internet explorer using Selenium webdriver	driver.FindElement(By.Id("Paperless")).Click();	0
24551981	24293002	How to deserialize a UDPTunnel in protobuf.net	var size = IPAddress.NetworkToHostOrder (_reader.ReadInt32 ());\nvar udpTunnel = new UDPTunnel { packet = _reader.ReadBytes(size) };	0
18036623	18035521	Fill in values in XML Template	var newXml = Regex.Replace(xml, "<%=(.+?)%>", m => MyFxn(m.Groups[1].Value));\n\n//replace this function with yours which returns the real values. It's\n//just a demo.... \nstring MyFxn(string s)\n{\n    var dict = new Dictionary<string, string>(){\n        {"user.name","name1"},\n        {"user.address.street","street1"}\n    };\n\n    return dict[s];\n}	0
27734831	27734755	How to pass multiple arguments between windows store pages?	class collectionscontainer\n{\n  private list<urlist> list1;\n  private list<urlist> list1;\n}\nClass Classname\n{\n  public void Methord(collectionscontainer c)\n  {\n    //hear u will get access of both lists \n  } \n}	0
12604539	8666502	How to get hWnd of Edit Box when there are more than one?	//Get first occuring Edit box\nIntPtr edithWnd = FindWindowEx(mainhWnd, IntPtr.Zero, "TEdit", "");\n//And the second\nedithWnd = FindWindowEx(mainhWnd, edithWnd, "TEdit", "");\n//And finally the one I want\nedithWnd = FindWindowEx(mainhWnd, edithWnd, "TEdit", "");	0
19038317	19038175	How to login and do POST request with Login Cookie	private class CookieAwareWebClient : WebClient\n{\n    public CookieAwareWebClient()\n        : this(new CookieContainer())\n    { }\n    public CookieAwareWebClient(CookieContainer c)\n    {\n        this.CookieContainer = c;\n    }\n    public CookieContainer CookieContainer { get; set; }\n\n    protected override WebRequest GetWebRequest(Uri address)\n    {\n        WebRequest request = base.GetWebRequest(address);\n\n        var castRequest = request as HttpWebRequest;\n        if (castRequest != null)\n        {\n            castRequest.CookieContainer = this.CookieContainer;\n        }\n\n        return request;\n    }\n}	0
3067749	3067704	C# DateTime Class and Datetime in database	new SqlCommand("UPDATE INVITATIONS SET Status=@status, InvitedEmail=@invitedEmail, SentDate=@sentDate, ...	0
12208727	12193435	Devexpress SearchLookUpEdit set value from database	int value= 12;\n       searchLookUpEdit1.Properties.ValueMember = "POID";\n       searchLookUpEdit1.Properties.DisplayMember = "PONumber";\n       searchLookUpEdit1.EditValue = ValueDisplay(); //it should match the value member\n\n private object ValueDisplay()\n    {\n        return value;\n    }	0
3026236	3018919	Solving Naked Triples in Sudoku	combos = (array containing 3-long combination of candidates)\nfor each combo in combos                 # iterate through every combo\n  matches = new array                    # initialize a blank array\n  for each cell in unit\n    if (cell does not contain candidates other than the ones in your current combo)\n      matches.add(cell)                  # this is a match!\n    end\n  end\n\n  if matches.size >= 3                   # naked triple found! (three matches for given combo)\n    for each cell in unit\n      if (cell is not in matches)\n        (delete every candidate in current combo in this cell)\n      end\n    end\n  end\n  delete matches                         # clear up memory\nend	0
16629948	16629867	C# Check if filename ends with pattern	void Main()\n{\n    string test = "file(321).pdf";\n    string pattern = @"\([0-9]+\)\.";\n    bool m = Regex.IsMatch(test, pattern);\n    if(m == true)\n       test = Regex.Replace(test, pattern, ".");\n\n   Console.WriteLine(test);\n}	0
7400329	7400009	Getting cookies from WebBrowser in F#/C#	let getCookie(url:string) = \n        let form  = new Form(Text="Internet Navigator")\n        form.AutoScaleDimensions <- new System.Drawing.SizeF(6.0F, 13.0F)\n        form.AutoScaleMode <- System.Windows.Forms.AutoScaleMode.Font\n        form.ClientSize <- new System.Drawing.Size(849, 593)\n        form.ResumeLayout(false)\n        form.PerformLayout()\n\n        let wb = new WebBrowser()\n        wb.Visible<-true\n        wb.AutoSize<-true\n        wb.Size <- new System.Drawing.Size(804, 800)\n        form.Controls.Add(wb)\n        wb.DocumentCompleted |> Event.add (fun _ -> form.Close())\n        wb.Navigate(url)\n        form.ShowDialog() |> ignore\n        wb.Document.Cookie\n\n[<STAThreadAttribute>]\ndo\n    let cookie = getCookie "http://www.google.com"\n    Console.Read() |> ignore	0
17126846	17126692	Match 2 Textboxes line order	List<string> tb1lines = textbox1.Lines.ToList();\nList<string> tb2lines = textbox2.Lines.ToList();\nList<string> newtb2lines = new List<string>();\n\nforeach (string s in tb1lines)\n    newtb2lines.Add(tb2lines.Where(l => l.StartsWith(s)).ToList()[0]);\n\ntextbox2.Lines = newtb2lines.ToArray();	0
13490767	13490320	Loop through a class which contains variables	static class Program {\n    static void Main()\n    {\n        Order o1 = new Order { Resenh = "abc" },\n              o2 = new Order { Resenh = "abc" };\n        ShowDiffs(o1, o2); // {nothing}\n        o2.Resenh = "def";\n        ShowDiffs(o1, o2); // Resenh changed from abc to def\n    }\n    static void ShowDiffs<T>(T x, T y)\n    {\n        var accessor = TypeAccessor.Create(typeof(T));\n        if (!accessor.GetMembersSupported) throw new NotSupportedException();\n        var members = accessor.GetMembers();\n\n        foreach (var member in members)\n        {\n            object xVal = accessor[x, member.Name],\n                   yVal = accessor[y, member.Name];\n            if (!Equals(xVal, yVal))\n            {\n                Console.WriteLine("{0} changed from {1} to {2}",\n                    member.Name, xVal, yVal);\n            }\n        }\n    }\n}	0
18335831	18335661	Remove duplicates from the list with lists as objects	var c2Items = new c2[] \n        {\n            new c2 { st1 = "value 1", str2 = "value 2" },\n            new c2 { st1 = "value 2", str2 = "value 1" },\n            new c2 { st1 = "value 1", str2 = "value 2" }\n        };\n\n        var parent = new cl() { c2List = new List<c2>(c2Items) };\n\n        IEnumerable<c2> distinctitems = \n            parent\n                .c2List\n                .GroupBy(o => new { o.st1, o.str2 })\n                .Select(o => o.First());	0
19459853	19459729	WebAPI Validation DataAnnotation creates runtime exception [HttpStatusCode 500]	public string Email { get; set; }	0
654036	651738	raising a vb6 event using interop	Option Explicit\n\nPrivate FText As String\n\nPublic Event OnChange(ByVal Text As String)\n\n'This exposes the raising the event\n\nPrivate Sub Change(ByVal Text As String)\n  RaiseEvent OnChange(Text)\nEnd Sub\n\nPublic Property Get Text() As String\n  Text = FText\nEnd Property\n\n\nPublic Property Let Text(ByVal Value As String)\n  FText = Value\n  Call Change(Value)\nEnd Property	0
29133648	29127536	How can I use Fast Member to Bulk Copy data into a table with inconsistent column names?	// Get valid columns from the [targetTable] on the db at runtime\n// and produce a simple mapping\n// validColumns is an IDictionary<string, string>\nvar membersExposedToReader = validColumns.Keys.ToArray();\n\n// data is an IEnumerable<T>           \nusing (var bcp = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.TableLock, tran))\nusing (var reader = ObjectReader.Create(data, membersExposedToReader))\n{\n    foreach (var member in membersExposedToReader)\n    {\n        bcp.ColumnMappings.Add(member, validColumns[member]);\n    }\n\n    bcp.BulkCopyTimeout = 120;\n    bcp.BatchSize = 0;\n    bcp.DestinationTableName = targetTable;\n    bcp.WriteToServer(reader);\n}	0
32240116	32238636	How to set a EF code first connection string at runtime	public OtherEventModel(string ConnectionString)\n       : base(ConnectionString)	0
11480872	11480072	Can an attribute be made that can redirect to an action?	filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Account" } });	0
17006471	17006457	How do I remove an entry from List<KeyValuePair<string, string>> based on just the key?	myList.RemoveAll(kvp => kvp.Key == "@index");	0
10092128	10092083	C# WinForms get value from quote text	string input = ...;\nvar match = Regex.Match(input, @"value=""([^""]*)""");\nif (match.Success) {\n  var name = match.Groups[1].Value;\n  ...\n}	0
18963853	18963402	Update row in Gridview?	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)\n    {\n        GridViewRow row = GridView1.Rows[e.RowIndex];\n        TextBox tbmanu1 = (TextBox)row.FindControl("tbmanu"); \n        //or try \n        //TextBox tbmanu1= (TextBox)row.Cells[0].FindControl("tbmanu");\n        string  myString = Convert.Tostring(tbmanu1.text);\n        cmd.Parameters["@manufacturer"].Value = myString;   \n     }	0
819899	819850	to perform validation for amout(price) in ASP.net	public static bool validateAmount(string amount)\n{\n    int posDecSep = amount.IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);\n    int decimalPlaces = amount.Length - posDecSep - 1;\n    if (posDecSep < 0) { decimalPlaces = 0; }\n    if (decimalPlaces > 2)\n    {\n        //handle error with args, or however your validation works\n        return false;\n    }\n    decimal decAmount;\n    if (decimal.TryParse(amount, out decAmount))\n    {\n        if (decAmount >= 0)\n        {\n            //positive\n        }\n        else\n        {\n            //negative\n        }\n    }\n    return true;\n}	0
34559670	34559101	Roslyn Resolved Syntax Tree without Workspaces	GetMembers()	0
22440664	22436999	How to install latest service stack open source dll	-IgnoreDependencies	0
19901159	19900234	How can I parse a deserialized property (during deserialization) using XmlSerializer?	[XmlAnyAttribute]\npublic XmlAttribute[]XAttributes {get; set;}	0
18215714	18215256	how to bind image and name in dropdownlist using asp.net	protected void BindDataToGridviewDropdownlist()\n{\n    XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("xml/XMLFILE.xml"));\n    DataSet ds = new DataSet();\n    ds.ReadXml(xmlreader);\n    xmlreader.Close();\n\n    if (ds.Tables.Count != 0)\n    {\n        foreach (DataRow dr in ds.Tables[0].Rows)\n        {\n            ListItem li = new ListItem(dr["name"].ToString(), dr["name"].ToString());\n            li.Attributes.Add("data-image", "images/" + dr["img"].ToString());\n            ddlDetails.Items.Add(li);\n        }\n    }\n\n}	0
28675789	28675660	How to pas a View Model object from a controller to another controller	studentDetailsViewmodel StudentDetailsModel= \n      (studentDetailsViewmodel )TempData["studentDetails"];	0
14132786	14132647	enable button in C# by removing 'disabled' property using firebug	protected void btn_Click(object sender, EventArgs e)\n{\n     if (btn.Enabled)\n     {\n           // do something         \n     }\n}\n\n<asp:Button ID="btn" runat="server" Enabled="false" OnClick="btn_Click" Text="Test" />	0
22582613	22582505	Assembly Mismatch	Assembly 'HRMSDataAccessLayer, .. uses 'EntityFramework, Version=4.4.0.0, ...\nwhich has a higher version than referenced assembly 'EntityFramework, Version=4.1.0.0,	0
23435077	23434831	XML Serializing a List<Class>	[XmlArray("MoreBars"), XmlArrayItem(typeof(MoreElement), ElementName = "More")]	0
3558876	457368	How to use launch condition option in installation package using C#	Property: PCSUITERUNTIMEEXISTS\nRegKey: SOFTWARE\PCSuite\Product\nRoot: vsdrrHKLM\nValue:  Nokia Pc Suite	0
23714544	23714353	Docking a WinForm inside another WinForm	private void Form1_Load(object sender, EventArgs e)\n{\n    Form2 frm2 = new Form2();\n    frm2.Show();\n\n    this.Controls.Add(frm2);\n}	0
11646914	11646298	Connecting a Test project to a WCF Service Automatically	var endpoint = RoleEnvironment.Roles["WebRole1"].Instances.First().InstanceEndpoints["Endpoint1"];\nvar siteUrl = String.Format("{0}://{1}", endpoint.Protocol, endpoint.IPEndpoint);	0
9208894	9192164	Removing items from a observablecollection bound to a datagrid Silverlight?	dgOrderItems.CommitEdit(DataGridEditingUnit.Row, true);	0
8988386	8988299	Select constants from a list by propertyname	string fieldName = "test1";\nobject fieldValue = typeof(Constants).GetField(fieldName, BindingFlags.Static).GetValue(null);	0
24072648	24070595	Is it possible to use Linqpad with a Repository and UnitOfWork pattern?	void Main()\n{\n     //IRepository<Website> _repository =  ;\n\n    var _repository = new Repository.Pattern.Ef6.Repository<Website>(this);\n\n    var website = _repository\n        .Query()\n        .Select();\n\n    website.Dump("The Oputput...");\n}	0
1079177	1079164	C#: Recursive functions with Lambdas	Func<int, int> fac = null;\nfac = n => (n <= 1) ? 1 : n * fac(n - 1);	0
4940310	4938963	How to get Facebook user id during deauthorization	string signedRequestValue = Request.Form["signed_request"];\nvar app = new FacebookApp();\nvar sig = FacebookSignedRequest.Parse(((FacebookConfigurationSection)ConfigurationManager.GetSection("facebookSettings")).AppSecret, signedRequestValue);\nlong userid = long.Parse(sig.UserId);	0
21844798	21844352	Comparing dataSet values	string expression = String.Format("FK_album = {0}", Inner_Id.Value);\nDataRow[] filteredRows = imageList.Tables[0].Select(expression);	0
3635056	3635042	Calculating Total Count of Items in List<T> for multiple KeyValuePairs in Dictionary<string,List<string>>	int sum = dictionary.Sum(x => x.Value.Count);	0
24587294	24586470	Filesystemwatcher on a folder and getting the filename	// Define the event handlers.\nprivate static void OnChanged(object source, FileSystemEventArgs e)\n{\n    // Specify what is done when a file is changed, created, or deleted.\n   Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);\n}\n\nprivate static void OnRenamed(object source, RenamedEventArgs e)\n{\n    // Specify what is done when a file is renamed.\n    Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);\n}	0
785110	785054	Minimizing all open windows in C#	using System;\nusing System.Runtime.InteropServices;\n\nnamespace ConsoleApplication1 {\nclass Program {\n    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]\n    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n    [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]\n    static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);\n\n    const int WM_COMMAND = 0x111;\n    const int MIN_ALL = 419;\n    const int MIN_ALL_UNDO = 416;\n\n    static void Main(string[] args) {\n        IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);\n        SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero); \n        System.Threading.Thread.Sleep(2000);\n        SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero);\n    }\n}\n}	0
3807630	3807475	managing native handles with generics	public sealed class SafeHandle<T> : IDisposable where T : IHandleTraits, new() {\n    private bool disposed;\n    private IntPtr handle_ = IntPtr.Zero;\n    private T handleType;\n    public SafeHandle() {\n        handleType = new T();                        \n        handle_ = handleType.Create();\n    }\n    // etc...\n}	0
28644697	28644388	how to Change the url of page asp.net?	routes.MapPageRoute("SomeContent",\n        "Admin/SomeContent"\n        "Admin/news.aspx?Id=24");	0
9872125	9872069	How to get file Size from OpenFileDialog?	var ofd = new OpenFileDialog();\nif (ofd.ShowDialog() == DialogResult.OK)\n{\n    var size = new FileInfo(ofd.FileName).Length;\n}	0
13338681	12815269	How to display the particular ID image from the server folder	private void CallImage()\n      {\n       SqlConnection SqlCon = new SqlConnection(GetConnectionString());\n       SqlCon.Open();\n       string query = "SELECT FilePath FROM CompanyInfo \n              WHERE VendorID= '" + ddlVendorID.SelectedValue + "'";\n       SqlCommand SqlCmd = new SqlCommand(query, SqlCon);\n       SqlDataAdapter da = new SqlDataAdapter(SqlCmd);\n       DataTable dt = new DataTable();\n       da.Fill(dt);\n       string ImageName = Convert.ToString(dt.Rows[0][0].ToString());\n       Image1.ImageUrl = ("~\\Upload\\Commerical Certificates\\" + ImageName);\n       SqlCon.Close();\n     }	0
33047016	33046845	puting files pathes that in specific dir in array c#	static void SaveFileListingToText(string folder, string outputTxtFilePath)\n    {\n        string[] files = System.IO.Directory.GetFiles(folder);\n        System.IO.File.WriteAllLines(outputTxtFilePath, files);\n    }	0
24488027	24487106	Xpath select all tr after second tr	GeneralUtils.GetListDataFromHtmlSourse(PageData, "//tr[position() > 2]//td[1]");	0
27876626	27876571	Printing out the string with most occurences of a specific char, in a string array	string answer;\nint prevCount = 0, count = 0;\nfor (int x = 0; x < list.Length; x++)\n{\n     int count = list[x].Split(c).Length - 1;\n     if(count>prevCount)\n     {\n         answer = list[x];\n         prevCount = count;\n     }\n\n\n}\nreturn answer;	0
3666974	3666947	how to create 1px X 1px on .Net	(new Bitmap(1,1)).Save(name,ImageFormat.Jpeg);	0
12919738	12874725	Uploading an Image Type Application/Octet-Stream from android phone	string[] sTypes = { "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", "image/x-png",\n    "image/png", "Application/Octet-Stream" };\nbool bIsMatch = false;\nforeach (string sType in sTypes)\n{\n    if (String.Compare(sType, FileUpload1.PostedFile.ContentType, true) == 0)\n        bIsMatch = true;\n}\nif (bIsMatch)\n{\n    //Allow upload\n}	0
7963279	7963275	How do I build a splash screen into a Windows Forms application without setting timers etc?	using Microsoft.VisualBasic.ApplicationServices;\n\npublic class Startup : WindowsFormsApplicationBase\n{\n    protected override void OnCreateSplashScreen()\n    {\n        SplashScreen = new SplashForm();\n    }\n\n    protected override void OnCreateMainForm()\n    {\n        MainForm = new MyMainForm();\n    }\n}\n\nstatic class Program\n{\n    static void Main(string[] args)\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        new Startup().Run(args);\n    }\n}	0
17629965	17629748	How to do a join on two tables with Linq using this EDMX diagram?	from student in ctx.Student\nselect new\n{\n    Student = student,\n    Subjects = from studsub in student.StudentsSubjects\n               select studsub.Subject\n};	0
18778781	18778662	how loop through multiple checkbox in C#	foreach (var control in this.Controls) // I guess this is your form\n            {\n                if (control is CheckBox)\n                {\n                    if (((CheckBox)control).Checked)\n                    {\n                        //update\n                    }\n                    else\n                    {\n                        //update another\n                    }\n                }\n            }	0
29512693	29512591	C# -Fetch Node Value and corresponding count for XML elements	var result = xdoc.Descendants("event")\n                 .Where(x => !String.IsNullOrEmpty((string)x.Element("command")))\n                 .GroupBy(x => (string)x.Element("command"))\n                 .Select(x => new\n                             {\n                                Value = x.Key,\n                                Count = x.Count()\n                             });	0
934366	934340	How to find a particular position of a selected item in Listbox making the Buttons Enabled in C#?	private bool SelectionIsContiguous(ListBox lb)\n{\n    for (int i = 0; i < lb.SelectedIndices.Count - 1; i++)\n        if (lb.SelectedIndices[i] < lb.SelectedIndices[i + 1] - 1)\n            return false;\n\n    return true;\n}\n\nprivate void SetMoveButtonStates()\n{\n    if (this.listBox.SelectedIndices.Count > 0)\n    {\n        if (this.listBox.SelectedIndices.Count > 1 && !SelectionIsContiguous(this.listBox))\n        {\n            this.btnMoveUp.Enabled = false;\n            this.btnMoveDown.Enabled = false;\n            return;\n        }\n\n        int firstSelectedIndex = this.listBox.SelectedIndices[0];\n        this.btnMoveUp.Enabled = firstSelectedIndex == 0 ? false : true;\n\n        int lastIndex = this.listBox.Items.Count - 1;\n        int lastSelectedIndex = this.listBox.SelectedIndices[this.listBox.SelectedIndices.Count - 1];\n        this.btnMoveDown.Enabled = lastSelectedIndex == lastIndex ? false : true;\n    }\n}	0
9256726	9256494	Ordering FieldInfos	FieldInfo[] infos = typeof(string).GetFields()\n   .OrderBy(fi => fi.FieldHandle.Value.ToInt32()).ToArray();	0
4662034	4661959	byte array to a file	File.WriteAllBytes(@"\\server\public_share\MyFile.txt", byteArray);	0
3255737	3255706	Split string by last separator	string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);	0
16901546	16901168	Extra table in database Entity Framework Code First With Database Migrations	Sql(@"CREATE TABLE.....")	0
11191415	11189729	Using AutoMapper to map the property of an object to a string	Mapper.CreateMap<Tag, string>().ConvertUsing(source => source.Name ?? string.Empty);	0
3070008	3069951	Using Directives, Namespace and Assembly Reference - all jumbled up with StyleCop!	[assembly: Microsoft.Moles.Framework.MoledType(typeof(System.IO.File))]\nnamespace MyNamespace\n{\nusing System;\nusing System.IO;\nusing Microsoft.Moles.Framework;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\n// Some Code...\n}	0
676295	676288	Generic list in an interface	public interface IEntity<T>\n{\n    IQueryable<T> GetAll();\n}\n\npublic class Dealer : IEntity<Dealer>\n{\n   public IQueryable<Dealer> GetAll() { }\n}	0
9951842	9951240	Best practice for SQL constant values	CREATE FUNCTION\n    [dbo].PRODUCT_ELECTRO()\nRETURNS INT\nAS\nBEGIN\n        RETURN 3\nEND\n\n\n-- This returns the value 3\nSELECT\n    dbo.PRODUCT_ELECTRO()\n\nIF @MyValue = dbo.PRODUCT_ELECTRO()\nBEGIN\n    PRINT 'The value is tres'\nEND	0
11790755	11789750	Replace all occurences of a string from a string array	string [] items = {"one","two","three","one","two","one"};\nitems =  items.Select(s => s!= "one" ? s : "zero").ToArray();	0
28932607	28907235	How to get the containing grids key from within the server side DataBinding event of a RadComboBox	protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)\n{\n    if (e.Item is GridCommandItem)\n    {\n        GridCommandItem commandItem = (GridCommandItem)e.Item;\n        RadComboBox combo = (RadComboBox)commandItem.FindControl("MethodRadComboBox");\n        combo.DataSource = e.Item.OwnerTableView.DataSource;\n        combo.DataBind();	0
27798813	27798702	Setting datepicker by code in Windows Phone 8	public void setDatePicker(string date){\n   datepicke1.SelectedDate = DateTime.Parse(date); // I used the name of your datepicker\n}	0
16654553	16653669	Universal generic type conversion from string	static Boolean TryParseString<T>(\n        String stringValue, ref T value)\n    {\n\n        Type typeT = typeof(T);\n\n        if (typeT.IsPrimitive)\n        {\n            value = (T)Convert.ChangeType(stringValue, typeT);\n            return true;\n        }\n        else if (typeT.IsEnum)\n        {\n            value = (T)System.Enum.Parse(typeT, stringValue); // Yeah, we're making an assumption\n            return true;\n        }\n        else\n        {\n            var convertible = value as IConvertible;\n            if (convertible != null)\n            {\n                return convertible.FromString(stringValue);\n            }\n        }\n\n        return false;\n\n    }	0
32638010	32637891	Return the whole line that contains a match using regular expressions in c#	string pattern = ".*foobar.*";\nRegex r = new Regex(pattern)\nforeach (Match m in r.Matches(input))\n{\n     Console.WriteLine(m.Value);\n}	0
7472690	7472651	ZoomOut and ZoomIn Images in Windows Phone 7 using double tap	private void OnDoubleTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)\n{\n if(scale.ScaleX == 1 && scale.ScaleY == 1) //The scale is currently 1, enlarge\n {\n   scale.ScaleX = 1.5;\n   scale.ScaleY = 1.5;\n } else { //Its bigger, reset to 1.\n   scale.ScaleX = 1;\n   scale.ScaleY = 1;\n } \n}	0
1858354	1846426	How To Limit a WCF Service Application, So That Only Unique Clients Can Access	operationContext.Channel.Abort();	0
7902297	7902247	C# error "String was not recognized as a valid DateTime"	string todaysDate = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);	0
3886754	3886713	Force local user to change password at next login with C#	de.Properties["PasswordExpired"].Value = 1;	0
8457981	8457601	How can I classify some color to color ranges?	public string Classify(Color c)\n{\n    float hue = c.GetHue();\n    float sat = c.GetSaturation();\n    float lgt = c.GetLightness();\n\n    if (lgt < 0.2)  return "Blacks";\n    if (lgt > 0.8)  return "Whites";\n\n    if (sat < 0.25) return "Grays";\n\n    if (hue < 30)   return "Reds";\n    if (hue < 90)   return "Yellows";\n    if (hue < 150)  return "Greens";\n    if (hue < 210)  return "Cyans";\n    if (hue < 270)  return "Blues";\n    if (hue < 330)  return "Magentas";\n    return "Reds";\n}	0
34420060	34419879	How i can calculate from textbox value (int) to label (int)	var myInt = Convert.ToInt32(tbMyTextBox.Text);\nvar myResult = myInt * 3;\nlblMyLabel.Text = myResult.ToString();	0
2864006	2863779	Passing a SAFEARRAY from C# to COM	for (var i = 0; i < facePositions.Length; i++)\n{\n  facePositions[i] = new FacePosition2();\n}	0
12169929	12169892	How do I fill a list view using a data table?	protected void Page_Load(object sender, EventArgs e)\n    {\n        lvItems.DataSource = GetSourceDBs();\n        lvItems.DataBind();\n    }	0
24986638	24986593	Need help alternating a series range from 1 to the number entered.	for (i = 1;  i < numberEntered; i++)\n{\n     even = i % 2;\n     if (even != 0)\n        results = results + i;\n     else\n       results = results - i;\n}	0
21440903	19312485	How to format heading in excel / csv using C#	...\nSystem.IO.StreamWriter writer = new System.IO.StreamWriter(dialog.FileName); //open the file for writing.\nwriter.Write("Personal Information" + delimiter + delimiter + "Working INFO" + delimiter);\nwriter.Write(report); //write the current date to the file. change this with your date or something.\n...	0
31721678	31716474	Issue with upgrading TFS Checkin Policies to VS2015	"%CommonProgramFiles%\microsoft shared\Team Foundation Server\14.0"	0
9932299	9932254	cannot insert data into database	nonquerycommand.ExecuteNonQuery();	0
1445774	1445766	C# Nullable<DateTime> to string	string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;	0
13998675	13998604	Pointing a delegate to a method in a class	class Program\n{\n    delegate void D1();\n\n    static void Main(string[] args)\n    {\n        var testObj = new Program();\n        D1 myDelegate = testObj.TestMethod;\n        myDelegate.Invoke();\n    }\n\n    void TestMethod()\n    {\n        Console.WriteLine("Foo!");\n    }\n}	0
5721706	5721657	String List parsing	var inputString = "item1;item2;item3";\nvar asList = inputString.Split( ';' ).ToList();	0
23097450	23097431	Writing Something to a File then loading it again	Encoding.ASCII	0
7009994	7009862	Pin Pad. A custom control like this one	private void Form1_Load(object sender, EventArgs e)\n{\n  int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n  Random rnd = new Random();\n  for (int i = array.Length - 1; i > 0; i--)\n  {\n    int j = rnd.Next(i);\n    int k = array[j];\n    array[j] = array[i - 1];\n    array[i - 1] = k;\n  }\n\n  for (int i = 0; i < array.Length; i++)\n  {\n    panel1.Controls["Button" + (i + 1).ToString()].Text = array[i].ToString();\n  }	0
161834	161822	How to indicate that a method was unsuccessful	public bool CalculatePoint(... out Point result);	0
13368601	13365245	Getting all classes that implement a given interface in WinRT	// We get the current assembly through the current class\nvar currentAssembly = this.GetType().GetTypeInfo().Assembly;\n\n// we filter the defined classes according to the interfaces they implement\nvar iDisposableAssemblies = currentAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IDisposable))).ToList();	0
19439608	19439566	Display an ASP.NET as XML	Content-Type:text/xml	0
20267173	20267008	Dynamic change body of lambda exprssion?	//property selector\nFunc<Person, Boolean> propertySelector = person => person.FirstNameIsActive;\n\n//your predicate\nFunc<Person, Boolean> predicate = person => propertySelector(person) == true;\n\n//new person with true, false properties.\nPerson p = new Person() {FirstNameIsActive = true,SecondNameIsActive = false};\n\nConsole.WriteLine(predicate(p).ToString()); //prints true\n\n//change the property selector\npropertySelector = person => person.SecondNameIsActive;\n\n//now the predicate uses the new property selector\nConsole.WriteLine(predicate(p).ToString()); //prints false	0
24367393	24366974	Problems about unscaled graphs in a popped windows	Form.AutoSize	0
9924751	9922388	What informations to provide in Xml comments?	/// <summary> Gets information on a customer </summary>\n///\n/// <param name='id'> A customer identifier in the form of a GUID string.\n/// e.g. "{D8C447DD-0E7F-4C8B-A3E5-2C6E160D297B}".\n/// Braces around the GUID are optional.\n/// This parameter must be a valid Guid. </param>\n///\n/// <returns> A Customer record describing the given customer, or\n/// null if the Customer is not found</returns>	0
2085317	2084455	How to use the GridView events	DropDownList ddl = GridViewParent.GridViewChild.Rows[someRowIndex].Cells[someCellIndex].FindControl("DropDownlist1") as DropDownList;\nstring v = ddl.SelectedItem.Text;	0
21364233	21357323	X509 Certificate Public Key Padding	X509Certificate2 x509certificate2 = new X509Certificate2(data);\nbyte[] rsaPublicKey = x509certificate2.PublicKey.EncodedKeyValue.RawData;	0
8445009	8383245	Creating rows in a datagridview using Parallel.ForEach	// Kick off thread\nTask.Factory.StartNew(delegate{\n     foreach(var x in files) {\n         // Do stuff\n\n         // Update calling thread's UI\n         Invoke((Action)(() => {\n              progressBar.PerformStep();\n         }));\n     }\n}	0
1017149	1015642	How to avoid multiple application instances?	[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\nApplication.Run(new Form1());\n   }\n}	0
10340409	10252086	showing inactive selected item in active item list	.Where(a=>a.IsActive == true || a.MeetingTypeId == viewModel.MeetingTypeId)	0
8261061	8261038	How to Create a Stylish progress bar and use it	progressBar1.Style = ProgressBarStyle.Marquee;	0
18376579	18375414	Change URI of main page after app was opened by a custom URI	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n    if (this.NavigationContext.QueryString.ContainsKey("param1"))\n    {\n        string param = this.NavigationContext.QueryString["param1"]; //Get "Param" this QueryString. \n\n        // .. Do Stuff\n\n        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));\n        NavigationService.RemoveBackEntry();\n\n    }\n}	0
13628257	13628124	Seperate range of numbers if in sequence by hyphen and if break in sequence occurs, then comma character	int start,end;  // track start and end\nend = start = arr[0];\nfor (int i = 1; i < arr.Length; i++)\n{\n    // as long as entries are consecutive, move end forward\n    if (arr[i] == (arr[i - 1] + 1))\n    {\n        end = arr[i];\n    }\n    else\n    {\n        // when no longer consecutive, add group to result\n        // depending on whether start=end (single item) or not\n        if (start == end)\n            result += start + ",";\n        else\n            result += start + "-" + end + ",";\n\n        start = end = arr[i];\n    }\n}\n\n// handle the final group\nif (start == end)\n    result += start;\nelse\n    result += start + "-" + end;	0
648106	648003	Ensure ascii values	using System.Linq;\n\n...\n\npublic static bool IsPrintableAscii(this string value)\n{\n    return value != null && value.All(c => c >= 32 && c < 127);\n}	0
13706941	13706553	Extracting data from plain text string	var objRegex = new System.Text.RegularExpressions.Regex(@"^(\d+)=\[([A-Z]+)\] ([A-Z]+) \{Q=(\d+) M=(\d+) B=(\d+) I=([a-z0-9\-]+)\}$");\nvar objMatch = objRegex.Match("000=[GEN] OK {Q=1 M=1 B=002 I=3e5e65656-e5dd-45678-b785-a05656569e}");\nif (objMatch.Success)\n{\n    Console.WriteLine(objMatch.Groups[1].ToString());\n    Console.WriteLine(objMatch.Groups[2].ToString());\n    Console.WriteLine(objMatch.Groups[3].ToString());\n    Console.WriteLine(objMatch.Groups[4].ToString());\n    Console.WriteLine(objMatch.Groups[5].ToString());\n    Console.WriteLine(objMatch.Groups[6].ToString());\n    Console.WriteLine(objMatch.Groups[7].ToString());\n}	0
7348341	7348092	How to put FK into another table using Stored Procedure	CREATE PROCEDURE dbo.EnterLoginData(@Username VARCHAR(50), @Password VARCHAR(50),\n                                    @ContactNo INT, @StateName VARCHAR(50)) \nAS BEGIN \n   DECLARE @StateID INT\n\n   -- check if state already exists\n   IF EXISTS(SELECT * FROM dbo.DGState WHERE DG_State = @StateName)\n\n      -- if it exists - retrieve the DG_StateNo\n      SELECT @StateID = DG_StateNo\n      FROM dbo.DGState \n      WHERE DG_State = @StateName\n\n   ELSE BEGIN\n\n      -- if it doesn't exists - insert new row \n      INSERT INTO dbo.DG_State(DG_State) VALUES(@StateName);\n\n      -- get the newly inserted row's ID using SCOPE_IDENTITY()\n      SELECT @StateID = SCOPE_IDENTITY()\n   END\n\n   INSERT INTO \n       dbo.DGRegion(DG_Username, DG_Password, DG_ContactID, DG_StateNo)\n   VALUES(@Username, @Password, @ContactNo, @StateID)\nEND	0
7441240	7441178	Picking ID's from a file	List<string> ids = File.ReadAllLines(logFile)\n     .Where(l => !String.IsNullOrWhiteSpace(l)) // Trim empty lines \n     .Where(l => l.StartsWith("Filename"))      // Just get ID lines\n     .SelectMany(l => l.Split('-').Skip(1))     // Skip the "FilenameX" section\n     .SelectMany(ids => ids.Split(              // Get IDs (+trim)\n                    new[]{' ',','}, StringSplitOptions.RemoveEmptyEntries)\n                )  \n     .ToList();	0
33966574	33966532	C# accepting only numbers	if(!float.TryParse(Console.ReadLine(), out originalFahrenheit)) //Parse fail\n{\n    //Your error message\n    return; //Exit program\n}	0
27363985	27363527	How to share an address using StreamSocket?	IStorageFile fileToSend = await KnownFolders.PicturesLibrary.GetFileAsync("foo.jpg");\nBasicProperties basicProperties = await fileToSend.GetBasicPropertiesAsync();\nIInputStream streamToSend = await fileToSend.OpenReadAsync();\n\nstring headers = "HTTP/1.1 OK 200\r\n" +\n    "Content-Length:" + basicProperties.Size + "\r\n" +\n    "Content-Type: " + fileToSend.ContentType + "\r\n" +\n    "Connection: Keep-Alive\r\n\r\n";\n\nwriter.WriteString(stringToSend);\nawait writer.StoreAsync();\nwriter.DetachStream();\n\nawait RandomAccessStream.CopyAndCloseAsync(streamToSend, socket.OutputStream);	0
4092683	4092495	C# Sending size of object with serialized object over Async socket connection	SocketPacket socketData = (SocketPacket)asyn.AsyncState;\nsocketData.currentSocket.EndReceive(asyn);\nbyte[] data = socketData.dataBuffer;	0
1952174	1952160	Invoking non static method from static method	public static void StaticMethod()    \n{\n     someInstance.InstanceMethod();\n}\n\npublic void InstanceMethod()\n{\n}	0
12481460	12479535	EmguCV Detect Image Blurriness	_capturedFrames.ForEach(x =>\n {\n    using(var gray = x.Convert<Gray, float>())\n    {\n       IntPtr complexImage = CvInvoke.cvCreateImage(gray.Size, IPL_DEPTH.IPL_DEPTH_32F, gray.NumberOfChannels);\n\n       CvInvoke.cvSetZero(complexImage);  // Initialize all elements to Zero\n       //CvInvoke.cvSetImageCOI(complexImage, 1);\n       CvInvoke.cvCopy(gray.Ptr, complexImage, IntPtr.Zero);\n       //CvInvoke.cvSetImageCOI(complexImage, 0);\n\n       var dft = new Matrix<float>(gray.Rows, gray.Cols, gray.NumberOfChannels);\n       CvInvoke.cvDFT(complexImage, dft, CV_DXT.CV_DXT_FORWARD, 0);\n\n       double min;\n       double max;\n       Point minLoc;\n       Point maxLoc;\n       dft.MinMax(out min, out max, out minLoc, out maxLoc);\n\n       if (max > overallMax)\n       {\n          overallMax = max;\n          index = _capturedFrames.IndexOf(x);\n       }\n\n       CvInvoke.cvReleaseImage(ref complexImage);\n    }\n });	0
4947332	4947169	How to handle authorization in an application?	public bool User.HasRightsFor(Module m, Action a)	0
21420877	21359194	Dictionary of dictionaries	var ret = rs.OfType<DictionaryEntry>()\n  .Where(x => x.Key.ToString().StartsWith("Title"))\n  .ToDictionary(\n    k => k.Value.ToString(),\n    v => rs.OfType<DictionaryEntry>()\n      .Where(x => x.Key.ToString().StartsWith(v.Key.ToString().Replace("Title", "")))\n      .ToDictionary(\n        x => x.Value.ToString().Split('?')[0] + "?",\n        x => x.Value.ToString().Split('?')[1]\n      )\n  );	0
425384	425292	Starting application from data file	//program.cs\n    [STAThread]\n    static void Main(string[] args)\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        if (args.Length > 0)\n        {\n            //launch same form as normal or different\n            Application.Run(new Form1(args));\n        }\n        else\n        {\n            Application.Run(new Form1());\n        }\n    }	0
13572983	13572897	Multiple XML elements overwriting each other	var xDoc = XDocument.Load(fileName);\n\nvar people = xDoc.Element("people");\npeople.Add(new XElement("person", new XElement("name", "name4")));\n\nxDoc.Save(fileName, SaveOptions.None);	0
7414848	7414783	How to get raw hash code from a class that re-implements GetHashCode?	RuntimeHelpers.GetHashCode(object)	0
11526494	11526484	List of object, get property with separator	string allIds = string.Join(", ", list.Select(i => i.Id.ToString()));	0
11099090	11096352	c# button click queueing	private Queue<Button> Button_Queue = new Queue<Button>();\nprivate bool isProcessing = false;\n\nprivate void Button_Click((object sender, EventArgs e){\n\nif(isProcessing){\n    Button_Queue.Enqueue(this);\n}\nelse\n{\n    isProcessing = true;\n\n    // code here\n\n    isProcessing = false;\n    while(Button_Queue.Count > 0){\n        Button_Queue.Dequeue().PerformClick();\n    }\n}	0
34443506	34411991	aspx localization local resources datetime format	cmd.Parameters.AddWithValue("@out", DateTime.ParseExact("01/31/1753 00:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));	0
23627966	23564689	Cannot access Amazon SQS message attributes in C#	IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient();\nReceiveMessageResponse receiveMessage = new ReceiveMessageResponse();\nReceiveMessageRequest request = new ReceiveMessageRequest();\n\n//Specify attribute list\nList<string> AttributesList = new List<string>();\nAttributesList.Add("MESSAGEPRIORITY");\n\n//Assign list and QueueURL to request\nrequest.MessageAttributeNames = AttributesList;\nrequest.QueueUrl = "myURL";\n\n//Receive the message...\nreceiveMessage = sqs.ReceiveMessage(request);\n//Body...\nstring messageBody = receiveMessage.Messages[0].Body;\n//...and attributes\nDictionary<string, MessageAttributeValue> messageAttributes = receiveMessage.Messages[0].MessageAttributes;	0
29034762	29034656	Clean up database from web application after browser disconnects	void Session_End(Object sender, EventArgs E) {\n    //remove temporary table\n}	0
30283673	30283261	Split string in c#	string start = @"NULL ({ 8 9 36 37 }) John ({ 1 }) Loizou ({ 2 3 }) delves ({ 4 }) into ({ 5 })";\n\nstring[] parts = start.Split(')');\n\nstring[] formattedParts = new string[parts.Length - 1];\n\nfor (int i = 0; i < parts.Length - 1; i++)\n{\n    string internalPart = parts[i].Trim();\n    internalPart = internalPart.Replace("(", "");\n    internalPart = internalPart.Replace(" ", ",");\n    internalPart = internalPart.Replace(",{,", " ");\n    internalPart = i < parts.Length - 2 ? internalPart.Replace(",}", "_") : internalPart.Replace(",}", "");\n\n    Console.WriteLine(internalPart);\n}	0
20209153	20208964	Trouble resolving Parameters in Web Forms in 3 tier design	Student objStudent = new Student(); \nobjStudent.Email = ""; \nobjStudent.FirstName = "";\nobjStudent.LastName = ""; \nobjStudent.StudentId = "";\nConfirmation = RequestDirector.EnrolStudent(objStudent, ProgramCode.Text);	0
1885278	1885270	How to find the path of the "Shared Documents" folder from c#?	Path.Combine(Environment.GetEnvironmentVariable("PUBLIC"), "Documents");	0
23834523	23833063	Cleanest way to check for consistency of multiple values in an object list	string1Varies |= foo.string1 != myFooList[0].string1;\nstring2Varies |= foo.string2 != myFooList[0].string2;\nstring3Varies |= foo.string3 != myFooList[0].string3;\nstring4Varies |= foo.string4 != myFooList[0].string4;	0
9830558	9770339	Avatar creation using predefined image sets	Bitmap avatarBitmap = new Bitmap(AvatarWidth, AvatarHeight);\nusing (Graphics g = Graphics.FromImage(avatarBitmap))\n{\n    foreach (Bitmap bitmap in ListOfImagesToDraw)\n    {\n        g.DrawImage(bitmap, 0, 0);\n    }\n}\navatarBitmap.Save(fileName, ImageFormat.Png);	0
8956975	8956871	C# change numbers to small indexes in string	public static string Subscript(this string normal)\n{\n    if(normal == null) return normal;\n\n    var res = new StringBuilder();\n    foreach(var c in normal)\n    {\n        char c1 = c;\n\n        // I'm not quite sure if char.IsDigit(c) returns true for, for example, '?',\n        // so I'm using the safe approach here\n        if (c >= '0' && c <= '9')\n        {\n            // 0x208x is the unicode offset of the subscripted number characters\n            c1 = (char)(c - '0' + 0x2080);\n        }\n        res.Append(c1);\n    }\n\n    return res.ToString();\n}	0
22442950	22442813	WCF Service to insert data to database in Visual Studio C#	public bool InsertBooking(Booking obj)\n    {\n        using(var db  = new Model1Entities())\n        {\n            db.Bookings.Attach(obj);\n            db.Bookings.Add(obj);\n\n            db.SaveChanges();\n        }\n        return true; // or return obj\n    }	0
4406056	4406045	Regular expression to validate date - C#	DateTime.Parse	0
9155676	9155483	Regular Expressions Balancing Group	var r = new Regex(@"\n[^{}]*                  # any non brace stuff.\n\{(                     # First '{' + capturing bracket\n    (?:                 \n    [^{}]               # Match all non-braces\n    |\n    (?<open> \{ )       # Match '{', and capture into 'open'\n    |\n    (?<-open> \} )      # Match '}', and delete the 'open' capture\n    )+                  # Change to * if you want to allow {}\n    (?(open)(?!))       # Fails if 'open' stack isn't empty!\n)\}                     # Last '}' + close capturing bracket\n"; RegexOptions.IgnoreWhitespace);	0
28688065	28686593	Databindings for custom control wont work?	someListControl.DataSource = datatable;\nsomeListControl.DisplayMember = "someAnotherColumnName"\n\nrbs_admin.DataBindings.Add("SelectedButton", datatable, "admin");	0
6977467	6977346	Recommend a design pattern	public interface IActionProvider{\n    public void execute(WorkItem item,ActionType actionType);\n}	0
33971558	33971514	Need to Concat strings in C# windows	var list = new List<string> {"A1", "A2", "A3"};\nvar str = list.Aggregate(string.Empty, (current, item) => current + string.Format("SUM({0}) AS {0},", item));\nstr = str.Remove(str.Length - 1);	0
8669002	8657443	C# Changing background color of an CustomFieldData event	private void Control_CustomCellAppearance(object sender, PivotCustomCellAppearanceEventArgs e)\n    {\n         PivotDrillDownDataSource ds = e.CreateDrillDownDataSource();\n         //get value from the original source according to the row index\n         String myValue = Convert.ToString(ds.GetValue(e.RowIndex, "sourceColumn"));\n\n         //backgroundcolor condition\n         if(myValue.Containts("something"))\n         {\n            e.Background = System.Windows.Media.Brushes.Green; \n         }\n    }	0
10003348	10003310	Parallel Filter Algorithm in C#	myCollection.AsParallel().Where(...);	0
24145440	24145111	Create table based on columns from a CSV file	var lines = File.ReadLines(textBox1.Text);\nList<string> headerRow = lines.ElementAt(0).Split(',').ToList();\nforeach (string header in headerRow)\n{\n   Create table etc.......\n}	0
12317685	12317452	Populate an Enum array via reflection	// create the enum values as object[]\nvar values = value.Split(',')\n  .Select(i => Enum.Parse(property.PropertyType.GetElementType(), i))\n  .ToArray()\n\n// create array of correct type\nArray array = (Array)Activator.CreateInstance(property.PropertyType, values.Length);\n\n// copy the object values to the array\nint i = 0;\nforeach(var value in values)\n{\n  array.SetValue(value, i++);\n}\n\n// set the property\nproperty.SetValue(this, array, null)	0
31742213	31742091	Selenium: Entering Username + Password	private static void LogInAsUser()\n{\n        Driver.FindElement(By.XPath("//a[contains(@href, '#login-window')]")).Click();\n\n        IWebElement username = Driver.FindElement(By.XPath("//input[contains(@id, 'UserName')]" ));\n        IWebElement password = Driver.FindElement(By.XPath("//input[contains(@id, 'Password')]"));\n\n        username.Clear();\n        username.SendKeys("exampleuser@exampleemail.com");\n\n        password.Clear();\n        password.SendKeys("example");\n\n        Driver.FindElement(By.Id("btnLogin")).Click();\n        {\n            Result.Pass(60);\n        }\n}	0
8766066	8766038	How to convert C# hashed byte array to string for passing to API?	byte[] SHA256Result;\nStringBuilder stringBuilder = new StringBuilder();\n\nforeach(byte b in SHA256Result)\n    stringBuilder.AppendFormat("{0:X2}", b);\n\nstring hashString = stringBuilder.ToString();	0
14618259	14618207	Can't get value from listbox	lbSelected.Items.Add(new ListItem(flightPath.name, flightPath.sidField));	0
5652926	5603727	Looping through datagridview and reading the CheckBoxColumn value	foreach (DataGridViewRow row in dgv_labelprint.Rows)\n {\n     if (value.Value == null)\n     {\n\n     }\n     else \n       if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBox"]).FormattedValue)\n       {\n          //Come inside if the checkbox is checked\n          //Do something if checked\n       }\n\n }	0
20594319	20594077	Get data from XML in simple way	namespace ConsoleApplication7\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            XDocument xdoc = XDocument.Load("test.xml");\n            XNamespace dns = "http://schemas.microsoft.com/ado/2007/08/dataservices";\n            //in xml every element should have it's namespace for this reason  I have to concatenate namespace with the name of element  \n            var elementsRes = xdoc.Root.Elements(dns+"element").Select((elt) => new PropertyKeyRef { PropertyName = elt.Element(dns+"DecisionKey").Value.ToString(),PropertyValue = elt.Element(dns+"DecisionText").Value.ToString() }).ToList();\n            foreach (var item in elementsRes)\n            {\n                //your code for the result  \n            }\n\n\n        }\n    }\n    public  class PropertyKeyRef\n    {\n        public string PropertyName\n        { get; set;  }\n        public string PropertyValue\n        { get; set; }\n    }\n}	0
25522689	25522420	How to find a pair of chars within a string in c# netMF?	String.IndexOf(...) != -1	0
18492665	18468719	Retrieving a user principal object using down-level user name	User.Identity.Name	0
4568752	4568726	Date Validation	var myDt=new Date(); \nmyDOB = document.getElementById('dateField').value.split('-');\nmyDate = myDOB[0];\nmyMonth= getMonthInDigit(myDOB[1]);\nmyYear = myDOB[2];\nvar now = new Date();\nmyDt.setFullYear(myYear,myMonth,myDate); //here year, month, date value should be parsed from the value u get\nvar diff = (now.getTime() - myDt.getTime()) \nif(diff < 0){ \n  alert("End Date should not be greater than Today"); \n}	0
18164108	18160991	Open new database connection in scope of TransactionScope without enlisting in the transaction	using (var db = new SqlConnection(constring + ";Enlist=false")) {\n...	0
24524618	24524295	How to set plural collection name in C# mongo driver?	var customers = database.GetCollection(typeof(Customer).Name.Pluralize().ToLower());	0
12447266	12447205	Running another instance of an application from one instance.	private void button1_Click(object sender, EventArgs e)\n{\n    Process p = new Process();\n    p.StartInfo.FileName = Application.ExecutablePath;\n    p.Start();\n}	0
1077769	1077747	Persist a DataContract as XML in a database	public static string Serialize<T>(T obj)\n{\n    StringBuilder sb = new StringBuilder();\n    DataContractSerializer ser = new DataContractSerializer(typeof(T));\n    ser.WriteObject(XmlWriter.Create(sb), obj);\n    return sb.ToString();\n}	0
6252665	6188762	NullReferenceException on if statement with only a bool check	[HttpPost]\npublic ActionResult AddBanking(int id, int? page, int bankId, string q)\n\n[HttpPost]\npublic ActionResult CreateBanking(int id, int? page, int bankId, string query, string \naccountNo, string accountManager, bool? personnal,\nint? branchId, int? selectedId, BankSearchModel data)	0
1439381	1439346	C# - Select XML Descendants with Linq	var items = doc.Descendants("field")\n               .Where(node => (string)node.Attribute("name") == "Name")\n               .Select(node => node.Value.ToString())\n               .ToList();	0
15341493	15303579	Using named parameters in Informix queries in an ASP.net application	IfxCommand query = new IfxCommand("SELECT slm_slmno FROM slmmas WHERE \n    slm_logon = ?");\nquery.Parameters.Add(new IfxParameter("Logon", logon));	0
6064381	6063902	DataGridView - Parent to Child Database Relation - Updating child DataGridView data	// Associate your BSs with your DGVs.\nParentDataGridView.DataSource = parentBindingSource;\nChildDataGridView.DataSource = childBindingSource;\n\n// (Most of) your code here:\nDataSet dSet = new DataSet();\nDataTable ParentList = ListToDataTable(_listOfAllAlbumObjects);\nDataTable ChildList = ListToDataTable(_listOfAllTrackObjects);\ndSet.Tables.AddRange(new DataTable[]{ParentList, ChildList});\nDataColumn parentRelationColumn = ParentList.Columns["AlbumId"];\nDataColumn childRelationColumn = ChildList.Columns["AlbumId"];\ndSet.Relations.Add("ParentToChild", parentRelationColumn, childRelationColumn);\n\n// Let's name this DT to make clear what we're referencing later on.\nParentList.TableName = "ParentListDT";\n\n// Rather than set the data properties on your DGVs, set them in your BindingSources.\nparentBindingSource.DataSource = dSet;\nparentBindingSource.DataMember = "ParentListDT";\n\nchildBindingSource.DataSource = parentBindingSource;\nchildBindingSource.DataMember = "ParentToChild";	0
5209917	5209886	Events from another thread in C#	protected virtual void fileSortProgressMerging(FileSort o, double progress) {\n    Gtk.Application.Invoke (delegate {\n        progressBar.Fraction = progress;\n        progressBar.Text = "Merging...";\n    });    \n}	0
24708036	24706390	Caliburn Micro - How can I inject dependencies into a ViewModel without requiring all its ancestors to have the same dependencies?	var sometype = IoC.Get<ThatType>();	0
13509483	13509007	Removing unrecognized ASCII characters from string	var stripped = Regex.Replace("str?ipped of ba??d char??cters", "[^ -~]", "");\n        Console.WriteLine(stripped); //outputs "stripped of bad characters"	0
915592	915547	How to get groups a group is member of in ActiveDirectory using C#?	directoryEntry.Properties["memberOf"][0]	0
4670316	4670279	How to convert a String[] to an IDictionary<String, String>?	Dictionary<string,string> ArrayToDict(string[] arr)\n{\n    if(arr.Length%2!=0)\n        throw new ArgumentException("Array doesn't contain an even number of entries");\n    Dictionary<string,string> dict=new Dictionary<string,string>();\n    for(int i=0;i<arr.Length/2;i++)\n    {\n      string key=arr[2*i];\n      string value=arr[2*i+1];\n      dict.Add(key,value);\n    }\n    return dict;\n}	0
3775826	3775809	Hiding the Set accessor	class FooBase\n{\n    public int ID { get; protected set; }\n    public string Name { get; protected set; }\n}\n\nclass Foo : FooBase\n{\n    public void SetId(int id) { /* ... */ }\n    public void SetString(string name) { /* ... */ }\n}	0
15304157	15304115	Using EF Code First, how to auto populate HashedPassword column?	public class Admins\n{\n    public int ID { get; set; }\n    public string Username { get; set; }\n    public string HashedPassword { get; set; }\n\n    private string _password;\n    public string Password\n    {\n        get { return _password; }\n        set\n        {\n            _password = value;\n            HashedPassword = HashingMethod(_password);\n        }\n    }\n}	0
1606337	1606263	Projection of dis-joint sets in LINQ	var q = from name in names\n                join email in emails on name equals email.Remove(email.IndexOf('@'))\n                select new\n                {\n                    Name = name,\n                    Email = email\n                };	0
13157649	13157360	Decode a string with nested encodes	string encodedString = "....";\nstring temp = string.Empty;\nstring decodedString = HttpServerUtility.UrlDecode(encodedString);\nwhile (decodedString != temp)\n{\n    temp=decodedString;\n    decodedString = HttpServerUtility.UrlDecode(temp);\n}	0
1769179	1769135	Can you use a C# library in a AMP-server?	regasm.exe	0
34411358	34410261	How can i change asp.net chart control series color?	Series Series1 = new Series();\n        Series Series2 = new Series();\n        Series Series3 = new Series(); \n        Series1.ChartType = SeriesChartType.Column;\n        Series2.ChartType = SeriesChartType.StackedColumn;\n        Series3.ChartType = SeriesChartType.StackedColumn;\n\n        int series1Data=30;\n        int series2Data=40;\n        int series3Data=series2Data-series1Data;\n        series2Data=series1Data;\n\n        Series1.Points.Add(series1Data);\n        Series2.Points.Add(series2Data);\n        Series3.Points.Add(series3Data);\n        Chart1.Series.Add(Series1);\n        Chart1.Series.Add(Series2);\n        Chart1.Series.Add(Series3);	0
8285346	8285260	How to run a executable before showing application main window?	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        Process p = Process.Start(@"exe file path");\n        p.WaitForExit();\n        p.Dispose();\n        base.OnStartup(e);\n    }\n}	0
3385512	3385471	How can I set the selected index of a comboBox base from its valueMember? (C# Window Form)	comboBoxMunicipality.SelectedValue = theMunicipalityIDtoSelect	0
1366550	1366427	Reusing SocketAsyncEventArgs with ReceiveAsync results in infinite loop	private void ProcessReceive( SocketAsyncEventArgs e )\n{\n    AsyncUserToken token = e.UserToken as AsyncUserToken;\n    if( e.ByteTransferred > 0 && e.SocketError == SocketError.Success )\n    {\n        // .. process normally ..\n    }\n    else\n    {\n        CloseClientSocket( e );\n    }\n}\n\nprivate void CloseClientSocket( SocketAsyncEventArgs e )\n{\n    AsyncUserToken token = e.UserToken as AsyncUserToken;\n    try\n    {\n        token.Socket.Shutdown( SocketShutdown.Send );\n    }\n    // throws error if it's already closed\n    catch( Exception ) {}\n    token.Socket.Close();\n}	0
12975350	12975306	Remove item from list using linq	_lstBase\n    .RemoveAll(a => a.Appointmerts.Any(item => appointmentsToCheck.Contains(item)));	0
19374418	13038482	Get the decimal part from a double	string outPut = "0";\n if (MyValue.ToString().Split('.').Length == 2)\n {\n outPut = MyValue.ToString().Split('.')[1].Substring(0, MyValue.ToString().Split('.')[1].Length);\n }\n Console.WriteLine(outPut);	0
19468969	19468845	Unable to programmatically set form background image from picture resource	crossPic.BackgroundImage = Properties.Resources.Moving_Avgs_Cross;	0
15914394	15913423	Keyboard events not firing in RT app	public MainPage()\n{\n    this.InitializeComponent();\n    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;\n    Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;\n}\n\nvoid CoreWindow_KeyUp(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)\n{\n    throw new NotImplementedException();\n}\n\nvoid CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)\n{\n    throw new NotImplementedException();\n}	0
9088204	9088136	Embedded Mono: How do you raise an event in C++?	MonoEvent* monoEvent;\nwhile (klass)\n{\n    void* itr = NULL;\n    while(monoEvent= mono_class_get_events(klass, &itr))\n    {\n       if(0 == strcmp(eventName, mono_event_get_name(monoEvent)))\n         raiseMethod = mono_event_get_raise_method(monoEvent);\n   }\n   klass = mono_class_get_parent(klass);\n}	0
2363066	2362381	Protected Set in VB.Net for a property defined in an interface	Public Class Foo\n  Implements IPersistable(Of Integer)\n  Private m_Id As Integer\n\n  Public ReadOnly Property Id() As Integer Implements IPersistable(Of Integer).Id\n    Get\n      Return m_Id\n    End Get\n  End Property\n\n  Protected Property IdInternal() As Integer\n    Get\n      Return m_Id\n    End Get\n    Set(ByVal value As Integer)\n      m_Id = value\n    End Set\n  End Property\nEnd Class	0
15768802	2691726	How can I remove the selection border on a ListViewItem	using System;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\npublic class MyListView : ListView\n{\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n\n    private const int WM_CHANGEUISTATE = 0x127;\n    private const int UIS_SET = 1;\n    private const int UISF_HIDEFOCUS = 0x1;\n\n    public MyListView()\n    {\n        this.View = View.Details;\n        this.FullRowSelect = true;\n\n        // removes the ugly dotted line around focused item\n        SendMessage(this.Handle, WM_CHANGEUISTATE, MakeLong(UIS_SET, UISF_HIDEFOCUS), 0);\n    }\n\n    private int MakeLong(int wLow, int wHigh)\n    {\n        int low = (int)IntLoWord(wLow);\n        short high = IntLoWord(wHigh);\n        int product = 0x10000 * (int)high;\n        int mkLong = (int)(low | product);\n        return mkLong;\n    }\n\n    private short IntLoWord(int word)\n    {\n        return (short)(word & short.MaxValue);\n    }\n}	0
25894437	25893516	How to add routes to a 3rd party asp.net application, when no access to Application_Start is available	[assembly: PreApplicationStartMethod(typeof(XYZ.SomeClassType), "InitializeCASHttpModule")]	0
21925821	21925245	How to pass method parameter into method's attribute value?	var method = typeof(YourClassType).GetMethod("ViewTransaction");\nvar attribute = method.GetCustomAttribute(typeof(ClaimsPrincipalPermission)) as ClaimsPrincipalPermission;\nattribute.AccountId = 1234;	0
29845553	29458616	Calling varargs method via DynamicMethod	var method = new DynamicMethod("printf", typeof(void), new Type[0], typeof(Program), true);	0
19933026	19932658	How connect to multiple database servers, display combined results?	var orders = ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>()\n    // filter to the relevant connection strings\n    .Where(s => s.ConnectionString.ToLower().Contains("metadata"))\n    .SelectMany(s => {\n         // for each connection string, select a data context        \n         using(var context = new NorthwindEntities(s.ConnectionString)) {\n             // for each context, select all relevant orders\n             return context.Orders.ToArray();\n         } // and dispose of the context when done with it\n     })\n    .Take(10) \n    .ToList();	0
9280220	9280143	How do I access a constructor with user input in C#	object.GetType()	0
4667352	4665069	Linq Expression to Select a Field	public static string GetUniqueId<T, TProperty>(this IQueryable<T> source, int length, Expression<Func<T, TProperty>> idProperty)\n    {\n        bool isUnique = false;\n        string uniqueId = String.Empty;\n        while (!isUnique)\n        {\n            uniqueId = PasswordGenerator.GenerateNoSpecialCharacters(length);\n            if (!String.IsNullOrEmpty(uniqueId))\n            {\n                var expr = Expression.Lambda<Func<T, bool>>(\n                    Expression.Call(idProperty.Body, typeof(string).GetMethod("Equals", new[] { typeof(string) }), Expression.Constant(uniqueId)), idProperty.Parameters);\n                isUnique = source.SingleOrDefault(expr) == null;\n            }\n        }\n\n        return uniqueId;\n    }	0
1315722	1315677	Is there an way to programatically read a file from a TrueCrypt disk into memory?	using System;\nusing System.Diagnostics;\n\nnamespace Test {\n\n    class TrueCrypeStart\n    {\n        static void Main(string[] args)\n        {\n\n            string password = getPassword(...);\n            Process tc= new Process();\n\n            tc.StartInfo.FileName   = "TrueCrypt.exe";\n            tc.StartInfo.Arguments = string.Format("/v \"{0}\" /p \"{1}\" /q", ...mount info ..., password); // for quiet!\n\n            tc.Start();\n        }\n    }\n}	0
2911081	2910928	how to set startup project through coding in c#	Option Strict Off\nOption Explicit Off\nImports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module RecordingModule\nSub TemporaryMacro()\nDTE.ExecuteCommand ("Project.SetasStartUpProject")\nEnd Sub\nEnd Module	0
24044290	24043716	how to write a recursive function for delete nested folder	public ActionResult DeleteLabel(int id)\n        {\n            Delete(id);\n            dbPanAgroDMSContext.SaveChanges();\n            return Json(new { Result = "OK" });\n        }\nprivate void Delete(int id)\n{\n      //For given id get all child ones first            \n          var query = dbPanAgroDMSContext.LabelMaster.Where(x => x.ParentLabelId == id).ToList();\n            foreach(var item in query)\n            {\n                     //for each child ,delet its' childs by calling recursively\n                    Delete(item.Id);\n            }\n            LabelMaster label = dbPanAgroDMSContext.LabelMaster.Find(id);\n            dbPanAgroDMSContext.LabelMaster.Remove(label);\n}	0
15816337	15813513	C# convert one's complement bits to a two's complement long?	if (myLong >> 63 != 0) // The last bit is not 0, meaning myLong is negative\n{\n    myLong = (myLong & (long.MaxValue >> 1)); // sets the leading bit to 0, making myLong positive\n    myLong = ~myLong + 1; // flips all bits and increments by 1\n}\nreturn myLong;\n\n\n// One-liner alternative\nreturn myLong >> 63 != 0 ? (~(myLong & (long.MaxValue >> 1))) + 1 : myLong;	0
15134627	15134471	Indentation in a C# RTB	string text ="1.Bitte blenden Sie ?ber die Layerpalette alle f?r  die Raumverkn?pfung notwendigen zus?tzlichen Layer ein.";\n        int rowMaxLenth = 30;\n        int firstRowIndex = 2;\n            text = text.Insert(firstRowIndex,"\t");\n\n\n\n\n        for (int i = 1; i < text.Length / rowMaxLenth; i++)\n        {\n\n            text= text.Insert((i*rowMaxLenth),"\n\t");\n        }\n        rchTextbox.Text = text;	0
31209536	31209489	Sort integer property of a list<Object>	var propertyList = yourMainList.Select(r=> r.YourProperty)\n                                .OrderBy(r=> r)\n                                .ToList();\n\n//here both lists count should be same\n\nfor(int i = 0; i < yourMainList.Count; i++)\n{\n     yourMainList[i].YourProperty = propertyList[i];\n}	0
30420147	30420074	How to export filtered datagridview to excel using epplus	DataTable filtered = table.DefaultView.ToTable();	0
10287372	10287227	How to turn a point3d array from Cartesian coordinates into Spherical coordinate system?	r = Math.Sqrt(p.X*p.X + p.Y*p.Y + p.Z*p.Z);\nif (r == 0) {\n  theta = 0;\n  phi = 0;\n} else {\n  theta = Math.Acos(p.Z/r);\n  phi = Math.Atan2(p.Y, p.X);\n}	0
9414405	9414052	How do I show text on a label for a specific time (like 3 seconds)?	if (!string.IsNullOrWhiteSpace(value))\n{\n  System.Timers.Timer timer = new System.Timers.Timer(3000) { Enabled = true };\n  timer.Elapsed += (sender, args) =>\n    {\n       this.InfoLabel(string.Empty);\n       timer.Dispose();\n    };\n }	0
4067612	4067068	Conditional DataGridView Formatting	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    // Compare the column to the column you want to format\n    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")\n    {\n        //get the IChessitem you are currently binding, using the index of the current row to access the datasource\n        IChessItem item = sourceList[e.RowIndex];\n        //check the condition\n        if (item == condition)\n        {\n             e.CellStyle.BackColor = Color.Green;\n        }\n    }\n}	0
10032638	10032314	unit testing with objects from 3rd party assemblies	[TestMethod]\npublic void TestMethod2()\n{\n    // Arrange\n    var po = new PrivateObject(typeof(MyObject));\n    var obj = (MyObject)po.Target;\n    // Act\n    var result = obj.Calculate(2);\n    // Assert\n    Assert.AreEqual(3, resul);\n}\n\npublic class MyObject\n{\n    internal MyObject()\n    {\n\n    }\n\n    public int Calculate(int a)\n    {\n        return 1 + a;\n    }\n}	0
27524881	27524814	when click on empty asp:textbox I want to set the visibility of a asp:label to false immediately	protected void Button1_Click(object sender, EventArgs e)\n{\n        if (TextBox1.Text == "")\n            Label1.Visible = true;\n\n}\nprotected void TextBox1_TextChanged(object sender, EventArgs e)\n{\n        if(TextBox1.Text != string.empty)\n        {\n            Label1.Visible = false;\n        }\n\n}	0
8795586	8794713	ObjectDataSource FilterExpression not working with multiple parameters	private void ApplyFilterExpression()\n{\n    var sbFilter = new System.Text.StringBuilder(200);\n\n    if (ddlTypes.SelectedIndex != 0)\n    {\n        sbFilter.Append("type='").Append(ddlTypes.SelectedValue).Append("'");\n    }\n\n    if (ddlUsers.SelectedIndex != 0)\n    {\n        if (sbFilter.Length != 0)\n        {\n            sbFilter.Append(" AND ");\n        }\n        sbFilter.Append("username='").Append(ddlUsers.SelectedValue).Append("'");\n    }\n    if (sbFilter.Length != 0)\n    {\n        dsLogs.FilterExpression = sbFilter.ToString();\n    } else\n    {\n        dsLogs.FilterExpression = null;\n    }\n}	0
22569233	22566308	Translate coordinates to another plane	Matrix transform = Matrix.CreateTranslation(-screenPlane.x, -screenPlane.y, 0);	0
24422873	24411445	How to copy file from Temporary Internet file folder	var path = Path.Combine(\n    Environment.GetFolderPath(Environment.SpecialFolder.InternetCache),\n    "Content.IE5");	0
29365115	29365055	Pass the collection result of a method as params argument	Process(GetWords().ToArray());	0
22466122	22456589	Issues with Cameras	Vector2 offset = new Vector2(GraphicsDeviceManager.PreferredBackBufferWidth / 2, 0); //or whatever you like; new Vector2(100, 0) for an instance\nPosition = player.Position + offset; // plus or minus don't know just test	0
4634475	4634425	Diffrent Hash code for same arrays in C#	public class WrappedArray\n{\n  sbyte[] _inner = new sbyte[10]\n\n  //...\n\n  override public int GetHashCode()\n  {\n    return _inner[0] ^ _inner[1] ^ _inner[2];\n  }\n}	0
12840834	12840767	How to write select query using Linq to XML?	var xDoc = XDocument.Parse(xml);\nvar bases = xDoc.Descendants("base")\n                .Select(b => new\n                {\n                    Id= b.Attribute("id").Value,\n                    Type = b.Attribute("type").Value\n                })\n                .ToList();	0
12875941	12875787	how to store only time in sql server when object data type is DateTime in c#	com.Parameters.Add(\n           new SqlParameter("startTime",SqlDbType.Time)).Value = \n                               WDet.ToString("HH:mm:ss");	0
5125927	5125813	convert a class type object to Intptr	public delegate bool CallBackPtr(int hwnd, int lParam);\n\n\n[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool EnumWindows(CallBackPtr lpEnumFunc, UInt32 lParam);\n\n\nstatic bool callbackreport(int hwnd, int lparam)\n{\n    Console.WriteLine("{0} {1}", hwnd, lparam);\n    return true;\n}\n\nstatic void Main(string[] args)\n{\n    EnumWindows(Program.callbackreport,0);\n}	0
1528500	1528473	C# make a window topmost using a window handle	[DllImport("user32.dll")]\nstatic extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);\n\nstatic readonly IntPtr HWND_TOPMOST = new IntPtr(-1);\nconst UInt32 SWP_NOSIZE = 0x0001;\nconst UInt32 SWP_NOMOVE = 0x0002;\nconst UInt32 SWP_SHOWWINDOW = 0x0040;\n\n// Call this way:\nSetWindowPos(theWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);	0
14722571	14718855	How to create WriteableBitmap from BitmapImage?	// load a jpeg, be sure to have the Pictures Library capability in your manifest\nvar folder = KnownFolders.PicturesLibrary;\nvar file = await folder.GetFileAsync("test.jpg");\nvar data = await FileIO.ReadBufferAsync(file);\n\n// create a stream from the file\nvar ms = new InMemoryRandomAccessStream();\nvar dw = new Windows.Storage.Streams.DataWriter(ms);\ndw.WriteBuffer(data);\nawait dw.StoreAsync();\nms.Seek(0);\n\n// find out how big the image is, don't need this if you already know\nvar bm = new BitmapImage();\nawait bm.SetSourceAsync(ms);\n\n// create a writable bitmap of the right size\nvar wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);\nms.Seek(0);\n\n// load the writable bitpamp from the stream\nawait wb.SetSourceAsync(ms);	0
3570241	3570214	Multiple OracleCommands per OracleConnection	void InvokeCommand (OracleConnection oracleConnection, string tableCommand) \n{\n     using(OracleCommand oracleCommand = new OracleCommand(tableCommand, oracleConnection)) \n     { \n         oracleCommand.ExecuteNonQuery(); \n     } \n}	0
18734812	18734770	c# public const A first	public readonly A first;\npublic readonly B second;	0
14423650	14423635	Timer don't show a month	label2.Text = DateTime.Now.ToString("dd/MM/yyyy");	0
22939379	22939055	c# Determine how many hours in a time period fall within specific hours	DateTime incidentStart = new DateTime(2014, 04, 06, 11, 30, 0, 0, 0);\nDateTime incidentEnd = new DateTime(2014, 04, 08, 10, 15, 0, 0, 0);\nint minutes =  (int)(incidentEnd - incidentStart).TotalMinutes;\nTimeSpan officeOpen = TimeSpan.FromHours(9);\nTimeSpan officeClosed = TimeSpan.FromHours(17);\ndecimal numHours = Enumerable.Range(0, minutes)\n    .Select(min => incidentStart.AddMinutes(min))\n    .Where(dt => dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday \n       &&  dt.TimeOfDay >= officeOpen && dt.TimeOfDay < officeClosed)\n    .GroupBy(dt => new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0, 0)) // round to hour\n    .Count();	0
7318983	7318942	Why don't these abstract methods need to be implemented?	... // no-op operations omitted for simplicity	0
4323503	4323475	how to add condition in object declaration ? EF -	foreach (var item in s) \n    { \n        template = new RSSTemplate() \n        { \n            title = item.titre, \n            description = item.description, \n            doctype = (lang == "E") ? "Spot-II: " : "Spot-IIII " \n        }; \n        t.Add(template); \n    }	0
7533087	7533060	VB.NET Public Property on a single line	public string Stub { get; set; }\n\nPublic Property Stub As String	0
2850351	2850296	How to maintain decimal precision in calculations	ToString()	0
4960025	4193440	n-dimensional Array	public static int NDToOneD(int[] indices, int[] lengths)\n{\n  int ID = 0;\n  for (int i = 0; i < indices.Length; i++)\n  {\n    int offset = 1;\n    for (int j = 0; j < i; j++)\n{\n      offset *= lengths[j];\n}\n    ID += indices[i] * offset;\n  }\n  return ID;\n}\n\n1DtoND(int[] indices, int[] arrayLengths)\n{\n  int[] indices = new int[lengths.Length];\n  for (int i = lengths.Length - 1; i >= 0; i--)\n  {\n    int offset = 1;\n    for (int j = 0; j < i; j++)\n    {\n      offset *= lengths[j];\n    }\n    int remainder = ID % offset;\n    indices[i] = (ID - remainder) / offset;\n    ID = remainder;\n  }\n  return indices;\n}	0
3327876	3327873	Is there any elegant way in LINQ to bucket a collection into a set of lists based on a property	return myCarCollection.GroupBy(r => r.Brand);	0
28539275	28539195	Linq: how to group by, max and orderby	db.Table.GroupBy(x => x.serialcode)\n        .Select(g => g.OrderByDescending(x => x.id).First())\n        .OrderByDescending(x => x.timestamp);	0
14177766	14177725	How to get HttpClient response time when running in parallel	private async void _HttpServerDemo()\n{\n    var info1 = _GetHttpWithTimingInfo("http://google.com");\n    var info2 = _GetHttpWithTimingInfo("http://stackoverflow.com");\n    var info3 = _GetHttpWithTimingInfo("http://twitter.com");\n\n    await Task.WhenAll(info1, info2, info3);\n    Console.WriteLine("Request1 took {0}", info1.Result);\n    Console.WriteLine("Request2 took {0}", info2.Result);\n    Console.WriteLine("Request3 took {0}", info3.Result);\n}\n\nprivate async Task<Tuple<HttpResponseMessage, TimeSpan>> _GetHttpWithTimingInfo(string url)\n{\n    var stopWatch = Stopwatch.StartNew();\n    using (var client = new HttpClient())\n    {\n        var result = await client.GetAsync(url);\n        return new Tuple<HttpResponseMessage, TimeSpan>(result, stopWatch.Elapsed);\n    }\n}	0
17204073	17204045	How can I extract a subset of a dictionary into another one in C#?	var onlyStrings = source.Where(s => s.Key != "number")\n                        .ToDictionary(dict => dict.Key, dict => dict.Value);	0
24524385	24512107	Looping through fields in TextFieldParser in c#	while (!parser.EndOfData)\n            {\n                //Processing row\n                string[] fields = parser.ReadFields();\n\n\n               isNumerical = int.TryParse(fields[0].ToString(), out regSeqNo);\n               mailDate = fields[2].ToString();\n\n            }\n\nInner loop is not required :)	0
5557569	5557547	Creating a dropdown with data from multiple tables	MyDBEntities _entities = new MyDBEntities();\nvar data = from v in _entities.Vendors\n           from c in _entities.Companies\n           where v.CompanyId = c.CompanyId\n           select new ListItem{Value = v.VendorId, Text = c.CompanyName};\n\nreturn data;	0
10052213	10051781	How do I draw a line between ListBoxItems	Color borderColor = Color.Black;\ng.DrawRectangle(new Pen(borderColor), e.Bounds);	0
5187107	5187049	How to refactor method of class with a lot of arguments?	public void MyMethod(MyArguments args)\n{\n    // do stuff\n}	0
29909539	29909471	How to remove remaining unwanted char from a string	mystring = mystring.Trim( '?' );	0
5688836	5688790	Using an attribute to prematurely return from a method	public class MustHaveFooAccessAttribute : AuthorizeAttribute\n{\n    protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        // Return true or false after checking authorization\n    }\n}	0
545248	544884	Code Generation for All CLR supported language using a CodeDomSerializer	//For C# The code would be\nNamespaceX.NamespaceY.ObjectXXX x = new NamespaceX.NamespaceY.ObjectXXX(NamespaceX.NamespaceY.ObjectYYY.PropertyXXX);\nthis.myControl.MyControlProperty = x;\n\n//For C++ The code would be\nNamespaceX::NamespaceY::ObjectXXX x = new NamespaceX::NamespaceY::ObjectXXX(NamespaceX::NamespaceY::ObjectYYY::PropertyXXX);\nthis->myControl->MyControlProperty = x;	0
8527775	8527585	How to remove this strange visual artifact in the corner of ToolStrip Winforms control?	.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;	0
18893648	18893475	porting C++ to C# for decoding a federal gov't FASC-N (Federal Agency Smart Card Number)	if (b1 & b2 != 0)	0
33794817	33788148	Using multiple shells/windows in a Prism application	protected override void InitializeShell()\n    {\n        var sc = new SplashScreen();\n        sc.ShowDialog();\n\n        App.Current.MainWindow = (Window)Shell;\n        App.Current.MainWindow.Show();\n    }	0
1827282	1827259	Negating a method call in an Expression tree	var condition = Expression.Not (contains_call);	0
27621872	27621777	Regex to check to find out items with given character	var singlestar = lst.Where(x =>Regex.Matches(x.Name,  "\\*").Count == 1).ToList();\nvar twostar = lst.Where(x =>Regex.Matches(x.Name,  "\\*\\*").Count == 1).ToList();	0
31043793	31042772	Unable to load DLL 'sqlite3' in SQLite Net Platform WinRT	SQLite for Windows Runtime	0
3212945	3212862	How can I get the local group name for guests/administrators?	S-1-5-32-546	0
21803892	21803847	Checking arguments only in debug mode	System.Diagnostics.Debug.Assert(!double.IsNan(x), "Some message shown if assert fails".)	0
4513986	4513904	Parse a string (in UTC+ format) to date format in either C# or javascript	DateTime dt = DateTime.ParseExact("Sun Dec 12 06:00:00 UTC+0530 2010", \n    "ddd MMM dd HH:mm:ss \"UTC\"zzz yyyy", \n    null);	0
3958046	3958006	Unchecking wrong item in CheckedListBox	foreach(object itemChecked in checkedListBox1) \n    {\n       if(checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked))== CheckState.UnChecked)\n          checkedListBox1.Items.Remove(itemChecked)\n    }	0
23779383	23777738	Using LINQ to get Max Count in Junction Table	var query = from s in Schedules\n                        join ss in Schedules on s.SessionID equals ss.SessionID\n                        join c in ClientSessions on ss.SessionID equals c.SessionID\n                        join l in Locations on s.LocationID equals l.LocationID\n                        where s.CompanyID =  109  && s.LocationID = 4 && (s.ClassDate >= DateTime.Now.AddDays(-7))\n                         group c by new\n                        {\n                            c.ClassDate,\n                            l.LocationName \n                        } into gcs\n                        select new  \n                        {\n                            ClassDate = gcs.Key.ClassDate,\n                            LocationName = gcs.Key.LocationName,\n                            SessionIDCount = gcs.c.Count()\n                        };	0
4904133	4904031	C# Array of Controls	for(int i = 0; i < control.Length; i++)\n{\n    TextBox textBox = control[i] as TextBox;\n    if(textBox != null)\n    {\n        if(textBox.Text == name[i])\n        {\n            exists[i] = true;\n            continue;\n        }\n    }\n}	0
16836953	16835130	How do I send an email through Outlook - letting the user edit it before sending?	var outlookApplication = new Application();\n\nvar inbox = outlookApplication.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);\n\nif (inbox != null)\n{\n   var email = outlookApplication.CreateItem(OlItemType.olMailItem);\n   ...\n   email.Display(true);\n}	0
7206233	7205953	Property explorer: bound data source	[RefreshProperties(RefreshProperties.Repaint)]\n    [AttributeProvider(typeof (IListSource))]\n    [DefaultValue(null)]\n    public new object DataSource { get; set; }	0
10555757	10555682	Nullable object must have a value?	fill.travel.GetValueOrDefault()	0
29017876	29013098	Entity Framework writes in the database while doing a read-only operation	Data Source=C:\data\mydb.sdf;Mode=Read Only	0
20136770	20136732	Linq Query using where clause in windows phone app	var filteredData = \n    from c in loadedCustomData.Descendants("record")\n    where (string)c.Attribute("PON") == "Adapur"\n    select new pincodes1()\n    {\n       PON = (string)c.Attribute("PostOfficeName"),\n       PIN = (string)c.Attribute("Pincode"),\n       DIS = (string)c.Attribute("Districts"),\n       CT = (string)c.Attribute("City"),\n       ST = (string)c.Attribute("State")\n    };	0
10384881	10384803	Get multiple connection strings from web.config	foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)\n    {\n        //use c.Name\n    }	0
15492684	15492589	set datatable first row as grid header	int index = 0;\nforeach(DataTableColumn col in DataTable.Columns)\n{\n  col.ColumnName = DataTable.Rows[0][index].ToString();\n  index++;\n}	0
29880850	29879823	Creating XDocument based on existing XML file	private static XDocument GroupContactsByGroupField(XDocument doc)\n    {\n        var contacts = doc.Descendants("Contact").Select(x => new\n        {\n            FirstName = x.Element("First_Name").Value,\n            LastName = x.Element("Last_Name").Value,\n            Group = x.Element("Group").Value,\n            HomeNumber = x.Element("Home_Number").Value,\n            MobileNumber = x.Element("Mobile_Number").Value\n        });\n        var contactsGroupedByGroup = contacts.GroupBy(x => x.Group);\n\n        var newDoc = new XDocument(new XElement("Groups", contactsGroupedByGroup.Select(x =>\n           new XElement("Group", new XAttribute("Name", x.Key),\n            x.Select(y => new XElement("Contact",\n                new XElement("First_Name", y.FirstName),\n                new XElement("Last_Name", y.LastName),\n                new XElement("Home_Number", y.HomeNumber),\n                new XElement("Mobile_Number", y.MobileNumber)\n            ))))));\n        return newDoc;\n    }	0
1678357	1678211	Window for a newly started process in C# is showing up behind my current open windows	var proc = new Process();\n    proc.StartInfo.FileName = attachmentPath;\n    proc.StartInfo.UseShellExecute = true;\n    proc.Start();\n\n    //Wait for window to spin up\n    proc.WaitForInputIdle();\n    BringWindowToTop(proc.MainWindowHandle);	0
9172509	9172485	calling virtual methods from within base class ctor	private readonly DateTime creationTime = DateTime.UtcNow;	0
15952452	15952208	Call VisibleOnPageLoad of RadWindow Client Side	EnableViewState="false"	0
10299623	10299339	Method with just one line will hit performance?	void Main()\n{\n    var starttime = DateTime.Now;\n    for (var i = 0; i < 1000000000; i++)\n    {\n        if (ValidateRequest()) continue;\n    }\n    var endtime = DateTime.Now;\n    Console.WriteLine(endtime.Subtract(starttime));\n\n    starttime = DateTime.Now;\n    for (var i = 0; i < 100000000; i++)\n    {\n        if (_doc != null) continue;\n    }\n    endtime = DateTime.Now;\n    Console.WriteLine(endtime.Subtract(starttime));\n}\n\nprivate object _doc = null;\n\nprivate bool ValidateRequest()\n    {\n        return _doc != null;\n    }	0
3476172	3475830	add data to DataGrid View through DataSet?	SqlDataAdapter da = new SqlDataAdapter(quryString, con);\nDataSet ds = new DataSet();\nda.Fill(ds, "Emp");\n\n//dataGridView1.DataSource = ds.Tables["Emp"];\ndataGridView1.Columns.Add("EmpID", "ID");\ndataGridView1.Columns.Add("FirstName", "FirstName");\ndataGridView1.Columns.Add("LastName", "LastName");\nint row = ds.Tables["Emp"].Rows.Count - 1;\n\nfor (int r = 0; r<= row; r++)\n{\ndataGridView1.Rows.Add();\ndataGridView1.Rows[r].Cells[0].Value = ds.Tables["Emp"].Rows[r].ItemArray[0];\ndataGridView1.Rows[r].Cells[1].Value = ds.Tables["Emp"].Rows[r].ItemArray[1];\ndataGridView1.Rows[r].Cells[2].Value = ds.Tables["Emp"].Rows[r].ItemArray[2];\n\n}	0
12844306	12843273	File download For Current Request	FileInfo file = new FileInfo(Path.Combine(localFolder, filename));\nint len = (int)file.Length, bytes;\nResponse.ContentType = "text/plain"; //Set the file type here\nResponse.AddHeader "Content-Disposition", "attachment;filename=" + filename; \ncontext.Response.AppendHeader("content-length", len.ToString());\nbyte[] buffer = new byte[1024];\n\nusing(Stream stream = File.OpenRead(path)) {\n    while (len > 0 && (bytes =\n        stream.Read(buffer, 0, buffer.Length)) > 0)\n    {\n        Response.OutputStream.Write(buffer, 0, bytes);\n        len -= bytes;\n    }\n}	0
8994271	8993922	How to pass int[] from c# to c++ using shared memory	int[] src = ...;\nIntPtr target = ...;\nvar bytesToCopy = ...;\n\nfixed(int* intPtr = src) {\n var srcPtr = (byte*)intPtr;\n var targetPtr = (byte*)target;\n for(int i from 0 to bytesToCopy) {\n  targetPtr[i] = srcPtr[i];\n }\n}	0
20652415	20652361	How to get a child of an "object sender" in a method?	Image image = (Image)((Border)sender).Child;\nimage.Source = // Set image source here.	0
27340956	27340759	Get dictionary name by string in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        string dicName = "Group";\n        var fishInfo = new FishInformation();\n        string myKey = "myKey";\n        int myValue = 1;\n        fishInfo.Dictionaries[dicName][myKey] = myValue;\n    }\n}\n\npublic class FishInformation\n{\n    public FishInformation()\n    {\n        Dictionaries = new Dictionary<string, Dictionary<string, int>>()\n        {\n            { "Group", new Dictionary<string, int>() },\n            { "Event", new Dictionary<string, int>() },\n            { "Audience", new Dictionary<string, int>() },\n            { "Type", new Dictionary<string, int>() }\n        };\n    }\n\n    public int FishId { get; set; }\n\n    public Dictionary<string, Dictionary<string, int>> Dictionaries { get; set; }\n\n    public Dictionary<string, int> GroupDic\n    {\n        get { return Dictionaries["Group"]; }\n    }\n\n    // ... other dictionary getters ...\n}	0
10817464	10817233	Getting correct return value on a method call using reflection	IEnumerable<IChangeTrackingEntity>	0
8876530	8876428	Getting all keys and their values from ObjectStateEntry in Entity Framework	private Dictionary<string, object> GetAllKeyValues(ObjectStateEntry entry)\n{\n    var keyValues = new Dictionary<string, object>();\n    var currentValues = entry.CurrentValues;\n    for (int i = 0; i < currentValues.FieldCount; i++)\n    {\n        keyValues.Add(currentValues.GetName(i), currentValues.GetValue(i));\n    }\n    return keyValues;\n}	0
2010404	2001597	How do you randomly zero a bit in an integer?	public static int getBitCount(int bits)\n    {\n        bits = bits - ((bits >> 1) & 0x55555555);\n        bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);\n        return ((bits + (bits >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;\n    }\n\n    public static int flipRandomBit(int data)\n    {\n        int index = random.Next(getBitCount(data));\n        int mask = data;\n\n        for (int i = 0; i < index; i++)\n            mask &= mask - 1;\n        mask ^= mask & (mask - 1);\n\n        return data ^ mask;\n    }	0
18219351	18218914	How to convert linq query into a datatable	//Obviously this is simplified and doesn't include your users stuff, but I think you get the idea.\n\nvar allProjectItems = (from x in db.DateItems\n  where\n    x.Date.ProjectId == projectId\n  select x).ToList();	0
27360880	27360734	How can you see the actual runtype of a type parameter?	? ContextT.GetType().FullName	0
9577441	9577410	C# convert byte[] to string with a charset	System.Text.Encoding enc = System.Text.Encoding.GetEncoding("shift-jis");\nresult.Append(enc.GetString(inputBytes,0,inputBytes.Length));	0
17236347	17235961	Using a class library variable in an aspx page	naming namespaces guidelines	0
14566330	14565986	How to populate collection with values from dataset	foreach (DataRow dr in ds.Tables[0].Rows) {  \n  userorgs.Add(dr["orgs_column"].ToString()); \n}	0
10839604	10839556	An easy way to parse a string to Key Value Pairs	public Person ParsePerson(string line1, string line2) \n{\n  string[] fields1 = line1.Split(new char[] {':', ' '}, StringSplitOptions.RemoveEmptyEntries);\n  string[] fields2 = line2.Split(new char[] {':', ' '}, StringSplitOptions.RemoveEmptyEntries);\n  return new Person() {\n    Balance = fields1[1],\n    Escrow = fields1[3],\n    Acc = fields1[1]\n  };\n}	0
10425166	10425150	Capitalize a single 'char'acter in C#?	Char.ToUpper(ch)	0
20640903	20640116	Case sensitive in regular expression	var result = Regex.IsMatch("Here's some FINDTHIS Text", // the text to search in\n                "FindThis", // this is the text we're looking for\n                RegexOptions.IgnoreCase); // specifies that it's not case sensitive	0
3521956	3521883	Path for image files in project	System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01;	0
8368508	8368380	Reading Outlook Mail with C#	// my-account@myserver.com is the name of my account\n// Unsent mails is the name of the folder I wanted to access\ninboxFolder = nameSpace.Folders["my-account@myserver.com"].Folders["Unsent mails"];\n\nforeach (Microsoft.Office.Interop.Outlook.MailItem mailItem in inboxFolder.Items)\n{\n    if (mailItem.UnRead) // I only process the mail if unread\n    {\n        Console.WriteLine("Accounts: {0}", mailItem.Body);\n    }    \n}	0
3531593	2644540	WPF AutoCompleteBox - How to restrict it choose only from the suggestion list?	public class CurrencySelectorTextBox : AutoCompleteBox\n{    \n    protected override void OnPreviewTextInput(TextCompositionEventArgs e)\n    {            \n        var currencies = this.ItemsSource as IEnumerable<string>;\n        if (currencies == null)\n        {\n            return;\n        }\n\n        if (!currencies.Any(x => x.StartsWith(this.Text + e.Text, true, CultureInfo.CurrentCulture))\n        {\n            e.Handled = true;\n        }\n        else\n        {\n            base.OnPreviewTextInput(e);\n        }            \n    }\n}	0
22852853	22812263	Selected Item of a TreeView	private void ToDoList_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n{\n    TreeViewItem selItem = ((TreeViewItem)ToDoList.SelectedItem);\n\n    //If the parent is a treeviewitem, this is a child node.\n    if (selItem.Parent is TreeViewItem)\n    {\n        //Check if the parent treeviewitem is the standards node.\n        if (((TreeViewItem)selItem.Parent).Header.ToString() == "Standards")\n        {\n            //Do stuff here.\n        }\n    }\n}	0
28559638	28559391	How can i delete between these tags <value></value>	class Program\n{\n    static void Main(string[] args)\n    {\n        XDocument doc = XDocument.Load("XMLFile1.xml");\n\n        foreach(var valueNode in doc.Descendants("data").SelectMany(n=> n.Elements("value")))\n        {\n            valueNode.Value = string.Empty;\n        }            \n    }\n}	0
8209690	8209438	PDF header doesnt get displayed Itextsharp	Document oNewDocument = new Document(PageSize.A4, 20f, 20f, 30f, 10f);\nPdfWriter.GetInstance(oNewDocument, new FileStream(pdfpath + "/" + sSaleInvoicePdf, FileMode.Create));  \n\n//Create some text to add to the header\nChunk text= new Chunk("my text");\nPhrase phHeader = new Phrase();\nphHeader.Add(text);\n\n//Assign the Phrase to PDF Header\nHeaderFooter header = new HeaderFooter(phHeader, false);\n\n//Add the header to the document\noNewDocument.Header = header;	0
3871032	3870917	Converting string to time	TimeSpan.Parse("0:0:0.365")	0
19431824	19429115	How to add permanent tooltips or labels to series of Charttype point to a MSChart c#	Series series = new Series("Default");\nseries.ChartType = SeriesChartType.Point; \n\nfor(int i=0; i<datbase.Count; i++)\n{\n  int index = chart.Series[0].Points.AddXY(database[i].x,database[i].y);\n  chart.Series[0].Points[index].Label = "Your Label Text";\n}	0
2625147	2625117	How do I convert from unicode to single byte in C#?	UnicodeEncoding unicode = new UnicodeEncoding();\nByte[] encodedBytes = unicode.GetBytes(unicodeString);	0
5013813	5013728	Using lambda expressions for method call	service.GetCustomers(sometime, someId, (viewmodels, exception)=>{/*handle callback here*/});	0
32847183	32846764	Group by Multiple Columns And Aggregate Multiple Columns on DATATABLE C#	var products = new DataTable();\nproducts.Columns.Add("ProductName", typeof(string));\nproducts.Columns.Add("Qty1", typeof(int));\nproducts.Columns.Add("Qty2", typeof(int));\nproducts.Columns.Add("Qty3", typeof(int));\n\nproducts.Rows.Add(new object[] {"A", 2, 0, 4});\nproducts.Rows.Add(new object[] {"A", 0, 4, 5});\nproducts.Rows.Add(new object[] {"A", 3, 2, 0});\nproducts.Rows.Add(new object[] {"B", 5, 4, 2});\nproducts.Rows.Add(new object[] {"C", 6, 4, 3});\nproducts.Rows.Add(new object[] {"C", 1, 1, 1});\n\nproducts.AsEnumerable()\n        .GroupBy (p => p.Field<string>("ProductName"))\n        .Select (p => new {\n            Name = p.Key,\n            Qty1 = p.Sum (a => a.Field<int>("Qty1")),\n            Qty2 = p.Sum (a => a.Field<int>("Qty2")),\n            Qty3 = p.Sum (a => a.Field<int>("Qty3"))\n        });	0
28870979	28870764	Handle Event before a Property Changes	public class AClass : INotifyPropertyChanging\n{\n\n    private int aField;\n\n    public int AProperty\n    {\n        get { return aField; }\n        set \n        {\n            OnPropertyChanging("AProperty");\n            aField = value; \n        }\n    }\n\n\n    private void OnPropertyChanging(string propertyName) \n    {\n        PropertyChanging(this, new PropertyChangingEventArgs(propertyName));\n    }\n\n    public event PropertyChangingEventHandler PropertyChanging = delegate { };\n}	0
7511855	7511714	How to trim few bytes of a byte array?	long[] array = ...;\n\nlong[] newArray = array.Skip(16).ToArray();	0
19539454	19539243	Setting other properties when property is set	private string path;\n\npublic string FileName { get; set; }\npublic string Path \n{\n    get \n    { \n        return path; }\n    set \n    { \n        path = value;\n        FileName = Path.GetFileName(value);\n    } \n}	0
13940407	13922314	Can I use zxing to generate a code_128 barcode image?	var content = "123456789012345678";\nvar writer = new BarcodeWriter\n{\n   Format = BarcodeFormat.CODE_128\n};\nvar bitmap = writer.Write(content);	0
1940152	1939070	access a lambda expression outside of the enclosing scope	class Program\n{\n    private static void Main(string[] args)\n    {\n        string result = null;\n        DoSomething(number => result = number.ToString());\n        Console.WriteLine(result);\n    }\n\n    private static void DoSomething(Action<int> func)\n    {\n        func(10);\n    }\n}	0
34482619	34482320	Validate XML using external DTD	settings.XmlResolver = new XmlUrlResolver();	0
17796139	13620223	How to detect Windows 8 Operating system using C# 4.0?	Version win8version = new Version(6, 2, 9200, 0);\n\nif (Environment.OSVersion.Platform == PlatformID.Win32NT &&\n    Environment.OSVersion.Version >= win8version)\n{\n    // its win8 or higher.\n}	0
8592387	8592254	WPF dashboard overlay 3rd party applications	Background="Transparent"\n    WindowStyle="None"\n    Topmost="True"\n    AllowsTransparency="True"	0
14882725	14882655	How to mock protected member of the base class	protected virtual	0
15577570	15577452	Extracting text from ftp address	string s = comboBox1.Text;\nstring path_s = Path.GetFileName( Path.GetDirectoryName( path ) );	0
12920199	12919627	insert more than one row of data from html table using C#?	for (int i = 0, i < Request.form["HiddenFieldHere"], i++)\n{\n        Contacts contact = new Contacts(); \n        contact.CustomerID  = i; \n        contact.ContactDetail=  Request.Form[string.format("contact{0},i)].ToString(); \n}	0
6835739	6835211	Remove ListItem in silverlight	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    if (lbChoices.SelectedItem != null)\n    {\n        ListBoxItem selectedItem = (ListBoxItem)lbChoices.SelectedItem; \n        int selectedIndex = lbChoices.SelectedIndex;\n        if (lbChoices.Items.Count > 1)\n        {\n            if (selectedIndex > 0)\n            {\n                lbChoices.Items.Remove(lbChoices.SelectedItem);\n                lbChoices.Items.Insert(selectedIndex - 1, selectedItem);\n            }\n        }\n    }\n}	0
6451174	6450856	Get ServerContext from web application on IIS	Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.Current;	0
4136302	4080434	How to change chart's x axis interval	chartCheck.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;	0
1991463	1990937	Particular content in richtextbox	using (var helper = new RichTextBox()) {\n    helper.LoadFile(@"c:\temp\test.rtf");\n    // Copy line #6\n    int startRange = helper.GetFirstCharIndexFromLine(5);\n    int endRange = helper.GetFirstCharIndexFromLine(6);\n    helper.SelectionStart = startRange;\n    helper.SelectionLength = endRange - startRange;\n    helper.Copy();\n  }\n  richTextBox1.SelectAll();\n  richTextBox1.Paste();	0
26188418	26188390	debug application in production	try catch	0
23814789	23814513	How do I reference a DLL in a .net script without Visual Studio	//css_reference iTextSharp.dll;	0
30388994	30388844	SaveChangesAsync not updating value in database table	public **async** Task<ActionResult> IncrementRefreshcounter(int id)\n       {\n         using ( var context = new MyDBContext())\n         {\n//at each page refresh i would be passing different id to my controller from view.for eg 1,2,3,4\n         var data=context.Statistics.where(x=>x.Depth==1 && r.Id==id).FirstorDefualt();\n             context.RefreshCounter++;//Increment here RefreshCounter.\n             await context.SaveChangesAsync();\n            }\n        }	0
19670937	19664977	How to create a Parent property for Children of an ObservableCollection TreeView	private DataModel CreateNode(DataModel parentNode)\n{\n    return new DataModel()\n    {\n        Children = \n        { \n            new DataModel() { Parent = parentNode }\n        },\n    };\n}	0
23169558	23169304	filter files by creation date using c#	DirectoryInfo info = new DirectoryInfo(directory);\n\nvar allLines = info.GetFiles("*.txt")\n                   .Where(p => p.CreationTime.Date == DateTime.Today)\n                   .OrderBy(p => p.CreationTime)\n                   .SelectMany(p => File.ReadAllLines(p.FullName));\n\nFile.WriteAllLines(outputFileName, allLines);	0
25506922	25488839	breezejs- how to add a new child entity and attach it to parent's collection of children	entityType.createEntity({ parentIdProperty: 'parent id value' });	0
5076005	5075964	How to add a reference in Visual studio 2010	using System.Net.Mail;	0
34059034	34058200	Is there Any Way to Convert Mongo ObjectId into string by javascript/jquery	var mId = {\n    Timestamp:1448950573,\n    Machine:13565407,\n    Pid:1756,\n    Increment:8888962\n};\n\nfunction getId(mongoId) {\n    var result = \n        pad0(mongoId.Timestamp.toString(16), 8) +\n        pad0(mongoId.Machine.toString(16), 6) +\n        pad0(mongoId.Pid.toString(16), 4) +\n        pad0(mongoId.Increment.toString(16), 6);\n\n    return result;\n}\n\nfunction pad0(str, len) {\n    var zeros = "00000000000000000000000000";\n    if (str.length < len) {\n        return zeros.substr(0, len-str.length) + str;\n    }\n\n    return str;\n}\n\nconsole.log(getId(mId))	0
3663798	3663739	method parameter with multiple interface restrictions	ToString()	0
9525720	9525116	How to clear check boxes after button click	foreach (GridViewRow row in gv.Rows)\n    {\n        var cb = row.FindControl("cbAdd") as CheckBox;\n        if (cb != null)\n           cb.Checked = false;\n\n    }	0
2487075	2487046	Changing an extention method from linq-to-sql to entity framework	public static int GetPublishedArticlesCount(this ObjectQuery<Article> source)	0
31176900	31176850	How to group an array of variables based on flags assigned to them with minimal code in C#	count[0]=20,count[1]=20;count[2]=20;count[3]=20;\nflag[0]=true,flag[1]=true,flag[2]=true,flag[3]=false;\n\nvoid display(int[] count,int[]flag)\n{         \n  for (int i = 0 ; i<=3 ; i++)\n  {\n    if (flag[i])\n    {\n      resetcount[i] = count[i];\n    }\n    else\n    {\n      resetcount[i] += count[i];\n    }	0
13263970	13263931	Convert JSON String to List of Dynamic Objects in C#	dyanmic [] jsonresponseArray= WhatEverJSONConvertor(JSONString);\n\nfor (int i = 0; i < DynamicArray.length; i++)\n{\n      Console.WriteLine(jsonresponseArray[i].AFieldInTheObject);\n}\n\n....\npublic dynamic[] WhatEverJSONConvertor(string json){\n   // parse and create a dynamic type object\n}	0
5255276	5255207	Splitting a string in C#	,(?=[^,]+:.*?)	0
6280767	6280524	How to add nodes to a treeview programatically?	TreeNode rootNode = TreeView.Nodes.Cast<TreeNode>().ToList().Find(n => n.Text.Equals("Root"));\nif (rootNode != null)\n{\n    rootNode.Nodes.Add("child2");\n}	0
13421473	13421433	count non-null elements of IEnumerable<HttpPostedFileBase>	files.Count(file=>file != null && file.ContentLength > 0);	0
18331080	18330733	How to call WCF service from C++	A. Create C++ proxy class from WSDL file\n B. Use that proxy class in your Code for communicating with Server. You will have to maintain Channel opening and closing.	0
26949925	26949857	How can i copy the files in the List<string> to another directory?	public void CopyFiles(string sourceDir, string targetDir)\n{\n    string[] files = Directory.GetFiles(sourceDir);\n    foreach (var fileName in files)\n    {\n        string targetFile = Path.Combine(targetDir, (new FileInfo(fileName)).Name);\n        if (File.Exists(targetFile) == false)\n            File.Copy(fileName, targetFile);\n    }\n}	0
14884681	14753791	Message serialized with XmlMessageFormater refuses to deserialize List<T> member	[XmlArray("LaneSelections"), XmlArrayElement("LaneSelection")]\n public List<LaneSelection> LaneSelections { get; set; }	0
19280069	19279726	find time in c# by use array of byte	byte[] a = new byte[] {224,198,23,200};\nDateTime.FromBinary(BitConverter.ToInt16(a, 0))	0
8269856	8269787	How does fluent nhibernate know which tables to access?	public class ExampleMap : ClassMap<Example>\n  {\n    public ExampleMap()\n    {\n        Table("MyExampleTable");\n        Id(a => a.Id).GeneratedBy.Identity();\n    }\n  }	0
5208558	5208530	sending massive amounts of TCP data	Application.DoEvents()	0
13259615	13259505	How to preserve user input in literal control on postback?	string txtCode = Request.Form["txtCode"];	0
16814880	16812740	Microsoft Report: Use a table in column of another table	public string FirstName { get; set; }\n\npublic string ProjectName { get; set; }	0
5426770	4296176	Prevent uninstall in setup project with OnBeforeUninstall	protected override void OnBeforeUninstall(IDictionary savedState)\n{\n    // Add this\n    base.OnBeforeUninstall(savedState);\n\n    if (ApplicationIsBusy())\n        throw new ApplicationException("Prevent uninstall while application busy.");\n}	0
1638571	1638499	How to get a querystring when it is URLEncoded or has percent characters in ASP.NET	default.aspx?p=??	0
24390494	24390443	Windows Forms - Data Binding to a DataSource properties's property	Binding b = new Binding("Text",\n                        this.meteredSpaceBindingSource,\n                        "ParentMeteredSpace.Name",\n                        true);\nthis.nameTextBox.DataBindings.Add(b);	0
8804003	8803977	InvalidCastException in a LINQ query	row.Field<int?>("Presently_Available") == null ? 0 : row.Field<int>("Presently_Available") ;	0
29003224	29003062	Storing Image into database but facing exception	string InsertImage = "insert into Record(Name,Picture) values(?name,?img)";\n...\ncmd.Parameters.AddWithValue("?name", TextBox2.Text);\n...	0
29428620	29428296	Deserialize json object that contains 3 sub-objects in c#	dynamic o = JsonConvert.DeserializeObject(jsonObj);\n\n            foreach (var item in o)\n            {\n                var x = item.p[0].propP1; // returns 'LoremIpsum'\n                var y = item.[0].propC1; // returns 'xxx1'\n            }	0
19812741	19806779	how to perform sum on distinct different then the group field	var query = from r in generateData().AsEnumerable()\n            group r by r.Field<string>("CustomerLocation") into g\n            select new\n            {\n                CustomerLocation = g.Key,\n                SumSubTotal = g.Sum(r => r.Field<int>("SubTotal")),\n                OrderCount = g.Count(),\n                SumCustomerDebt = \n                      g.GroupBy(r => r.Field<int>("CustomerID"))\n                       .Sum(cg => cg.First().Field<int>("CustomerDebt"))\n            };	0
29677448	27023424	How can I find the index value of the last item in the Application EventLog? (As it doesn't seem to be Entries.Count - 1)	private void eventLog_Application_EntryWritten(object sender, EntryWrittenEventArgs e)\n{\n    // Process e.Entry    \n}	0
9317199	9317110	Convert dictionary to ArrayList	ArrayList result = \n  new ArrayList((from kvp in myDict \n                 select \n                 new { Value=Base64Converter.ConvertBase64(kvp.Key), \n                       Display=kvp.Value }).ToArray());	0
24239594	24239577	Check a list has set of values	list1.Except(list2).Any();	0
20460432	20460387	Cannot get a message to display properly	Response.Redirect("frmManageUsers.aspx");\n            lblError.Text += "User has successfully been added! <br/>";	0
6635202	6635198	How would dependency injection apply to this scenario?	Bind<IEmployee>().To<FooEmployee>().Named("foo");\nBind<IEmployee>().To<BarEmployee>().Named("bar");\nBind<IEmployee>().To<BazEmployee>().Named("baz");	0
3560411	3560393	how to check first character of a string if a letter, any letter	string str = ...;\nbool isLetter = !String.IsNullOrEmpty(str) && Char.IsLetter(str[0]);	0
2041980	2041931	How to determine a full path of a named folder?	Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)	0
28131706	28131657	How can I dynamically select the property of an object in an object list I want to modify the value of	PropertyInfo propertyInfo;\nforeach (YourClass C in list)\n{\n    propertyInfo = C.GetType().GetProperty(propertyName);\n    propertyInfo.SetValue(C, Convert.ChangeType(appendedValue, propertyInfo.PropertyType), null);\n}\nreturn list;	0
9147481	9130151	Linq To excel cant find column in excel	var articleTextValues =\n    // Skip(1) since we don't want the header\n    from line in File.ReadAllLines(@"C:\Users\Timsen\Desktop\QUOTATION.CSV").Skip(1)\n    select line.Split(';')[11];	0
19246107	19245899	Reading Console of another exe in C# hangs UI	class Program\n{\n  static BackgroundWorker _bw = new BackgroundWorker();\n\n  static void Main()\n  {\n    _bw.DoWork += bw_DoWork;\n    _bw.RunWorkerAsync ("Message to worker");\n    Console.ReadLine();\n  }\n\n  static void bw_DoWork (object sender, DoWorkEventArgs e)\n  {\n    // This is called on the worker thread\n    Console.WriteLine (e.Argument);        // writes "Message to worker"\n    // Perform time-consuming task...\n  }\n}	0
22179258	22179072	serial port waiting for 13 bytes to be stored in the buffer	public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)\n    {\n      if (serial.BytesToRead >= 13)\n      {            \n        byte[] buffer = new byte[13];\n        serial.Read(buffer, 0, 13);\n        foreach (var item in buffer)\n        {\n          Console.Write(item.ToString());\n        }\n        Variables.buffering = BitConverter.ToInt64(buffer, 0);\n        Console.WriteLine();\n        Console.WriteLine(Variables.buffering);\n        Thread thread = new Thread(new ThreadStart(() => ThreadExample.ThreadJob(this)));\n        thread.Start();\n        thread.Join();\n      }\n    }	0
12297732	12297580	Converting SQL to LINQ formatting where clause	List<PatientDTO> lstChildProf = objService.GetAllPatient()\n    .Where( l => l.ChildFName == Strings.UCase(Strings.Trim(Txtname.Text))\n            && l.ChildName == Strings.UCase(Strings.Trim(txtSurName.Text)) \n            && l.chiuldMob == Strings.Trim(txtMobile.Text))\n    .ToList<PatientDTO>();	0
14911447	14911415	List<> unable to hold the data of database	Users user = new Users();	0
21033771	21032850	Losing selecteditem when clicking on a empty space in a listbox	public Form1(){\n            InitializeComponent();\n            if (listBox1.Items.Count < 6)\n            {\n\n                listBox1.Height = listBox1.Items.Count*12+9;\n            }\n            else\n            {\n                listBox1.Height = 69;\n            }\n\n        }	0
16110764	16110631	TextBlock + RichTextBox to clipboard	List<RichTextBox> rtbs = scrlPanel.Children.OfType<RichTextBox>().ToList();\n    List<TextBlock> texts = scrlPanel.Children.OfType<TextBlock>().ToList();\n\n    foreach(TextBlock txtb in texts)\n    {\n        RichTextBox rtb = rtbs[texts.indexOf(txtb)];\n        string rtbtext = new TextRange(rtb .Document.ContentStart, rtb .Document.ContentEnd).Text; \n        clipboard.Append(txtb.Text + " " + "::" + Environment.NewLine + rtbtext + Environment.NewLine);\n\n    }\n    Clipboard.SetText(clipboard.ToString());	0
11226574	11210805	How to save selections from a multi-select listbox using Entity Framework	using (var ctx = new FCEntities())\n{\n  var batch = new Batch() { Description = txtDescription.Text, Filename = filename};\n\n  foreach (var department in lstDepartments.CheckedItems)\n  {\n    var dept = (from d in ctx.Departments where d.DepartmentID == ((Department)department).DepartmentID select d).First();\n    batch.Departments.Add(dept);\n  }\n\n  ctx.Batches.AddObject(batch);\n  ctx.SaveChanges();\n}	0
34223680	34223151	Generate a list holding/making mapping between a List<string> and a List<int>	var source = new List<string>() { "a", "a", "b", "c", "a", "b", "b" };\n\nvar map =\n    source\n        .Distinct()\n        .Select((x, n) => new { x, n })\n        .ToDictionary(xn => xn.x, xn => xn.n + 1);\n\nvar result =\n    source\n        .Select(x => new { GroupIP = map[x], Value = x });	0
1426872	1426830	How do I order by NEWID in CoolStorage?	Order.List().OrderedBy("$NEWID()");	0
1751610	1439719	C# get thumbnail from file via windows api	ShellFile shellFile = ShellFile.FromFilePath(pathToYourFile);\nBitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;	0
8971674	8971625	How to remove specific session in asp.net?	Session["userid"] = null;	0
8188881	8188830	How to call non-static method from static method in an aspx.cs code-behind	public static void Data2(string value)\n{\n    ... do something with the value of the hidden field\n}	0
18053694	18053544	XPATH: how to get child nodes	string text = node.SelectSingleNode("./li/strong").InnerText;	0
28382031	28381982	build insert statement error Https has already been declared	(1253,'xkvkvy4ldmfbhlmftqsc','https://res.cloudinary.com/dncu6pqpm/image/upload/v1423309462/rfefef.jpg',1,07/02/2015 11:45:29,)	0
29904676	14921453	Change ComboBox background color in Windows 8	private void ComboBox_Loaded(Object sender, RoutedEventArgs e)\n{\n    var comboBox = sender as ComboBox;\n    var comboBoxTemplate = comboBox.Template;\n    var toggleButton = comboBoxTemplate.FindName("toggleButton", comboBox) as ToggleButton;\n    var toggleButtonTemplate = toggleButton.Template;\n    var border = toggleButtonTemplate.FindName("templateRoot", toggleButton) as Border;\n\n    border.Background = new SolidColorBrush(Colors.Red);\n}	0
1048916	1048871	How to change the format of specified lines in a RichTextBox	int lineCounter = 0;\nforeach(string line in richTextBox1.Lines)\n{\n   //add conditional statement if not selecting all the lines\n   richTextBox.Select(richTextBox.GetFirstCharIndexFromLine(lineCounter), line.Length);\n   richTextBox.SelectionColor = Color.Red;\n   lineCounter++;\n}	0
8609274	8609179	Linq query with null check to get rows in different cases	list.Where(p => (p.SchedulingEndDate == null && DateTime.Now > p.NewsDate)\n                            || (p.SchedulingEndDate != null && p.SchedulingStartDate != null && (DateTime.Now > p.NewsDate && DateTime.Now < p.SchedulingEndDate)));	0
11202260	11202236	How to parse specific characters of a string to integer?	string abc = "07:00 - 19:00";\nx  = int.Parse(abc.Substring(0,2)); // should be 7\ny  = int.Parse(abc.Substring(8,2)); // should be 19	0
9426522	9425140	selectively resolve dependencies of same interface in unity	var container = new UnityContainer();\ncontainer.RegisterType<IInterface, MyFirstClass>("first");\ncontainer.RegisterType<IInterface, MySecondClass>("second");\ncontainer.RegisterType<Class1>(new InjectionConstructor(new ResolvedParameter(typeof(IInterface), "first")));\ncontainer.RegisterType<Class2>(new InjectionConstructor(new ResolvedParameter(typeof(IInterface), "second")));\nvar class1 = container.Resolve<Class1>();\nAssert.IsInstanceOfType(class1.MyClass, typeof(MyFirstClass));\nvar class2 = container.Resolve<Class2>();\nAssert.IsInstanceOfType(class2.MyClass, typeof(MySecondClass));\n\npublic class MyFirstClass : IInterface\n{\n}\n\npublic class MySecondClass : IInterface\n{\n}\n\npublic interface IInterface\n{\n}\n\npublic class Class1\n{\n  public IInterface MyClass { get; set; }\n  public Class1(IInterface myClass)\n  {\n    MyClass = myClass;\n  }\n}\npublic class Class2\n{\n  public IInterface MyClass { get; set; }\n  public Class2(IInterface myClass)\n  {\n    MyClass = myClass;\n  }\n}	0
13813568	11578355	Printing directly to a thermal printer using ESC/POS Commands executed in C# with an interface of TCP/IP	Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n        clientSock.NoDelay = true;\n        IPAddress ip = IPAddress.Parse("192.168.0.18");\n        IPEndPoint remoteEP = new IPEndPoint(ip, 9100);\n        clientSock.Connect(remoteEP);\n        Encoding enc = Encoding.ASCII;\n\n        // Line feed hexadecimal values\n        byte[] bEsc = new byte[4];\n        bEsc[0] = 0x0A;\n        bEsc[1] = 0x0A;\n        bEsc[2] = 0x0A;\n        bEsc[3] = 0x0A;\n\n        // Send the bytes over \n        clientSock.Send(bEsc);\n\n        // Sends an ESC/POS command to the printer to cut the paper\n        string output = Convert.ToChar(29) + "V" + Convert.ToChar(65) + Convert.ToChar(0);\n        char[] array = output.ToCharArray();\n        byte[] byData = enc.GetBytes(array);\n        clientSock.Send(byData);\n        clientSock.Close();	0
21169497	21169408	How to Validate Drop-down inside GridView using JavaScript	dropdowns = gridview.getElementsByTagName('select');	0
18638802	18638575	datetime converter WPF	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n        if (value is DateTime)\n        {\n        DateTime test = (DateTime) value ;\n        string date = test.ToString("d/M/yyyy");\n        return (date);\n        }\n\n         return string.Empty;\n}	0
27863178	27856784	How to make an application crash when a Task throws an exception without waiting the finalizer	namespace ThreadExceptions\n{\n    using System;\n    using System.Threading;\n    using System.Threading.Tasks;\n\n    public static class TaskExtensions\n    {\n        public static Task ObserveExceptions(this Task task)\n        {\n            return task.ContinueWith((t) =>\n            {\n                ThreadPool.QueueUserWorkItem((w) =>\n                {\n                    if (t.Exception != null)\n                    {\n                        foreach (Exception ex in t.Exception.InnerExceptions)\n                        {\n                            throw new TaskException(ex);\n                        }\n                    }\n                });\n            }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.PreferFairness);\n        }\n    }\n}	0
16086417	16086187	C# - Programmatically Opening a Pop-Up Window in Browser	if (function.Equals("PopUp"))\n{\n    Request req = new Request();\n    string result = req.doRequest("function=" + function + "&num=" + trans_number, "http://localhost:4000/Handler.ashx");\n\n    if (result.Equals("True") || result.Equals("true"))\n    {\n        Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.open('http://localhost:4000/Transaction_Number.aspx', '_newtab')", true);\n    }\n\n    Session["result"] = result;\n\n    Page.ClientScript.RegisterStartupScript(Page.GetType(), null, "window.location.href = 'http://localhost:4000/Redirect.aspx.aspx'", true);\n}	0
4513507	4513438	C# Recursion Depth - How Deep can you go	var stackSize = 10000000;\nThread thread = new Thread(new ThreadStart(BigRecursion), stackSize);	0
28959028	28952079	Show custom profile information on manage page MVC5	using Microsoft.AspNet.Identity.EntityFramework;	0
7419714	7419611	Storing lines into a List	// I'm assuming you're using .NET 4\nvar lines = File.ReadLines(filename);\n\nvar components = new List<string>();\nStringBuilder builder = new StringBuilder();\nforeach (var line in lines)\n{\n    if (line.StartsWith("Component: "))\n    {\n        components.Add(builder.ToString());\n        builder = new StringBuilder();\n    }        \n    builder.Append(line);\n    builder.Append("\r\n");\n}\n\n// Get the trailing component\ncomponents.Add(builder.ToString());\n\n// Get rid of the first non-component part\ncomponents.RemoveAt(0);	0
1752975	1752964	How do I make sure a file path is safe in C#?	var fileName = System.IO.Path.GetFileName(userFileName);\nvar targetPath = System.IO.Path.Combine(userDirectory, fileName);	0
15133868	15133786	How to implement a equality method?	public class Client : IEquatable<Client>\n{\n  public string PropertyToCompare;\n  public bool Equals(Client other)\n  {\n    return other.PropertyToCompare == this.PropertyToCompare;\n  }\n}	0
8844512	8844443	Using AutoMapper in the Edit action method in an MVC3 application	Product product = _productRepository.FindProduct(model.ProductId);\n Mapper.Map(model, product);\n _productRepository.SaveChanges();	0
3338409	3338322	Simple C# List<>: given the primary key, how to find and update a nested object property in a List<>?	Ingredient theIngredient =\n(\n  from r in Recipes\n  where r.RecipeId == 2\n  from rs in r.RecipeSteps\n  where rs.RecipeStepID == 14\n  from ing in rs.Ingredients\n  where ing.IngredientId == 5\n  select ing\n).Single()\n\ntheIngredient.name = theName;	0
2956191	2956030	How to differentiate between various exception while calling a webservice in using .net?	try\n{\n    // webservice invocation\n}\ncatch (SoapException ex)\n{\n    // Handle Soap exceptions\n}\ncatch (IOException ex)\n{\n    // Handle IOException\n}\ncatch (Exception ex}\n{\n    // Handler of last resort - any exception not specifically handled above \n    // will be caught here\n}	0
3529133	3529098	Multiple TableLayoutPanels for complex table	table.Dock = DockStyle.Fill;\ndateTable.Dock = DockStyle.Top; \ntextTable.Dock = DockStyle.Fill;	0
10197450	10196675	Parsing XML with custom schema/ namespace	"//*[ local-name() = 'justName']"	0
24717325	24717100	Entity Framework changes my default database name	public BloodGroupContext()\n        : base("name=BloodGroup")\n    {\n\n    }	0
31155017	31154074	Awesomium webBrowser control - How Focus on A TextBox	var javascript = @"(function (){ \n\n           //write JavaScript code here.\n          document.getElementById('username').value = 'only this one';\n          var a = document.getElementById('username');\n          var evnt = a['onclick'];\n\n          if (typeof(evnt) == 'function') {\n             evnt.call(a);\n          }\n         document.getElementById('username').focus();\n\n        })()";\n\n         webBrowser_main.ExecuteJavascript(javascript );	0
16253151	16252996	Converting to file from Convert.ToBase64String	File.WriteAllBytes("1.sdf", Convert.FromBase64String(System.Text.Encoding.ASCII.GetString((byte[])ds.Tables[0].Rows[0][3])));	0
2444064	2444033	get dictionary key by value	var myValue = types.FirstOrDefault(x => x.Value == "one").Key;	0
5955585	5955456	Key value pair as a param in a console app	private static void Main(string[] args)\n{\n   Regex cmdRegEx = new Regex(@"/(?<name>.+?):(?<val>.+)");\n\n   Dictionary<string, string> cmdArgs = new Dictionary<string, string>();\n   foreach (string s in args)\n   {\n      Match m = cmdRegEx.Match(s);\n      if (m.Success)\n      {\n         cmdArgs.Add(m.Groups[1].Value, m.Groups[2].Value);\n      }\n   }\n}	0
32818372	32818149	How to avoid .NET Connection Pool timeouts when inserting 37k rows	void BulkInsert<T>(object p)\n{\n    IEnumerator<T> e = (IEnumerator<T>)p;\n    using (var sqlConnection = new SqlConnection(_connectionString))\n    {\n        while(true)\n        {\n            T item;\n            lock(e)\n            {\n                if (!e.MoveNext())\n                    return;\n                item = e.Current;\n            }\n            var result = sqlConnection.Execute(myQuery, new { ... } );\n        }\n    }\n}	0
26849964	26849963	Adding a linked label for a list of features	int i=0;\n            int yi = 30;\n            int y = 7;\n            int x = 2;\n\n            foreach (var element in agol.orgServices.services)\n            {\n                var linkLabel = new LinkLabel();\n                linkLabel.Name = element.name;\n                linkLabel.Text = element.name + "\n";\n                linkLabel.Location = new Point(x, y);\n                linkLabel.AutoSize = true;\n                linkLabel.Links.Add(new LinkLabel.Link(i, element.name.Length, element.url));\n                ServicesTab.Controls.Add(linkLabel);\n                linkLabel.LinkClicked += (s, z) =>\n                    {\n                       System.Diagnostics.Process.Start(z.Link.LinkData.ToString());\n                    };\n\n                y += yi;\n\n                //finalServiceList += element.name + "\n";\n            }	0
2580309	2579292	How can I add data in foreign key field in Entity Framework?	new System.Data.EntityKey("GenSatisModuleEntities.Rehber", "ID", RehberID);	0
3466165	3465089	How can i Convert Generic List into dataTable?	var dataTable = new DataTable();\n        dataTable.Columns.Add("Col1", list1.GetType().GetGenericArguments().First());\n        dataTable.Columns.Add("Col2", list2.GetType().GetGenericArguments().First());\n        dataTable.Columns.Add("Col3", list3.GetType().GetGenericArguments().First());\n        dataTable.Columns.Add("Col4", list4.GetType().GetGenericArguments().First());\n\n        // assumes they all match on count\n        for (int i = 0; i < list1.Count; i++)\n        {\n            dataTable.Rows.Add(list1[i], \n                               list2[i],\n                               list3[i],\n                               list4[i]);\n        }	0
13004787	13004693	How can I have my Linq select return something different based on a parameter of my method?	string numberFormat = zeroPad ? "D2" : "g";\n...\nValue = ((int) Enum.ToObject(t, x)).ToString(numberFormat),	0
25661755	25661548	C# return linq result as a list from a wcf service method then use it in aspx web forms page	protected void Page_Load(object sender, EventArgs e)\n    {\n        accountInfo_Ref.IaccountInfoSrvcClient accInfoClient = new    accountInfo_Ref.IaccountInfoSrvcClient();\n\n        int id = (int)Session["UserId"];\n\n        List<string> rows = new List<string>(accInfoClient.getAccountInfo(id));\n        // display the first row\n        string row = rows.FirstOrDefault();\n        if (String.IsNullOrEmpty(row))\n        {\n           // record cannot be found\n        }\n        else\n        {\n            string[] details = row.Split(';');\n\n            id_lbl.Text = details[0];\n            order_id_lbl.Text = details[1];\n        }\n    }	0
33480819	33255731	Get the running instance of VersionControlServer(tfs 2015) from Visual Studio 2015 to bind a GettingEventHandler to it	tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serveradressename));\n        versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));\n        versionControl.Getting += new GettingEventHandler(ScanAllNewDocs);	0
16178135	16177964	How to integrate ServiceStack service using protobuf with a non-ServiceStack client?	[DataContract]\npublic class Dto\n{\n    [DataMember(Order=i)]\n    public string PropertyName { get; set; }\n}\n\n[ProtoContract]\npublic class Dto\n{\n    [ProtoMember(i)]\n    public string PropertyName { get; set; }\n}	0
6629373	6628177	Merge Syntax SQL Server 2008	IF EXISTS(\n SELECT 1\n FROM MY_TABLE\n WHERE ITEM='somevalue' AND ENTERDATE='12/31/1999')\n    --Update Statement\n    UPDATE MY_TABLE\n    SET ITEM='anothervalue'\n    WHERE ITEM='somevalue' AND ENTERDATE='12/31/1999'\nELSE\n    --Insert Statement\n    INSERT INTO MY_TABLE\n    (ITEM, ENTERDATE)\n    VALUES\n    ('somevalue', '12/31/1999')	0
19072756	19072579	Why for loop is creating variable with the same address?	class Ref<T>\n{\n    public T Value { get; set; }\n}	0
23301518	23300993	What is the easiest way to get certain values from string if the length changes?	if (userAgent.Contains("MSIE"))\n        {\n            int index = userAgent.IndexOf("MSIE") + 5; // + length of("MSIE ")\n            int length = userAgent.IndexOf(';', index) - index;\n            Logger.Log(Loglevel.Debug, "Browser: Internet Explorer {0}",\n                userAgent.Substring(index, length)); \n        }	0
13891349	13891200	How to get all the possible 3 letter permutations?	var alphabet = "abcdefghijklmnopqrstuvwxyz";\nvar q = alphabet.Select(x => x.ToString());\nint size = 4;\nfor (int i = 0; i < size - 1; i++)\n    q = q.SelectMany(x => alphabet, (x, y) => x + y);\n\nforeach (var item in q)\n    Console.WriteLine(item);	0
8702000	8701981	How to transform a Dictionary<object, string> to a Dictionary<object, List<string>> with LINQ	var newDictionary = oldDictionary.ToDictionary(\n                                       pair => pair.Key,\n                                       pair => new List<string> { pair.Value });	0
64507	64272	How to eliminate flicker in Windows.Forms custom control when scrolling?	SetStyle(ControlStyles.OptimizedDoubleBuffer | \n         ControlStyles.UserPaint |\n         ControlStyles.AllPaintingInWmPaint, true);	0
32380423	32380069	is there an easier way to reverse the order of a DataGridViewSelectedRowCollection?	foreach (DataGridViewRow row in dataGridView1.SelectedRows.Cast<DataGridViewRow>().Reverse()) {\n\n  }	0
22891207	22891023	How can I get post data for asp.net c#	string[] keys = Request.Form.AllKeys;\nvar value = "";\nfor (int i= 0; i < keys.Length; i++) \n{\n   // here you get the name eg test[0].quantity\n   // keys[i];\n   // to get the value you use\n   value = Request.Form[keys[i]];\n}	0
14262616	14262545	Check a text box based on its Text value	Checked='<%# Container.DataItem.ToString().Equals("1") %>'	0
28911901	28909499	Convert DDM to DD Geographic Coordinate Conversion C#	//Parsing the DDM format is left as an excersize to the reader,\n//  as is converting this code snippet into a usable function.\ndouble inputDegrees = 52;\ndouble inputMinutes = 37.9418;\ndouble latitude = inputDegrees + (inputMinutes/60);  // 52.632363	0
14725819	14724676	How to open a dialog center-screeen or center-owner?	dlgViewModel myDlgViewModel = new dlgViewModel();\ndlgView myDlgView = new dlgView();\nmyDlgView.DataContext = miDlgViewModel;\nmyDlgView.Owner = App.Current.MainWindow;\nmyDlgView.ShowDialog();	0
22030671	22026493	SQL Server referential integrity add rows parent table	CREATE TRIGGER trig_insert_ctable\nON ctable\nINSTEAD OF INSERT\nAS\nBEGIN\n    Insert Into ptable\n    Select i.pid, '??'\n    From inserted i\n    Where not exists ( Select * From ptable p where p.pid = i.pid )\n\n    Insert Into ctable\n    Select * From inserted\nEND;	0
1595022	1594997	How do I inherit from Dictionary?	class Foo<TKey,TValue> : Dictionary<TKey, TValue>\n{   \n    Foo():base(){}\n    Foo(int capacity):base(capacity){}\n}	0
21326232	21326059	LINQ SELECT TAKE 1 EACH ROW	var positem = (from a in entities.POSEntries\n    where a.Invoice.AccountID == authLogin.userid && a.Invoice.InvoiceStatusID == 1\n                      select new\n                      {\n                          a.Item.ItemCode,\n                          a.Item.Name,\n                          Quantity = (from b in entities.POSEntries where b.Invoice.AccountID == authLogin.userid && b.Invoice.InvoiceStatusID == 1 select b).Count(),\n                          a.Item.SellingPrice\n                      }).Distinct().ToList();	0
12375422	12375382	Is it possible to set the background of a asp.net gridview cell?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n\n      if(condition)//Replace with your condition\n      {\n        e.Row.Cells[5].Attributes.Add("Style", "background: url(../Images/test.png) no-repeat 5px center\n      }\n    }\n}	0
26153977	26153958	How to read the Key from appsettings?	using System.Linq;\n\nstring key = ConfigurationManager.AppSettings.AllKeys.FirstOrDefault(k => \n                 ConfigurationManager.AppSettings[k] == value);	0
11314740	11314556	Simulate CTRL-C to shutdown Java application on C#	InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C);	0
32261992	32224905	Windows Universal App. Setting icons in code behind	HoursLabel.Text = "\uF017";	0
10979502	10979381	How to Join two Entities and Get Unique Rows from One	var result = entityA.Where(a => !entityB.Any(b => a.Number == b.Number))	0
1316773	1316744	How to make a Window that does not have a Title bar move	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n    const int WM_NCHITTEST = 0x0084;\n    const int HTCLIENT = 1;\n    const int HTCAPTION = 2;\n    protected override void WndProc(ref Message msg)\n    {\n        base.WndProc(ref msg);\n        if (msg.Msg == WM_NCHITTEST && msg.Result == (IntPtr)HTCLIENT)\n        {\n            msg.Result = (IntPtr)HTCAPTION;\n        }\n    }\n}	0
24159793	24144429	How to write following MongoDB query in C# Driver?	_collection.FindAs(typeof(DictionaryDocument), Query.Exists(key)).SetFields(Fields.Include(key)).SetLimit(1);	0
21573612	21554573	Deserializing .Net Object From PHP Using COM	var bytes = new byte[50]; // example byte array\n\nusing(var stream = new MemoryStream(bytes))\n{\n    BinaryFormatter formatter = new BinaryFormatter();\n    var obj = (YourExpectedType)formatter.Deserialize(stream);\n}	0
27532333	27528587	How to verify signatures of XML File in C# with <x509certificate> (not cert file)?	CspParameters cspParams = new CspParameters();\n        cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";\n        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);\n        XmlDocument xmlDoc = new XmlDocument();\n        xmlDoc.PreserveWhitespace = true;\n        xmlDoc.Load("ENVIO_DTE_345508.xml");\n        SignedXml signedXml = new SignedXml(xmlDoc);\n        XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");\n        XmlNodeList certificates = xmlDoc.GetElementsByTagName("X509Certificate");\n        X509Certificate2 dcert2 = new X509Certificate2(Convert.FromBase64String(certificates[0].InnerText));\n        foreach (XmlElement element in nodeList) {\n            signedXml.LoadXml(element);\n            bool passes = signedXml.CheckSignature(dcert2, true);\n        }	0
2403490	2403461	How to get regular expression matches between two boundaries	started:\sProject:\s(.*),	0
12935581	12935398	Get html element by value	HtmlElementCollection col=  webBrowser1.Document.GetElementsByTagName("input");\nHtmlElement wanted;\n\nforeach (HtmlElement item in col)\n{\n    if (item.GetAttribute("value")=="type102")\n    {\n        wanted = item;\n        break;\n    }\n}	0
5669229	5669198	How do I auto-increment a column in my table?	CREATE TABLE [dbo].[HomePageImages](\n    [RecordId] [int] IDENTITY(1,1) NOT NULL,\n    [AlternateText] [varchar](100) NOT NULL,\n    [ImageName] [varchar](50) NOT NULL,\n    [NavigateUrl] [varchar](200) NOT NULL,\n    [ImageUrl]  AS ('/content/homepageimages/'+[ImageName]),\n    [DisplayFrom] [datetime] NULL,\n    [DisplayTo] [datetime] NULL,\n CONSTRAINT [PK_HomePageImages] PRIMARY KEY CLUSTERED \n(\n    [RecordId] ASC\n)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nGO	0
6236685	6236602	How to open a file from Memory Stream	var file = Path.GetTempFileName();\nusing(var fileStream = File.OpenWrite(file))\n{\n    var buffer = memStream.GetBuffer();\n    fileStream.Write(buffer, 0, (int)memStream.Length);\n}	0
7524012	7523995	How can I access the row in a RowCommand event	GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);	0
13962226	13962128	setting Radcombobox value atfer inserting item	int lastitem = 0;\nlastitem = cmb_Contacts.Items.Count;\nthis.cmb_Contacts.SelectedIndex = lastitem - 1;	0
31543162	31542339	How do I decide whether to create a new window when i Click on a button	if (App.Current.MainWindow != null && App.Current.MainWindow.GetType() == typeof(MainWindow))\n{\n    this.Close();\n}\nelse\n{\n    MainWindow main = new MainWindow();\n    App.Current.MainWindow = main;\n    this.Close();\n    main.Show();\n}	0
5974296	5974167	How to read xml node value	using System;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Xml.XPath;\n\nclass Program\n{\n    static void Main()\n    {\n        using (var reader = XmlReader.Create("test.xml"))\n        {\n            var doc = XDocument.Load(reader);\n            var nameTable = reader.NameTable;\n            var namespaceManager = new XmlNamespaceManager(nameTable);\n            namespaceManager.AddNamespace("doc", "urn:tes:doc:Fsur.0.97");\n            var first = doc.XPathSelectElement("//doc:first", namespaceManager);\n            Console.WriteLine(first.Value);\n        }\n    }\n}	0
2139974	2139955	how to return an IList with members of an arbitrary type	IList<T> GetAnimalsOfType<T>() where T : Animal {\n    return dictionary[typeof(T)].OfType<T>().ToList();\n}	0
2034827	2034800	How do you find the group-wise max in LINQ?	var q = (\n    from order in _data.Orders  // ObjectQuery<Order>\n    orderby order.Amount descending select order\n).Distinct().Take(10);	0
24148256	24148182	Connection string without User Id or Password	Server=.\SQLEXPRESS;Database=myDB;Trusted_Connection=True;	0
6694592	6684206	How to fix a CA2000 IDisposable C# compiler warning, when using a global cache	public RegionContext GetContext(string regionCode)\n{\n    RegionContext temp = null;\n    RegionContext rc = null;\n\n    try\n    {\n        if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))\n        {\n            temp = new RegionContext(regionCode);\n            this.contextCache.Add(regionCode.ToUpper(), temp);\n\n            rc = temp;\n            temp = null;\n        }\n\n        return rc;\n    }\n    finally \n    {\n        if ( temp != null ) \n        {\n             temp.Dispose();\n        }\n    }\n}	0
11231607	11231525	write list items based on count	for(var i = 0; i < blah.Count; i++)\n{\n    if(i % 5 == 0)\n        //do new line\n\n    YourPrintFunction(i);\n}	0
21852205	21830727	how to access localDB from Windows Service	"Data Source=(localdb)\\.\\MyInstanceShared;Integrated Security=false;User Id=user;Password=pass321!@"	0
7665779	7662693	Cant connect to TFS 2010 in another domain	cmdkey /add:<yourserver> /user:TEST\user /pass:ThatUsersPassword	0
4303425	4301831	How do I log the XML that my proxy class sends to a web service?	public class ClientMessageLogger : IClientMessageInspector\n{\n    public void AfterReceiveReply(\n        ref System.ServiceModel.Channels.Message reply, object correlationState)\n    {\n        // Do nothing.\n    }\n\n    public object BeforeSendRequest(\n        ref System.ServiceModel.Channels.Message request, IClientChannel channel)\n    {\n        // Create a buffer.\n        MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);\n\n        // Set the request reference to an unspoiled clone.\n        request = buffer.CreateMessage();\n\n        // Make another unspoiled clone to process (taint) locally within this method.\n        Message originalMessage = buffer.CreateMessage();\n\n        // Log the SOAP xml.\n        Log(originalMessage.ToString());\n\n        return null;\n    }\n}	0
24493735	24493558	OleDbCommand Syntax error in INSERT INTO statement	command.CommandText = String.Format("INSERT INTO [{0}] (Tag, [Text]) \n                                    VALUES (?, ?)", newTable + "_Diff");	0
531356	531318	Override Console Close	// Declare the SetConsoleCtrlHandler function\n// as external and receiving a delegate.\n[DllImport("Kernel32")]\npublic static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);\n\n// A delegate type to be used as the handler routine\n// for SetConsoleCtrlHandler.\npublic delegate bool HandlerRoutine(CtrlTypes CtrlType);\n\n// An enumerated type for the control messages\n// sent to the handler routine.\npublic enum CtrlTypes\n{\n    CTRL_C_EVENT = 0,\n    CTRL_BREAK_EVENT,\n    CTRL_CLOSE_EVENT,\n    CTRL_LOGOFF_EVENT = 5,\n    CTRL_SHUTDOWN_EVENT\n}\n\nprivate static bool ConsoleCtrlCheck(CtrlTypes ctrlType)\n{\n    // Put your own handler here\n    return true;\n}\n\n...\n\nSetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);	0
31566311	31565937	INNER JOIN Syntaxe	queryString = @"SELECT * from WGCDOCCAB\nINNER JOIN  wgcnumeradores on wgcdoccab.numdoc = wgcnumerador.numero\n           WHERE serie ='1' AND tipodoc ='FSS' AND contribuinte ='999999990'";	0
11365642	11365007	Entity framework one to many	using (StudentDBContext a = new StudentDBContext())\n{\n   var b = ((from c in a.Student\n           join b in a.Notes on b.StudentId equals c.StudentId into sNotes\n                 from notes in sNotes.DefaultIfEmpty()\n           where c.StudentId==1001\n           select c).SingleOrDefault();\n   if (b != null )\n     ...\n}	0
11643001	11635737	Can we resize Datagridview like resizing windows?	private void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Left)\n        {\n            this.panel1.Height = pictureBox1.Top + e.Y; \n            this.panel1.Width = pictureBox1.Left + e.X;\n        }\n    }	0
13727482	13726864	Download an XmlDocument	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(@"\n<root name='rootAttribute'>\n    <OrderRequest name='one' />\n    <OrderRequest name='two' />\n    <OrderRequest name='three' />\n</root>\n"); // Load some random xml - use function to load whatever you need\n\nMemoryStream ms = new MemoryStream();\nusing (XmlWriter writer = XmlWriter.Create(ms))\n{\n    doc.WriteTo(writer); // Write to memorystream\n}\n\nbyte[] data = ms.ToArray();\nHttpContext.Current.Response.Clear();\nHttpContext.Current.Response.ContentType = "text/xml";\nHttpContext.Current.Response.AddHeader("Content-Disposition:",\n                    "attachment;filename=" + HttpUtility.UrlEncode("samplefile.xml")); // Replace with name here\nHttpContext.Current.Response.BinaryWrite(data);\nHttpContext.Current.Response.End();\nms.Flush(); // Probably not needed\nms.Close();	0
21502945	21502799	PictureEdit image location	using (Form ps = new PhotoSlider())\n    {\n\n        (ps.Controls[0] as PictureEdit).Image= Image.FromFile(e.Item.Caption);\n        ps.ShowDialog();\n    }	0
9045643	9045585	How to close a hidden window (WPF application)?	public partial class MainWindow : Window\n  {\n    private Window1 window2;\n\n    public MainWindow()\n    {\n      InitializeComponent();\n      this.window2 = new Window1();\n\n      this.window2.Show();\n    }\n\n    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n      this.window2.Visibility = System.Windows.Visibility.Hidden;\n    }\n  }	0
20915073	20913472	Entity Framework 6 Loading From DbContext Works But Same Load Doesn't Work In Context Wrapper	public IQueryable<T> Where<T>(Expression<Func<T, bool>> predicate) where T : class \n{ \n    return _Context.Set<T>().AsQueryable().Where(predicate); \n}	0
28775381	28759304	C# How to GetDirectories without 8.3 format names	var files = new DirectoryInfo(@"C:\Path\")\n                   .GetDirectories()\n                   .Select(f => f.Name)\n                   .Where(name => name.StartsWith("3626"));	0
14278434	14278350	how to open listview window explorer in listview control	private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)\n{\n    string pathdoubleClicked = listView1.FocusedItem.Tag.ToString();\n\n    if (System.IO.Directory.Exists(pathdoubleClicked))\n    {\n        PopulateListView(pathdoubleClicked);\n    }\n    else\n    {\n        Process.Start(pathdoubleClicked);\n    }\n\n    // ?\n    simpleStack.Push(pathdoubleClicked);\n}	0
24566712	24566612	Can I create game objects from outside monobehaviour	MonoBehaviour.Instantiate(ObjectPrefab);	0
10090620	10090539	How do i create a running windows process when a c# windows form loads?	//event handler for the form's Load event\npublic void MyWindow_FormLoad(object sender, EventArgs e)\n{\n   //kick off the process you want\n   Process.Start(@"C:\Program Files\MyOtherApp\MyOtherApp.exe");\n}	0
30445652	30444594	Can't find node using HTMLAgilityPack	WebRequest webRequest = HttpWebRequest.Create("http://pastebin.com/raw.php?i=gF0DG08s");\n        webRequest.Method = "GET";\n        string pageSource;\n        using (StreamReader reader = new StreamReader(webRequest.GetResponse().GetResponseStream()))\n        {\n            pageSource = reader.ReadToEnd();\n            HtmlDocument html = new HtmlDocument();\n            html.LoadHtml(pageSource);\n            HtmlNode OurNone = html.DocumentNode.SelectSingleNode("//div[@id='footertext']");\n            if (OurNone != null)\n            {\n                richTextBox1.Text = OurNone.InnerHtml;\n            }\n            else\n            {\n                richTextBox1.Text = "nothing found";\n            }\n        }	0
10572166	10571938	Normalizing text file from abnormal newlines?	List<string> Normalize(string fileName, int size)\n{\n    List<string> result = new List<string>();\n    int blanks = 0;\n\n    foreach (var line in File.ReadAllLines(fileName))\n    {\n        if (line.Trim() == "")\n        {\n            if (blanks++ < size)\n                result.Add("");\n        }\n        else\n        {\n            blanks = 0;\n            results.Add(line);\n        }\n    }\n    return line;\n}	0
22402272	22401624	Converting XML into a c# object	var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyPastedClass));\n MyPastedClass obj;\n using (var xmlStream = new StringReader(str))\n {\n      obj = (MyPastedClass)serializer.Deserialize(xmlStream);\n }	0
5235913	5235858	Combining The Results Of Two Linq Queries Into A Single Var?	var result1 = db1.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });\nvar result2 = db2.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });\n\nvar resultSum = result1.Concat(result2);	0
4084882	4084783	How to add data from a List<List<String>> to a list view	int i=1;\nListViewItem[] lItem =MyList.Select(X=> new ListViewItem(new String[]{i++.ToString()}.Concat(X).ToArray())).ToArray(); \nlistView1.Items.AddRange(lItem);	0
24196638	24196609	How to pad an integer so that n characters are displayed in the resulting string?	i.ToString(string.Format("D{0}", n));	0
14113588	14113558	Your to get the windows installation SID in c#?	using System;\nusing System.Security.Principal;\nusing System.DirectoryServices;\nusing System.Linq;\npublic static SecurityIdentifier GetComputerSid()\n{\n    return new SecurityIdentifier((byte[])new DirectoryEntry(string.Format("WinNT://{0},Computer", Environment.MachineName)).Children.Cast<DirectoryEntry>().First().InvokeGet("objectSID"), 0).AccountDomainSid;\n}	0
8178569	8178445	How to insert a file to an Image datatype in SQL Server 2005	string strSql="INSERT INTO tblPDFInfo (FileImage,PdfFileName,FeedDateTime,HasProcessed) \n               values(@fileBytes,@fileName,@getutcdate,@hasprocessed)";\n\nbyte []bytes=(byte[])fileData;\nobjCmd = new SqlCommand(strSQL, objConn, objTrans);\nobjCmd.Parameters.Add("@fileBytes", SqlDbType.Image,bytes.Length).Value=bytes;\nobjCmd.Parameters.Add("@fileName", SqlDbType.VarChar,100).Value=PDFfileName;\nobjCmd.Parameters.Add("@getutcdate", SqlDbType.DateTime).Value=DateTime.Now;\nobjCmd.Parameters.Add("@hasprocessed", SqlDbType.Bit).Value=0;\n\nobjCmd.ExecuteNonQuery();	0
24669020	24668773	Unable to add a new property the xml for serialization	String.Empty	0
13125810	13125576	Items not removed from List	lanList = (List<UserPlanned>)_jsSerializer.Deserialize(plannedValues,typeof(List<UserPlanned>));\n\nint count = planList.RemoveAll(eup => eup.ID <= -1);\n\nint countItems = planList.Count;	0
29362066	29341828	c# Triple DES encryption with two keys	public byte[] TripleDes(byte[] inputBuffer, byte[] key)\n{\n    using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())\n    {\n        des.Key = key;\n        des.Mode = CipherMode.ECB;\n        des.Padding = PaddingMode.None;\n\n        byte[] result;\n\n        using (MemoryStream stream = new MemoryStream())\n        using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(), CryptoStreamMode.Write))\n        {\n            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);\n            cryptoStream.Flush();\n            //cryptoStream.FlushFinalBlock();\n            result = stream.ToArray();\n        }\n\n        return result;\n    }\n}	0
24681452	24679686	Creating a 'NOT NULL' SQLite column without specifying a default value	CREATE TABLE MyTable (\n    ID INTEGER PRIMARY KEY AUTOINCREMENT,\n    Col1 nvarchar NOT NULL\n)	0
7136613	7136573	Catch windows shutdown event in a wpf application	Application.SessionEnding	0
3334618	3333900	Expression in DataTable	string FilterExpression = "Symbol = 'AAA'";	0
762372	761130	Bind multiple TextBoxes to one struct in WPF	public class MyModel\n{\n    public int Width{ get; set; }\n    public int Height{ get; set; }\n\n    public Size Size{ get{ return new Size( Width, Height ); }}\n};	0
18181730	18181659	Grab only part of the string at dynamic location	var array1 =  a.Split(';');\n\n// check the array length if it's needed to avoid \n// IndexOutOfRangeException exception\nvar array2 =  array1[1].Split(',');\n\nvar yourNumber = array2[array2.Length - 2]	0
13834558	13833423	How can i differentiate items in list in c#	public static void CopyPropertiesTo<T>(this T source, T dest)\n        {\n            var plist = from prop in typeof(T).GetProperties() where prop.CanRead && prop.CanWrite select prop;\n\n            foreach (PropertyInfo prop in plist)\n            {\n                prop.SetValue(dest, prop.GetValue(source, null), null);\n            }\n        }	0
22614756	22614564	Filling ViewBag from database returns NullReferenceException	[HttpGet]\npublic ActionResult Test()\n{\n    using (var context = new MyDataContext())\n    {\n        ViewBag.Roles = context.Roles.ToList();\n        return View();\n    }\n}	0
4741024	4740977	Threading: Variable Access and Termination of a Thread	static string preanswer;\n      static decimal answer = 0;\n\n      static void Main() \n      {\n       int score = 0;\n       //string preanswer;\n       //decimal answer = 0;\n...	0
5483784	5483678	How to get a value from attribute?	// Get all the attributes for the class\nAttribute[] _attributes = Attribute.GetCustomAttributes(typeof(NameOfYourClass));\n\n// Get a value from the first attribute of the given type assuming there is one\nint _i = _attributes.Where(_a => _a is EntityBindingAttribute).First().I;	0
31105427	31104335	Ignore Base Class Properties in Json.NET Serialization	[JsonObject]\npublic class Polygon : IEnumerable<Point>\n{\n    public List<Point> Vertices { get; set; }\n    public AxisAlignedRectangle Envelope { get; set; }\n\n    public virtual bool ShouldSerializeEnvelope()\n    {\n        return true;\n    }\n}\n\npublic class AxisAlignedRectangle : Polygon\n{\n    public double Left { get; set; }\n    ...\n\n    public override bool ShouldSerializeEnvelope()\n    {\n        return false;\n    }\n}	0
29054721	29054420	Programmatically create a 3D prism from location of its vertices	var alt = new[] { 1, -1 };\nvar result = ( from i in alt\n               from j in alt\n               from k in alt\n               select new Vector3(i * 1, j * 2, k * 3)\n              ).ToList();	0
11182687	11182535	Retrieving salt stored as plaintext alongside ciphertext using C#	yourString.Substring(0, yourString.IndexOf(Environment.NewLine));	0
2949092	2949081	How to make HTML Helpers that supports generic type?	public static class EmptyOrNullHelper\n{\n\n    public static string EmptyOrNull<T>(this HtmlHelper helper, IQueryable<T> type)\n    {\n        //Code\n    }\n\n}	0
16030325	16030257	Linq to replace dataTable values	IEnumerable<DataRow> rows = from row in DataTableObj.AsEnumerable()\n                              select row;\nforeach (DataRow row in rows)\n{\n   if(Convert.ToInt32(row["FKID1"])==-1)\n    row["FKID1"] = DBNull.Value;\n   if(Convert.ToInt32(row["FKID2"])==-1)\n    row["FKID2"] = DBNull.Value;\n}	0
24246688	24246640	How to format textbox to display SSN as the user types	yourMaskedTextBox.Mask = "000-00-0000";	0
14495443	14495390	SQL Connection String with Instance Parameter	const string connStringWork = "Data Source=server\\instance;Initial Catalog=db;Integrated Security=True;Application Name=??";\n\nusing (SqlConnection conn = new SqlConnection(connStringWork))\n{\n\n}	0
12857203	12856995	split String accept some characters	var result = input.Split(new[] { '"' }).SelectMany((s, i) =>\n  {\n      if (i%2 == 1) return new[] {s};\n      return s.Split(new[] { ' ', ',', ':', '|', '@', '(', ')', '[', ']', ';' },\n                               StringSplitOptions.RemoveEmptyEntries);\n  }).ToList();	0
32011980	32010796	Multiple levels of inheritance with Entity Framework using TPH	public abstract class TPHBase\n{\n    public int ID { get; set; }\n\n    public string CommonProperty { get; set; }\n}\n\npublic class TPHChild1 : TPHBase\n{\n    public string Child1Property { get; set; }\n}\n\npublic abstract class TPHChild2 : TPHBase\n{\n    public int? Child2Property { get; set; }\n}\n\npublic class TPHChild3 : TPHChild2\n{\n    public int? Child3Property { get; set; }\n}\n\npublic class TPHChild4 : TPHChild2\n{\n    public int? Child4Property { get; set; }\n}\n\nprotected override void OnModelCreating( DbModelBuilder modelBuilder )\n{\n    modelBuilder.Entity<TPHBase>()\n            .ToTable( "TPHBase" )\n            .Map<TPHChild1>( m => m.Requires( "Dyskryminator" ).HasValue( "c1" ) )\n            .Map<TPHChild3>( m => m.Requires( "Dyskryminator" ).HasValue( "c3" ) )\n            .Map<TPHChild4>( m => m.Requires( "Dyskryminator" ).HasValue( "c4" ) );\n\n    ...	0
26169820	26169326	Performance penalty between for loop and Parallel.For() with MaxDegreeOfParallelism of 1	for (int z = 0; z < 5; z++)\n{\n    int iterations = 15000;\n\n    Stopwatch s = Stopwatch.StartNew();\n\n    for (int i = 0; i < iterations; i++)        \n        Thread.Sleep(1);        \n\n    s.Stop();\n\n    Console.WriteLine("#{0}:Elapsed (for): {1:#,0}ms", z, ((double)s.ElapsedTicks / (double)Stopwatch.Frequency) * 1000);\n\n    var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };\n    s = Stopwatch.StartNew();\n\n    Parallel.For(0, iterations, options, (i) => Thread.Sleep(1));\n\n    s.Stop();\n\n    Console.WriteLine("#{0}: Elapsed (parallel): {1:#,0}ms", z, ((double)s.ElapsedTicks / (double)Stopwatch.Frequency) * 1000);\n}	0
27502887	27440994	What is the fastest way to load a wide row from Cassandra to C#?	var query = "SELECT * from grouped_feature_support WHERE" + \n            " algorithm_id = ? AND group_by_feature_id = ? " +\n            " AND select_feature_id = ? AND group_by_feature_value = ?";\n//Prepare the query once in your application lifetime\nvar ps = session.Prepare(query);\n//Reuse the prepared statement by binding different parameters to it\nvar rs = session.Execute(ps.Bind(parameters));\nforeach (var row in rs)\n{\n  //The enumerator will yield all the rows from Cassandra\n  //Retrieving them in the back in blocks of 5000 (determined by the pagesize).\n}\n//You can also use a IEnumerable<T> Linq Extensions to filter\nvar filteredRows = rs.Where(r => r.GetValue<long>("support") > 2);	0
3306633	3306600	C#: how to take a screenshot of a portion of screen	Rectangle rect = new Rectangle(0, 0, 100, 100);\n        Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);\n        Graphics g = Graphics.FromImage(bmp);\n        g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);\n        bmp.Save(fileName, ImageFormat.Jpeg);	0
2880734	2880643	Regex to replace tr tag with th tag anywhere in html file	Regex.Replace(html, @"(?<=<(/)?)th(?=[\s>])", "tr", RegexOptions.IgnoreCase);	0
14881967	14880827	Reading / writing new line character from/to xml	btn.ToolTip = System.Text.RegularExpressions.Regex.Unescape(keys["A1"]);	0
13337781	13337689	Searching for patterns in String, and removing	\b(?:\d[ -]*?){13,16}\b	0
10173549	10167009	deserialize json to object c# on windows phone	byte[] data = Encoding.UTF8.GetBytes(jsonString);\nMemoryStream memStream = new MemoryStream(data);\nDataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Car));\nCar car = (Car) serializer.ReadObject(memStream);	0
16909686	14941340	How to hide features and selectable folders/drives on an OpenFileDialog window?	OpenDialogPlaces o = new OpenDialogPlaces();\n//o.Places.Add(18);\n//o.Places.Add(5);\n//o.Places.Add(6);\no.Init();\no.OpenDialog.ShowDialog();\no.Reset();	0
26960584	26960559	Create a dynamic window to scan an image in C#	for(int x=-3; x <= 3; x++)\n{\n    for (int y=-3; y <= 3; y++)\n    {\n        IM[i+ x, j + y] //theres your reference, if you're going to get the average you can add it to a sum or whatever\n    }\n}	0
7011836	7011567	C++ <--> C# modify a marshalled array of bytes	public ushort GetBytesFromBlaster(IntPtr dataBytes, int arraySize)\n{\n    byte[] managed = new byte[arraySize];\n    Marshal.Copy(dataBytes, managed, 0, arraySize);\n    managed[0] = (byte)'a';\n    managed[1] = (byte)'b';\n    managed[2] = (byte)'c';\n    Marshal.Copy(managed, 0, dataBytes, arraySize);\n    return 3;\n}	0
24443334	24441277	SUM and GROUPBY lambda expression on DataDomainService	return this.ObjectContext.vwAplicacoes\n       .Where(d => d.DataOper > pstrDataInicio && d.DataOper < pstrDataFinal)\n       .GroupBy(x => new {x.CPFCNPJCliente,x.NomeCliente,x.TipoClientePFPJ,x.CodInternoCliente,x.CodTipoOper})\n       .Select(k => new {key = k.Key, \n                         totalLCValor = k.Sum(x=>x.LCValor),\n                         totalLCQtde = k.Sum(x=>x.LCQtde),\n                         totalLDValor = k.Sum(x=>x.LDValor),\n                         totalLDQtde = k.Sum(x=>x.LDQtde)})	0
27795116	27795056	Allow C# to accept and deal with POST requests	public class receivepost : IHttpHandler, System.Web.SessionState.IRequiresSessionState\n{\n\n    public void ProcessRequest(HttpContext context)\n    {\n\n\n        if (context.Request.Form["order_id"] != null)\n        {\n\n            int orderID = Convert.ToInt32(context.Request["order_id"]);\n\n            // SQL SYNTAX TO SAVE ORDERID IN TO DATABASE\n        }\n\n    }\n\n\n\n    public bool IsReusable\n    {\n        get\n        {\n            return false;\n        }\n    }\n\n}	0
25850306	25844373	Android AlertDialog, don't dismiss on key press, but on touch	AlertDialog dialog = new AlertDialog.Builder(this)\n    .SetTitle("blabla")\n    .SetMessage("blablabla")\n    .SetPositiveButton("OK", (sender, e) => {\n        SetResult(Result.Ok, oIntent);\n        Finish();\n    })\n    .SetNegativeButton("Cancel", (sender, e) => { })\n    .Show(); // Important, or GetButton() will return null\n\n// Now disable the default dismissing actions on key presses.\ndialog.GetButton((int)DialogButtonType.Positive).KeyPress += (sender, e) => { };\ndialog.GetButton((int)DialogButtonType.Negative).KeyPress += (sender, e) => { };	0
14022512	14022486	Selecting items using LinqtoEntities lambda C#	var query = (from c in categories\n         from r in c.Recipes\n         where r.IsCompanyRecipe == true\n         select c);	0
13193245	13193188	Datagridview colour changing	using System.Drawing;	0
18453726	18453654	getting specific x items from list using linq	var il = (from i in AllItems\n    where i.Iid == item.Iid\n    select i).Take(Int32.Parse(item.amount)).ToList();	0
25013406	25013275	get same result from c# linq as SQL statement	var details= (from r in NotificatieRecID\n              join n in Notificatie on r.Notificatie=n.ID\n              where n.Verzonden=0 &&\n              (from t in NotificatieRecID\n               group t by t.RelatieNr into grp\n               where grp.Count()>1\n               select grp.Key).Contains(r.relatieNr)\n              select new {\n                 Notificate=r.Notificatie,\n                 RelatieNr=r.RelatieNr\n  }).Distinct();	0
7957919	7873775	Call another WCF Data Service from WCF RIA Service using Entity Framework	namespace YourApp.Web \n{ \n    [EnableClientAccess] \n    public class WcfRelayDomainService : DomainService \n    { \n        public IQueryable<Restaurant> GetRestaurants() \n        { \n            // You should create a method that wraps your WCF call\n            // and returns the result as IQueryable;\n            IQueryable<MyDto> mydtos = RemoteWCF.QueryMethod().ToQueryable();\n            return mydtos; \n        } \n        public void UpdateDTO(MyDto dto) \n        { \n            // For update or delete, wrap the calls to the remote\n            // service in your RIA services like this.\n            RemoteWCF.UpdateMethod(dto);\n        }\n    }\n}	0
18546237	18546159	How to transfer string from listbox to richtextbox	//DoubleClick event handler for your listBox1\nprivate void listBox1_DoubleClick(object sender, EventArgs e){\n   richTextBox1.SelectedText = listBox1.SelectedItem.ToString();\n}	0
2268407	2266890	WPF: TreeViewItem bound to an ICommand	private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n    {\n        if (sender != null)\n        {\n            var treeView = sender as TreeView;\n            if (treeView != null)\n            {\n                var commandViewModel = treeView.SelectedItem as CommandViewModel;\n                if (commandViewModel != null)\n                {\n                    var mi = commandViewModel.Command.GetType().GetMethod("Execute");\n                    mi.Invoke(commandViewModel.Command, new Object[] {null});\n                }\n            }\n        }\n    }	0
9412115	9412047	c# - Total of all rows within a specific column	DataSet ds = new DataSet();\n        int Sum = 0;\n        foreach (DataRow dRow in ds.Tables[2].Rows)\n        {\n            Sum += Convert.ToInt32(dRow["Required Column"]);\n        }	0
32620649	32620491	Finding the sum of the values in a 2D Array in C#	//finds the sum of all values\npublic int SumArray(int[,] array)\n{\n    int total = 0;\n    // Iterate through the first dimension of the array\n    for (int i = 0; i < array.GetLength(0); i++)\n    {\n        // Iterate through the second dimension\n        for (int j = 0; j < array.GetLength(1); j++)\n        {\n            // Add the value at this location to the total\n            // (+= is shorthand for saying total = total + <something>)\n            total += array[i, j];\n        }\n    }\n    return total;\n}	0
13660783	13660650	Update data information on the screen/display	var worker = new BackgroundWorker();\n\nworker.DoWork += (s, e) =>\n{\n    Thread.Sleep(1500); // Some processing\n\n    Dispatcher.BeginInvoke(() => txMsg.Text = "Hello"); // Update the UI\n\n    Thread.Sleep(1500); // More processing\n};\n\nworker.RunWorkerAsync();	0
4939395	4939219	WPF full screen on maximize	private bool _inStateChange;\n\nprotected override void OnStateChanged(EventArgs e)\n{\n  if (WindowState == WindowState.Maximized && !_inStateChange)\n  {\n    _inStateChange = true;\n    WindowState = WindowState.Normal;\n    WindowStyle = WindowStyle.None;\n    WindowState = WindowState.Maximized;\n    ResizeMode = ResizeMode.NoResize;\n    _inStateChange = false;\n  }\n  base.OnStateChanged(e);\n}	0
10230548	10206761	C# wpf listbox dispaly more than one memberpath	string uriGroup = "http://localhost:8000/Service/Group"; //rest based http GET\n    private void button14_Click(object sender, EventArgs e)\n    {\n    XDocument xDoc = XDocument.Load(uriGroup); //Load the uri into the xdoc\n    var groups = xDoc.Descendants("Group") //descendants of xml query "Group" \n        .Select(n => new\n        {\n            GroupID = n.Element("GroudID").Value,\n            Group = n.Element("GroupName").Value, //first "Group" Sets the column title, second sets the Element to be listed in this case "GroupName" from my service. \n\n        })\n        .ToList();\n\n    dataGridView2.DataSource = groups;	0
24514270	24514114	set SqlConnection string properly	string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();	0
20552583	20349220	Get x:Uid propertry of TextBlock in Metro	public void Setup()\n{\n    var r = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();\n    r.QualifierValues.MapChanged += QualifierValues_MapChanged;\n}\n\npublic void Cleanup()\n{\n    var r = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();\n    r.QualifierValues.MapChanged -= QualifierValues_MapChanged;\n}\n\nvoid QualifierValues_MapChanged(Windows.Foundation.Collections.IObservableMap<string, string> sender, Windows.Foundation.Collections.IMapChangedEventArgs<string> @event)\n{\n    // you can fetch the default, and test if you need change\n    string d;\n    var m = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.DefaultContext.QualifierValues;\n    if (!m.TryGetValue("Language", out d))\n        return;\n\n    // you can set your own or use the first (default)\n    var l = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();\n    Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = l;\n}	0
6768266	6768151	Get values from textfile with C#	using System;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        var data = File\n            .ReadAllLines("test.txt")\n            .Select(x => x.Split('='))\n            .Where(x => x.Length > 1)\n            .ToDictionary(x => x[0].Trim(), x => x[1]);\n\n        Console.WriteLine("profile: {0}", data["profile"]);\n        Console.WriteLine("birthday: {0}", data["birthday"]);\n        Console.WriteLine("manufacturer: {0}", data["manufacturer"]);\n    }\n}	0
1445001	1444983	pass parameters in reflection C#	mymethod.Invoke(obj, new object[] { b, Rectangle.Empty });	0
1843081	1833938	Where to keep things like connectionstrings in an IoC pattern?	public class ConnectionStringProvider {\n    public string ConnectionString {\n        get{\n             // your impl here\n        }\n    }\n}\n\npublic class UserRepository {\n   public UserRepository(ConnectionStringProvider provider){\n        // set internal field here to use later\n        // with db connection\n   }\n}	0
8562209	8562069	Find and replace - should I use Regex?	var regex = new RegEx(("$1(\d\s)$2([a-z])");  // Set up your regex with named groups\nvar result = regex.Replace("inputstring", "$2 $1");  // Replace input string with the given text, including anything matched in the named groups $1 and $2	0
2412488	2412436	Loading xml into a xdoc, and then initializing an object	var templates = doc.Elements("template")\n.FirstOrDefault(template=>template.Attribute("name").Value.Equals("someKey")\n.Select(template=>new Template\n{\n    Title =  template.Elements("node").FirstOrDefault(node=>node.Attribute("name").Value.Equals("title")).Value,\n    Body = template.Elements("node").FirstOrDefault(node=>node.Attribute("name").Value.Equals("body")).Value\n });	0
20639233	20639039	adding querystring to collection from controller	// Create new url\n    string url = Request.UrlReferrer.AbsolutePath \n                         + "?" + querystring.ToString();\n\n    return Redirect(url); // redirect	0
8918060	8918041	How to get IP address of network adapter	System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[0].ToString();	0
3083199	3083101	How to call a shared function which its name came as a parameter	namespace TestProgram {\n\n  public static class TestClass {\n\n    public static void Test() {\n      Console.WriteLine("Success!");\n    }\n\n  }\n\n  class Program {\n\n    public static void CallMethod(string name) {\n      int pos = name.LastIndexOf('.');\n      string className = name.Substring(0, pos);\n      string methodName = name.Substring(pos + 1);\n      Type.GetType(className).GetMethod(methodName).Invoke(null, null);\n    }\n\n    static void Main() {\n      CallMethod("TestProgram.TestClass.Test");\n    }\n\n  }\n\n}	0
2743423	2743417	Datetime string formatting and CultureInfo	DateTime dateValue = new DateTime(2008, 6, 11);\nConsole.WriteLine(dateValue.ToString("ddd"));    // Displays Wed\n\nDateTime dateValue = new DateTime(2008, 6, 11);\nConsole.WriteLine(dateValue.ToString("ddd", \n                  new CultureInfo("fr-FR")));    // Displays mer.	0
10189114	10174757	one-to-many relationship saves foreign key as NULL in asp.net	Payroll.Entities.City city1 = new Payroll.Entities.City();\ncity1 = cs.SelectCity(Convert.ToInt64(cmbCity.SelectedItem.Value));\n\ne1.EmployeeName = "Archana";\ne1.RegistrationDate= dt;\ne1.FK_CityID = city1;\n\nes.AddEmpoyee(e1);	0
23346748	23280535	Maybe a Really simple, Dynamic Linq To Entities Select statement?	string SelectField = cb1.Name.Substring(2);\nParameterExpression pe = Expression.Parameter(typeof(Item), "p");\nExpression expr = Expression.Lambda(Expression.Property(pe, SelectField), pe);\n\nExpression<Func<Item, string>> expression = (Expression<Func<Item, string>>)expr;\n\nvar query = MyContext.Items.Select(expression);	0
9094173	9093240	Delete outer xml node without deleting inner xml	var doc = XDocument.Load(@".\Test1.xml");\n\nvar q = (from node in doc.Descendants("application")\n        let attr = node.Attribute("name")\n        where attr != null && attr.Value == "Test Tables"\n        select node.DescendantNodes()).Single();\n\nvar doc2 =  XDocument.Parse(q.First().ToString());	0
24513709	24513657	Comparing two counts in LINQ	var result = ctx.FileRecipients\n                .Count(f=>f.File_ID == 3 \n                       && f.downloaded == 'Y') == ctxt.FileRecipients\n                                                      .Count(f=>f.File_ID == 3);	0
31508326	31508193	Interaction between two user controls in windows form application	public partial class UserControlB: UserControl\n{\n    UserControlA userControlA;\n\n    public UserControlB(UserControlA ucA)\n    {\n        userControlA = ucA;\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        string myString = userControlA.TexBoxText;\n    }\n}	0
13885063	13884366	How to use WriteProgressCommand in a PowerShell C# cmdlet?	protected override void ProcessRecord()\n      {\n         ProgressRecord myprogress = new ProgressRecord(1, "Testing", "Progress:");\n\n          for (int i = 0; i < 100; i++)\n          {\n              myprogress.PercentComplete = i;\n              Thread.Sleep(100);\n              WriteProgress(myprogress);\n          }\n\n             WriteObject("Done.");\n      }	0
9142104	9140948	MonoTouch - How to redraw immediately UITableView when datasource is cleared	tbl.ReloadData ();	0
22537104	22519435	Drawing Lines On a Canvas From Grid to Grid as Added Programmatically	RC.X2 = p.X;\n      RC.Y2 = p.Y;\n      Canvas.SetLeft(g, Canvas.GetLeft(gr));\n      Canvas.SetTop(g, Canvas.GetTop(gr));	0
15307586	15307431	C# Copy variables into buffer without creating garbage?	int v1 = 123;\n        float v2 = 253F;\n        byte[] buffer = new byte[1024];\n        fixed (byte* pbuffer = buffer)\n        {\n            //v1 is stored on the first 4 bytes of the buffer:\n            byte* scan = pbuffer;\n            *(int*)(scan) = v1;\n            scan += 4; //4 bytes per int\n\n            //v2 is stored on the second 4 bytes of the buffer:\n            *(float*)(scan) = v2;\n            scan += 4; //4 bytes per float\n        }	0
26668237	26623619	C# values on ASPX page combine on refresh	for ( int i = 0; i < players.Length / 2; i++ )\n        {\n            players[i, 1] = "0";\n        }	0
24458676	24458610	How to find just one group a user is logged in as	for (int i = 0; i < groups.Count; i++){\n  if ( groups[i].ToString() == @"tmg\IT Members" ) \n  {\n     ...    // true...\n  }\n}	0
21968345	21968344	How to make a petapoco class with a name different than table name?	...\n[TableName("YourOldName")]\npublic class YourNewClassName\n{\n    ...\n}	0
694723	694713	How do you load embedded assemblies that you've bundled in with your main assembly?	Stream embedded = assembly.GetManifestResourceStream ("asm.dll");\nbyte [] buffer = new byte [embedded.Length];\nusing (embedded) {\n    int length = buffer.Length;\n    int offset = 0;\n    while (length > 0) {\n    int read = assemblyStream.Read (buffer, offset, length);\n    if (read == 0)\n    break;\n\n    length -= read;\n    offset += read;\n    }\n}\n\nAssembly assembly = Assembly.Load (buffer);	0
19148975	19148931	Trimming and Removing text from string?	string mySentence = "  Today is very   nice day!   ";\n\n    if (mySentence.Contains("very"))\n    {\n        mySentence = mySentence.Remove(mySentence.IndexOf("very")).Trim();\n    }	0
20086421	20076439	Multiple Nested Tables - ServiceStack Ormlite	// Iterate through Orders\n            foreach (var t in customer.CustomerOrder)\n           {\n                Db.LoadReferences(t);\n            }	0
2211201	2211172	Using LINQ to SQL; How Do I Insert a Row in a Table Without Setting all Column Values?	[Column(AutoSync=AutoSync.OnInsert,IsDbGenerated=true)]\npublic DateTime Created\n{\n}	0
20551576	20551507	Save 3 lists to text seperated by commas	for(int i=0; i<ingredients.Count;i++)\n{\n   writer.Write(ingredients[i] + ",");\n   writer.Write(newAmounts[i] + ",");\n   writer.Write(units[i] + "\n");\n }	0
4912875	4912795	Finding if a point intersects a rotated rectangle?	is rect.left <= point.x <= rect.right, is rect.bottom <= point.y <= rect.top	0
13496233	13236889	Sharepoint Workflow Global Variables in C# Workflow Project	public ReviewerBag()\n{\n    Reviewers = new Dictionary<string,Reviewer>();\n}\n...	0
12128938	12002957	How to set database login infos (connection info) for crystal report?	ConnectionInfo crconnectioninfo = new ConnectionInfo();\n    ReportDocument cryrpt = new ReportDocument();\n    TableLogOnInfos crtablelogoninfos = new TableLogOnInfos();\n    TableLogOnInfo crtablelogoninfo = new TableLogOnInfo();\n\n    Tables CrTables;\n\n    crconnectioninfo.ServerName = "localhost";\n    crconnectioninfo.DatabaseName = "dbclients";\n    crconnectioninfo.UserID = "ssssssss";\n    crconnectioninfo.Password = "xxxxxxx";  \n\n\n  cryrpt.Load(Application.StartupPath + "\\rpts\\" + dealerInfo.ResourceName);\n\n        CrTables = cryrpt.Database.Tables;\n\n        foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)\n        {\n            crtablelogoninfo = CrTable.LogOnInfo;\n            crtablelogoninfo.ConnectionInfo = crconnectioninfo;\n            CrTable.ApplyLogOnInfo(crtablelogoninfo);\n        }\n\n\n        cryrpt.RecordSelectionFormula = getCustInfoRptSelection();\n        cryrpt.Refresh();\n\n        allReportViewer.ReportSource = cryrpt;	0
6590039	6589948	How do I use Linq Sum After grouping by	List<Activity> activity;\nactivity\n  .GroupBy (a => new {a.Id, a.Activity})\n  .Select (ag => new {ag.Key.Id, ag.Key.Activity, TotalMarks=ag.Select(a => a.Marks).Sum()})	0
3685836	3632208	FtpWebRequest working with Explicit TLS/SSL	client: PASV\n(i would like to transfer files. Tell me which port and ip address should I use)\n\nserver: 227 Entering Passive Mode (172,16,3,4,204,173)\n(ok, use port 52397 on IP address 172.16.3.4.)\n\nclient: connects to this IP address/port and starts data transfer.	0
11241262	11241210	Exclude list items that contain values from another list	var results = dataset.Where(i => !excluded.Any(e => i.Contains(e)));	0
2206756	2206368	How to get tasks which windows mobile reminds you about?	int activeRemindingTasks = 0;\nOutlookSession session = new OutlookSession();\n\nfor (Task t in session.Tasks.Items)\n{\n  if (t.ReminderSet && t.ReminderTime <= DateTime.Now)\n  {\n    activeRemindingTasks++;\n  }\n}	0
28434349	28434250	Displaying a custom dialog window during a long-running task	.Result	0
5178174	5178137	How to transmit compressed strings from Java to C#	System.IO.Compression.GZipStream	0
3160296	3160267	How to create an array of enums	Enum[] enums = new Enum[] { enum1.Value1, enum2.Value2, etc };	0
4454594	4454058	No ItemChecked event in a CheckedListBox?	private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {\n        this.BeginInvoke((MethodInvoker)delegate { \n            okButton.Enabled = checkedListBox1.CheckedItems.Count > 0;\n        });\n    }	0
690526	690382	How can I put an array inside a struct in C#?	tPacket t = new tPacket();\nbyte[] buffer = new byte[Marshal.SizeOf(typeof(tPacket))];\nsocket.Receive(buffer, 0, buffer.length, 0);\n\nGCHandle pin = GCHandle.Alloc(buffer, GCHandleType.Pinned);\nt = (tPacket)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(tPacket));\npin.free();\n\n//do stuff with your new tPacket t	0
34022550	34022387	How do i initialise a property on a class in C# 6	new SomeServiceType()	0
8002343	8002320	Encode Files and strings into a binary file C#	public void save( String filename )\n{\n    XmlSerializer s = new XmlSerializer( this.GetType( ) );\n    MemoryStream w = new MemoryStream( 4096 );\n\n    TextWriter textWriter = new StreamWriter( w );\n\n    s.Serialize( textWriter, this );\n\n    FileStream f = new FileStream( filename, FileMode.CreateNew );\n    DeflateStream zipStream = new DeflateStream( f, CompressionMode.Compress );\n\n    byte[] buffer = w.GetBuffer( );\n    zipStream.Write( buffer, 0, buffer.Length );\n\n    zipStream.Close( );\n    textWriter.Close( );\n    w.Close( );\n    f.Close( );\n}	0
1384687	1382970	How to filter list of views from ?mail? in Lotus Notes?	...\nset vw = db.GetView ("Inbox")\nif (vw.entryCount > 0) then\n...\nend if	0
6071724	6071647	How to display in a Primary window from a secondary thread for a video player	Control.Invoke()	0
5668587	5668531	how to use datetime minvalue in get/set method when null is the database value	Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue : \nreader.GetDateTime(reader.GetOrdinal("event_start_date1"));	0
17264218	17264198	Filtering in ArrayList in C#	var StringOnly = mixed.OfType<string>();	0
29590046	29589886	how can I get the hierarchy index of a TreeNode in Winforms	treeView1.SelectedNode.Level;	0
11509148	11509068	Convert to 12 hr format	(model.ScheduledHour % 12) + (model.ScheduledAMPM == "AM" ? 0 : 12)	0
33641170	33556746	Render Control in ControlAdapter	public class RadioButtonAdapter : System.Web.UI.Adapters.ControlAdapter {\n    protected override void BeginRender(HtmlTextWriter writer) {\n        writer.Write("<div class=\"wrapper\">");\n        base.BeginRender(writer);\n    }\n    protected override void EndRender(HtmlTextWriter writer) {\n        base.EndRender(writer);\n        writer.Write("</div>");\n    }\n}	0
13678307	13678248	Passing a parameter from class A method to class B	//Class B\npublic static FileInfo myFileProperty\n{\n   get;\n   set;\n}\n\npublic static bool myMethod(FileInfo file)\n{\n//some codes here\nmyFileProperty = file;\nreturn false;\n}\n\n\n//Class A\nvoid OnChanged(object source, FileSystemEventArgs e)\n{\n\nXmlTextReader reader = new XmlTextReader(ClassB.myFileProperty);\n}	0
19890337	19890295	Place List<T> values in two arrays	var newList = new NewDataModel { \n                  XValues = data.Select(dm => dm.X).ToArray(), \n                  YValues = data.Select(dm => dm.Y).ToArray() };	0
22983508	22980328	keeping cursor within particular column of data grid view	//Code added in form load.\nMyGrid1.KeepCursorColumnIndex = 2; //I want to keep focus on column index 2\n\n\n\n//MyGrid custom grid class \npublic partial class MyGrid : DataGridView\n{\n    private int _freezCursorColumnIndex = -1;\n    public int KeepCursorColumnIndex\n    {\n        get\n        {\n            return _freezCursorColumnIndex;\n        }\n        set\n        {\n            _freezCursorColumnIndex = value;\n        }\n    }\n\n    public MyGrid()\n    {\n        InitializeComponent();\n    }\n    protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)\n    {\n\n        if (_freezCursorColumnIndex > -1 && this.CurrentRow != null && keyData == Keys.Return)\n        {\n            this.CurrentCell = this.CurrentRow.Cells[KeepCursorColumnIndex];\n            keyData = Keys.None;\n        }\n\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n}	0
6185869	6185772	dynamic gridview column autocalculation	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        e.Row.Cells[5] = (e.Row.Cells[3].Text - e.Row.Cells[4].Text)/1000\n    }\n}	0
20041693	20041666	How will I get a counter to display at 1 instead of 0?	Console.WriteLine("\nEnter the weight of turkey number {0}:",TurkeyCounter+1);	0
6282261	6282238	How do I display an error message for a GUI app from non-GUI related classes?	SaveFiles()	0
8633260	8633139	How to add a numeric order to the GridView using RowDataBound?	private int _rowIndex=0;\nprotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow) { \n                e.Row.Cells[0].Text = _rowIndex.ToString();\n               _rowIndex++;\n        }\n    }	0
28844840	28823422	Information Storage for 3 variables	List<Tuple<int, Point>>[] ItemList = new List<Tuple<int, Point>>[4]; // how to declare it\n\n        for (int i = 0; i < 4; i++)\n        {\n            ItemList[i] = new List<Tuple<int, Point>>(); // initilize each list\n        }\n\n        ItemList[1].Add(new Tuple<int, Point>(5, new Point(1, 2))); // add a new tuple to a specific array level\n\n        int count = ItemList[1].Count; // finds the count for a specific level of the array --> (1)\n\n        int getInt = ItemList[1].ElementAt(0).Item1; // finds int value --> (5)\n        Point getPoint = ItemList[1].ElementAt(0).Item2; // finds the point --> (1,2)	0
32425806	32425185	MonoDevelop's refactoring operation seems to convert foreach into slower for loop?	Company[] companies = core.GetCompanies("Dual");\nfor (int i=0; i<companies.Length; i++)\n{\n    Console.WriteLine (companies[i].Name);\n}	0
15244295	15244265	How to remove a combination of characters from a string?	str = str.Replace(",phani", string.Empty);	0
14527388	14527292	C# regex to match emoji	[\u1F30-\u1F5F]	0
1054087	1054076	Randomly generated hexadecimal number in C#	static Random random = new Random();\npublic static string GetRandomHexNumber(int digits)\n{\n    byte[] buffer = new byte[digits / 2];\n    random.NextBytes(buffer);\n    string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());\n    if (digits % 2 == 0)\n        return result;\n    return result + random.Next(16).ToString("X");\n}	0
7358852	7345813	How to automatically change which files are built depending on configuration - visual studio	protected readonly static string XML_PATH = \n#if DEBUG\n@"Resources/xml/Description.xml";\n#else\n@"Resources/xml/Description2.xml";\n#endif	0
19677234	19676936	How to read an exe file when it is running in C#	FileStream fs = \n    new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read);	0
1728028	1727983	NullReference at XML-Operations	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(_WorkingDir + "Session.xml");\nXmlElement xmlRoot = xmlDoc.DocumentElement;\nforeach(XmlElement e in xmlRoot.GetElementsByTagName("group"))\n{\n    // this ensures you are safe to try retrieve the attribute\n    if (e.HasAttribute("name")\n    { \n        // write out the value of the attribute\n        Console.WriteLine(e.GetAttribute("name"));\n\n        // or if you need the specific attribute object\n        // you can do it this way\n        XmlAttribute attr = e.Attributes["name"];       \n        Console.WriteLine(attr.Value);    \n    }\n}	0
16814915	16814648	get an special Substring in c#	public static void Main(string[] args)\n{\n    string input = "This is 2 much junk, 123,";\n    var match = Regex.Match(input, @"(\d*),$");  // Ends with at least one digit \n                                                 // followed by comma, \n                                                 // grab the digits.\n    if(match.Success)\n        Console.WriteLine(match.Groups[1]);  // Prints '123'\n}	0
20091389	20089184	Disabling ApplicationBarIconButton in wp7	((ApplicationBarIconButton)ApplicationBar.Buttons[index]).IsEnabled = true;	0
9102159	8796286	IMAP append message	long? uid = imap.UploadMessage("[Gmail]/Sent Mail", email);\n\nimap.DeleteMessageByUID((long)uid);	0
6829168	6829129	Equation to change every other two rows	bool white = ((rowId - 1) & 2) == 2;	0
12484662	9834007	How to pretty print with System.Json?	ToString(JsonSaveOptions.EnableIndent)	0
4199827	4199489	Build XML Dynamically using c#	XElement req = \n    new XElement("order",\n        new XElement("client", \n            new XAttribute("id",clientId),\n            new XElement("quoteback", new XAttribute ("name",quotebackname))  \n            ),\n        new XElement("accounting",\n            new XElement("account"),\n            new XElement("special_billing_id")\n            ),\n            new XElement("products", \n                new XElement(productChoices.Single(pc => pc.ChoiceType == choiceType).Name, \n                    from p in products\n                    where p.ChoiceType == choiceType\n                    select new XElement(p.Name)\n              )\n          )\n      );	0
2177090	2177001	Displaying trailing zeros except when a whole number	if (number % 1 == 0)\n                Console.WriteLine(string.Format("{0:0}", number));\n            else\n                Console.WriteLine(string.Format("{0:0.00}", number));	0
17276166	17273133	Change data capture and linq	CREATE FUNCTION dbo.GetUserHistory()\n    RETURNS table AS\nRETURN (\n\n    SELECT ID_number, Name, Age FROM cdc.fn_cdc_get_all_changes_dbo_User_Info\n    ((SELECT sys.fn_cdc_get_min_lsn('dbo_User_Info')), (SELECT sys.fn_cdc_get_max_lsn()),N'all')\n)	0
2804414	2804395	C# 4.0: Can I use a Color as an optional parameter with a default value?	public void log(String msg, Color? c = null)\n{\n    loggerText.ForeColor = c ?? Color.Black;\n    loggerText.AppendText("\n" + msg);\n}	0
6139787	6139679	Implicit <> Explicit interface	interface I1\n{\n    void implicitExample();\n}\n\ninterface I2\n{\n    void explicitExample();\n}\n\n\nclass C : I1, I2\n{\n    void implicitExample()\n    {\n        Console.WriteLine("I1.implicitExample()");\n    }\n\n\n    void I2.explicitExample()\n    {\n        Console.WriteLine("I2.explicitExample()");\n    }\n}	0
11295068	11295032	How to avoid case sensitive feature?	if (string.Compare(a, b, true) == 0)\n{\n ...\n}	0
26006763	26006745	Console won't print out the info from my method	static void Main(string[] args)\n        {\n\n            var frac = new fraction(1,5); \n\n            Console.WriteLine(frac);\n           Console.WriteLine("Press any key to continue..");\n            Console.ReadKey();\n        }\n\n\n\npublic class fraction\n    {\n        public int nom { get; set; }\n        public int denom { get; set; }\n        public fraction(int n, int d)\n        {\n            nom = n;\n            denom = d;\n\n        }\n\n        public override string ToString()\n        {\n            return string.Format("{0}\\{1}", nom, denom);\n        }\n    }	0
29745288	29742946	How to check Button clicked in general methode?	protected void Page_Load(object sender, EventArgs e)\n        {\n            if (!IsPostBack == true)\n            {\n                Session["button1WasClicked "] = false;\n}\n}\n\n\n   protected void linkToday_Click(object sender, EventArgs e)\n   {\n       Session["button1WasClicked "] = true;\n    }\n\n  protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)\n  {\n  gridAllPaymentBind(1);\n  }\n   public void gridAllPaymentBind(int pageIndex)\n   {\nbool button1WasClicked = (bool)Session["button1WasClicked "];\n   if (button1WasClicked == true)\n  {\n   result = 3;\n    command.Parameters.AddWithValue("@result", result);\n   }\n\n }	0
23434636	23434529	Reading individual words into an array using streamreader C#	string badWordsFilePath = openFileDialog2.FileName.ToString();\nstring[] badWords = File.ReadAllLines(badWordsFilePath);\nint test = badWords.Length;\nMessageBox.Show("Words have been imported!");\nBadWordsImported = true;	0
5172925	5172760	Extracting all key value pairs from "XML Like" text	XmlDocument doc = new XmlDocument();\ndoc.LoadXml("<root " + yourString + "/>");\n\nforeach(XmlAttribute att in doc.DocumentElement)\n{\n  // ... use att.Name & att.Value here\n}	0
11330660	11330579	How to get the other values that are not in the association table using Entity Framework code first	from s in DbContext.Screens\nwhere s.UserClassifications.Count() == 0\nselect s	0
16820262	16724901	Can Tesseract OCR recognize images with less than 4 characters?	.DefaultPageSegMode	0
19453576	19448298	Crystal report sending a parameter to specify	string customer = ComboBox.Text;\nstring connectionString =\nConsoleApplication1.Properties.Settings.Default.ConnectionString;\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\nconnection.Open();\nusing (SqlCommand command = new SqlCommand(\n"SELECT * FROM table WHERE table.customer LIKE @Name", connection))\n{\n//\n// Add new SqlParameter to the command.\n//\ncommand.Parameters.Add(new SqlParameter("Name", customer));	0
3302334	3301437	how to make my object in XNA cannot be entered by human	if(human.rectangle.X + human.rectangle.width >= house.rectangle.x && human.rectangle.X <= house.rectangle.x + house.rectangle.width)\n{\n// the human entered here, just disallow any walking action here\n}	0
6410098	6409926	Factory vs Abstract Factory Design Pattern	public abstract class AnimalFactory\n{\n    public abstract Animal CreateFish();\n    public abstract Animal CreateBird();\n    public abstract Animal CreateMammal();\n}\n\npublic class AfricanAnimalFactory : AnimalFactory\n{\n    public override Animal CreateFish()\n    {\n        return new Reedfish();\n    }\n\n    public override Animal CreateBird();\n    {\n        return new Flamingo();\n    }\n\n    public override Animal CreateMammal();\n    {\n        return new Lion();\n    }\n}	0
5613341	5613320	How to initialize auto-property to not null in C#?	MyProp = new Dictionary<string,string>();	0
7829313	7829258	onClick for dynamically generated LinkButton	if (!IsPostback)	0
20593315	20593263	Show an error on a label box for invalid username or password	var qry = (from test in  je.employee\n                  where test.emp_email.Equals(TxtUserName.Text) & test.emp_pass.Equals(TxtPassword.Text)\n                   select test).FirstOrDefault();\n   var qry2 = (from test1 in je.employer\n                    where test1.c_mail.Equals(TxtUserName.Text) & test1.c_pass.Equals(TxtPassword.Text)\n                    select test1).FirstOrDefault();\n    if (null!=qry)\n    {\n        Response.Redirect("EmployeeHome.aspx");\n    }\n    else if(null != qry2)\n    {\n         Response.Redirect("EmployerHome.aspx");          \n    }\n    else\n    {\n        Label1.Text = "Incorrect username or password!";\n    }	0
20533357	20515156	How to retrieve certain data from Access Database and display them in a combobox	private void LoadDataToCbo()\n{\n        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=EmployeeInformation.accdb";\n       // string query = @"SELECT FirstName from Employees";\n        string query =\n            @"SELECT EmpID, LastName & ', ' + FirstName & ' (' & EmployeePosition & ')' as Name FROM Employees";\n        OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);\n        DataTable source = new DataTable();\n        dAdapter.Fill(source);\n        cboSelectEmp.DataSource = source;\n        //cboSelectEmp.ValueMember = "FirstName";\n        //cboSelectEmp.DisplayMember = "FirstName";\n\n        cboSelectEmp.DisplayMember = "Name";\n        cboSelectEmp.ValueMember = "EmpID";\n\n}	0
6263259	6263059	Hide/show table in gridview on button click event	visible=false	0
848459	278997	How do I use reflection to get properties explicitly implementing an interface?	var explicitProperties =\nfrom method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)\nwhere method.IsFinal && method.IsPrivate\nselect method;	0
30616284	30616126	Generic method to replace two	private static Dictionary<Type, String> s_Search = new Dictionary<Type, String>()\n{\n    {typeof(MyTypeA), "optiona"},\n    {typeof(MyTypeB), "optionb"}\n}\n\n...\n\npublic XDocument DoSearch<T>()\n{ \n    return searchService.Search(dictionary[s_Search(typeof(T))]);\n}	0
13363322	13363283	IN equivocalness of T-SQL?	if (this.Something.GID == 1 || this.Something.GID == 2 )\n{\n Something = "something";\n}	0
25542735	25542575	How to make loop execute one iteration per 2 seconds with yield?	IEnumerator MyCoroutine()\n{\n    for (int i = 0; i < 5; i++)\n    {\n        Debug.Log(i); // before waiting\n        yield return new WaitForSeconds(2.0f);\n        // after waiting\n    }\n}	0
8359182	8330842	EF4.1 - Try update many rows	var history = db.UserHistory.Where(m => m.UserID == id).ToList();\nTryUpdateModel(history);\nhistory.ForEach(m => m.IsActive = false);\ndb.SaveChanges();	0
3771398	3771315	The Entity Framework takes the next data page automatically	// Bind data\nthis.IncomeGridView.DataSource = incomeData;\n\n// If incomeData is not empty then Taking the value of the Id field of the first \n// and the last row in data page\nif (incomeData.Any())\n{         \n    int pageSize = IncomeGridView.PageSize;\n    int pageIndex = IncomeGridView.PageIndex;\n\n    this.incomePaging_IdAtTheEndOfCurrentPage = incomeData\n        .Skip(pageIndex * pageSize) // Skip pages before this page\n        .Skip(pageSize -1)          // Skip all items except the last one\n        .Take(1)                    // Take the last one\n        .Id;\n\n    this.incomePaging_IdAtTheStartOfCurrentPage = incomeData\n        .Skip(pageIndex * pageSize) // Skip pages before this page\n        .Take(1)                    // Take the first one\n        .Id;\n}	0
3940417	3940391	Opening a Internet Explorer browser window to a specific URL in C#	WebRequest myWebRequest = WebRequest.Create(strURL);  \n        WebResponse myWebResponse = myWebRequest.GetResponse();  \n        Stream ReceiveStream = myWebResponse.GetResponseStream(); \n        Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); \n        StreamReader readStream = new StreamReader( ReceiveStream, encode ); \n        string strResponse=readStream.ReadToEnd(); \n        StreamWriter oSw=new StreamWriter(strFilePath); \n        oSw.WriteLine(strResponse); \n        oSw.Close(); \n        readStream.Close(); \n        myWebResponse.Close();	0
23629188	23629026	boolean variable to identify Prime number asp.net	protected void isPrimeButton_Click(object sender, EventArgs e)\n{\n\n    int TestNumber = int.Parse(primeNumberTextBox.Text);\n    bool isPrime = true;\n\n    for (int i = 2; i < TestNumber; i++)\n    {\n        if (TestNumber % i == 0)\n        {\n            isPrime = false;\n            break;\n        }\n    }\n    if (isPrime)\n        yesNoPrimeTextBox.Text = "prime";\n    else\n        yesNoPrimeTextBox.Text = "not prime";\n\n}	0
24756746	24756338	Can not add same column object into Xceed DataGrid	for(int i=0;i<=2;i++)\n{\n    Column c = new Column();\n    c.FieldName = "Text";\n    c.Title = "Title";\n    dgTable1.Columns.Add(c);\n }	0
21410248	21410065	Using Regex in C#.NET to extract data from a string	: (.+)?,.*: (\d+).*(\d+)	0
82408	82319	How can I determine the length of a .wav file in C#?	using System;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace Sound\n{\n    public static class SoundInfo\n    {\n        [DllImport("winmm.dll")]\n        private static extern uint mciSendString(\n            string command,\n            StringBuilder returnValue,\n            int returnLength,\n            IntPtr winHandle);\n\n        public static int GetSoundLength(string fileName)\n        {\n            StringBuilder lengthBuf = new StringBuilder(32);\n\n            mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", fileName), null, 0, IntPtr.Zero);\n            mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, IntPtr.Zero);\n            mciSendString("close wave", null, 0, IntPtr.Zero);\n\n            int length = 0;\n            int.TryParse(lengthBuf.ToString(), out length);\n\n            return length;\n        }\n    }\n}	0
3702738	3702626	Using LINQ to XML to traverse an HTML table	XElement myTable = xdoc.Descendants("table").FirstOrDefault(xelem => xelem.Attribute("class").Value == "inner");\nIEnumerable<IEnumerable<XElement>> myRows = myTable.Elements().Select(xelem => xelem.Elements());\n\nforeach(IEnumerable<XElement> tableRow in myRows)\n{\n    foreach(XElement rowCell in tableRow)\n    {\n        // tada..\n    }\n}	0
32414844	32414766	Avoiding repeating characters through regEx	string strIMEIRegEx = "^(?!0+$)[1-9][0-9]{14}$";\nstring strIMEIRegExAlt = "^(?!0+$)[a-fA-F1-9][a-fA-F0-9]{13}$";	0
1419628	1419581	How to access most frequently used programs in OS and most recent files of programs programmatically?	string folderName =  Environment.GetFolderPath (Environment.SpecialFolder.Recent);\nDirectoryInfo recentFolder=new DirectoryInfo(folderName);\nFileInfo[] files=recentFolder.GetFiles();	0
31845942	31845899	C# Get Console to (SPEAK) a response	using System.Speech.Synthesis;\n...\n\n // Initialize a new instance of the SpeechSynthesizer.\n      SpeechSynthesizer synth = new SpeechSynthesizer();\n\n      // Configure the audio output. \n      synth.SetOutputToDefaultAudioDevice();\n\n\n      synth.Speak("I am good how are you?");	0
19840186	19840008	Concatenate variables by commas in C# winforms	var lTest = string.Join(", ", numDayOccurances.Select(e=>e.Key.ToString()));	0
6056303	6048658	convert a flat database resultset into hierarchical object collection in C#	foreach (item in resultset)\n{\n  // Build a customer and order dictionary\n  if (!CustomerDictionary.Contains(item.Customer.Id)\n     CustomerDictionary.Add(item.Customer.Id, item.Customer)\n\n  if (!OrderDictionary.Contains(item.Order.Id)\n     OrderDictionary.Add(item.Order.id, item.Order)\n\n  // Now add the association      \n  var customer = CustomerDictinoary[item.Customer.Id];\n  customer.AddOrder(item.Order);\n\n  var order = OrderDictinoary[item.Order.id];\n  order.AddOrderItem(item.OrderItem);\n}	0
333671	333655	How to run any method knowing only her fully qualified name	BindingFlags.Public | BindingFlags.Static	0
3865181	3865022	How to know whether the user is scrolling the datagridview	public class DataGridViewEx : DataGridView\n    {\n        private const int WM_HSCROLL = 0x0114;\n        private const int WM_VSCROLL = 0x0115;\n        private const int WM_MOUSEWHEEL = 0x020A;\n\n        public event ScrollEventHandler ScrollEvent;\n        const int SB_HORZ = 0;\n        const int SB_VERT = 1;\n        public int ScrollValue;\n        [DllImport("User32.dll")]\n        static extern int GetScrollPos(IntPtr hWnd, int nBar);\n        protected override void WndProc(ref Message m)\n        {\n            base.WndProc(ref m);\n            if (m.Msg == WM_VSCROLL ||\n                m.Msg == WM_MOUSEWHEEL)\n                if (ScrollEvent != null)\n                {\n                    this.ScrollValue = GetScrollPos(Handle, SB_VERT);\n                    ScrollEventArgs e = new ScrollEventArgs(ScrollEventType.ThumbTrack, ScrollValue);\n                    this.ScrollEvent(this, e);\n                }            \n        }\n    }	0
12008422	12003227	Event Handler for multiple objects with a parameter, the parameter is the same in the event	foreach (RssFeed item in items)\n        {\n            var localItem = item;\n            WebClient webClient = new WebClient();\n            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) => this.webClient_DownloadStringCompleted(sender, e, localItem.MyListBox));\n            webClient.DownloadStringAsync(new System.Uri(localItem.Url));    \n        }	0
8325057	8314471	C1 Print Preview Dialog disable some save to file options	C1.Win.C1Preview.C1PrintPreviewDialog c1ppd = new C1.Win.C1Preview.C1PrintPreviewDialog();\nc1ppd.PreviewPane.ExportOptions[C1.C1Preview.Export.ExportProviders.XlsExportProvider.FormatKey].Enabled = false;	0
12945079	12920074	How to determine the end of a file transfer (data) from the client to the server (Socket)	var whenFileReceived = from header in socket.WhenReadExact(4)\n                       let bodySize = BitConverter.ToInt32(header)\n                       from body in socket.WhenReadExact(bodySize)\n                       select body;\n\nwhenFileReceived.Subscribe(\n    file =>\n    {\n        // Handle file here\n    });	0
13988126	13976941	Restart List Numbering with C# Word Interop	using System.Runtime.InteropServices;\nusing MSWord = Microsoft.Office.Interop.Word;\n\nnamespace ResetNumberingInWordDoc\n{\n    class Program\n    {\n        static void Main()\n        {\n            var application = new MSWord.Application();\n            var document = application.Documents.Open(@"C:\mydocument.docx");\n\n            const int listNumber = 1; //The first list on the page is list 1, the second is list 2 etc etc\n\n            document.Range().ListFormat.ApplyListTemplateWithLevel(\n                ListTemplate: document.ListTemplates[listNumber], \n                ContinuePreviousList: false, \n                ApplyTo: MSWord.WdListApplyTo.wdListApplyToWholeList,\n                DefaultListBehavior: MSWord.WdDefaultListBehavior.wdWord10ListBehavior);\n\n            document.Save();\n            document.Close();\n\n            application.Quit();\n\n            Marshal.ReleaseComObject(application);\n        }\n    }\n}	0
17522160	17521570	databind datagridview in multithreadded application	void LoadData()\n{\n    if (InvokeRequired)\n                Invoke(new MethodInvoker(InnerLoadData));\n}\n\nvoid InnerLoadData()\n{\n    dt = JobManager.GetTodaysJobs();\n    dataGridView1.AutoGenerateColumns = false;\n    dataGridView1.DataSource = dt;\n}	0
1570799	1570316	Get specific data from a string? C#	string group = "|17|11|05|";\n        string[] words = group.Split('|');\n        foreach (string word in words) {\n            if (word.ToString() != "") {\n                string cg = word;\n            }\n        }	0
7987227	7987171	javascript parameter character length limit?	var value = new JavaScriptSerializer().Serialize("some string that contains ' and \".");\nvar script = string.Format("alert({0});", value);\nClientScript.RegisterStartupScript(GetType(), "someKey", script, true);	0
10992112	10991452	How do I get the differences between two string arrays in C#?	foreach (string com in com2 )\n{\n    if (!com1.Contains(com))\n    {\n        MessageBox.Show(com);\n    }\n}	0
32683934	32683704	What would be more appropriate for my need (XML\Json) and how do I use it?	var xmlString = @"<items>\n  <item>\n    <id>100</id>\n    <name>lance</name>\n    <cost>9.99</cost>\n    <description></description>\n    <pathofimage></pathofimage>\n  </item>\n  <item>\n    <id>101</id>\n    <name>sword</name>\n    <cost>12.50</cost>\n    <description></description>\n    <pathofimage></pathofimage>\n  </item>\n</items>";\n\nvar doc = XDocument.Parse(xmlString);\nvar items = doc.Root.Elements("item").Select(e => new {\n                                    Id = int.Parse(e.Element("id").Value), \n                                    Name = e.Element("name").Value, \n                                    Cost = decimal.Parse(e.Element("cost").Value)});	0
254908	254784	How can I perform a nested Join, Add, and Group in LINQ?	var InnerQuery = from i in input\n                 join o in output\n                 on i.Input_ID equals o.Output_ID into joined\n                 from leftjoin in joined.DefaultIfEmpty()\n                 select new\n                 {\n                     Label = i.Label,\n                     AddedAmount = (i.Input_Amt + (leftjoin == null ? 0 : leftjoin.Output_Amt))\n                 };	0
1854504	1854484	UIElement position relative to Window	Point pt = tabControl.TranslatePoint(new Point(0, 0), windowInstance);	0
6935004	6934942	Structural/ conceptual advice on working with custom functions for SQL database from C#	stored procedure\nudf, user defined function\ntsql\nsql-server	0
21534021	21533726	Exporting SQL Server to Excel - Too many posts?	var wb = new XLWorkbook();\n\nvar dataTable = GetTable("Information");\n\n// Add a DataTable as a worksheet\nwb.Worksheets.Add(dataTable);\n\nwb.SaveAs("AddingDataTableAsWorksheet.xlsx");	0
1555609	1555566	show last four digits of SSN	var el = document.getElementById('MyTextBoxId');\nel.value = '***-**-' + (el.value.replace(/-/g,'') % 10000);	0
11430542	11430420	I need a C# function that will convert from one row format to another?	public string DotFormatToRowKey(string tempRowKey) {\n        var splits = tempRowKey.Split('.') // Split string at "."\n                     .Select(x => String.Format("{0:d2}", Int32.Parse(x))) // Specify string format\n                     .ToList();\n        return String.Join(String.Empty, splits.ToArray()); // Join array and return\n}	0
10687030	10686953	comparing session variable value to a string	((string)Session["loggedInUserType"]) == "Administrator"	0
3269604	3269518	Get the property name used in a Lambda Expression in .NET 3.5	string GetPropertyName<T>(Expression<Func<T>> property)\n{\n    var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;\n    if (propertyInfo == null)\n    {\n        throw new ArgumentException("The lambda expression 'property' should point to a valid Property");\n    }\n    return propertyInfo.Name;\n}	0
7723298	7723164	C# how get maximum value from list of lists	class Program\n{\n    static void Main(string[] args)\n    {\n        var l = new List<List<double>>() {new List<Double>() {0, 16.0000, 15.0000, 0, 2.7217, 3.7217}, \n                                          new List<Double>() {0, 0, 15.0000, 15.0000, 5.6904, 5.6904}};\n\n        int i = 1;\n        var result = from sublist in l\n                     select new { min = sublist.Min(), max = sublist.Max(), index = i++ };\n\n        foreach (var r in result)\n            Console.WriteLine(String.Format("Index: {0} Min: {1} Max: {2}",r.index,  r.min, r.max));\n\n        Console.ReadKey();\n    }\n}	0
7792809	7792739	How to Parse string Values to xml and bind it to dataset	DataSet dataSet = new DataSet();\nDataTable dataTable = new DataTable("table1");\ndataTable.Columns.Add("col1", typeof(string));\ndataSet.Tables.Add(dataTable);\n\nstring xmlData = "<XmlDS><table1><col1>Value1</col1></table1><table1><col1>Value2</col1></table1></XmlDS>";\n\nSystem.IO.StringReader xmlSR = new System.IO.StringReader(xmlData);\n\ndataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema);	0
34565191	34563489	Sort by numbers first	var x = new List<string>() { "a", "1", "b", "2" };\nvar sorted = x.OrderBy(c => Convert.ToChar(c))\n              .ToList();\n\nforeach (var c in sorted)\n    Console.WriteLine(c);\n\n// 1\n// 2\n// a\n// b	0
2906507	2906481	How do I convert a datetime with milliseconds to a string in C#?	string formatted = DateTime.Now.ToString("MMddyyyyHHmmssfff");	0
7445882	7445517	Asp.net adding parameter to url string	string url = Request.Url.GetLeftPart(UriPartial.Path);\nurl += (Request.QueryString.ToString() == "" ) ? "?pagenum=1" : "?" + Request.QueryString.ToString() + "&pagenum=1";	0
6339278	6337065	Create a Customer from a Guest - using MVC3, C#, Entity Framework, Razor Views, SQL Server	var customerNew = new Customer\n                  {\n                      // ... set all the properties here\n                  }\n\nvar phoneNew = new CustomerPhone\n            {\n                Number = customer.Number,\n                PhoneTypeId = 5\n            };\ncustomerNew.CustomerPhones.Add(phoneNew);  // add new phone to the association\n\nvar emailNew = new CustomerEmail\n            {\n                Email = customer.Email\n            };\ncustomerNew.CustomerEMails.Add(phoneNew);  // add new e-mail to the association\n\ndb.Customers.AddObject(customerNew);\ndb.SaveChanges();	0
3406232	3406217	How do you implement the equivalent of SQL IN() using .net	using System;\nusing System.Linq;\n\nstatic class SqlStyleExtensions\n{\n    public static bool In(this string me, params string[] set)\n    {\n       return set.Contains(me);\n    }\n}\n\nUsage:\n\nif (Variable.In("AC", "BC", "EA"))\n{\n\n}	0
12077201	12077017	how can a DataSet be filled using multiple SELECT queries run against an Excel file?	DataSet set1 = new DataSet();\nusing(OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [SheetName1$];", connection))\n{\n   adapter.Fill(set1 );\n}\n\nDataSet set2 = new DataSet();\nusing(OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [SheetName2$];", connection))\n{\n   adapter.Fill(set2);\n}	0
6054768	6054713	Method to check array list containing specific string	foreach( string row in arrayList){\n    if(row.contains(searchString)){\n       //put your code here.\n    }\n}	0
17479652	17479096	C# InMemoryCopy of Image file as StandardInput for process	fs.CopyTo(p.StandardInput.BaseStream)	0
10781875	10781282	Moving a control with keys	private void moveRight(Button button)\n    {\n        // Gets the current position of the control\n        Point relativePoint = button.TransformToAncestor(parentCanvas).Transform(new Point(0, 0));\n\n        Canvas.SetLeft( button , 5 + relativePoint.X );\n        button.Content = relativePoint;\n\n     }	0
17214837	17153312	Best way to detect navigation complete in webbrowser control	EventWaitHandle DocumentComplete = new EventWaitHandle(false, EventResetMode.AutoReset);\n\nvoid Form_Activated(object sender, System.EventArgs e)\n{\n    new Thread(new ThreadStart(DoWork)).Start();\n}\n\nvoid Browser_DocumentComplete(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)\n{\n    Data = Browser.Document.Body.GetAttribute(some_tag);\n    //process "Data" and do other stuff\n    DocumentComplete.Set();\n}\n\nvoid DoWork() {\n    for (; ; ) {\n        for (; ; ) {\n            //Some operation\n            Invoke(new NavigateDelegate(Navigate), URL);\n            DocumentComplete.WaitOne();\n        }\n    }\n}\n\nvoid Navigate(string url) {\n    Browser.Navigate(url);\n}\n\ndelegate void NavigateDelegate(string url);	0
15087230	15087162	C# Storing categories in a value - Bitmasks	public static class Categories\n{\n   public const int Category1 = 1;\n   public const int Category2 = 2;\n    //...\n   public const int Category3123 = 3123;\n   public const int Max = 5000;\n}\n\nBitArray myBitset = new BitArray((int)Categories.Max);\nmyBitSet.Set(Categories.Category1);\nmyBitSet.Set(Categories.Category4);	0
13455250	13455045	WCF - Missing integer parameter treated like 0	[OperationContract]\npublic void InsertSomeData(MyData data){...}\n\n[DataContract]\npublic class MyData{\n[DataMember]\npublic string version{get;set;}\n[DataMember(IsRequired=true)]\npublic int someId{get;set;}\n\n}	0
11157934	11157170	Copying datagrid column into an array?	DataSet ds = new DataSet();\n    List<object> myListArray = new List<object>();\n\n    foreach (DataRow dr in ds.Tables[0].Rows)\n    {\n        myListArray.Add(dr["MyColumnName"]);\n    }	0
13885539	13885236	Pass Dictionary<String,List<String>> to Javascript array	function llamada_Webservice(peticion) {\nvar categories = peticion;\n    for(item in categories{ // Data is saved in the variable named d if it's ASP.NET WebService\n        var categoria = item; // The name\n        var list = categories[item]; // The array that you could loop thru\n\n    }\n\n}	0
21790477	21790356	using linq to sql to get a limited selection of rows, possibly without joins	int recordsCount = (from x in foo\n             join y in bar\n             on x.barid equals y barid\n             where x.barProperty == 73).Count();	0
8898344	8897751	Pass Camera OnActivityResult to Webservice to be Saved on Server as Image	var bitmap = (Android.Graphics.Bitmap) data.Extras.Get("data");\n\nusing (var stream = new MemoryStream())\n{\n    bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);\n\n    // stream now contains the image data\n}	0
18652269	18652253	how compare value of datagridview cell is of decimal type or not	(DataGridViewRow  dgRow in dgvMarksEntryForClass.Rows)\n{\n    Decimal cellValue;\n    if (Decimal.TryParse(dgRow.Cells["dgcolMarksObtain"].Value, out cellValue)\n    {\n         //some action\n    }\n    else\n    {\n        //some action\n    }\n}	0
6114118	6114086	Get unique values from a List of strings	List<String> strings = new List<string>() { "100", "101", "101", "102", "103", "103", "104", "104", "105" };\nvar distinctStrings = strings.Distinct().ToList();	0
28223090	28222940	String array to datatable	string yourString = "insert your string"\nstring[] Splits = yourString.split(",");// Dividing your string by "," chars.\nint i=0;// declaring it here for using it later to check if the number is odd\nfor(int i=0; i < Splits.Length-1; i+=2)\n{\nInsertIntoDatabase(Splits[i,i+1]); //Inserting two strings into the database\n}\n//if i is odd, i will be equal exacly to the Length here. Otherwise...\nif(i<Splits.Length)\n{\nInsertIntoDatabase(Splits[i]); // Insert the last string in it's own row.\n}	0
11776766	11776634	Using HTML Agility Pack to grab text to the right of a node	HtmlNode sibling = strong.SelectSingleNode("following-sibling::text()");\nConsole.WriteLine("Course ID = " + sibling.InnerText.Trim());	0
29110417	29110265	HttpClient - Send a batch of requests	var taskList = new List<Task<JObject>>();\n\nforeach (var myRequest in RequestsBatch)\n{\n    taskList.Add(GetResponse(endPoint, myRequest));\n}\n\ntry\n{\n    Task.WaitAll(taskList.ToArray());\n}\ncatch (Exception ex)\n{\n}\n\npublic Task<JObject> GetResponse(string endPoint, string myRequest)\n{\n    return Task.Run(() =>\n        {\n            HttpClient httpClient = new HttpClient();\n\n            HttpResponseMessage response = httpClient.PostAsJsonAsync<string>(\n                 string.Format("{0}api/GetResponse", endpoint), \n                 myRequest, \n                 new CancellationTokenSource(TimeSpan.FromMilliseconds(5)).Token);\n\n            JObject resultResponse = response.Content.ReadAsAsync<JObject>();\n        });\n}	0
20492621	20142992	Google Drive Resumable upload no Response	WebResponse response = request.GetResponse();\nstring Location = response.Headers["Location"];	0
34495226	34494768	INSERT command for auto increment field in access from desktop app	string query = "insert into table(col2,col3,col4,col5,col6,col7,col8) \n    values ('v2','v3','v4','v5','v6','v7','v8')";	0
26408418	26406780	Programatically creating a NuGet package for a local repository	File.Open	0
21295775	21295491	Is a permission required to use notifications in an Android app?	NotificationCompat.Builder builder = new NotificationCompat.Builder(this)\n    .SetContentTitle("Button Clicked")\n    .SetSmallIcon(Resource.Drawable.ic_stat_button_click)\n    .SetContentText(String.Format("The button has been clicked {0} times.", _count));\n\n    // Obtain a reference to the NotificationManager\n    NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);\n    notificationManager.Notify(ButtonClickNotificationId, builder.Build());	0
6584250	6584037	MongoDB remove a subdocument document from a subdocument	var query = Query.And(Query.EQ("_id", applicationId),\n                         Query.EQ("Settings.Key",  "ImportDirectory"));\n        var update = Update.Pull("Settings.$.Overrides", new BsonDocument(){\n            { "Name", "PathDirectory" }\n        });\n        database.Applications().Update(query, update);	0
24319750	24319379	SQL Syntax error when trying to insert array values of a Datatable	OdbcCommand command = new OdbcCommand("INSERT INTO jevslimporttemp(JevSLImportTempCode, JevSLImportTempDescription, JevSLImportTempAmount)VALUES(?, ?, ?);", conn);\n\ncommand.Parameters.AddWithValue("JevSLImportTempCode", table.Rows[x][1].ToString());\ncommand.Parameters.AddWithValue("JevSLImportTempDescription", table.Rows[x][1].ToString());\ncommand.Parameters.AddWithValue("JevSLImportTempAmount", Convert.ToDouble(table.Rows[x][2].ToString()));	0
11643652	11631425	How I create a LDAP Filter with City ("l") Parameter	public void SearchByPlace(string city)\n        {\n            DirectoryEntry Entry = new DirectoryEntry("LDAP://" + Properties.Settings.Default.Domain);\n            string filter = "(&(objectClass=user)(objectCategory=person)(l=" + city + ")(cn=*))";\n            DirectorySearcher Searcher = new DirectorySearcher(Entry, filter);\n\n            var q = from s in Searcher.FindAll().OfType<SearchResult>()\n                    select new\n                    {\n                        Benutzer = GetProperty(s, "sAMAccountName"),\n                        eMail = GetProperty(s, "mail"),\n                        Vorname = GetProperty(s, "givenName"),\n                        Nachname = GetProperty(s, "sn"),\n                        Telefon = GetProperty(s, "telephoneNumber"),\n                        UserID = s.GetDirectoryEntry().Guid\n                    };\n\n            this.myListView.DataSource = q;\n            this.myListView.DataBind();\n        }	0
12537258	12537132	Can I write regex expression to check a password for some conditions?	if (Regex.IsMatch(subjectString, \n    @"^               # Start of string\n    (?=.*\p{Lu})      # Assert at least one uppercase letter\n    (?=.*\p{Ll})      # Assert at least one lowercase letter\n    (?=.*\d)          # Assert at least one digit\n    (?=.*[^\p{L}\d])  # Assert at least one other character\n    .{8,}             # Match at least 8 characters\n    $                 # End of string",             \n    RegexOptions.IgnorePatternWhitespace))	0
603742	597788	Find random point along a line	1 -- 50383220533284199945706810754936311181214547134666382315016772033813961148457676\n2 -- 125723425896904546349739165166331731432281836699962161072279259011758052396215820\n3 -- 235794378436564714387676526976517945151880763730707233042654663244625708155520494\n'This is my super secret password.'	0
10114829	10114670	MySql Linq-Entities Date Comparison	var expiredPolcies = context.ApiUsagePolicies\n    .Where(u => \n        (DateTime.UtcNow - u.UsagePolicyStart).TotalSeconds > u.UsagePeriodSeconds);	0
25191601	25190428	Can i filter Table from LinqToSQL?	DateTime filterDate=new DateTime(2014,5,1,0,0,0);\nvar query = ((IQueryable<SomeTable>)dc.GetTable<SomeTable>()).Where(item => item.Date < filterDate);\nvar filteredItems = query.ToList();	0
861699	861644	i am using google chart api i want to set the labels for x axis	using System;\n    using System.Net;\n    using System.IO;\n\npublic class Test\n{\n    public static void Main (string[] args)\n    {\n\n        WebClient client = new WebClient ();\n\n        Stream data = client.OpenRead (args[0]);\n        StreamReader reader = new StreamReader (data);\n        string s = reader.ReadToEnd ();\n        Console.WriteLine (s);\n        data.Close ();\n        reader.Close ();\n    }\n}	0
15256408	15256302	Update WPF Image Control Programmatically from Webcam Input	bi.CacheOption = BitmapCacheOption.OnLoad	0
2318905	2318885	Multiple Order By with LINQ	foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)	0
2873098	2873037	Calculate average in each group	var countryAvgs = countries\n    .Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});	0
4958994	4958950	Casting an interface	var myentities = distributionUnits.Cast<IEntity>().ToList();	0
27682610	27680977	Wait for multiple processes to complete	var processes = new Dictionary<string,Process>();\n\nforeach (string script in scriptList)\n{\n    ProcessStartInfo myProcess = new ProcessStartInfo();\n     myProcess.FileName = accoreconsolePath;\n     myProcess.Arguments = "/s \"" + script + "\"";\n     myProcess.CreateNoWindow = true;\n     myWait = Process.Start(myProcess);\n     processes.Add(script, myWait);\n}\n\nforeach(var script in processes.Keys)\n{\n    Process process = processes[script];\n\n    process.WaitForExit();\n    process.Close();\n\n    File.Delete(script);\n}	0
17702960	17702894	How do I set properties in a class with a parameterless constructor on instantiation in one statement?	var obj = new Thing{Id=3, Name="The Thing"};	0
11665985	11665807	Page Scope Variables Dissapear	public partial class SamplePage : System.Web.UI.Page\n{\n    int UserID;\n  protected void Page_Load(object sender, EventArgs e)\n  {\n\n  }\n protected void btnSearchUser_Click(object sender, EventArgs e)\n {\n    UserID=5;\n    ViewState["UserID"] = UserID;\n }\n protected void btnSubmit_Click(object sender, EventArgs e)\n {\n    if(ViewState["UserID"]!=null)\n    Response.Write(ViewState["UserID"].ToString());\n }\n}	0
13254127	13238163	How to use an interface to strip a generic in C#?	interface IVehicleFactory<TVehicle> where TVehicle:Vehicle\n{\n    TVehicle SomeMethod();\n}\n\nVehicleFactory<TVehicle> : IVehilceFactory<TVehicle> where TVehicle:Vehicle\n{\n    TVehicle SomeMethod()\n    {\n    }\n}\n\nCarFactory<TVehicle> : IVehicleFactory<TVehicle> where TVehicle:Vehicle\n{\n    TVehicle SomeMethod()\n    {\n       ~~Always returns car and uses cast from Vehicle when necessary.\n    }\n}\n\nclass VehicleFactory<TVehicle>\n{\n   static IVehicleFactory<TVehicle> CreateContextSpecificFactory()\n   {\n       if(someCondition)\n       {\n            return new CarFactory<TVehicle>;\n       }\n   }\n}\n\nclass CarCompany\n{\n    CarFactory<Car> carFactory = new CarFactory<Car>;\n    Car car = carFactory.SomeMethod();\n}\n\nclass VehicleCompany\n{\n    VehicleFactory<Vehicle> vehicleFactory = VehicleFactory<Vehicle>.CreateContextSpecificFactory();\n}	0
21567661	21567475	Unable to reference objects in a referenced assembly	public void Junk()\n{\n  global::SqlSmoke.Data. \n}	0
5152618	5152578	Removing "" elements in a ArrayList	var result = ftd.Cast<string[]>().Where(x => x[0] != "");	0
26237479	26237269	How can I send email leveraging my gmail account without revealing my password?	SmtpServer.Credentials = new System.Net.NetworkCredential(decrypt("asdf42das24dfsf44sdfa4fg"), decrypt("gjlkdivn3qefdasd48adjvjv4385939"));	0
4876991	4876885	Database handling in applications	MySqlConnection cn = new MySqlConnection(yourConnectionString);\n\n//Execute your queries\n\ncn.close();	0
32206409	32206348	linq data is grouped / hierachical	var clusteredhosts = dataViews.Clusters.SelectMany(c=>c.Hosts);	0
24192342	24192181	How to call an API on one server from a User-interface (Webpage) on a different server?	protected void Button1_Click(object sender, EventArgs e)\n{\n    using (var request = WebRequest.Create("http://foreignserver/api/..."))\n    using (var response = request.GetResponse())\n    using (var reader = new StreamReader(response.GetResponseStream())\n    {\n        string y = reader.ReadToEnd();\n        ...\n    }\n}	0
6106155	6103705	How can I send a file document to the printer and have it print?	private void SendToPrinter()\n{\n   ProcessStartInfo info = new ProcessStartInfo();\n   info.Verb = "print";\n   info.FileName = @"c:\output.pdf";\n   info.CreateNoWindow = true;\n   info.WindowStyle = ProcessWindowStyle.Hidden;\n\n   Process p = new Process();\n   p.StartInfo = info;\n   p.Start();\n\n   p.WaitForInputIdle();\n   System.Threading.Thread.Sleep(3000);\n   if (false == p.CloseMainWindow())\n      p.Kill();\n}	0
12956289	12956216	Moving folder from one location to another in a web service	string Source = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";\nstring destination = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";\nDirectoryInfo di = new DirectoryInfo(Source);\nFileInfo[] fileList = di.GetFiles(".*.");\nint count = 0;\nforeach (FileInfo fi in fileList)\n{\n    System.IO.File.Move(Source+"\\"+fi.Name , destinationFile+"\\"+fi.Name);\n}	0
11163969	11163699	Scripts compiled at runtime fail to invoke method with optional arguments	Dictionary<string, string> options = new Dictionary<string, string>();\noptions.Add("CompilerVersion", "v4.0");\nCSharpCodeProvider provider = new CSharpCodeProvider(options);	0
10120097	10119957	Return a variable based on the input of a function (.NET C# or VB)	CallByName (Me, "x", VbGet)	0
9352995	9352675	Entering menu only via Alt key	public MainWindow() {\n        InitializeComponent();\n        enableMenuTabs(false);\n        menu1.PreviewGotKeyboardFocus += delegate { enableMenuTabs(true); };\n        menu1.PreviewLostKeyboardFocus += delegate { enableMenuTabs(false); };\n    }\n\n    private void enableMenuTabs(bool enable) {\n        foreach (Control item in menu1.Items) item.IsTabStop = enable;\n    }	0
703317	701035	How do I join tables with a condition using LLBLGen?	relationships.Add(LookupTable2Entity.Relations.LookupTable1EntityUsingTable1ID, JoinHint.Left).CustomFilter = new FieldCompareValuePredicate(LookupTable2Fields.Col5, ComparisonOperator.Equal, "test");	0
6927535	6927280	NullReferenceException when setting string wp7	var response = JObject.Parse(e);\n  foreach (var item in _wall) {\n      var yh = (from ix in response["response"]\n                where (int)ix["uid"] == item.from_id\n                select ix).FirstOrDefault();\n      if (yh != null) {\n          item.image_uri = yh["photo_medium_rec"].ToString();\n          item.author_name = yh["first_name"] + " " + yh["last_name"];\n      }\n  }	0
7302832	7302516	Read all item from listbox in windows application	object obj = listBox1.SelectedItem;\nlistBox2.Items.Add(obj);\nlistBox1.Items.Remove(obj);	0
1919858	1919836	Take the datepicker value	DateTime dt = dateTimePicker1.Value;	0
7551805	7551771	How to Protect Base Field's Public/Private	public class ClassA\n{\n    private string _name;\n    public string Name { get { return _name; } protected set { _name = value; } }\n}\n\npublic class ClassB : ClassA\n{\n  /* nothing left to do - you can set Name in here but not from outside */\n}	0
11430450	11430426	How to allow user to enter only ONE SPACE after each word?	RegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@"[ ]{2,}", options);     \nMyTextBox.Text= regex.Replace(MyTextBox.Text, @" ");	0
6769439	6769389	How do we use a LINQ query on a Dictionary with a nested object?	var Result = from e in Elements \n             select new \n             { \n                 Key = e.Key, \n                 ValNum = e.Value.ValueNumber... \n             };	0
8994453	8986251	SQL Server: Store a database for portability	.\SQLExpress	0
9532630	9532473	Print a string and display the newlines & tabs in their character format	html = html.Replace("\r", "\\r").Replace("\n","\\n").Replace("\t","\\t");	0
4050434	4050052	how to copy from text box to struct C#	[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ascii)]\npublic struct mystruc\n{\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]\n    [FieldOffset(0x00)]\n    public byte[] install_name; // size limit 32 bytes\n\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]\n    [FieldOffset(0x33)]\n    public byte[] install_id;   // size limit 4 bytes\n\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]\n    [FieldOffset(0x37)]\n    public byte[] model_name;   // size limit 4 bytes\n}	0
18685295	18685136	Can I repeat a constant strings at declaration?	public class ExtendedGridCategoryAttribute : GridAttribute\n {\n      public ExtendedGridCategoryAttribute(int level, char tabCharacter)\n          : base(new string(tabCharacter, level))\n      {\n      }\n }\n\n [ExtendedGridCategory(2,'\t')]\n public string Foo { get; set; }	0
15644823	15643721	How to enable column in GridView?	protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)\n  {\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        Label a = e.Row.FindControl("Label3") as Label;\n        if (a.Text == "Sam")\n        {\n\n            e.Row.Cells[0].Enabled = true;\n            e.Row.Cells[1].Enabled = false;\n            e.Row.Cells[2].Enabled = false;\n            e.Row.Cells[3].Enabled = false;\n\n        }\n    }\n}	0
961706	961704	How do I join two paths in C#?	string basePath = @"c:\temp";\nstring filePath = "test.txt";\nstring combinedPath = Path.Combine(basePath, filePath); \n// produces c:\temp\test.txt	0
16043029	16022473	stC#: How to call a stored procedure and use a parameter as an array	db.AddOutParameter(dbCommand, "RecNum_OUT", DbType.String, 15);--	0
1796000	1795959	Define an anonymous structure as a parameter in a method	public static void Print<T>(T obj)\n{\n    Type type = typeof(T);\n    PropertyInfo[] properties = type.GetProperties();\n    foreach(PropertyInfo pi in properties)\n    {\n        Console.WriteLine(pi.Name + ": " + pi.GetValue(obj, null));\n    }\n}	0
18150470	18147147	Powershell - adding a cmdlet without visual studio	Add-Type	0
5154697	4859219	getting user profile picture using facebook c# sdk from codeplex	public static string GetPictureUrl(string faceBookId)\n    {\n        WebResponse response = null;\n        string pictureUrl = string.Empty;\n        try\n        {\n            WebRequest request = WebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture", faceBookId));\n            response = request.GetResponse();\n            pictureUrl = response.ResponseUri.ToString();\n        }\n        catch (Exception ex)\n        {\n            //? handle\n        }\n        finally\n        {\n            if (response != null) response.Close();\n        }\n        return pictureUrl;\n    }	0
12344424	12343037	How to use property Control.Enabled = false in order to make all control shadowed?	.... Form()\n{\nthis.InitializeComponent();\n\ntreeView1.EnabledChanged += (s, o) =>\n{\n    treeView1.BackColor = treeView1.Enabled ? Color.White : SystemColors.Control;\n};\n\n....\n\n}	0
848043	848030	Access to creator object	FrmModifyData = new FrmData();\nFrmModifyData.ParentData = this;\nFrmModifyData.ShowDialog();	0
12898017	12897913	C# get specific database using GetScheme	if (dbName.Contains("Logging"))\ncmbDatabaseList.Items.Add(dbName);	0
399010	398866	Instantiating objects with a Configuration class or with Parameters	Do.It(universe)	0
19182484	19182114	Shuffling a deck of cards with images	public class Dealer {\n\n  // Fisher-Yates shuffle algorithm with explicit generator\n  private static void CoreShuffle(IList<Kort> list, Random generator) {\n    if (Object.ReferenceEquals(null, list))\n      throw new ArgumentNullException("list");\n    else if (Object.ReferenceEquals(null, generator))\n      throw new ArgumentNullException("generator");\n\n    for (int i = list.Count - 1; i >= 0; --i) {\n      int index = generator.Next(i + 1);\n\n      Kurt h = list[index];\n      list[index] = list[i];\n      list[i] = h;\n    }  \n  }\n\n  public static Random rand = new Random(); // <- Be careful: Random is not thread safe; readonly is also a good addition here\n\n  // Return new shuffled list based on deckOfCards      \n  public List<Kort> ShuffledList() {\n    List<Kort> result = new List<Kort>(deckOfCards); // <- Check this line in your code\n    CoreShuffle(result, rand);\n\n    return result;   \n  }	0
14153577	14153477	parsing xml node with a value and a node inside	[System.Xml.Serialization.XmlTextAttribute()]\npublic string[] Text {get;set;}	0
9455594	9455228	How to this cube to draw in XNA with C#	//byte[] indices;\nshort[] indices;\n\n//indices = new byte[36];\nindices = new short[36];\n\n//iBuffer = new IndexBuffer(device, typeof(short), 36, BufferUsage.WriteOnly);\niBuffer = new IndexBuffer(device, IndexElementSize.SixteenBits, sizeof(short) * indices.Length, BufferUsage.WriteOnly);	0
5945406	5945393	Transfer listBox item to another listBox (Winforms C#)	private void AddClick(object sender, EventArgs e)\n{\n    // Set the DataSource property.          \n    listBox2.ValueMember = "Code";\n    listBox2.DisplayMember = "Description";    \n    listBox2.Items.Add((Violation)listBox1.SelectedItem); \n}	0
16241199	16240312	How to pass runtime argument variable in Expression.Call?	//I have other overloads for M, hence I need to specify the type of arugments\nvar methodInfo = typeof(C).GetMethod("M", new Type[] { typeof(Type), typeof(int[]) });\n\n//I fixed this issue where the first argument should be typeof(Type)\nvar typeArgumentExp = Expression.Parameter(typeof(Type));\n\nvar intArrayArgumentExp = Expression.NewArrayInit(typeof(int), Enumerable.Repeat(Expression.Constant(0), 3));\n\nvar combinedArgumentsExp = new Expression[] { typeArgumentExp }.Concat(intArrayArgumentExp);\nvar call = Expression.Call(methodInfo, combinedArgumentsExp);	0
9444312	9444191	How to read HTTP Response Body?	using (var client = new WebClient())\n{\n    string result = client.DownloadString("http://example.com/path/to/file");\n\n    switch (result)\n    {\n        case "OK":\n        case "NUMBER NOT IN LIST":\n        case "ERROR":\n            break;\n    }\n}	0
22328406	22328351	Cannot close excel from my code	appExcel = null	0
21784930	21784153	How can i assign json.net linq method according to a condition	var _JlinQ = J == "a" ? (JContainer)_JArray : (JContainer)_JObject;	0
6174933	6174605	How to create custom control with buttons and how to add event button click event in silverlight for windows mobile 7	Button btn = this.GetTemplateChild("myButton") as Button;\nbtn.Click += new RoutedEventHandler(_btn_Click);	0
11920423	11920249	How to load images in background thread without affecting the UI?	Invoke( (Action)(() => { pictureBox.image = loadedImage; }) );	0
23746020	23745763	Problems with HttpClient on WP8	client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;	0
3387303	3387222	How to get the last part of a string?	string lastPart = text.Split('/').Last();	0
30056305	30054310	How change 2 different UI text via C# script in Unity 4.6	public Text GuessUI;\npublic Text TextUI;\n\nTextUI.text = "Welcome to Number Wizard!";\nGuessUI.text = "500";	0
18381281	18381216	lambda expression and Messagebox in C#	private void SimpleLambda()\n{\n  Action<string> showMessage =  x => MessageBox.Show(x);\n\n  showMessage("Hello World!");\n}	0
12989410	12989396	C# Regex Match from TextBox.Text?	(?<=rl=').*(?=')	0
11710176	11710079	Attaching to Specific Instances of the IDE	var dte = GetDTE();\n                var debugger = dte.Debugger;\n                var processes = debugger.LocalProcesses;\n                int processIdToAttach; //your process id of second visual studio\n                foreach (var p in processes)\n                {\n                    EnvDTE90.Process3 process3 = (EnvDTE90.Process3)p;\n                    if (process3.ProcessID == processIdToAttach)\n                    {\n                        if (!process3.IsBeingDebugged)\n                        {\n                            if (doMixedModeDebugging)\n                            {\n                                string[] arr = new string[] { "Managed", "Native" };\n                                process3.Attach2(arr);\n                            }\n                            else\n                            {\n                                process3.Attach();\n                            }\n                        }\n                        break;\n                    }\n                }	0
13268008	13267937	Regex c# html spider	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(your html string);\n\nList<String> titles = (from x in doc.DocumentNode.Descendants()\n                       where x.Name == "img"\n                       && x.Attributes["title"] != null\n                       && x.Attributes["border"] != null\n                       && x.Attributes["border"].Value == "0"\n                       select x.Attributes["title"].Value).ToList<String>();	0
8263494	8263422	Matching two strings on different lines with tabs using regex	MatchCollection m1 = Regex.Matches(file, @"<span class=price>[$]\d+[.]\d+</span>[\s\n\t.]+<span class=supersaver>",\n                RegexOptions.Singleline);	0
5648113	5628230	Help with synchronization from a unit test in C#	[Test]\n    [Timeout(1250)]\n    public void Execute()\n    {\n        var locker = new object();\n        EventWaitHandle waitHandle = new AutoResetEvent(false);// <--\n        const int numberOfEvents = 10;\n        const int frequencyOfEvents = 100;\n        var start = DateTime.Now;\n        int progressEventCount = 0;\n\n        IGradualOperation tester = new TestGradualOperation(numberOfEvents, frequencyOfEvents);\n\n        var asyncExecutor = new AsynchronousOperationExecutor();\n\n        asyncExecutor.Progressed += (s, e) =>\n        {\n            lock (locker)\n            {\n                progressEventCount++;\n                waitHandle.Set();// <--\n            }\n        };\n\n        asyncExecutor.Execute(tester);\n\n        while (true)\n        {\n            waitHandle.WaitOne();// <--\n            if (progressEventCount < numberOfEvents) continue;\n            Assert.Pass("Succeeded after {0} milliseconds", (DateTime.Now - start).TotalMilliseconds);\n        }\n    }	0
11064602	10972456	How to query over a key-value collection using NHibernate?	IList<Guid> customerIds = session.CreateSQLQuery(\n            "SELECT Customer_ID FROM Banks WHERE Bank_ID = '" + this.ID + "'")\n            .List<Guid>();\n\nGuid[] array = new Guid[customerIds.Count];\ncustomerIds.CopyTo(array, 0);\n\nIList<Customer> customers = session.QueryOver<Customer>()\n                .Where(Restrictions.In("ID", array)).List();	0
2402789	2402739	How to retrieve the Screen Resolution from a C# winform app?	Form myForm;\nScreen myScreen = Screen.FromControl(myForm);\nRectangle area = myScreen.WorkingArea;	0
16821386	16783511	How to "finalize" a new row	bindingSource.EndEdit();\ndataGridView.NotifyCurrentCellDirty(true);\ndataGridView.EndEdit();\ndataGridView.NotifyCurrentCellDirty(false);	0
15938419	15938278	Drawing a line between two points using chart control	chart1.Series.Add("Line");\n        chart1.Series["Line"].Points.Add(new DataPoint(1, 1));\n        chart1.Series["Line"].Points.Add(new DataPoint(3, 3));\n        chart1.Series["Line"].ChartType = SeriesChartType.Line;	0
13768672	13768563	How to get values from dynamically created elements using jquery in code behind	Request.Form	0
24256002	24255921	remove an item from combobox	if (comboBox1.SelectedIndex != -1)\n{\n    var words = comboBox1.DataSource as List<Word>;\n    words.Remove(comboBox1.SelectedItem as Word);\n    comboBox1.DataSource = null;\n    comboBox1.DataSource = words;\n    this.comboBox1.DisplayMember = "Name";\n    this.comboBox1.ValueMember = "Value";\n    this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;\n}	0
22816987	22816928	How to check if a particular entry in a CheckedListBox is checked	CheckedListBox.GetItemChecked(index)	0
23185476	23184519	How to Regex match on spaces and replace without overwriting spaces	string[] specials = new string[] { "special1", "special2", "special3" };\nfor (int i = 0; i < specials.Length; i++)\n{\n    string match = string.Format("(?<=\\s){0}(?=\\s)", specials[i]);\n    if (Regex.IsMatch(name, match, RegexOptions.IgnoreCase))\n    {\n        name = Regex.Replace(name, match, specials[i], RegexOptions.IgnoreCase);\n        break;\n    }\n}	0
7580159	7580115	How to name method that raises an event	CheckIfLogChanged()	0
17808717	17808601	C#, JSON Parsing, dynamic variable. How to check type?	if (((JToken)obj).Type == JTokenType.Array)\n  {\n    Console.WriteLine("ARRAY!");\n  }\n  else if (((JToken)obj).Type == JTokenType.Object)\n  {\n    Console.WriteLine("OBJECT!");\n  }	0
9847039	9846135	Find a substring, replace a substring according the case	public static string ReplaceWithTemplate(this string original, string pattern, string replacement)\n{\n  var template = Regex.Match(original, pattern, RegexOptions.IgnoreCase).Value.Remove(0, 1);\n  template = template.Remove(template.Length - 1);\n  var chars = new List<char>();\n  var isLetter = false;\n  for (int i = 0; i < replacement.Length; i++)\n  {\n     if (i < (template.Length)) isLetter = Char.IsUpper(template[i]);\n     chars.Add(Convert.ToChar(\n                       isLetter ? Char.ToUpper(replacement[i]) \n                                : Char.ToLower(replacement[i])));\n  }\n\n  return new string(chars.ToArray());\n}	0
3357221	3357181	Can LINQ To SQL detect where a table association breaks?	where p.RoundFire != null	0
29612611	29607747	Getting the link for a virtual directory	var physicalPath = Path.Combine(Request.ApplicationPath, Settings.Default.KeyImagesFolder, relatedFinding.KeyImagePath);\nvar resourceUrl = Server.MapPath(physicalPath);	0
22717798	22717439	C# create combobox to insert value into mysql database	public partial class TestForm1 : TestForm\n    {\n        public TestForm1 ()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {           \n            comboBox1.Items.Add(new ComboBoxItem("value1","text1"));\n\n            foreach (object o1 in comboBox1.Items)\n            {\n                if (o1 is ComboBoxItem)\n                    MessageBox.Show("value=" + ((ComboBoxItem)o1).Value + "; text=" + ((ComboBoxItem)o1).Text);\n            }\n        }\n    }\n\n    public class ComboBoxItem\n    {\n        public string Value;\n        public string Text;\n        public ComboBoxItem(string val, string text)\n        {\n            Value = val;\n            Text = text;\n        }\n\n        public override string ToString()\n        {\n            return Text;\n        }\n    }	0
15327006	15326760	App that is not showing on projector	System.Windows.Forms.Screen.AllScreens	0
22292041	22291934	How to declare a dictionary compatible with any type in C#	public static Dictionary<int,T> FetchObjects<T>(string sqlQuery, T obj) where T : BaseClass\n{\n    DataTable dt = MyConnection.FetchRecords( sqlQuery );\n\n    Dictionary<int,T> objDict = new Dictionary<int, T>();\n\n    for(int i=0; i < dt.Rows.count; i++ ) {\n        obj.MapObjectByDataRow(dt.Rows[i]);      //Abstract function in BaseClass\n        objDict.Add(obj.Id, obj);\n    }\n\n    return objDict;\n}	0
3678259	3678184	How to make a video or audio file HTTP response always download instead of play in browser?	Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)\n Response.AddHeader("Content-Length", lenOfFile)\n Response.ContentType = "application/octet-stream"	0
18154939	18154822	Remove duplicate items in the ListBox	if (ListBox.SelectedItem != null)\n{\n   ListBox.Items.RemoveAt(ListBox.SelectedIndex);\n}	0
1332148	1332139	Calling a method from .dll globally in c# application	class SomeMainClassThatAlwaysIsUsed\n{\n    static SomeMainClassThatAlwaysIsUsed () {\n        new Kiosk.Kiosk().Disable();\n    }\n}	0
6101894	6101823	Filled Arcs in WPF	new LineSegment(new Point(x2, y2), true),\nnew ArcSegment(new Point(x3,y3),new Size(100*outerRadius,100*outerRadius), 0,largeAngle, SweepDirection.Clockwise, true),\nnew LineSegment(new Point(x4, y4), true),\nnew ArcSegment(new Point(x1, y1),new Size(100*innerRadius,100*innerRadius), 0,largeAngle, SweepDirection.Counterclockwise, true),	0
32140679	32140439	Winform C# Update DataGridView on DataTable Cell value changed	private DataTable _dt = new DataTable();  \n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n\n    _dt.Columns.Add("LongText");\n    DataRow dr = _dt.NewRow();\n    dr[0] = "One";\n    _dt.Rows.Add(dr);\n    dr = _dt.NewRow();\n    dr[0] = "Two";\n    _dt.Rows.Add(dr);\n    dr = _dt.NewRow();\n    dr[0] = "Three";\n    _dt.Rows.Add(dr);\n    dataGridView1.DataSource = _dt;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    _dt.Rows[0][0] = "daddy";\n}	0
24116882	24116683	Unable to run application	private void button1_Click(object sender, EventArgs e)\n{\n    Process myProc = new Process();\n    myProc.StartInfo.WorkingDirectory = "C:\\";\n    myProc.StartInfo.FileName = "Chat APP.exe";\n    myProc.Start();\n}	0
15752392	15744130	How to add radcombobox to cell in a table row cell	RadComboBox comboBox = new RadComboBox\n{\n    ID = "Foo"\n}\n\ncomboBox.Items.Add(new RadComboBoxItem((0).ToString(), "FirstItem"));\n\nnewCell.Controls.Add(comboBox);	0
1184818	1184812	How to compute a running sum of a series of ints in a Linq query?	int sum = 0;\nint[] b = a.Select(x => (sum += x)).ToArray();	0
10567993	10567984	RedirectToAction from inside [HttpPost] to [HttpGet] - parameters	[HttpPost]\npublic ActionResult Edit(EditViewModel viewModel, string itemId="")\n{\n    // ...\n\n    RedirectToAction("Edit", new { id = itemId });\n}	0
11748653	11745709	Dapper stored procedures with Postgresql without alphabetical parameters	GetProperies(...)	0
9803780	9803738	DateTime string format last digit of year	int digit = date.Year % 10;	0
9458769	9456879	Determine hard drive serial number in mono?	/sbin/udevadm info --query=property --name=sda	0
20464339	20460583	Text, audio resources in windows store apps	var uri = new Uri("ms-appx:///images/logo.png");\nvar file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);	0
9645052	9645009	I have inserted a row, I want to get it's ID and plus it with an int and insert in that row	objCommand.Connection = objConnection;\n            objCommand.CommandText = "INSERT INTO Moin " +\n                " (Title, TotalID, Code ) " +\n                "VALUES (@Title , @TotalID, @Code ) SELECT SCOPE_IDENTITY()";\nobject id = objCommand.ExecuteScalar();	0
11882665	11882173	Find Min and Max value in table between given variable in C#	using (var context = new YourContext()) {\n    var val = 15;\n    var query2 = context.Table\n        .GroupBy(\n            x => new {\n                IsGreaterThan = x.Column > val,\n                IsLessThan = x.Column < val\n            },\n            (key, data) => new { key = key, data = data.Select(x => x.Column) }\n        )\n        .Select(x => x.key.IsGreaterThan ? x.data.Min() : x.data.Max())\n        .ToList();\n    Console.WriteLine("First value larger than {0} = {1}", val, query2[0]);\n    Console.WriteLine("First value smaller than {0} = {1}", val, query2[1]);\n    Console.ReadLine();\n    return;\n}	0
17105518	17042314	devcomponents ribbon bar quick access toolbar	BaseItem.visible = false	0
1170393	1170383	C# console application icon	/win32icon:<file>	0
22024429	22024159	Facebook chat PLAIN authentication issue Windows Phone	public string SendWihSsl(string dataToSend)\n{\n    Byte[] data = System.Text.Encoding.UTF8.GetBytes(dataToSend);\n\n    ssl.Write(data, 0, data.Length);\n    ssl.Flush();\n    data = new Byte[2048];\n\n    int myBytesRead = 0;\n    StringBuilder myResponseAsSB = new StringBuilder();\n    do\n    {\n        myBytesRead = ssl.Read(data, 0, data.Length);\n        myResponseAsSB.Append(System.Text.Encoding.UTF8.GetString(data, 0, myBytesRead));\n        if (myResponseAsSB.ToString().IndexOf("</") != -1)\n        {\n            break;\n        }\n    } while (myBytesRead != 0);\n\n    return myResponseAsSB.ToString();\n}	0
169893	169866	Export pictures in Microsoft Word to TIFF	private void SaveToImage(Word.InlineShape picShape, string filePath)\n    {\n        picShape.Select();\n        theApp.Selection.CopyAsPicture();\n        IDataObject data = Clipboard.GetDataObject();\n        if (data.GetDataPresent(typeof(Bitmap)))\n        {\n            Bitmap image = (Bitmap)data.GetData(typeof(Bitmap));\n            image.Save(filePath);\n        }\n    }	0
19257947	19207278	mvvmlight windows 8 metro async load data in viewmodel constructor	ViewModelBase.IsInDesignModeStatic	0
10235091	10235038	How to generate a random number with 8 digits total in C#? (4 integer, 4 fractional part)	random.Next(10000000, 99999999+1) / 10000.0d;	0
29777104	29087675	Requests POI from a location using Xamarin (Android)	private void button1_Click(object sender, EventArgs e)\n{\n  HttpWebRequest webRequest = WebRequest.Create(@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=7500&types=library&sensor=false&key=AIzaSyD3jfeMZK1SWfRFDgMfxn_zrGRSjE7S8Vg") as HttpWebRequest;\n  webRequest.Timeout = 20000;\n  webRequest.Method = "GET";\n\n  webRequest.BeginGetResponse(new AsyncCallback(RequestCompleted), webRequest);\n}\n\nprivate void RequestCompleted(IAsyncResult result)\n{\n  var request = (HttpWebRequest)result.AsyncState;\n  var response = (HttpWebResponse)request.EndGetResponse(result);\n  using (var stream = response.GetResponseStream())\n  {\n    var r = new StreamReader(stream);\n    var resp = r.ReadToEnd();\n  }\n}	0
11704191	11704154	How to add information to database from gridview?	cmd.ExecuteNoneQuery();	0
13361753	13361690	How can i set a control event to null	this.listView.ItemChecked -= myEventHandler;\n\n// run some code\n\nthis.listView.ItemChecked += myEventHandler;	0
6284342	6284324	Extract substrings from a given string in C#	var name = theString.SubString(theString.IndexOf(' ') + 1);	0
7876456	7876363	Convert Entity Framework Object to JSON Object	class Dog {\n    private Bone myBone;\n    public Dog() {\n        myBone = new Bone(this);\n    }\n}\n\nclass Bone {\n    private Dog buriedBy;\n    public Bone(Dog d) {\n        buriedBy = d;\n    }\n}	0
6172768	6172301	How to get only those colums in a EXCEL worksheet that have a value	Excel.Application demoApp= new Excel.Application();\ndemoApp.Workbooks.Open(fileName);\nint rowCount = demoApp.ActiveSheet.UsedRange.Rows.Count;\nint colCount = demoApp.ActiveSheet.UsedRange.Columns.Count;	0
19412651	19412152	Getting the scrolling offset when storing coordinates	if (e.Button == MouseButtons.Left) {\n        var newPoint = new Point(e.X - this.AutoScrollPosition.X,\n                                 e.Y - this.AutoScrollPosition.Y);\n        // etc..\n    }	0
23161150	23160854	Performing background tasks in asp.net MVC4	Task.Factory.StartNew(() =>\n    {\n        //do something here with your Request.Files[0].InputStream;\n    },\n    CancellationToken.None,\n    TaskCreationOptions.LongRunning, // guarantees separate thread\n    TaskScheduler.Default);	0
12688265	12688245	How to loop over each line from a TextReader?	string line = null;\nwhile((line = reader.ReadLine()) != null) \n{\n    // do something with line\n}	0
24924127	24923689	C# Replacing Multiple Spaces with 1 space leaving special characters intact	foreach (string s in output.Split())\n{\n    var sessionName = s.Substring(0, 18).Trim();\n    var userName = s.Substring(18, 19).Trim();\n    var id = Int32.Parse(s.Substring(37, 8).Trim());\n    var whateverType = s.Substring(45, 12).Trim();\n    var device = s.Substring(57, 6).Trim();\n}	0
14497083	14496929	Want to fetch xml Values from string parameter	public class Program {\n    public static void Main(String[] args) {\n        XDocument xdoc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF-8""     standalone=""yes""?>\n<person>\n  <first-name>RaJeEv(??)</first-name>\n  <last-name>Diboliya</last-name>\n  <headline>Software Engineer at FASTTRACK INDIA.</headline>\n  <site-standard-profile-request>\n    <url>http://www.linkedin.com/profile?viewProfile</url>\n  </site-standard-profile-request>\n</person>");\n\n        XElement xe = xdoc.Elements("person").First();\n\n        Console.WriteLine("{0} {1}", xe.Element("first-name").Value, xe.Element("last-name").Value);\n    }         \n}	0
9883125	9873951	EF getting the current ObjectContext	public void context_SavingChanges(object sender, EventArgs e)\n{\n    ObjectContext context = sender as ObjectContext;\n    // Do whatever you need to do...\n}	0
29942702	29942666	List of distinct dates	dates = dates.Select(x => x.Date).Distinct().ToList();	0
21051864	21051743	Submit POST request from codebehind in ASP.NET	string URI = "http://www.myurl.com/post.php";\nstring myParameters = "param1=value1&param2=value2&param3=value3";\n\nusing (WebClient wc = new WebClient())\n{\n    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";\n    string HtmlResult = wc.UploadString(URI, myParameters);\n}	0
23058921	23058292	Row index from hierarchical gridview	protected void imgExpandSource_Click(object sender, ImageClickEventArgs e)\n{\n\n    ImageButton imgExpandSource = sender as ImageButton;\n    GridViewRow gvrow = (GridViewRow)imgExpandSource\n                             // GridViewRowRow of gvSource\n                             .NamingContainer\n                             // gvSource\n                             .NamingContainer\n                             // GridViewRow of gvTest\n                             .NamingContainer;\n    int x = gvrow.RowIndex;\n}	0
8640306	8639679	Stale data in first level cache	session.Refresh(cat);	0
29476098	29475824	SQLite local database in unity 3D	public void ClearFirstName(string tableName, string firstname )\n{\n    string query ;\n    query = "UPDATE " + tableName + " SET FirstName = '' WHERE FirstName = '" + firstname + "'";        \n    dbcmd = dbcon.CreateCommand();\n    dbcmd.CommandText = query;\n    reader = dbcmd.ExecuteReader();\n}	0
31191528	31147279	Convert HttpContent into byte[]	if (!content.IsMimeMultipartContent())\n{\n    throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");\n}\n\nvar uploadPath = **whatever**;\nif (!Directory.Exists(uploadPath))\n{\n    Directory.CreateDirectory(uploadPath);\n}\n\nvar provider = new MultipartFormDataStreamProvider(uploadPath);\nawait content.ReadAsMultipartAsync(provider);\n\nreturn File.ReadAllBytes(provider.FileData[0].LocalFileName);	0
4123721	4123462	Query rows that the datatable field contain any item in the list<string>	DataTable datatbl = new DataTable();\n        datatbl.Columns.Add(new DataColumn("description",typeof(string)));\n        // add simple test rows\n        datatbl.Rows.Add("I'm feeling lucky today.");\n        datatbl.Rows.Add("I'm feeling bad today.");\n        datatbl.Rows.Add("I'm feeling good today.");\n        // more test rows here...\n        List<string> lst = new List<string>(new string[] { "Lucky", "bad", "ok" });\n\n        var item =\n            from a in datatbl.AsEnumerable()\n            from b in lst\n            where a.Field<string>("description").ToUpper().Contains(b.ToUpper())\n            select a;\n\n        var item2 =\n            from a in datatbl.AsEnumerable()\n            where lst.Any(x => a.Field<string>("description").ToUpper().Contains(x.ToUpper()))\n            select a;	0
16273740	16273673	Retrieve and store two values from SQL Server into c#	using(var command = new SqlCommand("SELECT [Value1], [Value2] FROM [ExampleTable] where Ad_name=@adname", con))\n{\n    command.Parameters.AddWithValue("@adname", aname);\n\n    using(var reader = command.ExecuteReader())\n    {\n        while (reader.Read())\n        {\n            imgpath1 = reader[0];\n            imgpath2 = reader[1];\n        }\n    }\n}	0
3733362	3733337	Displaying two web pages on one page	var the_height=document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;//find the height of the internal page\n\nvar the_width=document.getElementById('the_iframe').contentWindow.document.body.scrollWidth;//find the width of the internal page	0
30952043	30951910	Unable to modify variables from separate thread	Sleep()	0
15230873	15230839	How to add object to context handling duplicates correctly?	foreach (var a in LocalAList)\n{ \n  if (a.Id == 0)\n    dbContext.Add(a);\n   else \n    dbContext.As.Attach(a)\n\n   dbContext.SaveChanges();\n}	0
27000600	27000350	Find an element with a period in it's name	var node = navigator.SelectSingleNode("//*[local-name()='TRANSACTION.TYPE']");	0
12495242	12494917	Serialize/deserialize double value to/from hex format	[Serializable()]\npublic class Variable\n{\n    int _shiftInt;\n\n    public string shift\n    {\n        get\n        {\n            return _shiftInt.ToString("X");\n        }\n        set\n        {\n            _shiftInt = int.Parse(value, System.Globalization.NumberStyles.HexNumber);\n        }\n    }\n\n    public int size { get; set; }\n    public int min { get; set; }\n    public int max { get; set; }\n    public string name { get; set; }\n    public string del { get; set; }\n\n    public Variable()\n    {\n        _shiftInt = 26;\n        size = 0;\n        min = 0;\n        max = 0;\n        name = "noname";\n        del = "-";\n    }\n}	0
9620175	9620061	How to recuperate the image of this rss feed ?	var reg = new Regex("src=(?:\"|\')?(?<imgSrc>[^>]*[^/].(?:jpg|bmp|gif|png))(?:\"|\')?");\n    var match=reg.Match(source);\n    if(match.Success)\n    {\n      var encod = match.Groups["imgSrc"].Value;\n    }	0
29555899	29554837	Populate Buttons With Database Values c#	for (int i = 0; i < 5; i++)\n        {\n            Button newPanelButton = new Button();\n            newPanelButton.Name = "txtRuntime" + i;\n            newPanelButton.Text = "Runtime"+i;\n            newPanelButton.Location = System.Drawing.Point.Add(new Point(4 + i * 307, 4), new Size(20, 20));// here make use of your logic.\n\n            this.Controls.Add(newPanelButton);\n        }	0
5670863	5662500	Overriding ComboBox to select item by pressing index through keyboard in C#	public class MyComboBox : ComboBox\n{\n    protected override void OnKeyPress(KeyPressEventArgs e)\n    {\n        var index = e.KeyChar - '1';\n        if( index >= 0 && index < this.Items.Count )\n            this.SelectedIndex = index;\n\n        base.OnKeyPress(e);\n    }\n}	0
14376538	14366055	How can I register concrete class based on last interface in structuremap	ObjectFactory.Initialize(c => c.Scan(scan =>\n{\n    scan.TheCallingAssembly();\n    scan.AddAllTypesOf<IHandleDomainService>();\n}));	0
19845015	19844974	Why am I getting a value of zero for my circle?	class Circle\n{\n    private double radius;\n\n    public Circle(double radius)\n    {\n        this.radius = radius;\n    }\n\n    public double Area\n    {\n        get { return Math.PI * Math.Pow(radius, 2); }    \n    }\n}	0
1277609	1277563	How do I get the handle of a console application's window	IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;	0
31401348	31400953	Differentiate between multiple dynamic fileupload controls	for (int i = 0; i <= Request.Files.Count - 1; i++)\n            {\n                HttpPostedFile PostedFile = Request.Files[i];\n                var controlName = Request.Files.Keys[i];\n                if (PostedFile.ContentLength > 0)\n                {\n                    //Store PostedFile here\n                    //(Left out to improve question readability)\n                }\n            }	0
13068475	13068442	Changing position of words in a string	DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);\nConsole.Write(dt.ToString("yyyy MM dd"));	0
12040996	12038985	Execute SET statement before STORED PROCEDURE call	"SET wsrep_on = 0; EXEC StoredProc @Param1;"	0
25446664	25443902	Excel addon for VBA editing	Sub ModifyVBACode()\n    Dim sCodeSource As String\n\n    'Get the source code in a string'\n\n    With ThisWorkbook.VBProject.VBComponents("CodeName").CodeModule\n        sCodeSource = .Lines(1, .CountOfLines)\n    End With\n\n    'modify your code'\n\n    With ThisWorkbook.VBProject.VBComponents("CodeName").CodeModule\n        'Delete the old source code'\n        .DeleteLines 1, .CountOfLines\n\n        'write the new one'\n        .AddFromString sCodeSource\n    End With\nEnd Sub	0
13069386	13069385	How can I express that an argument needs to implement multiple interfaces in C#	internal interface IF1\n{\n    void M1();\n}\n\ninternal interface IF2\n{\n    void M2();\n}\n\ninternal class ClassImplementingIF1IF2 : IF1, IF2\n{\n\n    public void M1()\n    {\n        throw new NotImplementedException();\n    }\n\n    public void M2()\n    {\n        throw new NotImplementedException();\n    }\n\n}\n\ninternal static class Test\n{\n\n    public static void doIT<T>(T t) where T:IF1,IF2\n    {\n        t.M1();\n        t.M2();\n    }\n\n    public static void test()\n    {\n        var c = new ClassImplementingIF1IF2();\n        doIT(c);\n    }\n}	0
31705604	31705407	How to get values out of XML elements containing a colon	XNamespace rs = "urn:schemas-microsoft-com:rowset"; //<---\nXNamespace z = "#RowsetSchema"; //<---\nvar doc = XDocument.Parse(DATA);\n\nIEnumerable<XElement> list = doc.Root.Descendants(rs + "data");\nstring returnValue = "";\nforeach (var item in list.Elements(z + "row")) //<---\n{\n    returnValue += item.Attribute("POSITION").Value; //<---\n    returnValue += "|";\n}	0
9080363	9080042	I want to enter data from a GridView into a Word document and have it downloaded from client	Response.ContentType = "application/octet-stream"	0
10752893	10752807	Build C# dll from SQL table	System.Resources.ResourceManager	0
4837927	4837789	How to create rtf using xml xslt and c#	XslCompiledTransform proc = new XslCompiledTransform();\nproc.Load("stylesheet.xslt");\nproc.Transform("input.xml", "output.rtf");	0
25676418	25676380	Select items in List that match an interface	IStepBuildDataSet buildDataSet = Steps.OfType<IStepBuildDataSet>().Single();\nIStepBuildFile buildFile = Steps.OfType<IStepBuildFile>().Single();	0
27659165	27659104	C# Result to a new line	var simple = new Simple3Des("randompass");\nvar input = txtAccount.Text.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);\n\nvar output = new StringBuilder();\n\nforeach (var i in input)\n    output.AppendLine(simple.Encode(i));\n\ntxtEncrypted.Text = output.ToString();	0
5106822	5106546	How to set size of form without heading and borders?	this.ClientSize = new Size(300, 300);	0
10830689	10829763	Accessing Excel Graphs in C#	private List<double> ExtractChartValues(FileInfo excelFile, string sheetName, int drawing, int chartSerie)\n{\n  ExcelPackage ePack = new ExcelPackage(excelFile);\n  ExcelWorksheet ws = ePack.Workbook.Worksheets[sheetName];\n\n  List<double> result = new List<double>();\n  ExcelChart ec = (ExcelChart)ws.Drawings[drawing];\n  ExcelRange dataRange = ws.Cells[ec.Series[chartSerie].Series];\n  foreach (ExcelRangeBase data in dataRange)\n  {\n    if (data.Value != null)\n      result.Add((double)data.Value);\n  }\n  return result;\n}	0
23759828	23759504	Actions datetimeoffset to local user settings region	DateTime .ToUniversalTime	0
33483112	33442875	Entity Framework 6 - Having the Primary Key as the property of a Type	public partial class MyEntity\n{\n    public MyEntityId BadIdea { get; set; }\n\n    [Key]\n    public Guid Id \n    { \n       get \n       { \n            // needs null check\n            return BadIdea.Value; \n       } \n       set \n       { \n           // needs null check\n           BadIdea.Value = value; \n       }\n    }\n}	0
854530	854500	Ways in .NET to get an array of int from 0 to n	arr = Enumerable.Range(0, n);	0
30736822	30715782	Link button Delete from ListView and DB in C#	private string currentProgramId;\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        currentProgramId = Request.QueryString["ProgramId"];	0
28264229	28261664	How to Click on specific button in web browser	HtmlElementCollection classButton = webBrowser1.Document.GetElementsByTagName("input"); \n\nforeach (HtmlElement element in classButton)\n\n{\n    var value = element.GetAttribute("value");\n\n    if (value.Trim().ToLower().Equals("????? ?? ???"))\n        {\n           element.InvokeMember("click");\n        }\n}	0
17248985	17248979	How to run Devexpress report designer at runtime ?	using System;\nusing System.Windows.Forms;\nusing DevExpress.XtraReports.UI;\n// ... \n\nprivate void Form1_Load(object sender, EventArgs e) {\n    XtraReport1 report = new XtraReport1();\n    ReportDesignTool dt = new ReportDesignTool(report);\n\n    // Invoke the standard End-User Designer form. \n    dt.ShowDesigner();\n\n    // Invoke the standard End-User Designer form modally. \n    dt.ShowDesignerDialog();\n\n    // Invoke the Ribbon End-User Designer form. \n    dt.ShowRibbonDesigner();\n\n    // Invoke the Ribbon End-User Designer form modally. \n    dt.ShowRibbonDesignerDialog();\n}	0
11030795	11030731	FluentNhibernate: Configure Database in XML	// read hibernate.cfg.xml\n Configuration config = new Configuration().Configure();\n // load mappings from this assembly\n Fluently\n      .Configure(config)\n      .Mappings(\n           m => m.FluentMappings.AddFromAssemblyOf<Program>())\n      );	0
28920036	28919973	Determining the Parent Folder of a given Path in C#	var info = Directory.GetParent(@"directory_path");\nvar name = info.Name; //this will give parentdirectory\nvar fullName = info.FullName; //this will give pages/parentdirectory	0
22247131	22246805	How to decode a URL in Portable Class Library (PCL)?	var urlDecoded = Uri.UnescapeDataString(urlEncoded).Replace('+', ' ');	0
10364359	10364287	Binding data to a ComboBox using code behind	cmbCapsNme.ItemsSource = ds.Tables[0];	0
14176007	14175191	Where do I place a custom membership provider in my project architecture?	Company.Security	0
19470549	19071504	Schedule Task to run every 1 hour	TransformBlock<int, int> block = new TransformBlock<int, int>(i =>\n{\n    //Thread.Sleep(5000);\n    DoSomething();\nreturn i + 1;\n});\n\nblock.LinkTo(block);\nblock.Post(0);	0
25050418	24783286	OpenXML Sax method for exporting 100K+ rows to Excel fast	for (int i = 1; i <= 50000; ++i)\n{\n    oxa = new List<OpenXmlAttribute>();\n    // this is the row index\n    oxa.Add(new OpenXmlAttribute("r", null, i.ToString()));\n\n    oxw.WriteStartElement(new Row(), oxa);\n\n    for (int j = 1; j <= 100; ++j)\n    {\n        oxa = new List<OpenXmlAttribute>();\n        // this is the data type ("t"), with CellValues.String ("str")\n        oxa.Add(new OpenXmlAttribute("t", null, "str"));\n\n        // it's suggested you also have the cell reference, but\n        // you'll have to calculate the correct cell reference yourself.\n        // Here's an example:\n        //oxa.Add(new OpenXmlAttribute("r", null, "A1"));\n\n        oxw.WriteStartElement(new Cell(), oxa);\n\n        oxw.WriteElement(new CellValue(string.Format("R{0}C{1}", i, j)));\n\n        // this is for Cell\n        oxw.WriteEndElement();\n    }\n\n    // this is for Row\n    oxw.WriteEndElement();\n}	0
8512979	8512966	How to use Where with IEnumerable assignment?	IEnumerable<ProductUser> products = myP2Locator\n                                    .GetMasterDBC()\n                                    .ProductUsers\n                                    .Where(pu => pu.UserId == userId);	0
26860301	26797856	Detect return from system screen	// Code to execute when the application is activated (brought to foreground)\n// This code will not execute when the application is first launched\nprivate void Application_Activated(object sender, ActivatedEventArgs e)\n{\n   //do stuff\n}\n\n// Code to execute when the application is deactivated (sent to background)\n// This code will not execute when the application is closing\nprivate void Application_Deactivated(object sender, DeactivatedEventArgs e)\n{\n   //do stuff\n}	0
23782608	23779309	Return a variable value and output from PL/SQL code block to C#	using (OracleCommand cmd = cnn.CreateCommand())\n{\n    OracleParameter status = new OracleParameter(":1", OracleType.VarChar, 32000);\n    p_line.Direction = ParameterDirection.Output;\n\n    OracleParameter line = new OracleParameter(":2", OracleType.Double);\n    p_status.Direction = ParameterDirection.Output;\n\n    OracleParameter stage= new OracleParameter("stage", OracleType.Int16);\n    p_country_name.Direction = ParameterDirection.Output;    \n\n    cmd.CommandText = script;\n    cmd.CommandType = CommandType.Text;\n    cmd.Parameters.Add(status);\n    cmd.Parameters.Add(line );\n    cmd.Parameters.Add(stage);\n    cmd.ExecuteNonQuery();\n\n    string status = status.Value.ToString();\n    string line = line.Value.ToString();\n    string stage= stage.Value.ToString();\n}	0
15162306	15162247	Dictionaries: An item with the same key has already been added	m_OrderManager.ListOrders()\n                        .OrderBy(x => x.m_ShippedDate)\n                        .Select(x =>x.m_ShippedDate)\n                        .Distinct()\n                        .ToDictionary(x => x.ToString(), x => x);	0
11353484	11353444	How to split a Chinese string by character?	s.Append(character);\ns.Append('\n');	0
8827731	8827649	Fastest way to convert int to 4 bytes in C#	unsafe static void Main(string[] args) {\n        int i = 0x12345678;\n        byte* pi = (byte*)&i;\n        byte lsb = pi[0];  \n        // etc..\n    }	0
13284985	13282572	Unity resolve parameter with named mapping	var container = new UnityContainer();\n\ncontainer.RegisterType<ISessionManager, DefaultSessionManager>()\n  .RegisterType<ISessionManager, OnCallSessionManager>("oncall")\n  .RegisterType<CustomerService>()\n  .RegisterType<CustomerService>(\n    "oncall",\n    new InjectionConstructor(\n      new ResolvedParameter(\n        typeof(ISessionManager),\n        "oncall")))\n  .RegisterType<ViewModel>()\n  .RegisterType<DataManager>(\n    new InjectionConstructor(\n      new ResolvedParameter(\n        typeof(CustomerService),\n        "oncall")));	0
24043133	24042664	How to set an image source in code-behind inside a library?	var assemblyName = this.GetType().GetTypeInfo().Assembly.GetName().Name;\nthis.MyImage.Source = new BitmapImage(new Uri(this.BaseUri, assemblyName + imagePath));	0
26355893	26345748	issue with Playerprefs	function OnTriggerEnter (other : Colliderstrong text){\n   if (collisionAlreadyConsidered) return;\n   collisionAlreadyConsidered = true;\n   // your code here...\n}\n\nfunction Update(){\n   collisionAlreadyConsidered = false;\n}	0
15812144	15811670	jquery how to write proper json object in c#	List<Person> people = new List<Person>();\nPerson p = new Person();\n\nwhile (dr.Read()) {\n    p = new Person();\n    p.id = dr["SpecialtyID"].ToString().Trim();\n    p.name = dr["SpecialtyName"].ToString().Trim();\n    people.Add(p);\n}\n\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nstring return_str = serializer.Serialize(people);	0
9907635	9907370	add/remove List<> items selected in a ListBox	//Take the existing\n    List<MailerKit> objExisting = (List<MailerKit>)comboBox1.DataSource;\n    //Add the new one\n    objExisting.Add(new MailerKit { KitName = comboBox1.SelectedText, ID = Convert.ToInt32(comboBox1.SelectedValue) });\n\n    //Rebind again\n    comboBox1.DataSource = objExisting;\n    comboBox1.DisplayMember = "KitName";\n    comboBox1.ValueMember = "ID";	0
4377096	4377013	From byte[] to XmlTextReader	byte[] buffer = new byte[5000]; // TODO a revoir\nint sizeReceived;\n\nsizeReceived = _socket.Receive(buffer);\nMemoryStream memory = new MemoryStream(buffer, 0, sizeReceived);\nreturn new XmlTextReader(memory);	0
29682823	29682772	Button cannot access text box	Control container = new Control();\nLoginView1.RoleGroups[0].ContentTemplate.InstantiateIn(container);\nforeach (Control control in container.Controls)\n{\n    if (control.ID == "txtName")\n    {\n        //Phew. Got your control\n    }\n}	0
19587091	19586133	StyleCop issue needs resolving - contains a call chain that results in a call to a virtual method defined by the class	protected override sealed void BaseAdd(ConfigurationElement policy)\n{\n    BaseAdd(policy, false);\n}	0
28315533	28315161	Rename runtime-generated names of columns of a devexpress datagrid	gridView1.Columns["fileName"].Caption = "Your custom name";	0
26841739	26841465	[SOLVED]how to display health using GUIText?	void OnGUI(){\n    GUI.color = Color.red;\n    GUI.Label(new Rect (20,20,200,20), "Health = " + hp);\n}	0
10614122	10614088	filtering a sublist of strings in C#	Regex reg = new Regex(query);\nvar searchHits = GetAll().Where(x => x.Keywords.Any(k => reg.IsMatch(k)));	0
22338460	22338356	How to add parentheses to (change text of) ListBox item based on condition?	var formatDiscount = discount != 0 ? "({0})" : "{0}";\nlstInfo.Items.Add(string.Format(formatline1, "Program Discount", string.Format(formatDiscount, discount.ToString("C2"))));	0
34116462	34115890	Add consecutive numbers to a limit, display how many iterations	int count_birthdays = 0;\nint used_candles = 0;\nwhile (used_candles <= candles)\n{\n    count_birthdays++;\n    used_candles = used_candles + count_birthdays;\n}	0
27883429	27883374	Formatting issue adding folder names to listbox C#	var path = Path.Combine(Directory.GetCurrentDirectory() + "\\MyProgram\\Test\\");\nforeach (var folder in Directory.GetDirectories(path))\n{\n    listBox1.Items.Add(folder.Remove(0, path.Length));\n}	0
1821909	1821885	Need help with C# generics	public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships	0
9567078	9566557	How to make a reference to a method name on an interface strongly typed	public static AResponse DoA2(ARequest aRequest)\n  {\n    return DoGen<ARequest, AResponse>(aRequest, worker => worker.DoA);\n  }\n  public static BResponse DoB2(BRequest bRequest)\n  {\n    return DoGen<BRequest, BResponse>(bRequest, worker => worker.DoB); \n  }\n  public static TResponse DoGen<TRequest, TResponse>(TRequest requestObj, \n       Func<IWorker, Func<TRequest, TResponse>> methodRef)\n    where TRequest : class\n    where TResponse : class\n  {\n    // lots of common code for logging & preparation \n    var worker = GetWorker();\n    var method = methodRef(worker);\n\n    return method(requestObj);\n  }	0
19330782	19330581	Pagging issue with subreport in RDLC report	AsyncRendering="True"	0
20747202	20746944	How to add namespace to XPath in C#?	XPathDocument oXPathDocument = new XPathDocument(path);\nXPathNavigator oXPathNameNavigator = oXPathDocument.CreateNavigator();\nXmlNamespaceManager nameSpace = new XmlNamespaceManager(oXPathNameNavigator.NameTable);\n//use the namespace address provided in the XML, not the path to the xml itself\nnameSpace.AddNamespace("ir","http://www.ikea.com/v1.0");\n\n//now you have to scope your query to the namespace you just defined, otherwise xpath will assume the node is not in a namespace\nproductModel.productName = oXPathNameNavigator.SelectSingleNode("//ir:ikea-rest/products/product/name", nameSpace).Value;	0
30769069	30768748	Need help making a File Export function remember the path that the user selects	public class MyClass\n{\n    private string selectedPath = "";\n\n    public void Export(int formatVersion, bool pureXmlDriver)\n    {\n        if (Device != null)\n        {\n            Utilities.StripShortNameFromLongNames(Device);\n            using (var folderBrowser = new FolderBrowserDialog())\n           {\n               folderBrowser.Description = Resources.SelectExportFolder;\n               folderBrowser.SelectedPath = selectedPath;\n               if (folderBrowser.ShowDialog() == DialogResult.OK)\n               {\n                   selectedFolder = folderBrowser.SelectedPath;\n                   try\n                   {\n                       Cursor = Cursors.WaitCursor;\n                       HandleExport(formatVersion, pureXmlDriver, selectedFolder);\n                   }\n                   finally\n                   {\n                       Cursor = Cursors.Default;\n                   }\n               }\n           }\n       }\n   }    \n}	0
31214754	31214529	C# validate XML file using XSD file	XmlDocument doc = new XmlDocument() ;\ndoc.load(xmlFileName) ;\ndoc.Schemas.Add("",xsdFileName);\ndoc.Schemas.Compile();\nTheSchemaErrors   = new List<string>() ;\nTheSchemaWarnings = new List<string>() ;\ndoc.Validate(Xml_ValidationEventHandler);\nif (TheSchemaErrors  .Count>0) { // display errors  }\nif (TheSchemaWarnings.Count>0) { // display warnings  }\n...\nprivate List<string> TheSchemaErrors ;\nprivate List<string> TheSchemaWarnings ;\n\nprivate void Xml_ValidationEventHandler(object sender,ValidationEventArgs e)\n{\n  switch (e.Severity)\n  {\n    case XmlSeverityType.Error   : TheSchemaErrors  .Add(e.Message) ; break;\n    case XmlSeverityType.Warning : TheSchemaWarnings.Add(e.Message) ; break;\n  }\n}	0
16148587	16148149	Preventing multiple entries in a foreach statement	foreach (var childOrg in viewModel.ChildOrganizations)\n{\n    List<OrganizationUserViewModel> childOrgUsers = new List<OrganizationUserViewModel>();\n    var users = this._organizationManager.GetOrganizationUsers(childOrg.OrganizationId);\n    foreach (var user in users)\n    {\n        var userViewModel = Gateway.Instance.Map<User, OrganizationUserViewModel>(user.User);\n        userViewModel.Organization_UserId = user.Organization_UserId;\n        if (selectedUsers != null)\n        {\n            var foundUser = selectedUsers.FirstOrDefault(x => x.UserId == userViewModel.UserId);\n\n            if(foundUser == null)\n            {\n                childOrgUsers.Add(userViewModel);\n            }\n        }\n    }\n    childOrg.Users = childOrgUsers.Distinct().ToList();\n}	0
20072721	20071806	Implementing separate application instances in taskbar like Skype	CompanyName.ProductName.SubProduct.VersionInformation	0
8610883	8610872	multiple c# windows form application	newForm.Show();\nthis.Hide();	0
5856186	5855946	Different ComboBox values in DataGridView in different rows	(dgv.Rows[i].Cells[5] as DataGridViewComboBoxCell).DataSource = dt;\n(dgv.Rows[i].Cells[5] as DataGridViewComboBoxCell).ValueMember = "sellingPrice";\n(dgv.Rows[i].Cells[5] as DataGridViewComboBoxCell).DisplayMember = "sellingPrice";	0
16740053	16736529	passing in a generated guid as qrcode data - LeadTools	Guid stringGUID = Guid.NewGuid().toString();	0
11865657	11865061	Linq to XML C# Descendants: How to read Attributes with the same name?	XDocument loaded = XDocument.Parse(readString);\n        var items = loaded\n                    .Descendants("return")\n                    .FirstOrDefault()\n                    .Element("ItemsBase")\n                    .Elements("item");\n        int i = 0;\n        foreach (var _item in items)\n        {\n            item[i, 0] = _item.Element("ItemID").Value;\n            item[i, 1] = _item.Element("Texts").Element("Name").Value;\n            item[i, 2] = _item.Element("PriceSet").Element("PurchasePriceNet").Value;\n            i++;\n        }	0
684392	684257	How do I configure a single component instance providing multiple services in Castle.Windsor?	container.Register(Component.For<IEntityIndexController, ISnippetController>()\n.ImplementedBy<SnippetController>()\n.LifeStyle.Transient);	0
11749945	11749599	Cast byte string to human-readble old-fashion string	string byteStr = input.Substring(2);\nbyte[] bytes = new byte [ byteStr.Length / 2 ];\nfor ( int i = 0, j = 0 ; i < byteStr.Length ; i += 2 , j++ )\n{\n     bytes [ j ] = byte.Parse ( byteStr.Substring ( i , 2 ) , NumberStyles.HexNumber );\n}\nstring str = Encoding.UTF8.GetString ( bytes );\nbyte[] UTF32Bytes = Encoding.UTF32.GetBytes ( str );	0
19726112	19725918	Will using ref in relation to a struct cause it to be stored on the heap?	var g = new Geoff(); //value type\nList<object> objects = new List<object>(); //collection of objects (reference type)\nobjects.Add(g); //implicitly casting g to object	0
22914707	22913935	Delete Button for each ListView Row	Button btn = (Button)sender;\nPeople.Remove((Person)btn.DataContext);	0
8935152	8935056	Cloning objects without Serialization	public static T DeepClone<T>(this T a)\n    {\n        using (MemoryStream stream = new MemoryStream())\n        {\n            DataContractSerializer dcs = new DataContractSerializer(typeof(T));\n            dcs.WriteObject(stream, a);\n            stream.Position = 0;\n            return (T)dcs.ReadObject(stream);\n        }\n    }	0
12241114	12241084	How to insert data into SQL Server	using(SqlConnection openCon=new SqlConnection("your_connection_String"))\n    {\n      string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";\n\n      using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))\n       {\n         querySaveStaff.Connection=openCon;\n         querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;\n         .....\n         openCon.Open();\n\n         openCon.Close();\n       }\n     }	0
8739164	8738887	DbSortClause expressions must have a type that is order comparable parameter Name :Key	u.UserClientRoles.OrderBy(r => r.Role.RoleName)	0
25250902	25250824	Windows Phone with Json - Error reading JObject from JsonReader	JArray arr = JArray.Parse(json);\n\nforeach (JObject obj in arr.Children<JObject>())\n{\n...\n}	0
4591875	4587047	storing JSON data in db	string Response = Utilities.HttpUtility.Fetch("https://graph.facebook.com/me?access_token=" + AccessToken, "GET", string.Empty);\n            using (System.IO.MemoryStream oStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(Response)))\n            {\n                oStream.Position = 0;\n                return (Models.FacebookUser)new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Models.FacebookUser)).ReadObject(oStream);\n            }	0
26677886	26672521	Hidden expander overlap below it	public int indexx = -1;\nprivate void StackPanel_Click(object sender, RoutedEventArgs e)\n{\n\n    if (indexx == 1)\n    { \n        indexx = -1;\n        Canvas.SetZIndex(panel, indexx);\n\n    }\n    else\n    {\n        indexx = 1;\n        Canvas.SetZIndex(panel, indexx);\n    }\n\n}	0
4907449	4906410	linq to sql, make one db call instead of three	var sum = (from p in db.Posts where p.Aspnet_User.UserName == userName select p.UpVotes).Concat\n                (from e in db.Events where e.Aspnet_User.UserName == userName select e.UpVotes).Concat\n                (from c in db.Comments where c.Aspnet_User.UserName == userName select (c.UpVotes - c.DownVotes)).Sum()	0
26363038	26357020	C# WebBrowser Page Scrolling From Code	HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\n        HtmlElement s = webBrowser1.Document.CreateElement("script");\n        s.SetAttribute("text", "function functionName() { /* Code to Execute in JS */ }");\n        head.AppendChild(s);\n        webBrowser1.Document.InvokeScript("functionName");	0
16660105	16659787	Convert string to binary zeros and ones	foreach (char c in "Test")\n    Console.WriteLine(Convert.ToString(c, 2).PadLeft(8, '0'));	0
2883645	2883576	How do you convert epoch time in C#?	public DateTime FromUnixTime(long unixTime)\n{\n    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n    return epoch.AddSeconds(unixTime);\n}	0
8259220	8255946	C# and XML - Read XML files from user-specified location	List<string> files = Directory.GetFiles("c:\\MyDir", "*.xml").ToList();    \n\nforeach(string fileLocation in files)\n{\n      XmlDocument obj = new XmlDocument();\n      obj.Load(filelocation);\n\n      //Your code to place the xml in a queue.\n}	0
16111213	16111148	How to covert shortened html string into actual html link in label	var date = "Tue Apr 16 20:30:32 +0000 2013";\nvar text = "Here is some social media news for the week... http://t.co/RR5DKvqUjd";\nvar textwithanchor = Regex.Replace(text, @"\(?\bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]", delegate(Match match)\n    {\n        return string.Format("<a href='{0}'>{0}</a>", match.ToString());\n    });\nvar html = "<strong>created_at:</strong> " + date + "<strong>&nbsp text:</strong> " + textwithanchor + "<br />";	0
26630217	26629934	How do I append a bit string in text block of a Windows Store app?	foreach (bool bit in encoded)\n{\n    tb2.Text += ((bit ? 1 : 0) + "");\n}	0
7279537	7279001	Loading large data	IList<MyObject> GetPageOfMyObjects(int pageSize, int zeroBasedPageNumber) {\n\n    return Session.CreateCriteria(typeof (MyObject))\n                    .SetFirstResult(pageSize*(pageNumber))\n                    .SetMaxResults(pageSize)\n                    .List<MyObject>();\n\n}	0
14592963	14592928	How do I open a SQL Server database read-only?	GRANT EXEC ON <proc> TO <user>	0
12969562	12891647	How to set the DisplayRectangle property of a control (.NET)	public class ExtendedControl : Control\n{\n    private Rectangle displayRectangle;\n\n    protected override Rectangle DisplayRectangle\n    {\n        get { return this.displayRectangle; }\n    }\n\n    public void SetDisplayRectangle(Rectangle rect)\n    {\n        this.displayRectangle = rect;\n    }\n\n    public EntendedControl()\n    {\n        this.displayRectangle = base.DisplayRectangle;\n    }\n}	0
26191957	26191936	Invalid cast exception while trying to set control visibility	System.Web.UI.HtmlControls.HtmlImage img = (System.Web.UI.HtmlControls.HtmlImage)e.Row.FindControl("img_expand1");\nimg.Visible = false;	0
404663	404651	How to get a specific cell in a DataGridView on selection changed	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n{\n    DataGridView dgv = (DataGridView)sender;\n\n    //User selected WHOLE ROW (by clicking in the margin)\n    if (dgv.SelectedRows.Count> 0)\n       MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());\n\n    //User selected a cell (show the first cell in the row)\n    if (dgv.SelectedCells.Count > 0)\n        MessageBox.Show(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());\n\n    //User selected a cell, show that cell\n    if (dgv.SelectedCells.Count > 0)\n        MessageBox.Show(dgv.SelectedCells[0].Value.ToString());\n}	0
17606255	17605824	Finding missing number in a sequence	var numbers = new List<int>{4, 8, 12, 16, 24, 28, 36};\nint first = numbers.First();\nint last = numbers.Last();\n\nvar missing = Enumerable.Range(first, last).Where(n => n % first == 0).Except(numbers);\n\n\nReturns:\n20\n32	0
5374459	5374435	regex for dates	Regex regex = new Regex("(?<day>\d{2})[.](?<month>\d{2})\[.](?<year>(\d{4}|\d{2}))", RegexOptions.CultureInvariant);\n\nMatch match = regex.Match("20.03.2011");\nif (match.Success)\n{\n   if (match.Groups["day"] != null)                           \n   {\n        string day = match.Groups["day"].value;\n   }\n   //etc.\n}	0
13116922	13116035	Failing to use String.Format to display Version String in WPF	verString = String.Format("FPGA 0x42 Version (dd/mm/yyyy ID): {0}/{1}/20{2} {3}", ((buffer[3] & 0xF8) >> 3), \n        (buffer[2] & 0x0F), ((buffer[2] & 0xF0) >> 4), (buffer[3] & 0x07));	0
18688252	18688125	Access items in listbox in windows phone 7?	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    using (bus_noContext ctx = new bus_noContext(bus_noContext.ConnectionString))\n    {\n        ctx.CreateIfNotExists();\n        ctx.LogDebug = true;\n        var buses = from c in ctx.Bus_routes\n                         select new bus_list{ BUS_NO = c.BUS_NO, SOURCE = c.SOURCE, DESTINATION = c.DESTINATION};\n        busno_list.ItemsSource = buses.ToList();\n\n        searchbox.Text = buses[20].SOURCE; // or whatever\n    }\n}	0
32990776	32679823	How to select multiple items using Autocomplete extender in c#?	DelimiterCharacters="," and ShowOnlyCurrentWordInCompletionListItem="true"	0
16161364	16155405	Back Button/ Cancel Button during In App Purchase	try\n{\n  receipt = await CurrentApp.RequestProductPurchaseAsync("MyItem", false);\n}\ncatch (Exception){}\n\n.... other code	0
14402769	14401018	Entity Framework - Challenging setup includes multiple primary keys, and multiple associations to foreign table	public class Customer\n{\n[Key, Required]\npublic string Code { get; set; }\n\npublic string Domain { get; set; }\n\npublic virtual ICollection<Address> Addresses{ get; set; }\n\npublic virtual Address BillToAddress { get { Addresses.Where(n=>n.Type = Address.BillingAddress)).Single(); }\n\npublic virtual ICollection<Address> ShipToAddresses { get { Addresses.Where(n=>n.Type = Address.ShipToAddress)); }\n}	0
25730765	25730691	Use Linq to remove dulicates that vary by one column value	var items = new List<Item>\n{\n    new Item {Color = "Green", Id = 1},\n    new Item {Color = "Red", Id = 1},\n    new Item {Color = "Red", Id = 2},\n    new Item {Color = "Green", Id = 3},\n    new Item {Color = "Red", Id = 4},\n    new Item {Color = "Green", Id = 4},\n};\n\nvar q = items.GroupBy(x => x.Id)\n             .Select(group => new \n                     {\n                         Id = group.Key, \n                         Green = group.Any(item => item.Color == "Green"), \n                         Red = group.Any(item => item.Color == "Red") \n                     });	0
32781985	32780498	Trying to read from XML File to List to use for DDT	[XmlRoot(ElementName="ClubRegisterQuick")]\npublic class Root\n{\n    public List<Club> Clubs { get; set; }\n}\n\n[Serializable]\npublic class Club\n{\n    public string Email { get; set; }\n    public string Clubname { get; set; }\n    public string Clubphonenumber { get; set; }\n    public string Firstname { get; set; }\n    public string Lastname { get; set; }\n    public string Town { get; set; }\n    public string Country { get; set; }\n    public string Location { get; set; }\n    public string Currency { get; set; }\n    public string Password { get; set; }\n    public string Clubtype { get; set; }\n}	0
7932970	7931531	How can I use Moles to return different values for multiple calls to a method in C#?	var toggle = false;\nMSomeInstance.SomeMethod.AllInstances.SomeMethod =\n    @this => { toggle = !toggle; return toggle; };	0
26651180	26644799	Drawing walls - visible only one side	RasterizerState rs = new RasterizerState();\nrs.CullMode = CullMode.None; \n\nGraphicsDevice.RasterizerState = rs;	0
6776259	6124865	C# VSTO Add-in - Convert plain text email to HTML	Inspector.CommandBars.ExecuteMso("MessageFormatHtml")	0
27249661	27249625	How to get sum of different columns in same row?	Table.Where(row => row.Id == 2).Sum(row => row.Col1 + row.Col3)	0
6036362	6036293	Encapsulating C# GUI components in a DLL	public interface CoolGui {\n  void DrawGui(Graphics g); \n}	0
13155086	13155050	Send Message using C#	using System.Net;\nusing System.IO;\nWebClient client = new WebClient ();\n// Add a user agent header in case the requested URI contains a \nquery.\nclient.Headers.Add ("user-agent", "Mozilla/4.0\n (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR\n1.0.3705;)");\nclient.QueryString.Add("user", "xxxx");\nclient.QueryString.Add("password", "xxxx");\nclient.QueryString.Add("api_id", "xxxx");\nclient.QueryString.Add("to", "xxxx");\nclient.QueryString.Add("text", "This is an example message");\nstring baseurl ="http://api.clickatell.com/http/sendmsg";\nStream data = client.OpenRead(baseurl);\nStreamReader reader = new StreamReader (data);\nstring s = reader.ReadToEnd ();\ndata.Close ();\nreader.Close ();\nreturn (s);	0
21308149	21306626	Creating a ThreadLocal EF context	using (DBEntities ctx = new DBEntities())\n{\n    // Explicitly open the context connection yourself - to help prevent connection pooling / sharing\n    // The connection will automatically be closed once exiting the using statement,  \n    // but it won't hurt to put a ctx.Connection.Close(); after everything inside the using statement.\n    ctx.Connection.Open();\n\n    // Do Stuff\n\n    // If necessary ctx.SaveChanges();\n    // Not necessary but you could put a ctx.Connection.Close() here, for readability if nothing else.\n}	0
15822779	15815361	How to add new tab in CMS desk in kentico cms	CMSDeskPage.GetDocumentPageUrlInternal(...)	0
8538087	8535877	How to bind Report Viewer with a Dictionary<string,int> as the data source?	var table = new DataTable();\nvar kvps = dictionary.ToArray();\ntable.Columns.AddRange(kvps.Select(kvp => new DataColumn(kvp.Name)).ToArray());\ntable.LoadDataRow(kvps.Select(kvp => kvp.Value).ToArray(), true);\nbindingSource.DataSource = table;	0
5160478	5061093	Dividing by power of 2 using bit shifting	public int DivideByPowerOf2(int x, int n)\n    {\n\n        return (x + ((x >> 31) & ((1 << n) + ~0))) >> n;\n    }	0
33961884	33923200	Two AutoCompleteBox controls in two different tabs in wpf	private void tabCtrl_SelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n            if (e.Source is TabControl)\n            {\n              // Business logic for binding autocompletebox\n            }\n        }	0
9769823	9769691	How to rewrite a SQL query in LINQ to Entities?	var brandNames =\n    from brand in db.Brands\n    where brand.ID == 1\n    select name;\n\nvar brandProductNames =\n    from p in db.all_products_option_names\n    where p.optionID == 7\n    where brandNames.Contains(p.option_value)\n    select p.productId;\n\nvar results =\n    from p in db.all_products_option_names\n    where p.optionID == 14\n    where brandProductNames.Contains(p.productId)\n    select new\n    {\n        setID = p.variantID, \n        name = p.option_value, \n        description = p.option_value_description, \n        sortOrder = p.sort_order\n    };	0
11051977	11051716	How to get datatable from stored procedure?	create or replace PROCEDURE "SP_UTILITIES_LOG" ( \np_utility_name IN varchar2, \np_r_object_id IN varchar2, \n/* your other parameters */\np_refcur out sys_refcursor /* notice the out parameter */\n)\nAS\nBEGIN\n/* one sample from your select*/\nIF(p_utility_name ='PRE-TRANSFORMATION')\n THEN     \n BEGIN     \n      OPERN p_refcur FOR \n      SELECT exported_file_path,component_tcm_id FROM utilities_log     \n      WHERE     platform_name= p_platform_name \n     AND        loading_status=p_loading_status      \n     AND extraction_status=p_extraction_status;       \n END;     \n END IF; \nEND;	0
4712871	3355416	How can I call a method from within a LINQ expression?	public IQueryable<Person> GetPersons()\n        {\n            var list = context.Persons.select(p=>p).AsEnumerable()\n                      .Select(m=>m.MyExtensionMethod());\n            return list;\n        }	0
12732784	12730304	Edit a XSL:param in C#	PARAM_blah.InnerText = "Content 2";\n  xslDoc.Save(@"c:\params.xslt")	0
8205752	8205738	How to add a control to a added tab C#	myTabPage.Controls.Add(tb);	0
33605308	33601567	Adding functionality to custom control	public class NumericUpDown : Control\n{\n    static NumericUpDown()\n    {\n        DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericUpDown), \n            new FrameworkPropertyMetadata(typeof(NumericUpDown)));\n    }\n\n    public override void OnApplyTemplate()\n    {\n        base.OnApplyTemplate();\n\n        Button increaseButton = this.GetTemplateChild("increaseButton") as Button;\n        if (increaseButton != null)\n        {\n            increaseButton.Click += increaseButton_Click;\n        }\n    }\n\n    private void increaseButton_Click(object sender, RoutedEventArgs e)\n    {\n        // Do what you want to do.\n    }\n}	0
14776257	14776177	Serialize C# Enum Definition to Json	Dictionary<string,int>	0
33250886	33250328	I need to find the file path and file name of a file that matches the string lastline	try\n        {\n            string lastline = "Controller"; // assuming you know the file your searching for\n            foreach (string filePaths in Directory.GetDirectories(@"E:\Program Files (x86)\foobar2000\library\"))\n            {\n                foreach (string f in Directory.GetFiles(filePaths, "*" + lastline + "*.*"))\n                {\n                    Console.WriteLine(f); // would print the filepath n the file name\n\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }	0
1111218	1111194	C# function to find the delta of two numbers	delta = Math.Abs(a - b);	0
15246596	15246533	WEBMETHOD: Add details of two columns into third column	public void MethodName(string firstName, string lastName)\n{\n       string FullName = firstName + lastName;\n       /*INSERT (firstName, lastName, FullName) using INSERT QUERY */\n}	0
16233607	16163107	EWS API: How to get pull notifications?	public void SubscribePullNotifications(FolderId folderId)\n{\n    Subscription = Service.SubscribeToPullNotifications(new FolderId[] { folderId }, 1440, null, EventType.NewMail, EventType.Created, EventType.Deleted);\n}\n\npublic void GetPullNotifications()\n{\n    IEnumerable<ItemEvent> itemEvents = Subscription.GetEvents().ItemEvents;\n    foreach (ItemEvent itemEvent in itemEvents)\n    {\n        switch (itemEvent.EventType)\n        {\n            case EventType.NewMail:\n                MessageBox.Show("New Mail");\n                break;\n        }\n    }\n}\n// ...\nSubscribePullNotifications(WellKnownFolderName.Inbox);\nTimer myTimer = new Timer();\nmyTimer.Elapsed += new ElapsedEventHandler(GetPullNotifications);\nmyTimer.Interval = 10000;\nmyTimer.Start();	0
15718464	15718091	How to implement Action delegate?	TextBox txt = Util.ApplySettings(o =>\n{\n    o.Caption = "Name";\n    o.FieldName = "UserName";\n    o.Width = 20;\n    o.Name = "txtName";\n});\n\npublic class Util\n{\n    public static TextBox ApplySettings(TextBoxConfig config)\n    {\n        //Doing something\n    }\n\n    public static TextBox ApplySettings(Action<TextBoxConfig> modifier)\n    {\n        var config = new TextBoxConfig();\n        modifier(config);\n\n        return ApplySettings(config);            \n    }\n}	0
33348672	33347552	Outlook Ui element, Object reference not set	public string txt_name;\n\n          public void setValues()\n          {\n             lbl_text.Text = txt_name;\n          }\n\n          public string set_lbl_text\n          {\n             get { return lbl_Task_text.Text; }\n             set {\n                     this.txt_name = value;                    \n                 }\n          }	0
19968857	19968648	How to get text from textBlock during SelectionChangeEvent from a ListBox?	var item = listBox.SelectedItem as className; // like ShareMediaTask\n\nvar task = new ShareMediaTask();\ntask.FilePath = item.imagePath;\ntask.Show();	0
1975569	1975556	Linq - OrderBy the minimum value of two columns using lambda expressions?	myEntitySet.OrderBy(e => e.DateA < e.DateB ? e.DateA : e.DateB);	0
13680326	13678642	how to move entire existing excel range to one row down using interop in C#	// Inserts a new row at the beginning of the sheet\nMicrosoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );\na1.EntireRow.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, \n                    Type.Missing );	0
15640043	15639809	How to print on UI and then make UI Thread wait for sometime in the same Click event in Windows phone app	await Task.Delay(1000);\n\n\npublic async void myMethod(){\n    printString1();\n    await Task.Delay(1000);\n    showImage();\n    await Task.Delay(1000);\n    printString2();\n}	0
31498860	31498443	Unable to read pixels from bitmap using Xamarin	Bitmap b = BitmapFactory.DecodeResource(Resources,Resource.Drawable.pic1);	0
14499808	13893344	GridLookUpEdit Set Index	int x = XGridLookUpEdit.Properties.GetIndexByKeyValue(XGridLookUpEdit.EditValue);\nXGridLookUpEdit.EditValue = \n    XGridLookUpEdit.Properties.View.GetRowCellValue(x + 1, "id");	0
33914788	33914313	Decrease price value	float price2 = float.Parse(price.Text, CultureInfo.InvariantCulture);\nminus.Click += delegate\n{\n    counttext.Text = string.Format("{0}", --count);\n    price.Text = string.Format("{0}", count * price2 + "???");\n};	0
5904370	5878463	Simplest way to post to a facebook fan page's wall with C#!	dynamic messagePost = new ExpandoObject();\nmessagePost.access_token = "[YOUR_ACCESS_TOKEN]";\nmessagePost.picture = "[A_PICTURE]";\nmessagePost.link = "[SOME_LINK]";\nmessagePost.name = "[SOME_NAME]";\nmessagePost.caption = "{*actor*} " + "[YOUR_MESSAGE]"; //<---{*actor*} is the user (i.e.: Aaron)\nmessagePost.description = "[SOME_DESCRIPTION]";\n\nFacebookClient app = new FacebookClient("[YOUR_ACCESS_TOKEN]");\n\ntry\n{\n    var result = app.Post("/" + [PAGE_ID] + "/feed", messagePost);\n}\ncatch (FacebookOAuthException ex)\n{\n     //handle something\n}\ncatch (FacebookApiException ex)\n{\n     //handle something else\n}	0
30531505	30531348	How can I resolve this loop in c#?	string prevState = string.Empty;\n   for (int i = 0; i < records.Rows.Count; i++)\n    {\n\n        string address = records.Rows[i][1].ToString(); \n        string  state = records.Rows[i][2].ToString();\n\n    if (!state.Equals(prevSate))\n    {\n        streetDictionary = state + ".txt";\n        if(File.Exists(streetDictionary))\n        {\n            //Here I need to identify state change, \n            //so if state change , to use another dictionary and load it, \n            //but if don't change it (state), I need to use the same dictionary \n            //(if is load it yet)\n            LoadStreetDictionary(streetDictionary);\n        }\n\n\n     }\n\n     //Process Address Standardization\n     StreetNameStandardization(address)\n     prevState = state; //Assigned to latest value\n    }	0
32205879	32205658	Linq - how to sort dynamically by three expressions?	var query = this.DbContext.RecipeTranslations\n            .Where(x => x.Language.Code == this.CurrentLanguge)\n            .Where(x => string.IsNullOrEmpty(name) || x.Title.Contains(name))\n            .Select(x => x.Recipe)\n            .Where(x => x.IsDeleted == false)\n            .Where(x => category == null || x.Categories.Any(cat => cat.Id == category));\n\nif (order == 1)\n{\n    query = query.OrderByDescending(byRank);\n}\nelse if (order == 2)\n{\n    query = query.OrderByDescending(byPopularity);\n}\nelse\n{\n    query = query.OrderByDescending(byCreatedOn);\n}\n\n// Finally\nvar list = query.Skip(start).Take(size).toList();	0
7982537	7982315	Compare two Lists using LINQ	var beforeListById = beforeList.ToDictionary(item => item.Id); \nvar afterListById = afterList.ToDictionary(item => item.Id); \n\nvar finalResult = from id in beforeListById.Keys.Union(afterListById.Keys)\n\n                  let before = beforeListById.ContainsKey(id) ? beforeListById[id] : null\n                  let after = afterListById.ContainsKey(id) ? afterListById[id] : null\n\n                  select new Record\n                  {\n                      Id = id,\n                      Description = (after ?? before).Description,\n                      Operation = (before != null && after != null) \n                                   ? (after.Description == before.Description ? "Null" : "Update")\n                                   : (after != null) ? "Add" : "Delete"\n                  };	0
433676	433668	How can I create an alias for a generic class in C#?	using Foo = System.Collections.Generic.KeyValuePair<int, string>;\n\nclass C { Foo x; }	0
7603103	7492318	Setting the visibility for a ThumbnailToolBarButton	if ( buttonPlayPause.Icon == Properties.Resources.play )\n    buttonPlayPause.Icon = Properties.Resources.pause;\nelse\n    buttonPlayPause.Icon = Properties.Resources.play;	0
25852562	25852551	How to add basic authentication header to WebRequest	string username = "Your username";\nstring password = "Your password";\n\nstring svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));\n\nrequest.Headers.Add("Authorization", "Basic " + svcCredentials);	0
30851234	30851209	How to call function on every value of String List and change it?	s.Tags = s.Tags.Select(t => TagCleaner.foo(t)).ToList();	0
28018149	27948824	Get IDropTarget with HWND throw 0xC0000005 access violation	DataObject daobj = new DataObject();\nStringCollection strcol = new StringCollection();\nstrcol.Add("F:\\test.jpg");\ndaobj.SetFileDropList(strcol);\nIDropTarget dt = (IDropTarget)ctrl;\ndt.OnDragDrop(new DragEventArgs(daobj, 0, 0, 0, DragDropEffects.Copy, DragDropEffects.Copy));	0
9226881	9226850	How to loop through and test values of properties of already instantiated object in .NET	var target = new MyObject();\n\nforeach(var property in target.GetType().GetProperties())\n{\n    Type propertyType = property.PropertyType;\n    object actual = property.GetValue(target, null);\n    object expected = propertyType.IsValueType\n        ? Activator.CreateInstance(propertyType)\n        : null;\n    Assert.AreEqual(expected, actual);\n}	0
25381117	25381094	Replace a substring	public string MyPrefixReplace(string source, string value, char delimiter = '.')\n{\n    var parts = source.Split(delimiter);\n    parts[0] = value;\n    return String.Join(delimiter.ToString(), parts);   \n}	0
14683294	14551450	How to hand code people picker in sharepoint 2010 for Coded UI	//write ur code here to find the parent control\nUITestControlCollection controlFound = matching.FindMatchingControls();\n//use loop to find the control	0
27906315	27904788	Alternate path in Orchard	public IEnumerable<string> SubPaths() {\n    return new[] { "Views", "Views/Items", "Views/Parts", "Views/Fields" };\n}	0
34259200	34259163	How to write to excel c#	object[,] arr = new object[rowCount, columnCount];\n    //Assign your values here\n\n    Excel.Range c1 = (Excel.Range)worksheet.Cells[0, 1];\n    Excel.Range c2 = (Excel.Range)worksheet.Cells[rowCount - 1, columnCount];\n    Excel.Range range = wsh.get_Range(c1, c2);\n\n    range.Value = arr;	0
17180363	17180325	Passing data to executable file with PHP	static void Main(string[] args)\n    {\n        string a;\n        if(args.Length == 0)\n        {\n             Console.Write("Please enter a string : ");\n             a = Console.ReadLine();\n        }\n        else\n             a = args[0];\n\n        Console.WriteLine("You have entered: {0}", a);\n        Console.ReadKey();\n    }	0
10354308	10354129	Check whether datagridview had been edited	protected override void OnLoad(EventArgs e)\n    {\n        myDataGridView.CellValueChanged += new DataGridViewCellEventHandler(\n        myDataGridView_CellValueChanged);\n    }\n\n    private void myDataGridView_CellValueChanged(\n    object sender, DataGridViewCellEventArgs e)\n    {\n       //some very crude examples of actions you might want to perform when the event handler is triggered.\n       myObject.update();\n       //or something else like\n       myObject.isUpdatable = true;\n    }	0
8327192	8326989	Usage of generics with windows forms	[Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic YourItemsCollection Items\n{\n    get { ... }\n    set { ... }\n}	0
22142866	22102212	How to free image cache/memory in Windows Phone 8?	BitmapImage image = new BitmapImage(); \nimage.DecodePixelType = DecodePixelType.Logical; \nimage.CreateOptions = BitmapCreateOptions.BackgroundCreation; \nimage.CreateOptions = BitmapCreateOptions.DelayCreation; \nimage.DecodePixelWidth = 56; \nimage.DecodePixelHeight = 100;	0
21964443	21964304	Deserialize Json Property's Property to Property	var jObject = JObject.Parse(json);\njObject["items"] = jObject["items"]["data"];\n\nMyData data = JsonConvert.DeserializeObject<MyData>(jObject.ToString());	0
24916423	24916235	Getting multiple address for a mail in .pst files	Outlook.Application app = new Outlook.Application();\n    Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");\n    outlookNs.AddStore(@"D:\pst\Test.pst");\n    Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);\n    List<MailItem> lstMails = emailFolder.Items.OfType<MailItem>().Where(x=>x.SenderEmailAddress.Contains("hari")).Select(x=>x).ToList();\n    foreach (Object obj in emailFolder.Items)\n    {\n       if(obj is MailItem)\n        {\n            MailItem item = (MailItem)obj;\n           String user=String.Empty;\n            foreach (Object obj1 in ((dynamic)item).Recipients)\n            {\n                user += ((dynamic)obj1).Name + ";";\n            }\n            Console.WriteLine(user + " " + item.Subject + "\n" + item.Body);\n        }\n    }	0
11675862	11675622	Split String into Array with No Delimiter	Dim parts = Regex.Matches(s, ".{2}").Cast(Of Match)().Select(Function(m) m.Value)	0
32219540	32219502	Remove duplicates from list, but keep their count numbers	for (int i = articleFullList.Count - 1; i >= 0; i--)	0
29397519	29397453	Change position of Columns In Excel file using C#	Excel.Range copyRange = xlWs.Range["C:C"];\n    Excel.Range insertRange = xlWs.Range["A:A"];\n    insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, copyRange.Cut());	0
7487948	7487702	WinForms ListBox Right-Click	private void Form1_Load(object sender, EventArgs e)\n{\n  listBox1.MouseDown += new MouseEventHandler(listBox1_MouseDown);\n}\n\nvoid listBox1_MouseDown(object sender, MouseEventArgs e)\n{\n  if (e.Button == MouseButtons.Right)\n  {\n    MessageBox.Show("Right Click");\n  }\n}	0
2839185	2839168	How to add identity column to datatable using c#	private void AddAutoIncrementColumn()\n{\n    DataColumn column = new DataColumn();\n    column.DataType = System.Type.GetType("System.Int32");\n    column.AutoIncrement = true;\n    column.AutoIncrementSeed = 1000;\n    column.AutoIncrementStep = 10;\n\n    // Add the column to a new DataTable.\n    DataTable table = new DataTable("table");\n    table.Columns.Add(column);\n}	0
11039585	11038416	Quering MS Access from C#	private void filterButton_Click(object sender, EventArgs e)\n{\n    dataGridView1.Columns.Clear();\n    MessageBox.Show(nameFilter.Text);\n    InitializeComponent();\n    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";\n    try\n    {\n        using (DataTable dt = new DataTable())\n            {\n                using (OleDbDataAdapter da = new OleDbDataAdapter(new SqlCommand("SELECT id FROM table1",new OleDbConnection(connectionString))))\n                {\n                    da.Fill(dt);\n                    MessageBox.Show(dt.Rows.Count.ToString());\n                    dataGridView1.DataSource = dt;\n                    dataGridView1.Update();\n                }\n            }       \n\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show(ex.Message);\n        return;\n    }\n}	0
3158939	3158674	Insert a new item into listview	ListViewGroup myGroup = items.Groups[0];\n     ListViewItem lvi = new ListViewItem(itemtext, myGroup);	0
934722	934486	How do I get a NameTable from an XDocument?	XmlReader reader = new XmlTextReader(someStream);\nXDocument doc = XDocument.Load(reader);\nXmlNameTable table = reader.NameTable;	0
33813261	33811997	Unable to post data to nodejs server using C# HttpClient	var express = require('express')\nvar bodyParser = require('body-parser')\n\nvar app = express()\n\n// parse application/x-www-form-urlencoded\napp.use(bodyParser.urlencoded({ extended: false }))\n\n// parse application/json\napp.use(bodyParser.json())	0
5620927	5620603	Non-Blocking read from standard I/O in C#	var buf=new byte[2048];\nvar inputStream=Console.OpenStandardInput(); //dispose me when you're done\ninputStream.BeginRead(buf,0,buf.Length,ar=>{\n    int amtRead=inputStream.EndRead(ar);\n    //buf has what you need. You'll need to decode it though\n},null);	0
6777660	6752526	how can i get the selected value of a multi-item checklistbox, c#, winforms	foreach (object itemChecked in chkListPatients.CheckedItems) \n    {\n        DataRow row = (itemChecked as DataRowView).Row;\n        string id = row[0].ToString();\n        MessageBox.Show(id);\n    }	0
16700536	16699817	Where clause not entering lambda	public IEnumerable<int> InfiniteRepeat(int i)\n{\n    do\n    {\n        yield return i;\n    } while (true);\n}	0
11573450	11573191	Syntax of a for-loop without braces?	for(int i = 0; i < 10; ++i) { Console.WriteLine(i) }	0
29453214	29452722	how to know which RedirectToAction I need?	public static class MyHelper\n{\n    public static Foo DoSomething() { return new Foo();  }\n}\n\npublic class MyController1 : Controller\n{\n    public ActionResult Index()\n    {\n        var result = MyHelper.DoSomething();\n        return File(...);\n    }\n}\n\npublic class MyController2 : Controller\n{\n    public ActionResult Index()\n    {\n        var result = MyHelper.DoSomething();\n        return JSON(...);\n    }\n}	0
860369	860305	How to use Linq to group every N number of rows	var q = Enumerable.Range(0, 100).GroupBy(x => x/3);	0
1024160	1024043	getting intellisense to show properties in markup for a custom server control	get;set;	0
33173583	33173335	Getting contents of Media Library Item in Sitecore	Sitecore.Data.Items.Item sampleItem = Sitecore.Context.Database.GetItem("/sitecore/media library/Files/yourhtmlfile");\nSitecore.Data.Items.Item sampleMedia = new Sitecore.Data.Items.MediaItem(sampleItem);\nusing(var reader = new StreamReader(MediaManager.GetMedia(sampleMedia).GetStream().Stream))\n{\n    string text = reader.ReadToEnd();\n}	0
13647741	13647455	Group by foreach bug	foreach(IGrouping<T1, T2> g in ViewBag.Links)\n{\n    ...\n}	0
10889425	10889273	How do I translate from typeName strings to generics?	public ActionResult DoSomething(string typeName, int? id)\n{\n    Type thisType = this.GetType(); // Get your current class type\n    var type = Type.GetType(typeName);\n    MethodInfo doSomethingElseInfo = thisType.GetMethod("DoSomethingElse");\n    MethodInfo concreteDoSomethingElse = doSomethingElseInfo.MakeGenericMethod(type);\n    concreteDoSomething.Invoke(this, null);\n}	0
12599652	12599374	CollectionViewSource MVVM Implementation for WPF DataGrid	public class ViewModel : NotifyProperyChangedBase\n{       \n    string uri;\n\n    public ObservableCollection<Movie> MovieList { get; private set; }\n\n    public CollectionView MovieView { get; private set; }\n\n    public ViewModel(MoveList movieList)\n    {\n        MovieList = movieList;\n        MovieView = GetMovieCollectionView(MovieList);\n        MovieView.Filter = OnFilterMovie;\n    }\n\n    public void UpdateDataGrid(string uri)\n    {     \n        this.uri = uri;\n        MovieView.Refresh();\n    }\n\n    bool OnFilterMovie(object item)\n    {\n        var movie = (Movie)item;\n        return uri.Contains(movie.ID.ToString());\n    }\n\n    public CollectionView GetMovieCollectionView(ObservableCollection<Movie> movList)\n    {\n        return (CollectionView)CollectionViewSource.GetDefaultView(movList);\n    }\n}	0
3618900	3618806	Make all controls on a form read-only at once	if (_cached == null)\n{\n    _cached = new List<TextBox>();\n\n    foreach(var control in Controls)\n    {\n        TextBox textEdit = control as TextBox;\n        if (textEdit != null)\n        {\n            textEdit.ReadOnly = false;\n            _cached.Add(textEdit);\n        }\n    }\n} \nelse\n{\n    foreach(var control in _cached)\n    {            \n        control .ReadOnly = false;\n    }\n}	0
4924176	4924126	Throttle CPU Usage of Application	System.Diagnostics.Process.PriorityClass	0
24898839	24878187	SignalR: Detecting Alive Connection in C# clients	public override Task OnDisconnected(bool stopCalled)\n{\n    if (stopCalled)\n    {\n        // We know that Stop() was called on the client,\n        // and the connection shut down gracefully.\n    }\n    else\n    {\n        // This server hasn't heard from the client in the last ~35 seconds.\n        // If SignalR is behind a load balancer with scaleout configured, \n        // the client may still be connected to another SignalR server.\n    }\n\n    return base.OnDisconnected(stopCalled);\n}	0
12215164	12214850	Formatting ASP.NET Gridview Money Values	DataFormatString="??{0:###,###,###.00}"	0
30526464	30526051	how to extract attribute from tag xml with c#?	"/channel/item/enclosure/param[@name='url']/@value"	0
28028213	28027886	How can I change a public variable in the Inspector?	GameObject.Find("Wanderer").GetComponent<SteerForTeether>().TetherPosition = "whatever";	0
5324911	5324884	Increase Value of Dictionary at a specified Key	MyDictionary[person.personID] += 1;	0
16696078	16695846	How to disable/enable a DropDownList with a button using JavaScript in ASP	if (gg.disabled) {\n         gg.removeAttribute("disabled");\n     } else {\n        gg.disabled = 'disabled';\n     }	0
4336361	4336336	Using C#, how can I update listbox Items from another class?	myListBox.DataBind();	0
32707295	32707104	Read log file from last read position	Regex pattern = new Regex(@"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");\n long lastPosition = 0;\n\n private void OnChanged(object source, FileSystemEventArgs e)\n {\n   string line;\n\n\n   Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read,     FileShare.ReadWrite);\n   stream.Seek(lastPosition, SeekOrigin.Begin);\n   StreamReader streamReader = new StreamReader(stream);\n\n   while ((line = streamReader.ReadLine()) != null)\n   {\n      if (pattern.Match(line).Success)\n      {\n        tbOutput.AppendText(line + Environment.NewLine);\n      }\n   }\n   lastPosition = stream.Position;  // may need to subtract 1!!!\n   streamReader.Close();\n   stream.Close();\n}	0
15124232	15123088	Getting data from a FormView's currently bound row	DataSourceSelectArguments args = new DataSourceSelectArguments();\n    SqlDataSource mds = (SqlDataSource)MyFormView.DataSourceObject;\n    DataView view = (DataView)mds.Select(args);\n    DataTable dt = view.ToTable();\n    DataRow dr2 = dt.Rows[1];	0
17592331	17591942	Get default backup path of sql server prgrammatiacally	CREATE FUNCTION dbo.fn_SQLServerBackupDir() \nRETURNS NVARCHAR(4000) \n AS \nBEGIN \n\n DECLARE @path NVARCHAR(4000) \n\nEXEC master.dbo.xp_instance_regread \n        N'HKEY_LOCAL_MACHINE', \n        N'Software\Microsoft\MSSQLServer\MSSQLServer',N'BackupDirectory', \n        @path OUTPUT,  \n        'no_output' \nRETURN @path \nEND;	0
25629545	25628319	Login with DocuSign REST API Authentication	oRequest.Headers.Add("X-DocuSign-Authentication",\n            string.Format(@"<DocuSignCredentials>\n                            <Username>{0}</Username>\n                            <Password>{1}</Password>\n                            <IntegratorKey>{2}</IntegratorKey>\n                           </DocuSignCredentials>",\n            "abc@gmail.com",\n            "mypassword",\n            "my-integrator-key"));	0
719960	708042	MS Access interop - Data Import	app.Quit(Access.AcQuitOption.acQuitSaveAll);\nif (!accessProcess.HasExited)\n{\n    Console.WriteLine("Access did not exit after being asked nicely, killing process manually");\n    accessProcess.Kill();\n}	0
16650425	16648200	How can I create polygons in Farseer?	//List of vectors defining my custom poly\n        Vector2[] vlist = \n            {\n                ConvertUnits.ToSimUnits(new Vector2(25,0)) \n                ,ConvertUnits.ToSimUnits(new Vector2(15,25)) \n                ,ConvertUnits.ToSimUnits(new Vector2(-15,25)) \n                ,ConvertUnits.ToSimUnits(new Vector2(-25,0))\n                ,ConvertUnits.ToSimUnits(new Vector2(-15,-10))\n                ,ConvertUnits.ToSimUnits(new Vector2(15,-10))\n            };\n\n        //get farseer 'vertices' from vectors\n        Vertices _shapevertices = new Vertices(vlist);\n\n        //feed vertices array to BodyFactory.CreatePolygon to get a new farseer polygonal body\n        _newBody = BodyFactory.CreatePolygon(_world, _shapevertices, _stats.Density);	0
23988107	23988019	Close connection when using a Transaction	private string getDocumentDetailsByNumber(string DocNumber)\n{\n    using (var connection = new SqlConnection("My Connection String"))\n    {\n        SqlTransaction transaction = connection.BeginTransaction();\n\n        DataSet DocNum = new DataSet();\n\n        string sDocNumber = "";\n        string[] taleNamesDoc = new string[1];\n        taleNamesDoc[0] = "docnumber";\n        SqlParameter[] paramDoc = new SqlParameter[1];\n        paramDoc[0] = new SqlParameter("@DocumentNumber", DocNumber.ToString().Trim());\n\n        SqlHelper.FillDataset(transaction, CommandType.StoredProcedure, "spGetDocumentDetailsByNumber", DocNum, taleNamesDoc, paramDoc);\n        string docTitle = DocNum.Tables["docnumber"].Rows[0][0].ToString();\n\n        transaction.Commit();\n\n        return docTitle;\n    }  // Connection is disposed and cleaned up. \n}	0
2884898	2884868	How to get the last option value from a DropDownList?	if (myDropDownList.Items.Count > 0)\n{\n    string myValue = myDropDownList.Items[myDropDownList.Items.Count - 1].Value;\n}	0
23844871	23553381	What is the best use of download and upload files in a windows store app?	var uri = new Uri("");\n        var downloader = new BackgroundDownloader();\n\n        downloader.SetRequestHeader("Range", "bytes=0-");\n        downloader.Method = "POST";\n\n        downloader.SetRequestHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryx5pLn3bHAS5Q8Ns5");\n\n        downloader.ServerCredential = new Windows.Security.Credentials.PasswordCredential()\n        {\n            UserName = signin.theusername,\n            Password = signin.thepassword\n        };	0
2032759	2032636	How to make an Abstract Base class IComparable that doesn't compare two separate inherited classes?	abstract class Base<T> : IComparable<T> where T : Base<T> {\n    public int Rank { get; set; } // Order instances of derived type T by Rank\n    public int CompareTo(T other) { return Rank.CompareTo(other.Rank); }\n}\nclass Foo : Base<Foo> {}\nclass Bar : Base<Bar> {}\n\nstatic class Program {\n   static void Main() {\n       var foo1 = new Foo { Rank = 1 };\n       var foo2 = new Foo { Rank = 2 };\n       var bar1 = new Bar { Rank = 1 };\n       var bar2 = new Bar { Rank = 2 };\n\n       Console.WriteLine(foo1.CompareTo(foo2));\n       Console.WriteLine(bar2.CompareTo(bar1));\n\n       //error CS1503: Argument '1': cannot convert from 'Bar' to 'Foo'\n       //Console.WriteLine(foo1.CompareTo(bar1));\n   }\n}	0
15745343	15745195	Hide C# Console App Window When Started by Task Scheduler	output type to Windows application	0
34202068	34201942	How to get installed packages in UWP10 across all users?	Windows.Management.Deployment.PackageManager packageManager = new Windows.Management.Deployment.PackageManager();\nIEnumerable<Windows.ApplicationModel.Package> packages = (IEnumerable<Windows.ApplicationModel.Package>) packageManager.FindPackages();	0
20400944	20400890	How to retrieve File Version of Assembly Information window in ASP.NET C#	FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;	0
32326310	32326130	How to read blob from SQL Server?	SqlCommand command = new SqlCommand();\nSqlDataReader reader = command.ExecuteReader();\nSystem.IO.Stream stream = reader.GetStream(1); // 1 is the index of the column	0
3765078	3765038	Is there an equivalent to 'continue' in a Parallel.ForEach?	return;	0
17797872	17796372	set Response Body of Httpresponse	context.Response.TrySkipIisCustomErrors = true;	0
11239281	11239197	How to restore original position after translation using TranslateTransform? (Windows Phone C#)	// _originalX and _originalY were initialized in your DragStart handler\ntranslate.X = _originalX;\ntranslate.Y = _originalY	0
17728899	17379526	c# - How to add string to resources?	Settings.Default.YourSetting = //Something\nSettings.Default.Save();	0
17770894	17770725	Remove certain tabs from tab control and add a tab at a certain index C#	List<string> pagesToKeep = new List<string>() {"Design", "Picture"};\nfor (int i = tabControlMain.TabPages.Count - 1; i>=0; i--)\n{\n    string curName = tabControlMain.TabPages[i].Name;\n    if(!pagesToKeep.Contains(curName))\n    {\n        tabControlMain.TabPages.RemoveAt(i);\n    }\n}	0
9275292	9275096	Merge 2 columns from datatable in datatextfield from dropdownlist	DataTable dt = function_return_Datatable(id);\ndt.Columns.Add("FullName", typeof(string), "FirstName + ' ' + LastName");\n\ndropdownlist1.DataSource = dt;\ndropdownlist1.DataTextField = "FullName";\ndropdownlist1.DataValueField = "ID";\ndropdownlist1.DataBind();	0
17509181	17509144	how to get null values in sqldatareader	int ordinal_so_type=reader.GetOrdinal("so_type");\n//...\nwhile(reader.Read()==true)\n{\n  //reading other columns here\n  if (reader.IsDBNull(ordinal_so_type)==false)\n  {\n    s.type=reader.GetInt32(ordinal_so_type);\n  }\n  else\n  {\n    //do whatever you like if the so_type column is null\n  }\n}	0
21389549	21389486	How to remove columns in a DataTable with certain characters in their name?	var colsToRemove= (from DataColumn x in table.Columns\n                          where x.ColumnName.StartsWith("#col_")\n                          select x.ColumnName);\n\nwhile (colsToRemove.Any())\n    table.Columns.Remove(colsToRemove.First());	0
6136546	6136288	Post image and text from iPhone to asp.net	string data = Request.Form["name"];	0
29675317	29673882	Add TypeConverter attribute to enum in runtime	Attribute[] newAttributes = new Attribute[1];\n    newAttributes[0] = new TypeConverterAttribute(typeof(LocalizedEnumTypeConverter));\n\n    TypeDescriptor.AddAttributes(MyEnum, newAttributes);	0
12850194	12850158	Enum syntax - extra comma allowed at end?	var ints = new[] { 2, 3, 4, 3, };\n\nvar obj = new SomeClass { Prop1 = "foo", Prop2 = "bar", };	0
3779027	3778698	How to circumvent sender's write-protection in events?	Dispatcher.BeginInvoke(new Action(() => {\n  (board.Children[0] as ColorAnimation).To = Color.FromArgb(1, Convert.ToByte(random.Next(0, 255)), Convert.ToByte(random.Next(0, 255)),     \n}));	0
32834499	32833992	Issues with protectedData API	public static byte [] Protect( byte [] data )\n        {\n            try\n            {\n                return ProtectedData.Protect( data, s_aditionalEntropy, DataProtectionScope.LocalMachine );\n            } \n            catch (CryptographicException e)\n            {\n                Console.WriteLine("Data was not encrypted. An error occurred.");\n                Console.WriteLine(e.ToString());\n                return null;\n            }\n        }\n\n        public static byte [] Unprotect( byte [] data )\n        {\n            try\n            {\n                return ProtectedData.Unprotect( data, s_aditionalEntropy, DataProtectionScope.LocalMachine );\n            } \n            catch (CryptographicException e)\n            {\n                Console.WriteLine("Data was not decrypted. An error occurred.");\n                Console.WriteLine(e.ToString());\n                return null;\n            }\n        }	0
11028782	11013108	Access to a SharePoint intranet page from application	WebClient client = new WebClient();\nclient.Credentials = CredentialCache.DefaultCredentials;	0
14611511	14611056	How to set a property in class from a derived class	public class FindIt\n{\n    // You need to let your derived class access the FindItFrm\n    protected FindItFrm Frm;\n\n    // Constructor needs to accept a FindItFrm\n    public FindIt(FindItFrm frm)\n    {\n        Frm = frm;\n    }\n}\n\npublic class FindItFrm\n{\n    private bool _amISet = false; \n\n    public bool AmISet\n    {\n        get { return _amISet; }\n        set { _amISet = value; }\n    }\n}\n\npublic class MyHelper : FindIt\n{\n    // Constructor\n    public MyHelper()\n        : base(new FindItFrm())\n    {\n        Frm.AmISet = true;\n    }\n}	0
29022336	29022026	Count of childrens 1-* children *-* Linq Entity Framework	foreach (var teacher in context.Teachers)\n{\n    Console.WriteLine("The teacher '{0}' is teaching the following classes:", \n        teacher.Name);\n\n    foreach (var teacherClass in teacher.Classes)\n    {\n        Console.WriteLine(" - {0} ({1} students)", \n            teacherClass.Name, teacherClass.Students.Count);\n    }\n}	0
8106951	8106802	How to identify which ListView was rightclicked ?	ContextMenu.SourceControl	0
27477392	27477317	Find 1st # in Sequence	int[] data = { 1, 2, 5, 7, 8, 9 };\nvar result = data.Aggregate(new List<List<int>>(), (list, item) =>\n{\n    List<int> previousList = list.Count > 0 ? list[list.Count - 1] : null;\n\n    if (previousList != null && item == previousList[previousList.Count - 1] + 1)\n    {\n        previousList.Add(item);\n    }\n    else\n    {\n        list.Add(new List<int> { item });\n    }\n\n    return list;\n});\n\nforeach (List<int> list in result)\n{\n    Console.WriteLine("Sequence: " + string.Join(", ", list));\n}	0
27744731	27744478	C# code to remove the xml node that doesnt have value	XmlDocument doc = new XmlDocument();\n    doc.Load("yourXml.xml");\n    XmlNodeList nodes = doc.GetElementsByTagName("book");\n    for (int i = nodes.Count - 1; i >= 0; i--)\n    {\n\n        string price = nodes[i]["price"].InnerText;\n        if (string.IsNullOrEmpty(price))\n        {\n            nodes[i].ParentNode.RemoveChild(nodes[i]);\n        }\n    }\n    doc.Save("yourXml.xml");	0
13125743	13078363	Create array of all ExpressionTree/Func-parameters	public static T GenerateFunc<T>(Type type)\n{\n    var target = typeof (Program).GetMethod("Target");\n\n    var invokeMethod = type.GetMethod("Invoke");\n    var parameters = invokeMethod\n      .GetParameters()\n      .Select(pi => Expression.Parameter(pi.ParameterType, pi.Name))\n      .ToList();\n\n    var parametersExpression = Expression.NewArrayInit(typeof(object), parameters);\n    var body = Expression.Call(target, parametersExpression);\n    return Expression.Lambda<T>(body, parameters).Compile();\n}	0
11401230	11401174	Fullscreen application option (hide app title bar)	FormBorderStyle = FormBorderStyle.None;	0
1758304	1758214	LINQ To SQL exception with Attach(): Cannot add an entity with a key that is alredy in use	public void Update(Customer customer)\n{\n  NorthwindDataContext context = new NorthwindDataContext();\n  context.Attach(customer);\n  context.Refresh(RefreshMode.KeepCurrentValues, customer);\n  context.SubmitChanges();\n}	0
15115892	15115613	Multiple actions were found that match the request	// A route that enables RPC requests\nroutes.MapHttpRoute(\n    name: "RpcApi",\n    routeTemplate: "rpc/{controller}/{action}",\n    defaults: new { action = "Get" }\n);\n\n// Default route\nroutes.MapHttpRoute(\n    name: "Default",\n    routeTemplate: "{controller}/{id}",\n   defaults: new { id =  RouteParameter.Optional }\n);	0
8185766	8185662	C# Listview, remove junk column	[c#]\nprivate void Form1_Load(object sender, System.EventArgs e)\n{\n    SizeLastColumn(lvSample);\n}\n\nprivate void listView1_Resize(object sender, System.EventArgs e)\n{\n    SizeLastColumn((ListView) sender);\n}\n\nprivate void SizeLastColumn(ListView lv)\n{\n    lv.Columns[lv.Columns.Count - 1].Width = -2;\n}	0
16070154	16069152	Control explorer window programmatically	var shellWindows = new SHDocVw.ShellWindows();\nvar myFolder = "C:\\temp"; // folder name you want to navigate to\nvar myHwnd = 0; // whatever window handle you're looking for\nforeach (SHDocVw.InternetExplorer shellWindow in shellWindows)\n{\n    if (shellWindow.HWND == myHwnd)\n    {\n        shellWindow.Navigate(myFolder);\n        break;\n    }\n}	0
5257309	5257279	How to divide the contents of a file depending on a particular time slot	DateTime.UtcNow	0
25893758	25891551	Scripting Functoid for Date Formatting in Maps Biztalk 2010	public string FormatDate(string inputDate)\n    {\n        System.DateTime strDate;\n        if (System.DateTime.TryParseExact(inputDate, "yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out strDate))\n        {\n            return strDate.ToString("yyyy-MM-dd");\n        }\n        return "INVALID DATE";\n    }	0
23646618	23646519	Reorder DataTable rows with comma seperated values	string IDorder = "js5,bs2,lk3";\nDataTable dtData = new DataTable();\n//create columns for datatable ID and name\nvar ordered = dtData.AsEnumerable().OrderBy(x => IDorder.IndexOf(x["ID"]));	0
8713890	8712785	How to get the remaining string after removing a substring	public string RemainingString(string str, int start, int length)\n{\n    return Regex.Replace(str, "^(.{" + start+ "})(?:.{" + length + "})(.*)$", "$1$2");\n}	0
3023696	3023649	Hour from DateTime? in 24 hours format	return fechaHora.Value.ToString("HH:mm");	0
32791743	32791632	Deserialize XML into C# object with list	[Serializable, XmlRoot("Entry")]\npublic class DeserializedClass\n{\n    public string entryValue1;\n    public string entryValue2;\n\n    [XmlElement("RootElement")]\n    public List<RootElement> rootElement { get; set; }\n}\n\npublic class RootElement\n{\n    public string rootElementValue1 { get; set; }\n    public string rootElementValue2 { get; set; }\n}	0
1129287	1129264	How do I format hours in DateTime to return 0 instead of 12?	string s = dt.ToString("H:mm:ss");	0
27883568	27883518	Fastest way to insert rows without violating the primary key	#NEW_POINTS	0
16877428	16877150	How can I grab this value from the xml file?	MyImage = item.Element(dcM + "content")\n               .Element(dcM + "thumbnail")\n               .Attribute("url").Value	0
8726830	8711604	My application wont run in command line?	cd C:\Users\Fer\Documents\Test Batch\Debug\\n   cd\n   smartHomeTest.exe	0
20281512	20281398	How to keep dropdown item list on top	.wrapper-dropdown-3 .dropdown {\n z-index: 1;\n}    \n\n/* Active state */\n\n    .wrapper-dropdown-3.active .dropdown {\n    opacity: 1;\n    pointer-events: auto;\n    z-index: 2;\n    }	0
470246	470242	Using a Boolean Expression in a StringBuilder	script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));	0
11941711	11941428	Updating A List With Linq	foreach (NetworkSwitch ns in intersect) \n        {   \n            foreach (KeyValuePair<int, VLAN> vlanpair in ns.VLANDict)\n            {\n                if(vlanpair.Value.Neighbors.RemoveAll(n => n.name == ns.name) > 0)\n                    vlanpair.Value.Neighbors.Add(ns);\n            } \n        }	0
5762202	5761965	How to restrict the TextBox to accept only one dot in decimal number in keypress event in C#	protected void TextBox1_TextChanged(object sender, EventArgs e)\n{\n   if(!Regex.IsMatch(TextBox1.Text, @"[0-9]+(\.[0-9][0-9]?)?"))\n      TextBox1.BackColor = Color.Red;\n\n   decimal value;\n   if(!decimal.TryParse(TextBox1.Text, out value))\n      TextBox1.BackColor = Color.Red;\n}	0
1577920	1577889	How to read xml file and save using httprequest and response	WebClient wc = new WebClient();\nwc.DownloadFile("http://xyz", @"C:\getxml.xml");	0
3262724	3262464	How to convert datetime format to date format in crystal report using C#?	Date({MyTable.dte_QDate})	0
14945662	14945310	linq version of sql with CAST to smallmoney	decimal value;\n\nvar sum = (from a in Context.TransTable\n           where a.ActionID == action.ActionID && a.UserID == (long)userId\n           select a.AdditionalValue).ToList().\n           Select(x => decimal.TryParse(x, out value) ? value : 0).Sum();	0
6960573	6960426	C# XML Documentation Website Link	///<Summary>\n/// This is a math function I found <see href="http://stackoverflow.com">HERE</see>\n///</Summary>	0
26049759	26049523	Cross controller update	public ActionResult Create([Bind(Include = "ServiceID,AssetID,Date,ContractorID,Notes")] ServiceHistory serviceHistory)\n{\n    if (ModelState.IsValid)\n    {\n        db.ServiceHistories.Add(serviceHistory);\n\n        // Upadte Next Service Date\n        var query = from r in db.Assets\n               where r.AssetID == serviceHistory.AssetID\n               select r;\n\n        foreach (Asset r in query)\n        {\n            int freq = (int)r.ServiceFrequency;\n            r.NextServiceDate = DateTime.Now.Date.AddMonths(freq);\n        }\n        db.SaveChanges();\n\n        return RedirectToAction("Details", "Assets", new { id = serviceHistory.AssetID });\n    }\n\n    ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Description", serviceHistory.AssetID);\n    return View();\n\n}	0
23897131	23896787	c# OleDbConnection csv to excel skips first line from csv	Extended Properties=Text;HDR=No;	0
20686393	20685700	Use plus and minus icons from TreeView	using System.Windows.Forms.VisualStyles;\n\nprotected override void OnPaint(PaintEventArgs e) {\n  VisualStyleRenderer treeClose = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Closed);\n  treeClose.DrawBackground(e.Graphics, new Rectangle(16, 16, 16, 16));\n  TextRenderer.DrawText(e.Graphics, "Closed Branch", SystemFonts.DefaultFont, new Point(32, 16), Color.Black);\n\n  VisualStyleRenderer treeOpen = new VisualStyleRenderer(VisualStyleElement.TreeView.Glyph.Opened);\n  treeOpen.DrawBackground(e.Graphics, new Rectangle(16, 32, 16, 16));\n  TextRenderer.DrawText(e.Graphics, "Opened Branch", SystemFonts.DefaultFont, new Point(32,32), Color.Black);\n\n  base.OnPaint(e);\n}	0
4978236	4978157	How to search for an image on screen in C#?	Bitmap CaptureScreen()\n{\n    var image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);\n    var gfx = Graphics.FromImage(image);\n    gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);\n    return image;\n}	0
2432492	2423268	How to find the logged in user in Sharepoint?	string username;\n            string sspURL = "URL where Sharepoint is deployed";\n\n            SPSite site = new SPSite(sspURL);\n\n            SPWeb web = site.OpenWeb();\n\n            SPUser user = web.CurrentUser;\n\n            username = user.LoginName;\n\n            site.AllowUnsafeUpdates = true;	0
3567177	3567161	String.Remove equivilant inside a static method	string foo = "abc";\nfoo = foo.Replace("b", "z"); // not String.Replace(...)	0
14286946	14286279	Adding a variable into the HTML.BeginForm Model	[HttpPost]\n    [AllowAnonymous]\n    [ValidateAntiForgeryToken]\n    public ActionResult PasswordReset(PasswordReset model, string passwordToken)\n    {\n        //Attemp to change password\n        model.PasswordResetToken = passwordToken;\n        var passwordChangeConfirmation = WebSecurity.ResetPassword(model.PasswordResetToken, model.Password);\n\n        //Password has been changed\n        if (passwordChangeConfirmation == true)\n        {\n            return RedirectToAction("Index", "Home");\n        }\n        //Password change has failed\n        else\n        {\n            return RedirectToAction("Error", "Account");\n        }\n    }	0
9525615	9524130	RestSharp requests on momentapp's restful api	public HttpStatusCode ScheduleTask(DateTime date, Uri url, string httpMethod, Uri callback = null)\n        {\n            var request = new RestRequest("jobs.json?apikey={apikey}&job[uri]={uri}&job[at]={at}&job[method]={method}", Method.POST);\n            request.AddUrlSegment("uri", "http://develop.myapp.com/Something");\n            request.AddUrlSegment("at", "2012-03-31T18:36:21");\n            request.AddUrlSegment("method", "GET");\n            var response = Execute(request);\n            return response.StatusCode;\n        }	0
29451410	29449619	removing multiple list items from a listview	// Removing items from the bottom of the selected items and working your way up\nfor (int i = listView1.SelectedIndices.Count - 1; i >= 0; i--)\n{\n    task.RemoveAt(listView1.SelectedIndices[i]);\n    listView1.Items.RemoveAt(listView1.SelectedIndices[i];\n}	0
20289084	20287024	Fluent NHibernate MySQL batching	var cfg = new NHibernate.Cfg.Configuration();\ncfg.SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider");\ncfg.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.MySqlDataDriver");\ncfg.SetProperty(NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.MySQLDialect");\ncfg.SetProperty(NHibernate.Cfg.Environment.UseSecondLevelCache, "false");\ncfg.SetProperty(NHibernate.Cfg.Environment.UseQueryCache, "false");\ncfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "false");\ncfg.SetProperty(NHibernate.Cfg.Environment.CommandTimeout, "300");\ncfg.SetProperty(NHibernate.Cfg.Environment.BatchSize, "1000");\ncfg.SetProperty(NHibernate.Cfg.Environment.BatchStrategy,  typeof(MySqlClientBatchingBatcherFactory).AssemblyQualifiedName);	0
11134346	11130423	speed of requests	Parallel.ForEach	0
2893527	2893484	Implementing a Stack using Test-Driven Development	TEST(StackTest, TestEmpty) {\n  Stack s;\n  EXPECT_TRUE(s.empty());\n  s.push(1);\n  EXPECT_FALSE(s.empty());\n  s.pop();\n  EXPECT_TRUE(s.empty());\n}\n\nTEST(StackTest, TestCount) {\n  Stack s;\n  EXPECT_EQ(0, s.count());\n  s.push(1);\n  EXPECT_EQ(1, s.count());\n  s.push(2);\n  EXPECT_EQ(2, s.count());\n  s.pop();\n  EXPECT_EQ(1, s.count());\n  s.pop();\n  EXPECT_EQ(0, s.count());\n}\n\nTEST(StackTest, TestOneElement) {\n  Stack s;\n  s.push(1);\n  EXPECT_EQ(1, s.pop());\n}\n\nTEST(StackTest, TestTwoElementsAreLifo) {\n  Stack s;\n  s.push(1);\n  s.push(2);\n  EXPECT_EQ(2, s.pop());\n  EXPECT_EQ(1, s.pop());\n}\n\nTEST(StackTest, TestEmptyPop) {\n  Stack s;\n  EXPECT_EQ(NULL, s.pop());\n}\n\n\nTEST(StackTest, TestEmptyOnEmptyPop) {\n Stack s;\n  EXPECT_TRUE(s.empty());\n  s.pop();\n  EXPECT_TRUE(s.empty());\n}\n\nTEST(StackTest, TestCountOnEmptyPop) {\n  Stack s;\n  EXPECT_EQ(0, s.count());\n  s.pop();\n  EXPECT_EQ(0, s.count());\n}	0
27041717	27041682	How to add a new row at the top of table in asp grid	dtCurrentTable.Rows.InsertAt(drCurrentRow, 0);	0
3712802	3712454	data grid bound with dropdown list	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        MyDatabaseDataContext mydb = new MyDatabaseDataContext();\n        var x = from y in mydb.MyTable\n                where y.myField == DropDownList1.SelectedItem.Text\n                select y;\n        GridView1.DataSource = x;\n        GridView1.DataBind();\n    }	0
26588099	26586622	Exception from HRESULT: 0x800A03EC INDIRECT	vehicle_makes_dropdown.Formula = "=indirect(""A2"")";	0
18032615	18032514	How can I set new instance for a property class in C#.	public static void ResetStaticProperties()\n {\n     SpintexEditorProperty.Property1 = 0;\n     SpintexEditorProperty.Property2 = 0;\n     SpintexEditorProperty.Property3 = 0;\n }	0
18967040	18966902	Marshall double[] to IntPtr in C#?	using System.Runtime.InteropServices;\n\n/* ... */\n\ndouble[] rotX = { 1.0, 0.0, 0.0 };\ndouble[] rotY = { 0.0, 1.0, 0.0 };\ndouble[] rotZ = { 0.0, 0.0, 1.0 };\n\nvar gchX = default(GCHandle);\nvar gchY = default(GCHandle);\nvar gchZ = default(GCHandle);\n\ntry\n{\n    gchX = GCHandle.Alloc(rotX, GCHandleType.Pinned);\n    gchY = GCHandle.Alloc(rotY, GCHandleType.Pinned);\n    gchZ = GCHandle.Alloc(rotZ, GCHandleType.Pinned);\n\n    SetRotationDirection(\n        gchX.AddrOfPinnedObject(),\n        gchY.AddrOfPinnedObject(),\n        gchZ.AddrOfPinnedObject());\n}\nfinally\n{\n    if(gchX.IsAllocated) gchX.Free();\n    if(gchY.IsAllocated) gchY.Free();\n    if(gchZ.IsAllocated) gchZ.Free();\n}	0
7709491	7709357	Collision of two diffrent object on GDI	var bmpObject1 = new bitmap->draw object 1\nvar bmpObject2 = new bitmap>draw object 2\nvar bmpCombined = new bitmap>draw object 1 and 2\nif (bmpObject1 = (bmpCombined - bmpObject2))\n    no collision\nelse\n    collision	0
6558131	6558090	Removing Items from a list of objects when an object property is duplicated	List<Product> distinctProducts = new List<Product>();\nHashSet<string> dupSet = new HashSet<string>();\nforeach (Product p in Product)\n{\n    if (dupSet.ContainsKey(p.Cat1))\n    {\n         // do not add\n    }\n    else\n    {\n         dupSet.Add(p.Cat1);\n         distinctProducts.Add(p);\n    }\n}	0
21868587	21868096	How to add map marker from lat/lng coordinates? Windows 8 phone	var overlay = new MapOverlay { PositionOrigin = new Point(0.5, 0.5), GeoCoordinate = coordinate };\n\n        var img = new Image { Width = 56, Height = 56 };\n        img.Source = new BitmapImage { UriSource = new Uri("/Assets/Icons/pin.png", UriKind.Relative) };\n        img.Tag = coordinate;\n        img.Tap += delegate\n        {\n            // handle tap\n        };\n\n        overlay.Content = img;\n\n        var mapLayer = new MapLayer { overlay };\n        map.Layers.Add(mapLayer);	0
2891456	2891414	Convert Null Value to String - C#.NET	foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())\n    {\n        var value = objDataTable.Rows[0][PropertyItem.Name.ToString()];\n        PropertyItem.SetValue(this, value == DBNull.Value ? "" : value.ToString() , null);\n    }	0
19313305	19311073	datalist not taking value on updatecommand	public static Control FindControlRecursive(Control control, string id)\n    {\n\n        if (control == null) return null;\n\n\n        Control c = control.FindControl(id);\n\n        if (c == null)\n        {\n            foreach (Control child in control.Controls)\n            {\n                c = FindControlRecursive(child, id);\n                if (c != null) break;\n            }\n        }\n\n        return c;\n    }	0
31366362	31364362	How to get full default route url?	var route = ((Route)RouteTable.Routes["Default"]).Defaults;\nvar url = string.Format("/{0}/{1}", route["controller"], route["action"]);	0
25203395	25203320	How to generate two random numbers, X and Y, and make sure they are never repeated?	const int BOARD_X = 10;\nconst int BOARD_Y = 6;\nconst int MINE_COUNT = 30;\n\nList<int> positions = Enumerable.Range(0, BOARD_X * BOARD_Y).ToList();\nvar rnd = new Random();\nfor (int i = 0; i < MINE_COUNT; i++) {\n    int index = rnd.Next(positions.Count);\n    int pos = positions[index];\n    positions.RemoveAt(index);\n    int x = pos % BOARD_X, y = pos / BOARD_X;\n    Console.WriteLine("({0}, {1})", x, y);\n}	0
27705742	27705616	Trying to remove some text from text REGEX	String temp = "1) chicken burger </br> 2)Chips </br> 3) xyz </br>";\ntemp  = temp.Replace("</br>",",");	0
11029066	11028490	Displaying DATE only	List<string> dateList = new List<string>();\nforeach(sMedication temp in medicationList) \n{\n    if (!dateList.Contains(temp.StartDate.ToShortDateString()))\n    {\n        dateList.Add((temp.StartDate.ToShortDateString()));\n    }\n}\nlstboxSchedule.ItemsSource = date	0
5459972	5459205	Background worker - report progress with string array	//do some heavy calculating\n        for (int i = 0; i < 2; ++i) {\n            string[] workerResult = new string[2];\n            workerResult[0] = "this string";\n            workerResult[1] = "some other string";\n            backgroundWorker1.ReportProgress(i, workerResult);\n        }	0
29823447	29787851	How to add parameters to generated method in Roslyn ( Microsoft.CodeAnalysis )? - Need exact syntax	SF.Parameter(SF.Identifier(sourceObjectName)).WithType(SF.ParseTypeName(sourceClass))	0
553101	542217	Load a BitmapSource and save using the same name in WPF -> IOException	if (File.Exists(filePath))\n{\nMemoryStream memoryStream = new MemoryStream();\n\nbyte[] fileBytes = File.ReadAllBytes(filePath);\nmemoryStream.Write(fileBytes, 0, fileBytes.Length);\nmemoryStream.Position = 0;\n\nimage.BeginInit();\nimage.StreamSource = memoryStream;\n\nif (decodePixelWidth > 0)\n    image.DecodePixelWidth = decodePixelWidth;\n\nimage.EndInit();\n}	0
28081036	28080957	Failed to call Asp.net method from Javascript	[System.Web.Services.WebMethod]\n  public static void Save()\n    {\n        Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);\n        return Json(new { Success = true }, JsonRequestBehavior.AllowGet);\n    }	0
2923754	2923734	Is it possible to compare a binary file in c#?	public bool CompareFiles(string filePath1, string filePath2)\n{\n\n  FileInfo info1 = new FileInfo(filePath1);\n  FileInfo info2 = new FileInfo(filePath2);\n\n\n  byte[] data1 = new byte[info1.Length]\n  byte[] data2 = new byte[info2.Length]; \n\n  FileStream fs1 = new FileStream(filePath1, FileMode.Open);\n  FileStream fs2 = new FileStream(filePath2, FileMode.Open);\n\n  fs1.Read(data1, 0, info1.Length);\n  fs2.Read(data2, 0, info2.Length);\n\n  fs1.Dispose();\n  fs2.Dispose();\n\n  SHA1 sha = new SHA1CryptoServiceProvider(); \n\n  byte[] hash1 = sha.ComputeHash(data1);\n  byte[] hash2 = sha.ComputeHash(data2);\n\n  // c# 2 or less: you need to compare the hash bytes yourself\n\n  // c# 3.5/4\n  bool result = hash1.SequenceEqual(hash2);\n\n  return result;\n}	0
4125923	4125888	preventing my application from sql injection?	; DELETE FROM Users --	0
5886014	5885984	C# How to set a default value for automatic properties?	public bool Value { get; set; } = true;	0
5478916	5478766	Recursion Help required with C#	static List<string> RecursiveGet(DateTime StartDate, DateTime EndDate, List<string> Output)\n{\n    if (Webservice.RecordCount > 9999)\n    {\n        TimeSpan T = EndDate.Subtract(StartDate);\n        T = new TimeSpan((long)(T.Ticks / 2));\n        DateTime MidDate = StartDate.Add(T);\n        Output.AddRange(RecursiveGet(StartDate, MidDate, Output));\n        Output.AddRange(RecursiveGet(MidDate.AddMilliseconds(1), EndDate, Output));\n    }\n    else\n    {\n        //Get Records here, return them in array\n        Output.Add("Test");\n    }\n    return Output;\n}\nstatic List<string> GetRecords(DateTime StartDate, DateTime EndDate)\n{\n    return RecursiveGet (StartDate, EndDate, new List<string>());\n}	0
16509490	16509297	How to set a DataGridView column to a DataGridViewComboBoxColumn?	var column = new DataGridViewComboBoxColumn();\n\ncolumn.DataSource = data.Tables[0].AsEnumerable().\n      Select(genre => new { genre = genre.Field<string>("genre") }).Distinct();\ncolumn.DataPropertyName = "genre";\ncolumn.DisplayMember = "genre";\ncolumn.ValueMember = "genre";\ngrid.DataSource = data.Tables[0];\n// Instead of the below line, You could use grid.Columns["genre"].Visible = false;\ngrid.Columns.Remove("genre");  \ngrid.Columns.Add(column);	0
5121062	5120991	XML to LINQ deserialize to an object from an XML Document	LMP_DayAhead dayAhead = GetDayAheadData();\nvar serializer = new XmlSerializer(dayAhead.GetType());\nusing (var writer = XmlWriter.Create("dayahead.xml"))\n{\n    serializer.Serialize(writer, shoppingCart);\n}	0
32337086	32336665	Replace commas in string C#	private static string replace_commas(String str_)\n{\n    StringBuilder str = new System.Text.StringBuilder(str_);\n\n    bool replace = true;\n\n    for(int i = 0; i != str.Length; ++i)\n    {\n        if(str[i] == ',' && replace)\n            str[i] = '|';\n\n        if(str[i] == '(')\n        {\n            replace = false;\n            continue;\n        }\n\n        if(str[i] == ')' && !replace)\n            replace = true;\n    }\n\n    return str.ToString();\n}	0
12247053	12245840	DataTable Modified row count reverting to 0 after adapter fill	//This is where the modified count reverts\nda.Fill(pca.chatDataSetG, "Chat");	0
3647349	3647263	How can I determine coordinates of a Hyperlink in WPF	private void Hyperlink_Click(object sender, RoutedEventArgs e)\n{\n    var hyperlink = sender as Hyperlink;\n    if (hyperlink != null)\n    {\n        var rect = hyperlink.ContentStart.GetCharacterRect(\n            LogicalDirection.Forward);\n        var viewer = FindAncestor(hyperlink);\n        if (viewer != null)\n        {\n            var screenLocation = viewer.PointToScreen(rect.Location);\n\n            var wnd = new Window();\n            wnd.WindowStartupLocation = WindowStartupLocation.Manual;\n            wnd.Top = screenLocation.Y;\n            wnd.Left = screenLocation.X;\n            wnd.Show();\n        }\n    }\n}\n\nprivate static FrameworkElement FindAncestor(object element)\n{\n    while(element is FrameworkContentElement)\n    {\n        element = ((FrameworkContentElement)element).Parent;\n    }\n    return element as FrameworkElement;\n}	0
28836525	28699452	Parallel forEach search file	DirectoryInfo nodeDir = new DirectoryInfo(@"c:\files");\n            Parallel.ForEach(nodeDir.GetDirectories(), async dir =>\n            {\n\n                foreach (string s in Directory.GetFiles(dir.FullName))\n                {\n                    Invoke(new MethodInvoker(delegate { lbxParallel.Items.Add(s); }));\n                    contador++;\n                   await Task.Delay(1);\n                }	0
1598522	1598349	Problem with ASP.NET Custom Validator for a Comma Separated List of Email Addresses	Regex emailRegEx = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", RegexOptions.IgnoreCase);	0
721745	721702	Concatenating an array of strings to "string1, string2 or string3"	if (s.Length > 1)\n{\n    uiText = string.Format("{0} and {1}", string.Join(", ", s, 0, s.Length - 1), s[s.Length - 1]);\n}\nelse\n{\n    uiText = s.Length > 0 ? s[0] : "";\n}	0
6299836	6299817	Show Modal dialog	dialog.ShowInTaskbar = false;	0
9880174	9800263	how to connect two people in your website	class GameDatails\n{\n  public Guid Role1 { get; set; } // holds the guid of the player who asks\n  public Guid  Role2 { get; set; } // holds the guid of the player who guesses\n  public List<KeyValuePair<Guid, string>> Messages; // holds the player/message pairs\n  public GameDetails(Guid role1, Guid role2)\n  {\n    this.Role1 = role1;\n    this.Role2 = role2;\n    this.Message = new List<KeyValuePair<Guid, string>>();\n  }\n}	0
33921969	33921395	Add empty rows to gridview	private void FirstGridViewRow(DateTime theDate)\n{\n    DataTable dt = new DataTable();\n    DataRow dr = null;\n    dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));\n    dt.Columns.Add(new DataColumn("Col1", typeof(string)));\n    dt.Columns.Add(new DataColumn("Col2", typeof(string)));\n    dt.Columns.Add(new DataColumn("Col3", typeof(string)));\n    dt.Columns.Add(new DataColumn("Col4", typeof(string)));\n    dt.Columns.Add(new DataColumn("Col5", typeof(string)));\n    dr = dt.NewRow();\n    for (var i = 1; i < 6; i++)\n    {\n        dr["RowNumber"] = i;\n        dr["Col1"] = string.Empty;\n        dr["Col2"] = string.Empty;\n        dr["Col3"] = string.Empty;\n        dr["Col4"] = string.Empty;\n        dr["Col5"] = string.Empty;\n        dt.Rows.Add(dr);\n        dr = dt.NewRow();\n    }\n    ViewState["CurrentTable"] = dt;\n}	0
6287896	6286528	EF Code-First doesn't update Sets immediately	context.Entry(j).State = EntityState.Modified;	0
20736362	20736306	Setting Custom Rules for String Comparison	bool MiddleCompare(string eng, string turk)\n{\n    //Replace turkish characters with english here\n    //Compare the newly formatted string, return true/false\n}	0
18703249	18703203	Speed up parsing of XML in C# Compact Framework (using XmlTextReader & XElement)?	XElement.FromReader(xmlTextReader)	0
23835776	23835752	how to compare an integer with a lambda?	Student temp = db.Students.Where(a => a.Id == idtoupdate).SingleOrDefault();	0
18530277	18530127	How to store value from a IQueryable list to a string variable?	string keyword ;\nif(pheader != null)\n   keyword = pheader.FirstOrDefault().VoucherNumber;\nelse\n   keyword = "";	0
4523695	4523680	Select from two tables inside an insert statement in sql	insert into dbo.order \n     (customer_id,package_id,notes) \n Select \n       user_id,Package_ID , 'notes value here'\n from\n      dbo.users,dbo.packages \n where \n     username = 'bader' AND  package_name = 'beginner';	0
9239739	9190437	Monitoring Bandwith on a remote machine with WMI	Set objWMI = GetObject("winmgmts://./root\cimv2")\nset objRefresher = CreateObject("WbemScripting.Swbemrefresher")\nSet objInterfaces = objRefresher.AddEnum(objWMI, _\n  "Win32_PerfFormattedData_Tcpip_NetworkInterface").ObjectSet\n\nWhile (True)\n    objRefresher.Refresh\n    For each RefreshItem in objRefresher\n\n        For each objInstance in RefreshItem.ObjectSet\n            WScript.Echo objInstance.Name & ";" _\n              & objInstance.BytesReceivedPersec & ";" _\n              & objInstance.BytesSentPersec\n\n        Next\n\n    Next\n    Wscript.Echo\n    Wscript.Sleep 1000\nWend	0
30232273	30232224	how to convert 44/5 in C# to get decimal values?	decimal cal = 55m/4;	0
5409958	5409884	How to read picture from URL and show it on my page	string imageFileName = "thefile.jpg";\ncontext.Request.MapPath(@"IMAGES\" + context.Request.QueryString["id"]); \ncontext.Response.ContentType = "image/jpeg";     \ncontext.Response.WriteFile(imageFileName);     \ncontext.Response.Flush(); \ncontext.Response.Close();	0
7100092	7100050	C# Automatically linking strings to properties using the string value	const string delimiter = "_Enabled";\nforeach (string data in aString) {\n  int index = data.IndexOf(delimiter);\n  if (index >= 0) {\n\n    // Get the name and value out of the data string \n    string name = data.Substring(0, index + delimiter.Length);\n    bool value = Convert.ToBoolean(data.Substring(index + delimiter.Length + 1));\n\n    // Find the property with the specified name and change the value\n    PropertyInfo  property = GetType().GetProperty(name);\n    if (property != null) {\n      property.SetValue(this, value);\n    }\n  }\n}	0
12751263	12751194	Nicer code for toggling a bool member	_isIt!!	0
23129794	23113837	Cant access control pattern of controlType.Text nested in DataGrid/DataItem	SelectionItemPattern pattern = rowToSelect.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;\npattern.Select();	0
7966926	7966812	How to bypass the enter/leave event in c sharp	private void PictureBox_Click(object sender, EventArgs e)\n{\n    focusableControl.Focus();\n}	0
33810524	33807658	Vigenere Square Lookup (using string arrays)	internal static string DecryptedText(string ciphertext, string keyword)\n{\n    string tempStore = "";\n    string KeyToUse = ExpandKey(RemoveAllNonAlpha(ciphertext), keyword);\n    string[] tempList;\n    int iSelector = 0;\n\n    for (int ii = 0; ii < RemoveAllNonAlpha(ciphertext).Length; ii++)\n    {\n        tempList = GetNewAlphaList(KeyToUse[ii].ToString());\n\n        for (int iii = 0; iii < tempList.Length; iii++)\n        {\n            ////seperated the two to verify they were not returning the wrong values\n            //string FromList = tempList[iii].ToString().ToLower();\n            //string FromCipher = RemoveAllNonAlpha(ciphertext)[ii].ToString().ToLower();\n\n            if (tempList[iii].ToString().ToLower() ==  RemoveAllNonAlpha(ciphertext)[ii].ToString().ToLower())//if (FromList == FromCipher)\n            {\n                tempStore += GetAlphaFromNumber(iii).ToLower();\n                break;\n            }\n        }\n    }\n\n    return ReplaceAllNonAlpha(tempStore, ciphertext);\n}	0
2951798	2951764	Find "not the same" elements in two arrays	new HashSet<int>(l1).ExceptWith(l2);	0
13245201	13237538	Creating a metro style app and adding it to openwith context menu	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
5057189	4982695	Customized Component for C# SerialPort	public Form1()\n{\n    InitializeComponent();\n    CheckForIllegalCrossThreadCalls = false; //just add this\n}	0
17376083	17375781	Is there a way to know what passed through a if statement	int[] array = {value1, value2, value3}\nfor (int index = 0; index < array.Count(); index++)\n{\n    if (array[index] < 4)\n    {\n        // do sth with index\n    }\n}	0
31352788	31352619	Get coordinates of image in ImageBox after centering?	private void pictureBox1_SizeChanged(object sender, EventArgs e)\n    {\n        pictureBox1.Invalidate();\n    }\n\n    private void pictureBox1_Paint(object sender, PaintEventArgs e)\n    {\n        Point pt = new Point(pictureBox1.Width / 2 - pictureBox1.Image.Width / 2, pictureBox1.Height / 2 - pictureBox1.Image.Height / 2);\n        Rectangle rc = new Rectangle(pt, pictureBox1.Image.Size);\n        e.Graphics.DrawRectangle(Pens.Red, rc);\n    }	0
15683826	15683717	Unicode to ASCII conversion/mapping	private static string NormalizeDiacriticalCharacters(string value)\n{\n    if (value == null)\n    {\n        throw new ArgumentNullException("value");\n    }\n\n    var normalised = value.Normalize(NormalizationForm.FormD).ToCharArray();\n\n    return new string(normalised.Where(c => (int)c <= 127).ToArray());\n}	0
29982848	29839922	How to insert line break into Word (docx) document using OpenXMLPowerTools?	public static void ReplaceNewLinesWithBreaks(XDocument xDoc)\n{\n    var textWithBreaks = xDoc.Descendants(W.t).Where(t => t.Value.Contains("\\r\\n"));\n    foreach (var textWithBreak in textWithBreaks)\n    {\n        var text = textWithBreak.Value;\n        var split = text.Replace("\\r\\n", "\\n").Split(new[] {"\\n"}, StringSplitOptions.None);\n\n        textWithBreak.Value = string.Empty;\n        foreach (var s in split)\n        {\n            textWithBreak.Add(new XElement(W.t, s));\n            textWithBreak.Add(new XElement(W.br));\n        }\n        textWithBreak.Descendants(W.br).Last().Remove();\n    }\n}	0
4627301	4627051	How to open / use a file descriptor	pipeServer.GetClientHandleAsString()	0
9938549	9929618	TimerCallback in MVC3	public class DailyJob : IJob\n{\n    public DailyJob() { }\n\n    public void Execute( JobExecutionContext context )\n    {\n        try {\n            DbLayer.ContestManager cm = new DbLayer.ContestManager();\n            cm.UpdateAllPhotosInContest();\n        } catch( Exception e ) {\n            //Handle this please\n        }\n    }\n\n    public static void ScheduleJob( IScheduler sc )\n    {\n        JobDetail job = new JobDetail("FinishContest", "Daily", typeof(DailyJob));\n        sc.ScheduleJob(job, TriggerUtils.MakeDailyTrigger("trigger1", 0, 0));\n        sc.Start();\n    }\n}\n\n//Global.asax\n        protected void Application_Start()\n        {\n            AreaRegistration.RegisterAllAreas();\n\n            RegisterGlobalFilters(GlobalFilters.Filters);\n            RegisterRoutes(RouteTable.Routes);\n\n            /* HERE */ DailyJob.ScheduleJob(new StdSchedulerFactory().GetScheduler());\n        }	0
8258101	8256762	Why must I add a DataGridView to a Form in order to get the data?	public IntPtr GetWpfWindowHandle(Window w)\n{\n   var interopHelper = new WindowInteropHelper(w);\n   return interopHelper.Handle;\n}	0
1518084	1518017	How to mockup a base controller in asp.net mvc?	var serviceMock = new Mock<IServiceLayer>();\n//serviceMock.Setup(s => s.SomeMethodCall()).Returns(someObject);\nvar controller = new BaseController(serviceMock.Object);	0
10606100	10606082	Mask to format int 1, 10, 100, to string "001", "010", "100"	string one = a.ToString("000"); // 001\nstring two = b.ToString("000"); // 010	0
1100206	1098797	CrystalReportViewer, check if a report is currently displayed?	crv.GetCurrentPageNumber > 0	0
21424435	21424318	Accessing multilevel dictionary using C#	var dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();\n\nforeach (var key in dict.Keys)\n{\n    var currentDictionary = dict[key];\n    foreach (var key2 in currentDictionary.Keys)\n    {\n        var nestedDictionary = currentDictionary[key2];\n        foreach (var item in nestedDictionary)\n        {\n            var currentKey = item.Key;\n            var currentValue = item.Value;\n        }\n    }\n}	0
16645046	16644644	Not able To find A Class in A namespace In c#	Aspose.Pdf.Facades	0
2788674	2788636	Array concatenation in C#	double[] d1 = new double[5];\ndouble[] d2 = new double[3];\ndouble[] dTotal = new double[d1.Length + d2.Length];\n\nd1.CopyTo(dTotal, 0);\nd2.CopyTo(dTotal, d1.Length);	0
7157283	7157237	How to display a string for DataTime in the localized format as in Web.Config	DateTimeFormatInfo formatInfo = new CultureInfo("de-DE", false).DateTimeFormat;\nDateTime time = DateTime.Now;\nConsole.WriteLine(time.ToString("yyyy-MM-dd hh:mm:ss.ff", formatInfo));	0
1013568	1013440	Querying a Dictionary with a Lambda Expression	var components = (from s in software.SoftwareComponents.Values\n                  select new\n                  {\n                      Name = s.ComponentName,\n                      Description = s.ComponentDescription\n                  })\n                 .ToList().GroupBy(s=>s.Name);	0
13204961	13204901	How to reflect Generic Type Parameters in C# .NET	class Program\n{\n    static IEnumerable<string> GetGenericArgumentNames(Type type)\n    {\n        if (!type.IsGenericTypeDefinition)\n        {\n            type = type.GetGenericTypeDefinition();\n        }\n\n        foreach (var typeArg in type.GetGenericArguments())\n        {\n            yield return typeArg.Name;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        // For a raw type\n        Trace.WriteLine(string.Join(" ", GetGenericArgumentNames(typeof(Foo<>))));\n        Trace.WriteLine(string.Join(" ", GetGenericArgumentNames(typeof(Foo<Quux>))));\n    }\n\n}\n\nclass Foo<TBar> {}\n\nclass Quux {}	0
542099	542024	HttpWebRequest with https in C#	request.Method = "POST";\n\nusing (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))\n{\n    writer.Write("nick=" + username + "&password=" + password);\n}	0
33827248	33824901	getters and setters with dictionary in c#	public object objValue;\npublic string strKey;\npublic override Dictionary<string, object> dictionary\n    {\n        get\n        {\n           return fn(); \n        }\n        set \n        {\n            setTest(strKey,objValue);\n        }\n    }\n\n    public void setTest(string strKey, object objValue)\n    {\n        dictionary[strKey] = objValue;\n    }	0
5968763	5968729	How to Specify Identity Column in Linq2SQL	[global::System.Data.Linq.Mapping.ColumnAttribute(\n    Storage="_ID", AutoSync=AutoSync.OnInsert, \n    DbType="Int NOT NULL IDENTITY", \n    IsPrimaryKey=true, IsDbGenerated=true)]	0
24623857	24623715	how to create a button that renames selected nodes in treeview.	private void button_click(object sender, EventArgs e)\n{\n    if (tv.SelectedNode != null)\n        tv.SelectedNode.Text = Interaction.InputBox("Rename the node name from " + tv.SelectedNode.Text);\n}	0
29157241	29137239	Accessing File Located in Sharepoint List	File.OpenRead	0
30676618	30676462	Retrieve Data from API using C#	XDocument xml = XDocument.Parse(new WebClient().DownloadString("http://sporing.bring.no/sporing.xml?q=TESTPACKAGE-AT-PICKUPPOINT"));	0
2568284	2568231	How can I replace this semaphore with a monitor?	ManualResetEvent manualResetEvent = new ManualResetEvent(false);\nbyte b;\npublic byte Function1()\n{\n    // new thread starting in Function2;\n\n    manualResetEvent.WaitOne();\n    return b;\n}\n\npublic void Function2()\n{\n    // do some thing\n    b = 0;\n    manualResetEvent.Set();\n}	0
17765561	17764328	How to set page numbering to start at chosen value in Word	Sub Macro1()\n    '\n    ' Macro1 Macro\n    '\n    '\n        With Selection.Sections(1).Headers(1).PageNumbers\n            .NumberStyle = wdPageNumberStyleArabic\n            .HeadingLevelForChapter = 0\n            .IncludeChapterNumber = False\n            .ChapterPageSeparator = wdSeparatorHyphen\n            .RestartNumberingAtSection = True\n            .StartingNumber = 3\n        End With\n    End Sub	0
10749354	10694055	application block cache query	public class MyBackingStore : IBackingStore\n{\n    public List<string> keys = new List<string>();\n\n    public void Add(CacheItem newCacheItem)\n    {\n        keys.Add(newCacheItem.Key);\n    }\n\n    public void Remove(string key)\n    {\n        keys.Remove(key);\n    }\n}	0
19142924	10886665	How to resolve a 'Bad packet length' error in SSH.NET?	foreach (var d in connectionInfo.Encryptions.Where(p => p.Key != "aes128-cbc").ToList()) \n{\n connectionInfo.Encryptions.Remove(d.Key); \n}	0
4424907	4424873	C# Libraries for timed actions	var task = Task.Factory.StartNew(() => GetFileData())\n                                       .ContinueWith((x) => Analyze(x.Result))\n                                       .ContinueWith((y) => Summarize(y.Result));	0
14150347	14150327	Generic Base Class with Constructor	public DataServiceBase(T entityManager) {\n    this._entityManager = entityManager;\n\n}	0
14344528	12894952	Can i bind against a DynamicObject in WinRT / Windows 8 Store Apps	public class DynamicLocalSettings : BindableBase\n{\n    public object this[string name]\n    {\n        get\n        {\n            if (ApplicationData.Current.LocalSettings.Values.ContainsKey(name))\n                return ApplicationData.Current.LocalSettings.Values[name];\n            return null;\n        }\n        set\n        {\n            ApplicationData.Current.LocalSettings.Values[name] = value;\n            OnPropertyChanged(name);\n        }\n    }\n}	0
12793188	12782726	save image with camera without compress image	var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);\nvar contentUri = Android.Net.Uri.FromFile(_file);\nmediaScanIntent.SetData(contentUri);\nthis.SendBroadcast(mediaScanIntent);	0
21191654	21190923	Is a lat lon within a bounding box?	If ( ( Lat <= NW.Lat && Lat >= SE.Lat ) &&\n     ( Lon >= NW.Lon && Lon <= SE.Lon ) )\n{\n    // The point is in the box\n}	0
20585668	20585130	NHibernate Insert Into Table	var customer = new Customer();\ncustomer.FirstName ...\nsession.Save(customer);	0
2624419	2624301	How to show that the double-checked-lock pattern with Dictionary's TryGetValue is not threadsafe	var dict = new Dictionary<int, string>() { { 1234, "OK" } };\n\nnew Thread(() =>\n{\n    for (; ; )\n    {\n        string s;\n        if (!dict.TryGetValue(1234, out s))\n        {\n            throw new Exception();  // #1\n        }\n        else if (s != "OK")\n        {\n            throw new Exception();  // #2\n        }\n    }\n}).Start();\n\nThread.Sleep(1000);\nRandom r = new Random();\nfor (; ; )\n{\n    int k;\n    do { k = r.Next(); } while (k == 1234);\n    Debug.Assert(k != 1234);\n    dict[k] = "FAIL";\n}	0
8620048	8619382	Unsafe threading with dictionary - Let's break some stuff	public void Work(object dict) {\n            var rnd = new Random();\n            Console.WriteLine((dict as Dictionary<Guid, Guid>).Count);\n            for (int i = 0; i < 1000000; i++) {\n                (dict as Dictionary<Guid, Guid>)[Guid.NewGuid()] = Guid.NewGuid();\n                for (int ix = 0; ix < rnd.Next(1000); ++ix) ;   // NOTE: random delay\n            }\n        }	0
781540	781381	How to name pure virtual protected property	public bool CanSelect\n{\n    get\n    {\n        return this.CanSelectCore();\n    }\n}\n\ninternal virtual bool CanSelectCore()\n{\n    ...\n}	0
16049312	16049213	How to convert an Enum to ViewModel	public List<DropdownViewModel> Get()\n{\n    return Enum.GetValues(typeof (CountryEnum)).Cast<int>()\n        .Select(id => new DropdownViewModel\n        {\n            id = id,\n            name = Enum.GetName(typeof (CountryEnum), id)\n        }).ToList();\n}	0
4445932	785799	How can I export a GridView.DataSource to a datatable or dataset?	BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource \nDataTable tCxC = (DataTable) bs.DataSource;	0
26874520	26873784	azure CreateNotificationHub with Sandbox programmatically	if (!isForProduction)\n                apns.Endpoint = "gateway.sandbox.push.apple.com";	0
3762158	3761873	WebHttpBinding in WCF: how to configure it the proper way?	using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceType)))\n{\n    try\n    {\n      // Open the ServiceHost to start listening for messages.\n      serviceHost.Open();\n\n      // The service can now be accessed.\n      Console.WriteLine("The service is ready.");\n      Console.WriteLine("Press <ENTER> to terminate service.");\n      Console.ReadLine();\n\n      // Close the ServiceHost.\n      serviceHost.Close();\n    }\n    catch (CommunicationException commProblem)\n    {\n      Console.WriteLine(commProblem.Message);\n      Console.ReadLine();\n    }\n}	0
15342130	15342082	Linq GroupBy. Return top one item of a subset of data	from f in lstBestFlightDealsForAllRoutes\ngroup f by new { f.AirportFrom, f.AirportTo } into g // group by route\nselect g.OrderBy(x => x.Price).First() // select cheapest flight	0
13243049	13242984	How do you allow transparent backgrounds on C# controls?	protected override CreateParams CreateParams\n{\n    get\n    {\n        CreateParams cp = base.CreateParams;\n        cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT\n\n        return cp;\n    }\n} \nprotected override void OnPaintBackground(PaintEventArgs pevent)\n{\n    // Don't paint background\n}	0
12235986	12235674	WPF application not displayed in Task Manager	WindowStyle="ToolWindow"	0
11143643	11143462	How to share List in Silverlight?	private void LoadData()\n    {\n        ServiceReference2.Service1Client webService = new ServiceReference2.Service1Client();\n        webService.GetContentCompleted += new EventHandler<ServiceReference2.GetContentCompletedEventArgs>(webService_GetContentCompleted);\n        webService.GetContentAsync();\n    }\n\n    private void webService_GetContentCompleted(object sender, ServiceReference2.GetContentCompletedEventArgs e)\n    {\n        IEnumerable<ServiceReference2.MediaContent> list = e.Result as IEnumerable<ServiceReference2.MediaContent>;\n        dataGrid1.ItemsSource = list;\n\n        ThirdMethod(list);\n    }\n\n    private void ThirdMethod(IEnumerable<ServiceReference2.MediaContent> list)\n    {\n        something = list;\n    }	0
28167293	28167170	Call button from another Form	form1.loadSettings_Click(this, EventArgs.Empty);	0
1323876	1323797	Marshaling pointer to an array of strings	[StructLayout(LayoutKind.Sequential)] \npublic struct UnmanagedStruct \n{ \n    [MarshalAs(UnmanagedType.ByValArray, SizeConst=100)] \n    public IntPtr[] listOfStrings; \n}\n\nfor (int i = 0; i < 100; ++i)\n{\n    if (listOfstrings[i] != IntPtr.Zero)\n        Console.WriteLine(Marshal.PtrToStringAnsi(listOfStrings[i]));\n}	0
3682433	3681052	Get Absolute URL from Relative path (refactored method)	/// <summary>\n/// Converts the provided app-relative path into an absolute Url containing the \n/// full host name\n/// </summary>\n/// <param name="relativeUrl">App-Relative path</param>\n/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>\n/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>\npublic static string ToAbsoluteUrl(this string relativeUrl) {\n    if (string.IsNullOrEmpty(relativeUrl))\n        return relativeUrl;\n\n    if (HttpContext.Current == null)\n        return relativeUrl;\n\n    if (relativeUrl.StartsWith("/"))\n        relativeUrl = relativeUrl.Insert(0, "~");\n    if (!relativeUrl.StartsWith("~/"))\n        relativeUrl = relativeUrl.Insert(0, "~/");\n\n    var url = HttpContext.Current.Request.Url;\n    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;\n\n    return String.Format("{0}://{1}{2}{3}",\n        url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));\n}	0
18349306	18349286	Using Linq is there a way to perform an operation on every element in an Array	var foo = new int[] { 1,2,3,4,5 };\nfoo = foo.Select(x=>x/2).ToArray();	0
28113912	28113818	Convert to LINQ lambda expression 4	var results = source.GroupBy(r => r.Key).Select(g => new\n{\n    g.Key,\n    Data = string.Join("", g.OrderBy(s => s.ID).Select(s => s.Text))\n});	0
12581908	12581874	C# - Singleton - do I need a constructor?	var s = new Singleton();	0
14814373	14814306	Converting a date string in C#	DateTime t = DateTime.parse("01.02.2004");\nString result = t.ToString("{yyyy-MM-dd}", CultureInfo.InvariantCulture);	0
17715019	17701480	Get all objects loaded in Current Session	ICollection entities = _session\n    .GetSessionImplementation()\n    .PersistenceContext\n    .EntityEntries\n    .Keys;	0
31612332	31539649	How can I make a column of check boxes in the ObjectListView behave like radio buttons?	private void tlvFields_SubItemChecking(object sender, BrightIdeasSoftware.SubItemCheckingEventArgs e)\n    {            \n        foreach(var field in f.Fields)\n        {\n            if(field.PK)\n            {\n                field.PK = false;\n            }\n        }\n        tlvFields.SetObjects(_files);\n    }	0
20140844	20140764	Get Xml from Class library project	var assembly = Assembly.GetExecutingAssembly();\nvar resourceName = "com.example.resource.xml";\n\nusing (Stream stream = assembly.GetManifestResourceStream(resourceName))\nusing (StreamReader reader = new StreamReader(stream))\n{\n    string result = reader.ReadToEnd();\n}	0
21779440	21779315	How to pass string array of Columns as parameter to SQL Server Stored procedure	DECLARE @ColNames VARCHAR(1000)\nDECLARE @sSQL NVARCHAR(MAX)\n\nSET @ColNames ='Column1, Column2,...'\n\nSET @sSQL = 'SELECT ' + @ColNames + ' FROM myTable....'\n\nexec sp_executesql @sSQL	0
26895527	26846976	remove duplicate sentences between specified words from string	String text = xtraReport1.GetCurrentColumnValue("Paczka_Notatki").ToString();\n\n    string finalNote = "";\n    string[] notes = System.Text.RegularExpressions.Regex.Split(text, @"\d{1,}\.\smessage:(?<Message>[\D\s]+)");\n\n    foreach (string note in notes)\n    {\n        if (!String.IsNullOrEmpty(note) && finalNote.IndexOf(note) == -1)\n        finalNote += note;\n        }\n    xrTableCell3.Text = finalNote;	0
10250610	10250552	How can I take only entries from even positions in List	var myList = new List<int>{ 1, 2, 3, 4, 5, 6 };\nvar evenIndexes = myList.Where( (num, index) => index % 2 == 0);	0
20323529	20323321	Unable to read weather feed with from weather.gov.sg having an xml namespace in the root tag	XDocument doc = XDocument.Load(...);\nXNamespace ns = "Some.Namepace";\nXElement el = doc.Element(ns + "ElementName");\n...	0
9836934	9836897	how to convert a float to a decimal so i can display it in a numeric up down	byte[] bytes = { 00, 00, 0x1c, 0x42};	0
16952377	16952279	How can i filter C# dataGridView across all field names?	StringBuilder filter = new StringBuilder();\n\nforeach(var column in dataGridView.Columns)\n{\n   if(filter.ToString() == "")\n   {\n       filter.Append(column.Name + " like '" + searchText.Text + "'");\n   }\n   else \n   {\n      filter.Append(" OR ");\n      filter.Append(column.Name + " like '" + searchText.Text + "'");\n   }\n}\n\nRowFilter = filter.ToString();	0
1047582	837813	Starting DataForm in edit mode	public class FixError : System.Windows.Ria.Data.Entity\n{\n    private string _Name;\n\n    [Required]\n    public string Name\n    {\n        get\n        {\n            return this._Name;\n        }\n        set\n        {\n            if ((this._Name != value))\n            {\n                this.ValidateProperty("Name", value);\n                this.RaiseDataMemberChanging("Name");\n                this._Name = value;\n                this.RaiseDataMemberChanged("Name");\n            }\n        }\n    }\n}	0
11309605	11309557	Assign a lambda expression using the conditional (ternary) operator	Action<int> ff = (1 == 2)\n  ? (Action<int>)((int n) => Console.WriteLine("nope {0}", n))\n  : (Action<int>)((int n) => Console.WriteLine("nun {0}", n));	0
15652198	15652146	Passing data to previous window form from another window form	mainForm.SomeMethod(..) or mainFor.SomeProperty = val	0
34050187	34050025	c# to vb.net conversion - Action(Of T, string) as tuple item	For Each item As Tuple(Of String, String, Action(Of T, String)) In list\n    Dim a as Action(Of T, String) = item.Item3\n    a(t, String.Empty)\nNext	0
2395859	2395851	How to store a table of equivalent values in C# for optimal use in my example?	var map = new Dictionary<string, string>();\nmap.Add("CHEVR", "CHEVROLET");\n\nstring fullName = map["CHEVR"];	0
1784004	1783987	get the control with a certain name provided as a string in c#	Button button1 = (Button)this.Controls[controlName];	0
1719820	1719810	fastest way to find the union and intersection items among two list	var set = new HashSet(list2)\nvar list3 = List1.Select(x => set.Contains(x) ? x : null).ToList();	0
6930670	6930630	Removing elements of a collection that I am foreaching through	list1 = list1.Where(l => l % 5 != 0).ToList();	0
6452396	6452361	Dealing with a null column in LINQ while concatenate to a string	contactTable.Select(c => ( (( c.Title ?? "") + " "  + c.FirstName).Trim()).ToList();	0
13394339	13394215	Send the current page as mail or get the Current page html	StringWriter str_wrt = new StringWriter();\nHtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);\nPage.RenderControl(html_wrt);\nString HTML =  str_wrt.ToString();	0
25691486	25689432	Pass a string from Windows Context menu to clickonce application	AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;	0
9767958	9767629	delete folder that contains thumbs.db	cd c:\\n\ndel /s /q thumbs.db	0
29992859	29991910	How to generate in C# a random number of length of 1024 bits?	using System.Security.Cryptography;\n...\nvar rng = new RNGCryptoServiceProvider();\nvar bytes = new byte[128];\nrng.GetBytes(bytes);	0
9948006	9947886	Editing the DataSource of a ComboBox	PopulateSelector()\n{\n    selector.DataSource = null;\n    selector.DisplayMember = "field2";\n    selector.ValueMember = "field1";\n    selector.DataSource = tbl;\n}\n\nRemoveRow()\n{\n    tbl.Rows[0].Delete();\n    PopulateSelector()\n}	0
7925056	7924892	How can I make a hashcode for a custom data structure?	public override int GetHashCode()\n{\n   return string.Format("{0}-{1}-{2}-{3}", X, Y, Face, Shell).GetHashCode();\n}	0
7679261	7679111	C# Best way to hold xml data	// saving it\n        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n        System.IO.File.WriteAllText(filename, doc.Value);\n\n        // loading it back in\n        System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();\n        xdoc.LoadXml(System.IO.File.ReadAllText(filename);	0
12910029	12909905	Saving image to file	SaveFileDialog dialog = new SaveFileDialog();\nif (dialog.ShowDialog() == DialogResult.OK)\n{\n   int width = Convert.ToInt32(drawImage.Width); \n   int height = Convert.ToInt32(drawImage.Height); \n   Bitmap bmp = new Bitmap(width,height);        \n   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);\n   bmp.Save(dialog.FileName, ImageFormat.JPEG);\n}	0
28474694	28471965	AjAX Rating Control storing and fetching from database using repeater in asp.net c# i	con = new SqlConnection(str);\n        con.Open();\n        cmd = new SqlCommand("sp_comments", con);\n        cmd.CommandType = CommandType.StoredProcedure;\n        cmd.Parameters.Add(new SqlParameter("@eid",Request.QueryString["id"].ToString()));\n        da=new SqlDataAdapter(cmd);\n        dt = new DataTable();\n        da.Fill(dt);\n        con.Close();\n\n        DataTable dtCloned = dt.Clone();\n        dtCloned.Columns[3].DataType = typeof(Int32);\n        foreach (DataRow row in dt.Rows)\n        {\n            dtCloned.ImportRow(row);\n        }\n        repeat.DataSource = dtCloned;\n        repeat.DataBind();	0
22331698	22331506	Getting null descendants using linq to xml	var xml = XDocument.Parse(xmlstr);\nXNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2011-08-01";\nvar items = xml.Root.Element(ns+"Items").Elements(ns+"Item");	0
6308289	6308208	Can a C# program read a text file into memory and then pass that object to a method that requires a filename?	System.IO.Path.GetTempFileName()	0
13780930	13767400	How can I suppress a single instance of ReSharper's suggestion to convert my foreach loop to a LINQ expression?	// ReSharper disable LoopCanBePartlyConvertedToQuery\n...\n// ReSharper restore LoopCanBePartlyConvertedToQuery	0
22513426	22513394	Making an X length List fit in between a 0 - 1 scale	myList[(int)Math.Round(sliderValue*myList.Count)]	0
15818840	15818369	WPF Get Current selection in FlowDocumentScrollViewer into CommandParameter	this._AddDefaultTriggerCommand = new RelayCommand<TextSelection>(\n                 param => AddDefaultTriggerCommandExecuted(param))	0
8636943	8636921	How can I get file from ftp (using c#)?	// Get the object used to communicate with the server.\n            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");\n            request.Method = WebRequestMethods.Ftp.DownloadFile;\n\n            // This example assumes the FTP site uses anonymous logon.\n            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");\n\n            FtpWebResponse response = (FtpWebResponse)request.GetResponse();\n\n            Stream responseStream = response.GetResponseStream();\n            StreamReader reader = new StreamReader(responseStream);\n            Console.WriteLine(reader.ReadToEnd());\n\n            Console.WriteLine("Download Complete, status {0}", response.StatusDescription);\n\n            reader.Close();\n            reader.Dispose();\n            response.Close();	0
29322330	29321633	Find implemented types from Generic interface in c#	Type interfaceType = typeof(IEventHandler<>);\nAssembly mscorlib = typeof(System.Int32).Assembly;\nAssembly system = typeof(System.Uri).Assembly;\nAssembly systemcore = typeof(System.Linq.Enumerable).Assembly;\n\nvar events = AppDomain.CurrentDomain.GetAssemblies()\n    // We skip three common assemblies of Microsoft\n    .Where(x => x != mscorlib && x != system && x != systemcore).ToArray();\n    .SelectMany(s => s.GetTypes())\n    .Where(p => p.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType)).ToArray();	0
1843066	1842832	Loading polymorphics objects - need pattern	class Order\n{\n    public static Order CreateOrder(string filename)\n    {\n         Stream stream = new FileStream(filename);\n         string typeinfo = stream.ReadLine();\n         Type t=null;\n         if(typeinfo=="LimitOrder")  // this can be improved by using "GetType"\n            t=typeof(LimitOrder);\n         else if(typeinfo==/* what ever your types are*/\n            t= //...\n         ConstructorInfo consInfo = t.GetConstructor(new Type[0]);\n         Order o= (Order)consInfo.Invoke(new object[0]);\n         o.Load(stream);\n         stream.Close();\n         return o;\n    }\n}	0
27233290	27232390	How to filter with types of generic interfaces in Linq?	List<ITemplate> allTemplates\n              = objects.Where(o => o.GetType()                                                                              \n                                    .GetInterfaces()\n                                    .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ITemplateInstance<>)))\n                       .Select(o => o.GetType()\n                                     .GetProperty("TemplateReference")\n                                     .GetValue(o))\n                       .OfType<ITemplate>()\n                       .ToList();	0
25236802	25236740	How to compare if((sender as Grid).Background== new SolidColorBrush(Colors.Green)) in wpf	var grid = sender as Grid;\n\nif(grid != null)\n{\n  var background = grid.Background as SolidColorBrush;\n\n  if(background != null)\n  {\n    var color = background.Color;\n\n    if(Colors.Green.Equals(color))\n    {\n       co = "Audited";\n    }\n    else if(Colors.Red.Equals(color))\n    {\n      co = "DoNotAudit";\n    }\n    else if(Colors.Orange.Equals(color))\n    {\n      co = "ReAudit";\n    }\n    else if(Colors.Yellow.Equals(color))\n    {\n      co = "TobeAudited";\n    }\n  }\n}	0
375808	372034	How do I listen for scrolling in a ListView?	public class TestListView : System.Windows.Forms.ListView\n{\n    private const int WM_HSCROLL = 0x114;\n    private const int WM_VSCROLL = 0x115;\n    public event EventHandler Scroll;\n\n    protected void OnScroll()\n    {\n\n        if (this.Scroll != null)\n            this.Scroll(this, EventArgs.Empty);\n\n    }\n\n    protected override void WndProc(ref System.Windows.Forms.Message m)\n    {\n        base.WndProc(ref m);\n        if (m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)\n            this.OnScroll();\n    }\n}	0
11492331	11492295	Loading XML encoded HTML into a WebView control	string html = HttpUtility.HtmlDecode("this is a test &lt;/a&gt; test &lt;em&gt;test2&lt;/em&gt; ... ");	0
23841057	23840973	How to efficiently retrieve a list of random elements from an IQueryable?	users.OrderBy(_ => Guid.NewGuid()).Take(3)	0
3640607	3640601	Writing to the Windows 7 "preview" window area	//In your window procedure:\nswitch (msg) {\n    case g_wmTBC://TaskbarButtonCreated\n        THUMBBUTTON buttons[2];\n        buttons[0].dwMask = THB_ICON|THB_TOOLTIP|THB_FLAGS;\n        buttons[0].iId = 0;\n        buttons[0].hIcon = GetIconForButton(0);\n        wcscpy(buttons[0].szTip, L"Tooltip 1");\n        buttons[0].dwFlags = THBF_ENABLED;\n        buttons[1].dwMask = THB_ICON|THB_TOOLTIP|THB_FLAGS;\n        buttons[1].iId = 1;\n        buttons[1].hIcon = GetIconForButton(1);\n        wcscpy(buttons[0].szTip, L"Tooltip 2");\n        buttons[1].dwFlags = THBF_ENABLED;\n        VERIFY(ptl->ThumbBarAddButtons(hWnd, 2,buttons));\n        break;\n    case WM_COMMAND:\n        if (HIWORD(wParam) == THBN_CLICKED)\n        {\n            if (LOWORD(wParam) == 0)\n                MessageBox(L"Button 0 clicked", ...);\n            if (LOWORD(wParam) == 1)\n                MessageBox(L"Button 1 clicked", ...);\n        }\n        break;\n}	0
13586633	13586524	How to transpose a list of lists, filling blanks with default(T)?	public static List<List<T>> Transpose<T>(List<List<T>> lists)\n{\n    var longest = lists.Any() ? lists.Max(l => l.Count) : 0;\n    List<List<T>> outer = new List<List<T>>(longest);\n    for (int i = 0; i < longest; i++)\n        outer.Add(new List<T>(lists.Count));\n    for (int j = 0; j < lists.Count; j++)\n        for (int i = 0; i < longest; i++)\n            outer[i].Add(lists[j].Count > i ? lists[j][i] : default(T));\n    return outer;\n}	0
31923566	31923153	Get minutes from CRON expression (c#)	var expression = "*/5 * * * *";\nvar split = expression.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n\nif (split.Length < 5)\n    throw new Exception("Invalid CRON expression");\n\nvar onlyDigits = "0123456789";\n\n// strip non numeric chars\nvar minutes = new string(split[0].Where(c => onlyDigits.Contains(c)).ToArray());	0
607030	606841	C#, Linq2SQL: Getting the highest of each group	var pets =  from pet in petSource\n            group pet by pet.Age into g\n            let max = g.OrderByDescending(p => p.Weight).FirstOrDefault<Pet>()\n            select new { Name = max.Name, Age = max.Age, Weight = max.Weight };	0
14295307	14295043	Saving multiple pieces of form input to a file	private void button1_Click(object sender, EventArgs e)\n{\n    if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n    {\n        using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))\n        {\n            sw.WriteLine(tB1.Text);\n            sw.WriteLine(tB2.Text);\n            sw.WriteLine(tB3.Text);\n            sw.WriteLine(tB4.Text);\n            sw.Close();\n        }\n\n   }\n\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n    {\n        using (StreamReader sr = new StreamReader(openFileDialog1.FileName))\n        {\n            tB1.Text = sr.ReadLine();\n            tB2.Text = sr.ReadLine();\n            tB3.Text = sr.ReadLine();\n            tB4.Text = sr.ReadLine();\n            sr.Close();\n        }\n    }\n\n}	0
1918807	1918742	Elegant way to create a nested Dictionary in C#	Dictionary<int, Dictionary<int, string>> dict = things\n    .GroupBy(thing => thing.Foo)\n    .ToDictionary(fooGroup => fooGroup.Key,\n                  fooGroup => fooGroup.ToDictionary(thing => thing.Bar,\n                                                    thing => thing.Baz));	0
16281192	2034540	Calculating Area of Irregular Polygon in C#	var points = GetSomePoints();\n\npoints.Add(points[0]);\nvar area = Math.Abs(points.Take(points.Count - 1)\n   .Select((p, i) => (points[i + 1].X - p.X) * (points[i + 1].Y + p.Y))\n   .Sum() / 2);	0
8440283	8440222	Parameterize a SELECT ROWCOUNT sql statement	string stmt = "SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "] \n                    like @searchTb AND [LoggedInUser] LIKE  @loggedinuser";\n\n    int count = 0;\n\n    using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))\n    {\n            cmdCount.Parameters.Add("@searchTb",SqlDbType.VarChar,40).Value="%" + searchTB.Text + "%"; \n            cmdCount.Parameters.Add("@loggedinuser",SqlDbType.VarChar,40).Value="%" + loggedinuser + "%"; \n\n            thisConnection.Open();\n            count = (int)cmdCount.ExecuteScalar();\n            thisConnection.Close();\n    }	0
14110154	14110070	Use System.Diagnostics in windows store application	System.Diagnostics	0
13624268	13624140	Deserialize LinkedIn Profile Json?	public class EndDate\n{\n    public int year { get; set; }\n}\n\npublic class StartDate\n{\n    public int year { get; set; }\n}\n\npublic class Value\n{\n    public string degree { get; set; }\n    public EndDate endDate { get; set; }\n    public string fieldOfStudy { get; set; }\n    public int id { get; set; }\n    public string schoolName { get; set; }\n    public StartDate __invalid_name__\nstartDate { get; set; }\n}\n\npublic class Educations\n{\n    public int _total { get; set; }\n    public List<Value> values { get; set; }\n}\n\npublic class RootObject\n{\n    public string _key { get; set; }\n    public Educations educations { get; set; }\n    public string emailAddress { get; set; }\n    public string firstName { get; set; }\n    public string lastName { get; set; }\n}	0
2245731	2245714	C# - Parsing a line of text - what's the best way to do this?	IEnumerable<double> doubles = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)\n                               .Select<string, double>(double.Parse)	0
22404459	22404403	Interface methods with varying parameters	public class CompleteParameters\n{\n  string parm1;\n  // whatever you want\n};\n\npublic class CompleteParametersTwo : CompleteParameters\n{\n  string parm2;\n};\n\n\npublic interface ICompleteable \n{\n    public void Complete(CompleteParameters parms);\n}	0
12190589	12190524	getting response as a string c#.net	Response.Clear();\nResponse.OutputStream.Write(bytes, 0, bytes.Length); \nResponse.End();	0
4085409	4085360	Use markup file inside assembly	using System;\nusing System.IO;\nusing System.Reflection;\nusing System.Xml;\n\nclass Application\n{\n    static void Main(string[] args) \n    {\n       Stream s = \n          Assembly.GetExecutingAssembly().GetManifestResourceStream("File1.xml");\n\n       XmlDocument xdoc = new XmlDocument();\n\n       using (StreamReader reader = new StreamReader(s))\n           xdoc.LoadXml(reader.ReadToEnd());\n    }\n}	0
12269696	12269670	Locking a Static Method in C#	[MethodImpl(MethodImplOptions.Synchronized)]	0
5526264	5526222	Remove whitespace from a string in C#?	Regex.Replace(myString, @"\s+", " ")	0
9662552	9657783	Static variable not updating after redirect	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n    {\n        string selected = String.Empty;\n\n        //check to see if the selected parameter was passed.\n        if (NavigationContext.QueryString.ContainsKey("selected"))\n        {\n            //get the selected parameter off the query string from MainPage.\n            selected = NavigationContext.QueryString["selected"];\n        }\n\n        //did the querystring indicate we should go to item2 instead of item1?\n        if (selected == "item2")\n        {\n            //item2 is the second item, but 0 indexed. \n            myPanorama.DefaultItem = myPanorama.Items[1];\n        }\n        base.OnNavigatedTo(e);\n    }	0
10763867	10758103	When I print bitmap, it eats up some of it	Bitmap bm = new Bitmap(this.chart1.Width, this.chart1.Height);\n    this.chart1.DrawToBitmap(bm, new Rectangle(50, 50, this.chart1.Width + 50, this.chart1.Height + 50));\n    e.Graphics.DrawImage(bm, 0, 0);	0
19962989	19960438	Timer updating label	Timer timer;\nStopwatch sw;\n\npublic Form1()\n{\n            InitializeComponent();              \n\n}\n\nprivate void btn_Import_Click(object sender, EventArgs e)\n{\n    timer = new Timer();\n    timer.Interval = (1000);\n    timer.Tick += new EventHandler(timer_Tick);\n    sw = new Stopwatch();\n    timer.Start();\n    sw.Start();\n\n    // start processing emails\n\n    // when finished \n    timer.Stop();\n    sw.Stop();\n    lblTime.text = "Completed in " + sw.Elapsed.Seconds.ToString() + "seconds"; \n}\n\n\nprivate void timer_Tick(object sender, EventArgs e)\n{\n    lblTime.text = "Running for " + sw.Elapsed.Seconds.ToString() + "seconds";\n    Application.DoEvents();\n}	0
13409485	13409176	How to determine if an IP Address is routable?	public static bool IsPrivateAddress(this IPAddress addr)\n{\n    if(addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)\n    {\n        return addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal;\n    }\n    var bytes = addr.GetAddressBytes();\n    return\n        ((bytes[0] == 10) ||\n        ((bytes[0] == 192) && (bytes[1] == 168)) ||\n        ((bytes[0] == 172) && ((bytes[1] & 0xf0)==16)));\n}	0
1224538	1224494	How to identify core .NET Framework assemblies?	object[] attribs = assembly.GetCustomAttributes();	0
20327193	20326981	changing css of controls in gridview separately for each row	if (e.CommandName == "O1")\n{\n    //chnaging the css of O1 button JUST IN THIS ROW\n    Button O1Button = (Button)row.FindControl("O1Button");\n\n    //Change the background-color:\n    O1Button.Style.Add("background-color", "yellow");\n\n    //Change the class\n    O1Button.CssClass = "class-name";\n}	0
30491744	30487181	Get xml node attribute depending on other attribute of the same node	var reportid = sitemap.Descendants("node")\n                      .Where(el => el.Attribute("id").Value == "630")\n                      .Select(el => el.Attribute("reportid").Value)\n                      .FirstOrDefault();\n\n// or, lookup of all reportid by id\nvar lookup = sitemap.Descendants("node")\n                    .ToDictionary(el => el.Attribute("id").Value, el => el.Attribute("reportid").Value);	0
1339533	1339524	C#: How do I add a ToolTip to a control?	private void Form1_Load(object sender, System.EventArgs e)\n{\n         // Create the ToolTip and associate with the Form container.\n         ToolTip toolTip1 = new ToolTip();\n\n         // Set up the delays for the ToolTip.\n         toolTip1.AutoPopDelay = 5000;\n         toolTip1.InitialDelay = 1000;\n         toolTip1.ReshowDelay = 500;\n         // Force the ToolTip text to be displayed whether or not the form is active.\n         toolTip1.ShowAlways = true;\n\n         // Set up the ToolTip text for the Button and Checkbox.\n         toolTip1.SetToolTip(this.button1, "My button1");\n         toolTip1.SetToolTip(this.checkBox1, "My checkBox1");\n}	0
18321496	18321367	I need to add a custom form size to the local Print Server through code	var formInfo = new FormInfo1();\nformInfo.Flags = 0;\nformInfo.pName = paperName;\n// all sizes in 1000ths of millimeters\nformInfo.Size.width = (int)(widthMm * 1000.0); \nformInfo.Size.height = (int)(heightMm * 1000.0);\nformInfo.ImageableArea.left = 0;\nformInfo.ImageableArea.right = formInfo.Size.width;\nformInfo.ImageableArea.top = 0;\nformInfo.ImageableArea.bottom = formInfo.Size.height;\n\n// Add the paper size to the printer's list of available paper sizes:\nbool bFormAdded = AddForm(hPrinter, 1, ref formInfo);	0
5267828	5267750	Saving a null date to SQL2008 via. SubSonic 2.x	(DateTime?)	0
15218326	15218228	Replace '[' 8 characters ']' with blank	string result = Regex.Replace(input, @"\[[^\]]{8}\]", "");	0
24492735	24492557	How to check if SQL schema allows NULL for a column?	Console.WriteLine(property.ColumnName +" = "+ field[property].ToString());	0
1805112	1805091	Thread to receive data from an ip and port	while(tcpClient.Connected)\n{\n    // do something while conn is open\n}	0
12119886	12119830	Date and time format conversion in C#	string input = "2012-06-28T08:26:57Z";\nvar dt = DateTime.Parse(input);\nstring output = dt.ToString(@"MM/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);	0
1714370	1714363	Converting a String to a DateTime variable?	public DateTime CurrentTime \n{\n    get \n    { \n       DateTime retVal;\n       if(DateTime.TryParse(this.Schedule.TimeTables.Max(x => x.StartTime), out retVal))\n       {\n           currentTime = retVal;\n       }\n\n       // will return the old value if the parse failed.\n       return currentTime;       \n    } \n    set \n    { \n        currentTime = value; \n    }\n}\nprivate DateTime currentTime;	0
15045166	15033946	Loading all mp3's into a audio array	public class SoundLoader : MonoBehaviour {\npublic AudioClip[] menuSound;\nvoid Start () {\n    menuSound = new AudioClip[]{\n        Resources.Load("sound1") as AudioClip,\n        Resources.Load("sound2") as AudioClip,\n        Resources.Load("sound3") as AudioClip\n    };\n    AudioSource.PlayClipAtPoint(menuSound[2],Vector3.zero);\n}\n}	0
7428162	7427977	Change label across pages	Response.Redirect("~/Home/Index.aspx");	0
14487904	14487766	Inheritance design: How to make a method operate on base class (C#)	public bool myMethod(ref IMyAbstractBaseClass anObject)\n{\n      myObject = new MyFirstClass();\n      return true;\n}\n\npublic bool myMethod2(MyAbstractBaseClass anObject)\n{\n      myObject.SomeProperty = 5;\n      return true;\n}\n\nIMyAbstractBaseClass myObject = new MyFirstClass();\nresult1 = myMethod(ref myObject);\nresult1 = myMethod2(myObject);	0
22901039	22900989	How to fix a rectangle to the borders of the form	public MyForm() \n{\n    this.Paint += this.PaintRectangles;\n}\n\nprivate void PaintRectangles(object sender, PaintEventArgs e)\n{\n    // use e.Graphics to draw stuff\n}	0
30667831	30643273	Automate of file download in IE 11 using c#	[DllImport("user32.dll", SetLastError = true)]\n    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n\n\n    static void DownLoadFile(IE browser)\n    {\n        browser.Link(Find.ByText("download")).ClickNoWait();\n\n        Thread.Sleep(1000);\n        AutomationElementCollection dialogElements = AutomationElement.FromHandle(FindWindow(null, "Internet Explorer")).FindAll(TreeScope.Children, Condition.TrueCondition);\n        foreach (AutomationElement element in dialogElements)\n        {\n            if (element.Current.Name.Equals("Save"))\n            {\n                var invokePattern = element.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;\n                invokePattern.Invoke();\n\n            }\n        }\n    }	0
13697803	13697273	Stored procedure in C#	using (var cmd = new SqlCommand("myQSProcedure_Delete", conn))\n  {\n      cmd.CommandType = CommandType.StoredProcedure;\n      cmd.Parameters.Add("@Id",SqlDbType.Int);\n      foreach (DataRow row in dtDelete.Rows)\n      {\n          cmd.Parameters["@Id"].Value = row[0];\n          cmd.ExecuteNonQuery();\n      }\n  }	0
287740	287685	Raise LostFocus event on a control manually	private void ButtonClick(object sender, EventArgs e) {\n    if(sender != null) {\n        sender.Focus();\n    }\n}	0
25685137	25154721	Execute 32bit C# console application which connects to Oracle 9.2 on Windows 2003 R2 Server	Environment.SetEnvironmentVariable("NLS_LANG", "American_America.UTF8");	0
9720199	9720125	On editing event , how to check if in the dropdownlist cell was selected a value	protected void OnSelectedIndexChanging(object sender, EventArgs e)\n{\n    DropDownList id = (DropDownList)sender;\n    GridViewRow row = GridData.Rows[GridData.EditIndex];\n    if(id.SelectedValue == "Yes")\n    {\n        TextBox column1 = (TextBox)row.FindControl("Column1ID");\n        column1.Visible = true;\n        TextBox column2 = (TextBox)row.FindControl("Column2ID");\n        column2.Visible = true;\n    }\n}	0
8367960	8367860	use of combobox ValueMember and DisplayMember	OleDbDataAdapter da = new OleDbDataAdapter("SELECT [name],[value] FROM [Sheet1$] where Component=1 ", strConn);\ncomboBox1.DisplayMember = "name";\ncomboBox1.ValueMember = "value";\ncomboBox1.BindingContext = this.BindingContext;	0
12523558	12522918	Creating a folder on box using C# and RESTSharp	static string box(string APIKey, string authToken)\n            {\n                RestClient client = new RestClient();\n                client.BaseUrl = "https://api.box.com/2.0";\n                var request = new RestRequest(Method.POST);\n                request.Resource = "/folders/0";\n                string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);\n                request.AddHeader("Authorization", Headers);\n                request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);\n\n                //request.RequestFormat = DataFormat.Json;\n                var response = client.Execute(request);\n                return response.Content;\n            }	0
6154068	6153618	Inject an integer with Ninject	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Ninject;\nusing Ninject.Activation;\nusing Ninject.Syntax;\n\n\n    public class Foo\n    {\n        public int TestProperty { get; set; }\n        public Foo(int max = 2000)\n        {\n            TestProperty = max;\n        }\n    }\n\n    public class Program\n    {\n\n        public static void Main(string [] arg)\n        {\n              using (IKernel kernel = new StandardKernel())\n              {\n                 kernel.Bind<Foo>().ToSelf().WithConstructorArgument("max", 1000);\n                  var foo = kernel.Get<Foo>();\n                  Console.WriteLine(foo.TestProperty); // 1000\n              }\n\n        }\n    }	0
21965247	21965235	Removing a User From an Active Directory Group	public void RemoveUserFromGroup(string userId, string groupName)\n{   \n    try \n    { \n        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY"))\n        {\n            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);\n            group.Members.Remove(pc, IdentityType.UserPrincipalName, userId);\n            group.Save();\n        }\n    } \n    catch (System.DirectoryServices.DirectoryServicesCOMException E) \n    { \n        //doSomething with E.Message.ToString(); \n\n    }\n}	0
7835199	7834518	How to make my image transparent?	Image image = new Image(); //or however you get this\nimage.Opacity = 0.5;\nRenderTargetBitmap bmp = new RenderTargetBitmap(image.Source.Width, image.Source.Height, 96, 96, PixelFormats.Pbgra32);\nbmp.Render(image);\n\nPngBitmapEncoder png = new PngBitmapEncoder();\npng.Frames.Add(BitmapFrame.Create(bmp));\nusing (Stream fs= File.Create("test.png"))\n{\npng.Save(fs);\n}	0
24167318	24167232	How to display some text in a GridView button	var btn = (IButtonControl)e.Row.Cells[0].Controls[0];\nbtn.Text = indexVariable;	0
13697134	13696419	Using External DLLs in a Portable Class Library	System.Data	0
10003729	10003638	Generate a file from a string and send to the user C#	Response.Clear();\nResponse.ContentType = "application/CSV";\nResponse.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");\nResponse.Write(csvBuilder.ToString());\nResponse.End();	0
11106598	11106320	How do I managing usage of multiple versions of unmanaged DLL calls in C#?	INativeMethods nativeMethods = NativeMethodsFactory.Get(UnsafeSdkVersion.V1);\nnativeMethods.CV_SetCommunicationType(aType);	0
24456623	24456490	Using Linq Grouping how to I order by specific Group then remaining Groups descending	var dtQueryResults = yourData\n            .OrderByDescending(v => v["RiskCategory"] == intRiskCategoryEnum)//true for ==2 goes first, false goes then\n            .ThenBy(v => v["RiskCategory"]) //the rest is sorted normally\n            .ThenBy(v => v["Reviewed"]) //inside the groups, the rest of your sorts is used\n            .ThenByDescending(v => v["DateOfService"]);	0
931029	921778	How to connect a winform to internet through a proxy server	' Search button: do a search, display number of results \nPrivate Sub btnSearch_Click(ByVal sender As System.Object, _\n  ByVal e As System.EventArgs) Handles btnSearch.Click \n\n' Create a Google Search object \nDim s As New Google.GoogleSearchService \n\nTry \n\n' google params \nDim strLicenceseKey As String = "google license key" ' google license key \nDim strSearchTerm As String = "Bruno Capuano" ' google license key \n\n' proxy settings \nDim cr As New System.Net.NetworkCredential("user", "pwd", "MyDomain") \nDim pr As New System.Net.WebProxy("127.0.1.2", 80) \n\npr.Credentials = cr \ns.Proxy = pr \n\n' google search\nDim r As Google.GoogleSearchResult = s.doGoogleSearch(strLicenceseKey, _\n  strSearchTerm, 0, 10, True, "", False, "", "", "")\n' Extract the estimated number of results for the search and display it\nDim estResults As Integer = r.estimatedTotalResultsCount \n\nMsgBox(CStr(estResults))\n\nCatch ex As System.Web.Services.Protocols.SoapException\n\nMsgBox(ex.Message)\n\nEnd Try\n\nEnd Sub	0
9066416	9066324	How to get data between certain quotes	string s = "<script type=\"text/javascript\" src=\"/stepcarousel.js\"></script>";\nint startIndex = s.IndexOf("src=\"") + "src=\"".Length;\nint endIndex = s.IndexOf("\"", startIndex);\nstring src = s.Substring(startIndex, endIndex - startIndex);	0
32763955	32763756	C# split string containing 'GO' keyword into multiple sql statements	string connectionString, scriptText;\nSqlConnection sqlConnection = new SqlConnection(connectionString);\nServerConnection svrConnection = new ServerConnection(sqlConnection);\nServer server = new Server(svrConnection);\nserver.ConnectionContext.ExecuteNonQuery(scriptText);	0
22064840	22064680	How to Redirect a page, outside of an Iframe using c#	Page_Init()\n{\n  if(Session["user"]==null)\n   {\n      string jScript = "window.top.location.href = '/Forms/Login.aspx';";\n      ScriptManager.RegisterStartupScript(this, this.GetType(), "forceParentLoad", jScript, true);\n      //Response.Redirect("~/Forms/Login.aspx");\n   }\n}	0
1841959	1839017	How to unit test file permissions in NUnit?	public delegate void ThrowExceptionDelegate();\nmystub.Stub(x => x.ReadFile()).Do(new ThrowExceptionDelegate(delegate()\n    { throw new IOException(); }\n    ));	0
10651086	10650756	Declare different variables according to property value	Dictionary<string, float> columnNameAndValue = new Dictionary<string, float>();\n\nforeach (DataColumn column in entry.Columns)\n{\n    if (column.ColumnName.Contains("weight") || \n        column.ColumnName.Contains("amount")) //float column.ColumnName = 0;\n    {\n        columnNameAndValue.Add(column.ColumnName, 0);\n    }\n}	0
3610035	3609805	how to achieve the project requirement	if(!RuntimeUp || m_reconnectInProgress) \n    return false;	0
4817354	4817231	Is there an easy way to convert a c# enum to a string, and back again?	MyEnum[] selection = { MyEnum.Mother, MyEnum.Father, MyEnum.Sister };\n\nstring str = string.Join(",", selection.Cast<int>());\n\nMyEnum[] enm = str.Split(',').Select(s => int.Parse(s)).Cast<MyEnum>().ToArray();	0
31490066	31490015	C# Printing a list from another class	static void Main(string[] args)\n{\n    foreach (var risk in myRisk.GetRisks()) {\n        Console.WriteLine("ID: " + risk.Id + ", Title: " + risk.Title); \n    }\n}	0
4018845	4018655	how to use collection from one form to other	public class StaticRef {\n    static StaticRef() {\n        Elementi = new ObservableCollection<element>();\n    }\n    public static ObservableCollection<element> Elementi {get; set;}\n}	0
33589839	33589070	How can I ensure that an iterator method will not yield any null items?	public class Graph\n{\n    public IEnumerable<Node> Nodes(Graph g)\n    {\n        Contract.Requires(g != null);\n        Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<Nodei>>, node => node != null));\n        foreach (var x in g.MethodForGettingNodes())\n        yield return x;\n    }\n}	0
21058950	20920090	Transfer winform data to yahoo login page inside Chrome browser	using OpenQA.Selenium;\nusing OpenQA.Selenium.IE;\nusing OpenQA.Selenium.Support.UI;\nusing OpenQA.Selenium.Chrome;\n\nnamespace WindowsFormsChrome\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            // download the chrome driver\n            IWebDriver driver = new ChromeDriver(@"C:\Users\Downloads\chromedriver"); \n            driver.Navigate().GoToUrl("http://www.yahoo.com");\n            IWebElement myField = driver.FindElement(By.Id("txtUserName"));\n            myField.SendKeys("UserName");\n            IWebElement myField = driver.FindElement(By.Id("txtPassword"));\n            myField.SendKeys("Password");\n            IWebElement myField = driver.FindElement(By.Id("btnLogin"));\n            myField.click()\n        }\n     }\n}	0
4630561	4630527	c# using HtmlAgilityPack to get data from HTML table	HtmlWeb hw = new HtmlWeb();              \nHtmlAgilityPack.HtmlDocument htmlDoc = hw.Load(@"http://www.some123123site.com/index");                 \nif (htmlDoc.DocumentNode != null)              \n{                   \n        foreach(HtmlNode text in htmlDoc.DocumentNode.SelectNodes("//tr/td/div/text()"))\n        {     \n            Console.WriteLine(text.InnerText);  \n        }\n}	0
26622860	26622808	How to generate ALPHANUMERIC Coupon Code in C#?	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";\n    var random = new Random();\n    var result = new string(\n        Enumerable.Repeat(chars, 8)\n                  .Select(s => s[random.Next(s.Length)])\n                  .ToArray());	0
11103252	11103188	How do you create a standalone exe in Visual Studio?	ilmerge /target:winexe /out:myoneexecutable.exe Foo.exe Bar1.dll Bar2.dll	0
26188237	26188157	Do work on N numbers of strings at a time from a List<string>	List<string> xList; //Contains 350 string\nint N = 100;\n\nfor (int i = 0; i <= xList.Count; i += N)\n{\n    var vList = xList.Skip(i).Take(N);\n    MessageBox.Show(string.Join(Environment.NewLine, vList.ToArray()));\n    counter += N;\n}	0
17203702	17203625	Series of Starting and Ending Index for Specific pattern of substring in C#	var r = new Regex(@"(\S)(?:\S*(\S))?");\nvar input = "AAA  AAAAA    AA";\nvar clusterPositions = r.Matches(input).Cast<Match>()\n                        .Select(m => new{start = m.Index, \n                                           end = m.Index + m.Length});	0
4669815	4669691	sql - variable storage	using ( SqlConnection conn = new SqlConnection( "connection string" )\n    {\n      conn.Open();\n\n      string selstr = "SELECT COUNT(*) FROM test3 WHERE PostID = @bleh";\n      SqlCommand cmd = new SqlCommand( selstr, conn );\n      SqlParameter name = cmd.Parameters.Add( "@bleh", SqlDbType.NVarChar, 255 );\n      name.Value = "value";\n      int count = cmd.ExecuteScalar();\n      //Do you stuff\n   }	0
23423913	23423851	How to find TimeZoneInfo by Name	string displayName = "(UTC-12:00) International Date Line West";\nvar tz = TimeZoneInfo.GetSystemTimeZones()\n    .FirstOrDefault(x => x.DisplayName == displayName);	0
3525880	3525737	How to determine if an object is a collection of objects implementing a common interface	var extractors = propInfo.GetValue(dataExtractor, null);\nvar asEnumerable = extractors as IEnumerable;\n\nif (asEnumerable != null)\n{\n    var enumerator = asEnumerable.GetEnumerator();\n    enumerator.MoveNext();\n\n    if (enumerator.Current != null)\n        return enumerator.Current is IDataExtractor;\n}\n\nreturn false;	0
18214457	18214394	How to remove redundance in text attributes?	public class SomeClass\n{\n    public const string SomeConstant = "Long long text 1";\n}\n\n[MyAttribute(SomeClass.SomeConstant)]\npublic class SomeOtherClass\n{\n}	0
16744671	16743868	Entity Framework model is not displaying table with composite key	namespace dbfirstjointable.Models\n{\n    using System;\n    using System.Collections.Generic;\n\n    public partial class Task\n    {\n        public Task()\n        {\n            this.Users = new HashSet<User>();\n        }\n\n        public int Id { get; set; }\n        public string Name { get; set; }\n\n        public virtual ICollection<User> Users { get; set; }\n    }\n}\n\nnamespace dbfirstjointable.Models\n{\n    using System;\n    using System.Collections.Generic;\n\n    public partial class User\n    {\n        public User()\n        {\n            this.Tasks = new HashSet<Task>();\n        }\n\n        public int Id { get; set; }\n        public string Name { get; set; }\n\n        public virtual ICollection<Task> Tasks { get; set; }\n    }\n}	0
2548406	2548372	Find all substrings between two strings	private IEnumerable<string> GetSubStrings(string input, string start, string end)\n{\n    Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));\n    MatchCollection matches = r.Matches(input);\n    foreach (Match match in matches)\n        yield return match.Groups[1].Value;\n}	0
14553652	14553615	How to get strings inside tags?	var cities = XDocument.Parse(myString).Descendants("City").Select(d => d.Value);	0
19592862	19592306	regex remove dynamic string and keep the rest	var input = "http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpg";\nvar re = new Regex("^(.+/product)/.+(/i/.+)$");\nvar m = re.Match(input);\nif (!m.Success) throw new Exception("does not match");\nvar result = m.Groups[1].Value + m.Groups[2].Value;\n//result = "http://example.com/media/catalog/product/i/m/images_3.jpg"	0
30846344	30798287	Disable/Enable context menu item depending on listview item	IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}},Path=SelectedItem.ShowBesItemEn}"	0
3623316	3623147	Binding Label content to Self string field but no result	{Binding Path=Header, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type FlowNode}}}.	0
21189585	21186426	DllImport fails on windows XP SP3 but works on windows 7	[DllImport("TestLib.dll", CallingConvention=CallingConvention.Cdecl)]\npublic static extern void DisplayHelloFromDLL();	0
8463314	8463219	How to write EF Code first mapping for Child with Many Parent Types scenario	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<Employee>.HasMany(p => p.Addresses).WithOptional()\n        .Map(d => d.MapKey("EmployeeId"));\n    modelBuilder.Entity<Supplier>.HasMany(p => p.Addresses).WithOptional()\n        .Map(d => d.MapKey("SupplierId"));\n    modelBuilder.Entity<Customer>.HasMany(p => p.Addresses).WithOptional()\n        .Map(d => d.MapKey("CustomerId"));\n}	0
11094801	11081206	Application closed when using Socket.IO via SocketIO4NET by WCF duplex channel	[CallbackBehavior(UseSynchronizationContext=false)]	0
11823469	11823455	C# List<dictionary> To Json	using Newtonsoft.Json;\nList<Dictionary<string, string>> testDictionary = new List<Dictionary<string, string>()>();\nstring json = JsonConvert.SerializeObject(testDictionary);	0
26251753	26218019	Windows Store Apps async xaml rendering	xamlRead.CacheMode = new BitmapCache();	0
26318586	26318383	How to structure classes in a C# program	Green = 1	0
23680248	23665973	Finding all uses of a Custom Attribute and retrieving the values	var attributes = Assembly.GetExecutingAssembly()\n            .GetTypes()\n            .SelectMany(t => t.GetMethods())\n            .SelectMany(m => m.GetCustomAttributes())\n            .Where(a => a.GetType() == typeof(PageKeyAttribute));	0
14885195	14884833	how to get route data value	[Authorize]\n    public ActionResult Edit()\n    {\n        var userId = (Guid)Membership.GetUser().ProviderUserKey;\n\n        var someService = new MyService();\n        var someData = someService.GetSomeDataByUserId(userId);\n        //...\n    }	0
1063886	1063812	Accessing Oracle Database from C#	tnsping yourdbname	0
3819968	3819815	How to implement SQLDependency caching in Asp.Net?	var command = new SqlCommand("SELECT something FROM dbo.ATable", connection);\nvar dependency = new SqlCacheDependency(command);\nvar result = ObtainResultUsingThe(command);\n\nCache.Insert("CacheKey", result, dependency);	0
33093867	33032136	Exchange 2013 API - Get Room Properties	EmailAddressCollection myRoomLists = service.GetRoomLists();\n        foreach (EmailAddress address in myRoomLists)\n        {\n            EmailAddress myRoomList = address.Address;\n            PropertySet AllProps = new PropertySet(BasePropertySet.FirstClassProperties);\n            NameResolutionCollection ncCol = service.ResolveName(address.Address, ResolveNameSearchLocation.DirectoryOnly, true, AllProps);\n            foreach (NameResolution nr in ncCol)\n            {\n                Console.WriteLine(nr.Contact.DisplayName);\n                Console.WriteLine(nr.Contact.Notes);\n            }\n        }	0
30435412	30241336	How to Change the Color Scheme in a Docx document?	ActiveDocument.ApplyDocumentTheme _ "C:\Users\Admin\Theme.thmx"\n\n ActiveDocument.Save	0
12981099	12981024	Trying to detect keypress	private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyCode == Keys.F1 && e.Alt)\n    {\n        //do something\n    }\n}	0
10458832	10458757	Will this getter make a database call every time it's referenced?	public class MyClass {\n...    \n\n    private List<SomeClass> _myProperty = null;\n    public List<SomeClass> MyProperty {\n        get { \n            if (_myProperty == null) _myProperty = SomeClass.GetCollectionOfThese(someId);\n            return _myProperty;\n        } \n    }\n...\n}	0
20781770	20781619	How to add an additional cell in gridview showing total number of rows?	private int RowNumber=0; // Define at the top\nprotected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n   if (e.Row.RowType == DataControlRowType.DataRow)\n   {\n\n      RowNumber += 1;\n   }\n    // you need to add one label at Footer section\n   if (e.Row.RowType == DataControlRowType.Footer)\n   {\n      Label lblTotalRow = (Label)e.Row.FindControl("lblTotalRow");\n      lblTotalRow.Text = RowNumber.ToString();\n   }\n}	0
24938318	24926728	GAL from outlook with exchange from which one to get?	"http://schemas.microsoft.com/mapi/proptag/0x800F101F".	0
27229547	27229484	How to replace this HTML snippet in some text?	strContent = strContent\n    .Replace("<div style=\"page-break-after:always\">" + \n             "<span style=\"display:none\">&nbsp;</span></div>",\n             "<br style=\"page-break-after: always;\" />");	0
807733	807720	Interface with a list of Interfaces	public interface IRequest<T> where T : IRequestDetail\n{\n    IList<T> Details { get; set; }\n\n    // stuff\n}\n\npublic class MyRequest : IRequest<MyRequestDetail>\n{\n    public IList<MyRequestDetail> Details {get; set; }\n\n    // stuff\n}	0
1134826	1134808	How to query a DataSet and iterate through the result?	DataTable dt;\n...\nforeach (DataRow dr in dt.Select(filter))\n{\n    // ...\n}	0
25933008	25932695	Does MS C# Implementation of String check ReferenceEquals of the immuteable base String first?	[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\n        public override bool Equals(Object obj) {\n            if (this == null)                        //this is necessary to guard against reverse-pinvokes and\n                throw new NullReferenceException();  //other callers who do not use the callvirt instruction\n\n            String str = obj as String;\n            if (str == null)\n                return false;\n\n            if (Object.ReferenceEquals(this, obj))\n                return true;\n\n            if (this.Length != str.Length)\n                return false;\n\n            return EqualsHelper(this, str);\n        }	0
5798316	5797188	keybd_event: global keystrokes simulations show up in unexpected manner in C# Console	private static void FlushKeyboard()\n{\n     while (Console.In.Peek() != -1)\n         Console.In.Read();\n}	0
16229284	16228986	Add a button to the left of a toolstrip	private void VerticalButtonTextEvent(object sender, PaintEventArgs e)\n    {\n        Button button = sender as Button;\n        if (button == null) return;\n\n        Graphics g = e.Graphics;\n        g.FillRectangle(SystemBrushes.Control, button.ClientRectangle);\n        using (Font f = new Font("Times New Roman", 8))\n        {\n            SizeF szF = g.MeasureString(button.Text, f);\n            g.TranslateTransform(\n                (float) ((Button) sender).ClientRectangle.Width/(float) 2 + szF.Height/(float) 2,\n                (float) ((Button) sender).ClientRectangle.Height/(float) 2 -\n                (float) szF.Width/(float) 2);\n            g.RotateTransform(90);\n            g.DrawString(button.Text, f, Brushes.Black, 0, 0);\n        }\n    }	0
7277714	7277696	What is the VB.NET syntax for using List.FindAll() with a lambda?	Dim tlist As List(Of group.category) _\n    = list.FindAll(Function(p) p.parid = titem.catid)	0
337831	337816	how do you pull in the html from a URL?	WebClient wClient = new WebClient();\nstring s = wClient.DownloadString(site2);	0
23681071	23680895	How to render a default text in a wpf listbox	private string _name = "";\npublic string Name { \nget\n{\n    if(string.IsNullOrEmpty(_name))\n    {\n        return "Unnamed";\n    }\n    else\n    {\n        return _name;\n    }\n}\n set\n{\n    _name = value;\n}\n}	0
10391685	10391622	Tracing a SQL Exception	try\n    {\n        command.Connection.Open();\n        command.ExecuteNonQuery();\n    }\n    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
1441121	1201276	How do I attach a UserControl to a form in an MVP pattern?	subView\n  |\n  V\nsubPresenter\n  |\n  V\nmainPresenter\n  |\n  V\nmainView	0
23368101	23356286	Accessing data saved in custom file type in Windows Forms application	System.Runtime.Hosting.ActivationArguments args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;\nif (args.ActivationData != null)\n{\n    foreach (string commandLineFile in AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData)\n    {\n        MessageBox.Show(string.Format("Command Line File: {0}", commandLineFile));\n    }\n}	0
8196953	8194006	C# setting screen brightness Windows 7	using System.Management;\n//...\nstatic void SetBrightness(byte targetBrightness) {\n    ManagementScope scope = new ManagementScope("root\\WMI");\n    SelectQuery query = new SelectQuery("WmiMonitorBrightnessMethods");\n    using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) {\n        using(ManagementObjectCollection objectCollection = searcher.Get()) {\n            foreach(ManagementObject mObj in objectCollection) {\n                mObj.InvokeMethod("WmiSetBrightness",\n                    new Object[] { UInt32.MaxValue, targetBrightness });\n                break;\n            }\n        }\n    }\n}	0
2252887	2252771	extracting method name from linq expression	public static class MethodUtils\n{\n    public static string NameFromExpression(LambdaExpression expression)\n    {\n        MethodCallExpression callExpression = \n            expression.Body as MethodCallExpression;\n\n        if(callExpression == null)\n        {                \n            throw new Exception("expression must be a MethodCallExpression");\n        }\n\n        return callExpression.Method.Name;\n    }\n}	0
25169073	25168622	.Net Program with both WinForm and Console Interfaces	static class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    [STAThread]\n    static void Main(string[] args)\n    {\n\n        if (ProcessCommandLine(args))\n            return;\n\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n    }\n\n    static bool ProcessCommandLine(string[] args)\n    {\n         //Process it, if some has been processed return true, else return false\n    }\n}	0
22728435	19756211	VK api: how to insert user id's at get request	qs["uids"] = uids;	0
8926065	8926031	How to have an Iterator for a Dictionary?	public IEnumerable<KeyValuePair<int, string>> Foo()\n{\n    var implementationDetail = new Dictionary<int, string>\n    {\n        { 1, "foo" },\n        { 2, "bar" },\n    };\n\n    return implementationDetail;\n}	0
2103440	2103418	c# best way to grab a xsd from a referenced project	Type t = typeof(TypeInOtherAssembly);\nAssembly assembly = t.Assembly;\nassembly.GetManifestResourceStream(...);	0
15642705	15642580	Adding Rows and Columns to a WPF DataGrid at Run-Time	public static void Display_Grid(DataGrid d, List<string> S1)\n{\n    ds = new DataSet();\n    DataTable dt = new DataTable();\n    ds.Tables.Add(dt);\n\n    DataColumn cl = new DataColumn("Item Number", typeof(string));\n    cl.MaxLength = 200;\n    dt.Columns.Add(cl);\n\n    int i = 0;\n    foreach (string s in S1)\n    {\n        DataRow rw = dt.NewRow();\n        rw["Item Number"] = S1[i];\n        i++;\n    }\n    d.ItemsSource = ds.Tables[0].AsDataView();\n}	0
18081361	18081013	Get single record from observablecollection	yourListBox.ItemsSource = yourCollection.Where((x) => x.id == id);	0
1068906	1068846	Delete currently loaded assembly	[return: MarshalAs (UnmanagedType.Bool)]\n[DllImport ("kernel32", CharSet = CharSet.Auto, SetLastError = true)]\nprivate static extern bool MoveFileEx (string lpExistingFileName, string lpNewFileName, int dwFlags);\n\npublic static bool ScheduleDelete (string fileFullName) {\n    if (!File.Exists (fileFullName))\n        throw new InvalidOperationException ("File does not exist.");\n\n    return MoveFileEx (fileFullName, null, 0x04); //MOVEFILE_DELAY_UNTIL_REBOOT = 0x04\n}	0
15688857	15688493	Dictionary with limited number of types	public class MyDic : IDictionary<object, object>\n{\n    private Dictionary<object, object> privateDic= new Dictionary<object,object>();\n\n\n    public void Add(object key, object value)\n    {\n        if (value.GetType() == typeof(string))\n            throw new ArgumentException();\n        privateDic.Add(key, value);\n    }\n    //Rest of the interface follows\n}	0
13538462	13538454	Returning variables from public class C#	public void main() {\n   IDFMeasure measure = new IDFMeasure();  // instantiate class\n   float[][] vals = measure.GetIDFMeasure(documents); // now call method on that class\n}	0
34426325	34426217	C# How to only select strings based on a common set of characters?	string str = @"128 2 2 0 24 49 50 46\n\n129 4 2 0 26 51 36 54 53\n\n130 4 2 0 26 51 41 52 56";\n\n        string[] strSplitted = str.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);\n        List<string> result = strSplitted.ToList();\n\n        foreach (var item in strSplitted)\n        {\n            if (!item.Contains("4 2 0"))\n            {\n                result.Remove(item);\n            }\n        }	0
33381709	33375491	How to use DataAdapter to call a stored procedure in C# with variable parameters	using(SqlConnection con = new SqlConnection("Your Connection String Here"))\n{ \n    SqlCommand cmd = new SqlCommand("sp_SomeName", con);\n    cmd.CommandType = CommandType.StoredProcedure;\n\n    //the 2 codes after this comment is where you assign value to the parameters you\n    //have on your stored procedure from SQL\n    cmd.Parameters.Add("@MONTH", SqlDbType.VarChar).Value = "someValue";\n    cmd.Parameters.Add("@YEAR", SqlDbType.VarChar).Value = "SomeYear";\n\n    SqlDataAdapter da = new SqlDataAdapter(cmd);\n    SqlDataSet ds = new SqlDataSet();\n    da.Fill(ds); //this is where you put values you get from the Select command to a \n  //dataset named ds, reason for this is for you to fetch the value from DB to code behind\n\n    foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.\n    {\n       someTextBox.Text = dr["Month"].ToString(); //you should probably know this code\n    }\n}	0
18120600	18120472	How do i copy files from one directory to another directory?	File.Copy(s[i], "c:\\anotherFolder\\" + Path.GetFileName(s[i]));	0
32736453	32011344	C# WPF Expander in Datagrid should be frozen (fix) while scrolling	private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)\n{\n    var dataGrid = (DataGrid)sender;\n    if (dataGrid.IsGrouping && e.HorizontalChange != 0.0)\n    {\n        TraverseVisualTree(dataGrid, e.HorizontalOffset);\n    }\n}\n\nprivate void TraverseVisualTree(DependencyObject reference, double offset)\n{\n    var count = VisualTreeHelper.GetChildrenCount(reference);\n    if (count == 0)\n        return;\n\n    for (int i = 0; i < count; i++)\n    {\n        var child = VisualTreeHelper.GetChild(reference, i);\n        if (child is ToggleButton)\n        {\n            var toggle = (ToggleButton)child;\n            toggle.Margin = new Thickness(offset, 0, 0, 0);\n        }\n        else\n        {\n            TraverseVisualTree(child, offset);\n        }\n    }\n}	0
20418527	20418475	C# HTML Parse of web page	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar node = doc.DocumentNode\n            .SelectSingleNode("//span[@class='market_listing_price market_listing_price_without_fee']");\n\nvar text = WebUtility.HtmlDecode(node.InnerText);	0
8565798	8565734	How do I select a desired row in a grouped result using c# LINQ	var results = Customers.GroupBy(c => c.ID)\n                       .Select(\n                          g => g.OrderByDescending(c => c.EndDate).First() );	0
28476538	28470049	Executing another Application with selected file using a button (C# Programming)	if( textBox1.Text != String.Empty && System.IO.File.Exists(textBox1.Text) )\n{\n    // The textbox has a filename in it, use it\n    mApp.Open(textBox1.Text, true, true);\n}\nelse\n{\n    // The user hasn't selected a config file, launch with default\n    mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);\n}	0
32725797	32725762	C# Set File Size	FileStream.SetLength	0
896597	853533	Aero Glass Borders on Popup Windows in C#	if (m.Msg == 0x84 /* WM_NCHITTEST */) {\n    m.Result = (IntPtr)1;\n    return;\n}\nbase.WndProc(ref m);	0
7910742	7909235	Silverlight 4 - Retrieve a solid color brush from Resource Dictionary at runtime?	Application.Current.Resources["ResourceName"] as SolidColorBrush	0
20661497	20659219	Windows Phone 8 App Dynamically/programmatically create buttons in g grid/Panel	private void Grid_View_Btn_1_Click(object sender, System.Windows.RoutedEventArgs e)\n    {   \n        Dispatcher.BeginInvoke(() => {         \n            StackPanel panel = new StackPanel();\n            panel.Orientation = System.Windows.Controls.Orientation.Vertical;\n            int i;\n            for (i=0;i<5;i++)\n            {\n                Button btn = new Button() { Content = "Button" };\n                btn.Width=130;\n                btn.Height = 66;\n                // btn.Margin = new Thickness(0,0,0,0)//try this if you use grid\n                //grid.Children.Add(btn);\n                panel.Children.Add(btn);\n            }\n\n            grid.Children.Add(panel);\n\n            //       Grid.SetRow(control, i);\n            //    Grid.SetColumn(control, j);\n            // TODO: Add event handler implementation here.\n        });\n    }	0
2209955	2209926	How to write the C# prototype to P/Invoke a function which takes a char* as an argument, and returns its value there	[DllImport(_libName, EntryPoint="DLLErrorMsg", CallingConvention=CallingConvention.Cdecl)]\npublic static extern UInt32 GetErrorMessage(UInt32 dwError, StringBuilder pBuf, UInt32 nBufSize);	0
15318768	15318632	How can I register this .NET interface with AutoFac?	builder.RegisterInstance(documentStore).As<IDocumentStore>();\n\nbuilder.Register(x => x.Resolve<IDocumentStore>().OpenSession())\n       .As<IDocumentSession>()\n       .InstancePerLifetimeScope();	0
14606951	14606705	Dynamically Change Local Resource Image in a Winform	Embedded Resource	0
20097589	20097425	Run cmd with parametrs from c# code	var pathToRbFile = @"C:\Ruby193\script\123.rb";\nvar arguments = string.Empty; // I don't know what the arguments would be\n\nvar info = new ProcessStartInfo(pathToRbFile, arguments);\nProcess.Start(info);	0
13022344	13022150	Playing with Radio button in wpf c#	void rdbtn1_Checked(object sender, RoutedEventArgs e)\n{\n     textBox1.IsReadOnly = false;\n     DatePicker1.Focusable = true;\n     DatePicker1.IsHitVisible = true;\n}\n\n\nvoid rdbtn1_Unchecked(object sender, RoutedEventArgs e)\n{    \n     textBox1.IsReadOnly = true;\n     DatePicker1.Focusable = false;\n     DatePicker1.IsHitVisible = false;    \n}	0
16058465	16058356	Best practice - inherited variables set in derived classes	public abstract class TestBase\n{\n    protected string itemType;    // can now become 'readonly`\n\n    protected TestBase(string keyName)\n    {\n       itemType = ConfigurationManager.AppSettings[keyName];\n    }\n}\n\npublic class TestClass1 : TestBase\n{\n    public TestClass1() : base("TestClass1.ItemType")\n    {\n        //itemType = ConfigurationManager.AppSettings["TestClass1.ItemType"];\n    }\n}	0
30117713	30117361	Find all duplicate records in SQL table with Entity Framework by Multiple colums	var query = from visit in db.Visits\n\n                    join address in db.Addresses on visit.AddressId equals address.Id\n\n                    group address by new {\n                        address.Name,\n                        address.Prename,\n                        address.Street,\n                        address.StreetNr,\n                        address.Zip,\n                        address.ZipLong\n                    } into temp\n                select  new {\n                    Name = temp.Key.Name,\n                    Prename = temp.Key.Prename,\n                    Street = temp.Key.Street,\n                    StreetNr = temp.Key.StreetNr,\n                    Zip = temp.Key.Zip,\n                    ZipLong = temp.Key.ZipLong,\n                    RecCount = temp.Count()\n                };\n\n            var list = query.Where(x => x.RecCount > 1).ToList();	0
12347488	12347465	How to load unmanaged library with P/Invoke?	[DllImport("User32.dll")]\npublic static extern int MessageBox(int h, string m, string c, int type);	0
14434796	14434750	iterate through particular column in a datatable	int code = Convert.ToInt32(dr["Code"]);	0
12782849	12781218	how check what datagridview checkbox has been selected	for (int i = 0; i <= GridView1.Rows.Count - 1; i++)\n        {\n\n\n            GridViewRow row = GridView1.Rows[i];\n            CheckBox Ckbox = (CheckBox)row.FindControl("CheckBox2");\n            if (Ckbox.Checked)\n            {\n               //........\n\n            }\n        }	0
994128	994117	Using First() with a generic collection through reflection	return (string) typeof(T).GetProperty(theProperty).GetValue(collection.First(), null);	0
3538600	3538444	SQL Server Database Restore with ReadXML	protected void ReadXML(string tableName)\n{\n    DataSet ds = new DataSet();\n    ds.ReadXml(Server.MapPath("App_Data\\" + tableName + ".xml");\n    using (SqlBulkCopy sbc = new SqlBulkCopy(ConnectionString))\n    {\n        sbc.DestinationTableName = tableName;\n        sbc.WriteToServer(ds.Tables[tableName]);\n        sbc.Close();\n    }\n}	0
1927776	1927602	Dialog doesn't display properly because of a loop after using .Show() method in C#	backgroundWorker.WorkerReportsProgress = true;\n\n        backgroundWorker.DoWork += (newSender, newE) =>\n        {\n            while (!this.ourCC.Connected)\n            {\n                this.ourCC.InitializeConnection();\n\n                if (!this.ourCC.Connected)\n                {\n                    backgroundWorker.ReportProgress(0, true);\n                }\n            }\n        };\n\n        backgroundWorker.ProgressChanged += (newSender, newE) =>\n        {\n            if (!ourECF.Visible)\n            {\n                ourECF.Show();\n            }\n        };\n\n        backgroundWorker.RunWorkerCompleted += (newSender, newE) =>\n        {\n            ourECF.Dispose();\n        };\n\n        backgroundWorker.RunWorkerAsync();	0
475289	474224	DataGridView/ListView - Display in an Outlook style?	private void lstItems_DrawItem(object sender, DrawItemEventArgs e)	0
14983253	14983187	String Replace Line Breaks	result = result.Replace("\n","").Replace("\r","\r\n")	0
22772291	22750430	custom papersize printDocument webforms	pd.PrinterSettings.PrinterName = "HP LaserJet P1005";\npd.OriginAtMargins = true;\nPaperSize pageSize = new PaperSize();\npageSize.RawKind = 512; //this is number of created custom size 563x1251\nMargins margins = new Margins(1, 1, 1, 1);\npd.DefaultPageSettings.Margins = margins;\npd.DefaultPageSettings.Landscape = true;\npd.PrintPage += new PrintPageEventHandler(pd_PrintPage);\npd.Print();	0
9897532	9897392	Format binding value with c#	Binding b = new Binding("Value")\n {\n      Source = this,\n      StringFormat = "c"\n };	0
27243019	27242813	Assign value to String Property based on integer Property value in Linq query	var data = db.ProjectSetups.ToList();\n     data = data.Select(c => new ProjectSetup\n                        {\n                            ProjectId = c.ProjectId,\n                            Name = c.Name,\n                            NameArabic = c.NameArabic,\n                            StartDate = c.StartDate,\n                            EndDate = c.EndDate,\n                            Date = c.Date,\n                            StringType = (c.Type.ToInt32() == 1 ? "Development" : "Rental").ToString(),\n                            StringStatus = (c.Status == 1 ? "InProgress" :\n                            c.Status == 2 ? "Completed" :\n                            c.Status == 3 ? "Dividend" : "Closed"),\n                            LandArea = c.LandArea,\n                            SaleAmount = c.SaleAmount\n\n                        }).ToList();	0
28465903	28464637	Entity Framework - how to select first row each IDNumber by one query Using lambda	var r = db.Orders.GroupBy(o => o.IdNumber).Select(g => g.OrderByDescending(o => o.InsuranceDate).FirstOrDefault());	0
27398628	27398386	How to create datatable in C#?	public DataTable MethodName(string Param)\n{\n    DataTable dt = new DataTable();\n    dt.Columns.Add("Order", typeof(Int32));\n    dt.Columns.Add("Driver", typeof(Int32));\n\n    DataRow dr = dt.NewRow();\n    dr["Order"] = AnotherMethod1(Param) ? 1 : 0;\n    dr["Driver"] = AnotherMethod2(Param) ? 1 : 0;\n    dt.Rows.Add(dr);           \n    return dt;	0
5890040	5889643	Problems with submitting text to access database	cmd.CommandText = @"INSERT INTO bookRated([title], [rating],  [review], [frnISBN], [frnUserName])VALUES('" + title.Replace("'", "''") + "', '" + rating.Replace("'", "''") + "','" + review.Replace("'", "''") + "','" + ISBN + "', '" + userName + "')";	0
2451341	2451336	How to Pass Parameters to Activator.CreateInstance<T>()	(T)Activator.CreateInstance(typeof(T), param1, param2);	0
14990726	14968729	Html Agility Pack loop through table rows and columns	foreach (HtmlNode row in doc.DocumentNode.SelectNodes("/html/body/table/tbody/tr/td/table[@id='table2']/tbody/tr"))\n            {\n                HtmlNodeCollection cells = row.SelectNodes("td");\n                for (int i = 0; i < cells.Count; ++i)\n                {\n                    if (i == 0)\n                    { Response.Write("Person Name : " + cells[i].InnerText + "<br>"); }\n                    else {\n                        Response.Write("Other attributes are: " + cells[i].InnerText + "<br>"); \n                    }\n                }\n            }	0
26429395	26429312	Redirect to a different page in a new window	window.open('../ClaimTimeExpense.aspx', '_blank')	0
16334175	16333979	C# - using "this" as a parameter to initialize a child class	public class MyClass\n{\n    private OtherClass _someProperty;\n    public OtherClass SomeProperty \n    {\n        get\n        { \n             if (this._someProperty == null) this._someProperty = new OtherClass(this);\n             return this._someProperty;\n        }\n    }\n}\n\npublic class OtherClass\n{\n    private MyClass _parent;\n    public OtherClass(MyClass parent)\n    {\n        this._parent = parent;\n    }\n}	0
31111038	31110291	Validate a Create and Edit DTO with nealy all same properties	public interface ITestDTO\n{\n    DateTime Date { get; }\n    int Number { get; }\n    int SchoolClassCodeId { get; }\n    int SchoolYearId { get; }\n    int TestTypeId { get; }\n    int? TestId { get; }\n}\n\npublic class EditTestDTO : ITestDTO\n{\n    [Required]\n    public DateTime Date { get; set; }\n    [Required]\n    public int Number { get; set; }\n    [Required]\n    public int SchoolClassCodeId { get; set; }\n    [Required]\n    public int SchoolYearId { get; set; }\n    [Required]\n    public int TestTypeId { get; set; }\n    [Required]\n    public int TestId { get; set; }\n\n    int? ITestDTO.TestId { get { return TestId; } }\n}\n\npublic class CreateTestDTO : ITestDTO\n{\n    [Required]\n    public DateTime Date { get; set; }\n    [Required]\n    public int Number { get; set; }\n    [Required]\n    public int SchoolClassCodeId { get; set; }\n    [Required]\n    public int SchoolYearId { get; set; }\n    [Required]\n    public int TestTypeId { get; set; }\n\n    int? ITestDTO.TestId { get { return null; } }\n}	0
12292424	12292311	What's the easiest way to add a zero-byte to a byte array?	byte[] bytes = ...\n\nif ((bytes[bytes.Length - 1] & 0x80) != 0)\n{\n    Array.Resize<byte>(ref bytes, bytes.Length + 1);\n}\n\nBigInteger result = new BigInteger(bytes);	0
7475562	7475518	xml file parsing	var results = from item in query\n              select new \n              {\n                   XMaxResult = item.XMax < 275 ? "pass" : "fail",\n                   ...\n              };	0
32124337	32124131	Parsing a generic variable from a Json text	int  summonerLevel= (int)JObject.Parse(data).First.First["summonerLevel"];	0
8110473	8110324	How to sort a dictionary by key	var r = new Dictionary<string, Point>();\nr.Add("c3", new Point(0, 0));\nr.Add("c1", new Point(0, 0));\nr.Add("t3", new Point(0, 0));\nr.Add("c4", new Point(0, 0));\nr.Add("c2", new Point(0, 0));\nr.Add("t1", new Point(0, 0));\nr.Add("t2", new Point(0, 0));\nvar l = r.OrderBy(key => key.Key);\nvar dic = l.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);\n\nforeach (var item in dic)\n{\n\n    Console.WriteLine(item.Key);\n}\nConsole.ReadLine();	0
30374849	30318609	How to change Customer ID through Acumatica Web Service	AR303000.Actions.ChangeID.Commit = true;\ncommands.Add(new Value { Value = "ABARTENDE", LinkedCommand = AR303000.CustomerSummary.CustomerID, Commit = true });\ncommands.Add(new Value { Value = "ABARTENDE1", LinkedCommand = AR303000.SpecifyNewID.CustomerID });\ncommands.Add(new Value { Value = "OK", LinkedCommand = AR303000.SpecifyNewID.ServiceCommands.DialogAnswer, Commit = true });\ncommands.Add(AR303000.Actions.ChangeID);\ncommands.Add(AR303000.Actions.Save);	0
26690062	26670437	How to populate date and time in dropdownlist?	DropDownListDate.Items.Add(DateTime.Now.ToShortDateString()); //for adding current date\n    for (int i = 1; i <= 59; i++) //loop to add next 60 days\n    {\n        DropDownListDate.Items.Add(DateTime.Now.AddDays(i).ToShortDateString());\n    }\n\n    DateTime dt = Convert.ToDateTime("09:00"); //for adding start time\n    for (int i = 0; i <= 25; i++) //Set up every 30 minute interval\n    {\n        ListItem li2 = new ListItem(dt.ToShortTimeString(), dt.ToShortTimeString());\n        li2.Selected = false;\n        DropDownListTime.Items.Add(li2);\n        dt = dt.AddMinutes(30);	0
10956984	10956961	How to SELECT a drop down list item by value programatically in C# and pass it to integer?	dt = obj.selectcat(Convert.ToInt32(catselectddl.SelectedValue));	0
12061671	12058158	TreeListControl within each NavbarControl Group	private void CreateGroup2(NavBarGroup navBarGroup)\n{\n\n    System.Windows.Controls.TreeView treeview = new System.Windows.Controls.TreeView();\n\n    TreeViewItem nod = new TreeViewItem();\n    nod.Header = "Tree Node1";\n    treeview.Items.Add(nod);\n\n    TreeViewItem nod1 = new TreeViewItem();\n    nod1.Header = "Tree Node2";\n    treeview.Items.Add(nod1);\n\n    TreeViewItem nod2 = new TreeViewItem();\n    nod2.Header = "Tree Node3";\n    nod1.Items.Add(nod2);\n\n    //StackPanel stcPnl = new StackPanel(); /optiona\n    //stcPnl.Children.Add(treeview);\n    //navBarGroup.Content = stcPnl;\n\n    navBarGroup.Content = treeview;\n\n    navBarGroup.DisplaySource = DisplaySource.Content;\n\n}	0
15418884	15418269	ServiceStack TypeLoadException - Unknown Origin	ServiceStack.Text\n  +\n  > ServiceStack.Interfaces\n  > ServiceStack.Common\n      + \n      > ServiceStack.Redis\n      > ServiceStack.OrmLite\n          +\n          > ServiceStack\n              +\n              > ServiceStack.ServiceInterface	0
4070984	4070806	How can I create an SSH connection from a C# application?	public void ExecuteExternalCommand(string command)\n{\n try\n {\n  // process start info\n  System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);\n  processStartInfo.RedirectStandardOutput = true;\n  processStartInfo.UseShellExecute = false;\n  processStartInfo.CreateNoWindow = true; // Don't show console\n\n  // create the process\n  System.Diagnostics.Process process = new System.Diagnostics.Process();\n  process.StartInfo = processStartInfo;\n  process.Start();\n\n  string output = process.StandardOutput.ReadToEnd();\n  Console.WriteLine(output);\n }\n catch (Exception exception)\n {\n  //TODO: something Meaninful\n }\n}	0
8197162	8196605	Bring button to front on Windows Phone UI	//Originally posted by CleverCode - http://forums.silverlight.net/post/63607.aspx\npublic static void PushToTop(this FrameworkElement element)\n{\n    if (element == null) throw new ArgumentNullException("element");\n    var parentPanel = element.Parent as Panel;\n    if (parentPanel != null)\n    {\n        // relocate the framework element to be the last in the list (which makes it "above" everything else)\n        parentPanel.Children.Remove(element);\n        parentPanel.Children.Add(element);\n        parentPanel.UpdateLayout();\n    }\n}	0
3082621	3082469	Adding data to Dictonary in C#	XDocument document = XDocument.Load(Application.StartupPath + "\\Sample.xml");\n\nDictionary<string, List<string>> result = (from root in document.Descendants("Element")\n                                                       group root by root.Attribute("Key").Value into KeyGroup\n                                                       select KeyGroup)\n                                                       .ToDictionary(grp => grp.Key, \n                                                                     grp => grp.Attributes("ValOne").Select(at => at.Value).ToList());	0
25281608	25281165	Remove duplicates from DropDownList from database MVC4	List<string> authorname = new List<string>();\n\nforeach (var item in DB.Books)\n{\n   if(!authorname.Contains(item.BookDetails.authorname.ToString()))\n      authorname.Add(item.BookDetails.authorname.ToString());\n}\n\nViewData["AuthorName"] = new SelectList(authorname);	0
4979390	4979354	json with C# in a WCF service?	string json = // Your JSON message\nWebRequest request = WebRequest.Create ("http://api.pennysms.com/jsonrpc");\nrequest.Method = "POST";\nvar postData = Encoding.UTF8.GetBytes(json);\nrequest.ContentLength = postData.Length;\nrequest.ContentType = "text/json";\nusing(var reqStream = request.GetRequestStream()) \n{\n    reqStream.Write(postData);\n}\nusing(var response = request.GetResponse())\n{\n    // Response status is in response.StatusCode\n    // Or you can read the response content using response.GetResponseStream();\n}	0
31028616	31028417	Deserializing with JSON.net dynamically	var client = new WebClient { UseDefaultCredentials = true };\n\nclient.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");\nvar result = JsonConvert.DeserializeObject<Object>(Encoding.UTF8.GetString(client.DownloadData(ConfigurationManager.AppSettings["InternalWebApiUrl"] + "/" + url)));\n\nreturn Request.CreateResponse(result);	0
1616279	1616047	How to pass Generic Type parameter to lambda expression?	// A lambda solution\n        Func<object, object> fnGetValue =\n            v =>\n                ReferenceEquals(v, null)\n                ? DBNull.Value\n                : v;\n\n\n        // Sample usage\n        int? one = 1;\n        int? two = null;\n        object o1 = fnGetValue(one); // gets 1\n        object o2 = fnGetValue(two); // gets DBNull	0
19351345	19351268	Find and delete a value in CSV	string names;\nList<string> values;\nusing (var stream = new StreamReader("path/to/file.csv"))\n{\n    names = stream.ReadLine();\n    values = stream.ReadLine().Split(',').ToList();\n}\nvalues.RemoveAt(9);\nnames; // first part of file\nstring secondPartOfFile = string.Join(",", values);	0
4482432	4482382	Searching a particular value in datatable	var table = new DataTable();\n\n        table.Columns.Add("id", typeof(int));\n        table.Columns.Add("name");\n        table.Columns.Add("unit");\n\n        var table2 = new DataTable();\n        table2.Columns.Add("id", typeof(int));\n        table2.Columns.Add("value");\n\n        table.Rows.Add(1, "a Name", "a Unit");\n        table.Rows.Add(2, "other", "other");\n\n        table2.Rows.Add(1, "value");\n        table2.Rows.Add(4, "other");\n\n        var result = table.AsEnumerable().Join(table2.AsEnumerable(), r1 => r1.Field<int>("id"), r2 => r2.Field<int>("id"),\n                                  (r1, r2) => new {Id = r1.Field<int>("id"), Value = r2.Field<string>("value") }).ToList();\n\n        foreach (var r in result)\n            Console.WriteLine(r.Id + "|"+ r.Value);	0
13351436	13350310	Consume a HTTP POST from a self hosted service	//This is run on it's own thread\nHttpListener listener = new HttpListener();\nlistener.Prefixes.Add(Properties.Settings.Default.BitsReplierAddress);\nlistener.Start();\n\nwhile (_running)\n{\n    // Note: The GetContext method blocks while waiting for a request. \n    // Could be done with BeginGetContext but I was having trouble \n    // cleanly shutting down\n    HttpListenerContext context = listener.GetContext();\n    HttpListenerRequest request = context.Request;\n\n    var requestUrl = request.Headers["BITS-Original-Request-URL"];\n    var requestDatafileName = request.Headers["BITS-Request-DataFile-Name"];\n\n    //(Snip...) Deal with the file that was uploaded\n}\n\nlistener.Stop();	0
10861435	10761058	How do I format so method parameters are stacked vertically, one per line?	ReSharper | Options -> \nCode Editing | C# | Formatting style | Line breaks and Wrapping -> \nLine wrapping | Wrap formal parameters	0
8127642	8107610	Can't open excel file generated with excelLibrary	string filename = "c:\Test.xls";\nWorkbook workbook = new Workbook();\nWorksheet sheet = new Worksheet("Test")\nworkbook.Worksheets.Add(sheet)\n\nfor(int i = 0;i < 100; i++)\n      sheet.Cells[i,0] = new Cell("");\n\nworkbook.save(filename);	0
6760529	6760424	C# MVC Implementing API with HMAC signature parameters	[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]\n    public class Securitycheck : ActionFilterAttribute {\n        public Securitycheck (String key, String sig) {\n        }\n        public override void OnActionExecuting(ActionExecutingContext filterContext) {\n            base.OnActionExecuting(filterContext);\n            if (failed) {\n               filterContext.Result = new RedirectResult(redirect);\n            }\n        }\n    }	0
32563920	30484634	Converting a two dimensional int array to a byte array	static byte[] ToBytes(object obj)\n    {\n        BinaryFormatter bf = new BinaryFormatter();\n        MemoryStream ms = new MemoryStream();\n        bf.Serialize(ms, obj);\n        byte[] bytes = ms.ToArray();\n        return bytes;\n    }\n    static int[,] FromBytes(byte[] buffer)\n    {\n        BinaryFormatter bf = new BinaryFormatter();\n        MemoryStream ms = new MemoryStream(buffer);\n        int[,] mat = (int[,])bf.Deserialize(ms);\n        return mat;\n    }	0
9731903	9731862	How to sort a list of objects by a variable that is not part of the object?	People.Sort((p1,p2)=>scoreFunc(p1)-scoreFunc(p2));	0
12609934	12609751	Understanding how to use classes	List<Animal> animals = new List<Animal>();\n\n            Horse hr = new Horse();\n            Dog dg = new Dog();\n            Bird br = new Bird();\n\n            animals.Add(hr);\n            animals.Add(dg);\n            animals.Add(br);\n\n            foreach(var animal in Animals)\n            {\n                Console.WriteLine(animal.eat());\n            }	0
30385400	30384793	How do I pass arguments to a Python script with IronPython	using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Windows.Forms;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing IronPython.Hosting;\nusing Microsoft.Scripting;\nusing Microsoft.Scripting.Hosting;\nusing IronPython.Runtime;\n\nnamespace RunPython\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);\n            ScriptRuntime runtime = new ScriptRuntime(setup);\n            ScriptEngine engine = Python.GetEngine(runtime);\n            ScriptSource source = engine.CreateScriptSourceFromFile("HelloWorld.py");\n            ScriptScope scope = engine.CreateScope();\n            List<String> argv = new List<String>();\n            //Do some stuff and fill argv\n            argv.Add("foo");\n            argv.Add("bar");\n            engine.GetSysModule().SetVariable("argv", argv);\n            source.Execute(scope);\n        }\n    }\n}	0
29320759	29320717	C# regular expression format	[RegularExpression("^08[3-9]$", ErrorMessage = "Please enter a valid 3 digit area code")]	0
29415535	29414707	Explanation of 'CA1800: Do not cast unnecessarily' needed	var something = new Something();\nobject expression = "Any value";\nstring expressionAsString = expression as string;\nfor (int i = 0; i < 2; i++)\n{\n    switch (i)\n    {\n        case 0:\n            something.Help = expressionAsString;\n            break;\n\n        case 1:\n            something.Description = expressionAsString;\n            break;\n    }\n}	0
20393143	20392906	without using foreach, how to get all GUID's in List<string> object and send to database method	var idList = string.Join(",", folderRequestIDs);//you will get a string "id1,id2,id3..."	0
17530937	17521347	TextRenderer. How to render text multiline with endellipsis?	TextRenderer.DrawText(e.Graphics, myString, this.Font,\n                      textRec, Color.Black, Color.Empty,\n                      TextFormatFlags.HorizontalCenter |\n                      TextFormatFlags.TextBoxControl |\n                      TextFormatFlags.WordBreak |\n                      TextFormatFlags.EndEllipsis);	0
11169112	11147496	Exit process created with CreateProcessWithLogonW on logout	this.ShowInTaskbar = false;\nthis.WindowState = FormWindowState.Minimized;\nthis.Visible = false;	0
1347269	1347209	How do I get the ColumnAttributes from a Linq.Table<TEntity>?	var context = new MyDataContext();\nMetaTable userMeta = context.Mapping.GetTable(typeof(User));\nvar dataMembers = userMeta.RowType.PersistentDataMembers;	0
22498921	22498740	What's required to properly escape a URI for use in HttpClient.PostAsync?	string uri = "http://myserver.com/" + Uri.EscapeDataString(userSuppliedName) + "/dosomething/";\nclient.PostAsync(uri, someObject, formatter);	0
6537059	6309174	Programmatically export Excel files to XML using xmlMaps	Application app = new Application();\napp.Workbooks.Open(@"C:\Sample.xlsx",\n                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n                   Type.Missing, Type.Missing);\nstring data = string.Empty;\napp.ActiveWorkbook.XmlMaps[1].ExportXml(out data);\napp.Workbooks.Close();	0
14360471	14360294	How to iterate through DataTable cells	DataTable dt1 = new DataTable(), dt2 = new DataTable();\n\n    // define and populate your tables\n\n    int count1 = dt1.Columns.Count * dt1.Rows.Count;\n    int count2 = dt2.Columns.Count * dt2.Rows.Count;\n\n    bool verified = count1 == count2;	0
15378697	15378551	How to bind connection string to my SqlDataSource	string connectionString = WebConfigurationManager.ConnectionStrings["sb_cpdConnectionString"].ConnectionString;\nds.ConnectionString = connectionString;	0
27781921	27781875	Create method with generic parameters	public void InsertIntoBaseElemList<T>(ref List<T> List, T Element)\n where T : BaseElem	0
12119954	12119863	How to delete a particular instance of FileSystemWatcher object	Dictionary<string, FileSystemWatcher>	0
20135587	20135369	C# .net Writing Content from POST Request as PDF Producing blank PDF	using (var reqStream = req.GetRequestStream()) \n{    \n  // reqStream.Write( ... ) // write the bytes of the file\n  // or stream.CopyTo(writeStream);\n}	0
32891496	32889284	Django server returns 403 Forbidden while logging in via C#	X-CSRFToken:<csrftoken cookie value>	0
11162912	11162567	how to show hidden div from codebehind c#	divGrid.Visible = true;	0
23876208	23876133	Send SMS in Windows Phone 7 or 8 C# application	How can compose messages without using launcher	0
8943311	8943244	Copy Selected Area's text to clipboard	Clipboard.GetText()	0
9788126	9788100	Remove all non-numeric characters except spaces	Regex.Replace(foo, "[^.0-9\\s]", "")	0
11362459	11361964	String.Split with specific tags	string input = String.Concat("<root>", @"<p></p><table><table><p></p></table></table>", "</root>");\n\n        XDocument doc = XDocument.Parse(input);\n        var valuesStr = doc.Root.Element("table").ToString();\n        string[] values = Regex.Matches(valuesStr, @"<.+?>")\n            .Cast<Match>()\n            .Select(o => o.Groups[0].Value)\n            .ToArray();	0
19619203	19611695	ActionResult update db for an dynamic list in MVC4	public ActionResult Create()\n    {\n        return View();\n    }\n\n    //\n    // POST: /booking/Create\n\n    [HttpPost]\n    [ValidateAntiForgeryToken]\n    public ActionResult Create(booking booking)\n    {\n        if (ModelState.IsValid)\n        {\n            db.bookings.Add(booking);\n            db.SaveChanges();\n        }\n\n        return View(booking);\n    }	0
1091376	1091359	C# Can't get String to DateTime conversion to work	DateTime lastupdate = DateTime.ParseExact(date, "ddd MMM dd, yyyy h:mm tt", new System.Globalization.CultureInfo("en-us"));	0
26637299	26637031	Pulling Column count and header text with auto generated columns in a gridview	GridViewRow headerRow = gv.HeaderRow; \nint count = headerRow.Cells.Count	0
13729123	13728895	Simpler way to overload a method for a variable with multiple types?	private interface ICalculator<T>\n    {\n        T Add(T x, T y);\n        // you may want to add more operations here\n    }\n\n    private class Int32Calculator: ICalculator<int>\n    {\n        public int Add(int x, int y)\n        {\n            return x + y;\n        }\n    }\n\n    private int Int32SomeFunction(int [][,] d)\n    {\n        return SomeFunction<int>(d, new Int32Calculator());\n    }\n\n    private T SomeFunction<T>(T[][,] d, ICalculator<T> calculator)\n        where T : struct \n    {\n        T sum = default(T);\n        for (int k = 0; k < d.GetLength(0); k++)\n            for (int j = 0; j < d[0].GetLength(1); j++)\n                for (int i = 0; i < d[0].GetLength(0); i++)\n                    sum = calculator.Add(sum, d[k][i, j]);\n        return sum;\n    }	0
22420792	22420503	Add Row Dynamically in TableLayoutPanel	// TableLayoutPanel Initialization\nTableLayoutPanel panel = new TableLayoutPanel();\npanel.ColumnCount = 3;\npanel.RowCount = 1;\npanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));\npanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));\npanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));\npanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));\npanel.Controls.Add(new Label() { Text = "Address" }, 1, 0);\npanel.Controls.Add(new Label() { Text = "Contact No" }, 2, 0);\npanel.Controls.Add(new Label() { Text = "Email ID" }, 3, 0);\n\n// For Add New Row (Loop this code for add multiple rows)\npanel.RowCount = panel.RowCount + 1;\npanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));\npanel.Controls.Add(new Label() { Text = "Street, City, State" }, 1, panel.RowCount-1);\npanel.Controls.Add(new Label() { Text = "888888888888" }, 2, panel.RowCount-1);\npanel.Controls.Add(new Label() { Text = "xxxxxxx@gmail.com" }, 3, panel.RowCount-1);	0
1672233	1672206	how to add 2 column value of table field in dropdown	for (int count = 0; count < dtitem.Rows.Count; count++)\n    {\n        dtitem.Rows[count]["name"] = dtitem.Rows[count]["name"].tostring() + "-" + dtitem.Rows[count]["tagname"].tostring();\n    }	0
28744260	28740755	How to bring WPF window to the front of TeamViewer dialog	TopMost = true	0
973332	973325	C# Displaying a image in a form that is non-blocking to the rest of my code	ImageClass MyImage = new ImageClass();\nMyImage.DisplayImage(@"C:\SomeImage.jpg");\nThreadPool.QueueUserWorkItem(new WaitCallback(new delegate(object o) {\n    Console.Writeline("This is the line after displaying the image");\n}));	0
2102355	2101986	save string array in binary format	//Source string\n        string value1 = "t";\n        //Length in bits\n        int length1 = 2;\n        //Convert the text to an array of ASCII bytes\n        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(value1);\n        //Create a temp BitArray from the bytes\n        System.Collections.BitArray tempBits = new System.Collections.BitArray(bytes);\n        //Create the output BitArray setting the maximum length\n        System.Collections.BitArray bitValue1 = new System.Collections.BitArray(length1);\n        //Loop through the temp array\n        for(int i=0;i<tempBits.Length;i++)\n        {\n            //If we're outside of the range of the output array exit\n            if (i >= length1) break;\n            //Otherwise copy the value from the temp to the output\n            bitValue1.Set(i, tempBits.Get(i));                \n        }	0
13922243	13922161	Is there some way to open a new connection that does not take part in the current TransactionScope?	using (var scope = new TransactionScope(TransactionScopeOption.Suppress))\n{\n    // Execute your command here\n}	0
20728190	20728103	Remove comment block <!-- --> from string in C#	myString = Regex.Replace(myString , @"(?s)(?<=<!--).+?(?=-->)", "")	0
434953	434897	ReSharper syntax suggestion	if (readOnlyFields.Contains(propertyName)) return false;\nelse return base.CanWriteProperty(propertyName);	0
17230400	17230360	Hot tow how the usage of a variable or method in Visual Studio 2012 (C Sharp)?	SHIFT + F12	0
13489548	13489115	How do I autoformat excel cells that contains both strings and numbers?	public object MyUDF(string TopicID, string TopicName)\n{\n    var value = _xlApp.WorksheetFunction.RTD("my_rtdserver", null, TopicID, TopicName);\n    double num;\n    if (!double.TryParse(value, out num))\n        return value;\n    return num;\n}	0
9037535	9036848	Reading XML node from C# when it's a resource in XAML	static string GetAppath(string xmlString, string picPath)\n    {\n        string appath = String.Empty;\n        XmlDocument xDoc = new XmlDocument();\n        xDoc.LoadXml(xmlString);\n\n        XmlNodeList xList = xDoc.SelectNodes("/picture");\n        foreach (XmlNode xNode in xList)\n        {\n            if (xNode["path"].InnerText == picPath)\n            {\n                appath = xNode["appath"].InnerText;\n                break;\n            }\n        }\n        return appath;\n    }	0
9526392	9526359	C# equivalent of fprintf	public void Log(String message, params object[] args)\n{\n    DateTime datet = DateTime.Now;\n    if (sw == null)\n    {\n        sw = new StreamWriter(strPathName, true);\n    }\n    sw.Write(String.Format(message,args));\n    sw.Flush();\n}	0
22847325	22846826	DataService how do you pass LONG	public TransactionCartItem GetTransactionCartItemByTransactionNumber(long transactionNumber)\n{   \n    var query =\n        this.ClientRepositories\n            .Context\n            .CreateQuery<TransactionCartItem>("GetTransactionCartItemByTransactionNumber")\n            .AddQueryOption("transactionNumber", transactionNumber + "L")\n            .FirstOrDefault();\n\n    return query;\n}	0
20760794	20760681	LINQ join two DataTables	var result = from dataRows1 in table1.AsEnumerable()\n             join dataRows2 in table2.AsEnumerable()\n             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into lj\n             from r in lj.DefaultIfEmpty()\n             select dtResult.LoadDataRow(new object[]\n             {\n                dataRows1.Field<string>("ID"),\n                dataRows1.Field<string>("name"),\n                r == null ? 0 : r.Field<int>("stock")\n              }, false);	0
18652530	18647657	aspx file cannot be found in project folder	Dynamic Data	0
3604571	3604327	How Can I Parse a Number Equivalent to DateTime.TryParseExact?	public static bool TryParseExact(string text, string format, out double value)\n{\n    if (double.TryParse(text, out value))\n    {\n        // basically, make sure that formatting the result according to the\n        // specified format ends up providing the same value passed in\n        return text == value.ToString(format);\n    }\n\n    return false;\n}	0
13377190	13339433	Retrieve data from Mysql to excel macro, Asp.net c#	Sub ADOExcelSQLServer() \n  Dim Cn As ADODB.Connection \n  Dim Server_Name As String \n  Dim Database_Name As String \n  Dim User_ID As String \n  Dim Password As String \n  Dim SQLStr As String \n  Dim rs As ADODB.Recordset \n  Set rs = New ADODB.Recordset \n\nServer_Name = "" ' Enter your server name here\nDatabase_Name = "" ' Enter your database name here\nUser_ID = "" ' enter your user ID here\nPassword = "" ' Enter your password here\nSQLStr = "select Period, Secured, Unsecured from cmisa.credit_facts" \n\nSet Cn = New ADODB.Connection \nCn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _ \n";Uid=" & User_ID & ";Pwd=" & Password & ";" \n\nrs.Open SQLStr, Cn, adOpenStatic \n ' Dump to spreadsheet\nWith Worksheets("1.Overview").Range("AI7:AK19") ' Enter your sheet name and range here\n    .ClearContents \n    .CopyFromRecordset rs \nEnd With \n ' Tidy up\nrs.Close \nSet rs = Nothing \nCn.Close \nSet Cn = Nothing	0
4035739	4035599	How do I pass an Array (By Reference, in VB6) to a C\C++ *.dll subroutine?	Dim returnVal\nDim outArgs(1)\nDim args(1)\nargs(0) = 3\nreturnVal = service.InvokeAction("GetTrackInfo", args, outArgs)\n'return Val now contains the track length\n'and outArgs(0) contains the track title\nDim emptyArgs(0)\nreturnVal = service.InvokeAction("Play", emptyArgs, emptyArgs)\n'returnVal indicates if the action was successful	0
14441967	14439355	Translating screen location to isometric tile location with scaling	Vector2 TranslationVectorFromScreen(Vector2 toTranslate)\n    {\n        Vector2 output = new Vector2();\n        Vector2 tempOffset = offset; // copy of the main screen offset as we are going to modify this\n\n        toTranslate.X -= GraphicsDevice.Viewport.Width / 2;\n        toTranslate.Y -= GraphicsDevice.Viewport.Height / 2;\n        tempOffset.X /= tileBy2;\n        tempOffset.Y /= tileBy4;\n\n        toTranslate.X /= tileBy2 * scale;\n        toTranslate.Y /= tileBy4 * scale;\n\n        toTranslate -= tempOffset;\n\n        output.X = (toTranslate.X + toTranslate.Y) / 2;\n        output.Y = (toTranslate.X - toTranslate.Y) / 2;\n\n        output += new Vector2(-1.5f, 1.5f); // Normaliser - not too sure why this is needed\n\n        output.X = (int)output.X; // rip out the data that we might not need\n        output.Y = (int)output.Y; // \n\n        return output;\n    }	0
21610841	21610784	nullable decimal from SqlDataReader	decimal? d= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"];	0
18576112	18575842	Avoid include duplication in EF	private IQueryable<Car> getCommonQuery()\n{\n            DataContext.AsQueryableFor<RTraining>()\n            .Include(rb => rb.Car.CarStatus)\n            .Include(rb => rb.Car.Item.Customer)\n            .Include(rb => rb.Car.Item.MyItem.Wheel.Customer);\n}\n\npublic Car GetCarByChildEntityId(long id)\n{\n     return executeQuery(getCommonQuery()).SingleOrDefault(rb => rb.Id == id).Car;\n}\n\npublic IEnumerable<IEntity> GetEntities()\n{\n     return executeQuery(getCommonQuery()).OfType<IEntity>();\n}	0
27274061	27273907	JavaScript for generate table row	var cell1 = row.insertCell(0);
\nvar element1 = document.createElement("input");
\nelement1.id = 'your_id';
\ncell1.appendChild(element1);	0
806447	806095	How do I serialize an object into an XDocument?	XDocument doc = new XDocument();\nusing (var writer = doc.CreateWriter())\n{\n    // write xml into the writer\n    var serializer = new DataContractSerializer(objectToSerialize.GetType());\n    serializer.WriteObject(writer, objectToSerialize);\n}\nConsole.WriteLine(doc.ToString());	0
1600990	1600962	Displaying the build date	private DateTime RetrieveLinkerTimestamp()\n{\n    string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;\n    const int c_PeHeaderOffset = 60;\n    const int c_LinkerTimestampOffset = 8;\n    byte[] b = new byte[2048];\n    System.IO.Stream s = null;\n\n    try\n    {\n        s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);\n        s.Read(b, 0, 2048);\n    }\n    finally\n    {\n        if (s != null)\n        {\n            s.Close();\n        }\n    }\n\n    int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);\n    int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);\n    DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n    dt = dt.AddSeconds(secondsSince1970);\n    dt = dt.ToLocalTime();\n    return dt;\n}	0
4536117	4535193	WebImage Crop To Square	private static void CropImage (HttpPostedFileBase sourceImage) {\n  var newImage = new WebImage(sourceImage.InputStream);\n\n  var width = newImage.Width;\n  var height = newImage.Height;\n\n  if (width > height) {\n    var leftRightCrop = (width - height) / 2;\n    newImage.Crop(0, leftRightCrop, 0, leftRightCrop);\n  }\n  else if (height > width) {\n    var topBottomCrop = (height - width) / 2;\n    newImage.Crop(topBottomCrop, 0, topBottomCrop, 0);\n  }\n\n  //do something with cropped image...\n  //newImage.GetBytes();\n}	0
22942216	22731236	How to force Castle.DynamicProxy to ignore changing versions of dependencies	public virtual ObjectTypeFromThirdPartySignedAssembly PropertyName { get; set; }\n\npublic virtual ObjectTypeFromThirdPartySignedAssembly MethodName()\n{\n}\n\npublic virtual void Method2(ObjectTypeFromThirdPartySignedAssembly inputObject)\n{\n}	0
11200531	11200243	How to create a custom HTML Helper method DropDownFor in ASP.Net MVC	TProperty val = expression.Compile().Invoke(htmlHelper.ViewData.Model);\nSelectListItem selectedItem = selectList.Where(item => item.Value == Convert.ToString(val)).FirstOrDefault();\nstring text = "";\nif (selectedItem != null) text = selectedItem.Text;\n\nreturn !enabled ? new MvcHtmlString("<span>" + text + "</span>")\n      : htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);	0
9479222	9428587	Only horizontal scrolling in a panel	protected override void WndProc(ref System.Windows.Forms.Message m)\n    {\n        ShowScrollBar(this.Handle, 1, false);\n        base.WndProc(ref m);\n    }\n\n    [DllImport("user32.dll")]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    private static extern bool ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);	0
5988868	5988850	DateTime format string	string formattedDate = date.ToString("yyyyMMdd HH:mm:ss");	0
22484172	22484127	Compare a string to multiple strings	if (stringCollection.All(s => s == string1) )	0
12511705	12509992	How can I set ClientCredentials?	_client.ClientCredentials.Windows.ClientCredential.Domain = "warzone42";\n_client.ClientCredentials.Windows.ClientCredential.UserName = "user1428798";\n_client.ClientCredentials.Windows.ClientCredential.Password = "p@ssw0rd";	0
14203721	14203636	Given a list of Date ranges, how I do verify that all the days in a date range are covered in the list?	01/01/2012 - 03/31/2012\n05/01/2012 - 07/01/2012\n07/02/2012 - 09/05/2012\n09/06/2012 - 12/31/2012	0
6074389	6074363	How do I format a timespan to show me total hours?	String timeStamp = "40:00:00";\nvar segments = timeStamp.Split(':');\n\nTimeSpan t = new TimeSpan(0, Convert.ToInt32(segments[0]), \n               Convert.ToInt32(segments[1]), Convert.ToInt32(segments[2]));\nstring time = string.Format("{0}:{1}:{2}", \n           ((int) t.TotalHours), t.Minutes, t.Seconds);	0
10381907	10381810	Get the n digit binary representation of a number	string str = Convert.ToString(8, 2).PadLeft(5, '0');	0
16598444	16597920	How to convert binary string to bytes[] array?	System.Text.Encoding	0
20470458	20470346	Get node property of XmlDocument in C#	string x = item.Attributes["title"].Value;	0
92105	92008	Programmatically setting the record pointer in a C# DataGridView	dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];	0
5640990	5640338	Asserting an exception thrown from a mock object constructor	using System;\nusing System.IO;\n\nnamespace fileFotFoundException {\n    public abstract class MyFile {\n\n        protected MyFile(String fullPathToFile) {\n            if (!File.Exists(fullPathToFile)) throw new FileNotFoundException();\n        }\n    }\n}\n\nnamespace fileFotFoundExceptionTests {\n    using fileFotFoundException;\n    using NUnit.Framework;\n\n    public class SubClass : MyFile {\n        public SubClass(String fullPathToFile) : base(fullPathToFile) {\n            // If we have to have it as an abstract class...\n        }\n    }\n\n    [TestFixture]\n    public class MyFileTests {\n\n        [Test]\n        public void MyFile_CreationWithNonexistingPath_ExceptionThrown() {\n            const string nonExistingPath = "C:\\does\\not\\exist\\file.ext";\n\n            Assert.Throws<FileNotFoundException>(() => new SubClass(nonExistingPath));\n        }\n    }\n}	0
11722006	11721807	I want to show the image in the Access column but failed to access	//Build Column\nDataColumn column = new DataColumn("MyImage"); \ncolumn.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.\ncolumn.AllowDBNull = true;\ncolumn.Caption = "My Image";\n\n//Add Column\nyourDataTable.Columns.Add(column); \n\n//Build row\nDataRow row = table.NewRow();\nrow["MyImage"] = <Image byte array>;\nyourDataTable.Rows.Add(row);	0
20024774	20006390	copy ROI from one image and copy to on another image in wpf	private BitmapSource CopyRegion(\n    BitmapSource sourceBitmap, Int32Rect sourceRect,\n    BitmapSource targetBitmap, int targetX, int targetY)\n{\n    if (sourceBitmap.Format != targetBitmap.Format)\n    {\n        throw new ArgumentException(\n            "Source and target bitmap must have the same PixelFormat.");\n    }\n\n    var bytesPerPixel = (sourceBitmap.Format.BitsPerPixel + 7) / 8;\n    var stride = bytesPerPixel * sourceRect.Width;\n    var pixelBuffer = new byte[stride * sourceRect.Height];\n    sourceBitmap.CopyPixels(sourceRect, pixelBuffer, stride, 0);\n\n    var outputBitmap = new WriteableBitmap(targetBitmap);\n    sourceRect.X = targetX;\n    sourceRect.Y = targetY;\n    outputBitmap.WritePixels(sourceRect, pixelBuffer, stride, 0);\n\n    return outputBitmap;\n}	0
29702100	29636910	Possible to ignore the initial value for a ReactiveObject?	this.WhenAnyValue( model => model.Field ).Skip( 1 )	0
8883351	8882874	Parse date string from xml feed to DateTime	public static class Extensions\n{\n    public static DateTime ParseTwitterDateTime(this string date)\n    {\n        const string format = "ddd MMM dd HH:mm:ss zzzz yyyy";\n        return  DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);\n    }\n\n    public static DateTime ParseFacebookDateTime(this string date)\n    {\n        const string format = "ddd, dd MMM yyyy HH:mm:ss zzzz";\n        return  DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);\n    }\n}	0
24302064	24299839	store specific datatable data to hiddenfield in asp.net	for (int i = 0; i < SomeDetails.Rows.Count; i++)\n        {\n            string row = "";\n            for (int j = 0; j < SomeDetails.Columns.Count; j++)\n            {\n                row += SomeDetails.Rows[i][SomeDetails.Columns[j].ColumnName].ToString() + " - ";\n            }\n            System.Diagnostics.Debug.WriteLine(row);\n        }	0
21902585	21901781	Gridview show controls (labels, buttons, textfields) even if Datasource is null	if (GridView1.DataSource == null)\n    {\n            DataTable dt = new DataTable();\n            dt.Columns.Add("Name");\n            DataRow dr = dt.NewRow();\n            dr[0] = "";\n            dt.Rows.Add(dr);\n            GridView1.DataSource=dt;\n            GridView1.DataBind();\n    }	0
32631636	32631499	How to fix unreachable code dedected warning	for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())\n            {\n                if (r.NamespaceURI != DbmlNamespace)\n                    r.Skip();\n                else\n                    throw UnexpectedItemError(r);\n            }	0
2633340	2633278	How can I end a property with a question mark in C#?	int a;\nbool b?;\na = b? ? 15 : 22;	0
18854178	18853380	Dictionary with priorities	public void PriorityUp(Item it)\n{\n    if (DecreasePriority(it))\n    {\n        IncreaseOther(it.Priority, new[] { it });\n    }\n}\n\npublic void PriorityUp(IEnumerable<Item> items)\n{\n    List<int> toDecrease = new List<int>();\n    foreach (var item in items)\n    {\n        if (DecreasePriority(item))\n        {\n            toDecrease.Add(item.Priority);\n        }\n    }\n\n    foreach(var p in toDecrease)\n    {\n        IncreaseOther(p, items);\n    }\n}\n\nprivate bool DecreasePriority(Item it)\n{\n    if(it.Priority <= 1)\n    {\n        return false;\n    }\n\n    it.Priority--;\n\n    return true;\n}\n\nprivate void IncreaseOther(int priority, IEnumerable<Item> toIgnore)\n{\n    foreach (var item in allItems.Values.Except(toIgnore))\n    {\n        if (item.Priority == priority)\n        {\n            item.Value.Priority++;\n        }\n    }\n}	0
14623296	14623154	C# Interfaces implementation	public Service()\n        : base(new DAL.Repository())\n    {\n           rep = (Repository)base.repository;\n\n    }	0
13602785	11576886	How to convert object to Dictionary<TKey, TValue> in C#?	public static KeyValuePair<object, object > Cast<K, V>(this KeyValuePair<K, V> kvp)\n    {\n        return new KeyValuePair<object, object>(kvp.Key, kvp.Value);\n    }\n\n    public static KeyValuePair<T, V> CastFrom<T, V>(Object obj)\n    {\n        return (KeyValuePair<T, V>) obj;\n    }\n\n    public static KeyValuePair<object , object > CastFrom(Object obj)\n    {\n        var type = obj.GetType();\n        if (type.IsGenericType)\n        {\n            if (type == typeof (KeyValuePair<,>))\n            {\n                var key = type.GetProperty("Key");\n                var value = type.GetProperty("Value");\n                var keyObj = key.GetValue(obj, null);\n                var valueObj = value.GetValue(obj, null);\n                return new KeyValuePair<object, object>(keyObj, valueObj);\n            }\n        }\n        throw new ArgumentException(" ### -> public static KeyValuePair<object , object > CastFrom(Object obj) : Error : obj argument must be KeyValuePair<,>");\n    }	0
26632966	26632874	Range Validator validate that date selected was within the past 3 days	rvTxtTransactionDateFrom.MinimumValue = DateTime.Today.AddDays(-3).ToString("MM/dd/yy");\nrvTxtTransactionDateFrom.MaximumValue = DateTime.Today.ToString("MM/dd/yy");	0
5005710	5005690	Creating graphics from scratch and returning them to print a page event	Bitmap img = new Bitmap(50, 50);\nGraphics g = Graphics.FromImage(img);	0
21742439	21742069	WinForms Setting A label Forecolour when the next TextBox Control is focused	public Form1() {\n  InitializeComponent();\n\n  textBox1.Enter += LabelFocus;\n  textBox2.Enter += LabelFocus;\n  textBox3.Enter += LabelFocus;\n}\n\nvoid LabelFocus(object sender, EventArgs e) {\n  TextBox tb = sender as TextBox;\n  if (tb != null) {\n    foreach (Label lbl in panel1.Controls.OfType<Label>()) {\n      if (lbl.TabIndex == (tb.TabIndex - 1)) {\n        lbl.ForeColor = Color.White;\n      } else {\n        lbl.ForeColor = Color.IndianRed;\n      }\n    }\n  }\n}	0
21102761	21100659	How to extract that string with HTMLAgilityPack?	private string getTextfrom()\n{\n    HtmlDocument doc = new HtmlDocument();\n    //doc.LoadHtml("<span itemprop=\"price\" content=\"164,06\"></span>");\n    string htmlContent = GetPageContent("http://pastebin.com/raw.php?i=zE31NWtU");\n    doc.LoadHtml(htmlContent);\n\n    HtmlNode priceNode = doc.DocumentNode.SelectNodes("//span")[0];\n    HtmlAttribute valueAttribute = priceNode.Attributes["content"];\n    return valueAttribute.Value;\n}\n\npublic static String GetPageContent(string Url)\n{\n\n    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);\n    myRequest.Method = "GET";\n    WebResponse myResponse = myRequest.GetResponse();\n    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);\n    string result = sr.ReadToEnd();\n    sr.Close();\n    myResponse.Close();\n\n    return result;\n}	0
12502673	12500266	Best way to validate data before inserting	CustomerValidator validator = new CustomerValidator();\nValidationResult results = validator.Validate(customerToInsert);\nif(results.IsValid){\n    using (var con = new SqlConnection(ConnectionString.GetWebTablesConnectionString()))\n        using (var cmd = new SqlCommand("InsertNewCustomer", con))\n        {\n            //Do the actual insert / SP call here, your object is valid\n        }\n    }\n}	0
10658340	10658042	Client credentials to get TOKEN of Facebook	grant_type=client_credentials	0
11035853	11035243	Crystal Reports printing from remote database - WPF	CrystalReportSource1.CacheDuration = 6000	0
13364472	13364333	Multiple Input fields of file type on a single view	if (file.ContentType.Contains("image"))\n{\n    var isImage = true;\n}	0
15476529	15379910	How to check parent folder	string webPath = @"C:\blabla\CS_Web\website\";\nstring servicePath = @"C:\blabla\CS_Web\SPM\Server.asmx";\n\nif(Path.GetDirectory(Path.GetDirectoryName(servicePath))==Path.GetDirectoryName(webPath)\n{\n   //You do something here\n}	0
11744272	11743809	How can a border be set around multiple cells in excel using C#	.Borders[Excel.XlBordersIndex.xlEdgeBottom] \n.Borders[Excel.XlBordersIndex.xlEdgeRight]\n.Borders[Excel.XlBordersIndex.xlEdgeLeft]  \n.Borders[Excel.XlBordersIndex.xlEdgeTop]	0
24766222	24765384	ASP.Net C# - Access dynamically generated List controls	CheckBoxList cblAnswers = new CheckBoxList();\ncblAnswers.ID = "cblAnswers";\nPage.Form.Controls.Add(cblAnswers);\n\nRadioButtonList rblAnswers = new RadioButtonList();\nrblAnswers.ID = "rblAnswers";\nPage.Form.Controls.Add(rblAnswers);	0
23517452	23516912	How to query directshow interface in directshow.net?	[ComImport, System.Security.SuppressUnmanagedCodeSecurity,\nGuid("6B652FFF-11FE-4fce-92AD-0266B5D7C78F"),\nInterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface ISampleGrabber\n{\n    [PreserveSig]\n    int SetOneShot(\n        [In, MarshalAs(UnmanagedType.Bool)] bool OneShot);\n\n    [PreserveSig]\n    int SetMediaType(\n        [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt);	0
2080064	2080058	Running an .exe from a website	System.Diagnostics.Process process;\n\nvar startInfo = New System.Diagnostics.ProcessStartInfo("C:\file.exe")\n\nprocess.StartInfo = startInfo;\nprocess.Start();\nprocess.WaitForExit();	0
5340099	5340077	minimize length of string in C#	string foo ="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in vehicula nulla. Phasellus libero dui, luctus quis bibendum sit amet";\n\nstring small_foo = foo.SubString(0, 50);	0
25991957	25991469	JSON passing as a null to a method argument	[HttpPost]\npublic ActionResult Test(TestClass data) {\n    RedirectIfSuccess();\n}\n\n\npublic class TestClass\n{\n    public string b { get; set; }\n    public string c { get; set; }\n    public TestSubClass d { get; set; }\n}\n\npublic class TestSubClass\n{\n    public int e { get; set; }\n}	0
4868093	4867901	Silverlight, getting ItemSource data from data template programaticlly	Border border = sender as Border;\nMyItemType item = border.DataContext as MyItemType;\nvar hourTime = item.hourTime;	0
6538014	6537813	Number of days in date range, excluding weekends and other dates, in C#	public static int DaysLeft(DateTime startDate, DateTime endDate, Boolean excludeWeekends, List<DateTime> excludeDates)\n    {\n        int count = 0;\n        for (DateTime index = startDate; index < endDate; index = index.AddDays(1))\n        {\n            if (excludeWeekends && index.DayOfWeek != DayOfWeek.Sunday && index.DayOfWeek != DayOfWeek.Saturday)\n            {\n                bool excluded = false; ;\n                for (int i = 0; i < excludeDates.Count; i++)\n                {\n                    if (index.Date.CompareTo(excludeDates[i].Date) == 0)\n                    {\n                        excluded = true;\n                        break;\n                    }\n                }\n\n                if (!excluded)\n                {\n                    count++;\n                }\n            }\n        }\n\n        return count;\n    }	0
13743414	13742975	Write text file and open at same time	FileStream currentFileStream = null;//EDIT\nstring tempFilePath = Directory.GetCurrentDirectory() + "\\TEMP.txt";\n\nif (!File.Exists(tempFilePath))\n{\n    currentFileStream = File.Create(tempFilePath);//creates temp text file\n    currentFileStream.Close();//frees the file for editing/reading\n}//if file does not already exist\n\nFile.WriteAllText(tempFilePath, textbox1.Text);//overwrites all text in temp file\n\n//Inside your exit function:\nif(File.Exists(tempFilePath)) File.Delete(tempFilePath);//delete temp file	0
3205740	3205608	How to Transform a LINQ Expression when you do not have one of the parameters when you define it	private Func<string, Expression<Func<Contact, bool>>> FilterDefinition =\n    val => c => c.CompanyName.Contains(val);\n\nprivate IQueryable<Contact> ApplyFilter(\n    IQueryable<Contact> contacts, string filterValue)\n{\n    Expression<Func<Contact, bool>> usableFilter = FilterDefinition(filterValue);\n\n    return contacts.Where(usableFilter);\n}	0
24837810	24837474	C# convert dates to Timestamp	var baseDate = new DateTime (1970, 01, 01);\n var toDate = new DateTime (2014, 07, 18);\n var numberOfSeconds = toDate.Subtract (baseDate).TotalSeconds;	0
23455272	23454812	Getting a web response timesout	response.Close();	0
11244778	11242651	XAML Cannot set value of property of base class from a different assembly	xmlns:b="clr-namespace:WpfApplication5;assembly=WpfApplication5"	0
27324437	27324436	How to use a JOIN SQL statement in ASP.NET using Access?	"SELECT SecurityInfo.QuestionNumber \nFROM [SecurityInfo] \nINNER JOIN [UserDetails] \nON SecurityInfo.ID = UserDetails.ID\nWHERE (((UserDetails.Email) = '" + email + "'));"	0
1831896	1831744	Unable to connect from remote machine	System.Net.IPAddress.Any	0
1439458	1439395	Expiring Singleton instance after period of time	public sealed class CategoryHandler\n{\n    private static CategoryHandler _instance = null;\n    private static DateTime _expiry = DateTime.MinValue;\n    private static readonly object _lock = new object();\n\n    private CategoryHandler() { }\n\n    public static bool HasExpired\n    {\n        get\n        {\n            lock (_lock) { return (_expiry < DateTime.Now); }\n        }\n    }\n\n    public static CategoryHandler Instance\n    {\n        get\n        {\n            lock (_lock)\n            {\n                if (HasExpired)\n                {\n                    // dispose and reconstruct _instance\n                    _expiry = DateTime.Now.AddMinutes(60);\n                }\n                return _instance;\n            }\n        }\n    }\n}	0
16864470	16864406	How do I pass a captured variable through a lamba expression as if it were uncaptured?	Random rnd = new Random();\n\nfor (Int32 taskIndex = 0; taskIndex < 10; taskIndex++)\n{\n    Int32 tempIndex = taskIndex;\n    _tasks.Add(String.Format("Task_{0}", tempIndex));\n    Progress.AddItem(_tasks[tempIndex]);\n\n    Int32 timeDelay = 5 + rnd.Next(10);\n\n    DispatcherTimer dispatcherTimer = new DispatcherTimer();\n    dispatcherTimer.Interval = TimeSpan.FromSeconds(timeDelay);\n    dispatcherTimer.Tick += (sndr, eArgs) =>\n    {\n        dispatcherTimer.Stop();\n        Progress.SetItemStatus(tempIndex, Status.Executing);\n    };\n    dispatcherTimer.Start();\n}	0
12124907	12124816	How to call datagrid sortification from a asp:button?	DataView myDataView = new DataView(mybll.GetItemsOrdered()); \nmyDataView.Sort = sortExpression + " DESC"; \nGridView.DataSource = myDataView; \nGridView.DataBind();	0
32906784	32906615	How can I add multiple params to a list in C#	Dictionary<int, string> dictionary = new Dictionary<int, string>();\ndictionary.Add(36, "hi");	0
16632864	16111282	MathNet Numerics Statistics Histogram	var v = DenseVector.Create(10, i => i+1);\n        Console.WriteLine(new Histogram(v, 5));	0
26849793	26849734	Is there some sort of algorithm to continue looping through an unknown amount of child members?	public void ProcessDrawingData(DrawingInstance instance)\n{\n     // Do processing\n     foreach (DrawingInstance d in ChildMembers)\n         ProcessDrawingData(d);\n}	0
16716611	16716494	C# parsing special Character with HttpWebResponse	tempString = Encoding.UTF8.GetString(buf, 0, count);	0
29094737	29094472	How to find closest point (point being (x,y), in a list of different points) to a given point?	public void generateFirstMap()\n{\n    int count = 0;\n    do\n    {\n        bool addPoint = true;\n        int randXpixels = Main.rand.Next(24, Main.screenWidth - 16);\n        int randYpixels = Main.rand.Next(27, Main.screenHeight - 27);\n        for (int a = 0; a < points.Count; a++)\n        {\n            int dX = randXpixels - points[a].X;\n            int dY = randYpixels - points[a].Y;\n            if (dX * dX + dY * dY < 200)\n            {\n                addPoint = false;\n                break;\n            }\n        }\n        if(addPoint)\n            points.Add(new Point(randXpixels,randYpixels));\n\n        count++;\n    } while (count < 100);\n}	0
4773137	4773068	Accessing current item from ListView data source	int index=0; // obtain the index of an item. \nTextBox num = (TextBox)ListView1.Items[index].FindControl("numTextBox");	0
23516052	23515908	Getting Values from nested Dictionary	Dictionary<string, string> heightAttr = MyDictionary["HEIGHT"];\nstring table  = heightAttr["table"];    //  TR_HEIGHT\nstring prefix = heightAttr["prefix"];   //  HEI	0
9708830	9606834	Cannot get any facebook permissions with C# facebook SDK 	var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);\noAuthClient.RedirectUri = new Uri("XXXXXXXXXXXXXX");\nvar loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", null }, { "scope", "user_about_me,user_relationships,email" } });\nreturn Redirect(loginUri.AbsoluteUri);	0
23104466	23104409	How to restrict the Operation method call in wcf if it fails in IParameterInspector BeforeCall method	public object BeforeCall(string operationName, object[] inputs)\n        {\n            if (UserAuthenticToken.IsValidUser())\n                return null;\n            else\n            {                    \n                throw new FaultException("User is not authenticated.");\n            }\n        }	0
19525007	19524531	aspx Create Wizard Control assign Role	Roles.CreateRole("Members");	0
13358403	13358011	Not able to access a value returned by function	public class CashFlowIndicator :IEnumerable\n{\n\n    static List<KeyValuePair<string, string>> chartValues;  // has been moved here from getCashFlowChartValues\n\n    public static void getCashFlowChartValues(int userid)\n    {\n            //List<KeyValuePair<string, string>> chartValues=new List<KeyValuePair<string,string>>();\n            chartValues = cashFlowChart(userid);\n    }    \n\n    public static List<KeyValuePair<string, string>> cashFlowChart(int userid)\n    {\n            //.............................\n            //..................................\n            var cashFlowItems = new List<KeyValuePair<string, string>>();\n\n            cashFlowItems.Add(new KeyValuePair<string, string>(a, b));\n            cashFlowItems.Add(new KeyValuePair<string, string>(c, d));\n        //.....................    \n\n            return cashFlowItems;\n    }    \n}	0
2270431	2270420	Finding <div> in html using C#	div[@id='idToFind']	0
17214074	17214008	Delete a file from database and file system	DbTransaction transaction = null;\nforeach (var report in reports)\n{\n    try\n    {\n        transaction = context.Connection.BeginTransaction();\n\n        context.ReportGenerations.DeleteObject(report);\n        context.SaveChanges();\n\n        string filePath = report.ReportPath;\n        if (File.Exists(filePath));\n        {\n            File.Delete(filePath);\n        }\n        transaction.Commit();\n    }\n    catch\n    {\n        transaction.Rollback();\n    }\n}	0
5177101	4499107	Programatically add and youtube video to wall post	var parameters = new Dictionary<string, object>();\n\n        parameters.Add("message", Commentary);\n        parameters.Add("link", Link);\n        if (!String.IsNullOrEmpty(ThumbnailImageUrl))\n            parameters.Add("picture", ThumbnailImageUrl);\n\n        try\n        {\n            _FacebookApp.Post("me/feed", parameters);\n        }\n        catch (Exception ex)\n        {\n            return ex.Message;\n        }	0
3000808	3000129	Fluent NHibernate - Mapping a dictionary of component/value type objects as a HasMany	Id(x => x.Id);\n        HasMany(x => x.Rates)\n            .AsMap(x => x.Type)\n            .KeyColumn("Item_Id")\n            .Table("InvoiceItem_Rates")\n            .Component(x =>\n                           {\n                               x.Map(r => r.Amount);\n                               x.Map(r => r.Quantity);\n                           })\n            .Cascade.AllDeleteOrphan();	0
14242921	14242759	How to rectify this exception in c#	using (var context = new NorthwindContext()) \n{\n    var query = context.Destinations.Where(i => i.Id >= 1).Select(i => new {\n                id = i.Id,\n              name = i.Destination\n    }).ToArray();\n }	0
4687102	4687093	From column when sending email	message.From = new MailAddress("support@website.com", "website.com support team");	0
9721577	9721512	Linq: Select from 2 datatable where column id from first table = column id from second table	var query =\n            from s in db.Student\n            from g in db.GeneralData\n            where s.id == g.id\n            select new\n            {\n                g.id,\n                g.name,\n                g.last_name\n            };	0
8991186	8990926	Faster contrast algorithm for a bitmap	byte contrast_lookup[256];\ndouble newValue = 0;\ndouble c = (100.0 + contrast) / 100.0;\n\nc *= c;\n\nfor (int i = 0; i < 256; i++)\n{\n    newValue = (double)i;\n    newValue /= 255.0;\n    newValue -= 0.5;\n    newValue *= c;\n    newValue += 0.5;\n    newValue *= 255;\n\n    if (newValue < 0)\n        newValue = 0;\n    if (newValue > 255)\n        newValue = 255;\n    contrast_lookup[i] = (byte)newValue;\n}\n\nfor (int i = 0; i < sourcePixels.Length; i++)\n{\n    destPixels[i] = contrast_lookup[sourcePixels[i]];\n}	0
34016878	33942321	how to declare and update my class in my .cshtml file	ValidateTaskViewModel model = new validateTaskViewModel();\n model.groupId = id;	0
3632870	3632860	How To loop the names in C#	TextBox boxes [] = new TextBox [] { TB1, TB2, TB3....}\n\nforeach (TextBox box in boxes) {\n}	0
24135792	24135675	How to change Application Culture in wpf?	CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");\nCultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-US");	0
6553385	6553125	Comparing two datasources in C#	dropDownList.DataSource.Except(query)	0
28110479	28110442	How to send a request with data using System.Net.HttpWebRequest	var url = "https://example.com/search?text=some+words&page=8";	0
19752088	19743830	Getting a class property from a data bound treeview on treeviewitem click	void HandleSelected(object sender, RoutedEventArgs e)\n    {\n        var tvi = e.Source as TreeViewItem;\n        var category = tvi.DataContext as Category;\n        ...\n    }	0
31689174	31688906	Cant show button text using a contextmenustrip item	Control ctrl;\n\nvoid MyContextMS_Opening(object sender, CancelEventArgs e) {\n  ctrl = ((ContextMenuStrip)sender).SourceControl;\n}\n\nprivate void SeeDetailsToolStripMenuItem_Click(object sender, EventArgs e) {\n  Button b = ctrl as Button;\n  if (b != null) {\n    MessageBox.Show(b.Text);\n  }\n}	0
8833208	8833076	How can I type one item at the time from ListBox items using Timer?	private int listBoxItemCounter = 0;\n\nprivate void Interval(object sender, EventArgs e)\n{\n   //setting interval\n\n   if(listBoxItemCounter<lbMessage.Items.Count) \n   {\n       SendKeys.Send(lbMessage.Items[listBoxItemCounter].ToString()+"{enter}");\n       listBoxItemCounter++; \n   }\n}	0
5546000	5545957	Need Regular Expression for path and file extension matching	[\w/]+(\.aspx(\?.+)?)?	0
4181246	4181182	C# Entity Framework: Narrow results with a field value	var query = from project in dataEntity.projects\n            where project.clientID = TARGET_ID\n            select project;\n\nlistBoxProjects.DataSource = query;	0
12279098	12279047	C#: Run application in debug mode	Trace.WriteLine("");	0
13572120	13572076	Elegant way of getting indexes of an array	(s, i) => new { i, s }	0
11852221	11851908	Highlight all searched word in richtextbox C#	static class Utility{\n    public static void HighlightText(this RichTextBox myRtb, string word, Color color){  \n\n       if (word == ""){\n            return;\n       }\n\n       int s_start = myRtb.SelectionStart, startIndex = 0, index;\n\n       while((index = myRtb.Text.IndexOf(word, startIndex)) != -1){\n           myRtb.Select(index, word.Length);\n           myRtb.SelectionColor = color;\n\n           startIndex = index + word.Length;\n       }\n\n       myRtb.SelectionStart = s_start;\n       myRtb.SelectionLength = 0;\n       myRtb.SelectionColor = Color.Black;\n    }\n}	0
16117965	16099531	UITypeEditor in PropertyGrid with multiselection	public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n{\n    object[] selectedValues = (object[])context.Instance;\n}	0
9348220	9257069	change sequence of columns of UltraWinGrid	Dictionary<int, string> gPos = new Dictionary<int,string>();\nDataTable dtCopy = (grid.DataSource as DataTable).Copy();\ndtCopy.PrimaryKey = null;\nforeach(UltraGridColumn gCol in grid.DisplayLayout.Bands[0].Columns)\n{\n    if(gCol.Hidden == true)\n        dtCopy.Columns.Remove(gCol.Key);\n    else\n      gPos.Add(gCol.Header.VisiblePosition, gCol.Key);\n}\nvar list = gPos.Keys.ToList();\nlist.Sort();\nint realPos = 0;\nforeach (var key in list)\n{\n    dtCopy.Columns[gPos[key]].SetOrdinal(realPos++);\n}	0
5937416	5876996	How set image to data grid view cell after data binding?	DataGridViewImageColumn ic= new DataGridViewImageColumn();\n  ic.HeaderText = "Img";\n  ic.Image = null;\n  ic.Name = "cImg";\n  ic.Width = 100;\n  DGV.Columns.Add(ic);\n\n\n  foreach (DataGridViewRow row in DGV.Rows)\n  {\n    DataGridViewImageCell cell = row.Cells[1] as DataGridViewImageCell;\n    cell.Value = (System.Drawing.Image)Properties.Resources.Icon_delete;\n  }	0
22653991	22651987	How to Store command prompt output in a text file and then search a word in C#?	Process p = new Process();\n    p.StartInfo = new ProcessStartInfo(@"C:\Windows\System32\ipconfig.exe", "/all") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, RedirectStandardInput = true, CreateNoWindow = true };\n    p.Start();\n    //Store the output to a string\n    String Contents = p.StandardOutput.ReadToEnd();\n\n    String[] LineByLineString = Contents.Split('\n');//Split the string line by line\n    String line = null;\n    foreach (var item in LineByLineString)\n    {\n        if (item.ToString().Contains("Tunnel")) //Get the line which has the word "Tunnel" in it\n        {\n            line = item;\n            break;\n        }\n    }\n    Console.WriteLine(line);	0
8983492	8983464	Convert from string to byte strange behavior	public static class StringExtensions\n    {\n        public static byte[] ToByteArray(this string str)\n        {\n            char[] arr = str.ToCharArray();\n            byte[] byteArr = new byte[arr.Length];\n\n            for (int i=0; i<arr.Length; ++i)\n            {\n                switch (arr[i])\n                {\n                    case '0': byteArr[i] = 0; break;\n                    case '1': byteArr[i] = 1; break;\n                    default: throw new Exception(arr[i]+" is not 0 or 1.");\n                }\n            }\n\n            return byteArr;\n        }\n    }	0
13192759	13192624	How to Add child node in Treeview in Silverlight	var products = new TreeViewItem {Header = "Products"};\n    var mediaPlayers = new TreeViewItem() {Header = "Media Players"};\n    var charts = new TreeViewItem() { Header = "Charts" };\n    var games = new TreeViewItem() { Header = "Games" };\n\n    products.Items.Add(mediaPlayers);\n    mediaPlayers.Items.Add(games);\n    games.Items.Add(charts);\n\nMyTreeView1.Items.Add(products);	0
34523965	34523663	How do i search the Folder which is in D drive using C#	string dir = Directory.GetDirectories(@"D:\","App_data_payroll").FirstOrDefault();\nstring targetPath = "D:\CopyToFolder\";\n\nif (System.IO.Directory.Exists(dir))\n{\n    string[] files = System.IO.Directory.GetFiles(dir);\n\n    // Copy the files and overwrite destination files if they already exist.\n    foreach (string s in files)\n    {\n        var fileName = System.IO.Path.GetFileName(s);\n        var destFile = System.IO.Path.Combine(targetPath, fileName);\n        System.IO.File.Copy(s, destFile, true);\n    }\n}	0
7574298	7573884	Un-Nesting List Iterations for Performance	from segment in RoadwaySegments\njoin sample in IndividualSpeeds on new { segment.StartId, segment.EndId } equals new { sample.StartId, sample.EndId } into segmentSamples\nfrom startHour in Enumerable.Range(0, 24)\nfrom startMin in new[] { 0, 15, 30, 45 }\nlet startMinSamples = segmentSamples\n    .Where(sample => sample.Speed > 0)\n    .Where(sample => sample.StartHour == startHour)\n    .Where(sample => sample.StartMin == startMin)\n    .Select(sample => sample.Speed)\n    .ToList()\nselect new SummaryItem\n{\n    StartId = segment.StartId,\n    EndId = segment.EndId,\n    SummaryHour = startHour,\n    SummaryMin = minute,\n    AvgSpeed = startMinSamples.Count <= 2 ? 0 : startMinSamples.Average()\n};	0
665589	665573	Multidimensional Arrays in a struct in C#	unsafe struct Distort\n{\n     int a_order;\n     fixed double a[DISTMAX * DISTMAX];\n}	0
13398153	13397676	How to retrieve all datas from Listbox when selected item changed	lbTexts.ValueMember = "Id";\n\n// Later\nint selectedId = Int32.Parse(lbTexts.SelectedValue);	0
19018427	19017948	Newtonsoft JSON - arrays not serialized properly	foreach (var p in parameters)\n        {\n            if (p.GetType().IsGenericType && p is IEnumerable)\n            {\n                JArray l = new JArray();\n                foreach (var i in (IEnumerable)p)\n                {\n                    l.Add(i);\n                }\n                props.Add(l);\n            }\n            else\n            {\n                props.Add(p);\n            }\n        }	0
9437865	9437212	Sorting a Range object in VSTO	Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;\nEnumerable.Range(1, 20).ToList().ForEach(i => sheet.Cells[21 - i, 1] = i);\nsheet.Columns[1].Sort(sheet.Columns[1]);	0
9293768	9293509	How to get a Combo box to output into text boxes after item selection	List<Venue> Ven = new List<Venue>();\n\nprivate void cboVenue_SelectedIndexChanged(object sender, EventArgs e)\n{\n    try\n    {\n        txtVenue.Text = Ven[cboVenue.SelectedIndex].m_VenName;\n    }\n    catch\n    {\n    }\n}	0
4346401	4346047	Parse particular text from an XML string	var url = "http://www.xxxxxxxxxxxxxx.co.uk/map.aspx?isTrafficAlert=true&lat=53.647351&lon=-1.93350";\nvar items = url.Split('?')[1]\n    .Split('&')\n    .Select(i => i.Split('='))\n    .ToDictionary(o => o[0], o => o[1]);\nvar lon = items["lon"];\nvar lat = items["lat"];	0
11644099	11643993	How can I implement method<T>(T) from an interface	ISearchTechnology<T>	0
4281382	4281368	Find index of element C#	int monthnumber = Array.IndexOf(Months, "November") + 1;	0
615976	615940	Retrieving the calling method name from within a method	StackTrace stackTrace = new StackTrace();\nMethodBase methodBase = stackTrace.GetFrame(1).GetMethod();\nConsole.WriteLine(methodBase.Name); // e.g.	0
16364511	16364309	What's the most efficient way to access the value of a match?	[TestMethod]\n    public void GenericTest()\n    {\n        Regex r = new Regex(".def.");\n        Match mtch = r.Match("abcdefghijklmnopqrstuvwxyz", 0);\n        for (int i = 0; i < 1000000; i++)\n        {\n            string a = mtch.Value;                  // 15.4%\n            string b = mtch.ToString();             // 19.2%\n            string c = mtch.Groups[0].Value;        // 23.1%\n            string d = mtch.Groups[0].ToString();   // 38.5%\n        }\n    }	0
13741499	13591185	Set permissions for directory and child items	WindowsIdentity id = WindowsIdentity.GetCurrent();\nvar sid = new SecurityIdentifier(WellKnownSidType.AccountDomainUsersSid, id.User.AccountDomainSid);\nvar security = dir.GetAccessControl();\nvar rule = new FileSystemAccessRule(sid,\n    FileSystemRights.FullControl,\n    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n    PropagationFlags.None,\n    AccessControlType.Allow);\nsecurity.AddAccessRule(rule);\ndir.SetAccessControl(security);	0
439317	439302	Allowing a method to lock its parent Object in Java	synchronized (this)\n{\n}	0
6830177	6830127	publish on Facebook application page as an application using Facebook c# sdk	var fb = new FacebookOAuthClient(FacebookApplication.Current);\n            dynamic resultt = fb.GetApplicationAccessToken();\n            var appAccessToken = resultt.access_token;\n\n            dynamic messagePost = new ExpandoObject();\n            messagePost.access_token = appAccessToken;\n            messagePost.picture = "http://www.destination360.com/europe/sweden/images/s/sweden-visby.jpg";\n            messagePost.link = "http://www.destination360.com/europe/sweden/images/s/sweden-visby.jpg";\n            messagePost.name = "[SOME_NAME]";\n            messagePost.caption = "{*actor*} " + "[YOUR_MESSAGE]";\n            messagePost.description = "[SOME_DESCRIPTION]";\n            messagePost.from = AppId;\n            messagePost.to = "130736200342432";\n            FacebookClient appp = new FacebookClient(appAccessToken);\n            var result = appp.Post("/" + AppId + "/feed", messagePost);	0
8116963	8115574	How to hide an asp:Image contained within a Repeater if the image field in the database is set to null	RepeaterItem ri = e.Item;\n\nvar image = ri.FindControl("image") as Image;\nif (image != null){\n    bool isUrlValid = ....;// your check here\n    image.Visible = isUrlValid\n}	0
23468838	23468594	Reading all root node names in an XML document	var xml = XElement.Parse(xmlString);\nvar names=xml.Elements().Attributes(@"Name").Select(attrib => attrib.Value);	0
9828329	9828308	How can I do a Union all in Entity Framework LINQ To Entities?	var query = (from x in db.Table1 select new {A = x.A, B = x.B})\n    .Concat( from y in db.Table2 select new {A = y.A, B = y.B} );	0
31167881	31167840	Naming Worksheet With EPPlus	objWorksheet.Name = "abcd";	0
32481562	32479099	ElasticSearch.Net - Update array with multiple components	var peopleId = //Get Id of document to be updated.\nvar persons = new List<Person>(3);\npersons.Add(new Person { name = "john", eyes = "blue", age = "27" });\npersons.Add(new Person { name = "mary", eyes = "green", age = "19" });\npersons.Add(new Person { name = "jane", eyes = "grey", age = "30" });\n\nvar response = Client.Update<People, object>(u => u\n            .Id(peopleId)\n            .Doc(new { person = persons})\n            .Refresh()\n        );	0
14941122	14940920	Copy part of data from one table to another C#	using System.Data.SqlClient;\n\nnamespace ConsoleApplication\n{\n    internal class Program\n    {\n        private static void Main(string[] args)\n        {\n            using (var objConnection = new SqlConnection("Your Conneciton String"))\n            {\n                objConnection.Open();\n                using (var objCommand = new SqlCommand("INSERT INTO ExcellentStudent (Name, Class, Score) SELECT Name, Class, Score FROM Student WHERE Score > 90", objConnection))\n                {\n                    objCommand.ExecuteNonQuery();\n                }\n                objConnection.Close();\n            }\n        }\n    }\n}	0
17674743	17671389	Copying rewrite rules from a web.config to another	XmlDocument doc1 = new XmlDocument();\ndoc1.Load(@"web.new.config");\n\nXmlDocument doc2 = new XmlDocument();\ndoc2.Load(@"web.config");\n\nXmlNode rules = doc2.SelectSingleNode("/configuration/system.webServer/rewrite/rules");\nXmlNodeList baserules = doc2.SelectNodes("/configuration/system.webServer/rewrite/rules/rule[contains(@name, 'GenericPrefix')]");\n\nXmlNodeList ruleList = doc1.SelectNodes("/configuration/system.webServer/rewrite/rules/rule[contains(@name, 'GenericPrefix')]");\n\nforeach(XmlNode baseruleOld in baserules)\n{\n    baseruleOld.ParentNode.RemoveChild(baseruleOld);\n}\n\nforeach(XmlNode rule in ruleList)\n{\n    XmlNode tocopynode = doc2.ImportNode(rule, true);\n    rules.AppendChild(tocopynode);\n}\n\ndoc2.Save("web.config");	0
1536913	1536848	C# Add Icon To ToolStripMenuItem	SomeToolStripMenuItem.Image = Image.FromFile("c:\myicon.ico")	0
3115363	3115034	Storing number of dynamically inserted controls for postback	protected override void OnInit(EventArgs e)\n{\n    int i = 0;\n    i = Int32.Parse(hdnTestCount.Value);\n\n    if(Request.Params[hdnTestCount.UniqueID] != null)\n    {\n        i = Int32.Parse(Request.Params[hdnTestCount.UnitueID]);\n    }\n\n    for (int j = 1; j <= i; j++)\n    {\n         TextBox txtBox = new TextBox();\n         txtBox.ID = "Test" + j.ToString();\n         plhTest.Controls.Add(txtBox);\n    }\n}\n\nprotected void btnAdd_OnClick(object sender, EventArgs e)\n{\n    int i = 0;\n    i = Int32.Parse(hdnTestCount.Value) + 1;\n\n    TextBox txtBox = new TextBox();\n    txtBox.ID = "Test" + i.ToString();\n    plhTest.Controls.Add(txtBox);\n    hdnTestCount.Value = i.ToString();\n}	0
2763642	2763526	How to get latest files in C#	class Program\n{\n    static void Main()\n    {\n        var files =\n            from file in Directory.GetFiles(@"c:\somedirectory")\n            let name = Path.GetFileNameWithoutExtension(file)\n            let tokens = name.Split('_')\n            where tokens.Length > 1\n            let date = DateTime.ParseExact(tokens[1], "yyyyMMdd", CultureInfo.InvariantCulture)\n            orderby date descending\n            select file;\n\n        foreach (var item in files)\n        {\n            Console.WriteLine(item);\n        }\n    }\n}	0
5538410	5538274	Programatically instantiate and add controls to UpdatePanel	internal void CreateMainPanel()\n{\n    Panel main = new Panel(){CssClass="form"};\n    UpdatePanel All = new UpdatePanel();\n    All.ContentTemplateContainer.Controls.Add(main);\n    //form is a static panel reference which I use inside the class\n    form = main;\n}	0
14851260	14849690	ZXing to verify a text form barcode reader	var writer = new BarcodeWriter();\n        writer.Format = BarcodeFormat.CODE_128;\n        var options = new EncodingOptions();\n        options.Height = 140;\n        options.Width = 300;\n        writer.Options = options;\n\n        try\n        {\n            Bitmap image = writer.Write(textBoxCodigoDeBarras.Text);\n            BitmapImage bi = ImageManager.BitmapToImagesource(image);\n            ImageCodigoDeBarras.Source = bi;\n        }\n        catch\n        {\n            //Could not generate image.\n            //Therefone Barcode is invalid.\n        }	0
16370658	16370508	populate listbox from list of objects	private void btnViewAll_Click(object sender, EventArgs e)\n    {\n        listBox1.Items.Clear();\n        foreach (SalesmanDetails details in salesmanList)\n        {\n            listBox1.Items.Add(String.Format("{0} {1}",details.firstName,details.surname));\n        }\n    }  \n\n    private void listBox1_DoubleClick(object sender, EventArgs e)\n    {\n         int SalesmanDetailsIndex = listBox1.SelectedIndex;\n         SalesmanDetails selectedSalesman=salesmanList[SalesmanDetailsIndex];\n         MessageBox.Show(String.Format("{0} {1} email {2}",selectedSalesman.firstName,selectedSalesman.surname,selectedSalesman.email));\n    }	0
31282333	12930587	Customizing SQL with Dapper Extensions	var sql = "SELECT id,a,b,c FROM Foo WHERE Foo.id in (\n    SELECT foo_id FROM foo-bar WHERE bar-id=@bar_id)"\nusing (var cn = new SqlConnection(the_connection_string)) {\n  cn.Open();\n  var returnedObject = cn.Query<dynamic>(sql, new { bar_id = some_value });\n}	0
8917120	8917067	How to constantly scroll to the end of text in multiline text box?	yourtextbox.SelectionStart = yourtextbox.Text.Length\n yourtextbox.ScrollToCaret()	0
21586228	21586107	C# get position of a character from string	string aS = "ABCDEFGHI";\nchar ch = 'C';\nint idx = aS.IndexOf(ch);\nMessageBox.Show(string.Format("{0} is in position {1} and between {2} and {3}", ch.ToString(), idx + 1, aS[idx - 1], aS[idx + 1]));	0
14482383	14482307	Convert unicode characters with c#	StreamWriter swHTMLPage = \n                new System.IO.StreamWriter(OutputFileName, false, Encoding.UTF8);	0
16788502	16788301	Loading Data to a gridview	rowValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);	0
13527572	13518973	SignalR cross domain and IIS 7.5 path to hub only works locally on the server, how to access it externally?	string url = "http://*:8081/";\n\nm_signalrServer = new Microsoft.AspNet.SignalR.Hosting.Self.Server(url);	0
17299373	17292897	Nancy: How to render Html without a Context	Nancy.Viewengines.Razor	0
10085140	10071004	Delay function to postpone IObservable values dynamically	source\n  .SelectMany(i => Observable.Timer(GetAsymptotingTime()).Select(_=>i))	0
30030778	30030606	C#, selecting certain parts from string	var point = "POINT (6.5976512883340064 53.011505757047068)";\n\nvar indexOfFirstBrace = point.IndexOf('(') + 1;\nvar indexOfLastBrace = point.IndexOf(')');\nvar coordinates = point.Substring(indexOfFirstBrace, indexOfLastBrace - indexOfFirstBrace).Split(' ');\n\nvar xCoordinate = coordinates[0];\nvar yCoordinate = coordinates[1];	0
30145403	30145336	Saving methods in a dictionary and use those methods on key match.	class Program\n{\n    private static void Main(string[] args)\n    {\n        var methods = new Dictionary<string, Action>();\n        //choose your poison:\n        methods["M1"] = MethodOne; //method reference\n        methods["M2"] = () => Console.WriteLine("Two"); //lambda expression\n        methods["M3"] = delegate { Console.WriteLine("Three"); }; //anonymous method\n        //call `em\n        foreach (var method in methods)\n        {\n            method.Value();\n        }\n        //or like tis\n        methods["M1"]();\n    }\n\n    static void MethodOne()\n    {\n        Console.WriteLine("One");\n    }\n}	0
32486000	32485913	how to place text inside quotes	text = text.Replace("\"Call of Duty Tools\"", "\"" + name + "\"");	0
23851545	23841744	Gmail not receiving certain messages, are showing up in sent folder	using (var message = new MailMessage(fromAddress, toAddress)\n{\n    Subject = subject,\n    Body = body\n})\n{\n    smtp.Send(message);\n}	0
23291853	23291797	How to avoid that a string splits on every whitespace in command line	"This is a test file.dotx"	0
12798263	12798197	Use FileSystemWatcher on a single file in C#	watcher.Path = Path.GetDirectoryName(filePath1); \nwatcher.Filter = Path.GetFileName(filePath1);	0
2482873	2482134	Using C# to detect whether a filename character is considered international	public static string RemoveDiacriticals(string txt) {\n  string nfd = txt.Normalize(NormalizationForm.FormD);\n  StringBuilder retval = new StringBuilder(nfd.Length);\n  foreach (char ch in nfd) {\n    if (ch >= '\u0300' && ch <= '\u036f') continue;\n    if (ch >= '\u1dc0' && ch <= '\u1de6') continue;\n    if (ch >= '\ufe20' && ch <= '\ufe26') continue;\n    if (ch >= '\u20d0' && ch <= '\u20f0') continue;\n    retval.Append(ch);\n  }\n  return retval.ToString();\n}	0
4629996	4629865	WPF TabItem Name of Open File	tabItem.Header = new System.IO.FileInfo(filepath).Name;	0
25298643	25298601	How do I retrieve a Value from a KeyValuePair inside a List?	return shopInventory.First(c => c.Key == key).Value;	0
5135950	5135936	How to implement a Dictionary with two keys?	IDictionary<CustomClass, double>	0
25781643	25526356	Setting Callback URL and retrieve data using RestSharp	public void Post([FromBody]JToken value)\n            {\n                var path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data");\n\n                File.WriteAllText(path + @"/WriteJSON" + DateTime.Now.Ticks.ToString() + ".txt", value.ToString());\n\n                // write any code that you want to here\n\n            }	0
14686783	14686560	Read data from a HttpWebRequest asynchronously while downloading	webRequest.EndGetResponse(result);	0
12052853	12052610	convert string with dots to currency with euro,	decimal.Parse(inputString, CultureInfo.InvariantCulture)	0
32346226	32266150	Doing cryptography on Windows Phone	public IBuffer ComputeHash(string value)\n{\n    IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);\n    var objAlgProv = HashAlgorithmProvider.OpenAlgorithm("SHA256");\n    var strAlgNameUsed = objAlgProv.AlgorithmName;\n\n    var buffHash = objAlgProv.HashData(buffUtf8Msg);\n\n    if (buffHash.Length != objAlgProv.HashLength)\n    {\n        throw new Exception("There was an error creating the hash");\n    }\n\n    return buffHash;\n}	0
5004780	5004724	How do I dynamically point an interface to a specific class at runtime?	Type t = Type.GetType("DoWorkType1");\nIDoWork idw = (IDoWork)Activator.CreateInstance(t);\nidw.Process();	0
32870315	32870021	Writing several object values from a Arraylist to Console	foreach (var car in cars.Cast<Car>())\n{\n    Console.WriteLine(car.carBrand)\n}	0
22652633	22652547	Can I insert data to a column in 3 different tables?	string insertQuery = "insert into accounts (...) values (...); insert into othertable (...) values (...)"	0
3158568	3158555	How do I count number of characters after dot	num.Length - num.IndexOf(".")-1;	0
20784753	20784627	How to remove a specific ChangeSet in TFS 2010?	TF rollback /changeset:C543	0
13502982	13502896	Datatable data checking puzzle	using System.Linq;\n\nvar badRecords = collection.ToLookup(x => x.CodeNum).Where(y => y.Count() > 1);	0
29612206	29611412	WPF listview, how to get sum of items	public class SumConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, \n                          System.Globalization.CultureInfo culture)\n    {\n        double sum = 0.0;\n        Type valueType = value.GetType();\n\n        if(valueType.Name == typeof(List<>).Name)\n        {\n            foreach (var item in (IList)value)\n            {\n                Type itemType = item.GetType();                     \n                PropertyInfo itemPropertyInfo = itemType.GetProperty((string)parameter);\n                double itemValue = (double)itemPropertyInfo.GetValue(item, null); \n                sum += itemValue;\n            }\n            return sum;\n        }\n        return 0.0;\n    }\n    public object ConvertBack(object value, Type targetType, object parameter, \n                              System.Globalization.CultureInfo culture)\n    { throw new NotImplementedException();  }\n}	0
11750252	11749636	How to convert a MySql selection into an string?	var query = "SELECT id FROM applys WHERE id = 10";\nvar connectionString = "yourmysqlconnectionstringgoeshere";\nusing(var connection=new MySqlConnection(connectionString))\n{\n    connection.Open();\n    using (var reader = new MySqlCommand(query, connection).ExecuteReader())\n    {\n        if(reader.Read())\n        {\n            if (reader["id"].ToString() =="10")\n            {\n                // do your stuff here\n            }\n        }\n    }\n}	0
18639285	18639239	rename a function in C#	private static void printf(string value)\n{\n    System.Console.WriteLine(value);\n}	0
1174678	1174640	Is there an easy way to add (#) to a filename when you find a duplicate filename?	var filenameFormat = "FooBar{0}.xml";\nvar filename = string.Format(filenameFormat, "");\nint i = 1;\nwhile(File.Exists(filename))\n    filename = string.Format(filenameFormat, "(" + (i++) + ")");\n\nreturn filename;	0
12616070	12615886	Holding a Session when Connecting to FTP server C#	System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);	0
4277896	4277849	How can I upload data and a file in the same post?	c.Headers.Add	0
15449479	15449142	Fastest way to store and retrieve value by two integer keys	public class Storage \n{\n   private Dictionary<Key, DomainObject> dict;\n\n   public Storage()\n   {\n      dict = new Dictionary<Key, DomainObject>(Key.Comparer.Instance)\n   }\n\n   public DomainObject Get(uint a, uint b)\n   {\n      DomainObject obj;\n      dict.TryGetValue(new Key(a,b), out obj);\n      return obj;\n   }\n\n   internal struct Key \n   {\n       internal readonly uint a;\n       internal readonly uint b;\n\n       public Key(uint a, uint b)\n       {\n          this.a = a;\n          this.b = b;\n       }     \n\n       internal class Comparer : IEqualityComparer<Key>\n       {\n           internal static readonly Comparer Instance = new Comparer();\n           private Comparer(){}\n\n           public bool Equals(Key x, Key y)\n           {  \n               return x.a == y.a && x.b == y.b;\n           }  \n\n           public int GetHashCode(Key x)\n           {    \n              return (int)((x.a & 0xffff) << 16) | (x.b & 0xffff));\n           }\n       } \n   }  \n}	0
17491388	17491328	C# Button is firing only on the second click	this.button1.Click += new System.EventHandler(this.dosomething);	0
31141637	31141553	C# help declaring variable i initialize it to	// This line increments the variable then prints its value.\nConsole.WriteLine("{0}", ++ Cash);\n// This prints the value of the (incremented variable)\nConsole.WriteLine("{0}", Cash);\n// The prints the value of the variable *then* increments its value\nConsole.WriteLine("{0}", Cash ++);	0
4214617	4214587	How to populate many GridView controls from one stored procedure?	SqlDataReader dr = DB.CheckDBIntegrity();\n\nwhile (!dr.NextResult())\n    {\n       // bind results to appropriate grid\n    }	0
2919388	2919158	How do I programmatically set property of control in aspx file?	... Text="<%$ Code: DateTime.Now %>" ...	0
24739620	24738121	Make a word in a TextBlock bold	Run bold = new Run();\nbold.Text = "Should be bold";\n\nbold.FontWeight = FontWeights.Bold;\n\nBlockInstructions.Inlines.Add(bold);\n\n\n\nRun notbold = new Run();\nnotbold.Text = "Shouldn't be bold";\n\nnotbold.FontWeight = FontWeights.Normal;\n\nBlockInstructions.Inlines.Add(notbold);	0
8234770	8189667	treeview infinite loop	foreach (DataRow dr in dt.Rows)\n    {\n        TreeNode child = new TreeNode();\n        child.Text = dr["kgr_ad"].ToString();\n        child.Value = dr["kgr_sno"].ToString();\n\n           child.CollapseAll();\n\n            kgrBsno.ChildNodes.Add(child);\n            AltGruplariYaz(child, Convert.ToInt32(dr["kgr_sno"]));\n}	0
1477948	1477920	Storing of settings without database	DSUser ds = new DSUser();\nds.ReadXml(fileName);\n\nds.AcceptChanges();\nds.WriteXml(fileName);	0
3344521	3343982	wpf set sorting programmatically, so that the header is toggled as sorted	int columnIndex = 0;\n            this.dataGrid1.ColumnFromDisplayIndex(columnIndex).SortDirection = \n                ListSortDirection.Descending;	0
32731393	32730821	Stop a Timer when it reaches zero	private void timer1_Tick(object sender, EventArgs e)\n{\n    //I've edited you're code if(countdowntime.TotalSeconds > 0)\n    //to this because @ "0:1" It will display Times Up\n    if (countdowntime.TotalSeconds >= 0)\n    {\n        timeremaining.Text = countdowntime.Minutes.ToString() + ":" + countdowntime.Seconds.ToString();\n    }\n    else\n    {\n        timeremaining.Text = "Times Up!\r\n";\n        timer1.Stop();\n        return;\n    }\n\n    TimeSpan tSecond = new TimeSpan(0, 0, 1);\n    countdowntime = countdowntime.Subtract(tSecond);\n}	0
20199836	20199727	How to Fetch Data from database using Entity Framework 6	using (ABCEntities ctx = new ABCEntities())\n    {\n        var query = (from c in ctx.Cities\n                    join s in ctx.States\n                    on c.StateId equals s.StateId\n                    where c.Pincode == iPincode\n                    select new {\n                            s.StateName, \n                            c.CityName, \n                            c.Area}).First().SingleOrDefault();\n\n        if (query != null)\n        {\n            cboState.SelectedItem.Text =query.State;        \n            cboCity.SelectedItem.Text = query.CityName;    \n            txtArea.Text = query.Area;                        \n        }\n    }	0
144189	144176	Fastest way to convert a possibly-null-terminated ascii byte[] to a string?	public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset)\n{\n    string result = null;\n\n    unsafe\n    {\n       fixed( byte* pAscii = &buffer)\n       { \n           result = new String((sbyte*)pAscii, offset, buffer.Length - offset);\n       }\n    }\n\n    return result;\n}	0
12778117	12778075	how to get desired datetime format	Console.WriteLine(time.ToString("ddd, MM/dd/yy hh:mm:ss"));	0
26515840	26514938	MySQL Database: Limit user access to data they created	..AND WHERE table.ownerID = @ownerid	0
6985015	6984889	Allow Two Instances of Application to Run	bool IsFree = false;\n\n\nMutex mutex = new Mutex(true, "MutexValue1", out IsFree);\n\nif(!IsFree)\n    mutex = new Mutex(true, "MutexValue2", out IsFree);\n\nif(!IsFree)\n{\n    //two instances are already running\n}	0
6708469	6708352	Group by multiple enumerables in LINQ	var ordersInList1 = list1.GroupBy(order => order.CustomerId)\n                         .ToDictionary(g => g.Key, g => g.Count());\nvar ordersInList2 = list2.GroupBy(order => order.CustomerId)\n                         .ToDictionary(g => g.Key, g => g.Count());\n\nvar results = ordersInList1.Keys.Union(ordersInList2.Keys)\n                           .Select(id =>\n                           new { \n                                CustomerId = id, \n                                CountOrders1 = ordersInList1[id], \n                                CountOrders2 = ordersInList2[id]\n                           })\n                           .ToArray();	0
33543582	33543288	How toDetermine if an object can be cast to a different type, without IConvertible	object set = new DbSet<MyClass>();\nvar conv = set.GetType().GetMethod("op_Implicit", BindingFlags.Static | BindingFlags.Public, null, new[] { set.GetType() }, null);\nif (conv != null && conv.ReturnType == typeof(DbSet))\n{\n    var rawSet = (DbSet)conv.Invoke(null, new object[] { set });\n}	0
32638276	32638156	SQL table data export to txt file on desktop	private void testie()	0
16001163	16001098	Convert user entered value to dollar currency	protected void btn_Click(object sender, EventArgs e)\n{\n    Decimal currency = Convert.ToDecimal(txtbox.Text, new CultureInfo("en-US"));\n    string money = currency.ToString("C");\n\n    if (currency % 1 == 0) {\n        money = money.Substring(0, money.Length - 3);\n    }\n\n    Response.write(money);\n}	0
101632	77659	Blocking dialogs in .NET WebBrowser control	window.alert = function () { }	0
2843361	2843357	Window screenshot using WinAPI	pictureBox.Handle	0
29296353	29244269	Call Javascript From C# in GeckoFX 33	public void evaluateScript(string command)\n        {\n\n            System.Diagnostics.Debug.WriteLine("evaluateScript: " + command);\n            using (Gecko.AutoJSContext context = new AutoJSContext(geckoWebBrowser1.Window.JSContext))\n            {\n                var result = context.EvaluateScript(command, geckoWebBrowser1.Window.DomWindow);\n            }\n        }	0
31857912	31856473	How to send an "Enter" press to another application in WPF	SendMessage(Handle, WM_KEYDOWN, VK_ENTER, 0);\nSendMessage(Handle, WM_KEYUP, VK_ENTER, 0);	0
27789163	27789091	Cant find method in DataSource namespace	var apartmentData = await DataSource.GetApartmentsAsync();	0
21096769	21096616	Read CSV files to two arrays c#	static void getTwoArraysFromFile(string filein, ref double[] acc, ref double[] period)\n{\n    string line;\n\n    List<double> p1 = new List<double>();\n    List<double> p2 = new List<double>();\n\n    System.IO.StreamReader file = new System.IO.StreamReader(filein);\n    while ((line = file.ReadLine()) != null)\n        try {\n            String[] parms = line.Trim().Split(',');\n\n            p1.Add(double.Parse(parms[1], CultureInfo.InvariantCulture));       \n            p2.Add(double.Parse(parms[0], CultureInfo.InvariantCulture));\n        }\n        catch { }\n\n    acc = p1.ToArray();\n    period = p2.ToArray();\n}	0
13186236	13186100	How change location of |DataDirectory| in ASP.NET application built in C#	AppDomain.CurrentDomain.SetData("DataDirectory", "YourPath");	0
27543649	27543399	How to input comma separated Hex values into a textbox and output as hex values, c#	Convert.ToByte(text, 16)	0
24978507	24978384	checkboxlist items as checked by default in codebehind asp.net	protected void Page_Load(object sender, EventArgs e)\n{\n    for (int i = 0; i < CheckBoxList.Items.Count; i++)\n    {\n        if(someCondition)\n            CheckBoxList.Items[i].Selected = true;\n\n    }\n\n}	0
19193798	19193727	Ignore files with GetFiles	Dim files As System.IO.FileInfo() = directory.GetFiles().Where(Function(fi) Not (fi.Extension.ToLower() = ".bad1" OrElse fi.Extension.ToLower() = ".bad2" OrElse fi.Extension.ToLower() = ".bad3")).ToArray()	0
5472163	5471892	How to create object from its Type.GUID	Dictionary<Guid,Type>	0
26158926	26158787	Get dynamic controls and text in Repeater	foreach (RepeaterItem item in Repeater.Items)\n{\n  if (item.ItemType == ListItemType.Item \n        || item.ItemType == ListItemType.AlternatingItem) \n    { \n      Label QuestionLabel = (Label)item.FindControl("QuestionLabel");\n    }\n}	0
26153656	26129514	Xamarin iOS: Wait for HKHealthStore SaveObject to finish	async bool SaveToHealth (Data d)\n{\n     var hkStore = new HKHealthStore ();\n     try {\n          await hkStore.SaveObjectAsync (d);\n          return true;\n     } catch {\n          return false;\n     }\n}	0
4960109	4959835	How do I update an objects parameters from a NameValueCollection (or similar)?	var type = myInstance.GetType();\nforeach(var keyValue in values)\n{\n   type.InvokeMember(keyValue.Key,BindingFlags.SetProperty,null,myInstance,  new object[]{keyValue.Value});    \n\n}	0
21281201	21280139	How to consume an rss feed under a specific account	ex: new NetworkCredential( "username", "password", "domain" )	0
12207764	12207732	Delete items from one list based on two parameters in other list	list1.RemoveAll(c => list2.Any(c2 => c2.Name == c.Name && c2.City == c.City));	0
18761017	18760786	WPF ContentControl: Iterating over child control	for (int i = 0; i < VisualTreeHelper.GetChildrenCount(contentControl); i++)\n        {\n            var child = VisualTreeHelper.GetChild(contentControl, i);\n            if(child is ContentPresenter)\n            {\n                var contentPresenter = child as ContentPresenter;\n                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(contentPresenter); i++)\n                {\n                    var innerChild = VisualTreeHelper.GetChild(contentPresenter, i);\n                }\n\n                break;\n            }\n        }	0
5431810	5420174	How do you get subject & title from a Word document (without opening it)?	using System;\nusing System.IO;\nusing System.IO.Packaging; // Assembly WindowsBase.dll\n\nnamespace ConsoleApplication16\n{\n  class Program\n  {\n     static void Main(string[] args)\n     {\n        String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n        String file = Path.Combine(path, "Doc1.docx");\n\n        Package docx = Package.Open(file, FileMode.Open, FileAccess.Read);\n        String subject = docx.PackageProperties.Subject;\n        String title = docx.PackageProperties.Title;\n        docx.Close();\n     }\n  }\n}	0
8280457	8279553	Converting varbinary to image	public static Image ConvertToImage(System.Data.Linq.Binary iBinary)\n    {\n        var arrayBinary = iBinary.ToArray();\n        Image rImage = null;\n\n        using (MemoryStream ms = new MemoryStream(arrayBinary))\n        {\n            rImage = Image.FromStream(ms);\n        }\n        return rImage;\n    }	0
15385997	15385921	Add label to Panel programmatically	private void VizualizareTest_Load(object sender, EventArgs e)\n{\n    for (int i = 0; i < 4; i++)\n    {\n        Panel pan = new Panel();\n        pan.Name = "panel" + i;\n        ls.Add(pan);\n        Label l = new Label();\n        l.Text = "l"+i;\n        pan.Location = new Point(10, i * 100);\n        pan.Size = new Size(200, 90);  // just an example\n        pan.Controls.Add(l);\n        this.Controls.Add(pan);\n\n    }\n}	0
783133	783106	How to select items that do not show up in a second list with Linq	var query = list1.Except(list2);	0
15222753	15222712	DataGridView Standard context menu	private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        e.Control.ContextMenu = new ContextMenu();\n    }	0
2970117	2970109	How can I get the POST And GET data that is passed in my ASP.Net application URL?	string a= Page.Request.QueryString["a"];\nstring u= Page.Request.QueryString["u"];	0
251285	251271	how to pass variables like arrays / datatable to SQL server?	SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);\ncopier.BatchSize = 500; //# of rows to insert at a time\ncopier.DestinationTableName = "dbo.MyTable";\ncopier.WriteToServer(myDataTable);	0
16033573	16033145	How to obtain a value in a collection based on a property	currentDatabase.Views[name, schema];	0
6347319	6347219	How can I save space when storing boolean data in c#	int bits = (field_1 ? 1 : 0) | (field_2 ? 2 : 0) | (field_3 ? 4 : 0) | (field_4 ? 8 : 0) | ...\n\nfield_1 = (bits & 1) != 0;\nfield_2 = (bits & 2) != 0;\nfield_3 = (bits & 4) != 0;\nfield_4 = (bits & 8) != 0;\n...	0
23976813	23976701	how to embed variables in text file in C#	Dictionary<string, int>	0
30973217	30915944	Resolving Interface with generic type constraint with Castle Windsor	public void Install(IWindsorContainer container, IConfigurationStore store)\n{\n    container.Register(\n    Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>))\n}\n);\n\npublic class Repository<T> : IRepository<T> where T : class, IEntity\n{\n...\n}	0
32316535	32316073	How to correctly refactor this big and with very similar code if/else statements?	string obje = String.Empty;\nlong userId = 0;\nlong objNewId = 0;\nlong objOldId = 0;\nstring action = String.Empty;\n\nobje = ConstantParams.WCFLOG_APPLICATION_Foo;\n\nSuperclassDto newDto = (SuperclassDto)response.Data;\nSuperclassDto oldDto = (SuperclassDto)oldObject;\n\nuserId = newFoo.UserApplicationId;\nobjNewId = newDto.Id;\nobjOldId = oldDto.Id;\n\naction = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;\n\nstring message = Helper.GenerateMessage(action, obje, userId, objNewId);	0
25331057	18100977	No overload for method SetError	Drawable icon_error = Resources.GetDrawable(Resource.Drawable.icon_error);//this should be your error image.\nicon_error.SetBounds(0,0,icon_error.IntrinsicWidth,icon_error.IntrinsicHeight);\n\nif (txtsubiect.Text.Length <= 0)\n                        {\n                            txtsubiect.RequestFocus();\n                            txtsubiect.SetError("Eroare,camp gol!", icon_error );\n                        }	0
6699362	6672980	datagrid access in C#	private void UpdateDataGridViewColor()\n    {\n        if (calledMethod == 2)\n        {\n            for (int i = 0; i < dataGridView1.RowCount; i++)\n            {\n                int j = 6;\n                DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();\n                CellStyle.ForeColor = Color.Red;\n\n                if (isLate(dataGridView1[j, i].Value.ToString()))\n                {\n                    dataGridView1[j, i].Style = CellStyle;\n                }\n            }\n        }\n    }	0
20448622	20448536	List C# find matching User	foreach(User _user in users)\n{\n   if(_user.connectionid == TextBox1.Text)\n   {\n      TextBox2.Text = _user.nick;\n      break;\n   }\n}	0
10070353	9829927	How to get pdf file bookmarks using c#	public void ExportBookmarksToXml(string SourcePdfPath, string xmlOutputPath, string Password = "")\n    {\n        PdfReader reader = new PdfReader(SourcePdfPath, new System.Text.ASCIIEncoding().GetBytes(Password));\n       //Collection of bookmarks\n        IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(reader);\n        using (MemoryStream memoryStream = new MemoryStream())\n        {\n            SimpleBookmark.ExportToXML(bookmarks, memoryStream, "ISO8859-1", true);\n            //MessageBox.Show(bookmarks[0].Values.ToString());\n            File.WriteAllBytes(xmlOutputPath, memoryStream.ToArray());\n        }\n    }	0
13635271	13610110	Excel Interop get width in pixels of text inside cell	Excel.Range xlRange = sheet.get_Range("A2");\nExcel.Font xlFont = xlRange.Font;\nstring fontName = xlFont.Name;\ndouble fontSize = xlFont.Size;\nFont font = new Font(fontName, (float)fontSize);\nfloat width = Graphics.FromImage(new Bitmap(1, 1)).MeasureString(title, font).Width;	0
10763356	10763326	Every X results form a string of data?	queryList.Batch(40).Pipe(x=>Console.WriteLine(String.Join(Environment.NewLine, x.ToArray()))).ToArray();	0
10157010	10156337	How to Authorize the service object for a specific user	service.setUserCredentials(username, password);	0
8522361	8474427	Exporting from an MSChart based app raising exceptions for vector formats	ImageFormat fmt = ImageFormat.Emf;\nImageFormat fmt2 = new ImageFormat(ImageFormat.Emf.Guid);\nConsole.WriteLine(fmt.ToString()); // gives: Emf\nConsole.WriteLine(fmt2.ToString()); // gives: [ImageFormat: b96b3cac-0728-11d3-9d7b-0000f81ef32e]	0
8363032	8362571	Force protobuf-net to ignore IEnumerable/ICollection interfaces	[ProtoContract(IgnoreListHandling = true)]\npublic class FileTree : ICollection<FilePath> ...\n{ ... }	0
16207009	16206960	How to save data into a format that can be called upon later on	[Serializable]\nclass SomeProperty\n{\n    public int Count1 {get;set;}   //2550\n    public int Count2 {get;set;}   //995\n    public int Count3 {get;set;}   //200000\n    public int Count4 {get;set;}   //7\n}\n\nList<SomeProperty> objects=new List<SomeProperty>();\nobjects.Add(...)\n\n//Saving\nXmlSerializer x = new XmlSerializer(objects.GetType());\nusing (FileStream stream = System.IO.File.Create(FilePath))\n{\n    XmlWriter writer = XmlWriter.Create(stream);\n    x.Serialize(writer, objects);\n}\n\n//Reading\nXmlSerializer x = new XmlSerializer(typeof(List<SomeProperty>));\nusing (FileStream fs = new FileStream(FilePath, FileMode.Open))\n{\n    XmlReader reader = new XmlTextReader(fs);\n    var objects= (List<SomeProperty>)x.Deserialize(reader);\n}	0
2623920	2623548	WinForms DataGridView - update database	using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], \n       rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],\n       rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]\n       FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))\n    {\n        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);\n        DataTable dt = new DataTable();\n        dt = RuleTable.DataSource as DataTable;\n        //ruleTableDA.Fill(dt);\n        ruleTableDA.Update(dt);\n    }	0
15096328	15096303	Generic function unable to compare between an array value and a standard value	if (matrix[row, col].CompareTo(max_val) > 0)	0
7620784	7620752	change text size of checkbox via c# code	chk[i].Font = new Font(chk[i].Font.FontFamily, 8.5f);	0
4378383	4378099	ListBox Item Removal	private void RemoveButton_Click(object sender, RoutedEventArgs e)\n{\n  foreach(ConfigSet item in this.configSetListBox.SelectedItems)\n  {\n      this.configSetListBox.ItemsSource.Remove(item); // ASSUMING your ItemsSource collection has a Remove() method\n  }\n}	0
31684975	31684525	GET WebRequest giving the same response as previous call	getrequest.Headers["Cache-Control"] = "no-cache";	0
32528520	32528079	Random String of Certain Numbers and Letters - Only a certain number of times	IEnumerable<char> PickRandom(char[] source, int count)\n{\n   return Enumerable.Repeat(1, count)\n                      .Select(s => source[random.Next(source.Length)]);\n}\n\n\nvar randomLetters = PickRandom(letters, 2);\nvar randomNumbers = PickRandom(numbers, 6);\n\nint lettersGroup1 = random.Next(2);\nint group1 = random.Next(6);\nint group2 = random.Next(6 - group1);\n\nvar result = randomNumbers.Take(group1)\n     .Concat(randomLetters.Take(lettersGroup1))\n     .Concat(randomNumbers.Skip(group1).Take(group2))\n     .Concat(randomLetters.Skip(lettersGroup1))\n     .Concat(randomNumbers.Skip(group1 + group2));\nvar stringResult = String.Join("", result);	0
1597293	1597255	Changing the BackColor of my custom UserControl - help!	private void MovieItem_Click(object sender, EventArgs e)\n{\n    foreach (Control y in this.Parent.Controls)\n    {\n        if (y is MovieItem && y != this)\n            y.BackColor = Color.White;\n    }\n    this.BackColor = Color.LightBlue;\n}	0
4505400	4495961	How to send a Status Code 500 in ASP.Net and still write to the response?	Context.Response.TrySkipIisCustomErrors = true	0
2978480	2042344	How to output namespace in T4 templates?	System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");	0
12604495	12604446	Attempting to connect to Excel spreadsheet in C#	string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;\n Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;\n Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";	0
15807493	15807242	Using C# regex, getting a value between two strings	var match= Regex.Match(values[(int)HomeColumnNames.VenueCrowdDate], datePattern);\n\nmatch.Groups[0]; //returns full match\nmatch.Groups[1]; //returns 1st group\n\n//Gets MatchCollection\nvar matches= Regex.Matches(values[ManyAddresses, datePattern);	0
20774896	20774882	How to create an object for a class and use its functions in one line	context.Response.Write(new JavaScriptSerializer().Serialize(ds));	0
25155413	25154717	How to Save/Overwrite existing Excel file without message	app.DisplayAlerts = false;\n        wb.SaveAs(@"C:\1\myExcel.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,\n                    Type.Missing, Type.Missing);\n        workbook.Close();\n        app.Quit();	0
1428054	1428047	How to Set WinForms Textbox to overwrite mode	MaskedTextBox box = ...;\nbox.InsertKeyMode = InsertKeyMode.Overwrite;	0
51537	51526	Changing the value of an element in a list of structs	MyList[1] = new MyStruct("bob");	0
15411627	15411521	Capturing IP address from Email in C#	Regex rex = new Regex("X-Originating-IP\\:\\s*\\[(.*)\\]", RegexOptions.Multiline|RegexOptions.Singleline);\n\nstring ipAddrText = string.Empty;\nMatch m = rex.Match(headersText);\nif (m.Success){\n    ipAddrText = m.Groups[1].Value;\n}\n\n// ipAddrText should contain the extracted IP address here	0
15921162	15920996	linq to xml getting value of an attribute out of web.config	XDocument document = Xdocument.Load("~/web.config");\nvar location = document.Descendants().Single(i=>i.Attribute("baseLocation") !=null)\n               .Attribute("baseLocation").Value;	0
25943192	25943038	C# Exporting interface as dll in an existing project with custom variable types	public interface IAnimal\n{\n    UInt32 Height { get; }\n}\n\npublic interface IExtension\n{\n    IEnumerable<IAnimal> GetAnimals();\n}	0
2411363	2375105	.NET 4 - Determine the number of touch points available in Win 7	[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]\nstatic extern int GetSystemMetrics(int nIndex);\n\nconst int SM_MAXIMUMTOUCHES = 95;\n\nint GetPointsAvailable()\n{\n    return GetSystemMetrics(SM_MAXIMUMTOUCHES);\n}	0
29625067	29624952	Set property value from FormClosing event	RevisionTools revTools = new RevisionTools(); \nrevTools.ShowDialog();\nthis.revEditState = false;	0
548983	531878	WPF video tearing on Windows XP	// Set the global desired framerate to 50 frames per second\nStartup += delegate(object sender, StartupEventArgs e)\n{\nTimeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline),\n     new PropertyMetadata(50));\n};	0
15123343	15121876	How do I display a PDF using PdfSharp in ASP.Net MVC?	public class PdfDocumentController : Controller\n{\n    public ActionResult GenerateReport(ReportPdfInput input)\n    {\n        //Get document as byte[]\n        byte[] documentData;\n\n        return File(documentData, "application/pdf");\n    }\n\n}	0
18698323	18698051	unable to parse date string of format like 2013-09-17T05:15:27.947	//without ParseExact\nvar t1= DateTime.Parse(dt);\n\n//you don't know how many milliseconds will be in your string, \n//and want absolutely use ParseExact anyway\nvar t2= DateTime.ParseExact(dt.PadRight(27, '0'), "o", culture);\n\n//you know you'll always have 3 chars for milliseconds.\nvar t3= DateTime.ParseExact(dt, "yyyy-MM-ddTHH:mm:ss.fff", culture);	0
2123012	2122985	removing the empty gray space in datagrid in c#	dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;	0
15596977	15596892	I-V data parsing in textfile	for (int j = 0; j < values.Length; j += 2) {\n    double i = double.Parse(values[j]);\n    double v = double.Parse(values[j+1]);\n    double r = v / i;\n}	0
13201385	13201384	Enhance Interop FormatConditons performance	// Disable conditional format calculations to enhance speed\nSheet.EnableFormatConditionsCalculation = false;	0
375964	375940	Find frequency of values in an Array or XML (C#)	XDocument doc = XDocument.Parse(xml);\n        var query = from item in doc.Descendants("item")\n                    select new\n                    {\n                        att1 = (string)item.Attribute("att1"),\n                        att2 = (string)item.Attribute("att2") // if needed\n                    } into node\n                    group node by node.att1 into grp\n                    select new { att1 = grp.Key, Count = grp.Count() };\n\n        foreach (var item in query.OrderByDescending(x=>x.Count).Take(4))\n        {\n            Console.WriteLine("{0} = {1}", item.att1, item.Count);\n        }	0
8047137	8046989	Access database data from the code behind using ASP.NET C#	using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString)\n{\n  var selectCommand = new SqlCommand("SELECT ...");\n  selectCommand.CommandType = CommandType.Text;\n  selectCommand.Connection = connection;??var dataAdapter = new SqlDataAdapter()??dataAdapter.SelectCommand = selectCommand??var dataSet = new DataSet();??connection.Open()??dataAdapter.Fill(dataSet, "myDataSet");??connection.Close()??// now, the dataSet.Tables[0] is a DataTable with your data in it. You can add, edit or remove data in this table before binding it to the ListView??myListView.DataSource = dataSet;??myListView.DataBind();\n}	0
9585941	9585815	Ensure that something is stored in Session before anything else in the Page Life Cycle	public string UserId\n{\n    get\n    {\n        string s = Session["UserId"];\n        if (s == null)\n        {\n            s = ... Get UserID from somewhere, e.g. database\n            Session["UserId"] = s;\n        }\n        return s;\n    }\n}	0
12661647	12643166	Bitmap in some cells of a DataGridView column	dataGridView1.Columns.Add("columnName1", "Column 1 Header");\ndataGridView1.Columns.Add("columnName2", "Column 2 Header");\n\nvar row1 = new DataGridViewRow();\nrow1.Cells.Add(new DataGridViewImageCell { Value = new Bitmap(@"C:\Path\to\image.jpg") });\nrow1.Cells.Add(new DataGridViewTextBoxCell { Value = "string" });\ndataGridView1.Rows.Add(row1);\n\nvar row2 = new DataGridViewRow();\nrow2.Cells.Add(new DataGridViewTextBoxCell { Value = "string"});\nrow2.Cells.Add(new DataGridViewImageCell { Value = new Bitmap(@"C:\Path\to\image.jpg") });\ndataGridView1.Rows.Add(row2);	0
4023761	4023282	Split a collection into parts based on condition with LINQ?	inv\n        .GroupBy(x => new { CustomerName = x.CustomerName, Date = x.Date })\n        .SelectMany(x => x\n                            .OrderBy(y => y.SortOrder)\n                            .Select((y,i) => new { Value = y, Sort = y.SortOrder - i })\n                            .GroupBy(y => y.Sort)\n                            .Select(y => y.Select(z => z.Value))\n        )	0
29562729	29561715	How do we load a html file from a folder on a sdcard into a webview panel?	web.NavigateToString(yourHtmlInString)	0
16215949	16197221	Retrieving Properties from DbSqlQuery	IdClass x = ImportFactory.AuthoringContext.Database.SqlQuery<IdClass>(sql).FirstOrDefault();	0
1996947	1996912	Select Column values from SqlDataReader command	// straight after this line:\ndr = cmd.ExecuteReader();\n\nif (dr.Read()) // you only have one row so you can use "if" instead of "while"\n{\n    var columnName = dr.GetString(0);\n    var rowCount = dr.GetInt32(1);\n}	0
5465841	5465785	How we create pages to show records from a DataTable in a DataGrid in WPF?	var perPage = 10;\nvar page = 2;\n\n//Will bind rows 11-20 to the DataGrid\ndataGrid.DataContext = DataTable.Rows.OfType<DataRow>().Skip(page*perPage).Take(perPage);	0
20976129	20975999	How to filter file types e.g .exe in a C# console application	void Main()\n{\n    String filter = String.Empty;\n\n    // prompt the user for a pattern (.e.g. "*.exe")\n    Console.Write("filter: ");\n    filter = Console.ReadLine();\n\n    // create a reference to the C:\Windows directory\n    DirectoryInfo root = new DirectoryInfo(\n      //fancy way for referencing %windir%\n      Environment.GetFolderPath(Environment.SpecialFolder.Windows)\n    );\n\n    // find all files matching ht epattern the user typed in\n    FileInfo[] executables = root.GetFiles(filter);\n\n    // iterate over them\n    foreach (var exe in executables)\n    {\n      // and print the name of each match\n        Console.WriteLine(exe.Name);\n    }\n}	0
11455888	11455593	Get the date after a word?	(?=born\s|died\s|passed\saway\s)(\w+.*?)(\w+\s\d+,\s\d+)	0
34330744	34330665	C# How can we write an independent end tag in xml	writer.WriteStartElement("Contrast");\nwriter.WriteAttributeString("name",???"left minus right");\nwriter.WriteString("1 -1");\nwriter.WriteEndElement();	0
8710729	8710068	Increment a double value	double countA= 0.00;\n  double countB= 0.00;\n  int test= 0;\n\n  string entry= myrow.grade.Trim().ToUpper();\n\n  switch(entry)\n  {\n      case "A":\n      countA++;\n      break;\n      case "B":\n      countB++;\n      break;\n      default:\n      test++;\n  }\n\n  countALabel.Text = Convert.ToString(countA);     \n  countBLabel.Text = Convert.ToString(countB);	0
9381881	9381819	Getting a substring results an error	if (dataGridView1.Rows[i].RowType == DataControlRowType.DataRow)\n{\n    if (dataGridView1.Rows[i].Cells[0].Value.ToString().Length > 13)\n    {\n        e.Graphics.DrawString(dataGridView1.Rows[i].Cells[0].Value.ToString().Substring(0,14), print6B, Brushes.Black, x-10, 130 + height);\n    }\n}	0
8990465	8990231	How can I create a dynamic Select on an IEnumerable<T> at runtime?	private class Foo {\n    public string Bar { get; set; }\n}\n\nprivate IEnumerable<Foo> SomeFoos = new List<Foo>() {\n    new Foo{Bar = "Jan"},\n    new Foo{Bar = "Feb"},\n    new Foo{Bar = "Mar"},\n    new Foo{Bar = "Apr"},\n};\n\n[TestMethod]\npublic void GetDynamicProperty() {\n\n        var expr = SelectExpression<Foo, string>("Bar");\n        var propValues = SomeFoos.Select(expr);\n\n        Assert.IsTrue(new[] { "Jan", "Feb", "Mar", "Apr" }.SequenceEqual(propValues));\n\n    }\n\npublic static Func<TItem, TField> SelectExpression<TItem, TField>(string fieldName) {\n\n    var param = Expression.Parameter(typeof(TItem), "item");\n    var field = Expression.Property(param, fieldName);\n    return Expression.Lambda<Func<TItem, TField>>(field, new ParameterExpression[] { param }).Compile();\n\n}	0
27335860	27335616	how do you create a custom table looks like this	this.flowLayoutPanel1.AutoScroll = true;\nthis.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;\nthis.flowLayoutPanel1.WrapContents = false;	0
27245592	27244770	Merge column header in gridview	if (e.Row.RowType == DataControlRowType.Header)\n{\n      e.Row.Cells[3].ColumnSpan = 2;\n      e.Row.Cells[4].Visible = false;\n      e.Row.Cells[3].Text = "Action";\n}	0
24419216	24418941	Creating a Bitmap from an IntPtr	Bitmap bmp = new Bitmap(1280, 960, System.Drawing.Imaging.PixelFormat.Format32bppRgb);\nvar data = bmp.LockBits(new Rectangle(0, 0, 1280, 960), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);\n\nbyte* srcBmpData = (byte*)pbyteBitmap.ToPointer();\nbyte* dstBmpData = (byte*)data.Scan0.ToPointer();\n\nfor (int buc = 0; buc < 1280 * 960; buc++)\n{\n    int currentDestPos = buc * 4;\n    dstBmpData[currentDestPos] = dstBmpData[currentDestPos + 1] = dstBmpData[currentDestPos + 2] = srcBmpData[buc];\n}\n\nbmp.UnlockBits(data);	0
3298319	3298308	Best way to call a configurable method	Type t = Type.GetType(type_name_from_config);\n\nIGivenInterface obj = (IGivenInterface) Activator.CreateInstance(t);	0
11323597	11323543	Add content to listview in runtime	void Btn_Click(Object sender,EventArgs e)\n{\n  var item1 = new ListViewItem(new[] {"text1", "text2", "text3", "text4"}); \n  lvRegAnimals.Items.Add(item1); \n}	0
25843804	25843699	how to add constructors parameter to a list?	public interface IParameterizedClass\n{\n   string ClassParameter {get}\n}\n\npublic class class1 : IParameterizedClass\n{\n   public string ClassParameter {get; private set;}\n   public class1(string someParameter)\n   {\n     // do some work\n\n     ClassParameter = someParameter;\n   }\n}  \n\npublic class class2 : IParameterizedClass\n{\n   public string ClassParameter {get; private set;}\n   public class2(string someParameter)\n   {\n     // do some work\n\n     ClassParameter = someParameter;\n   }\n}\n\npublic void getConstructorParametersToList()\n{\n    string[] myArrayList = null;\n    for(int i = 0; i < classList.Count; i++)\n    {\n        //Add the parameters from the constructors to a string array\n        myArrayList[i] = (classList[i] as IParameterizedClass).ClassParameter;\n    }\n}	0
11514039	11513532	Again with multiple IEntityChangeTracker interface instances	public static void SaveTrader(trader trader)\n    {\n        Mentor11Entities.Refresh(System.Data.Objects.RefreshMode.StoreWins, Mentor11Entities.traders);\n        GetMentor11().AddTotraders(trader);\n        GetMentor11().SaveChanges();\n        GetMentor11().AcceptAllChanges();\n        Mentor11Entities.Refresh(System.Data.Objects.RefreshMode.StoreWins, Mentor11Entities.traders);\n    }	0
8539123	8538272	Calculating a Subnet number from an IP Address and Subnet Mask in C#	string ipAddress = "192.168.1.57";\nstring subNetMask = "255.255.0.0";\n\nstring[] ipOctetsStr = ipAddress.Split('.');\nstring[] snOctetsStr = subNetMask.Split('.');\n\nif (ipOctetsStr.Length != 4 || snOctetsStr.Length != 4)\n{\n   throw new ArgumentException("Invalid input strings.");\n}\n\nstring[] resultOctets = new string[4];\nfor (int i = 0; i < 4; i++) \n{\n    byte ipOctet = Convert.ToByte(ipOctetsStr[i]);\n    byte snOctet = Convert.ToByte(snOctetsStr[i]);\n    resultOctets[i] = (ipOctet & snOctet).ToString();\n}\n\nstring resultIP = string.Join(".", resultOctets);	0
33847446	33847324	How to Add Subitems to Listview in WPF and this subitems Dynamically through programming?	ListView1.Items.Add(new \n{\n   ClinicID = "123",\n   Name = chkname.IsChecked ? "Khalid" : string.Empty,\n   Gender = chkgender.IsChecked ? "Male" : string.Empty\n});	0
7050693	7047809	Send image in WP7	Dictionary<string, object> data = new Dictionary<string, object>()\n                    {\n                    {"photo", byteArray},\n                    };\n                    PostSubmitter post = new PostSubmitter() { url = uploadServer, parameters = data };\n                    post.Submit();	0
5016826	5016752	Assigning a window handle from a literal value	int literal = 10;\nIntPtr handle = new IntPtr(literal);	0
7328316	7328308	Problem with simple join by multiple columns in two tables using linq	on new { Year = obj.st_year, Month = obj.st_month, Day = obj.st_day} \nequals new { Year  = ev.year, Month = ev.month, Day = ev.day}	0
12775057	12774979	A generic Find method to search by Guid type for class implementing IDbSet interface	public virtual T Find(params object[] keyValues)\n{\n    if (keyValues.Length != _keyProperties.Count)\n        throw new ArgumentException("Incorrect number of keys passed to find method");\n\n    IQueryable<T> keyQuery = this.AsQueryable<T>();\n\n    for (int i = 0; i < keyValues.Length; i++)\n    {\n        var x = i; // nested linq\n\n        keyQuery = keyQuery.\n        Where(entity => _keyProperties[x].GetValue(entity, null).Equals(keyValues[x]));\n    }\n\n    return keyQuery.SingleOrDefault();\n}	0
7542077	7542059	Most efficient way of reading data from a stream	using (var stream = new MemoryStream())\n{\n    byte[] buffer = new byte[2048]; // read in chunks of 2KB\n    int bytesRead;\n    while((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0)\n    {\n        stream.Write(buffer, 0, bytesRead);\n    }\n    byte[] result = stream.ToArray();\n    // TODO: do something with the result\n}	0
15307865	15307833	Set panel visiblity on Escape key press	bool bPanelFocus;\nprivate void cancelButon_Click(object sender, EventArgs e)\n{\n    if (popuppanel.Visible == true && bPanelFocus)\n    {\n        popuppanel.Visible = false;\n        mainpanel.Visible = true;\n        return;\n    }\n\n    //your code for the cancel button\n}	0
7125013	7117429	How to handle the user changing his mind without boolean flags?	typeof(NumericUpDown).GetField("currentValue", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(numericUpDown1, 5m);	0
21293058	21292262	how to do time stamping in access db using c#	private void button1_Click(object sender, EventArgs e)\n{\n    using OleDbConnection mycon = new OleDbConnection()\n    {\n        mycon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";\n\n        OleDbCommand command = new OleDbCommand();\n        command.CommandText = "INSERT INTO Table1 (Emp_ID, Asset_ID, Date_Column) VALUES (?, ?, ?)";\n\n        command.Parameters.Add("@EmpID", OleDbType.VarChar, 80).Value = textBox1.Text;\n        command.Parameters.Add("@AssetID", OleDbType.VarChar, 80).Value = textBox2.Text;\n        command.Parameters.Add("@Timestamp", OleDbType.Date).Value = DateTime.Now;\n\n        command.Connection = mycon;\n        mycon.Open();\n        command.ExecuteNonQuery();\n    }\n}	0
21733934	21733756	Best way to split string by last occurrence of character?	string s = "My. name. is Bond._James Bond!";\nint idx = s.LastIndexOf('.');\nConsole.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"\nConsole.WriteLine(s.Substring(idx + 1)); // "_James Bond!"	0
16653347	16653284	c# mysql update single row	string Query = @"UPDATE `users.db`.`userslogged` \n                 SET    `uses`='0' \n                 WHERE  `koffekeys` = @val";	0
4132837	4132810	How can I get a method name with the namespace & class name?	var methodInfo = System.Reflection.MethodBase.GetCurrentMethod();\nvar fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;	0
26674588	26674384	Map column names of sql table with an object property, C#, LINQ	string value = someData.GetType().GetProperty(key).GetValue(someData).ToString();	0
6897504	6896898	Special Characters in WCF REST parameter	/stores?city=BOLLN%C3%84S	0
8812414	8812382	Check if an object's type is from a particular namespace	e.OriginElement.GetType().Namespace	0
2560138	2560122	How can I have different LINQ to XML queries based on two different condition?	from xAudioinfo in xResponse.Descendants(ns + "DIDL-Lite").Elements(ns + "item")\nselect new RSMedia\n{\n   strAudioTitle = (xAudioinfo.Element(upnp + "artist") != null) \n      ? ((string)xAudioinfo.Element(dc + "title")).Trim()\n      : null,\n   strGen = (xAudioinfo.Element(upnp + "artist") == null) \n      ? ((string)xAudioinfo.Element(dc + "Gen")).Trim()\n      : null\n}	0
7193716	7193618	How can I reach the "object" behind a property with reflection?	Lion kaspar = new Lion { Name="Kaspar" };\nzooType.SetValue(londonZoo, kaspar, null);	0
4994521	4994469	Loop through constant members of a static class	public DropDownItemCollection TestCollection\n{\n    var collection = new DropDownItemCollection();\n    var instance = new TestClass();\n    foreach (var prop in typeof(TestClass).GetProperties())\n    {\n        if (prop.CanRead)\n        {\n            var value = prop.GetValue(instance, null) as string;\n            var item = new DropDownItem();\n            item.Description = value;\n            item.Value = value;\n            collection.Add(item);\n        }\n    }\n    return collection;\n}	0
4551588	4546487	How can I change column fore color in DataGridview as per condition?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            string status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "IsApprove"));\n\n            if (status == "pending")\n            {\n\n                e.Row.Cells[7].ForeColor = System.Drawing.Color.Yellow;\n            }\n            else if(status== "accept")\n            {\n\n                e.Row.Cells[7].ForeColor = System.Drawing.Color.Green;\n            }\n            else if (status == "reject")\n            {\n\n                e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;\n            }\n        }\n    }	0
2420241	2420178	Show Gridlines on a Grid	.RadGrid_WebBlue .rgRow td\n{\n    border: solid 1px #000000;\n}	0
24401748	24401664	Apply Sorting in ListView Control	public IQueryable<CollegeDataLibrary.CollegeDetail> GetData()\n{\n    var context = DataOperations.GetCollegeDetails();\n    return context.AsQueryable();\n}	0
1774423	1774410	Invocation of methods (with 'params'/generic cousins)	Max(new int[]{1}); // Invokes 2.\nMax<long>(new long[] { 1 }); // Invokes 4.	0
27568365	27568268	Excel to HTML Table using C#	public string XlsxToHTML(byte[] file)\n{\n   MemoryStream stream = new MemoryStream(file);\n   StringBuilder stringBuilder = new StringBuilder();\n\n   stringBuilder.Append("<table>");\n\n   using(ExcelPackage excelPackage = new ExcelPackage(stream))\n   {\n      ExcelWorkbook workbook = excelPackage.Workbook;\n      if(workbook!=null)\n      {\n         ExcelWorksheet worksheet = workbook.Worksheets.FirstOrDefault();\n         if(worksheet!=null)\n         {\n            var firstCell = worksheet.Cells[1,1].Value;\n            var secondCell = worksheet.Cells[1,2].Value;\n\n            stringBuilder.Append("<tr><td>"+firstCell+"</td></tr>");\n            stringBuilder.Append("<tr><td>"+firstCell+"</td></tr>");\n         }\n      }\n   }\n\n   stringBuilder.Append("</table>");\n\n   return stringBuilder.ToString();\n}	0
16550146	16550060	How can I make the beforeunload event fire only when a browser session is exited	var links = document.getElementsByTagName('a');\nfor(var i = 0, l = links.length; i < l; i++) {\n    links[i].onclick = function () {\n        foo = false;\n    }\n}	0
18370956	18370242	Convert ArrayOfString to List<string> in C# for Windows Phone 7	private void getObjectiveCompletedHandler(object sender, getObjectiveCompletedEventArgs e)\n    {\n      List<string> namesList = new List<string>();\n\n      foreach (string name in e.Result)\n       {\n        namesList.Add(name);\n       }\n    }	0
6456332	6456279	String Formatting C#	string myString = originalString.Substring(0, originalString.IndexOf("("));	0
33559761	33558704	button controls in user controls in ListView control as UpdatePanel Triggers in asp.net	protected void AnswerList_ItemDataBound(object sender, ListViewItemEventArgs e) {\n  LinkButton lb = e.Item.FindControl("btnUpdateAns") as LinkButton;\n  toolscriptmanagerID.RegisterAsyncPostBackControl(lb);  // ToolkitScriptManager\n}	0
19565524	19565380	Preventing a Certain Text to be Deleted or Change in a RichTextBox	richTextBox.Rtf = ...;\nrichTextBox.SelectAll(); or richTextBox.Select(start, length)//Select that line\nrichTextBox.SelectionProtected = true;\nrichTextBox.SelectionLength = 0;	0
34487354	34487331	Finding Max and Min Values of an Array returns 0	arr = new int[10];	0
24641623	24641280	Change the Color of a Rectangle Windows Phone 8	private void rectangle_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n    {\n        // Change this colour to whatever colour you want.\n        SolidColorBrush mySolidColorBrush = new SolidColorBrush();\n        mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0);\n\n        System.Windows.Shapes.Rectangle rect = (System.Windows.Shapes.Rectangle)sender;\n        rect.Fill = mySolidColorBrush;\n    }	0
9106986	9106900	How to limit textbox template field text length in gridview?	TextMode="MultiLine"	0
3147920	3147911	Wait till a process ends	var process = Process.Start(...);\nprocess.WaitForExit();	0
22657049	22654789	List Picker in Windows Phone 8	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n        {\n            base.OnNavigatedTo(e);\n            if (e.NavigationMode != NavigationMode.Back)\n            {\n              YourListPicker.ItemsSource = yourItemSource;\n            }\n        }	0
18249283	18249181	Getting a path of a Stream by converting to FileStream	var fileStream = stream as FileStream;	0
26467934	26385512	Programmatically generated PowerPoint presentations break PowerPoint 2013	public static void RemoveNotesFromDoc(string docPath)\n    {\n        try\n        {\n            using (PresentationDocument pDoc =\n                PresentationDocument.Open(docPath, true))\n            {\n                foreach (var slide in pDoc.PresentationPart.SlideParts)\n                {\n                    NotesSlidePart notes = slide.NotesSlidePart;\n\n\n                    if (notes != null)\n                    {\n                        slide.DeletePart(slide.GetIdOfPart(slide.NotesSlidePart));\n                    }\n                }\n            }\n        }\n    }	0
23527948	23527789	Retrieve Entry from Database where time value is null	OleDbCommand com = new OleDbCommand("SELECT count(*) from DI WHERE [Task] = ? AND [Time_Off] is null", Program.DB_CONNECTION);\ncom.Parameters.Add(new OleDbParameter("", "DI"));\nint count = (int)com.ExecuteScalar();\n\nif (count > 0)\n{\n    OleDbCommand com1 = new OleDbCommand("UPDATE DI SET [Time_OFF] = ? WHERE [Task] = ? AND [Time_Off] is null", Program.DB_CONNECTION);\n    com1.Parameters.Add(new OleDbParameter("", DateTime.Now.TimeOfDay));\n    com1.Parameters.Add(new OleDbParameter("", "DI"));\n    com1.ExecuteNonQuery();\n}\nelse\n{\n    DIPerson = DIlist[DIcomboBox.SelectedIndex];\n\n    OleDbCommand com2 = new OleDbCommand("INSERT INTO DI ([Person], [Task], [Time_On]) VALUES     (?, ?, ?)", Program.DB_CONNECTION);\n    com2.Parameters.Add(new OleDbParameter("", DIPerson.ID));\n    com2.Parameters.Add(new OleDbParameter("", "DI"));\n    com2.Parameters.Add(new OleDbParameter("", DateTime.Now.TimeOfDay));\n\n    com2.ExecuteNonQuery();\n}	0
10885974	10885750	Trimming ASP.NET Hyperlink Variables	NavigateUrl='<%# String.Format("AllAudits.aspx?model={0}&date={1}",\nEval("MODEL_NUMBER").ToString().Trim(), Eval("RECORD_DATE").ToString().Trim())%>'\nText='<%# Eval("MODEL_NUMBER") %>'	0
5721422	5720770	How to extract attribute from a XML field with Subsonic?	System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(MyTable.myXmlField); //MyTable entitie created by subsonic.\ndoc.SelectSingleNode("./row/@myAttribute").Value //Here I get the attribute from the XML field.	0
4724953	3345145	How to modify select parts of default chart style?	lineStyle.Setters.Add(new Setter(DataPoint.Background, Brushes.Black));	0
8244058	8243937	Linq to XML select distinct value from	XNamespace rs = "urn:schemas-microsoft-com:rowset";\nXNamespace z = "#RowsetSchema";\n\nXDocument doc = XDocument.Load(...);\n\nvar result = doc.Element(rs + "data")\n                .Elements(z + "row")\n                .Select(e => (string)e.Attribute("ows_Country"))\n                .Distinct()\n                .ToList();	0
19811987	19807918	How to know if datapager causes postback	for (int i = 0; i < page.Request.Form.Keys.Count; i++)\n        {\n            if (page.Request.Form.Keys[i].Contains("GelleryImagesPager"))\n            {\n               ...\n                break;\n            }\n        }	0
32244614	32225979	How to retrieve an Image in Bitmap format from the Media Library	var item = new Sitecore.Context.Database.GetItem(imageId);\nvar mediaItem = Sitecore.Data.Items.MediaItem(item);\nvar image = new System.Drawing.Bitmap(mediaItem.GetMediaStream());	0
1817149	1817108	.NET Regex Expression For Finding & Replacing Any ProductName Value In A .vdproj File In C#	Regex productNameExpression = new Regex(@"(?:\""ProductName\"" = \""8:.*)");	0
1536174	1536040	Dynamically add WebUser Controls in a loop	sharedUC uc = (sharedUC)LoadControl("~/sharedUC/control.ascx");\nplcContent.Controls.Add(uc);	0
22954468	22944449	Asp.net Membership provider with custom textboxes to login	bool isLogin = Membership.ValidateUser(loginUser.UserName, loginUser.Password);	0
394016	394005	Windows application	MyOtherInstantiatedForm.CustomerID = CurrentCustomerID;	0
33004943	33004868	Access form objects from a partial class	namespace Project1\n{\n    partial class Form1\n    {\n        label1. //nope!\n\n        public void CodeGoesInHere()\n        {\n            label1.Text = "hello"; // yep!\n        }\n    }\n}	0
24098787	24072393	Double Clicking marker google maps api c# ios	mapView.TappedMarker = (map, marker) => {\n\n//Change the title\n\nmapView.SelectedMarker = null;\nreturn false;\n}	0
227961	222572	Sorting a DropDownList? - C#, ASP.NET	DataView dvOptions = new DataView(DataTableWithOptions);\ndvOptions.Sort = "Description";\n\nddlOptions.DataSource = dvOptions;\nddlOptions.DataTextField = "Description";\nddlOptions.DataValueField = "Id";\nddlOptions.DataBind();	0
16670157	16670019	Regex starting with a string	string input = "TEST^AB^^HOUSE-1234~STR2255";\nvar matches = Regex.Matches(input, @"TEST\^AB\^\^(.+?)~").Cast<Match>()\n                .Select(m => m.Groups[1].Value)\n                .ToList();	0
7695872	7695865	How do I implement a LINQ-type IComparer<T> overload where T implements IComparable<T>?	Comparer<T>.Default	0
16520308	16518745	How to prevent asterisk with Enter is pressed inside C# /* */ comments	Text Editor > C# > Advanced > Generate XML documentation comments for ///	0
12953395	12951824	Threading model of Windows Store application	public async List<Foo> GetMyFooData()\n{\n    return await _myWebService.GetFooData();\n}	0
7475572	7475536	Parsing a CSV with comma in data	IEnumerable<string> LineSplitter(string line)\n{\n    int fieldStart = 0;\n    for(int i = 0; i < line.Length; i++)\n    {\n        if(line[i] == ',')\n        {    \n            yield return line.SubString(fieldStart, i - fieldStart);\n            fieldStart = i + 1;\n        }\n        if(line[i] == '"')\n            for(i++; line[i] != '"'; i++) {}\n    }\n}	0
15676915	15666960	How can I create a custom styled EntryElement with MonoTouch.dialog?	public override UITableViewCell GetCell(UITableView tableView) {\n    var cell = base.GetCell(tableView);\n    cell.BackgroundColor = _colour;\n    return cell;\n}	0
2729258	2729201	Mapping a BigInteger to a circle	BigInteger number;\nvar angle = ((double)number / Math.Pow(2, 160)) * TwoPi;	0
13338250	13338185	String was not recognized as a valid DateTime using C#	DateTime.ParseExact(gr.Cells[10].Text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);	0
18699303	18699283	Remove Last and begin specific character from String	input.Trim(";".ToCharArray())	0
18486141	18485561	Update the selected dropdownlist value base on value from another linq query	List<SelectListItem> selectlist = ViewData["dropDown_Color"] as List<SelectListItem>;\n            selectlist.ForEach(x =>\n            {\n                x.Selected = x.Value == userPref.color;\n\n            });	0
11575338	11575328	get html source through proxy	string source = GetPageSource("http://www.stackoverflow.com");\n\n    private string GetPageSource(string url)\n    {\n        string htmlSource = string.Empty;\n        try\n        {\n            System.Net.WebProxy myProxy = new System.Net.WebProxy("Proxy IP", 8080);\n            using (System.Net.WebClient client = new System.Net.WebClient())\n            {\n                client.Proxy = myProxy;\n                client.Proxy.Credentials = new System.Net.NetworkCredential("username", "password");\n                htmlSource = client.DownloadString(url);\n            }\n        }\n        catch (WebException ex)\n        { \n            // log any exceptions\n        }\n        return htmlSource;\n    }	0
8167095	8166862	Convert JSON as String to DataTable in C#	{\n    "List": [\n        {\n            "ProjectId": 504,\n            "RowId": 1,\n            "ProjectName": "Google",\n            "Member": "Private"\n        },\n        {\n            "ProjectId": 503,\n            "RowId": 2,\n            "ProjectName": "Facebook",\n            "Member": "Public"\n        }\n    ]\n}	0
18055866	18052758	How to set font-size of text box in bounded fields of grid view template fields?	TextBox txtTextBox1 = RowObject.FindControl("TextBox1");\ntxtTextBox1.Style["font-size"] = sTextSize + "px";	0
22077185	22077060	How to save '<' sysmbol in MSSQL daba fetching data from the textbox	const string sql = "INSERT INTO EXAMS VALUES (@question, @op1, @op2, @op3, @op4, @ans)";\nusing (var cmd = new SqlCommand(sql, conn))\n{\n    cmd.Parameters.Add(new SqlParameter("@question", question.text));\n    cmd.Parameters.Add(new SqlParameter("@op1", op1.text));\n    cmd.Parameters.Add(new SqlParameter("@op2", op2.text));\n    cmd.Parameters.Add(new SqlParameter("@op3", op3.text));\n    cmd.Parameters.Add(new SqlParameter("@op4", op4.text));\n    cmd.Parameters.Add(new SqlParameter("@ans", ans.text));\n    foreach (var parameter in cmd.Parameters.Cast<SqlParameter>().Where(parameter => parameter.Value == null))\n        parameter.Value = DBNull.Value;\n    cmd.ExecuteNonQuery();\n}	0
22966859	22964515	Converting StreamWriters to StreamReader	Stream.CopyToAsync	0
30622287	30574787	Authorization in Cloud Applications using AD Groups issue with new group	var groups = GraphUtil.GetMemberGroups(context.AuthenticationTicket.Identity).Result;\n                        //For each group, we have its, ID, we need to get the display name, and then we have to add the claim\n                        foreach(string groupid in groups)\n                        {\n                            var displayname=GraphUtil.LookupDisplayNameOfAADObject(groupid, context.AuthenticationTicket.Identity);\n                            context.AuthenticationTicket.Identity.AddClaim(new Claim("roles", displayname));\n                        }	0
7922903	7922890	In C#, Parse string into individual characters	Char[] letters = word.ToCharArray();	0
8129294	8129154	How to get text off a webpage?	HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();\n    HtmlAgilityPack.HtmlDocument doc = web.Load("Yor Path(local,web)"); \n    var result=doc.DocumentNode.SelectNodes("//body//text()");//return HtmlCollectionNode\n    foreach(var node in result)\n    {\n        string AchivedText=node.InnerText;//Your desire text\n    }	0
10713352	10713126	Architecture to Save word documents with search options	Regex.Replace(dBFieldOfWordXMLData, @"<[^>]*>", string.Empty);	0
5000231	5000223	How to create two constructor overloads, both taking only one string parameter?	class MyObject\n{\n    public MyObject(FileInfo file) { /* etc... */ }\n    public MyObject(string content) { /* etc... */ }\n}\n\n...\n\nMyObject o = new MyObject(new FileInfo(filename));	0
9706881	9704736	Taking the selected value CardNumber a combo box on form1 to form2	Form2 frm2;                 \nfrm2 = new Form2(); \nfrm2.PIN =  pin;               \nfrm2.ShowDialog();	0
14949070	14945176	Why isn't AutoDetectChangesEnabled set to false by default?	var mycontext = new DemoContext();\nvar myEntity = myContent.Thinhymybobs.find(akey);\nmyEntity.PropX = newvalue;\nmycontext.saveChnages();	0
22185081	5615538	Parse a date string into a certain timezone (supporting daylight saving time)	public DateTimeOffset ParseDateExactForTimeZone(string dateTime, TimeZoneInfo timezone)\n{\n    var parsedDateLocal = DateTimeOffset.ParseExact(dateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);\n    var tzOffset = timezone.GetUtcOffset(parsedDateLocal.DateTime);\n    var parsedDateTimeZone = new DateTimeOffset(parsedDateLocal.DateTime, tzOffset);\n    return parsedDateTimeZone;\n}	0
7163586	7146864	Normalize a System.Decimal - strip trailing zeros	public static class DecimalEx\n{\n    public static decimal Fix(this decimal value)\n    {\n        var x = value;\n        var i = 28;\n        while (i > 0)\n        {\n            var t = decimal.Round(x, i);\n            if (t != x)\n                return x;\n            x = t;\n            i--;\n        }\n        return x;\n    }\n}	0
1445851	1445845	Linq query to exclude from a List when a property value of List of different type are equal?	var MyFees = from c in ctx.Fees\n             where !ExcludedFeeIDs.Contains(c.FeeID)\n             select c;	0
22243007	22241233	Winforms Listbox databinding to list of files in a directory	IList<FileInfo> myList = new List<FileInfo>();\n        FileInfo test1 = new FileInfo(@"G:\test.xls");\n        myList.Add(test1);\n\n        listBox1.DisplayMember = "Name";\n        listBox1.ValueMember = "FullName";\n        listBox1.DataSource = myList;	0
30231540	30231226	Can we turn on/Off monitor with respect to time intervals in windows 8?	System.Timers.Timer timer = new System.Timers.Timer();\n    TimeSpan tsDifference = DateTime.Parse("06:00 pm").Subtract(DateTime.Now);\n    timer.Interval= (double)((tsDifference.Hours * 60 * 60) + (tsDifference.Minutes * 60) + (tsDifference.Seconds)) * 1000 + (tsDifference.Milliseconds);    \n    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n    timer.Enabled=true;\n\n      void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n            {\n               //turn off your monitor\n             }	0
535839	535741	How to name fields using Dynamic Linq?	var v = db.items.Select("new (item_name as name,item_price as price)");	0
14894061	14893966	Concatenate two DataTables	Datatable1.Columns.Add("city", typeof(string));\nDatatable1.Columns.Add("country", typeof(string));\n\nfor (int i = 0; i < Datatable1.Rows.Count; i++)\n{\n    Datatable1.Rows[i][2] = DataTable2.Rows[i][0].toString();\n    Datatable1.Rows[i][3] = DataTable2.Rows[i][1].toString();\n}	0
14998555	14997626	Dictionary thread lambda add	new Thread(\n  (temp_bot) =>\n    {\n      int crashes = 0;\n      while (crashes < 1000)\n      {\n        try\n        {\n           temp_bot = new Bot(config, sMessage, ConvertStrDic(offeredItems),\n           ConvertStrDic(requestedItems), config.ApiKey,\n             (Bot bot, SteamID sid) =>\n               {\n                 return (SteamBot.UserHandler)System.Activator.CreateInstance(\n                 Type.GetType(bot.BotControlClass), new object[] { bot, sid });\n               },\n             false);\n        } \n      catch (Exception e)\n      {\n        Console.WriteLine("Error With Bot: " + e);\n        crashes++;\n      }\n    }\n  }\n).Start();	0
9259135	9258992	How to check the node exists in xml and returns the string values by reading CDATA values	XmlDocument xml = new XmlDocument();\nxml.LoadXml(strXML);\n\nXmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xml.NameTable);\nxmlnsManager.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");\n\nXmlNodeList res = xml.SelectNodes("//tcm:Line/text()", xmlnsManager);\n\n\nforeach (XmlNode item in res)\n{\n    Console.WriteLine(item.InnerText);\n}	0
4449504	4449452	How to convert smallint of t-sql to integer in c#?	int intFromSmallInt = Convert.ToInt16(smallint);	0
25337377	25337346	retrieving a value from database then apply a split function on that	protected void Button2_Click(object sender, EventArgs e)\n {\n    string st = "SELECT F_L FROM split_master";\n    cmd = new SqlCommand(st, sqlcon);\n    cmd.Connection.Open();\n    SqlDataReader sqlread = cmd.ExecuteReader();\n    cmd.Connection.Close();\n    while(sqlread.Read()){\n        string[] word = sqlread["F_L"].ToString().Split();\n        for (int count = 0; count <= word.Length; count++)\n        {\n            MessageBox.Show(word[count]);\n        }\n    }\n  }	0
7744278	7744039	Query syntax instead loop with list<Process> difficult with translation	var processList = from p in Process.GetProcesses(machine)\n where p.MainWindowTitle.Contains(patternTitle)\n select p;	0
15332934	15332842	Getting trouble in Login Page 3-Tire architecture	public static int login(string userlogin, string pwdlogin)\n{\n        SqlConnection con = new SqlConnection();\n        con.ConnectionString = GetConnectionString();\n        con.Open();\n        int id = 0;\n        string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";\n        SqlCommand cmd = new SqlCommand();\n        cmd.CommandText = selectstr;\n        cmd.CommandType = System.Data.CommandType.Text;\n        cmd.Connection = con;\n        SqlDataReader reader = cmd.ExecuteReader();\n        while (reader.Read())\n        {\n               id++; \n        }\n        cmd = null;\n        reader.Close();\n        con.Close();\n        return id;\n}	0
853392	853349	how to authenticate ldap when not joined to a domain in Microsoft Active Directory using c#	DirectoryEntry entry = new DirectoryEntry("LDAP://server-name/DC=domainContext,DC=com");\nentry.Username = @"DOMAIN\account";\nentry.Password = "...";\nDirectorySearcher searcher = new DirectorySearcher(entry);\nsearcher.Filter = "(&(objectClass=user)(sn=Jones))";\nSearchResultCollection results = searcher.FindAll();	0
21936084	21936064	extract substring after the first underscore	string newfilename = file.Substring(file.IndexOf('_') + 1);	0
14749297	14749192	Accessing text box from other thread	delegate void SetTextCallback(TextBox textBox, string text);\nprivate void SetText(TextBox textBox, string text)\n{\n    if (textBox.InvokeRequired)\n    {\n        SetTextCallback d = new SetTextCallback(SetText);\n        this.Invoke(d, new object[] {textBox, text});\n    }\n    else\n    {\n        textBox.Text = text;\n    }\n}	0
13974352	13974051	Default platform in msbuild	msbuild.exe /property:Configuration=Debug;Platform=x64 App.sln	0
9737689	9737449	How to add page into Navigation stack?( Windows Phone)	public MainPage()\n{\n    InitializeComponent();\n\n    this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(MainPage_BackKeyPress);\n}\n\nvoid MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)\n{\n    e.Cancel = true;\n\n    Dispatcher.BeginInvoke(() =>\n    {\n        NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));\n    });\n}	0
16198548	16196946	Binding a queue<double> with the PointAndFigure Chart	this.chart1.Series.Add("Series1");\nthis.chart1.Series["Series1"].Points.DataBindY(myQ);	0
14290580	14290361	How can I run a C# program on my school's Linux server?	/usr/local/lib/mono/  ; various things here	0
3345973	3345292	MVVM and DI - How to handle Model objects?	class NoteViewModel : PropertyChangedBase, IHasSubject<Note> {\n  ...   \n} \n\nmyNoteViewModel = ... //obtain an instance\nmyNoteViewModel.WithSubject(new Note());	0
5562338	5562313	How to design a class with nested property? c#	class Class1\n{\n    public Class2 property1\n    {\n        get\n        {\n            return new Class2();\n        }\n    }\n}\n\nclass Class2\n{\n    public some_type property2\n    {\n        get\n        {\n            return some_value;\n        }\n    }\n}	0
24014612	24001831	Custom Made inputTextBox is flickering	if (!lastKeyboard.IsKeyUp(key))\n{\n    continue;\n}	0
1602725	1602707	Force a logged in user to re-login by invalidating his session	if(Application["SuspendedUsers"].Contains(Session["UserID"]) {\n  Session["IsSignedIn"] = false;\n  Application["SuspendedUsers"].Remove(Session["UserID"]);\n}	0
20017102	19989420	AutoMapper IEnumerable mapping bug	mappedItem.InstitutionsImplantations.Institution.InstitutionsImplantations = null;	0
12958475	12958394	Replace XML attributes	XDocument doc = XDocument.Load("doc.xml");\nvar attributes = doc.Descendants().Attributes("translatedID");\n\nforeach (var attribute in attributes)\n{\n    attribute.Value = DoSomethingWith(attribute.Value);\n}\n\ndoc.Save("transformed.xml");	0
22601765	22601546	Using regex to get the string between each back slash	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main()\n    {\n    // ... Input string.\n    string input = "C:\Development\TestEnvironment\VIdeo\MyVideo.mp3";\n\n    // ... One or more digits.\n    Match m = Regex.Match(input, "(?i)(?x)\\\\([\\w\\.]+)");\n\n    // ... Write value.\n    Console.WriteLine(m.Value);\n    }\n}	0
22701198	22701079	Using Model value includes quotation ASP MVC4	var someObj = @Html.Raw(Json.Encode(someValue));	0
8607776	8607621	Download attachment from email	using(Pop3 pop3 = new Pop3())  \n {  \n     pop3.Connect("server");  \n     pop3.UseBestLogin("user", "password");  \n     foreach (string uid in pop3.GetAll())  \n     {  \n         IMail email = new MailBuilder()\n         .CreateFromEml(pop3.GetMessageByUID(uid));  \n         Console.WriteLine(email.Subject);  \n         // save all attachments to disk  \n         email.Attachments.ForEach(mime => mime.Save(mime.SafeFileName));  \n     }  \n     pop3.Close();  \n }	0
5107327	5107302	HtmlAgility - Save parsing to a string	htmlDoc.DocumentNode.OuterHtml	0
345568	344964	How do I use databinding with Windows Forms radio buttons?	[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n        public bool Bar {\n            get {\n                try {\n                    return ((bool)(this[this.tableradio.BarColumn]));\n                }\n                catch (global::System.InvalidCastException e) {\n                    throw new global::System.Data.StrongTypingException("The value for column \'Bar\' in table \'radio\' is DBNull.", e);\n                }\n            }\n            set {\n                this[this.tableradio.BarColumn] = value;\n                this[this.tableradio.FooColumn] = !value;\n            }\n        }	0
7569258	7569212	How to bind to an owning window's control-property (from a dialog window)?	MyWin1 = new Window1 {\n  DataContext = this.DataContext,\n  Owner = this \n};\nMyWin1.ShowDialog();	0
23992243	23992182	How to create a connection to sql	public DataTable GetData(string textboxvalue)\n    {\n        DataTable data = new DataTable();\n        using (var conn = new SqlConnection("Your connection string"))\n        {\n            SqlCommand command = new SqlCommand("SELECT * FROM StudentInfoTable where Name=@Name", conn);\n            command.Parameters.Add("@Name", SqlDbType.NVarChar, 15).Value = textboxvalue;\n            SqlDataAdapter da = new SqlDataAdapter(command);\n            da.Fill(data);\n        }\n        return data;\n    }	0
10119173	10119102	Best algorithm on checking a node in a tree path?	public bool Search(TreeNode node, string searchString)\n{\n   if(node.Value == searchString) return true;\n   foreach(var childNode in node.Children)\n     if(Search(childNode, searchString)) return true;\n   return false;\n}	0
649466	649263	Injecting non-primative types without wrapping them in an inteface in StructureMap	x.ConstructedBy(y => new DateTimeGenerator(\n          "DateTime", DateTime.Now.AddMonths(-1), 60\n         )\n   ).WithName("DateTime");	0
2058684	2058639	Parsing a Date Like "Wednesday 13th January 2010" with .NET	string value = "Wednesday 13th January 2010";\nDateTime dt;\nDateTime.TryParseExact(\n    Regex.Replace(value, @"(\w+ \d+)\w+ (\w+ \d+)", "$1 $2"),\n    "dddd d MMMM yyyy", \n    DateTimeFormatInfo.InvariantInfo, \n    DateTimeStyles.None, out dt);	0
31255051	31254978	Transform collection of objects to a collection of tuples	public static IEnumerable<Tuple<T, T>> ToTuples<T>(this IEnumerable<T> objects)\n  {\n     IEnumerator<T> enumerator = objects.GetEnumerator();\n     while (enumerator.MoveNext())\n     {\n        T object1 = enumerator.Current;\n        if (enumerator.MoveNext())\n        {\n           yield return Tuple.Create(object1, enumerator.Current);\n        }\n     }\n  }	0
23737305	23737239	How to replace null by "NULL" in a List<string> without foreach loop?	src.Select(s => s ?? "NULL").ToList();	0
18181041	18181022	Exclude regex group value	\w*\|(?!220\|)(?<PORT>\w*)\|(?<NAME>\w*)\|\n     ^^^^^^^^^	0
18095078	18094951	How to set the properties for a dynamically created table row?	TableRow row1 = new TableRow();\n    row1.CssClass = "rowStyle1";\n\n    TableCell cell1 = new TableCell();\n    cell1.CssClass = "cellStyle1";\n\n\n//create css class as below in your css file :\n\n.rowStyle{\n    border:1px solid red;\n}\n.cellStyle1{\n    background-color:blue;\n}	0
5925971	5925941	grid view display image	void gridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n\n   if(e.Row.RowType == DataControlRowType.DataRow)\n   {\n       int type = int.Parse(e.Row.Cells[typeCellIndex].Text);\n       Image img = (Image) e.Row.Cells[imageCellIndex].FindControl(imageID);\n       switch type\n       {\n          case 1:\n          {\n             img.ImageUrl = "avtivity_choise.jpg";\n          }\n          ......\n       }\n\n   }\n\n }	0
5658101	5657487	C# OAuth 2.0 Library - How to Implement the Domain Model	include MyOpenAuth	0
21789895	21789859	How to state timezone in DateTime to get date and month	DateTime td = DateTime.UtcNow():	0
15767963	15767066	Get Session ID for a Selenium RemoteWebDriver in C#	class  CustomeRemoteDriver : RemoteWebDriver\n{    \n    public CustomRemoteDriver(Uri uri, DesiredCapabilities capabilities) \n    : base(uri, capabilities)\n    { \n    } \n\n    public SessionId getExecutionID() \n   { \n      return ((CustomRemoteDriver)Driver.Browser.driver).SessionId; \n   } \n}	0
17994655	17994453	Showing a hidden WPF window	this.visibility = Visibility.Collapsed;    \n...    \nthis.visibility = Visibility.Visible;	0
21534513	21534427	Datetime C#: Subtracting time off of exsisting time	DateTime before = CurrentTime.AddSeconds(-3);	0
7262736	7262518	Problem with datagrid view button column	if (DataGridView1.Columns[e.ColumnIndex] is DataGridViewButtonColumn && cellEvent.RowIndex != -1)\n{\n    DataRow currRow = DataGridView1.Rows[e.RowIndex];\n    SendValuesSomewhereElse(Convert.ToString(currRow[1]), Convert.ToString(currRow[2]), Convert.ToString(currRow[3]));\n}	0
2906737	2906706	How do I get my current DNS Server in C#?	IPInterfaceProperties.DnsAddresses	0
11958724	11958645	Best loop for cracking passwords	exApp.Workbooks.Open	0
1953801	1953771	C# On_buttonClick, remove null contents from listbox	for (int i = listBox.Items.Count - 1; i >= 0; i--) {\n    if (String.IsNullOrEmpty(listBox.Items[i] as String))\n        listBox.Items.RemoveAt(i);\n}	0
753777	753732	How to enumerate column names with NHibernate?	var columns = typeof(TheClass).GetProperties()\n    .Where(property => property.GetCustomAttributes(typeof(ColumnNameAttribute), false).Count > 0)\n    .Select(property => property.Name);	0
12491626	12491005	What is the easiest way to add a custom icon to an application using monodevelop?	Project Menu -> <project name> Options	0
4616954	4608122	ArgumentNullException by IpcClientChannel - Parameter name: URI	RemotingConfiguration.RegisterWellKnownClientType(typeof(Connector), "ipc://connector/connector");	0
26769264	26768843	Split String in get set function	private string[] z_multiChoiceOptions = null;\n    public string[] multiChoiceOptions\n    {\n        get\n        {\n            return this.z_multiChoiceOptions;\n        }\n\n    }\n\n    private string z_Options = null;\n    public string Options\n    {\n        get { return z_Options; }\n        set { \n            z_Options = value;\n            if (value != null)\n                this.z_multiChoiceOptions = Regex.Split(value, "\r\n");\n            else\n                this.z_multiChoiceOptions = null;\n        }\n    }	0
30729593	30727449	Comparing two decimals	var valOne = 1.1234560M; // Decimal.Round(1.1234560M, 6);  Don't round.\nvar valTwo = 1.1234569M; // Decimal.Round(1.1234569M, 6);  Don't round\n\nif (Math.Abs(valOne - valTwo) >= 0.000001M) // Six digits after decimal in epsilon\n{\n    Console.WriteLine("Values differ");\n}\nelse\n{\n    Console.WriteLine("Values are the same");\n}	0
3070205	3070060	Save Bitmap image in a location in C#	st = GdipSaveImageToFile( img, sd.FileName, ref clsid, IntPtr.Zero );	0
14511035	14510975	c# assign string value based on bool value which can be nullable	stringValue = BoolValue.HasValue ? BoolValue.Value ? "True" : "False" : null;	0
11259422	11258825	How to get actual URL from a list of routes?	var path = RouteTable.Routes[item.Link];\n Route ruta = path as Route;\n var link = ruta.RouteHandler as PageRouteHandler;\n if (link.VirtualPath.ToString().ToLower().Contains("~/displaycmspage.aspx?pagename="))\n {\n      //do work on url here\n }	0
25288121	25287882	how to switch from one tab to another tab Xamarin IOS	this.TabBarController.SelectedIndex = 4;	0
7384269	7384211	Formatting MAC address in C#	mac = string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());	0
2327612	2327594	Declaration of Anonymous types List	static List<T> CreateListFromSingle<T>(T value) {\n  var list = new List<T>();\n  list.Add(value);\n  return list;\n}\n\nvar list = CreateListFromSingle(\n   new{Name="Krishna", \n                 Phones = new[] {"555-555-5555", "666-666-6666"}}\n                );	0
4271190	4271160	How to pass a null value to a data driven unit test from a CSV file?	string orgOne = testContextInstance.DataRow["OrgOne"].ToString();\nif (orgOne=="null")\n    orgOne = null;	0
7626487	7626472	Assign some data fields to DropDownList item	Item.Value = "VALUE1,VALUE2";\n\nstring[] Values = Item.Value.Split(',');\n\ntxt1.Text = Values[0];\ntxt2.Text = Values[1];	0
660666	660657	Parse directory name from a full filepath in C#	new FileInfo(@"C:\temp\temp2\foo\bar.txt").Directory.Name	0
31941478	31941127	Change selection in ComboBox automatically	private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgse)\n{\n      ComboBox2.SelectedIndex = (sender as ComboBox).SelectedIndex;\n}	0
18227324	18226034	Handling JSON varriable vithout property	public class Schedule\n{\n    [JsonProperty("jsonrpc")]\n    public string Jsonrpc { get; set; }\n    [JsonProperty("id")]\n    public string Id { get; set; }\n    [JsonProperty("result")]\n    public Dictionary<string, Datas> Result { get; set; }\n}\n\npublic class Datas\n{\n    public IEnumerable<string> Notifications { get; set; }\n    public IEnumerable<string> Events { get; set; }\n    public IEnumerable<string> Lectures { get; set; }\n\n}	0
25942268	25942201	Creating new files in groups in new folders are inconsistent	Parallel.For(0, sourceline.Length, x =>\n{\n    string folder = ((int)(Array.IndexOf(sourceline, sourceline[x]) / bs)).ToString();\n\n    //i call a function here to go retrieve my document\n}	0
15860143	15860098	Dynamically assigned a Label Value and display a messages when values changes	txtDisplayData.TextChanged += (sender, e) => {\n    myLabel.Text = "Value changed to " + (sender as TextBox).Text;\n}	0
2052150	2048540	Hosting CLR in Delphi with/without JCL - example	ov := obj.Unwrap;	0
4725983	4725384	Programmatically uncheck checkboxcolumn in datagridview	(row.Cells[CheckBoxColumn.Index] as DataGridViewCheckBoxCell).value = false;	0
11475455	11475347	represent Memory Stream as a physical file	kernal.dll	0
12581238	12581088	How to add TemplateField programmatically	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    { \n        var linkField = new TemplateField();\n        linkField.ItemTemplate = new LinkColumn();\n        GridView1.Columns.Add(linkField);\n    }\n}\n\n\nclass LinkColumn : ITemplate\n{\n    public void InstantiateIn(System.Web.UI.Control container)\n    {\n        LinkButton link = new LinkButton();\n        link.ID = "linkmodel";\n        container.Controls.Add(link);\n    }\n}	0
33562406	33561767	What is a good algorithm in C# to find if there exists I,J,K such that 8*I+J*12+K*15=S for some S?	private static Boolean ScoreAddsUp(int score, int[] incs) {\n  HashSet<int> completed = new HashSet<int>();\n\n  List<int> frontier = new List<int>() {\n    0\n  };\n\n  while (frontier.Any(item => item <= score)) {\n    for (int i = frontier.Count - 1; i >= 0; --i) {\n      int front = frontier[i];\n\n      frontier.RemoveAt(i);\n      completed.Add(front);\n\n      foreach (int inc in incs) {\n        int item = front + inc;\n\n        if (item == score)\n          return true;\n\n        if (completed.Contains(item))\n          continue;\n\n        frontier.Add(item);\n      }\n    }\n  }\n\n  return false;\n}\n\n// Tests\nif (!ScoreAddsUp(29, new int[] { 8, 12, 15 }))\n  Console.Write("Not Found");\n\nif (ScoreAddsUp(28, new int[] { 8, 12, 15 }))\n  Console.Write("Found");	0
11551661	11551655	How can I visualize the way various DateTime formats will display?	DateTime.Now.ToString("D") displays "Wednesday, July 18, 2012"\nDateTime.Now.ToString("d") displays "7/18/2012"\nDateTime.Now.ToString("F") displays "Wednesday, July 18, 2012 3:57:13 PM"\nDateTime.Now.ToString("f") displays "Wednesday, July 18, 2012 3:57 PM"\nDateTime.Now.ToString("G") displays "7/18/2012 3:57 PM"\nDateTime.Now.ToString("g") displays "7/18/2012 3:57:30 PM"\nDateTime.Now.ToString("M") displays "July 18"\nDateTime.Now.ToString("R") displays "Wed, 18 Jul 2012 15:57:55 GMT"\nDateTime.Now.ToString("s") displays "2012-07-18T15:58:02"\nDateTime.Now.ToString("T") displays "3:56:38 PM"\nDateTime.Now.ToString("t") displays "3:56 PM"\nDateTime.Now.ToString("U") displays "Wednesday, July 18, 2012 10:58:09 PM"\nDateTime.Now.ToString("u") displays "2012-07-18 15:58:17Z"\nDateTime.Now.ToString("Y") displays "July, 2012"\nDateTime.Now.ToString("42") displays "42"	0
10587221	10586667	How to print serial number to Crystal Reports - WPF C#	begin transaction;\n\nretrieve and increment transaction #;\n\nopen report;\n\npass transaction # to report (via a parameter would be easiest);\n\nprint report;\n\nif report prints successfully then\n  commit;\nelse\n rollback;\nend if	0
5006270	5002942	How can I resize the parent control from a child control's resize event?	// at your custom panel level...\nprivate Boolean AmIResizing = false\n\nprivate void panel_Resize(object sender, System.EventArgs e) \n{ \n    if(AmIResizing)\n      return;\n\n    // set flag so it immediately gets out after first time started\n    AmIResizing = true;\n\n    // do your other resizing\n    // The settings here will otherwise force your recursive form level resizing calls\n    // but with your up-front check on the flag will get out.\n    // then, when the form is done with it's stuff...\n\n\n    // Now, clear the flag\n    AmIResizing = false;\n\n}	0
2477761	2477712	Convert local time (10 digit number) to a readable datetime format	DateTime startDate = new DateTime(1970, 1, 1);\nDateTime time = startDate.AddSeconds(1268927156 );	0
32240913	32240769	How to always get the website title without downloading all the page source	request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;	0
7879725	7879084	WPF Application - Press F1 to open Help in a browser (not with CHM file)	System.Diagnostics.Process.Start(@"[the url]");	0
20592268	20591841	How to Get the Selected Item of a ListPicker	var item = (sender as ListPicker).SelectedItem;	0
10927823	10927782	copy all type format file from folder in c#	string sourcePath = @"E:\test222";\nstring targetPath =  @"E:\TestFolder";\n\nforeach (var sourceFilePath in Directory.GetFiles(sourcePath))\n{\n     string fileName = Path.GetFileName(sourceFilePath);\n     string destinationFilePath = Path.Combine(targetPath, fileName);   \n\n     System.IO.File.Copy(sourceFilePath, destinationFilePath , true);\n}	0
13513513	13513488	Combobox selection to text file	string PathToFile = "c:\\File.txt";\n    System.IO.File.WriteAllText(PathToFile,Combobox.SelectValue.ToString());	0
16391412	16391234	Querying sibling XML nodes only inside a parent node	var points = pathsDocument.Descendants("Point");\n        foreach (var point in points)\n        {\n            var statements = point.Elements("Statement").Select(x => x.Element("StatementString").Value );\n            Console.WriteLine(string.Join(" ", statements.ToArray()));\n        }	0
8634640	8634574	grouping a linq statement, doesnt seem to group	(from d in All() group d by new { d.CustomerNumber, d.CustomerName } into g orderby g.Key.CustomerName select new Test { CustomerNumber = g.Key.CustomerNumber, TransactionAmount = g.Sum(s => s.TransactionAmount), CustomerName = g.Key.CustomerName });	0
10157086	10154046	Making text input in XNA (for entering names, chatting)	public class KbHandler\n{\n    private Keys[] lastPressedKeys;\n\n    public KbHandler()\n    {\n        lastPressedKeys = new Keys[0];\n    }\n\n    public void Update()\n    {\n        KeyboardState kbState = Keyboard.GetState();\n        Keys[] pressedKeys = kbState.GetPressedKeys();\n\n        //check if any of the previous update's keys are no longer pressed\n        foreach (Keys key in lastPressedKeys)\n        {\n            if (!pressedKeys.Contains(key))\n                OnKeyUp(key);\n        }\n\n        //check if the currently pressed keys were already pressed\n        foreach (Keys key in pressedKeys)\n        {\n            if (!lastPressedKeys.Contains(key))\n                OnKeyDown(key);\n        }\n\n        //save the currently pressed keys so we can compare on the next update\n        lastPressedKeys = pressedKeys;\n    }\n\n    private void OnKeyDown(Keys key)\n    {           \n        //do stuff\n    }\n\n    private void OnKeyUp(Keys key)\n    {\n        //do stuff\n    }\n}	0
15922314	15922041	How to validate a decimal number to have precision exactly one?	string input;\ndecimal deci;\nif (input.Length >=3 && input[input.Length - 2].Equals('.') && Decimal.TryParse(input , out deci))\n{\n    // Success\n}\nelse\n{\n    // Fail\n}	0
9466666	9464761	LDAP Authentication only for Admin account	public static bool ValidateCredential(string domain, string userName, string password)\n    {\n        using (var context = new PrincipalContext(ContextType.Domain, domain))\n        {\n            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))\n            {\n                if (user == null) return false;\n\n                using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Admins"))\n                {\n                    if (group == null) return false;\n\n                    foreach (var member in group.GetMembers())\n                    {\n                        if (member.Sid.Equals(user.Sid))\n                        {\n                            return context.ValidateCredentials(userName, password);\n                        }\n                    }\n                }\n            }\n        }\n\n        return false;\n    }	0
11269134	11269054	How to prevent Factory Method pattern causing warning about virtual member call in constructor?	public abstract class Document {\n    protected Document(IEnumerable<Page> pages) {\n        // If it's OK to add to _pages, do not use AsReadOnly\n        _pages = pages.ToList().AsReadOnly();\n    }\n    // ...\n}\n\npublic class Resume : Document {\n    public Resume() : base(CreatePages()) {\n    }\n    private static IEnumerable<Page> CreatePages() {\n        return new Page[] {\n            new SkillsPage(),\n            new EducationPage(),\n            new ExperiencePage()\n        };\n    }\n}	0
6077573	6077538	create an array via loop	readonly string[] _myArray \n    = Enumerable.Range(1, 1000)\n        .Select(i => i.ToString())\n        .ToArray();	0
11629168	11629099	Stringbuilder Formatting	stringBuilder.AppendFormat("{0,16}", number)	0
7769211	7768120	C#, XML - Loading a single XML file into two separate datasets based on a parameter	DataSet dsActive = new DataSet();\ndsActive.ReadXml(UsersXmlReader);\n\nDataSet dsInactive = ds.Copy();//Copy to your another dataset\nRemove(dsActive.Tables[0], "0");//Remove all inactive(where Active = 0) records from dsActive DataSet\nRemove(dsInactive.Tables[0], "1");//Remove all active(where Active = 1) records from dsInactive DataSet\n\nprivate void Remove(DataTable table, string active)\n{\n    for (int i = 0; i < table.Rows.Count; i++)\n    {\n        if (table.Rows[i]["Active"].Equals(active))\n        {\n            table.Rows[i].Delete();\n            i = i - 1;//Removed record so we need to check same index\n        }\n    }\n}	0
11365359	11364883	Parsing a DataGridView - C#	DataSet grid = new DataSet();\n            DataTable table = grid.Tables[0];\n\n            List<string> tableData = new List<string>();\n            foreach (DataRow row in table.Rows)\n            {\n                for (int i = 0; i < table.Columns.Count; i++)\n                {\n                    tableData.Add(row[i].ToString());\n                }\n            }\n\n            tableData.Where(x => x == "TestValue");	0
4067990	4067962	access a static field of a result type of function that has the same name with type	namesapce test {\n      public class A\n        {\n            public static int Num = 1;\n\n        }\n\n        class Programs:A\n        {\n\n            public A A()\n            {\n                Console.WriteLine(test.A.Num);\n                return new A();\n            }\n        }\n}	0
867435	59396	Rhino Mocks: How can I mock out a method that transforms its input?	Expect.Call(() => dao.Save(transaction))\n    .Do(new Action<Transaction>(x => x.IsSaved = true));	0
17862892	17840420	NRefactory: How do I access unresolved Named Arguments on a Property Attribute?	...\nCecilLoader loader = new CecilLoader();\nAssembly[] assembliesToLoad = {\n    ...\n    typeof(System.Data.Linq.Mapping.ColumnAttribute).Assembly\n    ...};\n\nIUnresolvedAssembly[] projectAssemblies = new IUnresolvedAssembly[assembliesToLoad.Length];\nfor(int i = 0; i < assembliesToLoad.Length; i++)\n{\n    projectAssemblies[i] = loader.LoadAssemblyFile(assembliesToLoad[i].Location);\n}\n\nIProjectContent project = new CSharpProjectContent();\nproject = project.AddAssemblyReferences(projectAssemblies);\n...	0
7579339	7555726	Problem retrieving dictionary from Isolated Storage	using System.Runtime.Serialization;\n    [DataContact]\n    public class classname()\n    {\n     [datamember]\n     public int propertyname;\n     }	0
10619654	10619596	Making a WPF TextBox binding fire on each new character?	UpdateSourceTrigger=PropertyChanged	0
10891443	10889768	C# - Read from excel sheet and pass variables into function	while(dr.Read()) {\n    string user = dr[0].ToString();\n    string pass = dr[1].ToString();\n    if(!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass)) \n       CreateUser(user, pass)\n}\ndr.Close()	0
33269898	33269716	How to cast an object of type Object to a object of type T?	return (T)Convert.ChangeType(obj, typeof(T));	0
32091654	32090288	how to build expression tree for multilevel property/child property	Expression bExpression = Expression.Property(Expression.Constant(obj), "B");\nExpression numExpression = Expression.Property(bExpression, "num");\n\nConsole.WriteLine(Expression.Lambda<Func<int>>(numExpression).Compile()());//Prints 5	0
22400864	22400629	Validate number INTEGER on text boxes IN windows forms issue	int i = 0;\nif(!string.IsNullOrEmpty(ChildAge.Text) && \n     !int.TryParse(ChildAge.Text, out i)\n  )\n{\n    MessageBox.Show("Enter Valid Age");\n}	0
29319887	29295274	Windows Phone back button	foreach (PageStackEntry stack in Frame.BackStack)\n{\n //check if stack contains history of the main page. (Solution name: Helloworld)\n if (stack.SourcePageType == typeof(HelloWorld.MainPage))\n   {\n    Frame.Navigate(stack.SourcePageType);\n    break;\n   }\n}	0
8075753	8073699	Trying To Install Windows Services - What's Wrong With This Code?	if (EventLog.SourceExists("YourEventSourceName"))\n    EventLog.DeleteEventSource("YourEventSourceName");	0
27739709	27739032	Text in Textblock to change Dynamically	private TimeSpan time;\nprivate void Timer()\n{\n     DispatcherTimer stopwatch_timer = new DispatcherTimer();\n     stopwatch_timer.Interval = new TimeSpan(0, 0, 0, 1, 0);\n     stopwatch_timer.Tick += new EventHandler(stopwatch_timer_Tick);\n     stopwatch_timer.Start();\n     time = stopwatch_timer.Interval;\n}        \nvoid stopwatch_timer_Tick(object sender, EventArgs e)\n{\n     TimerDisplay.Text = time.ToString();\n     time = time.Add(((DispatcherTimer)sender).Interval);   \n}	0
22756828	19840034	Newtonsoft json Serialize Primitive types WebApi	config.Formatters.Add(new WrappedJsonMediaTypeFormatter());\n\npublic class WrappedJsonMediaTypeFormatter : JsonMediaTypeFormatter\n{\n\n        public WrappedJsonMediaTypeFormatter() \n        {\n            base.SerializerSettings.Culture = new System.Globalization.CultureInfo("en-GB");\n            base.SerializerSettings.DateFormatString = "dd/MM/yyyy";\n        }\n\n        public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)\n        {\n            var obj = value;\n            if (type.IsPrimitive || Object.ReferenceEquals(type, typeof(string)))\n                obj = new { data = value };\n\n            if (Object.ReferenceEquals(value, null))\n                obj = new { };\n\n            return base.WriteToStreamAsync(type, obj, writeStream, content, transportContext);\n        }\n    }	0
33659319	33655546	How can I put a datepicker with mvc5	[DataType(DataType.Date)]\n[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]	0
3748483	3748433	How to add a new row to c# DataTable in 1 line of code?	dt.Rows.Add("Sydney");	0
9280216	9268103	Achieving DI without 3rd party framework	public MyMainPluginClass() : this(FactoryUtility.SetupIOC())\n{\n\n}\n\npublic MyMainPluginClass(IRepo repo)\n{\n\n}\n\npublic static class FactoryUtility\n{\n    private static bool Initialized  = false;\n\n    public static IRepo SetupIOC()\n    {\n        var container = TinyIoCContainer.Current;\n\n        if (!Initialized)\n        {\n            container.AutoRegister(new[] { Assembly.GetExecutingAssembly() });\n\n            Initialized = true;\n        }\n\n        var result = container.Resolve<IRepo>();\n\n        return result;\n    }\n}	0
21402781	21402744	Repeat numbers in List/IEnumerable	var list2 = List1.SelectMany(x => new []{x, x}).ToList();	0
6185666	6185530	Using XMLSerializer deserialise with array of elements the same type as the root element	[XmlRootAttribute("playlist")]\npublic class PlaylistResponse \n{\n    public int id;\n    public string title;\n    public string description;\n\n    [XmlArray(ElementName="childPlaylists")]\n    [XmlArrayItem(typeof(PlaylistResponse), ElementName="playlist")]\n    public PlaylistResponse[] ChildPlaylists;\n}\n\nXmlReader reader = XmlReader.Create(new StringReader(xml)); // your xml above\nXmlSerializer serializer = new XmlSerializer(typeof(PlaylistResponse));\nPlaylistResponse response = (PlaylistResponse)serializer.Deserialize(reader);\n\nint count = response.ChildPlaylists.Length; // 4	0
2650601	2650543	How to suppress a compiler warning in C# without using #pragma?	private string _field = null;	0
22940281	22940203	Both a generic constraint and inheritance	class A<T> : B where T : Person	0
25683753	25683512	C# RichTextBox how to change font ForegroundColor upon printing?	var selection = myRichTextBox.Selection;\nif (!selection.IsEmpty)\nrichTextBox1.SelectionColor = Color.Black;	0
27430294	27081229	Saving an image from the web to the Saved Pictures folder in Windows Phone 8.1 RT C#	var url = "Some URL";\nvar fileName = Path.GetFileName(url.LocalPath);\nvar thumbnail = RandomAccessStreamReference.CreateFromUri(url);\n\nvar remoteFile = await StorageFile.CreateStreamedFileFromUriAsync(fileName, url, thumbnail);\nawait remoteFile.CopyAsync(KnownFolders.SavedPictures, fileName, NameCollisionOption.GenerateUniqueName);	0
9703149	9702950	How to call the appropriate parameter on	EditHyperLink\n      .NavigateUrl("EditUserInfo.aspx?key=" + DataBinder.Eval(e.Row.DataItem,"UserCode"),650, 500, true);	0
15617087	15616932	Convert string array to custom object list using linq	string[] randomArray = new string[3] {"1", "2", "3"};\nList<CustomEntity> listOfEntities = randomArray.Select(item => new CustomEntity() { FileName = item } ).ToList();	0
16698859	16698828	Set same properties to several labels	label1.Text = label2.Text = label3.Text = "Text";	0
11268236	11267984	BindingSource isn't listening to all items for property changes	private BindingList<ModuleInfo> moduleList = new BindingList<ModuleInfo>();	0
550090	550072	How can i retrieve a connectionString from a web.config file?	VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(@"C:\Inetpub\wwwroot\YourApplication", true);\nWebConfigurationFileMap wcfm = new WebConfigurationFileMap();\nwcfm.VirtualDirectories.Add("/", vdm);\n\n\n// Get the connectionString\nConfiguration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");\nstring connection = config.ConnectionStrings.ConnectionStrings["YourConnectionString"];	0
9191499	9174999	How to create managed object in unmanaged C++ while wrapping it for JNA between Java and C#?	gacutil /i "$(TargetPath)"	0
22815899	22815727	How to swap elements on TableLayoutPanel?	private void SwapCells(Cell tile1, Cell tile2) {\n  Control c1 = tlp.GetControlFromPosition(tile1.Column, tile1.Row);\n  Control c2 = tlp.GetControlFromPosition(tile2.Column, tile2.Row);\n  TableLayoutPanelCellPosition cell1 = tlp.GetCellPosition(c1);\n  tlp.SetCellPosition(c1, tlp.GetCellPosition(c2));\n  tlp.SetCellPosition(c2, cell1);\n}	0
20458867	20458754	Method to output Messagebox messages	private void message(int choice, string result)\n        {\n           if(result == "Draw")\n           {\n            switch (choice)\n            case 1: MessageBox.Show("It is a draw. Both chose Rock");\n            break;\n            case 2: MessageBox.Show("It is a draw. Both chose Paper");\n            break;\n            case 3: MessageBox.Show("It is a draw. Both chose Scissor");\n            break;\n           }\n           //similarly do for the rest.\n        }	0
4857733	4857248	WPF Treeview Expand only to a certain depth?	Action recurse = () => ExpandTree(itm.ItemContainerGenerator, itm.Items, depth);\nitm.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, recurse);  // note the priority	0
6772413	6772361	Deleting items more than 1 day old from sql database	declare @when datetime = GETUTCDATE() - 1\ndelete from ShoppingCarts where DateCreated < @when	0
6357115	6356999	How to place the cursor Exact center of the screen	Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2,\n                            Screen.PrimaryScreen.Bounds.Height / 2);	0
28945515	28945190	C# Linq list with list in datagrid	var q = from m in mainList\n        let i = m.Info.LastOrDefault()\n        select new\n        {\n            m.Name,\n            Info1 = i == null ? null : i.Info1,\n            Info2 = i == null ? null : i.Info2,\n        };	0
12026324	12026138	How to set width for PdfPTable and align table center in page	string pdfpath = Server.MapPath("PDFs");\n        RoundRectangle rr = new RoundRectangle();\n\n        using (Document document = new Document())\n        {\n            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfpath + "/Graphics200.pdf", FileMode.CreateNew));\n            document.Open();\n            PdfPTable table = new PdfPTable(1);\n            table.TotalWidth = 144f;\n\n            table.LockedWidth = true;\n            PdfPCell cell = new PdfPCell()\n            {\n                CellEvent = rr,\n                Border = PdfPCell.NO_BORDER,\n\n                Phrase = new Phrase("test")\n            };\n            table.AddCell(cell);\n            document.Add(table);\n        }	0
18530079	18462064	Associate a private key with the X509Certificate2 class in .net	byte[] certBuffer = Helpers.GetBytesFromPEM(publicCert, PemStringType.Certificate);\nbyte[] keyBuffer  = Helpers.GetBytesFromPEM(privateKey, PemStringType.RsaPrivateKey);\n\nX509Certificate2 certificate = new X509Certificate2(certBuffer, password);\n\nRSACryptoServiceProvider prov = Crypto.DecodeRsaPrivateKey(keyBuffer);\ncertificate.PrivateKey = prov;	0
1469454	1469448	Using Linq find first object in list sorting by property A, then property B	var firstPoint = Points.OrderBy( p => p.X ).ThenBy( p => p.Y ).FirstOrDefault();	0
23970596	23970463	Using DataAnotations to exculde a specific string when posting to an MVC controller	[RegularExpression(@"^((?!asdasd).)*$", ErrorMessage = "'asdasd' is not allowed.")]	0
24249672	24249347	Can you do something like RoutePrefix with parameters?	[RoutePrefix("{projectName}/usergroups")]\npublic class UsergroupController : Controller\n{\n    [Route("")]\n    public ActionResult Index(string projectName)\n    {\n        ...\n    }\n}	0
12569665	12569567	Splitting array of objects and then process it in batches	List<object> rules = GetRules();\nint batchSize = 500;\nint currentBatch = 0;\n\nwhile (currentBatch * batchSize < rules.Count)\n{\n    object[] nextBatch = rules.Skip(currentBatch * batchSize)\n        .Take(batchSize).ToArray();\n    //use batch\n    currentBatch++;\n}	0
29207608	29207509	Get Physical Address(MAC) of Local LAN Networks without using IP in C#	public string GetMacAddress(string ipAddress)\n{\n    string macAddress = string.Empty;\n    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();\n    pProcess.StartInfo.FileName = "arp";\n    pProcess.StartInfo.Arguments = "-a " + ipAddress;\n    pProcess.StartInfo.UseShellExecute = false;\n    pProcess.StartInfo.RedirectStandardOutput = true;\n      pProcess.StartInfo.CreateNoWindow = true;\n    pProcess.Start();\n    string strOutput = pProcess.StandardOutput.ReadToEnd();\n    string[] substrings = strOutput.Split('-');\n    if (substrings.Length >= 8)\n    {\n       macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2)) \n                + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6] \n                + "-" + substrings[7] + "-" \n                + substrings[8].Substring(0, 2);\n        return macAddress;\n    }\n\n    else\n    {\n        return "not found";\n    }\n}	0
5263693	5263612	How to enumerate through the DataTables of a DataSet starting at the second table in the collection using C#	ds.Tables.OfType<DataTable>().Skip(1).ToList().ForEach(ACTION);	0
31006628	31001929	WCF Service - Logging Caller Details	log4net.LogicalThreadContext.Properties["CallerIp"] = ip;	0
8863975	8863782	Handling _bstr_t from byte array and back with C#	var bytes = new byte[] { 0xB5, 0xB8, 0xBF, 0xF2, 0xC3, 0xBC };\nvar output = Encoding.GetEncoding(949).GetString(bytes);	0
9086111	9076876	Save UIImage as png from another thread	if( !File.Exists( filename ) )\n{\n    using( var ns = new NSAutoreleasePool() )\n    {\n        NSError err;\n        using(UIImage img = UIImage.FromFile( path )) {\n            using (var scaled_img = img.Scale( 250,250 )) \n            {\n                //i also add a reflection effect                             \n                using( var reflected_img = scaled_img.AddImageReflection( 0.6f ) )\n                {\n                    using (var data = reflected_img.AsPNG ()) \n                    {\n                        data.Save( filename, true, out err );\n                    }\n                }\n             }\n        }\n    }\n}	0
7649772	7649447	Accessing cells in a gridview	private void MyGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n        {\n            if ((int)MyGridView.Rows[e.RowIndex].Cells[0].Value > 30)\n            {\n                e.CellStyle.BackColor = System.Drawing.Color.Red;\n                e.CellStyle.ForeColor = System.Drawing.Color.White;\n            }\n        }	0
31150687	31150101	programmatically print a web page	private void Button1_Click(object sender, EventArgs e)\n    {\n        PrintHelpPage();\n    }\n\n    private void PrintHelpPage()\n    {\n        // Create a WebBrowser instance. \n        WebBrowser webBrowserForPrinting = new WebBrowser();\n\n        // Add an event handler that prints the document after it loads.\n        webBrowserForPrinting.DocumentCompleted +=\n            new WebBrowserDocumentCompletedEventHandler(PrintDocument);\n\n        // Set the Url property to load the document.\n        webBrowserForPrinting.Url = new Uri(@"http://www.google.com"); //This is what you want to change\n    }\n\n    private void PrintDocument(object sender,\n        WebBrowserDocumentCompletedEventArgs e)\n    {\n        // Print the document now that it is fully loaded.\n        ((WebBrowser)sender).Print();\n\n        // Dispose the WebBrowser now that the task is complete. \n        ((WebBrowser)sender).Dispose();\n    }	0
9928382	9927897	how to make disable or unvisible email link when the it is clicked, also, how can i use general smtp server?	ActivateUser.aspx	0
1046119	1046040	How to properly return T from a generic method while implimenting an interface?	static void CallOutputType<T>(T t) where T : IFoo<T>\n{\n   t.OutputType(t);\n}	0
25291641	25291427	Simple console game, list for calculate sum of each player	int total = 0;\nif(playerDictionary.ContainsKey(playerName))\n    foreach(int score in playerDictionary[playerName])\n        total += score;\n\nConsole.WriteLine(total)	0
6009513	6009502	Linq to SQL - How to sort results from query	var returnall = from p in db.Orders\n                orderby p.ShipName\n                select p.ShipName;	0
9387127	9382111	How do I forcefully disconnect a client in SignalR	void OnReceive(string data)\n{\n    if(data.Equals("exit"))\n    {\n        connection.Stop();\n        return;\n    }\n\n    Console.WriteLine(data);\n}	0
885765	885744	WCF ServiceHost access rights	netsh http add urlacl url=http://+:8000/ServiceModelSamples/Service user=mylocaluser	0
30993929	30993835	C# Windows Form Application - value not printing in textbox for each time	for (int i = 0; i <= 10; i++)\n {\n    textBox1.Text = i.ToString();\n    textBox1.Refresh();\n    Thread.Sleep(100);\n }	0
6964709	6963547	How do you buffer items into groups in Reactive Extensions?	MyObservable\n    .Buffer(TimeSpan.FromSeconds(1.0))\n    .Select(MyList =>\n        MyList.GroupBy(C=>C.EntityID));	0
6406824	6405729	How do I access combo box inside another interface panel in C#?	this.Controls.Find("YourControlName", true);	0
5146049	5145994	How to get WCF RIA SupportsCancelation == true	MyContext ctx = new MyContext();\n\nvar loadOp = ctx.Load<Entity>(ctx.GetEntities());\nloadOp.Cancel();	0
8753451	8743078	How to retrieve member fields from nested classes recursively in C#	public Employee getEmployee() \n{\n    var emp=EmployeeProxy.GetEmployee();         \n    return new Employee {        \n    name=emp.Name,         \n        age=emp.Age,         \n        address=emp.AddressType.Select(a=>new Address{        \n             DoorNum=a.doorNum,        \n             Street=ae.street,        \n             Zip=a.zip,        \n        }),        \n        phones=new Phone[]{        \n             mobile=PhoneType.Mobile,        \n             homePhone=PhoneType.HomePhone,        \n        },        \n        dependents=emp.DependentsType.Select(d=>new Dependents{        \n             name=d.Name,        \n             age=d.Age,        \n             depPhone=new Phone{        \n                     mobile=d.DependentPhone.Mobile,        \n                     homePhone=d.DependentPhone.HomePhone,        \n             },        \n        }),         \n    }; //End of Return        \n} //End of method	0
4495262	4495147	Resizing a grid control programatically over a period of time	DoubleAnimation myDoubleAnimation = new DoubleAnimation();\n        myDoubleAnimation.From = myDict[iIndex].Shell.Width;\n        myDoubleAnimation.To = stack_outter.Width;\n        myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));\n        myDoubleAnimation.AutoReverse = false;\n        myDoubleAnimation.RepeatBehavior = new RepeatBehavior(1.0);\n\n        myStoryboard = new Storyboard();\n        myStoryboard.Children.Add(myDoubleAnimation);\n        Storyboard.SetTarget(myDoubleAnimation, myDict[iIndex].Shell);\n        Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(FrameworkElement.WidthProperty));\n        myStoryboard.Begin(myDict[iIndex].Shell);	0
10098732	10098568	converting iqueryable to IEnumerable	public IEnumerable<TimelineItem> GetTimeLineItems(int SelectedPID)\n   {\n      return db.TimelineItems.Where(tl => tl.ProductID == SelectedPID)\n        .Select( tl => new TimelineItem {\n            Description = tl.Description,\n            Title = tl.Title })\n        .AsEnumerable<TimelineItem>();\n   }	0
5608605	5608581	Looping through a list to find an object with the largest number efficiently!	SomeObject winner;\nfloat maxMass = 0.0f; // Assuming all masses are at least zero!\nforeach(SomeObject o in objects) {\n    if(o.mass > maxMass) {\n        maxMass = o.mass;\n        winner = o;\n    }\n}	0
18023429	18023181	C# Open file of text documents	using System;\nusing System.IO;\n\nnamespace SQLiteEntityMigrator\n{\n    class Program\n    {\n        static void Main()\n        {\n            string pathToDirectory = @"C:\Files";\n            System.IO.DirectoryInfo diDir = new DirectoryInfo(pathToDirectory);\n            System.IO.FileInfo[] files = diDir.GetFiles();\n\n            foreach (FileInfo lfileInfo in files)\n            {\n                // Work with files\n                Console.WriteLine(lfileInfo.Name);\n            }\n        }\n    }\n}	0
27140933	27140788	Calling a parameterized Stored Procedure that returns a value in C#	public int CheckIP()\n{\n string conn = "";\n conn = ConfigurationManager.ConnectionStrings["Connection"].ToString();\n SqlConnection sqlconn = new SqlConnection(conn);\n try\n {\n     sqlconn.Open();\n     DataSet ds = new DataSet();\n     SqlCommand objcmd = new SqlCommand("sp_CheckIP", sqlconn);\n     objcmd.CommandType = CommandType.StoredProcedure;\n\n     SqlParameter IPAddress = objcmd.Parameters.Add("@IpAddress", SqlDbType.VarChar);\n     IPAddress.Value = 0;\n\n\n     SqlParameter returnParameter = new SqlParameter("@AllowedLogInAttempts", SqlDbType.Int);\n     returnParameter.Direction = ParameterDirection.Output;\n     objcmd.Parameters.Add(returnParameter);\n\n      objcmd.ExecuteNonQuery();\n     int id = (int) returnParameter.Value;    \n\n     //Now here write your logic to assign value hidden field\n }\n catch (Exception ex)\n {\n     Response.Write(ex.Message.ToString());\n }\n finally\n {\n     sqlconn.Close();\n }\n}	0
20790591	20790533	How to concat expression in linq query	var query =\n    queryable\n        .Where(exp)\n        .Join(confQueryable, p => p.Id, c => c.Id, (p, c) => new {p, c})\n        .Where(@t => p.ParentId == parentProcessId)\n        .Select(@t => new {@t, hasChild = p.Processes.Any()})\n        .Select(@t => new ViewModel\n        {\n            Code = p.Code,\n            Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable\n            ParentId = p.Id,\n            Value = p.Id.ToString(),\n            HasChildren = hasChild, // use hasChild variable\n        });	0
690825	690773	Encoding ? in SMS message sent via Gateway not working correctly	System.Text.Encoding	0
17969591	17969549	Split the string based on regular expression	Regex.Split(input,@"\[.*?\][.]");	0
17164966	17164727	'CREATE VIEW' must be the first statement in a query batch	IF OBJECT_ID(N''RealEstate.vwContract'', N''V'') IS NOT NULL\n   DROP VIEW RealEstate.vwContract	0
2962019	2961848	How to use TimeZoneInfo to get local time during Daylight Savings Time?	var dt = DateTime.UtcNow;\nConsole.WriteLine(dt.ToLocalTime());\n\nvar tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");\nvar utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);\nConsole.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));	0
25359549	25357844	How to write this line in C++/CLI?	using namespace System;\nusing namespace System::Net;\nusing namespace System::Net::Security;\nusing namespace System::Security::Cryptography::X509Certificates;\n\n\nstatic bool ValidateServerCertificate(\n        Object^ sender,\n        X509Certificate^ certificate,\n        X509Chain^ chain,\n        SslPolicyErrors sslPolicyErrors)\n    {\n        return true;\n    }\n\nint main(array<System::String ^> ^args)\n{\n    // create callback object, pointing to your function\n    System::Net::Security::RemoteCertificateValidationCallback^ clb = gcnew RemoteCertificateValidationCallback(ValidateServerCertificate);\n    // assign it to the property\n    System::Net::ServicePointManager::ServerCertificateValidationCallback = clb;\n\n    return 0;\n}	0
34223029	34222995	c# Aggregate an enumerable containing a list<string> into one union list then get distinct values	List<string> distinct = list.SelectMany(x => x).Distinct().ToList();	0
33040330	33040116	Making GameObject appear and disappear for a finite amount of time	public GameObject gameobj;\n\nvoid Start()\n{\n    InvokeRepeating("DisappearanceLogic", 0, interval);\n}\n\nvoid DisappearanceLogic() \n{\n     if(gameobj.activeSelf) \n     {\n         gameobj.SetActive(false);\n     }\n     else\n     {\n         gameobj.SetActive(true);\n     }\n}	0
8739886	8728673	Regular Expression to remove contents in string	Regex.Replace(txtHighlight, @"</em>(.)\s*\d+s:\s*(.)<em", "</em>$1$2<em");	0
12025189	12025170	How can I add a unique row number to my Linq select?	var dataOut = from d in data\n                  join s in stat on d.Status equals s.RowKey into statuses\n                  from s in statuses.DefaultIfEmpty()\n                  join t in type on d.Type equals t.RowKey into types\n                  from t in types.DefaultIfEmpty()\n                  select new { d, s, t };\n    return dataOut.Select((x, index) => new Content.Grid {\n                PartitionKey = x.d.PartitionKey,\n                RowKey = x.d.RowKey,\n                Order = x.d.Order,\n                Title = x.d.Title,\n                Status = x.s == null ? "" : x.s.Value,\n                StatusKey = x.d.Status,\n                Type = x.t == null ? "" : x.t.Value,\n                TypeKey = x.d.Type,\n                Row = index\n           };	0
912273	912188	Linq Distinct() by name for populate a dropdown list with name and value	partnerService.SelectPartners().GroupBy(p => p.Name).Select(g => g.First());	0
6439354	6421165	Localization settings after login doesn't work	string lang = objUser.Profile.PreferredLocale;\n                Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.TabId, true, this.PortalSettings, String.Empty, lang), true);	0
15998553	15998459	Parallel Programming using TPL on WinForms	private void button1_Click(object sender, EventArgs e)\n    {\n        richTextBox1.Text = "";\n        label1.Text = "Milliseconds: ";\n\n        var watch = Stopwatch.StartNew();\n        List<Task> tasks = new List<Task>();\n        for (int i = 2; i < 20; i++)\n        {\n            int j = i;\n            var t = Task.Factory.StartNew(() =>\n            {\n                var result = SumRootN(j);\n                richTextBox1.Invoke(new Action(\n                        () =>\n                        richTextBox1.Text += "root " + j.ToString() + " " \n                              + result.ToString() + Environment.NewLine));\n            });\n            tasks.Add(t);\n        }\n\n        Task.Factory.ContinueWhenAll(tasks.ToArray(),\n              result =>\n              {\n                  var time = watch.ElapsedMilliseconds;\n                  label1.Invoke(new Action(() => label1.Text += time.ToString()));\n              });\n    }	0
23183036	23182891	Json Deserialization	var rowList = new List<object>();       \nwhile (reader.Read())\n        {\n            var nes = new\n            { \n\n                ProductID = reader["ProductID"].ToString(),\n                ProductName = reader["ProductName"].ToString(),\n                CategoryName = reader["CategoryName"].ToString(),\n                UnitPrice = reader["UnitPrice"].ToString()\n            };\n            rowList.Add(nes);\n\n        }\nvar serializeMe = new {table_name = rowList }\nstroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(serializeMe );\nResponse.Write(stroutput);	0
2179189	2178821	Parsing JSON objects to c#	JavaScriptSerializer js = new JavaScriptSerializer();\nPerson p2 = js.Deserialize<classtype>(str);	0
22743573	22743442	Aggregate value takes very long time	var orderedData = data.OrderBy(item => item.TimeStamp).ToList();\nint firstIndex = 0;\nvar from = orderedData.First().TimeStamp;\nvar to = orderedData.Last().TimeStamp;\nwhile (from < to)\n{\n    var sum = 0;\n    var newTo = from.AddHours(1);\n    while (firstIndex < data.Count && orderedData[firstIndex].TimeStamp < newTo)\n    {\n        sum += orderedData[firstIndex].Val;\n        ++firstIndex;\n    }\n    dailyInputData.Add(sum);\n    from = from.AddHours(1);\n }	0
26899471	26849931	Docusign Retrieve via ProcessBuilder	String[] command = new String [2];\n\n    command[0] = "\""+buildRoot+ "\\" + docuSignAppName+"\"";\n    logger.info(command[0].toString());\n    //ADDED FOR EXPLANATION - "C:\Program Files (x86)\DocuSign, Inc\Retrieve 3.2\DocuSignRetrieve.exe"\n    command[1] = arguments;\n    logger.info(command[1].toString());\n    //This starts a new command prompt\n    ProcessBuilder processBuilder = new ProcessBuilder("cmd","/c","DocusignRetreive.exe);\n    //This sets the directory to run the command prompt from\n    File newLoc = new File("C:/Program Files (x86)/DocuSign, Inc/Retrieve 3.2");\n    processBuilder.directory(newLoc);\n    logger.info("ProcessBuilder starting directory" +processBuilder.directory());\n    processBuilder.redirectErrorStream(true);\n\n    /*When the process builder starts the prompt looks like\n     *C:\Program Files (x86)\DocuSign, Inc\Retrieve 3.2\n     *Now DocusignRetrieve.exe is an executable in the directory to be run\n     */\n    p = processBuilder.start();	0
14894273	14889010	Remove Box collider of object in unity 3d	Destroy(hit3.collider);	0
21150852	21136834	Extract x,y values from deldir object using RDotNet	var res = new List<List<Tuple<double, double>>>();\n// w is the result of tile.list as per the sample in ?tile.list\nvar n = engine.Evaluate("length(w)").AsInteger()[0];\nfor (int i = 1; i <= n; i++)\n{\n    var x = engine.Evaluate("w[[" + i + "]]$x").AsNumeric().ToArray();\n    var y = engine.Evaluate("w[[" + i + "]]$y").AsNumeric().ToArray();\n    var t = x.Zip(y, (first, second) => Tuple.Create(first, second)).ToList();\n    res.Add(t);\n}	0
3213627	3187150	Executing stored proc from DotNet takes very long but in SSMS it is immediate	CREATE PROCEDURE dbo.MyProcedure\n(\n    @Param1 INT\n)\nAS\n\ndeclare @MyParam1 INT\nset @MyParam1 = @Param1\n\nSELECT * FROM dbo.MyTable WHERE ColumnName = @MyParam1 \n\nGO	0
13447260	13420799	Enabling Execution Policy for PowerShell from C#	string command = "/c powershell -executionpolicy unrestricted C:\script1.ps1";\nSystem.Diagnostics.Process.Start("cmd.exe",command);	0
22972887	22972771	How to declare a variable as static property in multi threaded environment	public static string StartDate\n{\n    get\n    {\n        return DateTime.Now.AddYears(-2).AddMonths(-1).ToShortDateString();\n    }\n}	0
2619977	2619749	Silverlight handling multiple key press combinations	void Canvas_KeyUp(object sender, KeyEventArgs e)\n{\n    //check for the specific 'v' key, then check modifiers\n    if (e.Key==Key.V) { \n        if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) {\n        //specific Ctrl+V action here\n        }\n    } // else ignore the keystroke\n}	0
14279694	14279603	How to create a data-type that is a subset of possible values for another data-type	public class Paint {\n\n  public string Name { get; private set; }\n\n  public Paint(string name) {\n    switch (name) {\n      case "Red":\n      case "Green":\n      case "Blue":\n        Name = name;\n        break;\n      default:\n        throw new ArgumentException("Illegal paint name '" + name + "'.");\n    }\n  }\n\n}	0
23277088	23276647	Converting XML to SQL Server Table using C# (or any other method)	try\n{\n    // add as many elements you want, they will appear only once!\n    HashSet<String> uniqueTags = new HashSet<String>();\n    // recursive helper delegate\n    Action<XElement> addSubElements = null;\n    addSubElements = (xmlElement) =>\n    {\n        // add the element name and \n        uniqueTags.Add(xmlElement.Name.ToString());\n        // if the given element has some subelements\n        foreach (var element in xmlElement.Elements())\n        {\n            // add them too\n            addSubElements(element);\n        }\n    };\n\n    // load all xml files\n    var xmls = Directory.GetFiles("d:\\temp\\xml\\", "*.xml");\n    foreach (var xml in xmls)\n    {\n        var xmlDocument = XDocument.Load(xml);\n        // and take their tags\n        addSubElements(xmlDocument.Root);\n    }\n    // list tags\n    foreach (var tag in uniqueTags)\n    {\n        Console.WriteLine(tag);\n    }\n}\ncatch (Exception exception)\n{\n    Console.WriteLine(exception.Message);\n}	0
22840050	22839099	Debug a .NET dump using windbg	.loadby sos mscorwks (for .net 2)\n.loadby sos clr (for .net 4, of course :( )\n!clrstack	0
2936577	2934575	Update gridview from code behind in asp.net	protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)\n{\n    int mytext = Convert.ToInt16(GridView1.Rows[e.RowIndex].Cells[1].Text);\n    string cConatiner = GridView1.Rows[e.RowIndex].Cells[4].Text;\n\n    GridView1.Rows[e.RowIndex].Cells[4].Text = mytext;\n}	0
6862202	6862123	vs2010 watch window : print out some member to parent node	[DebuggerDisplay("Content={Content}")]\npublic class MeanItem\n{\n...	0
19562689	19562127	finding date between terms of dates	var isTodayInTerm = termsforcurrentCalendar.Any(a =>DateTime.Today >= a.StartDate && DateTime.Today <= a.EndDate);\n\n    if (!isTodayInTerm)\n    {\n        var firstAvailableDate = termsforcurrentCalendar.FirstOrDefault(z => z.StartDate > DateTime.Today);\n        datetoBeChecked = firstAvailableDate.StartDate;\n    }	0
27334522	27334470	Cannot call stored procedure from c#	string constring = "Server=localhost;Port=3306;Uid=root;Pwd=mc brown;Database=your_database;	0
14621144	14618830	How can I use Entity Framework to load the results of a stored procedure?	using (DbContext context = new DbContext("DBConnectionStringNameFromAppConfig"))\n            {\n\n                SqlParameter[] parameters =\n                      {\n                                        new SqlParameter("@OwnerID", DBNull.Value),\n                                        new SqlParameter("@ExternalColorID", colorOwner.ExternalColorID),\n                                        new SqlParameter("@ProductionSiteID", DBNull.Value),\n                                        new SqlParameter("@PanelstatusNr", DBNull.Value),\n                                        new SqlParameter("@DateLastChecked", DBNull.Value),\n                                        new SqlParameter("@rowcount", DBNull.Value),\n                      };\n                var colors = context.Database.SqlQuery<Models.ColorSelectEvaluation>("[dbo].[sp_Color_Select_Evaluation] @OwnerID, @ExternalColorID, @ProductionSiteID, @PanelstatusNr, @DateLastChecked, @rowcount", parameters).ToList();\n\n            }	0
27438172	27438078	Get unchecked values from CheckBoxList in c#	string chkboxlistValue = "";\n        string uncheckedId = "";\n        foreach (ListItem val in chkbxId.Items)\n        {\n            if (val.Selected)\n            {\n                chkboxlistValue += val.Value + " ";\n            }\n            else\n            {\n                 uncheckedId += val.Value + ",";\n            }\n        }	0
18105403	18105273	Can I evaluate two groups of items with a foreach loop in C# winforms?	foreach(TabPage page in yourTabControl.TabPages){\n   foreach(Control c in page.Controls){\n      LoopThroughControls(c);\n   }  \n}\n\nprivate void LoopThroughControls(Control parent){\n   foreach(Control c in parent.Controls)\n      LoopThroughControls(c);\n}	0
30035878	30035814	C# ListView image icon size	listView1.View = View.LargeIcon;\n\n        ImageList iList = new ImageList();\n        iList.ImageSize = new Size(64, 64);  \n        iList.ColorDepth = ColorDepth.Depth32Bit;\n\n        listView1.LargeImageList = iList;	0
3838139	3837904	Fix broken element that miss ending tag or /> with c#	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(html);    \nSystem.IO.StringWriter sw = new System.IO.StringWriter();\nSystem.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);\ndoc.Save(xw);\nstring result = sw.ToString();	0
11846886	11239541	How to use TraceSource.TraceEvent in a ASP.NET C# web application	var traceSource = new TraceSource("TraceSourceName");\ntraceSource.TraceEvent(TraceEventType.Error, 2, "Hello World !");\ntraceSource.Close();	0
5311135	5311124	How to empty a list in C#?	myList.Clear();	0
2413800	2413789	How do I receive input to store as a string in a winforms project in C#?	private void button1_Click(object sender, EventArgs e)\n{\n    string text = textBox1.Text;\n}	0
6278228	6277623	release mode uses double precision even for float variables	class WorkingContext\n{ \n    public float Value; // you'll excuse me a public field here, I trust\n    public override string ToString()\n    {\n        return Value.ToString();\n    }\n}\nstatic void Main()\n{\n    // start with some small magic number\n    WorkingContext a = new WorkingContext(), temp = new WorkingContext();\n    a.Value = 0.000000000000000013877787807814457f;\n    for (; ; )\n    {\n        // add the small a to 1\n        temp.Value = 1f + a.Value;\n        // break, if a + 1 really is > '1'\n        if (temp.Value - 1f != 0f) break;\n        // otherwise a is too small -> increase it\n        a.Value *= 2f;\n        Console.Out.WriteLine("current increment: " + a);\n    }\n    Console.Out.WriteLine("Found epsilon: " + a);\n    Console.ReadKey();\n}	0
27273363	27273110	Delete From Table Where Column "In" range - Simple.Data	string[] genresToDelete = new[] { "Rock", "Pop" };\ndb.Albums.DeleteAll(genresToDelete.Contains(db.Albums.Genre));	0
26546823	26546808	Regular Expression to validate email	bool IsValidEmail(string email)\n{\n    try {\n        var addr = new System.Net.Mail.MailAddress(email);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}	0
9489279	9488993	How to get the href from LiteralControl?	var myAnchor = divLinkContainer.Controls\n    .Cast<Control>()\n    .Where(a => a is HtmlAnchor).Select(a=>(HtmlAnchor)a)\n    .Where(a => a.HRef.Contains(url))\n    .First();	0
12041506	12033965	Front end for C++ console program	compute()	0
21932795	21931507	c# WPF - Add total row in a DataGrid	private List<Article> GetArticles()\n    {\n        List<Article> arts = new List<Article>();\n\n        arts.Add(new Article { Name = "Name1", Price = 2.80 });\n        arts.Add(new Article { Name = "Name2", Price = 1.25 });\n        arts.Add(new Article { Name = "Name3", Price = 9.32 });\n        arts.Add(new Article { Name = "Name4", Price = 1.31 });\n        arts.Add(new Article { Name = "Name5", Price = 0.80 });\n        arts.Add(new Article { Name = "Name6", Price = 2.50 });\n        arts.Add(new Article { Name = "Name7", Price = 0.50 });\n        arts.Add(new Article { Name = "Total", Price = arts.Sum(l => l.Price)});\n        return arts;\n    }	0
1539625	1539615	Close a thread against a mysql database in c#	using(MySqlConnection conn = new MySqlConnection(connString))\n{\n    conn.Open();\n} // conn is automatically closed and disposed at the end of the using block	0
14274946	14274918	access a value returned by partial class	DataSet  ds =CommonClass.somemethod("mydata") ;	0
24097901	24097864	How to get a bit value with SqlDataReader and convert it to bool?	bool isConfirmed = (bool)sqlDataReader["IsConfirmed"]	0
12404786	12404317	How to format the given xml into single line (without spaces)	public static string StripXmlWhitespace(string Xml)\n{\n    Regex Parser = new Regex(@">\s*<");\n    Xml = Parser.Replace(Xml, "><");\n\n    return Xml.Trim();\n}	0
2618616	2618602	Linq: How to calculate the sales Total price and group them by product	var productListResult = orderProductVariantListResult\n        .GroupBy(pv => pv.Product)\n        .Select(g => new \n        {\n            Product = g.Key,\n            TotalOrderCount = g.Count(),\n            TotalSales = g.Sum(pv => pv.Sales),\n            TotalQuantity = g.Sum(pv => pv.Quantity),\n        })\n        .OrderByDescending(x => x.TotalOrderCount).ToList();	0
33185270	33184986	How to convert Json array to list in c#	public string[] allAdultFares{ get; set; }	0
12059758	12059322	I can't set the text in my Browser control to what I need	if (el.GetAttribute("name").Equals("_MYPW"))\n{                        \n    el.SetAttribute("value", "some text");\n    clickNextButton(hec);\n}	0
24789215	24788624	Change datagridview results according to input from textbox	DataTable dt = new DataTable();\nstring query = "SELECT TellerNum, SessionName, PrincipleName, SessionDate, Comments, SessionKey FROM [SESSION] WHERE TellerNum = @teller ORDER BY TellerNum;";\nusing (OleDbDataAdapter da = new OleDbDataAdapter(query, con)) {\n  da.SelectCommand.Parameters.AddWithValue("@teller", textBox1.Text);\n  da.Fill(dt);\n}\ndataGridView1.DataSource = dt;	0
5656174	5656161	size of array of structs in bytes	Marshal.SizeOf(typeof(MyStruct)) * array.Length	0
17297218	17296148	NotifyIcon hides app from taskbar. How to avoid that?	private void MainWindow_OnStateChanged(object sender, EventArgs e)\n{\n    if (WindowState != WindowState.Minimized) return;\n    this.ShowInTaskbar = true;\n    if (notifyIcon != null)\n    notifyIcon.ShowBalloonTip(2000);\n    this.WindowState = FormWindowState.Minimized;\n}	0
8313367	8313287	How to replace %20 with - in Url Rewriting	Uri myuri = new Uri(myolduri.ToString().Replace("%20","-"));	0
9915881	9915679	Set operation: how to filter a collection based on a COMBINED set of ints	var result = \n    from pav in ProductAttributes\n    join id in valueIds\n    on pav.AttributeValueID equals id\n    group pav by pav.ProductImageID into gj\n    where gj.Count() == valueIds.Count()\n    select gj.Key;	0
34235902	34225304	CreateInstance from another appdomain works on console application but throws MissingMethodException when unit testing	AppDomainSetup domaininfo = new AppDomainSetup();\n        domaininfo.ApplicationBase = System.Environment.CurrentDirectory;\n        AppDomain ad = AppDomain.CreateDomain("New Domain", null, domaininfo);\n\n\n        Worker remoteWorker = (Worker)ad.CreateInstanceFromAndUnwrap(\n            typeof(Worker).Assembly.Location,\n            typeof(Worker).FullName,\n            true,\n            BindingFlags.Instance | BindingFlags.Public,\n            null,\n            new object[] { new WorkerParam("string") },\n            CultureInfo.CurrentCulture, null);	0
22252408	21891430	Print dots on screen coordinates C#	using System.Drawing;    \n    Graphics g;\n    using (g = Graphics.FromHwnd(IntPtr.Zero))\n\n        {\n\n             g.DrawEllipse(Pens.Red, x,y, 20, 20);\n\n         }	0
20785451	20785220	How to check MySQL connection state in C#	var sqlCon= new SqlConnection(Properties.Settings.Default.sString);\nvar mySQLCon= new MySqlConnection(Properties.Settings.Default.dString);\nsqlCon.Open();\nmySQLCon.Open();\nvar temp = mySQLConn.State.ToString();\nif (sqlCon.State==ConnectionState.Open && temp=="Open")\n {\n   MessageBox.Show(@"Connection working.");\n }\nelse\n {\n  MessageBox.Show(@"Please check connection string");\n }	0
13157681	13157624	How to find smtp server name	smtp.gmail.com	0
5148430	5148329	How to handle PrincipalPermission Security exceptions	Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)\n        Dim er = HttpContext.Current.Error\n        If er.GetType.Equals(GetType(System.Security.SecurityException)) Then\n            HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl & "?ReturnUrl=" & HttpContext.Current.Request.Path)\n        End If\n    End Sub	0
7561643	7560728	Hosted PowerShell cannot see Cmdlets in the same Assembly	using System; \nusing System.Management.Automation; \n\n[Cmdlet(VerbsCommon.Get,"Hello")] \npublic class GetHelloCommand:Cmdlet \n{ \n    protected override void EndProcessing() \n    { \n        WriteObject("Hello",true); \n    } \n} \n\nclass MainClass \n{ \n    public static void Main(string[] args) \n    { \n        PowerShell powerShell=PowerShell.Create();\n\n        // import commands from the current executing assembly\n        powershell.AddCommand("Import-Module")\n            .AddParameter("Assembly",\n                  System.Reflection.Assembly.GetExecutingAssembly())\n        powershell.Invoke()\n        powershell.Commands.Clear()\n\n        powershell.AddCommand("Get-Hello"); \n        foreach(string str in powerShell.AddCommand("Out-String").Invoke<string>()) \n            Console.WriteLine(str); \n    } \n}	0
9600191	9599653	Special Characters in StreamWriter	\0\0...	0
28147629	28115608	How to create a Model Binder with automatic type cast	var valueRaw = propValue.ConvertTo(prop.PropertyType);\nentity.GetType().GetProperty(prop.Name).SetValue(entity, valueRaw);	0
7806611	7794563	Add to OnFocus codebehind without deleting current OnFocus	if(document.getElementById('REQUEST_LASTFOCUS') == document.getElementById('MainContent_TextBoxAdgangskode')) \n                    {\n                        document.getElementById('MainContent_TextBoxAdgangskode').value = '';\n                    }	0
2075823	2075811	How do I use low-level 8 bit flags as conditionals?	bool isInjected = ((kbd.flags & 0x10) != 0);	0
3108687	3108659	How to change picture file dimension in C#?	System.Drawing	0
34397890	34397806	Calculate fastest sum of field with where linq of datacontext	var sum = contestoDB.Eventi\n    .Where(w => w.DataPrenotazione.Date == dataSelezionata.Date)\n    .Sum(x => x.OrePreviste);	0
28154787	28099847	How can I get data type of each column in a SQL Server table/view etc. using C# Entity Framework?	var columns=typeof(tbl_Books).GetProperties();	0
2553371	2553314	Programatically change cursor speed in windows	[DllImport("user32.dll", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SystemParametersInfo(SPI uiAction, uint uiParam, String pvParam, SPIF fWinIni);	0
22480118	22479125	Xamarin iOS programmatically add navigation bar to table view	[Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate {\n  UIWindow window;   CompanyController cc;\n{     window = new UIWindow (UIScreen.MainScreen.Bounds);   \n      cc = new CompanyController ();\n    // If you have defined a root view controller, set it here:               window.RootViewController = new UINavigationController (cc);\n    // make the window visible     window.MakeKeyAndVisible ();\n    return true;   } }	0
2150498	2121010	wcf deserialize enum as string	[DataMember( Name = "foo" )]\nprivate string foo { get; private set; }\n\npublic Foo Foo \n{ \n  get \n  {\n    return Foo.Parse(foo);\n  }\n}	0
1597549	1597379	Method to convert URLs - would a Regex be appropriate	string prefix = url.ToLower().StartsWith("https://") ? "https://www." : "http://www.";\nurl = Regex.Replace(url, @"^((https?://)?(www\.)?)", prefix, RegexOptions.IgnoreCase);	0
15424008	15423906	Select thousands of files, based on file name	foreach (var filePath in File.ReadAllLines(indexFile))\n{\n    if (File.Exists(filePath))\n    {\n        var destinationPath = Path.Combine(destinationRoot, Path.GetFileName(filePath));\n        File.Copy(filePath, destinationPath);\n    }\n}	0
11916438	11916393	C# formatting text for a cookie cutter output of different size text	String.PadRight	0
18153737	18152288	XNA Parallaxing background wont show all the layers	// Use this one instead!\nspriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);\nspriteBatch.Draw(texture, position, new Rectangle(-scrollX, -scrollY, texture.Width, texture.Height), Color.White);\nspriteBatch.End();	0
8437974	8437916	How do I make the DataGridView show the selected row?	dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index;	0
15822176	15821359	Detecting mouse click on the node of polygone	Point[] listOfNodes = new Point[1];\nprivate void pictureBox1_MouseClick(object sender, MouseEventArgs e)\n{\n    foreach (Point item in listOfNodes)\n    {\n        if (item == e.Location)\n        {\n            //The node was clicked.\n        }\n    }\n}	0
567060	566570	How can I install a certificate into the local machine store programmatically using c#?	X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadWrite);\nstore.Add(cert); //where cert is an X509Certificate object\nstore.Close();	0
20549464	20549212	MSMQ ,reading multiple Queue messages from a single windows Service	new Thread(WorkerA) { IsBackground = true }.Start();\nnew Thread(WorkerB) { IsBackground = true }.Start();\n\nvoid WorkerA() {\n   while (true) { /* process queue a */ }\n}\n\nvoid WorkerB() {\n   while (true) { /* process queue b */ }\n}	0
6046368	6046350	Display meta tag content as a string on webpage	lblMetaTag.Text = \n   "&lt ;meta property='" + ctrl.property_name + "' content='" + \n    ctrl.property_value + "' /&gt ;";	0
6121120	6119533	Scaling the icon used by a maximised MDI child in the parent form's MenuStrip	var bmp = new Bitmap(16, 16);\nusing (var g = Graphics.FromImage(bmp))\n{\n    g.DrawImage(child.Icon.ToBitmap(), new Rectangle(0, 0, 16, 16));\n}\nvar newIcon = Icon.FromHandle(bmp.GetHicon());\nchild.Icon = newIcon;\n// ...\nchild.Show();	0
9426009	9424844	Login Logout Control	Session.Abandon();\n    Response.Redirect("~/LoginPage.aspx");	0
18370185	18347020	How do i merge these queries into 1	public static SelectList GetNonRacingHorses(int id, int raceId)\n{\n    HorseTracker entities = new HorseTracker();\n\n    var race = entities.Races.Single(r => r.Id == raceId);\n    var racehorses = from h in race.RacingHorses\n                     select h.Id;\n\n    var userhorses = (from h in entities.Horses\n                      where\n                          h.UserId == id\n                      orderby h.Name\n                      select h);\n\n    var nonracinghorses = from h in userhorses\n                          where !racehorses.Contains(h.Id)\n                        select h;\n\n    List<SelectListItem> sli = new List<SelectListItem>();\n\n    foreach (Horse horse in nonracinghorses)\n    {\n        sli.Add(new SelectListItem { Text = horse.Name, Value = horse.Id.ToString(), Selected = false});\n    }\n\n    return new SelectList(sli, "Value", "Text");\n}	0
19781657	19740814	Azure Mobile Services with persistent authentication	var liveIdClient = new LiveAuthClient(clientId);\nvar liveLoginResult = await liveIdClient.LoginAsync("wl.basic wl.signin".Split());\nif (liveLoginResult.Status == LiveConnectSessionStatus.Connected) {\n    var token = new JObject();\n    token.Add("authenticationToken", liveLoginResult.Session.AuthenticationToken);\n    var user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, token);\n}	0
9267032	9266774	Not sure how to phrase: Rewriting a method from tutorial	var user = db.User.Where(u => u.UserName == username).FirstOrDefault();	0
17133765	17133666	Using VS2010 with SqlClient and SQL Server 2012	public void insertData()\n        {\n            using (SqlConnection con = new SqlConnection(conString))\n            {\n                con.Open();\n                try\n                {\n                    using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))\n                    {\n                        cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));\n                        cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));\n                        cmd.Parameters.Add(new SqlParameter("Active", mActive));\n    cmd.ExecuteNonQuery();\n                    }\n                }\n                catch (Exception Ex)\n                {\n                    Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);\n                }\n            }\n        }	0
15647701	15647483	How to use user input as parameter in SQL query in windows form application?	using (cmd command = new SqlCommand())\n{\n    string sql = "Select * from table where projid=@UserEnteredProjid";\n    cmd.Connection = conn;\n    cmd.CommandType = CommandType.Text;\n    cmd.CommandText = sql;\n    cmd.Parameters.AddWithValue("UserEnteredProjid", your_value_here);      \n    SqlDataReader reader = command.ExecuteReader();\n    while (reader.Read())\n    {\n    //do something;\n    }\n}	0
17779297	17779238	must be a non-abstract type with a public parameterless constructor in redis	public class MyWrapper\n{\n    public ThirdPartyObject ThirdPartyInstance { get; set; }\n\n    public MyWrapper()\n    {\n        ThirdPartyInstance = new ThirdPartyObject("Constructors");\n    }\n}	0
7860976	7860949	Removing a list of objects of another list from Different Collections	listA = listA.Where(x=>listB.Any(y=>y.ID == x.ID)).ToList();	0
8492907	8492825	A void method that needs to return something	public class ClientRepository\n{\n    public ClientRepository()\n    {\n        this.DataContext = new HydraDataContext();\n    }\n\n    private HydraDataConetxt DataContext { get; set; }\n\n    // DBResult is a made up class which returns some info about the operation...\n    public DBResult Insert(Client client)\n    {\n        try\n        {\n            this.DataContext.Clients.InsertOnSubmit(client);\n            this.DataContext.SubmitChanges();\n\n             return DBResult.Success;\n        }\n        catch (Exception error)\n        {\n             return DBResult.Failed(error.Message);\n        }\n    }\n}	0
15880119	15879966	Windows 8 Store - Debug App Downloaded from store	Debug->Debug Installed App Package	0
23894344	23894128	Datatable LINQ select datarow only returning one row and how to order	where dr["LinkControl"].ToString() == linkC.linkCon.ToString()	0
8095993	8095670	StreamWriter crashes with large text files in C#	StreamWriter file;\ntry\n{\n     file = new StreamWriter("text6.txt");\n     file.Close();\n}\ncatch(Exception)\n{\n     throw;\n}	0
23888703	23888545	How to add get/set properties properly?	public string FullName\n{\n    get { return string.Format("{0} {1}", this.Name1, this.Name2); }\n}	0
20463764	20463681	Make foreach loop argument more efficent	foreach (XElement element in xdoc.Descendants("camera"))\n{\n    var value = element.Element("group").Value;\n    if (value == "A")\n        A.Items.Add(AddToGroup(element));\n    else if (value == "B")\n        B.Items.Add(AddToGroup(element));\n}	0
7284758	7284429	How to load javascript function from an dynamicall added control?	ScriptManager.RegisterStartupScript(\nthis.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",\n"<script type='text/javascript'>doSomething();</script>", false);	0
13725372	13725313	SqlCeRemoteDataAccess from C#	private void button_test_Click(object sender, EventArgs e)\n{\n    try\n    {\n        string str = "data source=" + textBox_server.Text + "; initial catalog=" + textBox_db.Text\n+ "; user id=" + textBox_user.Text + "; pwd=" + textBox_password.Text + ";";\n\n        SqlConnection sqlcon = new SqlConnection(str);\n        sqlcon.Open();\n        sqlcon.Close();\n        MessageBox.Show("Test Connection was successfull");\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show("Test Connection failed. "+ ex.Message);\n    }\n}	0
7023123	7022999	How can I prevent DataGridView double click to open a form more than one time?	Form4 f4 = null; // class field\n\n    // call this method when cellMouseDoubleClick is triggered\n    private void OpenForm4IfNotOpened()\n    {\n        if (f4 == null || f4.IsDisposed)\n        {\n            f4 = new Form4();\n\n            f4.id = movieIDInt;\n            f4.thename = thename;\n            f4.address = address;\n            f4.fax = fax;\n            f4.mobile = mobile;\n            f4.email = email;\n            f4.website = website;\n            f4.notes = notes;\n            f4.Show();\n        }\n        else\n        {\n            f4.BringToFront();\n        }\n    }	0
19434933	19434683	Save information using windows 8 Isolated Storage	using IsolatedStorageW8;	0
18091377	18091324	Regex to match all us phone number formats	\(?\d{3}\)?-? *\d{3}-? *-?\d{4}	0
1786514	1786479	splitting a filename - substring?	string number = Regex.Match("SCO_InsBooking_1000.pdf", @"\d+").Value;	0
9501236	9501073	How to convert byte[] array to IntPtr?	Encoding.GetString()	0
12922411	12922173	How To Resize Certain ListView Columns Proportional To Remaining Size Of ListView	int fixedWidth = 0;\n        int countDynamic = 0;\n\n        for (int i = 0; i < listView1.Columns.Count; i++)\n        {\n            ColumnHeader header = listView1.Columns[i];\n\n            if (header.Tag != null && header.Tag.ToString() == "fixed")\n                fixedWidth += header.Width;\n            else\n                countDynamic++;\n        }\n\n        for (int i = 0; i < listView1.Columns.Count; i++)\n        {\n            ColumnHeader header = listView1.Columns[i];\n\n            if (header.Tag == null)\n                header.Width = ((listView1.Width - fixedWidth) / countDynamic);\n        }	0
4900064	4899897	Filtering SqlDataSource with multiple dropdownlists	yourFilterExpression = "";\nif (dropDownList1.SelectedValue != null)\n filterExpression = // filter expression 1\nif (dropDownList2.SelectedValue != null)\n filterExpression += // filter expression 2	0
1046398	1046264	Validate a Word 2007 Template file	public static bool IsDocumentValid(WordprocessingDocument mydoc)\n{\n    OpenXmlValidator validator = new OpenXmlValidator();\n    var errors = validator.Validate(mydoc);\n    foreach (ValidationErrorInfo error in errors)\n        Debug.Write(error.Description);\n    return (errors.Count() == 0);\n}	0
12381829	12367696	Why aren't selected items showing up in my owner drawn listview control?	bool isSelected = e.State == ListViewItemStates.Selected;	0
6301206	6301150	Creating a silverlight border in codebehind?	var border = new Border();\n\nGrid.SetColumn(border, 0);\nGrid.SetColumnSpan(border, 3);\nGrid.SetRowSpan(border, 3);\n\nborder.CornerRadius = new CornerRadius(1);\nborder.Background = new SolidColorBrush(Colors.Red);\nborder.BorderBrush = new SolidColorBrush(Color.FromArgb(0xff, 0x33, 0x33, 0x33));\nborder.BorderThickness = new Thickness(1);\nborder.RenderTransformOrigin = new Point(0.5, 0.5);\n\nvar transformGroup = new TransformGroup();\ntransformGroup.Children.Add(new ScaleTransform());\ntransformGroup.Children.Add(new SkewTransform());\ntransformGroup.Children.Add(new RotateTransform());\ntransformGroup.Children.Add(new TranslateTransform());\nborder.RenderTransform = transformGroup;	0
10262	10205	Delimited string parsing?	string filename = @textBox1.Text;\n  string[] fields;\n  string[] delimiter = new string[] {"|"};\n  using (Microsoft.VisualBasic.FileIO.TextFieldParser parser =\n             new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) {\n                    parser.Delimiters = delimiter;\n                    parser.HasFieldsEnclosedInQuotes = false;\n                    while (!parser.EndOfData) {\n                       fields = parser.ReadFields();\n\n                       //Do what you need\n                    }\n  }	0
10922166	10921987	c# winforms - how to make a DataGridViewRow UnSelectable?	DataGridView1.SelectionChanged += new EventHandler(DataGridView1_SelectionChanged);\nprivate void DataGridView1_SelectionChanged(object sender, EventArgs e){\n    List<DataGridViewCell> toBeRemoved = new List<DataGridViewCell>();\n    foreach(DataGridViewCell selectedCell in DataGridView1.SelectedCells){\n        if (isCellUnSelectable(selectedCell))\n            toBeRemoved.Add(selectedCell);\n    }\n    foreach(DataGridViewCell cell in toBeRemoved){\n        cell.Selected = false;\n    }\n}	0
6778667	6778648	Datetime? to string	o.CustomerRequiredDate.HasValue ? o.CustomerRequiredDate.Value.ToString() : ""	0
27330853	27330826	How to get length of data received in socket?	int bytesReceived = 0;\nwhile (true)\n    {\n        i = socketForClient.Receive(cldata);\n        bytesReceived += i;\n        if (i > 0)\n        {\n            // same code as before\n        }\n    }	0
12152734	12152708	Temperature Conversion- 2's complement - 13bit	(float)(sbyte)data[1] + (float)data[0] / 256	0
31738165	31738149	Autofac: Substitute implementation but inject old implementation?	void Main()\n{\n    var builder = new ContainerBuilder();\n    builder.RegisterType<EventStore>().AsSelf();\n    builder.Register(cc => new DebugingEventStore(cc.Resolve<EventStore>())).As<IEventStore>();\n    var container = builder.Build();\n\n    container.Resolve<IEventStore>().DoWork();\n\n}\n\npublic interface IEventStore\n{\n    void DoWork();\n}\n\npublic class EventStore : IEventStore\n{\n    public EventStore(Foo doo, Bar bar)\n   { ....} \n    void IEventStore.DoWork()\n    {\n        Console.WriteLine("EventStore");\n    }\n}\n\npublic class DebuggingEventStore: IEventStore\n{\n    private IEventStore _internalEventStore;\n\n    public DebuggingEventStore(IEventStore eventStore)\n    {\n        this._internalEventStore = eventStore;\n    }\n    void IEventStore.DoWork()\n    {\n        this._internalEventStore.DoWork();\n        Console.WriteLine("DebuggingEventStore");\n    }\n}	0
21583769	21569770	Wrong Content-Type header generated using MultipartFormDataContent	content.Headers.Remove("Content-Type");\ncontent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);	0
13815631	13815564	How to scan a directory with wildcard with a specific subdirectory	var directories = \n    Directory.EnumerateDirectories(@"C:\Program\", "Version2.*")\n     .SelectMany(parent => Directory.EnumerateDirectories(parent,"Files"))	0
750897	750884	using dataadpter how to update data in database	myDataAdapter.Update(myDataSet);	0
1415981	1415911	Unable to Get data from DA layer. What to do?	//Model Layer\npublic class UserModel\n{\npublic virtual string Firstname{get;set;}\n}\n//DataAccess Layer\npublic class UserDao\n{\nList<UserModel> GetAll();\n}\n//BusinessLayer\npublic class UserDomainModel:UserModel\n{\npublic UserDomainModel(UserModel user,UserDao dao)\n{\n_user=user;\n_dao=dao;\n}\npublic override string FirstName\n{\nget\n{\nreturn _user.FirstName;\n}\nset\n{\n_user.FirstName=value;\n}\n\npublic void Save()\n{\n_dao.Save(_user);\n}\n}\n}	0
13356758	13356606	Exclude method from executing while debugging on Local machine	protected void Application_End(object sender, EventArgs e)\n{\n    if (RoleEnvironment.IsAvailable && !RoleEnvironment.IsEmulated)\n        core.cleanUpDB();\n}	0
3717778	3711372	Child Xml Element is not Deserializing	xmlns="tfs"	0
26315772	26315748	C# how do I make string from array of string?	string.Join(" ", split);	0
12193079	12192823	Find header value for a cell in a grid	if(e.Row.RowType == DataControlRowType.Header)\n{\n    Label header = (Label)e.Row.FindControl("LabelID");\n}	0
6855505	6855452	DataBinding over a property in viewModel	public class MyViewModel : INotifyPropertyChanged\n{\n    private string countText;\n\n    public string CountText        \n    {\n        get { return this.countText; }\n        set { this.countText = value; NotifyPropertyChanged("CountText"); }\n    }\n\n    .....snip.....\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private void NotifyPropertyChanged(params string[] properties)\n    {\n        if (PropertyChanged != null)\n        {\n            foreach (string property in properties)\n                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property));\n        }\n    }\n}	0
26731726	22441163	XPath validation using Regex	public class MyCustomAttribute : ValidationAttribute {\nprotected override ValidationResult IsValid(object value, ValidationContext validationContext)\n     {\n        //Your logic here.\n        return ValidationResult.Success;\n     }\n}	0
15311672	15311317	Invoke Method from xml file	private void button1_Click(object sender, EventArgs e)\n    {\n        MethodInfo val = this.GetType().GetMethod("Foo");\n        val.Invoke(this, new object[] {"1", "2"});\n    }\n\n    public void Foo(string p1, string p2)\n    {\n        MessageBox.Show("");\n    }	0
22558095	22557361	Passing parameters from one app to the other	class Program\n{\n    static void Main(string[] args)\n    {\n        System.Diagnostics.Process prc = new System.Diagnostics.Process();\n        prc.StartInfo.Arguments = string.Join("", Constants.Arguments);\n        prc.StartInfo.FileName = Constants.PathToInfoPath;\n        prc.Start();\n    }\n}\npublic class Constants\n{\n    public static string PathToInfoPath = @"C:\Program Files (x86)\Microsoft Office\Office14\INFOPATH.EXE";\n    public static string[] Arguments = new string[] { @"c:\users\accountname\Desktop\HSE-000403.xml" };\n}	0
16002886	16002673	How to get the argument to invoke an Expression?	public static MvcHtmlString InlineEditable<T,TP>(this HtmlHelper<T> helper, Expression<Func<T,TP>> fieldSelector)\n {\n     var compiledFieldSelector = fieldSelector.Compile();\n     var arg = helper.ViewData.Model;\n     var value = compiledFieldSelector(arg);\n     ....\n }	0
29755141	29754479	C# - Unable to set correct timezone	var myUsersTimeZone = "Central Standard Time";\nvar myServersTimeAsUtc = DateTime.UtcNow;\nvar myUsersTime = TimeZoneInfo.ConvertTimeFromUtc(\n            myServersTimeAsUtc,\n            TimeZoneInfo.FindSystemTimeZoneById(myUsersTimeZone));	0
21618612	21618492	How to validate the TextBox correctly in C#?	if (string.IsNullOrWhiteSpace(gradeLetter.Text) || !(gradeLetter.Text == "A" || gradeLetter.Text == "B" || gradeLetter.Text == "C" || gradeLetter.Text == "D" || gradeLetter.Text == "F"))	0
25910198	25910135	How to get single quoted words from string using c#	'([^']*)'	0
6144904	6103452	Regex to remove non-URL friendly characters, but allow Unicode and accents	Microsoft.Security.Application.AntiXss.GetSafeHtml()	0
18877828	18877772	Running Projects Programmatically	Process.Start	0
19901504	19900112	C# Serialize JSON turn \ into \\\\	var dataContacts = \n       {"Contacts":[{"Id":0,"Active":false,"Company":"Rory The Architect\\, Melt"}]};\n\nvar contacts = dataContacts.Contacts;	0
10164955	10164871	Entity Framework foreign key null remained as entity entered	Question q = new Question();\nQuestionLocation qL = new QuestLocation(){ CreateDate = DateTime.Now, Latitude = 10 , Longitude = 10 };\nq.StartDate = DateTime.Now;\nq.Objective = "foo";\nq.Location = qL;\n\n//And add newly created Quest into Database :\nDataContext.QuestLocations.Add(qL);\nDataContext.SaveChanges();\n\nDataContext.Quests.Add(q);\nDataContext.SaveChanges();	0
6919898	6919851	Create a user friendly drop down while retaining original column value?	SELECT\n   USERID, -- what the user actually selects\n   ISNULL(LNAME,'') + ', ' + ISNULL(FNAME,'') + ' (' + ISNULL(USERID,'') + ') '\n           AS FullName --what user sees and appears to SELECT\nFROM\n   USER\nORDER BY\n   FullName	0
10349125	10055659	How to find files in a folder in an ASP.NET application using C#?	var getFileName = Directory.GetFiles(Server.MapPath("~/PDF/Requirement"));  // Collection Of file name with extention.\n\nvar getFileNameExcludeSomeExtension1 = from f in Directory.GetFiles(Server.MapPath("~/PDF/Requirement"))\n                                       where Path.GetExtension(f) != ".scc" && Path.GetExtension(f) != ".db"\n                                       select Path.GetFileNameWithoutExtension(f);   // Collection Of file name with extention and filtering.\n\nvar getFileNameExcludeSomeExtension2 = from f in Directory.GetFiles(Server.MapPath("~/PDF/Requirement"))\n                                       where Path.GetExtension(f) != ".scc" && Path.GetExtension(f) != ".db"\n                                       select Path.GetFileName(f);   // Collection Of file name with out extention and filtering.	0
28712327	28711940	WPF DataGrid adds rows but not the data (blank rows)	public class Proxy\n{\n    public string ip {get; set;}\n    public string port {get; set;}\n}	0
25253400	24935484	How to use the nextToken in the ListMetrics function	// creates the CloudWatch client\nvar cw =  Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(Amazon.RegionEndpoint.EUWest1);\n// initialses the list metrics request\nListMetricsRequest lmr = new ListMetricsRequest();\nListMetricsResponse lmresponse = cw.ListMetrics(lmr);\n\nwhile (lmresponse.NextToken != null);\n{\n    // set request token \n    lmr.NextToken = lmresponse.NextToken;\n    lmresponse = cw.ListMetrics(lmr);\n\n    // Process metrics found in lmresponse.Metrics\n}	0
17930879	17837054	C# to VB.net - syntax issue with 2 dimmension array	MyBase.SetConfig(New EndpointHostConfig() With {\n   .GlobalResponseHeaders = New Dictionary(Of String, String) From {\n      {"Access-Control-Allow-Origin", "*"},\n      {"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"},\n      {"Access-Control-Allow-Headers", "Content-Type"}\n   }\n})	0
8042466	8042436	C# - String Replace	if (text.Length > 50) \n    text = text.Substring(0,50) + "...";	0
104222	104177	How do I embed an image in a .NET HTML Mail Message?	LinkedResource objLinkedRes = new LinkedResource(\n            Server.MapPath(".") + "\\fuzzydev-logo.jpg", \n            "image/jpeg");\nobjLinkedRes.ContentId = "fuzzydev-logo";       \nAlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(\n            "<img src='cid:fuzzydev-logo' />", \n            new System.Net.Mime.ContentType("text/html"));\nobjHTLMAltView.LinkedResources.Add(objLinkedRes);\nobjMailMessage.AlternateViews.Add(objHTLMAltView);	0
6192534	6192496	Generating random password in bulk	List<string> passwords = new List<string>();\n\nwhile (passwords.Length < 1000)\n{\n    string generated = System.Web.Security.Membership.GeneratePassword(\n                           10, // maximum length\n                           3)  // number of non-ASCII characters.\n    if (!passwords.Contains(generated))\n        passwords.Add(generated);\n}	0
13338128	13337873	GridView. How to display current values in empty fields?	protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n{\n    GridView1.EditIndex = e.NewEditIndex;\n    bindGridView1();\n}	0
6892506	6892483	Triggering an event whenever a new window is focused?	//at window load or at the constructor\nthis.Activated += OnWindowActivated;\n\nprivate void OnWindowActivated(object sender, EventArgs e)\n{\n     //your code here\n}	0
13237449	13236770	C#: Replace a single / with a *single* \	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Globalization;\n\nnamespace Test\n{\n    public class Program\n    {\n        public static void Main(string[] args)\n        {\n            Console.WriteLine(ConvertUnicodeEscapes("aa/u00C4bb/u00C4cc/u00C4dd/u00C4ee")); //  prints aa?bb?cc?dd?ee\n        }\n\n        private static Regex r = new Regex("/u([0-9A-F]{4})");\n        private static string ConvertUnicodeEscapes(string input)\n        {\n            return r.Replace(input, m => {\n                int code = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);\n                return char.ConvertFromUtf32(code).ToString();                    \n            } );\n        }       \n\n    }\n}	0
29295060	29295028	creating a default string in my string List	List<List<string>> chart = new List<List<string>>() { new List<String>() { "| |" }};	0
21567298	21517753	How to access nested grid view rows from parent RowUpdating method	GridViewRow ParentRow = gvEquipment.Rows[e.RowIndex] as GridViewRow;\nTable tb = ParentRow .Parent as Table;\nGridView gvChild = (GridView)tb.Rows[e.rowIndex +3].Cells[0].Controls[0];\n foreach (GridViewRow row in gvChild.Rows)\n {\n       //do update                         \n }	0
26460253	26420303	How to import data from one database to another	statement1 = SELECT myFields INTO OUTFILE @file;\n\nstatement2 = LOAD DATA LOCAL INFILE @file INTO TABLE myTable;	0
9466249	9466191	How can I return a object with the sum of all objects from a list using Linq?	foreach(var group in SpendlineList.GroupBy(x => x.Year))\n{\n   int year = group.Key;\n   int ammount = group.Sum(x => x.Ammount);\n}	0
6223687	6223652	How convert xaml to code behind?	BindingUtil.SetMultiBinding(Block, binding);	0
6219514	6219409	Implementation of class data validation	//Returns empty list if no errors.\npublic List<TunnelErrors> Validate()\n{\n    //Validate params\n}	0
8158723	8157828	SolrNet - Is there a way to build a Solr query using a for-loop?	var queries = checkboxlist\n    .Where(x => x.checked)\n    .Select(x => new SolrQueryByField(x.name, keyword))\n    .Cast<ISolrQuery>();\nvar query = new SolrMultipleCriteriaQuery(queries, SolrMultipleCriteriaQuery.Operators.AND);\nvar results = solr.Query(query, ...);	0
9369759	9369664	C# - Intrusive tree structure, using CRTP	class A : TreeNode<A> { }\nnew TreeNode<A>() //'this' is of type 'TreeNode<A>' but required is type 'A'	0
25289657	25289605	removing selected items from a checked list box	private void button_ekle_Click(object sender, EventArgs e)\n{   \n    for (int k = clb_input.Items.Count - 1; k >= 0; k--)\n    {\n        if (clb_input.GetItemChecked(k) == true)\n        {   \n            clb_output.Items.Add(clb_input.Items[k]);\n\n            // Remove from the Items collection, not from the CheckedItems collection\n            clb_input.Items.RemoveAt(k);\n        }\n        else { }\n    }\n}	0
10403570	10403544	How to reduce an if statement and pass multiple values to Contains?	List<string>validExtensions = new List<string>(){".jpg", ".jpeg" /* rest go here */ };\nif(validExtensions.Contains(myFilenameExension))\n{...}	0
1643826	1643790	csharp winform modal window, able to click on main window	Form f = new Form();\nf.Show(this);	0
22501861	22501781	Best way of concatenating one value of objects by comma separation? C#	string s = string.Join(",",Artists.Select(a => a.ArtistName));	0
23217057	23216649	How to pass Datatable to SQL Server using asp.net	dt.Columns.Add("Name", typeof(string));\n    dt.Columns.Add("Reg", typeof(long));	0
28708695	28708537	How do I add multiple attributes to an Enum?	public class TypeTextAttribute : Attribute\n{\n    public string TypeText;\n    public TypeTextAttribute(string typeText) { TypeText = typeText; }\n}	0
2735465	2713175	versioning in Fluent NHibernate	mapping.Version(x => x.Version);	0
29275962	29273828	Unity3d, C# pass function as parameter	public class ScriptA\n{\n    public delegate void MethodOneDelegate(int a, int b);\n\n    public void MethodOne(int a, int b)\n    {\n        Console.WriteLine(a + b);\n    }\n}\n\npublic static class ScriptB\n{\n    public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)\n    {\n        function(a, b);\n    }\n}\n\npublic static void Main()\n{\n    ScriptA scriptA = new ScriptA();\n    ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);\n}	0
25271619	25254212	How to convert a series of unicode characters into readable text?	var str = "\\u0434\\u0430\\u043C\\u043E";\n  var decoded = HttpUtility.HtmlDecode(Regex.Unescape(str)); //take a look the Regex.Unscape() call.	0
1547276	1547252	How do I concatenate two arrays in C#?	var z = new int[x.Length + y.Length];\nx.CopyTo(z, 0);\ny.CopyTo(z, x.Length);	0
25838192	25838152	Find timestamp closest to one hour ago in a list	list.OrderBy( x => Math.Abs((x.Date - desiredDate).TotalMilliseconds)).FirstOrDefault();	0
13041993	13041795	Splitting a dataset in to datatables	DataSet dsMain = GetMyMainDataSet();\n        DataSet dsTablesById = new DataSet();\n\n        foreach (DataRow row in dsMain.Tables[0].Rows)\n        {\n            string storeId = row["storeid"].ToString();\n            if (!dsTablesById.Tables.Contains(storeId))\n            {\n                dsTablesById.Tables.Add(storeId);\n                foreach (DataColumn col in dsMain.Tables[0].Columns)\n                {\n                    dsTablesById.Tables[storeId].Columns.Add(col.ColumnName, col.DataType);\n                }\n            }\n            dsTablesById.Tables[storeId].Rows.Add(row.ItemArray);\n            dsTablesById.Tables[storeId].AcceptChanges();\n        }	0
28766540	28766041	Formatting a column of List in C#	DataGrodView1DataSource = (from row in A select new {row.Period, Money = MakeMoney(Convert.ToString(row.Balance))}).ToList();	0
6807820	6713289	how to insert bookmark in word using c#/VB.NET	Dim _wordApp As ApplicationClass\nDim _doc As Document\nDim pos, len As Integer\nDim reg As Regex\nDim bookmarkName As String\nDim rng As Object\nDim search As String = "Some Text to search"\n\nDim nullobj As Object = System.Reflection.Missing.Value\nDim isReadOnly As Object = False\n_wordApp = New ApplicationClass()\n\n'open the word document\n_doc = _wordApp.Documents.Open(fileName, isReadOnly, nullobj, nullobj, nullobj, _\n     nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, _\n     nullobj, nullobj, nullobj, nullobj, nullobj)\n\n    _wordApp.Visible = False\n\n\n' keyword that you want to search\nreg = New Regex(search)\n' find the text in word file\nDim m As Match = reg.Match(_doc.Range.Text, 0)\npos = m.Index\n\n' start is the starting position of the token in the content...\nlen = search.Length\n' select the text\nrng = _doc.Range(pos, len + pos)\n\nbookmarkName = "MyBookmarkName"\n_doc.Bookmarks.Add(bookmarkName, rng)	0
15304174	15299946	Mapping private attributes of domain entities with Dapper dot net	var carRecord = DbConnection.Query<CarRecord>("select * from cars where id = @id", new {id = 1});\n        var carEntity = CarFactory.Build(carRecord);	0
6268018	6267016	How to type a grave accent/ back tick in a Visual Studio Console?	Console.Write((char) 96);	0
29197239	29197159	Show Text, Button and Pause	MessageBox.Show(string)	0
7174302	7174221	Crosshair cursor with additional lines in C#	private Cursor crossCursor(Pen pen, Brush brush, string name, int x, int y) {\n            var pic = new Bitmap(x, y);\n            Graphics gr = Graphics.FromImage(pic);\n\n            var pathX = new GraphicsPath();\n            var pathY = new GraphicsPath();\n            pathX.AddLine(0, y / 2, x, y / 2);\n            pathY.AddLine(x / 2, 0, x / 2, y);\n            gr.DrawPath(pen, pathX);\n            gr.DrawPath(pen, pathY);\n            gr.DrawString(name, Font, brush, x / 2 + 5, y - 35);\n\n            IntPtr ptr = pic.GetHicon();\n            var c = new Cursor(ptr);\n            return c;\n        }	0
3450446	3443118	WCF Data Services (oData): Dependency Injection with DataService	protected override MyEntityContext CreateDataSource() \n{\n    return ServiceLocator.Current.GetInstance<MyEntityContext>();\n}	0
23998900	23998664	How can calculate combinations on 2nd level array?	static IEnumerable<IEnumerable<T>> CartesianProduct<T>\n    (this IEnumerable<IEnumerable<T>> sequences)\n{\n    IEnumerable<IEnumerable<T>> emptyProduct =\n        new[] { Enumerable.Empty<T>() };\n    return sequences.Aggregate(\n        emptyProduct,\n        (accumulator, sequence) =>\n            from accseq in accumulator\n            from item in sequence\n            select accseq.Concat(new[] { item }));\n}	0
16975146	16975060	how should I give the user a selection and grab the guid from that selection	checkedListBox_Gateways.DisplayMember = "Key";\ncheckedListBox_Gateways.ValueMember = "Value";\ncheckedListBox_Gateways.Items.Add(new KeyValuePair<string, string>(gateway.Name, gateway.Id.ToString()));	0
2272112	2271881	Special Folders	Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)	0
8924779	8727944	Approaches to abstract class design which allow for edgecase method implementations with alternate arguments	public abstract class BaseClientService<T, R>\nwhere T : ISubsetInfo\n      R : IRequirement\n{\n    abstract T Extract(R requirement);\n}	0
9798260	9798178	Winforms DateTimePicker set default text and/or value	DateFrom.Checked = true;\n        DateFrom.Value = DateTime.Today.AddDays(-7);\n        if (DateFrom.Handle == null)\n            System.Threading.Thread.Sleep(0);\n        DateFrom.Checked = false;	0
13650209	13649762	DataGridView C# Help Needed	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)\n    {\n       MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());\n    }\n}	0
15992214	15991619	How to display a value as a percentage?	protected void Button1_Click(object sender, EventArgs e)     \n {\n int score = 0;\n\n if (qn1.SelectedValue == "Yes")\n    score++;\n if (qn2.SelectedValue == "Yes")\n    score++;\n if (qn3.SelectedValue == "Yes")\n    score++;\n if (qn4.SelectedValue == "Yes")\n    score++;\n if (qn5.SelectedValue == "Yes")\n    score++;\n\n literalScore.Text = (score*20).ToString() + " % ";\n }	0
24577473	24577417	Dynamically create an object with common properties	//\n// Use base class here\n//\nApplicant currentApplicant;\n\nswitch (Host)\n{\n    case "pilot":\n        currentApplicant = new PilotApplicant();\n        // set values for pilot\n        break;\n\n    case "cms":\n        CMSApplicant cmsApplicant = new CMSApplicant();\n        currentApplicant = cmsApplicant;\n        cmsApplicant.LocationName = (string)oReader["LocationName"];\n        break;\n\n    default:\n       currentApplicant  = null;\n       break;\n}	0
12831528	12831413	How to pass info to View from Index in this scenario - MVC3	public ActionResult Index()\n{   \n    var movies = new List<Movie>();\n\n    var songsPath = Server.MapPath("~/Content/themes/base/songs");\n    var folders = Directory.GetDirectories(songsPath);\n\n    foreach (var folder in folders)\n    {\n        Movie movie = new Movie();\n        movie.MovieName = new DirectoryInfo(folder).Name\n\n        string[] files = Directory.GetFiles(folder);\n\n        foreach (var file in files)\n        {\n            if (Path.GetExtension(file) == ".jpg" ||\n                Path.GetExtension(file) == ".png")\n            {\n                movie.Images.Add(Path.Combine(songsPath, file));\n            }\n            else \n            {\n                movie.Songs.Add(Path.Combine(songsPath, file));\n            }\n        }\n\n        movies.add(movie);\n    }\n    return View(movies);\n}	0
9032563	9032348	Is there easy way of calculating number of IPs from 2 given IP addresses?	int IPToInt(string IP)\n{\n    return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(IP).GetAddressBytes(), 0));\n}\n\nint num = IPToInt("127.0.1.10") - IPToInt("127.0.0.200") + 1;	0
13674804	13673373	How can I paste special unformatted plain text into Excel using C# and VSTO?	string textToPaste = (string)Clipboard.GetData("Text");\nClipboard.SetData("Text", textToPaste);\n((Excel.Range)Application.Selection).PasteSpecial(Excel.XlPasteType.xlPasteValues);	0
31653616	31626244	Retrieving the COM class factory for component with CLSID {688EEEE5-6A7E-422F-B2E1-6AF00DC944A6} failed	if([IntPtr]::size -eq 8) { Write-Host 'x64' } else { Write-Host 'x86' }	0
12031713	12031190	Metro Stye App Using File as DataSource No Async	Task<StorageFile> task = MyAsyncMethodThatGetsTheFile();\ntask.Wait();\nStorageFile file = task.Result;	0
5914216	5914104	How to find out the name of the constraint CHECK of a field in the MSAccess database?	DataTable.Constraints[Index].ConstraintName	0
14648435	14648186	How to show default/alternate image in datalist binded to image control	.DefaultImage {\n    background-position: center center;\n    background-image: url('Images/COMPUTER1.png');\n    background-repeat: no-repeat;\n}	0
15901252	15900687	How to deserialize an XML where element names are list-numerated?	var fieldElementNameRegex = new Regex(\n    "^field[0-9]+$",\n    RegexOptions.IgnoreCase | RegexOptions.Compiled);\n\nvar xml = XElement.Parse(xmlString);\n\nvar fieldElements = xml\n    .Descendants()\n    .Where(e => fieldElementNameRegex.IsMatch(e.Name.ToString()))\n    .ToArray();	0
12783890	12783337	Connecting to IMAP via StreamSocket in WinRT / C#	Environment.Newline	0
9820255	9264713	imapX illegal charachters in path	return _encoding.GetString(Convert.FromBase64String(contentStream));	0
31816202	31816054	Pass variable to WCF custom encoder?	public class MyTextMessageEncoder : MessageEncoder\n {\n\n        public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)\n        {\n            StreamReader sreader = new StreamReader(stream);\n            string msg = sreader.ReadToEnd();\n\n            stream.Seek(0, SeekOrigin.Begin);\n            XmlReader reader = XmlReader.Create(stream);\n            var message = Message.CreateMessage(reader, maxSizeOfHeaders, this.MessageVersion);\n            // Here I add my MessageHeader\n            var poweredBy = MessageHeader.CreateHeader(\n                            "X-Powered-By", "", "MyApp");\n\n            message.Headers.UnderstoodHeaders.Add(poweredBy);\n            return message;\n        }\n\n }	0
890601	890376	Add a control to the page header in ASP.NET	protected override void OnInit(EventArgs e)\n{\n    base.OnInit(e);\n    this.Page.PreRender += new EventHandler(Page_PreRender);\n}\n\nvoid Page_PreRender(object sender, EventArgs e)\n{\n    var scriptControl = new HtmlGenericControl("script");\n    Page.Header.Controls.Add(scriptControl);\n    scriptControl.Attributes["language"] = "javascript";\n    scriptControl.Attributes["type"] = "text/javascript";\n    scriptControl.Attributes["src"] = "blah.js";\n}	0
27783431	27716507	Receiving Gigs of data from Mobile Service on UpdateAsync method	[JsonIgnore]\npublic virtual Scenario Scenario { get; set; }	0
9119436	9119338	Declare a ThreadLocal dictionary	private ThreadLocal<IDictionary<string, MyClass>> myDictionary;	0
26530436	26530312	Recognizing the Menu Key in KeyDown	Keys.Apps	0
28058040	28057917	Showing a dynamic grid view from SQL select statement	protected void RefreshSQLDisplay(object sender, EventArgs e)\n{\n    foreach (BoundField col in GridView1.Columns)\n    {\n        if (col.DataField == "WeekEndingDate")\n        {\n            col.Visible = false;\n            break;\n        }\n    }\n}	0
537528	535606	How do I prevent DataRow cell values from being reset?	public DataTable ResultTable { get { return this[_resultKey]; } }\npublic DataTable this[string tableName]\n{\n    get { return _data.Tables[tableName].DefaultView.ToTable(); }\n}	0
12397001	12396840	How can I parse a TimeSpan with milliseconds included?	TimeSpan FrameTime = TimeSpan.Parse(StoredTime, DateTimeFormatInfo.InvariantInfo);	0
6215423	6215185	Getting length of video	using DirectShowLib;\nusing DirectShowLib.DES;\nusing System.Runtime.InteropServices;\n\n...\n\nvar mediaDet = (IMediaDet)new MediaDet();\nDsError.ThrowExceptionForHR(mediaDet.put_Filename(FileName));\n\n// find the video stream in the file\nint index;\nvar type = Guid.Empty;\nfor (index = 0; index < 1000 && type != MediaType.Video; index++)\n{\n    mediaDet.put_CurrentStream(index);\n    mediaDet.get_StreamType(out type);\n}\n\n// retrieve some measurements from the video\ndouble frameRate;\nmediaDet.get_FrameRate(out frameRate);\n\nvar mediaType = new AMMediaType();\nmediaDet.get_StreamMediaType(mediaType);\nvar videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));\nDsUtils.FreeAMMediaType(mediaType);\nvar width = videoInfo.BmiHeader.Width;\nvar height = videoInfo.BmiHeader.Height;\n\ndouble mediaLength;\nmediaDet.get_StreamLength(out mediaLength);\nvar frameCount = (int)(frameRate * mediaLength);\nvar duration = frameCount / frameRate;	0
10997244	10997171	Counting total rows in query	WITH cte\n     AS (SELECT t.*,\n                Row_number() OVER (ORDER BY Id) AS RowNum,\n                count(*) over() as Cnt\n         FROM   (SELECT *\n                 FROM   Table1\n                 UNION\n                 SELECT *\n                 FROM   Table2) t)\nSELECT *\nFROM   cte\nWHERE  RowNum BETWEEN @offset AND @offset + @limit	0
26508593	26507180	How do I set a nonstatic delegate in a WinForm?	[Browsable(false)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic System.Func<string, bool> IsValid { get; set; }	0
15590299	15589955	Assigning SQL value retrieved of dept to Session["UserAuthentication"]	object CurrentName = com.ExecuteScalar();\nif (CurrentName != null && CurrentName != System.DBNull.Value) {\n    {\n        Session["UserAuthentication"] = (string)CurrentName;\n        Session.Timeout = 1;\n        Response.Redirect("Default.aspx");\n    }\n    else\n    {\n        Session["UserAuthentication"] = "";\n    }\n}	0
13819243	13819133	How to make timed dialog that waits for response for max 30 seconds?	Timer time1 = new Timer();\ntime1.Elapsed += new ElapsedEventHandler(OnTimedEvent);\ntime1.Interval = 30000; // 30 secs\n...\ntime1.Enabled = true; // Start the timer\nmessage.ShowDialog();\n\nprivate void OnTimedEvent(object source, ElapsedEventArgs e)\n{\n    // Close your Form\n    message.Close();\n    // Maybe you could set a variable, that indicates you, that the timer timed out\n\n}	0
20605680	20546087	Add new word to windows speech recognition using C#	ISpLexicon::AddPronunciation	0
9202789	9202683	Adding to a Dictionary within a dictionary	testDictionary[userAgentResult] = allowDisallowDictionary;	0
15704560	15692674	Is the behaviour of DrawLine predictable with out of range parameters?	SolidBrush WhiteBrush = new SolidBrush(Color.White);\nmyGraphics.FillRectangle(WhiteBrush,0,0,5000,5000);	0
1356368	1356315	Datagridview Display	DataTable dt=new DataTable();\ndt.Columns.Add("No",typeof(int)); // Adding column into ColumnsCollection\ndt.Columns.Add("Name");\n\ndt.Rows.Add(1,"AAA");  // Adding rows into RowsCollection\ndt.Rows.Add(2,"BBB");\n\nDataGridView1.DataSource=dt; // Binding datasource	0
5077358	5077347	convert string to datetime in c#	DateTime.Parse(yourDateString, CultureInfo.GetCultureInfo("en-US"));	0
22905459	22903350	How can I create a way for my repository to do an Upsert?	public virtual void Save(TEntity entity)\n{\n    // assuming TEntity as property "Id" [Key] of type int\n    ((IObjectState) entity).ObjectState = entity.Id <= 0 ? ObjectState.Added : ObjectState.Modified;\n    _dbSet.Attach(entity);\n    _context.SyncObjectState(entity);\n}	0
14770062	14758436	Entity Framework Fluent, Table-Per-Type performance alternatives	IList<MyBaseClass> items = new List<MyBaseClass>();\n\nObjectContext oContext = ((IObjectContextAdapter)dbContext).ObjectContext;\n\nusing (var sqlConn = new SqlConnection(dbContext.Database.Connection.ConnectionString))\n{\n    SqlCommand sqlComm = new SqlCommand(){\n        Connection = sqlConn,\n        CommandText = "spGetMyDerivedItems",\n        CommandType = CommandType.StoredProcedure\n    };\n    sqlConn.Open();\n\n    using (SqlDataReader reader = command.ExecuteReader())\n    {\n        oContext.Translate<MyFirstDerivedClass>(reader).ToList().ForEach( x => items.Add(x));\n        reader.NextResult();\n        ...repeat for each derived type...          \n    }\n}\n\nreturn items;	0
18986835	18985855	C# Textbox enters info but leaves a ' * ' in textbox	e.Handled = true;	0
14405812	14395514	How to add facebook rss feeds using c# in a windows 8 application?	// this example pulls coca-cola's posts\nvar _Uri = new Uri("http://www.facebook.com/feeds/page.php?format=rss20&id=40796308305");\n\n// including user agent, otherwise FB rejects the request\nvar _Client = new HttpClient();\n_Client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");\n\n// fetch as string to avoid error\nvar _Response = await _Client.GetAsync(_Uri);\nvar _String = await _Response.Content.ReadAsStringAsync();\n\n// convert to xml (will validate, too)\nvar _XmlDocument = new Windows.Data.Xml.Dom.XmlDocument();\n_XmlDocument.LoadXml(_String);\n\n// manually fill feed from xml\nvar _Feed = new Windows.Web.Syndication.SyndicationFeed();\n_Feed.LoadFromXml(_XmlDocument);\n\n// continue as usual...\nforeach (var item in _Feed.Items)\n{\n    // do something\n}	0
23132830	23132555	Linq, group by DateTime.Date and then group by another criterium	group myData by new { myData.TimeStamp.Date,\n       Hour = (int) myData.TimeStamp.TimeOfDay.TotalMinutes / 60 } into barData	0
2232755	2232666	write innertext in xml file	XDocument xdoc = XDocument.Load(@"C:\configfolder\config.xml");\nxdoc.Root.Element("OVERRIDE_CONFIG_FILE_NAME").SetValue("HelloThere");\nxdoc.Save(@"C:\so2.xml");	0
2093446	2093397	C# XML Object Serialization: setting xmlns root attribute	[System.Xml.Serialization.XmlRoot(Namespace="http://topLevelNS")]\nclass MyClass\n{\n    [System.Xml.Serialization.XmlElement(Namespace = "http://SomeOtherNS")]\n    public int MyVar { get; set; }\n}	0
18863909	18862485	Radgrid customizing insert template	grid.MasterTableView.Columns.Add(boundColumn);\ngrid.MasterTableView.EditMode = GridEditMode.InPlace; // I have Added this line\nPlaceHolder1.Controls.Add(grid);	0
24685723	24685515	Display German characters in DataGridView	string[] lines = File.ReadAllLines(txtDRGFileName.Text, Encoding.Default);	0
26546354	26546280	Populate ViewModel with data returned from Entity Framework query	public VmPerson LoadPersonById(int personId)\n    {\n        using (var context = new Context())\n        {\n\n            var r = (from p in context.Person\n                join a in context.PersonAddress on p.PersonId equals a.PersonId\n                join e in context.PersonEmployment on p.PersonId equals e.PersonId\n                where p.PersonId == personId\n                select new VmPerson\n                {\n                    Person = p,\n                    PersonAddress = a,\n                    PersonEmploymentHistory = e\n                }).FirstOrDefault();\n\n            return r;\n        }\n    }	0
28090233	28088330	How do you match various date formats using C# regex and get the day, month and year?	var datePatternRegex = new Regex(@"\b\d{1,2}(/|-|.|\s)\d{1,2}(/|-|.|\s)(\d{4}|\d{2})");\nvar testData = new []{\n"This is test1 10/10/1012 data",\n"This is test2 1/1/1012 data",\n"This is test3 10-10-1012 data",\n"This is test4 1-1-1012 data",\n"This is test5 10.10.1012 data",\n"This is test6 1.1.1012 data",\n"This is test7 10 10 1012 data",\n"This is test8 1 1 1012 data",\n};\n\nforeach(var data in testData)\n{\n    Console.WriteLine("Parsing {0}", data);\n\n    var match = datePatternRegex.Match(data);\n    if(match.Success)\n    {\n        var result = match.Groups[0];\n        Console.WriteLine(result.Value);\n    }\n    else\n    {\n        Console.WriteLine("No Match");\n    }\n}	0
11543802	11543565	How can I slide a Form under the Windows taskbar and set transparency off?	Screen.PrimaryScreen.WorkingArea	0
23807158	23806904	C# DataGridView get selected row number Exception	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n{\n   this.Text = dataGridView1.SelectedCells[0].RowIndex.ToString();\n}	0
11954098	11953444	Filtering DataTable based on column data and assign it to DataGridView in C#	public void EventTypeFilter()\n{\n    DataTable table = dataSourceDataSet.Tables["TableName"];        \n    table.DefaultView.RowFilter = string.Format("EventType <> '{0}'", "Exam");\n    EventsDataGridView.DataSource = table;           \n}	0
1614000	1613964	How can I reference a method from another class without instantiating it?	// the original form\nclass MyForm()\n{\n     // form public method\n     public void MyMethod() { ... }\n}\n\n// class storing the reference to a form\nclass MyOtherClass\n{     \n    public static Form MyForm;\n\n    public void ShowForm()\n    {\n        MyForm = new MyForm();\n        MyForm.Show();\n    }\n}\n\n// invoke form public method in this class\nclass YetAnotherClass\n{\n    public void SomeMethod ()\n    {\n        MyOtherClass.MyForm.MyMethod();\n    }\n}	0
21876257	21875782	Extract Listbox's binded textblock to string wp7	var yourClassName = ListBox1.SelectedItem as YourClassType;\nNavigationService.Navigate(new Uri(String.Format("/TargetPage.xaml?param={0}", yourClassName.LineOne),  UriKind.Relative));	0
4427475	4427339	winforms - tooltip of statusbar labels not showing up	statusStrip1.ShowItemToolTips = true;\nstatusLblWeek.Text = weeklyHrs.ToString();\nstatusLblWeek.ToolTipText = " Consumption of this week " + statusLblWeek.Text;	0
12490433	12490337	iterate through a string[] List<string> fetch results alphabetically	public static List<string> GenerateMonthNames(string prefixText)    \n{\n    var items = new List<string>();\n    items.Add("Oliver");\n    items.Add("Olsen");\n    items.Add("learns");\n    items.Add("how");\n    items.Add("change");\n    items.Add("world");\n    items.Add("engaging");  \n\n    var returnList = items.Where(item=>item.Contains(prefixTest)).ToList();\n    returnList.Sort();\n\n    return returnList;\n}	0
14506786	14494572	Cancel all but last task	CancellationTokenSource cts = null;\nasync void Button1_Click(...)\n{\n  // Cancel the last task, if any.\n  if (cts != null)\n    cts.Cancel();\n\n  // Create Cancellation Token for this task.\n  cts = new CancellationTokenSource();\n  var token = cts.Token;\n\n  // Method to run asynchonously\n  Func<int> taskAction = () =>\n  {\n    // Something time consuming\n    Thread.Sleep(5000);\n    token.ThrowIfCancellationRequested();\n    return 100;\n  };\n\n  try\n  {\n    int i = await Task.Run(taskAction);\n  }\n  catch (OperationCanceledException)\n  {\n    // Don't need to do anything\n    return;\n  }\n}	0
243168	243152	How can I write a conditional lock in C#?	Action doThatThing = someMethod;\n\nif (condition)\n{\n  lock(thatThing)\n  {\n     doThatThing();\n  }\n}\nelse\n{\n  doThatThing();\n}	0
6896865	6896796	How can add an additional row to a LINQ query?	var manufacturers = (from m in manufacturerEngine.EngineFilter\n                     select new { m.ManufacturerID, m.Manufacturer }\n                    ).Distinct().ToList();\n\nmanufactorers.Add(new { ManufacturerID = -1, Manufacturer = "(All)" });\n\ncboManufacturerFilter.DataSource = manufacturers.ToArray();\n// ... etc ...	0
2606547	2606322	How to check if string is a namespace	public bool NamespaceExists(IEnumerable<Assembly> assemblies, string ns)\n{\n    foreach(Assembly assembly in assemblies)\n    {\n        if(assembly.GetTypes().Any(type => type.Namespace == ns))\n            return true;\n    }\n\n    return false;\n}	0
10475391	10475302	Find file in program files and launch that file	if (files.Length == 1)\n{\n    Process.Start(files[0]);\n}	0
4552145	4551794	How to add to a list the largest number of selected items in a list when there are two groups of selected items?	var indices = lb.SelectedIndices;\nint count = 0;\nint max = 0;\nint first = -1;\nfor (int i = 0; i < indices.Count; i++)\n{\n    ++count;\n    if (i == indices.Count - 1 || indices[i]  + 1 != indices[i + 1])\n    {\n        if (count > max)\n        {\n            max = count;\n            first = i - count + 1;\n        }\n        count = 0;\n    }\n}\n// max is the longest consecutive subsequence\n// first is its starting index	0
19215975	19215967	How to get a DataGrid column name when the header is clicked, WPF	private void columnHeader_Click(object sender, RoutedEventArgs e)\n{\n    string header = ((DataGridColumnHeader)sender).Content.ToString;\n}	0
28368555	27967573	Add blank spaces in the beggining and end of each line C#	using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nnamespace StringLineSpaceAdd\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            TextReader r = File.OpenText(@"D:\myFile.txt");\n            string currentLine="";\n            HashSet<string> previousLines = new HashSet<string>();\n            TextWriter w = File.CreateText(@"D:\\newFile.txt");\n            while ((currentLine = r.ReadLine()) != null)\n            {\n                // Add returns true if it was actually added,\n                // false if it was already there\n                if (previousLines.Add(currentLine))\n                {\n                    currentLine = " " + currentLine + " ";\n                    w.WriteLine(currentLine);\n                }\n            }\n            w.Close();\n        }\n    }\n}	0
14961178	14900265	Have ServiceStack default route go to MVC3 Controller	public override void Configure(Funq.Container container)\n{\n  //  Other Configuration constructs here\n\n  ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>();\n}	0
6964976	6964966	How do I subtract a second from a DateTime in Windows Phone 7?	EndTime = time.AddSeconds(-10)	0
7813627	7813615	How to get just folder path without the actual folder name?	directory.Parent	0
6708058	6708019	Convert String to Variable Name	this.Controls.Find("name_of_your_combobox");	0
4752464	4752355	Generic way to exit a .NET application	if (System.Windows.Forms.Application.MessageLoop)\n{\n  // Use this since we are a WinForms app\n  System.Windows.Forms.Application.Exit();\n}\nelse\n{\n  // Use this since we are a console app\n  System.Environment.Exit(1);\n}	0
21958784	21958429	Refactor Implicit Variable Assignment in Array to Explicit Assignment Outside of Array	new Person { Name = "Alicia", Age = 33 }	0
17204932	17204808	Overwriting Elements in Linq to XML	XElement xelement = XElement.Load("C:\\members.xml");\nIEnumerable<XElement> members = xelement.Elements();\nmembers.First(x => x.Element("AccountName").Value == memberName).Element("AccountBalance").Value = newBalance;\nxelement.Save("C:\\members.xml");	0
12232710	12232703	C# WinForms How to increase number with specific format	0.ToString("D4"); // "0000"\n1.ToString("D4"); // "0001"	0
30724528	30723949	How to return List of strings from C# to Managed c++	List<string>^ myvar = ManagedCSharp::ManagedClass::ShowValue();	0
23001452	23001409	LINQ to XML - Dynamic Element Select	List<string> names = (...)\n\ncsv +=\n    (from el in xmlDoc.Descendants("customer")\n     select String.Join("|", names.Select(x => (string)el.Element(x)))\n    )\n    .Aggregate(\n        new StringBuilder(),\n        (sb, s) => sb.AppendLine(s),\n        sb => sb.ToString()\n    );	0
29878012	29877904	Get all controls with names that start with specific string	foreach (Label l in this.Controls.OfType<Label>().Where(l => l.Name.StartsWith("tafel_noemer_")))\n{\n    l.Text = "bla bla";\n}	0
12036167	12035720	windows phone navigation immediately after loading page	public MainPage()\n{\n    InitializeComponent();\n\n    Loaded += (s, e) =>\n    {\n        InitializeSettings();\n\n        // Some login-password check condition\n        if (_login && _password)\n            NavigationService.Navigate(new Uri("/Conversation.xaml",\n                                               UriKind.Relative));\n    }\n}	0
9044116	9044081	"Forcing" Conformance to a Generic Constraint	if (typeof(T).IsClass)\n{\n    Type targetType = typeof(Target<>).MakeGenericType(typeof(T));\n    return Activator.CreateInstance(targetType);\n}\n...	0
3265015	3264747	Check signature for x509 certificate	string sha1Oid = CryptoConfig.MapNameToOID("SHA1");\nstring md5Oid = CryptoConfig.MapNameToOID("MD5");\nbool sha1Valid = rsa.VerifyHash(data, sha1Oid, signature);\nbool md5Valid = rsa.VerifyHash(data, md5Oid, signature);\nvalid = sha1Valid || md5Valid;	0
24513092	24512998	Is it possible to create a excel or csv from a windows phone application?	"Name","Age","Gender"\n"Jenny",21,"Female"\n"Bloggs, Fred",25,"Male"	0
26305923	26305857	Insert image to local SQL Server database in ASP.NET	int length = FileUpload.PostedFile.ContentLength;\nbyte[] picSize = new byte[length];\nHttpPostedFile uplImage= FileUpload.PostedFile;\nuplImage.InputStream.Read(picSize, 0, length);\n\nusing (SqlConnection con = new SqlConnection(connectionString))\n{\n    SqlCommand com = new SqlCommand("INSERT INTO [Table] (Name, Picture) values (@Name, @Picture)", con);\n    try\n    {\n        com.Parameters.AddWithValue("@Name", TextName.Text);\n        com.Parameters.AddWithValue("@Picture", picSize);\n        com.ExecuteNonQuery();\n    }\n    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    }\n}	0
21621672	21621403	Passing Values from One Form to an Other Form as Consutrutor Parameters	{\n        private void btn_Click(object sender, EventArgs e)\n        {\n         int a=1;\n         int b=2;\n         int c=3;\n\n         Form2 frm=new Form2(a,b,c);\n         frm.show();\n        }\n    }\n//form2\n\n\n {\n     private int a=b=c=0; \n\n     //it will be main load of your form \n     public Frm2()\n            {\n                InitializeComponent();\n\n            } \n\n     //pass values to constructor \n     public Frm2(int a, int b, int c)\n            {\n                InitializeComponent();\n                this.a = a;\n                this.b = b;\n                this.c = c;\n            } \n    }	0
5426714	5426496	How can I Change the default scale and precision of decimals in Fluent NHibernate?	public class DecimalConvention : IPropertyConvention\n    {\n        public void Apply(IPropertyInstance instance)\n        {\n            if (instance.Type == typeof(decimal) || instance.Name == "Value") //Set the condition based on your needs\n            {\n               instance.Precision(22).Scale(12);    \n            }\n        }\n    }	0
20168515	20168094	How do i parse the current exactly letter/char only?	// Obtain the character index where the user clicks on the control.\nint positionToSearch = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));\nchar currentChar = richTextBox1.Text[positionToSearch];// Get the character the cursor is on.\nwords.Items.Add(currentChar); // Add the current character to our list.	0
2578386	2578361	Passing more than one argument in asp.net button in gridview	void Button2_Click(object o, EventArgs e) {\n    Button myButton = (Button)o;\n    GridViewRow row = (GridViewRow)muButton.Parent.Parent;\n\n    string value1 = row.Cells[0].Text;\n    string value2 = row.Cells[1].Text;\n    ...\n}	0
23392483	23392357	Search every occurence of a substring in a string C#	string haystack = "(anything)....bbb....(anything)";  \nstring needle = "bb"; \nint pos = 0;\nwhile((pos = haystack.IndexOf(needle, pos)) != -1)\n{\n    Console.Write("Found at pos:" + pos.ToString());\n    Console.WriteLine(" - " + haystack.Substring(pos, needle.Length));\n    pos++;\n}	0
1087714	1087389	Passing a dynamic attribute to an internal constructor	public class Test\n{\n    internal Test(string x)\n    {\n    }\n\n    static void Main()\n    {\n        dynamic d = "";\n        new Test(d);\n    }\n}	0
23548622	23547749	c# Split Strings Into Separate Text Boxes	//split apart segments\nstring[] split1 = textBox2.Text.Split(';');\nforeach (string segment in split1)\n        {\n            //split sub-segment\n            string[] split2 = segment.Split(':');\n\n            //check if it's valid\n            if (split2.Count().Equals(2))\n            {\n                textBox3.Text += String.Format("{0}{1}", split2[0].Trim(), Environment.NewLine);\n                    textBox4.Text += String.Format("{0}{1}", split2[1].Trim(), Environment.NewLine);\n            }\n            else\n            {\n                throw new ArgumentException("Invalid Segment");\n            }\n        }	0
22323266	22314062	How after updating data from one of the UI (at network) reload data at other UIs and keep relatioship?	private void reloadbtn_Click(object sender, RoutedEventArgs e)\n    {\n     dbMRCPe.dbmrcpnephrologyEntities ctx2 = new dbMRCPe.dbmrcpnephrologyEntities();\n     ctx = ctx2;\n     topicmainViewSource.Source = ctx.topicmains;\n\n    }	0
32454915	32454435	Accessing ASP.net application hosted on one server from multiple machines on the network at the same time	static int i	0
32492280	32492253	C# How to check if a number is any of the group values?	if (new[] {2, 4, 8}.Contains(op.scale))	0
2788296	2736097	DataAnnotations validation from a class	internal static class DataAnnotationsValidationRunner\n{\n    public static IEnumerable<ErrorInfo> GetErrors(object instance)\n    {\n        return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()\n               from attribute in prop.Attributes.OfType<ValidationAttribute>()\n               where !attribute.IsValid(prop.GetValue(instance))\n               select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);\n    }\n}	0
2692438	2692372	bug in NHunspell spelling checker	MyThes thes = new MyThes("th_en_us_new.dat");	0
28927412	28927402	Best way to pause application in for statement	Await Task.Delay(TimeSpan.FromSeconds(1))	0
13718334	13718305	How to convert List<String> to Dictionary<int,String>	var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);	0
24628957	24628812	How to detect Windows 8 app going to background	Window.Current.VisibilityChanged += (s, e) => \n{\n    if (!e.Visible)\n    {\n        // Application went to background\n    }\n    else \n    {\n        // Application is FullScreen again\n    }\n};	0
2874385	1763696	How can I make a read-only ObservableCollection property?	public class Source\n{\n    Source()\n    {\n        m_collection = new ObservableCollection<int>();\n        m_collectionReadOnly = new ReadOnlyObservableCollection<int>(m_collection);\n    }\n\n    public ReadOnlyObservableCollection<int> Items\n    {\n        get { return m_collectionReadOnly; }\n    }\n\n    readonly ObservableCollection<int> m_collection;\n    readonly ReadOnlyObservableCollection<int> m_collectionReadOnly;\n}	0
14503045	14501562	Dynamically load dll from android_assets folder	const String pluginPath = "Plugins";\n\nvar pluginAssets = Assets.List(pluginPath);\nforeach (var pluginAsset in pluginAssets)\n{\n    var file = Assets.Open(pluginPath + Java.IO.File.Separator + pluginAsset);\n\n    using (var memStream = new MemoryStream())\n    {\n        file.CopyTo(memStream);\n\n        //do something fun.\n        var assembly = System.Reflection.Assembly.Load(memStream.ToArray());\n        Console.WriteLine(String.Format("Loaded: {0}", assembly.FullName));\n    }\n\n}	0
4712095	4712052	Help me parsing the following file format	string[]  parts = line.Split(':');\n   // assert parts.Length == 2\n   string tag = parts[0].Trim();\n   string[] values = parts[1].Split(' ', SplitOptions.NoDupes);  // or ','	0
18257597	18257119	Universal value for dictionary	using System.Runtime.InteropServices;\n[StructLayout(LayoutKind.Explicit)]\nstruct ByteArray {\n  [FieldOffset(0)]\n  public byte Byte1;\n  [FieldOffset(1)]\n  public byte Byte2;\n  [FieldOffset(2)]\n  public byte Byte3;\n  [FieldOffset(3)]\n  public byte Byte4;\n  [FieldOffset(4)]\n  public byte Byte5;\n  [FieldOffset(5)]\n  public byte Byte6;\n  [FieldOffset(6)]\n  public byte Byte7;\n  [FieldOffset(7)]\n  public byte Byte8;\n  [FieldOffset(0)]\n  public int Int1;\n  [FieldOffset(4)]\n  public int Int2;\n}	0
11963443	11963425	read xml file by linq	List<Device> devices = new List<Device>(loaded.Descendants("Device")\n                                             .Select(e =>\n                                               new Device(e.Element("username").Value,\n                                                          e.Element("AgentName").Value,\n                                                          e.Element("password").Value,\n                                                          e.Element("domain").Value\n                                                         )));	0
6470225	6469727	Hierarchial data in silverlight datagrid	public class Foo{\nobject Col1 {get;set;}\nobject Col2 {get;set;}\n\nobject Col50 {get;set;}\nNestedFoo[] NestedData {get;set;}}\n\npublic class NestedFoo{\nobject NestedCol1 {get;set;}\nobject NestedCol2 {get;set;}\n\nobject NestedCol50 {get;set;}}	0
5066905	5065552	Unable to access over a network using WCF	string hostName = System.Net.Dns.GetHostName();\nint port = 8080;\nUri serviceUri = new Uri(string.Format("http://{0}:{1}", hostName, port.ToString()));\n\n\nEndpointAddress endpoint = new EndpointAddress(serviceUri);	0
26355080	26354944	trying to check textbox value against values in a dataset column	foreach (DataRow row in table.Rows)\n{\n\n   if (row["CompanyName"].ToString() == TXTBXCustomerLookup.Text)\n   {\n      BTNUpdateCustomer.Enabled = true;\n      BTNDeleteCustomer.Enabled = true;\n      break; // condition matched break loop here no need to iterate further\n   }\n\n}	0
10472279	10472186	Read memory from process at dll in C#	using System;\nusing System.Diagnostics;\n\nclass Program {\n    static void Main(string[] args) {\n        var prc = Process.Start("notepad.exe");\n        prc.WaitForInputIdle();\n        foreach (ProcessModule module in prc.Modules) {\n            if (string.Compare(module.ModuleName, "user32.dll", true) == 0) {\n                Console.WriteLine("User32 loaded at 0x{0:X16}", (long)module.BaseAddress);\n                break;\n            }\n        }\n        prc.Kill();\n        Console.ReadLine();\n    }\n}	0
2608738	2608727	How does one calculate CPU utilization programmatically?	var p = System.Diagnostics.Process.GetCurrentProcess();\nvar span = p.TotalProcessorTime;	0
15906535	15906413	Set Created By value in Sitecore	using (new Sitecore.SecurityModel.SecurityDisabler())\n{\n    item.Editing.BeginEdit();\n    item[Sitecore.FieldIDs.Created] = Sitecore.DateUtil.ToIsoDate(DateTime.Now);\n    item.Editing.EndEdit();\n}	0
10877836	10877674	How to get file path of selected file?	Path.GetDirectoryName(dlg.Filename)	0
894516	894264	Fluent NHibernate Automapping: Alter DateTime to Timestamp	public class AlbumMappingOverride : IAutoMappingOverride<Album>\n{\n    public void Override(AutoMap<Album> mapping)\n    {\n        mapping.Map(x => x.Created).CustomSqlTypeIs("timestamp");\n    }\n}	0
21929567	21904527	EF: how to delete many-to-many relationship without loading more than is needed	var db = new TopicDBEntities();\n\nvar topic = new Topic { TopicId = 1 };\nvar subscription = new Subscription { SubscriptionId = 2};\ntopic.Subscriptions.Add(subscription);\n\n// Attach the topic and subscription as unchanged \n// so that they will not be added to the db   \n// but start tracking changes to the entities\ndb.Topics.Attach(topic);\n\n// Remove the subscription\n// EF will know that the subscription should be removed from the topic\ntopic.subscriptions.Remove(subscription);\n\n// commit the changes\ndb.SaveChanges();	0
14147959	14147897	How to use Actionmailer.Net.Standalone in a console application?	string template = "Hello @Model.Name! Welcome to Razor!";\nstring result = Razor.Parse(template, new { Name = "World" });	0
5417661	5415324	Adding a Row to Table of Late Bound MS Word	public void AddNewRow(int tableId, int rowCount)\n    {\n        object[] oParams = new object[1];\n        oParams[0] = tableId;\n        object table_ = tables.GetType().InvokeMember("Item",\n        BindingFlags.InvokeMethod,\n        null,\n        tables,\n        oParams);\n        object rows = table_.GetType().InvokeMember("Rows",\n        System.Reflection.BindingFlags.GetProperty,\n        null,\n        table_,\n        null);\n        oParams = new object[1];\n        if (rowCount == 1)\n        {\n            object row = rows.GetType().InvokeMember("Add",\n            BindingFlags.InvokeMethod,\n            null,\n            rows,\n            null);\n        }\n        else\n        {\n            for (int i = 0; i < rowCount; i++)\n            {\n                object row = rows.GetType().InvokeMember("Add",\n            BindingFlags.InvokeMethod,\n            null,\n            rows,\n            null);\n            }\n        }\n    }	0
6999224	6998923	How do I properly open a file for deletion?	using (FileStream file = new FileStream(path,\n       FileMode.Open,\n       FileAccess.ReadWrite,\n       FileShare.Delete))\n    {\n        // you can read the file here and check your stuff\n        File.Delete(path);\n    }	0
8526016	8525045	Print and open drawer with Epson T20 (thermal printer)	PosExplorer explorer = null;\n    DeviceInfo _device;\n    PosPrinter _oposPrinter;\nstring LDN;\n\n    explorer = new PosExplorer();\n    _device = explorer.GetDevice(DeviceType.PosPrinter, LDN);\n    _oposPrinter = (PosPrinter)explorer.CreateInstance(_device);\n    _oposPrinter.Open();\n    _oposPrinter.Claim(10000);\n    _oposPrinter.DeviceEnabled = true;\n // normal print\n    _oposPrinter.PrintNormal(PrinterStation.Receipt, yourprintdata); \n// pulse the cash drawer pin  pulseLength-> 1 = 100ms, 2 = 200ms, pin-> 0 = pin2, 1 = pin5\n    _oposPrinter.PrintNormal(PrinterStation.Receipt, (char)16 + (char)20 + (char)1 + (char)pin + (char)pulseLength); \n\n// cut the paper\n    _oposPrinter.PrintNormal(PrinterStation.Receipt, (char)29 + (char)86 + (char)66)\n\n// print stored bitmap\n    _oposPrinter.PrintNormal(PrinterStation.Receipt, (char)29 + (char)47 + (char)0)	0
7316576	7315563	How to check if is descendant within tree structure?	static bool GetIsDescendant(long idChild, long idAncestor, IEnumerable<Employee> employees)\n{\n    return GetAncestors(idChild, employees).Any(t => t.Id == idAncestor);\n}\n\nstatic IEnumerable<Employee> GetAncestors(long idEmployee, IEnumerable<Employee> employees)\n{\n    var employee = employees.SingleOrDefault(e => e.Id == idEmployee);\n\n    if (employee == null)\n    {\n        yield break;\n    }\n\n    while (employee.ParentId.HasValue)\n    {\n        var parent = employees.SingleOrDefault(e => e.Id == employee.ParentId.Value);\n\n        if (parent == null)\n        {\n            yield break;\n        }\n        else\n        {\n            employee = parent;\n            yield return parent;\n        }\n    }\n}	0
16194679	16194560	Getting data between values and greater than	2.1 >= d.Value.Value1 && !(2.1 >= d.Value.Value2)	0
24529024	24528689	try insert data to Excel file using OLEDB	Microsoft.Office.Interop.Excel.dll	0
2148325	2148310	Defining C# enums with descriptions	public enum SomeEnum: int\n{\n    [Description("Name One")]\n    NameOne = 1,\n}	0
24621374	24615575	Content from referenced project being removed on startup	static void Main(string[] args)\n{\n    var assembly = Assembly.GetExecutingAssembly();\n    var resourceName = "readEmbeddedResourceFile.Resources.MyFile.txt";\n\n    using (Stream stream = assembly.GetManifestResourceStream(resourceName))\n    {\n        if (null != stream)\n        {\n            byte[] b1 = new byte[stream.Length]; // creat an array to hold the file\n            stream.Read(b1, 0, (int)b1.Length); // read the file from the embedded resource\n            File.WriteAllBytes("MyFile.txt", b1); // write the file to the current execution directory\n        }\n    }\n}	0
8144863	8144675	how do I get a cell of data from a specific row in c# with a local sql database file	// See http://www.connectionstrings.com/ for how to build your connection string\nSqlConnection sqlConnection1 = new SqlConnection("Your Connection String");\nSqlCommand cmd = new SqlCommand();\nObject returnValue;\n\ncmd.CommandText = "SELECT COUNT(*) FROM Customers";\ncmd.CommandType = CommandType.Text;\ncmd.Connection = sqlConnection1;\n\nsqlConnection1.Open();\n\nreturnValue = cmd.ExecuteScalar();\n\nsqlConnection1.Close();	0
164814	164802	How do I access a public property of a User Control from codebehind?	MyUserControl myControl = (MyUserControl)e.item.FindControl("NameInASPX");\nmyControl.MyCustomProperty = foo;	0
10951541	10951478	Using INSERT INTO across local databases	using (SqlConnection connection = new SqlConnection("DataSource=..."))\nusing (SqlComamnd command = connection.CreateCommand())\n{\n    command.CommandText = "INSERT INTO ...";\n\n    connection.Open();\n    int i = command.ExecuteNonQuery(); // number of rows inserted\n}	0
9610080	9610036	Write string to a stream using utf16 encoding	System.Text.Encoding encoding = System.Text.Encoding.Unicode; \nBinaryWriter bw = new BinaryWriter (pStream, endoding);	0
3852066	3852048	two ways of displaying a decimal	implicit operator	0
15523138	14847831	WPF Command Line and MvvmLight with designdata	ViewModelLocator locator;\nif (!Resources.Contains("Locator"))\n{\n    locator = new ViewModelLocator();\n    Resources.Add("Locator", locator);\n}\nelse\n{\n    locator = (ViewModelLocator) Resources["Locator"];\n}\n\nWorkingWindow mainWindow = new WorkingWindow();\nmainWindow.ShowDialog();	0
21639368	21634178	Display HTML Table from JSON view using Knockout MVC 4 and C#	var json = {"ReportDate":"1/31/2014","ReportList":[{"ReportName":"test report","NumberOfRows":50,"HasData":"Yes","checkBox":false,"ResultMessage":"Message"}]};\n\n\n// create a javascript representation of the c# object, with observables\nvar ViewModel = function(reportDate, reportList) {\n    self = this;\n    self.ReportDate = ko.observable(reportDate);\n    self.Report = ko.observable(reportList);\n}\n\n\n// Apply the bindings to your new object\nko.applyBindings(new ViewModel(json.ReportDate, json.ReportList));	0
15747363	15746714	How to get the zoom event of a C# chart	double oldSelStart = -1;\n    double oldSelEnd = -1;\n    private void chart1_AxisViewChanged(object sender, ViewEventArgs e)\n    {\n        double newSelStart = chart1.ChartAreas["Default"].CursorX.SelectionStart;\n        double newSelEnd = chart1.ChartAreas["Default"].CursorX.SelectionEnd;\n        const double TOLERANCE = 0.1;\n\n        if (Math.Abs(oldSelEnd - newSelEnd) > TOLERANCE || Math.Abs(newSelStart - oldSelStart) > TOLERANCE)\n        {\n            oldSelStart = newSelStart;\n            oldSelEnd = newSelEnd;\n\n            //Zoom has actually changed do your stuff\n        }\n    }	0
6842491	6842324	Converting the date time to display milliseconds in C#	String dateTimeStr = DateTime.Now.ToString("hh.mm.ss.ffffff", "en-US");	0
20570775	20570548	Using a Singleton in XAML - Possible?	{x:Static NotifyIcon:NotificationScheduler.Instance}	0
21211105	21211019	Turn a JSON string into a dynamic object	dynamic dynamicObject1  = JsonConvert.DeserializeObject(json);\nConsole.WriteLine(dynamicObject1.Name);	0
20608282	20608171	Get value of Serialization-attribute	var type = typeof(anEnum);\n  var memInfo = type.GetMember(anEnum.Wohnbauflaeche.ToString());\n  var attributes = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute),\n      false);\n  var value= ((XmlEnumAttribute)attributes[0]).Name;	0
20653447	20653422	Shortening Enum declarations with aliases possible in C# with using directive	namespace A\n    {\n       using  EC = ClassB.EnumC ; // <- this is the correct definition\n\n       public class ClassB\n      {\n      ...	0
19772804	19770936	Save a Dynamics CRM 2011 form inside a Silverlight browser component	webBrowser.InvokeScript("eval", new string[] { "document.getElementById('crmContentPanel').ownerDocument.frames[0].Xrm.Page.data.entity.save()" });	0
3975667	3975636	How to create a delegate method for accessing datagridview control in c#?	autoGridView.Invoke(\n            new Action(\n                delegate()\n                {\n                    int temp2noofrows = autoGridView.Rows.Count - 1;// \n                }\n        )\n        );	0
26282911	26282559	WPF Window - When to load data so form appears instantly	private async void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    var invoices = await Task.Run(() => db.Invoices.AsNoTracking().ToList());\n    listbox1.ItemsSource = invoices;\n}	0
1323493	1319332	Design Pattern Alternative to Coroutines	IEnumerable Thread ()\n{\n    //do some stuff\n    Foo ();\n\n    //co-operatively yield\n    yield null;\n\n    //do some more stuff\n    Bar ();\n\n    //sleep 2 seconds\n    yield new TimeSpan (2000);\n}	0
2593536	2593508	C# DateTime manipulation	var groups = list.GroupBy(dateTime => dateTime.Date);\n\nforeach (var group in groups)\n{\n    Console.WriteLine("{0}:", group.Key);\n    foreach(var dateTime in group)\n    {\n        Console.WriteLine("  {0}", dateTime.TimeOfDay);\n    }\n}	0
489822	489791	How do you use a custom mouse Cursor in a .NET application?	form.Cursor = new Cursor(path);	0
30241654	30241254	DataTable is empty from calling stored procedure	using (var dataAdapter = new SqlDataAdapter(command))\n{\n    var parameter = new SqlParameter();\n    parameter.ParameterName = "@NumberList";\n    parameter.SqlDbType = SqlDbType.Structured;\n    parameter.Value = numberList;\n\n    //ADD THIS\n    command.Parameters.Add(parameter);\n\n    dataAdapter.Fill(dataTable);\n}	0
30950334	30839293	Disable Clock App in Windows 6.5	REGEDIT4\n\n;Enable blacklist of applications that should not run\n[HKEY_LOCAL_MACHINE\Security\Policies\Shell]\n"DisallowRun"=dword:1\n\n;Add entries to blacklist of applications that should not run\n[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun]\n"1"="fexplore.exe"\n"2"="iexplore.exe"\n"3"="clock.exe"	0
29172134	29172073	Is it possible to go to next and previous rows using Grid View?	int CurrentIndex = GridView1.SelectedIndex;\nif (CurrentIndex != GridView1.Rows.Count - 1){\n  int NextRowIndex = GridView1.Rows[GridView1.SelectedIndex + 1].RowIndex;\n  GridView1.SelectedIndex = NextRowIndex;\n  //get info\n}	0
13648325	13648104	Adding string in front and at end of a list	string s = string.Join(",", names.Select(s => string.Format("'{0}'", s)).ToArray());	0
13984647	13984547	How i will manage Data in Grid View coming from Service through WCF	[DataContract]\npublic class Customer\n{\n    [DataMember]\n    public int CustomerID{ get; set; }    }\n\n    [DataMember]\n    public string CustomerName{ get; set; }    \n}\n\n\npublic interface ICustomerService\n{\n\n   [OperationContract]\n   List<Customer> GetAllCustomer();\n}\n\n\npublic class CustomerService:ICustomerService\n{\n\n   List<Customer> GetAllCustomer()\n   {\n       List<Customer> customers = new List<Customer>();\n\n       using(SqlConnection con = new SqlConnection("Database Connection String"))\n       {\n        con.Open();     \n        using(SqlCommand cmd = new SqlCommand("Select * from Customer",con))\n        {\n            SqlDataReader dr = cmd.ExecuteReader();\n\n            while(dr.Read())\n            {\n                Customer customer = new Customer();\n                customer.CustomerID =Parse.Int(dr[0].ToString());\n                customer.CustomerName =dr[1].ToString(); \n                customers.Add(customer);\n            }\n        }\n       }\n    return customers;\n  }\n}	0
18842883	18824013	C# WinRT <-> C# WPF connection with TCP	public async void read()\n{\n  using(var dr=new DataReader(_client.InputStream))\n  {\n    dr.InputStreamOptions=InputStreamOptions.Partial;\n    while(true)\n    {\n      await dr.LoadAsync(1024); //I was missing this line, this is the actual read from the stresm\n      byte[] data=new byte[dr.UnconsumedBufferLength];\n      dr.ReadBytes(data); //This just interprets the byte read before\n      if(data.Length>0)\n        CommandReceived.Fire(IComman.FromData(data)); \n      await Task.Delay(15);\n    }\n  }\n}	0
28997277	28997098	how to check a word againest multiple text boxes	string holdWord = textBox1.Text; //BEEP\nchar charToCheck = Convert.ToChar(label1.Text); // 'E'\n\nbool result = holdWord.Contains(charToCheck); //TRUE	0
8074803	5820163	DataAnnotations with GridView	[ScaffoldColumn(false)]	0
32104868	32104695	DateTime of packet from Seconds and Microseconds	var dateTime = new DateTime(1970, 1, 1).AddSeconds(packet.Seconds).AddSeconds(packet.Microseconds / 1000000.0);	0
8523824	8523309	How to convert an array of value struct to bytes?	private static byte[] StructureToByteArray(Position[] posArray)\n{\n    if (posArray == null || posArray.Length == 0)\n    {\n        return new byte[0];\n    }\n\n    var lenOfObject = Marshal.SizeOf(typeof(Position));\n    var len = lenOfObject * posArray.Length;\n    var arr = new byte[len];\n\n    var handle = GCHandle.Alloc(posArray, GCHandleType.Pinned);\n    try\n    {\n        var ptr = handle.AddrOfPinnedObject();\n        Marshal.Copy(ptr, arr, 0, len);\n    }\n    finally\n    {\n        handle.Free();\n    }\n\n    return arr;\n}	0
9171822	9170993	Converting URI -> object -> imagesource	img = new Image();\nimg.Height = 150;\nimg.Width = 200;\nimg.Stretch = Stretch.Fill;\nimg.Source = new BitmapImage(new Uri("/FirstDemo;component/Images/Hero.jpg"));	0
2219331	2055943	How to find bad endpoints earlier?	public bool IsAlive(string hostnameOrAddress)\n    {\n        bool alive = false;\n        try\n        {\n            Uri address = new Uri(hostnameOrAddress);\n            HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(address);\n            request.Timeout = 5000;\n            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())\n            {\n                alive = DoesResponseStatusCodeIndicateOnlineStatus(response);\n            }\n        }\n        catch (WebException wex)\n        {\n            alive = DoesWebExceptionStatusIndicateOnlineStatus(wex);\n        }\n\n        return alive;\n    }	0
11529913	11529219	Disposal of TreeNodes	treeView1.Nodes.Remove(...)	0
897807	897753	Is it possible to accept a List<Guid> as a paramater from checkboxes in Asp.Net MVC?	public ActionResult Foo(IList<string> guidStrings) \n{\n   var guids = new List<Guid>();\n   foreach(var s in guidStrings)\n   {\n   guid.Add(new Guid(s));\n   }\n\n   return View(guidStrings);\n}	0
13068025	13067629	Socket communication take a long long time	TcpClient clientSocket = default(TcpClient);\n            serverSocket.Start();\n\n            while(True)\n{clientSocket = serverSocket.AcceptTcpClient()\n            requestCount = 0;\n            while ((clientSocket.Connected == true))\n            {\n                try\n                {\n                    requestCount = requestCount + 1;\n                    NetworkStream networkStream = clientSocket.GetStream();\n                    string serverResponse = Request.QueryString["id"] + ";" + Credenciada.ToString() + ".";\n                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);                          \n                    networkStream.Write(sendBytes, 0, sendBytes.Length);\n                    networkStream.Flush();                    \n                }\n                catch (Exception ex)\n                {                    \n                }\n            }\n}	0
23921027	23920906	Keep console window of a new Process open after it finishes	Process p = new Process();\nProcessStartInfo psi = new ProcessStartInfo();\npsi.FileName = "CMD.EXE";\npsi.Arguments = "/K yourmainprocess.exe";\np.Start(psi);\np.WaitForExit();	0
6564799	6564349	How create DataGridViewComboBoxColumn from simple DataTable	DataGridViewComboBoxColumn oCol = new DataGridViewComboBoxColumn();\noCol.Name = "cities";\noCol.DataSource = //your DataSource\nmyDataGridView.Columns.Add(oCol);	0
27169732	27169615	How to get the public IP address of localhost using asp.net c#?	IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());\nIPAddress ip= host.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();	0
9566278	9566190	At run-time, from a .Net application, how do I set the "description" field displayed in Task Manager?	[assembly: AssemblyTitle("My Title")]	0
18693404	18693258	separating string and Double Values on TextBox	var input = "$:2000.00";\nRegex regex = new Regex(@"-?\d+(\.\d{1,2})?");\nvar match = regex.Match(input);            \nif (match.Success)\n{\n    double d = double.Parse(match.Value);\n}	0
5220261	5220193	Renaming a Cell in Excel using C#	r.Name = "myName"	0
10006560	10006486	How to create xml from a template-c#	public class User\n{\n   public UserId{get;set;}\n\n   ...\n}	0
13273722	13272894	Move multiple items in a list	IList<int> myList = new List<int>(new[] {0, 1, 2, 3, 4, 5});\nIList<int> moveLeftList = new List<int>(new[] {0, 1, 3, 4});\n\n//Go through the original list in order and remove\n// all items from the move left list until you reach\n// the first item that is not going to be moved left.\n//Items removed are already as far left as they can be\n// so they do not need to be moved left and can therefore\n// be safely removed from the list to be moved.\nforeach (int item in myList)\n{\n    int index = moveLeftList.IndexOf(item);\n\n    if (index >= 0)\n        moveLeftList.RemoveAt(index);\n    else\n        break;\n}\n\nforeach (int item in moveLeftList)\n{\n    int index = myList.IndexOf(item);\n\n    //Dont move left if it is the first item in the list or it is not in the list\n    if (index <= 0)\n        continue;\n\n    //Swap with this item with the one to its left\n    myList.RemoveAt(index);\n    myList.Insert(index-1, item);\n}	0
2654390	2641395	Loading Content images from Blend from separate project	new Uri(Environment.CurrentDirectory + "\\Themes\\DefaultTheme\\BackgroundImage.png")	0
4119837	4119786	How to create an array in a for loop	Bitmap objBitmap = new Bitmap("im.bmp");\n        double[][] array = new double[objBitmap.Height][];\n        for (int y = 0; y < objBitmap.Height; y++) {\n            array[y] = new double[objBitmap.Width];\n            for (int x = 0; x < objBitmap.Width; x++) {\n                Color col = objBitmap.GetPixel(x, y);\n                if (col == Color.White) array[y][x] = 1.0;\n                else if (col == Color.Black) array[y][x] = 0.0;\n                else array[y][x] = 0.5;  // whatever\n            }\n        }\n        // Do something with array\n        //...	0
11397355	11397128	Table doesn't have a primary key when adding a new row to datatable	using (DataTable dt = new DataTable())\n    {\n        dt.Columns.Add("EntryDE", typeof(string));\n        dt.Columns.Add("Descr", typeof(string));\n        dt.Columns.Add("Id", typeof(int));\n\n        for (int i = 0; i < 10; i++) \n        {\n            DataRow dr = dt.NewRow();\n\n            dr["EntryDE"] = "abc";\n            dr["Descr"] = "xyz";\n            dr["Id"] = 1;\n            dt.Rows.Add(dr);\n        }\n    }	0
3904739	3904573	ASP.NET MVC RSS feed datetime format	DateTime.Now.ToString("r")	0
16150447	16150106	How to get the instance of an object as a string?	class MyClass {\n    private static int _counter = 0;\n    private int _id;\n    public MyClass() {\n        _id = ++_counter;\n    }\n    public override string ToString() {\n        return _id.ToString();\n    }\n}	0
12186125	12150230	Model containing a list of its own model type (Recursive Modeling?)	public class MyClass\n{\n    [Key]\n    public int MyClassId { get; set; }\n\n    public string Data { get; set; }\n\n    public virtual Classes Classes { get; set; }\n}\n\npublic class Classes\n{\n    [Key]\n    public int ClassesId { get; set; }\n\n    [Required]\n    public int MyClassId { get; set; }\n\n    public List<MyClass> Classes { get; set; }\n\n    [Required]\n    public virtual MyClass MyClass { get; set; }\n}	0
20775182	20775072	Serialize objects with inheritance by defining serialize method only in base class?	public NationDwarf(SerializationInfo info, StreamingContext context)\n    : base(info, context)\n{\n}	0
16662237	16661910	How to Restrict canvas size in wpf when Zoomed	private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)\n    {\n        double maxScale = 2.0;\n\n        if (e.Delta > 0)\n        {\n            st.ScaleX *= ScaleRate;\n            st.ScaleY *= ScaleRate;\n        }\n        else\n        {\n            st.ScaleX /= ScaleRate;\n            st.ScaleY /= ScaleRate;\n        }\n\n        if(st.ScaleX > maxScale)\n        {\n            st.ScaleX = maxScale;\n        }\n\n        if(st.ScaleY > maxScale)\n        {\n            st.ScaleY = maxScale;\n        }\n\n    }	0
8221268	8221244	creating a play / pause toggle switch	private void btnPlay_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)\n{\n     if(isPlaying)\n     {\n         music.pause();\n         isPlaying = FALSE;\n         return;\n     }\n\n     music.play();\n     isPlaying = TRUE;\n     return;\n}	0
1668444	1668399	Mousehover, tooltip showing multiple times	public ToolTip tT { get; set; }\n\npublic ClassConstructor()\n{\n    tT = new ToolTip();\n}\n\nprivate void MyControl_MouseHover(object sender, EventArgs e)\n{\n    tT.Show("Why So Many Times?", this);\n}	0
29054887	29054797	how to generate random characters in various text boxes	Random rnd = new Random();\nvar chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nvar sevenRandomChars = chars.OrderBy(_ => rnd.Next()).Take(7).ToList();	0
5771994	5771984	Row is repeated while inserting data	if (date.DayOfWeek != DayOfWeek.Sunday)\n{\n    cmd.Parameters["@Date"].Value = date.ToString("d");\n\n    sqlConn.Open();\n    cmd.ExecuteNonQuery();\n    sqlConn.Close();\n }\n date = date.NextDay();	0
25436394	25436326	Remove padding when number of zeros can change	s = Convert.ToInt32(s.Replace("PSS1", string.Empty)).ToString()	0
5191358	5191316	Adding an instance to a MEF container	var container = new CompositionContainer();\ncontainer.ComposeExportedValue<Application>("Application", Application.Current);	0
1012598	626446	return an SPListItemCollection with one random item	private SPListItemCollection GetRandomItem(SPList list)\n{\n    Random random = new Random();\n    int index = random.Next(0, list.ItemCount - 1);\n    SPQuery query = new SPQuery();\n    query.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\" /><Value Type=\"Integer\">{0}</Value></Eq></Where>", index);\n    return list.GetItems(query);\n}	0
3353952	3353860	byte[] to gray scale BitmapImage	const int bytesPerPixel = 4;\nint stride = bytesPerPixel * pixelsPerLine;\nUInt32[] pixelBytes = new uint[lineCount * pixelsPerLine];\n\nfor (int y = 0; y < lineCount; y++)\n{\n    int destinationLineStart = y * pixelsPerLine;\n    int sourceLineStart = y * pixelsPerLine;\n    for (int x = 0; x < pixelsPerLine; x++)\n    {\n        pixelBytes[x] = _rgbPixels[x].Pbgr32;\n    }\n}\nvar bmp = BitmapSource.Create(pixelsPerLine, lineCount, 96, 96, PixelFormats.Pbgra32, null, pixelBytes, stride);\nbmp.Freeze();\nreturn bmp;	0
333062	333056	Regarding Passing Many Parameters	public struct user \n{ \n    public string FirstName; \n    public string LastName; \n    public string zilionotherproperties; \n    public bool SearchByLastNameOnly; \n} \npublic user[] GetUserData(user usr) \n{ \n    //search for users using passed data and return an array of users. \n}	0
3831829	3831781	Output text with hyperlinks	using System.Text.RegularExpressions; \n\npublic string ConvertURLsToHyperlinks(string sInput) \n{ \n    return Regex.Replace(sInput, @"(\bhttp://[^ ]+\b)", @"<a href=""$0"">$0</a>"); \n}	0
19298736	19298656	c# how to while loop textboxes so it changes textbox every loop?	TextBox[] textBoxes = new TextBox[] { textBox1, textBox2, ... };\nwhile(x ...)\n{\n    something[x] = textBoxes[x].Text;\n}	0
16017630	16017569	Sending an ArrayList from a Server to a Client Application	context.Response.Write(new new JavaScriptSerializer().Serialize(text));	0
16738119	16737329	Recognize a Matrix in a group of points	for each pair of points (p1, p2):\n    let d be the distance vector (x and y) between them\n    if d.x > (image.width-p1.x)/3 or d.y > (image.height-p1.y)/3:\n        continue\n    let d_t be d turned 90 degrees (d.y, -d.x)\n    for i from 0 to 3:\n        for j from 0 to 3:\n            if there is no point at p1 + i*d + j*d_t:\n                continue outer loop\n    if you get here, you have a 4*4 grid	0
21811752	17751597	Error converting urlencode from PHP to C#	UTF8Encoding utf8 = new UTF8Encoding();<br>\nstring utf8Encoded = HttpUtility.UrlEncode(YOURURL, utf8)	0
22631175	22631074	Divide an integer by 100 and get value till two decimal points?	string txtText = "78907";\n\ndouble inputValue;\n\nif (double.TryParse(txtText, out inputValue))\n   double result = Math.Round(inputValue / 100, 2);	0
16003042	16002667	Datagridview insert data not show	public void refresh()\n      {\n           //Paste ur Query here and call it behind the button_click Event\n      }	0
22581553	22581391	Angle of View of a lens - C#	double d = 36D;\ndouble f = 50D;\n\ndouble fov = (d/ (2*f);\ndouble a = 2 * Math.Atan(fov) * 180.0 / Math.PI; // <- 39.598...	0
15133683	15133552	How to have a text in textboxes that at an click disappear?	// Holds a value determining if this is the first time the box has been clicked\n// So that the text value is not always wiped out.\nbool hasBeenClicked = false;\n\nprivate void TextBox_Focus(object sender, RoutedEventArgs e)\n{\n    if (!hasBeenClicked)\n    {\n        TextBox box = sender as TextBox;\n        box.Text = String.Empty;\n        hasBeenClicked = true;\n    }\n}	0
31177351	31168291	Download upload file from specific folder	Response.Clear();\nResponse.ContentType = "application/pdf";\nResponse.AddHeader("Content-Disposition", "attachment;filename=" + fileName + "");\nResponse.TransmitFile(filePath);\nResponse.End();	0
8583488	8583438	Cleaner property declaration	ptprop{TAB}bool{TAB}MyBoolean{Tab}_model{Enter}	0
2230896	2221545	WCF - Stream parameter is missing CR of CRLF	[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, \n        UriTemplate = UriTemplates.SomeWcfContract), OperationContract]\n    void SomeWcfContract(Stream vcard);	0
1213792	1211109	How to hide a property of custom collection while using DataGridView DataSource?	dgvDisplaySet.DataSource = _setSource\ngridColsToHide = _displaySet.hidePKFields\nFor gridCol = 0 To dgvDisplaySet.Columns.Count - 1\ndgvDisplaySet.Columns(gridCol).Visible = (gridCol >= gridColsToHide)\nNext	0
28948897	28944472	how to launch a second application in a second screen in WPF?	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        this.MaximizeToSecondaryMonitor();\n    }\n\n    public void MaximizeToSecondaryMonitor()\n    {\n        var secondaryScreen = Screen.AllScreens.Where(s => !s.Primary).FirstOrDefault();\n\n        if (secondaryScreen != null)\n        {\n            var workingArea = secondaryScreen.WorkingArea;\n            this.Left = workingArea.Left;\n            this.Top = workingArea.Top;\n            this.Width = workingArea.Width;\n            this.Height = workingArea.Height;\n\n            if (this.IsLoaded)\n            {\n                this.WindowState = WindowState.Maximized;\n            }\n        }\n    }\n}	0
7101	6890	How to wait for thread complete before continuing?	// Start all of the threads.\nList<Thread> startedThreads = new List<Thread>();\nforeach (...) {\n  Thread thread = new Thread(new ThreadStart(MyMethod));\n  thread.Start();\n  startedThreads.Add(thread);\n}\n\n// Wait for all of the threads to finish.\nforeach (Thread thread in startedThreads) {\n  thread.Join();\n}	0
34246038	34245636	Using lambdas LINQ query in C#	foreach(var datapersymbol in ctx\n  .HistoricalPriceData\n  .Where(h=>symblist.Contains(h.SymbolId))\n  .OrderByDescending(h=>h.Date)\n  .Select(h=>new {h.Date,h.LastPrice,h.Symbol.Symbol1}))	0
2433737	2433457	c# ProcessCmdKey overload, match generic combination	if ((keyData & Keys.Alt) != 0 && (keyData & Keys.KeyCode) >= Keys.A && (keyData & Keys.KeyCode) <= Keys.Z)	0
4341507	4341488	How can I prompt a user to choose a location to save a file?	private void button1_Click(object sender, System.EventArgs e)\n{\n     Stream myStream ;\n     SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n\n     saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;\n     saveFileDialog1.FilterIndex = 2 ;\n     saveFileDialog1.RestoreDirectory = true ;\n\n     if(saveFileDialog1.ShowDialog() == DialogResult.OK)\n     {\n         if((myStream = saveFileDialog1.OpenFile()) != null)\n         {\n             // Code to write the stream goes here.\n             myStream.Close();\n         }\n     }\n}	0
16213194	16212842	How to return Json as part of my view in C# MVC	public ActionResult MyResults(DataTablePrameters param = null) {\n  if(param == null)\n    return PartialView();\n\n  // Repository action...\n\n  return Json([...]);\n}	0
21964767	21964558	Starting a new C# project, need some guidelines	IsLegal(piece one, coord dest)\nCapturePossible(piece one, piece two) //inherits IsLegal?	0
16008639	16002929	Use Attribute for Enum description	public enum MyColors{\n[Description("Editor Color")]\nWhite,\n[Description("Errors Color")]\nRed,\n[Description("Comments Color")]\nGreen\n}\n\n\nvar type = typeof(MyColors);\nvar memInfo = type.GetMember(MyColors.White.ToString());\nvar attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),\nfalse);\nvar description = ((DescriptionAttribute)attributes[0]).Description;	0
34528661	34528593	Get text from textbox that inside asp:FormView	(Textbox)MainFormTemplate.FindControl("txt_In");	0
7082003	7081910	Wrapping multiple Lists in IDictionary	ObjectBatch[key] <-- get from A or B or C?\nAdd(IobjectModel) <-- will add to which list?	0
1911398	1911364	Ratios with Datatable	private Dictionary<String, Int32> GetCounts(DataTable dt)\n{\n    var result = new Dictionary<String, Int32>();\n\n    foreach (DataRow row in dt.Rows)\n    {\n    foreach (var v in row.ItemArray)\n    {\n    string key = (v ?? string.Empty).ToString();\n\n    if (!result.ContainsKey(key))\n    {\n    result.Add(key, 0);\n    }\n\n    result[key]++;\n    }\n    }\n\n    return result;\n}	0
4522791	4522696	Circular Inheritance for validation	Validator<T>	0
23791981	23777500	Accessing data from EF .sdf file and no edmx designer contents	class Service\n{\n    private ObservableCollection<Student> studentsList;\n\n    public StudentEntities StudentEntities { get; set; }\n\n    public ObservableCollection<Student> Students\n    {\n        get\n        {\n            if (studentsList == null && StudentEntities != null)\n            {\n                StudentEntities.Set<Student>().Load();\n                studentsList = StudentEntities.Set<Student>().Local;\n            }\n\n            return studentsList;\n        }\n    }\n\n    public static IEnumerable<Student> GetAllStudents()\n    {\n        // Code here\n    }   \n}	0
15569197	15567682	Cannot clear items for ASP:Repeater	if (!IsPostBack)\n    // Bind the repeater	0
2134774	2134700	C# skipping first line of a text file	using (StreamReader rdr = new StreamReader(fs))\n{\n  rdr.ReadLine();\n  ...	0
574341	574299	Resizing a panel in c# - WinForms	if (_resizing)\n  {\n    this.Height = top + e.Y;\n    this.Width = width + e.X;\n  }	0
11360829	11359020	Regex multiple occurences of text between tags	Regex regex = new Regex(@"(&lt;.*?internal.*?&gt;(.*?)&lt;.*?/.*?internal.*?&gt;)", RegexOptions.Singleline);	0
12856703	12856328	Loading data from SQL database into a list in C#	using (var db = new MyDbContext())\n{\n    var specialDates = db.SpecialDatesTable.ToList();\n}	0
5536901	5536865	how to get the web service response into grid view in C#	protected void Page_Load(object sender, EventArgs e)\n{\n    using (var proxy = new WebServiceClientProxy())\n    {\n        SomeModel[] data = proxy.GetData();\n        gridView1.DataSource = data;\n        gridView1.DataBind();\n    }\n}	0
9710304	9691000	Get Mouse click event from Microsoft Chart Control click on data marker	protected void Page_Load(object sender, EventArgs e)\n{\n    foreach (DataPoint dp in this.Chart1.Series["YourSeriesName"].Points)\n    {\n        dp.PostBackValue = "#VALX,#VALY";\n    }\n}\nprotected void Chart1_Click(object sender, ImageMapEventArgs e)\n{\n    string[] pointData = e.PostBackValue.Split(';');    \n}	0
23475497	23452026	XElement node with text node has its formatting ignored	XDocument DocumentRoot = XDocument.Parse(inputValue,LoadOptions.PreserveWhitespace);	0
7425877	7390818	Ignored Paper Size in PrintDialog/XPS Document Writer	private void PrintMe()\n{\n    var dlg = new PrintDialog();\n    FixedPage fp = new FixedPage();\n    fp.Height = 100;\n    fp.Width = 100;\n    fp.Children.Add(new System.Windows.Shapes.Rectangle\n        {\n            Width = 100,\n            Height = 100,\n            Fill = System.Windows.Media.Brushes.Red\n        });\n    PageContent pc = new PageContent();\n    pc.Child = fp;\n    FixedDocument fd = new FixedDocument();\n    fd.Pages.Add(pc);\n    DocumentReference dr = new DocumentReference();\n    dr.SetDocument(fd);\n    FixedDocumentSequence fds = new FixedDocumentSequence();\n    fds.References.Add(dr);            \n\n    if (dlg.ShowDialog() == true)\n    {\n        dlg.PrintDocument(fds.DocumentPaginator, "test");\n    }\n}	0
14044264	14044234	having trouble with modifying a thread	// Invoke version of your code sample:\n\nprivate void live_refresh()\n{\n  if(viewBackup.InvokeRequired)\n  {\n    viewBackup.Invoke(new MethodInvoker(live_refresh));\n    return ;\n  }\n  while(true)\n  ....\n  .....\n}	0
9196981	9196743	Copy only one color of an image to another image	Bitmap mySource = new Bitmap("your_image.jpg");\n\nfor(int w=0; w<mySource.Width; ++w)\n   for(int h=0; h<mySource.Height; ++h)\n   {\n      Color pixelColor = mySource .GetPixel(w, h);\n      if ( pixelColor != Color.Black )\n           mySource .SetPixel(w, h, Color.White);\n   }	0
19673569	19618609	How to convert from PhotoResult or BitmapImage to Bitmap?	var session = await EditingSessionFactory.CreateEditingSessionAsync(photoResult.ChosenPhoto);	0
584092	583463	Join multiple DataRows into a single DataRow	var aggregatedAddresses = from DataRow row in dt.Rows\ngroup row by row["AddressA"] into g\nselect new {\n    Address = g.Key,\n    Byte = g.Sum(row => (uint)row["Bytes"])\n};\n\nint i = 1;\nforeach(var row in aggregatedAddresses)\n{\n    result.Rows.Add(i++, row.Address, row.Byte);\n}	0
18385757	18385321	How to make a countdown timer that only begins in certain programs	System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("ProcessName");//Add visuals procname here\n            if (proc.Length > 0)\n            {\n                MessageBox.Show("Process running");\n                if (timer1.Enabled == false)\n                {\n                    timer1.Start();//Starts the countdown}\n                    System.Threading.Thread.Sleep(1000);\n                }\n                else\n                {\n                    MessageBox.Show("Process not running");\n                    if (timer1.Enabled == true)\n                    {\n                        timer1.Stop();//Stops the countdown}\n                        System.Threading.Thread.Sleep(1000);\n                    }	0
11908573	10655116	How to convert Persian Calendar date string to DateTime?	PersianCalendar p = new PersianCalendar();\n        string PersianDate1 = textBox1.Text;\n        string[] parts = PersianDate1.Split('/', '-');\n        DateTime dta1 = p.ToDateTime(Convert.ToInt32(parts[0]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[2]), 0, 0, 0, 0);\n        string PersianDate2 = textBox2.Text;\n        string[] parts2 = PersianDate2.Split('/', '-');\n        DateTime dta2 = p.ToDateTime(Convert.ToInt32(parts2[0]), Convert.ToInt32(parts2[1]), Convert.ToInt32(parts2[2]), 0, 0, 0, 0);\n        string s = (dta2 - dta1).ToString().Replace(".00:00:00", "");\n        textBox3.Text = s; // Show the result into the textbox	0
11666079	11666028	How to set DateTime format in IValueConverter and return string value?	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n     var item = (DateTime)value;\n     if (item != null)\n     {\n         return item.ToString("MMMyyyy");\n     }\n     return null;\n}	0
2829304	2829241	Need help managing MySql connections	internal void CloseFully()\n{\n    if (this.settings.Pooling && this.driver.IsOpen)\n    {\n        if ((this.driver.ServerStatus & ServerStatusFlags.InTransaction) != 0)\n        {\n            new MySqlTransaction(this, IsolationLevel.Unspecified).Rollback();\n        }\n        MySqlPoolManager.ReleaseConnection(this.driver);\n    }\n    else\n    {\n        this.driver.Close();\n    }\n    this.driver = null;\n}	0
21368151	21328334	How to get large thumbnails in hosted Explorer browser control?	IFolderView2::SetViewModeAndIconSize	0
12473023	12472995	Linq compare nullable string to string	var items = from n in db.Roles\n            where n.importID.HasValue && n.importId.Value == importID\n            select n;	0
23430053	23429831	Get Album info in Windows Phone 8.1	var props = await myStorageFileOrFolder.Properties.GetMusicPropertiesAsync();	0
34239781	34234099	How can I make a textBox value equal to a datagrivew cell value	foreach (TextBox control in Controls) //all textboxes but textbox6, because you dont want to compare it with itself\n            {\n                if (control.Text.Equals(textBox6.Text) && textBox6 != control)\n                {\n                    label1.Text = control.Text;\n                }\n            }	0
8158234	8158136	Client IP address from webbrowser object	var host = Dns.GetHostName();\nvar ipAddresses = Dns.GetHostAddresses(host);	0
8863075	8862888	Get result of executed method in Command Pattern	public interface ICommandWithResult<T> : ICommand\n{\n  T Result { get; }\n}\n\npublic class CalculateSalaryCommand : ICommandWithResultOf<int>\n{\n  public int Result { get; private set; }\n\n  // ...\n\n  public void Execute()\n  {\n    _salaryTs.CalculateSalary(_hour, _salaryPerHour);\n    this.Result = _salaryTs.Result;\n  }\n}\n\n// Usage:\n\nvar command = new CalculateSalaryCommand(new CalculateSalaryTS(), 10, 20);\ncommand.Execute();\nConsole.WriteLine("Salary is {0}", command.Result);	0
10358296	10358244	Merge 2 DateTime vars into one in C#	var output = new DateTime(date.Year, date.Month, date.Day,\n                          time.Hour, time.Minute, time.Second);	0
28503521	28503437	Most efficient way of coverting a DataTable to CSV	public static string DataTableToCSV(this DataTable datatable, char seperator)\n{\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < datatable.Columns.Count; i++)\n    {\n        sb.Append(datatable.Columns[i]);\n        if (i < datatable.Columns.Count - 1)\n            sb.Append(seperator);\n    }\n    sb.AppendLine();\n    foreach (DataRow dr in datatable.Rows)\n    {\n        for (int i = 0; i < datatable.Columns.Count; i++)\n        {\n            sb.Append(dr[i].ToString());\n\n            if (i < datatable.Columns.Count - 1)\n                sb.Append(seperator);\n        }\n        sb.AppendLine();\n    }\n    return sb.ToString();\n}	0
22292946	22164735	Set "Regarding" on New Phone Activity In Microsoft Dynamics CRM	var extraqs = string.Format("phonenumber={0}&subject={1}{2}", tel1, "Calling from ", customerName);\nextraqs += "&pType=1";\nextraqs += "&pId={" + guid + "}";\nextraqs += "&pName=";\n\nextraqs += "&partytype=1";\nextraqs += "&partyid={" + guid + "}";\nextraqs += "&partyname=";\n\n_url = string.Format("{0}/Activities/phone/edit.aspx?{1}", crmAddress, Uri.EscapeUriString(extraqs));	0
10745808	10745740	How to get a nullable Type object from a Type object	public static Type GetNullableType(Type t)\n{\n    if (t.IsValueType && (Nullable.GetUnderlyingType(t) == null)) \n        return typeof(Nullable<>).MakeGenericType(t); \n    else\n        return t;\n}	0
1209464	1209005	Are there any good tutorials that describe how to use ANTLR to parse boolean search strings	list of tokens = split input expression into tokens separated by spaces\nforeach token in tokens\n    if token is not keyword\n        text = "CONTAINS(Description, \"" + token + "\")"\n    else \n        text = token\n\n    output = output + text\nend	0
20521411	20520647	How to load a referenced assembly within another referenced assembly?	AppDomain.CurrentDomain.BaseDirectory	0
11845820	11845372	Send video frame via socket	while (true)\n{\n     Socket clientSocket;\n     clientSocket = sListen.Accept();\n\n     var converter = new System.Drawing.ImageConverter();\n     while(true) // find a better way to determine that the picture is still updating?\n    {\n        byte[] buffer = (byte[])converter.ConvertTo(_CurrentBitmap, typeof(byte[]));\n        clientSocket.Send(buffer, buffer.Length, SocketFlags.None);\n    }\n}	0
20211724	20209159	Make comment code can be written in multiple lines	MatchCollection commentMatches = Regex.Matches(regxTextBox.Text, comments,RegexOptions.Singleline);	0
19442998	19436466	How to create an optional foreign key to another table, using custom column names, with fluent api?	modelBuilder.Entity<Matter>()\n.HasOptional(m => m.ProjectManager)\n.WithMany(u => u.Matters)\n.HasForeinKey(k=>k.project_manager);	0
31551201	31550798	How many Januarys in a date range	int currentMonth = 5;\nint monthsBack = 20;\n\nint numberOfJans = (int) Math.Floor((monthsBack - currentMonth) / 12.0) + 1;	0
24495709	24493542	Date format in strong typed ListView's EditItemTemplate	Bind("FechaArribo","{0:d}")	0
11971677	11955096	Getting the name of a excel file	Microsoft.Office.Interop.Excel.Application myExcel;\nthis.Activate ( );\nmyExcel = ( Microsoft.Office.Interop.Excel.Application ) System.Runtime.InteropServices.Marshal.GetActiveObject ( "Excel.Application" )\nMessageBox.Show ( myExcel.ActiveWorkbook.FullName ); // gives full path\nMessageBox.Show ( myExcel.ActiveWorkbook.Name ); // gives file name	0
969572	969396	display fieldname and value of sharepoint list	using (SPSite site = new SPSite("<site_url_where_list_is>"))\n{\n    using (SPWeb web = site.OpenWeb())\n    {\n        SPList list = web.Lists["<list_name>"];\n        foreach (SPListItem listItem in list.Items)\n        {\n            foreach (SPField field in list.Fields)\n            {\n                object value = listItem[field.Id];\n                System.Diagnostics.Debug.WriteLine(field.Title + ": " + (value == null ? "(null)" : value.ToString()));\n            }\n        }\n    }\n}	0
3308310	3305868	How can I discover my end user's users' system performance settings?	int renderingTier = (RenderCapability.Tier >> 16);\nif (renderingTier == 0)\n{\n    Trace.WriteLine("No graphics hardware acceleration available");\n}\nelse if (renderingTier == 1)\n{\n    Trace.WriteLine("Partial graphics hardware acceleration available");\n}\nelse if (renderingTier == 2)\n{\n    Trace.WriteLine("Gotcha!!!");\n}	0
5964574	5964545	How to fill combobox with text file item!	string[] lineOfContents = File.ReadAllLines("Myfile.txt");\nforeach (var line in lineOfContents)\n{\n   string[] tokens = line.Split(',');\n   comboBox1.Items.Add(tokens[0]);\n}	0
33341635	33340653	How to run Power shell as Administrator	var processStartInfo = new ProcessStartInfo("powershell")\n            {\n                UseShellExecute = true,\n                CreateNoWindow = true,\n                Verb = "runas",\n                //UserName = username,\n                //Password = MakeSecureString(password)\n            };\n            var exec = Process.Start(processStartInfo);\n            exec?.WaitForExit(0);	0
19633833	19633709	Write File and Save it as a .htm	if(System.IO.File.Exists("d:\Demo.txt"))    \n    System.IO.File.Copy("d:\Demo.txt", "d:\Demo.htm", true);	0
13993404	13993371	how to pass list as parameter in function	void Yourfunction(List<DateTime> dates )\n{\n\n}	0
3674801	3674726	Duplicated strings in a 3TB TXT file	sort bigfile.txt | uniq -d	0
9986067	9985976	C# Regex for changing occurrences of [ into [[] and ] into []]	Regex.Replace(tempLogElement, "\[([\w\s]*)\]", "[[]$1[]]", RegexOptions.IgnoreCase);	0
8671143	8670926	Need help building an Entity Framework 4 query	ReadViewModel[] result = ( from read in context.Reads\n                           where SomeCondition\n                           select new ReadViwModel\n                           {\n                               ReadId = read.ReadId,\n                               // . . .\n                               HasAlarms = read.Alarms.Any(),\n                               // . . .\n                           } ).ToArray();	0
17357598	17357560	How to disable particular context Menu Item dynamically	private void conMenu1_Opening(object sender, CancelEventArgs e)\n{\n    conMenu1.Items[0].Enabled= false;\n}	0
1460298	1460273	How to check if a file exits on an webserver by its URL?	// create the request\nHttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\n\n// instruct the server to return headers only\nrequest.Method = "HEAD";\n\n// make the connection\nHttpWebResponse response = request.GetResponse() as HttpWebResponse;\n\n// get the status code\nHttpStatusCode status = response.StatusCode;	0
1986875	1986813	Change Local user settings from within c#	Set objComputer = GetObject _\n("LDAP://CN=atl-dc-01,CN=Computers,DC=Reskit,DC=COM")\nobjComputer.SetPassword "whatever"	0
24635205	24635126	How to re-write this linq from query syntax to method syntax?	recordsEpP.Where(row=> !string.IsNullOrEmpty(row.Column20) &&                 \n                       !string.IsNullOrEmpty(row.Column14) &&\n                        string.IsNullOrEmpty(row.Column8)\n         ).Select(row => new ReportDto{\n            Status = "P",\n            ContractNumber = row.ContractNumber,\n            Count = 1\n         }).ToList();	0
17710623	17710440	Label won't align properly in Windows XP	cpuLabel.Text = CPUID.Trim();	0
3707802	3707702	Converted copied text from textbox in c#	string strData=default(string);\n\n             object obj = Clipboard.GetData(DataFormats.Text);\n\n            if (obj == null)\n            {\n\n                return;\n            }\n            else\n                 strData = obj.ToString();\n\n           strData = strData.Replace(",",".") \n\n\n           Clipboard.SetData("Text", strData);	0
11006463	11005481	How to sync the lines in a text box with the rows of a database?	TRUNCATE TABLE foods	0
11045370	11045184	Parse HTML with HTML Agility Pack	HtmlDocument doc = new HtmlDocument();\n        doc.LoadHtml(//your html document);\n        foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[@class='divTableBodyText']")){\n        foreach (HtmlNode table in div.DocumentNode.SelectNodes("table")) {\n          foreach (HtmlNode tbody in div.DocumentNode.SelectNodes("tbody")) {\n            foreach (HtmlNode row in tbody.SelectNodes("tr")) {\n                foreach (HtmlNode cell in row.SelectNodes("td")) {\n                    Console.WriteLine(cell.InnerText);\n                }\n            }\n        }\n     }\n}	0
14940684	14937707	Getting incorrect decryption value using AesCryptoServiceProvider	string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";\n    string inputValue = "Test";\n    string keyValue = valid128BitString;\n\n\n    byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);\n    EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);\n    EncryptResult encyptedValue = new EncryptResult();\n    encyptedValue.IV = result.IV; //<--Very Important\n    encyptedValue.EncryptedMsg = result.EncryptedMsg;\n\n    string finalResult =Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));	0
7231269	7231170	C#: How to parse a user query	string.Replace()	0
11731346	11731241	MySQL Data Statistics	SELECT\n    Category,\n    IF(Date_SUB(CURDATE(), Interval 16 Hour) <= Datez, SUM(1), 0) AS c16hours,\n    IF(Date_SUB(CURDATE(), Interval 1 day) <= Datez, SUM(1), 0) AS c1day,\n    IF(Date_SUB(CURDATE(), Interval 30 days) <= Datez, SUM(1), 0) AS c30days,\n    (...)\nFROM tickets \nGROUP BY Category	0
5032701	5032667	How to open "Network Connections" window programmatically	ProcessStartInfo startInfo = new ProcessStartInfo("NCPA.cpl");\nstartInfo.UseShellExecute = true;\n\nProcess.Start(startInfo);	0
6523521	6523389	Getting the Text of ToolstripItem in a ContextMenuStrip	string toolstripItemName = e.ClickedItem.Text;	0
5261711	5261653	Self referencing many to many relationships in Fluent NHibernate automapping	public class MemberOverride : IAutoMappingOverride<Member>\n{\n    public void Override(AutoMapping<Member> mapping)\n    {\n        mapping.HasManyToMany(m => m.Friends)\n               .Table("MemberFriendsLinkTable");\n               .ParentKeyColumn("MemberId")\n               .ChildKeyColumn("FriendId");\n    }\n}	0
31832412	31822103	How to calll a stored proc via nHibernate which returns nothing	session.Flush();	0
16273728	16214570	How to improve Linq-To-Sql code	from t in types\nlet docs = context.documents.Where(d => (d.RKey == t.Id.ToString()\n                                     && d.RType == (int)RType.Type\n                                     && d.AType == (int)AType.Doc)\n                                   ||\n                                        (d.RKey == t.No \n                                     && d.RType == (int)RType.Art \n                                     && d.AType == (int)AType.Doc))\nlet tDoc = docs.FirstOrDefault(d => d.RType == (int)RType.Art && d.UseForThumb)\nlet docsCount = docs.Count()\nselect new Time\n{                                               \n  Id = t.Id,\n  //... more simple mappings here\n  DocsCount = docsCount,\n  ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0,\n}	0
8470491	8470455	Exit all functions from code in inner function	public void Function1()\n{\n    if (Function2() == false)\n        return;\n\n    // do other code if Function2 succeeded\n}\n\npublic bool Function2()\n{\n    if (1 == 1)\n    {\n        return false;\n    }\n    else\n    {\n        return true;\n    }\n}	0
31208987	31207924	Merging some List<double[]> within a List<List<double[]>>	var elementsACount = ListA.Count();\nvar groupedElementsIdxs = ListB.SelectMany(e => e);\nvar ungroupedElementsIdxs = Enumerable.Range(0, elementsACount).Except(groupedElementsIdxs);\n\nvar result = new List<List<double[]>>();\n// Merge and add the grouped elements.\nforeach (var el in ListB)\n{\n    result.Add(el.Select(e => ListA[e]).SelectMany(e => e).ToList());\n}\n// Merge and add the ungrouped elements.\nresult.Add(ungroupedElementsIdxs.Select(e => ListA[e]).SelectMany(e => e).ToList());	0
5345995	5342827	Entity-splitting scenario in EF4 CTP5 code-first implementation	var query = from u in context.Users\n            join c in context.Customers on u.CustId equals c.Id\n            select new UserProjection\n              {\n                Id = u.Id,\n                CustId = c.Id,\n                CustomerString = c.CustomerString,\n                FirstName = u.FistName,\n                LastName = u.LastName\n                Email = u.Mail\n              };	0
2927842	2927793	The best way to use dictionary items as we use the advantages of List	IDictionary<Int32, String> dictionary = new Dictionary<Int32, String>();\n\n// Iterate over all key value pairs.\nforeach (KeyValuePair<Int32, String> keyValuePair in dictionary)\n{\n    Int32  key = keyValuePair.Key;\n    String value = keyValuePair.Value;\n}\n\n// Iterate over all keys.\nforeach (Int32 key in dictionary.Keys)\n{\n    // Get the value by key.\n    String value = dictionary[key];\n}\n\n// Iterate over all values.\nforeach (String value in dictionary.Values)\n{\n}	0
7615012	7614997	Use linq to make a projection of an anonymous class with a list	myClass.Select(x=> new { Property1 = x.Property1, \n                         Property2 = x.Property2, \n                         SecondList = x.MyList.Select(i => new { i.SecondProperty4, i.SecondProperty5 }).ToList()\n                       }	0
19768677	19768407	Determine if a method is 'extern' using reflection	var isExtern = (mEnter.MethodImplementationFlags\n                    & MethodImplAttributes.InternalCall) != 0;	0
11740654	11740275	Kinect Manipulate Skeleton Data	var movedPosition = new SkeletonPoint\n{\n    X = (float)(mouseJoint.Position.X - 0.4),\n    Y = (float)(mouseJoint.Position.Y - 0.3)\n};\n\nvar movedJoint = new Joint\n{\n    Position = movedPosition\n};	0
10114606	10114588	WindowsForm control as a parameter	void SayHello(TextBox textBox)\n{\n    textBox.Text = "Hello world";\n}\n\n...\n\nSayHello(textBox1);	0
1434888	1434867	How to use multiple modifier keys in C#	if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))\n{\n    //Do work\n}\nelse if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)\n{\n    //Paste\n}	0
7544638	7544622	running C# web app with schedular in microsoft server	class Program\n{\n    static void Main()\n    {\n        using (var client = new WebClient())\n        {\n            var result = client.DownloadString("http://example.com/test.aspx");\n            File.WriteAllText("foo.txt", result);\n        }\n    }\n}	0
32420205	32418507	access labels created on button click outside event	// When you're creating it.\nitemName.Name = "itemName";\n\n// Finding it.\nvar itemName = (Label)this.Controls["itemName"];\n\n// Another way to find it.\nvar itemName = (Label)this.Controls.Find("itemName", true);	0
5183499	5183444	Format decimal as a percent with specific decimal places	Model.STPData.InitialRateSetting.Value.ToString("P5");	0
9641655	9641587	save contents of a datagridview or similar data table control	DataTable dt = ((DataView)this.dataGridView1.DataSource).Table;\n    dt.WriteXml(@"C:\test\text.xml");	0
5957761	5957736	c# check if a given file path contains a root directory	if(Path.IsPathRooted(path))...	0
26574694	26574601	Creating a parallelograme in c#	int i = 0, current_line = 0;\n\n            do\n            {\n                if (i < side)\n                {\n                    Console.Write("*");\n                    i++;\n                }\n                else\n                {\n                    Console.Write("\n");\n\n                    i = 0;\n                    current_line++;\n                }\n            } while (current_line < side);	0
32380731	31305651	Cant debug Using QueueClient.OnMessage on a console app	Empresa empresa = JsonConvert.DeserializeObject<Empresa>(mensaje);	0
16086434	16083873	How to get the distance between the baseline of text and the horizontal border of a label?	Font myFont = this.Font;\nFontFamily ff = myFont.FontFamily;\n\nfloat lineSpace = ff.GetLineSpacing(myFont.Style);\nfloat ascent = ff.GetCellAscent(myFont.Style);\nfloat baseline = myFont.GetHeight(e.Graphics) * ascent / lineSpace;	0
6494413	6494362	Get and order all elements from list of objects?	List<object> listOfObjects = { 1, "2", new object(), 3, 4, "5" };\nIEnumerable<int> orderedInts = listOfObjects .OfType<int>().OrderBy(i => i);	0
9838066	9838039	Programmatically set selected item in a WPF combobox	cmb.SelectedItem = (DATABASE_TYPES)Enum.Parse(typeof(DATABASE_TYPES), propertyNode.Attributes["default"].Value);	0
26226065	26224876	JSON data is not displaying in JQGrid	colModel: [{ name: 'DelLanguageID', index: 'DELLANGUAGEID', width: 65, editable: false },...	0
20181736	19905050	Sprache: left recursion in grammar	term := everything simple in an expression (like "1", "2", "3", etc.)\nexpression := term [ IN ( expression*) | IS NULL | "+" expression | "-" expression | etc.]	0
28348024	28347714	How to run portion of code in lower execution level	var sec = Directory.GetAccessControl(path);\nvar everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);\nsec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));\nDirectory.SetAccessControl(path, sec);	0
22796541	22790203	How to map a single property to each element's property of a collection using AutoMapper?	Mapper.CreateMap<Parent, ParentMapped>()\n    .AfterMap((m,d) => d.Children.ForEach(c => c.SomeFlag = m.SomeFlag));	0
28966424	28966100	How to wait for a response from a wpf mvvm popup	new MyCustomDialogWindow().ShowDialog();	0
1968125	1968049	How to separate character and number part from string	private void demo()\n        {\n            string cell = "ABCD4321";\n            int row, a = getIndexofNumber(cell);\n            string Numberpart = cell.Substring(a, cell.Length - a);\n            row = Convert.ToInt32(Numberpart);\n            string Stringpart = cell.Substring(0, a);\n        }\n\n        private int getIndexofNumber(string cell)\n        {\n            int indexofNum=-1;\n            foreach (char c in cell)\n            {\n                indexofNum++;\n                if (Char.IsDigit(c))\n                {\n                    return indexofNum;\n                }\n             }\n            return indexofNum;\n        }	0
6615045	6610653	How to determine which server IP address the client connected to	TcpClient.Client.LocalEndPoint	0
6613751	6602244	How to call an async method from a getter or setter?	string _Title;\npublic string Title\n{\n    get\n    {\n        if (_Title == null)\n        {   \n            Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });\n        }\n        return _Title;\n    }\n    set\n    {\n        if (value != _Title)\n        {\n            _Title = value;\n            RaisePropertyChanged("Title");\n        }\n    }\n}	0
34091108	34090998	Add a string to new List<string>(new string[] { });	string csv = "one,two,three";\nstring[] parts = csv.Split(',');\n\n_MyList.Add(new ListObjects()\n{\n     Name = tag.Name,\n     MyObjectList = parts.ToList()\n});	0
16642279	16642196	Get HTML code from a website C#	string urlAddress = "http://google.com";\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\nif (response.StatusCode == HttpStatusCode.OK)\n{\n  Stream receiveStream = response.GetResponseStream();\n  StreamReader readStream = null;\n\n  if (response.CharacterSet == null)\n  {\n     readStream = new StreamReader(receiveStream);\n  }\n  else\n  {\n     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));\n  }\n\n  string data = readStream.ReadToEnd();\n\n  response.Close();\n  readStream.Close();\n}	0
12270652	12268455	FileHelpers Csv reader - Failing to convert dd-mmm-yyyy DateTime Format	[FieldTrim(TrimMode.Both)]\n[FieldQuoted('"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]\n[FieldConverter(ConverterKind.Date, "dd-MMM-yyyy" )] \nprivate DateTime mDate;	0
5803431	5803359	how to use try catch blocks in a value returning method?	public bool CheckFileType(string FileName)\n {\n    bool result = false ;\n\n    try\n     {\n      string Ext = Path.GetExtension(FileName);\n      switch (Ext.ToLower())\n      {\n        case ".gif":                   \n        case ".JPEG":                    \n        case ".jpg":                  \n        case ".png":                   \n        case ".bmp":                   \n            result = true;\n            break;\n       }\n\n      }catch(Exception e)\n      {\n         // Log exception \n      }\n      return result;\n     }	0
9443092	9442899	Manipulating data in a collection with LINQ	String input = "1-1-1-00";\nvar wantedStrings = stringList.Where(str => str.StartsWith(input.Substring(0, 4)) && str[4] != '0');	0
30499605	30499307	Access column name by value in a cell C#	static string GetMyColumnName(DataView objDataView, object YOURVALUE)\n    {\n        int colCount = objDataView.Table.Columns.Count;\n        foreach (DataRowView rowView in objDataView)\n        {\n            for (int i = 0; i < colCount; i++)\n                if (rowView[i] == YOURVALUE) // Check if cell value is the one you are looking for\n                    return objDataView.Table.Columns[i].ColumnName;\n        }\n        throw new Exception("Column not found");\n    }	0
17344641	17344572	calling a public method from a different class private method	private void ClassBMethod()\n{\n    ClassA classA = new ClassA();\n    classA.CloaseLoadHistory();\n}	0
28889375	28889223	how merge list and keep values with linq	var result = dataList.GroupBy(x => x.Id).Select(grouping => new\n{\n     Id = grouping.First().Id,\n     Name = grouping.First().Name,\n     Number = grouping.Sum(x => x.CaseId == 2 ? -x.Number : x.Number)\n});	0
27003826	27003701	Parse This XML to object	var myObject = LoadFromXmlString<DATA_PROVIDERS>(xmlData);\n\npublic static T LoadFromXmlString<T>(string xml)\n{\n  T retval = default(T);\n  try\n  {\n    XmlSerializer s = new XmlSerializer(typeof(T));\n    MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(xml));\n    retval = (T)s.Deserialize(ms);\n    ms.Close(); \n  }\n  catch (Exception ex)\n  {\n    ex.Data.Add("Xml String", xml);\n    throw new Exception("Error loading from XML string.  See data.", ex);\n  }\n  return retval;\n\n}	0
24764681	24763698	Search for text value in sql table and display it in listbox on textbox.textChanged event	ListBox lb = new ListBox();\nstring connectionString = "your connection string here";\nusing (SqlConnection con = new SqlConnection(connectionString))\n{\n    con.Open();\n    string query = "SELECT Name + ' ' + cast(Date as varchar(20))+' '+ cast(Value as varchar(20)) as 'Text' FROM MyTable";\n    using (SqlCommand cmd = new SqlCommand(query, con))\n    {\n        using (SqlDataReader reader = cmd.ExecuteReader())\n        {\n            while (reader.Read()) {\n                lb.Items.Add(new ListItem((string)reader["Text"]));\n            }\n        }\n    }\n}	0
24275996	24099274	MenuItem in Window, CommandBinding in UserControl	CommandBindings.AddRange(_userControl1.CommandBindings);	0
15888285	15887843	How to set control x:Uid attribute programmatically for a metro app control?	public string Uid { get; }	0
7592480	7580819	Problem displaying images obtained in byte format from server	using (AutoResetEvent are = new AutoResetEvent(false))\n {\n  System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>\n   {\n     MemoryStream byteStream = new MemoryStream(resp);\n     byteStream.Write(resp, 0, resp.Length);\n     string[] iconname = entry.Name.Split(new char[] { '-' });\n     string newimagename = iconname[1];\n\n     Uri icon_url = new Uri(newimagename, UriKind.RelativeOrAbsolute);\n     icon = new BitmapImage(icon_url);\n     imag = new Image();\n     imag.Source = icon;\n     sourceofImage = icon.UriSource.ToString();\n     icon.SetSource(byteStream);\n     Console.WriteLine(icon.PixelHeight + ":" + icon.PixelWidth);\n     are.Set();\n     // string[] newname = entry.Name.Split(new char[] { '-', '.' });\n    // iconDict.Add(sourceofImage, icon);\n    });\n    are.WaitOne();\n    string[] newname = entry.Name.Split(new char[] { '-', '.' });\n    string newFileName = newname[1];\n    iconDict.Add(newFileName, icon);\n   }	0
7741262	7741095	How to prevent user to enter a special character in text box?	private void textBox1_TextChanged(object sender, TextChangedEventArgs e)\n    {\n        var currentText = textBox1.Text;\n        var selectionStart = textBox1.SelectionStart;\n        var selectionLength = textBox1.SelectionLength;\n\n        int nextAsterisk;\n        while ((nextAsterisk = currentText.IndexOf('*')) != -1)\n        {\n            if (nextAsterisk < selectionStart)\n            {\n                selectionStart--;\n            }\n            else if (nextAsterisk < selectionStart + selectionLength)\n            {\n                selectionLength--;\n            }\n\n            currentText = currentText.Remove(nextAsterisk, 1);\n        }\n\n        if (textBox1.Text != currentText)\n        {\n            textBox1.Text = currentText;\n            textBox1.SelectionStart = selectionStart;\n            textBox1.SelectionLength = selectionLength;\n        }\n    }	0
11759584	11759426	How can I iterate though each child node in an XML file?	foreach (XmlNode node in dataNodes)\n{\n     foreach (XmlNode childNode in node.ChildNodes)\n     {	0
20956189	20956126	How to get the output of a stored procedure?	myproductidparam = Convert.ToInt32(cm.Parameters["@TheProductID"].Value);	0
1668161	1667949	C# Parsing Excel custom cell format	DateTime.FromOADate	0
8454097	8441991	How to Build PDFBox for .Net	using System;\nusing System.IO;\n\nusing org.apache.pdfbox.pdmodel;\nusing org.apache.pdfbox.util;\n\nnamespace testPDF\n{\nclass Program\n{\n    static void Main()\n    {\n        PDFtoText pdf = new PDFtoText();\n\n        string pdfText = pdf.parsePDF(@"C:\Sample.pdf");\n\n        using (StreamWriter writer = new StreamWriter(@"C:\Sample.txt"))\n        { writer.Write(pdfText); }\n\n    }\n\n    class PDFtoText\n    {\n        public string parsePDF(string filepath)\n        {\n            PDDocument document = PDDocument.load(filepath);\n            PDFTextStripper stripper = new PDFTextStripper();\n            return stripper.getText(document);\n        }\n\n    }\n}\n\n}	0
33548492	33548434	How to bind enabled/disabled status to a control instead of view model?	{Binding ElementName=myControl, Path=myProperty}	0
22857244	22857137	How to find second last element from a List?	if (lsRelation.Count >= 2)\n    secLast = lsRelation[lsRelation.Count - 2];	0
31674031	31673432	How to call parameterised base class constructor from parameterless derived class?	public ItemFoldersForm(FormConstructor constuctorOptions) : base(constuctorOptions.WindowTitle, constuctorOptions.TabName, constuctorOptions.TabButton)\n{\n}\n\npublic ItemFoldersForm() : this(ConstructorOptions.GetRandomConstructorOptions())\n{\n}	0
20432871	20432111	How to store and retrieve 4 sbyte values in a signed int	int i = unchecked (\n (byte)byte0 << 24 | (byte)byte1 << 16 | (byte)byte2 << 8 | (byte)byte3 << 0);	0
21244480	21243740	Only specific properties are serialized in metadata	public class SomeRequest\n{\n    public int Max { get; set; }\n    public Header SomeHeader { get; set; }\n    public int Response { get; set; }\n}	0
27836082	27835988	ASP.NET AJAX: How to get a JSON response obtained using also Session?	//Store value in session\nHttpContext.Current.Session["mysession"]=value;\n\n//Get value from session\nvar sessionvaue=HttpContext.Current.Session["mysession"];	0
4307801	4307636	Sending mail with attachments programatically in ASP.NET	var m = new System.Net.Mail.MailMessage(from, to, subject, body);\nvar a = System.Net.Mail.Attachment.CreateAttachmentFromString(stringWrite.ToString(), "application/vnd.xls");\nm.Attachments.Add(a);	0
28655672	28655211	How to convert 8bit sound to 16bit	Dim buffer((44100 * 2) - 1) As Byte ' place to dump 8-16bit data\n\nFor i As Integer = 0 To data.Count - 1 ' data holds 8bit data\n\n    Dim aaa = Convert.ToInt16(data(i)) << 8 ' shift to most-significant-bits\n    Dim bb() As Byte = BitConverter.GetBytes(aaa)\n\n    buffer(i * 2) = bb(0)\n    buffer(i * 2 + 1) = bb(1)\nNext	0
19984107	19982721	create an array of strings from an RSS feed	XDocument doc = XDocument.Load("http://url_for_feed/feed.rss");\n\nList<string> items = (from x in doc.Descendants("item") \n     select x.Element("title").Value).ToList();	0
8738400	8683923	Replying to a User's wall message using Facebook C# SDK	try  \n{  \n    String statusUpdateID = "12345";  \n    fb.Post(String.Format("/{0}/comments", statusUpdateID), parameters);  \n}  \ncatch (FacebookOAuthException e)  \n{  \n    //this exception is thrown if your comment fails to post  \n}	0
22092050	22091463	How to images show in Wp8 i have a stream Path	private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)\n{\n    UnZipper unzip = new UnZipper(e.Result);\n    foreach (string filename in unzip.GetFileNamesInZip())\n    {\n        Stream stream = unzip.GetFileStream(filename);\n        BitmapImage image = new BitmapImage();\n        image.SetSource(stream);\n        imgCtr.Source = image;    \n    }\n}	0
20560557	20559966	How to set focus to a textedit on buttonclick in C# Winforms?	private void button1_Click(object sender, EventArgs e)\n        {\n            textBox1.Focus();\n        }	0
23821903	23821217	How to replace property value in dynamic JSON	JObject rss = JObject.Parse(json);\nJObject furnitures = rss.SelectToken("result").SelectToken("furnitureItem");\nfurnitures ["images"] = newValue;	0
29300976	29300541	How do you access this property from the OwinStartup file?	AppDbContext context = HttpContext.Current.GetOwinContext().Get<AppDbContext>();\nAppUserManager userManager = HttpContext.Current.GetOwinContext().Get<AppUserManager();	0
17030397	16348028	Can you use MySQL @ session variables in the C# connector?	server=192.168.0.0;password=root;User Id=root;Persist Security Info=True;database=my_db;Allow User Variables=True	0
697419	697398	Using HyperLinkFields to display details	if(!IsPostBack)\n{\n    try\n    {\n        intMyId = (int)Request.QueryString["id"];\n        //Do something with intMyId\n    }\n    catch(InvalidCastException ex)\n    {\n       //Record and show error message\n    }\n}	0
16454532	16454462	String parsing using RegEx	var s = "X:= FMLVAR(\"Function1\", \"Var1\");";\n\nvar match = new Regex(@"FMLVAR\(""(.+?)"", ""(.+?)""\);").Match(s);\n\nvar arg1 = match.Groups[1];\nvar arg2 = match.Groups[2];	0
8405947	8405904	How to get all items to a string [] from listview?	startInfo.Arguments = "--logfile=duration_output.txt " +\n    string.Join(" ", from item in listView1.Items.Cast<ListViewItem>()\n                     select @"""" + item.Text + @""""\n               );	0
1222838	1222778	validate 3 textfields representing date of birth	DateTime D;\nstring CombinedDate=String.Format("{0}-{1}-{2}", YearField.Text, MonthField.Text, DayField.Text);\nif(DateTime.TryParseExact(CombinedDate, "yyyy-M-d", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out D)) {\n  // valid\n} else {\n  // not valid\n}	0
25494209	25488290	Blur effect on windows 8 store apps	wb.Convolute(WriteableBitmapExtensions.KernelGaussianBlur3x3)	0
14025813	14025732	Extracting data from complex JSON structure in C#	var jObj = JsonConvert.DeserializeObject(json) as JObject;\nvar result = jObj["data"].Children()\n                .Cast<JProperty>()\n                .Select(x => new { \n                    Title = (string)x.Value["title"] ,\n                    Author = (string)x.Value["author"],\n                })\n                .ToList();	0
9518797	9518736	Passing data from View to Controller (MVC 3)	[HttpPost,ActionName("Mail")] // this Method allow to send a email\n    public ActionResult MailConfirmed(int id, string messageBody)\n    {\n        Customer customer = db.Customers.Find(id);\n\n        if(messageBody!=null)\n        {\n            System.Diagnostics.Debug.WriteLine(messageBody);\n            SendMail(customer.Mail, customer.Name, messageBody);\n            return RedirectToAction("Index");  \n        }\n        else\n        {\n            ModelState.AddModelError("", "Veuillez rentrer un message SVP"); \n        }\n        return View(customer);\n    }	0
26639351	26639038	Windows Phone Only Saving One Character of String	using (var streamReader = new StreamReader(file, Encoding.Unicode))	0
22629659	22623479	How to measure RFT metric in NDepend?	// <Name>RFT</Name>\nfrom t in Application.Types\nwhere !t.IsInterface && !t.IsEnumeration\nlet methodsUsedDirectly = \n   t.TypesUsed\n    .Where(tUsed => !tUsed.IsThirdParty)\n    .ChildMethods()\n    .Where(m => m.IsUsedBy(t))\n\nlet methodsUsedIndirectly = methodsUsedDirectly\n   .FillIterative(\n         methods => methods.SelectMany(\n                         m => m.MethodsCalled\n                               .Where(mCalled => !mCalled.IsThirdParty))\n   )\n   .DefinitionDomain.ToArray()\n\nlet rftLoC = methodsUsedIndirectly.Sum(m=>m.NbLinesOfCode)\n\nselect new { t, \n   methodsUsedDirectly, \n   methodsUsedIndirectly,\n   rft = methodsUsedIndirectly.Length,\n   rftLoC }	0
31386433	31386322	How to deserialize Jsonstring to c# listObject	string jsonTxt = @"[  \n[  \n    {  \n        ""data"":""Australia"",\n        ""text"":""Australia""\n    }\n],\n[  \n    {  \n        ""data"":""China"",\n        ""text"":""China""\n    }\n],\n[  \n    {  \n        ""data"":""Hong Kong"",\n        ""text"":""Hong Kong""\n    }\n],\n[  \n    {  \n        ""data"":""Indonesia"",\n        ""text"":""Indonesia""\n    }\n],\n[  \n    {  \n        ""data"":""Netherlands"",\n        ""text"":""Netherlands""\n    }\n]\n]";\nvar result = JsonConvert.DeserializeObject<List<RootObject>[]>(jsonTxt);	0
5590213	5590180	How to convert a Datetime string to a current culture datetime string	DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;\nDateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;\nstring result = Convert.ToDateTime("12/01/2011", usDtfi).ToString(ukDtfi.ShortDatePattern);	0
28622299	28622186	C# Looping through textboxes in a GroupBox	private void button1_Click(object sender, EventArgs e)\n{\n    int Counter = 0;\n\n    foreach (Control control in groupBox1.Controls)\n    {\n        TextBox textBox = control as TextBox;\n\n        if (textBox != null)\n            textBox.Text = Counter++.ToString();   \n    }\n}	0
8822450	8652766	Returning Guid of newly created item in Sharepoint Library	var FileSrvRelUrl = "/sub/doclib/Folder/File.doc";\nusing (var fileStream = new MemoryStream(new byte[100]))\n{\n    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, FileSrvRelUrl, fileStream, false);\n}\nvar web = clientContext.Web;\nvar f = web.GetFileByServerRelativeUrl(FileSrvRelUrl);\nvar item = f.ListItemAllFields;\nitem["SomeField"] = "Value";\n\nitem.Update();\nclientContext.Load(item, i=>i.Id);\nclientContext.ExecuteQuery();	0
32173297	32170507	Sending E-mail using C# with multiple images	body = body.Replace("#Title", blogTitle);\n            body = body.Replace("#BlogDate", blogDate.ToString());\n            body = body.Replace("#BlogCategory", blogCategory);\n            body = body.Replace("#BlogHeadline", blogHeadline + ".........");\n\n            mail.Body = body;\n\nAlternateView av1=AlternateView.CreateAlternateViewFromString(body,null,MediaTypeNames.Text.Html);\n            LinkedResource myPhoto=new LinkedResource("D:\\asp.net\\Learning Dot Net\\myPhoto.jpg");\n            myPhoto.ContentId="myImage";\n            av1.LinkedResources.Add(myPhoto);\n            myPhoto=new LinkedResource("D:\\asp.net\\Learning Dot Net\\books.jpg");\n            myPhoto.ContentId="blogImage";\n            av1.LinkedResources.Add(myPhoto);\n            mail.AlternateViews.Add(av1);\n            //code ends\n\n            mail.IsBodyHtml = true;	0
14819100	14806909	Append Xml a given number of times	private xmlelement dothework(string param1, string param2){\n\n    'do all necessary work to set up the element in here and then return it\n\n}	0
18964004	18950845	Send Cookie in Post Response WebAPI	cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;	0
19391364	19389900	How does one use a selected value on a drop down list when some value come back as null?	if (dtMyTable.Rows[0]["OptionalField"] != null)\n            {\n                if (dtMyTable.Rows[0]["OptionalField"].ToString() == "")\n                {\n                    ddlMyDropDownList .SelectedIndex = 0;\n                }\n                else\n                {\n                    ddlMyDropDownList .SelectedValue = dtMyTable.Rows[0]["OptionalField"].ToString();\n                }\n             }	0
26531625	26531568	C#: Calculate Percentage of new items added over a course of time?	double percent = oldCount == 0 ? 100 : ((double)newCount - oldCount) / oldCount * 100;	0
9091930	9080068	Warning message with virtual event	public virtual event EventHandler myEvent = delegate { };	0
12621357	12621133	How to concatenate the values of two Columns into One inside ListView	public string DescName \n  {\n      get \n      {\n           return Description + " " + Name;\n      }\n  {\n\n<GridViewColumn Width="300" Header="Name" DisplayMemberBinding="{Binding DescName}" />	0
23482851	23482337	Getting values from a database using a stored procedure?	using System.Data;\nusing System.Data.SqlClient;\n\n    public static DataSet GetLogin(Int32 userId)\n    {\n       DataSet logStatusDs = new DataSet();\n        //load the List one time to be used thru out the intire application\n        var ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString;\n        using (SqlConnection connStr = new SqlConnection(ConnString))\n        {\n            using (SqlCommand cmd = new SqlCommand("get_LoginStatusQ", connStr))\n            {\n                cmd.CommandType = CommandType.StoredProcedure;\n                cmd.Parameters.AddWithValue("@UserId", userId);\n                cmd.Connection.Open();\n                new SqlDataAdapter(cmd).Fill(logStatusDs);\n            }\n        }\n        return logStatusDs;\n    }	0
13017039	13016561	How can I fix "exception has been thrown by the target of an invocation" while accessing data?	var selectedCity = cbCity.SelectedItem;\nvar query = conn.Table<auto_fares>().Where(x => x.city == selectedCity);\nvar result = await query.ToListAsync();\nforeach (var item in result)\n{\n    txtDistance.Text = item.min_km.ToString();\n    lblDayFare.Text = item.min_fare.ToString();\n    lblNightFare.Text = item.night_charges.ToString();\n}	0
15816246	15815986	Dynamically Assigning Values to a Child Class in C#	public ABroker(DP_ePAFBroker data)\n{\n    foreach(var property in typeof(DP_ePAFBroker).GetProperties())\n    {\n        // get the value\n        var value = property.GetValue(data, null);\n        // set it on this instance\n        property.SetValue(this, value, null);\n    }\n}	0
8991229	8990933	How to Write Automated System Tests with C#?	using OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium;\n\nclass GoogleSuggest\n{\n    static void Main(string[] args)\n    {\n        IWebDriver driver = new FirefoxDriver();\n        driver.Navigate().GoToUrl("http://www.google.com/");\n        IWebElement query = driver.FindElement(By.Name("q"));\n        query.SendKeys("Cheese");\n        System.Console.WriteLine("Page title is: " + driver.Title);\n        driver.Quit();\n    }\n}	0
1097622	1097456	linq to xml access data based on field attribute	XDocument doc = XDocument.Parse("<Data><Rows><Row><Field Name=\"title\">Mr</Field><Field Name=\"surname\">Doe</Field></Row></Rows></Data>");\nstring[] matches = (from e in doc.Descendants("Field")\n                    where (string)e.Attribute("Name") == "surname"\n                    select (string)e).ToArray();	0
6172093	6172071	How to get data from streamreader into a new class	public class Info\n{\n    public string NewInfo { get; private set; }\n\n    public string OldInfo { get; private set; }\n\n    public Info(string newInfo, string oldInfo)\n    {\n        NewInfo = newInfo;\n        OldInfo = oldInfo;\n    }\n}	0
12283170	12283050	Create Application from code and load resource dictionnary from xaml	myApp.InitializeComponent()	0
20583072	20581112	How to bind Enum to combobox with empty field in C#	public static List<object> GetDataSource(Type type, bool fillEmptyField = false)\n    {\n        if (type.IsEnum)\n        {\n            var data = Enum.GetValues(type).Cast<Enum>()\n                       .Select(E => new { Key = (object)Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })\n                       .ToList<object>();\n\n            var emptyObject = new {Key = default(object), Value = ""};\n\n            if (fillEmptyField)\n            {\n                data.Insert(0, emptyObject); // insert the empty field into the combobox\n            }\n            return data;\n        }\n        return null;\n    }	0
30876313	30768232	Press one button, focus all buttons	GUI.color = Color.black;	0
16406876	16405521	How to access 'Results', 'Messages', and 'Return Value' of a Stored Procedure using Entity Framework 4	try\n{\n    // call EF SP method here...\n}\ncatch(SqlException se)\n{\n    Debug.WriteLine(se.Message);\n}\ncatch(Exception e)\n{\n    // all non-DB errors will be seen here...\n}	0
29864791	29864051	Opening runspaces multiple times	using (var powershell = PowerShell.Create())\nusing (Runspace runspace = RunspaceFactory.CreateRunspace(connection))\n{\n    runspace.Open();\n    powershell.Runspace = runspace();\n    powershell.AddScript(Command);\n    results = powershell.Invoke();\n    runspace.Close();\n}	0
4573396	4475889	get local groups and not the primary groups for a domain user	PrincipalContext context = new PrincipalContext(ContextType.Domain, "yourdomain.com");\nUserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "youruser"); \n\nforeach (GroupPrincipal group in userPrincipal.GetAuthorizationGroups())\n{\n    Console.Out.WriteLine("{0}\\{1}", group.Context.Name, group.SamAccountName);\n}	0
469928	469902	Finding values within certain tags using regex	Regex r = new Regex("<ref>(?<match>.*?)</ref>");\nforeach (Match m in r.Matches(csv[4]))\n{\n    if (m.Groups.Count > 0)\n    {\n    if (m.Groups["match"].Captures.Count > 0)\n    {\n    foreach (Capture c in m.Groups["match"].Captures)\n    {\n    child.InnerText += c.Value + ", ";\n    }\n    child.InnerText = child.InnerText.Substring(0, child.InnerText.Length - 2).Replace("-> ", "");\n    }\n    }\n}	0
10284173	10283528	Create a buffered copy of WCF Message	MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);\n    message = buffer.CreateMessage();\n\n    var copy = buffer.CreateMessage();\n    XmlDictionaryReader bodyReader = copy.GetReaderAtBodyContents();\n    bodyReader.ReadStartElement("Binary");\n    byte[] bodyBytes = bodyReader.ReadContentAsBase64();\n    string messageBody = Encoding.UTF8.GetString(bodyBytes);\n\n    return messageBody;	0
14130899	14130861	Visual Studio intellisense to show custom options for my properties	public enum MyColors\n{\n     Red,\n     Blue,\n     Green,\n     White,\n     Blue\n }	0
9187768	9187240	Locating the source of an UnhandledException	System.Collections.Concurrent	0
10207397	10206557	C# cast Dictionary<string, AnyType> to Dictionary<string, Object> (Involving Reflection)	IDictionary dictionary = (IDictionary)field.GetValue(this);\nDictionary<string, object> newDictionary = CastDict(dictionary)\n                                           .ToDictionary(entry => (string)entry.Key,\n                                                         entry => entry.Value);\n\nprivate IEnumerable<DictionaryEntry> CastDict(IDictionary dictionary)\n{\n    foreach (DictionaryEntry entry in dictionary)\n    {\n        yield return entry;\n    }\n}	0
9451369	9451352	Is it recommended to remove Row from DataTable while in Foreach loop?	InvalidOperationException()	0
14178803	14178573	Displaying TextView Text with resource layout	var labelOwner = FindViewById<TextView> (Resource.Id.TextViewOwner);\n    labelOwner.Text = stringOwnerDisplayText;\n\nvar labelAddress = FindViewById<TextView> (Resource.Id.TextViewAddress);\nlabelAddress.Text = stringAddressDisplayText;	0
19926055	19925498	Error using DateTime 0001-01-01 in C# with WCF and JSON	var date = new DateTime(1,1,1,0,0,0,DateTimeKind.Utc);	0
5804170	5804074	C# remove all but two least significant bits of color	colour.R &= 3;\ncolour.G &= 3;\ncolour.B &= 3;\ncolour.A &= 3;	0
7511308	7511219	Storing global immutable data in static classes	public class MyUserControl : UserControl \n{\n    [Dependency]\n    public LoggedUserService UserService { get; set; }\n\n    public void Method()\n    {\n        // the IoC container will ensure that the UserService\n        // property has been set to an object\n    }\n}	0
761315	761303	Where to write XML with XmlWriter for sending via HttpWebRequest POST in ASP.NET?	var buidler = new StringBuilder();\nvar writer = XmlWriter.Create(builder);	0
15660908	15642835	Looping - amount of years from months	int employmentInMonthsAmount = this.MaxEmploymentHistoryInMonths;\n\n                var intcounter = 0;\n                int years = 0;\n                for (var i = 0; i < employmentInMonthsAmount; i++)\n                {\n                    if (intcounter >= 12)\n                    {\n                        years++;\n                        intcounter = 0;\n                    }\n                    intcounter++;\n                }\n                var monthsleft = intcounter;	0
6810803	6739303	how to change the direction of X-axis label in ms charts	chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -90;	0
8186552	8142241	A way to monitor when a Control's screen location changes?	private Control         _anchorControl;\nprivate List<Control>   _parentChain = new List<Control>();\nprivate void BuildChain()\n{\n    foreach(var item in _parentChain)\n    {\n        item.LocationChanged -= ControlLocationChanged;\n        item.ParentChanged -= ControlParentChanged;\n    }\n\n    var current = _anchorControl;\n\n    while( current != null )\n    {\n        _parentChain.Add(current);\n        current = current.Parent;\n    }\n\n    foreach(var item in _parentChain)\n    {\n        item.LocationChanged += ControlLocationChanged;\n        item.ParentChanged += ControlParentChanged;\n    }\n}\n\nvoid ControlParentChanged(object sender, EventArgs e)\n{\n    BuildChain();\n    ControlLocationChanged(sender, e);\n}\n\nvoid ControlLocationChanged(object sender, EventArgs e)\n{\n    // Update Location of Form\n    if( _anchorControl.Parent != null )\n    {\n        var screenLoc = _anchorControl.Parent.PointToScreen(_anchorControl.Location);\n        UpdateFormLocation(screenLoc);\n    }\n}	0
1150815	1150803	C# codes to get a list of strings like A to Z?	list.Add((char)('A' + i) + ":");	0
21334822	21334662	Assert.AreEqual on a property that only has a Setter, unit testing in MVP	mockICalculatorView.VerifySet(m => m.Answer = 4, Times.Once());	0
33799537	33737417	How to Create an Instance of a Class in runtime derived from ObservableCollection<T>?	private void CreateObject(ObservableCollection<MobileModelInfo> Source)\n{\n    var gType = Source.GetType();\n    string collectionFullName = gType.FullName;\n    Type[] genericTypes = gType.GetGenericArguments();\n    string className = genericTypes[0].Name;\n    string classFullName = genericTypes[0].FullName;\n\n    // Get the type contained in the name string\n    Type type = Type.GetType(classFullName, true);\n\n    // create an instance of that type\n    object instance = Activator.CreateInstance(type);\n\n    // List of Propery for the above created instance of a dynamic class\n    List<PropertyInfo> oProperty = instance.GetType().GetProperties().ToList();\n}	0
21755678	21754144	ASP.NET dynamically add column to Gridview	BoundField test = new BoundField();\n            test.DataField = "New DATAfield Name";\n            test.Headertext = "New Header";\n            CustomersGridView.Columns.Add(test);	0
19513350	19512549	Linq update and merge two result sets (from data tables)	var query=from c in customer.AsEnumerable()\n         join uc in updatedCustomer.AsEnumerable()\n         on c.Field<int>("ID") equals uc.Field<int>("ID") into lf\n         from uc in lf.DefaultIfEmpty()\n         select new\n         {\n             ID=c.Field<int>("ID"),\n             Address=uc==null?c.Field<string>("Address"):uc.Field<string>("Address")\n         };\n\n//this will get the result you want,but it is not DataTable.\n//you need to convert query to datatable .\nDataTable result =customer.Clone();\n\nquery.ToList().ForEach(q=>result.Rows.Add(q.ID,q.Address));	0
10822424	10816523	Unable to cast Session variable Containing a List Of object to list	private void SetSession()\n{\n   if(Session["Account"] == null)\n      Session["Account"] = "Value";\n   else\n      //what do you want to do here\n}\n\n\nprotected void button1_click(.....)\n{\n    SetSession();\n    //do something\n}\n\nprotected void button2_click(....)\n{\n    SetSession();\n    //redirect\n}	0
30696683	30695836	filter from listbox regex	string filter = "12";\nstring line = "Id: 1 Leefijd pati?nt: 12 Gave blood: yes";\n\nRegex rx = new Regex(@"Leefijd[ ]pati?nt:[ ]+(\d+)");\nMatch _m = rx.Match( line );\nif (_m.Success && _m.Groups[1].Value == filter)\n{\n    Console.WriteLine("Add this to listbox {0} ", line );\n}	0
20372263	20372163	Sorting a list of strings in a very specific order	public class ExampleComparer : IComparer<Example>\n{\n    private const string Order = "XQLHPJ";\n\n    public int Compare(Example a, Example b)\n    {\n         int indexA = Order.IndexOf(a.GridValue);\n         int indexB = Order.IndexOf(b.GridValue);\n         if (indexA < indexB) { return -1; }\n         else if (indexB > indexA) { return 1; }\n         else { return 0; }\n    }\n}	0
7792785	7792521	A service that would track and catch whenever someone is trying to take a screenshot	GetDC(NULL)	0
13622352	12600099	How can I logout from facebook from my app in MonoTouch	NSHttpCookieStorage storage = NSHttpCookieStorage.SharedStorage;\n\n    foreach (NSHttpCookie cookie in storage.Cookies) \n    {\n      if(cookie.Domain == ".facebook.com")\n      {\n        storage.DeleteCookie(cookie);\n      }\n\n    }	0
17776311	17776053	Sending a message with C# works locally but silently fails live	catch (Exception ex) \n{\n          DisplayMessage.Text = "Failed to send email. Error = " + ex.message;\n        DisplayMessage.Visible = true;\n}	0
10377447	10377189	EncoderFallbackException while writing to file	static void Main(string[] args)\n{\n    // A perfectly valid surrogate pair with 1st character in the D800-DBFF range,\n    // and 2nd character in the DC00-DFFF range.\n    string validSurrogate = "\uD801\uDC01";\n\n    // Creating an invalid surrogate pair just by swapping the two characters in the first string.\n    string invalidSurrogate = validSurrogate.Substring(1, 1) + validSurrogate[0];\n\n    // This will work fine.\n    File.WriteAllText("valid.txt", validSurrogate);\n\n    // --! But this will crash !--\n    File.WriteAllText("invalid.txt", invalidSurrogate);\n}	0
8025612	8025203	How to save content of ArrayList to the file?	public string arrayToString(System.Collections.ArrayList ar)\n{\n    StringBuilder sb = new StringBuilder();\n    System.Xml.XmlWriterSettings st = new System.Xml.XmlWriterSettings();\n    st.OmitXmlDeclaration = true;\n    st.Indent = false;\n    System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(sb, st);\n    System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(ar.GetType());\n    s.Serialize(w, ar);\n    w.Close();\n    return sb.ToString();        \n}\n\npublic static void SaveArraytoFile(System.Collections.ArrayList ar, string fileName)\n{\n    using (System.IO.StreamWriter sw = new StreamWriter(fileName))\n    {\n        foreach (var item in ar)\n        {\n            sw.WriteLine(item);\n        }\n    }\n}	0
14806732	14806661	Looping through XML document	foreach (XmlNode xndNode in xnlNodes)\n{\n  string name= xndNode ["Name"].InnerText;\n  string AnnualSalary= xndNode ["AnnualSalary"].InnerText;\n  string DaysWorked= xndNode ["DaysWorked"].InnerText;\n\n //Your sql insert command will go here;\n}	0
2629741	2629720	Debug Windows Service	var ServiceToRun = new SomeService(); \n if (Environment.UserInteractive)\n {\n    // This used to run the service as a console (development phase only)\n\n    ServiceToRun.Start();\n\n    Console.WriteLine("Press Enter to terminate ...");\n    Console.ReadLine();\n\n    ServiceToRun.DoStop();\n }\n else\n {\n    ServiceBase.Run(ServiceToRun);\n }	0
416043	416027	How to generate 2-characters long words effectively?	List<string> GetWords(IEnumberable<char> characters) {\n    char[] chars = characters.Distinct().ToArray();\n    List<string> words = new List<string>(chars.Length*chars.Length);\n    foreach (char i in chars)\n       foreach (char j in chars)\n          words.Add(i.ToString() + j.ToString());\n    return words;\n}	0
6866365	6866347	Lambda\Anonymous Function as a parameter	void MakeOutput(Func<int> param) {\n    Console.WriteLine(param());\n}\n\nmakeOutput(delegate { return 4; });\nmakeOutput(() => { return 4; });\nmakeOutput(() => 4);	0
21486477	21466608	Programmatically add highlighting to shape (path)	Storyboard.SetTargetProperty(anim1, new PropertyPath("Fill.Color"));	0
17608169	17607862	Displaying rows for last 7 days	dateadd(day,datediff(day,0,GetDate()) + 7,0)	0
32848147	32847880	Can't get contents of the Clipboard in Windows 8.1 app	private async void Clipboard_ContentChanged(object sender, object e)\n{\n    textBox.Text = "clipboard now contains: " + await Clipboard.GetContent().GetTextAsync();\n}	0
31037719	31036802	How to format UITextField.ReplaceText	UITextRange range = myTextField.GetTextRange(start,end);\nmyTextField.ReplaceText(range, newstring);	0
20515434	20515247	Is it possible to use a silverlight reference in wpf?	Mscorlib\nSystem\nSystem.Core\nSystem.ComponentModel.Composition\nMicrosoft.VisualBasic	0
17143937	17143892	How can I add in a where clause to a select in LINQ?	var result =\n    from entry in feed.Descendants(a + "entry")\n    let content = entry.Element(a + "content")\n    let properties = content.Element(m + "properties")\n    let text = properties.Element(d + "Text")\n    let title = properties.Element(d + "Title")\n    let partitionKey = properties.Element(d + "PartitionKey")\n    where partitionKey.Value.Substring(2, 2) == "03"\n    where text != null\n    select new Content\n    {\n        Text = text.Value,\n        Title = title.Value\n    };	0
22882978	22882796	operator to access other classes's objects	for (int k = 0; k < total.ItemCount; k++)\n        {\n            var x = total[k] as OrderItem;\n            if (x == null) continue;\n            Console.WriteLine(x.Name);\n            Console.WriteLine(x.Order);\n        }	0
10413456	10412662	Cannot convert Array to String	string followers = (string)o["ids"].ToString();	0
30464395	30464214	Downloading a .JSON file in WP8.1	using (HttpClient client = new HttpClient())\n{\n    using (HttpResponseMessage response = await client.GetAsync(uri, cancel))\n    {\n        using (Stream stream = response.Content.ReadAsStreamAsync().Result)\n        {\n            using (StreamReader reader = new StreamReader(stream))\n            {\n                return new JsonSerializer().Deserialize<T>(new JsonTextReader(reader));\n            }\n        }\n    }\n}	0
7535309	7535280	Writing formatted XML with XmlWriter 	myXmlWriter.Settings.Indent = true;\nmyXmlWriter.Settings.IndentChars = "     "; // note: default is two spaces\nmyXmlWriter.Settings.NewLineOnAttributes = false;\nmyXmlWriter.Settings.OmitXmlDeclaration = true;	0
15066260	15066046	How to disable specific menu item from menu control in asp.net C# code behind	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (strAdmin == "False")\n        {\n            MenuItem mnuItem = Menu1.FindItem("Reports"); // Find particular item\n            Menu1.Items.Remove(mnuItem);\n            MenuItem mnuItem1 = Menu1.FindItem("Master"); // Find particular item\n            Menu1.Items.Remove(mnuItem1);\n            Menu1.Width = Unit.Percentage(30);\n        }\n    }	0
7584578	7581892	ToolStripButton disappear from PropertyGrid when user log-in to Windows	using System;\nusing System.Windows.Forms;\n\nclass MyPropertyGrid : PropertyGrid {\n    protected override void OnSystemColorsChanged(EventArgs e) {\n        // Do nothing\n    }\n}	0
6793768	6793738	How do I find the IP address of a web site that is sending data by POST method to an asp.net web page?	Request.ServerVariables("REMOTE_ADDR")	0
4152173	4152162	How to pull filtered Data from a Datatable and create a string	ToArray().\n            Cast<DataRow>().	0
9446951	9446718	Reading atom feeds title and posted datetime	var xdoc = XDocument.Load("http://blogs.technet.com/b/markrussinovich/atom.aspx");\nXNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom");\n\nvar info = xdoc.Root\n            .Descendants(ns+"entry")\n            .Select(n =>\n                new\n                {\n                    Title = n.Element(ns+"title").Value,\n                    Time = DateTime.Parse(n.Element(ns+"published").Value),\n                }).ToList();	0
2260032	2257180	how to create the image dynamically in ASP.NET?	for(int i=0;i<value;i++)\n{\nstring strimage="";\nstrimage="<img src=''.../>";\n\n}\n\ndiv.innerhtml=strimage;	0
7248843	7248207	Pass 128 bits from managed C++ to C#	public value struct Int128\n{\n    System::Int64 lo;\n    System::Int64 hi;\n};	0
1827800	1824989	How to store System.Windows.Controls.Image to local disk	private void SaveImageToJPEG(Image ImageToSave, string Location)\n        {\n            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)ImageToSave.Source.Width,\n                                                                           (int)ImageToSave.Source.Height,\n                                                                           100, 100, PixelFormats.Default);\n            renderTargetBitmap.Render(ImageToSave);\n            JpegBitmapEncoder jpegBitmapEncoder = new JpegBitmapEncoder();\n            jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));\n            using (FileStream fileStream = new FileStream(Location, FileMode.Create))\n            {\n                jpegBitmapEncoder.Save(fileStream);\n                fileStream.Flush();\n                fileStream.Close();\n            }\n        }	0
4169654	4169643	Lambda expression for getting items from list according to indexes	var result = indexes.Select(i => alist[i]).ToList();	0
31354956	31354867	How to sort textboxes and buttons selection order in C#	View -> Tab Order	0
6860828	6860776	assigning a Value in Set accssor Instead of using value keyword	void Set__MyValue(int value){\n  _value=5;\n}	0
2006869	2006762	How can I map my LINQ to SQL grouped result to this existing interface?	private class SponsorLevelGroup : ISponsorLevelGroup\n{\n   public string Level { get; set; }\n   public IList<Sponsor> Sponsors { get; set; }\n}\n\nvar result = ( from s in db.Sponsors\n               join sl in sb.SponsorLevels on s.SponsorLevelId equals sl.SponsorLevelId\n               select new Sponsor \n               {\n                 Name = s.Name,\n                 Level = sl.LevelName\n               }\n             ).GroupBy(s => s.LevelName)\n              .Select(g => new SponsorLevelGroup\n                               {\n                                   Level = g.Key,\n                                   Sponsors = g.ToList()\n                                }) ;	0
33301176	33298867	How to convert a large hexadecimal string to a byte array?	/// <summary>\n    /// Parses a continuous hex stream from a string.\n    /// </summary>\n    public static byte[] ParseHexBytes(this string s)\n    {\n        if (s == null)\n            throw new ArgumentNullException("s");\n\n        if (s.Length == 0)\n            return new byte[0];\n\n        if (s.Length % 2 != 0)\n            throw new ArgumentException("Source length error", "s");\n\n        int length = s.Length >> 1;\n        byte[] result = new byte[length];\n        for (int i = 0; i < length; i++)\n        {\n            result[i] = Byte.Parse(s.Substring(i * 2, 2), NumberStyles.HexNumber);\n        }\n        return result;\n    }	0
6117359	6103587	How to call a C# IEnumerable from IronRuby	Myro::getPixels(pic).each do |pixel|\n    ...\nend	0
32432872	32429016	Xml file show incorrect time data after exported it from gridview	Rds.WriteXml(@"c:\Reporting\WorkHours_Report.xml", System.Data.XmlWriteMode.WriteSchema);	0
8801354	8801246	using regexpression to replace a word	string resultString = null;\ntry {\n    resultString = Regex.Replace(subjectString, "(?:not|or)", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);\n} catch (ArgumentException ex) {\n    // Syntax error in the regular expression\n}	0
4139834	4139706	Search repeat (any type of repeat) substring in a long string without space	match_min = 2\nmatch_max = 5\n\nsearch_cache = Hashtable()\nfor (chunk_size = match_min; chunk_size < min(match_max+1, len(str)/2); chunk_size++){\n  for (start = 0; start < len(str) - chunk_size; start++){\n    sub = str.substring(start, start + chunk_size)\n    // We want to know if sub repeats\n    if (sub not in search_cache)\n      search_cache[sub] = str.substring(start + chunk_size, len(str) - chunk_size + 1).find(sub)\n    if (search_cache[sub] != -1)\n      print "MATCH FOUND %s at %d-%d" % (sub, start, search_cache[sub])\n  }\n}	0
22328588	22235615	How to do Linq LIKE or Contains when both values have strings added to them	userList = userList.Where(\n    r => (r.roles.Split(',')).Any(o => o == filter.role)\n);	0
1398809	1398796	'casting' with reflection	void SetValue(PropertyInfo info, object instance, object value)\n{\n    info.SetValue(instance, Convert.ChangeType(value, info.PropertyType));\n}	0
2881007	2880980	How to use scanner in c#.net application	private void TextBox1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Enter)\n    {\n        // Do your thing with the supplied barcode! \n        e.Handled = true;\n    }\n}	0
18377913	18377859	Merge values in a single List	list = list.GroupBy(s => s.Split(':')[0].ToLower())\n           .Select(g => g.Last())\n           .ToList();	0
28408190	28407866	Interval between wav file play loop in c#	using System.Threading;\nusing System.Threading.Tasks;\n\nSystem.Media.SoundPlayer player = new System.Media.SoundPlayer();\nplayer.Stream = Properties.Resources.ringtone;\n\nTask.Run(()=>\n{\n     while (true)\n     {\n        player.Play();\n        Thread.Sleep(2000);\n     }\n});	0
12677213	12677187	How to add or edit a child in parent view	Html.BeginCollectionItem	0
11006226	11005067	Converting a Grayscale image to black&white using Aforge.Net	// create filter\nThreshold filter = new Threshold( 100 );\n// apply the filter\nfilter.ApplyInPlace( image );	0
31468340	31468183	Change Application.ResourceAssembly in WPF?	Application.ResourceAssembly	0
7657593	7657562	Design Pattern which deals with loading databases	public interface IDataStore\n{\n  void AddData(SomeData data);\n}	0
21383542	21383499	Creating List from initializer	var foo = new Bar {\n    Prop = "value"\n};	0
10899523	10899491	Set one enum equal to another	obj1.enum1 = (MVC1.MyEnum)((int)obj2.enum1);	0
24419203	24419134	Default parameter must be compile-time constant	public void UpdateTable(int month = -1, int year = -1)\n    {\n        if (month == -1) month = DateTime.Now.Month;\n        if (year == -1) year = DateTime.Now.Year;\n    }	0
14009817	14009739	Render Line From Rectangles	void renderLine(Point p1, Point p2)\n{\n    List<Point> points = pointsOnLine(p1, p2);\n\n    int dx = Abs(p2.x - p1.x);\n    int dy = Abs(p2.y - p1.y);\n\n    Rectangle selection = world.SelectionRectangle;\n\n    int incr = selection.Width / world.Settings.TileSize.Width;\n    if(dy > dx)\n    {\n        incr = selection.Height / world.Settings.TileSize.Height;\n    }\n\n    int lastPoint = (points.Count-1) / incr;\n    lastPoint *= incr;\n\n    for (int i = 0; i <= lastPoint; i+=incr)\n        renderPoint(points[i], i == lastPoint);\n}	0
4070319	4067793	WPF: Opening 2 pages at one Window at the same time	LeftPage LP = new LeftPage()	0
32308672	32308599	Get datatype of column in datatable	if(dt!=null && dt.Rows.Count > 0)\n{\n    for (int j = 0; j < dt.Columns.Count; j++)\n     {\n           columntypes[j] = dt.Columns[j].DataType.Name.ToString();\n     } \n}	0
2151429	2151410	C# auto highlight text in a textbox control	textbox.SelectionStart = 0;\ntextbox.SelectionLength = textbox.Text.Length;	0
20382942	20382893	Simple way to populate a List with a range of Datetime	var startDate = new DateTime(2013, 12, 1);\nvar endDate = new DateTime(2013, 12, 5);\n\nvar dates = Enumerable.Range(0, (int)(endDate - startDate).TotalDays + 1)\n                      .Select(x => startDate.AddDays(x))\n                      .ToList();	0
6625815	6625709	Get Count in List of instances contained in a string	count = mylist.Count(s => myString.Contains(s));	0
21672465	21672402	How to get access to "CssClass" property for server element isn't WebControl in ASP.NET?	myCoolElement.Attributes["class"] = "mycoolstyle";	0
15705291	15700551	XNA Keyboard cyrillic Input	using System.Windows.Forms;\n\n...\n\nvar form = (Form)Form.FromHandle(window.Handle);\nform.KeyPress += form_KeyPress;\n\n...\n\nprivate void form_KeyPress(Object sender, KeyPressEventArgs e)\n{  \n    Console.WriteLine(e.KeyChar);\n    e.Handled = true;\n}	0
5139537	5139380	REG Threading: How to implement This	public event EventHandler Disconnected;\n\n\n    timer = new System.Timers.Timer(10000);\n    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n    timer.Enabled = true;\n\n    ...\n\n    private static void OnTimedEvent(object source, ElapsedEventArgs e)\n    {\n       // check if connection is alive\n       conneced = UltimateLibrary.http.HTTPUtility.isConnectionAvailable();\n       if (!connected)\n       { \n          // inform listeners\n          var listener = Disconnected;\n          if (null !- listener)\n          {\n              Disconnected(EventArgs.Empty);\n          }\n       }\n    }	0
32408723	32408076	Set Property Type to a Type of a Class	public class MyClass<MyType>\n{\n   public MyType MyProperty { get; set; }\n}	0
5596353	5587387	Convert SQL with 'is in' to QueryOver()	var query = contactRepository.GetAllOver()\n                .Where(x => x.Country != null && x.Country.Id == countryId)\n                .And(Restrictions.On(c => c.ID).IsIn(contactTypes)	0
25474164	25473928	C# Open winform from commandline	Application.SetCompatibleTextRenderingDefault(false);	0
7601526	7601171	How to repeat a set of characters	var s = String.Concat(Enumerable.Repeat("-.", 10));	0
31366675	29296778	How to generate an OWIN bearer token during registration of a user	AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());\nstring token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);	0
24556951	24533178	Iterating over all scenes before compilation	class MyBuilder : Editor {\n\n    private static string[] FillLevels ()\n    {\n        return (from scene in EditorBuildSettings.scenes where scene.enabled select scene.path).ToArray ();\n    }\n\n    [MenuItem ("MyTool/BuildGame")]\n    public static void  buildGame()\n    {\n        string[] levels = FillLevels ();\n        foreach (string level in levels) {\n            EditorApplication.OpenScene (level);\n            object[] allObjects = Resources.FindObjectsOfTypeAll (typeof(UnityEngine.GameObject));\n            foreach (object thisObject in allObjects) {\n               /* my gameObjects changing before compilation */\n            }\n            EditorApplication.SaveScene ();\n        }\n        BuildPipeline.BuildPlayer (levels, Path.GetFullPath (Application.dataPath + "/../game.exe"), BuildTarget.StandaloneWindows, BuildOptions.None);\n    }\n}	0
7970476	7970276	Reading from RavenDb immediately after writing to it returns inconsistent data	session.Query<Page>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).FirstOrDefault(page => page.PageId == pageId)	0
21633101	21606669	How to Reassign Consecutive Sequence/Incremental value (Counting numbers) on the list	var newSequence = int.Parse(Console.ReadLine());\n      if (newSequence <= products.Count&& newSequence>0)\n         {\n         products.Remove(product);\n         products.Insert(newSequence-1,product);\n         }\n      else\n         {\n      products.Remove(product);\n      products.Insert(newSequence <= 0 ? 0 : products.Count, product);\n         }\n      var count = 1;\n      foreach (var item in products)\n         {\n         item.Sequence = count;\n         count++;\n         }	0
22506943	22473430	Emit mapper domain model to view model	var mapper1 = ObjectMapperManager.DefaultInstance.GetMapper<A, B_ViewModel>();\nvar mapper2 = ObjectMapperManager.DefaultInstance.GetMapper<B, B_ViewModel>();\n\nvar result = new B_ViewModel();\nmapper1.Map(a, result); \nmapper2.Map(b, result);	0
15543019	15515162	How to get the pixels height and width of a font sizs in WinRT app?	TextBlock dummyTextBlock = new TextBlock();\ndummyTextBlock.FontFamily = new FontFamily("Tahoma");\ndummyTextBlock.FontSize = 18;\ndummyTextBlock.FontStyle = FontStyle.Normal;\ndummyTextBlock.FontWeight = FontWeights.Bold;\ndummyTextBlock.Text = "X";\ndummyTextBlock.Measure(new Size(0,0));\ndummyTextBlock.Arrange(new Rect(0,0,0,0));\ndouble width = dummyTextBlock.ActualWidth;\ndouble height = dummyTextBlock.ActualHeight;	0
16542321	16539361	navigate to another page after Thread sleep in wp7	var myPage = Application.Current.RootVisual as PhoneApplicationFrame;\n  myPage.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));	0
28933398	28933261	Updating last entry in OleDbCommand with the same ID	OleDbCommand commandUpdate = new OleDbCommand("UPDATE [Building_Login] SET Exited = '" + DateTime.Now + "' WHERE User_ID = @UserId AND Entered = (SELECT Top 1 Entered AS latest FROM [Building_Login] WHERE User_ID = @UserId ORDER BY Entered DESC)", connection);	0
6356487	6356400	Casting int to string in Linq where clause	p.ProductID != null &&  SqlFunctions.StringConvert((double)p.ProductID).Contains(s)	0
31792968	31792866	Regex to extract string between quotes	GroupCollection ids = Regex.Match(nodeValue, "(?<=ID=\")[^\"]*").Groups;	0
11869468	11828826	shutdown wpf while messagebox open	Application.Current.Shutdown();	0
4993879	4993741	Updating a *.CSPROJ using MSBUILD API	var Property001item =\n        (from pg in project.PropertyGroups.Cast<BuildPropertyGroup>()\n        from item in pg.Cast<BuildProperty>()\n        where item.Name == "Property001"\n        select item).FirstOrDefault();\nif (Property001item != null)\n{\n    Property001item.Value = "MyNewValue";\n}	0
1818810	1818689	argument passing to a javascript function from an asp.net c# button clock event	myButton.Attributes.Add("onclick", "openNewWindow('" + spcd + "');";	0
2475939	2475909	How to show only border of winforms window when resizing?	private void Form1_ResizeBegin(object sender, EventArgs e)\n            {\n                panel1.Visible = false;\n  Form1.ActiveForm.TransparencyKey = Color.Transparent;\n            }\n      private void Form1_ResizeEnd(object sender, EventArgs e)\n            {\n                panel1.Visible = true;\n Form1.ActiveForm.TransparencyKey = Color.Gray; // or whatever color your form was\n            }	0
21327345	21327101	Parsing a string with Dimensions in c#	string str = "14/01/13 09:06AM   502 19 <I>01203851288            0'00 00:00'45            D0";\n        var strings = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);	0
24910368	24910332	Getting data in Entity Framework	var books = (from book in db.Books  \n             select new { book.Title, book.Author.Name, book.Price }).ToList();	0
16183330	16183254	How to do LINQ Cross Join With Dot Notation	als.SelectMany(x => bros, (a, b) => new {A = a, B = b});	0
4091796	4091735	VIsual Studio WinForm connecting to SQL Server Database: C# syntax to transfer the data	System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection("SomeConnectionString")\n\nSystem.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();\ncmd.CommandText = "Insert Into tblExample (fldExample) Values (@fldExample)"; // Use a parameterized query to avoid SQL Injection\ncmd.Connection = cn;\n\ncmd.Parameters.AddWithValue("@fldExample", txtData.Text);  // Set the value of the parameter to the value of the textbox.\n// Use a try... catch...finally block to ensure the connection is closed properly\ntry\n{\n   cn.Open();\n   cmd.ExecuteNonQuery();\n   lblStatus.Text = "Item Inserted";\n}\ncatch(Exception ex)\n{\n   lblStatus.Text = ex.ToString();\n}\nfinally\n{\n   cn.Close(); // will happen whether the try is successful or errors out, ensuring your connection is closed properly.\n}	0
3952809	3950204	Create data objects from Xaml file	// The data model\npublic class TestItem\n{\n    public string Name { get; set; }\n    public decimal Value { get; set; }\n    public string Category { get; set; }\n}	0
9736650	9736549	Encrypt a password in C# and decrypt it in php	System.Security.Cryptography.Rijndael	0
7764737	7764692	List<string> how to get a specific string	string match = strings.FirstOrDefault(c => String.Equals(c, navn, StringComparison.InvariantCultureIgnoreCase));\nif (match != null)\n{\n   Console.WriteLine("going inside");\n   strings.Remove(match);\n   listBox_varer.Items.Clear();\n   for (int i = 0; i <= (strings.Count - 1); i++)\n   {\n       string pr = string.Concat(strings[i], Environment.NewLine);\n       listBox_varer.Items.Add(pr);\n    }\n }\n else\n {\n    Console.WriteLine("going in else");\n }	0
14210574	14209811	In WPF how to give the InteropBitmap drawing font	public MainWindow()\n{\n    InitializeComponent();\n\n    Grid myGrid = new Grid();\n    BitmapImage bmp = new BitmapImage(new Uri(@"C:\temp\test.jpg")); //Use the path to your Image \n    DrawingVisual dv = new DrawingVisual();\n    DrawingContext dc = dv.RenderOpen();\n    dc.DrawImage(bmp, new Rect(100, 100, 300, 300));\n\n    dc.DrawText(new FormattedText("Hello World",\n                CultureInfo.GetCultureInfo("en-us"),\n                FlowDirection.LeftToRight,\n                new Typeface("Arial"),\n                30, System.Windows.Media.Brushes.Black),\n                new System.Windows.Point(100, 120));\n\n    dc.Close();\n\n    myGrid.Background = new VisualBrush(dv); \n    this.Content = myGrid;\n}	0
9217769	9217686	Flatten XML structure by element with linq to xml	var doc = XDocument.Load("test.xml");\nXNamespace ns = "mynamespace";\nvar member = doc.Root.Element(ns + "member");\n\n// This will *sort* of flatten, but create copies...\nvar descendants = member.Descendants().ToList();\n\n// So we need to strip child elements from everywhere...\n// (but only elements, not text nodes). The ToList() call\n// materializes the query, so we're not removing while we're iterating.\nforeach (var nested in descendants.Elements().ToList())\n{\n    nested.Remove();\n}\nmember.ReplaceNodes(descendants);	0
11453050	11452826	Improving my failing regex	(.+\s*-\s*.+\s*-\s*.+)\s*-\s*((\w{1,3}\s*-\s*\w{1,3})|(\w{1,4}\s*-\s*\w{1,4}))\s*-\s*.+	0
17261800	17259186	DateTime saved as numeric value using SqlBulkCopy	DateTime.FromOADate(num).ToShortDateString();	0
16208761	16208671	How to Convert Int into Time in c#?	int val = 16;\nTimeSpan result = TimeSpan.FromHours(val);\nstring fromTimeString = result.ToString("hh':'mm");	0
30338954	30338899	variable number of serialized arrays c#	int var = 2;\nint var2 = 2;\nList<int[]> arrays = new List<int[]>();\nfor (int i = 0; i < var; i++)\n{\n    arrays.Add(new int[var2]);\n}	0
33416439	33414606	Need to create Expression<Action> from strings	// ... (same as yours except the last 2 lines)\nvar myAction = Expression.Lambda<Action>(Expression.Call(Expression.New(myType), myMethod));\nRecurringJob.AddOrUpdate(myAction, myCronString);	0
16413117	16407426	how can I get rid of the unnecessary black squares in portrait orientation in xna?	//For 480x800 (90* rotated wp7 device)\nGraphics.PreferredBackBufferWidth = 480;\nGraphics.PreferredBackBufferHeight = 800;	0
33388507	33244705	Easy and reasonable secure way to identify a specific network	private static bool m_isHomeLocation = false;\n  public static bool IsHomeLocation\n  {\n      get\n      {\n          if (m_isHomeLocation)\n              return true;\n          try\n          {\n              HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://yourLicenseServer:yourConfiguredPort");\n              request.ServerCertificateValidationCallback += ((s, certificate, chain, sslPolicyErrors) => true);\n              HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n              response.Close();\n              var thumbprint = new X509Certificate2(request.ServicePoint.Certificate).Thumbprint;\n              m_isHomeLocation = (thumbprint == "WhateverThumbprintYourCertificateHave");                    \n          }\n          catch\n          {\n              // pass - maybe next time\n          }\n          return m_isHomeLocation;\n      }\n  }	0
9611442	9590960	How to cause personal.xls workbook to open when starting Excel via automation?	Excel.Application xlApp = new Excel.Application();\nstring filename = xlApp.StartupPath + "\\personal.xls";\n\nxlApp.Workbooks.Open(filename, 0, false, 5, Missing.Value, Missing.Value, false,\n    Missing.Value, Missing.Value, Missing.Value, false, Missing.Value, false,\n    true, false);	0
21261417	21255530	Get hierarchical data neo4jclient	MATCH (root:Lvl1)-[:HAVE_LVL2|HAVE_LVL3*0..]->(leaf)\nRETURN distinct leaf	0
8421169	8407245	Dynamic TextBlock font size in Silverlight	// Event handler\nprivate void ControlsSizeChanged(object sender, System.Windows.SizeChangedEventArgs e)\n{\n    GetFontSize(sender as Control);\n}\n\n// Method for font size changes\npublic static void GetFontSize(Control control)\n{\n    PropertyInfo info;\n    if (control == null || control.ActualHeight <= 0)\n        return;\n    if(( info = control.GetType().GetProperty("FontSize", typeof(double))) != null)\n    {\n        info.SetValue(control, 0.7 * control.ActualHeight, null);\n    }\n}	0
29991765	29991670	How do I convert this LINQ query to lambda query?	public List<Tuple<Klasa2, Klasa2>> CompareLists(List<Klasa2> list1, List<Klasa2> list2)\n{\n    var pary =\n        list1.SelectMany(l1 => list2, (l1, l2) => new {l1, l2})\n            .Where(@t => @t.l1.tytul.Length < @t.l2.tytul.Length)\n            .Select(@t => new Tuple<Klasa2, Klasa2>(@t.l1, @t.l2));\n    return pary.ToList();\n}	0
17304607	17248309	Lambda Generic Expression w/ Out Parameter	public static string GetName<T>(Expression<T> field)\n{\n    var callExpression = field.Body as MethodCallExpression;\n    return callExpression != null ? callExpression.Method.Name : string.Empty;\n}	0
4107092	4106935	Determine rows/columns needed given a number	int columns = (int)sqrt(number);\nint lines = (int)ceil(number / (float)columns);	0
7264128	7260746	Using Rx (Reactive Extensions) to watch for specific item in ObservableCollection	theCollection.ItemsAdded\n    .Where(x => x.Key == "Foo")\n    .Subscribe(x => Console.WriteLine("Received Item!"));	0
15836017	15835802	Global.asax - Application_Error - How can I get Page data?	void Application_Error(object sender, EventArgs e)\n{\n    // Code that runs when an unhandled error occurs\n    if (HttpContext.Current != null)\n    {\n        var url = HttpContext.Current.Request.Url;\n        var page = HttpContext.Current.Handler as System.Web.UI.Page;\n    }\n}	0
25697925	25697917	How to display serial number in datagridview?	private void gridStateZone_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)\n    {\n        LoadSerial(gridStateZone);\n    }\n\n\nprivate void LoadSerial(DataGridView grid)\n    {\n        foreach (DataGridViewRow row in grid.Rows)\n        {\n            grid.Rows[row.Index].HeaderCell.Value = string.Format("{0}  ", row.Index + 1).ToString();\n            row.Height = 25;\n        }\n    }	0
13254271	13254211	how to convert string to DateTime as UTC as simple as that	DateTimeOffset.Parse(string).UtcDateTime	0
30993384	30990445	How to catch email deletion on the main inbox explorer?	Items.ItemAdd	0
30948010	30947513	How I implement Multithread pool for a repetitive process	Parallel.For(0, 1000000, (i, loopState) =>\n{\n    result[i] = Test(i);\n    if (result[i] == 0) \n    {\n        loopState.Stop();\n        return;\n    }\n});	0
25950206	25950044	Place a grid of labels on a form	foreach (var lbl in _labels)\n    {\n        if (x >= 580)\n        {\n            x = 0;\n            y = y + lbl.Height + 2;\n       }\n\n         lbl.Location = new Point(x, y);\n         this.Controls.Add(lbl);\n        x +=  lbl.Width;\n    }	0
20680878	20538410	C# interface inherited by C++	(ISample)this	0
26608671	26608550	Binding method to button in WPF	public partial class MainWindow : Window {\nprivate string[] ips;\n\npublic MainWindow()\n{\n    InitializeComponent();\n\n    try\n    {\n        IPAddress[] addrs = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList,\n           a => a.AddressFamily == AddressFamily.InterNetwork);\n        ServerOutputTextBox.AppendText("Your IPv4 address is: ");\n        foreach (IPAddress addr in addrs)\n        {\n            ServerOutputTextBox.AppendText(addr.ToString());\n        }\n\n        //Automatically set the IP address\n        ips = addrs.Select(ip => ip.ToString()).ToArray();\n\n    }\n    catch (Exception e)\n    {\n        MessageBox.Show(e.Message);\n    }\n\n}\n\n\nprivate void StartServerButton_Click(object sender, RoutedEventArgs e)\n{\n     Response.StartListening(ips);\n}	0
13009688	13009661	In an interface: Specify implemented method must take a subtype of an interface?	interface IMapper<T> where T : IModel\n{\n    void Create(T model);\n}\n\n...\n\npublic class CustomerMapper : IMapper<Customer>\n{\n    public void Create(Customer model) {}\n}	0
22362615	22362397	How to compress last modified file in C#	string lastModified = Directory.EnumerateFiles(path)\n                               .OrderBy(f => File.GetLastWriteTime(f))\n                               .Last();	0
5474919	5468870	Disabling alert window in WebBrowser control	WebBrowser1.ScriptErrorsSuppressed = true;	0
2109424	2108616	Validation-Textboxes allowing only decimals	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        // allows 0-9, backspace, and decimal\n        if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))\n        {\n            e.Handled = true;\n            return;\n        }\n\n        // checks to make sure only 1 decimal is allowed\n        if (e.KeyChar == 46)\n        {\n            if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)\n                e.Handled = true;\n        }\n    }	0
6569113	6568949	Change windows Culture Settings or define new using C#	dateString = "Sun 15 Jun 2008 8:30 AM -06:00";\nformat = "ddd dd MMM yyyy h:mm tt zzz";\ntry {\n    result = DateTime.ParseExact(dateString, format, provider);\n    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());\n}\ncatch (FormatException) {\n    Console.WriteLine("{0} is not in the correct format.", dateString);\n}	0
10079498	10079428	Converting from List<float> to int	// The first [0] indicates the index of the nested list within MainFocallengthList\n// The second [0] indicates the index of the item that you want in the nested list\nint zComponent = (int)(MainFocallengthList[0][0])	0
27477915	26836585	C# Regex find line that are not commented	public static readonly string BLOCK_COMMENTS = @"/\*(.*?)\*/";\npublic static readonly string LINE_COMMENTS  = @"--[^@](.*?)\r?\n";\npublic static readonly string STRINGS        = @"""((\\[^\n]|[^""\n])*)""";\n\nstring sWithoutComments = Regex.Replace(textWithComments.Replace("'", "\""), ServerConstant.BLOCK_COMMENTS + "|" + ServerConstant.LINE_COMMENTS + "|" + ServerConstant.STRINGS,\n                me =>\n                {\n                    if (me.Value.StartsWith("/*") || me.Value.StartsWith("--"))\n                        return me.Value.StartsWith("--") ? Environment.NewLine : "";\n                    return me.Value;\n                },\n                RegexOptions.Singleline);	0
22744532	22744368	C# Hashtable contains byte array value	//suppose this is the byte array you're looking for:\nbyte[] b = new byte[] { 1, 3, 5 };\n\nbool exists = myHashtable.Values.OfType<byte[]>().\n    ToList().Exists(c => c.SequenceEqual(b));	0
8567249	8567059	C# - Serializing Packets Over a Network	message MyMessage {\n    required int32 number = 1;\n}	0
7957177	7950994	Want to place data files for WinForm app in folder and get its path in code	string appPath = Path.GetDirectoryName(Application.ExecutablePath);\n\n    System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(appPath);\n    System.IO.DirectoryInfo directoryInfo2 = System.IO.Directory.GetParent(directoryInfo.FullName);\n\n    string path = directoryInfo2.FullName + @"\data";	0
18941135	18940974	Download multiple file from website, how to handle ctrl+c correctly	static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)\n{\n    try\n    {\n        Interlocked.Increment(ref globalStopFlag);\n\n        Console.ForegroundColor = ConsoleColor.Yellow;\n        Console.WriteLine("Program interrupted..deleting corrupted file");\n        Console.ResetColor();\n        if (File.Exists(fileInProgress))\n        {\n            while (IsFileLocked(fileInProgress))\n            {\n                System.Threading.Thread.Sleep(1000);\n            }\n            File.Delete(fileInProgress);\n        }\n    }\n    catch\n    {\n        Console.WriteLine("Error occured.");\n    }\n}\n\nvoid SomeDownloadFunction()\n{\n   using (somefile)\n   {\n     while (!downloadFinished)\n    {\n        long doINeedToStop = Interlocked.Read(ref   globalStopFlag)\n\n        if (doINeedToStop != 0)\n          return;\n\n        //Download the next set of packets and write them to somefile\n    }\n   }\n}	0
11802084	11802006	How to add 2 decimal values and add it into the new column of a DataSet?	// Create total column.\nDataColumn totalColumn = new DataColumn();\ntotalColumn.DataType = System.Type.GetType("System.Decimal");\ntotalColumn.ColumnName = "total";\ntotalColumn.Expression = "AmountSold + AmountUpgraded";\n\n// Add columns to DataTable.\n...\ntable.Columns.Add(totalColumn);	0
2270508	2270435	Limit on number of items in list box in WinForms	for (int i = 0; i < 10000; i++)\n{\n     listBox1.Items.Add("item:" + i.ToString());\n}	0
12383657	12382898	How do I check the state of a thread	if ((t.ThreadState & ThreadState.Running) == ThreadState.Running) { ...	0
32717899	32717827	How I can create a directory?	String directoryToCreate = @"C:\temp";\n\n  if (!Directory.Exists(directoryToCreate))\n    Directory.CreateDirectory(directoryToCreate);	0
25681941	25681773	How to change the connection string on another computer?	Data Source=(local)\yourInstanceName	0
14382254	14381485	dhtmlxScheduler for ASP.NET lightbox and server side controller	Scheduler.Lightbox.SetExternalLightboxForm("formName.aspx")	0
16069223	16045120	WCF Rest Change name of root return element	return new XElement("ProjectId", Guid.Empty);	0
7105867	7105769	How to remove the DataTable's Row without using loops?	DataRow[] rows = DTItem.Select(" SeqNo = " + SeqNo );\nrows[0].Delete();	0
921343	921271	validation for custom list sharepoint	public override void ItemAdding(SPItemEventProperties properties)\n{\n    base.ItemAdding(properties);\n\n    // only perform if we have an Email column\n    if (properties.AfterProperties["Email"] != null)\n    {\n        // test to see if the email is valid\n        if (!IsValidEmailAddress(properties.AfterProperties["Email"].ToString()))\n        {\n            // email validation failed, so display an error\n            properties.Status = SPEventReceiverStatus.CancelWithError;\n            properties.Cancel = true;\n            properties.ErrorMessage = "Please enter a valid email address";\n\n        }\n    }\n\n\n}	0
15101094	11190152	Joining two IQueryable variables of different types together using LINQ	var v_res = (from s in db.V_CMUCUSTOMER\n            select new { custName = s.customer_name custAddress = s.address}).ToList();\n\n--Values from table less values from view\nvar res = (from s in db.CMUCUSTOMERs\n          where !(from v in v_res\n            select v.ID).Contains(s.ID)\n          select new { custName = s.customer_name custAddress = s.address }).ToList();\n\n--join table and view values into one variable\nvar res_v_res = v_res.Union(res);	0
1331398	1331343	Replace nested ForEach with Select if applicable	var foos =\n    from dllFile in Directory.GetFiles(path, "*.dll")\n    from type in Assembly.LoadFrom(dllFile).GetTypes()\n    where !type.IsInterface && typeof(IFoo).IsAssignableFrom(type)\n    select (IFoo) Activator.CreateInstance(type);\n\nreturn foos.ToDictionary(foo => foo.Name, foo => foo.GetType());	0
24519633	24518740	Spreadsheetgear set data flags for specific column?	IRange.NumberFormat = "@"	0
11947080	11947035	How to add querystring for specific URL which match a controller in Mvc?	Url.Action( "Get", "People", new { id = 7 })	0
1172899	1172706	What is the best data structure for tree-like data of fixed depth in C#?	class TreeNode\n{\n  private string _name;\n  private int _someNumber;\n  private int _uniqueId;\n  private List<TreeNode> _childNodes;\n\n  public string Name{get{return _name;}}\n  public int SomeNumber{get{return _someNumber;}}\n  public int UniqueId{get{return _uniqueId;}}\n  public List<TreeNode> ChildNodes{get{return _childNodes;}}\n\n  public void TreeNode(string name, int someNumber, int uniqueId)\n  {\n    _name=name;\n    _someNumber=someNumber;\n    _uniqueId = uniqueId;\n    _childNodes = new List<TreeNode>();\n  }\n\n  public void AddNode(TreeNode node)\n  {\n    _childNodes.Add(node);\n  }\n\n  // other code for deleting, searching, etc.\n}	0
29482146	29482106	Convert an array of image physical paths on server to array of urls	string[] imagePaths = Directory.GetFiles(outputImgPath,"*.png");\nimagePaths.Select(x => string.Format("http://DOMAIN/Path/{0}" , Path.GetFileName(x)))	0
2635791	2635618	parse XML from string	var r = System.Xml.XmlReader.Create(new System.IO.StringReader("<Test> Result : this is the result</Test>"))\nwhile (r.Read()) {\n   if (r.NodeType == XmlNodeType.Element && r.LocalName == "Test") {\n     Console.Write(r.ReadElementContentAsString());\n   }\n}	0
27467077	27462532	How to reload or refresh a Windowsphone User Control in c#?	(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/MyProjectName;component/MyFolderName/MyPage.xaml", UriKind.Relative));	0
1295080	1294819	Can I convert the floating part of a double into an integer (without using string conversions)?	decimal d = (decimal)7.2828;\n       int val = decimal.GetBits(d - decimal.Truncate(d))[0];	0
6668837	6668500	Getting the helpstring attribute applied to C# properties exposed via COM interfaces	using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\n\nnamespace ClassLibrary1 {\n    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsDual)]\n    public interface IFoo {\n        int property {\n            [Description("prop")]\n            get;\n            [Description("prop")]\n            set;\n        }\n    }\n}	0
3885356	3885275	build .net solution from batch file	msbuild MySolution.sln /p:Configuration=Release /p:Platform="Any CPU"	0
21396350	21396341	MVC VaryByHeader User-Agent on All Actions for a Controller	public class CachingFilterAttribute : ActionFilterAttribute\n{\n  public override void OnActionExecuting(ActionExecutingContext \n    filterContext)\n  {\n    // set VaryByHeaders the way you need\n  }\n }\n\n [CachingFilter]\n public MyController : Controller...	0
11906128	11906067	Are named arguments part of a method's signature? How and why?	interface IFoo\n{\n    public int M(int x, int y);\n}\n\npublic class Foo : IFoo\n{\n    public int M(int y, int x)\n    {\n        return x - y;\n    }\n}\n\n...\n\nFoo foo = new Foo();\nIFoo ifoo = foo;\nConsole.WriteLine(foo.M(x: 10, y: 3)); // Prints 7\nConsole.WriteLine(ifoo.M(x: 10, y: 3)); // Prints -7	0
5489355	5489273	How do I disable the horizontal scrollbar in a Panel	panel.AutoScroll = true;\npanel.HorizontalScroll.Enabled = false;\npanel.HorizontalScroll.Visible = false;	0
5738397	5738348	display additional data to table fields - entity framework 4	//Create  CallViewModel contains ReasonName & CompanyName\n    public class CallViewModel\n    {\n        public int id { get; set; }\n        public string Text{ get; set; }\n        public string ReasonName { get; set; }\n        public string CompanyName { get; set; }\n    }\n\npublic List<CallViewModel> YourMethid()\n{\n    using (Entities _entities = new Entities())\n    {\n        var result = (from s in _entities.Call.Include("Reason").Include("Company")\n                      select new CallViewModel\n                          {\n                              id = s.id,\n                              Text = s.Text,\n                              CompanyName = s.Company.name,\n                              ReasonName = s.Reason.name\n                          }).ToList();\n        return result;\n    }\n}	0
32828944	32826964	Byte array image crop performance issue	private static unsafe void Crop(byte* src, byte* dst, Rectangle rSrc, Rectangle rDst)\n{\n    int* pDst = (int*)dst, pSrc = (int*)src + (rDst.Y * rSrc.Width + rDst.X);\n    int srcSkip = rSrc.Width - rDst.Width;\n    int rowCount = rDst.Height, colCount = rDst.Width;\n    for (int row = 0; row < rowCount; row++)\n    {\n        for (int col = 0; col < colCount; col++) *pDst++ = *pSrc++;\n        pSrc += srcSkip;\n    }\n}	0
27515302	27512205	how to open multiple urls from richtextbox	private void button1_Click(object sender, EventArgs e)\n{\n    foreach (string item in richTextBox1.Lines)\n    {\n        if (!string.IsNullOrEmpty(item))\n        {\n            ProcessStartInfo startInfo = new ProcessStartInfo();\n            startInfo.FileName = "firefox.exe";\n            startInfo.Arguments = "-new-tab " + item;\n            Process.Start(startInfo); \n        }\n    }\n}	0
2377709	2372807	C# Regex parsing HTML	string input = "<tr><TD><FONT size=\"2\">My Value 1</FONT></TD></tr>";\n string pattern = @"<[^>]*?>";\n string output = Regex.Replace(input, pattern, ""); //My Value 1	0
13927846	13927715	Setting A particular Day in a date	DateTime todayDate = DateTime.Now;\nDateTime after3MonthDate = todayDate.AddMonths(3);\n//Set First Day of Month\nafter3MonthDate = new DateTime(after3MonthDate.Year, after3MonthDate.Month, 1);	0
2813601	2811855	Make a usable Join relationship with LINQ on top of a database CSV design error	var newpersons =\n    data.Persons.Select(p => new\n        {\n          Id = p.Id,\n          Name = p.Name,\n          ArticleIds = p.CsvArticleIds.Substring(1, p.CsvArticleIds.Length -2).Split(',').ToList()\n        });	0
14895211	14893883	Remove prefix from a namespace of a xsd file	xsdString.Replace("xmlns:bb=", "xmlns=").Replace("<bb:", "<").Replace("</bb:", "</")	0
13258519	13253930	Batch Grid cell takes DataValueField from DropDownList when cell leaves edit mode	columns.ForeignKey(p => p.EmployeeID, (System.Collections.IEnumerable)ViewData["employees"], "EmployeeID", "EmployeeName");	0
32435008	32229375	How to start background task at boot - Windows Store app	SystemConditionType.SessionConnected	0
13588393	13588185	Deserialize JSon string using JSON.NET	var obj = (JObject)JsonConvert.DeserializeObject(json);\n\nvar dict = obj.First.First.Children().Cast<JProperty>()\n            .ToDictionary(p => p.Name, p =>p.Value);\n\nvar dt =  (string)dict["c"];\nvar d = (double)dict["g"];	0
32674370	32674312	Retrieve paged results using Linq	mycontext.mytable\n    .OrderBy(item=>.item.PropertyYouWantToOrderBy)\n    .Skip(HowManyYouWantToSkip)\n    .Take(50);	0
23505566	23505402	Asp.net redirect with a ID	ASP.NET HTTP GET request with parameters	0
21325753	21325661	Convert image path to base64 string	using (Image image = Image.FromFile(Path))\n    {                 \n        using (MemoryStream m = new MemoryStream())\n        {\n            image.Save(m, image.RawFormat);\n            byte[] imageBytes = m.ToArray();\n\n            // Convert byte[] to Base64 String\n            string base64String = Convert.ToBase64String(imageBytes);\n            return base64String;\n        }                  \n    }	0
3870243	3870215	Data binding on combo box	cmbPaidBy.DataSource = new BindingSource(_persons, null); \ncmbPaidBy.DisplayMember = "Value"; \ncmbPaidBy.ValueMember = "Key";	0
34442141	34439515	EF inserts a DB generated key, ignoring DatabaseGeneratedOption.None	public class Employee : INotifyPropertyChanged\n{\n    private int _employeeID;\n    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]\n    public int EmployeeID\n    {\n        get { return _employeeID; }\n        set\n        {\n         //Code omitted  \n        }\n    }	0
22711288	22709450	Edit RichTextBox programmatically without losing formatting	richTextBox1.SelectionStart = 20;\n    richTextBox1.SelectionLength = 120;\n    richTextBox1.Cut();	0
29834631	29833876	Assign Selected Value in DropDown from Variable	for (int i = 1; i <= totalPages; i++)\n{\n    PageDdl.Items.Add(new ListItem() { Text = i.ToString(), Selected = i == Convert.ToInt32(page) });\n}	0
28511597	28499186	NullValueHandling setting for a class on JSON.NET by JsonConverter attribute (for Azure DocumentDb)	JsonConvert.DefaultSettings = () => new JsonSerializerSettings\n    {\n        NullValueHandling = NullValueHandling.Ignore\n    };	0
19819750	19819612	Pass block of code as parameter and execute in try catch	// method definition...\nT ExecuteInTryCatch<T>(Func<T> block)\n{\n    try\n    {\n        return block();\n    }\n    catch (SomeException e)\n    {\n        // handle e\n    }\n}\n\n// using the method...\nint three = ExecuteInTryCatch(() => { return 3; })	0
23550256	23549501	Mongo DB C#, query with interface	public static IObjectWithID FindById<T>(MongoCursor cursor, ObjectId id) where T: IObjectWithID\n    {\n        var query = Query<T>.Where(e => e.Id == id);\n        var item = cursor.Collection.FindOneAs<T>(query);\n\n        return item;\n    }	0
14585160	14584672	Printing html file with pagebreaks	.page-break { page-break-before: always; }	0
9206996	9189200	Exporting Data Table to Excel using OLEDB throws too many fields defined error	public void CreateCSVFile(System.Data.DataTable dt, out StringWriter stw)\n        {\n            stw = new StringWriter();\n            int iColCount = dt.Columns.Count;\n            for (int i = 0; i < iColCount; i++)\n            {\n                stw.Write(dt.Columns[i]);\n                if (i < iColCount - 1)\n                {\n                    stw.Write(",");\n                }\n            }\n            stw.Write(stw.NewLine);\n            foreach (DataRow dr in dt.Rows)\n            {\n                for (int i = 0; i < iColCount; i++)\n                {\n                    if (!Convert.IsDBNull(dr[i]))\n                    {\n                        stw.Write(dr[i].ToString());\n                    }\n                    if (i < iColCount - 1)\n                    {\n                        stw.Write(",");\n                    }\n                }\n                stw.Write(stw.NewLine);\n            }\n        }	0
8923897	8911603	Running a unit test with mocked EPiServer properties fails	Global.EPConfig["EPfEnableFriendlyURL"]	0
33279774	33279676	two string variables compared against a private dictionary that returns a boolean value c#	public bool Authenticate()\n    {\n        Console.WriteLine("Please enter a username");\n        string inputUsername = Console.ReadLine();\n        Console.WriteLine("Please enter your password");\n        string inputPassword = Console.ReadLine();\n        return dictionary.ContainsKey(inputUsername) && dictionary[inputUsername] == inputPassword;\n    }	0
29716550	29714625	AJAX rating control inside update panel leads to reload the complete page	ChildrenAsTriggers="True"	0
28662452	28660520	Apply back folder links in Urls	new Uri("%YourUrl%).AbsoluteUri	0
24806820	24805933	XSLT to test a condition for all children without using foreach	...select="Students[Student[contains(@id, '2')]]"	0
26853131	26851214	Including an embedded resource in a compilation made by Roslyn	const string resourcePath = @"C:\Projects\...\Properties\Resources.resources";\nvar resourceDescription = new ResourceDescription(\n                "[namespace].Resources.resources",\n                () => File.OpenRead(resourcePath),\n                true);\n\nvar result = mutantCompilation.Emit(file, manifestResources: new [] {resourceDescription});	0
30456453	30456362	return message with parameter in javascript	function confirmDeletion(id) {\n  return confirm("Your message here: " + id);\n}	0
970239	970196	How to get position inside a select statement	var res = b.Select((l, i) => \n          new MyClass { IsFirst = (i == 0), IsLast = (i == b.Count-1) });	0
13676463	13676334	How to enable auto scroll?	public Form1()\n{\nInitializeComponent();\n\nPopulatePictures();\n}\n\nprivate void PopulatePictures()\n{\nthis.AutoScroll = true;\n\nstring[] list = Directory.GetFiles(@"C:\\Users\\Public\\Pictures\\Sample Pictures", "*.jpg");\nPictureBox[] picturebox= new PictureBox[list.Length];\nint y = 100;\n  for (int index = 0; index < picturebox.Length; index++)\n  {\n  picturebox[index] = new PictureBox();\n  this.Controls.Add(picturebox[index]);\n  picturebox[index].Location=new Point(index * 120, y);\n  if(x%12 == 0)\n  y = y + 150;\n  picturebox[index].Size = new Size(100,120);\n  picturebox[index].Image = Image.FromFile(list[index]);\n  }\n}	0
20013854	20013167	Global access, XML File (Setting file) values	public static class MyStaticClass\n{\n    //this is where we store the xml file line after line\n    private static List<string> _xmlLines;\n\n    //this is the class' static constructor\n    //this code will be the first to run (you do not have to call it, it's automated)\n    static MyStaticClass()\n    {\n        _xmlLines = new List<string>();\n\n        using (System.IO.StreamReader xml = new System.IO.StreamReader("yourFile.xml"))\n            {\n                string line = null;\n                while ((line = xml.ReadLine()) != null)\n                {\n                    _xmlLines.Add(line);\n                }\n            }\n            //remember to catch your exceptions here\n    }\n\n    //this is the get-only auto property\n    public static List<string> XmlLines\n    {\n        get\n        {\n            return _xmlLines;\n        }\n    }\n}	0
18590169	18589930	c# xml:get all atributes from file,but have add additional elements	var modes = XDocument.Load(fname)\n            .Descendants("Mode")\n            .Select(m => new\n            {\n                Name = m.Attribute("Name").Value,\n                ClassTypes = m.Elements().ToDictionary(e=>e.Name.LocalName,e=>e.Value)\n            })\n            .ToList();	0
1134335	1134047	How can I get a list of all of the available print/fax drivers	foreach (String printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)\n{\n    //Do your stuff\n}	0
17630082	17630012	Load libraries from app.config	var assembly = Assembly.LoadFrom("selected_math_library.dll");\nvar types = assembly.GetTypes();\n\nvar mathType = (from type in types\n                      where type.GetInterface("IMath") != null && !type.IsAbstract\n                      select type).ToList();\n\nif (mathType.Count > 0)\n{\n    IMath math = (IMath)Activator.CreateInstance(mathType);\n    // call methods from math\n\n}	0
19850746	19847107	Using Base Pointers with Offset to Read Process Memory	public partial class MainForm : Form\n{\n\n    Process myProcess = Process.GetProcessesByName("ffxiv").FirstOrDefault();\n\n    public MainForm()\n    {\n        InitializeComponent();\n    }\n\n    private void startButton_Click(object sender, EventArgs e)\n    {\n        int bytesRead;\n\n        IntPtr baseAddress = myProcess.MainModule.BaseAddress;\n        Console.WriteLine("Base Address: " + baseAddress);\n\n        IntPtr firstAddress = IntPtr.Add(baseAddress, 0xF8BEFC);\n        IntPtr firstAddressValue = (IntPtr)BitConverter.ToInt32(MemoryHandler.ReadMemory(myProcess, firstAddress, 4, out bytesRead), 0);\n        IntPtr finalAddr = IntPtr.Add(firstAddressValue, 0x1690);\n        Console.WriteLine("Final Address: " + finalAddr.ToString("X"));\n\n        byte[] memoryOutput = MemoryHandler.ReadMemory(myProcess, finalAddr, 4, out bytesRead);\n\n        int value = BitConverter.ToInt32(memoryOutput, 0);\n        Console.WriteLine("Read Value: " + value);\n    }\n}	0
18625016	18624561	How to parse deep XML values with C#	var itemKind = "Wanted";\n        var searchPhrase = "SomeSearchString";\n        var doc = XDocument.Load(filename);\n        var matches = doc.Descendants("item")\n            .Where(x => x.Attribute("itemkind") != null &&\n                x.Attribute("itemkind").Value == itemKind &&\n                x.Descendants("phrase").FirstOrDefault() != null &&\n                x.Descendants("phrase").FirstOrDefault().Value == searchPhrase)\n        .SelectMany(x => x.Descendants("action"));	0
11835630	11832959	How do I set variables in an SSIS package using variables that are set from a Environment Variable Configuration?	Variable v = null;\nv = pkg.Variables.Add("OutputFolder", false, "Template", String.Empty);\nv.EvaluateAsExpression = true;\nv.Expression = pkg.Variables["Template::FolderRoot"].Value + "\\Output\\";	0
20192088	20160872	ogg to mp3 using NAudio MFT	MediaFoundationInterop.Startup()	0
25963444	25960934	Serializing a Dictionary to XML	Dictionry<string, string> tags = SomeMethod();\n\nmessageBody.MessageBodyXmlBodyTagFields = tags\n      .Select(kv => new MessageBodyXmlBodyTagFields   \n         { PhoneNumber = kv.Key, Message = kv.Value })\n      .ToArray();	0
3843736	3843484	Processing unprocessed enter key c#	private void Form1_Load(object sender, EventArgs e)\n{\n    AssignHandler(this);\n}\n\nprotected void HandleKeyPress(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar == (char)Keys.Enter && (sender != this.textBoxToIgnore || sender ! this.gridViewToIgnore))\n    {\n        PlaySound();  // your error sound function\n        e.Handled = true;\n    }\n}\n\npublic void AssignHandler(Control c)\n{\n    c.KeyPress += new KeyPressEventHandler(HandleKeyPress);\n    foreach (Control child in c.Controls)\n    {\n        AssignHandler(child);\n    }\n}	0
5281954	5281809	Change label text in Static void C#	MainForm.changeText(...)	0
15558971	15557646	trouble setting values to a collection in an abstract class	if (nullableType == typeof(List<string>))\n{\n    ((List<string>)(prop.GetValue(this, null))).Add(value as string);\n}	0
4001197	3966670	Custom Editor for a Boolean Property in a PropertyGrid (C#)	bool flag = gridEntryFromRow.NeedsDropDownButton | gridEntryFromRow.Enumerable;	0
894832	894821	Selecting a TreeView Item without invoking SelectedItemChanged?	bool updatingSelected;\n\nvoid SomeHandler(object sender, EventArgs args) { // or whatever\n  if(updatingSelected) return;\n\n  //...\n}\n\nvoid SomeCode() {\n    bool oldFlag = updatingSelected;\n    updatingSelected = true;\n    try {\n       // update the selected item\n    } finally {\n       updatingSelected = oldFlag;\n    }\n}	0
16015913	16015837	Async await - it is the right Idea to avoid a blocking UI?	public async Task StartLoading(string[] files)\n{\n    return Task.Run(() =>\n    {            \n        foreach (string file in files)\n        {\n            Stopwatch swatch = new Stopwatch();\n            swatch.Start();\n            System.Threading.Thread.Sleep(5000);\n            FileInfo finfo = new FileInfo(file);\n            using (ExcelPackage package = new ExcelPackage(finfo))\n            {\n            // very long operation\n            }\n        } // For Each\n    };\n} // StartLoading	0
25038242	25037990	Adding XML Attribute to a WCF Service	[DataContract]\npublic class FruitCrate\n{\n  [XmlAttribute]\n  public int NumberOfFruits;\n\n  [DataMember(Name = "Cats")]\n  public CatContainer CatContainer;\n}\n\n[DataContract]\npublic class Cats2009\n{\n    [DataMember]\n    public string Name;\n}\n[DataContract]\npublic class CatContainer\n{\n    [XmlAttribute]\n    public string MomName;\n\n    [DataMember]\n    public List<Cats2009> Cats;\n}	0
1492232	1478353	How to clear datepicker control in silverlight?	datePicker1.ClearValue(DatePicker.SelectedDateProperty);	0
6029544	6029498	Getting Recent folders and Recent files in Windows XP	System.Environment.GetFolderPath(Environment.SpecialFolder.Recent)	0
24250313	24249863	Creating a mailto link in codebehind for a dynamically generated gridview	BoundField hlName = new BoundField();\n\n        hlName.DataField= dt.Columns[1].ToString();\n        hlName.DataFormatString= "<a href=\"mailto:{0}\">{0}</a>";\n        hlName.HtmlEncodeFormatString = false;	0
1120126	1119451	How to tell if a line intersects a polygon in C#?	public static PointF FindLineIntersection(PointF start1, PointF end1, PointF start2, PointF end2)\n{\nfloat denom = ((end1.X - start1.X) * (end2.Y - start2.Y)) - ((end1.Y - start1.Y) * (end2.X - start2.X));\n\n//  AB & CD are parallel \nif (denom == 0)\nreturn PointF.Empty;\n\nfloat numer = ((start1.Y - start2.Y) * (end2.X - start2.X)) - ((start1.X - start2.X) * (end2.Y - start2.Y));\n\nfloat r = numer / denom;\n\nfloat numer2 = ((start1.Y - start2.Y) * (end1.X - start1.X)) - ((start1.X - start2.X) * (end1.Y - start1.Y));\n\nfloat s = numer2 / denom;\n\n    if ((r < 0 || r > 1) || (s < 0 || s > 1))\nreturn PointF.Empty;\n\n// Find intersection point\nPointF result = new PointF();\nresult.X = start1.X + (r * (end1.X - start1.X));\nresult.Y = start1.Y + (r * (end1.Y - start1.Y));\n\nreturn result;\n }	0
11591950	11591837	c# load an image from URL into picturebox	protected void Page_Load(object sender, EventArgs e) {\n    pictureBox1.ImageLocation = "http://www.jmorganmarketing.com/wp-content/uploads/2010/11/image4.jpg"\n}	0
27341144	27341019	combine all json paths in string c#	using System;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\nusing System.Text;\n\npublic class Program\n{\n    public static void Main()\n    {\n            var json = @"\n{  \n   ""root"":{  \n      ""first"":{  \n         ""first1"":{  \n            ""value"":""1""\n         },\n         ""first2"":{  \n            ""value"":""2""\n         },\n         ""first3"":{  \n            ""value"":""3""\n         }\n      }\n    }\n}";\n\n        var jobject = JObject.Parse (json);\n        var sb = new StringBuilder ();\n\n        RecursiveParse (sb, jobject);\n\n        Console.WriteLine (sb.ToString());\n    }\n\n    public static void RecursiveParse(StringBuilder sb, JToken token)\n    {\n        foreach (var item in token.Children()) {\n            if (item.HasValues)\n            {\n                RecursiveParse (sb, item);\n            } else {\n                sb.AppendLine (item.Path);\n            }\n        }\n\n    }   \n}	0
1148524	1148200	Alternatives to NativeWindow for subclassing	protected override void WndProc(ref Message m) {\n  base.WndProc(ref m);\n  if (m.Msg == 0x82) this.ReleaseHandle();\n}	0
1816169	1214026	GnuPG Wrapper with C#	GnuPG gpg = new GnuPG();\n\n  gpg.Recipient = "myfriend@domain.com";\n  FileStream sourceFile = new FileStream(@"c:\temp\source.txt", FileMode.Open); \n  FileStream outputFile = new FileStream(@"c:\temp\output.txt", FileMode.Create);\n\n  // encrypt the data using IO Streams - any type of input and output IO Stream can be used\n  gpg.Encrypt(sourceFile, outputFile);	0
12418499	12403178	How to get columns of both datatable after innerjoining them using linq	DataTable targetTable = dsResults.Tables[0].Clone();\n        var dt2Columns = dsResults.Tables[1].Columns.OfType<DataColumn>().Select(dc =>\n            new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping));\n        targetTable.Columns.AddRange(dt2Columns.ToArray());\n        var rowData =\n            from row1 in dsResults.Tables[0].AsEnumerable()\n            join row2 in dsResults.Tables[1].AsEnumerable()\n                on row1.Field<decimal>("RecordId") equals row2.Field<decimal>("RecordId2")\n            select row1.ItemArray.Concat(row2.ItemArray).ToArray();\n        foreach (object[] values in rowData)\n            targetTable.Rows.Add(values);	0
4735868	4735833	Porting C++ to C# - templates	return Factorial(N-1).Value;	0
3756101	3756079	How to disconnect an anonymous event?	Binding bndTitle = this.DataBindings.Add("Text", obj, "Title");\nEventHandler handler = (sender, e) =>\n{\n    e.Value = "asdf" + e.Value;\n};\n\nbndTitle.Format += handler;\n// ...\nbndTitle.Format -= handler;	0
11491478	11491463	formatting comma separated parameter in vs2010	Tools > Options > Text Editor > C# > Formatting	0
10110912	10110872	c# list<int> how to insert a new value in between two values	List<int> initializers = new List <int>();\n\ninitializers.Add(1);\ninitializers.Add(3);\n\nint index = initializers.IndexOf(3);\ninitializers.Insert(index, 2);	0
18234393	18234223	IDisposable with Multiple Levels of Inheritance	class A : IDisposable\n{\n    public void Dispose() {\n      Dispose(true);\n      GC.SuppressFinalize(this); // <- May be excluded\n    }\n\n    protected virtual void Dispose(Boolean disposing)... // <- "disposing" recommended by Microsoft\n}\n\nclass B : A\n{\n    protected override void Dispose(Boolean disposing) {\n      // Dispose here all private resources of B\n      ...\n      base.Dispose(disposing);\n    }\n}\n\nclass C : B\n{\n    protected override void Dispose(Boolean disposing) {\n      // Dispose here all private resources of C\n      ...\n      base.Dispose(disposing);\n    }\n}	0
873742	873729	Watching Global Events created by a native process in a .NET process	bool createdNew;\nWaitHandle waitHandle = new EventWaitHandle(false,\n    EventResetMode.ManualReset, @"Global\MyEvent", out createdNew);\n// createdNew should be 'false' because event already exists\nThreadPool.RegisterWaitForSingleObject(waitHandle, MyCallback, null,\n    -1, true);\n\nvoid MyCallback(object state, bool timedOut) { /* ... */ }	0
9472961	9440015	Creating Zip without third party DLLs. Getting Part URI must start with a forward slash error	Uri partUri = PackUriHelper.CreatePartUri(new Uri(String.Concat(@".\", fileName), UriKind.Relative));	0
6506390	6504544	Passing array of strings from .c file to java dll via JNI	jobjectArray stringArray;\njString tmp;\nchar *stringA = "Test1";\nchar *stringB = "Test2";\njclass clsString; \njint size = 2;\n\nclsString = (*env)->FindClass(env, "java/lang/String");\nstringArray = (*env)->NewObjectArray(env, size, clsString, 0);\n\ntmp = (*env)->NewStringUTF(env, stringB);\n(*env)->SetObjectArrayElement(env, stringArray, 0, tmp);\n\ntmp = (*env)->NewStringUTF(env, stringA);\n(*env)->SetObjectArrayElement(env, stringArray, 1, tmp);\n\nobj = (*env)->NewObject(env, jClass, MID_init, stringArray);	0
3254772	3254680	C# String splitting - breaking string up at second comma	string[] parts =\n  Regex.Matches(myarray[0], "([^,]*,[^,]*)(?:, |$)")\n  .Cast<Match>()\n  .Select(m => m.Groups[1].Value)\n  .ToArray();	0
20586483	20586337	Load image from content as IImageProvider	string imageFile = @"images\background.jpg"\nvar file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);\nblendFilter.ForegroundSource = new StorageFileImageSource(file))	0
11066164	11065094	How to define a Structuring Element using C#?	object[,] myArray = new object[30,105];\nmyArray[0,0] = 1;	0
28051417	28049183	populate database from sql server generated script	using (var conn = new SqlConnection("data source=MySource; initial catalog=MYNewDB;persist security info=True;user id=MyUser;password=MyPassword;multipleactiveresultsets=True; "))\n{\n   string script = File.ReadAllText(@"C:\Somewhere\...\script.sql");\n\n   // split script on GO command\n   IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);\n\n   conn.Open();\n   foreach (string commandString in commandStrings)\n   {\n      if (commandString.Trim() != "")\n      {\n         using (var command = new SqlCommand(commandString, conn))\n         {\n            command.ExecuteNonQuery();\n         }\n      }\n   }\n   conn.Close();\n}	0
11702307	11702277	How to minimize application to tray by using command line argument	Environment.CommandLine	0
23950440	23950015	How to save dynamic ListBox items to a text file WP8	\\Create file and save data\n  using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))\n            {\n                using (StreamWriter writer = new StreamWriter(stream))\n                {\n                    writer.WriteLine(1);\n                    writer.WriteLine("Hello");\n                }\n            }\n\n\\To read from the file\nusing (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))\n{\n    using (StreamReader reader = new StreamReader(stream))\n    {\n        int number = Convert.ToInt32(reader.ReadLine());\n        string text = reader.ReadLine();\n    }\n}	0
19111543	19108012	How to get leaf node from a nested collection using lamda expression	void FindLeaves(Parent p, ICollection<Child> leaves)\n{\n    if (current.Children != null) return;\n\n    var toVisit = new Stack<Child>(p.Children());\n\n    while (toVisit.Count > 0) {\n        var current = toVisit.Pop(); \n\n        foreach (var child in current.Children)\n        {    \n            if (child.Isleaf)\n                leaves.Add(child);\n            else\n                tovisit.Push(child);\n        }\n    }\n}	0
5190033	5113722	how to disable copy, Paste and delete features on a textbox using C#	int cusorposition = m_TextBox1.SelectionStart;\nif (TextBox1.Text[0] == ' ')\n{\n//Trim Spaces at beginning.\n      m_TextBox1.Text = m_TextBox1.Text.TrimStart(' ');\n      m_TextBox1.Text = m_TextBox1.Text.TrimEnd(' ');\n      m_TextBox1.SelectionStart = cusorposition ;\n}	0
6132797	6119852	Need suggestion on background worker	private void DoTheThing()\n    {\n        try\n        {\n            while (true)\n            {\n                TheThing e = new TheThing();\n                Thread t = new Thread(new ThreadStart(e.Run));\n                t.Start();\n                Thread.Sleep(1000);\n            }\n        }\n        catch (ThreadAbortException) { }\n        catch (Exception ex) { /* Whatever error handling you got */ }\n    }	0
31022222	31022157	How to set text of Button as ON and OFF on each click in winforms?	private void btnNotification_Click(object sender, EventArgs e)\n{\n    var btn = sender as Button;\n    if (btn != null)\n    {\n        if (btn.Text == "ON")\n        {\n            btn.Text = "OFF";\n            accept_notif = "0";\n        }\n        else if (btn.Text == "OFF")\n        {\n            btn.Text = "ON";\n            accept_notif = "1";\n        }\n    }\n}	0
30636337	30635412	Converting Data Trigger XAML to C#	Style style = new Style(typeof(Image));\n\n// Style Setter to handle 'false' case\nstyle.Setters.Add(new Setter(Image.SourceProperty, new BitmapImage(new Uri("Resources/image2.png", UriKind.Relative))));\n\n// DataTrigger to handle 'true' case\nDataTrigger dataTrigger = new DataTrigger();\ndataTrigger.Binding = new Binding("Value");\ndataTrigger.Value = true;\ndataTrigger.Setters.Add(new Setter(Image.SourceProperty, new BitmapImage(new Uri("Resources/image1.png", UriKind.Relative))));\nstyle.Triggers.Add(dataTrigger);\n\nthis.image.Style = style;	0
19934438	19934145	Unittesting a table to determine that there are more than one record	Assert.IsTrue(sqlContext.TableName.FirstOrDefault(row => row.PrimaryKey != null) != null);	0
6862308	6039041	XML Replace in c#	private void convertClubComp(XmlDocument doc)\n    {\n        XmlNode sessionNode = doc.SelectSingleNode("Session");\n        XmlNode playerNode = sessionNode.SelectSingleNode("Players").SelectSingleNode("Player");\n        XmlNode groupNode = playerNode.SelectSingleNode("Groups");\n\n        Console.WriteLine(playerNode.Name);\n\n        XmlNode clubsNode = doc.CreateElement("Clubs", "");\n        foreach (XmlNode child in groupNode.ChildNodes)\n        {\n            clubsNode.AppendChild(child.CloneNode(true));\n        }\n        foreach (XmlAttribute attribute in groupNode.Attributes)\n        {\n            clubsNode.Attributes.Append((attribute.Clone() as XmlAttribute));\n        }\n        playerNode.ReplaceChild(clubsNode, groupNode);\n        Console.WriteLine(clubsNode.FirstChild.FirstChild.Name);\n\n        Console.WriteLine("!" + playerNode.FirstChild.NextSibling.NextSibling.NextSibling.NextSibling.NextSibling.Name);\n\n    }	0
11535811	11535788	How to bind boolean to combo box	creStation.Seat = cbSeats.SelectedValue=="Yes";	0
8995421	8994287	Can not get address_component element from Google Geocoding API XML output with LINQ	var receivedXml = XDocument.Load("http://maps.googleapis.com/maps/api/geocode/xml?latlng=49.1962253,16.6071422&sensor=false");\nConsole.WriteLine(receivedXml.Root.Element("result").Elements("address_component").Count());\nConsole.WriteLine(receivedXml.Descendants("address_component").Count());	0
5002305	5002248	Binding Dropdownlist Values using Dictionery	ddlAccHD.DataSource = achID;\nddlAccHD.DataValueField = "Key";\nddlAccHD.DataTextField = "Value";\nddlAccHD.DataBind();	0
3805535	3791060	How to use ObjectQuery with Where filter separated by OR clause	ObjectQuery<DbDataRecord> query = query.Where("it.RouteID=1 OR it.RouteID=2");	0
29756166	29755791	By-request singleton initialization using IoC container in MVVM application	//only initialized when it's used\nprivate static Lazy<List<Meat>> meatList \n     = new Lazy<List<Meat>>(\n             () =>\n             {\n                 //load single list here\n             }\n     );\npublic List<Meat> MeatList { get{ return meanList.Value; } }	0
14530463	14406445	Looping over the messages in IBM MQ server	queue.Get(message);\nConsole.WriteLine("Message " + i + " got = " + message.ReadString(message.MessageLength));\nmGetMsgOpts.Options = MQC.MQGMO_WAIT | MQC.MQGMO_BROWSE_NEXT;	0
27800339	27799669	Force external process to redraw borders after SetWindowPos	ShowWindow(i, ShowWindowCommands.Normal);	0
19382776	19382659	Render Asp.net server controls dynamically	pnlContainer.Controls.Add(new Panel{ID = "test"});	0
16217700	16217568	How to refer to an object name through a variable?	Dictionary<string, ComboBox> comboBoxes = new Dictionary<string, ComboBox>();\n\n//Use the string you want to refer to the combobox and the combobox item itself\ncomboBoxes.Add("bcbsTreets", comboBox1); \n\n//Use the name as defined in the previous step to get the reference to the combobox and\n//set the text\ncomboBoxes["bcbsTreets"].Text = "whatever";	0
34031558	34031239	Get contiguous date ranges	public static List<DateRange> GetContiguousTimespans(List<DateRange> ranges)\n{\n    List<DateRange> result = new List<DateRange>();\n    ranges.Sort((a,b)=>a.Start.CompareTo(b.Start));\n    DateRange cur = ranges[0];\n\n    for (int i = 1; i < ranges.Count; i++)\n    {\n        if (ranges[i].Start <= cur.End)\n        {\n            if (ranges[i].End >= cur.End)\n                cur.End = ranges[i].End;\n        }\n        else\n        {\n            result.Add(cur);\n            cur = ranges[i];\n        }\n    }\n\n    result.Add(cur);\n\n    return result;\n}	0
10836386	10835869	how to design these codes in a more oop way?	NewRosterItem(RosterItem item)	0
34183745	34181667	Matrix3D for a positive rotation around z in WPF	Matrix3D mat = new Matrix3D(cos, sin, 0, 0, -sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);	0
20044188	20044032	C# windows 8 block style layout autosize	double actualItemHeight = this.Height/ 0.10;\ndouble actualItemWidth = this.Width/ 0.10;	0
8777374	8777149	DataSource remains unaltered after deleting rows in DataGridView	List<MyObject> data = dataGridView.DataSource as List<MyObject>;\ndata.Remove(objectToDelete);	0
19617587	19617395	ASP.NET MVC4 Setting up DB Context and Models	using (var d = new AutoDb())\n{\n    var user = d.SystemUsers.FirstOrDefault( u => u.email == email);\n    if (user != null && user.Password == crypto.Compute(password))\n    {\n        r = true;\n    }\n}	0
24177997	24177303	How can i filter/remove a line that a specific word is not exist in the line?	string[] words = { "testing", "world", "??????", "new", "hello", "test" };\n\nList<string> newText = new List<string>() {         \n    "This line dosent match",\n    "date1",\n    "",\n    "This line does match with the word: hello",\n    "date2",\n    "",\n    "This line dosent match either",\n    "date1",\n    "",\n    "This line does match with the word: world",\n    "date4",\n    "",\n};\n\nint i = 0;\n\nwhile (i < newText.Count)\n{            \n    // Get an array of words\n    string[] lineWords = newText[i].Split(' ');\n\n    if (lineWords.Intersect(words).Count() == 0)\n    {\n        // This line has no matching words. Remove 3 lines.\n        for (int n = 0; n < 3; n++)\n            newText.RemoveAt(i);\n    }\n    else\n    {\n        // This line has matching words. Move forward 3 lines.\n        i += 3;\n    }\n}\n\nforeach (string line in newText)\n    Console.WriteLine(line);	0
6512922	6512874	Optimized Insert Process in a database in asp.net c#	using (SqlConnection connection = new SqlConnection(\n           connectionString))\n{\n    SqlCommand command = new SqlCommand(queryString, connection);\n\n    //add parameters here\n\n    command.Connection.Open();\n    command.ExecuteNonQuery();\n}	0
33238457	33237459	pair radio buttons in seperate panels	RadioButton rb1 = new RadioButton { Text = "RB1" };\n        RadioButton rb2 = new RadioButton { Text = "RB2" };\n        RadioButtonGroup rgb = new RadioButtonGroup(rb1, rb2);\n\n        foreach (RadioButton rb in new [] { rb1, rb2 }) {\n            Form f = new Form { Text = rb.Text };\n            f.Controls.Add(rb);\n            f.Show();\n            rb.CheckedChanged += delegate {\n                MessageBox.Show(rb.Text + ": " + rb.Checked);\n            };\n        }\n\n\n\nprivate class RadioButtonGroup {\n    RadioButton[] radioButtons = null;\n    public RadioButtonGroup(params RadioButton[] radioButtons) {\n        this.radioButtons = radioButtons;\n        foreach (var rb in radioButtons) {\n            rb.AutoCheck = false;\n            rb.Click += rb_Click;\n        }\n    }\n\n    void rb_Click(object sender, EventArgs e) {\n        foreach (RadioButton rb in radioButtons)\n            rb.Checked = (rb == sender);\n    }\n}	0
5900274	5900197	ASP.net access control in FormView ItemTemplate	if (FormView1.CurrentMode == FormViewMode.ReadOnly)\n{\n\n  Panel pnl = (Panel)FormView1.FindControl("pnl");\n}	0
12381747	12377442	Couldn't find a ICreatesObservableForProperty for	RxApp.ConfigureServiceLocator(\n        (type, key) => Kernel.Get(type, key),\n        (type, key) => Kernel.GetAll(type, key),\n        (from, type, key) =>\n            {\n                var binding = Kernel.Bind(type /*this was from*/).To(from /*ditto*/);\n                if (key != null)\n                    binding.Named(key);\n            }\n        );	0
12779750	12766693	How to get error messages from NSIS to .NET	[DllImport("shell32.dll", SetLastError = True)]\nreturn: MarshalAs(UnmanagedType.Bool)\nstatic extern bool IsUserAnAdmin(void);	0
16485129	15972400	How to use tweetsharp.search?	var service = new TwitterService(consumerKey, consumerSecrete);\n        service.AuthenticateWith(token, tokenSecrete);\n        var options = new SearchOptions { Q = "vucic" };\n\n        var tweets = service.Search(options);\n\n        foreach (var tweet in tweets.Statuses)\n        {\n            Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);\n        }	0
27535003	27534691	Configuring custom TextWriterTraceListener to web.config	MyTextTraceListener myTraceListener = new MyTextTraceListener ("application.log");\n    Trace.Listeners.Add(myTraceListener);	0
25743567	25743439	linq-sql join two tables and select columns	var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();\nvar secondQuery = (from t in _maternalcarevaluedb.Value select t).ToList();\n\nvar result = (from s in firstQuery\njoin k in secondQuery\non s.MotherId equals k.MotherId\n where (DateTime)s.SecondVisit.Date == DateTime.Now.Date \n select s).ToList();	0
25151427	25151260	WPF how can I get the defined public variable of the parent to the child	var parentWindow = Window.GetWindow(ConfigUserControl) as MYWINDOWCLASS;\n\nif(parentWindow != null)\n{\n   //Can access UserMgr on parentWindow\n   parentWindow.fUserMgr \n}	0
21208501	21208387	MD5 hash for file in C#	hasher = new md5\nloop\n    read a block of the file\n    hasher.addblock(current block)\n    hasher2 = hasher.clone()\n    hasher.finish()\n    hasher = hasher2\nend loop	0
23443962	23443940	How to convert an array of signed bytes to float?	float num = 0;\n\nfor (int i = 0; i < sbytesArr.Length; i++)\n{\n     num = (num | sbytesArr[i]) << i * 4;\n}	0
856729	856723	Casting value to T in a generic method	if (typeof(T) == typeof(int)) return (T)(object)map.GetInt(key);	0
2104410	2096764	Separation of concerns - DAO, DTO, and BO	// UserService uses UserRepository internally + any additional business logic.\nvar service = new UserService();\nvar user = service.GetById(32);\n\nuser.ResetPassword();\nuser.OtherBusinessLogic("test");\nuser.FirstName = "Bob";\n\nservice.Save(user);	0
9031490	9029982	Is there a common .NET regex that can be used to match the following numbers?	// var xml = ** load xml string\nvar document = XDocument.Parse(xml);\n\nforeach(var i in document.Root.Elements())\n{\n    var num = ""; \n    var code = "";\n\n    if(i.Attributes("num").Length > 0)\n    {\n        Console.WriteLine("Num: {0}", i.Attributes("num")[0].Value);\n        Console.WriteLine("Code: {0}", i.Attributes("code")[0].Value);\n    }\n    else\n    {\n        Console.WriteLine("Num: {0}", i.Element("num").Value);\n        Console.WriteLine("Code: {0}", i.Element("code").Value);\n    }\n}	0
11197189	11197174	Will expressions break if it is unnecessary to continue?	textbox.Text	0
12352688	12352537	How to build a .NET interpreter (or how does Powershell work?)	private static void Main(string[] args)\n{\n  // Call the PowerShell.Create() method to create an \n  // empty pipeline.\n  PowerShell ps = PowerShell.Create();\n\n  // Call the PowerShell.AddScript(string) method to add \n  // some PowerShell script to execute.\n  ps.AddScript("$arr = 1.5,2.0"); # Execute each line read from prompt\n\n  // Call the PowerShell.Invoke() method to run the \n  // commands of the pipeline.\n  foreach (PSObject result in ps.Invoke())\n  {\n    Console.WriteLine(result.ToString());\n  } \n}	0
2245925	2245737	Cannot decrypt data with C# that was encrypted using PHP (Rijdael-128)	static string Decrypt() {            \n  byte[] keyBytes = Convert.FromBase64String("DMF1ucDxtqgxw5niaXcmYQ==");\n  byte[] iv = Convert.FromBase64String("GoCeRkrL/EMKNH/BYeLsqQ==");\n  byte[] cipherTextBytes = Convert.FromBase64String("UBE3DkgbJgj1K/TISugLxA==");\n\n  var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, IV = iv, KeySize = 128, Key = keyBytes, Padding = PaddingMode.Zeros};\n\n  using (var decryptor = symmetricKey.CreateDecryptor())\n  using (var ms = new MemoryStream(cipherTextBytes))\n  using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {\n    var plainTextBytes = new byte[cipherTextBytes.Length];\n    int decryptedByteCount = cs.Read(plainTextBytes, 0, plainTextBytes.Length);\n    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n  }\n}	0
10335018	10301727	Marshalling C++ pointer interface back though C# function call in a non default AppDomain	bool CreateInstanceInAppDomain(const char *pcAppDomainName)\n{\n    bool bRtn = false;\n\n    gcroot<String^> csStrAppDomainName (gcnew String(pcAppDomainName));\n    mAppDomain = AppDomain::CreateDomain(csStrAppDomainName);\n    delete csStrAppDomainName;\n    Object^ MyInternalObject = mAppDomain->CreateInstanceAndUnwrap("AssemblyName", "ClassNameSpace.MyInternalCSharpClass");\n    mInternalClassAccess = dynamic_cast<MyInternalCSharpClass^>(MyInternalObject);\n    if (mInternalClassAccess)\n    {\n        bRtn = true;\n    }\n\n    return bRtn;\n}	0
8447633	8447429	DropDownList in C# selects a default (1st) item after postback	ListItem li = new ListItem("Select region", "");\ncmbRegion.Items.Insert(0,li);	0
2819516	2817726	C#: Hook up all events from object in single statement	private void HookUpEvents()\n{\n  Type purchaseOrderType = typeof (PurchaseOrder);\n  var events = purchaseOrderType.GetEvents();\n  foreach (EventInfo info in events)\n  {\n    if (info.EventHandlerType == typeof(Kctc.Data.Domain.DomainObject.InvalidDomainObjectEventHandler))\n    {\n      info.AddEventHandler(_purchaseOrder, new Kctc.Data.Domain.DomainObject.InvalidDomainObjectEventHandler(HandleDomainObjectEvent));\n    }\n  }\n}	0
14367202	14366906	AutoMapper: Map IList in model to IEnumerable in viewModel	var grp = new Group {Permissions = new List<Permission>{new Permission{Name="Permission 1"}, \n                                                       {new Permission{Name="Permission 2"}}}};\n\nMapper.CreateMap<Permission, PermissionViewModel>();\n\nMapper.CreateMap<Group, GroupViewModel>();\n\n\nvar result = Mapper.Map<GroupViewModel>(grp);	0
7385772	7385730	MyAutoScaleFactor may cause a runtime exception because it is a field of a marshal-by-reference class	var scaleFactor = form.MyAutoScaleFactor;\n\nreturn new Size(bounds.Right - bounds.Left + (int)(scaleFactor.Width * 4),\n                bounds.Bottom - bounds.Top);	0
17504675	17504637	How is list size dynamic?	List<T>	0
15008496	15008308	How to execute a piece of code exactly once with multithreading in mind?	class Foo\n{\n    private static bool ShouldOnlyExecuteOnceExecuted = false;\n    private static readonly object Locker = new object();\n\n    public Foo(string bar)\n    {\n        SetShouldOnlyExecuteOnce(bar);\n    }\n\n    private void SetShouldOnlyExecuteOnce(string bar)\n    {\n        if(!ShouldOnlyExecuteOnceExecuted)\n        {\n            lock(Locker)\n            {\n                if(!ShouldOnlyExecuteOnceExecuted)\n                {\n                    ShouldOnlyExecuteOnce(bar);\n                    ShouldOnlyExecuteOnceExecuted = true;\n                }\n            }\n        }\n    }\n}	0
3322851	3320444	Excel Data using LinQ Intersecting	List<CircuitSet> results =\n(\n  from s in sourceTest\n  join t in targetTest\n  on s.Id equals t.Id\n  where s.Data == t.Data && s.ControlType == t.ControlType ...\n  select s\n).ToList();	0
24295447	24285863	how to get the label content from a list box	foreach (object item in taskslistBox.Items)\n{\n    var listBoxItem = taskslistBox.ItemContainerGenerator.ContainerFromItem(item);\n    var myContentPresenter = FindVisualChild<ContentPresenter>(listBoxItem);\n    var myDataTemplate = myContentPresenter.ContentTemplate;\n    var mydata = (Label)myDataTemplate.FindName("tasklabel", myContentPresenter);\n    var xmlElement = (XmlElement)mydata.Content;\n    MessageBox.Show("element " + xmlElement.InnerText);\n}	0
3701590	3701563	In C#, is there a clean way of checking for multiple levels of null references	if (person != null && person.Head != null && person.Head.Nose != null)\n{\n    person.Head.Nose.Sniff();\n}	0
26016508	25960713	Microsoft oauth screen is not resized during in WebBrowser control on WP device	display=touch	0
8852925	8852863	DataTable - foreach Row, EXCEPT FIRST ONE	foreach (DataRow row in m_dtMatrix.Rows)\n            {\n                if (m_dtMatrix.Rows.IndexOf(row) != 0)\n                {\n                    ...\n                }\n            }	0
30446844	30446310	Dynamically create charts with wpf toolkit	var barSeries = new BarSeries\n              {\n                            Title = "Fruit in Cupboard",\n                            ItemsSource = new[]\n                                              {\n                                                  new KeyValuePair<string, int>("TOR", 10),\n                                                  new KeyValuePair<string, int>("SOC", 15),\n                                                  new KeyValuePair<string, int>("BOS", 18),\n\n                                                  new KeyValuePair<string, int>("NON", 11)\n                                              },\n                            IndependentValueBinding = new Binding("Key"),\n                            DependentValueBinding = new Binding("Value")\n                        };\n\n    myChart.Series.Add(barSeries);	0
5567573	5567397	ASP.NET MVC 2 - Retrieving the selected value from a dropdownlist and a listbox	public ActionResult RecieveForm(FormCollection values)\n{\n   var dropdownSelectedvalue = values["nameofdropdown"];\n   ...\n   work with result\n   ...\n   return View()\n}	0
16366359	16366297	how to search the dataset for specific data	// Presuming the DataTable has a column named Date. \n  string expression = "Date = '1/31/1979' or OrderID = 2";\n  // string expression = "OrderQuantity = 2 and OrderID = 2";\n\n  // Sort descending by column named CompanyName. \n  string sortOrder = "CompanyName ASC";\n  DataRow[] foundRows;\n\n  // Use the Select method to find all rows matching the filter.\n  foundRows = table.Select(expression, sortOrder);	0
27176897	27174230	How to calculate the angle of a trajectory without knowing the velocity	float GetAngle(float height, Vector3 startLocation, Vector3 endLocation)\n    {\n        float range = Mathf.Sqrt(Mathf.Pow(startLocation.x - endLocation.x,2) + Mathf.Pow(startLocation.z - endLocation.z,2));\n        float offsetHeight = endLocation.y - startLocation.y;\n        float g = -Physics.gravity.y;\n\n        float verticalSpeed = Mathf.Sqrt(2 * gravity * height);\n        float travelTime = Mathf.Sqrt(2 * (height - offsetHeight) / g) + Mathf.Sqrt(2 * height / g);\n        float horizontalSpeed = range / TravelTime;\n        float velocity = Mathf.Sqrt(Mathf.Pow(verticalSpeed,2) +  Mathf.Pow(horizontalSpeed, 2));\n\n        return -Mathf.Atan2(verticalSpeed / velocity, horizontalSpeed / velocity) + Mathf.PI;\n    }	0
4625432	4625081	Import custom ascii format from file	Open [File]\nwhile not EOF\n  Read [Line]\n  var [Reader] = ReaderFactory.GetReader([Line])\n  var [Record] = [Reader].Read([File])\n  Do what you want with record\nwend\nClose [File]	0
10930323	10928711	MonoTouch compiler directive for iPhone Simulator	using MonoTouch.ObjCRuntime;\nstatic bool InSimulator ()\n{\n    return Runtime.Arch == Arch.SIMULATOR;\n}	0
19125988	19125843	Elastic search with Nest	ElasticClient.Search<Announcement>(s=>s\n    .Query(q=>\n        q.Term(p=>p.Title, searchItem.Title)\n        && q.Term(p=>p.Num, searchItem.Num)\n        //Many more queries use () to group all you want\n    )\n)	0
27428170	27427900	Add data array into existing property	dic.Value["details"].Last.AddAfterSelf(JObject.Parse(json));	0
30103340	30103100	C#, Split after 2 ;'s in same line	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        string line = "0;0;11289;950;9732;899;9886;725;32893;2195;38010;2478;46188;3330;";\n        string[] values = line.Split(';');\n        char pointName = 'A';\n        for (int i = 0; i < values.Length - 1; i += 2) {\n            string endProductLine = string.Format("point A;point {0};{1};{2}", pointName, values[i], values[i + 1]);\n            Console.WriteLine(endProductLine);\n            pointName++;\n        }\n    }\n}	0
9761173	9760613	How to populate client combobox with items from service's list of objects	Private void combobox1_SelectedValueChanged(object sender, EventArgs e)\n{\n    combobox2.Items.Clear();\n\n    if (combobox1.SelectedValue == null)\n        return;\n\n    var companies = ServiceReference1.GetCompaniesOfType(combobox1.SelectedValue);\n    combobox2.Items.Add(companies);\n}	0
6636595	6636556	How to prevent XmlReader from skipping to end of file, or how to reset the reader	var doc = XDocument.Load(fileName);  // takes care of all Open/Close issues\n string title = doc.Element("title").Value;\n string mpaa = doc.Element("title") == null ? "" : doc.Element("mpaa").Value;	0
32690269	32656178	How to get the text value from Point using Microsoft UI Automation?	public static string GetValueFromNativeElementFromPoint2(Point p)\n{\n    var element = AutomationElement.FromPoint(p);\n    object patternObj;\n    if (element.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj))\n    {\n        var valuePattern = (ValuePattern) patternObj;\n        return valuePattern.Current.Value;\n    }            \n    return null;\n}	0
6700756	6700493	Encryption and Encoding to Cookie	byte[] data = new byte[10];\nstring encoded = Safe64Encoding.EncodeBytes(data);\n...\ndata = Safe64Encoding.DecodeBytes(encoded);	0
18980867	18978386	How to delete multiple checked items in a ListView?	protected void btndelete_Click(object sender, EventArgs e)\n        {\n            DataTable dt = new DataTable();\n            if (Session["CurrentTable"] != null)\n            {\n                dt = (DataTable)Session["CurrentTable"];\n                int j = 0;\n                for (int i = 0; i < listview1.Items.Count; i++)\n                {\n                    ListViewDataItem items = listview1.Items[i];\n                    CheckBox chkBox = (CheckBox)items.FindControl("chkdel");\n\n                    if (chkBox.Checked == true)\n                    {\n                        dt.Rows.RemoveAt(j);\n                        dt.AcceptChanges();\n                    }\n                    else\n                    {\n                        j++;\n                    }\n                }\n                Session["CurrentTable"] = dt;\n                listview1.DataSource = dt;\n                listview1.DataBind();\n                BindDataToGridviewDropdownlist();\n            }\n        }	0
12438255	12438208	iso-8859-1 string to Unicode string	string s = HttpUtility.HtmlDecode(@"<span title=""&#1590;&#1575;&#1601;&#1607;");	0
24455864	24455212	How do I pass a List<int> via FormUrlEncodedContent	var myList = new List<int> { 1, 2, 3 };\n\nvar myPostData = new KeyValuePair<string, string>[]\n{\n    new KeyValuePair<string, string>("myList", string.Join(",", myList))\n};\n\nvar content = new FormUrlEncodedContent(myPostData);	0
23132089	23131852	The model item passed into the dictionary is of type 'DbQuery ', but this dictionary requires a model item of type ICollection '	public class DbQuery<TResult> : IOrderedQueryable<TResult>, \nIQueryable<TResult>, IEnumerable<TResult>, IOrderedQueryable, IQueryable, \nIEnumerable, IListSource, IDbAsyncEnumerable<TResult>, IDbAsyncEnumerable	0
24370284	24370030	Exposing EF6 model subsets via WebAPI	public class ChangeUserNameViewModel\n{\n    public int UserId { get; set; }\n    public string NewName { get; set; }\n}	0
25932925	25918029	Populateing text field and value field of listbox time from SQL	int selectedBuilding = int.Parse(listBox1.GetItemText(listBox1.SelectedValue));\n\nusing (SqlConnection conn = new SqlConnection("ConnectionStrin")) {\n            using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM Printers WHERE BuildingID = " + selectedBuilding + "", conn)) {\n                conn.Open();\n                SqlDataAdapter da = new SqlDataAdapter(cmd);\n                DataTable dt = new DataTable();\n                da.Fill(dt);\n                conn.Close();\n\n            listBox2.DataSource = dt;\n            listBox2.ValueMember = "ID";\n            listBox2.DisplayMember = "Name";\n        }\n    }	0
3548438	3548387	Registry security settings	[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.RegistryPermission)]	0
16434169	16434011	Using FileHelpers to read CSV file from asp.net file upload	using FileHelpers;\n\n// First declare the record class\n\n[Delimitedrecord("|")]\npublic class SampleType\n{\n    public string Field1;\n    public int    Field2;\n}\n\n\npublic void ReadExample(HttpPostedFile file)\n{\n    FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));\n\n    SampleType[] records;    \n\n    records = (SampleType[]) engine.ReadStream(\n                         new StreamReader(file.InputStream), Int32.MaxValue);\n\n    // Now "records" array contains all the records in the\n    // uploaded file and can be acceded like this:\n\n    int sum = records[0].Field2 + records[1].Field2;\n}	0
14319884	14319818	MySQL Parameters not adding values	public int MyMethod(string username, string password)\n{\n    int count = 0;\n    string query = "SELECT * FROM accounts WHERE username = @user AND password = @pass LIMIT 1;";\n\n    using (MySqlCommand cmd = new MySqlCommand(query, connector))\n    {\n        cmd.Parameters.Add(new MySqlParameter("@user", username));\n        cmd.Parameters.Add(new MySqlParameter("@pass ", password));\n\n        connector.Open(); // don't forget to open the connection\n        count = int.Parse(cmd.ExecuteScalar().ToString());\n    }\n\n    return count;\n}	0
15583835	15583756	How to get the values of all controls of active form in one string and concatenate them?	private void button1_Click(object sender, EventArgs e)\n{\n    MessageBox.Show(ProcesControls(this));\n}\n\nprivate string ProcesControls(Control parent)\n{\n    string s = "";\n    foreach (Control c in parent.Controls)\n    {\n        if (c.HasChildren)\n            s+=ProcesControls(c);\n\n        s += c.Text;\n    }\n    return s;\n}	0
32167790	32165988	Universal MediaElement double tapped event	mediaElement.TransportControls.DoubleTapped += TransportControls_DoubleTapped;\n\n    private void TransportControls_DoubleTapped(object sender, Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs e)\n    {\n        mediaElement.IsFullWindow = !mediaElement.IsFullWindow;\n    }	0
30999757	30999485	How to remove List<int[]> from another List<int[]>	int[] t1 = new int[] { 0, 2 };\nList<int[]> trash = new List<int[]>()\n{\n    t1,\n    new int[] {0,2},\n    new int[] {1,0},\n    new int[] {1,1}\n};\nList<int[]> trash2 = new List<int[]>()\n{\n    new int[] {0,1},\n    new int[] {1,0},\n    new int[] {1,1}\n};\n\nConsole.WriteLine(trash.Count + "");//Count = 4\ntrash.RemoveAll(a => trash2.Any(b => b.SequenceEqual(a)));\nConsole.WriteLine(trash.Count + "");//Count = 2	0
15227658	15227552	Multiple items in a Dropdownlist	public string FullName\n{\n    get { return FirstName + " " + LastName; }\n}	0
32768523	32767988	Programmatically set focus when a control becomes visible	private void searchButton_Click(object sender, RoutedEventArgs e)\n{\n    searchButton.Visibility = Visibility.Collapsed;\n    AutoSearchBar.Visibility = Visibility.Visible;\n\n    // slightly delay setting focus\n    Task.Factory.StartNew(\n        () => Dispatcher.RunAsync(CoreDispatcherPriority.Low,\n            () => AutoSearchBar.Focus(FocusState.Programmatic)));\n}	0
1478406	1477508	SubSonic Batch insert	List<MyObject> = myObjects new List<MyObject>();\n\n// Populate your MyObject List from your CSV file\n\nSubSonicRepository<MyObject> repo = new SubSonicRepository<MyObject>(new MyDB());\nrepo.Add(myObjects);	0
6817606	6817302	How do I email bcc a list of users from a txt file?	string[] recipients = File.ReadAllLines(@"C:\Data\Items\emailItems.txt");\n\nstring recipient;\n\nforeach (var recipientLine in recipients)\n{\n     // Just to take care of leading/trailing spaces and blank lines\n     recipient = recipientLine.Trim();\n     if (!string.IsNullOrEmpty(recipient))\n     {\n         MailAddress bcc = new MailAddress(recipient);\n         message.Bcc.Add(bcc);   \n     }\n}	0
26264238	26256257	Keeping Cursor position at required position	private void Button_Click(object sender, RoutedEventArgs e)\n        {\n           int SelectionStart = MyTextBox.SelectionStart + 3;\n           MyTextBox.Text = MyTextBox.Text.Insert(MyTextBox.SelectionStart, ":-)");\n           MyTextBox.Focus(Windows.UI.Xaml.FocusState.Programmatic);\n           MyTextBox.SelectionStart = SelectionStart;\n        }	0
30262076	30261865	Display different values of one enumerator list into different sub menu of menu list	//gets the attributes from the enum\n    public static T GetAttribute<T>(this Enum value) where T : Attribute\n    {\n        if (value == null)\n        {\n            throw new ArgumentNullException();\n        }\n\n        var type = value.GetType();\n        var memberInfo = type.GetMember(value.ToString());\n        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);\n        return (T)attributes[0];\n    }\n\n    //this will pull the DisplayGroup from the Display attribute\n    public static string DisplayGroup(this Enum value)\n    {\n        var attribute = value.GetAttribute<DisplayAttribute>();\n        return attribute == null ? value.ToString() : attribute.GroupName;\n    }\n\n    //enum decoration looks like\n    public enum MyEnum\n    {\n        [Display(GroupName = "MyGroupName")]\n        AnEnum\n    }\n\n    //pull the group name like\n    var groupName = MyEnum.AnEnum.DisplayGroup();\n    //Assert.IsTrue(groupName.Equals("MyGroupName");	0
5038787	5037995	How can I create new blank solution in vs 2008 programmatically?	string visualStudioProgID = "VisualStudio.Solution.9.0";\nType solutionObjectType = System.Type.GetTypeFromProgID(visualStudioProgID, true);\nobject obj = System.Activator.CreateInstance(solutionObjectType, true);\nSolution3 solutionObject = (Solution3)obj;\nsolutionObject.Create(".", "MySolution");\nsolutionObject.SaveAs(@"C:\Temp\MySolution.sln"); //or wherever you prefer	0
28409449	28409085	Updating a listox Item value programatically	private void button3_Click(object sender, EventArgs e)\n{\n    if(lstItemCode.SelectedItem != null)\n    {\n        string newText = lstItemCode\n                            .SelectedItem\n                            .ToString()\n                            .Replace("Complete", string.Empty)\n                            .Trim();\n        lstItemCode.Items[lstItemCode.SelectedIndex] = newText;\n    }\n}	0
5182988	5182918	Retrieve MVID of an assembly from c#?	var myAssembly = Assembly.GetExecutingAssembly(); //or whatever\nvar mvid = myAssembly.ManifestModule.ModuleVersionID;	0
33083698	33079782	When add row at the end of datagridview bound to List the new row do not display after added row	DataGridView view = new DataGridView();\nview.DataSource = somesource;\nview.DataSource = null;\nview.DataSource = updatedsource;	0
22804953	22804744	Hide buttons for last row in gridview	if(gvOBMDetails.PageCount == 1)//Updated\n{\n    var lastRow = gvOBMDetails.Rows[gvOBMDetails.Rows.Count - 1];\n    lastRow.FindControl("btnEdit").Visible = false;\n    lastRow.FindControl("btnDelete").Visible = false;\n}\nelse if(gvOBMDetails.PageIndex == gvOBMDetails.PageCount -1)\n{\n    var lastRow = gvOBMDetails.Rows[gvOBMDetails.Rows.Count - 1];\n    lastRow.FindControl("btnEdit").Visible = false;\n    lastRow.FindControl("btnDelete").Visible = false;\n}	0
15382843	15222360	Add-in for Outlook in C# (Saving the Attachment and adding a url reference to the saved file path as attachment)	mi.Attachments.Add(""+[path of file to Attach Reference], OlAttachmentType.olByReference, i, Type.Missing);	0
24943109	24942118	Copy LocalDB in Winform gives me a 'File being used by another process'	string backupDB = @"FullPathToYourBackupFile.bak";\nstring databaseName = "YourDBName"; // This is not the MDF file, but the logical database name\nusing (var db = new DbContext())\n{\n    var cmd = string.Format("BACKUP DATABASE {0} TO DISK='{1}' WITH FORMAT;",\n                            databaseName, backupDB);\n    db.Database.ExecuteSqlCommand(cmd, null);\n}	0
11254684	11254647	How to calculate the time complexity of this odd method	public List<Book> Shoot()\n{\n    var authors = new Dictionary<string, int>();\n    foreach(var b in books) \n    {\n        if(authors.ContainsKey(b.Author))\n            authors[b.Author] ++;\n        else\n            authors.Add(b.Author, 1);\n    }\n\n    foreach(var b in books) \n    {\n        if(authors[b.Author] == 1)\n            yield return b;\n    }\n}	0
3855608	3853746	how to make program that be in the taskbar windows-CE	m_notifyIcon = new NotifyIcon();\nm_notifyIcon.Icon = this.Icon;\nm_notifyIcon.Visible = true;\nm_notifyIcon.Click += new EventHandler(m_notifyIcon_Click);\nm_notifyIcon.DoubleClick += new EventHandler(m_notifyIcon_DoubleClick);	0
4105367	4105264	Converting XML document to URL encoded query string for HTTP POST - C#	var query = string.Join("&",(\n            from parent in XElement.Parse(xml).Elements()\n            from child in parent.Elements()\n            select HttpUtility.UrlEncode(parent.Name.LocalName) + "_"\n                 + HttpUtility.UrlEncode(child.Name.LocalName) + "="\n                 + HttpUtility.UrlEncode(child.Value)).ToArray());	0
30220173	24589774	How to get my current Location with GeoPoint API in Windows Store Apps?	public async void getposition() {\n    Geolocator geolocator = new Geolocator();\n    Geoposition geoposition = null;\n    geoposition = await geolocator.GetGeopositionAsync();\n    MyMap.Center = geoposition.Coordinate.Point;\n    // zoom level\n    MyMap.ZoomLevel = 15;	0
11934336	11934298	Image button inside div position	#div_id {\nposition: relative;\n}	0
1519217	1519149	Graphic object outside of C# app - is it doable?	Graphics.FromHdc(IntPtr.Zero)	0
25974279	25935173	How to perform left join using two or more table in LInq to Sql query?	var products = \n        from p in this.Products \n        join cat in this.ProductCategoryProducts \n        .Where(c => c.ProductID == p.ProductID).DefaultIfEmpty()\n\n        from pc in this.ProductCategories \n        .Where(pc => pc.ProductCategoryID == cat.ProductCategoryID).DefaultIfEmpty()\n\n        where p.ProductID == productID\n        select new\n        {\n            ProductID = p.ProductID,\n            Heading = p.Heading,                \n            Category = pc.ProductCategory\n        };\n    return products ;	0
24390126	24388220	Create HBase Table programatically in Azure	var marlin = new Marlin(ClusterCredentials.FromFile("credentials.txt"));\nvar testTableSchema = new TableSchema();\ntestTableSchema.name = "table";\ntestTableSchema.columns.Add(new ColumnSchema() { name = "d" });\ntestTableSchema.columns.Add(new ColumnSchema() { name = "f" });\nmarlin.CreateTable(testTableSchema);	0
1340548	1336608	Load event for Grid	public Control()\n        {\n            InitializeComponent();\n            this.Loaded += new RoutedEventHandler(Control_Loaded);\n        }\n\nvoid Control_Loaded(object sender, RoutedEventArgs re)\n        {\n//Do any init here\n}	0
16531324	16531314	Reduce multiple consecutive equal characters from a string to just one	Regex.Replace(str, @"\++", "+");	0
24673927	24654910	Windows Store App - C# - TextBlock check if text is trimmed	private void textBlock_SizeChanged(object sender, SizeChangedEventArgs e)\n    {\n        TextBlock tb = sender as TextBlock;\n\n        if (tb != null)\n        {\n            Grid parent = tb.Parent as Grid;\n            if(parent != null)\n            {\n                if(parent.ActualWidth < tb.ActualWidth)\n                {\n                    tb.FontSize -= 10;\n                }\n            }\n        }\n    }	0
4884356	4884322	How to remove querystring part from Request.UrlReferrer.AbsoluteUri in C#	Response.Redirect(Request.UrlReferrer.AbsolutePath);	0
5381590	5380951	Selected Data in CheckBoxList to Gridview	protected void mybutton_click()\n{\n    StringBuilder sb = new StringBuilder();\n    foreach(ListItem item in CustomerListBox.Items)\n    {\n\n         If(item.selected)\n         {\n             sb.Append(item.SelectedValue+",");\n         }\n    }\n\n    FillGridview(sb);\n}\n\nprivate void FillGridview(StringBuilder sb)\n{\n    string s = sb.tostring().remove().lastindexof(",");\n    //pass this string as param and set it your where condition.\n    // Get the datatble or collection and bind grid.\n}\n\nSelect your desired columsn to display \nFrom Your Tables (put joins if required)\nWhere CustomerNumber IN (@CommaSeparatedAboveString_s);	0
26808651	26808547	How to convert Decimal to binary C# (4 bits)	string res = Convert.ToString(number, 2);\nres = new string('0', 8 - res.Length) + res;	0
24936527	24936458	Returning a ajax Error from C#	[WebMethod]\n[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\npublic static string Hello()\n{\n    Response.StatusCode = 400 ; // Will be captured on ajax error method \n    return "Hello World";\n}	0
6608943	6608719	How many threads to use?	foreach (var file in files)\n        {\n            var workitem = file;\n            Task.Factory.StartNew(() =>\n            {\n                // do work on workitem\n            }, TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);\n        }	0
14766295	14734615	JSon Deserializing getting type	var myObject = JObject.Parse(jsonString)\nvar someObject = myObject["myOtherObject"]["otherThing"];\nvar myString = (string) someObject["theString"];	0
27640623	25725151	Write to Windows Application Event Log without registering an Event Source	using(EventLog eventLog = new EventLog("Application")) \n    { \n        eventLog.Source = "Application"; \n        eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); \n    }	0
2878771	2878757	Simple C# USING statement for folder	using myNamespace;	0
9902146	9902105	Better way to use data set in C#	["<column_name>"]	0
987659	987608	PropertyInfo Sub Properties	foreach (var code in ctx.GetType().GetProperties())\n        {\n            Console.WriteLine(code.PropertyType + " - " + code.Name + " ");\n            if (code.PropertyType.ToString().Contains("System.Data.Linq.Table"))\n            {\n                  //this does not give me what i want here\n                  foreach (var pi in code.PropertyType.GetGenericArguments()[0].GetProperties())\n                  {\n                   Console.WriteLine(pi.Name);\n                  }\n            }\n        }	0
11717107	11716838	How to deserialize Nullable<bool>?	[XMLArray("Users")]\npublic class User\n{\n    [XmlIgnore]\n    public bool? m_copy;\n\n    [XmlAttribute("copy")]\n    public string copy\n    {\n        get { return (m_copy.HasValue) ? m_copy.ToString() : null; }\n        set { m_copy = !string.IsNullOrEmpty(value) ? bool.Parse(value) : default(bool?); }\n    }\n}	0
31170186	31168739	Convert Resources into Array or Dictionary	string[] files = Directory.GetFiles(@"resources", "*.wav");\n        Dictionary<string, Stream> dic = new Dictionary<string, Stream>();\n        foreach (var file in files)\n        {\n            byte[] data = File.ReadAllBytes(file);\n            MemoryStream stream = new MemoryStream(data);\n            dic.Add(Path.GetFileNameWithoutExtension(file), stream);\n        }\n\n        foreach (var item in  dic.OrderBy(d=>d.Key))\n        {\n            // here store item which has been ordered by name!\n        }	0
117766	116775	What is the best way to sort controls inside of a flowlayout panel?	SortedList<DateTime,Control> sl = new SortedList<DateTime,Control>();\n        foreach (Control i in mainContent.Controls)\n        {\n            if (i.GetType().BaseType == typeof(MyBaseType))\n            {\n                MyBaseType iTyped = (MyBaseType)i;\n                sl.Add(iTyped.Date, iTyped);\n            }\n        }\n\n\n        foreach (MyBaseType j in sl.Values)\n        {\n            j.SendToBack();\n        }	0
3532516	3531715	Postgres ODBC connection with named pipes on Windows	NpgsqlConnection conn = new NpgsqlConnection("Database=DatabaseName;User Id=postgres;Password=mypassword;");	0
1276205	1276150	ASP.NET : Filter unique rows from Data table	yourdataset.Tables["TableName"].DefaultView.ToTable(true,"disticecolumn");	0
15096659	15096621	Getting value of an attribute within namespace	string xml = @"...";\n\nXName nameRif = "rif";\nXDocument doc = XDocument.Parse(xml);\n\nvar q = from item in doc.Descendants()\n        let attributeType = item.Attribute(nameRif + "AgenteRetencionIVA")\n        select item.Value;\nvar a = q.ToArray();	0
20055488	20052438	Removing many to many entity Framework	var artist = this._db.Artists.Include(a => a.ArtistTypes)\n    .SingleOrDefault(a => a.ArtistID == someArtistID);\n\nif (artist != null)\n{\n    foreach (var artistType in artist.ArtistTypes\n        .Where(at => vm.SelectedIds.Contains(at.ArtistTypeID)).ToList())\n    {\n        artist.ArtistTypes.Remove(artistType);\n    }\n    this._db.SaveChanges();        \n}	0
2407473	2400625	C# how to do <enter> on barcode?	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        if (textBox1.Text.Contains("$"))\n        {\n            string[] str_split = textBox1.Text.Split("$".ToCharArray ());\n            textBox1.Text = str_split[0].ToString ();\n            textBox2.Text = str_split[1].ToString();\n        }\n    }	0
19230496	19230377	select all text in a textarea with CTRL+A	private void textBox1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyData == (Keys.Control | Keys.A)) {\n            textBox1.SelectAll();\n            e.Handled = e.SuppressKeyPress = true;\n        }\n    }	0
17366041	17366008	How to get all the rows of a table, where a column's value occurs more than once in LINQ to Entities?	Context.Customers.GroupBy(x => x.Col2) // group by Col2 value\n                 .Where(g => g.Count() > 1) // get groups with more than one item\n                 .SelectMany(g => g) // flatten results\n                 .ToList();	0
9663255	9663161	Simple Datetime format in form of YYYYMMDD	string sDate = "19901209";\n        string format = "yyyyMMdd";\n\n        System.Globalization.CultureInfo provider = \n                             System.Globalization.CultureInfo.InvariantCulture;\n        DateTime result = DateTime.ParseExact(sDate, format, provider); \n        // result holds wanted DateTime	0
20210570	20206452	Setting window title with Caliburn.Micro	Title={DynamicResource .... }	0
4440538	4440490	c# Windows Service Console.Writeln	System.Diagnostics.EventLog	0
5838844	5838797	From VS2010 in Windows 7 using Directory.Delete(path) from the VS debugger	attrib "MyFolder" -R -A -S -H	0
21255201	21254759	How to disable Win key of on-screen keyboard?	MOD_WIN      (0x0008)	0
3600916	3600871	Fastest way to cast int to UInt32 bitwise?	int color = -2451337;\nunchecked {\n    uint color2 = (uint)color;\n    // color2 = 4292515959\n}	0
11652274	11652196	Show in progress label until the operation finished	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    label1.Content = "In progress..";\n    Task.Factory.StartNew<List<string>>(\n    () =>\n    {\n        List<string> intList = new List<string>();\n        for (long i = 0; i <= 50000000; i++)\n        {\n            intList.Add("Test");\n        }\n\n        return intList;\n    })\n    .ContinueWith(\n        (t) => label1.Content = t.Result.ToString(),\n        TaskScheduler.FromCurrentSynchronizationContext());\n}	0
23091125	23090930	ASP.NET Repository design pattern	public interface ICustomerRepository : IDisposable\n{\n    IEnumerable<Customer> GetCustomers();\n    Customer GetCustomerByID(int customerId);\n    void InsertCustomer(Customer customer);\n    void DeleteCustomer(int customerId);\n    void UpdateCustomer(Customer customer);\n    void Save();\n}	0
13203846	13203675	How to read full filename if we know only a part of the filename eg, starts XYZ_----.txt from a folder	string path = ConfigurationManager.AppSettings["LogDir"];\nstring[] files = Directory.GetFiles("C:\\Records\\", "Record_*" + ".txt", SearchOption.TopDirectoryOnly);	0
18250420	18230345	MVC4 - Setting Initially Selected Item in DropDownList	private List<SelectListItem> GetListOfObjectTypes(SelectList selectList, string objectTypeName, string objectTypeId)\n{\n    List<SelectListItem> items = new List<SelectListItem>();\n    foreach (METAObjectType item in selectList.Items)\n    {\n         bool isSelected = false;\n         if (item.Name == objectTypeName)\n         {\n                isSelected = true;\n         }\n         items.Add(new SelectListItem {Selected= isSelected, Text=item.Name, Value=item.ObjectTypeId.ToString()});\n        }\n        return items;\n    }	0
22883000	22881051	How and where are Windows passwords stored on the disk, and what algorithms are used to hash them?	/// <summary>\n    /// Convert Password to NT Hash.  Convert to unicode and MD4\n    /// </summary>\n    /// <param name="passwordIn">password In</param>\n    /// <returns>NT Hash as byte[]</returns>\n    public static byte[] NTHashAsBytes(string passwordIn)\n    {\n        MD4Digest md = new MD4Digest();\n        byte[] unicodePassword = Encoding.Convert(Encoding.ASCII, Encoding.Unicode, Encoding.ASCII.GetBytes(passwordIn));\n\n\n        md.BlockUpdate(unicodePassword, 0, unicodePassword.Length);\n        byte[] hash = new byte[16];\n        md.DoFinal(hash, 0);\n\n\n        return hash;\n    }	0
5157000	4997987	How do I determine if a Process is Managed in C#?	Process mProcess = //Get Your Process Here\nforeach (ProcessModule pm in mProcess.Modules)\n{\n    if (pm.ModuleName.StartsWith("mscor", StringComparison.InvariantCultureIgnoreCase))\n    {\n        return true;\n    }\n}	0
27154235	27154090	Web Api Help Page - Show only some controllers but no others	[ApiExplorerSettings(IgnoreApi = true)]	0
15431557	7283753	Create nuget package for a solution with multiple projects	> nuget.exe pack proj.csproj -IncludeReferencedProjects	0
32252760	32252555	MethodInfo invoke for Overloaded methods in C#	var signature = new[] {typeof (byte[]), typeof (int), typeof (int), typeof (int)};\nMethodInfo methodSend = deviceType.GetMethod("Send", signature);	0
3521772	3520384	Ignore property mapping by accessbility in Fluent NHibernate AutoMapper	var cfg = Fluently.Configure()\n            .Database(configurer)\n            .Mappings(m =>\n                        {\n                            m.AutoMappings.Add(AutoMap.Assemblies(Assembly.GetExecutingAssembly())\n                                .Override<Team>(map => map.IgnoreProperty(team => team.TeamMembers)));\n                        });	0
351631	351557	How does one insert a column into a dataset between two existing columns?	DataSet ds = new DataSet();\nds.Tables.Add(new DataTable());\nds.Tables[0].Columns.Add("column_1", typeof(string));\nds.Tables[0].Columns.Add("column_2", typeof(int));\nds.Tables[0].Columns.Add("column_4", typeof(string));\nds.Tables[0].Columns.Add("column_3", typeof(string));\n//set column 3 to be before column 4\nds.Tables[0].Columns[3].SetOrdinal(2);	0
20804402	20804167	local folder in application	Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets/Images");	0
12376021	12373649	C# Reading Fixed Length File - Trimming Space in the values	const int maxInvoiceLength = 10;\nstring fileName = @"C:\temp\fs.txt";\nstring dir = Path.GetDirectoryName(fileName);\n\nDataTable dataTable;\n\nusing (OleDbConnection conn =\n    new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;" +\n        "Data Source=" + dir + ";" +\n        "Extended Properties=\"Text;\""))\n    {\n        conn.Open();\n\n        string query = String.Format("SELECT RecordTypeSCFBody, LEFT(InvoiceNumber + SPACE({0}), {0}), Amount FROM {1}", maxInvoiceLength, fileName);\n        using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))\n        {\n            dataTable = new DataTable();\n            adapter.Fill(dataTable);\n        }\n    }\n\n    Console.Write(dataTable.Rows[0][1].ToString());	0
18596294	18596245	In C#, how can I detect if a character is a non-ASCII character?	char c = 'a';//or whatever char you have\nbool isAscii = c < 128;	0
15153503	15153191	Getting ExtendedPropertyDefinition values from EWS in Outlook addin	//Setting the property with Exchange webservice:\n\nstring guid = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";\n\nGuid MY_PROPERTY_SET_GUID = new Guid(guid); \n\nMicrosoft.Exchange.WebServices.Data.ExtendedPropertyDefinition extendedPropertyDefinition =\nnew Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(MY_PROPERTY_SET_GUID, "Archivado", MapiPropertyType.String);\n\n\n//Recover the property using Outlook:\n\n\nOutlook.MailItem item = (Outlook.MailItem)e.OutlookItem;\n\nOutlook.UserProperties mailUserProperties = item.UserProperties;\n\ndynamic property=item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{Outlook.MailItem item = (Outlook.MailItem)e.OutlookItem;\n\n            Outlook.UserProperties mailUserProperties = item.UserProperties;\n            dynamic property=item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}/Archivado");	0
32618530	32617611	How to retrieve other user controls information from user control?	protected void Page_PreRender(object sender, EventArgs e)\n{\n    var listSocialShare = FindControlsRecursive<SocialElement>(Page);\n    int number = listSocialShare.Count();\n}\n\nprivate IEnumerable<T> FindControlsRecursive<T>(Control root)\n{\n    foreach (Control child in root.Controls)\n    {\n        if (child is T)\n        {\n            yield return (T)Convert.ChangeType(child, typeof(T));\n        }\n\n        if (child.Controls.Count > 0)\n        {\n            foreach (T c in FindControlsRecursive<T>(child))\n            {\n                yield return c;\n            }\n        }\n    }\n}	0
4209782	4186218	How to use LINQ to query from a list of objects into an existing object?	//just grab the first item\nvar item = result.GetSPListItems().FirstOrDefault();\n\n//then grab the properties into the existing ContractActionEntity                             \ncontractAction.Title = item.GetSPFieldValue("Title");\ncontractAction.Description = item.GetSPFieldValue("Description");\ncontractAction.DeliveryOrderID = SPHelper.GetFirstLookupID(item.GetSPFieldValue("Delivery Order"));\ncontractAction.EstimatedValue = item.GetSPFieldValue("Estimated Value").ToNullableDouble();\ncontractAction.AgreementTypeID = SPHelper.GetFirstLookupID(item.GetSPFieldValue("Contract Type")),	0
4124655	4124638	How to delete a drawn circle in c# windows form?	this.Invalidate();	0
27484455	27452449	Variable Includes in Linq to Sql EF statement	var entity = db.Forms;\n\nforeach (string s in includes)\n{\n    entity.Include(s);\n}\n\nForm form = entity.Where(m => m.Id == id).First();	0
5010023	5009890	Change Hidden Input With onFocus Between UserControls	document.getElementsByName('ChangeFlag')[0].value='TRUE	0
12966903	12966081	How to change notifyIcon1 icon in code	notifyIcon1.Icon = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\Users\Alex\Downloads\On.ico");	0
25036942	25036238	How to get the index value from html element?	public Int GetListIndex(string url)\n{\n   LinkCollection links = browser.Links;\n   int count = -1;\n   foreach(Link lnk in links)\n   {\n      if(lnk.GetAttributeValue("href").Contains(url))\n      {\n         return ++count;\n      }\n     count++;\n    }\n }	0
10361081	10361067	Where to store objects if I want them to be accessible for every class in my project	public class MyClass\n{\n    public static string str="Str";\n    ////\n}\n\npublic class NewClass\n{\n    public static string newstr="New "+MyClass.str;\n    ////\n}	0
14214955	13960423	programmatically add child to xamdatatree node	public class TreeNode : PropertyChangedNotifier\n{\n  private Label text;\n  private System.Drawing.Image icon;\n  private ObservableCollection<TreeNode> children;\n}\n\n        <ig:XamDataTree.GlobalNodeLayouts>\n            <ig:NodeLayout\n                Key="Children"\n                DisplayMemberPath="Text"\n                TargetTypeName="Model.TreeNode" \n                >\n            </ig:NodeLayout>\n        </ig:XamDataTree.GlobalNodeLayouts>	0
7044672	7044570	Setting DataKeys for Custom GridView	Hidden field	0
27038503	27038309	How rename the title of file from some folder if name contains some text	foreach (var file in Directory.EnumerateFiles("somePath", "test_*"))\n{\n    var newFileName = Path.GetFileName(file).Remove(0, 5);  // removes "test_"\n\n    File.Move(file, Path.Combine(Path.GetDirectoryName(file), newFileName));\n}	0
20681779	20681714	Array of buttons: change property	private void butt2_2_Click(object sender, EventArgs e) \n{\n  Button pushedBtn = sender as Button;\n  if(pushedBtn != null)\n  {\n     pushedBtn.BackColor = Color.Green;\n  }  \n}	0
6692309	6692184	c# HtmlAgility Pack - Unable to get image src	WebClient wc = new WebClient();\nstring html = wc.DownloadString("http://archive.ncsa.illinois.edu/primer.html");\ndoc.LoadHtml(html);	0
33656618	33653832	Preventing selection of certain items in Winforms ListBox	int lastIndex = 0;\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string s = listBox1.SelectedItem.ToString();\n    int newIndex = listBox1.SelectedIndex;\n    if (s == "" )\n    {\n        if (newIndex > lastIndex && newIndex  < listBox1.Items.Count)\n        {\n            listBox1.SelectedIndex++;\n        }\n        else if (newIndex < lastIndex && newIndex > 0)\n        {\n            listBox1.SelectedIndex--;\n        }\n    }\n    else lastIndex = newIndex;\n}	0
26788509	23154534	EF Power Tools - Reverse Engineer - Decimal Precision	public partial class OriginalContext : DbContext\n{\n    ...\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        ...\n        // This would be overwritten if we left it in the OriginalContext class\n        // modelBuilder.Entity<ConvertCarb>().Property(x => x.G_KWH).HasPrecision(18, 4);\n    }\n}\n\npublic class ExtendedContext : OriginalContext\n{\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        base.OnModelCreating(modelBuilder);\n\n        // Put the code here instead so it isn't overwritten when we reverse engineer\n        modelBuilder.Entity<ConvertCarb>().Property(x => x.G_KWH).HasPrecision(18, 4);\n    }\n}	0
12130117	12129251	Html agility cant get the results	using (var wc = new WebClient())\n{\n    HtmlDocument doc = new HtmlDocument();\n\n    doc.LoadHtml(wc.DownloadString("http://www.manta.com/mb?search=U.S.+Cellular&refine_company_loctype=B"));                \n\n    var divs = doc.DocumentNode.SelectNodes("//div[@class='clear']");\n\n    if (!divs.Any())\n        Response.Write("Not found or timeout protection mechanism");\n\n    foreach (var item in divs)\n    {\n        HtmlNode link = item.Descendants("a").FirstOrDefault();\n        Response.Write(link.GetAttributeValue("href", string.Empty));\n    }\n}	0
32005	32000	C# - SQLClient - Simplest INSERT	using (var conn = new SqlConnection(yourConnectionString))\n{\n    var cmd = new SqlCommand("insert into Foo values (@bar)", conn);\n    cmd.Parameters.AddWithValue("@bar", 17);\n    conn.Open();\n    cmd.ExecuteNonQuery();\n}	0
28471523	28471258	Select rows with LINQ from List<Dictionary<string, object>>	list.ForEach(x =>\n        {\n\n            x.Where(y => y.Value == null).ToList().ForEach(z=>\n                {\n                    if(list.All(l=>!l.ContainsKey(z.Key)|| l[z.Key]==null))\n                        x.Remove(z.Key);\n                });\n        });	0
8769477	8769416	Converting string to float and formatting it (C#)	float f = 0.0000666f;\nMessagebox.Show(String.Format("{0:0,0.0000000}", f));	0
1086638	1086618	Comparing enum flags in C#	public static bool IsSet<T>(this T value, T flags) where T : Enum\n{ \n    if (value is int)\n    {\n        return ((int)(object)a & (int)(object)b) == (int)(object)b);\n    }\n    //etc...	0
9467838	9200194	How to get Visual/Framework elements near mouse pointer in a Chart Control	OnMouseEnter()\n{\n    this.hittestPoint = currentMousePoint;\n}\n\nOnMouseLeave()\n{\n    this.hitTestPoint = currentMousePoint;\n}\n\nOnMouseDown()\n{\n    // Looking for mousedown within a 5 pixel radius of the line. \n    // Increase/decrease according to experimentation\n    const double radius = 5;\n\n    // Note see Euclidean distance for distance between vectors\n    // http://en.wikipedia.org/wiki/Euclidean_distance\n    double deltaX = (hitTestPoint.X - currentPoint.X);\n    double deltaY = (hitTestPoint.Y - currentPoint.Y);\n    double distance = Math.Sqrt(deltaX*deltaX + deltaY*deltaY);\n\n    if(distance < radius) \n    {\n         // Hittest detected!\n    }\n}	0
24192585	24192400	Wrapping Children of an XML Document	XDocument xDoc = XDocument.Parse(\n    @"<?xml version=""1.0"" encoding=""utf-16""?>\n    <root>\n        <element>YUP</element>\n        <element>YUP</element>\n        <element>YUP</element>\n    </root>");\n\nvar newsubroot = new XElement("newsubroot");\nnewsubroot.Add(xDoc.Root.Elements());\nxDoc.Root.RemoveAll();\nxDoc.Root.Add(newsubroot);	0
26689608	26689407	My image validator somehow affects my HttpPostedFileBase value	private bool IsFileTypeValid(HttpPostedFileBase image)\n    {\n        try\n        {\n            using (var img = Image.FromStream(image.InputStream))\n            {\n                return IsOneOfValidFormats(img.RawFormat);\n            }\n        }\n        finally\n        {\n            image.InputStream.Seek(0, SeekOrigin.Begin);\n        }\n    }	0
21188583	21167561	How can I access a resource image within XAML in a user control library?	ImageSource="pack://application:,,,/my_assembly;component/Resources/your_image.p??ng"	0
616674	616657	How can return reference to Dictionary from a method as readonly?	public class ReadOnlyDictionary<T, U>\n{\n    private IDictionary<T, U> BackingStore;\n\n    public ReadOnlyDictionary<T, U>(IDictionary<T, U> baseDictionary) {\n        this.BackingStore = baseDictionary;\n    }\n\n    public U this[T index] { get { return BackingStore[index]; } }\n\n    // provide whatever other methods and/or interfaces you need\n}	0
20252410	20250039	Give process permissions programmatically	proc.StartInfo.WorkingDirectory = path;	0
21548450	21548081	C# transparent label, how to inherit backcolor	Bitmap bitmap = new Bitmap(pictureBox1.Image);\n Color colorAtPoint = bitmap.GetPixel(label1.Location.X, label1.Location.Y);	0
17831767	17831244	Linq to return a new object with a selection from the list	return (from a in IDs\n        from b in a.Values\n        where b.Code == code\n        select (new A\n        {\n            ID = a.ID, Values = new List<B>\n            {\n                new B\n                {\n                    Code = b.Code, \n                    DisplayName = b.DisplayName\n                }\n            }\n        })).FirstOrDefault();	0
12856352	12817433	Generating route specific views in an MVC 3 Application	foreach (var programme in programmes)\n            {\n                routes.MapRoute("ProgrammeArea" + " " + programme.Code,\n                                programme.Url + "/{action}/{id}",\n                                new { controller = "PaymentDetails", action = "Index", id = programme.Id }\n                    );\n            }	0
15247769	15247454	Out generic parameters with types only known at runtime	object[] parameters = new object[] { null };\nType typeParam = typeof(string);\nType ifaceType = typeof(IOut<>).MakeGenericType(typeParam);\nMethodInfo method = ifaceType.GetMethod("Get");\n\nvar impl = new Impl();\nmethod.Invoke(impl, parameters);\n\nobject outParam = parameters[0];	0
7375901	7375551	Passing a byte[] around	byte[] retVal = MyInstance.FileRawData;\nretVal[1] = 0x00;	0
6238820	6238566	wpf convert some xaml to c#	var style = new Style(typeof(Ellipse));\nvar trigger = new DataTrigger();\ntrigger.Binding = new Binding("Opacity") { ElementName = "ellipse1" };\ntrigger.Value = 0.5;\nStoryboard sb = new Storyboard();\n\n//Add animation to sb, note the attached storyboard properties which are set with static methods:\n//Storyboard.SetTarget(...);\n//Storyboard.SetTargetProperty(...);\n//Storyboard.SetTargetName(...);\n\ntrigger.EnterActions.Add(new BeginStoryboard() { Storyboard = sb });\nstyle.Triggers.Add(trigger);	0
3062945	3062912	How can I translate this SQL statement to a Linq-to-SQL approach?	dbContext.Users.Any(x => x.ID == inputID)	0
14304828	14183361	How do I remove a specific folder with files in it from a zip using the Dotnetzip library?	int x;\n for (x = 0; x < zip.Count - 1; x++)\n {\n     ZipEntry e = zip[x];\n     if (e.FileName == "META-INF/")\n     {\n         zip.RemoveEntry(e.FileName);\n     }\n }	0
10562574	10562554	Kinect SDK player detection	void nui_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e) {\n    SkeletonFrame sf = e.SkeletonFrame;\n    //check which skeletons in array are active and use that array indexes for player index\n    SkeletonData player1 = sf.Skeletons[playerIndex1];\n    SkeletonData player2 = sf.Skeletons[playerIndex2];	0
16930190	16930138	Creating DateTime object from string	var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);	0
10302159	10302114	Get specific elements from string file	line.StartsWith("Hosts")	0
16961006	16960519	how to set the folder of destination when I use local copy?	copy /Y "$(SolutionDir)lib\$(ProjectName)\sqllitefile.dll" "$(TargetDir)\$(ProjectName)\sqllitefile.dll"	0
10815819	10736242	Converting a large CLOB object to .NET string to put into a DataGridView cell	if (reader.IsDBNull(i))\n{\n    cellValue = "NULL";\n}\nelse\n{\n    OracleLob clob = reader.GetOracleLob(i);\n    cellValue  = (string) clob.Value;\n}	0
12556813	12546602	How to test for upgrade lock in NHibernate?	LockMode.UpgradeNoWait	0
13067569	13067331	add items to ListBox Control from ListView Control	for (int intCount = 0; intCount < lvEmpDetails.SelectedItems.Count; intCount++)\n{\n     lbxEmpName.Items.Add(lvEmpDetails.SelectedItems[intCount].Text);  \n     lvEmpDetails.SelectedItems[intCount].Remove();    \n     //Every time remove item, reduce the index           \n     intCount--;   \n}	0
30686604	30681933	Custom papersize using floating point numbers	ISOA8 = A8	0
21560707	21560545	How to stop authorization loop?	if (ModelState.IsValid && Membership.ValidateUser(loginModel.UserName, loginModel.Password))\n{\n    FormsAuthentication.SetAuthCookie(loginModel.UserName, true);\n    return RedirectToLocal(returnUrl);\n}	0
19714878	19698131	Problematic Conversion of Pointers From C# code to VB.net	Dim pPixel = bitmapData.Scan0\n    For y As Integer = 0 To bitmapData.Height - 1\n        For x As Integer = 0 To bitmapData.Width - 1\n            Marshal.WriteByte(pPixel, 4 * x + 3, value)\n        Next\n        pPixel += bitmapData.Stride\n    Next	0
8527839	8527778	Dispatcher.Invoke from a new thread is locking my UI	_waitHandle.WaitOne();	0
1268867	1268479	What's the most streamlined way of performing a XSLT transformation in ASP.NET?	XDocument xDoc = XDocument.Load("output.xml");\n\n        XDocument transformedDoc = new XDocument();\n        using (XmlWriter writer = transformedDoc.CreateWriter())\n        {\n            XslCompiledTransform transform = new XslCompiledTransform();\n            transform.Load(XmlReader.Create(new StreamReader("books.xslt")));\n            transform.Transform(xDoc.CreateReader(), writer);\n        }\n\n        // now just output transformedDoc	0
29364232	29362105	GridView Filter buttons for collection	public void Filter(type filterType)\n{\n    MenuItems.Clear();\n    foreach(var item in AllItems)\n    {\n       if(item.type == filterType)\n       {\n          MenuItems.Add(item);\n       }\n    }\n}	0
27672055	27668276	ListView embedded in UserControl 'loses' Columns at runtime	[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] \npublic ListView.ColumnHeaderCollection  Columns {  \n    get { return listView.Columns; }  \n}	0
9605830	9605608	How to detect cell value changed datagridview c#	bindingSource1.DataSource = tbData;\ndataGridView1.DataSource = bindingSource1;\nbindingSource1.ListChanged += new ListChangedEventHandler(bindingSource1_ListChanged); \n\npublic void bindingSource1_ListChanged(object sender, ListChangedEventArgs e)\n{\n    DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); \n    cellStyle.ForeColor = Color.Red;\n\n    dataGridView1.Rows[e.NewIndex].Cells[e.PropertyDescriptor.Name].Style = cellStyle;\n}	0
2772910	2772574	High Runtime for Dictionary.Add for a large amount of items	public override int GetHashCode() {\n    return oneId << 16 | (anotherId & 0xffff);\n}	0
19915893	19915634	How to get a Child Nodes Attribute	XDocument doc = XDocument.Load("input.xml");\nforeach (XElement child in doc.Descendants("Parent").Elements("Child"))\n{\n  Console.WriteLine("Id: {1}, Name: {2}", child.Attribute("ID").Value, child.Attribute("Name").Value);\n}	0
8961235	8961180	Initialize Object with LINQ to XML	var root = XDocument.Parse(@"<data>\n<num>3</num>\n<str>string</str>\n<boo>true</boo>\n<point x=""3"" y=""5"" />\n</data>").Root;\n\npublic class MyObject()\n{\n  public class Point \n  {\n    int X {get;set;}\n    int Y  {get;set;}\n  }\n\n  public MyObject() {\n   Point = new Point();\n  }\n  public int Num {get;set;}\n  public string Str {get;set;}\n  public bool Boo {get;set;}\n  public Point Point {get; private set;}\n}\n\nvar myObj = root.Select(new MyObject\n{\n    Num = int.Parse(root.Element("num").Value),\n    Str = root.Element("str").Value,\n    Boo = bool.Parse(root.Element("boo").Value),\n    Point.X = int.Parse(root.Element("point").Attribute("x").Value),\n    Point.Y = int.Parse(root.Element("point").Attribute("y").Value)\n});	0
20153617	20153546	I'm trying to fill my List<Class> from a text file using C#?	var list = new List<cEspecie>();\n        using (StreamReader reader = File.OpenText(filePath))\n        {\n            while(!reader.EndOfStream)\n            {\n                string name = reader.ReadLine();\n                int type = int.Parse(reader.ReadLine());\n                int movility = int.Parse(reader.ReadLine());\n                int lifeTime = int.Parse(reader.ReadLine());\n                int deadTo = int.Parse(reader.ReadLine());\n                list.Add(new cEspecie(name, type, movility, lifeTime, deadTo));\n            }\n        }	0
20109570	20108185	How to make an application with no interface?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        this.Opacity = 0; // prevent ALT-TAB preview\n        this.WindowState = FormWindowState.Minimized;\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n        const int WM_SYSCOMMAND = 0x0112;\n        const int SC_RESTORE = 0xF120;\n        const int SC_MAXIMIZE = 0xF030;\n\n        if ((m.Msg == WM_SYSCOMMAND) && ((int)m.WParam == SC_RESTORE || (int)m.WParam == SC_MAXIMIZE))\n        {\n            return;\n        }\n\n        base.WndProc(ref m);\n    }\n}	0
18010261	17987438	Show block as Selected in Autocad - C#	List<ObjectId> pid = new List<ObjectId>();\n//Add ObjectIds to the pid\nSelectionSet ss1 = SelectionSet.FromObjectIds(pid.ToArray());\ned.SetImpliedSelection(ss1)	0
12116649	12038341	Floating custom touch control in WPF	var myPopup = sender as Popup;\n\nHwndSource hwndSource = (HwndSource)PresentationSource.FromVisual((Visual)VisualTreeHelper.GetParent(myPopup.Child)); \n\nhwndSource.EnableSurfaceInput();	0
9111151	9110388	Web browser control: How to capture document events?	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);\n    }\n\n    private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)\n    {\n        mshtml.HTMLDocument doc;\n        doc = (mshtml.HTMLDocument)webBrowser1.Document;\n        mshtml.HTMLDocumentEvents2_Event iEvent;\n        iEvent = (mshtml.HTMLDocumentEvents2_Event)doc;\n        iEvent.onclick += new mshtml.HTMLDocumentEvents2_onclickEventHandler(ClickEventHandler);\n    }\n\n    private bool ClickEventHandler(mshtml.IHTMLEventObj e)\n    {\n        textBox1.Text = "Item Clicked";\n        return true;\n    }\n}	0
9494141	9494070	Accessing a Class property without using dot operator	class MyDouble {\n    public Value {get; private set;}\n    public Double(double value) {\n        Value = value;\n    }\n    // Other declarations go here...\n    public static implicit operator double(MyDouble md) {\n        return md.Value;\n    }\n    public static implicit operator MyDouble(double d) {\n        return new MyDouble(d);\n    }\n}	0
4461163	4457773	I need a event to detect Internet connect/disconnect	INetworkListManager.get_IsConnectedToInternet()	0
530595	530274	Memory management - should I worry about resizing a temporary array of long-lived objects within a state machine?	[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]\npublic static void Resize<T>(ref T[] array, int newSize)\n{\n    if (newSize < 0)\n    {\n        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));\n    }\n    T[] sourceArray = array;\n    if (sourceArray == null)\n    {\n        array = new T[newSize];\n    }\n    else if (sourceArray.Length != newSize)\n    {\n        T[] destinationArray = new T[newSize];\n        Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);\n        array = destinationArray;\n    }\n}	0
28426278	28395252	DataType for Saving Images in DataColumn of DataTable	DataTable dt = new DataTable();\n        DataColumn dc = new DataColumn("Column1");\n        dc.DataType = System.Type.GetType("System.Byte[]");\n        dt.Columns.Add(dc);\n        DataRow row = dt.NewRow();\n        var imageConverter = new ImageConverter();\n        row["Column1"] = imageConverter.ConvertTo(Properties.Resources._1, System.Type.GetType("System.Byte[]")); \n        dt.Rows.Add(row);\n       this.dataGridView1.DataSource = dt;	0
26680947	26639471	How to name methods and properties that traverse a tree as akin to moving down through a fully-expanded folder explorer?	F\n|-B\n| |-A\n| |-D\n|   |-C\n|   |-E\n|-G \n| |-I\n|   |-H	0
18521056	18521022	How do I Convert Func<T, object> to Func<dynamic, object>?	Format = dyn => format((T)dyn);	0
27305675	27305217	Obtain current page name in Xamarin Forms app	var name = this.GetType ().Name;	0
7752235	7752120	How to avoid losing receiver when sending notification?	var evt = PropertyChanged;\nif ( evt != null ) evt( this, new PropertyChangedEventArgs( name ) );	0
9829953	9829788	Best way to make a C++ software package and C# package access same enumeration/constant ints	C#\n_______\nC++/CLI\n_______\nC++	0
29709880	29709849	How to do findAll in the new mongo C# driver and make it synchronous	var collection = database.GetCollection<ClassA>(Collection.MsgContentColName);\nvar doc = collection.Find(filter).ToListAsync();\ndoc.Wait();\nreturn doc.Result;	0
25186508	25186018	cannot get datagridview to refresh data	dataGridView1.DataSource = _soureItemCollection;\ndataGridView1.Databind();	0
17491666	17491607	How can I randomly generate one of two values for a string?	var a = (new Random()).Next(2) == 0? "test" : "production";	0
11601351	11536540	How to display "Times new roman" font for Romanian language in pdf using iTextSharp	FontFactory.Register("c:\\windows\\fonts\\times.ttf");\n            StyleSheet st = new StyleSheet();\n            st.LoadTagStyle(HtmlTags.TABLE, "border", "1");\n            st.LoadTagStyle("body", "face", "times new roman");\n            st.LoadTagStyle("body", "encoding", "Identity-H");	0
31110	31088	What is the best way to inherit an array that needs to store subclass specific data?	abstract class Vehicle<T> where T : Axle\n{\n  public string Name;\n  public List<T> Axles;\n}\n\nclass Motorcycle : Vehicle<MotorcycleAxle>\n{\n}\n\nclass Car : Vehicle<CarAxle>\n{\n}\n\nabstract class Axle\n{\n  public int Length;\n  public void Turn(int numTurns) { ... }\n}\n\nclass MotorcycleAxle : Axle\n{\n  public bool WheelAttached;\n}\n\nclass CarAxle : Axle\n{\n  public bool LeftWheelAttached;\n  public bool RightWheelAttached;\n}	0
5712538	5712499	Remove whitespace within string	var s = "This   is    a     string    with multiple    white   space";\n\nRegex.Replace(s, @"\s+", " "); // "This is a string with multiple white space"	0
8747617	8747560	How to create an object from a single item from an xml file using linq?	XDocument doc = //load xml document here\n\nvar instance = from item in doc.Descendants("ElementName")\n                   select new YourClass()\n                              {\n                                  //fill the properties using item \n                              };	0
18265721	18265577	Timer Control in C# windows Form	if (atimer != null)\n  {\n      atimer.Stop();\n      atimer.Dispose();\n      atimer = null;\n  }\n\n  atimer = new System.Timers.Timer();\n  atimer.Interval = 5000;\n  atimer.AutoReset = false;\n  if (atimer.Enabled)\n  {\n      return;\n  }\n  else\n  {\n      atimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);\n      atimer.Enabled = true;\n\n  }	0
19871865	19870281	Refreshing PivotItem's DataContext on WP8	public class PageViewModel\n{\n   ViewModel LeftPivot {get; set;}\n   ViewModel CurrentPivot {get; set;}\n   ViewModel RightPivot {get; set;}\n\n   int SelectedPivotIndex {get; set;}\n}	0
11342049	11339236	Create dates between two date range values from c#	{\n            foreach (DataRow dr in dtDetails.Rows)\n            {\n                DateTime startingDate = Convert.ToDateTime( dr["fromdate"]);\n                DateTime endingDate = Convert.ToDateTime(dr["todate"]);\n                DateTime newdate;\n                for (newdate = startingDate; newdate <= endingDate; newdate = newdate.AddDays(1))\n                {\n                  DataRow dr2 = dt2.NewRow();\n                    dt2.Rows.Add(newdate);\n\n                }\n\n            }\n        }	0
25722980	25663033	how to compare two datetimepicker values in c#	private void dtpdob_ValueChanged(object sender, EventArgs e)\n  {\n      int year = DateTime.Today.Year - dtpdob.Value.Year;\n      int month = DateTime.Today.Month - dtpdob.Value.Month;\n      int day = DateTime.Today.Day - dtpdob.Value.Day;\n      var a = year.ToString();\n      var b = month.ToString();\n      var c = day.ToString();\n      if (day != 0 && month!=0 && year!=0)\n      {\n          if(day!=1)\n          txtage.Text = a + " Years " + b + " Months " + c + " Days ";\n          else\n              txtage.Text = a + " Years " + b + " Months " + c + " Day ";\n      }\n      else if (day == 0 && month == 0)\n          txtage.Text = a + " Years ";\n      else if (day == 0 && month != 0)\n          txtage.Text = a + " Years " + b + " Months ";\n      else\n          txtage.Text = a + " Years " + b + " Months " + c + " Days "; \n  }	0
2140563	2140527	Using Unicode characters in C# controls	lblOmega.Text = "?";	0
16921677	16921652	How to write a Json file in C#?	List<data> _data = new List<data>();\n_data.Add(new data()\n{\n    Id = 1,\n    SSN = 2,\n    Message = "A Message"\n});\nstring json = JsonConvert.SerializeObject(_data.ToArray());\n\n//write string to file\nSystem.IO.File.WriteAllText (@"D:\path.txt", json);	0
2163209	2163191	.NET URI: How can I change ONE part of a URI?	Uri uri = new Uri("http://stackoverflow.com/questions/2163191/");\n\nUriBuilder builder = new UriBuilder(uri);\nbuilder.Host += ".nyud.net";\n\nUri result = builder.Uri;\n// result is "http://stackoverflow.com.nyud.net/questions/2163191/"	0
12805514	12805188	retrieve single cell value from strongly typed data column using dataadapter	StronglyTypedDataTable dt = ta.GetUserByUserID(UserID);   \nStronglyTypedRow row = dt[0];\nvar value = row.ColumnName;	0
29196237	29196040	Give an Object a Method in C#	class Program\n{\n    static void Main()\n    {\n        Example e = new Example();\n        e.Name = "Hello World";\n        var x = e.Name;\n        var y = x.addTextToName();\n        Console.WriteLine(y);\n        Console.ReadLine();\n    }\n\n}\nclass Example\n{\n    public string _name;\n    public string Name\n    {\n        get { return _name; }\n        set { _name = value; }\n    }\n}\npublic static class MyExtensions\n{\n    public static string addTextToName(this string str)\n    {\n        return str += " - Test";\n    }\n}	0
966153	966086	using various types in a using statement (C#)	using (IDisposable cmd = new SqlCommand(), con = (cmd as SqlCommand).Connection)\n{\n   var command = (cmd as SqlCommand);\n   var connection = (con as SqlConnection);\n   //code\n}	0
28837670	28836273	Using VFP Reports within a C# .Net Web Application	PARAMETERS pcParmFromWebSite, pcBadParm1, pcBadParm2, pcBadParm3\n\nIF PCOUNT() > 1\n   */ Error out\n   return\nendif \n\nif PCOUNT() = 1 AND atc( "ExecScript", pcParmFromWebSite ) = 1\n   */ The "&" does macro substitution and will in-fact ISSUE the\n   */ ExecScript with the parameters is has inclusive with it.\n   &pcParmFromWebSite\n   return whatever...\nendif	0
6967339	6966730	EF Generate Database from Model Deletes Function Imports	%VSINSTALLDIR%\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\TablePerTypeStrategy.xaml	0
20370142	20367073	How can I pass the selected Kendo Menu Text to Controller	item.Add().Text("Home").Action("Index","Sample", new { text = "home" });\nitem.Add().Text("About Us").Action("Index", "Sample", new { text = "about us" });	0
16913949	16901647	Interchange positions of two buttons	void swapLocation()\n    {\n        var tmp = ActiveControl.Location;\n\n        if((ActiveControl.Location.X==b9.Location.X)&&(Math.Abs(b9.Location.Y-ActiveControl.Location.Y)<=60))\n            {\n             ActiveControl.Location = b9.Location;\n             b9.Location = tmp;\n            }\n        if ((ActiveControl.Location.Y == b9.Location.Y) && (Math.Abs(b9.Location.X-ActiveControl.Location.X) <= 70))\n            {\n            ActiveControl.Location = b9.Location;\n            b9.Location = tmp;\n            }\n        }	0
13462333	13462272	Setting DataGrid StringFormat in C#	var binding = new Binding("MyDate");\n\nbinding.StringFormat = "MM/dd/yyyy";\ntextColumn.Binding = binding;	0
25525422	25525211	Regex to extract domain from a url	var uri = new Uri("www.Edmunds.com/Toyota_Camry_Hybrid");\nConsole.WriteLine(uri.Host);	0
19112036	19021193	Window.open navigates parent page to codeline url	rh.NavigateUrl = "javascript:void(window.open('default.aspx','Graph','height=600,width=900'););";	0
8591784	8591461	Getting content of a tag in LINQ to XML with namespaces	XNamespace bat = @"urn:x-commerceone:document:btsox:Batch.sox$1.0";\nXNamespace ns  = @"urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0";\n\nstring date = baseXML.Descendants(bat + "Batch").Elements(ns + "PurchaseOrder").Elements(ns + "OrderHeader").Elements(ns + "POIssuedDate").First().Value;	0
33101167	33099091	UWP Build on Jenkins	nuget.exe restore [MyApp.sln]	0
8868359	8868314	change the backcolor in a datagridview	void ColorGrid()\n{\n     foreach (DataGridViewRow row in dataGridView1.Rows) \n     {\n        if (row.Cells[5].Value.ToString() == "ok") \n        {\n            row.DefaultCellStyle.BackColor = Color.Green; \n        }\n        else\n        {\n            row.DefaultCellStyle.BackColor = Color.Red; \n        }\n     }\n}	0
21826599	21826529	C# How to check Remote IP Address from the Local Network	bool CheckConnectionStatus()\n{\n    String strConnection="/*your connection string here*/";\n    SqlConnection con = new SqlConnection(strConnection);\n    if(con.State == ConnectionState.Closed)\n    {\n       try\n      {        \n       con.Open();\n       con.Close();\n      }\n       catch(Exception e)\n      {\n        return false;\n      }\n    }\n    else\n   {\n    return true;\n   }\n}	0
203613	201518	Removing CSS Class Attribute From Tag in a Custom Server Control	private string _heldCssClass = null;\npublic override void RenderBeginTag(HtmlTextWriter writer)\n{\n   writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);   \n   writer.RenderBeginTag("span");\n   _heldCssClass = this.CssClass;\n   this.CssClass = String.Empty;\n   base.RenderBeginTag(writer);\n}\n\npublic override void RenderEndTag(HtmlTextWriter writer)\n{\n   writer.RenderEndTag();\n   base.RenderEndTag(writer);\n   this.CssClass = _heldCssClass;\n}	0
5664400	5664345	String to Binary in C#	public static byte[] ConvertToByteArray(string str, Encoding encoding)\n{\n    return encoding.GetBytes(str);\n}\n\npublic static String ToBinary(Byte[] data)\n{\n    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));\n}\n\n// Use any sort of encoding you like. \nvar binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));	0
16490500	16490463	How is local determined in ToLocalTime()	ToLocalTime()	0
11991935	11981432	How do I use a C# generated RSA public key in Android?	new BigInteger(1, modulus)	0
12944485	12944311	Windows 8 App Textbox Data binding not working	public class GameInfo : INotifyPropertyChanged\n{\n    private int _score;\npublic int Score\n{\n  get\n  {\n    return this._score;\n  }\n\n  set\n  {\n    if (value != this._score)\n  {\n    this._score = value;\n    NotifyPropertyChanged("Score");\n  }\n}\n\n  }    \npublic int counter = 0; // if you use _score, then you don't need this variable.\n    public event PropertyChangedEventHandler PropertyChanged;\n\n     private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n\n}	0
16210519	16057428	Connection Property in EF5	var sConnection = ((dataContext)ctx.Database.Connection);	0
15142952	15142885	Dynamically Invoke Method from method name string?	public string GetResponse()\n{\n    string fileName = this.Page.Request.PathInfo;\n    fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);\n\n    MethodInfo method = this.GetType().GetMethod(fileName);\n    if (method == null)\n        throw new InvalidOperationException(\n            string.Format("Unknown method {0}.", fileName));\n    return (string) method.Invoke(this, new object[0]);\n}	0
32010444	32008441	Regex to find <input with name>	(?<1><\s*input\s+[^>]*)(?:(?<2>\s*type\s*=\s*)(?<3>[""'])(?<4>[^>\s]*)(?<5>\3))(?:(?<6>\sname\s*=\s*)(?<7>[""'])(?<8>find_me)(?<9>[^>\s]*)(?<10>\3))(?<11>[^>]*>)	0
23286256	23279264	How to update a datagridview with updated sql table in C#?	yourDataGridView.DataSource=null;\nyourDataGridView.DataSource=dt;	0
6065304	6052678	Excel interop works on machine with Office 2007 but fails on machine with Office 2010	Microsoft.Office.Interop.Excel	0
1158916	1158236	How to do the following in LINQ	someDate = new DateTime(2009, 4, 1);\n\nvar query = \nfrom a in List\nwhere a.Category == "General"\nwhere a.Description == "Cover"\nwhere a.Item == "Type"\nwhere a.EffectiveDate < someDate\nlet minDate =\n(\n  from b in List\n  where a.Value == b.Value\n  where a.Category == b.Category\n  where a.Description == b.Description\n  where a.Item == b.Item\n  where a.EffectiveDate < b.EffectiveDate\n  orderby b.EffectiveDate\n  select new DateTime? ( b.EffectiveDate )\n).FirstOrDefault()\nwhere !minDate.HasValue || someDate < minDate.Value\norderby a.SortOrder\nselect a;	0
7938751	7938729	c# reflection current of runtime parameter values	MethodBase.GetParameters	0
26103224	26102772	EF Linq - how to select children in same query?	//I only use this bc I don't know the full schema.\nclass DTOCompany {\n  public int ID {get;set;}\n  public List<Orders> Orders {get;set;}\n}\n\npublic List<Companies> GetCompaniesOrders() {\n\n  using (var db = new Entities()) {\n    return db.Companies\n      .AsEnumerable() //may not be needed.\n      .Join(db.Orders,\n        c => CompanyId,\n        o => o.CompanyId,\n        (c,o) => new { Company = c, Orders = o})\n      )\n      .Select(co => new DTOCompany() {\n        ID = co.Companies.CompanyId,\n        Orders = co.Orders.ToList()\n      })\n      .ToList();\n  }\n}	0
15777453	15777378	Concepts on MVP with DDD	public class CodeBehindPage : System.Web.UI.Page, IViewInterface {\n    private Presenter myPresenter;\n\n    public CodeBehindPage() {\n        myPresenter = new Presenter(this); // Presenter will require IViewInterface\n    }\n}	0
2083973	2083959	create a c# datatable object with GUID as identifier?	// Create a new DataTable and set two DataColumn objects as primary keys.\n   DataTable myTable = new DataTable();\n   DataColumn[] keys = new DataColumn[1];\n   DataColumn myColumn = new DataColumn();\n   myColumn.DataType = System.Type.GetType("System.Guid");\n   myColumn.ColumnName= "ID";\n   // Add the column to the DataTable.Columns collection.\n   myTable.Columns.Add(myColumn);\n   keys[0] = myColumn;\n   // Set the PrimaryKeys property to the array.\n   myTable.PrimaryKey = keys;	0
23364944	23364847	Wpf datagrid auto-increment column generating wrong values?	private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        var serial = new VLANS();\n        vlan.Add(serial)\n        serial.S_No = vlan.Count;\n        serial.VlanName = t1.Text;\n        vlan.Add(serial);\n\n    }	0
9620396	9619886	Can I create an abstract base class UserContol so derived .ascx must implement certain controls?	if(controlType == "Type1")	0
2268438	2268420	Check if a file exist in the Server in ASP.NET	if (!System.IO.File.Exists(Server.MapPath(jSFile)))	0
6423437	6423417	Regular Expression Validation - Range Validation with minium length value and undefinited maximum length	ValidationExpression="^.{64,}$"	0
10857781	10857131	How to choose which properties EditorFor displays on Views	[ScaffoldColumn(false)]\npublic int ID { get; set; }\n\n[ScaffoldColumn(false)]\npublic DateTime ModifiedSince { get; set; }	0
28332414	28332308	Web API displaying multiple results for one input value/id	public IHttpActionResult GetProduct(int id)\n{\n    var product = products.Where(p => p.Id == id).ToList();\n    if (product == null) {\n        return NotFound();\n    }\n    return Ok(product);\n}	0
8504627	8504415	How to convert .aspx to pdf using C#?	string url= @"http://www.google.com";\n\ntry\n{\nSystem.Diagnostics.Process process = new System.Diagnostics.Process();\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.FileName = Server.MapPath("~/bin/") + "wkhtmltopdf.exe";\nprocess.StartInfo.Arguments = "\""+ url+ " " + Server.MapPath("~/PDFFiles/") + "test.pdf\"";\n\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.StartInfo.RedirectStandardError = true;\nprocess.Start();\nprocess.WaitForExit();\n\n}\ncatch (Exception ee)\n            {\n        //logging\n            }	0
16898933	16898760	Checked_Change Event of programatically generated Checkbox inside GridView Row	protected void Page_Load(object sender, EventArgs e)\n        {\n            List<string> names = new List<string>();\n            names.Add("Jhonatas");\n\n            this.GridView1.DataSource = names;\n            this.GridView1.DataBind();\n\n            foreach (GridViewRow gvr in GridView1.Rows)\n            {\n                //add checkbox for every row\n                TableCell cell = new TableCell();\n                CheckBox box = new CheckBox();\n                box.AutoPostBack = true;\n                box.ID = gvr.Cells[0].Text;\n\n                box.CheckedChanged += new EventHandler(box_CheckedChanged);\n                cell.Controls.Add(box);\n                gvr.Cells.Add(cell);\n            }\n        }\n\n        void box_CheckedChanged(object sender, EventArgs e)\n        {\n            string test = "ok";\n        }	0
5675363	5675211	Regular expression to find specific words in a text file in C#?	string pattern = "car";\nRegex rx = new Regex(pattern, RegexOptions.None);\nMatchCollection mc = rx.Matches(inputText);\n\nforeach (Match m in mc)\n{\n    Console.WriteLine(m.Value);\n}	0
23363872	23363673	C# regex with a certain word and hashtags	content = Regex.Replace(content, @"\B##companyname##\B", setup.Company, RegexOptions.IgnoreCase);	0
9609277	9609182	Determine application home location	static void Main()\n{\n\n  var AsmPath =System.IO.Path.GetDirectoryName( \n    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) ;\n\n   var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\n\n  if (AsmPath == desktopPath)\n  (\n      MessageBox.Show ("You can only run this from the desktop");\n      Application.Exit();\n  )\n  else \n       Application.Run(new Form1());\n}	0
18163978	18163919	How to search through multiple sets with one linq statement	bool result = listOfLists.SelectMany(x => x)\n                         .Concat(collectionA)\n                         .Concat(collectionB)\n                         .Any(x => x == "Item5");	0
20732629	20732533	what is there equivalent to rollback transaction of SQL in c#?	using (SqlConnection connection = new SqlConnection("connection string"))\nusing (SqlTransaction transaction = connection.BeginTransaction())\nusing (SqlCommand command = new SqlCommand("command text", connection) { Transaction = transaction })\n{\n    connection.Open();\n    try\n    {\n        command.ExecuteNonQuery();\n        transaction.Commit();\n    }\n    catch\n    {\n        transaction.Rollback();\n        throw;\n    }\n}	0
507525	506492	How to open files from explorer into different tabs	static void Main() \n{\n   if(SingleInstance.SingleApplication.Run() == false)\n   {\n      return;\n   }\n   //Write your program logic here\n}	0
346493	346297	Setting Default Namespace in Visual Web Developer 2008 Express	namespace MyDefaultNamespace {\n   // original code\n}	0
17954561	17953581	Get Numbers from file name	string input = "X_X_FY13_Template_X_6 4 13_V2.xlsx";\nstring result = input.Split('_').Where(x => x.Contains(' ')).FirstOrDefault();\nif(!String.IsNullOrEmpty)\n   result = result.Replace(" ","");	0
29793397	29793341	Create a new object each loop	List<Meal> mList = new List<Meal>();\nwhile (oReader.Read())\n{\n    Meal m = new Meal();\n    m.mealID = Convert.ToInt32(oReader["mealId"]);\n    m.mealName = oReader["mealName"].ToString();\n    m.quantity = Convert.ToInt32(oReader["quantity"]);\n    m.timeToProduce = Convert.ToInt32(oReader["timeToProduce"]);\n    m.availability = true;\n    mList.Add(m);\n}	0
1579539	1579475	Simple regex - replace quote information in forum topic in C#	string pattern = @"\[quote=(.*?)\|(\d+)\]([\s\S]*?)\[/quote\]";\nstring replacement = \n  @"<div class=""quote"">$3<div><a href=""users/details/$2"">$1</a></div></div>";\n\nConsole.WriteLine(\n    Regex.Replace(input, pattern, replacement));	0
28262465	28262121	find and replace in file xml	Dictionary<string, string> wordsToReplace = new Dictionary<string, string>();\n        wordsToReplace.Add("Test1", "amir");\n        wordsToReplace.Add("Test2", "amir1");\n        wordsToReplace.Add("Test3", "amir3");\n        wordsToReplace.Add("Test4", "amir4");\n        wordsToReplace.Add("Test5", "amir5");\n        wordsToReplace.Add("Test6", "amir6");\n        string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");\n\n        foreach (var pair in wordsToReplace)\n        {\n            //Performs each replacement\n            strVal = strVal.Replace(pair.Key, pair.Value);\n        }\n        File.Copy(Path.Combine(filePath), Path.Combine(filePath2));\n        System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);\n        ProcessRequest(filePath2, Lcourseid.Text);	0
1077984	1077938	WPF - how to handle mouse events outside component which raised that event?	Window1.DrawingCanvas.MouseLeftButtonDown += YourHandlerMethod;	0
15989573	15987496	Automatically escaping characters within strings	public string FixEscapeCharacterSequence(string query)\n    {\n        query = query.Replace("'", "\'");\n        //..Any other replace statements you need\n        //....\n\n        return query;\n    }	0
31701094	31700976	"Insert item into a list inside a list	var personToEdit = _person[stuff]; // You said 'stuff' is your index\n\npersonToEdit.Blocks.Add(block);	0
33483182	33483123	Make a message box only pop up once in c#	bool needAlert = false;\n\nforeach (char c in fileToCopySource)\n{\n    if (fileToCopySource.Contains(c))\n    {\n        needAlert = true;\n        break; // no more looping needed.\n    }\n}\n\nif(needAlert) MessageBox.Show("FOO"); // notify user that the inputDirectory isn't valid	0
21510610	21497771	How to add roles from database	protected void Application_PostAuthenticateRequest(object sender, EventArgs e)\n    {\n        var context = HttpContext.Current;\n        if (context.Request.IsAuthenticated)\n        {\n            string[] roles = LookupRolesForUser(context.User.Identity.Name);\n            var newUser = new GenericPrincipal(context.User.Identity, roles);\n            context.User = Thread.CurrentPrincipal = newUser;\n        }\n    }\n\n    #region helper\n\n    private string[] LookupRolesForUser(string userName)\n    {\n        string[] roles = new string[1];\n        CosmosMusic.Models.korovin_idzEntities db = new CosmosMusic.Models.korovin_idzEntities();\n        var roleId = db.Users.Where(x => x.username == userName).FirstOrDefault().id_role;\n        roles[0] = db.Role.Where(y => y.id_role == roleId).FirstOrDefault().name;\n\n        return roles;\n    }\n    #endregion	0
24510389	24508975	How to mock SendGrid	var transport = new Mock<ITransport>();\ntransport.SetupAllProperties();\ntransport.Setup(x => x.DeliverAsync(It.IsAny<SendGridMessage>())).ReturnsTask();\n\nvar em = new EmailManager(transport.Object);	0
2183907	2183769	How to get Item web client id in Exchange 2007 using EWS Managed API	ExchangeService service = new ExchangeService();\nEmailMessage message = EmailMessage.Bind(new ItemId("someId"));\nvar alternateId = new AlternateId();\nalternateId.UniqueId = message.Id.UniqueId;\nalternateId.Mailbox = "somemailbox";\nalternateId.Format = IdFormat.EwsId;\n\nvar convertedId = service.ConverId(alternateId, Format.OwaId) as AlternateId;	0
33502418	33502001	a faster way of decompressing a large zip file	public static string[] UnpackZip(string file, string targetDirectory)\n    {\n        Process p = new Process();\n        string unzip = "x -y \"-o" + targetDirectory + "\" \"" + file + "\" ";\n        p.StartInfo.FileName = "7z.exe";\n        p.StartInfo.Arguments = unzip;\n        p.Start();\n        p.WaitForExit();\n        if (p.ExitCode != 0)\n            throw new Exception("Errore durante l'unzip " + p.ExitCode + " - " + unzip);\n        return Directory.GetFiles(targetDirectory);\n    }	0
4431518	4181802	How can I allow sql to set datetime with subsonic	public partial class Products\n{\n    protected override void BeforeInsert()\n    {\n        Schema.GetColumn(Columns.CreatedOn).IsReadOnly = true;\n        base.BeforeInsert();\n        Schema.GetColumn(Columns.CreatedOn).IsReadOnly = false;\n    }\n\n    protected override void BeforeUpdate()\n    {\n        Schema.GetColumn(Columns.ModifiedOn).IsReadOnly = true;\n        base.BeforeUpdate();\n        Schema.GetColumn(Columns.ModifiedOn).IsReadOnly = false;\n    }\n}	0
2246724	2246694	How to Convert JSON object to Custom C# object?	public class User\n{\n    public User(string json)\n    {\n        JObject jObject = JObject.Parse(json);\n        JToken jUser = jObject["user"];\n        name = (string) jUser["name"];\n        teamname = (string) jUser["teamname"];\n        email = (string) jUser["email"];\n        players = jUser["players"].ToArray();\n    }\n\n    public string name { get; set; }\n    public string teamname { get; set; }\n    public string email { get; set; }\n    public Array players { get; set; }\n}\n\n// Use\nprivate void Run()\n{\n    string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";\n    User user = new User(json);\n\n    Console.WriteLine("Name : " + user.name);\n    Console.WriteLine("Teamname : " + user.teamname);\n    Console.WriteLine("Email : " + user.email);\n    Console.WriteLine("Players:");\n\n    foreach (var player in user.players)\n        Console.WriteLine(player);\n }	0
4727840	4727808	How to get all values of check boxes on button click asp.net	for each item as repeater in repeater.items\n\n checkbox = (CheckBox)item.findcontrol("checkboxid")\n\n if checkbox.checked\n  checkedBoxes.add(checkbox)\n end if\n\nend for	0
3729695	3727174	Deserializing a List of messages with protobuf-net	IEnumerable<SomeObject> list =  (Serializer.DeserializeItems<SomeObject>(memoryStream, PrefixStyle.Base128, 0));	0
16645664	16645462	C# insert datetime to DBF file	using(OdbcConnection dbfConn = new OdbcConnection())\n{\n    dbfConn.ConnectionString = @"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;Exclusive=No;Collate=Machine;NULL=NO;DELETED=YES;BACKGROUNDFETCH=NO;SourceDB=" + path;\n    dbfConn.Open();\n    OdbcCommand oCmd = dbfConn.CreateCommand(); // needed to query data\n    oCmd.CommandText = "INSERT INTO " + fileName + " +\n        "(tax_month,seq_no,tin,registered_name,last_name,first_name,middle_name,address1," + \n        "address2,gpurchase,gtpurchase,gepurchase,gzpurchase,gtservpurchase,gtcappurchase," + \n        "gtothpurchase,tinputtax,tax_rate) VALUES (" + \n        "?, 3, '222333445','TEST COMPANY','','','','DI MAKITA STREET','MANDALUYONG 1602', " + \n        "52107.14, 49107.14, 1000, 2000, 3000, 4000, 42107.14, 5892.86, 12)"\n    oCmd.Parameters.Add("@p1", OdbcType.DateTime).Value = tax_month;\n    int inserted = oCmd.ExecuteNonQuery();\n}	0
14991675	14967525	Regular expression to detect hidden DML(insert, update, delete) statements in a DDL(create, alter, drop) .sql script	var regex1 = new Regex(@"\n          (?s)\n          (create|alter|drop).+?\n          begin\n            (?:\n               (?> (?! begin | end ) .\n                  | begin (?<counter>)\n                  | end  (?<-counter>)\n                )*\n            )\n            (?(counter)(?!))\n          end\n          "\n        , RegexOptions.IgnorePatternWhitespace\n        );\n\n        var regex2 = new Regex(@"(?:insert|update|delete).+");\n\n        var result = regex2.Matches(regex1.Replace(your_input, ""))\n            .Cast<Match>()\n            .Select(m => m.Value);	0
19252347	19252013	Simple HTTP POST with an anonymous type as body	var postBody = new\n{\n   friend = new \n   {\n      name = "dave",\n      last ="franz"\n   },\n   id = "12345",\n   login = "mylogin" \n};\nvar postString = Newtonsoft.Json.JsonConvert.SerializeObject(postBody);\nusing(var wc = new WebClient())\n{\n    wc.Headers.Add("Content-Type", "application/json");\n    var responseString = wc.UploadString(serviceAddress, "POST", postString);\n}	0
27009886	27009729	Query aggregation with List of Objects	var result = report.SelectMany(x => x.OrderList)\n                               .GroupBy(x => x.OrderDate.Date)\n                               .Select(x => new\n                                   {\n                                       OrderDate = x.Key,\n                                       OrderCount = x.Count()\n                                   });	0
21771369	19946190	How to make a query on multiple(joined) Tables using Azure Mobile Services with windows phone 8?	CREATE mySchema.myView AS\nSELECT * FROM Table t1 INNER JOIN OtherTable t2 ON t1.a=t2.b	0
29093132	29092579	DisplayIndex Makes Button Move	dataGridview.AutoGenerateColumns = false;	0
28400300	28399682	POST single string Web API	var content = new FormUrlEncodedContent(new Dictionary<string, string> {\n{"value" , "buttonOne"} })	0
4332496	4332458	How to wait until a process terminates before continuing to execute - C#	pprocess.WaitForExit();\nbreak;	0
1192560	1192543	Drawing a contrasted string on an image	just draw the string 5 times.\n One time 1(or2) pixels to the left in black\n One time 1(or2) pixels to the right in black\n One time 1(or2) pixels above it in black\n One time 1(or2) pixels below it in black\n and the final time in white on the place where you want it	0
17893573	17893493	C# Showing all rows from a database table to DataGrid	ORDER BY date DESC	0
15140592	15140400	Regular expression to add a space before the last in a sequence of consecutive capital letters	string output=Regex.Replace(input, @"(?<=[A-Z]{2})(?=[A-Z][^A-Z]|[A-Z]$)", " ");	0
26769754	26769666	How to validate input on overloaded constructors?	public MyClass(int points)\n{\n    if (points < 0)\n        throw new ArgumentOutOfRangeException("points must be positive");\n    Init(points, points);\n}\n\npublic MyClass(int leftPoints, int rightPoints)\n{\n    if (leftPoints < 0)\n        throw new ArgumentOutOfRangeException("leftPoints must be positive");\n    if (rightPoints < 0)\n        throw new ArgumentOutOfRangeException("rightPoints must be positive");\n    Init(leftPoints, rightPoints);\n}\n\nprivate void Init(int leftPoints, int rightPoints)\n{\n    LeftPoints = leftPoints;\n    RightPoints = rightPoints;\n}	0
18063359	18062701	trying to center a Picturebox C#	pictureBox.Location = new Point(x - pictureBox.Size.Width/2, y - pictureBox.Size.Height/2);	0
20351721	20351171	Filter and load string to a listbox	string[] lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + @"\fil.txt");\n\n        int ctr = 0;\n\n        foreach (var item in lines)\n        {\n            string tmp = item;\n\n            tmp = tmp.Replace("127.0.0.1", "");\n            tmp = tmp.Replace("http://", "");\n            tmp = tmp.Replace("www.", "");\n            tmp = tmp.Trim();\n\n            if (ctr < lines.Length)\n            {\n                lines[ctr] = tmp;\n                ctr++;\n            }\n\n        }\n\n        //to skip initial lines\n        var result = lines.Skip(3).Distinct();	0
6602353	6472897	How to verify a remote DSN entry?	oRegConn = new ConnectionOptions();\noRegConn.Username = username;\noRegConn.Password = password;\nscope = new ManagementScope(@"//" + servername + @"/root/default", oRegConn);\nregistry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);\n\ninParams = registry.GetMethodParameters("GetStringValue");\ninParams["sSubKeyName"] = "SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources\\" + \n    dsnName;\ninParams["sValueName"] = "Server";\n\noutParams = registry.InvokeMethod("GetStringValue", inParams, null);\nserver = outParams["sValue"].ToString();	0
11931974	11931837	Image button position using css	.wrapper {\n  width: 800px;\n  height: 800px;\n}\n\n.row {\n  display: block;\n}\n\n.box {\n  width: 200px;\n  height: 200px;\n  margin: 10px;\n  background: #000000;\n}\n\n.offset1 {\n  margin-left: 210px;\n}\n\n.offset2 {\n  margin-left: 420px;\n}???	0
17392719	17392703	JSON show only the value without the key	new { \n    question.Text,\n    Answers = question.Answers.Select(a => a.Text)\n}	0
16521699	16521302	WPF can't remove a file	BitmapImage bi = new BitmapImage();\n        bi.BeginInit();\n        bi.UriSource = new Uri(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename);\n        bi.CacheOption = BitmapCacheOption.OnLoad;\n        bi.EndInit();\n        imgScreenshot.Source = bi;\n        File.Delete(ShellFolder.DocumentsFolder() + System.IO.Path.DirectorySeparatorChar + screenshot.Filename);	0
6766069	6766040	how to get a string manipulation?	string x = "490.00 001.09 987.1 876.99";\n\n string[] parts = x.Split();\n\n string x1 = parts[0];\n string x2 = parts[1];\n string x3 = parts[2];\n string x4 = parts[3];	0
33506061	33505154	DataGridView with XML - "Merging" child records	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        const string FILENAME = @"c:\temp\test.xml";\n        static void Main(string[] args)\n        {\n            XDocument doc = XDocument.Load(FILENAME);\n\n            var results = doc.Element("parent").Elements().Select(x => new\n            {\n                name = x.Name,\n                property1 = x.Attribute("property1").Value,\n                property2 = x.Attribute("property2").Value,\n                child_property1 = x.Element("optionalchild") == null ? null : x.Element("optionalchild").Attribute("property1").Value,\n                child_property2 = x.Element("optionalchild") == null ? null : x.Element("optionalchild").Attribute("property2").Value\n            }).ToList();\n\n        }\n    }\n}\n???	0
13110928	13110800	Asynchronous image drawing with OpenTK	foreach(var command in commands)\n{\n    Task<int>.Factory.StartNew(ExecuteCommand)\n        .ContinueWith(\n            t => Invalidate(t.Result),\n            CancellationToken.None,\n            TaskContinuationOptions.PreferFairness,\n            TaskScheduler.FromCurrentSynchronizationContext());\n}\n\n\nprivate void Invalidate(int heightMap)\n{\n    area.heightMap = eightMap;\n    glControl1.Invalidate();\n}\n\nprivate int ExecuteCommand()\n{\n    // returns new heightMap, because it's executes in non-UI thread\n    // you can't set UI control property\n    return Execute(area.heightMap, sim);\n}	0
15748788	15748420	Getting notified about program termination	public  void  CheckProc() \n    {\n        while (true)\n        {\n            if (process.HasExited == true)\n            {\n                MessageBox.Show("Process done successfully!");\n                break;\n            }\n\n        }\n    }	0
13125723	13125692	How to get data from dataset without linq?	if(_Data.Tables.Count > 0 && _Data.Rows.Count > 0 && _Data.Columns.Count > 0)\n {\n        string row0col0Data = _Data.Tables[0].Rows[0].Cols[0].ToString();\n }	0
2601768	2601670	Using generics to make an algorithm work on lists of "something" instead of only String's	private static IEnumerable<T> pairSwitch<T>(IEnumerable<T> input)\n    {\n        T current = default(T);     // just to satisfy compiler\n        bool odd = true;\n        foreach (T element in input)\n        {\n            if (odd) current = element;\n            else\n            {\n                yield return element;\n                yield return current;\n            }\n            odd = !odd;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        string test = "Hello";\n        string result = new string(pairSwitch(test).ToArray());	0
21485646	21485060	Populating Dropdown using Reflection	// Get one instance and then iterate all the properties\nvar selectListItems = new List<object>();\nvar first = db.BloodStore.First();\nforeach(var item in first.GetType().GetProperties()){\n    selectListItems.Add(new (){ Text = item.Name});\n}\n\nViewBag.SearchFields = selectListItems;	0
12603707	12603589	using xmlReader	String Mainxmltext = "<ClosedKPICalls>" +\n        "<ServiceInfo>  <ServiceNo>HR011</ServiceNo> <ServiceName>Petty cash</ServiceName>    " +\n        "<RecCount>0</RecCount>  <RegdKPI>2</RegdKPI>  </ServiceInfo> </ClosedKPICalls>";\n\nString xmlinnerText = "<TaskDetails> <name>Jhone</name> <Description>just for testing</Description> </TaskDetails>";\n\nXDocument xDoc = XDocument.Parse(Mainxmltext);\nxDoc.Root.Add(XElement.Parse(xmlinnerText));\nvar newxml = xDoc.ToString();	0
1674963	1674947	Get property value dynamically	prop.GetValue(item, null);	0
31733495	31733088	Linq Group By statement on a Dictionary containing a list	public class RICData\n{\n        public string PubDate { get; set; }\n        public string Settle { get; set; }\n        public int ColorDer { get; set; }\n}\n\npublic class NewRICData\n{\n        public string Label { get; set; }\n        public string Settle { get; set; }\n        public int Colorder { get; set; }\n}\n\nvar oldDict = new Dictionary<string, List<RICData>>();\n\nvar newDict = oldDict.SelectMany(pair => pair.Value.Select(data => new\n    {\n        PubDate = DateTime.Parse(data.PubDate), \n        NewRICData = new NewRICData\n        {\n            Label = pair.Key, \n            Settle = data.Settle, \n            ColorDer = data.ColorDer\n        }\n    }))\n    .GroupBy(x => x.PubDate.Date)\n    .ToDictionary(group => group.Key.ToString("d"), \n                  group => group.Select(x => x.NewRICData)\n                                .OrderBy(x => x.ColorDer));	0
23949895	19269851	C# Excel DateTime Export	//create the empty array\n    var result = new object[data.Count, data[0].Count];\n    //insert all of the values in it\n    for (int i = 0; i < data.Count; i++)\n    {\n        for (int j = 0; j < data[i].Count; j++)\n        {\n            if (j < data[i].Count)\n                result[i, j] = data[i][j];\n            else\n                result[i, j] = " ";\n        }\n    }\n\n    //change the date time values to doubles which are \n    //in the first column after the first entry\n    for (int i = 1; i < data.Count; i++)\n    {\n        result[i, 0] = (Convert.ToDateTime(result[i, 0])).ToOADate();\n    }\n\n        return result;	0
16331616	16076748	Identify rgb and cmyk color from pdf	PdfReader reader_FirstPdf = new PdfReader(pdf_of_FirstFile);\n\n\n            for (int i = 1; i <= reader_FirstPdf.NumberOfPages; i++)\n            {\n TextWithFont_SourcePdf Sourcepdf = new TextWithFont_SourcePdf();\n}\n                text_First_File = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader_FirstPdf, i, Sourcepdf);\n\n\n            public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)\n            {\n int r = renderInfo.GetColorNonStroke().R;\n                  int g = renderInfo.GetColorNonStroke().G;\n                   int b = renderInfo.GetColorNonStroke().B;\n\n}	0
2405707	2401424	How to set a custom id for listitems in BulletedList control while binding?	private void BindBulletList()\n     {\n         List<string> list = new List<string>();\n         list.Add("item1");\n         list.Add("item2");\n         list.Add("item3");\n         list.Add("item4");\n         list.Add("item5");\n\n         bullets.DataSource = list;\n         bullets.DataBind();\n\n         foreach (ListItem item in bullets.Items)\n         {\n             item.Attributes.Add("Id", "li_" + item.Text);\n         }\n\n\n     }	0
17053385	17053264	get part of a Computers name	String machinename = System.Environment.MachineName;\n\nif(machinename.ToUpper().Contains("SERVER"))\n{\n\n}\nelse if (machinename.ToUpper().Contains("CLIENT"))\n{\n\n}	0
29436133	29435946	How to convert Specific string into a specific int	public static int ConvertDayOfWeek(string day) {\n    List<string> days = new List<string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};\n    return days.IndexOf(day);\n}	0
9645683	9645280	Parsing token in HTTP Response body using C#	String.Split("\n").Where(l=>l.Contains("=")).Select(l=l.Split("=")).Where(li=>li.Length==2).Where(li=>li[0].ToLower()=="auth").Select(li=>li[1]).SingleOrDefault();	0
12329297	12329105	How to compare items between two disordered ListBox	var hashSet1 = new HashSet<string> { "C++", "C#", "Visual Basic" };\nvar hashSet2 = new HashSet<string> { "C#", "Visual Basic", "C++" };\n\nvar result = hashSet1.SetEquals(hashSet2);	0
24555153	24555106	How to read XML header information using Linq to XML	XElement rootelement = XElement.Load(@"path_to_your_file") ;\n\nvar name = rootElement.Attribute("name").Value ; \nvar classname = rootElement.Attribute("class").Value ; \nvar module = rootElement.Attribute("module").Value ;	0
4112889	4112550	Undesired termination of Thread created in Timer callback	static volatile bool SYNC_IN_PROGRESS; \n    static thread syncPoll; \n\n    public void StartSync() \n    { \n        SYNC_IN_PROGRESS = false; \n        syncPoll = new Thread(sync);\n        syncPoll.Start();\n    } \n\n    void sync() \n    { \n        while (true)\n        {\n             Debug.WriteLine("Sync?");\n             if (SYNC_IN_PROGRESS) Debug.WriteLine("Syncing..."); \n             Thread.Sleep(1000);\n        }\n    }	0
7853265	7844230	How Can I define Nullable EntitySet<>?	public Product()\n    {\n        this._Order_Details = new EntitySet<Order_Detail>(new Action<Order_Detail>(this.attach_Order_Details), new Action<Order_Detail>(this.detach_Order_Details));\n        this._Category = default(EntityRef<Category>);\n        this._Supplier = default(EntityRef<Supplier>);\n        OnCreated();\n    }	0
5189247	5189143	Help with Regular Expression in C#	(?<number>\d{5})_\n(?<text>STARTED|CLOSED|OPENED|NOT-OK)_\n(?<date>(19|20)[0-9]{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]))_\n(?<time>(20|21|22|23|[0-1]\d)[0-5]\d[0-5]\d).xml	0
14960139	14960048	Points on a circle by angle not spaced evenly	float x = origin.X + radius * (float)Math.Cos(i*Math.PI/180.0);\nfloat y = origin.Y + radius * (float)Math.Sin(i*Math.PI/180.0);	0
24373861	24373833	Can one use a list to find a collection of rows in a query?	List<string> firstList = .....;\nvar query = dataTable2.AsEnumerable()\n              .Where(r => firstList.Contains(r.Field<string>("IdColumn")));	0
32127695	32127621	passing a parameter from jQuery ajax call to C# method in web forms	data: JSON.stringify({QuestionNumber: QuestionNumber}),\n    dataType: "json",	0
4283241	4283157	how to convert ip address to url with VB.NET OR C#	IPHostEntry IpEntry = Dns.GetHostByAddress(ip); \n return iphostentry.HostName.ToString();	0
30829495	30825998	Xamarin: How to get HTML from page in WebView?	webView.EvaluateJavascript ("document.body.innerHTML")	0
11230727	8768775	C# & XLW 5 - how to raise an exception with sensible error message displayed in Excel?	private static cellMatrixException ReportMessage(string errorMessage, string mainCategory, string minorCategory)\n{\n    var theContent = new ArgumentList(mainCategory);\n    theContent.add(minorCategory, errorMessage);\n    return new cellMatrixException(errorMessage, theContent.AllData());\n}	0
16325202	16325047	How to Secure WebAPI with Single-Page	'/api/myController/myRestrictedAction/123'	0
2196864	2196824	How to Handle a Long Description Line For Interface Function	[Description(@"Line 1 description content here!  \n Line 2 description content here!\n Line 3 description content here! \n Line 4 description content here!\n Line 5 description content here! \n Line 6 description content here!")] \nvoid foo() \n{ \n}	0
34418402	34418149	Pass Interface as Parameter	class SomeClass\n{\n    ...\n    public void OnBeaconServiceConnect() \n    {\n        beaconManager.SetMonitorNotifier(new MonitorNotifier());\n        ...\n    }\n\n    ...\n\n    private MonitorNotifier : IMonitorNotifier\n    {\n        public void didEnterRegion(Region region) \n        {\n            Log.i(TAG, "I just saw an beacon for the first time!");       \n        }\n\n        public void didExitRegion(Region region) \n        {\n            Log.i(TAG, "I no longer see an beacon");\n        }\n\n        public void didDetermineStateForRegion(int state, Region region) \n        {\n            Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);        \n        }\n    }\n}	0
20571485	20571059	Re-measuring existing items in ListBox	public class ListEx : ListBox {\n  protected override void OnSelectedIndexChanged(EventArgs e) {\n    base.OnSelectedIndexChanged(e);\n    this.RecreateHandle();\n  }\n}	0
4573691	4573680	There is no Key attribute in EF CTP 5	System.ComponentModel.DataAnnotations	0
10983235	10982558	Opening a Word Document that contains Merge Fields and connects to a datasource from C#	static void OpenWordDocument()\n{\nSystem.Diagnostics.Process proc = new System.Diagnostics.Process();\nproc.EnableRaisingEvents = false;\nproc.StartInfo.FileName = @"fileName.bat";\nproc.Start();\n}	0
12480962	12480773	How do I programmatically show a keyboard for textbox?	private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)\n{\n            txtLongitude.Focus();\n}	0
14778654	14778535	Export double to Excel - decimal separator issue	i.ToString(new System.Globalization.CultureInfo("en-US").NumberFormat);	0
2024817	2024782	Insert records into a database from a hashtable	USE myDB\nGO\n\nCREATE TABLE CSVTest\n(\n    ID INT,\n    FirstName VARCHAR(60),\n    LastName VARCHAR(60)\n)\nGO\n\nBULK INSERT \nCSVTest\nFROM 'c:\temp\csvtest.txt'\nWITH\n(\n    FIELDTERMINATOR = ',',\n    ROWTERMINATOR = '\n'\n)\nGO\n\n\nSELECT *\nFROM CSVTest\nGO	0
11418217	11417436	Default Values For Missing Data Members In DataContractSerializer	[OnDeserialized]\nvoid OnDeserialized(StreamingContext context)\n{\n    this._timeout = TimeSpan.FromHours(12);\n}	0
26739186	26738697	How to store a recursive model with entity framework 5.0	modelBuilder.Entity<Node>()\n    .HasMany(o => o.Nodes)\n    .WithOptional() // or .WithRequired()\n    .Map(m => m.MapKey("ParentNodeId"));	0
11091241	11091208	C# HTTP POST with Boundary	multipart/form-data	0
718798	718782	Is isprefix more expensive than comparing two strings in C#?	public bool IsPrefix(string comp, string prefix) {\n  return Compare(comp, 0, prefix.Length, prefix, 0, prefix.Length);\n}	0
1269240	1268866	How to update with Linq-To-SQL?	public static void Update(IEnumerable<Sample> samples\n    , DataClassesDataContext db)\n{\n    db.Samples.AttachAll(samples);\n    db.Refresh(RefreshMode.KeepCurrentValues, samples)\n    db.SubmitChanges();\n}	0
7005964	7005761	How do I get the display name for an IdentityReference object?	identityReference.Translate(typeof(NTAccount)).Value	0
6481362	6464141	How to (or can I) list attributes of objects from a Generic list, displaying it in a combobox	foreach (car c in garage)\n        {\n            cBox1.Items.Add(c.make);\n            cBox2.Items.Add(c.year);\n        }	0
17235142	17234536	Filter out byte with certain value and XOR next byte	static byte[] Demungify(byte[] value)\n{\n    var result = new List<byte>(value.Length);\n    bool xor = false;\n    for (int i = 0; i < value.Length; i++)\n    {\n        byte b = value[i];\n        if (xor)\n        {\n            b ^= 0x20;\n            xor = false;\n        }\n        if (b == 0x7D)\n        {\n            xor = true; // xor the following byte\n            continue; // skip this byte\n        }\n        result.Add(b);\n    }\n    return result.ToArray();\n}	0
28148703	28148473	Zoom Video in WPF MediaElement	mediaelement.Width = canvas.Width;\n                mediaelement.Height = canvas.Height;\n                mediaelement.Stretch = Stretch.Fill;	0
24382615	24382458	Replacing characters at specific locations	string yourString = "2014-01-07-15.26.46.000452";\nstring newString = Regex.Replace(yourString, @"(\d+)-(\d+)-(\d+)-(\d+).(\d+).(\d+).(\d+)", "$1-$2-$3 $4:$5:$6.$7");	0
18237683	18237623	How to select List in a List by Key through LINQ	var trackKeynotes = Keynotes.SingleOrDefault(g => g.Key == trackKey);	0
33573563	33573471	Viewing ssrs reports in aspx page	serverReport.ReportPath = "/IncidentReport/IpCenter_assignmet";	0
33040557	31263419	C# WPF how to connect a wifi with password	string ssid = "YourSSID";\nbyte[] ssidBytes = Text.Encoding.Default.GetBytes(ssid);\nstring ssidHex = BitConverter.ToString(ssidBytes);\nssidHex = ssidHex.Replace("-", "");	0
27086268	27085325	Update bindings on button click	public class MainViewModel : ViewModelBase\n{\n    private PersonModel model;\n    private Person person;\n\n    public Person Person\n    {\n        get { return person; }\n        set { SetField(ref person, value); } // updates the field and raises OnPropertyChanged\n    }\n\n    public ICommand Update { get { return new RelayCommand(UpdatePerson); } }\n\n    private void UpdatePerson()\n    {\n        if (someCondition)\n        {\n            // restore the old values\n            Person = new Person(model.Person.FirstName, model.Person.LastName, model.Person.Age);\n        }\n\n        // update the model\n        model.Person = new Person(Person.FirstName, Person.LastName, Person.Age);\n    }\n}	0
13587166	13586648	SharePoint 2007 - Update all site home pages	using(SPSite site = new SPSite("http://localhost"))\nusing(SPWeb web = site.RootWeb)\n{\n    web.AllowUnsafeUpdates = true;\n    SPLimitedWebPartManager webParts = web.GetLimitedWebPartManager("Pagees/Home.aspx"\n        , System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);\n\n    MyWebPart wp = new MyWebPart();      // your custom webpart\n    wp.Title = "My WebPart";\n\n    webParts.AddWebPart(wp, "Left", 0);\n    webParts.SaveChanges(wp);\n}	0
19375443	19375354	How to parse encoding from WebClient Response?	var contentType = new ContentType(client.ResponseHeaders["Content-Type"]);\nConsole.WriteLine("{0} ({1})", contentType.MediaType, contentType.CharSet);\n\nvar charset = (contentType.CharSet ?? "UTF-8");	0
8663113	8662922	Programmatically check if page requires authentication based on web.config settings	var principal = new GenericPrincipal(new GenericIdentity(String.Empty, String.Empty), new string[]{});\nvar requiredAuthentication = UrlAuthorizationModule.CheckUrlAccessForPrincipal(Page.AppRelativeVirtualPath, principal, Request.HttpMethod);	0
14086282	14086192	How can i add some properties to UserControl?	[Browsable(true)] //so it appears in object explorer\npublic Color MyListColor\n{\n  get { return m_MyListColor;}\n  set \n  {\n    m_MyListColor = value;\n    Refresh();//or Update\n  }\n}	0
8523915	8523791	Syntax error in conversion for printing input file	richTextBox1.Text = File.ReadAllText(textBox1.Text);	0
5325860	5325814	C# Linq - Given two lists, how do I tell if either of them are contained in each other	int count = ListA.Intersect(ListB).Count();\nif ((count == ListA.Count()) || (count == ListB.Count())) {\n    // One list contains other\n}	0
5357574	5357368	Youtube videos link in my own admin	// Init service.\nYouTubeService service = new YouTubeService("MyApplicationName", "MyDeveloperApiKey");\n\n// Get playlists for youtube user (your client).\nPlaylistsFeed playlists = service.GetPlaylists(new YouTubeQuery("http://gdata.youtube.com/feeds/api/users/[CLIENT_USER]/playlists"));\n\n// Get playlist feed.\nPlaylistFeed feed = service.GetPlaylist(new YouTubeQuery("http://gdata.youtube.com/feeds/api/playlists/" + playlistID)));\n\n// Get list of video IDs for playlist.\n(from atomEntry in feed.Entries select (atomEntry as PlaylistEntry).VideoId).ToList());	0
9870179	9870105	Null Reference by a DataRow	DataTable tableSelectedItems;\nobject otabSelItems  = Session["tableSelectedItems"];\n\nif(otabSelItems is DataTable)\n   tableSelectedItems = (DataTable)otabSelItems;\nelse\n   tableSelectedItems = new DataTable();	0
7611247	7547567	How to start Azure Storage Emulator from within a program	static void StartAzureStorageEmulator()\n    {\n        ProcessStartInfo processStartInfo = new ProcessStartInfo()\n        {\n            FileName = Path.Combine(SDKDirectory, "csrun.exe"),\n            Arguments = "/devstore",\n        };\n        using (Process process = Process.Start(processStartInfo))\n        {\n            process.WaitForExit();\n        }\n    }	0
1613152	1613086	Help me delete the last three chars of any string please!	string test = "the%20matrix%20";\nstring clean = HttpUtility.UrlDecode(test);\n\nif (clean.Length > 2) // if you still want to strip last chars...\n    clean = clean.Substring(0, clean.Length - 3);	0
22713095	22664534	How to make Uri reference to a Resource image embedded in the assembly itself?	_myIcon = new BitmapImage(new Uri(@"Images\MyImage.png", UriKind.Relative));	0
14595548	14589606	Player animation is not working while taking in game controller input but works while taking in keyboard input	if (gamepadState.IsConnected){//Gamepad code}\n\nif (!gamepadState.IsConnected){//Keyboard code}	0
11795732	11795646	C# Login to https Website via program	cod OGZkZlVlNmJk\nglobal_login_hash   83a8ead80c5c544c86c51ab9914db0ab891d7223\nsession OWFhMANRVl5dVlVUVFoDCAlTBVFQB1QNDVZQVlFTU11cUAVSVFMDDwpRVVVTVgdZCFZSA1JSYmMyOA==\nsession_login_hash  38d1a6b20f20d7cb7a8cf93d7f3048087d8c9ffb\nurl ODNiOF5HRxICHE1PQUQdA01YEFcYRlI2MzNi\nuser_login  test\nuser_password   test\nversion A	0
8535524	8535424	How do I get the TreeNode that a context menu is called from?	void tvMouseUp(object sender, MouseEventArgs e)\n{\n    if(e.Button == MouseButtons.Left)\n    {\n        // Select the clicked node\n        tv.SelectedNode = tv.GetNodeAt(e.X, e.Y);\n\n        if(tv.SelectedNode != null)\n        {\n            myContextMenuStrip.Show(tv, e.Location)\n        }\n    }\n}	0
20468771	20468315	Task factory force more tasks to start at the beginning	new Thread()	0
13397326	13397081	Delete duplicates from TextBox, if line after = line before	string[] temp = richTextBox1.Lines;\n      for (int i= 0; i< richTextBox1.Lines.Length - 1; i++)\n      {\n          if (richTextBox1.Lines[i] == richTextBox1.Lines[i+ 1]\n               && rt.Lines[i] != String.Empty)\n          {\n              temp[i] = null;\n          }\n      }\n      richTextBox1.Lines = temp.Where(a => a != null).ToArray();	0
27214084	27214044	Combine path from a list of objects	Path.Combine(items.Select(o => o.Name))	0
8655211	8654541	Convert SWF to PNG image with transparency	// Enable trasparency - set BEFORE setting input SWF filename\nconverter.RGBAMode = true;	0
10571291	10550115	Printing visual with WPF and assigning printerName	PrintDialog dialog = new PrintDialog();\n        PrintQueue queue = new LocalPrintServer().GetPrintQueue(printerName);\n        dialog.PrintQueue = queue;\n        dialog.PrintVisual(canvas, "");	0
26107788	26106431	Loading byte array assembly into new AppDomain throws a FileNotFound exception	public object Execute(byte[] assemblyBytes)\n    {\n        AppDomain domainWithAsm = AsmLoad.Execute(assemblyBytes);\n        ....\n    }\n\n    [Serializable]\n    public class AsmLoad\n    {\n        public byte[] AsmData;\n\n        public void LoadAsm() \n        {\n            Assembly.Load(AsmData);\n            Console.WriteLine("Loaded into: " + AppDomain.CurrentDomain.FriendlyName);\n        }\n\n        public static AppDomain Execute(byte[] assemblyBytes)\n        {\n            AsmLoad asmLoad = new AsmLoad() { AsmData = assemblyBytes };\n            var app = AppDomain.CreateDomain("MonitoringProxy", AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }, new PermissionSet(PermissionState.Unrestricted));\n            app.DoCallBack(new CrossAppDomainDelegate(asmLoad.LoadAsm));\n            return app;\n        }\n    }	0
14745946	14743857	Change Current cell in Cell Enter Event of DataGridView	private void myGrid_CellEnter(object sender, DataGridViewCellEventArgs e)\n        {\n            //Do stuff\n            Application.Idle += new EventHandler(Application_Idle);\n\n        }\n\n        void Application_Idle(object sender, EventArgs e)\n        {\n            Application.Idle -= new EventHandler(Application_Idle);\n            myGrid.CurrentCell = myGrid[cursorCol,cursorRow];\n        }	0
9789208	9788962	How to get a dump of all local variables?	try\n{\n    double d = 1 / 0;\n}\ncatch (Exception ex)\n{\n    var trace = new System.Diagnostics.StackTrace();\n    var frame = trace.GetFrame(1);\n    var methodName = frame.GetMethod().Name;\n    var properties = this.GetType().GetProperties();\n    var fields = this.GetType().GetFields(); // public fields\n    // for example:\n    foreach (var prop in properties)\n    {\n        var value = prop.GetValue(this, null);\n    }\n    foreach (var field in fields)\n    {\n        var value = field.GetValue(this);\n    }\n    foreach (string key in Session) \n    {\n        var value = Session[key];\n    }\n}	0
8450073	8450020	Calculate Exponential Moving Average on a Queue in C#	return Quotes.DefaultIfEmpty()\n             .Aggregate((ema, nextQuote) => alpha * nextQuote + (1 - alpha) * ema);	0
2806802	2806790	Making Custom DataGridViewCell ReadOnly	public override Type EditType\n    {\n        get\n        {\n            return null;\n        }\n    }	0
12670755	12670740	Create SQL Server database from C# - using parameters	CREATE DATABASE	0
27073602	27073497	Set Properties of linq object to those of another	public void SetProperties(object source, object target)\n{\n    var contactType = target.GetType();\n    foreach (var prop in source.GetType().GetProperties())\n    {\n        var propGetter = prop.GetGetMethod();\n        var propSetter = contactType.GetProperty(prop.Name).GetSetMethod();\n        var valueToSet = propGetter.Invoke(source, null);\n        propSetter.Invoke(target, new[] { valueToSet });\n    }\n}	0
25122728	25122537	How to delete file using partial path name	Directory.GetFiles(yourPath, "Full System Backup-*.zip")\n    .ToList().ForEach(File.Delete);	0
10070519	10070483	Max Value in DropDownList - ASP.NET	int maxValue = DropDownList1.Items.Cast<ListItem>().Select(item => int.Parse(item.Value)).Max();	0
958897	958884	Custom Generic GetTable	where T: class	0
708310	708299	Sum DataTable columns of type string	var sum = dt.Compute("Sum(Convert(WeightRate, 'System.Int32'))");	0
18228412	18228305	How to split a string with more than one whitespaces as delimiters?	List<string> splitStrings = myString.Split(new[]{"  "}, StringSplitOptions.RemoveEmptyEntries)\n    .Select(s => s.Trim())\n    .ToList();	0
15762900	15762869	read an xml file with c#	string str =\n@"<?xml version=""1.0""?>\n<!-- comment at the root level -->\n<Root>\n    <Child>Content</Child>\n</Root>";\nXDocument doc = XDocument.Parse(str);\nConsole.WriteLine(doc);	0
860064	860027	Using Excel Interop and getting a print dialog	bool userDidntCancel =\n    excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrint].Show(\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);	0
25829166	25825963	Change properties in a class using a form from a different class	namespace com.myCompany.myApp\n{\n    public partial class frm_Configuration : Form\n    {\n        public frm_Configuration(GeneratePDF generatePdf)\n        {\n            InitializeComponent();\n            GeneratePDFBindingSource.DataSource = generatePdf;\n            GeneratePDFBindingSource.EndEdit();\n        }\n    }\n}	0
15177995	15174411	Reshape a viewmodel to a model	public ActionResult SomeAction(SavePeriodListViewModel model)\n{\n    // transform from model to LessonplannerResponse\n\n    // validate model\n\n    // do something with the model and return a view\n}	0
10673446	10671123	Run MonDevelop gtk# program without mono runtime terminal showing - Ubuntu	#!/bin/bash\nmono /path/to/executable.exe	0
6585696	6552840	C# remove duplicate dictionary items from List<>?	if(!String.IsNullOrEmpty(item["itemId"]))\n {\n    alert.DaleksApproaching(item["itemId"]);\n }	0
8616447	8616364	else statement of Datatable	Create Procedure GetCustomers(@name varchar(100))\nAS \nBEGIN\n select * from customer  where Name like (ISNULL(@name,Name))\nEND	0
26924890	26924555	How to find today's data from database from two different dates?	declare @month varchar(50) = '11'\ndeclare @mindate varchar(50)\ndeclare @maxdate varchar(50)\ndeclare @date varchar(50)\n\nselect @mindate=min(fromdate),@maxdate = max(todate)\nfrom ShiftChange Where Month = @month\n\nselect TOP 1 Shift From ShiftChange\nWHERE @date>= fromdate and todate<=@date\nand month = @month\norder by todate desc	0
27538237	27538183	Interfaces with set methods only for initialization?	public interface IReadable {\n    int SomeProperty {get;}\n}\n\npublic interface IInitializable : IReadable {\n    int SomeProperty {get;set;}\n}\n\nIReadable _passItOn;\npublic void InitializeAndUse(IInitializable initAndUse){\n    _passItOn = initAndUse;\n    initAndUse.SomeProperty = 42;\n\n    UseReadOnly(_passItOn);\n}	0
31852608	31852264	Is there a way to expand a one-dimensional Array into a 2D Array with the original values in the [0] index of the 2D Array in C#?	void Main()\n{\n    int[] sourceCollection = new [] {1,2,3,4,5,6,7} ;\n\n    var result = CopyArrayValues(sourceCollection, 2);\n    result.Dump();\n}\n//create a new 2d array\nT[,] CopyArrayValues<T>(T[] DataSource, int SecondLength)\n{\n    //Initialize the new array\n    var Target = new T[DataSource.Length, SecondLength];\n    //Copy values over\n    for (int i = 0; i < DataSource.Length; i++)\n    {\n        Target[i, 0] = DataSource[i];\n    }\n\n    return Target;\n}	0
6156019	6155958	How to assign values to items in a databound ddl?	...DataValueField="CustId"...\n\n...SelectCommand="SELECT [CustName], [CustId] FROM [Customer]"...	0
17897686	17897642	converting filenames to lower case	foreach (var file in Directory.GetFiles(@"C:\Temp\testrename"))\n{\n    File.Move(file, file.ToLowerInvariant());\n}	0
27289017	27260877	MSBuild how to pass a parameter to set a property value?	MSBuild.exe /p:Externals="c:\Temp"	0
3394741	3394703	Casting entire array of objects to string	string[] output = (from o in objectArray\n                   select o.ToString()).ToArray()	0
8119637	8115422	HttpListenerResponse and infinite value for its ContentLength64 property	void ProxyRequest(HttpListenerResponse httpResponse)\n{\n    HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:2345");\n    HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();\n\n    // Solution!!!\n    httpResponse.SendChunked = true;\n\n    byte[] buffer = new byte[32768];\n    int bytesWritten = 0;\n    while (true)\n    {\n        int read = HttpWResp.GetResponseStream().Read(buffer, 0, buffer.Length);\n        if (read <= 0)\n            break;\n        httpResponse.OutputStream.Write(buffer, 0, read);\n        bytesWritten += read;\n    }\n}	0
9957696	9957583	Serialize an array of arrays as a single XML element	using System.Linq;\n\n...\n\n[XmlIgnore]\npublic Field[][] Fields;\n\n[XmlArray("Fields")]\npublic Field[] SerializedFields\n{\n    get\n    {\n        return this.Fields.SelectMany(fields => fields).ToArray();\n    }\n    set\n    {\n        this.Fields = new Field[value.Max(field => field.x) + 1][];\n        for (int x = 0; x < this.Fields.Length; x++)\n        {\n            this.Fields[x] = value.Where(field => field.x == x).ToArray();\n        }\n    }\n}	0
19942408	19942275	Comparing large list of objects	var dbObjects = new Dictionary<int, ObjectModel>();\nforeach(var y in dbObject)\n{\n    dbObjects.Add(y.id, y);\n}\n\nforeach(var x in formObject)\n{\n    ObjectModel y;\n    if(dbObjects.TryGetValue(x.id, out y))\n    {\n        //compare each property and notify user of change if different\n    }\n}	0
19704240	19703686	manually create XML for DataTable to send to WebService in C#	public string ConvertDataTableToXml(DataTable table)\n {\n  MemoryStream stream = new MemoryStream();\n  table.WriteXml(stream, true);\n  str.Seek(0, SeekOrigin.Begin);\n  StreamReader reader = new StreamReader(stream);\n  string xmlstr;\n  xmlstr = reader.ReadToEnd();\n  return (xmlstr);\n }	0
28854673	28854497	Hide row in entity framework	var q = from e in dbContext.Equipment where !e.Location.Equals("Removed") select e;	0
3966140	3963952	ViewState["sample"] Variable not retaining value on postback in a composite control	protected override void OnLoad(EventArgs e)\n{\n    ...\n}	0
11178560	11178438	Access input hidden field Title attribute from code behind	TAB.Attributes["title"] = "aaa";	0
22179307	22178123	How to do non-linear page navigation in WPF & C#?	myBorder.Child = new MyUserControl();	0
13304573	13304536	Trim just white space, without escape characters	"\tsome text\t\t\t\t".Trim(' ')	0
1309093	1308927	Refactor methods invoking delgates with different parameter signatures	public delegate void Action(TYPE_OF_ESB esb, TYPE_OF_CONTACT_FOLDER contact folder);\n    private static void Process(Action action)\n    {\n        using (var esb = ExchangeService.GetExchangeServiceBinding())\n        {\n            var contactFolder = FolderService.GetPublicFolder(esb, Properties.Settings.Default.ExchangePublicFolderName);\n            action(esb, contactfolder);\n        }\n    }\n\nProcess((esb, contactfolder)=>processFolderDelegate(esb, contactFolder));\nProcess((esb, contactfolder)=>processContactDelegate(esb, contactFolder, contact));	0
13405973	13405717	regex pattern to match warping span's without attributes	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar spans = doc.DocumentNode.SelectNodes("//span[@*]")\n                .Select(s => s.InnerText)\n                .ToList();	0
15754714	15749072	Best way to backup Windows Phone App database	// Create the data context.\nMyDataContext db = new MyDataContext("Data Source='isostore:/mydb.sdf';Password='securepassword';");\n\n// Create an encrypted database after confirming that it does not exist.\nif (!db.DatabaseExists()) db.CreateDatabase();	0
19823362	19823181	how to pass objects through a button eventHandler	EditButton.Click += (sender, args) => openEditor(temp);	0
3065991	3003951	Add namespaces with and without names to an XElement	XNamespace blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9");\n        XNamespace xsi = XNamespace.Get(@"http://www.w3.org/2001/XMLSchema-instance");\n\n        XDocument doc = new XDocument(\n            new XDeclaration("1.0", "utf-8", "yes"),\n            new XElement(blank + "urlset",\n                new XAttribute("xmlns", blank.NamespaceName), \n                new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),\n\n                new XElement(blank + "url",\n                    new XElement(blank + "loc", "http://www.xyz.eu/"),\n                    new XElement(blank + "lastmod", "2010-01-20T10:56:47Z"),\n                    new XElement(blank + "changefreq", "daily"),\n                    new XElement(blank + "priority", "1"))\n             ));\n\n        Console.WriteLine(doc.ToString());	0
21601852	21268068	Automapper Missing Map Configuration	Mapper.Map<Source, Destination>(source, destination);	0
24673279	24671848	How to find browser download folder path	String path = String.Empty;\nRegistryKey rKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main");\n   if (rKey != null)\n       path = (String)rKey.GetValue("Default Download Directory");\n   if (String.IsNullOrEmpty(path))\n       path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\downloads";	0
23720781	23720469	Azure Blob Storage using Https	DefaultEndpointsProtocol=https;AccountName=myAccount;AccountKey=myKey;	0
15988475	15988296	The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value	new DataColumn("myDate", typeof(DateTime))	0
1706581	1706454	C#: multiline text in DataGridView control	dataGridView1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;\ndataGridView1.Rows.Add("test" + Environment.NewLine + "test"); // Environment.NewLine = "\r\n" in Windows	0
16723368	16723309	Check if a string is of the 00:00,00 format with an annotation	[RegularExpression("^[0-9]{2}:[0-9]{2},[0-9]{2}$")]\npublic string Stringy { get; set; }	0
10627681	10627650	how to replace 2 double quotes in a file	ReplaceTextInFile(file, file + "new", "\"\"", "\"");	0
23784856	23778409	How to change font style and font weight programmatically using c# in metro app for windows 8.1	textblock.FontStyle = Windows.UI.Text.FontStyle.Italic;\ntextblock.FontWeight = Windows.UI.Text.FontWeights.Bold;	0
4051259	4050649	web.config: Changing an application setting with C#	XmlDocument xmlDoc = new XmlDocument();     \nxmlDoc.Load(Server.MapPath("~/") + "app.config");     \nXmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");  \nnode.Attributes[0].Value = newValue;     \nxmlDoc.Save(xmlFile);	0
29265754	29256857	How to get the slide direction of pivot item?	// somewhere in constructor\nMyPivot.SelectionChanged += MyPivot_SelectionChanged;\n\nint previousIndex;\nprivate void MyPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    previousIndex = MyPivot.Items.IndexOf(e.RemovedItems.FirstOrDefault());\n    Debug.WriteLine("Previous index: {0}", previousIndex);\n}	0
2364104	2363933	Split sorted collection of numbers by interuption in sequence	private static List<List<int>> splitBySeq(List<int> someList)\n    {\n        //Stores the result\n        List<List<int>> result = new List<List<int>>();\n\n        //Stores the current sequence\n        List<int> currentLst = new List<int>();\n        int? lastNumber = null;\n\n        //Iterate the items\n        for (int i = 0; i < someList.Count; i++)\n        {\n            //If the have a "break" in the sequence and this isnt the first item\n            if (lastNumber != null && someList[i] != lastNumber + 1)\n            {\n                result.Add(currentLst);\n                currentLst = new List<int>();\n            }\n\n            currentLst.Add(someList[i]);\n            lastNumber = someList[i];\n        }\n\n        if (currentLst.Count != 0)\n            result.Add(currentLst);\n\n        return result;\n    }	0
16182040	16181980	How to add image to ToolStripMenuItem	private void BuildContextMenuStrip_Click(object sender, EventArgs e)\n{\n    ContextMenuStrip cxtMnuStrp = new ContextMenuStrip();\n\n    ToolStripMenuItem item = new ToolStripMenuItem("uniqueName") { Image = WindowsFormsApplication2.Properties.Resources.Search.ToBitmap() };\n\n    if (cxtMnuStrp.Items.Contains(item) == false)\n        cxtMnuStrp.Items.Add(item);\n\n    this.ContextMenuStrip = cxtMnuStrp;\n}	0
8529811	8526547	Explicit & Implicit Operator with Numeric Types & unexpected results	int? x = whatever;\nFred f = (Fred)x;	0
14270098	14264105	Create application bar in xaml and manipulate it in code	private void PanoControl_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n\n    if (PanoControl.SelectedIndex == 0)\n        this.ApplicationBar.IsVisible = false;\n    else if(PanoControl.SelectedIndex == 1)\n        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).IsEnabled = false;\n    else if (PanoControl.SelectedIndex == 2)\n    {\n        this.ApplicationBar.IsVisible = false;\n        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).IsEnabled = false;\n    }\n}	0
9559491	9559465	How to pass object data from one method to another	Payment m_orderPaymentObject = null;\nprivate void btnPaymentButton_Click(object sender, EventArgs e)\n{\n    amountDue = double.Parse(this.txtAmountDue.Text);\n    amountPaid = double.Parse(this.txtAmountPaid.Text);\n\n    m_orderPaymentObject = new Payment(amountDue, amountPaid);\n}	0
2998803	2998672	How do you send a named pipe string from umnanaged to managed code space?	m_pNamedPipe->SendMessage("Hi de hi\n")	0
597088	597037	How to copy one Graphics Object into another	Dim srcBmp As New Bitmap(pnl.Width, pnl.Height)\nDim clip As New Rectangle(New Point(0, 0), pnl.Size)\npnl.DrawToBitmap(srcBmp, clip)	0
32804724	32803158	How can I adjust steer angle based on speed in Unity?	float speedFactor = GetComponent<Rigidbody>().velocity.magnitude * 3.6f / maxSpeed; //or magnitude * 2.236936f for miles/h	0
3987255	3987212	Searching for multiple strings in multiple files	List<string> keys = ...;    // load all strings\n\nforeach(string f in Files)\n{\n    //search for each string that is not already found\n    string text = System.IO.File.ReadAllText(f);  //easy version of ReadToEnd\n\n\n    // brute force\n    foreach(string key in keyes)\n    {\n        if (text.IndexOf(key) >= 0) ....\n    }\n\n}	0
18490258	18489989	How to loop through checkbox value in gridview	Response.Redirect("ReassignpParticularWork.aspx");	0
10522517	10522343	How can I write a linq query for this?	var b = (\n    from o in db.Orders\n    where o.ProductID == 5\n    group o by o.CustomerID into og \n    select new {\n        CustomerID = og.Key\n        Price = Max(og.Price)\n    }\n);\nvar a = (\n    from o in db.Orders\n    join p in b on new {a.CustomerID, a.Price} equals \n            new {b.CustomerID, b.Price}\n    where o.ProductID == 5\n    select a.ID\n);\nvar r = a.ToString();	0
32271862	32271763	Creating zip file from multiple files	static void Main()\n    {\n    // Create a ZIP file from the directory "source".\n    // ... The "source" folder is in the same directory as this program.\n    // ... Use optimal compression.\n    ZipFile.CreateFromDirectory("source", "destination.zip",\n        CompressionLevel.Optimal, false);\n\n    // Extract the directory we just created.\n    // ... Store the results in a new folder called "destination".\n    // ... The new folder must not exist.\n    ZipFile.ExtractToDirectory("destination.zip", "destination");\n    }	0
29717098	29716936	How to code variable loop level in foreach in List<T>	public static void ShowAll(Person pers)\n{\n    Console.WriteLine(pers.Name);\n    foreach (var item in pers.Children)\n    {\n        ShowAll(item);\n    }\n}	0
30399578	29852691	Building a TreeView issue	The result is a tree with only one root that corresponds to a direction, and the characteristics in it are correct, as well as the segments inside the characteristics.	0
9511854	9511760	Multithreaded Single Producer Multiple Consumer Implementation	class SlimDemo\n{\n  static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();\n  static List<int> _items = new List<int>();\n  static Random _rand = new Random();\n\n  static void Main()\n  {\n    new Thread (Read).Start();\n    new Thread (Read).Start();\n    new Thread (Read).Start();\n\n    new Thread (Write).Start ("A");\n    new Thread (Write).Start ("B");\n  }\n\n  static void Read()\n  {\n    while (true)\n    {\n      _rw.EnterReadLock();\n      foreach (int i in _items) Thread.Sleep (10);\n      _rw.ExitReadLock();\n    }\n  }\n\n  static void Write (object threadID)\n  {\n    while (true)\n    {\n      int newNumber = GetRandNum (100);\n      _rw.EnterWriteLock();\n      _items.Add (newNumber);\n      _rw.ExitWriteLock();\n      Console.WriteLine ("Thread " + threadID + " added " + newNumber);\n      Thread.Sleep (100);\n    }\n  }\n\n  static int GetRandNum (int max) { lock (_rand) return _rand.Next(max); }\n}	0
6492850	6491931	Problems working with LINQ to XML	var xmlData = XDocument.Parse(xml);\n\nXNamespace ns = "http://checkout.google.com/schema/2";\n\nif (xmlData.Root.Name == ns + "authorization-amount-notification")\n{ \n    var amount = \n        xmlData\n        .Root\n        .Element(ns + "authorization-amount")\n        .Value;\n\n    var googleNumber = \n        xmlData\n        .Root\n        .Element(ns + "google-order-number")\n        .Value;  \n    _checkoutService.ChargeAndShip(googleNumber, amount);             \n\n    charged = true;\n}	0
15146063	15145944	counting weight-average of a sequence of doubles	double sum = 0.0;\nint count = 100000;\nfor (int i = 0; i < count; ++i) {\n    sum += 200000.0;\n}\ndouble average = sum / (double)count;\nConsole.WriteLine(average); // prints out exactly 200000	0
25696540	25696518	Is it possible to make a function with multiple parameters of different types take the parameters in any order without overloading?	private void OperationOverLoadTest()\n        {\n            this.myFunction(1, 1.1D, true);\n            this.myFunction(myDouble: 1.1D, myBool:false, myInt:1);\n\n        }\n\n        public void myFunction(int myInt, double myDouble, bool myBool)\n        {\n            //Some code here\n        }	0
1258292	1258269	Selecting A Subset Of A List With A Particular Element First In The List	var list = vendors.Where( v => v.Name.ToUpper().Contains( vendorNameSearch ) )\n                  .OrderBy( v => ComputeLevenshtein( v.Name.ToUpper(),\n                                                     vendorNameSearch ) );	0
5534507	5534463	Slow down when hashing a file	byte[] hash = md5.ComputeHash(stream);	0
1000748	999046	Using json.net, how would I construct this json string?	JObject o = new JObject();\no["rc"] = new JValue(200);\no["m"] = new JValue("");\no["o"] = new JValue(@"<div class='s1'>\n      <div class='avatar'>             \n          <a href='asdf'>asdf</a><br />\n          <strong>0</strong>\n      </div>\n      <div class='sl'>\n          <p>\n              444444444\n          </p>\n      </div>\n      <div class='clear'>\n      </div>                        \n  </div>");\n\nConsole.WriteLine(o.ToString());	0
11315247	11314967	Post image to wall user twitter	statuses/update	0
11594814	11594702	How to get image from Google static map API	using (WebClient wc = new WebClient()) {\n  wc.DownloadFile(url, @"c:\temp\img.png");\n}	0
105703	105676	Get a list of all computers on a network w/o DNS	nmap -O -oX "filename.xml" 192.168.0.0/24	0
5317032	5316992	SQL syntax for retrieving from a different table?	SELECT\n    User.FirstName,\n    User.SecondName,\n    User.Aboutme,\n    User.DOB,\n    Picture.PicturePath\nFROM User\nLEFT JOIN Pictures\nON User.UserID = Pictures.UserID\nWHERE User.UserID=1	0
8140808	8140350	Parse multiline BBCode with C# Regex	\[deck=([^\:]+?):(?:[^\]]+)\]([^\[]+?)\[/deck:(?:[^\]]+)\]	0
3096473	3096244	Get GAC entries by Public Key	version_somethingIcan'tRemember_publicKey	0
5013236	5013170	find max value from Dataset	dt.Rows.Cast<DataRow>().Max(row => row[ColumnName]);\n\ndt.Rows.Cast<DataRow>().Min(row => row[ColumnName]);	0
18958820	18956311	Encrypt AES in C++(OpenSSL), decrypt in C#	PaddingMode.PKCS7	0
1472293	1472264	Creating new image from cropped image	Bitmap newImage = originalBitmap.Clone(new RectangleF(x, y, width, height),  \n                                       System.Drawing.Imaging.PixelFormat.Format32bppArgb);\nnewImage.Save(newFilePath);	0
24072464	24072218	Adding data in sql Table	StrQuery = @"INSERT INTO ProduktTable (Navn, Varenr) VALUES ('"\n                + dataGridView1.Rows[i].Cells[0].Value + "',' "\n                + dataGridView1.Rows[i].Cells[1].Value + "');";	0
13898503	13898489	Counting the number of occurences of each character in a string	from c in str\ngroup by c into g\nselect new { letter= g.Key, count= g.Count()}	0
4592614	4592542	How can I open another page when pressing the Edit button on a gridview?	string BrowserSettings = "status=no,toolbar=no,menubar=no,location=no,resizable=no,"+\n                                        "titlebar=no, addressbar=no, width=600 ,height=750";\n            string URL = "http://localhost/MyPage.aspx";\n            string scriptText = "window.open('" + URL + "','_blank','" + BrowserSettings + "');";\n            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ClientScript1", scriptText, true);	0
29762316	29762046	How to pass a MouseEventArgs with correct properties into event handlers?	protected override void WndProc(ref Message m) {\n    if (m.Msg == 0xA0) {  // WM_NCMOUSEMOVE.\n        var pos = this.PointToClient(new Point(m.LParam.ToInt32()));\n        var evt = new MouseEventArgs(Control.MouseButtons, 0, pos.X, pos.Y, 0);\n        OnMouseMove(evt);\n    }\n    base.WndProc(ref m);\n}	0
28437970	28436010	Do I need to get rid of a postback or?	Session["id_utente"]	0
11065293	11065204	C# Program stops after a HTTP Request	resp.Close();	0
4639503	4639482	How to do a background for a label will be without color?	label1.BackColor = System.Drawing.Color.Transparent;	0
25067685	25067135	Add temporary property to list of objects	var payrolls = from aPayroll in (List<Payroll>)Session["payrolls"]\n               select new {\n                    Date = aPayroll.Date,\n                    PayScenario = aPayroll.PayCategory.PayScenario,\n                    Label = aPayroll.PayGroup.Label,\n                    Description = aPayroll.PayGroup.Description,\n                    EntryType = aPayroll.PayGroup.EntryType\n               };	0
2681717	2681661	backgroundworker+wpf -> frozen window	for (int i = 1; i <= 30; i++)\n{\n    int percent = (i * 100) / 30;\n    _worker.ReportProgress(percent);\n    for(int j = 0; ....)\n        ....\n}	0
14887495	14867540	datagridview not showing numbers from MS Access	private void Form6_Load(object sender, EventArgs e)\n        {\n            loadData();\n        }\n\nprivate void loadData()\n            {\n                str = new OleDbConnectionStringBuilder();\n                str.Provider = "Microsoft.ace.Oledb.12.0";\n                str.DataSource = @"\\sisc-erelim\4_Printing\VTDB\DB\VirginiTEADB2.accdb";\n                con = new OleDbConnection(str.ConnectionString);\n                dataGridView1.DataSource = fillTable("Select* from Accountstbl");\n                dataGridView1.Columns["Password"].Visible = false;\n                dataGridView1.Columns["Picture"].Visible = false;\n            }\n\n        private DataTable fillTable(string sql)\n        {\n            DataTable datatable = new DataTable();\n            using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))\n            {\n                da.Fill(datatable);\n            }\n\n            return datatable;\n        }	0
7366886	7366752	Retrieving static members of multiple classes programmatically	class Shape\n   {\n      /* ... */\n   }\n\n   class CircleShape : Shape\n   {\n      public static string Name\n      {\n         get\n         {\n            return "Circle";\n         }\n      }\n   }\n\n   class RectangleShape : Shape\n   {\n      public static string Name \n      {\n         get\n         {\n            return "Rectangle";\n         }\n      }\n   }\n\n   class Program\n   {\n      static void Main(string[] args)\n      {\n         var subclasses = Assembly.GetExecutingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Shape)));\n         foreach (var subclass in subclasses)\n         {\n            var nameProperty = subclass.GetProperty("Name", BindingFlags.Public | BindingFlags.Static);\n            if (nameProperty != null)\n            {\n               Console.WriteLine("Type {0} has name {1}.", subclass.Name, nameProperty.GetValue(null, null));\n            }\n         }\n      }\n   }	0
19143118	19143019	How to display employeephoto from database on listbox item click	File.WriteAllBytes()	0
4236334	4236114	Guide to setting up Fluent NHibernate from File - New Project	add-package nhibernate.core	0
5228578	5227225	Getting log4net's XML configuration file read in ASP.NET webforms	var fi = new FileInfo(Server.MapPath("~/log4net.config"));	0
20694410	20694397	Assigning to List to another List previous list automatically changes	this.PrevTBal = new List<TrialBalance>(this.TBal.Select(b => clone(b));	0
20998581	20998413	Where to place the coordinates of text in a C# graphic bitmap	//Position\nPointF drawPoint = new PointF(0F, 0F);\n// Draw string to screen.\ne.Graphics.DrawString("hey", drawFont, drawBrush, drawPoint);	0
10374309	10371930	Append text on rtf string at position	string rtfStuffs = this.richTextBox1.Rtf;\n// Edit as you see fit...\nthis.richTextBox1.Rtf = rtfStuffs;	0
21757762	21754086	nHibernate group by year and month with count	var query = (from article in _session.Query<Article>()\n                     where article.Parent == articleList && article.PublishOn != null\n                     group article by new { article.PublishOn.Value.Year, article.PublishOn.Value.Month } into entryGroup\n                     select new ArchiveModel\n                     {\n                         Year = entryGroup.Key.Year,\n                         Month = entryGroup.Key.Month,\n                         Count = entryGroup.Count()\n                     });	0
23959608	23956863	Handle exception like for each in lambda expression query	elList.Where(e => { DateTime x; DateTime.TryParse(e, out x); return x; })	0
16210805	16210730	Rounding a number with special conditions	var result =  Math.Ceiling((double) x/1000)*1000;	0
5253217	5253028	How To Set DateTime.Kind for all DateTime Properties on an Object using Reflection	// Same check for nullable DateTime.\n            else if (p.PropertyType == typeof(Nullable<DateTime>)) {\n                DateTime? date = (DateTime?)p.GetValue(obj, null);\n                if (date.HasValue) {\n                    DateTime? newDate = DateTime.SpecifyKind(date.Value, DateTimeKind.Utc);\n                    p.SetValue(obj, newDate, null);\n                }\n            }	0
8795332	8795309	Convert byte[] buf[offset] to int16	value += Convert.ToInt16(buf[offset] << 8)	0
3941615	3941576	How do I associate a button with a control?	public Form1() \n{\n  InitializeComponent();\n  button1.Tag = pictureBox1;\n  button1.Click += btnT_Click;\n  // etc..\n}\n\nprivate void btnT_Click(object sender, EventArgs e)\n{\n  var btn = (Button)sender;\n  cropPict((PictureBox)btn.Tag, CropSide.Top);\n}	0
7695996	7687014	How to check if user has granted a certain set of permissions to my app, using the Facebook C# SDK?	var fb = new FacebookClient("accessToken");\ndynamic result = fb.Get("/me/permissions");	0
1038679	1038674	C# prefixing parameter names with @	string says = @"He said ""This literal string lets me use \ normally \n    and even line breaks"".";	0
1006588	1006521	How do I bind a Combo so the displaymember is concat of 2 fields of source datatable?	var dict = new Dictionary<Guid, string>();\nforeach (DataRow row in dt.Rows)\n{\n    dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]);\n}\ncbo.DataSource = dict;\ncbo.DataTextField = "Value";\ncbo.DataValueField = "Key";\ncbo.DataBind();	0
3986510	3986503	How to extract file name from file path name?	string newPathForFile = Path.Combine(newPath, Path.GetFileName(filePath));	0
17228122	17189826	Rotate a document by 90 degrees before printing	/// <summary>\n    /// This is the event handler for PrintManager.PrintTaskRequested.\n    /// </summary>\n    /// <param name="sender">PrintManager</param>\n    /// <param name="e">PrintTaskRequestedEventArgs </param>\n    private void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)\n    {\n        PrintTask printTask = e.Request\n                               .CreatePrintTask("Pass", PrintSourceTaskHandler);\n        printTask.Options.Orientation = PrintOrientation.Landscape;\n    }	0
16606321	16606288	Returning value from a method	public string Send()\n{\n    //define the variable outside of try catch\n    string text = null; //Define at method scope\n    ///some variables           \n    try\n    {\n        ///\n    }\n\n    catch (WebException e)\n    {\n        using (WebResponse response = e.Response)\n        {\n            HttpWebResponse httpResponse = (HttpWebResponse)response;\n            Console.WriteLine("Error code: {0}", httpResponse.StatusCode);\n            using (Stream Data = response.GetResponseStream())\n            {\n                text = new StreamReader(Data).ReadToEnd();\n            }\n        }\n    }\n    return text;\n}	0
6069820	6069666	Saving image in paint app c#	Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);//to create bmp of same size as panel\nRectangle rect=new Rectangle(0,0,panel1.Width,panel1.Height); //to set bounds to image\npanel1.DrawToBitmap(bmp,rect);      // drawing panel1 imgae into bmp of bounds of rect\nbmp.Save("C:\\a.png", System.Drawing.Imaging.ImageFormat.Png); //save location and type	0
3760932	3760482	how to program Virtual PC 2007 to automate tasks?	HKCR\CLSID\{guid}	0
31961777	31961587	How to fill matrix in a class method?	public Matrix(int _n, int _m)\n{\n    n = _n;\n    m = _m;\n    arr = new string[n,m];\n}	0
6752741	6752660	Help with a LINQ Query	var result = from d in yourContextVar.YourTable\ngroup d by d.DataInicio.Day into g\nselect new { Day=g.Key, Count=g.Count() };	0
17202035	17201902	making a list item result VICEVERSA	public ActionResult List()\n        {\n            var currentDate = DateTime.Now;\n            var list = new List<ArchiveViewModel>();\n            for (var startDate = currentDate; startDate >= new DateTime(2012, 11, 1); startDate = startDate.AddMonths(-1))\n            {\n                list.Add(new ArchiveViewModel\n                {\n                    Month = startDate.Month,\n                    Year = startDate.Year,\n                    FormattedDate = startDate.ToString("MMMM, yyyy")\n                });\n            }\n            return View("List",list);\n        }	0
30698372	30698349	Xml serializing and deserializing with memory stream	memStream.Position = 0;	0
10563465	10563440	how do i create a c# program without GUI?	Application.EnableVisualStyles();\nApplication.SetCompatibleTextRenderingDefault(false);\nApplication.Run(new Form1());	0
17543572	17542762	How to connect my gridview to database?	void FillData()\n{\n    // 1\n    // Open connection\n    using (SqlCeConnection c = new SqlCeConnection(\n    Properties.Settings.Default.DataConnectionString))\n    {\n    c.Open();\n    // 2\n    // Create new DataAdapter\n    using (SqlCeDataAdapter a = new SqlCeDataAdapter(\n        "SELECT * FROM Animals", c))\n    {\n        // 3\n        // Use DataAdapter to fill DataTable\n        DataTable t = new DataTable();\n        a.Fill(t);\n        // 4\n        // Render data onto the screen\n        dataGridView1.DataSource = t;\n    }\n    }\n}	0
824058	824031	Custom DependencyProperty	public enum BrushTypes\n    {\n        Solid,\n        Gradient\n    }\n\n    public BrushTypes BrushType\n    {\n        get { return ( BrushTypes )GetValue( BrushTypeProperty ); }\n        set { SetValue( BrushTypeProperty, value ); }\n    }\n\n    public static readonly DependencyProperty BrushTypeProperty = \n               DependencyProperty.Register( "BrushType", \n                                            typeof( BrushTypes ), \n                                            typeof( MyClass ) );	0
6533528	5257124	How to add audio file to my form?	private void playSoundFromResource(){\n    SoundPlayer sndPing = new SoundPlayer(SoundRes.GetType(), "Ping.wav");\n    sndPing.Play();\n}	0
8436632	8436404	C# Socket send truncate info	int actuallyRead = stream.Read(bufferToStoreData, 0, bytesToRead);\nwhile (actuallyRead < bytesToRead) {\n    actuallyRead  += stream.Read(bufferToStoreData, actuallyRead, bytesToRead - actuallyRead);\n}	0
20144271	20144096	Group by a many-to-many relashionship	int[] addressIds = { 1, 3 };\n\nvar query = from c in categoryQuery\n            let searchCount = c.Addresses.Count(a => addressIds.Contains(a.Id))\n            where searchCount > 0\n            select new CategoryGetAllBySearchDto{\n               Id = c.Id,\n               Name = c.Name,\n               SearchCount = searchCount\n            };	0
11032675	11032394	Substring not working as expected if length greater than length of String	if(A.Length > 40)\n       B= A.Substring(0,40);\nelse\n       B=A;	0
31755783	31750228	Replacing Text of Content Controls in OpenXML	if (alias != null)\n{\n    // delete all paragraph of the sdt\n    sdt.Descendants<Paragraph>().ToList().ForEach(p => p.Remove());\n    // insert your new text, who is composed of:\n    // - A Paragraph\n    // - A Run\n    // - A Text\n    sdt.Append(new Paragraph(new Run(Text("As a consultant his job is to design, develop and love poney"))));\n}	0
8035111	8035057	How to set width and height to a master page variable from a web page	this.master	0
5738214	5736111	Setting Generics on the Fly	void HelperMethod<TType>(){\n    GetConfigurationSettingMessageResponse<TType> ch;\n    if (MessagingClient.SendSingleMessage(request, out ch))\n    {\n        ... //Do your stuff.\n    }\n\n}	0
3073979	3073697	Fastest way to store an ascii file's text in a RichTextBox?	myRtb.Text = File.ReadAllText(bigFile.txt, Encoding.ASCIIEncoding);	0
13328324	13328266	How can I specify a constructor for Unity to use when resolving a service?	[InjectionConstructor]\npublic ReferenceService(IAzureTable<Reference> referenceRepository)\n{\n    _referenceRepository = referenceRepository;\n}\n\npublic ReferenceService(CloudStorageAccount devStorageAccount)\n{\n    _referenceRepository = new AzureTable<Reference>(devStorageAccount, "TestReferences");\n}	0
10921944	10921909	How to prevent a listview from adding a blank line?	if(!string.IsNullOrEmpty(nextRow)) {\n   execute the code you need\n}	0
8932727	8932704	Looking for something similar to Path.Combine to navigate folders	var path1 = "c:\\temp\\foo\\bar";\nvar path2 = "..\\..\\foo2\\file.txt";\n\nvar path3 = Path.GetFullPath(Path.Combine(path1, path2)).Normalize();	0
26556002	26555852	How do you mitigate the effects of event handlers during deserialization?	var model = dataSource.Deserialize();\nmyForm.ModelBindingSource.DataSource = model;	0
3035306	3035291	how to add List<string> in Session state	List<string> ast = new List<string>();\n        ast.Add("asdas!");\n        Session["stringList"] = ast;\n        List<string> bst = (List<string>)Session["stringList"];	0
4690504	4690480	int to hex string	ToString("X4")	0
1075820	627937	How do I access FireFox 3 bookmarks while FireFox is running?	using System.Data.SQLite;  // need to install sqlite .net driver\n\nString path_to_db = @"C:\Documents and Settings\Jeff\Application Data\Mozilla\Firefox\Profiles\yhwx4xco.default\places.sqlite";\nString path_to_temp = System.IO.Path.GetTempFileName();\n\nSystem.IO.File.Copy(path_to_db, path_to_temp, true);\nSQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_temp + ";Version=3;Compress=True;Read Only=True;");\n\nSQLiteCommand sqlite_command = sqlite_connection.CreateCommand();\n\nsqlite_connection.Open();\n\nsqlite_command.CommandText = "SELECT moz_bookmarks.title,moz_places.url FROM moz_bookmarks LEFT JOIN moz_places WHERE moz_bookmarks.fk = moz_places.id AND moz_bookmarks.title != 'null' AND moz_places.url LIKE '%http%';";\n\nSQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader();\n\nwhile (sqlite_datareader.Read())\n    {\n        System.Console.WriteLine(sqlite_datareader[1]);\n    }\nsqlite_connection.Close();\nSystem.IO.File.Delete(path_to_temp);	0
24492279	24491196	How to get history of checkins/changsets for specific Team Project?	var tfsUrl = "http://myTfsServer:8080/tfs/defaultcollection";\nvar sourceControlRootPath = "$/MyTeamProject";\nvar tfsConnection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsUrl));\nvar vcs = tfsConnection.GetService<VersionControlServer>();\n\nvar changeSets = vcs.QueryHistory(sourceControlRootPath, RecursionType.Full);\n\nforeach (var c in changeSets)\n{\n    var changeSet = vcs.GetChangeset(c.ChangesetId);\n    foreach (var change in changeSet.Changes) \n    {\n       // All sorts of juicy data in here\n    }\n\n}	0
23491623	23491481	Only capture element with Linq to XML if parent is of specified type	doc.Descendants(ns1 + "MyElement")\n    .Where(x=>x.Parent.Name.LocalName=="MyParentElement")	0
32685640	32685528	I want to create an array containing my xmldocument nodes in c#	using System.Xml.Linq;\n\nvar quotes = XDocument\n .Load("quotations.xml")\n .Descendants("quote")\n .Select(q => q.Value)\n .ToArray();	0
17616375	17602687	Getting window handle of a gnuplot graph in C#	IntPtr windowId = IntPtr.Zero;\nwhile (windowId == IntPtr.Zero)//keeps trying to get the id until it has it\n     windowId = FindWindowByCaption(IntPtr.Zero, "Gnuplot (window id : 0)");      \n\nMoveWindow(windowId, 670, 100, 550, 400, true);//adjusts the location of the gnuplot window	0
30400516	30399798	Map dto to complex entity	Mapper.CreateMap<UploadDTO , Number>();	0
19958981	19958604	c# How to get Dataset contents in loop	for(int i=0; i<600; i++) {\n    getitems[i] = Convert.ToString(ds1.Tables[0].Rows[i]["column"]);\n    //Some logic\n}	0
29256824	29256730	Efficient code for using lots of buttons on a form	private void Btn_Click(object sender, EventArgs e)\n    {\n        convertingFrom = (sender as Button).Text.Substring(0, 3);\n        CCDisplay.Text = "Converting to: " + convertingFrom;\n    }	0
30029295	30029252	Regex to insert space C#	string pattern = "([^ ])<";\n   string replacement = "$1" + " <";	0
5362509	5362437	Assign NULL value to Boolean variable	Nullable<bool> b=null;	0
10253344	10253278	T4MVC - different controllers conflict	routes.MapRoute(\n    "Group_Default",\n    "Group/{action}/{groupId}",\n    new { controller = "Group" }\n);\n\nroutes.MapRoute(\n    "UserProfile_Default",\n    "Profile/{action}/{userId}",\n    new { controller = "Profile" }\n);	0
6129958	6129916	Lookup / Join with LINQ-to-Entities in C#	var orders = from product in database.Products\n            join order in database.Orders on product.Key equals order.KeyField \n           where product.ProductID == productID\n           select order;	0
3067906	3067461	linq to sql dynamic data modify object before insert and update	partial class MyAdminEntity : EntityBase\n{\n  internal override OnSaving(ChangeAction changeAction)\n  {\n    if (changeAction == ChangeAction.Insert)\n    {\n      CreatedBy = "<username>";\n      CreatedDate = DateTime.Now;\n    }\n    else if (changeAction == ChangeAction.Update)\n    {\n      CreatedBy = "<username>";\n      CreatedDate = DateTime.Now;\n    }\n  }\n}	0
670803	670796	How to get all files in a directory with certain extension in C#?	Directory.GetFiles (sourceDirectory_, "*.jpg")	0
1192071	1192054	Load image from resources area of project in C#	var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);	0
21322122	21322024	Interfaces and shared implementation	public abstract class ColumnBase\n{\n    public bool IsVisible { get; set; }\n\n    public bool IsGroupBy { get; set; }\n\n    public Type CLRType { get; set; }\n\n    public virtual string GetGroupByString()\n    {\n        return "base string";\n    }\n\n    public abstract string GetFilterString();\n}\n\npublic class ConcreteColumn : ColumnBase\n{\n    public override string GetGroupByString()\n    {\n        return "concrete string";\n    }\n\n    public override string GetFilterString()\n    {\n        return "who owns the filter string?";\n    }\n}	0
14620241	14620060	How should I update from Task the UI Thread	TaskScheduler scheduler = TaskScheduler.Current;\n...ContinueWith(obj => LogContent = obj.Result), CancellationToken.None, TaskContinuationOptions.None, scheduler)	0
12444347	12444330	Validate ASP.net calendar control against current date	if(calendercontroldate < DateTime.Now.Date)\n{\n    //Do something\n}	0
6443486	6443178	C# - Parse/Format a .txt file	foreach (string line in File.ReadAllLines("filename"))\n        {\n            Match m = Regex.Match(line, @"^\d+\s+[\d\w]+\s+\d+\s+.{24}");\n            if (m.Success)\n            {\n                string output = m.Value;\n                // do something with output, for example write to a file\n            }\n        }	0
9687954	9687895	How can I open page after some period of time (Windows Phone)	DispatcherTimer Timer = new DispatcherTimer()\n{\n    Interval = TimeSpan.FromSeconds(4)\n};\nTimer.Tick += (s, e) =>\n{\n    Timer.Stop();\n    NavigationService.Navigate(new Uri("SecondPage.xaml"));        \n};\nTimer.Start();	0
1290278	1290251	C# Custom Object Validation Design	class Field\n{\n    public bool Required { get; }\n    public string Value { get; set; }\n\n    // assuming that this method is virtual here\n    // if different Fields have different validation logic\n    // they should probably be separate classes anyhow and\n    // simply implement a common interface of inherit from a common base class.\n    public override bool IsValid\n    {\n        get { return Required && Value != String.Empty; }\n    }\n}	0
11719995	11719968	Convert double to round up using C#	int result = (int)Math.Ceiling(value);	0
13374105	13360471	Form post via Controller MVC3	var context = HttpContext.Current;\n        context.Response.Clear();\n        context.Response.Write("<html><head>");\n        context.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));\n        context.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));\n        for (int i = 0; i < inputValues.Keys.Count; i++)\n            context.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", HttpUtility.HtmlEncode(inputValues.Keys[i]), HttpUtility.HtmlEncode(inputValues[inputValues.Keys[i]])));\n        context.Response.Write("</form>");\n        context.Response.Write("</body></html>");\n        context.Response.End();	0
5228670	5228593	Downloading a file from a website using C#	webClient.Headers.Add(HttpRequestHeader.UserAgent, "blah")	0
21262139	21261530	MYSQL get Date column as string	string dateString;\nusing (IDbConnection connection = new MySqlConnection()) {\n    connection.ConnectionString = "YOUR STRING";\n    connection.Open();\n    try {\n        using (IDbCommand command = connection.CreateCommand())\n        {\n            command.CommandText = "SELECT DATE_FORMAT(X, '%Y/%m/%d') AS  X FROM Y";\n            using (IDataReader reader = command.ExecuteReader()) {\n                dateString = reader.GetString(0);\n\n                // Alternately you can read the data as a DateTime and use\n                // .NET's formatting.\n                //dateString = reader.GetDateTime(0).ToShortDateString();\n            }\n        }\n    }\n    finally {\n        connection.Close();\n    }\n}	0
16820595	16817791	How to Model Entity Framework Entity/Mapping With Only One-Way Navigation	HasRequired(t => t.WidgetType).WithRequired().HasForeignKey(t => t.FKField);	0
16414278	14730261	MongoDB map reduce c# with stored js function	MongoClient client = new MongoClient();\n    MongoServer server = client.GetServer();\n    MongoDatabase test = server.GetDatabase("test");\n    MongoCredentials credentials = new MongoCredentials("username", "password");\n    var databaseSettings = server.CreateDatabaseSettings("test");\n    var database = server.GetDatabase(databaseSettings);\n\n    BsonValue bv = test.Eval("GetSum",3,10 ); // return stored js function\nBsonValue bv1 = test.Eval(bv .AsBsonJavaScript.Code,3,10); // execute jsfunction	0
24629188	24627943	Parameter is not valid when i try to use bitmap	Bitmap map = new Bitmap(pictureBoxonlineTrain.Size.Width, pictureBoxonlineTrain.Size.Height))\n   using (Graphics graph = Graphics.FromImage(map)) {\n       graph.Clear(this.BackColor);\n       foreach (TimeTable t in OnlineTrainList.ToList()) {\n           Rectangle rectTrainState = new Rectangle(...);\n           graph.FillRectangle(RedBrush, rectTrainState);\n           graph.DrawString(...);\n       }\n   }\n   if (pictureBoxonlineTrain.Image != null) pictureBoxonlineTrain.Image.Dispose();\n   pictureBoxonlineTrain.Image = map;	0
16048403	16047217	How to write only selected class fields into CSV with CsvHelper?	using (var myStream = saveFileDialog1.OpenFile())\n{\n    using (var writer = new CsvWriter(new StreamWriter(myStream)))\n    {\n        writer.Configuration.AttributeMapping(typeof(DataView)); // Creates the CSV property mapping\n        writer.Configuration.Properties.RemoveAt(1); // Removes the property at the position 1\n        writer.Configuration.Delimiter = "\t";\n        writer.WriteHeader(typeof(DataView));\n        _researchResults.ForEach(writer.WriteRecord);\n    }\n}	0
11687356	11687243	Docking/Displaying Mutiple DataGridViews with Splitters Programmatically	tmpSplitter.BringToFront();	0
18036687	18036237	Show the heading direction of a compass on a map	myMap.Layers.Add(new MapLayer()\n {    \n    new MapOverlay()\n    {\n        GeoCoordinate = new GeoCoordinate(37.795032,-122.394927),\n        Content = new Ellipse\n        {\n            Fill = new SolidColorBrush(Colors.Red),\n            Width = 40,\n            Height = 40\n        }\n    }});	0
9614647	6164890	How to use JSON.NET's JsonTextReader to read from a NetworkStream asynchronously?	using(var io = new StreamReader())\n{ \n    io.Read(); \n}	0
10293965	10288432	Insert named parameter of type date into HQL Insert	var hql = "insert into Entity1 (fkid, mydate) \n  select fkid, :date from OtherEntity";\n\nsession.CreateQuery(hql)\n  .setDateTime("date", DateTime.Now)\n  .ExecuteUpdate();	0
13651249	13651052	Method to determine index of parent loop when child loop matches condition	string[] colorList = {"Royal Blue", "Tomato Red", "Mustard Yellow", "Midnight Blue", "Blue", "Blue", "Yellow", "Green", "Red", "Evergreen", "Purple", "Black", "Jet Black"};\nstring[] colorsToFind = "Blue,Yellow,Green".Split(',');\n\nfor (int i = 0; i < colorList.Length - colorsToFind.Length; i++)\n{\n    int j;  // we'll need this later\n    for (j = 0; j < colorsToFind.Length; j++)\n    {\n        if (colorList[j + i] != colorsToFind[j])\n        {\n            break;  // stop if it doesn't match\n        }\n    }\n\n    // j for-loop was exited because j == colorsToFind.Length so a set matched\n    if (j == colorsToFind.Length)\n    {\n        Console.WriteLine(i);\n        break;\n    }\n}	0
21101079	21100668	Replace string on loop	var re = new Regex(@"\{\}");\n\nstring s = "This sample will count: {}, {}, {}.";\n\nstring[] replacementStrings = new string[]{"r1", "r2", "r3"};\n\nint i = 0;\n\nstring n = re.Replace(s, m => \n    {\n        return replacementStrings[i++];\n    }); \n\nConsole.WriteLine(n); // outputs: This sample will count: r1, r2, r3.	0
19245251	19244924	Interpreting a JSON structure in my c# example	public class Rootobject\n{\n    public Root Root { get; set; }\n}\n\npublic class Root\n{\n    public Datum[] data { get; set; }\n}\n\npublic class Datum\n{\n    public string CardName { get; set; }\n    public Function[] functions { get; set; }\n}\n\npublic class Function\n{\n    public string State { get; set; }\n}	0
12308412	12303929	How can I parse a value in linq to entity?	var apps_temp = from app in context.Apps.All().ToList();\n\n//this query will not be translated to SQL.\nvar apps = from app in apps_temp\n    where (platform == AppPlatform.All ||\n    (app.Platform == sPlatform && new Version(app.PlatformVersion) <= version))&&\n    (availability == AppAvailability.All || app.Availability == sAvailability)\n    select app;\n\n\nreturn apps.ToList();	0
15041363	15040962	Disable selection by mouse in Microsoft Chart in a C# windows application	myChart.ChartArea[0].CursorX.IsUserSelection = false;\nmyChart.ChartArea[0].CursorX.IsUserEnabled = false;\n\nmyChart.ChartArea[0].CursorY.IsUserSelection = false;\nmyChart.ChartArea[0].CursorY.IsUserEnabled = false;	0
9497926	9497594	App gets stuck when typing in UITextField in a modally presented controller in Simulator	gdb program <PID printed to application output on startup>\n<gdb output>\n(gdb) thread apply all backtrace\n<more gdb output>	0
20635687	20635590	How to handle dependencies between business objects	public CarService(ICarRepository repository, IWheelService wheelservice)\n{\n    ...\n}	0
6521314	6521206	How do you set a username / password on a WCF Client using configuration?	clientCredentials.UserName.UserName = ConfigurationManager.AppSettings["username"];\nclientCredentials.UserName.Password = ConfigurationManager.AppSettings["password"];	0
8723777	8723632	How to find the NOT of Data Table	DataTable onlyInFirstTable = dt1.AsEnumerable().Except(dt2.AsEnumerable()).CopyToDataTable();	0
12900882	12899903	MVC 3 - RequiredAttribute - Override based on session	RuleFor(obj => obj.Email).NotEmpty().Unless(obj => Helpers.ConvertToInt(Services.UserService.GetCurrentPermissionId()) > 1)	0
30046898	30043826	Is it possible to make the Unity3D UI slider that follows a timeline?	public Slider testslider;\n\nvoid Update () {\n        testslider.value += (Time.deltaTime * 0.2f);\n    }	0
2433803	2433766	Overloading Controller Actions	public ActionResult GetAll() \n{ \n    return PartialView(/*return all things*/); \n} \n\npublic ActionResult Get(int id) \n{ \n    return PartialView(/*return 1 thing*/); \n}	0
19936262	19936139	Display different Gridviews with a Dropdownlist onchange	If(Ddl.SelectedValue == "1"){\n\n      GridView1.Visible = true;\n      GridView2.Visible = false;\n\n   }else{\n\n      GridView1.Visible = false;\n      GridView2.Visible = true;\n\n   }	0
2005524	2005478	Should a Test Data Builder construct defaults for it's non-primitives?	var customer = new Fixture()\n    .Build<Customer>()\n    .With(c => c.Id, 99)\n    .CreateAnonymous();	0
20276237	20276005	Servicestack using TryParse by default	this.PreRequestFilters.Add((httpReq, httpRes) => {\n    foreach (string key in httpReq.QueryString)\n    {\n        var val = httpReq.QueryString[key];\n        if (val == "NaN")\n            httpReq.QueryString[key] = "0";\n    }\n});	0
19496989	19496825	Single quoted string to uint in c#	public static int ChunkIdentifierToInt32(string s)\n{\n    if (s.Length != 4) throw new ArgumentException("Must be a four character string");\n    var bytes = Encoding.UTF8.GetBytes(s);\n    if (bytes.Length != 4) throw new ArgumentException("Must encode to exactly four bytes");\n    return BitConverter.ToInt32(bytes, 0);\n}	0
9982147	9981335	Unable to persist the CSS elements on a ASP.NET List Box items	(Client -> IIS WebServer -> ISAPI Extensions -> ISAPI load it/Execute it and send back the converted HTML -> Sends to IIS - > IIS sends back to Client)	0
307401	307365	corrupted email attachments in .NET	pdfStream.Seek(0,SeekOrigin.Begin)	0
28111381	27951362	NullReference when disposing session with transaction	internal NpgsqlException ClearPoolAndCreateException(Exception e)\n    {\n        Connection.ClearPool();\n        return new NpgsqlException(resman.GetString("Exception_ConnectionBroken"), e);\n    }	0
4294393	4294366	WPF C# Setting Font Family of Text Block	new FontFamily(new Uri("pack://application:,,,/"), "./Resources/#Charlemagne Std");	0
9579902	9568537	Multiple lines in Silverlight's autocompletebox	public class MultilineAutocompleteBox : AutoCompleteBox\n{\n    protected override void OnKeyDown(KeyEventArgs e)\n    {\n        if (e.Key == Key.Enter)\n            this.Text = string.Format("{0}\n", this.Text);\n\n        base.OnKeyDown(e);\n    }\n}	0
23102127	23048723	How to achieve better anti-aliasing in GlControl in OpenTK?	glControl = new GLControl(new OpenTK.Graphics.GraphicsMode(32, 24, 0, 8));	0
18541502	18541466	How to populate data dynamically using var theGalaxies = new List<Galaxy>	var theGalaxies = new List<Galaxy>();\nfor (int i=0; i < someArray.Length; i++)\n      theGalaxies.Add(new Galaxy() {Name=someArray[0], distance=someArray[1]});	0
4664803	4664779	Dynamic Object Drawing Based on User Click	Cursor.Position	0
5949603	5949296	Amazon S3 - How to properly build URLs pointing to the objects in a bucket?	using (var s3Client = AWSClientFactory.CreateAmazonS3Client("MyAccessKey", "MySecretKey"))\n{\n    GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()\n        .WithBucketName("MyBucketName")\n        .WithKey("MyFileKey")\n        .WithProtocol(Protocol.HTTP)\n        .WithExpires(DateTime.Now.AddMinutes(3));\n\n    string url = s3Client.GetPreSignedURL(request);\n}	0
8336775	8336635	regex pattern for a range and above 127	string pattern = "[\x00-\x1f]|[\x7f-\uffff]";	0
6086578	6083059	Playing MIDI file in C# from memory	using (var midiStream = new MemoryStream(Resources.myMidi))\n        {\n            var data = midiStream.ToArray();\n            try\n            {\n                using (var fs = new FileStream("midi.mid", FileMode.CreateNew, FileAccess.Write))\n                {\n                    fs.Write(data, 0, data.Length);\n                } \n            }\n            catch(IOException)\n            {}\n            string sCommand = "open \"" + Application.StartupPath + "/midi.mid" + "\" alias " + "MIDIapp";\n            mciSendString(sCommand, null, 0, IntPtr.Zero);\n            sCommand = "play " + "MIDIapp";\n            mciSendString(sCommand, null, 0, IntPtr.Zero);\n        }	0
32047265	32047165	Compare a string which has a param	string pattern = @"Time \(UTC \{(\+)*\d\}\)";\nRegex rgx = new Regex(pattern);	0
30398402	30397861	In SpecFlow can you store more than one hook in the same steps file	[AfterScenario("hook_afterscenario_x_cleanup")]\npublic void AfterScenarioX()\n{\n  //do x\n}\n\n[AfterScenario("hook_afterscenario_y_cleanup")]\npublic void AfterScenarioY()\n{\n  //do y\n}	0
24226519	24216057	Umbraco render strongly typed partial from api	var currentPage = Umbraco.TypedContent(myNodeIdParam);	0
10565151	10565136	How to get base filename without query portion?	new Uri("http://example.com/video.flv?start=5").Segments.Last()	0
22611138	22611061	How to retrieve a variable of type GeoCoordinate from app settings? Windows Phone	private GeoCoordinate MyGeoPosition;    \n\nprivate void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)\n{\n    MyGeoPosition = (GeoCoordinate)appSettings["pushPin"];\n}	0
949072	938801	Using TransactionScope with MySQL and Read Lock	// start transaction\n        using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))\n        {\n            using (SharedDbConnectionScope scope = new SharedDbConnectionScope(DB._provider))\n            {\n\n                try\n                {\n\n                    Record r = new InlineQuery().ExecuteAsCollection<RecordCollection>(\n                        String.Format("SELECT * FROM {0} WHERE {1} = ?param FOR UPDATE",\n                                        Record.Schema.TableName,\n                                        Record.Columns.Column1), "VALUE")[0];\n\n                    // do something\n\n                    r.Save();\n                 }\n             }\n         }	0
19638898	19638606	Exposing a property of a child view model in the parent view model	public SomeViewModel Childvm1\n{\n    get\n    {\n        return childvm1;\n    }\n    set\n    {\n        if (childvm1 != null) childvm1.PropertyChanged -= OnChildvm1PropertyChanged;\n        SetField(ref childvm1, value, "Childvm1");\n        if (childvm1 != null) childvm1.PropertyChanged += OnChildvm1PropertyChanged;\n    }\n}\n\nprivate coid OnChildvm1PropertyChanged(object sender, PropertyChangedEventArgs e)\n{\n    // now update Childvm2\n}	0
24387068	24386671	Dynamic link in asp.net gridview	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n        {\n            if (e.Row.RowType == DataControlRowType.DataRow)\n            {\n                HyperLink hlContro = new HyperLink();\n\n                    hlContro.NavigateUrl = "./Home.aspx?ID=" + e.Row.Cells[1].Text;\n                    //hlContro.ImageUrl = "./sample.jpg";\n                    hlContro.Text = "Documents";\n                    //GridView1.Rows[i].Cells[0].Controls.Add(hlContro);\n\n                e.Row.Cells[8].Controls.Add(hlContro);\n            }\n        }	0
11195066	11194903	Is there a generic type-constraint for "where NOT derived from"?	public interface IFooGenerator\n{\n    Foo GenerateFoo();\n}\n\ninterface ISerialFooGenerator : IFooGenerator { }\n\ninterface IParallelFooGenerator : IFooGenerator { }\n\npublic class FooGenerator : ISerialFooGenerator\n{\n    public Foo GenerateFoo()\n    {\n        //TODO\n        return null;\n    }\n}\n\npublic class ParallelFooGenerator<T> : IParallelFooGenerator\n    where T : ISerialFooGenerator, new()\n{\n    public Foo GenerateFoo()\n    {\n        //TODO\n        return null;\n    }\n}	0
15749285	15749267	How to run more forms simultaneously in one WinForms application?	childform.Show()	0
1060115	1059734	Multiple representations of the same entity	>>>>>  Nathan	0
24369381	24303637	Recognize two skeletons Kinect	int id1 = 0, id2 = 0;\n\n... \n\nif (skeletons.Length != 0)\n{\n    foreach (Skeleton skel in skeletons)\n    {\n         if (skel.TrackingState == SkeletonTrackingState.Tracked)\n         {\n                if (skel.TrackingID == id1)\n                    this.tracked(skel);\n                else if (skel.TrackingID == id2)\n                    this.trackedLeft(skel);\n                else\n                {\n                     if (id1 != 0 && id2 == 0)\n                         id2 = skel.TrackingID;\n                     else if (id2 != 0 && id1 == 0)\n                         id1 = skel.TrackingID;\n                }\n         }\n     }\n  }	0
28217861	28217375	Remove hyphens using regex	new Regex(@"\w{2,}\-\D", RegexOptions.IgnoreCase)\n    .Replace(s, m => m.Groups[0].Value.Replace("-", " "));	0
34051483	34049591	Odbc parses String as Date using internalGetDate?	catch (ArgumentOutOfRangeException ex)\n{\n    if (ex.Message == "Year, Month, and Day parameters describe an un-representable DateTime.")\n    {\n        pi.SetValue(myClass, null, null);\n        var odbcdatareader = typeof(OdbcDataReader);\n        var dataCache = odbcdatareader.GetField("dataCache",\n            BindingFlags.Instance | BindingFlags.NonPublic);\n        var dbcache = dataCache.GetValue(record);\n        var valuesfield = dbcache.GetType()\n            .GetField("_values", BindingFlags.Instance | BindingFlags.NonPublic);\n        var values = (object[]) valuesfield.GetValue(dbcache);\n        values[i] = new DateTime(1, 1, 1);\n        valuesfield.SetValue(dbcache, values);\n    }\n    else\n        throw;\n}	0
15100323	15100165	How to browse a 2D SortedList in C#	foreach (var chunk_row in Chunks.Vales)\n{\n    foreach (var chunk in chunk_row.Values)\n    {\n        chunk.Update(gameTime);\n    }\n}	0
1501810	1501764	Embed Image into own file	public static string ToBase64String(this Bitmap bm)\n{\n  MemoryStream s = new MemoryStream();\n  bm.Save(s, System.Drawing.Imaging.ImageFormat.Bmp);\n  s.Position = 0;\n  Byte[] bytes = new Byte[s.Length];\n  s.Read(bytes, 0, (int)s.Length);\n  return Convert.ToBase64String(bytes);\n}\n\npublic static Bitmap ToBitmap(this string s)\n{\n  Byte[] bytes = Convert.FromBase64String(s);\n  MemoryStream stream = new MemoryStream(bytes);\n  return new Bitmap(stream);\n}	0
22365445	22365285	Getter call not recognised as a statement	private static readonly	0
11600954	11600940	Access to the path while image uploading	var productPath = Server.MapPath("~/App_Upload/Product");\nfuImage.SaveAs(Path.Combine(productPath, fileName));	0
17611518	17611080	changing the system time format on windows 7	RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);\nrk.SetValue("sTimeFormat", "hh:mm:ss"); // HH for 24hrs, hh for 12 hrs	0
5305251	5304087	EF4 How to expose the join table in a many to many relationship	using (var context = new MyContext())\n{\n   var firstEntity = new FirstEntity { Id = firstId };\n   var secondEntity = new SecondEntity { Id = secondId; }\n\n   context.FirstEntities.Attach(firstEntity);\n   context.SecondEntities.Attach(secondEntity);\n\n   firstEntity.SecondEntities = new HashSet<SecondEntity>();\n   firstEntity.SecondEntities.Add(secondEntity);\n\n   context.SaveChanges();\n}	0
11466336	11465767	XNode to string for a child element without namespace	public static XElement IgnoreNamespace(this XElement xelem)\n    {\n        XNamespace xmlns = "";\n        var name = xmlns + xelem.Name.LocalName;\n        return new XElement(name,\n                        from e in xelem.Elements()\n                        select e.IgnoreNamespace(),\n                        xelem.Attributes()\n                        );\n    }\n\n\nstatic void Main(string[] args)\n{\n    var document = XDocument.Parse("<?xml version=\"1.0\" ?><div xmlns=\"http://www.ya.com\"><div class=\"child\"></div></div>");\n    var first = document.Root.Elements().First().IgnoreNamespace();\n    Console.WriteLine(first.ToString());\n}	0
26829516	26829472	How to add one double-quotes (") to string?	string mystring = "We use \"a laser\"";	0
18150265	18149913	Search Distinct values in DataTable	DataView view = new DataView(datatable);\n  DataTable distinctAmount = view.ToTable(true, "Amount", "xxx","xxxx"...);	0
21320321	21320188	Properties in my code behind all go null when Wizard control's next button is clicked,	public string Firstname{\n\n    get {\n\nreturn ViewState["Firstname"] == null ?String.Empty :(string)ViewState["Firstname"];\n\n    }\n    set { ViewState["Firstname"] = value; }\n}	0
12691204	12691069	Include version number in a file on successful build	Assembly web = Assembly.Load("App_Code");  \nAssemblyName webName = web.GetName(); \nstring myVersion = webName.Version.ToString();	0
7565274	7565211	Linq intersect or join to return items from one collection that have matching properties to another?	var match = (from a in accounts\n             select new { P = a.Prefix, N = a.Number, S = a.Suffix })\n  .Intersect(from l in lookup\n             select new { P = l.Prefix, N = l.Number, S = l.Suffix })\n  .Select(t => string.Format("{0}{1}{2}", t.P, t.N, t.S));;	0
21603457	21602935	How to Properly Set the State of a CheckBox Control in OnNavigatedTo	// in page Constuctor or in XAML:\nmyCheckBox.Click += myCheckbox_Click;\n\nprivate void myCheckbox_Click(object sender, RoutedEventArgs e)\n{\n   if (myCheckBox.IsChecked == true)\n   {\n      //do for check\n   }\n   else\n   {\n      //do for uncheck\n   }\n}	0
34512759	34512442	How to apply contract behavior to service with an attribute?	Debugger.Launch();	0
2406208	2406184	C# Lambda Expression Speed	Dictionary<Your_Key,Record>	0
24253964	24249419	Adding models to a list in presenter	_Model = (IAttendance)_Model.Clone();\nSetModelPropertiesFromView(_Model, _View);\nAttendanceList.Add(_Model);	0
11009699	11009655	Convert.DateTime throws error: String was not recognized as a valid DateTime for "06-13-2012"	DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)	0
33689819	33689646	Finding all groups in a split string	string input = "Tr.WH.Eu6.ISC";\nstring[] groups = input.Split('.');\nstring[] output = groups.Select((x, idx) => string.Join(".", groups.Take(idx + 1)))\n                        .ToArray();	0
29870274	29869882	How to Use a Tag to Change the Properties of Multiple Items With That Tag?	private void ChangeStyleByTag(Control parent, string tag)\n    {\n        foreach (Control c in parent.Controls)\n        {\n            if (c.Tag!=null && c.Tag.Equals(tag))\n            {\n                (c as Button).FlatStyle = FlatStyle.Flat;\n                (c as Button).FlatAppearance.BorderSize = 3;\n                (c as Button).FlatAppearance.BorderColor = Color.Blue;\n            }\n            else\n                ChangeStyleByTag(c, tag);\n        }\n    }\n\n    private void buttonBritishGas_Click(object sender, EventArgs e)\n    {\n\n        ChangeStyleByTag(this, "SelectedSupplier");\n        ChangeStyleByTag(this, "Supplier");\n    }	0
4469174	4443191	How do I extract table names from MS Access database using ADO	using System;\nusing System.Data;\nusing System.Data.OleDb;\n\npublic class DatabaseInfo {    \n    public static void Main () { \n        String connect = "Provider=Microsoft.JET.OLEDB.4.0;data source=.\\Employee.mdb";\n        OleDbConnection con = new OleDbConnection(connect);\n        con.Open();  \n        Console.WriteLine("Made the connection to the database");\n\n        Console.WriteLine("Information for each table contains:");\n        DataTable tables = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});\n\n        Console.WriteLine("The tables are:");\n            foreach(DataRow row in tables.Rows) \n                Console.Write("  {0}", row[2]);\n\n\n        con.Close();\n    }\n}	0
16018947	16018642	how to add dropdown list in detailview asp.net	protected void DV_WScript_ItemInserting(object sender, DetailsViewInsertEventArgs e)\n{\n        //Put here if you want to find control of your Insert Mode\n           DropDownList dropDown = (DropDownList)DetailsView1.FindControl("ddl_Ext");\n           string Ext = dropDown.selectedValue;\n\n}	0
10195432	10195405	pass textbox string to custom control using application properties	//To Set:    \nApp.Current.Properties["TextBoxString"] = textBox1.Text;\n//To Get:\nstring myProperty = (string) App.Current.Properties["TextBoxString"];	0
2103102	2102960	How to stop DispatcherTimer from inside Try - Catch?	private void dispatcherTimer_Tick(object sender, EventArgs e)\n{           \n    try\n    {\n       MethodOne()\n    }\n    catch (Exception)\n    {\n        (sender as DispatcherTimer).Stop();\n    }  \n}	0
31123721	31123465	Looping up inheritance to get overridden properties	public class baseType\n{\n    public string P { get { return "A"; }}\n}\n\npublic class child : baseType\n{\n    new public string P { get { return "B"; }}\n}\n\npublic static object GetBasePropValue(object src, string propName)\n{\n    return src.GetType().BaseType.GetProperty(propName).GetValue(src, null);\n}\n\npublic static object GetPropValue(object src, string propName)\n{\n    return src.GetType().GetProperty(propName).GetValue(src, null);\n}\n\nvoid Main()\n{\n    var x = GetPropValue(new child(), "P");\n    var y = GetBasePropValue(new child(), "P");\n}	0
3999620	3999540	DataGrid: Dyanmically adding rows	gvAdminSummary.Rows.Add( { p.FName, p.LName, p.PNo });	0
339798	339792	C# VS 2005: How to get a class's public member list during the runtime?	tt.GetType().GetFields()	0
9846973	9846948	Split string into string array of single characters	char[] characters = "this is a test".ToCharArray();	0
4240260	4240250	XML using in C#	XDocument document = XDocument.Parse(rawXmlString);\n\n// Iterates through each element inside the XML document\nforeach (XElement el in document.Root.Elements())\n{\n    // Iterates through each attribute in an element\n    foreach (XAttribute attribute in el.Attributes())\n    {\n        // Action here\n    }\n}	0
1488868	1488817	How to handle exception in a background thread in a unit test?	private AutoResetEvent ReceiveEvent = new AutoResetEvent(false);\nprivate EventArgs args;\nprivate bool ReceiveCalled = false;\n\n// event handler with some argument\nprivate void Receive(object sender, EventArgs args)\n{\n  // get some arguments from the system under test\n  this.args= args;\n\n  // set the boolean that the message came in\n  ReceiveCalled = true;\n\n  // let the main thread proceed\n  ReceiveEvent.Set();\n}\n\n[TestMethod]\npublic void Test()\n{\n  // register handler\n  Server.OnReceive += Receive;\n\n  var message = new Foo();\n  Client.Send(message);\n\n  // wait one second for the messages to come in\n  ReceiveEvent.WaitOne(1000);\n\n  // check if the message has been received\n  Assert.IsTrue(\n    ReceiveCalled, \n    "AcceptClientReceived has not been called");\n\n  // assert values from the message\n  Assert.IsInstanceOfType(args.Message, typeof(Foo))    \n}	0
1190046	1189979	Implementing conditional in a fluent interface	TicketRules\n.RequireValidation()\n.When(quartType => quartType == QuartType.Before,\n      rule => rule.TotalMilageIs(64))\n.When(quartType => quartType == QuartType.After,\n      rule => rule.TotalMilageIs(128));	0
2862031	2861976	How to open a WPF Content Stream?	Application.GetContentStream	0
24292959	24292927	LINQ query for retrieving data from list	var q = from n in table\n        group n by n.Senderinto g\n        select g.OrderByDescending(t=>t.Timestamp).FirstOrDefault();	0
12388607	12388579	To fetch the unique characters from a string?	string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";\nvar newstr = String.Join("", s.Distinct());	0
3820415	3819857	How to change Asp.net Theme via Web.Config on the fly	switch(Request.URL)\n{\n case "www.customer1.com":\n    Theme = "Customer1";\n    break;\n case "www.customer2.com":\n    Theme = "Customer2":\n    break;\n}	0
980873	980666	Need a method that accepts all kind of Subsonic Collections as a parameter	public void <T>(T list) where T : BindingListEx<IActiveRecord>\n{\n    foreach(IActiveRecord item in list)\n    {\n\n    }\n}	0
2002309	2002261	Find the number of divisors of a number given an array of prime factors using LINQ	int[] factors = new int[] { 2, 2, 3, 5 };\nvar q = from o in factors\n        group o by o into g\n        select g.Count() + 1;\nvar r = q.Aggregate((x, y) => x * y);	0
462031	451058	How to create a derived ComboBox with pre-bound datasource that is designer friendly?	if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n{\n    // Do your database/IO/remote call\n}	0
34079792	34079513	Alter table, passing dataype by parameter, results in a syntax error	var validator = new Regex(@"^\w+$");\nif (new[] { TABLE_kvp.Key, kvp.Key, kvp.Value }.All(validator.IsMatch))\n{\n    command.CommandText = String.Format("ALTER TABLE {0} ADD COLUMN {1} {2}", \n        TABLE_kvp.Key,\n        kvp.Key,\n        kvp.Value);   \n}	0
25602730	25591317	how to get rid of security message box from gecko webbrowser	Application.OpenForms[1].Close();	0
8443247	8443198	C# converts inches to cents	class Program : MarshalByRefObject\n{\n    static void Main(string[] args)\n    {\n        Console.Write("give number in inches : ");\n        int calculating = int.Parse(Console.ReadLine());\n        inches(calculating);\n        Console.ReadKey();\n    }\n\n    private static double inches(int calculating)\n    {\n        Console.WriteLine(calculating + " inches = " + 2.54 * calculating + " cm");\n        return 0;\n    }\n}	0
4795351	4795311	split string before hyphen - asp.net c#	string result = theString.Substring(0, theString.IndexOf("-")).Trim();	0
19480852	19480793	How to access to the Outer class's field from Inner class of same name in C#? (nested-class)	class OuterClass\n{\n    static int Number;\n\n    class InnerClass\n    {\n        public InnerClass(int Number)\n        {\n            OuterClass.Number = Number;   \n        }\n    }\n}	0
11297059	11251395	See if user is admin in Windows 7?	public static bool IsAuthorizedUser(string userId) \n {\n     PrincipalContext ctx = new PrincipalContext(ContextType.Machine);\n     UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);\n\n     bool result = false;\n     if(usr == null)\n     {\n         Console.WriteLine("usr is null");\n     }\n     else\n     {\n         foreach (Principal p in usr.GetAuthorizationGroups())\n         {\n             if (p.ToString() == "Administrators")\n             {\n                 result = true;\n             }\n         }\n      }\n      return result;\n    }	0
2507648	2506426	Using the Specification Pattern	GetCustomers().Where(customer => customer.IsActive && customer.City == "Oakland");	0
17869187	17867143	DataTable group by separated by comma	var query = from row in dataTable.AsEnumerable()\n                group row by row["cname"] into g\n                select new {    cname = g.Key,\n                                tname = g.First()["tname"] ,\n                                text = String.Join(", ", g.Select(r=>r["text"].ToString()).ToArray()),\n                                allowgrouping = g.First()["allowgroupping"]\n                };\n\n    foreach (var row in query)\n    {\n        resultDataTable.Rows.Add(row.cname, row.tname, row.text, row.allowgrouping);\n    }	0
28543852	28542970	Simple injector lifestyle warnings for web api controllers	var results = \n    from result in Analyzer.Analyze(container)\n    let disposableController =\n        result is DisposableTransientComponentDiagnosticResult &&\n        typeof(ApiController).IsAssignableFrom(result.ServiceType)\n    where !disposableController\n    select result;\n\nresults.Should().HaveCount(0, String.Join(Environment.NewLine,\n    results.Select(x => x.Description)));	0
21700862	21700743	get the total sum of all domain controllers	int domainCnt = Domain.GetCurrentDomain().FindAllDiscoverableDomainControllers().Count;	0
20795649	20795504	Update specific column in grid view from button click	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n        if(e.Row.Cells[0].Text =="F")\n        {\n            e.Row.Cells[0].Text = "CF";\n        }\n        else if (e.Row.Cells[0].Text == "N")\n        {\n            e.Row.Cells[0].Text = "CN";\n        }\n}	0
31751877	31751729	Remove Minutes from a Timespan duration	string startTime = teststart.Text;\nstring finishTime = testfinish.Text;\nstring lunchTime = testlunch.Text;\n\nTimeSpan duration = DateTime.Parse(finishTime).Subtract(DateTime.Parse(startTime)).\n    Subtract(TimeSpan.FromMinutes(Int32.Parse(lunchtime)));	0
23603788	23603628	How do I map a perlin noise function (libnoise) to an array of tiles?	Perlin.GetValue(x, y, z)	0
22224918	22194095	Is it possible to use two different header section in Master Page in Kentico?	{% x=CurrentDevice.IsMobile; if (x) {"<link href=\"mobile.css\" type=\"text/css\" rel=\"stylesheet\" />"} else {"<link href=\"normal.css\" type=\"text/css\" rel=\"stylesheet\" />"} %}	0
531034	531025	Dynamically getting/setting a property of an object in C# 2005	entObj.GetType().GetProperty("templateFROM").SetValue(entObj, _sVal, null);	0
30683291	30683269	Clone a file and modify it	using (var reader = File.OpenText(@"c:\test.txt"))\n{\n    using (var writer = File.CreateText(@"c:\test2.txt"))\n    {\n        string line;\n        while ((line = reader.ReadLine()) != null)\n        {\n            // Handle triggers or whatever\n            writer.WriteLine(line);\n        }\n    }\n}	0
17650784	17650407	How to set default date for the calender control in asp.net	protected void Page_Load(object sender, EventArgs e)\n    {\n    calenderSagar.SelectedDate=DateTime.Now.AddDays(-8);\n    }	0
1247253	1247239	How to simulate a Host file for the time of one request	ServicePointManager.ServerCertificateValidationCallback += delegate\n{\n    return true; // you might want to check some of the certificate detials...\n};	0
21069579	21068472	SignalR - Send message to user using UserID Provider	[HubName("myhub")]\n[Authorize]\npublic class MyHub1 : Hub\n{\n    public override System.Threading.Tasks.Task OnConnected()\n    {\n        var identity = Thread.CurrentPrincipal.Identity;\n        var request = Context.Request;\n        Clients.Client(Context.ConnectionId).sayhello("Hello " + identity.Name);\n        return base.OnConnected();\n    }\n}	0
615883	615874	How to convert a sortedDictionary into Dictionary?	var dictionary = new Dictionary<type1,type2>(optionsSorted);	0
16905547	16904361	Binding Linq-to-SQL Query results to Stringbuilder	foreach (var entrant in Entrants)\n{\n    Console.WriteLine(entrant);\n}	0
15925789	15925684	Webpage has expired	Response.Buffer = true;\n    Response.ExpiresAbsolute = DateTime.Now.Subtract(TimeSpan.FromMilliseconds(1));\n    Response.Expires = 0;\n    Response.CacheControl = "no-store";\n    Response.Cache.SetNoStore();\n    Response.AppendHeader("Pragma", "no-cache");\n    Response.post-check=0;\n    Response.pre-check=0;	0
12842177	12842150	Convert a Guid to byte[16] in C#	Guid.ToByteArray	0
26663390	26663339	How to Duplicate an Array in C#	string[] deck = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", };\nvar newDeck = Enumerable.Repeat(deck, 2).SelectMany(x => x).ToArray();	0
16096564	16096458	LoadControl, usercontrol in WebMethod	UserControl uc= new UserControl();\nControl control = uc.LoadControl("~/Shared/Controls/EmailTemplate_PartnerWithUs.ascx");	0
10075351	10073692	How to set radio buttons in a nested group box as a same group with radio buttons outside of that group box	private List<RadioButton> _radioButtonGroup = new List<RadioButton>();\nprivate void radioButton_CheckedChanged(object sender, EventArgs e)\n{\n    RadioButton rb = (RadioButton)sender;\n    if (rb.Checked)\n    {\n        foreach(RadioButton other in _radioButtonGroup)\n        {\n            if (other == rb)\n            {\n                continue;\n            }\n            other.Checked = false;\n        }\n    }\n}	0
33118495	33006917	Dropdownlist showing default value but cannot be populated again to update	cmd.CommandText = "SELECT * FROM COMPANY";\nDataTable dtt = new DataTable();\ndtt.Load(cmd.ExecuteReader());\nDropDownList ddlCompanyName = new DropDownList();\nString compidd = ddlCompanyName.SelectedValue;\nddlCompanyName.DataSource = dtt;\nddlCompanyName.DataTextField = "COMPANYNAME";\nddlCompanyName.DataValueField = "COMPANYID";\nddlCompanyName.DataBind();\nddlCompanyName.SelectedValue = compidd;	0
24218649	24159300	Resize control to match aspect ratio	private void Form1_Resize(object sender, EventArgs e)\n{\n    Control Container = this;\n    Control ViewPort = textBox1;\n\n    float ContainerRatio = 1f * Container.ClientRectangle.Width / Container.ClientRectangle.Height;\n\n    const float TargetRatio_3_2 = 3f / 2f;\n    const float TargetRatio_16_9 = 16f / 9f;\n    const float TargetRatio_4_3 = 4f / 3f;\n    const float TargetRatio_16_10 = 16f / 10f;\n    //..\n\n    float TargetRatio = TargetRatio_3_2;\n\n    if (ContainerRatio < TargetRatio)\n    {\n        ViewPort.Width = Container.ClientRectangle.Width;\n        ViewPort.Height = (int)(ViewPort.Width / TargetRatio);\n        ViewPort.Top = (Container.ClientRectangle.Height - ViewPort.Height) / 2;\n        ViewPort.Left = 0;\n    }\n    else\n    {\n        ViewPort.Height = Container.ClientRectangle.Height;\n        ViewPort.Width = (int)(ViewPort.Height * TargetRatio);\n        ViewPort.Top = 0;\n        ViewPort.Left = (Container.ClientRectangle.Width - ViewPort.Width) / 2;\n    }\n\n}	0
2930168	2929970	How to debug ctypes call of c++ dll?	>>> from comtypes import client, COMError\n>>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass')\n>>> try:\n...     myclassinst.DoInvalidOperation()\n... except COMError as e:\n...     print e.args\n...     print e.hresult\n...     print e.text\n...\n(-2147205118, None, (u'MyCOMClass: An Error Message', u'MyCOMClass.MyCOMClass.1', None, 0, None))\n-2147205118\nNone	0
18917285	18916947	installing multiple exe's at same time in window from application	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
16800608	16795721	Access Parent page name in Radwindow	function GetRadWindow() {\n            var oWindow = null;\n            if (window.radWindow)\n                oWindow = window.radWindow;\n            else if (window.frameElement.radWindow)\n                oWindow = window.frameElement.radWindow;\n            return oWindow;\n        }\n\nfunction GetparentWindowname()\n{\nvar _ParentName=GetRadWindow().BrowserWindow.document.location.href;\nalert(_ParentName);\n}	0
28958674	28811229	Gecko Select Element Set Selected without Submit	nsAStringBase eventType = (nsAStringBase)new nsAString("keyup");\n                                var ev = browser.Document.CreateEvent("HTMLEvents");\n                                ev.DomEvent.InitEvent(eventType, false, false);\n                                enquiryTypeCombo.GetEventTarget().DispatchEvent(ev);	0
15915800	15911616	MS Visio - Create/Insert a new Page/Tab in C#	namespace VisioExample\n{\n    using System;\n    using Microsoft.Office.Interop.Visio;\n\n    class Program\n    {\n        public static void Main(string[] args)\n        {\n            // Start Visio\n            Application app = new Application();\n\n            // Create a new document.\n            Document doc = app.Documents.Add("");\n\n            // The new document will have one page,\n            // get the a reference to it.\n            Page page1 = doc.Pages[1];\n\n            // Add a second page.\n            Page page2 = doc.Pages.Add();\n\n            // Name the pages. This is want is shown in the page tabs.\n            page1.Name = "Abc";\n            page2.Name = "Def";\n\n            // Move the second page to the first position in the list of pages.\n            page2.Index = 1;                \n        }\n    }\n}	0
19054851	19054753	C# Split Numbers & Strings	string[] digits = Regex.Split(Stack, @"\D+")\n    .Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();\ntextoutput1.Text = digits[0];\ntextoutput2.Text = digits.ElementAtOrdefault(1);	0
25864552	25864365	moving a csv file to new folder with todays date on different path	string sourceFile = @"c:\finaltest12.csv";\n        if (!File.Exists(sourceFile))\n            return;\n\n        string Todaysdate = DateTime.Now.ToString("dd-MMM-yyyy");\n        string newPath = Path.Combine(@"c:\test\final test\snaps\", Todaysdate);\n\n        if (!Directory.Exists(newPath))\n            Directory.CreateDirectory(newPath);\n\n        try\n        {\n            File.Move(sourceFile, Path.Combine(newPath, Path.GetFileName(sourceFile)));\n        }\n        catch\n        {\n            //ToDo\n        }	0
1278419	1278126	C# application terminates unexpectedly	public static void inputHandler(ConsoleCtrl.ConsoleEvent consoleEvent)\n{\n   if (ConsoleEvent == ConsoleCtrl.ConsoleEvent.CtrlLogOff)\n       return true; \n   return false;\n}	0
7274643	7197182	Windows Update API c# : set download location	foreach (IUpdate child in Item.BundledUpdates)\n{\n   child.CopyFromCache(path, false);\n}	0
3122173	3122140	How to Overload ActionResult in Asp.Net MVC2	[RequireRequestValue("someInt")]\npublic ActionResult MyMethod(int someInt) { /* ... */ }\n\n[RequireRequestValue("someString")]\npublic ActionResult MyMethod(string someString) { /* ... */ }	0
11013320	11013203	Getting the Name of a Func<TSource, TKey> Generic Type Parameter	Expression<Func<TSource, TKey>>	0
9508928	9508879	Cannot access a closed Stream of a memoryStream, how to reopen?	memoryStream = new MemoryStream();	0
12870849	12870137	Automatically add watermark to an image	private void button1_Click(object sender, EventArgs e)\n    {\n        using (Image image = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"))\n        using (Image watermarkImage = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\watermark.png"))\n        using (Graphics imageGraphics = Graphics.FromImage(image))\n        using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))\n        {\n            int x = (image.Width / 2 - watermarkImage.Width / 2);\n            int y = (image.Height / 2 - watermarkImage.Height / 2);\n            watermarkBrush.TranslateTransform(x, y);\n            imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width+1, watermarkImage.Height)));\n            image.Save(@"C:\Users\Public\Pictures\Sample Pictures\Desert_watermark.jpg");\n        }\n\n    }	0
23500620	23499432	How to Deserialize using binary Deserialization from file text file	public static void SaveRestaurantList(List<Restaurant> restaurantList) \n{ \n   using(FileStream fs = new FileStream("Restaurant.txt", FileMode.Create, FileAccess.Write))\n   {\n       BinaryFormatter bf = new BinaryFormatter(); \n       bf.Serialize(fs, restaurantList); \n   }\n}	0
30562982	30562822	How to filter a collection of delegates based on their parameter's generic type in C#?	var aDelegates = someClass.Delegates.Where(d => \n        d.Method.DeclaringType.GenericTypeArguments.FirstOrDefault().IsAssignableFrom(typeof(SomeInterfaceImplA)));	0
6220547	6220502	Accessing labels within a LoginView	var foo = (Label)LoginView1.FindControl("Foo");\nfoo.Text =  "I am Foo";	0
11834724	11834605	Handling shorthand closing tag while parsing XML	XmlReader.IsEmptyElement	0
5467934	5467905	Sending SMS from asp.net website	static void Main(string[] args)\n{\n    TwilioRestClient client;\n\n    // ACCOUNT_SID and ACCOUNT_TOKEN are from your Twilio account\n    client = new TwilioRestClient(ACCOUNT_SID, ACCOUNT_TOKEN);\n\n    var result = client.SendMessage(CALLER_ID, "PHONE NUMBER TO SEND TO", "The answer is 42");\n    if (result.RestException != null) {\n        Debug.Writeline(result.RestException.Message);\n    }    \n}	0
6157450	6156857	How to capture the whole query string?	string redirectURL = "http://www.example.com/myPage.aspx?" + Request.QueryString.ToString(); \nResponse.Redirect(redirectURL);	0
13515129	13514481	Getting children children in sitecore	contextItem.Axes.GetDescendants().Where(x => x.TemplateName == "cool    template").ToList();	0
11324157	11324058	Adding Data to a datagridview in another form in C#?	frm8.dataGridView1.Invalidate();	0
10444389	10444087	How to remove cookies under 1 domain in CookieContainer	CookieContainer c = new CookieContainer();\nvar cookies = c.GetCookies(new Uri("http://www.google.com"));\nforeach (Cookie co in cookies)\n{\n  co.Expires = DateTime.Now.Subtract(TimeSpan.FromDays(1));\n}	0
11395002	11394690	How to store Texture2D in a listDictionary in C#?	public class TurretHullInfo\n{\n    Texture2D Graphic { get; set; }\n    int Rows { get; set; }\n    int Columns { get; set; }\n}\n\npublic static class LoadGraphics\n{\n    //global variable\n    public static TurretHullInfo _blue_turret_hull;\n\n    public static void LoadContent(ContentManager contentManager)\n    {\n        //loads all the graphics/sprites\n        _blue_turret_hull = new TurretHull();\n        _blue_turret_hull.Graphic = contentManager.Load<Texture2D>("Graphics/Team Blue/Turret hull spritesheet");\n        _blue_turret_hull.Rows = 1;\n        _blue_turret_hull.Columns = 11;\n    }\n}\n\nclass Turret_hull : GameObject\n{\n    public Turret_hull(Game game, String team)\n        : base(game)\n    {\n        if(team == "blue")\n            _texture = LoadGraphics._blue_turret_hull.Graphic;     \n    }\n}	0
25092258	25090530	Getting MySQL cell data to an label in C#	command.CommandText = "SELECT CurrentNews FROM News";\nstring txtNews = Convert.ToString(command.ExecuteScalar());\nlblNews.Text = txtNews;	0
7343949	7343607	Problem Passing Parameters from XAML	cmds:PopupBehavior.CustomUI> \n    <views:View2 CategoryID="5"/> \n</cmds:PopupBehavior.CustomUI>	0
128896	128857	Is this a proper way to get a WebProfile?	public WebProfile p = null;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    p = ProfileController.GetWebProfile();\n    if (!this.IsPostBack)\n    {\n         PopulateForm();\n    }       \n}\n\npublic static WebProfile GetWebProfile()\n{\n    //get shopperID from cookie\n    string mscsShopperID = GetShopperID();\n    string userName = new tpw.Shopper(Shopper.Columns.ShopperId,        mscsShopperID).Email;\n    return WebProfile.GetProfile(userName); \n}	0
8917985	8909974	How to display an image from web in wp7?	public void LoadImage(string uri)\n{\n    WebClient wc = new WebClient();\n    wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);\n    wc.OpenReadAsync(new Uri(uri));\n}\n\nprivate void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)\n{\n    BitmapImage bi = new BitmapImage();\n    bi.SetSource(e.Result);             // Here, you got your image\n}	0
15103179	15102823	How to extract values from List<T> into M x 1 double[,] array concisely with less line of code?	var result = new double[entries.Count * 3, 1];\n\nfor (int i = 0; i < entries.Count; i++)\n{\n    result[i, 0] = entries[i].Position.X;\n    result[i + entries.Count, 0] = entries[i].Position.Y;\n    result[i + entries.Count * 2, 0] = entries[i].Position.Z;\n}	0
8608328	8608311	How to add buttons dynamically to my form?	private void button1_Click(object sender, EventArgs e)\n{\n    List<Button> buttons = new List<Button>();\n    for (int i = 0; i < 10; i++)\n    {\n        Button newButton = new Button();\n        buttons.Add(newButton);\n        this.Controls.Add(newButton);   \n    }\n}	0
8381789	8381733	Game of Life - Dead	if (surrounding_cells > 3)\n{\n   board[x, y] = dead;\n}	0
9786683	9786379	Overriding methods in Unity3d	class Tab\n{\n    public delagate void MyOnGUI(); // Declare the delegate\n\n    private MyOnGUI onGUI;  // An instance of the delegate\n\n    public Tab(string s, MyOnGUI onGUI)\n    {\n        this.onGUI = onGUI;\n        //...\n    }\n\n    public void OnGUI()\n    {\n        onGUI(); // Call the delegate\n    }\n}\n// ...\n\ntabs.addTab(new Tab("test", delegate(){\n    // Your code here\n    });	0
10270500	10270292	How to rotate picturebox	private Bitmap RotateImageByAngle(Image oldBitmap, float angle)\n{\n    var newBitmap = new Bitmap(oldBitmap.Width, oldBitmap.Height);\n    newBitmap.SetResolution(oldBitmap.HorizontalResolution, oldBitmap.VerticalResolution);\n    var graphics = Graphics.FromImage(newBitmap);\n    graphics.TranslateTransform((float)oldBitmap.Width / 2, (float)oldBitmap.Height / 2);\n    graphics.RotateTransform(angle);\n    graphics.TranslateTransform(-(float)oldBitmap.Width / 2, -(float)oldBitmap.Height / 2);\n    graphics.DrawImage(oldBitmap, new Point(0, 0));\n    return newBitmap;\n}	0
17486148	17484321	Allowing users to view parts of webpage based on their Windows domain login	[Authorize(Roles = "AdminRole, CreditAdvisorRole")]\npublic ActionResult Edit()\n{\n    var viewModel = _shopService.ShopIndex();\n    return View(viewModel);\n}	0
20354775	20353277	Create delegate from a constructor of unknown type implementing a known interface	var del = Expression.Lambda<Func<IMyInterface>>(Expression.New(type)).Compile();	0
8521920	7487009	Using Select to filter a dataset that was defined using Wizards in VS 2010?	this.specialTableAdapter.Connection.ConnectionString = "..top secret..";     \nthis.specialBindingSource.Filter = "customer_name like 'atwood%' ";     \nthis.specialTableAdapter.Fill(this.dataDataSet.customerTable);	0
21486380	21485953	String replace with pattern matching	// Error checking needed.....\nstring input = "You can use the [xyz] Framework to develop [123], web, and [abc] apps";\nRegex re = new Regex(@"(\[[^\]]+\])");\nMatchCollection matches = re.Matches(input);\ninput = input.Replace(matches[0].Value, ".NET").Replace(matches[1].Value, "desktop").Replace(matches[2].Value, "mobile");	0
30943889	30943693	How To Add Items From a ComboBox to a List Collection	List<string> comboItems = comboEmail.Items.Cast<string>().ToList();	0
13198315	13198203	combining two strings with least code	string s1 = "some_string";\nstring s2 = "AB";\n\nstring s3 = s1.Substring(0, Math.Min(s1.Length, 20 - s2.Length)) + s2;	0
928295	928216	Run a method on all objects within a collection	class MyArgs { }\nclass Razzie //pretend this is a 3rd party class that we can't edit\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n}\nstatic class RazzieExtensions\n{\n    public static Razzie MyMethod(this Razzie razzie, MyArgs args)\n    {\n        razzie.FirstName = razzie.FirstName.ToUpper();\n        return razzie;\n    }\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var bloops = new List<Razzie>\n            {\n                new Razzie{FirstName = "name"},\n                new Razzie{FirstName = "nAmE"}\n            };\n        var myArgs = new MyArgs();\n        var results = from item in bloops\n                      select new Razzie\n                      {\n                          FirstName = item.FirstName,\n                          LastName = item.LastName\n                      }.MyMethod(myArgs);\n\n        foreach (var r in results)\n            Console.WriteLine(r.FirstName);\n        Console.ReadKey();\n    }\n}	0
3120217	3120181	InvalidOperationException when assigning text to a TextField	void watcher_Changed(object sender, FileSystemEventArgs e)\n{\n    String text = File.ReadAllText(e.FullPath);\n\n    this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action) () => \n        {\n             this.txtFile.Text = text;\n             // Do all UI related work here...\n        });\n}	0
6507787	6507451	Linq to XML Read xml file using linq	XDocument doc = XDocument.Load(@"file.xml");\n    XNamespace df = doc.Root.Name.Namespace;\n    var results = from request in doc.Descendants(df + "Request")\n                  where request.Elements(df + "UniqueData").Elements(df + "UniqueNumber").Any()\n                  select new\n                  {\n                      ordNumber = (int)request.Attribute("OrderNumber"),\n                      uniqueNumber = (decimal)request.Element(df + "UniqueData").Element(df + "UniqueNumber")\n                  };\n    foreach (var result in results)\n    {\n        Console.WriteLine("{0}-{1}", result.ordNumber, result.uniqueNumber);\n    }	0
24420383	22991009	How to get Hounsfield units in Dicom File using Fellow Oak Dicom Library in c#	Hounsfield units = (Rescale Slope * Pixel Value) + Rescale Intercept	0
34097162	33871070	Highlighting cells/making them bold in Excel	Microsoft.Office.Interop.Excel.Range range = xlWorkSheet.get_Range("A1:A6","G1:G6");\nrange.Font.Bold = true;	0
30823417	30803875	How can assign a value that comes through the query string into a hidden mvc5 register control	Html.LabelFor(m => m.AvatarID, new { @class = "col-md-2 control-label" })\n            <div class="col-md-10">\n                @Html.TextBoxFor(m => m.AvatarID, new {@Value=Request.QueryString["ID"], @class = "form-control" })\n            </div>	0
25518849	25518753	Assign List value to a class properties	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n\n    public static void Main()\n    {\n        var listValue = new List<string>()\n        {\n            "Hello",\n            "Hello2",\n            "Hello3",\n        };\n\n        var sampleClass = new SampleClass();\n        var sampleType = sampleClass.GetType();\n        var properties = sampleType.GetProperties().OrderBy(prop => prop.Name).ToList();\n        for (int i = 0; i < listValue.Count; i++)\n        {\n            if (i < properties.Count)\n            {\n                properties[i].SetValue(sampleClass, listValue[i]);\n                Console.WriteLine(properties[i].Name + " = " + listValue[i]);\n            }\n        }\n        Console.ReadLine();\n    }\n\n    public class SampleClass\n    {\n        public string _VarA { get; set; }\n        public string _VarB { get; set; }\n        public string _VarC { get; set; }\n        //around 40 attribute\n    }\n}	0
955618	955611	XmlWriter to Write to a String Instead of to a File	using (var sw = new StringWriter()) {\n  using (var xw = XmlWriter.Create(sw)) {\n    // Build Xml with xw.\n\n\n  }\n  return sw.ToString();\n}	0
21977277	21977120	How to read some string character and identify it?	var values = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries);\nif (values.Length != 2)\n    throw new ArgumentException("Unexpected input format.");\n\nvar msb = Convert.ToByte(values[0]);\nvar lsb = Convert.ToByte(values[1]);\n\nvar result = (msb * 256) + lsb;	0
12302881	12302333	RegEx Pattern Matching	((\*\s*)?fcid\s*0x\w{6}\s*\[(device-alias.*?|pwwn\s\w{2}(\:\w{2}){7})\]|pwwn\s\w{2}(\:\w{2}){7})	0
5569470	5569427	Remove escape sequence in c#	Console.Out.WriteLine("\"hi there \"");\n// outputs "hi there "	0
18281829	18280976	Button prevents KeyDown event from triggering even with keypreview = true	protected override bool ProcessDialogKey(Keys keyData) {\n        switch (keyData) {\n            case Keys.Left:\n                //...\n                return true;\n        }\n        return base.ProcessDialogKey(keyData);\n    }	0
4178779	4178670	Create a delegate with arbitrary parameters	public TDelegate GetMethod<TDelegate>(MethodInfo methodToRepresent, object instanceToInvokeOn)\n  where TDelegate:class\n{\n   return (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), instanceToInvokeOn, methodToRepresent);\n}	0
3255949	3255276	LINQ. Update one dictionary from corresponding values in another joined by key	Dictionary<double, double> dictionary =\n(from d1 in dic1\n join d2 in dic2 on d1.Key equals d2.Key into kvp\n from nv in kvp.DefaultIfEmpty(d1)\n select nv).ToDictionary(x => x.Key, x => x.Value);	0
6082552	6082535	Open new instance of C# windows application	var info = new System.Diagnostics.ProcessStartInfo(Application.ExecutablePath);\nSystem.Diagnostics.Process.Start(info );	0
10500149	10500095	Getting time difference between two values	DateTime t1 = Convert.ToDateTime(textBox1.Text);\n        DateTime t2 = Convert.ToDateTime(textBox2.Text);\n        TimeSpan ts = t1.Subtract(t2);	0
8010397	8010353	Strange ASP.NET issue when trying to find value contained in a TextBox	descriptionBox.Attributes["readonly"] = "readonly"	0
1109281	1109270	What is the fastest way to find out if a string ends with another string?	String.EndsWith	0
11677912	11677765	Upload image to server with custom data	-------------------------------18788734234\nContent-Disposition: form-data; name="nonfile_field"\n\nvalue here\n-------------------------------18788734234\nContent-Disposition: form-data; name="myfile"; filename="ad.gif"\nContent-Type: image/gif\n\n[ooh -- file contents!]\n-------------------------------18788734234--	0
2116468	1796117	how to read text from notepad?	tempAccounts = GlobusFileHelper.ReadFiletoStringList(Path);\n\n       foreach (string AcctData in tempAccounts)\n        {\n            string[] tempArray = AcctData.Split(':');\n           foreach (string accounts in tempAccounts)\n            {\n                DecaptchaAccounts.Add(accounts);\n            }\n\n        }	0
23977609	23977569	How to fetch data from dynamically created textboxes (windows application)	string allTextBoxValues = "";\nforeach (Control childc in Controls) {\n    if (childc is TextBox && childc.Name.Contains("txt"))\n        allTextBoxValues += ((TextBox)childc).Text + ",";\n}	0
8321768	8321725	DataTable find or if not found insert row	var selectStatement = string.Format("CustomerId = {0}", customerId);\nvar rows = dt.Select(selectStatement);\nif (rows.Count < 1){\n  var dr = dt.NewRow();\n  dr["CustomerId"] = customerId; \n}	0
23666275	23666223	Find name of member in list	var userType = typeof(User);\nvar properties = userType\n                .GetProperties()\n                .Where(x => x.Name.StartsWith("Value")).ToList();\n\nforeach (var user in LiUsers)\n{\n    var property  = properties.FirstOrDefault(x => (int)x.GetValue(user) == 100);\n    if(property != null)\n    {\n        string name = property.Name;\n    }\n}	0
3746923	3693469	Load ink to a MathInputControl in C#	var ctl = new micautLib.MathInputControl();\n        var ink = new MSINKAUTLib.InkDisp();\n        ink.Load(System.IO.File.ReadAllBytes("c:\\temp\\test.isf"));\n        var iink = (micautLib.IInkDisp)ink;\n        ctl.Show();\n        ctl.LoadInk(iink);	0
9530936	9530850	Get last bytes from byte array	byte[] data = ...;\nbyte[] last8 = new byte[8];\nArray.Copy(data, data.Length-8, last8, 0, 8);	0
29232	29141	Using Interop with C#, Excel Save changing original. How to negate this?	Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0];  //or some other way of obtaining this workbook reference, as Jason Z mentioned\nwbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,\nType.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, \n            Type.Missing, Type.Missing, Type.Missing, Type.Missing,\nType.Missing);\nwbk.Close();\nexcelApplication.Quit();	0
13289837	13289735	Can I achieve a wildcard % in the middle of a DataView RowFilter command?	dv = new DataView(MyDataTable, \n"[Name 1] = '" + forename + "%' AND [Name 1] = '%" + surname + "'", \n"", DataViewRowState.CurrentRows);	0
30267924	30264774	How to overwrite hardware buttons to get the page name before back pressed	RelayCommand myGoBackCommand;\n\npublic BasicPage1()\n{\n    this.InitializeComponent();\n\n    this.navigationHelper = new NavigationHelper(this);\n    this.navigationHelper.LoadState += this.NavigationHelper_LoadState;\n    this.navigationHelper.SaveState += this.NavigationHelper_SaveState;\n    myGoBackCommand = new RelayCommand(() => GoBackAction());\n    this.navigationHelper.GoBackCommand = myGoBackCommand;\n}\n\nprivate void GoBackAction()\n{\n    //print previous page name before going back\n    Debug.WriteLine(Frame.BackStack.Last().SourcePageType);\n    if (navigationHelper.CanGoBack())\n        navigationHelper.GoBack();\n}	0
1020181	1020179	How can I capture keys on a WinForms application when the application is in focus?	protected override void OnKeyDown(KeyEventArgs e)\n{\n    e.SuppressKeyPress = true; // do this to 'eat' the keystroke\n    base.OnKeyDown(e);\n}	0
12442949	12442680	Windows Phone 7 - How to Update UI From while Loop?	public MainPage()\n        {\n            InitializeComponent();\n            Thread thread = new Thread(() => ReadFile(/*params*/));\n            thread.Start();\n        }\n\n        private void ReadFile(/*params*/)\n        {   \n            while(/*condition*/)\n            {\n                /* READ FILE */\n\n                //send task to UI thread to add object to list box\n                Dispatcher.BeginInvoke(() => listBox1.Items.Add("YOUR OBJECT"));\n            }\n        }	0
2766243	2766016	Instantiate a form, then find it later, without showing it initially	public class Contact\n{\n    string displayname = String.Empty;\n    List<Message> history = new List<Message>();\n    MessageForm theform = new MessageForm(this);\n\n    public void OnEvent(Message msg)\n    {\n        if(msg.Sender != me && !theform.Visible)\n            theform.Show();\n\n    }\n\n    public void Tell(string message)\n    {\n    }\n\n}	0
4253667	4253601	Send pdf as an attachment in email	string tempFileName = examType + "Report_" + DateTime.Today.Year.ToString() +  DateTime.Today.Month.ToString() + ".rtf";	0
30860892	30860658	How to link code for button function to checkboxlist in C#?	protected void ChartOutputButton_Click(object sender, EventArgs e)\n{ \n    //your code to generate chart\n}\n\nprotected void CheckBoxList1_SelectedIndexhanged(object sender, EventArgs e)\n{   \n    //you can call ChartOutputButton click event handler here\n    ChartOutputButton_Click(ChartOutputButton, null);\n}	0
17745458	17745329	How to use C-Library in C#	[DllImport("kernel32.dll", EntryPoint="MoveFile",\nExactSpelling=false, CharSet=CharSet.Unicode,\nSetLastError=true)]\nstatic extern bool MoveFile(string sourceFile, string destinationFile);\n\n//calling the function\nstatic void Main()\n{\n    MoveFile("sheet.xls", @"c:\sheet.xls");\n}	0
24432388	24432151	EF - Editing a many-to-many table	context.Entry(originalEntity).CurrentValues.SetValues(newEntityWithNewValues);	0
7380554	7374646	Reading current installed version of an application using windows api	Int32 m_len = 11512;\n        StringBuilder m_versionInfo = new StringBuilder(m_len);\n\n        StringBuilder m_sbProductCode = GetProductCodeFromMsiUpgradeCode();\n        MsiGetProductInfo(m_sbProductCode.ToString(), "**VersionString**", m_versionInfo, ref m_len);\n\n        return m_versionInfo.ToString();	0
9243639	9243561	Save formated text from MVC 3 app to MSSQL Database	var someText = "<b>Hello World</b> blahblah"; \n@Html.Raw(someText);	0
24709572	24709448	Can I use a parameter for the LIMIT condition in sqlite query	SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();\nbuilder.DataSource = "test.db";\n\nSQLiteConnection connection = new SQLiteConnection(builder.ConnectionString);\nusing (connection.Open())\n{\n    SQLiteCommand command = new SQLiteCommand("select * from people limit @limitNum", connection);\n    command.Parameters.Add(new SQLiteParameter("limitNum", 2));\n    SQLiteDataReader reader = command.ExecuteReader();\n\n    while (reader.Read())\n    {\n        Console.WriteLine(reader.GetValue(0));\n    }\n}	0
14907408	14907327	How to convert Func<T,bool> to Expression<Func<T,bool>>	Func<MyClass, bool> func = x=>Id == 5;\nExpression<Func<MyClass, bool>> expr = mc => func(mc);	0
14871131	2848359	how to write javascript in asp.net in code behind using C#	string myScriptValue = "function callMe() {alert('You pressed Me!'); }";\nScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true);	0
34109425	34109266	How to check for valid Event Handlers from a unit test (or even from the same unit)	if(YourEvent!=null){\n   foreach (var @delegate in YourEvent.GetInvocationList()){\n      //do your job\n   }\n}	0
9709910	9709884	Exception throw from a using block	try{\n    StreamReader reader =  new StreamReader(...), Encoding.ASCII);\n    try {\n        // Code that can throw an exception     \n    } finally {\n        reader.Dispose();\n    }\n} catch (Exception error) {\n    // Display error...\n}	0
7327556	7327538	How to change date format in asp.net	yourDate.toString("yyyy-MMM-dd hh:mm:ss");	0
17443604	17272961	Share Link with Picture URI on Facebook in Wp7	Dictionary<string, string> action1 = new Dictionary<string, string>();\n        action1.Add("name", "View on");\n        action1.Add("link", link);\n\n        parameters.Add("actions", action1);	0
16816084	16816039	Linq query to group items and query from the top item in each group	myList.GroupBy(m => m.Id)\n.Select(g => g.OrderByDescending(x => x.Date).First())\n.Where(<your filter>);	0
7798599	7798566	setting new value to an label in thread execution	delegate void SetLabel(string msg);\n\n    void SetLabelMethod(string msg)\n    {\n        labelX.text = msg;\n    }\n\n\nthis.Invoke(new SetLabel(SetLabelMethod), new object { msg }); // this is your form	0
13933311	13931217	bind text to a style in word	objWord.Selection.TypeText(resultaat);\n    objWord.Selection.set_Style(objDoc.Styles[stijl]);	0
19861880	19861214	How to put an image beside the text of a ToolStripMenuItem (or similar control)?	public Form1() {\n  InitializeComponent();\n  ((ToolStripDropDownMenu)FileMenuItem.DropDown).ShowCheckMargin = true;\n  ((ToolStripDropDownMenu)FileMenuItem.DropDown).ShowImageMargin = true;\n}	0
23610570	23609689	UITextField PlaceHolder Color change Monotouch	var t = new UITextField()\n{\n  AttributedPlaceholder = new NSAttributedString("some placeholder text", null, UIColor.Red)\n}	0
2751446	2751396	In Castle Windsor, can I register a Interface component and get a proxy of the implementation?	_windsor.Register(Component.For<ProductServices, IProductServices>()\n   .Interceptors(typeof(SomeInterceptorType));	0
443808	443683	How to create a method that takes any object and returns a name:value pair for all properties?	private static string SplitNameValuePairs<T>(T value)\n    {\n        StringBuilder sb = new StringBuilder();\n\n        foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))\n        {\n            if (property.GetIndexParameters().Length == 0)\n                sb.AppendFormat("{0}:{1};", property.Name, property.GetValue(value, null));\n        }\n        return sb.ToString();\n    }	0
11260535	11260397	How can I make the rectangles clickable, C#	private Rectangle _myRectangle;\nprivate void Form1_MouseDown(object sender, MouseEventArgs e)\n{\n    if (this._myRectangle.Contains(e.Location))\n    {\n\n    }\n}	0
5011130	5010975	How to do Speedy Complex Arithmetic in C#	createvertexbuffer()\nloadShader("path to shader code", vertexshader) // something like this I think\n// begin 'rendering'\nsetShader(myvertexshader)\nsetvertexbuffer(myvertexbuffer)\ndrawpoints() // will now 'draw' your points\nreadoutputbuffer()	0
27734519	25795777	Can I change the properties of a HttpClientHandler after the HttpClient has been created?	Dim Handler As New HttpClientHandler\n    Dim proxy As New WebProxy()\n    Dim urlBuilder As New System.UriBuilder\n    Handler.Proxy = proxy\n    Handler.UseProxy = True\n    Handler.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate\n    Dim Client As New HttpClient(Handler, True)\n\n    urlBuilder.Host = "124.161.94.8"\n    urlBuilder.Port = 80\n    proxy.Address = urlBuilder.Uri\n\n    Dim response As String = Await Client.GetStringAsync("http://www.ipchicken.com")\n\n    urlBuilder.Host = "183.207.228.8"\n    urlBuilder.Port = 80\n    proxy.Address = urlBuilder.Uri\n\n    response = Await Client.GetStringAsync("http://www.ipchicken.com")	0
5017748	5017658	LINQ to JSON in .NET	application/json	0
25473897	25473843	Return only part of string in linqQuery	var blogPosts = _repo\n         .GetPosts()\n         .OrderByDescending(o => o.PostedOn)\n         .Take(25)\n         .AsEnumerable()\n         .Select(x => new BlogPost \n                      { \n                         Description = x.Description.Substring(0, 20)),\n                         // set other properties\n                      });	0
15679627	15678516	how to call a base class non default constructor from the instantion of the derived class?	public B()\n    {\n        Console.WriteLine("I AM DERIVED class");\n    }\n    public B(int x): base(x)\n    {\n        Console.WriteLine("I AM DERIVED class (with a parameter)");\n    }	0
8548455	5454366	Windows 7 Mobile Broadband API - Crash with no exception	netsh mbn show interfaces	0
13441430	13441404	Increase string array value +1?	string input = u[i + 1];	0
29835160	29824779	How to get the StringLength from DataAnnotations	StringLengthAttribute strLenAttr = typeof(EmployeeViewModel).GetProperty(name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().SingleOrDefault();\n  if (strLenAttr != null)\n  {\n     int maxLen = strLenAttr.MaximumLength;\n  }	0
29942499	29824744	FormatException from SQLDataAdapter.Update caused by null value	da.UpdateCommand = cb.GetUpdateCommand().Clone();	0
27588640	27588488	Pointing to a variable of my choice in C#	bool Has_Unique_Index<T>(Indexed<T> obj)\n{\n    byte type = Verify_Type<T>(obj);\n    object dataSource = null;\n\n    switch (type)\n    {\n        case 0: dataSource = DataSource.Clients; break;\n        case 1: dataSource = DataSource.Rentals; break;\n        case 2: dataSource = DataSource.Cars;    break;\n        case 3: dataSource = DataSource.Faults;  break;\n        default: return false; // or throw an exception etc.\n    }\n\n    bool result = (dataSource as List<Indexed<T>>).Any(x => x.Index == obj.Index);\n    return result;\n}	0
18592039	18568853	How to write id3v tags to mp3 stream using idsharp	int originalTagSize = IdSharp.Tagging.ID3v2.ID3v2Tag.GetTagSize(filename);\n\nbyte[] tagBytes = tags.GetBytes(originalTagSize);\n\nif (tagBytes.Length < originalTagSize)\n{\n    // Eventually this won't be a problem, but for now we won't worry about shrinking tags\n    throw new Exception("GetBytes() returned a size less than the minimum size");\n}\nelse if (tagBytes.Length > originalTagSize)\n{\n    //In the original implementation is done with:\n    //ByteUtils.ReplaceBytes(path, originalTagSize, tagBytes);\n    //Maybe you should write a 'ReplaceBytes' method that accepts a stream\n}\nelse\n{\n    // Write tag of equal length\n    ms.Write(tagBytes, 0, tagBytes.Length);\n}	0
6218252	6204943	Generic - Typed CompositeDataBound Control	[TemplateContainer(typeof(MyUserGrid.MyContainer))]	0
896720	896701	How do I update text inside CDATA	((XmlCDataSection)myXmlNode.SelectSingleNode("title").FirstChild).Value = TextBoxName.Text	0
25078396	25076987	Copy everything in a Directory and rename copied Files	void Copy(string sourcePath, string targetPath)\n{\n\n    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))\n        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));\n\n    string newPath;\n    foreach (string srcPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))\n    {\n        newPath = srcPath.Replace(sourcePath, targetPath);\n        newPath = newPath.Insert(newPath.LastIndexOf("\\") + 1, "a"); //prefixing 'a'\n        newPath = newPath +  ".example";\n        File.Copy(srcPath, newPath, true);\n    }\n}	0
7354016	7353049	In Ado.Net, can I determine if columns in result sets are nullable?	ret.Add(new NameAndType { Name = column[NameIndex].ToString(),\n                                          Type = column[TypeIndex].ToString(),\n                                          IsNullable = column[13].ToString().Equals("True")	0
5977328	5977232	Dynamic Linq/Lambda Filtering	var param = Expression.Parameter<Customer>();\np = Expression.LambdaFunc<Customer, bool>(\n    Expression.Call(typeof(object), "Equals", null, //non-generic\n                    Expression.Property(param, columnName),\n                    Expresssion.Constant(value)\n    )\n);	0
19648542	19648536	In C#, how can i determine if a list has any item from another list?	if(list.Intersect(list2).Any())\n    DoStuff();	0
26049587	26049221	Calculating the bounding rectangle on a binary image	minY = getMinY(fastBitmap, indexToRemove);\n maxY = getMinY(fastBitmap, indexToRemove);\n minX = getMinY(fastBitmap, indexToRemove);\n maxX = getMinY(fastBitmap, indexToRemove);\n\n int getMinY(Bitmap bitmap, byte indexToRemove)\n {\n    for (int y = 0; y < height; y++)\n    {\n        for (int x = 0; x < width; x++)\n        {\n            if (fastBitmap.GetPixel(x, y).B == indexToRemove)\n            {\n                return y;\n            }\n        }\n    }\n    return 0;\n }\n\n int getMaxY(Bitmap bitmap, byte indexToRemove)\n {\n    for (int y = height; y > 0; y--)\n    {\n        for (int x = 0; x < width; x++)\n        {\n            if (fastBitmap.GetPixel(x, y).B == indexToRemove)\n            {\n                return y;\n            }\n        }\n    }\n    return height;\n }	0
4347134	4290499	Using Automappper to map to methods	public class MyBusinessObject\n{\n    private readonly Dictionary<string, object> extraProperties = new Dictionary<string, object>();\n\n    public int Id { get; set; }\n    public string Name { get; set; }\n\n    public void SetExtraPropertyValue<T>(string key, T value)\n    {\n        extraProperties.Add(key, value);\n    }\n    public T GetExtraPropertyValue<T>(string key, T defaultValue)\n    {\n        if (extraProperties.ContainsKey(key))\n        {\n            return (T)extraProperties[key];\n        }\n\n        return defaultValue;\n    }\n}	0
23014797	23014450	Quickly checking whether two line segments are from the same line	AB x AC = AB x AD = 0 (vector product)	0
30846753	30843847	Export VirtualChannelGetInstance function from c#	public static uint VirtualChannelGetInstance(Guid refiid, ref ulong pNumObjs, void** ppObjArray)	0
30769034	30749945	Create Azure Service Bus queue Shared Access Policy programmatically	string queuePolicyName = "SendPolicy";\nstring queuePrimaryKey = SharedAccessAuthorizationRule.GenerateRandomKey();\n\nQueueDescription queueDescription = new QueueDescription(queueName);\nSharedAccessAuthorizationRule queueSharedAccessPolicy = new SharedAccessAuthorizationRule(queuePolicyName, queuePrimaryKey, new[] { AccessRights.Send });\nqueueDescription.Authorization.Add(queueSharedAccessPolicy);\n\nawait _namespaceManager.CreateQueueAsync(queueDescription);	0
9364994	9364933	How can I emulate TSQL's DateDiff correctly in C#	private static int DateDiff(DateTime from, DateTime to)\n{\n    return (to.Date - from.Date).Days;            \n}	0
9409151	9408941	How to delete every second line from RichDataTextBox?	var lines=richTextBox1.Lines\n    . Where((l, index) => index % 2 == 0)\n    .Select((l, index) => l);\nrichTextBox1.Lines = lines.ToArray();	0
20607690	20606796	How can I add values to a NewtonSoft JObect?	string json = @"{\n                'IgnoredInterests': [\n                    {\n                        'Id': 1,\n                        'Name': 'test'\n                    },\n                    {\n                        'Id': 2,\n                        'Name': 'test'\n                    }\n                ]\n                }";\n        JObject obj = JObject.Parse(json);\n\n        string json_add = @"{\n                   'Id': 3,\n                   'Name': 'test'\n                }";    \n\n        JArray array = obj.GetValue("IgnoredInterests") as JArray;\n\n        JObject obj_add = JObject.Parse(json_add);\n\n        array.Add(obj_add);\n\n\n        foreach (JObject item in array.Children())\n        {\n            if (item.GetValue("Id").ToString() == "2")\n            {\n                array.Remove(item);\n                break;\n            }\n        }	0
25887368	25887220	unable to convert string to date c#	string myDate = "09172017"\nDateTime newDate = DateTime.ParseExact(myDate, "MMddyyyy", CultureInfo.InvariantCulture);	0
2104738	2104159	integration of tools with GUI driver	CreateDesktop()	0
14942230	14921527	Retrieve NMEA data in windows mobile 6	private string GetGPSPort()\n    {\n        string szStr="";\n        if (Registry.GetStringValue(Registry.HKLM,\n                        "System\\CurrentControlSet\\GPS Intermediate Driver\\Multiplexer",\n                        "DriverInterface",\n                        ref szStr)\n            == 0)\n        {\n            return szStr;\n        }\n        else \n        {\n            if (Registry.GetStringValue(Registry.HKLM,\n                "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers",\n                "CurrentDriver",\n                ref szStr) == 0)\n            {\n                string szPath = "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\" + szStr;\n                if (Registry.GetStringValue(Registry.HKLM, szPath, "CommPort", ref szStr) == 0)\n                {\n                    return szStr;\n                }\n            }\n        }\n        return "";\n    }	0
6583255	6583009	Convert Binary to Byte[] array	context.Response.BinaryWrite(images.toArray());	0
30140677	30140091	detecting mouseClick/touch on gameObject	public void OnMouseDown()\n{\n    doAction();\n}	0
29453237	29453048	How do I prevent my console app from closing until its condition is met?	Random rnd = new Random();\nint num1 = rnd.Next(1, 3);\nint num2;\n\nConsole.WriteLine("Guess my number");\n\nwhile(true)\n{  \n   //NOTE, if the user entered characters other than number, the program\n   //will throw an exception, you should check user input before making the parsing\n   num2 = int.Parse(Console.ReadLine());\n\n   if (num2 == num1)\n   {\n   Console.WriteLine("Very Good!");\n   break;\n   }\n   else\n    Console.WriteLine("Guess again");\n}\nConsole.ReadLine();	0
5602508	5602476	Using Entity Framework how can I retrieve a collection from a table?	Context.Students\n       .Include("GradeStudents")\n       .Include("GradeStudents.GradeParalelo")\n       .First<Student>(s => s.StudentId == 1)\n       .GradeStudents	0
11839388	11839248	Assign .net control property from a dictionary	public class Customer\n{\n    public Guid Id { get; set; }\n    public string Name { get; set; }\n    public string Phone { get; set; }\n}\n\nvar dictionary = new Dictionary<string, object>\n                             {\n                                 {"Id", new Guid()}, \n                                 {"Name", "Phil"}, \n                                 {"Phone", "12345678"}\n                             };\n\nvar customer = new Customer();\n\nforeach (var pair in dictionary)\n{\n     var propertyInfo = typeof(Customer).GetProperty(pair.Key);\n     propertyInfo.SetValue(customer, pair.Value, null);\n}	0
27692091	27691973	how to convert varchar to numeric or double in sql query	ROUND(CONVERT(DECIMAL(18,2),'You Value here'),2)	0
24199711	24199638	Ping to server for external connectivity	NetworkInterface.GetIsNetworkAvailable()	0
26778428	26766619	Sobel Edge Detection output for 16bit grayscale image	limit = 1000000	0
15200834	15196682	Injecting 'this' with Ninject	CalculateTax(products)	0
21875829	21874896	Parallelism based on request argument in WCF call?	[ServiceBehavior(\n   InstanceContextMode = InstanceContextMode.Single, // required to hold the dictionary through calls\n   ConcurrencyMode = ConcurrencyMode.Multiple] // let WCF run all the calls concurrently\nclass Service\n{\n  private readonly ConcurrentDictionary<int, object> _locks = new ConcurrentDictionary<int, object>();\n\n  public void MyWcfOperation(int entityId, other arguments)\n  {\n     lock (_locks.GetOrAdd(entityId, i => new Object())\n     {\n       // do stuff with entity with id = entityId\n     }\n  }\n}	0
21604897	21604676	how to update a primary key that is also a foreign key in another table with petapoco?	ON UPDATE CASCADE	0
11619263	11619241	Lambda expression to MINUS two string arrays	returnValue = allWords.Except(ignoreWords);	0
8726154	8616175	Accessing Patch Information?	[DllImport("msi.dll", CharSet = CharSet.Unicode)]\n    internal static extern Int32 MsiGetPatchInfoEx(string szPatchCode, string szProductCode, string szUserSid, int dwContext, string szProperty, [Out] StringBuilder lpValue, ref Int32 pcchValue);\n\n    // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa370128%28v=vs.85%29.aspx \n    // for valid values for the property paramater\n    private static string getPatchInfoProperty(string patchCode, string productCode, string property)\n    {\n        StringBuilder output = new StringBuilder(512);\n        int len = 512;\n        MsiGetPatchInfoEx(patchCode, productCode, null, 4, property, output, ref len);\n        return output.ToString();\n    }\n\n    public static string GetPatchDisplayName(string patchCode, string productCode)\n    {\n        return getPatchInfoProperty(patchCode, productCode, "DisplayName");\n    }	0
22298088	22297902	How to check where in your text file you found a string	if(loginUsername == "login")\n{\n  Console.WriteLine("Type in your username");\n  string loginUser = Console.ReadLine();\n  int lineCount=1;\n  foreach(var line in File.ReadLines("LoginFile.txt"))\n  {\n    if(line.Contains(loginUser))\n    {\n       Console.WriteLine("UserName found in Line No = "+ lineCount);\n       break;\n    }\n       lineCOunt++;\n  }\n}	0
975965	975876	Preferred way to pass multiple objects, all applying to one other object	public class ProductsPackages\n{\n    private Dictionary<int, int> _map;\n\n    public ProductsPackages(List<Product> products, List<Package> packages,\n                            Dictionary<int, int> map)\n    {\n        _map = map;\n    }\n\n    public List<Product> Products { get; private set; }\n    public List<Package> Packages { get; private set; }\n\n    public List<Package> GetPackages(Product product)\n    {\n        return (from p in Packages\n                join kvp in _map on p.ID == kvp.Value\n                where kvp.Key == product.ID\n                select p).ToList();\n    }\n}	0
17451080	17450950	Trouble writing to database in C# WinForm Application	string cmdText = "Insert INTO RetentionTable " +\n                "([DateTime],Center,CSP,MemberID,ContractNumber,RetentionType," + \n                "RetentionTrigger,MemberReason,ActionTaken,Other) " + \n                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\n using(OleDbConnection cn = new OleDbConnection(conString))\n using(OleDbCommand cmd = new OleDbCommand(cmdText, cn))\n {\n    cmd.Parameters.AddWithValue("@p1", DateTime.Now.ToString());\n    cmd.Parameters.AddWithValue("@p2", GetCenter("")); \n    cmd.Parameters.AddWithValue("@p3", GetName(""));\n    cmd.Parameters.AddWithValue("@p4", GetMemberID(""));\n    cmd.Parameters.AddWithValue("@p5", GetContractNumber(""));\n    cmd.Parameters.AddWithValue("@p6", GetType("")); \n    cmd.Parameters.AddWithValue("@p7", GetTrigger(""));\n    cmd.Parameters.AddWithValue("@p8", GetReason(""));\n    cmd.Parameters.AddWithValue("@p9", GetAction(""));\n    cmd.Parameters.AddWithValue("@p10", GetOther(""));\n    cmd.ExecuteNonQuery();\n }	0
8087992	8087982	SQL 2008 cannot connect with app	Data Source=HP_Desktop\LPR_HOME;Initial Catalog=Northwind;User ID=sa;Password=XXXXXXX;	0
26604019	26335393	Transfer big files with WCF service to sharepoint webpart	Page.Response.Flush();\n    //Page.Response.Close();\n    //Page.Response.End();	0
17212272	17212254	C# comparing two string arrays	bool areEqual = a.SequenceEqual(b);	0
2070493	2070365	How to generate an image from text on fly at runtime	private Image DrawText(String text, Font font, Color textColor, Color backColor)\n{\n    //first, create a dummy bitmap just to get a graphics object\n    Image img = new Bitmap(1, 1);\n    Graphics drawing = Graphics.FromImage(img);\n\n    //measure the string to see how big the image needs to be\n    SizeF textSize = drawing.MeasureString(text, font);\n\n    //free up the dummy image and old graphics object\n    img.Dispose();\n    drawing.Dispose();\n\n    //create a new image of the right size\n    img = new Bitmap((int) textSize.Width, (int)textSize.Height);\n\n    drawing = Graphics.FromImage(img);\n\n    //paint the background\n    drawing.Clear(backColor);\n\n    //create a brush for the text\n    Brush textBrush = new SolidBrush(textColor);\n\n    drawing.DrawString(text, font, textBrush, 0, 0);\n\n    drawing.Save();\n\n    textBrush.Dispose();\n    drawing.Dispose();\n\n    return img;\n\n}	0
19066622	19066378	Populating a DTO class with linq	var latestTemperatureQuery =\n    from temperature in db.RoomTemperature\n    join sensor in db.Sensor on temperature.SensorId equals sensor.Id\n    join sensorType in db.SensorType on sensor.TypeId equals sensorType.Id\n    let temperatureModel = new TemperatureModel\n    {\n        SensorType = sensorType.Type,\n        RoomTemperature = temperature.Temperature,\n        Created = temperature.Created\n    }\n    group temperature by temperatureModel.SensorId into groupedTemperatureModel\n    select groupedTemperatureModel.OrderByDescending(t => t.Created)\n   .FirstOrDefault();	0
11016421	11016292	Keeping debug strings out of build in C#	[Conditional("DEBUG")]\npublic void WriteLine(string message)\n{\n    if (m_Logger != null) m_Logger.WriteLine(message);\n}	0
3819437	3819396	How can I measure diagonal distance points?	d = Math.Sqrt(Math.Pow(end.x - start.x, 2) + Math.Pow(end.y - start.y, 2))	0
23847049	23845209	XNA Scale texture to predefined values	new Vector2(40f/plane.Texture.Width, 40f/plane.Texture.Height)	0
6119034	6118995	Matching Id with that of an object in an array	bool ValidateId(int Id, MyObject[] objects)\n{\n   return objects.Any( o=>o.Id == Id );\n}	0
24825050	24824933	I have a practice project i did that i need to compare two Lists . How do i make the comparison?	newValues.AddRange(existingValue.Except(newValues));	0
583980	583970	Need loop to copy chunks from byte array	int incomingOffset = 0;\n\nwhile(incomingOffset < incomingArray.Length)\n{\n   int length = \n      Math.Min(outboundBuffer.Length, incomingArray.Length - incomingOffset);\n\n   // Changed from Array.Copy as per Marc's suggestion\n   Buffer.BlockCopy(incomingArray, incomingOffset, \n                    outboundBuffer, 0, \n                    length);\n\n   incomingOffset += length;\n\n   // Transmit outbound buffer\n }	0
19642501	19076506	AvalonEdit insert text doesnt work	editor.Document.Insert(editor.TextArea.Caret.Offset, "\'");	0
17988095	17987375	Remove the null property from object	void Main()\n{\n    TestClass t=new TestClass();\n    t.Address="address";\n    t.ID=132;\n    t.Name=string.Empty;\n    t.DateTime=null;\n\n    t.Dump();\n    var ret = t.FixMeUp();\n    ((object)ret).Dump();\n}\n\npublic static class ReClasser\n{\n    public static dynamic FixMeUp<T>(this T fixMe)\n    {\n        var t = fixMe.GetType();\n        var returnClass = new ExpandoObject() as IDictionary<string, object>;\n        foreach(var pr in t.GetProperties())\n        {\n            var val = pr.GetValue(fixMe);\n            if(val is string && string.IsNullOrWhiteSpace(val.ToString()))\n            {\n            }\n            else if(val == null)\n            {\n            }\n            else\n            {\n                returnClass.Add(pr.Name, val);\n            }\n        }\n        return returnClass;\n    }\n}\n\npublic class TestClass\n{\n    public string Name { get; set; }\n    public int ID { get; set; }\n    public DateTime? DateTime { get; set; }\n    public string Address { get; set; }\n}	0
18230877	18230792	Variables within lambda/LINQ	if (run.Filters.All(\n       filter => {\n              FilterType t = ConvertFilterType(filter.FilterTypeId);\n              return\n              t != FilterType.A && t != FilterType.B && t != FilterType.C && t != FilterType.D && t != FilterType.E;                        \n         }))\n   {\n    throw new ArgumentException();\n   }	0
3524289	3524224	Using XmlSerializer to create an element with attributes and a value but no sub-element	public class Quantity {\n  // your attributes\n  [XmlAttribute]\n  public string foo;\n\n  [XmlAttribute]\n  public string bar;\n\n  // and the element value (without a child element)\n  [XmlText]\n  public int qty;\n\n}	0
8091865	8091829	How to check if one path is a child of another path?	if (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B)) ||\n    Path.GetFullPath(B).StartsWith(Path.GetFullPath(A)))\n   { /* ... do your magic ... */ }	0
24825770	24825158	Proper usage of out parameter in C#	public class MyExam {\n   public bool LoadSuccess { get; private set; }\n\n   public MyExam() {\n      //If not loadeded happily set the LoadSuccess property in here.\n   }\n}	0
5162306	5155420	I need a GUI for my project in c++	> 3.Qt is much easier to use and learn that MFC.\n\n> 4.Above all Qt is well documented.	0
20345418	20345279	How to simulate click "li" in the WebBrowser control	webBrowser1.Document.GetElementById("pageSize").InvokeMember("onchange")	0
28450998	28450889	How to disable a List of buttons	foreach(Button btn in buttonsToDisable)\n{\n    btn.Enabled = false;\n}	0
16950896	16950854	How pass XML file to the method?	submitInvoice("username", "password", xml.DocumentElement.OuterXml);	0
24060308	24060197	WPF UI update from BackgroundWorker	bw.ProgressChanged += (sender, eventArgs) =>\n            {\n                Console.WriteLine(eventArgs.UserState);\n            };\n\n\nprivate static void BwOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)\n        {\n            var bw = sender as BackgroundWorker;\n            bw.ReportProgress(0, "My State is updated");\n        }	0
11750325	11747469	Close window from different thread in WPF using Dispatcher.Invoke	public void RanToCompletion(Task task)\n    {\n        if (_frmProgress.Dispatcher.CheckAccess())\n            _frmProgress.Close();\n        else\n            _frmProgress.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(_frmProgress.Close));\n    }	0
29488680	29488572	Inserting values into table	cmd.Parameters.AddWithValue("@Sex", RadioButton1.SelectedItem.Text)\n//OR\ncmd.Parameters.AddWithValue("@Sex", RadioButton1.SelectedItem.Value)	0
843315	843179	Silverlight/WPF unable to bind ListBox	public ObservableCollection<userClient> userClientList { get; set; }	0
23696539	23696374	Load an object with values with reflection	PropertyInfo[] properties = typeof(Player).GetProperties();\n\nforeach (XAttribute attribute in playerElement.Attributes())\n{\n    PropertyInfo pi = properties.Where(x => x.Name == attribute.Name).FirstOrDefault();\n\n    if (pi != null)\n    {\n        pi.SetValue(player, attribute.Value);\n    }\n}	0
4564045	4563459	BCD Hex String to Integer	static Int32 GetYearFromBCD(Int32 time)\n{\n    List<Int32> YearList = new List<Int32>();\n    for (Int32 i = 3; i >= 0; i --)\n    {\n        Int32 place = i * 4;\n        Int32 val = 0x01 << place;\n\n        Int32 curVal = (Int32)(time / val);\n        if (curVal > 9 && YearList.Count > 0)\n        {\n            Int32 delta = (Int32)(curVal / 10);\n            YearList[YearList.Count - 1] += delta;\n            curVal -= delta * 10;\n        }\n        YearList.Add(curVal);\n        time -= curVal << place;\n    }\n    Int32 Year = 0;\n    for (Int32 y = 0; y < 4; y++)\n        Year += YearList[y] * (Int32)Math.Pow(10,(4 - y)-1);\n    return Year;\n}	0
234543	234231	Creating application shortcut in a directory	private static void configStep_addShortcutToStartupGroup()\n{\n    using (ShellLink shortcut = new ShellLink())\n    {\n        shortcut.Target = Application.ExecutablePath;\n        shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);\n        shortcut.Description = "My Shorcut Name Here";\n        shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;\n        shortcut.Save(STARTUP_SHORTCUT_FILEPATH);\n    }\n}	0
23222433	23222383	WPF get ListView height in C# when Window Size is changed	int wHeight = (int)lvMoN.ActualHeight;	0
5347914	5346405	ASP.NET Data Caching and how to invalidate	Dictionary<string, List<string>>	0
7990711	7990675	Setting a Custom Attribute on a list item in an HTML Select Control (.NET/C#)	ListItem test = new ListItem("text1", "value1");\ntest.Attributes.Add("data-value", "myValue1");\napplicationList.Items.Add(test);	0
6321956	6321880	C# Detect a given day between two days of the week	bool IsBetween(DayOfWeek min, DayOfWeek max, DayOfWeek toCheck)\n{   \n    if (min <= max)\n        return toCheck >= min && toCheck <= max;\n\n    return toCheck >= min || toCheck <= max;\n}	0
16126409	16026323	How to POST a form containing Editor Templates for an ICollection?	[HttpPost]\n    public ActionResult Edit(MultiLanguageText multilanguagetext)\n    {\n        if (ModelState.IsValid)\n        {\n            db.Entry(multilanguagetext).State = EntityState.Modified;\n            foreach (var local in multilanguagetext.LocalizedTexts) db.Entry(local).State = EntityState.Modified;\n            db.SaveChanges();\n            return RedirectToAction("Index");\n        }\n        return View(multilanguagetext);\n    }	0
6288715	6288683	Windows application using Silverlight	Out of Browser application	0
21643435	21643398	How to remove list element from an array after searching	list_emp_info = list_emp_info.Where(l=> Convert.ToDateTime(l.ResignDate) > DateTime.Now).ToArray();	0
1396260	1396197	Pass inherited Interface to a method	Check(derived.Cast<IBase>());	0
16484825	16484177	How to get row's and cell's index of a just edited cell in DataGrid	private void DataGridData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)\n    {\n        DataGridColumn col1 = e.Column;\n        DataGridRow row1 = e.Row;\n        int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);\n        int col_index = col1.DisplayIndex;\n    }	0
19608693	19608664	Previewing images in a listBox using pictureBox	private void listBox_Assets_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string file = IO.Path.Combine("the directory", listBox_Assets.SelectedItem);\n    if (IO.File.Exists(file)) \n      pictureBox1.Image = Image.FromFile(file);\n}	0
17858490	17857983	Excel Interop - Protect sheet excluding column	Worksheet wks = new Worksheet();\nwks.Range["F:F"].Locked = false;\nwks.Protect();	0
15084737	15084693	Displaying selected items of listbox into a message box	StringBuilder message = new StringBuilder();\nforeach (object selectedItem in listBox1.SelectedItems)\n{\n    message.AppendLine(selectedItem.ToString());\n}\nMessageBox.Show(message.ToString());	0
1866807	1866043	How to set the margin with P/Invoke SendMessage?	using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass MyTextBox : TextBox {\n  private int mRightMargin;\n\n  [DefaultValue(0)]\n  public int RightMargin {\n    get { return mRightMargin; }\n    set {\n      if (value < 0) throw new ArgumentOutOfRangeException();\n      mRightMargin = value;\n      if (this.IsHandleCreated) updateMargin();\n    }\n  }\n\n  protected override void OnHandleCreated(EventArgs e) {\n    base.OnHandleCreated(e);\n    if (mRightMargin > 0) updateMargin();\n  }\n\n  private void updateMargin() {\n    // Send EM_SETMARGINS\n    SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(mRightMargin << 16));\n  }\n\n  [DllImport("user32.dll", CharSet = CharSet.Auto)]\n  private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}	0
9328192	9213953	Add attachment to bug by url	multipart/form-data	0
15703605	15703479	Get The Substring From Path Directory	String pattern = @"(.*\\)(.*\\.*$)";\nString input = @"E:\Work\Taxonomies\012\20110826\20110826_final\full_entry_point_2011-08-26.xsd";\nString result = Regex.Match(input, pattern).Groups[2].Value;	0
6812311	6812272	C# DateTime formatting: How to display only the full hours, eg. 2 PM?	DateTime x = new DateTime(2011,10,10,08,00)\nConsole.WriteLine(x.ToString("h tt")); // Output: '8 AM'\n\nx = new DateTime(2011,10,10,16,08,00)\nConsole.WriteLine(x.ToString("h tt")); // Output: '4 PM'	0
4418541	4418498	C# equivalent of OBJ-C's	string[] charts = xmlString.Split(new string[] { "</record>" }, StringSplitOptions.None);	0
3039731	3026223	How to create a Task Scheduler App	[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]	0
13306000	13305094	Linq Join tables, Group by date, Sum of values?	var customerReadings = (from m in entity.MeterReadings\n    join n in entity.MeterReadingDetails on m.sno equals n.ReadingId\n    where m.Meters.CustomerId == CustomerId && m.ReadDate >= StartDate && m.ReadDate <= EndDate && m.Meters.TypeId == MeterTypeId\n    group n by new { Year = m.ReadDate.Value.Year, Month = m.ReadDate.Value.Month} into g\n    select new\n    {\n         Key = g.Key,\n         Value = g.Sum(x => x.Value),\n         Name = g.FirstOrDefault().MeterReadingTypes.TypeName\n     }).AsEnumerable()\n       .Select(anon => new MeterReadingsForChart\n       {\n         ReadDate = new DateTime(anon.Key.Year, anon.Key.Month, 1),\n         Value = anon.Value,\n         Name = anon.Name\n       });	0
21867730	21866604	Select Data from SQL, Return in Custom Format	System.Text.StringBuilder strb = new System.Text.StringBuilder();\n    strb.Append("[");\n    foreach (DataColumn column in ds.Tables[0].Columns)\n    {\n        strb.Append("'");\n        strb.Append(column.ColumnName);\n        strb.Append("', ");\n    }\n    strb.Append("],\n");\n\n    foreach (DataRow dr in ds.Tables[0].Rows)\n    {\n        strb.Append("[");\n\n        for (int i=0; i<dr.ItemArray.Length; i++)\n        {\n            if (i == (dr.ItemArray.Length - 1))\n            {\n                strb.Append(dr[i].ToString());\n            }\n            else\n            {\n                strb.Append("'");\n                strb.Append(dr[i].ToString());\n                strb.Append("', ");\n            }\n        }\n\n        strb.Append("],\n");\n    }	0
22079451	22079049	How to link multiple Query Operations in MongoDb C# Driver	Query.Or(Query.EQ("t", "F"), Query.EQ("t", "M"))	0
21853696	21852192	Autofill textboxes from database based on one textbox value	try\n    {\n        int i = Convert.ToInt32(CBCompanies.SelectedValue.ToString());\n        DataTable td = new DataTable();\n        da = new SqlDataAdapter("select * from tblCustomerCompany where CustomerID =" + CBCompanies.SelectedValue.ToString() + "  ORDER BY CustomerName", conn);\n        conn.Open();\n        da.Fill(td);\n        conn.Close();\n        textBox3.Text = td.Rows[0].ItemArray[5].ToString();\n    }\n    catch { }	0
5869019	5868966	Play a sound in a specific device with C#	public void playSound(int deviceNumber)\n{\n    disposeWave();// stop previous sounds before starting\n    waveReader = new NAudio.Wave.WaveFileReader(fileName);\n    var waveOut = new NAudio.Wave.WaveOut();\n    waveOut.DeviceNumber = deviceNumber;\n    output = waveOut;\n    output.Init(waveReader);\n    output.Play();\n}	0
34005680	34005590	EntityFramework pence to pounds	public class YourClassName {\n   public decimal Price { get; set; }\n\n   [NotMapped]\n   public decimal Pounds => Price/100;\n}	0
11769144	11768979	Latest date in Linq to sql	var highestDateID = Storage.OrderByDescending(x => x.Date).Select(x => x.Item_Id).FirstOrDefault();	0
6449370	6449319	Format passed time like facebook	const int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nif (delta < 0)\n{\n  return "not yet";\n}\nif (delta < 1 * MINUTE)\n{\n  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";\n}\nif (delta < 2 * MINUTE)\n{\n  return "a minute ago";\n}\nif (delta < 45 * MINUTE)\n{\n  return ts.Minutes + " minutes ago";\n}\nif (delta < 90 * MINUTE)\n{\n  return "an hour ago";\n}\nif (delta < 24 * HOUR)\n{\n  return ts.Hours + " hours ago";\n}\nif (delta < 48 * HOUR)\n{\n  return "yesterday";\n}\nif (delta < 30 * DAY)\n{\n  return ts.Days + " days ago";\n}\nif (delta < 12 * MONTH)\n{\n  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n  return months <= 1 ? "one month ago" : months + " months ago";\n}\nelse\n{\n  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n  return years <= 1 ? "one year ago" : years + " years ago";\n}	0
33039216	32987994	Include custom information in the generated Xaml Activity in WF4	IVsRunningDocumentTable rdt = (IVsRunningDocumentTable)GetGlobalService(typeof(SVsRunningDocumentTable));\nrdt.AdviseRunningDocTableEvents(new YourClassThatImplements(this), out cookie);	0
18245863	18237586	Unity3d - How to add gameobject list to array?	GameObject g = Selection.activeGameObject;\nif (g != null)\n{\n    Transform t  = g.transform;\n    foreach (Transform sub in t)  \n    {\n        Debug.Log(sub); // do something with the sub here\n    }\n\n}	0
11730969	11730945	How to make arrays values equal in C#?	if (sArray2.Length == sArray1.Length)\n        {\n            sArray2.CopyTo(sArray1, 0);    \n        }	0
23100805	23100718	Convert object model to XML	// in System.Xml.Linq\nXDocument doc = new XDocument();\nusing (var writer = doc.CreateWriter())\n{\n    // write xml into the writer\n    var serializer = new DataContractSerializer(objToSerialize.GetType());\n    serializer.WriteObject(writer, objectToSerialize);\n}\nConsole.WriteLine(doc.ToString());	0
24008520	23882724	WinForm asynchronously update UI status from console application call	public void ProcessData()\n {\n     new Thread(() => new RateBar().ShowDialog()).Start(); \n\n     Worker wk = new Worker();\n     wk.WorkProcess += wk_WorkProcess;\n\n     Action handler = new Action(wk.DoWork);\n     var result = handler.BeginInvoke(new AsyncCallback(this.AsyncCallback), handler);\n }	0
5846174	5846141	How to get the name of a control under the mouse pointer ( without making an event handler for each control ) ? 	PictureBox picSender = (PictureBox)sender;\nlabel1.Text = picSender.Name;	0
3624826	3618902	Command Param for making console invisible	Dynamic cmd = AutomationFactory.CreateObject("WScript.Shell");\n    cmd.Run("C:\Windows\System32\cmd.exe /c *myargs*",0,true);	0
5012472	5011111	How to Do a Query with Optional Search Parameters?	WHERE \n   (COALESCE(@Categ, 0) = 0 OR Categ = @Categ) AND \n   (COALESCE(@WorkPlace, 0) = 0 OR WorkPlace = @WorkPlace) AND \n   (COALESCE(@WorkPlace1, 0) = 0 OR WorkPlace1 = @WorkPlace1) AND \n   (COALESCE(@AsignedAs, 0) = 0 OR AsignedAs= @AsignedAs)	0
4067840	4067725	access a static field of a typename in generic function	public class A\n  {\n    private static int _num = 1;\n    public  virtual int Num { get { return _num; } set { _num = value; } }\n    public int GetClassNum<T>(T input) where T : A\n    {\n      return input.Num;\n    }\n  }	0
9750412	9750292	Scrolling listbox to the end using selectedItem	lbLog.SelectedIndex= -1;	0
8973410	8973322	How to check if string is in column value of returned DataRow array in C#?	if (RetrievedInitials.Contains(Requested_Initials))	0
30766595	30766558	If a word in a foreach loop contains xxx, show previous word	string line = "qwerty/asdfg/xxx/zxcvb";\nstring[] words = line.Split('/');\nstring previousWord = "";\nforeach (string word in words)\n{\n    if (word.Contains("xxx"))\n    {\n        Console.WriteLine(previousWord);\n    }\n    previousWord = word;\n}	0
33450875	33440741	LINQ - how to remove duplicate rows in table	var duplicates = (from r in dbContext.tbl_mytable \n                  group r by new { r.Name, r.date, r.status} into results\n                  select results.Skip(1)\n                 ).SelectMany(a=>a);\n\n dbContext.tbl_mytable.DeleteAllOnSubmit(duplicates);\n dbContext.SubmitChanges();	0
7501638	7498413	Vertical Tab Control with horizontal text in Winforms	Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem\n    Dim g As Graphics\n    Dim sText As String\n\n    Dim iX As Integer\n    Dim iY As Integer\n    Dim sizeText As SizeF\n\n    Dim ctlTab As TabControl\n\n    ctlTab = CType(sender, TabControl)\n\n    g = e.Graphics\n\n    sText = ctlTab.TabPages(e.Index).Text\n    sizeText = g.MeasureString(sText, ctlTab.Font)\n\n    iX = e.Bounds.Left + 6\n    iY = e.Bounds.Top + (e.Bounds.Height - sizeText.Height) / 2\n\n    g.DrawString(sText, ctlTab.Font, Brushes.Black, iX, iY)\nEnd Sub	0
31596914	31596859	timer that runs 2 of every 3 seconds c#	private int counter = 0;\nprivate int whichSecond = 0;\n\nvoid RunsEverySecond()\n{\n    if (whichSecond < 2)\n    {\n        counter += 5;\n        whichSecond++;\n    }\n    else\n    {\n        counter += 100;\n        whichSecond = 0;\n    }\n}	0
5899291	5899171	Is there anyway to handy convert a dictionary to String?	public static string ToDebugString<TKey, TValue> (this IDictionary<TKey, TValue> dictionary)\n{\n    return "{" + string.Join(",", dictionary.Select(kv => kv.Key.ToString() + "=" + kv.Value.ToString()).ToArray()) + "}";\n}	0
28070461	28070217	How to change value in data row with type mismatch?	DataTable dtCloned = dt.Clone();\ndtCloned.Columns[0].DataType = typeof(Int32); //in the column you actually need.\nforeach (DataRow row in dt.Rows) \n{\n    dtCloned.ImportRow(row);\n}	0
21702803	21681596	WPF Microsoft Bing Control SetView using a bounding rectangle	myMap.Loaded += (s,e)=>{myMap.SetView(boundingBox);};	0
4906657	4871293	Only top row of DataGridView updating?	string[] keywordsarray = keywordslower.Split\n    (new char[] {'\r','\n' }, StringSplitOptions.RemoveEmptyEntries);	0
9196124	9188783	How to dynamically load XAML for getting Controls information	App.xaml	0
7569938	7569904	Easiest way to read from and write to files	// Create a file to write to. \nstring createText = "Hello and Welcome" + Environment.NewLine;\nFile.WriteAllText(path, createText);\n\n// Open the file to read from. \nstring readText = File.ReadAllText(path);	0
1494882	1494861	Trouble with local variables in C#	int temp1 = 0;\nint temp2 = 0;\n    if (toReturn.Count > 1)\n        temp1 = toReturn[toReturn.Count - 2];\n    if (toReturn.Count > 0)\n        temp2 = toReturn[toReturn.Count - 1];	0
3228353	3227065	How to decode a url encoding string on Windows Mobile?	/// <summary>\n    /// UrlDecodes a string without requiring System.Web\n    /// </summary>\n    /// <param name="text">String to decode.</param>\n    /// <returns>decoded string</returns>\n    public static string UrlDecode(string text)\n    {\n        // pre-process for + sign space formatting since System.Uri doesn't handle it\n        // plus literals are encoded as %2b normally so this should be safe\n        text = text.Replace("+", " ");\n        return System.Uri.UnescapeDataString(text);\n    }\n\n    /// <summary>\n    /// UrlEncodes a string without the requirement for System.Web\n    /// </summary>\n    /// <param name="String"></param>\n    /// <returns></returns>\n    public static string UrlEncode(string text)\n    {\n        // Sytem.Uri provides reliable parsing\n        return System.Uri.EscapeDataString(text);\n    }	0
28454224	28453955	Find and take a part of url and replace it with a new created url using REGEX	Regex regex = new Regex(@"(?<=<a.*?href="")http://(\d*)@adam.tv(?="")");	0
2269217	2269150	How can I add new root element to a C# XmlDocument?	var p1node = oParent2.ImportNode(oParent1.DocumentElement, true);\nvar p2node = oParent2.RemoveChild(oParent2.DocumentElement);\n\noParent2.AppendChild(p1node);\np1node.AppendChild(p2node);	0
6480613	6480609	Downloading files with C#	unzipfiles()	0
24479728	24479019	How do I make a dynamic .Net object enumerable from IronRuby?	public class TrialObject : DynamicObject, IEnumerable<int> {\n   ...\n   public IEnumerable<BuildableObject> each() { return this; }\n   ...\n}	0
4534818	4534777	Retrieve domain from wildcard URI	String testString = "*.yahoo.co.uk";\nConsole.WriteLine(testString.TrimStart(new char[]{'.','*'}));	0
12105048	12104922	Representing double values in the exponential format in C#	if (dValue >= 0.01 && dValue <= 1000.0)\n{\n    if (Math.Abs(Math.Round(dValue, 2) - Math.Round(dValue, 0)) < 0.005) {\n        return string.Format("{0:F0}", dValue);\n    else\n        return string.Format("{0:F2}", dValue);\n}\nelse return (string.Format("{0:0.##E+00}", dValue));	0
7048182	7048135	Possible to do this without a loop?	public static int filterNumber(int x, int arbitraryNumber) {\n  if (x < arbitraryNumber) {\n    return x;\n  }\n\n  int result = x % arbitraryNumber;\n  if (result == 0) {\n    return arbitraryNumber;\n  }\n\n  return result;\n}	0
940125	940062	How to force StringTemplate to evaluate attribute within attribute?	StringTemplate st = new StringTemplate("$msg$");\nst.SetAttribute("msg", new StringTemplate("Hello $usr$"));\nst.SetAttribute("usr", "Jakub");\nConsole.WriteLine(st); \n// current output:  "Hello Jakub"\n// expected output: "Hello Jakub"	0
5542990	5542948	How can I get an xmlnode from xmlnodereader	XElement element = XElement.Load(reader);	0
1229960	1229860	Editing an XML file?	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(filePath);\n\nXmlNode node = FindYourNode(xmlDoc); //Method to find the specific node\nnode.AppendChild(yourNewXmlNode);\n\nxmlDoc.Save(filePath);	0
30721516	30721440	Python-like Byte Array String representation in C#	foreach (byte b in ba)\n{\n    if (b >= 32 && b <= 126)\n    {\n        hex.Append((char) b);\n        continue;\n    }\n\n    ...	0
7875082	7874967	How to set row color based on column condition in asp.net website	string status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "MessageActive"));\nif (status == "No")\n{\n    e.Row.BackColor = Drawing.Color.Red\n}	0
10553043	10292864	Datagridview Cells Styling with RTF string	"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1036{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Microsoft Sans Serif;}{\\f1\\fnil\\fcharset0 Microsoft Sans Serif;}}{\\colortbl ;\\red255\\green0\\blue0;}\\viewkind4\\uc1\\pard\\cf1\\f0\\fs17 " + value + "\\cf0\\f1}";	0
21238650	21196804	How do I access the GridNoRecordsItem from the ItemCommand?	protected void grdPrices_ItemCommand(object sender, GridCommandEventArgs e) {\n    if (e.CommandName.Equals("Autofill")) {\n\n        // This line actually is OK!\n        GridNoRecordsItem noRecordsItem = (GridNoRecordsItem)e.Item;\n\n        string start = "" + noRecordsItem.FindControl("dtStart").Value;\n        string end   = "" + noRecordsItem.FindControl("dtEnd").Value;\n    }\n}	0
16847342	16829108	Using Xpath with XpathSelectElement in a Loop	for (int sp_range = int.Parse(myParser.GetKey("SP_Range")); sp_range < int.Parse(myParser.GetKey("EP_Range")); sp_range++)\n{\n    cboPort.Items.Add(sp_range.ToString()); //Adds the load of values\n\n    foreach (XElement xml in main.XPathSelectElements("/Row/ip_addresses"))\n    {\n        xml.SetAttributeValue("id", sp_range++);//You have to re-iterate for the set# Nodes\n    }\n\n}\n\nmain.Save(xmlpath);	0
12110856	12110289	Creating a dynamic Stored Procedure on MSSQL SERVER 2008 R2	CREATE PROC usp_bar\n(\n@ID INT\n)\nAS\nBEGIN\nDECLARE @SQL NVARCHAR(100)\nDECLARE @Params NVARCHAR(100)\nSET @SQL = N'SELECT * FROM [Table] WHERE ID = @ID'\nSET @Params = N'@ID INT'\nEXEC sp_executesql @SQL, @Params, @ID = 5\nEND	0
24658572	24658536	How can select a item from listbox binding Windows Phone 7	private void visualizar_est_Click(object sender, System.EventArgs e)\n        {\n             var mySelectedItem = list_enfer.SelectedItem as yourObject;\n             //Then you can access the property inside yourObject\n             MessageBox.Show(yourObject.enfermedadasoc.ToString()); \n        }	0
5181423	5169179	How to enumerate PropertyGrid items?	public static GridItemCollection GetAllGridEntries(PropertyGrid grid)\n{\n    if (grid == null)\n        throw new ArgumentNullException("grid");\n\n    object view = grid.GetType().GetField("gridView", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(grid);\n    return (GridItemCollection)view.GetType().InvokeMember("GetAllGridEntries", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, view, null);\n}	0
9554813	9554744	How to prevent a row add to GridView during binding	void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n    if (row.RowType == DataControlRowType.DataRow){\n        e.Row.Visible = SomeCondition;\n    }\n}	0
33176824	33060874	Expression for Linq between 2 classes in a 1 to many relationship	var AllOpsWithTagQuery = from r in db.Tags\n           where(r.Tag.StartsWith(Query))\n           join o in db.Opportunities on r.OpId equals o.OpId\n           select o;	0
1756778	1756761	Preventing duplicate strings in C#	DataSet ds = DatabaseFunctions.getEmailsBySPROC("getEmailByCircuit", sql_CircuitEmail);\n\nif (ds != null)\n{\n    DataTable table = ds.Tables[0];\n    HashSet<string> emails = new HashSet<string>();\n    for (int idx = 0; idx < table.Rows.Count; idx++)\n    {\n        emails.Add(table.Rows[idx]["Email"].ToString());\n    }\n}\n\nStringBuilder result = new StringBuilder();\nforeach(string email in emails)\n{\n    result.Append(email + ";");\n}\n\nemailList = result.ToString();	0
18248192	18247985	Compare complex subquery between two values	var values = Enumerable.Range(1, 2);\n\n _unitOfWork.Repository<Student>().Get(o => o.OrganizationId == organizationId\n            && values.Contains(\n                o.Grades.Where( o1 => o1.LastVersion\n                    && o1.Type == 5\n                    && o1.Value == 1).Count()\n               ));	0
1130078	1120421	Unity Container - Passing in T dynamically to the Resolve method	var type = filter.GetType();\nvar genericType = typeof(ISearchable<>).MakeGenericType(type);\nvar searchProvider = _unityContainer.Resolve(genericType);	0
3684610	3684591	is it possible to convert from byte[] to base64string and back	Console.WriteLine(\n     Convert.ToBase64String(\n        Convert.FromBase64String(\n               Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));	0
12569643	12569432	Creating a dialog for Word Addin	public static DialogResult ShowDialog(Form dialog)\n{\n    NativeWindow mainWindow = new NativeWindow();\n    mainWindow.AssignHandle(Process.GetCurrentProcess().MainWindowHandle);\n    DialogResult dialogResult = dialog.ShowDialog(mainWindow);\n    mainWindow.ReleaseHandle();\n    return dialogResult;\n}	0
7024245	7024203	Wpf - Contextmenu in TabItem Header	_tabItem.Header = new ContentControl\n                 {\n                     Content = "StartPage",\n                     ContextMenu = _contextMenu\n                 };	0
12621836	12621619	Procedure with @tpv not workimg from c#	int mis=1652908150;\n\n//create the dataTable\ndt = new DataTable();\ndt.Columns.Add("crc32", typeof(int));\nvar row = dt.NewRow();\nrow["crc32"] = mis; // I do not see the point of convert.\ndt.Rows.Add(row);\n\n//exec the proc\nvar cmd = new SqlCommand("UpdateAdsList",con);\ncmd.CommandType = Syste.Data.CommandType.StoredProcedure;\n\ncmd.Parameters.AddWithValue("@tvp",dt);\n\ncon.Open();\n\nint misRow=cmd.ExecuteNonQuery();\n\ncon.close();	0
11242808	11242675	Displaying only desired columns in a grid	protected void RadGrid1_ColumnCreated(object sender, Telerik.WebControls.GridColumnCreatedEventArgs e)\n  {\n       if (e.Column.UniqueName == "ColumnName")\n       {\n           e.Column.Visible = false;\n       }\n  }	0
5314619	5314369	Photo printing in C#	e.Graphics.DrawImage(nextImage, e.PageSettings.PrintableArea.X - e.PageSettings.HardMarginX, e.PageSettings.PrintableArea.Y - e.PageSettings.HardMarginY, e.PageSettings.Landscape ? e.PageSettings.PrintableArea.Height : e.PageSettings.PrintableArea.Width, e.PageSettings.Landscape ? e.PageSettings.PrintableArea.Width : e.PageSettings.PrintableArea.Height);	0
1684932	1647693	Attribute for accessing custom properties in Forms Designer	[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]	0
28867881	28848909	Convert to PDF method only works once	IConverter converter =\n    new ThreadSafeConverter(\n        new PdfToolset(\n            new Win32EmbeddedDeployment(\n                new TempFolderDeployment())));\n\n// Keep the converter somewhere static, or as a singleton instance!\n// Do NOT run the above code more than once in the application lifecycle!\n\nbyte[] result = converter.convert(document);	0
2325508	2325124	A good WCF client design pattern	public interface IMyService\n{\n    decimal GetPrice(int productId);\n\n    void Book(int thingId);\n}	0
24708936	24708917	Replacing a foreach with a linq statement	printers.Where(printer => printer.Installed)\n  .ToList()\n  .ForEach(printer => installedPrinters.Add(printer));	0
28053133	28053066	Send keypress as parameters in function	private void carga_todos(object sender, KeyPressEventArgs e)\n{ \n    if (e.KeyChar == (char)Keys.Enter)\n    {\n       DoSomething();\n    }\n}\n\nprivate void AnotherFunctionThatNeedsToDoSomethingToo()\n{\n    DoSomething();\n}\n\nprivate void DoSomething()\n{\n    // stuff to do\n}	0
6758279	6758224	Finding adjacently repeated "and" in a sentence using regex?	Regex.Replace(text, @"(\band\s+)+", "and ");	0
16420346	16414186	Failed to save Unicode in converting from MS SQL Server to MySQL	; CharSet=utf8	0
32356036	32355543	Get reference tags child of an XML C#	XElement doc = XElement.Load("c:\xmlfile.xml");\n\nforeach (XElement element in elementsInDoc)\n    Console.WriteLine(element);  // or add to database\n\nforeach(XElement client in doc.Elements("cliente"))\n{\n     foreach(XElement contato in client.Elements("contato"))\n     {\n          //add name to database\n     }\n}	0
2468373	2468357	A Built-in Function to Convert from String to Byte	System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();\nbyte[] bytes= encoding.GetBytes(stringData);	0
6662812	6662344	How to capture the image in picturebox and make it downlodable in c# application?	private void SaveMe_Click(object sender, EventArgs e)\n    {\n        SaveFileDialog save = new SaveFileDialog();\n        save.Filter = "JPEG files (*.jpg)|*.jpg";//change for your needs\n        if (save.ShowDialog() == DialogResult.OK)\n        {\n            pictureBox1.Image.Save(save.FileName);\n        }\n    }	0
20732526	20732492	Decode specific HTML tag from Encoded line	var myString = "&lt;b&gt;&lt;br /&gt;&lt;i&gt;&lt;br /&gt;&lt;a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt";\nvar outputString = myString.Replace("&lr;br /&gt;", "<br />");	0
13974539	13973840	Loading an Inkbox Signature, stored as an array from SQLserverCE	var stream = new MemoryStream((byte[])dr["Signature"]);	0
32315841	32295072	Touch pad as mouse input control	Input.position	0
30296661	30296394	How to Take Value from a specific cell of GridView with autogenerated Columns	foreach(GridViewRow gvr in gv_Data){\n   TextBox t = gvr.Cells[0].FindControl("TextField1") as TextBox;\n   t.Text = "abc";\n   DropDownList ddl = gvr.Cells[1].FindControl("DropDownList1") as DropDownList;\n   ddl.SelectedValue = 100;\n}	0
4929172	4929164	How to store xml / settings inside User's directory	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
8374944	8374739	BindingList<T> where T is interface that implements other interface	interface IA { int Foo {get;} }\ninterface IB { string Foo {get;} }\ninterface IC : IA, IB {}	0
839105	839093	Removing element from ParameterInfo array in C#	List<ParameterInfo> list = new List<ParameterInfo>(args);\nlist.RemoveAt(1);\nargs = list.ToArray();	0
33160919	33160197	get buttons next to the one that was clicked	int xCount = 4;\nint yCount = 4;\nint buttonSize = 40;\nDictionary<Button, Point> pointByButton = new Dictionary<Button, Point>();\n\nfor (int x = 0; x < xCount; ++x)\n{\n    for (int y = 0; y < yCount; ++y)\n    {\n        Button newButton = new Button();\n        newButton.Location = new Point(100 + x * buttonSize, 150 + y * buttonSize);\n        newButton.Size = new Size(buttonSize, buttonSize);\n        newButton.Name = "" + (char)(y + 'A') + (x + 1);\n        newButton.Text = newButton.Name;\n        this.Controls.Add(newButton);\n\n        pointByButton.Add(newButton, new Point(x, y));\n\n        newButton.Click += new EventHandler((s, ev) =>\n        {\n            Point thisPoint = pointByButton[(Button)s];\n\n            foreach (var btn in pointByButton)\n            {\n                if (btn.Value.Y - thisPoint.Y != -1 || Math.Abs(btn.Value.X - thisPoint.X) != 1)\n                {\n                    btn.Key.Enabled = false;\n                }\n            }\n        });\n    }\n}	0
11941993	11941909	Unity Not Resolving Injected Properties from Configuration	_page = _container.Resolve<IBasePage>("LoginPage");	0
18288998	17399289	Working formation algorithms into football simulation	var playerCount = playersInLine.Count();\nvar teamFactor = Math.Pow(1.5, (playerCount-6)) - (1.5)^(-5));\nvar playerRates = playersInLine.Select(p => p.Rate + p.Rate * teamFactor);\n\nvar lineRate = playerRates.Sum();	0
25126071	25126006	Converting enum values into an string array	Enum.GetValues(typeof(VehicleData))\n    .Cast<int>()\n    .Select(x => x.ToString())\n    .ToArray();	0
23964354	23964109	Draw String in the middle of line drawn by Graphics.DrawLine	Point topLeft = new Point(Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y));\nPoint botRight = new Point(Math.Max(point1.X, point2.X), Math.Max(point1.Y, point2.Y));\n\nTextRenderer.DrawText(e.Graphics, "X", this.Font,\n               new Rectangle(topLeft,\n                 new Size(botRight.X - topLeft.X, botRight.Y - topLeft.Y)),\n               Color.Black, Color.White,\n              TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);	0
625057	45988	Choosing a folder with .NET 3.5	var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();\n     dlg1.Description = "Select a folder to extract to:";\n     dlg1.ShowNewFolderButton = true;\n     dlg1.ShowEditBox = true;\n     //dlg1.NewStyle = false;\n     dlg1.SelectedPath = txtExtractDirectory.Text;\n     dlg1.ShowFullPathInEditBox = true;\n     dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;\n\n     // Show the FolderBrowserDialog.\n     DialogResult result = dlg1.ShowDialog();\n     if (result == DialogResult.OK)\n     {\n         txtExtractDirectory.Text = dlg1.SelectedPath;\n     }	0
30659052	30658820	Split string with comma delimiter but not if it is a currency value using C#	String[] MySplit(String str)\n{\n    bool currency = false;\n    char[] chars = str.ToCharArray();\n\n    for(int i = 0; i < str.Length(); ++i)\n    {\n       if(chars[i] == '$')\n          currency=true;\n       else\n       if(currency && chars[i] == ',')\n       {\n           chars[i] = '.';\n           currency = false;\n       }\n    }\n    return new String(chars).Split(",");\n}	0
22428896	22428411	add Mono internal call where a string is passed by reference	*response = mono_string_new(mono_domain_get(), "Test repsonse");	0
13787782	13787335	Set focus back on a ComboBox if the value is incorrect	combobox.focus()	0
14353670	14353476	Specifying the columns of the datatable in a general method C#	public DataTable  CreateDataTable(Dictionary<string,Type> columns)\n      {\n            DataTable dt = new DataTable();\n            foreach( var key in columns)\n            {\n                var column = dt.Columns.Add();\n                column.ColumnName = key.Key;\n                column.DataType = key.Value;\n            }\n            return dt;\n\n        }\n\n\n        public void CreateNewDataTable()\n        {\n            var columns = new Dictionary<string, Type>()\n                {\n                    {"column", typeof (string)}\n                };\n            var dt = CreateDataTable(columns);\n        }	0
4499638	4499620	How to append parameter?	string query = "?page=15&sort=col";\nvar values = HttpUtility.ParseQueryString(query);\nvalues["value"] = "100";\nquery = values.ToString(); // page=15&sort=col&value=100	0
1589059	1589052	How would I convert this to a lambda expression?	return items.Where(i => Codes.Contains(i.Code)).ToList();	0
15063103	15017895	Adding an Embedded Chart to word document using open xml	public static void WriteChartParts(MainDocumentPart sourcePart, MainDocumentPart destnPart)\n    {\n        var paras = sourcePart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>();\n        var drawingElements = from run in paras\n                              where run.Descendants<Drawing>().Count() != 0\n                              select run.Descendants<Drawing>().First();\n\n       sourcePart.ChartParts.ForAll(chartPart =>\n       {\n           destnPart.AddPart<ChartPart>(chartPart, sourcePart.GetIdOfPart(chartPart));\n       });\n\n       drawingElements.ForAll(drw =>\n       {\n           destnPart.Document.Body.Append((drw as OpenXmlElement).Clone() as OpenXmlElement);\n       });\n       destnPart.Document.Save();\n    }	0
8603842	8505995	iTextSharp generated PDF: How to send the pdf to the client and add a prompt?	{\nxtype:'button',           \ntext: 'Generate PDF',           \nhandler: function () {\n     window.location = '/AddData.ashx?action=pdf';                   \n}\n}	0
13194232	13194079	Date coming out in a strange format	var jsondateString = "\/Date(1353456000000)\/".substr(6);\nvar current = new Date(parseInt(jsondateString ));\nvar month = current.getMonth() + 1;\nvar day = current.getDate();\nvar year = current.getFullYear();\nvar date = day + "/" + month + "/" + year;\nalert(date);	0
25222809	25220599	Need a method to obtain code that would construct a given expression tree	Expression<Func<Purchase,bool>> criteria1 = p => p.Price > 1000;\nExpression<Func<Purchase,bool>> criteria2 = p => criteria1.Invoke (p)\n                                             || p.Description.Contains ("a");\n\nConsole.WriteLine (criteria2.Expand().ToString());	0
9140487	9140474	use more than one labels	((Label)Page.FindControl("Label" + j)).Text = a;	0
474743	474679	Capture console exit C#	[DllImport("Kernel32")]\nprivate static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);\n\nprivate delegate bool EventHandler(CtrlType sig);\nstatic EventHandler _handler;\n\nenum CtrlType\n{\n  CTRL_C_EVENT = 0,\n  CTRL_BREAK_EVENT = 1,\n  CTRL_CLOSE_EVENT = 2,\n  CTRL_LOGOFF_EVENT = 5,\n  CTRL_SHUTDOWN_EVENT = 6\n}\n\nprivate static bool Handler(CtrlType sig)\n{\n  switch (sig)\n  {\n      case CtrlType.CTRL_C_EVENT:\n      case CtrlType.CTRL_LOGOFF_EVENT:\n      case CtrlType.CTRL_SHUTDOWN_EVENT:\n      case CtrlType.CTRL_CLOSE_EVENT:\n      default:\n          return false;\n  }\n}\n\n\nstatic void Main(string[] args)\n{\n  // Some biolerplate to react to close window event\n  _handler += new EventHandler(Handler);\n  SetConsoleCtrlHandler(_handler, true);\n  ...\n}	0
11646029	11559255	reactive extensions sliding time window	public static IObservable<T[]> RollingBuffer<T>(\n    this IObservable<T> @this,\n    TimeSpan buffering)\n{\n    return Observable.Create<T[]>(o =>\n    {\n        var list = new LinkedList<Timestamped<T>>();\n        return @this.Timestamp().Subscribe(tx =>\n        {\n            list.AddLast(tx);\n            while (list.First.Value.Timestamp < DateTime.Now.Subtract(buffering))\n            {\n                list.RemoveFirst();\n            }\n            o.OnNext(list.Select(tx2 => tx2.Value).ToArray());\n        }, ex => o.OnError(ex), () => o.OnCompleted());\n    });\n}	0
1998049	1179816	Best practices for serializing objects to a custom string format for use in an output file	public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)\n    {\n        Type t = typeof(T);\n        FieldInfo[] fields = t.GetFields();\n\n        string header = String.Join(separator, fields.Select(f => f.Name).ToArray());\n\n        StringBuilder csvdata = new StringBuilder();\n        csvdata.AppendLine(header);\n\n        foreach (var o in objectlist) \n            csvdata.AppendLine(ToCsvFields(separator, fields, o));\n\n        return csvdata.ToString();\n    }\n\n    public static string ToCsvFields(string separator, FieldInfo[] fields, object o)\n    {\n        StringBuilder linie = new StringBuilder();\n\n        foreach (var f in fields)\n        {\n            if (linie.Length > 0)\n                linie.Append(separator);\n\n            var x = f.GetValue(o);\n\n            if (x != null)\n                linie.Append(x.ToString());\n        }\n\n        return linie.ToString();\n    }	0
31956280	30976406	How to get only public property using reflection in C# in Windows Store App	IEnumerable<PropertyInfo> properties = \n    typeof(TClass)\n        .GetRuntimeProperties()\n        .Where( pi => pi.CanRead && pi.GetGetMethod().IsPublic );	0
5426350	5426289	What is the best practice for porting #defines from .h file to a C# application?	public class DigitalOuputs\n{\n  public const string FLAGLEDCOOL ="BIT12032"\n  ...\n}	0
1492360	1491916	C#.NET - How to inherit from an existing windows forms control	using System.Windows.Forms	0
17241451	17241378	DropDownList with Two SqlDataSources	SqlConnection connRed = new SqlConnection();\nSqlConnection connBlue = new SqlConnection();\nDataTable dt = null;\nSqlDataAdapter da = null;\n\nif(radioButtonRed.Checked)\n{\n    dt = new DataTable();\n    da = new SqlDataAdapter("select command", connRed);   \n}\nelse\n{    \n    dt = new DataTable();\n    da = new SqlDataAdapter("select command", connBlue);\n}\n\nda.Fill(dt);\ndgv.DataSource = dt;\ndgv.DataBind();	0
32030250	32029208	C# Convert string YYYYDDD to a normal date format	static void Main(string[] args)\n{\n    var dirs = Directory.GetFiles(@"C:\TestDirectory\", "MERSDLY.*");\n    foreach (string file in dirs)\n    {\n        var parts = file.Split("."); \n        var year = new DateTime(int.Parse(parts[1].Substring(0,4)), 1, 1);\n        year = year.AddDays(int.Parse(parts[1].Substring(4)) - 1);\n        parts[1] = year.ToString("MM-dd-yyyy");\n        File.Move(file,string.Join(".", parts));\n    }\n}	0
15605657	15605206	combobox items connect to column table in C# winforms	CityComboBoxEmp.DataSource = CityShow.UseSqlCommand("Select * From City").Tables[0];	0
4205385	4205085	c# WPF Cant get Parent Window	public Activity ShowLookUp(Window owner)\n    {\n\n        ActivityLookUp lookup = new ActivityLookUp();\n        lookup.Owner = owner;\n        lookup.ShowDialog();\n    }	0
14138832	14138771	How to filter a dictionary to have items with unique values?	.Where(group => @group.Any())	0
8381683	8381624	How do you nest label elements inside of a ScrollViewer?	boxAnswer.Content = new Label()\n                            {\n                                 Content = "Label",\n                                 Height = 28,\n                                 Name = "label1",\n                                 VerticalAlignment = VerticalAlignment.Top\n                             };	0
32398048	32009138	how to set width for ReportViewer for MVC	using System.Web.UI.WebControls;\n\n  ReportViewer reportViewer = new ReportViewer();\n  reportViewer.ProcessingMode = ProcessingMode.Local;\n  reportViewer.SizeToReportContent = true;\n  reportViewer.Width = Unit.Percentage(100);\n  reportViewer.Height = Unit.Percentage(100);	0
13227746	13155075	using xmlreader to read xml in xmldocument	StorageFolder folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("documents", CreationCollisionOption.OpenIfExists);\n            StorageFile file = await folder.GetFileAsync(file_name);\n            XmlDocument reade = await XmlDocument.LoadFromFileAsync(file);\n            //XmlReader reader = XmlReader.Create(@"Data/question/" + file_name);\n            XmlReader reader = XmlReader.Create(new StringReader(reade.GetXml()));	0
31112226	31107846	how to get information of a mail Item which is being dragged on Outlook 2007	// Check whether there is an Outlook process running.\n if (Process.GetProcessesByName("OUTLOOK").Count() > 0)\n {\n    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.\n   application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;\n  }	0
380609	380604	C# .NET Convert a JPEG Image into a Bitmap structure	// blob is a byte[] retrieved from DB\nBitmap bmp = new Bitmap(new MemoryStream(blob));	0
5481452	5481412	How to do an inline style with asp.net mvc 3 razor in a html helper	style = "width: 20px; background-color: " + Model.BackgroundColor + ";"	0
5202638	5202581	implement uniqueness , constraints while inserting data in a column with another column	insert into A (Aname, Work)\nselect 'GREAME', 'PLAYER'\nwhere not exists (select *\n                  from A\n                  where Aname = 'GREAME' and Work = 'PLAYER')	0
3261293	3251317	Delete one node/element from a set of similar nodes	XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load("XMLFile.xml");     \n XmlNode node = xmlDoc.SelectSingleNode("/Tags/Tag/Sample[@ID='135']");\n XmlNode parentNode = node.ParentNode;\n if (node != null) {\n   parentNode.RemoveChild(node);\n }\n xmlDoc.Save("NewXMLFileName.xml");	0
33169928	33169671	Find phone number from given string c#	string text = MyInputMethod();\nconst string MatchPhonePattern =\n       @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";\n\n        Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);\n\n        // Find matches.\n        MatchCollection matches = rx.Matches(text);\n\n        // Report the number of matches found.\n        int noOfMatches = matches.Count;\n\n\n        //Do something with the matches\n\n        foreach (Match match in matches)\n        {\n            //Do something with the matches\n           string tempPhoneNumber= match.Value.ToString(); ;\n\n         }	0
9229064	9227473	How to check if wp7 XNA touch event is within a defined rectangle	//Check if click is hitting enemy\nforeach (TouchLocation location in collection)\n{\n     if (rectangle.Contains((int)location.Position.X, (int)location.Position.Y))\n     {\n          enemyOut = enemy;\n          return true;\n     }\n}	0
9033041	9032778	Regular Expression for string replace	List<string> reservedWords = new List<string>() { "AND","OR","NEAR","NOT" };\nvar rep = Regex.Replace(\n            inputString,\n            @"([\""][\w ]+[\""])|(\w+)",\n            m=> reservedWords.Contains(m.Value) ? m.Value : "myfun(" + m.Value + ")" \n          );	0
12554666	12554005	C# Regex replace in string only outside tags	\bfoo\b(?![^<>]*>)	0
17543622	17543506	Using IDisposable interface to displose composition of classes	public void Dispose()\n    {\n        _objB.Dispose();\n    }	0
9366668	9350104	How to serialize a dictionary to an XML file?	var  dict = new Dictionary<string,Dictionary<Levels,Configuration>> ();\nvar  wtr = XmlWriter.Create (Console.Out);\nvar  dcSerializer = new DataContractSerializer (dict.GetType (), new [] {typeof (BinaryProblemConfiguration)});\ndcSerializer.WriteObject (wtr, dict);	0
18227206	18225456	Reading images from a directory and show them on the screen	namespace deneme_readimg\n{\n    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            DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");\n\n            // Clear the contents first\n            textBox1.Clear();\n            foreach (FileInfo file in dir.GetFiles())\n            {\n                // Append each item\n                textBox1.AppendText(file.Name); \n            }\n        }\n\n        private void textBox1_TextChanged(object sender, EventArgs e)\n        {\n\n        }\n    }\n}	0
5280968	5280918	1 to many relationship	public class Company\n{\n    public string CompanyID {get;set;}\n    List<Employee> Employees {get;set;}\n    List<ShareHolder> ShareHolders {get;set;}\n}\n\npublic class Employee\n{\n    public string CompanyID {get;set;}\n    //...\n}\n\npublic class ShareHolder\n{\n    public string CompanyID {get;set;}\n    //..\n}	0
2568593	2568576	Setting protected/private properties from a different instance of the same class	this.x == other.x && this.y == other.y;	0
25053497	25053434	Do Windows Phone 8 apps run on Windows Phone 8.1	Backward compatibility	0
28216040	28215808	Remove substring that starts with SOT and ends EOT, from string	public static void Main()\n {\n   string input = "This is   text with   far  too   much   " + \n                  "whitespace.";\n   string pattern = "\\s+";\n   string replacement = " ";\n   Regex rgx = new Regex(pattern);\n   string result = rgx.Replace(input, replacement);\n\n   Console.WriteLine("Original String: {0}", input);\n   Console.WriteLine("Replacement String: {0}", result);                             \n }	0
30146415	30146061	Find Biggest Concatenation Word in List	string[] words = { "five", "fivetwo", "fourfive", "fourfivetwo", "one", "onefiveone", "two", "twofivefourone" };\n\nvar allCombinations = words.SelectMany(w => words, (left, right) => left + right);\nvar combinedWords = words.Where(w => allCombinations.Contains(w));\nstring longestCombinedWord = combinedWords.OrderByDescending(w => w.Length).First();\n\nConsole.WriteLine(longestCombinedWord);	0
33572575	33556876	SearchCriteria in White - Can't Find Name in Current Context	using TestStack.White.UIItems.Finders	0
13134302	13133581	Linq to XML parsing	var propertyFilter = "IsAuthorFilterNeeded";\nvar query = xdoc.Descendants("LibraryRack")\n                .Where(lr => (string)lr.Attribute("Name") == "ScienceBooks")\n                .Descendants("Property")\n                .Where(p => (string)p.Attribute("Name") == propertyFilter)\n                .Descendants()\n                .Select(bc => (int)bc.Attribute("Value"));	0
15581521	15581454	Avoiding line length to become zero	function line(x0, y0, x1, y1)\n   dx := abs(x1-x0)\n   dy := abs(y1-y0) \n   if x0 < x1 then sx := 1 else sx := -1\n   if y0 < y1 then sy := 1 else sy := -1\n   err := dx-dy\n\n   loop\n     setPixel(x0,y0)\n     if x0 = x1 and y0 = y1 exit loop\n     e2 := 2*err\n     if e2 > -dy then \n       err := err - dy\n       x0 := x0 + sx\n     end if\n     if e2 <  dx then \n       err := err + dx\n       y0 := y0 + sy \n     end if\n   end loop	0
5872045	5871898	Dynamic pages with dynamic content	return new ContentResult\n{\n    Content = htmlFromDatabase,\n    ContentType = "text/html" // Change if you want depending on DB values\n};	0
1572386	1547967	asp http POST Read Data	byte[] buffer = new byte[Request.ContentLength];\nusing (BinaryReader br = new BinaryReader(Request.InputStream))\nbr.Read(buffer, 0, buffer.Length);	0
26788280	26788217	Windows phone 8 String to WebView uri	Jokes.Source = new Uri(ActualLoad, UriKind.Absolute);	0
5221005	5218436	Change transform origin of a matrix transform	OffsetX = OffsetX - M11 * hx - M21 * hy + hx;\nOffsetY = OffsetY - M12 * hx - M11 * hy + hy;	0
13682572	13682491	How to save a changed assembly using Mono.Cecil?	AssemblyDefinition.Write(fileName)	0
33235915	33235885	Converting from one array to another array in C#	IWebElement[] elements = Self.FindChildren();\nStep[] steps = elements.Select(x => new Step(x)).ToArray();	0
32123731	32123576	Delete Rows from a Constrained Reference Table	foreach(var nce in prospect.NewClubEmails)\n    db.NewClubProspectNewClubEmails.Remove(nce); \n\ndb.NewClubProspects.Remove(prospect);\ndb.SaveChanges();	0
4127996	4127809	cm to inch converter, two textboxes multply a value	string separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;\ntxtFoot.Text = txtFoot.Text.Replace(".", separator).Replace(",", separator);\ntxtInches.Text = txtInches.Text.Replace(".", separator).Replace(",", separator);\n\nDouble result = (Double.Parse(txtFoot.Text) * 30.48) + (Double.Parse(txtInches.Text) * 2.54);\nlblResult.Text = result.ToString();\nlblFootAndInches.Text = string.Format("{0}'{1}\"", txtFoot.Text, txtInches.Text);	0
19550456	19550402	Async with WPF properties	public string MyPath\n{\n    get { return _mypath; }\n    set\n    {\n        _myPath = value;\n        NotifyPropertyChanged(() => MyPath);\n        UpdateMyPathAsync();\n    }\n}\n\npublic async Task UpdateMyPathAsync()\n{\n    this.EnableUI = false; // Stop user from setting path again....\n    await LoadSomeStuffFromMyPathAsync(MyPath); \n    this.EnableUI = true;\n}	0
4614856	4614805	Parse full name into First Name and Last Name from SQL Server - Linq to Entities	string [] Name = fullNameString.Split(" ");\nstring firstname = Name.Take(Name.Length - 1);\nstring lastname = Name.Last();	0
5621917	5621808	Date comparison within timer	DateTime currentTime = DateTime.Now;\ncurrentTime = currentTime.AddMilliseconds(-currentTime.Millisecond);	0
32461378	32460827	Sum/Count Column Data Datatable C# Console App	var accountGroups = completeDT_units.AsEnumerable()\n                    .GroupBy(row => row.Field<String>("IDENTIFIER"))\n                    .Select(grp => new \n                     { \n                          Account = grp.Key, \n                          Count = grp.Sum(row=>row.Field<int>("INVOICE")) \n                     });	0
13589277	13587536	using IE credentials to log on with c#	WebClient client = new WebClient();\nclient.Credentials = CredentialCache.DefaultNetworkCredentials;\nclient.Proxy.Credentials = CredentialCache.DefaultCredentials;\nclient.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");	0
6540648	6046499	How can I bind a DataTable to a DataRepeater(Windows Powerpack) at Runtime?	txtEmail.DataBindings.Add("Text", "", "Email");\n    txtID.DataBindings.Add("Text", "", "ID");\n    txtName.DataBindings.Add("Text", "", "Name");\n\n    DataTable DT = BL.GetDataTable();\n    bSource.DataSource = DT;\n    DR.DataSource = bSource;	0
22245700	22245485	Focus move to first textbox of second row in Grid view	KeyboardNavigation.TabNavigation="Cycle"	0
29040345	29039792	Copy contents of cell/cells from one sheet in workBook1 to the other existing sheet in workbook2 using c#	//Check to see if path exists\n        if (!File.Exists(path1))\n        {\n            //if file does not exist, \n\n            MessageBox.Show("File does not exixt.");\n        }\n        //if exists, it will open the file to write to it\n        else\n        {\n            workBook1 = exlApp.Workbooks.Open(path1, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,\n                false, 0, true, false, false);\n        }\n\n        workBook2 = exlApp.Workbooks.Open(path2, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,\n               false, 0, true, false, false);\n\n\n\n\n        //Get the cell to copy the contents from \n        Excel.Range sourceRange = workBook1.Sheets[1].Range("A1");\n\n        //Get the destination cell(in a different workbook) to copy\n        Excel.Range destinationRange = workBook2.Sheets[1].Range("B2");\n\n        sourceRange.Copy(destinationRange);	0
3477820	3477549	How to Call javascript function with argument from code behind ASP.NET ,C#?	String csName = "myScript";\nType csType = this.GetType();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager cs = Page.ClientScript;\n\n// Check to see if the client script is already registered.\nif (!cs.IsClientScriptBlockRegistered(csType, csName))\n{\n  StringBuilder csText = new StringBuilder();\n  csText.Append("<script type=\"text/javascript\"> ");\n  csText.Append("addTab(" + myTabID + ", " + myTabList + "); </");\n  csText.Append("script>");\n  cs.RegisterClientScriptBlock(csType, csName, csText.ToString());\n}	0
13081114	13024829	How to remove entity from local copy without removing from Linq DB	var data = from p in context.Persons\n           where p.Required == "Y"\n           select p;	0
13534711	13534666	Read column from Sql and populate to listbox	while (rd.Read()){\n   ddl1.Items.Add(rd.GetValue(0).ToString());\n}	0
30928680	30928566	How to delete a row from database using lambda linq?	var friend = db.Friends.Where (x=>x.person.Id == user && x.Person1.Id == friend).FirstorDefault();\nif (friend != null)\n {\n   db.friends.Remove(friend);\n   db.SaveChanges()\n }	0
17324054	17323478	When shutting down the application, not all windows are closed	thread.IsBackground = true;	0
2419351	2419343	How to sum up an array of integers in C#	int sum = arr.Sum();	0
22079412	22079292	Null object from my model returned by view and passed to controller despite entering it in the form	NewList.Users.Add(User);	0
27695710	27695451	Create ObservableCollection from IList with grouping	gp=new ObservableCollection(groupedPeople);	0
30336848	30336596	Deserialize object using JSON.NET, but put some properties into a member of the class	public class EntityHeader\n{\n    int Id { get; set; }\n\n    int Checksum { get; set; }\n}\n\npublic class Entity\n{\n    private EntityHeader m_Header = new EntityHeader();\n    public EntityHeader Header { get { return m_Header; } }\n\n    [JsonProperty]\n    private int Id { set { m_Header.Id = value; } }\n\n    [JsonProperty]\n    private int Checksum { set { m_Header.Checksum = value; } }\n\n    public string Name { get; set; }\n\n    public bool Hair { get; set; }\n}	0
15112187	15110193	how to change text in datagridview text on condition .	private void masterDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n\n    if (masterDataGridView.Columns[e.ColumnIndex].Name.Equals("Gender"))\n                      {\n                          string _val = e.Value as string;\n                          if (_val == null)\n                              return;\n\n\n                          switch (_val)\n                          {\n                              case  "M" :\n                                  e.Value = "Male";\n                                  break;\n                              case "F":\n                                  e.Value = "Female";\n                                  break;\n\n                          }\n\n                      }\n}	0
14026179	14017157	RavenDB model Design one to many	public class Photo\n{\n    public string Id { get; set; }\n    public string Title { get; set; }\n    public string AlbumId { get; set; }\n}	0
32113135	31941328	How to connect to a folder with credentials in remote server	new Impersonator(usr_name_source, domain_source, password_source)	0
27135840	27135743	C# lambda syntax	private SomeMethod(List<string> s)\n{\n    Assert.IsNotNull(s);\n    Assert.AreEqual(1, s.Count);\n}\n\nclientSearchAsync("Getting", SomeMethod, Assert.IsNull);	0
29560113	29477100	ListPicker without selected item	protected ObservableCollection<observacao> _obsObservacao;\n    public ObservableCollection<observacao> obsObservacao\n    {\n        get { return _obsObservacao;}\n        set {\n            _obsObservacao = value;\n\n            observacao noSelection = new observacao();\n            noSelection.descricao ="Nothing Selected";\n\n            _obsObservacao.Insert(0, noSelection);\n        }\n    }	0
14203972	12633588	Parsing ISO Duration with JSON.Net	public class TimeSpanConverter : JsonConverter\n{\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        var ts = (TimeSpan) value;\n        var tsString = XmlConvert.ToString(ts);\n        serializer.Serialize(writer, tsString);\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,\n        JsonSerializer serializer)\n    {\n        if (reader.TokenType == JsonToken.Null)\n        {\n            return null;\n        }\n\n        var value = serializer.Deserialize<String>(reader);\n        return XmlConvert.ToTimeSpan(value);\n    }\n\n    public override bool CanConvert(Type objectType)\n    {\n        return objectType == typeof (TimeSpan) || objectType == typeof (TimeSpan?);\n    }\n}	0
28404477	28404294	How do you turn off Razor highlighting in VS 2013?	Tools -> Options ->Environment -> Fonts and Colors -> HTML Razor Code Background	0
13199484	13199204	How to determine if an object implements IDictionary or IList of any type	private void CheckType(object o)\n    {\n        if (o is IDictionary)\n        {\n            Debug.WriteLine("I implement IDictionary");\n        }\n        else if (o is IList)\n        {\n            Debug.WriteLine("I implement IList");\n        }\n    }	0
8290005	8289605	Change image.source with button?	Random r = new Random();\n        int rand = r.Next(0, 3);\n        switch (rand)\n        {\n            case 0:\n                charbox.Load("image1");\n                break;\n            case 1:\n                charbox.Load("image2");\n                break;\n            case 2:\n                charbox.Load("image3");\n                break;\n        }	0
5824317	5819744	MVC3 & StructureMap, injecting concrete class based on the controller	For<DogController>().Use<DogController>()\n  .Ctor<IPetInterface>("petStuff").Is<DogStuff>();\nFor<CatController>().Use<CatController>()\n  .Ctor<IPetInterface>("petStuff").Is<CatStuff>();\nFor<GiraffeController>().Use<GiraffeController>()\n  .Ctor<IPetInterface>("petStuff").Is<GiraffeStuff>();	0
5827166	76455	How do you change the color of the border on a group box?	groupBox1.Paint += PaintBorderlessGroupBox;\n\nprivate void PaintBorderlessGroupBox(object sender, PaintEventArgs p)\n{\n  GroupBox box = (GroupBox)sender;\n  p.Graphics.Clear(SystemColors.Control);\n  p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);\n}	0
1834295	1834271	Convert Time to decimal in C#	DateTime dt1 = DateTime.Parse("11:55");    \nDateTime dt2 = DateTime.Parse("9:35");\n\ndouble span = (dt1 - dt2).TotalHours;	0
13139144	3869022	Is there a way to check how many messages are in a MSMQ Queue?	using System.Diagnostics;\n\n// ...\nvar queueCounter = new PerformanceCounter(\n    "MSMQ Queue", \n    "Messages in Queue", \n    @"machinename\private$\testqueue2");\n\nConsole.WriteLine( "Queue contains {0} messages", \n    queueCounter.NextValue().ToString());	0
28061663	28061630	How to remove hyphen "-" but count the number before remove the hyphen in C#?	//Getting the textbox data and assigning to a string\n        string initialstring = textbox1.text;\n       //Calculating the total number of words available\n        int totalcount = initialstring.Split('-').Length;           \n       //Replacing the '-' character which need to be reassign to textbox\n        string formattedstring = initialstring.Replace("-", " ");\n       //Assigning formatted data to textbox\n        textbox1.text = formattedstring;	0
15475051	15474497	Compare date with today in asp.net	CompareValidator1.ValueToCompare = DateTime.Today.ToString("MM/dd/yyyy");	0
14037694	14037572	Need to create string representation of datetime	DateTime dt = new DateTime(2013, 1, 1);\n Console.WriteLine(string.Format("{0:MMM} {0,2:%d} {0:yyyy}", dt));	0
20188993	20188504	How to set up project of htmlHelpers so that it produces two dlls - for mvc3 and mvc4?	JSON.NET	0
12503984	12503917	Can I search for particular values within a List<T>?	try {   \n    var obj = list.First(x => x.Property1 == "1" && x.Property2 == "a");\n} catch {\n    // Not found\n}	0
6096878	6096692	filter IQueryable in a loop with multiple Where statements	private static IQueryable<Persoon> Filter(IQueryable<Persoon> qF, IDictionary<string, string> filter)\n{\n    IQueryable<Persoon> temp;\n    temp = qF;\n    foreach (var key in filter)\n    {\n        var currentKeyValue = key.Value;\n        if (key.Key == "naam")\n        {\n            temp = temp.Where(f => f.Naam == currentKeyValue);\n        }\n        else if (key.Key == "leeftijd")\n        {\n            temp = temp.Where(af => af.Leeftijd != null && af.Leeftijd.AantalJaarOud == Int32.Parse(currentKeyValue));\n        }\n    }\n    return temp;\n\n}	0
29153682	29103036	How to use Parse() method from the UnitsNet nuget package	Install-Package UnitsNet	0
11787499	11750672	Querying a SQL View containing XML columns from LINQ to EF	public class MyConnection : DbConnection\n{\n    ...\n    public override void Open()\n    {\n        using (SqlCommand cmd = new SqlCommand("SET ANSI_NULLS OFF", (SqlConnection)this.WrappedConnection))\n        {\n            cmd.ExecuteNonQuery();\n        }\n    }\n    ...\n}	0
28595457	28595333	How to use mappers for ICollections<Float>	ICollection<T>	0
4150661	4150522	Search a file that was created	string[] persons = File.ReadAllLines(Server.MapPath("filename.txt"));\nIEnumerable<string> personsWithBirthday =\n  from p in persons\n    where p.Contains("1980-08-21")\n      select p;\nforeach (var person in personsWithBirthday)\n Response.Write(person);	0
1520591	1520542	How to mark a method will throw unconditionally?	bool condition() { return false; }\nint bar() { return 999; }\nvoid foo(out int x)\n{\n    if (condition()) { x = bar(); return; }\n    // compiler complains about x not being set yet \n    throw MyMethodThatAlwaysThrowsAnException("missed something.");\n}\nException MyMethodThatAlwaysThrowsAnException(string message)\n{\n    //this could also be a throw if you really want \n    //   but if you throw here the stack trace will point here\n    return new Exception(message);\n}	0
8821004	8820974	How-To: Validate a FileStream is a valid PDF document with .NET	public bool IsValidPdf(string fileName)\n{\n   try\n   {\n      new iTextSharp.text.pdf.PdfReader(fileName);\n      return true;\n   }\n   catch (iTextSharp.text.exceptions.InvalidPdfException)\n   {\n      return false;\n   }\n}	0
32290593	32289571	How do I set a function property on a dynamic COM object?	AA.Filter[0, "market"] = 1;	0
2527174	2527018	Is there a less painful way to GetBytes for a buffer not starting at 0?	byte[] ToBytes() {\n        var ms = new MemoryStream(somelength);\n        var bw = new BinaryWriter(ms);\n        bw.Write(SomeShort);\n        bw.Write(SomeOtherShort);\n        return ms.ToArray();\n    }	0
73732	73713	How do I check for nulls in an '==' operator overload without infinite recursion?	Foo foo1 = null;\nFoo foo2 = new Foo();\nAssert.IsFalse(foo1 == foo2);\n\npublic static bool operator ==(Foo foo1, Foo foo2) {\n    if (object.ReferenceEquals(null, foo1))\n        return object.ReferenceEquals(null, foo2);\n    return foo1.Equals(foo2);\n}	0
7034573	7029698	Simple Data Unit of Work implementation	var db = Database.Open();\nvar tx = db.BeginTransaction(); // Internal IDbConnection opened by this call\ntry\n{\n    order = tx.Orders.Insert(order); // Returned record will have new IDENTITY value\n    foreach (var item in items)\n    {\n        item.OrderId = order.Id;\n        tx.Items.Insert(item);\n    }\n    tx.Commit(); // Internal IDbConnection closed by this call...\n}\ncatch\n{\n    tx.Rollback(); // ...or this call :)\n}	0
13588931	13588190	How to copy DataTable row to Object in C#?	public static List<T> TableToList<T>(DataTable table)\n{\n  List<T> rez = new List<T>();\n  foreach (DataRow rw in table.Rows)\n  {\n    T item = Activator.CreateInstance<T>();\n    foreach (DataColumn cl in table.Columns)\n    {\n      PropertyInfo pi = typeof(T).GetProperty(cl.ColumnName);\n\n      if (pi != null && rw[cl] != DBNull.Value)\n      {\n        var propType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;\n        pi.SetValue(item, Convert.ChangeType(rw[cl], propType), new object[0]);\n      }\n\n    }\n    rez.Add(item);\n  }\n  return rez;\n}	0
1596505	1596452	How do you get an XmlWriter to write an HTML tag with xmlns and xml:lang?	class Program\n{\n    static void Main(string[] args)\n    {\n        using (var xml = XmlWriter.Create(Console.Out, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }))\n        {\n            xml.WriteDocType("html", "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", null);\n            xml.WriteStartElement("html", "http://www.w3.org/1999/xhtml");\n            xml.WriteAttributeString("xml", "lang", "", "en");\n            xml.WriteEndElement();\n        }\n    }\n}	0
28709933	28709385	ASP.net c# how to parse the value of datetime to deduct minutes	DateTime dt;\nif(DateTime.TryParse(value, out dt))\n{\n      double minutesToDeduct = -3;\n      dt.AddMinutes(minutesToDeduct);\n}	0
1719504	1719500	In C#, what's the best way to search a list of a class by one of the class's members?	int index = list.FindIndex(m => m.Member == someMember);	0
12740564	12740516	convert PDF to byte	byte[] bytes = System.IO.File.ReadAllBytes(pathToFile);	0
19967307	19967205	C# .Net Access Internal Webpage from Internet via Public website	Response.ContentType = "image/jpeg";\nHttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);\nHttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();\nStream stream = httpWebReponse.GetResponseStream();\nImage _Image = Image.FromStream(stream);\n_Image.Save(Response.OutputStream, ImageFormat.Jpeg);	0
1623643	1623625	C# - Arguments for application	class myclass\n{\n  public static void main(string [] args)\n  {\n    if(args.Length == 1)\n    {\n       if(args[0] == "/i")\n       {\n         Console.WriteLine("Parameter i");\n       }\n    }\n  }\n}	0
26957144	26957132	Couldn't find a part of path error	wc.DownloadData("http://freegeoip.net/json/" + ip);	0
13872579	13872535	How to give IDs to Objects to use in any method?	public string InputNameBox\n{\n    get { return textBox1.Text; }\n    set { textBox1.Text = value; }\n}	0
11720080	11719283	How to close (auto hide) WPF window after 10 sec using timer	private void StartCloseTimer()\n{\n    DispatcherTimer timer = new DispatcherTimer();\n    timer.Interval = TimeSpan.FromSeconds(10d);\n    timer.Tick += TimerTick;\n    timer.Start();\n}\n\nprivate void TimerTick(object sender, EventArgs e)\n{\n    DispatcherTimer timer = (DispatcherTimer)sender;\n    timer.Stop();\n    timer.Tick -= TimerTick;\n    Close();\n}	0
5841553	5838415	Fill space between two curves in cartesian graph	List<PointF> joinedCurves = new List<PointF>();\njoinedCurves.AddRange(u);        \njointCurves.AddRange(d.Reverse());      \nPointF[] fillPoints = joinedCurves.ToArray();    \nSolidBrush fillBrush = new SolidBrush(Color.FromArgb(50, 0, 0, 200));    \nFillMode newFillMode = FillMode.Alternate;    \ng.FillClosedCurve(fillBrush, fillPoints, newFillMode, 0);	0
15986395	15986215	show all child forms through a method	using System.Reflection;\n\nprivate void openForm(string formName)\n{\n    // First check if this form is authorized \n    if (GenelIslemler.formAuthCheck(formName))\n    {\n        // Then check if is already opened\n        if (!IsOpen(formName))\n        {\n            // And now transform that string variable in the actual form to open\n\n            // This is the critical line. You need the fully qualified form name. \n            // namespace + classname \n            Type formType = Type.GetType ("RapunzoApps.ThisApp." + formName);\n            ConstructorInfo ctorInfo = formType.GetConstructor(Type.EmptyTypes);\n            Form theForm = (Form) ctorInfo.Invoke (null);\n            theForm.MdiParent = this;\n            theForm.WindowState = FormWindowState.Maximized;\n            theForm.Show();\n        }\n    }\n    else\n    {\n        MessageBox.Show("You dont have rights to access!", "uyar?", MessageBoxButtons.OK, MessageBoxIcon.Error);\n    }\n}	0
797780	797750	Is this the best way in C# to convert a delimited string to an int array?	public static int[] ToIntArray(this string value, char separator)\n{\n    return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));\n}	0
24699847	24641823	Loading XML file from UNC Path not working propertly	XDocument xDocument;\nxDocument= XDocument.Load(Path.Combine("\\\\server\\public\\Engineering","ConfigFile.xml"));	0
18090828	18090626	Import data from HTML table to DataTable in C#	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(htmlCode);\nvar headers = doc.DocumentNode.SelectNodes("//tr/th");\nDataTable table = new DataTable();\nforeach (HtmlNode header in headers)\n    table.Columns.Add(header.InnerText); // create columns from th\n// select rows with td elements \nforeach (var row in doc.DocumentNode.SelectNodes("//tr[td]")) \n    table.Rows.Add(row.SelectNodes("td").Select(td => td.InnerText).ToArray());	0
987209	987053	How to show form in front in C#	yourForm.TopMost = true;	0
21928333	21928311	How to use an OR statement within a LINQ Where statment	if (!String.IsNullOrEmpty(searchTagName))\n    {\n       Articles = Articles.Where(b => \n                b.Tag1.Contains(searchTagName) ||\n                b.Tag2.Contains(searchTagName) || \n                b.Tag3.Contains(searchTagName) ||\n                b.Tag4.Contains(searchTagName));\n    }	0
5634710	5634677	Is there a concise way to check if an int variable is equal to a series of ints? | C#	Hashset<int> ids = new HashSet<int>() {...initialize...};\n\nif(ids.Contains(id)){\n...\n}	0
26533533	26533469	How to incorporate my program into windows command promt?	public static void Main(string[] args)\n{\n    switch (args[0])\n    {\n        case "--do-something":\n           DoSomething();\n           break;\n    }\n}	0
11325713	11323765	Parse through Each li tag in browser using 'WatiN'	private void CrawlSite()\n{\n    int idx = 0;\n    do\n    {\n        idx = this.ClickLink(idx);\n    }\n    while (idx != -1);\n}\n\nprivate int ClickLink(int idx)\n{\n    WatiN.Core.Browser browser = GetBrowser();\n\n    ListItemCollection listItems = browser.List("ul_classname").ListItems;\n    if (idx > listItems.Count - 1)\n        return -1;\n\n    Link lnk = listItems[idx].Link(Find.ByClass("a class_name"));\n    lnk.Click();\n\n    //TODO: get your data\n\n    browser.Back();\n\n    return idx + 1;\n}	0
22318726	21547357	Print RDLC using Dataset without Database in C#	private void Form2_Load(object sender, EventArgs e)\n{\n     reportViewer1.LocalReport.SetParameters(SetParameter());\n     reportViewer1.RefreshReport();\n}\n\nprivate static IEnumerable<ReportParameter> SetParameter()\n{\n     return new List<ReportParameter>\n     {\n         new ReportParameter("Param1", "text1", false),\n         new ReportParameter("Param2", "text2", false),\n         new ReportParameter("Param3", "text3", false)\n     };\n }	0
4988857	4988826	C# Enter Data Into Texbox	string a = "My Message";\n\n\ntextbox1.Text = a;	0
4150685	4150640	IndexOutOfRange Exception from String.Format	private void button4_Click(object sender, EventArgs e)\n{\n    string[] lines = File.ReadAllLines("filename.txt");\n    string result = GetResultFromLines(lines, textBox5.Text);\n    label7.Text = (String.Format("Month of Birth{0}", result)); \n}	0
13401090	13401045	How to make a field read only outside class	public int NumberOfTeeth\n{\n get; private set;\n}	0
20630289	20620129	How to resolve issues with CRUD Operations in an ASP.NET MVC Kendo UI Grid	.Read(read => read.Action("GetAllUsers", "Admin").Type(HttpVerbs.Get))\n.Update(update => update.Action("UpdateUser", "Admin").Type(HttpVerbs.Post))\n.Destroy(update => update.Action("DeleteUser", "Admin").Type(HttpVerbs.Post))	0
6272899	6272819	How to use LINQ to XML to retrieve nested arrays?	var rawProperties = customerXml.Descendants("property")\n    .Select(arg =>\n        new\n        {\n            UnitBalance = arg.Element("unit-balance").Value,\n            Registers = arg.Descendants("dials").Select(x => x.Value).ToList()\n        })\n    .ToList();	0
25271432	25270490	Creating generic container with more than one value	struct structure\n{\n  public char a;\n  public string b;\n  public List<int?> c;\n}\n\nvar list = new List<structure>();	0
16063310	16063051	Combobox not displaying changing values	SelectedItem="{Binding Value, Mode=TwoWay}"	0
9136970	9136959	Weird C# declaration of a variable	byte len;\n\nif (data == null)\n{\n    len = (byte)0;\n}\nelse\n{\n    len = (byte)data.length;\n}	0
2622025	2621882	how to import data from a xml file into datagrid view using linq?	// choose you filename there\n        XElement xElement = XElement.Load("file.xml");\n        // choose appropriate properties\n        dataGridView1.DataSource = (from el in xElement.Elements()\n                  select new { a = el.Name.ToString(), b = "Whatever"}).ToList();	0
729101	729090	C#: How to add subitems in ListView	ListViewItem lvi = new ListViewItem();\nlvi.SubItems.Add("SubItem");\nlistView1.Items.Add(lvi);	0
798518	798499	Getting ipaddress and location of every user visiting your website	Request.UserHostAddress	0
1265303	1265086	Sharepoint List to ADO.Net data table	SPWeb oWebsite = SPContext.Current.Web;\nSPList oList = oWebsite.Lists["List_Name"];\nSPListItemCollection collListItems = oList.Items;\n\nDataGrid1.DataSource = collListItems.GetDataTable();\nDataGrid1.DataBind();	0
1860488	1860301	Can string formatting be used in text shown with DebuggerDisplay?	[DebuggerDisplay("Foo: Address value is {Address.ToString(\"<formatting>\"}")]	0
29292063	29189186	Convert from generic list to specific list using reflection	JsonConvert.DeserializeObject(jsonstring, prop.PropertyType.GenericTypeArguments[0]);	0
27605832	27605172	Accessing XML feed only works if fiddler is running	string path = "http://www.tfl.gov.uk/tfl/syndication/feeds/cycle-hire/livecyclehireupdates.xml";\n\nusing (System.Net.WebClient client = new System.Net.WebClient())\n{\n    client.Proxy = null;\n    client.DownloadString(path);\n}	0
15136288	15136104	Get/Set scrollbar position of ultrawingrid	var scrollPos = grid.ActiveRowScrollRegion.ScrollPosition;\nrefresh();\ngrid.ActiveRowScrollRegion.ScrollPosition = scrollPos;	0
15137726	15137689	Add/remove event suscriber in application bar item?	((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Click -= new System.EventHandler(Customization);	0
21036900	21036864	C# - OleDB Systax Error in From Clause	string sqlStatement = "SELECT * FROM [User]";	0
27822611	27802588	How to adjust vertical scroll position of DataGridView to show entire last row after changing its height?	protected override void OnRowHeightChanged(DataGridViewRowEventArgs e)\n    {\n        base.OnRowHeightChanged(e);\n        if (CurrentRow == e.Row && e.Row.Index == RowCount - 1)\n            FirstDisplayedScrollingRowIndex = e.Row.Index;\n    }	0
6650066	6649884	How To Pass Arguments In Jquery Function C# Web Application?	Page.ClientScript.RegisterArrayDeclaration("DataArray", "0.8, 0.5, 1.6");	0
11214005	11213103	formatnumber add commas every time how?	Dim a As Decimal = 123456789.123456D\nDim b As String = If(a < 0,"-","") & a.ToString("### ### ### ### ##0.####").Trim(" ")\n'Dim b As String = If(a < 0,"-","") & a.ToString("###-###-###-###-##0.####").Trim("-")	0
28820479	28820457	C# Winforms Default Button	this.ActiveControl = OkButton	0
13087542	13085959	Get Aero Window Colour	public void SomeMethod()\n{\n    int argbColor = (int)Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM","ColorizationColor", null);\n    var color = System.Drawing.Color.FromArgb(argbColor);\n    string hexadecimalColor = ConverterToHex(color);\n}\n\n\nprivate static String ConverterToHex(System.Drawing.Color c)\n{\n    return String.Format("#{0}{1}{2}", c.R.ToString("X2"), c.G.ToString("X2"), c.B.ToString("X2"));\n}	0
8931070	8930727	Remove Column from DataGridView	gvUsers.Columns["ID"].Visibility = false;	0
1869214	1869057	How to delete multiple db entities with Nhibernate?	var idList = new List<int>() { 5,3,6,7 };\n\n_session.CreateQuery("DELETE myObject o WHERE o.Id = IN (:idList)")\n    .SetParameterList("idList", idList)\n    .ExecuteUpdate();	0
12131532	12130757	Sorting many to many in entity framework	public IEnumerable<Item> Items\n    {\n        get\n        {\n            using (var context = new CatalogueContext())\n            {\n                var ids = context.Database.SqlQuery<int>("SELECT Item_Id FROM CategoryItems WHERE Category_Id = " +\n                                                         this.Id + " ORDER BY Position");\n                foreach (int id in ids)\n                    yield return context.Items.Find(id);\n\n            }\n        }\n    }	0
123791	123661	How to wait for a BackgroundWorker to cancel?	private BackgroundWorker worker = new BackgroundWorker();\nprivate AutoResetEvent _resetEvent = new AutoResetEvent(false);\n\npublic Form1()\n{\n    InitializeComponent();\n\n    worker.DoWork += worker_DoWork;\n}\n\npublic void Cancel()\n{\n    worker.CancelAsync();\n    _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made\n}\n\nvoid worker_DoWork(object sender, DoWorkEventArgs e)\n{\n    while(!e.Cancel)\n    {\n        // do something\n    }\n\n    _resetEvent.Set(); // signal that worker is done\n}	0
31828931	31828805	How to separate String array data?	static void Main(string[] args)\n{\n\n    // Input:\n    String[] values = { "A1", "B1", "C1", "5" };\n\n    // Results:\n    String[] digits = (from x in values where StringContainsNumbersOnly(x) select x).ToArray();\n    String[] cellRefs = (from x in values where !digits.Contains(x) select x).ToArray();\n\n}\n\nstatic bool StringContainsNumbersOnly(string inputString)\n{\n    return System.Text.RegularExpressions.Regex.IsMatch(inputString, @"^\d+$");\n}	0
17096561	17096494	Counting Letters in String	myString.Length; //will get you your result\n//alternatively, if you only want the count of letters:\nmyString.Count(char.IsLetter);\n//however, if you want to display the words as ***_***** (where _ is a space)\n//you can also use this:\n//small note: that will fail with a repeated word, so check your repeats!\nmyString.Split(' ').ToDictionary(n => n, n => n.Length);\n//or if you just want the strings and get the counts later:\nmyString.Split(' ');\n//will not fail with repeats\n//and neither will this, which will also get you the counts:\nmyString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));	0
33410195	33404177	How to do explicit loading for multiple entries in EF?	using (var context = new EmployeeContext())\n        {\n            var employee = context.Employees.Where(x=> x.Age > 20);\n            foreach( var item in employee)\n            {\n                context.Entry(item).Reference(x => x.ContactDetails).Load();\n                context.Entry(item).Reference(x => x.EmpDepartment).Load();\n                context.Entry(item.EmpDepartment).Collection(x => x.DepartmentProjects).Load();\n            }\n        };	0
5579799	5578599	XtraSchedule to display custom appointment caption	schedulerControl1.Views.MonthView.AppointmentDisplayOptions.EndTimeVisibility = DevExpress.XtraScheduler.AppointmentTimeVisibility.Never;\n\nschedulerControl1.Views.MonthView.AppointmentDisplayOptions.StartTimeVisibility = DevExpress.XtraScheduler.AppointmentTimeVisibility.Never;\n\nschedulerControl1.Views.MonthView.AppointmentDisplayOptions.TimeDisplayType = DevExpress.XtraScheduler.AppointmentTimeDisplayType.Text;\n\n        private void schedulerControl1_InitAppointmentDisplayText(object sender, DevExpress.XtraScheduler.AppointmentDisplayTextEventArgs e) {\n            e.Text = "test";\n        }	0
13400476	13400424	Multiple For-Loops	for (int j = 0; j < 12; j++) \n{  \n   string _image = String.Format("id('gen{0}')/a[{1}]/img", j, "1");                 \n   string _text = String.Format("id('gen{0}')/a[{1}]", j, "2");\n   ...........\n   WaitForElement(By.XPath(_text)).Click();\n\n   if(i % 4 == 3 && i != 11)\n   {\n      _carouselDot = String.Format("id('HomePage1_Carousel1')/div/ul/li[{0}]/a",\n                                                                 (i/4 + 2));\n       WaitForElement(By.XPath(_carouselDot)).Click();\n   }\n}	0
9611499	9611446	Cant change window size in Visual Studio?	private void Form1_Load(object sender, EventArgs e)\n{\n    this.Size = new System.Drawing.Size(300, 300);\n}	0
597055	470846	Winforms WPF Interop - WPF content fails to paint	_elementHost.Width++;	0
7156242	7156176	How to integated plupload into asp.net MVC2 project	[HttpPost]\n    public ActionResult Create(FormCollection collection)\n    {\n        // my project need single file upload so i get the first file\n        // also you can write foreach statement to get all files\n        HttpPostedFileBase postedFile = Request.Files[0];\n        Image image = new Image();\n        if (TryUpdateModel(image))\n        {\n            fRepository.AddImage(image);\n            fRepository.Save();\n\n            // Try to save file\n            if (postedFile.ContentLength > 0)\n            {\n                string savePath = Path.Combine(Server.MapPath("~/Content/OtelImages/"), image.ImageID.ToString() +\n                                                   Path.GetExtension(postedFile.FileName));\n                postedFile.SaveAs(savePath);\n\n                // Path for dbase\n                image.Path = Path.Combine("Content/OtelImages/", image.ImageID.ToString() +\n                                                   Path.GetExtension(postedFile.FileName));\n            }	0
33920087	33920054	Selecting a node if the attribute is equal to a predefined string	string attribValue = "test";\nstring expression = String.Format("Element[@Attribute = '{0}']", attribValue);\nroot.SelectNodes(expression);	0
17309129	17308863	Get WPF control height when it is set 'Auto'	textBox1.ActualHeight	0
554663	554649	How to bind LINQ data to dropdownlist	protected void BindMarketCodes()\n{    \n    using (var dataContext = new LINQOmniDataContext()) {\n        //bind to Country COde droplist\n        dd2.DataSource = from p in dataContext.lkpMarketCodes \n            orderby p.marketName\n            select new {p.marketCodeID, p.marketName};\n        dd2.DataTextField = "marketName";\n        dd2.DataValueField = "marketCodeID";\n        dd2.DataBind();\n    }\n}	0
13732098	13732070	How can I capture mouse events that occur outside of a (WPF) window?	private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        this.DragMove();\n    }	0
16190345	16190258	How can I INSERT or UPDATE values into a DB through code behind	// Update the access levels\n    foreach (RepeaterItem i in rptRollRules.Items)\n    {\n\nDataRow drRules = rules.NewRow(); //One table row per repeater row\n\n        //Retrieve the state of the CheckBox\n        CheckBox chkIsAllowed = (CheckBox) i.FindControl("chkIsAllowed");\n        Label lblRollId = (Label) i.FindControl("lblRollId");\n        Label lblAccessId = (Label) i.FindControl("lblAccessId");\n\n        drRules["rollId"] = lblRollId.Text;\n        drRules["rollAccessId"] = lblAccessId.Text;\n        drRules["allowed"] = chkIsAllowed.Checked.GetHashCode();\n\nrules.Rows.Add(drRules); //Add your row to the data table\n    }\n\ncmd = new SqlCommand(); //Can't remember the syntax\ncmd.CommandText = "EXEC YourMergeStoredProcedure @YourDataTable";\nSqlParameter sqlParameter = cmd.Parameters.AddWithValue("@YourDataTable", drRules);\nsqlParameter.SqlDbType = SqlDbType.Structured;\ncmd.ExecuteNonQuery();	0
26796968	26796081	parse nested json string in c#	public class JsonUserContext\n{\n    public string AccountNo { get; set; }\n    public string AuthValue { get; set; }\n}\n\npublic class UserContext\n{\n    public string AccountNo { get; set; }\n    public Auth AuthValue { get; set; }\n}\n\npublic class Auth\n{\n    public string TopUpMobileNumber { get; set; }\n    public string VoucherAmount { get; set; }\n}\n\n...\n\nvar jsonUserContext = JsonConvert.DeserializeObject<JsonUserContext>(json);\nvar authJson = jsonUserContext.AuthValue;\nvar userContext = new UserContext {\n    AccountNo = jsonUserContext.AccountNo,\n    AuthValue = JsonConvert.DeserializeObject<JsonUserContext>(authJson);\n};	0
32560205	32560158	How to display date in '12JAN2015 ' format from current date in mvc 4	string.Format("{0:ddMMMyyyy}", DateTime.Now)	0
27513301	27512972	Conditional LINQ query on self-joining table with 2 sets of data	var query = from e in Employees\n            join a in Employees on e.EmployeeAssistantID equals a.EmployeeID\n            where e.EmployeeID == 2\n            select new\n            {\n               EmployeeID = e.EmployeeID,\n               AssistantID = a.EmployeeID,\n               EmployeeProjects = Projects.Where(p => p.EmployeeID == e.EmployeeID),\n               AssistantProjects = Projects.Where(p => p.EmployeeID == a.EmployeeID)\n            };	0
24058525	24058132	Using polymorphism in VB	If TypeOf ctrl Is Control Then\n   ctrl = Directcast(ctrl, control)\nEnd If	0
15427531	15409382	Grab a List item based on newest datetime	var m04FrontpagesEntities = new view_M04FrontpagesService().GetByCategoryId(0).ToList().Select(x => new M02ArticlesService().GetById(x.M02ArticleId)).ToList().OrderByDescending(x => x.UpdatedDate); ;\nvar article = m04FrontpagesEntities.First();	0
18407164	18407079	How can you set an entire object using LINQ to SQL?	newContext.YourEntity.Attach(YourAlreadyPopulatedObject)	0
514901	514892	How do i make a http get request with parameters in c#	string url = "http://somesite.com?var=12345";	0
4824530	4824320	Printing a picture from a Console Application	PrintDocument pd = new PrintDocument();\npd.PrintPage += (thesender, ev) => {\n        ev.Graphics.DrawImage(Image.FromFile("Your Image Path"), \n        //This is to keep image in margins of the Page.\n        new PointF(ev.MarginBounds.Left,ev.MarginBounds.Top));\n    };\npd.Print();	0
23913849	23913243	Add Label with Textbox at design time	public class CustomTextBox : TextBox\n    {\n        public Label AssociatedLabel { get; set; }\n\n        public CustomTextBox():base()\n        {\n            this.ParentChanged += new EventHandler(CustomTextBox_ParentChanged);\n        }\n\n        void CustomTextBox_ParentChanged(object sender, EventArgs e)\n        {\n            this.AutoAddAssociatedLabel();\n        }\n\n        private void AutoAddAssociatedLabel()\n        {\n            if (this.Parent == null) return;\n\n            AssociatedLabel = new Label();\n            AssociatedLabel.Text = "Associated Label";\n            AssociatedLabel.Padding = new System.Windows.Forms.Padding(3);\n\n            Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);\n            AssociatedLabel.Location = new Point(this.Location.X - s.Width - AssociatedLabel.Padding.Right, this.Location.Y);\n\n            this.Parent.Controls.Add(AssociatedLabel);\n        }\n    }	0
18913573	18913538	C# Get non duplicates in a list	var singles = numbers.GroupBy(n => n)\n                     .Where(g => g.Count() == 1)\n                     .Select(g => g.Key); // add .ToArray() etc as required	0
9879299	9879250	Loop inside a array within a dictionary	var res = groups.Where(g => g.Value.Any(t => t.Equals("search_tag")));	0
20744476	20744423	Need Regex value to match correctly for my input text	Regex.Matches(s, "(\\w+)=\"([\\w\\.:\\-\\?/=]+)\"", ...params...);	0
23502679	23502648	How to add enum in generic lists	list.Add((T)(object)ProcessorEnum.B2B);	0
17491709	17482628	How to activate my application after I run another process - C#	public partial class OnScreenKeyboard : Form\n{\n\n    private const int WS_EX_NOACTIVATE = 0x08000000;\n\n    protected override CreateParams CreateParams\n    {\n        get\n        {\n            CreateParams p = base.CreateParams;\n            p.ExStyle |= WS_EX_NOACTIVATE;\n            return p;\n        }\n    }\n\n}	0
32273825	32273720	How to avoid the duplicates in drop-down list by using linq?	var filteredList = originalList\n  .GroupBy(x => x.Gender)\n  .Select(group => group.First());	0
5437018	5437002	reflection: private property how to extract custom attribute	var type = this.GetType();\nforeach(var prop in \n    type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))\n{\n    var attr = prop.GetCustomAttributes(typeof(SaveInStateAttribute), true);\n\n    if(attr.Length > 0)\n    {\n        // Add the attributes to your collection\n    }\n}	0
589346	589173	Rendering an image at runtime in WPF	Dispose()	0
19740493	19740189	2D graphics with C#	-Beginning DirecX11 Game Programming by Allen Sherrod and Wendy Jones(Course Technology)	0
17806220	17805705	how to get time line on y axis	var sl = new System.Windows.Forms.DataVisualization.Charting.StripLine();\n        sl.IntervalOffset = 8;\n        chart1.ChartAreas[0].AxisY.StripLines.Add(sl);	0
29386927	29384167	IndexOutOfRange unless I split the query into multiple queries	TextChange event	0
29235847	29213976	Prevent Silverlight Out-Of-Browser App from opening twice	private bool CheckSingleInstance()\n{\n    try\n    {\n        var receiver = new LocalMessageReceiver("application name", ReceiverNameScope.Global, LocalMessageReceiver.AnyDomain);\n        receiver.Listen();\n        return true;\n    }\n    catch (ListenFailedException)\n    {\n        // A listener with this name already exists\n        return false;\n    }\n}	0
5599939	5599078	Get Sitecore "Site" data from web.config in WCF	var site = Sitecore.Configuration.Factory.GetSite(sitename);	0
5168958	5168885	Regex fails to match string	string pattern = @"\/>[^<]*abc";\n\n\n  string text = @"<foo/> hello first abc hello second abc <bar/> hello third abc";\n\n\n  Regex r = new Regex(pattern, RegexOptions.IgnoreCase);\n\n\n  Match m = r.Match(text);	0
14065126	14065100	Get the name of the parameter that is passed to function	AddVariable("test variable")	0
5326140	5326111	How to refresh singleton in C#	if (m_Instance == null)	0
3141717	3141308	How do I retrieve the username that a Windows service is running under?	using System;\nnamespace WindowsServiceTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            System.Management.SelectQuery sQuery = new System.Management.SelectQuery(string.Format("select name, startname from Win32_Service")); // where name = '{0}'", "MCShield.exe"));\n            using (System.Management.ManagementObjectSearcher mgmtSearcher  = new System.Management.ManagementObjectSearcher(sQuery))\n            {\n                foreach (System.Management.ManagementObject service in mgmtSearcher.Get())\n                {\n                    string servicelogondetails =\n                        string.Format("Name: {0} ,  Logon : {1} ", service["Name"].ToString(), service["startname"]).ToString();\n                    Console.WriteLine(servicelogondetails);\n                }\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
23669211	23669107	Define a function in C# thet get Dynamic parameter?	public int Test(params object[] r)\n        {\n           //Your Code\n            return 0;\n        }	0
10972487	10972384	How do I get an auto completion from a database in visual studio ?	textBox1.AutoCompleteCustomSource = DataHelper.LoadAutoComplete();\ntextBox1.AutoCompleteMode = AutoCompleteMode.Suggest;\ntextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;	0
13226374	13226273	how to Parse XML using XElement.Parse without looking/changing Entities to characters?	var xmlText = "<name><firstname><![CDATA[Willi&aacute;ms]]></firstname></name>";	0
15965321	15937449	How to set session scope for plugin in StructureMap 2.6?	c.For<ISomeObject>().LifecycleIs(new HttpSessionLifecycle()).Use<SomeObject>();	0
31344972	31344765	How to take the Product of a List?	Console.WriteLine("My Job is to take the factorial of the number you give");\nConsole.WriteLine("What is the number?");\nint c = Convert.ToInt32(Console.ReadLine());\nint total = 1;\n\nfor (int i = 2; i < c; i++)\n{\n    total *= i;\n}\n\nConsole.WriteLine(total.ToString());\nConsole.ReadLine();	0
9461084	9458319	Using DataGrid to collect input data and store it in a List<>, programmatically	Binding bRaio=new Binding();\nbRaio.Path = new PropertyPath("RAIO");\nbRaio.Mode = BindingMode.TwoWay;\nColRaio.Binding = bRaio;	0
10276190	10247794	How to modify Http Method in C#?	hbWebRequest.Method = "POST";	0
9183825	9171187	Retrieving all user accounts on an accessible external Active Directory server over LDAPS	// create a search filter to find all objects\nstring ldapSearchFilter = "(&(objectCategory=person)(objectClass=user))";	0
7608656	7608527	How to get response from web API call	string urlData = String.Empty;\nWebClient wc = new WebClient();\nurlData = wc.DownloadString("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx");	0
17042844	17042264	Returning valid JSON from JSON Formatter on HTTP OK for WebAPI	return new HttpResponseMessage(HttpStatusCode.NoContent);  // 204 Status Code	0
897501	897485	C#: Which uses more memory overhead? A string or a char holding a sequence of a word?	//.Net Framework allocates memory space for "word" only once, all the three variables refer to this chunk of memory\nString s1, s2, s3;\ns1 = "word";\ns2 = "word";\ns3 = "word";\n\n//.Net Framework allocates memory for each array\nchar[] c1 = new char[] { 'w','o','r','d'};\nchar[] c2 = new char[] { 'w','o','r','d'};\nchar[] c3 = new char[] { 'w','o','r','d'};	0
2145765	2145736	How to add xml-stylesheet tags to an XML file using C#?	public static void Main()\n{\n    var doc = new XmlDocument();\n    doc.AppendChild(doc.CreateProcessingInstruction(\n        "xml-stylesheet", \n        "type='text/xsl' href='colors.xslt'"));\n}	0
12540547	12540458	How to replace same text in a text file	private void button1_Click(object sender, EventArgs e)\n{\n    try\n    {\n        string file= File.ReadAllText("data.txt");\n        FileStream fs = new FileStream("data.txt", FileMode.Append,\n        FileAccess.Write);\n        StreamWriter sw = new StreamWriter(fs);\n        if(file.Contains(textBox1.Text+"\r\n"+textBox2.Text);\n        {\n           //Do nothing if you already have them in the file\n        }\n        else\n        {\n          sw.WriteLine("Email ID: "+textBox1.Text);\n          sw.Write("Password: "+textBox2.Text);\n          sw.WriteLine();\n          sw.WriteLine();\n        }\n        sw.Flush();\n        sw.Close();\n        fs.Close();\n    }\n    catch (Exception)\n    {\n        MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\n        this.Close();\n    }\n        MessageBox.Show("DONE", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);\n        textBox1.Clear();\n        textBox2.Clear();\n}	0
2538084	2538052	How to access the controls of form2 in form1 in C# 2008/2010	Form2 secondForm = new Form2();\nForm2.Show();\n\nsecondForm.somePublicControl.Text = "test";\nMessageBox.Show(secondForm.somePublicVariable);	0
17589867	17587344	Accessing multiple arrays in JSON using C#	var postTitles = data.Children() // Select array container properties, like "2013"\n        .SelectMany(x => x.First) // Select each subitem from every array\n        .Select(r => // Create a report for each item\n            new Report\n                {\n                    Date = DateTime.Parse((string)r["date"]),\n                    Height = (int)r["height"]\n                }\n            );	0
4474448	4474326	C# equivalent to Python's traceback library	catch(Exception e)\n{\n    Console.WriteLine(e.StackTrace);\n}	0
7596554	7596302	Read file from position	using (FileStream fs = new FileStream(@"file.txt", FileMode.Open, FileAccess.Read))\n        {\n            fs.Seek(100, SeekOrigin.Begin);\n\n            byte[] b = new byte[fs.Length - 100];\n            fs.Read(b, 0, (int)(fs.Length - 100));\n\n            string s = System.Text.Encoding.UTF8.GetString(b);\n        }	0
13781495	13781468	Get list of properties from List of objects	List<string> properties = objectList.Select(o => o.StringProperty).ToList();	0
14413632	14413427	Calculate the angle of a click point	internal double GetAngleFromPoint(Point point, Point centerPoint)\n{\n    double dy = (point.Y - centerPoint.Y);\n    double dx = (point.X - centerPoint.X);\n\n    double theta = Math.Atan2(dy,dx);\n\n    double angle = (90 - ((theta * 180) / Math.PI)) % 360;\n\n    return angle;\n}	0
27963632	27296423	How to make first letter upper case in every word without using functions in mysql?	REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(COLUMN_NAME, '_a', 'A'), '_b', 'B'), '_c', 'C'), '_d', 'D'), '_e', 'E'), '_f', 'F'), '_g', 'G'), '_h', 'H'), '_i', 'I'), '_j', 'J'), '_k', 'K'), '_l', 'L'), '_m', 'M'), '_n', 'N'), '_o', 'O'), '_p', 'P'), '_q', 'Q'), '_r', 'R'), '_s', 'S'), '_t', 'T'), '_u', 'U'), '_v', 'V'), '_w', 'W'), '_x', 'X'), '_y', 'Y'), '_z', 'Z')	0
6343481	6341383	How to create a nested GridView to edit EF Code First relation?	Dim gv As GridView\n        Dim l1, l2 As Label\n        Dim strsql As String\n        For Each grd1 In GridView1.Rows\n            'find controls of parent gridrow\n            l1 = grd1.FindControl("l00")\n            l2 = grd1.FindControl("l1")\n            gv = grd1.FindControl("gv1")\n            strsql = "select file_name from product_file where pname='" & l1.Text & "' and categry='" & l2.Text & "'"\n          Dim dt1 As New DataTable()\n            Dim da1 As New SqlDataAdapter(strsql, con)\n            da1.Fill(dt1)\n            gv.DataSource = dt1\n            gv.DataBind()\n        Next	0
10985477	9518906	EWS Managed API - Save Draft with inline Images	string html = @"<html>\n                 <head>\n                 </head>\n                 <body>\n                    <img width=200 height=100  id=""1"" src=""cid:Desert.jpg"">\n                 </body>\n                 </html>";\n\n        newMessage.Body = new MessageBody(BodyType.HTML, html);\n        string file = @"D:\Tools\Desert.jpg";\n        newMessage.Attachments.AddFileAttachment("Desert.jpg", file);\n        newMessage.Attachments[0].IsInline = true;\n\n        //this is required to fix the issue - Add content id programatically\n        newMessage.Attachments[0].ContentId = "<Desert.jpg>";\n\n        newMessage.Save();	0
26264827	26264762	Converting an integer to an array of digits	int i = 123;\nvar digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();	0
21004766	21004566	Add row to Access Table from DataTable	string sql = String.Format("INSERT INTO Students(FirstName,LastName) VALUES({0},{1})", "John", "Connor")	0
11841148	11840992	WPF Navigator control - if source equals?	using System;\n\n...\n\nURI myUri = new URI("http://testinglink.com"); \n\nwebBrowserWorkFlows.Source = myUri;\n//OR    \nwebBrowserWorkFlows.Navigate(myUri);\n...\n\nif (webBrowserWorkflows.Source == myUri)\n{\n    // do stuff\n}	0
22500531	22500356	Identifying distinct item in a C# list after spliting the value	var grouped = from emp in empList\n                  group emp by emp.Location.Split('&')[0] into g\n                  select new {LocCode = g.Key, Emps = g};\n\n    foreach (var group in grouped) {\n        // group.LocCode contains, e.g., [USA].[NYC].,\n        // group.Emps contains all employees at this location\n    }	0
225556	225545	Detecting running in Main Thread in C# library	if (MyLibraryControl.InvokeRequired)\n  //do your thing here	0
16269721	16268498	How to make a Custom Dialog stay on top of its parent without being on top of other applications	MyCustomDialog.Show(this);	0
12268681	12268660	How do I construct a USING statement given the following code?	using (Stream st = request.GetRequestStream())\n{\n    st.Write(bytes, 0, bytes.Length);         \n}	0
4439739	4437447	How to release Outlook MailItem correct?	List entryids = new List();\n\nforeach (var selection in Globals.ThisAddIn.Application.ActiveExplorer().Selection)\n{\n    MailItem mi = selection as MailItem;\n    if (mi != null)\n    {\n        // For any reason it's not possible to change the mail here\n\n        entryids.Add(mi.EntryID);\n\n        Marshal.ReleaseComObject(mi);\n        mi = null;\n\n    }\n}\n\nforeach (string id in entryids)\n{\n    MailItem mi = Globals.ThisAddIn.Application.ActiveExplorer().Session.GetItemFromID(id);\n\n    // My changes on the mail\n\n    mi.Save();\n    Marshal.ReleaseComObject(mi);\n    mi = null;\n}	0
27587597	27579771	How to create "Text Contains" FormattingConditional (Format Condition) for Excel with C#	FormatCondition cond = sheet.get_Range("A1:I70000", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlTextString, Type.Missing, Type.Missing, Type.Missing, "SomethingToFilterIfContained", XlContainsOperator.xlContains, Type.Missing, Type.Missing);\n cond.Interior.Color = color;	0
22808011	22807276	Linq To Sql Finding item in many to many relationship	return dbContext.Users.Where(u => u.UserCodePK == userCode \n     && u.UserGroups.Where(ug => userGroupList.Contains(ug.GroupCodePK)).Any();	0
15828180	15824961	Simple update with Entity Framework	public static void UpdateProduct(ViewProduct productToUpdate)\n{\n    using (var context = new my_Entities())\n    {\n        var BaseProduct = (from prod in context.Product\n                           where prod.Ref == productToUpdate.BaseProduct.RefPrd)\n                          .FirstOrDefault();\n\n        if (BaseProduct != null)\n        {\n            //BaseProduct.NormeCe = false;\n            BaseProduct.field1 = productToUpdate.BaseProduct.field1;\n            BaseProduct.field2 = productToUpdate.BaseProduct.field2;\n\n            //update the necesary fields\n            //......\n            context.SaveChanges();\n        }\n    }\n}	0
8400097	8400050	Converting hex string back to char	hex = hex.Substring(2); // To remove leading 0x\nint num = int.Parse(hex, NumberStyles.AllowHexSpecifier);\nchar cnum = (char)num;	0
13154318	13140633	How to prevent the transformation of special signs in URI?	SQLFilter=Title LIKE '%" + searchTerm + "%'"	0
13954326	13954076	execute x number of Actions each every n milliseconds	static Task Repeat (List<Action> actions, CancellationToken token, int delay)\n{\n    var tasks = new List<Task> ();\n    var cts = CancellationTokenSource.CreateLinkedTokenSource (token);\n\n    foreach (var action in actions) {\n        var task = Task.Factory.StartNew (async () => {\n            while (true) {\n                cts.Token.ThrowIfCancellationRequested ();\n                await Task.Delay (delay, cts.Token).ConfigureAwait (false);\n                action ();\n            }\n        });\n        tasks.Add (task);\n    }\n\n    return Task.WhenAll (tasks);\n}	0
2082801	2082791	Is it possible to deserialize JSON to List<MyObject<T,K>> with JSON.Net	public KVPair() {\n}	0
6406918	6387118	How can I deal with NULL values in data table turning into missing XML elements when inserting in SQL Server?	I just solved this problem by assigning -1 instead of null. I know this is not the right solution. But I solved using this method.	0
13483003	13482895	Proper way of cancel execution of a method	CancellationTokenSource tokenSource = new CancellationTokenSource();\n Task.Factory.StartNew( () => {\n    // Do work\n    onCompleteCallBack(someResult);\n  }  tokenSource.Token);\n\nprivate void cancel_Click(object sender, RoutedEventArgs e)\n{\n    tokenSource.Cancel();\n\n}	0
23742343	23741894	How do I get my API to include a child class?	namespace HobbsEventsMobile.Models\n{\n    [DataContract]\n    public class Category\n    {\n        [DataMember]\n        public int ID;\n        [DataMember]\n        public string Name;\n        // everything else\n    }\n}	0
26643264	26642981	How get Event "item Selected" with AutoComplete in C#?	private void textBox1_KeyDown(object sender, KeyEventArgs e) {\n    if (e.KeyData == Keys.Enter) {\n        String selItem = this.textBox1.Text;\n    }\n}	0
29817582	29817328	Sum values in datatable using linq based on conditions	var result = from row in dt.AsEnumerable()\n            group row by row["ID"]\n            into g\n            select new\n            {\n                ID = g.Key,\n                Sum = g.Sum(x => int.Parse(x["Percentage"].ToString()))\n            };\n\nvar errorItems = result.Where(x => x.Sum != 100 && x.Sum != 0);\nif (errorItems.Any())\n{\n    var ids = errorItems.Select(x => x.ID);\n    string msg = string.Format("ID(s): [{0}] don't meet condition.", string.Join(",", ids));\n    MessageBox.Show(msg);\n}	0
17695193	17695147	convert selected item back to custom data type, winforms	listview1.Columns.Add("Col1");\nlistview1.Columns.Add("Col2");\nforeach(ArticleDetails ad in myCollection)\n{\n   var row = new ListViewItem(ad.Article.Name);\n   row.Tag = ad; // You can use this to store your object\n   row.SubItems.Add(ad.Article.Price);\n}\nlistview1.View = View.Details;\n\n\nprivate void btnDelete_Click(object sender, EventArgs e)\n{\n   var selected = (CustomDataType)listview1.SelectedItems[0].Tag;\n}	0
31770184	31770152	Setting Button Content from DatePicker DatePicked event	void fromDatePicker_DatePicked(DatePickerFlyout sender, DatePickedEventArgs args)\n    {\n      fromDate.Content =  sender.Date.DateTime.ToString();\n    }	0
5596019	5595978	how to replace javascript '\' with another char	yourVar = yourVar.replace(/\\/g, '?');	0
6911493	6911407	Insert string into SQL as datetime without CAST	with cte (ID, changedate, SupplierID) as (\n   --type but no data\n   select 0, getdate(), 0 where 0=1 union \n\n   SELECT 1720,  '1997-12-17 12:00:00 AM',  763\n   UNION ALL\n   SELECT 1721,  '1900-01-01 12:00:00 AM',  114\n)\nselect * into components8_2_2011_3  from cte	0
7782334	6577570	Adding number attribute to every HTML Tag	// note: Descendants() and DescendantNodes() is equivalent (unfortunately)\nvar query = htmldoc.DocumentNode.Descendants()\n    .Where(node => node.NodeType == HtmlNodeType.Element);	0
4778870	4778712	Removing Invalid Characters from XML Name Tag - RegEx 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.Text.RegularExpressions;\n\nnamespace WindowsFormsApplication3\n{\n    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            Regex r = new Regex(@"(?<=\<\w+)[#\{\}\(\)\&](?=\>)|(?<=\</\w+)[#\{\}\(\)\&](?=\>)");\n            textBox2.Text = r.Replace(textBox1.Text, new MatchEvaluator(deleteMatch));\n        }\n\n        string deleteMatch(Match m) { return ""; }\n    }\n}	0
31937755	31937416	How to get the Windows version to include in a UserAgent string	string versionString = "Unknown OS Version";\n\nvar osVersion = System.Environment.OSVersion;\nif (osVersion.Platform == PlatformID.Win32NT)\n{\n    versionString = string.Format("Windows NT {0}.{1}", \n                                  osVersion.Version.Major, \n                                  osVersion.Version.Minor); \n}\nelse\n{\n    // handle non-NT Windows\n}	0
8107520	8107479	Regex - replace characters	myString = Regex.Replace(myString, @"\$\[((?:\[.*?\]|.)*?)\]", "${$1}");	0
22938185	22936508	How to use ManualResetEvent without freezing my UI	'assume that backgroundworker is named "BBC"\n'support cancellation task\n BBC.WorkerSupportsCancellation = True\n'enable report progress \n BBC.WorkerReportsProgress = True\n'run it        \n BBC.RunWorkerAsync()	0
10122618	10122461	Get all tracked entities from a DbContext?	public class MyContext : DbContext\n{\n    //...\n\n    public override int SaveChanges()\n    {\n        foreach (var dbEntityEntry in ChangeTracker.Entries<AbstractModel>())\n        {\n            dbEntityEntry.Entity.UpdateDates();\n        }\n        return base.SaveChanges();\n\n    }\n}	0
13947950	13947790	Changing the colour of filtered text in binding data source	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    try\n    {\n        if (row.Cells[6].Value.ToString().Contains(textBox1.Text))\n            row.Cells[6].Style.ForeColor = Color.Red;\n    }\n    catch (Exception){}\n}	0
32415701	32414954	Is there a replacement for Attribute.IsDefined in UWP apps?	var types = this.GetType().GetTypeInfo().Assembly.GetTypes()\n        .Where(t => t.GetTypeInfo().GetCustomAttribute<MyAttribute>() != null);	0
7900105	7898891	How to obtain Server Time in LinqPad	Connection.Open();\nvar command = Connection.CreateCommand();\ncommand.CommandText = "select GetDate()";\ncommand.ExecuteScalar().Dump();	0
26913360	26912786	Sort elements of an XDocument based on their grandchild	// Extract "employee" Xelements in order.\nvar orderedEmployees = \n    from employee in xml.Descendants("employee")\n    orderby employee.Element("identification").Element("lastName").Value,\n            employee.Element("identification").Element("firstName").Value\n    select employee;\n\n// Build a new Xelement with the original root and orderded "employee" elements.\nvar result = new XElement(xml.Root.Name,\n                 from employee in orderedEmployees\n                 select new XElement(employee)\n             );	0
15632770	15472515	Problems with Castle dynamic proxy + Ninject as DI	var interfaceType = type.GetInterfaces().Single();\n\nvar proxy = generator.CreateClassProxy(type,\n    new Type[] { interfaceType },\n    new IInterceptor[]\n    {\n        new CacheInterceptor(), \n        new LoggingInterceptor()\n    });\n\n// I'm using directive ToConstant(..), and not To(..)\nBind(interfaceType).ToConstant(proxy).InThreadScope();	0
10145593	10145552	Displaying records for two weeks only! from creation	var now = DateTime.Now;\nvar twoWeeksAgo = now.AddDays(-14);\nvar adverts = \n    from advert in db. Adverts\n    where advert.date >= twoWeeksAgo && advert.date <= now\n    select advert;	0
20094574	20094407	How to set canvas ZIndex WPF button control in Click Event?	Canvas.SetZIndex(control name, int index);	0
26423664	26404569	Data from one datagridview to another c#.net	int count =0; // declare in public class\n\nprivate void button3_Click(object sender, EventArgs e)\n    {\n        if (dataGridView2.SelectedRows.Count > 0)\n        {\n         dataGridView1.Rows.Add(dataGridView2.SelectedRows.Count); // add rows before entering data inside the new dataGridView.\n        }\n        foreach (DataGridViewRow row in dataGridView2.SelectedRows)\n        {\n\n            {\n                string value1 = row.Cells[0].Value.ToString();\n                string value2 = row.Cells[1].Value.ToString();\n                dataGridView1.Rows[count].Cells[0].Value = value1;\n                dataGridView1.Rows[count].Cells[1].Value = value2;\n            }\n        }\n\n        count =count + 1;\n        dataGridView2.ClearSelection(); // I used this because i have to work with 4 dataGridViews \n}	0
11284189	11284140	How to remove a duplicate set of characters in a string	string url = "http://www.google.comhttp://www.google.com";\nif (url.Length % 2 == 0)\n{\n    string secondHalf = url.Substring(url.Length / 2);\n    if (url.StartsWith(secondHalf))\n    {\n        url = secondHalf;\n    }\n}	0
7404500	7404401	can't set the position of a contextmenustrip?	if (e.Button == MouseButtons.Right)\n{\n    contextMenuStrip1.Show(Cursor.Position);\n}	0
26685959	26644811	Make a bubble level with Unity 3D?	// where q is the Quaternion from the gyro\n\n    Matrix4x4 quatMatrix = Matrix4x4.TRS(Vector3.zero, q, Vector3.one);\n    Matrix4x4 scaleMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 0, 1));\n    Matrix4x4 scaled_matrix  = scaleMatrix * quatMatrix;\n    OutVector = scaled_matrix.MultiplyVector(Vector3.forward).normalized;	0
5534822	5534534	View Excel in WebBrowser control C#	File Download	0
26054016	26038138	How to use value from list without repeating? (Random.Range)	for(int a=0; a<16; a++)\n        {\n\n\n            //rnd = new Random ();\n            while (planePosition.Count != 0)\n            {\n                     int index = Random.Range (0, planePosition.Count-1);\n                     randomizedList.Add (planePosition [index]);\n                    Newplan.transform.position =  new Vector3 (randomizedList[r].x, randomizedList[r].y ,9.990011f);\n                    planePosition.RemoveAt (index);\n\n            }\n\n        }	0
11333651	11333382	Count all lines from file starting with a certain character and ending with a different character	File.ReadLines(somePath).Count(line=>Regex.IsMatch(line,"(^X.*$)|(^.*Y$)"))	0
12403961	12403344	Find out the names of all the attributes in an entity returned from CRM Dynamics	foreach (Entity entity in result.Entities)\n{\n    foreach (KeyValuePair<String, Object> attribute in entity.Attributes)\n    {\n        Console.WriteLine(attribute.Key + ": " + attribute.Value);\n    }\n}	0
1126069	1125958	How do I discover how my process was started	using System.Diagnostics;\nPerformanceCounter pc = new PerformanceCounter("Process",\n"Creating Process ID", Process.GetCurrentProcess().ProcessName);\nreturn Process.GetProcessById((int)pc.NextValue());	0
26785713	26783828	View New Form With Populated data after Clicking specific DataGrid Cell	editStudent editStudent = new editStudent();\n            editStudent.firstName.Text = dataGridView1.CurrentRow.Cells["First Name"].Value.ToString();\n            editStudent.ShowDialog();	0
13008190	13008161	Relative connection strings in c# for SQL Server 2008	"directory/file"	0
9401687	9401647	How to parse user credentials from URL in C#?	Uri uriAddress = new Uri ("http://user:password@www.contoso.com/index.htm ");\nConsole.WriteLine(uriAddress.UserInfo);	0
3939873	3939865	How exactly are Projects in the same Solution related?	[InternalsVisibleTo]	0
3131770	3131704	How to determine whether an relative path points outside an given path	public static bool IsChildOf(this string path, string parentPath)\n{\n    return Path.GetFullPath(path).StartsWith(Path.GetFullPath(parentPath),\n           StringComparison.InvariantCultureIgnoreCase);\n}	0
6693502	6692822	a specific plinq query	dic.AsParallel().First(y => y.Value == dic.Select(x => x.Value).Select(x => x.Max())).Key	0
12684783	12684213	Filter data from Xml according to date in C#	var userElement = xDox.Descendants("User")\n                .SingleOrDefault(u => u.Element("Name").Value == "David");\n\nif (userElement != null)\n{\n    var result = userElement.Descendants("Attempts")\n        .Select(a => new\n            {\n                Place = a.Element("Place").Value,\n                Date = DateTime.Parse(a.Element("Date").Value),\n                Distance = int.Parse(a.Element("Distance").Value)\n            })\n\n        .Where(a => a.Date >= DateTime.Parse("3/29/2012")\n                    && a.Date <= DateTime.Parse("8/29/2012"))\n\n        .GroupBy(a => a.Place)\n        .Select(g => new {Place = g.Key, Avg = g.Average(x => x.Distance)});\n}	0
15020291	15020233	How to replace characters in a string?	foreach (KeyValuePair<string, string> item in unwantedCharacters)\n{\n    fileContents = fileContents.Replace(item.Key, item.Value); \n}	0
7335789	7335629	Get DisplayAttribute attribute from PropertyInfo	var properties = typeof(SomeModel).GetProperties()\n    .Where(p => p.IsDefined(typeof(DisplayAttribute), false))\n    .Select(p => new\n        {\n            PropertyName = p.Name, p.GetCustomAttributes(typeof(DisplayAttribute),\n                false).Cast<DisplayAttribute>().Single().Name\n        });	0
2780743	2780295	How to set the PlayList Index for Mediaplayer(ExpressionMediaPlayer:Mediaplayer)	int currentPlayListItem = listBox.SelectedIndex;\ncustMediaElement.GoToPlaylistItem(currentPlayListItem);	0
6355090	6354923	C# reading a file and display in a table	string[] country = line.Split(token2);\nstring[] image = country[1].Split(token); //<- take string after = symbol, and split it\nstring row = "<tr><td>" + country[0] + "</td>" +"<table><tr>"; //<- take first string before = symbol	0
25416093	25416011	How do I access a Form's ComboBox selectedItem from a C# Program	SerialPort slavePort = new SerialPort(Convert.ToInt32(ComPortComboBox.SelectedText));	0
4953116	4953087	Determining the value of an object	Object a = 1;   // int\n    Object b = 2f;  // float\n    Object c = 3m;  // decimal\n\n    Response.Write(a.GetType() + ", " + b.GetType() + ", " + c.GetType());	0
31023395	31023312	How to create an array storing PictureBox names in C#	PictureBox[] diceloc = new PictureBox[] {pic1, pic2, pic3, pic4};	0
4094353	4094118	Trivia: How to convert a JSON2.org DateTime string to C# DateTime	var unixEpoch = DateTime(1970, 1, 1);\nvar ticksSinceEpoch = 1288296203190 * 10000;\nvar time = new DateTime(unixEpoch.Ticks + ticksSinceEpoch);	0
9977423	9944497	A table join in MVC application is being very slow	var loadoptions = new DataLoadOptions();\n        loadoptions.LoadWith<ReviewItem>(ri => ri.Review);\n        loadoptions.LoadWith<Review>(r => r.Student);\n        db.LoadOptions = loadoptions;	0
8521965	8521777	Swing and a miss LINQ to XML query	var vendors = rawData.Descendants(ns+"Vendor")\n                    .Select(x => new Vendor(x.Element(ns+"VendorId").Value,\n                                            x.Element(ns+"VendorName").Value))\n                    .ToList();	0
33937424	33937155	Return value from Task freez ui	Task<double> TestTask = Task.Factory.StartNew<double>(() =>\n        {\n            System.Threading.Thread.Sleep(10000);\n            return 0.5;\n        });\n        TestTask.ContinueWith(x =>\n        {\n             result = x.Result;\n            //do my stuff when its done\n\n        }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());	0
19815917	19815754	HashSet for unique characters	boolean[] array = new bolean[128];\n char c = 'a';\n array[(int) c] = true;	0
3581402	3581380	Can this be done without a regular expression?	preg_split("/\\s/", str);	0
3741865	3741824	What are the essential elements of a workflow?	public class Workflow\n{\n  internal IState Current { get; set; }\n\n  public void Start()\n  {\n     Current = new StartState();\n     Current.Start(this);\n  }\n\n  public void DoSomething()\n  {\n     Current.DoSomething(this);\n  }\n\n  public void DoSomethingElse()\n  {\n     Current.DoSomethingElse(this);\n  }\n}\n\npublic interface IState\n{\n  Start(Workflow context);\n  DoSomething(Workflow context);\n  DoSeomethingElse(Workflow context);\n}\n\npublic abstract BaseState : IState\n{\n  public virtual void Start(Workflow context)\n  {\n    throw new InvalidStateOperationException(); \n  }\n\n  public virtual void DoSomething(Workflow context)\n  {\n    throw new InvalidStateOperationException(); \n  }\n\n  public virtual void DoSomethingElse(Workflow context)\n  {\n    throw new InvalidStateOperationException(); \n  }\n}\n\npublic class StartState : BaseState\n{\n  public override void Start(Worklfow context)\n  {\n    // Do something\n    context.Current = new OtherState();\n  }\n}	0
1688031	1687502	C#: Decoupled comms between applications	\Programs\n    \Controller\n        bootstrapper.exe\n        \v1.0\n            controller.exe\n        \v1.1  <-- Current version\n            controller.exe	0
11903876	11903556	Regex - replace some html tag	(?:< *)(?!(?:br|hr)) *\w+ *\/ *\>	0
2898097	2898050	How to determine edges in an image optimally?	BitmapData bmd = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, b.PixelFormat);\n\nbyte* row = (byte*)bmd.Scan0 + (y * bmd.Stride);\n\n//                           Blue                    Green                   Red \nColor c = Color.FromArgb(row[x * pixelSize + 2], row[x * pixelSize + 1], row[x * pixelSize]);\n\nb.UnlockBits(bmd);	0
6096925	6089461	Remove Layers/Background from PDF in PHP/Bash/C#	using System;\nusing System.IO;\nusing System.Collections.Generic;\nusing iTextSharp.text;\nusing iTextSharp.text.pdf;\n\nnamespace LayerHide {\n\n    class MainClass\n    {\n        public static void Main (string[] args)\n        {\n\n            PdfReader reader = new PdfReader("test.pdf");\n            PdfStamper stamp = new PdfStamper(reader, new FileStream("test2.pdf", FileMode.Create));\n            Dictionary<string, PdfLayer> layers = stamp.GetPdfLayers();\n\n            foreach(KeyValuePair<string, PdfLayer> entry in layers )\n            {\n                PdfLayer layer = (PdfLayer)entry.Value;\n                layer.On = false;\n            }\n\n            stamp.Close();\n        }\n    }\n}	0
25687695	25687564	remove duplicated data in list C#?	public class ReportByProjectModel\n{\n        public string projectID { get; set; }\n        public int month { get; set; }\n        public int year { get; set; }\n        public string type { get; set; }\n\n    public override bool Equals(System.Object obj)\n    {\n        if (obj == null)\n        {\n            return false;\n        }\n\n        // If parameter is the wrong type then return false.\n        ReportByProjectModel p = obj as TwoDPoint;\n        if (p == null)\n        {\n            return false;\n        }\n\n        // Return true if the fields match:\n        return obj.projectID  == p.projectID\n           && obj.month == p.month \n           && obj.year == p.year\n           && obj.type == p.type;\n    }\n\n    public override int GetHashCode()\n    {\n        return string.Concat(projectID, "|", month, "|", year "|", type).GetHashCode();\n    }\n}	0
16314215	16211119	Windows Azure Cloud Service - Access to deployed xml file denied	public static T Deserialise(string settingsFile)\n    {\n        var fileContents = File.ReadAllText(settingsFile);\n        using (var fs = new MemoryStream(Encoding.ASCII.GetBytes(fileContents)))\n        {\n            var sr = new XmlSerializer(typeof (T));\n            var obj = (T) sr.Deserialize(fs);\n            fs.Close();\n            return obj;\n        }\n    }	0
8190148	8190083	insert datetime error	using (SqlCommand myCommand = new SqlCommand(\n    "INSERT INTO users (f_name, s_name, ...) VALUES (@f_name, @s_name, ...)")) {\n\n    myCommand.Parameters.AddWithValue("@f_name", f_name);\n    myCommand.Parameters.AddWithValue("@s_name", s_name);\n    //...\n\n    myConnection.Open();\n    myCommand.ExecuteNonQuery())\n    //...\n}	0
1179695	1179682	Need a little more help converting a CRC function from VB.NET to C#	if ((dwCrc & 1) != 0) ...	0
29746652	29746492	Is there a way to go back and add something to a line that's already been printed?	static void Main(string[] args)\n{\n    for (var i = 0; i < 5; i++)\n    {\n        Console.WriteLine("1,2,3,4,5");\n    }\n    Console.SetCursorPosition(10, 0);\n    Console.Write("you got x predictions correct here");\n    Console.ReadKey();\n}	0
29945696	29943003	Inheriting from an interface with properties of the same name	public partial class SearchedProductInternal : IProduct\n    {\n\n        public string ID\n        {\n            get { return ObjectIdField.ToString(); }\n        }\n        public string Name  {get;set;}\n\n        public string DescriptionShort{get { return shortDescriptionField; }\n        }\n\n        public string DescriptionLong {get { return longDescriptionField; }\n        }	0
11371091	11369693	Entity Framework Create Database & Tables At Runtime	//create the database\ndb.CreateDatabase();\n//grab the script to create the tables\nstring createScript = db.CreateDatabaseScript();\n//execute the script on the database\ndb.ExecuteStoreCommand(createScript);	0
16905658	16905584	Catch 'cannot open database' exception for a database and switch database	SqlConnection conn = null;\ntry\n{\n    conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PrimaryDatabase"].ConnectionString);\n    conn.Open();\n    // do stuff\n    conn.Close();\n}\ncatch (SqlException ex)\n{\n    try \n    {\n        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BackupDatabase"].ConnectionString);\n        conn.Open();\n        // do stuff\n        conn.Close();\n    }\n    catch\n    {\n        // log or handle error\n    }\n}	0
11532279	11532042	How to query related objects with nhibernate using contains	public IList<Ad> Search(string query)\n    {\n        return unitOfWork.Session\n            .CreateCriteria<Ad>()\n            .CreateAlias("Properties", "props")\n            .Add(Expression.InsensitiveLike("props.Value", query, MatchMode.Anywhere))\n            .List<Ad>();\n    }	0
10953283	9789737	Dapper and Oracle CRUD issues, how to?	var param = new DynamicParameters();\n\nparam.Add(name: "Cli", value: model.Cli, direction: ParameterDirection.Input);\nparam.Add(name: "PlayerAnswer", value: model.PlayerAnswer, direction: ParameterDirection.Input);\nparam.Add(name: "InsertDate", value: model.InsertDate, direction: ParameterDirection.Input);\nparam.Add(name: "Id", dbType: DbType.Int32, direction: ParameterDirection.Output);\n\nusing (IDbConnection ctx = DbConnectionProvider.Instance.Connection)\n{\n    ctx.Execute("INSERT INTO PLAYER_LOG (CLI, ANSWER, INSERT_DATE) VALUES (:Cli, :PlayerAnswer, :InsertDate) returning Id into :Id", paramList);\n}\n\nvar Id = param.get<int>("Id");	0
11607890	11607765	casting data split to integer	Bitmap abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_00.gif");\nif (berjaya[23].Equals(70)) \n{\n\n    abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");                    \n\n}\n\nmyPicturebox.Image = abc;	0
9375542	9375494	Remove elements from stackpanel	if (stackPanelAdd.Children.Count>0)\n{\n  stackPanelAdd.Children.RemoveAt(stackPanelAdd.Children.Count-1);\n}	0
5957140	5957080	How can I add a listView column header a click event programmatically	listView.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(Header_Click));	0
994470	994459	Getting unicode string from its code - C#	string codePoint = "0D15";\n\nint code = int.Parse(codePoint, System.Globalization.NumberStyles.HexNumber);\nstring unicodeString = char.ConvertFromUtf32(code);\n// unicodeString = "???"	0
18434079	18434051	Many FileStream's attached to one file	var fs1 = new FileStream("test.mkv", FileMode.Open, FileAccess.Read, FileShare.Read);\nvar fs2 = new FileStream("test.mkv", FileMode.Open, FileAccess.Read, FileShare.Read);	0
16050600	16048885	How to convert IntPtr to Cursor or SafeHandle?	class SafeCursorHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid {\n    public SafeCursorHandle(IntPtr handle) : base(true) {\n        base.SetHandle(handle);\n    }\n    protected override bool ReleaseHandle() {\n        if (!this.IsInvalid) {\n            if (!DestroyCursor(this.handle))\n                throw new System.ComponentModel.Win32Exception();\n            this.handle = IntPtr.Zero;\n        }\n        return true;\n    }\n    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]\n    private static extern bool DestroyCursor(IntPtr handle);\n}	0
7089147	7078054	Coding to make a SQL table from an InfoPath 2003 form without knowing the fields in advance	[WebMethod]\npublic void CreateTable(string infoPathData)\n{\n    var doc = new XmlDocument();\n    doc.LoadXml(infoPathData);\n\n    //gets the namespace uri - it is unique for each form\n    string nsUri = doc.ChildNodes[3].Attributes["xmlns:my"].Value;\n\n    var nsManager = new XmlNamespaceManager(doc.NameTable);\n    nsManager.AddNamespace("my", nsUri);\n\n    //select the myField node\n    var root = doc.SelectSingleNode("my:myFields", nsManager);\n\n    var sqlStatement = new StringBuilder();\n    sqlStatement.Append("CREATE TABLE ....");\n\n    foreach (XmlNode n in root.ChildNodes)\n    {\n        //n.Name - gets the name of the node (incl. NS)\n        //n.InnerText - gets the field value \n\n        //append to sqlStatement\n    }\n\n    //execute sql statement ...\n}	0
7847915	7834939	Dynamically add values to List<double> using get & set	public class ITestData\n{\n    public string pinName { get; set; } //Name of the pin\n    public double stressLevel { get; set; } //Stress level for latchup\n    public int psuCount { get; set;} //Number of PSU's \n\n    public List<double[]> preTrigger = new List<double[]>();\n    public List<double[]> inTrigger = new List<double[]>();\n    public List<double[]> postTrigger = new List<double[]>();\n\n\n    public void AddPreTrigger(double volt, double curr)\n    {\n        double[] data = new double[2];\n        data[0] = volt;\n        data[1] = curr;\n        preTrigger.Add(data);\n    }\n\n    public void AddInTrigger(double volt, double curr)\n    {\n        double[] data = new double[2];\n        data[0] = volt;\n        data[1] = curr;\n        inTrigger.Add(data);\n    }\n\n    public void AddPostTrigger(double volt, double curr)\n    {\n        double[] data = new double[2];\n        data[0] = volt;\n        data[1] = curr;\n        postTrigger.Add(data);\n    }\n}	0
1382531	1382515	how can read values and put them in Array C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      int[] arr = new int[3];\n      int i;\n      for (i = 0; i < 3; i++)\n      {\n        arr[i] = Convert.ToInt32(Console.ReadLine());\n      }\n      for (int k = 0; k < 3; k++)\n      {\n        Console.WriteLine(arr[k]);\n      }\n\n      Console.ReadKey();\n    }\n\n  }\n\n}	0
1013284	1013244	Converting GUID to String via Reflection	guid.ToString();	0
11017110	10903668	Show several tooltips at the same time (DevExpress)	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    { if ((msg.Msg == WM_KEYDOWN) && ModifierKeys == Keys.Control && !_isKeyDown)\n        {\n            _isKeyDown = true;\n            ShowShortCutToolTips();\n            this.Focus();\n            return true;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n   protected override void OnKeyUp(KeyEventArgs e)\n    {\n        base.OnKeyUp(e);\n        if(e.KeyValue == 17 || e.Control) // 17 = Control Key\n        {\n            _isKeyDown = false;\n            HideShortCutToolTips();\n        }\n    }	0
4387842	4387827	Linq to SQL - Multiple where clasues at runtime	if (!string.IsNullOrEmpty(reference))\n        query = query.Where(tb => tb.Reference = reference));	0
21291115	21288053	Hide a Column from ColumnChooser	column1.OptionsColumn.ShowInCustomizationForm = false;	0
23499809	23488543	Drawing quads with shaders and VBO	-0.095f, 0.0475f, 0.695f,\n           -0.095f, 0.00475f, 0.7455f,	0
1021251	1020612	Getting Images and bindingSource.Filter working together in a DataGridView	public class MyType\n{\n    public string Name { get; set; }\n    public Image Image { get; set; }\n}\n...\n[STAThread]\nstatic void Main()\n{\n    List<MyType> list = new List<MyType>();\n    list.Add(new MyType { Image=Bitmap.FromFile(image1Path), Name="Fred" });\n    list.Add(new MyType { Image=Bitmap.FromFile(image2Path), Name="Barney" });\n\n    DataTable table = list.ToDataTable();\n    BindingSource bs = new BindingSource(table, "");\n    bs.Filter = @"Name = 'Fred'";\n    Application.Run(new Form {\n        Controls = {\n            new DataGridView {\n                DataSource = bs,\n                Dock = DockStyle.Fill}\n        }\n    });\n}	0
14238056	14237609	Assert that all members of an array are equivalent using LINQ?	var leftHandSide = inputSequence.First();\nvar rightHandSideList = inputSequence.Skip(1);\n\nrightHandSideList.All(s => s.SequenceEqual(leftHandSide));	0
8897141	8897052	Using Viewbag data with a HTMLHelper MVC3. - Cannot be dynamically dispatched	public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(\n    this HtmlHelper<TModel> htmlHelper,\n    TypeOfYourEnum value\n)	0
9404279	9300531	TextWrapping textbox in WPF DataGrid	DataGridTextColumn l_column = new DataGridTextColumn();\nl_column.Header = l_columnName;\nl_column.Binding = new Binding(l_columnName);\nl_column.Width = l_iWidth;\n\nStyle l_textStyle = new Style(typeof(TextBlock));\nl_textStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));\nl_column.ElementStyle = l_textStyle;\nStyle l_textEditStyle = new Style(typeof(TextBox));\nl_textEditStyle.Setters.Add(new Setter(TextBox.TextWrappingProperty, TextWrapping.Wrap));\nl_column.EditingElementStyle = l_textEditStyle;\n\ndataGrid.Columns.Add(l_column);	0
6522860	6521853	Optimizing the property getter for a ValueType	int sizeInBytes;\nunsafe\n{\n    sizeInBytes = sizeof(DateTime);\n}	0
771813	771652	Is there a quick way to format an XmlDocument for display in C#?	public static class FormatXML\n{\n    public static string FormatXMLString(string sUnformattedXML)\n    {\n        XmlDocument xd = new XmlDocument();\n        xd.LoadXml(sUnformattedXML);\n        StringBuilder sb = new StringBuilder();\n        StringWriter sw = new StringWriter(sb);\n        XmlTextWriter xtw = null;\n        try\n        {\n            xtw = new XmlTextWriter(sw);\n            xtw.Formatting = Formatting.Indented;\n            xd.WriteTo(xtw);\n        }\n        finally\n        {\n            if(xtw!=null)\n                xtw.Close();\n        }\n        return sb.ToString();\n    }\n}	0
11645676	11525419	Using C# datetime in SQL where statement	string sqlStr = "SELECT * FROM View_AllJobDetails WHERE UpdatedDateStaff >= " + string.Format("{0:dd-MMM-yyyy}",lastlogged);	0
18517494	18516560	Accessing arrays dynamically	var arr1 = new int[] { 0, 1, 2, 3 };\n    var arr2 = new int[] { 0, 1, 2, 3 };\n    var arr3 = new int[] { 0, 1, 2, 3 };\n\n    var _root = new Dictionary<string, int[]>();\n    _root.Add("arr1", arr1);\n    _root.Add("arr2", arr2);\n    _root.Add("arr3", arr3);\n\n    for (int i = 1; i <= 3; i++)\n    {\n      int arrElem = _root["arr" + i][0];\n    }	0
33551291	33550091	Set value in Parent Page from Modal Popup Extender	//......\n   //.......\n\n   <ajaxToolkit:ModalPopupExtender runat="server" \n        TargetControlID="BtnOpenPopup" \n        EnableViewState="true" \n        OkControlID="BtnSubmit" \n        PopupControlID="PnlTest" \n        OnOkScript="onModalOk();"> <!-- here is the tag you have to add to get it work -->\n\n    </ajaxToolkit:ModalPopupExtender>\n  </div>\n</form>\n<script>\n    function onModalOk()\n    {\n        document.getElementById("lbl").innerText = document.getElementById('txtInput').value;\n    }\n</script>	0
9706198	9705955	How to mask string?	string result = Int64.Parse(s.Remove(5,2)).ToString("00-000-000000");	0
8945746	8945729	Get "Redirected from" URL	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        string referrer = Request.UrlReferrer;\n        // TODO: do something with the referrer\n    }\n}	0
34222593	34220558	delete some row based on cell value before importing to datagridview using c#	private void button1_Click_1(object sender, EventArgs e)\n{\n    String name = "Gemeinden_31.12.2011_Vergleich";\n    String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +\n                   @"C:\C# tutorial Backup\Zensus_Gemeinden_org.xlsx" +\n                   ";Extended Properties='Excel 12.0 XML;HDR=YES;';";\n\n    OleDbConnection con = new OleDbConnection(constr);\n    OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$D8:E11300] Where [population number] > 10000", con);\n    con.Open();\n\n    OleDbDataAdapter sda = new OleDbDataAdapter(oconn);\n    DataTable data = new DataTable();\n    sda.Fill(data);\n    dataGridView1.DataSource = data;\n    }	0
17814936	17814848	C# convert List into Branch	WebBrowseNode lastNode = null;\nfor (int numItem = list.Count - 1; numItem >= 0; numItem--)  // Go from the end to the beginning of the list\n{\n    string title = myStringList[numItem];\n\n    lastNode = new WebBrowseNode\n    {\n        Title = title,\n        Children = { lastNode }                              // Adds lastNode to the Children list\n    };\n}\n\nWebBrowseNode root = lastNode;	0
1758487	1236805	Cannot convert object, recieved from ajax call, into a long	Convert.ToInt64(((string[])id)[0])	0
15649043	15649025	How to exit a Windows Forms Application in C#	private void Defeat()\n{\n    MessageBox.Show("Goodbye");\n    Application.Exit();\n}	0
5960818	5960669	validate search result using Linq	var result = from orderLines in context.OrderLineSearch(searchTerm)\n             group orderLines by orderLines.OrderNumber into g   \n             select g.Key     \nbool hasElements = result.Any();	0
21931976	21930823	Calculate how much to Pan/Tilt image	// Calculate Pan\ndouble finalPan = Pan * widthPercent;\nif ((finalPan + zoomX) >= width)\n{\n    finalPan = width - zoomX;\n}\n\n// Calculate Tilt\ndouble finalTilt = Tilt * heightPercent;\nif ((finalTilt + zoomY) >= height)\n{\n    finalTilt = height - zoomY;\n}	0
15602198	15599654	How to create a file from System.IO.Stream in metro apps?	var client = new HttpClient();\nvar response = await client.GetAsync(uri);\nif (response.IsSuccessStatusCode)\n{\n    Stream stream = null;\n    StorageFolder localFolder = ApplicationData.Current.TemporaryFolder;\n    StorageFile file = await localFolder.CreateFileAsync("savename.htm",\n        CreationCollisionOption.ReplaceExisting);\n    stream = await file.OpenStreamForWriteAsync();\n\n    await response.Content.CopyToAsync(stream);	0
24844555	24844040	Select unique random rows from SQL Server table but always duplicates	INSERT INTO f_TWinGet\nSELECT TOP 1 j.Char, j.Serv, j.Random\nFROM dbo.just j \nLEFT JOIN f_TWinGet f\nON f.Char = j.Char\nAND j.Serv = f.Serv\nAND j.Random = f.Random\nWHERE f.Char IS NULL\nORDER BY NEWID()	0
5431999	5380434	WCF Data Service - iOS oData SDK Issues	[WebGet(ResponseFormat = WebMessageFormat.Json)] \npublic static void InitializeService(DataServiceConfiguration config)     { \n    config.SetEntitySetAccessRule("*", EntitySetRights.All);   \n    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); \n    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;\n }	0
1137928	1137905	get postback trigger	string postbackControlName = Request.Params.Get("__EVENTTARGET");	0
2503833	2493244	WPF to XPS in landscape orientation	// hard coded for A4\nfixedPage.Width = 11.69 * 96;\nfixedPage.Height = 8.27 * 96;	0
11102983	11102901	Get stack trace for C# app crashing on non-dev machine	try\n        {\n            //Your code\n        }\n        catch (Exception ex)\n        {\n            //Log info to a file in same directory\n        }	0
27653086	27652582	How can i split date and time separate?	DateTime dtValue;  // load your date & time into this variable\nTextBox1.Text = dtValue.ToString("yyyy-MM-dd");\nTextBox2.Text = dtValue.ToString("HH:mm:ss");	0
34399855	34399563	ASP.NET Chart with DataBindCrossTable	MONTH    Status    Count\nOctober  Lost      2\nOctober  Stolen    0\nOctober  Found     0\nNovember Stolen    1\nNovember Lost      1\nNovember Found     1\nDecember Stolen    1\nDecember Lost      0\nDecember Found     0	0
7568182	7568147	Compare version numbers without using split function	static class Program\n{\n    static void Main()\n    {\n        string v1 = "1.23.56.1487";\n        string v2 = "1.24.55.487";\n\n        var version1 = new Version(v1);\n        var version2 = new Version(v2);\n\n        var result = version1.CompareTo(version2);\n        if (result > 0)\n            Console.WriteLine("version1 is greater");\n        else if (result < 0)\n            Console.WriteLine("version2 is greater");\n        else\n            Console.WriteLine("versions are equal");\n        return;\n\n    }\n}	0
31939388	31939160	Avoid Lamda expression with multiple where clause	var filteredList = myList.where(x=> (conditions1(x)) || (condition2(x))).toList();\n\nif (filteredList.count == 0)\n    filteredList = myList;	0
1217674	1217671	How do I make my code perform a random function	private static Random r = new Random();\n\nprivate void BackPack() {\n    int i = r.Next(0,3);\n    Player.Skin.SetComponent((PedComponent)3, 3, i); \n}	0
27780134	27778804	Format of the initialization string does not conform to specification starting at index 129	"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=yes\";";	0
32869338	32867629	How to get a proper date from a text?	\b((?<day>[0-2]?\d|3[01]) )?January(?(day)| ([0-2]?\d|3[01]))\b	0
7815455	7815235	Date range falling between two dates in a LINQ query	return (from t1 in db.Appointments where (date1 >= t1.AppointmentStart && date2 <= t1.AppointmentEnd))	0
25781742	25720259	How to forget authorization credentials?	[Authorize(Roles=@"DOMAIN\APP-ResetToUser")]\npublic string ResetUser()\n{\n    return "Active user: " + User.Identity.Name;\n}	0
15794252	15794214	Traversing a binary tree	Node<T>	0
1537860	1537823	How can I ask Windows to print a document?	ShellExecute(my_window_handle, "print", path_to_file, NULL, NULL, SW_SHOW);	0
33502236	33500621	Adding space after datagridview column is appending txt to txt file	Clipboard.GetText(TextDataFormat.Text) + "\t" + DateTime.Now + Environment.NewLine	0
15116132	14795846	How convert some value to json by Newtonsoft?	foreach (DataRow row in table.Rows)\n            {\n                jsonWriter.WriteStartObject();\n                foreach (DataColumn col in table.Columns)\n                {\n                    jsonWriter.WritePropertyName(col.ColumnName);\n                    jsonWriter.WriteValue((row[col.ColumnName] == null) ? string.Empty : row[col.ColumnName].ToString());\n                }\n                jsonWriter.WriteEndObject();\n            }	0
13395310	13395269	Filter out alphabetic with regex using C#	void Main()\n{\n    var str = "some junk456456%^&%*333";\n    Console.WriteLine(Regex.Replace(str, "[a-zA-Z]", ""));\n}	0
25512352	25502875	Disable scrolling phone:webbrowser windows phone 8 / 8.1	\-WebBrowser\n     \-Border\n      \-Border\n       \WebBrowserInteropCanvas (New in Windows Phone 8, missing in WP7)\n        \-PanZoomContainer\n         \-Grid\n          \-Border (you need access this one)\n           \-ContentPresenter\n            \-TileHost	0
7516131	7514874	How to remove programmatically the security protection of a copied file in network directory?	yourfile.exe:Zone.Identifier	0
10828203	10828113	Fastest Way to Add Character at First, End and Between of each string in List of string	string result = string.Join(", ", elements.Select(e => "'" + e + "'"));	0
3852496	3852427	How can I get X, Y positions of mouse relative to form even when clicking on another control?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        foreach (Control c in this.Controls)\n        {\n            c.MouseDown += ShowMouseDown;    \n        }\n\n        this.MouseDown += (s, e) => { this.label1.Text = e.X + " " + e.Y; };\n\n    }\n\n    private void ShowMouseDown(object sender, MouseEventArgs e)\n    {\n        var x = e.X + ((Control)sender).Left;\n        var y = e.Y + ((Control)sender).Top;\n\n        this.label1.Text = x + " " + y;\n    }\n}	0
12288460	12250815	How to manage association in my entity model?	Include()	0
32075445	32074615	cannot add items to ContextMenuStrip on inherited winform	contextMenuStrip1.Items.Add(myAddedMenuStripItem);	0
6432182	6432120	c#: How do I run multiple windows services as one service?	Process.Start(..)	0
23853149	23852558	Named pipe client unable to connect to server running as Network Service	PipeSecurity pipeSa = new PipeSecurity(); \n    pipeSa.SetAccessRule(new PipeAccessRule("Everyone", \n                    PipeAccessRights.ReadWrite, AccessControlType.Allow)); \n    listeningPipe.SetAccessControl(pipeSa);	0
4410397	4361561	How can I use the Facebook C# SDK to post on Facebook Pages	FacebookApp fbApp = new FacebookApp();\nFacebookApp app = new FacebookApp(fbApp.Session.AccessToken);\nvar args = new Dictionary<string, object>();\nargs["message"] = "abc";\nargs["caption"] = "This is caption!";\nargs["description"] = "This is description!";\nargs["name"] = "This is name!";\nargs["picture"] = "[your image URL]";\nargs["link"] = "[your link URL]";\n\napp.Api("/me/feed", args, HttpMethod.Post);	0
31635693	31634471	How do I change one image to another upon clicking on a button	private void pictureBox1_Click(object sender, EventArgs e)\n{\n      if (flag)\n           pictureBox1.Image = WindowsFormsApplication21.Properties.Resources.GRAYSCALEsmalltub;\n      else\n           pictureBox1.Image = WindowsFormsApplication21.Properties.Resources.smalltub;\n      flag=!flag;\n}	0
3848281	3848162	How do I parse a polymorphic JSON array?	JArray root = JArray.Load(reader);\nforeach(JObject o in root)\n{\n    ct += "\r\n\r\n<tr><td>" + (string)o["fullName"] + "</td>";\n    ct += "<td>" + (string)o["contributorName"] + "</td>";\n    ct += "<td>" + (string)o["email"] + "</td>";\n}	0
15274149	15272697	Razor view capture RadioButtonFor with enum source	Visibility.VisibilityLevel _vizibility;\n\n    public Visibility.VisibilityLevel Visibility{\n        get {\n            if (_vizibility != Models.Visibility.VisibilityLevel.ShowThis)  //the default\n                return _hide_data;\n            var ans =  new MacDirectEntities()\n            ...\n            return ans.Visibility;\n        }\n        set {\n            _vizibility= value;\n        }\n    }\n}	0
31920678	31920218	showdialog closing from another thread	_prompt.Invoke((MethodInvoker)delegate\n{\n    _prompt.Close();\n});	0
22973040	22973017	How to display array items horizontally in a list box with C#?	listbox1.Items.Add(string.Format("The check array contents are: {0}", string.Join(" ", streamArray)));	0
22702837	22700676	Entity Framework conversion of data type (Data mapping)	var parsingService = new ParsingService(tb.Get("me"));\nvar model = parsingService.GetModel();	0
24831869	24831680	How to remove a LinkLabel as a tab stop when using .NET 3.5?	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        linkLabel1.TabStop = false;\n    }\n    // etc..\n}	0
4096427	4096405	how to prevent class 'a' from being inherited by another class?	java: final  \nvb: NotInheritable (NonOverrideable for properties)\nc#: sealed	0
23733391	23733346	c# How to convert Object to XML	var writer = new StringWriter();\nvar serializer = new XmlSerializer(typeof(YourData));\nserializer.Serialize(writer, obj);\nstring xml = writer.ToString();	0
1592691	1592656	checkboxes in repeater	if (!Page.IsPostBack)\n    {\n        rpt.DataSourceID = "";\n        rpt.DataBind();\n    }	0
15862765	15859642	PixelFormat convertation trouble	img = new UnmanagedImage(..., img.Stride, PixelFormat.Format8bppIndexed);	0
2431771	2431744	LINQ: How to skip one then take the rest of a sequence	foreach (var item in list.Skip(1))	0
20487999	20487948	MS SQL SERVER 2008r2 connection with Visual studio 2012	SqlConnection con = new SqlConnection(@"Data source=BIMESH-PC\SQLEXPRESS;initial catalog=LibrSystem;integrated security=true");\nSqlConnection con = new SqlConnection("Data source=BIMESH-PC\\SQLEXPRESS;initial catalog=LibrSystem;integrated security=true");	0
3390566	3390517	Map two values to one object	Color[,] colors = new[,] {\n    { Color.FromArgb(1, 2, 3), Color.FromArgb(3, 4, 5), Color.FromArgb(6, 7, 8), Color.FromArgb(9, 10, 11) },\n    { Color.FromArgb(21, 22, 23), Color.FromArgb(23, 24, 25), Color.FromArgb(26, 27, 28), Color.FromArgb(29, 30, 31) },\n};\n\nColor color = colors[index1, index2];	0
26884209	26884005	Compress or Zip a File - Windows Phone Universal Apps - C#	//The UploadFile and SyncroZipFile are StorageFile's.\nusing (Stream StreamToUploadFile = await UploadFile.OpenStreamForWriteAsync())\n{\n    using (Stream StreamToSyncroZipFile = await SyncroZipFile.OpenStreamForWriteAsync())\n    {\n        using (ZipArchive UploadFileCompressed = new ZipArchive(StreamToSyncroZipFile, ZipArchiveMode.Update))\n        {\n            ZipArchiveEntry NewZipEntry = UploadFileCompressed.CreateEntry(UploadFileName);\n\n            using (Stream SWriter = NewZipEntry.Open())\n            {\n                 await StreamToUploadFile.CopyToAsync(SWriter);\n            }\n        }\n    }\n}	0
1707073	1706903	IntPtr addition	//-2147483645\nConsole.WriteLine( int.MaxValue + 4 );\n\n//2147483651\nConsole.WriteLine( (uint)(int.MaxValue + 4) );	0
15437658	15437615	At which point in a web application can I call one method only once every 24 hours?	recurring background tasks in ASP.NET applications	0
23333185	23333091	how to open only one window in c# winform	using System.Threading;\n\n[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\n/// <summary>\n/// The main entry point for the application.\n/// </summary>\n[STAThread]\nstatic void Main()\n{\n   bool createdNew = true;\n   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))\n   {\n      if (createdNew)\n      {\n         Application.EnableVisualStyles();\n         Application.SetCompatibleTextRenderingDefault(false);\n         Application.Run(new MainForm());\n      }\n      else\n      {\n         Process current = Process.GetCurrentProcess();\n         foreach (Process process in Process.GetProcessesByName(current.ProcessName))\n         {\n            if (process.Id != current.Id)\n            {\n               SetForegroundWindow(process.MainWindowHandle);\n               break;\n            }\n         }\n      }\n   }\n}	0
14683575	14546828	Deployment of Entity Framework application using SQL server 2012	SQLEXPR_x86_ENU /ACTION=Install /FEATURES=SQLENGINE /INSTANCENAME=SQLEXPRESS /SQLSVCACCOUNT="NT AUTHORITY\SYSTEM" /AGTSVCACCOUNT="NT AUTHORITY\LOCAL Service" /SQLSVCSTARTUPTYPE=Automatic /BROWSERSVCSTARTUPTYPE=Automatic /TCPENABLED=1  /NPENABLED=1 /ADDCURRENTUSERASSQLADMIN	0
14579343	14579177	Treat a string as code in C#	db.Set<TEntity>().Find(id)	0
34053147	34052919	Using inherited interfaces in interface implementations in C#	interface IShelter<T> where T : IAnimal\n    {\n        void Store(T animal);\n    }\n    class DogShelter : IShelter<IDog>\n    {\n        public void Store(IDog animal)\n        {\n            throw new NotImplementedException();\n        }\n    }\n    class CatShelter : IShelter<ICat>\n    {\n        public void Store(ICat animal)\n        {\n            throw new NotImplementedException();\n        }\n    }	0
29856232	29855809	Raw request body to string array	var x = HttpUtility.UrlDecode("%5B%228124318066%22%2C%223869383310%22%2C%229417395507%22%5D");	0
4390615	4390300	How to make a floating control	MyForm form = new MyForm();\nform.Location = PointToScreen(new Point(e.X, e.Y));\nform.Show();	0
9674349	9674279	create a case statement in Controller to open up the correct View	public ActionResult Test(int id){\n switch(id){\n  case 1:\n    return View("view1");\n  case 2:\n    return View("view2");\n  case 3:\n    return View("view3");\n\n  }\n\n}	0
1578216	1577972	UserControl with Child Controls passed into a Repeater within the UserControl	[ParseChildren(true)]\n[PersistChildren(false)]	0
4974250	4974139	Attaching validation to EF objects used in MVC controllers/views?	[MetadataType(typeof(EFGeneratedClass_MetaData))]\npublic partial class EFGeneratedClass\n{\n}\n\npublic partial class EFGeneratedClass_MetaData\n{\n    [Required]\n    [Display(Name="Member1 Display")]\n    public string Member1 {get; set;}\n}	0
17665719	17665673	Undesired result from SQL query in C# console application	AccountTotal += CalculateIncome();	0
9381664	9369305	DirectoryEntry string working as literal but not as formatted string?	string cn = "Jeremy Stafford";\n  String group = "IT";\n  string ou = "QGT";\n  String domain1 = "QGT";\n  string domain2 = "Local";\n  string ldapFormatted = string.Format("LDAP://CN={0}, OU={1}, OU={2}, DC={3}, DC={4}", cn, group, ou, domain1, domain2);\n\n  var ldapHardCoded = @"LDAP://CN=Jeremy Stafford, OU=IT, OU=QGT, DC=QGT, DC=Local";\n  string message;\n\n  if (ldapFormatted.Equals(ldapHardCoded))\n  {\n    message = "They're the same value\n";\n  }\n  else\n  {\n    message = "Strings are not the same value\n";\n  }\n\n  if (ldapFormatted.GetType() == ldapHardCoded.GetType())\n  {\n    message += "They are the same type";\n  }\n  else\n  {\n    message += "They are not the same type";\n  }\n  message += "\n\n" + ldapFormatted + "\n" + ldapHardCoded;\n  MessageBox.Show(message);	0
34398787	34398478	How can i tell the StreamWriter when writing whats in the textBox1 to separate each string after a ,?	private void button1_Click(object sender, EventArgs e)\n    {\n        string[] cmdTextParts = textBox1.Text.Split(',');\n        foreach (string item in cmdTextParts)\n        {\n            cmdStreamWriter.WriteLine(item);\n        }\n    }	0
4799200	4799108	Consolidate/Merge data from TWO IEnumerable Lists into ONE	var query = from pricing in cargoSuppliers_Pricing\n            join content in cargoSuppliers_Content\n            on pricing.SupplierCode equals content.SupplierCode\n            select new CargoSupplier\n            {\n                // Copy properties from both objects here\n            };	0
5372613	5372600	C# "Constant Objects" to use as default parameters	public void doSomething(SettingsClass settings = null)\n{\n    settings = settings ?? DefaultSettings;\n    ...\n}	0
19615908	19615824	Deleting text from text file	var query = File.ReadLines("input.txt")\n    .Where(x => char.IsDigit(x.FirstOrDefault()))\n    .Select(x => string.Join("", x.TakeWhile(char.IsDigit)));\n\nFile.WriteAllLines("output.txt", query);	0
33006432	33006217	What character set to use on GSM modem	AT+CSCS=?	0
6817705	6817395	How to move control in panel by mouse	bool state = false;\nPoint prePoint;\n\nprivate void btn_MouseMove(object sender, MouseEventArgs e)\n{\nif (state)\n{\n    Point p = e.GetPosition(this);\n    Point p2 = e.GetPosition(btn);\n    btn.Margin = new Thickness(0, p.Y - p2.Y + p.Y - prePoint.Y, 0, 0);\n    prePoint = e.GetPosition(this);\n    // Capture Mouse here ! as far as i think. !!!\n    Mouse.Capture(this.ColorPlane, CaptureMode.Element);\n}\nelse\n{\n    // Release Mouse here ! as far as i think. !!!\n    Mouse.Capture(null);\n}\n}	0
17500668	17500412	How to execute any .exe by using a batch file if folder name contains spaces	start "" /b "C:\Users\bvino_000\Documents\Visual Studio 2010\Projects\RapidLoadToolV2\RapidLoadToolV2\bin\Debug\RapidLoadToolV2.exe"	0
23135330	23134633	How to detect photoresult orientation?	if (bitmap.PixelHeight > bitmap.PixelWidth) {\n     // portrait \n} else {\n     // landscape \n}	0
6212100	6212091	C#: how to handle floats properly	return ((value / 120.0) * 1440).ToString();	0
12371134	12370996	want to have multiple rows .net table	/adding first row\nTableRow row1 = new TableRow();\n\n//adding first cell\nTableCell cell1 = new TableCell();\n\n//adding label\nLabel text1 = new Label();\ntext1.Text = "Just test";\n\ncell1.Controls.Add(text1);\nrow1.Controls.Add(cell1);\ntable1.Controls.Add(row1);	0
7148448	7148400	add 0 before number if < 10	if ( Convert.ToInt32(Unreadz) < 10 ) port.Write("0" + Unreadz);\nelse port.Write("" + Unreadz);	0
15156279	15156215	Listbox item in foreach Condition	public void checkStock()\n    {\n        foreach (var listBoxItem in listBox1.Items)\n        {\n            // use the currently iterated list box item\n            MessageBox.Show(string.Format("{0} is not in stock!",listBoxItem.ToString()));\n\n        }\n    }	0
10426537	10420752	Timer and close an application	public System.Timers.Timer MyTimer { get; set; }\n    int counter;\n\n    public Form2_Load()\n    {\n        MyTimer = new System.Timers.Timer();\n        MyTimer.Interval = 1000;\n        MyTimer.Elapsed+=new System.Timers.ElapsedEventHandler(myTimer_Elapsed);\n        MyTimer.Start();\n    }\n\n    void  myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n    {\n        if (++counter == 30)\n        {\n            //do pic\n            this.Close();\n        }\n    }	0
5399526	5389525	Converting XElement into XmlNode	XElement xE = XElement.Parse("<Outer><Inner><Data /></Inner></Outer>");\n\n    XmlDocument xD = new XmlDocument();\n    xD.LoadXml(xE.ToString());\n    XmlNode xN = xD.FirstChild;\n\n    XElement xE2 = XElement.Parse(xN.OuterXml);	0
31370014	31369957	How to prevent the output of last comma character in line when writting to file	for (int i = 0; i < colonne; i++)\n{\n    for (int y = 0; y < righe; y++)\n    {\n        tw.Write(matrice[y, i]); \n\n        if (y < righe - 1)\n            tw.Write(",");\n    }\n\n    tw.WriteLine();\n}	0
34458950	34458898	How to alter a single property when fetching a set of objects with EF?	IEnumerable<Account> accounts = context.Accounts;\naccounts.Foreach(account => { account.Number = Guid.Empty; });\nreturn accounts;	0
10122350	10121061	Finding objects which contains at least all elements from subset using RavenDB and LINQ	var q = session.Query<Question>();\nforeach(var tag in tags)\n{\n    var currentTag = tag;\n    q = q.Where(x=>x.Tags.Any(xTag=>xTag == currentTag));\n}	0
17839682	17826536	How to check whether a textbox is present in a webpage or not using watin	bool isThere = browser.TextField(Find.ById("textbox1")).Exists;	0
1750412	1750054	How do I implement a datatable "group by"?	DataTable t = //\nvar groups = t.AsEnumerable()\n    .GroupBy(r => r.Field<T>("columnName"))	0
2417453	2417285	C# How to cast a strong datatype?	using ClassLibrary	0
9132196	9125791	facebook c# sdk how to post to user's wall as application from wp7	app.PostAsync("friendId/feed", parameters, fbCB);	0
33091528	32962476	Sending MHT file using C# Mail Message	MimeMessage messageMimeKit = MimeMessage.Load(Request.MapPath("~/Blah/378921.mht"));\n\n   messageMimeKit.From.Add(new MailboxAddress("Dev", "developer@gmail.com"));\n   messageMimeKit.To.Add(new MailboxAddress("Homer", "homer@gmail.com"));\n   messageMimeKit.Subject = "Another subject line";\n   using (var client = new MailKit.Net.Smtp.SmtpClient()) \n   {\n      client.Connect("smtp.gmail.com", 465, true);\n      client.Authenticate("homer@gmail.com", "*****");\n      client.Send(messageMimeKit);\n      client.Disconnect(true);\n   }	0
11028866	11028506	C#: How to go through dictionary items without exposing dictionary as public?	public IEnumerable<KeyValuePair<string, object>> CacheItems\n{\n    get\n    { // we are not exposing the raw dictionary now\n        foreach(var item in cacheItems) yield return item;\n    }\n}\npublic object this[string key] { get { return cacheItems[key]; } }	0
26772796	26772059	Sending Host name, Login Id & password dynamically to Putty using C#	string hostname = "hostname";\nstring login = "login";\nstring password = "password";\n\n\nProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.FileName = @"C:\Putty\putty.exe";\nstartInfo.Arguments = string.Format("{0}@{1} -pw {2}",login,hostname, password);\nProcess process = new Process();\nprocess.StartInfo = startInfo;\nprocess.Start();	0
11955806	11955462	How to test ASP NET ashx Handler With File Attached	[TestMethod]\npublic void TestCallUploadHandler()\n{\n    const string FILE_PATH = "C:\\foo.txt";\n    const string FILE_NAME = "foo.txt";\n    string UPLOADER_URI =\n        string.Format("http://www.foobar.com/handler.ashx?filename={0}", FILE_NAME);\n\n    using (var stream = File.OpenRead(FILE_PATH))\n    {\n        var httpRequest = WebRequest.Create(UPLOADER_URI) as HttpWebRequest;\n        httpRequest.Method = "POST";\n        stream.Seek(0, SeekOrigin.Begin);\n        stream.CopyTo(httpRequest.GetRequestStream());\n\n        var httpResponse = httpRequest.GetResponse();\n        StreamReader reader = new StreamReader(httpResponse.GetResponseStream());\n        var responseString = reader.ReadToEnd();\n\n        //Check the responsestring and see if all is ok\n    }\n}	0
2453148	2453095	How to do NHibernate queries with reference as criterion?	public IList<Foo> GetAllFoosReferencingBar(Bar bar)\n{\n    using (var tx = Session.BeginTransaction())\n    {\n        var result = Session.CreateCriteria(typeof(Foo))\n            .Add(Restrictions.Eq("ReferencedBar", bar) // <--- Added restriction\n            .List<Foo>();\n        tx.Commit();\n        return result; \n    }\n}	0
1576474	1576463	Keep window in foreground (even if it loses focus)	yourForm.TopMost = true;	0
4387030	4385783	Passing char pointer from C# to c++ function	[DllImport("MyNativeC++DLL.dll")]\nprivate static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares);\n\n\nstatic void Main(string[] args)\n{\n.........\n.........\n        StringBuilder b = new StringBuilder(255);\n        GetInstalledSoftwares(0, b);\n        MessageBox.Show(b.ToString());\n}	0
27085965	27085692	Follow-on to refreshing charts in c#	public void loadChart() {\n\n\n    // this populates my chart with data from the database\n    SqlConnection cnn = new SqlConnection(connectionString);\n\n    SqlCommand sqlcmd = new SqlCommand("SELECT * FROM tbl_salary;", cnn);\n    SqlDataReader dr;\n\n\n    try\n    {\n\n        cnn.Open();\n        dr = sqlcmd.ExecuteReader();\n\nthis.chart1.Series["salaryChart"].Points.Clear();\n        while (dr.Read())\n        {\n            this.chart1.Series["salaryChart"].Points.AddXY(dr.GetString(1), dr.GetInt32(2));\n\n        }\n        cnn.Close();\n    }\n    catch (Exception)\n    {\n\n    }\n}	0
6238371	6238355	how to convert List<List<int>> to multidimensional array	int[][] arrays = lst.Select(a => a.ToArray()).ToArray();	0
4899823	4898568	How to clear StructureMap cache?	void IContainer::EjectAllInstancesOf<T>()	0
33300837	33300525	WPF Inline Editing in textblock based on linenumbers	foreach(System.Windows.Documents.Run run in textBlock.Inlines.OfType<System.Windows.Documents.Run>())\n{\n    if (run.Text.Contains("<files ") || run.Text.Contains("</files>"))\n    {\n        run.Background = Brushes.Yellow;\n    }\n}	0
4140150	3832376	How can I convert an XML file to an instance of a MessageContract class?	namespace MessageContractTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string action = null;\n            XmlReader bodyReader = XmlReader.Create(new StringReader("<Example xmlns=\"http://tempuri.org/\"><Gold>109</Gold><Message>StackOverflow</Message></Example>"));\n            Message msg = Message.CreateMessage(MessageVersion.Default, action, bodyReader);\n            TypedMessageConverter converter = TypedMessageConverter.Create(typeof(Example), "http://tempuri.org/IFoo/BarOperation");\n            Example example = (Example)converter.FromMessage(msg);\n        }\n    }\n\n\n    [MessageContract]\n    public class Example\n    {\n        [MessageHeader]\n        public string Hello;\n\n        [MessageHeader]\n        public double Value;\n\n        [MessageBodyMember]\n        public int Gold;\n\n        [MessageBodyMember]\n        public string Message;\n    }\n}	0
33437736	33436319	How to select a table with no ID or class	Div detailsDiv = ie.Div("detailsDiv");\n\nTableCollection tableColl = detailsDiv.Tables;\nTable featuresTable = tableColl[1];	0
9729312	9729237	C# How to modify xml attributes based on searched string	modValue = Regex.Replace(url, @"localhost(:\d+){0,1}", newUrlName)	0
13706713	13706619	How to check if another file is in the same directory of the current running application?	Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);	0
3149477	3149427	How to add data to a dictonary from xml file in c# using XML to LINQ	dict = XDOC\n    .Load(Application.StartupPath + "\\Test.xml")\n    .Descendants("Child")\n    .Select((x,i) => new {data=x, index=i})\n    .ToDictionary(x => x.index, x => x.data.Attribute("Value").Value);	0
691107	690150	Delete an image bound to a control	//create new stream and create bitmap frame\nBitmapImage bitmapImage = new BitmapImage();\nbitmapImage.BeginInit();\nbitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read);\nbitmapImage.DecodePixelWidth = (int) _decodePixelWidth;\nbitmapImage.DecodePixelHeight = (int) _decodePixelHeight;\n//load the image now so we can immediately dispose of the stream\nbitmapImage.CacheOption = BitmapCacheOption.OnLoad;\nbitmapImage.EndInit();\n\n//clean up the stream to avoid file access exceptions when attempting to delete images\nbitmapImage.StreamSource.Dispose();	0
29759619	29759504	Need to generate report using LINQ	var result = mydata.Where(x=>x.route.Equals("2022") && x.shift.Equals("2120"))\n            .GroupBy(x=> x.Date).Select(grp => new {Date = grp.Key, Count = grp.Count()});	0
6149180	6149169	Automatic create folders in directory c#	Directory.CreateDirectory	0
21297796	21296429	Program crashes on startup with ImageBrush	ImageSource="Resources/Koala.jpg"	0
27821378	27819551	C# MVC Bind variables in a string to model	var controllerContext = new ControllerContext();\n//set values in controllerContext  here\nvar bindingContext = new ModelBindingContext();\nvar modelBinder = ModelBinders.Binders.DefaultBinder;\nvar result = modelBinder.BindModel(controllerContext, bindingContext)	0
25673576	25673407	Deserializing XML from API in ASP.NET MVC	[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/RestService.Models")]\npublic class ArrayDTO\n{\n    [XmlElement("LaborDTO")]\n    public LaborDTO[] collection { get; set; }\n}	0
3720685	3720590	Find a control on a page with a master page	Table tblForm = this.Master.FindControl("MainContent").FindControl("formtable") as Table;	0
22191080	22190948	how to select specific drop down list Item	ddlCountry.Items.FindByText(gvCountry.SelectRow.Cells[1].text).selected = true;	0
3176019	3175958	How do I read the fontName property of a IHTMLComputedStyle interface in C#?	[propget, id(DISPID_IHTMLCOMPUTEDSTYLE_FONTNAME)] HRESULT fontName([retval, out] TCHAR * p);	0
2023336	2022850	C# Using table.row.field values in a report header/footer	VFP - Title page = appears once at beginning of report\nVFP - Header = appear at top of each page\nVFP - Detail = what appears for each row in report\nVFP - Footer = appear at bottom of each page\nVFP - Summary page = appears once at end of report\n\nC# - Header = VFP Title Page\nC# - Footer = VFP Summary Page\n\nC# - Body = VFP Header, Detail and Footer all in one.\nC# - Body - add a TABLE Control to do individual rows as needed	0
4853853	4853204	Nearest ancestor's xs:documentation node of an xs:element	(//xs:element[@name='orderRequest']\n     /ancestor-or-self::*\n         /xs:annotation\n             /xs:documentation)[last()]	0
9652894	9645421	Regex replace value with first match	output = Regex.Replace(input, \n    @"\<a([^>]+)href\=.?mailto\:(?<mailto>[^""'>]+).?([^>]*)\>(?<mailtext>.*?)\<\/a\>", \n    m => m.Groups["mailto"].Value);	0
19206128	19205958	Could not find a part of the path . Update sql using upload buttom	if(fileUpload.HasFile && fileUpload.PostedFile.ContentLength>0) // check for \n                                                                 validity of file\n{\n  var path = string.Format("~/YourImageDir/{0}",Guid.NewGuid().ToString().\n  Replace("-",string.Empty));     \n  //then do your update with this above path \n}\nelse\n{\n // update without file path\n}	0
4069011	4068921	Correct to use an implementation instead of the abstraction or change implementation?	var i = obj as theClass	0
8936636	8936616	Using embedded resources in C# console application	using System.IO;\nusing System.Reflection;\nusing System.Xml;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var stream =  Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml");\n            StreamReader reader = new StreamReader(stream);\n\n            XmlDocument doc = new XmlDocument();\n            doc.LoadXml(reader.ReadToEnd());\n        }\n    }\n}	0
11057260	11049610	getting demographic information about twitter user	var users =\n            from tweet in twitterCtx.User\n            where tweet.Type == UserType.Show &&\n                  tweet.ScreenName == "JoeMayo"\n            select tweet;\n\n        var user = users.SingleOrDefault();\n\n        var name = user.Name;\n        var lastStatus = user.Status == null ? "No Status" : user.Status.Text;\n\n        Console.WriteLine();\n        Console.WriteLine("Name: {0}, Last Tweet: {1}\n", name, lastStatus);	0
1649901	1630791	Dynamic Data | LINQ TO SQL | General Validation	public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)\n{\n\n    try\n    {\n        base.SubmitChanges(failureMode);\n    }\n    catch (Exception e)\n    {\n        throw new ValidationException("Something is wrong", e);\n    }\n\n}	0
11607075	11605185	How to store only available columns in DataGridView	using (SqlConnection cn = new SqlConnection(YourConnectionString))\n        {\n            cn.Open();\n            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(cn))\n            {\n                bulkCopy.DestinationTableName = "dbo.Student";\n\n                try\n                {\n                    bulkCopy.ColumnMappings.Add("StudentID", "StudentID");\n                    bulkCopy.ColumnMappings.Add("Name", "Name");\n                    bulkCopy.ColumnMappings.Add("Address", "Address");\n\n                    // Bulk write on the server\n                    bulkCopy.WriteToServer(DtSet.Tables[0]);\n\n                }\n                catch (Exception ex)\n                {\n                    MessageBox.Show(ex.Message);\n                }\n            }\n\n        }	0
9808871	9808725	Create SQL parameters programmatically	sql = connection.CreateCommand();    \n    wherequery = @"WHERE fieldname = @p_FieldName ";\n    sql.Parameters.Add(new SqlParameter("@p_FieldName ", "some value for fieldname"));\n\n    if (txtValue.textLength > 0){\n        wherequery += " AND fieldname2 = @p_FieldName2 ";\n        sql.Parameters.Add(new SqlParameter("@p_FieldName2 ", txtValue.text));\n    }\n    query = @"SELECT * FROM tabe" + wherequery;\n\n    sql.CommandText = query;	0
28874900	28874156	Pass two JSON object by web client post method C#	public class Company\n{\n    public string Id { get; set; }\n    // Other properties\n}\n\npublic class Requestor\n{\n    public string Id { get; set; }\n\n    public string Email { get; set; }\n\n    public string FirstName { get; set; }\n\n    public string LastName { get; set; }\n    // Other properties\n}\n\npublic class Container\n{\n    public Company Company { get; set; }\n\n    public Requestor Requestor { get; set; }\n}\n\nvar requestor = new Container();\nrequestor.Company = new Company { Id = "sampleid" };\nrequestor.Requestor = new Requestor\n{\n    FirstName = "test",\n    LastName = "testname"\n};\n\nJsonSerializerSettings settings = new JsonSerializerSettings();\nsettings.ContractResolver = new CamelCasePropertyNamesContractResolver();\nvar data = JsonConvert.SerializeObject(requestor, settings);\n\nWebClient client = new WebClient();\nclient.Headers.Add(HttpRequestHeader.ContentType, "application/json");\n// Code for the credentials etc\nclient.UploadString(@"your url", data);	0
19358584	19358419	Only one checkbox to be selected	//We need this to hold the last checked CheckBox\nCheckBox lastChecked;\nprivate void chk_Click(object sender, EventArgs e) {\n   CheckBox activeCheckBox = sender as CheckBox;\n   if(activeCheckBox != lastChecked && lastChecked!=null) lastChecked.Checked = false;\n   lastChecked = activeCheckBox.Checked ? activeCheckBox : null;\n}	0
2040806	2040620	C# Propertygrid default value typeconverter	private bool myVal=false;\n\n[DefaultValue(false)]\n public bool MyProperty {\n    get {\n       return myVal;\n    }\n    set {\n       myVal=value;\n    }\n }	0
8080123	8080082	Edit array elements	string source = "C|D|E";\nstring[] sourcearray = source.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries);\nfor(int i=0; i < sourcearray.Length; i++)\n{\n   sourcearray[i] = sourcearray[i] + ":";\n}	0
28463947	28463495	Delete null values from c# datatable without loop	DataTable t = new DataTable(); //actually your existing one with bad records\nDataTable newTable = t.Select().Where(x => !x.IsNull(0)).CopyToDataTable();	0
14271535	14270854	Determine if an int value exists once in an array	public static bool One<T>(this IEnumerable<T> sequence)\n{\n   var enumerator = sequence.GetEnumerator();\n   return enumerator.MoveNext() && !enumerator.MoveNext();\n}\n\npublic static bool One<T>(this IEnumerable<T> sequence, Func<T, bool> predicate)\n{\n   return sequence.Where(predicate).One();\n}\n\n//usage\nif (someIntArray.One(item => item == 3)) ...	0
23833265	23833081	Something like Android-SharedPreferences on Windows Store Apps?	var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;\n\n// Create a simple setting\n\nlocalSettings.Values["exampleSetting"] = "Hello Windows";\n\n// Read data from a simple setting\n\nObject value = localSettings.Values["exampleSetting"];\n\nif (value == null)\n{\n    // No data\n}\nelse\n{\n    // Access data in value\n}\n\n// Delete a simple setting\n\nlocalSettings.Values.Remove("exampleSetting");	0
4608248	4608222	Is this correct syntax for a C# statment	intResult = Convert.ToInt32(cmdSelect.Parameters["RETURN_VALUE"].Value);	0
20064454	20064376	how to override a action method in the controller with same name and signature.?	[HttpPost]\npublic ActionResult ListRss(int languageId)\n{\n    return View();\n}\n\n[HttpGet] // or any other http types\npublic ActionResult ListRss(int languageId)\n{\n\n    return View() ;\n}	0
31051477	31051414	if Index of a combobox is equal to the index of your <List>?	var createList = new List<Create>();\n// Populate list\n\nvar selectedListItem = createList[cbSummary.SelectedIndex];	0
19320708	19318963	HttpWebRequest reeading from a String	private void toolStripButton5_Click(object sender, EventArgs e)\n {\n   url = "http://" + toolStripTextBox1.Text;\n   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n   HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n   Stream pageStream = response.GetResponseStream();\n   StreamReader reader = new StreamReader(pageStream,Encoding.Default);\n   string s = reader.ReadToEnd();\n   webBrowser1.DocumentText = s;\n }	0
10944012	10943945	Use split to create new string	int idx = info.IndexOf(',');\nstring result = info.Substring(idx + 1);	0
7486551	7486122	How can I implement search for a WPF ListBox with DataTemplate?	Private Sub MyEventHandler()\n    _ShipmentCollectionView.Filter = New Predicate(Of Object)(AddressOf FilterOut)\nEnd Sub\n\nPrivate Function FilterOut(ByVal item As Object) As Boolean\n        Dim MyShipment As Shipment = CType(item, Shipment)\n        If _FilterDelivered And MyShipment.TransitStatus = eTransitStatus.Delivered Then\n            Return False\n        End If\n        If _FilterOverdue And MyShipment.TransitStatus = eTransitStatus.InTransit AndAlso MyShipment.ExpectedDate < Today Then\n            Return False\n        End If\n        If _FilterUnshipped And MyShipment.TransitStatus = eTransitStatus.Unshipped Then\n            Return False\n        End If\n        If SearchString Is Nothing Or SearchString = "" Then\n            Return True\n        Else\n\n            Return MyShipment.Contains(SearchString)\n        End If\n    End Function	0
27814267	27814197	How to pass and read parameters in a winform in C#	public partial class frmAdd : Form\n    {\n        public frmAdd() //Should I add somthing here?\n        {\n            InitializeComponent();\n        }\n        public frmAdd(string str) : this()\n        {\n\n        }\n}	0
29194565	29194534	Raise tapped event windows phone	private void Button_Click(object sender, RoutedEventArgs e)\n{\n   Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => comboBox1.IsDropDownOpen = true);\n}	0
4181526	3162790	How to format data bound text in a label	set{ Text = "User name :" + value }\nget { return value;}	0
20803053	20802948	How to print word document in C#	using (PrintDialog pd = new PrintDialog())\n{\npd.ShowDialog();\nProcessStartInfo info = new ProcessStartInfo(@"D:\documents\filetoprint.doc");\ninfo.Verb = "PrintTo";\ninfo.Arguments = pd.PrinterSettings.PrinterName;\ninfo.CreateNoWindow = true;\ninfo.WindowStyle = ProcessWindowStyle.Hidden;\nProcess.Start(info);\n}	0
4057374	4057353	Get values from string?	string message = "ERR: 100, out of credit";\nstring[] parts = message.Split(new char[] { ',' });\nstring[] error = parts[0].Split(new char[] { ':' });\n\nstring errorNumber = error[1].Trim();\nstring errorDescription = parts[1].Trim();	0
17781593	17781442	C# why XmlDsigC14NTransform remove all whitespaces from xml	// Create a new XML document.\n    XmlDocument xmlDocument = new XmlDocument();\n\n    // Format using white spaces.\n    xmlDocument.PreserveWhitespace = true;\n\n    // Load the XML file into the document. \n    xmlDocument.Load("file.xml");	0
4272525	4272385	XElement to get all sub-element node names and values	var list = from x in XElement.Load(**yourxmlfile**).Element("Node").Elements()\n           select new\n           {\n              Name = x.Name,\n              Value = (string)x\n           };	0
18163317	18147966	WinApi+LinuxApi in one mono project	Environment.OSVersion.Platform	0
1803277	1803256	Getting the sum of a value in Linq	var query = foos\n            .GroupBy(x => new { x.Category, x.Code })\n            .Select(g => new Foo\n                {\n                    Category = g.Key.Category,\n                    Code = g.Key.Code,\n                    Quantity = g.Sum(x => x.Quantity)\n                });	0
21468250	21460659	Access Images from Phone Class Library	Uri imageUri = new Uri("/ASSEMBLY NAME;component/Assets/Topic1.png", UriKind.Relative);	0
19246620	19246547	GetBytes method cannot be translated into a store expression	var bytes = Encoding.ASCII.GetBytes("0");\n\nvar result = (from history in context.Histories\n                              where history.ID == Id & \n                          (history.Salary != null || history.Salary != bytes)\n                          select (DateTime?)history.Date).Max();\n            return result;	0
11879073	11877912	How to Check logged in user for multiple Roles in Asp.Net membership?	var userRoles = Roles.GetRolesForUser(userName);\nvar rolesNotAssigned = Roles.GetAllRoles().Except(userRoles);\nif (rolesNotAssigned.Length == 0)\n{\n    // user is in all roles   \n}	0
22227318	22226385	Iterating through a foreach loop looking for a value	//create a method to get daily revenue\npublic void GetDailyRevenue(PizzaOrder order)  \n{\n  //for each increments the total daily revenue (sale)\n  //then increments the total revenue for each order\n  //OrderList always have pizzaorder objects stored var only messing up here\n  OrderList.Add(order);\n  foreach (PizzaOrder po in OrderList)\n  {\n     dailyRevenue += order.GetAmountDue(po.NumberOfPizzas, po.NumberOfCokes);\n  }\n   //check what is the value of dailyRevenue here\n}	0
13741245	13738586	Datagridview Scroll Event handler	private void datagridview_Scroll(object sender, ScrollEventArgs e)\n        {\n            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)\n            {\n\n                if (e.NewValue > this.check1.Width/2 )\n                   foo();\n                else\n                   hoo();\n            }\n        }	0
12860260	12860119	wpf programatically set combobox selected item when bound to dictionary	myCombo.SelectedItem = new KeyValuePair<string, int>("myKey", boxItems["myKey"]);	0
15398694	15398670	how can i variable to method name in parameter	private void Form1_Load(object sender, EventArgs e)\n    {\n        Load();\n        //this line \n        InitTimer(() => this.Form1_Load(sender,e));\n    }\n\n    public void InitTimer(Action target) \n    {\n        System.Windows.Forms.Timer timer1;\n        timer1 = new System.Windows.Forms.Timer();\n        timer1.Tick += (sender, e) => target();\n        timer1.Interval = 5000; // in miliseconds\n        timer1.Start();\n    }	0
8185363	8185313	How to obtain the current url	//gets the current url\nstring currentUrl = Request.Url.AbsoluteUri;\n\n//check the url to see if it contains your value\nif (currentUrl.ToLower().Contains("obtain.aspx?thevalue"))\n    //do something	0
16766317	16766241	Retrieve Value/Name of selected item of comboBox	int curentIdTem =  Convert.ToInt32(((themeS)comboBox2.SelectedItem).Value);	0
8622863	8622772	SQL Query to get a boolean value from a BIT type column	while (dataRead.Read())\n                {\n                    items.Add(new ProductModel()\n                    {\n                        Selected=(bool)dataRead["SelectedProducts"],\n                        ProductName= dataRead["ProductName"].ToString()\n                    });\n                }	0
20119532	20119433	Remove space in xml element name	String.Replace(" ", "");	0
15167475	15167437	Casting interface with generic parameter implemented by class without generic parameter	public interface IDocument<out SegType> where SegType : ISegment\n{}	0
4363058	4362340	How to simulate http request using WatiN with specific HTTP referrer and query string?	// session is a custom version of FiddlerCore.Fiddler\n// details about BeforeRequest -> http://fiddler.wikidot.com/fiddlercore-demo\nsession.BeforeRequest += sess =>\n    sess.oRequest\n        .headers\n        .Add(\n            "Referer",\n            "http://www.i-am-middle-man.com/q=black"\n        );\n\nsession.BeforeResponse += sess =>\n        {\n            //sess.oResponse.headers.HTTPResponseCode\n            //sess.oResponse.headers["Host"]\n        };\n\nvar handler = WatiNHandler(BrowserTypes.IE);\nhandler.GoTo("http://www.my-url.com/");	0
24078971	24062877	How to get the ScrollViewer to scroll after statically set index containing List inside?	int index = 5; //say you want to display upto 5th element\n        ListBox lines = new ListBox();\n        lines.Width = 100;\n        ScrollViewer scrollViewer = new ScrollViewer();\n        scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;\n        for (int i = 0; i < 5; i++)\n        {\n\n            lines.Items.Add(new ListBoxItem\n                        {\n                           Content = i.ToString()\n                        });\n        }\n        foreach (ListBoxItem lv in lines.Items)\n        {\n            lv.Height = 10;\n\n        }\n        scrollViewer.Height = index * 10;\n        scrollViewer.Content = lines;\n        Grid.SetColumn(scrollViewer, 1);\n        childGrid.Children.Add(scrollViewer);	0
18877010	18877009	Deleting All Documents in RavenDB	private static void DeleteFiles(IDocumentStore documentStore)\n    {\n        var staleIndexesWaitAction = new Action(\n            delegate\n            {\n                while (documentStore.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)\n                {\n                    Thread.Sleep(10);\n                }\n            });\n        staleIndexesWaitAction.Invoke();\n        documentStore.DatabaseCommands.DeleteByIndex("Auto/AllDocs", new IndexQuery());\n        staleIndexesWaitAction.Invoke();\n    }	0
12555717	12555534	How can I convert my Python regex into C#?	Dictionary<string, List<Regex>> everything = new Dictionary<string, List<Regex>>()\n{\n    { "Type1", "49 48 29 ai au2".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },\n    { "Type2", "ki[0-9] 29 ra9".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },\n}\n\nstring GetInputType(string input)\n{\n    var codeSegments = input.ToLower().Split('-');\n    if(codeSegments.Length < 2) return "NULL";\n\n    string code = "-" + codeSegments[1] + "-";\n    var matches = everything\n        .Where(kvp => kvp.Value.Any(r => r.IsMatch(code)));\n\n    return matches.Any() ? matches.First().Key : "NULL";\n}	0
28716054	28715805	how to find string from array and assign it to a string in c# asp.net	string a = "Computer";\n        string result = "";\n        int ss = a.Length;\n        string[] m = { "t", "n", "m" };\n        int b=0;\n        string str = "";\n        for (int i = 0; i < ss;i++)\n        {\n            if(a[i]=='t' || a[i]=='n' || a[i]=='m')\n            {\n                b = i+1;\n                str = a[i].ToString();\n\n                break;\n            }\n        }\n      Label2.Text = "The first character from the list is " + str +\n            " occurred at position " + b.ToString() + " in " + a + ". it is the " + b.ToString() +\n            "rd of " + ss.ToString() + " characters in the word.";	0
13812527	13812335	How to hash an int[] in c#	public static int CombineHashCodes(params int[] hashCodes)\n{\n    if (hashCodes == null)\n    {\n        throw new ArgumentNullException("hashCodes");\n    }\n\n    if (hashCodes.Length == 0)\n    {\n        throw new IndexOutOfRangeException();\n    }\n\n    if (hashCodes.Length == 1)\n    {\n        return hashCodes[0];\n    }\n\n    var result = hashCodes[0];\n\n    for (var i = 1; i < hashCodes.Length; i++)\n    {\n        result = CombineHashCodes(result, hashCodes[i]);\n    }\n\n    return result;\n}\n\nprivate static int CombineHashCodes(int h1, int h2)\n{\n    return (h1 << 5) + h1 ^ h2;\n\n    // another implementation\n    //unchecked\n    //{\n    //    var hash = 17;\n\n    //    hash = hash * 23 + h1;\n    //    hash = hash * 23 + h2;\n\n    //    return hash;\n    //}\n}	0
7724595	7724550	Retrieve varbinary(MAX) from SQL Server to byte[] in C#	private static byte[] getDocument(int documentId)\n{\n    using (SqlConnection cn = new SqlConnection("..."))\n    using (SqlCommand cm = cn.CreateCommand())\n    {\n        cm.CommandText = @"\n            SELECT DocumentData\n            FROM   Document\n            WHERE  DocumentId = @Id";\n        cm.Parameters.AddWithValue("@Id", documentId);\n        cn.Open();\n        return cm.ExecuteScalar() as byte[];\n    }\n}	0
33899778	33899565	show only object properties from javascript object	for (var myList in myListItems) {\n  // Check if myList is a property on myListItems\n  if (myListItems.hasOwnProperty(myList)) {\n    console.log(myList);\n    console.log(myListItems[myList]);\n  }\n}	0
11531226	11531189	Multiplier operation string in C#	string repeated = string.Join(" ", Enumerable.Repeat("Hello", 10));	0
13461180	13461150	C# split string after each # symbol	string input = "27173316#sometext.balbalblabba#4849489#text#text2#number";\nstring[] values = input.Split('#');	0
105963	105609	I need a helper method to compare a char Enum and a char boxed to an object	static void Main(string[] args)\n    {\n        object val = 'O';\n        Console.WriteLine(EnumEqual(TransactionStatus.Open, val));\n\n        val = 'R';\n        Console.WriteLine(EnumEqual(DirectionStatus.Left, val));\n\n        Console.ReadLine();\n    }\n\n    public static bool EnumEqual(Enum e, object boxedValue)\n    {                        \n        return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));\n    }\n\n    public enum TransactionStatus { Open = 'O', Closed = 'C' };\n    public enum DirectionStatus { Left = 'L', Right = 'R' };	0
1525922	566815	StructureMap, scan assemblies and scoping	public class CustomScanner : ITypeScanner\n{\n    #region ITypeScanner Members\n\n    public void Process(Type type, PluginGraph graph)\n    {                                   \n        graph.AddType(type);\n        var family = graph.FindFamily(type);\n        family.AddType(type);\n        family.SetScopeTo(InstanceScope.Hybrid);\n    }\n\n    #endregion\n}	0
16468499	16468395	Error - No value given for one or more required parameters	string Query = "select * from [data$] where " + col1Name + " > '" + Col1Value + "' AND Gender = '" + gender +"'";	0
15620852	15620788	Data serialization with and without specific field	public class MyEntity\n{\n  // some props\n}\n\npublic class MyEntityWithId : MyEntity\n{\n  public int Id { get; set; }\n  // some props\n}	0
6993585	6993472	Manipulating a String : Detected a character in a string an select all the characters after that	var index = original.LastIndexOf('-');\nvar suffix = original.Substring(index);\nvar crop = original.Substring(0, index);	0
3087783	3087334	gridview.columns how to retrieve it?	int cells_count;\n            ArrayList Header_list = new ArrayList();\n\n//wrking..\n\n            cells_count = GridView1.HeaderRow.Cells.Count;\n\n            for (int i = 0; i < cells_count; i++)\n            {\n                Header_list.Add( GridView1.HeaderRow.Cells[i].Text );\n            }\n           // Label1.Text = GridView1.HeaderRow.Cells[1].Text;\n\n            //the first colunm name\n            Label1.Text = Header_list[0].ToString();	0
21436495	21435705	Calling an instance declared in one method from another method	ValueList _valueList;	0
3677319	3677182	Taskbar location	public static Rectangle GetTaskbarPosition() {\n        var data = new APPBARDATA();\n        data.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(data);\n        IntPtr retval = SHAppBarMessage(ABM_GETTASKBARPOS, ref data);\n        if (retval == IntPtr.Zero) throw new Win32Exception("Please re-install Windows");\n        return new Rectangle(data.rc.left, data.rc.top,\n            data.rc.right - data.rc.left, data.rc.bottom - data.rc.top);\n\n    }\n\n    // P/Invoke goo:\n    private const int ABM_GETTASKBARPOS = 5;\n    [System.Runtime.InteropServices.DllImport("shell32.dll")]\n    private static extern IntPtr SHAppBarMessage(int msg, ref APPBARDATA data);\n    private struct APPBARDATA {\n        public int cbSize;\n        public IntPtr hWnd;\n        public int uCallbackMessage;\n        public int uEdge;\n        public RECT rc;\n        public IntPtr lParam;\n    }\n    private struct RECT {\n        public int left, top, right, bottom;\n    }	0
32394537	32393591	How can I get the value from XML return boolean value?	public static bool FunEnable(string funNam)\n        {\n            bool result = true;\n            XmlDocument xDL = new XmlDocument();\n            xDL.Load(@"C:/XMLFile2.xml"); //Load XML file\n            XmlNodeList nodeList = xDL.SelectNodes("//itemb");\n            foreach (XmlNode node in nodeList)\n            {\n                if (node.Attributes["FunName"].Value.Equals(funNam))\n                {\n                    result = Convert.ToBoolean(node.Attributes["isEnable"].Value);\n                    break;\n                }\n            }\n            Console.WriteLine("with funName = "+ funNam +" isEnable equal to : " + result);\n            return result;\n        }	0
3494931	3494908	Copy one Xml Document contents into another one in C#	File.Copy	0
4065751	4065694	Playing wav file, concatenating string to call file	using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))\n{\n    for (int i = 1; i <= 99; i ++)\n    {\n        SoundPlayer simpleSound = (SoundPlayer)resxSet.GetObject("L" + i.ToString());\n        simpleSound.Play();\n    }\n}	0
30582497	30581069	TeamCity publishes NuGet package multiple times	---------------------*****------------\n[13:53:10] 2.19.5627.21133.nupkg (12s)\n[13:53:23] 2.19.5627.21281.nupkg (5s)\n[13:53:28] 2.19.5627.21680.nupkg (14s)\n[13:53:42] 2.19.5627.21777.nupkg (12s)\n[13:53:55] 2.19.5627.23661.nupkg (6s)\n[13:54:02] 2.19.5627.23808.nupkg (12s)\n[13:54:14] 2.19.5627.24431.nupkg (13s)\n[13:54:28] 2.19.5627.25366.nupkg (6s)\n[13:54:34] 2.19.5627.25732.nupkg (15s)\n[13:54:49] 2.19.5627.26132.nupkg (13s)\n[13:55:02] 2.19.5627.26469.nupkg (6s)\n[13:55:09] 2.19.5627.26890.nupkg (13s)\n[13:55:23] 2.19.5630.18299.nupkg (7s)\n[13:55:30] 2.19.5630.18837.nupkg (8s)\n[13:55:39] 2.19.5630.20862.nupkg (17s)\n[13:55:56] 2.19.5630.22872.nupkg (7s)\n[13:56:03] 2.19.5630.23126.nupkg (17s)	0
32634471	31682347	Attaching Browser Variable To PDF File In Internet Explorer	using (WebClient client = new WebClient())\n{\n   if (Directory.Exists(@"\\folder"))\n   {\n       string downloadURL = "http://example.com/retrievePDF.jsp?id=XXXXX";\n       client.DownloadFile(downloadURL, @"\\folder\" + fName + ".pdf");\n   }\n}	0
15339596	15339519	ASP Custom Routing with no parameters	routes.MapRoute( "GetCard", "partner/store/getcard", new { controller = "Partner", action = "GetCard"} );\n\n\nroutes.MapRoute( "GetCardWithShortcode", "partner/store/getcard/{voucherShortCode}", new { controller = "Partner", action = "GetCardWithShortCode" } );	0
18449328	18449258	Adding a parameter to a new eventhandler	string dataSourceName = ...;\ngridData.RowEditing += (sender, e) => grid_RowEditing(gridData, dataSourceName, e);\n        gridData.DataSource = tbl;\n        gridData.DataBind();\n\n\nvoid grid_RowEditing(GridView gridData, string dataSourceName, GridViewEventArgs e) {\n  ...\n}	0
28829065	28828492	How Do I Make a WPF Grid Containing an ItemsControl Have Columns of Equal Size	...\n    </Grid.RowDefinitions>\n    <ItemsControl Grid.IsSharedSizeScope="True" ItemsSource="{Binding CheckBoxItems}"  Grid.Row="0" Grid.Column="0" >\n        <ItemsControl.ItemsPanel>\n    ...	0
2117380	2117349	How to programatically access images in a resource file?	private void Form1_Load(object sender, EventArgs e)\n    {\n        var list = WindowsFormsApplication1.Properties.Resources.ResourceManager.GetResourceSet(new System.Globalization.CultureInfo("en-us"), true, true);\n        foreach (System.Collections.DictionaryEntry img in list)\n        {\n            System.Diagnostics.Debug.WriteLine(img.Key);\n            //use img.Value to get the bitmap\n        }\n\n    }	0
14303207	14270934	How to conditionally supply constructor arguments with StructureMap?	x.For<ProcessorSettings>().Add<ProcessorSettings>().Ctor<int>("frequency")\n    .Is(intVal1).Named("ProcessorSetting1");\nx.For<ProcessorSettings>().Add<ProcessorSettings>().Ctor<int>("frequency")\n    .Is(intVal2).Named("ProcessorSetting2");\nx.For<IType>().Add<TypeOne>().Ctor<ProcessorSettings>()\n    .Named("ProcessorSetting1");\nx.For<IType>().Add<TypeTwo>().Ctor<ProcessorSettings>()\n    .Named("ProcessorSetting2");	0
28941613	28941439	C# generic list as constructor parameter	if(property.GetValue(this,null) is IList \n            && property.GetValue(this,null).GetType().IsGenericType){\n\n            var listType = property.PropertyType.GetGenericArguments()[0];\n            var confType = typeof(ConfEntryList<>).MakeGenericType(listType);\n            var item = (ConfEntry)Activator.CreateInstance(confType,\n                  new object [] {property.Name, property.GetValue(this, null)});\n            confContainer.ConfEntries [i] =  item;\n       }	0
2938481	2938442	How to find which serial port is currently used?	foreach(string portname in SerialPort.GetPortNames())\n{\n    // Use your connection settings - own baud rate etc\n    SerialPort sp = new SerialPort(portname,4800, Parity.Odd, 8, StopBits.One); \n    try\n    {\n         sp.Open();\n         sp.Write("Your known command to phone");\n         Thread.Sleep(500);\n         string received = sp.ReadLine();\n\n         if(received == "expected response")\n         {\n              Console.WriteLine("Phone connected to: " + portname);\n              break;\n         }\n    }\n    catch(Exception)\n    {\n         Console.WriteLine("Phone NOT connected to: " + portname);\n    }\n    finally\n    {\n         sp.Close();\n    }\n}	0
10221462	10221421	Get MVC2 model attribute value from Controller	public static void PrintAuthorInfo(Type t) \n   {\n      Console.WriteLine("Author information for {0}", t);\n      Attribute[] attrs = Attribute.GetCustomAttributes(t);\n      foreach(Attribute attr in attrs) \n      {\n         if (attr is Author) \n         {\n            Author a = (Author)attr;\n            Console.WriteLine("   {0}, version {1:f}",\na.GetName(), a.version);\n         }\n      }\n   }	0
19829447	19829340	Match Strings to Class Properties	var valuesToSet = new Dictionary<string, object> \n                  {\n                        {"BitmapUnembeddableFonts", false}, \n                        {"UsePdaA", true}\n                  };\n\nvar settings = new FixedFormatSettings();\n\nvar properties = settings.GetType()\n                         .GetProperties()\n                         .Where(p => p.CanWrite);\n\nforeach (var property in properties)\n{\n    object valueToSet;\n    if(valuesToSet.TryGetValue(property.Name, out valueToSet))\n    {\n        property.SetValue(settings, valueToSet);\n    }\n}\n\nConsole.WriteLine(settings.BitmapUnembeddableFonts); //false\nConsole.WriteLine(settings.UsePdaA); //true	0
13770135	13769771	Getting a cache to update variable every half hour on the hour	DateTime time_to_expire = DateTime.Now.AddMinutes(30);\n        time_to_expire = new DateTime(time_to_expire.Year, time_to_expire.Month, time_to_expire.Day, time_to_expire.Hour, time_to_expire.Minute >= 30 ? 30 : 0, 0);	0
33473143	33473050	How to run a winform project for more than one?	Process.Start(Assembly.GetExecutingAssembly().CodeBase);	0
529467	528776	How can I run a query on a dataset that returns different columns to the table?	tblDeviceDataTable dtService = new tblDeviceDataTable();\ndtService.tblLocationID.AllowDbNull = true;\ntaDevice.FillDataByDeviceSN(dtService,txtDeviceSerial.Text);	0
27919681	27919041	binding grid view on button click in listview	protected void Page_Load(Object sender, EventArgs e)\n{\n    if(!IsPostBack)\n    {\n        BindGrid();\n    }\n}	0
6550236	6539397	Find out if HTC phone enters a mobile app	if(Request.UserAgent.ToUpper().Contains("HTC")){\n   //Code\n}	0
30769507	30728205	Set a field in all the children of an item	public void ResetFields(List<Item> items, List<string> fields)\n{\n    if (items.Any() && fields.Any())\n    {\n        foreach (Item item in items)\n        {\n           ResetFieldsOnItem(item, fields);\n        }\n    }\n}\n\npublic void ResetFieldsOnItem(Item item, List<string> fields)\n{\n    if (item != null && fields.Any())\n    {\n        using (new Sitecore.Security.Accounts.UserSwitcher(ElevatedUserAccount, true))\n        {\n            item.Editing.BeginEdit();\n\n            foreach (string field in fields)\n            {\n                item.Fields[field].Reset();\n            }\n\n            item.Editing.EndEdit();\n        }\n    }\n}	0
24163751	24163637	How to return a value from string function	string result = string.Empty;\n\n       try\n       {\n        // code here \n          Lidoc_num = com1.Parameters[0].Value.ToString();\n          result = Lidoc_num;\n       }\n    catch (OracleException ex)\n            {\n                if (ora_trn != null) ora_trn.Rollback();\n\n                if (ora_cn != null)\n                    if (ora_cn.State != ConnectionState.Closed)\n                        ora_cn.Close();\n\n                WriteErrors.WriteToLogFile("Dohvati_IDOC", "Gre?ka:" + ex.ToString());\n\n                result = "";\n            }\n\nreturn result;	0
10521124	10521097	C# Return from a try-catch block	public static Image GetExternalImg(string name, string size)\n    {\n        try\n        {\n            // Get the image from the web.\n            WebRequest req = WebRequest.Create(String.Format("http://www.picturesite.com/picture.png", name, size));\n            // Read the image that we get in a stream.\n            Stream stream = req.GetResponse().GetResponseStream();\n            // Save the image from the stream that we are rreading.\n            Image img = Image.FromStream(stream);\n            // Save the image to local storage.\n            img.Save(Environment.CurrentDirectory + "\\images\\" + name + ".png");\n            return img;\n        }\n        catch (Exception)\n        {\n              //grab an image from resource\n              return theDefaultImage;\n        }\n    }	0
8879416	8879385	Get the current system datetime	Datetime myEpoch = new DateTime(2005, 11, 11, 7, 0, 0, DateTimeKind.Utc);	0
6037506	6036338	Can I set the datasource for a column in grid, only for one specific row?	private void gridView1_ShownEditor(object sender, EventArgs e) {\n            GridView gridView = sender as GridView;\n            if(gridView.FocusedColumn.FieldName == "YourField") {\n                CheckedComboBoxEdit edit = gridView.ActiveEditor as CheckedComboBoxEdit;\n                object value = gridView.GetRowCellValue(gridView.FocusedRowHandle, "AnotherColumn");\n                // filter the datasource and set the editor's DataSource:\n                edit.Properties.DataSource = FilteredDataSource;// your value\n            }\n        }	0
14609471	14609380	Windows Forms - detecting button click from a panel inside the form	foreach (var button in panel.Controls.OfType<Button>())\n{\n    button.Click += HandleClick;\n}	0
736014	736010	Expanding this Regular Expressions to remove all special characters	string BBCSplit = Regex.Replace(BBC, @"<(.|\n)*?>|[:;]", string.Empty);	0
20147470	20147118	C# get Values of all items in Listbox	foreach (DataRowView drv in listBox1.Items)\n        {\n            int id= int.Parse(drv.Row[listBox1.ValueMember].ToString());\n           //if you want to store all the idexes from your listbox, put them into an array \n        }	0
21433724	21433684	How to user LINQ to convert list to dictionary?	var dict = meters.ToDictionary(m => m.MeterUID, m => m);	0
10073943	10073790	parsing Json File with gson: MalformedJsonException	"{\n    "tag_name": "M mit Mbrunnen",  // always use double quotes, single quote is not a valid json\n    "tag_id": "de_bw_xx_mstall",\n    "tag_description": "false",\n    "tag_latitude": "42.704895",\n    "tag_longitude": "10.652187",\n    "tag_description_f_a": "Ein weiteres Highlight in H" // extra comma removed from here\n}"	0
18154859	18154302	Get list of temporary internet files	static void Main(string[] args)\n    {\n        var path = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);\n        var dInfo = new DirectoryInfo(path);\n\n        DoStuff(dInfo);\n\n        Console.ReadLine();\n    }\n\n    static void DoStuff(DirectoryInfo directory)\n    {\n        foreach (var file in directory.GetFiles())\n        {\n            Console.WriteLine(file.FullName);\n        }\n\n        foreach (var subDirectory in directory.GetDirectories())\n        {\n            DoStuff(subDirectory);\n        }\n    }	0
20445949	20445904	DropDownList Value won't change	protected void Page_Load(object sender, EventArgs e)\n{\n  if (!Page.IsPostBack) {\n    SqlConnection con = new SqlConnection("connection string");\n    con.Open();\n    DataTable Seminars = new DataTable();\n    SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID  FROM SeminarData", con);\n    adapter.Fill(Seminars);\n    DropDownList1.DataSource = Seminars;\n    DropDownList1.DataTextField = "SeminarName";\n    DropDownList1.DataValueField = "SeminarName";\n    DropDownList1.DataBind(); \n    con.Close();\n  }\n}	0
9317731	9317531	Accessing Validator block ErrorMessage	public class Person\n{\n  [RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, DateTimeUnit.Year,\n           Ruleset="RuleSetA", MessageTemplate="Must be 18 years or older.")]\n  public DateTime DateOfBirth\n  {\n    get\n    {\n      return dateOfBirth;\n    }\n  }\n}	0
15638266	15638206	Get Int value from Controller to $.Ajax	[HttpPost]\npublic JsonResult AddInvoice(Invoice model)\n{\n    int invoiceId = CRMServiceDL.insertInvoiceDetail(model);\n    int success = invoiceId > 0 ? invoiceId : -1;\n\n    return Json(new { success });\n}	0
3148434	3148405	How to make these foreach loops efficient?	foreach (PatchFacilityManager PM in patchFacilityManager)\n    {\n        PM.IsSelected = facilityManagerId.Contains(PM.FacilityManagerId);\n    }	0
2877933	2875573	How to programmatically open the application menu in a .NET CF 2.0 application	private void cmdMenu_Click(object sender, EventArgs e)\n{\n    const int VK_MENU = 0x12;\n    SendKey(VK_MENU);\n}\n\n\npublic static void SendKey(byte key)\n{\n    const int KEYEVENTF_KEYUP = 0x02;\n    const int KEYEVENTF_KEYDOWN = 0x00;\n\n    keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);\n    keybd_event(key, 0, KEYEVENTF_KEYUP, 0);\n}\n\n[System.Runtime.InteropServices.DllImport("coredll", SetLastError = true)]\nprivate static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);	0
6157623	6070205	IHTMLImgElement to byte[]	string imgSrc = htmlImgElement.src;\nWebClient web = new WebClient();\nbyte[] imageData = web.DownloadData(imgSrc);	0
24247858	24219478	SignalR continuous messaging	public class DataTask : IRegisteredObject\n{\n     private readonly IGlobalData _global;\n     private readonly IDataService _service;\n     private readonly IHubContext _hub;\n\n     private Timer _timer;\n\n     public DataTask(IGlobalData global, IDataService service, IHubContext hub)\n     {\n          this._global = global;\n          this._service = service;\n          this._hub = hub;\n\n          var interval = new TimeSpan(0, 0, 10);\n          this._timer = new Timer(updateClients, null, TimeSpan.Zero, interval);\n\n          // register this task with asp.net\n          HostingEnvironment.RegisterObject(this);\n     }\n\n     public void Stop(bool immediate)\n     {\n          _timer.Dispose();\n\n          HostingEnvironment.UnregisterObject(this);\n     }\n\n     private async void updateClients(object state)\n     {\n          var result = await this._service.GetData();\n          // call the hub\n          this._hub.Clients.All.updateData(result);\n     }\n}	0
12862539	12862490	How do I determine the number of rows in the last page of an ASP:GridView?	int lastPageRecords = TotalRecords % PageSize;	0
13400489	13400422	get data from datable query	return sqlData\n           .AsEnumerable()\n           .Where(data => data.Field<String>("slideNo") == "5"))\n           .Select(data=> data.Field<String>("QuestionStartText"))\n           .Distinct()\n           .ToList();	0
6703280	6703180	Generic Method Enum To String Conversion	enum E\n{\n    A = 2,\n    B = 3\n}\n\npublic static string GetLiteral<T>(object value)\n{\n    return Enum.GetName(typeof(T), value);\n}\n\nstatic void Main(string[] args)\n{\n    Console.WriteLine(GetLiteral<E>(2));\n    Console.WriteLine(GetLiteral<E>(3));\n}	0
33143510	33141844	Speed up console application, Concurrency? Parralell Programming?	Parallel.ForEach	0
1291172	1291117	An inherited singleton class from a base class that takes parameters in its constructor?	public sealed class SingletonFoo : BaseFoo\n{\n    static readonly SingletonFoo instance = new SingletonFoo("Some Value");\n\n    static SingletonFoo()\n    {\n    }\n\n    private SingletonFoo(string value) : base(value)\n    {\n    }\n    // ...	0
32347783	32347338	Finding all possible combinations of array items that add to combination of items in other array	C = N!/(K!(N-K!)	0
4485292	4482677	Facebook ASP.NET MVC App with multiple controllers	[CanvasAuthorize(Perms = "user_about_me")]\npublic class FirstController : Controller {\n\n\n}\n\n[CanvasAuthorize(Perms = "user_about_me")]\npublic class SecondController : Controller {\n\n}	0
18197486	18197452	Reflection - Access custom attributes by name	method.GetCustomAttributes(true)\n      .Where(a => a.GetType().FullName == "NUnit.Framework.TestAttribute");	0
28587605	28587462	Closing my application is interfering with my Form1_FormClosing event	public static bool HasPermission=true;\n private void checkcon()\n  {\n     try\n     {\n       MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);\n       con.Open();\n\n       con.Close();\n     }\n     catch (Exception ex)\n     { \n       HasPermission=false;\n       MessageBox.Show("Your domain account does not have sufficient privilages to    continue with the application please contact the IS support Team.");              \n       Close();\n     }\n\n  }\n\n private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n  { if (HasPermission)\n    {\n    DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\n     if (result == DialogResult.No)\n     {\n        e.Cancel = true;\n     }\n     else\n     {\n     }\n     }\n  }	0
13056156	13055665	Parse Malformed XML With Linq	var xDoc = XDocument.Parse(xml); //XDocument.Load(filename)\n\nvar dict = xDoc.Descendants("field")\n               .Where(e=>e.HasAttributes)\n               .ToDictionary(e => e.Attribute("name").Value, e => e.Value);\n\nConsole.WriteLine(dict["currentsong"]);	0
21033640	21033173	Issue with windows service waiting for a named event, using EventWaitHandle.	string eName = "Global\\notification_event";	0
2666566	2666431	multiline column in data grid view. using c#	this.dataGridView1.Columns[index].DefaultCellStyle.WrapMode = DataGridViewTriState.True;	0
2955069	2955027	Extracting text from a file where date -time is the index	// This would come from Stream.ReadLine() or something\nstring line = "02/06/2010,10:05,1.0,2.0,3.0,4.0,5";\n\nstring[] parts = line.Split(',');\nDateTime date = DateTime.ParseExact(parts[0], "dd/MM/yyyy", null);\nTimeSpan time = TimeSpan.Parse(parts[1]);\ndate = date.Add(time); // adds the time to the date\nfloat float1 = Single.Parse(parts[2]);\nfloat float2 = Single.Parse(parts[3]);\nfloat float3 = Single.Parse(parts[4]);\nfloat float4 = Single.Parse(parts[5]);\nint integer = Int32.Parse(parts[6]);\n\nConsole.WriteLine("Date: {0:d}", date);\nConsole.WriteLine("Time: {0:t}", date);\nConsole.WriteLine("Float1: {0}", float1);\nConsole.WriteLine("Float2: {0}", float2);\nConsole.WriteLine("Float3: {0}", float3);\nConsole.WriteLine("Float4: {0}", float4);\nConsole.WriteLine("Integer: {0}", integer);	0
23648337	23471582	Connecting application to database on a pc over an intranet	string myconnectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\" + PCName + @"\data\data.mdb"	0
21239465	21239416	Read xml as a string	FileStream fStream = new FileStream(path);\nStreamReader sr = new StreamReader(fStream, System.Text.UTF8Encoding);\nItemController.cacheTG = sr.ReadToEnd();\nsr.Close();\nfStream.Close();	0
8787500	8787458	How to increment a integer variable itself	var ints = new int[5];  // declares an array of five integers, ints[0] to ints[4]\n\nfor (int i = 0; i < 5; i++) {\n    // do something with ints[i]\n}	0
10631809	10631618	Remember the page after session timeout	public static  void DisposeAndLogout()\n            {\n\n                HttpContext context = HttpContext.Current;\n                try\n                {\n                    FormsAuthentication.SignOut();\n                    FormsAuthentication.Initialize();\n                    Roles.DeleteCookie();\n                    context.Session.Clear();\n                }\n                catch (Exception ex)\n                {\n                    ErrorHandler.HandleException(ex);\n                }\n                finally\n                {\n                    FormsAuthentication.RedirectToLoginPage();\n//or can send to some other page\n                    string OriginalUrl = context.Request.RawUrl;\n                    string LoginPageUrl = @"~\Login.aspx";\n                    context.Response.Redirect(String.Format("{0}?ReturnUrl={1}", LoginPageUrl, context.Server.UrlEncode(OriginalUrl)));\n                }\n            }	0
13147567	13147322	Change a ListBox Background Color	private void listBox_DrawItem(object sender, DrawItemEventArgs e)\n{\n    e.DrawBackground();\n    Graphics myCustomGraphic = e.Graphics;\n    myCustomGraphic.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds);\n    // Print text\n    e.DrawFocusRectangle();\n}	0
326319	326309	How will locking behave in .net?	public List<Object> Objects\n{\n    get\n    {\n        lock (container)\n        {\n            return this.container;\n        }\n    }\n}	0
23921583	23921377	Remove entities from collection	var group = Context.Groups.First(g => g.Id == group.Id); // if you're sure of existing\n foreach (var customer in group.Customers.ToList()) // ToList is required to avoid 'Collection was modified' exception, I think\n      Context.Customers.Remove(customer);\n Context.SaveChanges();	0
33084268	33083741	Compare words in text with items in listbox	using (var reader = File.OpenText("c:\file.txt"))\n        {\n            while (!reader.EndOfStream)\n            {\n                string line = reader.ReadLine();\n                if (!listBox.Items.Contains(line))\n                    listBox.Items.Add(line);\n            }\n        }	0
11362193	11361240	Dynamically resolve and cast base to derived type at runtime	private void OnAsyncResponseReceived<T>(T response) where T : Response {\n  messageBinder.Forward(response);\n}	0
28518869	28518807	Split using regexp with exceptions, avoid a rewrite of Split function	(?<!-),	0
16322192	12083630	How do I send a POST request in RestSharp?	foreach (var pair in data) \n{ \n    request.AddParameter(pair.Key, pair.Value); \n}	0
24294541	24293646	Is there a code pattern for mapping a CSV with random column order to defined properties?	// Parse first line of text to add column heading strings and positions to your dictionary\n...\n\n// Parse data row into an array, indexed by column position\n...\n\n// Assign data to object properties\nx.ID = row[myDictionary["ID"]];\nx.FirstName = row[myDictionary["FirstName"]];\n...	0
19967288	19967019	Registering commands with its handlers using reflection	var methods = campaignCommandHandler.GetType().GetMethods().Where(x => x.Name == "Handle");\nforeach(var method in methods)\n{\n    var parameter = method.GetParameters().FirstOrDefault(x => typeof(Command).IsAssignableFrom(x.ParameterType));\n    if(parameter == null)\n    {\n        continue;\n    }\n    var commandType    = parameter.ParameterType;\n    var handler        = method.CreateDelegate(typeof(Action<>).MakeGenericType(commandType), campaignCommandHandler);\n    var registerMethod = commandService.GetType().GetMethod("RegisterHandler").MakeGenericMethod(commandType);\n\n    registerMethod.Invoke(commandService, new object[] { handler });\n}	0
20682285	20681700	Using invoke without a control	void Main()\n{\n    using (var fm = new Form())\n    {\n        var btn = new Button();\n        fm.Controls.Add(btn);\n        btn.Click += HandleClick;\n\n        Thread.CurrentThread.ManagedThreadId.Dump("Main thread");\n        fm.ShowDialog();\n    }\n}\n\npublic static void HandleClick(object sender, EventArgs e)\n{\n    var synchronizationContext = SynchronizationContext.Current;\n    var thread = new Thread(new ThreadStart(\n        () => BackgroundMethod(synchronizationContext)));\n    thread.Start();\n}\n\npublic static void BackgroundMethod(SynchronizationContext context)\n{\n    context.Post(state =>\n    {\n        Thread.CurrentThread.ManagedThreadId.Dump("Invoked thread");\n    }, null);\n}	0
2256149	2205993	winforms connection properties dialog for configuration string	using MSDASC;\nusing ADODB;\n\nprivate string BuildConnectionString()\n{\n     string strConnString = "";\n     object _con = null;\n     MSDASC.DataLinks _link = new MSDASC.DataLinks();\n     _con = _link.PromptNew();\n     if (_con == null) return string.Empty;\n     strConnString = ((ADODB.Connection)_con).ConnectionString;\n     return strConnString;\n}	0
3622872	3622443	Passing different content that implements the same interface	items = cms.GetArticles().Cast<IContent>().ToList();	0
4174347	4119608	Background Image on button created with Blend3	ImageBrush brush = new ImageBrush(new BitmapImage(new Uri("pack://siteoforigin:,,,/images/yourimage.gif")));\nbrush.Stretch = Stretch.Uniform;\nbtn.Background = brush;	0
20422140	20421591	How do I select an object by a sub-property	var query = from Product product in pc\n            from varsion in product.Version\n            let v= varsion as Entity.Version\n            where  v.id == g\n            select product;	0
905596	905582	How to Make a Text Box Equal All Letters To The Left of a Specific Letter or Character From Another Text Box in C#	string text = textbox1.Text;\ntextbox2.text = text.Substring(0, text.indexOf("-"));	0
457367	457360	C# How can I hide the cursor in a winforms app?	Cursor.Hide();	0
25150312	25150286	How do I escape quotes in a string variable?	"<font color=\"898A8E\">"\n             ^       ^	0
13267144	13266995	Random Color Generation in particular range	Random random = new Random();\nbyte randomNumber = (byte) random.Next(20, 256);\nColor blueish = Color.FromRgb(20, 20, randomNumber);	0
16921759	16921730	Controller's actions in c#	[HttpPost]	0
5354462	5354362	Distributed critical section in web-farm	set transaction isolation serializable;\nupdate t set lock = 1 where lock = 0;	0
20526392	20526173	Parse string with arithmetic operation	String sExpression = "23 + 323 =";\nint nResult = 0;\nMatch oMatch = Regex.Match(@"(\d+)\s*([+-*/])\s*(\d+)(\s*=)?")\nif(oMatch.Success)\n{\n    int a = Convert.ToInt32(oMatch.Groups[1].Value);\n    int b = Convert.ToInt32(oMatch.Groups[3].Value);\n    switch(oMatch.Groups[2].Value)\n    {\n        case '+';\n            nResult = a + b;\n            break;\n        case '-';\n            nResult = a - b;\n            break;\n        case '*';\n            nResult = a * b;\n            break;\n        case '/';\n            nResult = a / b;\n            break;\n    }\n}	0
14268479	14268439	Access all items inside List<T> in a random order	Random rnd = new Random();\nforeach(var elem in list.OrderBy(x => rnd.Next()))\n{\n\n}	0
6349719	6349286	How to bind with XAML	public MyClass SingletonInst\n{\n    get { return MyClass.Instance;}\n}	0
8425298	8425220	Using a List of a List as a Lookup Property for IEnumerable<T>.ToLookup()	persons.SelectMany(p => p.PersonalEffects.Select(e => new { Person = p, Effect = e }))\n       .ToLookup(o => o.Effect, o => o.Person);	0
32026098	32025891	C# how to access variables without creating an intance?	public class Worker {\n\n    public Economy InEconomy { get; private set; }\n    public int Wage { get; private set; }\n\n    // set the econdomy and wage in the constructor\n    public Worker(Economy economy, int wage) {\n        this.Wage = wage;\n        this.InEconomy = economy;\n    }\n\n    public void Pay() {\n        InEconomy.money -= this.Wage;\n    }\n}\n\npublic class Economy {\n    public int money;\n}	0
5290710	5290690	Creating a new background thread each time I invoke specific method	public void Example()\n    {\n        //call using a thread.\n        ThreadPool.QueueUserWorkItem(p => check_news("title", "news message"));\n    }\n\n    private void check_news(string news, string newsMessage)\n    {\n\n    }	0
10535277	10535199	Another BCD byte[] to int and back again	//Array padded to 8 bytes, to represent a ulong\nbyte[] bytes = {0, 0, 0, 0, 0, 0xFF, 0xFF, 0xFE};\n\nvar longBytes = BitConverter.ToUInt64(bytes, 0);\n\nvar arrayBytes = BitConverter.GetBytes(longBytes);	0
7712690	7712613	LINQ query to group results into an array	IEnumerable<GroupItem> linqQuery = detailList\n    .GroupBy(i => i.A)\n    .Select(g => new GroupItem() \n    { \n        A = g.Key, \n        AllBsWithinA = g.Select(i => i.B).ToList() \n    });	0
13265069	13264853	xmlTextWriter does not save the XML file to bin folder	public void SerializeToXML(YourClass yourObj)\n    {\n        if (!File.Exists("C:\\Info.xml"))\n            File.Create("C:\\Info.xml");\n        XmlSerializer serializer = new XmlSerializer(typeof(YourClass));\n        System.IO.TextWriter textWriter = new StreamWriter("C:\\Info.xml");\n        serializer.Serialize(textWriter, yourObj);\n        textWriter.Close();\n    }	0
14307288	14307183	assigning a priority to processes before they are launched	public void StartProcessesByPriority(Dictionary<String, ProcessPriorityClass> values)\n{\n    List<KeyValuePair<String, ProcessPriorityClass>> valuesList = values.ToList();\n\n    valuesList.Sort\n    (\n        delegate(KeyValuePair<String, ProcessPriorityClass> left, KeyValuePair<String, ProcessPriorityClass> right)\n        {\n            return left.Value.CompareTo(right.Value);\n        }\n    );\n\n    foreach (KeyValuePair<String, ProcessPriorityClass> pair in valuesList)\n    {\n        Process process = new Process();\n        process.StartInfo.FileName = pair.Key;\n        process.Start();\n\n        process.PriorityClass = pair.Value;\n\n        process.WaitForExit();\n    }\n}	0
27915672	27913802	How to join DataTable	DataTable dt1 = new DataTable("Table1");\n        DataTable dt2 = new DataTable("Table2");\n        DataTable dt3 = new DataTable("Table3");\n\n        if (dt1.Rows[0]["A1"] == dt2.Rows[0]["A2"])\n        {\n            dt3.Rows.Add(dt1.Rows[0]["A1"].ToString(), dt1.Rows[0]["B1"].ToString(), dt1.Rows[0]["C1"].ToString(), Convert.ToInt32(dt1.Rows[0]["D1"]) + Convert.ToInt32(dt1.Rows[0]["D2"]));\n        }	0
20145565	20145484	Adding cell row to int array	DriverNames[z] = row.Cells[0].Value != null ? int.Parse(row.Cells[0].Value.ToString()) : 0;	0
19752751	19739458	Change Application Title (Color, Location, Font) -Wp7	var imageUri = DrawTileImage(); //here you should draw an image with transparent \n                                //background and any icons/text layout \nStandardTileData NewTileData = new StandardTileData\n{ \n       Title = string.Empty,\n       BackgroundImage = imageUri,\n};	0
8756177	8755942	Deserializing char from xml	public string MyCharString { get; set; }\n\n    [XmlIgnore]\n    public char MyChar\n    {\n        get\n        {\n            return Convert.ToChar(MyCharString);\n        }\n    }	0
24664020	24663941	deserializing dynamic JSON response	[JsonProperty("external_urls")]\n public Dictionary<string,string> ExternalUrls { get; set; }	0
4137373	4137300	Show only selected rows in Gridview	DataTable table = DataSet1.Tables["Orders"];\n// Presuming the DataTable has a column named Date.\nstring expression;\nexpression = "Date > #1/1/00#";\nDataRow[] foundRows;\n\n// Use the Select method to find all rows matching the filter.\nfoundRows = table.Select(expression);\n\n// Print column 0 of each returned row.\nfor(int i = 0; i < foundRows.Length; i ++)\n{\n    Console.WriteLine(foundRows[i][0]);\n}	0
14982074	14979048	Install IIS from batch file - get error windows package manager	/l:log.etw	0
13912583	13910726	Entity Framework code first in data access layer	public List<DomainObject.ContractCenter> GetAll()\n{\n    try\n    {\n        using (var context = new DBContext())\n        {\n            return context.ContractCenters.\n                           Include(c => c.YourChildCollection1).\n                           Include(c => c.YourChildCollection2).\n                           ...\n                           ToList();\n        }\n    }\n}	0
13753422	13752373	Dynamically create members of interface	public static void SetData<T>(T obj)\n{\n  foreach (var property in typeof(T).GetProperties())\n    if (property.CanWrite && property.GetIndexParameters().Length == 0)\n    {\n      object val = null;\n\n      //// Optionally some custom logic if you like:\n      //if (property.PropertyType == typeof(string))\n      //    val = "Jan-Peter Vos";\n      //else\n\n        val = Activator.CreateInstance(property.PropertyType);\n\n      property.SetValue(obj, val, null);\n    }\n}\n\n[Test]\npublic void FirstSteps()\n{\n  // .. Your code ..\n\n  SetData(view);\n}	0
3373698	3373548	C#.net Populate a datagrid from the result of a .bat file	string[] input = myOutput.ReadToEnd().Split('\n');\n\n        DataTable table = new DataTable();\n\n        table.Columns.Add(new DataColumn("UserName", typeof(string)));\n        table.Columns.Add(new DataColumn("SessionId", typeof(string)));\n\n        foreach (string item in input)\n        {\n            DataRow row = table.NewRow();\n            row[0] = item.Split(',')[0];\n            row[1] = item.Split(',')[1];\n            table.Rows.Add(row);\n        }\n\n        myGridView.DataSource = table;\n\n        // for WebForms:\n        myGridView.DataBind();	0
20423063	20422910	Change all the colours of text in rows in a column depending on the column name (datagrid)	dataGridView1.Columns["DatePaid"].DefaultCellStyle.ForeColor = Color.Blue;	0
3486749	3486734	How can I edit a text file using C#?	void ConvertFile(string inPath, string outPath)\n{\n    using (var reader = new StreamReader(inPath))\n    using (var writer = new StreamWriter (outPath))\n    {\n        string line = reader.ReadLine();\n        while (line != null)\n        {\n            writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());\n            line = reader.ReadLine ();    \n        }\n    }\n}	0
15985204	15983413	How do I add my mono Program to the startup?	description "My Mono app"\n\nstart on runlevel [2345]\nstop on runlevel [016]\n\nsetuid nobody\nsetgid nogroup\nrespawn\nconsole log\n\nexec /path/to/app.exe	0
1922823	1922790	Creating and saving a text file from a c# ASP.NET app	Response.ClearContent();\nResponse.ClearHeaders();\nResponse.ContentType="text/plain";\nResponse.AppendHeader( "content-disposition", "attachment; filename=" + filename );\nResponse.AppendHeader( "content-length", fileContents.Length );\nResponse.BinaryWrite( fileContents );\nResponse.Flush();\nResponse.End();	0
24884396	24735022	How to get the applied style name in word template from C#	Object styleobject = document.Application.Selection.get_Style();\nstring stylename=((Word.Style)styleobject).NameLocal;	0
19806550	19806350	TeamCity build differs from Visual Studio 2010 build	corflags /32BITREQ+ result.exe	0
18158705	18158693	RegEx Escaping Comma	Match match = Regex.Match(response.Content, @"([0-9]+)"",""display");	0
13784943	13302602	Select distinct rows from a table using massive ORM	dynamic studentTable = new Students();\nvar students = studentTable.All(columns: "distinct StudentName");	0
2041049	2041000	Loop through all the resources in a .resx file	using System.Collections;\nusing System.Globalization;\nusing System.Resources;\n\n...\n\nResourceSet resourceSet = MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);\nforeach (DictionaryEntry entry in resourceSet)\n{\n    string resourceKey = entry.Key;\n    object resource = entry.Value;\n}	0
24191677	21454309	Loop on INI file sections	ini["MySection"]["MyKey"] = "MyValue";	0
30238037	30237253	Separate lists of words for nouns, verbs, adjectives, etc	var txt5 = "abactinal a 1 1 ! 1 0 01665972\r\nabandoned a 2 1 & 2 1 01313004 01317231\r\nabandon v 2 1 & 2 1 01313004 01317231  ";\nvar dic = new List<KeyValuePair<string, string>>();\nvar lines = txt5.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries);\nforeach (var line in lines)\n{\n     var cells = line.Split();\n     switch (cells[1])\n     { \n        case "a":\n          dic.Add(new KeyValuePair<string, string>("adjective", cells[0]));\n          break;\n        case "v":\n          dic.Add(new KeyValuePair<string, string>("verb", cells[0]));\n          break;\n        // Add more to cover all POS values\n        default:\n          break;\n      }\n }	0
16569548	16568570	Entity Framework: search for database entries with null fields	FactCache fact = db.FactCache.FirstOrDefault(\n  a => false == a.InputResourceID.HasValue\n  && false == a.PhaseID.HasValue\n  && a.MonthDate == monthDate\n  && a.AttributeKey == key);	0
24578893	24549279	Windows phone create animation of controls	dAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(5000));	0
24814761	24814681	How to strip blocks out of an IEnumerable?	inputArray.Select((item, index) => new {item, groupIndex = index / 8})\n          .GroupBy(x => x.groupIndex)\n          .Where(g => g.All(x => x.item != 0))\n          //.Select(g => g.First().item)\n          .SelectMany(g => g.Select(x => x.item))	0
15491971	15491940	String extraction confusion in C#	string fileName = Path.GetFileNameWithoutExtension(path);\nstring firstFourCharacters = fileName.Take(4);\n//Or \n//Check if the fileName.Length >= 4\nstring firstFourCharacters = fileName.Substring(0,4);	0
5519509	3245026	Getting DB Server DateTime in application	var dateQuery = yourDbContext.CreateQuery<DateTime>("CurrentDateTime() ");\nDateTime dateFromSql = dateQuery .AsEnumerable().First();	0
22037945	22037625	MVVMCross MvxBind, binding multiple values to one property	local:MvxBind="Enabled (IHaveDoneThis || IHaveDoneThat)"	0
9081102	9079118	how to insert dynamically image in crystal report	'C:\Id Maker\' + {table.Clgid} + '.jpg'	0
729439	729430	C# How to invoke with more than one parameter	public void DoSomething(string foo, int bar)\n{\n    if (this.InvokeRequired) {\n        this.Invoke((MethodInvoker)delegate {\n            DoSomething(foo,bar);\n        });\n        return;\n    }\n    // do something with foo and bar\n    this.Text = foo;\n    Console.WriteLine(bar);\n}	0
16061508	16061399	Validate one method C#	public bool IsValidated()\n    {\n    return !String.IsNullOrEmpty(textBox1.Text);\n    }\nprivate void button4_Click(object sender, EventArgs e)\n{\n        bool passed = IsValidated();\n}	0
6771259	6771236	How to Randomly Set Initial Index Declaratively or in Code?	myDropDownList.SelectedIndex = new System.Random().Next (myDropDownList.Items.Count);	0
24251741	24251634	How to take the output of a BAT file and save it to a string	void Main()\n{\n    StringBuilder sb = new StringBuilder();\n    var pSpawn = new Process\n    {\n         StartInfo = \n         { \n            WorkingDirectory = @"D:\temp", \n            FileName = "cmd.exe", \n            Arguments ="/c dir /b", \n            CreateNoWindow = true,\n            RedirectStandardOutput = true,\n            RedirectStandardInput = true,\n            UseShellExecute = false\n         }\n    };\n\n\n    pSpawn.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);\n    pSpawn.Start();\n    pSpawn.BeginOutputReadLine();\n    pSpawn.WaitForExit();\n    Console.WriteLine(sb.ToString());\n}	0
3196753	3196727	Getting html source from url, css inline problem!	using (var client = new WebClient())\n{\n    client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4";\n    string html = client.DownloadString(url);\n}	0
32409602	32408979	Track KeyPresses & Modifier Keys when window is minimized and log into a file	low level keyboard hooks	0
9461640	9461612	Change rows & colums in code-behind	Grid.SetRow(<your element>, <new row>)\nGrid.SetColumn(<your element>, <new column>)	0
23515178	23512584	Use ConfigureAwait(false) in a Windows Service?	fooTask.ConfigureAwait(false)	0
719602	719510	Linq - How to aggregate the results of another query	( from f in GetFooList()\n  where f.A > 3\n  group f by 1 into g\n  let MinA=g.Min(l=>l.A)\n  let MaxB=g.Max(h=>h.B)\n  select new {MinA, MaxB} ).SingleOrDefault()	0
9277083	9276983	Sort a Dictionary<int, List<int>> by keys + values inside list	// Creating test data\n    var dictionary = new Dictionary<int, IList<int>>\n    {\n        { 1, new List<int> { 2, 1, 6 } },\n        { 5, new List<int> { 2, 1 } },\n        { 2, new List<int> { 2, 3 } }\n    };\n\n    // Ordering as requested\n    dictionary = dictionary\n        .OrderBy(d => d.Key)\n        .ToDictionary(\n            d => d.Key,\n            d => (IList<int>)d.Value.OrderBy(v => v).ToList()\n        );\n\n    // Displaying the results\n    foreach(var kv in dictionary)\n    {\n        Console.Write("\n{0}", kv.Key);\n        foreach (var li in kv.Value)\n        {\n            Console.Write("\t{0}", li);\n        }\n    }	0
1252614	1252613	Handling Cancel Button in Yes/No/Cancel Messagebox in FormClosing Method	private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {\n    // Set e.Cancel to Boolean true to cancel closing the form\n}	0
28566623	28566541	How to use CanClose()?	CanClose( p => {  DoSomething(); } );	0
2327683	2327667	Quantity of specific strings inside a string	string s = "Whatever text FFF you can FFF imagine";\n\nConsole.WriteLine(Regex.Matches(s, Regex.Escape("FFF")).Count);	0
19759649	19759570	401 Error on connecting to github API from c# console app	WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");\nrequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));\n\nWebResponse response = request.GetResponse();	0
18963686	18962253	MVC4 query string to an Action	[HttpPost]\npublic virtual ActionResult TaskCreateWithModel(string schemaType, Task model)	0
16476759	16459156	Unable to save changes to xml file	serverlist.xml	0
2906654	2906613	How do you store calendar month and days in array?	GregorianCalendar calendar = new GregorianCalendar();\nstring[][] values = new string[12][];\nfor (int i = 0; i < 12; i++)\n{\n    values[i] = new string[calendar.GetDaysInMonth(year, i + 1)];\n}	0
11926786	11924707	How to interop between C# and c++	#ifdef __cplusplus\nextern "C" {\n#endif\n\n__declspec(dllexport) void D()\n{\n}\n\n#ifdef __cplusplus\n}\n#endif	0
12627486	12626544	WebBrowser control - wait for page loading after submit form	private void Form1_Load(object sender, EventArgs e)\n{\n   webBrowser1.Navigate("google.com");\n   webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);\n}\n\nvoid webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n   MessageBox.Show("Completed Now!");\n}	0
6942928	6942790	Ordering lists within a list in C#	var sorted = people.OrderBy(p => p.Sites.First().Organization)\n                   .ThenBy(p => p.LastName)\n                   .ThenBy(p => p.FirstName);	0
12253897	12253714	Dynamically create controls based on solution folder content	Control myControl = new Control();\nstring[] filePaths = Directory.GetFiles(@"c:\images\");\n\nforeach (string file in filePaths)\n{\n    Image image = new Image();\n    image.ImageUrl = file;\n    myControl.Controls.Add(image);\n}\n\nPage.Controls.Add(myControl);	0
2240606	2240346	How to convert an IEnumerable<IEnumerable<T>> to a IEnumerable<T>	var strings = combinedResults.Select\n    (\n        c => c.Where(i => i > 0)\n        .Select(i => i.ToString())\n    ).Where(s => s.Any())\n    .Select(s => String.Join(",", s.ToArray());	0
14958747	14958655	Execute two buttons with single click	private void Form1_Load(object sender, EventArgs e)\n{\n    webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;\n}    \n\nvoid webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    button2_Click(sender, e);\n}	0
26279705	26279614	Linq search for any of words in term	//split the search terms by space\nvar searchWords = searchTerm.ToLower().Split( " ".ToCharArray(), \n                          StringSplitOptions.RemoveEmptyEntries);\n\n//check if any of those search terms is present\nlist.Where(x => x.MyList.Any(y => \n        searchWords.All(sw=>y.ToSearch.ToLower().Contains(sw))));	0
3910511	3233089	How to make a control with children without declaring the template tag?	[ParseChildren(false)]\n[PersistChildren(true)]\npublic class MyControl : CompositeControl \n{\n    public override void RenderBeginTag(HtmlTextWriter writer)\n    {\n        base.RenderBeginTag(writer); // TODO: Do something else here if needed\n    }     \n\n    public override void RenderEndTag(HtmlTextWriter writer)\n    {\n        base.RenderEndTag(writer); // TODO: Do something else here if needed\n    }\n}	0
921303	921106	How to create ADO.NET Entity Framework ObjectContext extensions	public static class MyExtensions\n{\n    // extension methods go here\n}	0
18062942	18028181	Iterate though quadtree children	int max = trees.Count;\n        for (int i = 0; i < max; i++)\n        {\n            QuadTree tree = trees[i];\n            if (tree.Children.Count != 0)\n            {\n                foreach(QuadTree child in tree.Children)\n                {\n                    trees.Add(child);\n                }\n            }\n            max = trees.Count;\n        }	0
5930520	5930332	Using extension methods through the TryInvokeMember override of a DynamicObject	Dictionary<Type,ICollection<MethodInfo>>	0
586303	389763	How to install CodeRush Xpress on VS2005	Windows Registry Editor Version 5.00\n[HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express]\n[HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express\CodeRush for VS\3.2]\n    "HideMenu"=dword:00000000\n    "LoadDXPlugInsOnly"=dword:00000000\n    "StatusTextEnabled"=dword:00000001	0
5622774	5622442	Programmatically changing button label in Monotouch	btnActies.SetTitle ("title", UIControlState.Normal);	0
5089760	5087639	Copy a set of records from one sql-server to another using c# and entity framework	Customer customer = null;\nusing (var context = new MyContext("ProductionConnectionString"))\n{\n  // You must use Include to load all related data\n  customer = context.Customers.Include("...").Where(...).Single();\n}\n\nusing (var context= new MyContext("TestConnectionString"))\n{\n  context.Customers.AddObject(customer); // Inserts everything\n  using (var scope = new TransactionScope())\n  {\n    context.SaveChanges();\n    scope.Complete();\n  }\n}	0
27109318	27109056	Add items to a list of objects, where the list itself is of type T	private static T Get<T>() where T : IList\n{\n    T list = Activator.CreateInstance<T>(); \n    int a = 1;\n    (list as IList).Add(a);\n    return list;\n}	0
28997485	28997407	Ignore the first occurence of a character if it exists later	{(?<token>{?[^}]+}?)}	0
2427986	2411562	Getting run-time value of a ParameterExpression in a expression tree	// Replace Assign in your Block expression.\nExpression.Assign(variableTest, Expression.Lambda<Func<ParameterExpression>>(Expression.ArrayIndex(Expression.Constant(paramDefs), Expression.Constant(0))).Compile()()),	0
26288219	26285798	Wrap specflow scenario within try-catch	[AfterStep]\n    public void check()\n    {\n        var exception = ScenarioContext.Current.TestError;\n        if (exception is WebDriverException \n            && exception.Message.Contains("The HTTP request to the remote WebDriver server for URL "))\n        {\n            Assert.Inconclusive(exception.Message);\n        }\n    }	0
23627897	23627853	resx file access	Properties.Resources.MyString	0
23975558	23975500	Trying to load an XML into a class object using XElement and LINQ	Name = p.Attribute("Name").Value,\n              Type = (EnvironmentType)Enum.Parse(typeof\n             (EnvironmentType), p.Attribute("Type").Value, true),\n              DataCenters = p.Elements("DataCenter").Select(\n               dc => new DataCenter { \n                                      Name = dc.Attribute("Name").Value,                                      DeployEnvironmentName = dc.Attribute         \n                                     ("DeployEnvironmentName").Value                                      })\n                                });\n                                 ^^^\n            });	0
25429340	25428689	Populate list with missing dates LINQ	// ensure that it's sorted by date\npercentages.Sort((p1, p2) => p1.Date.CompareTo(p2.Date));\nList<Percentages> newPercentages = new List<Percentages>();\nforeach (Percentages percentage in percentages)\n{\n    Percentages lastPercentage = newPercentages.LastOrDefault();\n    if (lastPercentage != null)\n    {\n        TimeSpan diff = percentage.Date - lastPercentage.Date;\n        int missingMinutes = (int)diff.TotalMinutes - 1;\n        if(missingMinutes > 0)\n        {\n          var missing = Enumerable.Range(1, missingMinutes)\n            .Select(n => new Percentages\n            {\n                Date = lastPercentage.Date.AddMinutes(n),\n                Average = lastPercentage.Average,\n                High = lastPercentage.High,\n                Low = lastPercentage.Low\n            });\n          newPercentages.AddRange(missing);\n        }\n    }\n    newPercentages.Add(percentage);\n}	0
26900509	26900366	How to bind an object to a list?	public T AddComponent<T>()\n{\n    GenericComponent<Object> newComponent = new GenericComponent<Object>();\n    newComponent.component = (T)Activator.CreateInstance(typeof(T));\n    componentList.Add(newComponent);\n    return (T)newComponent.component;\n}	0
1511033	1510928	Is making my clickonce app partial-trust worth it?	permission.Assert();	0
24142253	24142103	Interface segregation principle usage	public interface IHungryRunner : IRunnable, IEatable\n{ }	0
22701154	22700968	How to convert an object having rows into a datatable	static DataTable GetTable(List<Object> yourObjectList)\n{\n// This is assuming you have a list of objects\nvar _firstObject = yourObjectList.First();\nvar table = new DataTable();\n\n// Do this multiple times for each parameter you have. \ntable.Columns.Add(_firstObject.ParamaterName, typeof(string));\n\nforeach(var obj in yourObjectList)\n{\ntable.Rows.Add(obj.ParamaterName, obj.ParamaterName2, etc);\n}\nreturn table;\n}	0
33583655	33583387	How to store multiple values into an array and then to DB?	var sb = new StringBuilder();\n foreach (DataGridViewRow row in dataGridView1.Rows)\n {    \n     sb.Append('<');\n     foreach (DataGridViewColumn col in dataGridView1.Columns)\n     {\n            sb.Append(dataGridView1.Rows[row.Index].Cells[col.Index].Value);\n            sb.Append(' ');\n     }\n     sb.Append('>');\n }\n var toInvoiceField = sb.ToString();	0
4008992	4008975	drawing a string with a transparent background using C#?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        this.Paint += new PaintEventHandler(Form1_Paint);\n\n    }\n\n    void Form1_Paint(object sender, PaintEventArgs e)\n    {\n        e.Graphics.DrawString("hello", new Font("Arial", 36), new SolidBrush(Color.FromArgb(255,0,0)), new Point(20,20));\n        e.Graphics.DrawString("world", new Font("Arial", 36), new SolidBrush(Color.FromArgb(0,0,255)), new Point(30,30));\n\n    }\n\n}	0
6708865	6708733	How do I implement this Custom Equality?	public sealed class Symbol : IEquatable<Symbol>\n    {\n        public string FileName { get; set; }\n        public DateTime FileDate { get; set; }\n        public long CRC32 { get; set; }\n\n        public bool Equals(Symbol other)\n        {\n            if (other == null)\n            {\n                return false;\n            }\n\n            return FileName == other.FileName &&\n                   (FileDate == other.FileDate || CRC32 == other.CRC32);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as Symbol);\n        }\n\n        public override int GetHashCode()\n        {\n            // since FileName must be equal (others may or may not)\n            // can use its hash code as your surrogate hash code.\n            return FileName.GetHashCode();\n        }\n    }	0
2730746	2730734	Is there a built-in .NET method for getting all of the properties and values for an object?	string value = new JavaScriptSerializer().Serialize(myItem);	0
4650343	4650307	How to insert an integer into a database through command prompt	string insertString = @"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES ("\n+ UserID + ",'Ted','Turner')";	0
20307517	20307491	How can declare & initialize a property in the same statement?	public class GridModel : PropertyChangedBase\n{\n    private List<string> leftValue = new List<string> { "Alpha", "Beta", "Gamma" };\n\n    public List<string> LeftValue \n    { \n        get\n        {\n            return leftValue;\n        }\n        set\n        {\n            leftValue = value;\n        } \n    }\n\n    [...]\n}	0
13553502	13553437	Group By List with Lambda	int topSource = list.GroupBy(o => o.source)\n                    .OrderByDescending(g => g.Count())\n                    .First()\n                    .Key;	0
29114406	29114243	How to extract AnonymousType Programmically?	public class Program \n{\n    public static void Main() \n    {\n        Extract(new { Name = "Yoza" });\n        Extract(new [] { new { Name = "Yoza" }, new { Name = "Dhika" } });\n    }\n\n    private static void Extract(object param = null) \n    {\n        if (param.GetType().IsArray) \n        {\n            var array = param as Array;\n            foreach(var element in array) \n            {\n                foreach(var item in element.GetType().GetProperties()) \n                {\n                    Console.WriteLine(string.Format("{0}: {1}", item.Name, item.GetValue(element)));\n                }\n            }\n        } \n        else \n        {\n            foreach(var item in param.GetType().GetProperties()) \n            {\n                Console.WriteLine(string.Format("{0}: {1}", item.Name, item.GetValue(param)));\n                item.GetValue(param);\n            }\n        }\n    }\n}	0
21411073	21410219	How to unlock Sqlite Database after delete	var ThisTrans = await db.QueryAsync<TransactionLine>("Select * From TransactionLine    Where  Tid = '" + PassInTransId + "'");\nforeach (var line in ThisTrans)\n{\n    var intDelStatus = await db.DeleteAsync(line);\n}	0
32586911	32586359	Button BackColor doesn't change	public void ClickedButton (object sender, EventArgs e)\n{\n    var btn = sender as Button;\n    if ((btn != null) && btn.BackColor == System.Drawing.SystemColors.Control)) {\n        btn.BackColor = Color.Turquoise;\n    }\n}	0
5034715	5034660	How to retrieve the client's machine name from within a WCF Operation Contract?	RemoteEndpointMessageProperty messageProperty = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;\nConsole.WriteLine("Remote address is: {0}", messageProperty.Address);	0
9746848	9727133	How to set Storyboard.SetTargetProperty in Code behind?	new PropertyPath("RenderTransform.Children[0].ScaleY")	0
21289342	21284741	Inherit from a class that inherit from a UIVIewcontroller (xamarin and c#)	[Register("A")]\npublic class A : UIViewController { }\n\n[Register("B")]\npublic class B : A { }	0
14871179	14870612	Grouping and Sum DataTable Rows without Linq	var allProducts = context.Products.Where(.....what products you want to take from     db).ToList();\n\n   Dictionary<String, Int32> dictionary = new Dictionary<String, Int32>();\n   foreach(var product in allProducts)\n   {\n      Int32 value = 0;\n      if(!dictionary.TryGetValue(product.Name, out value))\n      {\n         dictionary.Add(product.Name, product.Price);\n         continue;\n      }\n            value += product.Price;\n            dictionary[product.Name] = value;\n   }	0
24005461	23994505	How would you go about detecting events defined by libraries in other classes?	SdlDotNet.Core.Events.Quit += new QuitArgs(detectClose);	0
23090208	20669922	Get all Members from Domain Local Group across multi-forest environment	if (de.Properties["objectClass"].Contains("foreignSecurityPrincipal"))\n{\n    // use this value in a search condition for objectSid\n    var sidString = de.Properties["cn"].Cast<string>().First();\n\n    IdentityReference id = new SecurityIdentifier(sid);\n\n    var account = id.Translate(typeof(NTAccount)).ToString().Split('\\');\n\n    var userName = account[1];\n    var domainName = account[0];\n}	0
21463860	21458210	Omu.ValueInjecter checking property before allowing a set to occur	var source = new Source() { A = 3 };\nvar dest = new Dest();\ndest.InjectFrom<MyInjector>(source);\n\npublic class Source\n{\n    public int A { get; set; }\n    public bool SetA { get; set; }\n}\npublic class Dest\n{\n    public int A { get; set; }\n}\n\npublic class MyInjector : LoopValueInjection // or some other base class!\n{\n    protected override void Inject(object source, object target)\n    {\n        if (source is BaseEntityViewModel) _baseEntityViewModel = (BaseEntityViewModel)source;\n        base.Inject(source, target);\n    }\n    protected override bool UseSourceProp(string sourcePropName)\n    {\n        if (_baseEntityViewModel is BaseEntityViewModel)\n            return _baseEntityViewModel.SetProperties.Contains(sourcePropName);\n        else\n            return base.UseSourceProp(sourcePropName);\n    }\n}	0
1724999	1689089	Db4o query: find all objects with ID = {anything in array}	IList<SimpleObject> objs = new List<SimpleObject>();\nforeach(var tbf in ids)\n{\n     var result = from SimpleObject o in db()\n               where o.Id = tbf\n                  select o;\n\n     if (result.Count == 1)\n     {\n        objs.Add(result[0]);\n     }\n}	0
12345912	12345222	Split String results in uneven array item lengths due to trailing delimiters	string test = "[one]\t\t\t[two]\t\t\t";\nstring[] arrUnEven = test.Split(new char[] { '\t' }, StringSplitOptions.None);\n\ntest = test.TrimEnd(new char[] { '\t' });\ntest = test + new String( '\t',2);\nstring[] arrEven = test.Split(new char[] { '\t' }, StringSplitOptions.None);	0
5689004	5687355	Need help understanding how Ninject is getting a Nhibernate SessionFactory instance into a UnitOfWork?	Bind<ISession>().ToProvider<SessionProvider>().InRequestScope();	0
7134578	7134530	Correct way of Dictionary in a Dictionary Value?	Dictionary<string, Dictionary<string,List<string>>> pro = new Dictionary<string, Dictionary<string,List<string>>>()\n{\n    { "First", new Dictionary<string,List<string>>()\n        {\n            { "Part1", new List<string>() { "foo1", "foo2", "foo3" } },\n            { "Part2", new List<string>() { "bar1", "bar2", "bar3" } }\n        }\n    }\n};	0
17098182	17098129	Querying XML elements with identical name with Linq	var productTypes = from productType in xml.Elements("ProductType")\n                select new {\n                   Name = productType.Attribute("Name").Value,\n                   Amount = Convert.ToInt32(productType.Element("Amount").Value),\n                   // How to get all Pattern elements from that ProductType?\n                   Patterns = from patt in productType.Elements("Pattern")\n                              select new { Length = int.Parse(patt.Attribute("Length").Value),\n                                           .... }\n                 };	0
27243936	27243601	How to delete dynamically created textbox in asp.net	protected void Remove(object sender, EventArgs e)\n    {\n        foreach (Control control in PlaceHolder1.Controls)\n        {\n            //Here you need to take ID from ViewState["controlIdList"]\n            if (control.ID == "TakeIDFromControlListsID")\n            {\n                Controls.Remove(control);\n            }\n        }\n     }	0
27573414	27572844	How to pass values from a usercontrol to a customcontrol using style in Generic.xaml?	public static readonly DependencyProperty TextProperty =\n    TextBlock.TextProperty.AddOwner(typeof(ccTestFigure), new FrameworkPropertyMetadata(propertyChangedCallback: OnTextChanged));\n\nprivate static void OnTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)\n{\n    ((ccTestFigure)sender).UpdateText();\n}\n\nprivate void UpdateText() \n{\n    var typeface = new Typeface(\n                    FontFamily,\n                    FontStyle,\n                    FontWeights.Normal,\n                    FontStretches.Normal);\n\n   ft  = new FormattedText(\n           Text,\n           System.Threading.Thread.CurrentThread.CurrentCulture,\n           FlowDirection.LeftToRight,\n           typeface,\n           FontSize,\n           Foreground);\n}\n\npublic ccTestFigure()\n{\n}	0
17754373	17754287	Clearing all fields on a form with a master page	Content Place Holder\n-->LiteralControl\n   -->Other Control 1\n   -->Other Control 2\n   -->Other Control 3\n      -->Maybe another level 1\n      -->Maybe another level 2\n   -->Other Control 4	0
13255551	13034156	event fired at the end of scrolling in Silverlight	// uie is a UIElement\nIEnumerable<ScrollViewer> svList = uie.GetVisualDescendants<ScrollViewer>();\nif (svList.Count() > 0)\n{\n    // Visual States are always on the first child of the control\n    FrameworkElement element = VisualTreeHelper.GetChild(svList.First<ScrollViewer>(), 0) as FrameworkElement;\n    // getting all the visual state groups\n    IList groups = VisualStateManager.GetVisualStateGroups(element);\n    foreach (VisualStateGroup group in groups)\n    {\n        if (group.Name == "ScrollStates")\n        {\n            group.CurrentStateChanged += new EventHandler<VisualStateChangedEventArgs>(group_CurrentStateChanged);\n        }\n    }\n}\n\nprivate static void group_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)\n{\n    if (e.NewState.Name == "NotScrolling")\n    {\n        isNotScrolling = true;\n    }\n    else\n    {\n        isNotScrolling = false;\n    }\n}	0
28479101	28478859	print double with custom rounding and thousand separator	d.ToString("#,##0."+new string('#',(int)numUpDownRoundValue.Value))	0
1443373	1443363	Performing validation asp.net mvc without using models	class TestController : Controller\n{\n    [AcceptVerbs (HttpVerbs.Post)]\n    public ActionResult SomeAction (FormCollection form)\n    {\n        if (MyCustomValidation (form))\n            SaveData ();\n\n        RedirectToAction ("SomeAction");\n    }\n}	0
5397732	3293889	How to auto-detect Arduino COM port?	private string AutodetectArduinoPort()\n        {\n            ManagementScope connectionScope = new ManagementScope();\n            SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");\n            ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);\n\n            try\n            {\n                foreach (ManagementObject item in searcher.Get())\n                {\n                    string desc = item["Description"].ToString();\n                    string deviceId = item["DeviceID"].ToString();\n\n                    if (desc.Contains("Arduino"))\n                    {\n                        return deviceId;\n                    }\n                }\n            }\n            catch (ManagementException e)\n            {\n                /* Do Nothing */\n            }\n\n            return null;\n        }	0
16460192	16459913	Remove leading Characters and starting from Numeric	\d+.[a-zA-Z\ \d\#]*	0
6165386	6164782	Executing a process from .NET application without UAC prompt	Verb = "runas"	0
24307720	24307559	Initializing XAML user control	UserControl1 testUsrCtrl = new UserControl1();	0
18786554	18786526	How return value from anonymous method to label?	label1.Text = new Func<string>(() => { return "Some text"; })();	0
19163542	19163306	Get indices of top x equal elements	var items = new List<int> {1,1,2,3,4,4,5,6,7,7,8,9,10,11,11,12,13,13,13};\nint startIndex = items.IndexOf(items[items.Count - 1]);\nvar indexes = Enumerable.Range(startIndex, items.Count - startIndex);	0
3388297	3387203	COM interface disappears from ROT	::RegisterActiveObject(punk, CLSID_Interface, ACTIVEOBJECT_WEAK, &m_dwRegister);	0
2632887	2632806	How to Write to a User.Config file through ConfigurationManager?	Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);\nUserSettings settings;\nif ((settings = (UserSettings)configuration.Sections[GENERAL_USER_SETTINGS]) == null)\n{\n      settings = new UserSettings();\n      settings.SectionInformation.AllowExeDefinition =   \n                 ConfigurationAllowExeDefinition.MachineToLocalUser;\n      configuration.Sections.Add(GENERAL_USER_SETTINGS, settings);\n      configuration.Save();\n}	0
31426221	31417261	Keeping a service alive throughout the lifetime of the application	protected IApplicationState AppState\n{\n    get { return _appstate ?? (_appstate = Mvx.GetSingleton<IApplicationState>()); }\n}\nprivate IApplicationState _appstate;	0
9403918	9403864	How can I call a function that requires a return value that calls WebClient?	static public void isBarcodeCorrectOnServer(string barcode, Action<string> completed)\n{\n    //..\n    wc.DownloadStringCompleted += (sender, e) =>\n    {\n       if (e.Error == null)\n       {\n            //Process the result...\n            data = e.Result;\n            completed(data);\n       }\n    };\n    //..\n}	0
21011929	20897971	How to get a Custom Attribute value of WCF Contract's Operation using IDispatchMessageInspector	private UserAction GetIntendedUserAction(OperationDescription opDesc)\n{\n    Type contractType = opDesc.DeclaringContract.ContractType;\n    var attr = contractType.GetMethod(opDesc.Name).GeCustomAttributes(typeof(RequestedAction), false) as RequestedAction[];\n    if (attr != null && attr.Length > 0)\n    {\n        return attr[0].ActionName;\n    }\n    else\n    {\n        return UserAction.Unknown;\n    }\n}\npublic enum UserAction\n{\n    Unknown = 0,\n    View = 1,\n    Control = 2,\n    SysAdmin = 3,\n}\n[AttributeUsage(AttributeTargets.Method)]\npublic class RequestedAction : Attribute\n{\n    public UserAction ActionName { get; set; }\n    public RequestedAction(UserAction action)\n    {\n        ActionName = action;\n    }\n}	0
30489885	30486789	Signalr create two connection to two different hubs	var hubConnection = new HubConnection("http://localhost:14382");\nvar proxy1 = hubConnection.CreateHubProxy("Hub1");\nvar proxy2 = hubConnection.CreateHubProxy("Hub2");\nhubConnection.Start().Wait();	0
8609937	8609893	updating a database record with linq to sql in c#	var TheObjectInDB = (from o in TheDC.TheObjects\n                          where o.ObjectID == TheObject.ObjectID\n                          select o).SingleOrDefault();	0
19435473	19435458	Remove front characters from a string?	sName = sName.Substring(5)	0
33904500	33904291	C# reading each word in column in a text file	string[] lines = File.ReadAllLines(path);\nif (!String.IsNullOrEmpty(txt_uname.Text) \n     && lines.Where(u => u.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries)[1].Equals(txt_uname.Text)).Count() > 0)\n{ }	0
14100380	14099874	How to add a delete command button in devExpress gridview from codebehind?	protected void Page_Init(object sender, EventArgs e)\n{\n    GridViewCommandColumn column = new GridViewCommandColumn("....");\n    column.DeleteButton.Visible = true;\n    column.DeleteButton.Image.Url = "set path here";\n    column.Visible = true;\n    column.VisibleIndex = 2;//place where you want it to display\n    ASPxGridView1.Columns.Add(column); \n}\nprotected void Page_Load(object sender, EventArgs e)\n{\n   // Bind Data here\n    BindData();\n}	0
2119043	2119013	How do I add the result of factorial values?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Task_8_Set_III\n{\n    class Program                       \n     {\n        static void Main(string[] args)\n        {\n            double sum = 0;\n            for (int i = 1; i <= 7; i++)\n            {\n                double c = i / fact(i);\n                sum += c;\n                Console.WriteLine("Factorial is : " + c);\n                Console.ReadLine();\n                Console.WriteLine("By Adding.. will give " + sum);\n\n            }\n        }\n        static double fact(double value)\n        {\n            if (value ==1)\n            {\n                return 1;\n            }\n            else\n            {\n                return (value * (fact(value - 1)));\n            }\n        }\n    }\n}	0
5916225	5916205	ASP.NET - Accessing Session Variables from an outside application	select\n s.[SessionItemShort]\n,s.[SessionItemLong]\nfrom [ASPStateTempSessions] as s\nwhere s.[SessionId] = @sessionId	0
5579611	5578252	Validation in custom helper, null reference	var Label = htmlHelper.LabelFor(expression);\nvar Editor = htmlHelper.EditorFor(expression);\nvar Validation = htmlHelper.ValidationMessageFor(expression);\n\nliBuilder.InnerHtml = (Label == null ? "" : Label.ToString())\n                                + (Editor == null ? "" : Editor.ToString())\n                                + (Validation == null ? "" : Validation.ToString());	0
26611200	26488364	Group and sub group with linq	var query = from pro in products\n                       group pro by pro.CategoryName into newGroup1\n                       from newGroup2 in\n                           (from prod in newGroup1\n                            group prod by new { prod.DateLastModified.Year, prod.DateLastModified.Month } \n                           )\n                       group newGroup2 by newGroup1.Key;	0
4193727	4193708	How do I find the closest array element to an arbitrary (non-member) number?	Array.BinarySearch	0
6577559	6577452	Best way to find functions with regex?	Regex.Matches(source,@"([a-zA-Z0-9]*)\s*\([^()]*\)\s*{").Cast<Match>()\n    .Select (m => m.Groups[1].Captures[0].Value).ToArray()	0
5733320	5733232	How to scrape a page generated with a script in C#?	HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();\nHtmlAgilityPack.HtmlDocument doc = web.Load("http://www.google.com/search?q=foobar");\nstring html = doc.DocumentNode.OuterHtml;\nvar nodes = doc.DocumentNode.SelectNodes("//div"); //returns 85 nodes	0
15541153	15541045	C# - Failure sending mail	MailMessage mail = new MailMessage();\n mail.Subject = "Your Subject";\n mail.From = new MailAddress("senderMailAddress");\n mail.To.Add("ReceiverMailAddress");\n mail.Body = "Hello! your mail content goes here...";\n mail.IsBodyHtml = true;\n\n SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);\n smtp.EnableSsl = true;\n NetworkCredential netCre = new NetworkCredential("SenderMailAddress","SenderPassword" );\n smtp.Credentials = netCre;\n\n try\n  {\n   smtp.Send(mail);                \n  }\n  catch (Exception ex)\n  {               \n  }	0
6664213	6663769	OrderedCollection with Moveup And MoveDown	public static class ListExtensions\n{\n    public static void MoveUp<T>(this List<T> list, T item)\n    {\n        int index = list.IndexOf(item);\n\n        if (index == -1)\n        {\n            // item is not in the list\n            throw new ArgumentOutOfRangeException("item");\n        }\n\n        if (index == 0)\n        {\n            // item is on top\n            return;\n        }\n\n        list.Swap(index, index - 1);\n    }\n\n    public static void MoveDown<T>(this List<T> list, T item)\n    {\n        int index = list.IndexOf(item);\n\n        if (index == -1)\n        {\n            // item is not in the list\n            throw new ArgumentOutOfRangeException("item");\n        }\n\n        if (index == list.Count - 1)\n        {\n            // item is no bottom\n            return;\n        }\n\n        list.Swap(index, index + 1);\n    }\n\n    private static void Swap<T>(this List<T> list, int i1, int i2)\n    {\n        T temp = list[i1];\n        list[i1] = list[i2];\n        list[i2] = temp;\n    }\n}	0
18592221	18592101	How to access aspx control in code behind?	protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n    // Find the div control as htmlgenericcontrol type, if found apply style\n    System.Web.UI.HtmlControls.HtmlGenericControl div =  (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("DivContent");\n\n    if(div != null)\n        div.Style.Add("border-color", "Red");\n\n}	0
24528993	24528637	How to receive and process JSON data from a URL in C # Web Service?	string url = "http://example.com/MethodThatReturnsJson";\n\nusing (WebClient client = new WebClient())\n{\n    string webServiceJsonString = client.DownloadString(url);\n\n    YourObject yourObject = JsonConvert.DeserializeObject<YourObject>(webServiceJsonString);\n}	0
11054974	11054683	Setting DataGridView Row Heights Fast	public void PopulateData()\n    {\n        this.SuspendLayout();\n\n        DataGridViewRow[] rows = new DataGridViewRow[Data.RowCount];\n        for (int i = 0; i < rows.Length; i++)\n        {\n            DataGridViewRow row = new DataGridViewRow();\n            row.Height = Data.RowHeights[i];\n            rows[i] = row;\n        }\n        this.Rows.AddRange(rows);\n\n        this.ResumeLayout();\n    }	0
23186293	23179904	Read from html 5 local storage with selenium	value = (String) js.executeScript("return localStorage.getItem('key')");	0
18601184	18599974	How to query Active Directory for a user whose name contains a dollar sign ($)?	UserPrincipal user = UserPrincipal.FindByIdentity(context, "test$user");	0
29719195	29718898	LINQ Selecting a List within a List	vm.CGL1 = db.CallGuideArea.Select(\n                    a =>\n                        new CallGuideMenuL1\n                        {\n                            Area = a.Area,\n                            Products = a.CallGuideProducts.Select(p => new CallGuideMenuL2{CallGuideProductId=p.CallGuideProductId,Product=p.Product}).ToList()\n                        }).ToList();	0
9418566	9418517	How to force Console.WriteLine() to print verbatim strings?	string EscapeIt(string value) {\n  var builder = new StringBuilder();\n  foreach (var cur in value) {\n    switch (cur) {\n      case '\t': \n        builder.Append(@"\t");\n        break;\n      case '\r': \n        builder.Append(@"\r");\n        break;\n      case '\n':\n        builder.Append(@"\n");\n        break;\n      // etc ...\n      default:\n        builder.Append(cur);\n        break;\n    }\n  }\n  return builder.ToString();\n}	0
12490469	12489581	ContextMenu in ASPxHtmlEditor	protected void Page_Load(object sender, EventArgs e) {\n     if (!IsPostBack) {\n          MyHtmlEditor.ContextMenuItems.CreateDefaultItems();\n          MyHtmlEditor.ContextMenuItems.Insert(0, new HtmlEditorContextMenuItem("Add Title...", "AddTitle"));\n          MyHtmlEditor.ContextMenuItems.Insert(1, new HtmlEditorContextMenuItem("Change Title...", "ChangeTitle"));\n          MyHtmlEditor.ContextMenuItems.Insert(2, new HtmlEditorContextMenuItem("Remove Title", "RemoveTitle"));\n     }\n}	0
11454963	11454620	Open default browser from listView Subitem click	ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");  \nProcess.Start(sInfo);	0
18165589	18165307	MVC4 Pattern for receiving password reset token	WebSecurity.GeneratePasswordResetToken(email, 1440)	0
1292777	1292747	C# -Windows App - Regular Expression Help	// split on newline or comma\ntxtemailAddress.Text.Split(new[]{'\n', ','});	0
30631558	30609198	Linq to SQL query to find partial duplicates	var duplicates = (from z in dc.MyTables\n                  where (from a in\n                             (from b in dc.MyTables\n                              group b by new { b.ColumnA, b.ColumnB } into c\n                              select new\n                              {\n                                  ColumnA = c.Key.ColumnA,\n                                  ColumnB = c.Key.ColumnB\n                              })\n                             group a by a.ColumnA into d\n                             where d.Count() > 1\n                             select d.Key).Contains(z.ColumnA)\n                      orderby z.ColumnA ascending\n                      select new\n                      {\n                          ID = z.ID,\n                          ColumnA = z.CourseUrl2,\n                          ColumnB = z.ColumnB\n                      }).ToList();	0
2453391	2449459	Unable to add item to dataset in Linq to SQL	db.Categories.InsertOnSubmit(category);	0
7694093	7688566	Convert IObservable<byte[]> with irregular length byte arrays to IObservable<byte[]> with regular length arrays	Bytes\n        .SelectMany(b => b)\n        .Buffer(10)\n        .Select(bs => bs.ToArray());	0
13884993	13884872	How to properly model an XML node with Attributes?	public class Guid \n{\n    [XmlAttribute]\n    public bool IsPermaLink { get; set; }\n\n    // and the element value\n    [XmlTextAttribute]\n    public string Value;\n}\n\npublic class Item\n{\n    [XmlElement]\n    public Guid Guid { get; set; }\n}\n...\nvar theGuid = someItem.Guid.Value;\nvar guidIsPermaLink = someItem.Guid.IsPermaLink;	0
28429671	28429299	How to handle data from nested dictionary in C#	if (m_dictionary.Contains(s_title))\n    foreach(TClassType entry in m_dictionary[s_title].Values)\n        // Do something with the entry.	0
1728047	1728035	Deserialize Json in C# - How to Handle null Return Values	public string? name;	0
31680638	31679891	Windows Phone 8.1 Display Part of Webpage	(Install-Package HtmlAgilityPack)	0
19161366	19161147	Directory.GetFiles how to access subdirectories?	var allFiles = selDir.GetFiles("*.*", SearchOption.AllDirectories);	0
3759677	3759592	Finding File size in bit	long lengthInBits = new FileInfo(fileName).Length * 8;	0
6544697	6544558	Loop a DataGrid	myDGrid[rowIndex, colIndex];	0
20604581	20570392	WP8 Mail Pivot App	protected override async void OnNavigatedTo(NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n\n    try\n    {\n        await LayoutRoot.TransitionInSlideUp();\n    }\n    catch { }\n}	0
13040588	13040402	Need help translating function from c# to vb.net	Public Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)\n    Return Sub(a, b) f(a + x, b + y)\nEnd Function	0
2391755	2391743	How many elements of array are not null?	string[] strArray = new string[50];\n...\nint result = strArray.Count(s => s != null);	0
6484649	6484430	Replacing assemblies that are loaded only via reflection	ClassLibrary1.Class1	0
8041888	8041873	array of UInt16, what's the suffix in C#?	UInt16[] uint16_array= new UInt16[] { 0, 0, 0, 0 };	0
19536978	19536825	Selecting single attribute of elements from a list object based on another Hashset's element	var regIDs = from p in pr join id in inconsistantIDs on p.id equals id\n             select p.regid;\nHashSet<string> matchingRegIDs = new HashSet<string>(regIDs); // contains: "5555"	0
1663237	1663212	Fast way to check if a server is accessible over the network in C#	Paralell.ForEach()	0
29676181	29631718	Upload a File from HTML form using PostAsync	var requestContent = new MultipartFormDataContent();\nvar fileContent = new StreamContent(upload.InputStream);\nfileContent.Headers.ContentType = upload.ContentType;\nrequestContent.Add(fileContent, upload.FileName, upload.FileName);\n\nclient.PostAsync(url, requestContent);	0
4767262	4766969	To add a Serial Number as the First Column in a GridView	DataTable _test = new DataTable();\nDataColumn c = new DataColumn("sno", typeof(int));\nc.AutoIncrement = true;\nc.AutoIncrementSeed = 1;\nc.AutoIncrementStep = 1;\n_test.Columns.Add(c);\n_test.Columns.Add("description");\ngvlisting.DataSource = _test;	0
25350130	25349880	GetJsonObject from a for looped JsonArray show syntax error	JsonObject jObj = JsonObject.Parse(json);\nJsonArray jArr = jObj.GetNamedArray("records");\nfor (uint i = 0; i < jArr.Count; i++)\n{\n   JsonObject innerObj = jArr.GetObjectAt(i);\n   mData[i] = new Data(innerObj .GetNamedString("countryName"), innerObj .GetNamedString("countryId"), innerObj.GetNamedString("callPrefix"), innerObj .GetNamedString("isoCode"));\n}	0
6927925	6927482	Find All Span in a Text	string strRegex = @"(<span[\s\w\W]*?style='font-family:Symbol'[\s\w\W]*?>([\s\w\W])*?</span>)";\n\nRegex myRegex = new Regex(strRegex);	0
18934891	18934795	How to set max time and min time in c# datetime picker	DateTimePicker datePicker = new DateTimePicker;\ndateTimePicker.MinDate = DateTime.Parse("7:52:22");	0
15417514	15417440	SysDateTime() on Insert Query as parameter	dataAdapter.InsertCommand.CommandText = \n   "INSERT INTO Temas(Id,Level,Date,Description) (@Id,@Level,SYSDATETIME(),@Description)"	0
6665140	6577749	How do I remove SOAP envelope method names from request response?	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\npublic 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}	0
17688101	17688077	Disable textboxes based on radio button selection	txtEmail.Enabled = true;\ntxtEmail.BackColor = System.Drawing.Color.White;	0
6401294	6401245	matching a text input with a hashed value in MySQL	rethash = BitConverter.ToString(hash.Hash).Replace("-", "");	0
15589692	15589477	Control over random numbers in C#	var max = 1000;\nvar rnd = new Random();\nint a, b;\ndo\n{\n    a = rnd.Next(max);\n    b = rnd.Next(max);\n} while (a <= b);	0
27085130	27085067	Some columns in a DataGridView is readonly	dataGridView1.Columns["CompanyName"].ReadOnly = true;	0
3506704	3506665	How can I store a reference to object property in another object?	var sensorFields = typeof(SensorObject).GetProperties()\nforeach(var field in fields)\n{\n    var info = sensorFields.First(sensorField => sensorField.Name == field.Name);\n    var value = Convert.ToString(Reader[field.Destination]);\n    info.SetValue(sensorObj, value, new object[0]);\n}	0
4298197	4298149	C# using own font without install it	// Be sure to dispose your PrivateFontCollection\n// and Font to avoid an easy leak!\nSystem.Drawing.Text.PrivateFontCollection privateFonts = new PrivateFontCollection();\nprivateFonts.AddFontFile("c:\myapplication\mycustomfont.ttf");\nSystem.Drawing.Font font = new Font(privateFonts.Families[0], 12);\nthis.textBox1.Font = font;	0
1177801	1176548	How to insert programmatically a new line in an Excel cell in C#?	worksheet.Cells[0, 0].Style.IsTextWrapped = true;	0
7886239	7886107	return a value from checkbox_CheckChanged	public bool checkedthecheckbox { get; set; }\n\nCheckBox testchbox = new CheckBox();\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    testchbox.CheckedChanged += new EventHandler(testchbox_CheckedChanged);\n}\n\nvoid testchbox_CheckedChanged(object sender, EventArgs e)\n{\n    if (testchbox.Checked)\n        checkedthecheckbox = true;\n    else\n        checkedthecheckbox = false;\n}	0
7536517	7536491	Inheriting properties with accessibility modifier in C#	public interface A \n{\n    int X {get;}  // Leave off set entirely\n}	0
14576587	14574320	Interacting with Webdriver elements from a list	List<IWebElement> textfields = new List<IWebElement>();\ntextfields = Driver.FindElements(By.XPath("//*[@type='text']"));\n\nforeach (IWebElement field in textfields){\n    field.SendKeys("test);\n}	0
5677405	5677212	How do I convert DateTime .NET datatype to W3C XML DateTime data type string and back?	// DateTime to W3C dateTime string\nstring formatString= "yyyy-MM-ddTHH:mm:ss.fffffffzzz";\ndateTimeField.ToString(formatString) ;\n\n// W3C dateTime string to DateTime \nSystem.Globalization.CultureInfo cInfo= new System.Globalization.CultureInfo("en-US", true);\ndateTimeField= System.DateTime.ParseExact(stringValue, formatString, cInfo);	0
1245538	1244221	How to send a parameter to an object's constructor with Unity's Resolve<>() method?	IUnityContainer subContainer = this.container.CreateScopedContainer();\nsubContainer.RegisterInstance<Customer>(customer);\nsmartFormPresenter1 = subContainer.Resolve<SmartFormPresenter>();	0
858845	858630	XML indenting when injecting an XML string into an XmlWriter	string xml = ExternalMethod();\nXmlReader reader =  XmlReader.Create(new StringReader(xml));\nxw.WriteNode(reader, true);	0
8349428	8344185	SpriteSheet Animation with XNA	ElapsedTimeFrame += (float) GameTime.ElapsedTime.TotalSeconds;\n\nif (ElapsedTimeFrame >= TimePerFrame)\n{\n    CurrentFrameR.X = (CurrentFrameR.X + 1) % SheetSizeR.X;\n\n    if (CurrentFrameR.X == 0)\n    {\n       CurrentFrameR.Y = (CurrentFrameR.Y + 1) % SheetSizeR.Y;\n    }\n\n    ElapsedTimeFrame-= TimePerFrame;\n}	0
6983998	6982529	How to do an XML Serialization with force creating all obligatory elements	public IList<string> Validate(TextReader reader, XmlSchema schema)\n        {\n            XmlReaderSettings settings = new XmlReaderSettings();\n            settings.Schemas.Add(schema);\n            settings.ValidationType = ValidationType.Schema;\n\n            List<string> errors = new List<string>();\n\n            settings.ValidationEventHandler += (sender, e) =>\n            {\n                errors.Add(string.Format("Line {0} at position {1}{2}{3}",\n                        e.Exception.LineNumber, e.Exception.LinePosition,\n                                    Environment.NewLine, e.Message));\n            };\n\n\n            XmlReader xmlReader = XmlReader.Create(reader, settings);\n            while (xmlReader.Read()) { };\n\n            return errors;\n        }	0
25132559	25123070	Retrieve the text from a JavaScript alert via Webdriver	public String getAlert()\n{\n    Alert alert = driver.switchTo().alert();\n    String alertText = alert.getText();\n    alert.accept();\n    return alertText;\n}	0
2055554	1695280	How to do smooth Alpha chanel keying with Silverlight 3 Pixel Shaders?	float4 subtract = ... ; // color you want to remove\nfloat4 color = ... ;\n\ncolor.r -= subtract.r;\n... // for b and g\n\nif ( color.r < 0 )\n    color.r = 0;\n... // for b and g	0
13445549	13442124	Using Animations On Windows Phone	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n\n    myAnimation.Stop();\n}	0
29570281	29559142	access button click event from another .aspx page	public void Save()\n{\nstring TargetID = this.Page.Request.QueryString.Item("TargetID");\nif (TargetID.Length > 0) {\n    string scriptContent = "window.opener.document.getElementById('" + TargetID + "').click();window.close();";\n    this.Page.ClientScript.RegisterStartupScript(typeof(string), "SelectValueScript", scriptContent, true);\n}\n}	0
9451565	9451112	Clearing the screen	graphics.GraphicsDevice.Clear(Color.Black);	0
8406801	8406663	Remember authentication with web request	CookieContainer cookieContainer = new CookieContainer();\n// Create a request using a URL that can receive a post. \nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.url);\nrequest.CookieContainer = cookieContainer;\n\n//DO your request that sets cookies from the server.\n.........\n\n//Place another request with the cookies\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(someNewUrl);\nrequest.CookieContainer = cookieContainer;\n//this should have cookies from the previous request, which should keep you logged in.	0
4620859	4620717	Convert domain name to LDAP-style in .NET	string GetDomainDN(string domain)\n{\n    DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);\n    Domain d = Domain.GetDomain(context);\n    DirectoryEntry de = d.GetDirectoryEntry();\n    return de.Properties["DistinguishedName"].Value.ToString();\n}	0
16861143	16731862	How to access session variable in SSRS (SQL Server 2012)?	// Copy the session username to a report param called "CurrentUser".\n    ReportParameter userParam = new ReportParameter("CurrentUser", Session["user"]);\n\n    // add the parameter to the report\n    reportViewer.ServerReport.SetParameters(new ReportParameter[] { userParam });	0
6488962	6488921	Is there any way to strongly type a controls Tag property?	public class MyTreeNode<T> : TreeNode\n{\n    public T TypedTag { get; set; }\n}	0
22860838	22860102	How strict should be interfaces (a good interface design)	public interface IDriver\n{\n    bool Start();\n    bool Stop();\n    bool Read(uint[] signal1, uint[] signal2);\n}	0
3455619	3455586	How to check whether datatable contains any matched rows?	object objCompute=CompTab.Compute("SUM(Share)", "IsRep=0");\nif(objCompute!=DBNull.Value)\n{\ntotal = Convert.ToDecimal(objCompute);\n}	0
401678	401659	uncheckable items in CheckedListBox?	public Form1()\n{\n    InitializeComponent();\n    checkedListBox1.Items.Add("Can't check me", CheckState.Indeterminate);\n}\n\nprivate void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    if (e.CurrentValue == CheckState.Indeterminate)\n    {\n        e.NewValue = CheckState.Indeterminate;\n    }\n}	0
5374709	5374426	How to change the checked property of ListViewItem?	ListViewItem[] l_lvItem = (from X in Enumerable.Range(0, 10)\n                                   select new ListViewItem(new String[] { X.ToString(), (X + 1).ToString() }) { Checked = true }).ToArray();\nlistView1.Items.AddRange(l_lvItem);	0
8109298	8109273	Regular Expression for splitting an alpha-numeric string into 3 sections?	Regex regex = new Regex("(?<Section1>[0-9]{0,4})(?<Section2>[a-zA-Z]{0,3})(?<Section3>[0-9a-zA-Z]{1,4})");	0
2939504	2939493	How to add custom menu item to an existing app?	mnuHandle = GetSystemMenu(hwnd, false)\n\n  //add a line to the end\n  AppendMenu(mnuHandle, MF_SEPARATOR, 0, "")\n\n  //2 add a command ID = 200\n  AppendMenu(mnuHandle, MF_STRING, 0x200, "Command &1")\n  AppendMenu(mnuHandle, MF_STRING, 0x201, "Command &2")\n\n  //insert a new item to the 2. position\n  InsertMenu(mnuHandle, 2, MF_BYPOSITION, 0x202, "Command &3")\n\n  //remove a standard item \n  RemoveMenu(mnuHandle, 0, MF_BYPOSITION)	0
1871232	1834025	Need a faster DataGridView bulk edit method	DataTable dt = (DataTable)dataGridRes.DataSource;\ndataGridRes.DataSource = null;\n\nfor (int i = 0; i < dt.Rows.Count; i++)\n    dt.Rows[i].SetField(0, 1);\n\ndataGridRes.DataSource = dt;	0
4754329	4754316	Get the number of days between two different DateTime objects	static void Main(string[] args)\n{\n    DateTime begin = DateTime.Now;\n    DateTime end = begin.AddYears(1).AddMonths(1);\n    var result = end.Subtract(begin).TotalDays;\n}	0
6259276	6258977	regex to match string content until comment	Regex re1 = new Regex(@"""[^""]*""", RegexOptions.Multiline);\nRegex re2 = new Regex(@"(?<!//.*)\[%\w+%\]", RegexOptions.Multiline);\nstring input = @"[%tag%] = ""a"" + ""//"" + [%tag2%]; //[%tag3%]\n[%tag%] = ""a"" + ""ii//"" + [%tag2%]; //[%tag3%]";\n\nMatchCollection ms = re2.Matches(re1.Replace(input, ""));	0
16688897	16688169	How to get first unoccupied rows from Excel file using c#.net?	int rows = excelCell.Rows.Count + excelCell.Row - 1;	0
9624202	9624120	Remove tab from tabpages from current tab	tbRooms.TabPages.Remove(tbRooms.SelectedTab);	0
29754183	29754108	C# Why isn't this variable set if it's set?	public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)\n{\n    StreamWriter OutPath;\n    try\n    {\n        OutPath = new StreamWriter(path, rewrite);\n\n        for(int i = 0; i < NumberOfWords; i++)\n        {\n            try\n            {\n                OutPath.Write(NumberOfWords[i]);\n            }\n            catch(IOException e)\n            {\n                Console.WriteLine(e.Message);\n            }\n        }\n    OutPath.Close();\n    }\n    catch(IOException e)\n    {\n        Console.WriteLine(e.Message);\n    }\n}	0
24443108	24443046	Trying to figure out how to format what my linq statement returns	return context.Currencies.OrderBy(x => x.Abbreviation).Distinct().Select(x => string.Format("{0} - {1}",x.Abbreviation,x.Description)).ToList();	0
32660942	32659523	Find DataGrid Row by Object	HightlightPrintedRow(Part part, UltraGrid ultraGrid1)\n    {\n        foreach (var row in ultraGrid1.Rows)\n        {\n            if ((Part)row.ListObject == part)\n            {\n                row.Appearance.BackColor = Color.LightGreen;\n                break;\n            }\n        }\n    }	0
24436823	24436709	How do I highlight the text in a textbox at the startup of a window?	public AddDestination()\n    {\n        InitializeComponent();\n    }\n\n    private void AddDestination_Load(object sender, EventArgs e)\n    {\n        //Give cursor focus to the textbox\n        textBox1.Focus();\n\n        //Highlights text **DOES NOT WORK\n        textBox1.SelectionStart = 0;\n        textBox1.SelectionLength = textBox1.Text.Length;\n\n    }	0
4095109	2444578	Generic structure for performing string conversion when data binding	public T GetValueAs<T>(string sValue)\n    where T : struct\n{\n    if (string.IsNullOrEmpty(sValue))\n    {\n        return default(T);\n    }\n    else\n    {\n        return (T)Convert.ChangeType(sValue, typeof(T));\n    }\n}	0
27486089	27485804	Selenium C# how to get text in IWEbElement	By byCss = By.CssSelector(".clsTextWidgetParseError>input");\nvar element = Driver.FindElement(byCss );\nelement.Clear();\nelement.SendKeys(value);	0
1672776	1672737	Find date after a given weeks(months) in ASP.NET	DateTime dt = DateTime.Now.AddDays(14);\nDateTime dt1 = DateTime.Now.AddMonths(4);	0
2606405	2606368	How to get specific line from a string in C#?	string GetLine(string text, int lineNo)\n{\n  string[] lines = text.Replace("\r","").Split('\n');\n  return lines.Length >= lineNo ? lines[lineNo-1] : null;\n}	0
13210713	13210458	Unexpected XML declaration. White Space not allowed	sb.Clear();\nsb.AppendLine("<?xml version='1.0' encoding='utf-8'?>");	0
3919885	3919583	Catching a WebFaultException's details in WCF Rest	var r = httpWebRequest.GetResponse();\nif(r.StatusCode != 200)\n{\n    MessageBox.Show(r.Content); // Display the error \n}\nelse\n{\n    var streamIn = new StreamReader(r.GetResponseStream());\n    string strResponse = streamIn.ReadToEnd();\n    streamIn.Close();\n    return strResponse;\n}	0
25520174	25505683	How do I make certain parts of the ChartArea a different color?	double[] yValue21 = { 5, 5, 5, 5, 5, 5, 5 };\ndouble[] yValue22 = { 8, 8, 8, 8, 8, 8, 8 };\n\nseries.ChartType = SeriesChartType.Range;\nseries.Color = Color.FromArgb(70, 255, 0, 0);\nchart.Series.Add(series);\nchart.Series[2].Points.DataBindY(yValue21, yValue22);	0
21775802	21774230	How to expand a selected treeview node	public TreeNode FindNode(\nstring valuePath)	0
20371592	20371520	populating IEnumerable collection with a List<string> data	Countries = countries.Select(country => new SelectListItem {Text = country, Value = country});	0
313954	313918	De Serializing a list of strings without creating a new class?	[XmlArray(ElementName = "TypesOfThings")]\n[XmlArrayItem(ElementName="Thing")]\npublic List<string> TypesOfThings\n{\n   get;\n   set;\n}	0
29306968	29306917	Deleting data from an MS Access Database with C# via button click	OleDbCommand cmd = new OleDbCommand("DELETE FROM Book WHERE Title ='" +  tempTitle + "'", connect);	0
16241100	16241049	Assert that a test failure is a success	// do stuff\nbool success = DoStuff();\nAssert.IsFalse(success);	0
850615	850610	What's an efficient way to concatenate all strings in an array, separating with a space?	String output = String.Join(" ", myStrings);	0
30160017	30159898	Regex formating metacharacters	String result = Regex.Replace(input, @"[^\w.]+", "|");	0
23453198	23452443	Updating Bitmap from BackgroundWorker in MVVM/WPF	Dispatcher.Invoke((Action)delegate() { /*update UI thread here*/ });	0
4211398	4210902	If I build a type with a property using TypeBuilder do I need to use a propertyBuilder?	var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(\n    new AssemblyName("foo"), AssemblyBuilderAccess.RunAndSave);\nvar mb = ab.DefineDynamicModule("foo");\nvar tb = mb.DefineType("bar");\ntb.AddInterfaceImplementation(typeof(IFoo));\nvar method = typeof(IFoo).GetProperty("Property").GetGetMethod();\nvar impl = tb.DefineMethod("impl",\n    MethodAttributes.Private | MethodAttributes.Virtual,\n    typeof(int), Type.EmptyTypes);\nvar il = impl.GetILGenerator();\nil.Emit(OpCodes.Ldc_I4_7); // because it is lucky\nil.Emit(OpCodes.Ret);\ntb.DefineMethodOverride(impl, method);\n\nvar type = tb.CreateType();\nIFoo foo = (IFoo)Activator.CreateInstance(type);\nvar val = foo.Property;	0
18341373	18340808	How to Convert Persian Digits in variable to English Digits Using Culture?	char[][] numbers = new char[][]\n    {\n        "0123456789".ToCharArray(),"persian numbers 0-9 here".ToCharArray()\n    };\n    public void Convert(string problem)\n    {\n        for (int x = 0; x <= 9; x++)\n        {\n            problem.Replace(numbers[0][x], numbers[1][x]);\n        }\n    }	0
32767827	32702848	Retrieving Query from Parse.com on Xamarin.Android with many relations	var query = ParseObject.GetQuery ("Review")\n    .WhereEqualTo ("business", relationBusiness)\n    .WhereEqualTo ("user", relationUser)\n    .WhereEqualTo ("staff", relationStaff);\n\nIEnumerable<ParseObject> reviews = await query.FindAsync();	0
11351431	11350514	WinForms ListBox Append Selection	[DllImport("user32.dll", SetLastError = true)]\n    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);\n\n    public const byte KEYEVENTF_KEYUP = 0x02;\n    public const int VK_CONTROL = 0x11;\n\n    private void listBox1_MouseEnter(object sender, EventArgs e)\n    {\n        keybd_event(VK_CONTROL, (byte)0, 0, 0);\n    }\n\n    private void listBox1_MouseLeave(object sender, EventArgs e)\n    {\n        keybd_event(VK_CONTROL, (byte)0, KEYEVENTF_KEYUP, 0);\n    }	0
5374984	5374966	How to capture stream data? C# I/O Basic	using (var stream = new MemoryStream())\n{\n    // pass the memory stream to the method which will write to it\n    SomeClass.Write(stream, someModel);\n\n    // convert the contents to string using the default encoding\n    string result = Encoding.Default.GetString(stream.ToArray());\n\n    // TODO: do something with the result\n}	0
6512038	6511978	run console application in C# with parameters	// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = "Write500Lines.exe";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();	0
34202886	34202840	How to Open any file in new browser tab using ASP.NET with C#?	previewlink.NavigateUrl = New Url("someAddres", Url.Absolute)\npreviewlink.Target = "_blank";	0
11689918	11689875	How to read rows count using SqlDataReader	int rows = 0;\nif(rdr1.Read()) {\n    rows = (int) rdr1["Rows"];\n}	0
30973825	30973219	Linq - Group counts with 0 entries are missing from results	var bookings = from p in db. Properties\n               orderby p.Id\n               group p by p.Title into grp\n               select new\n               {\n                   key = grp.Key,\n                   cnt = grp.Count(p => p.Bookings.Where(b => b.StartDate.Year == Year))\n               };	0
26289030	26288951	Performing a time calculation inside a Linq query	using System.Data.Entity; //namespace\n\nfrom c in Contacts.Where(a => a.LastName.Contains("Anderson"))               \n                   select new\n                   {\n                       Id = c.Id,\n                       Surname= c.LastName,\n                       TheirTime = c.TimeZoneOffset,\n                       CalculatedTime = DbFunctions.AddMinutes(c.SavedUtcTime,x.UtcOffsetInMinutes)                  \n                   }	0
18946798	18946382	How to add many Polylines to canvas element?	canvasGraph.Children.Add(new Polyline(){\n  Points = new PointCollection(\n    new List<Point> {\n      new Point(x1, y1), \n      new Point(x2, y2)})});	0
6925724	6925086	How to detect the Ms-Access database exceeds the max size using c sharp	constant long TWO_G = (2*1024*1024*1024); \nconstant long MARGIN = (8 * 1024 * 1024); \nstring pathToMonsterMdb = "monster.mdb";\nFileInfo mdb = new FileInfo(pathToMonsterMdb);\nlong len = mdb.Length;\nif (len > (TWO_G - MARGIN) {\n   /* File's getting close to max size.  Deal with it. */\n}	0
9823862	9823836	Checking if a variable is of data type double	double price;\nbool isDouble = Double.TryParse(txtPrice.Text, out price);\nif(isDouble) {\n  // double here\n}	0
12915931	12915768	How to get Path to a copied file in the application directory	string fileName = \n    System.Reflection.Assembly.GetExecutingAssembly().Location +    \n    Path.DirectorySeparatorChar + \n    "Resources" + \n    Path.DirectorySeparatorChar +\n    "ResourceFileName.xslt";	0
9001923	9001871	Scenario with dependency properties-how to access each other	public static void OnAvailableItemsChanged(DependencyObject sender,  DependencyPropertyChangedEventArgs e)\n{\n   UC uc = sender as UC;\n   List<string> selectedItems = uc.SelectedItems;\n}	0
9397115	8990016	How do I get json.net to exclude nulls when deseralizing a collection?	[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]\npublic string Name { get; set; }	0
22655548	22655312	Creating CSV File from string array	string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nstring filePath = pathDesktop + "\\mycsvfile.csv";\n\nif (!File.Exists(filePath))\n{\n    File.Create(filePath).Close();\n}\nstring delimter = ",";\nList<string[]> output = new List<string[]>();\n\n//flexible part ... add as many object as you want based on your app logic\noutput.Add(new string[] {"TEST1","TEST2"});\noutput.Add(new string[] {"TEST3","TEST4"});\n\nint length = output.Count;\n\nusing (System.IO.TextWriter writer = File.CreateText(filePath))\n{\n    for (int index = 0; index < length; index++)\n    {\n        writer.WriteLine(string.Join(delimter, output[index]));\n    }\n}	0
6753126	6740391	New C#, how do I find a roadmap for navigating through objects/collections?	DataView *this[int]* which returned a... \n  > DataRowView which had the *Row* property which returns a... \n    > DataRow which finally has the *ItemArray* object!!	0
20963907	20882100	Remove Title Bar's Context Menu completely in WPF Window	private const int GWL_STYLE = -16; //WPF's Message code for Title Bar's Style \n    private const int WS_SYSMENU = 0x80000; //WPF's Message code for System Menu\n    [DllImport("user32.dll", SetLastError = true)]\n    private static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n    [DllImport("user32.dll")]\n    private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n\n    // Handling the Messages in Window's Loaded event\n\n    private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        var hwnd = new WindowInteropHelper(this).Handle;\n        SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);\n    }	0
34096243	34095865	How to load fileSystem in a hierarchyView?	private void Form1_Load(object sender, EventArgs e)\n{\n   PopulateTree(@"C:\treeview", treeView1.Nodes.Add("I want to remove this node"));\n}\npublic void PopulateTree(string dir, TreeNode node)\n{\n    DirectoryInfo directory = new DirectoryInfo(dir);\n    foreach (DirectoryInfo d in directory.GetDirectories())\n    {\n        TreeNode t = new TreeNode(d.Name);\n        PopulateTree(d.FullName, t);\n        node.Nodes.Add(t);\n    }\n    foreach (FileInfo f in directory.GetFiles())\n    {\n        TreeNode t = new TreeNode(f.Name);\n        node.Nodes.Add(t);\n    }\n}	0
24033899	24033786	reset the color of a previously pressed button after another button is pressed c#	class Form1 : Form\n{\n    private Button _lastButtonClicked;\n\n    protected void ClickHandler(object sender, EventArgs e)\n    {\n        if (_lastButtonClicked != null)\n           _lastButtonClicked.BackColor = Color.whatever;\n\n        _lastButtonClicked = sender as Button;\n        _lastButtonClicked = Color.newcolor;\n    }\n}	0
29838690	29838618	C#: how to get first character of a string?	var yourstring = "test"; // First char is multibyte char.\n        var firstCharOfString = StringInfo.GetNextTextElement(yourstring,0);	0
4647725	4647505	HttpWebRequest POST adds a NULL value to Form Variables	class Program\n{\n    static void Main(string[] args)\n    {\n        var webclient = new WebClient();\n        var valueToSend = new Message("some data", "some other data");\n        var parameters = new NameValueCollection \n          {\n            {"Key", Jsonify(valueToSend)}\n          };\n        webclient.UploadValues(\n          "http://localhost:8888/Ny", \n          "POST", \n          parameters);\n    }\n\n    static string Jsonify(object data)\n    {\n        using (MemoryStream ms = new MemoryStream())\n        {\n            var ser = new DataContractJsonSerializer(data.GetType());\n            ser.WriteObject(ms,data);\n            return Encoding.Default.GetString(ms.ToArray());\n        }\n    }\n\n}	0
4803206	4803045	add row to datagridview while OleDbDataReader.read()	// some codes here\nusing (OleDbDataReader dr = dbCommand.ExecuteReader())\n{ \n    while (dr.Read())\n    {\n        string f1 = dr.GetString("Field1");\n        string f1 = dr.GetString("Field2");\n        GView.Rows.Add(new object[] {f1, f2});\n    }\n}	0
10034048	10033862	Is it possible to send an aspx page in email body?	StringBuilder htmlResponse = new StringBuilder();\n    using (StringWriter sw = new StringWriter(htmlResponse))\n    {\n        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))\n        {\n            Control emailBody = Page.LoadControl("myEmailControl.ascx");\n            emailBody.RenderControl(textWriter);\n        }\n    }\n    string emailHtml = htmlResponse.ToString();	0
3611115	3586786	A different object with same identifier was already associated with the session error	SessionScope.Current.Evict(customer.EmailAddresses);\n                        foreach (var t in lst_email.Items)\n                        {\n                            var temp = (Email_Address)t;\n                            temp.Customer = customer;\n                            customer.EmailAddresses.Add(temp);\n\n                        }	0
2645423	2644864	how to read the data from a text file stored in the database	string[] array = data.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);  \nSystem.Diagnostics.Debug.WriteLine(string.Format("Number of numbers: {0}", array.Length));  \nforeach(string str in array)  \n{  \n    System.Diagnostics.Debug.WriteLine(str);  \n}	0
15759745	15759688	Update label text in background worker winforms	Label1.Invoke((MethodInvoker)delegate {\n   Label1.Text = i.ToString() + "Files Converted";});	0
10113763	10113630	Conditional method invocation from strings	Dictionary<string, Action<...>>	0
10671401	10671300	How to compare a user's multiple answers with my XML file?	XDocument xdoc = XDocument.Load(@"C:\Users\Administrator\Desktop\questioon\questioon\QuestionAnswer.xml");\nstring[] questions = xdoc.Root.Elements("Question").Select(x => (string)x).ToArray();\nstring[] answers = xdoc.Root.Elements("Answer").Select(x => (string)x).ToArray();\nstring[] userAnswers = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };\nfor (int i=0 ; i < questions.Length ; i++)\n{\n    // handle responses\n    string[] words = answers[i].Split(' ', StringSplitOptions.RemoveEmptyEntries)\n        .Select(w => w.ToLower().Trim()).ToArray();\n    string[] userWords = userAnswers[i].Split(' ', StringSplitOptions.RemoveEmptyEntries)\n        .Select(w => w.ToLower().Trim()).ToArray();\n    string[] correctWords = words.Intersect(userWords);\n\n    // do percentage calc using correctWords.Length / words.Length\n}	0
2073624	2073132	Need Help With Provider Design Patterns	userService.CreateAdminUser("keith", "godchaux");	0
1402872	1402860	c#, using lambdas with collection initialization	Func<XElement[]> elementCreatorFunc = \n    () => new[] { new XElement(...), new XElement(...) };\n\nXDocument doc = new XDocument(\n    new XDeclaration("1.0", "utf-8", "yes"),\n        new XElement("data",\n            new XElement("album",\n                elementCreatorFunc()\n                )\n            )\n        );	0
2260472	2260446	How to iterate through Dictionary and change values?	var dictionary = new Dictionary<string, double>();\nvar keys = new List<string>(dictionary.Keys);\nforeach (string key in keys)\n{\n   dictionary[key] = Math.Round(dictionary[key], 3);\n}	0
5549958	5549793	toolStripTextBox action on Enter	e.Handled = true;\n    System.Windows.Forms.SendKeys.Send("{TAB}"); // optional	0
31040669	30429461	Windows 10 IOT Lifecycle (or: how to property terminate a background application)	BackgroundTaskDeferral _defferal;\n    public void Run(IBackgroundTaskInstance taskInstance)\n    {\n         _defferal = taskInstance.GetDeferral();\n        taskInstance.Canceled += TaskInstance_Canceled;\n    }\n\n    private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)\n    {\n        //a few reasons that you may be interested in.\n        switch (reason)\n        {\n            case BackgroundTaskCancellationReason.Abort:\n                //app unregistered background task (amoung other reasons).\n                break;\n            case BackgroundTaskCancellationReason.Terminating:\n                //system shutdown\n                break;\n            case BackgroundTaskCancellationReason.ConditionLoss:\n                break;\n            case BackgroundTaskCancellationReason.SystemPolicy:\n                break;\n        }\n        _defferal.Complete();\n    }	0
5059621	5056850	Textbox in listview	1: <asp:ListView ID="ListView1" runat="server" onitemcommand="ListView1_ItemCommand">\n\n2:  <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Save">Save</asp:LinkButton> \n\n3:   \n    protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)\n        {\n            if (e.CommandName == "Save")\n            {\n                TextBox tb = (TextBox)e.Item.FindControl("TextBox1");\n                string x = tb.Text;\n            }\n        }	0
2838926	2838865	How to insert a child node in a TreeView Control in WPF?	var items = treeView1.Items;\nvar item = new TreeViewItem() { Header = "Interesting" };\nitems.Add(item);\nvar subitem = new TreeViewItem() {Header = "Sub Item"};\nforeach (TreeViewItem n in items)\n{\n  if (n.Header == "Interesting")\n    (n as TreeViewItem).Items.Add(subitem);\n}	0
3965621	3965596	inserted writes	int totalRecordsToWrite = 100000;\nint maxRecordsPerCommand = 500;\n\nSqlConnection sqlc = new SqlConnection(\n                        "Data Source=" + Environment.MachineName + @"\SQLEXPRESS;" +\n                        "Integrated security=true;" +\n                        "database=someDB");\n\nint currentRecord = 0;\n\nwhile (currentRecord < totalRecordsToWrite)\n{\n    SqlCommand sqlcmd;\n    string tmp = string.Empty;\n\n    for(int j = 0; j < maxRecordsPerCommand; j++)\n    {\n        currentRecord++;\n\n        if (currentRecord >= totalRecordsToWrite)\n          break;\n\n        // Insert record "currentRecord" of the 100000 here.\n\n        tmp += "inserto into [db].[Files](...) values (...);"\n    }\n\n    using (sqlcmd = new SqlCommand(tmp, sqlc))\n    {\n       try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } catch{}\n    }\n}	0
14066454	14066363	input string was not in correct format converting string to long in c#?	string[] BundleItemID = form.GetValues("txtbundleid");\n\n    for (int i = 0; i < skuid.Length; i++)\n    {\n        ProductBundleItem productbundleitem = new ProductBundleItem();\n        if (!string.IsNullOrEmpty(BundleItemID[i]))\n        {\n            long val = 0;\n            if (!long.TryParse(BundleItemID[i], out val))\n            {\n                MessageBox.Show(string.Format("{0} is not a valid Int64 value", BundleItemID[i]));\n                break;\n            }\n            productbundleitem.BundleItemId = val;\n        }\n    }	0
17639767	17639761	MaskedTextbox unable to insert NULL date into SQL	var value = (object) DBNull.Value;\nDateTime parsedDate;\nif (DateTime.TryParseExact(maskedTextBox2.Text, "dd.MM.yyyy", null, \n                           DateTimeStyles.None, out parsedDate))\n{\n    value = parsedDate;\n}\nprikaz.Parameters.AddWithValue("zodjdate", value);	0
15584762	15583706	How to identify the image is greyscale image or color image in c#	bool IsGreyScale(Bitmap YourCurrentBitmap)\n{\nColor c;\nfor(int i=0; i < YourCurrentBitmap.Width; i++)\n     for(int j=0; j < YourCurrentBitmap.Height; j++)\n          {\n               c = YourCurrentBitmap.GetPixel(i,j);\n               if(!(c.R == c.G == c.B)) return false;\n          }\nreturn true;\n}	0
1344504	1344356	c#, Set datagridview column format after datasource has been set	var persons = new[] {new {name = "aaa", salary = 40000}, \n                     new  {name = "aaa", salary = 40000}, \n                     new  {name = "aaa", salary = 40000}, \n                     new  {name = "aaa", salary = 40000}};\n\n\n    GridView1.DataSource = persons;\n    GridView1.AutoGenerateColumns = false;\n\n    var NameField = new BoundField();\n\n    NameField.HeaderText = "Name";\n    NameField.DataField = "name";\n    GridView1.Columns.Add(NameField);\n\n    var SalaryField = new BoundField();\n    SalaryField.HeaderText = "Salary";\n    SalaryField.DataField = "salary";\n    SalaryField.DataFormatString = "{0:c2}";\n    SalaryField.HtmlEncode = false;\n    GridView1.Columns.Add(SalaryField);\n\n\n    GridView1.DataBind();	0
1265787	1265773	How can i globally set the Culture in a WPF Application?	Dim newCulture As CultureInfo = new CultureInfo("fr-FR")\nCurrentThread.CurrentCulture = newCulture	0
13664151	13664079	Get a sibling from given node	document.SelectSingleNode("/material/item[val1='2']/name").InnerText	0
32629640	32627588	How to get embed value and file name in a directory	var body = doc.MainDocumentPart.Document.Body;\nvar pics = body.Descendants<DocumentFormat.OpenXml.Drawing.Pictures.Picture>();\nvar result = pics.Select(p => new\n    {\n        Id = p.BlipFill.Blip.Embed.Value,\n        Name = p.NonVisualPictureProperties.NonVisualDrawingProperties.Name.Value\n    });	0
29542552	29542396	C# How can i swap the first with the last character from a string	public static string FrontBack(string str) {\n    int len = str.Length;\n    return str[len-1] + str.Substring(1,len-2) + str[0]; \n}	0
3456323	3456263	Finding objects by their name	System.Collections.Generic.Dictionary<string, your object type>	0
14648554	14648032	Getting to "bottom" of XmlDocument - C#	XmlDocument xmlDoc = new XmlDocument("yourxml.xml");\nforeach (XmlNode childElement in xmlDoc.SelectNodes("//childElement"))\n{\n    customObject.collection.Add(childElement.Name, childElement.InnerText);\n}	0
9215167	8789822	Visible listview items in winforms listview?	for (int i = betterListView.TopItem.Index; i < betterListView.BottomItem.Index; i++)\n{\n  // your code here\n}	0
2895876	2895858	How do I unit test a finalizer?	GC.WaitForPendingFinalizers();	0
11783783	11776878	How to measure the Height of a Hyperlink element?	Font.Height	0
23264022	23263588	Input string was not in a correct format in my gridview	Text='<%# Eval("StudId").ToString() %>'\n\n Text='<%# Eval("Status").ToString() %>'	0
5775700	5775586	is it ok this connection string for access since any computer (using Internet)	TrustServerCertificate=True	0
18295148	18294182	Accessing a dynamic variable in javascript from Server Side using c#	Response.Write	0
8229771	8228336	How do i create a reference in my DB to a user from the ASP.NET build in usersystem?	newsitem.originalposter = (Guid)Membership.GetUser().ProviderUserKey;	0
13534953	13534800	creating multiple objects of a type in C#	namespace Cars\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            List<Cars> carList = new List<Cars>();\n\n            Console.WriteLine("PLz put the car  name:");\n            string ma = Console.ReadLine();\n            Console.WriteLine("PLz put  car no  :");\n             int pe = Convert.ToInt16(Console.ReadLine());\n\n            carList.Add(new Cars(ma,pe));\n        }\n\n\n\n        public class Cars\n        {\n\n            string ma;\n            int pe;\n\n            public Cars(string carName, int reg)\n            {\n                ma = carName;\n                pe = reg;\n\n            }\n\n        }\n    }\n}	0
29068106	29067875	CSVHelper C# Load from My object	// Populate your employeeList\n        TextWriter textWriter = new StreamWriter("foo.csv"); //foo.csv is the file you are saving to\n        var csv = new CsvWriter(textWriter);\n        foreach (var employee in employeeList)\n        {\n            csv.WriteField(employee.Id);\n            csv.WriteField(employee.Date.ToShortDateString());\n            csv.WriteField(employee.Account.AccountName);\n            csv.WriteField(employee.LabourChargeType.LabourChargeTypeName);\n            csv.NextRecord();\n        }\n        textWriter.Flush();\n        textWriter.Close();\n        textWriter = null;	0
30041149	30040200	Pre-filtering joined elements in LINQ to Objects	var X = (from l in lefts\n        let topright = (from r in rights where r.paramNumber == l.paramNumber && r.startDate < l.date orderby r.startDate descending select r)\n        where topright!=null\n        let toprightcheck = topright.First()\n     select new { lName = l.paramNumber, rname = toprightcheck.paramNumber, ldate = l.date, rdate = toprightcheck.startDate });	0
31240464	31240380	WPF two way binding infinite loop	bool navigating= false;    \nprivate void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n{\n    navigating= true;\n    SetCurrentValue(UrlProperty, webBrowser.Url);\n    navigating= false;\n}\n\nprivate static void UrlPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n{\n    if (!navigating)\n        (sender as WebView).webBrowser.Url = e.NewValue as Uri;\n}	0
7498472	7498099	How to have optional parameters in WCF REST service?	/whatever/blabla?some=data&whichis=optional	0
3023922	2997241	Parsing numbers at PreviewTextInput	private readonly List<Regex> ValidNumberRegex = new List<Regex>\n                                {\n                                    new Regex(@"^-?$"),\n                                    new Regex(@"^-?\d+$"),\n                                    new Regex(@"^-?\d+\.$"),\n                                    new Regex(@"^-?\d+\.\d+$"),\n                                    new Regex(@"^-?\d+\.\d+[eE]$"),\n                                    new Regex(@"^-?\d+\.\d+[eE]-?$"),\n                                    new Regex(@"^-?\d+\.\d+[eE]-?\d+$"),\n                                    new Regex(@"^-?\d+[eE]-?$"),\n                                    new Regex(@"^-?\d+[eE]-?\d+$"),\n                                };	0
12818334	12786236	Returning an object from a subroutine	public class SubjectDB   \n     {   \n        public string SubjectId  { get; set; }   \n        .   \n        .   \n        public List<AddressDB> Address { get; set; }   \n        .   \n        .   \n        [Key]   \n        public int Id { get; set; }\n\n        public SubjectDB()\n        {\n           this.Address = new List<AddressDB>();\n           .\n           .\n        }   \n     }   \n     public class DBEntities: DbContent   \n     {   \n        public DbSet<SubjectDB> SubjectDB { get; set; }   \n        public DbSet<AddressDB> AddressDB { get; set; }   \n        .   \n        .   \n     }	0
23384086	23383672	Run ASP.NET page with parameter?	Default.aspx?CONFERENCEID=3	0
23640503	23640107	Creating a hyperlinked image with onclick event in RowDataBound	ImageButton btn= new ImageButton();\nbtn.ImageUrl="Images/NoteIcons/note_add.png";\nbtn.Attributes.Add("onClientClick", "YourJavaScriptFunction();");\ne.Row.Cells[10].Controls.Add(btn);	0
18126154	18125818	json formating in c#	var jsonObject = JSON.parse("{\"Test\":{\"Name\":\"Test class\",\"X\":\"100\",\"Y\":\"200\"}}");	0
27251678	27250118	Scrollbar moving to right instead of left	Series S1 = SleepMovChar.Series["yourSeriesByNameOrNumber"];\nmov.AxisX.ScaleView.Position = S1.Points.Count - mov.AxisX.ScaleView.Size;	0
16512842	16512827	How to convert a Collection to byte array	var employees = new ObservableCollection<Employee>();\n\n\nusing (var stream = new MemoryStream())\n{    \n    var formatter = new BinaryFormatter();\n    formatter.Serialize(stream, employees);\n    var byteArray = new byte[stream.Length];\n    stream.Seek(0, SeekOrigin.Begin);\n    stream.Read(byteArray, 0, (int)stream.Length);\n    // do whatever you want with the bytes now....\n\n}	0
12095590	12095372	redirect user based on Roles?	protected void Page_Load(object sender, EventArgs e)\n{\n\n        if (Page.User.IsInRole("admin"))\n        {\n            // all is good, do not do anything\n            // if you want to initialized something, do it here\n        }\n        else\n        {\n            // opps you do not have access here, take him somewhere else\n            Response.Redirect("/accessPage.aspx");\n        }\n\n\n}	0
11163997	11163788	Pulling data from an XML file into a TreeView item (C#)	var xDocument = XDocument.Load("http://localhost/AnswerIt.xml");\n\nforeach (var element in xDocument.Descendants("category"))\n{\n    var node = lstQuestions.Nodes.Add(element.Attribute("name").Value);\n    foreach (var subElement in element.Elements("question"))\n    {\n        var subnode = node.Nodes.Add(subElement.Attribute("is").Value);\n        foreach (var answer in subElement.Elements("answer"))\n            subnode.Nodes.Add(answer.Attribute("couldbe")\n                   .Value.Replace("\t", ""));\n    }\n}	0
33128254	33127937	How to define different properties in one model class due to some flag	public class GenericClass<T>\n{\n    // T used in constructor.\n    public GenericClass(T t)\n    {\n        data = t;\n    }\n\n    // T as private member data type.\n    private T data;\n\n    // T as return type of property.\n    public T Data  \n    {\n        get { return data; }\n        set { data = value; }\n    }\n}	0
13239170	13239141	IEnumerable to IList casting possibilites	viewEntry.Parties = viewModel.PartiesSelected.ToList()	0
13864825	13864779	Issue with string in c#	string link_format = "<link rel='stylesheet' id='fontrequest' href='http://fonts.googleapis.com/css?family={0}' type='text/css' media='all'>";\n\nstring link = String.Format(link_format,Fonts);	0
28700254	28700161	Can't delete row from single column table	SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);	0
19531988	19531944	How to generate control number in c#	Random rand = new Random();\nstring startingDigits;\nif(maritimeEducation)\n{\n    startingDigits = "100";\n}\nelse\n{\n    startingDigits = "101";        \n}\n\nstring controlNumber = string.Format("{0}{1}{2}", \n    startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);	0
1102282	1102255	C#: String -> MD5 -> Hex	System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5");	0
15155316	15155264	How to reset an IEnumerator instance in below case	public void Reset() {\n  throw new NotImplementedException();\n}	0
6545515	6540250	Winforms Drawing - Parameter is not valid on system resume	using(SolidBrush drawBrush = new SolidBrush(ForeColor))\n    e.Graphics.DrawString(Text, Font, drawBrush, new PointF(x, y));	0
2766764	2766585	How do I combine these similar linq queries into one?	public Attrib DetermineAttribution(Data data)\n{\n    var c = data.actions.FirstOrDefault(c => c.actionType == Action.ActionTypeOne) ??\n            data.actions.FirstOrDefault(c => c.actionType == Action.ActionTypeTwo);\n    return c != null ? new Attrib { id = c.id, name = c.name } : null;\n}	0
6106949	6106819	How do I consume a RSS feed in ASP.Net webapp	var rssFeed = XDocument.Parse(yourRSSString);\nvar items = from item in rssFeed.Descendants("item")\n            select new FeedItemModel()\n                    {\n                        Title = item.Element("title").Value,\n                        DatePublished = DateTime.Parse(item.Element("pubDate").Value),\n                        Url = item.Element("link").Value,\n                        Description = item.Element("description").Value\n                    };	0
23512136	23511953	XML node innerText is loaded twice in dataGridView cell value using C#	for (int w = 0; w < timeTableGridView.Columns.Count; w++)	0
32171189	32169217	C# asp.net MVC wiring up one json output from Google MAPS AutoComplete API to a different json output	public ActionResult Autocomplete(string term)\n        {\n            var url = String.Format(" https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + term + "&types=address&location=53.4333,-7.9500&radius=250&key=MYKEY");\n            var jsonautocomplete = new System.Net.WebClient().DownloadString(url);\n\n            JavaScriptSerializer jss = new JavaScriptSerializer();\n            Rootobject autocomplete = JsonConvert.DeserializeObject<Rootobject>(jsonautocomplete);\n            var suggestions = autocomplete.predictions;\n            var model = suggestions.Select(x => new\n                   {\n                       label = x.description\n                   });\n            return Json(model, JsonRequestBehavior.AllowGet);\n        }	0
3671430	3671404	How do I access special directories in Windows?	string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);	0
17063664	17063454	Generate string of fixed length in C#	String s = "AB_000000";\nString newString="xyz";\ns = s.Remove(s.Length - newString.Length, newString.Length);\ns = s + newString;	0
4409512	4277938	How can I render out doublequotes in attributes on TableRows?	public class TableRowAttributeFix : TableRow\n{\n    private StringBuilder AttributesOutput = new StringBuilder();\n\n\n    protected override void Render(HtmlTextWriter writer)\n    {\n        foreach (String _attributeKey in Attributes.Keys)\n        {\n            var _attributeValue = Attributes[_attributeKey];\n\n            if (_attributeValue.Contains("\""))\n            {\n                AttributesOutput.Append(String.Format(" {0}='{1}' ", _attributeKey, _attributeValue));\n            }\n            else\n            {\n                AttributesOutput.Append(String.Format(" {0}=\"{1}\" ", _attributeKey, _attributeValue));\n            }\n        }\n\n\n        writer.Write("<tr id=\"" + ClientID + "\" " + AttributesOutput + " class=\"" + CssClass + "\" >");\n\n        RenderContents(writer);\n\n        writer.Write("</tr>");\n    }\n}	0
16207795	16207459	How to handle a transfer data from a postback to preinit event?	string studentID = HttpContxt.Current.Request.Form["txtStudentID"];	0
16113427	16113205	Need help finishing or rewriting this algorithm for navigating a Generic Collection	private void GotoStep()\n{\n    CurrentStep = CurrentPhase.Steps[CurrentStepIndex];\n}	0
28960395	28959626	hide UINavigationBar from @selector	[self.navigationController setNavigationBarHidden:YES animated:YES];	0
27767573	27754276	Create a generic rest service using WCF	[ServiceKnownType(typeof(List<MessageEmail>))]	0
29368923	29368853	One function for multiple Textbox WPF	private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n    {\n        var textBox = sender as TextBox;\n\n        textBox.IsReadOnly = false;\n        textBox.Background = new SolidColorBrush(Colors.White);\n        textBox.Foreground = new SolidColorBrush(Colors.Black);\n    }	0
4485243	4485209	How to override the minimize control?	private const int WM_SYSCOMMAND = 0x0112;\nprivate const int SC_MINIMIZE = 0xf020;\n\nprotected override void WndProc(ref Message m) {\n    if (m.Msg == WM_SYSCOMMAND) {\n        if (m.WParam.ToInt32() == SC_MINIMIZE) {\n            m.Result = IntPtr.Zero;\n            Height -= 100;\n            return;\n        }\n    }\n    base.WndProc(ref m);\n}	0
25354334	25354134	Programmatically Automating Getting the Correct COM Port, based on the Serial Device, through C#	foreach(SerialPort port in SerialPort.GetPortNames())\n{\n    SerialPort sp = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);\n    sp.Handshake = Handshake.None;\n\n    sp.Open();\n    sp.Write("<ID01>\r\n");\n\n    Thread.Sleep(250);  // give it some time to respond\n\n    string response = sp.ReadExisting();\n    if(response == "<ID01>S")\n    {\n        found = true;\n        // do something useful\n    }\n\n}	0
20531594	20531526	Resolving dependencies with constructor injection and named mappings using attributes on the constructor parameter	[Dependency("A")]	0
5808939	5808915	C# SqlCommand - Setting resultset to a variable	myCommand = new SqlCommand("SELECT TrialName FROM dbo.CT WHERE NumId='"+TrialId+"'", \n\nmyConnection);                \nSqlDataReader dr = myCommand.ExecuteReader();                \nif(dr.Read())\n{\n    String TName = dr[0].ToString(); \n}	0
1242189	842285	How do I create a custom Outlook Item?	Outlook.Application olApp = new Outlook.Application();\n    //mapifolder for earlier versions (such as ol 2003)\n    Outlook.Folder contacts = olApp.Session.GetDefaultFolder(Outlook.olDefaultFolders.olFolderContacts);\n    //must start with IPM.   & must be derived from a base item type, in this case contactItem.\n    Outlook.ContactItem itm = (Outlook.ContactItem)contacts.Items.Add(@"IPM.Contact.CustomMessageClass");\n    itm.Display(false);	0
1200416	1200357	How to ignore excel compatibility verification when converting to an old format?	wb.Application.DisplayAlerts = false;	0
13616664	13615570	Passing a string from IHttpHandler to Javascript and then to Silverlight	response = new JavaScriptSerializer().Serialize(response);	0
16985673	16983399	how to set RequiredFieldValidator to validate against specific user control which has multiple instance?	public String ValidationGroup\n{\n    get { return RequiredFieldValidator1.ValidationGroup; }\n    set { \n        RequiredFieldValidator1.ValidationGroup = value; \n        NewSchedule.ValidationGroup = value; \n    }\n}	0
2697960	2697944	C# Using colors in console , how to store in a simplified notation	public static void ColoredConsoleWrite(ConsoleColor color, string text)\n{\n    ConsoleColor originalColor = Console.ForegroundColor;\n    Console.ForegroundColor = color;\n    Console.Write(text);\n    Console.ForegroundColor = originalColor;\n}	0
6917730	6917707	How do I add an output file to the result window using mstest?	TestContext.AddResultFile(fullyQualifiedName);	0
1182801	1182772	How can i find selected node of treeview when click right button	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)  \n    {  \n        MessageBox.Show(string.Format("Node clicked: {0}", e.Node.Text));  \n    }  \n}	0
12805708	12805668	Entity Framework 4 - is it good to add a custom field?	public string MyCustomField { get; set; }	0
8308889	8308847	Math, largest number	return Math.Pow(10, numOfDigits) - 1;	0
7461402	7461378	convert xaml to c#	TextBox MyTextBox = new TextBox();\nMyTextBox.Name = "MyTextBox";\nBinding binding = new Binding("TextBox.Text");\nbinding.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent);\nMyTextBox.SetBinding(TextBox.TextProperty, binding);	0
18668662	18668611	cant make postbackurl send data to next page	cmd.Parameters.AddWithValue("@searchkey", "%" + SourceTextBox.Text);	0
28538273	28538102	Trying to pass a list from DAL through Controller	// This is a class that represents a row of your DataTable.\npublic class User\n{\n    public int UserNbr { get; set;}\n    public User(int userNbr)\n    {\n        UserNbr = userNbr;\n    }\n}\n\npublic List<User> allUsers ()\n{\n    var users = new List<User>();\n\n    // Create an instance of the DAL class.\n    var dal = new Restaurang4.DAL();\n\n    // Loop through the datatable's rows and create foreach of them \n    // a new User and then add it to the users list.\n    foreach(var dataRow in dal.findAllUsers().Rows)\n        users.Add(new User(dataRow.Field<int>("UserNbr ")));\n\n    return users;\n}	0
7510711	7081784	How to render a control in MVC 3 Razor using MEF	public virtual PartialViewResult Menu()\n{\n    var builder = new MenuModelBuilder(Context.MenuContainer);\n    ViewData.Model = builder.BuildModel();\n\n    return PartialView();\n}	0
24094221	24094093	How to print 2D array to console in C#	public static void Print2DArray<T>(T[,] matrix)\n    {\n        for (int i = 0; i < matrix.GetLength(0); i++)\n        {\n            for (int j = 0; j < matrix.GetLength(1); j++)\n            {\n                Console.Write(matrix[i,j] + "\t");\n            }\n            Console.WriteLine();\n        }\n    }	0
25745414	25744461	Task in child window suspend UI	Task.Factory.StartNew(TestMethod, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);	0
15196390	15196269	How to change the font size of all(n number of ) texblocks inside the stack panel programmatically?	foreach (var children in foobar.Children)\n        {\n            (children as TextBlock).FontSize = 20;\n        }	0
24685385	24665989	I need to create an object that can take the key value pair similar to this xsd	var fields = new List<FieldDefinition>\n        {\n            new FieldDefinition{ Type="string", DisplayName="FirstName"},\n            new FieldDefinition{ Type="int", DisplayName="EmployeeId"}\n        };\n\n        var infr = new List<Infrastructure>\n        {\n            new Infrastructure { def1=fields.FirstOrDefault()}// loop through to assign each item\n        };\n        foreach (var item in infr)\n        Console.WriteLine(item.def1.DisplayName + " -" + item.def1.Type);\n\n        Console.Read();\n\n    }\n}\n\npublic class Infrastructure\n{\n    public FieldDefinition def1 { get; set; }\n\n\n}\n\npublic class FieldDefinition\n{\n    public string Type { get; set; }\n    public string DisplayName { get; set; }\n}	0
1682156	1682123	Downloading a file over https in IE8, using ASP.NET	Response.ClearHeaders();\n      Response.Clear();	0
5667080	5666677	implement callback over ApplicationDomain-boundary in .net	class Program\n{\n    static void Main(string[] args)\n    {\n        Semaphore semaphore = new Semaphore(0, 1, "SharedSemaphore");\n        var domain = AppDomain.CreateDomain("Test");\n\n        Action callOtherDomain = () =>\n            {\n                domain.DoCallBack(Callback);\n            };\n        callOtherDomain.BeginInvoke(null, null);\n        semaphore.WaitOne();\n        // Once here, you should evaluate whether to exit the application, \n        //  or perform the task again (create new domain again?....)\n    }\n\n    static void Callback()\n    {\n        var sem = Semaphore.OpenExisting("SharedSemaphore");\n        Thread.Sleep(10000);\n        sem.Release();\n    }\n}	0
31076739	31076618	How to add a column of zeros in a List<List<double[]>>()?	var res = orig.\n    Select(list => list\n        .Select(array => array.Concat(new[] {0.0}).ToArray())\n        .ToList()\n    ).ToList();	0
4598490	4598438	Connection String in c#	string source = "Data Source=Server Address;Initial Catalog=Database Name;Integrated Security=SSPI;";	0
200185	198910	How can I add an image to my Run for a RichTextBlock?	BitmapImage bi = new BitmapImage(new Uri(@"C:\SimpleImage.jpg"));\nImage image = new Image();\nimage.Source = bi;\nInlineUIContainer container = new InlineUIContainer(image);            \nParagraph paragraph = new Paragraph(container); \nRichTextBoxOutput.Document.Blocks.Add(paragraph);	0
19528197	19527785	How to use a timer with a dictionary	public class Client\n{\n  public event Action<Client> Timeout;\n  System.Threading.Timer timeoutTimer;\n\n  public Client()\n  {\n    timeoutTimer = new Timer(timeoutHandler, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));\n  }\n\n  public void onDataRecieved()\n  {\n     timeoutTimer.Change(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));\n  }\n\n  public void timeoutHandler(object data)\n  {\n     CloseConnection();\n     if (Timeout != null)\n        Timeout(this);\n  }\n}\n\nclass Program\n{\n   List<Client> connectedClients = new List<Client>\n\n   void OnConnected(object clientData)\n   {\n      Client newClient = new Client();\n      newClient.Timeout += ClientTimedOut;\n      connectedClients.Add(newClient);\n   }\n\n   void ClientTimedOut(Client sender)\n   {\n      connectedClients.Remove(sender);\n   }\n}	0
18487453	18486468	How to change the name of petrel window programatically	INameInfoFactory nameFactory = (null != funcWindow) ? CoreSystem.GetService<INameInfoFactory>(funcWindow) : null;\n            var nameInfo = (null != nameFactory) ? nameFactory.GetNameInfo(funcWindow) : null;\n            if (null != nameInfo && nameInfo.CanChangeName)\n            {\n                nameInfo.Name = windowName;\n            }	0
9975153	9975122	Right way to get username and password from connection string?	string conString = "SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200";\nSqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);\nstring user = builder.UserID;\nstring pass = builder.Password;	0
30609728	30609491	How to properly merge lambda-expressions with different parameters	Expression<Func<long, bool>> condition = x => x < max; // Exp # 1\nExpression<Func<long, int, bool>> combined = null;\n\nif (count > 0)\n{\n    Expression<Func<int, bool>> limit = x => x > -1; // Exp # 2\n    combined = Expression.Lambda<Func<long, int, bool>>(\n        Expression.And(condition.Body, limit.Body), \n        new ParameterExpression[] \n        {\n            condition.Parameters[0], \n            limit.Parameters[0] \n        }\n    );\n} else {\n    // Count <= 0, `int` parameter will be provided, but `body` ignores it\n    combined = Expression.Lambda<Func<long, int, bool>>(\n        condition.Body, \n        new ParameterExpression[] \n        {\n            condition.Parameters[0], \n            limit.Parameters[0] \n        }\n    );\n}\n\n// compile `combined` expression\nvar comparator = combined.Compile();\n\nwhile (comparator(k++, n--))\n{\n    // Something\n}	0
24007793	24007706	How to get the date of a specific day in every month and year?	DateTime today = DateTime.UtcNow;\n int deltaMonday = DayOfWeek.Monday - today.DayOfWeek;\n var monday = today.AddDays(deltaMonday += deltaMonday < 0 ? 7 : 0);\n\n int deltaWednesday = DayOfWeek.Wednesday - today.DayOfWeek;\n var wednesday = today.AddDays(deltaWednesday += deltaWednesday < 0 ? 7 : 0);\n\n int deltaSaturday = DayOfWeek.Saturday - today.DayOfWeek;\n var saturday = today.AddDays(deltaSaturday += deltaSaturday < 0 ? 7 : 0);	0
774429	774399	Removing trailing decimals from a .ToString("c") formatted number	price.ToString("c0")	0
12842772	12842518	Number of Nodes with XPathDocument	XmlNode node = myDoc.SelectSingleNode("/");\n\nint i = node.SelectNodes("descendant::*").Count;	0
26303761	26303442	C# project doesnt realize the updates from WCF	Web.Config	0
16456550	16369450	How can I use JSON.NET to handle a value that is sometimes an object and sometimes an array of the object?	internal class GenericListCreationJsonConverter<T> : JsonConverter\n{\n\n    public override bool CanConvert(Type objectType)\n    {\n        return true;\n    }\n\n    public override bool CanRead\n    {\n        get { return true; }\n    }\n\n    public override bool CanWrite\n    {\n        get { return false; }\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        if (reader.TokenType == JsonToken.StartArray)\n        {\n            return serializer.Deserialize<List<T>>(reader);\n        }\n        else\n        {\n            T t = serializer.Deserialize<T>(reader);\n            return new List<T>(new[] { t });\n        }\n    }\n\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        throw new NotImplementedException();\n    }	0
31877008	31876406	Sum of consecutive, positive Integers	int[] list = new int[] { 1, 2, 3, 4, -1, 1, -2, 3, 4 };\nint count = 0;\n\nvar result = list\n    .GroupBy(n => n < 0 ? ++count : count)\n    .Select(x => x.Sum(n => n > 0 ? n : 0));	0
19110131	19109956	Can not bound xml data to dropdown list in c#	var items = XElement.Parse(GetClientXML()).Descendants()\n           .Select(node=> new{ClientId =(string)node.Attribute("ClientId"), Name = (string)node.Attribute("Name")}).ToList();\n\nddlassto.DataSource = items;\nddlassto.ValueMember = "ClientId";\nddlassto.DisplayMember = "Name";	0
30049281	30049105	SerialPort object does not receive any data under Windows XP	this.serialPort.Handshake = System.IO.Ports.Handshake.XOnXOff;	0
10718016	10717736	Relationship on same table with Entity Framework	modelBuilder.Entity<Item>()\n                    .HasOptional(c => c.ChildItems)\n                    .WithMany()\n                    .HasForeignKey(c => c.ThreadId);	0
22274024	22273291	How can I use timespan for each row of the sql table and sum it all up afterwards?	TimeSpan totalTime = new TimeSpan(0);\n\nforeach(var something in somethings)\n{\n   totalTime = totalTime.Add(new TimeSpan(something.end - something.start);\n}	0
32738812	32737708	How do I use a refresh token to get a new access token for Google SpreadsheetsService	var service = new DriveService(new BaseClientService.Initializer() {HttpClientInitializer = credential,\n                                                                            ApplicationName = "Drive API Sample",});\n\n// Dummy request example:\nFilesResource.ListRequest list = service.Files.List();\nlist.MaxResults = 1;\nlist.Q = "title=dummysearch";\nFileList dummyFeed = list.Execute();\n// End of Dummy request	0
699871	699852	How to find all the classes which implement a given interface?	var instances = from t in Assembly.GetExecutingAssembly().GetTypes()\n                where t.GetInterfaces().Contains(typeof(ISomething))\n                         && t.GetConstructor(Type.EmptyTypes) != null\n                select Activator.CreateInstance(t) as ISomething;\n\nforeach (var instance in instances)\n{\n    instance.Foo(); // where Foo is a method of ISomething\n}	0
12476050	12475855	Global Variable between two WCF Methods	public class SessionState\n{\n    private Dictionary<string, int> Cache { get; set; }\n\n    public SessionState()\n    {\n        this.Cache = new Dictionary<string, int>();\n    }\n\n    public void SetCachedValue(string key, int val)\n    {\n        if (!this.Cache.ContainsKey(key))\n        {\n            this.Cache.Add(key, val);\n        }\n        else\n        {\n            this.Cache[key] = val;\n        }\n    }\n\n    public int GetCachedValue(string key)\n    {\n        if (!this.Cache.ContainsKey(key))\n        {\n            return -1;\n        }\n\n        return this.Cache[key];\n    }\n}\n\npublic class Service1\n{\n    private static sessionState = new SessionState();\n\n    public void Method1(string privateKey)\n    {\n        sessionState.SetCachedValue(privateKey, {some integer value});\n    }\n\n    public int Method2(string privateKey)\n    {\n        return sessionState.GetCachedValue(privateKey);\n    }\n}	0
5721006	5695931	T4MVC - Dealing with optional parameters	[NonAction]\npublic ActionResult Index(string id)\n{\n    return Index(id, 1);\n}	0
20452807	20452777	Func<T, U, double> et al. as a Parameters in Constructor	[Test]\npublic void NamedAndUnnamedTest()\n{\n    Assert.AreEqual("Only value1 was supplied", DummyMethod(value1: 1));\n    Assert.AreEqual("Only value1 was supplied", DummyMethod(1));\n    Assert.AreEqual("Only value2 was supplied", DummyMethod(value2: 1));\n    Assert.AreEqual("Both arguments were supplied", DummyMethod(1, 2));\n}\n\nprivate string DummyMethod(int value1 = 0, int value2 = 0)\n{\n    if (value1 != 0 && value2 != 0)\n        return "Both arguments were supplied";\n    if (value1 == 0)\n        return "Only value2 was supplied";\n    return "Only value1 was supplied";\n}	0
8678184	8678080	How to convert a simple stream(http webresponse) to bitmapimage in c# windows 8?	InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();\nDataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));\nwriter.WriteBytes(response.Content.ReadAsByteArray());\nBitmapImage image = new BitmapImage();\nimage.SetSource(randomAccessStream);	0
8294786	8294730	Getting Specific Columns in Entity Framework	public List<bksb_Users> SearchStudents(string reference, string firstname, string lastname) \n    { \n        var anon = (from u in context.bksb_Users \n                where u.userName.Contains(reference) \n                && u.FirstName.Contains(firstname) \n                && u.LastName.Contains(lastname) \n                orderby u.FirstName, u.LastName \n                select new \n                 { \n                     user_id = u.user_id, \n                     userName = u.userName, \n                     FirstName = u.FirstName, \n                     LastName = u.LastName, \n                     DOB = u.DOB \n                 }).Take(100).ToList(); \n\n        return anon.Select(z => new bksb_Users()\n        {\n            user_id = z.user_id, userName = z.userName, FirstName = z.FirstName, DOB = z.DOB\n        }).ToList();\n    }	0
30366611	30364130	Is it posible to set the order of the serialization of a custom property of a custom component/control in the designer-generated code?	public partial class CustomControl : UserControl, ISupportInitialize {\n    public CustomControl() {\n        InitializeComponent();\n    }\n    private bool initializing;\n    private string id = "";\n\n    public string ID {\n        get { return id; }\n        set { id = value;\n              if (!initializing) label1.Text = value;\n        }\n    }\n    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]\n    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\n    public override string Text {\n        get { return base.Text; }\n        set {\n            base.Text = value;\n            if (!initializing && !this.DesignMode) label1.Text = value;\n        }\n    }\n\n    public void BeginInit() {\n        initializing = true;\n    }\n\n    public void EndInit() {\n        initializing = false;\n        label1.Text = ID;\n    }\n}	0
3319827	3319675	How to retrieve the value of a Custom Attribute from a DLL Loaded at runtime?	using System;\n[AttributeUsage(AttributeTargets.Class)]\npublic class ValidReleaseToApp : Attribute\n{\n    private string _releaseToApplication;\n    public string ReleaseToApplication { get { return _releaseToApplication; } }\n\n    public ValidReleaseToApp(string ReleaseToApp)\n    {\n        this._releaseToApplication = ReleaseToApp;\n    }\n} \n\n\nAssembly a = Assembly.LoadFrom(PathToDLL);\nType type = a.GetType("Namespace.ClassName", true);\nSystem.Reflection.MemberInfo info = type;\nvar attributes = info.GetCustomAttributes(true);\nif(attributes[0] is ValidReleaseToApp){\n   string value = ((ValidReleaseToApp)attributes[0]).ReleaseToApplication ;\n   MessageBox.Show(value);\n}	0
9126283	9126228	How to set string in Enum C#?	private IddFilterCompareToCurrent myEnum = \n(IddFilterCompareToCurrent )Enum.Parse(typeof(IddFilterCompareToCurrent[1]),domainUpDown1.SelectedItem.ToString());	0
34237940	34237920	Add list to another one - nested list	List<List<String>> inner = new List<List<String>>();\nList<String> leaves = new List<String>();\n\nleaves.Add( "some string" );\ninner.Add( leaves );\nlist.Add( inner );	0
8580158	8580053	How to load kml file into google map?	var layer = new google.maps.KmlLayer('<url of your KML file>');\nlayer.setMap(map);	0
5430591	5425122	Showing Mouse Axis Coordinates on Chart Control	private void chart1_MouseWhatever(object sender, MouseEventArgs e)\n{\n    chartArea1.CursorX.SetCursorPixelPosition(new Point(e.X, e.Y), true);\n    chartArea1.CursorY.SetCursorPixelPosition(new Point(e.X, e.Y), true);\n\n    double pX = chartArea1.CursorX.Position; //X Axis Coordinate of your mouse cursor\n    double pY = chartArea1.CursorY.Position; //Y Axis Coordinate of your mouse cursor\n}	0
10348415	10347549	Criteria method for nhibernate	public static List<T> ToList(DetachedCriteria criteria)\n{\n    ISession session = NhSessionHelper.GetCurrentSession();\n    List<T> l = criteria.GetExecutableCriteria(session).List<T>();\n    return l;\n}	0
11051601	11051572	Access to methods which is in another classlibrary,HOW?	MyLibrary.MyClass.MyMethod();	0
30682809	29912136	Converting a Outlook mail attachment to byte array with C#	const string PR_ATTACH_DATA_BIN = "http://schemas.microsoft.com/mapi/proptag/0x37010102";\n\nOutlook.Attachment attachment = mail.Attachments[0];  \n\n// Retrieve the attachment as a byte array\nvar attachmentData =\n    attachment.PropertyAccessor.GetProperty(PR_ATTACH_DATA_BIN);	0
30868993	30868863	How do I delete DB rows for a range of partial keys?	Delete from TABLENAME \n  where (FOO = <foo_value1> AND BAR = <bar_value1>)\n     or (FOO = <foo_value2> AND BAR = <bar_value2>);	0
9832895	9784567	.NET equivalent of curl to upload a file to REST API?	var strICS = "text file content";\n\nbyte[] data = Encoding.UTF8.GetBytes (strICS);\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://someurl.com");\nrequest.PreAuthenticate = true;\nrequest.Credentials = new NetworkCredential ("username", "password");;\nrequest.Method = "PUT";\nrequest.ContentType = "text/calendar";\nrequest.ContentLength = data.Length;\n\nusing (Stream stream = request.GetRequestStream ()) {\n    stream.Write (data, 0, data.Length);\n}\n\nvar response = (HttpWebResponse)request.GetResponse ();\nresponse.Close ();	0
28718634	28590223	WCF request-response logging via custom Trace Listener at one go	public object BeforeSendRequest(ref Message request, IClientChannel channel)\n{            \n        var key = request.Headers.MessageId.ToString();\n\n        //Do stuff\n\n        return null;\n}\npublic void AfterReceiveReply(ref Message reply, object correlationState)\n{            \n        var key = reply.Headers.RelatesTo.ToString();            \n\n        //Do stuff\n}	0
30598568	30597481	Understanding if statement syntax in c#	if(apollo.Any(item => item.Contains("Savings found")))	0
26608601	26608203	How to get registry keys and values in listview	listView1.View = View.Details;\nlistView1.Columns.Add("Name", 150);\nlistView1.Columns.Add("Data", 300);\n\nRegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");\nforeach (string keyName in key.GetValueNames())\n{\n    listView1.Items.Add(\n        new ListViewItem(\n            new string[] { keyName, key.GetValue(keyName).ToString() }\n        )\n    );\n}	0
21825674	21825110	How to get the row index of a WPF Datagrid?	private void imgDel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n{            \n     DependencyObject dataGridRow = sender as DependencyObject;\n     while (dataGridRow != null && !(dataGridRow is DataGridRow)) dataGridRow = VisualTreeHelper.GetParent(dataGridRow);\n     if (dataGridRow!= null)\n     {\n           // dataGridRow now contains a reference to the row,\n     }    \n}	0
11405014	11403065	C# Drawing - best solution	private void panelDraw_Paint(object sender, PaintEventArgs e)\n{\n    redrawDrawingPanel();\n}	0
27018624	27017971	Changing an unhandled exception to a handled one in a finally block	.method private hidebysig static void  Main(string[] args) cil managed\n{\n  .entrypoint\n  // Code size       49 (0x31)\n  .maxstack  1\n  IL_0000:  nop\n  IL_0001:  nop\n  .try\n  {\n    IL_0002:  nop\n    .try\n    {\n      IL_0003:  nop\n      IL_0004:  newobj     instance void A::.ctor()\n      IL_0009:  throw\n    }  // end .try\n    finally\n    {\n      IL_000a:  nop\n      IL_000b:  newobj     instance void B::.ctor()\n      IL_0010:  throw\n    }  // end handler\n  }  // end .try\n  catch B \n  {\n    IL_0011:  pop\n    IL_0012:  nop\n    IL_0013:  ldstr      "B"\n    IL_0018:  call       void [mscorlib]System.Console::WriteLine(string)\n    IL_001d:  nop\n    IL_001e:  nop\n    IL_001f:  leave.s    IL_0021\n  }  // end handler\n  IL_0021:  nop\n  IL_0022:  nop\n  IL_0023:  nop\n  IL_0024:  ldstr      "A"\n  IL_0029:  call       void [mscorlib]System.Console::WriteLine(string)\n  IL_002e:  nop\n  IL_002f:  nop\n  IL_0030:  ret\n} // end of method Program::Main	0
2737575	2737500	How to pass a const unsigned char * from c++ to c#	void dump_body(const unsigned char *body, int bodyLen)\n{\n    // you might want a different encoding...\n    String ^str = gcnew String((sbyte*)body, 0, bodyLen, gcnew ASCIIEncoding);\n    MyParser::Parser::DumpBody(str);\n}	0
498349	498224	Best way to test for existing string against a large list of comparables	var acronyms = new[] { "AB", "BC", "CD", "ZZAB" };\nvar regex = new Regex(string.Join("|", acronyms), RegexOptions.Compiled);\nfor (var match = regex.Match("ZZZABCDZZZ"); match.Success; match = match.NextMatch())\n    Console.WriteLine(match.Value);\n// returns AB and CD	0
28819490	28819215	String Combinations With Character Replacement	public static IEnumerable<string> Combinations(string input)\n{\n    int firstZero = input.IndexOf('0');   // Get index of first '0'\n    if (firstZero == -1)      // Base case: no further combinations\n        return new string[] { input };\n\n    string prefix = input.Substring(0, firstZero);    // Substring preceding '0'\n    string suffix = input.Substring(firstZero + 1);   // Substring succeeding '0'\n    // e.g. Suppose input was "fr0d00"\n    //      Prefix is "fr"; suffix is "d00"\n\n    // Recursion: Generate all combinations of suffix\n    // e.g. "d00", "d0o", "do0", "doo"\n    var recursiveCombinations = Combinations(suffix);\n\n    // Return sequence in which each string is a concatenation of the\n    // prefix, either '0' or 'o', and one of the recursively-found suffixes\n    return \n        from chr in "0o"  // char sequence equivalent to: new [] { '0', 'o' }\n        from recSuffix in recursiveCombinations\n        select prefix + chr + recSuffix;                                    \n}	0
7796945	7796895	determining modulus numbers on 0-based array	if(i % 4 == 2)	0
6689972	6689938	Determining a calendar year (with/without leap-years)	AddDays(364)	0
22006722	22006289	How to select descendant nodes of XML in c#?	var xml = @"<A>\n      <X>\n        <B  id=""ABC"">\n          <C name=""A"" />\n          <C name=""B"" />\n          <C name=""C"" />\n          <C name=""G"" />\n        </B>\n        <B id=""ZYZ"">\n          <C name=""A"" />\n          <C name=""B"" />\n          <C name=""C"" />\n          <C name=""D"" />\n        </B>\n      </X>\n</A>";\nvar doc = XDocument.Parse(xml);\nvar newDoc = new XElement("Result", doc.Root.Element("X").Elements());\n\n//this will print the same output as you expect (the 2nd XML in question)\nConsole.WriteLine(newDoc.ToString());	0
29084264	29082021	How to call ManagementObject with more than one parameter?	var bcdId = "{current}";\nvar sfp = "";\nvar obj = new ManagementObject(\n    "root\\WMI:BcdObject.Id=\"" + bcdId + "\",StoreFilePath=\"" + sfp + "\"");	0
17757833	17757520	Find a node by attribute and return a different attribute's value from that same node	var xml = @"<Critic-List>\n  <bruce-bennett>\n   <Movie Title=""White House Down (2013)"" Score=""C+"" Like=""false""/>\n   <Movie Title=""Despicable Me 2 (2013)"" Score=""A-"" Like=""true""/>\n   <Movie Title=""World War Z (2013)"" Score=""B+"" Like=""true""/>\n   <Movie Title=""Man of Steel (2013)"" Score=""B+"" Like=""true""/>    \n  </bruce-bennett>\n  </Critic-List>";\nXElement doc = XElement.Parse(xml);\n\nvar node = doc.XPathSelectElement("//Movie[@Title='Despicable Me 2 (2013)']");\nvar like = node.Attribute("Like").Value;	0
28826420	28825068	c# change file link path using regex	const string originalPath = @"file:\\mail\attach\2015_02\random file name";\nvar newPath = Regex.Replace(originalPath, @"file:\\{2}(.+)", @"file:\$1");\nConsole.WriteLine(newPath);	0
16694630	16692539	How to access remote machine to add/remove/manage users accounts?	using System.DirectoryServices;\n\nDirectoryEntry deParent = new DirectoryEntry("WinNT://[computername]", \n         @"[domain\adminname", "password");            \nDirectoryEntry deToRemove = deParent.Children.Find("usernametoremove");\ndeParent.Children.Remove(deToRemove);	0
20049045	20048868	Padding a zero to the beginning of a string	if (value.Length > 0 && value[0] == ' ')\n    value = '0' + value.Substring(1);	0
499863	499848	How to programmatically add a Tab to TabControl with a ListView control docked inside it?	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\n    // Create the listView\n    Dim lstView As New ListView()\n    lstView.Dock = DockStyle.Fill\n    lstView.Items.Add("item 1") //item added for test\n    lstView.Items.Add("item 2") //item added for test\n\n    // Create the new tab page\n    Dim tab As New TabPage("next tab")\n    tab.Controls.Add(lstView) // Add the listview to the tab page\n\n    // Add the tabpage to the existing TabCrontrol\n    Me.TabControl1.TabPages.Add(tab)\n\nEnd Sub	0
31102486	31101803	Implementing OpenID in ASP5	aspnet-contrib	0
31573700	31573630	Launch one project's executable from another project	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    WpfApplication1.MainWindow mw = new WpfApplication1.MainWindow();\n    mw.Show();\n}	0
18022692	18022368	Automatic Sequential number for grouped items in LINQ	var list = MainList.Join(DetailsList, x=>x.ID, x=>x.MAINLink,(x,y)=> new {x,y})\n                   .GroupBy(a=>a.x.ID)\n                   .Select(g=>g.Select((k,i)=>new {k,i}))\n                   .SelectMany(a=>a)\n                   .Select((a)=> new {\n                                     Main = a.k.x,\n                                     SequentialNUM = a.i + 1,\n                                     Detail = a.k.y\n                                   })\n                   .OrderBy(x=>x.Main.Id);	0
1673384	1673153	How can I check a url is publicly accessible?	class Program\n{\n    static void Main(string[] args)\n    {\n        PingReply reply = null;\n        PingOptions options = new PingOptions();\n        options.DontFragment = true;\n        Ping p = new Ping();\n        for (int n = 1; n < 255 && (reply == null || reply.Status != IPStatus.Success); n++)\n        {\n            options.Ttl = n;\n            reply = p.Send("www.yahoo.com", 1000, new byte[1], options);\n            if (reply.Address != null)\n                Console.WriteLine(n.ToString() + " : " + reply.Address.ToString());\n            else\n                Console.WriteLine(n.ToString() + " : <null>");\n        }\n        Console.WriteLine("Done.");\n        System.Console.ReadKey();\n    }\n}	0
22873997	22873825	How to detect shift+tab when overriding ProcessCmdKey	if (keyData == (Keys.Shift | Keys.Tab)) isShiftTab = true;	0
2931090	2930339	How get the offset of term in Lucene?	TermPositionVector vector = (TermPositionVector) reader.getTermFreqVector(docId, myfield);	0
14858281	14857780	Create Right-Click Dialog in .NET Application	ContextMenu myContextMenu = new ContextMenu();\n// Set various options for the context menu\n\nmyControl.ContextMenu = myContextMenu;	0
9786179	9786167	Find the URL of the current web application	string app = HttpContext.Current.Request.ApplicationPath;	0
4844478	4844465	Inject a value to object properties at run time in c#	var baseType = Type.GetType("ChildForm");\nSystem.Windows.Forms.Form formCall = (ChildForm)System.Activator.CreateInstance(baseType);\nbaseType.GetField("childId").SetValue(formCall, 5);	0
13617876	13601799	TLS connection: override certificate validation	private async void MainPage_Loaded(object sender, RoutedEventArgs e)\n    {\n        Launcher.LaunchFileAsync(await Package.Current.InstalledLocation.GetFileAsync("FiddlerRoot.cer"));\n    }	0
6219488	6219454	Efficient way to remove ALL whitespace from String?	Regex.Replace(XML, @"\s+", "")	0
20022345	20021840	How to set the insertion point at the first line of textbox?	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n\n        if (e.KeyChar == (char)Keys.Enter)\n        {\n            e.Handled = true;\n            if (textBox1.Text.Trim() == "")\n                {\n                MessageBox.Show("Empty");\n                textBox1.Focus();\n                 }\n           else \n           textBox2.Focus();\n\n        }\n    }	0
9821313	9821234	Writing a file from StreamReader stream	Stream stream = MyService.Download(("1231"));\nusing (Stream s = File.Create(path))\n{\n    stream.CopyTo(s);\n}	0
19980824	19977696	local movement on rigidbody sphere with the mouse and keyboard	public GameObject Camera;\npublic float moveSpeed = 0.0f;\n\nif (Input.GetKey ("right") || Input.GetKey ("d")) {\n    rigidbody.AddForce( Camera.transform.right * moveSpeed * Time.deltaTime);\n}\n\nif (Input.GetKey ("left") || Input.GetKey ("a")) {\n    rigidbody.AddForce( -Camera.transform.right * moveSpeed * Time.deltaTime);\n}\n\nif (Input.GetKey ("up") || Input.GetKey ("w")) {\n    rigidbody.AddForce( Camera.transform.forward * moveSpeed * Time.deltaTime);\n}\n\nif (Input.GetKey ("down") || Input.GetKey ("s")) {\n    rigidbody.AddForce( -Camera.transform.forward * moveSpeed * Time.deltaTime);\n}	0
2821742	2821688	My dataset contains two tables i need to get division of FirstTable.Row2/SecondTable.Row5	DataSet ds = GetMyData();\n// You should check here for there being at least 2 tables in the DataSet\n// and that Table 1 has at least 2 rows and Table 2 has at least 5 rows.\nvar result = \n    ds.Tables[0].Rows[1]["YourField"] / ds.Tables[1].Rows[4]["YourOtherField"];	0
3410628	3403890	Nhibernate Projection Query DTO, use method in stead of property	var criteria = someCriteriaThatReturnsPersistentEntities;\nvar items = criteria.List<IMailOrderAssignee>();\nvar projected = items.Select(i => new\n                                  {\n                                      Prop1 = i.SomeMethod(),\n                                      Etc\n                                  });	0
10195422	10195267	How to accessing WCF APIs in Silverlight?	APIRefClient.AddNums(x,y);	0
18023136	18023070	How to access Parameter Value of public method inside private method	public partial class EditQuestionMaster : Form\n    {\n        DbHandling db = new DbHandling();\n        int qid; // here is the class variable\n        public EditQuestionMaster(int qid_value)\n        {\n            InitializeComponent();\n\n            this.qid = qid_value; // set the value here\n\n            string subNtop = db.GetEditSubNTopic(qid_value);\n            string[] subNtopData = subNtop.Split('~');\n            cmbSubject.Text = subNtopData[2];                \n        }\nprivate void button1_Click(object sender, EventArgs e)\n        {       \n\n            qid // use it here	0
9825367	9825136	How create proxy class from wsdl?	wsdl.exe wsdl.wsdl /out:Proxy.cs	0
1429978	1429889	Calling constructor from other constructor in same class at the end	class Form1\n{\n   public Form1(Class1 c1)\n   {\n      if (c1 != null) this.member = c1.member;\n   }\n\n   public Form1() : this(null)\n   {\n   }\n}	0
19467847	19467690	MVC SQLQuery comparing database date with current date	var billPays = from s in db.BillPays.SqlQuery("SELECT * FROM BillPay WHERE '"+ DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")+"' > ScheduleDate").ToList()\n\nselect new BillPayModel\n    {\n            //model             \n    };	0
7611480	7611402	How to get the date of the next Sunday?	public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek)\n    {\n        int start = (int)from.DayOfWeek;\n        int target = (int)dayOfWeek;\n        if (target <= start)\n            target += 7;\n        return from.AddDays(target - start);\n    }	0
24290709	24289297	How to make Trackbar works while media is playing	public partial class Form1 : Form\n    {\n        Timer t;\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            axWindowsMediaPlayer1.URL = "YourUrlHere";\n            t = new Timer();\n            t.Interval = 1000;\n            t.Tick += new EventHandler(t_Tick);\n        }\n\n        void t_Tick(object sender, EventArgs e)\n        {\n            trackBar1.Value = (int)this.axWindowsMediaPlayer1.Ctlcontrols.currentPosition;\n        }\n\n        private void axWindowsMediaPlayer1_OpenStateChange(object sender, AxWMPLib._WMPOCXEvents_OpenStateChangeEvent e)\n        {\n            if (axWindowsMediaPlayer1.openState == WMPLib.WMPOpenState.wmposMediaOpen)\n            {\n                trackBar1.Maximum = (int)axWindowsMediaPlayer1.currentMedia.duration;\n                t.Start();\n            }\n        }\n    }	0
4815525	4815401	C# XML Serialization	[XmlRoot(ElementName="panel")]\npublic class Panel\n{\n    [System.Xml.Serialization.XmlElementAttribute("tr")]\n    public List<Tr> tr { get; set; }\n}\n\npublic class Tr\n{\n    [System.Xml.Serialization.XmlElementAttribute("td")]\n    public List<Td> td { get; set; }\n}\n\npublic class Td\n{\n    [System.Xml.Serialization.XmlElementAttribute("element")]\n    public Element Element { get; set; }\n}\n\npublic class Element\n{\n    [System.Xml.Serialization.XmlText]\n    public string prop { get; set; }\n}	0
26753144	26752815	Regular expression getting html between two comments	string afterFirst = html.Substring(Regex.Match(html, emailFeedTxtStart).Index + emailFeedTxtStart.Length);\n    string between = afterFirst.Substring(0, Regex.Match(afterFirst, emailFeedTxtEnd).Index);	0
4177355	4177332	Convert Stopwatch to int	Stopwatch czasAlg = new Stopwatch();\nczasAlg.Start(); \n//Do something \nczasAlg.Stop();\ndouble timeInSecondsPerN=czasAlg.Elapsed.TotalSeconds/n;	0
5288064	5287870	Reference hidden field generated from jQuery from C# with ASP.NET	Request["hiddenInputName"]	0
5417798	5417242	C# changing image of a button just paste's the new image ontop of the old image	//Change old image to null\nbtnterug.BackgroundImage = null;\n//Load New Image\nbtnterug.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.InfoProject2));	0
12093377	12092575	Html Agility Pack - Remove element, but not innerHtml	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar node = doc.DocumentNode.SelectSingleNode("//removeme");\nnode.ParentNode.RemoveChild(node, true);	0
17712695	17712557	Pull value of a particular node using XPath	XNamespace ns="http://ratequote.usfnet.usfc.com/v2/x1";\nvar doc = XDocument.Parse(xml); //or whatever\nvar costNode = doc\n    .Root\n    .Descendants(ns + "SERVICEUPGRADES")\n    .Single(e => (string)e.Element(ns + "SERVICE_TYPE") == "regional delivery")\n    .Element(ns + "TOTAL_COST");\nvar cost = (decimal)costNode;	0
13025767	13024233	Validate a string between another string?	string word=Regex.Escape("rang");//your word..used regex.escape to escape regex characters if any\n\nRegex rx = new Regex("\b(.*?)"+word+"(.*?)\b", RegexOptions.IgnoreCase);\n\nforeach (Match m in rx.Matches(yourInputText))\n{\n    if(m.Groups[1]!="" || m.Groups[2]!="")\n    {\n        //the word is between some words\n    }\n    else\n    {\n        //the word occurs separately\n    }\n}	0
15967636	15967546	C# XSD schema - how to get main properties values?	var attributes = (from n in xml.Root.Attributes("someProperty")\n                        select n.Value).ToList();	0
8034704	8008120	How to Use Custom Dictionary Class for DynamicComponent Mapping	mapping.Component(x => x.DynamicFields, c => c.DynamicComponent(\n    Reveal.Member<CustomDictionary, IDictionary>("_innerDictionary"),\n    c => {\n        c.Map(x => x["fld_num"]).CustomType(typeof(int));\n        c.Map(x => x["shortdesc"]).CustomType(typeof(string));\n    })\n);	0
13064024	13063693	Increase the maxRequestLength/executionTimeout of a ServiceHost in C#	var binding = new BasicHttpBinding { MaxReceivedMessageSize = 20000; };	0
17412681	17410362	Amazon AWS RDS - How to Programmatically Create a MS SQL Table in C#	USE Contacts; CREATE TABLE ContactDetails (Id INT NOT NULL PRIMARY KEY)	0
10201149	10201111	C# automation application 	Console Application	0
3502265	3502109	How to split a string in C#	string foo = "Eternal (woman)";\nstring bar = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);\n\nConsole.WriteLine(bar);    // "Eternal (Woman)"	0
7570485	7570287	Data Binding in if statements	Text='<%# (Eval("Integration").ToString() == "Y") ? DataBinder.Eval(Container.DataItem, "CustItem") : "" %>'	0
24534994	24534709	Remove substring in ASP.NET markup using LINQ	((Category)Container.DataItem).CategoryItems.Where(p => p.Active == true).OrderBy(p => p.Name.StartsWith("The ") ? p.Name.Substring(4): p.Name)	0
19752364	19751823	database for every user? or every one in same database	CREATE TABLE user (\n int id NOT NULL,\n .... // user data fields will come here...\n PRIMARY KEY(id)\n) ENGINE = InnoDB;\n\nCREATE TABLE map (\n int id NOT NULL,\n .... // map data fields will come here...\n PRIMARY KEY(id)\n) ENGINE = InnoDB;\n\nCREATE TABLE item (\n int id NOT NULL,\n .... // item data fields will come here...\n PRIMARY KEY(id)\n) ENGINE = InnoDB;\n\nCREATE TABLE map_has_item (\n  int map_id NOT NULL,\n  int item_id NOT NULL,\n  PRIMARY KEY (map_id, item_id),\n  FOREIGN KEY (map_id) REFERENCES map (id),\n  FOREIGN KEY (item_id) REFERENCES item (id)\n) ENGINE = InnoDB;\n\nCREATE TABLE user_has_map (\n  int user_id NOT NULL,\n  int map_id NOT NULL,\n  PRIMARY KEY (user_id, map_id),\n  FOREIGN KEY (user_id) REFERENCES user (id),\n  FOREIGN KEY (map_id) REFERENCES map (id)\n) ENGINE = InnoDB;	0
1508131	1508091	How do I click an ASP.NET webform's button when the page is hosted in a WebBrowser Control	WebBrowser1.Document.getElementById("mybutton").InvokeMember("click");	0
7841188	7841019	Converting dynamic C# objects to array	class Test\n{\n}\n\ndynamic dyn = new Test();\n\nTest[] tests = null;\n\nif (dyn is Test)\n{\n    tests = new Test[] { (Test)dyn };\n}\nelse if (dyn is Test[])\n{\n    tests = (Test[])dyn;\n}	0
33660261	33642513	How to copy table index to another table in ado.net	SqlBulkCopyOptions options = SqlBulkCopyOptions.KeepIdentity;\n        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection.ConnectionString, options))\n        {\n            bulkCopy.DestinationTableName = destTableName;\n                // Write from the source to the destination.\n            bulkCopy.WriteToServer(reader);\n        }	0
14351074	14350987	Enable disable button on text changed in c# winform	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        this.button1.Enabled = !string.IsNullOrWhiteSpace(this.textBox1.Text);\n    }	0
740948	740937	Accessing variables from other namespaces	namespace My.Namespace\n{\n    public class MyClassA\n    {\n        public void MyMethod()\n        {\n            // Use value from MyOtherClass\n            int myValue = My.Other.Namespace.MyOtherClass.MyInt;\n        }\n    }\n}\n\nnamespace My.Other.Namespace\n{\n    public class MyOtherClass\n    {\n        private static int myInt;\n        public static int MyInt\n        {\n            get {return myInt;}\n            set {myInt = value;}\n        }\n\n        // Can also do this in C#3.0\n        public static int MyOtherInt {get;set;}\n    }\n}	0
2498842	2498788	assign a xaml file in a frame source dynamically	ProjectTab.Source = new Uri("/ProjectTab.xml", UriKind.Relative);	0
10166353	10166001	MonoTouch: Localization from a Common Project	using System;\nusing MonoTouch.Foundation;\n\nnamespace Common.Localization\n{\n[Preserve]\npublic class DummieClassNeededToMakeLocalizationCompileToaDLL\n{\n    [Preserve]\n    public DummieClassNeededToMakeLocalizationCompileToaDLL ()\n    {\n    }\n}\n}	0
2714257	2714221	How to deal with Rounding-off TimeSpan?	public static TimeSpan Round(TimeSpan input)\n{\n    if (input < TimeSpan.Zero)\n    {\n        return -Round(-input);\n    }\n    int hours = (int) input.TotalHours;\n    if (input.Minutes >= 30)\n    {\n        hours++;\n    }\n    return TimeSpan.FromHours(hours);\n}	0
23342799	23339217	Navigate to one specific Item from one group with LongListSelector	longListSelector.ScrollTo(((AlphaKeyGroup<Object>)longListSelector.ItemsSource[x])[y]);	0
21012359	21012296	How to get Unique list of particular column based on condition on another column in LIST<T>	var results = input.Select(x => new { x.BirthMonth, x.BirthYear }).Distinct().ToList();	0
1059992	1059955	How do I use eventhandler from baseclass	public class MyBaseClass {\n    protected virtual void OnSomethingHappend( EventArgs e ) {\n        EventHandler handler = this.SomethingHappend;\n        if ( null != handler ) { handler( this, e ); }\n    }\n    public event EventhHandler SomethingHappend;\n}\n\npublic MyDerivedClass : MyBaseClass {\n    public void DoSomething() {\n        this.OnSomethingHappend( EventArgs.Empty );\n    }\n}	0
24200549	24200475	How to send a string to a method which decoding a string64?	byte[] bytes = System.Text.Encoding.UTF8.GetBytes(originalString);\nstring base64 = System.Convert.ToBase64String(bytes);	0
22422594	22422021	How do I verify that ryujit is jitting my app?	protojit.dll	0
7537265	7537230	What will be the fastest way to access an element from a collection?	GetHashCode()	0
26315341	26315291	Categorize duplicate elements under same key	var duplicateIPConnections = connectionsList.OrderBy(x => x.IP)\n                   .GroupBy(x => x.IP)\n                   .Select(g => new\n                   {\n                       Type = g.Key,\n                       Sites = g.Select(obj => new\n                       {\n                           obj.IP,\n                           obj.Name\n                       })\n                   });	0
8064817	8064672	Getting RGB colors	Accent 1: #4f81bd\nAccent 2: #c0504d\nAccent 3: #9bbb59\nAccent 4: #8064a2\nAccent 5: #4bacc6\nAccent 6: #f79646	0
8119812	8035028	Omitting doctype declaration of an XML when applying XSLT	XmlReaderSettings x = new XmlReaderSettings();\nx.DtdProcessing = DtdProcessing.Ignore;\nmyXslTransform.Load(xslFile);\nmyXslTransform.Transform(XmlReader.Create(xslFile, x), XmlWriter.Create(xmlFileOutput));	0
18727295	18727183	Convert Exponential to Integer	var i = System.Numerics.BigInteger.Parse("2.200000000000E+09",\n                         NumberStyles.Float ,\n                         CultureInfo.InvariantCulture);	0
27943022	27942648	Using an array to navigate to ViewControllers	if ([self.navigationController.viewControllers[[self.navigationController.viewControllers count]-2] isKindOfClass:[NewDoubleCheck class]]) {\n    // ViewController already exist, so we need to get back to it \n    NewDoubleCheck *viewController = (NewDoubleCheck *)self.navigationController.viewControllers[[self.navigationController.viewControllers count]-2];\n    [self.navigationController popToViewController:viewController animated:YES];\n  } else {\n    // Push to NewDoubleCheck\n  }	0
9534073	9533864	Self-Binding with Castle Windsor in C#	MyClass mc = container.Resolve<MyClass>();	0
2777991	2777937	How to wrap two unmannaged C++ functions into two managed C# functions?	[DllImport("Name.dll")]\n    private static extern IntPtr Compress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size);\n\n    [DllImport("Name.dll")]\n    private static extern IntPtr Decompress([MarshalAs(UnmanagedType.LPArray)]byte[] buffer, int size);\n\n    public static byte[] Compress(byte[] buffer) {\n        IntPtr output = Compress(buffer, buffer.Length);\n        /* Does output need to be freed? */\n        byte[] outputBuffer = new byte[/*some size?*/];\n        Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length);\n        return outputBuffer;\n    }\n\n    public static byte[] Decompress(byte[] buffer) {\n        IntPtr output = Decompress(buffer, buffer.Length);\n        /* Does output need to be freed? */\n        byte[] outputBuffer = new byte[/*some size?*/];\n        Marshal.Copy(output, outputBuffer, 0, outputBuffer.Length);\n        return outputBuffer;\n    }	0
1528784	1528767	Using a IList, how to populate it via a comma separated list of ID's	public IList CategoryIDs\n{\n    get\n    {\n        return list.Split(',')\n                .ToList<string>()\n                .ConvertAll<int>(new Converter<string, int>(s => int.Parse(s)));\n    }\n}	0
4841162	4835609	How to use Castle ActiveRecord with SQL Server 2008 FILESTREAM feature	[Property(Unique = true, NotNull = true, SqlType = "UNIQUEIDENTIFIER ROWGUIDCOL", Default = "(newid())")]\npublic Guid ImageGuid { get; set; }\n\n[Property(SqlType = "VARBINARY(MAX) FILESTREAM")]\npublic byte[] ImageFile { get; set; }	0
4139093	4139062	c# using excel to open xml file	System.Diagnostics.Process.Start("c:\\program files\\microsoft office\\office12\\excel.exe", "/r \"c:\\My Folder\\book1.xlsx\"");	0
32431048	32430759	Strip leading characters from a directory path in a listbox in C#	string folderName = steamPath.SelectedPath;\n    foreach (string f in Directory.GetDirectories(folderName))\n    {\n       // string[] strArr = f.Split('\\');\n        lb_FromFolder.Items.Add(f.Split('\\')[f.Split('\\').Length-1]);\n    }	0
25419585	25419463	Sorting iEnumerable with external iEnumerable	var sorted = from c in combinations\n             join s in sizes on c.Name equals s.InventSizeName\n             orderby s.Order\n             select c;	0
14968584	14968553	Using the += operator with delimiter	Label1.Text.Trim(',');	0
32247739	32232674	How to compare performance of messagepack-cli and json.net deserializers?	public void test_json(int _num, Test_Class _obj)\n{\n    JsonSerializer serializer = new JsonSerializer();\n\n    MemoryStream stream = new MemoryStream();\n\n    StreamWriter writer = new StreamWriter(stream);\n    JsonTextWriter jsonWriter = new JsonTextWriter(writer);\n    serializer.Serialize(jsonWriter, _obj);\n    jsonWriter.Flush();\n\n    Stopwatch stopWatch = new Stopwatch ();\n    stopWatch.Start ();\n    while (_num > 0) {\n        _num -= 1;\n        stream.Position = 0;\n\n        StreamReader reader = new StreamReader(stream);\n        JsonTextReader jsonReader = new JsonTextReader(reader);\n        Test_Class deserialised_object = serializer.Deserialize<Test_Class>(jsonReader);\n    }\n    stopWatch.Stop ();\n    TimeSpan ts = stopWatch.Elapsed;\n    string elapsedTime = String.Format ("{0:00}:{1:00}:{2:00}.{3:00}",\n        ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);\n\n    print ("json read: " + elapsedTime);\n}	0
11265047	11264828	reading bools from one form to another c#	public bool Room1;\npublic bool Room2;\npublic bool Room3;\npublic bool Room4;\npublic bool Room5;\nprivate void btnRoom1_Click(object sender, EventArgs e)\n{\n    this.Hide();\n\n    Room1 = true;\n    Room2 = false;\n    Room3 = false;\n    Room4 = false;\n    Room5 = false;\n\n    //This displays Form2\n    Form2 RoomTemplate = new Form2(this);\n    RoomTemplate.Show();\n}\n\npublic class Form2()\n{\n    public Form2(Form1 form1)\n    {\n        InitializeComponent();\n        if(form1.Room1 == true)\n        {\n            lblTitle.Text="Living Room";\n        }\n        else if(form1.Room2==true)\n        {\n            //\n        }\n        //\n    }\n}	0
22160784	22159386	Is there any delivered method which takes in timezoneoffset of UTC and calculate timezone in C#?	America/New_York	0
23672695	23671992	Passing local variables to expression tree as collection list	BlockExpression block = Expression.Block(\n    new ParameterExpression[] { i },\n    lines.ToArray()\n    );	0
4351141	4350992	how to format the date in various formats?	.ToRelativeDateString()	0
18563940	18563617	WMI to retrieve website physical path in c#	ManagementObjectSearcher searcher =\n   new ManagementObjectSearcher("root\\MicrosoftIISv2", \n                                "SELECT * FROM IIsWebVirtualDirSetting");\n\nforeach (ManagementObject queryObj in searcher.Get())\n{\n   result.Add(queryObj["Path"]);\n}	0
34334086	34306446	How to get the path of an open folder	string path = null;\nforeach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindows()) {\n    if (your_known_explorer_HWND == window.HWND) {\n        path = new Uri(window.LocationURL).LocalPath);\n        break;\n    }\n}	0
306629	306527	How would I pass additional parameters to MatchEvaluator	private string MyMethod(Match match, bool param1, int param2)\n{\n    //Do stuff here\n}\n\nRegex reg = new Regex(@"{regex goes here}", RegexOptions.IgnoreCase);\nContent = reg.Replace(Content, new MatchEvaluator(delegate(Match match) { return MyMethod(match, false, 0); }));	0
31598825	31591601	Data Source Patterns - Where's to put table's level methods?	User.getAllActiveUsers();	0
17105843	17105451	How to combine LINQ querys with different where conditions	var querySalesLabMat = \n   from b in bookings.AsEnumerable()\n   group b by new\n   {\n       b.Field<DateTime>("Date").Year,\n       b.Field<DateTime>("Date").Month,\n   } into g\n   orderby g.Key.Year, g.Key.Month\n   select new\n   {\n       g.Key.Year,\n       g.Key.Month,\n       LabourCosts = g.Where(r => r.Field<Int32>("t-account") >= tAccLabFrom && r.Field<Int32>("t-account") <= tAccLabTo)\n                      .Sum(r => r.Field<Decimal>("Sales_Debit") - r.Field<Decimal>("Sales_Assets")),\n       Sales = g.Where(r => r.Field<Int32>("t-account") >= tAccSalesFrom && r.Field<Int32>("t-account") <= tAccSalesTo)\n                .Sum(r => r.Field<Decimal>("Sales_Assets") - r.Field<Decimal>("Sales_Debit")),\n       MaterialCosts = g.Where(r => r.Field<Int32>("t-account") >= tAccMatFrom && r.Field<Int32>("t-account") <= tAccMatTo)\n                        .Sum(r => r.Field<Decimal>("Sales_Debit") - r.Field<Decimal>("Sales_Assets"))\n   };	0
8585074	8583958	how to wait for ThreadState.Abort?	th.Abort();\nth.Join();	0
10951387	10951052	Get rel value from URL link	XDocument x = XDocument.Parse("<xml><link rel=\"prev\" type=\"application/atom+xml\" href=\"/v3.2/en-us/\" /> <link rel=\"next\" type=\"application/atom+xml\" href=\"/v3.2/en-us/\" /></xml>");\n\nXElement link = x.Descendants("link")\n                 .FirstOrDefault(a => a.Attribute("rel").Value == "next");\n\nString href = string.Empty;\nif(link != null)\n{\n     href = link.Attribute("href").Value; \n}	0
14127420	14127029	Using Color specified in SpriteBatch.Draw with Custom shader	float4 NoEffects(float4 color : COLOR0, float2 coords : TEXCOORD0) : COLOR0\n{\n    return tex2D(s0, coords) * color;\n}	0
15472979	15472146	Translating a code example from c# into c++	private: Control ^ getFocused(Control::ControlCollection ^controls)\n{\n    for each (Control ^c in controls)\n    {\n        if (c->Focused)\n        {\n            return c;\n        }\n        else if (c->ContainsFocus)\n        {\n            return getFocused(c->Controls);\n        }\n    }\n\n    return nullptr;\n}	0
16341179	16339278	Find missing information between 2 lists	var missingGroup =\n        users.ToDictionary(user => user.UserName, user => \n            user.MemberOf.Except(groups.Select(w => w.Name)))\n            .Where(f => f.Value != null && f.Value.Count() > 0)\n            .ToDictionary(x => x.Key, x => x.Value);	0
10518990	10512378	Logging Application Block not logging to a file	if (!Logger.Writer.IsLoggingEnabled()) return;\n\n            var logEntry = new LogEntry { Severity = GetTraceEventTypeFromPriority(severity) };\n            logEntry.Categories.Add(GetLogCategory(app_name, severity)); // CHANGED TO NONE BECAUSE SITECORE SUCKS\n            logEntry.Priority = (int)severity;\n\n            if (!Logger.ShouldLog(logEntry)) return;\n\n            logEntry.Message = message;\n            logEntry.Title = GetLogTitle(RequestDataManager.RequestData.blah, message, severity);\n\n            lock (_locker)\n            {\n                Logger.Write(logEntry);\n            }	0
28328859	28328803	How to remove only LineFeed from a line in C#	.Split('\r').Trim()	0
28040979	28032810	For Tchart in C#, how to make markstip show out both series name and label value when mouse over	public partial class Form1 : Form\n  {\n    public Form1()\n    {\n      InitializeComponent();\n      InitializeChart();\n    }\n\n    private void InitializeChart()\n    {\n      tChart1.Series.Add(new Steema.TeeChart.Styles.Bar()).FillSampleValues();\n\n      tChart1[0].GetSeriesMark += Form1_GetSeriesMark;      \n      tChart1[0].Marks.Visible = false;\n\n      tChart1.Tools.Add(new Steema.TeeChart.Tools.MarksTip());\n    }\n\n    void Form1_GetSeriesMark(Steema.TeeChart.Styles.Series series, Steema.TeeChart.Styles.GetSeriesMarkEventArgs e)\n    {\n      e.MarkText = "X: " + series.XValues[e.ValueIndex].ToString() + ", Y: " + series.YValues[e.ValueIndex].ToString() + " - " + series.ToString();\n    }    \n  }	0
23689233	23689064	is there a way to ignore part of a datetime string when using DateTime.TryParseExact?	string date8 = "19430403000000-0400";\n\n        DateTimeOffset result2;\n        bool parsed = DateTimeOffset.TryParseExact(date8, "yyyyMMddhhmmss zzzz", CultureInfo.InvariantCulture,\n                               DateTimeStyles.AllowWhiteSpaces,\n                               out result2);	0
15030688	15030497	How to include framework dll's with my game so the user wont have to download them?	Copy Local=true	0
13797605	13796656	Removing Data Access layer coupling from user interface	public class BarcodeBLL\n{\n    private JDE8Dal _context;\n\n    public BarcodeBLL(JDE8Dal context)\n    {\n        _context = context;\n    }\n}	0
2544844	2544807	How to Retrieve data and want to read data from XML  in C#	private void Form1_Load(object sender, EventArgs e)\n        {\n            //load the xml document;\n\n            XmlDocument xdoc = new XmlDocument;\n            xdoc.Load("YourFile.xml");\n\n\n            // read the values\n\n            // using indexers\n            method1 = xdoc["root"]["Element"].Value;\n\n            // using xpath to select nodes\n            method2 = xdoc.SelectSingleNode( "root/element/element" ).Value;\n\n            // attributes\n            method3 = xdoc.SelectSingleNode("root/element").Attributes["YourAttribute"].Value;\n\n        }	0
29367277	29367095	How to split a integer string based on the character present in it	string obj = "784D3212";               \n            Match match = Regex.Match(obj, @"[A-Z]\d+");\n            if (match.Success)\n                obj = match.Value;	0
13830689	13830600	Consuming a HTTP stream without reading one byte at a time	private EventWaitHandle asyncWait = new ManualResetEvent(false);\nprivate Timer abortTimer = null;\nprivate bool success = false;\n\npublic void ReadFromTwitter()\n{\n    abortTimer = new Timer(AbortTwitter, null, 50000, System.Threading.Timeout.Infinite);\n\n    asyncWait.Reset();\n    input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null);\n    asyncWait.WaitOne();            \n}\n\nvoid AbortTwitter(object state)\n{\n    success = false; // Redundant but explicit for clarity\n    asyncWait.Set();\n}\n\nvoid InputReadComplete()\n{\n    // Disable the timer:\n    abortTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);\n    success = true;\n    asyncWait.Set();\n}	0
6980630	6980593	Open up a Form from a Button click?	var form = new YourForm();\nform.Show();	0
7403435	7403386	LINQ Not In, so that I can use in a Merge	var vwBusParkIDs = vwBusPark.toDataTable().AsEnumerable().Select(r => Convert.ToInt32( r["BusinessParkId"]));\nvar query = dataSet.BusinessPark.Where(entry => !vwBusParkIDs.Contains(entry.BusinessParkID));	0
10657852	10657784	How to create a single object from multiple databases/tables in Entity Framework	public CustomerRepository\n{\n    public Customer GetCustomerFor(int customerId)\n    {\n        var tier1Obj = Tier1DBContext.Customers.First(x => x.CustomerId == customerId);\n        var tier2Obj = Tier2DBContext.Customers.First(x => x.CustomerId == customerId);\n\n        // merge them into some new object\n\n        return mergedCustomerObject;\n    }\n}	0
16814421	16814292	How to query JSON array with C#, For a specific Property	var jObj = JObject.Parse(json);\nvar rates = jObj["rates"].Children().Cast<JProperty>()\n            .ToDictionary(p => p.Name, p => (double)p.Value);\n\n//A single statement instead of switch\nvar exchangeRate = rates[currencyPair.QuoteCurrencyCode];	0
11349896	11308721	Getting notified of a new subscription in NServiceBus	public void Init()\n    {\n        IBus bus = NServiceBus.Configure.With()\n           .DefaultBuilder()\n           .Log4Net()\n           .XmlSerializer()\n           .MsmqTransport()\n           .DisableRavenInstall()\n           .UnicastBus()\n           .CreateBus()\n           .Start();\n\n        IUnicastBus ubus = bus as IUnicastBus;\n\n        if (null != ubus)\n        {\n            ubus.ClientSubscribed += (s, e) => { Console.WriteLine("Client Subscribed {0}:{1}", e.SubscriberReturnAddress.Machine, e.SubscriberReturnAddress.Queue); };\n        }\n    }	0
2400568	2400545	Add elements to XDocument after LINQ Query	var totals = MyDocument.Descendants("TOTALS").FirstOrDefault();	0
25111574	25111548	How can i access a com object created in one function to other function in same class in C#	NestRTDObj = new ScripRTD();	0
11487784	11487376	Read specific tag in a RSS feed	var lst = Read("url");\n   var resDescription = (from x in lst where x.Title.Contains(day) \n                          select x.Description).ToArray() ;\n    return resDescription[0] ;\n}	0
2224023	2222924	TransactionScope helper that exhausts connection pool without fail - help?	using(TransactionScope scope = ...) {\n  using (SqlConnection conn = ...) {\n    conn.Open();\n    SqlCommand.Execute(...);\n    SqlCommand.Execute(...);\n  }\n  scope.Complete();\n}	0
3399461	3396808	How to deep clone objects containing an IList property using AutoMapper	var clone = new MainData();\n\n        clone.InjectFrom(mainData);//mainData is your source\n\n        mainData.Details.AsParallel.ForAll(detail => \n        {\n            var dc = new Detail();\n            dc.InjectFrom(detail);\n            clone.AddDetail(dc);\n        });	0
7934562	7934507	Can Massive work with MySql?	Install-Package Massive.MySQL	0
13227062	13226985	How to access control in DataGridTemplateColumn to get value?	TextBox tb = dgUser.Descendants<TextBox>()\n                   .OfType<TextBox>()\n                   .Where(t => t.Name == "txtcount")\n                   .Single();	0
10255283	10255165	Reorganizing XML using LINQ	XDocument xDoc = XDocument.Load(@"c:\temp\xmlproducts.xml");\n\n\nvar nodeGroup = from p in xDoc.Element("products").Descendants("product")\n        group p by p.Attribute("number").Value into g\n        select new \n        {\n            Key = g.Key,\n            Nodes = g.Descendants("investment")\n\n        };\n\n\nXDocument outDoc = new XDocument();\n\nvar root = new XElement("products");\n\nnodeGroup.ToList().ForEach(grp=>\n        {\n            var product = new XElement("product");\n            product.SetAttributeValue("number", grp.Key);\n\n            product.Add(grp.Nodes);\n\n            root.Add(product);\n        });	0
20138568	19767144	Adding multiple dataset from codebehind to .rdlc report	viewer.LocalReport.DataSources.Add(new ReportDataSource(reportDataSource, dataset.Tables[0]));\n                viewer.LocalReport.DataSources.Add(new ReportDataSource("reportDataSource1", dataset.Tables[1]));\n                viewer.LocalReport.DataSources.Add(new ReportDataSource("reportDataSource2", dataset.Tables[2]));\n                viewer.LocalReport.DataSources.Add(new ReportDataSource("reportDataSource3", dataset.Tables[3]));\n                viewer.LocalReport.DataSources.Add(new ReportDataSource("reportDataSource4", dataset.Tables[4]));	0
5545501	5545085	Manipulate an LDAP string	string str = "LDAP://company.com/OU=MyOU1,OU=MyOU2,OU=MyOU3,DC=MyCompany,DC=com";\nRegex regex = new Regex("OU=\\w+");\nvar result = regex.Matches(str);\nvar strList = new List<string>();\nforeach (var item in result)\n{\n    strList.Add(item.ToString().Remove(0,3));\n }\n Console.WriteLine(string.Join("/",strList));	0
19656929	19656829	Get access to the file system in Windows Azure	Local Storage	0
34391012	34390903	Getting files between two dates	DirectoryInfo DirInfo = new DirectoryInfo(@"C:/PCRequestFiles");\n\nvar files = from f in DirInfo.EnumerateFiles()\n       where f.CreationTimeUtc < EndDate && f.CreationTimeUtc > StartDate\n       select f;	0
19256054	15978250	How to save image to a folder and retrieve when needed	private void btn_Save_Click(object sender, EventArgs e)\n    {\n        FolderBrowserDialog fbd = new FolderBrowserDialog();\n        if (fbd.ShowDialog()==DialogResult.OK)\n        {\n            pictureBox1.Image.Save(fbd.SelectedPath + txtFileName + ".jpg");\n        }\n    }	0
9917766	9916995	How can I re-assign an auto-increment primary key value?	var sql = @"INSERT INTO Work (\n            WorkId ,\n            LotId ,\n            Description ,\n            )\n            VALUES (\n            '5',  '5', 'This Works'\n            );";\n        using (var db = new Context())\n        {\n            db.Database.ExecuteSqlCommand(sql);\n        }	0
13457392	13457330	How Change FontFamily Of A TextBox In A Windows Application RunTime(Code Behind)	Font oldFont = txtSubjectIn_Spammer_Send.Font;\ntxtSubjectIn_Spammer_Send.Font = new Font("Arial", oldFont.Size, oldFont.Style);	0
14902969	14901239	Listbox Trouble with Binding to ItemSource using a ObservableCollection	public partial class SystemControls : UserControl, ISystemControls\n{\n    IDriver _Driver;\n    SystemControls_VM _VM;\n        public SystemControls(IDriver InDriver, SystemControls_VM InVM)\n        {\n            _VM = InVM;\n            _Driver = InDriver;\n            DataContext = InVM;//new SystemControls_VM(_Driver);\n            InitializeComponent();\n        }	0
19876773	19876721	StackOverflow exception in a recursive method	if (t[i] == '{')\n        {\n            startIndex = i + 1;   // Start one character beyond {\n            break;\n        }\n\n        // ...\n\n        if (t[i] == '}')\n        {\n            stopIndex = i - 1;    // Stop one character prior to }\n            break;\n        }	0
18112965	18112783	How to specify custom SoapAction without service interface exposed	[OperationContract(ReplyAction="http://Microsoft.WCF.Documentation/ResponseToOCAMethod")]\nstring SampleMethod(string msg);	0
22479330	22474228	How to find the current position of a UIListBox programmatically in runtime in windows phone 8 app	StackPanel stack;           \n        stack = new StackPanel();\n        stackFinal.Orientation = System.Windows.Controls.Orientation.Vertical;\n        stackFinal.Children.Add(listToAdd);\n        stack.Children.Add(textboxToAdd);	0
1571296	1571207	ASP.NET Dynamically Change User Control Source	UserControls_header3 uh3 = (UserControls_header3)this.LoadControl(header3);\nphHeaderControls.Controls.Add(uh3);	0
21082840	21071503	facebook launch	Windows.System.Launcher.LaunchUriAsync(new Uri("fb:"));	0
7707239	7707206	EF InsertOrUpdate with string PK	var currency = GetByCurrency(entity.CurrencyCode);\n\nif (currency == null)\n     this.dbset.Add(entity);\nelse\n     currency.Something = entity.Something;	0
24836792	24836415	How to execute a stored procedures on button click with parameter input	SqlCommand Cmd = Connection.CreateCommand();\nCmd.CommandType = CommandType.StoredProcedure;\nCmd.CommandText = "ConsoleClosingIDSearch";\nCmd.Parameters.Add("@StartConsoleClosingID", SqlDbType.Int).value = Convert.ToInt32(TextBox1.Text);\nCmd.Parameters.Add("@EndConsoleClosingID ", SqlDbType.Int).value = Convert.ToInt32(TextBox2.Text);\n\nSqlDataAdapter Da = New SqlDataAdapter(Cmd);\nDataTable dt = New DataTable();\nDa.Fill(dt);\n\nGridView1.DataSource = dt;\nGridView1.DataBind();	0
2645804	2645529	Automatically inserting new fields in a web.config file	bool KeyExists(string key)\n{\n    return (!(ConfigurationManager.AppSettings[key] == null));\n}	0
10351694	2019224	Finding References in IXmlSerializable	[DC]    \nclass Container\n    {\n      [DM]\n      MyType i1 = new MyType();\n      [DM]\n      MyType i2 = i1;;\n      [DM]\n      MyType i3 = i1;\n    }	0
14472977	14472941	How to add checkbox in html table?	string html=""; \nhtml += "<table>";\nhtml += "<tr><th>" + "A" + "</th><th>" + "B" + "</th><th>" + "C" + "</th></tr>";\nhtml += "<tr><td>" + "0" + "</td><td>" + "1" + "</td><td>" + "2" + "</td></td>"+"<input type='checkbox' name ='chk1' /> "  +"</td>  </tr>"; \nhtml += "</table>";	0
5534589	5534570	Pass index of a List to button click event sender	var button = sender as Button;\nvar index = btnList.IndexOf(button);	0
25495351	25487588	Windows Phone - How to draw shapes in dynamically created canvas - XAML vs code behind	public class GameVM : INotifyPropertyChanged {\n\n  // Title and other properties\n\n  private Canvas _myUICanvas;\n  public Canvas myUICanvas\n  {\n    get {\n      _myUICanvas = Draw();\n      return _myUICanvas;\n    }\n    set {\n      // this is never called\n      _myUICanvas = value;\n    }\n  }\n\n  public Canvas Draw() {\n    Canvas newCanvas = new Canvas();\n    Ellispe stone = new Ellipse();\n    // [...] Add Fill, Strock, Width, Height properties and set Canvas.Left and Canvas.Top...\n    newCanvas.Children.Add(stone);\n    return newCanvas;\n  }\n}	0
11204760	11204678	Show image from DB	[HttpGet]\npublic ActionResult GetImage(long id, ...) \n{\n  ...\n   return File(fileBytes, "image/png");\n}	0
33865937	33865630	How to close winform window after button_click event	this.Close();	0
8030828	8029752	Copy items from one GridView to another	objects = Session["data"]; //cast this\nif (objects == null)\n    //init objects to a new list of your obj type\nobjects = objects.Union (\n    //your code for filtering grid rows\n    );\nSession["data"] = objects;	0
605830	605804	How to retrieve the text between two html markup with c#?	(?<=\<title\>).+?(?=\<\/title\>)	0
29705449	29705167	Custom Control Unhandled Exception in the Designer	this.TabPages[index].BackColor = Colors.CUSTOM_BLACK_2;	0
12711654	12698769	How to determine which application pool a SharePoint service application is running on in C#?	foreach (SPService service in SPFarm.Local.Services)\n{\n    if (service.Name.Equals("ServiceName"))\n    {\n        foreach (SPServiceApplication serviceApp in service.Applications)\n        {\n            SPIisWebServiceApplication webServiceApp = (SPIisWebServiceApplication) serviceApp;\n            SPIisWebServiceApplicationPool appPool = webServiceApp.ApplicationPool;\n        }\n    }\n}	0
17082524	17064796	Getting String Value From Database in C#	public int SaveAdminUserAccountInformation(AdminAccountProperties oAdminUser)\n        {\n            try\n            {\n                SqlParameter[] parm = new SqlParameter[4];\n\n                parm[0] = new SqlParameter(PARM_ADMIN_USER_ID, SqlDbType.Int);\n                parm[0].Value = oAdminUser.UserID;\n                parm[1] = new SqlParameter(PARM_USER_NAME, SqlDbType.VarChar);\n                parm[1].Value = oAdminUser.UserName;\n                parm[2] = new SqlParameter(PARM_ADMIN_USER_PASSWORD, SqlDbType.VarChar);\n                parm[2].Value = oAdminUser.Password;\n                parm[3] = new SqlParameter(PARM_USER_ROLE, SqlDbType.Int);\n                parm[3].Value = oAdminUser.UserRole;\n                int a =Convert.ToInt32(SqlHelper.ExecuteScalar(this._ConnString, CommandType.StoredProcedure, SQL_ADMIN_USER_INSERT_UPDATE, parm));\nreturn a;\n\n            }\n            catch (Exception ex)\n            {\n                throw ex;\n\n            }\n        }	0
14977784	14977610	Upload file to IIS from C# client	var r = WebRequest.Create("http://blabla/Update.ashx?fn=a.file");\n        var content = File.ReadAllBytes("a.file");\n        r.GetRequestStream().Write(content,0,content.Length);\n        r.Method = "POST";\n        var response = r.GetResponse();	0
15910251	15910087	What would be the equivalent of SQL [IN] statement for C# Lambda Expression?	var someInvoiceList = new int[] {1, 2, 3};\nvar result = list_A.Where(x => someInvoiceList.Contains(x.InvoiceID));	0
14242011	14241791	ViewState to compare CheckBoxList Selected Values	ArrayList list =  ViewState["PREV"] as ArrayList;\nfor (int i = 0; i < checkBoxList1.Items.Count; i++)\n{\n     if (checkBoxList1.Items[i].Selected == true && Convert.ToBoolean(list[i]) == false)\n       {\n           // Subscribe Method\n       }   \n     if (checkBoxList1.Items[i].Selected == false && Convert.ToBoolean(list[i]) == true)       \n       {\n           // Unsubscribe Method\n       }\n     else\n       {\n           // Continue to loop\n       } \n}	0
14869387	14869313	Best practice for getting a derived class to implement a property?	public BarType BarType{get{return BarType.WhaleFoo ;}}	0
16972222	16972177	Group values by two conditions with mixed values	var result = trackingList.Descendants("event")\n            .Select(E => new { Value1 = E.Element("value1").Value,\n                               Value3 = E.Element("value3").Value, \n                               Value4 = E.Element("value4").Value })\n            .GroupBy(g => g.Value3)\n            .Select(g => new { \n                 Value3 = g.Key, \n                 //DistintValue4 = g.Select(x => x.Value4).Distinct(),\n                 DateIn = g.Where(x => x.Value4 == "IN").Select(x => x.Value1).FirstOrDefault(),\n                 DateOut = g.Where(x => x.Value4 == "OUT").Select(x => x.Value1).FirstOrDefault()\n             });	0
24128607	24128496	How to remove one char from a string?	public void Remove (PictureBox pb){\n     if (pb.Tag.ToString().Length > 1) {\n         // Greater than 1 because we need to keep one D in case of DD, \n         String temp = pb.Tag.ToString();\n         pb.Tag = temp.Substring(0, temp.Length - 2);\n     }\n     else \n        pb.Tag = "D";\n        // Tag equals D because if there is only one D, it won't be deleted  \n}	0
18991515	18991450	How can I use Code Contracts to ensure that a non-blank, non-null val should always be returned from a method?	Contract.Ensures(Contract.Result<string>() != null);	0
18850313	18842531	How to set a value in XML using C#?	XmlDocument xmlDocSOR = new XmlDocument();\nXmlDocSOR.Load("filename.xml");\nXmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocSOR.NameTable);\nnamespaceManager.AddNamespace("rs", "urn:oasis:names:tc:ebxml-regrep:registry:xsd:2.1");\nnamespaceManager.AddNamespace("ns", "urn:oasis:names:tc:ebxml-regrep:rim:xsd:2.1");\nvar query = "/rs:SubmitObjectsRequest/ns:LeafRegistryObjectList/ns:ExtrinsicObject/ns:Slot";\nXmlNodeList nodeList = xmlDocSOR.SelectNodes(query, namespaceManager);\n\nforeach (XmlNode plainnode in nodeList)\n{\n    if (plainnode.Attributes["name"].Value == "sourcePatientId")\n    {\n        XmlNode childnode = plainnode.LastChild;\n        XmlElement ee1 = (XmlElement)childnode.FirstChild;\n        ee1.InnerText = sPatientID;                      \n     }\n }\n xmlDocSOR.Save("filename.xml");	0
25151428	25150386	SSMS extensibility/addin - get current database and server	IScriptFactory scriptFactory = ServiceCache.ScriptFactory;\nCurrentlyActiveWndConnectionInfo connectionIfno = scriptFactory.CurrentlyActiveWndConnectionInfo;\nUIConnectionInfo conn = connectionIfno.UIConnectionInfo;\nDebug.WriteLine("{0}::{1}", conn.ServerName, conn.AdvancedOptions["DATABASE"]);	0
29608284	21208908	Binding EF to DataGrid in WPF	private void FillData()\n    {\n        var q = (from a in ctx.Product\n                 select a).ToList();\n        Datagrid1.ItemsSource = q;\n    }	0
28930862	28929726	How to insert data into a bridging table with .NET Entity Framework?	diplomaProgram.Degrees.Add(Degree)	0
15944759	15944681	Difficulties with RectangleF	System.Drawing	0
5023571	5022368	Custom SettingsProvider and retrieving default value	private object GetDefaultValue(SettingsProperty setting)\n  {\n         if (setting.PropertyType.IsEnum)\n             return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());\n\n        // Return the default value if it is set\n        // Return the default value if it is set\n         if (setting.DefaultValue != null)\n         {\n             System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(setting.PropertyType);\n             return tc.ConvertFromString(setting.DefaultValue.ToString());\n         }\n         else // If there is no default value return the default object\n         {\n             return Activator.CreateInstance(setting.PropertyType);\n         }\n   }	0
14289119	14288908	Year, Month, and Day parameters describe an un-representable DateTime	if (em.Value == "" || ln.Value == "" || select.Value == "" || fn.Value == "" || pwr.Value == "" || pw.Value == "" || year.Value == "0" || date.Value == "0" || day.Value == "0" )\n{\n    panel1.Visible = true;\n}\nelse\n{\n    DateTime age = new DateTime(Convert.ToInt32(year.Value), Convert.ToInt32(date.Value), Convert.ToInt32(day.Value));\n\n    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);\n    SqlCommand cmd = new SqlCommand("insert into Register values ( '" + em.Value + "','" + ln.Value + "','" + select.Value + "','" + fn.Value + "','" + pwr.Value + "','" + age + "','" + pw.Value + "')", con);\n    cmd.ExecuteNonQuery();\n    con.Close();   \n}	0
32084367	32084280	Converting a class method to a property with a backing field	public static class Orders\n{\n    private static ListItemCollection _cache;\n    public static ListItemCollection Cache{ get{return _cache??(_cache = LoadListItemCollection());}\n\n    public static ListItemCollection LoadListItemCollection()\n    //your code\n}\n\n// One more apporach\npublic static class Orders\n{\n    private static ListItemCollection _cache;\n    public static ListItemCollection Cache{ get{return _cache??LoadListItemCollection(true);}\n\n    public static ListItemCollection LoadListItemCollection(bool refreshList=false)\n    { \n          if(!refreshList && _cache!=null)\n          {\n               return Cache;\n          }\n          //your code\n          ListItemCollection collListItem = list.GetItems(query);\n          //your code\n          _cache = collListItem;\n          return collListItem;\n    }\n}	0
12900048	12899995	How to format int into a string with leading Zeros and Commas	int myint = 12345;\nstring formatted = myint.ToString("000,000,000");	0
1349422	1348947	AudienceRestriction in SAML Assertion	//Create the SAML Assertion\nSamlAssertion samlAssert = new SamlAssertion();\nsamlAssert.AssertionId = Convert.ToBase64String(encoding.GetBytes(System.Guid.NewGuid().ToString()));samlAssert.Issuer = "http://www.example.com/";\n\n// Set up fthe conditions of the assertion - Not Before and Not After\nUri[] approvedAudiences = {new Uri("http://www.example2.com")};\nList<SamlCondition> conditions = new List<SamlCondition>();\nconditions.Add(new SamlAudienceRestrictionCondition(approvedAudiences));\nsamlAssert.Conditions = new SamlConditions(DateTime.Now, DateTime.Now.AddMinutes(5), conditions);	0
11100610	11096969	Rendering picture of a Webpage : berkelium-sharp	static void Main(string[] args)\n    {                        \n        BerkeliumSharp.Init(Path.GetTempPath());\n        using (Context context = Context.Create())\n        {\n            BerkeliumSharp.Update();\n            using (Window window = new Window(context))\n            {\n                string url = "http://www.google.com";\n                window.Resize(500, 500);\n                HandlePaint(window, @"m:\berkelium.png");\n                window.NavigateTo(url);\n\n                // Give the page some time to update\n                DateTime now = DateTime.Now;\n                while(DateTime.Now.Subtract(now).TotalSeconds < 1)\n                    BerkeliumSharp.Update();                   \n            }\n        }\n    }	0
20284899	20284566	Object share between more WPF windows	private Character player = new Character();\n\npublic Attribute(Character player)\n{\n    this.player = player;\n}\n\n...\n\nCharacter player = new Character(firstTextbox.Text);\nAttribute ChooseYourAttr = new Attribute(player);\n\n...\n\nprivate void attributeTopLabel_Initialized(object sender, EventArgs e)\n{\n    String welcomeAttribute = "Ahh. I see! So " + player.GetName();\n    attributeTopLabel.Content = welcomeAttribute;\n}	0
3289875	3289743	Getting strings from resx into an array without looping - C#.net	string[] AllStrings;\nusing (var Reader = new ResXResourceReader(fileName))\n{\n    AllStrings = Reader.Cast<DictionaryEntry>().Select(o => o.Value).OfType<string>().ToArray();\n}	0
4852636	4845640	How to get posts of user	var fb = new FacebookApp("access_token");\ndynamic result = fb.Get("/me/feed");\n\nforeach (dynamic post in result.data)\n{\n    var fromName = post.from.name;\n    Console.WriteLine(fromName);\n}	0
244897	244885	How do I inject a WebRequest/Response dependency?	public class WebRequestWrapper\n{\n   internal WebRequestWrapper() {..}\n\n   public WebRequestWrapper(WebRequest req)\n   {\n      _innerRequest = req;\n   }\n\n\n   public virtual string Url\n   {\n      return _innerReq.Url;\n   }\n\n   //repeat, make all necessary members virtual\n}	0
19271477	18851879	How to use Vestris API to power on ESX Server Virtual Machines using VM Name Only?	List<VMWareVirtualMachine> vitualMachines = virtualHost.RegisteredVirtualMachines.ToList();\nVMWareVirtualMachine serverTofind = vitualMachines.Where(vm => vm.PathName.Contains("Your server name")).First();	0
13011493	11915610	Skype4Com on Windows 8	regsvr32 C:\Program Files\Common Files\Skype\Skype4COM.dll	0
24152772	24149106	How to find mapping of OData edm model type to clr type?	//using Microsoft.Data.Edm\n        IEdmModel edmModel = Request.ODataProperties().Model;\n        ClrTypeAnnotation annotation = edmModel.GetAnnotationValue<ClrTypeAnnotation>(edmSchemaType);\n        if (annotation != null)\n        {\n            return annotation.ClrType;\n        }	0
4261053	4259605	Problem getting XML elements in an SVG file	var adam = SVG_Element.Descendants("{http://www.w3.org/2000/svg}line");	0
9546520	9546492	Search XML file for a word and update	var doc = XDocument.Parse(yourXMLGoesHere);\nvar elementsWithVersionAttribute) = doc.Descendants()\n                 .Where(e => e.Attribute("version")!=null)\n                 .Where(e => e.Attribute("version").Value == "5.25");\n\nforeach(var element in elementsWithVersionAttribute)\n{\n  element.SetAttributeValue("version", "6.25");\n}	0
29328660	29308554	How to set property isEnabled in each subitem button of listview in windows phone winrt?	foreach (var item in listview.Items)\n{\n    (item as your_object).IsEnable = false;\n}	0
14178433	14178426	C# Trying to type cast array values	int time2Intvar1;\nbool isOK = int.TryParse(time2var[0],out time2Intvar1);	0
763880	758782	When developing for a tablet PC, how do I determine if the user clicked a mouse or a pen?	// [DllImport( "user32.dll" )]\n// private static extern uint GetMessageExtraInfo( );\n\nuint extra = GetMessageExtraInfo();\nbool isPen = ( ( extra &  0xFFFFFF00 ) == 0xFF515700 );	0
9299763	9299562	Is it possible to load a list of xml-urls with XmlDocument? (C#)	var filePathsList = Directory.GetFiles(@"C:\temp", "*.xml");\nvar xmlDocuments = new List<XmlDocument>(filePathsList.Count());\nforeach (var filePath in filePathsList)\n{\n    var xmlDoc = new XmlDocument();\n    xmlDoc.Load(filePath);\n    xmlDocuments.Add(xmlDoc);\n}	0
23487955	23432943	Double screen app,access method in first window from second window	private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e)\n{\n\n    Application curApp = Application.Current;\n    var mainWnd = curApp.MainWindow as MainWindow;\n\n    //ActualClass is a string variable that i set every time i change the content of the main frame in mainwindow\n    if (mainWnd.ActualClass== "Page2.xaml")\n    {\n       //here i have to call a method of the Page2 class to launch an operation in Page2.cs only if the current page displayed in mainwindow frame is Page2.xaml\n           var content = mainWnd._mainFrame.Content as Page2Class;\n            if (content != null)\n            {\n                content.Method();\n            }\n    }\n\n\n}	0
20974076	20973996	Array of string pairs	string[,] arr = new string[,]{{"hgh","hjhjh"},{"jkjk","kjhk"}};	0
14560007	14559779	Mocking a method that takes a delegate in RhinoMocks	IHelperClass helperMock = MockRepository.GenerateMock<IHelperClass>();\nhelperMock\n  .Stub(x => x.HandleFunction<int>())\n  .WhenCalled(call => \n  { \n    var handler = (Func<int>)call.Argument[0];\n    handler.Invoke();\n  });\n\n// create unit under test, inject mock\n\nunitUnderTest.Foo();	0
34375697	34375650	Making Streamreader global in C#	void main(string[] args) {\n   var inputFileName= DetermineInputFileName(args);\n    var outputFileName= DetermineOutputFileName(args);\n   ReadAndWriteFile(inputFileName, outputFileName)\n}\n\nvoid ReadAndWriteFile(string inputFileName, string outputFileName) {\n  //only use the streamreader here\n   using(var inputFile = new StringReader) {\n      using (var outputFile = new StringWriter) {\n         do {\n             string line = String.Empty;\n             do {\n              var input = inputFile.ReadLine();\n              line += input;\n             while (ContinueReadingAfterThisInput(input))\n\n             var processedLine = Process(line);\n\n             outputFile.WriteLine(processedLine);\n         }\n\n      }\n\n   }\n\n}	0
26530290	26530110	.net unique values from two dimension array	var flattened = Enumerable.Range(0, arr.GetLength(0)).SelectMany(x => Enumerable.Range(0, arr.GetLength(1)).Select(y => arr[x, y]));\n\nvar distinct = flattened.Distinct().ToList();	0
15443247	15443159	Validate float value in KeyPress event	if (e.KeyChar=='.' && (obj.Text.IndexOf('.')>0 || obj.Text.Length==0))	0
9049330	9048626	DllNotFoundException with DllImport in Mono on Mac: wrong architecture	mono --version	0
25477433	25477376	how to show boolean data from excel in gridview?	gdv.ItemsSource = dataTable.AsDataView();	0
6205277	6205153	Filter IENumerable of Interface with property of class outside of interface	Course course=....\nforeach(IPeople person in course.Students) //or whatever	0
2976962	2976614	why doesnt my panel show all my buttons in my c# application?	private void AddAlphaButtons()\n{\n    char alphaStart = Char.Parse("A");\n    char alphaEnd = Char.Parse("Z");   \n\n    int x = 0;  // used for location info\n    int y = 0;  // used for location info\n\n    for (char i = alphaStart; i <= alphaEnd; i++)\n    {\n        string anchorLetter = i.ToString();\n        Button Buttonx = new Button();\n        Buttonx.Name = "button " + anchorLetter;\n        Buttonx.Text = anchorLetter;\n        Buttonx.BackColor = Color.DarkSlateBlue;\n        Buttonx.ForeColor = Color.GreenYellow;\n        Buttonx.Width = 30;\n        Buttonx.Height = 30;\n\n        // set button location\n        Buttonx.Location = new Point(x, y);\n\n        x+=30;\n        if(x > panel1.Width - 30)\n        { \n            x = 30;\n            y+=30;\n        }\n\n        this.panelButtons.Controls.Add(Buttonx);\n\n        //Buttonx.Click += new System.EventHandler(this.MyButton_Click);\n     }\n}	0
11843181	11843136	Delete a empty line from a File	string replacedContents = fileContents.Replace(\n    txt_editname.Text + "@" + txt_editno.Text + System.Environment.NewLine,"");	0
4895387	4895304	Extracting the required keywords from text	foreach (Match match in Regex.Matches(content, "^(.*?)\\s*(?::| is )\\s*([0-9,.+-]+)(.*)$", RegexOptions.Multiline))\n{\n    Console.WriteLine("Item1: {0} Item2: {1} Item3: {2}", match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value);\n}	0
17981050	17980757	Linq2sql table: List<fieldname> as parameter	internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)\n{\n    using (DBDataContext db = new DBDataContext())\n    {\n        item myItem = db.items.Single(t=>t.id==id);\n        keysToUpdate.ForEach(key => {\n            typeof(item).GetProperty(key)\n                .SetValue(item, GetValue(fieldsWithChanges, key), null);\n        });\n        db.SubmitChanges();\n    }\n}	0
8994651	8992945	LINQ to XML Deep Parsing Help Needed	var posAddr =\n    (from pos in possibleAddresses.Elements("POS-ADDR")\n     where (int)pos.Element("BUILDING").Element("RiskID") == riskIdToLookFor\n     select pos)\n    .Single();\n\nvar occupants =\n    from o in posAddr.Element("OCCUPANTS").Elements("OCCUP")\n    select new\n    {\n        Description = (string)o.Element("DESC")\n    }	0
16561759	16561673	String find and replace	private string ReplaceFirstOccurrence(string Source, string Find, string Replace)\n{\n int Place = Source.IndexOf(Find);\n string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);\n return result;\n}\n\nvar result =ReplaceFirstOccurrence(text,"~"+input,"");	0
6368556	6368491	I get System.InvalidCastException, when retrieving a dictionary from Session state	Session["ThreadPage"].GetType().ToString();	0
11902185	11901906	How to get hold of Content that is already read	using (var stream = new MemoryStream())\n{\n    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];\n    context.Request.InputStream.Seek(0, SeekOrigin.Begin);\n    context.Request.InputStream.CopyTo(stream);\n    string requestBody = Encoding.UTF8.GetString(stream.ToArray());\n}	0
34540483	34467964	How do I set alignment on DataGridTextColumn cell text using code	Dim txt As New DataGridTextColumn()\n    Dim s As New Style\n    s.Setters.Add(New Setter(TextBox.TextAlignmentProperty, TextAlignment.Right))\n    txt.CellStyle = s	0
8214088	8214072	In C# how can I truncate a byte[] array	byte[] sourceArray = ...\nbyte[] truncArray = new byte[10];\n\nArray.Copy(sourceArray , truncArray , truncArray.Length);	0
18354866	11494989	DropNet DropBox login, how to do it programmatically in a console application?	Globals.DropBox.Token = AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxStorageProviderTools\n.ExchangeDropBoxRequestTokenIntoAccessToken(\n      Globals.DropBox.config\n    , Globals.DropBox.AppKey, Globals.DropBox.AppSec\n    , Globals.DropBox.requestToken\n);	0
19158280	19158155	How to define a list in struct in asp c#?	public struct MyStruct\n{\n    private List<string> someStringList;\n\n    public List<string> SomeStringList\n    {\n         get\n         {\n             if (this.someStringList == null)\n             {\n                 this.someStringList = new List<string>();\n             }\n\n             return this.someStringList;\n         }\n    }\n}	0
13009461	13009401	how to create setup project to install scr file	X:\Windows\	0
13250164	13249888	How do I save object to database using EF and get primary key created back from database?	int id = 0; // assuming the datatype for eReportId is int\n\nusing (EReportDB.EReportEntities objectContext = new EReportDB.EReportEntities())\n{\n   EReportDB.EReport eReport = new EReportDB.EReport();\n   eReport.orderId = eContractReport.orderId;\n   eReport.timeIn = DateTime.Parse(eContractReport.timeIn, new CultureInfo("en-GB", false));\n   eReport.timeOut = DateTime.Parse(eContractReport.timeOut, new CultureInfo("en-GB", false));\n   eReport.isProducFact = eContractReport.isProducFact;\n   /*\n     ..snip..\n   */\n   eReport.olPkSizeRs_ = eContractReport.olPkSizeRs;\n   eReport.olPkWeightRs = eContractReport.olPkWeightRs;\n\n   objectContext.AddObject(eReport); // method to insert the entity \n   objectContext.SaveChanges();\n   id = eReport.eReportId;\n\n   transaction.Complete();\n}	0
8270488	8270396	AutoMapper - mapping child collections in viewmodel	Mapper.CreateMap<Parent, ParentViewModel>();\nMapper.CreateMap<Child, ChildViewModel>();\n\nvar v = Mapper.Map<Parent, ParentViewModel>(parent);	0
6754205	4277692	GetEntryAssembly for web applications	static private Assembly GetWebEntryAssembly()\n    {\n        if (System.Web.HttpContext.Current == null ||\n            System.Web.HttpContext.Current.ApplicationInstance == null) \n        {\n            return null;\n        }\n\n        var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();\n        while (type != null && type.Namespace == "ASP") {\n            type = type.BaseType;\n        }\n\n        return type == null ? null : type.Assembly;\n    }	0
31696902	31694260	How to get Azure Mobile service data into Grid View in Asp.net(C#)?	List<BranchList> items_list = await BranchTable\n           .Where(branchitem => branchitem.Enable == true)\n           .ToListAsync();\n\n            MyGridView1.DataSource = items_list;\n            MyGridView1.DataBind();	0
32178612	32176023	How to iterate through IEnumerable collection using for each or foreach?	var dictionary = items.Zip(Enumerable.Range(1, int.MaxValue - 1), (o, i) => new { Index = i, Customer = (object)o });	0
16498181	16497938	EF 5 Enable-Migrations : No context type was found in the assembly	Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose	0
24670243	24668712	Add Parameter to XElment on Runtime C#	var xmlDoc = new XDocument();\nxmlDoc.Add(new XElement("root"));\nif (prescriptionTemperatureList != null && prescriptionTemperatureList.Count > 0)\n{\n    foreach (var medicationEntity in prescriptionTemperatureList)\n    {\n        if (xmlDoc.Root != null)\n        {\n            var temperature = new XElement("Temprature");\n            if(!string.IsNullOrEmpty(medicationEntity.Value))\n                temperature.Add(new XElement("Temp_F", medicationEntity.Value));\n            if(!string.IsNullOrEmpty(medicationEntity.Value))\n                temperature.Add(new XElement("Temp_C", ((Convert.ToInt64(medicationEntity.Value)-32)/1.80).ToString()));\n            if(!string.IsNullOrEmpty(medicationEntity.Time))\n                temperature.Add(new XElement("vHour", (DateTime.Parse(medicationEntity.Time).Hour).ToString()));\n            .........\n            .........\n            xmlDoc.Root.Add(temperature);\n        }\n        newTempratureList.Add(medicationEntity);\n    }\n}	0
16465552	16465525	Will a pointless semicolon have any performance impact?	bool ProcessMessage() {...}\nvoid ProcessMessages() {\n   while (ProcessMessage())\n      ;\n}	0
16642487	16642479	Get file name of file from full path?	Path.GetFileName(someFullPath);	0
20806834	20806514	Stored procedure expects a parameter I am already passing in	if (first == null) {\n  first = "";\n}\nif (last == null) {\n  last = "";\n}	0
34161162	34120057	Upload files to share point using C#	using (ClientContext conext = new ClientContext(site.url))\n{\n    List projectFiles = projects.Web.Lists.GetByTitle("Project Files");\n    context.Load(projectFiles.RootFolder, w => w.ServerRelativeUrl);                       \n    context.ExecuteQuery();\n\n    FileStream documentStream = System.IO.File.OpenRead(filePath);\n    byte[] info = new byte[documentStream.Length];\n    documentStream.Read(info, 0, (int)documentStream.Length);\n\n    string fileURL = projectFiles.RootFolder.ServerRelativeUrl + "/Folder/FileName.ext";\n\n    FileCreationInformation fileCreationInformation = new FileCreationInformation();\n    fileCreationInformation.Overwrite = true;\n    fileCreationInformation.Content = info;\n    fileCreationInformation.Url = fileURL;\n    Microsoft.SharePoint.Client.File uploadFile = projectFiles.RootFolder.Files.Add(fileCreationInformation);\n    context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion);\n    context.ExecuteQuery();\n}	0
2578222	2578193	Saving formatted text from richtextbox	string s = richTextBox.Rtf;	0
25411575	25411455	Lambda Expression and Garbage Collection in 64 bit	System.GC.Collect()	0
29382313	29382194	Save data stream to a file every second in .NET	static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();\n\nvoid TimerInit(int interval) {\n    myTimer.Tick += new EventHandler(myTimer_Tick); //this is run every interval\n    myTimer.Interval = internal;\n    myTimer.Enabled = true;\n    myTimer.Start(); \n}\n\nprivate static void myTimer_Tick(object sender, EventArgs e) {\n    System.IO.File.WriteAllText(@"c:\path.txt", jointAngles); //You might want to append\n    if (reached 5 minutes or X write cycles) {\n        myTimer.Stop();\n    }\n}	0
8498379	8490131	Listbox not showing items	Form currentForm = Form.ActiveForm;\nListBox lb = (ListBox)currentForm.Controls.Find("ListboxName", true)[0];	0
27583790	27583642	int.TryParse(String, out Number) only works once in a button click event	string NumberLength = TextBoxPhoneNumber.Text;\nint Number;\nif (int.TryParse(NumberLength, out Number))\n{\n    //I parsed the number out. Now lets get the length\n    NumberLength = Number.ToString(CultureInfo.InvariantCulture);\n\n    if (NumberLength.Length > 10)\n    {\n        LblInfo.Visible = true;\n        LblInfo.ForeColor = Color.Red;\n        LblInfo.Text = "Phone number can not be longer than 10 digits!";\n        boolIsValid = false;\n    }\n    else if (NumberLength.Length < 10)\n    {\n        LblInfo.Visible = true;\n        LblInfo.ForeColor = Color.Red;\n        LblInfo.Text = "Phone number can not be shorter than 10 digits!";\n        boolIsValid = false;\n    }\n    else\n    {\n        LblInfo.Visible = false;\n        boolIsValid = true;\n    }\n}\nelse\n{\n    LblInfo.Visible = true;\n    LblInfo.ForeColor = Color.Red;\n    LblInfo.Text = "Phone number can only contain digits!";\n    boolIsValid = false;\n}	0
7692413	7692259	Named Pipe Server & Client - No Message	StreamWriter wr = new StreamWriter(p);\nwr.WriteLine("Hello!\n");\nwr.Flush();	0
12850821	12850747	How to launch modeless window and enforce a single instance of it in caliburn micro	// Create a reference to the model being used to instantiate the window\n// and let the IoC import the model. If you set the PartCreationPolicy\n// as Shared for the Export of SomeOtherModel, then no matter where you are\n// in the application, you'll always be acting against the same instance.\n[Import]\nprivate SomeOtherModel _otherModel;\n\n\npublic void ShowSomeOtherWindow()\n{\n    // use the caliburn IsActive property to see if the window is active\n    if( _otherModel.IsActive )\n    {\n        // if the window is active; nothing to do.\n        return;\n    }\n\n    // create some settings for the new window:\n    var settings = new Dictionary<string, object>\n                   {\n                           { "WindowStyle", WindowStyle.None },\n                           { "ShowInTaskbar", false },\n                   };\n\n    // show the new window with the caliburn IWindowManager:\n    _windowManager.ShowWindow( _otherModel, null, settings );\n}	0
17854887	17839013	Fast way to hash objects focussing on properties containing a certain attribute?	private void CompareChange<T>(T old, T newValue)\n    {\n        if (!EqualityComparer<T>.Default.Equals(old, newValue))\n            Interlocked.Increment(ref _ChangeCount);\n    }	0
32837423	32833503	How Do i pass form values from a Dictionary <String, String> to an Object in C#	public static class IDictionaryExtensions\n{\n    public static T ToObject<T>(this IDictionary<string, object> source)\n        where T : class, new()\n    {\n        T someObject = new T();\n        Type someObjectType = someObject.GetType();\n\n        foreach (KeyValuePair<string, object> item in source)\n        {\n            someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);\n        }\n\n        return someObject;\n    }\n}	0
30885079	30885001	Go through a string and check if contains a char and save the chars before in a list	List<string> numbers = new List<string>();\nstring test = "100+20+3-17+2";\nchar[] chars = new char[] { '+', '-', '*', '/' };\nnumbers = test.Split(chars).ToList();	0
9528515	9528178	how to get the count of the in the reverse order?	Console.WriteLine("Limit = 10000");\nConsole.WriteLine("Count: {0} of 10000. {1} remaining", count, 10000 - count);	0
8198572	7839691	GetType in static method	abstract class MyBase\n{\n   public static void MyMethod(Type type)\n   {\n      doSomethingWith(type);\n   }\n}	0
23585762	23585670	Convert Jagged Array to IEnumerable<KeyValuePair<int,int>>?	foreach (var t in jagged.SelectMany((row, rowIndex) => row.Select(value => new KeyValuePair<int, int>(value, rowIndex))))\n{\n    Console.WriteLine("{0} - {1}", t.Key, t.Value);\n}	0
30808177	30808103	XML value extraction using Regex in C#	Regex.Replace(str, @"<(A99_0[123]>).*?</\1", "<$1</$1");	0
3621334	3621295	How do I create a string with Quotes in it in C#	// a space after "eScore"\nstring profileArg = @"/profile ""eScore"" ";\n\n// no space after "eScore"\nstring profileArg = @"/profile ""eScore""";\n\n// space in "eScore "\nstring profileArg = @"/profile ""eScore """;\n\n// No space using escaping\nstring profileArg = "/profile \"eScore\"";	0
32971469	32971352	How to make int array Nullable?	int?[] contractsIDList = contractsId.Cast<int?>().ToArray();//for debug	0
1036340	1036337	string array -> longId array in a SQL statement	DELETE FROM table WHERE id IN (1,2,3,keys)	0
23596488	23594958	MessageBox in Windows Phone 8.1	protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)\n{\n    e.Cancel = true;\n    Deployment.Current.Dispatcher.BeginInvoke(() =>\n    {\n      MessageBoxResult mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning", MessageBoxButton.OKCancel);\n\n      if(mbr == MessageBoxResult.OK)\n      {   OK pressed  } \n      else\n      {   Cancel pressed  }\n    });\n}	0
24859360	24858648	how to get data in monthly wise by group the month and union using joins in linq	var collections = db.Collections.Where(x => x.Date_Time.Value.Year == thisYear)\n                                .Select(m => new {\n                                    dt = m.Date_Time.Value,\n                                    amount = m.Amount\n                                });\n\nvar deposits = db.Collections.Where(x => x.Date_Time.Value.Year == thisYear)\n                                .Select(m => new {\n                                    dt = m.Date_Time.Value,\n                                    amount = m.Amount\n                                });\n\nvar result = collections.Union(deposits)\n                        .GroupBy(m => m.dt.Month)\n                        .Select(g => new {\n                            date = g.First().dt.ToString("MM/yyyy"),\n                            totalAmount = g.Sum(x => x.amount)\n                         });	0
15742333	15742076	IPagedList localization	var options = new PagedListRenderOptions();\noptions.PageCountAndCurrentLocationFormat = "Page {0} of {1}."; //your custom string goes gere\noptions.ItemSliceAndTotalFormat = "Showing items {0} through {1} of {2}.";	0
7225938	7225870	How can I highlight the dates in month calender control?	DateTime[] absentDates = {myVacation1, myVacation2};\nmonthCalendar1.BoldedDates = absentDates;	0
18348015	15720803	Webbrowser disable all audio output - from online radio to youtube	using System;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nnamespace WinformsWB\n{\n    public partial class Form1 : Form\n    {\n        [DllImport("winmm.dll")]\n        public static extern int waveOutGetVolume(IntPtr h, out uint dwVolume);\n\n        [DllImport("winmm.dll")]\n        public static extern int waveOutSetVolume(IntPtr h, uint dwVolume);\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            // save the current volume\n            uint _savedVolume;\n            waveOutGetVolume(IntPtr.Zero, out _savedVolume);\n\n            this.FormClosing += delegate \n            {\n                // restore the volume upon exit\n                waveOutSetVolume(IntPtr.Zero, _savedVolume);\n            };\n\n            // mute\n            waveOutSetVolume(IntPtr.Zero, 0);\n            this.webBrowser1.Navigate("http://youtube.com");\n        }\n    }\n}	0
9852893	9778267	How can I access the XML file under SharePoint Mapped Folder for Creating Xml Reader?	string templatePath = SPUtility.GetGenericSetupPath("TEMPLATE");\nstring xmlPath = Path.Combine(templatePath, @"ADMIN\AIP_RefinementPanel\CustomFilterCategoryDefinition.xml");\nXmlReader reader = XmlReader.Create(xmlPath);	0
10160546	10160477	I need function to be executed according to status, hidden from the caller	public bool func(string name)\n{\n    var retryCount = 1;\n\n    string result = string.Empty;\n    while (retryCount <=2)\n    {\n        result = DoSomething(name);\n\n        if(result =="Whatever")\n            return true;\n\n        retryCount ++;\n    }\n\n    return false;\n\n\n}	0
5639748	5639699	OleDB selecting multiple CSVs with first row as field names in C#	OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\;Extended Properties=\"Text;HDR=Yes;FMT=Delimited\"");	0
7307744	7307600	How to configure a site to redirect automatically from HTTP to HTTPS in C#	if(!Request.IsSecureConnection) \n\n{ \n\n  string redirectUrl = Request.Url.ToString().Replace("http:", "https:"); \n  Response.Redirect(redirectUrl); \n\n}	0
5177280	5177254	How can I increment a date?	var dueDate = new DateTime(2011, 3, 3);\n\n//if you want to increment six days\nvar dueDatePlus6Days = dueDate.AddDays(6);\n\n//if you want to increment six months\nvar dueDatePlus6Months = dueDate.AddMonths(6);\n\nvar daysDiff1 = (dueDatePlus6Days - dueDate).TotalDays; //gives 6\nvar daysDiff2 = (dueDatePlus6Months - dueDate).TotalDays; //gives 184	0
19537619	19537411	XML serialization of List<Object>	[XmlInclude(typeof(Cat))]\n[XmlInclude(typeof(Dog))]\n[XmlRoot(ElementName="Animal")]\npublic abstract class Animal : IAnimal	0
8507071	8499582	Struggling to implement IFindSagas	public class MySaga : Saga<MySagaData>, IAmStartedByMessages<Message1>\n{\n    public override void ConfigureHowToFindSaga()\n    {\n         ConfigureMapping<Message1>(s => s.SomeID, m => m.SomeID);\n    }\n\n    public void Handle(Message1 message)\n    {\n       if(Data.Id != Guid.Empty)\n       {\n           // handle existing saga\n       }\n       else // create new saga instance\n       {\n          this.Data.SomeID = message.SomeID;\n          RequestUtcTimeout(DateTime.Now.AddHours(23), "End of batch");\n       }\n\n        // rest of the code to handle Message1\n    }\n\n    public override void Timeout(object state)\n    {\n        // some business action\n    } \n}	0
1359836	1359798	Display new form based on GridView data	DataRowView currentRow = A133BindingSource.CurrencyManager.List[A133BindingSource.CurrencyManager.Position] as DataRowView;\nA133Form oA133Form = new A133Form();\noA133Form.NewA133 = new A133(currentRow.Row);	0
9236502	9236465	High CPU usage, move cursor app C#	private void moveMouse(int startX, int endX, int startY, int endY)\n{\n\n  this.BeginInvoke(new Action(() => { InvokeMouseMove(startX, endX, startY, endY)\n   }));\n}\n\nprivate void InvokeMouseMove(int startX, int endX, int startY, int endY)\n    {\n        int newPosX = startX;\n        int newPosY = startY;\n        while (running)\n        {\n            Application.DoEvents();\n            //this.Cursor = new Cursor(Cursor.Current.Handle);\n            Cursor.Position = new Point(newPosX, newPosY);\n\n            if (colorCursor.Get(newPosX, newPosY))\n            {\n                MyMouse.sendClick();\n                countClicks++;\n                lblStatus.Text = "Klik: " + countClicks;\n            }\n\n            newPosX += 10;\n            if (newPosX > endX)\n            {\n                newPosY += 25;\n                newPosX = startX;\n            }\n            if (newPosY > endY)\n            {\n                newPosY = startY;\n            }\n        }\n    }	0
1213041	1212974	Keeping Windows Forms Picturebox in middle of TreeView	this.panel1.Controls.Add(treeView2);\nthis.panel1.Controls.Add(pictureBox1);\n\nthis.treeView2.Dock = DockStyle.Fill;\nthis.pictureBox1.Anchor = AnchorStyles.None;	0
13382723	13382670	How to put a method with one parameter into the Thread C#	thread = new Thread(new ParameterizedThreadStart(getSomething));\nthread.Start(2);\n\npublic static void getSomething(object obj) {\n      int i = (int)obj;\n}	0
16083559	16083126	Casting string in SSIS script task for for loop in C#	ToString()	0
7788455	7788431	C# inline conditional in string[] array	settings = new string[]{"setting1","1", "setting2","apple"}\n    .Concat(msettingvalue ? new string[] {"msetting","true"} : new string[0]);\n    .ToArray()	0
4086680	4086510	how to do grouping in LINQ	List<RelatedProduct> relatedProducts = new List<RelatedProduct>();\n        foreach (var group in query)\n        {\n            var key = group.Key;\n            relatedProducts.AddRange(group.ToList());\n        }	0
6106777	6106691	Adding an item to a Collection within a Collection	Group.OffersList.Where(x => x.GroupId == "1")\n                 .ToList()\n                 .ForEach(x => x.Add(Product));	0
11053197	11053026	Parse C# unformated strings in source code then convert to string format	"\s*\+\s*(\S.*?)\s*\+\s*"	0
26609109	26608869	How I can use Global.asax for storing the authentication for separate user?	public static MemberManager.Member _CurrentUser\n{\n  get\n  {\n    return (MemberManager.Member)System.Web.HttpContext.Current.Session["__MemberManager_Member"];\n  }\n  set\n  {\n    System.Web.HttpContext.Current.Session["__MemberManager_Member"] = value;\n  }\n}	0
22826437	22824723	How to make a Property nullable in web api	ODataConventionModelBuilder builder = new ODataConventionModelBuilder();\nvar collectionProperty = builder.EntityType<WebApiEntity>().CollectionProperty<CData>(c=>c.data);\ncollectionProperty.IsOptional();	0
25465911	25465800	Calculating uv texture coords for a procedurally generated circle mesh	uvs[i] = new Vector2(0.5f +(verts[i].x-centerX)/(2*radius), \n                             0.5f + (verts[i].y-centerY)/(2*radius));	0
28846724	28830094	WP8.1 change application tile background	var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);\nvar tileImage = tileXml.GetElementsByTagName("image")[0] as XmlElement;\ntileImage.SetAttribute("src", "ms-appx:///Assets/bild.JPG");\nvar tileText = tileXml.GetElementsByTagName("text");  \nvar tileNotification = new TileNotification(tileXml);\nTileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);	0
31404512	31403177	How to make a calculated property to persist in database in Entity Framework	public string FullName\n{\n    get\n    {\n        return FirstName + " " + LastName;\n    }\n    protected set {}\n}	0
16558567	16558317	How to download memorystream to a file?	MemoryStream memoryStream = new MemoryStream();\nTextWriter textWriter = new StreamWriter(memoryStream);\ntextWriter.WriteLine("Something");   \ntextWriter.Flush(); // added this line\nbyte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array\nmemoryStream.Close(); \n\nResponse.Clear();\nResponse.ContentType = "application/force-download";\nResponse.AddHeader("content-disposition", "attachment;    filename=name_you_file.xls");\nResponse.BinaryWrite(bytesInStream);\nResponse.End();	0
12701565	12701512	splitting comma separated dataset into separate arrays	List<string> lines = new List<string>(textFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None));\nfor (int iLine = 0; iLine < lines.Count; iLine++)\n{\n    List<string> values = new List<string>(lines[iLine].Split(new[] {","}, StringSplitOptions.None));\n        for (int iValue = 0; iValue < values.Count; iValue++)\n            Console.WriteLine(String.Format("Line {0} Value {1} : {2}", iLine, iValue, values[iValue]));\n}	0
2008812	2008786	Exposing class library DLL to COM with generics	public class HtmlTable<T> where T : class \n{ \n    List<T> listToConvert; \n\n    public HtmlTable(List<T> listToConvert) \n    { \n        this.listToConvert = listToConvert; \n    } \n} \n\n[ComVisible(true)]\npublic class StringHtmlTable : HtmlTable<String>\n{\n    // implementation goes here\n}	0
21097576	21097221	Get values of XDocument	foreach (XElement item in xmlDocument.Descendants("Itens").Elements("Item"))	0
9604952	9604842	Save non-transparent image from a PictureBox with transparent images	public static Bitmap Repaint(Bitmap source, Color backgroundColor)\n{\n Bitmap result = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);\n using (Graphics g = Graphics.FromImage(result))\n {\n  g.Clear(backgroundColor);\n  g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height));\n }\n\n return result;\n}	0
5398117	5398086	How to select a item in a Dictionary, using a list box	var contact = dict[listBox.SelectedItem];	0
23006727	23005401	Http Api request in ASP.NET WebPage	var client = new WebClient();\n   var stream  = client.OpenRead (url);\n   var reader = new StreamReader (stream);\n   string json = reader.ReadToEnd ();\n   data.Close ();\n   reader.Close ();\n   // Deserialize json (supposing you are using package Newtonsoft.Json)\n   var obj = JsonConvert.DeserializeObject(json);	0
19230237	19060770	how to create connection strings by reflection (edmx, entity framework)	builder.Metadata = string.Format("res://{0}", typeof(MyObjectContext).Assembly.FullName);	0
1945677	1945611	Setting the parameterless constructor as the injection constructor in container creation	container.RegisterType<IConfigurationService, SqlConfigurationService>(\n    new InjectionConstructor())	0
33301058	33300992	How to store words from string which are space seperated?	var Result = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList(); // 5 4 3 2\n\n//store each number in a single variable\nint i1 = Result[0]; //5\nint i2 = Result[1]; //4\nint i3 = Result[2]; //3\nint i4 = Result[3]; //2	0
7801754	7801714	How to extract 10 random rows from DataTable?	var random10 = dataTable.Rows.OfType<DataRow>().Shuffle(new Random()).Take(10);	0
5137531	5137436	How to do lookups using a list of string?	start -->   A?  -- NO --> R? -- YES --> B? -- YES --> "hailstorm"\n             |\n             +--- YES --> F? -- YES --> T? -- YES --> "firestorm"\n                          |             |\n                          |             +----- NO --> "searing wind"\n                          |\n                          +----- NO --> T? -- YES --> "storm"\n                                        |\n                                        +----- B? -- YES --> "snowstorm"	0
27841778	27827662	Comparing 2 lists of objects	public void Compare(List<Fruit> frList, List<Veg> vList)\n    {\n        foreach (Fruit f in frList)\n        {\n            foreach (Veg v in vList)\n            {\n                if (f == v)\n                { \n                   //some functionality\n                }else{\n                  //some other funtionality\n                }\n            }\n\n        }\n    }	0
14445444	14445133	How to set HLSL parameter of type float2?	e.Parameters["p"].SetValue(new Vector2(1, 2));	0
4540311	4539074	Alternative to set focus from within the Enter event	private void textBox2_Enter(object sender, EventArgs e) {\n        this.BeginInvoke((MethodInvoker)delegate { textBox3.Focus(); });\n    }	0
28838796	28838336	Calculating the previous quarter from the current Month in C#	private int PreviousQuarter(DateTime date)\n{\n        return (int)Math.Ceiling((double)date.AddMonths(-3).Month / (double)3);\n}	0
26744760	26744543	How I can pass data from a database to a "select tag" in ASP.NET?	using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BancoEstadoConnectionString"].ToString()))\n    {\n        SqlCommand comand = new SqlCommand(query, conn);\n\n        DataSet ds = new DataSet();\n        conn.Open();\n\n        var adapter = new SqlDataAdapter(command);\n        adapter.Fill(ds, "Authors");\n\n        Select1.DataSource = ds;\n        Select1.DataTextField = "au_fname";\n        Select1.DataValueField = "au_fname";\n        Select1.DataBind();\n    }	0
28391409	28362589	How to check every 2 minutes for report checking in datagrid wpf?	async void Main()\n{\n    Foo f = new Foo();\n    Task s = await f.Bar(); \n    Console.WriteLine("Done");\n}\n\npublic class Foo\n{\n    public Foo()\n    {\n    }\n    //recursive tail function\n    public async Task<Task> Bar()\n    {\n        //enter your code here\n        doSomething();\n        //Change this to what time you desire\n        await Task.Delay(1000);\n        return Bar();\n    }\n}	0
5549614	5549537	Drawing a circle using a PointF as its center c#	float x = center.X - radius;\nfloat y = center.Y - radius;\nfloat width = 2 * radius;\nfloat height = 2 * radius;\ngraphics.DrawEllipse(pen, x, y, width, height);	0
8616664	8614955	Drag and Drop - Moving a Label in Winforms	private Point lastPos;\n\nprotected override void OnMouseMove(MouseEventArgs e) {\n    if (e.Button == MouseButtons.Left) {\n        int dx = e.X - lastPos.X;\n        int dy = e.Y - lastPos.Y;\n        Location = new Point(Left + dx, Top + dy);\n        // NOTE: do NOT update lastPos, the relative mouse position changed\n    }\n    base.OnMouseMove(e);\n}\n\nprotected override void OnMouseDown(MouseEventArgs e) {\n    if (e.Button == MouseButtons.Left) {\n        lastPos = e.Location;\n        BringToFront();\n        this.Capture = true;\n    }\n    base.OnMouseDown(e);\n}\n\nprotected override void OnMouseUp(MouseEventArgs e) {\n    this.Capture = false;\n    base.OnMouseUp(e);\n}	0
27394069	27342282	Replicate record in a DataTable based on value of a column using C#	string[] strValues;\n    for (int i = 0; i < dtTable.Rows.Count; i++)\n    {\n        strValues= dtTable.Rows[i]["Column_Name"].ToString().Split(',');\n        if (strValues.Length > 1)\n        {\n            dtTable.Rows[i]["Column_Name"] = strValues[0];\n            for (int j = 1; j < strValues.Length; j++)\n            {\n                var TargetRow = dtTable.NewRow();\n                var OriginalRow = dtTable.Rows[i];\n                TargetRow.ItemArray = OriginalRow.ItemArray.Clone() as object[];\n                TargetRow["Column_Name"] = strValues[j];\n                dtTable.Rows.Add(TargetRow);\n            }\n        }\n    }	0
30475365	30475283	Change any string to string with specific size	var x= str== null \n        ? string.Empty \n        : str.Substring(0, Math.Min(20, str.Length));	0
23305504	23305424	How to create a "global" immutable List<T> list that can be binarySearched	private List<string> _MyList = new List<string>();\n\nprivate void InitializeList()\n{\n    //code here to fill list.\n\n    //Keep in mind, that binary search works on sorted lists.\n    _MyList.Sort(/* Place your object comparer here.  */);\n}\n\n\n\n//Make a copy in an array.\npublic string[] MyListAsArray\n{\n    get { return _MyList.ToArray(); }\n}\n\n\npublic int GetBinarySearchIndex(string value)\n{\n    return Array.BinarySearch(MyListAsArray, value/*, Place your object comparer here.  */);\n}	0
21419651	21419102	ReactiveUI, get a list from a viewmodel when navigated to - if the viewmodel implements interface	Router.CurrentViewModel\n    .Select(x => {\n        var haveCmds = x as IHaveCommands;\n        return haveCmds != null ? haveCmds.Commands : null;\n    })\n    .ToProperty(this, x => x.Commands, out _toolbarCommands);	0
11964062	11963139	How to correctly pin a HubTile to the start screen	void MenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n{\n    var menuItem = (MenuItem)sender;\n    var tileItem = menuItem.DataContext as TileItem;\n    CreateLiveTile(tileIte);\n}\nenter code here\nprivate void CreateLiveTile(TileItem item)\n{\n    // use the TileItem, not HubTile.\n}	0
33991637	33989559	How to load XAML content on demand	UserControl1 ctrl = new UserControl1();            \nGrid1.Children.Add(ctrl);	0
31922302	31887184	Windows Phone multi-touch	TouchPoint primaryTouchPoint = e.GetPrimaryTouchPoint(mainGrid);\nTouchPointCollection touchPoints = e.GetTouchPoints(mainGrid);\n\nforeach (TouchPoint tp in touchPoints)\n{\n    var controlPosition = myControl.TransformToVisual(Application.Current.RootVisual).Transform(new Point(0, 0));\n    if (tp.Action == TouchAction.Down && tp_is_in_myControl)\n        do_something;\n\n}	0
8602988	8602949	generate URL with @Url.Action	var url = '@Url.Action("Group", "Edit", new { id = "__id__" })'.replace('__id__', myParameterInJavascript);\nreturn '<a href="' + url + '">link</a>';	0
18756128	18716570	AutoMapper - Ignore properties from base class for all implementations	Mapper.AddGlobalIgnore("CreatedOn");\nMapper.AddGlobalIgnore("CreatedBy");\nMapper.AddGlobalIgnore("ModifiedOn");\nMapper.AddGlobalIgnore("ModifiedBy");	0
24034830	24033940	Add code in runtime	accountRepository.Find(dto => \n    (string.IsNullOrEmpty(firstName) ? false : dto.FirstName == firstName) || \n    (string.IsNullOrEmpty(lastName) ? false : dto.LastName == lastName) ||\n    (string.IsNullOrEmpty(email) ? false : dto.Email == email))\n    .Select(x => CreateAccount(x)).ToList();	0
12321662	12321490	How to determine whether two word documents are the same using word interop	Document tempDoc = app.CompareDocuments(doc1, doc2);\nbool anyChanges = tempDoc.Revisions.Count > 0;	0
14757952	14756345	how to handle empty detailsview on ondatabound	DataRowView myView = (DataRowView)DetailsView1.DataItem;\n        if (myView == null)\n        {	0
5176710	5176697	How can convert a datetime to double?	var converted = DateTime.Now.ToOADate();	0
21957753	21957717	Loop through XML file and display only chosen node	XDocument xDoc = XDocument.Parse(xmlString);\n\nvar names = xDoc.Descendants("name").Select(n => n.Value).ToList();	0
29328687	29308933	Getting wrong colors after an image manipulations	inp_bmp.Save("D:\\img\\4.png", System.Drawing.Imaging.ImageFormat.Png);	0
9922186	9903626	Creating an XML file using Schema	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\n\nnamespace XmlNameSpace\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            XNamespace xmlns = XNamespace.Get("urn:schema-name");\n            XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");\n            XNamespace schemaLocation = XNamespace.Get("urn:schema-name schema.xsd");\n\n            XDocument p =  new XDocument(\n                new XElement(xmlns + "root",\n                    new XAttribute(XNamespace.Xmlns + "xsi", xsi),\n                    new XAttribute(xsi + "schemaLocation", schemaLocation),\n                    new XElement("parent-of-some-child",\n                        new XElement("somechild","value"))\n                )\n            );\n\n\n            p.Save("c:\\test.xml");\n\n\n        }\n    }\n}	0
5746574	5746448	Struggling with a regular expression - new to it	filename="?(?<filename>[^;"]+)[;"\s]*type	0
18308054	18308012	How to split a string in chunks of eight chars?	IEnumerable<string> groups =  Enumerable.Range(0, binaryString.Length / 8)\n                                        .Select(i => binaryString.Substring(i * 8, 8));	0
17477949	17477507	Database schema for multiple companies	interface IMyTableName {\n    int companyId;\n}	0
6354068	6354036	C#: How do I round a decimal and assign it to an int16?	value = (Int16)Math.Round((x*6)/y);	0
22330413	22330366	Add value to array in C#	List<string> names = new List<string> {"Matt", "Joanne", "Robert"};\n\nnames.Add("Steve");\n\nforeach (string i in names)\n{\n    richTextBox1.AppendText(i + Environment.NewLine);\n}	0
20154299	20149242	POST PHP Arrays in VB NET or C#	collection[0][IDacta]=35&collection[0][fecha]=2013-11-20&collection[0][hora]=12:15&collection[0][num]=36646363463636&collection[0][tipo]=multa&collection[0][calle]=alberdi&collection[0][altura]=450&collection[0][dominio]=HDP 123&collection[1][IDacta]=36&collection[1][fecha]=2013-11-20&collection[1][hora]=10&collection[1][num]=36646363463636&collection[1][tipo]=multa&collection[1][calle]=alberdi&collection[1][altura]=450&collection[1][dominio]=HDP 123	0
15023234	15016175	Grouping text by characters into dictionary of chacartes with Unicode code points in Hex format	Int i = 64;\nstring hex = i.ToString("X");	0
30143590	30143514	Assigning new value to all array elements	//you can overwrite your previous array like this\nint[] arr = {-1,-1,-1,-1,-1,-1,-1};\narr = new int[] {0,1,2,5,7,18,20};	0
26795905	26794880	Send Button in Serial	//DetectCombination like this:\n    public DateTime PrevPress { get; set; }\n    public DateTime CurrentPress { get; set; }\n    public string PrevKey { get; set; }\n\n    private void SEND_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        string keycomb = DetectCombination(e.KeyChar.toString);\n    }\n    public string DetectCombination(string currentKey)\n    {\n        CurrentPress = DateTime.Now;\n        if(CurrentPress.CompareTo(PrevPress) < //100ms)\n        {\n            PrevKey+=currentKey;\n        }\n        else\n        {\n            PrevKey = currentKey;\n            PrevPress = CurrentPress;\n        }\n        return PrevKey;\n    }	0
21565238	21564534	Is there a combination of TextFormatFlags to allow text wrapping and an ending ellipsis?	TextFormatFlags.TextBoxControl	0
17039575	17039516	C# int only take 1 argu?	book.BookId = Int32.Parse(id.Value.ToString());	0
13296985	13296129	Detect if application is running under system account?	bool isSystem;\nusing (var identity = System.Security.Principal.WindowsIdentity.GetCurrent())\n{\n    isSystem = identity.IsSystem;\n}	0
12987835	12987799	InvalidOperationException after removing an element in an arrayList	for(int i = 0; i < list.Count(); i++){\n   if ((list[i] > 2) && (list[i] % 2 == 0)) {\n                list.RemoveAt(i); \n                i--; //as offsets have shifted by one due to removal\n            }\n}	0
4221152	4221055	C#/C++: How to visualize muli-dimensional arrays	sqrt((5-9)^2+(3-3)^2+(9-7)^2+...)	0
6587855	6587816	How to change the ErrorMessage for int model validation in ASP.NET MVC?	[Required(ErrorMessage = "Please enter how many Stream Entries are displayed per page.")]\n[Range(0, 250, ErrorMessage = "Please enter a number between 0 and 250.")]\n[Column]\n[DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")]\npublic int StreamEntriesPerPage { get; set; }	0
12804117	12782184	Use RecordSelectionFormula in Crystal Reports with an IN Clause	DataTable dtRawData = new DataTable();\nSqlConnection loConn = ConnectionUtilities.getServerConnection();\nloConn.Open();\nSqlDataAdapter sdaSysObjects = new SqlDataAdapter(psSqlStatement, loConn);\nsdaSysObjects.Fill(dtRawData);\nReport.SetDataSource(dtRawData);	0
32093079	32092920	how to Sum in LINQ using C#	var result = list.GroupBy(x => x.id)\n                 .Select(x => new { id = x.Key, Amount = x.Sum(z => z.amount) });	0
2729923	2729910	Is there a class like a Dictionary without a Value template? Is HashSet<T> the correct answer?	Dictionary<TKey, TValue>	0
16774241	16774191	create dynamically session value	string pageTitle = new PageManager().GetPageNode(new Guid(SiteMapBase.GetCurrentProvider().CurrentNode.Key)).Title;\nSession[pageTitle] = true; //remove double = as it is for comparing, \n                           //also get rid of single quotes	0
4496113	4495268	Binding Web Application, Site Collection, Sites and Library data to a Sharepoint 2007 dropdown list in a web part	SPFarm farm = SPFarm.Local;\n            SPWebService service = farm.Services.GetValue<SPWebService>("");\n            foreach (SPWebApplication webapp in service.WebApplications)\n            {\n                foreach (SPSite sitecoll in webapp.Sites)\n                {\n                    foreach (SPWeb web in sitecoll.AllWebs)\n                    {\n                        <<Use recursion here to Get sub WebS>>\n                        web.Dispose(); \n                    }\n\n                    sitecoll.Dispose();   \n\n                }\n\n            }	0
22795289	22795100	Launching a stream in VLC from C# program	vlc -vvv http://www.example.org/your_file.mpg	0
26694397	26694239	How to handle array of structures in C#?	private struct Triangle\n{\n    double[] LocalPoint0;\n    double[] LocalPoint1;\n    double[] LocalPoint2;\n\n    public Triangle(double LP0x, double LP0y, double LP0z, double LP1x, double LP1y, double LP1z, double LP2x, double LP2y, double LP2z)\n    {\n        LocalPoint0 = new double[3];\n        LocalPoint1 = new double[3];\n        LocalPoint2 = new double[3];\n        //snip\n    }\n}	0
10337239	10335110	Marshalling c# arrays to pointers for static c library	[DllImport("PixelFlowIE.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "PixelFlow")]\nprivate static extern void PixelFlowDLL([In, Out] Node[] gi, int width, int height, SourceInfo[] sources, int sourceCount, int iterations, int iterPerPeriod, ProgressCallback prg);	0
2929179	2929140	Can't cast treeviewitem as treeviewitem in wpf	strutureTree.ItemContainerGenerator.ContainerFromItem(structureTree.SelectedItem)	0
7888407	7888197	How do I search through an ItemCollection of a Pivot control	MainPivot.Items.Where(i => ((PivotItem)i).Header.ToString() == "News").FirstOrDefault();	0
22320748	22293038	Dequeue in a Priority queue using a Sorted Dictionary in C#	public T Dequeue()\n    {\n        var highestPriorityList = dictionary[dictionary.Keys.First()];\n        if (highestPriorityList.Count == 0)\n        {\n            dictionary.Remove(dictionary.Keys.First());\n        }\n        var topElement = highestPriorityList.First();\n        highestPriorityList.Remove(topElement);\n        return topElement;\n    }	0
15411301	15411230	Bind a char[] in WPF	string strEvtNumeroString\n    {\n        get\n        {\n            return strEvtNumero.ToString();\n        }\n        set\n        {\n            strEvtNumero = value.ToArray();\n        }\n    }	0
14051430	14051237	Want to create TextBox that can only accept value greater than previous entered	public partial class Form1 : Form\n{\n    int threshold = 0;\n    public Form1()\n    {\n        InitializeComponent();\n\n    }\n\n    private void textBox1_Validating(object sender, CancelEventArgs e)\n    {\n        TextBox tb = (TextBox)sender;\n        int value;\n        if (int.TryParse(tb.Text, out value))\n        {\n            if (value <= threshold)\n            {\n                errorProvider1.SetError(tb, "Value Must be Greater than " + threshold);\n            }\n            else\n            {\n                errorProvider1.Clear();\n                threshold = value;\n            }\n\n        }\n        else\n        {\n            errorProvider1.SetError(tb, "Value Must be an integer");\n        }\n\n    }  \n}	0
30922560	30922416	How to get value of the selected item	String c=combobox.SelectedValue	0
2350112	2350099	How to convert an int to a little endian byte array?	byte[] INT2LE(int data)\n  {\n     byte[] b = new byte[4];\n     b[0] = (byte)data;\n     b[1] = (byte)(((uint)data >> 8) & 0xFF);\n     b[2] = (byte)(((uint)data >> 16) & 0xFF);\n     b[3] = (byte)(((uint)data >> 24) & 0xFF);\n     return b;\n  }	0
3430964	3430114	transform a lambda expression	Type persistentAttributeInfoType = [TypeYouKnowAtRuntime];\nParameterExpression parameter = Expression.Parameter(persistentAttributeInfoType, "info");\nLambdaExpression lambda = Expression.Lambda(\n    typeof(Func<,>).MakeGenericType(persistentAttributeInfoType, typeof(bool)), \n    Expression.Equal(Expression.Property(parameter, "Owner"), Expression.Constant(null)),\n    parameter);	0
6581050	6580710	Using screen.primaryscreen for dual display	System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height \nSystem.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width	0
13467205	13467088	Using Timespan as key in dictionary?	Dictionary<TimeSpan,int> _dict = new Dictionary<TimeSpan,int>();\nwhile(true)\n{\n       TimeSpan t = // some timespan which is updating every second\n       int value =  // some value associated with timespan\n       _dict.Add(t,value);\n}	0
21552333	21545824	Adding one day to last day of the month	if (dt.Hour >= 14)\n                {\n                    dt.AddDays(1);\n                }\n                else if (dt.DayOfWeek == DayOfWeek.Sunday)\n                {\n                    dt.AddDays(1);\n                }\n                day = dt.Day;	0
9927103	9922854	Moving Pivotviewer Collections from Silverlight 4 to Silverlight 5	private CxmlCollectionSource _cxml;\n    void pViewer_Loaded(object sender, RoutedEventArgs e)\n    {\n        _cxml = new CxmlCollectionSource(new Uri("http://myurl.com/test.cxml",\n                                             UriKind.Absolute));\n        _cxml.StateChanged += _cxml_StateChanged;\n    }\n\n    void _cxml_StateChanged(object sender,\n                           CxmlCollectionStateChangedEventArgs e)\n    {\n        if(e.NewState == CxmlCollectionState.Loaded)\n        {\n            pViewer.PivotProperties =\n                       _cxml.ItemProperties.ToList();\n            pViewer.ItemTemplates =\n                       _cxml.ItemTemplates;\n            pViewer.ItemsSource =\n                       _cxml.Items;\n        }\n    }	0
33516877	33516397	Passing private variable to base class constructor	private const int DefaultLength = 10000;\n\nprivate int length = DefaultLength;\n\npublic Filtering() : base(DefaultLength)\n{\n}	0
19197132	19196900	How to close current Browser window and redirect to a previously opened window for the same browser	String x = "<script type='text/javascript'>window.opener.location.href='**Your new url of new page after completing test**';self.close();</script>";\nScriptManager.RegisterClientScriptBlock(this.Page,this.Page.GetType(), "script", x,false);	0
10927807	10927710	timer as part of a struct	private class Data{\n    public int Volume {get; set; }      \n    private System.Timers.Timer _aliveTimer;\n\n    public Data() \n    {   \n        _aliveTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n    }\n\n    public void Start() \n    {\n        _aliveTimer.Start();\n    }\n\n    private void OnTimedEvent(object source, ElapsedEventArgs e)\n    {\n        Console.WriteLine("this = " + volume);\n    }\n}\n\nData ret = new Data();\nret.Volume = rand.Next(1, 10) * 100;    \nret.Start();	0
24427944	24427462	Print Output to cmd	IntPtr fg = GetForegroundWindow(); //use fg for some purpose\n\nvar bufferSize = 1000;\nvar sb = new StringBuilder(bufferSize);\n\nGetWindowText(fg, sb, bufferSize);\n\nConsole.WriteLine(sb.ToString());	0
1348891	1348855	Calling a function in class A from a thread in class B [C#]	B child = new B(this, manualResetEvent);\n... etc...\n\nClass B\n{\nprivate A parent;\nprivate ManualResetEvent manualResetEvent;\n\npublic B(A p, ManualResetEvent mre)\n{\n    parent = p;\n    manualResetEvent = mre;\n    ... etc ...\n\n\nprivate void Manage()\n{\n    ... do some work ...\n    ... call some functions ...\n\n    parent.DoIt(param);\n\n    ... etc...	0
18505162	18505109	Counter with 5 digits	counter.ToString().PadLeft(5, '0')	0
22943467	22942480	Can I specify a local file location in the Uri parameter for XmlSchemaSet.Add() method?	_schemaUri = @"L:\schemaDoc.xsd";\nXmlSchemaSet schemas = new XmlSchemaSet();\nschemas.Add(_targetNamespace, _schemaUri);	0
18030862	18030759	C#/WPF - I can't update UI from a backgroundworker	///...blah blah updating files\nstring newText = "abc"; // running on worker thread\nthis.Invoke((MethodInvoker)delegate {\n    someLabel.Text = newText; // runs on UI thread\n});\n///...blah blah more updating files	0
5024654	5024595	Parsing a text file into fields using multiple delimiter types	([\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}) \[([\w]+)\] ([a-zA-Z0-9 ]+) -> (\([\w]+\)[a-zA-Z0-9 ]+): (.*)	0
24836735	24833621	Pass datagridview to event - Combine Events	private void mainLogDGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n{\n   if (((DataGridView)sender).Name == dataGridView1.Name) \n   { '//Grid one Process }\n   else if (((DataGridView)sender).Name == dataGridView2.Name) \n   { '//Grid TweProcess  }\n\n}\n\nprivate void filteredLogDGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n{\n      if (((DataGridView)sender).Name == dataGridView1.Name) \n      { '//Grid one Process }\n      else if (((DataGridView)sender).Name == dataGridView2.Name) \n      { '//Grid TweProcess  }\n}	0
20601755	20600704	how to remove and add css class to a specific textbox inside gridview in c# asp.net?	((TextBox)arow.FindControl("TextAmount")).Attributes["class"] = "erroramount";	0
21282147	21282084	How to write an XML file by fetching values from Table in Database?	YouDataSet.WriteXml(filepath)	0
1679171	1678627	Moving Data access layer to WCF service	client app -> Repository Interfaces -> Repository Implementations	0
30480373	30480070	json.net insert multiple objects on post	string path = @"C:\inetpub\wwwroot\JSON\dotNet_BW3b\bw_results.json";\n\nif (!File.Exists(path)) \n{\n    File.WriteAllText(path, json);    \n}\nelse\n{\n    File.AppendAllText(path, json);    \n}	0
31940749	31940728	Flatten a list in linq	var finalList = zz.SelectMany(a => a).ToList();	0
4668366	4668335	sql - duplicates	if not exists(select * from table where PostId =@PostId)\nBegin\n //add\nEnd	0
15539058	15538928	How do I get all class properties that accomplish a requisit established in its attribute value?	var propList = \n    from prop in myBookInstance.GetType()\n                               .GetProperties()\n    let attrib = prop.GetCustomAttributes(typeof(MyAttrib), false)\n                     .Cast<MyAttrib>()\n                     .FirstOrDefault()\n    where attrib != null && attrib.isListed\n    select prop;	0
20347783	20347567	Modified JSON string	class Result\n{\n  public int results {get;set;}\n  public List<Album> GetAlbumResult { get; set;}\n}	0
10813231	10813062	Dynamically creating variables in C#	var list = new List<DataGridView>();\n\nfor (int i = 1; i <nCounter ; i++)\n{\n    System.Windows.Forms.DataGridView dvName = new DataGridView();\n    dvName.Name = "dv" + i.ToString();\n    list.Add(dvName);\n    // other operations will go here..\n}\n\nforeach (var dv in list)\n{    \n    ...do something... \n}\n\nDataGridView secondDv = list.Single(dv=>dv.Name == "dv2");\nsecondDv.DoSomething()	0
31480829	31452815	Add Crosshair to Bing Maps WPF Control	var img = new Image();\n//Add code to load your image.\n\n//Center image some how. Try margins, or hortizontal and vertical alignment.\nimage.Margin = new Thickness(map.ActualWidth - img.ActualWidth, map.ActualHeight - img.ActualHeight);\n\nmap.Children.Add(image);	0
15268415	15267246	Updating Checked ListBox values in Database	DELETE \nFROM favfood\nWHERE id=@Id and foodid not in(new_list_of_food_ids)\n\n// serialized new_list_of_food_ids\n\nINSERT INTO favfood(id,foodid)\n(SELECT @Id, [int] \nFROM       OPENXML (@idoc, '/ArrayOfInt/int',1)\nWITH ([int]  int '.')\nwhere [int] not in (select foodid from favfood where id=@Id))	0
11654826	11654653	Replace most non alphanumeric characters with one value, remaining with another	var result = System.Text.RegularExpressions.Regex.Replace(input, @"[^a-zA-Z0-9]", m =>(m.Value == "'" || m.Value == "_") ? "" : "-");	0
16309463	16309222	Partial view wont render after ajax update	public ActionResult _SearchResult(string fname, string lname)\n{\n    var peopleList = repo.GetSearchResult(fname, lname);\n\n    //Is peopleList the right model type? If not, create your model here\n\n    return View(peopleList);\n}	0
10332943	10332665	Overwriting menu css with javascript in C#	#menu ul li.currentpage a:link, #menu ul li.currentpage a:visited\n{\n    background:#172c7d;\n    color:#fff;    \n}	0
33636381	33635869	Cropping an image from file and resaving in C#	private void croptoSquare(string date)\n{\n    //Location of 320x240 image\n    string fileName = Server.MapPath("~/Content/images/" + date + "contactimage.jpg");\n\n    // Create a new image at the cropped size\n    Bitmap cropped = new Bitmap(240,240);\n\n    //Load image from file\n    using (Image image = Image.FromFile(fileName))\n    {\n        // Create a Graphics object to do the drawing, *with the new bitmap as the target*\n        using (Graphics g = Graphics.FromImage(cropped) )\n        {\n            // Draw the desired area of the original into the graphics object\n            g.DrawImage(image, new Rectangle(0, 0, 240, 240), new Rectangle(40, 0, 240, 240), GraphicsUnit.Pixel);\n            fileName = Server.MapPath("~/Content/images/" + date + "contactimagecropped.jpg");\n            // Save the result\n            cropped.Save(fileName);  \n        }\n     }\n\n}	0
23368468	23364920	How to create a fast and lightweight UIElement	public class Circle : UIElement\n{\n    protected override void OnRender(DrawingContext drawingContext)\n    {\n        const double radius = 2.5;\n        drawingContext.DrawEllipse(Brushes.Red, null, new Point(), radius, radius);\n    }\n}	0
8309462	8309413	Saving and loading TextBox or other control values with a text file	var textBox = yourForm.Controls.Find("name", true) as TextBox;\n  if(textBox != null)\n       textBox.Text = "text";	0
4105878	4105762	Serializing object that inherits from List<T>	public class Foo<T> {\n    public string Name {get;set;}\n    private readonly List<T> items = new List<T>();\n    public List<T> Items { get { return items; } }\n}	0
9058332	9058249	Search through array/container to find value nearest to x only if it's less than x	// Assuming values is IEnumerable<double>\nvalues = values.Where(v => v <= input);\n\nreturn values.Any() ? values.Max() : resultWhenInputTooSmall;	0
11496629	11496512	C# Display Formatted Content of Array	for (int i = iteration; i <= MAX_SIZE_ARRAY; i--)\n {             \n   //iterates through the loop to display all the players name then score\n   if (score[iteration - 1] == 300)\n     Console.WriteLine("{0} score was {1}*", player[iteration - 1],                                  score[iteration - 1]);\n   else\n     Console.WriteLine("{0} score was {1}", player[i], score[i]);\n }	0
28113063	28107597	How to restore Configuration Settings when they fail to initialize	try\n{\n     var prop1= Settings.Default.prop1;\n}\ncatch (Exception ex)\n{\n    var userSettingsLocation =\n      Path.Combine(Environment.ExpandEnvironmentVariables(\n        "%USERPROFILE%"), "AppData","Local", "MyApp");\n    if (Directory.Exists(userSettingsLocation))\n    {\n         if (ex.InnerException is System.Configuration.ConfigurationException)\n         {\n             var settingsFile = (ex.InnerException as ConfigurationException).Filename;\n             File.Delete(settingsFile);\n             System.Windows.Forms.Application.Restart();\n         }\n    }\n}	0
23246916	23246745	Retrieve length of the class(declared as array) which is used as dictionary value	testing.Add("one", new test[] {});	0
22200936	22199332	MVC 4 - Kendo Grid Data Binding	public ActionResult User_Read([DataSourceRequest]DataSourceRequest request)\n    {\n        var model = new List<ViewModelA>()\n        {\n            new ViewModelA()\n            {\n                FirstName = "Name",\n                Supervisor = "Mgr",\n            },\n            new ViewModelA()\n            {\n                FirstName = "FirstName",\n                Supervisor = "Supervisor",\n            },\n        };\n\n        return Json(model.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);\n    }	0
27741426	27741352	how to add a node into an xml	XDocument doc = XDocument.Load("input.xml");\n        doc.Root.Element("Style").Element("AdminEntry").Add(new XElement("Message",\n            new XAttribute("id", 2),\n            new XAttribute("value", "label"),\n            new XAttribute("desc", "")));	0
23833074	23832261	How can i change the backcolor of picture box the number will taken from the textbox	int i = 3;\nstring PB= "pictureBox" + i;\nPictureBox pb= this.Controls.Find(PB, true).FirstOrDefault() as PictureBox;\npb.BackColor = Color.Green;	0
7052060	7051617	C# CodeDom Add embedded resource without first dropping file to disk	private string CmdArgsFromParameters(CompilerParameters options)\n{\n    StringBuilder stringBuilder = new StringBuilder(128);\n    // ...\n    StringEnumerator stringEnumerator = options.EmbeddedResources.GetEnumerator();\n    try\n    {\n        while (stringEnumerator.MoveNext())\n        {\n            string str = stringEnumerator.Current;\n            stringBuilder.Append("/res:\"");\n            stringBuilder.Append(str);\n            stringBuilder.Append("\" ");\n        }\n    }\n    finally\n    {\n        IDisposable disposable2 = stringEnumerator as IDisposable;\n        if (disposable2 != null)\n        {\n            disposable2.Dispose();\n        }\n    }\n    // ...\n    return stringBuilder.ToString();\n}	0
34479829	34478993	get utf-8 geocode google map API Street address in asp	using (WebClient wc = new WebClient())\n    {\n wc.Encoding = Encoding.UTF8;\n wc.DownloadStringCompleted += new   DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);\n\n        wc.DownloadStringAsync(new Uri(requestUri));\n    }	0
2063627	2058810	Output first two paragraphs from html stored as string	private string GetFirstParagraph(string htmltext)\n        {\n            Match m = Regex.Match(htmltext, @"<p>\s*(.+?)\s*</p>");\n            if (m.Success)\n            {\n                return m.Groups[1].Value;\n            }\n            else\n            {\n                return htmltext;\n            }\n        }	0
20574371	20573871	Dynamic Linq Contains to filter a List	public static IEnumerable<T> Filter<T>(IEnumerable<T> source, string searchStr)\n{\n  var searchStrLower = searchStr.ToLower();\n  var propsToCheck = typeof(T).GetProperties().Where(a => a.PropertyType == typeof(string) && a.CanRead);\n\n  return source.Where(obj => {\n    foreach (PropertyInfo prop in propsToCheck)\n    {\n      string value = (string)prop.GetValue(obj);\n      if (value != null && value.ToLower().Contains(searchStrLower)) return true;\n    }\n    return false;\n  });\n}	0
9118900	9117013	Adding multiple Cells to a single Row	SpreadSheet.Cell cell = new SpreadSheet.Cell()\n        {\n            CellReference = "A1",\n            DataType = SpreadSheet.CellValues.String,\n            CellValue = new SpreadSheet.CellValue("Cell1")                 \n        };\n\n        SpreadSheet.Cell cell2 = new SpreadSheet.Cell()\n        {\n            CellReference = "B1",\n            DataType = SpreadSheet.CellValues.String,\n            CellValue = new SpreadSheet.CellValue("Cell2")\n        };	0
21635371	21635287	Iterating through a Dictionary of Dictionaries	var dictOfDictionaries = Parse();\nforeach (var dictPair in dictOfDictionaries) {\n    Console.WriteLine("Key: {0}", dictPair.Key);\n    foreach (var innerPair in dictPair.Value) {\n        Console.WriteLine("\t{0}:{1}", innerPair.Key, innerPair.Value);\n    }\n}	0
1885780	1885426	Iterate through a list of words and search through a folder to find file(s) containing that word	string[] files = Directory.GetFiles("directorypath");\n\n    foreach (string s in files)\n    {\n        FileInfo file = new FileInfo(s);\n        StreamReader reader = file.OpenText();\n\n        if(reader.ReadToEnd().Contains("string you are looking for"))\n        {\n            return true;\n        }\n    }	0
21711136	21703968	Force to print in legal paper	writer.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, PdfBoolean.PDFTRUE);	0
33615997	33612215	How to mark job as durable in Quartz .net?	var job = JobBuilder.Create<TestJob>()\n                    .WithIdentity(typeof(TestJob).Name)\n                    **.StoreDurably(true)**\n                    .Build();	0
6413911	6413797	how do i format list view column to show currency symbol	String.Format("{0:c}", CurrencyValue);	0
24105273	24105239	How to avoid duplicates when adding items to a list box in C#	if (List2.SelectedItem != null \n  if (! List1.Items.Contains(List2.SelectedItem))\n     {  List1.Items.Add(List2.SelectedItem);\n        List2.Remove(List2.SelectedItem);\n     }	0
31630015	31628740	How can I return a list of words using regex, but define a word to also includes contents of a token?	string pattern = @"\w|\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)|\{((?<BR>\{)|(?<-BR>\})|[^{}]*)+\}";\n\n\n        string pattern = @"\n           \w|                                   #Match any word OR\n           \(((?<BR>\()|(?<-BR>\))|[^()]*)+\)|   #Match a () balanced group OR\n           \{((?<BR>\{)|(?<-BR>\})|[^{}]*)+\}    #Match a {} balanced group\n         ";	0
3703553	3703528	Convert serial port returned byte to millisecond	if (BitConverter.IsLittleEndian) {\n  Array.Reverse(b);\n}\nint ms = BitConverter.ToInt32(b, 0);	0
15157422	15157370	c# net2.0 Console App merge arguments in one single string	string result = string.Join(" ", args, 1, args.Count-1);	0
8027244	8026951	Interfacing octave with C#	Process.Start	0
28789442	28789357	Serializing Multiple Enum Values in WebApi	"Brown,+Blue"	0
20227058	20218782	deserialize inherited object	[BsonKnownTypes(typeof(subclass)]\nclass BaseClass {...}	0
3310760	3310595	telerik radgrid - how do I set the page focus to the insert button after clicking the add new record button to add a record	Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)\n    If TypeOf e.Item Is GridCommandItem Then\n\n        Dim myButton As LinkButton = TryCast(e.Item.FindControl("myButtonID"), LinkButton)\n        myButton.Focus()\n    End If\nEnd Sub	0
10948984	10948022	How can I get number of pages in a pdf file in AxAcroPdf?	GetNumPages(); Returns The number of pages in a file, or -1 if the number of \n               pages cannot be determined.	0
21249599	21249402	Need help to get IP from strings in c#	if (line.Contains("X-Originating-IP: ")) {\n    string ip = line.Split(':')[1].Trim(new char[] {'[', ']', ' '});\n    Console.WriteLine(ip);\n}	0
34219234	34218639	Return List value from another window	public partial class MainWindow : Window\n{\n    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        Window1 dlg = new Window1();\n        if(dlg.ShowDialog()??false)\n        {\n            MessageBox.Show(dlg.S);\n        }\n    }\n}\n\n    // Dialog\npublic partial class Window1 : Window\n{\n    public string S\n    {\n        get\n        {\n            return this.txt1.Text;\n        }\n    }\n\n    private void btnClose_Click(object sender, RoutedEventArgs e)\n    {\n        this.DialogResult = true;\n    }\n}	0
13241902	13241832	Comparing Winform Button Colors	if (btn2.BackColor == btn3.BackColor && btn3.BackColor == btn4.BackColor)\n        {\n            MessageBox.Show("ALL BUTTONS ARE THE SAME COLOR");\n        }\n        else\n        {\n            MessageBox.Show("ALL BUTTONS ARE NOT THE SAME COLOR");\n        }	0
1485247	1485237	Split String in C# without delimiter (sort of)	string str = "hello";\nchar[] letters = str.ToCharArray();	0
4019823	4019722	Trouble assigning a value to this variable	var commentsXML = xml.Element("ipb").Element("profile").Element("comments");\nthis.Comments = \n(\n    from comment in commentsXML.Descendants("comment")\n    select new Comment()\n    {\n        ID = comment.Element("id").Value,\n        Text = comment.Element("text").Value,\n        Date = comment.Element("date").Value,\n        UserWhoPosted = new Friend()\n        {\n            ID = comment.Element("user").Descendants("id"),\n            Name = comment.Element("user").Descendants("name"),\n            Url = comment.Element("user").Descendants("url"), \n            Photo =  comment.Element("user").Descendants("photo")\n        }\n    }\n).ToList();	0
32459172	32459118	Performance tuning a piece of C# / SQL code	var sbCopy = new SqlBulkCopy("myConnectionString")\n        {\n            DestinationTableName = tableName,\n            BatchSize = 100000\n        };\n\n        sbCopy.WriteToServer(_log_data.AsDataReader());	0
7520142	7519094	Pass array from c++ library to a C# program	#using <System.dll> // optional here, you could also specify this in the project settings.\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    const int count = 10;\n    int* myInts = new int[count];\n    for (int i = 0; i < count; i++)\n    {\n        myInts[i] = i;\n    }\n    // using a basic .NET array\n    array<int>^ dnInts = gcnew array<int>(count);\n    for (int i = 0; i < count; i++)\n    {\n        dnInts[i] = myInts[i];\n    }\n\n    // using a List\n    // PreAllocate memory for the list. \n    System::Collections::Generic::List<int> mylist = gcnew System::Collections::Generic::List<int>(count);\n    for (int i = 0; i < count; i++)\n    {\n        mylist.Add( myInts[i] );\n    }\n\n    // Otherwise just append as you go... \n    System::Collections::Generic::List<int> anotherlist = gcnew System::Collections::Generic::List<int>();\n    for (int i = 0; i < count; i++)\n    {\n        anotherlist.Add(myInts[i]);\n    }\n\n    return 0;\n}	0
1283537	1283471	Connecting siblings in binary search tree	void connect(Node node, int depth, List<Node> prev)\n{\n  if (node == null)\n    return;\n  if(prev.Size <= depth)\n    prev.Add(depth);\n  else {\n    prev[depth].sibling = node;\n    prev[depth] = node;\n  }\n  connect(node.left, depth+1, prev);\n  connect(node.right, depth+1, prev);\n}	0
6515960	6515290	Page doesn't postback after clicking OK in confirm box for Radiobuttonlist	RadioButtonOpenRestricted.AutoPostBack = true;\nRadioButtonOpenRestricted.Items.FindByValue("Open Access").Attributes.Add("OnClick", "if (!confirm('Are you sure?')) return false;");	0
16215767	16215741	C# read only Serial port when data comes	public static void Main()\n{\n    SerialPort mySerialPort = new SerialPort("COM1");\n\n    mySerialPort.BaudRate = 9600;\n    mySerialPort.Parity = Parity.None;\n    mySerialPort.StopBits = StopBits.One;\n    mySerialPort.DataBits = 8;\n    mySerialPort.Handshake = Handshake.None;\n\n    mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);\n\n    mySerialPort.Open();\n\n    Console.WriteLine("Press any key to continue...");\n    Console.WriteLine();\n    Console.ReadKey();\n    mySerialPort.Close();\n}\n\nprivate static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)\n{\n    SerialPort sp = (SerialPort)sender;\n    string indata = sp.ReadExisting();\n    Debug.Print("Data Received:");\n    Debug.Print(indata);\n}	0
2750192	2719685	How to take a screenshot with Mono C#?	Gdk.Window window = Gdk.Global.DefaultRootWindow;\nif (window!=null)\n{           \n    Gdk.Pixbuf pixBuf = new Gdk.Pixbuf(Gdk.Colorspace.Rgb, false, 8, \n                                       window.Screen.Width, window.Screen.Height);          \n    pixBuf.GetFromDrawable(window, Gdk.Colormap.System, 0, 0, 0, 0, \n                           window.Screen.Width, window.Screen.Height);          \n    pixBuf.ScaleSimple(400, 300, Gdk.InterpType.Bilinear);\n    pixBuf.Save("screenshot0.jpeg", "jpeg");\n}	0
4586910	4586779	Increment an index that uses numbers and characters	private static String Increment(String s)\n    {\n        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\n        char lastChar = s[s.Length - 1];\n        string fragment = s.Substring(0, s.Length - 1);\n\n        if (chars.IndexOf(lastChar) < 35)\n        {\n            lastChar = chars[chars.IndexOf(lastChar) + 1];\n\n            return fragment + lastChar;\n        }\n\n        return Increment(fragment) + '0';\n    }	0
9570277	9265395	How to terminate a Java Application from a C# service	ProcessStartInfo psi = new ProcessStartInfo("jps", "-v");\n        psi.RedirectStandardOutput = true;\n        psi.UseShellExecute = false;\n        Process p = new Process();\n        p.StartInfo = psi;\n        p.Start();\n        string[] output = p.StandardOutput.ReadToEnd().Split("\n".ToCharArray());	0
19482311	19481663	Simpler method for pooling integers	class IntegersGame\n{\n    private List<int> _sourceintegers;\n    private List<int> _integers;\n    public void Add(List<int> integers)\n    {\n        _sourceintegers = integers;\n        Reset();\n    }\n\n    public void Reset()\n    {\n        _integers = _sourceintegers.Select(p => p).ToList();\n        _integers.Sort();\n    }\n\n    public int GetFirst()\n    {\n        int ret = _integers.First();\n        _integers.Remove(ret);\n        return ret;\n    }\n\n    public List<int> GetAll()\n    {\n        return _integers;\n    }\n\n    public void Release(int des)\n    {\n        if (_sourceintegers.Contains(des))\n        {\n            _integers.Add(des);\n            _integers.Sort();\n        }\n    }\n\n    public int? Get(int source)\n    {\n        if(_sourceintegers.Contains(source) && (_integers.Contains(source))){\n            _integers.Remove(source);\n            return source;\n        }else{\n            return null;\n        }\n    }\n}	0
2992457	2992451	How to subtract a year from the datetime?	var myDate = DateTime.Now;\nvar newDate = myDate.AddYears(-1);	0
6362426	6362230	Crystal Report | Printing | Default Printer	// Note: untested\nvar dialog = new PrintDialog();\n\nNullable<bool> print = dialog.ShowDialog();\nif (print.HasValue && print.Value)\n{\n    var rd = new ReportDocument();\n\n    rd.Load("ReportFile.rpt");\n    rd.SetParameter("Parameter1", "abc");\n    rd.SetParameter("Parameter2", "foo");\n\n    rd.PrintOptions.PrinterName = dialog.PrinterSettings.PrinterName;\n    rd.PrintToPrinter(1, false, 0, 0);\n}	0
33775923	33775801	How to concatenate multiple column values into one column in datatable c#	DataColumn newColumn;\nnewColumn = new DataColumn("col4");\nnewColumn.Expression =  string.Format("Col1\-{0};Col2\-{1};Col3\-{2}", col1, col2, col3);\nscaleResponseData.Columns.Add(newColumn);	0
5783062	5782913	How to convert from type Image to type BitmapImage?	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}	0
13130143	13130094	Convert Datatable to Object with Linq and Group by	var result = from row in dt.AsEnumerable()\n             group row by new\n             {\n                 c1 = r.Field<string>("col1"),\n                 c2 = r.Field<string>("col2"),\n                 c3 = r.Field<string>("col3")\n             } into section\n             select new\n             {\n                 col1 = section.Key.c1,\n                 col2 = section.Key.c2,\n                 col3 = section.Key.c2,\n                 col4 = section.Select(r => r.Field<string>("col4")).ToList()\n             };	0
9486173	9486019	assigning to the base part of a derived class	void Main()\n{   \n    var thisThing= new ThingEditView {UsefulID = 1, A = 2, B = 3};\n    var foo = new ThingEditView(thisThing);\n\n    //foo.Dump();\n}\n\n// Define other methods and classes here\npublic class Thing\n{\n    public int A {get; set;}\n    public int B {get; set;}        \n    public Thing() {}\n    public Thing(Thing thing)\n    {    \n     this.A = thing.A;\n     this.B = thing.B;\n    }\n}\n\npublic class ThingEditView : Thing\n{\n    public int UsefulID {get; set;}\n    public ThingEditView() {}\n    public ThingEditView(Thing thing) : base(thing) {\n\n    }\n    public ThingEditView(ThingEditView view) : base(view) {\n        this.UsefulID = view.UsefulID;\n    }\n}	0
18874149	18873733	Compare Colors WPF	Ellipse obj = new Ellipse()\n{\n    Name = "",\n    Width = width,\n    Height = height,\n    Fill = Brushes.Transparent,\n    Stroke = Brushes.Red,\n};\n\n...\n\nif (obj.Stroke == Brushes.Red)\n{\n    obj.Stroke = Brushes.Green;\n}\nelse if (obj.Stroke == Brushes.Green)\n{\n    obj.Stroke = Brushes.Red;\n}\nelse\n{\n    obj.Stroke = Brushes.Gray;\n}	0
450532	450491	How to inject text to the cursor focus	Process[] processes = Process.GetProcessesByName("notepad");\nforeach (Process p in processes)\n{\n    IntPtr pFoundWindow = p.MainWindowHandle;\n    // Do something with the handle...\n}	0
23526862	23521712	two reports in one reportViewer	var dataSet = new DataSet();\nusing (var connection = new SqlConnection("ConnectionString")) \n{\n    var sqlAdapter = new SqlDataAdapter("SELECT * FROM TABLE1",connection); // Get the records\n    sqlAdapter.Fill(dataSet, "Table1");\n}\nReportViewer1.Reset();\nReportViewer1.LocalReport.Path = "university_project.Report1.rdlc"; // Path to your report file            \nvar dataSource = new ReportDataSource("ReportDataSet_Name", dataSet.Tables[0]); // Specify report's dataset name and the records it use\nReportViewer1.LocalReport.DataSources.Clear(); // Clean the sources so you can use different datasources each time\nReportViewer1.LocalReport.DataSources.Add(datasource);\nReportViewer1.LocalReport.Refresh();	0
19755269	19747743	Namespaced nodes of the same name - content of the attributes needed	XmlNodeList Testi = XMLdoc.SelectNodes("//ns:dbReference", nsmgr);\n            foreach (XmlNode xn in Testi)\n            {\n                if (xn.Attributes["type"].Value == "GO") \n                {\n                    String Testilator = xn.Attributes["id"].Value;\n                    String Testilator2 = xn.FirstChild.Attributes["value"].Value;\n\n                }\n            }	0
26900792	26900738	How do I create a Dictionary of classes, so that I can use a key to determine which new class I want to initialize?	var objectTypes = new Dictionary<int, Func<int, BaseObject>>();\nobjectTypes[0] = input => new ObjectA(input);\nobjectTypes[1] = input => new ObjectB(input);\n\nobjectTypes[0](1000);\nobjectTypes[1](2000);	0
29944591	29904225	Comparing dates in LINQ which are stored as strings in database	var result = context.MetaTags.Where(mt => SqlFunctions.DateDiff("s", mt.MetaTagFilter1, keyValueMetaTagFilter.MetaTagValue) <= 0);	0
1307806	1307298	Deleting a stored procedure in SQL server	SELECT\n    OBJECT_NAME(object_id)\nFROM\n    sys.sql_modules\nWHERE\n    definition LIKE '%' + 'mySP' + '%'	0
4789805	4789718	Redirect user to a specific page after login	protected void RegisterUser_CreatedUser(object sender, EventArgs e)\n    {\n        FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);\n\n        Response.Redirect( "~/default.aspx" );\n    }	0
25792744	25792656	Content page not able to access controls after changing the name of the page	namespace MyProject\n{\n    public class WebForm1	0
20539091	20537073	WPF Datagrid Focus and keyboard focus	Keyboard.Focus (GetDataGridCell (dataGridFiles.SelectedCells[0]));\n\nprivate System.Windows.Controls.DataGridCell GetDataGridCell (System.Windows.Controls.DataGridCellInfo cellInfo)\n{\n  var cellContent = cellInfo.Column.GetCellContent (cellInfo.Item);\n\n  if (cellContent != null)\n    return ((System.Windows.Controls.DataGridCell) cellContent.Parent);\n\n  return (null);\n}	0
13965341	13961297	How would I add Checbox dynamically into a Grid in WPF application	StackPanel innerStack;\nprivate void course_Loaded(object sender, RoutedEventArgs e)\n{\n    innerStack= new StackPanel{Orientation=Orientation.Vertical}\n    List<Course> courses = ldc.Courses.ToList();\n    foreach (var c in courses)\n    {\n        CheckBox cb = new CheckBox();\n        cb.Name=c.CourseID.ToString();\n        cb.Content = c.CourseID.ToString();\n        innerStack.Chicldren.Add(cb);\n    }\n    Grid.SetColumn(innerStack,  /*Set the column of your stackPanel, default is 0*/)\n    Grid.SetRow(innerStack,  /*Set the row of your stackPanel, default is 0*/)\n    Grid.SetColumnSpan(innerStack,  /*Set the columnSpan of your stackPanel, default is 1*/)\n    Grid.SetRowSpan(innerStack,  /*Set the rowSpan of your stackPanel, default is 1*/)\n\n    grid.Children.Add(innerStack);\n}	0
10707344	10706963	Call method of specific MDI child from parent	frmNewDocument child = ActiveMdiChild as frmNewDocument;\nif (child != null)\n{\n    child->saveFile();\n}	0
11730532	11730249	Redirecting based on value in database - ASP.NET MVC	db.Caglas.Where(c => c.ID == 1).SingleOrDefault();	0
1291953	1291829	How do I use a pattern Url to extract a segment from an actual Url?	var givenUri = "http://joesmith.sitename.com/";\nvar patternUri = "http://{username}.sitename.com/";\npatternUri = patternUri.Replace("{username}", @"([a-z0-9\.-]*[a-z0-9]");\n\nvar result = Regex.Match(givenUri, patternUri, RegexOptions.IgnoreCase).Groups;\n\nif(!String.IsNullOrEmpty(result[1].Value))\n    return result[1].Value;	0
24801226	24801166	C# Multidimensionarrays difference between setting a Value	int[,,] array = new int[3, 3, 3];\narray[0, 0, 0] = "foo"; // oops!\n\narray.SetValue("foo",0,0,0); // OK for now, but at runtime...	0
33267811	33267499	Concatenate two fields from two classes in select list	string connectionString = "Data Source=myDataSource;" + \n    "Initial Catalog=myCatalog;Integrated Security=mySecurity;" +\n    "MultipleActiveResultSets=True";	0
20359316	20359292	How do I conditionally pass a constructor to a base class?	public A(int? i): base(i ?? A.default_i) {}	0
16171330	16170927	How can I assign an ID to a checkbox in a Repeater?	protected void repeaterCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n        CheckBox chk = e.Item.FindControl("chbCategoria") as CheckBox ;\n        chk.Attributes.Add("PageID", DataBinder.Eval(e.Item.DataItem, "DB_FIELD").ToString());\n    }\n}	0
3077800	3077559	Showing image / text on screen without forms in c#	PerPixelAlphaForm transparentImageForm = new PerPixelAlphaForm();\ntransparentImageForm.SetBitmap(<IMAGE GOES HERE>,<OPACITY GOES HERE>);	0
12989141	11550874	Equivalent of 'KeyPreview' property in WinRT Metro	Windows.UI.Xaml.Window.Current.CoreWindow.KeyDown += (sender, arg) => {\n    // invoked anytime a key is pressed down, independent of focus\n}	0
5606066	5605963	Refreshing a DataGridView set up in the designer	dataAdapter.Fill(dataSource.TableName)	0
7964084	7964004	Error while sending null value to stored procedure DateTime parameter	SqlParameter parameter = cmdTwMainEntry.Parameters.Add("@scmDate", System.Data.SqlDbType.DateTime);\n        // Set the value.\n        parameter.Value = (!string.IsNullOrEmpty(txtWaitedDate.Text)) ? Convert.ToDateTime(txtWaitedDate.Text) : System.DbNull.Value;	0
7579808	7567751	Run a VBA Macro against an Excel sheet with C#	Function Insert_VBACode(ByRef oWB As Workbook)\n    Dim oVBP As VBProject   ' VB Project Object\n    Dim oVBC As VBComponent ' VB Component Object\n    On Error GoTo Err_VBP\n    Set oVBP = oWB.VBProject\n    Set oVBC = oVBP.VBComponents.Add(vbext_ct_StdModule)\n    oVBC.CodeModule.AddFromFile "c:\VBADUD\Templates\MSample.bas"\n    oWB.Application.Run "'" & oWB.name & "'!SayHello"\n    oWB.Save\nEnd Function	0
23076862	23073960	Auto-migrations to dynamic contexts for multi tenant databases	Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, MyContextConfiguration>());	0
14420866	14420837	Search for a sub-string within a string	string mystring = "somestring";\nint position = mystring.IndexOf("st");	0
633962	633944	What exception to throw from a property setter?	public int PropertyA\n{\n    get\n    {\n        return //etc...\n    }\n    set\n    {\n        if (condition == true)\n        {\n            throw new ArgumentOutOfRangeException("value", "/* etc... */");\n        }\n        // ... etc\n    }\n}	0
15792915	15792299	how to move the textblock location progamatically	textBlock.Margin = new Thickness(left, top, right, bottom);	0
14034705	14033558	Winforms combobox has lag populating	try\n        {\n           if (!counties.ContainsKey(items[0)\n           {\n             countries.Add(items[0], items[1]);\n           }\n        }\n        catch (Exception ex)\n        {\n              //MessageBox.Show(ex.Message);\n\n        }	0
28187435	28187134	Tcp server with accept list in C#	WSAAccept()	0
7901599	7901558	How do I deserialize XML into an object using a constructor that takes an XDocument?	public static MyClass FromXml (XDocument xd)\n{\n   XmlSerializer s = new XmlSerializer(typeof(MyClass));\n   return (MyClass)s.Deserialize(xd.CreateReader());\n}	0
16704718	16703863	Merging a decrypted search of items within a LINQ query	var newFiles = from f in files\n               join c in companies on f.CompanyId equals c.CompanyId\n               select new File\n               {\n                   prop1 = f.prop1,\n                   //Assign all your other properties\n                   Company = c\n               };	0
33385392	33385296	Stored procedure with output parameters returns -1 in c#	var noOutput = context.Database.ExecuteSqlCommand("EXEC my_sp_name @operatorID OUTPUT, @operatorCode OUTPUT", parameters.ToArray());	0
14778020	14776988	Retrieve current page in Internet Explorer using C#	Dim tWindows As ShellWindows = new ShellWindows\nFor Each tInstance As IWebBrowser2 in tWindows\n  Console.WriteLine(tInstance.LocationURL)\nNext	0
17277375	17240268	How can I get return values from C# .DLLs in LabVIEW 2012?	SetColor()	0
26647017	26646989	get set accessors from static Main() - and best practice for boolean store	private Values yourValues = new Values();\nprivate class Values\n{\n...	0
12105141	12104865	Extracting <a> from C# Webbrowser	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(@"<a onmousedown=""alert('test')"">...</a>");\n\nvar a = doc.DocumentNode.SelectNodes("//a[@onmousedown]")\n            .Select(x => x.Attributes["onmousedown"].Value)\n            .ToArray();	0
13898226	13889812	How to copy a item of a List Into an object in LINQ?	MyClass s = new MyClass();\n        int j = 0;\n        s.GetType().GetProperties().ToList().ForEach(x => { x.SetValue(s, mylist[j++], null); });	0
22525331	22525091	How to verify a password using BCrypt	string salt = BCryptHelper.GenerateSalt(6);\nvar passwordHash= BCryptHelper.HashPassword("Tom123", salt);\n\nbool value = BCryptHelper.CheckPassword("Tom123", passwordHash);	0
18275233	18275119	How to update a control on WPF MainWindow	if (GetLastInputInfo(ref LastInput))\n{\n    IdleTime = System.Environment.TickCount - LastInput.dwTime;\n    string s = IdleTime.ToString();\n\n    Dispatcher.BeginInvoke(new Action(() =>\n    {\n        label1.Content = s;\n    }));\n}	0
13240978	13240915	Converting a WebClient method to async / await	private async void RequestData(string uri, Action<string> action)\n{\n    var client = new WebClient();\n    string data = await client.DownloadStringTaskAsync(uri);\n    action(data);\n}	0
9020688	9019076	Kayak server Image response header	byte[] byteArray = new byte[0];\n                using (Image img = Image.FromFile(url))\n                {\n\n                    using (MemoryStream stream = new MemoryStream())\n                    {\n                        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);\n                        stream.Close();\n                        byteArray = stream.ToArray();\n                    }\n\n                }\n\n                String contentType = url.EndsWith("jpg") ? "image/jpg" : "image/png";\n                var responseHeader = WebServerUtils.Instance.CreateResponseHeader(byteArray.Length, contentType);\n                responseHeader.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);\n                response.OnResponse(responseHeader, new BufferedProducer(byteArray));	0
7756066	7753296	How to synchronize changes in nosql db (ravendb)	var topic = _session.Load<Topic>(topicId)\n                    .Customize(x => x.Include<Topic>(y => y.UserId));\n\nvar user = _session.Load<User>(topic.UserId);	0
7166106	7159645	app_code, modify element on aspx page	if (HttpContext.Current.Handler is Page)\n{\n    Page currentPage = (Page)HttpContext.Current.Handler;\n    if (currentPage != null)\n    {\n        //depending on where the control is located, you may need to use recursion\n        GridView gridView = currentPage.FindControl("GridView1");\n    }\n}	0
4360158	4360089	Serializing an array in C#	using (var stream = File.Create("file.xml")) {\n    var serializer = new XmlSerializer(typeof(string[]));\n    serializer.Serialize(stream, someArrayOfStrings);\n}	0
16700463	16700423	Json deserialization	textBox1.Text = FriendList.summary.unseen_count;	0
33455003	33454971	Remove spaces only before and after commas	s = Regex.Replace(s, " *, *", ",");	0
3135624	3134759	How can I best generate a static array of random number on demand?	function Noise1(integer x, integer y)\n    n = x + y * 57\n    n = (n<<13) ^ n;\n    return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);    \n  end function	0
23427365	23411916	Display specific lines from a .txt file to a listbox	{\n// Adding first genre title\nstring[] lines = File.ReadAllLines(@"C:\Users\James Dunn\Documents\Visual Studio 2012\Projects\Assignment 2\Assignment 2\MyJukeBox\bin\Debug\Media\Genre.txt");\nfor (int l = 3; l < lines.Length; l++)\n{\nmediaLibrary[0].Items.Add(lines[l]);\nif (l == 4)\nbreak;\n}\ngenreTitleTextBox.(mediaLibrary[0]);\n}	0
7739143	7738899	SelectionChanged Event of WPF comboBox is not firing if it has same items in it	ComboBoxItem newItem = new ComboBoxItem();\nnewItem.Content = "same item";\ncmbFunctionsList.Items.Add(newItem);	0
20300466	20300150	Need to read a series of .txt files in a folder and write them in to datagridview	public class ID\n{\n    public string id {get; set; }\n    public string UserName {get; set; }\n    public string Password {get; set; }        \n    public string Bla1 {get; set; }\n    public string Bla2 {get; set; }\n}\n\npublic IList<ID> GetAllID()\n{\n    string folderName = @"c:\IDFolder";\n    string fileName = "ID0";\n    string formatFile = ".txt";\n    IList<ID> IDs = new List<ID>();\n\n    for (int i = 0; i < 9; i++)\n    {\n        string indexFile = (i + 1).ToString();\n\n        string filePath = folderName + "\\" + fileName + indexFile + formatFile;\n\n        if (File.Exists(filePath))\n        {\n            string[] result = File.ReadAllLines(filePath);\n            ID id = new ID();\n            id.id = result[0];\n            id.UserName = result[1];\n            id.Password = result[2];\n            id.Bla1 = result[3];\n            id.Bla2 = result[4];\n\n            // add id into IDs\n            IDs.Add(id);\n        }\n     }\n     return IDs;\n}	0
12820996	12820204	Dynamically Get File Names In a Folder in my website server ( ftp )	void GetFiles()\n        {\n            DirectoryInfo d= new DirectoryInfo(strFolderPath);\n            var files = d.GetFiles("*.pdf*");\n            FileInfo[] subfileInfo = files.ToArray<FileInfo>();\n\n            if (subfileInfo.Length > 0)\n            {\n                for (int j = 0; j < subfileInfo.Length; j++)\n                {\n                    bool isHidden = ((File.GetAttributes(subfileInfo[j].FullName) & FileAttributes.Hidden) == FileAttributes.Hidden);\n                    if (!isHidden)\n                    {\n                        string strExtention = th.GetExtension(subfileInfo[j].FullName);\n                        if (strExtention.Contains("pdf"))\n                        {                            \n                            string path = subfileInfo[j].FullName;\n                            string name = bfileInfo[j].Name;                           \n                        }\n                    }\n                }\n            }	0
13940380	13940256	Process Linq groups all at once	Dim result = (From i In DataList\n             Group i By date = i.MyDate Into g\n             Select WorkingClass.ReturnData(date, g.Select(Function(gi) gi.MyInfo).ToList())).ToList()	0
28336348	28336014	Get autoplayed file path (file with arbitrary extension)	private void Form1_Load(object sender, EventArgs e)\n    {\n        string[] fileS = Environment.GetCommandLineArgs();\n        MessageBox.Show(fileS[1]);\n    }	0
10743592	10737526	Programmatically set Toolpart layout	[ToolboxItemAttribute(false), WebBrowsable(true), WebDescription("Set the list name to use."), WebDisplayName("List Name"), Personalizable(PersonalizationScope.User)]\npublic string ListName{ \n    get{return customListName;}\n    set{customListName = value;}\n}	0
4780655	4780623	Creating an interface to have a generic List object	public class ConcreteWrapper : IServiceWrapper<HighLevelConversionData>\n{\n    public int StatusCode {get;set;}\n    public string StatusMessage { get; set; }\n    public List<HighLevelConversionData> ReturnedData { get; set;}\n}\n\npublic class HighLevelConversionData\n{\n    public int customerID {get;set;}\n    public string customerName {get;set;}\n    public decimal amountSpent {get;set;}\n}\n\npublic interface IServiceWrapper<T>\n{\n    int StatusCode { get; set; }\n    string StatusMessage { get; set; }\n    List<T> ReturnedData { get; set;}\n}	0
23359339	23352007	How to write to a dynamical number of Textboxes?	this.Controls.OfType<TextBox>().ToList<TextBox>().ForEach(tb => tb.Text = "bla bla");	0
34314936	34261860	makefile recipe failed when started as a C# process	featureExtractionProcess.StartInfo.RedirectStandardError = true;	0
6534625	6534459	Set focus on date field in DateTimePicker control in Windows form	dateTimePicker1.GotFocus += new EventHandler(dateTimePicker1_GotFocus);\n\nvoid dateTimePicker1_GotFocus(object sender, EventArgs e)\n{\n    SendKeys.Send("{RIGHT 1}");\n}	0
3188768	3188672	How to elegantly check if a number is within a range?	int x = 30;\nif (Enumerable.Range(1,100).Contains(x))\n    //true\n\nif (x >= 1 && x <= 100)\n    //true	0
24737795	24737708	C# Display a TextBox for a few seconds	Timer t = new Timer();\nt.Interval = 1000;\ntimer1.Enabled = true;\ntimer1.Tick += new System.EventHandler(OnTimerEvent);	0
27346992	27346523	How to add parameter to method and to overrides in child classes	Alt+Enter	0
33064773	33064716	Index was outside the bounds of the array in - C#	string[] sql = line.Split(' ');\n\ndynamic id = sql[0];\ndynamic username = sql[1];\ndynamic email = sql[2];\ndynamic password = sql.Length >= 4 ? sql[3] : null;\ndynamic plainPassword = sql.Length == 5 ? sql[4] : null;	0
22255310	22254479	Xamarin C# EditText InputType Password	editText.InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText;	0
5397118	5397027	how can i store and reuse pieces of my lambda expressions	Expression<Func<User, bool>> KeysMatch = \n    map => map.User.Key == _users.PublicUser.Key \n        || map.User.Key == _users.CurrentUser.Key;\n\nSession.Query<DimensionGroup>()(dimgroup=>(\n    dimgroup.Users.Where(KeysMatch)\n    .Where(map => map.AccessLevel.ToAccessLevel() == AccessLevel.Write))\n    .Count() > 0\n));	0
12351023	12339588	Chaining WCF Async Methods in Silverlight	NewUser newUser = new NewUser();\nnewUser.Show();\nnewUser.Closed += (object sender, EventArgs e) =>\n{\n    player = new Player\n    {\n        PlayerName = newUser.txtPlayerName.Text,\n    };\n\n    // you aren't going to be able to catch timeout\n    // errors in async method calls\n    client.GetTableListAsync();\n\n    // we can initiate login even if TableList isn't loaded yet\n    client.LoginAsync(player.PlayerName);\n    client.LoginCompleted += (s2, e2) => {\n        // publish player logged in\n        client.PublishAsync(String.Format("{0} is logged in", player.PlayerName));\n    }\n}	0
18882264	18881919	Parsing a piece of html code as an XDocument?	var reader = new XmlTextReader("path/to/myHtmlFile.html");\nwhile (reader.Read())\n{\n  // Keep reading until we hit an element called iframe\n  if (reader.NodeType == XmlNodeType.Element && reader.Name == "iframe")\n  {\n    while (reader.MoveToNextAttribute())\n    {\n      // Keep moving to the next attribute until we hit one called src\n      if (reader.Name == "src")\n      {\n        return reader.Value;\n      }\n    }\n  }\n}	0
20441791	20441599	ListPicker, how to get the text from the selected item?	var content = ((ListPickerItem)EncodingList.SelectedItem).Content;	0
3284296	3284240	Compare two arrays or arraylists, find similar and different values	var onlyinfirst = from s in list1 where !list2.Contains(s) select s;\nvar onlyinsecond = from s in list2 where !list1.Contains(s) select s;\nvar onboth = from s in list1 where list2.Contains(s) select s;	0
7081752	7077461	via Win32 API how would you get the value of a class of SysListView32	VirtualAllocEx\nWriteProcessMemory to initlize LVITEM\nSendMessage(hwnd, LVM_GETITEM, WPARAM, LPARAM)\nReadProcessMemory\nVirtualFreeEx	0
30047957	30047798	Run javascript on aspx page after clicking a button with actual values	chart = new Dygraph(\n    document.getElementById(""MainContent_DivDiagramm""), \n    'http://webserver/test/Data/" + authuser + @"_data.csv?v=" + DateTime.Now.Ticks.ToString() + "');"	0
1956117	1955422	Running a command line program from within c#?	Process myProcess = new Process();\n\nmyProcess.StartInfo.FileName = "MyProgram.exe";\nmyProcess.StartInfo.Arguments = "1st_argument 2nd_argument" \nmyProcess.StartInfo.CreateNoWindow = false;\n\ntry\n{\n    myProcess.Start();\n    myProcess.WaitForExit();\n}	0
23260552	23257662	how to change MediaElement source when ListPicker_SelectionChanged?	private void ListPicker_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e){\n\nListPickerItem item = lp_sound.SelectedItem as ListPickerItem;\n\nif(item!=null)\n   bleep.Source = new Uri(Convert.ToString(item.Tag), UriKind.Relative);\n}	0
28490607	28490200	StackOverFlowException inside a recursive function	public ICollection<MenuItem> GetMenuItemsAsTreeList()\n    {\n        AllMenuItems = entityContext.MenuItemSet.ToList();\n\n        Dictionary<int, MenuItem> dic = AllMenuItems.ToDictionary(n => n.Id, n => n);\n\n        List<MenuItem> rootMenuItems = new List<MenuItem>();\n\n        foreach (MenuItem menuItem in AllMenuItems)\n        {\n            if (menuItem.ParentMenuItemId.HasValue)\n            {\n                MenuItem parent = dic[menuItem.ParentMenuItemId.Value];\n                menuItem.ParentMenuItem = parent;\n                parent.SubMenuItems.Add(menuItem);\n            }\n            else\n            {\n                rootMenuItems.Add(menuItem);\n            }\n        }\n\n        return rootMenuItems;\n    }	0
16916847	16916614	C# issue with oledb connection string for excel	string path = @"c:\test\abc.xlsx";	0
15115424	15115409	Make object that encapsulates List<> accessable via [] operator?	public SomeType this[int index] {\n    get { }\n    set { }\n}	0
31977008	31976424	How to determine how big array is and then display all the information inside?	Console.WriteLine("Enter the size of the array");\n        int number = int.Parse(Console.ReadLine());\n        int[] marks = new int[number];\n        for (int i = 0; i < marks.Length; i++)\n        {\n            Console.WriteLine("Enter some more numbers", i + 1);\n            marks[i] = int.Parse(Console.ReadLine());\n        }\n        for (int i = 0; i < marks.Length; i++)\n        {\n            Console.WriteLine("\nData #{0}: {1}\n", i + 1, marks[i]);\n        }	0
11794249	11794184	Linq to SQL valid Email Address in a where clause	var contacts = db.Contacts\n    .Where(cont.Accounts_CustomerID == accountId)\n    .Select(cont => new ContactLight\n                    {\n                        AccountId = cont.Accounts_CustomerID,\n                        FirstName = cont.Firstname,\n                        LastName = cont.Lastname,\n                        EmailAddress = cont.EmailAddress\n                    })\n    .AsEnumerable() //this forces request to client side\n    .Where(e => ValidEmail(e.EmailAddress));	0
2820181	2820141	StringFormat Double without rounding	double d = toDateTime.SelectedDateTime.Subtract(servicefromDateTime.SelectedDateTime).TotalHours; \n\nstring s = String.Format("{0:0}", Math.Truncate(d));	0
19483390	19483282	VS2012 equivalent of Eclipse's default Ctrl-Shift-O?	Edit / IntelliSense / Organize Usings	0
12163876	12163855	How to remove an element from an IGrouping	IGrouping<,>	0
23167034	23166581	Unable to fill data grid view dynamically using stored procedure	int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());\n    //int idc = 100;\n    DataSet ptDataset = new DataSet();\n    string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString(); \n    SqlConnection sqlCon = new SqlConnection(con);\n    sqlCon.Open();\n    SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);\n    sqlCmd.CommandType = CommandType.StoredProcedure;\n    sqlCmd.Parameters.AddWithValue("@id", id);\n    SqlDataAdapter da = new SqlDataAdapter(sqlCmd);\n    da.Fill(ptDataset);\n    dataGridView2.DataSource =  ptDataset.Tables[0];\n    sqlCon.Close();	0
9689758	9649475	HTTPOnly sets cookie expiration to session	FormsAuthenticationTicket ticket = new FormsAuthenticationTicket\n                                                (strUserID, //name\n                                                 false, //IsPersistent\n                                                 24 * 60); // 24 hours\n\n// Encrypt the ticket.\nstring encryTicket = FormsAuthentication.Encrypt(ticket);\n\n// Create the cookie.\nHttpCookie userCookie = new HttpCookie("Authentication", encryTicket);\nuserCookie.HttpOnly = true;\nResponse.Cookies.Add(userCookie);\n\ne.Authenticated = true;\nif (LoginPannelMain.RememberMeSet)\n{\n    HttpCookie aCookie = new HttpCookie("email", strUserLogin);\n    aCookie.HttpOnly = true;\n    aCookie.Expires = DateTime.Now.AddYears(1);\n    Response.AppendCookie(aCookie);\n}\nelse\n{\n    HttpCookie aCookie = new HttpCookie("email", "");\n    aCookie.HttpOnly = true;\n    Response.AppendCookie(aCookie);\n}	0
8992487	7265857	How can i grab pRgb32 image buffer from BitmapSource or PlanarImage (from Kinect)?	for (int i = 0; i < myBits.Length; i+=4)\n{\n    myBits[i+3] = myBits[i+2];\n    myBits[i+2] = myBits[i+1];\n    myBits[i+1] = myBits[i];\n    myBits[i] = 255;\n}	0
10455471	10454024	resolution independent grid for animations?	Pos *= NewResolutionSize/DefaultResolutionSize;	0
9185688	9185654	Datatable to XML using LINQ	table.AsEumerable().Select(row =>\n    new XElement("row",\n        table.Columns.Cast<DataColumn>().Select(col =>\n            new XAttribute(col.ColumnName, row[col])\n        )\n    )\n)	0
19899589	19826208	How do I load a CSS file with HTMLTextWriter	writer.AddAttribute(HtmlTextWriterAttribute.Href, "/stdtheme.css");\nwriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");\nwriter.RenderBeginTag(HtmlTextWriterTag.Link);	0
381420	381401	How do you compare DateTime objects using a specified tolerance in C#?	if((myDate - myOtherDate) > TimeSpan.FromSeconds(10))\n{\n   //Do something here\n}	0
27873588	27873562	How to convert a string to code? (C#)	string foo = "bar";\n     var resources = Project.Properties.Resources;\n     object o = resources.GetType().GetProperty(foo).GetValue(resources, null);\n     if (o is System.Drawing.Image) {\n            pictureBox.Image = (System.Drawing.Image) o;\n     }	0
6301911	6301883	Getting a .Net application to close on crash	Application.ThreadException	0
26605918	26605116	Query base entity to retrieve all derived entity's data using Linq to Entities	var q1 = from p in db.Persons\n         select new PartyViewModel {\n           Id = p.Id,\n           FirstName = p.FirstName,\n           LastName = p.LastName,\n           Name = null\n         };\nvar q2 = from o in db.Organizations\n         select new PartyViewModel {\n           Id = o.Id,\n           FirstName = null,\n           LastName = null,\n           Name = o.Name\n         };\n\nvar vm = q1.Union(q2).ToList();	0
14141309	14141066	Getting current MachineKey, or equivilent, for HMAC (in web-farm)	MachineKeySection section = (MachineKeySection) \n  ConfigurationManager.GetSection ("system.web/machineKey");	0
30766689	30766599	Select all images in the folder and save them in other folder	var filesToCopy = Directory.EnumerateFiles(@"c:\path to images", "*.jpeg");\n\nvar directoryToCopyTo = "c:\destination folder";\n\nforeach (var file in filesToCopy)\n{\n    File.Copy(file, Path.Combine(directoryToCopyTo, Path.GetFileName(file)));\n}	0
6151431	6046577	Inserting multiple records into MySQL using MySqlCommand in one query C# (MySQLConnector) & command Parameters for escaping quotes	public static string MySqlEscape(object value)\n{\n    string val = value.ToString();\n    if (val.Contains("'"))\n        return val.Replace("'", "''");\n    else\n        return val;\n}	0
9765241	9765231	How to find substring in list of strings using LINQ	collection.FirstOrDefault(s => s.StartsWith(whatever))	0
15995168	15995090	How retrieve number of last key pressed?	private void Form1_KeyUp(object sender, KeyEventArgs e)\n{\n    string pressedKey = e.KeyData.ToString();\n\n    if (pressedKey.StartsWith("D")) \n    { \n        pressedKey = pressedKey.Replace("D", "");\n        MessageBox.Show(pressedKey);\n    }\n\n    if (pressedKey.StartsWith("NumPad"))\n    { \n        pressedKey = pressedKey.Replace("NumPad", "");\n        MessageBox.Show(pressedKey);\n    }\n}	0
30016826	30016519	Use the return value in a thread	//* declare a delegate function\npublic delegate string SerialnoDlg();\n\n//* modify your Serialno this way\npublic string Serialno()\n{\n  if (this.InvokeRequired)\n  {\n    SerialnoDlg dlg = new SerialnoDlg(this.Serialno);\n    this.Invoke(dlg);\n    return String.Empty;\n  } \n  if (cbSerials.SelectedValue!=null)\n  {\n    string serial = cbSerials.SelectedValue.ToString();\n    return serial;\n  }\n  else\n  {\n    return String.Empty;\n  }\n}	0
27868508	27868486	How to break a do while loop?	do {\n    if (something)\n        break;\n}\nwhile (condition)	0
474196	474057	How to initialize an array through generics?	public static class Extenders\n{\n    public static T[] FillWith<T>( this T[] array, T value )\n    {\n        for(int i = 0; i < array.Length; i++)\n        {\n            array[i] = value;\n        }\n        return array;\n    }\n}\n\n// now you can do this...\nint[] array = new int[100];\narray.FillWith( 42 );	0
16093104	16091766	How to define model property for master detail	public ActionResult PostsByCategoryID(Guid Id)\n{\n\n  List<post> posts = ///get them by id\n\n return View(posts) ; //the view take list and displays the posts\n}	0
24041362	24041308	MS SQL OrderBy group of set criteria	order by\n case when x.Gender = 'f' and x.IsCouple = 0 then 1 else 0 end,\n x.ApplrovalRejectedDate desc,\n x.Id desc	0
34138913	34138823	Is there an access modifier that limits to a solution?	[assembly:InternalsVisibleTo("MainProject.Tests")]	0
5928963	5928947	How to resize a Data Grid View Column size	DataGridViewColumn column = dataGridView.Columns[0];\ncolumn.Width = 60;	0
17177298	17177240	Windows Within An App	window.ShowDialog()	0
12320995	12320537	how can I bind a complex class to a view, while preserving my custom validation attributes?	[HttpPost]\n    public ActionResult Create(User user)\n    {\n        if (TryValidateModel(user))\n        {\n            // creation code here\n            return RedirectToAction("Index");\n        }\n        else\n        {\n            return View(user);\n        }\n    }	0
32554982	32554958	How do i read a text files lines and remove the first line?	string[] files = File.ReadAllLines(userVideosDirectory + "\\UploadedVideoFiles.txt").Skip(1).ToArray();\nFile.WriteAllLines(userVideosDirectory + "\\UploadedVideoFiles.txt", files);	0
1105265	1105251	C# : how do you obtain a class' base class?	Type superClass = myClass.GetType().BaseType;	0
10688694	10688115	Large RegEx Match causing program hang	RegexOptions.Compiled	0
32343294	32341172	callback based async method with multiple parameters to awaitabletask	static Task<CompanyFile[]> DoWork()\n{\n    var tcs = new TaskCompletionSource<CompanyFile[]>();\n    Task.Run(async () =>\n    {\n        var cfsCloud = new CompanyFileService(_configurationCloud, null, _oAuthKeyService);\n        var files = await cfsCloud.GetRangeAsync();\n        tcs.SetResult(files);\n    });\n    return tcs.Task;\n}	0
13377038	13376982	Dynamic Serialization	public static string RemoveJsonNulls(this string str)\n    {\n        if (!str.IsEmptyOrNull())\n        {\n            Regex regex = new Regex(UtilityRegExp.JsonNullRegEx);\n            string data = regex.Replace(str, string.Empty);\n            regex = new Regex(UtilityRegExp.JsonNullArrayRegEx);\n            return regex.Replace(data, "[]");\n        }\n        return null;\n    }\n\npublic static string JsonNullRegEx = "[\"][a-zA-Z0-9_]*[\"]:null[ ]*[,]?";\n\npublic static string JsonNullArrayRegEx = "\\[( *null *,? *)*]";	0
14202985	14202902	XML Documentation for many Constants	/// <summary>Some content</summary>\npublic static int  UTIL_SUCCESS         = 0;	0
32697039	32696925	How to create a loop using values from appSettings in my console application	string appSetting = ConfigurationManager.AppSettings["myPath"];\nstring[] paths = appSetting.Split[','];\nforeach(string path in paths){\n   //Check if file exists by appending the file name to end of path \n   //and attempting to open the file\n   //If successful return path, if not return null\n}	0
8293927	8293473	Setting a default value on form start for DomainUpDown Control	DomainUpDown dd = new DomainUpDown();\n    dd.Items.Add("settings");\n    dd.Items.Add("Reading");\n    dd.SelectedIndex = 0; // this will make sure you get the first item selected	0
2876260	2876159	I am using mysql stored-procedure.My SP return dataset ,how to bind the value into crystal report	ReportObject.SetDataSource (dsYourDataSource);\nCrystalReportViewer1.ReportSource = ReportObject;	0
15661202	15550234	Print button not visible in ReportViewer	ReportPrintDocument rp = new ReportPrintDocument(ReportViewer1.ServerReport);\n  rp.Print();	0
15762730	15762642	Writing/Parsing library for CSV with unknown number of columns	new StringReader(line)	0
20661827	20661680	Read a Text File skipping Lines that has a TAB Character in them	DialogResult result = open_dialog.ShowDialog();\nif (result == DialogResult.OK) {\n    StreamReader sr = new StreamReader(open_dialog.FileName);\n\n    StringBuilder() sb = new StringBuilder();\n\n    // Don't set the rich_words.Text = data here because there's no need to.\n\n    string line;\n    using (var file = File.OpenText(dialog.FileName)) {\n        while ((line == file.ReadLine()) != null) {\n            if (!line.Contains('\t')) {\n                sb.AppendLine(line);\n            }\n            // No need to have an else since we only want to do stuff when the line does not contain a tab.\n        }\n    }\n\n    // Now that you have all of the text from the file into your StringBuilder, you add it as the text in the box.\n    rickbox.Text = sb.ToString();\n}	0
3038589	3034986	How to set a default value with Html.TextBoxFor?	[AcceptVerbs(HttpVerbs.Get)]\npublic ViewResult Create()\n{\n  // Loads default values\n  Instructor i = new Instructor();\n  return View("Create", i);\n}\n\n[AcceptVerbs(HttpVerbs.Get)]\npublic ViewResult Create()\n{\n  // Does not load default values from instructor\n  return View("Create");\n}	0
1885977	1885728	Textbox related Question: Validating Like it was a DatagridView Cell	private void textBox1_Leave(object sender, EventArgs e)\n    {\n        Int32 original_value = Convert.ToInt32(textBox1.Text);\n        textBox1.Text = Format(original_value).ToString();\n        //original_value still holds the value that the user entered.\n        //textbox holds the formated value.\n\n    }\n    public int Format(int a)\n    {\n        //code to format your input value\n        return a;\n    }	0
1565733	1565708	C# Dynamic Type in a GenericCollection Property	public IList myCollection { get; set; }	0
24054192	24052372	Deserialize HTTP POST Parameters	var data = new StreamReader(input).ReadToEnd();\n                var dataNvc = HttpUtility.ParseQueryString(data);\n                var dataCollection = dataNvc.AllKeys.ToDictionary(o => o, o => dataNvc[o]);\n                var jsonString = JsonConvert.SerializeObject(dataCollection);\n                var answerRequest = JsonConvert.DeserializeObject<LogHandler.AnswerRequest>(jsonString);	0
3036880	3036829	How to create a message box with "Yes", "No" choices and a DialogResult in C#?	DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);\nif(dialogResult == DialogResult.Yes)\n{\n    //do something\n}\nelse if (dialogResult == DialogResult.No)\n{\n    //do something else\n}	0
549097	548962	Data Binding - C#	if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {\n    // User picked a path and didn't cancel the dialog...\n    textBox1.Text = folderBrowserDialog1.SelectedPath;\n  }	0
7662974	7662589	filter a list of strings in C#	//grab all possible pairings in one data structure\n        List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();\n        string[] list = { "acks", "top", "cat", "gr", "by", "bar", "lap", "st", "ely", "ades" };\n        foreach (string first in list)\n        {\n            foreach (string second in list)\n            {\n                pairs.Add(new KeyValuePair<string, string>(first, second));\n            }\n        }\n\n        //test each pairing for length and whatever else you want really\n        List<string> sixLetterWords = new List<string>();\n        foreach (KeyValuePair<string, string> pair in pairs)\n        {\n            string testWord = pair.Key + pair.Value;\n            if (testWord.Length == 6)\n            {\n                sixLetterWords.Add(testWord);\n            }\n        }	0
21813753	21813694	How convert a List<string> to one long string?	string combindedString = string.Join(Environment.NewLine, newText);	0
16400440	16399713	Save attach of attached mail	if (attachment.ContentType == ContentType.MessageRfc822)\n{\n    string eml = ((MimeText)attachment).Text;\n    IMail attachedMessage = new MailBuilder().CreateFromEml(eml);\n    // process further\n}	0
21721077	21720294	LINQ version of SQL with left join and group by	var result = (from t1 in table1 \n                      join t2 in table2 on t1.id equals t2.itemId\n                     into t2d from td in t2d.DefaultIfEmpty()\n                     group t1 by t1.item into t1g select new {item=t1g.key, sum =t1g.Sum(p=>p.price??0)} ).ToList();	0
31684977	31684796	C#: Build 3D-Array and fill it with data	private static List<List<List<int>>> threeDArrayToThreeDList(int [,,] letters) {\n    // 3d-array to 3d-list\n    List<List<List<int>>> letterslist = new List<List<List<int>>>();\n\n    for (int i = 0; i < 2; i++) {\n        letterslist.Add (new List<List<int>> ());\n        for (int j = 0; j < 2; j++) {\n            letterslist[i].Add (new List<int> ());\n            for (int k = 0; k < 2; k++) {\n                Console.WriteLine (letters [i,j,k]);\n                letterslist [i] [j].Add(letters [i,j,k]);\n            }\n        }\n    }\n    return letterslist;\n}	0
8020735	8018901	How to insist that a textbox has a value	private void textBox1_Validating(object sender, CancelEventArgs e)\n    {\n        double doubleresult = 0;\n\n        bool result = Double.TryParse(textBox1.Text, out doubleresult);\n\n        if (result)\n        {\n            errorProvider1.SetError(textBox1, string.Empty);\n        }\n        else\n        {\n            errorProvider1.SetError(textBox1, "Must be a Double");\n            e.Cancel = true;\n        }\n    }	0
19779309	19779036	How to convert a IEnumerable to Dictionary	MyObjectCollection.ToDictionary(x=>makeStructFromMyObject(x), x=>x);\n\n\n//... with...\n\nprivate MyStruct makeStructFromMyObject(MyObject obj)\n{\n   //to be implemented by you\n}	0
16057570	16057508	How to enumerate a list in portions (to avoid OutOfMemoryException)?	int batchSize = 1000;\n\nvar lotsOfItems = Enumerable.Range(0, 10000000);\nvar batched = lotsOfItems.Batch(batchSize); \n\nforeach (var batch in batched)\n{\n    //handle each batch\n}	0
24140149	24139749	Change Xml value with XElement (with specified Attributes)	XDocument xDoc = XDocument.Load("file.xml");\n\n        XElement result = xDoc.Descendants("InstanceInfos")\n            .Where(x => x.Attribute("Name")\n                .Value == "i-82c61ac1")\n            .Descendants()\n            .SingleOrDefault();\n\n        result.Value = "Foo";\n\n        xDoc.Save("file.xml");	0
18728834	18728742	Parsing JSON into Object	Course[] courses = JsonConvert.DeserializeObject<Course[]>(returnjson);	0
15417079	15416607	How Run Two Operations concurrently in C#	private BackgroundWorker bw = new BackgroundWorker();\n\nbw.WorkerReportsProgress = true;\nbw.WorkerSupportsCancellation = true;\nbw.DoWork += new DoWorkEventHandler(bw_DoWork);\nbw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);\nbw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);\n\nprivate void bw_DoWork(object sender, DoWorkEventArgs e)\n{\n//load data from database\nSystem.Threading.Thread.Sleep(1);\nworker.ReportProgress(progressbar_value);\n}\n\nprivate void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\nProgress.value= progressbar_value;\n}\n\nprivate void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n//progress completed\n}	0
7846984	7841452	DevExpress gridView - trigger javascript alert from onRowInserted event	protected void Grid_RowInsertedEvent(object sender, ASPxDataInsertedEventArgs e) \n{\n    JSProperties["cp_RowInserted"] = true;\n    ...\n}\n\n// I prefer this in grid's Init event handler but you can place it in \n// RowInserted as well\nClientSideEvents.EndCallback = \n    @"function(s,e)\n    {\n        if(s.cp_RowInserted!=null)\n        {\n            alert('row inserted');\n            s.cp_RowInserted=null;\n        }\n    };";	0
4932565	4932535	How do I add a namespace when creating an XML file?	root.SetAttribute("noNamespaceSchemaLocation", \n    "http://www.w3.org/2001/XMLSchema-instance", \n    "valuations.xsd"\n);	0
26708875	26505504	In grid view row deleting	SqlConnection con=newSqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());\n      con.Open();\n      int Sno = Convert.ToInt32(grd.DataKeys[e.RowIndex].Values[0].ToString());\n      string query="delete from Details where Sno="+Sno;\n      SqlCommand cmd = new SqlCommand(query, con);\n      int result = cmd.ExecuteNonQuery();\n      con.Close();	0
16421168	16420861	Find textblock in code to manipulate color	ListBoxItem l = lbDagprogrammaInfo.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;\nBorder b = VisualTreeHelper.GetChild(l, 0) as Border;\nContentControl c = VisualTreeHelper.GetChild(b, 0) as ContentControl;\nContentPresenter p = VisualTreeHelper.GetChild(c, 0) as ContentPresenter;\nStackPanel s = VisualTreeHelper.GetChild(p, 0) as StackPanel;\nTextBlock t = s.FindName("txtVeranderkleur") as TextBlock;	0
10324370	10320493	Trying to get Win32_BIOS version by using a path string	Win32_BIOS.Name="Ver 1.00 BIOS A05 PARTTBL",SoftwareElementID="Ver 1.00 BIOS A05 PARTTBL",SoftwareElementState=3,TargetOperatingSystem=0,Version="DELL   - 6040000"	0
32165743	32165673	C# List<Item> parent child relation, order items alphabetically	void SortRecursively(List<Item> items) {\n  foreach (var item in items) {\n    item.Items = item.Items.OrderBy(i => i.Title).ToList();\n    SortRecursively(item.Items);\n  }\n}	0
4054851	4054824	WriteLine on Console but in Retro Style	public static void WriteSlow(string txt) {\n        foreach (char ch in txt) {\n            Console.Write(ch);\n            System.Threading.Thread.Sleep(50);\n        }\n    }	0
437213	437180	Read single value from query result	int result = 0;\nusing(SqlConnection conn = new SqlConnection(connectionString))\n{\n    conn.Open();\n    SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM test", conn);\n    result = (int)sql.ExecuteScalar();\n}	0
1970957	1970940	Problems using a StringBuilder to construct HTML in C#	builder.AppendFormat("<a href='#' onclick=\"foo('{0}','{1}')\">{2}</a>", var1, var2, var3);	0
22055756	22032857	EF4.4 how to set StoreWins on request, rather than separate refresh?	var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;\n\nvar query = objectContext.CreateObjectSet<SomeModel>()\n       .Where(x => x.Blah);\n\n((ObjectQuery)query).MergeOption = MergeOption.OverwriteChanges;\n\nreturn query.ToList();	0
7272099	7271980	any easy way to check if no items has been selected in a checkboxlist control?	CheckBoxList list = new CheckBoxList();\n if (list.SelectedIndex == -1)\n {\n      //Nothing is selected\n }	0
10161643	10161598	How can I replace a string with this rules?	// Remove all accents\nvar bytes = Encoding.GetEncoding("Cyrillic").GetBytes(text);\ntext = Encoding.ASCII.GetString(bytes);\n\n// Remove all unwanted characters\nvar regex = new Regex("[^a-zA-Z0-9-]");\ntext = regex.Replace(text, "");	0
3939901	3939760	Determine if DateTime is in a given Date Range	e.g\n     switch (month)\n     {\n       case 1:\n          if (day <20) return "Capricorn"; else return "Aquarius";\n          break;\n       case 2:\n          ...	0
29225876	29162361	Why does SqlDataAdapter's fill not allow me to add a row with the same its own rows' value as appearance?	DataTable t = new DataTable();\na.Fill(t);\n\nDataColumn newCol = new DataColumn("NewColumn", typeof(string));\nnewCol.AllowDBNull = true;\nt.Columns.Add(newCol);\nforeach (DataRow row in t.Rows)\n{\n     row["NewColumn"] = "With String";\n}\ndataGridView1.DataSource = t;	0
8495733	8494307	How can I change the outmost tag of bare XML in WCF?	[CollectionDataContract(ItemName="element", Name = "elementCollection")]\n    public class DataResponse<T> : List<T>\n    {\n        public DataResponse() : base()\n        {\n        }\n\n        public DataResponse(List<T> list) : base()\n        {\n            this.AddRange(list);        \n        }\n    }	0
9304277	9304067	How to count efficiently using C# and XML?	XDocument doc = XDocument.Parse(xml);\n\n  int heightCount = 0;\n  int widthCount = 0;\n  int priceCount = 0;\n\n  int heightThreshold = 3;\n  int widthThreshold = 1;\n  int priceThreshold = 1;\n\n  foreach (var product in doc.Descendants("product"))\n  {\n    int height = Convert.ToInt32(product.Element("H").Value);\n    int width = Convert.ToInt32(product.Element("W").Value);\n    int price = Convert.ToInt32(product.Element("P").Value);\n\n    if (height < heightThreshold)\n    {\n      heightCount++;\n    }\n\n    if (width < widthThreshold)\n    {\n      widthCount++;\n    }\n\n    if (price < priceThreshold)\n    {\n      priceCount++;\n    }       \n  }	0
10307841	10307665	Attaching a SQL server express database with WCF service application	SqlConnection conn = new SqlConnection(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Database1.mdf;User Instance=true");	0
683346	683330	How to make a window always stay on top in .Net?	Form.TopMost	0
4174056	4173982	C# How to get current URL from the IE?	foreach (InternetExplorer ie in new ShellWindows()) {\n            //...\n        }	0
22181851	22181515	Convert php to c#	SHA1 sha = new SHA1CryptoServiceProvider();\n        var resulta = sha.ComputeHash(new ASCIIEncoding().GetBytes("password"));\n        var resultb = sha.ComputeHash(resulta);\n\n        return "*" + BitConverter.ToString(resultb).Replace("-","");	0
19119678	19119591	Interface with multiple implementations in ninject	Bind<IProducer>().To<FaultProducer>().Named("FaultProducer");\n\npublic TradePublisher([Named("FaultProducer")] IProducer producer)\n    //...\n}	0
1527477	1527445	How do I create an array containing indexes matching a criteria?	int[] MagicFunction(string[] args)\n{\n    return args.Select((s, i) => new { Value = s, Index = i }) // Associate an index to each item\n               .Where(o => o.Value.StartsWith("-"))            // Filter the values\n               .Select(o => o.Index)                           // Select the index\n               .ToArray();                                     // Convert to array\n}	0
2331709	2331698	C# Array Merge Without Dupes	string[] arr1 = new string[2]{"Hello", "Stack"};\nstring[] arr2 = new string[2] { "Stack", "Overflow" };\n\nvar arr3 = arr1.Union(arr2).ToArray<string>();	0
8879472	8879455	Add Role attribute to MVC3 methods only in Release mode?	#if !DEBUG\n[Authorize(Roles="Admin")]\n#endif	0
16280766	16235512	Loading url with pdf in monodroid webview	PodWebView.LoadUrl ("http://docs.google.com/viewer?url=" + PodUrl);	0
23336748	23336648	Get string form XML file by attribute	var xml = XDocument.Parse(yourxmlstring, LoadOptions.None);\nvar resources= xml.Descendants("resources");\nforeach (var resourceElement in resources.Descendants("Hotel"))\n{\n    MessageBox.Show(resourceElement.Attribute("name").Value);\n}	0
5910643	5910432	C#: retrieve the first n records from a database	DataTable GetTopN(int n, DataTable content)\n{\n    DataTable dtNew = content.Clone();\n    if (n > content.Rows.Count)\n        n = content.Rows.Count;\n\n    for(int i=0; i<n; i++)\n    {\n        dtNew.ImportRow(content.Rows[i]);\n    }\n}	0
3187706	3187678	Convert decimal coordinates to Degrees, Minutes & Seconds by c#	double coord = 59.345235;\nint sec = (int)Math.Round(coord * 3600);\nint deg = sec / 3600;\nsec = Math.Abs(sec % 3600);\nint min = sec / 60;\nsec %= 60;	0
5627444	5627371	How do you use Moq to mock a simple interface?	Mock<IVendorBriefRepository> mock = new Mock<IVendorBriefRepository>();\n\nVendorBriefController controller = new VendorBriefController(mock.Object);\n\nVendorBrief brief = new VendorBrief();\n\ncontroller.DeleteVendorBrief(brief);\n\nmock.Verify(f=>f.DeleteVendorBrief(brief));\nmock.Verify(f=>f.SaveChanges());	0
1092082	1092067	Method has to be overriden but isn't abstract?	public void DoSomething() {\n    //things to do before\n    DoSomethingCore();\n    //things to do after\n}\nprotected abstract void DoSomethingCore();	0
22353663	22352972	How to unit test a class that depends on a class with a MASSIVE public interface?	using NSubstitute;\nvar substitutedWSUS = Substitute.For<IWSUSInterface>();	0
26441449	26368843	Can attributes implement an interface?	System.Attribute	0
186973	185648	Dispose of Image in WPF in Listbox (memory leak)	MyObject obj = new MyObject();\nobj.TheEvent += new EventHandler(MyHandler);\nobj = null;\n// Now you might think that obj is set for collection but it \n// (probably - I don't have access to MS' .NET source code) isn't \n// since we're still listening to events from it.	0
12022908	12022865	How to modify an element in a Dictionary?	runningcount[city]++;	0
33734908	33734838	Value cannot be null, Parameter name: path	// TODO Handle an empty string, populate listview with disk drives\n    DirectoryInfo dirInfo = new DirectoryInfo(filepath);	0
15901110	15897719	C# PresentViewController to a viewcontroller in storyboard	var controller = Storyboard.InstantiateViewController("HomeViewController") as UIViewController;	0
19170226	19170050	Using the highest value from one list to sort the second list.	List<Student> students = new List<Student>();\n// populate the students list\n\n// Mark the student with the highest total as we find him.\nStudent highestTotalStudent = null;\nvar highestTotal = 0.0;\n\nforeach (var student in students)\n{\n    var tempTotal = 0.0;\n\n    for (var i = 0; i < resultSet[0].Fees.Length; i++)\n    {\n        tempTotal += student.Fees[i].Amount;\n    }\n\n    if (tempTotal > highestTotal)\n    {\n        // We have a new winner\n        highestTotal = tempTotal;\n        highestTotalStudent = student;\n    }\n}\n\n// Finally, remove the located student, and re-insert her at the top of the list\nstudents.Remove(highestTotalStudent);\nstudents.Insert(0, highestTotalStudent);	0
6501111	6500989	Deleting XML using a selected Xpath and a for loop	string nodeXPath = "your x path";\n\nXmlDocument document = new XmlDocument();\ndocument.Load(/*your file path*/);\n\nXmlNode node = document.SelectSingleNode(nodeXPath);\nnode.RemoveAll();\n\nXmlNode parentnode = node.ParentNode;\nparentnode.RemoveChild(node);\ndocument.Save("File Path");	0
1329074	1013486	Parsing FtpWebRequests ListDirectoryDetails Line	Regex regex = new Regex ( @"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$",\n    RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace );	0
5996673	5996349	adding parameter to SourceURL link	if (value != "")\n    {\n        string viewValue = value.Substring(0, value.IndexOf("|"));\n        string viewType = value.Substring(value.IndexOf("|") + 1);\n        UserType userType = summaryViewModel.SelectedUserType;\n\n        sSummaryViewModel.ReportFrame.SourceURL =\n            WebPathHelper.MapUrlFromRoot(\n                string.Format("Reporting/Summary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}&userType={4}",summaryViewModel.BeginDate, summaryViewModel.EndDate, viewValue,  viewType, userType));\n    }	0
11842139	11841132	Insert and update multi item into database in the same time	foreach(item in AllData)\n        {\n           using (StorageEntities context = new StorageEntities())\n           {\n         //Update  \n          if (Exist(datefa))\n            {\n            var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault\n                    (data => data.CustomerId == AllData .CustomerId );\n\n                    int? LastProductTotal = query.CustomerProducTtotal;\n                    query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;\n\n                }\n                //Insert \n                else\n                {\n                    _CustomerProductTbl = new CustomerProductTbl();\n                    _CustomerProductTbl.CustomerId = AllData ._CustomerId;\n                    _CustomerProductTbl.CustomerProductDateFa = AllData.datefa;\n                    ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);\n                }\n                ClsDataBase.Database.SaveChanges();\n            }\n         }	0
8620256	8620110	How to find RowID in Excel using c# in windows app?	string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);\nbook = app.Workbooks.Open(execPath + @"\..\..\Book1.xls", \n       Missing.Value, Missing.Value, Missing.Value, \n       Missing.Value, Missing.Value, Missing.Value, Missing.Value, \n       Missing.Value, Missing.Value, Missing.Value, Missing.Value, \n       Missing.Value, Missing.Value, Missing.Value);\nsheet = (Worksheet)book.Worksheets[1];\nrange = sheet.get_Range("A1", Missing.Value);	0
7926158	7926072	Generics in C#, Dictionary<TKey,TValue>	Dictionary<string,int>	0
7948718	7948660	ListBox insert from a dictionary and i need to get the value and the key seperate	textBox2.Text = listBox1.SelectedValue.ToString();	0
22911323	22911103	WPF control derived from Label: are custom properties (with DP) not using the setter?	public static readonly DependencyProperty StrProperty =\n    DependencyProperty.Register(\n        "Str", typeof(string), typeof(CustomLabel),\n        new PropertyMetadata(StrPropertyChanged));\n\nprivate static void StrPropertyChanged(\n    DependencyObject obj, DependencyPropertyChangedEventArgs e)\n{\n    var label = obj as CustomLabel;\n    var str = e.NewValue as string;\n    ...\n}	0
20885277	20884700	Findcontrol in Multiview nested in Formview	BindFormView(tableID);\n                FillEditLists();	0
25498362	25498339	How to pass parameter to IN in sql server	CREATE TYPE dbo.IdList AS TABLE (Id INT)\nGO\n\nDECLARE @Ids dbo.IdList \n\nINSERT INTO @Ids(Id)VALUES(200),(201)\n\nSELECT EmpId, Name, Salary\nFROM Employee\nWHERE EmpId IN (SELECT Id FROM @Ids)	0
17821634	17821557	validate date in an ASP.NET MVC application	string dateString = "21.12.1985 3:12:15";\nDateTime date;\nif (DateTime.TryParseExact(dateString,"d.M.yyyy h:mm:ss",null,DateTimeStyles.None, out date))\n    Console.WriteLine(date);\n    else\n        Console.WriteLine("Invalid date");	0
8893717	8893373	Automapper IList - Signature of the body and declaration in a method implementation do not match	Mapper.CreateMap<IList<Profession>, IList<ProfessionDTO>>();	0
14485798	14485760	How can I restrict rows in a linq query based on a field having at least one entry that matches a row in a string array?	var menuItems = _contentRepository.GetPk("01" + pk + "000")\n.OrderBy(m => m.Order)\n.Where(m => m.Roles.Split(",").Any(x => roles.Contains(x) || x == "All"))\n.Select(m => new Menu.Item\n{\n    PartitionKey = m.PartitionKey,\n    RowKey = m.RowKey,\n    Order = m.Order,\n    Title = m.Title,\n    Type = m.Type,\n    Link = m.Link,\n    TextLength = m.TextLength\n});	0
14586104	14586001	setting session variable timeout to unlimited	public class SessionValue \n{\n      public object Value { get;set; }\n      public DateTimeOffset ExpiresOn { get;set; }\n}	0
30099939	30099889	How to get count of days?	DateTime start = Convert.ToDateTime(txtStart.Text);\nDateTime end = Convert.ToDateTime(txtEnd.Text);\nTimeSpan datedifference = end.Subtract(start);\nint dateCount = datedifference.Days + 1;	0
3872771	3872734	How to reference JSON serialization in ClassLibrary?	System.Web.Extensions	0
13227294	13227255	Select a folder with the SaveFileDialog	DialogResult result = folderBrowserDialog1.ShowDialog();\nif( result == DialogResult.OK )\n{\n    string folderName = folderBrowserDialog1.SelectedPath;\n    //........\n}	0
10357503	10357462	Sortable BindingList bound to DataGridView with programmatic sort	dataGridView1.Sort(dataGridView.Columns[0],ListSortDirection.Ascending);	0
14738908	14717177	DoDragDrop interfering with bindingsource	private void listBox1_MouseDown(object sender, MouseEventArgs e)\n{\n    bindingSource1.Position = listBox1.SelectedIndex;\n    DoDragDrop(new object(), DragDropEffects.Move);\n}	0
7816014	7815930	SortedList Desc Order	class DescendedDateComparer : IComparer<DateTime>\n    {\n        public int Compare(DateTime x, DateTime y)\n        {\n            // use the default comparer to do the original comparison for datetimes\n            int ascendingResult = Comparer<DateTime>.Default.Compare(x, y);\n\n            // turn the result around\n            return 0 - ascendingResult;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        SortedList<DateTime, string> test = new SortedList<DateTime, string>(new DescendedDateComparer());\n    }	0
19941618	19941583	How to map one property to another using C#?	public string Email \n{\n   get\n   {\n      return this.Usename;\n   }\n   set\n   {\n      this.Username = value;\n   }\n}	0
23628816	23628741	How to check format of a string before feeding it to Convert.DateTime()	DateTime myDt;\n    bool parsed = DateTime.TryParseExact(date,"d/M/yyyy",null,out myDt);\n    if(parsed) DoSomething;	0
13275992	13275960	upgrading: how to remove a project reference	Solution::Remove(Project prj);	0
3504165	3501812	Run an executable present in Windows Path using C#	Environment.GetEnvironmentVariable("Path").Split(";")	0
14692269	14692201	Download file from proxy server using c#	WebProxy wp = new WebProxy("http://contoso", 80);	0
21403169	21184156	C# HttpClient PostAsync turns 204 into 404	WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);\nWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);	0
31192254	31192027	How to associate entities during seed with Entity Framework	var module1 = new Module() { Id = 1, ModuleName = "Contabilidad", FontAwesomeClass = "fa-ambulance" };\ncontext.Modulos.Add(module);\ncontext.ModulosPorUsuario.Add(new ModulosPorUsuario()\n{\n    Email = "companyadmin@xx.onmicrosoft.com",\n    Modules = new List<Module>(){module1, module2 etc...};\n});	0
11722374	11722345	how to calculate the file size in C#	FileInfo file = new FileInfo(uploadsDocumentPath + fileName);\nif(file.Length > 157286400)\n{\n      // Return error here.\n}	0
14306755	14302394	C# use true/false from MySql database to either continue or show error	if (rdr.HasRows)\n        {\n            while (rdr.Read()) //Make sure this is added or it won't work.\n            {\n                if (rdr.GetBoolean("ban"))\n                {\n                    ErrorSuspend.Text = "Uw licentie is verlopen of geblokkeerd.                      Contacteer uw verdeler om een nieuwe licentie te bekomen.";\n                    return;\n                }\n\n                else\n                {\n                    Login Login = new Login();\n                    this.Content = Login;\n                }\n            }\n        }\n        else\n        {\n            ErrorLN.Content = "Licentie of naam incorrect.";\n            return;\n        }\n    }	0
23978269	23978250	How to use Linq Query in Object Data Source?	group b by new {b.Field<int>("loan_code"), b.Field<int>("emp_num")}	0
27114013	27091739	Create a linq query that get all elements that are not referenced in an aditonal table	IQueryable<User> users = context.Users;\n\nvar results = users.Where(x => x.Id != userId &&\n                                           !users.Where(v => v.Id == userId)\n                                                 .SelectMany(v => v.Friends.Select(d => d.Id))\n                                                 .Any(e => e == x.Id))\n                                                 .Select(x=>new\n                                                                {\n                                                                    //your projection\n                                                                })\n                               .ToList();	0
14583909	14583874	Verbatim string literals v escape sequences	bool areSame = ReferenceEquals("c:\\somewhere", @"c:\somewhere"); // true	0
14734847	13701856	How do you configure Lucene in Sitecore to only index the latest version of an item on the master db?	public class IndexCrawler : DatabaseCrawler\n{\n    protected override void IndexVersion(Item item, Item latestVersion, Sitecore.Search.IndexUpdateContext context)\n    {\n        if (item.Versions.Count > 0 && item.Version.Number != latestVersion.Version.Number)\n            return;\n\n        base.IndexVersion(item, latestVersion, context);\n    }\n}	0
24980719	24980387	Make table with varying width per column keeping the overall width of table constant in gridview in asp.net	.imgclass\n{\nmax-width:120px;\nbackground-color:green;\noverflow:hidden;  \n}	0
10590787	10590554	WPF ListView Update list items values after new item is added (values change with time)	Insert(0, T item	0
13221289	13221226	How to wait for the thread to end before continuing with the program	thread1.Start();\nthread2.Start();\n\nthread1.Join();\nthread2.Join();\n\nConsole.WriteLine("Done");\nConsole.ReadKey(true);	0
19421813	19421664	Get folder depth from a virtual path	int res = -99;\nstring input = fullPath.Trim();\nif (input.Length > 0 && input.Contains(@"\"))\n{\n    if (input.Substring(input.Length - 1, 1) == @"\") input = input.Substring(0, input.Length - 1);\n    res = input.Split('\\').Length - 2;\n}\nreturn res;	0
26119353	26119091	passing data to dynamically created ascx user control	SquareEUA userControl = (SquareEUA)(Page.LoadControl("~/UserControl/SquareEUA.ascx"));	0
22207909	22207034	how to work with linq association, entity isn't available	var memberships = from m in  First5MembershipDB.aspnet_Membership\n                  join u in First5MembershipDB.aspnet_Users on m.UserId equals u.UserId\n                  from r in u.aspnet_Roles\n                  join a in First5MembershipDB.Applications on r.WebApplicationID equals a.ApplicationId	0
5944116	5943965	Dynamically updating the source of a DataTemplate	var list = new ObservableCollection<NoteToSelf>();\n    list.Add(new NoteToSelf { Transcription = "oh hi", Duration = "9001 seconds" });\n    list.Add(new NoteToSelf { Transcription = "fgsfds", Duration = "$Texas seconds" });\n    listBox1.ItemsSource = list;	0
27105154	27105117	ToString for list og longs	var dataAsString = string.Join(", ", myData.Select(s => s.ToString()));	0
4719044	4710064	Soft delete - ActiveRecord with Listeners	foreach (NHibernate.Cfg.Configuration cfg in ActiveRecordMediator.GetSessionFactoryHolder().GetAllConfigurations())\n        {\n            cfg.SetListener(ListenerType.Delete, new SoftDeleteListener());\n            cfg.AddAssembly(assem);\n        }	0
5449410	5449393	Lambda expressions - select operator	var result = arrNames.Where(i => String.Compare("M", i) <= 0)\n                     .OrderBy(i => i);	0
23115087	23114910	Change DataField Attribute in a Gridview dynamically	C#\nBoundField field = (BoundField)this.GridViewAllPeopleEditMode.Columns[0];\nfield.DataField = "To";\n\nVB\nDim field As BoundField = DirectCast(Me.GridViewAllPeopleEditMode.Columns(0), BoundField)\nfield.DataField = "To"	0
3957790	3957709	Howto clear a textfile without deleting file?	String path = "c:/file.ini";\n    using (var stream = new FileStream(path, FileMode.Truncate))\n    {\n        using (var writer = new StreamWriter(stream))\n        {\n            writer.Write("data");\n        }\n    }	0
23833982	23833205	Getting multiple substrings from single string C#	var repspl = mydata.Split(';').Select( x =>  new { Key = x.Split(',')[0], Value = x.Split(',')[1] });	0
27380386	27380221	How to check if Windows Modal Dialog is present using Selenium WebDriver	IAlert alert = driver.SwitchTo().Alert();\nalert.Accept();	0
7084054	7084034	how to Cast string to a given Enum	return (CRF_DB.CRF_Requirement.LevelEnum)Enum.Parse(\n  typeof(CRF_DB.CRF_Requirement.LevelEnum), \n  prop.Value.ToString());	0
8637851	8637844	Can I force descendants to have a parameterless constructor?	: base()	0
26538125	26538097	How to add entries from one Dictionary to another of different types?	// extension method\npublic static Dictionary<string, string> Combine(this Dictionary<string, string> strs, Dictionary<int, int> ints)\n{\n    foreach (var i in ints)\n    {\n        strs.Add(i.Key.ToString(), i.Value.ToString());\n    }\n    return strs;\n}\n\n// usage\nstrs = strs.Combine(ints);	0
16532483	16532384	Open and search website from code	Process.Start(\n     "http://www.wolframalpha.com/input/?i="\n     + HttpUtility.UrlEncode("x^2+y^2 = 1")\n     + "&dataset=");	0
1501545	1500253	Replace text using regular expressions in MS Word - C#	_wordApp.Selection.Find.ClearFormatting();\n_wordApp.Selection.Find.MatchWildcards = true;\n_wordApp.Selection.Find.Text = "<[0-9]{3}-[0-9]{2}-[0-9]{4}>"; // SSN with dashes.\n\n_wordApp.Selection.Find.Replacement.ClearFormatting();\n_wordApp.Selection.Find.Replacement.Text = "test";\n\n_wordApp.Selection.Find.ClearFormatting();\n_wordApp.Selection.Find.MatchWildcards = true;\n_wordApp.Selection.Find.Text = "<[0-9]{9}>"; // SSN without dashes.\n\n_wordApp.Selection.Find.Replacement.ClearFormatting();\n_wordApp.Selection.Find.Replacement.Text = "test";	0
13690901	13690708	Timer C# use in game development	class Something\n{\n    DateTime _myDateTime;\n    Timer _timer;\n\n    public Something()\n    {\n        _timer = new Timer();\n        _timer.Interval = 1000;\n        _timer.Tick += Timer_Tick;\n\n        _myDateTime = DateTime.Now;\n        _timer.Start();\n\n    }\n\n    void Timer_Tick(object sender, EventArgs e)\n    {\n        var diff = DateTime.Now.Subtract(_myDateTime);\n        this.textBox1.Text = diff.ToString();\n    }\n}	0
25043722	25043608	Taking a screenshot of the desktop in C#	bmpScreenCapture.Save(ms, ImageFormat.Png);	0
12915527	12915507	Linq to xml for loop terminating early and unexpectedly	foreach(var element in doc.Root.Elements("b").ToList())\n{\n    // Removed the pointless XElement.Parse call; it's cleaner just to create\n    // an element with the data you want.\n    element.ReplaceWith(new XElement("c", "fixed"));\n}	0
5810777	5810728	How to define what is the number of the elapsed timer?	int index = list.IndexOf(((System.Timers.Timer)sender));	0
17541823	17541378	Adding a new row in between the two rows of the datagridview c#	PPUTDG.Rows.Insert(rowIndex, count);	0
22728258	22728176	How to refresh gridview of one mdi child form on button click of another mdi child form	EditEmp e = new EditEmp();\ne.ShowDialog();\nBindGrid();	0
8047815	8047772	Hexa base digit and Decimal base digit at C#	int masked = original & 0xffff00;	0
32744774	32744713	override an enum with a custom enum in the inherited class	public abstract class Criteria<TEnum>\n   where TEnum : struct, IConvertable\n{\n     public T Field { get; set; }\n}\n\npublic class MyCriteria : Criteria<MyFieldsEnum>\n{\n   // No need to override Field\n}	0
1187464	1187458	Are there equivalents to "this" for static variables in c#	TypeName.staticVariableName	0
15487292	15486763	WebApi bind body to Json dictionary	{"key1": 4, "key2": 50, "key3": {"member1": "value"}}	0
4227318	4227247	Plotting dates versus numbers in ZedGraph and C#	myPane.XAxis.Type = AxisType.Date;	0
16475641	16475507	C#, Datagridview, SQL Server	try\n{\n  con.open(); \n  cmd=new SqlCommand("select * from purchaseTable where convert(nvarchar(11),dateCol)=convert(datetime,@dtpValue)",conn);\n  cmd.parameters.AddWithValue("@dtpValue",dtpDate.Value.Date.ToString("dd/MM/yyyy");\n  SqlDataAdapter adapter = new SqlDataAdapter(command);\n  DataSet ds = new DataSet();\n  adapter.Fill(dataset);\n  gv.DataSource=ds.Tables[0];\n  con.close();\n}\ncatch(Exception ex)\n{\n}\nfinally\n{\n  con.close();\n}	0
14718616	14711453	Appending Text to File Windows store Apps (windows RT)	// Create a file in local storage\nvar folder = ApplicationData.Current.LocalFolder;\nvar file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.FailIfExists);\n\n// Write some content to the file\nawait FileIO.WriteTextAsync(file, "some contents");\n\n// Append additional content\nawait FileIO.AppendTextAsync(file, "some more text");	0
29262235	29260970	Clicking on a disabled control is calling the parent event in C#	panel.Click += delegate {\n            var l = Cursor.Position;\n            l = panel.PointToClient(l);\n            var c = panel.GetChildAtPoint(l);\n            if (c == null) {\n                // good\n            }\n            else {\n                // ignore (disabled control)\n            }\n        };	0
2012647	2011207	ASP.NET GridView EditTemplate and find control	protected void GridView1_PreRender(object sender, EventArgs e)\n {\n  if (this.GridView1.EditIndex != -1)\n   {\n     Button b = GridView1.Rows[GridView1.EditIndex].FindControl("Button1") as Button;\n     if (b != null)\n      {\n      //do something\n      }\n   }\n }	0
14912422	14912334	How can I rotate single object in the container?	e.Graphics.DrawRectangle(Pens.Blue, 10, 10, 20, 20);\n    e.Graphics.RotateTransform(20);\n    e.Graphics.DrawRectangle(Pens.Red, 10, 30, 20, 20);\n    e.Graphics.ResetTransform();	0
11863999	11863957	Listview that shows unread messages in bold and read messages in normal font in C#	if (condition)\n{\n    item.Font = New Font(item.Font, FontStyle.Bold);\n}	0
2089597	2089575	how do I subscribe to an event in raised in another assembly	foo.SomethingCompleted += (sender, e) => this.DoSomething();	0
12557852	12557807	How to invoke Constructors by String in C#?	Activator.CreateInstance(Type.GetType("your type"))	0
11314663	11314608	IQueryable: reuse query in a different context	public IQueryable<myItem> MyQuery(MyContext context)\n{\n\n        return (from myItem in context.MyItems\n                select ...);\n}\n\npublic void MyMethod()\n{\n    using(MyContext context = new MyContext())\n    {\n      var query = MyQuery(context);\n    }\n}	0
31375400	31375318	Changing the parent of instantiated object	public GameObject symbolCharacter;\n\n#region IPointerClickHandler implementation\n\npublic void OnPointerClick (PointerEventData eventData)\n{\n    // Instantiate an object on Click\n    symbolCharacter = Instantiate(Resources.Load ("Prefabs/Symbols/SymbolImage1")) as GameObject;\n    symbolCharacter.transform.SetParent(GameObject.FindGameObjectWithTag("MessagePanel").transform);\n}\n\n#endregion	0
11046208	11046051	SQL database date format	SqlDataSource1.SelectParameters.Add("@d1", date1);\nSqlDataSource1.SelectParameters.Add("@d2", date2);\nSqlDataSource1.SelectCommand = "Select * FROM test WHERE Name = '"+name.Text+"' AND Date between @d1 AND @d2";	0
22013885	22013794	StreamReader path using * - Illegal Characters in Path	var sourceDirectory = @"G:\C#Projects\folder1\"\nvar txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.tl2");\n\nforeach (string currentFile in txtFiles)\n{\n   StreamReader leFiles = new StreamReader(currentFile, System.Text.Encoding.Default);  \n}	0
7130440	4440200	how to get the page source and search with Watin	// Find text like ctr+F (NOT IN SOURCE BUT IN "WHAT YOU SEE"\n        if (ie.Text.Contains("SOME TEXT TO FIND").Equals(true))\n        {\n            //Do stuff you would like when found here\n            MessageBox.Show("Text Found! ");\n\n        }\n        else\n        { \n            // cant find\n        }\n\n        //OR\n\n        // Find text in SOURCE\n        if (ie.Html.Contains("SOME TEXT TO FIND").Equals(true))\n        {\n            //Do stuff you would like when found here\n            MessageBox.Show("Text Found! ");\n\n        }\n        else\n        { \n            // cant find\n        }	0
17895415	17895163	Parsing Tree Structure to If statements	with open('input.txt') as f:\n    indent = 8\n    prev_depth = -1\n    closes = []\n    for line in f:\n        line = line.strip()\n        if not line: continue\n\n        depth = line.count('|')\n        while prev_depth >= depth:\n            prev_depth -= 1\n            print(closes.pop())\n        pad = ' ' * (depth*indent)\n        print(pad + 'If ({})'.format(line.lstrip('| ').split(':', 1)[0]))\n        print(pad + '{')\n        closes.append(pad + '}')\n        if ':' in line:\n            pad2 = ' ' * ((depth+1)*indent)\n            print(pad2 + 'Return {}'.format(line[line.find(':')+1:].strip()))\n        prev_depth = depth\n    while closes:\n        print(closes.pop())	0
1393913	1310677	Eager loading of Linq to SQL Entities in a self referencing table	var users = from u in db.Users\n            select new\n            {\n              /* other stuff... */\n              AddedTimestamp = u.AddedTimestamp,\n              AddedDescription = u.AddedByUser.FullName,\n              ChangedTimestamp = u.ChangedTimestamp,\n              ChangedDescription = u.ChangedByUser.FullName\n            };	0
6373086	6373006	how to clear list till some item? c#	for(var i = List.Count()-1; i>=0; i--) {\n   var item = List[i];\n   if (item != "itemThatYourLookingFor") {\n      List.Remove(item);\n      continue;\n   }\n   break;\n}	0
30131433	30019550	Iterating over JArray in NLua	local each = luanet.each\n\nfor k in each(jArray) do\n    print (k)\nend	0
19746364	19746341	lambda expression with aggregation function	var sum = _itemsReceivedList\n            .Where(x=>x.Value.Category==c)\n            .Sum(x=>x.Value.Weight);	0
9525318	9525125	LINQ getting Distinct values	class AssemblyComparer : EqualityComparer<AssemblyPrograms> {\n    public override bool Equals(AssemblyPrograms x, AssemblyPrograms y) {\n        return x.ProgramID == y.ProgramID && x.AssemblyID == y.AssemblyID;\n    }\n\n    public override int GetHashCode(AssemblyPrograms obj) {\n        return obj.ProgramID.GetHashCode() ^ obj.AssemblyID.GetHashCode();\n    }\n}	0
9636482	9611069	Changing the Bar Colors in MS Candle Stick Chart	// setting bar colors\nthis._chart.Series[0]["PriceUpColor"] = "Green"; \nthis._chart.Series[0]["PriceDownColor"] = "Red";	0
9218391	9218329	Get property name, need to retrieve only certain columns	public static CSVData CreateCSVData(List<RegDataDisplay> rList,\n                                    string[] selectors)\n{ \n    CSVData csv = new CSVData();\n    foreach (string selector in selectors)\n    {\n        var prop = typeof(RegDataDisplay).GetProperty(selector);\n        var values = rList.Select(row => (string) prop.GetValue(row, null))\n                          .ToList();\n        csv.Columns.Add(values);\n    }\n}	0
30481453	30481338	Change the controls of a player after a collision?	if (hitDuff) {\n        timer += Time.deltaTime;\n        duffMovement();\n\n        if (timer > 5.0) {\n            start ();\n            hitDuff = false;\n        }\n}	0
31894011	31877232	Search DNN Portal User using custom Module	public static UserInfo GetUserByName(int portalId, string username)\n{\n    var foundUsers = UserController.Instance.GetUsersBasicSearch(portalId, 0, 10, "UserID", true, "UserName", username);\n    if (foundUsers.Any())\n    {\n        return foundUsers.FirstOrDefault();\n    }\n    else\n    {\n        return null;\n    }\n}	0
9055554	9054618	use embeded Firebird	FbConnection con = new FbConnection("User=SYSDBA;" + "Password=masterkey;" + "Database=TEST.FDB;" + "DataSource=127.0.0.1;" + "Port=3050;" + "Dialect=3;" + "Charset=UTF8;");\ntry  {\n         con.Open();\n     }\ncatch (Exception ex) \n     {\n        MessageBox.Show(ex.ToString());\n     }	0
6031306	6031245	winforms how to paint (fillRectangle) a single cell in TableLayoutPanel?	private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)\n    {\n        if (e.Row == 0 && e.Column == 1)\n        {\n            e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);\n        }\n    }	0
3704678	3704650	C# How do I use a value from one function in another?	string some_value = null;\n\npublic void reading(object sender, EventArgs e)\n{\n    some_value = "Foobar";\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    if (some_value != null)\n    {\n        // ...\n    }\n}	0
20259363	20259097	How to get GridViewRow from DataKeys	protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)\n{   \n    //Get data row view\n    DataRowView drview = e.Row.DataItem as DataRowView;\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {       \n        //Find textbox control\n        TextBox txtname = (TextBox)e.Row.FindControl("txtName");\n        string Name = txtname.Text;\n\n        if (((GridView)sender).DataKeys[e.Row.RowIndex].Value.ToString() == "Leave")\n        { \n            txtname.disable=true;\n        }\n        else \n        { \n            txtname.disable = false; \n        }\n    }\n}	0
20056888	20056417	nested json array parsing	public class OuterObject\n{\n     public FirstArrayObject[];\n     public List<ObjInNestedArray[]>;\n}\n\npublic class FirstArrayObject\n{\n   public string A;\n   public string B;\n   public string C;\n}\n\npublic class ObjInNestedArray\n{\n     string property1;\n     AnotherLevel AnotherLevel;\n\n}\n\npublic class AnotherLevelObj\n{\n      string prop1;\n}\n\nOuterObject response = JsonConvert.DeserializeObject<OuterObject>(responseBodyAsString);	0
5638597	5638556	How can I elegantly implement multiple string replacements in the same file?	string contents = File.ReadAllText(filePath);\ncontents = Regex.Replace(contents,\n    "( " + column.Key + " )",\n    " " + column.Value + " ");\ncontents = Regex.Replace(contents,\n    "(\\[\"" + column.Key + "\"\\])",\n    "[\"" + column.Value + "\"]");\nFile.WriteAllText(filePath, contents);	0
1829687	1829679	How to determine if a string is a valid variable name?	// using System.CodeDom.Compiler;\nCodeDomProvider provider = CodeDomProvider.CreateProvider("C#");\nif (provider.IsValidIdentifier (YOUR_VARIABLE_NAME)) {\n      // Valid\n} else {\n      // Not valid\n}	0
5393547	5393136	perfect side combination of right triangle	// Obvious min is 1, obvious max is 99.\nfor(int i = 1; i != 100; ++i)\n{\n  // There's no point going beyond the lowest number that gives an answer higher than 100\n  int max = 100 * 100 - i * i;\n  // There's no point starting lower than our current first side, or we'll repeat results we already found.\n  for(int j = i; j * j <= max; ++j)\n  {\n    // Find the square of the hypotenuse\n    int sqr = i * i + j * j;\n    // We could have a double and do hyp == Math.Round(hyp), but lets avoid rounding error-based false positives.\n    int hyp = (int)Math.Sqrt(sqr);\n    if(hyp * hyp == sqr)\n    {\n      Console.WriteLine(i + ", " + j + ", " + hyp);\n      // If we want to e.g. have not just "3, 4, 5" but also "4, 3, 5", then\n      // we can also here do\n      // Console.WriteLine(j + ", " + i + ", " + hyp);\n    }\n  }\n}	0
21235536	21172399	Intuit Customer Account Data API - Get Account Type	// Check account type\nif (account.GetType() == typeof(BankingAccount))\n{\n    // Get banking account type.\n    var bankingAccount = (BankingAccount)account;\n\n    if (bankingAccount.bankingAccountTypeFieldSpecified)\n    {\n        var bankingAccountType = bankingAccount.bankingAccountType;\n    }\n}	0
4831124	4796211	Alphabetically Ordering a SelectList in MVC	List<Reason> reasonList = _db.Reasons.OrderBy(m=>m.Description).ToList();\n        ReasonList = new SelectList(reasonList, "Id", "Description");	0
33045749	33045691	Type and identifier are both required in a foreach statement using an object	foreach(dtIntegration_v10_r1.Vendor objvendor in objVendors)\n{\n    //your code.\n}	0
10689400	10689338	How do I access specific rows in my LINQ model?	var Model = (from r in DB.Products select r).OrderBy(r => Guid.NewGuid()).Take(5).ToList();\n\nvar ProductID1 = Model[0].ProductID;\nvar ProductID2 = Model[1].ProductID;	0
11205011	11204905	how to convert image file into image bytes	Bitmap image = new Bitmap("example.jpg"); \n\n// Loop through the image\nfor(x=0; x<image.Width; x++)\n{\n    for(y=0; y<image.Height; y++)\n    {\n        Color pixelColor = image1.GetPixel(x, y);\n        my_int_array[x][y] = pixelColor.ToArgb();\n    }\n}	0
4064355	4064322	Generics: How to check the exact type of T, without object for T	public class BusinessManager<T> where T : Business, new()\n...\n\nT _business = new T();\nstring businessName = _business.GetBusinessName();\nreturn businessName;	0
7417660	7417604	DisplayMemberPath for several properties in ListView	string NamePath { get { return Name + ": " + Path; }}	0
31039217	31037577	vNext Dependency Injection Generic Interface	services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));	0
32184276	32184062	Is it safe to pass a pointer to a UTF-8 array to String(SByte*)	string s1 = new String((sbyte*)p, 0, bytes.Length, Encoding.UTF8);	0
3544457	3544352	Save createGraphics in a file as image	Bitmap _image = new Bitmap(100, 100);\nGraphics _g = Graphics.FromImage(_image);\n\n//Graphics _g = pictureBox1.CreateGraphics();\nPen _pen = new Pen(Color.Red, 3);\nPoint myPoint1 = new Point(10, 20);\nPoint myPoint2 = new Point(30, 40);\n\nfor (int i = 0; i < _listPS.Count; i++)\n{\n    _g.DrawLine(_pen, _listPS[i], _listPE[i]);\n}\n\n_image.Save(@"D:\test.bmp");\n_image.Dispose();\n_g.Dispose();	0
12609979	12609959	How to check if SQLDataReader has no rows	if(dr.HasRows)\n{\n    // ....\n}\nelse\n{\n    MessageBox.Show("Reservation Number Does Not Exist","Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);\n}	0
12390891	12390645	How to use Code first Fluent API for inheritant data structure?	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n        {\n            modelBuilder.Entity<Profile>()\n                .Map(m => m.ToTable("Profiles"));\n\n            modelBuilder.Entity<Post>()\n                .HasMany(p => p.Likes)\n                .WithMany()\n                .Map(m =>\n                    {\n                        m.ToTable("PostLikes");\n                        m.MapLeftKey("PostId");\n                        m.MapRightKey("UserId");\n                    });\n\n            modelBuilder.Entity<Profile>()\n                .HasMany(p => p.Blogs)\n                .WithMany()\n                .Map(m =>\n                {\n                    m.ToTable("ProfileBlogs");\n                    m.MapLeftKey("UserId");\n                    m.MapRightKey("BlogId");\n                });\n        }	0
8482332	8482296	Efficient way to insert a value into an array?	var newArray = new myObj[oldArray.Lenght+1];    \noldArray.CopyTo(newArray, 1);\nnewArray[0] = InsertRecord(myParam);	0
19668726	19668658	C# WebBrowser, setting opacity of div	background-color: #ff00ff;\nfilter:alpha(opacity=50);\nopacity: .5;	0
7765449	7527712	DevExpress: How to change the backcolor of a SearchLookUpEdit control	Private Sub SearchLookUpEdit1_Popup(sender As System.Object, _\n        e As System.EventArgs) Handles SearchLookUpEdit1.Popup\n\n    Dim popupControl As Control = CType(sender, IPopupControl).PopupWindow\n    popupControl.BackColor = Color.LightBlue\n    Dim lc As LayoutControl = CType(popupControl.Controls(2).Controls(0), LayoutControl)\n    Dim lcgroup As LayoutControlGroup = CType(lc.Items(0), LayoutControlGroup)\n    lcgroup.AppearanceGroup.BackColor = Color.LightBlue\n\nEnd Sub	0
17412700	17412647	how to pass custom parameters to a function like in MVC html.routeurl?	var attributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)\nimg.MergeAttributes<string, object>(attributes, replaceExisting:true);	0
2731099	2463812	Unable to Read an XML file into a data set when XML files containg data in French	Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR")	0
21687852	21687766	Updating data to XML file c#	public void WriteXML(){\n    var xmlDoc = XElement.Load("reminds.xml");\n\n    string nowaData = dataData.Text.ToString();\n    string nowyOpis = tblOpis.Text.ToString();\n\n    var nowePrzypo = new XElement("przypom",\n        new XElement("data", nowaData),\n        new XElement("opis", nowyOpis));\n\n    ***xmlDoc.Root.Add(nowePrzypo);***\n\n    xmlDoc.Save("reminds.xml");	0
1442204	1442095	C# Navigate to Anchors in WebBrowser control	HtmlElementCollection elements = this.webBrowser.Document.Body.All;\nforeach(HtmlElement element in elements){\n   string nameAttribute = element.GetAttribute("Name");\n   if(!string.IsNullOrEmpty(nameAttribute) && nameAttribute == section){\n      element.ScrollIntoView(true);\n      break;\n   }\n}	0
9761676	9761154	Fluent Nhibernate mapping hasMany	public PropertyMap()\n{\n  Table("Property");\n  Id(x => x.Id).GeneratedBy.Identity();\n  Map(x => x.Title).Length(255).Not.Nullable();\n  HasMany(x => x.Photos).KeyColumn("Id"); // you were already doing this\n}\n\npublic PhotoMap()\n {\n    Table("Photo");\n    Id(x => x.Id).GeneratedBy.Identity();\n    Map(x => x.Version);\n    Map(x => x.ImageData).CustomSqlType("VARBINARY(MAX)").Length(160000);\n    Map(x => x.ImageMimeType);\n    References( x => x.Property ) // you'll need 'Property' in your class definition too\n        .Column('PhotoId')\n        .Cascade.All();\n }	0
25696677	25696610	How can I read the output of the console and put it into a variable?	Job = JobList[random.Next(JobList.Length)].ToString();	0
17987464	17987252	xml de-serialization with a very simple file	[XmlRoot(ElementName = "DietPlan")]\npublic class TestData\n{\n    [XmlElement("Fruit")]\n    public string Fruits { get; set; }\n\n    [XmlElement("Veggie")]\n    public string test { get; set; }\n\n}	0
6375438	6375145	Searching by Name in XML file through LINQ in C# and displaying in GridView	string nameToSearch = "Bob";\nstring rawXML = null;\n\nusing (var stream = new StreamReader(File.OpenRead("<YOUR_FILE_PATH>")))\n{\n    rawXML = stream.ReadToEnd();\n}\n\nif (rawXML != null)\n{\n    XDocument doc = XDocument.Parse(rawXML);\n    XElement foundNode = doc.Descendants("Table1").Where(n => n.Attribute("Name").Value.Contains(nameToSearch)).FirstOrDefault();\n\n    if (foundNode != null)\n    {\n        string name     = foundNode.Attribute("Name").Value;\n        string text     = foundNode.Attribute("Text").Value;\n        string location = foundNode.Attribute("Location").Value;\n    }\n}	0
7148580	7148287	Can I pass a parameter to ISessionFactory in NHibernate?	private static ISessionFactory SessionFactory(System.Reflection.Assembly assembly)\n{\n    if (_sessionFactory == null)\n    {\n        var configuration = new Configuration();\n        configuration.Configure();\n        configuration.AddAssembly(assembly);\n        _sessionFactory = configuration.Configure().BuildSessionFactory();\n    }\n    return _sessionFactory;\n}	0
6866025	6865261	How do I get the current mail item from Outlook ribbon context menu	public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl)\n{\n    var item = ctl.Context as Inspector;\n    var mailItem = item.CurrentItem as MailItem;\n    if (item != null)\n        return (item != null && HasMyCategory(item));\n    else\n        return false;\n}	0
11854025	9337223	Setting IsEnabled on a ribbon textbox to true doing nothing	public static readonly ICommand DummyCommand = new RoutedCommand("Dummy", typeof(Control));\n    public static void Dummy(Object sender, ExecutedRoutedEventArgs e)\n    {\n        // Do nothing its a dummy command\n    }\n    public static void CanDummy(object sender, CanExecuteRoutedEventArgs e)\n    {\n        e.CanExecute = true;\n    }	0
11568471	11568295	How do I make a List of controls which are clicked?	int Y = 0;\nforeach(PictureBox pb in MyList)\n{\n    if(!pb.Visible)\n    {\n        e.Graphics.DrawImage(pb.BackgroundImage, new Point(0,Y));\n        Y += pb.Height;\n    }\n}	0
16306138	15258258	Get the Max Length of a column in Entity Framework	[Column("Name")]\n[Required(ErrorMessage = "Name is obligatory")]\n[StringLength(30, MinimumLength = 3, ErrorMessage = "Name has to have at least 3 characters")]\npublic string Name { get; set; }	0
6174156	6173874	How to write route for this scenario	routes.MapRoute(\n      "Grouproute", // Route name\n      "{group}/{action}/{id}", // URL with parameters\n      new { controller = "Group", action = "Index", id = UrlParameter.Optional }, // Parameter defaults\n      new { group = @"^.{1}group$" } //Contraints\n  );	0
18907663	18907563	how to filter list using linq windows phone ListPicker	var cat = (_categorySelector.SelectedItem as Parameter).Category;\nvar query = App.ViewModel.Items.OfType<Parameter>().Where(jj => jj.Category == cat).ToList();	0
21583537	21582365	Want to find duplicates in list which have overlaps timespans	var result = lmr.Where(i => lmr.Any(o => YourCondition(i,o) && i != o));\n\n    //up to you\n    private bool YourCondition(MyRow i, MyRow o)\n    {\n        return i.StartTime >= o.StartTime && i.EndTime <= o.EndTime && i.Day == o.Day;\n    }	0
12105273	12104952	Add Multiple record using Linq-to-SQL	public static void InsertFeedbacks(IEnumerable<QuestionClass.Tabelfields> allList)\n{\n    var fadd = from field in allList\n               select new Feedback\n                          {\n                              Email = field.Email,\n                              QuestionID = field.QuestionID,\n                              Answer = field.SelectedOption\n                          };\n    context.Feedbacks.InsertAllOnSubmit(fadd);\n    context.SubmitChanges();\n}	0
30907143	30906039	How to add images from resources folder as attachment and embed into outlook mail body in C#	attachment = mailitem.Attachments.Add("c:\temp\MyPicture.jpg")\nattachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")\nmailitem.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>"	0
32800565	32800316	How to read column from data table and display as check box format in C#	DataSet ds = new DataSet();\nOda.Fill(ds, "Table");\ndataGridView1.DataSource = ds.Tables["Table"];	0
6749300	6749130	Programmatically retrieve section names from a razor view	Stack<T>	0
8701386	8701224	How I can convert Date to String formate.?	public static string GetTimeElpased(int secondsElpased, int minutesElpased, int hoursElpased,\n    int daysElpased, int monthsElpased, int yearsElpased)\n{\n    if (secondsElpased < 30)\n        return "few seconds ago";\n\n    if (minutesElpased < 1)\n        return secondsElpased + " seconds ago";\n\n    if (minutesElpased < 5)\n        return "few minutes ago";\n\n    if (hoursElpased < 1)\n        return minutesElpased + " minutes ago";\n\n    if (hoursElpased < 5)\n        return "few hours ago";\n\n    if (daysElpased < 1)\n        return hoursElpased + " hours ago";\n\n    if (daysElpased == 1)\n        return "yesterday";\n\n    if (monthsElpased < 1)\n    return daysElpased + " days ago";\n\n    if (monthsElpased == 1)\n        return "month ago";\n\n    if (yearsElpased < 1)\n        return monthsElpased + " months ago";\n\n    string halfYear = (monthsElpased >= 6) ? " and half" : "";\n    if (yearsElpased == 1)\n        return "year" + halfYear + " ago";\n\n    return yearsElpased + " years ago";\n}	0
1087080	1087041	Can I test a substring in a textBox for isLetter?	^[a-zA-Z]{4}.*	0
3427011	3426816	How do I create an Excel range object that refers to a name in Excel (c#)	Excel.Range range = myWorksheet.get_Range("MyName", Type.Missing);	0
23515602	23515507	XDocument load with environment variables	string path = Environment.ExpandEnvironmentVariables("%NAME_OF_THE_PATH%/Default_TestRunConfiguration.xml");\n\nXDocument configuration = XDocument.Load(path);	0
8883471	8881865	Saving a WPF canvas as an image	RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.RenderSize.Width,\n    (int)canvas.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);\nrtb.Render(canvas);\n\nvar crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250));\n\nBitmapEncoder pngEncoder = new PngBitmapEncoder();\npngEncoder.Frames.Add(BitmapFrame.Create(crop));\n\nusing(var fs = System.IO.File.OpenWrite("logo.png"))\n{\n    pngEncoder.Save(fs);\n}	0
24540056	24539062	Is there a simple method to get coordinates of a particular item in a checkedlistbox?	void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {\n  Rectangle r = checkedListBox1.GetItemRectangle(e.Index);\n  TextBox newAmountTextBox = new TextBox();\n  newAmountTextBox.Location = new Point(r.Left, r.Top);\n  //...\n}	0
17136239	17136141	is it possible to get a left join list out a linq query	var aom = from a in accounts\n                  join ao in accountorders on a.ID equals ao.AccountID into aoGroup\n                  from aod in aoGroup.DefaultIfEmpty(new AccountOrder())\n                  join o in orders on aod.OrderID equals o.ID into oGroup\n                  group oGroup by a into g\n                  select new AccountOrderModel() { Name = g.Key.Name, orders = g.SelectMany(x => x).ToList() };	0
16796876	16796608	Make progress bar display download status	client.DownloadFileAsync(new Uri("http://download.thinkbroadband.com/10MB.zip"), desktop + "test.zip");	0
18026592	18023860	creating a SharePoint Lookup field via CSOM error	var lookupFieldXml = "<Field DisplayName="UserStatus" Type="Lookup" />";\nvar field = destinationList.Fields.AddFieldAsXml(lookupFieldXml, false, AddFieldOptions.AddToAllContentTypes);\nlookupField = context.CastTo<FieldLookup>(field);\nlookupField.LookupList = sourceLookupList.Id.ToString();\nlookupField.LookupField = "Title";\n// at this point, we can update against lookupField or field. It doesn't appear to matter.\nfield.Update();\ncontext.ExecuteQuery();	0
12486073	12486022	How to Filter data in DataSet C#?	foreach (ConsoleApplication4.DataSet1.wordRow row in kata.GetData())\n{\n     if(row.wordid==10)\n         System.Console.WriteLine(row.lemma);\n}	0
7046569	7046385	Building a lamda WHERE expression to pass into a method	static void myMethod<T>(List<T> list, Func<T,bool> predicate, ref int x)\n    {\n        x = 5;\n        var v = list.Where(predicate);\n        foreach (var i in v)\n            Console.Write(i);\n        Console.ReadLine();\n    }\n\n    static void Main(string[] args)\n    {\n        List<int> x = new List<int> { 1, 2, 3, 4, 5 };\n        int z = 0;\n        myMethod(x, p => p == z, ref z);\n    }	0
13704810	13704658	Sending IEnumerable to a view that already contains a model	public class YourViewModel\n    {\n\n        public sistema_DocType Type { get; set; }\n        public IEnumerable<string> Indices {get;set;}\n    }	0
28561991	28561931	How to correctly interpret DateTime.UTCNow serialized as json, taking time zones into account?	var date = new Date('2015-02-17T12:38:58.3220885Z');\ndate.toString()	0
26775358	26774416	Accessing children of second pivot item from code behind with their x:Name returns null in Windows Phone 8.1	public MainPage()\n{\n    this.InitializeComponent();   // check here as well to see if it declares every UI element correctly\n    this.NavigationCacheMode = NavigationCacheMode.Required;\n}	0
28958567	28958466	How can we map a string with case sensitive?	fieldArrayList[i].Replace(" ","").ToLower() == \n    fieldArrayRecord[j].Replace(" ","").ToLower()	0
26039020	26038804	C#, splitting serial data and displaying in separate textBox's	string[] slist = text.Split(':');	0
26406936	26406810	How to create and output data as links?	protected override void OnPreRender(EventArgs e)\n{     \n    var ctrl = new HtmlGenericControl("div");\n    string html = this.GetArticleText();\n\n    // create the html formatted HTML/Links taking into account anti-xss attacks\n    foreach(var tag in this.LoadAllTags())\n    {\n      html.Replace(tag.Key, this.CreateLinkHtml(tag);\n    }\n\n    ctrl.InnerHtml = html;\n\n    this.SomePageContainer.Controls.Add(ctrl);\n\n    base.OnPreRender(e);\n}	0
3798802	3798778	How to create a macro for string containig ,<Status, tinyint,>	(?<val>[A-Za-z]+)	0
2653478	2653453	Repository pattern - Switch out the database and switch in XML files	(from a in b\nwhere b.Element("type").Value == "test"\nselect new c(){d=b.Element("prop").Value}).ToList();	0
27789723	27789636	Open Resource File with FileStream fails	using (var rdr = new StringReader(Properties.Resources.Testing)) {\n        string line;\n        while ((line = rdr.ReadLine()) != null) {\n            // Do something with line\n            //...\n        }\n    }	0
23659831	23659452	Removing Closed Form from a List in C#	//code to create and add form\n  var form = new Form1();\n  form.FormClosed +=form_FormClosed;\n  _forms.Add(form);\n  form.Show();\n\n  //cleanup\n  private void form_FormClosed(object sender, FormClosedEventArgs e)\n  {\n        var closedForm = sender as Form1;\n        _forms.Remove(closedForm);\n  }	0
26341812	26341652	connect a single key event to the control that has focus	textBox1.KeyPress += new KeyPressEventHandler(textBox_KeyPress);\ntextBox2.KeyPress += new KeyPressEventHandler(textBox_KeyPress);\n\nprivate void textBox_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if(e.KeyChar == '\r')\n    {\n        e.Handled = true;\n        // some other stuff\n        Console.WriteLine(((TextBox)sender).Name); //actual textbox name\n    }\n}	0
33676837	33676517	How to deserialize a Bson document to a POCO?	public static List<Customer> LoadCustomers()\n{\n    var client = new MongoClient(connectionString);\n    var database = client.GetDatabase("orders");\n    //Get a handle on the customers collection:\n    var collection = database.GetCollection<Customer>("customers");\n    var docs = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();\n    return docs;            \n}	0
14019431	14019239	How can I avoid a StackOverflowException in C#?	public partial class MainForm : Form\n{\n    CheckAnswers checkanswers;\n    ...\n    public MainForm()\n    {\n        checkanswers = new CheckAnswers(this);\n        ...\n    }\n}\npublic class CheckAnswers // Not sure why you inherit MainForm here, but it's not a good idea, as someone already stated\n{\n    MainForm mainform;\n\n    public CheckAnswers (MainForm main)\n    {\n        mainform = main;\n    }\n    ...\n}	0
33736408	33732138	Windows Phone 8 NavigationService.Navigate throws a NullReferenceException	Loaded += navigate_pause();\n\n\n private RoutedEventHandler navigate_pause() \n {\n        Dispatcher.BeginInvoke(() =>\n        {\n            ((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/Pause.xaml", UriKind.Relative));\n        });\n        return null;\n }	0
21450776	21450681	How do I add checked item(s) in my checkedlistbox to a DataGridView?	private void button1_Click(object sender, EventArgs e)\n{\n    for (int i = 0; i < checkedListBox1.Items.Count; i++)\n    {\n        if (checkedListBox1.GetItemChecked(i))\n        {\n            dataGridView1.Rows.Add(checkedListBox1.Items[i], "1");\n        }\n    }\n}	0
1692705	17125	What are real life applications of yield?	Ideally some problem that cannot be solved some other way	0
9538135	9538048	Parse 2 numbers in C# divided by minus sign	var regex = new Regex(@"^(?<first>-?[\d.,]+)?-(?<second>-?[\d.,]+)?$");\nvar match = regex.Match(input);\nif (match.Success)\n{\n  int? a = match.Groups["first"].Success\n    ? Int32.Parse(match.Groups["first"].Value) \n    : (int?)null;\n\n  int? b = match.Groups["second"].Success\n    ? Int32.Parse(match.Groups["second"].Value) \n    : (int?)null;\n}	0
6888986	6888893	Insert string in RichTextBox at cursor position	richTextBox1.SelectionLength = 0;\nrichTextBox1.SelectedText = "//";	0
8646765	8646679	PictureBox Drawed image colors to array	Bitmap _b;\n private void Form1_Paint(object sender, PaintEventArgs e)\n {\n    _b = new Bitmap(pictureBox1.Width, pictureBox1.Height);\n    Graphics g = Graphics.FromImage(_b);\n    g.DrawEllipse(Pens.Black,new Rectangle(0,0,25,25));\n    pictureBox1.Image = _b;\n }\n ...\n private void ParseImage()\n {\n    for (int y = 0; y < _b.Height; y++)\n    {\n       for (int x = 0; x < _b.Width; x++)\n       {\n          Color c = _b.GetPixel(x, y);\n       }\n     }\n  }	0
33672714	33672635	How to handle long email address with regex?	MailAddress m = new MailAddress(email);	0
26257137	26256578	Get all app and web config files in solution	string[] configFiles = Directory.GetFiles( @"YourSolutonDirectoryLocation", "*.config", SearchOption.AllDirectories)\n                               .Where(x => x.EndsWith("App.config") || x.EndsWith("Web.config")).ToArray();	0
2829425	2829333	How to programatically send a TAB keystroke in netcf	using System;\nusing System.Windows.Forms;\n\nclass MyTextBox : TextBox {\n    protected override void OnKeyDown(KeyEventArgs e) {\n        if (e.KeyData == Keys.Enter) {\n            (this.Parent as ContainerControl).SelectNextControl(this, true, true, true, true);\n            return;\n        }\n        base.OnKeyDown(e);\n    }\n    protected override void OnKeyPress(KeyPressEventArgs e) {\n        if (e.KeyChar == '\r') e.Handled = true;\n        base.OnKeyPress(e);\n    }\n}	0
9091748	9091577	Regular expressions match not working accurately with semicolon	string val = "0926;0941;0917;0930;094D;";\nstring match = "0930;094D;"; // or match = "0930;" both found\n\nif (Regex.IsMatch(val,match))\n     Console.Write("Found");\nelse Console.Write("Not Found");	0
19947829	19947564	Regular expression : numbers with nine digits	if (Regex.IsMatch(Number,@"\d{9}"))\n   {\n         //Has 9 digits      \n   }	0
23123286	23123215	Find all possibilities C#	for(int i = 0; i < 10000; i++) {\n    Console.WriteLine(i.ToString("0000"));\n}	0
7199718	7199115	SplitterLocation doesn't save in the settings	private void Form1_FormClosing(object sender, EventArgs e)\n{\n  MailSystem.Properties.Settings.Default.splitterLocation = splitter1.Location;\n  MailSystem.Properties.Settings.Default.Save();\n}	0
31680632	31680492	How to save more values in XML	condition = conditions.Element("ipaddress");\nif (condition != null) {\n    string[] lines = condition.Value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);\n    this.IpAddress = new XElement("ipaddresses", lines.Select(o=> new XElement("item", o))).ToString();\n}	0
17142671	17142011	Monitoring timers in a windows service	public class MonitoredTimer {\n\n    private Timer _timer;\n    private int NextExecutionTime;\n    private int LastExecutionTime\n\n    public MonitoredTimer(TimerCallback callback,...) {\n        _timer = new Timer((s)=>callback(s);UpdateExecutionTimes());\n    }\n\n    public int GetLastExecution(){\n        return LastExecutionTime;\n    }\n\n    ...\n}	0
1652008	1652001	Ubiquitous way to get the root directory an application is running in via C#	System.Reflection.Assembly.GetExecutingAssembly().Location	0
5553297	5550918	How to use effective caching in .NET?	private static Cache Cache;\n\npublic void AddItem(string data)\n{\n    //Do a database call to add the data\n\n    //This will force clients to requery the source when GetItems is called again.\n    Cache.Remove("test");  \n}\n\npublic List<string> GetItems()\n{\n    //Attempt to get the data from cache\n    List<string> data = Cache.Get("test") as string;\n\n    //Check to see if we got it from cache\n    if (data == null)\n    {\n        //We didn't get it from cache, so load it from \n        // wherever it comes from.\n        data = "From database or something";\n\n        //Put it in cache for the next user\n        Cache["test"] = data;\n    }\n\n    return data;\n}	0
20087082	20085980	How to pass an object instead of it value	[TestClass]\npublic class StringObjectMapperTest\n{\n    private Dictionary<string, Setter> mapping = new Dictionary<string, Setter>();\n\n    public delegate void Setter(string v);\n\n    [TestMethod]\n    public void TestMethod1()\n    {\n        string string1 = "string1";\n        string string2 = "string2";\n        string text1 = "text1";\n        string text2 = "text2";\n\n        Add("STRING1", x => string1 = x);\n        Add("STRING2", x => string2 = x);\n\n        Assert.AreNotEqual(text1, string1);\n        Set("STRING1", text1);\n        Assert.AreEqual(text1, string1);\n\n        Assert.AreNotEqual(text2, string2);\n        Set("STRING2", text2);\n        Assert.AreEqual(text2, string2);\n    }\n\n    private void Set(string key, string value)\n    {\n        Setter set = mapping[key];\n        set(value);\n    }\n\n    private void Add(string p, Setter del)\n    {\n        mapping.Add(p, del);\n    }\n}	0
19529889	19529812	Insert Records in SQL Server from Oracle C#	Job  \nstep 1   Backup table \nstep 2   (if step 1 successful) Run SSIS package\n                    Truncate table\n                    Reload table using DB Link \nstep 3   (if step 2 failure) restore from backup	0
33127339	33127029	C#: How to shorten that XML appending?	var file_name = GlobalSettings.appDefaultFolder + "backups.xml";\nXDocument xdoc = XDocument.Load(file_name);\nvar backup999 = new XElement("backup",\n    new XAttribute("id", 999),\n    new XElement("foldername", "testing1"),\n    new XElement("backupdate", "99/99/9999")\n    );\n\nxdoc.Root.Add(backup999);\nxdoc.Save(file_name);	0
29626906	29626832	Nullable create via reflection with HasValue = false	public static Nullable<T> Create<T>() where T : struct \n{\n    return new Nullable<T>(); // or default(Nullable<T>) \n}	0
13150033	13089581	Reading Excel ROW using OleDb data retrieval	string connectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";\nstring testCaseName = "case_1";\nstring query = "SELECT * from [Sheet1$] WHERE TestCaseName=\"" + testCaseName + "\"";\nDataTable dt = new DataTable();\n\nusing (OleDbConnection conn = new OleDbConnection(connectionString))\n{\n    conn.Open();\n\n    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, conn))\n    {\n        DataSet ds = new DataSet();\n        dataAdapter.Fill(ds);\n        dt = ds.Tables[0];\n    }\n\n    conn.Close();\n}	0
16901367	16898311	Upload files to Azure Blob storage through WebApi without accessing local filesystem	public async Task<HttpResponseMessage> PostUpload()\n{\n    var provider = new MultipartFileStreamProvider(Path.GetTempPath());\n\n    // Read the form data.\n    await Request.Content.ReadAsMultipartAsync(provider);\n\n    // do the rest the same     \n}	0
7423947	7266101	Receive messages continuously using udpClient	//Client uses as receive udp client\nUdpClient Client = new UdpClient(Port);\n\ntry\n{\n     Client.BeginReceive(new AsyncCallback(recv), null);\n}\ncatch(Exception e)\n{\n     MessageBox.Show(e.ToString());\n}\n\n//CallBack\nprivate void recv(IAsyncResult res)\n{\n    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8000);\n    byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);\n\n    //Process codes\n\n    MessageBox.Show(Encoding.UTF8.GetString(received));\n    Client.BeginReceive(new AsyncCallback(recv), null);\n}	0
27036560	27036423	Using Html.DisplayFor() outside of view or getting formatted property from DisplayFormat annotation	public static string GetProductSnippet<T>(Product product, HtmlHelper<T> helper)\n{\n    return helper.DisplayFor(p => p.ReleaseDate).ToString();\n}\n\nvar markup = GetProductSnippet<List<Product>>(product, helper);	0
4050736	4003082	Call Oracle stored procedure from C#	create or replace procedure UpdateFileMapping(m in Number,y in    DBMS_SQL.varChar2_table,z in DBMS_SQL.number_table)\nIS  \nC NUMBER;\nN NUMBER;\n\nBEGIN\n\nC := DBMS_SQL.OPEN_CURSOR;\nDBMS_SQL.PARSE(C,'INSERT INTO tablename VALUES(:x  ,:fieldName,:mappedFieldId)',DBMS_SQL.NATIVE);\n DBMS_SQL.BIND_ARRAY(C,':fieldName',original_Field_Names);\nDBMS_SQL.BIND_ARRAY(C,':mappedFieldId',mapped_Field_Ids);\nDBMS_SQL.BIND_VARIABLE(C,':x',file_Id);\nN := DBMS_SQL.EXECUTE(C);\nDBMS_SQL.CLOSE_CURSOR(C);\n\nEND;	0
13500851	13500796	Is it possible to use a path with %% in it?	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/folder/file.txt";	0
23403688	23403487	How to Save Append type data from richTextBox	using (StreamWriter writer = File.AppendText(FilePath))\n {\n    writer.WriteLine(richTextBox1.text);\n }	0
4010594	4010565	array of ByteArray into MemoryStream	var ms = new MemoryStream();\nfor(var i=0; i < byteArray.Length; i++)\n  ms.Write(byteArray[i], 0, byteArray[i].Length);	0
10340418	10340253	Read Tree Menu Xml C#	XElement doc = XElement.Parse("You XML text");\n\nforeach (XElement treeNode in doc.Elements())\n    Console.WriteLine(treeNode.Value);	0
29768144	29767730	Use Textbox to search DataGrid	private void searchart()\n{\n  int itemrow = -1;\n  String searchValue = cueTextBox1.Text.ToUpper();\n\n  if (searchValue != null && searchValue != "")\n    {\n    foreach (DataGridViewRow row in dataGridView1.Rows)\n      {\n      //search for identical art\n      if (row.Cells[0].Value.ToString().Equals(searchValue))\n        {\n          itemrow = row.Index;\n          break;//stop searching if it's found\n        }\n      //search for first art that contains search value\n      else if (row.Cells[0].Value.ToString().Contains(searchValue) && itemrow == -1)\n      {\n        itemrow = row.Index;\n      }\n    }\n    //if nothing found set color red\n    if (itemrow == -1)\n    {\n      cueTextBox1.BackColor = Color.Red;\n    }\n    //if found set color white, select the row and go to the row\n    else\n    {\n      cueTextBox1.BackColor = Color.White;\n      dataGridView1.Rows[itemrow].Selected = true;\n      dataGridView1.FirstDisplayedScrollingRowIndex = itemrow;\n    }\n  }\n}	0
9412440	9412252	How can i draw the point in the pictureBox1 center + 10 using Random?	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            var halfX = pictureBox1.ClientRectangle.Width / 2;\n            var halfY = pictureBox1.ClientRectangle.Height / 2;\n\n            Random rnd = new Random();\n            var offsetX = rnd.Next(-10, 10);\n            var offsetY = rnd.Next(-10, 10);\n\n            drawPoint(halfX + offsetX, halfY + offsetY);\n        }\n\n        public void drawPoint(int x, int y)\n        {\n            Graphics g = Graphics.FromHwnd(pictureBox1.Handle);\n            SolidBrush brush = new SolidBrush(Color.LimeGreen);\n            Point dPoint = new Point(x, (pictureBox1.Height - y));\n            dPoint.X = dPoint.X - 2;\n            dPoint.Y = dPoint.Y - 2;\n            Rectangle rect = new Rectangle(dPoint, new Size(4, 4));\n            g.FillRectangle(brush, rect);\n            g.Dispose();\n        }\n     }	0
11313648	11313604	find out which control triggered postback	string ctrlname = page.Request.Params.Get("__EVENTTARGET");\nif (ctrlname != null && ctrlname != string.Empty)\n{\n    return this.Page.FindControl(ctrlname);\n}	0
4242362	4242336	Maintain Data after postback	i put them in a globally declared datatable	0
5623386	5623264	How to convert varBinary into image or video when retrieved from database in C#	BitmapImage bmpImage = new BitmapImage();\nMemoryStream msImageStream = new MemoryStream();    \n\nmsImageStream.Write(value, 0, value.Length);\n\nbmpCardImage.BeginInit();\nbmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray());\nbmpCardImage.EndInit();\n\nimage.Source = bmpCardImage;	0
1801198	1801183	Issues with Checkbox list losing Attrubutes on a postback	if(!Page.IsPostBack)\n{\n  YourDataBindingMethod();\n}	0
27151490	27148447	XML formatting comes out wrong	XDocument doc = new XDocument(\n                 new XComment("this is a comment"),\n                 new XElement("LoanRequest",\n                      new XElement("ssn", l.SSN),\n                      new XElement("creditScore", l.CreditScore),\n                      new XElement("loanAmount", l.LoanAmount),\n                      new XElement("loanDuration", l.loanDuration.ToString())));\n\ndoc.Save(path);	0
10304260	10304213	How to handle exception without using try catch?	if(connection.DidAnErrorOccur)	0
13055232	13054396	c# comparing current windows user to AD group	PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);\nUserPrincipal uPrincipal = UserPrincipal.Current;\n\n if (validate.IsUserInGroup("MyGroup", uPrincipal))\n            {\n                var MemberShipForm = new Membership();\n                MemberShipForm.Show();\n            }	0
24832130	24831822	How do I Compare values in column of a gridview	Operator="DataTypeCheck" Type="Integer"	0
17581778	17579656	How do you exclude a value of an Array?	public double Average()\n{\n    // Initialize smallest with the first value.\n    // The loop will find the *real* smallest value.\n    int smallest = temp[0];\n\n    // To calculate the average, we need to find the sum of all our temperatures,\n    // except the smallest.\n    int sum = temp[0];\n\n    // The loop does two things:\n    // 1. Adds all of the values.\n    // 2. Determines the smallest value.\n    for (int c = 1; c < temp.Length; ++c)\n    {\n        if (temp[c] < smallest)\n        {\n            smallest = temp[c];    \n        }\n        sum += temp[c];\n    }\n    // The computed sum includes all of the values.\n    // Subtract the smallest.\n    sum -= smallest;\n\n    double avg = 0;\n    // and divide by (Length - 1)\n    // The check here makes sure that we don't divide by 0!\n    if (temp.Length > 1)\n    {\n        avg = (double)sum/(temp.Length-1);\n    }\n   return avg;\n}	0
18106300	18106168	Using a validation summary to display label text	bool ResultUserExistence = register.CheckUniquenessUserID(txtUserId.Text);\n\nif (ResultUniquenessEmail == null)\n{\n    continue through code...\n}\n\nelse\n{\n    var err As new CustomValidator()\n    err.ValidationGroup = "UserUniqueness";\n    err.IsValid = False;\n    err.ErrorMessage = "Please choose a different user name. The current user name is already registered.";\n    Page.Validators.Add(err);    \n\n}	0
24211402	24170374	Don't get full Json of the Twitter Api (C#, application-only auth)	public static async Task<string> GetTwitterList(string bearerToken)\n    {\n        WebRequest request = WebRequest.Create("https://api.twitter.com/1.1/lists/statuses.json?slug=odyssee&owner_screen_name=dieVanDeIlias");\n\n        string result = "";\n\n        request.Method = "GET";\n        request.Headers.Add("Authorization", String.Format("Bearer {0}", bearerToken));\n        request.Timeout = Timeout.Infinite;\n\n        WebResponse response = await request.GetResponseAsync();\n\n        Encoding encoder = System.Text.Encoding.GetEncoding("utf-8");\n\n        string contentLength = response.Headers.Get("Content-Length");\n        int contentLengthInt = Convert.ToInt32(contentLength);\n\n        using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoder))\n        {\n            while (sr.Peek() >= 0)\n            {\n                result = sr.ReadToEnd();\n            }\n        }\n\n        return result;\n    }	0
4209715	4209479	Monitoring Enterprise Library caching	foreach(DictionaryEntry d in myExposedCacheManager.RealCache.CurrentCacheState) \n    {\n\n         Console.WriteLine(d.Key.ToString(), d.Value.ToString();\n    }	0
31911566	29944287	Ribbon not showing in XAML	MainWindow.xaml	0
12530460	12530410	Selecting 3 identical items from list	return\n    collection.Any(any => collection.Count(item => item.Equals(any)) == 3);	0
6915679	6915638	Reading csv file into a DataTable using C#?	using (var csv = new CachedCsvReader(new StreamReader(filePath), true))\n{\n    DataTable Table = new DataTable();\n    Table.Load(csv);\n}	0
25766396	25766292	Usage of extension methods for framework types	public static Frobulator ToFrobulator(this string Frobulator)	0
6579605	6579568	Handling SqlCommand null parameters in a select query in asp.net	bool useName = !String.IsNullOrEmpty(txtUsername.Text);\nStringBuilder query = new StringBuilder("select * from xy where id=@id");\nif(useName) \n query.Append(" AND name=@name");\n\nSqlCommand cmd = new SqlCommand(query.ToString());\n// add ID param\nif(useName) {\n  // add name param\n}	0
27723361	27723219	I have a XML tag that I am submitting I need to only show half of the opening tag for the closing	XElement burgerRequestNode = new XElement("BURGER_REQUEST",\n                                new XAttribute("_MISMOVersionID", 2.4),\n                                new XAttribute("_ActionType", "No Pickle"),\n                                new XAttribute("_CommentText", "Hello world!"));	0
14078131	14078061	Automating mulitple projects in a solution	right-click your solution > Properties > Common Properties > StartUp Project	0
7572190	7571928	Windows Service Hosted WCF Service Getting "Access Denied" When Trying To Read a File	WindowsIdentity.GetCurrent()	0
31959113	31957085	Creating a .csv file for my esurvey application. How do I start?	private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)\n        {\n            // Restore values stored in session state.\n            if (e.PageState != null && e.PageState.ContainsKey("greetingOutputText"))\n            {\n                greetingOutput.Text = e.PageState["greetingOutputText"].ToString();\n            }\n        }\n\n\n\nprivate void navigationHelper_SaveState(object sender, SaveStateEventArgs e)\n        {\n            e.PageState["greetingOutputText"] = greetingOutput.Text;\n\n        }	0
27569855	27549978	Export Windows forms datagridview to excel power pivot table with C#	public static void SerializeObject(this List<SPSR_ReporteSabanasxOrdenes_Todos_Result> list, string fileName)\n    {\n        var serializer = new XmlSerializer(typeof(List<SPSR_ReporteSabanasxOrdenes_Todos_Result>));\n        using (var stream = File.OpenWrite(fileName))\n        {\n            serializer.Serialize(stream, list);\n        }\n    }	0
2514925	1140560	Get Song Currently Playing In Windows Media Player	WMPLib.IWMPMedia song = wmp.newMedia(@"C:\SongName.mp3");         \n        string tmpArtist = song.getItemInfo("Artist");\n        string tmpTitle = song.getItemInfo("Title");	0
24119498	24119315	Read date from file name	DateTime dateValue; \nbool parsed = DateTime.TryParseExact(dateTime, \n                       "yyyyMMdd", \n                       CultureInfo.InvariantCulture, \n                       DateTimeStyles.None, \n                       out dateValue);	0
4294220	4294191	How to seperate two Ints from a ReadLine in C#	using (StreamReader sr = new StreamReader(file))\n  {\n     string lineIn = string.Empty;\n     while ((lineIn = sr.ReadLine()) != null)\n     {\n        string[] numbersAsStrings = lineIn.Split(' ');\n     }\n   }	0
10091288	10091199	Using Unique Key in SQL with or without try/catch as a valid way to verify integrity of data	IF NOT EXISTS(SELECT ...)	0
7721076	7720054	how to bind wpf combo box to all system font size	foreach (FontFamily F in Fonts.SystemFontFamilies) addToComboBox(F);	0
6847209	6847148	Is it possible to use a string for a LINQ query expression?	var query = ...\n\nif (status > 0)\n{\n    query = query.Where(o => o.id == status);\n}	0
31166535	31166352	Get specific word from string	var startIndex = tableUrl.LastIndexOf('[') + 1; // +1 to start after opening bracket\nvar endIndex = tableUrl.LastIndexOf(']');\nvar charsToRead = (startIndex - endIndex) - 1; // -1 to stop before closing bracket\n\nvar tableName = tableUrl.Substring( startIndex, charsToRead );	0
4830707	4830417	Manually unpinning a byte[] in C#?	//Pin it \nGCHandle myArrayHandle = GCHandle.Alloc(result,GCHandleType.Pinned);\n//use array\nwhile (r < length)\n{\n    int bytes = client.Client.Receive(result, r, length - r, SocketFlags.None);\n    r += bytes;\n}\n//Unpin it\nmyArrayHandle.Free();	0
2243662	2243622	C# Winforms - How to Pass Parameters to SQL Server Stored Procedures	// your TableAdapter\nPatientTableAdapter adapter = new PatientTableAdapter();\n\n\n// your input and output variables\nstring name = "somePatientName";\nint patientID? = 0;\nstring returnedName? = "";\n\n// TableAdapter Method, wired to Stored Proceedure\nadapter.SelectByName("somePatientName", out patientID, out returnedName);	0
8471219	8471185	How to obtain values from multiple Combo Boxes	string s"";\n\n  private void combobox1_SelectedIndexChanged(object sender, EventArgs e)\n        {\n          s = combobox1.Text+ combobox2.Text+ combobox3.Text+ combobox4.Text;\n        }\n\n  private void combobox2_SelectedIndexChanged(object sender, EventArgs e)\n        {\n          s = combobox1.Text+ combobox2.Text+ combobox3.Text+ combobox4.Text;\n        }\n  private void combobox3_SelectedIndexChanged(object sender, EventArgs e)\n        {\n          s = combobox1.Text+ combobox2.Text+ combobox3.Text+ combobox4.Text;\n        }\n  private void combobox4_SelectedIndexChanged(object sender, EventArgs e)\n        {\n          s = combobox1.Text+ combobox2.Text+ combobox3.Text+ combobox4.Text;\n        }	0
12162980	12162339	Find monitor configuration in terms of Screens Wide x Screens High	var width = Screen.AllScreens.Select(s => s.Bounds.X).Distinct().Count();\nvar height = Screen.AllScreens.Select(s => s.Bounds.Y).Distinct().Count();	0
1607552	1607439	how to change "-1" to "yes" value in Crystal Report field?	if (field=-1) then \n"Yes"\nelse\n"No"	0
22424716	22424174	How to catch user actions after closing Excel Workbook	If the workbook has been changed, this event occurs before the user is asked to save changes.	0
17439341	17439248	How to safely check if a dynamic object has a field or not	try\n{\n    dynamic testData = ReturnDynamic();\n    var name = testData.Name;\n    // do more stuff\n}\ncatch (RuntimeBinderException)\n{\n    //  MyProperty doesn't exist\n}	0
8811	8800	Best implementation for Key Value Pair Data Structure?	KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");	0
14936974	14936300	Windows 8 App XAML/C#: Set multiple pushpins to Bing map in one method	LocationCollection locationCollection = new LocationCollection ();\n  // The Venue class is a custom class, the Latitude & Logitude are of type Double\n  foreach (Venue venue _venues)\n  {\n       Bing.Maps.Location location = new Location(venue.Latitude, venue.Longitude);\n\n       // Place Pushpin on the Map\n       Pushpin pushpin = new Pushpin();\n       pushpin.RightTapped += pushpin_RightTapped;\n       MapLayer.SetPosition(pushpin, location);\n       myMap.Children.Add(pushpin);\n\n\n       locationCollection.Append(location);\n  }\n  myMap.SetView(new LocationRect(locationCollection));	0
16815747	16815455	How to download a file from another Sharepoint Domain	var url = "http://otherserver/documents/mydocument.doc";\nvar wc = new WebClient();\nwc.UseDefaultCredentials = true; // May be replaced by explicit credential\nwc.DownloadFile(url, @"c:\somewhere\mydocument.doc");	0
20967479	20964895	Intercept redirects from UpdatePanel Posts	Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);\n    function beginRequest(sender, args) {\n        args._request._events.addHandler('completed', changeURL);\n    }\n    function changeURL(sender, args) {\n        var s = new String(sender._xmlHttpRequest.responseText);\n        if (s.indexOf('pageRedirect') > -1)\n        {\n            var pattern = 'pageRedirect||';\n            var s1 = s.substring(s.indexOf(pattern) + pattern.length, s.length);\n            var nextPipe = s1.indexOf('|');\n            var encodedURL = s1.substring(0, nextPipe);\n            encodedURL = decodeURIComponent(encodedURL);\n            window.location.href = DoCustomizationsOntheURL(encodedURL);\n            args.stopPropagation();\n        }\n    }	0
5101831	5101791	How to run C# 4.0 app on Linux OS using mono?	mono MyApplication.exe	0
7735610	7735579	Setting default value for properties of Interface?	public interface IA {\n        int Prop { get; }\n\n        void F();\n    }\n\n    public abstract class ABase : IA {\n        public virtual int Prop\n        {\n            get { return 0; }\n        }\n\n        public abstract void F();\n    }\n\n    public class A : ABase\n    {\n        public override void F() { }\n    }	0
31876272	31868909	Getting points of polygons from a canvas	foreach (var polygon1 in this.PlayingCanvas.Children.OfType<Polygon>())\n    foreach (var polygon2 in this.PlayingCanvas.Children.OfType<Polygon>().Where(x => x != polygon1))\n            HelperMethods.PointCollectionsOverlap_Fast(getPoints(polygon1), getPoints(polygon2));	0
34047996	34040928	AxWindowsMediaPlayer - black screen	Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);	0
32822567	32822338	String input was not in a correct format- C#	private void btnupdate_Click(object sender, EventArgs e) \n{\n    try \n    {\n        string c = ConfigurationManager.ConnectionStrings["LMS"].ConnectionString;\n        SqlConnection con = new SqlConnection(c);\n        con.Open();\n        SqlCommand cmd = new SqlCommand("IssueUpdate", con);\n        cmd.CommandType = CommandType.StoredProcedure;\n        cmd.Parameters.Add("@BookID", SqlDbType.Int).Value = "Enter Value here";\n        cmd.Parameters.Add("@BookName", SqlDbType.NVarChar, 50).Value = "Enter Value here";\n        cmd.Parameters.Add("@DateIssue", SqlDbType.DateTime).Value = "Enter Value here";\n        cmd.Parameters.Add("@ReturnDate", SqlDbType.DateTime).Value = "Enter Value here";\n        cmd.Parameters.Add("@PersonID", SqlDbType.Int).Value = "Enter Value here";\n        cmd.ExecuteNonQuery();\n        con.Close();\n        storedproc();\n    }\n    catch (Exception ex) \n    {\n        Console.WriteLine("SqlError" + ex);\n    }\n}	0
28381079	28334359	Change MediaElement Source for Windows Phone Application in C#	mediaElement.Play()	0
28072039	28071986	First letter capital in string c#	label1.Text = FirstLetterToUpper("test text");	0
11866904	11862261	Nhibernate : Updating a child entity directly without inverse	Session.CreateQuery("update Risk set Closed = :completed where Id = :id")\n                    .SetInt32("id", id)\n                    .SetBoolean("completed", completed)\n                    .ExecuteUpdate();	0
31623138	31623063	C# String was not recognized as a valid DateTime	using System;\nusing System.Globalization;	0
12795711	12795674	Exception when converting UTC string to DateTime	DateTime TransformedReceivedDateTimeString = DateTime.Parse(ReceivedDateTimeString).ToUniversalTime();	0
22211225	22211094	ExecuteReader, Adding Values to List, index out of range	SqlCeCommand commandArbeitstage= new SqlCeCommand("select datepart(month, Datum) as Month, count(IDStundensatz) as Gesamt from tblstunden Where IDPersonal = @IDPersonal Group by datepart(month, Datum) Order By datepart(month, Datum)", verbindung);\n\ncommandArbeitstage.Parameters.Add("IDPersonal", SqlDbType.Int);\ncommandArbeitstage.Parameters["@IDPersonal"].Value = IDPersonal;\n\n\nSqlCeDataReader readerArbeitstage = commandArbeitstage.ExecuteReader();\nInt32[] Arbeitstage = new Int32[12];\n\nwhile (readerArbeitstage.Read())\n{\n    Arbeitstage[readerArbeitstage.GetInt32(0) - 1]  = readerArbeitstage.GetInt32(1));\n}\ntextBox53.Text = Arbeitstage[0].ToString();  // January\n// ... and so on up to 11	0
28989234	28989103	Send beep signal to Datalogic Barcodescanner in C#	// Send: ESC [ 6 q CR\n_serialPort.Write(new byte[] { 0x1B, 0x5B, 0x36, 0x71, 0x0D }, 0, 5);\n\n// Send: ESC [ 3 q CR\n_serialPort.Write(new byte[] { 0x1B, 0x5B, 0x33, 0x71, 0x0D }, 0, 5);\n\n// Send: ESC [ 7 q CR\n_serialPort.Write(new byte[] { 0x1B, 0x5B, 0x37, 0x71, 0x0D }, 0, 5);	0
10897728	10897383	Read XML file with LINQ and create object with IEnumerable propety	var it = db.Descendants("app")\n                    .OrderBy(app => app.Attribute("name").Value)\n                    .Select(app => new Apps() {\n                        Name = app.Attribute("name").Value,\n                        Logs = app.Descendants("log").Select(a =>\n                            new Logs() {\n                                Name = a.Attribute("name") != null ? a.Attribute("name").Value : null,\n                                Path = a.Attribute("path") != null ? a.Attribute("path").Value : null,\n                                Filename = a.Attribute("filename") != null ? a.Attribute("filename").Value : null\n                            }).ToList()\n                    }).ToList();	0
24818744	24818502	PR_SEARCH_KEY using EWS	ExtendedPropertyDefinition eDef = new ExtendedPropertyDefinition(0x300B, MapiPropertyType.Binary);\n        PropertySet prop = BasePropertySet.IdOnly;\n        prop.Add(eDef);\n        ItemView ivItemView = new ItemView(1000);\n        ivItemView.PropertySet = prop;\n        FindItemsResults<Item> fiResults = Inbox.FindItems(ivItemView);\n        foreach (Item itItem in fiResults) {\n            Byte[] PropVal;\n            String HexSearchKey;\n            if (itItem.TryGetProperty(eDef, out PropVal)) {\n                HexSearchKey = BitConverter.ToString(PropVal).Replace("-", "");\n                Console.WriteLine(HexSearchKey);\n            }\n\n        }	0
6465911	6455071	C# How-to send ENTER from program?	HtmlElementCollection es = webBrowser1.Document.GetElementsByTagName("input");\nHtmlElement ele = es[5];\nele.InvokeMember("Click");	0
21099714	21099011	How to get data from database with Entity Framework?	BindingSource bs = new BindingSource();\n        bs.DataSource = typeof(Book); // Book is a type of your Entity class\n\n        db.Book.ToList().ForEach(n => bs.Add(n)); \n        dgv.DataSource = bs;	0
33976182	33976130	null references for Random integers	public class ContactFormViewModel\n{\n    private Random Random { get; set; }\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public string EmailAddress { get; set; }\n    public string Message { get; set; }\n    public int Val1 { get; set; }\n    public int Val2 { get; set; }\n\n    public ContactFormViewModel()\n    {\n        Val1 = Random.Next(1,9);\n        Val2 = Random.Next(6,19);\n    }\n}	0
8243619	8243003	Forcing linq to perform inner joins	NOT NULL	0
5498184	5498157	Overloading a method based on parameter value?	public class Calc\n    {\n        public Calc(string sourceName, string newString )\n        {\n            calcOperator = Operator.Concat;\n            sourceType = dataType;\n        }\n\n        public Calc(int startindex, int  count )\n        {\n            calcOperator = Operator.PadLeft;\n            sourceType = dataType;\n        }\n}	0
22460667	22460071	How to convert List<string[]> to string[,]?	string[,] newArray = new string[newTotalRows, 3];\nfor (int i = 0; i < NameList.Count; i++) \n{\n    for (int j = 0; j < NameList[i].Length; j++)\n    {        \n        newArray[i, j] = NameList[i][j];\n    }\n}	0
4881832	4878929	C# Searching a listBox	List<string> items = new List<string>();\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        items.AddRange(new string[] {"Cat", "Dog", "Carrots", "Brocolli"});\n\n        foreach (string str in items) \n        {\n            listBox1.Items.Add(str); \n        }\n    }\n\n    private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        listBox1.Items.Clear();\n\n        foreach (string str in items) \n        {\n            if (str.StartsWith(textBox1.Text, StringComparison.CurrentCultureIgnoreCase))\n            {\n                listBox1.Items.Add(str);\n            }\n        }\n    }	0
33239939	33238403	how to select from filtervalues where genre comma delimited values contain only what is selected	self.filterProducts = ko.computed(function () {\n    return ko.utils.arrayFilter(self.products(),\n    function (product) {\n            var genreValues = product.genre.split(",");\n            var matches = ko.utils.arrayFilter(genreValues, function (genre) {\n                return self.filterValues.indexOf(genre.trim()) >= 0;\n            });\n            return matches.length == self.filterValues().length;\n    });\n});	0
19359695	19359560	Linking two lists in C#	private void combo_car_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (combo_car.SelectedIndex != -1)\n        {\n            textBox1.Text = listBox2[combo_car.SelectedIndex].ToString();\n        }           \n    }	0
20442456	20442340	scanning a matrix diagonally for the largest product of four adjacent numbers along a diagonal line and stating it's starting postion	for (int z = 0; z <= 16; z ++)	0
32519845	32503272	Multiple callback for one notification pushsharp window phone	var channel = new WindowsPushChannelSettings("NotificationFra", "ms-app://s-1-15-2-3763039301-", "bJl6kdPqXWtOclINfKNC");\n        push.RegisterService<WindowsToastNotification>(new WindowsPushService(channel));	0
18419522	18382833	Go from windowed mode to fullscreen	//Update() method\n        if (CurrentGameState == gameState.gameLoading)\n        {\n            if (Keyboard.GetState().IsKeyDown(Keys.Enter))\n            {\n                graphics.ToggleFullScreen(); //?\n            }\n            graphics.ApplyChanges();\n        }	0
29649297	29633974	How do I make changes to my local db in asp.net MVC 5	update-database	0
24615874	24614401	I want to detect a usb device via asp.net C# web page	chrome.usb.getDevices(enumerateDevicesOptions, callback);\n\n\nfunction onDeviceFound(devices) {\nthis.devices=devices;\nif (devices) {\n  if (devices.length > 0) {\n    console.log("Device(s) found: "+devices.length);\n  } else {\n    console.log("Device could not be found");\n  }\n} else {\n  console.log("Permission denied.");\n}\n}\n\nchrome.usb.getDevices({"vendorId": vendorId, "productId": productId}, onDeviceFound);	0
13260997	13260964	Cast to Int from a VB Collection	foreach (object FieldId in oHeaders)\n{\n    int value = Int32.Parse(FieldId.ToString());\n}	0
33214409	33213088	Entity Framework 6 Update Many to Many without updating or loading Child	public ActionResult ReceiveOrder(Address address)\n{\n    EFDbContext context = new EFDbContext();\n\n    context.Set<Addresses>().Attach(address);\n    foreach(Product p in address.Products) {\n        context.Set<Products>().Attach(p);\n    }\n    context.Entry(address).State = EntityState.Added; \n\n    context.SaveChanges();\n    context.Dispose();\n    return Json(new { success = true, responseText = "Okay" },\n            JsonRequestBehavior.AllowGet);\n}	0
33223871	33223624	Execute file from USB	var dir = Environment.CurrentDirectory;\nEnvironment.CurrentDirectory = Path.Combine(dir, "data", "install");\nSystem.Diagnostics.Process.Start("install2.exe");\nEnvironment.CurrentDirectory = dir;	0
1844574	1844553	Need a deterministic algorithm to generate a resource domain prefix for a given path in an evenly distributed fashion	Math.Abs(path.GetHashCode()) % resourceDomainCount	0
31789538	31191308	Can I use .NET Newtonsoft JSON package (with or without Linq) to deserialize this oddly formatted JSON response?	dynamic jobject = JObject.Parse(response);\nJArray jArray = jobject.data;\n\nforeach (JToken appointment in jArray)\n           { \n               parentName = appointment[1];\n               startMinute = appointment[5];\n               . . .\n           }	0
19598119	19597997	How can I set all negative values in a dictionary to be zero?	public class ValidatedDictionary : IDictionary<string, int>\n{\n    private Dictionary<string, int> _dict = new Dictionary<string, int>();\n    protected virtual int Validate(int value)\n    {\n        return Math.Max(0, value);\n    }\n    public void Add(string key, int value)\n    {\n        _dict.Add(key, Validate(value));\n    }\n\n    public bool ContainsKey(string key)\n    {\n        return _dict.ContainsKey(key);\n    }\n    // and so on: anywhere that you take in a value, pass it through Validate	0
31294546	31294429	Moving from VB.net to C#	string strNodesToHide = "100, 500, 900";\n\nSiteMapNode node = e.Node.DataItem as SiteMapNode;\n\nif (node["securityLevel"].length != 0) {\n  if (strNodesToHide.indexOf(node["securityLevel"]) > -1) {\n    e.Node.Parent.ChildNodes.Remove(e.Node);\n  }\n}	0
26115942	26115572	Devexpress GridView Selected Row	void TraverseRows(ColumnView view) {\n    for (int i = 0; i < view.DataRowCount; i++) {\n        object row =  view.GetRow(i);\n        // do something with row\n    }\n}	0
6135417	6135361	Datagrid extra column	dataGrid.RowHeaderWidth = 0;	0
8792505	8792441	How do I get my .NET application's path (not the path of the application that started my application)	Assembly.GetExecutingAssembly().Location	0
24899831	24899727	How to cancel winform button click event?	class ConfirmButton:Button\n    {\n    public ConfirmButton()\n    {\n\n    }\n\n    protected override void OnClick(EventArgs e)\n    {\n        DialogResult res = MessageBox.Show("Would you like to run the command?", "Confirm", MessageBoxButtons.YesNo\n            );\n        if (res == System.Windows.Forms.DialogResult.No)\n        {\n            return;\n        }\n        base.OnClick(e);\n    }\n}	0
9239680	9239646	Issue with textbox rounding a number	string number = listView1.SelectedItems[0].SubItems[11].Text;	0
347907	347818	Using Moq to determine if a method is called	static void Main(string[] args)\n{\n        Mock<ITest> mock = new Mock<ITest>();\n\n        ClassBeingTested testedClass = new ClassBeingTested();\n        testedClass.WorkMethod(mock.Object);\n\n        mock.Verify(m => m.MethodToCheckIfCalled());\n}\n\nclass ClassBeingTested\n{\n    public void WorkMethod(ITest test)\n    {\n        //test.MethodToCheckIfCalled();\n    }\n}\n\npublic interface ITest\n{\n    void MethodToCheckIfCalled();\n}	0
27291908	27276001	Get Created date from local path via asp.net	DateTime.Now	0
27976575	27976534	Avoid XML Escape Double Quote	settings.NewLineHandling = NewLineHandling.None;\nsettings.CheckCharacters = false;	0
33424558	33424194	Prevent Entity object from being inserted using Linq2Sql	db.Persons.Add(newPerson)	0
1243993	1243868	Get html tags embedded in xml using linq	static void Main(string[] args)\n    {\n        string xml = "<root><item><title><p>some title</p></title></item></root>";\n\n        XDocument xdoc = XDocument.Parse(xml);\n        XElement te = xdoc.Descendants("title").First();\n        using (XmlReader reader = te.CreateReader())\n        {\n            if (reader.Read())\n                title = reader.ReadInnerXml();\n        }\n    }	0
10910604	10899789	Aspose.Email assembly to check a mail server ListMessages method fails	ExchangeWebServiceClient client = new ExchangeWebServiceClient("https://exchange-server-host/ews/Exchange.asmx", "username", "password", "domain");	0
400325	400113	Best way to implement keyboard shortcuts in a Windows Forms application?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n  if (keyData == (Keys.Control | Keys.F)) {\n    MessageBox.Show("What the Ctrl+F?");\n    return true;\n  }\n  return base.ProcessCmdKey(ref msg, keyData);\n}	0
29744057	29699106	How to make SingleChoiceAction_execute Synchronous?	var choiceAction = (menuItem.ActionProcessor as MenuActionItemBase).Action as SingleChoiceAction;\nbool usePostBack = (choiceAction as ActionBase).Model.GetValue<bool>("IsPostBackRequired");	0
12680266	12680106	starting a new thread and calling a method with arguments C#	Thread oThread = new Thread(new ThreadStart(() => { sendEMailThroughOUTLOOK(recipient, subjectLine, finalbody); }));	0
22809370	22808348	Using embedded Icon for Tray in c#	notico.Icon = Properties.Resources.iconname;	0
5152816	5152790	Value of an Enum	int value = (int)MyEnum.MyEnumCode;	0
14576266	14576224	Using timer to run application inside NUNIT	[Test]\nvoid TestFiles()\n{\n    using(var process = Process.Start("app.exe"))\n    {\n        Thread.Sleep(1000);\n        process.Kill();\n        process.WaitForExit();\n    }\n\n    // Check your files now\n}	0
28802607	28802582	Not Recognized as a valid datetime. Unknown word starting at index 0	for (int x = 0; x < listBox1.Items.Count; x++)\n{\n    DateTime z = DateTime.Parse(listBox2.Items[x].ToString());\n    DateTime c = DateTime.Parse(listBox3.Items[x].ToString());\n    TimeSpan w = c.Subtract(z);\n}	0
23066717	23066484	Assigning values in group of Labels by using LINQ	myLabel.Text = ( object.Exists(x=>x.Item1 == countryCode)? objects.FirstOrDefault(x=>x.Item1==countryCode).Item2 : "";	0
936126	936114	How can I create a string array of each character in a string in C#?	string   A = "ABCDEFG";\nstring[] C = A.Select(c => c.ToString()).ToArray();	0
16236442	16236392	How to clear a textbox once a button is clicked in WPF?	TextBoxName.Text = String.Empty;	0
10640246	10640200	displaying varying results in a view from same controller action	public ActionResult ShowCourseId(int StudentId)\n{\n    var studentCourses = (from c in course.vwCourse\n                          where c.StudentID == StudentId\n                          group c by c.CourseID into g\n                          select g.FirstOrDefault()).ToList();\n\n    if(studentCourses  == null || !studentCourses .Any())\n    {\n        studentCourses  = (from c in course.vwCourse\n                           group c by c.CourseID into g\n                           select g.FirstOrDefault()).ToList();\n    }\n\n    ViewData.Model = studentCourses;\n    return View();\n}	0
11913724	11913567	Deleting row in a table not workng	public bool removeStock(string user_name,string stock_symbol) \n{ \n    user_name = user_name.Trim(); \n    stock_symbol = stock_symbol.Trim(); \n    string statement = "DELETE FROM users_stocks " + \n                        "WHERE user_name = @name AND stock_symbol = @stock" ; \n    SqlCommand cmdnon = new SqlCommand(statement, connection); \n    try \n    { \n        cmdnon.Parameters.AddWithValue("@name", user_name);\n        cmdnon.Parameters.AddWithValue("@stock", stock_symbol);\n        connection.Open(); \n        int num = cmdnon.ExecuteNonQuery(); \n        connection.Close(); \n        return true; \n    } \n    catch (SqlException ex) \n    { \n        Console.WriteLine(ex.ToString()); \n        connection.Close(); \n        return false; \n    } \n}	0
8463917	8462539	Retrieving Total amount of RAM on a computer	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        Console.WriteLine("You have {0} bytes of RAM",\n            new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);\n        Console.ReadLine();\n    }\n}	0
18212143	18210030	Get PixelValue when click on a picturebox	private void pictureBox2_MouseUp(object sender, MouseEventArgs e)\n{\n    Bitmap b = new Bitmap(pictureBox1.Image);\n    Color color = b.GetPixel(e.X, e.Y);\n}	0
10612946	10612828	How to find index of the lowest value in the listbox c#	lowestlow.Items.IndexOf(lowestlow.Items.FindByValue(llvalue))	0
28764079	28763941	DataGrid using BindingList refresh	urBindingList.ResetBindings();	0
14823604	14823400	How to create an array of User Controls programmatically	for (int i = 0; i < 10; i++)\n{\n    pnlContent.Controls.Add(Page.LoadControl("ucDemo.ascx"));\n}	0
5019171	5019067	Problem using a Stored Proc to read data from a .CSV file to a database	foreach(DataRow row in myDataTable.Rows) {\n  foreach(DataColumn col in row.Columns) {\n    String value = row[col].Value\n    StoreValue(row.Name, col.Name, value); // <-- this would call your proc.\n  }\n}	0
8008243	8008031	Can not update YAxis in ZedGraph with NumericUpDown	zedGraphControl1.Refresh();	0
21142023	21141840	Send email to address windows phone	using Microsoft.Phone.Tasks;\nEmailComposeTask emailComposeTask = new EmailComposeTask();\n\nemailComposeTask.Subject = "message subject";\nemailComposeTask.Body = "Append all your control strings here";\nemailComposeTask.To = "recipient@example.com";\nemailComposeTask.Cc = "cc@example.com";\nemailComposeTask.Bcc = "bcc@example.com";\n\nemailComposeTask.Show();	0
21340940	21340783	How to create a byte array that will have a BCC (Block Check Character) of a given value (0)?	0x32(#) = 0x23(2)^0x11	0
7033815	7033744	using MemoryStreams as content sources when attaching files to email, C#	myMemoryStream.Position = 0	0
27662006	27658934	How to set phone in silent mode or equivalent?	HRESULT SetVolume([in]  double Volume);	0
12579669	12579559	Linq orderby, start with specific number, then return to lowest	List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };\nint num = 4;\nvar newList = list.SkipWhile(x=>x!=num)\n                    .Concat(list.TakeWhile(x=>x!=num))\n                    .ToList();	0
4897337	4897301	need to show changed text after comparing two strings	static void Main(string[] args)\n{\n    string strComplete = "stackoverflow is good, I mean, stackoverflow is really good";\n    string strSearch = "stackoverflow";\n    Console.WriteLine(FormatString(strComplete, strSearch));\n    Console.ReadKey();\n}\n\nprivate static string FormatString(string strComplete, string strSearch)\n{\n    string strSpannedSearch = string.Format("{0}{1}{2}", "", strSearch, "");\n    return strComplete.Replace(strSearch, strSpannedSearch);            \n}	0
4254279	4254225	Opening an image file into WritableBitmap	BitmapImage bitmap = new BitmapImage(new Uri("YourImage.jpg", UriKind.Relative));\nWriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);	0
1239223	1237345	Mono.Cecil - How to get custom attributes	AssemblyDefinition assembly = AssemblyFactory.GetAssembly(pathBin);\nassembly.MainModule.Types[0].Methods[1].CustomAttributes[0].Constructor.DeclaringType.ToString()	0
11978195	11978154	add image to asp:linkbutton?	in page_load event when you click and make a postback change image\n\n if (IsPostBack)\n       {                  \n                 ImageButton1.ImageUrl = "~/Images/newimage.gif";                           \n\n       }	0
2858044	2852369	Switching DataSources in ReportViewer in WinForms	reportViewer1.Reset();	0
7373686	7373661	IDictionary AddAndReturn Extension For Fluent Interface	var poo =  new Dictionary<string,string> {\n        { "key1", "value1" },\n        { "key2", "value2" },\n        { "key3", "value3" }, // this is permissible\n};	0
17500661	17500624	Confused by calculation	8.3333333333 * 10^-4\n= 8.3333333333 times ( ten to the power of -4 )\n= 8.3333333333 * 0.0001\n= 0.00083333333\nN.b. After rounding	0
8755532	8755450	C# TPL lock shared object between tasks vs populating it with the results from Task(TResult) tasks	var workResults = _objects.AsParallel().Select(DoTaskWork);\nforeach(var r in workResults)\n{\n    result.Add(r);\n}	0
7158152	6490091	Reading a dbase table design	adapter.FillSchema(ds, SchemaType.Mapped);	0
25013680	25012749	How to perform combinatoric task in C#	private static void GetCombination(ref List<string[]> list, string[] t, int n, int m, int[] b, int M)\n{\n    for (int i = n; i >= m; i--)\n    {\n        b[m - 1] = i - 1;\n        if (m > 1)\n        {\n            GetCombination(ref list, t, i - 1, m - 1, b, M);\n        }\n        else\n        {\n            if (list == null)\n            {\n                list = new List<string[]>();\n            }\n            string[] temp = new string[M];\n            for (int j = 0; j < b.Length; j++)\n            {\n                temp[j] = t[b[j]];\n            }\n            list.Add(temp);\n        }\n    }\n}\n\npublic static List<string[]> GetCombination(string[] t, int n)\n{\n    if (t.Length < n)\n    {\n        return null;\n    }\n    int[] temp = new int[n];\n    List<string[]> list = new List<string[]>();\n    GetCombination(ref list, t, t.Length, n, temp, n);\n    return list;\n}	0
11238462	11238439	Convert Sql Statement into Linq for use with C#, Entity Framework, MVC3	var result = (from obj in yourDataContext.yourEntity\n             where obj.ObjId == currentUserId\n             select obj).FirstOrDefault();	0
14875162	14872415	Logging Mechanism in Windows 8 Application?	Windows.UI.Xaml.Application	0
8038123	8029053	how to access controls inside dataRepeater	dataRepeater1.CurrentItem.Controls["TextBox1"].Text	0
25450093	25448482	Compare Two Lists and find similar data	static public void ProcessData(List<ClassA> clsA, List<ClassB> clsB)\n    {\n        var newlist = (from a in clsA \n                             from b in clsB \n                             where a.data == b.data && a.value == b.value \n                             select a).ToList();\n    }	0
16803699	16803572	Sorting a FileInfo[] based using Natural Sorting on the filename (SQL files)	IEnumerable<FileInfo> fileInfosOrdered = fileInfos.OrderBy(fileInfo => int.Parse(fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('-'))));	0
34517633	34517470	Retrieve column names and types from SQL Server to DataTable C#	private static DataTable getReadingTableFromSchema()\n{\n    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalDbConnnectionString"].ConnectionString))\n    {\n        string sql = "SELECT * FROM [Readings]";\n        conn.Open();\n        SqlCommand cmd = new SqlCommand(sql, conn);\n        DbDataAdapter da = new SqlDataAdapter(cmd);\n        DataTable dtbl = new DataTable();\n        da.FillSchema(dtbl, SchemaType.Source);\n        return dtbl;\n    }\n}	0
2070876	2066048	How to make a System.Configuration.Install.Installer to get a variable from the Setup project?	public override void Install(IDictionary stateSaver)\n{\n      // If you need to debug this installer class, uncomment the line below\n      //System.Diagnostics.Debugger.Break();\n\n       string productName = Context.Parameters["ProductName"].Trim();\n\n       string whateveryouwant== Context.Parameters["whateveryouwant"].Trim();\n}	0
31804976	31803810	OpenFileDialog with many extensions	ofd.Filter = "Supported extensions | *.0??;*.1??;*.2??;*.3??;*.4??;*.5??;*.6??;*.7??;*.8??;*.9??";	0
10612309	10612207	to compare double and decimal should I cast double to decimal or decimal to double?	private static int Compare(double d, decimal m)\n{\n    const double decimalMin = (double)decimal.MinValue;\n    const double decimalMax = (double)decimal.MaxValue;\n    if (d < decimalMin) return -1;\n    if (d > decimalMax) return 1;\n    return ((decimal)d).CompareTo(m);\n}	0
12736431	12736380	C# Replace two specific commas in a string with many commas	int idxFirstComma = line.IndexOf(',');\nint idxSecondComma = line.IndexOf(',', idxFirstComma+1);\nint idxThirdComma = line.IndexOf(',', idxSecondComma+1);	0
18845264	18845056	Html tag in string C#	string s = "<img src=\""+getImageFromFile("~/Content/skin/Office2010Blue.png","image/png")+"\" style=\"width: 100px;height: 100px;\" />";\nvar html = new HtmlDocument();\n\n\n\n@html.CreateElement(s)\n\n\npublic string getImageFromFile(String url, String imgType)\n{\n    using (FileStream fs = new FileStream(Server.MapPath(url), \n                                   FileMode.Open, \n                                   FileAccess.Read)){\n        byte[] filebytes = new byte[fs.Length];\n        fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));\n    }\n    string encodedData = Convert.ToBase64String(filebytes);\n    return "data:"+imgType+";base64,+"encodedData; \n}	0
1568473	1568387	Aggregate detail values in Master-Detail view	class Master : INotifyPropertyChanged\n{\n    public int Id { get; set; } // + property changed implementation \n    public string Name { get; set; } // + property changed implementation\n    public double Sum {get {return Details.Sum(x=>x.Value);}}\n\n    public DeeplyObservableCollection<Detail> Details { get; }\n\n    // hooked up in the constructor\n    void OnDOCChanged(object sender, CollectionChangedEventArgs e) \n    { OnPropertyChanged("Sum"); }\n}	0
16099325	16099288	How to access properties of an object in a list?	typeOfImage = myImages.Select(image => image.AnyPropertyYouNeed).ToList();	0
17882520	17882145	Loading Raw XML Into Text View with Mono.Android	XmlDocument doc = new XmlDocument();\n        doc.Load(<your doc path>);	0
4667174	4667123	How do i buffer an image from external link	var webClient = new WebClient();\nusing(var fileStream = webClient.OpenRead("http://www.lokeshdhakar.com/projects/lightbox2/images/image-2.jpg")) \n{\n    byte[] fileContent = new byte[fileStream.Length];       \n}	0
15733677	15733612	Convert UTC to specific time zone	TimeZoneInfo.ConvertTimeFromUtc	0
24829968	24829440	How to get the HTML encoding right in C#?	Console.OutputEncoding = System.Text.Encoding.Unicode;	0
7331894	7331802	Date Time Encoding	31/10/2011 10:41:45\n\n*/*/** *:*:*\n\n*******	0
27871522	27870429	Determine file size for sitecollections and subsites using subfolders in SharePoint 2007	folderSize += file.TotalLength + file.Versions.Cast<SPFileVersion>().Sum(f => (long)f.Size);	0
8979743	8979708	How to declare and use arrays in C#	motionCam[1] = "Stop";	0
17936368	17822902	overwrite file in Zipping	foreach (String filename in filenames)\n            {\n                strRptFilename = filename.Substring(filename.LastIndexOf("\\") + 1);\n\n                outputStream = new MemoryStream();\n\n                FileStream fs = File.OpenRead(@"C:\uploaded\" + strRptFilename);\n\n                int bufferSize = 2048;\n                int readCount;\n                byte[] buffer = new byte[bufferSize];\n                readCount = fs.Read(buffer, 0, bufferSize);\n                while (readCount>0)\n                {\n                    outputStream.Write(buffer, 0, readCount);\n                    readCount = fs.Read(buffer, 0, bufferSize);\n\n                }\n                fs.Close();\n                outputStream.Position = 0;\n\n\n                ZipFile(ref outputStream, strRptFilename, ref oZipStream);\n                fs.Close();\n                outputStream.Close();\n\n            }	0
23436734	23436652	How to generate a sample xml from a class file	var instance = new SiteDefinition();\nvar serializer = new XmlSerializer(typeof(SiteDefinition));\n\nusing(var writer = new StreamWriter("C:\\Path\\To\\File.xml"))\n{\n    serializer.Serialize(writer, instance);\n}	0
31811915	31811525	How to disable a textbox without fading text?	Color color = textbox1.BackColor ;\ntextbox1.BackColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);\n\ncolor = textbox1.ForeColor ;\ntextbox1.ForeColor = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);	0
22669149	22668800	How do I accept an int in xml and serialize it as an enum	public enum AmenityCode \n{\n       [XmlEnum("1")]\n       AirConditioning = 1,\n       [XmlEnum("2")]\n       AirportTranfer = 2\n}	0
18535729	18534424	Enum with multiple descriptions	public enum Gender\n{\n    Man = 1,\n    Woman = 2\n}\n\npublic interface IGenderStrategy\n{\n    string DisplayName(Gender gender);\n}\n\npublic class ParentStrategy : IGenderStrategy\n{\n    public string DisplayName(Gender gender)\n    {\n        string retVal = String.Empty;\n        switch (gender)\n        {\n            case Gender.Man:\n                retVal =  "Dad";\n                break;\n            case Gender.Woman:\n                retVal =  "Mom";\n                break;\n            default:\n                throw new Exception("Gender not found");\n        }\n        return retVal;\n    }\n}\n\npublic static class EnumExtentions\n{\n    public static string ToValue(this Gender e, IGenderStrategy genderStategy)\n    {\n        return genderStategy.DisplayName(e);\n    }\n}\n\npublic class Test\n{\n    public Test()\n    {\n        Gender.Man.ToValue(new ParentStrategy());\n    }\n}	0
12836423	12836348	In C# arrays, how not to create duplicated random numbers?	if (i!=y && Array.Equals(lottoszamok[i], lottoszamok[y]))	0
6088587	6088567	creating an alias for a function name in C#	public static class Extensions \n{\n    public static void B(this Test t)\n    {\n       t.A();\n    }\n}	0
6859258	6859216	How to simplify update query in mysql?	SET t1p = \nCASE t1p\n WHEN '1' THEN 'AB'\n WHEN '2' THEN 'OD' \nEND	0
23528179	23528049	a method to find the nearest multiple of 2pi	return targetAngle + Math.Round((currentAngle - targetAngle)/(2*Math.Pi))*2*Math.Pi;	0
25301765	25301627	How to Pass multiple properties from ajax post call to aspx page webmethod?	[System.Web.Services.WebMethod]\npublic static string PostData(string title, string songPath, //...etc)\n{   \n    MyClass myObj = new myClass();\n    myObj.title = title;           \n    myObj.songPath = songPath;\n    return "done";\n}	0
28743668	28742618	Adding a table to the Membership-database	public DbSet<DownloadInformation> Download{ get; set; }	0
8281729	8281696	How can I check how many children does a node have?	iterator.Current.SelectChildren(XPathNodeType.All).Count	0
8229412	8229198	Wildcards in a Query String C#	string[] myUrls = new string[] {\n  "http://www.testurl.com/page?key=55555",\n  "http://www.testurl.com/page?key=555556789",\n  "http://www.testurl.com/page?foo=bar&key=55555&baz=938355555"};\n\nstring myToken = "key=55555";\nbool exists;\n\nforeach(string url in myUrls)\n{\n    System.Uri uri = new System.Uri(url);\n    string q = uri.GetComponents(UriComponents.Query, UriFormat.Unescaped);\n\n    if (q.Split('&').Any(x=>x== myToken))\n    {\n       Console.WriteLine(string.Format("found it in '{0}'", url));\n    }\n}	0
9757063	9757018	How to monitor Textfile and continuously output content in a textbox	public static Watch() \n{\n    var watch = new FileSystemWatcher();\n    watch.Path = @"D:\tmp";\n    watch.Filter = "file.txt";\n    watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite; //more options\n    watch.Changed += new FileSystemEventHandler(OnChanged);\n    watch.EnableRaisingEvents = true;\n}\n\n/// Functions:\nprivate static void OnChanged(object source, FileSystemEventArgs e)\n{\n    if(e.FullPath == @"D:\tmp\file.txt")\n    {\n        // do stuff\n    }\n}	0
12279925	12279803	How to combine many list items into one item?	var newList = ListOfImpacts.GroupBy(g => new {g.Source, g.Target})\n            .Select(g => new Impacts(g.Key.Source, g.Count(), g.Key.Target))\n            .ToList();	0
18851856	18850997	What information can be obtained from a Program GUID	System.Diagnostics.Process.Start("path to script here");	0
5690461	5686883	Unit testing with UIAutomation	[TestCleanup]\n    public void TearDown()\n    {\n        Dispatcher.CurrentDispatcher.InvokeShutdown();\n    }	0
2021253	2021202	c# Writing to a file without using using{}	void WriteInfo(string text)\n{\n    // Second parameter to StreamWriter ctor is append = true\n    using(StreamWriter sw = new StreamWriter(logFilePath, true))\n    {\n         sw.WriteLine(text);\n    }\n}	0
596378	596285	In domain-driven design, would it be a violation of DDD to put calls to other objects' repostiories in a domain object?	public DomainObject(delegate getApplicationsByBatchID)\n{\n    ...\n}	0
25824442	25824385	How to check if a target was not hit in WPF	bool isTargetHit;    \nprivate void OnMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n{\n    isTargetHit = false;\n\n    .......\n    VisualTreeHelper.HitTest(Drawing, \n                             null, \n                             MyCallback, \n                             new GeometryHitTestParameters(geom));\n\n    if(isTargetHit)\n    {\n        MessageBox.Show("You hit the target");\n    }\n    else\n    {\n        MessageBox.Show("You did not hit the target");\n    } \n}\n\nprivate HitTestResultBehavior MyCallback(HitTestResult result)\n{\n    isTargetHit = true;\n    return HitTestResultBehavior.Stop;\n}	0
7903879	7903129	How to get the value of a textbox on RadGrid ItemCommand event handler when using a Custom Command?	var gridEditFormItem = e.Item as GridEditFormItem ?? ((GridDataItem)(e.Item)).EditFormItem;\n\n                if (gridEditFormItem == null)\n                    throw new ApplicationException("gridEditFormItem is null");	0
10812657	10812629	GroupBy and count the unique elements in a List	var list = new List<string> { "Foo1", "Foo2", "Foo3", "Foo2", "Foo3", "Foo3", "Foo1", "Foo1" };\n\nvar grouped = list\n    .GroupBy(s => s)\n    .Select(group => new { Word = group.Key, Count = group.Count() });	0
1408180	1408057	Match Regular expression from a dictionary in C#	Dictionary<string, string> myCollection = new Dictionary<string, string>();\n\nmyCollection.Add("(.*)orange(.*)", "Oranges are a fruit.");\nmyCollection.Add("(.*)apple(.*)", "Apples have pips.");\nmyCollection.Add("(.*)dog(.*)", "Dogs are mammals.");\n// ...\n\nstring input = "tell me about apples and oranges";\n\nvar results = from result in myCollection\n              where Regex.Match(input, result.Key, RegexOptions.Singleline).Success\n              select result;\n\nforeach (var result in results)\n{\n    Console.WriteLine(result.Value);\n}\n\n// OUTPUT:\n//\n// Oranges are a fruit.\n// Apples have pips.	0
7878100	7870377	Gridview with bound parameter DateTime from Textbox throws DateTimeException when sorting	protected void tbTo_TextChanged(object sender, EventArgs e)\n    {\n        DateTime temp;\n\n        if(DateTime.TryParse(tbTo.Text,out temp)==false)\n        {\n            tbTo.Text = "";\n        }\n    }	0
29378262	29377910	Paint Event of Viewport3D	class MyViewPort : Viewport3D\n{\n    protected override void OnRender(DrawingContext drawingContext)\n    {\n        base.OnRender(drawingContext);\n    }\n}	0
16760950	16756225	how to verify that an XML file implements a specific schema	System.Xml.Schema.XmlSchemaSet xset = ...; // Loaded somehow\nSystem.Xml.XmlQualifiedName qn = ...; // LocalName + NamespaceURI\nif (xset.GlobalElements.Contains(qn))\n{\n    System.Xml.Schema.XmlSchemaElement el = (System.Xml.Schema.XmlSchemaElement)xset.GlobalElements[qn];\n    if (!el.IsAbstract)\n    {\n        // The XML file may implement the schemata loaded in this schema set.\n    }\n}	0
17657691	17657398	C# Detect if usb device is inserted	using System.IO.DriveInfo;\n\n var availableDrives = DriveInfo.GetDrives()\n.Where(d=> d.IsReady && d.DriveType == DriveType.Removable);	0
5298445	5298311	Examining Binary File for Information using Bit Masks	ushort yourWord = firstByte << 8 | secondByte;	0
2222195	2215324	Multiple Left Joins against Entity Framework	var q = from cp in Context.ContentPages\n        where cp.ID == someId\n        select new \n        {\n            ID = cp.ID,\n            Name = cp.Name,\n            ContentPageZones = from cpz in cp.ContentPageZones\n                               where cpz.Content.IsActive\n                               select new \n                               {\n                                   ID = cpz.ID,\n                                   // etc.\n                               }\n        };	0
16116266	16032867	Accessing a table by name in Word using c#	Word.Application wordApp = new Word.Application();\nWord.Document wordDoc = wordApp.Documents.Open(@"C:\Users\username\Documents\HasTables.docx");\nvar tableID = wordDoc.Tables[1].GetHashCode();	0
19524692	19524105	How to block or restrict special characters from textbox	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    var regex = new Regex(@"[^a-zA-Z0-9\s]");\n    if (regex.IsMatch(e.KeyChar.ToString()))\n    {\n        e.Handled = true;\n    }\n}	0
22996476	22995714	Comparing dates with week, month and year using .NET	// ----------------------------------------------------------------------\npublic void WeekOfYear()\n{\n    Week week = new Week( 2014, 14 );\n    Console.WriteLine( "Week: {0}", week );\n    Console.WriteLine( "Year: {0}, Month: {1}", week.Start.Year, week.Start.Month );\n    Console.WriteLine( "NextWeek: {0}", week.GetNextWeek() );\n} // WeekOfYear	0
1376908	1376802	Do I need to call InsertOnSubmit for every row that references a main row?	Order order = new Order\n{\n    itemId     = (int)    data["itemNumber"],\n    address    = (string) data["address"]\n};\n\nOrderPerson orderPerson = new OrderPerson\n{\n    orderRoleId = RoleIds.Customer\n};\norder.OrderPersons.Add(orderPerson);\n\nOrderHistoryEntry historyEntry = new OrderHistoryEntry\n{\n    historyTypeId = HistoryIds.Ordered\n};\norder.OrderHistoryEntries.Add(historyEntry);\n\ndb.Orders.InsertOnSubmit(order);\n\ndb.SubmitChanges();	0
26555776	26545117	How to use generic hub in SignalR	public sealed class TestHub\n  : Hub<ITestClient>\n{\n  public override Task OnConnected()\n  {\n    this.Clients.Caller.SayHello("Hello from OnConnected!");\n    return base.OnConnected();\n  }\n\n  public void Hi()\n  {\n    // Say hello back to the client when client greets the server.\n    this.Clients.Caller.SayHello("Well, hello there!");\n  }\n}\n\npublic interface ITestClient\n{\n  void SayHello(String greeting);\n}	0
31361943	31361795	Find existing instance of Office Application	object word;\n    try\n    {\n        word = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");\n//If there is a running Word instance, it gets saved into the word variable\n    }\n    catch (COMException)\n    {\n//If there is no running instance, it creates a new one\n        Type type = Type.GetTypeFromProgID("Word.Application");\n        word = System.Activator.CreateInstance(type);\n    }	0
12229798	12229776	C# ignoring "duplicates" in a data table	var books = Books.GroupBy(x=>x.Title).Select(x=>x.First()).ToList();	0
6206344	6200779	create new multidimensional array and fill it with values from other arrays	static int[,] Combine(params int[][] arrays)\n    {\n        int[][] combined = CombineRecursive(arrays).Select(x=>x.ToArray()).ToArray();\n        return JaggedToRectangular(combined);\n    }\n\n    static IEnumerable<IEnumerable<int>> CombineRecursive(IEnumerable<IEnumerable<int>> arrays)\n    {\n        if (arrays.Count() > 1)\n            return from a in arrays.First()\n                   from b in CombineRecursive(arrays.Skip(1))\n                   select Enumerable.Repeat(a, 1).Union(b);\n        else\n            return from a in arrays.First()\n                   select Enumerable.Repeat(a, 1);\n    }\n\n    static int[,] JaggedToRectangular(int[][] combined)\n    {\n        int length = combined.Length;\n        int width = combined.Min(x=>x.Length);\n        int[,] result = new int[length, width];\n\n        for (int y = 0; y < length; y++)\n            for (int x = 0; x < width; x++)\n                result[y, x] = combined[y][x];\n\n        return result;\n    }	0
32079302	32079219	Compare string value to datagridview row 0 in any cell	string mat = "test";\nfor(int i=0;i<dataGridView1.Rows[0].Cells.Count;i++){\n        if(dataGridView1[0,i].Value != null && mat == dataGridView1[0,i].Value.ToString())\n        {\n            tst.Text = dataGridView1[1,i].Value.ToString();\n        }\n}	0
27245955	27245762	How to create IsDirty inside OnPropertyChange, but at the same time turn it off when entities are loaded from a database	Isdirty=false	0
4282007	4282000	Starting program in C# including all files	Process.Start(new ProcessStartInfo {\n    FileName         = Path.Combine(addressToFirstTibia, "Tibia.exe"), \n    WorkingDirectory = addressToFirstTibia \n});	0
10784815	10784740	C# Checking if a Property 'Starts/Ends With' in a csproj	Condition="$(Configuration.EndsWith('3.5'))"	0
23634911	23632785	HTML file doesn't change after editing	mysite/mypage.html?v=1	0
17189241	17159684	How to add Data To GridView From TextBox & DropDownList	protected void Button2_Click(object sender, EventArgs e)\n{\n    foreach (GridViewRow oItem in GridView1.Rows)\n    {\n        string str1 = oItem.Cells[0].Text;\n        string str2 = oItem.Cells[1].Text;\n        string str3 = oItem.Cells[2].Text;\n        insertData(str1, str2, str3);\n    }\n}\npublic void insertData(string str1,string str2,string str3)\n{\n    SqlConnection cn = new SqlConnection("Your Connection strig");\n    string sql = "insert into tbl1 (column1,column2,column3) values ('" + str1 + "','" + str2 + "','" + str3 + "')";\n    SqlCommand cmd = new SqlCommand(sql, cn);\n    cmd.ExecuteNonQuery();\n}	0
2333562	1361861	Accessing Sql FILESTREAM from within a CLR stored procedure	CREATE PROC ReadFromFilestream\n    (\n        @pfilestreamGUID    UNIQUEIDENTIFIER,\n        @pOffsetIntoData    INT,\n        @pLengthOfData      INT,\n        @pData              VARBINARY(MAX) OUTPUT\n    )\n    AS\n    BEGIN;\n        SELECT @pData  = SUBSTRING(ValueData, @pOffsetIntoData, @pLengthOfData)\n          FROM [MESL].DataStream\n         WHERE DataStreamGUID = @pfilestreamGUID;\n    END;	0
1884879	1884838	WPF listbox dynamically populated - how to get it to refresh?	ObservableCollection<string>	0
13773898	13769780	How to assign a value via Expression?	ComplexObj obj = new ComplexObj();\nExpression<Func<ComplexObj, object>> expression = obj => obj.Contacts[index].FirstName;\nobj.AssignNewValue(expression, firstName);\n\n    public static void AssignNewValue(this ComplexObj obj, Expression<Func<ComplexObj, object>> expression, object value)\n    {\n        ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object));\n        Expression targetExpression = expression.Body is UnaryExpression ? ((UnaryExpression)expression.Body).Operand : expression.Body;\n\n        var newValue = Expression.Parameter(expression.Body.Type);\n        var assign = Expression.Lambda<Action<ComplexObj, object>>\n                    (\n                        Expression.Assign(targetExpression, Expression.Convert(valueParameterExpression, targetExpression.Type)),\n                        expression.Parameters.Single(), valueParameterExpression\n                    );\n\n        assign.Compile().Invoke(obj, value);\n    }	0
22693621	22693284	Yield usage in a lengthy process	ObservableCollection<T>	0
8154244	8154144	How to call a function be called only after a event finished in the same class?	class A\n{\n    AutoResetEvent are = new AutoResetEvent(false);\n    public void Download()\n    {\n        are.Reset();\n        try\n        {\n            //Do your work here\n        }\n        finally\n        {\n            are.Set();\n        }\n    }\n    public void Query()\n    {\n        are.WaitOne();\n    }\n\n}	0
6819637	6819607	C# Converting a Percentage Value read from Excel to a Double	var inputText = "87.5%";\nvar doubleValue = Double.Parse(inputText.Replace("%", ""));	0
10161823	10161669	How to save an image from RGB pixels array?	int width = 1; // read from file\nint height = 1; // read from file\nvar bitmap = new Bitmap(width, height, PixelFormat.Canonical);\n\nfor (int y = 0; y < height; y++)\n   for (int x = 0; x < width; x++)\n   {\n      int red = 0; // read from array\n      int green = 0; // read from array\n      int blue = 0; // read from array\n      bitmap.SetPixel(x, y, Color.FromArgb(0, red, green, blue));\n   }	0
6502099	6501964	how to use split to get the middle value which retrieve from datagridview	var input = "A,B,C; A1,B1,C1; A2,B2,C2;";\nvar resultList = Regex.Matches(input, @".*?,(.*?),.*?;")\n    .Cast<Match>()\n    .Select(arg => arg.Groups[1].Value)\n    .ToList();\n\nvar firstValue = resultList[0];\nvar secondValue = resultList[1];\n\n// bind to a combobox\ncomboBox1.DataSource = resultList;\n\nvar comaSeparatedString = string.Join(",", resultList);	0
17197951	17146255	Using the WaveformTimeline Control in the WPF Sound Visualisation Library	myWave = new WaveformTimeline();	0
13829786	13828297	How to replicate what Excel does to plot a "Scatter with smooth lines" graph	Cubic Spline	0
14975407	14899380	How to get the value of the textbox which created dynamically with the Raduploader in code behind?	if (rada_attach.UploadedFiles.Count > 0) {\n    for (var index = 0; index < rada_attach.UploadedFiles.Count; ++index) {\n        var textBoxValue = rada_attach.UploadedFiles[index].GetFieldValue("TextBox");\n    }\n}	0
33314762	33314568	Is there any simple C# code example to invoke Main() with public modifier from outside?	foreach(Type type in assembly.GetTypes())\n{\n    foreach(MethodInfo methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))\n    {\n        if (methodInfo.Name == "Main" /*TODO: && methodInfo.Parameters is valid*/)\n        {\n            methodInfo.Invoke(null, new object[0]);\n        }\n    }\n}	0
6623264	6608043	Combining multi coloumn failover logic into a single property in Entity Framework 4.1	public class Part\n{ \n    public string PartNumber\n    {\n        get\n        {\n            return this.PartId ?? this.ChildPartId;\n        }  \n    }\n\n    internal string PartId { get; set; }\n    internal string ChildPartId { get; set; }\n}\n\n\n\npublic class PartsContext : DbContext\n{ \n    public DbSet<Part> Parts { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Part>().Ignore(e => e.PartNumber);   \n        base.OnModelCreating(modelBuilder);\n    }\n}	0
8152151	8152139	Get all +ve number count in LINQ	int[] a = {1, 2, 3, 0, 5, 0}; \nint x = a.Where(b => b != 0).Count();	0
24873259	24873182	split string to Dictionnary<string, int>	"content;123 contents;456 contentss;789"\n    .Split(' ')\n    .Select(x => x.Split(';'))\n    .ToDictionary(x => x[0], x => int.Parse(x[1]));	0
33687093	33558707	How to evaluate a dynamic expression using IronJS?	private static void Run()\n{\n        var ctx = new IronJS.Hosting.CSharp.Context();\n\n        dynamic a = ctx.Execute("var a = (((2+5)*1000)/((30-20)*7)); a;");\n        Console.WriteLine(a);\n}	0
12041062	12041009	Inserting a Qty Value	int qte1 = Convert.ToInt32(yourTextBox1.Text);;\nint qte2 = Convert.ToInt32(yourTextBox2.Text);;\n\nint result = qte1 + qte2;	0
18753234	18753134	issue with SaveFileDialog winforms	if (!String.IsNullOrEmpty(sd.FileName))\n{\n   using(var fileStream = sd.OpenFile())\n   {\n      //you can use the stream if you need it (otherwise just close it)\n   }\n\n   AddWorksheetToExcelWorkbook(sd.FileName);    \n}	0
31424974	31424820	Deleting a row from a Datatable if that row exists in another Datable	DataTable dt1 = new DataTable();\ndt1.Columns.Add("Name");\ndt1.Rows.Add("Apple");\ndt1.Rows.Add("Banana");\ndt1.Rows.Add("Orange");\n\nDataTable dt2 = new DataTable();\ndt2.Columns.Add("Name");\ndt2.Rows.Add("Apple");\ndt2.Rows.Add("Banana");\n\nList<DataRow> rows_to_remove = new List<DataRow>();\nforeach (DataRow row1 in dt1.Rows)\n{\n    foreach (DataRow row2 in dt2.Rows)\n    {\n        if (row1["Name"].ToString() == row2["Name"].ToString())\n        {\n            rows_to_remove.Add(row1);\n        }\n    }\n}\n\nforeach (DataRow row in rows_to_remove)\n{\n    dt1.Rows.Remove(row);\n    dt1.AcceptChanges();\n}	0
19947720	19947122	How to read root attribute by XPath in c#	// Load the document and set the root element.\nXmlDocument doc = new XmlDocument();\ndoc.Load(LocalPath);\nXmlNode rootNode = doc.DocumentElement;\nvar dat = rootNode.Attributes["Date"].Value;	0
21960533	21960499	How to get date from day of year	int a = 53;\nint year = DateTime.Now.Year; //Or any year you want\nDateTime theDate = new DateTime(year, 1, 1).AddDays(a - 1);\nstring b = theDate.ToString("d.M.yyyy");   // The date in requested format	0
9869800	9614288	TinyMCE Editor text is not showing while using it in Update Panel	var prm = Sys.WebForms.PageRequestManager.getInstance();\nprm.add_endRequest(function () {\n    TinyMCEEditor();\n});	0
25122002	25121512	How to get approximate file path?	void GetFilePathWithOutExtention(string path)\n{\n    // Get the name of the folder containing your path (for further remove in the items folder)\n    string parentFolderName = Directory.GetParent(path).FullName;\n\n    string[] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);\n    foreach(string fileItemPath in filePaths)\n    {\n        // Get the current folder without the initial folder path\n        string currentItemPath = Path.GetDirectoryName(fileItemPath).Remove(0, parentFolderName.Length);\n        Console.WriteLine(Path.Combine(currentItemPath, Path.GetFileNameWithoutExtension(fileItemPath)));\n    }\n}	0
18528264	18527140	Windows Phone 8 maps	MyMap.Layers.Add(layer0);	0
9749534	9739406	How to override headers in geckoFX?	GeckoPreferences.User["intl.accept_languages"] = "ru";	0
10727327	10727261	Showing webpage if user just changed password	if(DateTime.Now < datepasswordchanged.AddMinutes(5))	0
15942691	15942593	How to set custom format to DateTime.Now?	dateValue.ToString("dddd hh:mm tt", CultureInfo.CreateSpecificCulture("en-US"))	0
18384902	18384850	compare item to list of items, excluding the item being compared.	if (RadUpload1.UploadedFiles.Count > 1)\n{\n    for (int fileBuffer = 0; fileBuffer < RadUpload1.UploadedFiles.Count-1; fileBuffer++)\n    {\n        for (int fileList = fileBuffer + 1; fileList < RadUpload1.UploadedFiles.Count; fileList++)\n        {\n            if (RadUpload1.UploadedFiles[fileBuffer] != RadUpload1.UploadedFiles[fileList])\n            {\n//....	0
30253768	30253677	Excluding words from dictionary	HashSet<String> StopWords = new HashSet<String> { \n   "a", "an", "the" \n }; \n\n ...\n\n tempDict = file\n   .SelectMany(i => File.ReadAllLines(i)\n   .SelectMany(line => line.Split(new[] { ' ', ',', '.', '?', '!', }, StringSplitOptions.RemoveEmptyEntries))\n   .AsParallel()\n   .Select(word => word.ToLower()) // <- To Lower case \n   .Where(word => !StopWords.Contains(word)) // <- No stop words\n   .Distinct()\n   .GroupBy(word => word)\n   .ToDictionary(g => g.Key, g => g.Count());	0
673235	673197	Can we access one control Id registered in one aspx in to another ascx control,,	Control myControl = this.Page.FindControl("myControl");	0
27030131	27030100	Cannot get bytes[] from string	byte[] b1 = Encoding.UTF8.GetBytes(textBox1.Text);	0
2075680	2075642	How to get value from the object but its type is unreachable	object b = t["key"];\nType typeB = b.GetType();\n\n// If ID is a property\nobject value = typeB.GetProperty("ID").GetValue(b, null);\n\n// If ID is a field\nobject value = typeB.GetField("ID").GetValue(b);	0
17037587	17037323	Show message before long operation	lblSearchMessage.Text = "Please wait...";\nApplication.DoEvents(); \nvar info = proxy.FindProfiles();\nlblSearchMessage.Text = "Completed";	0
6011090	6010931	What wrong with my loop .Need to calculate a running total	private void Calculate(Player player)\n{\n    for (int i = 0; i < player.Game.Stages.Length; i++)\n    {\n        int firstThrow = player.Game.Stages[i].FirstTry;\n        int secondThrow = player.Game.Stages[i].SecondTry;\n        int sumFirstAndSecond = firstThrow + secondThrow;\n        if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)\n        {\n            int stageScore= player.Game.Stages[i].TotalScore + player.Game.Stages[i + 1].FirstTry;\n            player.Game.Stages[i].TotalScore = sumFirstAndSecond + stageScore;\n         }\n         else if (i > 0) player.Game.Stages[i].TotalScore = player.Game.Stages[i - 1].TotalScore + sumFirstAndSecond;\n    }\n}	0
32021836	32021812	Select Range get line Text in wpf richtextbox	rtb2.AppendText(line+"\r");	0
12983021	12982970	Get Entry from URL	Page.RouteData.Values["UserName"] as string	0
14849745	1627431	Fix embedded resources for a generic UserControl	// Empty stub class, must be in a different file (added as a new class, not UserControl \n// or Form template)\npublic class MyControl : UserControl\n{\n}\n\n// Generic class\npublic class MyControl<T> : MyControl\n{\n     // ...\n}	0
7015897	7015849	How do I implement a search feature with Entity Framework?	ExecuteStoreQuery()	0
16696098	16694867	Terminating Background Worker from a different class	public void AllocateTrades()\n{\n    if (!worker.CancellationPending)\n    {\n        Method1();\n    }\n\n    if (!worker.CancellationPending)\n    {\n        Method2();\n    }\n\n    if (!worker.CancellationPending)\n    {\n        Method3();\n    }\n}	0
27030241	27030161	Is it possible to create a generic Func<T><T>	static class CreateNull<T>\n{\n   public static Func<T> Default = () => default(T);\n}\n\nvar createNull = CreateNull<User>.Default;	0
18740348	18738756	Saving data to db with Entity splitting	public void Save(Report report)\n    {\n        assignSettingsToEntity(report);\n        assignElementsToEntity(report);\n        assignChartsToEntity(report);\n        context.Reports.Add(report);\n        context.SaveChanges();     \n    }\n\n        public void assignElementsToEntity(Report report)\n    {\n        report.ReportElements = new List<ReportElements>();\n        foreach (ReportElement e in report.Elements)\n        {\n            ReportElements temp = new ReportElements();\n            temp.ElementName = e.Line.Name;\n            temp.Active = true;\n            report.ReportElements.Add(temp);\n        }\n    }\n    public void assignChartsToEntity(Report report)\n    {\n        report.ReportCharts = new List<ReportCharts>();\n        foreach (string c in report.getSettings().Charts)\n        {\n            ReportCharts temp = new ReportCharts();\n            temp.ChartId = c;\n            temp.Active = true;\n            report.ReportCharts.Add(temp);\n        }\n    }	0
33296383	33296256	How to rename database and files with entity framework	Server srv = new Server(conn);\nDatabase database = srv.Databases["AdventureWorks"];\ndatabase.Rename("newName");	0
3965618	3965043	How to open a new form from another form	// MainForm\nprivate ChildForm childForm;\nprivate MoreForm moreForm;\n\nButtonThatOpenTheFirstChildForm_Click()\n{\n    childForm = CreateTheChildForm();\n    childForm.MoreClick += More_Click;\n    childForm.Show();\n}\n\nMore_Click()\n{\n    childForm.Close();\n    moreForm = new MoreForm();\n    moreForm.Show();\n}	0
4301272	4301253	How to utilize a REST API in ASP.Net 3.5?	using RazorGatorService; \n\nRazorGatorResult result = RazorGatorService.GetSomeFunkyStuff();	0
10608360	10607807	How to detect water level on an image?	Bitmap b = new Bitmap(Image.FromFile(@"C:\Temp\water.jpg"));\n// create filter\nEdges filter = new Edges();\n// apply the filter\nfilter.ApplyInPlace(b);\n\npictureBox1.Image = b;	0
4572415	4572398	How does string.Format table in as many objects as it wants?	void Method(params object[] objs)\n{\n    // use objs\n}	0
8653702	8653354	Can I test method call order with AAA syntax in Rhino-Mocks 3.6?	mock.AssertWasCalled(m=>m.Method1(), options => options.WhenCalled(w => mockService.AssertWasNotCalled(x=>x.Method2())));\nmock.AssertWasCalled(m=>m.Method2(), options => options.WhenCalled(w => mockService.AssertWasNotCalled(x=>x.Method3())));\nmock.AssertWasCalled(m=>m.Method3());	0
7448124	7442311	Parsing a SQL string in c#	using Microsoft.Data.Schema.ScriptDom;\nusing Microsoft.Data.Schema.ScriptDom.Sql;\n\n.....\n\n        string sql = "SELECT * FROM SomeTable WHERE (1=1";\n        var p = new TSql100Parser(true);\n        IList<ParseError> errors;\n\n        p.Parse(new StringReader(sql), out errors);\n\n\n        if (errors.Count == 0)\n            Console.Write("No Errors");\n        else\n            foreach (ParseError parseError in errors)\n                Console.Write(parseError.Message);	0
12438080	12438023	How to sort a List<Person> with sometimes equal entries?	personList.Sort((p1, p2)=>string.Compare(p1.Forename+p1.Surname, p2.Forname+ p2.Surname, true));	0
7885604	7884185	WPF: How to dynamically Add Controls in dynamically created WPF Window	var window = new Window();\nvar stackPanel = new StackPanel { Orientation = Orientation.Vertical };\nstackPanel.Children.Add(new Label { Content = "Label" });\nstackPanel.Children.Add(new Button { Content = "Button" });\nwindow.Content = stackPanel;	0
32614139	32610606	How to delete a Member in a "JsonArray" if I only know its "UniqiueId"?	JsonArray membersArray = ...\n\nIJsonValue memberValue = null;\n\nforeach (IJsonValue jsonValue in membersArray)\n{\n    if (jsonValue.GetObject().GetNamedString("UniqueId") == "MANU")\n    {\n        memberValue = jsonValue;\n        break;\n    }\n}\n\nif (memberValue != null)\n{\n    bool removed = membersArray.Remove(memberValue);\n}	0
3271831	3271791	Declaration suffix for decimal type	float f = 1.2f;\ndouble d = 1.2d;\nuint u = 2u;\nlong l = 2L;\nulong ul = 2UL;\ndecimal m = 2m;	0
8252908	8252859	Remove all XML elements with no attributes C#	void RemoveRecurence(XElement e) {\n      foreach(var child in e.Elements()) {\n           RemoveRecurence(child);\n      }\n\n      if (e.Attribute("name") == null && e.Attribute("ref") == null) {\n           e.ReplaceWith(e.Elements());            \n      }\n }	0
13234869	13234758	Converting string to int - datareader	string zipString = reader.GetString(ordinals[(int)Enums.MemberColumn.Zip]);\nmember.Zip = Int16.Parse(zipString);	0
30468544	30468496	How to save the result of a SQL query in a variable in c#?	using (SqlConnection conn = new SqlConnection(connString))\n{\n      SqlCommand cmd = new SqlCommand("SELECT @@IDENTITY FROM TABLE", conn);\n        try\n        {\n            conn.Open();\n            newID = (int)cmd.ExecuteScalar();\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }\n }	0
28673654	28673487	How to encrypt in php5 and decrypt in windows store 8.1 and c# using aescbc	AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(\n    System.Text.Encoding.UTF8.GetBytes(pass)\n));	0
18234607	18234483	How can I get some additional information from an EF DbUpdateException	The INSERT statement conflicted with the FOREIGN KEY constraint "FK_QuestionQuestionStatus". The conflict occurred in database "TestDb", table "dbo.QuestionStatus", column 'QuestionStatusId'.	0
5759674	5759288	Example to use a hashcode to detect if an element of a List<string> has changed C#	class Program\n{\n    static void Main(string[] args)\n    {\n        var list1 = new List<string>();\n        var list2 = new List<string>();\n        for (int i = 0; i < 10000; i++)\n        {\n            list1.Add("Some very very very very very very very long email" + i);\n            list2.Add("Some very very very very very very very long email" + i);\n        }\n\n        var timer = new Stopwatch();\n        timer.Start();\n        list1.SequenceEqual(list2);\n        timer.Stop();\n        Console.WriteLine(timer.Elapsed);\n        Console.ReadKey();\n    }\n}	0
20766836	20766788	Trying to get user input in an conse app to quicksort the input (strings)	for(int i = 0; i< unsorted.Length; i++)\n{\n   unsorted[i] = Console.ReadLine();\n}	0
11142167	11141899	XML parsing with XPath. C#	var document = new XPathDocument("http://flibusta.net/opds/opensearch?searchTerm=%D0%A2%D0%BE%D0%BB&searchType=books");\nXPathNavigator navigator = document.CreateNavigator();\nvar ns = new XmlNamespaceManager(navigator.NameTable);\nns.AddNamespace("atom", "http://www.w3.org/2005/Atom");\n\nXPathNodeIterator nodes = navigator.Select("/atom:feed/atom:title", ns);\n\nwhile (nodes.MoveNext())\n{\n        XPathNavigator currentNavigator = nodes.Current;\n        string title = currentNavigator.Value;\n        Trace.WriteLine(title);\n}	0
5478192	5478173	String.Replace char to string	myString.Replace("??", "AE");	0
5670780	5670736	LINQ - GroupBy a key of paired object, then separate the grouped object into list of 2 objects?	list.GroupBy(o => o.MatchId)\n    .Select(g => new PairedObject\n                     {\n                         IsApproved = g.First(o => o.IsApproved),\n                         NotApproved = g.First(o => !o.IsApproved)\n                     });	0
19142200	19141976	Group a List of Data by Date	var results = Bean.Where(x => x.period > Date1 && x.period < Date2).GroupBy(dc => new {dc.serviceType, dc.periodType})	0
25905964	25905900	Searching inside a subfolder in asp.net	protected void Button1_Click(object sender, EventArgs e)\n    {\n           ListBox1.Items.Clear();\n           string[] files = Directory.GetFiles(Server.MapPath("~/files"),  "*.*", SearchOption.AllDirectories);\n\n           foreach (string item in files)\n           {\n               string fileName = Path.GetFileName(item);\n               if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))\n               {\n                   ListBox1.Items.Add(fileName);\n               }\n\n           }\n    }	0
30372017	30371760	convert list<char> that represent binary string into ASCII C#	string binary = "01001000";\nvar list = new List<Byte>();\nfor (int i = 0; i < binary.Length; i += 8)\n{\n    if (binary.Length >= i + 8)\n    {\n        String t = binary.Substring(i, 8);\n        list.Add(Convert.ToByte(t, 2));\n    }\n}\nstring result = Encoding.ASCII.GetString(list.ToArray()); // H	0
10118778	10118713	How to set active form for all time?	TopMost=true	0
2277930	2277836	How to do IBOutlets in MonoTouch?	myLabel.Text = "My Label!"	0
23300639	23271998	How can I get only the commited source code from Git?	git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT C~..G | xargs tar -rf myTarFile.tar	0
10703030	10702963	Displaying a WPF popup from a thread in an office add-in	Dispather.BeginInvoke(new Action(()=>{ this.m_ProgressBar.Value = progress; });	0
5822000	5763225	Ajax enabled wcf service using jquery POST data is not sent after a short while	[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Json)]	0
22947609	22944952	how to call received data in Serial Port C#	void Main()\n{\n    using (SerialPort serialPort1 = new SerialPort("COM1"))\n    using (SerialPort serialPort2 = new SerialPort("COM2"))\n    {\n        serialPort1.DataReceived += (sender, args) => {\n            Console.WriteLine("COM1 Received: " + serialPort1.ReadLine());\n        };\n\n        serialPort2.DataReceived += (sender, args) => {\n            Console.WriteLine("COM2 Received: " + serialPort2.ReadLine());\n        };\n\n        serialPort1.Open();\n        serialPort2.Open();\n\n        serialPort1.WriteLine("Hello, COM2!");\n\n        Thread.Sleep(200);\n    }\n}	0
26253177	26240787	To fill shape with color in power point interop	private void btn_Orange_Click(object sender, RibbonControlEventArgs e)\n{\n    if(type=="Fill")\n    {  \n       PowerPoint.Application ppApp = Globals.ThisAddIn.Application;\n            PowerPoint.ShapeRange ppshr = ppApp.ActiveWindow.Selection.ShapeRange;\n            // here the color RGB is given in format of BGR because interop reads it as BGR and not RGB\n\n            ppshr.Fill.ForeColor.RGB =System.Drawing.Color.FromArgb(0,168,255).ToArgb();\n       }\n }	0
10013213	10012561	C# - Group Results by Value after Split	string filename = @"D:\myfile.log";\nvar statistics = File.ReadLines(filename)\n    .Where(line => line.StartsWith("Process"))\n    .Select(line => line.Split('\t'))\n    .GroupBy(items => items[1])\n    .Select(g =>\n            new \n                {\n                    Division = g.Key,\n                    ZipFiles = g.Sum(i => Int32.Parse(i[2])),\n                    Conversions = g.Sum(i => Int32.Parse(i[3])),\n                    ReturnedFiles = g.Sum(i => Int32.Parse(i[4])),\n                    TotalEmails = g.Sum(i => Int32.Parse(i[5]))\n                });\n\nConsole.Out.WriteLine("Division\tZip Files\tConversions\tReturned Files\tTotal E-mails");\nstatistics\n   .ToList()\n   .ForEach(d => Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", \n           d.Division, \n           d.ZipFiles, \n           d.Conversions, \n           d.ReturnedFiles,  \n           d.TotalEmails));	0
5693267	5693246	Force a class to implement a method without restricting the parameters in C#	public interface ICollect<T>\n{\n    void Collect(T obj);\n}\n\npublic class Car : ICollect<Car>\n{\n    public void Collect(Car obj)\n    {\n    //Do stuff\n    }\n}	0
34316793	34316319	How can i change the route parameter's name	/VotBox/Notify/4/STARTCALL\n/VotBox/Notify/4/startcall\n/VotBox/Notify?CALLID=3&STATE=anyString\n/VotBox/Notify?callId=3&state=anyString	0
22210100	22209745	ClaimsAuthorizationManager - Authorize using request parameters	ClaimsAuthorization.CheckAccess("Read", "Employees", "Managers");	0
31987862	31987824	Method that takes alot of parameters	class YourNameHere\n{\n    public string EID { get; set; }\n    ...\n}	0
29145828	29141271	Save and load cell border information from strings	// Set border options for all "edges" of B2.\nworksheet.Cells["B2"].Borders.Weight = BorderWeight.Thick;\n\n// Set border option for the "right edge" only.\nworksheet.Cells["B2"].Borders[BordersIndex.EdgeRight].Color = SpreadsheetGear.Colors.Red;	0
27677437	27677368	How to insert bind column and unbind column datagridview values in database	string q = \n@" INSERT INTO PurchaseInvo \n         (SupplierId, Item, Quantity, PricePerItem, Total, BillNo) \n    VALUES \n         (@SupplierID, @Item, @Quantity, @PricePerItem, @Total, @Bill)";\n\nSqlCommand cmd = new SqlCommand(q, connectionString);\n\ncmd.Parameters.AddWithValue("@SupplierID", comboBox1.Text);\ncmd.Parameters.AddWithValue("@Item", dataGridView1.Rows[i].Cells["Item"].Value);\ncmd.Parameters.AddWithValue("@Qauntity", dataGridView1.Rows[i].Cells["Quantity"].Value);\ncmd.Parameters.AddWithValue("@PricePerItem", dataGridView1.Rows[i].Cells["PricePerItem"].Value);\ncmd.Parameters.AddWithValue("@Total", dataGridView1.Rows[i].Cells["Total"].Value);\ncmd.Parameters.AddWithValue("@Bill", bill);\n\ncmd.ExecuteNonQuery();	0
15252269	15252223	C#, Looping through dataset and show each record from a dataset column	DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());	0
19980151	19980112	How to do progress reporting using Async/Await	async Task<int> UploadPicturesAsync(List<Image> imageList, \n     IProgress<int> progress)\n{\n      int totalCount = imageList.Count;\n      int processCount = await Task.Run<int>(() =>\n      {\n          int tempCount = 0;\n          foreach (var image in imageList)\n          {\n              //await the processing and uploading logic here\n              int processed = await UploadAndProcessAsync(image);\n              if (progress != null)\n              {\n                  progress.Report((tempCount * 100 / totalCount));\n              }\n              tempCount++;\n          }\n          return tempCount;\n      });\n      return processCount;\n}\n\n\nprivate async void Start_Button_Click(object sender, RoutedEventArgs e)\n{\n    int uploads=await UploadPicturesAsync(GenerateTestImages(),\n        new Progress<int>(percent => progressBar1.Value = percent));\n}	0
27823344	27822302	Writing a text file into a gz file using GZipStream without first writing the text file to disk	var databaseResult = "<xml>Very Long Xml String</xml>";\n\n        using (var stream = new MemoryStream())\n        {\n            using (var writer = new StreamWriter(stream))\n            {\n                writer.Write(databaseResult);\n                writer.Flush();\n                stream.Position = 0;\n\n                using (var outFile = File.Create(@"c:\temp\output.xml.gz"))\n                using (var Compress = new System.IO.Compression.GZipStream(outFile, CompressionMode.Compress))\n                {\n                    var buffer = new byte[65536];\n                    int numRead;\n                    while ((numRead = stream.Read(buffer, 0, buffer.Length)) != 0)\n                    {\n                        Compress.Write(buffer, 0, numRead);\n                    }\n                }\n            }\n        }	0
12538496	12538440	String concatenation with escaped variables	string query = "select * from table_name where name = @name and date = @date order by state desc";\nusing (SqlCommand cmd = new SqlCommand(query))\n{\n  cmd.Parameters.Add("@name", name);\n  cmd.Parameters.Add("@date", date);\n  using (SqlDataReader reader = cmd.ExecuteReader())\n  { ... }\n}	0
2167928	2167919	Getting started with ActiveDirectory in C#	var pc = new PrincipalContext(ContextType.Domain, "MyDomain", "DC=MyDomain,DC=com");\nreturn pc.ValidateCredentials(username, pass);	0
29014045	29013664	SQL Server 2012 Insert Stored Procedure for N parameters	foreach(var property in myClass.GetType().GetProperties())\n{\n    SqlParameter newParam = new SqlParameter();\n    newParam.Name = property.Name;\n    ...\n    // set other fields of the new parameter here and add it to the array \n    // the logic to determine the exact type of param can get hairy\n }	0
17384587	17383420	Microphone BufferReady event handler doesnt get in windows phone 8 app	// Timer to simulate the XNA Framework game loop (Microphone is \n        // from the XNA Framework). We also use this timer to monitor the \n        // state of audio playback so we can update the UI appropriately.\n        DispatcherTimer dt = new DispatcherTimer();\n        dt.Interval = TimeSpan.FromMilliseconds(33);\n        dt.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };\n        dt.Start();	0
8990062	8989397	Handle one to many relations in Linq using Entity framework	var x = from d in db.Direccion\n        where d.Activo == true\n        from c in d.Cliente\n        select new \n        { c.IdCliente,\n          c.Descripcion };	0
32737570	32736412	Sitecore: How to get the user profile item of currently logged in user	using Sitecore.Intranet.Profiles;\nusing Sitecore.Intranet.Profiles.Providers;\nusing Sitecore.Security.Accounts; \n\n// ------------------------------\n\nvar userName = User.Current.Name;\nvar account = Account.FromName(userName, AccountType.User);\n\nvar profileProvider = new UserProfileProvider(new Settings());\nvar profile = profileProvider.GetProfile(account.LocalName.ToLower());\n\nvar profileItem = profile.ProfileItem;	0
10953770	10953579	How do I query Oracle and store the results into a DataGrid?	ObservableCollection<T>	0
22141938	22141804	Using methods from visual controls in a console application	RichTextBox r=new RichTextBox();\n\nr.Text="Test";	0
29375742	29375558	C# remove the string part "Color []" in the string "Color [ColorName]"	var test = "Color [Black]";\nvar color = Regex.Match(test, @"\[(.*?)\]").Groups[1];	0
1616481	1616007	Write to XML for creation of reporting services file, trouble with quotes	writer.WriteElementString("Value", "=Parameters!StartDate.Value + \" To \" Parameters!EndDate.Value");	0
16290816	16290717	Finding a C# dictionary using a string	var persons = new Dictionary<string, Dictionary<string, int>>\n{\n    { "Jeremy", new Dictionary<string, int> { { "age", 20 }, { "height_cm", 180 } } },\n    { "Evan", new Dictionary<string, int> { { "age", 18 }, { "height_cm", 167 } } },\n};\n\nDictionary<string, int> x = persons["Jeremy"];\nx["age"] = 34;	0
8546411	8546386	How to update a column in a database with array values?	StringBuilder command = new StringBuilder();\nfor(int i = 0; i < array.Length; i++) {\n    command.Append("UPDATE TABLENAME SET THECOLUMN = " + array[i] + \n                " WHERE ID = " + (i+1) + ";");\n}\n// Execute the command HERE	0
12901028	12900988	Transparent PNG in WPF window	AllowsTransparency="True"	0
11471800	11471517	Create asp.net website with editable config file	var config = (Configuration)WebConfigurationManager.OpenWebConfiguration("~");\nvar configSection = (MySectionTypeHere)myConfiguration.GetSection("system.web/section");\n\n//make your edits here\n\nmyConfiguration.Save();	0
12031739	12031551	Correct DateTime format in SQL Server CE?	void SetDate(int recordID, datetime timeStamp)\n {\n    string SQL = "UPDATE [sometable] SET someDateTimeColumn= @NewTime WHERE ID= @ID";\n\n    using (var cn = new SqlCeConnection("connection string here"))\n    using (var cmd = new SqlCeCommand(SQL, cn))\n    {\n        cmd.Parameters.Add("@NewTime", SqlDbType.DateTime).Value = timeStamp;\n        cmd.Parameters.Add("@ID", SqlDbType.Integer).Value = recordID;\n\n        cn.Open();\n        cmd.ExecuteNonQuery();\n    }\n}	0
17164252	17163965	Controller Methods with same name	public ActionResult EditOrder(string nordre = null, string code = null, string libelle = null)\n{\n    if (nordre != null)\n    {\n        // ...\n    }\n    else if (code != null && libelle != null)\n    {\n        // ...\n    }\n    else\n    {\n        return new EmptyResult();\n    }\n}	0
3667837	3667817	Line separation / Line break in a listbox	listBox6.Items.Add(z + " * " + i + " = " + awnser.ToString());\n    } \n\nlistBox6.Items.Add("--------------------");	0
16055511	16055305	Method that accepts multiple enum types	private Byte[] FillBits<T>(List<T> EnumList)\n        where T : struct, IConvertible\n{\n    if (!typeof(T).IsEnum) \n    {\n        throw new ArgumentException("T must be an enumerated type");\n    }\n    foreach (var e in EnumList)\n    {\n        int value = Convert.ToInt32(e);\n    }\n}	0
30145242	30145001	Getting Current Date and Time of a Specific Country	var info = TimeZoneInfo.FindSystemTimeZoneById("Turkey Standard Time");\n\nDateTimeOffset localServerTime = DateTimeOffset.Now;\n\nDateTimeOffset istambulTime= TimeZoneInfo.ConvertTime(localServerTime, info);	0
10705010	10704770	How to get Innertexts of multiple <a> tags?	var genreNode = _markup.DocumentNode.Descendants("div").Where(n => n.Id.Equals("genre")).FirstOrDefault();\nif (genreNode != null)\n{\n    // this pulls all <a> nodes under the genre div and pops their inner text into an array\n    // then joins that array using the ", " as separator.\n    return string.Join(", ", genreNode.Descendants("a")\n        .Where(n => n.GetAttributeValue("href", string.Empty).Equals("#"))\n        .Select(n => n.InnerText).ToArray());\n}	0
1457132	1457084	ASP.NET Login control, login with e-mail but e-mail is not the username (how to)?	FormsAuthentication.RedirectFromLoginPage	0
607336	607299	C++ Assertions that Can Display a Custom String with Boost or STL?	assert(("The number must be greater than zero!",  num > 0));	0
8661371	8660705	How to follow a .lnk file programmatically	IWshRuntimeLibrary.IWshShell wsh = new IWshRuntimeLibrary.WshShellClass();\nIWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(filename);	0
15192720	15192673	Calculating factorials in C# using loops	factorial *= counter;	0
811077	791247	Animating removed item in Listbox	public class ObservableStack<T> : ObservableCollection<T> \n{\n    private T collapsed;\n    public event EventHandler BeforePop;\n\n    public T Peek() {\n        if (collapsed != null) {\n            Remove(collapsed);\n            collapsed = default(T);\n        }\n        return this.FirstOrDefault();\n    }\n\n    public T Pop() {\n        if (collapsed != null) { Remove(collapsed); }\n        T result = (collapsed = this.FirstOrDefault());\n        if (BeforePop != null && result != null) BeforePop(this, new EventArgs());\n        return result;\n    }\n\n    public void Push(T item) {\n        if (collapsed != null) {\n            Remove(collapsed);\n            collapsed = default(T);\n        }\n        Insert(0, item);\n    }\n}	0
10420765	10420678	Want to add image to aspx rss page	writer.WriteStartElement("image");\nwriter.WriteElementString("url","http://www.fileparade.com/Images/logo88x31.png");	0
14853269	14853259	How to get part of a string from the end	string name = "01/01/2000 Club Lets Rock Jonny".Split(' ').Last();	0
1340460	1340438	Get value of static field	var field = typeof(Pages).GetField("Home", BindingFlags.Public | BindingFlags.Static);\nvar value = (string)field.GetValue(null);	0
15482241	15481892	Excel kept blank cells as an used cell	public void Insert (string text, Excel.Worksheet ws, string column){\n    OleDbCommand cmd0 = new OleDbCommand("DELETE FROM ["+ws.Name+"$] where /*column1*/ = '' AND /*column2*/ = '' /*...*/ AND /*columnN*/ = ''", _oleConn);\n\n    cmd0.ExecuteNonQuery();\n\n    OleDbCommand cmd1 = new OleDbCommand("INSERT INTO ["+ws.Name+"$] " +\n                       "([" + column + "]) VALUES(' " + text + " ')", _oleConn);\n\n    cmd1.ExecuteNonQuery();\n}	0
9784141	9784074	convert a complex structure to byte array in c#	Socket socket = OpenSocket();\nusing (var stream = new NetworkStream(socket))\n{\n    var formatter = new BinaryFormatter();\n    formatter.Serialize(stream, obj); \n}	0
3957283	3957033	How to use DataKeys and DataItemIndex	uxUserListDisplayer.DataKeys[row.DataItemIndex]["Kayname"]	0
4967801	4967764	Retrieving values from a Linq GroupBy	public IEnumerable<MyType> GetQuery()\n{\n\n  var query = from row in stats.AsEnumerable()\n                    group row by row.Field<string>("date") into grp\n                    select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) }; \n\n  foreach (var rw  in query)\n  {\n     yield return new MyType(rw.Date, rw.Count);\n  }\n}	0
26378051	26377892	Get rid of all null values in Combobox after iport data from mysql database	string sName = myreader666.GetString("1003");\nif(sName != null && !sName.Equals(""))\n    applicationcombobox.Items.Add(sName);	0
15857666	15857381	How can I pass a generic class in my method so that this code becomes reusable	public interface IPage {\n    public HttpResponse Response { get; set; }\n}\n\npublic class Page1 : IPage {\n}\n\npublic class Page2 : IPage {\n}\n\npublic class CheckuserAuthentication {\n    private IPage _page;\n\n    public CheckuserAuthentication(IPage page) {\n        _page = page;\n    }\n\n    public void AuthenticateUser(out Person person, out Animal animal) {\n        _page.Response.Write("Doesn't matter what page it writes to.. it will write to whatever you pass in..");\n    }\n}	0
23306929	23284290	how to edit utf-16 xml file if it have string line after the end of the main Node	string text = File.ReadAllText(filepath);\n        text = text.Replace("<Serie>N", "<Serie>"+textBox1.Text);\n        text = text.Replace("<Nom>487382","<Nom>"+textBox2.Text);\n       //saving file with UTF-16\n        File.WriteAllText("new.xml", text , Encoding.Unicode);	0
30757037	30727150	How can I integrate ReSharper's Dotsettings File in SonarQube?	.DotSettings	0
8949357	8949319	How to copy list of dictionaries	var ld2 = new List<Dictionary<string, string>>();\n\nforeach (var dict in ld1)\n{\n    ld2.Add(new Dictionary<string, string>(dict));\n}	0
28884783	28884646	C# - creating multiple files with specific names	int value;\nstring path = null;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    FolderBrowserDialog fbd = new FolderBrowserDialog();\n    if (fbd.ShowDialog(this) == DialogResult.OK)\n    {\n        MessageBox.Show(fbd.SelectedPath);\n        path = fbd.SelectedPath; //fbd not folderBrowserDialog1\n\n    }\n}\n\nprivate void textBox1_TextChanged(object sender, EventArgs e)\n{\n    value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    if (path != null && Directory.Exists(path))\n        for(int i=0;i<value;i++)\n            Directory.CreateDirectory(Path.Combine(path,string.Format("SomeFolder{0}",i)));\n}	0
8347895	8347858	Logging done right	logger.Debug(() => someObject.GetHeavyDescriptionFromLazyTree());	0
4177499	4177379	radio button, set first item as selected	protected void Page_Load(object sender, EventArgs e)\n{\n    if (Page.IsPostBack)\n        return;\n\n    radioButtonList1.SelectedIndex = 0;\n    ListBox1_SelectedIndexChanged(null, null);\n}\n\nprotected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    LoadContent(ListBox1.SelectedIndex);\n}	0
10693757	10667414	C# with datagridView	private void button3_Click(object sender, EventArgs e) {\n    //clear balance\n    projectpizzaDataSet ds = new projectpizzaDataSet();\n    projectpizzaDataSetTableAdapters.balanceTableAdapter daCust = new projectpizzaDataSetTableAdapters.balanceTableAdapter();\n\n    while (dataGridView1.Rows.Count > 0 {\n        dataGridView1.Rows.RemoveAt(0);\n    }\n\n    this.balanceTableAdapter.Update(projectpizzaDataSet.balance);\n}	0
11455329	11440685	Set the caret position on a newly create paragraph of a flow document	TextPointer moveTo = ConversationX.CaretPosition.GetNextInsertionPosition(LogicalDirection.Forward);\n\nif (moveTo != null)\n\n{\n\n    myRichTextBox.CaretPosition = moveTo;\n\n}	0
26910534	26909034	How to Hide Visibility of Individual PivotItem	//Check trial state and set PivotItem\nif ((Application.Current as App).IsTrial)\n{\n    PivotControl.Items.Remove(PivotControl.Items.Single(p => ((PivotItem)p).Name == "Name_PivotItem"));\n}\nelse\n{\n    PivotControl.Items.Add(PivotControl.Items.Single(p => ((PivotItem)p).Name == "Name_PivotItem"));\n}	0
1705316	1704826	Waiting for Appdomain code to finish	public class WorkUnit : MarshalByRefObject\n{\n   private AutoResetEvent _event = new AutoResetEvent(false);\n\n   public void Run()\n   {\n     WebClient wb = new WebClient();\n     wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);\n     wb.DownloadStringAsync(new Uri("some uri"));\n\n     Console.WriteLine("Waiting for download to comlete...");\n     _event.WaitOne();\n     Console.WriteLine("done");\n   }\n\n   void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n   {\n     Console.WriteLine("job is done now");\n     _event.Set();\n   }\n }	0
12327141	12307969	Monodevelop: Porting from C#/Visual Studio: Double Click disappear	// The following line is may not be needed but is here to show how to do it\neventbox1.GdkWindow.Events = eventbox1.GdkWindow.Events | Gdk.EventMask.ButtonPressMask;\n\nprotected void OnEventbox1ButtonPressEvent (object o, ButtonPressEventArgs args)\n{\n    if( ((Gdk.EventButton)args.Event).Type == Gdk.EventType.TwoButtonPress)\n        System.Media.SystemSounds.Beep.Play (); // Play a sound only if this is a double-click event\n}	0
9896634	9896479	String measurement with Graphics.MeasureString	Graphics grfx = Graphics.FromImage(new Bitmap(1, 1));\n\nSystem.Drawing.Font f = new System.Drawing.Font("Times New Roman", 10, FontStyle.Regular);\n\nstring text1 = "check_space";\nSizeF bounds1 = grfx.MeasureString(text1, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ));\n\nstring text2 = "check_space ";\nSizeF bounds2 = grfx.MeasureString(text2, f, new PointF(0,0), new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );	0
24449402	24449255	Async/Await with RestSharp in Windows Phone 8	private async void appBarButton_Send_Click(object sender, EventArgs e)\n  {\n      Api api = new Api();\n      SendMessage a = await api.SendMessage(contactNumber, textBox_Message.Text, textBox_Message);\n      MessageBox.Show(a.message);\n  }	0
3615908	3615829	MouseHover on Root node of a tree view	private void tvwACH_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)\n{\n     string strFile = string.Empty;\n\n     // the problem is here, root node does not have a parent\n     // also added a fix\n     if (e.Node.Parent != null && e.Node.Parent.Text == "FileHeader")\n     {\n          strFile = e.Node.ToString();\n\n          string str = strFile.Substring(10);\n          StringComparison compareType = StringComparison.InvariantCultureIgnoreCase;\n          string fileName = Path.GetFileNameWithoutExtension(str);\n          string extension = Path.GetExtension(str);\n          if (extension.Equals(".txt", compareType))\n          {\n              StringBuilder osb = new StringBuilder();\n              objFileHeader.getFileHeader(str, out osb);\n              e.Node.ToolTipText = Convert.ToString(osb);\n          }\n     }\n}	0
13236283	13236195	Formatting Currency to ALWAYS use USD regardless of users culture	System.Threading.Thread.CurrentThread.CurrentCulture = \n     new System.Globalization.CultureInfo("en-US", false);	0
607724	607683	n-Tier Architecture Feedback Needed	hashtable = BL.GetSubordinateEmployees(supervisor);	0
22989212	22987732	Write data from stored proc to .dbf file, c#	using(var connection = new SqlConnection("connectionString")) {\n    using(var command = connection.CreateCommand()) {\n        command.CommandText = "storedProcedure";\n        command.CommandType = CommandType.StoredProcedure;\n\n        var data = new DataTable("TableName");\n\n        // This will execute the stored procedure and put the data in a data table.\n        var adapter = new SqlDataAdapter(command);\n        adapter.Fill(data);\n\n        // This will create a dbc.\n        var dbc = @"c:\Data\Data.dbc";\n        var dbcCreator = new VfpClient.Utils.DbcCreator.DataTableDbcCreator(dbc);\n\n        // This will create a dbf with the data retrieved from the stored procedure.\n        dbcCreator.Add(data);\n    }\n}	0
11049355	11034860	ASP Page Reload Disable Confirmation	window.location = window.location.href	0
22141141	22103675	DB logging in transactionscope failed	public static void Logging()\n    {\n        var opt = new TransactionOptions\n        {\n            IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,\n            Timeout = TransactionManager.MaximumTimeout\n        };\n        using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, opt))\n        {\n            using (SqlConnection conn2 = new SqlConnection(connectString1))\n            {\n                conn2.Open();\n                SqlCommand command2 = new SqlCommand("insert into ErrorLog(AppURL,Title,Message) values ('a','b','c')", conn2);\n                int aff2 = command2.ExecuteNonQuery();\n                scope.Complete();\n            }\n        }\n    }	0
12268688	12268622	Displaying contents of a function to a textbox on a windows form	wifi.Text = GetSignalStrengthAsInt().ToString();	0
15504320	15503881	C# Change text on click event	private void ChangeXRLabels(Control control)\n{\n    foreach(Control childControl in control.Controls)\n    {\n         XRLabel label = childControl as XRLabel;\n         if(label != string.Empty)\n            label.Text = "Your Text Value goes Here";\n         else if(childControl.Controls.Count > 0)\n             ChangeXRLabels(childControl);\n    }\n}	0
474859	474841	Dynamically getting default of a parameter type	public object GetDefault(Type type)\n{\n    return type.IsValueType ? Activator.CreateInstance(type) : null;\n}	0
5377346	5377296	How to remove all Items from ConcurrentBag?	T someItem;\nwhile (!myBag.IsEmpty) \n{\n   myBag.TryTake(out someItem);\n}	0
31368507	31367574	Need suggestions with c# design patterns	interface Lang {\n    void List<String> speakers();\n}\n\nclass Lang1 : Lang {\n    public override void List<String> speakers() {\n        return ...;\n    }\n}\n\nclass Lang2 : Lang {\n    public override void List<String> speakers() {\n        return ...;\n    }\n}\n\nList<Lang> langs = new List<>();\nint idx = 0;\nlangs[idx++] = new Lang1();\nlangs[idx++] = new Lang2();\n\nprivate void cmbSelectLanguageDEMO_SelectedIndexChanged(object sender, EventArgs e) {\n    cmbSelectSpeakerDEMO.Items.AddRange( langs[cmbSelectLanguageDEMO.SelectedIndex].speakers() );\n}	0
22404357	22404043	Download file from folder in asp.net	protected void btnDownload_Click(object sender, EventArgs e)\n{        \n     lblresume.Text = "~/Student_Resume/" + fuResume.FileName.ToString();         \n     if (lblresume.Text != string.Empty)        \n     {\n         WebClient req = new WebClient();\n         HttpResponse response = HttpContext.Current.Response;\n         string filePath = lblresume.Text;               \n         response.Clear();\n         response.ClearContent();\n         response.ClearHeaders();\n         response.Buffer = true;\n         response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension");\n         byte[] data = req.DownloadData(Server.MapPath(filePath));\n         response.BinaryWrite(data);\n         response.End();                   \n     }    \n}	0
5425274	5425173	Programmatically replace transparent regions in an image with white fill?	void  Foo(Bitmap image)\n    {\n        for (int y = 0; y < image.Height; ++y)\n        {\n            for (int x = 0; x < image.Width; ++x)\n            {\n                // not very sure about the condition.                   \n                if (image.GetPixel(x, y).A != 255)\n                {\n                    image.SetPixel(x,y,Color.White);\n                }\n            }\n        }\n\n    }	0
19199300	19199269	How do I merge several text files into one text file using C#?	using (var output = File.Create("output"))\n{\n    foreach (var file in new[] { "file1", "file2" })\n    {\n        using (var input = File.OpenRead(file))\n        {\n            input.CopyTo(output);\n        }\n    }\n}	0
12893513	12893324	Relationships in entity framework	User newUser = new User(){ ... Set proprties ...};\n\ndb.Users.Add(newUser);\n\nnewUser.Roles.Add(r);\n\ndb.SaveChanges();	0
136041	135782	Generic logging of function parameters in exception handling	private static void MyMethod(string s, int x, int y)\n{\n    try\n    {\n        throw new NotImplementedException();\n    }\n    catch (Exception ex)\n    {\n        LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);\n    }\n}\n\nprivate static void LogError(MethodBase method, Exception ex, params object[] values)\n{\n    ParameterInfo[] parms = method.GetParameters();\n    object[] namevalues = new object[2 * parms.Length];\n\n    string msg = "Error in " + method.Name + "(";\n    for (int i = 0, j = 0; i < parms.Length; i++, j += 2)\n    {\n        msg += "{" + j + "}={" + (j + 1) + "}, ";\n        namevalues[j] = parms[i].Name;\n        if (i < values.Length) namevalues[j + 1] = values[i];\n    }\n    msg += "exception=" + ex.Message + ")";\n    Console.WriteLine(string.Format(msg, namevalues));\n}	0
20818440	20818405	How to save values of elemenents with same name to List	XDocument xDoc = XDocument.Load(path);\n\nList<Item>  itemList = (from e in xDoc.Descendants("SHOPITEM")\n                        select new Item {  \n                        Name = e.Element("PRODUCTNAME").Value,\n                        Images = (from i in e.Elements("IMGURL_ALTERNATIVE")\n                                    select i.Value).ToList()\n                                    }).ToList();	0
485440	485398	How to create a join in an expression tree for LINQ?	Tasks.Join(Labels.Where(l => l.Name == "accounting"), t => t.TaskId, l => l.SourceId, (t, l) => t)	0
33760465	33759928	How can I get a valid type object for generic constraints in C#?	constraints[i].GetGenericTypeDefinition().FullName	0
6312862	6312789	Extension method with Lambda/Selector/Predicate logic	Func<decimal, bool> BuildPredicate (NumericSearch search)\n{\n    switch (search.Kind) {\n        case SearchKind.Equal:\n            return (x => x == search.Value);\n        case SearchKind.LessThan:\n            return (x => x < search.Value);\n        // ...\n    }\n}\n\n// in ApplyNumericSearch\nvar predicate = BuildPredicate (search);\nreturn source.Where (x => predicate (selector (x));	0
6071543	6071466	C# - MessageBox - Message localization in resources and lines breaks	Shift-Enter	0
1138707	1138667	Extension Method for serializing an IEnumerable<T> object to a string array?	public static class XmlTools\n{\n  public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> inputs)\n  {\n     return inputs.Select(pArg => pArg.ToXmlString());\n  }\n}	0
19355270	19355038	How can I put functions in other cs file?	namespace PM\n{\n    partial class A\n    {\n        partial void OnSomethingHappened(string s);\n    }\n\n    // This part can be in a separate file. \n    partial class A\n    {\n        // Comment out this method and the program \n        // will still compile. \n        partial void OnSomethingHappened(String s)\n        {\n            Console.WriteLine("Something happened: {0}", s);\n        }\n    }\n}	0
21914023	21904657	Dictionary Failure binding in WPF	public MainWindow()\n{\n    Dictio = new Dictionary<int, object>();\n    for (int i = 0; i < 200; i++)\n    {\n        Dictio.Add(i, new object());\n    }\n    InitializeComponent();\n    this.DataContext = this;\n}\n\n<StackPanel>\n    <TextBox Text="{Binding Dictio[0], Mode=OneWayToSource}"/>\n    <TextBox Text="{Binding Dictio[1], Mode=OneWayToSource}"/>\n</StackPanel>	0
2959663	2959573	How to Update with LINQ?	public void UpdateCustomer(int CustomerId, string CustomerName)\n{\n  using (MyDataContext dc = new MyDataContext)\n  {\n    //retrieve an object from the datacontext.\n    //  datacontext tracks changes to this instance!!!\n    Customer customer = dc.Customers.First(c => c.ID = CustomerId);\n    // property assignment is a change to this instance\n    customer.Name = CustomerName;\n    //dc knows that customer has changed\n    //  and makes that change in the database\n    dc.SubmitChanges();\n  }\n}	0
16628084	16628041	Find all lines that contains given string	System.IO.StreamReader file = new System.IO.StreamReader("data.txt");\nList<string> Spec = new List<string>();\nwhile (!file.EndOfStream)\n{\n    if(file.ReadLine().Contains("Spec")) \n    {\n        Spec.Add(s.Substring(5, s.Length - 5));\n    }\n}	0
8660591	8660453	LINQ to read XML file and print results	void PrintNames(StringBuilder result, string indent, XElement el)\n    {\n        var attr = el.Attributes("name");\n        if (attr != null)\n        {\n            result.Append(indent);\n            result.Append(attr.Value);\n            result.Append(System.Environment.NewLine);\n        }\n        indent = indent + " ";\n        foreach(var child in el.Elements())\n        {\n            PrintNames(result, indent, child);\n        }\n    }\n\n...\n\nvar sb = new StringBuilder();\nPrintNames(sb, String.Empty, xdoc.Root);	0
25352365	25352344	How to set and get Base property in chronometer c# newbe	Chronometer chrono = new Chronometer();\nchrono.Base = 1000;	0
4509583	4508735	WPF broken layout	(PresentationSource.FromVisual(this) as HwndSource).CompositionTarget.RenderMode = RenderMode.SoftwareOnly;	0
7839668	7839480	How to create a generic Add Method for two values	public object Add(IConvertible a, IConvertible b)\n{\n    if(IsNumeric(a) && IsNumeric(b))\n        return a.ToDouble(CultureInfo.InvariantCulture) + b.ToDouble(CultureInfo.InvariantCulture);\n    return a.ToString() + b.ToString();\n}\n\npublic static bool IsNumeric(object o)\n{\n    var code = (int)Type.GetTypeCode(o.GetType());\n    return code >= 4 && code <= 15;\n}	0
4841935	4841901	C# Array: How do i fill an array with results which get from functions in C#?	class Program\n    {\n        static int moo(int a)\n        {\n            for (int i = 2; i < a; i++)\n                if (a % i == 0)\n                    return i;\n\n            return a;\n        }\n\n        static void Main(string[] args)\n        {\n            List<int> a = new List<int>();\n\n            for (int i = 0; i < 100; i++)\n                a.Add(moo(i));\n\n            for (int i = 0; i < a.Count; i++)\n                Console.WriteLine("a[{0}] = {1}", i, a[i]);\n        }\n    }	0
22425287	22425257	I want to make a picturebox disappear after a certain time has passed without using a control	System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();\ntimer1.Interval=60000;//one minute\ntimer1.Tick += new System.EventHandler(timer1_Tick);\ntimer1.Start();\n\nprivate void pictureBox1_Click(object sender, EventArgs e)\n{       \n    timer1.Stop();\n    timer1.Start();\n}\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    //do whatever you want            \n    pictureBox2.Visible = false;\n}	0
7464012	7463327	Metro style app tutorial using C#	ItemsSource="{Binding Items}"\nDisplayMemberPath="Title"	0
16213201	16213144	How to check for object of particular type in a HashSet in windows 8?	var item = hashSet.OfType<DesiredType>().FirstOrDefault();	0
8505572	8505469	LINQ advice on selecting distinct elements from a collection	return myRegion.Roads\n    .Where(x => x.RoadType == RoadType.Highway)\n    .DistinctBy(x => x.Id);	0
8797008	8749176	Expression for current context/workflowid	public sealed class GetWorkflowInstanceId : CodeActivity<Guid>{\n    protected override Guid Execute(CodeActivityContext context) {\n        return context.WorkflowInstanceId;\n    }\n}	0
14625825	14622628	Design issues when inserting User Controls in Tab Control	[STAThread]\n    static void Main() {\n        Application.EnableVisualStyles();          // <=== HERE!\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n    }	0
11576404	11576263	MVC3, Where is the request comming from	Request.UrlReferrer	0
13197771	13197394	Either adressing a property in a sub class or a binding issue	public class controlProperties : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private Visibility _visibility;\n\n    public Visibility VisibleState\n    {\n        get\n        {\n            return _visibility;\n        }\n\n        set\n        {\n            _visibility = value;\n            this.NotifyPropertyChanged("VisibleState");\n        }\n    }\n\n    public void changeVisibility(bool isVisible)\n    {\n        if (isVisible)\n            this.VisibleState = Visibility.Visible;\n        else\n            this.VisibleState = Visibility.Collapsed;\n    }\n\n    private void NotifyPropertyChanged(string propertyName)\n    {\n        var eventHandler = this.PropertyChanged;\n\n        if (eventHandler != null)\n        {\n            eventHandler(sender, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n}	0
13650646	13650567	Is there any way to access variables from a child class given a list of objects defined as the parent?	foreach(Tile tile in Tiles)\n{\n    if (tile is Sand)\n         ((Sand)tile).variable_fromsand = 10; \n}	0
32184876	32184558	How to touch toggle hidden under png image sprite in Unity3d	Canvas Group	0
32560208	32559970	C# How to iterate throught all the lists in child's list?	public void RecursiveMethod(List<DialogLine> list)\n    {\n         for(int i = 0; i < list.Count; i++)\n         {\n               EditorGUILayout.LabelField("Line " + i, EditorStyles.boldLabel);\n\n               list[i].line = EditorGUILayout.TextField("Question", list[i].line);\n               list[i].answer = EditorGUILayout.TextField("Answer", list[i].answer);\n               RecursiveMethod(list[i].dialogLines);\n         }\n    }	0
22578681	22578615	How do i return sum from a class	void throw()\n    {\n\n      Random r = new Random();\n      for (int i = 0; i <dice.GetLength(0); i++)\n        {\n            int totalSum = 0;\n            for (int j  = 0; j < dice.GetLength(1); j++)\n            {\n                dice[i, j] = r.Next(1, _yChoice);\n                totalSum += dice[i, j];\n            }\n            // Here you display totalSum for game with index i.\n        }\n\n  }	0
18246826	18246482	How do I add CollectionViewController into ViewController	//self is the base controller\n[self addChildViewController: simpleCollectionViewController];	0
17823589	17823188	Parsing Italian Date on USA server	DateTime arrivalDateConfirmed = DateTime.ParseExact(foo, "dd MMM yyyy HH\\:mm", new CultureInfo("it-IT"));	0
6253685	6253656	how do I join two lists using linq or lambda expressions	var query = from order in workOrders\n            join plan in plans\n                 on order.WorkOrderNumber equals plan.WorkOrderNumber\n            select new\n            {\n                order.WorkOrderNumber,\n                order.Description,\n                plan.ScheduledDate\n            };	0
9898232	9898126	How to find the underyling element associated with a TreeViewItem	container.Header	0
5291367	1917314	Is there a way to enable the IE8 Developer Tools from inside WebBrowser control in a .NET application	webBrowser.DocumentCompleted += (o, e) =>\n{\n    webBrowser.Document.Window.Error += (w, we) =>\n    {\n        we.Handled = true;\n\n        // Do something with the error...\n        Debug.WriteLine(\n            string.Format(\n               "Error: {1}\nline: {0}\nurl: {2}",\n               we.LineNumber, //#0\n               we.Description, //#1\n               we.Url));  //#2\n    };\n};	0
27244012	27227937	count number of mails of a particular date in Outlook using C#	int mCount = myInbox.Items.Count;\n     for (int a = 1; a < mCount; a++)\n\n            {\n               var itemn = (Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[a];\n\n                if (itemn.CreationTime >= fd && itemn.CreationTime < td)\n                {\n                    string subject = itemn.Subject;\n                    DateTime reciv = itemn.CreationTime;\n                    var mContent = itemn.Body;\n                    var senderId = itemn.SenderEmailAddress;\n\n                    worksheet.Cells[xlrow, 2] = reciv;\n                    worksheet.Cells[xlrow, 3] = senderId;\n                    worksheet.Cells[xlrow, 4] = subject + worksheet.Cells.WrapText;\n                    worksheet.Cells[xlrow, 5] = mContent + worksheet.Cells.WrapText;\n                    worksheet.Cells.WrapText = true;\n                    xlrow++;\n                }\n\n            }	0
14175911	14175850	Differences with delegate declaration in c#	new Deleg(FunctionName)	0
17825572	17785569	Get all list of assemblies in Windows 8 C#?	var folder = Package.Current.InstalledLocation;\nforeach (var file in await folder.GetFilesAsync())\n{\n    if (file.FileType == ".dll")\n    {\n        var assemblyName = new AssemblyName(file.DisplayName);\n        var assembly = Assembly.Load(assemblyName);\n        foreach (var type in assembly.ExportedTypes)\n        {\n            // check type and do something with it\n        }\n    }\n}	0
9936956	9936689	conver a list of data into 2d array or List in c#	int k = 3;\nfloat [] a = new float [k*n];\nfloat [,] b = new float [k, n];\n\nfor (int i = 0; i < a.length; i++)\n    b[i / n, i % n] = a[i];	0
26023671	26023596	bit shifting - keep value as a byte	int newNumber = ((byte)(myByte << 2));	0
31065000	31064964	need help minus value from database column	command.CommandText = "update class set quanitity = quanitity - "+Convert.ToInt32(textBox10.Text) ;	0
11026653	11026373	how to display icon in a cell of a grid view c#	dataGridView1.Columns.Add(new DataGridViewImageColumn());\n        dataGridView1.Rows.Add(2);\n\n        DataGridViewImageCell cell = (DataGridViewImageCell)dataGridView1.Rows[0].Cells[0];\n\n        Icon ic = new Icon("icon.ico");\n\n        cell.Value = ic;	0
3360773	3360661	Call a method of type parameter	public static void RunSnippet()\n{\n    var c = new GenericClass<SomeType>();\n}\n\npublic class GenericClass<T> where T : SomeType, new()\n{\n    public GenericClass(){\n        (new T()).functionA();\n    }   \n}\n\npublic class SomeType\n{\n    public void functionA()\n    {\n        //do something here\n        Console.WriteLine("I wrote this");\n    }\n}	0
5000001	4999988	To clear the contents of a file	System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);	0
1167372	1167021	How code binding text+image tooltip in wpf c#	TextBlock textBlock = new TextBlock();\ntextBlock.Foreground = Brushes.White;\ntextBlock.HorizontalAlignment = HorizontalAlignment.Center;\ntextBlock.VerticalAlignment = VerticalAlignment.Center;\ntextBlock.Text = "Overlaying Image Text";\n\nGrid toolTipPanel = new Grid();\ntoolTipPanel.Children.Add(td);\ntoolTipPanel.Children.Add(textBlock);\n\nToolTipService.SetToolTip(image1, toolTipPanel);	0
8913417	8912670	Multi-threading synchronization using wide scope lock with WCF callbacks	Task t = new Task(somethingToDo);\n// Fire off the new task\nt.Start();\n\n// Wait for the task to finish...\nt.Wait();\n\n// Do something else...	0
10615266	10615095	C# Excel Interop: can't read all data from excel	sheet.Cells.NumberFormat = "@";	0
20359736	20129863	How do I add a tooltip or overlay to a specific section of a chart?	double temp = chart1.ChartAreas[0].AxisX.ValueToPixelPosition(Convert.ToDouble(ce.sChannelFrequency) * 1000);\nusing (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1))) {\n    SizeF size = graphics.MeasureString(freq.Text, new Font("eurostile", 13, FontStyle.Bold, GraphicsUnit.Pixel));\n    temp -= (size.Width/2+10);\n}\nif (temp < 0) temp = 0;\ntemp = chart1.ChartAreas[0].AxisX.PixelPositionToValue(temp);\nfreq.X = chart1.ChartAreas[0].AxisX.ValueToPosition(temp);	0
7750900	7750837	Adding a secondary data source to an ASP.NET data repeater	IDataReader dr = GetData(sql);\n        var dataCollection = new List<string>();\n\n        while(reader.Read())\n        {\n            dataCollection.Add(reader.GetString(1));\n        }\n\n        var extraData = CallWS();\n\n        while(extraData.Read())\n        {\n            dataCollection.Add(extraData.GetString(1));\n        }\n\n        myRepeater.DataSource = dataCollection;\n        myRepeater.DataBind();	0
10741176	10740821	How to select dgvRow by rightClick?	private void dgvPermit_MouseDown(object sender, MouseEventArgs e)\n    {\n        DataGridView dgv = (DataGridView)sender;\n        DataGridView.HitTestInfo Hti;\n        if (e.Button == MouseButtons.Right)\n        {\n            Hti = dgv.HitTest(e.X, e.Y);\n            if (Hti.Type == DataGridViewHitTestType.Cell)\n            {\n                if (!((DataGridViewRow)(dgv.Rows[Hti.RowIndex])).Selected)\n                {\n                    dgv.ClearSelection();\n                    ((DataGridViewRow)dgv.Rows[Hti.RowIndex]).Selected = true;\n                }\n            }\n        }\n\n    }	0
24135358	24135201	Must Declare Scalar Variable	private void button3_Click(object sender, EventArgs e)\n    {\n        string ssr;\n        SqlConnection scr = new SqlConnection(@"Data Source=USER-PC\MSSQL;Initial Catalog=Highscore;Integrated Security=True");\n        scr.Open();\n        ssr = "Select Nume,Scor,DataInitiala,DataRecenta FROM Users where DataInitiala between @Param and @Param1 ";\n        SqlCommand cmd2 = new SqlCommand(ssr, scr);\n        cmd2.Parameters.AddWithValue("@Param", from.Text);\n        cmd2.Parameters.AddWithValue("@Param1", to.Text);\n        SqlDataAdapter adapter1 = new SqlDataAdapter();\n        adapter1.SelectCommand = cmd2;\n        DataSet ds1 = new DataSet();\n        adapter1.Fill(ds1);\n        dataGridView1.DataSource = ds1.Tables[0];\n        dataGridView1.Refresh();         \n    }	0
4711107	4682494	C# register the same windows service with different parameters	sc.exe create WcfService1 binPath= "MyService.exe /run WcfService1.dll"	0
13722295	13713814	WPF CommandParameter MultiBinding values null	public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n{\n    return values.ToArray();\n}	0
18223068	18122649	Downloading a file in Windows store app	StorageFile sampleFile = await myfolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);	0
11519666	11519543	How to add comma separated string into datatable in c#?	DataTable table = new DataTable();\ntable.Columns.Add("name", typeof(string));\ntable.Columns.Add("value", typeof(string));\n\nstring name = "A,B,C,D";\nstring value = "100,200,300,400";\n\nstring[] names = name.Split(',');\nstring[] values = value.Split(',');\n\nfor(int i=0; i<names.Length; i++)\n    table.Rows.Add(new object[]{ names[i], values[i] });	0
22170035	22169970	Finding all Interface that a class implements	var interfaces = typeof(Classname).GetInterfaces();	0
21667503	21667473	ListView Only Loading One Item	foreach (FileInfo file in Files)\n        {\n            lvi = new ListViewItem();\n            string s = file.Name.ToString();\n            char[] arr = s.ToCharArray();\n            lvi.Text = s;\n\n            localPlayers.Items.Add(lvi);\n        }	0
657515	657419	Viewing all event handlers associated with a Button?	controlName.EventName +=	0
23451714	23451626	how to center programmatically created radio buttons?	// Get all the RadioButtons on the form.\nvar allRadioButtons = this.Controls.OfType<RadioButton>().ToArray();\n\n// Get the width of the widest RadioButton.\nvar greatestWidth = allRadioButtons.Max(rb => rb.Width);\n\n// Calculate the X position to centre the widest RadioButton.\nvar commonLeft = (this.ClientSize.Width - greatestWidth) / 2;\n\n// Align all RadioButtons to the calculated X position.\nArray.ForEach(allRadioButtons, rb => rb.Left = commonLeft);	0
1316328	1316292	How to store masses of data offline and then update it into an SQLite database in batch?	using (SQLiteConnection = new SQLiteConnection(cntnStr))\n{\n    connection.Open();\n\n    string query = "Insert Into Pages (ID, Data, Name) Values (?, ?, ?)";\n    using (SQLiteCommand command = new SQLiteCommand(query, connection)\n    {\n        command.Parameters.Add("id", DbType.Int32);\n        command.Parameters.Add("data", DbType.String);\n        command.Parameters.Add("name", DbType.String);\n        foreach(Page p in pages)\n        {\n             command.Parameters["id"].Value = p.Id;\n             command.Parameters["data"].Value = p.Data;\n             command.Parameters["name"].Value = p.Name;\n             command.ExecuteNonQuery();\n        }\n    }\n}	0
6404701	6404685	How to select specific item from BindingList<KeyValuePair<string, string>>?	properties.Select(k => k.Key == "id").FirstOrDefault();	0
3001553	3001525	How to override default window close operation?	private override void OnClosing( object sender, CancelEventArgs e )\n{\n     e.Cancel = true;\n     //Do whatever you want here..\n}	0
6446104	6446064	Using Reflection To Find ArrayList Object Properties	foreach (object obj in al)\n{\n    foreach(PropertyInfo prop in obj.GetType().GetProperties(\n         BindingFlags.Public | BindingFlags.Instance))\n    {\n        object value = prop.GetValue(obj, null);\n        string name = prop.Name;\n        // ^^^^ use those\n    }\n}	0
33174073	33173633	Comparing Enumerable with enumerable in a linq query	var supplierMaterials = user.Environments.First().Subsidiarys\n                         .SelectMany(x => \n                           x.Catalogs.SelectMany(y => \n                               y.SupplierMaterials));	0
28274231	28273329	C#: Sort DATATABLE with column date	var orderedRows = from row in dt.AsEnumerable()\n                  let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)\n                  orderby date \n                  select row;	0
24091186	24090529	Transferring Data Between Client and Server and Dynamically Flush	ByteBuffer iLength = ByteBuffer.allocate(4);\niLength.order(ByteOrder.LITTLE_ENDIAN);\niLength.putInt(length);\noutput.write(iLength.array(), 0, 4);\noutput.write(buffer);\noutput.flush();	0
23990807	23950423	How to set time zones with DDay.iCal	iCal.AddLocalTimeZone();	0
16725728	16725631	How tooo pass values in URL in c#	int loop1, loop2;\n\n// Load NameValueCollection object.\nNameValueCollection coll=Request.QueryString; \n// Get names of all keys into a string array.\nString[] arr1 = coll.AllKeys; \nfor (loop1 = 0; loop1 < arr1.Length; loop1++) \n{\n    Response.Write("Key: " + Server.HtmlEncode(arr1[loop1]) + "<br>");\n    String[] arr2 = coll.GetValues(arr1[loop1]);\n    for (loop2 = 0; loop2 < arr2.Length; loop2++) \n    {\n         Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "   <br>");\n    }\n}	0
7928918	7915948	extjs4 server side validation,how to?	{\n    success:false,\n    errors:{\n        field1:errorMsg1,\n        field2:errorMsg2\n    }\n}	0
5043366	5043255	c# columns names from ilist	public class LstLog\n{\n    private Dictionary<string, string> columnDictionary = new Dictionary<string, string>();\n\n    // Methods\n    public LstLog(String column1, String column2, String column3, String column4)\n    {\n        columnDictionary["column1"] = column1;\n        columnDictionary["column2"] = column1;\n        columnDictionary["column3"] = column1;\n        columnDictionary["column4"] = column1;\n    }\n    public string GetColumnValue(string columnName)\n    {\n        if(columnDictionary.ContainsKey(columnName)\n            return columnDictionary[columnName];\n        else \n            return null;\n    }\n}	0
15776503	15776481	How to make my service stop auto-posting into windows application event log	this.AutoLog = false;	0
3676334	3675082	User control button click event	//web form default.aspx or whatever\n\nprotected override void OnInit(EventArgs e)\n{\n    //find the button control within the user control\n    Button button = (Button)ucMyControl.FindControl("Button1");\n    //wire up event handler\n    button.Click += new EventHandler(button_Click);\n    base.OnInit(e);\n}\n\nvoid button_Click(object sender, EventArgs e)\n{\n    //send email here\n}	0
23007879	23007047	Is there a long version of IntPtr in C#?	System.IntPtr	0
8625267	8625253	Calling string or in within if or try from outside	int bleh;\nif (somevalue == 0)\n{\nbleh = 5;\n}\nelse if (somevalue == 1)\n{\nbleh = 2;\n}\n\nx = bleh	0
9606827	9606741	How to retrieve non <appSettings> keys from the web.config?	var httpRuntimeSection = ConfigurationManager.GetSection("system.web/httpRuntime") as \nHttpRuntimeSection;\n\n//httpRuntimeSection.ExecutionTimeout	0
34332503	34332345	Set UTF8 encoding on streamwriter	System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(new FileStream(dlg.FileName, FileMode.Open), Encoding.UTF8);	0
15296308	15294239	Count from SQL Rows into C# textbox	protected void Page_Load(object sender, EventArgs e)\n{\n    lb1.Text = GetRecordCount(textbox2.Text).ToString();\n}\n\nprivate int GetRecordCount(string myParameter)\n{\n    string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();\n    Int32 count = 0;\n    string sql = "SELECT COUNT(*) FROM members WHERE sponsor = @Sponsor";\n    using (SqlConnection conn = new SqlConnection(connectionString))\n    {\n        SqlCommand cmd = new SqlCommand(sql, conn);\n        cmd.Parameters.Add("@Sponsor", SqlDbType.VarChar);\n        cmd.Parameters["@Sponsor"].Value = myParameter;\n        try\n        {\n            conn.Open();\n            count = (Int32)cmd.ExecuteScalar();\n        }\n        catch (Exception ex)\n        {\n\n        }\n    }\n    return (int)count;\n}	0
15088814	15086750	How to load formated data in gridview?	YourGrid.DataBound += YourGrid_RowDataBound\n\nvoid YourGrid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n  if (e.Row.RowType == DataControlRowType.DataRow)\n  {\n      e.Row.Cells[1].Text = "test_" + e.Row.Cells[1].Text;\n  }\n}	0
27623534	27622252	setting TimeOut on MessageBoxManager	MessageBoxManager manager = new MessageBoxManager();\nmanager.ShowTitleCountDown = true;\nmanager.AutoCloseResult = System.Windows.Forms.DialogResult.No;\nmanager.TimeOut = 5;\nmanager.AutoClose = true;\nmanager.HookEnabled = true;\nDialogResult res = MessageBox.Show("Testing", "Hello", MessageBoxButtons.YesNo);\n\nif (res == System.Windows.Forms.DialogResult.Yes)\n{\n    Console.WriteLine("yes pressed");\n}\nelse\n{\n    Console.WriteLine("no presssd");\n}	0
22545260	22544903	Impersonate for entire application lifecycle	public class ImpersonationContext {\n    public delegate bool ImpersonationDel(object obj);\n\n    public bool Invoke(ImpersonationDel del){\n        using (new Impersonation("LocalHost", "test", "test")){\n            return del.Invoke();\n        }\n    }\n}	0
14963059	14962803	JSON date from tweeter to C# format	DateTime.ParseExact	0
733876	733832	Save file from a byte[] in C# NET 3.5	byte[] buffer = new byte[200];\nFile.WriteAllBytes(@"c:\data.dmp", buffer);	0
24329336	24302523	Porting code from Android to Windows Phone	var keysE = ((JObject)atttemptMappingD).ToObject<Dictionary<string, object>>();\n\nforeach (var item in keysE)\n{\n     string key = (string)item.Key.ToString();\n     string value = ((JObject)atttemptMappingD)[key].ToString();\n}	0
11232567	11232475	How to return all combinations that contains a given *partial* combination?	private IEnumerable<int[]> CombinationsFor(int n, int k);\nprivate int CombinationsCount(int n, int k);\n\nprivate int IndexFor(int n, int[] combination)\n{\n    int k = combination.Count();\n    int ret = 0;\n\n    int j = 0;\n    for (int i = 0; i < k; i++)\n    {\n        for (j++; j < combination[i]; j++)\n        {\n            ret += CombinationsCount(n - j, k - i - 1);\n        }\n    }\n\n    return ret;\n}\n\nprivate IEnumerable<int> PossibleCombinations(int n, int k, int[] picked)\n{\n    int m = picked.Count();\n\n    int[] reverseMapping = Enumerable.Range(0, n)\n        .Where(i=>!picked.Contains(i))\n        .ToArray();\n\n    return CombinationsFor(n-m, k-m)\n        .Select(c => c\n            .Select(x=>reverseMapping[x])\n            .Concat(picked)\n            .OrderBy(x=>x)\n            .ToArray()\n        )\n        .Select(c => IndexFor(n, c));\n}	0
5652511	5651946	Unable to restart windows service from my ASP.NET application	class Program\n{\n    static void Main()\n    {\n        WindowsServiceManager service = new WindowsServiceManager();\n        service.Run("W32Time", 2000);\n        service.End("W32Time", 2000);\n    }\n}\n\npublic class WindowsServiceManager\n{\n    internal void Run(string serviceId, int timeOut)\n    {\n        using (ServiceController serviceController = new ServiceController(serviceId))\n        {\n            TimeSpan t = TimeSpan.FromMilliseconds(timeOut);\n            serviceController.Start();\n            serviceController.WaitForStatus(ServiceControllerStatus.Running, t);\n        }\n    }\n\n    internal void End(string serviceId, int timeOut)\n    {\n        using (ServiceController serviceController = new ServiceController(serviceId))\n        {\n            TimeSpan t = TimeSpan.FromMilliseconds(timeOut);\n            serviceController.Stop();\n            serviceController.WaitForStatus(ServiceControllerStatus.Stopped, t);\n        }\n    }\n}	0
31092650	31088120	C# Nest: How to index array of geo-poinst	client.Map<LocationArray>(m => m\n                        .MapFromAttributes().Properties(p=>p\n                            .NestedObject<Location>(no => no\n                            .Name(pl => pl.Locations.First())\n                            .Dynamic()\n                            .Enabled()\n                            .IncludeInAll()\n                            .IncludeInParent()\n                            .IncludeInRoot()\n                            .MapFromAttributes()\n                            .Path("full")\n                            .Properties(pprops => pprops\n                                .GeoPoint(ps => ps\n                                    .Name(pg => pg.Coordinate)\n                                    .IndexGeoHash().IndexLatLon()\n                                )\n                            )\n                        ))\n                    );	0
13843296	13843136	Ignoring property in automapper for a nested class	Mapper.CreateMap<BasicTaskViewModel, BasicTask>()\n      .ForMember(dest => dest.Project, opt => opt.Ignore());	0
5383475	5383333	How to get IP address of WCF web service	IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName());\n    IPAddress curAdd = heserver.AddressList[0];\n    curAdd.ToString();	0
23464819	23464641	How do I convert a string value of date like Mon, 5/5/2014 to datetime dd/MM/yyyy?	string date = "Thu, 15/05/2014";	0
4398741	4397605	how to get file from remote machine	Protected Sub btnDownloadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)\nDim myFtpWebRequest As FtpWebRequest\nDim myFtpWebResponse As FtpWebResponse\nDim myStreamWriter As StreamWriter\n\nmyFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")\n\n'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")\n\nmyFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile\nmyFtpWebRequest.UseBinary = True\n\nmyFtpWebResponse = myFtpWebRequest.GetResponse()\n\nmyStreamWriter = New StreamWriter(Server.MapPath("filename.ext"))\nmyStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)\nmyStreamWriter.Close()\n\nlitResponse.Text = myFtpWebResponse.StatusDescription\n\nmyFtpWebResponse.Close()\nEnd Sub	0
32123569	32122683	Toolstripcontrolhost with Toolstripsplitbutton- remove blank spaces	public void AddPanelToSplitButton (Panel panel, ToolStripSplitButton button)\n{\n\nToolStripControlHost tcHost = new ToolStripControlHost(panel);\ntcHost.Margin = Padding.Empty;\ntcHost.Padding = Padding.Empty;\ntcHost.AutoSize = false;\ntcHost.Size = panel.Size;\n\nToolStripDropDown dropDown = new ToolStripDropDown();\ndropDown.Items.Add(tcHost);\nbutton.DropDown = dropDown;\n\n\n}	0
19526666	19526576	create object from LINQ	var grouped = from row in sqlResults.AsEnumerable()\n                group row by row.Field<string>("LOCATION") into groupby\n                select new DataItem()\n                {\n                    Location = groupby.Key,\n                    PersonList = groupby.Select(row => \n                        row.Field<string>("Person")).ToList();\n                };	0
12161865	8615468	Get Value from ASPxComboBox get value	ASPxComboBox1.TextField = "Name"; //This is the displayMember   \nASPxComboBox1.ValueField = "ID";  //This is the valueMember\nASPxComboBox1.ValueType = typeof(String);\nASPxComboBox1.DataSource = DataTableWithIDandNameColumns;\nASPxComboBox1.DataBind();\n\nString theID = Convert.ToString(ASPxComboBox1.Value);//The column in the datasource that is specified by the ValueField property.\n   OR:\nString theID = Convert.ToString(ASPxComboBox1.SelectedItem.GetValue("ID"));//Any column name in the datasource.\n   Also:\nString theName = Convert.ToString(ASPxComboBox1.SelectedItem.GetValue("Name"));	0
12446276	12414485	How to UnitTest if all Properties are Set. There is no Duplication	Equals()	0
12351459	12351349	Best practices for validating wcf endpoint on client with/without SSL/TLS	GET mysite/myservice.svc	0
9205621	9205468	How to tell when object initializer is done	var x = new Foo();\nx.BeginInit();\nx.Property1 = 1;\nx.Property2 = 2;\nx.EndInit();	0
2633398	2633351	c# How Do I make Sure Webclient allows necessary time for download	WebClient client = new WebClient ();\n\n// Add a user agent header in case the \n// requested URI contains a query.\n\nclient.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");\n\nStream data = client.OpenRead (some_string);\nStreamReader reader = new StreamReader (data);\nstring s = reader.ReadToEnd ();\nConsole.WriteLine (s);\ndata.Close ();\nreader.Close ();	0
15142313	14975947	Setting up Binding to template child	private void ZoomPercentageComboBox_ZoomValueChanged(object sender, ZoomValueChangedEventArgs e)\n{\n    if (e.Source == templatedZoomPercentageComboBox)\n        ZoomPercentageComboBoxZoomPercentageValue = ((double)e.NewValue);\n}\n\nprivate const string ZoomBoxTemplateName = "PART_ZoomBox";\n\nprivate ZoomPercentageComboBox templatedZoomPercentageComboBox\n{\n    get\n    {\n        return this.GetTemplateChild(ZoomBoxTemplateName) as ZoomPercentageComboBox;\n    }\n}	0
12369667	10899761	C# - Passing an anonymous function as a parameter	public static Func<dynamic, MyDbObject> TableToMyDbObject =\n    (row) => new MyDbObject\n                 {\n                     Id = row.Id\n                 }	0
8988924	8988764	How to make DataGrid column stretch from C# code?	Grid.ColumnDefinitions[0].Width = new DataGridLength(0.2, DataGridLengthUnitType.Star);\nGrid.ColumnDefinitions[1].Width = new DataGridLength(0.8, DataGridLengthUnitType.Star);	0
6777871	6777671	Setting up structure map in a c# console application	public class SetupSM\n    {\n        public void Setup()\n        {\n            ObjectFactory.Configure(config =>\n            { \n                config.Scan(scan =>\n                {\n                    scan.TheCallingAssembly();\n                    scan.WithDefaultConventions();\n                });\n\n                config.For<ISomething>().Use<SomeThingOne>();\n            });\n    }	0
12591968	12591308	how to fire job in sql agent in c# in a fire and forget manner	CREATE proc startjob\nAS\nbegin\nEXEC dbo.sp_start_job N'Weekly Sales Data Backup'\nEND	0
15292876	15292417	OracleCommand Query Null parameters in where- ORA-01008: not all variables bound	command.CommandText = "select count(id) from  Table1 "\n + "where decode(Column1, :PARAM1, 1) = 1 AND decode(Column2, :PARAM2, 1) = 1";	0
2481128	2481010	How to bind WPF TreeView to a List<Drink> programmatically?	treeView1.ItemsSource = coldDrinks;	0
14088968	14088894	read a specific line from a file	private static void Main(string[] args)\n    {\n        string cacheline = "";\n        string line;\n\n        System.IO.StreamReader file = new System.IO.StreamReader("C:\\overview2.srt");\n        List<string> lines = new List<string>();\n        while ((line = file.ReadLine()) != null)\n        {\n            if (line.Contains("medication"))\n            {\n                lines.Add(cacheline);\n            }\n            cacheline = line;\n        }\n        file.Close();\n\n        foreach (var l in lines)\n        {\n            Console.WriteLine(l);           \n        }\n    }	0
12948174	12928660	Convert different format of DateTime to specific String format	if (DateTime.TryParse(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"), out result))\n                    sDateTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");\n                else\n                {\n                    if (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.Equals("dd-MMM-yy")) sDateTime = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");\n                    else sDateTime = DateTime.Now.Month +"/" + DateTime.Now.Day+ "/" + DateTime.Now.Year + " " +  DateTime.Now.ToString("hh:mm:ss tt");\n                }	0
34209121	34209033	How to change join 3 tables from linq expersion to lamda?	var listOFValue = (db.Forms.Join(db.Controls, form => form.RecordId, control => control.FormId,\n                (form, control) => new {form, control})\n                .Join(db.Values, @t => control.RecordId, values => values.ControlId, (@t, values) => new {@t, values})\n                .Where(@t => form.RecordId == formId && control.RecordId == fieldId)\n                .OrderBy(@t => values.Name)\n                .Select(@t => values)).ToList();	0
21619596	21619573	Reading three inputs from the user using Console.ReadLine()	string input = Console.ReadLine();\nstring[] split = input.Split(',');\ndouble month = Double.Parse(split[0]);\ndouble year = Double.Parse(split[1]);\ndouble numberofmonth = Double.Parse(split[2]);	0
963550	963503	How to save text-to-speech as a wav with Microsoft SAPI?	SpeechSynthesizer ss = new SpeechSynthesizer();\n        ss.Volume = 100;\n        ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult);\n        ss.SetOutputToWaveFile(@"C:\MyAudioFile.wav");\n        ss.Speak("Hello World");	0
28081854	28081512	How to calculate Date and Time duration between two date and time?	DateTime startTime =Convert.ToDateTime(txtstarttime.Text);\nDateTime endTime = Convert.ToDateTime(txtendtime.Text);\n\nDateTime startdate=Convert.ToDateTime(txtstartdate.Text);\nDateTime enddate=Convert.ToDateTime(txtenddate.Text);\nif(startTime>endTime)\n{\n TimeSpan span = endTime.Subtract (startTime);\n if(span!=null)\n {\n   string timedifference=Convert.ToString(span.Hours)+" Hours "+Convert.ToString(span.Minutes)+" Minutes "+Convert.ToString(span.Seconds)+" Seconds";\n }\n}\nif(startdate>enddate)\n{\n string datedifference=(enddate- startdate).TotalDays.ToString()+" days ";\n}\nif(datedifference!=null&&timedifference!=null)\n{\n  txtDuration=datedifference+ timedifference;\n}	0
7894095	7894065	How to do condition statement in LINQ based on code variables?	var environmentIDs = eventCalendar.Select(q => q.EnvironmentId).Distinct();	0
30937520	30937396	Allow only alphabetic name in text box in c#	private void txtName_TextChanged(object sender, EventArgs e)\n   {\n\n    //here is the problem add ! in font \n\n    if(!String.IsNullOrWhiteSpace(txtName)) // This will prevent exception when textbox is empty   \n    {\n    if (!System.Text.RegularExpressions.Regex.IsMatch(txtName.Text, "^[a-zA-Z]+$"))\n        {\n            MessageBox.Show("Enter Valid Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\n            txtName.Text.Remove(txtName.Text.Length - 1);\n            txtName.Clear();\n            txtName.Focus();\n         }\n    }\n   }	0
13768159	13766841	Monotouch CGAffineTransform, animate many Affine Transforms simultaniously on the same view	CGAffineTransform composite = CGAffineTransform.MakeTranslation(xOffset, yOffset);\ncpomposite.Scale(xScale, yScale)\nview.Transform = composite;	0
13076841	13076226	ConstructUsingServiceLocator in AutoMapper	Mapper.Initialize(cfg =>\n            {\n                // Adding "Construct" configuration \n                cfg.ConstructServicesUsing(t => new Dest(5));\n                // Telling AutoMapper to use already defined configuration to construct Dest class\n                cfg.CreateMap<Source, Dest>()\n                    .ConstructUsingServiceLocator();\n            });	0
18415442	18415395	Define a class MyClass<T> or a function MyFunction<T>(T x) where T can only by a type that implements IMyInterface	public void MyFunc<T>() where T : IMyInterface {\n}	0
8103266	8103233	How do I check whether an item exists in Listbox in asp.net?	string toMatch = drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text;\nListItem item = ListBox1.Items.FindByText(toMatch);\nif (item != null)\n{\n    //found\n}\nelse\n{\n    //not found\n}	0
3371855	3371839	Is it possible to access an instance variable via a static method?	public class AnotherClass\n{\n    public int InstanceVariable = 42;\n}\n\npublic class Program\n{\n    static AnotherClass x = new AnotherClass(); // This is static.\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(x.InstanceVariable);\n    }\n}	0
6306625	6306536	Serialization of internal class to xml	[EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n[Serializable]\npublic class InternalSerializable	0
7712514	7711590	how to zip the file using ionic library	using (var zip = new ZipFile())\n{\n    zip.AddFile("Backup.sql");\n\n    zip.Save(@"C:\folder\Access\"Backup.zip");\n}	0
29774741	29774612	Edit active WPF control in an active window	WindowCollection mainWin = System.Windows.Application.Current.Windows;\nMyWindow win = (MyWindow)mainWin[2];\nwin.MyWindowsFormsHost.Child = MyNewControl;	0
29302202	29302035	Combining grouped radio button methods into one?	public void radiobutton2_Checked(object sender, RoutedEventArgs e) {\n    var rb = (RadioButton)sender;\n    var tag = Convert.ToInt32(rb.Tag);\n    angle_Offset = (90*tag) - direction;\n}	0
34230905	34065047	Asign fixed value to parameter in RouteConfig	routes.MapRoute(\n        name: "createFile",\n        url: "create/file",\n        constraints: new\n        {\n           fixedParameter = "blue"\n        },\n        defaults: new { controller = "create", action = "newFile"}       \n      );	0
1616491	1616465	How to check if a item is selected in TreeView (C#)	TreeNode tn = ctl_treeView.SelectedNode;\n\nif ( tn == null )\n    Console.WriteLine("No tree node selected.");\nelse\n    Console.WriteLine("Selected tree node {0}.", tn.Name );	0
827221	827216	ASP.NET - How to strip Query String after/before ? from ASPX parameter passing?	String[] urlComponents = myUrl.Split('?')	0
2974872	2974652	How can I show a form without any controls focused?	private void Form1_Shown(object sender, EventArgs e)\n    {\n        textBox1.TabStop = false;\n        textBox1.Focus();\n        textBox1.Left = -300;\n    }	0
20168887	18631385	What's the minimum requirement for the DataSource property of ASPX server side data-bound controls?	set\n    {\n        if (((value != null) && !(value is IListSource)) && !(value is IEnumerable))\n        {\n            throw new ArgumentException(SR.GetString("Invalid_DataSource_Type", new object[] { this.ID }));\n        }\n        this.dataSource = value;\n        this.OnDataPropertyChanged();\n    }	0
4853059	4853010	How to implement re-try n times in case of exception in C#?	static T TryNTimes<T>(Func<T> func, int times)\n{\n  while (times>0)\n  {\n     try\n     {\n        return func();\n     }\n     catch(Exception e)\n     {\n       if (--times <= 0)\n          throw;\n     }\n\n  }\n}	0
3814079	3814026	How to release excel process?	public void Dispose()\n    {\n        if(!this.disposed)\n        {\n            if(cell != null)\n                Marshal.FinalReleaseComObject(cell);\n\n            if(cells != null)\n                Marshal.FinalReleaseComObject(cells);\n\n            if(worksheet != null)\n                Marshal.FinalReleaseComObject(worksheet);\n\n            if(worksheets != null)\n                Marshal.FinalReleaseComObject(worksheets);\n\n            if (workbook != null)\n            {\n                workbook.Close(false, Type.Missing, Type.Missing);\n                Marshal.FinalReleaseComObject(workbook);\n            }\n\n            Marshal.FinalReleaseComObject(workbooks);\n            xlApp.Quit();\n            Marshal.FinalReleaseComObject(xlApp);\n\n            GC.Collect();\n            GC.WaitForPendingFinalizers();\n\n            disposed = true;\n        }\n    }	0
3712124	3706792	WPF: Locate Parent Window from ListView ViewBase	Window.GetWindow(myControl);	0
33085632	33085528	Cast Derived to Base dictionary	Dictionary<string, BaseClass> AAA = \n    derivedclass.ToDictionary(\n        k => k.Key, \n        v => (BaseClass)v.Value);	0
16535351	16535056	Adding data to data base with variable table name	string Command = "INSERT INTO [" + variable + "]  VALUES ('" + _ID + "','" + txt1.Text + "') ";\nConnection(Command);	0
257741	257587	Bring a window to the front in WPF	void hotkey_execute()\n{\n    IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;\n    BackgroundWorker bg = new BackgroundWorker();\n    bg.DoWork += new DoWorkEventHandler(delegate\n        {\n            Thread.Sleep(10);\n            SwitchToThisWindow(handle, true);\n        });\n    bg.RunWorkerAsync();\n}	0
27064955	27056493	Office365 connector: no name for EmailAddresses	var contactsFolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts,\n        new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));	0
6749114	6749082	Optimising foreach loops	var modules = (from session in m_sessions\n               from pullHit in session.PullHits\n               where pullHit.Module == _Module && pullHit.Response == _response\n               select pullHit).Count();	0
14142212	14141869	How to bind userControls inside a DataRepeater in Windows Forms c#?	BindingSource bindingSource1 = new BindingSource();\nbindingSource1.DataSource = items;\ntextBox1.DataBindings.Add("Text", bindingSource1, "FirstName");\nlabel1.DataBindings.Add("Text", bindingSource1, "LastName");\ndataRepeater1.DataSource = bindingSource1;	0
1865967	519740	Keeping same session with different user-agents	Global.asax	0
1944250	1944246	"Elegant" way to get list of list of property values from List<T> of objects?	string[] customerIDs = list.Select(x => x.ID).ToArray();	0
13016307	13016227	how to group by letter and put in same letter size	var res = from sign in all \n          group sign by Char.ToLower(sign.first_letter) \n          into grp \n          select grp;	0
18507	15219	UltraWebGrid: How to use a drop-down list in a column	uwgMyGrid.Columns.FromKey("colTest").AllowUpdate = AllowUpdate.Yes;	0
6819784	6820100	Is it possible to read multiple files at once in C#?	var readers = new List<StreamReader> ();\n\nfor (...)\n{\n   var aa = new StreamReader(@"realtime_" + Foo.main_id + "_" + i + ".txt"); \n   readers.Add(aa);\n}	0
3712167	3711980	Get the attribute name/string of a class with attribute	public class ActivityTypeAttribute : Attribute \n{\n public Name { get; set; }\n}\n\n[ActivityType(Name="MyClass")]\npublic class MyClass { }\n\n...\n{\n ActivityTypeAttribute att = (ActivityTypeAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(ActivityTypeAttribute));\n\n  Debug.Assert( att.Name == "MyClass" );\n}\n...	0
3338458	3338425	Get Current Index for Removal in String Collection	int idx = 0;\nwhile (idx < strCol.Count)\n{\n    var wasSuccessful = PerformDRIUpdate(strCol[idx]);\n    if (wasSuccessful)\n        strCol.RemoveAt(idx);\n    else\n        ++idx;\n}	0
10949734	10647589	How can i replace cursor with bitmap in winform	public class Form_With_A_Cursor_Example {\n    public void Shows_A_Form_With_A_Cursor_Loaded_From_A_pictureBox() {         \n        Form frm = new Form();\n        PictureBox pb = new PictureBox() { Image = Image.FromFile( @"C:\Users\xxx\Pictures\someImage.bmp" ) };\n\n        frm.Cursor = new Cursor( ( (Bitmap)pb.Image ).GetHicon() );\n\n        frm.ShowDialog();\n    }\n}	0
4273779	4273756	Hexidecimal string to character?	char charVal = (char)int.Parse("5A", NumberStyles.AllowHexSpecifier);	0
5088393	5088355	bind data from several tables to specific control	ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;\nObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;\n\nvar query =\n    from order in orders\n    join detail in details\n    on order.SalesOrderID\n    equals detail.SalesOrderID into orderGroup\n    select new\n    {\n        CustomerID = order.SalesOrderID,\n        OrderCount = orderGroup.Count()\n    };	0
10080570	10080023	Design pattern: Save private members	public interface IDatabaseSaveable\n{\n   void InsertToDatabase(Database pDatabase);\n   void UpdateDatabase(Database pDatabase);\n}\n\npublic class Potato : IDatabaseSaveable\n{\n   private int mID;\n   private double mSmoothness;\n\n   public void InsertToDatabase(Database pDatabase)\n   {\n      pDatabase.InsertToPotatoes(mID, mSmoothness, ...);\n   }\n\n   public void UpdateDatabase(Database pDatabase)\n   {\n      pDatabase.UpdatePotatoes(mID, mSmoothness, ...);\n   }\n}	0
10964100	10940200	Adding TabItem from another User Control	Shell MainFrm = (Shell)App.Current.MainWindow;\nMainFrm.WorkSpaceControl.AddDataTab("Something");	0
27167919	27167036	Marshal.Copy, copying an array of IntPtr into an IntPtr	static void Main(string[] args)\n    {\n        IntPtr[] ptrArray = new IntPtr[]\n        {\n            Marshal.AllocHGlobal(1),\n            Marshal.AllocHGlobal(2)\n        };\n\n        Marshal.WriteByte(ptrArray[0], 0, 100);\n\n        int size = Marshal.SizeOf(typeof(IntPtr)) * ptrArray.Length;\n        IntPtr ptr = Marshal.AllocHGlobal(size);\n\n        Marshal.Copy(ptrArray, 0, ptr, ptrArray.Length);\n\n        // Now we have native pointer ptr, which points to two pointers,\n        // each of thme points to its own memory (size 1 and 2).\n\n        // Let's read first IntPtr from ptr:\n        IntPtr p = Marshal.ReadIntPtr(ptr);\n\n        // Now let's read byte from p:\n        byte b = Marshal.ReadByte(p);\n\n        Console.WriteLine((int)b);    // prints 100\n\n        // To do: release all IntPtr\n    }	0
3299039	3298922	How to List Directory Contents with FTP in C#?	FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);\nftpRequest.Credentials =new NetworkCredential("anonymous","janeDoe@contoso.com");\nftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;\nFtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();\nStreamReader streamReader = new StreamReader(response.GetResponseStream());\n\nList<string> directories = new List<string>();\n\nstring line = streamReader.ReadLine();\nwhile (!string.IsNullOrEmpty(line))\n{\n    directories.Add(line);\n    line = streamReader.ReadLine();\n}\n\nstreamReader.Close();	0
4724458	4724347	Change text for multiple buttons in one operation	foreach(var btn in this.Controls)\n{\n    Button tmpbtn;\n    try\n    {\n        tmpbtn = (Button) btn;\n    }\n    catch(InvalidCastException e)\n    {\n        //perform required exception handelling if any.\n    }\n    if(tmpbtn != null)\n    {\n       if(string.Compare(tmpbtn.Name,0,"btn_",0,4) == 0)\n       {\n            tmpbtn.Text = "Somthing"; //Place your text here\n       }\n    }\n}	0
32822193	32821883	How I can read the items of a collection from a text file	var items = System.IO.File.\n    ReadAllLines(path + "installer.ini").\n    Where(x => x.StartsWith("#product=")).\n    Select(x =>x.Replace("#product=", "").Trim()).\n    ToArray();\n\nListBox2.Items.AddRange(items);	0
17403122	17402977	How Can I count Html cell' in code behind?	var noOfCells = table.Rows.Select(r => r.GetCells()).Count();	0
1084686	1084668	Why is the result of a subtraction of an Int16 parameter from an Int16 variable an Int32?	short a = 2, b = 3;\nshort c = a + b;	0
4038965	4038944	a simple problem with ForLoop in C#	for (int L = 3; L >= 1; L--)\n    {\n        MessageBox.Show("dfsdff");\n    }	0
11682191	11681263	how to design search for multiple fields in asp.net	var conditionals = new Dictionary<string, string>();\n\nforeach(Control c in Page.Controls)\n{\n    if (c is TextBox)\n    {\n        if (!String.IsNullOrEmpty(c.Text))\n            conditionals.Add(c.Id, c.Text);\n    }\n}	0
17672753	17672656	how to split the values after comma and print in next line	string strToPrint ="";\nstring[] lst = yourString.Split(",".ToCharArray());\nforeach(string str in lst)\n{\nstrToPrint  += str + Environment.NewLine;\n}\nDo whatever you want with strToPrint;	0
28385556	28385468	Redirect page after showing a message using C#	protected void btnRedirect_Click(object sender, EventArgs e)\n{\n    string message = "You will now be redirected to YOUR Page.";\n    string url = "http://www.yourpage.com/";\n    string script = "window.onload = function(){ alert('";\n    script += message;\n    script += "');";\n    script += "window.location = '";\n    script += url;\n    script += "'; }";\n    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);\n}	0
6400545	6400520	I have a problem with ViewState	public bool SearchClicked\n{\nget { return  ViewState["bool"] == null ? false : (bool)ViewState["bool"]; }\nset { ViewState["bool"] = value; }\n}	0
16526283	16526220	Issue with DateTime.ParseExact method: always throws exception even with correct format	string format = "MMM-dd-yyyy hh:mm:ss tt";	0
24842829	24842781	Running Commands from C#	Process cwebp = new Process();\n cwebp.StartInfo.FileName=("cmd.exe");\n cwebp.StartInfo.Arguments = "/C " + Settings.EncoderSettings[0];\n cwebp.Start();	0
12097694	12097639	How to get the selected value from aspx drop down?	string data = DropDownListnew.SelectedValue; // property not .Text property	0
11739578	11739416	Retrieve specific fields from DB after authentication	public ActionResult Index(string searchString)\n    {\n\n...\n...\n\n   return View(user.Where(x => x.Order.Username == User.Identity.Name));	0
14842633	14842516	Build a byte array[4] using individual values/variables	XDocument doc = XDocument.Parse(xmlString);\nXElement root = from e in doc.DocumentElement/*don't remember the exact name*/;\nvar byteElements = new [] { root.Element("Byte1"), root.Element("Byte2"), ... };\nvar bytes =\n byteElements\n .Select(elem => (byte)elem); //this "cast" is an implicit conversion operator\n .ToArray();	0
32859983	32858906	How to convert Bitmap image to Base64PNG string in monodroid	string tempBase64 = Convert.ToBase64String(b);	0
29132509	29132426	Check if button in specific area	if (_yourSelectionRectangle.Contains(new Rectangle(button4.Location, button4.Size))\n{\n    ...\n}	0
12542028	12541980	C# Combinations of integers	public static IEnumerable<int> Foo(int x) {\n  string s = x.ToString();\n  for (int length = 1; length <= s.Length; length++) {\n    for (int i = 0; i + length < s.Length; i++) {\n      yield return int.Parse(s.Substring(i, length));\n    }\n  }\n}	0
5076201	5076177	How to display the number ?12? in the format of ?0000012?	var str = string.Format("{0:d7}", 12);	0
18029807	18029689	How to replace quotes in code for Reading Text File to CSV without causing character truncation?	static void TxtToCSV(string s, TextWriter writer)\n    {\n        foreach (var line in s.Replace(", ", "").Split(new string[] { Environment.NewLine }, StringSplitOptions.None))\n        {\n            foreach (var t in line)\n            {\n                writer.Write(t);\n            }\n            writer.WriteLine();\n        }\n        writer.Flush();\n    }	0
9409250	9391976	Reading Excel-file using Oledb - treating content of excel file as Text only	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";	0
2372001	2371912	Calling an application from a server	\\myserver\sharepath\foo.exe	0
21853235	21852741	How to Read from specified substring to next substring	if (currentText.Contains("1 . 1 To Airtel Mobile") && currentText.Contains("Total"))\n{\n    int startPosition = currentText.IndexOf("1 . 1 To Airtel Mobile");\n    int endPosition = currentText.IndexOf("Total");\n\n    string result = currentText.Substring(startPosition, endPosition-startPosition);\n    // result will contain everything from and up to the Total line\n    }	0
21729862	21729637	Best Linq Syntax for Adding Objects of a class to a List of a Base Class	private List<BaseObject> GetList()\n{\n    List<ObjectA> aList = MyData.ObjectA.FindAll(delegate(ObjectA my) { return my.ObjectAName == "Harold"; });\n    List<BaseObject> baseList = new List<BaseObject>(aList.OfType<BaseObject>());\n\n    return baseList;\n}	0
648848	648559	How to determine if a textbox in a windows form has focus	// in Form_Load\nforeach (var control in this.Controls)  control.Enter += OnEnterControl;\n\n\nprivate void OnEnterControl(object sender, EventArgs e)\n{\n  focusControl = (sender as Control);\n}	0
5679656	5675971	WCF deserialization trying to convert xml parameter to object when I just want the string	public Stream LookupItem(Message requestXml)\n    {\n        WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";\n        string responseXml = "<whatever />";\n        return new MemoryStream(Encoding.UTF8.GetBytes(responseXml ));\n    }	0
1532379	1529370	Testing the scope of a type with structureMap	[TestFixture]\npublic class container_registration\n{\n    [Test]\n    public void session_request_should_be_scopped_per_httpcontext()\n    {\n        var container = new Container(new DataRegistry());\n\n        var plugin = container.Model.PluginTypes.First(p => p.PluginType.UnderlyingSystemType == typeof(ISessionRequest));\n\n        plugin.Lifecycle.ShouldBeOfType(typeof(HttpContextLifecycle));\n    }\n}	0
22412757	22411396	Query in document with inline default namespace	XPathDocument compDoc = new XPathDocument(responseStream);\nXPathNavigator root =  compDoc.CreateNavigator();\n\nXmlNamespaceManager resolver = new XmlNamespaceManager(root.NameTable);\nresolver.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");\nresolver.AddNamespace("ts", "http://test.org/schema");\n\nXPathNavigator comp = root.SelectSingleNode("/soap:Envelope/soap:Body//ts:company", resolver);\n\nstring id = comp.SelectSingleNode("ts:id").Value;	0
7151741	7151692	Qt 4.7 QRegExp Email Address Validation	QString strPatt = "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";	0
599771	599731	Use the [Serializable] attribute or subclassing from MarshalByRefObject?	using System;\nusing System.Reflection;\n\n[Serializable]\npublic class SerializableClass\n{\n    public string WhatIsMyAppDomain()\n    {\n    return AppDomain.CurrentDomain.FriendlyName;\n    }\n}\n\npublic class MarshallByRefClass : MarshalByRefObject\n{\n    public string WhatIsMyAppDomain()\n    {\n    return AppDomain.CurrentDomain.FriendlyName;\n    }\n}    \n\nclass Test\n{\n\n    static void Main(string[] args)\n    {\n    AppDomain ad = AppDomain.CreateDomain("OtherAppDomain");\n\n    MarshallByRefClass marshall = (MarshallByRefClass)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "MarshallByRefClass");\n    SerializableClass serializable = (SerializableClass)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "SerializableClass");\n\n    Console.WriteLine(marshall.WhatIsMyAppDomain());\n    Console.WriteLine(serializable.WhatIsMyAppDomain());\n\n    }\n}	0
31554768	31521395	SQL query built from c# method optional parameters	protected void gvbind(int month = 0, string user = "")\n    {\n        //string query = "Select * from WebLogs w inner join(select max(ID) as id, username from WebLogs group by Username) w2 on w.id = w2.id and w.Username = w2.username where Year(LogEntryDate) = year(getDate())";\n\n        string query = string.Empty;\n        query = "SELECT * FROM [WebLogs] WHERE "+((user.Length>0)?"([Username] = '" + user + "') AND ":"") +   ((month>0)?" month(LogEntryDate) =" + month+ "AND ":"") + " year(LogEntryDate) = year(getdate()) ORDER BY [ID]";\n\n    }	0
3823929	3823874	ASP.NET HTTP to HTTPS redirect with www prefix	if (!serverName.StartsWith("www."))\n    serverName = "www." + serverName;	0
18717407	18717206	Remove BR tag from the beginning and end of a string	while(source.StartsWith("<br>")) \n    source = source.SubString(4);\nwhile(source.EndsWith("<br>"))  \n    source = source.SubString(0,source.Length - 4);\n\nreturn source;	0
13708703	13708594	How can I get the URL used to launch an XBAP?	BrowserInteropHelper.Source	0
8461311	8459458	Moveable Custom Control	void moveableStackPanel1_MouseUp(object sender, MouseButtonEventArgs e)\n    {\n        ReleaseMouseCapture();\n    }\n\n    void moveableStackPanel1_MouseDown(object sender, MouseButtonEventArgs e)\n    {\n        if (IsEnabled && IsVisible)\n            CaptureMouse();\n    }\n\n    void moveableStackPanel1_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (IsMouseCaptured)\n        {\n            Point newLoc = e.GetPosition(null);\n            Margin = new Thickness(newLoc.X, newLoc.Y, 0, 0);\n        }\n    }	0
4786037	4785775	Listview in Listview problem	public string[] getTagDatasource(object data)\n{\n    if (!(data is string) || data == null)\n       return new string[] { };\n\n    return data.ToString().Split(",");\n}	0
5269160	5269000	Finding Local Maxima Over a Dynamic Range	static IList<double> FindPeaks(IList<double> values, int rangeOfPeaks)\n    {\n        List<double> peaks = new List<double>();\n\n        int checksOnEachSide = rangeOfPeaks / 2;\n        for (int i = 0; i < values.Count; i++)\n        {\n            double current = values[i];\n            IEnumerable<double> range = values;\n            if( i > checksOnEachSide )\n                range = range.Skip(i - checksOnEachSide);\n            range = range.Take(rangeOfPeaks);\n            if (current == range.Max())\n                peaks.Add(current);\n        }\n        return peaks;\n    }	0
1899720	1899698	Truncate a string with an ellipsis, making sure not to break any HTML entity	var decoded = HttpUtility.HtmlDecode(theEncodedString);\ndecoded = Truncate(decoded);\nvar result = HttpUtility.HtmlEncode(decoded);	0
14514135	14509267	Regular expression to match href, but no media files	using HtmlAgilityPack;\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\nList<string> href = new List<string>();\n\nprivate void addHREF()\n{\n    //put your input to check\n    string input = "";\n\n    doc.LoadHtml(input);\n    //Which files ignore?\n    string[] stringArray = { ".png", ".jpg" };\n    foreach (var item in doc.DocumentNode.SelectNodes("//a"))\n    {\n        string value = item.Attributes["href"].Value;\n        if (stringArray.Any(value.Contains) == false)\n            href.Add(value);\n    }\n}	0
3867312	3867299	Reading multiple rows from Database - Where am I going wrong?	Player player = new Player()\nplayer.Name = reader["Name"].ToString(); \nplayer.Number = Convert.ToInt32(reader["Number"].ToString()); \n\n//push to list \nPlayerList.Add(player);	0
4346338	4346074	Encode values in a NameValueCollection C# .net	myCollection.AllKeys\n    .ToList()\n    .ForEach(k => myCollection[k] = \n            HttpUtility.HtmlEncode(myCollection[k]));	0
16887155	16886863	Redirect after login in site	protected void baseLogin1_LoggedIn(object sender, EventArgs e)\n{\n    if (Context.User.Identity.IsAuthenticated && Context.User.IsInRole("Admin"))\n    {\n        Context.Response.Redirect("admin/Default.aspx");\n    }\n}	0
19088669	19088558	Issues with mysql in c#	string insertquery = "INSERT INTO testconnectie(text) VALUES ('"+textvalue+"')";	0
15331447	15138434	Getting G-WAN to work with Mono	./configure --prefix=/usr\nmake\nmake install	0
27630085	27630031	How to make an array of buttons and put it on a panel that matches the size of the array?	public Button[][] InitButtonArray(int width, int height)\n    {\n        Button[][] btnArr = new Button[width][];\n        for (int x = 0; x < width; x++)\n        {\n            btnArr[x] = new Button[height];\n            for (int y = 0; y < height; y++)\n            {\n                btnArr[x][y] = new Button();\n            }   \n        }\n        return btnArr;\n    }\n    public void AdjustPanelSize(Panel panel,int buttonWith, int buttonHeight, int width, int height)\n    {\n        panel.Size = new Size(buttonWith * width, buttonHeight * height);\n    }	0
15917175	15916270	WP8 Can't re-select listbox item after using hardware back button	allItemsListBox.SelectedIndex = -1;\n\nprivate void OpenWinePage_Click(object sender, EventArgs e)\n{\n    allItemsListBox.SelectedIndex = -1;\n    NavigationService.Navigate(new Uri("/WinePage.xaml", UriKind.Relative));\n}	0
29970789	29970244	How to validate a phone number	public class Program\n{\n    public static void Main()\n    {\n        Console.WriteLine("Enter a phone number.");\n        string telNo = Console.ReadLine();                      \n        Console.WriteLine("{0}correctly entered", IsPhoneNumber(telNo) ? "" : "in");    \n        Console.ReadLine(); \n    }\n\n    public static bool IsPhoneNumber(string number)\n    {\n        return Regex.Match(number, @"^(\+[0-9]{9})$").Success;\n    }\n}	0
5611617	5611585	Work out number of hours based on hours in working day	int htot = 0, dtot = 0;\nwhile (date2>date1) {\n  int h1 = date1.Hour < work_start ? work_start : date1.Hour;\n  int h2 = date1.Hour > work_end ? work_end : date1.Hour;\n  htot += (h2-h1);\n  dtot++;\n  date1 = date1.AddDays(1);\n}	0
10226725	10226084	Creating objects in a main thread and working with them in another thread. How to do that?	ManualResetEvent MRE = new ManualResetEvent(false);//Add this field to Form1\n\n    void function1()\n    {\n        array[0].x = 5;\n        array[0].y = 4;\n        MRE.Set();//This notifies first thread, that values are set.\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        Thread thread1 = new Thread(function1);\n        thread1.Start();\n        MRE.WaitOne();//This makes this thread wait until the second thread calls MRE.Set()\n        function2();\n    }	0
26693728	26687742	DataContract deserialize XML	string xmlResultString = @"<ResultData xmlns=""http://schemas.datacontract.org/2004/07/TsmApi.Logic.BusinesEntities"" \nxmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">\n<Information>Schedule added.</Information>\n<Success>true</Success>\n</ResultData>";\n\nvar doc = XDocument.Parse(xmlResultString);\n\nforeach (var element in doc.Descendants())\n{\n    element.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();\n    element.Name = element.Name.LocalName;\n}\nxmlResultString = doc.ToString();\nvar rdr = new StringReader(xmlResultString);\nvar serializer = new XmlSerializer(typeof(ResultData));\nvar resultingMessage = (ResultData)serializer.Deserialize(rdr);	0
21922992	21922647	How can browsers display JSON returned from C# Web Service	public class WebService1 : System.Web.Services.WebService\n{\n    [WebMethod]\n    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]\n    public void HelloWorld()\n    {\n        JavaScriptSerializer js = new JavaScriptSerializer();\n        Context.Response.Clear();\n        Context.Response.ContentType = "application/json";           \n        HelloWorldData data = new HelloWorldData();\n        data.Message = "HelloWorld";\n        Context.Response.Write(js.Serialize(data));\n    }\n}\n\npublic class HelloWorldData\n{\n   public String Message;\n}	0
7922457	7922251	Check for set of characters in a string	using System;\nusing System.Collections.Generic;\nclass Program {\n\n    static IEnumerable<string> GetPermutations(string value) {\n        if (value.Length == 1) {\n            yield return value;\n        } else {\n            for (int i = 0; i < value.Length; ++i) {\n                string a = value[i].ToString();\n                foreach (string b in GetPermutations(value.Remove(i, 1))) {\n                    yield return a + b;\n                }\n            }\n        }\n    }\n\n    static void Main(string[] args) {\n\n        string test = "INEEDTOGETAHAIRCUT";\n        string chars = "OEGT";\n        foreach (string to_find in GetPermutations(chars)) {\n            int i = test.IndexOf(to_find);\n            if (i != -1) {\n                Console.WriteLine("Found {0} at index {1}", to_find, i);\n            }\n        }\n    }\n}	0
7977559	7977240	Draw text on a shape	... .ctor()\n{\n    ...\n    // indicate user will paint\n    SetStyle(ControlStyles.UserPaint, true);\n\n    // rest is optional if you want/need it\n    SetStyle(ControlStyles.AllPaintingInWmPaint, true);   \n    SetStyle(ControlStyles.ResizeRedraw, true);\n    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);\n    SetStyle(ControlStyles.Opaque, true);\n}\n\nprotected override void OnPaint(PaintEventArgs p)\n{\n    // depending on how you set the control styles, you might need\n    // this to draw the background of your control wit a call to the methods base\n    base.OnPaint(p);\n\n    Graphics g = p.Graphics;\n    // ... Do your painting here with g ....\n}	0
11244864	11243755	Random characters inside URL with vb.net	Public Class CustomRandomGenerator\n\n    Private Shared myRandom as New Random()\n\n    Public Shared Function GenerateRandomString() As String\n\n        Dim chars = "abcdefghijklmnopqrstuvwxyz0123456789"\n        Dim result = New String(Enumerable.Repeat(chars, 3).[Select](Function(s) s(random.[Next](s.Length))).ToArray())\n\n        Dim rdmpart = "x1y2z3"\n        rdm = rdmpart & result\n\n        Return result\n    End Function\n\nEnd Class	0
16900185	16898837	Insert to Sqlite DataBase in isolated storage performance	...\ntry \n{\n    db.RunInTransaction(() =>\n    {\n        foreach (var item in items)\n        {\n            db.InsertOrReplace(item);\n        }\n    });\n...	0
13981934	13981919	How to display subscript in Visual C#?	richTextBox1.SelectionCharOffset = -10;	0
20811182	20811099	Queue Select Range between specific entries	var message = rxByteQueue.SkipWhile(x => x != 0x01)\n                         .TakeWhile(x => x != 0x04)\n                         .Concat(new byte[] { 0x04 });	0
19223775	19220869	c# to read xml file and update the checkboxes with the nodes	XDocument doc = XDocument.Load(@"path\\test.xml");            \n\n        // Add nodes to treeView1.\n        TreeNode pnode;\n        TreeNode cnode;\n            var gnrl = from general in doc.Descendants("general")\n                       select new\n                       {\n                           parent = general.Attribute("name").Value,\n                           child = general.Descendants("service")\n                       };\n            //Loop through results\n            foreach (var general in gnrl)\n            {\n                 // Add a root node.\n            pnode = treeview.Nodes.Add(String.Format(general.parent));\n                foreach (var ser in general.child)\n                {\n                // Add a node as a child of the previously added node.\n                cnode = pnode.Nodes.Add(String.Format(ser.Attribute("name").Value));                        \n                }\n           }	0
14840790	14840735	Implement IsNotNullAndGreaterThanZero Extension Method using Generics	public static bool IsNotNullAndGreaterThanDefault<T>(this T? value)\n    where T : struct, IComparable<T>\n{\n    return value != null && value.Value.CompareTo(default(T)) > 0;\n}	0
17791825	17756940	C# Generate a non self signed client CX509Certificate Request without a CA using the certenroll.dll	ISignerCertificate signerCertificate = new CSignerCertificate();\nsignerCertificate.Initialize(true, X509PrivateKeyVerify.VerifyNone,EncodingType.XCN_CRYPT_STRING_HEX, SEScert.GetRawCertDataString());\ncert.SignerCertificate = (CSignerCertificate)signerCertificate;	0
9468025	9467896	Get the Credit Card Type based on Number	string isVisa = "^4[0-9]{12}(?:[0-9]{3})?$";\nstring ccnumber = "1234123412341234";\n\nif (System.Text.RegularExpressions.Regex.IsMatch(ccnumber, isVisa)) {\n  // valid Visa card\n}	0
24424842	24424777	Check if string contains string from an array then use that in LastIndexOf method	// this is just an example of 1 out of 3 possible variations\n        string titleID = "document for the period ended 31 March 2014";\n\n        // the array values represent 3 possible variations that I might encounter\n        string s1 = "ended ";\n        string s2 = "Ended ";\n        string s3 = "Ending ";\n        string[] sArray = new [] { s1, s2, s3};\n\n        var stringMatch = sArray.FirstOrDefault(titleID.Contains);\n        if (stringMatch != null)\n        {\n            TakeEndPeriod = titleID.Substring(titleID.LastIndexOf(stringMatch));\n        }	0
12081963	12081590	How do I find the highest version of a varchar in C#?	var maxVersion = PList\n    .Select(x => new Version(x.VERSION))\n    .Max()\n    .ToString();\n\nPList = PList.Where(x => x.PSP == LP && x.VERSION == maxVersion);	0
965593	965580	C# generics syntax for multiple type parameter constraints	void foo<TOne, TTwo>() \n   where TOne : BaseOne\n   where TTwo : BaseTwo	0
13519737	13492911	How to refresh a BindingGroup?	void StackPanel_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Key == Key.Return)\n            (sender as StackPanel).BindingGroup.UpdateSources();\n    }	0
30507370	30507307	The most efficient way to get object with max value from list of objects	var maxvalue = minMaxList.Max(w => w.getMax());\nvar maxitems = minmaxlist.Where(w => w.getMax() == maxvalue);	0
32431345	32430683	EF code first: inheriting from common base class, WEB api losing base properties	[DataMember]	0
9680174	9680014	Lambda Expression: How to select from two non-related tables with one query	db.Context.Apples\n  .SelectMany(a => db.Context.Bikinis, (a, b) => new {a, b})\n  .Where(x => x.a.Id == 10)\n  .Where(x => x.b.Id == 15)\n  .Select(x => new {NaturalColor: x.a.Color, FavoriteColor: x.b.Color })\n  .FirstOrDefault();	0
23033887	23033695	Reading only the first record from an XML file	var theFirstBook=XDocument.Load("books.xml").Descendants("book").First();	0
10682866	10639169	What is the best structure to use for associating a master-detail list	public class Person\n{\n  public string Name {get; set;}\n  public int Age {get; set; }\n  public List<Person> Friends {get; set;} \n}	0
19727216	19727171	Serialize XML to a class with a different name	[XmlRoot(ElementName = "ApiException")]\npublic class FootMouthAPIException\n{\n}	0
4243994	4243956	How to force a derived class to fill a list defined in the base class?	public abstract class Base\n{\n    public abstract List<int> List { get; }\n}\n\npublic class Derived : Base\n{\n    #region Overrides of Base\n\n    public override List<int> List\n    {\n        get { return new List<int> {1, 2, 3}; }\n    }\n\n    #endregion\n}	0
2199056	2198989	Creating a generic IList instance using reflection	var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName);\nvar list = (Ilist<T>)Activator.CreateInstance(type);	0
20375754	20375657	Error catching WPF button clicked	try\n{\n    var response = e.Result.getSearchCoordsResult;\n    var pagedResults = JsonConvert.DeserializeObject<TestMap.Classes.Global.ResultSetPager<TestMap.Classes.Global.Place>>(response);\n    Classes.Global.searched = 1;\n\n    Results.ItemsSource = pagedResults.SearchResults;\n\n    searchError.Text = "Search Result";\n}\ncatch (Exception ex)\n{\n    searchError.Text = "No Results Found";\n}	0
5521399	5521385	Check if a string can be made by chars of another string in C#	public static bool UsesSameLetters(string input, string check) {\n  var array = new BitArray(check.Length, false);\n  for (var i = 0; i < input.Length; i++) {   \n    var found = false;\n    for (var j = 0; j < check.Length; j++) {\n      if (input[i] == check[j] && !array.Get(j)) {\n        array.Set(j, true);\n        found = true;\n        break;\n      }\n    }\n    if (!found) {\n      return false;\n    }\n  }\n  return true;\n}	0
33006697	33006112	Getting a setting from Entitlements.plist	var settings = new NSDictionary (NSBundle.MainBundle.PathForResource ("settings.plist", null));\n\n        var value= (NSString)settings ["key"];	0
13354940	13354892	Converting from RGB ints to Hex	Color myColor = Color.FromArgb(255, 181, 178);\n\nstring hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");	0
12360352	12360201	Entity Framework Relationships between two views	AccountUnitOfWork.Accounts.Join(AccountUnitOfWork.Subscriptions, x => x.ID, s => s.ID)	0
13595201	13595159	Evaluate enum parameter	public int TestEnum(Enum myEnum)\n{\n    return (int)(object)myEnum;\n}	0
26799696	26798447	How to split items in Checkedlistbox having strings like A+B+C?	var subNameList = new List<string>();\nforeach (var item in myCheckedListBox.Items)\n{\n    foreach (string subName in (item.ToString().Split('+'))\n    {\n        subNameList.Add(subName);\n    }\n}	0
4362244	4362212	exception with nvarchar - data was truncated while converting from one data type to another	SqlParameter param = new SqlParameter("Field", SqlDbType.NVarChar)    \nParam.Value = Field;	0
10439188	10439038	Select a tableadapter at runtime	//class variable:\nDataSet ds  = new DataSet();\n\n//fill dataset in some of your method:\nusing(SqlConnection conn = new SqlConnection("connString"))\n{\n    DataTable table1 = new DataTable("People");\n    DataTable table2 = new DataTable("Cars");\n    ds.Tables.Add(table1);\n    ds.Tables.Add(table2);\n    string query1 = @"SELECT * FROM People";\n    string query2 = @"SELECT * FROM Cars";\n    string[] queries = { query1, query2 };\n    for(int i = 0; i < queries.Length; i++)\n    {\n         using(SqlDataAdapter da = new SqlDataAdapter(queries[i], conn))\n             da.Fill(ds.Tables[i]);\n    }\n}\n\n//now bind tables to your button click events (this is example for Cars):\nvoid button1_Click()\n{\n    dataGridView1.DataSource = null;\n    dataGridView1.DataSource = ds.Tables["Cars"].DefaultView; \n\n    //do the same for table "People" in some other button click event\n}	0
19343041	19342988	How to unpackage a DbSet<T> stored as an object without knowing its subtype at compile time?	var dbSet = MyContext.Set(MyType);\ndbSet.Attach(MyValue);	0
17897619	17897399	How to make every object in list null	for (i = 0; i < list.Count; i++) {\n    list[i] = null;\n}	0
3436073	3436050	String validation in .NET	if (Regex.IsMatch("input",@"[^A-Z0-9/-]"))\n{\n   //invalid character found\n}	0
24630373	24630192	How to remove an extra column at the start in DataGrid	HeadersVisibility="Column"	0
19824029	19823803	Getting DataKeyNames for row on button click	protected void viewHoursButton_OnClick(object sender, EventArgs e)\n{\n    Button btn = sender as Button;\n    GridViewRow row = btn.NamingContainer as GridViewRow;\n    string pk = storyGridView.DataKeys[row.RowIndex].Values[0].ToString();\n    System.Diagnostics.Debug.WriteLine(pk);\n}	0
25268276	25268153	How to copy and paste text from one text file to another using C#?	int counter = 0;\n        string line;\n\n        // Read the file and display it line by line.\n        System.IO.StreamReader file = new System.IO.StreamReader(@"c:\AnswerFile.txt");\n    System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(@"C:\outputFile.txt");\n\n        while ((line = file.ReadLine()) != null)\n        {\n            System.Console.WriteLine(line);\n            fileWriter.WriteLine(line);\n            counter++;\n        }\n\n        file.Close();\n        fileWriter.Close();\n        System.Console.WriteLine("There were {0} lines.", counter);\n        // Suspend the screen.\n        System.Console.ReadLine();	0
31614637	31614529	Kendo UI Grid - Client Template: Escaping # sign	data-target='\#login'	0
33492456	33474604	Add on conflict replace to Nhibernate mapping file	session.CreateSQLQuery("CREATE TABLE offices (id integer primary key autoincrement, name TEXT, address TEXT, managername TEXT, email TEXT, website TEXT, phone1 TEXT, phone2 TEXT, phone3 TEXT, picture TEXT, mid BIGINT UNIQUE ON CONFLICT REPLACE, registerid TEXT, latitude DOUBLE, longitude DOUBLE)").ExecuteUpdate();	0
710543	710511	How can I hide methods in my C# code from documentation?	void INetSerializable.ReadObjectData(Streamer stream)	0
22613638	22613379	Selecting Random record in a datagridview	private Random rnd = new Random();\nprivate int lastSelectedIndex = -1;\n\nvoid RandomRecord()\n{\n    int noRows = dataset.Tables[0].Rows.Count;\n    int index = rnd.Next(noRows);\n\n    while(index == lastSelectedIndex && noRows > 1) {\n        index = rnd.Next(noRows);\n    }\n\n    lastSelectedIndex = index;\n\n    TxtDisplayQuestion.Text = dataset.Tables[0].Rows[index][Emp_Title].ToString();\n}	0
14678628	14678599	reading value from XML?	XmlTextReader reader = new XmlTextReader(a);\n        while (reader.Read())\n        {\n            if (reader.Name == "AV_")\n            {\n                label1.Text += reader.Value;\n            }	0
3014962	3014945	Dictionary.ContainsKey return False, but a want True	public class Key\n{\n    string name;\n    public Key(string n) { name = n; }\n\n    public override int GetHashCode()\n    {\n        if (name == null) return 0;\n        return name.GetHashCode();\n    }\n\n    public override bool Equals(object obj)\n    {\n        Key other = obj as key;\n        return other != null && other.name == this.name;\n    }\n}	0
6306555	6306472	do something before collection changes in observablecollection in wpf	public class MyCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged\n{\n    public MyCollection(Collection<T> list)\n        : base(list)\n    {\n    }\n\n    public MyCollection()\n        : base()\n    {\n    }\n\n    #region INotifyCollectionChanged Members\n\n    public event NotifyCollectionChangedEventHandler CollectionChanged;\n\n    protected void NotifyChanged(NotifyCollectionChangedEventArgs args)\n    {\n        NotifyCollectionChangedEventHandler handler = CollectionChanged;\n        if (handler != null)\n        {\n            handler(this, args);\n        }\n    }\n    #endregion\n\n    public new void Add(T item)\n    {\n        // Do some additional processing here!\n\n        base.Add(item);\n        this.NotifyChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, base.Count-1));\n        this.OnPropertyChanged("Count");\n    }\n}	0
20425457	20425424	Process a List<Dictionary<int, T>> to a List<List<T>> C# generics	lists = dicts.ConvertAll(d => d.Values.ToList());	0
3661823	3661747	time format in access 2007 - need help	Date dt = <value>;\nString time = dt.ToString("hh:mm");	0
34314396	34314186	Converting Character to Ascii	string fileText = @"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";\n\n int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();	0
12817928	12817758	Sorting of data in Dropdown	dataView.Sort = "studentName ASC";	0
33094655	33092932	Call and export two Gridviews into two separate worksheets	Microsoft.Office.Interop.Excel._Application app  \n      = new Microsoft.Office.Interop.Excel.Application();\n\n// creating new WorkBook within Excel application\nMicrosoft.Office.Interop.Excel._Workbook workbook \n     =   app.Workbooks.Add(Type.Missing);\n\n\n\nExportToExcel(app, workbook, gv1, 'sheet1', 1)\n\nExportToExcel(app, workbook, gv2, 'sheet2', 2)   \n}	0
21935435	21934986	Login failed for user SQL Server 2008	server=FlorinPilca-PC\SQLEXPRESS;database=DynamicWebServices;Integrated Security=True;	0
22659775	22659352	how to store the values into data table which are entered in grid view?	for (int i = 0; i < datagridItemEntry.Rows.Count; i++)\n                {\n                    string query1 = "insert into "+combCustomerName.Text+" values(" + gvSalesInv.Rows[i].Cells[0].Value + "," + gvSalesInv.Rows[i].Cells[1].Value + "," + gvSalesInv.Rows[i].Cells[2].Value + "," + gvSalesInv.Rows[i].Cells[3].Value + "," + gvSalesInv.Rows[i].Cells[4].Value + "," + gvSalesInv.Rows[i].Cells[5].Value + "," + gvSalesInv.Rows[i].Cells[6].Value + "," + gvSalesInv.Rows[i].Cells[7].Value + "," + gvSalesInv.Rows[i].Cells[8].Value + "," + gvSalesInv.Rows[i].Cells[9].Value + "," + gvSalesInv.Rows[i].Cells[10].Value + "," + gvSalesInv.Rows[i].Cells[11].Value + ")";\n                    SqlCommand cmd1 = new SqlCommand(query1, con);\n                    cmd1.ExecuteNonQuery();\n\n                }	0
12094993	12094425	Dropdownlists with many conditions - select from database	table.field	0
822744	822737	.NET Regex fails to match in code, works in every testing harness	"</?(?!p|a|b|i)\\b[^>]*>"	0
8705654	8704815	Dependency injection with UrlHelper	public class DynamicUrlHelper\n{\n  private readonly ISomeDependency dep;\n  public DynamicUrlHelper(ISomeDependency dep)\n  {\n    this.dep = dep;\n  }\n  public Uri DoMagic(Uri uri)\n  {\n    return uri.DoMagic(this.dep);\n  }\n}\npublic interface ISomeDependency\n{\n}\npublic static class UrlHelper\n{\n  public static Uri DoMagic(this Uri uri, ISomeDependency dep)\n  {\n    // do it!\n    return uri;\n  }\n}	0
6733951	6733891	define arrays with dynamic names	Dictionary<string, double[]> doubleArrays = new Dictionary<string, double[]>();\n\ndoubleArrays.Add("a", new double[] { 1.0, 1.2 });\n// etc.\ndouble[] someArray = doubleArrays["a"];	0
6356764	6356634	Send email of ASP.net Page HTML	public string RenderControl(Control ctrl) \n{\n    StringBuilder sb = new StringBuilder();\n    StringWriter tw = new StringWriter(sb);\n    HtmlTextWriter hw = new HtmlTextWriter(tw);\n\n    ctrl.RenderControl(hw);\n    return sb.ToString();\n}	0
27183784	27183643	How to find entered date already exist in min and max date?	str = "select top 1 EmpCode  From Musterroll WHERE '" + txtdate.Text + "' <= (Select Max(Todate)  From LeaveApply where Status='approved') and '" + txtdate.Text + "' >= (Select Min(Fromdate)  From LeaveApply where Status='approved') and Status='approved' order by EmpCode desc";	0
11472330	11472250	.net regex match line	Regex rgMatchLines = new Regex ( @"^.*$", RegexOptions.Multiline);	0
27285619	27278783	Get the DocumentText of a webBrowser after form submission	public string NewDocumentTextForMeToPlayWith{ get; set; }\n\nprivate void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    NewDocumentTextForMeToPlayWith = webBrowser1.DocumentText;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    HtmlElement theform = webBrowser1.Document.GetElementsByTagName("form")[0];\n    theform.InvokeMember("Submit");\n    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)\n    {\n        Application.DoEvents();\n    }\n\n    Thread.Sleep(1000);\n\n\n}	0
20786664	20786623	How much Hours overlap between 2 date ranges	DateTime dtBegin, dtBegin1,  dtBegin2, dtEnd, dtEnd1, dtEnd2;\n  dtBegin = dtBegin1 < dtBegin2 ? dtBegin1 : dtBegin2;\n  dtEnd = dtEnd1 > dtEnd2 ? dtEnd1 : dtEnd2;\n  TimeSpan range = dtEnd - dtBegin;\n  int hours = range.Hours	0
8871155	8863785	How to get the base 64 encoded value of a certificate with private key?	var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadOnly);\nvar certificate = store.Certificates.Find(X509FindType.FindByThumbprint, \n    "BLABLABLA", false)[0]; // doesn't matter how you get the cert\nvar exported = certificate.Export(X509ContentType.Pfx, "the password");\nvar base64 = Convert.ToBase64String(exported);\nstore.Close();	0
21862748	21862650	Implicit Operators and lambdas	Lambda<TIn, TOut> l = new Func<TIn, TOUt>(o => ... );	0
8660535	8659342	LINQ : select all that match a single field, merge on original	var filtered = goals.Where(n => n.Requirements\n                                 .Any(r => r.Name == order.Name))\n                                 .Where(m => m.Requirements.Any(p => p.Total <= order.Total) \n                                             && !user.Notebook.GoalsReaches.Any(g => g.ID == n.Id))\n                                 .Select(n => n.Id);	0
17975346	17975103	Is there a native spell check method for datatype string?	public IDictionary<string, IEnumerable<string>> Analyze(string text)\n{\n    var results = new Dictionary<string, IEnumerable<string>>();\n\n    using (var hunspell = new Hunspell("Resources\\en_GB.aff", "Resources\\en_GB.dic"))\n    {   \n        string[] words = Regex.Split(text, @"\W+", RegexOptions.IgnoreCase);\n        IEnumerable<string> misspelledWords = words.Where(word => !hunspell.Spell(word));\n\n        foreach (string word in misspelledWords)\n        {\n            IEnumerable<string> suggestions = hunspell.Suggest(word);\n            results.Add(word, suggestions);\n        }\n    }\n    return results;\n}	0
6008798	6008754	Accessing the youngest element of a ConcurrentQueue in presence of multiple threads operating on the queue	Interlocked.CompareExchange<T>(T, T)	0
4024219	4016770	Add Factory Support for a Windsor Registration Dynamically	Func<ISomeService>	0
26509618	26509560	String Replace For Insert	fixf_over = fixf_over.Replace("F", "0");	0
1222607	1222577	How to release late bound COM objects?	if(Marshal.IsComObject(oGE)==true)\n{\n  Marshal.ReleaseComObject(oGE);\n}	0
1019909	1019790	How to find a child of a parent unmanaged win32 app	SystemWindow.AllToplevelWindows	0
18440494	18440320	How to delete entry from file	if (!l.Contains((dateTimePicker1.Text.ToString().Trim() + ','+ \n    eventNameDeleteTextBox.Text.ToString().Trim()+',')))\n     finalData.Add(l);	0
32497491	32496553	Is it possible to add a background image to the top left header of dataGridView?	private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)\n    {\n        if (e.RowIndex<0 && e.ColumnIndex<0)\n        {\n            e.Graphics.DrawImage(myImage, e.CellBounds);\n            e.Handled = true;\n        }\n    }	0
1532882	1532852	XML field replacement in C#	// create new XmlDocument and load file\nXmlDocument xdoc = new XmlDocument();\nxdoc.Load("YourFileName.xml");\n\n// find a <User> node with attribute ID=2\nXmlNode userNo2 = xdoc.SelectSingleNode("//User[@ID='2']");\n\n// if found, begin manipulation    \nif(userNo2 != null)\n{\n   // find the <password> node for the user\n   XmlNode password = userNo2.SelectSingleNode("password");\n   if(password != null)\n   {\n      // change contents for <password> node \n      password.InnerText = "somthing that is different than before";\n   }\n\n   // find the <host> node for the user\n   XmlNode hostNode = userNo2.SelectSingleNode("host");\n   if(hostNode != null)\n   {\n      // change contents for <host> node \n      hostNode.InnerText = "the most current host that they were seen as";\n   }\n\n   // save changes to a new file (or the old one - up to you)\n   xdoc.Save("YourFileNameNew.xml");\n}	0
15819660	15819620	Count number of entries?	entries.Elements("entry").Count();	0
27334335	27334299	How can I return just a single class instance from a SQLite query?	String qry = String.Format("SELECT ChallengeTypeFK, {0}, {1} FROM LettersWordPhrases WHERE Id = ?", keyLang, candidateAnswersLang); \nDBModels.LettersWordsPhrases lwp = dbConn.Query<DBModels.LettersWordsPhrases>(qry, randomId).FirstOrDefault();	0
20147410	20147307	How to add combo box items from SQL db?	SqlCommand cmd = new SqlCommand("select price from tblbill where items=@itemname", con);\n cmd.Parameters.AddWithValue("@itemname",ComboBox1.SelectedItem.ToString());\n\n SqlDataReader dr = cmd.ExecuteReader();\n            if(dr.Read())\n            {\n               textBox1.Text= dr[0].ToString();                  \n            }	0
2005326	2005308	save Load User Control Dynamic to viewstate	public class FooControl : Control\n{\n    public string Bar\n    {\n        get { return ViewState["Bar"] as string; }\n        set { return ViewState["Bar"] = value; }\n    }\n}	0
26312815	26292563	Factory pattern with Managed Ext Framwork (MEF)	private static readonly CompositionContainer _container;\n\nstatic ObjectFactory()\n{       \n    var directoryCatalog = new DirectoryCatalog(Environment.CurrentDirectory)\n    _container = new CompositionContainer(directoryCatalog);        \n}\n\npublic static IClass CreateObject(ObectType objectType)\n{       \n    var objectTypes objectTypes = new List<Lazy<IClass, IMetaData>>();\n    try\n    {\n       objectTypes.AddRange(_container.GetExports<IClass, IMetaData>());\n    }\n    catch (CompositionException compositionException)\n    {\n        Console.WriteLine(compositionException.ToString());\n        Console.ReadLine();\n    }\n\n    return objectTypes.FirstOrDefault(x => x.Metadata.Type == objectType.ToString());\n}	0
3369208	3369102	Writing out namespace attributes in LINQ to XML	var el = new XElement(\n    "Activity",\n    new XAttribute(XName.Get("Class", "SomeNamespace"), "WorkflowConsoleApplication1.Activity1"),\n    new XAttribute(\n        XName.Get("VisualBasic.Settings", "SomeOtherNamespace"),\n        "Assembly references and imported namespaces for internal implementation"));\nConsole.WriteLine(el.ToString());	0
31768325	31768262	create query with parameter that can be null	public List<User> SearchUsers(string userName, int? userId)\n{\n    using (var ctx = new MyEntities())\n    {\n        IQueryable<User> query = ctx.User;\n\n        if (userName != null)\n            query = query.Where(u=>u.Name.Contains(userName));\n\n        if (userId != null)\n            query = query.Where(u=>u.ID==userId.Value);\n\n        var users = query\n            .OrderByDescending(u => u.ID)\n            .ToList();\n\n        return users;\n    }\n}	0
29012000	29011185	I have set up a web service but have no idea how to get data from it in MVC 5 c#	var client = new MyService.api.ApiReferenceClient();\nvar loginResponse = client.LoginRequest(loginRequest);	0
16560757	16560642	insert into postgresql table using c#	cmd3=new SqlCommand("insert into table2 values(@table1id,@champs1,@table1id2)",conn);\ncmd3.parameter.AddWithValue("@table1id",ID);//ID=ID of first table\ncmd3.parameter.AddWithValue("@champs1",chaps);\ncmd3.parameter.AddWithValue("@table1id2",ID);//ID=ID of first table\ncmd3.ExecuteNonQuery();	0
27582769	27574947	How to implement call to call ExecuteAsync using RestSharp	EventWaitHandle resetEvent = new AutoResetEvent(false);\n        client.ExecuteAsync(request, response =>\n        {\n            callback(response.Content);\n\n            resetEvent.Set();\n            return;\n        });\n\n        resetEvent.WaitOne();\n\n    }\n\n    private static void callback(string content)\n    {\n        System.Console.WriteLine(content);\n    }	0
11885588	11868329	Session variables after logout and login	Session.Abandon()	0
2522978	2522933	How to find whether a string contains any of the special characters?	Regex RgxUrl = new Regex("[^a-z0-9]");\n                    blnContainsSpecialCharacters = RgxUrl.IsMatch(stringToCheck);	0
9199817	9185581	Windows Phone 7 buttons with images	Button[] cardButtons = new Button[52];\nfor(int i = 0; i < 52; i++)\n{\n   Uri uri = new Uri("/images/someImage.png", UriKind.Relative);  \n   BitmapImage imgSource = new BitmapImage(uri);\n   Image image = new Image();\n   image.Source = imgSource;\n   cardButtons [i] = new Button();\n   cardButtons[i].Content = image;\n}	0
1662332	1662002	How to draw triangle wave using ZedGraph?	double amplitude = 1.7;\n                double period = 2;\n                PointPairList ppl = new PointPairList();\n                double y=0;\n                for (double x = 0; x <= 10; x += .005)\n                {\n                    double p = (x % (period)) / period ;\n                    if (p >= 0 && p <= 0.25)\n                        y = 4 * p * amplitude;\n                    if (p > 0.25 && p < 0.5)\n                        y = amplitude - (p - 0.25) * 4 * amplitude;\n                    if(p>0.5 && p<=0.75)\n                        y = - 4 * (p-0.5) * amplitude;\n                    if(p>0.75 && p<=1)\n                        y = - (amplitude - (p - 0.75) * 4 * amplitude);\n                    ppl.Add(x,y);\n                }\n\n                var line = zg1.MasterPane[0].AddCurve("", ppl, Color.Blue);\n                line.Symbol.IsVisible = false;\n                zg1.AxisChange();\n                zg1.Refresh();	0
22278522	22278242	How do I load a file in a Visual Studio solution/assembly programmatically?	var assembly = Assembly.GetExecutingAssembly();\nstring configFileContents;\nusing(StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("MySolutionNamespace.ContainingFolder.SiteConfiguration.json"), Encoding.Unicode))\n{\n    configFileContents = reader.ReadToEnd();\n}\n\nConsole.WriteLine(configFileContents);\nConsole.ReadKey();	0
18389852	18383028	get data from json web service every second	[DataContract]\npublic class QuestConf:List<object>\n{\n    [DataMember]\n    public Question question { get; set; }\n    [DataMember]\n    public List<Answer> answers { get; set; }\n}	0
32351193	32348920	How to resume the app with another page then the suspended?	//...\n    // the following line returns something like e.g. "MainPage"\n    var pageTypeName = ((Frame)Window.Current.Content).SourcePageType.Name;\n    // store pageTypeName in app scope\n    // Navigate to passcode page ...	0
22241582	22240517	C# How to check if dialog box is still open?	DialogBox dialogBox = new DialogBox();\n\n    // Show window modally \n    // NOTE: Returns only when window is closed\n    Nullable<bool> dialogSelection = dialogBox.ShowDialog();\n    if dialogSelection = null // box is still open	0
737935	737919	Mail attachments not attaching	foreach (string file in mailAttachmentFilePath)\n    {\n        Attachment data = new Attachment(file);\n        mail.Attachments.Add(data);\n    }	0
2446276	2446256	How find a SubForm of a application with changing texts?	public bool FindWindow(string windowName)\n    {\n        foreach (Form childWindow in this.MDIChildren)\n        {\n            if (childWindow.Name == windowName)\n                return true;\n        }\n\n        return false;\n    }	0
2866650	2866637	Nicely formatted text file	LogFile.Write(string.Format("{0,-10} {1,-11} {2,-30} {3}", ...));	0
32588274	32279585	How to get posts filtered by category in SiteFinity 8	BlogsManager blogsManager = BlogsManager.GetManager();\nTaxonomyManager manager = TaxonomyManager.GetManager();\nHierarchicalTaxon taxo = manager.GetTaxa<HierarchicalTaxon>().Where(t => t.Taxonomy.TaxonName == "Category" && t.Name == "YOUR_CATEGORY_NAME").SingleOrDefault();\nSystem.Linq.IQueryable<BlogPost> blogPosts = blogsManager.GetBlogPosts().Where(b => b.Status == ContentLifecycleStatus.Live && b.GetValue<TrackedList<Guid>>("Category").Contains(taxo.Id));\n\nforeach (BlogPost blogPostObj in blogPosts) {\n//HERE YOU CAN USE BLOG POST INFORMATION\n}	0
22781607	22780571	Scale windows forms window	private Size oldSize;\nprivate void Form1_Load(System.Object sender, System.EventArgs e)\n{\n    oldSize = base.Size;\n}\nprotected override void OnResize(System.EventArgs e)\n{\n    base.OnResize(e);\n    foreach (Control cnt in this.Controls) {\n        ResizeAll(cnt, base.Size);\n    }\n    oldSize = base.Size;\n}\nprivate void ResizeAll(Control cnt, Size newSize)\n{\n    int iWidth = newSize.Width - oldSize.Width;\n    cnt.Left += (cnt.Left * iWidth) / oldSize.Width;\n    cnt.Width += (cnt.Width * iWidth) / oldSize.Width;\n\n    int iHeight = newSize.Height - oldSize.Height;\n    cnt.Top += (cnt.Top * iHeight) / oldSize.Height;\n    cnt.Height += (cnt.Height * iHeight) / oldSize.Height;\n}	0
19169396	19169116	Stop OnClientClick="aspnetForm.target ='_blank';" from firing from other control clicks?	OnClientClick="aspnetForm.target ='_self';"	0
4254728	4254351	Get the URI from the default web proxy	var proxy = System.Net.HttpWebRequest.GetSystemWebProxy();\n\n//gets the proxy uri, will only work if the request needs to go via the proxy \n//(i.e. the requested url isn't in the bypass list, etc)\nUri proxyUri = proxy.GetProxy(new Uri("http://www.google.com"));\n\nproxyUri.Host.Dump();        // 10.1.100.112\nproxyUri.AbsoluteUri.Dump(); // http://10.1.100.112:8080/	0
17896814	17896796	How to add a plus minus sign to a label	(U+00B1)	0
15409344	15409303	Number increment from string value	string s = "00001";\nint number = Convert.ToInt32(s);\nnumber += 1;\nstring str = number.ToString("D5");	0
15518881	15518519	Calculating Time elapsed for ten users at the same time	DateTime elapsedTime = DateTime.Now - StartTime.	0
23063567	23063331	How to create a Uml Diagram with Visual Studio 2013	Help > About Microsoft Visual Studio	0
3875288	3875087	StructureMap default instance overloading with explicit arguments, error 205	ObjectFactory.Initialize(\n    x => x.For<ISystemQuery>.Add<BuildQuery<T>>.Ctor<string>().Is(connectionString)\n);	0
33891417	33891043	Use if Interfaces	public string testMethodGEneric(object instance)\n{\n    StringBuilder sb = new StringBuilder();\n    sb.Append(JsonConvert.SerializeObject(instance));\n    return sb.ToString();\n}	0
2795412	2795402	Nullables? Detecting them	private bool IsNullableType(Type theType)\n{\n    return theType.IsGenericType && \n           theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>));\n}	0
4032926	4032872	How to append line at the Top of exising text file in c#	FileStream.write( buffer, 0, space_reserved_for_line);\n//be aware that this will overwrite what has been written there	0
15091453	15091260	Get ID in GridView from checkBox	foreach (GridViewRow gvr in table_example.Rows)\n        {\n            if (((CheckBox)gvr.FindControl("CheckBox1")).Checked == true)\n            {\n                //Here I need the tID of the row that is checked\n\nint tID = Convert.ToInt32(gvr.Cells[1].Text);\n                WebService1 ws = new WebService1();\n                ws.addID(tID);\n            }\n        }	0
32380740	32380622	Binding the ItemsSource of a ListView to the property of an already bound property	public List<Armamento> armamento { get; set; }	0
16761807	16761793	Show default picture from a picture box before opening a file dialog	public Form1() {\n    InitializeComponent();\n    pictureBox1.Image = Properties.Resources.DefaultPicture;\n}	0
450559	450383	Creating a simple 'spider'	WebClient webClient = new WebClient(); \nconst string strUrl = "http://www.yahoo.com/"; \nbyte[] reqHTML; \nreqHTML = webClient.DownloadData(strUrl); \nUTF8Encoding objUTF8 = new UTF8Encoding(); \nstring html = objUTF8.GetString(reqHTML);	0
4895975	4895601	Retrieving Hierarchal data in Entity Code-First	[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Category_Category", Storage="Categories", ThisKey="pkCategoryID", OtherKey="ParentCategoryID")]\npublic EntitySet<Category> Categories\n{\n  get\n  {\n    return this._Categories;\n  }\n  set\n  {\n    this._Categories.Assign(value);\n  }\n}	0
12429981	12429949	Switch statement with static fields	public const string PID_1 = "12";\npublic const string PID_2 = "13";\npublic const string PID_3 = "14";	0
6322051	6320924	Coding web page to display name and link to all files in a folder	string dir = Request.Form("dir");\nif (string.IsNullOrEmpty(dir))\n    dir = "/";\n\nif (Session["Logged_User"] == null)\n{\n    Response.Write("Not Authorized");\n    Response.End();\n}\n\nSystem.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Server.MapPath(dir));\nStringBuilder sb = new StringBuilder();\nsb.Append("<ul class=\"jqueryFileTree\" style=\"display: none;\">").Append(Environment.NewLine);\nforeach (System.IO.DirectoryInfo di_child in di.GetDirectories())\n{\n    sb.AppendFormat("\t<li class=\"directory collapsed\"><a href=\"#\" rel=\"{0}\">{1}</a></li>\n",  dir + di_child.Name, di_child.Name);\n}\n\nforeach (System.IO.FileInfo fi in di.GetFiles())\n{\n    string ext = (fi.Extension.Length > 1) ? fi.Extension.Substring(1).ToLower() : "";\n    sb.AppendFormat("\t<li class=\"file ext_{0}\"><a href=\"#\" rel=\"{1}\">{2}</a></li>\n", ext, dir + fi.Name, fi.Name);\n}\nsb.Append("</ul>");\nResponse.Write(sb.ToString());	0
13033517	13033458	Manage entity access and permissions with Entity Framework	[Authorize(Roles="Customer, Company")]\npublic ActionResult ViewOrders(...)\n{\n    ...\n}\n\n[Authorize(Roles="Customer")]\npublic ActionResult CreateOrder(...)\n{\n    ...\n}	0
4896977	4896940	Select single row with LINQ TO SQL	public void DeleteSpiritUser(string nick)\n{\n    var user = (from u in _dc.Spirit_Users \n                where u.Nick == nick \n                select u).SingleOrDefault();\n\n    if(user != null)\n    {\n       using (var scope = new TransactionScope())\n       {\n           _dc.Spirit_Users.DeleteOnSubmit(user);\n           _dc.SubmitChanges();\n           scope.Complete();\n       }\n   }\n}	0
4904509	4904480	How can I use a dynamic settings.Blah instead of AppSettings["blah"]?	public abstract class MyBaseClass\n{\n    public dynamic Settings\n    {\n        get { return _settings; }\n    }\n\n    private SettingsProxy _settings = new SettingsProxy();\n\n    private class SettingsProxy : DynamicObject\n    {\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            var setting = ConfigurationManager.AppSettings[binder.Name];\n            if(setting != null)\n            {\n                result = setting.ToString();\n                return true;\n            }\n            result = null;\n            return false;\n        }\n    }\n}	0
16563502	16551677	Verifying Controls on a Windows Form	private bool CheckControls()\n    {\n        foreach (Control ctrl in this.Controls)\n        {\n           //Write the code to check whether the control value is null\n            //case: Testbox return true;\n            //case: Dropdown return true;\n            //case: Listbox return true;\n            //..etc\n\n        }\n        return false;\n    }	0
20683788	20683691	outlook mail object bcc	Outlook.Recipient recipBcc =\n        mail.Recipients.Add(Recipients.GetString(8));\nrecipBcc.Type = (int)Outlook.OlMailRecipientType.olBCC;	0
1835169	1835124	C# Selection of Top 2 product details from each region	var query = productList\n   .GroupBy(r => r.Region)\n   .Select(group => new { Region = group.Key,\n                          Orders = group.OrderByDescending(p => p.ProductPrice)\n                                        .Take(2) });	0
33757506	33753493	Fetching available storage space in Windows phone 8.1	public async Task<UInt64> GetLocalFolderFreeSpaceAsync()\n    {\n        var retrivedProperties =\n            await ApplicationData.Current.LocalFolder.Properties.RetrievePropertiesAsync(new string[] {"System.FreeSpace"});\n        return (UInt64) retrivedProperties["System.FreeSpace"];\n    }	0
9840976	9840257	How to get SPSite from a full page url	using (SPSite mySiteCollection = new SPSite ("http://intranet.test.com/sites/Accounting/Pages/Welcome.aspx"))\n{\n    ...\n}	0
2891568	2891521	1-Dimensional Array Counting Same Elements	public int LargestSequence(byte[] array) {\n  byte? last = null;\n  int count = 0;\n  int largest = 0;\n  foreach (byte b in array) {\n    if (last == b)\n      ++count;\n    else {\n      largest = Math.Max(largest, count);\n      last = b;\n      count = 1;\n    }\n  }\n  return Math.Max(largest, count);\n}	0
10949887	10896414	Drawing an envelope around a curve	private void GetEnvelope(PointF[] curve, out PointF[] left, out PointF[] right, float offset)\n        {\n            left = new PointF[curve.Length - 1];\n            right = new PointF[curve.Length - 1];\n\n            for (int i = 1; i < curve.Length; i++)\n            {\n                PointF normal = new PointF(curve[i].Y - curve[i - 1].Y, curve[i - 1].X - curve[i].X);\n                float length = (float)Math.Sqrt(normal.X * normal.X + normal.Y * normal.Y);\n                normal.X /= length;\n                normal.Y /= length;\n\n                PointF midpoint = new PointF((curve[i - 1].X + curve[i].X) / 2F, (curve[i - 1].Y + curve[i].Y) / 2F);\n                left[i - 1] = new PointF(midpoint.X - (normal.X * offset), midpoint.Y - (normal.Y * offset));\n                right[i - 1] = new PointF(midpoint.X + (normal.X * offset), midpoint.Y + (normal.Y * offset));\n            }\n        }	0
2355862	2355842	Find Type of Type parameter	typeof(T)	0
1003289	1003275	How to convert byte[] to string?	string result = System.Text.Encoding.UTF8.GetString(byteArray);	0
28844566	28844536	C# Trick with lambdas	Friend f = new Friend((id) => dir[id].GetData());	0
20771171	20771154	Selection of a folder path with C#	// Configure save file dialog box\nMicrosoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();\ndlg.FileName = "Document"; // Default file name\ndlg.DefaultExt = ".text"; // Default file extension\ndlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension \n\n// Show save file dialog box\nNullable<bool> result = dlg.ShowDialog();\n\n// Process save file dialog box results \nif (result == true)\n{\n    // Save document \n    string filename = dlg.FileName;\n}	0
11202662	11202605	To delete a desk top file in asp.net c#	string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\n    File.Delete(Path.Combine(desktopPath, "filetobedeleted"));	0
26355154	26351120	reset password in custom membership	System.Guid.NewGuid().ToString("P"));	0
9540651	9540472	How to unit-test a class which needs a specific file to be present	public class SettingsReader()\n{\n    public SettingsReader(System.IO.StreamReader reader)\n    {\n        // read contents of stream...\n    }\n}\n\n// In production code:\nnew SettingsReader(new StreamReader(File.Open("settings.xml")));\n\n// In unit test:\nnew SettingsReader(new StringReader("<settings>dummy settings</settings>"));	0
11832207	11812061	Dragging objects from one application to another	DataObject d = new DataObject(); \nd.SetData(DataFormats.Serializable, myObject); \nmyForm.DoDragDrop(d, DragDropEffects.Copy);	0
21144075	21142889	SignalR Join Group From Controller	var hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();\nhubContext.Groups.Add(connectionId, groupName);	0
16366033	16328757	need help on button to switch on webcam for C# based QR code project	// select the first available camera and start capturing\n     camDevices.SelectCamera(0);\n     camDevices.Current.NewFrame += Current_NewFrame;\n     camDevices.Current.Start();	0
20588930	20588858	Remove one child node from a parrent node with more than 1 node of the same name	string nodeToDelete = @"C:\Users\Stian\Desktop\toComp\334.jpg";\nvar xDoc =  XDocument.Load(fname);\n\nxDoc.Descendants()\n    .First(n => (string)n == nodeToDelete)\n    .Remove();\n\nstring newXml = xDoc.ToString();	0
12342979	12301792	How can I resolve circular dependencies in Funq IoC?	public Bar(Lazy<IFoo> foo) ...\npublic Foo(Lazy<IBar> bar) ...\n\ncontainer.Register<IBar>(c => new Bar(c.LazyResolve<IFoo>());\ncontainer.Register<IFoo>(c => new Foo(c.LazyResolve<IBar>());	0
13266625	13235030	How to get result of rollup query for a custom entity	List<Guid> GetAllResultsFromRollupQuery(XrmServiceContext xrm, Guid rollupQueryId)\n{\n    var rollupQuery = xrm.GoalRollupQuerySet.Where(v => v.Id == rollupQueryId).First();\n    var qa = GetQueryExpression(xrm, rollupQuery.FetchXml);\n\n    qa.PageInfo.Count = 1000;\n    qa.ColumnSet.AddColumn(rollupQuery.QueryEntityType + "id");\n\n    var result = new List<Guid>();\n    EntityCollection ec = null;\n\n    do\n    {\n        ec = xrm.RetrieveMultiple(qa);\n        ec.Entities.ToList().ForEach(v => result.Add((Guid)v.Attributes[rollupQuery.QueryEntityType + "id"]));\n        qa.PageInfo.PageNumber += 1;\n\n    } while (ec.MoreRecords == true);\n\n\n    return result;\n}\n\nQueryExpression GetQueryExpression(XrmServiceContext xrm, string fetchXml)\n{\n    var req = new FetchXmlToQueryExpressionRequest { FetchXml = fetchXml };\n    var result = (FetchXmlToQueryExpressionResponse)xrm.Execute(req);\n    return result.Query;\n}	0
9664080	9664029	C# Changing the number of dimensions in an array	Int32[] myArray = new Int32[xSize * ySize];\n\n// Access\nmyArray[x + (y * xSize)] = 5;	0
30251661	30251539	Extract all patterns using Regex	\b(?:Column|Cell)\b\(.*?\)	0
25132765	24969854	Add a Layout on Orientation change in Xamarin.Forms	if(landscapecontent.Children.Count>1)\n     { \n       //Don't add any views\n     }	0
14387681	14386694	Linq to return summed values from differing datatable	var distinctValues = \n    (from data in DtSet.Tables["tblData"].AsEnumerable()\n     join cost in DtSet.Tables["tblCost"].AsEnumerable().Where(r=>!r.IsNull("Amount"))\n        on data.Field<string>("InvNo") equals cost.Field<string>("InvNo") \n            into dc\n    select new\n    {\n        name_1 = "1",\n        name_2 = "I",\n        name_3 = data.Field<string>("EorD"),\n        name_4 = data.Field<string>("InvNo"),\n        name_5 = dc.Sum(d=>d.Field<int>("Amount"))\n    })\n    .Distinct();	0
14554539	14554447	check method for custom attribute	private static bool hasTestCaseAttribute(MemberInfo m)\n    {\n        return m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any();\n    }	0
7546923	7545146	gmail Conversation via smtp	mail.Headers.Add("In-Reply-To", <messageid>);	0
2528928	2528833	How to create the border of a dynamic canvas in Silverlight?	Canvas musicPlayerCanvas = new Canvas();\nmusicPlayerCanvas.Background = new SolidColorBrush(Colors.Purple);\n\nBorder border = new Border();\nborder.BorderBrush = new SolidColorBrush(Colors.Black);\nborder.BorderThickness = new Thickness(5);\nborder.Height = 80;\nborder.Width = 1018;\nborder.Child = musicPlayerCanvas;\n\nLayoutRoot.Children.Add(border);	0
22038545	22038142	Regex for valid URL characters	Uri.IsWellFormedUriString(stringURL, UriKind.RelativeOrAbsolute)	0
15125224	15125099	How to remove duplicates from an Array using LINQ	names.Distinct().ToList().ForEach( n => Console.WriteLine(n));	0
14972520	14972296	Instead of looping needs a handy way of setting node list value in xml	foreach (var rowElement in XDocument.Load("yourXml").Descendants("ROW"))\n{\n    var idElement = rowElement.Element("WF_PROCESSID");\n    if (string.IsNullOrWhiteSpace(idElement.Value))\n    {\n        idElement.Value = strWfId;\n    }\n}	0
26778239	26758481	Apply a default sort column in ObjectListView	objectListView1.Sort(targetColumn, SortOrder.Ascending);	0
8299133	8298942	Convert string to anonymous method	class ClientScript : IScriptFramework {\n    public override String Method(Object object) {\n        return %CLIENT_CODE%;\n    }\n}	0
24760195	24760168	How to edit a value using Entity Framework?	public sis_user Save(sis_user user, bool edit)\n    {\n        if (edit)\n        {\n            //How to edit?\n            sis_user userAux =_context.sis_user.FirstOrDefault(x => x.login == user.login);\n            userAux.Name = "Different Name";\n            _context.SaveChanges();\n            return user;\n        }\n\n        //To add.\n        _context.sis_sis_user.Add(user);\n        _context.SaveChanges();\n        return user;\n    }	0
787311	787303	How to use .Net assembly from Win32 without registration?	function ClrCreateManagedInstance(pTypeName: PWideChar; const riid: TIID;\nout ppObject): HRESULT; stdcall; external 'mscoree.dll';\n\nprocedure TMyDotNetInterop.InitDotNetAssemblyLibrary;\nvar\n  MyIntf: IMyIntf;\nhr: HRESULT;\nNetClassName: WideString;\nbegin\n//Partial assembly name works but full assembly name is preffered.\n    NetClassName := 'MyCompany.MyDLLName.MyClassThatImplementsIMyIntf,\n          MyCompany.MyDLLName';\n    hr := ClrCreateManagedInstance(PWideChar(NetClassName), IMyIntf, MyIntf);\n    //Check for error. Possible exception is EOleException with ErrorCode\n    //FUSION_E_INVALID_NAME = $80131047 2148732999 : The given assembly name \n    //or codebase was invalid.\n    //COR_E_TYPELOAD = $80131522 - "Could not find or load a specific type \n    //(class, enum, etc)"\n    //E_NOINTERFACE = $80004002 - "Interface not supported".\n    OleCheck(hr);\nend;	0
7157704	7157665	Reject a string with only strings in password	"^[^a-z](.*[^a-z])?$"	0
1530494	1530295	How can i do conditional formatting in datgridview in C#?	DataGridViewCellStyle cellstyle = new DataGridViewCellStyle();\ncellstyle.BackColor = Color.Black;\ncellstyle.ForeColor = Color.Yellow\ndgvAllData.Rows[5].Cells[2].Style = cellstyle;\ndgvAllData.Rows[3].Cells[2].Style = cellstyle;\ndgvAllData.Rows[6].Cells[2].Style = cellstyle;	0
21399557	18377818	Progressbar for loading data to DataGridView using DataTable	private void buttonLoad_Click(object sender, EventArgs e)\n    {\n        progressBar.Visible = true;\n        progressBar.Style = ProgressBarStyle.Marquee;\n        System.Threading.Thread thread = \n          new System.Threading.Thread(new System.Threading.ThreadStart(loadTable));\n        thread.Start();\n    }\n\n    private void loadTable()\n    {\n        // Load your Table...\n        DataTable table = new DataTable();\n        SqlDataAdapter SDA = new SqlDataAdapter();\n        SDA.Fill(table);\n        setDataSource(table);\n    }\n\n    internal delegate void SetDataSourceDelegate(DataTable table);\n    private void setDataSource(DataTable table)\n    {\n        // Invoke method if required:\n        if (this.InvokeRequired)\n        {\n            this.Invoke(new SetDataSourceDelegate(setDataSource), table);\n        }\n        else\n        {\n            dataGridView.DataSource = table;\n            progressBar.Visible = false;\n        }\n    }	0
3786123	3785483	control id change automatically in MasterPage	alert('<%= txtUName.ClientID %>')	0
5051547	5051528	How to calculate matrix determinant? n*n or just 5*5	for (j = i + 1; j < n + 1; j++)	0
11224535	11224364	How to parse XML without specific tag names in C#	XmlDocument doc = new XmlDocument();\n    doc.Load(fileName);\n    XmlNode root = doc.DocumentElement;\n    XmlNode s = root.SelectSingleNode('/' + rootName + '/' + section);	0
11377088	11377072	Convert DateTime to PRTime C#	public static class TimeHelper\n    {\n        // PRTime is Int64 count of microseconds from 1970-01-01-00-00-0000\n        static Int64 ToPRTime(DateTime dateTime)\n        {\n            TimeSpan t = (dateTime - new DateTime(1970, 1, 1));\n            return Convert.ToInt64(t.TotalMilliseconds * 1000);\n        }\n\n        static DateTime FromPrTime(Int64 prTime)\n        {\n            var someDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);\n            var milliSeconds = prTime / 1000;\n           return someDate.AddMilliseconds(milliSeconds);\n        }\n    }	0
5821218	5820922	Custom Attribute Method Level Authorization	[PrincipalPermission(SecurityAction.Demand, Role = 'LoginViaSiteVisitors')]\ninternal static bool HasDesiredPermissions()\n{\n   //....\n}	0
1528093	1525068	How do you make a user control property of type collection<string> editable/setable in visual studio designer	[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design",\n"System.Drawing.Design.UITypeEditor, System.Drawing")] \npublic Collection<string> ThisIsTheCollection { get; set; }	0
19021580	19021361	How to assign property value from DefaultValue attribute	foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))\n        {\n            DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];\n\n            if (myAttribute != null)\n            {\n                property.SetValue(this, myAttribute.Value);\n            }\n        }	0
24299389	24299323	How to hide DataBase Field in Crystal Report On Condition	{dtTotalProduction.Value11} = "NOT APPLICABLE"	0
25584284	25574832	How to do a multiple case insensitive replace using a StringBuilder	static readonly Regex re = new Regex(@"\b(\w+)\b", RegexOptions.Compiled);\nstatic void Main(string[] args)\n{\n    string input = @"Dear Name, as of dAte your balance is amounT!";\n    var replacements = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n    {\n        {"name", "Mr Smith"},\n        {"date", "05 Aug 2009"},\n        {"amount", "GBP200"}\n    };\n    string output = re.Replace(input, match => replacements.ContainsKey(match.Groups[1].Value) ? replacements[match.Groups[1].Value] : match.Groups[1].Value);\n}	0
12861736	12861698	Initialize an array to a value	for(int i = 0; i < constraintValue.Length; i++)\n    constraintValue[i] = -1;	0
12849599	12848655	Accessing My defined tags in RSS in C#	item.ElementExtensions[0]	0
18339719	18339133	Check if selected item is visible [virtual ListView in details view]	listView1.Items[SelectedItemIndex].Bounds.IntersectsWith(listView1.ClientRectangle)	0
5934529	5934486	Using local const	public void SomeMethod()\n{\n    const string dateFormat = "MM/dd/yyyy";\n\n    ... // Lot of operations\n\n\n    return Date.Now.ToString(dateFormat);\n}	0
3742860	3742711	C# - How to get certain generic types from an assembly using linq	from asm in AppDomain.CurrentDomain.GetAssemblies()\nfrom type in asm.GetTypes()\nwhere (type.IsClass || type.IsStruct)\n  && type.GetInterfaces().Any(\n  intf => intf.IsGenericType\n    && intf.GetGenericTypeDefinition() == typeof(ISomeInterface<>))\nselect type;	0
26584615	26552339	c# databound combobox changing data in other controls	comboBoxSelection1.BindingContext = new BindingContext();	0
6944257	6944187	How do I use a Static class in Global.asax	protected void Application_Start(object sender, EventArgs e)\n    {\n        // ROUTING.\n        Helper.RegisterRoutes(RouteTable.Routes);\n    }\n\n\npublic static class Helper\n{\n    public static void RegisterRoutes(RouteCollection routes)\n    {\n        // Register a route for Categories/All\n        routes.MapPageRoute(\n                "All Categories",       // Route name\n                "Categories/All",       // Route URL\n                "~/AllCategories.aspx"   // Web page to handle route\n            );\n\n        // Register a route for Products/{ProductName}\n        routes.MapPageRoute(\n            "View Content",             // Route name\n            "Content/{ContentId}",   // Route URL\n            "~/Cms/FrontEndCms/Content.aspx"        // Web page to handle route\n        );\n\n}	0
9722996	9722912	How to rotate a bitmap in C#, and end up with a bitmap?	Bitmap rotated = new Bitmap(<dimensions>)\nusing(Graphics g = Graphics.FromImage(rotated))\n{\n  // Code to draw the rotated image to g goes here\n}	0
9792946	9792882	Creating HTML from a DataTable using C#	DataTable dt = new DataTable();\n\ndt.Columns.Add("col1");\ndt.Columns.Add("col2");\ndt.Columns.Add("col3");\ndt.Rows.Add(new object[] { "a", "b", "c" });\ndt.Rows.Add(new object[] { "d", "e", "f" });\n\nstring tab = "\t";\n\nStringBuilder sb = new StringBuilder();\n\nsb.AppendLine("<html>");\nsb.AppendLine(tab + "<body>");\nsb.AppendLine(tab + tab + "<table>");\n\n// headers.\nsb.Append(tab + tab + tab + "<tr>");\n\nforeach (DataColumn dc in dt.Columns)\n{        \n    sb.AppendFormat("<td>{0}</td>", dc.ColumnName);        \n}\n\nsb.AppendLine("</tr>");\n\n// data rows\nforeach (DataRow dr in dt.Rows)\n{\n    sb.Append(tab + tab + tab + "<tr>");\n\n    foreach (DataColumn dc in dt.Columns)\n    {\n        string cellValue = dr[dc] != null ? dr[dc].ToString() : "";\n        sb.AppendFormat("<td>{0}</td>", cellValue);\n    }\n\n    sb.AppendLine("</tr>");\n}\n\nsb.AppendLine(tab + tab + "</table>");\nsb.AppendLine(tab + "</body>");\nsb.AppendLine("</html>");	0
16694799	16694581	Live connect SDK REST request for updating token	requestUrl.AppendFormat("&scope={0}", {whatever value the scope is suppose to be});	0
12254278	12254200	How to find if dataTable contains column which name starts with abc	var datatable = new DataTable();\n var abccolumns = datatable.Columns.Cast<DataColumn>()\n                                   .Where(c => c.ColumnName.StartsWith("abc"));	0
24664667	24664591	Linq to SQL One to Many query databind to Gridview	var results = from u in db.Users\n             Select new {\n                           UserID = u.UsrID,\n                           UserName = u.UserName,\n                           UserRoles = string.Join(", ", u.UserRoles.Select(r => r.Name))\n                        };	0
20758834	20758167	How can I use the factor variable to make the bitmap to fit in the pictureBox1?	pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;	0
34091527	34091319	How to clear a TextBox so that the default Undo method still functions?	textBox1.Focus();\ntextBox1.SelectAll();\nSendKeys.Send("{BACKSPACE}");	0
18362088	18361712	need to read files by their extensions	string extension = System.IO.Path.GetExtension(textBox_Choose.Text);\nif (extension == ".txt")\n    dotxt();\nelse if(extension == ".csv")\n    doexcel();\nelse\n{\n    //deal with an unexpected case\n}	0
21504239	21504216	Use of base constructor	class Base {\n\n  public Base(string type) { ... }\n}\n\nclass Extend : Base {\n\n  public Extend(string type, string name) : base(type) { ... }\n\n}	0
2368507	2368477	Can encode/decode a Image Object to keep it in a XML file using Compact Framework?	Convert.ToBase64String	0
18673434	18673405	Usage of C# get set methods	public int Capacity\n    {\n        get\n        {\n            return this.UsedCapacity/this.MaxCapacity;\n        }\n        set\n        {\n            if(value > MaxCapacity)\n               throw new Exception("Can't set capacity bigger then max capacity");\n            // Your code...\n        }\n\n    }	0
11067957	11067914	How do I reverse text in C#?	char[] chararray = this.toReverse.Text.ToCharArray();\nArray.Reverse(chararray);\nstring reverseTxt = "";\nfor (int i = 0; i <= chararray.Length - 1; i++)\n{\n    reverseTxt += chararray.GetValue(i);\n}\nthis.toReverse.Text = reverseTxt;	0
26759067	26738378	How can I tell what my parameter values are?	cmd2 -->   \n  Parameters -->\n    base -->\n      base -->\n        Non-Public members -->\n          [System.Data.SqlClient.SqlParameterCollection] -->\n             _items -->	0
19259389	19259358	Perform class methods on a casted object	genericclass.classpropertystring = ((DateTime)rdr["DateFromSQLDB"]).ToShortDateString();	0
24616566	24616498	Closing MemoryStream in async task	var requests = new Task[parts.Count];\n    foreach (var part in parts)\n    {\n        var partNumber = part.Item1;\n        var partSize = part.Item2;\n        requests[partNumber - 1] = UploadPartAsync(partNumber, partSize);\n    }\n\n    await Task.WhenAll(requests);\n\n...\n\nasync Task UploadPartAsync(int partNumber, int partSize)\n{\n    using (var ms = new MemoryStream(partSize))\n    using (var bw = new BinaryWriter(ms))\n    {\n        var offset = (partNumber - 1) * partMaxSize;\n        var count = partSize;\n        bw.Write(assetContentBytes, offset, count);\n\n        ms.Position = 0;\n        Console.WriteLine("beginning upload of part " + partNumber);\n        await uploadClient.UploadPart(uploadResult.AssetId, partNumber, ms);\n    }\n}	0
3264658	3264572	Using expression tree to navigate and return an object that owns a property	var parameterExpression = exp.Parameters[0];	0
28953052	28951751	IsolationLevel to lock table C#	var options = new TransactionOptions();\noptions.IsolationLevel = IsolationLevel.Serializable;\n\nusing (var scope = new TransactionScope(TransactionScopeOption.Required, options))\n{\n    var something = ReadSomething();\n    WriteSomething(something);\n    scope.Complete();\n}	0
6027522	6027449	Raise event in one thread to invoke methods in a second thread	var msgEnum = blockingCollection.GetConsumingEnumerable();\n\n//Per thread\nforeach( Message message in msgEnum )\n{\n   //Process messages here\n}	0
27279311	27279142	How search triple elements (key_value pair Dictionary) by one of them - IEnumerable error	[TestMethod]\npublic void Testing()\n{\n    byte b = 48;\n    var item = My_Class.CharactersMapper\n                       .Where(d => d.Key.Key_2 == b)\n                       .FirstOrDefault();\n\n    Assert.IsNotNull(item, "not found");\n\n    char ch = item.Value;\n    Assert.AreEqual('a', ch, "wrong value found");\n}	0
5987608	5987512	How to stop a form from loading in c# windows forms	public static void Main()\n    {\n        using (var signInForm = new SignInForm())\n        {\n            if (signInForm.ShowDialog() != DialogResult.OK)\n                return;\n        }\n        Application.Run(new MainForm());\n    }	0
31294418	31280710	Managing Application Insights Cookies	..snippet..\n }({\n        instrumentationKey: "<your key>",\n        sessionRenewalMs:<your custom value in ms>,\n        sessionExpirationMs:<your custom value in ms>\n\n    });	0
21184953	21184713	Append current message to the previous message	public void showMessage(string message, bool InLine)\n{\n    if (InLine)\n        messageBox.Items[messageBox.Items.Count-1] += message;\n    else\n        messageBox.Items.Add(message);\n}	0
32218195	32076457	Assign Tooltip to cell of selected row in Infragistics WebDataGrid	Protected void wdgMedGrp_InitializeRow(object sender, RowEventArgs e)\n{\n    try\n    {\n       e.Row.Items[1].Tooltip = e.Row.Items[2].Value.ToString();\n    }\n    catch (Exception){} // ignore any exceptions\n}	0
21285810	21267505	Query with RefNumberList for invoice QuickBooks QBFC	msgset.Attributes.OnError = ENRqOnError.roeContinue;\nstring[] InvoiceList = { "144", "9999" };\nforeach (string invNum in InvoiceList)\n{\n    IInvoiceQuery invQuery = msgset.AppendInvoiceQueryRq();\n    invQuery.ORInvoiceQuery.RefNumberList.Add(invNum);\n}	0
1928292	1928221	Array of array initialization by using unmanaged pointers in C#	unsafe static void T1(int numberOfRows, int numberOfColumns)\n    {\n        int* bigArray = stackalloc int[numberOfRows * numberOfColumns];\n        int** matrix = stackalloc int*[numberOfRows];\n\n        for (int i = 0; i < numberOfRows; i++)\n        {\n            matrix[i] = (bigArray + i * numberOfColumns);\n        }\n\n    }	0
6860728	6860529	Writing a comma separated string line by line to a file	if (chkWhiteList.Checked)\n    {\n        string rawUser = rtboxWhiteList.Text;\n        string[] list = rawUser.Split(new char[] { ',' });\n\n        using (StreamWriter whiteList = new StreamWriter(cleanDir + @"\white-list.txt"))\n            {\n                foreach (string user in list)\n                {\n                     whiteList.WriteLine(String.Format("{0}\r\n", user));\n                }\n\n            }\n    }	0
23681636	23681278	Replace String Between XML element tags	string key = "BusinessID";\nRegex x = new Regex("(<" + key + ".*" + "'>)(.*)(</" + key + ">)");\nstring s = @"<BusinessID xmlns='http://schemas.datacontract.org/2004/07/BG.Bus.Mobile.Classes'>string</BusinessID>";\nstring repl = "the replacement text";\nstring Result = x.Replace(s, "$1" + repl + "$3");	0
1999904	1999881	How to avoid/warn user for wrong entries in Windows Application	if(!int.TryParse(range.Text, out level))\n{\n  MessageBox.Show("Please Enter Only Number");\n}\nelse\n{\n  // No need for your Parse now, level has the right value already\n}	0
12037107	12036991	EF4 - insert only if a column has a unique value?	UNIQUE CONSTRAINT	0
32486306	32484192	Substring build in iteration loop based on delimiters	var IDArray = Convert.ToString(NodesID).Split('/');\nvar builder = new StringBuilder();\nfor (int i = 0; i < IDArray.Length; i++)\n{\n    builder.Append(IDArray[i]);\n    var stringToUse = builder.ToString();\n\n    //...\n    //Use the stringToUse here. It contains exactly what you want.\n    //...\n\n    builder.Append("/");\n}	0
5225122	5225061	Exponential Decay Surrounding Bounding Box	if (n<low)\n  a[n] *=  exp(-t*(low-n));\nelse if (n>high)\n  a[n] *=  exp(-t*(n-high));\nelse \n  a[n] *=  1.0;	0
9010716	9010439	Reference data in SQLDataReader by column and rows or any alternative	int resign = 0;\nint not_resign = 0;\nint resign_count = 0;\nint not_resign_count = 0;\n\nwhile (reader.Read())\n{   \n    if (Convert.ToInt32(reader["Resigned"]) == 1)\n    {\n        resign = Convert.ToInt32(reader["Sum"]);        \n        resign_count = Convert.ToInt32(reader["Count"]);        \n    }\n    else\n    {\n        not_resign = Convert.ToInt32(reader["Sum"]);        \n        not_resign_count = Convert.ToInt32(reader["Count"]);        \n    } \n}	0
281413	68283	View/edit ID3 data for MP3 files	TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = "New Album Title";\nf.Save();	0
6049673	6049522	Windows Service installation - current directory	Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);	0
25596834	25596187	WPF Datagrid get all checked rows (without using WPF binding)	foreach (DiseaseSymptom item in DiseaseSymptomsDataGrid.ItemsSource)\n{\n    if (((CheckBox)StatusIdColumn.GetCellContent(item)).IsChecked == true)\n    {\n        selectedDiseases.Add(item);\n    }\n}	0
16902846	16902577	Laggy Code in Game of Life 3D	for (int i = 0; i < cell.Count(); i++)\n    {\n        if (cell[i].dies)\n        {\n            if (animated && delay == 50)\n            {\n                cell.RemoveAt(i);\n                cellsdied += 1;\n                i--;\n            }\n            else\n            {\n                cell[i].willdie = true;\n            }\n        }\n    }	0
14047502	14047136	WPF Dynamic Controls	void OnButtonClick(object sender, RoutedEventArgs routedEventArgs)\n{\n    var files = Directory.GetFiles(@"C:\img");\n    foreach (var file in files)\n    {\n        var bitmap = new BitmapImage();\n        bitmap.BeginInit();\n        bitmap.UriSource = new Uri(file);\n        bitmap.CacheOption = BitmapCacheOption.OnLoad;\n        bitmap.EndInit();\n        var img = new Image { Source = bitmap };\n        img.MouseDown += OnImageMouseDown;\n        //Add img to your container\n    }\n}\n\nvoid OnImageMouseDown(object sender, MouseButtonEventArgs e)\n{\n    var img = sender as Image;\n    //Operate\n}	0
5026061	5026020	How can I assign a DBNull in a better way?	public double? GetVolume(object data)\n    {\n        double value;\n        if (data != null && double.TryParse(data.ToString(), out value))\n            return value;\n        return null;\n    }\n\n    public void Assign(DataRow theRowInput, DataRow theRowOutput)\n    {\n        theRowOutput[0] = (object)GetVolume(theRowInput[0]) ?? DBNull.Value;\n    }	0
6281621	6267470	Detect if Google Analytics eCommerce Tracking is enabled via Google Analytics API	ga:transactions	0
22318198	22317993	linq select a new, by list of columns names	var list = DataTableFromDB.AsEnumerable().Select(x => \n            {\n                var sampleObject = new ExpandoObject();\n                foreach (var col in columnsNames)\n                {\n                    ((IDictionary<String, Object>)sampleObject)\n                     .Add(col, x.Field<string>(col));\n                }\n                return sampleObject;\n            });	0
30075737	30075075	How to Use web Handlers for PDF creation?	public void ProcessRequest (HttpContext context) {\n\n    // Get your file as byte[]\n    string filename = "....file name.";\n    byte[] data = get your PDF file content here;\n\n    context.Response.Clear();\n                context.Response.AddHeader("Pragma", "public");\n                context.Response.AddHeader("Expires", "0");\n                context.Response.AddHeader("Content-Type", ContentType);\n                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));\n                context.Response.AddHeader("Content-Transfer-Encoding", "binary");\n                context.Response.AddHeader("Content-Length", data.Length.ToString());\n                context.Response.BinaryWrite(data);\n                context.Response.End(); \n\n}	0
9371526	9370859	GET FRIENDLY PORT NAME Programatically	Public Shared Function ListFriendlyCOMPOrt() As List(Of String)\n\n    Dim oList As New List(Of String)\n\n    Try\n        Using searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM26%'")\n            For Each queryObj As ManagementObject In searcher.Get()\n                oList.Add(CStr(queryObj("Caption")))\n            Next\n        End Using\n\n        Return oList\n\n    Catch err As ManagementException\n        MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)\n    End Try\n\n    Return oList\n\nEnd Function	0
3616816	3616774	How can i handle the key that was left to the Right control key	private void Form1_KeyUp(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Apps)\n    {\n        // the key in question was pressed (key code = 93)\n    }\n}	0
11285970	11285957	Changing multiple control properties at once	foreach(var c in this.Controls)\n{\n    var label = c as Label;\n    if(label != null) label.Text = "test";\n}	0
30457923	30455196	VSTO Addin Dialog Box	// Display message box\nDialogResult result = MessageBox.Show(messageBoxText, caption, button, icon);\n\n// Process message box results \nswitch (result)\n{\n    case MessageBoxResult.Yes:\n        // User pressed Yes button \n        // ... \n        break;\n    case MessageBoxResult.No:\n        // User pressed No button \n        // ... \n        break;\n    case MessageBoxResult.Cancel:\n        // User pressed Cancel button \n        // ... \n        break;\n }	0
17211438	17211155	how do we get the Column Size and dataType from getschemaTable?	StringBuilder sb = new StringBuilder();\n    foreach (DataRow row in schemaTable.Rows)\n    {\n        foreach (DataColumn column in schemaTable.Columns)\n        {\n            sb.AppendLine(column.ColumnName + ":"  +row[column.ColumnName].ToString());\n        }\n        sb.AppendLine();\n    }\n    File.WriteAllText(@"C:\Users\Manuela\Documents\GL4\WriteLines.txt", sb.ToString());	0
25727384	25721898	Handling unpredictable structure results from mongodb via csharp driver in visual studio	[BsonIgnoreExtraElements]\npublic class MongoClass\n{\n...\n}	0
8768597	8768480	How to change the value of dataGrid Cell automatically c#?	private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    if(e.ColumnIndex == 0 || e.ColumnIndex == 1)\n         this.dataGridView1.Rows[e.RowIndex].Cells[2].Value = System.Convert.ToInt32(this.dataGridView1.Rows[e.RowIndex].Cells[0].Value) * System.Convert.ToInt32(this.dataGridView1.Rows[e.RowIndex].Cells[1].Value);\n}	0
2421560	2421544	Launching an .exe from the current folder sometimes fails	string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\npath = Path.Combine(path, "OtherApp.exe");	0
9141379	9141345	How to read different types of data from text file (C#)?	from line in File.ReadAllLines(fileName).Skip(1)\n    let columns = line.Split(',')\n    select new\n    {\n      Plant = columns[0],\n      Material = int.Parse(columns[1]),\n      Density = float.Parse(columns[2]),\n      StorageLocation = int.Parse(columns[3])\n    }	0
6152668	6152646	The variable name '@Param' has already been declared	DS.SelectCommand = \n    "SELECT ReportName, ReportType, \n     FROM Table \n     WHERE ReportName LIKE @param \n     ORDER BY ReportType Desc";\nDS.SelectParameters.Clear();\nDS.SelectParameters.Add("Param", searchTxtBox.Text.Replace("'", "''"));	0
9244263	9242359	Optimise parameters in a set of non-linear equations simultaneously	f[i + j*n] = (RHS_of_equation[i](data_point[j]) - LHS_of_equation[i](data_point[j]))	0
7769975	7769928	Replace iterator at the end of string	var orig = text;\n\nwhile (Stuff.FindNameByText(text) != null)\n{\n    text = string.Format("{0} ({1})", orig, i.ToString());\n    i++;\n}\nFile.SetNewName(text)	0
23228318	23228141	How to run 2 methods at the same time?	class MainClass\n    {\n        public static void Main()\n        {\n            Task.Factory.StartNew(MainClass.test2);\n            Task.Factory.StartNew(MainClass.Update);\n\n            Console.ReadLine();\n        }\n\n        public static void test2()\n        {\n            while (true)\n            {\n                System.Threading.Thread.Sleep(500);\n                Console.WriteLine("Test");\n\n            }\n        }\n\n        public static void Update()\n        {\n            while (true)\n            {\n                Console.WriteLine("Hello");\n                System.Threading.Thread.Sleep(250);\n            }\n\n\n        }\n\n    }	0
1031276	1031261	Why is only a parameter-less Main method considered as a "valid startup object" for a C# project?	Main(String[] args)	0
11400784	11400440	How do I ensure my website or web app based on html works on all browsers properly	.gradient-bg {\n    background: #ececed;\n    background: -moz-linear-gradient(top,  #ececed 0%, #fefefe 100%);\n    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ececed), color-stop(100%,#fefefe));\n    background: -webkit-linear-gradient(top,  #ececed 0%,#fefefe 100%);\n    background: -o-linear-gradient(top,  #ececed 0%,#fefefe 100%);\n    background: -ms-linear-gradient(top,  #ececed 0%,#fefefe 100%);\n    background: linear-gradient(top,  #ececed 0%,#fefefe 100%);\n    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ececed', endColorstr='#fefefe',GradientType=0 );\n}	0
25500058	25499826	How to search text based on line number in string	private static string getLine(string text,string text2Search)\n{\n    string currentLine;\n    int endPoint = 10;\n    using (var reader = new StringReader(text)) \n    {\n        int lineCount = 0;\n        while ((currentLine= reader.ReadLine()) != null) \n        {\n            if (lineCount++ >= endPoint && \n                currentLine.Contains(text2Search,StringComparison.OrdinalIgnoreCase))\n            {\n                return currentLine;\n            }\n        }\n    }\n    return string.Empty;\n}	0
15929275	15928666	How do I easily parse a textbox to perform calculations if operators are found?	string value = "1.2+5.3-1";\n        char[] delimiters = new char[] { '+', '-' };\n        string[] parts = value.Split(delimiters);\n        string[] signs =  Regex.Split(value, "[0-9]|\\.");	0
316913	316903	How to check if I can create a file in a specific folder	string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");\n// perhaps check File.Exists(file), but it would be a long-shot...\nbool canCreate;\ntry\n{\n    using (File.Create(file)) { }\n    File.Delete(file);\n    canCreate = true;\n}\ncatch\n{\n    canCreate = false;\n}	0
21934350	21934303	Regex to remove carriage return followed by space	string text = Regex.Replace( contents, @"(\r|\n)+^ +", "" , RegexOptions.None | RegexOptions.Multiline );	0
7819916	7819833	Extract variables from text using RegEx and c#	Regex theRegex = new Regex(@"\[URL=([^\]]+)\]([^\[]+)\[/URL\]");\nstring text = "Lorem ipsum dolor sit amet, consectetur[URL=/test.aspx?ID=12345]lorem ipsum[/URL] adipiscing elit. Nullam interdum eleifend mauris, nec condimentum nisi lacinia sit amet. Mauris faucibus, orci ac[URL=/Default.aspx?ID=222222]lorem[/URL] convallis volutpat, dolor libero sollicitudin quam, id feugiat magna orci[URL=/Default.aspx?ID=333333]lorem ipsum dolor[/URL] quis augue. Integer nec euismod sem.";\nMatchCollection matches = theRegex.Matches(text);\nforeach (Match thisMatch in matches)\n{\n//        thisMatch.Groups[0].Value is e.g. "[URL=/test.aspx?ID=12345]lorem ipsum[/URL]"\n//        thisMatch.Groups[1].Value is e.g. "/test.aspx?ID=12345"\n//        thisMatch.Groups[2].Value is e.g. "lorem ipsum"\n\n}	0
1846333	1846311	Float Variable format	?5/3\n1.6666666666666667\n?String.Format("{0:0.00}", 5/3)\n"1,67"\n?System.Math.Round(5/3, 2)\n1.67\n\n?(5.0 / 3).ToString("0.00")\n"1,67"\n?(5 / 3).ToString("0.00")\n"1,00"\n?(5.0 / 3).ToString("E") //Exponential\n"1,666667E+000"\n?(5.0 / 3).ToString("F") //Fixed-point\n"1,67"\n?(5.0 / 3).ToString("N") //Number\n"1,67"\n?(5.0 / 3).ToString("C") //Currency\n"1,67 ???"\n?(5.0 / 3).ToString("G") //General\n"1,66666666666667"\n?(5.0 / 3).ToString("R") //Round-trip\n"1,6666666666666667"\n?(5.0 / 3).ToString("this is it .")\n"this is it 2"\n?(5.0 / 3).ToString("this is it .0")\n"this is it 1,7"\n?(5.0 / 3).ToString("this is it .0##")\n"this is it 1,667"\n?(5.0 / 3).ToString("this is it #####")\n"this is it 2"\n?(5.0 / 3).ToString("this is it .###")\n"this is it 1,667"	0
8327664	8327580	Creating an input for a customizable keyboard shortcut	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        Keys modifierKeys = e.Modifiers;\n\n        Keys pressedKey = e.KeyData ^ modifierKeys; //remove modifier keys\n\n        //do stuff with pressed and modifier keys\n??       var converter = new KeysConverter();\n        textBox1.Text = converter.ConvertToString(e.KeyData);\n}	0
23854233	23852359	Adding elements to XDocument at runtime from DataTable	XDocument doc = new XDocument(\n    new XDeclaration("1.0", "UTF-8", null),\n    new XElement("Document")\n);\n\nforeach(var row in dtAlpha.AsEnumerable())\n{\n    var alphabets = new XElement("Alphabets",\n                        new XElement("Data",\n                            new XElement("Capital", row.Field<string>("Capital")),\n                            new XElement("Small", row.Field<string>("Small"))\n                        )\n                    );\n    var language = new XElement("Language",\n                        new XElement("Name", "English")\n                    );\n    doc.Root.Add(alphabets);\n    doc.Root.Add(language);\n}	0
1758130	1743027	What is the best way to write a validation layer for SQLite	create table example\n( \n  age integer not null check (typeof(age)='integer'),\n  name text not null check (length(name) between 1 and 100),\n  salary integer check (salary is null or typeof(salary)='integer')\n)	0
8291724	8257635	Dynamically add a User Control to a page without page postback	StringBuilder b = new StringBuilder();\n    HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));\n    UserControl u = new Page().LoadControl("~/UserControl.ascx") as UserControl;\n    u.RenderControl(h);\n\n    return b.ToString();	0
7873514	7873432	Variable Declaration inside an IF C#	private bool IsFaceNoneOrPartial(Down down)\n{\n   var face = down.GetFace();\n\n   return face != Face.None || face != Face.Partial;\n}\n\n// Your code is now:\nif( down == null || IsFaceNoneOrPartial(down))\n{\n\n}	0
7433735	7433539	Format double type with minimum number of decimal digits	static void Main(string[] args)\n    {\n        Console.WriteLine(FormatDecimal(1.678M));\n        Console.WriteLine(FormatDecimal(1.6M));\n        Console.ReadLine();\n\n    }\n\n    private static string FormatDecimal(decimal input)\n    {\n        return Math.Abs(input - decimal.Parse(string.Format("{0:0.00}", input))) > 0 ?\n            input.ToString() :\n            string.Format("{0:0.00}", input);\n    }	0
27962372	27957505	Find Highest Divisible Integer In Set By X	private Int32 GetHighest(Int32 y, out Int32 totalMax)\n{\n    var Set = new Int32[] { 4, 3, 2 };\n    totalMax = int.MinValue;\n    int itemMax = int.MinValue;\n    foreach (var x in Set)\n    {\n       int total = x * (y / x);\n       if(total >= totalMax && (total > totalMax || x > itemMax))\n       {\n           totalMax = total;\n           itemMax = x;\n       }\n    }\n    return itemMax;\n}	0
10900111	10899942	Standards for accessing Webservice in C#	ServiceWse serivce = new ServiceWse();\nCookieContainer cookieContainer = new CookieContainer();\nserivce.Timeout = 1000 * 60 * CommonFunctions.GetConfigValue<int>(Consts.Common.WebServiceTimeout, 20);\nserivce.Url = CommonFunctions.GetConfigValue(Consts.Urls.MyServiceSecuredURL, string.Empty);\nserivce.CookieContainer = cookieContainer;\nif (CommonFunctions.GetConfigValue(Consts.Security.UseSecuredServices, false))\n    CommonFunctions.SetWSSecurity(_service.RequestSoapContext);	0
29018673	29012107	Accessing a public method from a class inside a SurfaceListBox	private void MainSurfaceListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n            var listBox = sender as SurfaceListBox;\n            if (listBox == null) return;\n            var childElement = FindChild(listBox, i => i as LoopPanelVertical);\n            childElement.LineUp();\n        }\n\n        static T FindChild<T>(DependencyObject obj, Func<DependencyObject, T> pred) where T : class\n        {\n            var childrenCount = VisualTreeHelper.GetChildrenCount(obj);\n            for (var i = 0; i < childrenCount; i++)\n            {\n                var dependencyObject = VisualTreeHelper.GetChild(obj, i);\n                var foo = pred(dependencyObject);\n                return foo ?? FindChild(dependencyObject, pred);\n            }\n            return null;\n        }	0
862693	862670	ImageGrid component or something like that	Panel[] panels = { panel0, panel1, ... }	0
20823713	20823614	Capture progressbar value onMouseClick	private void seekBar_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n{\n    double MousePosition = e.GetPosition(seekBar).X;\n    this.seekBar.Value = SetProgressBarValue(MousePosition);\n}\n\nprivate double SetProgressBarValue(double MousePosition)\n{\n    double ratio = MousePosition/seekBar.ActualWidth;\n    double ProgressBarValue = ratio*seekBar.Maximum;\n    return ProgressBarValue;\n}	0
4472412	4472385	How to produce a StackOverflowException with a few lines of code?	A() { new A(); }	0
30940608	30940481	How to download file without specific content type	return File(fs, System.Web.MimeMapping.GetMimeMapping(fileName), fileName);	0
24280692	24280046	Insert data from text file to sql	TextReader tr = File.OpenText(textBox1.Text);\n\n      string line;\n      while ((line = tr.ReadLine()) != null)\n      {\n          string[] parts = line.Split('|');\n         if(parts.Count() == 4)\n          {\n            string sql1 = "INSERT INTO Info(Name,Address,Age,Sex) select '" + parts[0] + "','" + parts[1]  + "','" + parts[2]  +"','" + parts[3]  +"'  ";\n          SQLcode.DoInsert(sql1);\n          }\n          else\n          {\n            // values are more than specified columns.\n          }\n      }	0
20053417	20052659	Pass parameter value from one function to another in C#	public class YourClass: YourBaseClass\n    {\n        QuizArgs args = null;\n        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)\n        {\n\n            args = navigationParameter as QuizArgs;\n            var SectorGroups = QuizDataSource.GetGroups(args.sector);\n            this.DefaultViewModel["Groups"] = SectorGroups;\n        }\n\n        void ItemView_ItemClick(object sender, ItemClickEventArgs e)\n        {\n             if(args == null)\n                 throw new NullReferenceException();\n\n             var itemId = args.UniqueId;\n             var sectorId = new QuizArgs\n             {\n                 sector = "nav",\n                 question = 2,\n                 Total = 0,\n                 type=itemId\n             };\n\n\n             this.Frame.Navigate(typeof(Quiz), sectorId);\n\n\n        }\n    }	0
8280599	8280583	How to start a process under current User?	Process.Start	0
9793475	9793102	How to terminate a log in	int count = 0;\n\n   public void Login()\n   {\n      if(count <= 3)\n      {\n           if (user_box.Text == "1111" && Password_box.Text == "Master")\n           {\n                 MessageBox.Show("Welcome Albert Einstein.");\n           }\n           else\n           {\n                 MessageBox.Show("No User Input.");\n                 count++;\n           }\n       }\n       else\n       {\n            user_box.Enabled = false;\n            Password_box.Enabled = false;\n       }\n   }	0
12273243	12273222	First mouse click event on an item in a listbox doesn't trigger the function	Listbox1_SelectedValueChanged(object sender, EventArgs e)\n{\n    Listbox listbox = (Listbox)sender;\n    MessageBox.Show(listbox.SelectedItem.ToString());\n}	0
30013065	30012461	saving listview into SQLite database - unhandled exception	private void writeResultsButton_Click(object sender, EventArgs e)\n{\n    sql_con = new SQLiteConnection("Data Source=DemoT.db;Version=3;New=True;Compress=True;");\n\n    sql_cmd = sql_con.CreateCommand();\n    sql_cmd.CommandText = "CREATE TABLE [tablename] ( [column1]....";\n\n    sql_cmd.Connection.Open();\n    sql_cmd.ExecuteNonQuery();\n\n    foreach(ListViewItem item in resultsList.Items)    \n    {    \n        sql_cmd.Parameters.Add("@columnHeader1", "value1");    \n        sql_cmd.Parameters.Add("@columnHeader2", "value2");    \n        sql_cmd.Parameters.Add("@columnHeader3", "value3");\n\n        sql_cmd.CommandText = "INSERT INTO notes (Path,Size,LastModified) values (@columnHeader1,@columnHeader2,@columnHeader3)";\n\n        sql_cmd.ExecuteNonQuery();    \n    }   \n\n    sql_cmd.Connection.Close();\n\n    sql_cmd.Dispose();\n}	0
11647828	9294234	How to keep change history while renaming files in Visual Studio using Perforce	Private Sub SolutionItemsEvents_ItemRenamed(ByVal ProjectItem As EnvDTE.ProjectItem,\n                                                ByVal OldName As String)\n                Handles SolutionItemsEvents.ItemRenamed\n\n        Dim process As System.Diagnostics.Process\n\n        process.Start("p4", "move -k " & ProjectItem.Properties.Parent.Document.Path &\n                      "\\" & OldName & " " & ProjectItem.Document.Path)\n    End Sub	0
27279818	27279737	Calling bootstrap function in a dynamic anchor control	HtmlAnchor login = new HtmlAnchor();\n login.Attributes.Add("data-toggle", "modal");\n login_pos.Controls.Add(login);	0
7700059	7699936	In C#, how should I create a csv from parent-child table?	class Node\n{\n    string name;\n    int population;\n\n    Node parent;\n    List<Node> children;\n\n    public Node(Node parent, string name, int population)\n    {\n        this.parent = parent;\n        this.name = name;\n        this.population = population;\n        children = new List<Node>();\n    }\n\n\n    public void Add(Node child)\n    {\n        children.Add(child);\n    }\n}	0
4977577	4977571	How to print out the value that subprocess prints with C#?	// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = "Write500Lines.exe";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();	0
10131242	10130921	Assigning a string to a TextBox.Text property on a form causes a NullReferenceException	public ApplicationProperties(String AFullPath, String ATitle, String ADescription, Boolean ALegacy, Boolean AProduction, Boolean ABeta)\n        : this() // --> Call the parameterless constructor before executing this code\n    { \n        _fullPath = AFullPath; \n        _title = ATitle; \n        _description = ADescription; \n        legacy = ALegacy; \n        production = AProduction; \n        beta = ABeta; \n        this.CenterToScreen(); // --> Maybe move this to the Shown event (not sure if you need to)\n    }	0
2976716	2976701	Save WebBrowser Control Content to HTML	File.WriteAllText(path, browser.Document.Body.Parent.OuterHtml, Encoding.GetEncoding(browser.Document.Encoding));	0
107448	107196	C# - Why is a different dll produced after a clean build, with no code changes?	View > MetaInfo > Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next step\n\nView > MetaInfo > Show!	0
33705492	33705449	Traversing through a array of lists	for(int i = 0; i < myArr[0].Count; i++) Console.WriteLine(myArr[0][i]);	0
28680963	28680890	how to get values from fully qualified data type?	public override ToString()\n{\n    return this.Name + "," + this.Weight + "," + this.Quantity\n}	0
26102860	26102809	c# Check if a file path contains a specific directory	public static bool IsFileBelowDirectory(string fileInfo, string directoryInfo, string separator)\n{\n    var directoryPath = string.Format("{0}{1}"\n    , directoryInfo\n    , directoryInfo.EndsWith(separator) ? "": separator);\n\n    return fileInfo.StartsWith(directoryPath, StringComparison.OrdinalIgnoreCase);\n}	0
1818296	1818131	convert an enum to another type of enum	public static class TheirGenderExtensions\n{\n    public static MyGender ToMyGender(this TheirGender value)\n    {\n        // insert switch statement here\n    }\n}\n\npublic static class MyGenderExtensions\n{\n    public static TheirGender ToTheirGender(this MyGender value)\n    {\n        // insert switch statement here\n    }\n}	0
18009197	18008715	Persian text box to hex to byte	byte[] yourStrBytes = Encoding.GetEncoding("your encoding").GetBytes("your str");\n  string hexStr = BitConverter.ToString(yourStrBytes).Replace("-", "");\n  byte[] hexStrBytes=Encoding.UTF8.GetBytes(hexStr);	0
182823	180930	Object Initializer syntax to produce correct Json	List<string> data = new List<string>()\n        {\n            "One",\n            "Two",\n            "Three"\n        };\n\n        string result =\n            "{ "\n            +\n            string.Join(", ", data\n              .Select(c => @"""" + c + @""": """ + c + @"""")\n              .ToArray()\n            ) + " }";	0
21486288	21486217	How to create loop for changing Lable[ID] in asp.net using c#?	for(int index = 1; index <= 3; index ++)\n{\n    Label label = (Label)this.Controls.Find("Label" + index, false)[0];\n    label.Text = multiarray[rowcount - 1, index]; \n}	0
25759392	25722473	Updating a DataTable	foreach(DataRow drHierarchyListToUpdate in ds.Tables["Hierarchy"].Rows)\n        {\n            string HierarchyParent = drHierarchyListToUpdate["HierarchyParent"].ToString();\n            string HierarchyValueDescription = drHierarchyTrueValueList["HierarchyValueDescription"].ToString();\n            int HierarchyParentType = Convert.ToInt32(drHierarchyListToUpdate["HierarchyParentType"]);\n\n            if (HierarchyParent == HierarchyValueDescription && HierarchyParentType != 0)\n            {\n                drHierarchyListToUpdate["HierarchyParentValue"] = Convert.ToInt32(drHierarchyTrueValueList["HierarchyTrueValue"]);\n            }\n            else if (HierarchyParent != HierarchyValueDescription && HierarchyParentType == 0)\n            {\n                drHierarchyListToUpdate["HierarchyParentValue"] = 0;\n            }\n        }\n        ds.Tables["Hierarchy"].AcceptChanges();	0
17493790	17493555	How to nest Solution Folders in IWizard implementation in VSTemplate	ICollection<KeyValuePair<String, SolutionFolder>> _solutionFolders = new Dictionary<String, SolutionFolder>();\n\n_solutionFolders.Add(new KeyValuePair<string, SolutionFolder>("Api", (SolutionFolder)solution.AddSolutionFolder("Api").Object));\n\n_solutionFolders.Add(new KeyValuePair<string, SolutionFolder>("Api.Commands", (SolutionFolder)_solutionFolders.Single(d => d.Key.Equals("Api")).Value.AddSolutionFolder("Commands").Object));\n_solutionFolders.Add(new KeyValuePair<string, SolutionFolder>("Api.Queries", (SolutionFolder)_solutionFolders.Single(d => d.Key.Equals("Api")).Value.AddSolutionFolder("Queries").Object));	0
7661077	7660160	Is it possible to change what is displayed in a Visual Studio Debugger Variables window Value column for a 3rd party class?	[assembly: DebuggerDisplay(@"\{Color = {color}}", Target = typeof(Pen))]	0
27022854	27022809	C# Filter List of Objects With a Simple List	filteredList = allOrgs.Where(a => !childOrgs.Any(c => c.id == a.id)\n                               && !parentOrgs.Any(c => c.id == a.id) \n                            );	0
3946332	3946312	How do I Convert Integer value to Binary value as a string in C#?	// bin = "1110100"\nvar bin = Convert.ToString(116, 2)	0
10613580	10602259	change column backcolor to default in C# Datagridview	Column1.CellTemplate.Style = Column2.CellTemplate.Style;	0
6544206	6543548	Whats going on with this byte array?	EF BF BD	0
3910268	3910222	Combine object properties into a list with LINQ	var result = from item in someList\n             let values = new int[]{ item.A, item.B, item.C, ... }\n             from x in values\n             select x;	0
714416	707518	Printing transformed XML	private static void PrintReport(string reportFilename)\n{\n    WebBrowser browser = new WebBrowser();\n\n    browser.DocumentCompleted += browser_DocumentCompleted;\n\n    browser.Navigate(reportFilename);\n}\n\nprivate static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    WebBrowser browser = sender as WebBrowser;\n\n    if (null == browser)\n    {\n        return;\n    }\n\n    browser.Print();\n\n    browser.Dispose();\n}	0
19707953	19707871	How to get Array of one property from List of objects?	List<Flywheel> parts1 = new List<Flywheel>();\nvar mydata = parts1.Select(x => x.FW_DMF_or_Solid).OrderBy(x => x).Distinct().ToArray();	0
2738195	2738155	Quickly retrieve the subset of properties used in a huge collection in C#	List<string> categories = collection\n    .Cast<Foo>()\n    .Select(foo => foo.Category)\n    .Distinct()\n    .ToList();	0
29366324	29361275	Unable to add toasts to the group in windows phone 8.1	toast.Group	0
10168126	10168103	Retreiving SQL row and set to string	//Taken from MSDN\nprivate static void ReadOrderData(string connectionString)\n{\n    string queryString =\n        "SELECT OrderID, CustomerID FROM dbo.Orders;";\n    using (SqlConnection connection = new SqlConnection(\n               connectionString))\n    {\n        SqlCommand command = new SqlCommand(\n            queryString, connection);\n        connection.Open();\n        SqlDataReader reader = command.ExecuteReader();\n        try\n        {\n            while (reader.Read())\n            {\n                Console.WriteLine(String.Format("{0}, {1}",\n                    reader[0], reader[1]));\n            }\n        }\n        finally\n        {\n            // Always call Close when done reading.\n            reader.Close();\n        }\n    }\n}	0
9636006	9635955	Regex expression	\S*\s?\S*	0
26772597	26772481	How to set database table values in a string?	var rows = ds.Tables[0].Rows;\nforeach (DataRow row in rows)\n{\n   var name = row["Name"];\n   var code= row["EmpCode"];\n   var type= row["TypeName"];\n}	0
13488554	13488245	DateTime conversion exception	String date = "1980/1/1";\nDateTime dateTime = DateTime.ParseExact(date, "yyyy'/'M'/'d",null);	0
7904482	7904342	Add hover property for menu in asp.net, I am using a link as menu	#NavigationMenu a:hover {\n background-color: #FF0000;\n color: #0000FB;\n text-decoration: none;\n}\n\na:hover {\n background-color: #F9F6F4;\n color: #465c71;\n text-decoration: none;\n}	0
5874794	5850529	Accessing a TextBlock which is contained inside a ListBox	if(((WhateverTypeIsInDetailsCollection)HINList.SelectedItem).Category1 == something) {\n     // then do whatever you want\n}	0
13672968	13668174	Control cursor in 3D	using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())\n{\n if (skeletonFrame == null)\n     return;\n\n    if (skeletons == null || skeletons.Length != skeletonFrame.SkeletonArrayLength)\n    {\n        skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];\n    }\n    skeletonFrame.CopySkeletonDataTo(skeletons);\n\n    if (skeletons.All(s => s.TrackingState == SkeletonTrackingState.NotTracked))\n        return;\n\n    Skeleton firstTrackedSkeleton = skeletons.Where(s => s.TrackingState == SkeletonTrackingState.Tracked).FirstOrDefault();\n\n    CoordinateMapper cm = new CoordinateMapper(YourKinectSensor);\n    ColorImagePoint colorPoint = cm.MapSkeletonPointToColorPoint(first.Joints[JointType.HandRight].Position, ColorImageFormat.RgbResolution640x480Fps30);\n\n     //Here the variable colorPoint have the X and Y values that you need to position your cursor.\n}	0
5288589	5288568	C# - When to use standard threads, ThreadPool, and TPL in a high-activity server	.BeginRead(...)	0
2729623	2729584	Performance issues with repeatable loops as control part	_filteredCalls = _filteredCalls.Where(c => c.Caller.E164.Length > 4 || c.Caller.E164.Equals("0"))	0
25889061	25888709	how to create a new uri which needs to contain a string	var folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);\nvar path = Path.Combine(folder, "myFolder/StoryBox/desert.html");\nvar uri = new Uri("file:" + path);	0
32776683	32776032	Change label text from the button outside GridView asp.net c#	protected void btn_Click(object sender, EventArgs e)\n    {\n        foreach (GridViewRow row in YourGridviewName.Rows)\n        {\n\n          Label label = row.FindControl("lbl_reviewDate") as Label;\n          label.Text = DateTime.Now.Date.ToString("d");\n          Label labelID = row.FindControl("lbl_id") as Label;\n        }\n    }	0
15814997	15814917	Generic dependency injection with Unity	container.RegisterType(typeof(IMyGenericInterface<>), typeof(MyConcreteGenericClass<>));	0
28282560	28251464	Add-in framework: get AddIn location	System.Reflection.Assembly.GetAssembly(_view.GetType()).Location	0
22902509	22902265	Arrange controls in circular/rectangular shape dynamically	int radius = 200;\n\n        for (int i = 1; i < 20; i++)\n        {\n            TextBox tb = new TextBox();\n\n            tb.Left = (int)(Math.Cos((double)i) * radius) + radius;\n            tb.Top = (int)(Math.Sin((double)i) * radius) + radius;\n\n            this.Controls.Add(tb);\n        }	0
28589069	28567075	Determine if a Database is "Equal" to a DacPackage	...\nDacServices dacSvc = new DacServices(connectionString);\nstring deployScript = dacSvc.GenerateDeployScript(myDacpac, @"aDb", deployOptions);\n\nif (DatabaseEqualsDacPackage(deployScript))\n{\n  Console.WriteLine("The database and the DacPackage are equal");\n}\n...\nbool DatabaseEqualsDacPackage(string deployScript)\n{\n  string equalStr = string.Format("GO{0}USE [$(DatabaseName)];{0}{0}{0}GO{0}PRINT N'Update complete.'{0}GO", Environment.NewLine);\n  return deployScript.Contains(equalStr);\n}\n...	0
11439406	11438491	How do I store TreeViewItem ToggleButton, similar to TreeViewItem Header object?	private void Click(object sender, RoutedEventArgs e)\n{\n    if (e.Source == sender)\n    {\n\n    }\n}	0
7200383	7200311	Is there any listbox control on the page?	if (Page.Controls.OfType<ListBox>().Count() > 0)\n   {\n       Response.Write("Listbox control exist");\n   }	0
6440651	6440489	filter duplicate URLs domain from List c#	[TestMethod]\n    public void TestMethod1()\n    {\n        var sites = new List<string> {"yahoo.com", "http://yahoo.com", "http://www.yahoo.com"};\n\n        var result = sites.Select(\n            s =>\n            s.StartsWith("http://www.")\n                ? s\n                : s.StartsWith("http://") \n                      ? "http://www." + s.Substring(7) \n                      : "http://www." + s).Distinct();\n\n        Assert.AreEqual(1, result.Count());\n    }	0
13896097	13893315	Add a List<object> to EF	myDBContext.GameStates.Include("playerHand").Include("dealerHand").Include("theDeck").Include("dealerHidden").where(...);	0
34241546	34211751	Binding DatagridColumn to StaticResource pointing to ObservableCollection in WPF	SelectedItem="Client"	0
1811760	1811756	How to get the maximum of more than 2 numbers in Visual C#?	int[] array1 = { 0, 1, 5, 2, 8 };\nint[] array2 = { 9, 4 };\n\nint max = array1.Concat(array2).Max();\n// max == 9	0
34411603	34411087	ComboBox KeyDown event how to take into account last pressed key	string str = string.Empty;\n        if (e.Key > Key.D0 && e.Key < Key.D9)\n        {\n            str = ((int)e.Key - (int)Key.D0).ToString();\n        }\n        MessageBox.Show(str);	0
17390807	17390763	c# - Multidimensional Array position	string[][] arr = new string[10][];\n\narr[1] = new string[10];\narr[1][1] = "3";	0
1200593	1154558	How to load an Excel Addin using Interop	var excel = new Application();\nvar workbook = excel.workbooks.Add(Type.Missing);\nexcel.RegisterXLL(pathToXll);\nexcel.ShowExcel();	0
8603340	7849564	How to upload a file in encrypted form	GetObjectMetadataRequest meta = new GetObjectMetadataRequest();\n\nGetObjectMetadataResponse response = s3Client.GetObjectMetadata(meta);\nif(response.ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256)\n{\n   // your code goes here\n}	0
18412443	18407548	How to detect Cameras attached to my machine using C#	ManagementObjectSearcher()	0
30728387	30728240	Click to a random url on page with GeckoFX	var links = new List<GeckoElement>()\nforeach(var link in browser.Document.Links) {\n   if(!String.IsNullOrEmpty(link.GetAttribute("href").ToString()))\n      links.Add(link);\n}\nif(links.Count > 0)\n   ((GeckoHtmlElement)links[new Random().Next(0, links.Count)]).Click()\nelse\n   MessageBox.Show("No Links found")	0
12207284	12204652	How do I associate an IP address to a network name in Windows 8 Metro	// Get all profiles\nvar profiles = NetworkInformation.GetConnectionProfiles();\n\n// filter out profiles that are not currently online \nvar connected = from p in profiles where p.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None select p;\n\n// find all hosts\nvar hosts = NetworkInformation.GetHostNames();\n\n// find hosts that have an IP Address\nvar online = from h in hosts where h.IPInformation != null select h;\n\n// Now loop there each online connection and match network adapter ids with hosts\nforeach (var c in connected)\n{\n   var matches = from o in online where o.IPInformation.NetworkAdapter.NetworkAdapterId == c.NetworkAdapter.NetworkAdapterId select o;\n}	0
4791088	4791057	Converting Timespan to DateTime in C#	double d = double.Parse(((Range)ws.Cells[4, 1]).Value2.ToString());\n\nDateTime conv = DateTime.FromOADate(d);	0
28846711	28844948	Retrieve AD sAMAccountNames from memberOf property	var samNames = new List<string>();\nusing (var group = GroupPrincipal.FindByIndentity(principalContext, "GroupName"))\n{\n     if (group != null)\n     {\n         var users = group.GetMembers(true);\n         foreach (UserPrincipal user in users)\n         {\n             samNames.add(user.SamAccountName);\n         }\n     }\n}	0
13271260	13269559	How to Custom Group By multiple records according some criteria	int[] groupA = { 1, 2, 3 };\n        int[] groupB = { 4, 5 };\n\n        var result = data\n            .GroupBy(a => groupA.Contains(a.Group) ? "A" : \n                          groupB.Contains(a.Group) ? "B" : \n                          "N/a")\n            .Select(a => new\n            {\n                KEY = a.Key,\n                VALUE = a.Count()\n            });	0
627747	627649	Getting data from WCF Async methods inside a foreach loop	private void SomeMethod()\n{    \n   List itemsList = GetItems();    \n   foreach(Item i in itemsList)    \n   {        \n      MyClient client = new MyClient();      \n      client.GetSomeValueCompleted += client_GetSomeValueCompleted;      \n      client.GetSomeValueAsync(i.ID, client);\n   } \n}   \n\nprivate void client_GetSomeValueCompleted(object sender, GetSomeValueEventArgs e)\n{  \n   int id = e.Result;  \n\n   //  how do I assign this ID to my itemsList object, i  ???\n   (e.UserState as MyClient).ID = id;\n}	0
915877	915850	Is there a lock statement in VB.NET?	// C#\nlock (someLock)\n{\n    list.Add(someItem);\n}\n\n// VB\nSyncLock someLock\n    list.Add(someItem)\nEnd SyncLock	0
8050744	8050663	How to insert data by generating the primary key automatically	"insert into realtimedata(column1, column2, ... ,columnN) values('" + Name+ "','" + Symbol+ "','" + D + "','" + Green + "','" + GB + "','" + GS + "','" + GBIntraBuy + "','" + GBTR1Buy + "','" + GBTR2Buy + "','" + GBTR3Buy + "','" + GBIntraSell + "','" + GBTR1Sell + "','" + GBTR2Sell + "','" + GBTR3Sell + "','" + GRSTL + "','" + Red + "');"	0
20682535	20682475	how to add menu at front	MainMenu.Items.AddAt(0, mnuTest);	0
3427046	3426914	How to distinguish Mouse.Clicks from different part of a control	private void Control_MouseDown(object sender, MouseButtonEventArgs e)\n    {\n       if( ((FrameworkElement)(e.OriginalSource)).Name == "PART_Rectangle")\n       {\n           //RectangleMouseDown \n      }\n    }	0
7181208	7181046	Adding to a vector2 in C#? How so?	location.X += (orth.X * turningRadius);\nlocation.Y += (orth.Y * turningRadius);	0
10149158	10148986	Split a period of time into multiple time periods	var realDates = splitDates\n    .Where(d => d > dateFrom && d < dateTo)\n    .Concat(new List<DateTime>() {dateFrom.AddDays(-1), dateTo})\n    .Select(d => d.Date)\n    .Distinct()\n    .OrderBy(d => d)\n    .ToList();\n\n// now we have             (start - 1) -- split1 -- split2 -- split3 -- end\n// we zip it against          split1   -- split2 -- split3 --  end\n// and produce       start,split1 -- split1+1,split2 -- split2+1,split3 -- split3+1,end\n\nrealDates.Zip(realDates.Skip(1), (a, b) => Tuple.Create(a.AddDays(1), b));	0
25230466	25223777	How can i totally disable tabbing on DataGridView but keep ability to select rows?	protected override void OnActivated(EventArgs e) {\n\n    ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;\n    objKeyboardProcess = new LowLevelKeyboardProc(captureKey);\n    ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);\n\n    base.OnActivated(e);\n}\n\nprotected override void OnDeactivate(EventArgs e) {\n\n    UnhookWindowsHookEx(ptrHook);\n    objKeyboardProcess = null;\n    ptrHook = IntPtr.Zero;\n\n    base.OnDeactivate(e);\n}	0
17952749	17950398	SQL Returning rows with max value in column, within a specific range	var commandText = string.Format("SELECT T1.IsoShtRevID, T1.LineID, T1.FileName, T1.Revision " +\n                                "FROM dbo.PDSIsometricSheets T1 " +\n                                "INNER JOIN (" +\n                                    "SELECT LineID, MAX(Revision) as MaxRevision " +\n                                    "FROM dbo.PDSIsometricSheets " +\n                                    "WHERE SchemaName='{0}' AND Revision <= 5 AND Revision >= 0" +\n                                    "GROUP BY LineID" +\n                                ") T2 " +\n                                "ON T1.LineID = T2.LineID AND T1.Revision = T2.MaxRevision ", projectNo);	0
19264680	19264547	Adding object into a list c# -windows phone	var  sampleList = new HashSet<Result>(rootoject.result.Where(item\n            => item.status == "approved")).ToList();\nvar sampleRootObject = new RootObject();\nsampleRootObject.result = sampleList; // The setter needs to be made public\napprovedList.Add( sampleRootObject);	0
32377751	32374726	Connecting to database dynamically with table adapters	//Work with existing connection...\n\ntableAdapter1.Connection.Close();\ntableAdapter1.Connection.ConnectionString = "Your new DB connection string";\ntableAdapter1.Connection.Open();\n\n//Work with same adapter but now pointing to new DB specified in above string.	0
6872175	6871323	WPF difficult binding: bind value to IConverter with as input the result from a static method	public class Item\n{\n    public string DisplayText { get; set; }\n}\n\npublic class ItemViewModel\n{\n    private Item _model;\n\n    public string DisplayText\n    {\n        get { return _model.DisplayText; }\n    }\n\n    public int Score\n    {\n        get { return MyStaticClass.MyStaticMethod(_model);\n    }\n}	0
11824650	11824605	Replace Variables in String?	foreach (var tag in ArrayNode)\n{\n  Comp = Comp.Replace(tag.TagPointer, tag.TagValue);\n}	0
33713442	33713298	C# Run a loop in the background	using System;\nusing System.Threading;\n\nnamespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var ts = new ThreadStart(BackgroundMethod);\n            var backgroundThread = new Thread(ts);\n            backgroundThread.Start();\n\n            // Main calculations here.\n            int j = 10000;\n            while (j > 0)\n            {\n                Console.WriteLine(j--);\n            }\n            // End main calculations.\n        }\n\n        private static void BackgroundMethod()\n        {\n            // Background calculations here.\n            int i = 0;\n            while (i < 100000)\n            {\n                Console.WriteLine(i++);\n            }\n            // End background calculations.\n        }\n    }\n}	0
31811601	31811264	concurrect oprating with limit on thread count in a infinity loop	public class ThreadWorker<T>\n{\n    SemaphoreSlim _sem = null;\n    List<T> _lst;\n\n    public ThreadWorker(List<T> lst, int maxThreadCount)\n    {\n        _lst = lst;\n        _sem = new SemaphoreSlim(maxThreadCount);\n    }\n\n    public void Start()\n    {\n        var i = 0;\n        while (i < _lst.Count)\n        {\n            i++;\n            var pull = _lst[i];\n            _sem.Wait(); /*****/\n            Process(pull);\n        }\n    }\n\n    public void Process(T item)\n    {\n        var t = new Thread(() => Opration(item));\n        t.Start();\n    }\n\n    public void Opration(T item)\n    {\n        Console.WriteLine(item.ToString());\n        _sem.Release(); /*****/\n    }\n}	0
19884370	19884313	Getting values form multiple text boxes with same name	int i;\nvar items = Request["important"];\nstring myString = "test ";\nfor (i=0; i < items.Length; i++)\n{\n    myString += items[i];\n\n}\nResponse.Write(myString);	0
12598998	12587709	C# SSIS Data Flow Component - Creating custom input columns	public override void OnInputPathAttached(int inputID)\n    {\n        IDTSInput100 input = ComponentMetaData.InputCollection[0];\n\n        IDTSVirtualInput100 vInput = input.GetVirtualInput();\n\n        IDTSExternalMetadataColumnCollection100 externalColumnCollection = input.ExternalMetadataColumnCollection;\n        IDTSExternalMetadataColumn100 externalColumn;                \n\n        foreach (IDTSVirtualInputColumn100 vCol in vInput.VirtualInputColumnCollection)\n        {            \n            externalColumn = externalColumnCollection.New();\n            externalColumn.Name = vCol.Name;\n            externalColumn.DataType = vCol.DataType;               \n        }\n    }	0
32245731	32244730	Win 10 UAP - Drawing a Line to the Canvas	var line = new Line();\n        line.Stroke = new SolidColorBrush(Colors.Black);\n        line.StrokeThickness = 3;\n        //line.Width = 50;\n        line.X1 = 0;\n        line.Y1 = 0;\n        line.X2 = 50;\n        line.Y2 = 0;\n\n        Canvas.SetTop(line, 50);\n        Canvas.SetLeft(line, 50);\n\n\n        TheCanvas.Children.Add(line);	0
21899503	21898741	Passing parameter to WCF Service Ctor from Proxy Client	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] \n public class Service : IService	0
11326290	11323584	Unable to read data from the transport connection: The connection was closed error in console application	request.KeepAlive = false;\nrequest.ProtocolVersion = HttpVersion.Version10;	0
2010555	2010548	DateTime formatting in .Net for MySQL database	command.Text = "insert into myTable(myDate) values(?dateParam)";\ncommand.Parameters.Add("?dateParam", theDate);	0
28819033	28818946	How to get top 5 products with highest views?	var topProductsIds = db.PRODUCT_VIEWS_TABLE // table with a row for each view of a product\n    .GroupBy(x => x.PRODUCT_ID) //group all rows with same product id together\n    .OrderByDescending(g => g.Count()) // move products with highest views to the top\n    .Take(5) // take top 5\n    .Select(x => x.Key) // get id of products\n    .ToList(); // execute query and convert it to a list\n\nvar topProducts = db.PRODUCTS // table with products information\n    .Where(x=> topProductsIds.Contains(x.ID)); // get info of products that their Ids are retrieved in previous query	0
19765051	19756239	deactivate ' pin to start ' on Application List page when pinning an app via code using C#?	var primaryTile = ShellTile.ActiveTiles.First();	0
9861050	9852496	Creating a cab. installer with compact framework intergrated	_setup.xml	0
6003423	5989380	Sending specific keys on the Numpad like +, -, / or Enter (simulating a keypress)	bool keyDown = true; // true = down, false = up\n const uint WM_KEYDOWN = 0x0100;\n const uint WM_KEYUP = 0x0101;\n const int VK_RETURN = 0x0D;\n\n IntPtr handle = IntPtr.Zero;\n // Obtain the handle of the foreground window (active window and focus window are only relative to our own thread!!)\n IntPtr foreGroundWindow = GetForegroundWindow();\n // now get process id of foreground window\n uint processID;\n uint threadID = GetWindowThreadProcessId(foreGroundWindow, out processID);\n if (processID != 0)\n {\n // now get element with (keyboard) focus from process\n GUITHREADINFO threadInfo = new GUITHREADINFO();\n threadInfo.cbSize = Marshal.SizeOf(threadInfo);\n GetGUIThreadInfo(threadID, out threadInfo);\n handle = (IntPtr)threadInfo.hwndFocus;\n }\n\n int lParam = 1 << 24; // this specifies NumPad key (extended key)\n lParam |= (keyDown) ? 0 : (1 << 30 | 1 << 31); // mark key as pressed if we use keyup message\n PostMessage(handle, (keyDown) ? WM_KEYDOWN : WM_KEYUP, VK_RETURN, lParam); // send enter	0
8090509	8090451	How to get the index of the selected column in data grid view in windows forms using c#?	private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        MessageBox.Show(e.ColumnIndex.ToString());\n    }	0
31426503	31425485	Accessing Listview index above index 9 in C#?	public void populateProductList()\n        {\n            string cmdString = "SELECT * FROM PRODUCT";\n\n            StockDbConnection dbcon = new StockDbConnection();\n            SqlCeConnection Conn = new SqlCeConnection(dbcon.ReturnConnection("ConnString"));\n            SqlCeCommand cmd = new SqlCeCommand(cmdString, Conn);\n            DataSet ds;\n            try\n            {\n                Conn.Open();\n\n                SqlCeDataAdapter da = new SqlCeDataAdapter(cmdString, Conn);\n                da.fill(ds);\n                lstDGView.DataSource=ds;\n\n            }\n            catch (Exception exp)\n            {\n                MessageBox.Show(exp.Message);\n            }\n        }	0
9152838	9141198	How to programmatically import a pfx with a chain of certificates into the certificate store?	string certPath = <YOUR PFX FILE PATH>;\nstring certPass = <YOUR PASSWORD>;\n\n// Create a collection object and populate it using the PFX file\nX509Certificate2Collection collection = new X509Certificate2Collection();\ncollection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);\n\nforeach (X509Certificate2 cert in collection)\n{\n    Console.WriteLine("Subject is: '{0}'", cert.Subject);\n    Console.WriteLine("Issuer is:  '{0}'", cert.Issuer);\n\n    // Import the certificate into an X509Store object\n}	0
13953021	13950118	Invoke a SignalR hub from .net code as well as JavaScript	var hubContext = GlobalHost.ConnectionManager.GetHubContext<UpdateNotification>();\nhubContext.Clients.All.yourclientfunction(yourargs);	0
23709048	23709034	How do i display the first item in the already?	comboBox1.SelectedIndex = 0;	0
31367725	31363649	Save data in windows phone 8.1 c#	var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;\n if (localSettings.Values.ContainsKey("textblockVisibility"))\n {\n     var value = localSettings.Values["textblockVisibility"];\n     textblock.Visibility = (bool) value ? Visibility.Visible : Visibility.Collapsed;\n }\n else\n {\n      var valueToSave = textBlock.Visibility == Visibility.Visible ? true : false;\n      localSettings.Values.Add("textblockVisibility", valueToSave);\n }	0
13395500	13395321	change column name in datagridview	DateTime dt = DateTime.Now;\n\nstring s = dt.DayOfWeek.ToString();\nfor (int i = 0; i < 10; i++)\n{\n    dataGridView1.Columns.Add(string.Format("col{0}", i), s);\n}\n\nfor (int i = 0; i < dataGridView1.Columns.Count; i++)\n{\n\n   string str = dataGridView1.Columns[i].HeaderText;\n   if (str == "Wednesday")\n   {\n       dataGridView1.Columns[i].HeaderText = "fifth day of week";\n   }\n}	0
5257421	5257380	subtract columns in a table with LINQ	var query = from row in db.Rows\n            group row by row.UserId into tmp\n            select new {\n              UserId = tmp.Key,\n              Money = tmp.Sum(x => x.Type == '+' ? x.Money : -x.Money)\n            };	0
8847543	8847516	Displaying current datetime in MessageBox in C#	MessageBox.Show(current.ToString());	0
1279502	1278344	How do you get an iPhone's Device Name in C#	AMDeviceCopyValue(device, 0, "DeviceName");	0
12160544	12146200	NHibernate Group By Many-to-Many Association	// Option 1\nvar r = from message in Session.Query<Message>()\n        from userid in message.AssociatedUsers\n        group userid by userid into g\n        select new { UserID = g.Key, Count = g.Count() };\n\n// Option 2\nstring userId = null;\nvar r = Session.QueryOver<Message>()\n    .JoinQueryOver<string>(m => m.AssociatedUsers, () => userId)\n    .SelectList(list => list\n        .SelectGroup(() => userid)\n        .Select(Projections.Count()))\n    .List<object[]>();	0
6518013	6517894	What's wrong with my Xpath?	XDocument xdoc = XDocument.Load("XMLFile1.xml");\nforeach (XElement element in xdoc.XPathSelectElements("//file/ROWS/row/code"))\n{\n\n}	0
13466359	13466337	how to implement method that return object based on type passed	public class MyClass {\n    public IBase GetObject<T>() where T:IBase, new() // EDIT: Added new constraint \n    {\n        // should return the object based on type.\n        return new T();\n    }\n\n}	0
29514842	29504704	how to Add the standard Analyzer in sitecore 6.5 so that stop word is not ignored	foreach (var s in searchterm.Split(' '))\n{\n  if (!Lucene.Net.Analysis.Standard.StandardAnalyzer.STOP_WORDS_SET.Contains(s))\n  {\n     completeQuery.Add(new Term("title", s));\n  }\n}	0
3318381	3308299	Replace bookmark text in Word file using Open XML SDK	IDictionary<String, BookmarkStart> bookmarkMap = \n      new Dictionary<String, BookmarkStart>();\n\n  foreach (BookmarkStart bookmarkStart in file.MainDocumentPart.RootElement.Descendants<BookmarkStart>())\n  {\n      bookmarkMap[bookmarkStart.Name] = bookmarkStart;\n  }\n\n  foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)\n  {\n      Run bookmarkText = bookmarkStart.NextSibling<Run>();\n      if (bookmarkText != null)\n      {\n          bookmarkText.GetFirstChild<Text>().Text = "blah";\n      }\n  }	0
27051665	27051652	How to set different global variable values for release and debug mode C#	#if DEBUG\n   public const string RootUrl = "http://url/";\n#else\n   public const string RootUrl = "http://another/";\n#endif	0
2965810	2965554	How to check if a child-object is populated	Debug.WriteLine(member1.Settings.HasLoadedOrAssignedValues ? member2.Settings.Count : -1);	0
19094763	19094707	Get a list of all underlying ids from an Enum C#	Enum.GetValues(typeof(Handlers)).Cast<int>().ToList();	0
17498679	17498359	output model from xml to view MVC4	public ActionResult ListMovies()\n{\n  MovieSummary summary = Deserialize();\n  return View(summary);\n}	0
27030050	27029923	What is regular expression pattern for barcode result specific format in c#	^ASD-[A-Z]{3}-\d+	0
15818716	15818622	How to map an enum property in Entity Framework 4	[Column("User_Status")]\npublic int UserStatusAsInt { get; set; }\n\n[NotMapped]\npublic UserStatus UserStatus\n{\n  get { return (UserStatus) this.UserStatusAsInt; }\n  set { this.UserStatusAsInt = (int)value; }\n}	0
22154959	22154931	AccesDB value to textbox	"SELECT FirstName FROM Member WHERE MemberID = " + index	0
9376311	9376188	How to generate a non-growing (int) random array c#?	// while the array is sorted\n        var sortedCopy = array1.ToList();\n        sortedCopy.Sort();\n        while (array1.SequenceEqual(sortedCopy))\n        {\n            Array.Sort(array1, new Comparison<int>((left, right) => random.Next(-1, 1)));\n        }	0
3070212	3068966	Parsing mail subject with inline specified encoding	var popClient = new POPClient();\npopClient.Connect("pop.test.lt", 110, false);\npopClient.Authenticate("test@test.lt", "test");\n\n// Get OpenPop.Net message\nvar messageInfo = popClient.GetMessage(1, false);\n\n// Covert raw message string into stream and create instance of SharpMessage from SharpMimeTools library\nvar messageBytes = Encoding.ASCII.GetBytes(rawMessage);\nvar messageStream = new MemoryStream(messageBytes);\nvar message = new SharpMessage(messageStream);\n\n// Get decoded message and subject\nvar messageText = message.Body;\nvar messageSubject = message.Subject;	0
3893011	3892734	Split C# collection into equal parts, maintaining sort	/// <summary>\n/// Partition a list of elements into a smaller group of elements\n/// </summary>\n/// <typeparam name="T"></typeparam>\n/// <param name="list"></param>\n/// <param name="totalPartitions"></param>\n/// <returns></returns>\npublic static List<T>[] Partition<T>(List<T> list, int totalPartitions)\n{\n    if (list == null)\n        throw new ArgumentNullException("list");\n\n    if (totalPartitions < 1)\n        throw new ArgumentOutOfRangeException("totalPartitions");\n\n    List<T>[] partitions = new List<T>[totalPartitions];\n\n    int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);\n    int k = 0;\n\n    for (int i = 0; i < partitions.Length; i++)\n    {\n        partitions[i] = new List<T>();\n        for (int j = k; j < k + maxSize; j++)\n        {\n            if (j >= list.Count)\n                break;\n            partitions[i].Add(list[j]);\n        }\n        k += maxSize;\n    }\n\n    return partitions;\n}	0
25876975	25876812	Find Node By Unique value in First Child Node Sibling Structure	public TreeNode NodeByIndex(TreeNode root, int NodeIndex)\n{\n  if (root.NodeIndex == NodeIndex)\n    return root;\n\n  if (root.FirstChild != nil)\n  {\n    TreeNode c = NodeByIndex(root.FirstChild, NodeIndex);\n    if (c != nil)\n      return c;\n  }\n\n  if (root.NextSibling != nil)\n  {\n    TreeNode c = NodeByIndex(root.NextSibling, NodeIndex);\n    if (c != nil)\n      return c;\n  }\n\n  return null;\n}	0
7470307	7470258	How to get the SqlType of a column in a DataTable?	System.Data.DataTable	0
8722778	8721417	object[] as a datagridview datasource	var datasource = from p in (object[])\n                             select new\n                             {\n                                 Column1 = p.GetType().GetProperty("property1").GetValue(p, null),\n                                 Column2 = p.GetType().GetProperty("property2").GetValue(p, null),\n                                 Column3 = p.GetType().GetProperty("property3").GetValue(p, null),\n                                 Column4 = p.GetType().GetProperty("property4").GetValue(p, null),\n                             };\n\n\n            dataGridView1.DataSource = datasource;\n\n            dataGridView1.Columns[0].DataPropertyName = "Column1";\n\n            dataGridView1.Columns[1].DataPropertyName = "Column2";\n\n            dataGridView1.Columns[2].DataPropertyName = "Column3";\n\n            dataGridView1.Columns[3].DataPropertyName = "Column4";	0
22015765	22015711	Making a checkbox to have check after a condition	checkbox.Checked = condition;	0
2834287	2834233	How to foreach through a 2 dimensional array?	string[][] table = new string[][] { new string[] { "aa", "aaa" }, new string[]{ "bb", "bbb" } };	0
6777749	5772189	How better to map configuration elements to application objects?	interface IConfigurationConverter<TElement, TObject>\n{\n    TObject Convert(TElement element);\n}\n\nclass FooConfigurationConverter : IConfigurationConverter<FooElement, Foo>\n{\n    public Foo Convert(FooElement element)\n    {\n        return new Foo { Value = element.Value };\n    }\n}\n\nFooConfigurationConverter converter = IoC.Resolve<IConfigurationConverter<FooElement, Foo>>();\nFoo foo = converter.Convert(element);	0
33679684	33679428	In C#, how can a closure reference itself?	var someVar = new FooBar();\nEventHandler closure = null;\nclosure = (s, e) => {\n    doSomething(someVar);\n    // Unsubscribe from further events\n    // textBox1.TextChanged -= myself?\n    // If I don't unsubscribe, I'm needlessly keeping reference\n    // to someVar, and I don't intend to keep triggering this code\n    // upon further events.\n    textBox1.TextChanged -= closure;\n};\ntextBox1.TextChanged += closure;	0
12120031	12119957	how to get button find control value in nested grid using c#	foreach (GridViewRow row in grdSubClaimOuter.Rows) \n{\nif (row.RowType == DataControlRowType.DataRow) \n{\n    GridView gvChild = (GridView) row.FindControl("grdSubClaim");\n    // Then do the same method for Button control column \n    if (gvChild != null)\n    {\n        foreach (GridViewRow row in gvChild .Rows) \n        {\n            if (row.RowType == DataControlRowType.DataRow) \n            {\n                Button btn = (Button ) row.FindControl("buttonID");\n                if (btn != null )\n                {\n                    // do your work\n                }\n            }\n        }\n    }\n}\n}	0
6722547	6722533	How can I check for a stream before initializing one in a loop in C#	StreamWriter genStream;\n\nforeach (var m in moviesWithGenre)\n{\n    // Creates new HTML file if new Genre is detected\n    if (m.Genre != tmpGen)\n    {\n        tmpGen = m.Genre;\n\n        // initiates streamwriter for catalog output file\n        FileStream fs = new FileStream(cPath + Path.DirectorySeparatorChar + m.Genre, FileMode.Create);\n        // Set genStream to the FileStream\n        genStream = new StreamWriter(fs);	0
8692990	8692975	How to cast the result of sql command to the int variable?	using (SqlConnection conn=new SqlConnection(sql_string)) {\n\n    conn.Open();\n\n    SqlCommand command=new SqlCommand(\n        sql_query,\n        conn\n    );\n\n    Int32 quizid=((Int32?)command.ExecuteScalar()) ?? 0;\n\n}	0
17398505	17398438	Avoid numerous casts in inheritance tree	public interface A<T> where T: A<T> {\n    List<T> Children {get;}\n}	0
29385376	29369726	How to get all images from a url to picturebox in c#?	private void Form1_Load(object sender, EventArgs e)\n    {\n        int x = 10, y = 10;\n        string[] file = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures\",             "*.jpg");\n        PictureBox[] pb = new PictureBox[file.Length];\n        for (int i = 0; i < file.Length; i++)\n        {\n            pb[i] = new PictureBox();\n            pb[i].Size = new System.Drawing.Size(100,100);\n            pb[i].ImageLocation = file[i];\n            pb[i].Location = new Point(x, y);\n            this.Controls.Add(pb[i]);\n            x += 100;\n            if (i == 5)\n            {\n                 x = 10;\n                 y += 120;\n            }\n        }\n    }	0
3509987	3509959	C# Action and Func parameter overloads	public void Execute(Action<T> action, T param) {\n     Execute( (a, _) => action(a) , param, null);\n}\n\npublic void Execute(Action<T1, T2> action, T1 param1, T2 param2) {\n    Execute( (a, b, _) => action(a, b) , param1, param2,  null);\n}\n\npublic void Execute(Action<T1, T2, T3> action, T1 param1, T2 param2, T3 param3) {\n    DoStuff();\n    action(param1, param2, param3)\n    DoMoreStuff();\n}	0
17400478	17400353	WCF - How can I get a reference to the incoming message string in my service implementation?	OperationContext.Current.IncomingMessageProperties["RawMessage"]	0
6796968	6766309	Any libraries that can parse ID3 chunks from aiff files?	TagLib.File file = TagLib.File.Create(@"C:\Sample.aif");\nstring album = file.Tag.Album;\nstring title = file.Tag.Title;	0
16563138	16562878	print console characters faster	var stringBuilder = new StringBuilder();\n        bitCounter = 0;\n        foreach (bool bit in bitData)\n        {                \n            if (bit)\n                stringBuilder.Append("???");\n            else\n                stringBuilder.Append(" ");\n            bitCounter++;\n            if (bitCounter > 7)\n            {\n                bitCounter = 0;\n                Console.WriteLine(stringBuilder.ToString());\n                stringBuilder.Clear();\n            }\n        }	0
7865412	7865375	Start a new line in wpf textbox	TextWrapping="Wrap"\nVerticalScrollBarVisibility="Visible" (or auto)\nAcceptsReturn="True"	0
16674140	16673870	create a regular expression of a specific sentence	var exp = new Regex(@"angle\(Vector\((.*?),(.*?)\),Vector\((.*?),(.*?)\),(.*?),(.*?)\)");\n\nvar match = exp.Match("angle(Vector(JointA,jointB),Vector(JointA,jointB),minValue,maxValue)");\n\n\nvar jointA1 = match.Groups[0];\nvar jointB1 = match.Groups[1];\nvar jointA2 = match.Groups[2];\nvar jointB2 = match.Groups[3];\nvar max     = match.Groups[4];\nvar min     = match.Groups[5];	0
26230496	26211535	Create table using OpenXML in powerpoint	List<OpenXmlElement> elements = new List<OpenXmlElement>();\n        elements.Add(new P.NonVisualGraphicFrameProperties\n            (new P.NonVisualDrawingProperties() { Id = 1, Name = "xyz" }, new P.NonVisualGraphicFrameDrawingProperties(),new ApplicationNonVisualDrawingProperties()));\n\n\n\n        P.GraphicFrame graphicFrame = tableSlidePart.Slide.CommonSlideData.ShapeTree.AppendChild(new P.GraphicFrame(elements));	0
13869881	13869824	How to change the image to the size of the picture box?	OpenFileDialog fd = new OpenFileDialog();\n        DialogResult r = fd.ShowDialog();\n        if (r == System.Windows.Forms.DialogResult.OK)\n        {\n            pictureBoxMap1.Image = Bitmap.FromFile(fd.FileName);\n            pictureBoxMap1.SizeMode = PictureBoxSizeMode.StretchImage;\n            pictureBoxMap1.Refresh();\n       }	0
30985828	30985577	Add image to the radio button	myRadioButton.Content = new Image()\n{\nSource = (new ImageSourceConverter()).ConvertFrom(\n                         "Images/pic.png") as\n                             ImageSource\n};	0
1644091	1637779	C# Bind value of datagridview column to DataTable	DataTable myTable = getYourDataByMagic();\n\nDataGridViewComboBoxColumn box = new DataGridViewComboBoxColumn();\nBindingSource bs = new BindingSource();\nbs.add("choice one");\nbs.add("choice two");\n\nbox.HeaderText = "My Choice";\nbox.Name = "select";\nbox.DataSource = bs;\nbox.DataPropertyName = "select";\n\nmyTable.Columns.Add(new DataColumn("select"));\nthis.dataGridView1.Columns.Add(box);\nthis.dataGridView1.DataSource = myTable;	0
9378442	9378300	Read entire elements from an XML network stream	var settings = new XmlReaderSettings\n{\n    ConformanceLevel = ConformanceLevel.Fragment\n};\n\nusing (var reader = XmlReader.Create(stream, settings))\n{\n    while (!reader.EOF)\n    {\n        reader.MoveToContent();\n\n        var doc = XDocument.Load(reader.ReadSubtree());\n\n        Console.WriteLine("X={0}, Y={1}",\n            (int)doc.Root.Element("x"),\n            (int)doc.Root.Element("y"));\n\n        reader.ReadEndElement();\n    }\n}	0
23454320	23454197	C# Button update(refresh) xml Value	public TemperaturePresenter()\n  {\n     _view = new MainView(this);\n     serverDoc = new XmlDocument();\n     responseDoc = new XmlDocument();\n     LoadTemperatures();\n  }\n  public void LoadTemperatures()\n  {\n        ThreadPool.QueueUserWorkItem(\n        delegate\n        {\n            .. a lot of things to check here ...\n        }\n  }\n\n  ,,,,,\n\n\n  public void btnUpdate_Click(object sender, EventArgs e)\n  {            \n     _parent.LoadTemperatures();\n  }	0
26063435	26062488	Pass string value created in one function as parameter to function	public bool CheckForDuplicates(string value)\n{\n  string[] split = value.Split('|');\n  return split.Length != split.Distinct().ToArray().Length;\n}	0
11917766	11917749	Copy items from CheckedListBox to ListBox	foreach(var Item in checkedlistbox.CheckedItems)\n    Listbox.Items.Add(Item);	0
32149106	32148962	Processes in Sequence design pattern	void Method(SomeType obj)\n{\n    MethodA(obj);\n    MethodB(obj);\n    MethodC(obj);\n}\n\nvoid MethodA(SomeType obj)\n{\n}\n\nvoid MethodB(SomeType obj)\n{\n}\n\nvoid MethodC(SomeType obj)\n{\n}	0
6305797	6305453	Dictonary without unique keys	int emptyKey = 0;\n\n...\nif (!String.IsNullOrEmpty(navChildren.Value))\n{\n   string key = "Empty_" + emptyKey.ToString();\n   emptyKey ++;\n   itemTable.Add(key, navChildren.Value);\n   //Add blank keys\n}	0
28863963	28862192	Two images overlapping case in windows phone	someImage.SetValue(Canvas.ZIndexProperty, 1); \nsomeOtherImage.SetValue(Canvas.ZIndexProperty, 2);	0
22012354	22011431	Unity ioc - how to pass parameters to the constructor of the dependent object	unity.Resolve<DataConnector>(new ParameterOverride("SomePropertyName", someValue), new   ParameterOverride("SomeOtherProperty", someOtherValue)	0
5628596	5628524	Returning Concatenated String with LINQ for Dropdown	public partial class City\n{\n    public string CityNameAndState\n    {\n        get\n        {\n            return CityName + delimiter + State;\n        }\n    }\n}	0
7983397	2714645	Decimal - truncate trailing zeros	public static decimal Normalize(decimal value)\n{\n    return value/1.000000000000000000000000000000000m;\n}	0
15622629	15622451	Calling C++ method from C# to calculate CRC	ushort[] crc_table = {\n    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,\n    0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef\n};\n\nushort CalculateCrc( byte[] data )\n{\n    int i;\n    ushort crc = 0;\n    int len = data.Length;\n\n    for (int j = 0; j < len; j++)\n    {\n        i = ( crc >> 12 ) ^ ( data[j] >> 4 );\n        crc = (ushort) (crc_table[ i & 0x0F ] ^ ( crc << 4 ));\n        i = ( crc >> 12 ) ^ ( data[j] >> 0 );\n        crc = (ushort) (crc_table[ i & 0x0F ] ^ ( crc << 4 ));\n    }\n\n    return crc;\n}	0
5591364	5591329	c# how to add byte to byte array	byte[] newArray = new byte[theArray.Length + 1];\ntheArray.CopyTo(newArray, 1);\nnewArray[0] = theNewByte;\ntheArray = newArray;	0
11614945	11614865	Update progress bar from for loop	double progress = (x / max) * 100;	0
7447741	7447321	Passing numeric parameters to stored procedure in appropriate and easy way	cmd.Parameters.Add(new SqlParameter(/*overload that accepts dbType and value*/));	0
3992778	3992752	Best way to control page titles on a large website in ASP.NET	Page.Header.Title	0
24219285	24219084	Convert date in Domain class that is created by EF6	public DateTime Date { get; set; }\n\n\n[System.ComponentModel.DataAnnotations.Schema.NotMapped]\npublic DateTime PersianDate\n    {\n        get\n        {\n                var value  = ConvertToHijri(Date);\n\n                return (value);\n        }\n    }	0
13458400	13449413	How to acess DataGridCell on Right click on WPF DataGrid	private void DataGrid_MouseRightButtonUp_1(object sender, System.Windows.Input.MouseButtonEventArgs e)\n{\n    var hit = VisualTreeHelper.HitTest((Visual)sender, e.GetPosition((IInputElement)sender));\n    DependencyObject cell = VisualTreeHelper.GetParent(hit.VisualHit);\n    while (cell != null && !(cell is System.Windows.Controls.DataGridCell)) cell = VisualTreeHelper.GetParent(cell);\n    System.Windows.Controls.DataGridCell targetCell = cell as System.Windows.Controls.DataGridCell;\n\n    // At this point targetCell should be the cell that was clicked or null if something went wrong.\n}	0
2774093	2773817	C# Object Array CopyTo links both arrays' values?	try this:-\n\npublic static MyType[] DeepClone(MyType[] obj)\n     {\n                using (MemoryStream ms = new MemoryStream())\n                {\n                    BinaryFormatter formatter = new BinaryFormatter();\n                    formatter.Serialize(ms, obj);\n                    ms.Position = 0;\n\n                    return (MyType[])formatter.Deserialize(ms);\n                }\n      }	0
3859151	3859082	How to copy to unit test out-folder?	[DeploymentItem(@"C:\vsprojects\MyProject\Tests\testdata\XmlContentFileOne.xml")]  \n[TestMethod]  \npublic void MyTest()  \n{  \n  //test \n}	0
22831606	22826145	How to specify port number in a service stack service?	public static void Main()\n{\n    // Very simple self hosted console host\n    var appHost = new AppHost();\n    appHost.Init();\n    appHost.Start("http://*:8080/"); // Update the port number here, change 8080\n    Console.ReadKey();\n}	0
28070070	28069888	How to run sql scripts sequentially	BEGIN TRY\n{ sql_statement |\n  statement_block }\nEND TRY\nBEGIN CATCH\n{ sql_statement |\n  statement_block }\nEND CATCH	0
19943161	18626646	How to set transparent to see through surface underneath in Microsoft.DirectX at top view?	device.RenderState.ZBufferWriteEnable = false;	0
3014967	3014901	Compare day and show hour only using DateTime formats	DateTime.Now.Subtract(dt).Days == 0 ? "Today" : "Yesterday"	0
3788246	3788194	C# Xml Parsing from StringBuilder	StringBuilder sb = new StringBuilder (xml);\n\nTextReader textReader = new StringReader (sb.ToString ());\nXDocument xmlDocument = XDocument.Load (textReader);\n\nvar nodeValueList = from node in xmlDocument.Descendants ("node")\n                    select node.Value;	0
12331637	12331500	How do I read a .proto formatted binary file in C++?	TextureAtlasSettings::TextureAtlasEntry taSettings;\n\n\nifstream file("Content\\Protobuf\\TextureAtlas0.bin", ios::in | ios::binary);\n\nif (file.is_open())\n{\n    if (!taSettings.ParseFromIstream(&file)) \n    {\n        printf("Failed to parse TextureAtlasEntry");\n    }\n}	0
31161709	30872850	EF Update Many-to-Many in Detached Scenario	var obj = GetObjectFromDB(...); \nAutoMapObj(obj, modifiedObj); \nSaveInDb();	0
13731165	13731107	Linq any - How to select	context.Favorite\n  .Where(f => f.UserId == UserId)\n  .Join(context.Objects, t => t.ObjectId, u => u.Id, (t, u) => t);	0
25665006	25663540	Exchange 2013 get uniqueId of WellKnownFolderName	var folder = Folder.Bind(ewsInstance, WellKnownFolderName.DeletedItems);\nif (Equals(event.ParentFolderId.UniqueId, folder.Id.UniqueId))//...	0
31351147	31320991	i want to fetch all text from a text file and convert in to a xml file	string fileContents = File.ReadAllText("input.txt"); //your example source text is in this file\nstring pattern = @"(.*)?\{([^}]+)\}";\n\nMatchCollection matches = Regex.Matches(fileContents, pattern, RegexOptions.Multiline);\n\nStringBuilder sb = new StringBuilder();\nsb.AppendLine("<?xml version='1.0' encoding='UTF-8'?>");\nsb.AppendLine("<contents>");\n\nforeach (Match match in matches)\n{\n    string nodeName = match.Groups[1].Value;\n    string nodeValue = match.Groups[2].Value;\n\n    sb.AppendFormat("<{0}>{1}</{0}>", nodeName.ToLower(), nodeValue);\n    sb.AppendLine();\n}\nsb.AppendLine("</contents>");\n\nFile.WriteAllText("output.xml", sb.ToString());	0
14042987	14041369	Databind comobox in data-template with enum	var colors = typeof(Colors).GetTypeInfo().DeclaredProperties;\nforeach (var item in colors)\n{\n   cbBorderColor.Items.Add(item);\n}	0
18135843	18135754	need help for using selected item from listview as a variable on sql query	private void listView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if(listView1.SelectedItems.Count > 0)\n    {\n        SqlConnection cnn = new SqlConnection(tools.ConnectionString);\n        SqlCommand cmd = new SqlCommand("select EmployeeId,BirthDate from Employees where FirstName = @name  ",cnn);\n        cmd.Parameters.AddWithValue("@name", listView1.SelectedItems[0].Text );\n        cnn.Open();\n        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);\n        while (dr.Read())\n        {\n            MessageBox.Show("Id= "+dr["EmployeeID"].ToString() + "\nBirth Date= "+dr["BirthDate"].ToString());\n        }\n        cnn.Close();\n    }\n\n}	0
22829011	22828855	Loop Through Specific Column Values in data table	radioButton3.Text = dt.Rows[0]["SubName"] \nradioButton4.Text = dt.Rows[1]["SubName"] \nradioButton5.Text = dt.Rows[2]["SubName"]	0
19792502	19753820	How do I make a set of blocks look seamless when I know the size of the texture and the position and dimensions of the blocks?	Mesh mesh = GetComponent<MeshFilter>().mesh;\nVector3[] vertices = mesh.vertices;\nVector2[] uvs = new Vector2[vertices.Length];\n\nfor (int i = 0; i < uvs.Length; i++)\n{\n    // Find world position of each point\n    Vector3 vertexPos = transform.TransformPoint(vertices[i]);\n    // And assign its x,y coordinates to u,v.\n    uvs[i] = new Vector2(vertexPos.x, vertexPos.y);\n}\nmesh.uv = uvs;	0
19992407	19992057	How to evaluate a lambda expression to determine object type	void Main()\n{\n    Expression<Func<object>> f = () => new Potato();\n    Helper.MyProduce(f);\n}\n\n\npublic class Tomato \n{}\npublic class Potato\n{}\n\npublic static class Helper\n{\n    public static void MyProduce(Expression<Func<object>> expression)\n    {\n        var func = expression.Compile();\n        var result = func();\n\n        if(result is Tomato)\n            Console.Write("Tomato");\n        else if (result is Potato)\n            Console.Write("Potato");\n        else\n            Console.Write("Unknown");\n    }\n}	0
28336526	28336320	C# Get string between two characters in a string	Regex regex = new Regex(@"([""'])(?:(?=(\\?))\2.)*?\1");\nforeach (var match in regex.Matches("{{\"textA\",\"textB\",\"textC\"}}"))\n{\n    Console.WriteLine(match);\n}	0
6227111	6225918	Change the Background of MS Excel 2003	Sub backcolor()\nRange("a1:a10").Interior.ColorIndex = xlNone\nFor Each cell In Range("a1:a10")\n    If cell.Value = "Sunday" Or cell.Value = "Saturday" Then\n        cell.Interior.ColorIndex = 3\n    End If\nNext cell\nEnd Sub	0
33110987	33110898	Group by generates a huge query	var visits = _db.Visits.AsNoTracking()\n             .Select(c=> new   // reduce the initial data set\n             { \n                 City= c.City, \n                 Code = c.Code, \n                 Name = c.Name \n             })\n             .GroupBy(x => x.City)\n             .Select(group => new    // build results\n             {\n                 City = group.Key.Code, \n                 CityName = group.Key.Name, \n                 Count = group.Count()\n             })\n             .OrderByDescending(x => x.Count);	0
1368573	1368383	Accessing a control from inside a class	if (eventType != null && eventType.SelectedItem.Text == "Big Party")\n{\n    DoSomeWork(); //should be changing values or visible options on the page    \n}	0
18844017	18843918	How to get all matches using regex	(?=([A-Z]{2}))	0
28772359	28771053	Best way to store and access List of Objects in Controller	MemoryCache cache = MemoryCache.Default;\nstring baseCacheKey = "Users";\n\npublic void DoSomethingWithUsers(int userId)\n{\n    var cacheKey = baseCacheKey + userId.ToString();\n    if (!cache.Contains(cacheKey))\n    {\n        RefreshUserCache(userId);\n    }\n    var users = cache.Get(cacheKey) as List<User>\n\n    // You can do something with the users here\n}\n\npublic static RefreshUserCache(int userId)\n{\n    var users = ws.SelectUsers();\n\n    var cacheItemPolicy = new CacheItemPolicy();\n    cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1);\n    var cacheKey = baseCacheKey + userId.ToString();\n    cache.Add(cacheKey, users , cacheItemPolicy);\n}	0
14514846	14514771	I am having trouble with Bresenham's algorithm	0-45 x,y\n  45-90 y,x\n 90-135 -y,x\n135-180 -x,y\n180-225 -x,-y\n225-270 -y,-x\n270-315 y,-x\n315-360 x,-y	0
11110814	11110559	How to validate a model utilizing DataAnnotations attributes without it being mapped to EF context?	var validationContext = new ValidationContext(model);\nvar validationResult = new List<ValidationResult>();\nValidator.TryValidateObject(model, validationContext , validationResult);	0
23192588	23192110	Can not Print in WPF	var printDoc = new PrintDocument()\n    var dlg = new PrintDialog()\n\n    If(dlg.ShowDialog() == DialogResult.OK)\n    {\n           printDoc.Document = [doc to print]\n           printDoc.Setting = dlg.settings\n           PrintDoc.print()\n    }	0
20804811	20804742	how to find listview by name in winform	var tmp = Controls.Find("ListView1", true);	0
28879444	28879243	find attribute value using element value	//ChangeSet[.//id[text()='CS-2215']]	0
16501318	16501285	Adding an Item to the top of a LongListSelector	App.ViewModel.Items.Insert(0, new ItemViewModel() { ThingOne = "Blah", ThingTwo = "BlahBlahBlah"});	0
27844583	27844167	How to pass Array values to asp.net c# web services	Person per = new Person(); // your MVC4 App local model.\nper.Name = "Vibin";\nper.Phone = 123456789;\nFirstService.WebService service = new FirstService.WebService();\nmvcEmpty.FirstService.Person p = new mvcEmpty.FirstService.Person(); // Web service person generated during proxy generation when you add web reference.\np.Name = per.Name;\np.phone = per.Phone;\nservice.TakeList(p);	0
10193021	10192878	how to get the number of repetitions from List<int>	var query1 = from a in ListIdProducts \n                         group a by new { a } into g\n                         select new\n                         {\n                             item = g.Key,\n                             itemcount = g.Count()\n                         };	0
24405313	24404985	Cron expression with excluding of a specific day of week	0 0 12 ? * TUE,WED,THU,FRI,SAT,SUN *	0
30656251	30085926	How do you Add or Update a JProperty Value in a JObject	var item = JObject.Parse("{ 'str1': 'test1' }");\n\nitem["str1"] = "test2";\nitem["str3"] = "test3";	0
33804022	33802067	iisreset over a list of servers programmatically	static void Main(string[] args)\n    {            \n        string[] servers = LoadServersFromFile(); \n\n        foreach (string server in servers)\n        {\n            Process.Start("iisreset", server.Trim());\n        }            \n    }\n\n    private static string[] LoadServersFromFile()\n    {\n        //just listed all servers comma separated in a text file, change this to any other approach fits for your case\n        TextReader reader = new StreamReader("Servers.txt");\n        return reader.ReadToEnd().Split(',');\n    }	0
11986884	11986813	Check a webpage every hour in C#	using System;\nusing System.Net;\nusing System.Timers;\n\nclass Program\n{\n    static void Main()\n    {\n        Timer t = new Timer(TimeSpan.FromHours(1).TotalMilliseconds);\n        t.Elapsed += (sender, e) =>\n        {\n            // This code will execute every hour\n            using (var client = new WebClient())\n            {\n                // Send an HTTP request to download the contents of the web page\n                string result = client.DownloadString("http://www.google.com");\n\n                // do something with the results\n                ...\n            }\n        };\n        Console.WriteLine("press any key to stop");\n        Console.ReadKey();\n    }\n}	0
9581254	9581113	Inserting data into one table then multiple rows into another using data from the first using stored procedures (SQL + C#)	using (SqlConnection  connection= new SqlConnection(connectionstring))\n   {\n     connection.Open();\n     SqlTransaction transaction = connection.BeginTransaction();\n     try\n     {\n        SqlCommand command = new SqlCommand("proc1",connection);\n        //execute the above command\n        command.CommandText="proc2";\n        //execute command again for proc2\n        transaction.Commit();                   \n     }\n     catch\n     {\n       //Roll back the transaction.\n       transaction.Rollback();\n     }  \n   }	0
9637649	9616001	Override XML Serialization Method	public class gdEvent\n    {\n    [XmlAttribute(AttributeName = "startTime")]\n    private string m_startTimeOutput;\n    private DateTime m_startTime; //format 2011-11-02T09:00:00Z\n\n    [XmlAttribute(AttributeName = "endTime")]\n    private string m_endTimeOutput;\n    private DateTime m_endTime; //2011-11-02T10:00:00Z\n\n    public DateTime startTime\n    {\n        get\n        {\n        return m_startTime;\n        }\n        set\n        {\n        m_startTime = value;\n        m_startTimeOutput = m_startTime.ToString("yyyy-MM-ddTHH:mm:ssZ");\n        }\n    }\n\n    public DateTime endTime\n    {\n        get\n        {\n        return m_endTime;\n        }\n        set\n        {\n        m_endTime = value;\n        m_endTimeOutput = m_endTime.ToString("yyyy-MM-ddTHH:mm:ssZ");\n        }\n    }	0
7266855	7266728	How to map a windows service program's file	// dir is path where your service EXE is running\nstring dir = Path.GetDirectoryName(\n    Assembly.GetExecutingAssembly().Location);    \n// mail_file_path is where you need to search\nstring mail_file_path = Path.Combine(dir , @"\template\mailbody.html");	0
6764761	6764716	File's modification date in C#	System.IO.FileInfo file1 = new System.IO.FileInfo(file1Name);\nSystem.IO.FileInfo file2 = new System.IO.FileInfo(file2Name);\nif(file1.LastWriteTime != file2.LastWriteTime)\n    //Do some stuff.	0
24865038	24864939	How to check Treeview collapse/expand icon clicked?	private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)\n{\n    var Test = treeView1.HitTest(e.Location);\n    if (Test.Location == TreeViewHitTestLocations.PlusMinus)\n    { \n       //You can check here\n    }\n}	0
9379747	9353151	Access Ribbon Elements Programatically in XML Ribbon	IRibbonUI.Invalidate()	0
16165033	16164939	How to get list of USB in winform using c#?	foreach (DriveInfo drive in DriveInfo.GetDrives())\n {\n     if (drive.DriveType == DriveType.Removable)\n     {\n        if (drive.IsReady)\n                 cmbUSB.Items.Add(drive.Name + "-" + drive.VolumeLabel);\n                                                     //^^^^^^^^^^^^^^^^\n                                                     //here   \n     }\n }	0
8699240	8699208	Finding the control at run time when the name of the control is know in string	var myControl = (Control)this.FindName("Control Name");	0
2454568	2454549	how to get count of '#' in a string?	int RowFormat = "grtkj####mfr".Count(ch => ch == '#');	0
23424517	23424238	Xml elements other than 2 elements	var elementNamesToKeep = new[] { "Field1", "Field2" };\nforeach (var symbol in xelem.Elements())\n{\n   var stripped = new XElement(\n      symbol.Name,\n      symbol.Elements().Where(e => elementNamesToKeep.Contains(e.Name.ToString())));\n}	0
809861	804273	LINQ Query Syntax to Lambda	string lambdaSyntax = query.Expression.ToString();	0
16394456	16333550	Error in application when run from any server except localhost	expected start tag	0
28658356	28631362	How to change backGround colr in Xamarin forms NavigationPage	new NavigationPage(new LoginPage()) { BarBackgroundColor = Color.Green };	0
27960554	27959889	Implement a WCF-Mock and the endpoint before implementing the real service	public class ServiceFacade : IMyWCFService\n{\n    private IMyWCFService _clientImplementation;\n\n    public ServiceFacade()\n    {\n        _clientImplementation = (Settings.Default.UseMockService == true) ? new MockWCFServiceClient() : new MyWcfServiceClient();\n\n    }\n\n    #region IMyWCFService implementation\n\n    public int MyServiceCall()\n    {\n       return _clientImplementation.MyServiceCall();\n    }\n\n    #endregion\n\n}	0
32538159	32538082	retrive the last match case or list with regular expression and than work with it	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(webData);\nforeach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@data-swhglnk]"))\n{\n    HtmlAttribute data = node.Attributes["data-swhglnk"];\n    //do your processing here\n}	0
9685	9673	Remove duplicates from array	int[] s = { 1, 2, 3, 3, 4};\nint[] q = s.Distinct().ToArray();	0
25164346	25163359	Azure ExecuteBatch - how to set prefer-no-content header in c#?	TableBatchOperation.Insert	0
4573178	4573077	Is there a way to convert a 3D array String[3,7,x] to csv?	string[] values = new string[3];\nfor (int i = 0; i < 3; i++) {\n  values[i] = myArr[3, 7, i];\n}\nstring csv = String.Join(", ", values);	0
32744514	32741260	Displaying Crystal Report With Display String Property Causes ArgumentOutOfRangeException	iif(CurrentFieldValue > 0, "*", "")	0
4726984	4726905	c# phone format extension method	string ThisFormat = null;\nif (CountryCode == 1) { ThisFormat = string.Format("{0:###-###-####}", long.Parse(ThePhone)); }\nreturn ThisFormat;	0
16413578	16413494	how to resize ratio in image	width = height * 2 //2:1\nwidth = height * 0.66 //2:3	0
7260707	7260550	Getting an Exception from an Enum	default: { throw new Exception("Invalid Distance Unit Specified: " + DefinedUnits.Distance != null ? DefinedUnits.Distance.ToString() : '**null**' ); }	0
12024597	12024470	Unhandled Exception Still Crashes Application After Being Caught	dispatcherUnhandledExceptionEventArgs.Handled = true;\n\ndispatcherUnhandledExceptionEventArgs.Handled = true;	0
21609216	21608793	Add delegate expression as a parameter	public string GetStringValueFromData(DataTable data, Func<DataRow, object> expression)\n{\n    switch (this.MethodType)\n    {\n        case (LabelMethodType.Count):\n            return data.AsEnumerable().Select(expression).Count().ToString();\n        case (LabelMethodType.Sum):\n            return data.AsEnumerable().Select(expression).Cast<int>().Sum().ToString();\n        case (LabelMethodType.Average):\n            return data.AsEnumerable().Select(expression).Cast<int>().Average().ToString();\n    }\n\n    return string.Empty;\n}	0
22041338	22040868	sum of datatable column containing forward slash	var tuple = dt.Rows.Cast<DataRow>()\n                   .Select(row => row["ColumnABC"].ToString().Split('/'))\n                   .Select(strs => new Tuple<int, int>(\n                         Int32.Parse(strs[0]),\n                         Int32.Parse(strs[1])))\n                   .Aggregate((curr, next) => new Tuple<int, int>(\n                        curr.Item1 + next.Item1,\n                        curr.Item2 + next.Item2));\n\nvar result = String.Format("{0}/{1}", tuple.Item1, tuple.Item2);	0
20749081	20749057	I'm having a issue getting a string	returnUser()	0
27528637	27528489	Adding a Save As Function to a form using a listbox store of data	using (SaveFileDialog dialog = new SaveFileDialog())\n{\n    dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;\n    dialog.FilterIndex = 2 ;\n    dialog.RestoreDirectory = true ;\n\n    if (dialog.ShowDialog() == DialogResult.OK)\n    {\n        // Can use dialog.FileName\n        string Path = dialog.FileName;\n       ....	0
15386455	15386245	How to reproduce a lost Session in asp.net/c#?	protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)\n{\n    if (HttpContext.Current.Session != null)\n    {\n        // Restore session if session is lost but cookie is not\n        // HttpContext.Current.Session["user_id"] == null &&\n        if (HttpContext.Current.Request.Cookies["hash"] != null)\n        {\n            // do your job here\n            RestoreSessionMethod();\n        }\n    }\n}	0
14655145	14655023	Split a string that has white spaces, unless they are enclosed within "quotes"?	string input = "one \"two two\" three \"four four\" five six";\nvar parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")\n                .Cast<Match>()\n                .Select(m => m.Value)\n                .ToList();	0
34459918	34459881	Name of Text Written in TextBoxes	TextBox senderTextBox= (TextBox)sender; \nstring mood = senderTextBox.Text;	0
5613936	5613900	How to select and list multiple items in a checkedlistbox C#	private void button1_Click(object sender, EventArgs e) {\n        listBox1.Items.Clear();\n        foreach (var item in checkedListBox1.CheckedItems) {\n            listBox1.Items.Add(item);\n        }\n    }	0
13069800	13069594	Creating mathematical function in runtime from string	Evaluate()	0
28777279	28561437	How to add multiple namespaces into IEdmModel in OData service	// Set the default namespace \nbuilder.Namespace = "Default";\nbuilder.EntitySet<Product>("Products");\n\nvar prodType = builder.EntityType<Product>();\n// Set the namespace for type product\nprodType.Namespace = "ProductNamespace";	0
14653361	14653332	How to avoid namespace and source file name confliction in C#?	using Apples = Apples.Apples;	0
13115441	13115208	Check if xml values are contained within a list	var results = doc.Descendants("M")\n????.Where(foo => ValidUsers.Any(s => foo.Value.Contains(s)));	0
6729089	6729062	Creating a button programmatically in Windows Phone 7 (WP7)	btn.Click +=	0
13339080	13339059	How to send email with delay?	application that will be sending mail even website is not accessed by some body for a significant time interval	0
26304862	26302591	Populate a ComboBox on MainForm via Logic.cs	public static class MyTaskComboBoxPopulater()\n{\n    public static void LoadTasksToCombobox(ComboBox comboBox)\n    {\n        try\n            {\n                StreamReader task = new StreamReader(dataFolder + TasksFile);\n                string tasks = task.ReadLine();\n\n                while (tasks != null)\n                {\n                    comboBox.Items.Add(tasks);\n                    tasks = task.ReadLine();\n                }    \n            }\n        catch\n        {\n        }\n    }\n}\n\npublic Form MainForm()\n{\n    public static void TaskPopulate()\n    {\n        MyTaskComboBoxPopulater.LoadTasksToCombobox(cbTask);\n    }\n}	0
14445502	14393226	Fluent NHibernate - Ignore Primary Key Convention for 1 mapping file	AutoMap.AssemblyOf<Role>().Override<Role>(map =>\n{\n    map.Id(x => x.Id, "RoleName")\n        .CustomType<int>()\n        .GeneratedBy.Identity()\n        .UnsavedValue("0");\n});	0
12970421	12962400	SQL not available after a failed insert with NHibernate	try {\n    session.Save(entity);  // has duplicate key\n} catch {}\n\nAssert(entity.Id, Key.Unsaved);\n\nsession.SaveOrUpdate(entity2); // will issue INSERT and throws again	0
4600629	3547950	EF Generic Repository get Id from new inserted generic entity	public override TR Create<T, TR>(T entity)\n    {\n        string entitySet = GetEntitySetName<T>();\n        _context.AddObject(entitySet, entity);\n        _context.SaveChanges();\n\n        //Returns primaryKey value\n        return (TR)context.CreateEntityKey(entitySet, entity).EntityKeyValues[0].Value;                       \n    }	0
3259855	3237851	screen coordinates with a horizontal scroll bar	Point p = new Point(x, y);\np.Offset(AutoScrollPosition);\nchild.Location = p;	0
18393787	18393746	I want to search a user inputed string in a database and display all possible results	if (Request.QueryString[TextBox1.Text] != null) {\n    ResultsQuery = Request.QueryString[TextBox1.Text].Split(' ');    \n}	0
6465484	6465329	How to Find All the Controls in a Form, During the Run Time	List<Control> list = new List<Control>();\n\n            GetAllControl(this, list);\n\n        private void GetAllControl(Control c , List<Control> list)\n        {\n            foreach (Control control in c.Controls)\n            {\n                list.Add(control);\n\n                if (control.Controls.Count > 0)\n                    GetAllControl(control , list);\n            }\n        }	0
7811446	7811254	How do you get the fact that a cell of a datagridview has been modified without the cell losing focus?	// This event handler manually raises the CellValueChanged event\n// by calling the CommitEdit method.\nvoid dataGridView1_CurrentCellDirtyStateChanged(object sender,\n    EventArgs e)\n{\n    if (dataGridView1.IsCurrentCellDirty)\n    {\n        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n    }\n}	0
10043441	10039531	Import from excel using c#	SaveLocation = Server.MapPath("~/Temp") + "\\" + path;	0
32383690	32383629	C# pause foreach loop until button pressed	private static List<Action> listOfMethods= new List<Action>();\nprivate static int stepCounter = 0;\n\nlistOfMethods.Add(() => method1());\nlistOfMethods.Add(() => method2());\nlistOfMethods.Add(() => method3());\n//====================================================================\nprivate void invokeActions()\n{\n       listOfMethods[stepCounter]();\n\n       stepCounter += 1;\n       if (stepCounter >= listOfMethods.Count) stepCounter = 0;\n}\n//====================================================================\nprivate void buttonTest_Click(object sender, EventArgs e)\n    {\n        invokeActions();\n    }	0
21035451	21032177	IL optimization attempt results in slower execution	private void Validate(int index, object value)\n{\n    /* snip */\n    if (((SqlParameter) value).ParameterName.Length == 0)\n    {\n        string str;\n        index = 1;\n        do\n        {\n            str = "Parameter" + index.ToString(CultureInfo.CurrentCulture);\n            index++;\n        }\n        while (-1 != this.IndexOf(str));\n        ((SqlParameter) value).ParameterName = str;\n    }\n}	0
14389148	14389038	Comparing data from two models in one controller	public class MyViewModel\n{\n    public Input Input { get; set; }\n    public Resort Resort { get; set; }\n}	0
6453389	6421548	Filtering and then selecting data from flexgrid	foreach (C1.Win.C1FlexGrid.Row item in _c1FlexGrid.Rows.Selected)\n{\n    if (!item.Visible)\n       item.Selected = false;\n}\nClipboard.SetDataObject(_c1FlexGrid.Clip);	0
17215499	17214364	Passing file from web service to client in ASP.NET	protected void downloadButton_Click(object sender, EventArgs e)\n    {\n        Response.Clear();\n        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyFile.exe"));\n        Response.Buffer = true;\n        Response.ContentType = "application/octet-stream";\n\n        using (var downloadStream = new WebClient().OpenRead("http://otherlocation.com/MyFile.exe")))\n        {\n            var uploadStream = Response.OutputStream;\n            var buffer = new byte[131072];\n            int chunk;\n\n            while ((chunk = downloadStream.Read(buffer, 0, buffer.Length)) > 0)\n            {\n                uploadStream.Write(buffer, 0, chunk);\n                Response.Flush();\n            }\n        }\n\n        Response.Flush();\n        Response.End();\n    }	0
8235199	8234971	Adding parameters to IDbCommand	var parameter = command.CreateParameter();\nparameter.ParameterName = "@SomeName";\nparameter.Value = 1;\n\ncommand.Parameters.Add(parameter);	0
5871947	5871646	Add a realtime progress update to a slow page in asp.net	(new Thread(\n    () => {\n        DoLongRunningWork();\n    }\n) { Name = "Long Running Work Thread"\n    ,\n    Priority = ThreadPriority.BelowNormal \n    }).Start();	0
12194721	12193495	Load a Flickr tree as html recursive in C#	function rec(Collection c, TreeNode n)\n{\n   TreeNode me = new TreeNode();\n   n.ChildNodes.Add(me);\n   for each collection v in c:\n       rec(v, me)\n   for each set s in c:\n       AddSet(s, me)\n}	0
28166985	28153637	MVC5 Routing with two parameters in an Area	context.MapRoute(\n            "News",\n            "News/Post/{id}/{name}",\n            new { action = "Index", controller = "Post" },\n            new { id = @"\d+" }\n        );	0
20738558	20736964	How to trim more spaces of data base data using linq to sql query?	a=> a.user.displayname.Replace(" ","").contains(searchtext);	0
31947805	31478745	Method Shadowing Using NSubstitute in NUnit	mockObj.When(x => mockObj.MyChildMethod(Arg.Any<string>(), Arg.Any<string>(), null)).Do(MyMethod)\n\nprivate void MyMethod(CallInfo callInfo)\n        {\n            mockObj.MyChildMethod((string)callInfo.Args()[0],(string)callInfo.Args()[1], "param3");\n        }	0
20095717	20095589	How to make Windows 8.1 app go to a visual state?	VisualStateManager.GoToState(yourcontrolinstance, "FullScreenLandscape", true);	0
31906315	31906030	C# Combine String from Json Webrequest before binding Windows Universal	for(int i = 0; i < myList.Count; i++)\n   myList[i].icon_url = "my_base_url" + myList[i].icon_url;	0
5737495	5737440	Object in sphere(bounding sphere), want it to restrict movement within sphere	class Sphere {\n    public Vector3 Pos;\n    public double Radius;\n}\n\nvoid Test() \n{\n    Sphere big = new Sphere() { Pos = new Vector3(0, 0, 0), Radius = 10.0 };\n    Sphere small = new Sphere() { Pos = new Vector3(8, 0, 0), Radius = 1.0 };\n    Vector3 move = new Vector3(0, 10, 0);\n\n    // new position without check, if within sphere ok\n    Vector3 newPos = small.Pos + move;\n    if (Vector3.Distance(newPos, big.Pos) < big.Radius - small.Radius)\n        return;\n\n    // diff in radius to contact with outer shell\n    double space = (big.Radius - small.Radius) - Vector3.Distance(small.Pos, big.Pos);\n\n    // movement past moment of hitting outer shell\n    double far = Vector3.Distance(newPos, big.Pos) - (big.Radius - small.Radius);\n\n    // scale movement by ratio to get movement to hit shell\n    move = move * (space / (space + far));\n    newPos = small.Pos + move;\n}	0
3630325	3630296	How do I display the system's default http proxy	string proxyServerAddress = proxyserver.AbsoluteUri;	0
1618543	1616003	Data binding for TextBox	this.textBox.DataBindings.Add("Text",\n                                this.Food,\n                                "Name",\n                                false,\n                                DataSourceUpdateMode.OnPropertyChanged);	0
24603978	24602507	NHibernate QueryOver with Restrictions	IList<Department> departments;\nvar parents = new List<int> {167};\n\n// advantage of this "original" QueryOver is, that it can accept\n// more parent IDs.. not only one "100" as in our example\n// so if we neet children of 100,101,102\n// we can get more from this syntax: new List<int> {100, 101,102...};\ndepartments = session\n    .QueryOver<Department>()\n    .Where(Restrictions.On<Department>( x=> x.Parent.Id)\n        .IsIn(parents))\n    .List();\n\n// this style is just a bit more straightforward \n// saving few chars of code, using 'WhereRestrictionOn'\ndepartments = session\n    .QueryOver<Department>()\n    .WhereRestrictionOn(x => x.Parent.Id).IsIn(parents)\n    .List();\n\n// in case we do have the only one parent ID to search for\n// we do not have to use the IS IN\ndepartments = session\n    .QueryOver<Department>()\n    .Where(x => x.Parent.Id == 100)\n    .List();	0
24091327	24091255	Add periods in a string	line=Regex.Replace(line,@"([\w])(\d{2})(\d{2})(\w)(\w)","$1.$2.$3.$4.$5");	0
5883402	5883294	How do check if another application window is open on my machine (i.e., iterate through all open windows)?	System.Diagnostics.Process.Start(@"C:\Dev");\nSystem.Threading.Thread.Sleep(10000);\nSystem.Diagnostics.Process.Start(@"C:\Dev");	0
9498188	9498084	How can I open a new Form from a Thread?	//This has to be done on the UI-Thread, before calling the async method\nvar dispatcher = Dispatcher.CurrentDispatcher;\n\n//Now, in your async callback, do something like this\nprivate void AsyncCallback(IAsyncResult result){\n    dispatcher.Invoke(new Action(() =>\n    {\n        //Create your form Here           \n    }\n}	0
12320805	12320759	Custom DateTime format for Oracle Database	CultureInfo provider = CultureInfo.InvariantCulture;\nString format = "dd/MM/yyyy hh:mm:ss";\nreturn DateTime.ParseExact(dateString, format, provider);	0
1297114	1297094	How to get an image file extension from the web when it has been stripped?	System.Net.HttpWebRequest	0
3712305	3712276	LINQ Query That Can Change But Can Group?	var result = from a in DB.Table;\n\nif (Something == 0) \n{\n result = result.Where(r => r.Value > 0);\n}\n\nvar finalResult = \nfrom a in result\ngroup a by a.Value into b\nselect new {Group = b};	0
854669	854591	How to check for nulls in a deep lambda expression?	var result = GetValue(one, x => x.Two == null ? null :\n                                x.Two.Three == null ? null :\n                                x.Two.Three.Four == null ? null :\n                                x.Two.Three.Four.Foo;	0
22667492	22666970	Prevent 2 consecutive commas in a MaskedTextBox	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    // you might also want to check if the textBox1 is empty or whatever else. \n    if (e.KeyChar == ',' && textBox1.Text.EndsWith(",")) \n    {\n        e.Handled = true;\n    }\n}	0
19736839	19736812	Looping through xml elements starting with a certain element	foreach (XmlNode node in document.SelectNodes("Available/Item").SkipWhile(n => n.Value != 121))\n{\n    //code\n}	0
9108171	9107916	Sorting rows in a data table	DataView dv = ft.DefaultView;\n   dv.Sort = "occr desc";\n   DataTable sortedDT = dv.ToTable();	0
5336679	5336621	How to easily detect click inside of rectangle/image?	if (r.Contains(p))	0
8018268	8018189	parsing a xml file with c#	XDocument xdoc= XDocument.Load(@"A:\Users\Tono\Desktop\SaveContentFromCache\SaveContentFromCache\FileSignatures.xml");\n\nList<FileSignature> fileSignatures = (from file in xdoc.Element("Files").Elements("File")\n         select new FileSignature\n         {\n           signature= file.Element("Signature").Value,\n           extensions= file.Element("Extension").Value.Split('|'),\n           description = file.Element("Description").Value\n         }).ToList();	0
6837340	6836551	replacing substring inside attributes of XmlDocument	XDocument doc = XDocument.Load(path);\n doc.XPathSelectElements("//element[@attribute-name = 'myMachine']").ToList().ForEach(x => x.SetAttributeValue("attribute-name", "newMachine"));	0
4215582	4215512	How to disable filtering in telerik grid	grid.AllowFilteringByColumn = false;	0
13063813	13062291	How to return using the Usercontrol WPF	(this.Parent as Panel).Children.Remove(this)	0
32632411	32632312	C# - Split a string with spaces in between in multiple strings	string sentence = "Example sentence";\nstring [] sentenses = sentence.Split(' ');\n\nstring one = sentenses[0];\nstring two = sentenses[1];	0
19399874	19399607	Saving multiple lists into ViewState	var list = TemplateTypeProcedureList.Add(new item);\n TemplateTypeProcedureList = list;	0
15460162	15459512	C# Last DataGridView Row Value in Textbox	int lastRow = yourDataGridView.Rows.Count - 1;\nobject last_order_ID = yourDataGridView.Rows[lastRow].Cells["order_ID"].Value;\nyourTextBox.Text = Convert.ToString(last_order_ID);	0
1366356	1366321	How to get the process names of applications in taskbar using c#?	Process[] processes = Process.GetProcesses();\n            foreach (var item in processes)\n            {\n                if(item.MainWindowTitle.Length > 0)\n                    Console.WriteLine(item.MainWindowTitle);\n            }	0
15454271	15454231	Parse XML file in Windows Phone	foreach (var item in level1Element.Descendants("item"))\n    item.Value; // this contains szt and ml	0
20859757	20859455	Console Application to count all '#' characters in a text file	static void Main(string[] args) {\n  //String fileName = @"C:\Documents and Settings\9chat73\Desktop\count.txt"; \n\n  // To search dinamically, just ask for a file:\n  Console.WriteLine("Enter a file to search");\n  String fileName = Console.ReadLine().Trim(); \n\n  if (File.Exists(fileName)) {\n    Console.WriteLine("Enter a word to search");\n    String pattern = Console.ReadLine().Trim();\n\n    // Do not forget to escape the pattern! \n    int count = Regex.Matches(File.ReadAllText(fileName), \n                              Regex.Escape(pattern), \n                              RegexOptions.IgnoreCase).Count;\n\n    Console.WriteLine(count.ToString());\n  }\n\n  Console.ReadLine();\n}	0
23039464	23039398	application not work correctly after change type to windows application	Upload()	0
19832469	19832191	How to get the non public property of an object and its value at the same time	this.GetType().GetField("Person",   \n     System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).GetValue(this)	0
26548412	26548358	Lambda Statement	List<string> vals = new List<string>();\nvals.AddRange(filterValue.Split(new char[] { ',' }));\nvar bindingEntities = entities.Where(\n             e => e.ExtraProperties.Any(\n             kvp => vals.Contains(kvp.Value.ToString()))).ToList();	0
25366437	25255507	Talking to a KX-NCP1000 PABX	public static class Extensions\n  {\n    /// <summary>\n    /// Obtain the current state of the socket underpinning a TcpClient.\n    /// Unlike TcpClient.Connected this is reliable and does not require \n    /// capture of an exception resulting from a failed socket write.\n    /// </summary>\n    /// <param name="tcpClient">TcpClient instance</param>\n    /// <returns>Current state of the TcpClient.Client socket</returns>\n    public static TcpState GetState(this TcpClient tcpClient)\n    {\n      var foo = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()\n        .SingleOrDefault(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint));\n      return foo != null ? foo.State : TcpState.Unknown;\n    }\n  }	0
1321996	1321959	How to get hiddenfield in itemtemplate of gridview in button click	string hiddenFieldValue = ((HiddenField) yourGridView.Rows[0].FindControl("yourHiddentFieldName")).Value;	0
10238128	10238065	Sending a variable in a C# EventHandler?	public class ButtonClickedEventArgs : EventArgs\n{\n    public int EventInteger { get; private set; }\n\n    public ButtonClickedEventArgs(int i)\n    {\n        EventInteger = i;\n    }\n}	0
4318718	4318693	String to byte[] and vice versa?	// string to byte[]\nbyte[] bytes = Encoding.UTF8.GetBytes(someString);\n\n// byte[] to string\nstring anotherString = Encoding.UTF8.GetString(bytes);	0
9923244	9923117	Filter List Data C#	filterString.Split(',')\n  .Select(s => s.Split('-'))\n  .GroupBy(ss => ss[0])\n  .Select(group => string.Join("-", new[]{group.Key}.Concat(group.Select(ss => ss[1])).ToArray()));	0
4329550	4329521	How to handle Word close event from WinForms application?	process.WaitForExit();	0
4094899	4094805	Writing a method that will accept table as an input	if(TabmeNameA)\n{\n   // Execute Query for table A\n}\nif(TabmeNameB)\n{\n   // Execute Query for table B\n}	0
7233800	7232743	How to move DateTime to and from XML and Dataset	DataSet1.WriteXml(fileName, XmlWriteMode.WriteSchema);	0
33755165	33753943	Get only InnerText of this node excluding children	var xpath = "//td[contains(text(),'Invoice-Number') or contains(span,'Invoice-Number')]";\nvar invoiceCell = doc.DocumentNode.SelectSingleNode(xpath);	0
20389523	20364198	How to make LINQ to EF query more efficient	var PriceDrops = idxContext.ListingPriceChanges\n        .Where(a => a.DateAdded >= LastRunTime && ListingIDsChunk.Contains(a.ListingID))\n    .GroupBy(g => g.ListingID)\n    .Where(g => g.Count() > 1)\n    .Select(g => g.OrderByDescending(a => a.DateAdded).Take(2))\n    .ToList()\n    .Where(g => g.First().ListPrice < g.Last().ListPrice)\n    .SelectMany(g => g)\n    .ToList();	0
28938570	28938175	Fetch blob into a linq object	(byte[])reader["blob"];	0
14981630	14981570	Add reference to webservice	wsdl.exe description.wsdl	0
20409576	20409443	Replacing a pattern in C#	string s = "a,,,b,c,,,,d";\nvar replaced = Regex.Replace(s, ",(?=,)", ",null");\nConsole.WriteLine(replaced);	0
20063023	20062717	Display filenames of selected files - asp:fileupload	protected void uploadFile_Click(object sender, EventArgs e)\n{\n   if (UploadImages.HasFiles)\n   {\n       foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)\n       {\n         uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),\n           uploadedFile.FileName)); \n         listofuploadedfiles.Text += String.Format("{0}<br />", uploadedFile.FileName);\n       }\n   }\n}	0
2518235	2518220	Missing backslashes in filename using C#	Path.Combine	0
19181045	19179686	ASP Chart, Year, Month, Day drill down	foreach (DataPoint p in Chart1.Series[0].Points)\n{\n    p.Url = string.Format("details.aspx?id={0}", p.XValue);\n}	0
1413426	1413407	How to get notified of session end?	Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)\n' Fires when the session ends\nEnd Sub	0
1940275	1940214	How to check if a list is ordered?	var studyFeeds = Feeds.GetStudyFeeds(2120, DateTime.Today.AddDays(-200), 20);   \nvar expectedList = studyFeeds.OrderByDescending(x => x.Date);\nAssert.IsTrue(expectedList.SequenceEqual(studyFeeds));	0
19853570	19809811	How to hide or manipulate a control inside a ListView	TextBox Box = new TextBox()\n\nButton Butt = new Button();\n\nBox = (TextBox)e.Item.FindControl("TextBoxComment")\nButt = (Button)e.Item.FindControl("ButtonSubmit")\n\nBox.Visible = false;	0
11291031	11290871	ASP.NET WebAPI XML Serialization after RC update	GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;	0
27728722	27728606	Converting string into multidimensional char array c#	string input = "S#####\n.....#\n#.####\n#.####\n...#.G\n##...#";\n\nchar[,] charArray = new char[6, 6];\n\nvar lines = input.Split(new [] { '\n' });\nint row = 0;\nforeach (string line in lines)\n{\n    int column = 0;\n    foreach (char character in line)\n    {\n       charArray[row, column] = character;\n       column++;\n    }\n    row++;\n}\nConsole.ReadKey();	0
28116224	28116165	Get collection containing a specific object out of a collection	RoomCollection = LocationalLinkList.Where(o => o.RoomCollection.Any(i => i.Room == obj));	0
8926884	8926754	Read until condition is met and read next line storing it as an array	string[] readAllLines = File.ReadAllLines("path/to/file");\nfor (int i = 0; i < readAllLines.Length-1; i++)\n{\n    if (readAllLines[i].StartsWith("[employee]"))\n    {\n        string[] employees = readAllLines[i + 1].Split(',');\n        // Do something\n    }\n}	0
20813193	20813005	How to change default timezone c#	DateTime utcTime = DateTime.UtcNow;\n\n        string zoneID = CurrentUserSession.TimeZoneID // Here you get the current login user session and their TimeZone which you configured in database at the time of user creation. or if you want to get client pc time zone then you have to use javascript and get client pc Timezone\n\n        TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById(zoneID);\n        DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);	0
5053613	5053546	Excuting Javascript Commands From Cs	protected void btnFoo_Click(object sender, EventArgs e)\n{\n    if(!ClientScript.IsStartupScriptRegistered("foo"))\n        ClientScript.RegisterStartupScript(GetType(), "foo", "foo();", true);\n}	0
17427069	17423117	WPF / MVVM not updating till I click in the window	public CameraControlViewModel( DataModel dataModel )\n: base( dataModel )\n{\n    dataModel.PropertyChanged += DataModelOnPropertyChanged;    \n\n    _captureImageCommand = new RelayCommand( captureImage, captureImage_CanExecute );\n    _capturedImage = new BitmapImage();\n    _capturedImage.BeginInit();\n    _capturedImage.UriSource = new Uri( "Images/fingerprint.jpg", UriKind.Relative );\n    _capturedImage.CacheOption = BitmapCacheOption.OnLoad;\n    _capturedImage.EndInit();\n}\n\nprivate bool captureImage_CanExecute( object arg)\n{\n    return !dataModel.IsScriptRunning && !_captureInProgress;\n}	0
26250909	26250875	Add a static value in list when using Except	var diff = a.Except(b)\n            .Select(s=>new modelClass(){id = s, isTrue = true})\n            .ToList();	0
27496362	27496179	Using a RegEx via C# to split by keywords except within quotes	string str = "A1 = B2 AND A2 = 'M AND M' AND A3 NOT IN ( 'E1' , 'E2' )";\nRegex regex = new Regex(@"(?<!'\w+)\sAND\s(?!\w+')");\nstring[] arr = regex.Split(str);	0
1234299	912741	How to delete Cookies from windows.form?	webBrowser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())")	0
2988798	2988699	how to reverse the order of words in query or c#	string location = "India,Tamilnadu,Chennai,Annanagar";\nstring[] words = location.Split(',');\n\nArray.Reverse(words);\n\nstring newlocation = String.Join(",", words);\n\nConsole.WriteLine(newlocation); // Annanagar,Chennai,Tamilnadu,India	0
29627799	29625859	C# Panel with Grid/Overlay	public partial class MainWindow : Window\n{\npublic MainWindow()\n{\n    InitializeComponent();\n    fillWithToggles();\n}\n\npublic void fillWithToggles()\n{\n    for (int i = 0; i < 10; i++)\n    {\n        ColumnDefinition gridCol = new ColumnDefinition();\n        gridCol.Name = "Column" + i.ToString();\n        DynamicGrid.ColumnDefinitions.Add(gridCol);\n    }\n\n    for (int i = 0; i < 10; i++)\n    {\n        RowDefinition gridRow = new RowDefinition();\n        gridRow.Name = "Row" + i.ToString();\n        DynamicGrid.RowDefinitions.Add(gridRow);\n    }\n\n    for (int x = 0; x < 10; x++)\n    {\n        for (int y = 0; y < 10; y++)\n        {\n            System.Windows.Controls.Primitives.ToggleButton tb = new ToggleButton();\n            tb.VerticalAlignment = VerticalAlignment.Stretch;\n            tb.HorizontalAlignment = HorizontalAlignment.Stretch;\n            Grid.SetColumn(tb, x);\n            Grid.SetRow(tb,y);\n            DynamicGrid.Children.Add(tb);\n        }                \n    }\n}}	0
1318161	1318154	C# validating data in multiple text boxes?	Core.Model.Settings.Labels.ToList()\n.ForEach(x => schedulerStorage1.Appointments.Labels.Add(Color.FromArgb(x.ARGB), x.LabelName));	0
26917256	26889095	Are there any restrictions on opening a Windows runtime (Metro) app from within another Windows runtime app?	await Launcher.LaunchUriAsync(new Uri("bingmaps:?cp=40.726966~-74.006076"));	0
4460731	4460709	Detect if control was disposed	Control.IsDisposed	0
29688694	29688436	How to compile single c# file on mac console using mono?	mono Hello.exe	0
2366810	2366059	I need help syncing perforce on a remote machine with c#	public static void perforce_sync()\n    {\n\n        string computer_name = @"server_name";\n        ManagementScope scope = new ManagementScope("\\\\" + computer_name + "\\root\\cimv2");\n        scope.Connect();\n        ObjectGetOptions object_get_options = new ObjectGetOptions();\n        ManagementPath management_path = new ManagementPath("Win32_Process");\n        ManagementClass process_class = new ManagementClass(scope, management_path, object_get_options);\n        ManagementBaseObject inparams = process_class.GetMethodParameters("create");\n        inparams["CommandLine"] = @"p4 sync -f //release/...";\n        ManagementBaseObject outparams = process_class.InvokeMethod("Create", inparams, null);\n        Console.WriteLine("Creation of the process returned: " + outparams["returnValue"]);\n        Console.WriteLine("Process ID: " + outparams["processId"]);\n\n    }	0
30460118	30460072	Monogame XNA transform matrix for a single object?	SpriteBatch.Begin(...matrix);\n\n//Draw stuff with matrix\n\nSpriteBatch.End();\n\nSpriteBatch.Begin();\n\n//do the rest of the drawing\n\nSpriteBatch.End();	0
19307043	19295757	Using group by and count lambda expression	public List<DummyModel> Method(int id)\n    {\n        return _context.Visitas.Where(a => a.CicloId == id).GroupBy(a => a.Estado).\n            Select(n => new DummyModel { Name = n.Key.Descripcion, Value = n.Count() }).ToList();\n    }	0
22843246	22544130	I want to delete a user from a list that ID's and rows change dynamically using Selenium in C#	string pagesource = wd.PageSource;\n            int username = pagesource.IndexOf("what you are looking for");\n            string anything = pagesource.Substring(username - 60, 70);\n            string buttonID = anything.Substring(anything.IndexOf("an ID"), 10);\n            string buttonID2 = buttonID.Substring(0, buttonID.IndexOf('_'));	0
28952750	28952684	Entity Framework 6 code first fluent api config for one to one entity relationship	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    // Configure StudentId as PK for StudentAddress\n    modelBuilder.Entity<StudentAddress>()\n        .HasKey(e => e.StudentId);\n\n    // Configure StudentId as FK for StudentAddress\n    modelBuilder.Entity<Student>()\n                .HasOptional(s => s.StudentAddress) // Mark StudentAddress is optional for Student\n                .WithRequired(ad => ad.Student); // Create inverse relationship\n\n}	0
21602273	21602047	RedirectToAction() loss request data	[HttpPost]\npublic ActionResult Index(MyViewModel model)\n{\n    if (!ModelState.IsValid)\n    {\n        // some validation error occurred => redisplay the same form so that the user\n        // can fix his errors\n        return View(model);\n    }\n\n    // at this stage we know that the model is valid => let's attempt to process it\n    string errorMessage;\n    if (!DoSomethingWithTheModel(out errorMessage))\n    {\n        // some business transaction failed => redisplay the same view informing\n        // the user that something went wrong with the processing of his request\n        ModelState.AddModelError("", errorMessage);\n        return View(model);\n    }\n\n    // Success => redirect\n    return RedirectToAction("Success");\n}	0
31298752	31297227	Issues changing color in richtextbox	void AboutBox_Load(object sender, EventArgs e)\n    {\n        this.ColorPrefix(richTextBox1, "[b]", Color.Green);\n        this.ColorPrefix(richTextBox1, "[f]", Color.Red); // change the color!\n        this.ColorPrefix(richTextBox1, "[e]", Color.Yellow); // change the color!\n    }\n\n    private void ColorPrefix(RichTextBox rtb, string prefix, Color color)\n    {\n        int position = 0, index = 0;\n        while ((index = rtb.Find(prefix, position, RichTextBoxFinds.None)) >= 0)\n        {\n            rtb.Select(index, prefix.Length);\n            rtb.SelectionColor = color;\n            position = index + 1;\n        }\n        rtb.Select(rtb.TextLength, 0);\n    }	0
17849444	13151178	Create a windows application using Microsoft Office Word add-in	public void ReleaseObject(object obj)\n       {\n           try\n           {\n               System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);\n               obj = null;\n           }\n           catch (Exception)\n           {\n               obj = null;\n           }\n           finally\n           {\n               GC.Collect();\n           }\n       }	0
19288396	19264944	'Streaming' data into Sql server	private static void InsertDataUsingObservableBulkCopy(IEnumerable<Person> people, \n                                                      SqlConnection connection)\n{\n    var sub = new Subject<Person>();\n\n    var bulkCopy = new SqlBulkCopy(connection);\n    bulkCopy.DestinationTableName = "Person";\n    bulkCopy.ColumnMappings.Add("Name", "Name");\n    bulkCopy.ColumnMappings.Add("DateOfBirth", "DateOfBirth");\n\n    using(var dataReader = new ObjectDataReader<Person>(people))\n    {\n        var task = Task.Factory.StartNew(() =>\n        {\n            bulkCopy.WriteToServer(dataReader);\n        });\n        var stopwatch = Stopwatch.StartNew();\n        foreach(var person in people) sub.OnNext(person);\n        sub.OnCompleted();\n        task.Wait();\n        Console.WriteLine("Observable Bulk copy: {0}ms",\n                           stopwatch.ElapsedMilliseconds);\n    }\n}	0
756743	756723	StringDictionary as a common static list?	public static class Common\n{\n    private static StringDictionary _domains;\n    static Common()\n    {\n        _domains = new StringDictionary();\n        _domains.Add("212", "Location A");\n        _domains.Add("555", "Location B");\n        _domains.Add("747", "Location C");\n        _domains.Add("000", "Location D");\n    }\n    public static StringDictionary Domains\n    {\n        get\n        {\n            return _domains;\n        }\n    }\n}	0
19681122	19681048	Add scrollbar to Groupbox containing Thumbail images	private void AddPicturesToGroupBox(List<PictureBox> pictureBoxes)\n{\n    Panel myPanel = new Panel();\n    myPanel.Dockstyle = Dockstyle.Fill;\n    myPanel.AutoScroll = true; //this allows the panel to display scrollbars when it needs to\n\n    foreach (var pic in pictureBoxes)\n    {\n        myPanel.Controls.Add(pic); //put your pictures onto the panel\n    }\n\n    this.gbFacets.Controls.Clear();\n    this.gbFacets.Controls.Add(myPanel); //put your panel inside the Groupbox\n}	0
20968135	20964871	Making web service calls with WCF client + cookies	var prop = new HttpRequestMessageProperty();\nprop.Headers.Add(HttpRequestHeader.Cookie, sharedCookie);\nOperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, prop);	0
11140205	11127756	Dealing with Object Graphs - Web API	public class TaskViewModel {\n  public TaskViewModel ()\n  {\n     this.Activities = new List<ActivityViewModel>();\n   }\n\n  public int TaskId { get; set; }\n  public string TaskSummary { get; set; }\n  public string TaskDetail { get; set; }\n\n  public virtual IList<ActivityViewModel> Activities { get; set; }\n}\n\npublic class ActivityViewModel{\n  public ActivityViewModel()\n  {        \n  }\n\n  //Activity stuff goes here\n  //No reference to Tasks here!!\n}	0
31984233	31983625	Only get entries from DB matching the current week	var dbHours = DAO.Instance.HourRegistration\n    .Where(x => x.Login_ID == logId && x.Cust_ID == custId)\n    .Include(x => x.Customer)\n    .ToList()\n    .Where(x => GetIso8601WeekOfYear(x.Date) == GetIso8601WeekOfYear(DateTime.Now));	0
10793270	10793243	c# Assigning a reference	active_account = chosen.CreateAccount(\n    account_num, account_pin, name, balance, type);\n\nactive_account.DoStuff();	0
27367738	27367621	Implicitly declaring a parameter in an ASP.NET MVC action	public class BaseController : Controller\n{\n    protected string Token { get; private set; }\n\n    protected override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        base.OnActionExecuting(filterContext);\n\n        string token = Request.QueryString["token"] as string;\n        Token = token ?? string.Empty;\n    }\n}	0
4311633	4311526	How to internet explorer properties window in C#	"C:\Windows\system32\rundll32.exe" C:\Windows\system32\shell32.dll,Control_RunDLL C:\Windows\system32\inetcpl.cpl,,4	0
27684452	27684288	Regular Expression for Multiple Dates	function CompareDates(tbStartDateID, tbEndDateID) {\n    var startDate = document.getElementById(tbStartDateID).value;\n    var endDate = document.getElementById(tbEndDateID).value;\n    //Difference in milliseconds\n    var timeDiff =  Date.parse(endDate) - Date.parse(startDate);\n    if (Date.parse(endDate) > Date.parse(startDate)) {\n\n        alert("It is okay, end date is greater than start date");\n    }\n    else {\n        alert("Start Date must be lesser than end Date");\n    }\n}	0
10290858	10290838	How to get MAX value from Dictionary?	d.Keys.Max(); // Returns the greatest key	0
32144209	32143890	Update Drop Down List From Selection Of Another	protected void ddlCompName_SelectedIndexChanged(object sender, EventArgs e)\n{\n  if (VBS.Left(ddlCompName.SelectedItem.Text, 2) == "On")\n  {\n    ddlLocation.SelectedValue = "Building One";\n  }\n}	0
29870325	29854174	Navigation from OnDoubleTapped method	Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new DispatchedHandler(() =>\n            {\n                Frame thisFrame = Window.Current.Content as Frame;\n                Window.Current.Activate();\n                thisFrame.Navigate(typeof(Target));\n            }));	0
20300571	20300245	Join Two DataTables (Some Rows Match some Don't)	var results = (from table1 in T1.AsEnumerable()\n               join tmp in T2.AsEnumerable() on table1["Registration"] equals tmp["Registration"] into grp\n               from table2 in grp.DefaultIfEmpty()\n               select new\n               {\n                   Registration = (String)table1["Registration"],\n                   DistanceInKM = (decimal)table1["DistanceInKM"],\n                   TotalDistanceTravelledKM = (table2 == null ? (double?)null : (Double)table2["TotalDistanceTravelledKM"])\n               };	0
18738241	18738102	Combine columns from different tables in Lambda	var result = ItemCategoryDetailOptions\n    .Where(i => !i.IsHidden && i.Retired != null)\n    .Select(i => i.Option)\n    .Distinct()\n    .Union(Items\n      .Where(i => i.Brand != null)\n      .Select(i => i.Brand)\n      .Distinct()))\n    .Where(i => i.Contains("LG"));	0
3997787	3997066	Define a list type into a variable	public IEnumerable<T> GetSomething<T>()\n{\n    return (from foo in NHibernate_Helper.session.Linq<T>() select foo);\n}\n...\nGetSomething<TheType>();	0
4753352	4741036	COM+ component not reading configuration from static context	private static readonly Lazy<IUnityContainer> m_unityContainer = new Lazy<IUnityContainer>(() => new UnityContainer().LoadConfiguration());	0
31742077	31054312	How to use two arrays in one foreach loop using C#	int[] numbers = { 1, 2, 3, 4 };\n            string[] words = { "one", "two", "three" };\n\n            var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);\n\n            foreach (var item in numbersAndWords)\n                Console.WriteLine(item);\n\n            // This code produces the following output: \n\n            // 1 one \n            // 2 two \n            // 3 three	0
28992142	28992052	How to pass along cell value to row databound event after rowediting event	DropDownList newMedChangeChangeDD = (DropDownList)e.Row.FindControl("NewMedChangeChangeDD");\nnewMedChangeChangeDD.SelectedValue = DataBinder.Eval(e.Row.DataItem, "YourDataFieldName").ToString();	0
24586338	24586281	calculating person age showes the same number everytime	DateTime drid2 = Convert.ToDateTime(textBox74.Text);\nDateTime drid3 = DateTime.Now;\nint yy1 = Math.Abs(drid1.Year - drid2.Year);\ntextBox70.Text = yy1.ToString();	0
1945300	1945257	C # to VB.NET - Using interface	Dim vUsers As New UserSettings()\n\nDim vUserI As UserSettings.IUserSettings = DirectCast(vUsers, UserSettings.IUserSettings)	0
7808892	7808807	How to compare HH:MM in C#	TimeSpan s1 = TimeSpan.Parse(t1);\nTimeSpan s2 = TimeSpan.Parse(t2);\nreturn s1.CompareTo(s2);	0
9767861	9767768	convert this lines of delegate from c# to vb .net	Public ReceiveData As Action(Of List(Of Byte)) = Sub() \nEnd Sub	0
20229260	20228926	populate DropDownList with a list	protected void Page_Load(object sender, EventArgs e)        \n{\n  if (!Page.IsPostBack && Session["listSession"] != null)\n  {\n    var myBall = (List<Ball>)Session["listSession"];\n    foreach (var ball in myBall)\n      DropDownList1.Items.Add(item.getBallInfo());\n  }\n}	0
9914690	9914623	how to make a right join using LINQ to SQL & C#	var RightJoin = from adds in dc.EmpresaAddendas\n                 join cats in CatAddendas \n                     on adds.IDAddenda equals cats.IDAddenda into joined\n                 from cats in joined.DefaultIfEmpty()\n                 select new\n                 {\n                     Id = cats.IDAddenda,\n                     Description = cats.Descripcion \n                 };	0
22731605	22731541	How to add an ImageButton to label using c#	Delete.Controls.Add(img);	0
16522157	16521824	How to show control in transparent window?	Form.TransparencyKey	0
12741743	12741657	Getting the previous value of an object at ValueChanged event	public class LastDateTimePicker : DateTimePicker {\n    protected override void OnValueChanged(EventArgs eventargs) {\n        base.OnValueChanged(eventargs);\n\n        LastValue = Value;\n        IsProgrammaticChange = false;\n    }\n\n    public DateTime? LastValue { get; private set; }\n    public bool IsProgrammaticChange { get; private set; }\n\n    public new DateTime Value { \n        get { return base.Value; }\n        set {\n            IsProgrammaticChange = true;\n            base.Value = value;\n        }\n    }\n}	0
3641499	3641296	Create thread just like if it were a separated application in C#	public delegate void SetWebAddressDelegate ( WebBrowser browser, Uri newUrl);\n\npublic void SetWebAddress ( WebBrowser browser, Uri newUrl )\n{\n    if (browser.InvokeRequired)\n        browser.Invoke(new SetWebAddressDelegate(SetWebAddress), browser, newUrl);\n    else\n        browser.Url = newUrl;\n}	0
20553649	19303612	ListView with lots of items has problems with painting	typeof(Control).GetProperty("DoubleBuffered", BindingFlags.NonPublic |\n BindingFlags.Instance).SetValue(yourListView, true, null);	0
16374346	16374024	How to two joins in linq	var text = listView3.SelectedItems[0].Text;\n\nvar subTask = (from sub in ado.submit_task\n  join s in ado.student on sub.student_id equals s.id\n  join t in ado.task on sub.task_id equals t.id\n  where t.t_name == text\n  select new { s.s_name, sub.state, sub.to, sub.evaluation, sub.task_id });	0
12127109	12127098	How can i get only a part of a file name?	public override string ToString()\n{\n    return Regex.Replace(this.fsi.Name, @"[\d]", string.Empty);\n}	0
15020048	15012377	Fire an Event with dot42	[EventHandler]\npublic void sendMessage(View view)\n{\n    Toast.MakeText(this, "Button pressed", Toast.LENGTH_LONG).Show();\n}	0
34078961	34077612	Linq To Entities Group By with multiple tables in key	var query =\n    TableCs.SelectMany(c => c.TableA.TableBs\n        .Where(b => b.Col5 == "SomeValue"\n            // && ...\n        ),\n        (c, b) => new { c, b }\n    )\n    .GroupBy(r => new { r.c.Col2, r.c.Col3, r.b.Col5 })\n    .Select(g => new\n    {\n        g.Key.Col2,\n        g.Key.Col3,\n        g.Key.Col5,\n        SomeColumnC = g.Sum(r => r.c.SomeColumn),\n        SomeColumnB = g.Sum(r => r.b.SomeColumn)\n        // ...\n    });	0
14261313	14261010	Removing a runtime's created TabItem by name	tb = (TabPage)(tc_Descuento.Controls.Find("Cuota-" + Convert.ToString(cuota.num_cuota), false).First());	0
2554222	2546211	CRM 4.0 Picklist Value is updated via workflow, but old value still shows on form until refresh	public void Execute(IPluginExecutionContext context)\n{\n    if (context.InputParameters.Properties.Contains("Target") &&\n        context.InputParameters.Properties["Target"] is DynamicEntity)\n    {\n        DynamicEntity opp = (DynamicEntity)context.InputParameters["Target"];\n        opp["salesstagecode"] = new Picklist(200004);\n    }\n}	0
32860355	32846047	Get Specific Attribute on Route Method from WebAPI Request	public class AuthorizableRouteFilterAttribute : AuthorizationFilterAttribute\n{\n   public override void OnAuthorization(HttpActionContext context)\n   {  \n      IPrincipal principal = Thread.CurrentPrincipal;            \n      /*Your authorization check here*/\n\n      if (!principal.IsInRole("YourRole")) // or whatever check you make\n      {\n           context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);\n           return;\n      }\n   }        \n}\n\n\n[HttpPost]\n[AuthorizableRouteFilter]\npublic HttpResponseMessage DataAction([FromBody] DataType data)\n{\n    /* Actions */\n}	0
9866163	9866131	Expression Encoder SDK with c#, how to cut video, audio	// Create a media item and get a pointer to the inital source.\nMediaItem item = new MediaItem(@"c:\users\Public\Videos\Sample Videos\Wildlife.wmv");\nSource source = item.Sources[0];\n\n// Change the first clip so that instead of spanning the entire file\n// I'm just going to encode the bit from 5 to 10 seconds.\nsource.Clips[0].StartTime = new TimeSpan(0, 0, 5);\nsource.Clips[0].EndTime = new TimeSpan(0, 0, 10);\n\n// Also add the bit from 20 to 30 seconds from the original file.\nTimeSpan secondClipStart = new TimeSpan(0,0,20);\nTimeSpan secondClipEnd = new TimeSpan(0,0,30);\nsource.Clips.Add(new Clip(secondClipStart, secondClipEnd));	0
17973294	17973139	AdvTree select all nodes programatically	For Each nd As Node In tvComputers.Nodes\n     tvComputers.SelectedNodes.Add(nd)\n Next	0
7349773	7349682	Setting focus on a text box on page load	document.getElementById('<%= tbSearchLastName.ClientID%>').focus();	0
10258912	10258873	string of ints to list of ints with a TryParse	TheListOfLeadIDs = (from string s in TheString.Split(',')\n                    let value = 0\n                    where int.TryParse(s, out value)\n                    select value).ToList<int>();	0
6641772	6641619	AppDomain event that gets called for *ATTEMPTED* assembly resolution	public static class AssemblyLoader\n{\n    public delegate void LoadDelegate(string path);\n\n    public void LoadAssembly(string path)\n    {\n        if(OnPreLoad != null)\n            OnPreLoad(path);\n        // load assembly here\n    }  // eo LoadAssembly\n\n    public event LoadDelegate OnPreLoad;\n} // eo AssemblyLoader	0
16934314	16933842	Find token values within a string c#	string pattern = "Hi, my name is ${name}, I am ${age} years old. I live in ${address}";\n    string input = "Hi, my name is Peter, I am 22 years old. I live in San Francisco, California";\n    string resultRegex = Regex.Replace(Regex.Escape(pattern), @"\\\$\\\{(.+?)}", "(?<$1>.+)");\n    Regex regex = new Regex(resultRegex);\n    GroupCollection groups = regex.Match(input).Groups;\n\n    Dictionary<string, string> dic = regex.GetGroupNames()\n                                          .Skip(1)\n                                          .ToDictionary(k => "${"+k+"}",\n                                                        k => groups[k].Value);\n    foreach (string groupName in dic.Keys)\n    {\n        Console.WriteLine(groupName + " = " + dic[groupName]);\n    }	0
17832106	17831927	Parse DateTime issue in C#	string serverDate = "Sat Nov 03 13:03:13 GMT+05:30 2012";\n\nvar date = DateTime.ParseExact(serverDate, @"ddd MMM dd HH:mm:ss \G\M\TK yyyy", CultureInfo.InvariantCulture);	0
34224817	34222960	CSS - Setting image-size in the Outlook browser	?RenditionID=6	0
32270964	32269979	How to inject an instance of a type, per request using Unity Container for Web API	public static void RegisterTypes(IUnityContainer container)\n    {\n        // Some other types registration .\n\n        container.RegisterType<StoreDetails>(\n            //new PerResolveLifetimeManager(), \n            new InjectionFactory(c => {\n                int storeId;\n                if(int.TryParse(HttpContext.Current.Request.Headers["StoreId"], out storeId)) {\n                    return new StoreDetails {StoreId = storeId};\n                }\n                return null;\n            }));\n    }	0
8072572	8072506	Add Icons to Application Bar Based on Page	ApplicationBar.Buttons.Clear();\nApplicationBar.Buttons.Add(new ApplicationBarIconButton(iconUri) {Text = "some button"});	0
11524621	11507010	How to Update or Refresh a panel or control in tab container	protected void btnAdd_Click(object sender, EventArgs e)\n    {\n\n        this.divAddEditRow.Visible = false;\n        btnShowAddSection.Visible = true;\n\n        if (pnlStatus.Visible == true)\n        {               \n            WorkflowDataService.InsertWFStatus(0, txtEdit.Text);\n            gvStatus.DataBind();\n        }\n\n        if (pnlAction.Visible == true)\n        {\n            WorkflowDataService.InsertWFAction( 0, txtEdit.Text);\n            gvAction.DataBind();\n        }   \n    }	0
25119164	25118859	Different Approach to count Facebook, Twitter, Google+ Shares via jQuery?	{"count":92127,"url":"http:\/\/www.google.co.uk\/"}	0
15353560	15353200	Convert Generic Method Parameter to Specific Type	public List<T> Get<T>(Expression<Func<T,bool>> expr){\n    var expr2 = expr as Expression<Func<Stuff, bool>>;\n    if (expr2 != null){\n        return Get(expr2) as List<T>;\n    }\n\n    //...\n}	0
16086678	16085373	In WPF, how do you tell if the left mouse button is currently down without using any events?	private void _sliderVideoPosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {\n        _adjustingVideoPositionSlider = true;\n        _mediaElement.Pause();\n    }\n\n    private void _sliderVideoPosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n    {\n        _adjustingVideoPositionSlider = false;\n        _mediaElement.Play();\n    }\n\n    private void _sliderVideoPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n    {\n        if (_adjustingVideoPositionSlider)\n        {\n            _mediaElement.Position = TimeSpan.FromMilliseconds((int)e.NewValue);\n        }\n    }	0
17368410	17222802	Correctly Using CanExecute for MVVM Light ICommand	bool CanSendStuff(object parameter);\n    //\n    // Summary:\n    //     Defines the method to be called when the command is invoked.\n    //\n    // Parameters:\n    //   parameter:\n    //     Data used by the command. If the command does not require data to be passed,\n    //     this object can be set to null.\n    void Execute(object parameter);	0
23230123	23230096	Sample name generator that randomly picks from an array of names	Random rnd = new Random();\nvar randomname = {"Jess", "Jay", "Jen", "Jack", "Jan"}.OrderBy(a => rnd.NextDouble()).First();	0
9202864	9202831	How do I cast this type into a Dictionary?	Dictionary<string, IPropertyListDictionary> maindict = (data["section0"].DictionaryItems).ToDictionary(x => x.Key, x => x.Value);	0
28924725	28924693	how to combine this linq query to a combobox	var fillcmb=(from crs in re.Sections\n             from r in re.Courses\n                where crs.CourseID == r.CourseID\n                select new { Name = r.Name.ToString(), CourseID = crs.CourseID})\n            .ToList();	0
9899463	9899364	Autofac with F#	open Autofac\nlet _containerBuilder = new ContainerBuilder()\n\n_containerBuilder.RegisterGeneric(typedefof<CommandObserver<_>>)\n    .As(typedefof<ICommandObserver<_>>);\n\n_containerBuilder.RegisterGeneric(typedefof<PropertyProvider<_>>)\n    .As(typedefof<IPropertyProvider<_>>);	0
15030197	15030152	XmlReader how to do it from memory and not disk	Page.Cache	0
28822636	28821889	Get value between unknown string	(?<=office.*\n.*300px">).*(?=<\/td)	0
3066051	3066039	Setting a timer?	Thread.Sleep(60000);	0
5275324	5275115	Add a Median Method to a List	public static decimal GetMedian(this IEnumerable<int> source)\n{\n    // Create a copy of the input, and sort the copy\n    int[] temp = source.ToArray();    \n    Array.Sort(temp);\n\n    int count = temp.Length;\n    if (count == 0)\n    {\n        throw new InvalidOperationException("Empty collection");\n    }\n    else if (count % 2 == 0)\n    {\n        // count is even, average two middle elements\n        int a = temp[count / 2 - 1];\n        int b = temp[count / 2];\n        return (a + b) / 2m;\n    }\n    else\n    {\n        // count is odd, return the middle element\n        return temp[count / 2];\n    }\n}	0
25968587	25947012	How to open locally stored html file within flyout?	private void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)\n    {\n        SettingsCommand settingsCommand = new SettingsCommand(\n             "About",\n             "About",\n             command =>\n             {\n                 var flyout = new SettingsFlyout();\n                 flyout.Title = "About";\n\n                 WebView wView = new WebView();\n                 wView.Height = 700;\n                 wView.Width = 300;\n                 wView.Navigate(new Uri("ms-appx-web:///assets/About.html", UriKind.Absolute));\n\n                 flyout.Content  = wView;\n\n                 flyout.Show();\n             }\n           );\n        args.Request.ApplicationCommands.Add(settingsCommand);\n\n    }	0
30811613	30811541	Not getting desired elements from XDocument	XNamespace ns = "http://xmlgw.companieshouse.gov.uk/v1-0/schema";\nvar results = xDocument.Descendants(ns + "CoSearchItem")                                \n                                  .Select(n => new \n                                  { \n                                       CompanyName = n.Element(ns +"CompanyName").Value, \n                                       CompanyNumber = n.Element(ns +"CompanyNumber").Value \n                                   })\n                                   .ToList();	0
28325201	28307399	Access IIS IP Blocked List using impersonation account	ServerManager.dll	0
4530597	4530459	Deleting items from datagrid (xml)	protected void dg_DeleteCommand(object sender, DataGridCommandEventArgs e)     \n{\n         XmlFunctions.Remove(grid selected value);     \n}\n\npublic static void Remove(string itemValue) \n{\n   XDocument doc = XDocument.Load("xmlfile.xml");\n   doc.Descendants("test")\n         .Where(p=>p.Attribute("id") != null \n                   && p.Attribute("id").Value == itemValue)\n         .SingleOrDefault().Remove();\n}	0
22983138	22980942	Custom date picker throws exception windows phone	private void LanchDatePicker()\n{\n    datepicker = new CustomDatePicker\n    {\n        IsTabStop = false, \n        MaxHeight = 0,\n        Value = null\n    };\n\n   datepicker.ValueChanged += DatePicker_OnValueChanged;\n   LayoutRoot.Children.Add(datepicker);\n   datepicker.ClickTemplateButton();\n}	0
29036724	29036329	Add items to Bootstrap Dropdown from Code Behind	Repeater1.DataSource = yourdatasource\n    Repeater1.Databind()\n\n\n<asp:Repeater id="Repeater1" runat="server">\n<HeaderTemplate><Ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"></HeaderTemplate>\n<ItemTemplate>\n\n    <li role="presentation">\n        <a role="menuitem" href="#"> <%# Eval("yourfieldfromcodebhind here") %> </a>\n\n    </li>\n</ItemTemplate>\n</asp:Repeater>	0
34529130	34527893	How to get actual position of non-resizeable window using GetWindowRect	[DllImport(@"dwmapi.dll")]\nprivate static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute);\n\npublic static bool GetWindowActualRect(IntPtr handle, out Rect rect) \n{\n const int DWMWA_EXTENDED_FRAME_BOUNDS = 9;\n int result = DwmGetWindowAttribute(handle, DWMWA_EXTENDED_FRAME_BOUNDS, out rect, Marshal.SizeOf(typeof(Rect)));\n\n return result >= 0;\n}	0
22608705	22608458	How to count seconds and then use them in a conditional?	DateTime endTime = DateTime.Now.AddSeconds(2);\nwhile (!Console.KeyAvailable && DateTime.Now < endTime)\n    Thread.Sleep(1);\nif (Console.KeyAvailable)\n{\n    var keyPress = Console.ReadKey();\n    string keyPressString = keyPress.KeyChar.ToString();\n    keyPressString = keyPressString.ToUpper();\n    if (keyPressString == lettersAndChars)\n    {\n        Console.Clear();\n        goto Start;\n    }\n}\nConsole.Clear();\nConsole.WriteLine("Game Over");	0
31467616	31466779	Only last member of a list gives a Rectangle Intersect xna	foreach (Player p in main.initializer.playerlist)\n     {\n        p.intersection = false;\n\n        foreach (Blocks b in main.initializer.blocklist)\n        {\n            if (p.Hitbox.Intersects(b.box))\n                {\n                p.intersection = true;\n                break;  \n                }\n        }\n}	0
1207749	1207685	How do I handle a DBNull DateTime field coming from the SQL Server?	if (!srRow.IsClosed_DateNull())\n{\n  myDate = srRow.Closed_Date;\n}	0
28801401	28800896	Cannot INSERT NULL into Column on Remove	itemXrefSet = db.Set<ItemXref>();\nforeach (var xref in itemsToRemove)\n{\n    itemXrefSet.Remove(xref);\n}\ndb.SaveChanges();	0
28056032	28055874	Possible to convert string date to mysql DateTime?	STR_TO_DATE('2014/24/12 02:50PM', '%Y/%d/%m %h:%i%p')	0
10552098	10552080	Saving a canvas to re use it later on	onDraw()	0
278457	278439	Creating a temporary directory in Windows?	public string GetTemporaryDirectory()\n{\n   string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n   Directory.CreateDirectory(tempDirectory);\n   return tempDirectory;\n}	0
1689422	1689397	How to get cardinal mouse direction from mouse coordinates	int dx = e.X - lastX;\nint dy = e.Y - lastY;\nif(Math.Abs(dx) > Math.Abs(dy))\n  direction = (dx > 0) ? Direction.Right : Direction.Left;\nelse\n  direction = (dy > 0) ? Direction.Down : Direction.Up;	0
33176531	33176461	List index Convert into datatable	DataTable table = (DataTable) L[0];	0
3800807	3800792	Prefix '0' to the int variable which less than '10', How?	string someMethod(int i){\n  return string.Format("{0:d2}", i);\n}	0
25185951	25176528	Trigger an action to start after X milliseconds	await Task.Delay(2000);	0
3602423	3602392	Round Double To Two Decimal Places	double someValue = 2.346;    \nString.Format("{0:0.00}", someValue);	0
7628997	7628960	how to get two column values in a single query using linq to entities	from m in member\nselect new {\n             FULLNAME = String.Concat(m.Firstname+" ", m.secondname)       \n}	0
6874072	6874042	passing data from data set to a dictionary	Dictionary<int, string> dict = data.ToDictionary(e => e.id, e => e.name);	0
18272158	18271848	How to checked or unchecked all parent and child nodes separately by button click	private void ChangeNodesSelection(TreeNodeCollection node,bool doCheck)\n    {\n        foreach (TreeNode n in node)\n        {\n            n.Checked = doCheck;\n            if (n.Nodes.Count > 0)\n            {\n                ChangeNodesSelection(n.Nodes,doCheck);\n            }\n        }\n    }\n\nprivate void UncheckParentNodes(TreeNodeCollection node)\n    {\n        foreach (TreeNode n in node)\n        {\n            if (n.Parent == null && n.Nodes.Count == 0)\n                n.Checked = false;\n        }\n    }	0
10594828	10594743	LinqToXml: parsing to dictionary	var dictionary = doc.Descendants("Place")\n                    .GroupBy(x => (int) x.Attribute("Type"))\n                    .ToDictionary(g => g.Key, g => g.Count());	0
26661005	26660733	How can I take a parameter or call a function which is declared in other braces?	public partial class Form1 : Form\n{\n  private string parameter = null;\n\n  public Form1()\n  {\n    InitializeComponent();\n\n    // ...\n    parameter = abc.ToString();\n  }	0
34062917	34062801	How to simplify return's statement from try-catch	try\n{\n    var metadata = GetMetadata();\n    return metadata ?? _provider.GetLatestMetadata(guid);\n}\ncatch (Exception ex) when ( ex is AuthenticationException\n                            || ex is HttpUnauthorizedRequestException\n                            || ex is WebException\n                            || ex is VcenterException\n                          )\n{\n    return _provider.GetLatestMetadata(guid);\n}	0
8169866	8169838	FileStream (jpeg from pdf converter) to Byte[]	byte[] data = File.ReadAllBytes("path/to/file.jpg")	0
7240956	7240709	How to check if window is opned and close it	var f1=Application.OpenForms["ErrorForm"];       \nif(f1!=null) \n  f1.Close(); \n\nf1=  new ErrorForm(Errors);\nf1.Show();	0
11673130	11673113	Find position of tags in string	int position = yourString.IndexOf('test');	0
19915604	19893407	String to decimal conversion: dot separation instead of comma	mystring.Replace(".", ",");	0
32732668	32732197	Filtering DataGridView over two columns in one textbox	dataGridViewPerson.DataSource = listPerson.ToList().Where(x => (x.name + " " + x.surname)\n                                                   .Contains(textBoxSearch.Text)).ToList();	0
18735663	18735592	Connection to CRM Sql Server	string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";\n\nusing(SqlConnection _con = new SqlConnection(connectionString))\n{\n   string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";\n\n   using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))\n   {\n      DataTable customerTable = new DataTable("Top5Customers");\n\n      SqlDataAdapter _dap = new SqlDataAdapter(_cmd);\n\n      _con.Open();\n      _dap.Fill(customerTable);\n      _con.Close():\n\n   }\n}	0
22272099	22271674	Change several fields in Array	List<byte> bList = arr.ToList();\n    // ...do your changes and inserts...\n    arr = bList.ToArray<byte>();	0
3204954	3200875	How to instantiate PrivateType of inner private class	var parentType = typeof(DailyStat);\nvar keyType = parentType.GetNestedType("DailyKeyStat", BindingFlags.NonPublic); \n//edited to use GetNestedType instead of just NestedType\n\nvar privateKeyInstance = new PrivateObject(Activator.CreateInstance(keyType, true));\n\nprivateKeyInstance.SetProperty("Date", DateTime.Now);\nprivateKeyInstance.SetProperty("Type", StatType.Foo);\n\nvar hashCode = (int)privateKeyInstance.Invoke("GetHashCode", null);	0
882518	882407	How to add an attribute to a serialized XML node?	[XmlRoot("floors")]\npublic class FloorCollection\n{\n    [XmlAttribute("type")]\n    public string Type { get; set; }\n    [XmlElement("floor")]\n    public Floor[] Floors { get; set; }\n\n}	0
12769706	12766216	Keep openning OpenFileDialog until selecting valid file	OpenFileDialog dialog = new OpenFileDialog();\n        dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";\n        dialog.FileOk += delegate(object s, CancelEventArgs ev) {\n            var size = new FileInfo(dialog.FileName).Length;\n            if (size > 250000) {\n                MessageBox.Show("Sorry, file is too large");\n                ev.Cancel = true;             // <== here\n            }\n        };\n        if (dialog.ShowDialog() == DialogResult.OK) {\n            MessageBox.Show(dialog.FileName + " selected");\n        }	0
23806605	23806210	How to use Any between two ienumerables	var currentportFrom = tms.TMSSwitchPorts\n                 .Where(a => a.SwitchID == fromID)\n                 .Select(a2 => a2.PortNumber)\n                 .ToList();\nvar currentportTo = tms.TMSSwitchPorts\n                 .Where(a => a.SwitchID == fromID)\n                 .Select(a2 => a2.PortNumber)\n                 .ToList();\n\nif(currentportFrom.Any(cp => currentportTo.Contains(cp))\n{\n    //do something\n}	0
11363071	11362600	C# Best way to retrieve strings that's in quotation mark?	public static string[] ExtractNumbers(string[] originalCodeLines)\n    {\n        List<string> extractedNumbers = new List<string>();\n\n        string[] codeLineElements = originalCodeLines[0].Split('"');\n        foreach (string element in codeLineElements)\n        {\n            int result = 0;\n            if (int.TryParse(element, out result))\n            {\n                extractedNumbers.Add(element);\n            }\n        }\n\n        return extractedNumbers.ToArray();\n    }	0
4365094	4364770	Getting a string from a resource file in an untyped manner	var Translations = new ResourceManager("MyResources", \n    Assembly.GetExecutingAssembly())\n        .GetResourceSet(CultureInfo.CurrentCulture, false, true)\n        .Cast<DictionaryEntry>()\n        .Where(e => e.Value is string)\n        .ToDictionary(e => e.Key, e => (string) e.Value);\n\nvar result = Translations["TranslateThisKey"];	0
5644534	5593444	Pause & Resume live video capture from webcam using DirectX.capture	1) When i paused a file say test.avi was generated.\n2) when i resumed i renamed test to test1.avi and created new test.avi \nfile and merged them when user clicks on stop.	0
8459825	8458249	WP7 - InvalidOperationException while playing sound	The Stream object must point to the head of a valid PCM wave file. Also, this wave file must be in the RIFF bitstream format.\n\nThe audio format has the following restrictions:\n\n    Must be a PCM wave file\n    Can only be mono or stereo\n    Must be 8 or 16 bit\n    Sample rate must be between 8,000 Hz and 48,000 Hz	0
4043320	4043302	Possible to make a global Var. C#	public static class Globals\n{\n    public static string Foo;\n}	0
20218543	20218409	subquery in LINQ for Update	var obj = this.context.bikes.SingleOrDefault(x => x.id == id);\n// check if the obj is not null. \nif(obj!=null)\n{\n    obj.name = name;\n    // I suppose that each bike has a unique type. Hence, I am not using the \n    // SingleOrDefault() and then checking if the result is null.\n    obj.bike_type = this.context.type_bike\n                        .Where(x=> x.id == id)\n                        .Select(q=>q.name)\n                        .Single();\n    obj.bike_type_id = typeBike;          \n    this.context.SubmitChanges(); \n}	0
12842625	12841979	How to set ticks between ticks in TeecChart	tChart1.Axes.Bottom.MinorTickCount = 10;	0
22013458	22013101	Problems with randomizing a list	x < RNG.Next(52)	0
17875638	17875519	Sql data reader wont return my values to objects	protected void findAffectedUserButton_Click(object sender, EventArgs e)\n{\n    ticket.AffectedUser = affectedUserTextBox.Text;\n    ticket.SearchAffectedUser();\n    firstNameValueLabel.Text = ticket.FirstName;\n    middleNameValueLabel.Text = ticket.MiddleName;\n    lastNameValueLabel.Text = ticket.LastName;\n    emailValueLabel.Text = ticket.Email;\n\n}	0
16402626	16402484	how to automatically convert a web address into a hyperlink when binding to asp.net control	myValue.Contains("http") ? "<a href='" + myValue + "'>" + myValue + "</a>" : myvalue;	0
17368467	17367408	How to preserve formatting of textshape format of powerpoint slide using c#	With Shape.TextFrame.TextRange\n  .Replace "this text", "with this text"\nEnd With	0
19020154	19019620	Get End Time from Start Time and Duration	//assuming that you have a validation for your startTime that this will always on this format "HH:mm:ss"\nprivate static string GetEndTime(string startTime, int duration, DayOfWeek dayOfWeek)\n{\n    DateTime startDateTime = DateTime.Parse(startTime);\n    DateTime endDateTime = startDateTime.AddHours(duration);\n\n    return endDateTime.ToString("HH:mm:ss");\n}\n\nprivate static DayOfWeek GetEndDay(int duration, DayOfWeek dayOfWeek)\n{\n    int days = duration / 24;\n    DayOfWeek endDay = dayOfWeek + days;\n\n    return endDay;\n}\n\nstatic void Main()\n{\n    string testStartTime = "00:00:00";\n    DayOfWeek startDay = DayOfWeek.Sunday;\n    int duration = 48;\n\n    string endTime = GetEndTime(testStartTime, duration, startDay);\n    DayOfWeek endDay = GetEndDay(duration, startDay);\n    Console.WriteLine("End Time is {0} hours on {1}", endTime, endDay.ToString());\n\n}	0
18113064	18113016	Entity Framework Distinct records from multiple tables	var distinctValues = (from a in dataContext.A_Table\n                      join b in dataContext.B_Table\n                      on a.EmpID equals b.EmpID\n                      join c in dataContext.C_Table\n                      on b.SomeID equals c.ID\n                      where a.IsActive == true\n                      && a.ID == id\n                      select new NewClass()\n                      {\n                          ID = c.ID,\n                          Name = c.Name\n                      }).ToList()\n                      .GroupBy(x=>new {ID = x.ID,Name = x.Name})\n                      .Select(x=>new {ID = x.Key.ID,Name = x.Key.Name});	0
33598409	33598324	Join multiple orderedDictionary In c#	var dictionariesMerged = ticketToPickerMapForVerifiedTab.Cast<DictionaryEntry>()\n    .Union(ticketToPickerMapForHVTab.Cast<DictionaryEntry>())\n    .Union(ticketToPickerMapForKPTab.Cast<DictionaryEntry>());\n\nvar dictionary = new OrderedDictionary();\n\nforeach (DictionaryEntry tuple in dictionariesMerged)\n    dictionary.Add(tuple.Key, tuple.Value);	0
6572606	6572457	How to grab an image and save it in a folder [c# windows application]	Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Size.Width, Screen.PrimaryScreen.Bounds.Size.Height);\nGraphics g = Graphics.FromImage(bmp);\ng.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);\ng.Save();\nbmp.Save("D:\\file.jpg", ImageFormat.Bmp);	0
2816445	2816398	Select more then one node from XML using LINQ	var elements = \n    from element in xml.Root.Elements()\n    where element.Name == "content" ||\n          element.Name == "index"\n    select element;\nvar newContentNode = new XElement("content", elements);	0
22965557	22965263	How to access the root objects of my ViewModel from within an EditorFor?	public class TransportViewModel  \n{\n    public List<WheelProperty> WheelPropertyList {get;set;}\n    ...\n}\n\npublic class WheelProperty\n{\n    public TransportViewModel TransportView {get;set;}\n    public string PropertyA {get;set;}\n    public string PropertyB {get;set;}\n    ...\n}	0
10396678	10396612	extract variables and values from http post / string c#	// just use 'theResponse' here instead\nvar xml = "<callback variable1=\"foo1\" variable2=\"foo2\" variable3=\"foo3\" />";\n\n// once inside an XElement you can get all the values\nvar ele = XElement.Parse(xml);\n\n// an example of getting the attributes out\nvar values = ele.Attributes().Select(att => new { Name = att.Name, Value = att.Value });\n\n// or print them\nforeach (var attr in ele.Attributes())\n{\n    Console.WriteLine("{0} - {1}", attr.Name, attr.Value);\n}	0
15920959	15920915	Convert 12hr Time String to DateTime object	DateTime result;\nif (DateTime.TryParseExact(text, "hh:mmtt", CultureInfo.InvariantCulture,\n                           DateTimeStyles.None, out result))\n{\n    Console.WriteLine("Parsed to: {0}", result);\n}	0
13959705	13957362	C/C++ Interoperability Naming Conventions with C#	_int32 DWORD	0
26358389	26356306	Is it right to add c# windows exe as reference in another c# winform?	ClassLibrary1, Version=1.2.3.4, Culture=neutral, PublicKeyToken=b77a5c561934e089	0
3660178	3660110	Selecting rows with distinct column values using LINQ	var designations = (from SPListItem employee in employees\n                    select employee["Employee Designation"].ToString())\n                   .Distinct()\n                   .ToList();	0
3726905	3723525	NHibernate creating a proxy instance failed due to abstract method	protected internal abstract	0
21541023	21527243	Unit Test to ensure only selected HTTP verbs are applicable to WebAPI	var config = new HttpConfiguration();\n\nconfig.Routes.MapHttpRoute(\n        name: "DefaultApi",\n        routeTemplate: "api/{controller}/{id}",\n        defaults: new { id = RouteParameter.Optional }\n    );\n\nIApiExplorer explorer = config.Services.GetApiExplorer();\n\nvar apiDescs = explorer.ApiDescriptions;	0
14282875	14282774	Writing Date Value	Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");\nConsole.WriteLine(dateToDisplay.ToString("MMddyyyy"));	0
22324541	22324507	create json array in c#	dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");\n\nstring name = stuff.Name;\nstring address = stuff.Address.City;	0
16324320	16324201	Piping (multiple) expressions in RegEx	TEST009 Flag1\ndef345 FLAG1\nzxy789     Flag1	0
10142501	10142289	How can I change the size of font in texbox in ultratoolbarsmanager, using Infragistics?	textBoxTool1.InstanceProps.Width = 114;	0
44810	44787	How do you get the current image name from an ASP.Net website?	int num = 1;\n\nif(Session["ImageNumber"] != null)\n{\n  num = Convert.ToInt32(Session["ImageNumber"]) + 1;\n}\n\nSession["ImageNumber"] = num;	0
15251333	15251143	Hiding XElement nodes with no data	public void AddIfValid(XElement root, string tagName, string value, string excludeValue)\n{\n    if (value != excludeValue)\n        root.Add(new XElement(tagName, value);\n}	0
18193730	18193319	changing webservice calls to test or prod via radio button	npfunctions.finfunctions service = new npfunctions.finfunctions();\nif (TestBtn.Checked == true)\n{\n    service.url="<testurl>";\n}\nelse\n{\n  service.url="<produrl>";\n}\n    Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());	0
12492255	12492209	Gridview row with dropdownlist	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType != DataControlRowType.Header)\n    {\n        for (int i = 0; i < e.Row.Cells.Count; i++)\n        {\n           DropDownList ddl = new DropDownList();\n           ddl.DataSource = getImpacts();\n           ddl.DataBind();\n           e.Row.Cells[i].Controls.Add(ddl);\n        }\n    }\n}	0
13208498	13208457	allow only distinct values in ComboBox	for (int intCount = 0; intCount < ds.Tables[0].Rows.Count; intCount++)\n{\n     var val=ds.Tables[0].Rows[intCount][value].ToString();\n\n     //check if it already exists\n     if(!cmb.Items.Contains(val))\n     {\n            cmb.Items.Add(val);\n     }\n}	0
27835374	27835301	read the content of file by getting it from dll	public static string GetResourceFileContentAsString(string fileName)\n    {\n        var assembly = Assembly.GetExecutingAssembly();\n        var resourceName = "Your.Namespace." + fileName;\n\n        string resource = null;\n        using (Stream stream = assembly.GetManifestResourceStream(resourceName))\n        {\n            using (StreamReader reader = new StreamReader(stream))\n            {\n                resource = reader.ReadToEnd();\n            }\n        }\n        return resource;\n    }	0
33260137	33259175	Add a symbol to a .docx file	char tick = (char) 252;\n\np.Append("Hello World").Append(tick).Font(new FontFamily("Wingdings"));	0
1848559	1848540	How to use console output in an ASP.NET environment?	Debug.Write()	0
30046063	30045914	Can't get the text value of linkbutton in gridview	LinkButton uList = (LinkButton)gvDealerSupportMail.Rows[rowValue].FindControl("userList");\nstring test = uList.Text;	0
34308764	34308141	How to get specific part of webpage in mvc?	public string GetContent(string url)\n    {\n\n        HtmlWeb hw = new HtmlWeb();\n        HtmlDocument doc = hw.Load(url);\n        HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@id='t1']");\n\n        return node.InnerHtml;\n    }	0
2363364	2363117	Shutdown WPF application after n seconds of inactivity	public partial class Window1 : Window {\n    DispatcherTimer mIdle;\n    private const long cIdleSeconds = 3;\n    public Window1() {\n      InitializeComponent();\n      InputManager.Current.PreProcessInput += Idle_PreProcessInput;\n      mIdle = new DispatcherTimer();\n      mIdle.Interval = new TimeSpan(cIdleSeconds * 1000 * 10000);\n      mIdle.IsEnabled = true;\n      mIdle.Tick += Idle_Tick;\n    }\n\n    void Idle_Tick(object sender, EventArgs e) {\n      this.Close();\n    }\n\n    void Idle_PreProcessInput(object sender, PreProcessInputEventArgs e) {\n      mIdle.IsEnabled = false;\n      mIdle.IsEnabled = true;\n    }\n  }	0
19633795	19633466	Loop through HTML with tags from string	HtmlDocument doc = new HtmlDocument();\n doc.Load("file.htm");\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n {\n    HtmlAttribute att = link["href"];\n    // DO SOMETHING WITH THE LINK HERE\n }\n doc.Save("file.htm");	0
21542467	21542144	Naive Gravity for Tetris game using 2D Array for the playfield	int k = 0;\nfor(int iy = 9; iy >= 0; iy--) {\n    if(!_linesToClear.Contains(iy)) {\n        for(int ix = 0; ix < 6; ix++) {\n            _playfield[iy + k][ix] = _playfield[iy][ix];\n        }\n    }\n    else\n        k++;\n}	0
1871797	1871736	How to customize datetime format or to convert DateTime to String with required format	string FormatDateTime(string dateString) {\n    DateTime dt = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);\n    return dt.ToString("MM/dd/yyyy HH:mm:ss");\n}	0
3256228	3250852	Extend UIButton in monotouch	class MyButton : UIButton\n{\npublic MyButton(RectangleF rect) : base(rect) {}\n\nstatic MyButton FromType(UIButtonType buttonType)\n{\n    var b = new MyButton (new RectangleF(0, 0, 200, 40));\n    b.SetTitle("My Button",UIControlState.Normal);\n\n    //additional customization here\n\n    return b;\n    }\n}	0
8664189	8664157	C# SQL stored procedure (which inserts) - pass parameters and retrieve parameter	connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]); \nsql = "aStoredProc"; \ncommand = new SqlCommand(sql, connection); \ncommand.CommandType = CommandType.StoredProcedure; \ncommand.Parameter.Add(new SqlParameter("@FirstName", SqlDbType.VarChar)).Value = sFirstname; \ncommand.Parameter.Add(new SqlParameter("@SurName", SqlDbType.VarChar)).Value = sSurname; \ncommand.Parameter.Add(new SqlParameter("@SurName", SqlDbType.VarChar)).Value = sSurname; \nSqlParameter ParamId = cmd.Parameters.Add( "@Id", SqlDbType.Int);\ncommand.Direction = ParameterDirection.InputOutput;\ncommand.Parameter.Add(ParamId);\nconnection.Open();  \ncommand.ExecuteNonQuery(); \nint ID = ParamId.Value;\nconnection.Close();	0
26196380	26196335	c# Listitems dont add if exisit in array	var days = new List<ViewModels.Day>()\n{\n daySunday,\n dayMonday,\n dayTuesday,\n dayWednesday,\n dayThursday,\n dayFriday,\n daySaturday\n};\n\nmodel.ScheduleHiddenDays = days.Where(x => !hDays.Contains(x.Id)).ToList();	0
15294642	15294499	C# failing to set property inside IEnumerable	var objects = GetObjectsFromApiCall().ToList();	0
30680830	30679792	Application keep Alive in Shared Hosting , No Access to IIS Manager	private static void _SetupRefreshJob()\n{\n   //remove a previous job\n   Action remove = HttpContext.Current.Cache["Refresh"] as Action;\n   if (remove is Action)\n   {\n       HttpContext.Current.Cache.Remove("Refresh");\n       remove.EndInvoke(null);\n   }\n   //get the worker\n   Action work = () =>\n   {\n       while (true)\n        {\n          Thread.Sleep(60000);\n          WebClient refresh = new WebClient();\n          try\n          {\n           refresh.UploadString("http://www.websitename.com/", string.Empty);\n          }\n          catch (Exception ex)\n          {\n                    //snip...\n          }\n          finally\n          {\n            refresh.Dispose();\n          }\n      }\n  };\n  work.BeginInvoke(null, null);\n\n  //add this job to the cache\n  HttpContext.Current.Cache.Add(\n  "Refresh",\n  work,\n  null,\n  Cache.NoAbsoluteExpiration,\n  Cache.NoSlidingExpiration,\n  CacheItemPriority.Normal,\n  (s, o, r) => { _SetupRefreshJob(); }\n  );\n}	0
7931465	7930202	can't figure out how to return the selected row of grid in ModalDialog	myGrid.GetRowValues(myGrid.GetFocusedRowIndex(), 'column1;column2;columnN', ProcessRowValues);\n\nfunction ProcessRowValues(values) {\n    alert('column1.value=' + values[0]);\n    alert('column2.value=' + values[1]);\n}	0
33969424	33969202	Split special string in c#	string s1 = "/TEST/TEST123";\n    string s2 = "/TEST1/Test/Test/Test/";\n    string s3 = "/Text/12121/1212/";\n    string s4 = "/121212121/asdfasdf/";\n    string s5 = "12345";\n\n    string pattern = @"\/?[a-zA-Z0-9]+\/?";\n\n    Console.WriteLine(Regex.Matches(s1, pattern)[0]);\n    Console.WriteLine(Regex.Matches(s2, pattern)[0]);\n    Console.WriteLine(Regex.Matches(s3, pattern)[0]);\n    Console.WriteLine(Regex.Matches(s4, pattern)[0]);\n    Console.WriteLine(Regex.Matches(s5, pattern)[0]);	0
19339264	19339178	How to pass the address of a managed object to an unmanaged event handler?	Dictionary<int, MyCustomObject>	0
5821018	5820795	how can I prevent my custom element from getting its own div?	protected override HtmlTextWriterTag TagKey\n {\n     get \n     {\n          // return elmement that you would like  HtmlTextWriterTag.Span for instance.\n     }\n }	0
18784001	18783856	Get full byte array from bytes received from websocket	byte[] completeBuffer;\n\n        using(MemoryStream memStream = new MemoryStream())\n        {\n            while (true) // Until closed and ReadAsync fails.\n            {\n                int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);\n                if(read == 0)\n                    break;\n\n                memStream.Write(readBuffer, 0, read);\n                bytesReceived += read;\n\n            }\n\n            completeBuffer = memStream.ToArray();\n        }\n\n        // TODO: do anything here with completeBuffer	0
17222804	17219318	Building Jagged Tree With Parentless Nodes In C#	List<List<GroupItem>> resultList = ...\n\nvar roots = new List<GroupItem>();\n\nICollection<GroupItem> parentLevel = roots;\nforeach (var nodeLevel in resultList.AsEnumerable().Reverse())\n{\n    //Find each parent's child nodes:\n    foreach (var parent in parentLevel)\n    {\n        parent.Items = nodeLevel.Where(node => node.ParentCode == parent.ItemCode)\n                                .Cast<SelectableItem>().ToList();\n    }\n\n    //Add parentless nodes to the root:\n    roots.AddRange(nodeLevel.Where(node => node.ParentCode == null));\n\n    //Prepare to move to the next level:\n    parentLevel = nodeLevel;\n}	0
20455517	20455432	how to bind combobox values from sql server 2008	comboBox_city.Items.Insert(0,new ListItem("---Select---",""));	0
12805350	12805287	Is it possible to use OfType in a linq where?	var accountSources = db.Sources.OfType<AccountSource>();\nvar actionItemStates = accountSources.SelectMany(a => a.ActionItemStates);	0
31670874	31668121	How to set a gameobject to an exact length in unity	public void newScale(GameObject theGameObject, float newSize) {\n\n    float size = theGameObject.GetComponent<Renderer> ().bounds.size.y;\n\n    Vector3 rescale = theGameObject.transform.localScale;\n\n    rescale.y = newSize * rescale.y / size;\n\n    theGameObject.transform.localScale = rescale;\n\n}	0
23809518	23809255	Stored procedure access from form	command.CommandType = CommandType.StoredProcedure;	0
4110815	4110734	hiding columns of a datagrid (asp.net/c#)	Private Sub setPrinterView()\n  For Each tr As TableRow In DirectCast(Me.GridView1.Controls(0), Table).Rows\n      For i As Int32 = 1 To 4\n          If tr.Cells.Count - i < 0 Then Exit For\n          tr.Cells(tr.Cells.Count - i).Visible = False\n      Next\n   Next\nEnd Sub	0
15652088	15543313	Excel file with openxml with multiple sheets in single workbook	// Open the document for editing.\nusing (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) \n{\n\n   // Insert code here.\n\n}	0
27308004	27307708	How do I get XML from a Webservice?	DataSet ds = new DataSet();\nds.ReadXml(new StringReader(wet.GetCitiesByCountry("United Kingdom")));	0
28054184	28054140	LINQ to create list of strings from indexes stored in int[]	List<string> result = indexes.Select(i => words[i]).ToList();	0
14626943	14626916	Unique values of old list	var unique = oldList.Except(newList);	0
19226056	19225923	How to group a list of lists into repeated items	var results = ItemList.SelectMany(i => i.subItems).GroupBy(i => i.subItemGroup);	0
4321670	4321554	Using Late-Binding to Automate Word is throwing a MissingMemberException	object appClass = Marshal.GetActiveObject("Word.Application");\n        object documents = appClass.GetType().InvokeMember("Documents", BindingFlags.GetProperty, null, appClass, null);\n        object count = documents.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, documents, null);	0
5280592	5255212	How to pass parameters to crystal report?	objRpt.SetParameterValue(0, Convert.ToInt32(Request.QueryString["Cheque_IssueRecord_Secretary_Review_TT_ID"]));\n            objRpt.SetParameterValue(1, Request.QueryString["tCOMDB"]);\n\n            //The viewer's reportsource must be set to a report before any parameter fields can be accessed.\n            CrystalReportViewer1.ReportSource = objRpt;	0
2807719	2058093	C# Application Becomes Slow and Unresponsive as String in Multiline Textbox Grows	TextBox.AppendText()	0
16171836	16168077	Update content depending on string in view model	return View("Index", NewUserListModel(input));	0
1668371	1668353	How can I generate a cryptographically secure pseudorandom number in C#?	using System.Security.Cryptography;\n...\nRandomNumberGenerator rng = new RNGCryptoServiceProvider();\nbyte[] tokenData = new byte[32];\nrng.GetBytes(tokenData);\n\nstring token = Convert.ToBase64String(tokenData);	0
8574672	8574607	How change file coding from windows-1251 to utf-8	string text = File.ReadAllText(path, Encoding.GetEncoding("windows-1251"));\n XDocument documentcode = XDocument.Parse(text);  // not load.	0
15300643	15280599	Windows 8 Metro App File Share Access	WCF Web Service	0
6329434	6329356	Issue in exporting data to CSV	asdasd,"-A1177",11/03/1984	0
29418965	29418853	Convert decimal numbers from string to double	lines.Select(x => double.Parse(x, CultureInfo.InvariantCulture)).ToArray();	0
4469407	4469392	Passing string parameter with alphabetic characters to a javascript function as argument fails	string.Format("javascript:OpenNewsletter1({0}, '{1}')",\n    reader.GetInt("Id").ToString(),\n    HttpUtility.HtmlEncode("dcsfs"))	0
29349135	29340364	CRM Custom Action Parameter	OrganizationRequest request = new OrganizationRequest("ise_account_newinvoice_")\nrequest.Parameters.Add("Target", xAccountReference);\nrequest.Parameters.Add("invoicenumber", strInvoiceNumber);\n\nOrganizationResponse xResponse = orgSvcContext.Execute(request);	0
8023136	8023021	run c# app from network share	caspol -machine -addfulltrust program.exe	0
4472491	4472462	Convert imageUrl to byte[] for caching	byte[] image = (new WebClient()).DownloadData(imgPhoto.ImageUrl);	0
12805721	12805142	Message Box to contain Table in C#	Window1 win = new Window1(new List<string> { "john", "susan" });\nwin.ShowDialog();\n\npublic Window1(IEnumerable<string> names)\n{\n    Names = names;\n    InitializeComponent();\n}\npublic IEnumerable<string> Names { get; private set; }\n\n<Window x:Class="ListViewUpdate.Window1"\n        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n        DataContext="{Binding RelativeSource={RelativeSource self}}"\n        Title="Window1" Height="300" Width="300">\n<Grid>\n    <ListView ItemsSource="{Binding Path=Names}" />\n</Grid>\n</Window>	0
13935315	13935188	Accessing Properties or a Parent Class from Base	public class BaseModel\n{\n    protected string TableName { get; set; }\n\n    public BaseModel()\n    {         \n    }\n\n    public abstract void Save();\n}	0
23373540	23368799	How to not let any mouse/cursor to enter the window in WPF	private void Form1_MouseEnter(object sender, EventArgs e)\n    {\n        Cursor.Position = new Point(this.Location.X - 1, this.Location.Y - 1);\n    }	0
461105	461098	Leading Zero Date Format C#	return dateTimeValue.ToString("MM-dd-yyyy");	0
14978508	14977977	how to hide Gridview row values in asp.net	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (...){\n            //hide controls\n            foreach (Control c in e.Row.Controls)\n            {\n                 c.Visible=false;\n            }\n            //change color\n            e.Row.Style.Add("background-color","red");\n        }\n    }	0
1844041	1844029	WPF - Is it possible to negate the result of a data binding expression?	public class NegatingConverter : IValueConverter\n{\n  public object Convert(object value, ...)\n  {\n    return !((bool)value);\n  }\n}	0
12388515	12388468	Insert more than one row in database at the same time c#	SqlConnection connection = new SqlConnection(...);\nconnection.Open();\n\nSqlCommand command = new SqlCommand(...);\ncommand.Connection = connection;\ncommand.ExecuteNonQuery();	0
22998157	22997616	Displaying database details on a datagrid	// Assumes that connection is a valid SqlConnection object.\nstring queryString = \n  "SELECT CustomerID, CompanyName FROM dbo.Customers";\nSqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);\n\nDataSet customers = new DataSet();\nadapter.Fill(customers, "Customers");	0
11475159	11474643	Building an OrderBy Lambda expression based on child entity's property	var sortOn = "Category.Description";\nvar param = Expression.Parameter(typeof(Product), "p");\nvar parts = sortOn.Split('.');\n\nExpression parent = param;\n\nforeach (var part in parts)\n{\n    parent = Expression.Property(parent, part);\n}\n\nvar sortExpression = Expression.Lambda<Func<Product, object>>(parent, param);	0
10108194	9146298	SLXNA plus Accelerometer causing screen to rotate during gamplay, solutions?	protected virtual void OnOrientationChanged(\nOrientationChangedEventArgs e\n)	0
28505907	28504772	change logfile name dynamically in app.config	var path = Path.GetDirectoryName(logFile);\nvar fileName = Path.GetFileNameWithoutExtension(configFile);\nvar todayFileName = fileName + DateTime.Now.ToString("_yyyy_MM_dd");\nvar ext = Path.GetExtension(configFile);\nvar newLogFile = path + todayFileName + ext;	0
8390568	8390543	how can i drag a 2d level array from a txt file	0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0\n0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0\n0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0\n0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0\n0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0\n0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0\n0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0\n0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0\n0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0\n0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0\n0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0\n0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0\n0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0\n0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0\n0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0\n0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1	0
2239060	2238862	Filtering Active Directory Users in Alphabetical Order	(&(objectClass=user)(objectCategory=person)(cn>='a')(cn<='b'))	0
11534297	11534226	Mimic Peripheral behavior using a programming language	[DllImport("user32.dll", EntryPoint="SendInput", SetLastError=true)]\ninternal static extern int SendMouseInput(int cInputs, ref MOUSEINPUT pInputs, int cbSize);\n\n[DllImport("user32.dll", EntryPoint="SendInput", SetLastError=true)]\ninternal static extern int SendKeyboardInput(int cInputs, ref KEYBDINPUT pInputs, int cbSize);	0
10805149	10804784	Can you disable the click of an Ajax accordion in C#?	ajaxaccordionPane1.Visible = false;	0
3054128	3054093	How can i do re coding without assign null value?	static void Main(string[] args)\n    {\n        FileInfo f = new FileInfo("C:/temp/Arungg.txt");\n\n        StreamWriter Tex = f.Exists ? f.AppendText() : f.CreateText();\n\n        Tex.WriteLine("Test1");\n        Tex.WriteLine("Test2");\n        Tex.Write(Tex.NewLine);\n        Tex.Close();\n\n        Console.WriteLine(" The Text file named Arungg is created ");\n    }	0
11562186	11556410	How can i call dynamic object like a function?	public static dynamic Display;\nvoid Main()\n{\n        Display = new MyCallableObject();\n\n        //this is what i was after\n        Console.Write(Display("bla bla bla"));     \n} \n\npublic class MyCallableObject:DynamicObject\n{\n     public override bool TryInvoke(InvokeBinder binder, object[] args, out Object result)\n     {\n        result = string.Format("This is response for {0}",args.FirstOrDefault());\n        return true;\n     }\n}	0
20200171	20200095	How to add to specific listview column	lvi.SubItems.Add(item1);\n\nlvi.SubItems.Add(string.Empty); // skip Percent column\n\nlvi.SubItems.Add(item2);	0
17295810	17294807	Comapring Decimal with zero in if Statement?	if (payRoll.DeductedTax == 0)	0
29961286	29961188	Viewstate set Property value	set\n    {\n       ViewState["TransactionData"] = value;\n       gridview.DataSource = value as List<TransactionEntity>; //check if null etc \n       gridview.DataBind();// ...               \n    }	0
14820966	14820818	extracting list of longs from database	var TheData = MyDC.Table\n                  .Where(...)\n// optionally     .Select(l => new { l.StringOfLongs, l.SomeObjectProp })\n                  .AsEnumerable() // move execution to memory\n                  .Select(l => new Model() {\n                      TheListOfLongs = l.StringOfLongs.Split(',')\n                                        .Select(x => Int64.Parse(x))\n                                        .ToList(),\n                      SomeObjectProp = l.SomeObjectProp\n                  }).ToList();	0
2133926	2133879	C# using static variable as parameter to DeploymentItem	Path.Combine	0
31729221	31729034	Settings control position at runtime from name	Control x = this.Controls.Find(controlName, true).FirstOrDefault();\n\nif (x != null)  \n    x.Location = new Point(xCoord, yCoord);	0
17554541	17549453	How to save image using JpegBitmapEncoder	private void SaveImage(string path)\n{\n    var jpegEncoder = new JpegBitmapEncoder();\n    jpegEncoder.Frames.Add(BitmapFrame.Create(colorImageWritableBitmap));\n    using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))\n    {\n        jpegEncoder.Save(fs);\n    }\n}	0
5065179	5065130	How do i show enum values in a combo-box?	cbState.DataSource = Enum.GetNames(typeof(caseState));	0
5092231	5092174	Get Item[i] from listview	public delegate string getCurrentItemCallBack (int location);\n\n...\n\nprivate string GetCurrentItem(int location)\n{\n   if (this.listViewModels.InvokeRequired)\n      {\n       getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem);\n       return this.Invoke(d, new object[] { location });\n      }\n      else\n      {\n       return this.listViewModels.Items[location].ToString();\n      }\n}	0
23985363	23985294	Why I can't convert a byte[2] array to int with BitConverter?	int value = (buf[0] << 2) | (buf[1] >> 6);	0
4679146	4678882	How do I write context/specification style unit tests with an MSText/xUnit framework?	[TestClass]\npublic class when_i_add_two_numbers : with_calculator\n{\n    public override void When()\n    {\n        this.calc.Add(2, 4);\n    }\n\n    [TestMethod]\n    public void ThenItShouldDisplay6()\n    {\n        Assert.AreEqual(6, this.calc.Result);\n    }\n\n    [TestMethod]\n    public void ThenTheCalculatorShouldNotBeNull()\n    {\n        Assert.IsNotNull(this.calc);\n    }\n}\n\npublic abstract class with_calculator : SpecificationContext\n{\n    protected Calculator calc;\n\n    public override void Given()\n    {\n        this.calc = new Calculator();\n    }\n}\n\npublic abstract class SpecificationContext\n{\n    [TestInitialize]\n    public void Init()\n    {\n        this.Given();\n        this.When();\n    }\n\n    public virtual void Given(){}\n    public virtual void When(){}\n}\n\npublic class Calculator\n{\n    public int Result { get; private set; }\n    public void Add(int p, int p_2)\n    {\n        this.Result = p + p_2;\n    }\n}	0
19919408	19919371	Parsing date after calling sp in asp.net	dia.DataTextFormatString = "{0:dd/MM/yyyy}";	0
15763599	15763459	C# WinForms - Adding text to each line in a textbox	var list = new List<string>(textBox1.Lines);\n\nfor (int i = 0; i < list.Count; ++i)\n{\n  list[i] = "A" + list[i] + "B";\n}\n\ntextBox1.Lines = list.ToArray();	0
4361759	4361746	ExecuteScalar missing Assembly Reference	using System.Data.SqlClient;\n....\nvar command = new SqlCommand();\ncommand.ExecuteScalar();	0
15439510	15439363	How to get 'ReadOnly' or 'WriteOnly' properties from a class?	PropertyInfo[] myProperties = c.GetType().GetProperties(BindingFlags.Public |\n                                                    BindingFlags.SetProperty |\n                                                    BindingFlags.Instance);\n\nforeach (PropertyInfo item in myProperties)\n{\n    if (item.CanRead)\n        Console.Write("Can read");\n\n    if (item.CanWrite)\n        Console.Write("Can write");\n}	0
21457035	21455358	How to search in subcategories by giving a 'head' category in MVC4	var results = context.ExecuteStoreQuery<Product>("exec MySearchStoredProc").ToList();	0
310955	310062	WCF Web Service: Upload a file, Process that file, Download that processed file back	[ServiceContract]\npublic interface IFileService\n{\n  [OperationContract]\n  byte[] ProcessFile(byte[] FileData);\n}	0
29859671	29859615	Writing to user defined XML file	SaveFileDialog fdgSave= new SaveFileDialog(); \nfdgSave.InitialDirectory = Convert.ToString(Directory.GetCurrentDirectory()); \nfdgSave.Filter = "XML (*.XML)|*.xml|All Files (*.*)|*.*" ; \nfdgSave.FilterIndex = 1; \n\nif(fdgSave.ShowDialog() == DialogResult.OK) \n{ \n    Console.WriteLine(fdgSave.FileName);//Do what you want here\n}	0
20385806	20384992	Extracting a specific column from a csv file	private bool SomeMethod(String path, String id)\n{\n    string [] column ;\n\n    foreach (string line in File.ReadLines(Path))\n    {  \n        column = line.Split(',');\n\n        //check that there are at least 5 columns before comparing it with ID\n        if ((column.Length >= 5) && (id == column[4]))\n        {\n            return false;\n        }\n    }\n}	0
26433803	26433723	Converting an xml into list of anonymous object	var listOfLanguages = xDoc.Descendants("LanguageList").Descendants()\n                          .Select(l => new\n                          {\n                              Name = l.Attribute("name").Value,\n                              Code = l.Attribute("code").Value\n                          });	0
15709794	15709721	Upload a file to specific folder in windows forms and upload file name to sql server	File.OpenRead()	0
23211805	23077012	Keep a reference to objects passed to a UserControl	Label="{Binding RoundButtons[3].Label}"\nVisibility="{Binding RoundButtons[3].VisibilityState, FallbackValue=Visible}"	0
31949510	31949093	Using c# to set the source of a mediaElement	mediaElement.Source = new Uri("ms-appx:///Assets/HarlemCampus.wmv");	0
6940914	6940100	Unit Test: Replicating Heavy Server Load With Local Server	threads[i] = new Thread(() => {\n    try {\n        for (var j = 0; j < 10; j++) {\n            // Send the request\n            var request = Http.WebRequest("http://localhost/SomePage");\n            var document = new HtmlDocument();\n            document.LoadHtml(request.Data);\n\n            // Get the required info\n            var title = document.DocumentNode.SelectSingleNode("//title").InnerText.Trim();\n\n            // Test if the info is valid\n            if (title != "Some Page") {\n                isValid = false;\n                break;\n            }\n        }\n    }\n    catch (Exception ex) {\n        Trace.WriteLine(ex);\n    }\n});	0
24108617	24107565	Open file from isolatedstorage in default app (Windows Phone 8)	new Uri("ms-word:isostore:file.txt", UriKind.Absolute);	0
3410775	3409655	adding attachment to email from browse button	string fileName = Path.Combine(Path.GetTempPath(),FileUploadControl.FileName);\nusing (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))\n{\n    byte[] buffer = new byte[1024];\n    int bytesRead; while ((bytesRead = FileUploadControl.PostedFile.InputStream.Read(buffer, 0, buffer.Length)) > 0) \n    {\n        fs.Write(buffer, 0, bytesRead);\n    }\n}\n\nAttachment attachment = new Attachment(fileName);\nmsg.Attachments.Add(attachment);	0
30184760	30167213	Windows phone 8.1 universal app DataTransferManager UI not showing	request.FailWithDisplayText("fail");	0
8754253	8754069	How to create a custom event log using C#	if (!System.Diagnostics.EventLog.SourceExists(sourceName))\n            System.Diagnostics.EventLog.CreateEventSource(sourceName, logName);	0
16659586	16659454	Go To Line in Text Editor	int pos = textBox1.GetFirstCharIndexFromLine(9);\n textBox1.SelectionStart = pos;\n textBox1.ScrollToCaret();	0
6473151	6473019	Running Javascript to size an ASP.NET control once it is rendered or updated by a postback	ScriptManager.RegisterStartupScript(Page, GetType(Page), "myScript", "$(function() {{ alert ('Your page is loaded.'); }});", True)	0
10413196	10413036	How can a SqlParameter value be set to the result of a SQL function?	var cmd = new SqlCommand("update Table set ADateField = @p1 where Id = @id");\ncmd.Parameters.AddWithValue("@id", 42);\nif( useFunction )\n{\n  cmd.CommandText = cmd.CommandText.Replace("@p1", "sysutcdatetime()");\n}\nelse\n{\n  cmd.Parameters.AddWithValue("@p1", exactDate);  \n}\ncmd.ExecuteNonQuery();	0
25659803	25658323	Why SpellCheck always marks words from additional dictionary (utf-8, utf-8 with BOM, UTF-16) as bad?	box.Language = System.Windows.Markup.XmlLanguage.GetLanguage("fr");\nString text = System.IO.File.ReadAllText(lex_file.AbsolutePath, Encoding.UTF8);\nSystem.IO.File.WriteAllText(lex_file.AbsolutePath, text, Encoding.GetEncoding(1252));	0
16581076	16580911	Passing arguments from managed C# to Managed C++	public ref class MyClass\n{\npublic:\n    void Sample(String^ var1, array<String^>^ var2);\n};	0
29696070	29695875	Listbox not showing	form.ShowDialog();	0
1849262	1849236	How do I update a listview item that is bound to a collection in WPF?	class ItemClass : INotifyPropertyChanged\n{\n    public int BoundValue\n    {\n         get { return m_BoundValue; }\n         set\n         {\n             if (m_BoundValue != value)\n             {\n                 m_BoundValue = value;\n                 OnPropertyChanged("BoundValue")\n             }\n         }\n    }\n\n    void OnPropertyChanged(string propertyName)\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n\n    int m_BoundValue;\n}	0
20925931	20925815	Add MouseLeftButtonUp events dynamicly	test.MouseLeftButtonUp += imClicked;\n\n\nprivate void imClicked(object sender, MouseButtonEventArgs e)\n    {\n             MessageBox.Show("hello");\n    }	0
20814853	18813484	Method for Sorting 2D Matricies, How can i make the method generic?	public static void Sort2DArray<T>(T[,] matrix)\n    {\n        var numb = new T[matrix.GetLength(0) * matrix.GetLength(1)];\n\n        int i = 0;\n        foreach (var n in matrix)\n        {\n            numb[i] = n;\n            i++;\n        }\n        Array.Sort(numb);\n\n        int k = 0;\n        for (i = 0; i < matrix.GetLength(0); i++)\n        {\n            for (int j = 0; j < matrix.GetLength(1); j++)\n            {\n                matrix[i, j] = numb[k];\n                k++;\n            }\n        }\n    }	0
17402168	17401497	Sort on discriminator - EF	YourContext.Dogs.OrderBy(d => (d is SomeDog) ? 1 : 2)	0
13618458	13617549	Solving a Directed Graph with Recursion	NOT LIKE '%' + b.arrival + '%'	0
11743394	11461740	Set a group of actions to require the same authorization	[Authorize]	0
2465955	2465226	Accessing the Settings of another application	// Get the application path.\nstring exePath = System.IO.Path.Combine(\n    Environment.CurrentDirectory, "ConfigurationManager.exe");\n\n// Get the configuration file.\nSystem.Configuration.Configuration config =\n  ConfigurationManager.OpenExeConfiguration(exePath);\n\n// Get the AppSetins section.\nAppSettingsSection appSettingSection = config.AppSettings;	0
21588518	21587029	How can I keep track of state DRY-ly?	public void SetState(int stateNum)\n{\n    _state = stateNum;\n}\nprivate int _state = 1;\n\npublic bool IsThisStateOne { get { return _state == 1; } }\npublic bool IsThisStateTwo { get { return _state == 2; } }\npublic bool IsThisStateThree { get { return _state == 3; } }	0
21385795	21385597	Preventing duplicates before insert in datagridview	for (int i = 0; i < dataGridView2.Rows.Count; i++)\n{\n    if (textBox1.Text == dataGridView2.Rows[i].Cells[0].Value.ToString())\n    {\n        MessageBox.Show("duple");\n        return;\n    }\n}\n\ndataGridView2.Rows.Add(textBox1.Text.Trim(), pictureBox3.Image, pictureBox6.Image);	0
19543991	19543874	Regex - documentation	Your regular expression explained	0
11567400	11567332	Populate an asp.net Gridview dynamically with List<T>	GridView1.DataSource = dtSearchResults ;\n\nGridView1.DataBind();	0
5642051	3739370	Auto-Interval precision in MS Chart	# = Convert.ToInt32(Math.Abs(Math.Log10(range) - .5)) + 1;	0
20466600	20466408	Reading from attribute in .NET	class Program\n{\n    static void Main(string[] args) {\n        Test();\n        Console.Read();\n    }\n\n    [Custom(Foo = "yup", Bar = 42)]\n    static void Test() {\n        // Get the MethodBase for this method\n        var thismethod = MethodBase.GetCurrentMethod();\n\n        // Get all of the attributes that derive from CustomAttribute\n        var attrs = thismethod.GetCustomAttributes(typeof(CustomAttribute), true);\n\n        // Assume that there is just one of these attributes\n        var attr1 = (CustomAttribute)attrs.Single();\n\n        // Print the two properties of the attribute\n        Console.WriteLine("Foo = {0},  Bar = {1}", attr1.Foo, attr1.Bar);\n    }\n}\n\nclass CustomAttribute : Attribute\n{\n    public string Foo { get; set; }\n    public int Bar { get; set; }\n}	0
27962627	27960617	Select the minimum value from strings starting with a number	int small=Convert.ToInt32(MyArray[0].SubString(0,1));\n string result = MyArray[0];\n for(int i=0; i < MyArray.Length; i++)\n {\n  if(Convert.ToInt32(MyArray[i].SubString(0,1))<small)\n    {\n      result=MyArray[i];\n    }\n\n }	0
21475407	20652573	Printing XRLabel on every Report Page	Image img = new Bitmap(300, 300);\nGraphics g = Graphics.FromImage(img);\nFont schriftart = new Font(StyleVerwaltung.Instance.Schriftart,\n    StyleVerwaltung.Instance.SchriftgroesseDruckInfo);\nStringFormat format = new StringFormat();\nformat.Alignment = StringAlignment.Center;\n\n_Report.Watermark.ImageAlign = ContentAlignment.BottomLeft;\n_Report.Watermark.ImageViewMode = ImageViewMode.Clip;\ng.SmoothingMode = SmoothingMode.AntiAlias;\ng.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;\ng.InterpolationMode = InterpolationMode.HighQualityBicubic;\ng.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\ng.TranslateTransform(0, g.VisibleClipBounds.Size.Height);\ng.RotateTransform(270f);\ng.DrawString(text, schriftart, Brushes.Black,\n    new Rectangle(0, 0, (int)g.VisibleClipBounds.Size.Width,\n                        (int)g.VisibleClipBounds.Height),\n    format);\ng.ResetTransform();\ng.Flush();\n\n_Report.Watermark.Image = img;\n_Report.Watermark.ShowBehind = true;	0
32619943	32619893	How to get context based on database type?	public DbContext GetContext(DatabaseType dbType)\n{\n    switch(dbType)\n    {\n        case DatabaseType.address:\n            return new AddressContext();\n        case DatabaseType.names:\n            return new NamesContext();\n        default:\n            throw new ArgumentException("Unexpected db type.");\n    }\n}	0
10204359	10187692	How to export nested gridview to excel/word with gridlines on the child grid	CellSpacing="2"	0
3336199	3293785	Inversion of Control & Dependency Injection in the .NET Framework	WorkflowRuntime.AddService	0
23380684	23380461	split string in to several strings at specific points	public static void ToCSV(string fileWRITE, string fileREAD)\n{\n    string[] lines = File.ReadAllLines(fileREAD);\n    string[] splitLines = lines.Select(s => Regex.Replace(s, "(.{5})(.)(.{3})(.*)", "$1,$2,$3,$4")).ToArray();\n    File.WriteAllLines(fileWRITE, splitLines);\n}	0
6731699	6731648	Background worker variable assignments in DoWork	static object Locker = new object();\n\nlock (Locker)\n{\n   // variable assignment in here.\n}	0
1996989	1996975	How can one "scan" a lambda expression in C#?	public Examples(Expression<Func<dynamic, dynamic>> func) {\n    ...\n}	0
8949042	8948883	How do I convert datacolumn values to decimals for use in a chart?	using (var reader = database1DataSet.DataTable1.CreateDataReader())\n        {\n            int colOrdinal = database1DataSet.DataTable1.Columns["YourColumnName"].Ordinal\n            while (reader.Read())\n            {\n                chart1.Series["ser1"].Points.AddY(reader.GetInt32(colOrdinal));\n            }\n        }	0
8169207	8169042	How to synchronize UI and access objects from another thread?	Dispatcher.Invoke(...);  OR\nDispatcher.BeginInvoke(...);	0
5042099	5041958	Deserializing JSON string to Object with json.net	class WeaponList\n{\n    public Dictionary<string, WeaponDetails> Weapons { get; set; }\n}	0
9942135	9942075	receiving an array from a WCF service and display it into a listbox	listBox1.ItemsSource = Groups;       // no .ToString()\nlistBox1.DisplayMemberPath = "Name"; // should be a Group property	0
10679376	10660027	how to insert datetime into time(0) field	objSBC.ColumnMappings.Add(new SqlBulkCopyColumnMapping("datatable column name","sql server column name"));	0
24473549	24473255	Entity Framework Code First one to many optional with fluent mapping	public class CompanyContext : DbContext\n{\n    protected override void OnModelCreating(DbModelBuilder builder)\n    {\n        builder.Entity<Company>()\n            .HasRequired(c => c.TimeZone)\n            .WithMany()\n            .HasForeignKey(c => c.TimeZoneId);\n\n        base.OnModelCreating(builder);\n    }\n\n}\n\n[Table("Company")]\npublic class Company\n{\n    [Key]\n    public int Id { get; set; }\n\n    public int TimeZoneId { get; set; }\n\n    [StringLength(255)]\n    [Required]\n    public string Name { get; set; }\n\n    // this will be navigation property\n    public TimeZone TimeZone { get; set; }\n\n}\n\n[Table("TimeZone")]\npublic class TimeZone\n{\n    [Key]\n    public int Id { get; set; }\n\n    [StringLength(255)]\n    public string Name { get; set; }\n\n}	0
8870169	8869134	Finding text between tags and replacing it along with the tags	var s = "My temp folder is: [code]Path.GetTempPath()[/code]";\n\nvar result = Regex.Replace(s, @"\[code](.*?)\[/code]",\n    m =>\n        {\n            var codeString = m.Groups[1].Value;\n\n            // then you have to evaluate this string\n            return EvaluateMyCode(codeString)\n        });	0
13929965	13929866	how to save the datetime in datagrid as dd/mm/yyyy hh:mm	DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-AU"))	0
3724221	3724052	How do I query by the count of a property in nhibernate without using a detached criteria?	from bowl where fruits.size > 1	0
7918260	7878934	How to draw a simple rectangle on DrawingArea with specific size, and X Y positions?	Private void DrawRectangle()\n    {\n    Gdk.Color RectangleColor = colorbutton_RectangleColor.Color;\n    eventbox_rectangle.ModifyBg(StateType.Normal, RectangleColor); \n    //To modify the size of the rectangle use the following.\n    eventbox_rectangle.HeightRequest = 10;\n    eventbox_rectangle.WidthRequest = 10;\n    }	0
26590169	26589457	How can I convert the following linq queries to a (Having) like in SQL	IQueryable query = from x in Context.Stuff\n                   select x;\n\nList<Stuff> output = List<Stuff>();\n\noutput = query.Where(r => r.Title).Contains("SearchTerm")).ToList();\noutput += query.Where(r => r.Title).Contains("DifferentSearchTerm")).ToList();	0
1842318	1841362	Recursion limit exceeded	return Json("helloWorld");	0
21469727	21469704	getting distinct values from objects acording to one of its fields	List<string> types = source.Select(x => x.type)\n                           .Distinct()\n                           .ToList();	0
10990947	10984766	How to access a DetailsView's ItemTemplate's TextBox in code behind? ASP.Net C#	if (_DetailsView.FindControl("TextBoxInsertItem") != null)	0
25479639	25479496	How to get an item from asp:Repeater in Event handler?	var txt = (sender as TextBox).Text;\nvar repeaterItem = (sender as TextBox).NamingContainer as RepeaterItem;\nvar hiddenFieldKey =repeaterItem.FindControl("hiddenFieldKey") as HiddenField;\n\n// Get data from viewstate\nDataTable data = ViewState["Data"] as DataTable;\nvar dataRow= data.Rows.Find(hiddenFieldKey.Value);\n//You can use this row to get the values of the other columns\n\nint newDays = 0;\ntry\n{\n    newDays = int.Parse(txt);\n}\ncatch { return; }	0
28295206	28294343	How to convert a byte-array to a Image in C#?	public BitmapImage ImageFromBuffer(Byte[] bytes)\n        {\n            if (bytes == null || bytes.Length == 0) return null;\n            var image = new BitmapImage();\n            using (var mem = new MemoryStream(bytes))\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
8435929	8239469	How to find the data source of a Pivot Table using OpenXML	worksheet.PivotTables[0].CacheDefinition.SourceRange.FullAddress;	0
4964737	4964588	Open file ReadOnly	var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); \nusing (var sr = new StreamReader(fs))\n{\n    // etc...\n}	0
12173908	12094098	Error mapping many to many in nhibernate	"Dpsir.Dpsir.DpsirId", dpsirs.Select(d => d.DpsirId).ToArray()	0
10980477	10980237	Xml to Text Convert	XmlDocument doc = new XmlDocument();\n    doc.LoadXml(your text string);\n\n    StringBuilder sb = new StringBuilder();\n    foreach (XmlNode node in doc.DocumentElement.ChildNodes)\n    {\n        sb.Append(char.ToUpper(node.Name[0]));\n        sb.Append(node.Name.Substring(1));\n        sb.Append(' ');\n        sb.AppendLine(node.InnerText);\n    }\n\n    Console.WriteLine(sb);	0
19001021	18998763	How to retrieve binary image from database using C# in ASP.NET	//Get byte array from image file in the database with basic query\nSqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);\nDataTable dt = new DataTable();\nmyAdapter1.Fill(dt);\n\nforeach (DataRow row in dt.Rows)\n{\n    // Get the byte array from image file\n    byte[] imgBytes = (byte[]) row["logo"];\n\n    // If you want convert to a bitmap file\n    TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));\n    Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);\n\n    string imgString = Convert.ToBase64String(imgBytes);\n    //Set the source with data:image/bmp\n    imgLogoCompany.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);\n}	0
7918140	7918080	How can I sort a 2d array using Linq?	var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);	0
18319857	18319833	Convert &#XXXX; character from HTML to correct format	WebUtility.HtmlDecode()	0
4791403	4791390	Find the flow direction from CurrentCulture in c#	CultureInfo.TextInfo.IsRightToLeft	0
10153114	10142979	How to reverse resolve custom attributes?	public static T GetEnumValue<T, TExpected>(char value) where TExpected : Attribute\n    {\n        var type = typeof(T);\n\n        if (type.IsEnum)\n        {\n            foreach (var field in type.GetFields())\n            {\n                dynamic attribute = Attribute.GetCustomAttribute(field,\n                    typeof(TExpected)) as TExpected;\n\n                if (attribute != null)\n                {\n                    if (attribute.Value == value)\n                    {\n                        return (T)field.GetValue(null);\n                    }\n                }\n            }\n        }\n\n        return default(T);\n    }	0
31724849	31724542	How to stop adding duplicate username into database table?	if (not exists(select 1 from DeliveryMen where Username= @Username and Email=@Email))\nbegin\ninsert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (@name ,@username, @password, @email ,@phone ,@city,@License)\nend	0
9616030	9615893	How to change file and directory name using c# regex	public void RenameFiles(string folderPath, string searchPattern = "*.*")\n{\n foreach (string path in Directory.EnumerateFiles(folderPath, searchPattern))\n {\n  string currentFileName = Path.GetFileNameWithoutExtension(path);\n  string newFileName = ToUrlSlug(currentFileName);\n\n  if (!currentFileName.Equals(newFileName))\n  {\n   string newPath = Path.Combine(Path.GetDirectoryName(path),\n    newFileName +  Path.GetExtension(path));\n\n   File.Move(path, newPath);\n  }\n }\n}	0
9719926	9716486	Add TermSetGroup in Sharepoint via Code	SPSecurity.RunWithElevatedPrivileges(delegate() { \nusing(SPSite elevatedSite = new SPSite(YOUR_SITEID))\n{\n    var elevatedTSession = new TaxonomySession(SPContext.Current.Site);\n    var elevatedTermstore = elevatedTSession.TermStores[0]; //Or other if you have more\n    //your code here, but using elevatedTermstore instead\n}	0
8944174	8937642	How to add a dropdownlist in excel using spreadsheetgear?	// Create workbook and a local variable to Cells\nIWorkbook workbook = Factory.GetWorkbook();\nIRange cells = workbook.ActiveWorksheet.Cells;\n// Build up some data to use in our validation list\ncells["A1:A5"].Value = "=ROUND(RAND()*100, 0)";\n// Create cell validation on Column B using values from other cells\ncells["B:B"].Validation.Add(SpreadsheetGear.ValidationType.List, ValidationAlertStyle.Information, ValidationOperator.Default, "=$A$1:$A$5", "");\n// Create cell validation on Column C using a static list\ncells["C:C"].Validation.Add(SpreadsheetGear.ValidationType.List, ValidationAlertStyle.Information, ValidationOperator.Default, "a,b,c", "");	0
19138506	19126256	Specifying a filter condition on a Text Search with MongoDB C# driver	var filter = Query.EQ("Type", 1);\nvar textSearchCommand = new CommandDocument\n{\n    {"text", this.Collection.Name},\n    {"search", searchString},\n    {"filter", BsonValue.Create(filter)}\n};\n\nvar commandResult = this.Collection.Database.RunCommand(textSearchCommand);	0
22971527	22970403	How to detect MouseWheel event is ended in WPF	//Use dispatcher timer to avoid problems when manipulating UI related objects\n    DispatcherTimer timer;\n    float someValue = 0;\n\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        timer = new DispatcherTimer();\n        timer.Tick += timer_Tick;\n        timer.Interval = TimeSpan.FromMilliseconds(500 /*Adjust the interval*/);\n\n\n        MouseWheel += MainWindow_MouseWheel;\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n        //Prevent timer from looping\n        (sender as DispatcherTimer).Stop();\n\n        //Perform some action\n        Console.WriteLine("Scrolling stopped (" + someValue + ")");\n\n        //Reset for futher scrolling\n        someValue = 0;\n    }\n\n    void MainWindow_MouseWheel(object sender, MouseWheelEventArgs e)\n    {\n        //Accumulate some value\n        someValue += e.Delta;\n\n        timer.Stop();\n        timer.Start();\n    }	0
22353840	22353447	c# sort XElement, with comments	var xDoc = XDocument.Parse(/* your xml */);\nvar reordered = xDoc.Root\n                    .Elements("Child")\n                    .Select(el => new {\n                                        Element = el,\n                                        Comments = el.NodesAfterSelf()\n                                                     .TakeWhile(n => n.NodeType == XmlNodeType.Comment)\n                                      })\n                    .OrderBy(pair => (int)pair.Element.Attribute("id"))\n                    .SelectMany(pair => new [] { pair.Element }.Concat(pair.Comments));\nxDoc.Root.ReplaceAll(reordered);	0
9158275	9158082	Nullable DateTime conversion	DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]);	0
25785407	25785235	How to access programmatically created timer controls?	public static List<JobTimer> _timers;\n\n    public class JobTimer : System.Windows.Forms.Timer\n    {\n        private int IntJobID;\n        public int JobID\n        {\n            get { return IntJobID; }\n            set { IntJobID = value; }\n        }\n    }\n\n    public static void CreateTimer(int JobID)\n    {\n        if (_timers == null)\n        {\n            _timers = new List<JobTimer>();\n        }\n        JobTimer ControlJobTimer = new JobTimer();\n        ControlJobTimer.Enabled = true;\n        ControlJobTimer.JobID = JobID;\n        ControlJobTimer.Interval = 30000;\n        ControlJobTimer.Tick += new EventHandler(JobTimer_Tick);\n        ControlJobTimer.Start();\n        _timers.Add(ControlJobTimer);\n    }	0
27177005	27145410	Get Storage from an out look folder in redemption	RDOMail hiddenMessage = YourRDOFolder.HiddenItems.Find("Subject = 'Flow' ")	0
18080177	17955942	Passing model with dynamic json object to MVC controller	Json.Encode/Decode	0
24356944	24352744	Ado.Net Fill Grid By Logged in User	string UserId = HttpContext.Current.User.Identity.Name;	0
31800295	31800115	Using RegEx to Uppercase [variables]	public static string VariablesToUpperCase(this string input)\n    {\n        string pattern = @"\[\w+\]";\n        Regex rgx = new Regex(pattern);\n        return rgx.Replace(input, (m) => { return m.ToString().ToUpper(); });\n    }	0
2357495	2357444	Set properties of a class only through constructor	public class Thing\n{\n   private readonly string _value;\n\n   public Thing(string value)\n   {\n      _value = value;\n   }\n\n   public string Value { get { return _value; } }\n}	0
1567544	1567513	Windows Service with NLog	void Installer1_AfterInstall(object sender, InstallEventArgs e)\n{\nstring myAssembly = Path.GetFullPath(this.Context.Parameters["assemblypath"]);\nstring logPath = Path.Combine(Path.GetDirectoryName(myAssembly), "Logs");\nDirectory.CreateDirectory(logPath);\nReplacePermissions(logPath, WellKnownSidType.NetworkServiceSid, FileSystemRights.FullControl);\n}\n\nstatic void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow)\n{\nFileSecurity sec = File.GetAccessControl(filepath);\nSecurityIdentifier sid = new SecurityIdentifier(sidType, null);\nsec.PurgeAccessRules(sid); //remove existing\nsec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow));\nFile.SetAccessControl(filepath, sec);\n}	0
25518085	25517899	Click on a button within LongListSelector Windows phone 8	bool isBtnClicked = false;\n\nprivate void MyLLS_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    // check if button is clicked, if so, return and reset the isBtnClicked flag.\n    if (isBtnClicked)\n    {\n        isBtnClicked = false;\n        return;\n    }\n    var item = (MyItemType)MyLLS.SelectedItem;\n    // Job 1 goes here\n}\n\nprivate void btDownload_Click(object sender, RoutedEventArgs e)\n{\n    var button = (MyItemType)(sender as Button).DataContext; \n    // set it true when button clicked\n    isBtnClicked = true;         \n    // Job 2 goes here\n}	0
26691877	26691660	C# - Getting keyboard input after event	// enum to store panel movement direction\npublic enum PanelMovement\n{\n    None;\n    Left;\n    Right;\n}\n\n// member variable to store last panel movement\nprivate PanelMovement mCurrentMovement = PanelMovement.None;\n\nprivate void rightLeftForm_KeyDown(object sender, KeyEventArgs e)\n{\n        if (e.KeyCode.ToString() == "R")\n        {\n            // store direction after player has pressed "R"\n            mPanelMovement = PanelMovement.Right;\n        }\n        else if (e.KeyCode.ToString() == "L")\n        {\n           // store direction after player pressed "L" \n           mPanelMovement = PanelMovement.Left;\n        }\n        // react on number key pressed\n        else if(e.KeyCode >= Keys.D1 && e.KeyCode <= Keys.D9)\n        {\n            if(mPanelMovement == PanelMovement.Left)\n               // move panel left\n            else if(mPanelMovement == PanelMovement.Right)\n              // move panel right\n        }\n    }	0
7103858	7103823	How to turn these C# foreach loops into LINQ to Objects and return a bool?	return myVegas.Project.Tracks\n    .Where(track => track.IsVideo())\n    .SelectMany(track => track.Events)\n    .Any(trackEvent => trackEvent.Start == currentEvent.Start);	0
8968695	8968678	Convert Date Value to Specific Format in C#	var date = DateTime.Parse("14/11/2011"); // may need some Culture help here\nConsole.Write(date.ToString("yyyy-MM-dd"));	0
12577968	12577828	Custom names to enumeration values	[Display()]	0
30276683	30276370	Data chart doesn't add all data	public void Makedp()\n        {\n            theSerie.Points.Clear();\n            theSerie.Points.AddY(getal);\n            theSerie.Points.AddY(getal1);\n            theSerie.Points.AddY(getal2);\n            theSerie.Points.AddY(getal3);\n            theSerie.Points.AddY(getal4);\n            theSerie.Points.AddY(getal5);\n\n    }	0
4400820	4395200	someone knows how to delete pack foxpro data from oledb driver with c#	static void Main(string[] args)\n    {\n    Console.WriteLine("Starting program execution...");\n\n    string connectionString = @"Provider=VFPOLEDB.1;Data Source=h:\dave\"; \n\n    using (OleDbConnection connection = new OleDbConnection(connectionString)) \n    { \n        using (OleDbCommand scriptCommand = connection.CreateCommand()) \n        { \n            connection.Open();\n\n            string vfpScript = @"SET EXCLUSIVE ON\n                                DELETE FROM test WHERE id = 5\n                                PACK"; \n\n            scriptCommand.CommandType = CommandType.StoredProcedure; \n            scriptCommand.CommandText = "ExecScript"; \n            scriptCommand.Parameters.Add("myScript", OleDbType.Char).Value = vfpScript; \n            scriptCommand.ExecuteNonQuery(); \n        } \n    } \n\n    Console.WriteLine("End program execution..."); \n    Console.WriteLine("Press any key to continue"); \n    Console.ReadLine(); \n    }	0
12156239	12156173	How to handle events on a background thread?	Task.Factory.StartNew	0
8919256	8918475	XNA model import - All meshs appear on top of each other	Matrix[] transforms = new Matrix[model.Bones.Count];\nmodel.CopyAbsoluteBoneTransformsTo(transforms);\n\nforeach (ModelMesh mesh in model.Meshes) {\n    foreach (BasicEffect ef in mesh.Effects) {\n        ef.World = transforms[mesh.ParentBone.Index];\n        //Also do other stuff here, set projection and view matrices\n    }\n}	0
25376838	25376765	Select many 2 fields with a same type	public List<D> getSelectedDs()\n{\n     return Bs.SelectMany(b => b.FirstC.Ds.Union(b.SecondC.Ds))\n              .Where(x => x.IsSelected).ToList();\n}	0
18931330	18931082	How to mark last row in DataGridView in case of vertical scroll bar?	dataGridView1.CurrentCell.Selected = false;\nvar lastRow = dataGridView1.Rows[dataGridView1.Rows.Count - 1];\n//de-select the last selected rows;\ndataGridView1.SelectedRows.OfType<DataGridViewRow>().ToList().ForEach(x=>x.Selected=false);\nlastRow.Selected = true;\ndataGridView1.FirstDisplayedCell = lastRow.Cells[0];	0
32096435	32096344	Check if date exist in list of dates	DateTime date_1 = new DateTime(2016, 1, 1); \nbool exist = dates.Any (d => d.Month == date_1.Month && d.Day == date_1.Day);\nConsole.WriteLine(exist);\n\nDateTime date_3 = new DateTime(2016, 1, 2); \nexist = dates.Any (d => d.Month == date_3.Month && d.Day == date_3.Day);\nConsole.WriteLine(exist);	0
23980550	23980528	how to convert this Query to Linq	db.RateTable\n  .GroupBy(x => x.Rate) \n  .Select(g => g.Count())\n  .OrderByDescending(g => g) \n  .First()	0
4794553	4794514	How do I suppress automatic generated columns in a DataGridView?	DataGridView.AutoGenerateColumns = false;	0
13331070	13331017	EF join two tables into one model	CREATE VIEW [ViewName] AS\nSELECT *\nFROM Table1 JOIN Table2 ON Table1.AppGuid = Table2.AppGuid	0
28876161	28876021	How do I create a Type with multiple generic type parameters	Type type = typeof(IMyInterface<,>).MakeGenericType(type1, type2);	0
30964393	30940998	Windows Store App - Dynamic Binding	var binding = new Binding\n        {\n            Source = _sectionHeaderSlider,\n            Mode = BindingMode.TwoWay,\n            Path = new PropertyPath("Value"),\n        };\n        BindingOperations.SetBinding(ScrollTransform, Windows.UI.Xaml.Media.CompositeTransform.TranslateXProperty, binding);	0
22324408	22324287	Bind Model inside list to a repeater	value=<%#Eval("Employer.vatNumber")%>	0
10711977	10711859	Make sure your signed XML is signed by you	signedXml.SigningKey = Key;	0
2322835	2322823	Func<T, TResult> for with void TResult?	Action<T>	0
27965416	20686116	Smo user created stored procedure	if (mystr.Schema != "sys")\n{\n    classGenerated += mystr.Name + Environment.NewLine;\n}	0
23345360	23345120	Given the DayOfWeek number, find the date of a day in the previous week	public static class DateExtensions\n{\n    public static DateTime Next(this DateTime from, DayOfWeek dayOfWeek)\n    {\n        int start = (int)from.DayOfWeek;\n        int wanted = (int)dayOfWeek;\n        if (wanted <= start)\n            wanted += 7;\n        return from.AddDays(wanted - start);\n    }\n\n    public static DateTime Previous(this DateTime from, DayOfWeek dayOfWeek)\n    {\n        int end = (int)from.DayOfWeek;\n        int wanted = (int)dayOfWeek;\n        if (wanted >= end)\n            end += 7;\n        return from.AddDays(wanted - end);\n    }\n}\n\n\nvar lastFriday = DateTime.Today.Previous(DayOfWeek.Friday);	0
3346456	3346233	Number Formatting in Thousands	string formatted = value.ToString("N0");	0
1455466	1455343	How to add a custom column to a MvcContrib Grid?	column.For("PDF").Named("PDF").Action(p => { %> \n<td><img src="../Content/Images/pdf.gif" /></td> <% });	0
17435046	17434784	Natural Join of two DataTables in C#	var result = from t1 in table1.AsEnumerable()\n             join t2 in table2.AsEnumerable() on (int)t1["ID"] equals (int)t2["ID"]\n             select new\n             {\n                 Student = t1,\n                 Facts = t2\n             };\nforeach(var s in result)\n    Console.WriteLine("{0} {1} {2}", s.Student["student-id"], s.Facts["Col1"], s.Facts["Col2"]);	0
1681624	1681546	Custom WPF Control Dependency Property Not Binding to external DP	public static readonly DependencyProperty RandomNumberProperty =\n    DependencyProperty.Register(\n      "RandomNumber",\n      typeof(int),\n      typeof(Tester),\n      new FrameworkPropertyMetadata\n      {\n        BindsTwoWayByDefault = true,\n      });	0
6929242	6928377	Obtaining the ctl property from a gridview control in C#, ASP.Net	linkbutton CommandArgument='<%# Eval("some_id") %>' \n\nprotected void linkButton_Click(object sender, EventArgs e)\n{\n\n    LinkButton linkButton = (LinkButton) sender;           \n    if (linkButton != null)\n    {\n        if (linkButton.CommandArgument != null)\n        {\n            ...some code...\n        }\n    }\n\n}	0
21135803	21134432	How post on Facebook many wall?	var posters = new FacebookBatchParameter[]\n    {\n        new FacebookBatchParameter(HttpMethod.Post,string.Format("/{0}/feed", "100000481752xxx"),messagePost),\n        new FacebookBatchParameter(HttpMethod.Post,string.Format("/{0}/feed", "100003279105xxx"),messagePost)\n    };\n\nvar result = client.Batch(posters);	0
33797165	33797085	Getting value from SelectedItem RadGridView	var typeValue = ((AssetListData)AssetList_GridView.SelectedItem).assetType;	0
27258811	27258608	Using Textboxfor or Editorfor a property that is part of a list	for (var i = 0; i < Model.Organizations.Count(); i++)\n{ \n    <%= Html.TextBoxFor(m => m.Organizations[i].Name) %> \n\n    <%= Html.TextBoxFor(m => m.Organizations[i].Number) %>\n}	0
26716950	26716330	Get the metatable for foreign key	var parents = table.Columns.OfType<MetaForeignKeyColumn>().Select(s => s.ParentTable).Distinct();\nvar children = table.Columns.OfType<MetaChildrenColumn>().Select(s => s.ChildTable).Distinct();	0
4841409	4841401	convert string array to string	string[] test = new string[2];\n\ntest[0] = "Hello ";\ntest[1] = "World!";\n\nstring.Join("", test);	0
16052254	16050929	Get list of elements where there are two records	var required = new List<string> { "LQ", "GR" };\nvar query = data\n    .GroupBy(x => x.dcid)\n    .Where(g => g\n        .Select(x => x.tpc)\n        .Intersect(required)\n        .Count() == required.Count)\n    .Select(g => g.Key);	0
13867052	13864681	lambda equivalent to sql update with joins	foreach(var customer1 in customers1) {\n    var customer2 = customers2.FirstOrDefault(c2 => customer1.ID.Equals(c2.ID));\n    if (customer2 != null) customer1.Email = customers2.Email;\n}	0
18892176	18889687	How to utilise C# methods in a different programming language	extern "C"{\n    __declspec(dllexport) void _cdecl MyFunction()\n     {\n          _MyImpl(); //see below wy this\n      }\n    }\n\nvoid MyImpl()\n{\n    MyCSharpObj^ test = gcnew MyCSharpObj()...\n    test->Methods(...\n}	0
23396186	23394654	signing a xml document with x509 certificate	KeyInfo keyInfo = new KeyInfo();\n    KeyInfoX509Data keyInfoData = new KeyInfoX509Data( Key );\n    keyInfo.AddClause( keyInfoData );\n    signedXml.KeyInfo = keyInfo;	0
5885879	5885225	Javascript: decoding a string	newstring = yourstring.Replace("&amp;", "&");	0
31925919	31921288	How to get restricted properties from Web for whole collection in SharePoint	using (var ctx = new ClientContext(webUri))\n{            \n\n    ctx.Load(ctx.Web.Webs, wcol => wcol.Include(w => w.HasUniqueRoleAssignments, w => w.Title, w => w.RoleAssignments));\n    ctx.ExecuteQuery();\n\n    foreach (var web in ctx.Web.Webs)\n    {\n        Console.WriteLine(web.HasUniqueRoleAssignments);\n    }\n}	0
24503557	24503480	How can I subtract 11:00pm from 1:30am without getting 9:30 as the result, in C#	var dt1 = new DateTime(2014, 1, 1, 10, 0, 0);\nvar dt2 = new DateTime(2014, 1, 1, 13, 0, 0);\nvar t1 = new TimeSpan(dt2.Ticks - dt1.Ticks);	0
24114317	24114290	Is it possible to load a partial view via string replacement in a controller in asp.net MVC 5	public ActionResult ActionName(ModelName modelObject)\n{\n//Desired Code\nreturn PartialView("name of the partial view", someViewModel);\n}	0
12919309	12919079	Simple Digital Safe, Knowing what order a user presses buttons	StringBuilder _code = new StringBuilder();\n\nvoid button1_Click(object sender, EventArgs e)\n{\n    _code.Append('1');\n\n  CheckCode();\n}\n\n// ... similarly implement other button click events\n\n\nvoid CheckCode()\n{\n    if (_code.ToString().Contains("13221"))\n    {\n        MessageBox.Show("ACCESS GRANTED");\n    }\n}	0
19644437	19643844	How can I download from each group of links each time one file at the same time?	//for (int x = 0; x < imagesSatelliteUrls.Count; x++)\nParallel.For(0, imagesSatelliteUrls.Count, /*new ParallelOptions { MaxDegreeOfParallelism = 20 },*/ x =>\n{\n    if (!imagesSatelliteUrls[x].StartsWith("http://"))\n    {\n        imagesSatelliteUrls[x] = stringForSatelliteMapUrls + imagesSatelliteUrls[x];\n    }\n\n    using (WebClient client = new WebClient())\n    {\n        if (!imagesSatelliteUrls[x].Contains("href"))\n        {\n            client.DownloadFile(imagesSatelliteUrls[x],\n                                UrlsDir + "SatelliteImage" + x.ToString("D6"));\n        }\n    }\n\n    counter++;\n}); // end of Parallel.For	0
31464086	31463034	is there any way to check what Keys pressed from anywhere of Windows Form ?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    switch (keyData)\n    {\n        case /* whatever key combination */:\n        // do something\n        default:\n            return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n    return true;\n}	0
6454912	6454622	Prevent windows Shutdown with CANCEL option C#	private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n    {\n        if (e.CloseReason.Equals(CloseReason.WindowsShutDown))\n        {\n           if (MessageBox.Show("You are closing this app.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)\n               return;    \n           else    \n               e.Cancel = true;\n        }\n    }	0
5626229	5625899	Create images with Different format with Text	System.Drawing	0
23265729	23010130	XDocument, it says that a node is text but it is an element	if (System.Security.SecurityElement.IsValidText(text.XmlDecodeEntities()))	0
31191155	31191133	c# initializer block property set a property without set	Children.Add()	0
12952381	12952289	If DirectoryInfo contain a Directory	DirectoryInfo[] test = dir.GetDirectories();\nif (test.Any(r => r.FullName.Equals(Path.Combine(dir.FullName,"Test_Folder"))))\n{\n   ContainsTestFolder = true;\n}	0
17332108	17331908	Close OleDbConnection if passed as parameter	public OleDbCommand CreateMyOleDbCommand(OleDbConnection connection,\n    string queryString, OleDbParameter[] parameters) \n{\n    OleDbCommand command = new OleDbCommand(queryString, connection);\n    command.Parameters.AddRange(parameters);\n    return command;\n}	0
27200323	27200297	C# - How to shift focus from one text box to another?	a1_2.Focus(FocusState.Programmatic)	0
1005909	1005871	How to remove windows user account folder using C#?	DirectoryInfo dir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));\ndir = dir.Parent.Parent.Parent;\nDirectoryInfo[] userDirs = dir.GetDirectories(userName);\n\nforeach (DirectoryInfo userDir in userDirs)\n{\n    userDir.Delete(true);\n}	0
21677335	21677182	Delete a data table from data set in c#	for(int i=0;i<dt.rows.count;i++)\n    {\n          for(intj=0;j<=dt.columns.count;j++)\n            {\n\n             if( dt.rows[i][j]!=0)\n            {\n                 flag=1;\n                 break;\n              }\n\n             }\n    }\n\n    if(flag==1)\n    {\n       // dont remove the table\n    }\n\n    else\n    {\n\n     ds.tables.remove(dt);\n    }\n\n}	0
29304012	29303270	Get values of tablerow - dataset Windows CE	foreach (var row in filtered)\n        {\n            Console.WriteLine("{0}, {1}, {2}", row["coding"], row["amount"], row["description"]);\n        }	0
9978860	9978675	Filter result using linq to return a count of entries by remove duplicates using specific parameter	int uniqueByIdCount = list.Select(x => x.Id).Distinct().Count();\nint uniqueByNameCount = list.Select(x => x.Name).Distinct().Count();	0
22355168	22355014	I cannot figure out how to add a child node to a treeview	public Form1()\n{\n   InitializeComponent();\n   var parent = new TreeNode("Graphic Requests");\n\n   TreeNodesList.Add(new TreeNode("Art Not Started"));\n   TreeNodesList.Add(new TreeNode("Art In Progress"));\n   TreeNodesList.Add(new TreeNode("Items To Accept/Modify"));\n   TreeNodesList.Add(new TreeNode("Final Art Not Locked"));\n\n   foreach (var node in TreeNodesList)\n   {\n       parent.Nodes.Add(node);\n   }\n   treeView1.Nodes.Add(parent);\n}	0
22380770	22380427	Replacing part of a query string with another value	using System.Text.RegularExpressions;\nstring newUrl= Regex.Replace("http://spdata.com?value=1&rem=288&data=1", @"rem=\d*", "membership=1",RegexOptions.IgnoreCase);	0
34336931	34333059	MigraDoc + PDFsharp to generate Horizontal PDF	PageSetup pageSetup = document.DefaultPageSetup.Clone();\n// set orientation\npageSetup.Orientation = Orientation.Landscape;\n// ... set other page setting you want here...	0
4431161	3630478	How to validate X.509 Certificate in C# using Compact Framework	RSACryptoServiceProvider rsa = signingCertificate_GetPublicKey();\nreturn rsa.VerifyData( SignedValue(), CryptoConfig.MapNameToOID( "SHA1" ), Signature() );\n\nRSACryptoServiceProvider signingCertificate_GetPublicKey()\n{\n    RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();\n\n    RSAParameters publicKeyParams = new RSAParameters();\n    publicKeyParams.Modulus = GetPublicKeyModulus();\n    publicKeyParams.Exponent = GetPublicKeyExponent();\n\n    publicKey.ImportParameters( publicKeyParams );\n\n    return publicKey;\n}\n\nbyte[] GetPublicKeyExponent()\n{\n    // The value of the second TLV in your Public Key\n}\n\nbyte[] GetPublicKeyModulus()\n{\n    // The value of the first TLV in your Public Key\n}\n\nbyte[] SignedValue()\n{\n    // The first TLV in your Ceritificate\n}\n\nbyte[] Signature()\n{\n    // The value of the third TLV in your Certificate\n}	0
5237830	5196739	How do you create a custom GTK# Widget with its own controls?	protected override void OnSizeAllocated (Gdk.Rectangle allocation)\n    {\n        if (this.Child != null)\n        {\n            this.Child.Allocation = allocation;\n        }\n    }\n\n    protected override void OnSizeRequested (ref Requisition requisition)\n    {\n        if (this.Child != null)\n        {\n            requisition = this.Child.SizeRequest ();\n        }\n    }	0
10438372	10438285	c# add data to firebird database	FbConnection fbCon = new FbConnection(csb.ToString());\n  FbCommand fbCom = new FbCommand("INSERT INTO players(ID,name,score) VALUES (@id,@name,@score)", fbCon);\n  fbCom.Parameters.AddWithValue("id", zID + 1);\n  fbCom.Parameters.AddWithValue("name", var);\n  fbCom.Parameters.AddWithValue("score", score);\n  fbCom.ExecuteNonQuery();	0
23192984	23192855	How to get the last two sections of a URL	string str = "http://www.example.com/services/product/Software.aspx";\n        int lastIndexOfBackSlash = str.LastIndexOf('/');\n        int secondLastIndex = lastIndexOfBackSlash > 0 ? str.LastIndexOf('/', lastIndexOfBackSlash - 1) : -1;\n\n        string result = str.Substring(secondLastIndex, str.Length - secondLastIndex);	0
12717109	12716897	Way to pad an array to avoid index outside of bounds of array error	if(extractArray.Length < 183)\n    Array.Resize<string>(ref extractArray, 183);	0
12599883	12599660	Accessing a private class from another file	public partial class Form1\n{\n    private class SessionData\n    {\n        public void getTicket();\n    }\n}	0
10371473	10356149	Need assistance creating "Save As" method for SQL Server CE database	public Repository GetRepository(string fileName)\n{\n   var man = new DbFileManager();\n   string dbFilePath = man.GetFile(fileName);\n\n   return new Repository(dbFilePath); // TODO: Check dbFilePath\n}	0
30096535	30096398	How to save to more JSON data to a already created file?	File.AppendText(filename, "Write this text into a file!");	0
1567994	1567961	programmatically navigate a linq to sql result	foreach (var application in jobApplications)\n{\n    // use the application wisely\n}	0
22526263	22526190	How do I set available options for a property?	public enum Staff\n{\n    Alice,\n    Bob,\n    Chris,\n    Diana\n}	0
24379520	24368136	checkbox.checked is always false in a grid view	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        //code to bind data to gridview\n    }\n\n}	0
1588631	1588553	How to get ListViewItem under MouseCursor while dragging sth. over it	private void listBox_DragOver(object sender, \n  DragEventArgs e)\n{\n  //for ListView\n  var point = listView.PointToClient(new Point(e.X, e.Y));\n  var item = listView.GetItemAt( point.X, point.Y);     \n  if(item != null)\n  {\n     //do whatever - select it, etc\n  }\n\n\n  //or, for ListBox \n  var indexOfItem = \n    listBox.IndexFromPoint(listBox.PointToClient(new Point(e.X, e.Y)));\n  if (indexOfItem != ListBox.NoMatches)\n  {\n     //do whatever - select it, etc\n  }\n}	0
22089307	22089285	Get hidden field value in code behind	var value = this.rssLink.Value;	0
19345623	19345521	Converting track bar values to a double	Pendulum.angle = ((double)tbrAngle.Value) / 100.0;	0
33647633	33647200	youtube Add Subscription via C#	string[] scopes = new string[] { YouTubeService.Scope.Youtube };\n\n\n // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%\nUserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }\n, scopes\n, "test"\n, CancellationToken.None\n, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;\n\nYouTubeService service = new YouTubeService(new YouTubeService.Initializer()\n     {\n     HttpClientInitializer = credential,\n     ApplicationName = "YouTube Data API Sample",\n     });	0
3513845	2576238	StructureMap with my own attributes in C#	ObjectFactory.Initialize(x =>\n{\n    x.PullConfigurationFromAppConfig = true;\n    x.SetAllProperties(p => p.TypeMatches(t => \n        t.GetCustomAttributes(typeof(InjectAttribute), true).Length > 0));\n}	0
21443916	21441571	Get Post request parameters in custom AuthorizeAttribute	public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        filterContext.HttpContext.Request.InputStream.Length() //17 here\n        string jsonPostData;\n        var stream = request.InputStream;\n        var reader = new System.IO.StreamReader(stream);\n        jsonPostData = reader.ReadToEnd();\n        filterContext.HttpContext.InputStream.Length() //17 here\n        filterContext.HttpContext.Request.InputStream.Position = 0; //17 here\n\n  base.OnAuthorization(filterContext); //so when the request reaches controller its empty\n}	0
18899964	18899357	Serial port reading	private byte[] rcveBuf = new byte[8];\n    private int rcveLen;\n\n    private void tempSerial_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n        SerialPort sp = (SerialPort)sender;\n        rcveLen += sp.Read(rcvebuf, rcveLen, rcveBuf.Length - rcveLen);\n        if (rcveLen == rcveBuf.Length) {\n           Array.Copy(rcveBuf, communication.tempResponse, rcveBuf.Length);\n           communication.dataRecievedTemp = true;\n           rcveLen = 0;\n        }        \n    }	0
1944441	1944432	Can we add variables and properties in interfaces in C#.NET?	public interface ISampleInterface\n{\n    // method declaration\n    bool CheckSomething(object o);\n\n    // event declaration\n    event EventHandler ShapeChanged;\n\n    // Property declaration:\n    string Name\n    {\n        get;\n        set;\n    }\n}	0
15028199	15028144	C# how to always round down to nearest 50	double n = Math.Floor(n / 50.0) * 50.0;	0
24319660	24319597	Escape special characters in SQL INSERT INTO via C#	sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES (@userId, @imagePath, @userComments, @dateCommented)";\n\nsqlCom.Parameters.AddWithValue("@userId", userId);\nsqlCom.Parameters.AddWithValue("@imagePath", imagePath);\nsqlCom.Parameters.AddWithValue("@userComments", comments);\nsqlCom.Parameters.AddWithValue("@dateCommented", theDate);	0
25091990	25091947	Storing an array of a different type into a jagged array	var jaggedArray = new object[3];\n        jaggedArray[0] = new[] { 1, 2, 3 };\n        jaggedArray[1] = new[] { "str", "onemore" };\n        jaggedArray[2] = new[] { new { prop = 14 }, new { prop = 12 }, new { prop = 1 } };\n        Console.Write(jaggedArray[0].ToString());	0
24219810	24219719	Auto formatting numeric string	string number = "1257.00";\n    double value = 0.00;\n    if (double.TryParse(number, out value)) \n    {\n        string roundedNumber = number.Substring(0, (number.IndexOf('.') > 0 ? number.IndexOf('.') : number.Length)-1) + "0";\n        if (double.TryParse(roundedNumber, out value))\n        {\n            Console.WriteLine(String.Format("{0:0.##}", value));\n        }\n        else\n        {\n            Console.WriteLine("Error!");\n        }\n    }\n    else\n    {\n        Console.WriteLine("Error!");\n    }	0
5351454	5351272	Declaring a global variable in ASP.NET codebehind	namespace WebApplication1\n{\n    public partial class _Default : System.Web.UI.Page\n    {\n        private Dictionary<string, object> myDictionary;\n\n        protected void Page_Load(object sender, EventArgs e)\n        {\n            myDictionary = new Dictionary<string, object>();\n            myDictionary.Add("test", "Some Test String as Object");\n        }\n\n        protected void TextBox1_TextChanged(object sender, EventArgs e)\n        {\n            myDictionary.Add("TextBox1Value", TextBox1.Text);\n        }\n\n        protected void Button1_Click(object sender, EventArgs e)\n        {\n            TextBox1.Text = myDictionary["test"].ToString();\n        }\n    }\n}	0
11614551	11613772	How I can find a User with the GUID(objectGUID) Parameter in Active Directory	var user = new DirectoryEntry("LDAP://<GUID=119d0d80-699d-4e81-8e4e-5477e22ac1b3>");	0
15499506	15499451	How to get all registered service types in Autofac	var services =\n    context.ComponentRegistry.Registrations.SelectMany(x => x.Services)\n           .OfType<IServiceWithType>()\n           .Select(x => x.ServiceType);	0
4130541	4130476	Changing the time it takes for the mousehover event to fire	ToolTip t = new ToolTip();\n t.InitialDelay = 500;\n t.SetToolTip(button1, "Hello");	0
794591	794459	Windows Forms - ErrorProvider + DataGridView	public Form1()\n{\n    this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);\n}\n\nprivate void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n        {\n            if (!this.Validates(e.FormattedValue)) //run some custom validation on the value in that cell\n            {\n                this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Error";\n                e.Cancel = true; //will prevent user from leaving cell, may not be the greatest idea, you can decide that yourself.\n            }\n        }	0
19282069	19281415	How to use html.ValidationMessageFor	[Required(ErrorMessage = "First name is required")]\n[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]\npublic string F_Name { get; set; }\n\n[Required(ErrorMessage = "Last name is required")]\n[StringLength(30, ErrorMessage = "Name can be no larger than 30 characters")]\npublic string L_Name { get; set; }	0
15629708	15629295	Accessing android activity from ASP.NET MVC Web Application	WebView.addJavascriptInterface()	0
1850985	1850946	Can't get Value from ComboBox	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n      comboBox1.Items.Add(new Item(1, "one"));\n      comboBox1.Items.Add(new Item(2, "two"));\n      comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);\n    }\n    void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n      Item item = comboBox1.Items[comboBox1.SelectedIndex] as Item;\n      MessageBox.Show(item.Value.ToString());\n    }\n    private class Item {\n      public Item(int value, string text) { Value = value; Text = text; }\n      public int Value { get; set; }\n      public string Text { get; set; }\n      public override string ToString() { return Text; }\n    }\n  }	0
7491767	7491700	how to change color of a column in datagridview?	grid.Columns["NameOfColumn"].DefaultCellStyle.ForeColor = Color.Gray;	0
29262091	26851552	How to C# send AT command to GSM modem and get response	Thread.Sleep(1000);\n_serialPort.WriteLine("ATE1" + "\r");\n\nThread.Sleep(1000);\n_serialPort.WriteLine("AT" + "\r");	0
16030629	16024965	Providing Uninstall option in custom NuGet packages	uninstall.ps1	0
3803549	3803194	Group by name and Include duplicate data in linq to xml c#	var set = xd.Descendants("Microbiology");\nvar results = set.GroupBy(p => p.ReadCode).Select(g => new {Code = g.Key, Tests = g.OrderByDescending(t => t.Date)});	0
3777764	3777733	How do I link to a web page inside a WPF menu item?	Process.Start("http://www.google.com");	0
11595979	11594259	How can I pass a variable from a ASP website to a desktop application?	WebClient webClient = new WebClient();\nvar text = webClient.DownloadString("http://www.example.com/page.aspx");	0
23376232	23373625	Writing ObservableCollection to file	string[] contenutoStorico = rigaStorico.Select(x => x.Name).ToArray();\n\nIsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();\nusing (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("history.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))\n{\n    for (int i = 0; i < contenutoStorico.Length; i++)\n    {\n        writeFile.WriteLine(contenutoStorico[contenutoStorico.Length-i-1]);                    \n    }\n    writeFile.Close();\n}	0
15576928	15554786	How to Use Windows On Screen Keyboard in C# WinForms	string progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";\nstring keyboardPath = Path.Combine(progFiles, "TabTip.exe");\n\nthis.keyboardProc = Process.Start(keyboardPath);	0
7928376	7928330	Get Image from code behind	Server.MapPath("~/Icons/CMJN.png")	0
9898212	9897677	Mapping of ViewModel with SelectList in MVC3	[Required(ErrorMessage = "Please select a Course.")]\n    public int CourseId { get; set; }\n    // public string CourseName { get; set; }\n    public SelectList CourseList { get; set; }	0
10492284	10492235	How to change Current theme to Window classic Theme in Window7 at runtime	//Sets the current theme\nProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.CreateNoWindow = false;\nstartInfo.FileName = ?rundll32.exe?;\nstring startuppath = Application.StartupPath.ToString();\nstring Arguments = ?Shell32.dll,Control_RunDLL desk.cpl desk,@Themes /Action:OpenTheme /File:\?C:\\Windows\\Resources\\Themes\\Windows Classic.Theme\?";\nstartInfo.Arguments = Arguments;\ntry\n{\n// Start the process with the info we specified.\n// Call WaitForExit and then the using statement will close.\nusing (Process exeProcess = Process.Start(startInfo))\n{\nexeProcess.WaitForInputIdle();\n\nIntPtr p = exeProcess.MainWindowHandle;\nShowWindow(p, 1);\nSendKeys.SendWait(?{enter}?);\n}\n}\ncatch\n{\n// Log error.\n}	0
11725091	11682244	Not able to set Size property for Conditional Formatting	Dim fontSize As Variant\nDim fontType As Variant\nDim fontBold As Variant\nDim cellIn As Variant\n\nSub setVars()\n\n    With Range("A1")\n        fontSize = .Font.Size\n        fontType = .Font.Name\n        fontBold = .Font.Bold\n        cellIn = .Interior.Color\n    End With\n\n\nEnd Sub\n\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n\n    Application.ScreenUpdating = False\n    Application.EnableEvents = False\n\n    Dim r As Range\n    Set r = Range("A1:J10")\n\n    With r\n        .Font.Size = fontSize\n        .Font.Name = fontType\n        .Font.Bold = fontBold\n        .Interior.Color = cellIn\n    End With\n\n    With r.Rows(Target.Row)\n        .Interior.ColorIndex = 5\n        .Font.Bold = True\n    End With\n\n    With r.Columns(Target.Column)\n        .Interior.ColorIndex = 5\n        .Font.Bold = True\n    End With\n\n    Application.ScreenUpdating = True\n    Application.EnableEvents = True\n\nEnd Sub	0
16437681	16437509	How can I access variable from delegate?	public class ActionContext\n{\n    public Action Action;\n    public int Variable = 0;\n    public delegate void Foo(ref int i);\n\n    public ActionContext(ActionContext.Foo action)\n    {\n        Action = () => action(ref this.Variable);    \n    }\n}\n\n\n\npublic void Test()\n{\n    // I don't want provide ActionContext through delegate(ActionContext)\n    ActionContext context = new ActionContext(\n        (ref int variable) => variable = 10);\n\n    context.Action.Invoke();\n}	0
2790504	2790454	Deleting Row Method on GridView	protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)\n{\n  customer.Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString());\n  FillCustomerInGrid();\n}	0
12333259	12333149	Linq To SQL - How to disable loading of associations?	var result = datacontext.Families.Select( s => new { ID = s.ID, Name = s.Name, Comment = s.Comment});	0
10774845	10774735	How to add menu items in specific position in WPF?	myContextMenu.Items.Insert( newIndex, new MenuItem() {Header="Test"});	0
32294071	32294025	How can i delete space from text file and replace it semicolon?	string[] allLines = File.ReadAllLines(@"d:\test.txt");\nusing (StreamWriter sw = new StreamWriter(@"d:\test.txt"))\n{\n    foreach (string line in allLines)\n    {\n        if (!string.IsNullOrEmpty(line) && line.Length > 1)\n        {\n            sw.WriteLine(Regex.Replace(line,@"\s+",";"));\n        }\n    }\n}\nMessageBox.Show("ok");	0
27430399	27430151	Dapper and Varbinary(max) stream parameters	_memorystream.Seek(0, SeekOrigin.Begin);	0
8448568	8402839	Advancing Powerpoint Slideshow programatically with click animations	private void OnNextClicked(object sender, RoutedEventArgs e)\n{\n    oSlideShowView.Application.SlideShowWindows[1].Activate();\n    oSlideShowView.Next();\n}	0
2294188	2294153	A Builtin function to Convert Byte to String	string myString = Encoding.ASCII.GetString(bytes);	0
14990767	14986859	Set Root Namespace Prefix in an XDocument	XNamespace xmlns = "XSDName";\nXNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";\nXNamespace schemaloc = @"XSDName XSDName.xsd";\nXDocument xdoc = new XDocument(\n    new XElement(xmlns + "BaseReport",\n    new XAttribute(xsi + "schemaLocation", schemaloc),\n    new XAttribute(XNamespace.Xmlns + "ns1", xmlns),\n    new XAttribute(XNamespace.Xmlns + "xsi", xsi)));	0
18124476	18124168	Items doesn't appear in ListBox in C#, but in XAML yes	ObservableCollection<MyData> items = new ObservableCollection()\n\nitems.Add(new MyData());\n\nListBox1.ItemSource = items;	0
23238666	23238580	LINQ getting an item <t> from a collection	var selected = m_PersonCollection.Where(t => t.Active == true).FirstOrDefault();	0
19775967	19775858	Make Label visible in XAML	check.Visibility = Visibility.Visible;	0
14956099	14940180	Serializing an object containing an array	public class child\n{\n    public int id { get; set; }\n    public String name { get; set; }\n\n    public child(int id, string name)\n    {\n        this.id = id;\n        this.name = name;\n    }\n}	0
20446706	20446666	Is it possible to extract only particular values from a Dictionary (C#)?	double[] numbers = Users.Values.Select(v => v.number).ToArray();	0
3371974	3371821	Serializing A Custom BindableDictionary<TKey,TValue>?	List<KevValuePair<Tkey,Tvalue>>	0
1029649	1028605	LINQ: How to get items from an inner list into one list?	from parent in parents \nwhere parent.Children.Any (c => c.CategoryNumber==1)\nselect parent into p\nfrom child in p.Children\nwhere child.CategoryNumber == 2\nselect child	0
25113964	25113915	NullReferenceException unhandled by user code while changing XML document	nsmgr.AddNamespace("ns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03");\ndoc2.SelectSingleNode("/ns:Document/ns:CstmrCdtTrfInitn/ns:GrpHdr/ns:MsgId", nsmgr).InnerText = "some text";	0
10151258	10150808	Play MP3 file from app	WindowsMediaPlayer wmp = new WindowsMediaPlayer();\nStream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream("yourfile.mp3");\nstring temppath = Path.GetTempPath() + "\\temp.mp3";\nusing (Stream output = new FileStream (temppath, FileMode.Create))\n{\n   byte[] buffer = new byte[BUFFER_SIZE];\n   int read;\n\n        while ( (read= stream.Read(buffer, 0, buffer.Length)) > 0)\n        {\n            output.Write(buffer, 0, read);\n        }\n}\nwmp.URL = temppath;\nwmp.controls.play();	0
31745045	31744169	LINQ counting unique strings in a list and storing the values in a tuple	var lines = new List<string[]>\n    {\n        new[] { "That", "is", "is", "a", "cat" },\n        new[] { "That", "bat", "flew", "over", "the", "flew", "cat" }\n    };\n\n    var distinctWords = lines.SelectMany(strings => strings).Distinct().ToArray();\n\n    var result = (\n        from line in lines\n        let lineWords = line.ToArray()\n        let counts = distinctWords.Select(distinctWord => lineWords.Count(word => word == distinctWord)).ToArray()\n        select new Tuple<string[], int[]>(distinctWords, counts)\n    ).ToList();	0
30996775	30748094	How to modify list property without affecting other list property of same type?	foreach(myClass data in source)\n{\n    myClass tmpData = new myClass(){\n        Something = data.Something;            \n    };\n    myClass1.Add(tmpData);\n}	0
3539065	3539054	c# - how to copy a section of "byte[]" to another array?	var byteArray = new byte[] { 1, 0, 1 };\nvar startIndex = 1;\nvar length = 2;\n\nbyteArray.Skip(startIndex).Take(length).ToArray();	0
9863247	9863189	Improving a method by using LINQ	public IEnumerable<RoleAreasModel> Foo(Guid id)\n{\n   var mapper = new RolesMapper();\n   return from role in GetByUserGUID(id)\n          let areaRecord = RoleAreasService.Instance.GetRecord(RoleAreasRecord.Fields.ID, role.ID)\n          select new RoleAreasModel(areaRecord.Area, mapper.MapToModel(role), getAreaControllersData(areaRecord.ID));\n}	0
17350164	17350058	Converting a thresholded image into a byte array?	public static Byte[] BmpToArray(Bitmap value) {\n      BitmapData data = value.LockBits(new Rectangle(0, 0, value.Width, value.Height),   ImageLockMode.ReadOnly, value.PixelFormat);\n\n      try {\n        IntPtr ptr = data.Scan0;\n        int bytes = Math.Abs(data.Stride) * value.Height;\n        byte[] rgbValues = new byte[bytes];\n        Marshal.Copy(ptr, rgbValues, 0, bytes);\n\n        return rgbValues;\n      }\n      finally {\n        value.UnlockBits(data);\n      }\n    }	0
12385936	12385600	Showing images along with their names in listview	ListView.LargeIcon	0
33887579	33883881	How to read stored procedure output and return it as list	public List<yourClass> GetData()\n{\nusing (SqlConnection con = new SqlConnection(Global.Config.ConnStr))\n{\n\n    DataTable dt = new DataTable();\n    List<yourClass> details = new List<yourClass>();\n\n    SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);\n    cmd.CommandType = CommandType.StoredProcedure;\n\n    SqlDataAdapter da = new SqlDataAdapter(cmd);\n    da.Fill(dt);\n\n     foreach(DataRow dr in dt.Rows)\n            {\n                yourClass obj = new yourClass();\n\n                obj.fullname= dr["fullname"].ToString();\n                obj.email= dr["email"].ToString();\n\n                details.Add(obj);\n            }\n\n\n            return details;\n        }	0
12188523	12188383	Parsing a large XML file to multiple output xmls, using XmlReader - getting every other element	doc.readInnerXml()	0
15981728	15981703	How to convert byte[] to String with no encoding, no loss of data	string Convert(byte[] data)\n{\n    char[] characters = data.Select(b => (char)b).ToArray();\n    return new string(characters);\n}	0
15878923	15878719	MaskedTextBox - How put IBeam at the end, even if the user click anywhere?	mtb.SelStart = 0;\nmtb.SelLength = 0;	0
32576158	32566072	How can I bind to data being populated in another thread?	private void timer_updateGui_Tick(object sender, EventArgs e)\n{\n    lock(MyClass.dt)\n    {\n    chart_highLevel.DataSource = MyClass.dt.Copy();\n    }\n    chart_highLevel.DataBind(); // Update the databind\n\n}\n    public DataTable dt = {get; private set;}\nprivate void bw_analyser_DoWork(object sender, DoWorkEventArgs e)\n{\n    while(true)\n    {    \n        // ... populate 'values'\n        lock(dt)\n        {\n        dt.Rows.Add(values); // values are the data to fill the DataTable, dt          }\n    }\n}	0
11877823	11877801	Two Dimensional Array Insert from middle and shift	List < List < object > >	0
2540080	2540050	How is List<T> implemented in C#?	public int IndexOf(T item)\n{\n    return Array.IndexOf<T>(this._items, item, 0, this._size);\n}\n\npublic static int IndexOf<T>(T[] array, T value, int startIndex, int count)\n{\n    return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);\n}\n\ninternal virtual int IndexOf(T[] array, T value, int startIndex, int count)\n{\n    int num = startIndex + count;\n    for (int i = startIndex; i < num; i++)\n    {\n        if (this.Equals(array[i], value))\n            return i;\n    }\n    return -1;\n}	0
15789631	15789476	RegEx Replace string	var r = new Regex(@"(\s|,)*,(\s|,)*");	0
982337	982152	How can I get the assembly version as a integer in C#?	var version = Assembly.GetExecutingAssembly().GetName().Version();\n\nDebug.Assert(version.Major >= 0 && version.Major < 100)\nDebug.Assert(version.Minor >= 0 && version.Minor < 100)\nDebug.Assert(version.Build >= 0 && version.Build < 10000)\nDebug.Assert(version.Revision >= 0 && version.Revision < 100)\n\nlong longVersion = version.Major * 100000000L + \n                   version.Minor * 1000000L + \n                   version.Build * 100L + \n                   version.Revision;\n\nint intVersion  = (int) longVersion;\n\nDebug.Assert((long)intVersion == longVersion)	0
6620011	6619931	How should an array be passed to a Javascript function from C#?	System.Web.Script.Serialization.JavaScriptSerializer oSerializer = \n         new System.Web.Script.Serialization.JavaScriptSerializer();\nstring barJson = oSerializer.Serialize(bar.ToArray<string>());\n\nmyWebBrowser.InvokeScript("myJsFunc", new object[] { foo.Text, barJson});	0
4732938	4732818	How to check that string contains is english only	var regex = new Regex("[a-zA-Z0-9 ]*");\n        var result = str.Split(',')\n                        .Where(s => regex.Match(s).Value == s)\n                        .ToArray();	0
3274922	3274897	Simple rating algorithm to sorting results according to user query	from urls in _context.Urls	0
17102005	17101889	How to Create Find in Notepad in C#	textBox1.Select(idx, text.Length);	0
16699065	16698849	c# copy text till end of line richtextbox	string settings = string.Empty;\nIEnumerable<string> lines = File.ReadLines(myPath); //reads all lines of text file\nforeach (string s in lines) //iterate thru all lines\n{\n    if s.Contains("=")\n    {\n        settings = s.substring(s.IndexOf("=")); //get substring from "=" to end of line\n        break; //break out of the loop\n    }\n}	0
34355328	34355277	How to Write text box text into text file in c#?	System.IO.File.WriteAllText(filepath, text);	0
13245732	13245505	How to prevent multiple user login from the same user id in asp.net using cache?	if(HttpContext.Current.Session!=null){\n//Proceed with xyz\n}	0
21600845	21600758	how to retrieve data from dictionary type list?	foreach(Dictionary<string, string> dict in products)	0
14728943	14728843	How do I define a mapped code first member that will be ignored by wcf	[DataContract]\npublic class Foo\n{\n    [DataMember]\n    public string NonIgnoredProperty { get; set; }\n\n    [IgnoreDataMember]\n    public string IgnoredProperty { get; set; }\n\n    // ....\n}	0
20651557	20651101	How to implement the interface like this in VB.net	Partial Public Class LoginUserControl\n    Inherits System.Web.UI.UserControl\n    Implements IView\n    Public Shadows Event Load As EventHandler Implements IView.Load\n    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n\n    End Sub\n\nEnd Class\n\n\nPublic Interface IView\n    Event Load As EventHandler\nEnd Interface	0
22681325	22662440	How to upload an image in Windows 8.1 metro application?	if (rootPage.EnsureUnsnapped())\n  {\n  FileOpenPicker openPicker = new FileOpenPicker();\n  openPicker.ViewMode = PickerViewMode.Thumbnail;\n  openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\n  openPicker.FileTypeFilter.Add(".jpg");\n  openPicker.FileTypeFilter.Add(".jpeg");\n  openPicker.FileTypeFilter.Add(".png");\n\n  StorageFile file = await openPicker.PickSingleFileAsync();\n  if (file != null)\n  {\n    // Application now has read/write access to the picked file\n    //OutputTextBlock.Text = "Picked photo: " + file.Name;\n  }\n  else\n  {\n    //OutputTextBlock.Text = "Operation cancelled.";\n  }\n}	0
19546870	19546843	Select all in TextBox by clicking a button	myTextBox.Focus();	0
29753534	29676611	Deadlocks on single table with no transaction (?) on update or insert statements	Deadlock Id 29756: Process (Familyid 0, Spid 282) was waiting for a 'exclusive page' lock on page 26700113 of table 'test_deadlock_t' in database 'xxx' but process (Familyid 0, Spid 1051) already held a 'exclusive page' lock on it.\nDeadlock Id 29756: Process (Familyid 0, Spid 1051) was waiting for a 'exclusive page' lock on page 29892374 of table 'test_deadlock_t' , indid 1 in database 'xxx' but process (Familyid 0, Spid 282) already held a 'exclusive page' lock on it.	0
2704352	2704340	How to delete characters and append strings?	int i = 123;\nstring n = "N" + i.ToString().PadLeft(8, '0');	0
11342639	11342292	Path issue with wkhtmltopdf.exe to convert HTML file to PDF	var url = Request.Url.GetLeftPart(UriPartial.Authority) + "/PrintArticle.aspx?articleID=" + Request["articleID"] + "&download=yes&Language=" + Request["Language"];	0
25107491	24974528	Sorting List<T> on a member of type<U> decided at runtime	if (propertyName.Contains('.'))\n    {\n            // support to be sorted on child fields.\n            String[] childProperties = propertyName.Split('.');\n            property = typeof(TEntity).GetProperty(childProperties[0]);\n            propertyAccess = Expression.MakeMemberAccess(parameter, property);\n            for (int i = 1; i < childProperties.Length; i++)\n            {\n                    property = property.PropertyType.GetProperty(childProperties[i]);\n                    propertyAccess = Expression.MakeMemberAccess(propertyAccess, property);\n            }\n    }	0
26690257	26689983	c# 6 Primary ctor	public class Point\n{\n    [CompilerGenerated]\n    [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n    private readonly int \u003CX\u003Ek__BackingField;\n    [CompilerGenerated]\n    [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n    private readonly int \u003CY\u003Ek__BackingField;\n\n    public int X\n    {\n      get\n      {\n        return this.\u003CX\u003Ek__BackingField;\n      }\n    }\n\n    public int Y\n    {\n      get\n      {\n        return this.\u003CY\u003Ek__BackingField;\n      }\n    }\n\n    public Point(int x, int y)\n    {\n      this.\u003CX\u003Ek__BackingField = x;\n      this.\u003CY\u003Ek__BackingField = y;\n      base.\u002Ector();\n    }\n}	0
20687620	20687538	Which data structure to use for two elements in C#?	Tuple<TOne, TTwo> IndexCombiner<TOne, TTwo>(\n    Table table,\n    Func<Table, TOne> selectorOne,\n    Func<Table, TTwo> selectorTwo)\n{\n    return Tuple.Create(selectorOne(table), selectorTwo(table));\n}	0
10360753	6835006	How can I copy the pixel data from a Bitmap with negative stride?	((byte*)scan0 + (y * stride))	0
23907203	23906990	How to display a number with a given number of decimal places	decimal d = 1m;\nint decimalPlaces = 2;\nstring format = decimalPlaces == 0 \n            ? "#,##" \n            : "#,##." + new string('0', decimalPlaces);\nstring result = d.ToString(format); // 1.00	0
3616302	3616208	How do i call a stored procedure with parameters from c# code behind	using (SqlConnection conn = new SqlConnection("connection string goes here"))\nusing (SqlCommand comm = new SqlCommand("tesproc", conn))\n{\n    comm.CommandType = CommandType.StoredProcedure;\n    comm.Parameters.AddWithValue("@a", 0.1);\n    // etc\n\n    conn.Open();\n\n    using (SqlDataReader reader = comm.ExecuteReader())\n    {\n        while (reader.Read())\n        {\n            int id = reader.GetInt32(reader.GetOrdinal("id"));\n            // etc\n        }\n    }\n}	0
16356367	16356324	XML to JSON Conversion seems to add extra backslashes	(JAVASCRIPT)\nvar str = JSON.stringify(data);\nreturn JSON.stringify(str);	0
14478639	14478556	DateTime.ParseExact to sortable format throws exception	updateBook.orderFrom = DateTime.Now;	0
7587470	7477261	Send multiple WebRequest in Parallel.For	response.Close()	0
568477	553972	Word Wrap in ICSharpcode TextEditor	ICSharpCode.TextEditor	0
9230788	9229980	How to get all mshtml.IHTMLDivElement from IHTMLDocument2?	mshtml.IHTMLDocument2 doc = (IHTMLDocument2)MainBrowser.Document;\n\nif (null != doc)\n{\n     foreach (IHTMLElement element in doc.all)\n     {\n           if (element.id == "wrapper")\n           {\n                 HTMLDivElement container = element as HTMLDivElement;\n\n                 dynamic dd = container;\n\n                 string result = dd.IHTMLElement_innerHTML;\n\n                 // You get ANY member of HTMLDivElementClass\n\n                  break;\n             }\n     }\n}	0
17918857	17918798	Winforms preferences values	Settings.Default.path= subForm2.rep();\n\nSettings.Default.Save();	0
27505421	27505306	Adding attributes to radio buttons of radiobuttonlist	private void FireEventOnLoad()\n{\n\n    foreach (ListItem item in rblAmit.Items)\n    {\n        item.Attributes.Add("onclick", "javascript:DisplayAlert();");\n    }\n\n    if (rblAmit.Items.FindByText("Senior") != null)\n    {\n        rblAmit.Items.FindByText("Senior").Selected = true;\n    }\n}	0
13817187	13817122	How to store Files on Shared network drive in c#	var fileStream = File.Create(@"\\server\c\DTA\");\n...	0
15311249	15311125	Facebook C# SDK mapping places to a model	[DataContract]\n public class Place\n {\n    [DataMember(Name = "location")]\n    public Location Locations { get; set; }\n\n    [DataMember(Name = "category")]\n    public string Category { get; set; }\n\n    [DataMember(Name = "name")]\n    public string Name { get; set; }\n\n    [DataMember(Name = "id")]\n    public string ID { get; set; }\n}	0
3688240	3688195	HTMLEncode in Winforms	System.Web.HttpUtility.HtmlEncode(foo);	0
22316743	20793938	How to add folder into windows indexing list with windows search api	Uri path = new Uri(location);\n\nstring indexingPath = path.AbsoluteUri;\n\nCSearchManager csm = new CSearchManager();\nCSearchCrawlScopeManager manager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();\nmanager.AddUserScopeRule(indexingPath, 1, 1, 0);\nmanager.SaveAll();	0
5746854	5746700	Include javascript from assembly in MVC	string rsname = "MyAssembly.my_script.js";\n\nstring url = ((Page)HttpContext.CurrentHandler)\n    .ClientScript.GetWebResourceUrl(this.GetType(), rsname);	0
17512354	17512249	Get directory size with threshold	int totalSize = 0;\ndirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)\n     .TakeWhile(fi => (totalSize += fi.Length) < threshold)\n     .Count();      // Force query to execute\n\nreturn (totalSize <= threshold) ? totalSize : -1;	0
10012815	10012786	How to remove a part of the string	test = test.Substring(7);	0
3862433	3844969	Changing Resolution in OpenTK	GL.Viewport(gameWindow.ClientRectangle);	0
10378210	10265241	AutoSuggestion in a WPF combobox	Combobox.IsDropDownOpen = true	0
25141117	25141018	get the source of image when user clicks it in c#	private void selected(object sender, MouseButtonEventArgs e)\n{\n    Image newimage = new Image();\n    newimage.Source = ((Image)sender).Source;\n}	0
656396	656350	Disable context menu in Internet Explorer control	WebBrowser browser;\nbrowser.Document.ContextMenuShowing += new HtmlElementEventHandler(MyCustomContextMenuMethod);	0
22647793	22647548	Exception while parsing negative double numbers in C#	var climateString = "?2.8"; \n\nvar fmt = new NumberFormatInfo();\nfmt.NegativeSign = "?";\nvar number = double.Parse(climateString, fmt);	0
5348172	5348049	How to Update database using linq and EF	public ActionResult Deposit(DepositTicket dt)\n{\n    using (var db = new MatchGamingEntities())\n    {\n        MembershipUser currentUser = Membership.GetUser();\n        Guid UserId = (Guid)currentUser.ProviderUserKey;\n        var MyAccount = db.Accounts.SingleOrDefault(a => a.UserId == UserId);\n\n        BankTransaction transaction = new BankTransaction();\n        transaction.Amount = dt.Amount;\n        transaction.AccountId = MyAccount.AccountId;\n        transaction.Created = DateTime.Today;\n        transaction.TransactionType = "Credit";\n        Debug.Write(String.Format("Amount: {0} AccountId: {1}", transaction.Amount, transaction.AccountId);\n        db.BankTransactions.AddObject(transaction);\n        MyAccount.Balance += transaction.Amount;\n\n        db.SaveChanges();\n        return View();\n    }	0
6373674	6373645	C# WinForms: How to set Main function STAThreadAttribute	Invoke((Action)(() => { saveFileDialog.ShowDialog() }));	0
20751741	20750901	Convert various date formats to MM/dd/yyyy in C#	DateTime originalDate,dt;\n    String msDate = "24-12-2013";\n    String[] format = {"d-M-yyyy","M/d/yyyy"};\n    CultureInfo enUS = new CultureInfo("en-US");\n    foreach (var frmt in format)\n    {\n        if(DateTime.TryParseExact(msDate, frmt, enUS, DateTimeStyles.None,out dt))\n        {\n            originalDate = dt;\n            Console.WriteLine(originalDate.ToString());\n        }\n     }	0
10822290	10744827	How to change the name of a NetworkAdapter in c#?	string fRegistryKey = string.Format(@"SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{0}\Connection", NIC_GUID);\n\nRegistryKey RegistryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, @"\\" + Server.Name);\n\nRegistryKey = RegistryKey.OpenSubKey(fRegistryKey, true); //true is for WriteAble.\n\nRegistryKey.SetValue("Name", "<DesiredAdapterName>");	0
944670	944619	How to copy file from local system to other system in C# (windows app)?	File.Copy(\n    @"C:\localpath\file.hlp", \n    @"\\remotemachinename\localpathonremotemachine\file.hlp");	0
3298228	3298201	using RegEx to replace string	Regex r = new Regex(@"<(.|\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);	0
14436034	14435803	xpath query to select data in range	/AppXmlLogWritter/LogData[substring(LogDateTime, 1, 8) >= 20130115 \n                              and substring(LogDateTime, 1, 8) <= 20130116]	0
30612987	30612485	How to retrieve all topics from Azure Bus Service?	string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");\nNamespaceManager nm = NamespaceManager.CreateFromConnectionString(connectionString);\nIEnumerable<TopicDescription> topicList=nm.GetTopics();\n        foreach(var td in topicList)\n        {\n            Console.WriteLine(td.Path);\n        }	0
8239650	8238578	Get Value selected dropdownlist option	Request.Form[ddl.UniqueID]	0
13051782	13049039	How to efficiently Add Many Items in Combobox in WPF	using (Dispatcher.DisableProcessing())\n{\n  for(int i=0;i<=255;i++)\n    _ChannelBitLengthList.Add(i.ToString());\n}	0
9332379	9332353	C# Regular Expression Help Needed	Regex.Replace(myString, "<[^>]*>", "");	0
32457698	32457299	Display the values in Bytes and MB	static void Main()\n{    \n    DialogResult dialogResult = MessageBox.Show("There is " + toReadableSize(freeSpaceInC) + " free in C: and " + toReadableSize(freeSpaceInD) + " free in D:. Do you want to continue the installation?", "MATLAB_R2008a_ENU_EU", MessageBoxButtons.YesNo);\n\n    if (dialogResult == DialogResult.Yes)\n    {\n        Form1 fm1 = new Form1();\n        fm1.ShowDialog();\n        fm1.Close();\n    }            \n    else if (dialogResult == DialogResult.No)\n    {\n        Application.Exit();\n    }\n}\n\nprivate static string toReadableSize(int size)\n{\n    if(size < 1024)\n        return size + "B";\n\n    if(size < 1024*1024)\n        return Math.Round(((float)size / 1024), 2) + "KB";\n\n    if(size < 1024*1024*1024)\n        return Math.Round(((float)size / (1024*1024)), 2) + "MB";\n\n    return Math.Round(((float)size / (1024*1024*1024)), 2) + "GB";\n}	0
14019067	14019054	How to Changing ListView inside backgroundworker? Cross-Thread Error	ListViewItem abg = new ListViewItem(isititle3);\n\n\n     if (listView1.InvokeRequired)\n                    listView1.Invoke(new MethodInvoker(delegate\n                    {\n           listView1.Items.Add(abg);           \n\n                    }));\n                else\n           listView1.Items.Add(abg);	0
13863742	13863541	WPF Nested ListViews - selectedValue of parent ListView	private void handleInner(object o, RoutedEventArgs e)\n{\n    InnerControl innerControl = e.OriginalSource as InnerControl;\n    if (innerControl  != null)\n    {\n        //do whatever\n    }\n    e.Handled = false;\n}	0
24629083	24603994	Find First Unique Number	Ticks\n   Min   Max     Avg  Actual\n    2  14502     584  -3     Original\n    2    919      40  -3     if (y.Any()) actual = y[0];\n    2   1423      60  -3     a.GroupBy(g => g).Where(w => w.Count() == 1)\n                                            .Select(s => s.Key)\n                                            .FirstOrDefault();\n    2   1553      65  -3     a.ToLookup(i => i).First(i => i.Count() == 1).Key;\n    2    317      15  -3     a.GroupBy(i => i).First(i => i.Count() == 1).Key;	0
20283738	20281379	How to configure SMTP mail setting	foreach (var to in _pToMailId)\n            {\n                message .To.Add(to);\n            }	0
262112	244408	Deleting items from one collection in another collection	foreach(TypeA objectA in listA){\n    listB.RemoveAll(objectB => objectB.Id == objectA.Id);\n}	0
32209254	32195745	update the database from package manager console in code first environment	public class ApplicationDbContext : DbContext\n{\n    public ApplicationDbContext()\n        : base("MyConnection", throwIfV1Schema: false)\n    {\n        Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MyObjextContextMigration>());\n    }\n    ...	0
33702560	33702153	Fetch only text from email html body	var service = new ExchangeService\n{\n    Credentials = new WebCredentials("somename", "somepass"),\n    Url = new Uri("someurl")\n};\n\nvar itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties)\n{\n    RequestedBodyType = BodyType.Text\n};\n\nvar itemview = new ItemView(1) {PropertySet = itempropertyset};\nvar findResults = service.FindItems(WellKnownFolderName.Inbox, itemview);\nvar item = findResults.FirstOrDefault();\nitem.Load(itempropertyset);\nConsole.WriteLine(item.Body);	0
26619737	26619714	Reading user input into a list through a class member	Vechicle v = new Vechicle();\nv.Make = 'Ford';\nv.Year = 1990;\nv.Model = 'Sedan'\nMotorDeats.Add(v);	0
14966383	14966153	No data passed to a "Create" view object	public string m_Address { get; set; }	0
33451902	33451867	How do I generate a preset amount of random numbers?	int numberOfElems = int.Parse(userImput.Text);\nRamdom r = new Random();\nList<int> myNumbers = new List<int>();\nfor(int i=0; i<numberOfElems; ++i)\n{\n   int number = r.Next(0,100); // will bring a random number from 0 to 99\n   myNumbers.Add(number);\n}	0
16175876	16172971	Show Radius of Ellipse - WPF	Path path = new Path();\n        EllipseGeometry eg = new EllipseGeometry();\n        eg.Center = new Point(left + side / 2, top + side / 2);\n        eg.RadiusX = side / 2;\n        eg.RadiusY = side / 2;\n        path.Data = eg;\n        paths.Add(path);\n        canvas1.Children.Add(paths[paths.Count - 1]);\n        .\n        .\n        path = new Path();\n        borderColor.Color = Colors.Red;\n        path.Stroke = borderColor;\n        path.StrokeThickness = 2;\n        LineGeometry r = new LineGeometry();\n        r.StartPoint = eg.Center;\n        r.EndPoint = new Point(eg.Center.X + eg.RadiusX, eg.Center.Y);\n        path.Data = r;\n        paths.Add(path);\n        canvas1.Children.Add(paths[paths.Count - 1]);	0
5426587	5426582	Turn byte into two-digit hexadecimal number just using ToString?	myByte.ToString("X2")	0
4694528	4694346	C# sp2010 adding items to a list	ClientContext clientContext = new ClientContext("http://sp2010Server/sites/mySite");\nSP.List oList = clientContext.Web.Lists.GetByTitle("Site Requests");\n\nListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();\nListItem oListItem = oList.AddItem(itemCreateInfo);\noListItem["Title"] = "title";\noListItem["Description"] = "description";\noListItem["Url"] = "someUrl";\n\noListItem.Update();\n\nclientContext.ExecuteQuery();	0
14147492	14142659	Dynamic XML/JSON from WCF Service	[DataContract(Name = "Continent")]\npublic class Entity\n{\n    [DataMember]\n    public int Id { get; set; }\n\n    [DataMember]\n    public string Name { get; set; }\n}	0
5233193	5232734	how to make textbox who only allow integer value?	private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)\n{\n  // Filter out non-digit text input\n  foreach (char c in e.Text) \n    if (!Char.IsDigit(c)) \n    {\n      e.Handled = true;\n      break;\n    }\n}	0
21846893	21846655	How to add a column to a List<> at run run time	var missionIdList = new List<object>();\n\nwhile (sqlreader.Read())\n{\n   var obj = new { c1 = Convert.ToInt32(sqlreader[0].ToString()), \n                   c2 = Convert.ToInt32(sqlreader[1].ToString()),\n                   c3 = Convert.ToInt32(sqlreader[2].ToString()),\n                   uid = uid };\n   missionIdList.Add(obj);\n}	0
4107867	3526585	Determine if an object exists in a S3 bucket based on wildcard	public bool Exists(string fileKey, string bucketName)\n{\n        try\n        {\n            response = _s3Client.GetObjectMetadata(new GetObjectMetadataRequest()\n               .WithBucketName(bucketName)\n               .WithKey(key));\n\n            return true;\n        }\n\n        catch (Amazon.S3.AmazonS3Exception ex)\n        {\n            if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)\n                return false;\n\n            //status wasn't not found, so throw the exception\n            throw;\n        }\n}	0
21270038	21269122	Read Large XML file using XPath	public void ParseXML(string XMLPath)\n    {\n        XmlReader xmlReader = XmlReader.Create(XMLPath);\n\n        while (xmlReader.Read())\n        {\n            if (xmlReader.Name.Equals("FileLocation") && (xmlReader.NodeType == XmlNodeType.Element))\n            {\n                string url = xmlReader.GetAttribute("Url");\n            }\n        }\n\n    }	0
3207183	3207137	Safely Closing A Thread	var thread = new Thread(\n    ()=>\n    {\n        MessageBox.Show("Buy pizza, pay with snakes");\n    });\nthread.IsBackground = true;\nthread.Start();	0
613075	613068	SQL Server Timeout troubleshooting	WITH RECOMPILE	0
14119735	14119228	C# how to label y axis as string rather than numbers?	private void chart1_Customize(object sender, EventArgs e)\n    {\n        foreach (var label in chart1.ChartAreas[0].AxisY.CustomLabels)\n        {\n            label.Text = (string)char.ConvertFromUtf32(Int32.Parse(n) + 64);\n        }\n    }	0
11859379	11859282	Convert separator to enter character	string.Join(@"|\r\n", sOutput, sOtherFaults, sClosedFault, sTemp);	0
3569843	3569811	How to know if a PropertyInfo is a collection	if ( typeof( IEnumerable ).IsAssignableFrom( pi.PropertyType ) )	0
6319790	6319771	Using LINQ to strip a suffix from a string if it contains a suffix in a list?	var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();\nif (firstMatchingSuffix != null)\n    myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));	0
4042293	4042229	Linq-to-sql logic pain	model.Ideas = ideaList.Where(\n                  idea => idea.Tags.Any(\n                        tag => tag.Name == Name)).ToList();	0
20413838	19636569	Changing dimensions of image capturing using DirectShow	IntPtr m_ip = IntPtr.Zero;\nm_ip = capture.Click();\nBitmap b = new Bitmap(640, 480, capture.Stride, PixelFormat.Format24bppRgb, m_ip);\nb = ResizeBitmap(b,220,220); //The size of your box\nb.RotateFlip(RotateFlipType.RotateNoneFlipY);\npictureBox2.Image = b;\n\nprivate static Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height)\n{\n   Bitmap result = new Bitmap(width, height);\n   using (Graphics g = Graphics.FromImage(result))\n   g.DrawImage(sourceBMP, 0, 0, width, height);\n   return result;\n}	0
26935141	26934325	How to get Simple injector to auto resolve interface when it only has one concrete?	ScopedLifestyle scopedLifestyle = new WebApiRequestLifestyle();\n\nvar assembly = typeof(YourRepository).Assembly;\n\nvar registrations =\n    from type in assembly.GetExportedTypes()\n    where type.Namespace == "Acme.YourRepositories"\n    where type.GetInterfaces().Any()\n    select new\n    {\n        Service = type.GetInterfaces().Single(),\n        Implementation = type\n    };\n\nforeach (var reg in registrations)\n    container.Register(reg.Service, reg.Implementation, scopedLifestyle);	0
2469897	2468979	Encrypting socket communication with RSA in C#	System.Net.Security.SslStream	0
15473861	15461379	Get my actual DNS	NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();\n    foreach (NetworkInterface ni in nics)\n    {\n        if (ni.OperationalStatus == OperationalStatus.Up)\n        {\n            IPAddressCollection ips = ni.GetIPProperties().DnsAddresses;\n            foreach (System.Net.IPAddress ip in ips)\n            {\n                MessageBox.Show(ip.ToString());\n            }\n        }\n    }	0
19674617	19674532	Enum to int best practice	enum MyEnum\n{\n    Foo = 0,\n    Bar = 100,\n    Baz = 9999\n}	0
7059357	7059140	How do I load a JavaScript file with Jint in C#?	StreamReader streamReader = new StreamReader("test.js");\n        string script = streamReader.ReadToEnd();\n        streamReader.Close();\n\n        JintEngine js = new JintEngine();\n\n        js.Run(script);\n        object result = js.Run("return status;");\n        Console.WriteLine(result);\n        Console.ReadKey();	0
4651427	4506492	How to cause AggregateException with TPL?	using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nnamespace SomeAsyncStuff\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Task.Factory.StartNew(() => { throw new NullReferenceException("ex"); });\n\n            // give some time to the task to complete\n            Thread.Sleep(3000);\n\n            GC.Collect();\n            // GC.WaitForPendingFinalizers();\n            Console.WriteLine("completed"); \n        }\n    }\n}	0
6354092	6354049	How to make auto casting between list item?	obj1item.AddRange(v.Cast<obj1>())	0
5096638	5096627	converting a string to a list of integers	List<int> foo = num_list.Split(';').Select(num => Convert.ToInt32(num)).ToList();	0
17792200	17792159	Returning a String in an Async Event Handler	public void delegate OnError(object sender, string message);\npublic event OnError OnErrorEvent; \n\n...\n\n\n\n           client.DownloadStringCompleted += (senders, ex) =>\n            {\n                if (ex.Error == null)\n                {\n                    //Process the result...\n                    return ex.Result;\n                }\n                else\n                {\n                   if(OnErrorEvent != null)\n                   OnErrorEvent(this, "An error occurred. The details of the error: " + ex.Error;);\n                }\n            };	0
14632540	14632446	How to throw an ArgumentNullException before calling other constructor	private MyClass(IWhatEver a)\n    {\n        if (a == null)\n        {\n            throw new ArgumentNullException("a");\n        }\n\n        // the cool code comes here, I could put it into\n        // the CallMeFromConstructor method but is there another way?\n    }\n\n    public MyClass(IWhatEver a, ISomeThingElse b) : this(a)\n    {\n        if (b == null)\n        {\n            throw new ArgumentNullException("b");\n        }\n    }\n\n    public MyClass(IWhatEver a, IAnotherOne b) : this(a)\n    {\n        if (b == null)\n        {\n            throw new ArgumentNullException("b");\n        }\n    }	0
17218372	17218150	How to I read any file in binary using C#?	using (var binReader = new System.IO.BinaryReader(System.IO.File.OpenRead("PATHIN")))\nusing (var binWriter = new System.IO.BinaryWriter(System.IO.File.OpenWrite("PATHOUT")))\n{\n    byte[] buffer = new byte[512];\n    while (binReader.Read(buffer, 0, 512) != 0)\n    {\n        binWriter.Write(buffer);\n    }\n}	0
2641304	2641242	Match multiple lines with a regex in C#	MatchCollection matches = Regex.Matches( text, @"([-]+\d{24})\n                                                 (?<Content>.*?)\n                                                 (?=\1)", \n                                         RegexOptions.IgnorePatternWhitespace | \n                                         RegexOptions.Singleline );\n\nforeach ( Match match in matches )\n{\n    Console.WriteLine( \n        string.Format( "match: {0}\n\n", \n                       match.Groups[ "Content" ].Value ) );\n}	0
4383654	4383635	In C#, why can't I pass a StringReader to a method with a Stream parameter?	var xmlBytes = Encoding.UTF8.GetBytes(Request.Form["mXML"]);\nvar ms = new MemoryStream(xmlBytes);\nvar reply = MStatic.DeserializeMatch(ms);	0
7874322	7874294	Creating a default constructor on a subclass	//Default constructor\n    public SoccerPlayer()\n        : base("default name", 0, default(Sexs))\n    {\n\n    }	0
482984	100235	Looking for a simple standalone persistent dictionary implementation in C#	System.Collections.Generic	0
10225829	10225384	Want to show value of slider in textblock?	Text="{Binding ElementName=YourSlider,Path=Value}"	0
3824935	3824876	How to drawn my own progressbar on winforms?	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MyProgressBar : Control {\n    public MyProgressBar() {\n        this.SetStyle(ControlStyles.ResizeRedraw, true);\n        this.SetStyle(ControlStyles.Selectable, false);\n        Maximum = 100;\n        this.ForeColor = Color.Red;\n        this.BackColor = Color.White;\n    }\n    public decimal Minimum { get; set; }  // fix: call Invalidate in setter\n    public decimal Maximum { get; set; }  // fix as above\n\n    private decimal mValue;\n    public decimal Value {\n        get { return mValue; }\n        set { mValue = value; Invalidate(); }\n    }\n\n    protected override void OnPaint(PaintEventArgs e) {\n        var rc = new RectangleF(0, 0, (float)(this.Width * (Value - Minimum) / Maximum), this.Height);\n        using (var br = new SolidBrush(this.ForeColor)) {\n            e.Graphics.FillRectangle(br, rc);\n        }\n        base.OnPaint(e);\n    }\n}	0
13276752	13276634	Visual Studio - Keeping command window open	Process.Start("cmd.exe", "/K \"dir\"");	0
14958860	14958821	How do i close shut down my application from another Form?	Application.Exit();	0
12477454	12477422	How to use returned linq variable?	var value = selectedSiteType.First(); \n   // returns the first item of the collection\n\n   var value = selectedSiteType.FirstOrDefault(); \n   // returns the first item of the collection or null if none exists\n\n   var value = selectedSiteType.Single(); \n   // returns the only one item of the collection, exception is thrown if more then one exists\n\n   var value = selectedSiteType.SingleOrDefault(); \n   // returns the only item from the collection or null, if none exists. If the collection contains more than one item, an exception is thrown.	0
9246234	9231347	Seeing Trends in Code Metrics with NDepend	from t in JustMyCode.Types\nwhere t.IsPresentInBothBuilds() &&\n      t.CodeWasChanged()\nlet tOld = t.OlderVersion()\n\nlet newLoC = t.NbLinesOfCode  \nlet oldLoC = tOld.NbLinesOfCode\nlet newCC = t.CyclomaticComplexity\nlet oldCC = tOld.CyclomaticComplexity\nlet newCov = t.PercentageCoverage\nlet oldCov = tOld.PercentageCoverage\nwhere newLoC > oldLoC || newCC > oldCC || newCov < oldCov\nselect new { t, newLoC, oldLoC, newCC, oldCC, newCov, oldCov }	0
13829641	13829496	LINQ method to find the value for a specific key without looping? (Parsing a json in C#)	for (int i = 0; i < Obj.items.Length; i++)\n{\n    Obj.items[i].id //do something with this here\n}	0
11949288	11933760	How to get last N documents from collection in mongo?	SortByBuilder sbb = new SortByBuilder();\nsbb.Descending("_id");\nvar allDocs = collection.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(N);	0
19634069	19633945	RichTextBox --> Change Font for specific line	string[] textBoxLines = richTextBox1.Lines;\nfor (int i = 0; i < textBoxLines.Length; i++)\n{\n    string line = textBoxLines[i];\n    if (line.StartsWith("-->"))\n    {\n        richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexFromLine(i);\n        richTextBox1.SelectionLength = line.Length;\n        richTextBox1.SelectionFont = yourFont;\n    }\n}\nrichTextBox1.SelectionLength = 0;//Unselect the selection	0
7445491	7417259	Facebook SDK - how to add fields in C#	categories = new[] { "city", "country", "state_province" }	0
14654321	14648891	Windows 8 c# save a camera's picture on local storage	private async void Camera_Clicked(object sender, TappedRoutedEventArgs e)\n{       \n   CameraCaptureUI camera = new CameraCaptureUI();\n   camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);\n   StorageFile photo = await camera.\n                          CaptureFileAsync(CameraCaptureUIMode.Photo);\n\n   if (photo != null)\n   {\n      var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("some_file_name.jpg");\n      if (targetFile != null)\n      {\n         await photo.MoveAndReplaceAsync(targetFile);                 \n      }\n   }\n}	0
21342813	21342765	Most efficient way to make duplicates unique in collection	List<string> values = new List<string> { "item1", "item1", "item1" };\n\n        values.Sort();\n\n        string previousValue = string.Empty; \n        int number = 1; \n        for(int i = 0 ; i < values.Count; i ++) \n        {\n            if (values[i].Equals(previousValue))\n            {\n                previousValue = values[i]; \n                values[i] = values[i] + "-" + number;\n                number++;\n            }\n            else\n            {\n                previousValue = values[i]; \n                number = 1; \n            }\n\n        }	0
17428923	17428853	Updating specific things in an XML file	XDocument xdoc = XDocument.Load(path_to_xml); // load xml file\n// query for data you want to update\nvar experience = xdoc.Root.Attribute("experience");\nexperience.SetValue(42); // update data\nxdoc.Save(path_to_xml); // save updated data	0
4460708	4460654	Best Practice: Convert LINQ Query result to a DataTable without looping	// Query the SalesOrderHeader table for orders placed \n// after August 8, 2001.\nIEnumerable<DataRow> query =\n    from order in orders.AsEnumerable()\n    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)\n    select order;\n\n// Create a table from the query.\nDataTable boundTable = query.CopyToDataTable<DataRow>();	0
1161671	1161412	Creating a new Guid inside a code snippet using c#	Public Sub InsertPartialGuid()            \n        Dim objSel As TextSelection = DTE.ActiveDocument.Selection        \n        Dim NewGUID As String = String.Format("{0}", (System.Guid.NewGuid().ToString().ToUpper().Split("-")(0)))\n        objSel.Insert(NewGUID, vsInsertFlags.vsInsertFlagsContainNewText)\n        objSel = Nothing\n    End Sub	0
2498492	2498432	C# Windows application prevents Windows from shutting down / logging off	public Form1()\n{\n    InitializeComponent();\n\n    this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);\n}\n\nvoid Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n    // Or any of the other reasons suitable for what you want to accomplish\n    if (e.CloseReason == CloseReason.WindowsShutDown)\n    {\n        //Stop your infinite loop\n    }\n}	0
21617778	21617643	How can I get this regex to allow spaces	Regex strPattern = new Regex(@"^[]0-9A-Za-z &[@!*(){}:?.,^%#$~`;'_/\\-]*$");	0
22675718	22675675	How can I convert seconds to hours minutes and seconds?	TimeSpan myTimeSpan = TimeSpan.FromSeconds(9755);\nConsole.WriteLine("Hours: " + myTimeSpan.Hours); // 2\nConsole.WriteLine("Minutes: " + myTimeSpan.Minutes); // 42\nConsole.WriteLine("Seconds: " + myTimeSpan.Seconds); // 35	0
6557601	6557577	Rename File open by self	using (StreamWriter sw = new StreamWriter(new FileStream(fileName1, FileMode.Create)))\n{\n  sw.WriteLine("before");\n  sw.Close();\n}\n\nFile.Move(fileName1, fileName2);\n\nusing (StreamWriter sw = new StreamWriter(new FileStream(fileName2, FileMode.Append)))\n{\n  sw.WriteLine("after");\n}	0
16175612	16175454	Two lists of DateTimes - searching for chains of "bumps"	If diff(X[i],Y[j]) < 60 "Output something";\n\nIf (X[i]<Y[j])i++;\nElse j++;	0
4509993	4509700	Moving from string array into datarow	// Declare a DataTable object.\nDataTable dt = new DataTable();\n\n// Add some columns to the DataTable\ndt.Columns.Add("StringHolder");\n\n// Now suppose , you are having 10 items in your string array\nforeach(string str in strArray)\n{\n    DataRow drow = dt.NewRow() ;   // Here you will get an actual instance of a DataRow\n    drow ["StringHolder"] = str;   // Assign values \n    dt.Rows.Add(drow);             // Don't forget to add the row to the DataTable.             \n}	0
14254009	14253815	Windows Service cannot create a text file	string path = @"path\test.txt";\nif (!File.Exists(path)) \n{\n  // Create a file to write to. \n   using (StreamWriter sw = File.CreateText(path)) \n   {\n     sw.WriteLine("Hello world, the service has started");\n    }   \n }	0
12540760	12540714	Creating A New Object Based Off An Existing Object Filtered By a List of Properties	public static Dictionary<string, object> FilterMovie(MovieResponse movie, string[] fields)\n{\n    var data = new Dictionary<string, object>();\n    var movieType = movie.GetType();\n\n    foreach (var field in fields)\n    {\n        data.Add(field, movieType.GetField(field).GetValue(movie));\n    }\n\n    return data;\n}	0
9513996	9513236	Get unique elements from a List<String>	List<string> nodup = dup.Distinct().ToList();\nList<int> remIndex = new List<int>();\nfor (int nIdx = 0; nIdx < nodup.Count; nIdx++)\n{\n    string[] strArr = nodup[nIdx].Split(' ');\n    if (String.Compare(strArr[1], "23", true) != 0)\n        remIndex.Add(nIdx);\n}\nforeach (int remIdx in remIndex)\n    nodup.RemoveAt(remIdx);	0
6482342	6482269	How to get the DataGrid row data in Textboxs	OnSelectedIndexChanged="Grid_SelectedIndexChanged"\n\n\n   void Grid_SelectedIndexChanged(Object sender, EventArgs e)\n   {\n\n     // Get the currently selected row using the SelectedRow property.\n      GridViewRow row = Grid.SelectedRow;\n\n     //Fill textboxes here\n     Code.Text =  row.Cells[0].Text;\n\n    }	0
25133602	25133569	Converting a list of lists into a single list using linq	var allTrackAreasCombined = allTrackAreas.SelectMany(t => t).ToList();	0
30714764	30714059	Compare similarity of two Strings for name verification	char[] firstName = firstName.ToCharArray();\nchar[] lastName = lastName.ToCharArray();\nchar[] res = firstName.Except(lastName).ToArray();\nif(res.Length < 1)\n{\n  res = lastName.Except(firstName).ToArray();\n}\nnameLengthDif = res.Length	0
14095388	14095344	C# - Compile variable as name/code	int[]  array = new int[3];\n\n    for (int i = 0; i < array.Length; ++i)\n    {\n        array[i] = 20;\n    }	0
26215560	26213519	QueryOver: select columns from subquery	MyModel main = null;\nMyModelDTO dto = null;\n\n// the main query\nvar query = session.QueryOver<MyModel>(() => main);\n\n// the subquery used for projection\nvar subquery = QueryOver.Of<OtherModel>()\n    // select something, e.g. count of the ID\n    .SelectList(selectGroup => selectGroup.SelectCount(o => o.ID))\n    // some condition\n    // kind of JOIN inside of the subquery\n    .Where(o => o.xxx == main.yyy); // just example\n\n// now select the properties from main MyModel and one from the subquery\nquery.SelectList(sl => sl\n      .SelectSubQuery(subquery)\n         .WithAlias(() => dto.Count)\n      .Select(() => main.ID)\n        .WithAlias(() => dto .ID)\n      ....\n    );\n\n// we have to use transformer\nquery.TransformUsing(Transformers.AliasToBean<MyModelDTO >())\n\n// and we can get a list of DTO\nvar list = query.List<MyModelDTO>();	0
5379948	5379813	Help to implement a ZipWithRatio extention method	public static IEnumerable<T> MergeWithRatio<T>(this IEnumerable<T> source, IEnumerable<T> mergeSequence, int ratio)\n{\n    int currentRatio  = 1;\n    bool mergeSequenceIsEmpty = !mergeSequence.Any();\n\n    using (var mergeEnumerator = mergeSequence.GetEnumerator())\n    {\n        foreach (var item in source)\n        {\n            yield return item;\n            currentRatio++;\n            if (currentRatio == ratio &&  !mergeSequenceIsEmpty)\n            {\n                if (!mergeEnumerator.MoveNext())\n                {\n                    mergeEnumerator.Reset();\n                    mergeEnumerator.MoveNext();\n                }\n                yield return mergeEnumerator.Current;\n                currentRatio = 1;\n            }\n        }\n    }\n}	0
1372037	1368064	System.FormatException: String was not recognized as a valid DateTime	protected void comments_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)\n    {\n        e.InputParameters["todayDate"] = DateTime.Now;\n    }	0
20010678	20007145	Select single xml node w/ namespaces with XPath Csharp	XmlNode nodes = xmlSoapRequest.SelectSingleNode("//sf:Account/sf:Name", man);	0
19598890	19598682	add textbox value to list	if (string.IsNullOrWhiteSpace(textBoxNum1.Text) == false)\n{\n   MyLottoNumbers = Regex.Matches(textBoxNum1.Text, @"([^\s]+)\s*")\n                         .OfType<Match>()\n                         .Select(mt => int.Parse(mt.Groups[0].Value))\n                         .ToList();\n}\nelse\n{\n  MyLottoNumbers = new List<int>(); // Create empty list as to not throw an exception.\n}	0
32374735	32374642	How to parse date YYYYMMDDHHMMSSUTC	string timeString = "20150828020000UTC";\nIFormatProvider culture = new CultureInfo("en-US", true);\nDateTime dateVal = DateTime.ParseExact(timeString, "yyyyMMddHHmmss'UTC'", culture);	0
34073429	34071024	How to display an image from a network folder or local drive in a Windows Universal App	async void Button_Click_2(object sender, RoutedEventArgs e)\n{\n    var _Name = "HelloWorld.txt";\n    var _Folder = KnownFolders.DocumentsLibrary;\n    var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting;\n\n    // create file \n    var _File = await _Folder.CreateFileAsync(_Name, _Option);\n\n    // write content\n    var _WriteThis = "Hello world!";\n    await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);\n\n    // acquire file\n    try { _File = await _Folder.GetFileAsync(_Name); }\n    catch (FileNotFoundException) { /* TODO */ }\n\n    // read content\n    var _Content = await FileIO.ReadTextAsync(_File);\n    await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync();\n}	0
8848607	8848319	Exclude properties from serialization to Json string - DynamicJson	var r = DynamicJson.Serialize(s);\nDynamicJson tt = DynamicJson.Parse(r);\ntt.Delete("Key");\n\nr = tt.ToString();	0
700999	700962	Replace date in a DateTime with another date	day = 1\nmonth = 4\nyear = 2009\n\nDate2 = new DateTime(day,month,year,Date1.Hours,Date1.Minute,Date1.Seconds)	0
33919427	33918509	Changing the value type/value of a cell in DataGridView c#	String dummyString;\nif (Convert.ToBoolean(cell.Value))\n{\n    dummyString = "Yes";\n}\nelse\n{\n    dummyString = "No";\n}\nint rowIndex = cell.RowIndex;\nint colIndex = cell.ColumnIndex;\n\ndataGridView1[colIndex, rowIndex] = new DataGridViewTextBoxCell();\ndataGridView1[colIndex, rowIndex].Value = dummyString;	0
6820210	6820175	c# How can I export a shared Outlook calendar to excel?	Microsoft.Office.Interop.Outlook.MAPIFolder blab = Globals.ThisAddIn.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);	0
7727517	7727483	WebClient - How to get source after you POST'ed something	WebClient.UploadValues	0
9345782	9345715	Extract value from simple XML element (root only) using XDocument	string xml = "<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">36</int>";\n            XmlDocument doc = new XmlDocument();\n            doc.LoadXml(xml);\n            string val = doc.InnerText;	0
4482478	4482476	convert a Pseudocode into c# code	do {\n    i++;\n} while (x[i] < j);	0
31930051	31929965	"use of unassigned local variable" C#	int barbTrainingCost = 0;	0
9313532	9313350	MonoDevelop on Mac - Export Settings	/Users/whatever/Library/MonoDevelop-2.6	0
28996346	28996159	Contracts - How to Require collection contains no nulls	// at the beginning of your method\nContract.Requires(MyCollection != null && Contract.ForAll(MyCollection, x => x != null));\n// other code\nforeach(var item in MyCollection)\n{\n   Contract.Assume(item != null);\n   // call method on item which can create a message from the static checker if the assume is not included\n}	0
21549845	21549645	Store tooltip for a control in C#.net	Control c = new Control();\nToolTip t = new ToolTip();\nc.Tag = t;\n\nTooltip t = (ToolTip)c.Tag;	0
11813068	11813053	how can i let the user to only copy the TextEdit's text	TextEdit.Properties.ReadOnly = true	0
24127322	24127071	iTextSharp is producing a corrupt PDF with Response	PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);\n        document.Open();\n\n        //Adiciona os campos de assinatura\n        document.Add(Assinatura());\n\n        //fecha o documento ao finalizar a edi??o\n        document.Close();\n\n        //Prepara o download\n        byte[] bytes = memoryStream.ToArray();\n        memoryStream.Close();\n        Response.Clear();\n        Response.ContentType = "application/pdf";\n        Response.AddHeader("Content-Disposition", "attachment;filename=ControleDePonto.pdf");\n        Response.Buffer = true;\n        Response.Cache.SetCacheability(HttpCacheability.NoCache);\n        Response.BinaryWrite(bytes);\n        Response.End();	0
11202971	11202661	How to configure a foreign key that is defined in the model with one to zero or one relationship	[ForeignKey("UserId")]	0
14532702	14532521	Unity3D Game: deal with constants within one file	private static GameConfig _instance = null;\npublic static GameConfig instance \n{\n    get {\n        if (!_instance) {\n            //check if an GameConfig is already in the scene\n            _instance = FindObjectOfType(typeof(GameConfig)) as GameConfig;\n\n            //nope create one\n        if (!_instance) {\n            var obj = new GameObject("GameConfig");\n            DontDestroyOnLoad(obj);\n            _instance = obj.AddComponent<GameConfig>();\n            }\n        }\n        return _instance;\n    }\n}	0
10119433	10119204	Expression on two integer type columns of datatable	DataTable table = new DataTable();\n\ntable.Columns.Add("OrderCount",typeof(int));\n\ntable.Columns.Add("OrderPrice",typeof(int));\n\ntable.Rows.Add(new object[] { 1, 1 });\n\ntable.Rows.Add(new object[] { 2, 3 });\n\ntable.Rows.Add(new object[] { 4, 5 });\n\ntable.Columns.Add("Result", typeof(string));\n\ntable.Columns["Result"].Expression = "Convert(OrderCount, 'System.String') + OrderPrice";	0
6903494	6903360	Compare two documents and change text color	if (richTextBox2.Find(mystring)>0)\n{\n    int my1stPosition=richTextBox1.Find(strSearch);\n    richTextBox2.SelectionStart=my1stPosition;\n    richTextBox2.SelectionLength=strSearch.Length;\n    richTextBox2.SelectionFont=fnt;\n    richTextBox2.SelectionColor=Color.Green;\n}	0
14701006	14700858	Set dropdown list to initial value	date0.SelectedIndex = 0;\ndate1.SelectedIndex = 0;\ndate2.SelectedIndex = 0;\ndate3.SelectedIndex = 0;\n\n\nmonth0.SelectedIndex = 0;\nmonth1.SelectedIndex = 0;\nmonth2.SelectedIndex = 0;\nmonth3.SelectedIndex = 0;\n\nyyyy0.SelectedIndex = 0;\nyyyy1.SelectedIndex = 0;\nyyyy2.SelectedIndex = 0;\nyyyy3.SelectedIndex = 0;	0
11508204	11508131	How do I calculate a random point that is a fixed distance from another point?	x = r ? cos( ? )\ny = r x sin( ? )	0
24044522	24038662	Update A Customer in QBO API 3	Customer found = GetQboCustomer(); \nCustomer customerToUpdate = new Customer(); \ncustomerToUpdate.Id = found.Id; \ncustomerToUpdate.SyncToken = found.SyncToken; \n//Set Other Properties \n//Perform Sparse Update	0
12983878	12983731	Algorithm for Calculating Binomial Coefficient	public static long combination(long n, long k)\n    {\n        double sum=0;\n        for(long i=0;i<k;i++)\n        {\n            sum+=Math.log10(n-i);\n            sum-=Math.log10(i+1);\n        }\n        return (long)Math.pow(10, sum);\n    }	0
2860089	2860054	C# xml read, show error	Console.WriteLine("id:" + textReader.id.ToString());\nConsole.WriteLine("name:" + textReader.name.ToString());\nConsole.WriteLine("time:" + textReader.time.ToString());	0
2215619	2215580	How to resolve url with non-ancestor references	Uri uri = new Uri("http://www.mysite.com/home/../help/helppage.aspx");\nuri.AbsoluteUri; // <- Contains http://www.mysite.com/help/helppage.aspx	0
10077867	10077320	How to remove href tag from CDATA	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar nodes = doc.DocumentNode\n    .Descendants("a")\n    .Where(n => n.Attributes.Any(a => a.Name == "href" && a.Value.StartsWith("/abc/def")))\n    .ToArray();\n\nforeach(var node in nodes)\n{\n    node.ParentNode.RemoveChild(node,true);\n}\n\nvar newHtml = doc.DocumentNode.InnerHtml;	0
11627864	11627764	Set many CheckBox	foreach (CheckBox checkbox in yourPanelContainer.Controls.OfType<CheckBox>())\n{\n   checkbox.Checked = true;\n}	0
14872650	14853561	How to define the scopes for network drives in windows indexing service?	//servername/path	0
4483962	4483912	Find a control in Windows Forms by name	var matches = this.Controls.Find("button2", true);	0
2810333	2810306	convert string data array to list	var persons = (from n in names()\n               let s = n.split('~')\n               select new Person { Name=s[1], Age=int.Parse(s[0]) }\n              ).ToList();	0
24150547	24051110	Converting a TreeNodePath to a TreeNode	private TreeNode nodeFromPath(String path)//Converts a treenode path into a treenode\n{\n    TreeNode tn = new TreeNode();\n\n    char[] delimiters = {'\\'};\n\n    string[] roots = path.Split(delimiters);\n    List<int> nodeIndeces = new List<int>();\n\n    for(int j = 0; j < roots.Length ;j++)\n    {\n        nodeIndeces.Add(selectedNode.Index);\n        selectedNode = selectedNode.Parent;\n    }\n    nodeIndeces.Reverse();\n    tn = treeView1.Nodes[0];\n\n    for (int i = 1; roots.Length > i; i++)\n    {\n        tn = tn.Nodes[nodeIndeces[i]];\n    }\n\n    return tn;\n\n}//end nodeFromPath	0
26873468	26870397	Convert and pass typedrow as parameter to custom rowdeleted event	public static object[] GetItemArray(this DataRow row, DataRowVersion version)\n{\n    var count = (row.Table).Columns.Count;\n    var items = new List<object>(count);\n    for (var i = 0; i < count; i++)\n    {\n        items.Add(row[i, version]);\n    }\n    return items.ToArray();\n}	0
1879781	1879752	C# - Regexp - ArgumentException	//verbatim \nRegex r = new Regex(@"Mond ([1-9]) \x5B([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\x5D");\n\n//or escaped\nRegex r = new Regex("Mond ([1-9]) \\x5B([1-9]):([1-9][0-9]{0,2}):([1-9][0-9]{0,2})\\x5D");	0
2050239	2049821	How to convert a string "001" to int 001	public string NextId(string currentId)\n{\n    int i = 0;\n    if (int.TryParse(currentId, out i))\n    {\n        i++;\n        return(i.ToString().PadLeft(3,'0'));\n    }\n    throw new System.ArgumentException("Non-numeric string passed as argument");\n}	0
28568320	28568246	Working with Unicode Blocks in Regex	if (Regex.IsMatch(subjectString, @"\p{IsBasicLatin}")) {\n    // Successful match\n}	0
27338613	27319485	Dropzone delete uploaded images from sever	init: function() {\n    this.on("removedfile", function(file) {\n        //add in your code to delete the file from the database here \n    });\n}	0
10037794	10037495	lambda to expression tree	var resultSelector = Expression.Lambda<Func<T, TLookup, TLookup>>(l, s, l);	0
15663406	15663260	Update Multiple tables using the same SQLParameter?	cmd.CommandText = @"update table0 set active= 'N' where id=@id;\n      update table1 set active= 'N' where id= @id;\n      update table2 set active= 'N' where id= @id;\n      update table4 set active= 'N' where id= @id;";\ncmd.Parameters.Add(new SqlParameter("@id", id));\ncmd.ExecuteNonQuery();	0
3231086	3197891	How to make an application HAVE a form but not BE a form?	using System;\nusing System.Windows.Forms;\n\nnamespace Example\n{\n    internal static class Program\n    {\n        [STAThread]\n        private static void Main()\n        {\n            new Bootstrapper().Run();\n        }\n    }\n\n    public class Bootstrapper\n    {\n        public void Run()\n        {\n            // [Application initialization here]\n            ShowView();\n        }\n\n        private static void ShowView()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Form1());\n        }\n    }\n}	0
2688227	2671498	nslookup for C# and C++ to resolve a host using a specific Server	var Options = new JHSoftware.DnsClient.RequestOptions();\nOptions.DnsServers = new System.Net.IPAddress[] { \n           System.Net.IPAddress.Parse("1.1.1.1"), \n           System.Net.IPAddress.Parse("2.2.2.2") };\nvar IPs = JHSoftware.DnsClient.LookupHost("www.simpledns.com", \n                                          JHSoftware.DnsClient.IPVersion.IPv4, \n                                          Options);\nforeach(var IP in IPs)\n{\n   Console.WriteLine(IP.ToString());\n}	0
3933799	3929389	NAudio convert input byte array to an array of doubles	void waveIn_DataAvailable(object sender, WaveInEventArgs e)\n    {\n        byte[] buffer = e.Buffer;\n\n        for (int index = 0; index < e.BytesRecorded; index += 2)\n        {\n            short sample = (short)((buffer[index + 1] << 8) |\n                                    buffer[index]);\n            float sample32 = sample / 32768f;                \n        }\n    }	0
21303241	21303138	C# - Playing random sound files from folder	var soundsRoot = @"c:\lyde";\nvar rand = new Random();\nvar soundFiles = Directory.GetFiles(sounds, "*.wav");\nvar playSound = soundFiles[rand.Next(0, soundFiles.Length)\nSystem.Media.SoundPlayer player1 = new System.Media.SoundPlayer(playSound);	0
26061727	26055997	Handling Optional Parameters when running Crystal Reports 2011 report from C#	cryRpt.ParameterFields["UserProfile"].CurrentValues.IsNoValue = true;	0
23289434	23289051	Get data in parts from database	var startRecord = 0;\nvar records = db.where(x=>x.ID ==ID).Skip(startRecord).Take(1000);\nwhile (records.Any())\n{\n  startRecord += 1000;\n  // do something with your records\n\n  records = db.where(x=>x.ID ==ID).Skip(startRecord).Take(1000);\n}	0
32130787	32113426	How to address an assembly in xaml, which is located somewhere else	AppDomain currentDomain = AppDomain.CurrentDomain;\ncurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSomeFolder);\n\n...\n\nprivate Assembly LoadFromSomeFolder(object sender, ResolveEventArgs args)\n{\n    return Assembly.LoadFrom("C:\..\..." + args.Name);\n}	0
17449028	17448955	UnitTest a method that is time-dependent	DateTime.Now	0
31582762	31573517	Detecting two tags in Unity3D for player death	bool wall1 = false;\nbool wall2 = false;\n\nvoid Update()\n{\n    if( wall1 && wall2 )\n    {\n        Die();\n    }\n}\n\nvoid OnCollisionEnter(Collision other)\n{\n    if (other.transform.tag == "Crush")\n    {\n        wall1 = true;\n    }\n    else if(other.transform.tag == "Crush1")\n    {\n        wall2 = true;\n    }\n}\n\n\nvoid OnCollisionExit(Collision other)\n{\n    if (other.transform.tag == "Crush")\n    {\n        wall1 = false;\n    }\n    else if(other.transform.tag == "Crush1")\n    {\n        wall2 = false;\n    }\n}	0
22767677	22767350	Is it possible to inherit data annotations in C#?	public class AccountEmail { }\n\n    public class AccountCredentials : AccountEmail\n    {\n        public Password Password { get; set; }\n    }\n\n    public class PasswordReset : AccountCredentials\n    {\n        [Required]\n        public string ResetToken { get; set; }\n\n        public Password NewPassword { get; set; }\n    }\n\n    public class Password\n    {\n        [Required(ErrorMessage = "xxx.")]\n        [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]\n        public string Value { get; set; }\n\n        public override string ToString()\n        {\n            return Value;\n        }\n    }	0
1949452	1949341	How do I Check previous data in LINQ?	public partial class User\n{\n    partial void OnFirstNameChanging(string value)\n    {\n    }\n}	0
31171074	31168657	How can I respond to a keyboard chord and replace the entered alpha key with a special one?	public partial class Form1 : Form\n{\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        if (this.ActiveControl != null && this.ActiveControl is TextBox)\n        {\n            string replacement = "";\n            TextBox tb = (TextBox)this.ActiveControl;\n            bool useHTMLCodes = checkBoxUseHTMLCodes.Checked;\n\n            if (keyData == (Keys.Control | Keys.A))\n            {\n                replacement = useHTMLCodes ? "&aacute;" : "??";\n            }\n            else if (keyData == (Keys.Control | Keys.Shift | Keys.A))\n            {\n                replacement = useHTMLCodes ? "&Aacute;" : "??";\n            }\n\n            if (replacement != "")\n            {\n                tb.SelectedText = replacement;\n                return true;\n            }\n        }\n\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n}	0
9380305	9380262	What's Wrong With My Lambda Expression?	bool test = people.Any(p => p.FirstName == "Bob");	0
5936229	5936193	Fill Keys and values of a Dictionary<K, V> using arrays in C#	myDictionary = keys.Zip(values, (k, v) => new { k, v })\n                   .ToDictionary(o => o.k, o => o.v);	0
11838462	11838422	XAML User Control not showing	Grid.Children.Add(_spatialFilterMode);	0
5355060	5094346	Issues with Dynamic Search Expressions in EF	searchExpressions.Add(new SearchExpression("Individual\n                                            .IndividualNames\n                                            .Select(GivenName)",\n                      ComparisonOperator.Contains, "Test");	0
20656281	20656183	How to load image to the image control in c#?	Server.MapPath()	0
20467466	20461396	Mapping different property values using value injector	class Program\n{\n    static void Main( string[] args )\n    {\n        Animal animal = new Animal() { AnimalId = 1, Name = "Man1" };\n        Man man = new Man();\n        man.InjectFrom<Animal>( animal );\n    }\n}\n\npublic class Animal:ConventionInjection\n{\n    public int AnimalId { get; set; }\n    public string Name { get; set; }\n\n    protected override bool Match( ConventionInfo c )\n    {\n        return ((c.SourceProp.Name == "AnimalId") && (c.TargetProp.Name == "ManId"));\n    }\n}\n\npublic class Man : Animal\n{\n\n    public int ManId { get; set; } \n    public string Communicate { get; set; }\n}	0
22015546	22014794	c# do the equivalent of restarting a Task with some parameter	// Method that makes calls to fetch and write data.\n    public async Task DoStuff()\n    {\n        Task currTask = null;\n\n        object somedata = await FetchData();\n\n        while (somedata != null)\n        {\n            // Wait for previous task.\n            if (currTask != null)\n                Task.WaitAny(currTask);\n\n            currTask = WriteData(somedata);\n\n            somedata = await FetchData();\n        }\n    }\n\n    // Whatever method fetches data.\n    public Task<object> FetchData()\n    {\n        var data = new object();\n\n        return Task.FromResult(data);\n    }\n\n    // Whatever method writes data.\n    public Task WriteData(object somedata)\n    {\n        return Task.Factory.StartNew(() => { /* write data */});\n    }	0
30756004	30749752	Stored procedure timesout called from code, executes ok from SSMS	cmd.CommandTimeout = 0;	0
22732956	22732665	How to convert a String into a Class reference	object obj = System.Windows.Forms.Application.OpenForms[row.Cells[0].Value.ToString()];\nType t = Type.GetType("myNamespace.PC_01, myAssembly");\n\nif (obj.GetType() == t)\n{\n   ((dynamic)obj).accept();\n}	0
5629887	5629861	How to put a strikethrough in a listview or repeater	.yourCSSClass {text-decoration: line-through;}\n\n<asp:Label ID="lb_titleLabel" runat="server" CssClass="center-head" Text='<%# Eval("lb_title") %>' />\n                 <p><asp:Label CssClass="yourCSSClass" ID="lb_descriptionLabel" runat="server" Text='<%# Eval("lb_description") %>' /></p>	0
9929064	9928971	Raising event from custom control added dynamically to the form	MyButton.Click += ButonClickEventHandler;\nPage.Controls.Add(MyButton)	0
726970	726909	How to compare values from different tables with a single query on Linq-to-SQL?	bool result = (db.As.Max(a => a.Instant) - db.Bs.Max(b => b.instant)) > new TimeSpan(0,0,1);	0
34427822	34427200	Accessing a value in a subclass as a property vs. by index for List<>	objects that implement IList<T>	0
2523702	2523651	How to use C# to parse a glossary into database?	StreamReader SR;\nstring Term_Name;\nstring Term_Definition\n\nSR = File.OpenText(filename);\nTerm_Name = SR.ReadLine();\nwhile(Term_Name != null)\n{\n    Term_Definition = SR.ReadLine();\n    // make your database call here to insert with these two variables.  I don't know what DB you are using.\n    Term_Name = SR.ReadLine();\n}\nSR.Close();	0
3324614	3324605	How to cast list of X to list of Y in C#?	List<DerivedSecond> foo = firstList.Select(x => (DerivedSecond)x).ToList();	0
11600466	11600355	How to open/close console window dynamically from a wpf application?	[DllImport("Kernel32")]\npublic static extern void AllocConsole();\n\n[DllImport("Kernel32")]\npublic static extern void FreeConsole();\n\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    AllocConsole();\n    Console.WriteLine("test");\n}	0
16176391	16176333	Determines order in foreach(Panel p in pnl)	foreach (Panel p in pnl.Controls.OfType<Panel>().OrderBy(x => x.Left)) {\n  // do something with p\n}	0
10193304	10193255	Is it possible to remove panel2 from SplitContainer in Windows Forms?	splitContainer1.Panel2.Hide();	0
14810784	14810318	joining two tables columns bottom by bottom , not in row	dt1.Merger(dt2)	0
16584702	16583145	retrieve the data using monthcalendar control	using (var con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=  C:\Users\JAY\Desktop\Employee.mdb"))\nusing (var cmd = new OleDbCommand("select * from Emp_Details WHERE DOB= ?", con))\n{\n    cmd.Parameters.AddWithValue("@P1", monthCalendar1.SelectionRange.Start);\n    using (var da = new OleDbDataAdapter(cmd))\n    {\n        da.Fill(ds, "Emp_Details");\n        if (ds.Tables["Emp_Details"] !=null && ds.Tables["Emp_Details"].Rows.Count>0)\n        {\n            DataRow dr = ds.Tables["Emp_Details"].Rows[0];\n            txtEmployeeNo.Text = dr[0].ToString();\n            txtName.Text = dr[1].ToString();\n            txtAddress.Text = dr[2].ToString();\n            comboBox1.Text = dr[3].ToString();\n            txtMobNo.Text = dr[4].ToString();\n        }\n    }\n}	0
23419018	23418878	Saving formCollections values to an array	public ActionResult TriageScore(TriVM tri, FormCollection formCollection)\n        {\n            int i = 0;\n            string[] value = new string[formCollection.Count];\n            foreach (var key in formCollection.AllKeys)\n            {\n                value[i] = formCollection[key];\n                i++;\n            }\n         }	0
25046352	25046061	Unity C# Deserialization dealing with extra properties	public class foo {\n    public int bar {get;set;}\n    public int baz {get;set;}\n}	0
16845821	16845294	regex to match page[0-9] and nothing before or after	/page[0-9]+	0
13035829	13035580	Many to many query in LINQ	var query = (from a in db.Addresses\n             join oba in db.obAddresses on a.AddressID equals oba.AddressID\n             // do not join with db.obAddresses again\n             join s in db.States on a.StateID equals s.StateID\n             where oba.obID == passedinID // filter here\n                   && a.AddressTypeID == '5'\n             select new {\n                   a.Address,\n                   a.City,\n                   a.StateID,\n                   s.StateAbbreviation,\n                   a.ZipCode\n             }).FirstOrDefault();	0
11636481	11636153	Read file from listbox	foreach (string value in listBox1.SelectedItems)\n{\n    StreamReader sr = new StreamReader(value);\n    ...\n}	0
18973403	18971829	How to implement a progress bar in windows forms C#?	DoWork()	0
1122519	1122483	Random String Generator Returning Same String	private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden\nprivate string RandomString(int size)\n    {\n        StringBuilder builder = new StringBuilder();\n        char ch;\n        for (int i = 0; i < size; i++)\n        {\n            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));                 \n            builder.Append(ch);\n        }\n\n        return builder.ToString();\n    }\n\n// get 1st random string \nstring Rand1 = RandomString(4);\n\n// get 2nd random string \nstring Rand2 = RandomString(4);\n\n// creat full rand string\nstring docNum = Rand1 + "-" + Rand2;	0
4160219	4160165	Detect if the caller has access to my assembly internals	System.Diagnostics.StackTrace st = new StackTrace();\n    MethodBase mb = st.GetFrame(1).GetMethod();\n    Assembly a = mb.DeclaringType.Assembly;	0
7061228	7061214	LINQ to Entities - put all fields into final result	var query =\n    from order in orders\n    join detail in details\n    on order.SalesOrderID equals detail.SalesOrderID\n    where order.OnlineOrderFlag == true\n    && order.OrderDate.Month == 8\n    select new\n    {\n        SalesOrderHeader = order;\n        SalesOrderDetail = detail;\n    };	0
31658246	31657754	How do I replace only specific match in a match collection?	string input = "20 * (6+3) / ((4+6)*9)";\nConsole.WriteLine(input);\nDataTable dt = new DataTable();\nRegex rx = new Regex(@"\([^()]*\)");\nstring expression = input;\nwhile (rx.IsMatch(expression))\n{\n    expression = rx.Replace(expression, m => dt.Compute(m.Value, null).ToString(), 1);\n    Console.WriteLine(expression);\n}\nConsole.WriteLine(dt.Compute(expression, null));	0
6280053	6279893	How to access file path for XML file in an assembly folder?	Assembly.GetExecutingAssembly().GetManifestResourceStream(path)	0
33499017	33498895	How to access a file placed in a generic Folder inside of an ASP.NET Web Application	string xlsNameWitPath = Path.Combine(Server.MapPath("~/ProductCatalog/"), xlsFileName);	0
3192602	3192588	How to specify custom SoapAction for WCF	[ServiceContract(Namespace = "http://www.TextXYZ.com/FUNC/1/0/action")]\npublic interface IMyServiceContract\n{\n    [OperationContract]\n    void MyMethod();\n}	0
94255	93989	Prevent multiple instances of a given app in .NET?	[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}\n\nprivate static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";	0
20550144	20548949	3 Attempts to delete XML node using C#	string xmlfile = Server.MapPath("~/uploads/banners.xml");\n        var xDoc = XDocument.Load(xmlfile);\n        string fileName = "resdrop.png"; // Value from SQL DB\n\n        xDoc.Descendants("filename")\n            .Where(c => c.Value == fileName)\n            .Select(x => x.Parent)\n            .Remove();\n        xDoc.Save(xmlfile);	0
7756445	7756343	If statement pertaining to database criteria	if(!line.StartsWith("YYYY"))\n{\n     //....do stuff here\n}	0
15964986	15923774	How to change password using Google.GData.Apps of .net	AppsService service = new AppsService("domain", "adminusername", "adminpassword");\n  UserEntry user = service.RetrieveUser("viresh1");\n  user.Login.Password = "newpassword";\n  service.UpdateUser(user);	0
8918629	8918570	Create list with 2 columns using foreach	var odds = mod.Where((item, index) => index % 2 == 0).ToList();\nvar evens = mod.Where((item, index) => index % 2 == 1).ToList();	0
4960679	4960646	How to access XML String values in C#?	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(yourString);	0
13923302	13923193	List all files from online FTP directory to a listview C#	public string[] ListDirectory() {\n        var list = new List<string>();\n\n        var request = createRequest(WebRequestMethods.Ftp.ListDirectory);\n\n        using (var response = (FtpWebResponse)request.GetResponse()) {\n            using (var stream = response.GetResponseStream()) {\n                using (var reader = new StreamReader(stream, true)) {\n                    while (!reader.EndOfStream) {\n                        list.Add(reader.ReadLine());\n                    }\n                }\n            }\n        }\n\n        return list.ToArray();\n    }	0
13471132	13470940	Adding a DataGridViewCheckBoxColumn	dgvDocDisplay.Columns.AddRange(\n    new DataGridViewColumn[]\n    {\n        new DataGridViewTextBoxColumn { Name = "Tag" },\n        new DataGridViewTextBoxColumn { Name = "[ ]" },\n        new DataGridViewCheckBoxColumn { Name = "#" },\n        new DataGridViewTextBoxColumn { Name = "Type" }\n        // etc\n    });	0
7246880	7246857	App.config application settings and variables	string newPath = Path.Combine(\n    ConfigurationManager.AppSettings["SecondPath"], \n    fileName\n);	0
17368500	17368452	insert into error, using access db in c#	cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(id.Text));\ncmd.Parameters.AddWithValue("@Name", name.Text);\ncmd.Parameters.AddWithValue("@Score", Convert.ToInt32(score.Text));	0
10945877	10945639	how do I get the last item from the listview	var r = Enumerable.Empty<ListViewItem>();\n\nif(this.listView1.Items.Count > 0)\n    r = this.listView1.Items.OfType<ListViewItem>();\n\nvar last = r.LastOrDefault();\n\nif (last != null)\n{\n    // do your stuff\n}	0
28436701	28436348	How to insert data into 2 tables simultaneously (SQL management studio 2008 )	BEGIN TRANSACTION\nINSERT INTO Employee_Data (Name, Contact)\nVALUES ('X', 'Y')\nDECLARE @id as int = SCOPE_IDENTITY()\nINSERT INTO Employee_Achievements (EmployeeId, Achievement_Name , Marks , Grade)\nVALUES ( (@id, 'A1', 'M1', 'G1'), (@id, 'A2', 'M2', 'G2') )\nCOMMIT TRANSACTION	0
4055758	4055684	Replace a database MDF file with backup file during runtime in C#	USE master \nGO \nALTER DATABASE YourDatabaseName \nSET OFFLINE WITH ROLLBACK IMMEDIATE \nGO	0
3291311	3289321	C# - Capturing Windows Messages from a specific application	PostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_ACTIVE_CALLINFO, (int)_thisHandle);\nPostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_ALL_REGISTRATIONINFO, (int)_thisHandle);\nPostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_CALL_EVENTS, (int)_thisHandle);\nPostMessage((int)_hWnd, _windowsMessages[0], SHOCK_REQUEST_REGISTRATION_EVENTS, (int)_thisHandle);	0
10805138	10805053	Multiple Classes With Same Methods	public partial class SHIPMENT_LINE : ISetConnection\n{\n   private ConnectionSetter connector = new ConnectionSetter();\n\n   public void SetConnection(BHLibrary.Configuration.ConnectionOption Environment)\n   {\n      this.connector.SetConnection(Environment);\n   }\n}\n\npublic class ConnectionSetter : ISetConnection\n{\n    public void SetConnection(BHLibrary.Configuration.ConnectionOption Environment)\n   {\n      // Implementation\n   }\n}	0
8931385	8931203	How do I control two listboxes using a Vertical Scrollbar?	listBox1.BeginUpdate();\n        listBox2.BeginUpdate();\n        listBox1.TopIndex = \n        listBox2.TopIndex = ++x;\n        listBox1.EndUpdate();\n        listBox2.EndUpdate();	0
16509234	16509220	Delimiting double quotes for replacing XML characters	Replace("\"", "&quot;")	0
19593541	11090946	Mono on Mac OS X - Illegal Instruction 4	System.Data.SqlClient	0
21495918	21495169	Pack files into one, to later programmatically unpack them	using (var fs = File.Create(...))\nusing (var bw = new BinaryWriter(fs))\n{\n    foreach (var file in Directory.GetFiles(...))\n    {\n        bw.Write(true); // means that a file will follow\n        bw.Write(Path.GetFileName(file));\n        var data = File.ReadAllBytes(file);\n        bw.Write(data.Length);\n        bw.Write(data);\n    }\n    bw.Write(false); // means end of file\n}	0
5936027	5913177	WCF - multiple service contracts using pretty same data contracts	[DataContract]\npublic class UserForService1 : User\n{\n     private User mUser;\n     public UserForService1(User u)\n     {\n         mUser = u;\n     }\n\n     //expose only properties you'd like the user of this data contract to see\n     [DataMember]\n     public string SomeProperty\n     {\n         get\n         {\n            //always call into the 'wrapped' object\n            return mUser.SomeProperty;\n         }\n         set\n         {\n            mUser.SomeProperty = value;\n         }\n     }\n     // etc...\n}	0
27676395	27676161	How to get found substring while using Regex.Replace method?	var identifiers = new Dictionary<string, string>();\nint i = 0;\nvar input = "FGS1=(B+A*10)+A*10+(C*10.5)";\nRegex r = new Regex("([A-Z][A-Z\\d]*)");\nbool f = false;\n\nMatchEvaluator me = delegate(Match m)\n{\n    var variableName = m.ToString();\n\n    if(identifiers.ContainsKey(variableName)){\n        return identifiers[variableName];\n    }\n    else {\n        i++;\n        var newVariableName = "i" + i.ToString();\n        identifiers[variableName] = newVariableName;\n        return newVariableName;\n    }\n};\n\ninput = r.Replace(input, me);\nConsole.WriteLine(input);	0
10749897	10749826	retrieve username and password from web.config	System.Configuration.ConfigurationManager.AppSettings["MyName/MyPassword"]	0
23889930	23888266	How to disable standard context menu of a ListBox scrollbar?	using System;\nusing System.Windows.Forms;\n\nclass MyListBox : ListBox {\n    protected override void WndProc(ref Message m) {\n        // Intercept WM_CONTEXTMENU\n        if (m.Msg != 0x7b) base.WndProc(ref m);\n    }\n}	0
18147023	18146855	Using Active Directory/LDAP to Login user in ASP.NET 3.5 app	using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, myDomainTextBox.Text))\n{\n    // validate the credentials\n    bool cIsValid = pc.ValidateCredentials(myUserNameTextBox.Text, myPasswordBox.Password);\n\n    if (cIsValid)\n    {\n        // Do some stuff\n    }\n}	0
13286150	13286050	Convert dropdownlist into text	string strdt= drpdte0.SelectedValue+"/"+drpmm0.SelectedValue+"/"+drpyyyy0.SelectedValue;\nstring formatedDate = strdt.ToString("dd-MM-yyyy");	0
23561990	23561782	Using foreach iterator value inside EventHandler	// these actions should be invoked during cleanup\nprivate readonly List<Action> _cleanupActions = new List<Action>();\n\npublic void Start()\n{\n    foreach (var m in mappings)\n    {\n        // you need both closures in order to reference them inside\n        // the cleanup action\n        var mapping = m;\n        PropertyChangedEventHandler handler = (s, e) => { /* ... */ };\n\n        // attach now\n        mapping.PropertyChanged += handler;\n\n        // add a cleanup action to detach later\n        _cleanupActions.Add(() => mapping.PropertyChanged -= handler);\n\n}\n\npublic void Stop()\n{\n    // invoke all cleanup actions\n    foreach (var action in _cleanupActions)\n        action();\n}	0
731304	731281	Copy a ResourceDictionary to a Dictionary in C#	resourceDictionary.Keys.Cast<string>().ToDictionary\n    (x => x,                             // Key selector\n     x => (string) resourceDictionary[x] // Value selector\n     );	0
11650031	11649813	Finding a char from an array, spliting at that point and then inserting another char after	StringBuilder sb = new StringBuilder();\n\nstring[] splitString = fTextSearch.Split(errorChars, StringSplitOptions.None);\n\nint numNewCharactersAdded = 0;\nforeach( string itm in splitString)\n{\n   sb.Append(itm); //append string\n   if (fTextSearch.Length > (sb.Length - numNewCharactersAdded))\n   {\n      sb.Append(fTextSearch[sb.Length - numNewCharactersAdded]); //append splitting character\n      sb.Append(fTextSearch[sb.Length - numNewCharactersAdded - 1]); //append it again\n      numNewCharactersAdded ++;\n   }\n}\n\nfTextSearch = sb.ToString();	0
6706070	6706032	How can I get the height of a ListView item?	int itemHeight = yourListView.GetItemRect(itemIndex).Height;	0
5271289	3513208	Handling events from Word using dynamic com interop from C#	AutomationEvent quitEvent = AutomationFactory.GetEvent(word,"Quit");\nquitEvent.EventRaised += new EventHandler<AutomationEventArgs>(quitEvent_EventRaised);	0
23050163	23050116	Confused over access to private variable from Linq query	private static string GetProperyName(ObjectGraph obj) {\n  return obj._propertyName;\n}\n\npublic string PropertyName\n{\n   get\n   {\n        // ermmm, not sure why this Select can access _propertyName???\n        var parents = string.Join("/", Parents.Select(GetProperyName));\n        return string.Format("{0}/{1}", parents, _propertyName);\n    }\n}	0
2023543	2023478	How to deep copy an object containing a lambda expression?	Action<OtherComponent> action = new Action<OtherComponent>((null) => { });\nif ( some stuff from the input file )\n    action += x => { x.Foo(); x.Bar = 5; }	0
17504308	17504258	How to send special characters to web services?	String query = URLEncoder.encode("something of yours / words", "utf-8");\nString url = "http://stackoverflow.com/search?q=" + query;	0
609627	585047	Returning a CLR type from IronRuby	[Fact]\npublic void Then_the_object_should_be_accessible_in_csharp()\n{                       \n    var engine = Ruby.CreateEngine();\n\n    engine.Runtime.LoadAssembly(typeof (BuildMetaData).Assembly);\n\n    engine.ExecuteFile(buildFile);\n\n    var klass = engine.Runtime.Globals.GetVariable("MetaDataFactory");\n\n    var instance = (RubyObject)engine.Operations.CreateInstance(klass);\n\n    //You must have shadow-copying turned off for the next line to run and for the test to pass.\n    //E.g. in R# "ReSharper/Options/Unit Testing/Shadow-Copy Assemblies being tested" should be un-checked.\n    var metaData = (BuildMetaData)engine.Operations.InvokeMember(instance, "return_meta_data");\n\n    Assert.Equal(metaData.Description, "A description of sorts");\n\n    Assert.Equal(metaData.Dependencies.Count, 1);\n}	0
8397228	8397193	Is it possible to set CanRead and CanWrite Properties of a NetworkStream objects in C#?	NetworkStream nStreamObj1 = new NetworkStream(clientSocket, FileAccess.Read);\nNetworkStream nStreamObj2 = new NetworkStream(clientSocket, FileAccess.Write);	0
697233	697065	How do I list the requesting user's roles in a WCF service?	foreach (IdentityReference idRef in WindowsIdentity.GetCurrent().Groups)\n{\n    Console.WriteLine(idRef.Translate(typeof(NTAccount)).Value);\n}	0
20457588	20457537	Type Conversion for data	List<Pencil> input = GetPencil();\nList<Pencil1> output = input.Select(x => new Pencil1 { Name = x.Name, Price = x.Price }).ToList();	0
11134633	11133947	How to open second window from first window in wpf?	private void Button_Click(object sender, RoutedEventArgs e)\n        {            \n            window2 win2= new window2();\n            win2.Show();\n            this.Close();\n        }	0
11926350	11925305	Regex - negative look-behind anywhere on line	(?<!//.*?)(?<Keyword>foreach)	0
20212602	20211678	WPF - duplicating a stackpanel	private void btn_Click(object sender, RoutedEventArgs e)\n        {\n            Button btn = sender as Button;\n            StackPanel stkButtonParent = btn.Parent as StackPanel;\n            StackPanel stkCover = stkButtonParent.Parent as StackPanel;\n            StackPanel newRow = NewRow();\n            stkCover.Children.Add(newRow);\n        }\n\n        private StackPanel NewRow() {\n            StackPanel stk = new StackPanel();\n            stk.Orientation = Orientation.Horizontal;\n            Label lbl = new Label();\n            lbl.Foreground = Brushes.Red; // some attribute\n            TextBox txt = new TextBox();\n            txt.Background = Brushes.Transparent; // some attribute\n            Button btn = new Button();\n            btn.Content = "Add new row";\n            btn.Click += btn_Click;\n            stk.Children.Add(lbl);\n            stk.Children.Add(txt);\n            stk.Children.Add(btn);\n            return stk;\n        }	0
21236171	21160337	How can I merge two JObject?	JArray dataOfJson1=json1.SelectToken("data");\n\nJArray dataofJson2=json2.SelectToken("data");\n\nforeach(JObject innerData in dataofJson2) \n{\n    dataOfJson1.Add(innerData);\n}	0
6837635	6837612	in a "for" loop, is the Terminating Condition Re-Evaluated on Each Iteration?	complicated()	0
18383332	18383255	Intersect or union with a custom IEqualityComparer using Linq	// Property names changed to conform with normal naming conventions\nvar results = collection1.Concat(collection2)\n                         .GroupBy(x => x.key)\n                         .Select(g => new Item {\n                                     Key = g.Key,\n                                     Total1 = g.Sum(x => x.Total1),\n                                     Total2 = g.Sum(x => x.Total2)\n                                 });	0
16848076	16847831	Sitecore Fast Query - How to search for text containing special characters (such as an apostrophe)?	var searchTerm = "hot n' tasty";\nvar query = string.Format("fast:/sitecore/content/Home/Products//*[@ContentDescriptionText=\"%{0}%\"]", searchTerm);\nvar items = Database.SelectItems(query);	0
24270338	24039066	Display a Simpleitk image in a picture Box	// Cast to we know the the pixel type\n  input = SimpleITK.Cast(input, PixelId.sitkFloat32);\n  // calculate the nubmer of pixels\n  VectorUInt32 size = input.GetSize();\n  int len = 1;\n  for (int dim = 0; dim < input.GetDimension(); dim++) {\n    len *= (int)size[dim];\n  }\n  IntPtr buffer = input.GetBufferAsFloat();	0
7792814	7790242	Is there a way to know how many instances the webrole contains at current time?	foreach (var roleDefinition in RoleEnvironment.Roles) \n{ \n   foreach (var roleInstance in roleDefinition.Value.Instances) \n   { \n      Trace.WriteLine("Role instance ID: " + roleInstance.Id, "Information");\n   }\n}	0
4493651	4493454	matweb.com: How to get source of page?	webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"; //maybe substitute your own in here	0
13010991	13009066	add header to the XDocument, and schema	XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");\n            XNamespace xsd = XNamespace.Get("http://www.w3.org/2001/XMLSchema");\n            XNamespace ns = XNamespace.Get("http://schema.test.com/test");\n\n\n            XDocument doc = new XDocument(\n\n                new XDeclaration("1.0", "utf-8", "yes"),\n\n                new XElement(\n\n                    ns + "root",\n                    new XAttribute("xmlns", ns.NamespaceName),\n                    new XAttribute(XNamespace.Xmlns + "xsd", xsd.NamespaceName),\n                    new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),\n                    from p in Data select new XElement(ns + p.Key, p.Value)\n\n                )\n\n                    );	0
29132149	29117995	C# set resource value based on method return value	string imageToReturn = GetImageToReturn();\n\nobject obj = Properties.Resources.ResourceManager.GetObject(imageToReturn, resourceCulture);\npictureBoxTurn.Image = (System.Drawing.Bitmap)obj;	0
22250069	21992506	Sqlite for windows store doesn't search for arabic text	//define your connection here\nstatic SQLite.SQLiteConnection dbConn = = new SQLite.SQLiteConnection(file.Path);\n//in your method that makes the call:\nstring text="???";\ndbConn.Query<DB.QuranText>(@"SELECT * FROM QuranText where AyaWithoutTashkeel LIKE", "%" + text + "%");	0
4022946	4022746	WPF: Add a dropshadow effect to an element from code-behind	// Get a reference to the Button.\nButton myButton = new Button();\n\n// Initialize a new DropShadowBitmapEffect that will be applied\n// to the Button.\nDropShadowBitmapEffect myDropShadowEffect  = new DropShadowBitmapEffect();\n// Set the color of the shadow to Black.\nColor myShadowColor = new Color();\nmyShadowColor.ScA = 1;\nmyShadowColor.ScB  = 0;\nmyShadowColor.ScG  = 0;\nmyShadowColor.ScR  = 0;\nmyDropShadowEffect.Color = myShadowColor;\n\n// Set the direction of where the shadow is cast to 320 degrees.\nmyDropShadowEffect.Direction = 320; \n\n// Set the depth of the shadow being cast.\nmyDropShadowEffect.ShadowDepth = 25; \n\n// Set the shadow softness to the maximum (range of 0-1).\nmyDropShadowEffect.Softness = 1;\n// Set the shadow opacity to half opaque or in other words - half transparent.\n// The range is 0-1.\nmyDropShadowEffect.Opacity = 0.5; \n\n// Apply the bitmap effect to the Button.\nmyButton.BitmapEffect = myDropShadowEffect;	0
12019594	12019524	Get Active Window of .net application	[DllImport("user32.dll")]\nstatic extern IntPtr GetActiveWindow();\n\n[DllImport("user32.dll")]\npublic static extern int SendMessage(int hWnd, IntPtr msg, int wParam, int lParam);\n\npublic const int WM_SYSCOMMAND = 0x0112;\npublic const int SC_CLOSE = 0xF060;\n\n// close the active window using API        \nprivate void FindAndCloseActiveWindow()\n{\n IntPtr handle=GetActiveWindow();\n SendMessage(handle, WM_SYSCOMMAND, SC_CLOSE, 0);\n}	0
23135051	23134246	How to Create a file and folder in the Program Files using C#	var dir = Path.Combine(Environment\n    .GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyProgram");\nif(!Directory.Exists(dir))\n    Directory.CreateDirectory(dir);\nSQLiteConnection.CreateFile(Path.Combine(dir, "MyDatabase.sqlite"));	0
13383555	13383465	C# console application threading issue with Tasks	foreach (KeyValuePair<string, List<string>> entry in productDictionary) \n{\n  string writePath = String.Format(@"{0}\{1}-{2}.txt", directoryPath, hour, entry.Key);\n  List<string> list = entry.Value; // must add this.\n  Task writeFileTask = Task.Factory.StartNew(() => WriteProductFile(writePath, list));\n}	0
13847472	13847186	Formatting a query to enumerate through 2 different datatables	var matched = from s in sendTable.AsEnumerable()\n              join r in recvTable.AsEnumerable() on\n              new {BUS = s.Field<int>("BUS"), IDENT = s.Field<int>("IDENT"),...} equals\n              new {BUS = r.Field<int>("BUS"), IDENT = r.Field<int>("IDENT"),...}\n              select new {Send = s, Receive = r};	0
854987	854971	How to Insert Multiple Rows in a foreach command with LINQ?	EngineDB.SubmitChanges();	0
1037932	1037795	Getting an export from an MEF container given only a Type instance	var export = _container.GetExports(someType, null, null).FirstOrDefault();	0
20167518	20167478	How to assign different values to a string variable using in branches of if condition	string myOutput = "image.png";\nstring statementOutput;\n\nif (myOutput.Contains("youtu.be"))\n{\n    statementOutput = "Video output";\n}\nelse\n{\n    if (myOutput.Contains(".png"))\n    {\n        statementOutput = "Image output";\n    }\n    else\n    {\n        statementOutput = "Nothing's here";\n    }\n}\n\nLabel1.Text = statementOutput;	0
11477126	11476597	Creating Video from generated bitmap images c#	DispatcherTimer dt = new DispatcherTimer();\ndt.Interval = 25;  //25 ms --> 50 frames per second\ndt.Tick += delegate(object sender, EventArgs e){\n\n             //get the image and display it\n\n          }\n\ndt.Start(); //to start record	0
14792590	12333279	Using the Redpark SDK in MonoTouch	rscMgr.Write(ref txbuffer[0],1);	0
17179237	17090454	Messages answers Grouped By the Parent Original Message	var model=Messages\n             .OrderBy(o=>o.MessageParent_Id==0?Id:o.MessageParent_Id)\n             .ThenBy(o=>o.Id);	0
8460082	8458963	size of the next queued datagram - UDP	SocketError error;\nbyte[] buffer = new byte[512]; // Custom protocol max/fixed message size\nint c = this.Receive(buffer, 0, buffer.Length, SocketFlags.None, out error);\n\nif (error != SocketError.Success)\n{\n    if(error == SocketError.MessageSize)\n    {\n        // The message was to large to fit in our buffer\n    }\n}	0
26716672	26662534	How to save text values from web page locally and is it possible to have web page front end, C# back end?	var userInput = document.getElementById("userInputId").value;\n\nvar fileURL = 'data:application/notepad;charset=utf-8,' + encodeURIComponent(userInput);\nvar fileName = "test.txt";\n\n\nif (!window.ActiveXObject) {\n  var save = document.createElement('a');\n  save.href = fileURL;\n\n  save.target = '_blank';\n  save.download = fileName || 'unknown';\n\n  var event = document.createEvent('Event');\n  event.initEvent('click', true, true);\n  save.dispatchEvent(event);\n  (window.URL || window.webkitURL).revokeObjectURL(save.href);\n}\n\n// for IE\nelse if (!!window.ActiveXObject && document.execCommand) {\n  var _window = window.open(fileURL, '_blank');\n  _window.document.close();\n  _window.document.execCommand('SaveAs', true, fileName || fileURL)\n  _window.close();\n}	0
5152243	5152191	Convert DateTime Format	DateTime.ParseExact("3/1/2011 12:00:00 AM", "G", \n           CultureInfo.GetCultureInfo("en-US")).ToString("yyyy-MM-dd");	0
27383913	27382917	Attach unencrypted tag data to encrypted file	Header (5 bytes):\n    Version* (1 byte, unsigned int)         = 1\n    Metadata Length** (4 bytes, unsigned int) = N\n\nMetadata (N bytes):\n    well formed XML\n\nEncrypted Data (rest of file)	0
23244030	23243869	Streaming in images to Unity	Resources.Unload	0
9846284	9845620	Implementing interface properties in interfaces?	interface IReportParams\n{\n    IEnumerable<Guid> SelectedItems { get; }\n    IEnumerable<StatusEnum> SelectedStatuses { get; }\n}\n\nclass MvcReportParams : IReportParams\n{\n    public MvcReportParams()\n    {\n        SelectedItems = new Collection<Guid>();\n        SelectedStatuses = new Collection<StatusEnum>();\n    }\n\n    public IEnumerable<Guid> SelectedItems { get; private set; }\n    public IEnumerable<StatusEnum> SelectedStatuses { get; private set; }\n}\n\nclass WpfReportParams : IReportParams\n{\n    public WpfReportParams()\n    {\n        SelectedItems = new ObservableCollection<Guid>();\n        SelectedStatuses = new ObservableCollection<StatusEnum>();\n    }\n\n    public IEnumerable<Guid> SelectedItems { get; private set; }\n    public IEnumerable<StatusEnum> SelectedStatuses { get; private set; }\n}	0
15547029	15540508	add files to solr with C#	Dictionary<string, object>	0
24776149	24776023	How to specify name of configuration type?	Add-Migration -ConfigurationTypeName ConfigNameGoesHere addedMessageProperty	0
347587	347575	How to check if a computer is responding from C#	System.Net.NetworkInformation	0
5881186	5881115	how to Post multiple records to website from c#?	SqlCommand cmd = new SqlCommand("select top 10 field1, field2, field3, field4 prices", conn);\n\nSqlDataReader rd = cmd.ExecuteReader();\n\n\nwhile (rd.Read())\n{\n\n\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);\n\nreq.Method = "POST";\n\nreq.ContentType = "application/x-www-form-urlencoded";\n\n\nWebResponse rs; string strNewValue;\n\nStreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);\n\n\nstrNewValue = "field1='" + rd[0].ToString() + "'&field2='" + rd[1].ToString() + "'&field3='AM'&field4=" + rd[2].ToString();\n\nstOut.Write(strNewValue);\nstOut.Close();\nrs = req.GetResponse();\n\n}\n\nrd.Close();	0
22421514	22420558	How to replace the Text value with another string inside SelectListItem or SelectList mvc3?	List<SelectListItem> listService = Model.ServiceTypeList.Select(x => new SelectListItem { Text = x.Text.Replace("A", "X").Replace("A", "X"), Value = Convert.ToString(x.Value) }).Cast<SelectListItem>().ToList();	0
32583631	32583235	DateTime.Now value differs based on Android devices	System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");\nConvert.ToDateTime("9/16/2017 12:16:00 PM", enUS);	0
7277346	7277228	Implement a Save method for my object	internal static class DataLayer {\n\n    public static bool Update(int id, string label) {\n        // Update your data tier\n        return success; // bool whether it succeeded or not\n    }\n}\n\ninternal class BusinessObject {\n\n    public int ID {\n        get;\n        private set;\n    } \n\n    public string Label {\n        get;\n        set;\n    } \n\n    public bool Save() {\n        return DataLayer.Update(this.ID, this.Label); // return data layer success\n    }\n}	0
6765341	6765281	code to run my application in system tray	System.Windows.Forms.NotifyIcon	0
22165965	21873784	Loading StateMachine Elements in Workflow Rehosted Designer	ToolboxItemWrapper(typeof ( System.Activities.Core.Presentation.FinalState))	0
17216990	17216881	How to disable menu items?	if(UserType == "Power-User")\n        {\n        MenuItem mnuItem = Menu1.FindItem("MenuOption"); // If delete a specific item\n\n         //to remove\n         Menu1.Items.Remove(mnuItem);\n         //to disable and not remove \n         mnuItem.Enabled = false;\n        }\n        if (UserType == "BT_User")\n      { \n       Your other logic\n      }	0
20857083	20844873	Grabbing specific, non-specific occurrances of a string with RegEx	new Regex("//i.4cdn.org/" + board + "/src/[^.]+\\." + fileType, RegexOptions.Singleline);	0
20408099	20408030	Storing multiple values, some needing to be changed at run-time, to be refered to by a single key	class YourValue\n{\n    public int A;\n    public float B;\n    public string C;\n}\n\nDicitonary<int, YourValue> yourDictionary;	0
17044303	17043230	Not able to view the latest file from a directory in ASP.NET	"&t=654102310650"	0
13006598	13006355	Datetime insert in sql shows error when having date as a foreign language	string query = "INSERT INTO mytable (p_num, p_date) SELECT @num,@dt";\nusing (SqlConnection conn = new SqlConnection("....."))\n{\n    conn.Open();\n    using (SqlCommand cmd = new SqlCommand(query, conn))\n    {\n        cmd.Parameters.AddWithValue("num", 1);\n        cmd.Parameters.AddWithValue("dt", DateTime.Today);\n\n        cmd.ExecuteNonQuery();\n    }\n    conn.Close();\n}	0
21352228	21352083	Assembly.LoadFrom get Custom Attribute	var asm = Assembly.LoadFrom(@"C:\References\WebDemoAttributes.dll");\n\nvar myClassType = asm.GetTypes()\n                     .FirstOrDefault(t => t.GetCustomAttributes()\n                     .Any(a => a.GetType().Name == "ClassAttribute"));	0
4146714	3981813	How can I force LINQ to SQL to perform an INNER JOIN on a nullable foreign key?	using (MyDataContext context = CreateDataContext())\n{\n    // Set the load options for the query (these tell LINQ that the\n    // DataNode object will have an associated DataObject object just\n    // as before).\n    context.LoadOptions = StaticLoadOptions;\n\n    // Run a plain old SQL query on our context.  LINQ will use the\n    // results to populate the node object (including its DataObject\n    // property, thanks to the load options).\n    DataNode node = context.ExecuteQuery<DataNode>(\n        "SELECT * FROM Node INNER JOIN Object " +\n        "ON Node.ObjectId = Object.ObjectId " +\n        "WHERE ObjectId = @p0",\n        objectId).FirstOrDefault();\n\n    //...\n}	0
21755785	21689007	Image Binding with UriSource from the user Picture library Windows 8	BitmapImage bitmapImage = new BitmapImage();\nif (file != null)\n{\n    FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);\n    bitmapImage.SetSource(stream);\n}\n\nImageUri = bitmapImage;	0
31195470	31192453	Ensuring that a file saves before databind	XmlDataSource1.Data = null.\n XmlDataSource1.Data = gsXML.OuterXml	0
1762981	1762966	linq query from more tables	public ActionResult myItems() {\n    var dataContext = new RecordsDataContext();\n    var query = from i in dataContext.myItems\n                join ou in dataContext.OtherUsers\n                on i.id_user equals ou.id_user //check real reference, since I don't know\n                join mu in dataContext.myUsers\n                on ou.id_user equals mu.id_user\n                where mu.username == Membership.GetUser().UserName.ToString()\n                select i;\n    return View(query);\n}	0
9600032	9586307	Javascript troubles with IE 9	function CallSilverlight() \n{\n  if(silverlightControl != null)\n  {\n    silverlightControl.Content.SilverlightScriptableObject.PerformRfidRead(); //**2**  \n  }\n}	0
10541144	10541004	Drag and drop from C# to Outlook	//put the file path is a string array\nstring[] files = new String[1];\nfiles[0] = @"C:\out.txt";\n\n//create a dataobject holding this array as a filedrop\nDataObject data = new DataObject(DataFormats.FileDrop, files);\n\n//also add the selection as textdata\ndata.SetData(DataFormats.StringFormat, files[0]);\n\n//do the dragdrop\nDoDragDrop(data, DragDropEffects.Copy);	0
16188818	14797670	How to set Focus in Unbounded datagridview specified columns?	DataGridView1.CurrentCell = DataGridView1[columnnumber,rownumber];\n\nTo put it in edit mode: \nDataGridView1.BeginEdit(true);	0
27787753	27784325	add item combobox with datasource	const int EMPTYCUSTOMERKEY = -1;  //be sure Customers will not contain this value\nconst string EMPTYCUSTOMERVALUE = "<select one customer>";\n\nMyclass m = new Myclass();\nDictionary<int, string> customerSource = m.LoadCustomers();\n\ncustomerSource.Add(EMPTYCUSTOMERKEY, EMPTYCUSTOMERVALUE);\n\ncombo1.DataSource = new BindingSource(customerSource, null);\ncombo1.DisplayMember = "Value";\ncombo1.ValueMember = "Key";	0
4710071	4709646	How do i add a string after text if it's not already there?	var sbOut = new StringBuilder();\n    var combined = String.Join(Environment.NewLine, textbox1.Lines);\n    //split string on "name:" rather than on lines\n    string[] lines = combined.Split(new string[] { "name:" }, StringSplitOptions.RemoveEmptyEntries);\n    foreach (var item in lines)\n    {\n        //add name back in as split strips it out\n        sbOut.Append("name:");\n        //find first space\n        var found = item.IndexOf(" ");\n        //add username IMPORTANT assumes no spaces in username\n        sbOut.Append(item.Substring(0, found + 1));\n        //Add thumbnail:example.com if it doesn't exist\n        if (!item.Substring(found + 1).StartsWith("thumbnail:example.com"))                \n            sbOut.Append("thumbnail:example.com ");\n        //Add the rest of the string\n        sbOut.Append(item.Substring(found + 1));\n\n\n    }	0
22170825	22170723	How To Set Many Elements Visible Property at one time in ASP.NET	protected void Page_Load(object sender, EventArgs e)\n{\n    HideRadioButtonLists(Page.Controls);\n}\n\nprivate void HideRadioButtonLists(ControlCollection controls)\n{\n    foreach (WebControl control in controls.OfType<WebControl>())\n    {\n        if (control is RadioButtonList)\n            control.Visible = false;\n        else if (control.HasControls())\n            HideRadioButtonLists(control.Controls);\n    }\n}	0
25794043	25793912	How can I read the next DataGridView row?	for(int i=0;i<datagrid.Rows.Count;i++){\n    val=datagrid[0,i].Value.Tostring();   // 0 is column no\n}	0
25304910	25304706	How do I create specific text format in a text file?	using( StreamWriter w = new StreamWriter(@"C:\Temp\test\test.txt"))\n{\n    for (int k = 0; k < ret.GetLength(0); k++)\n    {\n        w.Write("{");\n        for (int l = 0; l < ret.GetLength(1); l++)\n        {\n            var val = ret[k, l];\n            w.Write(val + ",");\n        }\n        w.WriteLine("},");\n    }\n}	0
12452563	12452542	Trying to call method of object indexed in ArrayList in C#	(Unit.unitArray[selectedUnit] as MyClass).DisplayUnitAttributes()	0
30659563	30593351	Serializing objects bigger than 2MiB to Json in Asp.net	web.config	0
13601174	13601118	Dynamically creation of controls in asp.net c#	Panel panel1 = new Panel();\npanel1.Controls.Add(yourLabel); // add your dynamically created controls\nthis.Page.Controls.Add(panel1); // add the panel to your page	0
24320960	24320907	set random color to a textbox from a set of colors in windows phone?	Color[] fore=  {Color.Yellow,Color.Red,Color.Blue,Color.White,Color.Green };\n     int sIndex = rnd.Next(fore.Length);\n     textblock.Foreground = new SolidColorBrush(fore[sIndex]);	0
13165838	13142173	DynamicDataDisplay ChartPlotter remove all plots	EnumerableDataSource<Point> m_d3DataSource;\npublic EnumerableDataSource<Point> D3DataSource {\n    get {\n        return m_d3DataSource;\n    }\n    set {                \n        //you can set your mapping inside the set block as well             \n        m_d3DataSource = value;\n        OnPropertyChanged("D3DataSource");\n    }\n}     \n\nprotected void OnPropertyChanged(PropertyChangedEventArgs e) {\n    PropertyChangedEventHandler handler = PropertyChanged;\n    if (handler != null) {\n        handler(this, e);\n    }\n} \n\nprotected void OnPropertyChanged(string propertyName) {\n    OnPropertyChanged(new PropertyChangedEventArgs(propertyName));\n}	0
548123	548091	DataGridView Update	TableType table = (TableType) stagingGrid.DataSource;\nmyStagingTableAdapter.Update(table);	0
2916180	2915979	How do I work with WIndows Forms in WPF?	System.Windows.Forms.DialogResult dres;\n dres = form.ShowDialog();\n if (dres != System.Windows.Forms.DialogResult.OK) return;	0
8606040	8606024	C#: How to design a generic class so that the type parameter must inherit a certain class?	public class MyClass<T> where T: IAmSomethingSpecial	0
1362351	1334894	Multiview - View Clear State	var Id = Convert.ToInt32((ID.Value)); \n\ntblV updateV = new tblV();        \nupdateV.vID = venueId;        \nupdateV.vame = updateName.ToString();        \nupdateV.vPostcode = updatePropPostcode.ToString();  \n\nnotYetUpdated.Visible = false;    \nupdateSuccessFailed.Visible = true; \n\nif (vRepos.Update(updateV))        \n{                   \nupdateMessage.Text = "Updated.";        \n}        \nelse        \n{     \nupdateMessage.Text = "An error has occurred, please try again.";        \n}	0
28887027	28886852	Assert that text has been input - Selenium Web Driver	string id = "mainContentPlaceHolder_registrationWizard_txtFirstname";\nIWebElement firstName = driver.FindElement(By.Id(id));\nfirstName.SendKeys("1");\n\nAssert.AreEqual(firstName.GetAttribute("value"),"1")	0
30055819	30055045	Condensing a large combination of data type specific foreach loops into one simple function	class MainClass\n{\n    static void Main()\n    {\n        var houses = new [] {\n            new { number = 1 },\n            new { number = 2 }\n        };\n\n        var streets = new[] {\n            new { name = "AAA" },\n            new { name = "BBB" }\n        };\n\n        var q = CartesianProduct (\n            houses.Select (x => x.number.ToString()),\n            streets.Select (x => x.name)\n        );\n\n        foreach( var item in q )\n            Console.WriteLine(string.Join(" ", item));\n    }\n\n\n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(params IEnumerable<T>[] lists) \n    {\n        IEnumerable<IEnumerable<T>> result = new[]{ new T[]{} }; \n        foreach(var list in lists) \n            result = from previous in result \n                    from current in list\n                    select previous.Concat(new[] {current}); \n        return result; \n    }   \n}	0
41149	40680	How do I get the full url of the page I am on in C#	Request.Url.ToString()	0
28602015	28601983	Pass list of strings to webservice	ASMXWebServiceReference.ArrayOfString myArray = new ASMXWebServiceReference.ArrayOfString();\nmyArray.AddRange(emailsToFollow);	0
23983971	23983943	Generics in a dictionary used for mapping	interface IMyMap {\n    ...\n}\nclass MyMap<T> : IMyMap {\n    public Func<T, T> Map { get; set; }\n}\n\nvar dict = new Dictionary<string, IMyMap> {\n    { "Open", new MyMap<bool> { ... }\n};	0
1473633	1471534	WPF Datagrid RowDetailsTemplate visibility bound to a property	private void Details_Click(object sender, RoutedEventArgs e)\n    {\n      try\n      {\n        // the original source is what was clicked.  For example \n        // a button.\n        DependencyObject dep = (DependencyObject)e.OriginalSource;\n\n        // iteratively traverse the visual tree upwards looking for\n        // the clicked row.\n        while ((dep != null) && !(dep is DataGridRow))\n        {\n          dep = VisualTreeHelper.GetParent(dep);\n        }\n\n        // if we found the clicked row\n        if (dep != null && dep is DataGridRow)\n        {\n          // get the row\n          DataGridRow row = (DataGridRow)dep;\n\n          // change the details visibility\n          if (row.DetailsVisibility == Visibility.Collapsed)\n          {\n            row.DetailsVisibility = Visibility.Visible;\n          }\n          else\n          {\n            row.DetailsVisibility = Visibility.Collapsed;\n          }\n        }\n      }\n      catch (System.Exception)\n      {\n      }\n    }	0
5971542	5971495	How would you approach this simple string parsing problem?	myString = Regex.Replace(myString, @"\s+", " ").Trim();	0
5727788	5727053	how to give the chance to update or rename the treelist node at the time of inserting?	TreeListNode node = treeList.AppendNode(..);\ntreeList.FocusedNode = node;\ntreeList.ExpandAll();\ntreeList.ShowEditor();	0
22871081	22870251	How to Deserialize a xml file's listed items which is present within another listed items	static void Main(string[] args)\n    {\n        var xml ="<?xml version=\"1.0\"?><School><Classes numberOfFields=\"5\"><Class name=\"10\" dataType=\"double\"><Section value=\"A\"/><Section value=\"B\"/><Section value=\"C\"/></Class><Class dataType=\"double\"/><Class dataType=\"double\"/><Class dataType=\"double\"/><Class dataType=\"double\"/></Classes></School>";\n        School result;\n        var serializer = new XmlSerializer(typeof(School));\n        var xmlDoc = new XmlDocument();\n        xmlDoc.LoadXml(xml);\n        using (var reader = new XmlNodeReader(xmlDoc))\n        {\n            result = (School)serializer.Deserialize(reader);\n        }\n    }\n\n\npublic class School\n{\n    [XmlArray("Classes")]\n    [XmlArrayItem("Class")]\n    public List<Class> Classes { get; set; }\n}\n\npublic class Class\n{\n    [XmlElement("Section")]\n    public List<Section> ClassSections { get; set; }\n}\n\npublic class Section\n{\n    [XmlAttribute("value")]\n    public string Value { get; set; }\n}	0
20206903	20206624	Getting All Items Earlier Than Now From DB	db.ScheduledTasks.Where(s => s.date < System.DateTime.UtcNow);	0
858881	857494	Change DNS Zone from secondary to Primary with WMI ChangeZoneType	enter code here\n    For Each DNSZone As ManagementObject In mgrZones            \n         DNSZone("zonetype") = 1 'sets it to primary\n         DNSZone.Put()\n   Next	0
8041452	8041343	How to Split a Byte[]	IEnumerable<byte[]> Split(byte splitByte, byte[] buffer) \n{\n    List<byte> bytes = new List<byte>();\n    foreach(byte b in buffer) \n    {\n        if (b != splitByte)\n            bytes.Add(b);\n        else\n        {\n            yield return bytes.ToArray();\n            bytes.Clear();\n        }\n    }\n    yield return bytes.ToArray();\n}	0
1651957	1626902	How to set DataGridViewColumn data Type at RunTime based on the cell's value?	if (this.dataGridViewName[e.ColumnIndex, e.RowIndex].Value.ToString().StartsWith("http"))\n        {\n            Process p = new Process();\n            p.StartInfo.FileName = Utilities.getDefaultBrowser();\n            p.StartInfo.Arguments = this.dataGridViewName[e.ColumnIndex, e.RowIndex].Value.ToString();\n            p.Start();\n        }	0
4153847	4139887	How do I get the _id of the rcently inserted document after an insert using mongo csharp?	//user = users.Save(user);\nusers.Save(user);\n\nstring idStr = user["_id"].ToString();\n\nConsole.WriteLine("_id == {0}", idStr);	0
30342454	30342119	Trying to change a XML node with no success	var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);\nnsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);\nvar node = xmlDoc.SelectSingleNode("/ns:MTConnectDevices/ns:Devices/ns:Device/ns:Description", nsmgr);	0
6655493	6650742	Why select a new value in repository combobox but it cannot be fetched in the gridcontrol?	object value = (sender as BaseEdit).EditValue;\nif(value != null)\n  string format = value.ToString();        \n  if (format.Equals(stringA))        {            \n    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, view.Columns.ColumnByFieldName("field3Name"), intA);	0
2017081	2017046	Databind a List with a Template to a Dropdown Datasource	public class OwnedProvinces \n{   \n    public Guid ProvinceID { get; set; } \n    public string ProvinceName { get; set; }\n}	0
19335027	19331456	Post JSON Array to WCF Rest Service Results in Empty Parameters. DataContract?	[DataContract]\npublic class Marker\n{\n   [DataMember]\n   decimal position { get; set; }\n   [DataMember]\n   int markerPosition { get; set; }\n}	0
14168487	14168439	How to get file size in WinRT?	storageFile.getBasicPropertiesAsync().then(\n    function (basicProperties) {\n        var size  = basicProperties.size;\n    }\n);	0
8510438	8510348	How to write a Linq to SQL join query with parameter which returns columns from both table?	var result =\n    from d in dbContext.Domains\n    join ic in dbContext.Image_Categories on d.domCode equals ic.icDomainCode\n    where d.domCode == 'code'\n    select new { ic.icCategory, d.domHosting, d.domCode }	0
12645529	12644925	DataTable DataView - Bit Value in Database	Admin = datarowviewUsers["Administrator"].ToString() == "True" ? true : false	0
32812161	32652241	Read up to nth level of list using Linq and save required data to another list	// Declare the function so that it can be referenced from within\n// the function definition.\nFunc<Node, object> convert = null;\n\n// Define the function.\n// Note the recursive call when setting the 'Children' property.\nconvert = n => new \n{\n    id = n.AssociatedObject.ID,\n    name = n.AssociatedObject.Name,\n    children = n.Children.Select(convert)\n};\n\n// Convert the list of nodes to a list of the new type.\nvar jsonTree = \n    nodes\n    .Select(convert)\n    .ToList();	0
4067380	3997548	C#, TeamCity - Avoiding the post build events on the TeamCity server	- root\n|-- bin\n|-- build\n|-- lib\n|-- src\n|-- tools	0
11868916	11867619	Looping through node created by HtmlAgilityPack	HtmlWeb w = new HtmlWeb();\nHtmlDocument doc = w.Load("http://www.google.com/patents/US3748943");\nforeach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='patent_bibdata']/br[1]/preceding-sibling::a"))\n{\n    Console.WriteLine(node.InnerHtml);\n}	0
29258154	29258026	How to float.Parse or TryParse to a single Console.WriteLine in c#	((float)y)/50	0
12573953	12573592	Can I deduce the previous row from a DGV's DefaultValuesNeeded event?	private void dataGridViewPlatypi_CellEnter(object sender,   DataGridViewCellEventArgs args)\n{\n    string prevVal = string.Empty;\n    if (args.RowIndex > 0)\n    {\n        prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.ToString();\n    } else if (args.ColumnIndex > 1)\n    {\n        prevVal = dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex-1].Value.ToString();\n    }\n    dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal;\n}	0
6723585	6723560	Using values for a ListBox from a text file in C#	listBox1.Items.AddRange(File.ReadAllLines(@"C:\file.txt"));	0
8757990	8757864	LINQ group by date descending, and order by time ascending	IEnumerable<A> sorted = listOfA.OrderByDescending(a => a.Start.Date)\n                               .ThenBy(a => a.Start.TimeOfDay);	0
26802860	26802724	Convert a Flag Enum to another Flag Enum in C#	EnumTypeOne a = EnumTypeOne.STUFF_ONE|EnumTypeOne.STUFF_TWO;\nEnumTypeTwo b = (EnumTypeTwo)a;	0
30275635	30271557	Multiple REST API requests using PLinq	var tasks = File.ReadLines(filepath).Select(url => client.GetAsync(url));\nvar results = await Task.WhenAll(tasks);	0
6073286	6063551	Telerik reporting in Silverlight, parameters are not arriving to server	public ObjectInstancesReport()\n    {\n        //\n        // Required for telerik Reporting designer support\n        //\n        InitializeComponent();\n\n        table1.ItemDataBinding += new EventHandler(table1_ItemDataBinding);\n        this.DataSource = null;\n\n        this.Report.NeedDataSource += new EventHandler(Report_NeedDataSource);\n    }\n\n    void Report_NeedDataSource(object sender, EventArgs e)\n    {\n        var objectTypeId = this.ReportParameters["ObjectTypeId"].Value == null ? 1 : Convert.ToInt32(this.ReportParameters["ObjectTypeId"].Value);\n        var searchText = (string)this.ReportParameters["SearchText"].Value;\n        var page = this.ReportParameters["Page"].Value == null ? 1 : Convert.ToInt32(this.ReportParameters["Page"].Value);\n        var pageSize = this.ReportParameters["PageSize"].Value == null ? 20 :  Convert.ToInt32(this.ReportParameters["PageSize"].Value);	0
8847132	8831821	Change line colour in Excel 2007 chart series	MSExcel.Series Series1 = (MSExcel.Series)Chart.SeriesCollection(1);\nSeries1.Border.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(79, 129, 189));	0
19888936	19888889	Datetime Hour and Min formatting in xaml	Text="{Binding BookedFrom,StringFormat={}{0:HH:mm}}"	0
11797418	11797392	Getting an error when checking the length of a variable that might be null	if (Model.Notes!=null)\n{\n\n  if(Model.Notes.Length == null || Model.Notes.Length < 170)\n  {\n      //do the same awesome thing..\n  }\n\n}	0
21363676	21363488	Temporary disallow access to certain page	Response.Redirect("Thealertpage.aspx");	0
28026641	28026592	How to find the position of a letter in a word with similar characters using IndexOf()	String.IndexOf(string value, int startIndex)	0
5418405	5418359	in C#, how can i take an image from a URL and convert to System.Data.Linq.Binary	byte[] raw;\nusing(var client = new WebClient()) { // in System.Net\n    raw = client.DownloadData(url);\n}\nvar binary = new Binary(raw); // in System.Data.Linq	0
31852948	31848431	How to close a IWpfTextView based on a condition from the IWpfTextViewCreationListener - VsTextViewCreated	var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));\nMicrosoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;\nMicrosoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);\n\nMicrosoft.VisualStudio.Shell.Interop.IVsUIHierarchy uiHierarchy;\nuint itemID;\nMicrosoft.VisualStudio.Shell.Interop.IVsWindowFrame windowFrame;\nMicrosoft.VisualStudio.Shell.VsShellUtilities.IsDocumentOpen(serviceProvider, _iTextDocument.FilePath, Guid.Empty, out uiHierarchy, out itemID, out windowFrame);\n\nwindowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);	0
20245220	20245151	Get Multiple CheckBoxList Values In WinForms	var values = MyMultiListComboBox.SelectedItems.Cast<Customer>()\n                                .Select(x=>x.Id).ToList();	0
8281900	8281869	detect keypress event for all textboxes inside a nested TableLayoutPanel	private void Recursive(TableLayoutPanel tableCriterias)\n{\n    foreach (var control in tableCriterias.Controls)\n    {\n        var textBox = control as TextBox;\n        if (textBox != null)\n            textBox.KeyPress += new KeyPressEventHandler(this.ApplyFiltersOnEnterKey);\n        else if(control is TableLayoutPanel)\n            Recursive(control as TableLayoutPanel);\n    } \n}	0
31679794	31470203	Generate a Guid only with strings that could bind to BindableName property without converting it to string from alphanumeric,to avoid duplicacy	Guid guidValue = Guid.NewGuid();\nMD5 md5 = MD5.Create();\nGuid hashed = new Guid(md5.ComputeHash(guidValue.ToByteArray()));	0
17474443	17472072	how to create autofac factory for dependency resolution	public class DbContextFactory\n{\n    private ILifetimeScope m_RootLifetimeScope;\n\n    public DbContextFactory(ILifetimeScope rootLifetimeScope)\n    {\n        m_RootLifetimeScope = rootLifetimeScope;\n    }\n\n    public IDbContext CreateDbContext()\n    {\n        if (logic for selection first dbcontext)\n        {\n            return m_RootLifetimeScope.ResolveNamed<IDbContext>("first");\n        }\n        else if (logic for selection second dbcontext)\n        {\n            return m_RootLifetimeScope.ResolveNamed<IDbContext>("second");\n        }\n        else \n        {\n            throw new NotSupportedException();\n        }\n    }\n}\n\n//registration\n\nbuilder.RegisterType<DbContextFactory>().SingleInstance();\n\n//using\n\nvar factory = yourContainer.Resolve<DbContextFactory>();\nvar context = factory.CreateDbContext();	0
25093278	25093267	Can I get a method by signature, using reflection?	public MethodInfo GetMethod(\n    string name,\n    Type[] types\n)	0
3775185	3775047	fetch column names for specific table	var conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND.mdb";\nusing (var con = new OleDbConnection(conStr))\n{\n    con.Open();\n    using (var cmd = new OleDbCommand("select * from Suppliers", con))\n    using (var reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))\n    {\n        var table = reader.GetSchemaTable();\n        var nameCol = table.Columns["ColumnName"];\n        foreach (DataRow row in table.Rows)\n        {\n            Console.WriteLine(row[nameCol]);\n        }\n    }\n}	0
20695780	20694493	Matching sql date with .NET date	if(mydbrecord.DateField.Date.ToString("yyyy/MM/dd") == DateTime.Now.Date.ToString("yyyy/MM/dd"))\n{...}	0
8871557	8870931	How to show a decimal corretly formatted in 0.00$ format?	[DisplayFormat(DataFormatString = "{0:###.###$}")]\npublic decimal myVal { get; set; }	0
17493591	17487735	How to read unformatted contents of the numeric cells using NPOI?	string formatProofCellReading(ICell cell)\n{\n    if (cell == null)\n    {\n        return "";\n    }\n    if (cell.CellType == CellType.NUMERIC)\n    {\n        double d = cell.NumericCellValue;\n        return (d.ToString());\n    }\n    return cell.ToString();\n}	0
21384666	21384422	Access image in CS file C# WPF	var SourceUri = new Uri("pack://application:,,,/MyCompany.MyProduct.MyAssembly;component/MyIcon.ico", UriKind.Absolute);\nthisIcon = new BitmapImage(SourceUri);	0
17353106	17349535	Updating Database using Datagrid in C#	DataSet ds;\nOleDbDataAdapter dataAdapter;\nvoid ReadData()\n    {\n        this.ds = new DataSet();\n        string connString = "CONNICTION STRING GOES HERE";\n        this.dataAdapter = new OleDbDataAdapter("QUERY GOES HERE", connString);\n        this.dataAdapter.Fill(this.ds, "TABLE1");\n        this.ds.AcceptChanges();\n        //set the table as the datasource for the grid in order to show that data in the grid\n        this.dataGridView1.DataSource = ds.DefaultViewManager;\n    }\n\n    void SaveData()\n    {\n        DataSet changes = this.ds.GetChanges();\n        if (changes != null)\n        {\n            //Data has changes. \n            //use update method in the adapter. it should update your datasource\n            int updatedRows = this.dataAdapter.Update(changes);\n            this.ds.AcceptChanges();\n        }\n    }	0
15995646	15995543	How Dynamic format string using keydown	private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)\n{\n    if (maskedTextBox1.Text.Length == 1)\n    {\n        maskedTextBox1.Mask = "(00) 00";\n        maskedTextBox1.SelectionStart = 2;\n    }\n}	0
18899042	18898869	how to replace one/multiple spaces into a deliminator using C#	string newStr = string.Join(":", \n                str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));	0
2495736	2495617	Instantiate object from Linq to XML Query	var qry = from country in XElement.Parse(xml).Elements("country")\n              from cc in country.Elements("creditcardype")\n              let api = cc.Element("api")\n              select new CountrySpecificPIIEntity\n              {\n                  Country = (string)country.Attribute("countrycode"),\n                  CreditCardType = (string)cc.Attribute("credicardtype"),\n                  Api = (string)api.Attribute("api"),\n                  FilterList = new List<string>(\n                      from filter in api.Element("filters").Elements("filter")\n                      select filter.Value)\n              };	0
5841277	5841220	how to get the prefect url from html encoded url	string s = HttpUtility.UrlDecode(@"folderpath\Microsoft%202007\chapter1\images");	0
28599121	28584520	Azure Mobile services, C# backend get actually user access token for provider	var serviceUser = this.User as ServiceUser;\n        var identities = await serviceUser.GetIdentitiesAsync();\n        var fbIdentity = identities.OfType<FacebookCredentials>().FirstOrDefault();\n\n        //do whatever you want with the token\n        var facebookClient = new FacebookClient(fbIdentity.AccessToken);\n        dynamic myProfile = await facebookClient.GetTaskAsync("/me");	0
8349738	8327723	Update Button Label	function onSuccess(mathResult){\n    document.getElementById("result").value = mathResult;\n    document.getElementById("btnDivide").value = "test";\n\n}	0
9050245	9050204	Permutation of a list of strings algorithm	for (int m = 0 ; m != 8 ; m++) {\n    string s = "a";\n    if ((m & 1) != 0) s += ",";\n    s += "b";\n    if ((m & 2) != 0) s += ",";\n    s += "c";\n    if ((m & 4) != 0) s += ",";\n    s += "d";\n    Console.WriteLine(s);     \n}	0
30528085	30525830	LINQ Lambda Left join with an Inner join	var query = db.staff\n              .GroupJoin(db.training,\n                         s => s.id,\n                         t => t.staff_id,\n                         (s, t) => new { Staff = s, Training = t.FirstOrDefault() })\n              .Join(db.manager,\n                    gj => gj.Staff.manager_id,\n                    m => m.id,\n                    (gj, m) => new { Staff = gj.Staff, Training = gj.Training, Manager = m })\n              .Where(st => st.Training == null\n                        && st.Manager.id == managerId);	0
4263784	4263742	How do I add a value to a table?	List<string> suggestions = new List<string>();\nsuggestions.Add("Use Lists");	0
8707796	8707759	How to convert a string to UTF8?	UTF8Encoding utf8 = new UTF8Encoding();\nstring unicodeString = "Quick brown fox";\nbyte[] encodedBytes = utf8.GetBytes(unicodeString);	0
22116725	22116678	How to print the type of object in string.format	public override string ToString()\n{\n return String.Format("{0} This is a  [{2}] Called {1}", GetType().Name, SpeciesName,   GoesBy );   \n\n}	0
12640256	12636780	DateTime conversion from Utc to Local in .NET 4.0	localTime= TimeZone.CurrentTimeZone.ToLocalTime(utcTime);	0
5902886	5902852	One to many Enum in C#	/// <summary>\n/// Represent all available status for Transaction\n/// </summary>\n[Flags]\npublic enum TransactionStatus\n{\n    New = 0,\n    Submitted = 1,\n    PendingStatus = 2,\n    Accepted = 4,\n    Rejected = 8,\n    InProgress = 16,\n    Completed = 32,\n    Failed = 64,\n    Canceled = 128\n}\n\n/// <summary>\n/// Represent all available pending status for Transaction\n/// </summary>\n[Flags]\npublic enum PendingStatus\n{\n    PendingA = 256,\n    PendingX = 512,\n    PendingY = 1024\n}  \n\n// Example to set transaction as accepted and pending\n\nvar MyTransactionStatus = Accepted & PendingA;\n\n// How to check transaction is pendingA regardless of its status ?\n\nif (MyTransactionStatus & PendingA == PendingA) ...	0
17400536	17400378	Get start position of byte chunk from a byte array	public static int IndexOfArray<T>(T[] source, T[] search)\n{\n\n    var result = Enumerable.Range(0, source.Length - search.Length)\n                           .Select(i => new\n                           {\n                               Index = i,\n                               Found = source.Skip(i)\n                                  .Take(search.Length)\n                                  .SequenceEqual(search)\n                           })\n                           .FirstOrDefault(e => e.Found);\n    return result == null ? -1 : result.Index;\n}	0
17017841	16980487	Telerik RadPageView in BackStage mode: howto change selected item color without whole new theme?	void radPageView1_SelectedPageChanging(object sender, RadPageViewCancelEventArgs e)\n    {\n        e.Page.Item.BackColor = Color.Red;\n        e.Page.Item.DrawFill = true;\n        e.Page.Item.GradientStyle = GradientStyles.Solid;\n\n        radPageView1.SelectedPage.Item.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local);\n        radPageView1.SelectedPage.Item.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local);\n        radPageView1.SelectedPage.Item.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local);\n    }	0
2826278	2826262	Round a decimal to the nearest quarter in C#	x = Math.Round (x * 4, MidpointRounding.ToEven) / 4;	0
26354915	25998239	How to retrieve values from an array in MongoDB using C#	foreach (BsonDocument nestedDocument in Document["name"].AsBsonArray)\n                        {\n                            Total += Convert.ToDouble(nestedDocument["amount"]);\n                        }	0
2934696	2934525	Dynamic data-entry value store	DATASET Table (Virtual "table")\nID - primary key\nName - Name for the dataset/table\n\nCOLUMNSCHEMA Table (specifies the columns for one "dataset")\nDATASETID - int (reference to Dataset-table)\nCOLID - smallint (unique # of the column)\nName - varchar\nDataType - ("varchar", "int", whatever)\n\nRow Table \nDATASETID\nID - Unique id for the "row"\n\nColumnData Table (one for each datatype)\nROWID - int (reference to Row-table)\nCOLID - smallint\nDATA - (varchar/int/whatever)	0
13152182	13152088	How to send XML request to another server?	wsdl.exe http://myservice/myservice?wsdl\nsvcutil.exe http://myservice/myservice?wsdl	0
1226740	1226726	How do I capture the enter key in a windows forms combobox	protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar == 13)\n    {\n        MessageBox.Show("Enter pressed", "Attention");                \n    }\n}	0
3583128	3582866	Func for 5 arguments	public delegate TResult Func<T1,T2,...,TN,TResult>(T1 arg1, T2 arg2,...,TN argN);	0
16497953	16497898	How do I Compare two char[] arrays for equivalency?	string s = new string(foo1);\nstring t = new string(foo2);\n\nint c = string.Compare(s, t);\nif(c==0){\n    //its equal\n}	0
31153397	31153311	How to select a month in drop down list according current month upon page load?	MonthDropDownList.SelectedIndex = month - 1;	0
32465610	32406964	Returning a 403 from a webapi2 controller	public IEnumerable<Employee> Get(int departmentID)\n{\n   try\n   {\n      return GetEmployees(departmentID);\n   }\n   catch(Exception ex) //assuming invalid dept or unauthorized throw Argument & Security Exceptions respectively\n   {\n        if(ex is SecurityException)\n            throw new HttpResponseException(HttpStatusCode.Forbidden);\n        else if(ex is ArgumentException)\n            throw new HttpResponseException(HttpStatusCode.NotFound);\n        else\n             //handle or throw actual unhandled exception\n    }\n}	0
26854533	26850880	Unable to list the dates from filtered datagridview into combobox	private void PopulateStockDatesIndex()\n{\n    comboBox_stockDates.Items.Clear();\n    comboBox_stockDates.Items.Add("Choose to Filter");\n\n    foreach (DataGridViewRow row in dataGridView_flaggedComments.Rows)\n    {\n        for (int i = 0; i < dataGridView_flaggedComments.Rows.Count - 1; i++)\n        {\n            if (dataGridView_flaggedComments.Rows[i].Cells["Comments_Date"].Value.ToString() != "")\n            {\n                string str = dataGridView_flaggedComments.Rows[i].Cells["Comments_Date"].Value.ToString();\n                DateTime date = DateTime.ParseExact(str, "dd/MM/yyyy h:mm:ss tt", CultureInfo.GetCultureInfo("en-GB"));\n                if (!comboBox_stockDates.Items.Contains(date.ToString("dd/MM/yyyy")))\n                {\n                    comboBox_stockDates.Items.Add(date.ToString("dd/MM/yyyy"));\n\n                }\n                comboBox_stockDates.SelectedIndex = 0;\n            }\n        }\n    }\n}	0
13466669	13464715	How do I set the connection timeout for my AdomdConnection?	Connection Timeout = 0	0
33119164	33116747	how to await till UploadStringAsync method completes	public static  async string  insert(string id, string type, string cat, Action<object,Exception> callback)\n    {\n         ----\n        string result  = await wc.UploadStringTaskAsync(uri, "POST", json);\n\n    }	0
12178135	12178089	Create a Timer which execute a SQL Query for Example after 20 min?	public void StartCheckin(int dueTime)\n{\n    var t = new Timer(new TimerCallback(CancelCheckin));\n    t.Change(dueTime, Timeout.Infinite);\n}\n\nprivate void CancelCheckin(object state)\n{\n    // cancel checkin\n    // dispose of timer\n    ((Timer)state).Dispose();\n}	0
15102957	15102939	access elements inside webbrowser tool	var element = this.objWebBrowser.Document.GetElementsByTagName("button").\n                  Cast<HtmlElement>().Where(e => \n                                            e.GetAttribute("class")).\n                                            FirstOrDefault();\n\nif(element == null) return;\n\nelement.InvokeMember("click");	0
24798185	24798150	copy list of objects into another list of objects	List<Address> addresses = people.Select(p => p.Address).ToList();	0
8636335	8636289	Take objects which attributes contains any element of array	// untested\nvar names = context.Members.Select(m => m.Name).ToList();\nnames = names.Where(n => words.Any(w => n.Contains(w));	0
33868192	33868068	WebClient downloads blank string for any url but only on Webserver	public string RequestUrl(string reqUrl)\n    {\n        WebClient client = new WebClient();\n        try\n        {\n            return client.DownloadString(reqUrl);\n        }\n        catch (Exception e)\n        {\n            return "" + e;\n        }\n    }	0
11135468	11135337	XUnit Assertion for checking equality of objects	Assert.True(obj1.Equals(obj2));	0
6627906	6627882	JSON File to Byte[], need to go Byte[] to JSON string	Encoding.UTF8.GetString(data)	0
24238645	24238036	Rotate cameran around a gameobject in unity3d	public class CameraOrbit : MonoBehaviour\n{\n  public Transform target;\n  public float speed;\n  public float distance;\n  private float currentAngle = 0;\n\n  void Update()\n  {\n      currentAngle += Input.GetAxis(...) * speed * Time.deltaTime;\n\n      Quaternion q = Quaternion.Euler(0, currentAngle, 0);\n      Vector3 direction = q * Vector3.forward;\n      transform.position = target.position - direction * distance;\n      transform.LookAt(target.position);\n  }\n}	0
15270140	15270034	How to retrieve different object types from IQueryable	Server server = query.Single().s;  // first check for nulls and\nserver.CEServer = query.Single().c;	0
14588280	14552273	IronRuby, How to pass argument variables from C# to Ruby?	class Run_Marshal\n\n    def initialize(id, name)\n        @list = []\n        @list[0] = Employee_Info.new(id, name.to_s)\n\n        File.open("employee_sheet.es", "wb") {|f| Marshal::dump(@list, f)}\n    end\nend	0
9209415	9209056	How to move cursor to the next row in datagridview	if (dataGridView1.CurrentRow != null)\n    dataGridView1.CurrentCell =\n        dataGridView1\n        .Rows[Math.Min(dataGridView1.CurrentRow.Index + 1, dataGridView1.Rows.Count - 1)]\n        .Cells[dataGridView1.CurrentCell.ColumnIndex];	0
11250618	11248554	How to retrieve certificate information of a .Net dll in c#	Assembly asm = Assembly.LoadFrom("your_assembly.dll");\nstring exe = asm.Location;\nSystem.Security.Cryptography.X509Certificates.X509Certificate executingCert =\n   System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile(exe); \nConsole.WriteLine (executingCert.Issuer);	0
26952076	26951388	JSON parsing takes way too long	string fileName = @"c:\temp\json\yourfile.json";\n        string json;\n\n        using (StreamReader sr = new StreamReader(fileName))\n        {\n            json = sr.ReadToEnd();\n        }\n\n        response myResponse = fastJSON.JSON.ToObject<response>(json);\n\n        var item = myResponse.First(i => i.defindex == "5051");\n\n        foreach (var price in item.prices)\n        {\n            foreach (var quality in price)\n            {\n                Console.WriteLine("{0} {1}", quality.Tradable.Craftable[0].value, quality.Tradable.Craftable[0].currency);\n                keyprice = quality.Tradable.Craftable[0].value;\n                return keyprice;\n            }\n        }	0
19388699	19388364	Auto Login user from another website?	FormsAuthentication.SetAuthCookie(userName, false);	0
7824989	7824958	How to specify parameters with spaces when starting a new process	string parms =  filechooser.Filename ;      \npsi = new ProcessStartInfo("timidity", "\"" + parms + "\"");	0
14417329	14417108	Relationship between tables	if (db.Memberships.Any(x => x.UserName == model.UserName) \n{\n    // handle error here\n    // return view with error message "user name already in use"\n}\n\nvar token = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, null, true);\nvar membership = db.Memberships.SingleOrDefault(x => x.UserName == model.UserName);\nif (membership != null) \n{\n    var newProfile = new Teacher\n    {\n        Membership = membership\n        // add other properties here if required\n    }\n    db.Teachers.Add(newProfile);\n    db.SaveChanges();\n}	0
2948027	2947561	Send XML String as Response	Request.UrlReferrer.ToString();	0
12740836	12740284	How can I match data to be inserted into my ComboBox in C#	string myXMLfile = @"C:\MySchema.xml";\n    DataSet ds = new DataSet();\n    // Create new FileStream with which to read the schema.\n    System.IO.FileStream fsReadXml = new System.IO.FileStream \n        (myXMLfile, System.IO.FileMode.Open);\n\n        ds.ReadXml(fsReadXml);\n        combobox1.DataSource = ds;\n        combobox1.Displaymember="name";	0
3348483	3348320	Copying ComboBox Items to a StringCollection in C#	Foreach(object o in combobox.items)\n{\n//might need to access a datamember of the combobox's item if more complex solution is required, but this will probably do\nstringcollection.Add(o.ToString);\n}	0
1604812	1604773	Verify Text of item in Listbox is the same one in List<string> C#	if (RemovePackages_Listbox.SelectedItem.ToString() == choicetitle[RemovePackages_Listbox.SelectedIndex])\n            {\n                MessageBox.Show("The above code worked!");\n            }\n\nelse\n{\n    MessageBox.Show("RemovePackages_Listbox.SelectedItem.ToString() is "+RemovePackages_Listbox.SelectedItem.ToString()+" and choicetitle[RemovePackages_Listbox.SelectedIndex] is "+choicetitle[RemovePackages_Listbox.SelectedIndex]);\n}	0
23188872	23188855	I get Anonymous type members must be declared with a member assignment when casting to shortdate?	var json = from r in results\n                   select Convert(new\n                   {\n                       r.CaseId,\n                       r.TamisCaseNo,\n                       r.TaxPdr,\n                       r.OarNo,\n                       r.Tin,\n                       DateReceived = r.DateReceived.ToShortDateString(),\n                       r.IdrsOrgAssigned,\n                       r.IdrsTeAssigned,\n                       r.DateRequestComp\n                   });	0
16706787	16706726	Change date format from ddmmyyyy to yyyyddmm	//example date\nstring dateString= "09301986";\n\n//output date\nDateTime finalDate;        \n\nif (!DateTime.TryParseExact(dateString, "ddMMyyyy", CultureInfo.InvariantCulture,  DateTimeStyles.None, out finalDate))\n{\n   DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture,\n   DateTimeStyles.None, out finalDate);\n\n}\n\nstring finaldate = finalDate.ToString("yyyy-MM-dd");	0
4078749	4078566	find control in panel in datalist	protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n        Panel panel1 = e.Item.FindControl("Panel1") as Panel;   //assume your panel name is Panel1\n        if (panel1 != null)\n        {\n            Label LblHead = panel1.FindControl("LblHead") as Label;\n            if (LblHead != null)\n            {\n                string LanguageID = Globals.GetSuitableLanguage(Page);\n                if (LanguageID == "ar")\n                {\n                    LblHead.Attributes.Add("CssClass", "hed_logo2");\n                }\n            }\n        }\n    }\n}	0
6973895	6973872	How to prevent DOS/Console application that was called using Process class in .NET, from automaticly closing the command prompt after finish?	Process proc = new Process();\n\nproc.StartInfo.UseShellExecute = false;\nproc.StartInfo.RedirectStandardOutput = true;\nproc.StartInfo.FileName = lLocation.Text+"\\pywin32.exe";\nproc.StartInfo.Arguments = lLocation.Text+"\\data.pos";\nproc.Start();\n\nstring output = proc.StandardOutput.ReadToEnd();\nproc.WaitForExit();	0
32881656	32881521	Input string was not in a correct format, tried but unable to resolve	counter = Convert.ToInt32(fbrc_getfabricID.Substring(index + 3));	0
30698802	30697585	I got some values from database dynamically want in whole numbers in C#	Math.Ceiling	0
6075873	6075809	How to use Web Config Files in Silverlight	public static string GetSomeSetting(string settingName)\n        {\n            var valueToGet = string.Empty;\n            var reader = XmlReader.Create("XMLFileInYourRoot.Config");\n            reader.MoveToContent();\n\n            while (reader.Read())\n            {\n                if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")\n                {\n                    if (reader.HasAttributes)\n                    {\n                        valueToGet = reader.GetAttribute("key");\n                        if (!string.IsNullOrEmpty(valueToGet) && valueToGet == setting)\n                        {\n                            valueToGet = reader.GetAttribute("value");\n                            return valueToGet;\n                        }\n                    }\n                }\n            }\n\n            return valueToGet;\n        }	0
15548342	15547675	what am I missing here? DataGrid and ListView not getting populated in WPF application	return @"Integrated Security=True;Data Source=(local);" +\n                     "Initial Catalog=OfficeSupply";	0
18102017	18003560	Fluent NHibernate - column name from property in Session.QueryOver	object a = null;\n\n        return Session.QueryOver<T>()\n               .SelectList(l =>\n                   l.Select(\n                   Projections.GroupProperty(\n                   Projections.SqlFunction("CANDIES", NHibernateUtil.Int32, Projections.Property(expression))\n                   )).WithAlias(() => a)	0
18535880	18535799	Send file+parameters in post request	NameValueCollection parameters = new NameValueCollection();\nparameters.Add("value1", "123");\nparameters.Add("value2", "xyz");\noWeb.QueryString = parameters;\nvar responseBytes = oWeb.UploadFile("http://website.com/file.php", "path to file");\nstring response = Encoding.ASCII.GetString(responseBytes);	0
11492008	11491973	Fill dictionary with sampledata	x:TypeArguments	0
25420551	25420477	Entity framework, can I map a class to a key/value table?	var entities = ...;\nvar o = new StoreConfiguration();\nforeach(var p in typeof(StoreConfiguration).GetProperties())\n{\n   var entity = entities.FirstOrDefault(e=>e.Key == p.Name);\n   if (entity == null) continue;\n\n   var converter = TypeDescriptor.GetConvertor(p.Type);\n   p.SetValue(o, converter.ConvertFromString(entity.Value));\n}	0
4127694	4127270	C# how to loop while mouse button is held down	using Timer = System.Timers.Timer;\nusing Systems.Timers;\nusing System.Windows.Forms;//WinForms example\nprivate static Timer loopTimer;\nprivate Button formButton;\npublic YourForm()\n{ \n    //loop timer\n    loopTimer = new Timer();\n    loopTimer.Interval = 500;/interval in milliseconds\n    loopTimer.Enabled = false;\n    loopTimer.Elapsed += loopTimerEvent;\n    loopTimer.AutoReset = true;\n    //form button\n    formButton.MouseDown += mouseDownEvent;\n    formButton.MouseUp += mouseUpEvent;\n}\nprivate static void loopTimerEvent(Object source, ElapsedEventArgs e)\n{\n    //do whatever you want to happen while clicking on the button\n}\nprivate static void mouseDownEvent(object sender, MouseEventArgs e)\n{\n    loopTimer.Enabled = true;\n}\nprivate static void mouseUpEvent(object sender, MouseEventArgs e)\n{\n    loopTimer.Enabled = false;\n}	0
9906128	9906073	several statements in lambda	var evarage = productionreportentry.Sum(productionReportEntry => \n{ \n   Trace.Writeline(productionReportEntry.Cycletime);\n   return productionReportEntry.Cycletime;\n});	0
31192912	31192748	IndexOf match result positive on unknown character	int indexFound = source.IndexOf(toFind, System.StringComparison.OrdinalIgnoreCase);	0
3293221	3293203	WPF Cannot hide another window	Application.Current.MainWindow.Hide();	0
13508929	13508908	Deviding Text box value by number c#	textBox13.Text = (double.Parse(textbox1.Text) / 536).ToString();	0
13971786	13971730	c# Leaner way of initializing int array	int[] array = Enumerable.Range(0, nums).ToArray();	0
29659179	29658802	Converting listview subitems to double	listView2.Items[i].SubItems[1].Text	0
12945414	12924739	Using VisualStudio's icons	// An aggregate catalog that combines multiple catalogs\nvar catalog = new AggregateCatalog();\n\n// Adds all the parts found in the necessary assemblies\ncatalog.Catalogs.Add(new AssemblyCatalog(typeof(IGlyphService).Assembly));\ncatalog.Catalogs.Add(new AssemblyCatalog(typeof(SmartTagSurface).Assembly));\n\n// Create the CompositionContainer with the parts in the catalog\nCompositionContainer mefContainer = new CompositionContainer(catalog);\n\n// Fill the imports of this object\nmefContainer.ComposeParts(this);	0
20328021	17633785	Changing "required" property of a field in SharePoint 2010 custom Newform.aspx	objListFormWebPart.ItemContext.Fields["fieldDisplayName"].Required = false;	0
14653474	14653462	Change item in collection with LINQ	foreach (var item in allCars.Where(c => c.Model == "Colt"))\n{\n    item.Model = "Dart";\n}	0
1846570	1846549	how to access to LinqToSqlcCasses from another application	System.Data.Linq	0
908646	880609	How to use generics containing private types with Visual Studio Unit Tests	using System.Runtime.CompilerServices;\n\n// ...\n\n[assembly: InternalsVisibleTo("AssemblyATest")]\n[assembly: InternalsVisibleTo("AssemblyAIntegTest")]	0
5788411	5787344	Dependency Injection and specific dependency implementation	public class MyValidator\n{\n    private readonly OneAndOnlyChecksumGenerator checksumGenerator;\n\n    public MyValidator(OneAndOnlyChecksumGenerator checksumGenerator)\n    {\n        this.checksumGenerator = checksumGenerator; \n    }\n\n    // ...\n}	0
17577015	17576796	Insert item at the beginning of dictionary	List<KeyValuePair<int, string>>	0
20300172	20299997	Creating text files with specific names	var myfile = @"C:\myfile"\nforeach (Button bt in mainCanvasGrid.Children)\n{\n   File.WriteAllLines(myfile + bt.Name + ".txt", new []{"[yourtexthere]"});\n}	0
33057448	33057226	How to make a timed delay between two lines of code in C#?	using UnityEngine;\nusing System.Collections;\n\npublic class demo : MonoBehaviour {\n    // Details at: http://docs.unity3d.com/Manual/Coroutines.html\n\n    // Use this for initialization\n    void Start () {\n        // Some start up code here...\n        Debug.Log("Co-1");\n        StartCoroutine("OtherThing");\n        Debug.Log("Co-2");\n    }\n\n    IEnumerator OtherThing()\n    {\n        Debug.Log("Co-3");\n        yield return new WaitForSeconds(0f);\n        Debug.Log("Co-4");\n        DoOneThing();\n        yield return new WaitForSeconds(1f);\n        Debug.Log("Co-5");\n        DoOtherThing();\n    }\n\n    void DoOneThing()\n    {\n        Debug.Log("Co-6");\n    }\n\n    void DoOtherThing()\n    {\n        Debug.Log("Co-7");\n    }\n}	0
16793539	16771799	Metro App WebView for html Hyperlink Navigation to open in browser	/// <summary>\n        /// Regex pattern for getting href links.\n        /// </summary>\n        private static readonly Regex HrefRegex = new Regex("href=\"([^\"]*)\"", RegexOptions.IgnoreCase);\n\n        // Append target="_blank" to all hrefs\n        html = HrefRegex.Replace(html, new MatchEvaluator(HrefReplace));\n\n        /// <summary>\n        /// Replaces the contents of href with href and target.\n        /// </summary>\n        /// <param name="match">The match.</param>\n        /// <returns>The href with target.</returns>\n        private static string HrefReplace(Match match)\n        {\n            return string.Format("{0} target=\"_blank\"", match.Value);\n        }	0
7640703	7638744	Saving changes to eagerly loaded associations in RIA Services	[Association("InstallationDistrict", "DistrictID", "DistrictID", IsForeignKey = true)]	0
3594099	3594091	C# Automatically assign property based on other property values	public class SomeType\n{\n    public string A { get; set; }\n    public string C { get; set; }\n\n    private string _b;\n    public string B \n    { \n        get { return _b; } \n        set \n        { \n            // Set B to some new value\n            _b = value; \n\n            // Assign C\n            C = string.Format("B has been set to {0}", value);\n        }\n    }\n}	0
28277800	28232281	How to consume post/put WCF RestFul Service	string sURL =  @"http://localhost:50353/urUriName/"+ txtfname.Text;\n        WebRequest webGETURL;\n\n        webGETURL = WebRequest.Create(sURL);\n       webGETURL.Method = "DELETE"; \n       webGETURL.ContentType = @"Application/Json; charset=utf-8";\n      HttpWebResponse wr = webGETURL.GetResponse() as HttpWebResponse;\n       Encoding enc=Encoding.GetEncoding("utf-8");\n    // read response stream from response object\n    StreamReader loResponseStream = new StreamReader(wr.GetResponseStream(), enc);\n\n    // read string from stream data\n    string strResult = loResponseStream.ReadToEnd();\n\n    // close the stream object\n    loResponseStream.Close();\n    // close the response object\n    wr.Close();\n    // assign the final result to text box\n    Response.Write(strResult);	0
8581890	5706725	How can I dynamically read a classes XmlTypeAttribute to get the Namespace?	XmlTypeAttribute xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(\n                                   typeof(theType),\n                                   typeof(XmlTypeAttribute)\n                                 );\nXNamespace ns = xmlAttribute.Namespace;	0
17943079	17942734	Bind images to a listbox in wpf	foreach (FileInfo fileInfo in files)\n{\n    if (fileInfo.Extension.Equals(".JPG", StringComparison.InvariantCultureIgnoreCase) ||\n        fileInfo.Extension.Equals(".JPEG", StringComparison.InvariantCultureIgnoreCase) ||\n        fileInfo.Extension.Equals(".GIF", StringComparison.InvariantCultureIgnoreCase) ||\n        fileInfo.Extension.Equals(".PNG", StringComparison.InvariantCultureIgnoreCase))\n    {\n        list.Add(fileInfo.FullName);\n    }\n}	0
1929824	1907698	How to highlight data ranges in excel using C#?	Excel.Application excelApp = ...;\n\nstring prompt = "Please select the range.";\nstring title = "Input Range";\nint returnDataType = 8;\nString DefaultRange = oXL.Selection.Address();\n\nExcel.Range myRange = excelApp.InputBox(\n                          prompt,\n                          title,\n                          DefaultRange,\n                          Type.Missing,\n                          Type.Missing,\n                          Type.Missing,\n                          Type.Missing,\n                          returnDataType)	0
4363581	4353092	How to get SelectedDataKey value in the GridView RowCommand Event?	if (e.CommandName == "printReport")\n        {\n            int rowindex = Convert.ToInt32(e.CommandArgument);\n            int MRLID = Convert.ToInt32(gvMRLSearch.DataKeys[rowindex].Value);	0
7787138	7786609	How to use .NET 4 SplashScreen in a WPF Prism based application?	internal static class Entry\n{\n    public static void Main(string[] args)\n    {\n        var splashScreen = ...;\n        splashScreen.Show();\n\n        var bootstrapper = ...;\n        bootstrapper....;\n    }\n}	0
12050701	12050627	How to View the preview zip files list in c#	if (FileUpload1.HasFile)\n  {\n    using (ZipFile zip = ZipFile.Read(FileUpload1.FileContent))\n    {\n      foreach (ZipEntry entry in zip)\n      {\n        if (entry.IsDirectory)\n          Response.Write("Directory: ");\n        else\n          Response.Write("File : ");\n        Response.Write(entry.FileName + "<br /><br />");\n      }\n    }\n  }	0
5365294	5365213	Get innerText from XElement	XDocument xdoc = XDocument.Load("test.xml");\nvar html = xdoc.Descendants("highlights").First().Value;\n\nHtmlDocument htmlDoc = new HtmlDocument();\nhtmlDoc.LoadHtml(html);\nvar result = htmlDoc.DocumentNode.InnerText;	0
23920954	23920748	Deserializing a JSON file using C#	MyClass myobject=JsonConvert.DeserializeObject<MyClass>(json);	0
17426782	17426762	What's the best way to add a copy of a list in another list?	new List<string>(ls)	0
9984686	9984637	Compare value of int	if ((new[] {1,2,4,5}).Contains(someInt))	0
23081807	22943981	get longListSelector source from a different view	List<MyConnection.locationList.locations> source;\nprivate void Application_Launching(object sender, LaunchingEventArgs e)\n    {\n\n        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n        source = new List<MyConnection.locationList.locations>();\n\n        if (!settings.Contains("firstrun"))\n        {\n            source.Add(new MyConnection.locationList.locations("Dulles, VA"));\n            source.Add(new MyConnection.locationList.locations("Dulles, VA (Q)"));\n        }\n}	0
5482586	5482522	Usage of tragets on events using attributes	using System;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.All,AllowMultiple=false,Inherited=true)]\ninternal class TestAttribute : Attribute\n{\n}\ninternal class Test\n{\n    [event: Test]\n    [field: Test]\n    [method: Test]\n    public event Action action;\n\n    static void Main() \n    {\n        MethodInfo method = typeof(Test).GetEvent("action")\n                                        .GetRemoveMethod(); // Or GetAddMethod\n        Console.WriteLine(method.IsDefined(typeof(TestAttribute), true));\n    }\n}	0
6416341	6416050	How to create a trie in c#	public class Trie\n{\n  public class Node\n  {\n    public string Word;\n    public bool IsTerminal { get { return Word != null; } }\n    public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();\n  }\n\n  public Node Root = new Node();\n\n  public Trie(string[] words)\n  {\n    for (int w = 0; w < words.Length; w++)\n    {\n      var word = words[w];\n      var node = Root;\n      for (int len = 1; len <= word.Length; len++)\n      {\n        var letter = word[len - 1];\n        Node next;\n        if (!node.Edges.TryGetValue(letter, out next))\n        {\n          next = new Node();\n          if (len == word.Length)\n          {\n            next.Word = word;\n          }\n          node.Edges.Add(letter, next);\n        }\n        node = next;\n      }\n    }\n  }	0
4366134	4366068	how to design the component in c# then client can be define parameter at begin and whenever they want to complete the operation using information	public class myControl\n{\n    public myControl()\n    {\n    }\n\n    public myControl(string arg1, string arg2, string arg3)\n    {\n        Arg1 = arg1;\n        Arg2 = arg2;\n        Arg3 = arg3;\n    }\n\n    public void completemytask() {\n        if(String.IsNullOrEmpty(Arg1) || \n           String.IsNullOrEmpty(Arg2) ||\n           String.IsNullOrEmpty(Arg3))\n               throw new ArgumentException("Not all arguments are specified.");\n        else\n               completetask(Arg1, Arg2, Arg3);\n    }\n\n    public void completetask(arg1, arg2, arg3) \n    {\n        // do what you want\n    }\n\n    public string Arg1 { get; set; }\n    public string Arg2 { get; set; }\n    public string Arg3 { get; set; }\n}	0
7687904	7687843	Retrieving random data from sql database no repeat	List<String>	0
23815429	23815153	Xamarin: Set UITextField Height	var f = textField.Frame;\n\n        f.Height = 100f;\n\n        textField.Frame = f;	0
12789259	12789132	Setting a property in VM from current row in observable collection	public Model SelectedItem\n{\n   ...\n}	0
27069874	27069653	Using a base class as parameter	class Program\n    {\n\n    static void Main(string[] args)\n    {\n        ModelBase sp = new SpecificModel2();\n        TestIt(ref sp);\n\n    }\n    public static bool TestIt(ref ModelBase BaseModel)\n    {\n        BaseModel.UserID = 10;\n        BaseModel.UserName = "Evan";\n\n        return true;\n    }\n}\npublic abstract class ModelBase\n{\n    public int UserID { get; set; }\n    public string UserName { get; set; }\n}\n\npublic class SpecificModel : ModelBase\n{\n    public int specificInt { get; set; }\n    public string specificString { get; set; }\n}\n\npublic class SpecificModel2 : ModelBase\n{\n    public int specificInt { get; set; }\n    public string specificString { get; set; }\n}\n}	0
1016863	1016823	C# - How can I rename a process window that I started?	[DllImport("user32.dll")]\nstatic extern int SetWindowText(IntPtr hWnd, string text);\n\n\n\nprivate void StartMyNotepad()\n{\n    Process p = Process.Start("notepad.exe");\n    Thread.Sleep(100);  // <-- ugly hack\n    SetWindowText(p.MainWindowHandle, "My Notepad");\n}	0
24872644	24855696	allowDiskUse in Aggregation Framework with MongoDB C# Driver	var pipeline = new BsonDocument[0]; // replace with a real pipeline\nvar aggregateArgs = new AggregateArgs { AllowDiskUse = true, Pipeline = pipeline };\nvar aggregateResult = collection.Aggregate(aggregateArgs);\nvar users = aggregateResult.Select(x =>\n    new User\n    {\n        Influence = x["Influence"].ToDouble(),\n        User = new SMBUser(x["user"].AsBsonDocument)\n    }).ToList();	0
17254572	17253716	Reading strange xml doc	XmlDocument version = new XmlDocument();\nversion.Load(path);\n\nforeach (XmlNode node in version.ChildNodes[0].ChildNodes)\n{\n    if (node.Name == "Version")\n        MessageBox.Show("Version: " + node.InnerText);\n    else if (node.Name == "Lastfix")\n        MessageBox.Show("LastFix: " + node.InnerText);\n}	0
5450426	5450387	Shell Integrate in Windows for a Specific File Type With C#	.myfile	0
19271759	19271685	Object change in C#	public 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
5410755	5410647	How to pass an array of structures through Postback? 	protected S_indiv _myData;	0
5684791	5684686	Pivot Control - issue with data binding	public ObservableCollection<Basket> baskets = new ObservableCollection<Basket>(); \n\npublic pivotPage() \n{ \n    InitializeComponent(); \n\n    this.DataContext = baskets;\n\n    //for testing purposes \n    baskets.Add(new Basket()); \n    baskets.Add(new Basket()); \n\n}	0
7816933	7816810	recursion-get sequence of parent folders in .Net using recursion	declare @folders as table (id int, name nvarchar(20), parent int);\ninsert into @folders values(1, 'Root',  null);\ninsert into @folders values(2, 'Root_A', 1);\ninsert into @folders values(3, 'Root_B', 1);\ninsert into @folders values(4, 'Root_C', 1);\ninsert into @folders values(5, 'Root_C_A', 4);\ninsert into @folders values(6, 'Root_C_A_A', 5);\ninsert into @folders values(7, 'Root_C_A_A_A', 6);\n\ndeclare @folderID int;\nset @folderID=7;\n\nwith Folders (id, name, parent, number) as\n(\n    select ID, name, parent, 0 as number \n        from @folders \n        where id=@folderID\n    union all\n    select i.ID, i.Name, i.Parent, d.number + 1\n        from @folders as i\n        inner join Folders as d on d.Parent = i.ID\n)\nselect id, name, number\nfrom Folders\norder by number desc;	0
28031154	28031095	How to read data from SQL Database and store it into ComboBox?	string qry = "SELECT [COL1] FROM [TABLE1];\n\n// Store selected records to DataTable\n\nforeach(DataRow row in dt.Rows)\n{\n    comboBox.Items.Add(row[0].ToString());\n}	0
32041270	32041116	Retrieve a list of tree paths	static IEnumerable<IEnumerable<T>> ComputePaths<T>(T Root, Func<T, IEnumerable<T>> Children) {\n    var children = Children(Root);\n    if (children != null && children.Any())\n    {\n        foreach (var Child in children) \n            foreach (var ChildPath in ComputePaths(Child, Children)) \n                yield return new[] { Root }.Concat(ChildPath);            \n    } else {\n        yield return new[] { Root };\n    }\n}	0
4135679	4134194	How can I edit a collection of filenames in a property grid?	[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]\n    public List<string> Files {\n        get { return m_files; }\n        set { m_files = value; }\n    }	0
21302131	21301669	How to call LostFocus event of another control from the other control	private void button2_GotFocus(object sender, RoutedEventArgs e)\n{\n    button1.RaiseEvent(new RoutedEventArgs(LostFocusEvent, button1));\n}\n\n\nprivate void button1_LostFocus(object sender, RoutedEventArgs e)\n{\n\n}	0
1297035	1297033	How do I implement a matching algorithm using predicates?	private static T FindInCollection<T>(ICollection<T> collection, Predicate<T> match)\n{\n    foreach (T item in collection)\n    {\n        if (match(item))\n            return item;\n    }\n    return default(T);\n}	0
13357402	13357237	How can I get the name of the DeploymentItem?	[TestClass]\npublic class Test\n{\n    const string filename = "TestData/TestExcel.xlsx";\n\n    [TestMethod]\n    [DeploymentItem(filename)] \n    public void GivenAnExcel_ConverToPDF()\n    {\n        var result = pdfConverter.ConvertExcelDocument(filename);\n        AssertIsPdf(result);\n    }\n}	0
2811403	2777732	Really annoying bug with TopMost property in Windows Forms	SetWindowPos(hwnd, HWND_TOPMOST, ...)	0
23876207	23875781	Change variable in linq	functional programming	0
27741845	27741752	json expects a property "@class". How to define in c#	public class Test\n{\n    [JsonProperty("@class")]\n    public string Name { get; set; }\n}	0
19070781	19070634	Change datetimepicker displayed date	DateTimePicker dateTimePicker1 = new DateTimePicker();\npublic Form1()\n{\n    InitializeComponent();\n    dateTimePicker1.Format = DateTimePickerFormat.Custom;\n    dateTimePicker1.CustomFormat = "yyyy-mm-dd";\n    //You can play with this to change location\n    dateTimePicker1.Location = new Point(20, 20);\n    this.Controls.Add(dateTimePicker1);\n}	0
21556412	21041151	How can I verify a .jar Java applet signature using c#	using System;\nusing System.Diagnostics;\n\npublic class VerifyJar\n{\n    public static void Main()\n    {\n        Process p = new Process();\n        p.StartInfo.FileName = "jarsigner"; // put in full path\n        p.StartInfo.Arguments = "-verify liblinear-1.92.jar"; // put in your jar file\n        p.StartInfo.UseShellExecute = false;\n        p.StartInfo.RedirectStandardOutput = true;\n        p.Start();\n\n        string output = p.StandardOutput.ReadToEnd();\n        p.WaitForExit();\n\n        // Handle the output with a string check probably yourself\n        // Here I just display what the result for debugging purposes\n        Console.WriteLine("Output:");\n        Console.WriteLine(output);\n\n        // For me, the output is "jar is unsigned. (signature missing or not parsable)"\n        // which is correct for this particular jar file.\n    }\n}	0
26491275	26491214	Using Multiple Conditions with Count - LINQ	r.Count(x => (x.DateOrganized >= startDate.Date) &&\n             (x.DateOrganized <= endDate.Date));	0
4317433	4317402	WPF - Control 2nd window from 1st window	public partial class Window1 : Window\n{\n\n    private bool SecondWindowOpen = false;\n    private Window2 window2;\n\n    public Window1()\n    {\n        InitializeComponent();\n    }\n\n    private void OpenSecondWindow_Click(object sender, RoutedEventArgs e)\n    {\n        if (SecondWindowOpen == false)\n        {\n            window2 = new Window2();\n            window2.Visibility = Visibility.Visible;\n            this.SecondWindowOpen = true;\n        }\n        else\n        {\n            //do whatever you want with window2, like window2.Close();\n            //or window2.Visibility = Visibility.Hidden;\n        }\n    }\n}	0
23323809	23322463	Callling a wcf within android app and passing listview selected item	string num;\nint num2;\n\nnum = "2";\n\n// method 1 - will throw Exception if num is not a parsable int\nnum2 = int.Parse(num);\n\n// method 2 - will not throw exception - if success is true num2 will contain the parsed int\nbool success = int.TryParse(num,out num2);	0
33626689	33481542	c# Randomize DataTable rows	DataTable dt = ds.Tables[0].Copy();\n        if (!dt.Columns.Contains("SortBy"))\n          dt.Columns.Add("SortBy", typeof (Int32));\n\n        foreach (DataColumn col in dt.Columns)\n          col.ReadOnly = false;\n\n        Random rnd = new Random();\n        foreach (DataRow row in dt.Rows)\n        {\n          row["SortBy"] = rnd.Next(1, 100);\n        }\n        DataView dv = dt.DefaultView;\n        dv.Sort = "SortBy";\n        DataTable sortedDT = dv.ToTable();\n\n        rprItems.DataSource = sortedDT;\n        rprItems.DataBind();	0
7371437	7370697	How to deal with GetDataPresent to let it accept all the derived types	protected override void OnDragEnter(DragEventArgs drgevent) {\n        var obj = drgevent.Data.GetData(drgevent.Data.GetFormats()[0]);\n        if (typeof(Base).IsAssignableFrom(obj.GetType())) {\n            drgevent.Effect = DragDropEffects.Copy;\n        }\n    }	0
714147	714101	Quickest way in C# to find a file in a directory with over 20,000 files	string startPath = @"C:\Testing\Testing\bin\Debug";\nstring[] oDirectories = Directory.GetDirectories(startPath, "xml", SearchOption.AllDirectories);\nConsole.WriteLine(oDirectories.Length.ToString());\nforeach (string oCurrent in oDirectories)\n    Console.WriteLine(oCurrent);\nConsole.ReadLine();	0
2984313	2984286	How to focus a control in an MDIParent when all child windows have closed?	private void toolStripButton1_Click(object sender, EventArgs e) {\n        Form child = new Form2();\n        child.MdiParent = this;\n        child.FormClosed += new FormClosedEventHandler(child_FormClosed);\n        child.Show();\n    }\n\n    void child_FormClosed(object sender, FormClosedEventArgs e) {\n        if (this.MdiChildren.Length == 1) {\n            this.BeginInvoke(new MethodInvoker(() => treeView1.Focus()));\n        }\n    }	0
9016409	9016056	Dynamic datatable	DataSet cyclesDataSet = new DataSet("Cycles");\nsomeclass.CycleComplete(cyclesDataSet, "C1");\n.\n.\n.\npublic void CycleComplete(DataSet dataset, String cycleId)\n{\n    var cycleTable = dataset.Tables.Add("cycleId");\n    // Manipulate table here.\n}	0
6716812	6716793	Using FormsAuthentication	if(Roles.IsUserInRole("Administrator")) {\n    FormsAuthentication.SetAuthCookie(\n        "ClientsUserNameHere",\n        false // <-- set to true only if you want persistent cookies\n    );\n    Response.Redirect("~/Home/SomeUserPage");\n}	0
5001278	5001225	C# How can I force Localization Culture to en-US for tests project	Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");	0
19165228	19164870	C#: Comparing strings in a List<string> with string attributes in Objects in a seperate List<Object> using Obj.getName()	// get card names in your deck\nvar deckCardNames = MyDeck.Cards.Select( c => c.getCardName() );\n// get card names in magazine cards that are not in your deck\nvar missingMagCardNames = MagCards.Except( deckCardNames );\n// instantiate card objects for each missing card name\nvar missingCards = missingMagCardNames.Select(mc => new Card(mc));\n// add missing cards to your deck\nMyDeck.Cards.AddRange( missingCards );\n\n// whole thing inline\nMyDeck.Cards.AddRange( MagCards.Except( MyDeck.Cards.Select( c => c.getCardName() ) ).Select (mc => new Card(mc) ) );	0
12010515	12010301	How do you launch a URL that includes quotes?	Uri myUri = new Uri("http://google.com/search?hl=en&q=\"hello world\"");\n        System.Diagnostics.Process.Start(myUri.AbsoluteUri);	0
9983207	9976115	How to create DirectoryEntry for specific group	private static DirectoryEntry getGroupDE(String group)\n{\n    String adserver = "dc.companyname.com";\n    String searchroot = "ou=Groups,dc=companyname,dc=com";\n    DirectorySearcher ds = new DirectorySearcher();\n    ds.SearchRoot = new DirectoryEntry(String.Format("LDAP://{0}/{1}",adserver,searchroot));\n    ds.SearchScope = SearchScope.Subtree;\n    ds.Filter = String.Format("(&(objectCategory=group)(sAMAccountName={0}))",group);\n    SearchResult sr = ds.FindOne();\n    if (sr == null)\n    {\n        return null;\n    }\n    return sr.GetDirectoryEntry();\n}	0
4829555	4829477	Custom dataannotation enum for property	public enum DataUsage\n    {\n        Count,\n        Average,\n        Median,\n        Percentage\n    }\n\n    public class DataAnnotationAttribute : Attribute\n    {\n        public DataAnnotationAttribute(DataUsage usage)\n        {\n            this.Usage = usage;\n        }\n\n        public DataUsage Usage { get; private set; }\n    }\n\n    [DataAnnotation(DataUsage.Average)]\n    public decimal MyProperty { get; set; }	0
17344557	17344377	How to designate if some DateTime value is in the same day in C#?	DateTime date1 = new DateTime(2013, 6, 27, 7, 47, 0);\n// Get date-only portion of date, without its time.\nDateTime dateOnly = date1.Date;\n\nif (Date1.Date == Date2.Date)\n{ //lucky Day}\nelse \n{ // loser\n }	0
31693335	31693233	How to make UserControl add attachments	private void buttonGetFile_Click(object sender, EventArgs e)\n{\n    OpenFileDialog dialog = new OpenFileDialog();\n    dialog.Filter = "Text files | *.txt"; // file types, that will be allowed to upload\n    dialog.Multiselect = false; // allow/deny user to upload more than one file at a time\n    if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK\n    {\n        String path = dialog.FileName; // get name of file\n        using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it\n        {\n            // ...\n        }\n    }\n}	0
13494186	13492558	How to access a parent element from iframe using c#?	protected void Doneclicked(object sender, EventArgs e)\n    {\n        ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptid", "window.parent.location.href='ParentPageName.aspx';", true);  \n }	0
23544548	23544503	How do I make a cell in a Datatable blank instead of 0?	datadable.Rows[x][y] = DBNull.Value;	0
7287583	7287440	Dictionary Ordering	var ordered = dictionary.Keys.Orderby(x => Regex.Replace(x, @"^(\d+)R", "$1B"));	0
10008707	9924770	Show only small area of the video with directshow	//get the real video width\nhr1 = videoWindow2.get_Width(out videoWidth);\nDsError.ThrowExceptionForHR(hr1);\n\n//get the real video height\nhr1 = videoWindow2.get_Height(out videoHeight);\nDsError.ThrowExceptionForHR(hr1);\n\n//calculate the width when setting the height to the panel height\nvideoWidthF = (float)videoWidth;\nvideoHeightF = (float)videoHeight;\npanelWidthF = (float)panelWidth;\npanelHeightF = (float)panelHeight;\n\n// calculate the margins\nint margin = (int)(((panelHeightF / videoHeightF*videoWidthF) - panelWidthF) / 2);\n\n// Position video window in client rect of main application window\nhr1 = videoWindow2.SetWindowPosition(-margin, 0, (int)(panelHeightF / videoHeightF * videoWidthF), panel.Height);	0
18858279	18857869	Hide selection bar in ListBox	LstBxTaskList.SelectedIndex= - 1;	0
7900351	7877730	Get different object from Ninject depending on ConstructorArgument	Bind<IFoo>().To<Foo1>().WithMetadata("Type", typeof(MyRule1))\nkernel.Get<IFoo>(m => m.Get<Type>("Type", null) == typeof(myRule), ConstructorArgument("rule", myRule))	0
8331121	8331045	How to escape single quote in url query string with asp net	sURL = sURL.Replace("'", "\'");	0
21595210	21595152	split array and get last value of each index	var ids = input.Split(',').Select(x => int.Parse(x.Split('0')[1])).ToList();	0
14653519	14653171	Reading xml receipt in C# for specific attribute from windows phone 8 store	System.Xml.XmlDocument r = new System.Xml.XmlDocument();\nr.LoadXml(receipt);\nforeach (System.Xml.XmlNode n in r.GetElementsByTagName("ProductReceipt"))\n{\n    System.Diagnostics.Debug.WriteLine(string.Format("Node: {0}", n.Name));\n    foreach (System.Xml.XmlAttribute a in n.Attributes)\n    {\n        System.Diagnostics.Debug.WriteLine(string.Format("\tAttribute {0}: {1}", a.Name, a.Value));\n    }\n}	0
13593169	13593073	Getting XML Elements and Subelements into a List	XDocument xDoc = XDocument.Parse(xmlstring); //or XDocument.Load(filename);\nvar list = xDoc.Descendants("record")\n            .Select(r => new Record\n            {\n                Name = (string)r.Element("name"),\n                Skills = r.Descendants("skill")\n                           .Select(s=>new Skill{\n                               SkillName = (string)s.Element("skillname"),\n                               SkillType = (string)s.Element("skilltype"),\n                           })\n                           .ToList()\n            })\n            .ToList();	0
11238020	11218823	AddUrlSegment throws NullReferenceException in RestSharp	string _baseUrl = "www.test.com";\n\nRestClient client = new RestClient(_baseUrl);\nRestRequest restRequest = new Request();\nrestRequest.Resource = "/{someToken}/Testing";\nrestRequest.AddParameter("someToken", theToken , ParameterType.UrlSegment);	0
15685724	15685296	How can a Razor DropDownList GET a pretty URL	FormMethod.Get	0
1940356	1940339	Getting a property from an representation of it	Test t = new Test();\nType testType = t.GetType();\nPropertyInfo[] properties = testType.GetProperties();	0
33672266	33220127	Can I use SqlDependency with multiple listeners / load balance	WAITFOR(\n    RECEIVE TOP(1) * FROM {NameOfQueue}\n), TIMEOUT @timeoutvalue;	0
3467967	3467893	How do I convert byte values into decimals?	byte[] data = File.ReadAllBytes(fileName);\nint count = data.Length / 4;\nDebug.Assert(data.Length % 4 == 0);\n\nIEnumerable<float> values = Enumerable.Range(0, count)\n    .Select(i => BitConverter.ToSingle(data, i*4));	0
1546949	1546925	Comparing two List<string> for equality	CollectionAssert.AreEqual(expected, actual);	0
9418565	9418554	Starting a new thread in a foreach loop	foreach(MyClass myObj in myList)\n    {\n        MyClass tmp = myObj; // Make temporary\n        Thread myThread = new Thread(() => this.MyMethod(tmp));\n        myThread.Start();\n    }	0
14627065	14626857	.NET Regex: how to retrieve multiple matches on multiple lines	var src = @"var a = new Person();\nvar x = new WebClient();";\nvar pattern = @"(\w+\s*)(\w*\s*)=\s+new\s+(\w+)\(\)";\nvar expr = new System.Text.RegularExpressions.Regex(pattern,RegexOptions.Multiline);\nforeach(Match match in expr.Matches(src) )\n{\n    var assignType = match.Groups[1].Value;\n    var id = match.Groups[2].Value;\n    var objType = match.Groups[3].Value;        \n}	0
30345863	30342259	How I can remove more than 1 items from drop down list?	string[] Plist = (string[])ViewState["plist"];   \nvar dt = from row in ((DataTable)ViewState["StaffStudList"]).AsEnumerable()\n     where !Plist.Contains(row["uid_nmbr"])\n     select row;\n\nddl.DataTextField = "NAME";\nddl.DataValueField = "uid_nmbr";\nddl.DataSource = dt;      \nddl.DataBind();	0
30400670	30388196	BackgroundDownloader only downloading 5 at once	var download = backgroundDownloader.CreateDownload(...);\ndownload.Priority = BackgroundTransferPriority.High;\nTask<DownloadOperation> task = download.StartAsync(...).AsTask();	0
30142673	30141661	C# Treeview, how to keep only one rootline checked?	private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {\n    if (e.Node.Checked) {\n        for (var node = e.Node.PrevNode; node != null; node = node.PrevNode) uncheckTree(node);\n        for (var node = e.Node.NextNode; node != null; node = node.NextNode) uncheckTree(node);\n    }\n}\n\nprivate void uncheckTree(TreeNode node) {\n    node.Checked = false;\n    foreach (TreeNode child in node.Nodes) uncheckTree(child);\n}	0
26091414	26090996	How to retrieve data from tablecell ASP.NET	txtBox1.ID = "txtBox1";	0
7665049	7652253	Some changes on Soundex Algorithm	private string SoundexByWord(string data)\n{\n    var soundexes = new List<string>();\n    foreach(var str in data.Split(' ')){\n        soundexes.Add(Soundex(str));\n    }\n#if Net35OrLower\n    // string.Join in .Net 3.5 and before require the second parameter to be an array.\n    return string.Join(" ", soundexes.ToArray());\n#endif\n    // string.Join in .Net 4 has an overload that takes IEnumerable<string>\n    return string.Join(" ", soundexes);\n}	0
6606290	6605805	Tree structure as string - how to match nested braces?	foreach (char c in "a(c()e(g()i()k()))")\n{\n    if (c == '(')\n    {\n        Stack.Push(Parent);\n        Parent = Child;\n    }\n    else if (c == ')')\n    {\n        Child = Parent;\n        Parent = Stack.Pop();\n    }\n    else\n    {\n        Child = new SimpleTreeNode() { Value = c };\n        Parent.Children.Add(Child);\n    }\n}	0
33670012	33669782	How to check if x509 certificate issuer is microsoft	private  bool IsAcceptedCertificate(X509Certificate2 cert)\n{\n    try\n    {\n        if(cert.Verify() && cert.Issuer.StartsWith("CN=Microsoft"))\n\n        {\n            return true;\n        }\n    }\n    catch (CryptographicException ex)\n    {\n        System.Diagnostics.Debug.WriteLine(ex.ToString());\n    }\n\n    //if not microsoft\n    return false;\n}	0
26568619	26533722	Validate OAuth bearer token with form post	string token = "Your token goes here";\nMicrosoft.Owin.Security.AuthenticationTicket ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(token);	0
8479183	8479086	Unable to catch RadioButtonList SelectedValue inside grid	for (int i = 0; i <= gvQuestion.Rows.Count - 1; i++)\n{\n   RadioButtonList rdbChoice = (RadioButtonList)gvQuestion.Rows[i].FindControl("rdbChoice");\n   string rd = rdbChoice.SelectedValue;\n}	0
5507101	5506455	Refresh DataContext for Views in WPF?	MyObject o = new MyObject();\no.MyString = "One";\nthis.DataContext = o;\n// ... some time later ...\no.MyString = "Two";\nthis.DataContext = o;	0
11503068	11502951	How to hide a property Default value in my control?	[ValueConversion(typeof(int), typeof(string))]\npublic class IntegerConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        int intValue = (int)value;\n        return intValue != 0 ? intValue.ToString() : string.Empty;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        int intValue = 0;\n        int.TryParse((string)value, out intValue);\n        return intValue;\n    }\n}	0
21890544	21890125	Returning two values immediately surrounding a test value in an IEnumerable<float>	public Tuple<float, float> GetClosestValues(IEnumerable<float> values, float target)\n{\n    float lower = 0;\n    float upper = Single.MaxValue;\n    foreach (var v in values)\n    {\n        if (v < target && v > lower) lower = v;\n        if (v > target && v < upper) upper = v;\n    }\n\n    return Tuple.Create(lower, upper);\n}	0
13062898	12913660	Prevent Http requests in Website basis on Config Value	public void Init(HttpApplication context)\n        {\n            context.BeginRequest += new EventHandler(context_BeginRequest);\n        }\n\n        public void context_BeginRequest(Object source, EventArgs e)\n        {\n            //Code to reject the HTTP requests on basis of Config Value\n            HttpApplication application = (HttpApplication)source;\n            HttpContext context = application.Context;\n\n            if (context != null)\n            {\n                if (Utilities.Utility.HttpsCheck)\n                {\n                    if (!context.Request.IsSecureConnection)\n                    {\n                        context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;\n                        context.Response.StatusDescription = "Secure connetion required";\n                        context.Response.End();\n                    }\n                }\n            }\n        }	0
20679684	20671116	MVC 4 - Building a Helper that accesses ViewData	public static class ValidationExtensions\n{\n        public static MvcHtmlString AddCustomValidationSummary(this HtmlHelper htmlHelper)\n        {\n            string result = "";\n\n            if (htmlHelper.ViewData.ModelState[""] != null && htmlHelper.ViewData.ModelState[""].Errors.Any())\n            {\n                result = "<div class='note note-danger'><h4 class='block'>Errors</h4><p>" + htmlHelper.ValidationSummary().ToString() + "</p></div>";\n            }\n\n            return new MvcHtmlString(result);\n        }\n}	0
5704520	5654451	Cannot declare unconventional PK via Data Annotations for a MVC3 Entity Model	[Key]\npublic string UserName { get; set; }	0
17780985	17780877	How to assign values for multiple class property like a list of items using for loop?	public class Helper\n    {\n    public bool A { get; set; }\n    public bool B { get; set; }\n    public bool C { get; set; }\n\n    public List<Action<bool>> Setters { get; set; }\n    public Helper()\n        {\n        this.Setters = new List<Action<bool>>() \n            { b => this.A = b, b => this.B = b, b => this.C = b };\n        }\n\n    public void SetToFalse(IEnumerable<Action<bool>> setters)\n        {\n        // try to set A, B, C to false in a for loop\n        foreach (var a in setters)\n            {\n            a(false);\n            }\n        }\n    }	0
33932360	33932238	displaying XML to html after retrieving from SQL 2014 XML column	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Data;\nusing System.Data.SqlClient;\n\nnamespace ConsoleApplication58\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string connStr = "Enter Your Conneciton String Here";\n            string SQL = "Select XML_COL_NAME from table1";\n            SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);\n\n            DataTable dt = new DataTable();\n            adapter.Fill(dt);\n            dt.WriteXml("filename");\n        }\n    }\n}	0
5346965	5346870	Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables?	modelBuilder.Entity<Customer>().HasRequired(x => x.PrimaryMailingAddress)\n    .WithMany()\n    .HasForeignKey(x => x.PrimaryMailingAddressID)\n    .WillCascadeOnDelete(false);\n\nmodelBuilder.Entity<Address>()\n    .HasRequired(x => x.Customer)\n    .WithMany(x => x.Addresses)\n    .HasForeignKey(x => x.CustomerID);	0
11871624	11871558	Parsing Through XML Files with Selected Keywords	if (itemDescription.Contains(txtComKeyword1) || itemDescription.Contains(txtComKeyword2) || itemDescription.Contains(txtComKeyword3) || itemDescription.Contains(txtComKeyword4))\n{\n...\n}	0
25807944	25807863	How to set path of .dll file from windows form application project in C#?	Environment.SetEnvironmentVariable	0
17388491	17388335	Loop of intensive processing and serializing - how to completely clean memory after each serialization in C#?	GC.Collect();\n GC.WaitForPendingFinalizers();	0
3773482	3773456	Is there .net magic to get parameter values by name in console application?	string data = null;\nbool help   = false;\nint verbose = 0;\n\nvar p = new OptionSet () {\n    { "file=",      v => data = v },\n    { "v|verbose",  v => { ++verbose } },\n    { "h|?|help",   v => help = v != null },\n};\nList<string> extra = p.Parse (args);	0
8954799	8954759	How do you access an asp.net code behind session object member variable in javascript?	var userID = <%=MyPageType.MySessionClass.Current.User.UserID%>;	0
21839604	21839503	I need a fast work-around for "There is already an open DataReader associated with this Command which must be closed first"	"MultipleActiveResultSets=True;"	0
2075226	2074454	Override a static method	public interface IRolesService\n{\n    bool IsUserInRole(string username, string rolename);\n}\n\npublic class RolesService : IRolesService\n{\n    public bool IsUserInRole(string username, string rolename)\n    {\n        return Roles.IsUserInRole(username, rolename);\n    }\n}\n\npublic class MockRoleService : IRolesService\n{\n    public bool IsUserInRole(string username, string rolename)\n    {\n        return true;\n    }\n}	0
23360855	23267960	How to parse tree from TFS Test Plan	ITestManagementTeamProject teamProject = testManagementService.GetTeamProject(projectId);\n        ITestPlan testplan= teamProject.TestPlans.Find(testplanId);\n        IStaticTestSuite newSuite = teamProject.TestSuites.CreateStatic();\n        newSuite.Title = "new title";\n\n        testplan.RootSuite.Entries.Add(newSuite);\n        testplan.Save();	0
22270611	22255125	CUDAFY, how to get arrays inside structs	[Cudafy]\npublic struct myStructTwo\n{\n    public float value_x[size];\n}	0
24212769	24212520	Parsing xml into anonymous type	var xdata = XDocument.Parse(data);\nvar items = xdata.Descendants("Inc")\n            .Select(d => new\n            {\n                DName = (string)d.Element("id_name"),\n                RelNo = ((string)d.Descendants("rel_no").FirstOrDefault() ?? "")\n            })\n            .ToList();	0
7115885	7115818	How should one best recode this example extension method to be generic for all numeric types?	// IComparable constraint for numeric types like int and float that implement IComparable\npublic static T clip<T>(this T v, T lo, T hi) where T : IComparable<T>\n{\n  // Since T implements IComparable, we can use CompareTo\n  if(v.CompareTo(lo)<0)\n    v=lo; // make sure v is not too low\n  if(v.CompareTo(hi)>0)\n    v=hi; // make sure v is not too high\n  return v;\n}	0
16561267	16561136	How to apply CSS to navigation bar with master pages?	#nav {\n    color:yellow;\n}\n#nav li {\n    font-size:19pt;\n}	0
19418668	19411756	Deleting cookies / looping login & logout request	static void Main(string[] args)\n{\n    while (true)\n    {\n        try\n        {\n            CookieContainer cookies = new CookieContainer();\n\n\n            HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://www.********/index.php");\n            loginRequest.CookieContainer = cookies;\n\n            // Configure login request headers and data, write to request stream, etc.\n\n            HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();\n\n\n            HttpWebRequest logoutRequest = (HttpWebRequest)WebRequest.Create("http://www.********/logout.php");\n            logoutRequest.CookieContainer = cookies;\n\n            // Configure logout request headers and data, write to request stream, etc.\n\n            HttpWebResponse logoutResponse = (HttpWebResponse)logoutRequest.GetResponse();\n        }\n        catch (Exception err)\n        {\n            Console.WriteLine(err.Message);\n        }\n    }\n}	0
11812224	11709248	Creating Collision for specific objects in a list in XNA	if(planet.ID == 0) \n{ if (planet.Bounds.Contains((int)tl.Position.X, (int)tl.Position.Y)) { changeScreenDelegate(ScreenState.Menu); } }	0
3495311	3492856	Entity Framework - writing query using lambda expression	var query = db.UM_RolePermission\n            .Where(rp => db.UM_RoleUser\n                         .Where(ru => ru.UM_User.UserID == userId)\n                         .Select(ru => ru.RoleID)\n                         .Contains(rp.RoleId))	0
19537483	19537344	List won't add string Array	DMSrows.Add(new TrdRamValue{\n           Value =val,\n           State =val.Error,\n           dt =val.Time\n     });	0
573234	573231	Multipule Operations in a finally block	using (var resA = GetMeAResourceNeedingCleanUp())\nusing (var resB = new AnotherResourceNeedingCleanUpn(...)) {\n  // Code that might throw goes in here.\n}	0
32819827	32819767	Call methods instead of property with Eval	Databinder.Eval	0
6592842	6592802	How sort data taking from database in c#	foreach (State st in stc.OrderBy(s => s.StateName))\n{\n    ddlState.Items.Add(new ListItem(st.CircleCode + "-" + st.StateName, st.CircleCode));\n}	0
8120610	8113033	using sql server 2008 decision tree to make predictions in C#	-- create table\n    declare @t table (name varchar(50), age varchar(50), reply varchar(3), answer varchar(50))\n    insert @t (name, age, reply, answer)\n    values ('John', '10-20', 'yes', 'apple'),\n    ('Kate', '20-30', 'yes', 'orange'),\n    ('Sam', '10-20', 'yes', 'apple'),\n    ('Peter', '10-20', 'no', '----'),\n    ('Tom', '20-30', 'no', '----'),\n    ('Mike', '10-20', 'yes', 'orange')\n\n-- get answer\n    select  t.name, t.age, t.reply, case t.reply when 'yes' then t.answer else w.answer end answer\n    from    @t t\n            left join (\n                select age, answer\n                from (\n                    select  age, answer, count(*) cnt, row_number() over (partition by age order by count(*) desc) rnk\n                    from    @t\n                    where   reply = 'yes' \n                    group by age, answer\n                ) s\n                where rnk = 1\n            ) w on t.age = w.age	0
25247634	25243431	Image variable to byte[] array	EMPLOYER_SIGN = new Bitmap(426, 155);\n    using (Graphics gr = Graphics.FromImage(EMPLOYER_SIGN))\n    {\n        gr.SmoothingMode = SmoothingMode.HighQuality;\n        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;\n        gr.PixelOffsetMode = PixelOffsetMode.HighQuality;\n        gr.DrawImage(Image.FromFile("C:/SCR/temp/sign.jpg"), new Rectangle(0, 0, 426, 155));\n    }\n    MemoryStream ms = new MemoryStream();\n    EMPLOYER_SIGN.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n    BARRAY_EMPSIGN = ms.ToArray();\n    ms.Dispose();\n    pictureBox3.Image = EMPLOYER_SIGN;	0
12378727	12378704	How to combine many text files into groups of 4	using(StreamWriter outfile3 = new StreamWriter(...))\n {\n    count++;\n\n    foreach (string dirFileName in array2)\n    {\n\n        if(fourCount == 1)\n        {\n            outfile3.Close();  // add this\n            outfile3 = new StreamWriter(folderPath.Text + "\\" + count + ".txt");\n            outfile3.WriteLine(readFromFile);\n        }\n\n       ...\n    }\n }	0
1034331	1029340	Extract OLE Object (pdf) from Access DB	public static byte[] StripOleHeader(byte[] fileData)\n    {\n        const string START_BLOCK = "%PDF-1.3";\n        int startPos = -1;\n\n        Encoding u8 = Encoding.UTF7;\n        string strEncoding = u8.GetString(fileData);\n\n        if (strEncoding.IndexOf(START_BLOCK) != -1)\n        {\n            startPos = strEncoding.IndexOf(START_BLOCK);\n        }\n\n        if (startPos == -1)\n        {\n            throw new Exception("Could not find PDF Header");\n        }\n\n        byte[] retByte = new byte[fileData.LongLength - startPos];\n\n        Array.Copy(fileData, startPos, retByte, 0, fileData.LongLength - startPos);\n\n        return retByte;\n    }	0
24254312	24253468	MVVM pattern for raising dependent property RaisePropertyChanged events	protected override void RaisePropertyChanged(string propertyName = null)\n    {\n        PropertyChangedEventHandler handler = this.PropertyChangedHandler;\n        switch (propertyName)\n        {\n            case "IsDownloaded":\n            case "IsAvailableToUse":\n            case "IsPurchased":\n                if (handler != null) handler(this, new PropertyChangedEventArgs("IsDownloaded"));\n                if (handler != null) handler(this, new PropertyChangedEventArgs("IsAvailableToUse"));\n                if (handler != null) handler(this, new PropertyChangedEventArgs("IsPurchased"));\n\n                break;\n            default:\n                if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));\n                break;\n        }\n    }	0
29253389	29251907	MySQL connection throws null reference	var cs = new DbConnectionStringBuilder();\ncs["SERVER"] = server;\ncs["DATABASE"] = database;\ncs["UID"] = uid;\ncs["PASSWORD"] = password;\nvar connectionString = cs.ConnectionString;	0
26180536	26179387	C# Loop executes for some variables from taken from SQL then fails	"VolumeRebateExecute.CommandTimeout = 120;"	0
628514	628483	How can I set a WPF control's color to a system color programatically, so that it updates on color scheme changes?	grid1.SetResourceReference(\n    Control.BackgroundProperty,\n    SystemColors.DesktopBrushKey);	0
26795019	26794900	counter for attempts in c#	int Answer; // declares the Answer variable outside button event\nint Guesses = 0; // declare this outside button event, and initialize it to 0.\n                 // initialization will happen when the Form object is created.\n\n...\n\nprivate void btnGuess_Click(object sender, EventArgs e)\n{\n    int UserGuess;\n    // DO NOT reset the counter here. This line is the culprit that\n    // resets the counter every time you click the button\n    //int Guesses = 0;     // start counter\n    ...\n} \n\n...	0
5543248	5543189	Get result HTML from WebPage	protected string RenderPartialViewToString(string viewName, object model)\n{\n    if (string.IsNullOrEmpty(viewName))\n        viewName = ControllerContext.RouteData.GetRequiredString("action");\n\n    ViewData.Model = model;\n\n    using (StringWriter sw = new StringWriter()) \n    {\n        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);\n        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);\n        viewResult.View.Render(viewContext, sw);\n\n        return sw.GetStringBuilder().ToString();\n    }\n}	0
20597180	20596180	How do you make a Console program that shuts down Windows?	using System.Diagnostics;\n\nProcessStartInfo shutdown = new ProcessStartInfo("shutdown.exe", "-s");\n    Process.Start(shutdown);	0
1803808	1803792	C#, how to use IEnumerator in a user defined class	public class Basket: IEnumerable {\n  private Fruit[] fruits;\n\n  public IEnumerator getEnumerator() {\n    return fruits.GetEnumerator();\n  }\n}	0
4223058	4223040	Method that accept n Number of Parameters in C #	public void MyMethod(params int[] numbers)\n{\n   for (int i=0;i<numbers.Length;i++)\n   {\n       //numbers[i] is one of the parameters\n   }\n}	0
19227467	19225225	How To generate unique ID for controls inside a User Control	private Dictionary<string, int> controlInstances = new Dictionary<string, int>();\n\nprivate string RenderControl(Control control)\n{\n    StringBuilder sb = new StringBuilder();\n    StringWriter sw = new StringWriter(sb);\n    HtmlTextWriter writer = new HtmlTextWriter(sw);\n\n    int index = GetOrAddControlInstanceCount(control);\n\n    control.ClientIDMode = ClientIDMode.Static;\n    control.ID = control.GetType().Name + index;\n\n    control.RenderControl(writer);\n\n    return sb.ToString();\n}\n\nprivate int GetOrAddControlInstanceCount(Control control)\n{\n    string key = control.GetType().Name;\n\n    if (!controlInstances.ContainsKey(key))\n    {\n        controlInstances.Add(key, 0);\n    }\n\n    return controlInstances[key]++;\n}	0
30465812	30465666	how to manipulate json easily	string json = @"{\n  'Name': 'Bad Boys',\n  'ReleaseDate': '1995-4-7T00:00:00',\n  'Genres': [\n    'Action',\n    'Comedy'\n  ]\n}";\n\nMovie m = JsonConvert.DeserializeObject<Movie>(json);	0
1378824	1378819	Using a Hashtable to store only keys?	HashSet<T>	0
16501222	16500944	How to print in output window of visual studio express for windows phone?	System.Diagnostics.Debug.WriteLine("your string");	0
26020316	26020174	How to pass a linked list as argument into a method and how to call it?	private LnkedList<Program> _Programs = new LinkedList<Program>();\n\npublic void menu()\n{\n    Console.WriteLine("\n Choose what to do :\n1. Add new Entry\n2. Search Phone\n3.quit\n");\n\n    int choice = Convert.ToInt16(Console.ReadLine());\n    switch(choice)\n    {\n        case 1: DetailAccept();\n            AddL(getName(), getCellNo(), _Programs);\n\n    }\n}	0
596775	596730	How to show "busy" dialog (spinning wheel) on Smart Phone	using System.Windows.Forms;\n...\nCursor.Current = Cursors.WaitCursor;	0
31495036	31494574	How to specify where clause with nullable column	where !f.DeleteFlg.HasValue || !f.DeleteFlg.Value	0
12115430	12115120	How do I use LINQ to select from DataTable, with a list of the required column names	string[] commonCols = obj.Common_Columns;\nDataView myTableView = new DataView(srcDataTable); \nDataTable srcReducedTable = myTableView.ToTable(false, commonCols);	0
2625362	2603764	Problem with finding the next word in RichTextBox	TextPointer ptr1= RichTextBox.CaretPosition.DocumentStart.GetPositionAtOffset(Index);\n\nchar nextChar = GetNextChar();\n//we continue until there is a character\nwhile (char.IsWhiteSpace(nextChar))\n{\n   Index++;\n   ptr1= RichTextBox.CaretPosition.DocumentStart.GetPositionAtOffset(Index);\n   nextChar = GetCharacterAt(Ptr1);\n}\n//so now ptr1 is pointing to a character, and we do something with that TextPointer\nChangeFormat(ptr1);	0
13143986	13143898	When using an ASP.Net UpdatePanel, requests from Popup window are blocked	public class YourPage: Page, IReadOnlySessionState { ... }	0
23287093	23286766	Idle Detection in WPF	var timer = new DispatcherTimer\n    (\n    TimeSpan.FromMinutes(5),\n    DispatcherPriority.ApplicationIdle,// Or DispatcherPriority.SystemIdle\n    (s, e) => { mainWindow.Activate(); }, // or something similar\n    Application.Current.Dispatcher\n    );	0
20735462	20731793	multiple boxplots in one chart in C#	Chart.chart_main.Series["BoxPlotSeries"]["BoxPlotSeries"] = string.Join(";", xValue);	0
5721632	5721403	Windows Forms right-click menu for multiple controls	void runMenuItemClick(object sender, EventArgs e) {\n    var tsItem = ( ToolStripMenuItem ) sender;\n    var cms = ( ContextMenuStrip ) tsItem.Owner;\n    Console.WriteLine ( cms.SourceControl.Name );\n}	0
14583910	14557312	Change tag Content of a WebBrowser from a Timer	webBrowser1.Invoke(new ThreadStart(delegate\n                    {\n                        Application.DoEvents();\n                        HtmlElement token2 = webBrowser1.Document.All["token2"];\n                        //MessageBox.Show(token2.InnerHtml);\n                        token2.InnerHtml = currentToken;\n                    }));	0
13088865	13076204	WebBrowser navigating between internally stored html resources through links in the html	if (e.Url.ToString().Contains("test2"))\n{\n    e.Cancel = true;\n    webBrowser1.DocumentText = WindowsFormsApplication1.Properties.Resources.test2.ToString();\n}	0
18398254	18391809	Creating a Parameterized query that allows user input stored as a string to compare to a database field	SQl_Command.CommandText = "SELECT COUNT(ID) As MyCount FROM members WHERE ([Primary Exp] = N'" + exp + "') AND ([Approved] = 'True') OR ([Approved] = 'True') AND ([Secondary Exp] = N'" + exp + "')";	0
28692661	28692562	Regex - split by dot if it is at the end of word	New Text.RegularExpressions.Regex("[ ,]+$")	0
14496906	14496848	SQL 'IN' operator in lambda	string[] nums = {"007","7"};\nListA.Where(x => (x.Name == "James Bond") || (nums.Contains(x.Number));	0
33887269	33886925	Unable to retrieve column values from one of the tables joined in a stored procedure?	public List<GroupUserList> GetData()\n    {\n\n        DataTable dt = new DataTable();\n        List<GroupUserList> details = new List<GroupUserList>();\n        using (SqlConnection con = new SqlConnection(Global.Config.ConnStr))\n        {\n            SqlCommand cmd = new SqlCommand("spp_adm_user_user_group_sel", con);\n            cmd.CommandType = CommandType.StoredProcedure;\n\n\n            SqlDataAdapter da = new SqlDataAdapter(cmd);\n            da.Fill(dt);\n            foreach(DataRow dr in dt.Rows)\n            {\n                GroupUserList usr = new GroupUserList();\n\n                usr.name = dr["Group_Name"].ToString();\n                usr.fullname = dr["fullname"].ToString();\n                usr.designation = dr["designation"].ToString();\n                usr.mobile = dr["mobile"].ToString();\n                usr.email = dr["email"].ToString();\n\n                details.Add(usr);\n            }\n\n\n            return details;\n        }\n\n    }	0
25688520	25687850	Convert to Dictionary and Fill missing items	var stats = context.Exams\n    .GroupBy(x => x.Classification)\n    .ToDictionary(x => x.Key, g => g.Count()) // execute the query\n    .Union(Enum.GetValues(typeof(ClassificationLevel))\n        .OfType<ClassificationLevel>()\n        .ToDictionary(x => x, x => 0)) // default empty count\n    .GroupBy(x => x.Key) // group both\n    .ToDictionary(x => x.Key, x => x.Sum(y => y.Value)); // and sum	0
13992246	13992107	WPF Datagrid- auto refresh	//On PageLoad, populate the grid, and set a timer to repeat ever 60 seconds\nprivate void Page_Loaded(object sender, RoutedEventArgs e)\n{\n    try\n    {\n        RebindData();\n        SetTimer();\n    }\n    catch (SqlException e)\n    {\n        Console.WriteLine(e.Message);\n    }\n}\n\n//Refreshes grid data on timer tick\nprotected void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n    RebindData();\n}\n\n//Get data and bind to the grid\nprivate void RebindData()\n{\n    String selectstatement = "select top 2 ItemID, ItemName,ConsumerName, Street, DOJ from ConsumarTB order by ItemID ";\n    da = new SqlDataAdapter(selectstatement, con);\n    ds = new DataSet();\n    da.Fill(ds);\n    dataGrid1.ItemsSource = ds.Tables[0].DefaultView;\n}\n\n//Set and start the timer\nprivate void SetTimer()\n{\n    DispatcherTimer dispatcherTimer = new DispatcherTimer();\n    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);\n    dispatcherTimer.Interval = new TimeSpan(0, 0, 60);\n    dispatcherTimer.Start();\n}	0
17089797	17089739	Converting string with letters and numbers to decimal only numbers	string hexString = "01048CABFB";\nlong intVal = Int64.Parse(hexString, System.Globalization.NumberStyles.HexNumber);\n// intVal = 4371295227	0
29087200	29087075	raw pixel array to gray scale BitmapImage	for (int c = 0; c < bitmap.Palette.Entries.Length; c++)\n    bitmap.Palette.Entries[c] = Color.FromArgb(c, c, c);	0
15008009	15007097	How to remove strings from a string based on the contents of a string array?	string newSomething = something.Substring(0, something.IndexOf(' '));	0
20340733	20340713	Can't add to a List of int?	if (obj == null)\n    {\n        List<int> mylist = new List<int>();\n\n        this.ViewState["stepToRemoveForportfolioForStep"] = mylist ;\n\n\n        return mylist;\n    }	0
9784109	9784038	Get and Iterate through Controls from a TabItem?	public static IEnumerable<T> FindVisualChildren<T>(DependencyObject rootObject) where T : DependencyObject\n{\n  if (rootObject != null)\n  {\n    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(rootObject); i++)\n    {\n      DependencyObject child = VisualTreeHelper.GetChild(rootObject, i);\n\n      if (child != null && child is T)\n        yield return (T)child;\n\n      foreach (T childOfChild in FindVisualChildren<T>(child))\n        yield return childOfChild;\n    }\n  }\n}	0
25757278	25756451	How to use ListBox.Items as Itemsource of a List<String>	List<string> feed = MyList.Items.Cast<object>()\n    .Select(o => o.ToString()).ToList();	0
17392629	17224667	Ninject factory not working with conventions for me	public class BaseTypeBindingGenerator<InterfaceType> : IBindingGenerator\n{\n    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)\n    {\n        if (type != null && !type.IsAbstract && type.IsClass && typeof(InterfaceType).IsAssignableFrom(type))\n        {\n            string.Format("Binds '{0}' to '{1}' as '{2}", type, type.Name, typeof(InterfaceType)).Dump();\n\n            yield return bindingRoot.Bind(typeof(InterfaceType))\n                                    .To(type)\n                                    .Named(type.Name) as IBindingWhenInNamedWithOrOnSyntax<object>;\n        }\n    }\n}	0
24251824	24251752	Filter SqlDataReader with Where Clause	while (reader.Read())\n{\n    status = rdr.getstring(1);\n    if (status != 'N') continue;\n    // process \n}	0
12103258	12098508	How can I call LinkButton OnClick Event from JavaScript?	var btn = document.getElementById('<%=LinkButton5.ClientID%>');\nbtn.click();	0
29733540	29733378	How to handle GoBack in the Navigation Drawer in Windows Phone 8.1?	protected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;\n     }\n\n    protected override void OnNavigatedFrom(NavigationEventArgs e)\n    {\n        Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;\n    }	0
23418865	23418807	How to unit test public behavior dependent on private state?	[Test]\npublic void Connect_throws_exception_if_already_connected()\n{\n       var foo = new Foo();\n       foo.Connect();\n\n\n       Exception thrownExc = null;\n\n       try\n       {\n            foo.Connect();\n       }\n       catch(InvalidOperationException exc)\n       {\n           thrownExc = exc;\n       }\n\n       Assert.IsNotNull(thrownExc, "It was expected to get exception on 2nd connect attempt, but nothing were thrown.");\n}	0
25881876	25881748	is it posible to relate two different classes that contains same method but with different parameters?	public abstract class BillCalculator: IBillable \n{\n    abstract decimal Bill();\n}\n\npublic class HourlyBillCalculator: BillCalculator\n{\n   public int HoursWorked { get; set; }\n   public decimal PricePerHour { get; set; }\n\n   public HourlyBillCalculator(int hoursWorked, decimal pricePerHour) \n   {\n      HoursWorked = hoursWorked;\n      PricePerHour = pricePerHour;\n   }\n\n   public override Bill() \n   {\n      // Calculate the Bill\n   }\n}\n\npublic class CommisionBillCalculator: BillCalculator {\n     public decimal CommisionRate { get; set; }\n\n     public CommisionBillCalculator(decimal rate)\n     {\n         CommisionRate = rate;\n     }\n\n     public override Bill() {\n          // Calculate the Bill\n     }\n}	0
4851875	2790597	Resharper Warnings with MVVM	[UsedImplicitlyAttribute]	0
14676487	14676238	how to convert existing data access class as a webservice	[Operation Contract]\npublic static int Add(Term term, string useString, string useForString, string broaderTermString, string narrowerTermString, string relatedTermString, string userName, ref int historyTermId);	0
20463457	20463361	C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?	SqlCommand cmd = new SqlCommand("store procedure Name", con);\ncmd.CommandType = CommandType.StoredProcedure;\nSqlDataAdapter adapter= new SqlDataAdapter(cmd);\nDataSet ds = new DataSet();\nadapter.Fill(ds);\nif(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)\n{\n    //your code\n}	0
23727522	23727486	C# / Windows Firewall - Remove IP from rule	delete rule name="BlockedIPs"	0
27499644	27499528	c# find words in sequence in richtextbox	string[] words = richTextBox1.Text.Split(' ');       \n foreach (string searchString in words)\n {\n      if (richTextBox1.Text.Contains(searchString))\n      {\n         richTextBox2.AppendText(searchString + " is found.\n");\n      }\n }	0
1597679	1597654	Searching in xml with linq	c.Value.IndexOf(_sSemptom, StringComparison.OrdinalIgnoreCase) > -1	0
28502395	28501353	Reveal portions of an image behind another image	public Form1()\n{\n    InitializeComponent();\n    pictureBox1.Image = Bitmap.FromFile(your1stImage);\n    bmp = (Bitmap)Bitmap.FromFile(your2ndImage);\n    pb2.Parent = pictureBox1;\n    pb2.Size = new Size(10,10);\n    /* this is for fun only: It restricts the overlay to a circle: \n    GraphicsPath gp = new GraphicsPath();\n    gp.AddEllipse(pb2.ClientRectangle);\n    pb2.Region = new Region(gp);\n    */\n\n}\n\nBitmap bmp;\nPictureBox pb2 = new PictureBox();\n\nprivate void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    Rectangle rDest= pb2.ClientRectangle;\n    Point tLocation =   new Point(e.Location.X - rDest.Width - 5, \n                                  e.Location.Y - rDest.Height - 5);\n    Rectangle rSrc= new Rectangle(tLocation, pb2.ClientSize);\n\n    using (Graphics G = pb2.CreateGraphics() )\n    {\n        G.DrawImage(bmp, rDest, rSrc, GraphicsUnit.Pixel);\n    }\n    pb2.Location = tLocation;\n}	0
32270471	32206396	How to use string values for Y-Axis in xlLine ChartType	//series.Values = data.Keys.ToArray();\n        //series.XValues = data.Values.ToArray();\n\n        series.XValues = data.Keys.ToArray();\n        series.Values = data.Values.ToArray();	0
24939554	24939364	Select the next item in a listbox C#	lb.SelectedIndex = 0;\n\nfor (int i = 0; i < lb.Items.Count; i++)\n{\n    using (var process = new Process())\n    {\n        string tn = lb.SelectedItem;\n        string url = "privateURL" + tn + "privateURL";\n        process.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";\n        process.StartInfo.Arguments = url;\n        process.Start();\n    }\n    lb.SelectedIndex := lb.SelectedIndex + 1;\n}	0
19182692	19147967	Print out RDLC of ReportViewer as an image format	var byts = report.Render("Image", "<DeviceInfo><OutputFormat>PNG</OutputFormat></DeviceInfo>");\nFile.WriteAllBytes("c:\\test.png", byts);	0
19993442	19993302	Adding New folder in treeview c# Winforms	Directory.CreateDirectory(Path.Combine(treeView1.SelectedNode.Tag as string, "New Folder"));	0
526545	526540	How do I find the position of a cursor in a text box? C#	myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");	0
2187875	2187637	How to get FormValueProvider instance in a Custom Model Binder in ASP.NET MVC 2	var formValueProvider = new FormValueProvider(controllerContext);\nbindingContext.ValueProvider = formValueProvider;	0
25524467	25524180	Format numeric string with comma separator for indian numbering system	var s = String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble("12345678.90"));	0
5603463	5603274	How to overwrite (NOT append) a text file in ASP.NET using C#	protected void Page_Load(object sender, EventArgs e)\n{\n    if (File.Exists(Server.MapPath("newtxt.txt")))\n    {\n        TextBox1.Text = System.IO.File.ReadAllText("newtxt.txt");\n    }\n    else\n    {\n        Response.Write("<script>alert('File does not exists')</script>");\n    }       \n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    System.IO.File.WriteAllText("newtxt.txt", TextBox1.Text);\n}	0
13914837	13912758	Is there a better way to filter mails based on date?	Microsoft.Office.Interop.Outlook.Items restrictedItems = subFolder.Items.Restrict("*filter*");\n\nfor (int i = 1; i <= restrictedItems.Count; i++)...	0
3142481	3142396	RegEx pattern not showing matches	string pattern = @"[~#&!%+{}]+";	0
22305925	22305880	Color a specific word in a long text in c#	private void  txt_TextChanged(object sender, EventArgs e)\n        {\n            this.CheckKeyword("passed", Color.Purple, 0);\n            this.CheckKeyword("failed", Color.Green, 0);\n        }\nprivate void CheckKeyword(string word, Color color, int startIndex)\n    {\n        if (this.txt.Text.Contains(word))\n        {\n            int index = -1;\n            int selectStart = this.Rchtxt.SelectionStart;\n\n            while ((index = this.txt.Text.IndexOf(word, (index + 1))) != -1)\n            {\n                this.txt.Select((index + startIndex), word.Length);\n                this.txt.SelectionColor = color;\n                this.txt.Select(selectStart, 0);\n                this.txt.SelectionColor = Color.Black;\n            }\n        }\n    }	0
9832898	9832823	Object[] to double[] c#	var doubles = Array.ConvertAll<object, double>(objects, o => (double)o);	0
19598705	19598650	How to create a dictionary from a list with an object as key	static void Main(string[] args)\n{\n    Data.Add(new Foo() { a = 0, b = 0, c = 99 });\n    Data.Add(new Foo() { a = 1, b = 0, c= 69 });\n\n    // Key: new Key() { a = ???, b = ??? }\n    // Value: c\n    var Data_Map = Data.ToDictionary(\n               x => new Key{ a = x.a, b = x.b},\n               x => x.c, \n               new KeyEqualityComparer ());\n\n}	0
11275494	11275446	Fill a rectangle inside button control	var myRectangleButton = (Button)this.FindName("myRectangleButton");	0
43505	43500	Is there a built-in method to compare collections in C#?	Enumerable.SequenceEqual	0
27555569	27555154	Sorting ObservableCollection to DataGrid does work correctly for first run	// consider this:\n// ObservableCollection<...> myCollection = ...\n// then\nvar view = CollectionViewSource.GetDefaultView(myCollection);\nview.GroupDescriptions.Add(new PropertyGroupDescription("Group1"));\nview.SortDescriptions.Add(new SortDescription("Group1", ListSortDirection.Ascending));\nMyDataGrid.ItemsSource = myCollection;	0
28169335	28169101	How to delete specific nodes from an XElement?	var nodes = xRelation.Elements().Where(x => x.Element("Conditions") != null).ToList();\n\nforeach(var node in nodes)\n    node.Remove();	0
21133908	21131439	MVC 5 Linq-SQL Performing search from 3 joined Tables	public List<Student> GetStudentsByCourseName(string courseName)\n    {\n        var list = new List<Student>();\n        var course = db.Courses.SingleOrDefault(o => o.Title == courseName);\n\n        if (course != null)\n        {\n            list = course.Enrollments.Select(o => new Student {\n                    FirstName = o.Student.FirstName,\n                    LastName = o.Student.LastName\n                }).ToList();\n        }\n\n        return list;\n    }	0
7031647	7030962	How to change data coming from database into DataGridView	dataGridView1.CellFormatting +=\n        new System.Windows.Forms.DataGridViewCellFormattingEventHandler(\n        this.dataGridView1_CellFormatting);\n\nprivate void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Salary")\n    {\n        if (e.Value != null)\n        {\n            try\n            {\n                e.Value = String.Format("Rs. {0:F2}", e.Value);\n                e.FormattingApplied = true;\n            }\n            catch (FormatException)\n            {\n                e.FormattingApplied = false;\n            }\n        }\n    }\n}	0
16633018	16632696	How do I add a tool to my project?	Problem Signature 09:   System.IO.FileNotFoundException	0
23598841	23296854	Web API validation of serialized string	// Validate\n        Validate<List<User>>(user);\n\n        if (!ModelState.IsValid)\n        {\n            return new InvalidModelStateResult(ModelState, true, new DefaultContentNegotiator(), Request, new MediaTypeFormatter[] { new JsonMediaTypeFormatter() }); // Force JSON\n        }	0
3473039	3473019	Convert a C printf(%c) to C#	int x = (int)0xA0FF;  // use differing high and low bytes for testing\n\n        byte[] bytes = new byte[2];\n        bytes[0] = (byte)(x >> 8);  // high byte\n        bytes[1] = (byte)(x);       // low byte	0
24468268	24467004	Changing a specific part of a string conditionally with Regex	static string Replace(string input, int index, double addition)\n{\n    int matchIndex = 0;\n    return Regex.Replace(input, @"\d+", m => {\n        if (matchIndex++ == index) {\n            var value = int.Parse(m.Value) + addition;\n            if (value < 0)\n                throw new InvalidOperationException("your message here");\n            return value.ToString();\n        }\n\n        return m.Value;\n    });\n}	0
13760481	13760072	select certain columns off a data table	System.Data.DataTable table = new System.Data.DataTable();\nfor (int i = 1; i <= 11; i++)\n    table.Columns.Add("col" + i.ToString());\n\nfor (int i = 0; i < 100; i++)\n{\n    System.Data.DataRow row = table.NewRow();\n    for (int j = 0; j < 11; j++)\n        row[j] = i.ToString() + ", " + j.ToString();\n    table.Rows.Add(row);\n}\n\nSystem.Data.DataView view = new System.Data.DataView(table);\nSystem.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");	0
15090175	15090093	How can I hide a specific column form a dataGridView?	gridview.Columns["ColumnName"].Visible = false;	0
15774898	15774529	Changing the params modifier in a method override	virtual void M(int x, int y) { }\n...\noverride void M(int y, int x) { } \n...\nM(x = 1, y = 2);	0
16941133	16941118	C# - Mark Variable As Const (Readonly)	public static class Foo\n{\n    public static readonly int MIN;\n\n    static Foo()\n    {\n        MIN = 18;\n    }\n\n    public static void Main()\n    {\n\n    }\n}	0
18941082	18941057	How to check If datatable contains anyrow	DataTable dt = DBHandling.GetReferralDrName();\nif (dt != null && dt.Rows.Count > 0)\n{\n    foreach (DataRow dr in dt.Rows)\n    {\n        cmbReferralDr.Items.Add(dr["LastName"].ToString() + " " + dr["FirstName"].ToString());\n    } \n}	0
14861733	14860859	List XPath of all nodes in C#	static void Main(string[] args)\n    {\n        String html = @"\n        <html>\n        <head>\n            <title>Test</title>\n        </head>\n        <body>\n            <div>\n                <p>Test2</p>\n            </div>\n        </body>\n        </html>\n        ";\n\n        XmlDocument doc = new XmlDocument();\n        doc.LoadXml(html);\n\n        foreach (XmlNode node in doc.ChildNodes)\n            ExamineNode(node, "");\n\n        Console.ReadLine();\n    }\n\n    static void ExamineNode(XmlNode node, String parentPath)\n    {\n        String nodePath = parentPath + '/' + node.Name;\n\n        if (!(node is XmlText))\n        {\n            Console.WriteLine(nodePath); // I want to show the path to this node\n\n            foreach (XmlNode childNode in node.ChildNodes)\n                ExamineNode(childNode, nodePath);\n        }\n    }	0
4182606	4182303	Email Configuration Settings not being fetched	var msg = new System.Net.Mail.MailMessage("from@yoursite.com", "to@somesite.com", "Subject", "Body text...");\n  var c = new System.Net.Mail.SmtpClient("smtp.gmail.com", 25);\n  c.Credentials = new System.Net.NetworkCredential("test123@gmail.com", "PassworD");\n  c.Send(msg);	0
5548829	5548771	C#, showing a numeric string as a number in original formatting	private static void TryToParse(string value)\n   {\n      int number;\n      bool result = Int32.TryParse(value, out number);\n      if (result)\n      {\n         Console.WriteLine("Converted '{0}' to {1}.", value, number);         \n      }\n      else\n      {\n         if (value == null) value = ""; \n         Console.WriteLine("Attempted conversion of '{0}' failed.", value);\n      }\n   }	0
16370334	16369953	How to set padding for gridview data with C#?	Tabela.CellPadding = 10;	0
4031305	4031262	how to merge 2 List<T> with removing duplicate values in C#	List<int> list1 = new List<int> { 1, 12, 12, 5};\nList<int> list2 = new List<int> { 12, 5, 7, 9, 1 };\nList<int> ulist = list1.Union(list2).ToList();	0
17902908	17902838	Obtaining XmlElement from XDocument	var newDoc = new XmlDocument();\nnewDoc.LoadXml(doc.ToString());\n3rdPartyFunction(newDoc);	0
16279115	16278908	Centering controls within a form in winforms	private void InitializeComponent(string str)\n{\n    this.BackColor = Color.LightGray;\n    this.Text = str;\n    //this.FormBorderStyle = FormBorderStyle.Sizable;\n    this.FormBorderStyle = FormBorderStyle.FixedSingle;\n    this.StartPosition = FormStartPosition.CenterScreen;\n\n    Label myLabel = new Label();\n    myLabel.Text = str;\n    myLabel.ForeColor = Color.Red;\n    myLabel.AutoSize = true;\n\n    Label myLabel2 = new Label();\n    myLabel2.Text = str;\n    myLabel2.ForeColor = Color.Blue;\n    myLabel2.AutoSize = false;\n    myLabel2.Dock = DockStyle.Fill;\n    myLabel2.TextAlign = ContentAlignment.MiddleCenter;\n\n    this.Controls.Add(myLabel);\n    this.Controls.Add(myLabel2);\n\n    myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;\n    myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;\n}	0
20758858	20758783	Download a file PDF from a web site	Response.Clear();\n    Response.ContentType = "application/pdf";\n    Response.AddHeader("Content-Disposition", "attachment; filename=Yourfile.pdf");\n    Response.BinaryWrite(yourpdfstream.ToArray());\n    Response.Flush();\n    Response.Close();\n    Response.End();	0
6716133	3307932	How to change the report's "document map" root label?	LocalReport.DisplayName="User-friendly name.";	0
15270630	15270160	How to get the build project in TFS Custom build activitiy	build configuration	0
24793628	24736926	How to choose flyout menu item in c# metro style app	((Resize.Flyout as MenuFlyout).Items[0] as MenuFlyoutItem).Text = "hello world";	0
8904216	8904170	Regex expression for date	(?:0[1-9]|[12][0-9]|3[01])(?:0[1-9]|1[0-2])(?:[0-9]{2})	0
14988010	14987901	How to Get Reference to Method from MethodInfo (C#)	lookup.Add(methodInfo.Name\n      , (SkillEffect)Delegate.CreateDelegate(typeof(SkillEffect), methodInfo));	0
28298253	28298187	Reading configuration file from .NET Source Project, not from target	var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);\n\nvar tempValue = config.AppSettings["setting_name"];	0
22593573	22593491	How to Ignore Daylight Savings	var time = DateTimeOffset.Parse("2014-06-30T07:45:00+02:00").DateTime.TimeOfDay;	0
11422530	11421828	Monotouch : Setting Window in pre 5.0 devices	CheckSystemVersion()	0
32831445	32831184	Detecting HTTPRequest failure	var content = new MemoryStream();\n            var webReq = (HttpWebRequest)WebRequest.Create("http://google.com");\n\n            using (WebResponse response = await webReq.GetResponseAsync())\n            {\n                HttpWebResponse res = (HttpWebResponse)response;\n                if(res.StatusCode==HttpStatusCode.OK)\n                {\n                    //your code\n                }\n\n            }	0
21862745	21850516	C# Setting Custom Connection of SSIS custom data flow component through custom UI	private void comboConnections_SelectedIndexChanged(object sender, EventArgs e)\n        {\n            var val = comboConnections.SelectedItem;\n\n            this.metaData.RuntimeConnectionCollection[0].ConnectionManagerID = ((ConnectionManager)val).ID;\n        }	0
12918792	12918626	Select distinct values ignoring one field	;WITH CTE as(\nselect *,ROW_NUMBER() over (partition by PropertyId,UserId  order by AccesedOn desc) as rn\nfrom table1)\n\nselect * from CTE where rn=1	0
11411530	11411486	How to get IPv4 and IPv6 address of local machine?	string strHostName = System.Net.Dns.GetHostName();;\nIPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);\nIPAddress[] addr = ipEntry.AddressList;\nConsole.WriteLine(addr[addr.Length-1].ToString());\nif (addr[0].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)\n            {\n                Console.WriteLine(addr[0].ToString()); //ipv6\n            }	0
6087667	6087344	Reading Data from Text File to a CheckedListBox	string filePath = @"C:\test.txt";\nif (System.IO.File.Exists(filePath))\n   checkedListBox1.Items.AddRange(System.IO.File.ReadAllLines(filePath));	0
23681094	23681023	NHibernate using optional where	var query = Session.QueryOver<Orders>();\n\nif (ids == null || ids.Count == 0)\n{\n    query = query.WhereRestrictionOn(x => x.OrderId).IsIn(Ids);\n}	0
4125485	4107065	how do I update an entity with a collection navigation property (with MVC2)	Timesheet DBTimesheet = context.Timesheets\n                    .Include("TimesheetEntries")\n                    .Where(t => t.Id == timesheet.Id).First();\n\n//Delete if in database but not in submission\nDBTimesheet.TimesheetEntries\n   .Where(dbE => !timesheet.TimesheetEntries.Any(e => e.Id == dbE.Id)).ToList()\n   .ForEach(dbE => context.TimesheetEntries.DeleteObject(dbE));\n\n//Update if in submission and in database\ntimesheet.TimesheetEntries\n    .Where(e => DBTimesheet.TimesheetEntries.Any(dbE => dbE.Id == e.Id)).ToList()\n    .ForEach(e => context.TimesheetEntries.ApplyCurrentValues(e));\n\n//Add if in submission but not in database\ntimesheet.TimesheetEntries\n    .Where(e => !DBTimesheet.TimesheetEntries.Any(dbE => dbE.Id == e.Id)).ToList()\n    .ForEach(e => DBTimesheet.TimesheetEntries.Add(e));\n\ncontext.SaveChanges();	0
25660152	25659942	How to hide footer row in GridView in c#	GridView1.ShowFooter = administratorUsers.ToString() == "1";	0
24375672	24375354	Encrypt a file and save as the same file	public class Encryption\n{\n    public void Encrypt(string inputFilePath, string outputfilePath)\n    {\n        string encryptionKey = ConfigurationManager.AppSettings["EncDesKey"];\n        var inputData = File.ReadAllBytes(inputFilePath);\n\n        using (Aes encryptor = Aes.Create())\n        {\n            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n            encryptor.Key = pdb.GetBytes(32);\n            encryptor.IV = pdb.GetBytes(16);\n\n            using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))\n            {\n                using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n                {\n                    foreach (var item in inputData)\n                    {\n                        cs.WriteByte(item);\n                    }\n                }\n            }\n        }\n    }\n}	0
24438965	24391845	Linq to SharePoint with Distinct Results	using System.Linq;\nusing Microsoft.SharePoint.Linq;\n\nMyDataContext dc = new MyDataContext("http://localhost");\nvar varUserActivity = (from item in dc.UserActivityList\n                       orderby item.UsernameName.ToString().Substring(item.UsernameName.ToString().IndexOf('#') + 1, 1).ToLower().Replace("domain\\", "") ascending\n                       select new { letter = item.UsernameName.ToString().Substring(item.UsernameName.ToString().IndexOf('#') + 1, 1).ToLower().Replace("domain\\", "") }).Distinct();\n\nforeach (var uaitem in varUserActivity)\n{\n    this.Controls.Add(new LiteralControl(uaitem.letter + "<br>"));\n}	0
5920379	5920369	Getting variables value in aspx page rather than code behind	map.setCenter(new GLatLng(<%= Lat %>, <%= Lon %>), 10);	0
19088336	19087755	Parse Complex Xml in Windows Phone	XDocument loadedData = XDocument.Load("Try.xml");\n            var data = from query in loadedData.Descendants("item")\n                       from a in query.Elements("record")\n                       select new Person\n            {\n                Name = (string)a.Value\n\n            };\n            var array = data.ToArray();	0
720364	718386	How can I use the Windows look'n'feel for a system tray context menu?	using System;\nusing System.Windows.Forms;\nusing System.Drawing;\n\npublic class AC : ApplicationContext\n{\nNotifyIcon ni;\npublic void menu_Quit(Object sender, EventArgs args)\n{\nni.Dispose();\nExitThread();\n}\npublic AC()\n{\nni = new NotifyIcon();\nni.Icon = SystemIcons.Information;\nContextMenu menu = new ContextMenu();\nmenu.MenuItems.Add("Quit", new EventHandler(menu_Quit));\nni.ContextMenu = menu;\nni.Visible = true;\n}\npublic static void Main(string[] args)\n{\n//Application.EnableVisualStyles();\n//Application.SetCompatibleTextRenderingDefault(false);\nAC ac = new AC();\nApplication.Run(ac);\n}\n}	0
20627123	20626985	Image after resize has white border	public static Bitmap ResizeImage(Bitmap image, int percent)\n    {\n        try\n        {\n            int maxWidth = (int)(image.Width * (percent * .01));\n            int maxHeight = (int)(image.Height * (percent * .01));\n            Size size =   GetSize(image, maxWidth, maxHeight);\n            Bitmap newImage = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb);\n            SetGraphics(image, size, newImage);\n            return newImage;\n        }\n        finally { }\n    }\n\n   public static void SetGraphics(Bitmap image, Size size, Bitmap newImage)\n    {\n        using (Graphics graphics = Graphics.FromImage(newImage))\n        {\n            graphics.CompositingQuality = CompositingQuality.HighQuality;\n            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;\n            graphics.SmoothingMode = SmoothingMode.HighQuality;\n            graphics.DrawImage(image, 0, 0, size.Width, size.Height);\n        }\n    }	0
10180517	10180442	Multiple rows printing from database	while(reader.Read())\n{\n   // set your variables\n   // do something with the variables\n}	0
11205916	11205572	Export and format data into Excel from C#	//This would convert the listview1 content to Excel document and create the file in the given path        \n    private void CreateExcelFromListview()\n    {\n        ListViewExport.ListViewToCsv(listView1, "C:\\test.csv", true);\n        OpenInExcel("C:\\test.csv");\n    }\n\n    //This would open the document on screen\n    public void OpenInExcel(string strFileName)\n    {\n        try\n        {\n            new Excel.Application {Visible = true}.Workbooks.Open(strFileName);\n        }\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.Message);\n        }\n    }	0
30165932	30165918	Obtain non-maximized window position/size when window is maximized	bool b = WindowState == FormWindowState.Maximized;\nint xpos = !b? Location.X : RestoreBounds.X;\nint ypos = !b? Location.Y : RestoreBounds.Y;\nint width = !b? Width : RestoreBounds.Width;\nint height = !b? Height : RestoreBounds.Height;	0
24512694	24499645	Castle and NLog change connection string at runtime	public class LoggerInstall : IWindsorInstaller\n{\n    private const string NLogConnectionString = "NLogConnection";\n\n    public void Install(IWindsorContainer container, IConfigurationStore store)\n    {\n        var config = new NLog.Config.LoggingConfiguration();\n        container.AddFacility<LoggingFacility>(l => l.LogUsing(new OwnNLogFactory(GetYourConnectionStringMethod(NLogConnectionString))));\n    }\n}\n\n\npublic class OwnNLogFactory : NLogFactory  \n{\n    public OwnNLogFactory(string connectionString)\n    {\n        foreach (var dbTarget in LogManager.Configuration.AllTargets.OfType<DatabaseTarget>().Select(aTarget => aTarget))\n        {\n            dbTarget.ConnectionString = connectionString;\n        }\n    }\n}	0
19223208	19223078	Custom calculated field in ListBox with databinding	private int _lookupValue;\npublic bool isRight\n    {\n      get {\n        return (Math.Abs(_lookupValue) % 2 == 0 ? true : false);\n      }\n    }	0
9677880	9676291	Service proxy freezes application	Test(0)	0
3873731	3873702	Code-snippet or short cut to create a constructor in Visual Studio	public MyClass()\n{\n\n}	0
27935571	27935511	Pushing a List of objects	for (int j = 0; j < 10; ++j)\n{\n    SavedScan.PointData pointData = new SavedScan.PointData();\n    pointData.amplitude = 5.0;\n    tmp.Add(pointData);\n}	0
30639713	30639449	InvalidCastException when casting dynamically to interface	let hwIns = asm.CreateInstance("HelloWorld") |> unbox<IHelloWorld>	0
9276585	9276447	Doing multiple joins within a LINQ statement	var result = from a in Context.DGApprovedLink \n             join h in Context.DGHost on a.HostID equals h.ID\n             join c in Context.DGConfig on a.ResponseCode equals c.SubType\n             where c.Type == "HTTP Status"\n             select new {\n                 a.ID,\n                 a.HostID,\n                 h.URL,\n                 a.SourceURL,\n                 a.TargetURL,\n                 c.Value,\n                 a.ExtFlag };	0
23026064	23025970	Application.DoEvents In a WinForm	async/await	0
13153345	13153164	Porting code from MFC to C#	List<byte>	0
25600595	25600450	Call a class in Visual studio through a button	private void button1_Click(object sender, EventArgs e)\n{\n    StartpoComp spc = new poComp.Client.StartpoComp();\n    //myFormsLabel.Text = spc.SomePublicVariable;\n    //spc.SomePublicMethod(param1);\n}	0
21588579	21394313	Getting pinch-to-zoom x/y scale values independent of each other in Windows Store Apps	int numActiveContacts;\nDictionary<uint, int> contacts;\nList<PointF> locationsOfSortedTouches;\n\nvoid myCanvas_PointerPressed(object sender, PointerRoutedEventArgs e) {\n  PointerPoint pt = e.GetCurrentPoint(myCanvas);\n  locationsOfSortedTouches.Add(new PointF((float) pt.Position.X, (float) pt.Position.Y));\n  touchHandler.TouchesBegan(locationsOfSortedTouches);\n  contacts[pt.PointerId] = numActiveContacts;\n  ++numActiveContacts;\n  e.Handled = true;\n}\n\nvoid myCanvas_PointerMoved(object sender, PointerRoutedEventArgs e) {\n  var pt = e.GetCurrentPoint(myCanvas);\n  var ptrId = pt.PointerId;\n  if (contacts.ContainsKey(ptrId)) {\n    var ptrOrdinal = contacts[ptrId];\n    Windows.Foundation.Point currentContact = pt.Position;\n    locationsOfSortedTouches[ptrOrdinal] = new PointF((float) pt.Position.X, (float) pt.Position.Y);\n    //distance calculation and zoom redraw here\n  }\n  e.Handled = true;\n}	0
4818823	4818809	Multiple Backgroundworkers + C#	var worker1 = new BackgroundWorker { WorkerReportsProgress = true };\nvar worker2 = new BackgroundWorker { WorkerReportsProgress = true };\nDoWorkEventHandler doWork = (sender, e) =>\n{\n    for (int i = 0; i < 10; i++)\n    {\n        var progress = (int)((i + 1) * 100.0 / 10);\n        var worker = (BackgroundWorker)sender;\n        worker.ReportProgress(progress);\n        Thread.Sleep(500);\n    }\n};\nworker1.DoWork += doWork;\nworker2.DoWork += doWork;\nworker1.ProgressChanged += (sender, e) =>\n{\n    label1.Text = e.ProgressPercentage.ToString();\n};\nworker2.ProgressChanged += (sender, e) =>\n{\n    label2.Text = e.ProgressPercentage.ToString();\n};\n\nworker1.RunWorkerAsync();\nThread.Sleep(1000);\nworker2.RunWorkerAsync();	0
13844297	13842869	Set Window.Owner using hWnd	Window dialog = new MyDialog();\nWindowInteropHelper wih = new WindowInteropHelper(dialog);\nwih.Owner = ownerHwnd;\n\n//Block input to the owner\nWindows.EnableWindow(ownerHwnd, false);\n\nEventHandler onClosed = null;\nonClosed = (object sender, EventArgs e) =>\n{\n    //Re-Enable the owner window once the dialog is closed\n    Windows.EnableWindow(ownerHwnd, true);\n\n    (sender as Window).closed -= onClosed;\n};\n\ndialog.Closed += onClosed;\ndialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;\ndialog.ShowActivated = true;\ndialog.Show();\n\n//Import the EnableWindow method\n[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool EnableWindow(IntPtr hWnd, bool bEnable);	0
11477252	11477083	Hashing text with SHA-256 at Windows Forms	// this is where you get the actual binary hash\nbyte[] inputHashedBytes = Sha256.ComputeHash(inputBytes);\n\n// but you want it in a string format, similar to a variety of UNIX tools\nstring result = BitConverter.ToString(inputHashedBytes)\n   // this will remove all the dashes in between each two characters\n   .Replace("-", string.Empty)\n   // and make it lowercase\n   .ToLower();	0
26158756	26157992	UI not updating from EventAggregator	Dispatcher.BeginInvoke(new Action(() => Trace.WriteLine("DONE!", "Rendering")), DispatcherPriority.ContextIdle, null);	0
6723737	6723251	How to utilize SelectedItem within LoadingRow Eventhandler of DataGrid?	e.Row.Loaded += (s,_) => call_dataGrid.SelectedItem = (s as DataGridRow).DataContext;	0
30707287	30707242	Parsing into a string from type DateTime	foreach (Appointment appointment in appointments)\n{\n  appointStart = appointment.Start.ToString();\n  appointLength = appointment.Length.ToString();\n  appointDescription = appointment.DisplayableDescription;\n}	0
30403760	30403675	How to check same value in two integer Arrays in C#	array1.Intersect(array2).ToList().ForEach(i => Console.WriteLine(i));	0
17307691	17307644	Query multiple lists in one go	List<List<foo>> lists = new List<List<foo>>()\n{\n    spamSpamAndSpam,\n    spamSpamSpamSausageEggsAndSpam,\n    //etc.\n};\n\nIEnumerable<foo> items = lists.SelectMany(item => item);\n//do stuff with items.	0
29629125	29628378	How to filter datagridview using multiple checkboxes	string rowFilter = string.Empty;\n        if (cb11.Checked)\n        {\n            rowFilter += " [AreaCode] = " + cb11.Text.Trim();\n        }\n        if (cb16.Checked)\n        {\n            if (rowFilter.Length > 0)\n                rowFilter += " OR";\n            rowFilter += " [AreaCode] = " + cb16.Text.Trim();\n        }\n        if (cb31.Checked)\n        {\n            if (rowFilter.Length > 0)\n                rowFilter += " OR";\n            rowFilter += " [AreaCode] = " + cb31.Text.Trim();\n        }\n\n        try\n        {\n            //Check an see what's in the dgv\n            DataView dv = new DataView(dt);\n            dv.RowFilter = rowFilter;\n            datagridview1.DataSource = dv;\n        }\n        catch (Exception)\n        {\n            MessageBox.Show("Can???t find the column", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);\n        }	0
2002779	2002692	Clone a row with a primary key in SQL?	INSERT INTO Addresses\n( address1, address2 )\nSELECT address1, address2\n  FROM Addresses\n WHERE addressId = ID	0
16742035	16741855	convert string to ConnectionStringSettings	public ConnectionStringSettings getConnection(string server, string database)\n{\n    string connection = ConfigurationManager.ConnectionStrings["myConnString"].ToString();\n    connection = string.Format(connection, server, database);\n\n    return new ConnectionStringSettings("myConnString", connection);\n}	0
26137386	26135821	C# calculate difference from two rows based on a sql query	for(int i=0; i < dst.Tables[0].Rows.Count - 1; i+=2)\n{\n    if(dst.Tables[0].Rows.Count % 2 != 0)\n         Console.WriteLine("Wrong records count")\n\n    int number1Row1 =Convert.ToInt32(dst.Tables[0].Rows[i]["Number1"]);\n    int number1Row2 =Convert.ToInt32(dst.Tables[0].Rows[i]["Number2"]);\n    int number2Row1 =Convert.ToInt32(dst.Tables[0].Rows[i+1]["Number1"]);\n    int number2Row2 =Convert.ToInt32(dst.Tables[0].Rows[i+1]["Number2"]);\n\n    DateTime dateRow1 =Convert.ToDateTime(dst.Tables[0].Rows[i]["Date"]);\n    DateTime dateRow2 =Convert.ToDateTime(dst.Tables[0].Rows[i+1]["Date"]);\n\n    double calc = ((number1Row2- number1Row1 + number2Row2 - number2Row1)/2)*(dateRow1 - dateRow2).TotalDays\n\n    Console.WriteLine(calc);\n}	0
9034776	9028373	Metro App can no longer be programmatically killed?	App.Current.Exit()	0
2456544	2456526	Filter to values in collection in one query	List<String> Types \n    = Directory.GetFiles(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727")\n        .Where(x => System.IO.Path.GetFileNameWithoutExtension(x).Contains("Microsoft"))   \n        .Where(x => yourCollection.Contains(x))\n        .ToList();	0
9945310	9944994	Fast serialization/deserialization of structs	byte[] bytes = GetFromDisk();\nfixed (byte* bytePtr = bytes) {\n Child* childPtr = (Child*)bytePtr;\n //now treat the childPtr as an array:\n var x123 = childPtr[123].X;\n\n //if we need a real array that can be passed around, we need to copy:\n var childArray = new Child[GetLengthOfDeserializedData()];\n for (i = [0..length]) {\n  childArray[i] = childPtr[i];\n }\n}	0
14446145	14446053	Multiple relations in Entity Framework ICollection?	public class User\n{\n    public int ID { get; set; }\n    public string Username { get; set; }\n    public virtual ICollection<Post> PostsThisUserLikes {get;set;}\n}\npublic class Post\n{\n    public int ID { get; set; }\n    public string Contents { get; set; }\n    public virtual ICollection<User> UsersWhoLikeThis { get; set; }\n}	0
29457532	29457384	querying from cached data, simple linq statement	string cityName = CachedCities.Where(x => x.Id == item.Address.CityId)\n                    .Select(a => a.Name)\n                    .FirstOrDefault();	0
22505911	22482374	WCF Service converts localhost to www.localhost.com only in case of json response	[DataMember]\npublic DateTime DiscountStart\n{\n    get { return this._discountStart.ToUniversalTime(); }\n    set { this._discountStart = value; }\n}	0
24683832	24683196	How do I implement a segmented Text box in c# that enforces user to enter values in specific format?	maskedTextBox1.Mask = "00-000-0-0000";	0
5971209	5971164	Attached an anonymous type to an object; how to retrieve it? 	dynamic o = e.UserState;\no.title;	0
19530569	19530452	Left Join List<t> with Datatable -Linq	var table = \n    dtProducts.AsEnumerable()\n        .Select(r => p.Field<string>("Description")).ToList();\nvar result = \n    productList\n       .Where(p => !table.Any(t => StringComparer.OrdinalIgnoreCase.Equals(t, p.TechnicalDescription)));	0
11085505	11085440	"For loop" to check elements of a CheckBoxList	CheckBoxList cbl = (CheckBoxList)FindControl("CBL_categ");\n\nif (cbl != null)\n{\n        for (int i = 0; i < cbl.Items.Count; i++)\n        {\n            if (cbl.Items[i].Selected)\n            {\n                catn = cbl.Items[i].Value;\n             }\n         }\n }	0
17634250	17634214	WebApi Syntax Anomaly	WebApiConfig. TypeNameHandling(GlobalConfiguration.Configuration);	0
5190497	5190405	using GO keyword in SQL Server	DECLARE @STRING1 AS VARCHAR(50)\nDECLARE @STRING2 AS VARCHAR(50)\n\nSET @STRING1='BATCH 2'\nSET @STRING2='BATCH 3'\n\nSELECT @STRING1 AS RESULT\nGO\n\nSELECT @STRING2 AS RESULT\nGO	0
18642753	18641964	how to get current day in windows phone?	var dateTime = DateTime.Now.Day;	0
27354614	27354007	Forcing an update of a property from within a custom control	Value += 0.5;	0
24567761	24530415	Implement a IsProcessOpen into an application	namespace My_Program\n{\n    static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        static Mutex mx;\n        const string singleInstance = @"MU.Mutex";\n\n        [STAThread]\n        static void Main(string[] args)\n        {\n            try\n            {\n                System.Threading.Mutex.OpenExisting(singleInstance);\n                MessageBox.Show("The program is already running!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);\n                return;\n            }\n            catch (Exception e)\n            {\n                mx = new System.Threading.Mutex(true, singleInstance);\n            }\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Main());\n        }\n    }\n}	0
20754033	20753999	Sorting List Given a specific scenario	var orderedList = \n      customers.OrderBy(c => c.Name).ThenByDescending(c => c.Date).ToList();	0
5608789	5572776	How to retrieve DirectoryEntry from a DirectoryEntry and a DN	DirectoryEntry User = YourPreExistingUser();\n\nstring managerDN = User.Properties["manager"][0].ToString();\n\n// Browse up the object hierarchy using DirectoryEntry.Parent looking for the\n// domain root (domainDNS) object starting from the existing user.\nDirectoryEntry DomainRoot = User;\n\ndo\n{\n    DomainRoot = DomainRoot.Parent;\n}\nwhile (DomainRoot.SchemaClassName != "domainDNS");\n\n// Use the domain root object we found as the search root for a DirectorySearcher\n// and search for the manager's distinguished name.\nusing (DirectorySearcher Search = new DirectorySearcher())\n{\n    Search.SearchRoot = DomainRoot;\n\n    Search.Filter = "(&(distinguishedName=" + managerDN + "))";\n\n    SearchResult Result = Search.FindOne();\n\n    if (Result != null)\n    {\n        DirectoryEntry Manager = Result.GetDirectoryEntry();\n    }\n}	0
32382025	32381320	Get column by table name entity framework reflection	((IQueryable)table).ElementType.GetProperties()	0
1540787	1540779	How to get the numeric value from the Enum?	int value = (int)System.Net.HttpStatusCode.Forbidden;	0
10550886	10550610	Get only word before special char	var patt = @"\s(\b(.+?))/";\nvar matches = Regex.Matches("[ADVP again/RB ] [VP seen/VBN ] [NP is/VBZ ] [NP a/DT focal/JJ asymmetry/NN ].", patt);\n\nvar matchedValues = matches\n    .Cast<Match>()\n    .Select(match => match.Groups[1].Value);\n\nvar output = string.Join(" ", matchedValues);	0
18373343	18373167	How are going to read a text file and auto save in c #	string fileText = File.ReadAllText("filePath");\n  if (fileText.Contains("apple"))\n  {\n       Messagebox.Show("This word is exist");\n  }\n  else\n  {\n       Messagebox.Show("The word does not exist!");\n       File.AppendAllText(@"filePAth", "The word does not exixt in the text file" + Environment.NewLine);\n  }	0
4635112	4635031	Drawing a map based on an array, and applying run time changes	for(int i=0; i<100; i++)\n{\n    for(int j=0;j<150;j++)\n    {\n        <access[i,j] and draw a rectangle with color accordingly to your contents.>\n    }\n}	0
7879343	7878805	String to byte array	var arr = new byte[s.Length/2];\nfor ( var i = 0 ; i<arr.Length ; i++ )\n    arr[i] = (byte)Convert.ToInt32(s.SubString(i*2,2), 16);	0
23301921	23301768	Flowlayout Panel Disable Middle Mouse Wheel Scrolling	public class FlowPanel : FlowLayoutPanel {\n  protected override void OnMouseWheel(MouseEventArgs e) {\n    // base.OnMouseWheel(e);\n  }\n}	0
23856502	23763530	How do you make the header row unselectable in a table that was imported into a dataGridView	foreach (DataGridViewColumn col in dataGridView1.Columns)\n        {\n            col.SortMode = DataGridViewColumnSortMode.NotSortable;\n        }	0
7887209	7877193	How to fire a JQuery selector from WatiN	browser.Eval(string.Format("$('#{0},.{0}').change();", id)); //Both for classes and id's	0
31710	31708	How can I convert IEnumerable<T> to List<T> in C#?	var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();	0
9501090	9501042	Casting a custom type from VB6 to a List<> in C#?	List<your_new_similar_class>	0
6617283	6617193	How to split a string in C#?	string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";\nstring[] data = test.Split(',');\nDictionary<string, string> dic = new Dictionary<string, string>();\nfor(int i = 0; i < data.Length; i++) {\n    int index = data[i].IndexOf(':');\n    string key = data[i].Substring(0, index);\n    string value = data[i].Substring(index + 1);\n    if(!dic.ContainsKey(key))\n        dic.Add(key, value);\n    else\n        dic[key] = string.Format("{0}, {1}", new object[] { dic[key], value }); \n}	0
6659376	6659362	Best practice for passing parameters, which can take two values	public class Foo\n{\n    public void Start()\n    {\n        PreCommon();\n\n        // Code [Start]\n\n        PostCommon();\n    }\n\n    public void Stop()\n    {\n        PreCommon();\n\n        // Code [Stop]\n\n        PostCommon();\n    }\n\n    private void PreCommon()\n    {\n        // Code [Pre-Common]\n    }  \n\n    private void PostCommon()\n    {\n        // Code [Post-Common]\n    }    \n    ...\n\n}	0
1096627	1096553	Stretch Bitmap without anti-aliasing	g.InterPolationMode = InterpolationMode.NearestNeighbor	0
2461699	2461512	How to intercept capture TAB key in WinForms application?	Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean\n  Dim keyPressed As Keys = CType(msg.WParam.ToInt32(), Keys)\n\n  Select Case keyPressed\n    Case Keys.Right msgbox("Right Arrow Key Caught")\n    Case Keys.Left msgbox("LeftArrow Key Caught")\n    Case Keys.Up msgbox("Up Arrow Key Caught")\n    Case Keys.Down msgbox("Down Arrow Key Caught")\n    Case Else Return MyBase.ProcessCmdKey(msg, keyData)\n  End Select\nEnd Function	0
32503597	32503432	Change download-file name ItextSharp	Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);	0
7772159	7772015	WPF Application exit code	Application.Current.Shutdown(110);	0
20771809	20771798	Trying to reverse a char array in C#	foreach (char character in myChar)\n {\n     Console.Write(character);\n }	0
18942746	18930765	ServiceStack HasPermission in the context of the request	public class CanViewAttribute : RequestFilterAttribute {\n    private readonly string permission;\n\n    public CanViewAttribute(string permission) {\n        this.permission = permission;\n    }\n\n    public override void Execute(IHttpRequest req, IHttpResponse res, object responseDto) {\n        // todo: check permission\n\n        if (!hasPermission) {\n          res.StatusCode = (int)HttpStatusCode.Forbidden;\n          res.EndRequest();\n        }\n    }\n}	0
7176422	7176337	How to update table using the Dataset?	sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'	0
22185209	22134514	Httpclinet getasync resetting cookies	var wwwUri = new Uri("https://www.mywebsite.com");\nCookiejar.SetCookies(baseUri, Cookiejar.GetCookieHeader(wwwUri));	0
16962765	16961891	How to Set Outhtml for Gecko Browes in C#	geckoWebBrowser1.LoadHtml("<html><body><h1>Hello!!!</h1></body></html>");	0
27737991	27737859	Launching debug mode application from c#	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.CreateNoWindow = false;\nstartInfo.UseShellExecute = false;\nstartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(this.PathToExeTextBox.Text);\nstartInfo.FileName = this.PathToExeTextBox.Text;\nProcess.Start(startInfo);	0
31501323	31501039	How to do the pagination when read xml data by LINQ	//setup basic query\nvar query = from r in document.Descendants("Orders")\n            select new\n            {\n                OrderID = r.Element("OrderID").Value,\n                CustomerID = r.Element("CustomerID").Value,\n                EmployeeID = r.Element("EmployeeID").Value,\n            };\n\n//setup query result ordering,\n//assume we have variable to determine ordering mode : bool isDesc = true/false\nif (isDesc) query = query.OrderByDescending(o => o.OrderID);\nelse query = query.OrderBy(o => o.OrderID);\n\n//setup pagination, \n//f.e displaying result for page 2 where each page displays 100 data\nvar page = 2;\nvar pageSize = 100;\nquery = query.Skip(page - 1*pageSize).Take(pageSize);\n\n//execute the query to get the actual result\nvar items = query.ToList();	0
28977453	28977356	Get href value with onServerClick	public void room_click(object sender, EventArgs e)\n    {\n        var href = ((System.Web.UI.HtmlControls.HtmlAnchor)sender).HRef;\n    }	0
8180303	8180140	Changing TabIndex when a control gets disabled	Select()	0
8299894	8299142	How to generate MD5 hash code for my WinRT app using C#?	public static string ComputeMD5(string str)\n    {\n        var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);\n        IBuffer buff = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);\n        var hashed = alg.HashData(buff);\n        var res = CryptographicBuffer.EncodeToHexString(hashed);\n        return res;\n    }	0
24080562	24080492	LINQ lambda with where clause	totalTickets = context.EventParentSponsors.Join(context.EventSponsors, \n                                                x=>x.EventSponsorId,\n                                                y=>y.EventSponsorId,\n                                                (x,y) =>\n                                                new \n                                                {\n                                                    ID=x.ParentSponsorID , \n                                                    Count = x.InvitationCount \n                                                })\n                                          .Where(x=>x.ID==parentId)\n                                          .Select(x=>x.Count)\n                                          .FirstOrDefault();	0
30925259	30924930	How to make a programs icon in the task bar change based on something like time?	this.Title = DateTime.Now.ToString();	0
14372981	14372198	DataGridView cell text and cell value	private void DataGridView1_CellFormatting(object sender,\n    DataGridViewCellFormattingEventArgs e)\n{\n    DataGridView dgv = (DataGridView)sender;\n    if (dgv.Columns[e.ColumnIndex].Name == "TargetColumnName" &&\n        e.RowIndex >= 0 &&\n        dgv["TargetColumnName", e.RowIndex].Value is int)\n    {\n        switch ((int)dgv["TargetColumnName", e.RowIndex].Value)\n        {\n            case 1:\n                e.Value = "one";\n                e.FormattingApplied = true;\n                break;\n            case 2:\n                e.Value = "two";\n                e.FormattingApplied = true;\n                break;\n        }\n    }\n}	0
8817455	8817353	Assembly.LoadFrom behaviour different in Windows 7	Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)	0
21757951	21757376	Java socket read bytes from C#	int data;\nwhile((data=streamFromClient.read()) != -1) {\n  char theChar = (char) data;\n  System.out.println("" + theChar);\n}	0
22614159	22559330	ASP.Net to Excel export - column width and alternate row coloring	XLWorkbook workbook = new XLWorkbook("test.xlsx");\nIXLWorksheet worksheet = workbook.AddWorksheet("Sheet1");\nworksheet.Cell(1, 1).SetValue("Test").Style.Font.SetBold(true);\nworksheet.AdjustToContent(); // this changes the column width to fit the content\nworkbook.Save();	0
11542456	11542340	Linq get data from m to n tables?	var modullerList = new List< TblModuller>();\n\nforeach (var rol in roller)\n{\n     moduls_in_roles = entity.TblModulsInRoles.Where(x => x.Roles.RoleName == rol);\n     foreach(var modul in moduls_in_roles)\n     {\n        if(!modullerList .Contains(modul))\n            modullerList .Add(modul);\n     }\n}	0
21961439	21961178	Checking a Selected value in the combobox	string value = Type_CB.SelectedItem.ToString();\nstring value2 = "3";\nif (value2 == value)\n{\ndo some work\n}	0
777157	776703	How to check for null values?	if(data.GetColumnValue("Column Name") == null)\n{\n    ...\n}	0
7032650	7032600	Linq, get distinct elements grouped by a field	var a = o.GroupBy(x => x.Name).Select(g => g.First())	0
25816838	25814659	Looping through objects to get their properties in Windows Phone	MainPage()\n{\n    DoSomethingToImages(LayoutRoot);\n}\n\nDoSomethingToImages(Panel panel)\n{\n    foreach(Image img in panel.Children.Where(x=> x is Image))\n    {\n        DoSomething(img);\n    }\n    var panels = panel.Children.Where(x=> x is Panel);\n    if (panels.Count > 0)\n    {\n        foreach(Panel p in panels)\n        {\n            DoSomethingToImages(p);\n        }\n    }\n}	0
10194330	10194110	Cancel step if validation fails in asp.net wizard	protected void Wizard1_SideBarButtonClick(object sender, WizardNavigationEventArgs e)\n  {\n    e.Cancel = !ValidateWizardStep(e.NextStepIndex);\n  }\n\n  protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)\n  {\n    e.Cancel = !ValidateWizardStep(e.NextStepIndex);\n  }	0
14102394	14101995	how does a delegate know which function to call in case of multiple subscribers	this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);	0
5132810	5132788	Insert data as first item	Object firstItem = comboBox.Items[0];	0
23346106	23240629	Creating MS Word Content Controls on a loop	private Run ParseForOpenXML(string textualData)\n{\n    Run run = new Run();\n\n    //split string on paragraph breaks, and create a Break object for each\n    string[] newLineArray = { Environment.NewLine, "\n" };\n    string[] textArray = textualData.Split(newLineArray, StringSplitOptions.None);\n    bool first = true;\n\n    foreach (string line in textArray)\n    {\n        if (!first)\n        {\n            run.Append(new Break());\n        }\n        first = false;\n\n        //split string on tab breaks, and create a new TabChar object for each\n        bool tFirst = true;\n        string[] tabArray = line.Split('\t');\n        foreach(string fragment in tabArray)\n        {\n            if (!tFirst)\n            {\n                run.Append(new TabChar());\n            }\n            tFirst = false;\n\n            Text txt = new Text();\n            txt.Text = fragment;\n            run.Append(txt);\n        }\n    }\n\n    return run;\n}	0
29592708	29592602	how to show a form from a c# dll in a vb.net appliaction	Dim welcomeScreen as New WelcomeScreen()\nwelcomeScreen.Show()	0
33528527	33525881	Draw a graph in Windows Forms Application from a DataTable in a Data Access class	protected void Page_Load(object sender, EventArgs e)\n{\n    // Initializes a new instance of the DataAccess class \n    DataAccess da = new DataAccess();\n\n    // The styling of the graph\n    chart1.Series["Series1"].ChartType = SeriesChartType.Column;\n    chart1.Series["Series1"].IsValueShownAsLabel = true;\n\n    // The required lines for getting the data from the method in the DataAccess\n    chart1.DataSource = da.select_top_sheep(farmerID);\n    chart1.Series["Series1"].XValueMember = "SheepID";\n    chart1.Series["Series1"].YValueMembers = "Weight";\n    chart1.DataBind();\n}	0
22606175	22605865	Protected method access from derived class	public class BaseClass\n{\n  protected internal virtual void Foo(){}\n} \n\npublic class Derived1 : BaseClass\n{\n   protected internal override void Foo()\n    {\n     //some code...\n    }\n}	0
4079207	4079191	WinForm Applications event handler	// Implicit method-group conversion, should work from C# 2.0 or later.\n// Essentially shorthand for listBox1.Click += new EventHandler(clicked);\nlistBox1.Click += clicked; \n\n// Creating a delegate-instance from a 'compatible' delegate,\n// a trick I recently learnt from his highness Jon Skeet\nlistBox1.Click += new EventHandler(onClicked);	0
34131248	34129575	How to rollback EF 7 migrations programmatically?	var migrator = db.GetInfrastructure().GetRequiredService<IMigrator>();\nmigrator.Migrate("Migration1");	0
27667529	27667479	unexpected result drawing circle	for (int x = 0; x < 20; x++)\n        {\n            System.Drawing.Graphics graphics = e.Graphics;\n            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(xpos - 10 - x / 2, ypos - 10 - x / 2, x, x);\n            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);\n\n        }	0
10526410	10525784	Benefits of a BrowserPanel?	//Save the HTML to a file\nstring fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\a.html";\nSystem.IO.StreamWriter file = new System.IO.StreamWriter(fileName);\nfile.WriteLine(htmlContent);\nfile.Close();\n\n//Open the HTML file in the default browser\nProcessStartInfo start = new ProcessStartInfo();\nstart.FileName = fileName;\nProcess myProcess = Process.Start(start);	0
7108303	7108265	Unable to display the full image in datagridview cell	for(int i = 0; i < dataGridView1.Columns.Count; i ++)\n                if(dataGridView1.Columns[i] is DataGridViewImageColumn) {\n                    ((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;\n                    break;\n                }	0
19636006	19597054	MVC 4 Validation Date ISSUE - Cannot blank out a previously entered date field	protected void Application_Start()\n{\n    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;\n   .....\n}	0
18286907	18286874	While and IF in data reader	if (DR1.HasRows)\n        {\n            while (DR1.Read())\n            {\n                flowLayoutPanel1.Controls.Add(label);\n            }\n        }\nelse\n    MessageBox.Show("No results found")	0
2622821	2620650	StructureMap - Scan - Generic Interface with base implementation and specific	StructureMap.ObjectFactory.Configure(x =>\n{\n    x.Scan(y =>\n    {\n        y.TheCallingAssembly();\n        y.ConnectImplementationsToTypesClosing(typeof(IGenericSetupViewModel<>));\n    });\n    x.For(typeof (IGenericSetupViewModel<>)).Use(typeof(GenericSetupViewModel<>));\n});	0
4585792	4585778	Comparing C# objects using Json	Equals()	0
31062237	31049360	Application Insights: How to track crashes in Desktop (WPF) applications?	var exceptionTelemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(new Exception());\n        exceptionTelemetry.HandledAt = Microsoft.ApplicationInsights.DataContracts.ExceptionHandledAt.Unhandled;\n        telemetryClient.TrackException(exceptionTelemetry);	0
8165880	8165509	Store hierarchical Const data	System3 / Rules / Rule7	0
5586363	5585081	How to pass value from view to controller	[HttpPost]\npublic ActionResult Index() {\n\n    string name = Request["name"];\n}	0
6153143	6153074	How to write data to a text file in C#?	string path = @"C:\temp\file"; // path to file\nusing (FileStream fs = File.Create(path)) \n{\n        // writing data in string\n        string dataasstring = "data"; //your data\n        byte[] info = new UTF8Encoding(true).GetBytes(dataasstring);\n        fs.Write(info, 0, info.Length);\n\n        // writing data in bytes already\n        byte[] data = new byte[] { 0x0 };\n        fs.Write(data, 0, data.Length);\n}	0
12683998	12683980	double.parse convert two zero decimal to one decimal	string str = "10.00";\ndouble db = double.Parse(str);\nString.Format("{0:0.00}", db); // will show 10.00	0
5739839	5737279	Is it a good practise to use CommonServiceLocator to inject dependencies into base class?	public class BaseClass\n{\n    public BaseClass()\n    {\n    }\n\n    public IService Service { get; set; }\n}	0
9702616	9702419	decimal removed after validation @ WPF Textbox	binding.ConverterCulture = CultureInfo.CurrentCulture;	0
31427687	31427627	Column added only works for first row in GridView	foreach (DataRow row in main.Rows)\n      {\n          row["NotPOD"] = Convert.ToInt32(row["Jobs"]) - Convert.ToInt32(row["POD"]);\n      }	0
7485441	7484498	Best Way to Save a Font in SQL Server database	CREATE TABLE dbo.YourTable\n     (....... define the fields here ......)\n     ON Data                   -- the basic "Data" filegroup for the regular data\n     TEXTIMAGE_ON LARGE_DATA   -- the filegroup for large chunks of data	0
28484406	28483014	Adding Struct : Interface to a List<Interface>	struct Foo1 : IFoo {...}\nstruct Foo2 : IFoo {...}\n\nList<IFoo> listOfFoo = new List<IFoo>();\n\nIFoo foo1 = new Foo1();\nIFoo foo2 = new Foo2();\nlistOfFoo.Add(foo1);\nlistOfFoo.Add(foo2);\n\n// lets retrieve the first element and check if it's a Foo1 value type\nif(listOfFoo[0] is Foo1){\n    // cast element from List to Foo1\n    Foo1 foo = (Foo1) listOfFoo[0];\n}	0
5057598	5057567	How to do logging in c#?	public void Logger(String lines)\n{\n\n // Write the string to a file.append mode is enabled so that the log\n // lines get appended to  test.txt than wiping content and writing the log\n\n  System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);\n  file.WriteLine(lines);\n\n  file.Close();\n\n}	0
4280557	4280493	Print & Print Preview a Bitmap plus a Label with Text in it in c#	private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)\n {\n   e.Graphics.DrawImage(capturebox.BackgroundImage, 0, 0);\n   e.DrawString(ExtraNotes.Text, SystemFonts.CaptionFont, Brushes.Black, 10, 10);\n   e.Graphics.DrawImage(capturebox.Image, 0, 0);    \n }	0
17627674	17625742	How do I insert a string AFTER a specific string within a string?	int LastRegister = fileString.LastIndexOf("Register TagPrefix");\nint InsertPosition = fileString.IndexOf('>', LastRegister) + 2;\nfileString = fileString.Insert(InsertPosition, "String x");	0
12484314	12484215	Quotient in Windows phone 7 + silverlight + C#	double num1 = 27;\nint num2 = 7;\ndouble dblResult = num1 / num2; // will yield floating point result 3.857...\nint intResult    =(int)num1 / num2; // will yield integer quotient 3	0
27397168	27397044	How to remove rows from a bound Datagridview	dataGridView2.DataSource = null;	0
11223595	11222708	How to parse HTML tag?	int result = -1;\n            var matches = Regex.Matches(\n                HTMLText,\n                @"(?:\S+\s)?\S*page views\S*(?:\s\S+)?",\n                RegexOptions.IgnoreCase\n            );\n\n            foreach (Match m in matches)\n            {\n                string val = m.Value;\n                int res=-1;\n                if (Int32.TryParse(val, out res))\n                {\n                    result = res;\n                    break;\n                }\n            }	0
336830	336817	How can I detect whether a user control is running in the IDE, in debug mode, or in the released EXE?	public static bool IsInRuntimeMode( IComponent component ) {\n    bool ret = IsInDesignMode( component );\n    return !ret;\n}\n\npublic static bool IsInDesignMode( IComponent component ) {\n    bool ret = false;\n    if ( null != component ) {\n        ISite site = component.Site;\n        if ( null != site ) {\n            ret = site.DesignMode;\n        }\n        else if ( component is System.Windows.Forms.Control ) {\n            IComponent parent = ( (System.Windows.Forms.Control)component ).Parent;\n            ret = IsInDesignMode( parent );\n        }\n    }\n\n    return ret;\n}	0
29014485	29014456	Finding first element of an array containing "-"	Array.IndexOf(array, "-");	0
5607380	5607116	How to select XML node by attribute and use it's child nodes data?	int saves = 0;\n\nList<Saves> saveGames = new List<Saves>();\n\nsaveGames.Add(new Saves());\n\nwhile (textReader.Read())\n{\n   if (textReader.NodeType == XmlNodeType.Element)\n      whatsNext = textReader.Name;\n   else if (textReader.NodeType == XmlNodeType.Text)\n   {\n      if (whatsNext == "name")\n         saveGames[saves].name = Convert.ToString(textReader.Value);\n      //else if statements for the rest of your attributes\n      else if (whatsNext == "Save")\n      {\n         saveGames.Add(new Saves());\n         saves++;\n      }\n   }\n   else if (textReader.NodeType == XmlNodeType.EndElement)\n      whatsNext = "";\n}	0
31995415	31994886	WPF dynamic binding of a control property to another control property	checkbox.SetBinding(CheckBox.IsCheckedProperty, new Binding("Topmost") { Source = win });	0
9293713	9292953	Dynamically created button in WPF	System.Windows.Controls.Button newBtn = new Button();\n  Image imageControl = new Image();\n  imageControl.Source = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture));\n  newBtn.Content = imageControl;\n  newBtn.Name = "Button" + i.ToString();\n  sp.Children.Add(newBtn);\n\n  i++;	0
28560909	28560857	LINQ and PagedList how to orderby	list = list.OrderByDescending(x => x.timestamp);	0
9336976	9335551	document database with search features	session.Query<Resturant, Resturants_Search>()\n  .Customize(c=>c.WithinRadiusOf(radios: 3, latitude: 51, longitude: 43)\n  .Search(r=>r.Query, "Seafood")\n  .Select(r=>new{r.Name, r.Address})\n  .Take(5);	0
26630386	26630092	How to redirect two step backward after clicking delete button in asp.net and vb.net	function goBack() {\n    window.history.go(-2)\n}	0
533543	533527	How do I replace special characters in a URL?	System.Web.HttpUtility.UrlEncode("c# objects");	0
5472479	5472461	pass IDictionary<,> as a parameter in attribute, possible?	[My(Key = "1234", Value = "1234")]\n[My(Key = "4234", Value = "4234")]	0
9534166	9533929	Best way to copy file from File Share?	System.Data.DataTable dt; //Fill your data into this datatable\n\nstring destPath = "Drive:\\Your_destination_path";\nstring fullSrcPath = null;\n\nforeach(System.Data.DataRow dr in dt.Rows){\n    fullSrcPath = dr["PathColName"].ToString() + "\\" + dr["fileColName"].ToString();\n    if(System.IO.File.Exists(fullSrcPath)){\n        System.IO.File.Copy(fullSrcPath,destPath+ "\\"+dr["fileColName"].ToString());\n    }\n}	0
6997380	6995871	C#: how to read a line from a stream and then start reading it from beginning?	Stream responseStream = CopyAndClose(resp.GetResponseStream());\n// Do something with the stream\nresponseStream.Position = 0;\n// Do something with the stream again\n\n\nprivate static Stream CopyAndClose(Stream inputStream)\n{\nconst int readSize = 256;\nbyte[] buffer = new byte[readSize];\nMemoryStream ms = new MemoryStream();\n\nint count = inputStream.Read(buffer, 0, readSize);\nwhile (count > 0)\n{\n    ms.Write(buffer, 0, count);\n    count = inputStream.Read(buffer, 0, readSize);\n}\nms.Position = 0;\ninputStream.Close();\nreturn ms;\n}	0
27458829	27458747	How do I convert less than 8 bytes to a ulong in C#?	byte[] bytes = new byte[255]{ 0x1F, 0x1A, 0x1B, 0x2C, 0x3C, 0x6D, 0x1E }; //7 bytes\n\nwhile(bytes.length < 8){\n   bytes.Concat(new byte[] { 0x00 });\n}\n\nlong res = BitConverter.ToUInt64(bytes, 0);	0
2072638	2072581	Integrating phrase translation with String.Format	/\{\d+\}/	0
5130135	5130114	ListView Layout	white-space:nowrap	0
12663936	12663918	Matching Negative Sequence	(word1).*?(word2)	0
12541674	12541642	Getting multiple indexes from passing single value	int[] xx = {4,5,4,3,2};\n\nint search = 4;\n\nvar result = xx.Select((b, i) => b.Equals(search) ? i : -1).Where(i => i != -1);	0
22325575	22325168	Is there a way in C# to create a design template for a component	public class yourbuttontemplate : System.Windows.Forms.Button\n{\n    yourbuttontemplate() //constructor\n    {\n        this.Height=20;\n        this.Width=40;\n        this.BackColor=Color.Blue;\n    }\n}	0
33239917	33239632	Is there a better way to select multiple rows in Entity Framework?	return from u in ManageEntity.AspNetUsers\n    select new UserDetails{\n        Username = u.UserName,\n        Lockouts = u.LockoutEnabled,\n        AccessFailedCounts = u.AccessFailedCount\n    };	0
11374307	11374102	Castle Windsor Register by Convention - how to register generic Repository based on Entity?	container.Register(Component.For(typeof(IRepository<>))\n            .ImplementedBy(typeof(Repository<>))\n            .LifeStyle.Transient);	0
9137058	9137031	Advice on refactoring a regex character class subtraction	"(?![" + listOfUnicodeChars + "])[\\p{Lu}" + ... + "]"	0
11626639	11626485	LInq to Sql query with Group by	var query = from b in context.TableB\n             group new { c1 } by new\n             {\n                b.c1\n             } into GroupByC1\n             select new \n             {\n                c1 = GroupByC1.Key.C1,\n                count1 = GroupByC1.count()\n             } \n\nvar result = from a in tableA\n             join b in query on a.c1 equals b.c1\n             where b.count1 > 10	0
1767617	1767385	setting Excel cell format from C# using late binding	using System;\nusing Excel = Microsoft.Office.Interop.Excel;\n\npublic class MyClass\n{\n    public void FormatRange(Excel.Worksheet sheet)\n    {\n    Excel.Range range = sheet.Cells["1","A"];\n    range.Interior.ColorIndex = 15;//This sets it to gray\n    range.Font.Bold = true;//Sets the Bold\n    range.NumberFormat = "@";//Sets it to numeric\n    }\n}	0
8268898	8268625	get pointer on byte array from unmanaged c++ dll in c#	[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]\npublic static extern byte* bufferOperations(byte* incoming, int size);\n\npublic void TestMethod()\n{\n    var incoming = new byte[100];\n    fixed (byte* inBuf = incoming)\n    {\n        byte* outBuf = bufferOperations(inBuf, incoming.Length);\n        // Assume, that the same buffer is returned, only with data changed.\n        // Or by any other means, get the real lenght of output buffer (e.g. from library docs, etc).\n        for (int i = 0; i < incoming.Length; i++)\n            incoming[i] = outBuf[i];\n    }\n}	0
9758230	9708854	Is there a way to import an extension method for a number type into IronPython code?	(1).__index__()	0
19273242	19273177	Matching last occurance of character using Regex	/>([^<>]+)</	0
16360818	16360453	Correct way to encapsulate through generic interfaces	// Client-side\n\ninterface IBox\n{\n    IEnumerable<ITool> Tools { get; }\n}\n\ninterface ITool\n{\n    void Use();\n}\n\n// Server-side\n\nclass Box : IBox\n{\n    public List<Tool> ToolList = new List<Tool>();\n\n    public IEnumerable<ITool> Tools\n    {\n        get { return ToolList; } // With .NET 3.5 and earlier cast here is neccessary to compile\n        // Cast to interfaces shouldn't be so much of a performance penalty, I believe.\n    }\n}\n\nclass Tool : ITool\n{\n    string _msg = "default msg";\n    public string Msg\n    {\n        get { return _msg; }\n        set { _msg = value; }\n    }\n\n    public void Use()\n    {\n        Console.WriteLine("Tool used! Msg: {0}", _msg);\n    }\n}\n\n\ninterface IRoom\n{\n    IEnumerable<IBox> Boxes { get; }\n}\n\nclass Room : IRoom\n{\n    public List<Box> BoxList = new List<Box>();\n\n    public IEnumerable<IBox> Boxes\n    {\n        get { return BoxList; } // and here...\n    }\n}	0
5989684	5989621	Select items based on popularity: Avoiding a glorified sort	void Main()\n{\n    var list = Enumerable.Range(1, 9)\n        .Select(i => new { V = i, P = i })\n        .ToArray();\n    list.Dump("list");\n\n    var sum =\n        (from element in list\n         select element.P).Sum();\n\n    Dictionary<int, int> selected = new Dictionary<int, int>();\n    foreach (var value in Enumerable.Range(0, sum))\n    {\n        var temp = value;\n        var v = 0;\n        foreach (var element in list)\n        {\n            if (temp < element.P)\n            {\n                v = element.V;\n                break;\n            }\n\n            temp -= element.P;\n        }\n        Debug.Assert(v > 0);\n        if (!selected.ContainsKey(v))\n            selected[v] = 1;\n        else\n            selected[v] += 1;\n    }\n\n    selected.Dump("how many times was each value selected?");\n}	0
1166390	1166352	How to find out TextWriter instance is a Console?	static void Main(string[] args)\n{\n     Console.WriteLine("Console.Out: {0}", IsConsoleOut(Console.Out));\n     Console.WriteLine("Other: {0}", IsConsoleOut(new StreamWriter(Stream.Null)));\n     Console.ReadLine();\n}\n\nprivate static bool IsConsoleOut(TextWriter textWriter)\n{\n     return object.ReferenceEquals(textWriter, Console.Out);\n}	0
49311	49302	How to Identify Postback event in Page_Load	public static Control GetPostBackControl(Page page)\n{\n    Control control = null;\n\n    string ctrlname = page.Request.Params.Get("__EVENTTARGET");\n    if (ctrlname != null && ctrlname != string.Empty)\n    {\n        control = page.FindControl(ctrlname);\n    }\n    else\n    {\n        foreach (string ctl in page.Request.Form)\n        {\n            Control c = page.FindControl(ctl);\n            if (c is System.Web.UI.WebControls.Button)\n            {\n                control = c;\n                break;\n            }\n        }\n    }\n    return control;\n}	0
13730295	13729820	Deserializing JSON with indexed array in c#	[JsonObject(MemberSerialization.OptIn)]\npublic class LinksJSON\n{\n    [JsonProperty]\n    public body body { get; set; }\n\n    [JsonProperty]\n    public string message { get; set; }\n\n    [JsonProperty]\n    public string error { get; set; }\n\n    [JsonProperty]\n    public bool status { get; set; }\n}\n\n[JsonObject(MemberSerialization.OptIn)]\npublic class body\n{\n    [JsonProperty]\n    public link link { get; set; }\n}\n\n[JsonObject(MemberSerialization.OptIn)]\npublic class link\n{\n    [JsonProperty]\n    public string[] linkurl { get; set; }\n}	0
1820407	1820372	Creating eventhandler at runtime in c#	private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    lock(resultArray)\n    resultArray.Add(e.Result);\n}	0
30191675	30191427	Displaying rows from table into datagridview with matched column value	DBConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FacesDatabase.mdb";\nDBConnection.Open();\nOleDbCommand command = new OleDbCommand();\ncommand.Connection = DBConnection;\nstring query = "Select FaceID,FaceName,RollNo,FaceImage from " + tableName + " where FaceName IN ('"+ string.Join("','",MatchName.ToArray())+ "')";\ncommand.CommandText = query;\nOleDbDataAdapter da=new OleDbDataAdapter(command);\nDataTable dt=new DataTable();\nda.Fill(dt);\ndataGridView1.DataSource=dt;\nDBConnection.Close();	0
16877504	16877465	MapRoute to remove action from url for single action	routes.MapRoute("project",\n       "project/{id}/{slug}",\n       new { controller = "project", action = "index", id = UrlParameter.Optional, slug = "" },\n       new { id = @"\d+"});	0
25989107	25987253	How to read from a GridView	txtOutputfield.Text = GridView1.Rows[i].Cells[j].Text;	0
24131626	24131482	Why does C# make the caller provide the actual parameter value for a method that has an optional parameter?	M("{0}", false);	0
25073234	25073113	How can I deserialize both responses using the same class?	public class Data\n{\n  [JsonProperty("messages")]\n  public List<...> Messages { get; set; }\n\n  [JsonProperty("m")]\n  public List<...> m_list { \n    get{ return Messages; }\n    set{ Messages = value; }\n  }\n\n  [JsonProperty("timestamp")]\n  public int Timestamp { get; set; }\n\n  ... \n\n  [JsonProperty("request")]\n  public int RequestsLeft { get; set; }\n\n  ...\n}	0
13234582	13234131	Do I need to call IsolatedStorageSettings.Save method in windows phone application?	IsolatedStorageSettings.Save	0
17914216	17914039	Regex with C#: How do I replace a string that matches a specific group	Regex regex = new Regex("^[^{}]*(\\{([^}]*)\\})[^{}]*$"); \nstring inputStr = "mystring{valueToRaplace}";\nstring replaceWithThis = "Replace with this";\n\n//change m.Groups[2] to whichever index you want to replace\nstring final = regex.Replace(inputStr, \n                    new MatchEvaluator(new Func<Match, string>(m => inputStr.Replace(m.Groups[2].Value, replaceWithThis))));	0
8778673	8778659	c# key press trigger button click	btnBrowserGo_Click(null, null);	0
19648601	19648532	How to get/access a text field value stored in a C# user Control	public MyControl : Control {\n    public string Result { get { return _txtField.Text; }}\n}	0
6407521	6407376	how to pass xml document as a string to a asp.net webservice	XmlDocument xml = new XmlDocument();\nxml.Load("file1.xml");\nstring xmlString = xml.OuterXml;	0
6344646	6344443	How to get the list of Regions in the RegionManager in PRISM?	public bool ContainsRegionWithName(string regionName)	0
10190692	10190316	How do you validate against each string in a list using Fluent Validation?	public class AccountsValidator : AbstractValidator<AccountViewModel>\n{\n    public AccountsValidator()\n    {\n        RuleFor(x => x.Accounts).SetCollectionValidator(\n            new AccountValidator("Accounts")\n        );\n    }\n}\n\npublic class AccountValidator : AbstractValidator<string> \n{\n    public AccountValidator(string collectionName)\n    {\n        RuleFor(x => x)\n            .NotEmpty()\n            .OverridePropertyName(collectionName);\n    }\n}	0
23655920	23655570	Get the values from CSV based on headers	var csv = new LinqToExcel.ExcelQueryFactory(csvFile);\n\nvar query =\n    from row in csv.Worksheet()\n    let Volume = row["volume"].Cast<double>()\n    where Volume == 0.1\n    select new\n    {\n        Price = row["Price"].Cast<int>(),\n        Volume,\n        Local = row["Local, Zones 1 & 2"].Cast<decimal>(),\n        Zone3 = row["Zone 3"].Cast<decimal>(),\n        //etc\n    };	0
10530752	10530677	C# Listview Cant Edit it with Button	frm.InitializeComponent();	0
19474443	19474418	Adding cells at specific index	e.Row.Cells.AddAt(2, cell1);	0
14443819	14442926	Access string value in separate DataList	protected void CheckBox1_CheckedChanged(Object sender, EventArgs e)\n{\n    CheckBox chk = (CheckBox)sender;\n    DataListItem item = (DataListItem)chk.NamingContainer;\n\n    TextBox txt = (TextBox)excludeTextBox.Items[item.ItemIndex].FindControl("myTextBox");\n\n    //--- do work here with txt\n}	0
19768641	19768519	c# Extract multiple numbers from a string	var result = new Regex(@"\d+").Matches(s)\n                              .Cast<Match>()\n                              .Select(m => Int32.Parse(m.Value))\n                              .ToArray();	0
10645782	10645754	How to make a richTextBox scroll?	richTextBox.SelectionStart = richTextBox.Text.Length;\nrichTextBox.ScrollToCaret();	0
27230225	27230119	Save data in a temporary .csv file to another csv file	File.Copy(tempFileName, saveFialog.FileName);	0
355513	355492	How to read TermainsServices IADsTSUserEx Property from LDAP in C#?	//user is a DirectoryEntry\nIADsTSUserEx adsiUser = (IADsTSUserEx)user.NativeObject;	0
31636019	31634588	Getting accumulated balance column in Crystal Reports	SELECT\n     s1.sum_id, s1.sum_date, s1.id, s1.sum_accname, s1.sum_description, s1.credit, s1.debit, s1.dep_date, s1.chq_due_date, s1.dp_custname,\n     SUM(ISNULL(s2.debit, 0) - ISNULL(s2.credit, 0)) As balance\nFROM\n     sum_balance s1 LEFT JOIN\n     sum_balance s2 ON s1.id >= s2.id \n                   AND s1.sum_id >= s2.sum_id \n                   AND s1.sum_date >= s2.sum_date\nWHERE\n    s1.sum_accname = {?ac_name}\nand\n    s1.sum_date >= {?fromDate}\nand\n    s1.sum_date <={?toDate}\nGROUP BY\n    s1.sum_id, s1.sum_date, s1.id, s1.sum_accname, s1.sum_description, s1.credit, s1.debit, s1.dep_date, s1.chq_due_date, s1.dp_custname	0
17723985	16520666	Android :-Consume a WCF web service with Post Method Params with json string request and Response	public static String getJsonData(String webServiceName,String parameter)\n{  \n    try  \n    {\n    String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";\n    HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));\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    final String responseText = EntityUtils.toString(entity);\n\n    string=responseText;\n    Log.i("Output", ""+responseText);\n      }\n      catch (Exception e) {\n    }\n\nreturn string;\n}	0
2882802	2882756	C# Access the Properties of a Generic Object	public int CountContacts<TModel>(TModel entity) where TModel : IContacts\n\n\ninterface IContacts\n{\n   IList<Contact> Contacts {get;} //list,Ilist,ienumerable\n}	0
13205489	13204377	Condition Statement in 1D array	NextMove = playerPositions[0] + DiceThrow(); \nfor (int i = 0; i < NumberOfPlayers; i++)\n{\n     while (RocketInSquare(NextMove))\n          NextMove++;\n\n     playerPositions[i] = NextMove;\n}	0
10809335	10809262	selenium locate two the same controls	"//a[@onclick='CloneDiv('#Div2');return false;']"	0
14809459	14809413	how to change default values of axis to user values	tChart1.Axes.Custom[0].SetMinMax(min, max);	0
8517431	8517348	Casting byte to DateTime causing error C#	DateTime issueDate = new DateTime(binfile.ReadInt64());	0
2096112	2096091	C# regex to match text string	^(?=.*\bone\b)(?=.*\btwo\b)	0
8245674	8245085	Use !Task.IsCompleted to show user current progress in GUI	private void Form1_Load(object sender, EventArgs e)\n{\n  CancellationTokenSource cts = new CancellationTokenSource();\n  Task worker = new Task(() => DoSomething());\n  Task ui_updater = new Task(() => UpdateGui(CancellationToken token));\n  worker.Start();\n  updater.Start();\n  // Worker task completed, cancel GUI updater.\n  worker.ContinueWith(task => cts.Cancel());\n}\nprivate void DoSomething()\n{\n // Do an awful lot of work here.\n}\nprivate void UpdateGui(CancellationToken token)\n{ \n  while (!token.IsCancellationRequested)\n {      \n   UpdateLabel();\n   Thread.Sleep(500);\n }\n}\nprivate void UpdateLabel()\n{\n  if (this.InvokeRequired)\n  {\n   this.BeginInvoke(new Action(() => UpdateLabel()), new object[] { });\n  }\n    else\n    {\n        label1.Text += ".";\n        if (label1.Text.Length >= 5)\n            label1.Text = ".";\n    }\n}	0
11579205	11579035	Remove all empty/unnecessary nodes from HTML	static List<string> _notToRemove;\n\nstatic void Main(string[] args)\n{\n    _notToRemove = new List<string>();\n    _notToRemove.Add("br");\n\n    HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml("<html><head></head><body><p>test</p><br><font><p><span></span></p></font></body></html>");\n    RemoveEmptyNodes(doc.DocumentNode);\n}\n\nstatic void RemoveEmptyNodes(HtmlNode containerNode)\n{\n    if (containerNode.Attributes.Count == 0 && !_notToRemove.Contains(containerNode.Name) && (containerNode.InnerText == null || containerNode.InnerText == string.Empty) )\n    {\n        containerNode.Remove();\n    }\n    else\n    {\n        for (int i = containerNode.ChildNodes.Count - 1; i >= 0; i-- )\n        {\n            RemoveEmptyNodes(containerNode.ChildNodes[i]);\n        }\n    }\n}	0
2143268	2143245	What's the best way to read a tab-delimited text file in C#	DataTable dt = new DataTable();\nusing (CsvReader csv = new CsvReader(new StreamReader(CSV_FULLNAME), false, '\t')) {\n    dt.Load(csv);\n}	0
4058848	2994148	A pattern for multiple LoadOperations using WCF RIA Services	context.Load(context.GetMyStatusValues1Query()).Completed += (s, e) =>\n  {\n    this.StatusValues1 = context.StatusValues1;\n  }\n\ncontext.Load(context.GetMyStatusValues2Query()).Completed += (s1, e1) =>\n  {\n    this.StatusValues1 = context.StatusValues2;\n  }	0
8886877	8886444	Efficient way to validate xml?	xreader.ReadStartElement("test"); // moves to document root, throws if it is not <test>\nxreader.Skip(); // throws if document is not well-formed, e.g. root has no closing tag.	0
17594798	17594544	C# Parsing JSON Array(HTTPrequest Response) to display	JObject obj = JObject.Parse(File.ReadAllText("1.json"));\nforeach (JToken o in obj["data"]["innerData"] as JArray)\n    Console.WriteLine(o["dataInfo"]);	0
20209266	20194040	How can I crop original image in a pictureBox that shows image in Stretch mode?	void pictureBox1_MouseUp(object sender, MouseEventArgs e)\n    {\n            xUp = e.X;\n            yUp = e.Y;\n\n            Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));\n\n            using (Pen pen = new Pen(Color.YellowGreen, 3))\n            {\n\n                pictureBox1.CreateGraphics().DrawRectangle(pen, rec);\n            }\n\n            xDown = xDown * pictureBox1.Image.Width / pictureBox1.Width;\n            yDown = yDown * pictureBox1.Image.Height / pictureBox1.Height;\n\n            xUp = xUp * pictureBox1.Image.Width / pictureBox1.Width;\n            yUp = yUp * pictureBox1.Image.Height / pictureBox1.Height;\n\n            rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));\n    }	0
2616498	2616487	String format options for int in .NET	3.ToString("00");	0
7836764	7832431	Implementing ExpandoObject in Scala	trait ExpandoObject extends Dynamic with mutable.Map[String, Any] {\n  lazy val fields = mutable.Map.empty[String, Any]\n  def -=(k: String): this.type = { fields -= k; this }\n  def +=(f: (String, Any)): this.type = { fields += f; this }\n  def iterator = fields.iterator\n  def get(k: String): Option[Any] = fields get k\n  def applyDynamic(message: String)(args: Any*): Any = {\n    this.getOrElse(message, new Assigner(this, message))\n  }\n}\n\nimplicit def anyToassigner(a: Any): Assigner = a match {\n  case x: Assigner => x\n  case _ => sys.error("Not an assigner.")\n}\n\nclass Assigner(ob: ExpandoObject, message: String) {\n  def :=(value: Any): Unit = ob += (message -> value)\n}	0
3077831	3077810	query a sub-collection of a collection with linq	from product in products\nwhere product.productid == 1\nfrom image in product.productimages\nwhere image.ismainimage\nselect image.imagename	0
6635114	6628704	Need help with converting SQL to LINQ - LEFT JOIN with Count	var results = Teachers\n              .Where(t => t.IsActive == true)\n              .Select(t => \n              {\n                  TeacherID  = t.TeacherID,\n                  FirstName = t.FirstName,\n                  LastName = t.LastName,\n                  Title = t.Title,\n                  Grade = t.Grade,\n                  Count = t.Students.Where(s => s.IsActive == true).Count()                 \n              });   \n results.ToList().Dump();	0
5218774	5218489	Check if a table exists within a database using LINQ	int result = entity.ExecuteStoreQuery<int>(@"\n    IF EXISTS (SELECT * FROM sys.tables WHERE name = 'TableName') \n        SELECT 1\n    ELSE\n        SELECT 0\n    ").SingleOrDefault();	0
26406387	26296851	How to Configure owin/Katana to listen on all host ip addresses	static string url = "http://*:9080";	0
7089427	7089331	how to bind imageurl of datalist to the image control which is out side of datalist on insert command	imgThumb.ImageUrl="~/Controls/ShowImage.ashx?FileName=" +ImgName;	0
23686439	23685184	Outlook folders are not being deleted	for (int i = olInboxFolder.Folders.Count; i >= 1; i--)	0
19016875	18992397	Store and retrieve the token received for the user after authorizing with facebook or twitter	manager.AddClaim(userId, new Claim("facebookAccessToken", fbAccessToken"));	0
16266040	16264915	Getting String between Div with the help of Class Name	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar innerText = doc.DocumentNode\n                   .SelectSingleNode("//div[@class='topheader-left common-txt']")\n                   .InnerText;\n\n\nDateTime time = DateTime.ParseExact(WebUtility.HtmlDecode(innerText).Split('|')[1].Trim(), \n                                    "hh:mm:ss tt",\n                                    CultureInfo.InvariantCulture);	0
219877	219808	Can I use LINQ to convert a List<MyObjectType> into a DataSet?	//extension method to convert my type to an object array.\npublic static object[] ToObjectArray(this MyClass theSource)\n{\n  object[] result = new object[3];\n  result[0] = theSource.FirstDouble;\n  result[1] = theSource.SecondDouble;\n  result[2] = theSource.TheDateTime;\n\n  return result;\n}\n\n\n//some time later, new up a dataTable, set it's columns, and then...\n\nDataTable myTable = new DataTable()\n\nDataColumn column1 = new DataColumn();\ncolumn1.DataType = GetType("System.Double");\ncolumn1.ColumnName = "FirstDouble";\nmyTable.Add(column1);\n\nDataColumn column2 = new DataColumn();\ncolumn2.DataType = GetType("System.Double");\ncolumn2.ColumnName = "SecondDouble";\nmyTable.Add(column2);\n\nDataColumn column3 = new DataColumn();\ncolumn3.DataType = GetType("System.DateTime");\ncolumn3.ColumnName = "TheDateTime";\nmyTable.Add(column3);\n\n// ... Each Element becomes an array, and then a row\nMyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());	0
17919679	17915861	How to use multiple passes in HLSL?	for (int i = 0; i < effect.Techniques.Count; i++)\n{\n    for (int j = 0; j < effect.Techniques[i].Passes.Count; j++)\n    {\n        effect.Techniques[i].Passes[j].Apply();\n        quad.RenderFullScreenQuad(effect); \n    }\n}	0
4905255	4905094	SelectedIndexChanged to filter ascx control	if(String.IsNullOrEmpty(Sesssion["iteration"])\n     iteration = "0";\nelse\n     iteration = Session["iteration"]	0
32669454	32669373	How would i count the frequency of a number on an List<double> in C#?	var dictionary= list.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());	0
12249177	12249051	Unique combinations of list	IEnumerable<T> remainingItems = list.Skip(startingElementIndex + 1);	0
4878680	4877632	Create all permutations of a string incrementally c#	public IEnumerable<char[]> AlphaCombinations(int length = 5, char startChar = 'A', char endChar = 'C')\n{\n    int numChars = endChar - startChar + 1;\n    var s = new String(startChar, length).ToCharArray();    \n    for (int it = 1; it <= Math.Pow(numChars, length); ++it) \n    {        \n        yield return s;\n\n        for (int ix = 0; ix < s.Length; ++ix) \n            if (ix == 0 || it % Math.Pow(numChars, ix) == 0) \n                s[s.Length - 1 - ix] = (char)(startChar + (s[s.Length - 1 - ix] - startChar + 1) % numChars);\n    }\n}\n\n...\n\nforeach (var s in AlphaCombinations(5))\n{\n    Console.WriteLine(s);\n}	0
32186306	32124575	Updating datatable to multiple tables in entity framework	class Program\n{\n    static void Main(string[] args)\n    {\n        SchoolDBEntities dataContext = new SchoolDBEntities();\n        //Create student object\n        Student student1 = new Student();\n        student1.StudentName = "Student 01";\n        //Create course objects\n        Cours mathCourse = new Cours();\n        mathCourse.CourseName = "Math";\n        Cours scienceCourse = new Cours();\n        scienceCourse.CourseName = "Science";\n        //Save courses to student 1\n        student1.Courses.Add(mathCourse);\n        student1.Courses.Add(scienceCourse);\n        //Save related data to database\n        //This will automatically populate join table\n        //between Students and Courses\n        dataContext.Students.Add(student1);\n        dataContext.SaveChanges();\n    }\n}	0
15769705	15769661	How do you uncheck one button when another is clicked?	If (Button1.Checked == true)\n{ \nButton2.Checked = false;\n}\nElse\n{\nButton2.Checked = true;\n}	0
16270562	16270447	Return a variable object (dynamic?)	public abstract object Parse(string s);	0
27796566	27796213	how to get ajax calendar extender position C#	CalendarExtender1.PopupPosition = AjaxControlToolkit.CalendarPosition.Right;	0
19283642	19283138	How to add new Node to xml file	string movieListXML = @"c:\test\movies.xml";\n        XDocument doc = XDocument.Load(movieListXML);\n        foreach (XElement movie in doc.Root.Descendants("Movie"))\n        {\n            movie.Add(new XElement("Time", "theTime"));\n        }\n        doc.Save(movieListXML);	0
13246385	13246313	Format a String literal	string myString = "wAr aNd pEaCe";        \nTextInfo myTI = new CultureInfo("en-US", false).TextInfo;\nConsole.WriteLine("\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase(myString));	0
7099305	7095668	Need help inserting commas after each character in specific part of string	using System;\n\nclass ReplaceAContentsWithCommaSeparatedChars\n{\n    static readonly string acroStartTag = "<a>";\n    static readonly string acroEndTag = "</a>";\n\n    static void Main(string[] args)\n    {\n        string s = "Alpha <a>Beta</a> Gamma <a>Delta</a>";\n        while (true)\n        {\n            int start = s.IndexOf(acroStartTag);\n            if (start < 0)\n                break;\n\n            int end = s.IndexOf(acroEndTag, start + acroStartTag.Length);\n            if (end < 0)\n                end = s.Length;\n\n            string contents = s.Substring(start + acroStartTag.Length, end - start - acroStartTag.Length);\n            string[] chars = Array.ConvertAll<char, string>(contents.ToCharArray(), c => c.ToString());\n            s = s.Substring(0, start)\n                + string.Join(",", chars)\n                + s.Substring(end + acroEndTag.Length);\n        }\n\n        Console.WriteLine(s);\n    }\n}	0
9653839	9653405	How to fix this code for printing this GridView control?	ScriptManager.RegisterStartupScript(Gridview2, Gridview2.GetType(), "onclick", "window.open('Print.aspx','PrintMe','height=400px,width=800px,scrollbars=1');", true);	0
11988668	11988396	How can I get a list of items that is part of an object?	var db = new Context();\nvar myClass = db.SomeClass.Include("SomeObject").Single(class => class.Id == 1);	0
34010667	34010449	Creating GeoJSON output from Well Known Text with C#	public class GeometryDto\n    {\n        public string Type { get; set; }\n\n        public double[,] coordinates { get; set; }            \n\n    }\n\n    class Program\n    {\n        static void Main()\n        {\n            var obj = new GeometryDto\n            {\n                Type = "Polygon",\n                coordinates = new double[,] { { 319686.3666000003, 7363726.795 }, { 319747.0519000003, 7363778.9233 }, { 5.3434444, 6.423443 }, { 7.2343424234, 8.23424324 } }                     \n            };\n            var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);\n            Console.WriteLine(json);\n            Console.ReadKey();\n        }\n    }	0
5537348	5537286	How to get CPU usage for more than 2 cores?	PerformanceCounter pc0 = new PerformanceCounter("Processor", "% Processor Time", "0");\nPerformanceCounter pc1 = new PerformanceCounter("Processor", "% Processor Time", "1");\nPerformanceCounter pc2 = new PerformanceCounter("Processor", "% Processor Time", "2");\nPerformanceCounter pc3 = new PerformanceCounter("Processor", "% Processor Time", "3");	0
9311624	9311478	Marshalling stucts with bit-fields in C#	[StructLayout(LayoutKind.Sequential)]\npublic struct Rgb16 {\n    private readonly UInt16 raw;\n    public byte R{get{return (byte)((raw>>0)&0x1F);}}\n    public byte G{get{return (byte)((raw>>5)&0x3F);}}\n    public byte B{get{return (byte)((raw>>11)&0x1F);}}\n\n    public Rgb16(byte r, byte g, byte b)\n    {\n      Contract.Requires(r<0x20);\n      Contract.Requires(g<0x40);\n      Contract.Requires(b<0x20);\n      raw=r|g<<5|b<<11;\n    }\n}	0
3624989	3624865	react in controller, which and if action link is clicked in view	[HttpPost]\n[ValidateInput(false)]\npublic ActionResult ResendPassword(EditUserModel model)\n{\n    try\n    {\n        Admin admin = new Admin();\n        admin.SendForgottenPasswordToUser(model.UserName);\n        return View("EditUser", model);\n    }\n    catch (Exception ex)\n    {\n        // Error handling here.\n    }\n}	0
22498169	22497715	How to compare the whole array for having same value	if (temp.All(s => s == ""))\n{\n}	0
20195769	20195292	Download file from sql server using c#	using (SqlCommand cmd = new SqlCommand("select ContentType from UploadFile WHERE Id = 1"))\n{\n    con.Open();\n    SqlDataReader obj = cmd.ExecuteReader();\n    byte[] bytes = (byte [])obj.GetValue(0);\n}	0
7795271	7795161	c# how to String.Format decimal with unlimited decimal places?	string.Format("{0:#,#.#############################}", decimalValue)	0
26032406	26031853	How to make textbox readonly in a gridview?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n      if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)\n      {\n       //on you condition\n        TextBox txt = (TextBox)e.Row.FindControl("ControlID");\n        if(txt !=null)\n        {\n          txt.Attributes.Add("readonly", "readonly");           \n         // txt.Attributes.Remove("readonly"); To remove readonly attribute\n        }\n      }\n    }	0
7373589	7373554	How to be able to write to a textbox side-by-side names of the items which are find inside Listbox in C#?	foreach (string s in Listbox.SelectedItems) \n{\n   TextBox.Text += s + ", ";   \n}	0
842316	842298	Working with a hashtable of unknown but similar objects (C#)	IMyInterface a = new MyObject();\n\n// with Hashtable\nHashtable ht = new Hashtable();\nht.Add("key", a);\nIMyInterface b = (IMyInterface)ht["key"];\n\n// with Dictionary\nvar dic = new Dictionary<string, IMyInterface>();\ndic.Add("key", a);\n // no cast required, value objects are of type IMyInterface :\nIMyInterface c = dic["key"];	0
24277465	24125340	Using two get and set properties for the same object	public List <Deduction > DeductionDetails\n{\n    get { return (List<Deduction>)dgEmployeeDeductions.DataSource; }\n    set { dgEmployeeDeductions.DataSource = value; }\n}	0
23219204	23218342	Populate 2Dimensional Array	// suppose the definition of array 'coins' is somewhere else\n\nint counter = 0;\nint coin;\n\nint[] change_given = new int[coins.Length]; // will be the same length as 'coins'\n\nfor (int i = 0; i < coins.Length; i++)\n{\n    coin = Math.Min(quantities[i], (int)(change / coins[i]));\n    counter += coin;\n    change -= coin * coins[i];\n    // want to store [coins[i], coin] in an 2Darray\n    change_given[i] = coin;\n}\n\nfor (int j = 0; j < change_given.Length; j++)\n{\n     Console.WriteLine("Number of coins of type {0} returned: {1}", j, change_given[j]);\n}	0
24286997	24283030	DataGrid CustomColumn Binding	protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)\n{\n    var dataGridBoundColumn = cell.Column as DataGridBoundColumn;\n    var datePicker = new DatePicker { Width = 50, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };\n    var cellContent = cell.Content as TextBlock;\n\n    if (dataGridBoundColumn != null)\n    {\n        var bindingExpression = (cell.Content as TextBlock) != null ? BindingOperations.GetBindingExpression(cellContent, TextBlock.TextProperty) : null;\n\n        if (bindingExpression != null)\n        {\n            var newBindning = new Binding(bindingExpression.ParentBinding.Path.Path)\n                {\n                    UpdateSourceTrigger = bindingExpression.ParentBinding.UpdateSourceTrigger, Mode = bindingExpression.ParentBinding.Mode\n                };\n\n            datePicker.SetBinding(DatePicker.TextProperty, newBindning);\n        }\n    }\n\n    return datePicker;\n}	0
23744902	23744842	First button click to start timer, second to stop	if (timer1.Enabled) {\n  timer1.Stop();\n} else {\n  timer1.Start();\n}	0
29161465	29161215	Serial Port Data Received only working when breakpoint set C#	public void comport_DataReceived2(object sender, SerialDataReceivedEventArgs e)\n{\n    var bytes = comport.BytesToRead;\n    if( bytes > 30 )\n    {\n         var test2 = comport.ReadExisting();\n        // additional testing code as required...\n    }\n}	0
22426446	22426390	Disable selection of controls by arrow keys in a form	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    if (!msg.HWnd.Equals(this.Handle) && \n        (keyData == Keys.Left || keyData == Keys.Right ||\n        keyData == Keys.Up || keyData == Keys.Down))\n        return true;\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
10182434	10182327	Lightswitch lambda use	partial void OpenPositions_Compute(ref int result)\n{\n    result = this.DataWorkspace.ApplicationData.Positions\n        .Count(p => p.IsPositionOpen && position.Client.Id == this.Id);\n}	0
21460043	21454252	How to cleanup resources in a DLL when Powershell ISE exits - like New-PSSession and New-PSJob	GC.SuppressFinalize(this);	0
26530938	26529586	Bind object properties to a datagrid in WPF	[Browsable(false)]	0
18397053	18396656	Getting name(s) of FOLDER containing a specific SUBSTRING from the C:Temp directory in C#	var pattern = "*" + txtNameSubstring.Text + "*";\nvar directories = System.IO.Directory.GetDirectories("C:\\Temp", pattern);	0
724905	724862	Converting from hex to string	static void Main()\n{\n    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");\n    string s = Encoding.ASCII.GetString(data); // GatewayServer\n}\npublic static byte[] FromHex(string hex)\n{\n    hex = hex.Replace("-", "");\n    byte[] raw = new byte[hex.Length / 2];\n    for (int i = 0; i < raw.Length; i++)\n    {\n        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);\n    }\n    return raw;\n}	0
4747227	4747148	Convert calendar-week to Date	string[] spl = input.ToLower().Split("w");\nint year = int.Parse(spl[1]);\nint week = int.Parse(spl[0]);	0
19275990	19275581	Filling a textbox with limited size	bool flag = false;\nint count = line.Length;\n\ndo\n{\n    try\n    {\n       txt.Text = line.SubString(0, count);\n       flag = true;\n    }\n    catch(TheException)\n    {\n       count--;\n    }\n}\nwhile(!flag);	0
22865338	22823860	Validation in Update Panel within a Repeater	if (String.IsNullOrEmpty(tbReplyName.Text.ToString().Trim()))\n            strValidationMessage = "<li>Please enter your name.</li>";\n\nLiteral ltrErrorMessage = (Literal)e.Item.FindControl("ltrErrorMessage");\n            ltrErrorMessage.Text = strValidationMessage;	0
4356567	4356449	Working with BigIntegers in C#	var dividend = BigInteger.Parse("25");\n\nBigInteger remainder;\nvar quotient = BigInteger.DivRem(dividend, 2, out remainder);\nif (!remainder.IsZero) {\n    throw new Exception("Division resulted in remainder of " + remainder + "!");\n}	0
33011257	33010886	How to ensure that specific string can be converted to SolidBrush in WPF?	if(converter.IsValid("red")\n{\n     borderBrush = converter.ConverterFromString("red") as SolidColorBrush;\n}	0
2703651	2703623	Interop Excel method LinEst failing with DISP_E_TYPEMISMATCH	MyExcel.Application xl = new MyExcel.Application();\n    MyExcel.WorksheetFunction wsf = xl.WorksheetFunction;\n    List<int> x = new List<int> { 1, 2, 3, 4 };\n    List<int> y = new List<int> { 11, 12, 45, 42 };\n    //object o = wsf.LinEst(x, y, true, true);\n    object o = wsf.LinEst(y.ToArray(), x.ToArray(), false, true);	0
24047676	24047506	Reactive Extensions - Equivalent LINQ expression as fluent expression	return quotes\n    .GroupBy(q => q.Symbol)\n    .SelectMany(g => g.Buffer(2, 1).Select(b => new PriceChange {\n        Symbol = b[0].Symbol,\n        Change = (b[1].Price - b[0].Price) / b[0].Price\n     })\n    );	0
20768043	20767989	LINQ query in lambda syntax	var palindromes = Enumerable.Range(100, 9900)\n    .SelectMany(\n        i => Enumerable.Range(100, 9900),\n        (i, j) => i * j)\n    .Where(p => /* where condition */)\n    .OrderBy(p => p);	0
25776879	25776851	Combine two lists with linq	myIds.Union(yourIds)\n.Select(x => new \n             { \n                 Id = x,\n                 Mine = myIds.Contains(x), \n                 Yours = yourIds.Contains(x)\n             });	0
2161743	2161728	C# TreeNode control, how do I run a program when node is clicked?	private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n{\n    // Starts Internet Explorer\n    Process.Start("iexplore.exe");\n\n    // Starts the application with the same name as the TreeNode clicked\n    Process.Start(e.Node.Text);\n}	0
29843574	29838685	how to load a table query by reference table in EF6	var cats = from category in _context.Categories
\n                           from item in _context.DataItems.Where(i => i.CategoryId == category.Id && i.Owner == id).DefaultIfEmpty()
\n                           select new { Category = category, Items = item };	0
28908832	28906895	Determining uv coords for dynamically generated mesh in unity	u = (az - range.West) / (range.East - range.West);\nv = (inc - range.South) / (range.North - range.South);	0
12989227	12989192	Custom setter for C# model	public class Administrator\n{\n    public int ID { get; set; }\n\n    [Required]\n    public string Username { get; set; }\n\n    private string _password;\n\n    [Required]\n    public string Password\n    {\n        get\n        {\n            return this._password;\n        }\n\n        set\n        {  \n             _password = Infrastructure.Encryption.SHA256(value);                \n        }\n    }\n}	0
34205114	34204896	Universal Windows App get slected item name	var item = ((ListBoxItem)MenuBox.SelectedItem).Name;	0
8378872	8378821	c# string[] to jquery string list?	var list = @Html.Raw(ViewData["List"]);	0
5790283	5790155	Add an event to a object & handle it	using System;\n\nnamespace CustomEvents\n{\n  public class Car\n  {\n    public delegate void OwnerChangedEventHandler(string newOwner);\n    public event OwnerChangedEventHandler OwnerChanged;\n\n    private string make;\n    private string model;\n    private int year;\n    private string owner;\n\n    public string CarMake\n    {\n      get { return this.make; }\n      set { this.make = value; }\n    }\n\n    public string CarModel\n    {\n      get { return this.model; }\n      set { this.model = value; }\n    }\n\n    public int CarYear\n    {\n      get { return this.year; }\n      set { this.year = value; }\n    }\n\n    public string CarOwner\n    {\n      get { return this.owner; }\n      set\n      {\n        this.owner = value;\n        // To avoid race condition\n        var ownerchanged = this.OwnerChanged;\n        if (ownerchanged != null)\n          ownerchanged(value);\n      }\n    }\n\n    public Car()\n    {\n    }\n  }\n}	0
31240507	31240248	How Can I Divide Two Field In SharePoint With Visual Studio C#	int avgSalary = Convert.ToInt32(newDef["MaxSalary"]) / Convert.ToInt32(newDef["MinSalary"]);\nnewDef["AvgSalary"] = avgSalary.ToString();	0
2548033	2548018	Convert Byte Array to Bit Array?	BitArray bits = new BitArray(arrayOfBytes);	0
26629009	26627886	Not able to set cookie from action	Domain = null	0
16706576	16702130	How to make a search functionality that contains more than one word in ASP MVC4?	var data1 = (from con in dbData.tblPresenters\n                             let FillName = con.PresenterFirstName + " " + con.PresenterLastName\n                             where FillName.ToLower().Trim().Contains(txtName.Text.Trim().ToLower()) \n                             select new\n                             {                                    \n                                 FirstName = con.PresenterFirstName,\n                                 LastName = con.PresenterLastName,\n\n                             }).ToList();	0
32400239	32397921	Add a registry entry which contains binary data	static void Main(string[] args)\n    {\n        string machineName = Environment.MachineName;\n        createReg(machineName);\n    }\n    public static void createReg(string machineName)\n    {\n        RegistryKey rk = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);\n        var registryKey = getInstalledSoftware(rk);\n    }\n    public static object getInstalledSoftware(RegistryKey rkey)\n    {\n        string keyname = @"SYSTEM\CurrentControlSet\services\HTTP\Parameters\SslBindingInfo\0.0.0.0:7800";\n        RegistryKey key = Registry.LocalMachine.OpenSubKey(keyname);\n        object val = key.GetValue("AppId");\n        return val;\n    }	0
18889617	18889391	Concatinating values of a matching string in an arrray	var results = \n    array1\n        .Zip(array2, (x1, x2) => new { x1, x2 })\n        .ToLookup(x => x.x1, x => x.x2)\n        .Select(x => new { x.Key, Value = String.Join(" ", x), });	0
15388144	15388072	How to add extension methods to Enums	enum Duration { Day, Week, Month };\n\nstatic class DurationExtensions {\n  public static DateTime From(this Duration duration, DateTime dateTime) {\n    switch duration {\n      case Day:   return dateTime.AddDays(1);\n      case Week:  return dateTime.AddDays(7);\n      case Month: return dateTime.AddMonths(1);\n      default:    throw new ArgumentOutOfRangeException("duration")\n    }\n  }\n}	0
11909369	11909313	Using structs in C# to read data	public stuct MyStruct\n{\n    public int Age { get; private set; }\n    public int Height { get; private set; }\n    private char[] name;\n    public char[] Name \n    {\n        get { return name; }\n        set\n        {\n            if (value.Length > 12) throw new Exception("Max length is 12");\n            name = value;\n        }\n    }\n    public MyStruct(int age, int height, char[] name)\n    {\n    }\n}	0
19783988	19764684	UnauthorizedAccessException occurring when trying to add directories to TreeView	public static void SetAccessRule(string directory)\n    {\n        System.Security.AccessControl.DirectorySecurity Security = System.IO.Directory.GetAccessControl(directory);\n        FileSystemAccessRule accountAllow = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);\n        Security.AddAccessRule(accountAllow);\n    }	0
8731365	8730497	How to deserialize json string to a domain object?	using (var reader = new MemoryStream(Encoding.Unicode.GetBytes("YourStringValue")))\n{\n     var ser = new DataContractJsonSerializer(typeof(Deal));\n     return (Deal)ser.ReadObject(reader);\n}	0
32088178	32087806	Get value from XML file using C#	...\n        xmlnode = xmldoc.GetElementsByTagName("SSIS:Parameters");\n\n        for (i = 0; i <= xmlnode.Count - 1; i++)\n        {\n           var val = xmlnode[i].FirstChild.Attributes["SSIS:Name"].Value;\n           Console.WriteLine(val);\n        }\n        Console.ReadLine();\n        ...	0
7915769	7915657	Where inside a where in linq	where new List<int> { val0, val1, val2 }.Distinct().Count() == 3\n   && (val0 + val1 + val2 == 2)	0
13884007	13883943	Create An Array of Array in c#	IList<TestList> testList;\n\npublic class TestList\n{\n    public int x{ get; set; }\n    public string Name { get; set; }\n    public int y{ get; set; }\n}\n\nvar newList = testList.Select(t => new object[] { t.x, t.Name, t.y});\nvar myArrayOfArrays = newList.ToArray();	0
28692353	28691679	How to give custom labels to x axis of chart control?	string[] monthNames = { "100", "75" , "50" , "25" ,"0"};\nint startOffset = -2;\nint endOffset = 2;\nforeach (string monthName in monthNames)\n{\n CustomLabel monthLabel = new CustomLabel(startOffset, endOffset, monthName, 0, LabelMarkStyle.None);                        \n chart1.ChartAreas[0].AxisX.CustomLabels.Add(monthLabel);\n startOffset = startOffset + 25;\n endOffset = endOffset + 25;\n}	0
31256726	31256617	How do I launch my app from a bash script passing in a parameter?	public static void Main(string[] args)\n{\n    // args are your command-line arguments\n    // here we check that there was one argument provided, and show a message if there wasn't\n    if (args.Length != 1)\n    {\n        Console.WriteLine("Usage: sync.exe [profile-name]");\n        System.Exit(1);\n    }\n    string profileName = args[0];\n    // do stuff with the profile name\n}	0
12304252	12303735	In C#, how do I bind an array to DataGridView such that the values in the array are displayed?	string FilePath = @"c:\data.txt";\nvar arrData = File.ReadLines(FilePath).Select(line => \n                                              line.Split('\t')).ToArray();\n\nvar query = from x in arrData\n            select new { FirstName = x[0], LastName = x[1], Age = x[2] };\n\ndataGridView1.DataSource = query.ToList();	0
15327796	15327752	Clean way to check for Null in Lambda Expressions	var result = Store.FirstOrDefault(x => x.Products.Coupon != null && x.Products.Coupon.Any() && x.Products.Coupon[0] == 100);	0
10213098	10212793	Change the Column Name in Datatable in C#	DataTable table = new DataTable();\ntable.Columns.Add("ItemNo", typeof(string));\ntable.Columns.Add("ItemName", typeof(string));\nDataRow dr = table.NewRow();\ndr[0] = "1";\ndr[1] = "Name1";\ntable.Rows.Add(dr);\ndr = table.NewRow();\ndr[0] = "1";\ndr[1] = "Name1";\ntable.Rows.Add(dr);\ntable.Columns[0].ColumnName = "Item #";	0
13348533	13348475	Change the attribute value of an XML Node	if (ownerID != null)	0
22104587	22103919	Get SqlDataReader instead of RecordSet in Execute SQL task	List<MyClass> MyClasses = new List<MyClass>();\n\nString strSQL = "select * from Table01";\nSqlCommand cmd = new SqlCommand { Connection = Cn, CommandText = strSQL };\ntry\n{\n    Cn.Open();\n    SqlDataReader sdr = cmd.ExecuteReader();\n    while (sdr.Read())\n    {\n        MyClasses.Add(new MyClass(sdr.GetValue(0));\n    }\n    sdr.close();       \n}\ncatch (Exception Ex) {}\nfinally \n{\n    Cn.Close();\n}	0
15243100	15242923	How to Bind a column of GridView to a DropDownList?	this.GridView1.Rows[i].Cells[0].Value = teachername;	0
5394176	5393766	How to start an incremental crawl of a search scope from code in SharePoint?	SearchServiceApplicationProxy proxy = SearchServiceApplicationProxy.GetProxy(SPServiceContext.Current);\nGuid appId = ssap.GetSearchServiceApplicationInfo().SearchServiceApplicationId;\nSearchServiceApplication app = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(appId);\nContent content = new Content(app)\n\nContentSource cs = content.ContentSources["<content source name>"];\ncs.StartIncrementalCrawl();\n// check on cs.CrawlStatus if finished	0
1358997	1358976	Moving entry point to DLL in a WinForm app	// In DLL\npublic static class ApplicationStarter\n{\n     public static void Main()\n     {\n          // Add logic here.\n     }\n}\n\n// In program:\n{\n     [STAThread]\n     public static void Main()\n     {\n          ApplicationStarter.Main();\n     }\n}	0
17633444	17633413	Canvas with shape on it - MouseUp events fire on both of them when I click shape	void Ellipse_MouseUp(object sender, MouseButtonEventArgs e)\n{\n    e.Handled = True;\n    MessageBox.Show("Ellipse click");\n}	0
19408316	19408090	General method to select first row from every group in DataTable, give a List of grouping column	string newcolExpression = @"' ' + " + string.Join(" + ",GroupByColumns) ; // prepend a space to ensure string concatenation\n// e.g. "' ' + ID1 + ID2"\n\ndt.Columns.Add("GroupBy",typeof(string),newcolExpression);\n\ndt = dt.AsEnumerable()\n       .GroupBy(r => r["GroupBy"])\n       .Select(g => g.OrderBy(r => r["PK"]).First())\n       .CopyToDataTable();\n\ndt.Columns.Remove("GroupBy");	0
13276695	13276576	How do I get the contents of a web page that is behind a log-in page?	string page = client.DownloadData(url);	0
14394711	14394030	Moving items in listbox to its original position	InstitutionLst.Insert(0, Item);	0
9517474	9508173	How to concatenate multiple FlowDocuments together into 1 FlowDocument	'targetDocument is flowdocument that will be aggregate of both\n'insertDocument contains document content you want to insert into target\n Dim insertBlocks As List(Of Block) = insertDocument.Blocks.ToList()\n targetDocument.Blocks.AddRange(insertBlocks)	0
24423786	24414219	How to view arp -a "ProcessStartInfo.RedirectStandardOutput" into DATAGRIDVIEW	// add columns to your grid (could also be done in designer)\ndataGridView1.Columns.AddRange(\n    new DataGridViewTextBoxColumn(),\n    new DataGridViewTextBoxColumn(), \n    new DataGridViewTextBoxColumn());\n\nwhile (!process.StandardOutput.EndOfStream)\n{\n    string[] values = process.StandardOutput.ReadLine().Split(new char[0], StringSplitOptions.RemoveEmptyEntries);\n    if (values.Length == 3) dataGridView1.Rows.Add(values);\n}	0
21231975	21176810	Locate control in asp:listview when I have the clientid for the control?	private Control RecursiveFindControl(Control aRootControl, string aFindControlClientId)\n    {\n        if (aRootControl.ClientID == aFindControlClientId)\n\n            return aRootControl;\n\n        foreach (Control ctl in aRootControl.Controls)\n        {\n            Control foundControl = RecursiveFindControl(ctl, aFindControlClientId);\n\n            if (foundControl != null)\n                return foundControl;\n        }\n\n        return null;\n    }	0
19106909	19106748	Identify large differences within a sorted list	List<double> doubleList = new List<double>{\n    0.0015,\n    0.0016,\n    0.0017,\n    0.0019,\n    0.0021,\n    0.0022,\n    0.0029,\n    0.0030,\n    0.0033,\n    0.0036\n};\n\ndouble averageDistance = 0.0;\ndouble totals = 0.0;\ndouble distance = 0.0;\n\nfor (int x = 0; x < (doubleList.Count - 1); x++)\n{\n    distance = doubleList[x] - doubleList[x + 1];\n    totals += Math.Abs(distance);\n}\n\naverageDistance = totals / doubleList.Count;\n\n// check to see if any distance between numbers is more than the average in the list\nfor (int x = 0; x < (doubleList.Count - 1); x++)\n{\n    distance = doubleList[x] - doubleList[x + 1];\n    if (distance > averageDistance)\n    {\n        // this is where you have a gap that you want to do some split (etc)\n    }\n}	0
24737049	24736656	Delete words from file	class Program\n{\n    static void Main(string[] args)\n    {\n        var allLines = File.ReadLines("file.txt");\n       List<string> list =  new List<string>();\n        foreach (var line in allLines)\n        {\n\n            if (line.Contains("n/a"))\n            {\n                var newLine = line.Replace(",n/a,", string.Empty); \n                list.Add(newLine);\n                 list.Add(line.PadLeft(line.Length+2,'/'));\n            }\n            else\n            {\n                list.Add(line);\n            }\n\n        }\n        File.WriteAllLines("newFile.txt",list);\n    }\n}	0
19169263	19169195	Regular expression to match <font> attribute	string pattern = "<font[^>]*>";\n                  ^         ^\n            Notice the removed / from the expression	0
26139977	26139728	How to return to Index of Controller after delete method invoked	public ActionResult Delete(int id = 0)\n    {\n        Entry entry = _db.Entries.Single(r => r.Id == id);\n        if (entry == null)\n        {\n            return HttpNotFound();\n        }\n        return View(entry);\n    }\n\n    //\n    // POST: /Restaurant/Delete/5\n\n    [HttpPost, ActionName("Delete")]\n    public ActionResult DeleteConfirmed(int id)\n    {\n        var entryToDelete = _db.Entries.Single(r => r.Id == id);\n\n        _db.Entries.Remove(entryToDelete);\n\n        _db.SaveChanges();\n\n        return RedirectToAction("Index",new { id =  entryToDelete.CategoryId });\n    }	0
13812559	13811601	How can I modify a previously configured StructureMap configuration?	ObjectFactory.Model.EjectAndRemoveTypes(match\n    => match != null && match.GetInterfaces().Any(i\n        => i.Name.Contains("IValidationRule")));	0
14558695	14558628	Download current page HTML with out creating a new session	using (WebClient client = new WebClient())\n{\n    client.Headers[HttpRequestHeader.Cookie] = \n        System.Web.HttpContext.Current.Request.Headers["Cookie"];\n    string htmlCode = client.DownloadString("http://aksphases:200/lynliste.aspx");  \n}	0
15389103	15388956	Can't access MYSQL server from c# forms application - error in connection string	string connStr = "server=localhost;user=root;database=world;port=3306;password=******;";\n MySqlConnection conn = new MySqlConnection(connStr);	0
1565538	1565504	Most succinct way to convert ListBox.items to a generic list	var myOtherList = lbMyListBox.Items.Cast<String>().ToList();	0
18605536	18605359	How to get the Filename(s) Uploaded using the Ajax Uploader	if (Request.Files.Count > 0)\n{\n HttpPostedFile ObjFile = Request.Files[0];\n string filename = strTick + System.IO.Path.GetFileNameWithoutExtension(ObjFile.FileName);\n string originalName = ObjFile.FileName;\n}	0
13677095	13677060	Getting Color Values C#	List<Color> lc = new List<Color>();\nColor c = new Color();\nc.R = 0xFF;\nc.G = 0x00;\nc.B = 0x00;\nlc.Add(c);\n...\n...\nlc.Sort((c1, c2) => c1.ToArgb().CompareTo(c2.ToArgb));	0
7283352	7283185	How to find maximum occured word from text?	var result =\n    Regex.Matches(s, @"\b\w+\b").OfType<Match>()\n        .GroupBy(k => k.Value, (g, u) => new { Word = g, Count = u.Count() })\n        .OrderBy(n => n.Count)\n        .Take(10);	0
13731078	11770821	Save as PDF using c# and Interop not saving embedded pdf in a word document	d.ExportAsFixedFormat(filename.ToString(), WdExportFormat.wdExportFormatPDF,false,WdExportOptimizeFor.wdExportOptimizeForOnScreen,\n                    WdExportRange.wdExportAllDocument,1,1,WdExportItem.wdExportDocumentContent,true,true,\n                    WdExportCreateBookmarks.wdExportCreateHeadingBookmarks,true,true,false,ref oMissing);	0
7148408	7148302	how to optimize this task?	try\n{\nthis.SuspendLayout();\n}\nfinally\n{\nthis.ResumeLayout();\n}	0
10794591	10794525	create an xml document in c# and store that file into bin folder of the project	string path =  Path.GetDirectoryName(Application.ExecutablePath) ;\nchangesetDB .Save( Path.Combine( path , "data.xml"));	0
8001258	7771320	Fill struct from IntPtr received in lParam property of Window Message going across process boundaries in C#	GCHandle openCompleteResultGCH = GCHandle.Alloc(m.LParam);	0
15788097	15788055	How to create persistent unique MD5 hash	private const string _myGUID = "{C05ACA39-C810-4DD1-B138-41603713DD8A}";\n    public static string ConvertStringtoMD5(string strword)\n    {\n        MD5 md5 = MD5.Create();\n        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(_myGUID + strword);\n        byte[] hash = md5.ComputeHash(inputBytes);\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < hash.Length; i++)\n        {\n            sb.Append(hash[i].ToString("x2"));\n        }\n        return sb.ToString();\n    }	0
8974394	8974254	Convert a byte array into an image w/o FromStream (for Mono)	Image.FromStream	0
21075326	21074696	DataGridView - update value dynamically	private void dgvNews_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n{\n        var databaseRecordId = e.RowIndex;\n        dgvNews.Rows[e.RowIndex].Cells[0].Value = "AAAAAA";\n}	0
1293774	1293721	Searching for strings in big binary files	120, 2000, ...	0
6423771	6423718	Generics design pattern for holding a list of varying types	// or maybe interface IColumn instead, depending on your needs\nclass Column\n{\n    // any non-generic stuff common to all columns\n}\n\nclass Column<T> : Column where T : IComparable, IConvertible\n{\n    // any generic stuff specific to Column<T>\n}\n\nclass Table\n{\n    private List<Column> _columns;\n}	0
10121831	10121730	How to perform a registration up to verification of account in mvc?	public ActionResult Verify(string verificationid, string email)\n{\n    //// call the service from here and validate \n    //// if valid then return View();\n}	0
17611970	17611696	WPF two way data bind to custom data type in observable collection	private double _value;\n    public double Value\n    {\n        [DebuggerStepThrough]\n        get { return _value; }\n        [DebuggerStepThrough]\n        set\n        {\n            if (Math.Abs(value - _value) > Double.Epsilon)\n            {\n                _value = value;\n                OnPropertyChanged("Value");\n            }\n        }\n    }	0
6260788	6260614	Joining items in a single List<>	var result = allEvents\n   .GroupBy(e => e.StartDate)\n   .Select(gp => new EntertainmentEvent\n                        {\n                          Title = string.Join(", ", gp), \n                          StartDate = gp.Key \n                        });	0
23649075	23648897	Create buttons dynamically in asp.net page and fire click event to all buttons	button.ID = "raid" + i;\nbutton.Text = category[i];\nbutton.Click +=button_Click;\nbutton.CommandArgument +=category[i];\n\n\nprivate void button_Click(object sender, EventArgs e)\n{\n    Button btn = (Button)sender;\n    string category = btn.CommandArgument;\n}	0
13631672	13631356	how to add items into listview dynamically in winforms	private void btnAdd_Click(object sender, EventArgs e) {\n    listView1.Items.Add(\n        new ListViewItem(new[] { \n            txtFirmName.Text, txtAccountNo.Text, txtAmount.Text }));\n}	0
15213434	15213401	Extracting data from text file	using (StreamReader sr = new StreamReader(path)) \n        {\n            while (sr.Peek() >= 0) \n            {\n                var keyPair =  sr.ReadLine();\n                var key = keyPair.Split('=')[0];\n                var value = keyPair.Split('=')[1];\n            }\n        }	0
14406846	14406738	Convert KeyValuePair<int,string> to an int[] array and string[] array	int[] keys = partitioned.Select(pairs => pairs.Select(pair => pair.Key).ToArray())\n    .ToArray();\nstring[] values = partitioned.Select(pairs => pairs.Select(pair => pair.Value).ToArray())\n    .ToArray();	0
10423682	10423221	How to create a lambda expression that can handle or cast unknown types?	public static class PropertyInfoExtensions\n{\n    public static Action<object, object> GetValueSetter(this PropertyInfo propertyInfo)\n    {\n        var instance = Expression.Parameter(typeof(object), "i");\n        var argument = Expression.Parameter(typeof(object), "a");\n        var setterCall = Expression.Call(\n            Expression.Convert(instance, propertyInfo.DeclaringType),\n            propertyInfo.GetSetMethod(),\n            Expression.Convert(argument, propertyInfo.PropertyType));\n        return Expression.Lambda<Action<object,object>>(setterCall, instance, argument).Compile();\n    }\n}	0
2528560	2528543	Why is var m = 6 + + + + + + + + 6; valid in c#?	var m = 6 + ( +( +( +( +( +( +( +( 6 ))))))));\n      //6 + 6	0
31543902	31543708	Get original filename from File	[HttpPost]\n       public ActionResult Upload(HttpPostedFileBase file)\n       {\n           if (file != null && file.ContentLength > 0)\n           {\n               var fileName = Path.GetFileName(file.FileName);\n\n\n\n               file.SaveAs(path);\n           }\n        }	0
14154015	14152821	Unbind property from model MVC	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);\n   base.OnModelCreating(modelBuilder);\n}	0
12087109	12087014	How can I get all text nodes from XML file	string input = @"\n            <root>\n                <slide>\n                    <Image>hi</Image>\n                    <ImageContent>this</ImageContent>\n                    <Thumbnail>is</Thumbnail>\n                    <ThumbnailContent>A</ThumbnailContent>\n                </slide>\n            </root>";\n\n        XDocument doc = XDocument.Parse(input);\n        //You can also load data from file by passing file path to Load method\n        //XDocument doc = XDocument.Load("Data.xml");\n        foreach(var slide in doc.Root.Elements("slide"))\n        {\n            var words = slide.Elements().Select(el => el.Value);\n            string s = String.Join(" ", words.ToArray());\n        }	0
28256608	28253298	The behavior of method/global variables inside a critical section using Mutex Class	public class BankAccount\n   {\n      private int Balance;\n\n      private Mutex MyMutex = new Mutex();\n\n\n      public bool BankTransferWithMutex(int amount)\n      {\n         bool result = false;\n\n         MyMutex.WaitOne();\n\n         if (Balance >= amount)\n         {\n            Balance -= amount;\n            result = true;\n         }\n\n         MyMutex.ReleaseMutex();\n         //My question is here..\n         return result;\n      }\n   }	0
5521308	5521235	Bind the values without duplicates from database into dropdown using LINQ	var clientquer = Entity.New_Bank\n                        .Select(x=> new {Bank_ID2=x.Bank_ID2,\n                                         Bank_Name=x.Bank_Name})\n                        .Distinct();	0
6450471	6450434	Website Information using c#	using System.Net;\nusing System.Windows.Forms;\n\nstring url = "http://www.google.com";\nstring result = null;\n\n    WebClient client = new WebClient();\n    result = client.DownloadString( url );	0
30031424	29995238	How can I get a MySqlConnection object from a DLL	connection.Open();	0
2499540	2499522	XmlNode.SelectNode with multiple attribute	USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil') and contains(EMAIL_ID,'kapil@abc.co.in')]	0
17786217	17785433	try/catch in TransactionScope in C#	private void PerformTransactionalOperation()\n{\n    Log.Write("Starting operation.");        \n\n    try\n    {\n        using (var scope = CreateTransactionScope())\n        {\n            if (PerformTransactionalOperationCore())\n            {\n                Log.Write("Committing...");\n                scope.Complete();\n                Log.Write("Committed");\n            }\n            else\n            {\n                Log.Write("Operation aborted.");\n            }\n        }\n    }\n    catch (Exception exception)\n    {\n        Log.Write("Operation failed: " + exception.Message);\n        throw;\n    }\n}\n\nprivate bool PerformTransactionalOperationCore()\n{\n    // Perform operations and return status...\n}	0
30854259	30854185	How do I keep previously painted objects from disappearing when a new one is creating in a Windows Form Application?	private List<Ball> balls = new List<Ball>(); // Style Note:  Don't do this, initialize in the constructor.  I know it's legal, but it can cause issues with some code analysis tools.\n\nprivate void pbField_Paint(object sender, PaintEventArgs e)\n{\n    if (b != null)\n    {\n        foreach(Ball b in balls)\n        {\n            b.Paint(e.Graphics);\n        }\n    }\n}\n\nprivate void pbField_MouseClick(object sender, MouseEventArgs e)\n{           \n    int width = 10;\n    b = new Ball(new Point(e.X - width / 2, e.Y - width / 2), width);\n    balls.Add(b);\n    Refresh();\n}	0
25725452	25725144	How to know which was my last page in Windows Phone 8.1	var lastPage = Frame.BackStack.Last().SourcePageType	0
19070773	19070636	Creating a class from an XML file that can be enumerated through	foreach (XBMCShow show in test.Show) {\n                               ----\n                                 ^\n\n     if(show.ShowName == "Bones") {\n         ...	0
19656621	19656362	How to detect user-made changes of a NumericUpDown field in WinForms?	private void MyMethod()\n{\n    numericUpDown.ValueChanged -= numericUpDown_ValueChanged;\n    numericUpDown.Value = 100;\n    numericUpDown.ValueChanged += numericUpDown_ValueChanged;\n}	0
8001526	8000690	Opening an image file to a Bitmap class as 32bppPArgb	g.DrawImage(\n      tempImage,\n      new Reactangle( Point.Empty, Image.Size ),\n      new Reactangle( Point.Empty, Image.Size ),\n      GraphicsUnit.Pixels );	0
26928709	26928431	Windows Phone 8.1 select an item in a listview by holding	private void LstMyListView_Holding(object sender, HoldingRoutedEventArgs e)\n{\n    FrameworkElement element = (FrameworkElement)e.OriginalSource;\n    if (element.DataContext != null && element.DataContext is MyItem)\n    {\n        MyItem selectedOne = (MyItem)element.DataContext;\n        // rest of the code\n    }\n}	0
12902918	12902383	Format/bytes for sending XML to socket	using (var client = new TcpClient())\n{\n    client.Connect(host, porg);\n    using (var stream = client.GetStream())\n    {\n        // Or some other encoding, of course...\n        byte[] data = Encoding.UTF8.GetBytes(xmlString);\n\n        stream.Write(data, 0, data.Length);\n\n        // Whatever else you want to do...\n    }\n}	0
13821798	13572026	Table data Gateway with EntityFramework	public IDataReader FindWithLastName(String lastName) {\n     String sql = "SELECT * FROM person WHERE lastname = ?";	0
34420795	34420479	Too many redirections were attempted using WebRequest	// hwr.Host = Utils.GetSimpleUrl(url);	0
8459177	8459165	how to set label position respecting the tabcontrol size?	label.Dock = DockStyle.Top | DockStyle.Right;	0
30052851	30050979	How to stop data duplication in database	try\n{\n int i =  cmd.ExecutenonQuery())\n}\ncatch (ConstraintException ex)\n{\n  throw new ApplicationException("data is duplicated");\n}	0
26773291	26715815	How to detect implicit method to delegate conversion in Roslyn?	void VisitBinaryExpression(BinaryExpressionSyntax binaryExpression)\n{\n   var conversion = semanticModel.GetConversion(binaryExpression.Right);\n   if (conversion.IsMethodGroup)\n   {\n\n   }\n}	0
1319694	1319582	Destroying Windows in GTK#	this.Sensitive = false; \n  result = myConfWindow.run();\n  if (result == gtk.RESPONSE_CLOSE:)\n    myConfWindow.destroy();\n  this.Sensitive = true;	0
14597271	14596950	WPF Get the Cursor in the box	private void checkBox1_Checked(object sender, RoutedEventArgs e)\n        {\n          textBox1.IsEnabled = true;\n          textBox1.Focus();\n        } \n\n        private void checkBox1_Unchecked(object sender, RoutedEventArgs e)\n        {\n            textBox1.IsEnabled = false;\n        }	0
28695758	28691714	How to use string format on a list item	c = drART["MVRD"].ToString();\nc2 = (String.Format("{0:###,###0,000} ", Convert.ToInt32(c), cult));\nListVrd.Add(c2);	0
11255318	11253239	using URL Rewriting	void appliaction_BeginRequest(object sender, EventArgs e)\n {\n    HttpRequest request = sender as HttpRequest;\n     if???request.Url.Host.Contains("site1.com"))\n     {\n        request.RequestContext.HttpContext.Server.Transfer("site1.com/site1", true);\n    }\n\n  }	0
8802833	8801564	ASP.NET - How to add hyperlinks to pie chart sections?	Point.Url = "/url?querystring"	0
19074430	19074374	Find if field in one Enumerable exists in two possible fields of another	IEnumerable<Contact> contacts = ...\nIEnumerable<Property> properties = ...\n\nvar query = from property in properties\n            from name in new[] { property.Rep, property.PropMgr }\n            join contact in contacts on name equals contact.FullName\n            select contact;\n\nvar result = query.Distinct().ToList();	0
17197140	17195207	Including Pictures in an Outlook Email	attachment = MailItem.Attachments.Add("c:\temp\MyPicture.jpg")\nattachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")\nMailItem.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>"	0
34066093	34065479	Observable sequence that polls repository until a valid value is returned	var pollingPeriod = TimeSpan.FromSeconds(n);\n\nvar scheduler = new EventLoopScheduler(ts => new Thread(ts) {Name = "DestinationPoller"});\n\nvar query = Observable.Timer(pollingPeriod , scheduler)\n    .SelectMany(_ => destinationRepository.GetDestination().ToObservable())\n    .TakeWhile(response => response.HasDestination)\n    .Retry()    //Loop on errors\n    .Repeat()  //Loop on success\n    .Select(response => response.Destination)\n    .Take(1);	0
32171731	32171676	how can i fix the picture box in C#	PictureBox pb = (PictureBox)this.Controls.Find("pcbx" + p1, true)[0];\npb.BackgroundImage=Image.FromFile(@"C:\location\22.jpg");	0
5401060	5401024	How to fetch webpage title and images from URL?	using System;\nusing HtmlAgilityPack;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n\n    string url = @"http://www.veranomovistar.com.pe/";\n    System.Net.WebClient wc = new System.Net.WebClient();\n    HtmlDocument doc = new HtmlDocument();\n    doc.Load(wc.OpenRead(url));\n\n    var metaTags = doc.DocumentNode.SelectNodes("//title");\n\n    if (metaTags != null)\n    {\n        string title = metaTags[0].InnerText;\n    }\n}	0
32571002	32570940	how can I populate data table with values from a database	try\n{\n    var connection = @"your connection string";\n    //your command\n    var command = "your command";\n    var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);\n    var dataTable = new DataTable();\n\n    //Get data\n    dataAdapter.Fill(dataTable);\n}\ncatch (System.Data.SqlClient.SqlException sqlEx)\n{\n    //Use sqlEx.Number to hanlde excception more specific\n    //for example if sqlEx.Number -1 => Could Not Connect to Server.\n}\ncatch (Exception ex)\n{\n}	0
11928317	11928232	Is there a way to remove extra newlines from text using LINQ?	var lines = script.Split('\n')\n            .Where(line => !string.IsNullOrWhiteSpace(line));\n\nstring output = string.Join("\n", lines);	0
28407952	28407824	TryParse of Enum is working, but I think it shouldn't	Enum.TryParse<TEnum>(string value, ...)	0
14210752	14066144	Mono for android: Base64 string to image in gridview	string base64 = item.UserIMG;\n\nif (item.UserIMG != null) // If there's actually a string inside item.UserIMG\n{\n    System.IO.Stream s = new MemoryStream(Convert.FromBase64String(base64));\n\n    byte[] arr = Convert.FromBase64String(base64);\n    Drawable img = Drawable.CreateFromStream(s, null);\n\n    ImageView UserAvatar = view.FindViewById<ImageView>(Resource.Id.imgView);\n    UserAvatar.SetImageDrawable(img);\n }\n else  // If item.UserIMG is "" or null\n    {\n       ImageView UserAvatar = view.FindViewById<ImageView>(Resource.Id.imgView);\n    }	0
27877076	27875132	How to make custom inspector add object reference in Unity	using UnityEngine;\nusing System.Collections;\nusing UnityEditor;\n\n[CustomEditor(typeof(MyScript))]\npublic class MyScriptEditor : Editor {\n\n    public override void OnInspectorGUI()\n    {\n        var script = (MyScript) target;\n\n        script.someProperty = EditorGUILayout.IntField("A value", script.someProperty);\n        script.texture = (Texture) EditorGUILayout.ObjectField("Image", script.texture, typeof (Texture), false);\n    }\n}	0
22096542	22096427	Can I make a strict deserialization with Newtonsoft.Json?	public class Dog\n{\n    public string Name;\n\n    [JsonConstructor]\n    public Dog()\n    {\n\n    }\n\n    public Dog(string name)\n    {\n        Name = name + "aaa";\n    }\n}	0
32673572	32673408	c# Read a text file until a specific word and copy lines in a new text file	StreamReader Read2;\n\n    Read2 = File.OpenText("save" + campionatoselezTxt.Text + "bex.txt");\n    StreamWriter Write2 = File.CreateText("read" + campionatoselezTxt.Text + "bex.txt");\n\n\n    while (!Read2.EndOfStream)\n    {\n\n        string NewLine = "";\n        for (int K = 0; K < 8; K++)\n        {\n            if (K != 0)\n                NewLine = NewLine  + ";" + Read2.ReadLine();\n            else\n                NewLine = Read2.ReadLine();               \n        }\n\n         if(NewLine.Contains("Specific Word"))\n                break;\n\n        Write2.WriteLine(NewLine);\n    }\n\n    Read2.Close();\n    Write2.Close();	0
6585860	6585832	How to forbid a class method/property to be overriden in C#?	public new void SomeMethod()\n{\n}	0
23680398	23225953	Problems on export data from GridView to Excel	GridView1.AllowPaging = false;\nGridView1.DataBind();	0
11414184	11396109	Generate word document and set orientation landscape with html	Response.Write("<html>")\nResponse.Write("<head>")\nResponse.Write("<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; \ncharset=UTF-8"">")\nResponse.Write("<meta name=ProgId content=Word.Document>")\nResponse.Write("<meta name=Generator content=""Microsoft Word 9"">")\nResponse.Write("<meta name=Originator content=""Microsoft Word 9"">")\nResponse.Write("<style>")\nResponse.Write("@page Section1 {size:595.45pt 841.7pt; margin:1.0in 1.25in 1.0in\n1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")\nResponse.Write("div.Section1 {page:Section1;}")\nResponse.Write("@page Section2 {size:841.7pt 595.45pt;mso-page-orientation:\nlandscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;\nmso-footer-margin:.5in;mso-paper-source:0;}")\nResponse.Write("div.Section2 {page:Section2;}")\nResponse.Write("</style>")\nResponse.Write("</head>")\nResponse.Write("<body>")\nResponse.Write("<div class=Section2>")	0
34164454	34154163	How to find a substring inside a string via JavaScript in SharePoint?	var str = "NderonHyseniBurimRamusaAlenScott"; \nvar test = "NderonHyseni";//username\n\nvar res = str.match(test);\ndocument.getElementById("demo").innerHTML = res;\n\nif(res != null)\n{\n alert("true");\n}\nelse{\nalert("false");}\n}	0
9245464	9245438	asp.net login control where saves passwords	Membership.ValidateUser()	0
16983700	16983618	How to remove duplicates from collection using IEqualityComparer, LinQ Distinct	EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());	0
21102332	21101087	Generated Image for Tile with wrong Color	string fileName = @"Shared\ShellContent\Tile.jpg";\nGrid someElement = new Grid() \n{\n    // Add Stuff\n}\nsomeElement.Measure(new Size(width, height));\nsomeElement.Arrange(new Rect(0,0,width, height));\nvar bitmap = new WriteableBitmap(someElement, null);\n\nusing(var stream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(fileName, FileMode.OpenOrCreate))\n{\n    bitmap.SaveJpeg(stream, width, height, 0, 100);\n}\n\nUri uri = new Uri("isostore:/" + fileName, UriKind.Absolute);	0
33509245	33509198	Foreach backwards for listboxes?	foreach (ListViewItem lvi in istView1.SelectedItems.Cast<ListViewItem>().AsEnumerable().Reverse());	0
6865956	6865890	How can I read/stream a file without loading the entire file into memory?	const int chunkSize = 1024; // read the file by chunks of 1KB\nusing (var file = File.OpenRead("foo.dat"))\n{\n    int bytesRead;\n    var buffer = new byte[chunkSize];\n    while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)\n    {\n        // TODO: Process bytesRead number of bytes from the buffer\n        // not the entire buffer as the size of the buffer is 1KB\n        // whereas the actual number of bytes that are read are \n        // stored in the bytesRead integer.\n    }\n}	0
13147015	13146974	How can I find all strings between two known values?	List<string> lst=Regex.Matches(input,@"(?<=\[).*?(?=\])")\n                      .Cast<Match>()\n                      .Select(x=>x.Value)\n                      .ToList();	0
7271270	7271219	Find if a directory has a parent	else if (dir != null && dir.Parent != null)	0
7429966	7428327	Problems with extracting a method because of parallelism	StartNewTest(i => new PSTLooper(intHands).EvalEnumeration(i));\n\npublic void StartNewTest(Func<int, long[]> func)\n{\n     Parallel.For(0, Environment.ProcessorCount, i => \n          { handTypeSum[i] = func(i); });\n}	0
32836903	32836832	custom format to display negative numbers including sign	string result = String.Format("{0:0.00}",  this.Hours).PadLeft(8, '0');	0
2069285	2069201	Load a DLL and Its Dependencies	var names = myAssembly.GetReferencedAssemblies();	0
12712120	12711899	Change application name shown in Win7 taskbar	vshost32.exe	0
15769558	15769101	Setting a field deep in the arbitrary object structure	object obj = new D { c = new C { b = new B { a = new A { i = 1 } } } };\nList<string> path = new List<string> { "c", "b", "a", "i" };\nobject value = 42;\n\nFieldInfo fieldInfo = null;\nobject prevObj = null;\nobject obj2 = obj;\nfor (int i = 0; i < path.Count; i++)\n{\n    string fieldName = path[i];\n    fieldInfo = obj2.GetType().GetField(fieldName);\n    if (i == path.Count - 1) prevObj = obj2;\n    obj2 = fieldInfo.GetValue(obj2);\n}\nif (fieldInfo != null)\n{\n    fieldInfo.SetValue(prevObj, value);\n}\nConsole.WriteLine(((D)obj).c.b.a.i == (int) value);	0
10325328	10325289	How to factorize an operator?	public IQueryable<Post> GetWithSticky(bool isSticky)\n{\n   return Get().Where(p => (p.Type == PostType.Sticky) == isSticky);\n}	0
2234687	2234676	setting mail header in c#	MailMessage mail = new MailMessage();\nmail.To = "me@mycompany.com";\nmail.From = "you@yourcompany.com";\nmail.Subject = "this is a test email."; \nmail.Body = "this is my test email body"; \nmail.IsBodyHtml = false;\nSmtpMail.SmtpServer = "localhost";  //your real server goes here \nSmtpMail.Send( mail );	0
2738718	2738698	How to print all columns in a datareader	static List<string> GetDataReaderColumnNames(IDataReader rdr)\n{\n    var columnNames = new List<string>();\n    for (int i = 0; i < rdr.FieldCount; i++)\n        columnNames.Add(rdr.GetName(i));\n    return columnNames;\n}	0
34469931	34467714	Two Arrays have same values but do not returns equal	bool Deneme () \n{\n    for (int i = 0; i < correctOnes.Length; i++) {\n\n        if (!Mathf.Approximately (correctOnes[i].magnitude, cubeRotation[i].rotation.eulerAngles.magnitude))     \n        {\n            return false;\n        }\n    }\n    return true;\n}	0
24699281	24699083	How to get the 4. Wednesday of the next Month as DateTime?	else if (instance == 4)  //if the 4th week is requested\n    {\n        day = day.AddDays(21); // i add 28 days\n    }	0
5075954	5075872	Creating a compound iterator in F#	let validMoves = \n    AllCells \n    |> Seq.collect LegalMovesAround\n    |> Seq.distinct	0
22743150	22743036	How to cast object to every number in a sorting of list-view?	case "int":\n    returnValue = ((int) x).CompareTo((int) y);	0
16956305	16956181	Listing sql data in C#	using (var sqlCommand = new SqlCommand(SelectMembers, sqlConnection)) {\n    // fetch data and iterate through results\n    var reader = sqlCommand.ExecuteReader();\n    while (reader.Read()) { \n        // create an object, set its properties and add it to the return list\n        Member member = new Member();\n        member.SomeProperty = reader["MY_COLUMN"];\n        list.Add(member);\n    }\n}	0
17845269	17795850	custom validator of checkbox in gridview only mark one row invalid	public void noneChecked(object source, ServerValidateEventArgs args)\n{\n    GridViewRow gvrow = (GridViewRow)(source as Control).Parent.Parent;\n\n    bool cbnone = ((CheckBox)gvrow.FindControl("cbnone")).Checked;\n    bool cbr = ((CheckBox)gvrow.FindControl("cbr")).Checked;\n    bool cbx = ((CheckBox)gvrow.FindControl("cbx")).Checked;\n    bool cbp = ((CheckBox)gvrow.FindControl("cbp")).Checked;\n    bool cbe = ((CheckBox)gvrow.FindControl("cbe")).Checked;\n    if ((cbr || cbx || cbp || cbe) && cbnone)\n    {\n        ((CustomValidator)gvrow.FindControl("vcbnone")).IsValid = false;\n        args.IsValid = false;\n    }\n}	0
9773335	9773204	C# Display repeated letter in string	string enteredWord = textBox1.Text;\nHashSet<char> letters = new HashSet<char>();\nforeach(char c in enteredWord)\n{\n    if (letters.Contains(c))\n        label1.Text += c.ToString();\n    else\n        letters.Add(c);\n}	0
11521083	11520667	How can I store same key in IDictionary?	class TDictionary<K, V>\n{\n    struct KeyValuePair\n    {\n        public K Key;\n        public V Value;\n    }\n\n    private readonly List<KeyValuePair> fList = new List<KeyValuePair>();\n\n    public void Add(K key, V value)\n    {\n        fList.Add(new KeyValuePair { Key = key, Value = value });\n    }\n\n    public List<V> this[K key]\n    {\n        get { return (from pair in fList where pair.Key.Equals(key) select pair.Value).ToList(); }\n    }\n\n    public List<K> Keys\n    {\n        get { return fList.Select(pair => pair.Key).ToList(); }\n    }\n\n    public List<V> Values\n    {\n        get { return fList.Select(pair => pair.Value).ToList(); }\n    }\n}	0
15205628	15205056	scraping text using html agilitypack	web.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0";\ndoc = web.Load("http://translate.google.com/#en/bn/like");\nwebBrowser1.DocumentText = doc.DocumentNode.OuterHtml;	0
19287924	19287819	can't get only the date from datetime	somedate.ToString("d")	0
13549368	13524982	Display text with no rectangle	android:background="@android:color/transparent"	0
15012010	15011814	I need advice developing a sensitive data transfer/storage/encryption system	1.2      <-- version of this format, so I can add things in the future\nkey1=value1\nkey2=value2\n...	0
15333751	15333375	Is there a way to find the PackageFamilyName at runtime?	Package.Current.Id.FamilyName	0
15720886	15720788	Building NHibernate query throws - variable 'x' of type referenced from scope '', but it is not defined	TheEnum enumType;\nif (!string.IsNullOrWhiteSpace(typeFilter))\n     query = query.And(c => Enum.TryParse<TheEnum>(typeFilter, out enumType) && enumType== c.ComponentType)	0
32366167	32342925	Pressing toggle button in toggle group calls more than one button	GameObject.FindObjectOfType<MusicPlayer>()	0
14977895	14977493	Get entered time from RadTimePicker c#	DateTime d = radTimeStartTime.SelectedDate.Value;\nstring time = d.ToString("HH:mm:ss");	0
4131280	4131268	How do I add an extra item in my drop down list,I am using datatable as datasource	dropdownlist1.Items.Insert(0, new ListItem("Select country", "0"));	0
15452507	15452451	How to separate string to more than one part C#	var input = "www.google.com;www.yahoo.com;www.gmail.com";\nvar result = string.Join(";", input.Split(';').Select(x => string.Format("<a>{0}</a>",x)));	0
12640234	12640070	How to add a parent node using foreach	foreach (XmlNode node in xd.DocumentElement.ChildNodes)\n    {\n        XmlNode imported = xd.ImportNode(node, true);\n        XmlElement ex = xd.CreateElement("ex");\n        ex.AppendChild(imported["a"]);\n        ex.AppendChild(imported["b"]);\n        ex.AppendChild(imported["c"]);\n        ex.AppendChild(imported["d"]);\n        xd.AppendChild(ex);\n    }	0
19704523	19704364	Entity Framework - getting a table's column names as a string array	var colNames = typeof(User).GetProperties().Select(a => a.Name).ToList();	0
14683680	14353434	selecting data between 2 dates	Sqlcommand cmd=new sql command ("Select data from tablename \n                                where date>=startdate \n                                and date<=enddate",connection)	0
22220885	22199063	Monodroid add editText programmatically to layout view	textView.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);	0
1904184	1904160	Getting the IP Address of a Remote Socket Endpoint	Socket s;\n\nIPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;\nIPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;\n\nif (remoteIpEndPoint != null)\n{\n    // Using the RemoteEndPoint property.\n    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);\n}\n\nif (localIpEndPoint != null)\n{\n    // Using the LocalEndPoint property.\n    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);\n}	0
4158211	4158171	Application Trust Level on Network Drive for Nhibernate C# Application	[assembly: AllowPartiallyTrustedCallers]	0
19207691	19151363	Windows Service to run a function at specified time	protected override void OnStart(string[] args)\n    {\n\n        _timer = new Timer(intervalMins * 60 * 1000); //Runs timer every 10 mins\n        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n        //timer_Elapsed(this, null);\n        _timer.Start();\n    }\n\n    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n    {\n\n        TimeSpan span = startAt - DateTime.Now;\n        //Debugger.Break();\n        if (span.Minutes <= intervalMins &&\n            span.Minutes > 0)\n        {\n            try\n            {\n                IOSPush = new IOSPushCtrlr();\n                IOSPush.SendAppleNotifications();\n            }\n            catch (Exception ex)\n            {\n                bl.InsertErrorLogs("Error", "", ex.Message);\n            }\n        }\n\n    }	0
19585002	19584207	How do I save a Bitmap to a file?	Schets schets = ... //Say here what your schets is, otherwise it's null.	0
17231635	17230234	Windows forms - display image in gridview	for (int row = 0; row <= [YourDataGridViewName].Rows.Count - 1; row++)\n{\n    ((DataGridViewImageCell)gvFiles.Rows[row].Cells[1]).Value = Properties.Resources.Picture1\n}	0
21855577	21855249	return a list-object from a dictionary	public static List<Data> GetDataList()\n{\n    return meters.Values.SelectMany(m => m.data).ToList();\n}	0
3718219	3718112	is there any way to ignore reading in certain lines in a text file?	string content = File.ReadAllText(filename);\nRegex r = new Regex(@"CREATE TABLE [^\(]+\((.*)\) ON");\nstring whatYouWant = r.Match(content).Groups[0].Value;	0
4121266	4121149	How to sort 3D array in c#, with each row is specific to one entry if 1D array?	var oneDArray = new int[]; //fill it.. :)\n    var twoDArray = new int[,]; //fill it.. :)\n    var mapping = new int[oneDArray.Length];\n\n    //lets create the mapping\n    for (int i = 0; i < mapping.Lenght; i++)\n      mapping[i] = i;\n\n    //now lets sort the 1D array\n    for (int i = 0; i < oneDArray.Length; i++)\n      for (int j = i; j < oneDArray.Length; i++){\n\n        if ( oneDArray[i] < oneDArray[j] ){\n            Swap(oneDArray, i, j);\n            Swap(mapping, i, j);\n        }\n    }	0
19786705	19786681	Show Asp.Net Page By Using Javascript	window.location.href = "OtherPage.aspx"	0
27566550	27566175	Scroll first listbox item into view	BeginInvoke((Action)(() => KommentarListBox.ScrollIntoView(item)));	0
8823521	8822923	Index Prefix Length for BLOB with Nhibernate and MySQL	new Configuration.Configure().Add()	0
9483369	9482174	How to save pages with unique names?	protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n    var currentPath = HttpContext.Current.Request.Path;\n    // do some logic to generate newPath\n    var newPath = GetNewPath ( currentPath );\n    HttpContext.Current.RewritePath(newpath);\n    // after this point ASP.NET will work as the user would have requested newpath\n}	0
18240479	18240456	Only getting last item in list	using (StreamWriter write = new StreamWriter("PROPNUMTEST.txt"))\n{\n   foreach (string x in propnumList)\n   {\n     ....\n   }\n}	0
1661239	1660175	How Internet Explorer Prepare Print Preview window	HtmlDocument document = WebBrowser1.Document;\n\nforeach (HtmlElement element in document.GetElementsByTagName("LINK"))\n{\n    string cssMedia = element.GetAttribute("Media");\n\n\n    if (cssMedia == "print")\n        element.SetAttribute("Media", "screen"); //sets print styles to display normally\n    else\n        element.SetAttribute("Media", "hidden"); //hides normal styles\n}	0
7108718	7108642	How to override a base class' DB connection string?	private readonly string connectionString;\n\npublic Foo() : this(Settings.Default.DbConnectionString) {\n}\n\npublic Foo(string connectionString) {\n    this.connectionString = connectionString;\n}	0
26720873	26720342	Draw a Grid layout based on known cols and rows	int n = 16;\n    int grid = (int)Math.Sqrt(n);\n    int x = 0, y = 0;\n    int yCounter = 0;\n    int xCounter = 0;\n    for (int i = 0; i < n; i++)\n    {\n        myGeometricObject[i] = new GeometricObject();\n\n        if(i % grid == 0 && i > 0)\n        {\n            yCounter++;\n            xCounter = 0;\n            y = yCounter * 50;\n        }\n        // Next 2 lines\n        x = xCounter * 50;\n        xCounter++;\n\n        myGeometricObject[i].Location = new System.Drawing.Point(x, y);\n        myGeometricObject[i].Size = new System.Drawing.Size(50, 50);\n        this.Controls.Add(myGeometricObject[i]);\n    }	0
3141574	3141565	search inside array of strings	// to find a match anywhere in the word\nwords.Where(w => w.IndexOf(str, \n    StringComparison.InvariantCultureIgnoreCase) >= 0);\n\n// to find a match at the beginning only\nwords.Where(w => w.StartsWith(str, \n    StringComparison.InvariantCultureIgnoreCase));	0
7246637	7246492	Formatting the result of DriveInfo's TotalSize in C#	public string GetSize(long size)\n{\n   string postfix = "Bytes";\n   long result = size;\n   if(size >= 1073741824)//more than 1 GB\n   {\n      result = size / 1073741824;\n      postfix = "GB";\n   }\n   else if(size >= 1048576)//more that 1 MB\n   {\n      result = size / 1048576;\n      postfix = "MB";\n   }\n   else if(size >= 1024)//more that 1 KB\n   {\n      result = size / 1024;\n      postfix = "KB";\n   }\n\n   return result.ToString("F1") + " " + postfix;\n}	0
27814453	27814152	Convert Comma separated string to XML using C#	using System.Xml.Linq; // required namespace \n\nXDocument xmlDoc = new XDocument();\nXElement xElm = new XElement("Languages",\n                    from l in lang.Split(',')\n                    select new XElement("lang", new XAttribute("Name", l)                \n                    )\n                );\nxmlDoc.Add(xElm);	0
6924840	6924782	Simple C# Noop Statement	((Action)(() => { }))();	0
532877	513678	Custom TextBox Control And Validation Display	protected override void Render(System.Web.UI.HtmlTextWriter writer)\n{\n    if(_req != null)\n        _req.RenderControl(writer);\n    base.Render(writer);\n}	0
10032151	9993347	WPF DataGrid ColumnHeader Style: Can't make text bold in ControlTemplate	protected override void OnAutoGeneratedColumns(EventArgs e)\n    {\n        var dataTable = pivotMod.DataTable;\n        foreach (DataGridColumn gridCol in Columns)\n        {\n            var colName = gridCol.Header.ToString();\n            DataColumn col = dataTable.Columns[colName];\n\n            // set the datacontext of the gridcolumn to the modfield ...\n            ModFieldGUIWrapper modField = col.ExtendedProperties["ModField"] as ModFieldGUIWrapper;\n            gridCol.SetValue(FrameworkElement.DataContextProperty, modField);\n\n            // set the header to the data object so that the datatrigger's binding works!!\n            gridCol.Header = modField;\n\n        }\n        base.OnAutoGeneratedColumns(e);\n    }	0
22717978	22717271	Trying to read an Excel file with EPPlus works on the server, but not through a browser	byte[] file=File.ReadAllBytes(@"C:\file.xlsx");\nMemoryStream ms=new MemoryStream(file);\nusing (ExcelPackage package = new ExcelPackage(ms))\n{\n    if (package.Workbook.Worksheets.Count == 0)\n        strError = "Your Excel file does not contain any work sheets";\n    else\n    {\n        foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)\n        {	0
8819713	8819594	How to substract and round times	var t1 = TimeSpan.Parse("13:00").TotalMinutes;\n var t2 = TimeSpan.Parse("13:45").TotalMinutes;\n var round = (1 + ((int)(t2 - t1) / 60)) * 60; //Assuming t2 is always greater than t1	0
25692518	25692447	Expression API throws exception: variable 'x' of type 'x' referenced from scope '', but it is not defined	public static void Compare<TComparate>(Expression<Func<TComparate, bool>> predicate)\n{\n    if (predicate.Compile()((TComparate)comparatePerson)) return;\n\n    var expression = (BinaryExpression)predicate.Body;\n\n    var actual = Expression.Lambda(expression.Left, predicate.Parameters)\n        .Compile().DynamicInvoke(comparatePerson);\n    var expected = Expression.Lambda(expression.Right, predicate.Parameters)\n        .Compile().DynamicInvoke(comparatePerson);\n}	0
6750699	6750581	Using RenderTargetBitmap to save a portion of the displayed images	// (BitmapSource bmps)\nCroppedBitmap crop = new CroppedBitmap(bmps, new Int32Rect(selRect.X, selRect.Y, selRect.Width, selRect.Height));	0
9722095	9722047	Object to add resources to ResourceDictionary	Merged Resource Dictionary	0
3343389	3343206	How to create a folder in the application installed directory	Application.StartupPath	0
7237707	7237177	How to get days in range	void Main()\n{\n    DateTime today = new DateTime(2011, 8, 29);\n    DateTime nextWeek = new DateTime(2011, 9, 4);\n\n    foreach (DateTime dateTime in today.ListAllDates(nextWeek))\n    {\n       Console.WriteLine(dateTime);\n    }\n    Console.ReadLine();\n}\n\npublic static class DateTimeExtenions\n{\n    public static IEnumerable<DateTime> ListAllDates(this DateTime lhs, DateTime futureDate)\n    {   \n        List<DateTime> dateRange = new List<DateTime>();\n        TimeSpan difference = (futureDate - lhs);\n        for(int i = 0; i <= difference.Days; i++)\n        {\n            dateRange.Add(lhs.AddDays(i));\n        }\n        return dateRange;\n    }\n}	0
32120088	32119628	Retrieve Selected Checkbox Value From Previous Page	//if you are loading the new page\nif (!Page.IsPostBack)\n{\n    if(Session["Step02AllServices"] != null)\n    {\n        Step02AllServices.Checked = (bool) Session["Step02AllServices"];\n        //similarly assign other checkbox values as they are in session already\n    }\n    else\n    {\n        //do normal assignment\n    }\n}	0
11853777	11851357	How can I join three datasources with LINQ?	var questions = questionService.Details(pk, rk);\nvar topics = contentService.GetTitles("0006000")\n                .Where(x => x.RowKey.Substring(2, 2) != "00");\nvar  types = referenceService.Get("07");\n\nmodel = (\n    from q in questions\n    join t in topics on q.RowKey.Substring(0, 4) equals t.RowKey into topics2\n    from t in topics2.DefaultIfEmpty()\n    join type in types on q.type equals type.RowKey into types2\n    from type in types2.DefaultIfEmpty()\n    select new Question.Grid {\n        PartitionKey = q.PartitionKey,\n        RowKey = q.RowKey,\n        Topic = t == null ? "No matching topic" : t.Title,\n        Type = type == null ? "No matching type" : type.Title,\n        ...	0
227133	227121	Casting a UserControl as a specific type of user control	foreach(UserControl uc in plhMediaBuys.Controls) {\n    MyControl c = uc as MyControl;\n    if (c != null) {\n        c.PublicPropertyIWantAccessTo;\n    }\n}	0
9323097	9322766	Adding multiple "temporary" values in a datagridview and store them in the database	YourClass\n{\nprivate List<object> list;\n\npublic Page_Load(object sender, args e)\n{\n          if (!isPostBack) // only initialize once when the page first loads\n          {\n              list = new List<object>();\n              datagrid.datasource = list;\n          }\n}\n\nprotected void OnClickButton(object sender, args e)\n{\n     list.add(new { Gender = genderComboBox.Text, Country = countryComoBox.Text });\n     datagrid.DataBind();\n}\n}	0
8878755	8878710	How to implement workflow within an object	Strategy Pattern	0
12647280	12647153	Do I need to move external libraries with my application for each device	System.*	0
2876606	2876590	Optional Specification of some C# Optional Parameters	SomeMethod(bar: false);	0
1223881	1223865	Best practice regarding returning from using blocks	public int Foo()\n{\n  using(..)\n  {\n     return bar;\n  }\n}	0
2361506	2361482	How to assign the value(total values added from each textbox) to the 'txtTotal' Textbox in gridview	grdList.Columns[2].FooterText = sumDebit.ToString();	0
23821028	23820840	how to get data from one page and display in other page in asp.net	using (XmlWriter writer = XmlWriter.Create(<FilePath>))     {\n        writer.WriteStartDocument();\n        writer.WriteStartElement("UserInfo");\n        writer.WriteElementString("FirstName", "ABC");\n        writer.WriteElementString("Email", "abc@dc.com");\n        -----\n        writer.WriteEndElement();\n        writer.WriteEndDocument();\n\n        }	0
29445431	28682027	Can I access the full power of Autofac in UnitTests, using the Moq integration	using (var mock = AutoMock.GetLoose())\n{\n    mock.Container.ComponentRegistry.Register(\n        RegistrationBuilder\n            .ForType<MyClass>()\n            .PropertiesAutowired()\n            .CreateRegistration<MyClass, ConcreteReflectionActivatorData, SingleRegistrationStyle>()\n    );\n}	0
23547822	23547506	Select a column based on a variable	var results = Messages\n    .GroupBy(m => new { m.Year, m.Month })\n    .Select("new (Key.Year as Year, Sum(Metric1) as Metric)");	0
13805069	13804765	Factory Pattern where should this live in DDD?	upper\n  --> domain\n  --> domain_factory	0
5615930	5615840	Validating ASP.NET MVC2 FormCollection against Model	class NameAndEmail\n{\n    [Required(ErrorMessage = "Name is a required field.")]\n    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]\n    public string Name { get; set; }\n\n\n    [Required(ErrorMessage = "Email address is a required field.")]\n    [Email(ErrorMessage = "Email address must be a valid format.")]\n    [StringLength(100, ErrorMessage = "Email address must be 100 characters or less.")]\n    [DisplayName("Email address")]\n    public string Email { get; set; }\n}\nclass SsUserMetaData : NameAndEmail\n{\n    [Required(ErrorMessage = "Username is a required field.")]\n    [StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]\n    public string Username { get; set; }\n\n\n    [Required(ErrorMessage = "Password is a required field.")]\n    [StringLength(1000, MinimumLength = 6, ErrorMessage = "Passwords must be at least 6 characters long.")]\n    [DisplayName("Password")]\n    public string PasswordHash { get; set; }\n}	0
12518490	12518444	using await inside a callback	queue.QueueCompleted += (s, eA) =>\n            {\n                Task.Run(async ()=>{\n                    //blah\n                });\n            };	0
18506715	18490457	How to read YML feeds - or ignore DOCType if read as XML	XmlDocument doc = new XmlDocument();\n                    doc.LoadXml(Regex.Replace(File.ReadAllText(downloadFileName), "<!DOCTYPE.+?>", string.Empty));	0
9449876	9449854	How to set a label equal to a textbox, with every letter on a separate line?	label1.Text = String.Empty;\n\n        foreach (char c in textBox1.Text)\n        {\n            label1.Text += c + Environment.NewLine;\n        }	0
6679985	6624066	How to set values in x axis MSChart using C#	string[] range = new string[10];\n\n    private void Form1_Shown(object sender, EventArgs e)\n    {\n        chart1.ChartAreas[0].AxisX.Minimum = 7;\n        chart1.ChartAreas[0].AxisX.Maximum = 16;\n\n        range[0] = "";\n        range[1] = "7-8";\n        range[2] = "8-9";\n        range[3] = "9-10";\n        range[4] = "10-11";\n        range[5] = "11-12";\n        range[6] = "12-1";\n        range[7] = "1-2";\n        range[8] = "2-3";\n        range[9] = "";\n\n        Series S1 = new Series();            \n        S1.Points.AddXY(9, 25);\n        S1.Points.AddXY(10, 35);\n        S1.Points.AddXY(11, 15);\n        chart1.Series.Add(S1);            \n\n    }\n\n    int count;\n    private void chart1_Customize(object sender, EventArgs e)\n    {\n        count = 0;\n        foreach (CustomLabel lbl in chart1.ChartAreas[0].AxisX.CustomLabels)\n        {\n            lbl.Text = range[count];\n            count++;\n        }                        \n    }	0
1677662	1672437	Using NHibernate with ancient database with some "dynamic" tables	sess.CreateSQLQuery("SELECT tempColumn1 as mappingFileColumn1, tempColumn2 as mappingFileColumn2, tempColumn3 as mappingFileColumn3 FROM tempTableName").AddEntity(typeof(Cat));	0
13580257	13579760	replacing an object in listview with new one?	for (int i = 0; i < listView1.Items.Count; i++)\n{\n    if (listView1.Items[i].SubItems[1].ToString() == item.SubItems[1].ToString())\n    {\n        listView1.Items[i] = (ListViewItem)item.Clone();\n    }\n}	0
12610517	12610434	How to create a path to xml element in C#	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load("Path of the xml");\nXmlNode titleNode = xmlDoc.SelectSingleNode("//level1/level2/level3");	0
15896678	15892310	Add Checkbox Column into GridControlEx	string query = "SELECT CAST(1 AS BIT) AS Process, TransID, Company, Period, EmpID, Employee FROM Trx"\n\ntblClaim = DB.sql.Select(query);\ngcxClaim.ExGridControl.DataSource = tblClaim;\ngcxClaim.ExGridView.OptionsBehavior.Editable = true;\nfor (int i = 0; i < tblClaim.Columns.Count; i++)\n{\n    gcxClaim.ExGridView.Columns[i].OptionsColumn.AllowEdit = false;\n}\ngcxClaim.ExGridView.Columns["Process"].OptionsColumn.AllowEdit = true;	0
12778185	12778058	Don't allow text entry in numericUpDown	numericUpDown.ReadOnly = true;	0
22878890	22878550	How to get/read data from the xml file in C# Windows application	using System.Xml;\n\n...\n\nXmlDocument MyXmlFile = new XmlDocument();\nMyXmlFile.LoadXml(PATH_TO_MY_XML);\n\n// Using \nXmlNode xmlValueItem = MyXmlFile.GetElementsByTagName("ValueItem")[0];\n\nstring position = xmlValueItem.Attributes["Position"].InnerText;	0
1306387	1306182	Left outer Join with LINQ	from c in DataContext.cus_contact\njoin cp in DataContext.cus_phone_jct on c.id equals cp.contact_id into cp2 \n  from cp3 in cp2.DefaultIfEmpty()\njoin p in DataContext.cus_phone on cp3.phone_id equals p.id into p2 \n  from p3 in p2.DefaultIfEmpty()\nwhere c.cus_id = 4\nselect \n  c.id,\n  cp3.id\n  ...	0
14631469	14631373	Textbox that MUST contain both numbers and letters?	if(!str.Any(Char.IsLetter) || !str.Any(Char.IsDigit)) {  \n  MessageBox.Show("Please Enter both numbers and letters");\n  return;\n}	0
17047702	17047602	Proper way to initialize a C# dictionary with values already in it?	static class Program\n{\n    private static readonly Dictionary<string, string> _myDict = new Dictionary<string, string>\n    {\n        { "test", "test" },\n        { "test2", "test2" }\n    };\n\n    static void Main(string[] args)\n    {\n        Console.ReadKey();\n    }\n}	0
18773103	18772998	How to get Single Row From Query without a foreach Loop?	var query2 = (from p in dbContext.ViewRights where p.user_id==user_id select p).FirstOrDefault()	0
24866974	24866671	Regex match word except when it's a part of a url	(?<!https?://\S*)\bco\b	0
21473677	21473322	How to add handler to ListBoxItem in code?	lbi.MouseLeftButtonUp += GoToEditDraft;\nprivate void GoToEditDraft(object sender, MouseButtonEventArgs mouseButtonEventArgs)\n{\n    //TODO: put some logic here\n}	0
23758552	23757570	test xml node with c#	var existingItem = \n        xDocument.Root\n                 .Elements("Item")\n                 .FirstOrDefault(o => \n                                      (string)o.Attribute("Text") == texts \n                                        && \n                                      (string)o.Attribute("Value") == values\n                                 );\nif(existingItem != null)\n{\n    //DELETE !!!\n}\nelse\n{\n    //ADD !!!\n}	0
28110788	28108622	how to change starting position combobox C# mysql	(selectedIndex + 1)	0
11884284	11884128	How do you select a lower level item as the displaymember for a ListBox	var SocketInfos = sockets.Select((s) => new {ClientIpAddress = s.ConnectionInfo.ClientIpAddress,\n                                             Socket = s}).ToList();\n\nListBox1.DataSource=SocketInfos ;\nListBox1.DisplayMember="ClientIpAddress";	0
3112247	3112053	hints of impending failure	4 users calling page1 -> costs 4   - 6   mb, 4 threads\n5 users calling page1 -> costs 7   - 14  mb, 5 threads\n2 users calling page2 -> costs 120 - 200 mb, 1 thread	0
16161289	16147142	How to read a particular node from xml in C#?	XmlNodeList xnList = doc.SelectNodes("/Loop/Loop/Segment[@Name='AAA']");\n          foreach (XmlNode xn in xnList)\n          {\n              if (xn.HasChildNodes)\n              {\n                  foreach (XmlNode item in xn.ChildNodes)\n                  {\n                      Console.WriteLine(item.InnerText);\n                  }\n              }  \n          }	0
11150397	11143637	Executing Chain of Responsibility variation	public T Execute(T instance)\n{\n     T result = instance;\n     foreach(var individual in tasks.GetTasks())\n     {\n         if(!individual.CanExecute()) break;\n\n         result = individual.Process(result);\n     }\n\n     return result;\n}	0
17527880	16798714	Using Linq for comparison of two Datatables	if (User.Identity.IsAuthenticated)\n{\n    DataColumn dc = new DataColumn("isMarked", System.Type.GetType("System.Int32"));\n    ds.Tables[0].Columns.Add(dc);\n    string[] strArray = ds.Tables[0].AsEnumerable().Select(s => s.Field<string>("itemid")).ToArray<string>();\n    HashSet<string> hset = new HashSet<string>(strArray);\n    foreach (DataRow dr in ds.Tables[0].Rows)\n    {\n         if (hset.Contains(dr["itemid"].ToString().Trim()))\n             dr[3] = 1;\n         else\n             dr[3] = 0;\n    }\n}	0
5230278	5197028	Cannot send displayed email using redemption in c#	// Event object to wait for\nSystem.Threading.ManualResetEvent _manualEvent = new ManualResetEvent(false);\n\nprivate void DisplayMail() {\n    ...\n    // register an eventhandler for the close event\n    _newMail.OnClose += new Redemption.IRDOMailEvents_OnCloseEventHandler(_newMail_OnClose);\n\n    _newMail.Recipients.Add(txtTo);\n    _newMail.Recipients.ResolveAll();\n    _newMail.Subject = subject;\n    _newMail.HTMLBody = body;\n\n    _newMail.Display(false, null);\n    // wait here until the message-window is closed...\n    _manualEvent.WaitOne();\n}\n\nprivate void _newMail_OnClose()\n{\n    _manualEvent.Set();\n}	0
4592781	4592770	many to many relation with nhibernate on the entity	[List(1, Name = "Product", Table = "Product", Cascade = CascadeStyle.None, Lazy = false, Fetch = CollectionFetchMode.Select)]\n    [NHibernate.Mapping.Attributes.Key(2, Column = "categoryId")]\n    [Index(3, Column = "ordinal")]\n    [ManyToMany(4, ClassType = typeof(Product), Column = "productId")]\n    public virtual IList<Category> Categorys	0
8135585	8135463	How to add a count to a button click in a Winform	bool Save=false;\n\nprivate void SaveButton_Click(object sender, EventArgs e)\n{\n  Save=true;\n  ....\n}\n\nif(!Save)\n{\n  frmExit search = new frmExit();\n  search.ShowDialog();\n}	0
25666360	25657882	Reading csv file with fields in double quotes as structure	string yourCSVString; // "\"var1\",\"var2\",\"var3\"";\n string processedString;\n processedString=yourCSVString.Replace("\"","");\n Console.WriteLine(processedString);	0
16310379	16309017	unchecked only all child node in treeview	private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)\n{\n    if (updatingTreeView) return;\n    updatingTreeView = true;\n    CheckChildren_ParentSelected(e.Node, e.Node.Checked);\n    if (e.Node.Checked)\n    {\n        SelectParents(e.Node, e.Node.Checked);\n    }\n    updatingTreeView = false;\n}	0
413671	413618	Array that can be resized fast	List<int> nums = new List<int>(3); // creates a resizable array\n                                   // which can hold 3 elements\n\nnums.Add(1);\n// adds item in O(1). nums.Capacity = 3, nums.Count = 1\n\nnums.Add(2);\n// adds item in O(1). nums.Capacity = 3, nums.Count = 3\n\nnums.Add(3);\n// adds item in O(1). nums.Capacity = 3, nums.Count = 3\n\nnums.Add(4);\n// adds item in O(n). Lists doubles the size of our internal array, so\n// nums.Capacity = 6, nums.count = 4	0
23646563	23646357	Removing duplicates from a list<T>	Song.AllSongs.GroupBy(s => s.Path).Select(group => group.First()).ToList()	0
4277676	4277567	Detect particular tokens in a string. C#	string test = "Hi #Name#, You should come and see this #PLACE# - From #SenderName#";\nRegex reg = new Regex(@"#\w+#");\nforeach (Match match in reg.Matches(test))\n{\n    Console.WriteLine(match.Value);\n}	0
11833915	11833178	How can you programmatically import XML data into an Excel file?	ImportXml()	0
29084140	29084027	Calculate number of cells with a specific value	int countFixed=0;\nint countUnFixed=0;\nfor(int i=0;i<dgv.RowCount;i++)\n{\n   if((string)dgv.Rows[i].Cells[1].Value == "Fixed") //try referring to cells by column names and not the index \n      countFixed++;\n   else if((string)dgv.Rows[i].Cells[1].Value == "Not Fixed")\n      countUnFixed++;\n}	0
30529074	30528392	Reading a range of cells in an Excel doc gives me an error	xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\bla\blas\users.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);\nxlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);                \n\nRange range1 = worksheet1.Cells[1, 1];\nRange range2 = worksheet1.Cells[3, 3];\n\nRange range = worksheet1.get_Range(range1, range2);\n\nobject[,] valArray = range.Value2 as object[,];\nint xCount = valArray.GetLength(0);\nint yCount = valArray.GetLength(1);\n\nfor (int i = 1; i <= xCount; i++)\n{\n    for (int j = 1; j <= yCount; j++)\n    {\n        object currentValue = valArray[i, j];\n        if (currentValue != null)\n        {\n            Console.WriteLine(currentValue.ToString());\n        }\n    }\n}	0
10290309	10290209	store all the results of a loop in a single string	String.Join(",", (from a in dataGridView1.AsEnumerable() select a.Cells[2].Value.ToString()).ToList())	0
24604763	24604707	How to check string has number as well as two special char only	Regex.IsMatch(input, @"^[\d-\.]+$")	0
14218875	14218855	Values of Boolean array	var Checked = CheckedPart.All(p => p);	0
11054524	11054477	Getting error while store data in sql server 2005 through textbox	String query = "insert into try (data,sno) values (@data,22)"; \nSqlCommand cmd = new SqlCommand(query, conn); \ncmd.Parameters.AddWithValue("@data", TextBox1.text);\ncmd.ExecuteNonQuery();	0
14923528	14910238	Dynamically resolve a resource key	Label lv = (Label)e.Item.FindControl("lbl");\n\n\nResourceManager resMngr = new ResourceManager(typeof(SupertextCommon.Default));\nlv.Text = resMngr.GetObject(someProperty, culture);	0
16118458	16113156	Disable Selecting of Empty Lines in ListBox	private void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n        {\n            if (listBox1.Items.Count > 0)\n            {\n                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)\n                    e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);\n                else\n                    e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);\n\n                string text = listBox1.Items[e.Index].ToString();\n\n                e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top);                \n            }\n        }	0
10928042	10927907	How to get the value of editable column of datagrid and on which event	(your datagridview).Rows[e.RowIndex].Cells[e.ColumnIndex].Value	0
5878067	5853126	Convert to expression	public Expression<Func<Addition, bool>> IsMatch(long additionId)\n    {\n        return a => a.AdditionsPrices.Any(x => x.AdditionId == additionId);\n    }	0
4059975	4059759	How to restrict code in managed tool from executing?	AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n\nWindowsPrincipal user = (WindowsPrincipal)System.Threading.Thread.CurrentPrincipal;\nWindowsIdentity ident = user.Identity;	0
21034536	21034426	How to read same child element types from an XML tree recursively?	private void ParseControlsData()\n{\n    var doc = XDocument.Load("Controls.xml");\n\n    var controls = from control in doc.Element("controls").Elements("control")\n                   select CreateFromXElement(control);\n\n    var controlsList = controls.ToList();\n\n    Console.ReadLine();\n}\n\nprivate Control CreateFromXElement(XElement element)\n{\n    var control = new Control()\n    {\n        Id = (string)element.Attribute("id"),\n        ControlType = (string)element.Attribute("controlType"),\n        SearchProperties = (string)element.Attribute("searchProperties")\n    };\n\n    var childrenElements = element.Element("childControls");\n    if (childrenElements != null)\n    {\n        var children = from child in childrenElements.Elements("control")\n                       select CreateFromXElement(child);\n\n        control.ChildrenControl = children.ToList();\n    }\n\n    return control;\n}	0
34274973	34274849	Assigning a variable enum value	while(reader.Read())\n{\n   Id = Convert.IsDbNull(reader[0]) ? Convert.ToInt32(0) : Convert.ToInt32(reader[0]);\n   Name = Convert.IsDbNull(reader[1]) ? string.Empty : reader[1].ToString();\n   FinalOutcome = Convert.IsDbNull(reader[2]) ? FinalOutcome.DontKnow : (Outcome) Convert.ToInt32(reader[2]);\n}	0
30203035	30203017	C# convert int to English word	Dictionary<int, string> specialNumberNames = new Dictionary<int, string>()\n{\n   {1, "First"},\n   {2, "Second"},\n   ...\n}\n\nint number = 1;\nstring specialName = specialNumberNames[number];	0
33954028	33953985	How can I convert string to Guid?	String source = "e2ddfa02610e48e983824b23ac955632";\n\n  Guid result = new Guid(source);	0
28705209	28704931	Set Text Property of TextBox and Label in Gridview dynamically	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n  if (e.Row.RowType == DataControlRowType.DataRow)\n  {\n     Label lblpsaia = (Label)e.Row.FindControl("lblpsaia");\n     lblpsaia.Text = "Sample Text Here";\n\n     TextBox txtpsaia = (TextBox)e.Row.FindControl("txtpsaia");\n     txtpsaia.Text = "Sample Text Here";\n   }\n}	0
19325454	19325361	Change the access modifier in runtime	MyClass instance = new MyClass();\nMethodInfo yourMethod = instance\n                            .GetType()\n                            .GetMethod("MyMethod", BindingFlags.NonPublic | BindingFlags.Instance);\nvar returnValue = yourMethod.Invoke(instance, new object[] { });\nConsole.WriteLine(returnValue);	0
22843908	22843788	How do i use net user inside a C# console program?	enable_admin.StartInfo.Arguments = "user " + "administrator " + "/active:yes";\n                                                               ^----\n    enable_admin.StartInfo.FileName = @"C:\Windows\System32\net";\n    disable_admin.StartInfo.Arguments = "user " + "administrator " + "/active:no";\n                                                                ^----\n    disable_admin.StartInfo.FileName = @"C:\Windows\System32\net";	0
7321086	7321058	How to display words that appear more than 'x' times in a text?	string text = "yay blah blah blah blah woo woo yay yay yay.";\n\nvar words = Regex.Split(text, @"\W+")\n    .AsEnumerable()\n    .GroupBy(w => w)\n    .Where(g => g.Count() > 3)\n    .Select(g => g.Key);\n\nwords.ToList().ForEach(Console.WriteLine);	0
2595411	2595365	Marshaling an array of IntPtrs in C#	[DllImport("blah.dll")]\nprivate static extern void SomeFunction(IntPtr[] array);	0
3333365	3309539	.NET Xml Serialization: Integer Element with Attribute?	class BarId\n{\n    [XmlText()]\n    public int Content {get; set;}\n\n    [XmlAttribute()]\n    public string BarString {get; set;}\n}\n\npublic class Foo{\n    public BarId BarId {get; set;}\n}	0
13392035	13391878	Converting query to Lambda Expression	List<string> containerTypes = productInRepository\n                .Where(x => x.containerType != string.Empty)\n                .OrderBy(x => x.containerNo)\n                .Select(x => x.containerType.Trim())\n                .Distinct();	0
1196069	1195828	C#: Produce a continuous tone until interrupted	private void button1_Click(object sender, EventArgs e)\n{\n    // Starts beep on background thread\n    Thread beepThread = new Thread(new ThreadStart(PlayBeep));\n    beepThread.IsBackground = true;\n    beepThread.Start();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    // Terminates beep from main thread\n    Console.Beep(1000, 1);\n}\n\nprivate void PlayBeep()\n{\n    // Play 1000 Hz for 5 seconds\n    Console.Beep(1000, 5000);\n}	0
13415063	13414564	How to override SortedList Add method for sorting by value	private MySortedList()\n{\n}\n\npublic override void Add(object key, object value)\n{\n    if (key == null || value == null)\n    {\n        //throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));\n        throw new ArgumentNullException(); // build your own exception, Environment.GetResourceString is not accessible here\n    }\n\n    var valuesArray = new object[Values.Count];\n    Values.CopyTo(valuesArray , 0);\n\n    int index = Array.BinarySearch(valuesArray, 0, valuesArray.Length, value, _comparer);\n    if (index >= 0)\n    {\n        //throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", new object[] { this.GetKey(index), key }));\n        throw new ArgumentNullException(); // build your own exception, Environment.GetResourceString is not accessible here\n    }\n\n    MethodInfo m = typeof(SortedList).GetMethod("Insert", BindingFlags.NonPublic | BindingFlags.Instance);\n    m.Invoke(this, new object[] {~index, key, value});\n}	0
11983465	11982957	Add enums to a list according to the value received back from database	Permissions = \n    new Func<DataRow, List<Permission>>(permissionData =>\n    {\n        List<Permission> permissions = new List<Permission>();\n        // do all your if checks here to add the necessary permissions to the list\n        return permissions;\n    })(data[0])	0
14108372	14108258	Making elements changeable from references	public  void GetBehavior(string behaviorName, ref TutorialPopupBehavior b) {\n            foreach(TutorialPopupBehavior beh in _tutorialItems) {\n                if(beh._popupName == behaviorName) {\n                    b = beh;\n                     Return;\n                }\n            }\n            print ("Could not find behavior of name " + behaviorName);\n            b = null;\n        }	0
16963428	16926046	Lambda scope for Entity_Filter Method - MS Lightswitch 2012	filter = TL => TL.CreditDepartment.PermissionsGlues.Any(g => g.User.UserName == Application.User.Name);	0
9550963	9550892	how can append to xml	string xml =\n   @"<project>\n        <user>\n           <id>1</id>\n           <name>a</name>\n        </user>\n        <user>\n           <id>2</id>\n           <name>b</name>\n        </user>\n     </project>";\n\nXElement x = XElement.Load(new StringReader(xml));\nx.Add(new XElement("user", new XElement("id",3),new XElement("name","c") ));\nstring newXml = x.ToString();	0
34418876	34418362	Sid of local group in machine	WinNT://MACHINENAME/	0
22627048	22626783	Subtract array values of Object	Warrior warrior = new Warrior(25,24);\n        Warrior warrior1 = new Warrior(20,20);\n\n        Cell[,] cells = new Cell[6, 6];\n        cells[3, 5] = new Cell(warrior);\n        cells[5, 4] = new Cell(warrior1);\n\n        int x1 = cells[3, 5]._x - cells[5, 4]._x;\n        int x2 = cells[3, 5]._y - cells[5, 4]._y;\n        Console.WriteLine(x1);\n        Console.WriteLine(x2);\n\n public class Cell\n{\n    public Cell(Warrior warrior)\n    {\n        _x = warrior.x;\n        _y = warrior.y;\n    }\n\n    public int _x;\n    public int _y;\n    public Warrior _warrior;\n}\n\npublic class Warrior\n{\n    public Warrior(int x, int y)\n    {\n        this.x = x;\n        this.y = y;\n    }\n\n    public int x;\n\n    public int y;\n}	0
1427854	1427819	C#: Getting value via reflection	var parser = new CSharpParser();\nvar context = new CSharpContext();\n\ncontext["car"] = carobject;\n\nstring brandNameOfCar = \n          parser.Evaluate<string>("car.brand.name.ToFormatedString()", context);	0
7748211	7747774	Can I use a DataGridView in a Windows Service?	if (ServerTableDay.Count > 0) {\n     testGrid.DataSource = ServerTableDay;\n}	0
29708097	29604673	JavaScript with WebBrowser control C#	HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];\nHtmlElement scriptEl = webBrowser1.Document.CreateElement("script");\nIHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\nelement.text = script;//script is your script which you defined\nhead.AppendChild(scriptEl);	0
440636	440570	How do I detect if jQuery is in a document navigated to in the WinForm WebBrowser control?	bool hasjQuery = webBrowser1.Document.InvokeScript("jQuery") != null;	0
15232687	15232639	Select from table, then insert that (value + 1) into another table?	INSERT INTO yourOtherTable ( reqId ) \nSELECT reqID + 1 \nFROM RequestID	0
6960314	6960263	Using the Expression API, is there a way to "combine" a Func<T> with another?	Func<T> myProp = () => \n{ \n  //run your code here\n  return func();\n}	0
24032081	24031982	Convert string into datetime in razor view with javascript?	if(new Date("your date string") <= Date.now)\n{\n    // your code\n}	0
8358749	8358108	XML Object Serialization on Collection At Root Level	XmlSerializer serializer = new XmlSerializer(typeof(Animal[]), new XmlRootAttribute("Animals"));\n\npublic class Animal\n{\n    [XmlElement]\n    public string Name;\n    [XmlElement]\n    public string Type;\n}	0
1683971	1683934	How can I make an image grow x % on mouseover event in wpf?	private void image1_MouseEnter(object sender, MouseEventArgs e)\n{\n    Image img = ((Image)sender);\n    img.Height = img.ActualHeight * 1.1;\n\n}\n\nprivate void image1_MouseLeave(object sender, MouseEventArgs e)\n{\n    Image img = ((Image)sender);\n    img.Height /= 1.1;\n}	0
28661346	28661328	WPF Telerik :Remove Vertical Column on left side of the gridview	RowIndicatorVisibility="Collapsed"	0
32743764	28174643	Utilizing Override in UserControl to Change Property Breaks Trigger	protected override void OnPreviewKeyDown(KeyEventArgs e)\n{\n    if (e.Key == Key.Enter)\n    {\n        if (Text.StartsWith(DecoderPrefix))\n            SetCurrentValue(TextProperty, Text.Remove(0, DecoderPrefix.Length));\n    }\n\n    base.OnPreviewKeyDown(e);\n}	0
2319832	2319008	How to map a case insensitive dictionary to NHibernate.?	NHibernate.Collection.PersistentGenericMap<TKey, TValue>	0
13275404	13274936	A Form's key events go missing	Application.AddMessageFilter(...)	0
26374970	26374806	Cast to base class from derived class	MyBaseClass mybc = new MyBaseClass();	0
21980918	21974472	How to make a GameObject upside down through code?	using UnityEngine;\nusing System.Collections;\n\npublic class Example : MonoBehaviour {\n    void Update() {\n        transform.Rotate(Vector3.right, Time.deltaTime);\n        transform.Rotate(Vector3.up, Time.deltaTime, Space.World);\n    }\n}	0
6687936	6659457	how to set dropdownlist height and how to show dropdownlist's list always downward display	cbo.Height = new Unit("250px");	0
34270899	34270678	Search list of objects for maximum value by date	foreach(var item in ItemList)\n{\n    AnotherFunction(item.ItemId, item.ItemDate, ItemList.Where(x => x.ItemDate == item.ItemDate)\n                                                        .OrderByDesc(z => Convert.ToInt32(z.ItemPrice.Replace("$", "")))\n                                                                                 .First().ItemPrice);\n}	0
27932129	27931880	Parse JSON string with C#	{\n  "C:\\workspace\\folder\\test\\added.txt": "synced",\n  "C:\\workspace\\folder\\test\\pending.test": "pending"\n}	0
22728884	22728828	Move Images from ladder Sub folders to Main Folder using C#	public static void MoveFilesToMain(string sourceDirName, string destDirName)\n    {\n        DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n        DirectoryInfo[] dirs = dir.GetDirectories();\n\n        FileInfo[] files = dir.GetFiles();\n\n        if (files.Length == 0 && dirs.Length == 0)\n        {\n          Directory.Delete(sourceDirName, false);\n          return;\n        }\n\n        foreach (FileInfo file in files)\n        {          \n            File.Move(Path.Combine(sourceDirName, file.Name), Path.Combine(destDirName, file.Name));\n        }\n\n        foreach (DirectoryInfo subdir in dirs)\n        {\n          MoveFilesToMain(subdir.FullName, destDirName)\n        }\n    }	0
313080	313030	Rhino Mocks: How to return conditonal result from a mock object method	Expect.Call(sqr.CanRender(null)).IgnoreArguments()\n    .Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})\n    .Repeat.Any();	0
18111094	18028233	Entity Framework Saving One to One relation in Table Splitting	if (file != null && file.ContentLength > 0)\n{\n    BinaryReader b = new BinaryReader(file.InputStream);\n    byte[] binData = b.ReadBytes((int)file.InputStream.Length);\n\n    var customerDoc = new CustomerDoc { CustomerID = customer.CustomerID, Document = binData };\n    db.Entry(customerDoc).State = EntityState.Modified;\n    db.SaveChanges();\n}	0
28062029	28049187	Multiple selection ListView	public IEnumerable<City> SelectedCities{ get { return CityList.Where(x => x.IsSelected && x.Country == SelectedCountry); } }	0
9072779	9072519	2 forms in a button WINFORM	// untested...\nfirstForm.Show();\nif (secondForm.ShowDialog() != DialogResult.Ok)\n{\n    firstForm.Close();\n}	0
22415386	22415136	In a WPF Program, I want to change the Stroke Color on all the "Lines" on a "Canvas"	foreach (FrameworkElement Framework_Element in My_Canvas.Children)\n  {\n    // tries to find .Stroke on the FrameworkElement class\n    // (Line)Framework_Element.Stroke\n\n    // correct way\n    ((Line)Framework_Element).Stroke = new SolidColorBrush(Colors.Black);\n\n    // or\n\n    var currentLine = (Line)Framework_Element;\n    currentLine.Stroke = new SolidColorBrush(Colors.Black);\n  }	0
17236302	17233702	Get child node values at XElement	XElement xe = client.QueryXml("SELECT Uri FROM Orion.Pollers WHERE NetObjectID = 15", null);\n\n    IList<XElement> indexedElements = xe.Elements().ToList();\n\n    foreach (var item in ((XElement)xe.Elements().ToList()[1]).Elements().ToList())\n    {\n        try\n        {\n            //Do something with \n            //item.Value\n        }\n        catch (Exception exc)\n        {\n            throw exc;\n        }\n\n\n    }	0
15584155	15584135	Add default options to anonymous list - Linq	var RecordList = objContext.Categories\n    .Select(c => new { DisplayText = c.CatName, Value = c.CategoryId })\n    .ToList();\nRecordList.Insert(0, new { DisplayText = "-- Select --", Value = 0 });	0
24338745	24338735	check if the all values of array are different	// 1\nvalues.Distinct().Count() == values.Length;\n\n// 2\nnew HashSet<int>(values).Count == values.Length;\n\n// 3.1\n!values.Any(x => values.Count(y => x == y) > 1);\n\n\n// 3.2\nvalues.All(x => values.Count(y => x == y) == 1);	0
27923960	27921606	c# How to generate and stream a pdf file to browser on the fly without ever having to write to a local directory	using (MemoryStream ms = new MemoryStream())\n{\n    Document doc = new Document(PageSize.A4, 50, 50, 15, 15);\n\n    PdfWriter writer = PdfWriter.GetInstance(doc, ms);\n\n    //You need to actually write something to the document here...\n\n    return ms.ToArray();\n}	0
10588687	10588601	Checking For null in Lambda Expression	var allItems = itemsList\n                 .Where(s => string.IsNullOrEmpty(s[Constants.ProductSource])\n                             || s[Constants.ProductSource] == source)\n                 .ToList()	0
23569167	23568326	labeling a legend in epplus	lineChart.Series[0].Header = "Series 1 Name";	0
6862069	6862035	LINQ to XML Select Statement - No Results	XNamespace ns = "http://tempuri.org/TestDataset.xsd";\nXDocument data = LoadTestData("TaxRate.xml");\nvar taxdata = (from x in data.Descendants(ns + "TaxRate")\n              select new\n              {\n                  Code = x.Element(ns + "Code").Value,\n                  Rate = x.Element(ns + "Rate").Value,\n                  AbbreviationEN = x.Element(ns + "AbbreviationEN").Value,\n                  AbbreviationFR = x.Element(ns + "AbbreviationFR").Value,\n                  GLSubCode = x.Element(ns + "GLSubCode").Value\n               }).ToList();	0
11279632	11279590	GridView Access Data Source	OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\YOUR_ACCESS_FILE_PATH");\nconn.Open();\nOleDbCommand cmd = new OleDbCommand("SELECT * FROM cartTable WHERE orderNo = " + intOrderNo , conn);\nOleDbDataReader reader = cmd.ExecuteReader();\nDataTable dt = new DataTable();\ndt.Load(reader);\n\n//Bind your grid\nthis.gridView1.DataSource = dt;\nthis.gridView1.DataBind();	0
24223911	24223680	C# script to clean file takes a long time to execute	string tempFile = Path.GetTempFileName();\nstring fileName = Dts.Variables["User::File_Name_Path_4"].Value.ToString();\nusing (var writer = new StreamWriter(tempFile))\nusing (var reader = new StreamReader(fileName))\n{\n    while(!reader.EndOfStream)\n    {\n        writer.WriteLine(reader.ReadLine().Replace("#Fields: ", ""));\n    }\n}\nFile.Delete(fileName);\nFile.Move(tempFile, fileName);	0
9091473	9091370	Send parameter as arrays in Webservice	foreach (string value in txtproductCode)\n    {\n        // process the value\n               string productCode = value ;\n    }	0
19904600	19903115	Google Analytics from C#	var userId = @User.Id;\nga('set', 'dimension1', userId);	0
13079384	13022425	Append Whitespace to stringbuilder Left Justified	sb.AppendFormat("{0,-15}", "TEST");	0
23987975	23987963	comma separated string to List<int> in C#	var list = input.Split(',').Select(Convert.ToInt32).ToList();	0
10548670	10548590	Find most identical string in string collection	string str = "Arial Bold Itali";\n\nif(str.StrartWith("Arial"))\n{\n   return str;\n}	0
33775749	33775604	How to List candidate word	List<string> strings = new List<string>()\n{\n    "abc", \n    "abb", \n    "acc", \n    "acb", \n    "zx",\n    "zxc", \n    "zxx", \n    "caa", \n    "cba", \n    "ccc",\n};\nstring input = "ab";// <= or whatever\nforeach (string foundString in strings)\n{\n    if (foundString.StartsWith(input))\n    {\n        Console.Out.WriteLine(foundString);\n    }\n}	0
1735775	1735763	Change the settings of a single NIC using WMI (C#)?	foreach(ManagementObject objMO in objMOC) \n{ \n    if(!(bool)objMO["ipEnabled"]) \n        continue;\n\n    if(!string.Equals(objMO["MACAddress"], "00:ff:xx:xx:xx:xx"))\n        continue;\n\n    // change settings\n\n    break;\n}	0
12866176	12865994	Display progress as percentage	int incrementAmount = total_results/100;\nif (progress % incrementAmount) { percentage++; }	0
31560838	31560452	Change MS Excel Row Colour in Excel using C#	Excel.Application application = new Excel.Application();\n                Excel.Workbook workbook = application.Workbooks.Open(@"C:\Users\MyPath\Desktop\ColorBook.xls");\n                Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["DailyWork"];\n                Excel.Range usedRange = worksheet.UsedRange;\n                Excel.Range rows = usedRange.Rows;\n                try\n                {\n                    foreach (Excel.Range row in rows)\n                    {\n                        if (row.Cells.EntireRow.Interior.ColorIndex == -4142)\n                        {\n                            row.Interior.Color = System.Drawing.Color.Red;\n                        }\n                    }\n                    workbook.Save();\n                    workbook.Close();\n                }\n                catch (Exception ex)\n                {\n                    MessageBox.Show(ex.ToString());\n                }	0
5395921	5395764	How to send a webrequest to default browser from WPF application?	Uri uri = new Uri("http://services.mysite.com/document/documentservice.svc");\nHttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);       \n\nHttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];\nCookie authenticationCookie = new Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority);\n\nwebRequest.CookieContainer = new CookieContainer();\nwebRequest.CookieContainer.Add(authenticationCookie);\nWebResponse myResponse = webRequest.GetResponse();\nStream stream = myResponse.GetResponseStream();	0
18482551	18482460	How convert TimeSpan to 24 hours and minutes String?	myTimeSpan.ToString(@"hh\:mm")	0
14681461	14681437	Is it acceptable to inherit from a class just for clarity?	GenericDatabase<string, CharacterStat>	0
26308445	25525234	ETW Logging - TraceEventSession overwrites file	var _etwSession = new TraceEventSession("MyEtwLog", @"C:\Logs\MyEtwLog." + MyTimestamp + ".etl");\n_etwSession.EnableProvider(new Guid("MyGuid"), TraceEventLevel.Always);\n\nThread.Sleep(1000 * 60);\n\n_etwSession.SetFileName(@"C:\Logs\MyEtwLog" + timestamp + ".etl");	0
3036891	3036871	Convert Int List Into Integer	int total = 0;\nforeach (int entry in list)\n{\n    total = 10 * total + entry;\n}	0
8918540	8918478	How do I list all images in a folder using C#?	DirectoryInfo di = new DirectoryInfo(@"C:\YourImgDir");\n\nFileInfo[] Images = di.GetFiles("*.jpg");	0
4750713	4750680	How to get to page1 when I refresh my gridview?	mygridView.PageIndex = 0;	0
27677231	27676984	Getting all rows from a column of an sql db using asp.net?	while(dr.HasRows)\n    {\n        dr.Read();\n        label.Text = dr[0].ToString() + "<br />";   \n    }	0
19059299	19058873	How can I show Currency with Negative instead of Parentheis in ASP NET MVC?	protected void Application_BeginRequest(object sender, EventArgs e)\n        {\n\n            CultureInfo culture = new CultureInfo("en-us");\n            culture.NumberFormat.CurrencyNegativePattern = 1;    \n\n            Thread.CurrentThread.CurrentUICulture = culture;\n            Thread.CurrentThread.CurrentCulture = culture;\n        }	0
3228965	3228809	how to wordwrap text in tooltip	[ DllImport( "user32.dll" ) ] \nprivate extern static int SendMessage( IntPtr hwnd, uint msg,\n  int wParam, int lParam); \n\nobject o = typeof( ToolTip ).InvokeMember( "Handle",\n   BindingFlags.NonPublic | BindingFlags.Instance |\n   BindingFlags.GetProperty, \n   null, myToolTip, null ); \nIntPtr hwnd = (IntPtr) o; \nSendMessage( hwnd, 0x0418, 0, 300 );	0
18361235	18244499	How to keep personalization when moving class derived from WebPartManager to new assembly?	// Read the 'PageSettings' column from the ASP personalization tables\n// into a byte array variable called 'rawData' first. Then continue:\n\nvar mems = new System.IO.MemoryStream(rawData);\nvar formatter = new System.Web.UI.ObjectStateFormatter();\nvar oldState = formatter.Deserialize(mems) as object[];\n\nvar index = oldState.ToList()\n                    .FindIndex(o =>\n                        o as Type != null &&\n                        ((Type)o).Name.Contains("WebPartManager"));\n\n// In our case, the derivative class name is "MyWebPartManager", you\n// may need to change that to meet your requirements\n\noldState[index] = typeof(WebPartManager);\n\nmems = new System.IO.MemoryStream();\nformatter.Serialize(mems, oldState);\nvar newState = mems.ToArray();\n\n// Write 'newState' back into the database.	0
19837174	19836924	Ignore a nunit test based on the data that is loaded in TestCaseSource	public static void Assert(Func<bool> cond, string message = "")\n{\n    if(cond())\n    {\n        Assert.Ignore(message);\n    }\n}	0
4539420	4538147	EntityDataSource with a GridView WHERE Explnation	Guid myActiveUser = (Guid)Membership.GetUser().ProviderUserKey;    \nEntityDataSource1.Where = "it.User = " + myActiveUser.ToString();	0
9106593	9106566	Get days as an int from a timespan?	var span = someDate.Subtract(anotherDate);\n int days = span.Days;	0
26612591	26583904	Set default font in Outlook with an addin	Word.Application oWord = new Word.Application();\nWord.EmailOptions oOptions;\noOptions.ReplyStyle.Font.Name = "Arial";\noOptions.ReplyStyle.Font.Size = 10;\n\noOptions.ComposeStyle.Font.Name = "Arial";\noOptions.ComposeStyle.Font.Size = 10;	0
32562144	32561949	Length of a string in c# WinForm	if (Textbox1.Text.StartsWith("a")) {\n    // do stuff\n    ...\n  }	0
12751045	12750915	Keep an application running	private readonly ManualResetEvent _shutdownEvent = new ManualResetEvent(false);\nprivate Thread _thread;\n\npublic MyService()\n{\n    InitializeComponent();\n}\n\nprotected override void OnStart(string[] args)\n{\n    _thread = new Thread(MonitorThread)\n    {\n        IsBackground = true\n    }\n}\n\nprotected override void OnStop()\n{\n    _shutdownEvent.Set();\n    if (!_thread.Join(5000))\n    {\n        _thread.Abort();\n    }\n}\n\nprivate void MonitorThread()\n{\n    while (!_shutdownEvent.WaitOne(5000))\n    {\n        Process[] pname = Process.GetProcessesByName("PipeServiceName.exe");\n        if (pname.Count == 0)\n        {\n             // Process has stopped. ReLaunch\n             RelaunchProcess();\n        }\n     }\n}\n\nprivate void RelaunchProcess()\n{\n    Process p = new Process();\n\n    p.StartInfo.FileName = "PipeServiceName.exe";\n    p.StartInfo.Arguments = ""; // Add Arguments if you need them\n\n    p.Start();\n}	0
9330969	9301528	c# How to get an overrided Panel to work inside a User Control	this.Attributes.Add("onclick", "__doPostBack('" + this.UniqueID + "', '');");	0
16551104	16550986	In need of some advice controlling a C# winforms application via a asp.net website	int seconds = 4;\nSystem.Timers.Timer _clientTimer = new System.Timers.Timer(seconds * 1000);\n_clientTimer.AutoReset = false;\n_clientTimer.Elapsed += clientTimer_Elapsed;\n_clientTimer.Start();\n\nprivate void clientTimer_Elapsed(object sender, ElapsedEventArgs e)\n{\n    try\n    {\n        // Connect to web service, get status, if status != 0 do something...\n    }\n    finally\n    {\n        _clientTimer.Start();\n    }\n}	0
8889145	8866614	Automatically Setting Internet Explorer/Windows to use a Socks5 proxy using C#	PoshHttp.Proxies.SetProxy("socks=socks://$ip:$port");	0
12045038	12044929	Searching for partial substring within string in C#	(int)(input.Length * 0.88m)	0
33178833	33178596	EventHandler Library with asynchronous, infinite loop and global variable locking	public static bool IsConnected { get; protected set; }\n    protected readonly static object _sync = new object();\n    protected static Task NetworkTask;\n\n    public static void Start(int period = 1000)\n    {\n        NetworkTask = Task.Run(() =>\n            {\n                lock (_sync)\n                {\n                    IsConnected = MyNetworkManager.IsConnected();\n                    System.Threading.Thread.Sleep(period);\n                }\n            });\n    }	0
20395079	20394962	Transfer bitmap from C# server program over TcpClient to Java Socket gets corrupted	int bytesRead;\nwhile ((bytesRead = in.read(buf)) != -1) {\n    outStream.write(buf, 0, bytesRead);\n}	0
11258922	11012826	Deploying a XML Web Service with UDP other than HTTP	string IPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];\nstring port = HttpContext.Current.Request.ServerVariables["REMOTE_PORT"];\nif (IPAddress == null)\n{ \n            IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];\n}	0
31862876	31862767	Entity Framework not sure how to retrieve Guid from one table to use in another	context.Department.AddOrUpdate(x => x.Id,\nnew Department() { Id = Guid.NewGuid(), Name = "System", ImageNameLight = "", ImageNameDark = "" },\nnew Department() { Id = Guid.NewGuid(), Name = "Estimating", ImageNameLight = "", ImageNameDark = "" },\nnew Department() { Id = Guid.NewGuid(), Name = "Assembly", ImageNameLight = "dep-assy-off", ImageNameDark = "dep-assy-on" },\nnew Department() { Id = Guid.NewGuid(), Name = "Project Engineering", ImageNameLight = "dep-pe-off", ImageNameDark = "dep-pe-on" },\n);\n\ncontext.SaveChanges();\n//Do whatever with your new context	0
13748602	13748601	Generic with multiple constraints	public class MyClass<T> where T : BaseClass, IInterface\n{\n    public MyClass(T value)\n    {\n        Register(value);\n    }\n}	0
23547077	23546987	checking for values in multiple if statement and storing multiple comments based on results	var shirtAttributes = new List<string>();\nif (shirt.IsBlack)\n{\n    shirtAttributes.Add("black");\n}\nif (shirt.IsLarge)\n{\n    shirtAttributes.Add("large");\n}\nif (shirt.IsLongSleeve)\n{\n    shirtAttributes.Add("long sleeve");\n}\nvar shirtAttributesString = string.Join(",", shirtAttributes);	0
4219483	4210658	What would be a walkaround for JavaScript alerts that are generated in a page's onload() using Selenium?	selenium.Click("ctl00_Content_ctl00_btnSubmit");                        \n    Thread.Sleep(5000);\n    selenium.KeyDownNative("32");\n    selenium.KeyUpNative("32");	0
2972085	2943633	How to add a string array to a node in xml c#	XmlNode node = xdoc.SelectSingleNode(path);            \n\nforeach(string x in val)\n{\n    XmlNode subNode = xdoc.CreateNode(XmlNodeType.Element, subNodeName, null);\n    subNode.InnerText = x;\n    node.AppendChild(subNode);\n}	0
16009567	16009515	How to Add Column infront of another column through Code Behind?	Grid layoutRoot = new Grid();\n layoutRoot.ColumnDefinitions.Insert(0, new ColumnDefinition() { Width = new GridLength(0, GridUnitType.Star) });	0
27407783	27407169	C# Replace with regex	string exp = "(?<=,\")([^\"]+,[^\"]+)(?=\",)";\nvar regex = new Regex(exp); \nstring replacedtext = regex.Replace(filecontents, m => m.ToString().Replace(",",""))	0
2432348	2432281	Get sum of two columns in one LINQ query	from p in m.Items\ngroup p by 1 into g\nselect new\n{\n    SumTotal = g.Sum(x => x.Total), \n    SumDone = g.Sum(x => x.Done) \n};	0
7386422	7381508	Determining whether a service is already installed	private static bool IsServiceInstalled(string serviceName)\n    {\n        ServiceController[] services = ServiceController.GetServices();\n        foreach (ServiceController service in services)\n            if (service.ServiceName == serviceName) return true;\n        return false;\n    }\n\n    private static bool IsServiceInstalledAndRunning(string serviceName)\n    {\n        ServiceController[] services = ServiceController.GetServices();\n        foreach (ServiceController service in services)\n            if (service.ServiceName == serviceName) return service.Status != ServiceControllerStatus.Stopped;\n        return false;\n    }	0
28067243	28067196	SortedSet - custom order when storing a class object	internal class SortedIndex\n{\n    public double Comparable { get; set; }\n    public int Index { get; set; }\n}\n\ninternal class SortedIndexComparar : IComparer<SortedIndex>\n{\n    public int Compare(SortedIndex x, SortedIndex y)\n    {\n        return x.Comparable.CompareTo(y.Comparable);\n    }\n}	0
18683922	18683775	Split wrapped text into array	public List<string> GetSubstrings(string toSplit, int maxLength, Graphics graph, Font font)\n{\n     List<string> substrings = new List<string>();\n     string[] words = toSplit.Split(" ".ToCharArray());\n     string oneSub = "";\n     foreach (string oneWord in words)\n     {\n        string temp = oneSub + oneWord + " ";\n\n        if (graph.MeasureString( temp, font).Width > maxLength) \n        {\n           substrings.Add(oneSub);\n           oneSub = oneWord + " ";\n        }\n        else\n           oneSub = temp;\n     }\n     substrings.Add(oneSub);\n     return substrings;\n}	0
17814705	17814648	C# - Create a 2D Array and then loop through it	int[,] array = new int[row, column];\n            Random rand = new Random();\n\n            for (int i = 0; i < row; i++)\n            {\n                for (int j = 0; j < column; j++)\n                {\n                    array[i, j] = rand.Next(0, 10);\n\n                }\n            }	0
4567065	4567023	Setting String as Image Source in C#	Uri uri = new Uri("...", UriKind.Absolute); \nImageSource imgSource = new BitmapImage(uri); \nmyImage.Source = imgSource;	0
8356396	8356334	Parseing regex with groups and subgroups?	(?m)^(?<Stars>\*+)|(?<Date>\d{1,2}/\d{1,2} \d{2})	0
13906050	13906032	Concatenate 3 lists of words	var list = from s1 in list1\n           from s2 in list2\n           from s3 in list3\n           select s1 + " " + s2 + " " + s3;	0
18093807	18091421	DelegateFactories don't return a new object(Unit of Work pattern)	builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();	0
13930638	13915623	Setting OperationTimeout on Wcf RoutingService	// add the endpoint the router uses to receive messages\n            serviceHost.AddServiceEndpoint(\n                 typeof(IRequestReplyRouter),\n                 new BasicHttpBinding(), \n                 "http://localhost:8000/routingservice/router");\n\n            // create the client endpoint the router routes messages to\n            var client = new ServiceEndpoint(\n                                            ContractDescription.GetContract(typeof(IRequestReplyRouter)), \n                                            new NetTcpBinding(),\n                                            new EndpointAddress("net.tcp://localhost:8008/MyBackendService.svc"));\n\n            // Set SendTimeout, this will be used from the router generated proxy as OperationTimeout\n            client.Binding.SendTimeout = new TimeSpan(0, 10, 0);	0
23327309	23326967	Adding to database using Oledb Syntax error in INSERT INTO statement	cmd.Parameters.AddWithValue("@Price", Convert.ToDecimal(TextBox3.Text));	0
22244098	22239849	Using an ExpandableObjectConverter on a Generic class for a PropertyGrid	Type steppedValueType = iTypeDescriptorContext.PropertyDescriptor.PropertyType.GetGenericArguments()[0];	0
12539875	11886217	Metro app using socketstream to write to Win32 TCPListener in C#	private StreamSocketListener listener;\n\nprivate async void Test()\n{\n    listener = new StreamSocketListener();\n    listener.ConnectionReceived += OnConnection;\n    await listener.BindServiceNameAsync(port.ToString());\n}\n\nprivate async void OnConnection(StreamSocketListener sender,\n    StreamSocketListenerConnectionReceivedEventArgs args)\n{\n    // Streams for reading a writing.\n    DataReader reader = new DataReader(listener.InputStream);\n    DataWriter writer = new DataWriter(socket.OutputStream);\n\n    writer.WriteString("Hello");\n    await writer.StoreAsync();\n}	0
6385232	6385205	How do I override the setter method of a property in C#?	public virtual Vector2 Position	0
24982888	24982014	Windows Phone 8 : How to load content for each pivot item using MVVM?	if (SystemTray.ProgressIndicator == null)\n{\n    var indicator = new ProgressIndicator { IsIndeterminate = true };\n    var visibilityBinding = new Binding("ProgressBarIsActive");\n    BindingOperations.SetBinding(indicator, ProgressIndicator.IsVisibleProperty, visibilityBinding);        \n    SystemTray.SetProgressIndicator(this, indicator);	0
8756323	8756167	How to simulate Left click in WPF from inside the event handler of right click	this.grid1 = ((System.Windows.Controls.Grid)(target));\nthis.grid1.MouseLeftButtonDown += new MouseButtonEventHandler(grid1_MouseLeftButtonDown);\nthis.grid1.MouseRightButtonDown += new MouseButtonEventHandler(grid1_MouseRightButtonDown);\n\n\nvoid grid1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)\n{\n   if( leftClicked < (e.Timestamp - maxTimeBetweenClicks) )\n   {\n      MouseButtonEventArgs fakeLeftMouse = new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, e.LeftButton);\n      grid1_MouseLeftButtonDown(sender, e);\n   }\n\n   leftClicked = 0;\n   throw new NotImplementedException();\n}\n\nvoid grid1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n{\n   leftClicked = e.Timestamp;\n\n   throw new NotImplementedException();\n}	0
15769343	15768830	Find properties of an object that are dictionary whose keys are of certain type	public static TSource DoDictionaries<TSource, TValue>(TSource source, Func<TValue, TValue> cleanUpper)\n    {\n        Type type = typeof(TSource);\n\n        PropertyInfo[] propertyInfos = type\n            .GetProperties()\n            .Where(info => info.PropertyType.IsGenericType &&\n                           info.PropertyType.GetGenericTypeDefinition() == typeof (Dictionary<,>) &&\n                           info.PropertyType.GetGenericArguments()[1] == typeof (TValue))\n            .ToArray();\n\n        foreach (var propertyInfo in propertyInfos)\n        {\n            var dict = (IDictionary)propertyInfo.GetValue(source, null);\n            var newDict = (IDictionary)Activator.CreateInstance(propertyInfo.PropertyType);\n            foreach (var key in dict.Keys)\n            {\n                newDict[key] = cleanUpper((TValue)dict[key]);\n            }\n            propertyInfo.SetValue(source, newDict, null);\n        }\n\n        return source;\n    }	0
21730652	21730261	My form loses focus after button click in c#	private void button1_Click(object sender, EventArgs e)\n    {\n        this.ActiveControl = null;\n    }	0
6910961	6902133	Accessing child controls that are in a templated user control ASP.NET	public partial class BaseFormControl : System.Web.UI.UserControl\n{\n\n\n\n[TemplateContainer(typeof(ContentContainer))]\n[PersistenceMode(PersistenceMode.InnerProperty)]\n[TemplateInstance(TemplateInstance.Single)]\npublic ITemplate Content { get; set; }\n...	0
9414275	9413701	Create bitmap from binary data	Bitmap bmp = new Bitmap(16, 14);\nint line=0;\n\nfor (int i = 0; i < pixels.Length; i++)\n{\n    for (int j = 0; j<8; j++)\n    {\n        if (((pixels[i] >> j) & 1) == 1)\n        {\n            bmp.SetPixel( (i%2)*8 + 7-j, line, Color.Black);\n        }\n    }\n    if(i%2==1) line++;\n}	0
13064863	13064625	Fetch Row contents of a table	Request.Form[]	0
231412	231323	convert XmlNode to XNode?	XmlNode myNode;\nXNode translatedNode = XDocument.Parse(myNode.OuterXml);	0
26818060	26817718	Get value of prefer-32bit flag from assembly	Assembly assembly = Assembly.LoadFile(file);\nModule manifest = assembly.ManifestModule;\nPortableExecutableKinds kind;\nImageFileMachine platform;\nmanifest.GetPEKind(out kind, out platform);\nif((kind & PortableExecutableKinds.Preferred32Bit) != 0)\n{\n    //is Prefer-32bit\n}	0
5675719	5675673	Without using "fixed", how do I access values of an array within a struct?	[StructLayout(LayoutKind.Sequential)]\npublic struct BIRDFRAME\n{\n    public uint dwTime;\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst=127)] \n    public BIRDREADING[] readings; \n}	0
17787659	17782998	ORA-01036: illegal variable name/number for a simple query	string strSql=string.Format("select * from tblUser where UserName like {0} || '%'",":Name");	0
8812006	8811901	c# Convert a string to 2 doubles	public double[] Convert(string parm)\n{\n    //input shall be: string s = x12y04;\n    //inp s looks like x12y04\n\n    //splut the string on the Y (so this tech should also work for x89232y329)\n    //so this will create res[0] that is x89232 and an res[1] that is 329\n    string[] res = parm.Split(new string[] { "y" }, StringSplitOptions.RemoveEmptyEntries);\n    //now for the x in res[0], we replace it for a 0 so it are all numbers\n    string resx = res[0].Replace("x", "0");\n\n    //now we will get the strings to doubles so we can really start using them.\n    double x = double.Parse(resx);\n    double y = double.Parse(res[1]);\n\n    //get the values back\n    return new double[] { x, y };\n\n}	0
4340858	4340824	Are there any interfaces shared by value types representing numbers?	p1.X+p2.X	0
16869768	16869717	Convert DateTime and Boolean to string	Items.Add( new ItemViewModel\n {\n\n        LineOne = check.ClientName,\n        LineTwo = check.NSMDateTime.ToString(),\n        LineThree = check.HaveRead.ToString(),\n        MyappId = check.MonitoringID\n });	0
27719740	27719576	Retrieve "property getter" from the property name	var delegateType = typeof(Func<>).MakeGenericType(propInfo.PropertyType);\nvar deleg = propInfo.GetMethod.CreateDelegate(delegateType, instance);	0
11838666	11837626	adding a hyperlink to a workitem (not a link to another workitem)	Hyperlink hl = new Hyperlink("http://microsoft.com");\nhl.Comment = "Microsoft";\n\nworkItem.Links.Add(hl);	0
33013610	33013202	Is a custom exception suitable in this case?	Guid == null	0
33835715	33835328	Method accepts Type - How to make it accept a generic?	static RestResponse<T> ApiCall<T>(object param1, object param2, ...) where T: new()\n\nRestResponse<T> response = (RestResponse<T>)client.Execute<T>(request);\n\nreturn restResponse;	0
25250666	25250612	How to join table with multiple columns in linq?	var query = from t1 in table1\n            from t2 in table2\n            where t1.ID == t2.orderId || t1.ID == t2.pickupId\n            select new { t1, t2};	0
5027432	5027374	How to quickly parse the following data into a data structure	var input = "A=B&C=D&E=F";\n    var output = input\n                    .Split(new string[] {"&"}, StringSplitOptions.RemoveEmptyEntries)\n                    .Select(s => s.Split('=', 2))\n                    .ToDictionary(d => d[0], d => d[1]);	0
4769170	4769074	How do I fill a rectangle with the exception of a area	protected override void OnPaint(PaintEventArgs e){\n    var rgn  = new Region(new Rectangle(50, 50, 200, 100));\n    var path = new GraphicsPath();\n    path.AddEllipse(60, 60, 180, 80);\n    rgn.Exclude(path);\n    e.Graphics.FillRegion(Brushes.Blue, rgn);\n}	0
25708848	25708823	Binding ContentControl Content with Window Content	window.content.Content = view;	0
24474731	24474644	Get the Element Value in the XML by using LINQ to XML	pp.Code = sec.Elements("COLUMN").First(c => c.Attribute("NAME").Value == "STOCK.STOCK_CODE").Value;	0
18091439	18090878	What chart type do I need for a wave line	var data = new List<Tuple<double,double>>();\nfor (double x = 0; x < Math.PI * 2; x += Math.PI / 180.0) {\n    data.Add(Tuple.Create(x, Math.Sin(x)));\n}\nchart1.ChartAreas.Add("area1");\nvar series = chart1.Series.Add("series1");\nseries.ChartType = SeriesChartType.Line;\nseries.ChartArea = "area1";\nseries.XValueMember = "Item1";\nseries.YValueMembers = "Item2";\nchart1.DataSource = data;	0
31125320	31116095	How to log ASP.NET Web API request body into a Application Insights failure?	var telemetry = new ExceptionTelemetry(context.Exception);\ntelemetry.Properties.Add("name", "value");\nnew TelemetryClient().Track(telemetry);	0
9502647	9502491	How can I determine variable scope in this C# Webforms example?	protected void Submit_Click(object sender, EventArgs e)\n    {\n        if (SomeCondition(x,y))\n        {\n            ViewState["foo"] = "apple";\n            ViewState["bar"] = "orange";\n        }\n    }\n\n    protected void ShowFooBar_Click(object sender, EventArgs e)\n    {\n        if(ViewState["foo"] != null && ViewState["bar"] != null)\n        {\n            Response.Write("foo=" + ViewState["foo"] + "& bar=" + ViewState["bar"]);\n        }\n    }	0
20144007	20143895	Refactor if statement with object-oriented style	public interface IMemoProcessor\n{ \n   void Run();\n}\n\npublic class EmailMemoProcessor : IMemoProcessor\n{\n   public void Run()\n   {\n      // Send email\n   }\n}\n\npublic class SmsMemoProcessor : IMemoProcessor\n{\n   public void Run()\n   {\n      // Send sms\n   }\n}\n\n// Factory looks at the type of memo and creates appropriate memo processor.\nvar memoProcessor = MemoProcessorFactory.Create(memo);\nmemoProcessor.Run();	0
3044523	3044489	C#.NET: Retrieve list of computers in a FOLDER in a domain	//ActiveDirectorySearch1\n//Displays all computer names in an Active Directory\nusing System;\nusing System.DirectoryServices; \nnamespace ActiveDirectorySearch1\n{\nclass Class1\n{\nstatic void Main (string[] args)\n{\n//Note : microsoft is the name of my domain for testing purposes.\nDirectoryEntry entry = new DirectoryEntry(LDAP://microsoft);\nDirectorySearcher mySearcher = new DirectorySearcher(entry);\nmySearcher.Filter = ("(objectClass=computer)");\nConsole.WriteLine("Listing of computers in the Active Directory"); \nConsole.WriteLine("============================================"); foreach(SearchResult resEnt in mySearcher.FindAll())\n{ \nConsole.WriteLine(resEnt.GetDirectoryEntry().Name.ToString()); }\nConsole.WriteLine("=========== End of Listing ============="); \n}\n}\n}	0
18917969	18900285	Entity Framework, T4 templates, and how to find out if a property has a 1-1 mapping table collapsed	bool collapsedTable = false;\n\nstring relationshipTypeName = navProperty.RelationshipType.Name;\nvar assocSet = container.BaseEntitySets.OfType<AssociationSet>()\n                                       .Where(es => es.Name == relationshipTypeName && !es.ElementType.IsForeignKey)\n                                       .FirstOrDefault();\n\nif (assocSet != null)\n{\n    collapsedTable = true;\n}	0
30572155	30571782	How can I determine whether Stored Procedure Parameter is optional from C# code (I am using Sql Server)	Server servev = new Server("YourServerName"); \n    Database dataBase = servev .Databases["YourDatabase"]; \n    var paramData = dataBase.StoredProcedures["YourProcedureName"].Parameters;\n\n    foreach(StoredProcedureParameter param in param) {\n       string paramName=param.Name;\n       string paramValue=param.DefaultValue;\n    }	0
2249783	2249725	How to set default selected item of listbox in winform c#?	public class Form1 : Form\n{\n    private bool itemsLoading;\n\n    public Form1()\n    {\n        InitializeComponent();\n        LoadListItems();\n    }\n\n    private void LoadListItems()\n    {\n        itemsLoading = true;\n        try\n        {\n            listBox1.DataSource = ...\n            listBox1.SelectedItem = ...\n        }\n        finally\n        {\n            itemsLoading = false;\n        }\n    }\n\n    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (itemsLoading)\n            return;\n\n        // Handle the changed event here...\n    }\n}	0
803389	803331	C#: How to get the assigned value from an action?	PFA(form => UpdateTextBox(form.Richbox1,"Test"));\n\n\npublic void UpdateTextBox(RichTextBox box,string text)\n{\n\n   if (box.Name=="Richbox1")\n   {\n       text+="\n";\n   }\n\n   box.AppendText(text);\n}	0
2988425	2988406	Get day from DateTime using C#	int d = (int)System.DateTime.Now.DayOfWeek	0
3319499	3319441	How to know when to cast to an Xelement or XAttribute?	XElement element = e.Current as XElement;\nXAttribute attrib = e.Current as XAttribute;\n\nif(element != null)\n   //Is Element, use element\nelse\n   //Is Attribute, use attrib	0
11171495	11171471	How do I sum double and int using Expression.Add?	Expression.Convert	0
26412250	26402646	Entity Framework - incorrectly doing 2 select statements instead of a join	db.Employees.Include(e => e.HolidayEntitlement).ToList()	0
11583537	11583439	linq-to-sql grouping anonymous type	var TheCounterInDB = (from a in MyDC.Appointments\n                      where TheIDs.Contains(a.ID)\n                      group a by a.AppointStatus into TheGroups\n                      select new { \n                             TheStatus = TheGroups.Key,\n                             TheTotalCount = TheGroups.Count(),\n                             TheLateCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate < DateTime.Today),\n                             ThePendingCount = TheGroups.Count(x => x.AppointStatus == 1 && x.AppointDate >= DateTime.Today)\n                      }).ToList();	0
17269771	17268805	Display a dictionary with a custom dataClass	public class myClass\n{\n  private string key;\n  private string val;\n\n  public string Key\n  {\n     get\n     {\n        return key;\n     }\n     set\n     {\n        key = value;\n     }\n  }\n\n  public string Value\n  {\n     get\n     {\n        return val;\n     }\n     set\n     {\n        val = value;\n     }\n  }\n\n  public myClass(string newKey, string newVal)\n  {\n     key = newKey;\n     val = newVal;\n  }\n}\n\n   public partial class Form1 : Form\n{\n  List<myClass> list = new List<myClass>(); \n\n  public Form1()\n  {\n     InitializeComponent();\n     list.Add(new myClass("a","aa"));\n     list.Add(new myClass("b", "bb"));\n     list.Add(new myClass("v", "vv"));\n     comboBox1.DataSource = list;\n     comboBox1.DisplayMember = "Key";\n     comboBox1.ValueMember = "Value";\n  }\n}	0
32696666	32690579	data repeater not showing image	private void Form3_Load(object sender, EventArgs e)\n{\n    this.productPhotoTableAdapter.Fill(this.adventureWorks2014DataSet.ProductPhoto);\n\n    byte[] mydata = (byte[])this.adventureWorks2014DataSet.ProductPhoto[100]["LargePhoto"];\n    MemoryStream stream = new MemoryStream(mydata);\n    pictureBox1.Image = Image.FromStream(stream);\n}	0
32181445	31876937	Get items from DataTemplate for ArtOfTest controls	var listBoxItem = repairCompanyList.Find.AllByType<ListBoxItem>().FirstOrDefault(r => r.Text == "Name");\nAssert.IsNotNull(listBoxItem, "Lack of expected list box item");\nlistBoxItem.User.Click();	0
23761114	23758131	How to link Window.SizeChanged in a C# Windows 8 App	Window.Current.SizeChanged += OnWindowSizeChanged;	0
13766248	13766198	C# accessing property values dynamically by property name	public static object ReflectPropertyValue(object source, string property)\n{\n     return source.GetType().GetProperty(property).GetValue(source, null);\n}	0
6660959	6660899	Simple select from generic list	foreach (var productGroup in allProducts.GroupBy(p => p.GetDisplayName()) {\n    # productGroup.Key is the display name\n    # and productGroup enumerates all the products for the display name\n}	0
8776758	8773502	Update a control's value from a static class in ASP.NET	public static class Job \n{ \n    public static string UpdatedValue { get; private set; } // Or whatever the property is you wish to expose.\n\n    // The Execute method is called by a scheduler and must therefore  \n    // have this exact signature (i.e. it cannot take any paramters). \n    public static string Execute() \n    { \n        // Do work\n        Job.UpdatedValue = "Execute Completed";\n    } \n} \n\n\nprotected override OnInit(EventArgs e)\n{\n    base.OnInit(e);\n    this.TextLabel.Text = Job.UpdatedValue;\n}\n\n\n// Using MSDN basic sample\nprotected void Timer1_Tick(object sender, EventArgs e)\n{\n    this.TextLabel.Text = Job.UpdatedValue;\n}	0
24362043	24361869	How to click a button by using keys	private void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Numpad1)\n    {\n        button1.performClick();\n        textbox.text += button1.text;\n        input += button1.text;\n    }\n    else if (e.KeyCode == Keys.Numpad2)\n    {\n        button2.performClick();\n        textbox.text += button2.text;\n        input += button2.text;\n    }\n    .\n    .\n    .\n    //rest of the code to handle other numpad keys\n}	0
12558595	12558537	Drawing a Grid of Dots on a PictureBox in C#	ControlPaint.DrawGrid(e.Graphics, rect, size, Color.Black);	0
29469662	29469622	Open another asp.net page in a different tab	ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key", "window.open('http://www.google.com.hk/','_blank');", true);	0
1970278	1970209	Currency format	String.Format( new System.Globalization.CultureInfo("es-ES"), "{0:###,###,###,###,##0.##}", Convert.ToDecimal(_monthPay)));	0
12777700	12777484	Added DateTime? DataMemberto DataContract - existing clients fail with "Nullable object must have a value"	[DataMember(IsRequired = false)]	0
18971374	18967930	Selenium WebDriver Focus Jumps to IEDriverServer.exe CMD Window	InternetExplorerOptions options = new InternetExplorerOptions();\noptions.RequireWindowFocus = true;\nIWebDriver driver = new InternetExplorerDriver(options);\n//navigate and sendkeys now	0
532214	532166	How to reference generic classes and methods in xml documentation	/// <see cref="FancyClass{T}.FancyMethod{K}(T)"/> for more information.	0
3782106	3781148	WPF: Determine/Set position of vertical Scrollbar	DependencyObject obj = this.DocumentScrollViewer;\n\n        do\n        {\n             if (VisualTreeHelper.GetChildrenCount(obj) > 0)\n             {\n                obj = VisualTreeHelper.GetChild(obj as Visual, 0);\n             }\n        }\n        while (!(obj is ScrollViewer));\n\n        this.scroller = obj as ScrollViewer;	0
19872520	19872334	Emebeded Statement can not be a declaration or labled stateme	if (dtpFrom.DateTime != null) \n{\n    Func<BAL.Receipt , DateTime? > expr = receipt => receipt.Date ;\n}	0
16824228	16824173	Comparing values without including zero?	IEnumerable<double> values = new[] { x, y, z, a, b, c };\ndouble nonZeroMin = values.Where(v => v != 0).Min();	0
1554493	1521315	Is there a way to set the DB as Single User Mode in C#?	Server server = GetServer();\n         if (server != null)\n        {\n            Database db = server.Databases[Settings.Instance.GetSetting("Database", "MyDB")];\n            if (db != null)\n            {\n                server.KillAllProcesses(db.Name);\n                db.DatabaseOptions.UserAccess = DatabaseUserAccess.Single;\n                db.Alter(TerminationClause.RollbackTransactionsImmediately);	0
31415906	31415857	C# - How to extract a list of one particular array member from a list of arrays	var myListOfStrings = listOfArrays.Select(a => a[1]).ToList();	0
15972971	15972852	JSON object displays null	return db.Users.Include(x => x.Addresses).Include(x => x.Positions).AsEnumerable();	0
11624028	11623490	C# Write Listview, and Read Listview (how to add indicator for listview for subitem)	using(StreamReader reader = new StreamReader(logFileName))\n{\n  StringBuilder currentItem = new StringBuilder();\n  char currentChar;\n  while (true)\n  {\n    if (reader.Peek() == 'specialChar')\n    {\n      if (currentChar == '|')\n      {\n        // This indicates that the currentItem is subItem\n        AddNewSubitem(currentItem.ToString());\n      }\n      else\n      {\n        AddNewItem(currentItem.ToString());\n      }\n      currentItem.Clear();\n      reader.Read();\n    }\n    else if (reader.Peek() != null)\n    {\n      curentItem.Append(reader.Read());\n    }\n    else\n    {\n      break;\n    }\n  }\n}	0
5350857	5350728	Need help with a regular expression	if ((m = (new Regex(@"(\d*\.?\d*)([MGTP%]?)", RegexOptions.IgnoreCase).Match(Size))).Success)\n{\n   Size = m.Groups[1].ToString();\n   if (m.Groups.Count > 1)\n   SizeUnit = m.Groups[2].ToString(); // if not given, SizeUnit is percentage\n}	0
31737744	31737635	Left Outer Join ObjectSet<T> to IQueryable	var vendorOrders = from v in context.Vendors\n                   where vendorNameList.Contains(v.Name) // vendorNameList is a string []\n                   join v1 in orders.toList() on v equals v1.Vendor into list\n                   from vo in list.DefaultIfEmpty()\n                   select new { Vendor = v, Order = orders == null ? "" : orders.ID };	0
18023019	18022950	try/catch performance	catch\n{\n//nothing\n}	0
1965202	1965179	Drag/drop ins Data Grid View -Row and column are always -1	Point theLoc = DG.PointToClient(new Point(e.X, e.Y));\n\n        DataGridView.HitTestInfo theHit = DG.HitTest(theLoc.X,theLoc.Y);\n        int theCol = theHit.ColumnIndex;\n        int theRow = theHit.RowIndex;\n        MessageBox.Show(theCol.ToString() + " " + theRow.ToString());	0
25041191	25041003	How to populate ListBox with Display and Value	lbEnt.Items.Add(new ListItem(drTemp["Client"].ToString(),drTemp["Client"].ToString()));	0
32903161	32902780	c# wpf - Right-Click to change SelectedDate and show ContextMenu	private void RadContextMenu_Opening(object sender, Telerik.Windows.RadRoutedEventArgs e)\n{\n    var calendarButton = (sender as RadContextMenu).GetClickedElement<CalendarButton>();\n    if (calendarButton != null && (calendarButton.ButtonType == CalendarButtonType.Date || calendarButton.ButtonType == CalendarButtonType.TodayDate))\n    {\n        var calendarButtonContent = calendarButton.Content as CalendarButtonContent;\n        if (calendarButtonContent != null)\n        {\n            var clickedDate = calendarButtonContent.Date;\n            radCalendar.SelectedDate = calendarButtonContent.Date;\n        }\n    }\n    else\n    {\n        e.Handled = true;\n    }\n}	0
18868968	18868870	Auto retrieval of data in textbox	SqlConnection Conn = new SqlConnection(Connection_String);\nSqlCommand Comm1 = new SqlCommand(Command, Conn);\nConn.Open();\ntextBox.Text = Comm1.ExecuteScalar();\nConn.Close();	0
3024587	3024562	Regex pattern failing	[^A-Za-z0-9 ]	0
963274	963270	Should we store format strings in resources?	// "{0}{1}{2}: Some message. Some percentage: {3}%"\nstring someString = string.Format(Properties.Resources.SomeString\n                                  ,token1, token2, token3, number);	0
14762572	14762470	How do i build array of regions?	// Three-dimensional array. \nint[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, \n                             { { 7, 8, 9 }, { 10, 11, 12 } } };	0
12592880	12592777	Customising element name of entries in an XML-serialised HashSet<string>	public class TN\n{\n    [XmlElement(ElementName="TN")]\n    public string tnumber;\n\n}	0
16596365	16596231	Convert Oracle Date to c# DateTime	DateTime dateTime = DateTime.ParseExact(ds.Tables[0].Rows[0][0].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);	0
18918652	18917413	Moq - how to initalize testing object once for multiple tests	private TestedService service;\n\n[SetUp]\npublic void SetUp()\n{\n    this.service = new TestedService(_mockedObject1.Object, _mockedObject2.Object, ...,\n        _mockedObject7.Object);\n} \n\n[TestMethod]\npublic void Test1()\n{\n    _mockedObject1.Setup(etc);\n    _mockedObject2.Setup(etc);\n\n    //Act and Assert\n    this.service.Whatever(...);\n}	0
24649434	9606546	Working with mshtml in c#	var doc = IE.Document;\nvar element = ((IHTMLDocument3)doc).getElementByID("ID");	0
1301001	1300948	Genericize command parameter creation when using null dates	oCmd.CreateParameter("@Date", DbType.DateTime,\n    updateDate > DateTime.MinValue ? (object)updateDate : DBNull.Value);	0
7617102	7617074	Detect end of running process without Admin rights	var process = Process.Start("ProgramX.exe");\n...\nprocess.WaitForExit();	0
22137692	22137444	How can I retrieve multiple last_insert_rows in SQLite?	PRAGMA temp_store = MEMORY;\nCREATE TEMP TABLE TempIds (id INTEGER);\n\nINSERT INTO t VALUES (@p_1); INSERT INTO TempIds VALUES(last_insert_rowid());\nINSERT INTO t VALUES (@p_2);  INSERT INTO TempIds VALUES(last_insert_rowid());\n...\n\nSELECT id FROM TempIds;	0
5899446	5888933	Making nhibernate do a join on a many-to-many relationship	link.Session.QueryOver<ContactAssociation>(() => ca)\n                                       //.Fetch(asoc => asoc.Client)\n                                       .JoinAlias(() => ca.Client, ()=> client)\n\n.Left.JoinQueryOver<BuEntry>(() => client.BuEntries, () => be)\n                                       .Where(() => client.ID == clientKey)\n                                       .JoinQueryOver<BuLevel>(() => be.BuLevel)\n                                       .Where(bu => bu.LevelNo > buLevel);	0
1293283	1293273	How do I get a path suitable for storing temporary files?	string sPath;\nsPath = Path.GetTempPath();    \nConsole.WriteLine("Temporary Path := " + sPath );	0
30583331	30515872	Given a path, how can i find out its host?	\\LocaSharedFolder	0
13911333	13902516	Failure in delete performance counter category	cd %systemroot%\system32\nlodctr /R	0
7862474	7862439	Creating an abstract class that implements multiple interfaces in c#	public interface IPartImportsSatisfiedNotification\n    {\n        void SomeMethod();\n    }\n\n    public abstract class MyClass : IDisposable, IPartImportsSatisfiedNotification\n    {\n        private string name;\n        public MyClass(string name)\n        {\n            this.name = name;\n        }\n\n        public abstract void SomeMethod();\n\n        public abstract void Dispose();\n    }\n\n    public class SubClass : MyClass\n    {\n        public SubClass(string someString) : base(someString)\n        {\n\n        }\n\n        public override void SomeMethod()\n        {\n            throw new NotImplementedException();\n        }\n\n        public override void Dispose()\n        {\n            throw new NotImplementedException();\n        }\n    }	0
12526645	12526497	Use LINQ to populate a single list from two other lists without duplicates	var difference = NormalFruitList.Where(normFruit =>\n            !OrigFruitList.Exists(\n                origFruit => origFruit.Category == normFruit.Category \n                    && origFruit.SubCategory == normFruit.SubCategory));\n\n        // If new Category is found in NormalFruitList it will be added to the end\n        int index = 0;\n        var result = new List<Fruit>(OrigFruitList);\n        foreach (var item in difference.Reverse())\n        {\n            index = result.IndexOf(OrigFruitList.FirstOrDefault(fruit => fruit.Category == item.Category));\n            result.Insert(index == -1 ? OrigFruitList.Count : index + 1, item);\n        }	0
30200985	30200034	List A value compared to all possible in List B	var value = Model.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).AnswerID;\n            if ( Model.QuizHeader.QuizQuestions.Any(item => item.QuizAnswers.Any( x=> x.AnswerID == value)))	0
15476814	15476537	How to find both integer or decimal in System.Text.RegularExpressions.Regex	Regex = new Regex("((?:\d*\.)?\d+)(years?)");	0
20695444	20695417	How many different ways in Visual C# is there to read in a file?	System.IO.File.ReadAllText("TestFile.txt")	0
2551492	2546421	Storyboard apply to all labels	public SpellerWindow(IKeyboard keyboard, int colomnNumber, SolidColorBrush background, SolidColorBrush foreground )\n{\n    ....\n}	0
1711461	1709680	Changing internal representation in runtime	public abstract class Thing\n{\n    private class LightThing : Thing\n    { ... }\n    private class HeavyThing : Thing \n    { ... }\n    public static Thing MakeThing(whatever) \n    { /* make a heavy or light thing, depending */ }\n    ... etc ...\n}	0
3304562	3304546	In C#, how can I display only a certain number of digits?	Double.ToString(String)	0
34044499	34044129	Need to create a dropdownlist delimiters	Dictionary<string, string> delims = \n    Enumerable.Range(char.MinValue, char.MaxValue - char.MinValue)\n    .Select(i => Convert.ToChar(i))\n    .Where(c => !Char.IsControl(c))\n    .ToDictionary(c => c.ToString(), c => c.ToString());	0
1810048	1810028	How to print 1 to 100 without any looping using C#	public static void PrintNext(i) {\n    if (i <= 100) {\n        Console.Write(i + " ");\n        PrintNext(i + 1);\n    }\n}\n\npublic static void Main() {\n    PrintNext(1);\n}	0
30076595	30076468	Match an email address if it contains a dot	Func<string, bool> dotBeforeAt = delegate(string email) \n{ \n    var dotIndex = email.IndexOf(".");\n    return dotIndex > -1 && (dotIndex < email.IndexOf("@"));\n};\n...\nemails.Where(dotBeforeAt).ToList();	0
33049023	33048195	something wrong with rotation controls in 2d top down shooter in unity3d	target = camera.ViewportToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y));	0
865624	865602	Entity - Linq to Sql Only load a part of the entity	public IQueryable<Person> FindAllPersons()\n{\n    return from person in db.Persons\n           select new Person(){Name = person.Name, Age = person.Age};\n}	0
10776799	10776662	How to perform aggregate function on last 4 rows of data?	var result = from w1 in db.Table\n             from w2 in db.Table.Where(x => x.WeekEnding >= w1.WeekEnding.AddDays(-28))\n             select new\n             {\n                 FranchiseId = w1.FranchiseId,\n                 WeekEnding = w1.WeekEnding,\n                 Sales = w1.Sales,\n                 SalesMin = w2.Min(x => x.Sales)\n             };	0
9038153	9038096	Data Binding to a LinkedList?	CollectionViewSource.GetDefaultView(ViewModel.TheCollectionProperty).Refresh();	0
10773353	10773339	How to BASE64 encode URLs?	static public string EncodeTo64(string toEncode) {\n    byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);\n    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);\n    return returnValue;\n}\nstatic public string DecodeFrom64(string encodedData) {\n    byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);\n    string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);\n    return returnValue;\n}\nMessageBox.Show(DecodeFrom64("aHR0cDovL3d3dy5pbWRiLmNvbS90aXRsZS90dDA0MDE3Mjk="));	0
20569909	20569759	How to order XML Document by pubDate?	XDocument doc = XDocument.Load(yourfile.xml);\nstring format = "ddd, dd MMM yyyy hh:mm:ss zzz";\nvar elements = \n       doc.Descendants("item")\n          .OrderBy(i => DateTime.ParseExact(i.Element("pubDate").Value,\n                                            format,\n                                            CultureInfo.InvariantCulture);	0
4924175	4924084	How can we efficiently read only integers from text file in C#	public void ReadJustNumbers()\n            {\n                Regex r = new Regex(@"\d+"); \n                using (var sr = new StreamReader("xxx"))\n                {\n                    string line;\n                    while (null != (line=sr.ReadLine()))\n                    {\n                        foreach (Match m in r.Matches(line))\n                        {\n                            Console.WriteLine(m.Value);\n                        }\n                    }\n                }\n            }	0
23130281	23128574	How to tell if Target.Value is double or string	object obj = Target.Value;\nMessageBox.Show(obj.GetType().ToString());	0
30231753	30231413	Casting Range.Value2 of Excel interop to string	myString = range.Value2 == null ? "" : range.Value2.ToString();	0
8860080	8859917	Using java + php in windows	new Java("java.text.SimpleDateFormat","EEEE,	0
7446824	7444712	how to grab the link uri in watin testing framework	foreach (IE currIE in IE.InternetExplorers())\n{\n    Console.WriteLine("URL: " + currIE.Url);\n}	0
2611210	2611068	how to do this conversion?	string mvi = Moneys.GetValue(8) as string;\nmoney.Currency = 0M;\nif (!String.IsNullOrEmpty(mvi))\n   if (!Decimal.TryParse(mvi, out money.Currency))\n     throw new FormatException("mvi");	0
29977100	29976089	csharp using sql query with special characters	using (SqlConnection conn = new SqlConnection())\n{\n    conn.ConnectionString = "Integrated Security=true;Initial Catalog=xyz;server=abc";\n    string sqlQuery = "Select * from myTable where name like '%[\\]%' or name like '%[%]%'";\n    conn.Open();\n    using (SqlCommand command = new SqlCommand(sqlQuery, conn))\n    {\n        var result = command.ExecuteReader();\n    }\n}	0
15282592	15282447	How Can I Parse CSV in C#	var txt = "-123.118069008,49.2761419674,0 -123.116802056,49.2752350159,0 -123.115385004,49.2743520328,0";\n        var output = new StringBuilder();\n        foreach (var group in txt.Split(' '))\n        {\n            var parts = group.Split(',');\n            var lat = double.Parse(parts[0]);\n            var lng = double.Parse(parts[1]);\n            if (output.Length > 0)\n                output.AppendLine(",");\n            output.Append("new google.maps.LatLng("+lat+","+lng+")");\n        }\n        MessageBox.Show("["+output+"]");	0
6985413	6985245	Please help me bring this simple fluent nhibernate mapping to life	public Class ClassAMap : ClassMap<ClassA>{\n    public ClassAMap(){\n       Id(x => x.Id);\n       References(x => x.ObjAC, "TableC_ID").Cascade.All();\n       ...\n    }\n }\n\n public Class ClassBMap : ClassMap<ClassB>{\n    public ClassBMap(){\n       Id(x => x.Id);\n       References(x => x.ObjBC, "TableC_ID").Cascade.All();\n       ...\n    }\n }\n\n public Class ClassCMap : ClassMap<ClassC>{\n    public ClassCMap(){\n       Id(x => x.Id);\n    }\n }	0
30274867	30274634	How to Find a class in external reference that implements certain interface?	interface MyInterface { }\n\npublic static void Main()\n{\n    Assembly asm = Assembly.Load("externalAssembly");\n\n    var interfaces = asm.GetTypes().Where(t => t.IsSubclassOf(typeof(MyInterface)));\n\n    foreach (var i in interfaces)\n    {\n        Console.WriteLine(String.Format("Found: {0}", i.Name));\n    }\n}	0
1455324	1455310	linq to sql - how do i rewrite the following	var suppliers = from s in context.Supplier where \n    SqlMethods.Like(s.CompanyName, "[0-9]%")\nselect s;	0
20044401	19953296	Passing a DataTable to a SP with ServiceStack ORMLite	DataTable dataTableTmp = new DataTable();\n        dataTableTmp.Columns.Add("ID_USER", typeof(Int32));\n        dataTableTmp.Columns.Add("ID_DATA", typeof(Int32));\n        dataTableTmp.Columns.Add("HEADER_TXT", typeof(string));\n\n\n        foreach (var r in DomandeRisposteList)\n        {\n            DataRow ro = dataTableTmp.NewRow();\n            ro[0] = r.IdUser;\n            ro[1] = r.IdData ;\n            ro[2] = r.HeaderTxt ;\n\n            dataTableTmp.Rows.Add(ro);\n        }\n\n        var dbConn = dbFactory.OpenDbConnection();\n\n        var res = dbConn.Exec(dbCmd =>\n        {\n            dbCmd.CommandType = CommandType.StoredProcedure;\n            dbCmd.Parameters.Add(new SqlParameter("@LISTA_QUESTIONARIO", dataTableTmp));\n            dbCmd.CommandText = "IF_SP_QUESTIONARIO_INSERT_TEST";\n            return dbCmd.ExecuteReader().ConvertToList<DomandeRisposteItem>(); \n        });\n\n        return res;	0
12387630	12387577	Splitting string based on uneven number of white spaces	string strtemp = "1052 root         0 SW<  [hwevent]";\nstring[] array = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);	0
11568845	11568807	returning object as json from mvc, how to display on the view	success: function (result) {\n    /// what to do here? \n    result = jQuery.parseJSON(result);\n    /// Exploit your object(s) ;)\n},	0
31079952	31079847	GridView update from Button Click event crashes	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        e.Row.Cells[0].Attributes["width"] = "30px";\n        e.Row.Cells[1].Attributes["width"] = "40px";   -> CRASHES AT INDEX 1\n        e.Row.Cells[2].Attributes["width"] = "40px";\n        e.Row.Cells[3].Attributes["width"] = "50px";\n        e.Row.Cells[4].Attributes["width"] = "50px";\n        e.Row.Cells[5].Attributes["width"] = "100px";\n        e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Left;\n    }\n}	0
19830589	19812803	C# Comparing two images	var src = element.GetAttribute("src");\n\n    //downloads the byte array of the image from its src\n    var file = webClient.DownloadData(src);	0
7959990	7959505	Return XML Nodes in a particular order	IOrderedEnumerable<XmlNode> booksNodes = doc.DocumentElement.SelectNodes("//BOOKS")\n    .Cast<XmlNode>()\n    .OrderBy(node => node.Attributes["title"].Value);	0
11669591	11656017	Generic Enum to Lowercased String Mapping Using AutoMapper	Mapper.CreateMap<Enum, String>().ConvertUsing(e => e.ToString().ToLower());	0
727198	727173	C# 3.0 - How can I order a list by week name starting on monday?	public class Event\n{\n  public string Day; \n}\n\n[Test]\npublic void Te()\n{\n  var dayIndex = new List<string> {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"};\n  var list = new List<Event> {new Event(){Day = "saturday"}, new Event() {Day = "Monday"}, new Event() {Day = "Tuesday"}};\n  var sorted = list.OrderBy(e => dayIndex.IndexOf(e.Day.ToUpper()));\n  foreach (var e in sorted)\n  {\n    Console.WriteLine(e.Day);\n  }\n}	0
19987494	15904314	Invalid Signature Reading XML from Http Response	public void ProcessRequest(HttpContext context)\n{\n     // a bunch of request handling logic\n     //...\n     HttpResponse response = context.Response;\n     XmlDocument signedXML = getTheSignedXMLData(); //the XML\n     signedXML.PreserveWhitespace = true;\n     signedXML.Save(response.Output);\n }	0
1175670	1175644	When out of index of fixed array how to pragmatically restart at beginning	[Test]\npublic void WhenFileIDModifierIsBiggerThanArrayArrayShouldStartOverAndReturnVal()\n{\n    var filecountfordate = 71;\n    var chararray = new[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', \n      'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', \n      'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8',\n                           '9'\n                       };\n\n    filecountfordate = filecountfordate % chararray.Length;\n\n\n    var expected = "9";\n    var actual = chararray[filecountfordate].ToString();\n\n    Assert.AreEqual(expected, actual);\n}	0
13006763	13006735	how to put parameter value in prefix search of SQL	DECLARE @searchTerm nvarchar(60) = N' "' + @pvchProductName + N'*" ';\n// where the "60" above should be adjusted to account for the length\n// of pvchProductName, plus 5. So if pvchProductName is [n]varchar(30),\n// then nvarchar(35) would be fine.\n\nSELECT Description, ProductDescriptionID\nFROM Production.ProductDescription\nWHERE CONTAINS (Description, @searchTerm);	0
2253853	2253835	Ambiguous Call with a Lambda in C# .NET	MyClass.DoThis((Foo foo) => foo.DoSomething());	0
2384922	2384912	how to achieve timespan to string conversion?	DateTime d = new DateTime(time_span.Ticks);\nstring time = d.ToString("HH:mm:ss");	0
12817430	12817298	Change property value causes a change in all properties	custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);	0
19947904	17328352	How can i generate a localized keyboard shortcut in C# / WPF?	private void LocalizeShortcuts()\n{\n    foreach (KeyGesture keyGuesture in this.InputGestures.OfType<KeyGesture>().ToArray())\n    {\n        this.InputGestures.Remove(keyGuesture);\n\n        System.Windows.Forms.Keys formsKey = (Keys)KeyInterop.VirtualKeyFromKey(keyGuesture.Key);\n        if ((keyGuesture.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)\n        {\n            formsKey |= Keys.Alt;\n        }\n\n        if ((keyGuesture.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)\n        {\n            formsKey |= Keys.Control;\n        }\n\n        if ((keyGuesture.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)\n        {\n            formsKey |= Keys.Shift;\n        }\n\n        string keyDisplayString = TypeDescriptor.GetConverter(typeof(Keys)).ConvertToString(formsKey);\n        this.InputGestures.Add(new KeyGesture(keyGuesture.Key, keyGuesture.Modifiers, keyDisplayString));\n    }\n}	0
27382082	27382012	Unable to Insert Current Timestamp in DB using C#	int ActivateState;\nif (rdoActivateMappingYes.Checked)\n{\n    ActivateState = 1;\n    cmd.Parameters.AddWithValue("@ActivationDate", DateTime.Now);\n}\nelse\n{\n    ActivateState = 0;\n    cmd.Parameters.AddWithValue("@ActivationDate", DBNull.Value);\n}	0
931954	931911	How to make a control "transparent" for the mouse or Route MouseMove event to parent?	Panel _currentlyMovingCard = null;\nPoint _moveOrigin = Point.Empty;\nprivate void Card_MouseDown(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Left)\n    {\n        _currentlyMovingCard = (Panel)sender;\n        _moveOrigin = e.Location;\n    }\n}\n\nprivate void Card_MouseMove(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Left && _currentlyMovingCard != null)\n    {\n        // move the _currentlyMovingCard control\n        _currentlyMovingCard.Location = new Point(\n            _currentlyMovingCard.Left - _moveOrigin.X + e.X,\n            _currentlyMovingCard.Top - _moveOrigin.Y + e.Y);\n    }\n}\n\nprivate void Card_MouseUp(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Left && _currentlyMovingCard != null)\n    {\n        _currentlyMovingCard = null;\n    }\n}	0
19983833	19983490	how to step through lambda expression	[System.Diagnostics.DebuggerStepThrough]\n    public static void Log(Database db)\n    {\n        Action<string> Log = MyLogger.Log;\n        db.Log = Log;\n    }	0
18772169	18767817	how can I send selected rows(with checkbox ) of datagridview to datatable?	public DataTable GetDataTableFromDataGridView(DataGridView dataGridView)\n{\n    DataTable dataTable = new DataTable();\n    foreach (DataGridViewColumn column in dataGridView.Columns)\n    {\n        //// I assume you need all your columns.\n        dataTable.Columns.Add(column.Name, column.CellType);\n    }\n\n    foreach (DataGridViewRow row in dataGridView.Rows)\n    {\n        //// If the value of the column with the checkbox is true at this row, we add it\n        if (row.Cells["checkbox column name"].Value == true)\n        {\n            object[] values = new object[dataGridView.Columns.Count];\n\n            for (int i = 0; i < row.Cells.Count; i++)\n            {\n                values[i] = row.Cells[i].Value;\n            }\n            dataTable.Rows.Add(values);\n        }\n    }\n\n    return dataTable;\n}	0
252301	249721	How to convert DateTime from JSON to C#?	[DataContract]\npublic class TestClass\n{\n\n    private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);\n\n    [IgnoreDataMember]\n    public DateTime MyDateTime { get; set; }\n\n    [DataMember(Name = "MyDateTime")]\n    private int MyDateTimeTicks\n    {\n        get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; }\n        set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); }\n    }\n\n}	0
23625888	23625691	Interaction between two separate Windows in wpf	Window1 win = new Window1();\nwin.Variablex = 1;	0
8701573	8701146	Exclute/ignore parameter in image's ImageUrl but still show it within a Repeater	void Application_BeginRequest(Object sender, EventArgs e)\n{\n    string currentPath;\n    currentPath = Request.Path; // /product/0001_100_00_KK00_F02.png/Tv-Sony-lcd-black-bravia-KDL-26V4500\n    if (currentPath.IndexOf(".png") > -1)\n    {\n        string[] paths = currentPath.Split('/');\n        currentPath = currentPath.Replace("/" + paths[paths.Length - 1], ""); // /product/0001_100_00_KK00_F02.png\n        Context.RewritePath(currentPath);\n    }\n}	0
20190470	20190435	How to to get part of the string	if (abc.Length < 9)\n    return abc;\nelse\n    return abc.Substring(0, 9);	0
17617417	17616164	C# Go to next control in the tab order from custom Property Grid	switch (m.Msg)\n    {\n        case WM_KEYDOWN:\n            {\n                if (wParam == SHIFT)\n                {\n                    isShiftDown = true;\n                    return true;\n                }\n            }\n            break;\n\n        case WM_KEYUP:\n            {\n                if (wParam == TAB)\n                {\n                    bool ismoved = moveSelectedGridItem(!isShiftDown);\n\n                     // First: modify the method "moveSelectedGridItem" to return bool value (if grid moved: true, if TAB pressed after last grid item: false)\n\n                    if(!ismoved)\n                        // handle your implementaion here\n\n                    return true;\n                }\n                else if (wParam == SHIFT)\n                {\n                    isShiftDown = false;\n                    return true;\n                }\n            }\n            break;\n    }\n\n    return ProcessKeyEventArgs(ref m);\n}	0
17765504	17759711	Formatting text using PDFsharp	// Create a font\nXFont font = new XFont("Verdana", 12, XFontStyle.Bold | XFontStyle.Underline);\n\n// Draw the text\ngfx.DrawString("Hello, World!", font, new XSolidBrush(XColor.FromArgb(255, 0, 0)),\n  100, 100,\n  XStringFormats.Center);	0
34354882	34354166	Set combobox with long datasource	var parent = comboBox.Parent;\n        parent.Controls.Remove(comboBox);\n        comboBox.DataSource = ds;\n        parent.Controls.Add(comboBox);	0
16602801	16602703	How can I return two views from an action?	public ActionResult Page()\n{\n    //LINQ x expressions\n    //LINQ y expressions\n    if(Request.QueryString["type"] == "x")\n    {\n        return View(linqExpX.ToList());\n    }\n    else if(Request.QueryString["type"] == "y")\n    {\n        return View(linqExpY.ToList());\n    }\n\n    return someDefaultView; \n}	0
20153653	20153547	Saving values into List in a class by using LINQ	var items = from item in xmlDocument.Descendants("item")\n            select new Item\n            {\n                Name = item.Element("name").Value,\n                ImagesUrl = Enumerable.Range(1,5).Select(x => item.Element("img"+x).Value).ToList();\n            };	0
24737073	23834001	How to activate spellCheck in C# Windows Form Application?	System.Windows.Forms.Integration.ElementHost elementHost1 = new System.Windows.Forms.Integration.ElementHost();\nSystem.Windows.Controls.TextBox textBox = new System.Windows.Controls.TextBox();\ntextBox.SpellCheck.IsEnabled = true;\nelementHost1.Child = textBox;	0
8896283	8886608	Reporting Services C# Collapsible Detail Subreport in Row Passing Parameters	this.ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEvent);\n\n    void SubreportProcessingEvent(object sender, SubreportProcessingEventArgs e)\n    {\n        SqlDataAdapter sda = new SqlDataAdapter();\n        DataSet ds = new DataSet();\n\n        ds = getSubReportData(e.Parameters[0].Values[0]);\n        ReportDataSource rds = new ReportDataSource("SqlDataSourceProg", ds.Tables["SiteProfileSvcRate"]);\n\n        rds.Name = "SiteProfileSvcRate";\n\n        e.DataSources.Add(rds);\n    }\n\n    private DataSet getSubReportData(string strSvcId)\n    {\n        DataSet ds = new DataSet();\n        SqlParameter[] sParam = new SqlParameter[1];\n\n        sParam[0] = new SqlParameter("svcid", strSvcId);\n        ds = dac.GetDataSet("xwiWR_SP_SiteProfile_SvcRate_Current", sParam, "SiteProfileSvcRate");\n\n        return ds;\n    }	0
7497642	6212516	Automapper inheritance -- reusing maps	public static IMappingExpression<A, T> ApplyBaseQuoteMapping<A, T>(this   IMappingExpression<A, T> iMappingExpression)\n        where A : QuoteMessage\n        where T : CalculationGipMessage\n    {\n        iMappingExpression\n            .ForMember(a => a.LoginUserName, b=> b.MapFrom(c => c.LoginUserName))\n            .ForMember(a => a.AssetTestExempt, b => b.Ignore())\n            ;\n\n        return iMappingExpression;\n    }\n\n\nMapper.CreateMap<QuoteMessage, CalculationGipMessageChild>()\n            .ApplyBaseQuoteMappingToOldCol()\n             // do other mappings here	0
17082550	17082481	can't get output parameters from a SqlParameter inside a query	INSERT INTO tr_text (form, item, enabled, programID) VALUES (@myForm, @myItem, 1, @myProgramID) \nset @id = SCOPE_IDENTITY();	0
26785503	26785280	Getting the current folder path when trying to get ProgramFilesX86 on server 2003	string x = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);	0
21552549	21552393	Accessing .NET assemblies via COM in PHP	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter	0
28269920	28269563	How to change comboBox items if i checked radioButton using c#	private void radioButton1_CheckedChanged(object sender, EventArgs e)\n{\n    if(radioButton_1.Checked)\n    {\n         comboBox1.Items.Remove("google");\n         comboBox1.Items.Add("yahoo");\n    }\n    else\n    {\n         comboBox1.Items.Remove("yahoo");\n         comboBox1.Items.Add("google");\n    }\n}	0
14746488	14746348	How to Add File Upload Control in TableCell using C#	FileUpload fileUpload = new FileUpload();\ncell3.Controls.Add(fileUpload);	0
18189027	18124646	Manually focus camera in EMGU CV	DsDevice[] devs = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // getting video devices\n IFilterGraph2 graphBuilder = new FilterGraph() as IFilterGraph2; \n IBaseFilter capFilter = null;\n if (graphBuilder != null)\n graphBuilder.AddSourceFilterForMoniker(devs[0].Mon, null, devs[0].Name, \n    out capFilter); //getting capture filter for converting it into IAMCameraControl\n IAMCameraControl _camera = capFilter as IAMCameraControl;\n _camera.Set(CameraControlProperty.Focus, 250, CameraControlFlags.Manual); //Setting focus to macro (in my camera, range between 0 - 250)	0
1284007	133270	Illustrating usage of the volatile keyword in C#	class Test\n{\n    int foo;\n\n    static void Main()\n    {\n        var test = new Test();\n\n        new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();\n\n        while (test.foo != 255) ;\n        Console.WriteLine("OK");\n    }\n}	0
24169786	24169626	Make sure to insert and update row in database	while(sqlQueryHasNotSucceeded)\n{\n    try\n    {\n        updateCmd.ExecuteNonQuery();\n        sqlQueryHasNotSucceeded = false;\n    }\n    catch(Exception e)\n    {\n        LogError(e);\n        System.Threading.Thread.Sleep(1000 * 10);\n    }\n}	0
22123031	22122933	Loop through an array of strings and compare to previous values	HashSet<string> prevSet = new HashSet<string>();\n\nforeach ( string str in myArray )\n  if ( !prevSet.Add(str) ) return str;	0
5199539	5199299	c# savefilediaglog saving text of specific length	using (var wText = new StreamWriter(myStream, Encoding.Default)) {\n       string st = gettxt();\n       wText.Write(st);\n       //wText.WriteLine("sdfsderfsdsf");\n   }	0
20132112	20131799	Get number of lines in file and add first 40 characters	StreamReader fileIn = new StreamReader(fileName);\nfor(int i=0; i<4 && !fileIn.EndOfStream; ++i)\n{\n    string line = fileIn.ReadLine();\n    if(line.Length > 40)\n        richTextBox1.AppendText(line.Substring(0,40) + Environment.NewLine);\n    else\n        richTextBox1.AppendText(line + Environment.NewLine);\n}\nint j;\nfor(j=0; !fileIn.EndOfStream; ++j)\n    fileIn.ReadLine();\nif(j>0)\n    richTextBox1.AppendText(j.ToString() + " more lines are not shown.";\nfileIn.Close();	0
10348467	10348236	How do I get the time in miliseconds on windows phone 7?	DateTime unixEpoch = new DateTime(1970, 1, 1);\nDateTime currentDate = DateTime.Now;\nlong totalMiliSecond = (currentDate.Ticks - unixEpoch.Ticks) /10000;\nConsole.WriteLine(totalMiliSecond);\nstring fileName = string.Concat(totalMiliSecond,".jpg");\nConsole.WriteLine(fileName);	0
16361007	16360294	Parsing a formatted string with RegEx or similar	MatchCollection matchlist = Regex.Matches(receivedData, @"(?<tag>\d+(?:-\d+)?),""(?<data>.*?)""");\n        foreach (Match match in matchlist)\n        {\n            string tag = match.Groups["tag"].Value;\n            string data = match.Groups["data"].Value;\n        }	0
18026928	18026887	How can I assign an enumerated type value to a variable?	switch (stringValue)\n{\n    case "BeltPrinterType.ONiel": enumValue = BeltPrinterType.ONiel; break;\n    ...etc...\n}	0
11204340	11203252	Change list of objects to properties of an object	var listobj = new List<object>() { 1, 2, "3", "4", 1.2 };    \n var x = new ExpandoObject() as IDictionary<string, Object>;\n\n foreach (var obj in listobj)\n {\n      //Add a property dynamically - property name and value\n      x.Add(obj.ToString(), obj.ToString());  \n }	0
23523894	23523760	Determine AM/PM from string as "05:00:00"	if (time.Hour < 9) // less than 9AM, it must be PM!\n  time.AddHours(12);	0
10899061	10898795	Modify custom query to paginate with a gridview	WITH MyPagedData as (\nSELECT *,\nROW_NUMBER() OVER(ORDER BY IdentityCol DESC) as RowNum,\nROW_NUMBER() OVER(ORDER BY IdentityCol ASC) as InverseRowNum\nFROM requestbases where currentstatus == 'Approved 1' and ammountwithvat > 100000\n)\n\nSELECT * from MyPagedData where RowNum between @StartIndex and @StartIndex + 20	0
25476309	25476043	How to Monitor HTTP Requests Directly From C# Server Console?	public static class Program\n{\n    private const string Url = "http://localhost:8080/";\n\n    public static void Main()\n    {\n        using (WebApp.Start(Url, ConfigureApplication))\n        {\n            Console.WriteLine("Listening at {0}", Url);\n            Console.ReadLine();\n        }\n    }\n\n    private static void ConfigureApplication(IAppBuilder app)\n    {\n        app.Use((ctx, next) =>\n        {\n            Console.WriteLine(\n                "Request \"{0}\" from: {1}:{2}",\n                ctx.Request.Path,\n                ctx.Request.RemoteIpAddress,\n                ctx.Request.RemotePort);\n\n            return next();\n        });\n    }\n}	0
22463164	22458932	RequestNavigate a view *away* from an ItemsControl Region	INavigationAware viewModel = viewToRemove.DataContext;\nviewModel.OnNavigatedFrom(null);\nIRegion myRegion = _regionManager.Regions["MyRegion"];\nmyRegion.Remove(viewToRemove);	0
30735140	30735011	Detect if Application was suspended in OnNavigatedFrom for Windows Phone 8	protected override void OnNavigationFromPage(System.Windows.Navigation.NavigationEventArgs e)\n{\n    if (e.Uri.ToString() != "app://external/") \n    {\n        //App being suspended.\n    }\n    else\n    { \n        UnSubscribeFromEvents(); \n    }\n}	0
17610347	17608477	C# Detecting a Click in WndProc and calling a function after click happened	[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]\nprotected override void WndProc(ref Message m)\n{\n    switch(m.Msg)\n    {\n         case 0x201:\n           //left button down\n           break;\n          case 0x202:\n           clickedHappened(); //left button up, ie. a click\n           break;\n         case 0x203:\n           //left button double click\n           break;\n    }\n\n    base.WndProc(ref m);\n}	0
736128	736085	Rename File in IsolatedStorage	var oldName = "file.old"; var newName = "file.new";\n\nusing (var store = IsolatedStorageFile.GetUserStoreForApplication())\nusing (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))\nusing (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))\nusing (var reader = new StreamReader(readStream))\nusing (var writer = new StreamWriter(writeStream))\n{\n  writer.Write(reader.ReadToEnd());\n}	0
18538094	18537393	Processing windows messages, threading COM objects	private void some_event(object sender, EventArgs e)\n{\n    MainForm.IsClipboardListenerOn = false;\n    // some code that makes the clipboard changed message fire\n    //...\n    this.BeginInvoke(new Action(() => MainForm.IsClipboardListenerOn = true));\n}	0
27201152	27197293	Hovering over Windows Slider changes colour	App.xaml	0
5508077	5508050	How to get a property value based on the name	return car.GetType().GetProperty(propertyName).GetValue(car, null);	0
29623440	29621880	c# interop word print multiple pages in one page	document.PrintOut(Background: true, PrintZoomRow: 2, PrintZoomColumn: 2);	0
6933862	6933496	Accessing GridView data from a templatefield	protected void btnComplete_Click(object sender, EventArgs e)    \n{  \n     Button btn = (Button)sender;\n     GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;\n\n     //Alternatively you could use NamingContainer\n     //GridViewRow gvRow = (GridViewRow)btn.NamingContainer;\n\n     Label lblComments = (Label)gvRow.FindControl("lblComments");\n\n     // lblComments.Text ...whatever you wanted to do\n}	0
110372	110325	Get millions of records from fixed-width flat file to SQL 2000	BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS )	0
8017600	8017480	Concatenate wave files at 5 second intervals	int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;	0
18746463	18746223	How to create a bitmap from a Device Context?	// Set the size/location of your bitmap rectangle.    \nRectangle bmpRect = new Rectangle(0, 0, 640, 480);\n    // Create a bitmap\n    using (Bitmap bmp = new Bitmap(bmpRect.Width, bmpRect.Height))\n    {\n        // Create a graphics context to draw to your bitmap.\n        using (Graphics gfx = Graphics.FromImage(bmp))\n        {\n            //Do some cool drawing stuff here\n            gfx.DrawEllipse(Pens.Red, bmpRect);\n        }\n\n        //and save it!\n        bmp.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\MyBitmap.bmp", System.Drawing.Imaging.ImageFormat.Bmp);\n    }	0
19195082	19195056	how to change column width inside datalist control in asp.net	padding:5px;	0
14650023	14649843	Using dictionary keys as field name in LINQ	foreach (var pair in list)\n{\n    graphic.DrawString(pair.Value, font, brush, startX, startY + offset);\n    graphic.DrawString(":", font, brush, semicolonPos, startY + offset);  \n\n    var pi=typeof(Customer).GetProperty(pair.key);\n    var val= pi.GetValue(query,null);\n    graphic.DrawString(val, font, brush, semicolonPos, startY + offset);\n}	0
11623730	11623669	Reading Text Files and then breaking down lines into columns	File.ReadAllLines	0
10396174	10395168	C++ DLL imported into a C# application	MathFuncs.Add()	0
14890026	14889978	Getting Current Class's Name	this.GetType().Name	0
5237188	5236824	Show combined result from unrelated tables (linq to sql)	var usernames = ((from e in db.EmailAlerts select e.UserName).Union\n                (from t in db.TextAlerts select t.UserName)).Distinct();\nvar result =\n    from u in usernames\n    select new \n    {\n        Username = u.Username,\n        ActiveType1Email = (from e in db.EmailAlerts\n                           where e.UserName == u\n                           && e.Type == (int)AlertType.Type1\n                           && a.Description == "active"\n                           select e).FirstOrDefault();\n        /*\n         ... and so on repeat for activeType1Text, activeType2Email and activeType2Text\n\n        */\n    }\n\n    // and then go trough the result set which is IEnumarable<T> and use it for what you need\n    foreach(var a in result)\n    { \n      var something = a.ActiveType1Email;\n      /* etc. */ \n    }	0
5957558	5957378	How to use a custom Resource provider with Attributes?	Approaches to solve the problem:	0
6867694	6867658	Quartz.Net - Quarterly starting from today	0 0 0 1 */3 ?	0
3142660	3136303	Convert DataTable to XML file and viceversa	myDT_For_DGV.TableName = "CheckOutsAndIns";\n\nif (openFileDialog1.ShowDialog() == DialogResult.OK) \n       {              \n              myDT_For_DGV.ReadXml(@openFileDialog1.FileName);\n            //MessageBox.Show(openFileDialog1.FileName);\n\n        }\n\n//TO WRITE TO XML\nif (myDT_For_DGV.Rows.Count != 0)\n        {\n            saveFileDialog1.ShowDialog();\n            saveFileDialog1.FileName = "checkOutFile.xml";\n            myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);\n        }	0
23034839	23034646	Get Value of Tuple From MySQL into String Array	using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection("S;Port=P;Database=DB;Uid=U;Pwd=P"))                      {\n       connection.Open();\n       MySql.Data.MySqlClient.MySqlCommand cmd=connection.CreateCommand();\n       cmd.CommandText = "SELECT * FROM table_name";\n       MySql.Data.MySqlClient.MySqlDataReader datr = cmd.ExecuteReader();            \n       coun = Convert.ToInt32(cmd.ExecuteScalar());\n       int counter = 0;\n       string[] First_String = new string[datr.FieldCount];\n       string[] Second_String = new string[datr.FieldCount];\n       string[] Third_String = new string[datr.FieldCount];\n       while (datr.Read()){                          \n                 First_String[counter] = datr[0].ToString();\n                 Second_String[counter] = datr[1].ToString();\n                Third_String[counter] = datr[2].ToString();\n                        /* and so on...*/   \n                counter++;\n       }\n}	0
30591639	30591548	ON c# I'm use Restsharp read data json client.Execute(request); why show format XML how do show format JSON	request.AddHeader("Accept", "application/json");\nrequest.AddHeader("Content-Type", "application/json; charset=UTF-8");	0
3939235	3938669	How can I get an active UNC Path in DFS programatically	public static ArrayList GetActiveServers(string sDFSPath, string sHostServer)\n{\n    ArrayList sHostNames = new ArrayList(); \n\n    ManagementPath oManagementPath = new ManagementPath();\n    oManagementPath.Server = sHostServer;\n    oManagementPath.NamespacePath = @"root\cimv2";\n\n    oManagementScope = new ManagementScope(oManagementPath);\n    oManagementScope.Connect();\n\n    SelectQuery oSelectQuery = new SelectQuery();\n    oSelectQuery.QueryString = @"SELECT * FROM Win32_DfsTarget WHERE LinkName LIKE '%" + sDFSPath.Replace("\\", "\\\\") + "%' and State = 1";\n\n    ManagementObjectSearcher oObjectSearcher = new ManagementObjectSearcher(oManagementScope, oSelectQuery);\n    ManagementObjectCollection oObjectCollection = oObjectSearcher.Get();\n\n    if (oObjectCollection.Count != 0)\n    {\n        foreach (ManagementObject oItem in oObjectCollection)\n        {\n            sHostNames.Add(oItem.Properties["ServerName"].Value.ToString());\n        }\n    }\n\n    return sHostNames;\n}	0
20872743	20872692	Insert command string building	// Obviously fill in the "..." with the rest of the fields you need to use\nstring sql = "INSERT INTO ProjectMaster (ProjectCode, TransactionType, ...) "\n           + "VALUES (@ProjectCode, @TransactionType, ...)";\nusing (var connection = new SqlConnection(...))\n{\n    connection.Open();\n    using (var command = new SqlCommand(sql, connection))\n    {\n        // Check the parameter types! We don't know what they're meant to be\n        command.Parameters.Add("@ProjectCode", SqlType.NVarChar).Value = ...;\n        command.Parameters.Add("@TransactionType", SqlType.NVarChar).Value = ...;\n        ...\n        command.ExecuteNonQuery();\n    }\n}	0
30590107	30589242	How to display date in custom format with Compact Framework	Dictionary<string,string> days = new Dictionary<string,string>();\ndays.Add("Monday", "MON");\ndays.Add("Tuesday", "TUE");\ndays.Add("Wednesday", "WED");\ndays.Add("Thuesday", "THU");\ndays.Add("Friday", "FRI");\ndays.Add("Saturday", "SAT");\ndays.Add("Sunday", "SUN");\n//Edit\nMessageBox.Show(days[DateTime.Now.DayOfWeek.ToString()] + DateTime.Now.ToString( " MM/dd"));	0
25160330	25160141	C# Find out if a control is showing on the screen	public bool isVisible(Control c)\n    {\n        if (c.Visible == false)\n            return false;\n        else\n            if (c.Parent != null)\n                return isVisible(c);\n            else\n                return c.Visible;\n    }	0
9823973	9812180	How to print a FlowDocument on a single page with different page sizes?	ColumnWidth="500"	0
18791472	18790875	How to parse a datetime string to date object	datetime = DateTime.Parse("2013-02-01T12:30:00.001+01:00");\n   //datetime object shows 2013-02-01 12:30:00 but the ms are still stored. \n   //just use "o"\n\n   WriteLine(datetime.ToString());\n   //2013-02-01 12:30:00\n\n   WriteLine(datetime.ToString("o"));\n   //2013-02-01T12:30:00.0010000+01:00\n\n   WriteLine(datetime.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz"));\n   //2013-02-01T12:30:00.001+01:00\n\n\n   String str = datetime.ToString("o");\n   WriteLine("my: "+str);\n   //my: 2013-02-01T12:30:00.0010000+01:00	0
10022783	9990243	Set value in model when dynamically creating object of model	object o = GetModuleType(model.ControllerName);\n        db.Entry(o).State = EntityState.Added;\n        try\n        {\n            db.Entry(o).CurrentValues["CommonProperty"] = DistinctValue;\n        }\n        catch (Exception err) { }	0
2173053	2172731	ASCII raw symbols to control a printer from a .txt file	printFile.WriteLine("\x02L");\nprintFile.WriteLine("D11");\nprintFile.WriteLine("ySWR");\nprintFile.WriteLine("421100001100096" + date);\nprintFile.WriteLine("421100002150096" + time);\nprintFile.WriteLine("421100001200160" + price);\nprintFile.WriteLine("E");\nprintFile.WriteLine();	0
6430183	6430153	Problems with settings a string C#	string ***deletetask*** = DeleteTaskBox.Text;\nScheduledTasks st = new ScheduledTasks(@"\\" + System.Environment.MachineName);\nst.DeleteTask(***deletest***);	0
6497639	6497592	LINQ: Getting Keys for a given list of Values from Dictionary and vice versa	var values = dictionary.Where(x => someKeys.Contains(x.Key)).Select(x => x.Value);\n var keys = dictionary.Where(x => someValues.Contains(x.Value)).Select(x => x.Key);	0
12380053	12380028	Passing a form as a reference into a class, but where should I call it from?	namespace MyApplication\n{\n    public partial class Form1 : Form\n    {\n        private Downloader downloader;\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            this.downloader = new Downloader(this);\n        }\n\n        private void downloadButton_Click(object sender, EventArgs e)\n        {\n           downloader.Whatever();\n        }\n    }\n}	0
1064231	1064213	Determine the name of a constant based on the value	public string FindConstantName<T>(Type containingType, T value)\n{\n    EqualityComparer<T> comparer = EqualityComparer<T>.Default;\n\n    foreach (FieldInfo field in containingType.GetFields\n             (BindingFlags.Static | BindingFlags.Public))\n    {\n        if (field.FieldType == typeof(T) &&\n            comparer.Equals(value, (T) field.GetValue(null)))\n        {\n            return field.Name; // There could be others, of course...\n        }\n    }\n    return null; // Or throw an exception\n}	0
497569	497209	How to set up a WCF client using wsDualHttpBinding in code?	Uri baseAddress = new Uri("http://localhost/CommService");\n WSDualHttpBinding wsd = new WSDualHttpBinding();\n EndpointAddress ea = new EndpointAddress(baseAddress, EndpointIdentity.CreateDnsIdentity("localhost"));\n client  = new CommServiceClient(new InstanceContext(this), wsd, ea);	0
19638707	19637623	How do I insert a string before my LINQ-created string?	var OutputText = listData.Select( x => x.Name, blah, blah, blah) );\nstring FilePath = @"C:\data.txt";\nSystem.IO.File.WriteAllLines(FilePath, Enumerable.Repeat(myHeaderString, 1)\n    .Concat(OutputText));	0
19617432	19617368	Sqlite database and datagrid	private void UpdateDataGrid(SQLiteConnection con, string sql)\n{\n    DataSet dataSet = new DataSet();\n    SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(sql, con);\n    dataAdapter.Fill(dataSet);\n\n    dataGrid.DataSource = dataSet.Tables[0].DefaultView;\n}	0
24512147	24511989	Winservice - Timer: Same task being executed parallel	private void TimerElapsed(object source, ElapsedEventArgs e)\n{ \n    _myTimer.Stop();\n    PerformAction();\n    _myTimer.Start();\n}	0
9203970	9203928	Is there a LINQ way to go from a list of key/value pairs to a dictionary?	var result = Enumerable.Range(0, array.Length / 2)\n                       .ToDictionary(i => array[i * 2], i => array[i * 2 + 1]);	0
14815201	14813345	Word Interop Move Table Row	Table tbl = aDoc.Tables[1];\n        Row toMove = tbl.Rows[src];\n        object beforeRow = tbl.Rows[dest];\n        Row newRow = tbl.Rows.Add(ref beforeRow);\n        toMove.Select();\n        wrd.Selection.Copy();\n        newRow.Select();\n        wrd.Selection.Paste();\n        toMove.Delete();\n        newRow.Delete();	0
11167985	11167300	IsolatedStorageException in Designview	using System.ComponentModel;\n\n...\n\nif (DesignerProperties.IsInDesignView)\n{\n    // return dummy data for the design view\n}\nelse\n{\n   // grab data from isolated storage\n}	0
17862453	17862427	C# Adding a root to an XDocument	XDocument yourResult = new XDocument(new XElement("Booklist", doc.Root));	0
9751897	9751666	Equate array of controls to existing control	RadioButton[] diff = new RadioButton[10];\n\nfor (int i = 0; i < 10; ++i)\n{\n    diff[i] = someparentControl.FindName("rad_D" + i.ToString()) as RadioButton;\n}	0
33233276	33233138	Get part of string data with LINQ	var domains = something.Select(e => e.Email).Select(s => s.Split('@')[1]).Distinct();	0
19400976	19400583	.NET for Windows Store Apps: UrlEncode	string sourceText = "??????";\nbyte[] win1251bytes = Encoding.GetEncoding("windows-1251").GetBytes(sourceText);\nstring hex = BitConverter.ToString(win1251bytes);\nstring result = "%" + hex.Replace("-", "%");\n// Result: %EF%F0%E8%E2%E5%F2	0
1093396	1093241	how to get string value from thread	Label1.Text = myVal;	0
23286021	23285849	How to replace a specific text in a line in c#	Regex.Replace(s,@"varchar\([0-9]*\)", "varchar(MAX)");	0
22660657	22659724	Getting a bool or int result from a Stored Proc	CREATE PROCEDURE [dbo].[testProc] \n    @inval bit output\nAS\nBEGIN\n    declare @outval bit\n\n    select @outval = @inval\n    select @outval\nEND\n\n\nusing (var dbContext = new testContext())\n{\n    var data = dbContext.Database.SqlQuery<bool>("exec testProc {0}",false).FirstOrDefault();\n    Console.WriteLine(data);\n}	0
27460487	27460384	copy one array to another at certain index c#	public static void CopyTo1(int[] array1, int[] array2, int startat)\n    {\n        for (int i = 0; i < array1.Length; i++)\n        {\n           array2[startat] = array1[i];\n            startat++;\n           Console.Write(array2[i].ToString());\n        }\n    }	0
18815864	18815779	Add a Generic List/Enumerable DataRow to DataTable?	foreach (T item in rowData)\n  {\n      foreach (PropertyDescriptor prop in properties)\n      {\n         DataRow newRow = _dataGridTable.NewRow();\n         foreach (DataColumn column in _dataGridTable.Columns)\n         {\n             if (columnsHashSet.Contains(prop.Name))\n             {\n                 newRow[prop.Name] = prop.GetValue(item) ?? DBNull.Value;\n                break;\n             }\n          }\n       }\n      _dataGridTable.Rows.Add(newRow); // _dataGridTable is my existing DataTable\n   }	0
24759853	24759805	Deserialize DateTime From C# CLR	string parameteres = string.Format"{\"Parameter\":{\"personId\":\"{0}\",\"date\":\"{1:yyyy-MM-dd HH:mm:ss}\"}}",PersonId,Date.Value);	0
26905987	26905853	application textbox display currency in $ instead of R	var saCulture = CultureInfo.GetCultureInfo("af-ZA");\nTxtActualYTDgros1.Text = String.Format(saCulture ,"{0:C}", Actual_YTD_Gross);\nTxtSpndPlan1.Text = String.Format(saCulture, "{0:C}", Spend_Plan_YTD);\nTxtVarience1.Text = String.Format(saCulture, "{0:C}", Variance_Value);	0
19314726	19301891	MvvmLight SimpleIoc and multiple concrete implementations	public interface IProvider { }\npublic abstract class BaseProvider : IProvider { }\npublic class Provider1 : BaseProvider { }\npublic class Provider2 : BaseProvider { }\n\n[Test]\npublic void RegisterTwoImplementations_GetAllInstances_ReturnsBothInstances()\n{\n    SimpleIoc.Default.Register<Provider1>();\n    SimpleIoc.Default.Register<Provider2>();\n\n    SimpleIoc.Default.Register<BaseProvider>(() => \n            SimpleIoc.Default.GetInstance<Provider1>(), "a" );\n\n    SimpleIoc.Default.Register<BaseProvider>(() =>\n            SimpleIoc.Default.GetInstance<Provider2>(), "b");\n\n    var result = SimpleIoc.Default.GetAllInstances<BaseProvider>();\n\n    Assert.That(result, Is.Not.Null);\n    Assert.That(result.Count(), Is.EqualTo(2));\n    Assert.That(result.Any(x => x.GetType() == typeof(Provider1)), Is.True);\n    Assert.That(result.Any(x => x.GetType() == typeof(Provider2)), Is.True);\n}	0
16310356	16301393	How do I create two images in same column within a slickgrid?	// if value is [dataContext.delete.id, dataContext.add.id] for example\nfunction twoButtonFormatter(row, cell, value, columnDef, dataContext) {\n  var str = ''; // initialize a string\n\n  // First button\n  str += "<input class='del' type='button' id='"+ value[0] +"' /> ";\n\n  // second button\n  str += "<button data-id='"+value[1]+"' class='add'>Add</button>";\n\n  // return the html string of both buttons\n  return str;\n}	0
6129519	6129496	Constructor requirements on generics parameter?	public interface MyInterface\n{\n    void Init(string s);\n    string S { get; set; }\n}\n\nT SomeMethod<T>(string s) : where T : MyInterface, new()\n{\n    var t = new T();\n    t.Init(s);\n\n    var t = new T\n    { \n        S = s\n    };\n\n    return t;\n}	0
5793447	5143513	Watin : Get Datetime and perform calculation	string myDate = this.Elements.textfield.Value;\nDateTime dt = Convert.ToDateTime(myDate);\nDateTime dtNew = dt.AddDays(-3);\nthis.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());	0
15197485	15197240	validate variable before use in function	public XmlNode getName(String a, double b)\n{\n   int someval;\n   if (int.TryParse(s, out someval))\n   {\n       // do whatever you were going to in here, but using someval not a\n   }\n   else\n   {\n      return null;\n   }  \n}	0
7889101	7888937	How to read a List<> from an XML file using C#? (XNA based issue)	public void LoadContent(XDocument doc, TileMap myMap)\n{\n    var lookup = new Dictionary<string, Action<string>>()\n    {\n        { "E", v => { Console.WriteLine("E  = " + v); } },\n        { "ID", v => { Console.WriteLine("ID = " + v); } },\n        { "B", v => { Console.WriteLine("B  = " + v); } },\n        { "H", v => { Console.WriteLine("H  = " + v); } },\n        { "T", v => { Console.WriteLine("T  = " + v); } },\n    };\n\n    var actions =\n        from e in doc.Root\n            .Element("Asset")\n            .Element("R")\n            .Elements("Item")\n            .Elements("C")\n        from mv in e\n            .Elements("Item")\n            .Elements()\n        let name = mv.Name.ToString()\n        let value = mv.Value\n        select new Action(() => lookup[name](value));\n\n    foreach (var a in actions)\n        a.Invoke();\n}	0
29683115	29682804	Can I pass a filtered CollectionViewSource to a method?	List<MyObject> lst = cvs.Cast<MyObject>().ToList();	0
26835007	26834920	How to save and read a text?	public class ExampleClass : MonoBehaviour \n{\n    void saveScore(int score) \n    {\n        PlayerPrefs.SetInt("Player Score", score);\n    }\n\n    void getScore() \n    {\n        print(PlayerPrefs.GetInt("Player Score"));\n    }\n}	0
18873218	18873110	Using reflection to set properties from a dictionary	//Get the type\nvar type= this.GetType();\n\nforeach (string key in Settings.Keys) \n{\n    //Get the property\n    var property = type.GetProperty(key);\n    //Convert the value to the property type\n    var convertedValue = Convert.ChangeType(Settings[key], property.PropertyType);\n    property.SetValue(this, convertedValue); \n}	0
18129878	18126385	convert string to double now working?	f = Convert.ToDouble(textBox1.Text, new System.Globalization.CultureInfo("en-US"));	0
18278908	18278892	How to replace forward slash with backward slash	string.Replace("/", "\\")\nstring.Replace("/", @"\")	0
295263	295254	How do I implement a cancelable event?	class Foo\n{\n    public event CancelEventHandler Bar;\n\n    protected void OnBar()\n    {\n        bool cancel = false;\n        CancelEventHandler handler = Bar;\n        if (handler != null)\n        {\n            CancelEventArgs args = new CancelEventArgs(cancel);\n            foreach (CancelEventHandler tmp in handler.GetInvocationList())\n            {\n                tmp(this, args);\n                if (args.Cancel)\n                {\n                    cancel = true;\n                    break;\n                }\n            }\n        }\n        if(!cancel) { /* ... */ }\n    }\n}	0
17167093	17166667	Validating an XML against an embedded XSD in C#	Stream objStream = objFile.PostedFile.InputStream;\n\n// Open XML file\nXmlTextReader xtrFile = new XmlTextReader(objStream);\n\n// Create validator\nXmlValidatingReader xvrValidator = new XmlValidatingReader(xtrFile);\nxvrValidator.ValidationType = ValidationType.Schema;\n\n// Add XSD to validator\nXmlSchemaCollection xscSchema = new XmlSchemaCollection();\nxscSchema.Add("xxxxx", Server.MapPath(@"/zzz/XSD/yyyyy.xsd"));\nxvrValidator.Schemas.Add(xscSchema);\n\ntry \n{\n  while (xvrValidator.Read())\n  {\n  }\n}\ncatch (Exception ex)\n{\n  // Error on validation\n}	0
9800272	9800110	ASP.NET C# - How to retain value after Response.Redirect	protected void ddl_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string id = ddl.SelectedValue;\n    string id2 = ddl2.SelectedValue;\n    HttpCookie cookie = new HttpCookie("SecondId", id2);\n    Response.Cookies.Add(cookie);\n    Response.Redirect("http://sharepoint2007/sites/home/Lists/CustomList/DispForm.aspx?ID=" + id);\n}\n\nprotected void OnLoad(object sender, EventArgs e)\n{\n    string id2 = Request.Cookies["SecondId"];\n    //send a cookie with an expiration date in the past so the browser deletes the other one\n    //you don't want the cookie appearing multiple times on your server\n    HttpCookie clearCookie = new HttpCookie("SecondId", null);\n    clearCookie.Expires = DateTime.Now.AddDays(-1);\n    Response.Cookies.Add(clearCookie);\n}	0
7520141	7519093	Unable to change selectedNode in a treeView during AfterLabelEdit	void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {\n        TreeNode nextnode = this.treeView1.SelectedNode.Parent;\n        var timer = new Timer() { Enabled = true, Interval = 50 };\n        timer.Tick += delegate {\n            this.treeView1.SelectedNode = nextnode;\n            timer.Dispose();\n        };\n    }	0
9085700	9085603	How can I wrap a method with a callback parameter into a Task?	public Task<bool> AskConfirmation()\n{\n    var tcs = new TaskCompletionSource<bool>();\n    AskConfirmation(b => tcs.TrySetResult(b));\n    return tcs.Task;\n}	0
6359504	6359281	Page Life Cycle, does db connection go in Page_Load	string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";\nusing (SqlConnection mySqlConnection = new SqlConnection(connectionString))\n{\n    string procedureString = "Callin_Insert";\n    SqlCommand mySqlCommand = new SqlCommand(procedureString, mySqlConnection);\n    mySqlCommand.CommandType = CommandType.StoredProcedure;\n\n    mySqlCommand.Parameters.Add("@LVDate", SqlDbType.DateTime).Value = DateTime.Now;\n    mySqlCommand.Parameters.Add("@LVTime", SqlDbType.DateTime).Value = DateTime.Now;\n    mySqlCommand.Parameters.Add("@CuID", SqlDbType.Int).Value = CustID;\n    mySqlCommand.Parameters.Add("@Type", SqlDbType.Int).Value = Keypress;\n\n    mySqlConnection.Open();\n    mySqlCommand.ExecuteNonQuery();\n\n    //i have no idea what does this mean, data adapter is for filling Datasets and DataTables\n    SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();\n    mySqlDataAdapter.SelectCommand = mySqlCommand;\n}	0
22865378	22862377	c# internet explorer control , make style none as if wpf window style none and allowtransparency	Window window = new Window();\nwindow.WindowStyle = WindowStyle.None;\nwindow.ResizeMode = ResizeMode.NoResize;\nwindow.Width = 800;\nwindow.Height = 600;\n\nWebBrowser webBrowser = new WebBrowser();\nwebBrowser.Navigate("http://m.naver.com");\n\nwindow.Content = webBrowser;\nwindow.Show();	0
10031616	10029884	getting split weeks in method to get list of months	var monthlist1 =                \n    data.Select(x => new { wkdate = x.WKENDDATE }).OrderBy(y => y.wkdate).Where(l=> ExportHelper.isSplitWeek(l.wkdate,l.wkdate.AddDays(6)) != true)\n    .Select(m => new{monthname = m.wkdate.ToString("MMM yyyy", CultureInfo.CreateSpecificCulture("en-US"))})\n    .Distinct()            \n    .ToList();\n\n  var monthlist2 = \n     data.Select(x => new { wkdate = x.WKENDDATE.AddDays(6) }).OrderBy(y => y.wkdate).Where(l=> ExportHelper.isSplitWeek(l.wkdate.AddDays(-6),l.wkdate) == true).Select(m => new\n    {monthname = m.wkdate.ToString("MMM yyyy", CultureInfo.CreateSpecificCulture("en-US"))}) \n    .Distinct()            \n    .ToList();\n\n  var monthlist = monthlist2.Union(monthlist1)\n   .Distinct()\n   .ToList();	0
16125591	16125513	Use of a DataGridView with C# and MySQL	cmd.CommandText = "SELECT m.cvemunicipio, m.nombre AS NombreA, e.nombre AS NombreB FROM tbMuncipios m INNER JOIN tbEstados e ON m.CveEstado = e.CveEstado";	0
3939647	3939618	Interface is forceing abstract class to implement its functions	public abstract void MyMethodDeclaredInTheInterface();	0
6249091	6249041	How to send username password to website from windows application	var client = new RestClient("http://example.com");\n\nvar request = new RestRequest("resource/{id}", Method.POST);\nrequest.AddParameter("username", txtUsername.Text); // adds to POST or URL querystring based on Method\nrequest.AddParameter("password", txtPassword.Text); // adds to POST or URL querystring based on Method\n\n// execute the request\nRestResponse response = client.Execute(request);\nvar content = response.Content; // raw content as string	0
2459122	2435638	How to get levels for Fry Graph readability formula?	Bitmap image = new Bitmap(@"C:\FryGraph.png");\n\nimage.GetPixel(int x, int y);	0
7586327	7586225	Attaching a .avi file to an email	MailMessage nMsg = new MailMessage();\n\nnMsg.From = new MailAddress(fromAddress);\nnMsg.Subject = subject;\n\nAttachment attachFile = new Attachment("Your file path here");\nnMsg.Attachments.Add(attachFile);\n\nSmtpClient mailer = new SmtpClient("yousmtpserver");\nmailer.Send(nMsg);	0
872809	872796	Asp.net mvc - Accessing view Model from a custom Action filter	filterContext.Controller.ViewData.Model	0
32205740	32205629	How to assign object to field	Dictionary<int, string> myDict = new Dictionary<int, string>();\nmyDict.Add(1, "Sth1");\nmyDict.Add(2, "Sth2");\nmyDict.Add(3, "Sth3");\n\nstring Result = myDict[3]; //Sth3	0
17969110	17969060	How can I get conditional data with LINQ	yourcollection.Where(i => i.IsOk).Select(i => i.Number).ToList()	0
13336264	13336198	How to use more than one Operator in an If Statement using C#	DateTime strExpectedSubDate = DateTime.ParseExact(gr.Cells[3].Text, dateformat);\nDateTime strAuthReqDate = DateTime.ParseExact(gr.Cells[8].Text, dateformat);\nDateTime strDate = System.DateTime.Now;\nif (strAuthReqDate == null && strDate < strExpectedSubDate)\n{\n}	0
14285112	14285067	Entity Framework contains clause doesn't find	using (var context = new eTicaretEntity())\n{\n    return context.GetActiveProducts()\n                  .Where(p => p.Name.ToUpper().Contains(name.ToUpper()))\n                  .ToList();\n}	0
26295129	26155856	How to RESEED LocalDB Table using Entity Framework?	context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('TableName', RESEED, 0)")	0
24655791	24655608	String array to byte array C#	string[] abc = new string[]{"hello", "myfriend"};\n\nstring fullstring = String.Join(Environment.NewLine, abc);    // Joins all elements in the array together into a single string.\nbyte[] arrayofbytes = Encoding.Default.GetBytes(fullstring);     // Convert the string to byte array.	0
32915245	32914833	Determine if the paragraph is a standard text or a heading	switch(thisparagraphStyle.ParagraphFormat.OutlineLevel)\n{\n  case WdOutlineLevel.wdOutlineLevel1:\n    // Heading 1\n    break; \n  case WdOutlineLevel.wdOutlineLevelBodyText:\n    // Body Paragraph\n    break;\n}	0
30114487	30019488	Marshalling C-style array of LPWSTR to managed string[] using pInvoke	[DllImport("Dll1.Windows.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]\n    public static extern void TestArrayOfStrings(\n        [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] [Out] out string[] test, \n        out int size, string someString);\n\nextern "C" DLL1_API void TestArrayOfStrings(wchar_t ***strings, int *size, wchar_t *someString){\n    const size_t alloc_size = 64; \n    STRSAFE_LPWSTR temp = (STRSAFE_LPWSTR)CoTaskMemAlloc(alloc_size);\n    StringCchCopy(temp, alloc_size, someString);\n    *strings = (wchar_t **)CoTaskMemAlloc(sizeof(wchar_t));\n    *strings[0] = temp;\n    *size = 1;\n}	0
13167738	13167677	How to write a method that takes an enum as a generic and returns the int value	public static int ToInt(this Enum value)\n{\n    return Convert.ToInt32(value);\n}	0
3649199	3649145	Using ref parameters in linq	Func<string, int, Line> lineFunc = (pt, ll) =>\n{\n    int offset = 0;\n    return new Line() { Text = BreakLine(pt, ll, ref offset) };\n};\nvar test = from pt in productText\n            from ll in lineLimits\n            select lineFunc(pt, ll);	0
16921262	16920892	Manipulating information stored in array	private void netOilRadBtn_CheckedChanged(object sender, EventArgs e)\n{\n    using (var sw = new StreamWriter("test.txt")) //testing purposes only\n    { \n        //StreamReader sr = new StreamReader("OUTPUT.CSV");\n\n        var items =  netOil.Zip(seqNum, (oil, seq) => new {Oil = oil, Seq = seq});\n        var items2 =  netOil2.Zip(seqNum2, (oil, seq) => new {Oil = oil, Seq = seq});\n\n        foreach (var item in items.Join(items2,\n                     i=>i.Seq,i=>i.Seq, (a,b)=>\n                     {\n                         double first = Convert.ToDouble(a.Oil);\n                         double second = Convert.ToDouble(b.Oil);\n\n                         double answer = (first - second) / first;\n                         return string.Format("{0}, {1}", a.Seq, answer);\n                     }))\n\n        { \n            sw.WriteLine(item);\n        }\n    }\n}	0
8260558	8260357	Extract information from a String once matches	string UserInfoPattern = @"UserInfo='(?<UserInfo>[^']+)";\nstring HostInfoPattern = @"HostInfo='(?<HostInfo>[^']+)";	0
24691640	24691532	How to debug an application which suddenly terminates without any feedback?	Runtime.getRuntime().gc();	0
27746541	27746141	Compare two images with PictureBox controls	private int pos = 0; //x coordinate of mouse in picturebox\n\nprivate void pictureBox1_Paint(object sender, PaintEventArgs e)\n{\n    if(pos == 0)\n    {\n        e.Graphics.DrawImage(Properties.Resources.imageRight, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));\n    }\n    else\n    {\n        e.Graphics.DrawImage(Properties.Resources.imageLeft, new Rectangle(0, 0, pos, pictureBox1.Height),\n            new Rectangle(0, 0, pos, pictureBox1.Height), GraphicsUnit.Pixel);\n        e.Graphics.DrawImage(Properties.Resources.imageRight, new Rectangle(pos, 0, pictureBox1.Width - pos, pictureBox1.Height),\n            new Rectangle(pos, 0, pictureBox1.Width - pos, pictureBox1.Height), GraphicsUnit.Pixel);\n    }\n}\n\nprivate void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    pos = e.X;\n    pictureBox1.Invalidate();\n}	0
21194764	21194609	How to perform action when Shift+Enter is pressed?	if (Keyboard.Modifiers == ModifierKeys.Shift && Keyboard.IsKeyDown(Key.Enter))\n{\n    MessageBox.Show("test");\n}	0
11511924	11511831	How can i loop through Two Lists <float> in another List? And then put the strings to a key? Almost working	string[] xFrames = new string[wocl.Count];\nstring[] yFrames = new string[wocl.Count];\n\nfor (int i = 0; i < wocl.Count; i++)\n{\n   xFrames[i] = string.Format("Frame_X_{0} ", i + 1);\n   yFrames[i] = string.Format("Frame_Y_{0} ", i + 1);\n\n   for(int j =0; j < wocl[i].Length; j++)\n   {\n       xFrames[i] += string.Format("{0},", wocl[i].Point_X[j]);\n       yFrames[i] += string.Format("{0},", wocl[i].Point_Y[j]);\n   }\n\n   xFrames[i].Trim(",".ToCharArray());\n   yFrames[i].Trim(",".ToCharArray());\n}	0
7315933	7306353	Delete Wall Post on page as page C# SDK	var fb = new FacebookClient("pageAccessToken");\nfb.Delete(postId);	0
17776602	17776393	Resize and Fit Image in WPF	int x1 = 0, y1 = 0, x2 = 50, y2 = 50;\nif (img. Width <= img.Height) \n{\n   // compute x1, y1 to fit img horizontally into bmp\n}\nelse\n{\n   // compute y1, y2 to fit img vertically into bmp\n}\n\ng.DrawImage(img, x1,y1, x2,y2);	0
2432482	2432428	Is there any algorithm for calculating area of a shape given co-ordinates that define the shape?	class Point { double x, y; } \n\ndouble PolygonArea(Point[] polygon)\n{\n   int i,j;\n   double area = 0; \n\n   for (i=0; i < polygon.Length; i++) {\n      j = (i + 1) % polygon.Length;\n\n      area += polygon[i].x * polygon[j].y;\n      area -= polygon[i].y * polygon[j].x;\n   }\n\n   area /= 2;\n   return (area < 0 ? -area : area);\n}	0
6829795	6829678	How to delete selected Items from a ListView by pressing the delete button?	private void listView1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (Keys.Delete == e.KeyCode)\n    {\n        foreach (ListViewItem listViewItem in ((ListView)sender).SelectedItems)\n        {\n            listViewItem.Remove();\n        }\n    }\n}	0
16432505	16432450	Convert a List<T> into an ObservableCollection<T>	ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);	0
5373552	5373473	How do you take the reciprocal of a vector?	Vector2 Velocity\nVector2 Reciprocal\nReciprocal.X = Reciprocal.Y = Math.Sqrt(Math.Pow((1.0/Velocity.Length()),2)/2)	0
1206029	1206019	Converting string to title case in C#	string title = "war and peace";\n\nTextInfo textInfo = new CultureInfo("en-US", false).TextInfo;\ntitle = textInfo.ToTitleCase(title); //War And Peace	0
30677920	30677892	how to print members of a class when one of the properties of the class is a list	foreach (Course course in courses) \n{\n  resultLabel.Text += course.FormatDetailsForDisplay();\n  foreach(var student in course.Students)\n   resultLabel.Text += "student:" + student.Name;\n}	0
23274841	23273718	DataSet showing name only and not table data c#	dt.Rows.Add(ds.Tables["IncomingProductTotals"]);	0
8072724	8068156	access to full resolution pictures from camera with MonoDroid	private string _imageUri;\n\nprivate Boolean isMounted\n{\n    get\n    {\n        return Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted);\n    }\n}\n\npublic void BtnCameraClick(object sender, EventArgs eventArgs)\n{\n      var uri = ContentResolver.Insert(isMounted ? MediaStore.Images.Media.ExternalContentUri\n                              : MediaStore.Images.Media.InternalContentUri, new ContentValues());\n     _imageUri = uri.ToString();\n      var i = new Intent(MediaStore.ActionImageCapture);\n      i.PutExtra(MediaStore.ExtraOutput, uri);\n      StartActivityForResult(i, CAPTURE_PHOTO);\n}\n\n    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\n    {\n        if (resultCode == Result.Ok && requestCode == CAPTURE_PHOTO)\n        {\n          Toast.MakeText(this, string.Format("Image URI is {0}",_imageUri), ToastLength.Short).Show();    \n        }\n    }	0
5419433	5419278	Get index of an object in a Generic list	int index = list.FindIndex(MiniMapRecord p => p.IDa == IDa.SystemID & p.IDb == pInputRecordMap.IDb);	0
33502279	33461098	RDLC report columns based on DataTable columns	MainReportByPatient.rdlc\nPatient name, birth, id, etc\naddress, phone, email, etc...\n+------------\n|  SubReportMeds.rdlc\n|  +------------\n|  |  Medication    Dose     Purpose\n|  |  details...    details  details\n|  |  details...    details  details\n|  |  details...    details  details\n|  +-------------\n|  ExamHistory.rdlc\n|  +------------\n|  |  Exam Date     Reason     blah...\n|  |  details...    details... blah..\n|  |  details...    details... blah..\n|  |  details...    details... blah..\n|  |  ExamDetail.rdlc\n|  |  +-------------\n|  |  | additional nested level per exam to show details... just example\n|  |  +-------------\n|  |\n|  +------------\n|\n+-------------	0
13407625	13407606	Get all days of week to datagridview columns	???\ndataGridView1.Columns[i].HeaderText += (dtStart + counter).DayOfWeek.ToString();	0
20235711	20234347	Evaluating a mathematical expression	public Double Calculate(string argExpression)\n        {\n            //get the user passed string\n            string ExpressionToEvaluate = argExpression;\n            //pass string in the evaluation object declaration.\n            Expression z = new Expression(ExpressionToEvaluate);\n            //command to evaluate the value of the **************string expression\n            var result = z.Evaluate();\n            Double results = Convert.ToDouble(result.ToString());\n\n            return results;\n\n        }	0
2112010	2111971	How can I loop a process that ends in an event? (c#.NET)	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n    {\n        var worker = sender as BackgroundWorker;\n\n        while (true) // or something\n        {\n            DoProcess();\n            worker.ReportProgress(0, null);\n        }\n    }\n\n    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)\n    {\n        OnFinished();\n    }	0
22593590	22592817	Set the style of a custom button	this.Style = (Style)Application.Current.Resources["CfcButtonStyle"];	0
28118882	28086619	how do I prevent datagridview checkbox column replication	DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();\ncol.Name = "myColumn";\n// Set any other desired properties ...\n\nif (!dataGridView1.Columns.Contains(col.Name))\n{\n    dataGridView1.Columns.Add(col);\n}	0
13398783	13398526	Cannot add manual anonym items to IQueryable	[DataContract]\npublic class CountryInfo\n{\n    [DataMember(Name = "country")]\n    public string Country { get; set; }\n\n    [DataMember(Name = "schengen", EmitDefaultValue = false)\n    public bool? Schengen { get; set; }\n}	0
4764631	4764401	Please show me what's going wrong with this delete row function for SQL in C#	dAdapter.DeleteCommand	0
1598582	1597074	Send Authenticated User To WCF Application	public void BeginSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)\n{\n   string currentContextUserName = HttpContext.Current.User.Identity.Name;\n\n   MessageHeader userNameHeader = MessageHeader.CreateHeader("Username", "urn:my-custom-namespace", currentContextUserName);\n\n   request.Headers.Add(userNameHeader);\n}	0
17966261	17966221	c# SIMPLE factorial program	result = NewUserNumber * (NewUserNumber - 1);	0
32108696	32108501	Automapper Member mapping on codition SeemsConvoluted	var context = new Context {\n    WellId = myObject.Id,\n    Name = myObject.Name,\n    Important = (isOptionTrue ? myObject.NormProp : myObject.ReplayProp)\n};	0
19660677	19660366	Changing one element of string in hashtable in C#	for (int i = 0; i < 10; i++)\n{\n    Console.WriteLine("Vnesete kluc");\n    string kluc = Console.ReadLine();\n    if (kluc.StartsWith("a"))\n        kluc = "A" + kluc.Substring(1);\n    Console.WriteLine("Vnesete podatok");\n    string podatok = Console.ReadLine();\n    hashtable.Add(kluc, podatok);\n}	0
12939805	12939553	Linking Combo box item to a web page in C#	private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n\n        ComboBoxItem item = comboBox.SelectedItem as ComboBoxItem;\n\n\n    }	0
7283365	6981974	Copying with c# in geoserver	using System;\nusing System.Net;\nusing System.IO;\n\n...\n\nstring url = "http://localhost:8080/geoserver/rest/workspaces";\nWebRequest request = WebRequest.Create(url);\n\nrequest.ContentType = "text/xml";\nrequest.Method = "POST";\nrequest.Credentials = new NetworkCredential("admin", "geoserver");\n\nbyte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");\nStream reqstr = request.GetRequestStream();\nreqstr.Write(buffer, 0, buffer.Length);\nreqstr.Close();\n\nWebResponse response = request.GetResponse();\n\n...	0
32347827	32230665	Pagination with PrincipalSearcher	((DirectorySearcher) searcher.GetUnderlyingSearcher()).PageSize = 0;	0
20793839	20793788	How to access property in foreach List	foreach(var item in after_grouping)\n{ \n    listAfterCopy.Add(\n        new SelectedItemOnPoCopy(\n            item.no.category_subcategory,\n            item.no.item,\n            item.price,\n            item.quantity\n        )\n    );\n}	0
3943362	3943323	how to deal with Unexpected date & time format's?	string dateString = "03/01/2009 10:00 AM";\n    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");\n    DateTimeStyles styles DateTimeStyles.None;\n    DateTime dateResult;\n\n    if(DateTime.TryParse(dateString, culture, styles, out dateResult))\n    {\n        do something with dateResult\n    }	0
13715102	13714822	How can I measure the aproximation of the time spent in a process context switch?	ManagementScope managementScope = new ManagementScope("\\\\.\\ROOT\\cimv2");\nObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Thread");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, objectQuery);\nManagementObjectCollection objectCollection = searcher.Get();\n\nforeach (ManagementObject m in objectCollection)\n{\n    Console.WriteLine("ContextSwitchesPersec : {0}", m["ContextSwitchesPersec"]);\n}	0
30120180	30119947	Find the minimum value with the same id in a list	myObjects = myObjects\n    .Groupby(obj => obj.Id)\n    .Select(grp => grp.OrderBy(obj => obj.OperationId).First())\n    .ToList();	0
28183886	28183776	Azure SQL Server Rest API access	Azure Service Management API	0
315265	315231	Using Reflection to set a Property with a type of List<CustomClass>	class Foo\n{\n    public string Bar { get; set; }\n}\nclass Program\n{\n    static void Main()\n    {\n        Type type = typeof(Foo); // possibly from a string\n        IList list = (IList) Activator.CreateInstance(\n            typeof(List<>).MakeGenericType(type));\n\n        object obj = Activator.CreateInstance(type);\n        type.GetProperty("Bar").SetValue(obj, "abc", null);\n        list.Add(obj);\n    }\n}	0
30859585	30845804	Display google chart date in dd MMM yyyy format	var data = new google.visualization.DataTable();\n        data.addColumn('date', 'Column Name');\n        data.addColumn('number', 'Temp. In Celsius');\n        data.addColumn({ type: 'string', role: 'annotation' });\n        data.addColumn({ type: 'string', role: 'annotationText' });\n\nfor (var i = 0; i < dataValues.length; i++) {              \n\n\ndata.addRow([ToJavaScriptDate(dataValues[i].ColumnName),dataValues[i].Value, 'Min Temp', 'Min temp']);\n            }                 \n\n\n  // used to convert  string to date \n    function ToJavaScriptDate(value) {\n        var pattern = /Date\(([^)]+)\)/;\n        var results = pattern.exec(value);\n        return new Date(parseFloat(results[1]));\n    }	0
16151296	16150994	how to determine which cells in a datagridview are checked?	foreach(DataGridViewRow row in dataGridView.Rows){\n    if (row.Cells[0].Value != null && (bool)row.Cells[0].Value){\n       //checked, do something\n    }\n}	0
6999292	6998916	Duplicate console output of self process	var writer = new SplitWriter(Console.Out, @"c:\temp\logfile.txt");\nConsole.SetOut(writer);	0
15726500	15726197	Parsing a JSON array using Json.Net	string json = @"\n[ \n    { ""General"" : ""At this time we do not have any frequent support requests."" },\n    { ""Support"" : ""For support inquires, please see our support page."" }\n]";\n\nJArray a = JArray.Parse(json);\n\nforeach (JObject o in a.Children<JObject>())\n{\n    foreach (JProperty p in o.Properties())\n    {\n        string name = p.Name;\n        string value = (string)p.Value;\n        Console.WriteLine(name + " -- " + value);\n    }\n}	0
274545	274544	Retrieving annotated method from attribute constructor	foreach(Type type in assembly)	0
25176553	25176493	How to fire JS from code behind of a UserControl by an event	1). ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "alert('hi!')", true);//no need to use javascript with alert when bool set to true\n\n 2). ScriptManager.RegisterStartupScript(page, page.GetType(), "msg", "alert('hi!')", true);\n\n 3). ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('hi!');</script>", true);	0
10884411	10884322	Calling a service via Ajax Request	[System.Web.Script.Services.ScriptService()]	0
15267973	15267230	C# Excellibrary - how to get cell content?	Workbook book = Workbook.Load(directory + "file.xls");\nWorksheet sheet = book.Worksheets[0];\nxlInfo = new string[sheet.Cells.LastRowIndex, 3];\n\nxlInfo[0, 0] = Convert.ToString(sheet.Cells[1, 0]);\nxlInfo[0, 1] = Convert.ToString(sheet.Cells[1, 1]);\nxlInfo[0, 2] = Convert.ToString(sheet.Cells[1, 2]);	0
9699409	9698883	Programming C# array multiplication	private string addEveryOther(string x) \n{    \n  int[] d = x.Select(n => Convert.ToInt32(n.ToString())).ToArray();\n\n  for(int i = 0; i < d.Length; i += 2)\n  {\n    d[i] = d[i] * 2;\n    MessageBox.Show(d[i].ToString()); //Display the result? \n  }\n\n  // And later returning a string:\n  return String.Concat(d.Select(n => n.ToString()));\n}	0
11449985	11449691	How to rewrite a string by pattern	Regex rgx = new Regex( @"\({[^\}]*\})");\nstring output = rgx.Replace(input, new MatchEvaluator(DoStuff));\n\n\nstatic string DoStuff(Match match)\n{\n//Here you have access to match.Index, and match.Value so can do something different for Match1, Match2, etc.\n//You can easily strip the {'s off the value by \n\n   string value = match.Value.Substring(1, match.Value.Length-2);\n\n//Then call a function which takes value and index to get the string to pass back to be susbstituted\n\n}	0
17990277	17989241	How to mock Application.Current for unit-testing?	if(Application.ResourceAssembly == null)\n    Application.ResourceAssembly = typeof(MainWindow).Assembly;\n\nvar window = new MainWindow();	0
22499380	22497373	restore application in old state after automatic shutdown of application in WPF	using using System.Runtime.Serialization.Formatters.Binary;\nusing System.IO;\n[Serializable]\nclass Example\n{\n    private int i;\n    private void Save(string fileToSave)\n    {\n        using(Stream writer = File.OpenWrite(fileToSave))\n        {\n            BinaryFormatter bf = new BinaryFormatter();\n            bf.Serialize(writer, this);\n        }\n    }\n    private void Load(string loadFromFile)\n    {\n        using (Stream reader = File.OpenRead(loadFromFile))\n        {\n            BinaryFormatter bf = new BinaryFormatter();\n            Example temp = (Example)bf.Deserialize(reader);\n            //and here you can restore your class from loadFromFile\n            this.i = temp.i;\n        }\n    }\n}	0
142362	142356	Most efficient way to get default constructor of a Type	type.GetConstructor(Type.EmptyTypes)	0
4720153	4720129	How do I create a variable that a different thread can use? (C#)	void Main() \n{\n    a.doit();\n}\n\npublic class a\n{\n      private static int i = 1;\n      public static void doit()\n      {\n        Thread ask = new Thread (new ThreadStart (prompt));\n\n        ask.Start();\n        Console.WriteLine(i);\n        Console.Read();\n        Console.WriteLine(i);\n      }\n\n    static void prompt()\n    {\n        Console.WriteLine ("Testing!");\n        a.i++;\n    }\n}	0
15676087	15676058	How to execute a command via command-line and wait for it to be done	public void runCmd()\n {\n    String command = @"/k java -jar myJava.jar";\n    ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");\n    cmdsi.Arguments = command;\n    Process cmd = Process.Start(cmdsi);\n    cmd.WaitForExit();    \n }\n.\n.\n.\n runCmd(); ? ? ? ?\n MessageBox.Show("This Should popup only when runCmd() finishes");	0
26843370	26843247	FormatException when trying to write string to database	da.InsertCommand.Parameters.Add("@Price", SqlDbType.Decimal).Value = txtPPrice.Text;	0
1523572	1523553	How to SetValue a Dynamic Type Field	string typeName = Request.QueryString["TypeName"];\nType t = Type.GetType(typeName);\nobject instance = Activator.CreateInstance(t);\nt.GetField("SomeField").SetValue(instance, "Hello");	0
11118662	10757617	How I can have two connections open at once to synchronize two databases mysql in c#?	string const query = "SELECT * FROM LocalTableName";\nusing (DbCommand sql =_MySQLConnection.CreateCommand()){\n    sql.CommandText = query;\n    using (DbDataReader row = sql.ExecuteReader()){\n        // the data is sstored in row now upload to remote\n        using (DbCommand sql_remote = _MySQLRemote.CreateCommand()){\n            sql_remote.CommandText = "INSERT INTO RemoteTableName SET field1 = @p_field1";\n            sql.Parameters.Add("@p_field1", row["field1"].toString());\n            sql.ExecuteNonQuery();\n            sql.Parameters.Clear();\n        }\n    }\n}	0
13371161	13371052	LINQ to xml - how do I select a particular node?	var doc = XDocument.Parse(xmltext);\nvar selectedRegion = doc.Root.Descendents("region").FirstOrDefault(r => r.Attribute("section").Value == "target value");	0
29195115	29194980	Using GetElementsByTagName in C# Windows Form with XML	xd1.LoadXml("<data>" + ns[0].InnerXml + "</data>");	0
27926461	27926117	Using ValueConversion in a XAML application in Windows 8.1	public object Convert(object value, Type targetType, \n        object parameter, string language)\n\npublic object ConvertBack(object value, Type targetType, \n        object parameter, string language)	0
1323053	1323007	Adding a Column of one datatable to another	DataTable tbl1;\nDataTable tbl2;\n\ntbl1.Columns.Add("newCol");\n\nfor(int i=0; i<tbl.Rows.Count;i++)\n{\n   tbl1.Rows[i]["newcol"] = tbl2.Rows[i]["newCol"];\n   tbl1.Rows[i]["date"] = tbl2.Rows[i]["date"];\n}	0
16908205	16908197	Replacing string characters in c#	var output = Regex.Replace(input, @"#(\w+)", "*$1*");	0
28317190	28316962	Looping through a CSV file and storing line value in a variable C#	private static void YourApiCall(string email)\n{\n   //...\n}\n\nprivate static void RunApiWithEmailsFrom(string file)\n{\n    System.IO.File.ReadLines(file).ToList().ForEach(YourApiCall);\n}	0
9064954	662379	Calculate date from week number	public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)\n{\n    DateTime jan1 = new DateTime(year, 1, 1);\n    int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;\n\n    DateTime firstThursday = jan1.AddDays(daysOffset);\n    var cal = CultureInfo.CurrentCulture.Calendar;\n    int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n\n    var weekNum = weekOfYear;\n    if (firstWeek <= 1)\n    {\n        weekNum -= 1;\n    }\n    var result = firstThursday.AddDays(weekNum * 7);\n    return result.AddDays(-3);\n}	0
7396386	7395674	Server/client sockets	Socket socketListener;\n\n// create listening socket\nsocketListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);\nIPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 30120);      // use port 30120\n//bind to local IP Address.\nsocketListener.Bind(ipLocal);\n\n//start listening\nsocketListener.Listen(4);\nwhile (true)   // loop that accepts client connections\n{\n    Socket socketWorker = socketListener.Accept();\n    HandleClientConnection(socketWorker);   // your routine where you communicate with a client\n}	0
30339161	30339083	How to add properties to controls that are created in a class ASP.NET C#?	browser.Attributes["multiple"] = "multiple"	0
14725465	14725368	How to extract the filename from a request url using Regex in ASP.NET	Match fileNameMatch = Regex.Match("url", @"\w+\.aspx");\n   string fileName = fileNameMatch.Value;	0
19283623	19283495	Rounding decimals to two decimal places in c#	d = Math.Ceiling(d * 100) / 100;	0
3169683	3169517	python: c# binary datetime encoding	>>> x = 634124502600000000\n>>> secs = x / 10.0 ** 7\n>>> secs\n63412450260.0\n>>> import datetime\n>>> delta = datetime.timedelta(seconds=secs)\n>>> delta\ndatetime.timedelta(733940, 34260)\n>>> ts = datetime.datetime(1,1,1) + delta\n>>> ts\ndatetime.datetime(2010, 6, 18, 9, 31)\n>>>	0
9350596	9350582	Use of unassigned local variable (Very simple function with a string array). C# language	string[] linea = new string[3];//3 is the length of your array\n//you can store 3 elements in linea [0] [1] and [2]	0
30489802	30489117	Specifiying a default namespace for XDocument gives empty value	class Program\n{\n    static void Main(string[] args)\n    {\n        var xmlRoot = new XElement(XName.Get("root", "http://somenamespace"));\n        xmlRoot.SetAttributeValue("xmlns", "http://somenamespace");\n        var xmlDocument = new XDocument(xmlRoot);\n        var xmlNamespace = xmlDocument.Root.GetDefaultNamespace().NamespaceName;\n    }\n}	0
20962342	20961509	How do I sum and display the result of each column of textboxes?	for (int j = 0; j < statsBonus.GetLength(0); j++)\n{\n    int sum = 0;\n    for (int i = 0; i < statsBonus.GetLength(1); i++)\n    {\n        sum+= Int32.Parse(statsBonus[j,i].Text);\n    }\n    totalsBefore[j].Text = sum.ToString();\n}	0
12900279	12900161	searching a datatable	DataTable clonedTable = dt.Clone();\n\nDataRow[] rows = dt.Select("PartName Like '" + SearchString + "%'");\n\nforeach ( DataRow row in rows ){\n    cloneTable.importRow( row );\n}\n\nclonedTable.acceptChanges();	0
20313350	20313308	C# Beginner: Delete ALL between two characters in a string (Regex?)	txtSourceCodeFormatted.Text = Regex.Replace(SourceCode, "<.*?>", string.Empty);	0
22365758	22364188	How to add a PushPin item to a map? Windows Phone	MapLayer layer1 = new MapLayer();\n\nPushpin pushpin1 = new Pushpin();\n\npushpin1.GeoCoordinate = MyGeoPosition;\npushpin1.Content = "My car";\nMapOverlay overlay1 = new MapOverlay();\noverlay1.Content = pushpin1;\noverlay1.GeoCoordinate = MyGeoPosition;\nlayer1.Add(overlay1);\n\nmyMap.Layers.Add(layer1);	0
22047711	22038320	Set Chart Series Color in Word	Series series1.Format.Line.ForeColor.RGB = System.Drawing.Color.FromArgb(111,154,169).ToArgb()	0
7649063	7640796	how to use double Quotes correctly?	string cID = "blah";\nstring loginKey = "foo";\n\nvar xml = new XElement("CStatus",\n              new XAttribute("timestamp", "0"),\n              new XAttribute("type", "login"),\n              new XAttribute("cid", cID),\n              new XAttribute("key", loginKey)\n          );\n\nstring sendMsg = xml.ToString();	0
27969621	27969423	Finding the closest integer value, rounded down, from a given array of integers	List<int> numbers = new List<int>() { 0, 2000, 4000, 8000, 8500, 9101, 10010 };\nint myNumber = 9000;\n\nint r=numbers.BinarySearch(myNumber);\nint theAnswer=numbers[r>=0?r:~r-1];	0
6293788	6293549	Setting authentication header for WebBrowser control - ASP.NET	string authHeader = "Authorization: Basic " + Convert.ToBase64String(authData) + \n        "\r\n" + "User-Agent: MyUserAgent\r\n";	0
5644623	5644587	Find type of nullable properties via reflection	propertyType = propertyInfo[propertyInfoIndex].PropertyType;\n    if (propertyType.IsGenericType &&\n        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))\n    {\n      propertyType = propertyType.GetGenericArguments()[0];\n    }	0
14733515	14733223	How to append a WebControl immediately after a WebControl in CodeBehind	var textBoxAgeIndex = TextBoxAge.Parent.Controls.IndexOf(TextBoxAge);\n\nTextBoxAge.Parent.Controls.AddAt(textBoxAgeIndex +1, new LiteralControl("Invalid Age."));	0
28985981	28985638	How get unmanaged exe or dll file digital signature subject name?	using System.Security.Cryptography;\nusing System.Security.Cryptography.X509Certificates;\n\n\nvar signer = X509Certificate.CreateFromSignedFile("[path to the file]");\nvar cert = new X509Certificate2(signer);\n\nvar certChain = new X509Chain();\ncertChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;\ncertChain.ChainPolicy.RevocationMode = CheckRevocOffline ? X509RevocationMode.Offline : X509RevocationMode.Online;\ncertChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);\ncertChain.ChainPolicy.VerificationFlags = VerificationFlags;\n\nvar certChainIsValid = certChain.Build(cert);\n\nif (!certChainIsValid)\n{\n    //file is likely to be self signed, revoked or expired\n}\n\nvar subjectName = cert.SubjectName.Name;	0
21112440	21111429	create a text file using an input as part of the name	dim firstInput, secondInput, folderPath, application\ndim fso, myFileD\ndim objShell\nSet objShell = WScript.CreateObject( "WScript.Shell" )\n\nSet fso = CreateObject("Scripting.FileSystemObject")\n\nfolderPath = "C:\dummyFolder"\n''extra "" for whitespace in path\napplication = """c:\Program Files\Mozilla Firefox\firefox.exe"""\n\nfirstInput = InputBox("Enter first input")\nsecondInput = InputBox("Enter second input")\n\nSet myFile = fso.CreateTextFile(folderPath & firstInput & ".txt", True)\nmyFile.WriteLine(secondInput)\nmyFile.Close\n\nobjShell.Run(application)	0
4280802	4280788	How to use Sendmessage in C#?	using System.Runtime.InteropServices;\n...\n[DllImport("user32.dll")]\nprivate static extern IntPtr SendMessage\n    (IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);	0
4159444	4159411	LINQ to XML - Trying to select a list of elements by the value of their attributes	var bar = doc.Descendants("node")\n    .Where(x => (string)x.Attribute("type") == "type1")\n    .ToList();	0
30545044	29715079	How to check if the cursor is on blank console space(C#)	if (Console.CursorLeft == checkedXPosition && Console.CursorTop == checkedYPosition)\n{\n  // Do something\n}	0
6776957	6776881	how can i use a control in template?	var button = (Button)this.Template.FindName("btn", this);	0
348142	348046	Unity Application Block, inherited injection	public abstract class BaseClass\n{\n    public IUnityContainer Container { get; protected set; }\n\n    public BaseClass() : BaseClass(null) {}\n\n    public BaseClass( IUnityContainer container )\n    {\n        this.container = container ?? this.CreateContainer();\n    }\n\n    public abstract IUnityContainer CreateContainer();\n}\n\npublic class DerivedClass : BaseClass\n{\n    public IUnityContainer ChildContainer { get; private set; }\n\n    public DerivedClass() : DerivedClass(null,null) {}\n\n    public DerivedClass( IUnityContainer parent, IUnityContainer child )\n        : BaseClass( parent )\n    {\n        this.ChildContainer = child ?? this.CreateChildContainer();\n    }\n\n    public IUnityContainer CreateContainer()\n    {\n         return new UnityContainer();\n    }\n\n    public IUnityContainer CreateChildContainer()\n    {\n         return this.Container.CreateChildContainer();\n    }\n\n}	0
1213170	1213059	Getting the text of the menu item that was clicked?	MenuItem m = (MenuItem)e.OriginalSource;	0
4191646	4191579	how to edit column value before binding to gridview after retriving from database?	DataTable dt = getMyDataTable();\nforeach (DataRow dr in dt.Rows)\n{\n     string email = Convert.ToString(dr["email"]);\n     email = email.Substring(0, email.IndexOf('@'));\n     dr["email"] = email;\n}	0
23301121	23298768	Empty data template in Windows 8 Grid app	public class CompanyTemplateSelector : DataTemplateSelector\n{\n    protected override Windows.UI.Xaml.DataTemplate SelectTemplateCore(object item, Windows.UI.Xaml.DependencyObject container)\n    {\n        var containingItem = container as GridViewItem;\n\n        if (item is UserDetails)\n        {\n            UserDetails detail = (UserDetails)item;\n            if (detail.UserId == -1) \n            {\n                containingItem.IsEnabled = false;\n                return Empty;\n            }\n            else\n            {\n                containingItem.IsEnabled = true;\n                return DataPresent;\n            }\n        }\n\n        return DataPresent;\n    }\n\n    public DataTemplate DataPresent\n    {\n        get;\n        set; \n    }\n\n    public DataTemplate Empty\n    {\n        get;\n        set; \n    }\n}	0
18180995	18180434	How to calculate code coverage with NCover using Jenkins?	NCover.Reporting Coverage.xml //or FullCoverageReport:Html //op "C:\Coverage Report"	0
1826367	1826355	Add a document and metadata to a document library without creating 2 versions	destItem.SystemUpdate( false );	0
14588834	14577796	Can I get user id from mvc 3 web app in console app?	public class MembershipRepository : IMembershipRepository\n{\n    private readonly WebStoreDataContext _dataContext;\n\n    public MembershipRepository(WebStoreDataContext dataContext)\n    {\n        _dataContext = dataContext;\n    }\n\n    public IEnumerable<User> GetUsers()\n    {\n        return _dataContext.Users;\n    }\n\n    public Guid GetUserId(string name)\n    {\n        return _dataContext.Users.Where(u => u.UserName == name).Select(u => u.UserId).Single();\n    }\n}	0
31858203	31857464	OutOfMemoryException in c# when deserializing XML file	public static T Deserialize<T>(string Filepath)\n    {\n        using (FileStream FStream = new FileStream(Filepath, FileMode.Open))\n        {\n            var Deserializer = new XmlSerializer(typeof(T));\n            return (T)Deserializer.Deserialize(FStream);\n        }\n    }	0
6158360	5968841	Dynamic table names	DataSet s = new DataSet ();\n      DataTable t1 = new DataTable ();\n      t1.Columns.Add ("A", typeof (int));\n      t1.Columns.Add ("B", typeof (string));\n      s.Tables.Add (t1);\n      t1.Rows.Add (1, "T1");\n      t1.Rows.Add (2, "T1");\n\n      DataTable t2 = new DataTable ();\n      t2.Columns.Add ("A", typeof (int));\n      t2.Columns.Add ("B", typeof (string));\n      s.Tables.Add (t2);\n      t2.Rows.Add (1, "T2");\n      t2.Rows.Add (2, "T2");\n      t2.Rows.Add (3, "T2");\n\n      var result = from t in s.Tables.OfType<DataTable> ()\n                   from r in t.Rows.OfType<DataRow> ()\n                   select r;	0
4919268	4917809	Barcode with Text Under using ItextSharp	string prodCode = context.Request.QueryString.Get("code");\ncontext.Response.ContentType = "image/gif";\nif (prodCode.Length > 0)\n{\n  Barcode128 code128          = new Barcode128();\n  code128.CodeType            = Barcode.CODE128;\n  code128.ChecksumText        = true;\n  code128.GenerateChecksum    = true;\n  code128.StartStopText       = true;\n  code128.Code                = prodCode;\n  System.Drawing.Bitmap bm    = new System.Drawing.Bitmap(code128.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White));\n  bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);            \n}	0
6197863	6197794	How to get IE version info in Winform?	var ieVersion = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Internet Explorer").GetValue("Version");	0
15920265	15920154	Can I use a space between two words in enumeration?	public string GetUIFriendlyString(SoftwareEmployee employee)\n{\n    switch (employee):\n    {\n      case TeamLeader: return "Team Leader";\n      // same for the rest\n    }\n}	0
8564029	8563803	How to prevent minimize of child window when parent window minimizes	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n    }\n    private Form ownedWindow;\n\n    private void button1_Click(object sender, EventArgs e) {\n        if (ownedWindow != null) return;\n        ownedWindow = new Form2();\n        ownedWindow.FormClosed += delegate { ownedWindow = null; };\n        ownedWindow.Show(this);\n    }\n\n    protected override void WndProc(ref Message m) {\n        // Trap the minimize and restore commands\n        if (m.Msg == 0x0112 && ownedWindow != null) {\n            if (m.WParam.ToInt32() == 0xf020) ownedWindow.Owner = null;\n            if (m.WParam.ToInt32() == 0xf120) {\n                ownedWindow.Owner = this;\n                ownedWindow.WindowState = FormWindowState.Normal;\n            }\n        }\n        base.WndProc(ref m);\n    }\n}	0
14213344	14212935	Treeview copy to RichtextBox or print	void PrintNewTreeView()\n{\n    var pd = new PrintDocument();\n    pd.PrintPage += OnPrintPage;\n    pd.Print(); \n}\n\nvoid OnPrintPage(object sender, PrintPageEventArgs e)\n{\n    var bitmap = new Bitmap(newTreeView.Bounds.Size);\n    newTreeView.DrawToBitmap(bitmap, bitmap.Size);\n    var pt = Point.Empty; // drawing origin\n    e.Graphics.DrawImage(bitmap, pt);\n}	0
7705801	7705114	NHibernate QueryOver with SubQuery in where with or	Post p = null;\nSubPost s = null;\nreturn session.QueryOver<Post>( () => p)\n           .where( () => p.User.Id == 1)\n           .Where( () => p.Level == 1 || p.Level == 2 || p.Lvel ==3 )\n           .JoinAlias( () => s.Post , () => p)\n           .Where( () => p.User.Id == 1)\n           .List<Post>();	0
8739611	8739577	Converting string value to hex decimal	int a = 12000;\nint b = 0x2ee0;\na == b	0
15693936	15693639	How can I determine whether a column exists in a SQL Server CE table with C#?	public bool isValidField(string tableName, string columnName)\n{\n    var tblQuery = "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS"\n                   + " WHERE TABLE_NAME = @tableName AND"\n                   + " COLUMN_NAME = @columnName";\n\n    SqlCeCommand cmd = objCon.CreateCommand();\n    cmd.CommandText = tblQuery;\n    var tblNameParam = new SqlCeParameter(\n        "@tableName",\n        SqlDbType.NVarChar,\n        128);\n\n    tblNameParam.Value = tableName\n    cmd.Parameters.Add(tblNameParam);\n    var colNameParam = new SqlCeParameter(\n        "@columnName",\n        SqlDbType.NVarChar,\n        128);\n\n    colNameParam.Value = columnName\n    cmd.Parameters.Add(colNameParam);\n    object objvalid = cmd.ExecuteScalar(); // will return 1 or null\n    return objvalid != null;\n}	0
7684711	7684678	C# Filtering employee ID's from a list to modify a query	// Code to see if the 'all employees' radiobutton is selected.\n\nvar k = from id in employeeIdList\n        where AllSelected || employeeIDs.Contains(id)\n        select id;	0
4627649	4627624	Converting JS 'escape'd string back to correct format in C#	String DecodedString = Server.UrlDecode(EncodedString);	0
32576042	21434140	How to parse a quoted string	System.Text.RegularExpressions.Regex.Unescape	0
8980025	8963799	Axis label values in charts	for (int i = 0; i < vals.Length -1; i++)\n {\n     series1.Points.Add(Convert.ToDouble(vals[i])); \n     series1.AxisLabel = date[i]; \n }\n//replace this\n\n\nfor (int i = 0; i < vals.Length -1; i++)\n {\n     series1.Points.AddXY(Convert.ToString(date[i]), Convert.ToDouble(vals[i])); \n }\n\nseries1.AxisLabel = date[0]; \n//with this	0
28319577	28318959	Linq - Group by first letter of name	Select().GroupBy(x => x.Name.Substring(0,1).ToUpper(), (alphabet, subList) => new { Alphabet = alphabet, SubList = subList.OrderBy(x => x.Name).ToList() })\n                .OrderBy(x => x.Alphabet)	0
6074711	5241718	Taking ownership of files with 'broken' permissions	using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))\n{\n    directoryInfo = new DirectoryInfo(path);\n    directorySecurity = directoryInfo.GetAccessControl();\n\n    directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);\n    Directory.SetAccessControl(path, directorySecurity);    \n}	0
33395455	33394947	Create database in App_Start	Database.SetInitializer(new TodoDbInit());	0
2602586	2602271	Best way to manipulate and compare strings	var input = "/Data/Main/Table=Customers/";\nvar regex = new Regex(@"\w+?/");\nvar matches = regex.Matches(input);\nforeach (var match in matches)\n{\n    Console.WriteLine(match.ToString());\n}\nConsole.ReadKey();	0
5505954	5425962	Deleting all QueryTables in Excel 2007 Workbook	// loop through each list object on each Worksheet\nif (sheet.ListObjects.Count > 0)\n{\n   foreach (ListObject obj in sheet.ListObjects)\n   {\n     obj.QueryTable.Delete();\n   }\n}	0
14137074	14066710	Body not rotating to face downward with gravity	public override void Update(GameTime gameTime)\n    {\n        Vector2 velocity = Body.LinearVelocity;\n\n        float radians = (float)(Math.Atan2(-velocity.X, velocity.Y) + Math.PI/2.0);\n\n        Body.Rotation = radians;\n\n        base.Update(gameTime);\n    }	0
15725405	15710581	How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner	[Test]\npublic void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()\n{\n    string payload = null;\n\n    browser.AddMessageEventListener("callMe", ((string p) => payload = p));\n\n    browser.LoadHtml(\n        @"<!DOCTYPE html>\n                     <html><head>\n                     <script type='text/javascript'>\n                        window.onload= function() {\n                            event = document.createEvent('MessageEvent');\n                            var origin = window.location.protocol + '//' + window.location.host;\n                            event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);\n                            document.dispatchEvent (event);\n                        }\n                    </script>\n                    </head><body></body></html>");\n\n    browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();\n    Assert.AreEqual("some data", payload);\n}	0
7847919	7824847	c# ssl request - certifcate validation	ssl_verify_depth 1;	0
5743917	5743851	Can i make a linq expression optional parameter in c# 4.0?	public void GetMessages(string folder = "INBOX")\n{\n    this.GetMessages(DEFAULT_VALUE, folder);        \n}	0
292329	292233	Get Windows Username from WCF server side	private static void DemandManagerPermission()\n{\n    // Verify the use has authority to proceed\n    string permissionGroup = ConfigurationManager.AppSettings["ManagerPermissionGroup"];\n    if (string.IsNullOrEmpty(permissionGroup))\n    throw new FaultException("Group permissions not set for access control.");\n\n    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n    var p = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, permissionGroup, true);\n    p.Demand();\n\n}	0
17864341	17863912	How can I write a string array to Excel file, with a tab delimiter?	for (int i = 0; i < range.Rows.Count; i++) {\n        range.Rows[i].Value = lines[i];\n        range.Rows[i].TextToColumns(\n            range.Rows[i],\n            Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited,\n            Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone,\n            false,\n            true\n        );          \n    }	0
11008328	11008310	Cannot insert into database	var insertCommand = "INSERT INTO CarBike (name,image,price,[desc],date,userid) VALUES(@0,@1,@2,@3,@4,@5)";	0
708233	708213	Using statement and Close methods	protected override void Dispose(bool disposing)\n{\n    if (disposing)\n    {\n        this._userConnectionOptions = null;\n        this._poolGroup = null;\n        this.Close();\n    }\n    this.DisposeMe(disposing);\n    base.Dispose(disposing);\n}	0
12428735	12428622	How can I combine a method and a dictionary used by the method for lookups?	public string GetRefStat(int pk) \n{ \n    return new Dictionary<int, int>   \n    {  \n        {1,2},  \n        {2,3},  \n        {3,5}   \n    }[pk]; \n}	0
10120608	10118117	Pasting CJK characters to a RichTextBox adds an unwanted second font	Lucida Sans Unicode	0
9834202	9834180	How to avoid private property null check to do lazy loading?	//Constructor default to not loaded\nbool isLoaded = false;\n\nprivate string _name;\npublic string Name \n{\n   get {\n      if (!isLoaded)\n         LoadData(); //this popultes not just but all the properties\n      return _name;\n   }\n}   \n\nprivate LoadData()\n{\n    //Load Data\n    isLoaded = true;\n}	0
9418668	9418595	How to avoid our program being crashed because a DLL it has dynamically loaded is buggy	try\n  {\n    if (crash.Equals("crash") == true)\n    {\n      bool test = anObject.isStringNormalized(null);\n    }\n    else\n    {\n      bool test = anObject.isStringNormalized("test");\n    }\n  } catch (Exception ex) {\n    Console.WriteLine("exception in dll call: "+ex);\n  }	0
34292009	34291680	Is it advisable to use async/await for a long running operation?	void RunLongTask()\n{\n     // long work to do\n\n     // in case of wpf you can report progress to ui\n     Dispatcher.Invoke(ProgressDelegate, 0);\n\n     // more work\n\n     Dispatcher.Invoke(ProgressDelegate, 1);\n\n     // etc...\n}\nasync Task RunLongTaskAsync()\n{\n    await Task.Factory.StartNew(RunLongTask, TaskCreationOptions.LongRunning);\n}	0
7054509	7047904	Generating a dataset with few unique values	public static int[] FewUnique(int uniqueCount, int returnSize)\n    {\n        Random r = _random;\n        int[] values = new int[uniqueCount];\n        for (int i = 0; i < uniqueCount; i++)\n        {\n            values[i] = i;\n        }\n\n        int[] array = new int[returnSize];\n        for (int i = 0; i < returnSize; i++)\n        {\n            array[i] = values[r.Next(0, values.Count())];\n        }\n\n        return array;\n    }	0
13739633	13739596	Getting a reference to the current instance of the view model	var viewModel=DataContext as MainWindowViewModel;	0
1235737	1235718	Using a single Func<T,bool> with Where() and inheritance	jobs.Where(new Func<JobExtended, bool>(ValidJob));	0
19999370	19999283	Losing characters in strings after performing a split with RegEx	string[] result = Regex.Split(str, @"\s{3,}(?=4)");	0
529434	518778	Setting the SelectedTab on a PropertyGrid	public int SelectedTabIndex \n    {\n        set\n        {\n            Type pgType = typeof(PropertyGrid);\n            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;\n\n            ToolStripButton[] buttons = (ToolStripButton[]) pgType.GetField("viewTabButtons", flags).GetValue(this);\n            pgType.GetMethod("SelectViewTabButton", flags).Invoke(this, new object[] { buttons[value], true });\n        }\n    }	0
2743228	2743226	Strategy Pattern with Type Reflection affecting Performances?	if (node.Behavior is NodeDataOutputBehavior)	0
19662240	19662130	Print image using windows print image dialog	private void button1_Click(object sender, EventArgs e)\n    {\n        string fileName = @"C:\Development\myImage.tif";//pass in or whatever you need\n        var p = new Process();\n        p.StartInfo.FileName = fileName;\n        p.StartInfo.Verb = "Print";\n        p.Start();\n    }	0
2386614	2386582	How to connect an ORM to the IoC container?	IPersonRepository personRepo = ObjectFactory.GetInstanceOf<IPersonRepository>();\nint id = 12;\nIPerson person = personRepo.GetBy(id);	0
31153815	31153778	Reflection based comparion of two object values	public class BoxComp : IComparer<Box>\n{\n    // Compares by Height, Length, and Width. \n    public int Compare(Box x, Box y)\n    {\n       ///you code to do comparison\n    }\n}	0
28703682	28703567	Keep delimiters after using String.Split	var input = "aa*ab+ac/ad-ae=af;ag";\nvar parts = Regex.Matches(input, @"[;\*\+/=-]|[^;\*\+/=-]+")\n                .Cast<Match>()\n                .Select(m => m.Value)\n                .ToList();	0
23511471	23511079	How can I move a button with mousehover?	public partial class Form1 : Form\n{\n    private Rectangle buttonRectangle;\n\n    private bool checkRectangle = false;\n\n    public Form1()\n    {\n        InitializeComponent();\n        button2.TabStop = false;\n        buttonRectangle = button2.ClientRectangle;\n        buttonRectangle.Location = button2.Location;\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        button2.Location = new Point(25, 25);\n    }\n\n    private void button2_MouseHover(object sender, EventArgs e)\n    {\n        button2.Location = new Point(50, 50);\n        checkRectangle = true;\n    }\n\n    private void Form1_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (!checkRectangle)\n        {\n            return;\n        }\n\n        if (!buttonRectangle.Contains(e.X, e.Y))\n        {\n            checkRectangle = false;\n            button2.Location = buttonRectangle.Location;\n        }\n    }\n}	0
32879515	32879445	How to define grid view inside RowCommand	GridViewRow gvRow = (GridViewRow)((Control)e.CommandSource).NamingContainer;\nInt32 rowIndex = gvRow.RowIndex; // required if you want to find index of the control from where event has been raised.  \nGridView gvProducts = gvRow.FindControl("gvProducts") as GridView;	0
6378969	5772415	Implementing Matrix Transform on New Object	TransformPoints(Point[]) or TransformVectors(Point[])	0
23142527	23142311	I need a SQL query in c# windows + sql server app to check whether the ip address of the user is in database(a kind of black list) or not?	string query = "SELECT count(*) from BlackList WHERE IP=ip";\n\nSqlCommand cmd = new SqlCommand(query, con);\nvar rowCount = (int)cmd.ExecuteScalar();\ncon.Close();\nif (rowCount>0)\n  MessageBox.Show("This IP is black Listed.Retry after few seconds.");	0
21520965	21282031	Starting console app as new process hides window	Process.Start	0
801431	801406	C#: Create a lighter/darker color based on a system color	Color lightRed = ControlPaint.Light( Color.Red );	0
16271485	16271187	Deserialize a nested json string using Json.net and C#?	var json = "{\"data\":[{\"id\":\"CAMVqgY1g1cdLU5anDL69Tt5pyRh51-qkyKMHWHgH2mAG+vn+xQ%40mail.gmail.com\",\"content\":\"Coba ngirim email mohon diterima\r\n\",\"judul\":\"coba 1\",\"sender\":\"Aldo Erianda\"},{\"id\":\"CAMVqgY1Trb5ZShRxzoX%3D0xaVQs5-Psh0J8V3JwQYVevcr8i5WA%40mail.gmail.com\",\"content\":\"sampai nga ya\r\n\",\"judul\":\"coba 2\",\"sender\":\"Aldo Erianda\"}]}";\nvar deserialized = JsonConvert.DeserializeObject<IDictionary<string, JArray>>(json);\nJArray recordList = deserialized["data"];\nforeach (JObject record in recordList)\n{\n    Console.WriteLine("id: " + record["id"]);\n    Console.WriteLine("content: " + record["content"]);\n    Console.WriteLine("judul: " + record["judul"]);\n    Console.WriteLine("sender: " + record["sender"]);\n}\nConsole.WriteLine("count: " + recordList.Count);	0
9180061	9179658	How to asynchronously wait for response from an external application that intercepts printer output	class PrintJob\n{\n    public PrintJob()\n    { \n        Event = new ManualResetEventSlim();\n    }\n\n    public ManualResetEventSlim Event {get; private set;}\n\n    public int Status{ get; set;}\n}	0
24539703	24539653	String Comparison with overload	string first = "StringCompaRison";\nstring second = "stringcoMparisoN";\nif(first.Equals(second,StringComparison.OrdinalIgnoreCase)\n{\n        Console.WriteLine("Equal ");\n}\nelse\n        Console.WriteLine("Not Equal");	0
19656492	19656242	Convert some bool properties to a flags enum	using System;\n\nnamespace ConsoleApplication1\n{\n\n    [Flags]\n    public enum FlagEnum\n    {\n        EnumValue1 = 1,\n        EnumValue2 = 2,\n        EnumValue3 = 4\n    }\n\n    public static class LegacyClass\n    {\n        public static bool PropA { get; set; }\n        public static bool PropB { get; set; }\n        public static bool PropC { get; set; }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            LegacyClass.PropB = true;\n            FlagEnum result = LegacyClass.PropA ? FlagEnum.EnumValue1 : 0;\n            result |= LegacyClass.PropB ? FlagEnum.EnumValue2 : 0;\n            result |= LegacyClass.PropC ? FlagEnum.EnumValue3 : 0;\n        }\n    }\n}	0
25327926	25327874	Delete row from string[] by index	sr.ReadLine();\nstring str = sr.ReadToEnd();	0
9723970	9723084	Step out of a distributed transaction for one of my Entity Framework ObjectContexts	using (new TransactionScope(TransactionScopeOption.Suppress))\n{\n    // Create logging context and audit your data\n}	0
23488602	23486253	How to use pointer to process image with c# and emgucv?	Image<Gray, Byte> img = new Image<Gray, byte>(510, 510);            \n        // Fill image with random values\n        img.SetRandUniform(new MCvScalar(), new MCvScalar(255));\n        // Show Image\n        ImageViewer.Show(img);\n        var data = img.Data;\n        int stride = img.MIplImage.widthStep;\n        fixed (byte* pData = data)\n        {\n            for (int i = 0; i < 255 * stride; i++)\n                *(pData + i) = (byte)(i % stride);\n        }\n        // Show Image Again\n        ImageViewer.Show(img);	0
2340652	2340607	How to check file in use in c#	FileStream fileStream = null;\n\ntry\n{\n    fileStream =\n        new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write);\n}\ncatch (UnauthorizedAccessException e)\n{\n    // The access requested is not permitted by the operating system\n    // for the specified path, such as when access is Write or ReadWrite\n    // and the file or directory is set for read-only access. \n}\nfinally\n{\n    if (fileStream != null)\n        fileStream.Close ();\n}	0
8225910	8225865	Change already attached event handler runtime	control.Tap -= OnClick1;\ncontrol.Tap += OnClick2;	0
5155623	5155587	Create a Cross-Container Tab Index	private void textBox1_Leave(object sender, System.EventArgs e)\n{\n    textBox2.Focus();\n}	0
33350030	33304133	.NET C# conversion from UTF 16 LE to UTF 16 BE failing	sendMsg.SetIntProperty(XMSC.JMS_IBM_CHARACTER_SET, 1201);	0
1953084	1951039	check sunday falls between two dates	public static bool DoesIncludeSunday(DateTime startDate, DateTime endDate)\n{\n    bool r = false;\n    TimeSpan testSpan = new TimeSpan(6, 0, 0, 0);\n    TimeSpan actualSpan =endDate - startDate;\n\n    if (actualSpan >= testSpan) { r = true; }\n    else\n    {\n        DateTime checkDate = endDate;\n        while (checkDate > startDate)\n        {\n            r = (checkDate.DayOfWeek == DayOfWeek.Sunday);\n            if(r) { break; }\n            checkDate = checkDate.AddDays(-1);\n        }\n    }\n\n    return r;\n}	0
3087191	3086118	Read XML file using LinQ	XDocument xml = XDocument.Load(@"<path to your xml file"); \n\n        var resultSet = from x in xml.Descendants("section")                          \n                        select x.Attribute("name");\n\n        var resultsSet2 = from x in xml.Descendants("section")\n                          where x.Attribute("name") == "<the selected value of your data grid>"\n                          select new\n                          {                               \n                              id = x.Element("locstring").Attribute("ID").Value,\n                              name = x.Element("locstring").Element("Name").Value\n                          };	0
12841824	12841456	How to synthesize a static virtual/abstract member?	public abstract class Animal\n{\n    public abstract int NumberOfLegs { get; }\n\n    public void Walk()\n    {\n        // do something based on NumberOfLegs\n    }\n}\n\npublic class Cat : Animal\n{\n    private const int NumLegs = 4;\n\n    public override int NumberOfLegs { get { return NumLegs; } }\n}\n\npublic class Spider : Animal\n{\n    private const int NumLegs = 8;\n\n    public override int NumberOfLegs { get { return NumLegs; } }\n}	0
1116049	968819	Change description of a SharePoint group	SPGroup g = web.SiteGroups["GroupName"];\nSPFieldMultiLineText text = (SPFieldMultiLineText)web.SiteUserInfoList.Fields[SPBuiltInFieldId.Notes];\nSPListItem groupItem = web.SiteUserInfoList.GetItemById(g.ID);\ngroupItem[text.InternalName]= groupDescription;\ngroupItem.Update();	0
21189983	21118613	RazorView, use same model object for more than one template	public class ModelWrapper{\n\n      public object Model { get; set}\n}	0
1780647	1780606	Redirecting Console Output to winforms ListBox	public class ListBoxWriter : TextWriter\n{\n    private ListBox list;\n    private StringBuilder content = new StringBuilder();\n\n    public ListBoxWriter(ListBox list)\n    {\n    this.list = list;\n    }\n\n    public override void Write(char value)\n    {\n    base.Write(value);\n    content.Append(value);\n    if (value == '\n')\n    {\n    list.Items.Add(content.ToString());\n    content = new StringBuilder();\n    }\n    }\n\n    public override Encoding Encoding\n    {\n    get { return System.Text.Encoding.UTF8; }\n    }\n}	0
615120	615106	Setting the contents of a textBox to upper-case on CurrentItemChanged	private void rootBindingSource_CurrentItemChanged(object sender, System.EventArgs e)\n{\n    toUserTextBox.Text = toUserTextBox.Text.ToUpper();\n    readWriteAuthorization1.ResetControlAuthorization();\n}	0
25879282	25879189	Change the value for a Json attribute	request.attrib1 = "new_value";	0
2048709	2048652	Load ASCX controls dynamically using AJAX	void MyTreeView_SelectedNodeChanged(Object sender, EventArgs e)\n{\n    PanelOnTheRight.Controls.Clear();\n\n    MyEditControl editControl = LoadControl("~/usercontrols/mycontrol.ascx");\n    editControl.IdToEdit = ((TreeView)sender).SelectedNode.Value;\n\n    PanelOnTheRight.Controls.Add(editControl);\n}	0
23411649	23411515	How to populate dropdown list before page loads in webforms?	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n         List<string> list = new List<string>()\n         {\n            "test",\n            "test2"\n         };\n        ShowAssumptions.DataSource = list;\n        ShowAssumptions.DataBind();\n    }\n}	0
4538547	4538510	What's Regx for the following	string pattern = @"(\d+)@abc\.com";\nstring input = "My address is 15464684@abc.com and you can send SMS to me";\nMatch match = Regex.Match(input, pattern);\n\n// Get the first named group.\nGroup group1 = match.Groups[1];\nConsole.WriteLine("Group 1 value: {0}", group1.Success ? group1.Value : "Empty");	0
13930841	13930815	Adjusting Font-Size of ListItem in codebehind	CurrentListBox.Items[0].Attributes.Add("style", "font-size:x-large;");	0
8043748	8043163	LINQ: How to modify the return type of AsParallel depending on a context?	var result = \n                source\n#if TURN_ON_LINQ_PARALLELISM\n                .AsParallel()\n#endif\n                .Select(value => value.StartsWith("abcd"));	0
48719	48680	Winforms c# - Set focus to first child control of TabPage	private void frmMainLoad(object sender, EventArgs e)\n{\n    ActiveControl = textBox1;\n}	0
1847257	1844752	How to do partial word searches in Lucene.NET?	parser.Parse(query.Keywords.ToLower() + "*")	0
7923742	7911455	HTML Agility Pack RemoveChild - not behaving as expected	void Main()\n{\n    string html = "<html><span>we do like <b>bold</b> stuff</span></html>";\n    HtmlDocument doc = new HtmlDocument();\n    doc.LoadHtml(html);\n    RemoveTags(doc, "span");\n    Console.WriteLine(doc.DocumentNode.OuterHtml);\n}\n\npublic static void RemoveTags(HtmlDocument html, string tagName)\n{\n    var tags = html.DocumentNode.SelectNodes("//" + tagName);\n    if (tags!=null)\n    {\n        foreach (var tag in tags)\n        {\n            if (!tag.HasChildNodes)\n            {\n                tag.ParentNode.RemoveChild(tag);\n                continue;\n            }\n\n            for (var i = tag.ChildNodes.Count - 1; i >= 0; i--)\n            {\n                var child = tag.ChildNodes[i];\n                tag.ParentNode.InsertAfter(child, tag);\n            }\n            tag.ParentNode.RemoveChild(tag);\n        }\n    }\n}	0
28133644	28133535	Regex for html tags that are encapsulated by table elements	HtmlDocument htmlDocument = new HtmlDocument();\nhtmlDocument.LoadHtml(html);\nvar nodes = htmlDocument.DocumentNode.SelectNodes("//table");	0
21511114	21510974	Appearing UISwitch in wrong cell of UITableView	if ([settingObjectCell.switcher isEqualToString:@"YES"] || [settingObjectCell.switcher isEqualToString:@"NO"])\n{\n    // Your existing code\n}\nelse\n{\n    //Move this line here\n    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;\n    // remove switch\n    cell.accessoryView = nil;\n}	0
29170774	29170105	Make my XML to string output look presentable	using System.XML.Linq;\n\nclass XMLParseProgram\n{\npublic DataTable ReadXML(string strXML)\n{\n  XDocument xdoc = XDocument.Load(strXML);\n\n  var property= from props in xdoc.Element("Solution").Elements("Property").ToList().ToList();\n\nif (property!= null)\n            {\n\n                DataTable dtItem = new DataTable();\n                dtItem.Columns.Add("Name");\n                dtItem.Columns.Add("Value");\n\nforeach (var itemDetail in property.ElementAt(0))\n                {\n                    dtItem.Rows.Add();\n\n                    if (itemDetail.Descendants("Name").Any())\n                        dtItem.Rows[count]["Name"] = itemDetail.Element("Name").Value.ToString();\n\n                    if (itemDetail.Descendants("Value").Any())\n                        dtItem.Rows[count]["Value"] = itemDetail.Element("Value").Value.ToString();\n}\n}\n}\n\n}	0
10179212	10178072	pass parameters into a url after executing a SQL Query	while(reader.Read())\n{\n    string _firstname = reader[0].ToString();\n    string _lastname = reader[1].ToString()\n    ...\n}	0
2565258	2527679	How to clean up after myself when drawing directly to the screen	InvalidateRect(NULL, NULL, TRUE)	0
32874881	32874748	How to fill dataGrid view from backgroundWorker_DoWork Result	dataGridView1.Invoke((Action)(() => dataGridView1.DataSource = superset));\n    dataGridView1.Invoke((Action)(() => dataGridView1.DataSource = superset.Tables[0]));	0
11326354	11326267	How to zip an existing folder with files inside it?	FastZip fastzip = new FastZip(); \n        Boolean recurse = true; \n        String filter = null; \n\n        fastzip.CreateZip("azip.zip",  folderName, recurse, filter);	0
19243032	19163257	Umbraco. Get node's url in console application	UmbracoContext.Current.ContentCache	0
26204617	26204458	Reading special field from variable XML File c#	XDocument xdoc = XDocument.Load(yourFileName));\nvar persons = from lv1 in xdoc.Descendants("Person")\n              select lv1.Value;	0
9737920	9737863	how to trim IP Address string to get the first 3 parts of it?	String result = input.substring(0,input.lastIndexOf("."));	0
10318588	8577548	How to pass a function as an object instead of a function?	Public Shared ReadOnly ItemsProperty As PropertyData = RegisterProperty("Items", GetType(IEnumerable(Of Person)), Sub() new Person())	0
15208758	15208674	HOw can I handle Dynamically generated Controls	Button btnUpld = new Button();\n            btnUpld.Width = 100;\n            btnUpld.ID = "btnUpRow" + i + "Col" + j;\n            btnUpld.Text = "Upload";\n             btnUpld.Click += new EventHandler(btnUpld_Click); \n           cell.Controls.Add(btnUpld);\n\n\n\n//code behind\nprivate void btnUpld_Click(object sender, System.EventArgs e) \n{\n// Add upload functionality here\n}	0
1135005	1134993	Control another application using C#	Application application = Application.Launch("foo.exe");\n   Window window = application.GetWindow("bar", InitializeOption.NoCache);\n\n   Button button = window.Get<Button>("save");\n   button.Click();	0
10745247	10745144	If statement - 'or' but NOT 'and'	public static bool IsExactlyOneTrue(IEnumerable<Func<bool>> conditions) {\n    bool any = false;\n    foreach (var condition in conditions) {\n        bool result = condition();\n        if (any && result) {\n            return false;\n        }\n        any = any | result;\n    }\n    return any;\n}	0
30375910	30352895	How do I construct a function that allows me to pass in several includes for EF via params?	public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includes)\n{\n    var query = DbSet.AsNoTracking();\n\n    query = includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));\n\n    return query;\n}\n\nMyGenericRepository<A>().GetAllIncluding(x=> x.B, x=> x.C).FirstOrDefault()	0
11510586	11509720	HTML Agility pack - parsing img src and href from relative paths	var htmlStr = "yourhtml";\nvar doc = new HtmlDocument();\ndoc.LoadHtml(htmlStr);\nvar baseUri = new Uri("baseUriOfYourSite");\nvar images = doc.DocumentNode.SelectNodes("//img/@src").ToList();\nvar links = doc.DocumentNode.SelectNodes("//a/@href").ToList();\nforeach (var item in images.Concat(links))\n{\n    item.InnerText =  new Uri(baseUri, item.InnerText).AbsoluteUri;    \n}	0
24069125	24068743	identify that no Gridview Row is selected	if(gridview1.SelectedIndex == -1){\n    //no item has been selected\n}	0
9716990	9716749	Fire a RowCommand event from ImageButton created dynamically inside ITemplate	GridView GV = new GridView(); //Make sure to create the grid view on every postback and populate it. Alternatively (i dont know if its a good practice.) you can store a reference of gridview in session.\nGV.RowCommand += new GridViewCommandEventHandler(GV_RowCommand); //bind the row command event. this should solve the problem.	0
19337562	19337520	Converting a String with plain text to byte array in hex style?	public static byte[] getBytesFromString(String str)\n{\n   return Encoding.ASCII.GetBytes(str)\n}	0
12320361	12318857	How to check in C# if user account is active	class Program\n{\n    static void Main(string[] args)\n    {\n\n        // Create the context for the principal object. \n        PrincipalContext ctx = new PrincipalContext(ContextType.Machine);\n\n        UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "Administrator");\n        Console.WriteLine(String.Format("Administrator is enable: {0}", u.Enabled));\n\n    }\n}	0
22414511	22414255	programmatically opening adobe but pdf won't load	proc.StartInfo.Arguments = string.Format("\"{0}\"", file.FullName);	0
34274082	34273787	How can I get a list of the returned fields from a Stored Proc?	string[] columnNames = dtPlatypusResults.Columns.Cast<DataColumn>()\n                             .Select(x => x.ColumnName)\n                             .ToArray();	0
6184411	6184353	A integer isn't upgraded by a thread c#	MyClass.MyStaticInt += aNumber;	0
16705578	16705558	sqlite-net like statement crashes	Global.db.Query<Cards>("select * from Cards where card_name like ?",\n    "%" + nameTextBox.Text + "%");	0
1458196	1458068	c# reading csv file gives not a valid path	var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Uploads\\");\nstring connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=Delimited""", fileName);\nOleDbConnection oledbConn = new OleDbConnection(connectionString);\noledbConn.Open();\nvar cmd = new OleDbCommand("SELECT * FROM [countrylist.csv]", oledbConn);	0
13879188	13878602	How to get web application Database Status in asp.net?	public void displayDBDetails()\n{\n    SqlConnection sqlConn = new SqlConnection(string yourConnectionString);\n    sqlConn.Open();\n\n    string dbName = sqlConn.Database.ToString();\n    string dbStatus = sqlConn.State.ToString();\n    string dbServerVersion = sqlConn.ServerVersion.ToString();\n    etc.....\n}	0
10698523	10698453	Datacontract in wcf	[ServiceContract]\npublic interface ISampleService\n{\n        [OperationContract]\n        int sum(SampleData obj);\n}\n\npublic class SampleService : ISampleService\n{\n        public int sum(SampleData obj)\n        {\n           // logic here\n        }\n}\n\n[DataContract]\npublic class SampleData\n{\n       [DataMember]\n       public int i { get; set; }\n\n       [DataMember]\n       public int q { get; set; }\n}	0
24979008	24978956	Find the index in a single array of a Cartesian coordinate	Z = (Y * 11 + X)	0
883954	876814	Enum with default typecast? is that possible?	public enum State:byte\n{\n    EmailNotValidated = 0x00,\n    EmailValidated = 0x10,\n    Admin_AcceptPending = 0x40,\n    Active = 0x80,\n    Admin_BlockedAccount = 0xff\n}	0
28808315	28807920	How to delete file after using XImage.FromFile?	CacheOption = BitmapCacheOption.OnLoad	0
8895799	8895745	How do I change a image on a Button using Windows Forms?	Button.Image	0
27505901	27307054	Can I use C++ dll through Interop to offload to Xeon Phi?	Automatic offload	0
7668175	7656338	Converting to Enum using type variable	Enum.Parse(t, @string) as Enum;	0
22008568	21988095	how to resolve The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))	PowerPoint_App.Visible = MsoTriState.msoTrue;	0
14982412	14982252	German umlauts in EndpointAddress with net.tcp	EndpointAddress endpointAddress = new EndpointAddress(\n    "net.tcp://" + IdnMapping.GetAscii("s?d") + ":8001/EmployeeService"\n);	0
7457856	7457834	Need help with a simple Linq query running with Entity Framework 4	var userA = auction.UserAuctionLances.OrderByDescending(d => d.DateTimeOfLance).FirstOrDefault().User;	0
6264579	6264554	How to check empty DataTable	if (dataTable1 != null)\n{\n   foreach (DataRow dr in dataTable1.Rows)\n   {\n      // ...\n   }\n}	0
12839613	12839563	Retrieve dictionary from dictionary in C#	Dictionary<string, Dictionary<string, bool>> dict = \n    jss.Deserialize<Dictionary<string, Dictionary<string, bool>>>(json);\nDictionary<string, bool> dict1 = dict["A"];	0
30771534	30752031	How do you Request[""] with a Dynamic Variable? Request["@Variable"]?	NameValueCollection nvc = Request.Form;\n foreach (var item in Request.Form.AllKeys)\n {\n        //do something you want.\n        // Examble : if(item == "A")// item will return name of input\n        // Note: nvc[item] return value of input\n }	0
14730919	14730665	Check if Startup Folder already contains program	WshShell shell = new WshShell(); \nvar link = (IWshShortcut)shell.CreateShortcut(linkPathName); //Link the interface to our shortcut\nvar target = link.TargetPath;\n//compare to your program's path...	0
1345531	1345508	How do i connect to a SQL database from C#?	string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";\n\nusing(SqlConnection _con = new SqlConnection(connectionString))\n{\n   string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";\n\n   using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))\n   {\n      DataTable customerTable = new DataTable("Top5Customers");\n\n      SqlDataAdapter _dap = new SqlDataAdapter(_cmd);\n\n      _con.Open();\n      _dap.Fill(customerTable);\n      _con.Close();\n\n   }\n}	0
8394137	8394111	How to convert SQL query with Unions to LINQ?	var query1 = (from d in db.DiaryPosts\n              where d.UserID = 1\n              select new { \n                UserID = d.UserID\n                Content = d.Content\n                UpdateTime = d.UpdateTime \n              }).ToList();\nvar query2 = (from d in db.DiaryPosts\n              join f in db.Friends\n              on d.UserId = f.FriendId\n              where f.UserId = 1\n              select new { \n                UserID = d.UserID\n                Content = d.Content\n                UpdateTime = d.UpdateTime \n              }).ToList();\nvar query3 = (from d in db.DiaryPosts\n              join f in db.Followers\n              on d.UserId = f.FollowerID\n              where f.UserId = 1\n              select new { \n                UserID = d.UserID\n                Content = d.Content\n                UpdateTime = d.UpdateTime \n              }).ToList();\n\nvar myunionQuery = query1.Union(query2).Union(query3).OrderBy(d => d.UpdateTime);	0
12106906	12106683	How to get value from combobox using substring in C# 	foreach (object item in cmb.Items)\n    {\n      string[] str = item.ToString().split(new char[] {' '}\n, StringSplitOptions.RemoveEmptyEntries);\n      if(str[1] == "Banana")\n      {\n           Console.Write(str[0]);\n      }\n    }	0
8382139	8381988	How to create aspx pages into domain?	/post.aspx?userId=1	0
23703285	23701947	How to redirect a users when they visit to the login page?	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        // if is already logged in\n        if (HttpContext.Current.User.Identity.IsAuthenticated)\n        {\n            // redirect to home page\n            Response.Redirect("/");\n        }\n    }    \n}	0
16384490	16384399	Storing selected datagridview cells in an array in C#	public string[] addedMovies = new string[100];	0
10231267	10230948	Get the item a user unselects in a ASP CheckBoxList	protected void checkboxlist_SelectedIndexChanged(object sender, EventArgs e)\n{\n        CheckBoxList list = (CheckBoxList)sender;\n        string[] control = Request.Form.Get("__EVENTTARGET").Split('$');\n        int idx = control.Length - 1;\n        string sel = list.Items[Int32.Parse(control[idx])].Value;  \n}	0
24739550	24738323	get specific image location from PixtureBox inside Panel	Point last;  // hold the last mousemove location\n\nprivate void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    // store the location in last\n    last.X = e.Location.X;\n    last.Y = e.Location.Y;\n}\n\nprivate void pictureBox1_MouseHover(object sender, EventArgs e)\n{\n    // do whatever we want to do with the last location\n    Trace.WriteLine(last);\n}	0
3232473	3231945	Inherited WeakReference throwing ReflectionTypeLoadException in Silverlight	using System;\n\nnamespace Frank\n{\n    public class WeakReference<T> where T : class\n    {\n        private readonly WeakReference inner;\n\n        public WeakReference(T target)\n            : this(target, false)\n        { }\n\n        public WeakReference(T target, bool trackResurrection)\n        {\n            if(target == null) throw new ArgumentNullException("target");\n            this.inner = new WeakReference(target, trackResurrection);\n        }\n\n        public T Target\n        {\n            get\n            {\n                return (T)this.inner.Target;\n            }\n            set\n            {\n                this.inner.Target = value;\n            }\n        }\n\n        public bool IsAlive {\n            get {\n                 return this.inner.IsAlive;\n            }\n        }\n    }\n}	0
26100287	26096740	Update Listbox with item on navigation	static List<object> listSrc = new List<object>();\n\noverride OnNavigatedTo()\n{\n   listSrc.Add("whatever you want");\n   sniplist.ItemsSource= listSrc;\n}	0
4518921	4518747	Howw to add new value with generic Repository if there are foreign keys (EF-4)?	params ForeignKey[]	0
15250867	15249817	Send mail with attachment	mSmtpClient.Timeout = int.MaxValue;	0
9798840	9798788	How do I call a function by string without using reflection?	var functions = new Dictionary<string, Func<float, float>>();\nfunctions.Add("sqr", x=>x*x);\n\nConsole.WriteLine(functions["sqr"](3));	0
18065641	18065446	Open new form after selecting item on listbox	private void button1_Click(object sender, EventArgs e)\n{\n    switch (listBox1.SelectedItem.ToString())\n    {\n        case "House":\n            House h = new House();\n            h.ShowDialog();\n            break;\n        case "People":\n            People p = new People();\n            p.ShowDialog();\n            break;\n        case "Outdoor":\n            Outdoor o = new Outdoor();\n            o.ShowDialog();\n            break;\n    }\n\n}	0
29732107	29732063	how to reference datatable names	txtCustomerRef.Text = dobj.GetCustomerData(selectedValue).Rows[0]["CustomerRef"].ToString();\ntxtCustomerName.Text = dobj.GetCustomerData(selectedValue).Rows[1]["CustomerName"].ToString();	0
9718295	9718028	Changing style of the system tray icon at run time	notifyIcon.Icon = <Some Icon> (ex. Properties.Resources.IconRed, if in your resources).	0
34158456	34158177	how to pass xml from controller to other controller in mvc4	Session["ArbitraryKeyString"] = "Assign any object";\nstring arbitraryString = (string)(Session["ArbitraryKeyString"] ?? "Session returns null if key not found");	0
5542182	5542141	Getting One Field Into An Array?	var ids = db.Table.Where(a => a.Value > 0).Select(row => row.Id).ToList();	0
15086466	15086374	Unsubscribe Event Handler from Protected Override Void	protected override void OnViewLoaded(object sender, ViewLoadedEventArg e)\n    {\n        base.OnViewLoaded(sender, e);\n        list = VisualTreeUtil.FindFirstInTree<ListView>(Application.Current.MainWindow, "ListView");\n        ConfigureAndSuperviseInputControls(this.list);\n        ScrollViewer scroll = VisualTreeUtil.FindFirstInTree<ScrollViewer>(this.list);\n        scroll.ScrollChanged+=new ScrollChangedEventHandler(scroll_ScrollChanged);       \n    }\n\n  void scroll_ScrollChanged(object sender, ScrollChangedEventArgs e)\n    {  \n        ConfigureAndSuperviseInputControls(this.list);\n        ScrollViewer scroll = (ScrollViewer)sender;\n        if (scroll.ContentVerticalOffset==scroll.ScrollableHeight)\n        {\n           scroll.ScrollChanged-=new ScrollChangedEventHandler(scroll_ScrollChanged); \n        }\n    }	0
22389859	22389000	Sorting DataGridView with null datetimes	private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)\n    {\n        try\n        {\n            if (DBNull.Value.Equals(e.CellValue1) || DBNull.Value.Equals(e.CellValue2))\n            {\n                if (DBNull.Value.Equals(e.CellValue1) || e.CellValue1.Equals(null))\n                {\n                    e.SortResult = 1;\n                }\n                else if (DBNull.Value.Equals(e.CellValue2) || e.CellValue2.Equals(null))\n                {\n                    e.SortResult = -1;\n                }\n            }\n            else\n            {\n                e.SortResult = (e.CellValue1 as IComparable).CompareTo(e.CellValue2 as IComparable);\n            }\ne.Handled = true\n        }\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.ToString());\n        }\n    }	0
10939785	10939711	Throwing exception with message from regex match	\[([A-Z]+)\]	0
2244872	2230035	How to change AppointmentStatus in managed Exchange Web Services	var extendedProperty = new ExtendedPropertyDefinition(new Guid("00062002-0000-0000-C000-000000000046"), 0x8217, MapiPropertyType.Integer);\nmeeting.SetExtendedProperty(extendedProperty, 1);	0
8407742	8407719	How to add csv data to Dictionary in C#	m_dicTransactions.Add(int.Parse(columns[0]), columns[1]);	0
6081536	6081433	Getting relative virtual path from physical path	String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);	0
8647898	8647738	Multiple Generics ambiguity	IEnumerable<T>	0
5543063	5542901	Finding controls in placeholder	PlaceHolder p = (PlaceHolder)FindControlRecursive(Page, "PlaceHolder1");\n\n\n\npublic static Control FindControlRecursive(Control ctrl, string controlID)\n{\n if (string.Compare(ctrl.ID, controlID, true) == 0)\n {\n  // We found the control!\n  return ctrl;\n }\n else\n {\n  // Recurse through ctrl's Controls collections\n  foreach (Control child in ctrl.Controls)\n  {\n   Control lookFor = FindControlRecursive(child, controlID);\n\n   if (lookFor != null)\n   return lookFor;  // We found the control\n  }\n\n // If we reach here, control was not found\n return null;\n }\n}	0
21963512	21962815	What to feed the datasource for a trirand.jqgrid grid with EF	[HttpPost]\npublic ActionResult BugJqGridDataRequested()\n{\n    using (var db = new BugContext()) {\n        var bugs = db.Bugs.Select(b => new { Prop1 = b.Prop, Prop2 = b.NavigationProperty.Data }).ToList();\n        return Json(new {\n            /// The number of pages which should be displayed in the paging controls at the bottom of the grid.\n            Total = 1,\n            /// The current page number which should be highlighted in the paging controls at the bottom of the grid.\n            Page = 1,\n            /// Anything serializable\n            /// UserData = null,\n\n            //The number of all available bugs not just the number of the returned rows!\n            Records = bugs.Count,\n            Rows = bugs\n        });\n    }\n}	0
751036	751016	Is it possible to enforce the use of a using statement in C#	public static void WorkWithFile(string filename, Action<FileStream> action)\n{\n    using (FileStream stream = File.OpenRead(filename))\n    {\n        action(stream);\n    }\n}	0
21277407	21277364	Best way to get the value from a tuple in C#	Tuple<string, string> getvalue = GetMultipleValue();	0
11819599	11819247	Reading attached files from database using OLE-DB	DBEngine dbe = new DBEngine();\n    Database db = dbe.OpenDatabase(@"z:\docs\test.accdb", false, false, "");\n    Recordset rs = db.OpenRecordset("SELECT TheAttachment FROM TheTable", \n        RecordsetTypeEnum.dbOpenDynaset, 0, LockTypeEnum.dbOptimistic);\n\n    Recordset2 rs2 = (Recordset2)rs.Fields["TheAttachment"].Value;\n\n    Field2 f2 = (Field2)rs2.Fields["FileData"];\n    f2.SaveToFile(@"z:\docs\ForExample.xls");\n    rs2.Close();\n    rs.Close();	0
13663864	13663844	Access outside variable from a Static function	private static List<string> s = new List<string> { "a", "b" };\n\nstatic string GenRan()\n{\n    int r = Rand();\n    string a = null;\n\n    if (r == 1)\n    {\n        a += s[0];\n        s.RemoveAt(0);\n    }\n    if (r == 2)\n    {\n        a += s[1];\n        s.RemoveAt(1);\n    }\n    return a;\n}	0
8608709	8608200	Programmatically acess Google chrome history	SQLiteConnection conn = new SQLiteConnection\n    (@"Data Source=C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data\Default\History");\nconn.Open();\nSQLiteCommand cmd = new SQLiteCommand();\ncmd.Connection = conn;\n//  cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";\n//  Use the above query to get all the table names\ncmd.CommandText = "Select * From urls";\nSQLiteDataReader dr = cmd.ExecuteReader();\nwhile (dr.Read())\n{\nConsole.WriteLine(dr[1].ToString());\n}	0
27223681	27223320	How to get first and last day in month view at DateTimePicker	DateTime dt = new DateTime(year, month, 1);\nint offset = ((int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 6) % 7 + 1;\nDateTime firstDate = dt.AddDays(-offset);\nDateTime lastDate = firstDate.AddDays(41);	0
6099348	6097922	How to open a pdf at a specific page from ASP.Net MVC using iframes	#search=???word1 word2???	0
5290233	5290173	Insert new XML node using LINQ	XDocument doc = XDocument.Parse("<Questions>...</Questions>");\ndoc.Root.Add(\n    new XElement("Question",\n        new XElement("Id", 3),\n        new XElement("Text", "ccc"),\n        new XElement("Reserver"))\n    );	0
7433095	7432925	disabling shell window while running c# program	[DllImport("kernel32.dll")]\nstatic extern IntPtr GetConsoleWindow();\n\n[DllImport("user32.dll")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nconst int SW_HIDE = 0;\nconst int SW_SHOW = 5;\n\nvar handle = GetConsoleWindow();\n\n// Hide\nShowWindow(handle, SW_HIDE);\n\n// Show\nShowWindow(handle, SW_SHOW);	0
10303979	10303599	How to convert this Xceed XAML to C#	new Binding()\n{\n    Path = new PropertyPath(FrameworkElement.DataContextProperty),\n    RelativeSource = new RelativeSource(RelativeSourceMode.Self)\n}	0
32201400	32199074	convert date from 23-08-2015 00:00:00 to Tue Aug 23 2015 00:00:00 GMT+0530	string startDateCalendar = Convert.ToString(startDate.ToString("ddd MMM dd yyyy HH:mm:ss")) + " GMT+0530";	0
2668566	2668250	Unrecognised database format	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False;	0
22731718	22731476	How to convert C# code to C++?	#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned char byte;\n\nbyte *ReadBytes(const char *filename, size_t size){\n    FILE *fp = fopen(filename, "rb");\n    byte *buff = malloc(size);\n    byte *p = buff;\n\n    while(size--)\n        *p++ = fgetc(fp);\n    fclose(fp);\n\n    return buff;\n}\n\nint main(){\n    byte *bytes = ReadBytes("data.txt", 8);\n    byte *reverse = malloc(8);\n    for(int i=7, j=0; i >= 0; --i, ++j)\n        reverse[j] = bytes[i];\n\n    double value = *(double*)reverse;\n    printf("%f\n", value);\n    free(bytes);free(reverse);\n    return 0;\n}	0
25846418	25846342	Comparing string with string from file	File.ReadAllText(<pathoffile>)	0
25206324	25204613	Cannot fill temporary table from gridview	invoiceTableEdited.Columns.Add("MyColumn1", typeof(string));\ninvoiceTableEdited.Columns.Add("MyColumn2", typeof(string));	0
7456059	7455329	Regex to match method content	var reg = @"\n(?<body>\n\{(?<DEPTH>)\n(?>\n(?<DEPTH>)\{\n    |\n\}(?<-DEPTH>)  \n    |\n(?(DEPTH)[^\{\}]* | )\n)*\n\}(?<-DEPTH>)\n(?(DEPTH)(?!))\n)";\n        var input = "abc{d{e}f}gh{i}";\n        foreach (Match m in Regex.Matches(input,reg, RegexOptions.IgnorePatternWhitespace)) Console.WriteLine(m.Groups["body"].Value);	0
27294608	27294354	How to set foreground color of progress bar programatically?	myProgressBar.Foreground = new SolidColorBrush(Colors.Green);	0
22197981	22152804	How to consume an MIME response attachment in C#?	Stream mimeMsgStream;\nvar m = new MimeMessage(mimeMsgStream);	0
7850494	7850385	How to obtain a current page size of the memory MS Windows 7 in C#?	#include <windows.h>\nint main(void) {\n    SYSTEM_INFO si;\n    GetSystemInfo(&si);\n\n    printf("The page size for this system is %u bytes.\n", si.dwPageSize);\n\n    return 0;\n}	0
24457272	24457142	How can I get specific links in a class?	if(el.GetAttribute("class") != "haberlink")\n   continue;	0
24948007	24947894	RedirectToAction with a parameter not working	[HttpPost]<---- Remove this \npublic ActionResult Index(String CityName)\n{\n\n\n}	0
6741079	6740992	Ninject: How to bind an open generic with more than one type argument?	Bind(typeof(IRepository<,>)).To(typeof(Repository<,>));	0
25535022	25533051	Update datagridview from row click on another datagridview	private void dgClasses_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        DataGridView dgv = sender as DataGridView;\n        if (dgv == null)\n            return;\n        if (dgv.CurrentRow.Selected)\n        {\n            string selectedval;\n            DataGridViewRow row = this.dgClasses.SelectedRows[0];\n            selectedval = row.Cells["ID"].Value.ToString();\n\n            XmlReader xmlFile = XmlReader.Create(txtFileLocation.Text, new XmlReaderSettings());\n            DataSet dataSet = new DataSet();\n\n            dataSet.ReadXml(xmlFile);\n\n            DataView dvClass = dataSet.Tables["Product"].DefaultView;\n            dvClass.RowFilter = "Class=" + "'" + selectedval + "'";\n\n            dgProducts.DataSource = dvClass;\n\n            xmlFile.Close();\n        }\n    }	0
24209785	24208832	c# : How ot create a grid row array programatically	Grid[] row = new Grid[counts];\nfor (int i = 0; i < counts; i++)\n{\n    row[i] = new Grid();\n    row[i].RowDefinitions.Add(new RowDefinition());\n}	0
3316623	3316563	escape special chartcter in detail view c#	System.Web.HttpUtility.HtmlDecode(string)	0
22330325	22330211	Remove Items from sub list matching another sub list with Linq	var query = allData.Join(except,\n    item => item.CodigoSeguradora,\n    item => item.CodigoSeguradora,\n    (a, b) => new { a, b });\n\nforeach (var pair in query)\n    pair.a.Franquias.RemoveAll(f => \n        pair.b.Franquias.Select(x => x.CodFranquia).Contains(f.CodFranquia));	0
25211370	25030522	aspx page save on pdf	string attachment = "attachment; filename=" + Session["pdf_name"] + ".pdf";\nResponse.ClearContent();\nResponse.AddHeader("content-disposition", attachment);\nResponse.ContentType = "application/pdf";\nStringWriter s_tw = new StringWriter();\nHtmlTextWriter h_textw = new HtmlTextWriter(s_tw);\nh_textw.AddStyleAttribute("font-size", "8pt");\nh_textw.AddStyleAttribute("color", "Black");\nPanel1.RenderControl(h_textw);//Name of the Panel\nDocument doc = new Document();\nPdfWriter.GetInstance(doc, Response.OutputStream);\ndoc.Open();\nStringReader s_tr = new StringReader(s_tw.ToString());\nHTMLWorker html_worker = new HTMLWorker(doc);\nhtml_worker.Parse(s_tr);\ndoc.Close();\nResponse.Write(doc);	0
27698782	27698656	Initialising an array of objects using new	for (int i = 0; i < scan.length; i++)\n{\n    scan[i] = new Scan();\n}	0
21853047	21848449	Inserting data into element of a generated class	[XmlText]	0
10715080	10692092	How To Set A RadGrid's Page Size Programmatically Without Triggering A PageSizeChanged Event	protected void RadGrid1_PageSizeChanged(object source, GridPageSizeChangedEventArgs e) \n    {                \n       RadGrid1.PageSizeChanged-=new GridPageSizeChangedEventHandler(RadGrid1_PageSizeChanged);\n       RadGrid1.PageSize =  e.NewPageSize;\n\n      RadGrid1.PageSizeChanged += new GridPageSizeChangedEventHandler(RadGrid1_PageSizeChanged);\n\n      RebindGrid();\n    }	0
6737378	6737194	Does anyone know how to communicate with device that support SAE J1939 interface	SAE J1939 defines five layers in the 7-layer OSI network model,	0
32408416	32408316	C# - Supporting different version of a program in the same source	public interface IMyClass {\n    int Test();\n}\n\nclass MyClass1 : IMyClass {\n    public virtual int Test() {\n        int val = 1;\n        val += 100;\n        return val;\n    }\n}\n\nclass MyClass2 {\n    public override int Test() {\n        return 2*base.Test()\n    }\n}	0
20296491	20296442	append string in List<String> contained in a dictionary using LINQ	var myResult = myFieldList.GroupBy(o => o.FieldName, o => o.FieldValue)\n  .ToDictionary(grp => grp.Key, grp => string.Join("\r\n", \n                                       grp.Where(x=>!string.IsNullOrEmpty(x))));	0
2317162	2317111	How to relate Customer and Payment Details	public interface IPaymentType \n{\n  bool Pay(double amount);\n}\n\npublic class CreditCardPType : IPaymentType\n{\n  double limit;\n  // implement Pay()\n}    \npublic class Cheque: IPaymentType\n{\n  int accountNumber;\n  // implement Pay()\n} \n\npublic class Customer\n{\n    public IPaymentType paymentType { get; set; }\n}\n\n\nCustomer customer = new Customer();\ncustomer.paymentType = new CreditCardPType();	0
333475	333391	How to detect what Application Pool I am currently running under? (IIS6)	public string GetAppPoolName() {\n\n        string AppPath = Context.Request.ServerVariables["APPL_MD_PATH"];\n\n        AppPath = AppPath.Replace("/LM/", "IIS://localhost/");\n        DirectoryEntry root = new DirectoryEntry(AppPath);\n        if ((root == null)) {\n            return " no object got";\n        }\n        string AppPoolId = (string)root.Properties["AppPoolId"].Value;\n        return AppPoolId;\n    }	0
34089275	34089129	Read data from xml	XNamespace ns = "urn:schemas-microsoft-com:office:excel";\n IEnumerable<string> ss = xdoc.Descendants(ns + "Crn")\n                              .Elements(ns + "Text")\n                              .Select(x => (string)x);	0
20137894	20137875	Parsing datetime with millisecond	"dd/MM/yyyy h:mm:ss FFF"	0
3736235	3736140	Comparing two Dictionary of Dictionaries	var thirdDict = secondDict.ToDictionary(\n    x => x.Key, \n    x => x.Value.Keys.Except(firstDict[x.Key]).ToDictionary(y => y, y => x.Value[y]));	0
26474173	26472764	foreach to update values in object overwrites values	.ToList()	0
28313146	28309499	Finding lowest Value in one dim array using iteration (Can't use max/min)	int j = 0;\n double min = 0; \n for (int i = 0; i < myDoubles.Length; i++)\n  {\n    if (i == 0)\n    {\n      min = myDoubles[i];\n    }\n    else if (min > myDoubles[i])\n    {\n      min = myDoubles[i];\n      j = i;\n    }\n  }\n  Console.WriteLine("myDoubles[{0}] = {1} is the lowest value in the array", j, min);	0
31000285	31000039	mask all digits except first 6 and last 4 digits of a string( length varies )	var cardNumber = "3456123434561234";\n\nvar firstDigits = cardNumber.Substring(0, 6);\nvar lastDigits = cardNumber.Substring(cardNumber.Length - 4, 4);\n\nvar requiredMask = new String('X', cardNumber.Length - firstDigits.Length - lastDigits.Length);\n\nvar maskedString = string.Concat(firstDigits, requiredMask, lastDigits);\nvar maskedCardNumberWithSpaces = Regex.Replace(maskedString, ".{4}", "$0 ");	0
13587268	13496932	Call PHP based webservice	System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.InnerXml = xml;\nHttpWebRequest req = (HttpWebRequest)WebRequest.Create(endPoint);\nreq.Timeout = 100000000;\n\nif (proxy != null)\n    req.Proxy = new WebProxy(proxy, true);\n\nreq.Headers.Add("SOAPAction", "");\nreq.ContentType = "application/soap+xml;charset=\"utf-8\"";\nreq.Accept = "application/x-www-form-urlencoded"; \nreq.Method = "POST";\nStream stm = req.GetRequestStream();\ndoc.Save(stm);\nstm.Close();\nWebResponse resp = req.GetResponse();\nstm = resp.GetResponseStream();\nStreamReader r = new StreamReader(stm);\nstring responseData = r.ReadToEnd();\n\nXDocument response = XDocument.Parse(responseData);\n\n/* extract data from response */	0
13028663	12978161	Get Recipients List from Email C#	EntityCollection Recipients = email.GetAttributeValue<EntityCollection>("to");\n\nforeach (var party in Recipients.Entities)\n{  \nvar partyName = party.GetAttributeValue<EntityReference>("partyid").Name;\nvar partyId = party.GetAttributeValue<EntityReference>("partyid").Id;\n\n???\n}	0
30236731	30236410	using dictionary with WCF	public Dictionary<int, string> GetLanguageSettingList()\n    {\n        Repository exrepo = new Repository(this.ConnectionString);\n\n        return exrepo.GetLanguageSettingList().Where(c=>c.Id!=null).ToDictionary(c=>c.Id.Value, c=>c.Language);\n    }\n\n\npublic partial class LanguageList\n{\n    public string Language { get; set; }\n    public Nullable<int> Id { get; set; }\n}	0
11691488	11677306	Forgot Password	ou = System.DirectoryServices.DirectoryEntry("LDAP://ou=Users,dc=whatever,dc=something,dc=localetc")\nsearch = System.DirectoryServices.DirectorySearcher(ou, "(samAccountName="+acc"+")", Array[str](["distinguishedName"]]))\nresult = search.FindAll() # note 1\nif result.Count != 1:\n    raise BadError\nelse:\n    ent = System.DirectoryServices.DirectoryEntry(result[0].Properties["distinguishedName"][0])\n    ent.Username = admin # note 2\n    ent.Password = pwd\n    ent.Invoke("SetPassword", Array[object](["newpassword!"]))\n    ent.Properties["LockOutTime"].Value = 0\n    ent.CommitChanges()	0
691027	690389	Inject different object to constructor with StructureMap for certain case	ForRequestedType<DataContext>()\n    .CacheBy(InstanceScope.Hybrid)\n    .AddInstances(inst => inst.ConstructedBy(() => \n        new SecondDataContext { Log = new DebuggerWriter() })\n        .WithName("secondDataContext"))\n    .TheDefault.Is\n    .ConstructedBy(() => new FirstDataContext {Log = new DebuggerWriter()});\n\nForRequestedType<IRepository<SpecificObject>>()\n    .TheDefault.Is\n    .OfConcreteType<SqlRepository<SpecificObject>>()\n    .CtorDependency<DataContext>()\n    .Is(inst => inst.TheInstanceNamed("secondDataContext"));	0
4864726	4864557	How to create an array of List<int> in C#?	var myData = new List<int>[]\n{\n    new List<int> { 1, 2, 3 },\n    new List<int> { 4, 5, 6 }\n};	0
23835315	23703735	How to set large string inside HttpContent when using HttpClient?	var jsonString = JsonConvert.SerializeObject(post_parameters);\n    var content = new StringContent(jsonString, Encoding.UTF8, "application/json");	0
7030112	7029262	sorting items in RadListBox on destination listbox when trasferring	//sorts items by text\nRadListBox1.Sort();	0
11760683	11757757	Json Datetime issue	JsonConvert.SerializeObject(this, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" });	0
17294544	17268362	AutoMapper for a list scenario only seems to repeat mapping the first object in the list	userSearchModel.UserList = UserEvent.Select(item => Mapper.Map<User, UserListModel>(item));	0
7344037	7341288	Detect system language change in WPF	string language = "";\nSystem.Windows.Input.InputLanguageManager.Current.InputLanguageChanged += \n       new    InputLanguageEventHandler((sender, e) =>\n{\n   language = e.NewLanguage.DisplayName;\n});	0
6773638	6773551	Can I use a UserControl to reuse a DropDownExtender despite having page-specific parameters?	[Bindable(BindableSupport.Yes)]	0
4052400	4051737	C# Creating a custom control	public FileExplorer() {\n        this.BeforeExpand += customBeforeExpand;\n        // CreateTree(this);    // <== delete this line\n    }\n\n    protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n        if (!DesignMode) CreateTree(this);\n    }	0
3279216	3279016	C# Parallel Task methods that return value using Func<>	Task<Row> source = Task.Factory.StartNew<Row>(() => ...; return someRow;  );\n Row row = source.Result; // sync and exception handling	0
16740169	16740108	C# trigger method on setter of a DependencyProperty	public static DependencyProperty MinutesProperty =\n    DependencyProperty.Register("Minutes", typeof(string), typeof(TimelineControl),\n    new PropertyMetadata(OnMinutesChanged));\n\nprivate static void OnMinutesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    // Handle change here\n\n    // For example, to call the my_method() method on the object:\n    TimelineControl tc = (TimelineControl)d;\n    tc.my_method();\n}	0
7498993	7498697	Change Label content dynamically	DispatcherTimer timer = new DispatcherTimer();\nDateTime endDate = new DateTime();\nTimeSpan timeToGo = new TimeSpan(0, 1, 0);\n\npublic MainWindow()\n{\n    InitializeComponent();\n\n    this.timer.Tick += new EventHandler(timer_Tick);\n    this.timer.Interval = new TimeSpan(0, 0, 1);\n\n    this.endDate = DateTime.Now.Add(timeToGo);\n\n    this.timer.Start();\n}\n\nvoid timer_Tick(object sender, EventArgs e)\n{\n    this.lblTimer.Content = this.ToStringTimeSpan(this.endDate - DateTime.Now);\n\n    if (this.endDate == DateTime.Now)\n    {\n        this.timer.Stop();\n    }\n}\n\nstring ToStringTimeSpan(TimeSpan time)\n{\n    return String.Format("{0:d2}:{1:d2}:{2:d2}", time.Hours, time.Minutes, time.Seconds);\n}	0
7871543	7871392	Programmatically disable/unregister Excel UDF in C#	(default)	0
990276	978862	How to make forward-only, read-only WMI queries in C#?	using System;\nusing System.Management;\n\nnamespace WmiTest\n{\n    class Program\n    {\n        static void Main()\n        {\n            EnumerationOptions options = new EnumerationOptions();\n            options.Rewindable = false;\n            options.ReturnImmediately = true;\n\n            string query = "Select * From Win32_Process";\n\n            ManagementObjectSearcher searcher =\n                new ManagementObjectSearcher(@"root\cimv2", query, options);\n\n            ManagementObjectCollection processes = searcher.Get();\n\n            foreach (ManagementObject process in processes)\n            {\n                Console.WriteLine(process["Name"]);\n            }\n\n            // Uncomment any of these\n            // and you will get an exception:\n\n            //Console.WriteLine(processes.Count);\n\n            /*\n            foreach (ManagementObject process in processes)\n            {\n                Console.WriteLine(process["Name"]);\n            }\n            */\n        }\n    }\n}	0
23260050	23259864	Extracting field from an XElement	var Ids = root.XPathSelectElements("/ResultSet/results/rows/row/cell[1]")\n              .Select(o => (string)o)\n              .ToArray();	0
11596529	11485278	How to format DateTime in GridView with LINQ to SQL data source?	DateTime today=DateTime.Now;\nstring todayString=today.ToString();\nstring dateOnly=todayString.Split(' ')[0];	0
20445776	20444553	how to build flat API with indexer against dictionary backing	public class GroupManager\n{\n    private readonly GroupStore groups = new GroupStore();\n\n    public GroupStore Groups { get { return this.groups; } }\n\n    public void Add(string groupName, string connectionSring)\n    {\n        groups.Add(groupName, connectionSring);\n    }\n}\n\npublic class GroupStore : IEnumerable<string>\n{\n    private readonly ConcurrentDictionary<string, HashSet<string>> groupStore = new ConcurrentDictionary<string, HashSet<string>>();\n\n    public IEnumerable<string> this[string index] { get { return this.groupStore[index]; } }\n\n    public IEnumerator<string> GetEnumerator()\n    {\n        return groupStore.Keys.GetEnumerator();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return (IEnumerator)GetEnumerator();\n    }\n\n    public void Add(string groupName, string connectionSring)\n    {\n        //groupStore.AddOrUpdate(...);\n    }\n}	0
12976606	12975260	Spawning process holds on to a socket port. How to prevent it from doing so?	proc.StartInfo.UseShellExecute = true;	0
32607352	32429965	Pivot inside a ScrollViewer, scrollviewer wont scroll	private void PivotItem_PointerWheelChanged(object sender, PointerRoutedEventArgs e)\n    {\n        if (e.GetCurrentPoint(scrollViewer).Properties.MouseWheelDelta == (-120))\n        {\n            // On Mouse Wheel scroll Backward\n            scrollViewer.ChangeView(null, scrollViewer.VerticalOffset + Window.Current.CoreWindow.Bounds.Height / 10, null, false);\n        }\n        if (e.GetCurrentPoint(scrollViewer).Properties.MouseWheelDelta == (120))\n        {\n            // On Mouse Wheel scroll Forward\n            scrollViewer.ChangeView(null,scrollViewer.VerticalOffset - Window.Current.CoreWindow.Bounds.Height / 10, null, false);\n        }\n    }	0
8462652	8462641	Convert int (number) to string with leading zeros? (4 digits)	var result = input.ToString().PadLeft(length, '0');	0
31128155	31124824	Pick Observable latest value when any value is produced by another Observable	stateSource.Sample(eventSource)\n     .Zip(eventSource,...)	0
30794197	30793966	How to find string value is in exponential format in C#?	private bool IsExponentialFormat(string str)\n{\n    double dummy;\n    return (str.Contains("E") || str.Contains("e")) && double.TryParse(str, out dummy);\n}	0
3608615	3608525	How to globally add data to a static class in another dll	public static class MyStaticClassInB\n{\n\n    static MyStaticClassInB() { /*fill data here*/ }\n\n    public static object GetData(Type type) { return MyStaticClass.GetData(type); }\n\n    public static void SetData(Type type, object o) { MyStaticClass.SetData(type, o); }\n}	0
17535203	17534625	Cross-thread operation not valid, control accessed from thread other than the thread it was created on	var handle = this.Handle;\nif (_output.InvokeRequired)\n{\n  .....\n}	0
19297843	19297038	Immediately read data from a DataSource	someinfo = (int)((DataTable)cbInfo.ComboBox.DataSource).Rows[0][0];	0
29758257	29758100	A faster way to decompress a text file that uses a unique form of compression	public static IEnumerable<char> Decompress(string compressed)\n{\n    for(var i = 0; i < compressed.Length; )\n    {\n        var c = compressed[i++];\n        if(c == '??')\n        {\n            var count = int.Parse(compressed.Substring(i, 2), NumberStyles.HexNumber);\n            i += 2;\n\n            c = compressed[i++];\n\n            foreach(var character in Enumerable.Repeat(c, count))\n                yield return character;\n        }\n        else\n        {\n            yield return c;\n        }\n    }\n}	0
24078114	24054460	Problems with reading, overwriting and showing a txt file C#	while ((x = inputFile.ReadLine()) != null)\n        {\n            c++;\n          //reading and keeping in memory the highscores\n        }\n  if(c==0) //make all the highscore labels empty, skip sorting the highscores	0
7579443	3550733	C# WPF - Parent window jumps to top left corner of screen when Child window is shown	trans.Owner = this;	0
11348154	11031278	Crystal Reports Multiple Tables Issue	//{@Sunday}\nDateAdd("d", 0, {WeekTable.StartOfWeek})\n\n...\n\n//{@Saturday}\nDateAdd("d", 7, {WeekTable.StartOfWeek})	0
10530022	10529758	How to read text data in particular font using C#?	System.Text.Encoding GreekEncoding = System.Text.Encoding.GetEncoding(1253);\nSystem.IO.StreamReader sr = new StreamReader(@"c:\test.txt", GreekEncoding);\nSystem.Diagnostics.Debug.WriteLine(sr.ReadLine());\nsr.Close();\nsr.Dispose();	0
6548904	6548891	A regular expression for anchor html tag in C#?	HtmlDocument doc = new HtmlDocument();\n\ndoc.LoadHtml(@"<a id=""[constant]""\n      href=""[specific]""\n    >GlobalPlatform Card Specification 2.2\n    March, 2006</a>\n");\n\nvar anchor = doc.DocumentNode.Element("a");\n\nConsole.WriteLine(anchor.Id);\nConsole.WriteLine(anchor.Attributes["href"].Value);	0
529234	529188	Executing a certain action for all elements in an Enumerable<T>	Names.ToList().ForEach(e => ...);	0
20122985	20122890	function that recalls itself upon a catch of non-critical error	public void logic()\n{\n    bool running = true;\n\n    while(running)\n    {\n        running = false;\n\n        try\n        {\n            inner_logic();\n        }\n        catch(non_critical e)\n        {\n            running = true;\n        }\n    }\n}	0
29677415	29627789	Deserialize String to Google TokenResponse	var tokenResponse = new TokenResponse\n{\n    RefreshToken = refreshToken // or you will have to deserialize the string first\n}	0
7104532	7103360	How to get pressed char from System.Windows.Input.KeyEventArgs?	GetCharFromKey(Key key)	0
15370087	15369696	Remove slashes from date and file extension from string	var name = Path.GetFileNameWithoutExtension(name);\nreturn Regex.Replace(name, @"(?<!\d)(\d\d\d\d)-(\d\d)-(\d\d)(?!\d)", "$2$3$4");	0
28374464	28373901	Using more than one value in query to send email in asp.net	Dictionary<string, string> emails = new Dictionary<string, string>();\n...\nwhile (reader.Read())\n{\n  emails[Convert.ToString(reader["email"])] = Convert.ToString(reader["UserName"]);\n}\n\nforeach(string email in emails.Keys)\n{\n  ...\n  mail.To.Add(email);\n  ...\n  mail.Body = "Greetings " + emails[email] + "!".\n  ...\n}	0
11779110	11778698	listbox drag and drop items, items name	var files = (string[])e.Data.GetData(DataFormats.FileDrop);\nforeach (var filename in files)\n{\n    var nameOnly = System.IO.Path.GetFileName(filename);\n}	0
242724	242718	How do i split a String into multiple values?	string[] tokens = text.Split(',');\n\n    for (int i = 0; i < tokens.Length; i++)\n    {\n          yourListBox.Add(new ListItem(token[i], token[i]));\n    }	0
7118005	7093226	Control binding with CurrencyManager without BindingSource	string s1 = textBox1.Text;\nstring s2 = textBox2.Text;\nbool b1 = checkBox1.Checked;\ndr["NAME"] = s1;\ndr["SURNAME"] = s2;\ndr["ACTIVE"] = b1;	0
6627110	6627029	How to sort files by date in file name using c#?	var di = new DirectoryInfo(FileDirectory);\nvar Files = di.GetFiles()\n              .OrderBy( f => f.Name.Substring(f.Name.LastIndexOf('_')+1)\n              .ToList();	0
32915873	32915753	How do I get selected database name from Combo box in a text box when I choose the Path name	FolderBrowserDialog dlg = new FolderBrowserDialog();\nif(dlg.ShowDialog()== DialogResult.OK)\n{\n    var database = yourDatabaseComboBox.SelectedItem.ToString();\n    var extension= "bak";\n    var databaseFileName = string.Format("{0}.{1}", database, extension);\n    txtLocBa.Text = System.IO.Path.Combine(dlg.SelectedPath, databaseFileName);\n}	0
21450433	21448948	Lotus Notes Sending email with options	_notesDocument.ReplaceItemValue("DeliveryPriority", "H");\n        _notesDocument.ReplaceItemValue("DeliveryReport", "C");	0
13519388	13519241	Get DbContext from DbSet	public static void MarkAsModified(this DbContext context, object entity)\n    {\n        context.Entry(entity).State = EntityState.Modified;\n    }	0
6711847	6711098	Adding XML values to dropdownlist, c#	XDocument xml = XDocument.Load(Server.MapPath("~/Upload/" + FileUpload1.FileName));\n\nforeach (var el in xml.Document.Descendants().First().Descendants().First().Descendants())\n{\n    DropDownList1.Items.Add(new ListItem(el.Attribute(XName.Get("name")).Value, Value = el.Value));\n}	0
5835408	5835300	Parsing a DateTime instance	if (date.Date == DateTime.Today) {\n    result = "today, " + date.ToString("t");\n} else if (date.Date.Day == DateTime.Today.AddDays(-1).Day) {\n    result = "yesterday, " + date.ToString("t");\n} else {\n    result = (new TimeSpan(DateTime.Now.Ticks).Days - new TimeSpan(date.Ticks).Days) + " days ago";\n}	0
20115308	20115134	How to get filtered list based on common items in two lists in c#	var result = capability.Where(c => type2Capability.Any(c2 => c.Name == c2.Name));	0
9136455	9136301	Convert PHP to C# - how to handle arrays?	char decode_char(char c, string a1, string a2)\n{\n    for (int i = 0; i < a1.Length; i++)\n    {\n        if (c == a1[i]) return a2[i];\n        if (c == a2[i]) return a1[i];\n    }\n    return c;\n}\nstring decode_str(string s)\n{\n    const string a1 = "0123456789WGXMHRUZID=NQVBL";\n    const string a2 = "bzaclmepsJxdftioYkngryTwuv";\n    StringBuilder sb = new StringBuilder();\n    foreach (char c in s)\n        sb.Append(decode_char(c, a1, a2));\n    return DecodeFrom64(sb.ToString());\n}\nstring DecodeFrom64(string encodedData)\n{\n    byte[] encBytes = Convert.FromBase64String(encodedData);\n    return Text.Encoding.Unicode.GetString(encBytes);\n}	0
11533892	11533780	Extract a value from Datatable and store to a collection in c#	var table = new DataTable();\n            var column = new DataColumn("col1");\n\n            table.Columns.Add(column);\n\n            var row = table.NewRow();\n            row[0] = @"<configuration><Store parameter=""Atribs"">AB,CD</Store></configuration>";\n            table.Rows.Add(row);\n\n            row = table.NewRow();\n            row[0] = @"<configuration><Store parameter=""Atribs"">EF,GH,IJ</Store></configuration>";\n            table.Rows.Add(row);\n\n            var data = new List<List<string>>();\n\n            foreach (DataRow dRow in table.Rows)\n            {\n                var temp = new List<string>();\n                string xml = dRow.Field<string>("col1");\n\n                var element = XElement.Parse(xml);\n                string[] values = element.Descendants("Store").First().Value.Split(',');\n\n                temp.AddRange(values);\n                data.Add(temp);\n            }	0
1482039	1482027	WCF Xml Serialization and AutoImplemented Properties	[DataMember(Name = "DeviceID")]	0
15319481	15319374	how to add binary imges From DataBase to Pdf using ItextSharp	byte[] raw = (byte[])ds.Tables.Rows[i]["TiffImage"];//where ds is the dataset \n//in which you are getting your data and i is the ith row	0
34286668	34285365	How to use MemoryCache insted of Timer to trigger a method?	MemoryCache memCache = MemoryCache.Default;\nmemCache.Add(<mykey>, <myvalue>,\n          new CacheItemPolicy()\n          {\n            AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(_expireminutes)),\n            SlidingExpiration = new TimeSpan(0, 0, 0)\n          }\n          );	0
21346722	21346116	PropertyChangedCallback invokes prior to OnApplyTemplate in WinRT	private void OnFooChanged(...)\n{\n    if (someNamedPart != null && someOtherNamedPart != null && ...)\n    {\n        // Do something to the named parts that are impacted by Foo \n        // when Foo changes.\n    }\n}\n\nprivate void FooChangedCallback(...)\n{\n    // Called by WinRT when Foo changes\n    OnFooChanged(...)\n}\n\nprotected override void OnApplyTemplate(...)\n{\n    // Theoretically, this can get called multiple times - every time the \n    // consumer of this custom control changes the template for this control.\n    // If the control has named parts which must react to the properties\n    // this control exposes, all that work must be done here EVERY TIME\n    // a new template is applied.\n\n    // Get and save named parts as local variables first\n\n    OnFooChanged(...)\n}	0
9605098	9605065	C# assigning elements of a list to a list of variables	let [| a; b; c |] = "aaa,bbb,ccc".Split(',')	0
31902468	31902392	How to set a countdown timer to hourly	int hour = 1;\nint setinterval = hour * 60 * 60 * 1000;\ntimerName.Interval = setinterval;	0
12760752	12721907	How to make console be able to print any of 65535 UNICODE characters	using System;\nusing System.Text;\n\nclass Program {\n    static void Main(string[] args) {\n        Console.OutputEncoding = Encoding.UTF8;\n        Console.WriteLine("????? ?????");\n        Console.ReadLine();\n    }\n}	0
17275753	17275670	Serializing List<> with XmlSerializer	public class DocumentOrder {\n  // ...\n  [XmlAttribute]\n  public string Name { get; set; }\n  [XmlElement("Document")]\n  public List<Document> Documents { get; set; }\n}	0
1023003	1022986	Compare Two Arrays Of Different Lengths and Show Differences	var Foo_Old = new[] { "test1", "test2", "test3" }; \nvar Foo_New = new[] { "test1", "test2", "test4", "test5" };\n\nvar diff = Foo_New.Except( Foo_Old );\nvar inter = Foo_New.Intersect( Foo_Old );\nvar rem = Foo_Old.Except(Foo_New);\n\nforeach (var s in diff)\n{\n    Console.WriteLine("Added " + s);\n}\n\nforeach (var s in inter)\n{\n    Console.WriteLine("Same " + s);\n}\n\nforeach (var s in rem)\n{\n    Console.WriteLine("Removed " + s);\n}	0
16635298	16635274	A dangerous Request.Form when value entered into a textbox	validateRequest="false"	0
11286930	11286018	Converted BitmapImage not displaying on Page	Dispatcher.BeginInvoke(() =>\n{\n    globalWrapper = (PhotoWrapper)JsonConvert.DeserializeObject(\n                                      response.Content, typeof(PhotoWrapper));\n    tempImage = new BitmapImage();\n    tempImage.BeginInit();\n    tempImage.CacheOption = BitmapCacheOption.OnLoad;\n    tempImage.SetSource(new MemoryStream(globalWrapper.PictureBinary, 0,\n                                         globalWrapper.PictureBinary.Length));\n    tempImage.EndInit();\n    globalWrapper.ImageSource = tempImage;\n    PictureList.Items.Add(globalWrapper);\n});	0
31796924	31796873	Convert string to specific date format C#	var input = "27/08/2015 00:00:00";\nvar output = DateTime.ParseExact(input, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)\n                     .ToString("yyyyMMdd");	0
19289041	19288791	Getting the information of repeated nodes from a xml file in C#	XDocument doc=XDocument.Load(xmlPath);\nList<string> values=doc.Descendants("file")\n                       .Select(x=>x.Value)\n                       .ToList();	0
17438756	17433986	Save an image from a folder to another folder under a different name	System.IO.File.Copy(Server.MapPath("/Images/defaultImage.jpeg"), Server.MapPath("/Dog/defaultImage.jpeg"));	0
5117567	5115812	Accessing Sharepoint from a WebApplication	service.URL = "http://localhost:51112/Service1.svc?wsdl";	0
30217327	30133501	YouTube v3 API caption download using SDK nuget package	UserCredential credential;\n        using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))\n        {\n            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(\n                GoogleClientSecrets.Load(stream).Secrets,\n                new[] { YoutubeService.Scope.<THE_RIGHT_SCOPE_HERE> },\n                "user", CancellationToken.None);\n        }\n\n        // Create the service.\n        _service = new YouTubeService(new BaseClientService.Initializer {\n        ApplicationName = config.AppName,\n                HttpClientInitializer = credential,\n                ApplicationName = "Books API Sample",\n            });	0
21580715	21580370	Change value of control in GridView edit template	protected void gvMaint_RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowState == DataControlRowState.Edit)\n    {\n        TextBox txtFreqMiles = (TextBox)e.Row.FindControl("txtFreqMiles");\n\n        // At this point, you can change the value as normal\n        txtFreqMiles.Text = "some new text";\n    }\n}	0
33226154	33226103	Linq query to return as a List from a Model	var query = (from s in _db.VtRegisterEmails\n                     where s.Email.Contains(id)  //  .Where(n => n.Email == id)\n                     select s)\n                     .ToList();	0
7100432	7100396	RegEx Help, match long string, select substring	Match match = Regex.Match(input, @"http://www.domain.com/link/([a-zA-Z0-9]+)/")\nstring key = match.Groups[1].Value;	0
31395569	31395503	WCF Service with parameterized constructor	public class SalesService : Service<Sales>, ISalesService.cs\n{\n   private readonly IRepositoryAsync<Sales> _repository;\n\n   // This is the constructor WCF's default factory calls\n   public SalesService() : this(new ..)\n   {\n   }\n\n   protected SalesService(IRepositoryAsync<Sales> repository)\n   {\n      _repository = repository;\n   }\n}	0
1925719	1925691	Proportionately distribute (prorate) a value across a set of values	Input basis: [0.2, 0.3, 0.3, 0.2]\nTotal prorate: 47\n\n----\n\nR used to indicate running total here:\n\nR = 0\n\nFirst basis:\n  oldR = R [0]\n  R += (0.2 / 1.0 * 47) [= 9.4]\n  results[0] = int(R) - int(oldR) [= 9]\n\nSecond basis:\n  oldR = R [9.4]\n  R += (0.3 / 1.0 * 47) [+ 14.1, = 23.5 total]\n  results[1] = int(R) - int(oldR) [23-9, = 14]\n\nThird basis:\n  oldR = R [23.5]\n  R += (0.3 / 1.0 * 47) [+ 14.1, = 37.6 total]\n  results[1] = int(R) - int(oldR) [38-23, = 15]\n\nFourth basis:\n  oldR = R [37.6]\n  R += (0.2 / 1.0 * 47) [+ 9.4, = 47 total]\n  results[1] = int(R) - int(oldR) [47-38, = 9]\n\n9+14+15+9 = 47	0
30592998	30592562	Create a treeview from a recursiv list C# Asp.net	public HtmlGenericControl RenderMenu(List<item> nodes)\n{\n    if (nodes == null)\n        return null;\n\n    var ul = new HtmlGenericControl("ul");\n\n    foreach (Node node in nodes)\n    {\n        var li = new HtmlGenericControl("li");\n        li.InnerText = node.texte;\n\n        if(node.listeItems != null)\n        {\n            li.Controls.Add(RenderMenu(node.listeItems));\n        }\n\n        ul.Controls.Add(li);\n    }\n\n    return ul;\n}	0
3692522	3689809	WPF window changing the value of another window's control	public class Model :INotifyPropertyChanged\n{\n  .... Implement interface ... \n\n  public double Opacity\n  {\n    get { return this._opacity; } \n    set {this._opacity = value; this.OnPropertyChanged("Opacity"); } \n  }\n}	0
7217351	7217200	Get Row Values from onrowupdating GridView Event 	e.NewValues("Desc")	0
26929881	26928167	Creating a matching GUID	QUuid GetWindowsGuid(const QByteArray& b)\n{\n    uint _a;\n    ushort _b;\n    ushort _c;\n    uchar _d, _e, _f, _g, _h, _i, _j, _k;\n\n    _a = ((uchar)b[3] << 24) | ((uchar)b[2] << 16) | ((uchar)b[1] << 8) | (uchar)b[0];\n    _b = (((uchar)b[5] << 8) | (uchar)b[4]);\n    _c = (((uchar)b[7] << 8) | (uchar)b[6]);\n    _d = b[8];\n    _e = b[9];\n    _f = b[10];\n    _g = b[11];\n    _h = b[12];\n    _i = b[13];\n    _j = b[14];\n    _k = b[15];\n\n    QUuid guid(_a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k);\n    return guid;\n}	0
2396813	2396288	How to get an image to a pictureBox from an URL? (Windows Mobile)	public Bitmap getImageFromURL(String sURL)\n    {\n        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(sURL);\n        myRequest.Method = "GET";\n        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();\n        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());\n        myResponse.Close();\n\n        return bmp;\n    }	0
34016545	34016189	FeedDialog using WebAuthenticationBroker	WebAuthenticationBroker.AuthenticateAndContinue(new Uri("https://www.facebook.com/dialog/feed?app_id=145634995501895&display=popup&caption=An%20example%20caption&link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https://developers.facebook.com/tools/explorer"))	0
8159268	8159211	How to expose/bubble events to outside in Composite Winforms Controls?	public event EventHandler RefreshRequested;	0
6828679	6828653	Setting CreationTime of a directory	Directory.SetCreationTime(strFile, DateTime.Now);	0
22471587	22471415	How to subscribe to an event via c#	dataProvider.OnDataChanged+=myevent_OnDataChanged;\nwhile (true)\n{\n    input = Console.ReadKey(true);\n\n    if ConsoleKeyInfo(input.Key == ConsoleKey.C && (input.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)\n    {\n        break;\n    }\n}	0
297362	297217	ASP.NET C#, need to press a button twice to make something happen	protected void Page_Load(object sender, EventArgs e)\n{    \n    if (!Page.IsPostBack)\n        {   \n             LoadData()\n        }\n}\n\nprivate void LoadData()\n{\n    labDownloadList.Text = null;\n    //Session variables:    \n    if (Session["Game"] != null)\n    ...\n}\n\nprotected void btnFilter_Click(object sender, EventArgs e)\n{    \n    game = lstGames.SelectedValue;\n    modtype = lstTypeMod.SelectedValue;\n    filter = true;\n    LoadData();\n}	0
31835162	31832175	Best solution for async chicken and egg story	Task.Run	0
29901028	29899754	Mocking stored procedure's output parameter	mockObjectContext.Setup(m => m.SP_IsUserAllowedToDoThings(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ObjectParameter>())).Callback<string, string, ObjectParameter>((a, b, c) =>\n        {\n            c.Value = true;\n        });	0
29312523	29312497	Sorting a List<string> with Times C#	List<string> list = new List<string>() {"8:00AM", "4:00AM", "2:00AM", "3:14PM"};\nList<string> sortedList = list.OrderBy(s => DateTime.Parse(s)).ToList();	0
1661264	718916	Strange Pager behaviour in ListView	protected void listview_PreRender(object sender, EventArgs e)\n{\n    getLostCardsList();//your method for binding\n}	0
13191097	13190600	How to create textbox in pdf using iTextSharp?	using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))\n{\n    TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 100, 300), "Vertical");\n    stamper.AddAnnotation(tf.GetTextField(), 1);\n    stamper.Close();\n}	0
5867692	5867641	Elegant approach to get a CSV string from selected data rows in a datagrid	string AllowedProfiles = profiles.Aggregate(string.Empty, (current, row) => current + string.Format(",{0}", row[1])).Remove(0,1);	0
7463570	7458240	Ninject binding with WhenInjectedInto extension method	private class ClassC     \n{         \n    private IDoSomething _doSomething;          \n    public ClassC(IDoSomething doSomething)\n    {             \n        _doSomething = doSomething;         \n    }          \n\n    public void SaySomething()          \n    {              \n        Console.WriteLine("Hello from Class C");               \n        //var x = _Kernel.Get<IDoSomething>();               \n        _doSomething.SaySomething();          \n    }     \n}	0
16048215	16046923	Windows forms ImageList - Add images with Relative path - No file copy	Resources.SomeName	0
4328786	4328750	I need to know how to deserialize a specific XML into objects defined in a custom class in C#	public class userAttributeList\n{\n    [XmlElement]\n    public List<UserAttribute> attribute { get; set; }\n\n    public UserAttributeList()\n    {\n        attribute = new List<UserAttribute>();\n    }\n}\n\npublic class UserAttribute\n{\n    public int userId { get; set; }\n    public int attId { get; set; }\n    public string attName { get; set; }\n    public int attTypeId { get; set; }\n    public string attTypeName { get; set; }\n    public string attData { get; set; }\n}	0
10710388	10710156	Using reflection to get values from properties from a list of a class	PropertyInfo piTheList = MyObject.GetType().GetProperty("TheList"); //Gets the properties\n\nIList oTheList = piTheList.GetValue(MyObject, null) as IList;\n\n//Now that I have the list object I extract the inner class and get the value of the property I want\n\nPropertyInfo piTheValue = piTheList.PropertyType.GetGenericArguments()[0].GetProperty("TheValue");\n\nforeach (var listItem in oTheList)\n{\n    object theValue = piTheValue.GetValue(listItem, null);\n    piTheValue.SetValue(listItem,"new",null);  // <-- set to an appropriate value\n}	0
12642302	12642283	How to access the properties in a class from another class	FileData fd = new FileData(new BatchData());	0
1552673	905081	nHibernate Validator custom IMessageInterpolator	ClassValidator classValidator = new ClassValidator(obj.GetType(), null, new CustomMessageInterpolator(), \nCultureInfo.CurrentCulture, ValidatorMode.UseAttribute);\nInvalidValue[] validationMessages = classValidator.GetInvalidValues(obj);	0
32065446	32064687	Random variable selects same values despite single instance	public double GetRandomNumber(double minimum, double maximum)\n{ \n    return game.rand.NextDouble() * (maximum - minimum) + minimum;\n}	0
18876820	18875805	accepting and EULA for a quiet install of an EXE c#	setup.exe /v/qn	0
4231904	4231824	WebBrowser Control download file in session	myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");	0
16240138	16240003	C# - Remove all items from listbox	BindingSource bindingSource = (BindingSource)listBox1.DataSource;\nIList SourceList = (IList)bindingSource.List;\n\nSourceList.Clear();	0
848413	848399	Setting a css class to HtmlInputCheckBox in C#	FieldCtrl.Attributes["class"] = "MyCssClass";	0
11880031	11879939	How to parse Html by Agility into a string in C#?	var blockQuoteNode = document.DocumentNode.Descendants("blockquote").First(); // or do a document.DocumentNode.SelectSingleNode(//put the exact xpath value of the blockquote element here...)\nvar stringsYouNeed = blockQuoteNode.InnerText;	0
7516113	7499269	Connection opening problem in SQLite	SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();\nbuilder.FailIfMissing = true;\nbuilder.DataSource = "Insert the fully qualified path to your sqlite db";\nSQLiteConnection connection = new SQLiteConnection(builder.ConnectionString);\nconnection.Open();	0
11446265	11445125	Disabling particular Items in a Combobox	Font  myFont = new Font("Aerial", 10, FontStyle.Regular);\n\nprivate void comboBox1_DrawItem(object sender, DrawItemEventArgs e)\n{        \n    if (e.Index == 1)//We are disabling item based on Index, you can have your logic here\n    {\n        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.LightGray, e.Bounds);\n    }\n    else\n    {\n        e.DrawBackground();\n        e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), myFont, Brushes.Black, e.Bounds);\n        e.DrawFocusRectangle();\n    }\n} \n\n void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (comboBox1.SelectedIndex == 1)\n            comboBox1.SelectedIndex = -1;\n    }	0
10573798	10573423	How to read custom data type	public class UserData\n{\n    public int userID { get; set; }\n    public string name { get; set; }\n    public string email { get; set; }\n    public string contact { get; set; }\n    public string status { get; set; }\n}	0
8088515	8088495	How to encode a URL string	string url = "http://www.test.com/images/" + HttpUtility.UrlEncode("tony's pics.jpg");	0
10404870	10404416	Connecting a MS Access (.mdb) Database to a MVC3 Web Application	string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;\npublic void InsertRow(string connectionString, string insertSQL)\n{\n    using (OleDbConnection connection = new OleDbConnection(connectionString))\n    {\n        // The insertSQL string contains a SQL statement that\n        // inserts a new row in the source table.\n        OleDbCommand command = new OleDbCommand(insertSQL);\n\n        // Set the Connection to the new OleDbConnection.\n        command.Connection = connection;\n\n        // Open the connection and execute the insert command.\n        try\n        {\n            connection.Open();\n            command.ExecuteNonQuery();\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n        }\n        // The connection is automatically closed when the\n        // code exits the using block.\n    }\n}	0
21150836	21150802	C# object to int for MYSQL datediff	cmd.CommandText = "SELECT DATEDIFF(end_date, NOW()) FROM `as_users` WHERE username = '" + this.username_txt.Text + "'";\nconn.Open();\nint daysLeft = Convert.ToInt32(cmd.ExecuteScalar());\nMessageBox.Show("Days Left: " + daysLeft );\nif (daysLeft >= 0)\n{\n    MessageBox.Show("expired");\n}	0
57363	57350	How do I get the current user's Local Settings folder path in C#?	String appData = \n    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);	0
905377	905317	Permutations of capitalization	public static List<string> Permute( string s )\n{\n  List<string> listPermutations = new List<string>();\n\n  char[] array = s.ToLower().ToCharArray();\n  int iterations = (1 << array.Length) - 1;\n\n  for( int i = 0; i <= iterations; i++ )\n  {\n    for( int j = 0; j < array.Length; j++ )\n    array[j] = (i & (1<<j)) != 0 \n                  ? char.ToUpper( array[j] ) \n                  : char.ToLower( array[j] );\n    listPermutations.Add( new string( array ) );\n  }\n  return listPermutations;\n}	0
11180976	11180836	Parsing the integer part of string	string input = textBox3.Text.Trim();\nMatch match = Regex.Match(input,\n    "^" +\n    "((?<d>[0-9]+)d)? *" +\n    "((?<h>[0-9]+)h)? *" +\n    "((?<m>[0-9]+)m)? *" +\n    "((?<s>[0-9]+)s)?" +\n    "$",\n    RegexOptions.ExplicitCapture);\n\nif (match.Success)\n{\n    int d, h, m, s;\n    Int32.TryParse(match.Groups["d"].Value, out d);\n    Int32.TryParse(match.Groups["h"].Value, out h);\n    Int32.TryParse(match.Groups["m"].Value, out m);\n    Int32.TryParse(match.Groups["s"].Value, out s);\n    // ...\n}\nelse\n{\n    // Invalid input.\n}	0
2050192	2050077	Xml Serialization of a List where the parent element has additional elements	public class Category\n{       \n    [XmlAttribute]\n    public string Attrib1 { get; set; }\n\n    [XmlAttribute]\n    public string Attrib2 { get; set; }     \n\n    [XmlElement("Item")]\n    public List<string> Items { get; set; }\n}	0
17916774	17909266	Control number of threads	public delegate void FileClosedHndlr();\n\n\n   public class MyThread\n   {\n      private event FileClosedHndlr FileClosed;\n\n      public void MyMain()\n      {\n         Thread t = new Thread(new ThreadStart(start));\n         FileClosed += new FileClosedHndlr(MyThread_FileClosed);\n         t.Start();\n      }\n\n      void MyThread_FileClosed()\n      {\n         // Thread has ended file open\n         // open another file\n      }\n\n      private void start()\n      {\n         // Open the file\n         // End thread\n\n         if (FileClosed != null)\n         {\n            FileClosed();\n         }\n      }\n   }	0
28074072	28072616	Encrypted Communication for File I/O	[Browser]  <== SSL ==>  [Pres-Server]  <== SSL ==>  [App-Server]  <== IPSec ==>  [File System]	0
20129628	20129475	How can i fill a multidimensional array from a text file?	public static string[,] GetData(int row, int column, string filePath)\n    {\n        int[,] data = new string[row, column];\n        using (StreamReader reader = File.OpenText(filePath))\n        {\n            for (int r = 0; r < data.GetLength(0); r++)\n            {\n                for (int c = 0; c < data.GetLength(1); c++)\n                {\n                    if (reader.EndOfStream)\n                    {\n                        return data;\n                    }\n\n                    //Note that Parse throw error if the string is not a valid int\n                    //use it only if you anticipate that your file contain int only and other\n                    //string should be considered as errors. otherwise use TryParse\n                    data[r, c] = int.Parse(reader.ReadLine());\n                }\n            }\n        }\n\n        return data;\n    }	0
28217788	28206153	System reflection IL emit override method syntax	FieldBuilder field = ivTypeBld.DefineField("_value", typeof(string), FieldAttributes.Public);\n    MethodBuilder toStringMethod = ivTypeBld.DefineMethod("ToString",\n        MethodAttributes.Public\n        | MethodAttributes.HideBySig\n        | MethodAttributes.NewSlot\n        | MethodAttributes.Virtual\n        | MethodAttributes.Final,\n        CallingConventions.HasThis,\n        typeof(string), \n        Type.EmptyTypes);\n\n    ILGenerator il = toStringMethod.GetILGenerator();\n    il.Emit(OpCodes.Ldarg_0);\n    il.Emit(OpCodes.Ldfld, field);\n    il.Emit(OpCodes.Ret);\n\n    ivTypeBld.DefineMethodOverride(toStringMethod, typeof(object).GetMethod("ToString"));	0
1183811	1183698	How to use WebResponse to Download .wmv file	public void DownloadFile(string url, string toLocalPath)\n{\n    byte[] result = null;\n    byte[] buffer = new byte[4097];\n\n    WebRequest wr = WebRequest.Create(url);\n\n    WebResponse response = wr.GetResponse();\n    Stream responseStream = response.GetResponseStream;\n    MemoryStream memoryStream = new MemoryStream();\n\n    int count = 0;\n\n    do {\n        count = responseStream.Read(buffer, 0, buffer.Length);\n        memoryStream.Write(buffer, 0, count);\n\n        if (count == 0) {\n            break;\n        }\n    }\n    while (true);\n\n    result = memoryStream.ToArray;\n\n    FileStream fs = new FileStream(toLocalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);\n\n    fs.Write(result, 0, result.Length);\n\n    fs.Close();\n    memoryStream.Close();\n    responseStream.Close();\n}	0
12563843	12562702	How to get a control in a listbox on code behind windows phone?	Button button1 = sender as Button;\n            button1.Backgorund = new SolidColorBrush(Colors.Red);	0
8837811	8837741	Using StringBuilder with DataSet to build dynamic table	DataSet valuesSet = getBlendInfo.GetProcessValues(reqID);\nforeach (DataRow dRow in valuesSet.Tables[0].Rows)\n{\n    bool firstColumn = true;\n    foreach (DataColumn dbColumn in valuesSet.Tables[0].Columns)\n    {\n        if (firstColumn)\n            firstColumn = false;\n        else\n        {\n            tblString.Append("<td>");\n            tblString.Append(dRow[dbColumn].ToString());\n            tblString.Append("</td>");\n        }\n    }\n}	0
31066931	31066834	Convert Int To Hex	public void IntToHex(int num)\n    while(num>=0)\n    {\n        num/=16;   // never set num smaller than 0\n    }	0
31151488	31151304	How can I get original character?	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        string inputKey;\n\n        bool capsLock = IsKeyLocked(Keys.CapsLock); // Check for capslock is on\n        bool shift = e.Shift; // Check for Shift button was pressed\n\n        if ((shift && !capsLock) || (!shift && capsLock))\n        {\n            inputKey = new KeysConverter().ConvertToString(e.KeyCode);\n        }\n        else if ((shift && capsLock) || (!shift && !capsLock))\n        {\n            inputKey = new KeysConverter().ConvertToString(e.KeyCode).ToLower();\n        }\n    }	0
30089653	30089624	Regex Spliting a String Mid Search-Phrase	messageList = Regex.Split(content, @"(?<=\r\n)(?=TXT)");	0
22875563	22875444	Indent multiple lines of text	var result = indent + textToIndent.Replace("\n", "\n" + indent);	0
15239287	15224503	store datetimepicker value of c# into mysql database	dtpDate = datetimepicker1.value.date;\ndtpTime = datetimepicker2.value.Timeofday;\nMySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);\ncon.Open();\ncmd.ExecuteNonQuery();\ncon.Close();	0
619316	619303	How can I access a GridView on a page from a control on a Page?	public GridView GridViewToRebind {get; set;}	0
10817140	9750358	How to Check In into the Facebook.?	Dictionary<string, string> objcoordinates = new Dictionary<string, string>();\n                objcoordinates["latitude"] = ViewModelLocator.ShareOptionsStatic._eventInfoModel.latitude == 0.0 ? "34.04503" : System.Convert.ToString(ViewModelLocator.ShareOptionsStatic._eventInfoModel.latitude);\n                objcoordinates["longitude"] = ViewModelLocator.ShareOptionsStatic._eventInfoModel.longitude == 0.0 ? "-118.265633" : System.Convert.ToString(ViewModelLocator.ShareOptionsStatic._eventInfoModel.longitude);\n                Dictionary<string, object> param = new Dictionary<string, object>();\n\n                param["message"] = "Hello.Messages.!"\n                param["place"] = "49127904491";\n                param["coordinates"] = objcoordinates; // "'latitude'= '37.4163458217','longitude'= '-122.15198690595'";\n                objClient.PostAsync("me/checkins", param);	0
3903193	3903159	LINQ orderby FK using a left join	let orderIndex = _categoryOrders.OrderIndex ?? int.MaxValue	0
14816882	14816815	What is the correct way to restrict access to properties that need to be assigned from another assembly?	public interface IMessage\n{\n    int ID { get; }\n    IMessage Parent { get;  }\n}	0
29813043	29812984	RegEx to replace a particular pattern v-q- to q- and v- to q- .	Regex.Replace(ttt, @"\/(v-[^\.]*?q-|v-)", "/q-");	0
4698913	4698855	Onmouseover using Hyperlinks	a {\n  background-image: url(images/image1.jpg);\n}\na:hover {\n  background-image: url(images/image2.jpg);\n}	0
4735712	4227	Accessing a Dictionary.Keys Key through a numeric index	int LastCount = mydict.Keys.ElementAt(mydict.Count -1);	0
20971853	20971330	CommunicationException when I call WCF from Silverlight (or how to get ALL data from DB in one function)	Select(i => new Mod()\n{\n Items = i.Items.Select((j) => new Item() { Foo = j.Foo } }	0
25729054	25728571	Sitecore save with silent and search	var tempItem = (SitecoreIndexableItem)item;\nSitecore.ContentSearch.ContentSearchManager.GetIndex("Index Name").Refresh(tempItem);	0
1954889	1954788	Setting the correct codepage for a database read operation	String.Format	0
20014175	19649073	Drawing Image wrong size WPF	verticalWall.Stretch = Stretch.Fill;	0
11885305	11885021	Disposing streams in called method from caller	void method1(){\n               using (var Dest = new DataStream(true))\n               {\n                   MailMessage m = Method2(Dest);\n                   .....\n                   m.Send();\n               }\n            }\n\n            MailMessage Method2(Stream Dest){\n\n                // code that reads info into the stream\n\n                // Go back to the start of the stream\n                Dest.Position = 0;\n\n                // Create attachment from the stream\n                Attachment mailattachement = new Attachment(Dest, contentType);\n\n                //Create our return value\n                var message = new MailMessage();\n                message.To.Add(UserInfo.UserDetail.Email);\n                message.Subject = "P&L Data View - " + DateTime.Now.ToString();\n                message.Attachments.Add(mailattachement);\n                return message;\n           }	0
11783646	11782672	menu item on CommandBar at a specified position	button = (CommandBarButton)\n    cellbar.Controls.Add(MsoControlType.msoControlButton, \n    Missing.Value, Missing.Value,\n    1, true);	0
23012803	22913437	Set formatting in RTF string?	private void _btnFormat_Click(object sender, RoutedEventArgs e)\n    {\n        TextRange rangeOfText = new TextRange(richTextBoxArticleBody.Document.ContentStart, richTextBoxArticleBody.Document.ContentEnd);\n        rangeOfText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);\n        rangeOfText.ApplyPropertyValue(TextElement.FontSizeProperty, "12");\n        rangeOfText.ApplyPropertyValue(TextElement.FontFamilyProperty, "Arial");\n        rangeOfText.ApplyPropertyValue(TextElement.FontStyleProperty, "Normal");\n        rangeOfText.ApplyPropertyValue(Inline.TextDecorationsProperty, null);\n        rangeOfText.ApplyPropertyValue(Paragraph.MarginProperty, new Thickness(0));\n\n    }	0
4146685	4146674	Using Attributes for Generic Constraints	public static void Insert<T>(this IList<T> list, IList<T> items)\n{\n    var attributes = typeof(T).GetCustomAttributes(typeof(InsertableAttribute), true);\n\n    if (attributes.Length == 0)\n        throw new ArgumentException("T does not have attribute InsertableAttribute");\n\n    /// Logic.\n}	0
19642946	19642489	Add Control for dynamically created Label	private void LabelClick(object sender, EventArgs e)\n    {\n        string Path = ((Label)sender).Text ;\n        System.Diagnostics.Process.Start(Path) ; \n     }	0
21135228	21132680	Count the number of attendees, that have accepted a meeting with EWS	Appointment app;\n\nint count = app.RequiredAttendees.Count(x => (x.ResponseType.HasValue && x.ResponseType.Value == MeetingResponseType.Accept));	0
21140232	21138558	Add javascript into httpmodule of DNN	public void Init(HttpApplication context)\n{\n    context.PreRequestHandlerExecute += new EventHandler(this.RegisterPagePrerenderHandler);\n}\n\nprivate void RegisterPagePrerenderHandler(object s, EventArgs e)\n{\n    if (HttpContext.Current.Handler is Page)\n    {\n        Page page = (Page) HttpContext.Current.Handler;\n        page.PreRender += delegate (object ss, EventArgs ee) {\n            if (page is CDefault)\n            {\n                page.ClientScript.RegisterClientScriptInclude("key", page.ResolveUrl("~/myjs.js"));\n            }\n        };\n    }\n}	0
26724168	26718193	How to find Unit Tests that call a specific method during their execution?	-coverbytest	0
28455946	28455647	SQL LINQ Lambda for inner join to select specific column	List<String> listOfCities = db.Venue.Join(db.Event,\n                               venue => venue.venueName, \n                               ev => ev.venueName, \n                               (venue, ev) => venue.venueAddress)\n                               .Distinct().ToList();	0
10994560	10994507	Performance Issues when Parsing Messages using multiple Regex Commands	regexMatch = resolverKvp.Key.Pattern.Match(topicName);\nif (regexMatch.Success)\n{\n      //etc	0
6330267	6330133	Get client machine name	Request.ServerVariables("REMOTE_ADDR")	0
7807699	7807471	Test data to build tree menu using recursive method?	public void BuildChildItems(MenuItem parentMenuItem, int numberOfChildren, int level)\n{\n  if(level == 0) return;\n\n  var results_for_this_level = create_results_for_this_level();\n  parentMenuItem.Add(results_for_this_level);\n\n\n  foreach(sibling in results_for_this_level)\n  {\n     BuildChildItems(sibling, numberofChildren, level-1) //note the decrement of level here\n  } \n    }	0
12093985	12092030	Select cell by right mouse click	if (e.RightButton == MouseButtonState.Pressed)\n{\n    grid.Focus();\n    grid.UnselectAll();\n    grid.CurrentCellInfo = new GridViewCellInfo(cell);\n    grid.SelectedCells.Add(grid.CurrentCellInfo);\n}	0
4223194	4223123	client - server application crashes	try\n{\n   var t = new Thread(()=>\n      {\n          Thread.Sleep(5000);\n          throw new Exception();\n      });\n   t.Start();\n   //t.Join();\n}\ncatch\n{\n    //you can't deal with exception here\n    //even though you uncomment `t.Join`\n    //the application will crash even there is a try-catch wrapped\n}	0
17954780	17954532	How to convert C/C++ struct to C#	struct asdf{\nstring            mc;\ndouble[]          md;\n\nbyte[]            muc;\n\nbyte              muc0;\nbyte              muc1;\nbyte              muc2;\nbyte              muc3;\n};	0
16661010	16660222	WPF and Json Deserializer with multiple items	var rawData = "{\"Controllers\": [{\"Name\" : \"xbox\", \"IP\" : \"192.100.14.160\"} ,{\"Name\" : \"ps3\", \"IP\" : \"192.100.14.131\"}]}";\nDataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ControllerCollection), new Type[] {typeof(Controller)});\nMemoryStream sr = new MemoryStream(Encoding.Unicode.GetBytes(rawData));\n//sr.Seek(0, SeekOrigin.Begin);\nControllerCollection pat = (ControllerCollection)serializer.ReadObject(sr);\nsr.Close();	0
20413344	20411800	Regular expression to put a backslash at the end of a path, if necessary	Path.Combine()	0
31999619	31998947	its is possible to open to different forms in one from using splinter in C#	private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n{\n    if (treeView1.SelectedNode.Name == "Node1")\n    {\n        Form2 f = new Form2();\n        f.TopLevel = false; // won't work without this!  \n        this.splitContainer1.Panel2.Controls.Add(f); // add your form to the desired container\n        f.Show(); // now display the form\n    }\n}	0
13990975	12932149	How to change the expected content type of WSDL client?	wsHttpBinding.TextEncoding = Encoding.UTF8;	0
30512376	30512218	Setting schema name for DbContext	public class MyContext: DbContext \n        {\n            public MyContext(): base("MyContext") \n            {\n            }\n\n            public DbSet<Student> Students { get; set; }\n\n            protected override void OnModelCreating(DbModelBuilder modelBuilder)\n            {\n                //Configure default schema\n                modelBuilder.HasDefaultSchema("Ordering");\n            }\n        }	0
18097812	18097711	Get max column length for each column in a table represented by a list of Dictionaries	var source = new List<Dictionary<string, object>>();\n\n// (...)\n\nvar maxColumnLengths = source.SelectMany(x => x)\n                             .GroupBy(x => x.Key)\n                             .ToDictionary(g => g.Key,\n                                           g => g.Max(x => x.Value.ToString().Length));	0
15388150	15388079	How to initialize an array of Point?	Point[] points = new Point[] { new Point { X = 0, Y = 1 }, new Point { X = 2, Y = 1 }, new Point { X = 0, Y = 3 } };	0
21497082	21497077	Set a variable date to six months prior to today	var sixMonthsPriorToNow = DateTime.Now.AddMonths(-6);	0
1838323	1838101	C++/CLI : How to declare template array as method parameters	public:\n  generic <typename T>\n  static bool ArrayEquals(array<T>^ a, array<T>^ b)\n  {\n      return true;\n  }	0
7725830	7725732	Get RoutedEvent Source as grandchild of handler	MouseButtonEventArgs.OriginalSource	0
32577589	32555646	Unity3D failing to exicute Newtonsoft Json code	#If Unity\ntempJson = tempJson.Replace("MO1Common", "Assembly-CSharp")\n#EndIf	0
23135634	20662409	run c# code from 2 buttons in a gridview	protected void gridview_search_RowCommand(object sender, \n    GridViewCommandEventArgs e)\n{\n   if (e.CommandName.CompareTo("unlock_account") == 0)\n   {\n      int user = (int)gridview_search.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;\n\n      //unlock account method\n      userObj.unlockAccount(user);\n\n      }\n}	0
6046672	6046501	How to know which generated button was pushed in listbox?	private void Button_Click(object sender, RoutedEventArgs e)\n{\n  Button btn = sender as Button;\n  var myObject = btn.DataContext;\n}	0
7602622	7602581	load xelement into a datatable	branchesDataTable.ReadXml(new StringReader(new XElement("branches", elList).ToString()));	0
20073307	20071826	How do I send a link to another action in an email?	HtmlHelper.GenerateRouteLink(Request.RequestContext,\n                             RouteTable.Routes,\n                             "Click here.",\n                             targetRouteName,\n                             Request.Url.Scheme,\n                             Request.Url.Authority,\n                             "",\n                             new RouteValueDictionary(new { action = "ResetPasswordAction", controller = "YourController", passwordToken = token }),\n                             new Dictionary<string, object>()\n    );	0
30793725	30793332	How to deserialize after serializing with binary DataContactSerializer?	binWriter.Flush()	0
34131103	34130828	Is it possible to consume an XML RPC service using a basic HTTP request?	static void Main(string[] args)\n    {\n          HttpWebRequest request = BuildWebRequest();\n\n          var response = request.GetResponse() as HttpWebResponse;\n          var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();\n\n    }\n\n    private static HttpWebRequest BuildWebRequest()\n    {\n        var request = WebRequest.Create(Url) as HttpWebRequest;\n\n        request.Method = "POST";\n        request.ContentType = "application/xml";\n        request.Timeout = 40000;\n        request.ServicePoint.Expect100Continue = true;\n\n        string body = @"<?xml version="1.0"?>\n<methodCall>\n  <methodName>examples.getStateName</methodName>\n  <params>\n    <param>\n        <value><i4>40</i4></value>\n    </param>\n  </params>\n</methodCall>";\n\n        byte[] bytes = Encoding.Default.GetBytes(body);\n\n        using (var requestStream = request.GetRequestStream())\n        {\n            requestStream.Write(bytes, 0, bytes.Length);\n        }\n\n        return request;\n    }	0
26211749	26211628	Linq - Select a particular column	string column = 'dob'; // This is dynamic\n\nvar data = ctx.tblTable\n                    .Where(e => e.Id == Id && e.Name == name)\n                    .ToList()\n                    .Select(e => GetPropValue(e, column))\n                    .FirstOrDefault();\n\n\npublic object GetPropValue(object obj, string propName)\n{\n     return obj.GetType().GetProperty(propName).GetValue(obj, null);\n}	0
33896001	33895728	Using Parameter on an HTML link	string bodyFormat = "<table><tr><td>Please be informed that your employee <b>{0}</b> wants to send the no <b>{1}</b>. <br /> Please see attached the <b><a href=\'http://myproject/myproject.aspx?Parameter={1}'> SF </a></b>.<br /><br /></td> </tr><tr><td>If you need more details <b>{2}</b>.</td></tr> </table>";\nstring body = string.Format(bodyFormat, Convert.ToString(Session["Userfull"]), id, Convert.ToString(Session["User"]));	0
525549	518281	Can I change an XText object into a string with character references and entities resolved?	string textvalue = text.Value;	0
9975343	9975279	Open a file in c#	foreach (System.IO.FileInfo thefile in fiArr)\n{\n    if (thefile.Name == "index.html")\n    {\n        Process.Start(thefile.Name);\n    }\n}	0
5200070	5200014	Making a second database query based on the first	protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)\n    {\n        DataRowView drw = (DataRowView)e.Item.DataItem\n        String sql = String.Format("Select * FROM UserInfo WHERE user_id={0}", drw["user_id"]);\n\n\n        Label lblUserName = (Label) e.Item.FindControl("lblUserName");\n        lblUserName.Text = //WWhatever you get from query...\n    }	0
285041	283128	How do I send ctrl+c to a process in c#?	p.StandardInput.Close()	0
19593196	19592947	How to modify one column and copy one DataTable into another DataTable	private void CopyColumns(DataTable source, DataTable dest, params string[] columns)\n{\n  dest = source.AsEnumerable()\n               .Select(row=> {\n                   DataRow newRow = dest.NewRow();\n                   newRow[columns[0]] = ((string)row[columns[0]])\n                                       .Replace("USD","").Trim('/');                      \n                   for(int i = 1; i < columns.Length; i++) {\n                     newRow[columns[i]] = row[columns[i]];\n                   }\n                   return newRow;  \n                }).CopyToDataTable();\n}	0
28038184	28038075	Force the browser to save downloaded file in a specific location	Response.SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });\nreturn myFileStreamResult	0
28879692	28879190	how to use regex.Matches in c#	Regex.Replace(word , @"(\w+)=(case.*?\bend\b)", @"$2 ""$1""", RegexOptions.IgnoreCase);	0
28077725	28077313	Organizing data in a class	public class Floor {\n    public int DBedrooms {get; set; }\n    public int DKitchens {get; set; }\n    public int DLiving { get; set; } \n}\n\npublic class House {\n    public List<Floor> Floors{get;set;}\n    public string NSchool { get; set; }\n    public int NSchoolDist { get; set; }\n    public int NCrime { get; set; } \n}	0
7768466	7768397	How to create copy of class object without any reference?	public static T DeepCopy(T other)\n{\n    using (MemoryStream ms = new MemoryStream())\n    {\n        BinaryFormatter formatter = new BinaryFormatter();\n        formatter.Serialize(ms, other);\n        ms.Position = 0;\n        return (T)formatter.Deserialize(ms);\n    }\n}	0
12524824	12524638	How to get value from one TextBox to another TextBox using Tab Index	private void textBox1_Leave(object sender, EventArgs e)\n    {\n        textBox2.Text = textBox1.Text;\n    }\n\n    private void textBox2_Enter(object sender, EventArgs e)\n    {\n        textBox2.Text = textBox1.Text;\n    }	0
4384995	4384934	How to capitalize only the first letter of a string, while lowercasing the rest?	petitioner = respetMyReader["pet_name"].ToString();\npetitioner = petitioner.Substring(2,1).ToUpper() + petitioner.Substring(1).ToLower();	0
28796014	28792548	How can I play byte array of audio raw data using NAudio?	byte[] bytes = new byte[1024];\n\nIWaveProvider provider = new RawSourceWaveStream(\n                         new MemoryStream(bytes), new WaveFormat());\n\n_waveOut.Init(provider);\n_waveOut.Play();	0
2963474	2963255	Dropdown list bound to object data source - how to update on a button click	Accommodations1.Items.Insert(0,new ListItem("Select",""));	0
3728941	3726295	How to make "mouse-transparent" panel?	IsHitTestVisible="False"	0
5820176	5819645	Automapper automatically resolve correct subclass to map to?	Mapper.CreateMap<BaseViewModel,BaseDto>()\n        .Include<FirstViewModelImpl,FirstDtoImpl>()\n        .Include<SecondViewModelImpl,SecondDtoImpl>();\n\nMapper.CreateMap<FirstViewModelImpl,FirstDtoImpl>();\nMapper.CreateMap<SecondViewModelImpl,SecondDtoImpl>();	0
33869773	33869358	ASP.Net MVC 5 how to use Authorize Attribute with multiple login (Multiple user table)	User.IsInRole	0
26682239	26651271	Algorithm for Table / Seat assignment	//Place everyone at a table while avoiding seating competitors together\nfor each table T:\n   UP = a randomly shuffled list of unseated people\n   for each person X from UP\n      While there still is at least one seat available at T AND\n          X is not a competitor of anyone already seated at T\n             seat X at T\n\n   if T still has one or more seats available\n      abort;  //With the decisions taken so far, noone can be seated at T. This run has no result.\n\n//Complete seat configuration found. Award a penalty point for evey person not seated with a colleague.\npenaltyPoints = 0\nfor each table T:\n   for each person X seated at T\n      If there is no other person at T that is from X's company\n         Add a penalty point.	0
19561525	19561399	Write Filestream into StreamWriter in c#	using (FileStream c2pStreamFile =File.OpenRead(FilePathName))\n{\n    using (FileStream logStream = File.Open(TraceFilePathName,FileMode.Append))\n    {\n       c2pStreamFile.CopyTo(logStream);\n    }\n}	0
18252767	18252498	Check same elements in two lists	List<string> names = new List<string>(); // This will hold text for matched items found\nforeach (ListItem item in tempListName)\n{\n    foreach (string value in tempList)\n    {\n        if (value == item.Value)\n        {\n            names.Add(item.Text);\n        }\n    }\n}	0
25709009	25708960	Comparing user input	class Words\n{\n  public static bool WordCompare(char[] input, char[] output)\n    {\n        List<char> used = new List<char>();\n        bool flag = true;\n\n        if(input.Length!=output.Length) {return false;}\n\n        for(int i=0;i<input.Length;++i)\n        {\n                if (input[i]==output[i])\n                {\n                    used.Add(ch_in);\n                }\n               else\n                {\n                     flag = false;\n                     break;\n                }\n        }\n        return flag;\n    }	0
11887843	10982523	WPF modal window as tool window in WinForms disappears	// Use the interop helper for the specified wpf window hosted by the win32 owner\nWindowInteropHelper wih = new WindowInteropHelper(wpfForm);\nwih.Owner = this.someWin32FormsControl.Handle;	0
17933731	17933697	Checking if a DateTime is before DateTime.Now	if(dateAndTime1 < DateTime.Now)\n{\n  //do something\n}	0
16903810	16798407	Windows Structured Storage - 32-bit vs 64-bit COM Interop	[StructLayout(LayoutKind.Sequential)]\npublic struct PropertySpec\n{\n    public PropertySpecKind kind;\n    public PropertySpecData data;\n}	0
33298926	33292434	Count down from 60 seconds	public String s;\npublic float currentTime = 60f;\nprivate int barAmount;\n\nvoid Update () {\n    currentTime -= Time.deltaTime;\n\n   barAmount = (int) Mathf.Lerp(0f, 100f, currentTime);\n\n   // timeBar.valueCurrent = barAmount;\n\n\n    float cTime = currentTime;\n\n    TimeSpan timeSpan = TimeSpan.FromSeconds(cTime);\n\n    s =  string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}",timeSpan.Days ,timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);\n\n}	0
33209955	33209894	How to detect Enter with C#?	ConsoleKeyInfo cki = Console.ReadKey(true);\n\nswitch (cki.Key)\n{\n    case ConsoleKey.Enter:\n        Console.WriteLine("Enter key has been pressed");\n        break;\n    case ConsoleKey.Escape:\n        Console.WriteLine("Escape key has been pressed");\n        break;\n    default:\n        Console.WriteLine("Please press Enter or Esc");\n        break;\n}	0
20424041	20423997	How to use Group by of two elements in an object and get the count in List?	var groups = data.GroupBy(item => new { item.Class, item.Division });\n                 .Select(item => new StudentCount \n                                     { \n                                         Class = item.Key.Class, \n                                         Division = item.Key.Divison,\n                                         Count = item.Count()\n                                     });	0
4274733	4274553	InvalidOperationException thrown while trying to open new Window	Action action = () => {\n    SomeWindow window = new SomeWindow();\n    window.ShowDialog();\n};\nDispatcher.BeginInvoke(action);	0
12771229	12771101	Can ServiceStack.Text deserialize JSON to a custom generic type?	[Serializable]	0
4599318	4599259	reading text of a text box	private void Page_Load()\n{\n  if (!IsPostBack)\n  {\n     txt_Name.Text = "somestring";\n  }\n}	0
18576542	18576488	Get The number in a specific string	var input = "Schema.PCK.*14500*Name";\nRegex pattern = new Regex(@"Schema\.PCK\.([a-zA-Z]*)(?<num>\d+)");\nvar match = pattern.Match(input);\nstring num = match.Groups["num"].Value;	0
1504100	1503551	Regular expression to define format of backup filenames	Regex rgx = new Regex("\(\?\<Month\>.+?\)");\nrgx.Replace("^backup_(?<Month>\d{2})_(?<Year>\d{2})_(?<Username>\w+)\.(?<extension>bak)$"\n, DateTime.Now.Month.ToString());	0
19944496	19944120	64 Bit Access Database Jet Engine	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"	0
9528198	9527353	Showing Only Specified Property Based on Configuration	#If FrenchVersion Then\n   ' <code specific to the French language version>.\n#ElseIf GermanVersion Then\n   ' <code specific to the German language version>.\n#Else\n   ' <code specific to other versions>.\n#End If	0
3089861	3089546	Webpart accessing a large list of groups	public static bool GroupExists(SPGroupCollection groups, string name)\n{\n    if (string.IsNullOrEmpty(name) || (name.Length > 255) || (groups == null) || (groups.Count == 0))\n    {\n        return false;\n    }\n    else\n    {\n        return (groups.GetCollection(new String[] { name }).Count > 0);\n    }\n}	0
34508964	34502289	WPF how to access sibling from custom UserControl code	UserControl1.UserControl2 = UserControl2;\nUserControl2.UserControl1 = UserControl1;	0
33234850	33234699	How to change background colour of Main Camera in runtime setting RGBA values?	Camera.main.GetComponent<Camera>().backgroundColor = new Color(228f / 255f, 234f / 255f, 241f  / 255f, 0f);	0
4033332	4033250	C# XML conversion	XmlDocument doc = new XmlDocument();\ndoc.Load(... your string ...);\ndoc.Save(... your destination path...);	0
185716	185559	Remove domain information from login id in C#	using System;\nusing System.Text.RegularExpressions;\npublic class MyClass\n{\n    public static void Main()\n    {\n    string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None);\n    Console.WriteLine(domainUser);\n\n    }\n\n}	0
6753682	6753613	How to divide DATETIME column value into day, month and year in C#	DateTime dt = DateTime.Parse(x);\nint day = dt.Day;\nint month = dt.Month;\nint year = dt.Year;	0
3872118	3872104	How do I add attributes to properties generated by Linq2Sql in a different partial class	[MetadataType(typeof(MyClassMetadata)]\npublic partial class MyClass\n{\n    public class MyClassMetadata\n    {\n         [StringLength(30)]\n         public string FirstName {get;set;}\n\n         [StringLength(30)]\n         [Required]\n         public string LastName {get;set;}    \n    }\n}	0
4507614	4507602	How do I customize the namespace in code generated by protobuf-net	package My.Test {\n     enum TestEnum {\n        FIRST = 0;\n        SECOND = 1;\n        THIRD = 2;\n    }\n}	0
30131557	30131507	ITextSharp - Google Chrome Save Button Saves PDF as .ASPX page	Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.pdf");	0
26985531	26984428	How to replace a matched group value with Regex	var connectionString = @"data source=MY-PC\SQLEXPRESS;";\nvar pattern = @"(data source=)((\w|\-)+?\\\w+?)\;";\nvar newConnectionString = Regex.Replace(connectionString, pattern, "$1" + "something");\nConsole.WriteLine(newConnectionString);	0
23187599	23187572	Take screenshot from window content (without border)	public static Bitmap TakeDialogScreenshot(Form window)\n{\n   var b = new Bitmap(window.Width, window.Height);\n   window.DrawToBitmap(b, new Rectangle(0, 0, window.Width, window.Height));\n\n   Point p = window.PointToScreen(Point.Empty);\n\n   Bitmap target = new Bitmap( window.ClientSize.Width, window.ClientSize.Height);\n   using (Graphics g = Graphics.FromImage(target))\n   {\n     g.DrawImage(b, 0, 0,\n                 new Rectangle(p.X - window.Location.X, p.Y - window.Location.Y, \n                               target.Width, target.Height),  \n                GraphicsUnit.Pixel);\n   }\n   b.Dispose();\n   return target;\n}	0
4563640	4562683	Sharepoint Web Part validation set off by Publishing Controls	WebPartManager mgr = WebPartManager.GetCurrentWebPartManager(Page);\nif (mgr.DisplayMode.Equals(mgr.SupportedDisplayModes["Browse"]))\n{\n     messageRequiredValidator.Enabled = true;\n}\nelse\n{\n     messageRequiredValidator.Enabled = false;\n}	0
774628	774457	Combination Generator in Linq	public static IEnumerable<string> GetPermutations(string s)\n{\n    if (s.Length > 1)\n        return from ch in s\n               from permutation in GetPermutations(s.Remove(s.IndexOf(ch), 1))\n               select string.Format("{0}{1}", ch, permutation);\n\n    else\n        return new string[] { s };\n}	0
3310651	3310630	Generate a simple C# class from XML	xsd.exe /?	0
6078208	6078101	SortedSet add confusion	int GetFileContentNumber(string filename)\n{\n  using(var reader=new StreamReader(filename)\n  {\n    char[] chars=new char[6];\n    reader.Read(buf, 0, 6);\n    return int.Parse(new String(chars));\n\n  }\n}\n\nIEnumerable<string> files = System.IO.Directory.GetFiles(textBox1.Text)\n    .Select(filename=>new KeyValuePair<string,int>(filename, GetFileContentNumber(filename)))\n    .OrderBy(pair=>pair.Value)\n    .Select(pair=>pair.Key);	0
21668046	21667954	Calculator using an array	string str = yourTextBoxValue.Text;\nstring[] strs = str.Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries);\nint param1 = int.Parse(strs[0]);\nint param2 = int.Parse(strs[1]);\nint result = param1 + param2;\nyourLabel.Text = result.ToString();	0
13981508	13980864	How can I create a shelltoast?	private void ToastWrapWithImgAndTitleClick(object sender, RoutedEventArgs e)\n    {\n        var toast = GetToastWithImgAndTitle();\n        toast.TextWrapping = TextWrapping.Wrap;\n\n        toast.Show();\n    }\n\n    private static ToastPrompt GetToastWithImgAndTitle()\n    {\n        return new ToastPrompt\n        {\n            Title = "With Image",\n            TextOrientation = System.Windows.Controls.Orientation.Vertical,\n            Message = LongText,\n            ImageSource = new BitmapImage(new Uri("../../ApplicationIcon.png", UriKind.RelativeOrAbsolute))\n        };\n    }	0
4346874	4346855	ASP.NET how to set text on a master page?	(this.Master as SiteMaster).BodyTitle.Text = "Home";	0
34429937	34425908	C# How to get the length of chars in a string	string [] entries =  {"xyz 1","q 2","poiuy 4"};\nfor(int i=0;i<entries.Length;i++)\n{\n    var parts = entries[i].Split(' ');\n    var txtCount = parts[0].Length;\n    Console.WriteLine(String.Format("{0} {1}", txtCount, parts[1]));\n}	0
8660521	8660403	Problems with wrapping a C++ DLL from C#	extern "C"	0
8520949	8520879	Get the path of every explorer window with c#	SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();\n\nstring filename;\n\nforeach ( SHDocVw.InternetExplorer ie in shellWindows )\n{\n   filename = Path.GetFileNameWithoutExtension( ie.FullName ).ToLower();\n\n   if ( filename.Equals( "explorer" ) )\n   {\n      // Save the location off to your application\n      Console.WriteLine( "Explorer location : {0}", ie.LocationURL );\n\n      // Setup a trigger for when the user navigates\n      ie.NavigateComplete2 += new SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(handlerMethod);\n   }\n}	0
21201991	21153660	While loop balloontipclick as condition	bool for3 = false;\n                    for (; ; )\n                    {\n                        Norm.ShowBalloonTip(10000);\n                        System.Threading.Thread.Sleep(10000);\n                        Application.DoEvents();\n                        if (loopVariable)\n                            for3 = true;\n                        if (for3) break;\n                        System.Threading.Thread.Sleep(60000);\n\n                    }\nprivate static bool loopVariable = false;\n\n  void Norm_BalloonTipClicked(object sender, EventArgs e)\n   {\n       loopVariable = true;\n   }	0
3434445	3433620	Setting Binding Properties in a Template	public class TimeOfDayBinding\n    : MarkupExtension\n{\n    public PropertyPath Path { get; set; }\n\n    public override object ProvideValue(IServiceProvider serviceProvider)\n    {\n        var binding = new Binding()\n        {\n            Path = Path,\n            Converter = new TimeOfDayConverter(),\n        };\n        binding.ValidationRules.Add(new ValidateTimeOfDay()\n        {\n            ValidatesOnTargetUpdated = true,\n        });\n        return binding.ProvideValue(serviceProvider);\n    }\n}	0
2318087	2317889	Checkbox on Datagrid with auto-generated columns, how to pass check-state to source without row change?	dataGridView1.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange);	0
7962021	7961930	Plotting a point	Graphics g = this.CreateGraphics();\ng.DrawString("???", new Font("Calibri", 12), new SolidBrush(Color.HotPink), (PlotArea.X + (7 - xMin)* PlotArea.Width/(xMax - xMin)), (PlotArea.Bottom - (6 - yMin) * PlotArea.Height / (yMax - yMin)));\ng.Dispose();	0
827854	827547	Determine DDL value for dynamic column creation in oninit event	string value = Request["myDropDownID"];	0
10965830	10965829	How do I de/serialize JSON in WinRT?	using System.IO;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\n\npublic static T Deserialize<T>(string json)\n{\n    var _Bytes = Encoding.Unicode.GetBytes(json);\n    using (MemoryStream _Stream = new MemoryStream(_Bytes))\n    {\n        var _Serializer = new DataContractJsonSerializer(typeof(T));\n        return (T)_Serializer.ReadObject(_Stream);\n    }\n}\n\npublic static string Serialize(object instance)\n{\n    using (MemoryStream _Stream = new MemoryStream())\n    {\n        var _Serializer = new DataContractJsonSerializer(instance.GetType());\n        _Serializer.WriteObject(_Stream, instance);\n        _Stream.Position = 0;\n        using (StreamReader _Reader = new StreamReader(_Stream)) \n        { return _Reader.ReadToEnd(); }\n    }\n}	0
13507488	13507260	Regex to help me break up Telephone numbers?	^(00\d{2}|\+\d{2})?(0\d)?([\d ]+)(?:[xX](\d+))?	0
3359235	3359209	How to use Regex to split data together with extracting pattern value	Regex.Split(text, @"(\d{4}-\d{2}-\d{2})")	0
29575475	29575442	Generate an array in C# at the desired length, each element has desired initial value	var myArray = Enumerable.Range(0,5).Select(x => 15).ToArray();	0
2568628	2567170	Outlook 2007 Add In. adding menu every time i debug the application in VS2008	try\n    {\n        commandBar = Application.CommandBars["mytoolbar"];\n    }\n    catch (ArgumentException e)\n    {\n\n    }\n\n    if (commandBar == null)\n    {\n        commandBar = Application.CommandBars.Add("mytoolbar ", 1, missing, true);\n    }	0
4573075	4572798	How do I assign a SqlDbType.UniqueIdentifier to a string?	CommandSelect.Parameters["@UserProfileID"].Value = \n                                     new Guid(ship.GetUser().ProviderUserKey);	0
4555609	4555593	How to check for null in the operator== method?	(object)a == null	0
28369569	28369528	Access an Object in Another Class from an Interface?	public class Rack : IRack\n{\n   public void SwapAllTiles(IBag bag) { ...Now you can access it... }\n}	0
15179249	15179060	How to get HttpClient Json serializer to ignore null values	[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]	0
8704020	8689505	ILSpy, how to resolve dependencies?	var resolver = new DefaultAssemblyResolver();\nresolver.AddSearchDirectory("path/to/my/assemblies");\n\nvar parameters = new ReaderParameters\n{\n    AssemblyResolver = resolver,\n};\n\nvar assembly = AssemblyDefinition.ReadAssembly(pathToAssembly, parameters);	0
22603557	22223395	Equals sign magically appears in message sending to pager	MailMessage emailmsg = new MailMessage("from@address.co.za", "to@address.co.za")\nemailmsg.Subject = "Subject";\nemailmsg.IsBodyHtml = false;\nemailmsg.ReplyToList.Add("from@address.co.za");\nemailmsg.BodyEncoding = System.Text.Encoding.UTF8;\nemailmsg.HeadersEncoding = System.Text.Encoding.UTF8;\nemailmsg.SubjectEncoding = System.Text.Encoding.UTF8;\nemailmsg.Body = null;\n\nvar plainView = AlternateView.CreateAlternateViewFromString(EmailBody, emailmsg.BodyEncoding, "text/plain");\nplainView.TransferEncoding = TransferEncoding.SevenBit;\nemailmsg.AlternateViews.Add(plainView);\n\nSmtpClient sSmtp = new SmtpClient();\nsSmtp.Send(emailmsg);	0
29138732	29138288	Comparing two datatables in C# and finding new, matching and non-macting records	// Get matching rows from the two tables\nIEnumerable<DataRow> matchingRows = table1.AsEnumerable().Intersect(table2.AsEnumerable());\n\n// Get rows those are present in table2 but not in table1\nIEnumerable<DataRow> rowsNotInTableA = table2.AsEnumerable().Except(table1.AsEnumerable());	0
6652477	6652276	C# Using CodeDom to add variables as part of a class	CodeMemberField field = new CodeMemberField(typeof(byte[]), "bytes");\nfield.Attributes = MemberAttributes.Public;\n\nmainClass.Members.Add(field);	0
17750959	17734636	Moving data between interfaces without violating SOLID principles?	public class Cart\n{\n    private List<ICartItem> CartItems;\n\n    // ...Other Class Methods...\n\n    [HttpPost]\n    public void AddItem(int productVariantID)\n    {\n        var product = ProductService.GetByVariantID(productVariantID);\n\n        if (product != null)\n        {\n            CartItems.Add(CartItemConverter.Convert(product));\n            CartService.AddItem(productVariantID);\n        }\n    }\n\n    [HttpPost]\n    public void RemoveItem(int productVariantID)\n    {\n        CartItems.RemoveAll(c => c.VariantID == productVariantID);\n        CartService.RemoveItem(productVariantID);\n    }\n\n    public IEnumerable<ICartItem> GetCartItems()\n    {\n        return CartItems;\n    }\n\n    // ...Other Class Methods...\n}	0
14558914	14395853	Google documents. I need to edit a document with public link c#	// Public Link contains the resourceID\n// example:  https://docs.google.com/file/d/097iZigwrANhGTElvZDdCVmlZNzQ/edit\n// resourceID:  097iZigwrANhGTElvZDdCVmlZNzQ\n// Get Your Document Entry\n\nstring editUri = "http://docs.google.com/feeds/documents/private/full/%3A" + resourceID;\nDocumentEntry docEntry = (DocumentEntry)service.Get(editUri);	0
10242829	10242061	c# Best Method to create a log file	private static readonly object Locker = new object();\n    private static XmlDocument _doc = new XmlDocument();\n    static void Main(string[] args)\n    {\n        if (File.Exists("logs.txt"))\n            _doc.Load("logs.txt");\n        else\n        {\n            var root = _doc.CreateElement("hosts");\n            _doc.AppendChild(root);\n        }\n        for (int i = 0; i < 100; i++)\n        {\n            new Thread(new ThreadStart(DoSomeWork)).Start();\n        }\n    }\n    static void DoSomeWork()\n    {\n        /*\n\n         * Here you will build log messages\n\n         */\n        Log("192.168.1.15", "alive");\n    }\n    static void Log(string hostname, string state)\n    {\n        lock (Locker)\n        {\n            var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("host"));\n            el.SetAttribute("Hostname", hostname);\n            el.AppendChild(_doc.CreateElement("State")).InnerText = state;\n            _doc.Save("logs.txt");\n        }\n    }	0
31195626	31194421	How to bold certain parts of a UITextView	var bold = new UIStringAttributes {\n    Font = UIFont.FromName("Helvetica-Bold", 20f)\n};\n\nvar email = new NSMutableAttributedString ("E-mail: jon.smith@test.com");\nemail.SetAttributes (bold.Dictionary, new NSRange (0, 6));\n\ncustomLabel.AttributedText = email;	0
21138403	21138175	What is the event that occurs when a user clicks an icon of application running on taskbar?	public Form1()\n{\n     InitializeComponent();\n     this.Activated += Form1_Activated;\n}\n\nprivate void Form1_Activated(object sender, EventArgs e)\n{\n   if (this.WindowState == FormWindowState.Minimized)\n   {\n      //TODO: take required action here\n   }\n}	0
33178701	33178145	Implementing empty value check in for each loop for Excel column	if (Methods.toString(row["DATEOFHIRE"]) == "")\n                                {\n                                    lblMsg.Visible = true;\n                                    lblMsg.Text = "Hire date is not presnt";\n                                    lblMsg.ForeColor = System.Drawing.Color.Red;\n                                    return false;\n                                }	0
6148321	6148226	How to count number of Excel files from a folder using c#?	var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\n{\n    ".xls",\n    ".xlsx",\n    ".pdf",\n};\nvar baseDir = @"D:\";\nvar count = Directory.EnumerateFiles(baseDir)\n                     .Count(filename =>\n                                extensions.Contains(Path.GetExtension(filename)));	0
30179486	30179212	How to reference chart ID that is stored in string?	(this.FindControl(chartName) as Chart).Series	0
6571969	6571497	How can i see the text presented in the File using Print Preview	public Form1()\n{\n  InitializeComponent();\n  printDocument1.PrintPage += new PrintPageEventHandler(this.printDocument1_PrintPage);\n}	0
20723871	20723863	How to get the xml node inside another node having attribute	XmlDocument xDoc = new XmlDocument();\n        xDoc.Load("myxml.xml");\n        //XmlNode node = xDoc.SelectSingleNode("//pages/page[@id='1'])");\n        XmlNode node1 = (xDoc.SelectSingleNode("//pages/page[@id='1']/field/addedbox/label"));	0
21750410	20999236	do programmatically "Set scale to default"	void ZoomReset()\n    {\n        GetActiveZgc().IsEnableHPan = false;\n        GetActiveZgc().IsEnableHZoom = false;\n\n        for (int i = GetActiveZgc().GraphPane.ZoomStack.Count * 2; i >= 0; i--)\n        {\n            GetActiveZgc().ZoomOut(GetActiveZgc().GraphPane);   \n        }\n\n        GetActiveZgc().GraphPane.XAxis.Scale.Min = 0;\n        GetActiveZgc().GraphPane.YAxis.Scale.Min = 0;\n\n        GetActiveZgc().IsEnableHPan = true;\n        GetActiveZgc().IsEnableHZoom = true;\n\n    }	0
316583	316582	How do you wait for input on the same Console.WriteLine() line?	Console.Write("What is your name? ");\nvar name = Console.ReadLine();	0
1554270	1554233	Finding all methods with missing security check	public class MyService\n{\n    // The method must be virtual.\n    public virtual DoSomethingWhichRequiresAuthorization()\n    {\n    }\n}\n\npublic static class MyServiceFactory\n{\n    private static ProxyGenerator _generator;\n    private static ProxyGenerator Generator\n    {\n        get\n        {\n            if (_generator == null) _generator = new ProxyGenerator();\n            return _generator;\n        }\n    }\n\n    public static MyService Create()\n    {\n        var interceptor = new AuthorizationInterceptor();\n\n        return (MyService)Generator.CreateClassProxy(\n            typeof(MyService), new[] { interceptor });\n    }\n}\n\npublic class AuthorizationInterceptor : IInterceptor\n{\n    public void Intercept(IInvocation invocation)\n    {\n        // invocation.Method contains the MethodInfo\n        // of the actually called method.\n        AuthorizeMethod(invocation.Method);\n    }\n}	0
1830320	1828133	How can i be notified of a right click event of a Listbox in C#	private void listBox1_MouseRightButtonUp(object sender, MouseButtonEventArgs e)\n{\n    object item = GetElementFromPoint(listBox1, e.GetPosition(listBox1));\n    if (item!=null)\n        Console.WriteLine(item);\n    else\n        Console.WriteLine("no item found");\n}\n\nprivate object GetElementFromPoint(ItemsControl itemsControl, Point point)\n{\n    // you can use either VisualTreeHelper.HitTest or itemsControl.InputHitTest method here; both of them would work\n    //UIElement element = VisualTreeHelper.HitTest(itemsControl, point).VisualHit as UIElement;\n    UIElement element = itemsControl.InputHitTest(point) as UIElement;\n    while (element!=null)\n    {\n        if (element == itemsControl)\n            return null;\n        object item = itemsControl.ItemContainerGenerator.ItemFromContainer(element);\n        if (!item.Equals(DependencyProperty.UnsetValue))\n            return item;\n        element = (UIElement)VisualTreeHelper.GetParent(element);\n    }\n    return null;\n}	0
13022773	12968169	Format cell in an excel sheet using interop	Excel.Worksheet oSheet;\nExcel.Range oRange;\noRange = oSheet.get_Range("Q3", "Q40");	0
15149258	15149235	Background Worker How To	(sender as BackgroundWorker).ReportProgress(50);	0
10214726	10214391	Is it ever appropriate to parse XML with Regular expressions?	Regex regEx = new Regex("Weird-Elt_.*", RegexOptions.Compiled);\n\nXDocument doc = XDocument.Parse(xml1);\nvar x1 = from e in doc.Descendants("Parent").Descendants()\n         where regEx.IsMatch(e.Name.LocalName)\n        select e;	0
23317305	23316950	C# How can I make a loop which changes 3 labels	Dictionary<int, string> daysDictionary = new Dictionary<int, string>()\n                                                {\n                                                   {1, "poniedzia?ek"},\n                                                   {2, "wtorek"},\n                                                   {3, "?roda"},\n                                                   {4, "czwartek"},\n                                                   {5, "pi?tek"},\n                                                   {6, "sobota"},\n                                                   {7, "niedziela"}\n                                                };\n     return daysDictionary[zmienna];	0
14494167	14493939	C# windows forms application:How can I replace a single line in a textfile without deleting the original file?	StringBuilder newFile = new StringBuilder();\nstring temp = "";\nstring[] file = File.ReadAllLines(@"txtfile");\n\nforeach (string line in file)\n{\n    if (line.Contains("string you want to replace"))\n    {\n        temp = line.Replace("string you want to replace", "New String");\n        newFile.Append(temp + "\r\n");\n        continue;\n    }\n    newFile.Append(line + "\r\n");\n}\n\nFile.WriteAllText(@"txtfile", newFile.ToString());	0
23267146	23267048	Write every value inside a char list	Console.Write("Gissade Bokst?ver:");\n\nforeach(var item in lista_f_gissning)\n{\n   string s = item.ToString();\n   Console.Write("{0} ", s);\n}	0
17979127	17978916	Minimum groups of contiguous sequences	var outputRanges = new List<Range>();\nforeach (var range in inputRanges)\n{\n   // Let Range.Touches(Range) define a function that returns true\n   // iff the two ranges overlap at all (that is, A.Start and/or A.End\n   // is between B.Start and B.End)\n   var overlaps = outputRanges.Where(range.Touches).ToList();\n\n   // If there are no overlaps, then simply add it to the output\n   if (!overlaps.Any())\n   {\n       outputRanges.Add(range);\n   }\n   // If there are overlaps, merge them\n   else\n   {\n       outputRanges.RemoveAll(overlaps);\n       overlaps.Add(range);\n       outputRange.Add(new Range() {\n           Start = overlaps.Min(_=>_.Start),\n           End = overlaps.Max(_=>_.End)\n       });\n   }\n}	0
22057786	22049141	Remote Desktop ActiveX control	protected void CreateRdpActiveX()\n{\n    try\n    {\n        string clsid=GetRdpActiveXClsIdByOSVersion();\n        Type type = Type.GetTypeFromCLSID(clsid, true);\n        this.axRdp = new AxHost (type.GUID.ToString());\n        ((ISupportInitialize)(axRdp)).BeginInit();\n        SuspendLayout();\n        this.panel1.Controls.Add(axRdp);     \n        ((ISupportInitialize)(axRdp)).EndInit();\n        ResumeLayout(false);\n        var msRdpClient8 = axRdp.GetOcx() as IMsRdpClient8;\n        if(msRdpClient8!=null)\n        {\n             var advancedSettings9 =msRdpClient8.AdvancedSettings9 as IMsRdpClientAdvancedSettings8;\n             if(advancedSettings9!=null) \n                 advancedSettings9.BandwidthDetection=true;\n\n        }\n    }\n    catch (System.Exception ex)\n    {\n        System.Console.WriteLine(ex.Message);\n    }\n}	0
12047628	12047616	Passing Parameters from one XAML page to another	Application.Current.Properties["youvalueindex"];	0
22960172	22960080	creating a C# dll in visual studio	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nusing System.Net;\nusing System.Net.Sockets;\n\n namespace ClassLibrary2\n {\n    public class take_off\n    {\n        public void testfunction()\n        {\n            UdpClient udpClient = new UdpClient(5556);\n            IPAddress ipAddress = IPAddress.Parse("192.168.1.1");\n            IPEndPoint sending_end_point = new IPEndPoint(ipAddress, 5556);\n            int seq = 0;\n\n            for(int i=0; i<30; i++) \n            {    \n                seq = seq + 1;\n                System.Console.WriteLine("send landing command");\n                string buff1= String.Format("AT*REF={0},290717696\r",seq);\n                byte[] bytesToSend = Encoding.ASCII.GetBytes(buff1);\n                udpClient.Send(bytesToSend,bytesToSend.Length,sending_end_point);\n            }\n        }\n    }\n}	0
7892993	7892969	How do I override a method in WCF Resfull service?	[OperationContract(Name = "GetDataWithNumber")]\npublic User GetNameFromId(int id)\n\n[OperationContract(Name = "GetDataWithString")]\npublic User GetNameFromEmail(string email)	0
14334310	14333358	Edit Row In the Second Page of Gridview	gridview.EditIndex = iActiveIndex % gridview.PageSize;	0
31128485	31128408	Add row to HTML <Select> at Run-time in ASP.Net	var o = lanHtml as System.Web.UI.HtmlControls.HtmlSelect;\n\nif(o!=null)\n{\n    o.Items.Add(new ListItem("English", "En"));\n}	0
25443738	25443580	How to exclude a statement from first iteration of a loop in c#?	bool flag=false;\nfor(int z=0;z<TestCases.Count;z++)\n{\n   if(z!=0)\n    flag=true;\n\n   if(flag)\n      RunthisFunction();\n}	0
28583999	28583956	Open an Word Document	object oMissing = System.Reflection.Missing.Value;\n\nDocument doc = word.Documents.Open(filename, ref oMissing,\n        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,\n        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,\n        ref oMissing, ref oMissing, ref oMissing, ref oMissing);	0
7729493	7729423	Is it possible to create a C# 'pointer' to a DateTime object?	Wrapper w1 = new Wrapper { TheDate = DateTime.Now };\nWrapper w2 = new Wrapper { TheDate = DateTime.Now.AddYears(10) };\n\nWrapper w;\nif (something)\n{\n    w = w1;\n}\nelse\n{\n    w = w2;\n}\n\nw.DoSomething();\n\nclass Wrapper\n{\n    public DateTime TheDate { get; set; }\n    public void DoSomething()\n    {\n    }\n}	0
30478830	30478701	FIND A SPECIFIC FILE IN A FOLDER "C:\TEST" THAT CONTAINS MULTIPLE ARCHIVES ".ZIP" USING C#	foreach(var zipPath in Directory.GetFiles("C:\\Test"))\n{\n    using (ZipArchive archive = ZipFile.OpenRead(zipPath))\n    {\n        foreach (ZipArchiveEntry entry in archive.Entries)\n        {\n            var position = entry.Name.IndexOf(filetosearch , StringComparison.InvariantCultureIgnoreCase);\n            if (position > -1)\n            {\n                listView1.Items.Add(entry.Name);\n            }\n        }\n    }\n}	0
10902621	10902620	How to search for a phrase in a RichTextBox and highlight every instance of that phrase with a color you specify	String richText = richTextBox1.Text;\nString ValToSearchFor = "duckbilledPlatypus";\nint pos = 0;\npos = richText.IndexOf(ValToSearchFor, 0);\nwhile (pos != -1) {\n    richTextBox1.Select(pos, ValToSearchFor.Length);\n    richTextBox1.SelectionColor = Color.Red;\n    pos = richText.IndexOf(ValToSearchFor, pos + 1);\n}	0
21052734	21034898	Creating a black filter for a custom ShaderEffect	sampler2D input : register(s0);\nfloat threshold : register(c0);\nfloat4 blankColor : register(c1);\n\nfloat4 main(float2 uv : TEXCOORD) : COLOR\n{\n    float4 color = tex2D(input, uv);\n    float intensity = (color.r + color.g + color.b) / 3;\n\n    float4 result;\n    if (intensity < threshold)\n    {\n        result = blankColor;\n    }\n    else\n    {\n        result = color;\n    }\n\n    return result;\n}	0
7173809	7173677	c# how to convert float to int	using System;\nusing System.IO;\n\nnamespace Stream\n{\n  class Program\n  {\n    static void Main (string [] args)\n    {\n      float\n        f = 1;\n\n      int\n        i;\n\n      MemoryStream\n        s = new MemoryStream ();\n\n      BinaryWriter\n        w = new BinaryWriter (s);\n\n      w.Write (f);\n\n      s.Position = 0;\n\n      BinaryReader\n        r = new BinaryReader (s);\n\n      i = r.ReadInt32 ();\n\n      s.Close ();\n\n      Console.WriteLine ("Float " + f + " = int " + i);\n    }\n  }\n}	0
28379414	28379058	How do I call a public void in c#	public class blahblah\n{\n\n    int x, y = 2;   // this sets y as 2, but x is not set \n\n    public void count()\n    {\n        Console.WriteLine("Hi: " + y);\n    }\n    public void counting()\n    {\n        int z =  x * y;\n        Console.WriteLine("Z = {0}", z);\n\n    }\n\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        blahblah b = new blahblah(); //instantiate the object\n        b.count();  //call a method on the object\n        b.counting();\n\n        Console.ReadKey();\n    }\n\n}    \n\n// output:\n// Hi: 2\n// z = 0	0
28691842	28690337	Retrieving value from Datepicker to notifications	DateTime SelectedDate = MyDatePicker.Date.Date;	0
9326824	9326510	Substitute leading spaces and terminate matching before particular character	String s = "    <span> code <span> code <span/> code </span>";\nConsole.WriteLine(Regex.Replace(s, @"(?<=^\s*)\s", "&nbsp;"));	0
18004302	18004278	C#--How do I use a Null Coalescing operator to allow use of an extension method that won't accept null parameters?	item.DueDate == null ? null : item.DueDate.Value.ToUniversalTime().ToString("o")	0
14351698	14242675	Outlook Add-in: Fetch attendees email address of selected meeting	// Recipients are not zero indexed, start with one\n\nfor (int i = 1; i < appointment.Recipients.Count - 1; i++)\n{\n    string email = GetEmailAddressOfAttendee(appointment.Recipients[i]);\n}\n\n\n// Returns the SMTP email address of an attendee. NULL if not found.\nfunction GetEmailAddressOfAttendee(Recipient TheRecipient)\n{\n\n    // See http://msdn.microsoft.com/en-us/library/cc513843%28v=office.12%29.aspx#AddressBooksAndRecipients_TheRecipientsCollection\n    // for more info\n\n    string PROPERTY_TAG_SMTP_ADDRESS = @"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";\n\n    if (TheRecipient.Type == (int)Outlook.OlMailRecipientType.olTo)\n    {\n        PropertyAccessor pa = TheRecipient.PropertyAccessor;\n        return pa.GetProperty(PROPERTY_TAG_SMTP_ADDRESS);\n    }\n    return null;\n}	0
31340665	31340545	how to pass a form as a parameter?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.Name = "form";\n\n        Form f = this;\n\n        doSomethingWithForm(f);\n    }\n\n    private void doSomethingWithForm(Form f)\n    {\n        Console.WriteLine(f.Name);\n    }\n}	0
33065947	33065903	C#: How to convert List<x> to Dictionary <string, x> where x is an object and key of dictionary is a string inside of x	List<Student> students = ...;\nvar dict = students.ToLookup(o => o.Group);\nvar group1 = dict["group1"];	0
21938396	21937963	Read non regular time format from excel in C#	string s = "29-Aug-01 11.23.00.000000000 AM";\n\nDateTimeOffset myDate = DateTimeOffset.ParseExact(\n    s,\n    "dd-MMM-yy hh.mm.ss.fffffff00 tt",\n    System.Globalization.CultureInfo.InvariantCulture);	0
23033203	23033108	Grouping in a generic list	var QueryResult = (from x in lstReport\n                        group x by x.ID into res\n                        select new Test\n                        {\n                            ID = res.Key,\n                            Category = res.Count() > 1 ? "Grouped" : res.First().Category,\n                            Approver = res.First().Approver\n                        }).ToList();	0
5872576	1306006	How to add data attributes to html element in ASP.NET MVC?	new { data_myid = m.ID }	0
278840	278761	Is there a .NET Framework method for converting file URIs to paths with drive letters?	private static string ConvertUriToPath(string fileName)\n{\n   Uri uri = new Uri(fileName);\n   return uri.LocalPath;\n\n   // Some people have indicated that uri.LocalPath doesn't \n   // always return the corret path. If that's the case, use\n   // the following line:\n   // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);\n}	0
23693455	23693399	Sending mail using default sender address	protected void Page_Load(object sender, EventArgs e)\n{\n    lblFrom.Text = "youremail@gmail.com";\n}	0
19796144	19795938	HttpWebClient getting hidden field data from web page	using(var wc=new WebClient())\n{\n    var dom = wc.DownloadString(someUrl);\n    var htmlDoc = new HtmlDocument();\n    htmlDoc.LoadHtml(dom);\n    var reqVerTokenElement = htmlDoc\n                        .DocumentNode\n                        .Descendants("input")\n                        .Where(n => n.Attributes["name"]!=null \n                                    && n.Attributes["name"].Value\n                                        =="__RequestVerificationToken")\n                        .FirstOrDefault();\n    if(reqVerTokenElement!=null)\n    {\n        var tokenValue = reqVerTokenElement.Attributes["value"].Value;\n    }\n}	0
22740638	22740123	Deleting a row in grid view,in which data and column names are given from code behind	protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n    if (e.CommandName == "Delete")\n    {\n        int Prod_Id = Convert.ToInt32(e.CommandArgument);        \n\n        DataTable dtToGrid = (DataTable)Session["dtToGrid"];\n\n        DataRow rowToBeDeleted = dtToGrid.Rows.Where(r=>r["Prod_Id"] == Prod_Id.ToString());\n\n        if (rowToBeDeleted != null)\n        {\n          dtToGrid.Rows.Remove(rowToBeDeleted);\n\n          grd.DataSource = dtToGrid;\n          grd.DataBind();\n\n          // do your summation logic.\n        }\n    }\n}	0
6272304	6272290	Reading exactly one row from Linq-to-SQL	return context.MyProcName(myParameter).Single().THeColumnINeed;	0
9704784	9704707	install clickonce application on the same machine, under different logins	app.exe.config	0
30154860	30152510	Passing an enum as an annotation parameter and getting list of items	var enumList = Enum.GetValues(attribute.EnumType).Cast<Enum>().Select(x => new SelectListItem(){\n                    Text = x.ToString(),\n                    Value = Convert.ToInt32(x).ToString()\n                });	0
21756060	21755094	How to get all entity's fields CRM 2011?	QueryExpression query = new QueryExpression("contact");\nquery.ColumnSet.AddColumns("firstname", "lastname");\nquery.Criteria.AddFilter(filter1);	0
18721326	18720602	Press button on webbrowser	private void button1_Click(object sender, EventArgs e)\n{\n    bool found = true;\n    while (found)\n    {\n        if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)\n        {\n            found = ClickLoadMoreButton();\n            Application.DoEvents();\n        }\n    }\n}\n\nprivate bool ClickLoadMoreButton()\n{\n    var buttons = webBrowser1.Document.GetElementsByTagName("button");\n    foreach (HtmlElement el in buttons)\n    {\n        var firstChild = el.FirstChild;\n        if (firstChild != null)\n        {\n            if (!string.IsNullOrEmpty(firstChild.InnerText))\n            {\n                if (firstChild.InnerText.ToLower().Replace(" ", string.Empty).Equals("loadmore"))\n                {\n                    el.InvokeMember("click");\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}	0
17045490	17042388	Extract a new object by matching a common property between an IQueryable<T> and a Dictionary<String, String>	combinedCol = (from mapCol in DirectoryMappingsCollection.ToList()\n               join propCol in DirectoryProfilePropertiesCollection\n               on mapCol.DirectoryAttribute equals propCol.Key\n               select new CombinedMappingDataCollection\n               {\n                   DetailName = mapCol.DetailRequirement.DetailName,\n                   AttributeName = propCol.Key,\n                   AttributeValue = propCol.Value\n               }).ToList();	0
28618725	28467645	Resize PNG image without losing color data from fully transparent pixels	using ImageMagick;\n\nusing (var sourceImage = new MagickImage(texture)){ //texture is of type Stream\n    sourceImage.Resize(desiredWidth, desiredHeight);\n    sourceImage.Write(memoryStream, MagickFormat.Png);\n}\n// use memoryStream here	0
11269582	11133084	Unable to get free disk space from Metro-style app	[DllImport("kernel32.dll", SetLastError = true)]\nstatic extern bool GetDiskFreeSpaceEx(\n    string lpDirectoryName,\n    out ulong lpFreeBytesAvailable,\n    out ulong lpTotalNumberOfBytes,\n    out ulong lpTotalNumberOfFreeBytes);\n\nstatic void TestDiskSpace()\n{\n    IStorageFolder appFolder = ApplicationData.Current.LocalFolder;\n    ulong a, b, c;\n    if(GetDiskFreeSpaceEx(appFolder.Path, out a, out b, out c))\n        Debug.WriteLine(string.Format("{0} bytes free", a));\n}	0
1937269	1936798	ListView Headers Don't Show Up	listView1.View = View.Details;	0
12745456	12744803	EXT JS change row column	.master-row .x-grid-cell {background: red; color:Green}	0
6956732	6956707	How to use ScriptManager in class file?	ScriptManager.RegisterClientScriptBlock(\n            this,\n            typeof(Page),\n            "TScript",\n            script,\n            true);	0
31807968	31699374	How can I embed a string resource and retrieve it after compiling with CodeDom?	StreamReader stream = new StreamReader(resourceAssembly.GetManifestResourceStream(""Resources.resx""))	0
25707406	25707389	How to use the return value from a method	bool returnedValue =  endwall(controlPlayer, controlEndblock);   \nif(returnedValue)\n{\n    //code if returns true\n}\nelse\n{\n    //code if returns false\n}	0
2867140	2866018	How to store integer in config file but retrieve it as an enumeration?	protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)\n{\n Level = (ProductLevel) int.Parse(reader.GetAttribute("level"));\n}	0
8475385	8475187	Detecting PS/2 port state in C#	ConnectionOptions opts = new ConnectionOptions();\nManagementScope scope = new ManagementScope(@"\\.\root\cimv2", opts);\nstring query = "select * from Win32_Keyboard";\nSystem.Management.ObjectQuery oQuery = new ObjectQuery(query);\nManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, oQuery);\nManagementObjectCollection recordSet = searcher.Get();\nforeach (ManagementObject record in recordSet)\n{\n    Console.WriteLine("" + record.Properties["Description"].Value);\n    Console.WriteLine("" + record.Properties["Layout"].Value);\n    Console.WriteLine("" + record.Properties["DeviceID"].Value);\n    Console.WriteLine("" + record.Properties["PNPDeviceID"].Value);\n    Console.WriteLine("" + record.Properties["Status"].Value + "\n");\n}	0
22977164	22976963	Using method add all numbers of the array	int[,] A = new int[3, 4] \n{ \n    { 4, -5, 12, -2},\n    { -9, 15, 19, 6},\n    { 18, -33, -1, 7}\n};\n  private void TotArray(int[,] array) \n  {\n      int sum = 0;\n      int rows = array.GetLength(0);\n      int cols = array.GetLength(1);\n      for (int i = 0; i < rows; i++)\n      {\n          for (int j = 0; j < cols; j++)\n          {\n              sum += A[i, j];\n          }\n      }\n      MessageBox.Show("The sum of the array is " + sum.ToString() + "."); //Show the sum\n   }\nprivate void button1_Click(object sender, EventArgs e)\n{\n    TotArray(A);\n}	0
9698079	9698020	All ComboBoxItem ValueMembers are last item from DataReader	string qr1 = "select * from categorymaster";\n        SqlCommand cmd1 = new SqlCommand(qr1, con);\n        con.Open();\n        SqlDataReader dr1 = cmd1.ExecuteReader();\n        cmbcat.Items.Clear();\n        while (dr1.Read())\n        {\n            cmbcat.Items.Add(new Item(dr1[1].ToString(), dr1[0].ToString()));\n\n        }\n        con.Close();	0
15901484	15901422	Determine if two collections share at least one element	var listA = new List<int>();\nvar listB = new List<int>();\n\nbool hasCommonItem = listA.Any(i => listB.Contains(i));	0
11820640	11816308	Multiple windows application's bug in Mono	Application.Run()	0
31828911	26323702	REST WCF - stream download is VERY slow with 65535 (64KB) chunks that cant be changed	return BaseStream.Read(buffer, offset, Math.Min(count, maxSocketRead));	0
8372820	8372499	Display View in folder without Controller or Action in ASP.net MVC	protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {\n\n   if (controllerType == null)\n      return new DumbController();\n\n   return base.GetControllerInstance(requestContext, controllerType);\n}\n\nclass DumbController : Controller {\n\n   protected override void HandleUnknownAction(string actionName) {\n\n      try {\n         View(actionName).ExecuteResult(this.ControllerContext);\n      } catch (Exception ex) {\n         throw new HttpException(404, "Not Found", ex);\n      }\n   }\n}	0
1110781	1110724	Determine Final Destination of a Shortened URL	private static string GetRealUrl(string url)\n{\n    WebRequest request = WebRequest.Create(url);\n    request.Method = WebRequestMethods.Http.Head;\n    WebResponse response = request.GetResponse();\n    return response.ResponseUri.ToString();\n}	0
13369419	13225536	How do I pass an array as a method result to Microsoft NAV?	DotNetArray.ClearArray;\n\nREPEAT        \n   DotNetArray.Add(Customer.Name);        \nUNTIL \n\nDotNetArray.EndOfArray;	0
10729141	10728774	How to create a dbcontext query that returns the relational database structure in json	public JsonResult MvrSummary(int MvrId)\n        {\n       MedicalVarianceEntities DbCtx = new MedicalVarianceEntities();\n            var data = from entity in DbCtx.Mvrs\n                          select new\n                          {\n                              Prop1 = entity.PKMvrId,\n\n                              ChildProp = entity.MvrEmployees.Select(x=>x.ODSEmpNumber),\n                              GrandChildProp = entity.MvrEmployees.Select(x=>x.MvrEmployeesStorageErrors.Select(y=>y.MvrEmployeesStorageErrorsId))\n                          };\n return Json(data, JsonRequestBehavior.AllowGet);\n}	0
12724144	12724003	Custom button that inherits from button in xaml has does not exist in namespace error	xmlns:local="clr-namespace:myResources;assembly=myResources"	0
14562093	14562000	Creating a DateTime from a string	DateTime dateTime = DateTime.Today + TimeSpan.Parse(myTime);	0
12723668	12723577	Inserting spaces between cells	label.Padding = new Padding(10);\nlabel.Padding = new Padding(left:10, top:10, right:10, bottom:10);\nlabel.Padding.Left = 10;	0
9161989	8883079	Getting Intellisense on the interface that a method implements if that method does not have its own XML comments	internal interface ISomeInterface  \n{\n  /// <summary>\n  /// Integer1 help text by interface.\n  /// </summary>\n  int Integer1 { get; set; }\n}\n\ninternal class Class2 : ISomeInterface\n{\n  public int Integer1 { get; set; }\n\n  public int CallInterface1( )\n  {\n    return Integer1; // <- Place cursor on Integer1 and press Ctrl+Shift+F1\n  }\n}	0
18264359	18264349	Iterating the assignment of a variable's name	for(int i = 0; i <= 10; i++){\n    new Thread(run);\n}	0
899374	899350	How to copy the contents of a String to the clipboard in C#?	System.Windows.Forms.Clipboard.SetText(...)	0
26651251	26621194	awesomium web scraping certain parts	string html = webControl2.ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML");\nvar htmlDoc = new HtmlAgilityPack.HtmlDocument();\nhtmlDoc.LoadHtml(html);\n\nvar playerIds = new List<string>();\n\nvar playerNodes = htmlDoc.DocumentNode.SelectNodes("//a[contains(@href, '/link/profile-view.jsp?user=')]");\n\nif (playerNodes != null)\n{\n    foreach (var playerNode in playerNodes)\n    {\n        string href = playerNode.Attributes["href"].Value;\n\n        var parts = href.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);\n        if (parts.Length > 1)\n        {\n            playerIds.Add(parts[1]);\n        }\n    }\n\n    id.DataSource = playerIds;\n}	0
6106081	6105738	Trouble with PredicateBuilder	test = invertedIndex.Where(predicate.Compile());	0
4148347	4147211	Using reflection to call a DLL but another DLL required is throwing an exception	string oldPath = Environment.CurrentDirectory;\nEnvironment.CurrentDirectory = @"G:\Remote\Debug";\nAssembly loadedDLL = Assembly.LoadFrom(...);\nEnvironment.CurrentDirectory = oldPath;\n// etc..	0
9358458	9358151	How to get a link's title and href value separately with html agility pack?	string name= namenode.Element("a").Element("b").InnerText;\n    string url= linknode.Element("a").GetAttributeValue("href","unknown");	0
5396786	5396746	C# lambda expressions as function arguments	public static U[] MakeArray<T, U>(this IEnumerable<T> @enum, Func<T, U> rule)\n{\n    return @enum.Select(rule).ToArray();\n}	0
6697018	6696909	LINQ filter by type on list from dictionary value	IEnumberable<MySubType> query = dataItemMap[identCode].OfType<MySubType>();	0
6339924	6339826	Looking for the simplest way to extract tow strings from another in C#	string a = "11. Test string. With dots.";\nvar res = a.Split(new[] {". "}, 2, StringSplitOptions.None);\nstring number = res[0];\nstring val = res[1];	0
24115081	24099953	Saving highscores on Windows Store app?	public class LocalSettingsHelper\n{\n    public static void Save<T>(string key, T value)\n    {\n        ApplicationData.Current.LocalSettings.Values[key] = value;\n    }\n\n    public static T Read<T>(string key)\n    {\n        if (ApplicationData.Current.LocalSettings.Values.ContainsKey(key))\n        {\n            return (T)ApplicationData.Current.LocalSettings.Values[key];\n        }\n        else\n        {\n            return default(T);\n        }\n    }\n\n    public static bool Remove(string key)\n    {\n        return ApplicationData.Current.LocalSettings.Values.Remove(key);\n    }\n}	0
15655684	15655643	Set values with conditions LINQ	var result = from a in tableA\n             join b in tableB on a.Key = b.ForeignKey\n             select new \n             {\n                 Value = a.value * b.coef\n             };	0
17999350	17998443	C# algorithm refactor splitting an array into 3 parts?	int cols = 3;\nIEnumerable<JToken> colItems[3]; // you can make this dynamic of course\n\nint rem = numItems % cols;\nint len = numItems / cols;\n\nfor (int col=0; col<cols; col++){\n    int colTake = len;\n    if (col < rem) colTake++;\n    colItems[col] = items.Skip(col*len).Take(colTake);\n}	0
17366094	17366045	Must declare the scalar variable ?@Login?. Error when trying to add parameter to SqlDataSource	using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["intranetv2"].ConnectionString))\n{\n\n    SqlCommand cmd = new SqlCommand("insert into [MyBase].[Dbo].[LogErrors] (Username, StackTrace, ShortDescription, DetailDescription, ErrorType) VALUES (@Login, @Stack, @Message, @Txt, @Source)", conn);\n\n                SqlParameter param = new SqlParameter();\n                param.ParameterName = "@Login";\n                param.Value = user.Login;\n                cmd.Parameters.Add(param);\n\n                SqlParameter param2 = new SqlParameter();\n                param2.ParameterName = "@Stack";\n                param2.Value = ex.StackTrace;\n                cmd.Parameters.Add(param2);\n    (...)	0
17641755	17641669	Splitting a string containing both characters and numbers on the basis of space	using (StringReader tr = new StringReader(Mystring)) {\n  string Line;\n  while ((Line = tr.ReadLine()) != null) {\n    if (Line.Length > 0) {\n      string[] temp = Line.Split(' ');\n      listview1.Items.Add(new ListViewItem(temp[1], temp[3]));\n    }\n  }\n}	0
4877120	4877079	How Upload File To Buffer in ASP.NET	public static byte[] ReadFile(string filePath)\n{\n  byte[] buffer;\n  FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);\n  try\n  {\n     int length = (int)fileStream.Length;  // get file length\n     buffer = new byte[length];            // create buffer\n     int count;                            // actual number of bytes read\n     int sum = 0;                          // total number of bytes read\n\n    // read until Read method returns 0 (end of the stream has been reached)\n    while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)\n       sum += count;  // sum is a buffer offset for next reading\n    }\n  finally\n  {\n    fileStream.Close();\n  }\n   return buffer;\n }	0
25785840	25763439	In C#, how can I process all RabbitMQ messages currently on the queue?	var factory = new ConnectionFactory { HostName = "localhost" };\nusing (var connection = factory.CreateConnection())\n{\n    using (var channel = connection.CreateModel())\n    {\n        var queueDeclareResponse = channel.QueueDeclare(Constants.QueueName, false, false, false, null);\n\n        var consumer = new QueueingBasicConsumer(channel);\n        channel.BasicConsume(Constants.QueueName, true, consumer);\n\n        Console.WriteLine(" [*] Processing existing messages.");\n\n        for (int i = 0; i < queueDeclareResponse.MessageCount; i++)\n        {\n            var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();\n            var body = ea.Body;\n            var message = Encoding.UTF8.GetString(body);\n            Console.WriteLine(" [x] Received {0}", message);\n        }\n        Console.WriteLine("Finished processing {0} messages.", queueDeclareResponse.MessageCount);\n        Console.ReadLine();\n    }\n}	0
11554037	11307405	how to send bid ask message by quick fix?	MarketDataSnapshotFullRefresh message =  new MarketDataSnapshotFullRefresh(new QuickFix.Symbol("QF"));\n MarketDataSnapshotFullRefresh.NoMDEntries group =  new MarketDataSnapshotFullRefresh.NoMDEntries();\n //For Bid \n group.set(new QuickFix.MDEntryType('0')); \n group.set(new QuickFix.MDEntryPx(12.32));\n group.set(new QuickFix.MDEntrySize(100));    \n message.addGroup(group);\n //For Ask\n  group.set(new QuickFix.MDEntryType('1'));\n  group.set(new QuickFix.MDEntryPx(12.32));\n  group.set(new QuickFix.MDEntrySize(100));    \n  message.addGroup(group);	0
5164768	5164730	Populate a LINQ table in code?	using System;\nusing System.Data;\n\nnamespace ConsoleApplication10\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      var dt = new DataTable();\n      dt.Columns.Add("Id", typeof(int));\n      dt.Columns.Add("Project Name", typeof(string));\n      dt.Columns.Add("Project Date", typeof(DateTime));\n\n      for (int i = 0; i < 10; i++)\n      {\n        var row = dt.NewRow();\n        row.ItemArray = new object[] { i, "Title-" + i.ToString(), DateTime.Now.AddDays(i * -1) };\n        dt.Rows.Add(row);\n      }\n\n      var pp = from p in dt.AsEnumerable()\n               where (int)p["Id"] > 2\n               select p;\n\n      foreach (var row in pp)\n      {\n        Console.WriteLine(row["Id"] + "\t" + row["Project Name"] + "\t" + row["Project Date"]); \n      }\n\n      Console.ReadLine();\n    }\n  }\n}	0
5411336	5411306	Is there a type-safe ordered dictionary alternative?	List<KeyValuePair>	0
12776961	12776792	Running two loops in Parallel	Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());	0
15174048	15173835	Listbox index display on Label or Textbox	public partial class Form1 : Form\n{\n    List<People> people = new List<People>();\n\n    public Form1()\n    {\n        InitializeComponent();\n        people.Add(new People("Joe Montana"));\n        people.Add(new People("Alex Smith"));\n        people.Add(new People("Colin Kaepernick"));\n\n        foreach (People p in people)\n        {\n            this.listBox1.Items.Add(p.Name);\n        }\n    }\n\n    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        this.textBox1.Text = people[listBox1.SelectedIndices[0]].Name;\n    }\n}\n\nclass People\n{\n    public People(string Name)\n    {\n        this.Name = Name;\n    }\n\n    public string Name\n    {\n        get;\n        set;\n    }\n}	0
11972965	11972747	c# Xpath with multiple namespaces	xmlnsManager.AddNamespace("d","http://schemas.microsoft.com/ado/2007/08/dataservices");	0
22560905	22560837	Returning a singleton from one method call	public class WrapperClass\n{\n    public DNControl DayNightControl {get; internal set;}\n    public MapHandler MapHandler {get; internal set;}\n    public TemperatureControl TemperatureControl {get; internal set;}\n}\n\npublic static class GameControl\n{\n    public static WrapperClass GetEverything()\n    {\n        var wrapper = new WrapperClass();\n\n        wrapper.DayNightControl = DNControl.Instance;\n        wrapper.MapHandler = MapHandler.Instance;\n        wrapper.TemperatureControl = TemperatureControl.Instance;\n\n        return wrapper;\n    }\n\n    // if that's still pertinent you may keep your individual methods too\n}	0
29729420	29729249	How to capture response returned by EXE file C#	using(Process proc = new Process())\n{\n    proc.StartInfo.UseShellExecute = false;\n    proc.StartInfo.FileName = <your exe>;\n    proc.StartInfo.Arguments = <your parameters>;\n    proc.StartInfo.RedirectStandardOutput = true;\n    proc.OutputDataReceived += LogOutputHandler;\n    proc.Start();\n    proc.BeginOutputReadLine();\n    proc.WaitForExit();\n}\n\nprivate static void LogOutputHandler(object proc, DataReceivedEventArgs outLine)\n{\n    <write your result to a file here>\n}	0
19318454	19317031	How to add a table and save data to an existing database	internal sealed class PictureDBContextConfiguration : DbMigrationsConfiguration<PictureDBContext>\n{\n    public PictureDBContextConfiguration()\n    {\n        AutomaticMigrationsEnabled = true; // This will allow CodeFirst to create the missing tables/columns\n        AutomaticMigrationDataLossAllowed = true;  //This will allow CodeFirst to Drop column or even drop tables\n    }\n}	0
19488134	19378377	Install Windows Service With Startup Parameter	protected override void OnBeforeInstall(IDictionary savedState)\n        {                \n                string parameter = "YOUR COMMAND LINE PARAMETER VALUE GOES HERE";\n                var assemblyPath = Context.Parameters["assemblypath"];\n                assemblyPath += @""" "" " + parameter + "";\n                Context.Parameters["assemblypath"] = assemblyPath;\n                base.OnBeforeInstall(savedState);\n        }	0
12843258	12843048	Get numbers after a certain string	string str = "BEGIN Fin Bal -461.000 Day 4 END";\ndecimal d;\nstring n = str.Split(' ').Where(s => decimal.TryParse(s, out d)).FirstOrDefault();\nConsole.WriteLine(n == null ? "(none)" : decimal.Parse(n).ToString());	0
3052578	3052484	How can a formcollection be enumerated in ASP.NET MVC2	Dictionary<string, string> tmpCollection = collection.\n                                 AllKeys.ToDictionary(k => k, v => collection[v]);	0
2471117	2368748	How to OpenWebConfiguration with physical path?	public static Configuration OpenConfigFile(string configPath)\n{\n    var configFile = new FileInfo(configPath);\n    var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);\n    var wcfm = new WebConfigurationFileMap();\n    wcfm.VirtualDirectories.Add("/", vdm);\n    return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");\n}	0
20790482	20790288	Append header to text file	using (var sr = new StreamReader(fileToRead))\n    using (var sw = new StreamWriter(fileToWrite, true))\n    {\n        if (sw.BaseStream.Position == 0)\n            sw.WriteLine("bla bla...");  // Only write header in a new empty file.\n\n        var count = 1;	0
9578841	9574966	How to use JsonTextReader twice	JsonReader reader = token.CreateReader();	0
20137356	20137136	Resorting a SortedList by key	public static class Extension\n    {\n        public static SortedList<TValue, TKey> ShiftKeyValuePair<TKey, TValue>(this SortedList<TKey, TValue> instance)\n        {\n            SortedList<TValue, TKey> key = new SortedList<TValue, TKey>();\n            foreach (var item in instance)\n                key.Add(item.Value, item.Key);\n            return key;\n        }\n    }	0
3470875	3467969	Tooltip not showing for nested control	private void memoExEdit1_Popup(object sender, EventArgs e) {\n    MemoExPopupForm popupForm = (sender as DevExpress.Utils.Win.IPopupControl).PopupWindow as MemoExPopupForm;\n    MemoEdit meDirections = popupForm.Controls[2] as MemoEdit;\n    meDirections.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(meDirections_EditValueChanging);\n}\n\nvoid meDirections_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e) {\n    GetRemainingChars(sender);\n}\n\npublic void GetRemainingChars(object sender) {\n    TextEdit control = sender as TextEdit;\n    int maxChars = control.Properties.MaxLength;\n    tipCharacterCounter.ShowHint(control.Text.Length + "/" + maxChars, control, ToolTipLocation.RightBottom);\n}	0
23995478	23919151	XmlArray Serialization - How can I make the serializer ignore the class name of items in a list?	[XmlIgnore]\npublic List<MyObject> Objects{ get; set; }\n\n[XmlArray(ElementName = "OBJECT")]\n[XmlArrayItem(Type = typeof(int), ElementName = "PROPA")]\n[XmlArrayItem(Type = typeof(string), ElementName = "PROPB")]\npublic List<object> XmlObjects\n{\n    get\n    {\n        var xmlObjects = new List<object>();\n\n        if (Objects != null)\n        {\n            xmlObjects.AddRange(Objects.SelectMany(x => new List<object>\n            {\n                x.PropA,\n                x.PropB\n            }));\n        }\n\n        return xmlObjects;\n    }\n    set { }\n}	0
12058014	12057741	Failed to convert parameter value from a String to a Double C#	param.ParamName = "@SalePrice";\nparam.ParamValue = sPrice;\nparam.ParamDBType = SqlDbType.Float;\nparameters.Add(param);	0
9293935	9293460	Unit-Testing an Action with NUnit	// arrange\nvar dataAccessApi = MockRepository.GenerateMock<IDataAccessApi>();\nvar restExecution = MockRepository.GenerateMock<IRestExecution>();\nvar sinkNodeResource = new SinkNodeResource(dataAccessApi, restExecution);\nstring uri = "http://SomeUri.com";\nstring sourcePath = "Some Source Path";\n\n// act\nsinkNodeResource.CopyToUserSession(uri, sourcePath);\n\n// assert\ndataAccessApi.AssertWasCalled(\n    x => x.Request<object>(\n        Arg<RestRequest>.Matches(\n            y => y.Method == Method.POST && \n                 y.Resource == uri &&\n                 y.Parameters.Count == 1 &&\n                 y.Parameters[0].Value as string == sourcePath\n        ),\n        Arg<Action<object>>.Is.Equal((Action<object>)restExecution.Get)\n    )\n);	0
829138	829080	How to build a query string for a URL in C#?	using System.Web;\nusing System.Collections.Specialized;\n\nprivate string ToQueryString(NameValueCollection nvc)\n{\n    var array = (from key in nvc.AllKeys\n        from value in nvc.GetValues(key)\n        select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)))\n        .ToArray();\n    return "?" + string.Join("&", array);\n}	0
7095354	7095149	C# Winform DataGridView New added row value	private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)\n        {\n            if (this.dataGridView1.CurrentRow != null)\n            {\n                this.textBox1.Text = this.dataGridView1.CurrentRow.Cells["Column1"].Value.ToString();\n            }\n        }	0
30552529	29625813	How to make azure webjob run continuously and call the public static function without automatic trigger	static void Main()\n{\n    var host = new JobHost();\n    host.CallAsync(typeof(Functions).GetMethod("ProcessMethod"));\n    // The following code ensures that the WebJob will be running continuously\n    host.RunAndBlock();\n}\n\n[NoAutomaticTriggerAttribute]\npublic static async Task ProcessMethod(TextWriter log)\n{\n    while (true)\n    {\n        try\n        {\n            log.WriteLine("There are {0} pending requests", pendings.Count);\n        }\n        catch (Exception ex)\n        {\n            log.WriteLine("Error occurred in processing pending altapay requests. Error : {0}", ex.Message);\n        }\n        await Task.Delay(TimeSpan.FromMinutes(3));\n    }\n}	0
1329451	1329427	Want to form a string with given hex code values	char [] charsToRemove = {\n    '\u201C', // These are the Unicode code points (not the UTF representation)\n    '\u201D'\n};\n\nchar [] charsToSubstitute = {\n    '"',\n    '"'\n};	0
11004688	11004536	Deserializing array in JSON.NET	public class MyClass\n{\n    public string title { get; set; }\n    public List<List<double>> raw_data { get; set; }\n}	0
24428819	24428760	I want to get name of focused textbox controls that I created at run-time in WP 8.1	void Xi_GotFocus(object sender, RoutedEventArgs e)\n{ \n    TextBox t = sender as TextBox;\n    string name = t.Name;\n}	0
1397541	1397512	Find image format using Bitmap object in C#	using(Image img = Image.FromFile(@"C:\path\to\img.jpg"))\n{\n    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))\n    {\n      // ...\n    }\n}	0
2038422	2038387	RS232 question - how to read weight to PC	// where this.port is an instance of SerialPort, ie\n// this.port = new SerialPort(\n//  portName,\n//  1200,\n//  Parity.None,\n//  8,\n//  StopBits.One);\n//  this.port.Open();\n\nprotected override bool GetWeight(out decimal weightLB, out bool stable)\n{\n    stable = false;\n    weightLB = 0;\n\n    try\n    {\n        string data;\n\n        this.port.Write("W\r\n");\n        Thread.Sleep(500);\n        data = this.port.ReadExisting();\n\n        if (data == null || data.Length < 12 || data.Substring(8, 2) != "LB")\n        {\n            return false;\n        }\n\n        if (decimal.TryParse(data.Substring(1, 7), out weightLB))\n        {\n            stable = (data[11] == '0');\n\n            return true;\n        }\n    }\n    catch (TimeoutException)\n    {\n        return false;\n    }\n\n    return false;\n}	0
327073	326818	How to validate domain credentials?	bool valid = false;\n using (PrincipalContext context = new PrincipalContext(ContextType.Domain))\n {\n     valid = context.ValidateCredentials( username, password );\n }	0
5339171	5339145	Adding byte[] interpreted as a number and short	b += ((short) a[0]) << 8;\nb += a[1];	0
24477986	24477963	Passing string as parameter	void Update(){\n    Method("String");\n}	0
18211354	18211256	Confused about how to fill an array	Random rnd = new Random();\n    int[,] array=new int[2,2];\n    for (int i = 0; i < 2; i++)\n    {\n        for (int j = 0; j < 2; j++)\n        {\n               array[i,j] = rnd.Next(0,100);\n\n        }\n    }	0
17657386	17657215	How to switch on generic-type-parameter in F#?	type XElement with\n  member this.Attr<'T>(name) = \n    match this.Attribute(XName.Get name) with\n    | null -> Unchecked.defaultof<'T>\n    | attr -> Convert.ChangeType(attr.Value, typeof<'T>) :?> 'T	0
19753578	19753379	String isn't splitting, but file is being read	string[] tokens = Regex.Split(line, @"\s+");	0
26149394	26149205	Partitioning a list given total partitions and partition number	int smallPartitionSize = list.Count / totalPartitions;\nint remainder = list.Count % totalPartitions;\nint selectedPartitionSize = smallPartitionSize + (partitionNumber <= remainder) ? 1 : 0;\nvar start = (partitionNumber - 1) * smallPartitionSize + Math.Min(remainder, partitionNumber - 1);\nreturn list.Skip(start).Take(selectedPartitionSize);	0
27728468	27728445	How to read Xml value from dataReader column	string xmlData = (string)reader["LoadData"]	0
12240422	12240364	Windows Store Project - Assembly reference error when trying to run cmd commands from a C# file in VS2012	using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var prc = Process.Start("explorer.exe");\n        }\n    }\n}	0
34310273	34309686	Linq c# group/sum a lot of columns	var properties = typeof(MyEntity).GetProperties().ToList();\nmyEntities.GroupBy(x => x.numerator)\n        .Select(x => new\n        {\n            Key = g.Key,\n            Sums = properties.Select(p => new \n            { \n                Name = p.Name, \n                Sum = g.Sum(entity => (int)p.GetValue(entity, null)) \n            }).ToList()\n        }).ToList();	0
11569240	11569163	Removing nodes from a TreeView with multiple selection (TreeViewMS)	private void removeToolStripMenuItem_Click(object sender, EventArgs e) \n{ \n    for (int i = treeView1.SelectedNodes.Count - 1; i >= 0; i--)\n    {\n        TreeNode n = (TreeNode)treeView1.SelectedNodes[i];\n        treeView1.Nodes.Remove(n);\n    }\n    treeView1.Update(); \n    treeView1.Refresh(); \n}	0
19756413	19756285	Can a enum contain bools and strings if so how do I change the values?	public class loginStatus : Functions\n{\n    public static bool isLoggedIn = false;\n    public static string userFileName = "";\n}	0
18525617	18525579	date and time formating in ASP.NET Data Binding	Eval("Date", "{0:dd/MM/yyyy hh:mm:ss tt}")	0
22338851	22338732	Open every URL in a new window c#	Process.Start("iexplore.exe", "-noframemerging http://www.example.com");	0
10814474	10814370	Deleting Multiple Items from a ListBox; Update in XML	if (e.KeyCode == Keys.Delete)\n{\n  foreach (int index in listBox1.SelectedIndices.Cast<int>().OrderByDescending(i=>i))\n  {\n    root.Elements("Entry").ElementAt(index).Remove();\n    listBox1.Items.RemoveAt(index);\n  }\n\n  root.Save(path);\n}	0
3441618	3417223	Exposing properties to Intellisense in Silverlight	public enum Templates\n{\n    Template1, Template2, ...\n}\n\npublic Templates defaultTemplates\n{\n   get;\n   set;\n}	0
32013243	32013086	Resizing array to lose empty values	var arr = years.Where(x => !string.IsNullOrEmpty(x)).ToArray();//or what ever you need	0
17107274	17107220	Convert DataSet to List	var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name = dataRow.Field<string>("Name")}).ToList();	0
27738140	27738084	Facebook integration for login	private static string GetFacebookUserJSON(string access_token)\n{\n    try\n    {\n      string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);\n\n      WebClient wc = new WebClient();\n      Stream data = wc.OpenRead(url);\n      StreamReader reader = new StreamReader(data);\n      string s = reader.ReadToEnd();\n      data.Close();\n      reader.Close();\n\n      return s;\n    }\n\n    catch (WebException wex)\n    {\n        string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();\n        return pageContent;\n    }\n}	0
3737091	3737053	Cancel A WinForm Minimize?	private void myForm_SizeChanged(object sender, System.EventArgs e)\n{\n   if (myForm.WindowState == FormWindowState.Minimized)\n   {\n       myForm.WindowState = FormWindowState.Normal;\n   }\n}	0
31203600	31202824	Maintaining order of DataTable rows during parallel processing	var items = new ConcurrentDictionary<DataRow, Dictionary<object,object>>;\n\nParallel.ForEach(dataTable.AsEnumerable(),row => {\n    var result = ...; \n    items.Add(row, result);\n});\n\nvar finalResult = dataTable.Rows.Cast<DataRow>().Select(r => items[r]).ToList());	0
25023106	25022570	How to insert text & image together in single column of a table using c#?	// HTML:\n<img src="path/to/img.jpg" alt="Alt text">\n\n// Markdown: \n![Alt text](/path/to/img.jpg)	0
4328067	4327920	Binding a List inside of a List to a GridView	yourGrid_RowDataBound(object sender, EventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        YourClass currentClass = (YourClass) e.Row.DataItem;\n\n        for (int i = 0; i < currentClass.stringFlags.Length; i++)\n        {\n            string currentFlag = currentClass.stringFlags[i];\n\n            if (currentFlag == "Tax")\n            {\n                Image imgTax = (Image) e.Row.FindControl("imgTax");\n                imgTax.Visbile = true;\n            }\n            else if (currentFlag == "Compliance")\n            {\n                Image imgCompliance = (Image) e.Row.FindControl("imgCompliance");\n                imgCompliance.Visbile = true;\n            }\n            else if (currentFlag == "Accounting")\n            {\n                Image imgAccounting = (Image) e.Row.FindControl("imgAccounting");\n                imgAccounting.Visbile = true;\n            }\n        }\n    }\n}	0
12529094	12529010	C# Using Linq to join 2 tables with 2 same columns	var results = from r1 in table.AsEnumerable()\n              join r2 in comment.AsEnumerable()\n              on new {\n                        signal=r1.Field<string>("SignalName"), \n                        message=r1.Field<int?>("MessageID")\n               } \n              equals new {\n                        signal=r2.Field<string>("SignalName"), \n                        message=r2.Field<int?>("MessageID")\n              } into prodGroup\n              from r3 in prodGroup.DefaultIfEmpty();	0
19395601	19395533	Store and retrieve images from database using path	public Image byteArrayToImage(byte[] byteArrayIn)\n{\n     MemoryStream ms = new MemoryStream(byteArrayIn);\n     Image returnImage = Image.FromStream(ms);\n     return returnImage;\n}	0
26650979	26650717	Create a new List from existing one and group objects	var query = users.GroupBy(x => x.UserName).OrderByDescending(x => x.Count())\n                                        .Select(x => new { UserName = x.Key, Grades = String.Join(",", x.Select(z => z.Grade)) });	0
30588930	30567896	json.Net save to file	UserInfo results = new UserInfo\n    {\n        Name = Request["name"],\n\n    };\n\n    StringBuilder sb = new StringBuilder();\n    StringWriter sw = new StringWriter(sb);\n    JsonWriter jsonWriter = new JsonTextWriter(sw);\n    jsonWriter.Formatting = Formatting.Indented;\n    jsonWriter.WriteStartObject();\n    jsonWriter.WritePropertyName("Name");\n    jsonWriter.WriteValue(results.Name);\n    jsonWriter.WriteEndObject();\n\n    string json = sw.ToString();\n    jsonWriter.Close();\n    sw.Close();\n\n    string path = @"C:\inetpub\wwwroot\JSON\json.Net\results.json";\n\n    if (!File.Exists(path))\n    {\n        File.WriteAllText(path, json);\n    }\n    else\n    {\n        File.AppendAllText(path, json);\n    }\n\n}\n\n// create a class object to hold the JSON value\npublic class UserInfo\n{\n    public string Name { get; set; }\n\n}	0
4014067	4014046	How to determine which DataRow is bound to a DataGridViewRow	Dim drv as DataRowView = myDataGridViewRow.DataBoundItem\n\nDim dr as DataRow = drv.Row	0
24701152	24700986	Retrieving an object from a generic List by property value of an Item in the list	Dim teams As List(Of Team) = [your team list]\nDim id As Integer = 10\nDim match As Team = (From item As Team In teams Select item Where item.ID = id).FirstOrDefault()	0
29739890	29739672	How can i loop over all comboBoxes controls i have and add the items of each comboBox to a List?	List<string> Items = new List<string>();\n        var comboBoxes = this.Controls\n              .OfType<ComboBox>()\n              .Where(x => x.Name.StartsWith("comboBox"));\n        foreach (var cmbBox in comboBoxes)\n        {\n            foreach (var cmbitem in cmbBox.Items)\n            {\n                Items.Add(cmbitem.ToString());\n            }\n        }	0
24687725	24687274	Screen Flicker while drawing C#	public partial class Form1 : Form\n{\n    private Point _firstPoint;\n    private Point _secondPoint;\n    private bool _hasClicked;\n\n    public Form1()\n    {\n        InitializeComponent();\n\n        _hasClicked = false;\n        _firstPoint = new Point();\n        _secondPoint = new Point();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    private void pictureEdit1_MouseMove(object sender, MouseEventArgs e)\n    {\n        _secondPoint.X = e.X;\n        _secondPoint.Y = e.Y;\n        pictureEdit1.Refresh();\n    }\n\n    private void pictureEdit1_MouseUp(object sender, MouseEventArgs e)\n    {\n        if (!_hasClicked)\n        {\n            _firstPoint.X = e.X;\n            _firstPoint.Y = e.Y;\n        }\n\n\n        _hasClicked = !_hasClicked;\n        pictureEdit1.Refresh();\n    }\n\n    private void pictureEdit1_Paint(object sender, PaintEventArgs e)\n    {\n        if (_hasClicked)\n            e.Graphics.DrawLine(Pens.Red, _firstPoint, _secondPoint);\n    }	0
17200003	17199946	Listview skips first column	ListViewItem.Text	0
17570756	17570627	How to handle multiple actions when Serial Port data received	void myEventHandler(object sender, SerialDataReceivedEventArgs e)\n{\n    DoSqlUpdate();\n    this.Invoke(UpdateUI, data);  // pass whatever data that needs to be updated\n    SendResponseMessage();\n}	0
21424438	21419951	How can I register components using a convention but dynamically named?	container.Register(\n   Classes.FromAssembly(Assembly.GetExecutingAssembly())\n      .BasedOn<ICommon>()\n      .LifestyleTransient()\n      .Configure(component => component.Named(component.Implementation.FullName + "XYZ"))	0
1297592	1297491	how to find out if a certain namespace is used, and if so, where?	public int getFailedFieldsCount() {\n    return ListOfFailedFieldsInOneRecord.Count();\n}	0
4200643	4200612	How can I get a distinct count of a field using linq?	Users\n    .GroupBy(u => u.beerID)\n    .Select(g => new {beerId = g.Key, count = g.Count()})\n    .OrderByDescending(x => x.count)\n    //.FirstOrDefault()	0
4131454	4131443	C# find exact-match in string	bool contains = Regex.IsMatch("Hello1 Hello2", @"(^|\s)Hello(\s|$)"); // yields false\nbool contains = Regex.IsMatch("Hello1 Hello", @"(^|\s)Hello(\s|$)"); // yields true	0
5620477	5619933	How to delete a record from datagridview by clicking on a 'Delete' DataGridViewLinkColumn	private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)\n {\n      if (e.ColumnIndex == 0)\n      {\n           dataGridView1.Rows.RemoveAt(e.RowIndex);\n      }\n }	0
2509452	2509285	Getting details of a DLL in .NET	using System.Diagnostics;\n\nFileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo("C:\\temp\\Test.dll");\nMessageBox.Show(myFileVersionInfo.ProductName.ToString()); //here it is	0
4255209	4254529	Is it possible to set LinqDataSource.OrderBy to a method's result?	public int SortOrderBy { get { return GetSortValue(); } }	0
3763296	3762705	find current element in repeater	private void rptPanier_ItemDataBound(Object sender , RepeaterItemEventArgs e) \n{\n    if (e.Item.ItemType == ListItemType.Header)\n    {\n      var myItem = (Hyperlink)e.Item.FindControl("YourControlName");\n    }\n}	0
10712929	10712815	How to specify a file path in ASP.NET MVC	string filepath = Server.MapPath("~/... ...jpg");	0
3861622	3861602	How to check if a windows form is already open, and close it if it is?	FormCollection fc = Application.OpenForms;\n\nforeach (Form frm in fc)\n{\n//iterate through\n}	0
32576860	32576555	Ensuring release of pessimistic lock	--acquire lock\nDECLARE\n      @ReturnCode int\n    , @ClientID nvarchar(255) = '12345';\n\nEXEC  @ReturnCode = sp_getapplock\n      @Resource = @ClientID\n    , @LockMode = N'Exclusive' \n    , @LockOwner = 'Session'\n    , @LockTimeout = 0;\n\nIF @ReturnCode < 0\nBEGIN\n    RAISERROR('Lock for quote not be granted for ClientID %s. Return code=%d', 16, 1, @ClientID, @ReturnCode);\nEND;\n\n--release lock\nDECLARE\n      @ReturnCode int\n    , @ClientID nvarchar(255) = '12345';\n\nEXEC  @ReturnCode = sp_releaseapplock\n      @Resource = @ClientID\n    , @LockOwner = 'Session';	0
18764321	18735642	Umbraco: Unable to get RelatedLinks property value in code-behind	Document doc = new Document(Node.GetCurrent().Id);\n        umbraco.cms.businesslogic.property.Property relatedLinks = doc.getProperty("RelatedLinks");\n        XmlNode relatedLinksAsXml = relatedLinks.ToXml(new XmlDocument());	0
29423352	29417659	Adding SlideMasters and SlideLayouts to a Presentation	m_1 = Presentation.add_master(M_1)\nm_2 = Presentation.add_master(M_2)\nm_3 = Presentation.add_master(M_3)\n\nl_1a = m_1.add_layout(L_1A)\nl_1b = m_1.add_layout(L_1B)\nl_2a = m_2.add_layout(L_2A)\nl_2b = m_2.add_layout(L_2B)\nl_3a = m_3.add_layout(L_3A)\nl_3b = m_3.add_layout(L_3B)\n\nslide_1 = Presentation.Slides.add_slide(based_on=l_1a)\nslide_2 = Presentation.Slides.add_slide(based_on=l_1b)\nslide_3 = Presentation.Slides.add_slide(based_on=l_2a)\nslide_4 = Presentation.Slides.add_slide(based_on=l_2b)\nslide_5 = Presentation.Slides.add_slide(based_on=l_3a)\nslide_6 = Presentation.Slides.add_slide(based_on=l_3b)	0
26685697	26685632	InvalidOperationException thrown in Http post when try to create HttpContent	using(System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) {\n    //Initialize a HttpClient\n    client.BaseAddress = new Uri(strURL);\n    client.Timeout = new TimeSpan(0, 0, 60);\n    client.DefaultRequestHeaders.Accept.Clear();\n\n    //I changed this line.\n    System.Net.Http.HttpContent content = new System.Net.Http.FormUrlEncodedContent(convertNameValueCollectionToKeyValuePair(HttpUtility.ParseQueryString(objPostData.ToString()));\n\n    using(System.Net.Http.HttpResponseMessage response = client.PostAsync(strAddr, content).Result) {}\n}	0
9639523	9635423	Getting property privacy with Sharepoint 2010	try\n        {\n            SPUser AdminUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\SYSTEM"];\n            var superToken = AdminUser.UserToken;\n            HttpContext con = HttpContext.Current;\n            SPSecurity.RunWithElevatedPrivileges(delegate()\n            {\n                using (SPSite site = new SPSite(SPContext.Current.Site.Url, superToken))\n                {\n                    SPServiceContext context = SPServiceContext.GetContext(site);\n                    HttpContext.Current = null;\n                    UserProfileManager upm = new UserProfileManager(context, false);\n                    \\get useprofile code\n                 }  \n             });\n           HttpContext.Current = con;\n        }\n        catch (Exception ex)\n        {\n            throw ex;\n        }	0
31988697	31966649	Using ADO.NET and SQL Server, how to fetch datarows of two tables at once (snapshot)?	var ds = new DataSet();\n\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n    connection.Open();\n\n    var command = connection.CreateCommand();\n    var transaction = connection.BeginTransaction(IsolationLevel.Snapshot);\n\n    command.Transaction = transaction;\n    command.CommandText = "select * from Log; select * from LogDetail";\n\n    SqlDataAdapter da = new SqlDataAdapter(cmd);\n    da.Fill(ds);\n\n    transaction.Commit();\n}	0
24352123	24351966	Combo box custom items and data bound items	BindingSource GetBS(bool addAll = false)\n{\n    ......\n    con.Open(); \n    cmd = new SqlCommand("uspPodruznicaSelect", con); \n    da.SelectCommand = cmd; \n    da.SelectCommand.CommandType = CommandType.StoredProcedure; \n    da.Fill(dbtable); \n\n    if(addAll)\n    {\n        DataRow dr = dbTable.NewRow();\n        dr["ItemID"] = 0;\n        dr["ItemData"] = "ALL";\n        dbTable.Rows.InsertAt(dr, 0);\n    }\n\n    bsource.DataSource = dbtable; \n    con.Close(); \n    return bsource;\n}	0
28436331	28436224	No connection string found in App config using external Start-up application	public string GetConnectionString()\n    {\n        string connectionString = new EntityConnectionStringBuilder\n        {\n            Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",\n            Provider = "System.Data.SqlClient",\n            ProviderConnectionString = new SqlConnectionStringBuilder\n            {\n                InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],\n                DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],\n                IntegratedSecurity = false,\n                UserID = ConfigurationManager.AppSettings["SystemDBUsername"],\n                Password = ConfigurationManager.AppSettings["SystemDBPassword"],\n                MultipleActiveResultSets = true,\n            }.ConnectionString\n        }.ConnectionString;\n\n        return connectionString;\n    }	0
33647785	33647405	How can I add an additional parameter to a button click EventHandler?	private void SubscribeClick(PropertyGrid grid) {\n        button.Click += new EventHandler(\n            (sender, e) => button_Click(sender, e, grid)\n        );\n    }	0
25640659	25640608	How to convert openFileDialog.FileNames to FileInfo[]	FileInfo[] files = openFileDialog.FileNames.Select(f => new FileInfo(f)).ToArray();	0
5620383	5620124	Simple web control isn't rendering properly	protected override void OnPreRender(EventArgs e)\n{         \n  MessageTextLit.Text = MessageText;          // Set correct CSS class         \n  if (Type == MessageType.Good)              \n      ErrorPanel.CssClass = "good-box";         \n  else if (Type == MessageType.Error)             \n      ErrorPanel.CssClass = "bad-box";      \n}	0
27176919	27167084	remove recipient from mail.recipient collection	foreach (var recipient in mail.Recipients)\n{\n   if (string.Compare(recipient.Address, "joe.blogs@someaddress.com", true) == 0)\n    {\n        recipient.Delete();\n        break;\n    }\n}	0
34199784	34199620	Disable the maximize and minimize buttons of a c# console	class Program\n    {\n        private const int MF_BYCOMMAND = 0x00000000;\n        public const int SC_CLOSE = 0xF060;\n        public const int SC_MINIMIZE = 0xF020;\n        public const int SC_MAXIMIZE = 0xF030;\n\n        [DllImport("user32.dll")]\n        public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);\n\n        [DllImport("user32.dll")]\n        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);\n\n        [DllImport("kernel32.dll", ExactSpelling = true)]\n        private static extern IntPtr GetConsoleWindow();\n\n        static void Main(string[] args)\n        {\n            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_CLOSE, MF_BYCOMMAND);\n            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_MINIMIZE, MF_BYCOMMAND);\n            DeleteMenu(GetSystemMenu(GetConsoleWindow(), false), SC_MAXIMIZE, MF_BYCOMMAND);\n            Console.Read();\n        }\n\n    }	0
12549260	12549197	Are there any Int24 implementations in C#?	[StructLayout(LayoutKind.Sequential)]\npublic struct UInt24 {\n    private Byte _b0;\n    private Byte _b1;\n    private Byte _b2;\n\n    public UInt24(UInt32 value) {\n        _b0 = (byte)(value & 0xFF);\n        _b1 = (byte)(value >> 8); \n        _b2 = (byte)(value >> 16);\n    }\n\n    public unsafe Byte* Byte0 { get { return &_b0; } }\n    public UInt32 Value { get { return _b0 | ( _b1 << 8 ) | ( _b2 << 16 ); } }\n\n\n}\n\n// Usage:\n\n[DllImport("foo.dll")]\npublic static unsafe void SomeImportedFunction(byte* uint24Value);\n\nUInt24 uint24 = new UInt24( 123 );\nSomeImportedFunction( uint24.Byte0 );	0
21731341	21731262	How to both deserialize a stream with protobuf and write it to file	stream.Seek(0, SeekOrigin.Begin);	0
1039504	1039474	Can I programmatically add a linkbutton to gridview?	DataBind()	0
12999712	12998732	how to register a rihno stub in MS unity?	container.RegisterInstance(typeof(ILogger), loggerStub);	0
33218075	33217476	Set Scrollviewer position of GridView control	ScrollViewer.ScrollToVerticalOffset(double);	0
9805951	9805482	Comparing Radio Button List's SelectedIndex to SelectedIndex[0] or Selectedindex[1]	switch (rBtnList.SelectedIndex)\n        {\n            case 0:\n                    //something to do;\n                break;\n            case 1:\n                //something to do\n                break;\n        }	0
11215354	11215286	Threshold image with trackbar	imageAttr.SetThreshold((float)kryptonTrackBar1.Value / 100.0f);	0
11140648	11140129	Validating input with Regex	Regex curlyThings = new Regex(@"\{0:.*?\}");\n        Regex kosherCurlyThings = new Regex(@"\{0:(yy|yyyy|MM|dd|hh|mm|ss)\}");\n\n        MatchCollection matchCollection = curlyThings.Matches("CG{0:yyyy}-{0:MM}-{0:dd}asdf{0:GARBAGE}.csv");\n        foreach(Match match in matchCollection)\n        {\n            if(!kosherCurlyThings.IsMatch(match.Value))\n            {\n                Console.WriteLine("{0} isn't kosher!", match.Value);\n            }                \n        }	0
26990961	26987029	Populate current date and time as default in footer template	GridViewRow gridStoppageFooterRow = gvw_InspectionMainProcess.FooterRow;\nRadDateTimePicker txt_LineInchargeDateTime = gridStoppageFooterRow.FindControl("txt_LineInchargeDateTimeFooter") as RadDateTimePicker;\ntxt_LineInchargeDateTime.SelectedDate = DateTime.Now;	0
33003980	32999572	How to change the exposure of a skybox at runtime in Unity?	RenderSettings.skybox.SetFloat("_Exposure", Mathf.Sin(Time.time * Mathf.Deg2Rad * 100) + 1);	0
24857948	24857898	Converting String to Int without converting the variable itself	MagicInt x = 123;\nstring s = x;\nint i = x;\nConsole.WriteLine("s is " + s);\nConsole.WriteLine("i is " + i);\n\n\npublic struct MagicInt\n{\n    public MagicInt(int value)\n    {\n        _value = value;\n    }\n    public MagicInt(string value)\n    {\n        _value = int.Parse(value);\n    }\n\n    int _value;\n\n    public static implicit operator int(MagicInt value)\n    {\n        return value._value;\n    }\n\n    public static implicit operator string(MagicInt value)\n    {\n        return value._value.ToString();\n    }\n\n    public static implicit operator MagicInt(int value)\n    {\n        return new MagicInt(value);\n    }\n\n    public static implicit operator MagicInt(string value)\n    {\n        return new MagicInt(value);\n    }\n\n}	0
31844071	31812035	RelayCommand parameter passing in Xamarin	OpenMenuItemCommand = new RelayCommand<MenuItem>(OpenMenuItem);\n  ...\n  public void OpenMenuItem(MenuItem item)\n  {\n  }	0
25737096	25720968	Populating ListView Column-wise from an array in C#	string[] temp = new string[10];\nfor (int i = 0; i < 20000; i++)\n        {\n            temp[0] = Array1[i].ToString();\n            temp[1] = Array2[i].ToString();\n            temp[2] = Array3[i].ToString();\n            temp[3] = Array4[i].ToString();\n            temp[4] = Array5[i].ToString();\n            temp[5] = Array6[i].ToString();\n            temp[6] = Array7[i].ToString();\n            temp[7] = Array8[i].ToString();\n            ListViewItem listItem = new ListViewItem(temp);\n            MyListView.Items.Add(listItem);\n        }	0
11954943	11954305	Function to determine if two tables are related	{TableA => {TableB, TableC}, \n TableB => {TableC, TableD}, \n TableC => {}, \n etc..}	0
30842831	30842433	How to change the colour and style of MajorGrid of AxisY in ASP.net chart	Chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = System.Web.UI.DataVisualization.Charting.ChartDashStyle.Dash;	0
13754505	13753917	Application with dual authentication: custom and Active Directory	public EOMForm()\n    {\n        InitializeComponent();\n\n        // Show the connection string when hovering over the database label (Test Mode Only)\n        if(Properties.Settings.Default.TestMode)\n            this.toolTip1.SetToolTip(this.databaseLabel, EomAppCommon.EomAppSettings.ConnStr);\n\n        // Security\n        DisableMenus();\n    }\n\n    private void DisableMenus()\n    {\n        // Disable individual menu items\n        foreach (var menuItem in this.TaggedToolStripMenuItems())\n            menuItem.Enabled = Security.User.Current.CanDoMenuItem((string)menuItem.Tag);\n\n        // Apply disabled color to top level menus that have all their items disabled\n        foreach (var menu in menuStrip1.DisabledMenus())\n            menu.ForeColor = SystemColors.GrayText;\n    }	0
32014142	32013910	Google Currency Converter	WebClient web = new WebClient();\n            string url = string.Format("https://www.google.com/finance/converter?a={2}&from={0}&to={1}", fromCurrency.ToUpper(), \n                toCurrency.ToUpper(), amount);\n\n\n            string response = web.DownloadString(url);\n\n            var split  = response.Split((new string[] { "<span class=bld>"}),StringSplitOptions.None);\n            var value = split[1].Split(' ')[0];\n            decimal rate = decimal.Parse(value,CultureInfo.InvariantCulture);	0
25354399	25354366	Want to add a validation using regular expression the format should be like this xxxxx-xxxxxxx-x	[RegularExpression(@"^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$", ErrorMessage = "Entered CNIC format is not valid.")]	0
327320	327310	How can I make some items in a ListBox bold?	public partial class Form1 : Form\n {\n    public Form1()\n    {\n        InitializeComponent();\n\n        ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"});\n        ListBox1.DrawMode = DrawMode.OwnerDrawFixed;\n    }\n\n    private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)\n    {\n        e.DrawBackground();\n        e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds);\n        e.DrawFocusRectangle();\n    }\n }	0
14492545	14492342	Cropping an image stored locally	private void MainPage_Loaded(object sender, RoutedEventArgs e)\n{\n    var bmp = new WriteableBitmap(0, 0).FromContent("Assets/ApplicationIcon.png");\n    var croppedBmp = bmp.Crop(0, 0, bmp.PixelWidth/2, bmp.PixelHeight/2);\n    croppedBmp.SaveToMediaLibrary("myImage.jpg");\n}	0
6914628	6914381	picturebox path parameter	hamlekullanici.Image = Image.FromFile(\n        string.Format(@"images\{0}{1}.png", username, number);	0
14735840	13723596	How to use MetadataTypeAttribute with extended classes	[MetadataType(typeof(ClientViewModel.ClientMetaData))]\npublic class ClientViewModel : Client\n{\n    internal class ClientMetaData\n    {\n        [Display(ResourceType = typeof(ResourceStrings), Name = "Client_FirstName_Label")]\n        public string FirstName { get; set; }\n    }\n}	0
26056039	26055474	How to access Program Files folder via ASP.NET MVC	IIS APPPOOL\*YOURAPPPOOLNAME*	0
8150172	8150109	Sending xsd Date over WCF	xsd:date	0
16350873	16350856	MVC 4 C# How to create a method that returns a list<object>	public List<ProductOptionsDetail> GetOptions() {\n    return new List<ProductOptionsDetail>()\n        {\n            new ProductOptionsDetail() { Name = "None", Value = "None", IsDefault = true, SortOrder = 1 },\n            new ProductOptionsDetail() { Name = "Linen texture", Value = "Linen", IsDefault = false, SortOrder = 2 },                         \n            new ProductOptionsDetail() { Name = "Canvas texture", Value = "Canvas", IsDefault = false, SortOrder = 3 },\n            new ProductOptionsDetail() { Name = "Watercolor texture", Value = "Canvas", IsDefault = false, SortOrder = 4 },\n            new ProductOptionsDetail() { Name = "Pebble texture", Value = "Pebble", IsDefault = false, SortOrder = 5 }\n        };\n}	0
18098599	18096905	Create a list from a DataTable	var dict = dt.AsEnumerable()\n             .ToDictionary(\n                 row => row[0].ToString(),\n                 row => {\n                     return new MarketDataBEO()\n                     {\n                         MarketID = row[0].ToString(),\n                         MarketHeirarchyID = row[1].ToString()\n                         // Other class members here\n                         // MarketName = row[2].ToString()\n                         // TotalMarketSizeCYM1GI = row[3].ToString()\n                     }\n             );\n\nforeach (var m in dict.Values)\n{\n    if (!string.IsNullOrEmpty(m.MarketHeirarchyID))\n        dict[m.MarketHeirarchyID].childDetails.Add(dict[m.MarketID]);\n}\n\nvar result = dict.Values.ToList();	0
1198931	1198889	Is there any non-dummy way to get only 100 rows from a DataTable in C#?	IEnumerable<DataRow> rows = myDataTable.AsEnumerable().Take(100);	0
24596846	24595542	Sqlite-net in universal app - where is my db?	var dbFile = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "//Sample.db";\nvar sql = new SqlConnection(dbFile);	0
24216063	24215907	How can I obtain a value from an output parameter while also providing a value as an input?	parm2.Direction = ParameterDirection.InputOutput;	0
23863287	23862935	Matching hyphenated word	/\b(?<!-)\w+-\w+(?!-)\b/g	0
1619684	1619625	WIll LINQ cache a value if a select for it presents twice?	var list = from row in table.AsEnumerable()\ngroup row by row.Field<byte>("ID") into g\nlet name = (from c in g\n            select c.Field<string>("name")).First()\nselect new\n{   \n    ID = g.Key,   \n    Name = name,\n    Localized = myDic[name]\n};	0
4965485	4965170	Help using a few text boxes to display and save data to database	public class MyTextBoxWithID : TextBox\n{\n    public int ID { get; set; }\n\n\n}	0
2946228	2946164	StreamWriter Problem - 2 Spaces Written as Hex '20 c2 a0' instead of Hex '20 20'	string sourceString = ..some string...\nsourceString = sourceString.Replace((char)160, ' '); //replace nobr with space	0
15278576	15277891	Change color in datagridview based on differences in two datatables?	for (int i = 0; i < dgvCurrentCM.RowCount; i++)\n    {\n        if (dgvCurrentCM.Rows[i].Cells[0].Value != null)\n        {\n            if ((int)dgvCurrentCM.Rows[i].Cells[0].Value != (int)dgvOldCM.Rows[i].Cells[0].Value)\n            {\n                dgvCurrentCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red;\n                dgvOldCM.Rows[i].DefaultCellStyle.ForeColor = Color.Red;\n            }\n        }\n    }	0
30422780	30422261	How to throw an exception from the method with return type as void using Microsoft Fakes on VS 2013	ShimListenerConfiguration.InitializeEnv = () =>\n            {\n                throw new Exception();\n            };	0
9728237	9727328	Task processing status with a message queue	public class ImportProductsSataData{ \n       public Guid Id {get; set}\n       public int ProdctsToBeImported {get; set}\n       public int ProdctsImported {get; set}\n       public int ProdctsFailedToImport {get; set}\n}	0
15985695	15985657	Cannot retrieve data from database in C#	foreach(DataRow row in t.Rows)\n{\n        PAge = row["PAge"].ToString();\n        Amount = row["Amount"].ToString();\n        PName = row["PName"].ToString();\n        DName = row["DName"].ToString();\n        Psex = row["PSex"].ToString();\n        PPhoneNo = row["PPhoneNo"].ToString();\n        PAddress = row["PAddress"].ToString();\n        Treatment = row["Treatment"].ToString();\n        Teethno = row["Teethno"].ToString();\n}	0
25022877	25022658	How to check if all items in an array of strings are key in a NameValueCollection?	if (requiredFields.All(requiredField => collection[requiredField] != null))	0
25081110	25081074	How to get an excel file uploaded in MVC controller	[HttpPost]\n    public ActionResult GetFile(HttpPostedFileBase file) \n    {\n        if (file.ContentLength > 0) \n        {\n            //do stuff here\n        }         \n    }	0
27582728	27582547	Customize winforms calendar control	private void dateTimePicker1_ValueChanged(object sender, EventArgs e) {\n\n  var dtp = sender as DateTimePicker;\n\n  var selectedDate = dtp.Value;\n\n  if (!(selectedDate.DayOfWeek == DayOfWeek.Saturday || selectedDate.DayOfWeek == DayOfWeek.Sunday))\n  {\n\n    var offset = (int)DayOfWeek.Saturday - (int)selectedDate.DayOfWeek;\n\n    var saturday = selectedDate + TimeSpan.FromDays(offset);\n\n    dtp.Value = saturday;\n\n    label1.Text = "only saturday or sunday please";\n\n  }	0
34505433	34505222	How to Filter file from directory by using File name using linq?	var GetFileByFileName = Directory.GetFiles(@"D:\Re\reactdemo")\n                                       .Select(x => new FileInfo(x))\n                                       .Where(x => x.Name == "package.json")\n                                       .Take(1)\n                                       .ToArray();	0
25693026	25692085	Asp.net get rid of session on server on logout after clearing cookies, session, and formsauth	Session.Clear()	0
24330457	24330371	Get contents of a Var where part of line matches search string C#	var results = myFullCsv.Where(line => line.Split(',')[2] == targetValue)\n                       .ToList();	0
31548047	31547803	How to add an empty row to a datatable based on value from column	for (int i = 0; i < dataTable.Rows.Count; i++)\n    if (dataTable.Rows[i][0] == "TOTALS")\n        dataTable.Rows.InsertAt(dataTable.NewRow(), ++i);	0
28438772	28437512	Create abstract classes that contain common methods to be used from their children	public abstract class Environment\n{\n    private static Environment instance;\n\n    public static T GetInstance<T>() where T : Environment\n    {\n        return (T)instance;\n    }\n}\n\npublic class Desert : Environment\n{\n\n}\n\npublic class class1\n{\n    public void SomeMethod()\n    {\n        Environment.GetInstance<Desert>()\n    }\n}	0
5310961	5309534	c# XML serializer nonamespace using list	void Main()\n{\n    var s = new XmlSerializer(typeof(OlpData));\n    using (var t = new StreamWriter("code.xml"))\n    {\n        var xml = new OlpData { Resources = new[] { WriteGeneral() } };\n        s.Serialize(t, xml);\n    }\n}\n\n[XmlRoot("OLPData")]\npublic partial class OlpData\n{\n    [XmlAttribute(AttributeName = "noNamespaceSchemaLocation", Namespace = XmlSchema.InstanceNamespace)]\n    public string attr = @"C:\Program Files\Dassault Systemes\B19\intel_a\startup\Olp\XSchemas\Upload.xsd";\n\n    [XmlElement("Resource")]\n    public Resource[] Resources;\n}\n\npublic partial class Resource\n{\n}	0
6735017	6734977	C# how to append a string.join and not to append the very last string	string Combinestr = string.Join("\nTotal Found", newListing);	0
15644190	15644122	Replace character in string with tab & must contain 4 total tabs	string[] lines = System.IO.File.ReadAllLines(input_file);\nvar result = new List<string>();\nforeach(var line in lines)\n{\n    var strings = line.Split('\t');\n    var newLine = "";\n    foreach(var s in strings)\n    {\n        var newString = s.Replace('??','\t');\n        var count = newString.Count(f=>f=='\t');\n        if (count<4)\n            for(int i=0; i<4-count; i++)\n                newString += "\t";\n        newLine += newString + "\t";\n    }\n    result.Add(newLine);\n}\nFile.WriteAllLines(output_file, result);	0
7890061	7889916	how to make command line in a multiline TextBox	private void textBoxK2400_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Return)\n    {\n        string command = textBoxK2400.Text.Split('\n').LastOrDefault();\n        if (!String.IsNullOrEmpty(command) && command.StartsWith(">>"))\n        {\n            K2400.WriteString(command.Substring(2), true);\n            textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;\n            textBoxK2400.Text += ">>"; // It's not necessary\n        }\n    }\n}	0
15111808	15111544	telerik radcombobox : C# lambda expression to get list of values of checked items	List<int> selectedValues = cblMagistrateCourts.Items.Where(i => i.Checked)\n                                                    .Select(i => Convert.ToInt32(i.Value))\n                                                    .ToList();	0
5487619	5486159	Localization for multiple languages at same time	params string[]	0
24937695	24937624	DataGridView with a row with 2 text lines	columnName.DefaultCellStyle.WrapMode = DataGridViewTriState.True;	0
24809162	24809100	Can I update value in a ListView?	ListViewItem lvi = listView1.FindItemWithText("s2");\nif (lvi != null)\n{\n    lvi.SubItems[0].Text = "s2_baa";\n}	0
414000	413985	Commenting try catch statements	try\n{   \n    real code // throws SomeException\n    real code // throws SomeOtherException\n}\ncatch(SomeException se)\n{\n    // explain your error handling choice if it's not obvious\n}\ncatch(SomeOtherException soe)\n{\n    // explain your error handling choice if it's not obvious\n}	0
9707998	9707870	WinForms Anchor Control changes Location Origin?	this.Size = new Size(100, 200);\nthis.Location = new Point(100, 100);\n\nButton b = new Button();\nb.Text = "Test";\nb.Location = new Point(10, 10);\nb.Size = new Size(75, 23);\n//b.Anchor = AnchorStyles.Left | AnchorStyles.Top;\nb.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;\n\nthis.Controls.Add(b);\nthis.Show();	0
30246984	30246298	Detect PowerModeChange and wait for execution	[DllImport("user32.dll", SetLastError=true)]\nstatic extern bool ShutdownBlockReasonCreate(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string reason);\n\n[DllImport("user32.dll", SetLastError=true)]\nstatic extern bool ShutdownBlockReasonDestroy(IntPtr hWnd);\n\n//The following needs to go in a Form class, as it requires a valid window handle\npublic void BlockShutdownAndSave()\n{\n    //If calling this from an event, you may need to invoke on the main form\n    //because calling this from a thread that is not the owner of the Handle\n    //will cause an "Access Denied" error.\n\n    try\n    {\n        ShutdownBlockReasonCreate(this.Handle, "You need to be patient.");\n        //Do your saving here.\n    }\n    finally\n    {\n        ShutdownBlockReasonDestroy(this.Handle);\n    }\n}	0
25202938	24736466	How to make sure that all call to asp web api is authorized?	public?class?AuthorizationHeaderHandler?:?DelegatingHandler\n{\n????protected?override?Task<HttpResponseMessage>?SendAsync(\n????HttpRequestMessage?pRequest,?CancellationToken?pCancellationToken)\n????{\n????????IEnumerable<string>?apiKeyHeaderValues?=?null;?\n????????if?(!pRequest.Headers.TryGetValues("Authorization",?out?apiKeyHeaderValues)\n            || !TokenRepo.IsVallidToken(apiKeyHeaderValues))\n????????{\n            var?response?=?new?HttpResponseMessage(HttpStatusCode.Unauthorized)\n????????????{\n????????????????Content?=?new?StringContent("{\"error\":?\"invalid_token\"}")\n????????????};\n????????????response.Content.Headers.ContentType?=?new?MediaTypeHeaderValue("application/json");\n            return?Task.Factory.StartNew(()?=>?response);\n        }\n        return?base.SendAsync(pRequest,?pCancellationToken);\n    }\n}	0
2006910	2006867	Hide an element in ASP.net based on an if inside a Repeater	protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)\n    {\n        Domain.Employee employee = (Domain.Employee)e.Item.DataItem;\n        Control myControl = (Control)e.Item.FindControl("controlID");\n        //Perform logic\n    }\n}	0
29731171	29730973	Encrypt a string to match length of original string	static String alphabet = "abcdefghijklmnopqrstuvwxyz";\n\npublic static String encrypt(String originalString)\n{\n    String returnString = "";\n    int shift = alphabet.Length / 2; \n\n    foreach (char c in originalString)\n    {\n         int nextIndex = alphabet.IndexOf(c) + shift;\n\n         if (nextIndex > alphabet.Length)\n            nextIndex = nextIndex - alphabet.Length;\n\n         returnString += alphabet[nextIndex];\n         shift = alphabet.IndexOf(alphabet[nextIndex]);\n    }\n\n    return returnString;\n}\n\npublic static String decrypt(String encryptedString)\n{        \n    String returnString = "";\n    int shift = alphabet.Length / 2; \n\n    foreach (char c in encryptedString)\n    {\n        int nextIndex = alphabet.IndexOf(c) - shift;\n\n         if (nextIndex < 0)\n            nextIndex = alphabet.Length + nextIndex; // nextIndex is negative so we are decreasing regardless\n\n        returnString += alphabet[nextIndex];\n        shift = alphabet.IndexOf(c);\n    }\n\n    return returnString;\n}	0
30633033	30632853	How would I add properties to an entity using a method instead of hard coding it (using Entity Framework)?	public class ExtraEntityProperty\n{\n    public int Id { get; set; } // PK\n    public string EntityName { get; set; }\n    public string PropertyType { get; set; }\n    public string PropertyName { get; set; }\n}\n\npublic class ExtraEntityPropertyValue\n{\n    public int Id { get; set; } // PK\n    public int ExtraEntityPropertyId { get; set; } // FK\n    public string PropertyValue { get; set; }\n}	0
11906978	11906917	Array written as name[x, y] rather than name[x][y]	var jagged = new int[3][]; //not defining the size of the child array...\nvar multi = new int[3,8]; //defining a 3x8 "square"\nvar multiBad = new int[3,]; //Syntax error!\nvar jaggedSquare= new int[3][8]; //another 3x8 "square"	0
223176	223162	Parse filename from full path using regular expressions in C#	//  using System.Text.RegularExpressions;\n\n/// <summary>\n///  Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM\n///  Using Expresso Version: 3.0.2766, http://www.ultrapico.com\n///  \n///  A description of the regular expression:\n///  \n///  Any character that is NOT in this class: [\\], any number of repetitions\n///  End of line or string\n///  \n///\n/// </summary>\npublic static Regex regex = new Regex(\n      @"[^\\]*$",\n    RegexOptions.IgnoreCase\n    | RegexOptions.CultureInvariant\n    | RegexOptions.IgnorePatternWhitespace\n    | RegexOptions.Compiled\n    );	0
2827329	2827241	String date time format	var myDate = DateTime.Parse(item.Element("upload_date").Value);\nDate = String.Format("{0:d}", myDate);	0
8273540	8273509	How to add files recursively to a listbox by selecting a dir in C#	string[] filePaths = Directory.GetFiles(@"C:\CurrentDirectoryName", "*.*", SearchOption.AllDirectories);	0
21962974	21925799	Bearer token for external logins	var fb = new FacebookAuthenticationOptions\n{\n    AppId = "...",\n    AppSecret = "...",\n    SignInAsAuthenticationType = "ExternalCookie",\n    Provider = new FacebookAuthenticationProvider\n    {\n        OnAuthenticated = async ctx =>\n            {\n                var access_token = ctx.AccessToken;\n                ctx.Identity.AddClaim(new Claim("access_token", access_token));\n            }\n    }\n};\napp.UseFacebookAuthentication(fb);	0
10682046	10681880	Download html with encoding utf-8 vs iso-8859-1	WebClient.Encoding	0
22766308	22763643	Can a Pen or Brush paint a Point?	public void DrawPoint(Graphics G, Pen pen, Point point)\n    {\n        // add more LineCaps as needed..\n        int pw2 = (int ) Math.Max(1, pen.Width / 2);\n        using(var brush = new SolidBrush(pen.Color))\n        {\n            if (pen.EndCap == LineCap.Square)\n                G.FillRectangle(brush, point.X - pw2, point.Y - pw2, pen.Width, pen.Width);\n            else\n                G.FillEllipse(brush, point.X - pw2, point.Y - pw2, pen.Width, pen.Width);\n        }\n    }	0
21689822	21688857	How to enable $expand and $select on ODataQueryOptions?	public IHttpActionResult Get(ODataQueryOptions<YourEntity> odataQueryOptions)\n{\n    //Your applyTo logic and results.\n\n    if (odataQueryOptions.SelectExpand != null)\n    {\n        Request.SetSelectExpandClause(odataQueryOptions.SelectExpand.SelectExpandClause);\n    }\n\n    return Ok(results, results.GetType());\n}\n\nprivate IHttpActionResult Ok(object content, Type type)\n{\n    Type resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);\n    return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;\n}	0
428265	428196	Why is a cached Regexp outperforming a compiled one?	var m3 = Regex.Match(pattern, item); // Wrong\nvar m3 = Regex.Match(item, pattern); // Correct	0
14700632	14695705	How to make DNN textfield readonly	string teValue = TextEditor1.Value;\nLabel1.Text = teValue;\nTextEditor1.Visible = false;	0
16126913	16126697	How to add on mouse hover effect in Word 2010 addin	Word Mini Toolbar	0
7989980	7975870	Is it possible to add a view in code-first context?	_context.Database.SqlQuery<Model>("spTest").ToList();	0
32229886	32229735	Converting a Person's Height from feet and inches to just inches C#	// assuming we have string inputStr\nstring[] tokens = inputStr.Split ('.');\nif (tokens.Length < 2 || tokens.Length > 2)\n{\n    throw new ArgumentException ();\n}\n\nint feet = int.Parse (tokens[0]);\nint inches = int.Parse (tokens[1]);\nif (inches >= 12)\n{\n    throw new ArgumentException ();\n}\n\nint totalInches = (feet * 12) + inches;	0
21457018	21456640	How to obtain a textbox control from a div of repeater row?	foreach(RepeaterItem item in Repeater1.Items)\n{\n    var tbx = item.FindControl("tbx") as TextBox;\n    if(tbx != null)\n    {\n        foreach (ShoppingCart r in cart.shoppingcart)\n        {\n           if (r.ProductID == command)\n           {\n               r.ProductAmount = Convert.ToInt32(tbx.Text);\n           }\n        }\n     }\n}	0
9758314	9758260	How to display rows as columns in DataGridView?	var tbl = dset.Tables["Profile"]:\nvar swappedTable = new DataTable();\nfor (int i = 0; i <= tbl.Rows.Count; i++)\n{\n    swappedTable.Columns.Add(Convert.ToString(i));\n}\nfor (int col = 0; col < tbl.Columns.Count; col++)\n{\n    var r = swappedTable.NewRow();\n    r[0] = tbl.Columns[col].ToString();\n    for (int j = 1; j <= tbl.Rows.Count; j++)\n        r[j] = tbl.Rows[j - 1][col];\n\n    swappedTable.Rows.Add(r);\n}\ndataGridView1.DataSource = swappedTable;	0
32028967	32021741	Integer overflow detection C# for Add	static int Add(int a, int b, out bool overflowFlag)\n{\n    unchecked\n    {\n        int c = a + b;\n        overflowFlag = ((a ^ b) >= 0) & ((a ^ c) < 0);\n        return c;\n    }\n}\nstatic int Add(int a, int b, out int overflowBit)\n{\n    unchecked\n    {\n        int c = a + b;\n        overflowBit = (int)((uint)((a ^ c) & ~(a ^ b)) >> 31);\n        return c;\n    }\n}	0
3111289	3111264	Using anonymous generic types with multiple generics	var anon = new { One = "1", Two = "2" };\nvar result = DoSomethingElse(anon,42);\n\npublic static T2 DoSomethingElse<T, T2>(T value, T2 otherValue)\n    where T2 : new()\n{\n    return new T2();\n}	0
32667242	32667177	C# how do i create a DateTime Variable that has the current date, but a different time?	TimeSpan now = DateTime.Now.TimeOfDay;\n            TimeSpan time2 = new TimeSpan(15, 23, 30); //(15h:23m:00s)\n            TimeSpan dif = time2 - now;	0
4691345	4690959	Double Buffering non-rectangular allocation	Brush solidBrush = new SolidBrush(p.BackColor);\nmyBuffer.Graphics.FillRectangle(solidBrush, 0, 0, p.Width, p.Height);	0
10454724	10332363	Getting Hue from every pixel in an Image	private void HueFilter()\n{\n  float y;\n  Bitmap i = (Bitmap)imgViwer.Image;\n\n  for (int a = 0; a < i.Height; a++)\n  {\n      for (int c = 0; c < i.Width; c++)\n      {                   \n          y = i.GetPixel(c, a).GetHue();\n          if (y >= 210 && y <= 260)\n          {\n              i.SetPixel(c, a, Color.Black);\n          }\n      }\n  }\n\n  imgViwer.Image = i;\n}	0
25203159	25202577	Creating PDF/A with GhostscriptProcessor	string[] CreateTestArgs(string inputPath, string outputPath)\n{\n    List<string> gsArgs = new List<string>();\n    gsArgs.Add("-notused");\n    gsArgs.Add("-dPDFA");\n    gsArgs.Add("-dBATCH");\n    gsArgs.Add("-dNOPAUSEgsArgs");\n    gsArgs.Add("-sDEVICE=pdfwrite");\n    gsArgs.Add(@"-sOutputFile=" + outputPath);\n    gsArgs.Add(@"-f" + inputPath);\n    return gsArgs.ToArray();\n}	0
459521	459442	INSERT from ASP.NET to MS Access	OleDbConnection conn = new OleDbConnection (connectionString);\n\nOleDbCommand command = new OleDbCommand();\ncommand.Connection = conn;\ncommand.CommandText= "INSERT INTO myTable (col1, col2) VALUES (@p_col1, @p_col2)";\ncommand.Parameters.Add ("@p_col1", OleDbType.String).Value = textBox1.Text;\n...\ncommand.ExecuteNonQUery();	0
22359450	22359210	Listbox not showing values after DataBind from a comma delimited string	string promoIDs = "Test1, Test2, Test3, Test4";\nstring[] values = promoIDs.Split(',');\nforeach (string value in values)\n{\n    string item = value.Trim(); // Trim the spaces\n    lstBoxPromoItems.Items.Add(new ListItem(item, item));\n}	0
21721958	21721891	Replace specific color pixels in an image	var YourImage = (Bitmap)Image.FromFile("LicensePlate.png");\n\nfor (var x = 0; x < YourImage.Width; x++)\n   for (var y = 0; y < YourImage.Height; y++) {\n       var pixel = YourImage.GetPixel(x, y);\n       if (pixel.r > 200 && pixel.g > 200 && pixel.b > 200)\n                YourImage.SetPixel(x, y, Color.White);\n   }	0
7255894	7255844	Application crashes and transactions in .NET	var transaction = connection.BeginTransaction();	0
19097155	19095075	Compare two dates with a range	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click\n\n    Dim fileDate As Date = Convert.ToDateTime("Sep 25, 2013")\n    Dim rightNow As Date = Convert.ToDateTime(Date.Now.ToString("MMM dd, yyyy"))\n    Dim lastWeek = rightNow.AddDays(-7)\n\n    If rightNow >= fileDate And lastWeek <= fileDate Then\n\n        Debug.Print("its new")\n    Else\n        Debug.Print("too old")\n    End If\nEnd Sub	0
14964735	14962081	Click on 'OK' button of message box using WINAPI in c#	SendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);\nSendMessage(btnHandle, WM_LBUTTONUP, 0, 0);\nSendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);\nSendMessage(btnHandle, WM_LBUTTONUP, 0, 0);	0
245128	245045	Add close button (red x) to a .NET ToolTip	1    class MyToolTip : ToolTip\n    2     {\n    3         public MyToolTip()\n    4         {\n    5             this.OwnerDraw = true;\n    6             this.Draw += new DrawToolTipEventHandler(OnDraw);\n    7 \n    8         }\n    9 \n   10         public MyToolTip(System.ComponentModel.IContainer Cont)\n   11         {\n   12             this.OwnerDraw = true;\n   13             this.Draw += new DrawToolTipEventHandler(OnDraw);\n   14         }\n   15 \n   16         private void OnDraw(object sender, DrawToolTipEventArgs e)\n   17         {\n                      ...Code Stuff...\n   24         }\n   25     }	0
3944149	3944056	Left Join If A Certain Field Is A Certain Value?	var Results =\n    from a in Db.Table1\n      join b in Db.Table2 on \n               new { ID= a.Id, Bit = true } \n               equals \n               new { ID = b.Id, Bit = b.Value ==1 } \n      into c \n      from d in c.DefaultIfEmpty()\n      select new {\n           Table1 = a, \n           Table2= d  //will be null if b.Value is not 1\n      };	0
22496893	22317689	How to Parse Json data to normal data in C#	string json = responseBody;\n    JObject parsed = JObject.Parse(json);\n    string results = (string)parsed["result"];	0
11407807	11407777	How to delete an employee with his training record in this GridView?	DELETE employee from  Employee_Courses  where dbo.employee.Username = @Username	0
28203700	28202145	Create attachment from the stream of the data	// convert to Stream type not MemoryStream!\nbyte[] byteArray = Encoding.UTF8.GetBytes(someString);\n\nStream theStream = new MemoryStream(byteArray);\n\nmyMessage.AddAttachment(theStream, "someattachmentname.xml");	0
23282050	23281763	Is there a way to extract the message from WebException?	public static string ParseExceptionRespose(WebException exception)\n    {\n        string responseContents;\n        Stream descrption = ((HttpWebResponse)exception.Response).GetResponseStream();\n\n        using (StreamReader readStream = new StreamReader(descrption))\n        {\n            responseContents = readStream.ReadToEnd();\n        }\n\n        return responseContents;\n\n    }	0
17328592	17326700	Everyone's sid in Windows 8	directorySecurity.AddAccessRule(\n   new FileSystemAccessRule(\n       worldSecurityIdentifier,\n       FileSystemRights.Read | FileSystemRights.Write,\n       InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n       PropagationFlags.None,\n       AccessControlType.Allow));	0
23986251	23986250	WPF Using an image as a cursor but mouse events are not working over buttons	Mouse.OverrideCursor = new Cursor(new System.IO.MemoryStream(MyNameSpace.Properties.Resources.TheResourceName));	0
3556973	3556799	Transformation from one position scale of notation to another	public class Formatter\n{\n  List<char> symbols;\n  int base;\n\n  public Formatter(string format)\n  {\n    string[] splitted = format.Split(",");\n    symbols = splitted.Select(x => x[0]).ToList();\n    base = symbols.Size;\n  }\n\n  public long Parse(string value)\n  {\n    long result = 0;\n    foreach(char c in value)\n    {\n      long n = symbols.IndexOf(c);\n      result = result*base+n;\n    }\n    return result;\n  }\n\n  public string Encode(long value)\n  {\n    StringBuilder sb = new StringBuilder();\n    while(value>0)\n    {\n      long n = value % base;\n      value /= base;\n      sb.Insert(0, symbols[n]);\n    }\n    return sb.ToString();\n  }\n}	0
19298713	19297995	(ASP.NET Cache API) Is it possible that an item may be removed from cache before its set expiry?	CacheItemRemovedCallback onRemoveCallback	0
8302862	8302152	Parallels.ForEach Taking same Time as Foreach	System.Threading.ThreadPool.SetMaxThreads(4, 4);	0
5327461	5327387	c# autoclose window with sleep but text disappears	Application.DoEvents()	0
18584021	18568281	How do I toggle the switch back to previous value of the slider	private int _lastSliderValue = 100;\nprivate void sw_music_Toggle(object sender, RoutedEventArgs e)\n{\n    if(slider.Value >= 1) // I think you don't need this\n    {\n        if (sw_music.IsOn)\n        {\n            slider.Value = _lastSliderValue;\n            Intro_Sound.Play();\n        }\n        else\n        {\n            _lastSliderValue = slider.Value;\n            slider.Value = 0;\n            Intro_Sound.Stop();\n        }\n\n        if(slider.Value > 1)\n        {\n            Intro_Sound.Play();\n            sw_music.IsOn = true;\n        }\n    }\n}	0
24797679	24797485	How to download image from url using c#	client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");\nclient.DownloadFile(new Uri(url), @"c:\temp\image35.png");	0
7906454	7905651	How to DataBind a TextBox to a particular index in a List<>	list = new List<Person>();\nlist.Add(new Person { ID = 1, Name = "Name 1", Age = 21 });\nlist.Add(new Person { ID = 2, Name = "Name 2", Age = 28 });\nlist.Add(new Person { ID = 3, Name = "Name 3", Age = 44 });\n\ntextBox1.DataBindings.Add(new Binding("Text", list[0], "Name", false));\ntextBox2.DataBindings.Add(new Binding("Text", list[1], "Name", false));\ntextBox3.DataBindings.Add(new Binding("Text", list[2], "Name", false));\n\ninternal class Person\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public int Age { get; set; }\n}	0
17696376	17696312	Search and replace text in a datagridview c#	dataGridView1[2, i].Value = dataGridView1[2, i].Value.ToString().Replace(textBox6.Text, textBox7.Text);	0
22544911	22544746	Getting a value of a cell in a selected row	foreach (GridViewRow row in GridView1.Rows)\n        {\n            if (row.Cells[3].Text == tbNumberSource.Text)\n            { \n                // Match Found\n            }\n        }	0
20324014	20115742	WPF : Dynamically create a grid with specified x rows and y columns with static image in each cell	private void CreateGraphicalDisplay(int rows,int columns,int row,int column)\n    {\n        ClearGraphicPanel();\n        for (int i = 1; i <= rows; i++)\n        {\n\n        StackPanel childstack = new StackPanel();\n\n\n            for (int j = 1; j <= columns; j++)\n            {\n                Image gage = new Image();\n                gage.Stretch = Stretch.Fill;\n\n                if (i == row && j == column)\n                {\n                    gage.Source = new BitmapImage(new Uri(@Highlightedimage));\n                }\n                else\n                {\n                    gage.Source = new BitmapImage(new Uri(@NormalImage));\n                }\n                gage.Width = 12;\n                gage.Height =12;\n                gage.HorizontalAlignment = HorizontalAlignment.Left;\n                gage.Margin = new Thickness(10, 1, 1, 1);\n\n                childstack.Children.Add(gage);\n            }\n\n            containerstack.Children.Add(childstack);\n        }\n\n    }	0
8658861	8657805	Correct way to call a C DLL method from C#	[UnmanagedFunctionPointer(CallingConvention.Cdecl)]\npublic delegate void rdOnAllDoneCallbackDelegate(int parameter);\n\n[DllImport("sb6lib.dll", CallingConvention = CallingConvention.Cdecl)]\npublic static extern int rdOnAllDone(rdOnAllDoneCallbackDelegate d);\n\nclass Foo {\n    private static rdOnAllDoneCallbackDelegate callback;   // Keeps it referenced\n\n    public static void SetupCallback() {\n       callback = new rdOnAllDoneCallbackDelegate(rdOnAllDoneCallback);\n       rdOnAllDone(callback);\n    }\n\n    private static void rdOnAllDoneCallback(int parameter) {\n       Console.WriteLine("rdOnAllDoneCallback invoked, parameter={0}", parameter);\n    }\n}	0
11136102	11136001	Given a Path, how to determine whether it is directory or a file	foreach(string currentName in Directory.GetFileSystemEntries("C:\\AAAA")) \n   { \n       FileAttributes att = File.GetAttributes(currentName);\n       if((att & FileAttributes.Directory) == FileAttributes.Directory)\n           // is a directory\n       else\n           // is a file\n   }	0
10588333	10541793	DataContractSerializer deserialization of properties moved from derived class to base class	Property hides the inherited member...Use the new keyword if hiding was intended	0
7931643	7931128	Properly instantiating a class assigned to a private static volatile variable using reflection and locking	class Program\n    {\n        static Lazy<string> _Lazy;\n        static string _connectionString;\n\n        public string LazyValue\n        {\n            get\n            {\n                return _Lazy.Value;\n            }\n\n        }\n\n        public static void Init(string connectionString)\n        {\n            _connectionString = connectionString;\n            _Lazy = new Lazy<string>(() => new string(connectionString.ToArray()), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);\n        }	0
25679457	25679053	Converting inconsistent data to DateTime	string[] dates = new [] { "2014-01-01", "01-01-2014"};\n\n        foreach (string d in dates)\n        {\n            DateTime parsed;\n            if (DateTime.TryParseExact(d, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))\n                Console.WriteLine("yyyy-MM-dd: {0}", parsed);\n            else if (DateTime.TryParseExact(d, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed))\n                Console.WriteLine("dd-MM-yyyy: {0}", parsed);\n        }	0
1984005	1983812	How to run form and console at the same time with c#?	using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\nusing System.Windows.Forms;\n\n    namespace Project1\n    {\n    class Class2\n    {\n\n        [STAThread]\n        static void Main()\n        {\n           Console.WriteLine("hello");\n           Class2 t = new Class2();\n           t.test();\n           Console.WriteLine("second string");\n        }\n\n\n\n        public void test()\n        {\n            Thread t = new Thread(new ThreadStart(StartNewStaThrea));\n            t.Start();\n        }\n\n\n        private void StartNewStaThrea()\n        { \n            Application.Run(new Form1()); \n        }\n\n    }\n}	0
2077308	2077291	Help in Regex - Match YouTube Url	"\"(http:[^\"]*)\""	0
1852094	1851991	.NET Compact Framework: define default size to a custom control	[DefaultValue(typeof(Size), "500, 500")]	0
18677235	18667138	Use LINQ expression to Update Property of object	var id = new string[] { "SS41231" }.AsQueryable();\n\n// *it* represents the current element\nvar res = id.Where("it.Length > @0 AND it.Substring(@1, @2) = @3", 1, 0, 2, "SS"); // Save the result, don't throw it away.\n\nif (res.Any())\n{\n    // Line below in normal LINQ: string newID = res.Select(x => "98" + x.Substring(2)).First();\n    string newId = res.Select("@0 + it.Substring(@1)", "98", 2).Cast<string>().First();\n\n    Console.WriteLine(newId);\n}	0
31181870	31180129	Combine tables using row values as column LINQ C# SQL	var result = users.GroupJoin(details,\n            user => user.Id,\n            detail => detail.Id,\n            (user, detail) => new\n            {\n                user.Id,\n                user.Name,\n                user.Age,\n                Height = detail.SingleOrDefault(x => x.Key == "Height").Value,\n                Eyes = detail.SingleOrDefault(x => x.Key == "Eyes").Value,\n                Hair = detail.SingleOrDefault(x => x.Key == "Hair").Value,\n            });	0
23810011	23804953	Can I write event handler of any control on other page	.RadScheduler .rsSunCol, .RadScheduler .rsSatCol {\n    background-color: red;\n}	0
27161749	27158317	WPF: How do I make a custom modal dialog flash?	private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n    {\n        var retVal = IntPtr.Zero;\n\n        switch (msg)\n        {\n            case UnsafeNativeConstants.WM_NCACTIVATE:\n                retVal = UnsafeNativeMethods.DefWindowProc(hwnd, UnsafeNativeConstants.WM_NCACTIVATE, new IntPtr(1), new IntPtr(-1));\n                AssociatedObject.UpdateTitlebar((int)wParam == 1 ? true : false);\n                handled = true;\n                break;\n        }\n\n        return retVal;\n    }	0
18277368	18277308	Invoke remote powershell command from C#	InitialSessionState initial = InitialSessionState.CreateDefault();\nRunspace runspace = RunspaceFactory.CreateRunspace(initial);\nrunspace.Open();\nPowerShell ps = PowerShell.Create();\nps.Runspace = runspace;\nps.AddCommand("invoke-command");\nps.AddParameter("ComputerName", "mycomp.mylab.com");\nScriptBlock filter = ScriptBlock.Create("Get-childitem C:\\windows");\nps.AddParameter("ScriptBlock", filter);\nforeach (PSObject obj in ps.Invoke())\n{\n   // Do Something\n}	0
20585219	20585142	Abstracting communication with an API in JSON C#	Product product = new Product();\nproduct.Name = "Apple";\nproduct.Expiry = new DateTime(2008, 12, 28);\nproduct.Sizes = new string[] { "Small" };\n\nstring json = JsonConvert.SerializeObject(product);\n//{\n//  "Name": "Apple",\n//  "Expiry": "2008-12-28T00:00:00",\n//  "Sizes": [\n//    "Small"\n//  ]\n//}	0
33886682	33886361	How to access nested object from JSON with Json.NET in C#	class Planet\n    {\n        [JsonProperty("planet")]\n        PlanetInfo[] planet { get; set; }\n    }\n    class Product\n    {\n        [JsonProperty("estimatedLocationDate")]\n        string estimatedLocationDate {get;set;}\n    }\n    class PlanetInfo\n    {\n\n        public string id { get; set; }\n\n        public string name { get; set; }\n\n        [JsonProperty("publishedDate")]\n        public string publishdate { get; set; }\n\n        [JsonProperty("estimatedLaunchDate")]\n        public string estimatedLaunchDate { get; set; }\n\n        [JsonProperty("createdTime")]\n        public string createtime { get; set; }\n\n        [JsonProperty("lastUpdatedTime")]\n        public string lastupdate { get; set; }\n\n        [JsonProperty("product")]\n        public Product product { get; set; }\n    }	0
10850868	9327438	Include derived property into a linq to entity query	class Program\n{\n    static void Main(string[] args)\n    {\n        using (MyDbContext ctx = new MyDbContext())\n        {\n            res = ctx.Tasks.Where(Task.ShouldUpdateExpression).ToList();\n        }\n    }\n}\n\npublic class MyDbContext : DbContext\n{\n    public DbSet<Task> Tasks { get; set; }\n}\n\npublic class Task\n{\n    public int ID { get; set; }\n    public DateTime LastUpdate { get; set; }\n    public bool ShouldUpdate\n    {\n        get\n        {\n            return ShouldUpdateExpression.Compile()(this);\n        }\n    }\n\n    public static Expression<Func<Task, bool>> ShouldUpdateExpression\n    {\n        get\n        {\n            return t => t.LastUpdate < EntityFunctions.AddDays(DateTime.Now, 3);\n        }\n    }\n}	0
28137376	28137141	Regex match, insert string data to SQL database	using(SqlConnection connection = new SqlConnection("Data Source=ServerName;" + \n          "Initial Catalog=DataBaseName;" + \n          "User id=UserName;" + \n          "Password=Secret;"))\n{\n    connection.Open();\n    string sql =  "INSERT INTO Address(Naam,Straat,Postcode) VALUES(@param1,@param2,@param3)";\n        SqlCommand cmd = new SqlCommand(sql,connection);\n        cmd.Parameters.Add("@param1", SqlDbType.Varchar, 50).value = naamtankstation.Groups[1].Value; \n        cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = straattankstation.Groups[1].Value;\n        cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = postcodetankstation.Groups[1].Value;\n        cmd.CommandType = CommandType.Text;\n        cmd.ExecuteNonQuery();\n}	0
28323963	28323667	one of several controls may be clicked but all have the same code	foreach (Textbox t in groupPanel1.Controls.OfType<TextBox>())\n{\nt.MouseClick += new MouseEventHandler(\n  delegate(object sender, MouseEventArgs e)\n  {\n    btnSave.Enabled = true;\n  };\n}	0
22408973	19777217	WCF Casting inquery	private DataAccessService.DataAccessSqlParameter ConvertParam(SqlParameter param)\n{\n    DataAccessService.DataAccessSqlParameter daparam = new DataAccessService.DataAccessSqlParameter();\n    daparam.ParameterName = param.ParameterName;\n    daparam.ParameterValue = param.Value;\n    return daparam;\n}	0
7122621	7110294	Get key events in CheckedListBox control when a listbox item is selected	/// <summary>\n/// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey method.\n/// </summary>\n/// <param name="key"></param>\n/// <param name="dataGridViewWantsInputKey"></param>\n/// <returns></returns>\npublic bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)\n{\n    // Let the custom edit control handle the keys listed.\n    switch (key & Keys.KeyCode)\n    {\n        case Keys.Escape:\n            return true;\n        default:\n            return !dataGridViewWantsInputKey;\n    }\n}	0
27241740	27241444	How to show messagebox one time only before closing window	private static bool _isConfirmed = false;\nprivate void Window_Closing(object sender, CancelEventArgs e)\n{\n\n    if (!_isConfirmed)\n    {\n        MessageBoxResult result = MessageBox.Show("Please Be Sure That Input & Output Files Are Saved.  Do You Want To Close This Program?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Warning);\n        if (result == MessageBoxResult.Yes)\n        {\n            Application.Current.Shutdown();\n        }\n        else\n        {\n            e.Cancel = true;\n        }\n        _isConfirmed = true;\n    }\n}	0
6258797	6258720	DataTable - Select only find row where value is less than 10?	if (VotePeriods.Rows.Count > 0)\n{\n    DataRow[] vp = VotePeriods.Select("PeriodID = '" + voteperiod +"'");\n\n    if (vp.Length > 0)\n    {\n        return vp[0];\n    }\n}	0
23895504	23894078	How to Create Scrollbar for a ListBox in C#	//Create ScrollViewer which is a child of Grid\nvar scroll = new ScrollViewer();\n//add to the grid\nchildGrid.Children.Add(scroll);\n//create lisbox and set it to the content of scrollviewer which is a Child of ScrollViewer\nvar listBox = new ListBox();\nscroll.Content = listBox;	0
18087536	18087278	C# Processing same object with different "processors" a flyweight pattern?	void Recusion(TreeItem parent) \n{\n    // First call the same function for all the children.\n    // This will take us all the way to the bottom of the tree.\n    // The foreach loop won't execute when we're at the bottom.\n    foreach (TreeItem child in parent.Children) \n    {\n         Recursion(child);\n    }\n\n    // When there are no more children (since we're at the bottom)\n    // then finally perform the task you want. This will slowly work\n    // it's way up the entire tree from bottom most items to the top.\n    Console.WriteLine(parent.Name);\n}	0
6730404	6730132	How to set borders of a custom textbox for PAssword type?	int howMuchRoundCorners = 5;\nkryptonTextBox.StateCommon.Border.Rounding = howMuchRoundCorners;	0
3571916	3571904	regex 'literal' meaning in regex	Regex.Escape	0
11587564	11580414	How to interact with non-visible div from Selenium?	"css=div[class='className']"	0
29235667	29235184	How to find coordinates of a point inside selected row in DataGridView	var rt = dgv.GetRowDisplayRectangle(rowIndex, false);	0
14006716	14006654	Parse a XDocument to a Dictionary<string, string>	private static string GetElementPath(XElement element)\n    {\n        var parent = element.Parent;\n        if(parent == null)\n        {\n            return element.Name.LocalName;\n        }\n        else\n        {\n            return GetElementPath(parent) + "->" + element.Name.LocalName;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var xml = @"\n            <Foo>\n                <Bar>3</Bar>\n                <Foo>\n                    <Bar>10</Bar>\n                </Foo>\n            </Foo>";\n        var xdoc = XDocument.Parse(xml);\n        var dictionary = new Dictionary<string, string>();\n        foreach(var element in xdoc.Descendants())\n        {\n            if(!element.HasElements)\n            {\n                var key = GetElementPath(element);\n                dictionary[key] = (string)element;\n            }\n        }\n        Console.WriteLine(dictionary["Foo->Bar"]);\n    }	0
17752451	17752120	Autoincrement with SQL Insert	int newId = 0;\n\nusing (SqlCommand cmd = new SqlCommand(\n    @"INSERT INTO Results (HasSucceeded, Screenshot)\n      VALUES (@HasSucceeded, @Screenshot);\n      DECLARE @ResultID int = SCOPE_IDENTITY();\n      UPDATE Results SET ScenarioID = @ResultID\n                     WHERE ResultID = @ResultID;\n      SELECT @ResultID;", conn))\n{\n    cmd.Parameters.AddWithValue("@HasSucceeded", HasSucceeded);\n    cmd.Parameters.AddWithValue("@Screenshot", screenshot);\n\n    newId = (int)cmd.ExecuteScalar();\n}\n\n// ...Use newId here...	0
6648536	6648218	How to send continuous keypress to a program?	[DllImport("User32.dll")]\n            public static extern int SendMessage(IntPtr hWnd, uint msg, int wparam, int lparam);	0
16085972	16082113	Get the folder name of the current page ASP.NET C#	protected void Page_Load(object sender, EventArgs e)\n{\n    string[] file = Request.CurrentExecutionFilePath.Split('/'); \n    string fileName = file[file.Length-2];\n\n    if (fileName == "Dashboard")\n    {\n        MainNavList.Items.FindByText("Dashboard").Attributes.Add("class", "active");\n    }	0
6061140	6060746	How do I remove duplicate xml element values in an XDocument?	var duplicates = (from req in doc.Descendants(ns + "StateSeparationRequest")\n                      group req by req.Descendants(ns + "StateRequestRecordGUID").First().Value\n                      into g\n                      where g.Count() > 1\n                      select g.Skip(1)).SelectMany( elements => elements );\n    foreach (var duplicate in duplicates)\n    {\n        duplicate.Remove();\n    }	0
10657133	10657117	Referencing current assembly with CompilerParameters	typeof(Program).Assembly.Codebase	0
21366726	21366152	Concat two List<T>'s where a field value in each is equal	var allMaleLastNames = males.Select(m => m.LastName);\nvar allFemaleLastNames = females.Select(f => f.LastName);\n\nvar uniqueSharedLastNames = new HashSet<string>(\n    allMaleLastNames.Intersect(allFemaleLastNames));\n\nvar result = males.Concat(females)\n    .Where(p => uniqueSharedLastNames.Contains(p.LastName));	0
27251673	27251411	Menu for methods in c#	class Program\n{\n    static Dictionary<int, Action> exercises = new Dictionary<int, Action>\n    {\n        // put the numbers with the exercise method here:\n        {1, () => Exercise1()},\n        {2, () => Exercise2()},\n    };\n    public static void Main(String[] args)\n    {\n        int opt;\n\n        Console.WriteLine("program name");\n        Console.WriteLine();\n        // Print valid names - Alternatively get them from a list\n        foreach (int i in exercises.Keys)\n        {\n            Console.WriteLine(string.Format("{0}. Exercise {0}", i));\n        }\n        Console.WriteLine();\n\n        Console.WriteLine("Choose exercise number: ");\n        opt = int.Parse(Console.ReadLine());\n\n        // call like this:\n        exercises[opt]();\n    }\n }	0
5624108	5623565	Use OrderBy in a LINQ predicate?	var baseQuery = from co in collection where !co.IsVirtual select co; // base of query\n        IOrderedEnumerable<Result> orderedQuery; // result of first ordering, must be of this type, so we are able to call ThenBy\n\n        switch(CurrentDisplayMode) // use enum here\n        { // primary ordering based on enum\n            case CRSChartRankingGraphDisplayMode.Position: orderedQuery = baseQuery.OrderBy(co => co.Price);\n                break;\n            case CRSChartRankingGraphDisplayMode.Grade: orderedQuery = baseQuery.OrderBy(co => co.TotalGrade);\n                break;\n        }\n\n        this.collectionCompleteSorted = orderedQuery.ThenBy(co => co.CurrentRanking).ToList(); // secondary ordering and conversion to list	0
2445577	2393114	How to secure login and member area with SSL certificate?	Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender\n\n    If Request.IsSecureConnection = False And _ \n        Not Request.Url.Host.Contains("localhost") Then \n\n        Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://")) \n    End If  End Sub	0
8541799	8541788	Is there an easy way under Linux to implement a function that acts like GC.GetTotalMemory in C++?	getrusage(2,3p)	0
27081445	14319435	Delayed NUnit Assert message evaluation	var constrain = Is.True.After(notificationPollingDelay);\nvar condition = constrain.Matches(() => eventData.Count == 0);\nAssert.IsTrue(condition, \n              "Received unexpected event with last event data" + \n              eventData.Last().Description());	0
6630270	6629263	How do I prevent decimal values from being truncated to 2 places on save using the EntityFramework 4.1 CodeFirst?	public class MyContext : DbContext\n{\n    public DbSet<Metrics> Metrics { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Metrics>().Property(x => x.PPM).HasPrecision(4, 3);\n    }\n}	0
31734580	31734431	C# - Web API - Serializing Enums as strings with spaces	public enum MyEnum\n{\n    [EnumMember(Value = "Type One")]\n    TypeOne,\n    [EnumMember(Value = "Type Two")]\n    TypeTwo,\n    [EnumMember(Value = "Type Three")]\n    TypeThree\n}	0
11308543	11308328	MOQ - SetupSequence	var firstTime = true;\n\n    mock.Setup(x => x.GetNumber())\n        .Returns(()=>\n                        {\n                            if(!firstTime)\n                                return 1;\n\n                            firstTime = false;\n                            return 0;\n                        });	0
13470420	13470375	Search the particular text in datagrid using C#	string sql2 = \n"Select * from builderScreenResourceBundleTBL where screenId like '%"+YourTextBox.Text+"%'";	0
21386172	21385076	MongoDB - Inserting the result of a query in one round-trip	collection.Database.Eval(new BsonJavaScript(@"\n  var count = db.test.count();\n  db.test.insert({ currentCount: count });\n");	0
3593839	3592845	Tracking open pages with ASP.Net	using (Mutex m = new Mutex(false, "Global\\TheNameOfTheMutex")) \n    {\n            // If you want to wait for 5 seconds for other page to finish, \n            // you can do m.WaitOne(TimeSpan.FromSeconds(5),false)\n\n            if (!m.WaitOne(TimeSpan.Zero, false))\n                Response.Write("Another Page is updating database.");\n            else\n                UpdateDatabase();                              \n\n    }	0
30293089	30288955	Call dynamic method from string	public void CallMethod(dynamic d, string n)\n    {\n        d.GetType().GetMethod(n).Invoke(d, null);\n    }	0
24786459	24786402	Can I access a secured network folder with Directory.GetFiles()?	using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())\n{\n    if (unc.NetUseWithCredentials("uncpath", user, domain, password))\n    {\n         //  Directory.GetFiles() here \n    }\n}	0
1125755	1125739	Access the Contents of a Web Page with C#	class Program\n{\n    static void Main(string[] args)\n    {\n        using (var client = new WebClient())\n        {\n            var contents = client.DownloadString("http://www.google.com");\n            Console.WriteLine(contents);\n        }\n    }\n}	0
17217392	17217163	Find if string contains value and then extract	string mystring = "My text and url http://www.google.com and some more text.";\n\nRegex urlRx = new Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);\n\nMatchCollection matches = urlRx.Matches(mystring);	0
11889037	11887747	Set Combobox dropdown to max columns of datatable	for (int i = 1; i < myDataTable.Columns.Count+1; i++)\n   {\n      comboBox1.Items.Add(i); \n   }	0
519510	518625	C# doubles show comma instead of period	Application.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");	0
9004231	9002847	C# - How to get list of USERs/GROUPs having access to shared folder on a Remote Machine	private bool CheckAccess(DirectoryInfo directory)\n{\n\n    // Get the collection of authorization rules that apply to the current directory\n    AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n\n    foreach (var rule in acl)\n    {\n        // do something here\n    }\n}	0
11769596	11769460	Get input with '/' character in url input	"http://site.com/user/{username}/{*path}"	0
26946834	26946789	How to set a constraint for a type so it must be of another generic typed type	public interface IUnitOfWork\n{  \n    //the newly added.\n    T GetInheretedRepository<T, TEntity>() where T : class, IRepository<TEntity>; \n}\n\npublic interface IRepository<TEntity>\n{\n    TEntity Resolve(); // dummy function, just to get the idea\n}	0
9210136	9209878	searching a particular setter programmatically	var formatSetter=dataRecord.Cells[i].EditorStyle.Setters.OfType<Setter>()\n    .FirstOrDefault(setter=>setter.Property.Name == "Format");\nif (formatSetter!=null)\n...	0
19628686	19583497	Problems in DropDownList with updatepanel	if(!IsPostBack) \n{  \n//Code when initial loading \n}\n else \n{ \n// code when post back \n}	0
31526837	31526400	RestSharp send Dictionary	var c = new RestClient(baseurl);\nvar r = new RestRequest(url, Method.POST);  // <-- must specify a Method that has a body\n\n// shorthand\nr.AddJsonBody(dictionary);\n\n// longhand\nr.RequestFormat = DataFormat.Json;\nr.AddBody(d);\n\nvar response = c.Execute(r); // <-- confirmed*	0
19428348	19428242	How to refer to a specific point in Chart Windows Form Control?	chart1.Series[0].Points[1].Item	0
2779149	2778875	Add data to a list box from a dropdown	void SelectedIndex_Changed(Object sender, EventArgs e) \n{\n    myListBox.Items.Clear();\n    myListBox.Items.Add(myDropDown.SelectedItem); \n}	0
27848111	27626889	Convert Unicode to Double Byte	public async Task<string> GetStringAsync(string IdArchivo)\n{\n    string FinalData = await Task.Factory.StartNew(() =>\n        {\n            string NData = string.Empty;\n            Byte[] BData = GetBinaryData(IdArchivo);\n            string SData = Encoding.UTF8.GetString(BData);\n            for (int i = 0; i < SData.Length; i++)\n            {\n                if (i > 0)\n                    i++;\n\n                if (i <= SData.Length - 1)\n                    NData += SData[i];\n            }\n            return NData;\n        });\n    return FinalData;\n}\n\npublic Byte[] GetBinaryData()\n{\n\n    // Just retrieve the file from my database \n}	0
2530511	2522025	Using empty row as default in a ComboBox with Style "DropDownList"?	public static void ComboFilter(ComboBox cb, DataTable dtSource, TextBox filterTextBox)\n{\n    cb.DropDownStyle = ComboBoxStyle.DropDownList;\n    string displayMember = cb.DisplayMember;\n    DataView filterView = new DataView(dtSource);\n    DataRowView newRow = filterView.AddNew();\n    newRow[displayMember] = "";\n    try { newRow.EndEdit(); }   // fails, if a column in dtSource does not allow null\n    catch (Exception) { }       // works, but the empty line will appear at the end\n    filterView.RowFilter = displayMember + " LIKE '%" + filterTextBox.Text + "%'";\n    filterView.Sort = displayMember;\n    cb.DataSource = filterView;\n}	0
12790048	12555049	Timer in Portable Library	internal delegate void TimerCallback(object state);\n\ninternal sealed class Timer : CancellationTokenSource, IDisposable\n{\n    internal Timer(TimerCallback callback, object state, int dueTime, int period)\n    {\n        Contract.Assert(period == -1, "This stub implementation only supports dueTime.");\n        Task.Delay(dueTime, Token).ContinueWith((t, s) =>\n        {\n            var tuple = (Tuple<TimerCallback, object>)s;\n            tuple.Item1(tuple.Item2);\n        }, Tuple.Create(callback, state), CancellationToken.None,\n            TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,\n            TaskScheduler.Default);\n    }\n\n    public new void Dispose() { base.Cancel(); }\n}	0
9755048	9754968	Accessing unmanaged memory by address allocated in COM / C++ from C# via Interop	IntPtr bAddr = new IntPtr( iAddr );  // bAddr = (byte**)iAddr\nIntPtr rAddr = new IntPtr(Marshal.ReadInt32(bAddr)); //rAddr = (*bAddr);\n\nbyte [] bArray = new byte [iSize];   \n// Marshal the array from an unmanaged to a managed heap.   \nMarshal.Copy( rAddr, bArray, 0, iSize );   \nfor (int i=0; i < iSize; i++)   \n   Console.WriteLine( bArray[i] );   \n\n// Release the unmanaged array.   \nMarshal.FreeCoTaskMem( rAddr );	0
10467717	10466330	Can't get multiple parameters to controller to work	routes.MapRoute(\n    name: "ContinueDonation",\n    url: "ContinueGiving/{id}/{personId}",\n    defaults: new { controller = "Donation", action = "ContinueDonation" },\n    constraints: new { id = @"\d+", personId = @"\d+" }\n);	0
14930936	14930820	Master/detail editing - passing value to detail model property	Html.BeginForm("Create","DealDetail", new { id = Model.DealID }, FormMethod.Post);	0
8610545	8610345	Get info from div tag	string data = @"\n<div class=""c1"">text1</div></br> \n<div class=""c2"">text2</div></br> \n<div class=""c3"">text3</div></br> \n";\n\nstring pattern = @"\n(?:class\=\x22)  # Match but don't capture the class= quote\n(?<Key>\w+)      # Get the key value\n(?:\x22>)        # MBDC the quote and >\n(?<Value>[^<]+)  # Extract the text into Value named capture group\n";\n\n// Ignore allows us to comment the  pattern; it does not affect regex processing!\nRegex.Matches(data, pattern, RegexOptions.IgnorePatternWhitespace)\n     .OfType<Match>()\n     .ToDictionary (mt => mt.Groups["Key"], mt => mt.Groups["Value"] )\n     .ToList()\n     .ForEach(kvp => Console.WriteLine ("Key {0} Value {1}", kvp.Key, kvp.Value));\n\n/* Output\nKey c1 Value text1\nKey c2 Value text2\nKey c3 Value text3\n*/	0
28165788	28165713	Check if a Windows ListBox contains a string c# ignorecase?	lstFieldData\n    A\n    B\n    C\n    D\n\n    if (!lstFieldData.Items.Contains(ItemValue.ToUpper()))\n            MessageBox.Show(ItemValue + "Item not found.");\nlstFieldData\na\nb\nc\nd\n    if (!lstFieldData.Items.Contains(ItemValue.ToLower()))\n            MessageBox.Show(ItemValue + "Item not found.");	0
14975816	14975781	How to set the Gridview row background color in asp.net	foreach (GridViewRow row in yourGridView.Rows) {\n      row.BackColor = Color.Green; \n }	0
31273901	31273353	Inserting multiple values between daterange into DB	if(IsPost){\n    DateTime pFrom = new DateTime();\n    DateTime pTo = new DateTime();\n\n    var bookedFrom = Request.Form["dateFrom"];\n    var bookedTo = Request.Form["dateTo"];\n\n    if(DateTime.TryParse(bookedFrom, out pFrom) && DateTime.TryParse(bookedTo, out pTo))\n    {\n        DateTime dateF = pFrom;\n        DateTime dateT = pTo;\n\n        var dates = new List<DateTime>();\n\n        for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))\n        {\n           dates.Add(dt);\n        }\n\n        foreach(var dat in dates){\n            db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (@0, @1, @2, @3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);\n        }\n    }\n    else\n    {\n        Response.Write("<script language=javascript>alert('Invalid date from : " + bookedFrom + " and date to : " + bookedTo + "');</script>"); \n    }\n}	0
30921058	30918963	Proper way to handle a group of asynchronous calls in parallel	await Task.WhenAll(services.Select(async s => {\n   Console.WriteLine("Running " + s.Name);\n   var _serviceResponse = await client.PostAsync(...);\n   Console.WriteLine(s.Name + " responded with " + _serviceResponse.StatusCode);\n}));	0
16537571	16536680	Modifying flood fill algorithm for specific task	if (GameArr[i - 1, j].BlockValue == old_Value) count++;\n       if (GameArr[i, j - 1].BlockValue == old_Value) count++;\n       if (GameArr[i + 1, j].BlockValue == old_Value) count++;\n       if (GameArr[i, j + 1].BlockValue == old_Value) count++;\n\n       if(count>2)\n            Destroy(i, j,GameArr[i,j].BlockValue,0);	0
4141913	1863564	How to capture HTTP packet with SharpPcap	TCPPacket packet = TCPPacket.GetEncapsulated(rawPacket);	0
9084203	9084147	Listening to the same Event from different sources	void Listen(UIElement element)\n{\n    if (pEnable) element.MouseDown += MyMouseDownEventHandler\n            else element.MouseDown -= MyMouseEventHandler;\n}	0
11276406	11275439	How to pass downloading file details into async callback method and showing the progressbar like x files out of y has been downloaded	internal class TrackDownloadState\n {\n    public string Filename;\n    public string Id;\n    public Uri Source;\n    // and so on, all the information you need\n }	0
33531738	33531528	Encoding type of byte[] from Weblient (with post)	var url = "https://www.binsearch.info/fcgi/nzb.fcgi?q=192636313";\nSystem.Net.ServicePointManager.Expect100Continue = false;\nusing (var client = new WebClient())\n{\n    var values = new NameValueCollection\n    {\n        { "action", "nzb" },\n        { "192636313", "checked" }\n    };\n    byte[] result = client.UploadValues(url, values);\n    var resultstring = new StreamReader(new GZipStream(new MemoryStream(result), CompressionMode.Decompress))\n                       .ReadToEnd();\n}	0
12894054	12893934	Save a browsed file to a pre-defined folder using c#	//detination filename\nstring newFileName = @"C:\NewImages\NewFileName.jpg";    \n\n// if the user presses OK instead of Cancel\nif (openFileDialog1.ShowDialog() == DialogResult.OK) \n{\n    //get the selected filename\n    string filename = openFileDialog1.FileName; \n\n    //copy the file to the new filename location and overwrite if it already exists \n    //(set last parameter to false if you don't want to overwrite)\n    System.IO.File.Copy(filename, newFileName, true);\n}	0
32720619	32719049	How to bind a List<string[]> to a DataGridView control?	dataGridView.DataSource = userNphotoValues\n    .Select(arr => new { UserName = arr[0], PhotoPath = arr[1] })\n    .ToArray();	0
19551893	19551857	How to add Intellisense description to an enum members c#	/// <summary>\n/// Account types enumeration\n/// </summary>\npublic enum AcoountTypeTransaction\n{\n    /// <summary>\n    /// This is the Debug  constant.\n    /// </summary>\n    [Description("Account type debit")]\n    Debit = 0,\n    /// <summary>\n    /// This is the Credit constant.\n    /// </summary>\n    [Description("Account type Credit")]\n    Credit = 1\n}	0
27542768	27542683	How to print invoice in a particular format on a thermal printer	string columnName = "...";\nif(columnName.Length > 60)\n{\n    graphic.DrawString(columnName_part1, new Font("Times New Roman", 10, FontStyle.Bold), new SolidBrush(Color.Black), startX, startY);\n    startY += 50;\n    graphic.DrawString(columnName_part2, new Font("Times New Roman", 10, FontStyle.Bold), new SolidBrush(Color.Black), startX, startY);\n}	0
12726519	12726480	NullReferenceException when trying to add in one-to-many relation	public Item() \n{\n    this.Sizes = new List<Size>();\n}	0
19088721	19088407	How to get Date Difference in textbox?	DateTime d1 = TextBox1.Text!=string.Empty?Convert.ToDateTime(TextBox1.Text): DateTime.MinValue;\nDateTime d2 = TextBox2.Text!=string.Empty?Convert.ToDateTime(TextBox2.Text):DateTime.MinValue;\nTimeSpan tspan= d2-d1;\nTextBox3.Text = tspan.TotalDays.ToString();	0
24450788	24450729	Getting selected Item in DataGrid in WPF	private void personelEntityDataGrid_SelectionChanged(object sender, RoutedEventArgs e)\n{\n    PersonelEntity pers = (PersonelEntity)personelEntityDataGrid.SelectedItem;\n    if(pers != null)\n    {\n    NameBox.Text = pers.Name; // I get exception here\n    AgeBox.Text = pers.Age.ToString();\n    PhoneNumberBox.Text = pers.PhoneNumber;\n    AddresBox.Text = pers.Address;\n    }\n\n}	0
14999384	14998539	where to put try/catch in 3 tier architecture	...\ncatch(FileNotFoundException fnfe)\n{\n    string m = String.Format("Cannot save changes. A FileNotFoundException occurred. Check the path '{0}' is valid, that your network is up, and any removable media is available. Please see inner exception.", path);\n\n    _log.Error(m, fnfe);\n\n    throw new StorageLifecycleException(m, fnfe);\n}	0
13224238	13218843	SQL Statement after adding parameters	public void OutputSQLToTextFile(SqlCommand sqlCommand)\n{\n        string query = sqlCommand.CommandText;\n        foreach (SqlParameter p in sqlCommand.Parameters)\n        {\n            query = query.Replace(p.ParameterName, p.Value.ToString());\n        }\n        OutputToTextFile(query);\n    }	0
7794425	7793726	How to return formatted text from a method call in wpf	protected override void OnRender(DrawingContext drawingContext)\n    {\n        this.formattedToolTip = new FormattedText(\n                (string)this.TextProperty,\n                System.Globalization.CultureInfo.CurrentCulture,\n                FlowDirection.LeftToRight,\n                new Typeface(\n                     new FontFamily("Arial"),\n                     FontStyles.Normal,\n                     FontWeights.Bold,\n                     FontStretches.Normal),\n                11,\n                new SolidColorBrush(Colors.Black));\n\n        drawingContext.DrawText(\n                this.formattedToolTip,\n                new Point(10, 10)); //// Margin of 10 pixels from top and left.\n    }	0
814027	814001	Convert JSON string to XML or XML to JSON string	// To convert an XML node contained in string xml into a JSON string   \nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\nstring jsonText = JsonConvert.SerializeXmlNode(doc);\n\n// To convert JSON text contained in string json into an XML node\nXmlDocument doc = JsonConvert.DeserializeXmlNode(json);	0
3041881	3041330	How to assign a numbering scheme to TreeNodes based on position	public static class Extensions\n    {\n        public static string GetPosition(this TreeNode node)\n        {\n            string Result = "";\n            BuildPath(node, ref Result);\n            return Result.TrimStart('.');\n        }\n        private static void BuildPath(TreeNode node,ref string path)\n        {\n            path = "." + node.Index + path;\n            if (node.Parent != null) \n                BuildPath(node.Parent, ref path);\n        }\n    }	0
6424553	6424420	How to Sort a List<> by a Integer stored in the struct my List<> holds	list.Sort((s1, s2) => s1.Score.CompareTo(s2.Score));	0
23179090	23178951	How To Make My Form Respond to Ctrl-Alt, in C#?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)    \n {\n    if (keyData == (Keys.Control | Keys.Alt ) \n    {\n       //Do Stuff here\n    }\n    return base.ProcessCmdKey(ref msg,keyData);\n }	0
1454381	1452120	Why does converting a datasource to a datatable prevent formating	DataColumn col1;\ncol1.DataType = Type.GetType("System.DateTime"); // or other type	0
14565322	14565289	How to save bmp as pdf?	void DrawImage(XGraphics gfx, int number)\n{\n  BeginBox(gfx, number, "DrawImage (original)");\n\n  XImage image = XImage.FromFile(jpegSamplePath);\n\n  // Left position in point\n  double x = (250 - image.PixelWidth * 72 / image.HorizontalResolution) / 2;\n  gfx.DrawImage(image, x, 0);\n\n  EndBox(gfx);\n}	0
19319351	19317698	How do I manage the configuration settings for a class library?	ProcessName.exe.config	0
13871474	13871148	Extract part of a big XML	IEnumerable<XElement> elements = xmlResponse.Root.Element("OutputXml").Element("Response").Elements("Product");\n\nforeach(XElement element in elements)\n{\n    // Do Work Here\n}	0
3414320	3414263	IEnumerable to string	var singleString = string.Join(",", _values.ToArray() );	0
6051924	6051875	is there any LINQ expression to convert a Datatable to a Dictionary	table.AsEnumerable()\n     .ToDictionary<int, string>(row => row.Field<int>(col1),\n                                row => row.Field<string>(col2));	0
24547268	24546604	How to check for empty textbox	foreach (Control child in this.Controls)\n    {\n        TextBox textBox = child as TextBox;\n        if (textBox != null)\n        {\n            if (!string.IsNullOrWhiteSpace(textBox.Text))\n            {\n                MessageBox.Show("Text box can't be empty");\n            }\n        }\n    }	0
28627981	28627640	INotifyChangedProperty dynamic implementation	using System.Runtime.CompilerServices;\n\nclass BetterClass : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n    // Check the attribute in the following line :\n    private void FirePropertyChanged([CallerMemberName] string propertyName = null)\n    {\n        var handler = PropertyChanged;\n        if (handler != null)\n            handler(this, new PropertyChangedEventArgs(propertyName));\n    }\n\n    private int sampleIntField;\n\n    public int SampleIntProperty\n    {\n        get { return sampleIntField; }\n        set\n        {\n            if (value != sampleIntField)\n            {\n                sampleIntField = value;\n                // no "magic string" in the following line :\n                FirePropertyChanged();\n            }\n        }\n    }\n}	0
1176868	1176846	How to Format a string to be a part of URL?	string cleaned = Regex.Replace(url, @"[^a-zA-Z0-9]+","-");	0
15571004	15570812	Convert date and time string to DateTime in C#	string strDateStarted = "Thu Jan 03 15:04:29 2013";           \nDateTime datDateStarted;\nDateTime.TryParseExact(strDateStarted, new string[] { "ddd MMM dd HH:mm:ss yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datDateStarted);\nConsole.WriteLine(datDateStarted);	0
25118138	25117662	ASP.NET Listbox not selecting multiple values	IEnumerator ie =  ListBox2.Items.GetEnumerator();\n\n    while (ie.MoveNext())\n    {\n        ListItem li = (ListItem)ie.Current;\n        //Use ListItem here\n    }	0
31702133	31702025	Finding symbol in text c#	var sign = System.Text.RegularExpressions.Regex.Match("<[>=]?|=|>=?|??=").Value;	0
4617329	4617124	How to consume WCF services without svcutil.exe?	ChannelFactory<IService>	0
6929591	6929542	How can I reformat a string to exclude leading zeros?	int.Parse(s).ToString();	0
10627188	10627141	How can I replace the contents of one List<int> with those from another?	OriginalPterodactylVals.Clear();\nChangedPterodactylVals.ForEach(val => { OriginalPterodactylVal.Add(val); });	0
316731	316727	Is a double really unsuitable for money?	double x = 3.65, y = 0.05, z = 3.7;\n        Console.WriteLine((x + y) == z); // false	0
6243209	6243137	Problem with backreferences in C#'s regex	Match m = Regex.Match(line, "<strong>Date</strong> - (?<date>.*) (?<time>.*)<br>");\nif( m.Success )\n{\n    date = m.Groups["date"].Value;\n    time = m.Groups["time"].Value;\n}	0
14622799	14622235	Show other view at application first launch	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n{\n    if (ApplicationFirstLaunched() == true)\n    {\n       NavigationManager.Current.Navigate(ApplicationView.DemoView);\n    }\n}	0
23766983	23766593	Adding a new table to existing database in mvc4	public class PlayerDBContext : DbContext\n{\n    public DbSet<Abbreviations> Abbrvs { get; set; }\n    public DbSet<Team> Teams{ get; set; }\n    //and any other context specific information OnModelCreating, SaveChanges, etc\n}	0
18013613	18013031	Bitmap to byte[] using Fopen	public static byte[] GetBytesWithMarshaling(Bitmap bitmap)\n{\n    int height = bitmap.Height;\n    int width = bitmap.Width;\n\n    //PixelFormat.Format24bppRgb => B|G|R => 3 x 1 byte\n    //Lock the image\n    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);\n    // 3 bytes per pixel\n    int numberOfBytes = width * height * 3;\n    byte[] imageBytes = new byte[numberOfBytes];\n\n    //Get the pointer to the first scan line\n    IntPtr sourcePtr = bmpData.Scan0;\n    Marshal.Copy(sourcePtr, imageBytes, 0, numberOfBytes);\n\n    //Unlock the image\n    bitmap.UnlockBits(bmpData);\n\n    return imageBytes;\n}	0
16507810	16500611	Problems creating a one-to-one relationship with an access database in c#	MSysRelationships.grbit	0
30308153	20570435	EWS Managed API find items with ItemID	EmailMessage email = EmailMessage.Bind(service, new ItemId(StringItemId));	0
19589090	19568993	How to implement EntitySetController Queryable ODATA with NHibernate as ORM and handle transaction as well?	using (var tx = session.BeginTransaction())\n{\n    // Do something\n    tx.Commit();\n}	0
15657433	15655210	How to merge two memory streams?	var streamOne = new MemoryStream();\nFillThisStreamUp(streamOne);\nvar streamTwo = new MemoryStream();\nDoSomethingToThisStreamLol(streamTwo);\nstreamTwo.CopyTo(streamOne); // streamOne holds the contents of both	0
31780913	31779439	Set Properties Dynamically WPF Applciation	Button option = sender as Button;\n\n Properties.Settings.Default[option.Name] = _margin;	0
15527457	15526797	SqlBulkCopy performance	SSPROP_FASTLOADOPTIONS -> ORDER(Column)	0
23912972	23912644	Accept Dynamic Changes in ASP.NET gridview	this.gv.DataBind();	0
8771062	8769803	How to show the Finished button in the quiz instead of Next button?	protected void Page_Load(object sender, EventArgs e)     \n{     \n    questionDetails.DataBind();  \n\n    if (questionDetails.PageCount == 1)       \n    {       \n        nextButton.Text = "Finished";       \n    }   \n}	0
4029710	4027343	Is there a way to enforce a minimum string length with NHibernate?	public class Product\n{\n    [Length(Min=3,Max=255,Message="Oh noes!")]\n    public virtual string Name { get; set; }\n}	0
4097680	1903246	Filtering NHibernate SubType with ICriterion	ICriteria crit = sess.CreateCriteria(typeof(Mammal));  \n   crit.Add( Expression.Not( Expression.Eq("class", typeof(DomesticCat)) ) );  \n   List mammals = crit.List();	0
7263942	7249481	How to reference a specific object from a list in a config file using .NET MVC with C#	User defaultPublicUser = null;\n        foreach (var newUserData in _configData.Users)\n        {\n            var newUser = new User(newSite, newUserData.FullName, newUserData.Login, newUserData.Password);\n            var userRole = newSite.UserRoles.First(ur => ur.Name == newUserData.UserRoleName);\n            if (newUserData.UserRoleName == "Public")\n            {\n                defaultPublicUser = newUser;\n            }\n            newUser.UserRoles.Add(userRole);\n            newUser.UserStatusType = _daoFactory.GetUserStatusTypeDao().GetById(UserStatusType.cActive);\n            _daoFactory.GetUserDao().Save(newUser);\n        }\n        _daoFactory.GetUserDao().FlushChanges();	0
15363759	15363586	Too many arguments using a String in MailSystem.Net	client.Login(user, "\"" + password + "\"");	0
7337023	7336932	How to convert Milliseconds to date format in C#?	DateTime date = new DateTime(long.Parse(ticks));\ndate.ToString("yyyy-MM-ddThh:mm:ssZ");	0
30801422	30801255	How to unit test FileStream's File.Open	class\n{   \n\n    void LoadNodes(IFileLoader loader)\n    {\n         using(var reader = loader.GetReader()) \n         {\n              var nodes = XmlReaderUtils.EnumerateAxis(reader, new[] { "Node", "ArticleGroup" });\n         }\n\n    }\n}	0
22757269	22756613	c# how to populate a complex object containing a list with sql	var result = from p in db.Persons\n             join r in db.Responsibilities on p.Id equals r.PersonId\n             where p.Id == IdImSearchingFor\n             group r.ResponsibleForId by p into g\n             select new Person \n             {\n                 Id = g.Key.Id, \n                 Name = g.Key.Name,\n                 ResponsibleFor = g.ToList()\n             };	0
4111379	4111362	Remove Image Source in silverlight for WP7	CanvasImg.Source = null;	0
9522823	9521527	When/how do I Unregister a RegisteredWaitHandle	Thread.Yield	0
11391229	11391137	How can I write an object to a binary file in C#?	if (newEmail.Attachments.Count > 0)\n{\n      for (int i = 1; i <= newEmail.Attachments.Count; i++)\n      {\n           newEmail.Attachments[i].SaveAsFile\n                (@"C:\TestFileSave\" +\n                newEmail.Attachments[i].FileName);\n      }\n}	0
30514232	30514153	how can I remove all words that start with sequence of characters	\bARC\S*\s*	0
16506997	16506900	Setting crystal report text field on FormLoad	TextObject txt1 = (TextObject)RaseedLayout.ReportDefinition.Sections["YOURSECTIONHERE"].ReportObjects["txtRepRaseedNumber"];\n\ntxt1.Text = "??????";	0
2039032	2038865	Can I convert bitmaps with OpenMP in C#?	public static Image ConvertToGrayScale(Image srce) {\n  Bitmap bmp = new Bitmap(srce.Width, srce.Height);\n  using (Graphics gr = Graphics.FromImage(bmp)) {\n    var matrix = new float[][] {\n        new float[] { 0.299f, 0.299f, 0.299f, 0, 0 },\n        new float[] { 0.587f, 0.587f, 0.587f, 0, 0 },\n        new float[] { 0.114f, 0.114f, 0.114f, 0, 0 },\n        new float[] { 0,      0,      0,      1, 0 },\n        new float[] { 0,      0,      0,      0, 1 }\n    };\n    var ia = new System.Drawing.Imaging.ImageAttributes();\n    ia.SetColorMatrix(new System.Drawing.Imaging.ColorMatrix(matrix));\n    var rc = new Rectangle(0, 0, srce.Width, srce.Height);\n    gr.DrawImage(srce, rc, 0, 0, srce.Width, srce.Height, GraphicsUnit.Pixel, ia);\n    return bmp;\n  }\n}	0
18925235	18924931	How To Run A Registry File With User Interaction In C#	System.Diagnostics.Process.Start("regedit.exe", "/s \""+strRegPath+"\"");	0
20518358	20493184	DataGridTemplateColumns, AutoGenerateColumns=true and binding to a DataTable	private DataTemplate GetDataTemplate(string columnName)\n{\n    string xaml = "<DataTemplate><ComboBox SelectedValue=\"{Binding Path=[" + columnName +\n                  "].SelectedEnumeratedElementItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\"" +\n                  " ItemsSource=\"{Binding Path=[" + columnName +\n                  "].Items}\" DisplayMemberPath=\"Name\"/></DataTemplate>";\n\n    var sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml));\n    var pc = new ParserContext();\n    pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");\n    pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");\n    var datatemplate = (DataTemplate)XamlReader.Load(sr, pc);\n\n    return datatemplate;\n}	0
8350080	8350036	I didn't close previous DataReader, but where?	using(OleDbDatareader read = command.ExecuteReader())\n{\n\n   ...\n\n}	0
4795577	4795483	How to remove more than one dot (.) from text?	string s = "10.20.30";\n        int n;\n        if( (n=s.IndexOf('.')) != -1 )\n            s = string.Concat(s.Substring(0,n+1),s.Substring(n+1).Replace(".",""));	0
25361507	25361442	How to return a subset of XElements inside parent XElement	var element = new XElement("ValidationResults",\n    doc.Element("ValidationResults")\n       .Elements("ValidationResult")\n       .Where(x => x.Element("Scheme").Value == "Scheme A")));	0
10502237	10497464	How to make this code faster?	Search:   abc def ghi jkl\nText:     abc def ghi klm abc def ghi jkl\ni=0:      abc def ghi jkl?\nskip 2:       XXX XXX  <--- you save two iterations here, i += 2\ni=2:                  abc?\ni=3:                      abc? ...	0
19360687	19360615	Sort list on 3 values	var result = MyCollection.OrderBy(x => x.CategoryCounter)\n                         .ThenBy(y => y.GroupCounter)\n                         .ThenBy(z => z.QuestionCounter);	0
33180514	33178562	UI disappearing after a few seconds	private void doBuild(object sender, TappedRoutedEventArgs e)\n{\n    Button myButton = new Button();\n    myButton.Width = 160;\n    myButton.Height = 72;\n    myButton.Content = "Click Me";\n    var margin = myButton.Margin;\n    margin.Top = 250;\n    margin.Left = 15;\n    myButton.Margin = margin;\n\n    Grid.SetColumn(myButton, 1);\n\n    LayoutRoot.Children.Add(myButton);\n    LayoutRoot.UpdateLayout();\n}	0
9184696	9172017	How do I connect to a locally installed OpenLDAP service?	var host = "localhost:389";\nvar credential = new NetworkCredential("user", "secret");\n\nusing (var con = new LdapConnection(host) { Credential = credential, AuthType = AuthType.Basic, AutoBind = false })\n{\n    con.SessionOptions.ProtocolVersion = 3;\n    con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(VerifyCertDelegate);\n    //con.SessionOptions.StartTransportLayerSecurity(new DirectoryControlCollection());\n    con.Bind()\n    //Do other ldap operations here such as setting the user password\n    var pass = "newpass";\n    var req = new ModifyRequest\n    {\n        DistinguishedName = "cn=user,ou=test,dc=example,dc=com"\n    };\n\n    var dam = new DirectoryAttributeModification\n    {\n        Name = "userPassword",\n        Operation = DirectoryAttributeOperation.Replace\n    };\n    dam.Add(pass);\n    req.Modifications.Add(dam);\n\n    con.SendRequest(req);\n}	0
7294551	7294233	Save video stream into the database's table	varbinary(MAX)	0
2011839	2011832	Generate Color Gradient in C#	int rMax = Color.Chocolate.R;\nint rMin = Color.Blue.R;\n// ... and for B, G\nvar colorList = new List<Color>();\nfor(int i=0; i<size; i++)\n{\n    var rAverage = rMin + (int)((rMax - rMin) * i / size);\n    // ... and for B, G\n    colorList.Add(Color.FromArgb(rAverage, gAverage, bAverage));\n}	0
25741136	25740888	Round down by a specific precision in C#	Math.Floor(value / precision) * precision	0
8436075	8436030	How to get data from a gridview at runtime on web form asp.net	Datatable dt = SomeMethodReturningDataTable();\n\nViewstate["Table"] = dt;\n\nGridView.DataSource = ViewState["Table"];\nGridview.DataBind();	0
5148581	5148411	Get objects with max value from grouped by linq query	var invadersOrderedInColumns = invaders\n    .GroupBy(d => d.GetPosition().X)\n    .Select(d => d.OrderByDescending(y => y.GetPosition().Y).First());	0
4683927	4683881	Parsing user provided enumeration values in C#	var type = Type.GetType("YourNameSpace.Color");\nvar belongs = Enum.GetNames(type).Any(o => o == "Red");	0
9874332	9874019	Converting from arabic string to hex html string in C#	string name = "????";\nforeach (char c in name)\n{\n    int value = (int)c;\n    string hex = value.ToString("X4");\n    Console.WriteLine("{0} : {1}", hex, c);\n}	0
29536988	29536588	How to map table names and column name different from model in onmodelcreating method in Entity Framework -6?	[Table("tbl_Student")]\npublic class Student\n{\n    [Column("u_id")]\n    public int ID { get; set; }\n}	0
10448765	10448448	How do I create hyperlinks from resource files?	myHyperLinkControl.NavigateUrl	0
21208214	21207937	DevExpress GridView | DataGridView	// Obtain the number of data rows. \nint dataRowCount = gridView.DataRowCount;\n// Traverse data rows  \nfor (int i = 0; i < dataRowCount; i++) {\n    object cellValue = gridView.GetRowCellValue(i, "... specify field name here ...");\n    // do something with cell Value\n\n}	0
34572294	34571778	How would I check to see if website a is online	async Task<Boolean> IsAvailable()\n{\n    string url = "http://www.google.com";\n    try\n    {\n        using (var client = new HttpClient())\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);\n            var response = await client.SendAsync(request);\n            if (response.IsSuccessStatusCode)\n            {\n                response.Dump();\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n    }\n    catch (Exception ex)\n    {\n      return false;\n    }\n}	0
10928493	10928402	How to make a method that is ran when webservice method ends?	private void WebMethodAction()\n    {\n        Execute(() =>\n        {\n            Console.WriteLine("Hello World");\n        });\n    }\n\n    private int WebMethodFunc(int a, int b)\n    {\n        return Execute(() =>\n        {\n            return (double)a / (double)b;\n        });\n    }        \n\n    public void Execute(Action action)\n    {\n        // call Execute<T> and discard result\n        Execute(() => { action.Invoke(); return true; });\n    }\n\n    public T Execute<T>(Func<T> func)\n    {\n        T result = func.Invoke();\n\n        // cleanup\n        Console.WriteLine("Cleanup");\n\n        return result;\n    }	0
25719215	25718375	Web API / WCF how keep object alive	[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]\npublic static class EngineContainer\n{\n    private static Engine _engine { get; set; }\n    public static Engine GetEngine \n    {\n        get { if (_engine == null) Init(); return _engine; }\n    }\n}	0
1090318	1090294	How to read arrays from file in C#	using ( Stream stream = new FileStream( @"C:\foo.txt", FileMode.Open ) )\nusing ( TextReader reader = new StreamReader( stream ) )\n{\n    string contents = reader.ReadToEnd( );\n    contents = contents.Replace( "{", "" ).Replace( "}", "" );\n    var values = new List<int>();\n    foreach ( string s in contents.Split( ',' ) )\n    {\n        try\n        {\n            values.Add( int.Parse( s ) );\n        }\n        catch ( FormatException fe )\n        {\n            // ...\n        }\n        catch ( OverflowException oe )\n        {\n            // ...\n        }\n    }\n}	0
5723012	5722095	Handling Nested JSON Object via Facebook C# SDK	dynamic result = fbApp.Api("/" + EventID);    \ndynamic street = result.venue.street;	0
2567608	2567573	How do I change the logged in user to another?	System.Security.Principal.WindowsImpersonationContext impersonationContext;\nimpersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();\n\n//Insert your code that runs under the security context of the authenticating user here.\n\nimpersonationContext.Undo();	0
20097689	20097625	c# - Find element value in an Object within a List within Dictionnary	var result = _reference.FirstOrDefault(x => \n                      x.Value.Any(z => z._element3 == "mySearch"));\nif (result.Key != null)\n    MyFirstObject mfo = result.Key;	0
29784330	29784230	the Construction of and passing of parameters of a method that searches a 2-d array filled with random numbers	public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)\n{\n    if(searchableArray.Any(x => soughtOutNum))\n    {\n        colsIndex = searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(0);\n        rowIndex= searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(1);\n    }\n    else\n    {\n        return false;\n    }        \n}	0
15320258	15316179	How to prevent a backspace key stroke in a TextBox?	string m_TextBeforeTheChange;\n    int m_CursorPosition = 0;\n    bool m_BackPressed = false;\n\n    private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)\n    {\n        m_TextBeforeTheChange = KeyBox.Text;\n        m_BackPressed = (e.Key.Equals(System.Windows.Input.Key.Back)) ? true : false;\n    }\n\n    private void KeyBox_TextChanged(object sender, TextChangedEventArgs e)\n    {\n        if (m_BackPressed)\n        {\n            m_CursorPosition = KeyBox.SelectionStart;\n            KeyBox.Text = m_TextBeforeTheChange;\n        }\n    }\n\n    private void KeyBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)\n    {\n        KeyBox.SelectionStart = (m_BackPressed) ? m_CursorPosition + 1 : KeyBox.SelectionStart;\n    }	0
11425892	11425826	How to split strings using C# and Linq	List<Set> sets;\nusing (var context = new MyDataContext())\n{\n    sets = context.Sets.ToList();\n}\n\nvar result = sets.SelectMany(s => \n    s.Members.Split(',').Select(m => new { s.ID, m }));	0
8689422	8689399	How to detect double click on window title in c#	#define WM_NCMBUTTONDBLCLK              0x00A9	0
15400136	15400109	Create copy of string formatted as date	// this is your original string\nstring _str = "20130101";\n\n// you need to convert it to valid DateTime datatype\n// so you can freely format the string to what you want\nDateTime _date = DateTime.ParseExact(_str, "yyyyMMdd", CultureInfo.InvariantCulture);\n\n// converting to your desired format, which is now a string\nstring _dateStr = _date.ToString("yyyy-MM-dd");	0
11463162	11462064	WPF TextBlock Text updates only once	public partial class MyWindow : Window\n{\n    static MyWindow()\n    {\n        EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.MouseEnterEvent, new MouseEventHandler(MyMouseEventHandler));\n    }\n\n    public MyWindow()\n    {\n        InitializeComponent();\n    }\n\n    static private void MyMouseEventHandler(object sender, MouseEventArgs e)\n    {\n        // To stop the tooltip from appearing, mark the event as handled\n        // But not sure if it is really working\n        e.Handled = true;\n\n        FrameworkElement source = e.OriginalSource as FrameworkElement;\n        if (null != source && null != source.ToolTip)\n        {\n            // This really disables displaying the tooltip. It is enough only for the current element...\n            source.SetValue(ToolTipService.IsEnabledProperty, false);\n\n            // Instead write the content of the tooltip into a textblock\n            textBoxDescription.Text = source.ToolTip.ToString();\n        }\n    }	0
7875328	7833410	Different behavior of Sharepoint controls on postback	protected override void RenderFieldForDisplay(HtmlTextWriter output)\n{\n  TextWriter writer = new StringWriter();\n  base.RenderFieldForDisplay(new HtmlTextWriter(writer));\n  string x=  writer.ToString();\n  string y= "&#160;";\n  string z= "<br/>";\n  x= x.Equals(y) ? x.Replace(y, string.Empty) : x.Replace(" ", y).Replace("\r\n", z).Replace("\n", z).Replace("\r", z);\n  output.Write(x);\n}	0
1675607	1675576	I want to detect when user close browser window?	function CloseSession( )\n{\n    location.href = 'SignOut.aspx'; \n}\nwindow.onbeforeunload = CloseSession;	0
5678325	5678230	declaring global variables from within a function?	public class ApplicationController\n{\n    public static IfaceClient2Server Server { get; set; }\n}	0
5833447	5819433	Access DropDownList in EditItemTemplate within GridView on GridView_RowEditing	In your rowdatabound Event handler\nCheck if the row is the edit row\nddl.Items.Clear()\nif (dataitem is textbox or ddl)\n   ddl.items.add("textBox");\n   ddl.items.add("DDL");\nelse\n   ddl.items.add("CB");\n   ddl.items.add("RB");	0
10717622	10716556	separate filenames string in windows explorer?	foreach ( string filePath in System.IO.Directory.EnumerateFiles ( pathOfDirectory ) )\n{\n    string filename = System.IO.Path.GetFileName ( filePath );\n    string id = filename.Substring ( 0 , filename.IndexOf ( '_' ) );\n    string extension = filename.Substring ( filename.LastIndexOf ( '.' ) + 1 );\n}	0
757386	757371	How do I call a subclass method on a baseclass object?	// obj is your object reference.\nobj.GetType().InvokeMember("MethodName", \n    System.Reflection.BindingFlags.InvokeMethod, null, obj, null /* args */)	0
10079134	10069647	Command names present in Quick access toolbar	FILENAME.exportedUI	0
27932872	27932833	VAT at my cost by 25% VAT	decimal parsed = 0, prisMoms = 0;\nvar canParse = decimal.TryParse(TextBoxpris.Text, out parsed);\n\nif(canParse)\n{\n  prisMoms = parsed + (parsed * 0.25m);\n}	0
11781143	11780576	Linq-select group from specific date	var today = DateTime.Now;\n\nvar result = mc.AttendingTypes\n             .Where(at => at.FromDate <= today)\n             .GroupBy(at => at.GroupId)\n             .Select(g => g.OrderByDescending(m => m.FromDate).FirstOrDefault())\n             .ToList();	0
16230378	16229834	How to use Outlook's AdvancedSerach to find expiring e-mail via assigned server policy	DateTime expirationDate = DateTime.Now.AddDays(30);\nstring expiresFilter = String.Format("urn:schemas:mailheader:expires>'{0}' AND urn:schemas:mailheader:expires<'{0}'", DateTime.Now, expirationDate);\nstring scope = "'" + inboxFolder.FolderPath + "'";\nOutlook.Search search = Globals.ThisAddIn.Application.AdvancedSearch(scope, expiresFilter, true, "Expiring Retention Policy Mail");	0
3621287	3617528	LabelFor htmlhelper MVC2: How can a propertyName by empty	metadata.DisplayName	0
31906347	31905645	Name To Decimal To Binary Algorithm	foreach (char ch in name)\n{\n    int decNumber = ch;\n    Console.WriteLine(decNumber);                \n    for (int i = 0; i < name.Length; i++)\n    {\n        Console.WriteLine("Enter a number:");\n        int a = Convert.ToInt32(Console.ReadLine());\n        var result = Convert.ToString(a, 2);\n        Console.WriteLine(result);\n    }             \n}	0
9492460	9492433	Need help using Moq	private void TestCreate()\n{\n    var mocker = new Mock<ISomeInterface>();\n    mocker.Setup(x => x.Create(It.IsAny<SomeClass>())).Returns(3);\n    var result = mocker.Object.Create(new SomeClass());\n}\n\nprivate void TestCreate()\n{\n    var mocker = new Mock<ISomeInterface>();\n    var someClass = new SomeClass();\n    mocker.Setup(x => x.Create(someClass)).Returns(3);\n    var result = mocker.Object.Create(someClass);\n}	0
24065363	24065178	How to add scroollbar to combo box items in c#	ComboBox cb = new ComboBox();\n        List<string> items = new List<string>();\n        items.Add("1");\n        items.Add("2");\n        items.Add("3");\n        items.Add("5");\n        items.Add("7");\n        items.Add("8");\n        cb.ItemsSource = items;\n        cb.MaxDropDownHeight = 20;\n        childGrid.Children.Add(cb);	0
11337635	11337565	String parsing and find common white space location	var stringList = new[] { "abc   xyz 123   456", "cba 1234a 45623 say", "avc  4567 bv    456" };\nvar shortest = stringList.OrderBy(s => s.Length).First();\nvar result = new Collection<int>();\n\nfor (int i = 0; i < shortest.Length; i++)\n{\n    if (stringList.All(c => c[i] == ' ')) result.Add(i+1);\n}\n\n// Test the results\nforeach (var index in result)\n{\n    Console.WriteLine(index);\n}	0
13886683	13886330	Read Excel First Column using C# into Array	public static string[] FirstColumn(string filename)\n    {\n        Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();\n\n        if (xlsApp == null)\n        {\n            Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");\n            return null;\n        }\n\n        //Displays Excel so you can see what is happening\n        //xlsApp.Visible = true;\n\n        Workbook wb = xlsApp.Workbooks.Open(filename,\n            0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);\n        Sheets sheets = wb.Worksheets;\n        Worksheet ws = (Worksheet)sheets.get_Item(1);\n\n        Range firstColumn = ws.UsedRange.Columns[1];\n        System.Array myvalues = (System.Array)firstColumn.Cells.Value;\n        string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray(); \n        return strArray;\n    }	0
22350551	22350358	select data more than 365 days old in linq	int number = 3;\nList<t_physical_inventory> Location = null;\n        Location = (from c in dc.t_physical_inventories\n                    where (c.dte_cycle_count == null \n                       || (DateTime.Now.Date - Convert.ToDateTime(c.dte_cycle_count))\n                               ).Days > 365) \n                       && (c.qty > 0)\n                    orderby (c.location)\n                    select c).Take(number).ToList();	0
7899697	7888871	Hyperlink keeps failing	e.handled = true;	0
20144223	20144122	Detect asp:FileUpload has a file using Jquery?	if (document.getElementById('<%= ImageUploader.ClientID %>').files.length === 0) \n{\n   // File upload do not have file\n}\nelse {\n   // File upload has file\n}	0
32047648	32047517	How to extract Icons from Exe or DLL byte array / memory stream?	MemoryStream stream = new MemoryStream(myByteArray);\n\n//and then load that MemoryStream with IconLib Load method:\n\nMultiIcon multiIcon = new MultiIcon();\nmultiIcon.Load(stream)\n\n//Iterate through different resolution icons under index 0\nList<Icon> iconList = new List<Icon>();\nforeach(IconImage iconImage in multiIcon[0])\n{\n iconList.Add iconImage.Icon\n}	0
4552867	4552825	Make method public for UNITTESTS build configuration	[assembly: InternalsVisibleTo("ProjectName.Tests")]	0
3410416	3223444	How to programmatically load a HTML document in order to add to the document's <head>?	public virtual void PopulateCssTag(string tags)\n{\n    // tags is a pre-compsed string containing all the tags I need.\n    this.Wrapper = this.Wrapper.Replace("</head>", tags + "</head>");\n}	0
25115495	25115124	How can I set selected in a ComboBox, based on ValueMember?	comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)	0
28034250	28033841	Convert to a custom DateTime type if DateTime.Parse fails	DateTime dt;\nif(DateTime.TryParse(someVar, out dt))\n   myObj.FinishDateField = dt;	0
20447434	20447316	Convert object to integer in hashtable	foreach (DictionaryEntry i in hashtable)\n{\n   if (i.Value is ?lke)\n   {\n       ?lke x = (?lke)i.Value;\n       Console.WriteLine(" " + x.?lke + " " + x.n?fus);\n   }\n }	0
23819988	23819530	More elegant way to add button to array	public partial class Form1 : Form\n{\n    Button[,] MovementPiece;  //Declare at the class level\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        MovementPiece = new Button[,]{ { button1, button2, button3 }, \n                          { button4, button5, button6 },\n                          { button7, button8, button9 }\n                        }; //Initialized in your Form Load event\n\n        // Do your button initialization here\n    }\n}	0
9506382	9506104	LINQ: Grouping By and Selecting from a List of objects based on max value	myItems.GroupBy(item => item.Name)\n       .Select(grp => grp.Aggregate((max, cur) => \n                            (max == null || cur.Date > max.Date) ? cur : max))	0
25484821	25484318	Using linq how to get counts of integer in my list	var num = (from c in list \nwhere c < 5\nselect c).Count();	0
8674934	8674830	Timer in C# to run once then after X sec run again	public bool StopRequested {get; set;}\n\nvoid timer_Tick(object sender, EventArgs e)\n{\n    if (timerRescan != null) timerRescan.Stop();\n    if (StopRequested) return;\n    try\n    {\n         ScanForIeInstances()\n    }\n    catch (Exception ex)\n    {\n         log.Warn("Exception 3", ex);\n    }\n    finally\n    {\n        timerRescan.Start();\n    }\n}	0
33434343	33433872	Zoom to mouse position like 3ds Max in Unity3d	if (Input.GetAxis("Mouse ScrollWheel") != 0)\n    {\n        RaycastHit hit;\n        Ray ray = this.transform.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);\n\n        if (Physics.Raycast(ray , out hit))\n        {\n            desiredPosition = hit.point;\n        }\n        else\n        {\n            desiredPosition = transform.position;\n        }\n\n        float distance = Vector3.Distance(desiredPosition , transform.position);\n        Vector3 direction = Vector3.Normalize( desiredPosition - transform.position) * (distance * Input.GetAxis("Mouse ScrollWheel"));\n\n        transform.position += direction;\n    }	0
28416254	28373879	Retrieve all instances of recurring event via CSOM	byte[] data = new ASCIIEncoding().GetBytes("{ 'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml': '<View><Query><Where><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">little test</Value></Eq></Where></Query></View>' } }");\n\n        HttpWebRequest itemRequest =\n            (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/Web/lists/getbytitle('" + listName + "')/getitems");\n        itemRequest.Method = "POST";\n        itemRequest.ContentType = "application/json; odata=verbose";\n        itemRequest.Accept = "application/atom+xml";\n        itemRequest.Headers.Add("Authorization", "Bearer " + accessToken);\n\n        itemRequest.ContentLength = data.Length;\n        Stream myStream = itemRequest.GetRequestStream();\n        myStream.Write(data, 0, data.Length);\n        myStream.Close();         \n\n        HttpWebResponse itemResponse = (HttpWebResponse)itemRequest.GetResponse();	0
2783766	2783718	How to call functions inside a C dll which take pointers as arguments from C#	[DllImport("Operations.dll")]\n    public static extern void Operation(\n        [MarshalAs(UnmanagedType.LPArray)]ushort[] inData, \n        int inSize1, int inSize2,\n        [MarshalAs(UnmanagedType.LPArray)]int[] outCoords,\n        ref int outCoordsSize);	0
23816074	23816016	Unit Test Specific Rows in a Datasource	[DeploymentItem("muhExcelFile.xlsx")]\n[DataSource("muhExcelDataSource")]\n[TestMethod]\npublic void UseAllRowsInThisMethod()\n{\n\n    if(rowVariable == testCondition)\n    {\n        //perform test\n    }\n\n\n}	0
7515452	7515101	How to delete two TreeNode at same time	if (fileText.EndsWith("_1"))\n            {\n                selectedFile.NextNode.Remove();\n                selectedFile.Remove();\n            }\n            else\n            {\n                selectedFile.PrevNode.Remove();\n                selectedFile.Remove();\n            }	0
22595166	22253935	Vertex Factory in Quickgraph GraphML deserialization	XName XNgraph = XName.Get("graph", "http://graphml.graphdrawing.org/xmlns");\nvar edges = xelement.Elements(XNgraph)	0
13139669	13139499	How to load the specific node from XML using C#	XElement doc = XElement.Load("yourStream.xml");\nXNamespace t="http://schemas.xmlsoap.org/ws/2005/02/trust";\nXNamespace a="urn:oasis:names:tc:SAML:2.0:assertion";\n\nvar lstElmVal=doc.Descendants(t+"RequestedSecurityToken")\n.Descendants(t+"Assertion")\n.Element(a+"AttributeStatement")\n.Elements(a+"Attribute")\n.Where(x=>x.Attribute("Name").Value=="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")\n.Select(y=>y.Value);\n\n//lstElmVal now contains your required data	0
5720660	5720557	Dynamically Change AJAX WaterMark Text	if (txtAccountName.Text == wmAccountName.WatermarkText)\n        txtAccountName.Text = string.Empty;	0
7536352	7513058	ASP.NET Chart Controls, is it possible to use a gradient on a pie chart?	Color[] myPalette = new Color[5]{ \n             Color.FromArgb(255,101,187,226), \n             Color.FromArgb(255,253,214,91), \n             Color.FromArgb(255,38,190,151), \n             Color.FromArgb(255,253,183,101),\n             Color.FromArgb(255,218,143,183)};\n\n        chart.Palette = ChartColorPalette.None;\n        chart.PaletteCustomColors = myPalette;\n\n        //Loop over the data and add it to the series\n        int i = 0;\n        foreach (var item in data)\n        {\n            chart.Series[0].Points.AddXY(item.Key, Convert.ToDouble(item.Value));\n            chart.Series[0].Points[i].BackGradientStyle = GradientStyle.Center;\n            chart.Series[0].Points[i].Color = myPalette[i];\n            chart.Series[0].Points[i].BackSecondaryColor = LightenColor(myPalette[i]);\n            //chart.Series[0].Points[i].SetCustomProperty("Exploded","true");\n\n            i++;\n        }	0
22171930	22171767	How to read textfile line by line into RichTextbox	List<string> lines = File.ReadLines ("E:\\vikas\\abc.txt").ToList();\n\nforeach (string current in lines)\n{\n    richTextBox1.Text += current;\n}	0
11341572	11203524	Newly created item field values	public static Dictionary<string, string> GetFieldsAndValuesOfCreatedItem(object item)\n{\n    var propertyInfoList = item.GetType().GetProperties(BindingFlags.DeclaredOnly |\n                                                            BindingFlags.Public |\n                                                            BindingFlags.Instance);\n\n    var list = new Dictionary<string, string>();\n\n    foreach (var propertyInfo in propertyInfoList)\n    {\n        var valueObject = propertyInfo.GetValue(item, null);\n        var value = valueObject != null ? valueObject.ToString() : string.Empty;\n\n        if (!string.IsNullOrEmpty(value))\n        {\n            list.Add(propertyInfo.Name, value);\n        }\n    }\n\n    return list;\n}	0
5418187	829983	How to convert a sbyte[] to byte[] in C#?	sbyte[] signed = { -2, -1, 0, 1, 2 };\nbyte[] unsigned = (byte[]) (Array)signed;	0
263525	263518	C# Uploading files to file server	File.Copy(filepath, "\\\\192.168.1.28\\Files");	0
15799052	15751927	Combine two datasets in one Crystal Report	Pm-Table.account-ID	0
21855183	21854920	Add bitmap resources to list	FlopCard1.Image = (Bitmap)Resources.ResourceManager.GetObject("h4", Resources.Culture);	0
34332028	34330781	How to dynamically update picturebox picture using pictures from resources without using "My" statement	try\n{\n    string[] images = { @"Resource\picture1", @"Resource\picture2" };\n    this.pictureBox1.Image = Image.FromFile(images[0]);\n}\ncatch (Exception e)\n{\n    Console.WriteLine(e.Message);\n}	0
25766801	25766213	Loading Xml File Into Section, Key and Value Collection	var attributes = from attribute in root.Elements().Attributes()\n                 select new SettingsEntry()\n                 {\n                   Section = attribute.Parent.Name.LocalName,\n                   Key = attribute.Name.LocalName,\n                   Value = attribute.Value\n                 };\nreturn attributes.ToList();	0
9016777	9016738	Dialog in WPF dissapears when clicking on application icon in taskbar	nrDialog.Owner = this;	0
15733983	15733925	Group some strings of a list by every x index occurance	var group0 = strings.Where((s, i) => (i/rotation)%2 == 0).ToArray();\nvar group1 = strings.Where((s, i) => (i / rotation) % 2 == 1).ToArray();	0
18875010	18874697	How to Validate users by SqlDataSource Control?	protected void cmdLogin_Click(object sender, EventArgs e)\n{\n    DataView dView = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);\n    if (dView.Count == 1)\n        Response.Redirect("~/Default.aspx");\n    else\n        lblError.Text="Incorrect username or password!";\n}	0
7967771	7967724	Unable to make arrays in a list/arraylist	var olData = new string[7];  // create first array\nolData[0] = ...  // etc\nol.Add(olData);  // add first array\n\nolData = new string[7];  // create second array\nolData[0] = ...  // etc\nol.Add(olData);  // add second array\n\n// ...	0
32472900	32472512	ComboBox Color Picker with LivePreview, set up itemssource at ComboBox	new SolidColorBrush(System.Windows.Media.Colors.Blue);	0
17090254	17088091	Get sum of objects before with linq	using System;\nusing System.Collections.Generic;\n\nstatic class MyExtensions\n{\n    public static IEnumerable<TResult> AggregatingSelect<TItem, TAggregate, TResult>(\n        this IEnumerable<TItem> items,\n        Func<TItem, TAggregate, TAggregate> aggregator,\n        TAggregate initial,\n        Func<TItem, TAggregate, TResult> projection)\n    {\n        TAggregate aggregate = initial;\n        foreach (TItem item in items)\n        {\n            aggregate = aggregator(item, aggregate);\n            yield return projection(item, aggregate);\n        }\n    }\n\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var numbers = new[] { 3, 1, 4, 9 };\n        var result = numbers.AggregatingSelect(\n            (int item, int agg) => item + agg, \n            0, \n            (int item, int agg) => agg);\n        Console.WriteLine(string.Join(",", result));\n    }\n}	0
3431670	3431617	Creating Dynamic Predicates- passing in property to a function as parameter	public Predicate<Feature> GetFilter<T>(\n    Expression<Func<Feature, T>> property,\n    T value,\n    string condition)\n{\n    switch (condition)\n    {\n    case ">=":\n        return\n            Expression.Lambda<Predicate<Feature>>(\n                Expression.GreaterThanOrEqual(\n                    property.Body,\n                    Expression.Constant(value)\n                ),\n                property.Parameters\n            ).Compile();\n\n    default:\n        throw new NotSupportedException();\n    }\n}	0
10161458	10161400	C# Changing the value of an element in a list of type Rectangle	Rectangle ri = Rectangles[i];\nRectangle rt = Rectangles[t];\n\nRectangle[i] = new Rectangle( rt.Left, ri.Bottom, rt.Height, rt.Width );	0
12268548	12268483	C# Linq query with where clause query containing a dynamic variable	public query(int myYear, int myMonth){\n               DateTime my = new DateTime(myYear,myMonth,1);\n               var context = new MCSSUtility.Entities();\n               return context.FBApis.Where(p => EntityFunctions.CreateDateTime(p.year, p.month, 1, 0, 0, 0)  >= my);\n            }	0
13579580	13545635	How can I get the Twitter follower screenNames of a given Username with Twitterizer?	foreach (var follower in followers.ResponseObject)\n        {\n            follower.ScreenName;\n        }	0
21503186	21493553	Get/Set Workflow Variable from uiTypeEditor	var processParms = WorkflowHelpers.DeserializeProcessParameters(buildDefinition.ProcessParameters);\n\nobject obj;\nprocessParms.TryGetValue("MyOtherVariable", out obj);\nMyOtherVariable myOtherVariable = obj as MyOtherVariable;	0
276202	276166	nested linq queries, how to get distinct values?	var rootcategories2 = (from p in sr.products\n                               group p.subcategory by p.category into subcats\n\n                               select subcats);	0
19463580	19462253	How to change row color in datagridview after checkbox is selected	if (isSelect)\n{\n    // Change row color\n    var row = this.dataGridView1.Rows[e.RowIndex]\n    row.DefaultCellStyle.BackColor = Color.Red;\n}	0
4619293	4619277	Get url parts without host	new Uri(someString).PathAndQuery	0
5289586	5289242	iSingleResult row count	FooterText.Value = "";\nforeach (var dataRow in FooterC)\n{\n   FooterText.Value = dataRow.ExtraText;\n}	0
14688878	14572226	hiding a button from a plugin toolbar	var commandBars = ((CommandBars)_dte2.CommandBars);\nif (commandBars == null)\n{\n    return;\n}\nvar commandBar = commandBars["MyPluginProductName"];\nif (commandBar == null)\n{\n    return;\n}\nvar startButton = commandBar.Controls["startCommand"];\nif (startButton == null)\n{\n    return;\n}\nstartButton.Visible = false;	0
14577280	14576649	Printing multiple document in c# window application	e.HasMorePages = true;	0
31743899	31743720	Get date range after date selection	private IQueryable<Insurer> GetInsurers(DateTime UserSelectedDate)\n{\n    return db.Insurers(dt=> UserSelectedDate >= dt.StartDate && UserSelectedDate <= dt.StopDate)\n}	0
10925066	10921244	Truncating an Oracle Temp Table in a Transaction, Truncates *ALL* Temp Tables	create global temporary table test1 (n number) on commit delete rows;\ninsert into test1 values (1);\n--Expected: 1\nselect count(*) from test1;\ncommit;\n--Expected: 0\nselect count(*) from test1;\ninsert into test1 values (2);\n--Expected: 1\nselect count(*) from test1;\ncreate global temporary table test2 (n number) on commit delete rows;\n--Expected: 0\nselect count(*) from test1;\ncommit;\n--Expected: 0\nselect count(*) from test1;	0
1258816	1223194	Loading Subrecords in the Repository Pattern	userRepository.FindRolesByUserId(int userID)\nuserRepository.AddUserToRole(int userID)\nuserRepository.FindAllUsers()\nuserRepository.FindAllRoles()\nuserRepository.GetUserSettings(int userID)	0
33269355	33268809	how can I add a value to the list from the Dictionary<int,Object> and the list is in the Object	dic[key].AddressBook.Add(new ContactNumber(666));	0
10846811	10846550	Disappointing performance with Parallel.For	int[] nums = Enumerable.Range(0, 1000000).ToArray();\n        long total = 0;\n\n        // Use type parameter to make subtotal a long, not an int\n        Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>\n        {\n            subtotal += nums[j];\n            return subtotal;\n        },\n            (x) => Interlocked.Add(ref total, x)\n        );	0
18887270	18886945	Reading a text file and inserting information into a new object	string line;\n    List listOfPersons=new List();\n\n    // Read the file and display it line by line.\n    System.IO.StreamReader file = \n        new System.IO.StreamReader(@"c:\yourFile.txt");\n    while((line = file.ReadLine()) != null)\n    {\n        string[] words = line.Split(',');\n        listOfPersons.Add(new Person(words[0],words[1],words[2]));\n    }\n\n    file.Close();	0
29978928	29978847	JsonConverter JsonWriter object in object	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n{\n    var list = value as List<ItemClass>;\n\n    writer.WriteStartObject();           // << Added\n    writer.WritePropertyName("items");   // << Added\n\n    writer.WriteStartArray();\n    foreach (var item in list)\n    {\n        writer.WriteStartObject();\n        writer.WritePropertyName(item.Id);\n\n        writer.WriteStartObject();\n        writer.WritePropertyName("data");\n        writer.WriteValue(item.Data);\n        //writer.WriteEndObject();       // << Removed\n\n        //writer.WriteStartObject();     // << Removed\n        writer.WritePropertyName("description");\n        writer.WriteValue(item.Description);\n        writer.WriteEndObject();\n\n        writer.WriteEndObject();\n    }\n    writer.WriteEndArray();\n\n    writer.WriteEndObject();             // << Added\n}	0
11798706	11798511	Format a number in a Textbox on Enter key press	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar == '\r')\n    {\n        decimal value;\n        if (decimal.TryParse(\n            textBox1.Text,\n            NumberStyles.Any,\n            CultureInfo.InvariantCulture,\n            out value))\n        {\n            textBox1.Text = value.ToString(\n                "### ### ##0.00",\n                CultureInfo.InvariantCulture).TrimStart().Replace(".", ",");\n        }\n    }\n}	0
3549892	3549796	Calling an old OLE component from C#	var type = Type.GetTypeFromProgID(progIdString);\nvar obj = Activator.CreateInstance(type);\nvar server = (IComponentServer)obj;	0
2634555	2634531	C# Wrapping an application within another application	Assembly.Load(rawBytes)	0
10373827	10373561	Convert a number to a letter in C# for use in Microsoft Excel	static string GetColumnName(int index)\n{\n    const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\n    var value = "";\n\n    if (index >= letters.Length)\n        value += letters[index / letters.Length - 1];\n\n    value += letters[index % letters.Length];\n\n    return value;\n}	0
19206939	19206125	Accessing User Password in DNN API	System.Web.Security.Membership.ValidateUser(username,password)	0
7497873	7497786	Passing null as SQLParameter DateTime value	SqlParameter moFrom1Param = new SqlParameter("@MoFrom1", dTOForwarding.MoFrom1 == null ? DBNull.Value : dTOForwarding.MoFrom1);\n            moFrom1Param.IsNullable = true;\n            moFrom1Param.Direction = ParameterDirection.Input;\n            moFrom1Param.SqlDbType = SqlDbType.DateTime;\n            cmd.Parameters.Add(moFrom1Param);	0
267637	267603	Binding source is string with path to property	public partial class Window1 : Window\n{\npublic MyClass2 MyClass2Object { get; set; }\npublic Window1()\n{\n// use data context instead of source\nDataContext = this;\n\nInitializeComponent();\n\nMyClass2Object = new MyClass2();\nBinding binding = new Binding();\nbinding.Path = new PropertyPath("MyClass2Object.StringVar");\nTextBoxFromXaml.SetBinding(TextBox.TextProperty, binding);\n}\n}\n\npublic class MyClass2\n{\npublic string StringVar { get; set; }\npublic MyClass2()\n{\nStringVar = "My String Here";\n}\n}	0
4831996	4831783	Updating the DisplayMember of a ListBox	// untested\n e.Value = (e.Item as MyClass).DisplayValue;	0
13348248	13348218	Generic Parameter. How to pass in to a constructor and then add to a list?	class ExpiryList<TAnyType>\n{\n    protected ConcurrentDictionary <TAnyType, DateTime> m_list;\n\n    ExpiryList(TAnyType obj, DateTime expiryDate)\n    {\n        m_list.AddOrUpdate(obj, expiryDate, (x, y) => { return expiryDate; });\n    }\n}	0
26913962	26913760	How to access recorded video in WP 8.1 app	StorageFile mediafile = await Windows.Storage.KnownFolders.VideosLibrary.GetFileAsync("cameraCapture.mp4");\nvar stream = await mediafile.OpenAsync(Windows.Storage.FileAccessMode.Read);\nVideoLeinwand.SetSource(stream, mediafile.ContentType);\nVideoLeinwand.Play();	0
8623110	8622977	Set Eval in Code Behind	btnProcess.CommandArgument =  DataBinder.Eval(e.Row.DataItem, "intId") & " ~ " & DataBinder.Eval(e.Row.DataItem, "IdECompleted")	0
13278876	13278778	How to use XElement.Parse and then find the value of a specific element?	XNamespace ns = "http://schemas.microsoft.com/HPCS2008R2/common";\n\nvar value = (string)XDocument.Parse(input)\n    .Descendants(ns + "Property")\n    .Where(p => (string)p.Element(ns + "Name") == "State")\n    .Elements(ns + "Value").FirstOrDefault();	0
17378389	17373772	getting the value from a column in a stored procedure via select statement	string storagePath = stuSubSvc.RetrieveInformation(elementId, submission)\n  .Select(s => s.StoragePath).SingleOrDefault();	0
7253291	7253216	Add three numbers with textBox	int result = \n  int.Parse(textBox1.Text) + \n  int.Parse(textBox2.Text) + \n  int.Parse(textBox3.Text);\ntextBox4.Text = result.ToString();	0
7591104	7591067	Create a thumbnail from only part of an image	using(Bitmap bitMap = (Bitmap)Image.FromFile("myimage.jpg")) // assumes a 400 * 300 image from which a 160 * 120 chunk will be taken\n{\n\nusing(Bitmap cropped = new Bitmap(160,120))\n{\n\n  using(Graphics g=Graphics.FromImage(cropped))\n  {\n\n    g.DrawImage(bitMap, new Rectangle(0,0,cropped.Width,cropped.Height),100,50,cropped.Width,cropped.Height,GraphicsUnit.Pixel);\n\n\n    cropped.Save("croppedimage.jpg",ImageFormat.Jpeg);\n  }\n}\n}	0
15902764	15902593	Relationship between access file table and sql server table	[...]\nusing (var bulkCopy = new SqlBulkCopy(destinationConnection))\n{             \n bulkCopy.ColumnMappings.Add("name", "nameperson"); //THIS A MAPPING REPLACE IT WITH YOUR NEED\n bulkCopy.DestinationTableName = "profile2";\n[....]	0
10060457	10006112	HTML Agility Pack - Get Text From 1st STRONG Tag Inside SPAN Tag	var nodes = doc.DocumentNode.SelectNodes("//span[@class='advisory_link']//strong[1]");\n\n        if (nodes != null)\n        {\n            foreach (var node in nodes)\n            {\n                string Description = node.InnerHtml;\n                return Description;\n            }\n        }\n\n        return null;	0
12352466	12352186	C# ASP Control Panel Link Visible Only To Role Admin	private void Page_Load (object sender, System.EventArgs e)\n{\n    // ... previous code ...\n\n    // Add the following code:\n    if (Context.User.IsInRole("Admin"))\n    {\n        myLink.Visible = true;\n    }\n    else\n    {\n        myLink.Visible = false;\n    }\n\n    // ... following code ...\n}	0
11023503	11023378	c# how to open a binary file and store it in a 16 bit buffer	using (var inputStream = File.Open(inputFile))      \nusing (var reader = new BinaryReader(inputStream))      \n{           \n    int index = 0;\n    while (inputStream.Position < inputStream.Length)\n        pixelBuffer[index++] = reader.ReadInt16();      \n}	0
27462045	27461981	Method always returns void in Windows Phone application	userService.UserServiceClient userService = new UserService.UserService Client();\nuserService.LogInCompleted += (a, ae) =>\n {\n    if (ae.Result != null)\n    {\n       bool exists = ae.Result;\n    }\n  };\nuserService.LogInAsync(login, password);	0
8066709	8066634	System beep on Windows 7	Console.Beep()	0
26584832	26584202	Connecting To A Website To Look Up A Word(Compiling Mass Data/Webcrawler)	var dom = CQ.CreateFromUrl("http://www.jquery.com");\nstring definition = dom.Select(".definitionDiv").Text();	0
32081994	32081550	Entity framework dynamic table name part	public class Item\n{\n  //...\n}\n\npublic class YourContext: DbContext \n{\n    private string suffix="_2015";\n\n    public SchoolDBContext(string _suffix): base() \n    {\n       this.suffix=_suffix;\n    }\n\n    public DbSet<Item> Items{ get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n         // Map an Entity Type to a Specific Table in the Database\n         modelBuilder.Entity<Item>().ToTable("Item"+suffix);\n\n        base.OnModelCreating(modelBuilder);\n    }\n}	0
23843201	23843178	Read SortedList from Hashtable	SortedList sortedList = (SortedList)ht["root"];\n\nobject value = sortedList[test];	0
8213113	8162099	Reading exe in windows c#	Assembly SampleAssembly = Assembly.LoadFrom("Assembly path here");\n\n            // Display all the types contained in the specified assembly.\n            foreach (Type oType in SampleAssembly.GetTypes())\n            {\n                Console.WriteLine(oType.Name);\n            }	0
5485963	5485896	My main method exits with a TypeLoadException	HKLM\Software\Microsoft\Fusion\ForceLog	0
4210147	4209964	Store data into Objects based on the input C#	string productChoice = "auto";\nOrder nwOrder = new Order();\nProducts nwProducts = new Products();\nnwOrder.products = nwProducts;\nproductChoiceType nwPCT = new productChoiceType();\nif(productChoice == "auto") {   \n  AutoDataprefill adp = new AutoDataprefill();\n  //adp.Parameter = ...\n  //adp.Pnc = ...\n  nwPCT.auto_dataprefill = adp;\n}\nelse if (productChoice == "vehicle")\n{\n  // etc...\n}\nnwProducts.products = nwPCT;	0
30583381	30583317	how to have a function containing a sub function in C#	static void Main(string[] args)\n{\n      int x = 0;\n      Action act = ()=> {\n        x +=2;\n      };\n\n\n      act();\n      x += 1;\n      act();\n      // x would equal 5 here\n      Console.WriteLine(x);\n}	0
5964856	5964827	C#, Get latest selected value from one of two ListBoxes	ListBox lb = (ListBox)sender;\nvar item = lb.SelectedItem;	0
12525287	12525270	Next larger integer after dividing	int i = (int)Math.Ceiling(d1/d2);	0
659451	659183	How do I get the month number from the year and week number in c#?	static int GetMonth(int Year, int Week)\n{\n    DateTime tDt = new DateTime(Year, 1, 1);\n\n    tDt.AddDays((Week - 1) * 7);\n\n    for (int i = 0; i <= 365; ++i)\n    {\n        int tWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(\n            tDt, \n            CalendarWeekRule.FirstDay, \n            DayOfWeek.Monday);\n        if (tWeek == Week)\n            return tDt.Month;\n\n        tDt = tDt.AddDays(1);\n    }\n    return 0;\n}	0
19217894	19217573	C++ format placeholders equivalent in c#	string st = string.Format("{0:000000} and {1:000000}", 123 ,456);\n//st => 000123 and 000456	0
355029	355020	Formatting double as string in C#	string s;\ndouble epislon = 0.0000001; // or however near zero you want to consider as zero\nif (Math.Abs(value) < epislon) {\n    int digits = Math.Log10( Math.Abs( value ));\n    // if (digits >= 0) ++digits; // if you care about the exact number\n    if (digits < -5) {\n       s = string.Format( "{0:0.000000000}", value );\n    }\n    else if (digits < 0) {\n       s = string.Format( "{0:0.00000})", value );\n    }\n    else {\n       s = string.Format( "{0:#,###,###,##0.000}", value );\n    }\n}\nelse {\n    s = "0";\n}	0
20582684	20498331	How to switch between multiple, same schema, databases in my .edmx EF model?	public partial class MyDatabaseEntities : DbContext\n{\n    public MyDatabaseEntities(string connectionString)\n        : base(connectionString)\n    {\n    }\n}	0
18907952	18895864	How to use foreach for the textboxes in a panel	if (inglist.SelectedIndex > -1 && rows > 0 && SelectedExist == false)\n{\n\n    foreach (Control txt in mypanel.Controls.Cast<Control>().OrderBy(c => c.TabIndex))\n    {\n        if (txt is TextBox && txt.Text == "")\n        {\n            txt.Text = CmpStr;\n            break;\n        }\n        else\n        {\n            if (txt is TextBox && txt.Text == CmpStr)\n            {\n                break;\n            }\n        }\n    }\n}	0
20560609	20558490	Errors when retrieving values from database determined by combobox to gridview	SqlDataAdapter daS = new SqlDataAdapter("select cName, cDetails, cDetails2 from ComDet where cName = @name", conn);\ndaS.SelectCommand.Parameters.Add("@name", SqlDbType.VarChar).Value = ListU.SelectedValue;	0
14746094	14746069	How to change the color of a pixel in an image	test.SetPixel(where.X, where.Y, Color.FromArgb(0x78FF0000));	0
1180124	1179031	How to keep application shortcuts current/in sync?	Sub ReplaceShortcut (folder, target, targetTarget)\n  set oFso = CreateObject("Scripting.FilesystemObject")\n  Set oFolder = oFso.GetFolder(folder)\n  Set oFiles = oFolder.Files\n\n  For Each oFile In oFiles\n\n    If LCase(oFso.GetExtensionName(oFile.name)) = "lnk" Then\n        Set oLnk = oShell.CreateShortcut(oFile.path)\n        If instr(1, oLnk.TargetPath, target, 1)<>0 Then\n            oLnk.TargetPath = replace(oLnk.TargetPath, target, targetTarget)\n            oLnk.Save\n        End If\n    End If\n  Next\nEnd Sub	0
220553	220202	How do you run a program you don't know where the arguments start?	Process myProcess = New Process;\nmyProcess.StartInfo.FileName = "cmd.exe";\nmyProcess.StartInfo.Arguments = "/C " + cmd;\nmyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nmyProcess.StartInfo.CreateNoWindow = True;\nmyProcess.Start();\nmyProcess.WaitForExit();\nmyProcess.Close();	0
7200773	7200652	How to Moq a FtpDataStream	string csvdata = "1,2,3,4,5":\nvar ms = new MemoryStream(Encoding.UTF8.GetBytes(csvdata));\nms.Position = 0;\n_ftpConnection.Setup(m => m.FtpConnect(It.IsAny(), It.IsAny())).Returns(ms);	0
13656253	13651718	How to set default value to asp textbox in radgrid while the texbox is data binded	protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)\n{\n    if (e.Item is GridEditableItem && e.Item.IsInEditMode)\n    {\n        GridEditableItem item = e.Item as GridEditableItem;\n        TextBox txtFormat = (item.FindControl("txtFormat") as TextBox);\n        txtFormat.Text = "Your text";\n    }\n}	0
22362873	22362257	How to draw a square	public void DrawSquare(int sideLength)\n{\n  for(int row = 1; row <= sideLength; row++)\n  {\n     for (int col = 1; col <= sideLength; col++)\n     {\n       if (col <= row) \n         Console.Write('*');\n       else\n         Console.Write('#');\n     }\n     Console.WriteLine();\n  }\n}	0
31624725	31624670	Reading string elements in C#	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(htmltablestring);\n\nforeach (HtmlNode table in doc.DocumentNode.SelectNodes("//table[@id='table2']")) { \n\n streamWriter.WriteLine(table.OuterHtml);\n\n}	0
29578830	24724343	Get file info from NTFS-MFT reference number	[DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )]\ninternal static extern SafeFileHandle CreateFile( string lpFileName, EFileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile );\n\n[DllImport( "kernel32.dll", SetLastError = true )]\ninternal static extern SafeFileHandle OpenFileById( IntPtr volumeHandle, ref FileIdDescriptor lpFileId, uint dwDesiredAccess, uint dwShareMode, uint lpSecurityAttributes, uint dwFlagsAndAttributes );	0
11715377	11715062	Unable to open Excel file after executing Program	Excel.Application XlApp = null;\n        Excel.Workbook workbook = null;\n        Excel.Worksheet Ws = null;\n        Excel.Range Range1 = null;\n        Excel.Worksheet X = null;\n\n        XlApp = new Excel.Application();\n        XlApp.Visible = true;\n        workbook = XlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);\n        Ws = (Excel.Worksheet)workbook.Worksheets[1];\n        XlApp.WindowState = XlWindowState.xlMaximized;\n\n\n                Ws = (Excel.Worksheet)workbook.Worksheets[1];\n\n                Ws.Activate();\n                Ws.Name = "MyFirstSheet";\n\n\n\n              int rowIndex = 1; int columnIndex = 2;\n               xlApp.Cells(rowIndex, columnIndex) = "Blah"	0
25061385	25061287	InternetExplorer - RemoteWebDriver, how to specify the path to the executable file?	public class SuperTest {\n    public SuperTest() {\n      System.setProperty("webdriver.ie.driver", "C:\\Path\\To\\IEDriver.exe");\n    }\n  }\n  public class Test extends SuperTest {}	0
5224943	5224926	Make a new DataTable with the same columns as another DataTable	myTable = table.Clone()	0
4704758	4702893	MSTest - Multiple Assertions from a list	[TestMethod]\n        public void GetAnswersForResultIs47()\n        {\n            List<string> listOfExpressions = findArithmeticSymbolsInNumericOrder13579ThatGivesThisResult(47);\n            Assert.AreEqual(true, listOfExpressions.Contains("1*3+5*7+9"));\n            Assert.AreEqual(true, listOfExpressions.Contains("-1-3*5+7*9"));\n        }	0
17753366	17747417	Disable Space key on Windows Phone	private void SearchCriteria_KeyDown(object sender, System.Windows.Input.KeyEventArgs e\n{\n    if (e.Key.ToString() == "Space")\n    {\n        DelLast = SearchCriteria.Text;\n        NeedsToDelete = true;\n        _selectionStart = SearchCriteria.SelectionStart;\n    }\n}\nprivate void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)\n{\n    if (NeedsToDelete == true)\n    {\n        SearchCriteria.Text = DelLast;\n        SearchCriteria.SelectionStart = _selectionStart;\n        NeedsToDelete = false;\n    }\n}	0
17128701	17128501	Detect attribute on method based on string representation of namespace/assembly	Type t;\n\nt.GetMembers().Where(m => m.GetCustomAttributes(false).Any(a => a.GetType().Namespace == "Some.nameSpace" && a.GetType().Name == "AttributeName")).ToArray();	0
5966965	5957984	How to add text to icon in c#?	public static Icon GetIcon(string text)\n{\n    //Create bitmap, kind of canvas\n    Bitmap bitmap = new Bitmap(32, 32);\n\n    Icon icon = new Icon(@"Images\PomoDomo.ico");\n    System.Drawing.Font drawFont = new System.Drawing.Font("Calibri", 16, FontStyle.Bold);\n    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);\n\n    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);\n\n    graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;\n    graphics.DrawIcon(icon, 0, 0);            \n    graphics.DrawString(text, drawFont, drawBrush, 1, 2);\n\n    //To Save icon to disk\n    bitmap.Save("icon.ico", System.Drawing.Imaging.ImageFormat.Icon);\n\n    Icon createdIcon = Icon.FromHandle(bitmap.GetHicon());\n\n    drawFont.Dispose();\n    drawBrush.Dispose();\n    graphics.Dispose();\n    bitmap.Dispose();\n\n    return createdIcon;\n}	0
12010577	12010511	Get the "Key" for a strongly typed model in the controller	ModelState.AddModelError("Email", "the email is invalid");	0
6243115	6243011	How can I retrieve SoapEnvelope information just from the URL of web services in C#?	System.ServiceModel.Description.MetadataExchangeClient	0
10107100	10103225	Delete all links from quicklaunch?	SPNavigationNodeCollection nodes = web.Navigation.QuickLaunch;\n for(int i = nodes.Count - 1; i >= 0; i--)\n            {\n                nodes[i].Delete();\n            }	0
5884358	5884272	C# datatable, duplicate data	DataTable dt = new DataTable();\nDataRow dr = dt.Rows[0];\ndt.Rows.Add(dr.ItemArray);	0
7325477	7320632	What's the best method to choose per my requirement to store the values	namespace ConsoleApplication1\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int[] EmpIds = new int[] { 123, 1234, 1234 };\n        int[] PayIds = new int[] { 1, 1, 2 };\n        Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();\n\n        // populate dictionary\n        for (int i = 0; i < EmpIds.Length; i++)\n        {\n            if (!dict.ContainsKey(EmpIds[i]))\n            {\n                List<int> values = new List<int>();\n                dict.Add(EmpIds[i], values);\n            }\n            dict[EmpIds[i]].Add(PayIds[i]);\n        }\n        foreach (int k in dict.Keys)\n        {\n            foreach (int v in dict[k]) Console.WriteLine("{0} -> {1}", k, v);\n            Console.WriteLine();\n        }\n        Console.ReadKey();\n    }\n}\n}	0
24166416	24165807	Add with value not working	if(txtZoeken.Text != string.Empty)\n    {\n        naam = "%" + txtZoeken.Text + "%";\n    }\n\n    string Query = "SELECT Naam, Omschrijving,Prijs,Productnummer,CategorieNaam FROM Producten INNER JOIN Categorie ON Producten.Categorie = Categorie.CategorieId WHERE naam LIKE ?";\n    OleDbCommand SqlQuery = new OleDbCommand(Query, Conn);\n    SqlQuery.Parameters.AddWithValue("@naam",naam);	0
34210743	34210471	How to change DateTimePicker format in windows forms?	private void button1_click(object sender, EventArgs e)\n{       \n    label1.Text = dateTimePicker1.Value.ToString("dddd dd-MM-yyyy");            \n}	0
1607184	1398680	XML Serialization - XmlCDataSection as Serialization.XmlText	public class CDataField : IXmlSerializable\n    {\n        private string elementName;\n        private string elementValue;\n\n        public CDataField(string elementName, string elementValue)\n        {\n            this.elementName = elementName;\n            this.elementValue = elementValue;\n        }\n\n        public XmlSchema GetSchema()\n        {\n            return null;\n        }\n\n        public void WriteXml(XmlWriter w)\n        {\n            w.WriteStartElement(this.elementName);\n            w.WriteCData(this.elementValue);\n            w.WriteEndElement();\n        }\n\n        public void ReadXml(XmlReader r)\n        {                      \n            throw new NotImplementedException("This method has not been implemented");\n        }\n    }	0
13372126	13369273	removing selected rows in dataGridView	private void DataGrid_KeyDown(object sender, KeyEventArgs e)\n {\n   if (e.KeyCode == Keys.Delete)\n   {\n    Int32 selectedRowCount =  DataGrid.Rows.GetRowCount(DataGridViewElementStates.Selected);\n    if (selectedRowCount > 0)\n     {\n        for (int i = 0; i < selectedRowCount; i++)\n        {\n            DataGrid.Rows.RemoveAt(DataGrid.SelectedRows[0].Index);  \n        }\n     }\n   }\n}	0
17821377	17821145	C# Using a delegate to a member function to create a new thread	Task.Factory.StartNew(() => func(c));	0
19863180	19862748	PetaPoco - setting transaction isolation level	"SET TRANSACTION ISOLATION LEVEL READ COMMITTED SELECT * FROM tblNewObject WHERE Id = @0"	0
8244811	8244740	Is it overkill to use a service bus if all messages are sent locally?	Queue<T>	0
26908599	22101636	Using virtual properties to support NHibernate proxies; ReSharper warns of virtual member call in constructor	public class Video : IAbstractDomainEntity<string>\n{\n    private string _id;\n    private string _title;\n    private string _author;\n\n    public virtual string Id\n    {\n        get { return _id; }\n        set { _id = value; }\n    }\n    public virtual string Title\n    {\n        get { return _title; }\n        set { _title = value; }\n    }\n    public virtual string Author\n    {\n        get { return _author; }\n        set { _author = value; }\n    }\n    public virtual int Duration { get; set; }\n    public virtual bool HighDefinition { get; set; }\n\n    public Video()\n    {\n        _id = string.Empty;\n        _title = string.Empty;\n        _author = string.Empty;\n    }\n}	0
11205875	11205366	Datagridview can't get the text from selected row specific control button field	LinkButton btn = (LinkButton)GridView1.SelectedRow.Cells[1].Controls[1];\nstring text = btn.Text;	0
8494579	8494493	Silverlight Rich text editor - extract as String?	public string Xaml { get; set; }	0
17091134	17073992	How to Call a Web Service in C#	Right Click on  Protocols -> New -> Key\n            Name: TLS 1.0\n\n            Right Click on the new key -> New -> Key\n            Name: Client\n\n            Select the created folder (Client), right click New -> Value DWORD\n            Name: Enabled	0
22988557	22988170	Add ComboBox to DataGridView C# Winforms	DataGridView1.Rows.Add(val[0], val[1], val[2], va[3], val[4]);\nDataGridViewComboBoxCell cb= new DataGridViewComboBoxCell();\ncb.MaxDropDownItems = 5;\ncb.Items.Add(DataGridView1.Rows[DataGridView1.Rows.Count - 1].Cells[3].Value.ToString());\ncb.Value = DataGridView1.Rows[DataGridView1.Rows.Count - 1].Cells[3].Value.ToString();\nDataGridView1.Rows[DataGridView1.Rows.Count - 1].Cells[3] = cb;	0
31718463	31718265	How can i get the password of oracle user instance from oracle connection string using C#?	builder.ConnectionString = con.ConnectionString;	0
3594288	3593099	RichTextBox & Disabling Mouse Scrolling	using System;\nusing System.Windows.Forms;\n\nclass MyRtb : RichTextBox {\n    protected override void WndProc(ref Message m) {\n        if (m.Msg == 0x207) this.Clear();\n        else if (m.Msg != 0x208) base.WndProc(ref m);\n    }\n}	0
17366606	17366415	how can I add values into a new data table column in the existing rows	DataTable DBTable = LoadMailingListContent(Location);\n\nDataColumn dc = new DataColumn("FirstName");\nDBTable.Columns.Add(dc);\ndc = new DataColumn("LastName");\nDBTable.Columns.Add(dc);\nforeach (DataRow d in DBTable.Rows)\n{ \n    var names = d["fullname"].ToString().Split(' ');\n    d["FirstName"] = names[0];\n    d["LastName"] = names[1];\n}	0
29422983	29421619	C# RSA implementation with OpenSSL keys & Bouncy castle	System.Buffer.BlockCopy	0
1158556	1158530	ASP.NET Server.Mappath problem from inner folders	Server.MapPath("~/myConfig.xml")	0
14662493	14662410	Looking for a shurtcut of Properties.Settings.Default	Properties.Settings settings = Properties.Settings.Default;\nsettings.var1 = "x";\nsettings.var2 = "y";\nsettings.var3 = "Z";\nsettings.Save();	0
3931034	3931016	ASP.NET localization of multi-value messages	ApplicationStrings.ErrorLabel	0
1604575	1604552	How do I get the number of the item selected in a listbox (C#)	MyListBox.SelectedIndex	0
881254	881251	How to get the path of app(without app.exe)?	path = System.IO.Path.GetDirectoryName( path );	0
11949363	11949287	C# prevent access to all object methods from other threads	public class Foo {\n    private readonly YourType tail;\n    private readonly object syncLock = new object();\n    public Foo(YourType tail) {this.tail = tail;}\n\n    public A() { lock(syncLock) { tail.A(); } }\n    public B() { lock(syncLock) { tail.B(); } }\n    public C() { lock(syncLock) { tail.C(); } }\n}	0
3348553	3336581	NHibernate: Default value for a property over a null column	internal virtual bool? isActive {get;set;}\npublic bool MyInterface.IsActive \n{\n    get{ return isActive ?? false; }\n    set{ isActive == value ?? false; };\n}	0
4029960	4029217	WCF Service Serialization: The deserializer has no knowledge of any type that maps to this name	[ServiceContract] \npublic interface IExample \n{ \n    [OperationContract] \n    [ServiceKnownType(typeof(Job))]\n    void DoSomething(IJob); \n} \n\npublic class Example : IExample \n{ \n    public void DoSomething(IJob job) \n    { \n        ... \n    } \n}	0
10318596	10318498	finding a child object in list declared as the parent object	public Fruit GetFruit(Type type)\n{    \n    return fruits.Find(x => x.GetType() == type);\n}	0
29562016	29559090	Easily call an Rest api with RestSharp	request.AddJsonBody(new { user = model });	0
11020149	11020029	unable to display data from list	lstboxSchedule.ItemsSource = dateList;	0
24355073	24354953	Locate Folders inside of Folder	public static void GetDirectoryTreeRecursively(string _path)\n{\n    var directories = Directory.GetDirectories(_path);\n    foreach (var directory in directories)\n    {\n        // use path, save to list, etc...\n        GetDirectoryTreeRecursively(directory);\n    }\n}	0
18411334	18411252	appending a dataset to a session variable	((DataSet)Session["xyz"]).Merge(ds1) ;	0
18204628	18204433	HasMany gives null children	_session = CreateSession(); //(Test class method to create session)\n\n    //reload them\n    var item1b = LoadByName("Item1");\n    var item2b = LoadByName("Item2");\n\n    //check we have loaded new objects\n    Assert.AreNotSame(item1, item1b);\n    Assert.AreNotSame(item2, item2b);	0
7477740	7477692	C#: Best way to check against a set of Enum Values?	bool IsCDF(MyEnum enumValue)\n{\n    return((enumValue & (MyEnum.C | MyEnum.D | MyEnum.F)) != 0);\n}	0
16526049	16523826	How to skip login page if the user data is saved in the isolatedstorage	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    // at this point, the page has been fully loaded:        \n    IsolatedStorageSettings WasalnySettings = IsolatedStorageSettings.ApplicationSettings;\n    if (WasalnySettings.Contains("CurrentUserGUID"))\n    {\n        string mydata = (string)WasalnySettings["CurrentUserGUID"];\n        NavigationService.Navigate(new Uri("/Home.xaml", UriKind.Relative));\n    }\n}	0
17321512	17321289	Use Process.Start with parameters AND spaces in path	string fullPath = @"C:\FOLDER\folder with spaces\OTHER_FOLDER\executable.exe"\nProcessStartInfo psi = new ProcessStartInfo();\npsi.FileName = Path.GetFileName(fullPath);\npsi.WorkingDirectory = Path.GetDirectoryName(fullPath);\npsi.Arguments = "p1=hardCodedv1 p2=" + MakeParameter();\nProcess.Start(psi);	0
9946258	9946180	Using a DLL that has data access capabilities causes an error	app.config	0
11476051	11475816	c# left-shift nibbles in a byte array	var pos = 0;\nvar newByte = b1[pos] << 4;\nnewByte |= b2[pos]	0
19320978	19317230	How I can remove special XElements in a XML file in C#?	public void ProcessRequest (HttpContext context) {\n    context.Response.ContentType = "text/xml";\n\n    string xml = @"\n        <plants>\n          <plant id=""DB"" display="".testDB.."" group=""NPS_DB"" />\n          <plant id=""EL"" display="".testEL.."" group=""NPS_EL"" />\n          <plant id=""IN"" display=""..testIN."" group=""NPS_IN"" />\n          <plant id=""SB"" display="".testSB.."" group=""NPS_SB"" />\n          <plant id=""BL"" display="".testBL.."" group=""NPS_BL"" />\n          <plant id=""LS"" display=""..testLS.."" group=""NPS_LS"" />\n        </plants>\n    ";\n\n    XDocument x = XDocument.Parse(xml);\n    string[] ActiveUserList = { "NPS_DB", "NPS_BL" };\n\n    var att = x.Descendants("plant").Where(el => !ActiveUserList.Contains(el.Attribute("group").Value));\n\n    att.Remove();\n\n    context.Response.Write(x.ToString());\n}	0
2860516	2860484	C#: IEnumerable, GetEnumerator, a simple, simple example please!	public class AlbumList : IEnumerable<Album>\n{\n    // ...\n\n    public IEnumerator<Album> GetEnumerator()\n    {\n        return this.albums.GetEnumerator();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return GetEnumerator();\n    }\n}	0
10421618	10421457	change label ForeColor for specific string	var allLabels = GetAll(form, typeof(Label)); /// you can use this as first param if in form methods\nforeach(Label oneLabel in allLabels)\n{\n  if (oneLabel.Text == "Something")\n  {\n    // set color or whatever\n  }\n}	0
6177576	6177538	c# custom date format	// extend with minutes, seconds etc. if needed\nvar text = String.Format ("{0} day(s), {1} hour(s)", totalTimeInRoom.Days, totalTimeInRoom.Hours);	0
13284374	13283012	How can i remove the duplicate element from a xml document without scribbling the structure of xml using c#	XElement xml = XElement.Load("data.xml");\n\nstring toRemove ="Hurricanes";\n\n//Find the Number of Duplicates\nint duplicateCount=xml.Descendants("Term")\n                      .GroupBy(xe => xe.Attribute("Name").Value)\n                      .Where(x => x.Key == toRemove)\n                      .Select<IGrouping<string, XElement>, int>(y => y.Count())\n                      .First();\n\n//Remove all duplicates but one\nxml.Descendants("Term").Where(xe => xe.Attribute("Name").Value == toRemove)\n                       .Take(duplicateCount-1)\n                       .Remove();\n\nxml.Save("moddata.xml");	0
4898310	4898034	How to connect to MYSQL with WPF?	public interface MyPersonRepository{\n    Person GetById(args);\n    Person Insert(args);\n    Person Update(args);\n    void Delete(args);\n}	0
6165273	6165238	Execute VBScript Function from C# with parameters	System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\yourfile.vbs");	0
6991888	6991844	How to Mock a Predicate in a Function using Moq	[TestMethod]\n  public void CanGetPurchaseOrderByPurchaseOrderNumber()\n {\n\n      _purchaseOrderMockRepository.Setup(s => s.Find(It.IsAny<Func<PurchaseOrder, bool>>()))\n          .Returns((Func<PurchaseOrder, bool> expr) => new List<PurchaseOrder>() {FakeFactory.GetPurchaseOrder()});\n\n      _purchaseOrderService.FindPurchaseOrderByOrderNumber("1111");\n\n      _purchaseOrderMockRepository.VerifyAll();\n\n\n }	0
22958997	22958893	String Parsing using C#	String toParse = "http://playdebug.games.com/facebook/title.html";\nString result = Path.GetFileNameWithoutExtension(toParse);	0
5647390	5647328	C# - Convert a string of hex values to hex	byte b;\nif (byte.TryParse(s, NumberStyles.HexNumber, \n    CultureInfo.InvariantCulture.NumberFormat, out b)) \n{\n    // b contains the value.\n}	0
4486470	4486451	Replace the start and end of a string ignoring the middle with regex, how?	exp = new Regex(@"YourtagStartRegex(bodyRegex)YourtagClosingRegex");\n str = exp.Replace(str, "<center>$1</center>");	0
34026104	34025205	How to redirect url from public class in mvc4 razor	[HttpPost]\n public ActionResult SendMail(SendMail SendMail)\n {\n  if (...)\n  {\n    //Sending Mail SMPT Setting    \n    return RedirectToRoute(URL);\n  }\n  else\n  return RedirectToRoute(URL);\n}	0
21891195	21888814	How can I cast an object as a type defined in a Type property?	dynamic contextInstance = Activator.CreateInstance(Context);	0
3608125	3608101	Convert expression from C# into Java	long l = (long) myString.charAt(0)	0
3631000	3630942	xml to data structure	var doc = XDocument.Load("xmlfile1.xml");\n\nvar steps = from step in doc.Root.Elements("step")\n            select new Step\n                   {\n                       Id       = (int)step.Element("id"),\n                       BackId   = (int)step.Element("backid"),\n                       Question = (string)step.Element("question"),\n                       YesId    = (int)step.Element("yesid"),\n                       NoId     = (int)step.Element("noid"),\n                   };\n\nvar dict = steps.ToDictionary(step => step.Id);\n\nvar currentStep = dict[3];\n\nwhile (true)\n{\n    switch (Ask(currentStep.Question))\n    {\n        case Yes:  currentStep = dict[currentStep.YesId];  break;\n        case No:   currentStep = dict[currentStep.NoId];   break;\n        case Back: currentStep = dict[currentStep.BackId]; break;\n        default:   return;\n    }\n}	0
1918299	1918280	What control should you databind a List<string> to?	BindingList<string>	0
2984664	2984624	Method in ICollection in C# that adds all elements of another ICollection to it	public static class CollectionExtensions\n{\n    public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> newItems)\n    {\n        foreach (T item in newItems)\n        {\n            collection.Add(item);\n        }\n    }\n}	0
17206095	17205520	Convert members of interface based dictionary to concrete based dictionary	Dictionary<KeyType, IList<ValueType>> newDict = \n                   myDict.ToDictionary(\n                       k => k.Key as KeyType, \n                       v => v.Value.OfType<ValueType>() as IList<ValueType>);	0
23981477	23981396	How is ASP.NET User filled in after Authentication?	Request -> HttpModules -> HttpHandler -> HttpModules -> Client	0
13903179	13902957	How can i improve performance in this Minesweeper algorithm?	this.SuspendLayout();\n... logic      \nthis.ResumeLayout(false);	0
1492173	1492131	need to remove xml nodes in a string and leave the text	class Program\n{\n    static void Main(string[] args)\n    {\n        string contents = string.Empty;\n\n        XmlDocument document = new XmlDocument();\n        document.LoadXml("<outer>a<b>b</b>c<i>d</i>e<b>f</b>g</outer>");\n\n        foreach(XmlNode child in document.DocumentElement.ChildNodes)\n        {\n            if (child.NodeType == XmlNodeType.Element)\n            {\n                contents += child.InnerText;\n            }\n        }\n\n        Console.WriteLine(contents);\n\n        Console.ReadKey();\n    }\n}	0
10300427	10231132	How-to: Remove text from Word document footer using C#	Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();\n\nDocument doc = ap.Documents.Open(docFile.FullName, ReadOnly: false, Visible: false);\ndoc.Activate();\n\n// These 3 lines did the trick.\ndoc.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryFooter;\ndoc.Application.Selection.MoveRight(WdUnits.wdCharacter, 1);\ndoc.Application.Selection.Delete(WdUnits.wdCharacter, 9);\n\nap.Documents.Close(SaveChanges: false, OriginalFormat: false, RouteDocument: false);\n\n((_Application) ap).Quit(SaveChanges: false, OriginalFormat: false, RouteDocument: false);\nSystem.Runtime.InteropServices.Marshal.ReleaseComObject(ap);	0
27067603	27066612	Get handle of top window (Sort windows by Z index)	[DllImport("user32.dll", SetLastError = true)]\nstatic extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);\n\nenum GetWindow_Cmd : uint\n{\n    GW_HWNDFIRST = 0,\n    GW_HWNDLAST = 1,\n    GW_HWNDNEXT = 2,\n    GW_HWNDPREV = 3,\n    GW_OWNER = 4,\n    GW_CHILD = 5,\n    GW_ENABLEDPOPUP = 6\n}\n\nprivate IntPtr GetTopmostHwnd(List<IntPtr> hwnds)\n{\n    var topmostHwnd = IntPtr.Zero;\n\n    if (hwnds != null && hwnds.Count > 0)\n    {\n        var hwnd = hwnds[0];\n\n        while (hwnd != IntPtr.Zero)\n        {\n            if (hwnds.Contains(hwnd))\n            {\n                topmostHwnd = hwnd;\n            }\n\n            hwnd = GetWindow(hwnd, GetWindow_Cmd.GW_HWNDPREV);\n        }\n    }\n\n    return topmostHwnd;\n}	0
16651898	16651796	Task doesn't change parameters	for (int i = 0; i < 100; i++)\n{\n    int taskNumber = i\n    tk[i] = Task.Factory.StartNew(() => taskThread(taskNumber));\n}	0
14904506	10751075	How to test a DataTables server-processing sourced table with Watin?	public void CheckForCells()\n{\n    Table table = Document.Table(Find.ById("MyTableID"));\n\n    int counter = 0;\n    while (table.TableRows.Count < 5 && counter < 50)\n    {\n        table.Refresh();\n        counter++;\n        System.Threading.Thread.Sleep(10);\n    }\n\n}	0
3777839	3777465	How to specify file extension in ASP.Net upload control?	string[] validFileTypes = { "bmp", "jpg", "png" };\n    string ext = Path.GetExtension(fileUpload1.FileName);\n    bool isValidType = false;\n\n    for (int i = 0; i < validFileTypes.Length; i++)\n    {\n        if (ext == "." + validFileTypes[i])\n        {\n            isValidType = true;\n            break;\n        }\n    }\n\n    if (!isValidType)\n    {\n        lblMessage.Text = "Invalid File Type";\n    }\n    else\n    {\n        lblMessage.Text = "File Uploaded Successfullty";\n    }	0
3189513	3189477	Problems with Executing a DB2 External Stored Procedure	using (var conn = new iDB2Connection(_CONNSTRING)) \nusing (var cmd = conn.CreateCommand())\n{ \n    conn.Open();\n\n    cmd.CommandType = CommandType.StoredProcedure;\n    cmd.CommandText = "MPRLIB.SIGNTIMESHEET";\n    cmd.Parameters.Add("@SSN", timesheet.EmployeeUniqueKey.ToString("0000000000"));\n    cmd.Parameters.Add("@SIGNATURE", timesheet.EmployeeTypedName);\n    cmd.Parameters.Add("@WORKSTATION", timesheet.EmployeeSignedComputer);\n    cmd.Parameters.Add("@TOTALHOURS", GetJobHoursTotal(timesheet.Id).ToString("00000.000").Replace(".", ""));\n    cmd.Parameters.Add("@COMMENT", timesheet.EmployeeComments);\n\n    cmd.ExecuteNonQuery();\n}	0
30374056	30373344	C# IUserStore implementation GetPasswordHash	public Task SetPasswordHashAsync(TUser user, string passwordHash)\n    {\n        user.PasswordHash = passwordHash;\n        return Task.FromResult(0);\n    }\n\n    public Task<string> GetPasswordHashAsync(TUser user)\n    {\n        return Task.FromResult(user.PasswordHash);\n    }	0
12041097	12008331	Retrieving file installation path from registry	RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths\myexe.exe");\n                string regFilePath = null;\n\n                object objRegisteredValue = key.GetValue("");\n\n                registeredFilePath = value.ToString();	0
17244149	17244097	Extract a date from a text	Regex rg = new Regex(@"[01]?\d[/-][0123]?\d[/-]\d{2}");\nMatch m = rg.Match(string);\nm.ToString();	0
20241160	20241082	A value of type 'int' cannot be used as a default parameter because there are no standards conversions to type C#	public RoomActor GetActorByReferenceId(int ReferenceId, RoomActorType ReferenceType = RoomActorType.UserCharacter)	0
18928708	18927810	How do I create an Entity automatically with DateTime.Now, instead of the user specify the value?	[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult  FormPostAction([Bind(Exclude = "CreateTime")] Topic topic)\n{\nand here you have to initialize CreateTime with whatever value you want...\n}	0
25535463	25531984	call a remote powershell script with parameters from c# program	public void RemoteConnection() \n{\n  connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, credentials);\n        runspace = RunspaceFactory.CreateRunspace(connectionInfo);\n        runspace.Open();\n        Pipeline pipeline = runspace.CreatePipeline(path);\n\n        Command myCommand = new Command(path);\n        CommandParameter testParam0 = new CommandParameter("-suma");\n        myCommand.Parameters.Add(testParam0);\n\n        CommandParameter testParam = new CommandParameter("x", "34");\n        myCommand.Parameters.Add(testParam);\n        CommandParameter testParam2 = new CommandParameter("y", "11");\n        myCommand.Parameters.Add(testParam2);\n\n        pipeline.Commands.Add(myCommand);\n        var results = pipeline.Invoke();\n        foreach (PSObject obj in results)\n          Console.WriteLine(obj.ToString());\n}	0
4246347	4246307	is it possible to refactor this into a single method	public void SourceInfo_Get()    \n{\n    SendGet(pFBlock.SourceInfo);\n}\n\npublic void SourceAvailable_Get()\n{\n    SendGet(pFBlock.SourceAvailable);\n}\n\nprivate void SendGet(Object obj) {\n    MethodInfo mi = obj.GetType().GetMethod("SendGet");\n    if (mi != null)\n    {\n        ParameterInfo[] piArr = mi.GetParameters();\n        if (piArr.Length == 0)\n        {\n            mi.Invoke(obj, new object[0]);\n        }\n    }\n}	0
4099694	4099652	c# how do you return dataset from sqldatareader?	var ds = new DataSet();\n\nusing(var conn = new SqlConnection(connString))\n{\n    conn.Open();\n    var command = new SqlCommand(InitializeQuery(), conn);\n    var adapter = new SqlDataAdapter(command);\n\n    adapter.Fill(ds);\n}	0
18441342	18439758	How to know a specific checkbox inside datagridview is checked or not?	private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n    {\n        if (dataGridView1.IsCurrentCellDirty)\n        {\n            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n        }\n    }\n\n    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n    {\n        if (((e.ColumnIndex) == 1) && ((bool)dataGridView1.Rows[e.RowIndex].Cells[1].Value))\n        {\n            MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());\n\n        }\n    }	0
22425186	22425059	How to send url with parameters from windows phone 8	WebClient webClient = new WebClient();\nwebClient.DownloadStringCompleted += (s, e) =>\n{\n\n};\nwebClient.DownloadStringAsync(new Uri(String.Format("http://example.com?par1={0}&par2={1}", "param1", "param2"), UriKind.RelativeOrAbsolute));	0
28239415	28238557	Print custom attribute in view from different controllers	public class TitleAttribute : ActionFilterAttribute\n    {\n        protected string description;\n\n        public TitleAttribute(String descritionIn)\n        {\n            this.description = descritionIn;\n        }\n\n        public String Description\n        {\n            get\n            {\n                return this.description;\n            }\n        }\n\n        public override void OnResultExecuting(ResultExecutingContext filterContext)\n        {\n            filterContext.Controller.ViewBag.Title = description;\n        }\n    }	0
20959388	20959292	When I extract text from a PDF file using iText I am getting values from previous pages	var reader = new PdfReader(foregroundFile);\n\nRectangleJ customerIdRectangle = new RectangleJ(0, 495, 108, 27);\n\nfor (int i = 1; i <= reader.NumberOfPages; i++)\n{\n    RenderFilter[] filters = new RenderFilter[1];\n    LocationTextExtractionStrategy regionFilter = new LocationTextExtractionStrategy();\n    filters[0] = new RegionTextRenderFilter(customerIdRectangle);\n    FilteredTextRenderListener strategy = new FilteredTextRenderListener(regionFilter, filters);\n    string output = "";\n    output = PdfTextExtractor.GetTextFromPage(reader, i, strategy);\n    Console.WriteLine(output);\n}	0
30253595	30253052	Get windows operating system version in windows phone8	System.Environment.OSVersion	0
2232134	2232089	How can I sort an XDocument by attribute?	XDocument input = XDocument.Load(@"input.xml");\nXDocument output = new XDocument(\n    new XElement("Users",\n        from node in input.Root.Elements()\n        orderby node.Attribute("Name").Value descending\n        select node));	0
18181281	18180391	how I can update my entity in wcf service	db.NIOCPay_PayDetail.Attach(doc);\ndb.ChangeTracker.Entries<NIOCPay_PayDetail>().FirstOrDefault().State =\n                               System.Data.EntityState.Modified;\ndb.SaveChanges();	0
14369842	14369406	Could not find endpoint element with name and contract	ABCService.ServiceClient ABCClient = new ServiceClient("ABCServiceV1");\nABCService.Service1Client ABCClient1 = new Service1Client("ABCServiceV2");	0
32531096	32529184	Data Passing Between Two Form with SQL	userLabel2.Text =\n    (Application.OpenForms["yourForm1"] as yourForm1).userLabel.Text;	0
15366421	14901965	How to get size of Azure CloudBlobContainer	public static long GetSpaceUsed(string containerName)\n        {\n\n            var container= CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString)\n                             .CreateCloudBlobClient()\n                             .GetContainerReference(containerName);\n            if (container.Exists())\n            {\n                return (from CloudBlockBlob blob in\n                            container.ListBlobs(useFlatBlobListing: true)\n                        select blob.Properties.Length\n                  ).Sum();\n            }\n            return 0;\n        }	0
16642578	16642159	insert new node with its attribute to xml	var doc = XDocument.Load("yourxmlfile.xml");\nvar x = new XElement("level", \n         new XAttribute("id", 3), \n         new XAttribute("name", "Level 3"));\n\ndoc.Element("group").Add(x);\ndoc.Save("yourxmlfile.xml");	0
8596728	8596678	How to use XML in C# file instead of using external XML file?	try\n   {\n      _assembly = Assembly.GetExecutingAssembly();\n      _imageStream = _assembly.GetManifestResourceStream("MyNamespace.MyImage.bmp");\n      _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNamespace.MyXmlFile.xml"));\n   }\n   catch\n   {\n      MessageBox.Show("Error accessing resources!");\n   }	0
7406964	7406898	Add string to array only if data is available	List<string> list = new List<string>();\nvar str = DropDownListIssue.SelectedItem.ToString();\nif (!string.IsNullOrEmpty(str))\n    list.Add("Issue=" + str);\nstr = DropDownListSubIssue.SelectedItem.ToString();\nif (!string.IsNullOrEmpty(str))\n    list.Add("SubIssue=" + str);\nstr = DropDownListLayout.SelectedItem.ToString();\nif (!string.IsNullOrEmpty(str))\n    list.Add("Layout=" + str);\n\nstring[] var4 = list.ToArray();	0
6621155	6621129	To convert String XML into a data table in C#	DataSet ds;\n        StringReader reader = new StringReader(string);\n        ds.ReadXml(reader);\n        dataGridView1.DataSource = ds.Tables["TableName"];	0
26279173	26278515	Parts of string in regex	var myUrl     = "wmq://aster-C1.it.google.net@EO_B2:1427/QM.0021?queue=SOMEQueue?";\nvar myRegex   = new Regex(@"wmq://(.*?)@(.*?)\?queue=(.*?)\?");\nvar myMatches = myRegex.Match(myUrl);\n\nDebug.Print(myMatches.Groups[1].Value);\nDebug.Print(myMatches.Groups[2].Value);\nDebug.Print(myMatches.Groups[3].Value);	0
8390133	8390078	String Manipulation - Get the last 'x' amount of chars	var result = Path.GetFileName(@"C:\Code\AppSettings");\n// result == "AppSettings"	0
29399989	29399400	Row-like string with even spacing in between values	string pattern = string.Format("{0}\t\t{1}\t\t{2}\t\t{3}\t\tAnnualSalary: {4}, Annual Bonus: {5}", \nemp[index].first, \nemp[index].last, \nemp[index].number,\nemp[index].department, \nemp[index].annualSalary).ToString("c"),\nemp[index].annualBonus);	0
14692106	14691969	How to get AngleProperty	RotateTransform rTransform = new RotateTransform(angle);\n...\nvar temp = rTransform.Angle;	0
19621065	19620703	How to access a textbox text from gridview to a button Onclick event	protected void btnSave1_Click(object sender, EventArgs e)\n{\n     GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;\n     TextBox TextBox1 = row.FindControl("TextBox1") as TextBox; \n\n      //Access TextBox1 here.\n      string myString = TextBox1.Text;\n}	0
26899188	26899054	Converting JSON string in C#	var json = "{email:'bob@gmail.com'}";\nvar user = JsonConvert.DeserializeObject<User>(json);	0
1769472	1769447	interesting OutOfMemoryException with StringBuilder	GC.Collect()	0
26611606	26611488	Retrieving an element from a created list	string sql = @"SELECT COUNT(PRODUCT_TYPE_NO) AS NumberOfProducts\n               FROM dbo.PRODUCT\n               Where PRODUCT_TYPE_NO IN ({0});";\n\nstring[] paramNames = PTNList.Select(\n    (s, i) => "@type" + i.ToString()\n).ToArray();\n\nstring inClause = string.Join(",", paramNames);\nusing (SqlCommand cmd = new SqlCommand(string.Format(sql, inClause)))\n{\n    for (int i = 0; i < paramNames.Length; i++)\n    {\n        cmd.Parameters.AddWithValue(paramNames[i], PTNList[i]);\n    }\n\n    // con.Open(); // if not already open\n    int numberOfProducts = (int) cmd.ExecuteScalar();\n}	0
12356933	12356833	Deserialize REST date format	var dt = new DateTime(1970, 1, 1).AddSeconds(1347274789); //09/10/2012 10:59:49	0
20491290	19541329	reportviewer using rdlc in WPF	_reportViewer.RefreshReport();	0
1193464	1193455	How do I get last year's date in C#?	DateTime lastYear = DateTime.Today.AddYears(-1);	0
25451082	25450906	Reading varying sized string from serial port	private void Form1_Shown(object sender, EventArgs e)\n{\n    serialPort1 = new SerialPort(comboPorts.SelectedItem.ToString(), 115200);\n\n    serialPort1.Open();\n    Thread t = new Thread(ReadThread);\n    t.Start(serialPort1);\n}\n\nprivate void ReadThread(object context)\n{\n    SerialPort serialPort = context as SerialPort;\n\n    while (serialPort.IsOpen)\n    {\n        string inData = serialPort.ReadLine();\n        Console.WriteLine(inData);\n    }\n}	0
5855635	5855599	Translation of a string in code behind in a localresource file	GetLocalResourceObject("yourkey").ToString();\n\nGetGlobalResourceObject("MyGlobalResources", "HelloWorldString").ToString();	0
1880698	1880679	Embedd a xsd file in C#	// Get the assembly that contains the embedded schema\nvar assembly = Assembly.GetExecutingAssembly();\nusing (var stream = assembly.GetManifestResourceStream("namespace.schema.xsd"))\nusing (var reader = XmlReader.Create(stream))\n{\n    XmlSchema schema = XMLSchema.Read(\n        reader, \n        new ValidationEventHandler(ValidationEventHandler));\n}	0
15348825	15304726	Representing a Foreign Key as some other value in a WPF StackPanel GridViewColumn	public string CustomerName\n{\n    get\n    {\n        var db = new Context();\n\n        var customer = db.Customers.Find(CustomerId);\n        _customerName = customer.Name;\n\n        return _customerName;\n    }\n}	0
10520445	10519996	Entity Framework 3 - Filter Elements in Chained Navigational Properties	public class OrderView\n{\n  public int Id { get; set; }\n  public IEnumerable<OrderItem> OrderItems { get; set; }\n  ...\n}\n\nvar query = from o in context.Orders\n            select new OrderView\n            {\n              Id = o.Id,\n              OrderItems = //custom filtering\n              ...\n             };	0
13845092	13842688	Removing a complete Row from a gridview when a row satisfies a condition	var stuffIActuallyWantInMyGrid = new List<DataSet>(); //A list of whatever you dt is of\n    foreach(var x in dt)\n    {\n        if(x == WhateverMyCriteriaAre)\n        {\n           stuffIActuallyWantInMyGrid.Add(x);\n        }\n    }\n    GridView3.DataSource = stuffIActuallyWantInMyGrid;\n    GridView3.DataBind();	0
8327750	8327684	C# - Access array without null exception	public string getQueryStringValueOrEmpty(string key)\n{\n  string result = HttpContext.Current.Request.QueryString[key];\n\n  if(result == null)\n  {\n    result = string.Empty;\n  }\n\n  return result;\n}	0
12334553	12266422	What's the best way to serve up multiple binary files from a single WebApi method?	public HttpResponseMessage Get()\n{\n    var content = new MultipartContent();\n\n\n    var ids = new List<int>() { 1, 2 };\n\n    var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());\n\n    content.Add(objectContent);\n\n\n    var file1Content = new StreamContent(new FileStream(@"c:\temp\desert.jpg", FileMode.Open));\n\n    file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");\n\n    content.Add(file1Content);\n\n\n    var file2Content = new StreamContent(new FileStream(@"c:\temp\test.txt", FileMode.Open));\n\n    file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");\n\n    content.Add(file2Content);\n\n\n    var response = new HttpResponseMessage();\n\n    response.Content = content;\n\n    return response;\n}	0
24897584	24854865	DataTable adding Columns to DataGrid instead of adding new rows?	String SelectQuery = "Select ID,TaskName,TaskDue,Status from TASKS Order BY Status";\n   SQLiteConnection slite = new SQLiteConnection("data source = SupportDash.sqlite");\n   slite.Open();\n\n   SQLiteDataAdapter data = new SQLiteDataAdapter(SelectQuery, slite);\n   SQLiteCommandBuilder Command = new SQLiteCommandBuilder(data);\n   var Bind = new BindingSource();\n   DataTable table = new DataTable();\n\n   Bind.DataSource = table;\n\n   MyTasksGrid.AutoGenerateColumns = false;\n   MyTasksGrid.DataSource = table;\n\n   MyTasksGrid.DataSource = Bind;\n   MyTasksGrid.Refresh();\n\n   data.Fill(table);	0
30478794	30477775	How to take total count from selected checkbox while using from Collection C#	int totalSelected = 0;\nforeach (string key in collection.AllKeys)\n{\n    int subTotalSelected = collection.GetValues(key).Where(x => x.Contains("true")).Count();\n    totalSelected += subTotalSelected;\n}	0
9946332	9946270	how to run an mstest dll from command line	mstest /testcontainer:path\to\tests.dll	0
6630173	6630140	Lock keyword and application resets	private readonly object myLock = new object();\n\n  void DoSomething()\n  {\n    lock(myLock)\n    {\n      ...\n    }\n  }	0
5697903	5697871	Find Control Name from non-UI thread	Application.Current.Dispatcher.Invoke(new Action(\n    delegate {\n         // Put code that needs to run on the UI thread here\n    }));	0
30659031	30658512	LINQ request for getting the furthest xml child node with an attribute	IEnumerable<string> ids = xelement.Descendants()\n.Where(x => x.Attributes().Any(a => a.Name.LocalName == "ID") && x.Attributes().First(a => a.Name.LocalName == "ID").Value == "28390")\n.Select(t => t.Name.LocalName);	0
3898879	3898858	Get all html between two elements	.*<(?<tag>.+)>Start</\1>(?<found_data>.+)<\1>End</\1>.*	0
16817300	16817204	How to display checkbox value and text in WPF?	private void CheckBox_Checked(object sender, RoutedEventArgs e)\n{\n     //Get the boolean current value [true or false]\n     bool valueSelectedToBool = (sender as CheckBox).IsChecked;\n\n     //Get the string current value ["true" or "false"]\n     string valueSelectedToString = (sender as CheckBox).IsChecked.ToString();\n\n     MessageBox.Show(valueSelectedToString );\n}	0
32192111	32191950	How do I store the Directory name chosen from FolderBrowserDialog() in wpf?	public void SettingsButton(object sender, RoutedEventArgs e)\n        {\n            var dialog = new System.Windows.Forms.FolderBrowserDialog();\n            System.Windows.Forms.DialogResult result = dialog.ShowDialog();\n\n            if (result == System.Windows.Forms.DialogResult.OK)\n            {    \n                string[] files = Directory.GetFiles(dialog.SelectedPath);\n\n                string resultStr = string.Empty;\n                foreach (String item in files)\n                {\n                    resultStr += item.ToString() + "\n";\n                }\n\n                MessageBox.Show("path:" + dialog.SelectedPath + "\n" + \n                                "files: " + files.Count().ToString() + "\n" + \n                                 resultStr, "Message");\n            }\n        }	0
14348184	14343824	How to group items by location and summing their quantity?	foreach(order in orders)\n{\n   order.partlist = GetItem(order.name).parts; // partlist is a list of Part objects, not stored anywhere.\n}\nforeach(location in locations)\n{\n   foreach(order in GetOrdersAtLocation(location))\n   {\n      foreach(part in order.parts)\n      {\n         location.partlist += { part.name, part.quantity * order.quantity }; // partlist is a list of parts and quantities, to be displayed.\n      }\n   }\n }	0
3587867	3569793	Using the HelpProvider class to show help, UI is always behind help window	private void textBox1_KeyDown(object sender,\nSystem.Windows.Forms.KeyEventArgs e)\n{\n  if(e.KeyCode ==Keys.F1)\n  {\n    System.Diagnostics.Process.Start(@"C:\WINDOWS\Help\mspaint.chm");\n  }\n}	0
15165564	15165503	Linq - How to apply a where clause on the maximum element of a list	var bPersons = persons.Where(p => \n                             p.Categories\n                              .OrderByDescending(c => c.Date)\n                              .First().Value == "B")	0
5940508	5939101	How to set an automatic restarting of a Windows Service application, C#?	System.Timers.Timer myTimer;\nvoid Main()\n{\n    myTimer = new System.Timers.Timer(1000);\n    myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);\n    myTimer.Start();\n}\n\nvoid myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n    myTimer.Stop();\n    // process event\n    myTimer.Start();\n}	0
26014929	26014776	How to set width=auto on GridViewColumn through Bindings?	public double DepotAssignmentWidth \n{ \n    get \n    { \n        return (hasBoolean) ? 50 : double.NaN; \n    }\n}	0
1823686	1823583	C# Reusing an Adapter to populate other controls	myControl.DataSource = dt.AsEnumerable().Select(dr => dr.Field<string>("Regiao")).Distinct().ToArray();	0
7371544	7371490	How does wikimedia transform its model syntax?	balancing groups	0
2304831	2173329	Get Score with NHibernate.Search	IFullTextQuery query = search.CreateFullTextQuery("query goes here");\n\nquery.SetProjection("FirstName", "LastName", ProjectionConstants.SCORE);	0
6532682	6532648	How to find empty bytes array	var Empty = Buffer.All(B => B == default(Byte));	0
27380425	27376133	C#: HttpClient with POST parameters	string url = "http://myserver/method";    \nstring content = "param1=1&param2=2";\nHttpClientHandler handler = new HttpClientHandler();\nHttpClient httpClient = new HttpClient(handler);\nHttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);\nHttpResponseMessage response = await httpClient.SendAsync(request,content);	0
3713781	3713770	Static abstract methods in C# (alternatives for particular use case)	public abstract class Note\n{\n    public abstract void LoadScaledTex(scale);\n}\n\npublic class NoteA : Note\n{\n    private static ScaledTexData instance;\n\n    public override void LoadScaledTex(scale)\n    {\n        lock(this.GetType())\n        {\n            if(instance == null)\n            {\n                instance = new ScaledTexData(scale);\n            }\n        }\n    }\n}	0
21588641	21588468	Retreiving Data From Multiple Tables in a LINQ to SQL query	var result = from tsd in TradeStatsData\n             join cp in CalculatedPrices on tsd.TradeID equals cp.TradeID\n             where cp.Price == null && cp.ActiveTime < DateTime.Now\n             select new\n             {\n                CP = cp,\n                Action = tsd.Action,\n                CurrencyPair = tsd.CurrencyPair\n             };	0
20682568	20682378	use LINQ to query a list	var groupResults = new List<Tuple<string, List<string>>>();\nList<string> subLines = null;\nforeach(var line in lines)\n{\n    if(line.StartsWith("01"))\n    {\n        subLines = new List<string>();\n        groupResults.Add(Tuple.Create(line, subLines));\n    }\n    // consider to handle the case where a line begin with 02 with no 01 before\n    else if(subLines != null && line.StartsWith("02"))\n    {\n        subLines.Add(line);\n    }\n}	0
25400602	25400533	How to get the index of element inside nested Lists	RpBase.DataSource = PymentsList.SelectMany(x=>x.Base)\n                               .Select((x,i)=>new { Base = x, Id =i})	0
26385586	26385262	How to select this XML node and extract its attribute	var doc = XElement.Parse(xml);\nXNamespace ns = "http://schemas.microsoft.com/sqlserver/2004/07/showplan";\n\nforeach (var stmnt in doc.Descendants(ns + "StmtSimple"))\n{\n    string value = (string)stmnt.Attribute("QueryPlanHash");\n}	0
1060715	1060690	Regex - Match a Pattern Before a Character	([A-Z]{1,3})(?==)	0
19785239	19771882	Retrieve first and last values on HighChart	yextremes = chart.yAxis[0].getExtremes();\nxextremes = chart.yAxis[0].getExtremes();\nyMax = yextremes.dataMax;\nxMax = xextremes.dataMax;\nyMin = yextremes.dataMin;\nxMin = xextremes.dataMin;	0
22072059	22071900	Data contract serialization for WCF web service request	[DataContract]\n[Serializable]\npublic sealed class Request\n{\n   [DataMember]\n   public int EventID { get; set; }\n}	0
24304399	24303465	How to detect changes in 1 entity framework object	DbEntityEntry entry = Context.Entry(entity); //where Context is DbContext or derived\n\n// entry.State is available here	0
11616946	11615661	Add object other than string to ToolStripDropDownButton DropDownItem	ToolStripDropDownButton b = new ToolStripDropDownButton();\n  b.DropDownItems.Add(new ToolStripButton("Hello") { Tag = new Something() });	0
20199198	20198498	Try-Catch doesn't show Message Dialog box with await	string errorMessage = string.Empty;\n\ntry \n{\n\n  HttpClient client = new HttpClient();\n  HttpResponseMessage response = await    \n  client.GetAsync("http://localhost:12345/api/items");\n\n  var info = new List<SampleDataGroup>();\n\n  if (response.IsSuccessStatusCode)\n  {\n    var content = await response.Content.ReadAsStringAsync();\n\n    var item = JsonConvert.DeserializeObject<dynamic>(content);\n\n    foreach (var data in item)\n    {\n        var infoSect = new SampleDataGroup\n        (\n            (string)data.Id.ToString(),\n            (string)data.Name,\n            (string)"",\n            (string)data.PhotoUrl,\n            (string)data.Description\n        );\n        info.Add(infoSect);\n    }\n  }\n  else\n  {\n      errorMessage = "Error";\n  }      \n}    \ncatch (Exception ex)\n{\n  ErrorMessage = ex.Message;\n}\n\nif (errorMessage != string.Empty) \n{\n  MessageDialog dlg = new MessageDialog(errorMessage);\n  await dlg.ShowAsync();\n}	0
29563354	29561304	How Can I Encode My New Xml Document?	XmlDocument docsec = new XmlDocument();\ndocsec.LoadXml(send);\nusing (TextWriter writer = new StreamWriter("C:\XmlNEW.xml", false, Encoding.UTF8))\n    docsec.Save(writer);	0
31381545	31376446	Unable to download audio with MediaLibraryExtensions.SaveSong in windows phone 8	private static void SaveFileMP3(string _fileName)\n{\n    MediaLibrary lib = new MediaLibrary();\n    Uri songUri = new Uri(_fileName, UriKind.RelativeOrAbsolute);\n    lib.SaveSong(songUri, null, SaveSongOperation.CopyToLibrary);\n    //MediaLibraryExtensions.SaveSong(lib, songUri, null, SaveSongOperation.CopyToLibrary);\n\n}	0
24614169	24613480	Get Updated Row Count in Transaction Scope	SqlTransaction transaction = SqlConnection.BeginTransaction(IsolationLevel.ReadUncommitted);	0
5591140	5590291	Windows Media Player control - get/set video position?	axWindowsMediaPlayer1.Ctlcontrols.currentPosition = positionInSeconds;	0
6789439	6789408	Finding & terminating threads to shutdown application	thread.IsBackground = true	0
7356223	7356205	Remove file extension from a string of a file?	Path.GetFileNameWithoutExtension	0
13122085	13122061	How to access same List in Class from multiple .cs files?	public class DataClass \n { \n    public string Timestamp { get; set; }\n    private static DataClass instance; \n    private DataClass() { }\n    public static DataClass Instance \n    {\n        get \n        {\n            if(instance==null) \n            { \n                instance = new DataClass(); \n            } \n             return instance; \n        } \n    }  \n}\n\npublic class Class1\n{\n     public void SetValue(string str)\n     {\n         DataClass ds = DataClass.Instance;\n         ds.Timestamp  = "value1";\n     }\n}\n\npublic class Class2\n{\n     public string GetValue(string str)\n     {\n         DataClass ds = DataClass.Instance;\n         return ds.Timestamp;\n     }\n}\n\n\nClass1 c1 = new Class1();\nc1.SetValue("hello");\nClass2 c2 = new Class2();\nstring value = c2.GetValue();	0
23944774	23918285	MVC4 Code First - What data annotation gives me a data type of XML in the SQL database?	[Required]\n[AllowHtml]\n[Column(TypeName = "xml")]\npublic string Content { get; set; }	0
2987639	2984511	Access parent class from custom attribute	[MyCustomAttribute(typeof(MyClass))]\npublic class MyClass {\n  ///\n}	0
26723502	26723352	Repeat multiple calculations in C#	number = Convert.ToInt32(textBox2.Text);\npower = Convert.ToInt32(textBox3.Text);\n\ntextBox1.Text = Convert.ToString(Math.Pow(number, power));	0
4088747	4088614	C#: detecting if running as super user, both in Windows and Mono	private bool AmIRoot()\n{\n   //Declarations:\n   string fileName = "blah.txt",\n          content = "";\n\n   //Execute shell command:\n   System.Diagnostics.Process proc = new System.Diagnostics.Process();\n   proc.EnableRaisingEvents=false; \n   proc.StartInfo.FileName = "whoami > " + fileName;\n   proc.StartInfo.Arguments = "";\n   proc.Start();\n   proc.WaitForExit();\n\n   //View results of command execution:\n   StreamReader sr = new StreamReader(fileName);\n   content = sr.ReadLine();\n   sr.Close();\n\n   //Clean up magic file:\n   File.Delete(fileName);\n\n   //Return to caller:\n   if(content == "root")\n      return true;\n   else\n      return false;\n}	0
26709338	26708785	How to get the specific sub-string position in a string	string inout = "2";\n        int startIndex;\n        int endIndex;\n        startIndex = s.LastIndexOf(inout);\n        endIndex = startIndex + inout.Length-1;	0
29425831	29347689	Location tracking in background with Universal Windows 10 app	private ExtendedExecutionSession session;\n\nprivate async void StartLocationExtensionSession()\n{\n   session = new ExtendedExecutionSession();\n   session.Description = "Location Tracker";\n   session.Reason = ExtendedExecutionReason.LocationTracking;\n   session.Revoked += ExtendedExecutionSession_Revoked;\n   var result = await session.RequestExtensionAsync();\n   if (result == ExtendedExecutionResult.Denied)\n   {\n       //TODO: handle denied\n   }\n}	0
8340331	8339843	ListBox Not showing data	public class Categories \n{\n    public string Id { get; set; }\n    public string Title { get; set; }\n\n    public Categories() { }\n\n    public Categories(string value, string text) \n    {\n        this.Id = value;\n        this.Title = text;\n    }\n}	0
9195186	9195137	How to programatically delete shortcut from user's desktop?	string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nFile.Delete(Path.Combine(desktopPath, "Touch Data.lnk"));	0
23825563	23825291	LINQ - how to sort by date	db.Records\n.Where(i => i.Form.CompetitionID == cID)\n.GroupBy(i => i.Nickname)\n.Select(g => new { MaxCount = g.Count(), MaxDate = g.Max(i => i.DateAdded), Nickname = g.Key})\n.OrderByDescending(gx => gx.MaxCount)\n.ThenByDescending(gx => gx.MaxDate)\n.Select(gx => new TopUserModel()\n{\n     Nickname = gx.Nickname,\n     Position = gx.MaxCount\n}).Take(100).ToList();	0
2957834	2957794	How to extract part of a string?	DateTime.ToString("hh:mmtt")	0
14667789	14667754	Sort string list with dates in C#	var list = new List<string> {"01/01/2013", "10/01/2013", "20/01/2013"};\nvar orderedList = list.OrderByDescending(x => DateTime.Parse(x)).ToList();	0
14484350	14477476	Finding Secondary Tiles in my Background Task fails with code 1	public sealed class SecondaryTileUpdater : IBackgroundTask\n{\n    public async void Run(IBackgroundTaskInstance taskInstance)\n    {\n        //HERE: request a deferral\n        var deferral = taskInstance.GetDeferral();\n\n        var list = await SecondaryTile.FindAllAsync(); // Here it fails :(\n        foreach (SecondaryTile liveTile in list)\n        {\n            // Update Secondary Tiles\n            // (...)\n        }\n\n        //HERE: indicate you are done with your async operations\n        deferral.Complete();\n    }\n}	0
16404847	16404784	How to add 2 of the same properties to a Model?	public class ProductSale\n{\n\n  [ForeignKey("CreatedByUser")]\n  public int CreatedByUserId {get;set;}\n\n  [ForeignKey("ModifiedByUser")]\n  public int UpdatedByUserId {get;set;\n\n\n  public virtual User CreatedByUser {get;set;}\n  public virtual User ModifiedByUser {get;set}\n}	0
13375257	13375227	How to always get a whole number if we divide two integers in c#	totalpagescount = (Totallistcount + perpagecount - 1) / perpagecount ;	0
3255191	3255046	Disallow ListView to have zero selected items	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass MyListView : ListView {\n    protected override void WndProc(ref Message m) {\n        // Swallow mouse messages that are not in the client area\n        if (m.Msg >= 0x201 && m.Msg <= 0x209) {\n            Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);\n            var hit = this.HitTest(pos);\n            switch (hit.Location) {\n                case ListViewHitTestLocations.AboveClientArea :\n                case ListViewHitTestLocations.BelowClientArea :\n                case ListViewHitTestLocations.LeftOfClientArea :\n                case ListViewHitTestLocations.RightOfClientArea :\n                case ListViewHitTestLocations.None :\n                    return;\n            }\n        }\n        base.WndProc(ref m);\n    }\n}	0
34407722	34407607	Splitting list of objects by DateTime property	List<ShowcaseModel> list = new List<ShowcaseModel>();\n//...\nvar gooupByDay = list.GroupBy(o=>o.StartDate.Value.Date);	0
2607618	2607543	Problems in selecting a node in XML with Namespace using XPATH	// Create and load XML reader\nXmlReader reader = XmlReader.Create(new FileStream(@"D.\test.xml", FileAccess.Read));\n\n// get the root element    \nXElement root = XElement.Load(reader);\n\n\n// create instance of XML namespace manager\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(reader.NameTable);\n\n// add your namespace to the manager and give it a prefix\nnsmgr.AddNamespace("ns", "http://www.portalfiscal.inf.br/nfe");\n\nXElement node = root.XPathSelectElement("//ns:det[@nItem="1"]/ns:prod/ns:cProd", nsmgr);\n.......	0
7752622	7722433	how to get SMS delivery in my C# Application?	sms.RequestDeliveryReport = true;	0
15143355	15143003	Windows Phone app, Convert.tobase64 gives ArgumentOutOfRange exception	Convert.ToBase64CharArray(_imageBytes, 0, 3000, outa, 0);\nConvert.ToBase64CharArray(_imageBytes, 3000, 3000, outa, 4000);\nConvert.ToBase64CharArray(_imageBytes, 6000, 3000, outa, 8000);\nConvert.ToBase64CharArray(_imageBytes, 9000, 1000, outa, 12000);	0
19402078	19402024	C# how to inherit from default constructor	public AuctionVehicle(int AuctionID) : this() \n{\n   ...\n}	0
25748355	25748093	how to recognize "(x,y)" from the text	string text = "aldkjf;la(100,200)a;slknl;knw(400,400)";\n    string pattern = @"\(\d+,\d+\)";\n\n    var matches = Regex.Matches(text, pattern);\n\n    foreach(Match match in matches)\n    {\n        var numberMatches = Regex.Matches(match.Value, @"\d+");\n\n        double x = double.Parse(numberMatches[0].Value);\n        double y = double.Parse(numberMatches[1].Value);\n\n        Console.WriteLine("{0}, {1}", x, y);\n    }	0
12748090	12746993	XmlDocument loading from file with non latin file path	var d = File.ReadAllText(xmlPath);\nxmlData.LoadXml(d);	0
31821852	25374621	c# JSON Serialization Data Member Order	[DataMember(Order = 10)]	0
13338577	13338562	How to scramble string C#?	StringBuilder jumbleSB = new StringBuilder();\n         jumbleSB.Append(theWord);\n         int lengthSB = jumbleSB.Length;\n         for (int i = 0; i < lengthSB; ++i)\n         {\n             int index1 = (rand.Next() % lengthSB);\n             int index2 = (rand.Next() % lengthSB);\n\n             Char temp = jumbleSB[index1];\n             jumbleSB[index1] = jumbleSB[index2];\n             jumbleSB[index2] = temp;\n\n         }\n\n         Console.WriteLine(jumbleSB);\n    }	0
5687524	5687471	C# mvc3 redirect sitemap.xml to controller action	routes.MapRoute(\n    "Sitemap",\n    "sitemap.xml",\n    new { controller = "Home", action = "Sitemap" } \n);	0
18847508	18847300	Find an item on a list using wildcard characters	list.Where(str => str.Contains("battle"));	0
9111716	9105222	FileHelpers Take Limit?	FileHelperAsyncEngine engine = new FileHelperAsyncEngine(typeof(Customer)); \nengine.BeginReadFile("TestIn.txt"); \n\nint recordCount = 0;\n\nforeach (Customer cust in engine)\n{    \n    // your code here \n    Console.WriteLine(cust.Name);\n\n    recordCount++;\n    if (recordCount > 100)\n        break; // stop processing \n}\n\nengine.Close();	0
19348788	19348622	How to get child node by number from XML file	XDocument xdoc = XDocument.Parse(xml);\nvar ordered = xdoc.Descendants("data")\n                  .OrderByDescending(x => int.Parse(x.Attribute("times").Value))\n                  .ToArray();\nxdoc.Root.RemoveAll();\nxdoc.Root.Add(ordered);	0
26603320	26602415	Searching for a specific sound within an audio file	Fast Fourier transform (FFT)	0
7550523	7550343	Removing text using regular expressions	string s = "653 09-23-2011 21 27 32 40 52 36 ";\ns = s.Substring(s.IndexOf("2011 ") + 5);	0
23862848	23862764	How to convert AjaxCalendar extender Textbox Date input to SqlServer Date input	var cmd = new SqlCommand(connectionstring);\ncmd.CommandText = "SELECT A.Col1,B.Application_Date,B.ID, FROM RESULT as B, EMPLOYEE as A WHERE B.Application_Date, B.Employee_Name Between @inputone AND @inputtwo";\ncmd.Parameters.Add("@inputone", SqlDbType.DateTime).Value = inputone;\ncmd.Parameters.Add("@inputtwo", SqlDbType.DateTime).Value = inputtwo;	0
28767787	28767660	Avoiding CamelCasePropertyNamesContractResolver for a specific method	return Json(data, new JsonSerializerSettings(){ContractResolver = new DefaultContractResolver()});	0
30432561	30432006	Get all the values from excel file by using linqtoexcel	public ActionResult ExcelRead()\n{\n    string pathToExcelFile = ""\n    + @"C:\MyFolder\ProjectFolder\sample.xlsx";\n\n    string sheetName = "Sheet1";\n\n    var excelFile = new ExcelQueryFactory(pathToExcelFile);\n    var getData = from a in excelFile.Worksheet(sheetName) select a;\n    string getInfo = String.Empty;\n\n    foreach (var a in getData)\n    {\n        getInfo += "Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">>   ";\n\n    }\n    ViewBag.excelRead = getInfo;\n    return View();\n}	0
12982041	12981986	Concatenating IEnumerable<KeyValuePair<string,string>> values into string using Linq	var strings = attributes.Select(kvp => string.Format("@{0}={1}", kvp.Key, kvp.Value));\nstring path = string.Join(" and ", strings);	0
14046057	14045967	Adding XML attribute to an element	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\nXmlNodeList dataNodes = doc.GetElementsByTagName("DATA");\nif (dataNodes != null && dataNodes.Count > 1)\n{\n    dataNodes[0].Attributes.Append(doc.CreateAttribute("D_COMMS", "On this date we said"));\n}	0
14440298	14440101	Internationalize Windows Phone 7 App	public App()\n    {\n        // Standard Silverlight initialization\n        InitializeComponent();\n\n        // Phone-specific initialization\n        InitializePhoneApplication();\n\n        // Set the current thread to US!\n        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");\n        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");	0
25269996	25212646	Parameter by reference in a lambda expression in C# and Microsoft Fakes	dataset = new System.Data.DataSet()	0
7149010	7148997	Problem with vb to c# converter	Dictionary<string, ConfigKey>	0
30406444	30406254	Reading files in c# with filestream and streamreader	string text = Encoding.UTF8.GetString(buffer, start_len, end_len);	0
22742894	22742694	How to add in another date column field codes so that update can work in the gridview?	if (DateTime.TryParseExact(strStartDate, new string[] { "dd/MM/yyyy" } ,\n                               System.Globalization.CultureInfo.InvariantCulture,\n                               System.Globalization.DateTimeStyles.None, out datStartDate)\n    &&\n    DateTime.TryParseExact(strEndDate, new string[] { "dd/MM/yyyy" } ,\n                               System.Globalization.CultureInfo.InvariantCulture,\n                               System.Globalization.DateTimeStyles.None, out datEndDate)\n   )\n   {\n       updateEventGridviewRecord(id, strEventType, strEventName, datStartDate);\n   }	0
5368217	5368200	How to convert one type to another using reflection?	Mapper.CreateMap<FromCsvFile, OptionsEnt >();\nreturn Mapper.Map<FromCsvFile, OptionsEnt>(fromCsvFile);	0
27328697	27327912	How to rename a file with string format in C#?	string path = @"C:\Users\Public\fileName.txt";\n\n if (File.Exists(path))\n            File.Move(path, "DestinationFilePath");	0
10387296	10387165	Is there a way to modify these column definitions programmatically?	Width="{Binding Width, ElementName=ColumnXHeader}"	0
9096896	9096795	How do you mock a void method that sets a read-only property?	var randomizerClass = new RandomizerClass();\nranomizerClass.GetRandomValue();\nvar result = ranomizerClass.Result;\n\nAssert.IsTrue(result > 0 && result < 101);	0
6412633	6411993	Call Default Model Binder from a Custom Model Binder?	public class DateTimeModelBinder : IModelBinder\n{\n\n#region IModelBinder Members\npublic object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n{\n\n    if (controllerContext.HttpContext.Request.HttpMethod == "GET")\n    {\n        string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];\n        DateTime dt = new DateTime();\n        bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt);\n        if (success)\n        {\n            return dt;\n        }\n        else\n        {\n            return null;\n        }\n    }\n\n    DefaultModelBinder binder = new DefaultModelBinder();\n    return binder.BindModel(controllerContext, bindingContext);\n\n}\n#endregion\n}	0
3258057	3240170	How can I modify a POST request using a custom IHttpModule and an HttpRequest filter?	// return bytesRead;\nreturn newByteCountLength;	0
4342910	4328343	Programmatically read from library	SPFile xslFile = SPContext.Current.Web.GetFile("/myWeb/myXlsLibrary/myXsl.xsl"); \nStream xslStream = xslFile.OpenBinaryStream();	0
11738841	11738684	Inject in custom membership provider with StructureMap	DependencyResolver.Current.GetService<IRepository<User>>();	0
14965200	14964990	HTML Agility Pack and LINQ	//*[@id=\"Table3\"]/tbody/tr[td//text()[contains(., 'targetString')]]	0
9646129	9644585	How to display a MessageBox in a FormClosing event to prompt for cancellation?	protected override void OnFormClosing(FormClosingEventArgs e) {\n        base.OnFormClosing(e);\n        if (!e.Cancel) {\n            if (MessageBox.Show("Really?", "Close", MessageBoxButtons.YesNo) != DialogResult.Yes) {\n                e.Cancel = true;\n            }\n        }\n    }	0
19662136	19589272	How to create an application global Progress Window without blocking running threads?	public static class CWaitingMessage\n{\n    private static event Action CloseWindow = delegate { };\n\n    public static void Open(string sMessage)\n    {\n        Thread t = new Thread(delegate()\n               {\n                   frmWaiting window = new frmWaiting(sMessage);\n                   CloseWindow += () => window.Dispatcher.BeginInvoke(new ThreadStart(() => window.Close()));\n                   window.Closed += (sender2, e2) => Window.Dispatcher.InvokeShutdown();\n                   window.Show();\n                   System.Windows.Threading.Dispatcher.Run();\n               });\n\n        t.SetApartmentState(ApartmentState.STA);\n        t.Start();\n    }   \n\n    public static void Close()\n    {\n        CloseWindow();\n    }      \n}	0
301341	298491	How do I close a form when a user clicks outside the form's window?	protected override void OnShown(EventArgs e)\n{\n    base.OnShown(e);\n    this.Capture = true;\n}\n\nprotected override void OnCaptureChanged(EventArgs e)\n{\n    if (!this.Capture)\n    {\n        if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))\n        {\n            this.Close();\n        }\n        else\n        {\n            this.Capture = true;\n        }\n    }\n\n    base.OnCaptureChanged(e);\n}	0
25359579	25359496	Is there a way to get the declaring method/property of an Attribute at runtime	foreach (var propertyInfo in type.GetProperties())\n{\n    if (propertyInfo.IsDefined(typeof(FooPropertyAttribute), true))\n    {\n        var attr = (FooPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(FooPropertyAttribute), true)[0];\n        attr.FooMethod(propertyInfo); // <-- here\n    }\n}	0
6293997	6293932	Extract Values between Open/Close Tags	Match result = System.Text.RegularExpressions.Regex.Match(inputString,"<editID>.*</editID>");\nMatch result = System.Text.RegularExpressions.Regex.Match(inputString,"<editDate>.*</editDate>");	0
25997194	25997127	How to set an object list to a class?	public class SomeClass{\n    ...\n\n    List<Object> requestQueue = new List<Object> (20);\n\n    BleRequest currentRequest = null;//Another class\n\n    requestQueue.Add (currentRequest);\n\n    currentRequest = requestQueue[0] as BleRequest;\n    requestQueue.RemoveAt(0);\n    ...\n}	0
6211360	6211311	Logging in to a website with C#	using (var ie = new IE(loginUrl)) \n{\n    if (ie.TextField("username").Exists \n       && ie.TextField("password").Exists)\n    {\n        ie.TextField("username").Value = "username";\n        ie.TextField("password").Value = "password";\n        ie.Button(Find.ByName("submit")).Click();\n    }\n}	0
9520320	9520285	How can i construct a variable name in code from a string?	List<string> test = new List<string>();\nfor (int i = 1; i < 10; i++)\n{\n    test.Add("some text");\n}	0
9832857	9816243	Mocked object doesn't have all properties shown in Intellisense - in one project but has them in the other	public static Range Cell\n{\n    get\n    {\n        var mockCell = Substitute.For<Range>();\n        mockCell.Address.Returns("$A$1");\n        mockCell.Formula = "=1+1";\n        mockCell.ToString().Returns(mockCell.Formula.ToString());\n        //mockCell.ToString().Returns(info => mockCell.Formula.ToString());\n        //SubstituteExtensions.Returns(mockCell.ToString(),  mockCell.Formula.ToString());\n        mockCell.Worksheet.Returns(Sheet);\n        mockCell.Worksheet.Name.Returns(MockSheetName);\n\n        return mockCell;\n    }\n}	0
25099037	25098999	c# datatable group by many columns	DateTime epoch = new DateTime(1970, 1, 1);\n\nvar result = (from row in new DataTable().AsEnumerable()\n              group row by new\n                           {\n                               Date = row.Field<string>("Date"),\n                               Slice = row.Field<string>("Slice")\n                           }\n              into grp\n              select new\n                     {\n                         AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),\n                         Date = ((DateTime.Parse(grp.Key.Date)) - epoch).TotalMilliseconds,\n                         grp.Key.Slice\n                     }).ToList();	0
4069868	4069501	Factory Method or Some Other Pattern?	public class TaskResolverAttribute : Attribute\n{\n    public Type ResolverType { get; private set; }\n\n    public TaskResolverAttribute(Type resolverType)\n    {\n        if (!typeof(ITaskResolver).IsAssignableFrom(resolverType))\n            throw new ArgumentException("resolverType must implement ITaskResolver");\n\n        ResolverType = resolverType;\n    }\n}\n\npublic class MyTaskResolver : ITaskResolver\n{\n}\n\n[TaskResolver(typeof(MyTaskResolver))]\npublic class MyTask\n{\n}\n\npublic static class TaskResolverFactory\n{\n    public static ITaskResolver GetForType(Type taskType)\n    {\n        var attribute =\n            Attribute.GetCustomAttribute(taskType, typeof(TaskResolverAttribute)) as TaskResolverAttribute;\n        if (attribute == null)\n            throw new ArgumentException("Task does not have an associated TaskResolver");\n\n        return (ITaskResolver)Activator.CreateInstance(attribute.ResolverType);\n    }\n}	0
4447014	4445414	How to skip the function with lambda code inside?	[DebuggerStepThrough]\nstatic A GetA<A>(IList<A> aCollection, string b) where A : Test\n{\n    DoNoOp();\n    return aCollection.FirstOrDefault(a => a.b == b);\n}\n\nstatic void DoNoOp()\n{\n    // noop\n    Console.WriteLine("got here");\n}	0
2882737	2882619	Hello World to Twitter from C#	var tweet = twitterCtx.UpdateStatus("Hello world");	0
2991667	2991613	.NET: Calling GetInterface method of Assembly obj with a generic interface argument	Type type = AsmType.GetInterface("PluginInterface`1", true);	0
12178274	12176907	Aggregating Left Join in NHibernate using QueryOver/ICriteria	Comment comment=null;\nvar results=session.QueryOver<Blog>()\n    .Left.JoinAlias(b=>b.Comments,()=>comment)\n    .SelectList(\n        list=>list\n        .SelectGroup(b=>b.Id)\n        .SelectGroup(b=>b.Title)\n        .SelectCount(b=>comment.Id)\n    )\n    .List<object[]>()\n    .Select(b => new {\n                Id = (Guid)b[0],\n                Title = (string)b[1],\n                Comments=(int)b[2]\n               });	0
33044531	33044437	How to convert date format to different date format?	var result = DateTime.Parse("2015-09-18T19:00:00").ToString("yyyy/MM/dd/HHmm")	0
23476413	23476096	How to use JMail component in ASP.NET website?	Microsoft.Net.Mail	0
3783942	3783925	get values from nested Dictionary using LINQ. Values of Dictionary are list of lists	Dictionary<int, List<List<int[]>>> dictionary = ...\nvar values = dictionary.Values.SelectMany(x => x.SelectMany(y => y.SelectMany(z => z));	0
2636239	2636065	Alpha in ForeColor	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyLabel : Label {\n  protected override void OnPaint(PaintEventArgs e) {\n    Rectangle rc = this.ClientRectangle;\n    StringFormat fmt = new StringFormat(StringFormat.GenericTypographic);\n    using (var br = new SolidBrush(this.ForeColor)) {\n      e.Graphics.DrawString(this.Text, this.Font, br, rc, fmt);\n    }\n  }\n}	0
23418447	23415984	Using PngBitmapDecoder, MemoryStream, FlowDocument, XPSDocument to Preview Images	public static BitmapSource GetBitmapImage(Bitmap bitmap)\n{\n    BitmapImage bitmapImage = new BitmapImage();\n    using (MemoryStream stream = new MemoryStream())\n    {\n        bitmap.Save(stream, ImageFormat.Png);\n        stream.Position = 0;\n        bitmapImage.BeginInit();\n        bitmapImage.StreamSource = stream;\n        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n        bitmapImage.EndInit();\n    }\n    return bitmapImage;\n}	0
19484354	19484302	Setting up a Loop	Set salesA, salesB, salesC = 0\nWhile choice != 'Z'\nBegin\n    Initials = InputString\n    Number = InputNumber\n    If string[0] == 'A' Then salesA += Number\n    Else If string[0] == 'B' Then salesB += Number\n    Else If string[0] == 'C' Then salesC += Number\nEnd\nPrint salesA, salesB and salesC	0
18017793	18017744	Trying to Replace ' with literal C#	test = test.Replace("'", @"\'");	0
4600572	4600509	CollectionViews in MVVM	CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(dt); \n\n this will give you the CollectionView in ViewModel	0
1560179	1560167	How to access wikipedia	string Text = "http://www.wikipedia.org/";\nHttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Text);\nrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";\nHttpWebResponse respons;\nrespons = (HttpWebResponse)request.GetResponse();\nEncoding enc = Encoding.GetEncoding(respons.CharacterSet);\nStreamReader reader = new StreamReader(respons.GetResponseStream(), enc);\nstring sr = reader.ReadToEnd();	0
11970440	11966436	What's my mistake in send a confirmation email in ASP.net with C#	var email = new MailMessage();\n        email.From = new MailAddress("johnnytables@xkcd.com");\n        email.To.Add("johnnysmom@xkcd.com");\n        email.Subject = "DROP TABLE STUDENT";\n        email.Body = "Our student records are gone!";\n\n        SmtpClient smtp = new SmtpClient();\n        smtp.Host = "127.0.0.1";\n        smtp.Port = 25;\n        smtp.UseDefaultCredentials = true;\n        smtp.Credentials = new NetworkCredential("johnnytables@xkcd.com", "password");\n        smtp.Send(email);	0
21458858	21457211	C# Upload a zip file of two files to FTP based on two strings without being able to save anywhere	Local Storage	0
757929	738193	How-to draw a circle on a changing background	Graphics g = this.CreateGraphics();	0
16120662	16120649	c# How to return a list through a class return?	private List<Module> modules;\n\npublic void AddModule(Module add)\n{\n    modules.Add(add);\n}\n\n// this one should be generic too\npublic List<Module> Modules\n{\n    get { return modules; }\n}	0
10206332	10206271	How to exit a Windows Forms/C# program	Application.Run(a.Form);	0
31544200	31544090	How to refer to current open window in wpf	var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);	0
19923341	19923238	C# SQL Server Compact Insert solution	var cmd = new SqlCeCommand(\n    "INSERT INTO Players (PlayerID, PlayerName, Team_Abbreviation) VALUES (@ID, @Name, @Team);", sql);\ncmd.Parameters.AddWithValue("@ID", player.ID.Replace("/ice/player.htm?id=", null));\ncmd.Parameters.AddWithValue("@Name", player.Name);\ncmd.Parameters.AddWithValue("@Team", player.Team);	0
5340826	5340552	ASPx set Cookie Domain	MyCookie.Domain = "test.co.uk";	0
32801451	32800775	How to prevent API calls to be called more than once	var vctx = new VenueContext();\n        using(var dbtransaction = vctx.Database.BeginTransaction(IsolationLevel.RepeatableRead))\n        {\n            try\n            {\n                var order = vctx.Orders.Include("Venue").Include("Transactions.MenuItem").FirstOrDefault(x => x.Id == orderid);\n                if (order.StatusId != 1)\n                {\n                    return false;\n                }\n                if (status == 3 || status == 4)\n                {\n                    vctx = MoneyRepository.AddMoney(order.UserId, order.Total * -1, vctx);\n                }\n                order.StatusId = status;\n                vctx.SaveChanges();\n                dbtransaction.Commit();\n            }\n            catch (Exception)\n            {\n                dbtransaction.Rollback();\n                return false;\n            } \n        }\n        return true;\n    }	0
9933844	9894316	Using Ruby to connect to a Microsoft SOAP web service that requires a username, password and a security certificate (.cer file) to connect to it	client = Savon::Client.new do\n  http.auth.basic "user_name", "password"\n\n  # Use a local wsdl\n  wsdl.document = File.expand_path("../wsdl/ebay.xml", __FILE__)\n  # or from internet\n  wsdl.document = "http://service.example.com?wsdl"\n\n  # to list SOAP actions\n  client.wsdl.soap_actions\nend	0
1283437	1283433	Parsing Information out of a Scraped Screen (HTML)	myDoc.SelectSingleNode("//div[@class='header']/h2").InnerText	0
9456736	9456670	How do I get the total number of index of a ComboBox in WPF?	var cb = new ComboBox();\nvar nrOfItems = cb.Items.Count;	0
251994	251439	Passing int list as a parameter to a web user control	class IntListConverter : TypeConverter {\n    public static List<int> FromString(string value) {\n       return new List<int>(\n          value\n           .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n           .Select(s => Convert.ToInt32(s))\n       );\n    }\n\n    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {\n        if (destinationType == typeof(InstanceDescriptor)) {\n            List<int> list = (List<int>)value;\n            return new InstanceDescriptor(this.GetType().GetMethod("FromString"),\n                new object[] { string.Join(",", list.Select(i => i.ToString()).ToArray()) }\n            );\n        }\n        return base.ConvertTo(context, culture, value, destinationType);\n    }\n}	0
17534119	17532974	Swagger Api Documentation - Model List<Enum>	{\n    "myClass": {\n        "id": "myClass",\n        "properties": {\n            "myList": {\n                "type": "List",\n                "items": {\n                    "type": "string"\n                },\n                "allowableValues": {\n                    "valueType": "LIST",\n                    "values": [\n                        "alpha",\n                        "bravo",\n                        "charlie"\n                    ]\n                }\n            }\n        }\n    }\n}	0
7022831	7022049	Xdocument get subelemnts attributes with Linq	var loopInfo = from loop in document.Descendants(ns + "Loop")\n               select new Loop\n               {\n                   LoopID = loop.Attribute("LoopId").Value,\n                   LoopIdentifier = loop.Attribute("Identifier").Value,\n                   LoopSegments = loop.Descendants(ns + "Segment").Select(s => s.Attribute("SegmentId").Value).ToArray(),\n                   LoopUsage =  loop.Descendants(ns + "Segment").Select(s => s.Attribute("Usage").Value).ToArray()\n               };	0
7971588	7970666	Get cell phone manufacturer and model names with compact framework	StringBuilder sb = new StringBuilder(256);\n\n    if (SystemParametersInfoString(SPI_GETPLATFORMTYPE, sb.Capacity, sb, 0) != 0)\n    {\n        String name = sb.ToString();        \n    }	0
19588458	19586799	Vertex Cube Center of Rotation	public void Render(Camera cam)\n{\n    //...\n    //push the cube to the origin\n    bEffect.World *= Matrix.CreateTranslation(-50, -50, 50); \n    //perform the rotation\n    bEffect.World *= cam.rotX;\n    bEffect.World *= cam.rotY;\n    bEffect.World *= cam.rotZ;\n    //undo the translation\n    bEffect.World *= Matrix.CreateTranslation(50, 50, -50);\n    //...	0
12920742	3604280	C# - Running a new process as User - with OUT a password?	LogonUser()	0
33926069	33925903	C# precisely show label for X seconds and hide it for Y seconds	private async Task DoIt()\n{\n    for(int i = 0 ; i < numExpositions; i++)\n    {\n        wordLabel.Visible = true;\n        await Task.Delay(expositionTime); //expositionTime is the number of milliseconds to keep the label visible\n        wordLabel.Visible = false;\n        await Task.Delay(intervalTime); //intervalTime is the number of milliseconds to keep the label hidden\n    }\n\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    DoIt();\n}	0
5572264	5572168	Can you paste a block of cells in one shot using Excel Interop w/o using the clipboard?	void SetRange(Worksheet worksheet, DataSet dataSet)\n{\n    object[] values = GetValuesFromDataSet(dataSet);\n    int rowCount = values.GetUpperBound(0);\n    int columnCount = values.GetUpperBound(1);\n    Range range = worksheet.Range(worksheet.Cells(1, 1), worksheetCells.(rowCount, columnCount));\n    range.Value = values;\n}	0
14673458	14672960	How can I get the certain data from autonumber id using a SQL select statement	string sqltest = "select id from items where description = @description and class = @class";	0
23853503	23652243	Display an image for a TreeNode	DHTMLX Tree View	0
30206007	30205435	Display Different Drop Down list values based on a textbox value of Integer Data type	con.Open();\nSqlCommand cmd = new SqlCommand("SELECT DISTINCT Address_Type FROM \nContact_AddressInfo WHERE ContactID ='" + TextBox.Text + "'", con);\nSqlDataReader ddlValues;\nddlValues = cmd.ExecuteReader();\nddl.DataSource = ddlValues;\nddl.DataValueField = "Address_Type";\nddl.DataTextField = "Address_Type";\nddl.DataBind();	0
21774452	21774315	Find object in tree of objects	private Industry GetIndustryById(List<Industry> IndustryList, int? id)\n{\n    if (id != null)\n    {\n        foreach (Industry industry in IndustryList)\n        {\n            if (industry.id == id)\n            {\n                return industry;\n            }\n        }\n        foreach (Industry industry in IndustryList)\n        {\n            if (industry.industryList != null)\n            {\n                // Here was your mistake. If you return GetIndustryById()\n                // without checking for null first, you will return null\n                // if that subtree doesn't contain the target, even if\n                // a subsequent subtree does.\n\n                var result = GetIndustryById(industry.industryList, id);\n\n                if (result != null)\n                    return result;\n            }\n        }\n    }\n    return null;\n}	0
6891469	6891267	Copying rows from one DataGridView to another	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n{\n    if (this.dataGridView2.DataSource != null)\n    {\n        this.dataGridView2.DataSource = null;\n    }\n    else\n    {\n        this.dataGridView2.Rows.Clear();\n    }\n    for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)\n    {\n        int index = dataGridView2.Rows.Add();\n        dataGridView2.Rows[index].Cells[0].Value = dataGridView1.SelectedRows[i].Cells[0].Value.ToString();\n        dataGridView2.Rows[index].Cells[1].Value = dataGridView1.SelectedRows[i].Cells[1].Value.ToString();\n        .....\n    }\n}	0
12029596	12029572	C# insert values to string	text = text.Replace("[", "[[")\n           .Replace("]", "]]");	0
20201306	20201268	Formating a phone number in c#	Console.WriteLine(String.Format("({0})-{1}", phoneNum.SubString(0, 2), phoneNum.SubString(3, 9));	0
20776808	20776768	2d Array in C# with random numbers	Random rnd = new Random();\n    int[,] lala = new int[3,5];\n    for(int i=0;i<3;i++)\n    {\n        for(int j=0;j<5;j++)\n        {\n            lala[i, j]= rnd.Next(1, 10);\n            Console.WriteLine("[{0}, {1}] = {2}", i, j, lala[i,j]);\n        }\n    }	0
13757741	13757312	How to store hashed password in database	var provider = new SHA1CryptoServiceProvider(salt);\nbyte[] bytes = Encoding.UTF8.GetBytes(input);\nstring result = Convert.ToBase64String(provider.ComputeHash(bytes)); // store it	0
3246306	3246237	How to find multiple occurrences with regex groups?	string text = "C# is the best language there is in the world.";\nstring search = "the";\nMatchCollection matches = Regex.Matches(text, search);\nConsole.WriteLine("there was {0} matches for '{1}'", matches.Count, search);\nConsole.ReadLine();	0
33640449	33640362	How can I search a database for tags relating to a post?	var posts = db.Posts.Where(p=>p.Tags.Any(t=>t.id==id));	0
20522701	20522358	listbox highlights the selecteditem even after coming back in mvvm windows phone app	listbx.SelectedIndex = -1;	0
2142700	2142650	Reflection Help - Set properties on object based on another object	Type target = typeof(DisabilityPaymentAddEntity);\nforeach(PropertyInfo pi in display.GetType().GetProperties())\n{\n     PropertyInfo targetProp = target.GetProperty(pi.Name);\n     if(targetProp!=null)\n     {\n        targetProp.SetValue(this, pi.GetValue(display, null), null);\n     }\n}	0
3981380	3981364	Is there an existing library to parse JSON to Dictionary<String,Object> in .net?	var json = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };\nvar dict = (IDictionary<string, object>)json.DeserializeObject(yourString);	0
32962304	32962116	how to get string array values from a stream?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Runtime.Serialization;\nusing System.IO;\nusing System.Net;\nusing Newtonsoft.Json;\n\nnamespace ConsoleApplication1\n{\n  class Program\n{\n    static void Main(string[] args)\n    {\n        using (var client = new WebClient())\n        {\n            var url = "http://localhost:14596/api/values";\n            client.Headers[HttpRequestHeader.ContentType] = "application/json";\n            client.Headers[HttpRequestHeader.Accept] = "application/json";\n            byte[] result = client.DownloadData(url);\n            // now use a JSON parser to parse the resulting string back to some CLR object\n            string[] resultArr = parse(result);\n\n        }\n    }\n\n    public static string[] parse(byte[] json)\n    {\n         string jsonStr = Encoding.UTF8.GetString(json);\n            return JsonConvert.DeserializeObject<string[]>(jsonStr);\n        }\n\n    }\n}	0
4343908	4343452	Detect scroll on a WebBrowser control	protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)\n    {\n        Follow();\n        if (!IsBusy && Url == e.Url && ReadyState == WebBrowserReadyState.Complete)\n        {\n            Document.Window.AttachEventHandler("onscroll", DocScroll);\n        }\n    }	0
9205603	9205340	Drawing One Element per Second	List<UIElement> elements = GetElements();\n\nCanvas canvas = new Canvas();\nthis.AddChild(canvas);\n\nvar bw = new BackgroundWorker();\n\nbw.DoWork += ( sender, e ) =>\n{\n  foreach (var k in elements)\n  {\n     Dispatcher.BeginInvoke( new Action( () => canvas.Children.Add( k ) ) );\n     Thread.Sleep( 1000 );\n  }\n};\n\nbw.RunWorkerAsync();	0
6918017	6917933	Find All User's AppData Directories	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
29404095	29402559	Convert string to IInputStream in C#	public static IInputStream ToInputStream(this string input)\n{\n    byte[] bytes = Encoding.UTF8.GetBytes(input);\n    MemoryStream stream = new MemoryStream(bytes);\n    return stream.AsRandomAccessStream();\n}	0
5242394	5242371	how to check if i have At least one file *.bak in my folder?	var hasBak = Directory.GetFiles(yourdir, "*.bak").Length > 0;	0
22003118	22003082	How to randomly get a string from a collection but prefer strings at the beginning of the collection	Random rnd = new Random();\nvar randomItem = list[Math.Min(rnd.Next(list.Count+1), rnd.Next(list.Count+1))];	0
21866635	21834438	Cannot assign new value to a read-only attribute	var TestId = Oid.FromToken("Test:26017", _context.MetaModel);\nvar TestAsset = _context.MetaModel.GetAssetType("Test");\nvar newTestAsset = _context.Services.New(TestAsset, TestId);\n\nvar TestStatusAttr = newTestAsset.GetAttributeDefinition("Status.Name");\nnewTestAsset.SetAttributeValue(TestStatusAttr, "Failed");\n_context.Services.Save(newTestAsset);	0
32818357	32816899	Find the object which contains an object with a specific property value in a nested list	var adressWithTypeA = Addresses\n  .FirstOrDefault( s => s.AddressTypes.Any(x => x._Type_ == "a"))\n\nif (adressWithTypeA != null)\n{\n  var adressCode = adressWithTypeA.AddressCode;\n}	0
20844995	20844959	How to parse a string by certain pattern and tokenize the result to the dictionary?	str.Split(new string[]{" AND "}, StringSplitOptions.RemoveEmptyEntries)\n   .Select(likeClause => likeClause.Split(new string[]{" LIKE "}, StringSplitOptions.RemoveEmptyEntries))\n   .ToDictionary(a => a[0], a => a[1].Trim(new char[]{'\'', '%'}))	0
17073444	17053968	How to avoid migrations in model first database with Entity Framework 5 and code first entities?	Add-Migration -IgnoreChanges	0
28590613	28590410	HtmlAgilityPack cant get string indexer	var s2 = htmlDocument.DocumentNode\n         .Descendants()\n         .Where(a => a.Attributes["id"]!=null && a.Attributes["id"].Value == "ct")\n         .ToList();	0
26361699	26361441	How do I detect Ctrl + S in a Window in C#? My EventArgs don't have `e.Modifiers`	private void CutContractKeyDown(object sender, KeyEventArgs e)\n{\n      if (e.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control)\n     {\n       MessageBox.Show("CTRL + S");\n     }\n}	0
6610112	6608825	How can I join two tables and use aggreagate function in one LINQ query	from p in db.Articles.Where(p => p.user_id == 2)\nselect new\n{\n    p.article_id, \n    p.title, \n    p.date, \n    p.category,\n    AverageScore = db.Articles_Scores\n                     .Where(o => o.user_id == p.user_id && p.article_id == o.article_id)\n                     .Average(m => m.score)\n};	0
26733891	26733739	Converting string to date time	string originalDate = "09/25/2014 09:18:24";\n\nDateTime formattedDate;\n\nif (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))\n{\n    string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);\n}	0
33580446	33458502	Set the window state of a hidden window	pHandle = FindWindowEx(IntPtr.Zero, pHandle, "Notepad", Nothing)	0
5151645	5151561	How to set a columnspan in tableLayoutPanel	public Form1() {\n        InitializeComponent();\n        var button = new Button();\n        button.Dock = DockStyle.Fill;\n        tableLayoutPanel1.Controls.Add(button);\n        tableLayoutPanel1.SetCellPosition(button, new TableLayoutPanelCellPosition(0, 1));\n        tableLayoutPanel1.SetColumnSpan(button, 2);\n    }	0
9125699	9124587	Access the ToolStripMenuItem child in WinForms	private void ActivateMenus(ToolStripItemCollection items)\n{\n    foreach (ToolStripMenuItem item in items)\n    {\n        item.Visible = true;    \n        ActivateMenus(item.DropDown.Items);\n    }\n}	0
28990128	28960854	How to get Tags of Azure ResourceManagementClient object	var credentials = new TokenCloudCredentials(<subscrtiption id>, <token>);\nnew ResourceManagerClient(credentials).DoSomething();	0
15294680	15294568	Passing String to next XAML Page	string str="mydata";\nthis.Frame.Navigate(typeof(QualityRecordsResults), mydata);	0
18373768	18371867	How to retrieve aggregated values from a linq query?	from spl in SpeciesLists \n             join ar in Areas on spl.Station.Area equals ar.Id \n             join ground  in Grounds on ar.Ground equals ground.Id \n             join re in Regions on ground.Region  equals re.Id \n             where spl.Station.Trip.year ==2013\n             && spl.Station.Trip.ProtectedArea == 1\n             group spl by new { slp.Description, ar.description, ground.Code } into Result\n             select new \n               {\n                  SpciesCommonName = Result.Key.Description,\n                  Are = Result.Key.description,\n                  Ground = Result.Key.Code,\n                  NumberOfTripsInProtectedAreas = Result.Count()\n               }	0
3211821	3211739	extract generic list from generic list using linq	lA.SelectMany(a => a.PropertyOfListOfBType).Where(b => b.SomeProperty).ToList()	0
14398571	14398111	Get common rows in two Data tables	var matched = from table1 in PromotionRequest.AsEnumerable()\n               join table2 in PromotionResponse .AsEnumerable() on\n               table1.Field<string>("PromoId ") equals table2.Field<string>("PromoId ")\n               where table1.Field<string>("PromoId ") == table2.Field<string>("PromoId ")\n               select table2;\nif (matched.Any())\n {\n }	0
23936398	23936314	Accessing a password protected MS access database in C# issue	var dbe = new DBEngine();\nvar databaseFile = @"C:\Users\x339\Documents\Test.accdb";\nvar password = "abc123";\nDatabase db = dbe.OpenDatabase(databaseFile, False, False, string.Format("MS Access;PWD={0}", password));	0
2772829	2772720	Using ftp in C# to send a file	WebRequest request = WebRequest.Create("ftp://" + server + "/");\n\nWebRequest request = WebRequest.Create("ftp://" + server + "/filename.ext");	0
12553886	12552335	MvvmLight IDataService with async await	RaisePropertyChanged(LocationString);	0
27137287	27136614	Create custom column in Linq with sum total of column	TotalAmount = gser.Sum(sumn => sumn.Amount)	0
25742049	25741403	Winform:TreeView Node Collapse without Node Click event firing	bool suppressClick = false;\n\nprivate void treeView1_Click(object sender, EventArgs e)\n{\n    if (suppressClick) return;\n    // else your regular code..\n}\n\nprivate void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n    if (e.Node.IsExpanded)\n         { suppressClick = false; }\n    else { suppressClick = true; }\n}	0
3680634	3680346	Elegant way to split string into 2 strings on word boundaries to minimize length difference	public static string Get2Lines(string input)\n    {\n        //Degenerate case with only 1 word\n        if (input.IndexOf(' ') == -1)\n        {\n            return input;\n        }\n        int mid = input.Length / 2;\n\n        int first_index_after = input.Substring(mid).IndexOf(' ') + mid;\n        int first_index_before = input.Substring(0, mid).LastIndexOf(' ');\n\n        if (first_index_after - mid < mid - first_index_before)\n            return input.Insert(first_index_after, "<BR />");\n        else\n            return input.Insert(first_index_before, "<BR />");\n    }	0
1916843	1916679	How can I get a number to count forward on the screen in WPF?	private DispatcherTimer timer;\nprivate int count = 0;\n\npublic Window1()\n{\n    InitializeComponent();\n    this.timer = new DispatcherTimer();\n    this.timer.Interval = TimeSpan.FromSeconds(1);\n    this.timer.Tick += new EventHandler(timer_Tick);\n    this.timer.Start();\n}\n\nvoid timer_Tick(object sender, EventArgs e)\n{\n    this.textBox1.Text = (++count).ToString();\n}	0
28293695	28275811	Image is not opening after converting with aspose	// If you provide a URL in string, Aspose will load the web page\nvar doc = new Aspose.Words.Document("http://www.google.com");\n// If you just provide the TIF extension, it will save as TIFF image\ndoc.Save(@"c:\out.tif");\n// TO customize, you can use save options in save method	0
12719048	12719013	How to catch all types of exception in one single catch block?	try\n{\n\n}\ncatch(Exception ex)\n{\n     switch (ex.GetType().ToString())\n     {\n         case "System.InvalidOperationException":\n              //cast ex to specific type of exception to use it's properties\n              ((InvalidOperationException)ex).SomeMethod();\n         break;\n         case "System.NotSupportedException":\n             ((System.NotSupportedException)ex).AnotherMethod();\n         break;\n         case "System.Web.Services.Protocols.SoapException":\n             ((System.Web.Services.Protocols.SoapException)ex).OtherMethod();\n         break;\n     }\n\n}	0
5700715	5698160	TcpClient reading data and populating array	NetworkStream clientStream = tcpClient.GetStream();\nMemoryStream messageStream = new MemoryStream();\nbyte[] inbuffer = new byte[65535];\n\nif (clientStream.CanRead)\n{\n    do\n    {\n        var bytesRead = clientStream.Read(inbuffer, 0, buffer.Length);\n        messageStream.Write(inbuffer, 0, bytesRead);\n    } while (clientStream.DataAvailable);\n}\n\nmessageStream.Position = 0;\nvar completeMessage = new byte[messageStream.Length];\nmessageStream.Write(completeMessage, 0, messageStream.Length);	0
34329653	34320872	Can't get a json response from an API with C#	if (response.IsSuccessStatusCode)\n{\n    string json = response.Content.ReadAsStringAsync().Result;\n}	0
22503868	22503762	session variables for classes	temp = Session["userSesh"] as UserData;	0
4472867	4472113	Setting initial focus to a control in a Silverlight form using attached properties	public static void SetInitialFocus(UIElement element, bool value)\n{\n    Control c = element as Control;\n    if (c != null && value)\n    {\n        RoutedEventHandler loadedEventHandler = null;\n        loadedEventHandler = new RoutedEventHandler(delegate\n        {\n            // This could also be added in the Loaded event of the MainPage\n            HtmlPage.Plugin.Focus();\n            c.Loaded -= loadedEventHandler;\n            c.Focus();\n        });\n        c.Loaded += loadedEventHandler;\n    }\n}	0
1774515	1774498	How to iterate through a DataTable	DataTable dt = new DataTable();\n\nSqlDataAdapter adapter = new SqlDataAdapter(cmd);\n\nadapter.Fill(dt);\n\nforeach(DataRow row in dt.Rows)\n{\n    TextBox1.Text = row["ImagePath"].ToString();\n}	0
22427117	22426763	How to mimick VB use of COM Object Interface using C#	var oReservices = new REServices();\noReservices.Init(SessionContext);\nIBBUtilityCode oUtilCode = oReservices\nvar sSQL = "SELECT * FROM CONSTITUENT_BANK"\nvar rs = oUtilCode.CreateDisconnectedADORecordset(sSQL)	0
12603733	12603416	How can I post stories to current logged in user's Facebook wall using Facebook C# SDK?	/me/feed	0
10996723	10964757	Trouble sending XML string to Java webservice from .NET	wc.Headers["Content-Type"] = "text/xml";	0
12080460	12080241	Storing Methods in Entity Framework Database	//this would go in your entity class \npublic int GetNotificationCount()\n{    \n   MethodInfo mi = typeof(HelperClass).GetMethod(this.NotificationMethodName);    \n   return (int)mi.Invoke(this, null); \n}\n\npublic class HelperClass\n{\n  //your class that currently has all the methods to get notification count\n}	0
31436823	31436600	Downloading by C# with indirect url	WebRequest request = HttpWebRequest.Create(@"http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");\nusing (WebResponse response = request.GetResponse())\n{\n    Stream responseStream = response.GetResponseStream();\n    using(var fs = File.Create("MarketWatchPlus-1394.4.24.xlsx"))\n    {\n        var zipStream = new System.IO.Compression.GZipStream(responseStream,  System.IO.Compression.CompressionMode.Decompress,true);\n        zipStream.CopyTo(fs);\n    }\n}	0
19516440	19516274	C# Post data to URI and save html response	string data = "username=<value>&password=<value>"; //replace <value>\n    byte[] dataStream = Encoding.UTF8.GetBytes(data);\n    private string urlPath = "http://xxx.xxx.xxx/manager/";\n    string request = urlPath + "index.php/org/get_org_form";\n    WebRequest webRequest = WebRequest.Create(request);\n    webRequest.Method = "POST";\n    webRequest.ContentType = "application/x-www-form-urlencoded";\n    webRequest.ContentLength = dataStream.Length;  \n    Stream newStream=webRequest.GetRequestStream();\n    // Send the data.\n    newStream.Write(dataStream,0,dataStream.Length);\n    newStream.Close();\n    WebResponse webResponse = webRequest.GetResponse();	0
17172297	17171403	How would one trim all non-alphanumeric and numeric characters from the beginning and end of a string?	string something = "()&*1@^#47*^#21%Littering aaaannnnd??(*&^1#*32%#**)7(#9&^";\n   string somethingNew = Regex.Replace(something, @"[^\p{L}-\s]+", "");	0
14139909	14126254	Entity Framework 5 won't insert self referencing many to many relationship	AutoDetectChangesEnabled = false;	0
27591800	27591552	Get all descendants LINQ to XML	IEnumerable<XElement> output = doc.Descendants("key")\n  .Where(n => n.Value == "CFBundleIconFiles");\n\nIEnumerable<string> result = \n  output.SelectMany(a => \n    (a.NextNode as XElement).Descendants().Select(n => n.Value));\n\nMessageBox.Show(string.Join(Environment.NewLine, result));	0
15848253	15848183	Display JSON Array Data Returned from Controller in Asp.Net MVC	data.Data[0].Title	0
8741226	8740893	A generic error occurred in GDI+ 	Image.FromStream	0
24000416	23981424	Get data of specific cell from selected row in DataGrid WPF C#	DataRowView drv = (DataRowView)myGrid.SelectedItem; \nString result = (drv["CustomerID"]).ToString(); \nMessageBox.Show(result);	0
32834446	32834358	Create a hyperlink from a text file in C#	private void textBox1_DoubleClick(object sender, EventArgs e)\n    {\n        if (string.Compare(textBox1.SelectedText.Trim(), "HERE") == 0)\n            System.Diagnostics.Process.Start("http://www.google.com");\n    }	0
21488672	21488601	Find Line that Contains String and Delete that Line in .txt file	lines = lines.Where(line => !line.Equals("DonatorPlayer")).ToArray();	0
6986089	6986045	Easy but hard Regex	Regex lastRegex = new Regex(@".*Status:(.+?)<>");\nMatchCollection allMatches = lastRegex.Matches(sample);\nif (allMatches.Count > 0)\n{\n    Console.WriteLine(allMatches[allMatches.Count-1].Groups[1].Value);\n}	0
30158703	30158423	Issue with SoundPlayer	var assembly = Assembly.GetExecutingAssembly();\nvar folder = Path.GetDirectoryName(assembly.Location);\nvar soundFile = Path.Combine(folder, "MySoundFile.wav");	0
31546164	31542092	Plus sign in Regular Expression pattern	String input = Regex.Replace(formula, "[( )+]", "");	0
3743596	3743562	C# count of timespan within a timespan	int periods = (int)(TS1.Ticks / TS2.Ticks);	0
31598904	31598743	How to get the values from Html.ListBox in asp.net MVC	public ActionResult MyAction(FormCollection formCollection)\n{\n    var addedItems = formCollection["Empresa"].Split(',');\n\n    //....more code that does stuff with the items\n}	0
13753004	13752912	C# letter permutation with a prefix word	string prefix = "NAME";\nstring alphabet = "abcdefghijklmnopqrstuvwxyz";\n\nIEnumerable<string> words = from x in alphabet\n                            from y in alphabet\n                            select prefix + x + y;	0
9115791	9115497	Get value from selected checkboxes (Checkbox array)	var names = formCollection.AllKeys.Where(c => \n                    c.StartsWith("idCheckBox") && \n                    formCollection.GetValue(c) != null &&\n                    formCollection.GetValue(c).AttemptedValue == "1");	0
9044357	9042561	Dragging Image into a FlowDocument inside a RichTextBox at runtime	if (e.Data.GetDataPresent("ImageSource")) {\n    e.Effects = DragDropEffects.Copy;\n    e.Handled = true;\n}	0
4616904	4616674	VisualSVN - adding from separate Repos?	svn:externals	0
20528425	20528265	Naming and structure of a function	public class ReturnClass\n{\n    public ReturnClass()\n    {\n        IsOk = true;\n    }\n\n    public bool IsOk { get; set; }\n    public string ErrorText { get; set; }\n}	0
23704232	23704127	C# - Is it possible to ignore null values in a rest response?	var jsonConfig = config.Formatters.JsonFormatter;\n   jsonConfig.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;	0
2689884	2689859	split text to parts	System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Microsoft\Pictures\2010-04-22\003.jpg\n");\nstring dir = f.DirectoryName;\nstring file = f.Name;	0
2666622	2666616	Math .Net I want to represent a huuuuge number in .net	System.Numerics.BigInteger	0
7398185	7398147	How do I create an instance from a string that provides the class name?	Activator.CreateInstance(Type.GetType(ClassName));	0
8787980	8787202	Accessing AdornerPanel from an AdornerLayout or an Adorner or a adorned Control?	public void AddLabelDecoration()\n{\n    AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this);\n\n    TextBlock textBlockMarkTooltipContent = new TextBlock();\n    textBlockMarkTooltipContent.Text = "Test Label Adorner";\n\n    AdornerPanel labelAdornerAdornerPanel = new AdornerPanel();\n\n    // add your TextBlock to AdornerPanel\n    labelAdornerAdornerPanel.Children.Add(textBlockMarkTooltipContent);\n\n    // set placements on AdornerPanel\n    AdornerPlacementCollection placement = new AdornerPlacementCollection();\n    placement.PositionRelativeToAdornerHeight(-1, 0);\n    placement.PositionRelativeToAdornerWidth(1, 0);\n    AdornerPanel.SetPlacements(labelAdornerAdornerPanel, placement);\n\n    // create Adorner with AdornerPanel inside\n    _labelAdornerMarkTooltipContentAdorner = new Adorner(this)\n    {\n        Child = labelAdornerAdornerPanel\n    };\n\n    adornerLayer.Add(_labelAdornerMarkTooltipContentAdorner);\n}	0
16967720	16967650	How can I identify a specific call to a function automatically?	using System.Runtime.CompilerServices;\n\nvoid Main()\n{\n    var myObj = new MyClass();\n    myObj.Method1("foo", 1);\n}\n\npublic class MyClass\n{\n    public void Method1(object someArgument, object someOtherArgument,\n                 [CallerMemberName] string callerMemberName = null,\n                 [CallerFilePath] string callerFilePath = null,\n                 [CallerLineNumber] int callerLineNumber = 0)\n    {\n        Console.WriteLine(\n             string.Format("Called with {0}, {1} from method {2} in file {3} at line number {4}",\n                someArgument, someOtherArgument, \n                callerMemberName, callerFilePath, callerLineNumber));\n    }\n}	0
6013593	6013561	How to serialize a class generated from XSD to XML	Stream stream = File.Open(filename, FileMode.Create);\n  XmlFormatter formatter = new XmlFormatter (typeof(XmlObjectToSerialize));\n  formatter.Serialize(stream, xmlObjectToSerialize);\n  stream.Flush();	0
7796541	7796502	C# warning for unused variable in foreach	// TODO: Documentation\npublic static void ConsumeSequence<T>(this IEnumerable<T> source)\n{\n    // TODO: Argument validation\n    using (var iterator = source.GetEnumerator())\n    {\n        while (iterator.MoveNext())\n        {\n            // Deliberate no-op\n        }\n    }\n}	0
2298028	2297968	Using Log4Net during setup application	XmlConfigurator.Configure(Stream configStream)	0
24127470	24127335	Reading a specific column from a text file in C#	File.ReadLines("path").Sum(\n    line \n        => \n    int.Parse(Regex.Match(line, @"Hours:\s(\d+)").Groups[1].Value))	0
1773855	1773718	How to save default context settings in c#?	System.Collections.Specialized.StringCollection	0
25912895	25912701	Read the value of a string in the dll that is created dynamicly	Assembly a = Assembly.Load("test.dll");        \n    Type myType = a.GetType("LicensecodeDll.Check");        \n    MethodInfo myMethod = myType.GetMethod("returnValue");        \n    object obj = Activator.CreateInstance(myType);       \n    myMethod.Invoke(obj, null);	0
22378085	22377868	why the datasource shows as null of the Datagridview, when it's already has been assigned with data?	dgvAvailableCourses.DataSource = dtCourse	0
917960	917910	How to find a list of wireless networks (SSID's) in Java, C#, and/or C?	WlanClient client = new WlanClient();\nforeach ( WlanClient.WlanInterface wlanIface in client.Interfaces )\n{\n    // Lists all available networks\n    Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList( 0 );\n    foreach ( Wlan.WlanAvailableNetwork network in networks )\n    {                     \n        Console.WriteLine( "Found network with SSID {0}.", GetStringForSSID(network.dot11Ssid));\n    }\n}\n\nstatic string GetStringForSSID(Wlan.Dot11Ssid ssid)\n{\n    return Encoding.ASCII.GetString( ssid.SSID, 0, (int) ssid.SSIDLength );\n}	0
4702024	4701619	Silverlight 4 C# - How to catch a NullReferenceException?	if (dataGrid.CurrentColumn != null && dataGrid.CurrentColumn.DisplayIndex == 1)	0
24970992	19589420	.NET Chart Control: How to use a LineAnnotation?	LineAnnotation annotation = new LineAnnotation();\nannotation.IsSizeAlwaysRelative = false;\nannotation.AxisX = chart1.ChartAreas[0].AxisX;\nannotation.AxisY = chart1.ChartAreas[0].AxisY;\nannotation.AnchorX = 5;\nannotation.AnchorY = 100;\nannotation.Height = 2.5;\nannotation.Width = 3;\nannotation.LineWidth = 2;\nannotation.StartCap = LineAnchorCapStyle.None;\nannotation.EndCap = LineAnchorCapStyle.None;\nchart1.Annotations.Add(annotation);	0
2929817	2929775	Conditional validation	OnValidating(object sender, ServerValidateEventArgs e)\n{\n if(CertainTextBox.Text.IsNullOrEmpty() && CertainRecordDoesNotExistInDB))\n{\n // validate\n// and set e.Valid to the desired validation output\n}\nelse\n{\n e.IsValid = false;\n}\n}	0
19849134	19849084	How can I get a running total of my observable sequence?	var observable = this.GetHeartBeat()\n    .TimeInterval()\n    .Buffer(3, 1)\n    .Select((l, i) => string.Format("{0}, {1}", l.Average(x => 60 / x.Interval.TotalSeconds), i))\n    .Subscribe(i => System.Diagnostics.Debug.WriteLine(i));	0
33691558	33691508	Get field from class using string	var somethinf = myRecord.Where(prop => ((string)typeof(Class).GetProperty("Second").GetValue(prop)) == something);	0
28794562	28784920	apply font on certain portion of text in textbox	var t1 = ws.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, 20, 15, 200, 77);\nt1.TextFrame2.TextRange.Text = "Text1, text2";\nt1.TextFrame2.TextRange.Characters[8, 5].Font.Bold = MsoTriState.msoCTrue;\nt1.TextFrame2.TextRange.Characters[8, 5].Font.Name = "Segoe UI";	0
22832249	22832177	How to add item into the list with correct current datetime?	item[NewsFields.Date.InternalName] = \n    Microsoft.SharePoint.Utilities\n         .SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);	0
21039654	21039209	How can I speed up my MVC4 application DEVELOPMENT?	PocoEntity1 pocoEntity1 = new () \n{ \n  UserName = ViewModel.UserName,\n  UserPicture = ViewModel.UserPicture \n  (and so on) \n}	0
14419220	14419182	How to override closing control in Windows Form c#	protected override void OnFormClosing(FormClosingEventArgs e)\n{\n    if (e.CloseReason == CloseReason.WindowsShutDown) return;\n\n    // DO WHATEVER HERE\n}	0
19912550	19691509	VS2013 Failure to load Resource file for Windows 8 App	XDocument xDoc = XDocument.Load(@"Assets\Tiles\SM_Date.xml");\nXmlDocument wideTileXml = new XmlDocument();\nwideTileXml.LoadXml(xDoc.ToString());	0
33689561	33681473	How to compare type symbols (ITypeSymbol) from different projects in Roslyn?	ITypeSymbol.DeclaringSyntaxReferences	0
11113036	11112969	How to subtract 2 UTC dates in C#	TimeSpan interval = date2.Subtract(date1);\ndouble Hours = interval.TotalHours;	0
32074206	32073937	Store URL Parameter as String Variable ASP.NET	RouteData.Values["id"]	0
20240902	20240536	Insert closing "input" HTML element	static void AddClosingTag()\n{\n    string input = "This is some content <input type='readonly' value='value1'> and there is further content. This is some additional <input type='readonly' value='value2'> text and then there is further text.";\n\n    int index = 0;\n\n    while (true)\n    {\n        index = input.IndexOf("<input", index);\n        if (index == -1)\n        {\n            break;\n        }\n        index = input.IndexOf(">", index);\n        input = input.Insert(index + 1, "</input>");\n    }\n\n    Console.WriteLine(input);\n}	0
30676330	30665358	windows phone 8.1 universal app : clear cookies	Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); \nvar cookieManager = myFilter.CookieManager; \nHttpCookieCollection myCookieJar = cookieManager.GetCookies(new Uri("target URI for WebView")); \nforeach (HttpCookie cookie in myCookieJar) \n{ \n    cookieManager.DeleteCookie(cookie); \n}	0
21692421	21692356	Split a string of Number and characters	List<int> liNumeric = new List<int>();  \n foreach (string st in liRoom)  \n { \n   // int.Parse will fail if you don't have any digit in the input \n   if(st.Any(char.IsDigit))\n   {\n       liNumeric.Add(int.Parse(new string(st.Where(char.IsDigit).ToArray()))); \n   }\n\n }  \n if (liNumeric.Any()) //Max will fail if you don't have items in the liNumeric\n {\n     int MaxValue = liNumeric.Max();\n }	0
9962921	9927339	Aspx page to download any type of file from a specific directory on web server	Page.Response.ContentType = "application/octet-stream"\n        Page.Response.AddHeader("Content-Disposition", "attachment; filename=""" & strFilename & """")\n        Page.Response.OutputStream.Write(objAttachment.Data, 0, objAttachment.Data.Length)	0
6096324	6096196	byte[] to XML with .NET/C#	using (var stream = new MemoryStream(UserData, false))\n  {\n     var doc = Xdocument.Load(stream);\n\n     ...\n  }	0
31712034	31711692	Desirialized data to dictionary using a foreach loop C# MVC	public static DataTable DoSomething() \n    {\n        DataTable table = new DataTable();\n        table.Columns.Add("Student Name");\n        table.Columns.Add("Student Number");\n        table.Columns.Add("Registered");\n\n        getJsonData data = new JavaScriptSerializer().Deserialize<getJsonData>(System.IO.File.ReadAllText(@"C:\Users\mailb_000\Downloads\texts\test.json"));\n\n        foreach (var item in data.students)\n        {\n            table.Rows.Add(item.Name, item.StudentNo, item.registered);\n            Debug.Write(table);\n        }\n\n        return table;\n    }\n\n    public class getJsonData\n    {\n        public List<students> students { get; set; }\n    }\n\n\n    public class students\n    {\n\n        public string Name { get; set; }\n\n        public int StudentNo { get; set; }\n\n        public string registered { get; set; }\n    }	0
26283486	26282149	Apply Color to a Specific Word	pgf.Range.Words[4].Font.Color = WdColor.wdColorGreen;	0
7877346	7877292	C# Start EXE with Parameters and Save	ProcessStartInfo.Arguments	0
19324324	19324186	How to open WPF window from Console Application	Application app = new Application();\napp.Run(new Window1());	0
10216038	10213375	Loquacious Nhibernate not able to access non-public properties for mapping	compIDMapper.Property("_someProtectedInt", m => m.Column("SomeProtectedInt"));	0
21603914	21603818	How do I convert object to list<String>	List<string> dspString = new List<string>();\n...\nwhile(RDisplay.Read())\n{\n    try\n    {\n        dspString.Add(RDisplay.GetString(0));\n    }\n    catch(OdbcException ex)\n    {\n        MessageBox.Show(ex.Message);\n    }\n}	0
4637472	4498630	WPF Control inside ElementHost is invisible	TextEditor.Margin = 1000;	0
23738615	23738195	Using dynamic in C# without referencing a DLL	public interface IDynamicService {\n    void DoSomething();\n}\n\npublic void static main() {\n    var assembly = Assembly.LoadFrom("filepath"); \n    var aClass = assembly.GetType("NameSpace.AClass");\n    IDynamicService instance = Activator.CreateInstance(aClass) as IDynamicService;\n\n    if (instance != null) {\n        instance.DoSomething();\n    }\n}	0
11861103	11860907	Find the parent directory in c#	public static string ExtractFolderFromPath(string fileName, string pathSeparator, bool includeSeparatorAtEnd)\n        {\n            int pos = fileName.LastIndexOf(pathSeparator);\n            return fileName.Substring(0,(includeSeparatorAtEnd ? pos+1 : pos));\n        }	0
30766495	30765897	Thread sleeping in a BackgroundWorker	private void BgWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)\n    {\n        int min = 0;\n        int oldProgress = 0;\n        foreach (var hw in hwList)\n        {\n            // new ManualResetEvent(false).WaitOne(1);\n            // Thread.Sleep(1);\n            int progress = Convert.ToInt32((Double)min / hwList.Count * 100);\n            min++;\n\n            // Only report progress when it changes\n            if(progress != oldProgress){\n                 bgWorker.ReportProgress(progress);\n                 oldProgress = progress;\n            }\n        }\n    }\n\n    // Updating the progress\n    private void BgWorkerOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs)\n    {\n        ProgressBar.Value = progressChangedEventArgs.ProgressPercentage;\n    }	0
19170731	19170698	Reading odd XML file	XmlNodeList elemList = doc.GetElementsByTagName("RcsTweet");\n    for (int i = 0; i < elemList.Count; i++)\n    {\n        string name = elemList[i].Attributes["Name"].Value;\n        string handle = elemList[i].Attributes["Handle"].Value;\n        string tweet = elemList[i].Attributes["Tweet"].Value;\n    }	0
4341840	4341727	Use value from a user control into the main form (C#)	MyForm.Controls.OfType<MyCustomControlType>().Sum(c => c.TimeTakenProperty)	0
19919109	19918187	Print transient text in a textBlock: WP8 and dispatcher magic	private async void Button_Click(object sender, RoutedEventArgs e)\n{\n    string text = TextBlock1.Text;\n    TextBlock1.Text = "Bazinga!";\n    await Task.Delay(5000);\n    TextBlock1.Text = text;\n}	0
23082276	23081058	Trigger to sum in values in an SQL database column	CREATE TRIGGER [dbo].[trg_Transaction]\n   ON  [dbo].[Transaction]\n   AFTER INSERT,DELETE,UPDATE\nAS \nBEGIN\n    UPDATE dbo.Head SET Total_Sum=(SELECT SUM(Amount) FROM dbo.[Transaction] WHERE Head.Id=[Transaction].HeadId GROUP BY HeadId)\nEND\nGO	0
18802196	18801563	Custom Serialization/Deserialization of multiple objects into/from one xml file using XmlSerializer	public virtual void ReadXml(XmlReader reader)\n    {\n\n        Type type = this.GetType();\n        FieldInfo[] pInfo = type.GetFields();\n\n        // Added\n        reader.ReadStartElement();\n\n        foreach (FieldInfo property in pInfo)\n        {\n            object value = null;\n            reader.ReadToFollowing(property.Name);\n\n            Type propertyType = property.FieldType;\n            value = reader.ReadElementContentAs(property.FieldType, null);\n            type.GetField(property.Name).SetValue(this, value);                \n        }\n\n        // Added\n        reader.ReadEndElement();\n    }\n\n    // Serialize\n    Type type = typeof(List<Person>); //Changed Type to List of Persons\n    XmlSerializer serializer = new XmlSerializer(type);\n    TextWriter writer = new StreamWriter(filename);\n\n    serializer.Serialize(writer, list);\n\n    writer.Close();	0
3665040	3665012	how to convert seconds in min:sec format	int totalSeconds = 222;\nint seconds = totalSeconds % 60;\nint minutes = totalSeconds / 60;\nstring time = minutes + ":" + seconds;	0
25155417	25154379	Change color of navigation bar title	//AppDelegate.cs\npublic partial class AppDelegate : UIApplicationDelegate\n{\n    // class-level declarations\n    UIWindow window;\n    public static UIStoryboard Storyboard = UIStoryboard.FromName ("MainStoryboard", null);\n    public static UIViewController initialViewController;\n\n    // ...\n    public override bool FinishedLaunching (UIApplication app, NSDictionary options)\n    {\n        window = new UIWindow (UIScreen.MainScreen.Bounds);\n        initialViewController = Storyboard.InstantiateInitialViewController () as UIViewController;\n\n        UINavigationBar.Appearance.SetTitleTextAttributes (\n            new UITextAttributes () { TextColor = UIColor.FromRGB (0, 127, 14) });\n\n        window.RootViewController = initialViewController;\n        window.MakeKeyAndVisible ();\n        return true;\n    }\n}	0
24225396	24225269	Replace word in string but ignore accented characters	string[] splittedInput = input.Split(' ');\nStringBuilder output = new StringBuilder();\nforeach(string word in splittedInput) \n{\n  if(string.Compare(word, bannedWord, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) == false)\n  {\n    output.Append(word);\n  }\n} \n\nstring s_output = output.ToString();	0
9507772	9503323	Replace Hyperlinks with Plain-Text followed by URL in Brackets using C#	using System;\nusing System.Text.RegularExpressions;\n\nstring inputText = "your text here";\nstring rx = "<a\\s+ .*? href\\s*=\\s*(?:\"|') (?<url>.*?) (?:\"|') .*?> (?<anchorText>.*?) \\</a>";\nRegex regex = new Regex( rx, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace );\nstring regexReplace = "${anchorText} [${url}]";\n\nstring result = regex.Replace( inputText, regexReplace );	0
16648756	16542708	Set DateTimeCreate with EWS Proxy classes	ItemType newItem = xmlParser.LoadItem(); //info for newItem takes from xml\n        newItem.ExtendedProperty = new ExtendedPropertyType[1];\n        PathToExtendedFieldType q = new PathToExtendedFieldType();\n        q.PropertyTag = "3590"; //DeliveryTime\n        q.PropertyType = MapiPropertyTypeType.SystemTime;\n        newItem.ExtendedProperty[0] = new ExtendedPropertyType();\n        newItem.ExtendedProperty[0].ExtendedFieldURI = q;\n        newItem.ExtendedProperty[0].Item = new System.DateTime(2014, 5, 5, 5, 5, 5).ToString("yyyy-MM-ddTHH:mm:ssZ");	0
14610578	13842518	Missing schema errors when using an Xsd to validate Xml from a serialized WCF Proxy class	var dataType = data.GetType();\nvar xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(dataType, typeof(XmlTypeAttribute));\nXNamespace ns = xmlAttribute.Namespace;\nusing (var fileWriter = new StreamWriter(filePath))\n{\n   var xSerializer = new XmlSerializer(dataType, ns.NamespaceName);\n   xSerializer.Serialize(fileWriter, data);\n   fileWriter.Close();    \n}	0
3322503	3322455	How to change colors of a GDI+ LinearGradientBrush?	myBrush.LinearColors = new Color[2] { Color.Blue, Color.Whatever };	0
6294188	6293953	Extract from DataRow or DataReader with one function	public List<MyType> GetMyTypeCollection(DbDataReader reader)\n{\n//mapping code here\n}	0
21980957	21980554	Color specific words in RichtextBox	private void Rchtxt_TextChanged(object sender, EventArgs e)\n        {\n            this.CheckKeyword("while", Color.Purple, 0);\n            this.CheckKeyword("if", Color.Green, 0);\n        }\n\n\n\nprivate void CheckKeyword(string word, Color color, int startIndex)\n    {\n        if (this.Rchtxt.Text.Contains(word))\n        {\n            int index = -1;\n            int selectStart = this.Rchtxt.SelectionStart;\n\n            while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1)\n            {\n                this.Rchtxt.Select((index + startIndex), word.Length);\n                this.Rchtxt.SelectionColor = color;\n                this.Rchtxt.Select(selectStart, 0);\n                this.Rchtxt.SelectionColor = Color.Black;\n            }\n        }\n    }	0
12563064	12563015	Convert custom array object to string array	_showResults.Select(a => a.ToString()).ToArray()	0
11367632	11365809	Sharepoint Alert Access denied	string employeeIdToRemove = "1337";\nGuid siteGuid = SPContext.Current.Site.ID;\n\nSPSecurity.RunWithElevatedPermissions(delegate\n{\n   using (SPSite mySite = new SPSite(siteGuid))\n   {\n      SPListItemCollection listItems = mySite.Lists["SuperSecretList"].Items;\n      int itemCount = listItems.Count;\n\n      for (int k=0; k<itemCount; k++)\n      {\n         SPListItem item = listItems[k];\n\n         if (employeeIdToRemove.Equals(item["Employee"].ToString()))\n         {\n             listItems.Delete(k);\n         }\n      }\n   }\n});	0
11418216	11418006	Clipboard can copy a few words?	textBox1.Text = "MY name is not exciting";\n        //pretend you only want "not exciting" to show\n        int index = textBox1.Text.IndexOf("not");//get the index of where "not" shows up so you can cut away starting on that word.\n\n        string partofText = textBox1.Text.Substring(index);//substring uses the index (in   this case, index of "not") to take a piece of the text. \n\n        Clipboard.SetText(partofText);\n        textBox2.Text = Clipboard.GetText();	0
22465790	22465665	Regex that always returns false	string disallowedPattern = "^[A-Z]:\\\\$";	0
9949389	9949330	How to randomly place 2D asteroids so they don't overlap with each other?	2D Collision Detection	0
15592161	15587720	Send sensitive data from my website to my C# application	e.g mywebsite.com/login.php?username=admin?password=MD5HashedPassword	0
3920217	3920111	Entity Framework 4 - AddObject vs Attach	var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };\nvar myAddress = ctx.Addresses.First(a => a.PersonID != existingPerson.PersonID);\nexistingPerson.Addresses.Attach(myAddress);\n// OR:\nmyAddress.PersonReference.Attach(existingPerson)\nctx.SaveChanges();	0
29697509	29696828	How do I get 10 ordered entries inside a view?	var yourList=Model.MovieList.OrderBy(x=>x.Rating).Take(10);	0
3709300	3709104	How do you read a file which is in use?	using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n{\n    using (StreamReader reader = new StreamReader(stream))\n    {\n        while (!reader.EndOfStream)\n        {\n\n        }\n    }\n}	0
502904	502877	Analyze the use of a ASP.NET webservice	public class MyWebServiceDiagnosticsModule : IHttpModule\n{\n    public MyWebServiceDiagnosticsModule ()\n    {\n    }\n    void IHttpModule.Init(HttpApplication context)\n    {\n    context.BeginRequest += new EventHandler(BeginRequest);\n    }\n    private void BeginRequest(object sender, EventArgs e)\n    {\n    HttpContext ctx = HttpContext.Current;\n    string url = ctx.Request.Url.ToString().ToLower();\n    if (url.Contains("mywebservice.asmx"))\n    {\n        LogMethodCall(url); // parse URL and write to DB\n    }\n    }\n}	0
6807787	6807727	In protobuf-net can i have a byte field?	byte[] Payload= datafromsomewhere;\n            var ms = new MemoryStream(Payload);\n            var req = Serializer.Deserialize<AbcClass>(ms);	0
16867054	16867040	How to get image from url using c# / javascript	PictureBox.Load(string);	0
3904626	3904604	How to Start Windows Service in Administrator Mode	netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user	0
9008455	9007823	Read elements from XML and use them in a method	public bool result()\n{    \n    Dictionary<string, string> files = new Dictionary<string, string>();\n    files.Add("esecpath", "C:\\testconfig.xml");\n    // ... etc for each file\n\n    // if you want to see if any don't exist, then use ...\n    // if(files.Any(f => !File.Exists(f.Value)))\n\n    // else, these are all the created files\n    var createdFiles = files.Where(f => !File.Exists(f.Value));\n    if(createdFiles.Count() > 0)\n    {\n        // A file doesn't exist!  Therefore you are creating it!\n    }\n    var directories = files.Select(f => Checking.CitXml(f.Value, f.Key));\n\n    return directories.All(d => Directory.Exists(d));\n}	0
575068	574979	Library or Code Snippet for AutoComplete in Text Control based on the previous user entered values	private void button1_Click(object sender, EventArgs e)\n{\n    this.textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;\n    this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;\n\n    string[] items = GetListForCustomSource();\n    this.textBox1.AutoCompleteCustomSource.AddRange(items);\n\n}\n\nprivate string[] GetListForCustomSource()\n{\n    var result = new List<string>();\n\n    foreach(var value in Enum.GetNames(typeof(DayOfWeek)))\n    {\n        result.Add(value);\n    }\n\n    return result.ToArray();\n}	0
2513126	2513069	How to read a textfile using C#.Net	public IEnumerable<string> ReadLines(string fileName)\n{\n    string line;\n    using (var rdr = new StreamReader(fileName))\n        while ( (line = rdr.ReadLine()) != null)\n            yield return line;\n}\n\nReadLines("yourfile.txt")\n    .Where(l => l.StartsWith("6"))\n    .Select(l => new {Part1 = l.SubString(6, 9), Part2 = l.SubString(45, 17)});	0
25313951	25313884	Is it safe to run multiple DoWork functions on a single BackgroundWorker?	backgroundWorker.DoWork += (s, args) => \n{\n    firstFunctionToDoSomeWork(s,args);\n    secondFunctionToDoSomeWork(s,args);\n};	0
30005189	30005160	is there a ready method which gives you the repetition of word in a string in c#?	string str = "abcabcabcabcabc"; // 5 times\nint cnt = Regex.Matches(str ,"abc").Count; // 5	0
21603872	21603724	Console App how to run a function by entering action into cmd	static void Main(string[] args)\n{\n    Console.WriteLine("Welcome to c#");\n\n    string input = Console.ReadLine();\n\n    if(input.ToUpper() == "DOWNLOADPOS")\n       DownloadPOS();\n}	0
8790553	8790367	C# Console Application - Edit User Setting at runtime	Settings.Default.MyProperty1 = "some value";\nSettings.Default.MyProperty2 = 2;\nSettings.Default.Save();	0
9573469	9573194	How can I start and wait for an external process?	private Timer myTimer;\n\nprivate void DoSomething()\n{\n    if (myTimer != null)\n    {\n        myTimer.Dispose();\n        myTimer = null;\n    }\n\n    Method1();\n\n    myTimer = new Timer(CheckForProcess, null, 100, 100);\n}\n\nprivate void CheckForProcess(object state)\n{\n    bool isOpened = false;\n    foreach (Process clsProcess in Process.GetProcesses())\n    {\n        if (clsProcess.ProcessName.Contains("AdobeARM"))\n        {\n            isOpened = true;\n            break;\n        }\n    }\n\n    //Once the pop up from Method 1 comes i call other methods     \n    if (isOpened)\n    {\n        myTimer.Dispose();\n        myTimer = null;\n        Method2();\n        Method3();\n        Method4();\n    }\n}	0
18769573	18753719	How to await for QueryCompleted event?	public static Task<IList<MapLocation>> QuerryTaskAsync(this ReverseGeocodeQuery reverseGeocode)\n    {\n        TaskCompletionSource<IList<MapLocation> > tcs=new TaskCompletionSource<IList<MapLocation>>();\n        EventHandler<QueryCompletedEventArgs<IList<MapLocation>>> queryCompleted = null;\n        queryCompleted=(send, arg) =>\n        {\n            //Unregister event so that QuerryTaskAsync can be called several time on same object\n            reverseGeocode.QueryCompleted -= queryCompleted;\n\n            if (arg.Error != null)\n            {\n                tcs.SetException(arg.Error);\n            }else if (arg.Cancelled)\n            {\n                tcs.SetCanceled();\n            }\n            else\n            {\n                tcs.SetResult(arg.Result);\n            }\n        };\n\n        reverseGeocode.QueryCompleted += queryCompleted;\n\n        reverseGeocode.QueryAsync();\n\n        return tcs.Task;\n    }	0
2790024	2789998	Helping to make some easy regular exspression	/[0-9]+\.[0-9]{2}/	0
5099066	5098514	JSON serialization performance issue on WP7	[OnDeserializing]\npublic void OnDeserializing(StreamingContext context)\n{\n    IsNotifying = false;\n}\n\n[OnDeserialized]\npublic void OnDeserialized(StreamingContext context)\n{\n    IsNotifying = true;\n}	0
21722385	21722305	How to sort same list using lambda expression?	ObjectList = ObjectList.OrderBy(x=>x.Name). ToList() ;	0
20787694	20787312	sort a one-dimensional list of items into child/parent structure	var data = " 0100000000     Coffee\r\n 0110000000     Mocha\r\n 0120000000     Cappuccino\r\n 01210" +\n    "00000     Semi skimmed\r\n 0121100000     Starbuckz\r\n 0121200000     Costa\r\n 01220" +\n    "00000     Skimmed\r\n 0130000000     Latte";\nvar linesByPrefix = \n    (from l in data.Split(new[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)\n    let pair = l.Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries)\n    select new LineData\n    {\n        OriginalCode = pair[0],\n        Title = pair[1],\n        Children = new List<LineData>()\n    })\n    .ToDictionary(l => l.OriginalCode.TrimEnd('0'));\n\nforeach (var line in linesByPrefix)\n{\n    var parentCode = line.Key.Substring(0, line.Key.Length - 1);\n    LineData parent;\n    if(linesByPrefix.TryGetValue(parentCode, out parent))\n    {\n        line.Value.Parent = parent;\n        parent.Children.Add(line.Value);\n    }\n}\nvar roots = linesByPrefix.Values.Where(l => l.Parent == null);	0
12198393	12198063	Catch only a specific HttpException	if ((lastErrWrapper != null) && (lastErrWrapper.InnerException != null) \n  && (lastErrWrapper.InnerException is ViewStateException)\n{\n}	0
15474487	15474423	Replace the string array value	arr_val[3] = "200";	0
21257158	21257111	Retrieve by lambda query and bind to DataTable in C#	foreach(var emp in _empData)\n{\n    var newRow = _dtSC.Rows.Add();\n    newRow.SetField("ID", emp.ID);\n    // and so on ...\n    // you are free to not initialize a field like Deduction\n}	0
9094388	9094341	how to assign the string value to listbox selectd value	ListBox.Text= "string Value" ;	0
8560921	8560445	How to drag a picturebox control	public void MusicNote_MouseUp(object sender, MouseEventArgs e)\n    {\n        isDragging = false;\n        this.MouseMove -= new MouseEventHandler(OnDrag);\n    }	0
3156202	3156028	Tweetsharp - Getting lists for authenticated user	var service = new TwitterService();\n    service.AuthenticateWith(<your consumerKey>, <your consumerSecret>, <your token>, <your tokensecret>);\n\n    var listsUsersLists = service.ListListsFor(listOwnerScreenName);\n    var listsUserIsIn = service.ListListMembershipsFor(listOwnerScreenName);\n    var subscribedToLists = service.ListListSubscriptionsFor(subscriberName);	0
30932314	30931788	Adding from a Listbox to database	protected void btnFinalizeSO_Click(object sender, EventArgs e)\n{\n    using(MyDataBaseEntities db = new MyDataBaseEntities())\n   {\n       Number lastNumber = (from c in db.Number orderby IDNumber select c).LastOrDefaul();\n       foreach(var item in ListBoxSO.Items)\n       {\n\n            Number n = new Number();\n            n.IdNumber = lastNumber.IdNumber +1; \n            n.Id = lastNumber.Id + 1;\n            n.Name = ListBoxSO.GetItemText(item);\n            db.Number.Add(n);\n       }\n      db.SaveChanges();\n   }\n}	0
32054499	32049742	EF 7 set initial default value for DateTime column	entity.Property(e => e.ShipDate).HasDefaultValueSql("getutcdate()");	0
3385221	3384967	How to compare Image objects with C# .NET?	// 1. Capture the actual pixels from a given window\nSnapshot actual = Snapshot.FromRectangle(new Rectangle(0, 0, 100, 100));\n\n// 2. Load the reference/master data from a previously saved file\nSnapshot expected = Snapshot.FromFile("Expected.png"));\n\n// 3. Compare the actual image with the master image\n//    This operation creates a difference image. Any regions which are identical in \n//    the actual and master images appear as black. Areas with significant \n//    differences are shown in other colors.\nSnapshot difference = actual.CompareTo(expected);\n\n// 4. Configure the snapshot verifier - It expects a black image with zero tolerances\nSnapshotVerifier v = new SnapshotColorVerifier(Color.Black, new ColorDifference());\n\n// 5. Evaluate the difference image\nif (v.Verify(difference) == VerificationResult.Fail)\n{\n    // Log failure, and save the diff file for investigation\n    actual.ToFile("Actual.png", ImageFormat.Png);\n    difference.ToFile("Difference.png", ImageFormat.Png);\n}	0
18905354	18904194	Will a user control be correctly disposed if it contains a control within an other object?	tabItem.Content	0
15372353	15372325	How to get the most recent date from a table	var post = UnitOfWork.TableName.Query(postFilter)\n    .OrderByDescending(x => x.CreatedDate)\n    .FirstOrDefault();	0
32668939	32668869	Cross-thread operation not valid: Control 'webForm' accessed from a thread other than the thread it was created on	fc.Invoke(new MethodInvoker(delegate { fc.Close(); }));	0
13739170	13721680	How to access User Control graph dynamically?	Application.OpenForms["Name of the Form"]	0
661878	567303	WCF certificates not being set on custom credentials	this.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();\nthis.ChannelFactory.Endpoint.Behaviors.Add(new CentralAuthClientCredentials());	0
28621471	28621311	Foreach item i in collection of lists	public void ProcessList(List<myListType> theList)\n{\n    //Do some cool stuff here...\n}	0
30035124	30035073	How using entity framework fluent API to config such relationship?	modelBuilder.Entity<Car>()\n            .HasOptional(m => m.Dealer)\n            .WithMany(m => m.Cars);	0
23277372	23235044	cannot load data into datagridview C# for a multitable sql query	dataGridView1.Columns[0].Name = "FEE_HEAD_NAME";\n       ataGridView1.Columns[0].HeaderText = "FEE_HEAD_NAME";\n       dataGridView1.Columns[0].DataPropertyName = "FEE_HEAD_NAME";\n\n       dataGridView1.Columns[1].HeaderText = "FEE_HEAD_AMOUNT";\n       dataGridView1.Columns[1].Name = "FEE_HEAD_AMOUNT";\n       dataGridView1.Columns[1].DataPropertyName = "FEE_HEAD_AMOUNT";	0
10084766	10084709	How to get Value from DropDownList inside a ListView?	if(e.Item.ItemIndex!=-1)\n{\n     string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue; \n}\n\nif not working then try     \nstring shipmethod = (e.Item.FindControl("ShippingComapnyDDL") as DropDownList).SelectedValue;	0
2570216	2492910	How to move a mail to SPAM ? Using Google Mail Migration API?	MailItemEntry entry = new MailItemEntry();\nentry.Rfc822Msg = new Rfc822MsgElement(rfcTextOfMessage);\nentry.Labels.Add(new LabelElement("Spam"));	0
34520088	34520014	Get Values With One Select and Bind To View Model	AdVM model = a.ADGetAllUser(s).Where(x => x.UserName == id).Select(x=> new AdVM() {Username = x.UserName, DisplayName = x.DisplayName... other fileds}).SingleOrDefult();	0
2413853	2413459	Reflecting constructors with default values in C#4.0	var ctrs = from c in provider.GetConstructors()\n           where c.GetParameters().Where(p => !p.IsOptional).Count() == 0\n           select c;\nConstructorInfo ctr = ctrs.FirstOrDefault();	0
778055	778025	Can I add one XmlDocument within a node of another XmlDocument in C#?	XmlDocument document1, document2;\n// Load the documents...\nXmlElement xmlInner = (XmlElement)document1.SelectSingleNode("/document1/inner");\nxmlInner.AppendChild(document1.ImportNode(document2.DocumentElement, true));	0
13388405	13388197	AJAX Incorrect Parameter	public void myCFunction(int id)\n{\n  //do some stuff\n}	0
162013	160022	Determine if a resource exists in ResourceManager	// At startup.\n    ResourceManager mgr = Resources.ResourceManager;\n    List<string> keys = new List<string>();\n\n    ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true);\n    foreach (DictionaryEntry o in set)\n    {\n        keys.Add((string)o.Key);\n    }\n    mgr.ReleaseAllResources();\n\n    Console.WriteLine(Resources.A);	0
5199711	5196438	Accessing a repository in AccountController through constructor	kernel.Bind<IThingRepository>().To<SqlThingRepository>();	0
30950484	30950454	How to avoid selecting textbox value when press Enter?	Control nextControl;\n\nif (e.KeyCode == Keys.Enter)\n{     \n    nextControl = GetNextControl(ActiveControl, !e.Shift);\n    if (nextControl == null)\n    {\n        nextControl = GetNextControl(null, true);\n    }\n    nextControl.Focus();\n\n    TextBox box = nextControl as TextBox;\n    if (box != null)\n        box.Select(box.Text.Length, 0);\n\n    e.SuppressKeyPress = true;\n}	0
3185896	3185450	How to create an in-memory icon for my unit test	Icon icon = System.Drawing.SystemIcons.WinLogo;	0
24002110	24001648	populating drop down list to get Value field different from Text field	lblCode.Text = ddlZONE.SelectedItem.Value;	0
7663666	7663615	Using the Take Method on my model Substitute Variable	public ActionResult Index(int? toTake)\n{\n    foreach(var sheet in Model.Sheets.Take(toTake != null ? toTake.Value : 100))\n    {\n    }\n\n    return View();\n}	0
308524	308476	Fastest way to find out whether two ICollection<T> collections contain the same objects	[Tested]\n\npublic virtual bool ContainsAll<U>(SCG.IEnumerable<U> items) where U : T\n{\n  HashBag<T> res = new HashBag<T>(itemequalityComparer);\n\n  foreach (T item in items)\n    if (res.ContainsCount(item) < ContainsCount(item))\n      res.Add(item);\n    else\n      return false;\n\n  return true;\n}	0
34211294	34210947	How to get List of all Providers in Event Viewer using C#?	EventLogSession session = new EventLogSession();\n\nvar providers = session.GetProviderNames().ToList();	0
16853793	16730351	How to decode image from stream, into existing image	var stream = new MemoryStream(data);\nvar formsBitmap = new Bitmap(stream);\n\nvar width = formsBitmap.Width;\nvar height = formsBitmap.Height;\nif (bitmap == null || height != bitmap.PixelHeight || width != bitmap.PixelWidth)\n{\n    bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null);\n    imgPreview.Source = bitmap;\n}\n\nBitmapData data = formsBitmap.LockBits(new Rectangle(0, 0, formsBitmap.Width, formsBitmap.Height),\n                                        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);\n\ntry\n{\n    bitmap.WritePixels(new Int32Rect(0, 0, width, height), data.Scan0, data.Stride * data.Height, data.Stride);\n}\nfinally\n{\n    formsBitmap.UnlockBits(data);\n}\n\nformsBitmap.Dispose();	0
5177889	5177804	Encrypt string to fixed length	string secretKey = "MySecretKey";\n        string salt = "123";\n        System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();\n        byte[] preHash = System.Text.Encoding.UTF32.GetBytes(secretKey + salt);\n        byte[] hash = sha.ComputeHash(preHash);\n        string password = prefix + System.Convert.ToBase64String(hash);	0
25960010	19619110	C# wpf webbrowser control - download file	System.Net.WebClient _wclient = new System.Net.WebClient();\n_wclient.DownloadFile("https://www.***.com/phoenix/views/akgCharts/zoomAkgChart.jsp?&date=20130502&time=123000",", @"c:\MedicalReport_" + DateTime.Now + ".pdf");	0
12259247	12136754	how to subtract two datatables with linq	var query =    \n    from row1 in dt1    \n    where !(from row2 in dt2    \n            select row2.ID)    \n           .Contains(row1.ID)    \n    select row1;	0
15746719	15745603	How do I modify the setter value of a dependency property?	public string MyName\n{\n    get { return (string)GetValue(MyNameCustomProperty); }\n    set { SetValue(MyNameCustomProperty, value); }\n}\npublic static DependencyProperty MyNameCustomProperty = DependencyProperty.Register("MyName", typeof(string), typeof(MyTabControl), new PropertyMetadata("", MyPropertyChanged, CoerceCurrentReading));\n\nprivate static void MyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    //contains coerced value\n}\n\nprivate static object CoerceCurrentReading(DependencyObject d, object value)\n{\n    MyTabControl tab = (MyTabControl)d;\n    return (string)value + " World";\n}	0
11124067	11123825	Getting SPList by a value from SPListTemplateType Enumeration	SPList tasksList = web.Lists.Cast<SPList>().FirstOrDefault(\n    list => list.BaseTemplate == SPListTemplateType.Tasks);	0
9477803	9477647	Searching for a tabpage in the tabcontrol C#	bool found = false;\n        foreach (TabPage tab in tabControl1.TabPages) {\n            if (filename.Equals(tab.Name)) {\n                tabControl1.SelectedTab = tab;\n                found = true;\n            }\n        }\n        if( ! found)\n                tabControl1.TabPages.Add(filename,filename);	0
17769574	17769442	Get unique strings based on a substring in C#	string[] file = {   "cat dog lion tiger",\n                    "cat dog deer bear",\n                    "mouse rat bear deer",\n                    "lion tiger cat dog",\n                    "cat dog deer bear"};\n\n    Dictionary<string, string> dict = new Dictionary<string, string>();\n\n    List<string> lst = new List<string>();\n\n    foreach (string s in file)\n    {\n        string[] words = s.Split(' ');\n        // assumption - thare are at least 2 words in a line - validate it\n        if (!dict.ContainsKey(words[1]))\n        {\n            lst.Add(s);\n            dict.Add(words[1], words[1]);\n        }\n    }\n\n    foreach (string s1 in lst)\n        Console.WriteLine(s1);	0
5253154	1319616	How to change Outlook Calendar Color in C#?	myNamespace = outLookApp.GetNamespace("MAPI");\nif (myNamespace.Categories["liveMeeting"] == null)\n{\n  myNamespace.Categories.Add("liveMeeting", OlCategoryColor.olCategoryColorDarkRed, OlCategoryShortcutKey.olCategoryShortcutKeyNone);\n}\nnewEvent.Categories = "liveMeeting";	0
10936263	10936176	Searching for text in a database with Entity Framework	var users = from u in context.TPM_USER select u;\nif (!string.IsNullOrWhiteSpace(FirstName))\n    users = users.Where(u => u.FIRSTNAME.ToLower().Contains(FirstName.ToLower()));\nif (!string.IsNullOrWhiteSpace(LastName))\n    users = users.Where(u => u.LASTNAME.ToLower().Contains(LastName.ToLower()));	0
16189479	16174590	Store same key in Machine.config and App.config	protected override void BaseAdd(ConfigurationElement element)\n    {\n\n\n CustomConfigurationElement newElement = element as CustomConfigurationElement;\n\n      if (base.BaseGetAllKeys().Where(a => (string)a == newElement.Key).Count() > 0)\n      {\n        CustomConfigurationElement currElement = this.BaseGet(newElement.Key) as CustomConfigurationElement;\n\n        if (!string.IsNullOrEmpty(newElement.Local))\n          currElement.Local = newElement.Local;\n\n        if (!string.IsNullOrEmpty(newElement.Dev))\n          currElement.Dev = newElement.Dev;\n\n        if (!string.IsNullOrEmpty(newElement.Prod))\n          currElement.Prod = newElement.Prod;\n      }\n      else\n      {\n        base.BaseAdd(element);\n      }\n    }	0
13477619	13477498	Array sorting by two parameters	sourcearray.OrderBy(a=> a.sum).ThenBy(a => a.random)	0
30020006	30019958	Entity Data Model get data from different databases	YourContext db=YourContext("connectionname")	0
6345958	6344103	Ninject: Resolve dependency by name only	kernel.Bind<object>().To<MyClass>().Named("A")\nkernel.Get<object>("A");	0
32945793	32943959	List all controls of all web pages of an application in a page	using (StreamReader sr = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + pageName + ".designer.cs"))\n            {\n                String line = "";\n\n                while ((line = sr.ReadLine()) != null)\n                {\n                    if (line.Contains(';'))\n                    {\n                        String[] tab = line.Split(' ');\n                        String nomSplit = tab[tab.Length - 1].Split(';')[0];\n\n                        this.listeControls.Items.Add(new ListItem(nomSplit, nomSplit));\n                    }\n                }\n            }	0
24898688	24898402	Need help in splitting the address	string message = "ABCD E FGHI JKLMNOP QRSTU VWXYz Apt NUMBER1234 Block A";\n        string firstline = message;\n        string secondline="";\n        if(message.Length > 30)\n        {\n            for(int i = 30; i > 0;)\n            {\n                if(message[i] == ' ')\n                {\n                    firstline = message.Substring(0, i);\n                    secondline = message.Substring(i + 1);\n                    break;\n                }\n                else\n                {\n                    i--;\n                }\n            }\n        }	0
3887834	3887818	Converting from an int to a bool in C#	Insertvotes(objectType, objectId , (vote == 1), userID); //calling	0
22935219	22934709	substring a multibyte character safely c#	var yourstring = "test";\n    StringInfo si = new StringInfo(yourstring);\n    var substring = si.SubstringByTextElements(1);	0
25535773	25532748	App crashes when on Suspend	Frame.Navigate(typeof(SecondPage), FirstPageViewModel);	0
6078535	6078384	C# Display a cycle through of all files / folders on the computer	public class FileSystemList : IEnumerable<string>\n{\n    DirectoryInfo rootDirectory;\n\n    public FileSystemList(string root) \n    {\n         rootDirectory = new DirectoryInfo(root);\n    }\n\n    public IEnumerator<string> GetEnumerator() \n    {\n        return ProcessDirectory(rootDirectory).GetEnumerator();\n    }\n\n    public IEnumerable<string> ProcessDirectory(DirectoryInfo dir) \n    {\n        yield return dir.FullName;\n        foreach (FileInfo file in dir.EnumerateFiles())\n            yield return file.FullName;\n        foreach (DirectoryInfo subdir in dir.EnumerateDirectories())\n            foreach (string result in ProcessDirectory(subdir))\n                yield return result;\n    }\n\n    IEnumerator IEnumerable.GetEnumerator() \n    {\n        return GetEnumerator();\n    }\n}	0
25409312	25409001	ASP disable button during postback	private void Page_Load()\n{\n   if (!IsPostBack)\n   {\n    //doNothing\n    }\nelse\n    {\n    //button.disabled = true\n    }\n}	0
20755577	20755549	Set a default value for my dropdownlist which is filled from database	protected void Page_Load(object sender, EventArgs e)\n{       \n   if (!IsPostBack)\n   {\n       writerddl.DataSource = DS.show_all_writers();\n       writerddl.DataValueField = "writerid";\n       writerddl.DataTextField = "writersname";            \n       writerddl.DataBind();\n       writerddl.Items.insert(0, new ListItem("Please select",""));\n   }\n}	0
11004947	11004912	Parsing a date time from an xml document with timezone abbreviations (e.g. CET )	DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);	0
1577983	1577949	In a knot with Generics	public class DomainObject<T, TRepo> \n     where T: DomainObject<T, TRepo> \n     where TRepo: IRepository<T, TRepo>\n{\n     public static TRepo Repository\n     {\n         get;\n         private set; \n     }\n}\n\npublic interface IRepository<T, TRepo>\n     where T: DomainObject<T, TRepo>\n     where TRepo: IRepository<T, TRepo>\n{\n     void Save(T domainObject);\n}	0
33115259	33093484	My C# Regex pattern fails to match text between tags	int startIndex = line.IndexOf(">") + 1;\nline = line.Substring(startIndex, line.IndexOf("<", startIndex));	0
19549368	19549252	DataTable and Table-Valued Parameter returning no rows	cmd.CommandType = CommandType.StoredProcedure;	0
6506610	6506389	How reload main window?	static class Program\n{\n  [STAThread]\n  static void Main()\n  {\n      Main main;\n      do\n      {\n         main = new Main();\n      } while (DialogResult.OK == main.ShowDialog ());\n  }\n} \n\nprivate void ChangeUsers()\n{\n    this.DialogResult = DialogResult.OK;\n    this.Close();\n}	0
14662751	14632249	ASP.NET MVC 4 how to implement Oauth with custom membershipprovider and roleprovider	public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName)\n\npublic override int GetUserIdFromOAuth(string provider, string providerUserId)\n//return -1 if User got no OauthAccount\n\npublic override string GetUserNameFromId(int userId)	0
17866721	17866575	Getting a SQL Column's data based on another Column's data in C#	DataTable dt = AnimalGrants.Tables["AnimalGrants"];\nstring columnName = "Title";\nList<string> ListOfAnimalGrantTitles = new List<string>();\nint i = 0;\nforeach (DataRow dr in dt.Rows.Cast<DataRow>().OrderBy(t => t[1]))\n{\n    ListOfAnimalGrantTitles.Add(dr[0]);\n}	0
26852979	26852929	How do you pass a function to itself a variable number of times to form an "n level method call"?	r = 6;\nfor (int k = 0; k < N; k++)\n    r = randomNumber.Next(1, r);	0
3363639	3362497	send appointment invitation to lotus notes 8.5 clients via c#	oNotesDocument.ReplaceItemValue("EnterSendTo", "xx@xx.com");	0
18857422	18857366	How to pass parameters to C# Console Application via task scheduler on win 2k3 server?	"c:\myProgram.exe false myVal"	0
22590253	22435507	Autofac with quartz	public class HJob : IJob\n{\n    public void Execute(IJobExecutionContext context)\n    {\n        using (var container = CustomDependencyResolver.Container.BeginLifetimeScope(\n            builder => builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().As<IRepositoryFactory>().InstancePerLifetimeScope()\n            ))\n        {\n\n        }\n    }\n}	0
29044466	29044449	Is there a good way to debug inside of a LINQ statment in C# in VS 2012 or beyond, to check the iteration of a lamda function in a where?	.Select(i => {\n    return i; //Add a breakpoint on this line.\n});	0
14813600	14808346	Save Strokes of inkManager in localStorage - windows 8 app	StorageFile myMerge = await ApplicationData.Current.LocalFolder.CreateFileAsync("myimg.png");\n\n                IOutputStream ac = await myMerge.OpenAsync(FileAccessMode.ReadWrite);\n\n                if (ac != null)\n                    await _inkManager.SaveAsync(ac);	0
31191165	31189912	Getting the value of the 'href' inside of a div in HTMLAgilityPack in C#	var list = page.DocumentNode.SelectNodes("//div[@class='s_newsbox']/a[string-length(@href)>0]");\n       foreach (var obj in list)\n        {\n          var url = obj.SelectSingleNode(".").Attributes["href"].Value;	0
22785386	22745377	uploading image to azure blob storage	stream.Seek(0, SeekOrigin.Begin);	0
24058464	24058008	Reading Style XAML from Codebehind	FileStream fs = new FileStream("Dictionary1.xaml", FileMode.Open);\n        ResourceDictionary dictionary = (ResourceDictionary)XamlReader.Load(fs);	0
8281722	8281703	Generate XML from a class	public class StackOverflow_8281703\n{\n    [XmlType(Namespace = "")]\n    public class Foo\n    {\n        [XmlText]\n        public string Value { set; get; }\n        [XmlAttribute]\n        public string id { set; get; }\n    }\n    public static void Test()\n    {\n        MemoryStream ms = new MemoryStream();\n        XmlSerializer xs = new XmlSerializer(typeof(Foo));\n        Foo foo = new Foo { id = "bar", Value = "some value" };\n        xs.Serialize(ms, foo);\n        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));\n    }\n}	0
4829794	4829758	Handling RequiredFieldValidator inside of a User Control	[ValidationProperty("Text")]\n public partial class Control\n {\n    public string Text \n    {\n        get { return textbox.Text;}\n    }\n\n }	0
2289587	2245560	Change Windows Mobile 5 Theme via C#	using System.Runtime.InteropServices;\nusing Microsoft.Win32;\n...\n[DllImport("coredll.dll")]\nprivate static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);\n...\npublic const int HWND_BROADCAST = 0xffff;\npublic const int WM_WININICHANGE = 0x001A;\n\n// Copy wallpaper file to windows directory\nFile.Copy(@"\My Documents\My Pictures\ImageFileName.jpg", @"\Windows\stwater_240_240.jpg", true);                \n\n// Update registry\nRegistry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Today", "Wall", "ImageFileName");\n\n// Send message to refresh today screen\nSendMessage((IntPtr)HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0);	0
7914796	7914369	Validating XML on XSD with the error line numbers	private void SchemaValidationEventHandler(object sender, ValidationEventArgs e) {\n    Console.WriteLine("XML {0}: {1} (Line {2})",\n                         e.Severity,\n                         e.Message,\n                         e.Exception.LineNumber);\n}	0
24773063	24772784	Where can i find an API that locates stores by zip code and name?	Google GeoCoding API	0
5458150	5298727	Transform configurations on deployment of console applications	"C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" MyConsoleProj\MyConsoleProj.csproj /P:Configuration=ConfigA\ncp MyConsoleProj\app.ConfigA.config MyConsoleProj\bin\x86\ConfigA\MyConsoleProj.exe.config\ncd MyConsoleProj\bin\x86\ConfigA\n7z a -y C:\MyConsoleProj-ConfigA.zip\ncd ..\..\..\..	0
9073871	9073849	c# console application dot effect	for(int i = 0;i < 5;i++)\n{\n  Console.Write(".");\n  Thread.Sleep(500);\n}	0
1108932	1108872	Copy DataGridView contents to clipboard	myDataGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;	0
22166494	22166261	Inline raw XML inside a c# code file	string data = Resources.TestData;	0
32180136	32179702	Draw custom ellipse in winform C#	private void RotateTransformAngle(PaintEventArgs e)\n{\n    // Set world transform of graphics object to translate.\n    e.Graphics.TranslateTransform(100.0F, 0.0F);\n\n    // Then to rotate, prepending rotation matrix.\n    e.Graphics.RotateTransform(30.0F);\n\n    // Draw rotated, translated ellipse to screen.\n    e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);\n}	0
6516634	6516591	How to implement "Access-Control-Allow-Origin" header in asp.net	Response.AppendHeader("Access-Control-Allow-Origin", "*");	0
6864291	6864234	SQL Server datetime issue?	Set DateFormat DMY\nGO\nINSERT INTO Table_02( ID,ClosingDate) \nSelect 1, Cast('27/07/2011 12:00:00 AM' As DateTime)	0
18838732	18838361	How to serialize DayOfWeek to have its number?	[Serializable]\npublic enum DayOfWeekEnum\n{\n    [EnumMember]\n    [XmlEnum(Name = "0")]\n    Sunday = 0,\n\n    [EnumMember]\n    [XmlEnum(Name = "1")]\n    Monday = 1,\n\n    [EnumMember]\n    [XmlEnum(Name = "2")]\n    Tuesday = 2,\n\n    [EnumMember]\n    [XmlEnum(Name = "3")]\n    Wednesday = 3,\n\n    [EnumMember]\n    [XmlEnum(Name = "4")]\n    Thursday = 4,\n\n    [EnumMember]\n    [XmlEnum(Name = "5")]\n    Friday = 5,\n\n    [EnumMember]\n    [XmlEnum(Name = "6")]\n    Saturday = 6,\n}	0
21748054	21748015	Pass a control to a function using its own "Click" event	private ctlRating_Click(object sender, EventArgs e) {\n    ChangeOutline(sender as StarRatingControl);\n}\n\nprivate ChangeOutline(StarRatingControl control) {\n    if(control.SelectedStar > 0) {\n        control.OutlineThickness = 0;\n    }\n    else {\n        control.OutlineThickness = 1;\n    }\n}	0
25279467	25279400	Ask for save as or open for downloading excel sheet from c#	Response.ContentType = "image/jpeg";\nResponse.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");\nResponse.TransmitFile(Server.MapPath("~/images/sailbig.jpg"));\nResponse.End();	0
22726789	22726653	Grab IP Text From IPChicken	body.table.tr.td.p.b	0
24487945	24487881	Execute a Function before a Timer start	method1();\nupdateAutoSMSTimer.Start();	0
18008102	18005391	User control menu link	.h_mnu_01 ul li a{\n    float: left;\n    color: #FFFFFF;\n    padding: 5px 11px;\n    text-decoration: none;\n    border-right-width: 1px;\n    border-right-style: solid;\n    border-right-color: #000000;\n}	0
9242954	9242852	Game level read from file in XNA	1,1,1,1\n1,0,1,1	0
7100734	7100049	how to handle events: array of controls with c sharp (old com control)	[ComImport]\n[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n[TypeLibType(TypeLibTypeFlags.FHidden)]\n[Guid("eventGuid")]\n[CLSCompliant(false)]\npublic interface IEvent\n{       \n   [DispId(123)]\n   void control_connected(int status, string description);\n}\npublic class EventSink:IEvent\n{\n   object control;\n   public EventSink (object control)\n   {\n        this.control=control;\n   }  \n   public event EventHandler<ControlConnectedEventArgs> ControlConnected;\n   void control_connected(int status, string description);\n   {\n       EventHandler<ControlConnectedEventArgs> temp=this.ControlConnected;\n       if(temp!=null)\n           temp(this.control, new ControlConnectedEventArgs(status,description));\n   }\n}	0
6087755	6087501	Linq to SQL Multiple Table Select as Keyvalue Pair	(from ???\n select new KeyValuePair<string, string>(stu.Name, stu.StudentId))\n    .Distinct().ToList()	0
29258513	29258191	How to add own header to Azure Mobile Services call?	public Task<HttpResponseMessage> InvokeApiAsync(\n    string apiName,\n    HttpContent content,\n    HttpMethod method,\n    IDictionary<string, string> requestHeaders,\n    IDictionary<string, string> parameters\n)	0
19643072	19643013	How to stop the console from flashing and disappearing	namespace ConsoleApplication1\n{\n   class Program\n   {\n      static void Main (string[] args)\n      {\n         System.Console.WriteLine("My name ?s Trevor");\n         Console.ReadKey();  // Add this line here.\n      }\n   }\n}	0
9039401	9039181	Add/Remove elements from XML in C#	// load the xml\nvar doc = XDocument.Load(@"C:\path\to\file.xml");\n\n// add a new location to "Alaska"\nvar parent = doc.Descendants("state")\n    .Where(e => (string)e.Attribute("name") == "Alaska")\n    .SingleOrDefault();\n\nif (parent != null)\n{\n    // create a new location node\n    var location =\n        new XElement("Location",\n            new XAttribute("Name", "loc5"),\n            new XElement("Address", "e1"),\n            new XElement("DateNTime", "e2")\n        );\n\n    // add it\n    parent.Add(location);\n}\n\n// remove a location from "Wyoming"\nvar wyoming = doc.Descendants("state")\n    .Where(e => (string)e.Attribute("name") == "Wyoming")\n    .SingleOrDefault();\n\nif (wyoming != null)\n{\n    // remove "loc4"\n    wyoming.Elements(e => (string)e.Attribute("Name") == "loc4")\n           .Remove();\n}\n\n// save back to the file\ndoc.Save(pathToFile);	0
25230236	25230142	How to send an item in an array to the back and move the other items forward? C#	for (int i = indx; i < xs.Length-1; i++)\n{\n    int tmp = xs[i];                    \n    xs[i]   = xs[i+1];\n    xs[i+1] = tmp;\n}	0
19224238	19224026	Need to clone a bitmap image without locking the original image	Graphics.FromImage	0
11184198	10980771	How to scroll in flowlayout panel without showing scrollbar in windows form	private void btnLeft_Click(object sender, EventArgs e)\n{\nif (flowPanelItemCategory.Location.X <= xpos)\n{\nxmin = flowPanelItemCategory.HorizontalScroll.Minimum;\nif (flowPanelItemCategory.Location.X >= xmin)\n{\nxpos -= 100;\nflowPanelItemCategory.Location = new Point(xpos, 0);\n}\n}\n}\n\nprivate void btnRight_Click(object sender, EventArgs e)\n{\nif (flowPanelItemCategory.Location.X <= xpos)\n{\nxmax = flowPanelItemCategory.HorizontalScroll.Maximum;\nif (flowPanelItemCategory.Location.X < xmax)\n{\nxpos += 100;\nflowPanelItemCategory.Location = new Point(xpos, 0);\n}\n}\n}	0
22154234	22101515	How to send multiple images from android to a WCF Rest Service as a stream to write to a network drive?	public static class FileUploader extends AsyncTask<UploadFile , Void , String> implements Future<String>\n{\n    @Override\n    protected void onPreExecute() {\n        filesUploading ++;\n    }\n\n    @Override\n    protected String doInBackground(UploadFile... uploadFile) \n    {\n        try \n        {\n            return postFile(uploadFile[0].file, uploadFile[0].projectNo, uploadFile[0].filename);\n        } catch (Exception e)\n        {\n            e.printStackTrace();\n        }\n        return null;\n    }               \n\n    @Override\n    protected void onPostExecute(String result) {\n        super.onPostExecute(result);\n        filesUploading --;\n    }\n\n    @Override\n    public boolean isDone() {\n          return AsyncTask.Status.FINISHED == getStatus();\n    }\n\n\n}	0
5733580	5733332	C#: Creating a Methodheader Parser	internal static string CreateAstSexpression(string filename)\n    {\n        using (var fs = File.OpenRead(filename))\n        {\n            using (var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp,\n                                                           new StreamReader(fs)))\n            {\n                parser.Parse();\n\n                // RetrieveSpecials() returns an IList<ISpecial>\n                // parser.Lexer.SpecialTracker.RetrieveSpecials()...\n                // "specials" == comments, preprocessor directives, etc.\n\n                // parser.CompilationUnit retrieves the root node of the result AST\n                return SexpressionGenerator.Generate(parser.CompilationUnit).ToString();\n            }\n        }\n    }	0
2882214	2876366	C# - Silverlight - CustomAttribute with Enum	[MetadataAttribute]\n[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\npublic class ModuleActivationButtonAttribute : ExportAttribute\n{\n    public Enum TargetRegion { get; set; }\n\n    public ModuleActivationButtonAttribute(object targetRegion) : base(typeof(IModuleActivationButton))\n    {\n        TargetRegion = targetRegion as Enum;\n    }\n}	0
7094540	7094383	Search for combination of two items with Linq	var arr = new byte[] { 1, 2, 3, 4, 5, 6 };\n\nvar res = arr.Zip(arr.Skip(1), (a, b) => new { a, b }).Select((x, i) => new { x, i })\n    .FirstOrDefault(v => v.x.a == 3 && v.x.b == 4);\n\n\nif (res != null)\n{\n    Console.WriteLine(res.i);\n}	0
24330946	24330726	Changing the color of dynamically created buttons not using clicked at event	button = this.tableLayoutPanel1.GetControlFromPosition(j, i);\nbutton.BackColor = Color.BLACK;	0
1033639	1033559	How to determine how long a song is using winmm.dll?	StringBuilder sb = new StringBuilder(128);\nmciSendString("status mediafile length", sb, 128, IntPtr.Zero);\nlong songlength = Convert.ToUInt64(sb.ToString());	0
32567465	32567237	Add items to ListView on Android in Xamarin application	adapter.Add ("Another Item!");	0
20608886	20608463	How to mock HttpContext in a ShoppingCart controller/model	var principalMock = new Mock<IPrincipal>();\nvar identityMock = new Mock<IIdentity>();\nidentityMock.Setup(x => x.Name).Returns("Test!");\nidentityMock.Setup(x => x.IsAuthenticated).Returns(true); // optional ;)\nuserMock.Setup(x => x.Identity).Returns(identityMock.Object);\nvar httpReqBase = new Mock<HttpRequestBase>(); // this is useful if you want to test Ajax request checks or cookies in the controller.\nvar httpContextBase = new Mock<HttpContextBase>();\n\nhttpContextBase.Setup(x => x.User).Returns(principalMock.Object);\nhttpContextBase.Setup(x => x.Session[It.IsAny<string>()]).Returns(1); //Here is the session indexer. You can swap 'any' string for specific string.\nhttpContextBase.Setup(x => x.Request).Returns(httpReqBase.Object);	0
26047695	26047538	Replace one control with another	pnlDisplay.Controls.Clear();	0
21040207	21040066	Logon failure: unknown user name or bad password	NetworkCredential myCred = new NetworkCredential(GlobalVariablesBO.UserID, GlobalVariablesBO.Password, GlobalVariablesBO.Domain);\n            WebClient webclient = new WebClient();\n            webclient.Credentials = myCred;\n            string tempFileForStorage = Path.Combine(Path.GetTempPath(), Path.GetFileName(dBO.SPFileName));\n            sharepointUpload.SaveAs(tempFileForStorage);\n            webclient.UploadFile("ServerPath", "PUT", tempFileForStorage);\n            webclient.Dispose();\n            File.Delete(tempFileForStorage);	0
6747021	6746871	Want to cause a postback after closing a Shadowbox	Shadowbox.init({\n    onClose: function () {\n        window.location.href = window.location.href;\n    }\n});	0
1585190	1585024	How does the Search Predicate of Findall work in a generic List	public delegate bool Predicate<A>(A arg);\n...\npublic List<T> FindAll(Predicate<T> predicate)   \n{\n    var result = new List<T>();\n    foreach (T item in this)\n        if (predicate(item))\n            result.Add(item);\n    return result;\n}	0
4141364	4139385	Append to text file	public void writetext()\n    {\n        using (TextWriter writer = new StreamWriter("filename.txt", true))  // true is for append mode\n        {\n            writer.WriteLine("First name, {0} Lastname, {1} Phone,{2} Day of birth,{3}", textBox1.Text, textBox2.Text, maskedTextBox1.Text, textBox4.Text);\n\n\n        }\n\n    }	0
15197665	15197615	Getting the minimum value and maximum value out of a series of numbers in C# without sorting	static void process(ref double minValue, ref double maxValue, ref double number)\n    {\n\n        if (number > maxValue)\n        {\n            maxValue = number;\n        }\n        if (number < minValue)\n        {\n            minValue = number;\n        }\n\n    }	0
21541335	21541305	if statement short-hand	foreach (var c in new[] {c1, c2, c3, c4, c5})\n{\n  if (!string.IsNullOrEmpty(c))\n  {\n    var _individual = new Individual { Age = Convert.ToInt32(c) };\n    request.Individuals.Add(_individual);\n  }\n}	0
8805994	8805664	Merging row content of text files in c#	string[] files = new string[] { @"c:\temp\file1.txt", @"c:\temp\file2.txt" };\nvar hash = new Dictionary<string, Dictionary<string, bool>>();\nforeach (var file in files)\n{\n    string[] fileContents = File.ReadAllLines(file);\n    foreach (string line in fileContents)\n    {\n        string[] a = line.Split(',');\n        if (!hash.Keys.Contains(a[0]))\n            hash[a[0]] = new Dictionary<string, bool>();\n        hash[a[0]][a[1]] = true;\n    }\n}\nforeach (var key in hash.Keys)\n    Console.WriteLine(key + "," + string.Join(",", hash[key].Keys.ToArray()));	0
7190178	7161379	How to set the scroll focus to specified control in c# windows app?	Point CurrentPoint; \n\nprivate void Form1_Activated(object sender, EventArgs e)\n{\n   this.AutoScrollPosition = new Point(Math.Abs(this.AutoScrollPosition.X), Math.Abs(CurrentPoint.Y));\n}\n\nprivate void Form1_Deactivate(object sender, EventArgs e)\n{\n   CurrentPoint = this.AutoScrollPosition;\n}	0
11653906	11653434	Get Value from XML File based on two child node values	//book[title[text()='Book123'] and author[text()='Author123']]	0
12786771	12786718	How to send the ping argument in C#	using System;\nusing System.Net;\nusing System.Net.NetworkInformation;\n\nnamespace ConsoleApplication6\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var ping = new Ping();\n\n            var reply = ping.Send(IPAddress.Loopback);\n\n            if (reply.Status == IPStatus.Success)\n            {\n                Console.WriteLine("Pinging with server: " + reply.Address);\n                Console.WriteLine("Press any key to continue");\n                Console.ReadKey(true);\n            }\n        }\n    }\n}	0
29593060	29592950	WinForm: control won't add to a panel	listeTours.Last().Location = new System.Drawing.Point(coordDepart.X, coordDepart.Y + ((listeTours.Count() + 1) * 30));	0
27203946	27202013	Deserialize Json issue due to spaces	public class Item\n{\n\n    private string firstName = "";\n    private string secondName = "";\n\n    [JsonProperty("First Name")]\n    public string FirstName\n    {\n        get { return firstName; }\n        set { firstName = value; }\n    }\n\n    [JsonProperty("Second Name")]\n    public string SecondName\n    {\n        get { return secondName; }\n        set { secondName = value; }\n    }\n}	0
4604206	4603851	WPF layer event separation	if(e.OriginalSource == menuCanvas)\n{\n    //Your code\n}	0
22852693	22852545	Have single-threaded app block till a specific event occurs and then resume	private static ManualResetEventSlim _event = new ManualResetEventSlim (false);\n\npublic static void AwaitTemplatePropagation(this Connection conn, DBObject template)\n{\n    template.PropertyUpdated += OnPropertyUpdated; // Something?\n\n    template.RegisterForPropertyUpdates(new string[] { "TransactionCount" });\n\n    // Magic happens?\n    // if you are using this method many times you have to reset the event first\n    _event.Reset(); //Sets the state of the event to nonsignaled, which causes threads to block.\n    _event.WaitHandle.WaitOne();\n\n    template.UnregisterPropertyUpdates(new string[] { "TransactionCount" });\n\n    // Return to the calling function in the main thread\n }\n\npublic void OnPropertyUpdated(...)\n{\n    _event.Set();\n}	0
24768540	24718818	Unable to create a constant value of type	var result=db.ListA.Where(a => ListB.Contains(a.FinAccCompelteCode)).ToList();	0
23552129	23551874	Combine Values of datetime picker and combobox selected index	var datePickerDate = dateTimePicker.Value;\nvar comboboxTime = comboBox.SelectedText;\nvar dateTimeString = String.Format("{0} {1}", datePickerDate, comboboxTime);\n\nvar combinedDate = DateTime.Parse(dateTimeString);	0
2203498	2203474	Register all declared child classes of a class in C#	var targetAssembly = Assembly.GetExecutingAssembly(); // or whichever\nvar subtypes = targetAssembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Pet)));	0
26465840	26465756	IEnumerable<T> - How to use one method for both enumerators	public IEnumerator<KeyValuePair<int, Line>> GetEnumerator()\n    {\n        Line line = null;\n        current = 0;\n\n        while ((line = GetNext()) != null)\n            yield return new KeyValuePair<int, Line>(current, line);\n    }\n\n    public abstract Line GetNext();\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n    {\n        return (IEnumerator)GetEnumerator();\n    }	0
34056393	34054821	How can i make that when searching for youtube uploads using google api v3 it will show more then 50 results?	var nextPageToken = "";\n        while (nextPageToken != null)\n        {\n          var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");\n          playlistItemsListRequest.PlaylistId = uploadsListId;\n          playlistItemsListRequest.MaxResults = 50;\n          playlistItemsListRequest.PageToken = nextPageToken;\n\n          // Retrieve the list of videos uploaded to the authenticated user's channel.\n          var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();\n\n          foreach (var playlistItem in playlistItemsListResponse.Items)\n          {\n            // Print information about each video.\n            Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);\n          }\n\n          nextPageToken = playlistItemsListResponse.NextPageToken;\n        }	0
1473438	1473344	Adding commas to a decimal number which is in a string of text with .NET 2.0	string input = "Blah Blah Blah. Total price: $1234567.89; Blah Blah Blah Blah";\n\nstring output = Regex.Replace(input, @"\d+(\.\d\d)?", match => decimal.Parse(match.Value).ToString("N"));	0
5791818	5791773	Getting keys from a Lookup	var keys = myLookup.Select(g => g.Key).ToList();	0
2981193	2979918	Tree deletion with NHibernate	public class Node_Map : ClassMap<Node>\n    {\n        public Node_Map()\n        {\n            References(x => x.Parent, "IdCmsNodeParent");\n            HasMany(x => x.Childs).AsBag()\n                                  .Inverse()\n                                  .Cascade.Delete()\n                                  .KeyColumn("IdNodeParent");\n        }\n    }	0
14761555	14761334	interacting with awesominum webcontrol	var control = <some awesomium WebControl instance>;\ncontrol.SelectAll();\ncontrol.CopyHtml();\nvar html = Clipboard.GetText();	0
705061	703026	Shared resource dictionary between several user controls and across assemblies	Style="{StaticResource MyButtonStyle}"	0
34168731	34168662	WPF set Textbox Border color from C# code	textBox.BorderBrush = System.Windows.Media.Brushes.Red;	0
8713927	8713882	XmlElement has a list as attribute but its items aren't separated by comma	private float[] _numbers;\n[XmlAttribute(AttributeName = "numbers")]\npublic string Numbers\n{\n    get\n    {\n        return string.Join(",", _numbers);\n    }\n}	0
7768446	7768287	Get full class name from table name in nhibernate	configuration.ClassMappings.Where(x => x.Table.Name == "Site").First().EntityName	0
22150145	22148095	How to make user use 1 app only on 1 PC ( or to create License)	HASH(MotherBoard.Product + MotherBoard.SerialNumber + PhysicalDisk.ModelNumber + PhysicalDisk.SerialNumber + ComputerSystemProduct.UUID)	0
3090307	3090269	Add One DataView to Another in C#	System.Data.DataView dv = new System.Data.DataView();\nSystem.Data.DataView dv1 = new System.Data.DataView();\ndv.Table.Merge(dv1.Table);	0
22807119	22806888	WP8 NullReferenceException while saving picture to media library	using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())\n{\n    if (isoStore.FileExists("fileName"))\n    {\n        using (var fileStream = isoStore.OpenFile("fileName", FileMode.Open))\n        {\n            byte[] bytes = new byte[0]; // Read bytes from fileStream\n\n            MediaLibrary library = new MediaLibrary();\n            library.SavePicture("name", bytes);\n        }\n    }\n}	0
12315941	12304411	Lightswitch get data from related datatable	this.Orders.Supplier.Email	0
834082	834043	Scroll Event in C#	if(this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 1].Displayed)\n{\n   //last rows is displayed, do what you gotta do\n}	0
25546574	25546430	Passing id in a custom column in a webgrid is throwing error	format: (item) = >\n{\nvar links = Html.ActionLink("Delete", "ActionName","ControllerName", new {id = item.PrimaryKey},null) \nreturn Html.Raw(links.ToString())\n}	0
2808488	2808447	How to remove the domain name?	string loginName = SPContext.Current.Web.CurrentUser.LoginName;\nstring[] loginNameParts = loginName.Split('\\');\nstring loginNameWithoutDomain = nameParts[1];	0
6029352	6028619	RegularExpression Validation on a DataBound GridView	Regex numeric = new Regex(@"^\d+$");\n\nvoid GridView_RowDataBound(Object sender, GridViewRowEventArgs e) {\n    // check out all cells in the current row\n    foreach(var cell in e.Row.Cells) {\n        // do some validation thingy\n        if(!numeric.Match(cell.Text).Success) {\n             cell.CssClass = "error"; // put error class on the cell\n        }\n    }\n}	0
30610721	30603928	Changing Grid Image source on Button Click via Xaml.cs	ImageBrush b1 = new ImageBrush();\n        b1.ImageSource = new BitmapImage(new Uri(@"ms-appx:///Assets/Theme2.png", UriKind.RelativeOrAbsolute));\n        BG.Background = b1;	0
10456225	10456169	DateTime manipulation	DateTime startDate = Convert.ToDateTime( orderDate ).AddMonths(-1);\n// set to first of month\nstartDate = startDate.AddDays(1-startDate.Day);\n\n// Set end date to last of month, which is one day before first of next month\nDateTime endDate = startDate.AddMonths(1).AddDays(-1);	0
17030825	17030721	Possible to use one resource file with multiple languages?	string culturePref = [Your setting from web-config]; // "en-US" or "en-EU"\n    try\n    {\n        Thread.CurrentThread.CurrentCulture =\n            CultureInfo.CreateSpecificCulture(culturePref);\n\n    }\n    catch\n    {\n        Thread.CurrentThread.CurrentCulture =\n            new CultureInfo("en-US");\n    }\n    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;	0
4563078	4561577	Postmortem debugging with WinDBG	//\n// MessageId: E_ADS_BAD_PARAMETER\n//\n// MessageText:\n//\n//  One or more input parameters are invalid\n//\n#define E_ADS_BAD_PARAMETER              _HRESULT_TYPEDEF_(0x80005008L)	0
30657825	30657711	Change the Value of a Label in a page before sending to mail	StringWriter _writer = new StringWriter();\nHttpContext.Current.Server.Execute("AreaManagersMail.aspx", _writer);\n\nMailMessage newMail = new MailMessage();\n\n//other initialisation here    \n\nnewMail.Body = _writer.ToString();	0
26185148	26184657	12 hour clock, the 12th hour in decimal	for (int i = 0; i < 7; i++)\n    {\n        DateTime dt = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);\n        string timestring = dt.ToString("h:mm");\n        labels[i].Text = timestring;\n\n        DateTime timeIn = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);\n        DateTime timeOut = DateTime.ParseExact(textboxesOut[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);\n\n        if(timeIn.Hour == 12) timeIn = timeIn.AddHours(-12);  //a easy way\n\n        if (dropdownIn[i].SelectedValue == "PM")\n        {\n            timeIn = timeIn.AddHours(12);\n        }\n\n        if (dropdownOut[i].SelectedValue == "PM")\n        {\n            timeOut = timeOut.AddHours(12);\n        }\n        labels[i].Text = (timeOut - timeIn).TotalHours.ToString("f2");\n    }	0
4792375	4791860	Database to DropDownList and AutoPostBack to Label	SqlCommand cmd = new SqlCommand("select B.HESAP_NO FROM  YAZ..MARDATA.S_TEKLIF B WHERE B.MUS_K_ISIM = '" + DropDownList1.SelectedItem.Value + "'", myConnection);	0
8845392	8845376	How to get the same random number twice?	int ran = random.Next(lbMessage.Items.Count);\nSendKeys.Send(lbMessage.Items[ran].ToString().Substring(currentChar++, 1));\n\nif (currentChar == lbMessage.Items[ran].ToString().Length) {\n    SendKeys.Send("{enter}");\n    tmrSpace.Enabled = false;\n    currentChar = 0;\n}	0
33343685	33343062	Merged String Checker (custom rules)	public bool IsMatch(string target, string part1, string part2)\n{\n    if (target.Length != part1.Length + part2.Length)\n    {\n        return false;\n    }\n    if (target == "")\n    {\n        return true;\n    }\n\n    if (part1.Length > 0 && target[0] == part1[0])\n    {\n        if (IsMatch(target.Substring(1), part1.Substring(1), part2.Substring(0)))\n        {\n            return true;\n        }\n    }\n    if (part2.Length > 0 && target[0] == part2[0])\n    {\n        if (IsMatch(target.Substring(1), part1.Substring(0), part2.Substring(1)))\n        {\n            return true;\n        }\n    }\n\n    return false;\n}	0
24393218	24393128	Trying to get message alert for empty text box	string fileName = fileText.Text;\nif(string.IsNullOrWhiteSpace(fileName) || !System.IO.File.Exists(fileName)) {\n    MessageBox.Show("Wrong file name");\n    return;\n}	0
32251901	32251362	Multiple Timers	private async void DoStuff()\n{\n    MessageBox.Show("action1");\n    await Task.Delay(4000),\n    MessageBox.Show("action2");\n    await Task.Delay(4000);\n    //...\n}	0
4928930	4928810	How do I write an extension method for a generic type with constraints on type parameters?	public class Matrix<T>  where T : new() {\n     public T[,] values;\n }\n\n\n public static class MatrixExtension {\n     public static T getCalcResult<T>(this Matrix<T> mat)  where T : new() {\n         T result = new T();\n         return result;\n     }\n }\n\n class Program {\n     static void Main(string[] args)  {\n        Matrix<int> m = new Matrix<int>();\n        int aNumber = m.getCalcResult();\n        Console.WriteLine(aNumber); //outputs "0"\n }	0
6356381	6356351	Formatting a float to 2 decimal places	ToString("0.00"); //2dp Number\n\nToString("n2"); // 2dp Number\n\nToString("c2"); // 2dp currency	0
11549427	11549332	How to improve performance of a method	static void Main(string[] args)\n{\n    Stopwatch stopWatch = new Stopwatch();\n    stopWatch.Start();\n    Thread.Sleep(10000);\n    stopWatch.Stop();\n    TimeSpan ts = stopWatch.Elapsed;\n\n    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n        ts.Hours, ts.Minutes, ts.Seconds,\n        ts.Milliseconds / 10);\n\n    Console.WriteLine("RunTime " + elapsedTime);\n}	0
20122756	20122443	How to get upper and lower value of specific column cell value in datatable using Linq	var forNext = (from myRow in myDataTable.AsEnumerable()\n                           where myRow.Field<int>("DocumentID") > CurrentID\n                           orderby myRow.Field<int>("DocumentID")\n                           select myRow).FirstOrDefault();\n\n            var forPrevious = (from myRow in myDataTable.AsEnumerable()\n                               where myRow.Field<int>("DocumentID") < CurrentID\n                               orderby myRow.Field<int>("DocumentID") descending\n                               select myRow).FirstOrDefault();	0
27220732	27220637	How to validate input for Int32.Parse() (without exceptions)	string stringValue = "123";\nint intValue = 0;\n\nbool check = int.TryParse(stringValue, out intValue);	0
5003694	5003482	How to make a windowless / command-line application return but continue executing in background?	static void Main(string[] args)\n{\n    if (args.Length > 0 && args[0] == "run")\n    {\n        //actually run your application here\n    }\n    else\n    {\n        //create another instance of this process\n        ProcessStartInfo info = new ProcessStartInfo();\n        info.FileName = Assembly.GetExecutingAssembly().Location;\n        info.Arguments = "run";\n        info.UseShellExecute = false;\n        info.CreateNoWindow = true;\n\n        Process.Start(info);\n    }\n}	0
11994330	11994183	How do I update a progress bar based on a foreach loop that runs based on a variable array?	int count = finalFiles.Length;\nint current = 0;\nforeach (string file in finalFiles)\n{\n    current++;\n    pbUpload.Value = current / count * 30 + 70;\n}	0
11510105	11509938	AES and SHA1 from perl to .net	UnicodeEncoding UE = new UnicodeEncoding();\nbyte[] bfr;\nbyte[] pwdBits = UE.GetBytes(plainText);\nbyte[] result;\n\nint extends = (1 + (pwdBits.Length / 16)) * 16;\nbfr = new byte[extends];\n\npwdBits.CopyTo(bfr, 0);\n\nusing (MemoryStream msCrypt = new MemoryStream())\n{\n    RijndaelManaged RMCrypto = new RijndaelManaged();\n    RMCrypto.Padding = PaddingMode.PKCS7;\n    using (ICryptoTransform encriptor = RMCrypto.CreateEncryptor(Key, IV))\n    {\n         using (CryptoStream cs = new CryptoStream(msCrypt, encriptor, CryptoStreamMode.Write))\n         {\n              cs.Write(bfr, 0, bfr.Length);\n              cs.FlushFinalBlock();\n              result = msCrypt.ToArray();\n              cs.Close();\n         }\n         msCrypt.Close();\n    }\n}\nreturn result;	0
5222689	5222643	Check if text appears on the text property of any element in SelectList	if (tempList.Select(i => i.Text).Contains(GroupDisplayName))\n     // do the rest	0
29173065	29172742	Download image from img src in c#	using (WebClient client = new WebClient())\n{\n    client.DownloadFile("http://somedomain/image.png",\n    @"c:\temp\image.png");\n\n    // You can also you the async call \n    client.DownloadFileAsync("http://somedomain/image.png",\n    @"c:\temp\image.png");\n}	0
31421240	31418442	How can create a random code	int randomNumber;\n\nrandomNumber = new Random().Next(1, n + 1);\n\nswitch(randomNumber)\n{\n   case 1: ShowPage1();\n           break;\n   case 2: ShowPage2();\n           break;\n   case 3: ShowPage3();\n           break;\n   ...\n   case n: ShowPageN();\n             break;\n}	0
12406618	12406276	WCF how to avoid defining many operationcontracts	[OperationContract]\nStudentDTO GetStudent(int studentId);\n[OperationContract]\nStudentDTO UpdateStudent(CreateStudentDTO student);\n[OperationContract]\nStudentDTO UpdateStudent(UpdateStudentDTO student);\n\n[DataContract]\npublic class StudentDTO\n{\n  public int Id { get; set; }\n  public string Name { get; set; }\n  public StudentInformationDTO StudentInformation { get; set; }\n\n  // other student's data here\n}	0
27732277	27712304	Data Validation not working in Edit Mode	public class User: IValidatableObject\n{\n     public int Id{get; set;}\n     public string UserName{get; set;}\n     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n     {\n          if(string.IsNullOrEmpty(UserName))\n               yield return new ValidationResult("Username field is required!", new string[]{"UserName"});\n          else \n          {\n               // check if another User has the same username already\n               var db= new YourDbContext();\n               var exists=db.Users.FirstOrDefault(t=>t.Id!=Id && t.UserName.ToLower()=UserName.ToLower());\n               if(exists!=null)\n                   yield return new ValidationResult("Username is already used by another user!", new string[]{"UserName"});\n          }\n     }\n}	0
22656229	22655927	Get Data From one SQL Server to Other SQL server (using C#)	using (SqlConnection connection = new SqlConnection("yourConnectionString"))\n{\n    connection.Open();\n\n    SqlCommand command = new SqlCommand("select bhand from importdb where bhand = 3 and store = 14", connection);\n    SqlDataReader reader = command.ExecuteReader();\n\n    SqlConnection connection2 = new SqlConnection("yourConnectionStringTo2ndDB");\n    connection2.Open();\n\n    while (reader.Read())\n    {\n        SqlCommand command = new SqlCommand("insert into importabd ('bhand') values ('" +  reader[0]+"')", connection2);\n        command.ExecuteNonQuery();\n    }\n    connection2.close();\n}	0
21186187	21185498	Retrieve Data From Database in C# and ASP.NET with buttonClick	using System.Data.SQLClient;\n\nClass DataExtract\n{ \n\nPublic DataTable Extract()\n  {\n     SqlConnection con = new SqlConnection("Data Source = .;\n                                       Initial Catalog = domain;\n                                       Integrated Security = True");\n     con.Open();\n     SqlCommand cmd = new SqlCommand("Select * from tablename", con); \n\n     Return new DataTable().load(cmd.ExecuteReader());\n\n  }\n}	0
26847233	26844344	How to create a WCF Service that has an always running component?	[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]\npublic class MyService : IMyService{\n{\n    private int _counter;\n    public int Test(){ return _counter++; }\n}	0
31541286	31540521	how to set column in GridView to default value?	public int _QtyAdvised = 1;\npublic int QtyAdvised\n        {\n            get { return _QtyAdvised; }\n            set { _QtyAdvised = value; }\n        }	0
10210045	10210024	How to create array of 100 new objects?	point[] array = new point[100];\nforeach(point p in array)\n{\n    p = new point();\n}\narray[0].x = 5;	0
33343356	33341350	Custom paging using Data Column with gap in Records	-- Variable to hold the offset value\nDeclare @RowSkip As int\n-- Variable to hold the fetch value\nDeclare @RowFetch As int\n\n--Set the value of rows to skip\n Set @RowSkip = 20000\n--Set the value of rows to fetch\n Set @RowFetch = 50000\n\nSelect *\nFrom dbo.tblSample \nOrder by (Select 1)  \nOffset @RowSkip Row \nFetch  Next @RowFetch Rows Only;	0
580706	576741	Customising the browse for folder dialog to show the path	var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();\n     dlg1.Description = "Select a folder to extract to:";\n     dlg1.ShowNewFolderButton = true;\n     dlg1.ShowEditBox = true;\n     //dlg1.NewStyle = false;\n     dlg1.SelectedPath = txtExtractDirectory.Text;\n     dlg1.ShowFullPathInEditBox = true;\n     dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;\n\n     // Show the FolderBrowserDialog.\n     DialogResult result = dlg1.ShowDialog();\n     if (result == DialogResult.OK)\n     {\n         txtExtractDirectory.Text = dlg1.SelectedPath;\n     }	0
28504741	28504444	MySql library not found	using MySQL.Data	0
17830857	17830160	how to allow paging operation to navigate from one page to another in grid view control	private void gridview1_PageIndexChanging(object sender,System.Web.UI.WebControls.GridViewPageEventArgs e)        \n {\n    gridview1.ShowFooter = false;\n    gridview1.EditIndex = -1;\n    gridview1.PageIndex = e.NewPageIndex;\n        if (ViewState("VW_Data") != null) {\n            dtData= new DataTable();\n            dtData= (DataTable)ViewState("VW_Data");\n\n            gridview1.DataSource = dtData;\n            gridview1.PageSize = ddlRecordsPerPage.SelectedValue;\n            gridview1.DataBind();\n        } \n       else {\n               GetData();\n            }\n  }	0
32137564	32137324	How to to do a $project with the mongo C# 2.0 driver	.Project(root => \n    new Root2 {\n        ezBaseId = root.EzBaseId,\n        classificationId = root.Id.ClassificationId,\n        name = root.Id.Name,\n        specification = root.Id.Specification,\n        img = root.Id.Image,\n        articles = root.Articles,\n        supplier = root.Id.Supplier\n    });	0
30595596	26995592	Suggest a way in threading that always fixed number of threads must be used in computing?	OrderablePartitioner<Tuple<int, int>> chunkPart = Partitioner.Create(0, fileList.Count, 1);//Partition the list in chunk of 1 entry\n\nParallelOptions opt= new ParallelOptions();\nopt.TaskScheduler = null;\nopt.MaxDegreeOfParallelism = 8;\n\nParallel.ForEach(chunkPart, opt, chunkRange =>\n{\n    for (int i = chunkRange.Item1; i < chunkRange.Item2; i++)\n    {\n        DoSomething(fileList[i].FullName);\n    }\n});	0
15788167	15786294	Retrieve Windows Update history using WUAPILib from a remote machine	Type t = Type.GetTypeFromProgID("Microsoft.Update.Session", "remotehostname");\nUpdateSession session = (UpdateSession)Activator.CreateInstance(t);\nIUpdateSearcher updateSearcher = session.CreateUpdateSearcher();\nint count = updateSearcher.GetTotalHistoryCount();\nIUpdateHistoryEntryCollection history = updateSearcher.QueryHistory(0, count);\nfor (int i = 0; i < count; ++i)\n{\n    Console.WriteLine(string.Format("Title: {0}\tSupportURL: {1}\tDate: {2}\tResult Code: {3}\tDescription: {4}\r\n", history[i].Title, history[i].SupportUrl, history[i].Date, history[i].ResultCode, history[i].Description));\n}	0
13547764	13520632	How to cancel an awaiting task?	var task = Listener.AcceptTcpClientAsync();\ntask.Wait(MainToken.Token);\nMainToken.Token.ThrowIfCancellationRequested();	0
17284341	17281809	Converting Excel cell to percentage using epplus	foreach (var dc in dateColumns)\n  {\n    sheet.Cells[2, dc, rowCount + 1, dc].Style.Numberformat.Format ="#0\\.00%";\n   }	0
19798509	19798358	Close button not working in windows forms application	private void CancelButton_Click(object sender, EventArgs e) {\n    this.AutoValidate = System.Windows.Forms.AutoValidate.Disable;\n    this.Close();    // or this.DialogResult = DialogResult.Cancel\n}	0
30984769	30984672	Order IEnumerable<T> object based on Dictionary	var sorted = list.OrderByDescending(x => dictionary[x.id])	0
4189172	4176807	Display multiple objects in property grid	_PropertyGrid.SelectedObjects = (selected as object[]);	0
24782275	24781214	Copying an image file to an empty folder in using WPF C#	public static void Copy()\n    {\n        string _finalPath;\n        var files = System.IO.Directory.GetFiles(@"C:\"); // Here replace C:\ with your directory path.\n        foreach (var file in files)             \n        {\n            var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path\n            _finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014\n            if (System.IO.Directory.Exists(_finalPath))\n            {\n                _finalPath = System.IO.Path.Combine(_finalPath, filename);\n                System.IO.File.Copy(file, _finalPath, true);\n            }\n        }\n    }	0
23915962	23915578	c# finding text rtb using richtextbox.Find and using as check	if(richTextBox2.Text.Contains("Core"))\n{\n    MessageBox.Show("Found Core");\n}\nif(richTextBox2.Text.Contains("Business"))\n{\n    MessageBox.Show("Found Business");\n}	0
20966479	20966209	Can I have a select like this with a LINQ to Entitites query?	var questions = _questionsRepository\n    .GetAll()\n    .Where(q => q.Problem.SubTopicId == subTopicId || subTopicId == 0)\n    .Where(q => q.QuestionStatusId == questionStatusId || questionStatusId == 0)\n    .Where(q => q.AssignedTo == assignedTo || assignedTo == "0")\n    .Where(q => q.ModifiedBy == modifiedBy || modifiedBy == "0")\n    .Include(q => q.Problem)\n    .Include(q => q.Answers)\n    .Select(x => new {\n        QuestionId = x.QuestionId,\n        QuestionUId = x.QuestionUId,\n        Answers = x.Answers,\n        ProblemId = x.Problem.ProblemId\n    })\n    .AsEnumerable()\n    .Select(x => new Question {\n        QuestionId = x.QuestionId,\n        QuestionUId = x.QuestionUId,\n        Answers = x.Answers,\n        Problem = x.ProblemId\n    })\n    .ToList();	0
12579371	12566420	Set image width dynamically in MonoTouch	img.Frame = fillrect;	0
29668994	29668882	Distinct rows from db table with unique IDs but same names	var result = Context.Movie\n                    .DistinctBy(m => new {\n                                            // take all properties except your ID\n                                         })\n                    .ToList();	0
4888323	4888216	Split string by a complete string separator	string[] bits = Regex.Split("AA@AAA_@#@BBBBBB@#@CCCCCC", "@#@");	0
7188274	5017046	Remove padding/margin from DataGridView Cell	void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)//remove padding\n{\n   // ignore the column header and row header cells\n\n   if (e.RowIndex != -1 && e.ColumnIndex != -1)\n   {\n      e.PaintBackground(e.ClipBounds, true);\n      e.Graphics.DrawString(Convert.ToString(e.FormattedValue), e.CellStyle.Font, Brushes.Gray, e.CellBounds.X, e.CellBounds.Y - 2, StringFormat.GenericDefault)\n      e.Handled = true;\n   }\n}	0
17117263	17117210	XML to Dataset : How does one access a complex type within a node?	var name = "Company B";\nvar xdoc = XDocument.Load("company.xml");\nvar contacts = from company in xdoc.Descendants("Company")\n               where (string)company.Element("CompanyName") == name\n               from contact in company.Element("Contacts").Elements()\n               select new {\n                   City = (string)contact.Element("City"),\n                   Country = (string)contact.Element("Country"),\n                   FirstName = (string)contact.Element("FirstName")\n               };	0
14935163	14932863	Load local html file in webbrowser control in editable mode	webBrowser1.AllowWebBrowserDrop = false;\n    webBrowser1.Url = new Uri(@"D:\TEMP\sample.htm");	0
2188160	2188059	Winforms user controls custom events	class MyUserControl : UserControl\n{\n   public event EventHandler TextBoxValidated\n   {\n      add { textBox1.Validated += value; }\n      remove { textBox1.Validated -= value; }\n   }\n}	0
13962490	13962430	Button switches app page from mainpage to page 1	NavigationService.Navigate(new Uri("/page1.xaml",UriKind.Relative));	0
8399130	8398966	how to find number of duplicate element in Binary search tree	for i = 0 to MAX_VALUE do\n  currentNode = root;\n  while(TRUE)\n      if (currentNode.Value == i)\n           apprearanceCount++;\n      if (i > currentNode.Value)\n           currentNode = currentNode.RightNode;\n      else \n           currentNode = currentNode.LeftNode;\n      if currentNode == NULL then break; // Don't forget to save appearance count	0
8529903	8529879	Changing a string to have first character uppercase and remainder lowercase	public string Capitalise(string str) {\n    if (String.IsNullOrEmpty(str))\n        return String.Empty;\n    return Char.ToUpper(str[0]) + str.Substring(1).ToLower();\n}	0
7587380	7587267	C# WriteAttributeString - Multiple Elements	writer.WriteStartElement("CommunicationList");\n\nwriter.WriteStartElement("Communication");\nwriter.WriteAttributeString("primary", "N");\nwriter.WriteAttributeString("value", "heisenburg@albuquerquecarwash.com");\nwriter.WriteAttributeString("purpose", "PERSONAL");\nwriter.WriteAttributeString("type", "EMAIL");\nwriter.WriteEndElement();\n\nwriter.WriteEndElement();	0
26195299	26195133	How to consume HttpClient from F#?	let getAsync (url:string) = \n    async {\n        let httpClient = new System.Net.Http.HttpClient()\n        let! response = httpClient.GetAsync(url) |> Async.AwaitTask\n        response.EnsureSuccessStatusCode () |> ignore\n        let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask\n        return content\n    }	0
4446198	4446163	Linq to SQL Joining to the Same Table Twice for Two Different Tables	from ca in ConsumerApplications\njoin est in RepairOrderEstimates on ca.RepairOrderEstimateID == est.RepairOrderEstimateID\njoin statConsumerApp in Statuses on ca.StatusID == statConsumerApp.StatusID\njoin statEstimate in Statuses on est.StatusID == statEstimate.StatusID\nselect new {\n  ConsumerAppID = ca.ConsumerAppID,\n  LastName = ca.LastName,\n  AppStatus = statConsumerApp.StatusName,\n  EstimateStatus = statEstimate.StatusName,\n}	0
34004587	34003173	Label color property in listview xamarin	amountLabel.SetBinding(Label.TextColorProperty, new Binding("amount")\n   { Converter = new AmountColorConverter() }\n);	0
4009735	4009714	Collection of strings to dictionary	var dico = strings.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());	0
5179013	5178976	Linq: assign variables in Lambda expressions	var result = list.Select(a =>\n  {\n    var localVariable = a.number + 2;\n    return new \n    {\n        Variable = localVariable \n    };\n  }\n);	0
8542265	8542250	How can I rename XML root ArrayOfElement in C#?	[XmlRoot("Articles")]\npublic class Articles : List<Article> { }	0
31771264	31771143	How to get item[0] from "listview.ItemsSource" on universal(wpf)	var x = t.First();	0
5340866	5340746	Custom Fields Only From Sharepoint List	SPBuiltInFieldId.Contains(field.Id)	0
197062	197059	Convert dictionary values into array	// dict is Dictionary<string, Foo>\n\nFoo[] foos = new Foo[dict.Count];\ndict.Values.CopyTo(foos, 0);\n\n// or in C# 3.0:\nvar foos = dict.Values.ToArray();	0
8810687	8810654	C# Declare a variable as generic instead of using a generic method	public SomeMethod<T>(string repositoryName) where T : Entity, IOrderedEntity\n{\n    List<T> entityList = repository<T>.All().OrderBy(x => x.DisplayOrder).ToList();\n\n    foreach (var entityRecord in entityList)\n    {\n        //... do work ...\n    }\n}	0
25742757	25742207	Know resulting image size before performing a resize in Imageresizer	ImageBuilder.Current.GetFinalSize(ImageSize, new ResizeSettings(parameters));	0
3043663	3043611	Search in a List<DataRow>?	var searchValue = SOME_VALUE;\nvar result = list.Where(row => row["MyColumn"].Equals(searchValue)); // returns collection of DataRows containing needed value\nvar resultBool = list.Any(row => row["MyColumn"].Equals(searchValue)); // checks, if any DataRows containing needed value exists	0
18706008	18705875	How to get the values href values rather than the anchor tags?	var urls = html.DocumentNode.SelectNodes("//a[contains(@href, 'watch?v=')")\n            .Select(a => a.Attributes["href"].Value)\n            .ToList();	0
9625449	9625342	split a string from a text file into another list	var list = new List<string[]>();\n        using (StreamReader reader = new StreamReader("Test.txt"))\n        {\n            string line;\n            while ((line = reader.ReadLine()) != null)\n            {\n                list.Add(line.Split(' '));\n            }\n        }\n\n        string firstWord = list[0][0]; //12345 \n        string secondWord = list[0][1]; //Test	0
5529347	5509374	Background work with UI	private void RunButton_Click(object sender, RoutedEventArgs e)\n{\n    ThreadPool.QueueUserWorkItem(\n        delegate\n        {\n            // Do work\n\n            Dispatcher.Invoke(new Action(\n               delegate \n               { \n                   // Do UI stuff\n               }));\n\n            // Do more work\n\n            Dispatcher.Invoke(new Action(\n               delegate \n               { \n                   // Do UI stuff\n               }));\n        });\n}	0
6399778	6399767	How do I remove combo box dynamically in C# by pressing a button in runtime?	flowLayoutPanel.Controls.RemoveAt(flowLayoutPanel.Controls.Count - 1);	0
27195819	27195706	Linq, project elements from 2 lists	var composites = widths.Zip(distances, (w, d) => new Composite() { Width = w, Distance = d })\n                       .ToList();	0
3615776	3615753	How to get "unordered choose two" permutation in a list of Strings in C#	var sourceStrings = new List<string> {"A", "B", "C"};\n\nvar resultStrings = from a in sourceStrings\n                    from b in sourceStrings\n                    where a != b\n                    select a + "-" + b;\n\nforeach (var result in resultStrings)\n    Console.WriteLine(result);	0
19134158	19134063	asp.net splitting xml DataTable	DataTable dt1  = ds.Tables[0].Select("Column1 ='1000'").CopyToDataTable();\nDataTable dt2 = ds.Tables[0].Select("Column1 ='1234'").CopyToDataTable();	0
22318645	22317596	Copy content of word document Sections	System.Collections.ArrayList al = new System.Collections.ArrayList();\n\nint mycount = 0;\n\nforeach (Microsoft.Office.Interop.Word.Section section in document.Sections)\n\n{\n\n    al.Insert(mycount, section.Range.Text.ToString());\n\n    mycount++;\n\n}     \n\n mycount = 0;\n\n while (mycount < al.Count)\n\n {\n\n    MessageBox.Show(" Section Text " + al[mycount].ToString());\n\n   mycount++;\n\n }	0
7913946	7912584	Exchange Web Service FolderId for a not well known folder name	//set Server\n        ExchangeService server = new ExchangeService(ExchangeVersion.Exchange2007_SP1);\n        server.UseDefaultCredentials = true;\n        string configUrl = @"https://yourServerAddress.asmx";\n        server.Url = new Uri(configUrl);\n        //SetView\n        FolderView view = new FolderView(100);\n        view.PropertySet = new PropertySet(BasePropertySet.IdOnly);\n        view.PropertySet.Add(FolderSchema.DisplayName);\n        view.Traversal = FolderTraversal.Deep;\n        FindFoldersResults findFolderResults = server.FindFolders(WellKnownFolderName.Root, view);\n        //find specific folder\n        foreach(Folder f in findFolderResults)\n        {\n            //show folderId of the folder "test"\n            if (f.DisplayName == "Test")\n                Console.WriteLine(f.Id);\n        }	0
13333433	13333292	One entity to another with multiple properties	modelBuilder.Entity<UserMessage>()\n    .HasMany(d=>d.PermittedUsers)\n    .WithMany(d=>d.Messages)\n    .Map(c=>c.ToTable("UserMessageUsers"));	0
24176295	24176044	Rename all file names in a directory using datagridview column value	string sourceDir = "D:\\Temp\\";\n        DirectoryInfo d = new DirectoryInfo(sourceDir);\n        string newFileName = "";\n        string oldFileName = "";\n        foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            newFileName = sourceDir + row.Cells["ID"].Value.ToString() + ".csv";\n            oldFileName = sourceDir + row.Cells["Name"].Value.ToString() + ".csv";\n\n            if (File.Exists(oldFileName))\n            {\n                File.Move(oldFileName, newFileName);\n            }                \n        }	0
12208429	12208302	How to select a node with a given attribute value in C#?	XElement doc = XElement.Load("yourStream.xml");\nXNamespace g = "http://www.nlog-project.org/schemas/NLog.xsd";//global namespace g\n\nforeach (var itm in doc.Descendants(g + "targets").Where(x=>x.Atrribute("name").Value=="syslog"))\n{\nitm;//your required node\n}	0
12777174	12661053	WCF add custom HTTP header into request	public class CustomFilter : MessageFilter\n{\n    private int minSize;\n    private int maxSize;\n    public CustomFilter()\n        : base()\n    {\n\n    }\n    public CustomFilter(string paramlist)\n        : base()\n    {\n        string[] sizes = paramlist.Split(new char[1] { ',' });\n        minSize = Convert.ToInt32(sizes[0]);\n        maxSize = Convert.ToInt32(sizes[1]);\n    }\n    public override bool Match(System.ServiceModel.Channels.Message message)\n    {\n        return true;\n    }\n    public override bool Match(MessageBuffer buffer)\n    {\n        return true;\n    }\n}	0
18728183	18728150	Windows Form Control with Children	foreach(Control control in panel.Controls)\n{\n    if(control is TextBox)\n    {\n         TextBox textBox = control as TextBox;\n         //etc.\n    }\n}	0
26813283	26808227	Copy text from row in GridEX	private void gridEXMon_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)\n        {\n            if (e.Row.RowIndex < 0)\n                return;\n\n            int BillID = Convert.ToInt32(e.Row.Cells["Cell1"].Value);\n            String BillID = Convert.ToString(e.Row.Cells["Cell2"].Value);\n            Decimal BillID = Convert.ToDecimal(e.Row.Cells["Cell3"].Value);\n            int BillID = Convert.ToInt32(e.Row.Cells["Cell4"].Value);\n\n            ReportInfo report = new ReportInfo();\n            // Here you need to pass the 4 cell values to your Pop up Dialog\n            report.ShowDialog();\n        }	0
150288	149823	Accessing a dynamitcally added buttoncolumn's (in a Datagrid) click event. C#/ASP.NET	protected void Page_Load(object sender, EventArgs e)\n{\n  DataGrid dg = new DataGrid();\n\n  dg.GridLines = GridLines.Both;\n\n  dg.Columns.Add(new ButtonColumn {\n    CommandName = "add",\n    HeaderText = "Event Details",\n    Text = "Details",\n    ButtonType = ButtonColumnType.PushButton\n  });\n\n  dg.DataSource = getDataTable();\n  dg.DataBind();\n\n  dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);\n\n  pnlMain.Controls.Add(dg);\n}\n\nprotected void dg_ItemCommand(object source, DataGridCommandEventArgs e)\n{\n  if (e.CommandName == "add")\n  {\n    throw new Exception("add it!");\n  }\n}\n\nprotected DataTable getDataTable()\n{\n  // returns your data table\n}	0
21632971	21632629	How to determine selected value in MVC dropdownlist based on web.config in more elegant way	List<SelectListItem> serverItems = new List<SelectListItem>();\n            serverItems.Add(new SelectListItem { Text = "P", Value = "P" });\n            serverItems.Add(new SelectListItem { Text = "A1", Value = "A1" });\n            serverItems.Add(new SelectListItem { Text = "A2", Value = "A2" });\n            serverItems.Add(new SelectListItem { Text = "T1", Value = "T1" });\n            serverItems.Add(new SelectListItem { Text = "T2", Value = "T2" });\n\n            string selectedValue = System.Configuration.ConfigurationManager.AppSettings["server:serverName"].ToString();\n\n            SelectListItem item = serverItems.Where(t => t.Value == selectedValue).SingleOrDefault();\n\n            if (item != null)\n            {\n                item.Selected = true;\n            }	0
9244450	9235718	converting linq to sql to stored procedure for bulk insert	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
21865887	21838673	Delete Chart Based On Location?	//...\n    using Office = Microsoft.Office.Core;\n    using Excel = Microsoft.Office.Interop.Excel;\n    using ios = System.Runtime.InteropServices;\n    //...\n\n    private void btnDeleteChart_Click(object sender, EventArgs e)\n    {\n        Excel.Application xl = GetExcel();\n        if (xl == null) return;\n\n        Excel.Workbook wb = xl.ActiveWorkbook;\n        Excel.Worksheet sht = wb.ActiveSheet;\n        Excel.Range rSrch = sht.Range["B4:D8"];\n\n        Excel.Range rShp;\n\n        foreach (Excel.Shape shp in sht.Shapes)\n        if (shp.Type ==  Office.MsoShapeType.msoChart)\n        {\n            rShp = shp.TopLeftCell;\n            if(xl.Intersect(rShp,rSrch)!=null)shp.Delete();\n        }\n    }\n\n    private Excel.Application GetExcel()\n    {\n        Excel.Application xl = \n          (Excel.Application)ios.Marshal.GetActiveObject("Excel.Application");\n        if (xl == null) MessageBox.Show("No Excel !!");\n        return xl; \n    }	0
4124668	4123613	Formating an integer as octal	System.Convert.ToString(15, 8)	0
19168552	19166605	margin of buttons in windows phone apps	// generate rows and columns\nfor (int i = 0; i < gridSize; i++)\n{\n    gridPanel.RowDefinitions.Add(new RowDefinition());\n    gridPanel.ColumnDefinitions.Add(new ColumnDefinition());\n}\n\nfor (int i = 0; i < gridSize; i++)\n{\n    for (int j = 0; j < gridSize; j++)\n    {\n        buttons[i, j] = new Button\n            {\n                Content = "0",\n                FontSize = 16,\n                Foreground = new SolidColorBrush(Colors.Transparent),\n                // all buttons have the same margin, no calculation needed\n                Margin = new Thickness(-12) \n            };\n        // placing in a row and column via attached properties\n        buttons[i, j].SetValue(Grid.RowProperty, i);\n        buttons[i, j].SetValue(Grid.ColumnProperty, j);\n        buttons[i, j].Click += new RoutedEventHandler(cell_Click);\n        opened[i, j] = false;\n        this.gridPanel.Children.Add(buttons[i, j]);\n    }\n}	0
2570234	2570222	How to retrieve a binary file from .NET assembly?	var assembly = Assembly.GetExecutingAssembly();\n\n// don't forget to do appropriate exception handling arund opening and writing file\nusing(Stream input = assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"))\nusing(Stream output = File.Open("output.xlsx"))\n{\n     input.CopyTo(output);\n}	0
15657889	15657039	Accessing nested DataGridview via Parent/ TabControl->TabPage	foreach (TabPage tbp in tbctrl.TabPages)\n        {\n            foreach (Control ctrl in tbp.Controls)\n            {\n                if (ctrl is DataGridView)\n                {\n                    DataGridView newDgv = (DataGridView)ctrl;\n                    string strValue = newDgv.Rows[0].Cells[0].Value.ToString();\n                }\n            }\n        }	0
22283755	22280682	Compile Assembly on the fly	var referenceAssemblies = new List<string> {\n        "System.dll",\n        "System.Data.dll",\n        "System.Xml.dll",\n        "System.Windows.Forms.dll" \n    };\n    var homedir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\n    var mshtml = Path.Combine(homedir, "Microsoft.mshtml.dll");\n    referenceAssemblies.Add(mshtml);\n\n    cp.ReferencedAssemblies.AddRange(referenceAssemblies.ToArray());	0
29314074	29313836	Convert Mac Address Generation from SQL to C#	var macAddress = String.Concat(1234567.ToString("X").PadLeft(6, '0'), int.Parse(nextMacAddressParameter.Value).ToString("X").PadLeft(6, '0'));	0
3348650	3348620	Using the Xbox 360 Controller in a WPF application	Microsoft.Xna.Framework.Input.GamePad	0
28744831	28744742	How can I ignore Excel cell value if text is struck through?	myworksheet.Cells[row, col].Font.Strikethrough;	0
34069769	34068831	How to create Excel file with EPPlus for A4 paper	ws.PrinterSettings.FitToPage = true;	0
19317088	19306654	Hide the verbosity of a component system and provide a more elegant interface to the user in a generic way	// Link to component of type B through a property.\n// The name doesn't matter.\n[ComponentLink]\nB B { get; set; }\n\n// Called when components are added or removed.\n// The parameter type acts as a filter.\n[NotifyComponentLinked]\nvoid Added(object o)\n{ Console.WriteLine(this.GetType().Name + " linked to " + o.GetType().Name + "."); }\n[NotifyComponentUnlinked]\nvoid Removed(object o)\n{ Console.WriteLine(this.GetType().Name + " unlinked from " + o.GetType().Name + "."); }\n\n// Attaches to events in compenents of type D and E.\n// Rewriting this with Lambda Expressions may be possible,\n// but probably would be less concise due to lack of generic attributes.\n//\n// It should be possible to validate them automatically somehow, though.\n[EventLink(typeof(D), "NumberEvent")]\n[EventLink(typeof(E), "NumberEvent")]\nvoid NumberEventHandler(int number)\n{ Console.WriteLine("Number received by F: " + number); }	0
28967050	28966271	can not remove item from a dropdownlist in datagrid c#	ListItem itemToRemove = cboSpaceCategory.Items.FindByText("Practices Wanted to Buy");\ncboSpaceCategory.Items.Remove(itemToRemove);	0
19380320	19380279	Changing datagridview cell color based on condition	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    foreach (DataGridViewRow Myrow in dataGridView1.Rows) \n    {            //Here 2 cell is target value and 1 cell is Volume\n        if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition \n        {\n            Myrow .DefaultCellStyle.BackColor = Color.Red; \n        }\n        else\n        {\n            Myrow .DefaultCellStyle.BackColor = Color.Green; \n        }\n    }\n}	0
20002828	19991816	How to set file version for an Interop DLL generated using ilasm	ilasm.exe Interop.filename.il /dll /key=snkey.snk /resource:Interop.filename.res	0
23446763	23433347	deleting rows from datatabe causes error	// 1. Find the Unique itemIDs to remove\nvar idsToRemove = emails.Select("failEmail = 'fail'").Select (x => x["itemID"]).Distinct();\n// 2. Find all the rows that match the itemIDs found\nvar rowsToRemove = emails.Select(string.Format("itemID in ({0})", string.Join(", ", idsToRemove)));\n// 3. Remove the found rows.\nforeach(var rowToRemove in rowsToRemove)\n{\n    emails.Rows.Remove(rowToRemove);\n}\nemails.AcceptChanges();	0
24389276	24389186	Cant add data to Gridview	protected void Page_Load(object sender, EventArgs e)\n    {\n    if(!IsPostBack)\n    {\n        BindData();\n    }\n    }	0
10219117	10215144	Hide Area in URL using AttributeRouting	[RouteArea("AreaName", AreaUrl = "")]	0
27211993	27211960	How to know the center of a bidimensional array	int size = 3;\nint[,] array = new int[size, size];\n\nint centerValue = array[size / 2, size / 2];	0
30283614	30283537	How to sort list<string> in c#	List<string> a = new List<string> { "1234-273-3456", "45656-345-5466", "4234-333-3422", "6466-656-5654" };\n\n//backup of main list\nList<string> b = new List<string>(a);\n\n//sorting a list\na.Sort();	0
25000376	24999966	How can i search in a treeView1 for words/strings in items using textBox1?	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        foreach (TreeNode tn in treeView1.Nodes)\n        {\n            Call(tn); \n        }\n    }\n\n    private void Call(TreeNode treeNode)\n    {\n        if (treeNode.Text == textBox1.Text)\n        {\n            treeNode.BackColor = Color.Red;\n        }\n        else\n        {\n            treeNode.BackColor = Color.White;\n        }\n        foreach (TreeNode tn in treeNode.Nodes)\n        {\n            Call(tn);\n        }\n    }	0
3549473	3548852	How can I get a list of tables in a SQL Server database along with the primary key using ONLY C#?	using Microsoft.SqlServer.Management.Common;\nusing Microsoft.SqlServer.Management.Smo;\n\npublic class LoadStuff\n{\n    string mDatabaseConnectionString = "Something";\n    ...\n    public void LoadDatabase(string tDatabaseName)\n    {\n        using (var vSqlConnection = new SqlConnection(mDatabaseConnectionString))\n        {\n            var vConnection = new ServerConnection(vSqlConnection);\n            var vServer = new Server(vConnection);\n            var vDatabase = vServer.Databases[tDatabaseName];\n            var vTables = vDatabase.Tables;\n        }\n    }\n}	0
27593789	27593494	Storing MySQL Connection String in Variables from User Input then Building String [C#]	private void btnStoreCon_Click(object sender, EventArgs e)\n    {\n        dbConStr.strServer = "Server=" + txtServer.Text + ";";\n        dbConStr.strPort = "Port=" + txtPort.Text + ";";\n        dbConStr.strDatabase = "Database=" + txtDatabase.Text + ";";\n        dbConStr.strUid = "Uid=" + txtUsername.Text + ";";\n        dbConStr.strPwd = "Pwd=" + txtPassword.Text + ";";\n\n        dbConStr.strConnect = dbConStr.strServer + dbConStr.strPort + dbConStr.strDatabase + dbConStr.strUid + dbConStr.strPwd;\n    }	0
7418072	7417702	populate LINQ to XML to Grdiview	IEnumerable<XElement> matches = \n               from Doctor in doc.Descendants("Doctor") \n               where (int)Doctor.Attribute("ID") > 1 \n               select new {\n                              Specialist = Doctor.Attribute("Specialist").Value,\n                              ID = Doctor.Attribute("ID").Value,\n                              Username = Doctor.Element("Username").Value,\n                              Password = Doctor.Element("Password").Value\n                };\n\nGridView1.DataSource = matches;\nGridView1.DataBind();	0
1438077	1438045	C# Best way to convert string date format to another string?	string newFormat = DateTime.ParseExact(theDate, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'/'MM'/'dd")	0
25521266	25516638	How to assign values base class properties inside a derived class object without listing them one by one?	public EmployeeFormatted(Employee em)\n        {\n            var emProps = em.GetType().GetProperties();\n            foreach (var prop in emProps)\n            {\n                this.GetType().GetProperty(prop.Name).SetValue(this,prop.GetValue(em));\n            }\n            this.FullName = FomratName(em.FirstName, em.LastName);\n        }	0
2635907	2628799	Get input from user with ActivityBuilder in WF 4	static ActivityBuilder CreateTask1()\n    {\n        Dictionary<string, object> properties = new Dictionary<string, object>();\n        properties.Add("User_Name", new InArgument<string>());\n\n        var res = new ActivityBuilder();\n\n        res.Name = "Task1";\n\n        foreach (var item in properties)\n        {\n            res.Properties.Add(new DynamicActivityProperty { Name = item.Key, Type = item.Value.GetType(), Value = item.Value });\n        }\n\n        Sequence c = new Sequence();\n\n        c.Activities.Add(new WriteLine { Text = new VisualBasicValue<string> { ExpressionText = "\"Hello \" + User_Name" } });\n\n        res.Implementation = c;\n\n        return res;\n    }	0
5957225	5957077	Local constant initialised to null reference	#IF (SILVELIGHT)\n    public const string DefaultName = null;\n#ELSE\n    public const string DefaultName = "Win7";\n#ENDIF	0
7151588	7151451	LINQ to SQL lambda where [nullable object must have a value error]	DateTime? datevalue = context.Datas == null\n    ? null\n    : (DateTime?)context.Datas.Where(x => x.UserId != null && x.UserID.Equals(userId))\n                              .Min(x => x.Time);	0
15093633	15092906	Serialize a PropertyGrid (SerializeToXML) failed	private void btnSave_Click(object sender, EventArgs e)\n{\n    var MyBooks = myProertyGrid.SelectedObject as MyBookCollection;\n    SerializeToXML(MyBooks);\n}	0
18260718	18260259	combobox focus on beginning of text after selection	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n  this.BeginInvoke(new Action(() => { comboBox1.Select(0, 0); }));\n}	0
9572206	9572005	How can I map a relative path outside of the controller?	AppDomain.CurrentDomain.DynamicDirectory	0
5721697	5721577	Change value to a global variable and take it value in other class	public class Foo\n{\n    public int FileCounter;\n\n    public void SomeMethod()\n    {\n        FileCounter++;\n    }\n}\n\npublic class Bar\n{\n    public void SomeMethod()\n    {\n        var foo = new Foo();\n        foo.SomeMethod();\n\n        Debug.WriteLine( string.Format("FileCounter: {0}", foo.FileCounter ) );\n    }\n}	0
12610152	12609913	filtering dataset on multiple ACCESS databases to optimize results	string query2 = select columnZ, columnX from XYZTable where columnY = 'test' ;;\n\nDictionary<string, string> table2Dict = new Dictionary<string, string>();\n\ntable2Dict.add(columnZ, columnX);\n\ncolZvalue = table2Dict[checkValuepassed];	0
31863904	31858886	how to bind data to the dropdownlist on selected value of the other dropdownlist in asp.net?? I have already bind data to the all the dropdown	BindListA()\n    ... read the data for A and bind to dropdown A\n    ... call BindListB(list A *default* value (first value?))\n\nBindListB(A value)\n    ... using the A value passed to this function\n    ... read the data for B and bind this to dropdown B\n    ... call BindListC(list B *default* value (first value?))\n\nBindListC(B value)\n    ... using the B value passed to this function\n    ... read the data for C and bind to dropdown C\n\nOn page_load event\n    if it is not a postback\n        call BindListA()\n\nOn ListA_selectedIndexChanged event\n    call BindListB(ListA selected Value)\n\nOn ListB_selectedIndexChanged event\n    call BindListC(ListB selected value)\n\nOn ListC_selectedIndexChanged event\n    do whatever it is you want to do with the user's selection off list C	0
17837307	17836725	How I send a data from child form to parent MDI form or parent MDI from to child form in C#?	public partial class Form1 : Form\n{\n\n  public void RegisterSon()\n  {\n     ChildForm frm = new ChildForm();\n     frm.MyEventChild += new MyEvntHndler(frm_MyEventChild);\n  }\n\n  void frm_MyEventChild(string data)\n  {\n\n  }\n}\n\npublic delegate void MyEvntHndler(string data);\n\npublic class ChildForm: Form\n{\n  public event MyEvntHndler MyEventChild;\n\n  private void button1_Clicked(object sender, EventArgs e)\n  {\n     if (MyEventChild != null)\n     {\n        MyEventChild("This is my data");\n     }\n  }\n}	0
30541157	30535798	Foreach bind items to Datatable with C# and JSON	for (int i = 0; i < jsonItemData.Count; i++) {\n          DataRow dtRow = dtInventory.NewRow();\n          dtRow["ItemID"] = sItemID.ToString();\n          dtRow["ItemImageUrl"] = jsonItemData[sItemID]["icon_url"].ToString();\n          dtRow["ItemName"] = jsonItemData[sItemID]["market_name"].ToString();\n          dtRow["Tradeable"] = jsonItemData[sItemID]["tradable"].ToString();\n\n          dtInventory.Rows.Add(dtRow); //this line adds the row to the table\n}	0
17337987	17337658	How to Poweroff /suspend WinCE 6 device from C#	[Flags]\npublic enum ExitFlags\n{\n  Reboot = 0x02,\n  PowerOff = 0x08\n}\n\n[DllImport("coredll")]\npublic static extern int ExitWindowsEx(ExitFlags flags, int reserved);\n\n...\n\nExitWindowsEx(ExitFlags.PowerOff, 0);	0
7713005	7712873	How do I link/point to specific objects in C#?	Public class pixel\n{\n    int x, y;\n    int NumberOfNeighbours;\n    int ConnectivityNumber;\n    int ClusterNumber;\n\n    //neighbors:\n    Pixel _neighborN;\n    Pixel _neighborNE;\n    ...\n    Pixel _neighborNW;\n}	0
3779958	3779241	Silverlight (like) Validation in Windows Form app	protected virtual void MyTextBox_OnValidating(CancelEventArgs e)\n{\n     this.SaveButton.Enabled = (Validate(MyTextBox));\n}	0
11798669	11798281	Deserialize boolean element with string attribute	[XmlText]\npublic bool ServiceValue {get;set;}	0
1078941	1073277	PDFsharp save to MemoryStream	MigraDoc.DocumentObjectModel.Document doc = new MigraDoc.DocumentObjectModel.Document();\nMigraDoc.Rendering.DocumentRenderer renderer = new DocumentRenderer(doc);\nMigraDoc.Rendering.PdfDocumentRenderer pdfRenderer = new MigraDoc.Rendering.PdfDocumentRenderer();\npdfRenderer.PdfDocument = pDoc;\npdfRenderer.DocumentRenderer = renderer;\nusing (MemoryStream ms = new MemoryStream())\n{\n  pdfRenderer.Save(ms, false);\n  byte[] buffer = new byte[ms.Length];\n  ms.Seek(0, SeekOrigin.Begin);\n  ms.Flush();\n  ms.Read(buffer, 0, (int)ms.Length);\n}	0
2258787	2258775	How to convert DateTime value C# into something like 31st January 2009 but in Polish Language?	CultureInfo polish = new CultureInfo("pl-PL");  // I *think* this is Polish -- you might need to check!\nDateTime.Now.ToString("d MMMM yyyy", polish);	0
3836850	3836644	C# Convert Relative to Absolute Links in HTML String	var baseUri = new Uri("http://test.com");\nvar pattern = @"(?<name>src|href)=""(?<value>/[^""]*)""";\nvar matchEvaluator = new MatchEvaluator(\n    match =>\n    {\n        var value = match.Groups["value"].Value;\n        Uri uri;\n\n        if (Uri.TryCreate(baseUri, value, out uri))\n        {\n            var name = match.Groups["name"].Value;\n            return string.Format("{0}=\"{1}\"", name, uri.AbsoluteUri);\n        }\n\n        return null;\n    });\nvar adjustedHtml = Regex.Replace(originalHtml, pattern, matchEvaluator);	0
14626184	14625865	How to write a database query in asp.net mvc3 to get a record?	using(YourEntityname context=new YourEntityname())\n{\n     var val=context.Users.Where(p=>p.EmpName==name).Select(u=>u.Designation);\n}	0
1690431	1690369	Get program title from process name in C#	var info = Process.GetProcessesByName("devenv").FirstOrDefault();\n\n        if (info != null)\n        {\n            Console.WriteLine(info.MainModule.FileVersionInfo.ProductName);\n            Console.WriteLine(info.MainModule.FileVersionInfo.FileDescription);\n        }	0
9577983	9577804	Highlight the selected row in data list	protected void DataList1_ItemDataBound(object sender, \n                             DataListItemEventArgs e) \n{\n     if (e.Item.ItemType == ListItemType.Item || \n         e.Item.ItemType == ListItemType.AlternatingItem)\n     { \n         //Add eventhandlers for highlighting \n         //a DataListItem when the mouse hovers over it.\n         e.Item.Attributes.Add("onmouseover", \n                "this.oldClass = this.className;" + \n                " this.className = 'EntryLineHover'"); \n         e.Item.Attributes.Add("onmouseout", \n                "this.className = this.oldClass;");\n         //Add eventhandler for simulating \n         //a click on the 'SelectButton'\n         e.Item.Attributes.Add("onclick", \n                this.Page.ClientScript.GetPostBackEventReference(\n                e.Item.Controls[1], string.Empty));\n     }\n}	0
73007	72913	Is it possible to advance an enumerator and get its value in a lambda?	e => e.MoveNext() ? e.Current : null	0
6928617	6928600	Convert object to int in Linq Where clause	_dttMasterViewTransaction.AsEnumerable().Where(r => (int)r["JEID"] == FundsID)	0
24350134	24349966	How can a WCF Service obtain Query Parameters?	[ServiceContract]\npublic interface IService\n{\n    [WebGet(UriTemplate = "callback?code={requestCode}")]\n    void OAuthCallback(string requestCode);\n}	0
20786133	20785932	how to show values on Index, returned by Json request?	var mera_obj = result.key;\n alert("data is : "+mera_obj[0].ayah);	0
23417945	23417877	How to automatic add the first line of text from a list box to a text box	presentlyPlayingTextBox.Text = playlistListBox.SelectedItem.ToString();	0
13693576	13693520	How to evaluate Enum in an If statement?	public enum AppInstallType { msi, exe }\n\npublic class Application\n{\n    //Properties\n    public string AppID { get; set; }\n    public string AppName { get; set; }\n    public string AppVer { get; set; }\n    public string AppInstallArgs { get; set; }\n    public AppInstallType InstallType;\n    public string AppInstallerLocation { get; set; }\n}\n\nif(InstallType == AppInstallType.msi)	0
5413895	5413836	Visual Studio 2008 - Getting Data from Column of DataGridView in Selected Row	object firstColumnValue=dgCustomers.CurrentCell.Cells[0].Value;	0
3444404	3444246	Convert Action<T> to Action<object>	public Action<object> Convert<T>(Action<T> myActionT)\n{\n    if (myActionT == null) return null;\n    else return new Action<object>(o => myActionT((T)o));\n}	0
34332203	34332081	using substring and foreach in a lambda expression	var parser = new Regex(@"\bTest", RegexOptions.Compiled);\nGetNames().Where(x => parser.IsMatch(x.Value)).ToDictionary(x => x.Key, y => y.Value)	0
2733950	2733923	How to get List of results from list of ID values with LINQ to SQL?	public List<MyType> GetMyTypes(List<int> ids)\n{\nreturn (from myType in db.MyTypes\n        where ids.Contains(myType.Id)\n        select new MyType\n        {\n            MyValue = myType.MyValue\n        }).ToList();\n}	0
9861173	9861164	Only assignment, call, increment, decrement, and new object expressions can be used as a statement	string remarks = AddDgvNew[6, i].Value==null?"":AddDgvNew[6,i].Value.ToString();	0
24002592	23867849	File copy only x file extension	fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);\n\n                total += (int)fi.Length;\n\n                copied += (int)fi.Length;\n                copied /= 1024;\n                progressBar1.Step = copied;\n\n                progressBar1.PerformStep();\n                label1.Text = (total / 1048576).ToString() + "MB van de " + (maxbytes / 1024).ToString() + "MB gekopie??rd";\n\n                label1.Refresh();\n            }	0
8618513	8400691	Displaying associated table using LINQ	protected void btn5_Click(object sender, EventArgs e)\n{ \n    using (EStoreEntities ctx5 = new EStoreEntities())\n    {\n        var query = ctx5.Order_Details.Select(x => new { \n                                                      Col1 = x.AAA,\n                                                      Col2 = x.BBB,\n                                                      Col3 = x.Order.AAA\n                                                   });\n\n        tb5.Text = (query as ObjectQuery).ToTraceString();\n        gv5.DataSource = query;\n        gv5.DataBind();\n    }\n}	0
2081285	2080634	Listbox Notification message	public partial class Form1 : Form {\n    public Form1() {\n      InitializeComponent();\n      listBox1.SelectionMode = SelectionMode.MultiSimple;\n      listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);\n    }\n\n    void listBox1_SelectedIndexChanged(object sender, EventArgs e) {\n      for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; --ix) {\n        int index = listBox1.SelectedIndices[ix];\n        if (index % 2 != 0) listBox1.SelectedIndices.Remove(index);\n      }\n    }\n  }	0
2700464	2699385	How to wait for an event to be triggered in silverlight test	var done = false;\nvar viewModel = new ProjectListViewModel(eventAggregatorMock.Object, moduleManagerMock.Object);\n\nObservable\n   .FromEvent<EventArgs>(viewModel, "ModelLoaded"))\n   .Take(1)\n   .Subscribe(viewModel => \n       {\n           Assert.IsNotNull(viewModel.Model);\n           Assert.AreEqual(4, viewModel.Model.Count);\n           done = true;\n       });\n\nEnqueueConditional(() => done);\nEnqueueTestComplete();	0
12931586	12931197	How to loop through dropdown items in a toolstrip	foreach (var items in catDrpDwn.DropDown.Items)\n        {\n            var it = (LibraryItems)items;\n            if (it.Checked == true)\n            {\n\n            }\n        }	0
16991177	16991092	How to resolve warning: TKey has the same name as the type paramater from outer type	class ObservableDictionary<TKey,TValue>\n{\n     // This class already knows about TKey and TValue since it's an inner class in the "outer" generic class\n     protected class KeyedDictionaryEntryCollection : KeyedCollection<TKey, DictionaryEntry> \n     {\n        // Your existing code, as is...\n     }\n}	0
17867468	17867375	StreamReader is repeating same string	Program that reads all lines: C#\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\n\nclass Program\n{\n    static void Main()\n    {\n    //\n    // Read in a file line-by-line, and store it all in a List.\n    //\n    List<string> list = new List<string>();\n    using (StreamReader reader = new StreamReader("file.txt"))\n    {\n        string line;\n        while ((line = reader.ReadLine()) != null)\n        {\n        list.Add(line); // Add to list.\n        Console.WriteLine(line); // Write to console.\n        }\n    }\n    }\n}\n\nOutput\n\nFirst line of your file.txt file.\nSecond line.\nThird line.\nLast line.	0
33284066	33282534	Serializing collections only one level deep with Entity Framework	return Context.Things.Select(s => s).Include(s => s.OtherThings);	0
23381963	23380268	Normal of a 3-dimensional wave	public Vector3 normalAt (float x, float z)\n{\n    float argument = Time.realtimeSinceStartup + x * frequency * transform.forward.x + z * frequency * transform.forward.z;\n    float nx = amplitude * frequency * transform.forward.x * Mathf.Cos(argument);\n    float ny = -1.0f;\n    float nz = amplitude * frequency * transform.forward.z * Mathf.Cos(argument);\n    return new Vector3(nx, ny, nz).normalized; // Not sure about sign. Maybe you need to multiply the result by -1.\n}	0
4126166	4114110	Proper Join/GroupJoin implementation	var records = source\n              .GroupJoin(myContext.TableB,\n              info => info.CustomerID,\n              owner => owner.CustomerID,\n              (info, owner) => new\n              {\n                  info,\n                  Owner = owner.Select(o => o.LastName).First()\n              })\n              .Select(record => new\n              {\n                  record.info.CustomerID,\n                  record.Owner,\n                  record.info.Store\n              });	0
31330702	31330612	How replace unique string include some characters Before with an increment Number	int count = 0;\nvar result = Regex.Replace(\n               text, \n               @"\d\d\d\d(__Same_String__)", \n               m => (++count).ToString().PadLeft(4, (char)(count + '0')) + m.Groups[1].Value);	0
18131943	18130706	How can i disable a button using a System.Timers.Timer in monodroid?	protected void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n {\n    try{\n       t.Stop();\n       MainActivity.RunOnUiThread(() => { button.Enabled = false; });\n    catch(){\n       Console.WriteLine("Exception: "+ex);       \n    }\n }	0
2883529	2883493	C# LINQ join With Just One Row	var row = (from b in TableB\n        join a in TableA on a.AId equals b.AId\n        where a.AValue = yourValue).Single();	0
1376993	1374584	Strangeness with clipboard access	//Store the old clipboard data\nIDataObject clipboardData = Clipboard.GetDataObject();\n\nClipboard.SetText("Hello world!");\n\nstring value = Clipboard.GetText();\nConsole.WriteLine(value);\n\n//Clear the clipboard again and restore old data\nClipboard.Clear();\nClipboard.SetDataObject(clipboardData);\n\nConsole.ReadLine();	0
12150339	12150298	c# Lambda expression for next and previous dates	var previous date = top10Date.Where(d => d.Date > latestDate.Date).OrderBy(d => d.Date).FirstOrDefault();	0
5315122	5315035	how do I select something from a table and output to a label?	while (reader.Read())\n{\n      Name.Text = (reader[0].ToString());\n}	0
12986711	12986666	C# How to start from line 0 in richtextbox with loop	foreach (string s in splitarray)\n{\n  if(Richtextbox1.Text.Trim() == string.Empty)//Checking for first Array Item\n  {\n   Richtextbox1.Text =  s;\n  }\n  else\n  {\n   Richtextbox1.Text = Richtextbox1.Text + s;\n  }\n}	0
29263580	29263474	How to use switch case in C#	string message = string.Empty;\n           switch (userId)\n           {\n               case -1:\n                   errLbl.Text = "The current temporary password you entered is invalid.\\nPlease re-enter your current temporary password.";\n                   break;\n               case -2:\n                   errLbl.Text = "Username already exists. Please choose a different username";\n                   break;\n               default:\n                   message = "You have successfully created your account.  You will now be redirected to the Login page.  Thanks.";\n           string url = "Login";\n           string script = "window.onload = function(){ alert('";\n           script += message;\n           script += "');";\n           script += "window.location = '";\n           script += url;\n           script += "'; }";\n           ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);\n\n                   break;\n           }	0
30748979	30748883	Convert time string to DateTime	string date = "2015-06-10";\n    string time = " 12:20pm";\n    DateTime combinedResult = DateTime.Parse(date + time);\n    Console.WriteLine(combinedResult.ToString());	0
20285873	20280604	Add unique ID to a session	public string generateID()\n{\n    return Guid.NewGuid().ToString("N");\n}	0
13087453	13086456	Register double clicks on a row in a list view	Binding="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=DataContext.YourCommandName}"	0
9966722	9966620	Modifying a point, UnboundNameException	PythonEngine.Execute("QWE.X = 0", scope);	0
21334619	21334425	C# Reading, Storing, and Combining Arrays	byte [] ComboByte = {iHex, FirstFour[0], FirstFour[1], FirstFour[2], First Four[3]};	0
1342499	1168955	Reposity pattern using linq	// C# sample\nnamespace MyCompany.MyApp.Entities.Oracle\n{\n    public class MyClass\n    {\n    // ...\n    }\n}\n\nnamespace MyCompany.MyApp.Entities.SqlServer\n{\n    public class MyClass\n    {\n    // ...\n    }\n}	0
12840517	12837276	Implementing a tick/round based combat system	class CombatEventList\n{\n   public static AddEvent(CombatEvent event, int ticksTillHappens)   \n}\n\nvirtual class CombatEvent\n{\n    public virtual void CombatAction()\n}\n\nclass PlayerActionChoice : ComabtEvent\n{\n   public void CombatAction\n   {\n       var playerAction = GetUserDecision();//returns i.e CombatEvent PlayerMeeleAttack\n       CombatEventList.AddEvent(playerAction, 0);\n   }\n}\n\nclass PlayerMeeleAttack : CombatEvent\n{\n   int cooldownInTicks = 50;\n\n   public void CombatAction\n   {\n       MakeAttack()//damages the moster etc - all the stuff the attack is supposed to do\n       var nextEvent = new PlayerActionChoice();\n       CombatEventList.AddEvent(nextEvent, cooldownInTicks);\n   }\n}	0
17666305	17665961	How to speed up search in a huge dictionary	var dic = new Dictionary<string, string>();\ndic.Add("910235487", "Diabetes, tumors, sugar sick");\ndic.Add("120391052", "Fever, diabetes");\n\nchar[] delimiters = new char[] { ' ', ',' };\n\nvar wordCodes =\n    from kvp in dic\n    from word in kvp.Value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)\n    let code = long.Parse(kvp.Key)\n    select new { Word = word, Code = code };\n\nvar fullTextIndex =\n    wordCodes.ToLookup(wc => wc.Word, wc => wc.Code, StringComparer.OrdinalIgnoreCase);\n\nlong[] test1 = fullTextIndex["sugar"].ToArray();       // Gives 910235487\nlong[] test2 = fullTextIndex["diabetes"].ToArray();    // Gives 910235487, 120391052	0
20404961	20404854	Get DEP Setting	public enum DepSystemPolicyType\n{\n    AlwaysOff = 0,\n    AlwaysOn,\n    OptIn,\n    OptOut\n}\n\n[DllImport("kernel32.dll")]\nstatic extern int GetSystemDEPPolicy();\n\npublic static void ValidateDepPolicy()\n{\n    int policy = GetSystemDEPPolicy();\n    //here you can evaluate the return value\n    //against the enum DepSystemPolicyType\n}	0
14745921	14745852	How I can send a mail with PDF File	var filename = @"c:\test.pdf";\nm.Attachments.Add(new Attachment(filename));	0
2008434	2008365	splitting multiple paths in string	string testString = @"SYNC C:\Users\Fox Mulder\SyncClient C:\Users\Fox Mulder\SyncServer";\n\nint firstIndex = testString.IndexOf(Path.VolumeSeparatorChar);\nint secondIndex = testString.LastIndexOf(Path.VolumeSeparatorChar);\nstring path1, path2;\n\nif (firstIndex != secondIndex  && firstIndex != -1)\n{\n    path1 = testString.Substring(firstIndex - 1, secondIndex - firstIndex);\n    path2 = testString.Substring(secondIndex - 1);\n\n    Console.WriteLine("Path 1 = " + path1);\n    Console.WriteLine("Path 2 = " + path2);\n}	0
14345238	14345092	Need to ping remote server programmatically and store output of telnet	ProcessStartInfo info = new ProcessStartInfo();\ninfo.Arguments = "/c ping 203.189.91.127";\ninfo.CreateNoWindow = true;\ninfo.FileName = "cmd.exe";\ninfo.RedirectStandardOutput = true;\ninfo.UseShellExecute = false;\ninfo.WindowStyle = ProcessWindowStyle.Hidden;\n\nProcess process = new Process();\nprocess.StartInfo = info;\nprocess.Start();\n\nString result;\n\ntry\n{\n    while ((result = process.StandardOutput.ReadLine()) != null)\n    {\n        Console.WriteLine(result);\n    }\n}\ncatch { }	0
645971	645962	How can I change components of a form from within another object?	// untested code\nclass MyObjectClass\n{\n   public delegate void Reportback(int percentage);\n\n   public void DoSomething(Reportback callBack) { ...; callback(i*100F/total); ...}\n}\n\n\nclass Form1: Form\n{\n   private void reportProgress(int percent) { ...; progressbar1.value = percent; }\n\n   void SomeMethod() {  myObject1.DoSomething(reportprogress); }\n}	0
9984562	9984463	How to bind List Data to combobox	void client_GetLocationCompleted(object sender, GetLocationCompletedEventArgs e)\n{\n    LocationCombo.SelectedValuePath = "Lid";\n    LocationCombo.DisplayMemberPath = "Lname";\n    LocationCombo.ItemsSource = e.Result;\n}	0
16723484	16703418	Convert Generic List of objects to SqlXml	MemoryStream memoryStream = new MemoryStream();\nXmlSerializer xs = new XmlSerializer(typeof(TypeOfObjectToBeConverted));\nXmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);\nxs.Serialize(xmlTextWriter, objectToBeConverted);\nmemoryStream = (MemoryStream)xmlTextWriter.BaseStream;\nmemoryStream.Position = 0;\nSystem.Data.SqlTypes.SqlXml obj = new System.Data.SqlTypes.SqlXml(memoryStream);	0
336863	336731	How can I create a view in a SQL Server database with C#?	SqlConnection conn = null;\nconn = new SqlConnection("yourConnectionString");\nconn.Open();\nstring strSQLCommand = "CREATE VIEW vw_YourView AS SELECT YOurColumn FROM YourTable";\nSqlCommand command = new SqlCommand(strSQLCommand, conn); \nstring returnvalue = (string)command.ExecuteScalar(); \nconn.Close();	0
13698513	13698484	Get list of database servers with C#	DataTable dt = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();	0
1015657	1015646	How do I break a loop at a certain point when debugging?	if (i == 1000){\n  int a = 1;\n}	0
11456770	11456391	for loop date don't want to include current date	IList<DateTime> exclusionDates = new List<DateTime>();\n\nwhile (drDates.read())\n{\n    exclusionDates.Add(Convert.ToDateTime(drDates["reportDate"].ToString()));\n}\n\nfor (DateTime dateTime = startDate; dateTime < endDate; dateTime += TimeSpan.FromDays(interval))\n{\n    if (!exclusionDates.Contains(dateTime))\n    {\n        this.Label1.Text += dateTime.ToString() + "</br>";\n    }\n}	0
32203534	32203189	C#, How to simply change order of class members	var x = new { Z = "", Y = 1, X = true };\nConsole.WriteLine(x.GetType().GetProperties().Select(y => y.Name));	0
33819726	33819651	C# sort a dictionary by value	List<KeyValuePair<string, string>> BillsList = aDictionary.ToList();\n\nBillsList.Sort(delegate(KeyValuePair<string, string> firstPair,\n    KeyValuePair<string, string> nextPair)\n    {\n        return firstPair.Value.CompareTo(nextPair.Value);\n    }\n);	0
11219946	11204461	download zip files by use of reader in c#	WebRequest objRequest = System.Net.HttpWebRequest.Create(url);\nobjResponse = objRequest.GetResponse();\nbyte[] buffer = new byte[32768];\nusing (Stream input = objResponse.GetResponseStream())\n{\nusing (FileStream output = new FileStream ("test.doc",\nFileMode.CreateNew))\n{\nint bytesRead;\n\nwhile ( (bytesRead=input.Read (buffer, 0, buffer.Length)) > 0)\n{\noutput.Write(buffer, 0, bytesRead);\n}\n}\n}	0
27183837	27179756	page break before last row table Office Interop	tempRow.AllowBreakAcrossPages = 0;	0
4873773	4873728	What are the best practices for doing a task after a certain time interval?	System.Windows.Forms.Timer tmrWindowsFormsTimer = new  System.Windows.Forms.Timer();\ntmrWindowsFormsTimer.Interval = TimeSpan.FromMinutes(1);\ntmrWindowsFormsTimer.Tick += new EventHandler(tmrWindowsFormsTimer_Tick);\ntmrWindowsFormsTimer.Start();\n\n\nprivate void tmrWindowsFormsTimer_Tick(object sender, System.EventArgs e) {\n  tmrWindowsFormsTimer.Stop();\n  DoAutoSaveAllControls();\n}	0
9695848	9695847	Is there a work around to cast an object from a DataKeyArray to a String in ASP.Net?	GridView1.DataKeys[Index].Value	0
2057619	2057534	Using Multiple Data Readers	string sql_Phone = "SELECT Phone_Number FROM Contact_Details WHERE Emp_ID = @EmpID";\nusing (SqlConnection cn2 = new Sqlconnection(databaseConnectionString))\nusing (SqlCommand cmd_Phone = new SqlCommand(sql_Phone, cn2))\n{\n    cmd_Phone.Parameters.Add("@EmpID", SqlDbType.Int);\n    cn2.Open();\n\n    while (dr_SignUp.Read())\n    {\n        List<string> arrPhone = new List<string>();\n        cmd_Phone.Parameters[0].Value = dr_SignUp["Emp_ID"];\n\n        using (SqlDataReader dr_Phone = cmd_Phone.ExecuteReader())\n        {\n            while (dr_Phone.Read())\n            {\n                arrPhone.Add(dr_Phone["Phone_Number"].ToString());\n            }\n        }	0
19218291	18507471	how can i use Messagebox.Show in async method on Windows Phone 8?	Dispatcher.BeginInvoke(delegate(){messagebox.show("your stuff");});	0
34484477	34483874	Apply sobel filter for edge detection in emgucv	Image<Gray, byte> gray = new Image<Gray, byte>(@"C:\Users\Public\Pictures\Sample Pictures\1.jpg");\n            Image<Gray, float> sobel = gray.Sobel(0, 1, 3).Add(gray.Sobel(1, 0, 3)).AbsDiff(new Gray(0.0));\n            pictureBox1.Image = sobel.ToBitmap();	0
1364756	836457	Silverlight 3 - Accessing TreeView Item's parent object	private void OrgTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)\n{\n    if (e.NewValue != null)\n    {\n        var parent = ((TreeView)sender).GetParentItem(e.NewValue);\n        if (parent != null)\n        {\n            Status.Text = "Parent is " + parent.ToString();\n        }\n    };\n}	0
8514371	8514294	How can I return a primitive from a method with a generic return type?	(T)(object)	0
7380841	7380780	Pressing right arrow causes up arrow to be set	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n    if (keyData == ((Keys)(Keys.Shift | Keys.Up)))\n        MessageBox.Show("Up arrow");\n    else if (keyData == Keys.Right)\n        MessageBox.Show("Right arrow");\n\n    // it doesn't matter what I return, the glitch happens anyway\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
23838588	18755975	Take parameter of a method into custom action filter MVC3 asp	public class NotificationFilter : ActionFilterAttribute\n{\n    public int _id;\n    public string _proccess;\n    public Guid _uid; \n\n    public NotificationFilter(int id,string proccess)\n    {\n        _id= id;\n        _proccess = proccess;\n    }\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n         var val = filterContext.ActionParameters["uid"];\n\n        _uid = (Guid)val;\n    }\n\n    public override void OnActionExecuted(ActionExecutedContext filterContext)\n    {\n         var uid = _uid;\n\n         dosomething(id,name,uid)\n    }\n}	0
9782045	9781796	Code for reading an XML file into a DataTable	DataSet ds = new DataSet();\n        ds.ReadXml(fileNameWithAbsolutePath);\n        return ds.Tables[0];	0
7189072	7188566	Sending Ctrl+Z to a serial port	(char)26	0
8076756	8076685	EF: how do i model 1:1 without db referential integrity?	--------------------------\n| Base ID | Extension ID |\n--------------------------	0
2757828	2756652	Getting path of the file that saved on Sharepoint Document library	public override void ItemAdded(SPItemEventProperties pobjSPItemEventProperties)\n{         \n    using (SPWeb objSPWeb = pobjSPItemEventProperties.OpenWeb())\n    {\n        string strFileUrl = pobjSPItemEventProperties.ListItem.File.Url;\n        //save to DB here\n    }\n}	0
2683856	2683791	Custom iterator for dictionary?	var myFilteredCollection = myCollection.Where( x => x.AmIIncludedInTheIteration );\n\nforeach (var x in myFilteredCollection ) ...	0
8055368	8055055	Get actual return type from a Expression<Func<T, object>> instance	public static Type GetObjectType<T>(Expression<Func<T, object>> expr)\n{\n    if ((expr.Body.NodeType == ExpressionType.Convert) ||\n        (expr.Body.NodeType == ExpressionType.ConvertChecked))\n    {\n        var unary = expr.Body as UnaryExpression;\n        if (unary != null)\n            return unary.Operand.Type;\n    }\n    return expr.Body.Type;\n}	0
16179214	16178905	Set up bool value	// Property\npublic bool Option1 { get; set; }\n\n// Below is inside Main, or a method\n// Set Option to true, for value to retrieve\nOption1 = true;\n// List of values\nList<string> MyList = new List<string>() { "1", "2" };\n\nforeach(string optionValue in MyList) {\n    // Attempt to retrieve PropertyInfo with the given option and value\n    PropertyInfo newPI = this.GetType().GetProperty("Option" + optionValue);\n    if(newPI != null) {\n        object value = newPI.GetValue(this, null);\n        newPI.SetValue(this, false);\n    }\n}	0
8102525	8102109	What makes a name of a method equivalent to an action delegate?	void Main() \n{? ? \n    Flow.Sequence(new Action(delegate(){ F1(); }), new Action(delegate(){ F2(); }));? ? \n    Flow.Sequence(new Action(F1), new Action(F2)); \n}	0
13646464	7797083	AutoMapper registration in Unity DI	Container\n .RegisterType<ConfigurationStore, ConfigurationStore>\n                              (\n                                 new ContainerControlledLifetimeManager()\n                               , new InjectionConstructor(typeof(ITypeMapFactory)\n                               , MapperRegistry.AllMappers())\n                              )\n .RegisterType<IConfigurationProvider, ConfigurationStore>()\n .RegisterType<IConfiguration, ConfigurationStore>()\n .RegisterType<IMappingEngine, MappingEngine>()\n .RegisterType<ITypeMapFactory, TypeMapFactory>();	0
33917322	33916930	Changing value of control in TabItem makes TabControl change index. How?	private void myTab_SelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n            if (e.Source is TabControl) //if this event fired from TabControl\n            {\n                if (tabItemName.IsSelected)\n                {\n                    //Do what you need here.\n                }\n            }\n        }	0
11247180	11246282	Create a context to a local database using a context class from a WCF data service	void Save(ServerBlog sb)\n{\n    using (var db = new LocalContext())\n    {\n        var clientBlog = new ClientBlog\n        {\n            Text = db.Text\n            // or the same using AutoMapper\n        };\n        db.Blogs.Add(clientBlog):\n    }\n}	0
26362769	26359591	Value are assigned to wrong label	strScript.Append(@"[...]\n      var data = google.visualization.arrayToDataTable([  \n            ['Course', 'Progression'],");\n\nforeach (DataRow row in dsChartData.Rows)\n{\n  strScript.Append("['" + row["Course"] + "'," + row["Progression"] + "],");\n}	0
18022901	18022656	Generate Word document and attach/send email without saving?	static byte[] GetData()\n{\n    string s = "<html><head></head><body><p>Word doc body here</p></body></html>";\n    byte[] data = Encoding.ASCII.GetBytes(s);\n    return data;\n}	0
14245682	11985393	Create edit link to document in sharepoint	function DispEx(ele, objEvent, fTransformServiceOn, fShouldTransformExtension,\n    fTransformHandleUrl, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, \n    strServerFileRedirect, strCheckoutUser, strCurrentUser, strRequireCheckout, \n    strCheckedoutTolocal, strPermmask)	0
9891395	9891306	How to get a static property declared from another instance. c#	LoginDialog.RunDialog()	0
30304799	27760716	Simple Injector register multiple type of same interface with metadata	// Definition\npublic interface IMyServiceFactory {\n    IMyService CreateNew();\n}\n\n// Implementation\nsealed class ServiceFactory : IMyServiceFactory {\n    public IMyService CreateNew() {\n        return new MyServiceImpl();\n    }\n}\n\n// Registration\ncontainer.RegisterSingle<IMyServiceFactory, ServiceFactory>();\n\n// Usage\npublic class MyService {\n    private readonly IMyServiceFactory factory;\n\n    public MyService(IMyServiceFactory factory) {\n        this.factory = factory;\n    }\n\n    public void SomeOperation() {\n        using (var service1 = this.factory.CreateNew()) {\n            // use service 1\n        }\n\n        using (var service2 = this.factory.CreateNew()) {\n            // use service 2\n        }\n    }\n}	0
10146435	10146269	Set imagesource of wpf image	logo.BeginInit();\nlogo.UriSource = new Uri("pack://application:,,,/Images/Klar.JPG");\nlogo.EndInit();	0
14980846	14980660	How to convert Type in a visually decent, visual-studio-style string	Assembly.ReflectionOnlyLoad()\nAssembly.ReflectionOnlyLoadFrom()	0
11904349	11904253	c#.net Regex - Need to find a sequence of characters, then replace one character within it	new Regex("([a-zA-Z])'([a-zA-Z])").Replace(input, match => match.Groups[1] + "''" + match.Groups[2])	0
19904524	19904424	How to use single dbml file with different database	DataContext context = new DataContext (newConnectionString);	0
3701348	3701261	ASP.net - LinkButtons in a Repeater within an UpdatePanel are not triggering a postback of any kind	[<asp:LinkButton CommandName='Schedule' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Name") %>' ID="ScheduleButton" runat="server" CausesValidation="false" OnCommand="LinkButtonCommandEventHandler" >Schedule</asp:LinkButton>]	0
12459158	12459105	access active assembly resources	Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();	0
2763519	2763128	Get the currency from current culture?	var ri = new RegionInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);\n  Console.WriteLine(ri.ISOCurrencySymbol);	0
19306244	19306215	How do I find the corrent location of the pictureBox? It should be to be in the center of form1	pb.Size = new Size(500,500);\npb.Location = new Point((ClientSize.Width-pb.Width)/2,\n                        (ClientSize.Height-pb.Height)/2);	0
7476699	7476559	How to parse this? ftpWebRequest ListDirectorDetials	var value = "09-17-11  01:00AM               942038 my.zip";\nvar tokens = value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\nif (tokens.Length > 3)\n{\n    var test = new Test\n    {\n        DateCreated = DateTime.ParseExact(tokens[0] + tokens[1], "MM-dd-yyHH:mmtt", CultureInfo.InvariantCulture),\n        Size = int.Parse(tokens[2]),\n        Name = tokens[3]\n    };\n\n    // at this stage:\n    // test.DateCreated = 17/09/2011 01:00AM\n    // test.Size = 942038\n    // test.Name = "my.zip"\n}	0
12789882	12789830	How to do telnet in C# console application	TcpClient tc = null;\ntry\n{\n    tc = new TcpClient("192.168.1.117", 23);\n    // If we get here, port is open\n} \ncatch(SocketException se) \n{\n    // If we get here, port is not open, or host is not reachable\n}\nfinally\n{\n   if (tc != null)\n   {\n      tc.Close(); \n   }\n}	0
321727	314062	De/Serialize directly To/From XML Linq	public XDocument Serialize<T>(T source)\n    {\n        XDocument target = new XDocument();\n        XmlSerializer s = new XmlSerializer(typeof(T));\n        System.Xml.XmlWriter writer = target.CreateWriter();\n        s.Serialize(writer, source);\n        writer.Close();\n        return target;\n    }\n\n    public void Test1()\n    {\n        MyClass c = new MyClass() { SomeValue = "bar" };\n        XDocument doc = Serialize<MyClass>(c);\n        Console.WriteLine(doc.ToString());\n    }	0
25790735	25790659	Linq Where/OrderBy string to int	dbResults = gaResultDetails.All\n  .Where(c => c.ContentLink.Id == contentId && c.RequestType.Id == requestTypeId)    \n  .AsEnumerable()\n  .OrderBy(c => c.DateFrom)\n  .ThenBy(c => int.Parse(c.Data_2))\n  .Take(Take) \n  .ToList();	0
28808569	28804584	How to make gridview column hyperlink clickable and catch the event?	private void Hyperlink_OnClick(object sender, RoutedEventArgs e)\n    {\n        var hl = e.OriginalSource as System.Windows.Documents.Hyperlink;\n        Process.Start(hl.NavigateUri.AbsoluteUri);\n    }	0
20382315	20358429	How to add a Page Number Reference to a table cell in a MS Word Footer	Word.Range rng=table.Cell(2,2).Range;\nrng.End=rng.End-1;\nrng.Start=rng.End;\nrng.Select();\napp.Selection.Range.Fields.Add(app.Selection.Range,Word.WdFieldType.wdFieldPage,oMissing,oMissing);	0
6818003	6810479	Getting hardware GUID for video adapter in C#	Manager.Adapters[0].Information.DeviceIdentifier	0
24186656	24186251	Combine Two Properties From Entity In List And Flatten It With Linq	var result = games\n    .SelectMany(game => new[] { game.AwayTeamId, game.HomeTeamId })\n    .Distinct()\n;	0
27978306	27977961	Object lifetime in static list - weak reference of objects	class BaseClass : IDisposable\n{\n    private WeakReference<BaseClass> myReference;\n    private static List<WeakReference<BaseClass>> instances = new List<WeakReference>();\n\n    public static UpdateClasses(MyData stuff)\n    {\n        foreach(var ref in instances)\n        {\n           BaseClass target;\n           if (ref.TryGetTarget(out target))\n           {\n               // code to update target here\n           }\n        }\n    }\n    protected BaseClass()\n    {\n       myReference = new WeakReference<BaseClass>(this,true);\n       instances.Add(myReference);\n    }\n\n    ~BaseClass()\n    {\n       Dispose();\n    }\n\n    public void Dispose()\n    {\n       instances.Remove(myReference);\n    }\n}	0
11343675	11104828	WPF DataGrid scrolling with down arrow key acts strangely	public class MainLogData \n{ \n    public string Timestamp { get; set; } \n    public string Level { get; set; } \n    public string Message { get; set; } \n}	0
11739168	11739033	How to get a DataTable object from a database using its tablename in C#?	string Sql="SELECT * FROM MYTABLE WHERE 1=0";\nstring connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MYDATA.MDB;"\n\nOleDbConnection new OleDbConnection(connectionstring);\nconn.Open();\nOleDbCommand cmd = new OleDbCommand(Sql, conn);\nOleDbDataAdapter adapter = new OleDbDataAdapter(cmd);\nDataTable table = new DataTable();\nadapter.Fill(table);\nconn.Close();	0
2375720	2355679	How to make this LINQ to XML query more elegant?	XElement[] hits = (from record in config.Elements(modsV3 + "mods").Elements(modsV3 + "name")\nwhere   record.XPathSelectElement(string.Format("./{0}namePart[@type='family' and .='{1}']", modsV3, familyName)) != null &&\n        record.XPathSelectElement(string.Format("./{0}namePart[@type='given' and .='{1}']", modsV3, givenName)) != null &&\n        record.XPathSelectElement(string.Format("./{0}role/{0}roleTerm[@type='code' and .='aut']", modsV3)) != null\nselect record.Parent).ToArray<XElement>();	0
35116	35103	How do I store information in my executable in .Net	write(MD5(SecretKey + ConfigFileText));	0
25292887	25292250	how to read a json file record by record	var fileJson = JToken.Parse(file);\n\nforeach (var item in fileJson["transactions"])\n{\n    // do stuff\n}	0
8796039	8736543	ASPxListBox items to string	ASPxListBox listBox = instance;\n\nstring selectedItemsAsString = string.Empty;\n\nforeach (ListEditItem item in listBox.SelectedItems)\n    selectedItemsAsString += item.Value + ";";\n\nif (selectedItemsAsString.Length > 0)\n    selectedItemsAsString = selectedItemsAsString.Trim(new char[] { ';' });	0
5670673	5670658	How to recalculate elements with IEnumerable.Select?	var result = list.Select(\n    (element, index) => new MyType { Num = index + 1, Text = element.Text }\n);	0
3014539	3014327	How to use Excel file from visual studio project resource	Dim sPath As String = My.Computer.FileSystem.GetTempFileName\n        My.Computer.FileSystem.WriteAllBytes(sPath, My.Resources.us, False)	0
29225459	29192812	how to remove white space content between the bullet symbol and the paragraph using OpenXML	var a = new AbstractNum(\n                                new Nsid() { Val = "FFFFFF80" }\n                                , new MultiLevelType() { Val = MultiLevelValues.HybridMultilevel }\n                                , new Level(\n                                  new LevelSuffix { Val = LevelSuffixValues.Space, },\n                                  new NumberingFormat() { Val = NumberFormatValues.Bullet },\n                                  new LevelText() { Val = "-" }\n                                ) { LevelIndex = 0 }\n                              ) { AbstractNumberId = abstarctnumberId };	0
6499344	6499334	Best way to change dictionary key	public static void RenameKey<TKey, TValue>(this IDictionary<TKey, TValue> dic,\n                                      TKey fromKey, TKey toKey)\n{\n  TValue value = dic[fromKey];\n  dic.Remove(fromKey);\n  dic[toKey] = value;\n}	0
31631449	31629937	Match to most match words with LINQ	var wantedWords = "word3 word2".Split();\nvar strings = new List<string>\n{\n    "word1 word2 word3 word4 word5",\n    "word1 word2",\n    "word4 word5",\n    "word1 word4 word5"\n};\nvar result = from s in strings\n             let words = s.Split()\n             select new\n             {\n                 String = s,\n                 MatchedCount = wantedWords.Count(ww => words.Contains(ww))\n             } into e\n             where e.MatchedCount > 0\n             orderby e.MatchedCount descending\n             select e.String;	0
5962689	5962659	How to store a collection of Dictionaries?	List<Dictionary<string,string>> list = new List<Dictionary<string,string>>();\nDictionary<string,string> dict1 = new Dictionary<string,string>();\n\nlist.Add(dict1);\nlist.Add(new Dictionary<string,string>());	0
11069546	11069240	Unable to search in Generic list on the basis of string data type	IEnumerable<T> myEnumerable = currentList.Select(current => current.address = address);	0
13063058	13059347	Inverting a gradient/lighting	tiles.color = new Color(1 - tiles.distance / size, 1 - tiles.distance / size, 1 - tiles.distance / size);	0
8302607	8299450	c# search in list for two string in the same line	foreach (string line in simpleList)\n{\n    string rec_idGB = line.Split('\t')[0].Substring(4).Trim();\n    string tagGB = line.Split('\t')[2].Substring(7).Trim();\n    bool thereIsAMatch = false;\n    foreach (string line2 in fullList)\n    {\n        if (line2.Contains(rec_idGB) && line2.Contains(tagGB))\n        {\n            thereIsAMatch = true;\n            break;\n        }\n    }\n    if(!thereIsAMatch)\n    {\n        // This is what you want?\n    }\n}	0
22126641	22125973	sfx files do extract though input the wrong password	cmp.EncryptHeaders = true;	0
25362115	25361901	Mapping One to Many on non-primary key	var result = from p in db.Person\n             join a in db.Address\n             on p.PersonSystemID equals a.PersonSystemID\n             select new { Person = p, Address = a };	0
3210859	3210685	how to detect MSword is opened with specific file?	List<Process> processes = new List<Process>();	0
19945762	19935499	Display different control on Gridview Cell based on specific cell data	protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            // You can replace this with a switch statement\n            if (DataBinder.Eval(e.Row.DataItem, "Discontinued").ToString() == "False")\n            {\n                TextBox txtTemp = new TextBox();\n                txtTemp.Text = "I am a textbox";\n                e.Row.Cells[10].Controls.Add(txtTemp);\n            }\n            else\n            {\n                // Add other controls here\n            }\n        }\n    }	0
32381260	32380316	ASP.NET Custom Validator On 2 Fields	protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)\n    {\n        args.IsValid = false;\n        string fname = txtfirstname.Text;\n        string lname = txtlastname.Text; // Get the last name\n        SqlConnection conn = new SqlConnection(strCon);\n\n        SqlDataAdapter da = new SqlDataAdapter("select * from usertable where usertable.firstname=@fn and usertable.lastname=@ln", conn); // Add last name to query\n        da.SelectCommand.Parameters.Add("@fn");\n        da.SelectCommand.Parameters["@fn"].Value = fname;\n        da.SelectCommand.Parameters.Add("@ln"); // New parameter.\n        da.SelectCommand.Parameters["@ln"].Value = lname;\n        DataSet ds = new DataSet();\n        da.Fill(ds);\n        if (ds.Tables[0].Rows.Count > 0)\n            args.IsValid = true;\n\n    }	0
16235915	16235818	Updating from different thread didn't update Listbox	public void dumpList()\n{\n    if (this.InvokeRequired)\n    {\n       this.Invoke(new MethodInvoker(this.dumpList));\n       return;\n    }\n\n    ListBoxS.DataSource = sl.dump(); //Returns a List<string>()\n}	0
6429625	6429603	How can I declare a string within this method?	st.DeleteTask(tester);	0
6716943	6706632	custom fluentvalidator	public class QualificationSetValidator : PropertyValidator {\n    // Default error message specified in the base ctor\n    // but it can be overriden using WithMessage in the RuleFor call\n    public QualificationSetValidator() : base("At least one property must be selected.") {\n\n    }\n\n    protected override bool IsValid(PropertyValidatorContext context) {\n        // You can retrieve a reference to the object being validated \n        // through the context.Instance property\n        tblNeutralFileMaint neutral = (tblNeutralFileMaint)context.Instance;\n\n        // You can also retrieve a reference to the property being validated\n        // ...using context.PropertyValue\n\n        // here is where you can do the custom validation\n        // and return true/false depending on success.\n\n     }\n }	0
7205442	7205402	Initializing multidimentional arrays in c# (with other arrays)	int[] arr1 = new[] { 1, 2, 3 };\nint[] arr2 = new[] { 4, 5, 6 };\nint[] arr3 = new[] { 7, 8, 9 };\n\nint[][] jagged = new[] { arr1, arr2, arr3 };\n\nint six = jagged[1][2];	0
31294719	31294374	Change gridview's row color ASP.NET	protected void MergeGrid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        if (e.Row.RowIndex == 0) //Select the row\n        {\n            e.Row.BackColor = System.Drawing.Color.FromArgb(255, 0, 0);\n\n            //or you can select the color\n            //e.Row.BackColor = System.Drawing.Color.Red;\n        }\n    }\n}	0
16102640	16102520	How to get installed exe file system path after scheduling in windows scheduler?	System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);	0
842554	842465	Reading a line from a streamreader without consuming?	public class PeekableStreamReaderAdapter\n    {\n        private StreamReader Underlying;\n        private Queue<string> BufferedLines;\n\n        public PeekableStreamReaderAdapter(StreamReader underlying)\n        {\n            Underlying = underlying;\n            BufferedLines = new Queue<string>();\n        }\n\n        public string PeekLine()\n        {\n            string line = Underlying.ReadLine();\n            if (line == null)\n                return null;\n            BufferedLines.Enqueue(line);\n            return line;\n        }\n\n\n        public string ReadLine()\n        {\n            if (BufferedLines.Count > 0)\n                return BufferedLines.Dequeue();\n            return Underlying.ReadLine();\n        }\n    }	0
27146916	27144243	Stop raycasts from going through walls	RaycastHit hit;\nif(Physics.Raycast(transform.position, fwd, out hit ,10))\n{\n    if (hit.transform.gameObject == playerTarget)\n    {\n        Debug.Log ("Raycast entered ");\n        myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime); \n        if (dir.magnitude > maxDistance) \n        { \n            character.Move(myTransform.forward * moveSpeed * Time.deltaTime); \n        }\n    }\n}	0
26699746	26699639	Reuse expression to select single	public static PropertyCompliance PropertyIsCompliant(this IEnumerable<PropertyCompliance> complianceRecords, DateTime checkDate) {\n    return complianceRatings\n         .OrderByDescending(cr => cr.Date)\n         .First(cr => cr.Date <= checkDate);\n}	0
23012011	23011488	The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value?	if(DateTime.TryParse(txtStartingdate.Text, out stdate)\n{\n    SqlParameter projectStartingDateParam = new SqlParameter("@projectstartingdate", SqlDbType.DateTime);\n        projectStartingDateParam.Value = stdate;\n    cmd.Parameters.Add(projectStartingDateParam);\n}	0
31512208	28745766	WPF MVVM Input Validation Using WAF Framework	BookListView.xaml:    \n\nwaf:ValidationHelper.IsEnabled="true" \nwaf:ValidationHelper.IsValid="{Binding IsValid, Mode=OneWayToSource}"	0
4471021	4471001	get line number for XElement here	XDocument xdoc = XDocument.Load(file, LoadOptions.SetLineInfo);\nIEnumerable<XElement> categories = xdoc.Descendants("Category");\nforeach (XElement category in categories)\n{\n    //get line number for element here...\n    string lineNumber = ((IXmlLineInfo)category).HasLineInfo() ? ((IXmlLineInfo)category).LineNumber : -1;\n}	0
15310343	15310315	ASP .Net Security implementation	Server.Transfer	0
21633142	21633037	Find prefixes and suffixes of a string	string pattern = "bread";\nvar prefixes = Enumerable.Range(1, pattern.Length - 1)\n                         .Select(p => pattern.Substring(0, p));\nvar suffixes = Enumerable.Range(1, pattern.Length - 1)\n                         .Select(p => pattern.Substring(p, pattern.Length - p));	0
32104032	32102929	How to Convert a Byte Array to String for a DataGridView	void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    // 2 - Salt, 3 - SecurePassword\n    if (e.ColumnIndex == 2 || e.ColumnIndex == 3)\n    {\n        if (e.Value != null)\n        {\n            byte[] array = (byte[])e.Value;\n            e.Value = BitConverter.ToString(array);\n            e.FormattingApplied = true;\n        }\n        else\n            e.FormattingApplied = false;\n    }\n}	0
4205868	4205798	Getting and parsing remote date time value	return DateTime.ParseExact(value, "ddd MMM dd hh:mm:ss yyyy", culture, styles);	0
26015779	26015682	LINQ Sum of entries based on latest date	int built = db.Builds\n    .GroupBy(b => b.Code)\n    .Sum(g => g.OrderByDescending(b => b.BuildDate).First().BuildQuantity);	0
21989689	21989577	How do i insert html into my table?	SqlCeCommand command = new SqlCeCommand("UPDATE Bio SET text = @htmlText WHERE id = @id", conn);\n\nSqlCeParameter param;\n\n// NOTE:\n// For optimal performance, make sure you always set the parameter\n// type and the maximum size - this is especially important for non-fixed\n// types such as NVARCHAR or NTEXT; In case of named parameters, \n// SqlCeParameter instances do not need to be added to the collection\n// in the order specified in the query; If however you use ? as parameter\n// specifiers, then you do need to add the parameters in the correct order\n//\nparam = new SqlCeParameter("@id", SqlDbType.Int);\ncommand.Parameters.Add(param);\nparam = new SqlCeParameter("@htmlText", SqlDbType.NVarChar, -1);\ncommand.Prepare();\n\n//Set the values and the length of the string parameter\ncommand.Parameters[0].Value = ViewBag.Id;\ncommand.Parameters[1].Value = form["textbox"];\ncommand.Parameters[1].Size = form["textbox"].Length;\n\n\n\n// Execute the SQL statement\n//\ncommand.ExecuteNonQuery();	0
2874397	2874341	How to let regex know that it should stop after a first occurence?	time = time.Substring(time.IndexOf(":") + 1);	0
970729	970692	How can I force a C# constructor to be a factory?	public SmartForm(string loadCode)\n{\n    _loadCode = loadCode;\n    SmartForms smartForms = new SmartForms(_loadCode);\n    this.IdCode = smartForms[0].IdCode;\n    this.Title = smartForms[0].Title;\n}	0
25204225	25203381	Trouble with clicking on an image in running IE with SHDocVw	foreach (IHTMLElement element in htmlDoc.all)\n{\n    var input = element as IHTMLInputImage;\n    if (input != null && Path.GetFileName(input.src).Equals("icon_go.GIF", StringComparison.OrdinalIgnoreCase))\n    {\n        ((IHTMLElement)input).click();\n    }\n}	0
17443475	17443260	How to sort depends on Particular Column In Datagridview?	System.Data.DataView	0
14612008	14611919	How to create consecutive named files	for(int i = 0; i<10; i++)\n{\n    string fileName = string.Format("10FRE{0:D3}",i);\n    // other codes\n}	0
5980637	5980343	How do I determine visibility of a control?	public static bool WouldBeVisible(Control ctl) \n{\n      // Returns true if the control would be visible if container is visible\n      MethodInfo mi = ctl.GetType().GetMethod("GetState", BindingFlags.Instance | BindingFlags.NonPublic);\n      if (mi == null) return ctl.Visible;\n      return (bool)(mi.Invoke(ctl, new object[] { 2 }));\n}	0
33814203	33804476	Can you instruct EF to ignore tables that already exist	Add-Migration MyBaseline ??gnoreChanges	0
11995764	11994216	OpenXml: Determining the Image in a Cell in Excel	[Test]\n    public void GetImageRelationshipIdAndImageOfThatId()\n    {\n        string row = "1";\n        string col = "0";\n\n        WorkbookPart wbPart = document.WorkbookPart;\n        var workSheet = wbPart.WorksheetParts.FirstOrDefault();\n\n        TwoCellAnchor cellHoldingPicture = workSheet.DrawingsPart.WorksheetDrawing.OfType<TwoCellAnchor>()\n             .Where(c => c.FromMarker.RowId.Text == row && \n                    c.FromMarker.ColumnId.Text == col).FirstOrDefault();\n\n        var picture = cellHoldingPicture.OfType<DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture>().FirstOrDefault();\n        string rIdofPicture = picture.BlipFill.Blip.Embed;\n\n        Console.WriteLine("The rID of this Anchor's [{0},{1}] Picture is '{2}'" ,row,col, rIdofPicture);\n\n        ImagePart imageInThisCell = (ImagePart)workSheet.DrawingsPart.GetPartById(rIdofPicture);\n\n    }	0
11613759	11612864	Is there a way to download a file without Webclient in Silverlight?	byte[] bytes;\npublic void DownloadFile()\n{\n    WebClient webClient = new WebClient();\n    webClient.OpenReadCompleted += (s, e) =>\n       {\n           Stream stream = e.Result;\n           MemoryStream ms = new MemoryStream();\n           stream.CopyTo(ms);\n           bytes = ms.ToArray();\n       };\n    webClient.OpenReadAsync(new Uri("http://myurl.com/file.zip"), UriKind.Absolute);\n}	0
5114069	5113919	How to Convert 2-D array into Image in c#	// Create 2D array of integers\nint width = 320;\nint height = 240;\nint stride = width * 4;\nint[,] integers = new int[width,height];\n\n// Fill array with random values\nRandom random = new Random();\nfor (int x = 0; x < width; ++x)\n{\n    for (int y = 0; y < height; ++y)\n    {\n        byte[] bgra = new byte[] { (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), 255 };\n        integers[x, y] = BitConverter.ToInt32(bgra, 0);\n    }\n}\n\n// Copy into bitmap\nBitmap bitmap;\nunsafe\n{\n    fixed (int* intPtr = &integers[0,0])\n    {\n        bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb, new IntPtr(intPtr));\n    }\n}	0
18027044	18027043	How do I browse a Websphere MQ Queue through all messages?	while (true)\n{\n    string messageText = msg.ReadString(msg.MessageLength);\n    Messages.Add(messageText);\n    msg = new MQMessage();\n    _queue.Get(msg, mqGetNextMsgOpts);\n}	0
677955	677909	double[,] type, how to get the # of rows?	double[,] lookup = { {1,2,3}, {4,5,6} };\n\nint rows = lookup.GetLength(0); // 2\nint cols = lookup.GetLength(1); // 3    \nint cells = lookup.Length; // 2*3 = 6	0
10732683	10732638	Is there syntax validator for Regex?	public bool isValidRegex(string input){\n     bool ret;\n\n\n     ret = true;\n\n     try{\n         new Regex(input);\n     }\n     catch (ArgumentException){\n          ret = false;\n     }\n\n     return ret;\n}	0
12410123	12410071	returning total in controller action from a view	(from p in db.vwCustomer.Where(a => a.CustomerId == id) select p.LateFee).sum();	0
30509104	30508336	Import modified data in Excel to Database Table	MERGE Products AS TARGET\nUSING UpdatedProducts AS SOURCE \n    ON TARGET.ProductID = SOURCE.ProductID\nWHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName OR TARGET.Rate <> SOURCE.Rate \n    THEN UPDATE SET TARGET.ProductName = SOURCE.ProductName, \n                    TARGET.Rate = SOURCE.Rate \nWHEN NOT MATCHED BY TARGET \n    THEN INSERT (ProductID, ProductName, Rate) \n        VALUES (SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)\nWHEN NOT MATCHED BY SOURCE \n    THEN DELETE	0
29033589	29033453	How to bit-shift and concatenate to get correct result?	byte val1LowBits = (byte) (r[0] >> 8);\nbyte val1HighBits = (byte) (r[1] & 0xff);\nbyte val2LowBits = (byte) (r[1] >> 8);\nbyte val2HighBits = (byte) (r[2] & 0xff);\n\nuint val1 = (uint) ((val1HighBits << 8) | val1LowBits);\nuint val2 = (uint) ((val2HighBits << 8) | val2LowBits);	0
23046940	23043591	Binding data to a DropDownList Error	Currency curFrom = (Currency)Enum.Parse(typeof(Currency), ComboBoxFrom.SelectedValue);	0
9264413	9264359	Adding properties based on lambda expressions	Lambda.Reflect<SomeClass>(x => x.AMethod());    \nLambda.Reflect<SomeClass>(x => x.AProperty);    \nLambda.Reflect(() => local);	0
9265187	9265052	performance issues with jquery textbox changed ajax postback	private void textBox1_Leave(object sender, System.EventArgs e)\n{\n  string StrSql = Textbox1.Text; // your sql queries goes here\n  using(SqlConnection con = new SqlConnection(Constr))\n  {\n    SqlCommand cmd = new SqlCommand(strSql, con); \n    cmd.ExecuteNonQuery();  \n  }\n\n}	0
1662549	1656767	Custom objects as arguments in controller methods defined by MapRoutes	public sealed class AlternateOutputAttribute :\n                    ActionFilterAttribute, IActionFilter\n{\n    void IActionFilter.OnActionExecuted(ActionExecutedContext aec)\n    {\n        ViewResult vr = aec.Result as ViewResult;\n\n        if (vr == null) return;\n\n        var aof = aec.RouteData.Values["alternateOutputFormat"] as String;\n\n        if (aof == "json") aec.Result = new JsonResult\n        {\n            JsonRequestBehavior = JsonRequestBehavior.AllowGet,\n            Data = vr.ViewData.Model,\n            ContentType = "application/json",\n            ContentEncoding = Encoding.UTF8\n        };\n    }\n}	0
20718946	20718351	SQl Transactions - query doesnt return value as expected	Declare @status nvarchar(50),@tablename nvarchar(50), @colname nvarchar(50),\n@id nvarchar(50), @qry nvarchar(500)\nset @tablename  = 'person'\nset @colname = 'id'\nset @id = '15'\nbegin try\nbegin transaction\n set @qry='delete '+@tablename+' where '+@colname+'=@id'\n execute sp_executesql @qry,N'@id nvarchar(50)',@id=@id\n rollback \n --NO FK violation.So begin another transaction and soft delete\n begin transaction\nset @qry='update '+@tablename +' set deleted=1 where '+@colname+'=@id'\n\nexecute sp_executesql @qry,N'@id nvarchar(50)',@id=@id\ncommit\n\nselect 1\n\nend try\n\nbegin catch\nprint(Error_Message())\n--FK violation.Do nothing.Return 0\nselect 0\n\nend catch	0
30268374	30268338	how to get new mysql connector for c#	Install-Package MySql.Data	0
1391493	1391483	does timespan take into account leap year when calculating days between two random dates?	DateTime date0 = new DateTime(2001, 12, 31);\nDateTime date1 = new DateTime(2000, 12, 31);\nDateTime date2 = new DateTime(1999, 12, 31);\nConsole.WriteLine("{0} / {1}", (date2 - date1).Days, (date1-date0).Days);	0
16193114	16193100	Check if a table is empty with Entity Framework using CodeFirst	using (var db = new CreateDbContext())\n{\n    if(!db.Projects.Any())\n    {\n        // The table is empty\n    }\n}	0
31915584	31910950	How can i stop my player from moving in a direction when a collision is made	if(Player.X + Player.Width >= Enemy.X && Player.X < Enemy.X)\n{\n    right = false;\n}	0
10224385	10223811	Show progress bar while downloading an Image in ASP.Net webform	.ImageClass\n{\n      display: block;\n      background-image: url('../images/loading-circle.gif');\n      background-position: center center;\n      background-repeat:no-repeat;\n}	0
8998217	8998173	How to compute expression	System.Reflection.Emit	0
22143783	22143422	Search in C# bringing back multiple rows - datagrid view	while (dr.Read())\n        {\n            for (int k = 0; k < columncount; k++)\n            {\n\n                switch (dr.GetFieldType(k).ToString())\n                {\n                    case "System.Int32":\n                        rowdata[k] = dr.GetInt32(k).ToString();\n                        break;\n\n                    case "System.DateTime":\n                        rowdata[k] = dr.GetDateTime(k).ToString();\n                        break;\n\n                    case "System.String":\n                        rowdata[k] = dr.GetString(k);\n                        break;\n                }\n\n                //dataGridView1.Rows.Add(rowdata); <= This shouldn't be here\n            }\n          //Add row after loop completes all columns\n          dataGridView1.Rows.Add(rowdata);\n        }	0
4155120	4155009	How to Bind Listbox in WPF to a generic list?	public class YourViewModel\n{\n        public virtual ObservableCollection<YourComplexType> YourCollection\n        {\n            get\n            {\n                var list = new ObservableCollection<YourComplexType>(YourStaticClass.YourList);\n                var allEntity = new YourComplexType();\n\n                allEntity.Name = "all";\n                allEntity.Id = 0;\n\n                list.Insert(0, allEntity);\n\n                return list;\n            }\n\n        }\n}	0
13358684	13357526	IMEX in OleDbConnection	Microsoft.Office.Interop.Excel	0
30713474	30712203	How to Post a null byte from an edit or update page on ASP.NET MVC	byte[] Signature;  \nbyte[] Photo;  \nbyte[] Signature2;  \n\nif (Model.MSignature != null)\n{\n    Signature = new byte[model.MSignature.InputStream.Length];\n    model.MSignature.InputStream.Read(Signature, 0, Signature.Length);\n}\n\nif (Model.MPhoto != null)\n{\n    new byte[model.MPhoto.InputStream.Length];\n    model.MPhoto.InputStream.Read(Photo, 0, Photo.Length);\n}\n\nif (Model.WSignature != null) \n{\n    new byte[model.WSignature.InputStream.Length];\n    model.WSignature.InputStream.Read(Signature2, 0, Signature2.Length);\n}	0
4892727	4892668	How to mark members that are required by runtime but shouldn't be used in code?	// My Core Immutable Type\nnamespace MyProject {\n  public sealed class Student { \n    private readonly string _name;\n    public string Name { \n      get { return _name; }\n    }\n    public Student(string name) {\n      _name = name;\n    }\n  }\n}\n\n// My Xml Serialization Type\nnamespace MyProject.Serialization {\n  public class SerializableStudent {\n    public string Name;\n\n    public SerializableStudent(Student source) {\n      Name = source.Name;\n    }\n\n    public Student ConvertToStudent() {\n      return new Student(Name);\n    }\n\n  }\n}	0
9933332	9918051	XNA 2D Collision Detection	private readonly Dictionary<Type, List<MapObject>> mTypeObjects = \nnew Dictionary<Type, List<MapObject>>();\n\nprivate readonly Dictionary<FACTION, List<MapObject>> mFactionCreatures =\nnew Dictionary<FACTION, List<MapObject>>();	0
9689030	9688561	Remove an item from a collection of Lists	var errPRNlines = File.ReadAllLines(myFile.FullName.ToString(), Encoding.GetEncoding(1250))\n.Skip(1)\n.Where (line => line.Contains("Not available"))\n.Select(line => \n    line.Split(new[] { "  " }, StringSplitOptions.RemoveEmptyEntries)\n    .Where((col, index) => index!=2))\n.ToList();	0
4028504	4028456	C# - Displaying server control based on how many items are in a datalist	if(DataListName.Items.Count > 1)\n{\n    Literalmulti.Visible = true;\n} \nelse\n{\n    Literalsingle.Visible = true;\n}	0
13393274	11079514	How to convert Fluent NHibernate mapping to NHibernate Built-in Code Based Mapping	public virtual void Map(ModelMapper mapper)\n    {\n        mapper.Class<LocalizationEntry>(m =>\n        {\n            m.ComponentAsId(x => x.Id, n =>\n            {\n                n.Property(x => x.Culture);\n                n.Property(x => x.EntityId);\n                n.Property(x => x.Property);\n                n.Property(x => x.Type);\n            });\n\n            m.Property(t => t.Message, c =>\n            {\n                c.NotNullable(true);\n                c.Length(400);\n            });\n        });\n    }	0
23959613	23959317	Different kind of deserializing XML in C#	var adWords = new List<AdWordsGeoPerformance>();\n\nvar xDoc = XDocument.Parse(doc);\nforeach(var r in xDoc.Descendants("row"))\n{\n    var adWord = new AdWordsGeoPerformance()\n    {\n        Clicks = int.Parse((string)r.Attribute("clicks")),\n        CountryTerritory = (string)r.Attribute("countryTerritory"),\n        Day = DateTime.Parse((string)r.Attribute("day")),\n    };\n\n    adWords.Add(adWord);\n}	0
18405295	18359327	On printing mono chrome bitmap image one extra vertical line is also getting printed	byteWidth = Math.Ceiling(bitmapDataWidth / 8.0);	0
19677349	19677198	Convert text utf8 to char or string	string hexString = "0e2a0e270e310e2a0e140e350e040e230e310e1a";\n\n// unscramble the hex\nbyte[] bytes = new byte[hexString.Length / 2];\nfor(int i = 0; i < bytes.Length; i++)\n{\n    bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);\n}\n\n// convert to a string via big-endian utf-16\nstring result = Encoding.BigEndianUnicode.GetString(bytes); // "??????????"	0
30752706	30741857	wav file concatenation exception with naudio library	mplayer.close();	0
33690200	33674743	Automate control creation in windows forms designer	var host = GetService(typeof(IDesignerHost)) as IDesignerHost;\n   var button = host.CreateComponent(typeof(Button), "someName") as Button;\n   FindForm().Controls.Add(button);	0
26753336	26753237	How to make sure not to dispose objects that are still used by others	interface1.dispose();	0
18429336	18317923	How to change a colore of menu bar when user click on net link	string thisURL = this.Page.GetType().Name.ToString();       \n        switch (thisURL)\n        {\n            case "home_aspx":\n                lihome.Attributes.Add("class", "Active");                \n                break;\n         case "support_aspx":\n                lisupport.Attributes.Add("class", "Active");\n                break;\n         case "logout_aspx":\n                lilogout.Attributes.Add("class", "Active");\n                break;\n         }	0
16601731	16579336	How to get the value from the list with in the object	MarkelRate = Markel.MarkelService(username, password, dt, GR.State, classCode, GR.Territory, EachOcc, GeneralAgg, Deductible);\n        foreach (msu.markelcorp.com.Markel.MarkelClassGuide.GLClassRate item in MarkelRate.List)\n        {\n           string PrmiumRate = item.BaseRate.ToString();\n        }	0
8918940	8918446	Showing Validation error for server side validation	ASP.NET MVC 3 provides a mechanism that can make a remote server call in order to validate a form field without posting the entire form to the server. This is useful when you have a field that cannot be validated on the client and is therefore likely to fail validation when the form is submitted. For example, many Web sites require you to register using a unique user ID. For popular sites, it can take several attempts to find a user ID that is not already taken, and the user's input is not considered valid until all fields are valid, including the user ID. Being able to validate remotely saves the user from having to submit the form several times before finding an available ID.	0
15097745	15097715	Prevent new values from LINQ query	var queryResultList = (from s in selected\n             where n.contains("www")\n             select s).ToList();	0
5514222	5514051	How do I navigate a website programmatically from a windows forms application?	webbrowser.Document.All["ID OF ELEMENT (I THINK NAME WORKS TOO)"].InvokeMember("click");	0
7979106	7979061	Efficient way to extract double value from a List<string> in C#	double[] dGraphPoints = sGraph.Split("/m")\n                              .Select(s => s.Trim())\n                              .Where(s => !string.IsNullOrEmpty(s))\n                              .Select(s => Double.Parse(s))\n                              .ToArray()	0
1671013	1670992	Repeat Forever a If Function	string Command;\nwhile (true) {\n  Command = Console.ReadLine();\n  if (Command == "About") {\n    Console.WriteLine("This Operational System was build with Cosmos using C#");\n    Console.WriteLine("Emerald OS v0.01");\n  }\n}	0
349575	349087	how to check status of checkboxes in gridview columns on click of button	function checkBoxselectedornot()\n{\n\n       var frm=document.forms['aspnetForm'];\n       var flag=false;\n       for(var i=0;i<document.forms[0].length;i++)\n       {\n           if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)\n           {\n                 if(document.forms[0].elements[i].checked)\n                 {\n                      flag=true\n                 }  \n           }\n       } \n      if (flag==true)\n      {\n        return true\n      }else\n      {\n        alert('Please select at least one Event.')\n        return false\n      }\n\n}	0
5817997	5817847	Schema from stored procedure	public static DataTable SchemaReader(string tableName) \n{      \n  string sql = "MySP";//replace this with your store procedure name      \n  conn.Open();      \n  SqlCommand cmd = new SqlCommand(sql, conn);\n  cmd.CommandType = CommandType.StoredProcedure;      \n  SqlDataReader reader = cmd.ExecuteReader();       \n  DataTable schema = reader.GetSchemaTable();       \n  reader.Close();      \n  conn.Close();      \n  return schema; \n}	0
22038051	22037928	Take 1 inside GroupBy in Linq	var sData = vehicle.GsmDeviceLogs\n              .Where(gs => gs.Speed > zeroSpeed && !gs.DigitalInputLevel1)\n              .OrderBy(gs => gs.DateTimeOfLog)\n              .GroupBy(gs => gs.DateTimeOfLog)\n              .Select(gs => gs.First())\n              .ToList();	0
33252492	33252105	Inside a switch statement, is there any way to refer to the value being switched?	var op = eqtn[curidx];\nswitch (op)\n{\n    ...	0
2497124	2497113	Compiler optimization of repeated accessor calls	accessCount++	0
3823788	3823544	xml serialization specify xmlelement and xmlattribute together	[XmlRoot("Book")]\npublic class Book\n{\n   [XmlAttribute]\n   public string Title;\n\n   [XmlElement]\n   public Publisher Publisher;\n}\n\n[Serializable]\npublic class Publisher\n{\n  [XmlText]\n  public string Value;\n\n  [XmlAttribute]\n  public string Reference;\n}	0
21238177	21137325	Show only the meetings where the user is the organizer with EWS	if (organizator == address.Address)	0
10696714	10696521	Clarification on Build Action	private void ExtractFromAssembly()\n{\n    string strPath = Application.LocalUserAppDataPath + "\\MyFile.db";\n    if (File.Exists(strPath)) return; // already exist, don't overwrite\n    Assembly assembly = Assembly.GetExecutingAssembly();\n    //In the next line you should provide NameSpace.FileName.Extension that you have embedded\n    var input = assembly.GetManifestResourceStream("MyFile.db");\n    var output = File.Open(strPath, FileMode.CreateNew);\n    CopyStream(input, output);\n    input.Dispose();\n    output.Dispose();\n    System.Diagnostics.Process.Start(strPath);\n}\n\nprivate void CopyStream(Stream input, Stream output)\n{\n    byte[] buffer = new byte[32768];\n    while (true)\n    {\n        int read = input.Read(buffer, 0, buffer.Length);\n        if (read <= 0)\n            return;\n        output.Write(buffer, 0, read);\n    }\n}	0
4653071	4653049	Specify Double-Click event for a Control in Visual Studio Designer	[DefaultEvent("DoubleClick")]\npublic class MyClass {\n\n    public event EventHandler DoubleClick;\n\n}	0
29361627	29361007	How to check whether the logged-in user is interactive or idle in wpf application	var timer = new DispatcherTimer\n    (\n    TimeSpan.FromMinutes(5),\n    DispatcherPriority.ApplicationIdle,// Or DispatcherPriority.SystemIdle\n    (s, e) => { mainWindow.Activate(); }, // or something similar\n    Application.Current.Dispatcher\n    );	0
10211375	10211237	Changing the sizemode of a background image in picturebox	whatever.BackgroundImageLayout = ImageLayout.Stretch	0
34322450	34322370	Accessing a property of a subclass in C#	public class PagedListArgs\n{\n     public PagedListArgs(){\n         MyParts = new DataViewParts();\n     }\n\n     public DataViewParts MyParts { get; set; }\n\n     public class DataViewParts\n     {\n         private string _type;\n         public string Type\n         {\n             get { return _type; }\n             set { _type = value; }\n         }\n\n         private string _filter;\n         public string Filter\n         {\n             get { return _filter; }\n             set { _filter = value; }\n         }  \n     }\n}	0
7854838	5028926	Run Selenium tests in multiple browsers one after another from C# NUnit	using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing OpenQA.Selenium.IE;\nusing System.Threading;\n\nnamespace SeleniumTests \n{\n    [TestFixture(typeof(FirefoxDriver))]\n    [TestFixture(typeof(InternetExplorerDriver))]\n    public class TestWithMultipleBrowsers<TWebDriver> where TWebDriver : IWebDriver, new()\n    {\n        private IWebDriver driver;\n\n        [SetUp]\n        public void CreateDriver () {\n            this.driver = new TWebDriver();\n        }\n\n        [Test]\n        public void GoogleTest() {\n            driver.Navigate().GoToUrl("http://www.google.com/");\n            IWebElement query = driver.FindElement(By.Name("q"));\n            query.SendKeys("Bread" + Keys.Enter);\n\n            Thread.Sleep(2000);\n\n            Assert.AreEqual("bread - Google Search", driver.Title);\n            driver.Quit();\n        }\n    }\n}	0
32087656	32086870	Get window state change notifications from another pocess	AutomationElement windowElement = AutomationElement.FromHandle(WindowHandle);\nif(windowElement != null)\n{\n            System.Windows.Automation.Automation.AddAutomationPropertyChangedEventHandler(\n                    windowElement,\n                    System.Windows.Automation.TreeScope.Element, this.handlePropertyChange,\n                    System.Windows.Automation.AutomationElement.BoundingRectangleProperty);\n}\n\n    private void handlePropertyChange(object src, System.Windows.Automation.AutomationPropertyChangedEventArgs e)\n    {\n        if(e.Property == System.Windows.Automation.AutomationElement.BoundingRectangleProperty)\n        {\n            System.Windows.Rect rectangle = e.NewValue as System.Windows.Rect; \n            //Do other stuff here\n        }\n    }	0
22734352	22734312	Converting my generic form variable into a specific type of form	GeFoss.TextEdit temp = (GeFoss.TextEdit)myFORM;	0
13544470	13544425	How can I replace a word in a txt file in C#	File.WriteAllText(fileName, File.ReadAllText(fileName).Replace(word1, word2));	0
10281513	10280617	C# Chart Control serie is covered by custom label	public HitTestResult HitTest (\nint x,\nint y,\nChartElementType requestedElement\n)	0
18094970	18094786	extract data from json in asp.net c#	Task task = project.tasks.FirstOrDefault(t=> t.id == "tmp_fk1345624806538");	0
12766556	12764890	Getting full property name using ModelMetadata	var propertyName = ExpressionHelper.GetExpressionText(expression).	0
31921327	31912831	How to allow different login ID to be logged into the application for once in the same local computer	public void SingleInstanceHandler()\n{\n    Process[] procList = Process.GetProcesses();\n\n    foreach(Process proc in procList)\n    {\n      if (!string.IsNullOrEmpty(proc.MainWindowTitle))\n      {\n        if (proc.MainWindowTitle == windowTitle) \n        {\n          //Show relevant message\n          Application.Current.Shutdown();\n        }\n      }\n    }\n}	0
29751465	29750223	C# comparing two object if they are equal	public override bool Equals(object obj)\n{\n    Test test = obj as Test;\n    if (obj == null)\n    {\n        return false;\n    }\n    return Value == test.Value &&\n        String1 == test.String1 &&\n        String2 == test.String2;\n}	0
29075554	29075458	Select from datatable with where clause	dt.where(e => {check something}).Select({select code here})	0
27954372	27953655	Create a list of all available assets by checking previous entries in table	using (TheContext db = new TheContext())\n{\n    List<Computer> compQuery = (from compTrack in db.compTracking\n                               where compTrack.AssetActionId == 1  // or compTrack.AssetAction.ID presumably\n                               select compTrack.Computer).ToList();\n}	0
6871150	6866692	How to invalidate page to enforce rendering again?	(Application.Current.Resource["myColor"] as SolidColorBrush).Color = Colors.Red;	0
7964050	7964015	Maximum and Minimum values in a PointF[] array	Point \n  min = first item in array, \n  max = first item in array;\n\nforeach (item in array of points)\n{\n  min.x = Math.Min (min.x, item.x)\n  min.y = Math.Min (min.y, item.y)\n  max.x = Math.Max (max.x, item.x)\n  max.y = Math.Max (max.y, item.y)\n}\n\n\n(min,max) are now the opposite corners of an axis aligned bounding box	0
19805283	19805181	Populating a list with table data	var query = (from b in db.Blogs\n                orderby b.Title\n                select b.Title).ToList();\n\nforeach (var item in query)\n        {\n            mylistbox.items.add(item );\n        }	0
5396047	5395992	Exporting application to be runnable	mono my.exe	0
11591390	11560297	count number of rows in excel using c#	var query = from row in dTable.AsEnumerable()\n             where ((row.Field<string>("columnname")).contains("VPUDB")\n                   || (row.Field<string>("columnname")).contains("VPULN"))\n\n      select row;	0
29609658	29609447	Hide Datalist Item if checkbox value in database is checked	SqlCommand com = new SqlCommand("Select Image,UserName,Description,Private,CompValue FROM FutureProjTbl WHERE Private == 'N'", connection.con);	0
21993388	21992869	wpf how to get canvas from itemspaneltemplate in code behind?	Canvas foundCanvas =UIHelper.FindChild<Canvas>(Application.Current.MainWindow, "MarkerCanvas");	0
18814364	18814109	EF many-to-many relationship with specific scheam	modelBuilder.Entity<Role>()\n    .HasMany(p => p.SystemKeys)\n    .WithMany(p => p.Roles)\n    .Map(p => p.ToTable("SystemKeyRole", "ACL"));	0
8206883	8206860	How to return nullable datetime in ef linq query	data = (from t in db.Table\n    where ...\n    select new\n    {\n        Property = t.Table2.OrderByDescending(x => x.DateField).select(x=> x.DateField).FirstOrDefault()\n    });	0
18142191	18141928	Create xml rootNode via c#	XmlDocument doc = new XmlDocument();\nXmlSchemaSet xss = new XmlSchemaSet();\nxss.Add("cim", "http://iec.ch/TC57/2009/CIM-schema-cim14#");\nxss.Add("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");\ndoc.Schemas = xss;\nXmlNode rootNode = doc.CreateElement("rdf:RDF"); // This overload assumes the document already knows about the rdf schema as it is in the Schemas set\ndoc.AppendChild(rootNode);	0
14716303	14715826	How to override save behavior of object in Entity Framework	class MyModel\n{\n    public string Text { get; set; }\n}\n\nclass MyViewModel : MyModel\n{\n    public new string Text\n    {\n        get { return base.Text; }\n        set { base.Text =value.ToUpper(); }\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        MyViewModel mvm = new MyViewModel();\n        mvm.Text = "hello there";\n        var s = ((MyModel) mvm).Text; // "HELLO THERE"\n    }\n}	0
25956221	25677410	How do White work on already running application?	Application application;\nProcess[] processes = Process.GetProcessesByName(@"someapplication.exe");\nif (processes.Length == 0)\n  application = Application.Launch(@"someapplication.exe");\nelse\n  application = Application.Attach(@"someapplication.exe");	0
11360382	11351630	Making 1 page pdfs from a multipage pdf using itextsharp	using (FileStream fs = new FileStream(argPdfFileName, FileMode.Create))\n{\n  Document doc = new Document(argReader.GetPageSize(argPdfPageNumber));\n  PdfCopy copy = new PdfCopy(doc, fs);\n  doc.Open();\n  PdfImportedPage page = copy.GetImportedPage(argReader, argPdfPageNumber);\n  copy.AddPage(page);\n  doc.Close();\n}	0
13445915	13445751	smtp server requires authentication but I believe it already has it	client.Port = 587	0
18528668	18528603	Linq to xml extension method with filter	xElement\n.Element("RES")\n.Elements("R")\n.Where\n(\n    x=>\n    x\n    .Elements("MT")\n    .Where\n    (\n        z=>\n        z.Attribute("N").Value == "IsSpecialArticle"\n    )\n    .Select\n    (\n        z=>\n        z.Attribute("V").Value\n    ).SingleOrDefault() == "true"\n)	0
12431122	12149801	Difficulty subscribing to SelectedItem property as input to SProc in EF4, Generic Repository Pattern/MVVM	public static void ReturnExtendedPartProperties(MainWindowVM mainWindowVM)\n  {\n       mainWindow.ReturnAttsPerPn_Result = new ObservableCollection<ReturnAttsPerPn_Result>();\n       using (var myEntities = new MyEntities())\n       {\n             var results = myEntities.ReturnAttsPerPn(mainWindowVM.SelectedPart.PnID)\n             if (mainWindowVM.SelectedPart != null)\n             {\n                  mainWindowVM.ReturnAttsPerPn_Result.Clear();\n                  foreach (ReturnAttsPerPn_Result attresult in results)\n                  {\n                        mainWindowVM.ReturnAttsPerPn_Result.Add(attresult);\n                  }\n              } \n       }\n }	0
11773195	11772871	Member with the same signature is already declared	public interface IViewModel\n{\n}\n\npublic class ViewModelOne : IViewModel\n{\n}\n\npublic class ViewModelTwo : IViewModel\n{\n}\n\n\npublic class SiteMapper \n{\n    private Dictionary<Site, List<IViewModel>> map { get; set; }\n\n    public void Register(Site site, IViewModel viewModel)\n    {\n        // Add combination to map\n    }\n\n    public List<IViewModel> MapDomainToViews(Site site) \n    {\n        if (map.ContainsKey(site))\n            return map[site];\n        else\n            ....\n    }\n}	0
17353605	17352918	Item in DropDownList	var selected = reader["causeID_1"].ToString();\n...\nvar index = CmbCausa1.FindString(selected);\nCmbCausa1.SelectedIndex = index;	0
26137034	26135985	How to club a week and day string like "21Fr" into DateTime format?	// parse the input\nstring input = "21Fr";\n// assuming week number is always 2 characters. e.g.: 01, 02, ..., 21, ...\nint weeks = int.Parse(input.Substring(0, 2));\n// assuming abbreviated day names like this\nstring[] abbrDayNames = { "Su", "Mo", "Tu", "We","Th", "Fr", "Sa" };\nint dayOfWeekValue = Array.IndexOf(abbrDayNames, input.Substring(2));\nDayOfWeek dayOfWeek = (DayOfWeek)dayOfWeekValue;\n\n// now let's build the DateTime\n// start from first day of year, 6:00 AM\nDateTime parsed = new DateTime(DateTime.Now.Year, 1 ,1, 6, 0, 0);\n// add first part, weeks\nparsed = parsed.AddDays((weeks - 1) * 7);\n// reset to first day of week\nparsed = parsed.AddDays(-(int)parsed.DayOfWeek);\n// then add the second part, day of week\nparsed = parsed.AddDays((int)dayOfWeek);	0
28731662	28731363	Setting WPF Window Background Image at App Start Up	imgBackground.ImageSource = new BitmapImage(\n    new Uri("pack://application:,,,/Resources/Background.png"));	0
32196633	32196612	using Thread with Parameter as Object	var thread = new Thread(() => Method(parameter));\nthread.Start();	0
13443575	13443369	Get a Font's Metrics in Pixels	descentPixel = font.Size * descent / fontFamily.GetEmHeight(FontStyle.Regular);	0
7651979	7651398	regex for {productName}-{version}-{X}-of-{Y}.EXE in c#	Regex.IsMatch(subjectString, @"/\w+-(?:\d+\.){3}\d+-\d+-of-\d+.EXE/",\n                                                   RegexOptions.Multiline)	0
4869728	4869673	Is it safe to rely on Func.GetHashCode for a set of Func definitions?	Dictionary<T,U>	0
29424721	29424549	C# Editing a text file	for (int i = 0; i < lines.Length; i++)\n        {\n            string[] lineData = lines[i].Split(',');//split the line into an array ["Smith" ,"4567" ,"Food" ,"$2.00" ,"Pending" ,"4/2/2015 6:26:37 PM"]\n            if (lineData[0] == "Smith")//0 is the index of the client name\n            {\n                lineData[3] = "$4.00";//modifie the value\n                lines[i] = String.Join(",", lineData);\n                File.WriteAllLines("../../textFile/ExpenseReportingData.txt", lines);\n            }\n        }	0
20155296	20155272	How to get around Cannot Enumerate More than once using two queries	var firstQuery = (from r in db.SomeProcedure(Id)\n                   select new MyClass\n                   {\n                        Id = r.Id,\n                        Name = r.Name,\n                        Company= r.Company,\n                        Title = r.Title\n                   }).ToList();\n\n    var secondQuery = (from d in firstQuery\n                      group d by d.Title into groupedTitles\n                     select new MyClass2\n                     {                                 \n                         Title = groupedTitles.Key,  //How To include the Id                                  \n                     });\n\n      List<MyClass> mClass = firstQuery;\n      List<MyClass2> mClass2 = secondQuery.ToList();	0
21202827	21202761	Trigger a click sender in another method	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n{\n    OnActivity_Click(this.btn1, null);\n}	0
23322656	23322591	WPF: Trying to add a class to Window.Resources	public class SlidersToColorConverter : IMultiValueConverter	0
32764524	32763270	Take hex code from specified offset - C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        const string path = @"C:\temp\test.txt";\n        static void Main(string[] args)\n        {\n            long offset = 25;\n            long key = offset - (offset % 16);\n            using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n            {\n                BinaryReader brFile = new BinaryReader(fileStream);\n                fileStream.Position = key;\n\n                List<byte> offsetByte = brFile.ReadBytes(16).ToList();\n\n                string offsetString = string.Join(" ", offsetByte.Select(x => "0x" + x.ToString("x2")).ToArray());\n            }\n        }\n    }\n}???	0
14349124	14348660	Update Datagrid when ItemsSource changes	public MainViewModel()\n{\n    initializeload();\n    timer.Tick += new EventHandler(timer_Tick);\n    timer.Interval = new TimeSpan(0, 0, 15);\n    timer.Start();\n}\n~MainViewModel()\n{\n    Dispose(false);\n}\npublic void Dispose()\n{\n    Dispose(true);\n    GC.SuppressFinalize(this);\n}\nprotected virtual void Dispose(bool disposing)\n{\n    if (!disposed)\n    {\n        if (disposing)\n        {\n            timer.Stop();\n            timer.Tick -= new EventHandler(timer_Tick);\n        }\n        disposed = true;\n    }\n}\n\nprivate void timer_Tick(object sender, EventArgs e)\n{\n    try \n    {\n        SystemStatusData.Clear();\n        initializeload();\n    } \n    catch (...) \n    {\n        // Problem best to stop the timer if there is an error...\n        timer.Stop();\n    }\n}\n\nprivate bool disposed;\nprivate DispatcherTimer timer = new DispatcherTimer();	0
25201683	25201043	I have a code in c# were in header text there is a checkbox and i click on the text box below check boxes should be clicked	private void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n    //customized global checkbox  in header\n    int iCheckBoxColumnIndex = 7; // index of check box cell\n    bool bValue = checkBox1.Checked;\n    for (int iRow = 0; iRow < dataGridView1.Rows.Count; iRow++)\n    {\n        if (iRow == dataGridView1.NewRowIndex)\n            continue;\n        dataGridView1.Rows[iRow].Cells[iCheckBoxColumnIndex].Value = bValue;\n        checkValue(iRow, bValue);\n    }\n}	0
29101738	22899214	how to encrypt a file While downloading	FileStream fsInput = new FileStream(sInputFilename, \n                    FileMode.Open, \n                    FileAccess.Read);\n\n    FileStream fsEncrypted = new FileStream(sOutputFilename, \n                    FileMode.Create, \n                    FileAccess.Write);	0
12418109	12415438	Signing a string with HMAC-MD5 with C#	byte[] keyInBytes = Encoding.UTF8.GetBytes(key);	0
13859539	13858565	Check only one ListViewItem at time	// I need to know the last item checked\nprivate ListViewItem lastItemChecked;\n\nprivate void listView_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    // if we have the lastItem set as checked, and it is different\n    // item than the one that fired the event, uncheck it\n    if (lastItemChecked != null && lastItemChecked.Checked\n        && lastItemChecked != listView.Items[e.Index] )\n    {\n        // uncheck the last item and store the new one\n        lastItemChecked.Checked = false;\n    }\n\n    // store current item\n    lastItemChecked = listView.Items[e.Index];\n}	0
24281174	24275301	Where are the default WPF Control Templates?	private string getTemplate(Control control)\n{\n    StringBuilder stringBuilder = new StringBuilder();\n\n    XmlWriterSettings xmlSettings = new XmlWriterSettings();\n    xmlSettings.Indent = true;\n\n    using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, xmlSettings))\n    {\n        XamlWriter.Save(control.Template, xmlWriter);\n    }\n    return stringBuilder.ToString();\n}	0
8014143	8012137	UIBarButtonItem with Custom View	UIButton l__objCustomUIButton = UIButton.FromType(UIButtonType.Custom);\n//l__objCustomUIButton.SetImage(UIImage.FromFile("your button image"), UIControlState.Normal);\nl__objCustomUIButton.TouchUpInside += delegate { this.WeatherButtonEvent(); };\nUIBarButtonItem l__objButton = new UIBarButtonItem(l__objCustomUIButton);	0
1588146	1587845	Reuse imagemagick process instance in asp.net app	convert.exe ( first_image.jpg ...some options... -write first_image_small.png +delete ) ( ... second image ... ) last_image ... options ... last_image_small.png	0
21001487	20999252	Convert a TimeSpan Formatstring to an InputMask	//using System.Text.RegularExpressions;\n\nstring input = @"hh\:mm\:ss\.fff"; //i suppose it's FormatString in your case, don't know the MaskedTextBox\nstring output = Regex.Replace(input, "[a-zA-Z]","0");	0
21261812	21261570	Remove selected item from ListView from ImageFileCollectionViewModel	for (int i = 0; i < copyOfSelection.Count; i++)\n{\n    copyOfSelection.RemoveAt(i);\n    File.Delete(destination_dir);        \n}	0
25164708	25164376	Change WP8 App Background in C#	public static void SetAppBackground(string imageName)\n{\n    var imageBrush = new ImageBrush\n    {\n        ImageSource = new BitmapImage(new Uri(imageName, UriKind.Relative))\n    };\n    App.RootFrame.Background = imageBrush;\n}	0
23262927	23262504	How to custom serialize a property?	[Serializable]\npublic class Feed\n{\n    public string id { get; set; }\n    public string id_str { get; set; }\n    public User user  { get; set; }\n    public string created_at \n    { \n        get { return CreatedAt.ToString(FORMAT); }\n        set { CreatedAt = DateTime.ParseExact(value, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture); }\n    }\n    [NotSerialized]\n    public DateTime CreatedAt { get; set; }\n}	0
14524132	14524007	Accessing the header in OpenReadCompleted Method on windows phone 8	WebClient c = (WebClient)sender;\n        string id = c.Headers["NewsID"];	0
25545419	25545270	How to format double in C# to such format?	string.Format(CultureInfo.InvariantCulture, "{0:0.0}",  2.0d);	0
12283299	12283130	Better way to remove items from combobox - c#	comboBox.Items.AddRange(all.Where(x => x != "abc").ToArray());	0
22437093	22437038	How to replace a string with another	if (yourString.Contains(".")) { youString = yourString.Replace(".", ","); }	0
17830148	17829533	How to stop server process during a post on client side?	long process	0
2610802	2610779	Use LINQ and lambdas to put string in proper case	TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;\n\nstring result = string.Join(" ", input.Split(' ')\n                                      .Select(word => textInfo.ToTitleCase(word))\n                                      .ToArray());	0
2472540	2472316	Using C# & SMO, how do I add a backup device to a SQL Server?	Server server = new Server("localhost");\nBackupDevice newDevice = new BackupDevice();\nnewDevice.Parent = server;\nnewDevice.Name = "newDevice";\nnewDevice.BackupDeviceType = BackupDeviceType.Disk;\nnewDevice.PhysicalLocation = "c:\temp\newdevice.bak";\nnewDevice.Create();	0
29073447	29072906	Silverlight set cursor to Cursors.Wait	ThreadingHelper.Invoke(() => {\n                        var page = (MainPage)Application.Current.RootVisual;\n                        page.Cursor = cursorStyle;\n                    });	0
13057981	13057928	Convert TimeSpan.TotalMilliseconds to datetime and format it as hour:minute	TimeSpan ResponseTimeSpan = new TimeSpan(0, 0, 0, (int)ResponseTime);\n\nstring ResponseTimeDisplay = ResponseTimeSpan.ToString();	0
866878	866867	Is there a way to count the number of seconds since bootup?	System.Environment.TickCount	0
6494025	6473989	How to deal with double quotes in JavaScript when referencing a C# variable	onclick="copyDescription('<%# Server.HtmlEncode(Eval("Description").ToString()) %>');"	0
22873872	22827638	Even with a valid access_token with right set of permissions, FacebookClient does not get ALL of the photos for given album id	var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions{...};\nfacebookOptions.Scope.Add("email");\nfacebookOptions.Scope.Add("user_about_me");\nfacebookOptions.Scope.Add("user_events");\nfacebookOptions.Scope.Add("user_groups");\nfacebookOptions.Scope.Add("user_likes");\nfacebookOptions.Scope.Add("user_photos");\nfacebookOptions.Scope.Add("user_videos");\nfacebookOptions.Scope.Add("user_checkins");\nfacebookOptions.Scope.Add("user_friends");\nfacebookOptions.Scope.Add("user_location");\nfacebookOptions.Scope.Add("user_photo_video_tags");\nfacebookOptions.Scope.Add("user_actions.music");\nfacebookOptions.Scope.Add("user_activities");\napp.UseFacebookAuthentication(facebookOptions);	0
13231670	13230989	Selenium webdriver script failing to locate button even with ID	driver.findElement(By.id("action1")).submit();	0
11477646	11477558	How do I return a list from a BackgroundWorker for use in the next line of code in the UI thread?	private void SearchBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    this.searchProgressTimer.Stop();\n    this.searchProgressBar.Value = 0;\n    this.words = (List<String>)e.Result;\n\n    foreach (String word in this.words) // BREAKPOINT HERE\n        MessageBox.Show(word);\n}	0
20570607	20570486	Serialization and deserialization of an int matrix c#	public static T[,] ToMultiD<T>(this T[][] jArray)\n    {\n        int i = jArray.Count();\n        int j = jArray.Select(x => x.Count()).Aggregate(0, (current, c) => (current > c) ? current : c);\n\n\n        var mArray = new T[i, j];\n\n        for (int ii = 0; ii < i; ii++)\n        {\n            for (int jj = 0; jj < j; jj++)\n            {\n                mArray[ii, jj] = jArray[ii][jj];\n            }\n        }\n\n        return mArray;\n    }\n\n    public static T[][] ToJagged<T>(this T[,] mArray)\n    {\n        var cols = mArray.GetLength(0);\n        var rows = mArray.GetLength(1);\n        var jArray = new T[cols][];\n        for (int i = 0; i < cols; i++)\n        {\n            jArray[i] = new T[rows];\n            for (int j = 0; j < rows; j++)\n            {\n                jArray[i][j] = mArray[i, j];\n            }\n        }\n        return jArray;\n    }	0
27609058	27608992	Self-updating WPF ProgressBar in c#	// In constructor\nProgressBarControl()\n{\n    this.Loaded += async (o,e) =>\n    {\n        double v = progressBar1.Minimum; \n        while (v < progressBar1.Maximum)\n        {\n            progressBar1.Value = v;\n            ++v;\n            await Task.Delay(100); // Wait 100ms\n        }\n    };\n}	0
14646613	14645964	Deserializing XML from String	string xml = "<StatusDocumentItem xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><DataUrl/><LastUpdated>2013-02-01T12:35:29.9517061Z</LastUpdated><Message>Job put in queue</Message><State>0</State><StateName>Waiting to be processed</StateName></StatusDocumentItem>";\nvar serializer = new XmlSerializer(typeof(StatusDocumentItem));\nStatusDocumentItem result;\n\nusing (TextReader reader = new StringReader(xml))\n{\n    result = (StatusDocumentItem)serializer.Deserialize(reader);\n}\n\nConsole.WriteLine(result.Message);\nConsole.ReadKey();	0
28454047	28453871	c# Pass data from Data table into another form	public partial class Form1 : Form\n    {\n        public Form1()\n        {\n          //code that you have already wrote \n          Form2 f2 = new Form2(dTable);\n          f2.ShowDialog();\n        }\n     }\npublic partial class Form2 : Form\n    {\n        public Form2(Datatable table)\n        {\n            //Do whatever you want with this table\n            //Example \n            label1.Text = table.Rows[0][0].ToString();\n        }\n    }	0
18265740	18265728	DBSet how to multiple update?	var EPins = (from EPin in db.Pins\n            where\n                (EPin.UserID == null && EPin.CC == 5000)\n            select EPin).Take(5);\n\nforeach (var item in Epins.ToList())\n{\n    item.OrderID = OrderID;\n    item.UserID = intUserID;\n}\ndb.SaveChanges();	0
8555685	8555651	Is it possible to use MSDN's LinkedList class to make a list where one parent node points to multiple children?	LinkedListNode<T>	0
22437435	22437324	convert time from server to local time in windows phone 8	var date = DateTime.Parse("2014-03-16 07:07:25 UTC");\nvar localtime = date.ToLocalTime();	0
1563046	1563037	Code Rush: Keyboard Shortcut to Change Member Scope	ALT + up/down arrow	0
33981180	33928716	Get all model types	var dcx = new MyDbContext();\nvar objContext = ((IObjectContextAdapter)dcx).ObjectContext;\nvar types = db.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Select(x => Type.GetType(x.FullName));\nforeach (var t in lst) {\n...	0
12759399	12757772	How can I insert products into combo box by loading form	XElement xElement = XElement.Load(@"XMLFile1.xml");\n\n            var producttypes = from ptypes in\n                                   xElement.Descendants("product")\n                               let xAttribute = ptypes.Attribute("type")\n                               where xAttribute != null\n                               select xAttribute.Value;\n\n            comboBox1.Items.Clear();\n            foreach (var ptypes in producttypes)\n            {\n            comboBox1.Items.Add(ptypes);\n            }	0
4253997	4253914	export gridview to excel sheet	Response.ContentEncoding = Encoding.Unicode;\nResponse.BinaryWrite(Encoding.Unicode.GetPreamble());	0
33090377	33090110	Give a name to a writeable bitmap	properties.Title = name;\nvar bitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);\nbitmap.SetValue(NameProperty, (string)properties.Title);	0
4905961	4849671	How can I turn off the x-axis labels in an ASP.NET Chart Control?	Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;	0
9280111	9279769	Splash Screen Timer	SplashScreen splash = new SplashScreen("/Images/Agrar.png");\n    splash.Show(false);\n    Thread.Sleep(10000);\n    splash.Close( TimeSpan.FromSeconds(20)); //fade out over 20 seconds	0
3646424	3646407	How would I wait for multiple threads to stop?	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
21556518	21551923	How do I compare two DynamicJsonObjects to check they are equal?	public static bool AreJsonObjectsEqual(DynamicJsonObject obj1, DynamicJsonObject obj2)\n{\n    var memberNamesNotEqual = obj1.GetDynamicMemberNames().Except(obj2.GetDynamicMemberNames()).Any();\n    if (!memberNamesNotEqual)\n    {\n       dynamic dObj1 = (dynamic)obj1;\n       dynamic dObj2 = (dynamic)obj2;\n       foreach (var memberName in obj1.GetDynamicMemberNames()){\n           if(dObj1[memberName] != dObj2[memberName]) return false\n       }\n       return true\n    }\n    return memberNamesNotEqual;\n}	0
20542022	16892702	The given value of type String from the data source cannot be converted to type bigint of the specified target column	bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(0, 1));\nbulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(1, 2));\nbulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(2, 3));\nbulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(3, 6)); //look here, index is different\nbulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(4, 8)); //and again\nbulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(5, 9));	0
26405752	26403432	C# Winforms : Find out when a label goes to next line	// Imagining you got your blob of data, spaces and all, in one hit.  \nstring blob = myWayOfGettingData;\ntextBox1.Text = blob;\nint lineIndex = 0;\nstring[] allLines = new string[textBox1.Lines.Count()];\nallLines = textBox1.Lines;\nforeach (string line in textBox1.Lines)\n{\n    if (!string.IsNullOrEmpty(line))\n    {\n         allLines[lineIndex] = "$" + allLines[lineIndex];       \n     }\n     lineIndex++;\n }\n textBox1.Lines = allLines;	0
15824068	15823864	Error when displaying data in a datalist from sqldatasource in asp project	Products.Name as Products_Name	0
17003302	17003282	Contructor is inaccessible due to its protection level	public class CheckTexture\n{   \n    Thread Search;\n    public CheckTexture()\n    {\n        Search = new Thread(Scan);\n        Search.Start();\n    }	0
16428723	16428389	Creating An Ambient Property That Inherits From a Parent's Property	public class MyControl : Control\n{\n\n    private Font myOtherFont;\n    public Font MyOtherFont\n    {\n        get\n        {\n            if (this.myOtherFont == null)\n            {\n                if (base.Parent != null)\n                    return base.Parent.Font;\n            }\n\n            return this.myOtherFont;\n        }\n        set\n        {\n            this.myOtherFont = value;\n        }\n    }\n\n    private bool ShouldSerializeMyOtherFont()\n    {\n        if (base.Parent != null)\n            if (base.Parent.Font.Equals(this.MyOtherFont))\n                return false;\n\n        if (this.MyOtherFont == null)\n            return false;\n\n        return true;\n    }\n\n    private void ResetMyOtherFont()\n    {\n        if (base.Parent != null)\n            this.MyOtherFont = base.Parent.Font;\n        else\n            this.MyOtherFont = Control.DefaultFont;\n    }\n}	0
12989123	12989029	How to make Visual C# studio recognize key input	this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);	0
17855620	12190672	Can i password encrypt SQLite database?	//if the database has already password\ntry{\n            string conn = @"Data Source=database.s3db;Password=Mypass;";\n            SQLiteConnection connection= new SQLiteConnection(conn);\n            connection.Open();\n            //Some code\n            connection.ChangePassword("Mypass");\n            connection.Close();\n    }\n//if it is the first time sets the password in the database\ncatch\n    {\n            string conn = @"Data Source=database.s3db;";\n            SQLiteConnection connection= new SQLiteConnection(conn);\n            connection.Open();\n            //Some code\n            connection.ChangePassword("Mypass");\n            connection.Close();\n    }	0
31309112	31308569	Consolidate similar methods into a single method to reduce duplication	using System.Collections.Generic;\nnamespace Test\n{\n    class Program\n    {\n        static void Main()\n        {\n            Dictionary<string, Object> dictionary = new Dictionary<string, string>();\n\n            dictionary.Add("cat", "one");\n            dictionary.Add("dog", "two");\n            dictionary.Add("llama", "three");\n            dictionary.Add("iguana", "four");\n\n            var test1 = GetWhatEver(dictionary, "llama");\n            var test2 = GetWhatEver(dictionary, "llama");\n            var test3 = GetWhatEver(dictionary, "llama");\n        }\n\n         static Object GetWhatEver(Dictionary<string, Object> dict, string key_to_find)\n        {\n            foreach (var kvp in dict)  \n            {\n                if (kvp.Key == key_to_find)\n                {return kvp.Value;}\n            }\n            return null;\n        }\n\n    }\n}	0
3942973	3923847	How to return fully populated objects using FileHelpers for partially complete data?	[DelimitedRecord(",") ]\n[IgnoreFirst(1)] \npublic class Product\n:INotifyRead\n{\n    public int? ID;\n    public string Description;\n\n    [FieldConverter(ConverterKind.Decimal)]\n    public decimal? Val;\n\n    private static Product Previuous;\n\n    public void AfterRead(EngineBase engine, string line)\n    {\n        if (!ID.HasValue && Previous != null)\n              this.ID = Previus.ID;\n\n        if (!Val.HasValue && Previous != null)\n              this.Val= Previus.Val;\n\n        Previuous = this;\n    }\n}	0
6761367	6760764	show only the selected column in the datagridview from xml using c#	dgv.Columns["lastname"].Visible = false;	0
13983497	13983353	Deleting registry key based on one of it's values?	string[] CheckItemsArray = new string[checkedListBox1.CheckedItems.Count+1];\n        checkedListBox1.CheckedItems.CopyTo(CheckItemsArray, 0);\n\n        foreach (string CheckedItem in CheckItemsArray)\n        {\n            if (CheckedItem != null)\n            {\n                //your deleting logic here\n\n            }\n        }	0
23202342	23202096	Displaying data in the Data Grid View? Access, C#	foreach (DataRow currentRow in itemDS.Tables[0].Rows)\n{\n    //Decalare variables for item quantity and price\n    var itemQuant = Convert.ToDouble(currentRow[1]);\n    var priceEach = Convert.ToDouble(currentRow[3]);\n\n    //Multiply the item quantity by the item price\n    double subTotal = itemQuant * priceEach;\n\n\n    // add to data grid view\n    invoiceDataGridView.Rows.Add(currentRow[1].ToString(), currentRow[2].ToString(), currentRow[3].ToString(), subTotal);\n\n    //do this for each row\n    colTotal += subTotal;\n}	0
12182745	12182726	First SQL result dropped from results	dr.Read();	0
18092017	18091527	How do I modify this join in accordance with a model change involving inheritance?	query = query.Join(db.Reports,\n                x => new\n                {\n                    T = (Reportable)x.SourceUser,\n                    x.TargetReportable\n                },\n                x2 => new\n                {\n                    SourceUser = x2.TargetReportable,\n                    TargetReportable = (Reportable)x2.SourceUser\n                },\n                (x, x2) => new { x, x2 }).Where(f => (f.x.SourceUser == user)).Select(p => p.x);	0
254674	254669	What does placing a @ in front of a C# variable name do?	void Foo(int @string)	0
25847899	25847476	asp.net - How to use variable in Sql?	private void BindGrid()\n{\n    var CurrentUser = User.Identity.Name;\n    string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;\n    using (SqlConnection con = new SqlConnection(constr))\n    {\n\n        if (CurrentUser != null)\n        {\n        using (SqlCommand cmd = new SqlCommand())\n            {\n                GridView GridView1 = LoginView3.FindControl("GridView1") as GridView;\n                cmd.CommandText = "select Id, Name from tblFiles WHERE email = @CurrentUser";\n                cmd.Parameters.Add("@CurrentUser", SqlDbType.NVarChar);\n                cmd.Parameters["@CurrentUser"].Value = User.Identity.Name;\n                cmd.Connection = con;\n                con.Open();\n                GridView1.DataSource = cmd.ExecuteReader();\n                GridView1.DataBind();\n                con.Close();\n\n            }\n        }\n    }\n}	0
17926910	17926640	Getting an XML element	XDocument xmlDoc = XDocument.Parse(xml);\nXNamespace  ns = xmlDoc.Root.GetDefaultNamespace();\nvar helloElem = xmlDoc.Root.Element(ns+ "hello");	0
4671255	4671048	Architecture of my application	public class ContextFactory {\n       private List<PrincipalContext> contexts = new List<PrincipalContext>();\n       public PrincipalContext GetPrincipalContext(ContextType contextType, string domainName)\n       {\n           PrincipalContext existingContext = contexts.First(item=>item.ContextType==contextType && \n              item.DomainName == domainName);\n           if (existingContext == null) {\n               existingContext = new PrincipalContext(contextType,domainName);\n               contexts.Add(existingContext);\n           }\n           return(existingContext);\n        }\n    }\n    public void Dispose()\n    {\n        foreach (PrincipalContext context in contexts) {\n            context.Dispose();\n        }\n     } \n}	0
7272091	7272020	How to get the string (of source-code) that generated a lambda-expression?	Expression<Func<double,double>> expr = x => x * x;\nstring s = expr.ToString(); // "x => (x * x)"	0
3005108	3005050	How to remove a string from Dictionary<>	List<String> list = new List<string>();\nforeach (DataRow row in dtcolumnsname.Rows)\n{\n    list.Add((string) row["ColumnName"]);\n}	0
2405984	2402119	SetScrollPos: scroll bar moving, but control content not updating	public void ScrollTo(int Position)\n    {\n        SetScrollPos((IntPtr)this.Handle, 0x1, Position, true);\n        PostMessageA((IntPtr)this.Handle, 0x115, 4 + 0x10000 * Position, 0);\n    }	0
5312777	5312630	how can i make a tablelayout invisible and then visible in winforms	PromotionTable.Visible=true;\nPromotionTable.Invalidate();\nmyForm.Refresh();	0
28529051	28527390	Create a circle avatar image in .net	public ActionResult Avatar()\n        {\n            using (var bitmap = new Bitmap(50, 50))\n            {\n                using (Graphics g = Graphics.FromImage(bitmap))\n                {\n                    g.Clear(Color.White);\n                    using (Brush b = new SolidBrush(ColorTranslator.FromHtml("#eeeeee")))\n                    {\n\n                        g.FillEllipse(b, 0, 0, 49, 49);\n                    }\n\n                    float emSize = 12;\n                    g.DrawString("AM", new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),\n                        new SolidBrush(Color.Black), 10, 15);\n                }\n\n                using (var memStream = new System.IO.MemoryStream())\n                {\n                    bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Png);\n                    var result = this.File(memStream.GetBuffer(), "image/png");\n                    return result;\n                }\n            }\n        }	0
29668854	29667012	Generating Unique Colors	public class UniqueColorGenerator {\n        private int _colorIndex;\n        private readonly int _offsetIncrement;\n\n        public UniqueColorGenerator() {\n            this._offsetIncrement = 1;\n        }\n\n        public UniqueColorGenerator( uint offsetIncrement ) {\n            this._offsetIncrement = ( int )offsetIncrement;\n        }\n\n        public Color Next() {\n            return Color.FromArgb( _colorIndex += _offsetIncrement );\n        }\n    }	0
26206207	26206161	Set a variable value from listbox in C#	private void Form1_Load(object sender, EventArgs e)\n    {\n        listBox1.Items.Add("9");\n        listBox1.Items.Add("15");\n        listBox1.Items.Add("27");\n\n        int x = int.Parse(listBox1.Items[0].ToString());\n        MessageBox.Show(x.ToString());\n\n    }\n\n    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        int x = int.Parse(listBox1.SelectedItem.ToString());\n        MessageBox.Show(x.ToString());\n    }	0
9306	9303	How do you retrieve selected text using Regex in C#?	int indexVal = 0;\nRegex re = new Regex(@"Index: (\d*)")\nMatch m = re.Match(s)\nif(m.Success)\n  indexVal = int.TryParse(m.Groups[1].toString());	0
616676	616629	Display "Wait" screen in WPF	public static void ForceUIToUpdate()\n{\n  DispatcherFrame frame = new DispatcherFrame();\n\n  Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render, new DispatcherOperationCallback(delegate(object parameter)\n  {\n    frame.Continue = false;\n    return null;\n  }), null);\n\n  Dispatcher.PushFrame(frame);\n}	0
2640941	2640920	Where to locate the unattend.xml schema	xsd.exe unattend.xml	0
7625726	7625631	C# custom json serialization	public string x { get { return a + b; } }	0
7438710	7438563	DataAnnotation with a configurable value?	[ConfigedRegularExpression("PasswordExpression")]	0
316016	316009	C# Best way to get folder depth for a given path?	Directory.GetFullPath().Split("\\").Length;	0
12395635	12393598	How to disable ReSharper ConvertToAutoProperty warning for specific properties?	// ReSharper disable ConvertToAutoPropertyWithPrivateSetter\nprivate int _id;\npublic int ID { get { return _id; } }\n// ReSharper restore ConvertToAutoPropertyWithPrivateSetter	0
26958594	26958398	Finding the max sum of successive random numbers in an array	public static void ShowLargestSum(int[] arr) {\n  int largest = arr[0], start = 0, end = 0;\n  for (int i = 0; i < arr.Length; i++) {\n    int sum = 0;\n    for (int j = i; j < arr.Length; j++) {\n      sum += arr[j];\n      if (sum > largest) {\n        largest = sum;\n        start = i;\n        end = j;\n      }\n    }\n  }\n  Console.WriteLine("first index: {0} (value: {1}), last index: {2} (value:{3}), total sum: {4}", start, arr[start], end, arr[end], largest);\n}	0
11917016	11917002	How to insert row that contains autoincrement column	INSERT INTO users_stocks\n(UserName, StockSymbol, Company)\nVALUES\n(@user_name, @stock_symbol, @company)	0
19052086	19021134	Correct Settings for Proxy	IWebProxy myProxy = WebRequest.DefaultWebProxy;\nmyProxy.Credentials = new NetworkCredential(username, password);\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);          \nrequest.Proxy = myProxy;	0
20205169	20199984	Convert jpg to png and assign to image control	WriteableBitmap wb = new WriteableBitmap(50, 50);\nwb.FromByteArray(array);\n\nicon.Source = wb;	0
7655139	7655043	XML ASMX Service with 1 return value - not XDocument so How to Parse?	string result = downloaded.Split('\n')[1];	0
3767740	3767072	most matched field value	var feedCodes = new string[] { "9051245", "9051246", "9051247", "9051245", "9031454", "9021447" };\n\nvar mostOccuring = feedCodes.Where(feedCode => feedCode != null)\n    .GroupBy(feedCode => feedCode.Length < 3 ? feedCode : feedCode.Substring(0, 3))\n    .OrderByDescending(group => group.Count())\n    .FirstOrDefault();\n\nif(mostOccuring == null)\n{\n    //some exception handling\n}\nelse\n{\n    //process mostoccuring.Key\n}	0
5275208	5275123	How to work with a Generic List of a Generic Type in a Generic Class	abstract class Team<T>\n    {\n        public List<Person> Members = new List<Person>();\n    }	0
9260827	9260303	How to change menu hover color	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        menuStrip1.Renderer = new MyRenderer();\n    }\n\n    private class MyRenderer : ToolStripProfessionalRenderer {\n        public MyRenderer() : base(new MyColors()) {}\n    }\n\n    private class MyColors : ProfessionalColorTable {\n        public override Color MenuItemSelected {\n            get { return Color.Yellow; }\n        }\n        public override Color MenuItemSelectedGradientBegin {\n            get { return Color.Orange; }\n        }\n        public override Color MenuItemSelectedGradientEnd {\n            get { return Color.Yellow; }\n        }\n    }\n}	0
20324973	20294555	How to access a Matlab field inside a struct from C#	MWNumericArray fieldA = (MWNumericArray) data["a", 1]; //data(1,1).a\nMWNumericArray fieldB = (MWNumericArray) data["b", 1]; //data(1,1).b\nfieldA = (MWNumericArray) data["a", 2]; //data(1,2).a\nfieldB = (MWNumericArray) data["b", 2]; //data(1,2).b	0
11354890	11354460	MongoDB C# CommandDocument how to add query	var collection = database.GetCollection("log");\nvar query = Query.And(\n    Query.GT("datetime", new DateTime(2012, 7, 5, 19, 55, 18, 475, DateTimeKind.Utc)),\n    Query.LT("datetime", new DateTime(2012, 7, 5, 20, 55, 18, 475, DateTimeKind.Utc))\n);\nvar result = collection.Distinct("cs_uri_stem", query);\nforeach (var distinctValue in result)\n{\n    // process distinctValue\n}	0
1329179	1329143	Public class with internal abstract member	public class Foo\n    : ClosedShapeBase\n{\n    protected override ShapeBase CloneShape()\n    {\n        throw new NotImplementedException();\n    }\n\n    protected override PointF[] CreatePoints(RectangleF bounds, int angle)\n    {\n        throw new NotImplementedException();\n    }\n\n    protected override ILinesAdjuster GetLinesAdjuster()\n    {\n        throw new NotImplementedException();\n    }\n}	0
32029664	32028673	Can I add numbers to int value instead of changing it?	int variable = 10;    // start with 10 points\nvariable++;           // add 1\nvariable += 3         // add 3	0
23199939	23199763	SqlDataReader - how to discover that column is empty	SqlDataReader rdr = cmd.ExecuteReader();\nint colIndex = read.GetOrdinal("MyColumnName");\n\nwhile (rdr.Read())\n{\n    // [true | false] your validation goes here!; \n\n    if (rdr.IsDBNull(colIndex)){\n       //value is  null\n    }\n}	0
15451076	15451001	where on LINQ with DataTable	var results = from myRow in dsPac.AsEnumerable()\n               where myRow.Field<string>("Package_Name").Equals(lblPackageName.Text)\n               select new { Holiday_ID = myRow["Holiday_ID"],\n                            Holiday_Description = myRow["Holiday_Description"],\n                            Holiday_Date = myRow["Holiday_Date"] };	0
2408021	2407944	How can I validate the output of XmlSerializer?	Stream stream = new MemoryStream(Encoding.UTF8.GetBytes("<YourXml />"));\nvar input = mappingAssembly.GetManifestResourceStream(\n            "MySchema.xsd"\n            ); //This could be whatever resource your schema is           \nvar schemas = new XmlSchemaSet();            \nschemas.Add(\n   "urn:YourSchemaUrn",\n   XmlReader.Create(\n      input\n      )\n );\n\nvar settings = new XmlReaderSettings\n                           {\n                               ValidationType = ValidationType.Schema,\n                               Schemas = schemas\n                           };\n\nsettings.ValidationEventHandler += MakeAHandlerToHandleAnyErrors;\n\nvar reader = XmlReader.Create(stream, settings);\nwhile (reader.Read()) {} //Makes it read to the end, therefore validates	0
3650140	3650118	How to split a string on numbers and it substrings?	(\d+|[A-Za-z]+)	0
5484038	5484022	In .NET, is it possible to set Events based on calling of a function	public delegate void EventHandler();\npublic event EventHandler ev;\n\npublic void AFun\n{\n   ...do stuff\n   ev(); //emit\n}\n\n//somewhere in the ctor\nev += MyEventHandler;\n\n//finally \n\nvoid MyEventHandler\n{\n    //handle the event\n}	0
3789838	3789759	Suggestions for how to clean up this API	public static void Process(int i) { ... }\npublic static void Process(string s) { ... }\npublic static void Process(Dictionary<string, string> dic) { ... }\npublic static void Process(Dictionary<string, int> dic) { ... }\n\n[...]\n\npublic dynamic Decode(string input)     // or 'object' if you prefer\n{\n    var t = GetDecodedType(input);\n    if (t == typeof(int))\n        return DecodeInt(input);\n    else if (t == ...)\n        // ...\n}\n\n[...]\n\nstring s = ...; // Encoded string\nProcess(Encoder.Decode(s));            // if you used 'dynamic' above\nProcess((dynamic)Encoder.Decode(s));   // if you used 'object' above	0
15909570	15906817	Deserialising XML without a declaration or namespace in Silverlight	string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);\n\n var document = XDocument.Parse(data);\n AgentState agent= (from c in document.Elements()\n                        select new AgentState()\n                                   {\n                                       agentName = c.Element("agentName").Value,\n                                       extension = c.Element("extension").Value,\n                                       currentlyIn=c.Element("currentlyIn").Value\n                                   }).Single();	0
17220824	17217077	Create zip file from byte[]	using (var compressedFileStream = new MemoryStream()) {\n    //Create an archive and store the stream in memory.\n    using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false)) {\n        foreach (var caseAttachmentModel in caseAttachmentModels) {\n            //Create a zip entry for each attachment\n            var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);\n\n            //Get the stream of the attachment\n            using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body)) {\n                using (var zipEntryStream = zipEntry.Open()) {\n                    //Copy the attachment stream to the zip entry stream\n                    originalFileStream.CopyTo(zipEntryStream);\n                }\n            }\n        }\n\n    }\n\n    return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };\n}	0
10183363	10096285	Regex in C# - remove quotes and escaped quotes from a value after another value	string serialized = JsonSerializer.Serialize(chartDefinition);\n    serialized = Regex.Replace(serialized, @"""function\(\)([^""\\]*(?:\\.[^""\\]*)*)""", "function()$1").Replace("\\\"", "\"");	0
24182994	24182837	How to update config file from code behind page in C#	// using System.Configuration;\n// using System.IO;\nvar fileMap = new ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = File.Exists("XYZ.exe.config") ? "XYZ.exe.config" : "XYZ.config";\nstring path = Path.Combine(Application.StartupPath, key);\nif (!Directory.Exists(path))\n{\n    Directory.CreateDirectory(path);\n}\nvar config = System.Configuration.Configuration; \nconfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\nconfig.AppSettings.Settings.Item(key).Value = path;\nconfig.Save(ConfigurationSaveMode.Modified);	0
31073848	31073799	Get only Whole Words from a .Contains() statement	var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();\nvar words = sentence.Split().Select(x => x.Trim(punctuation));\nvar containsHi = words.Contains("hi", StringComparer.OrdinalIgnoreCase);	0
16753558	16753441	c# How to click a radio buton on a webpage	HtmlElementCollection es = webBrowser1.Document.GetElementsByTagName("radio");  \nforeach (HtmlElement e in es)  {  \n   if (e.GetAttribute("value") == "4") {  \n        e.InvokeMember("Click");  \n   }  \n }	0
32287142	32287037	Find pairs of numbers in an array or List	var numbers = new[]\n{\n    1,\n    50,\n    2,\n    100,\n    102,\n    800\n};\n\nvar treshold = 2;\n\nvar numWithIndexes = numbers.Select((value, index) => new { value, index });\n\nvar pairs = from num1 in numWithIndexes\n            from num2 in numWithIndexes\n            where (num2.value - num1.value <= treshold) && (num2.value - num1.value > 0)\n            select new[]\n        {\n            num1.value, // first number in the pair\n            num2.value, // second number in the pair\n            num1.index, // index of the first number in the pair\n            num2.index  // index of the second member in the pair\n        };\n\nforeach (var pair in pairs)\n{\n    Console.WriteLine("Pair found: " + pair[0] + ", " + pair[1] +\n                      " at line " + pair[2] + ", " + pair[3]);\n}	0
5270201	5270180	How to check/filter uppercase words alone from a string using C#?	string test = "This IS a STRING";\nvar upperCaseWords = test.Split(' ').Where( w => w == w.ToUpper());	0
10601014	10600854	How to select specfic column in LINQ?	ds.Table[0].AsEnumerable()\n    .Where<DataRow>(r => r.Field<int>("productID") == 23)\n    .Select(r => new { ProductName = r.Field<string>("productName"), \n                       Description = r.Field<string>("description"),\n                       Price = r.Field<decimal>("price") });	0
25185392	25185101	To put all the class attributes into a list	var  man = new Man();\n//fill man properties\nforeach (var prop in man.GetType().GetProperties()) //use man.GetType().GetFields() for fields\n{\n    lst.Add(prop.GetValue(man));\n}	0
25431411	25431272	C# - Dealing with contradictions in string.replace	s = new string(s.Select(x => x == 'A' ? 'B' : x == 'B' ? 'A' : x).ToArray());	0
8049035	8048682	How to Display access database data in listview by date in descending order	OleDbDataAdapter da = new OleDbDataAdapter("select * from MyTable order by [Date] desc", con);	0
13477039	13469888	How to display html file from local folder inside an iframe?	file:///c:\temp\a.html	0
29548171	29482466	Passing EnvelopeId, JobId to PowerMTA from email sent through .NET	MailMessage mail = new MailMessage();\nmail.Headers.Add("x-envid", "MyEnvId");\nmail.Headers.Add("x-job", "MyJobId");	0
8893917	8893815	C# byte array to fixed int pointer	byte[] rawdata = new byte[1024];\n\nfixed(byte* bptr = rawdata)\n{\n    int* ptr=(int*)bptr;\n    for(int i = idx; i < rawdata.Length; i++)\n    {\n        //do some work here\n    }\n}	0
8520590	8520466	How to Display DataSet in ListView/GridView	if(datasetObject.tables.count > 0)\n    {\n    GridView.DataSource = datasetObject;\n    GridView.DataBind();\n\n    }\nelse\n{\n  lable.Text = "No Record Found";\n}	0
16187755	16187354	SQL Server connection string in winform application	connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=databaseName;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my.mdf"	0
7183033	7182998	Lambda Expression: CS to VB.Net	Dim colors As List(Of Color) = sColors.ConvertAll(Of Color)(\n    Function(s) DirectCast((New ColorConverter).ConvertFromString(s), Color)\n)	0
4831784	4831205	How to create CSV string from String Array, If string is blank at any index than just discard it	var yourArray = ...;\nyourArray = yourArray.Where(str => !string.IsNullOrWhiteSPace(str)).ToArray();\n\nvar yourResult = Enumerate\n  .Range(0, yourArray.Length)\n  .Select(index => (index % 3 == 0)?("<br>" + yourArray[index]):yourArray[index])\n  .Aggregate((cur, nex) => cur + "," + nex);	0
22426777	22426738	IGrouping to IEnumerable	IEnumerable<List<MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id)\n                                            .Select(group => group.ToList())\n                                            .ToList();	0
4409934	4403029	Query printer status on my d-link print server	OLEPRNLib.SNMP snmp = new OLEPRNLib.SNMP();\nint Retries = 1;\nint TimeoutInMS = 2000;\nstring CommunityString = "public";\nstring IPAddressOfPrinter = "192.168.1.12";\nstring ALLINEED;\n\n// Open the SNMP connect to the print server\nsnmp.Open(IPAddressOfPrinter, CommunityString, Retries, TimeoutInMS);\nALLINEED = snmp.Get(".1.3.6.1.4.1.11.2.3.9.1.1.3.0");\nsnmp.Close();\n\nConsole.Write(ALLINEED);	0
6527011	6526960	C#: Finding out if the last element in a List<string> is a carriage return?	if (string.IsNullOrWhiteSpace(mailingList.LastOrDefault())	0
26298991	26298285	Finding an index of an element in a string array	string[] vals = { "val1", "val2" ,"val3"};\nint idx = Array.IndexOf(vals, "val2");	0
23657288	23657161	Code for variable's value within the Model	public int Age\n{\n    get { return (DateTime.Now - BirthDate).TotalDays / 365; }\n}	0
9741197	9738989	Accessing the number of processors in WMI	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Management;\nusing System.Text;\n\nnamespace ConsoleFoo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            try\n            {\n                ManagementObjectSearcher mgtObj = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ComputerSystem");\n                foreach (ManagementObject item in mgtObj.Get())\n                {\n                    Console.WriteLine("Number Of Processors  {0}", item["NumberOfProcessors"]);\n                }\n            }\n            catch (ManagementException e)\n            {\n                Console.WriteLine("Exception {0} ", e.Message);\n            }\n            Console.ReadKey();\n        }\n    }\n}	0
20348118	20348026	.NET Is there such a thing as 'Mandatory Parameter'?	void IArray.Insert(int index, Object value)\n{\n    Contract.Requires(index >= 0);\n    Contract.Requires(index <= ((IArray)this).Count);  // For inserting immediately after the end.\n    Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) + 1);\n}	0
11001323	10998742	How to list all elements from a column in a TextBox from SharePoint?	TextBox1.Text = TextBox1.Text + " " + (string)item["Title"];	0
12472164	12472112	How can I split a string that has three spaces as its separators?	string[] array2 = ss.Split(new string[]{"   "}, StringSplitOptions.None);	0
10164003	10163378	generate data from formatted string	string s = "the first number is: {0} and the last is: {1} ";\nint first = 2, last = 5;\nstring f = String.Format(s, first, last);\n\nstring pattern = @"the first number is: ([A-Za-z0-9\-]+) and the last is: ([A-Za-z0-9\-]+) ";\nRegex regex = new Regex(pattern);\nMatch match = regex.Match(f);\nif (match.Success)\n{\n    string firstMatch = match.Groups[1].Value;\n    string secondMatch = match.Groups[2].Value;\n}	0
7303571	7303143	position of a text on windows form	public static Point GetLocationFromHandle(IntPtr handle, string controlNameToLocate) {\n        Control c = FromHandle(handle);\n\n        if (c != null)\n        {\n            Control myCtrl = c.Controls[controlNameToLocate] as Control;\n            if (myCtrl != null)\n            {\n                return myCtrl.Location;\n            }\n        }\n\n        return Point.Empty;\n    }	0
11054644	11054510	Wpf text box not updated from view model	set\n{\n   sUIDispatcher.BeginInvoke((Action)(() => Raise("Name")));\n}	0
24230434	24228956	Get button sender ImageBrush.ImageSource from XAML	var brush = but01.Background as ImageBrush;\nBitmapImage source = brush.ImageSource as BitmapImage;\nUri uri = source.UriSource;\nstring uriStr = uri.OriginalString;	0
13164309	13163724	How can I accomplish the following mapping with Automapper?	Mapper.CreateMap<Source, MyClass1>();\n        Mapper.CreateMap<Source, MyClass2>();\n\n        Mapper.CreateMap<Source, Destination>()\n            .ForMember(x => x.A, m => m.MapFrom(p => p))\n            .ForMember(x => x.B, m => m.MapFrom(p => p));\n\n\n        var source = new Source() { a = 1, b = 2, c = 3, x = 4, y = "test", z = true };\n        var destination = new Destination() { A = new MyClass1(), B = new MyClass2() };\n        Mapper.Map<Source, Destination>(source, destination);	0
14767844	14767169	GridViewRow is null in DataGrid	private void btnUserId_Click(object sender, RoutedEventArgs e)\n{            \n    Button button = sender as Button;\n    if (button == null)\n        return;\n\n    DataGridRow clickedRow = null;\n    DependencyObject current = VisualTreeHelper.GetParent(button);\n\n    while (clickedRow == null)\n    {\n        clickedRow = current as DataGridRow;\n        current = VisualTreeHelper.GetParent(current);\n    }\n\n    // after the while-loop, clickedRow should be set to what you want\n}	0
1889059	1888825	listbox and how to perform actions on selected items	while (listBox1.SelectedIndices.Count > 0)\n    listBox1.Items.RemoveAt(listBox1.SelectedIndices[0]);	0
33261117	33260753	C# Merge properties from two (or more) lists based on common property	var theModel = models.First(); // select a model\n\nforeach (var interm in intermediates.Where(x => x.Parent == theModel.Node))\n{\n    foreach (var res in results.Where(x => x.Parent == interm.Node))\n    {\n        res.Name = theModel.Name;\n    }\n}	0
13402791	13400645	Distinguish Save and Autosave events in Microsoft Excel Add in	Tools -> Options -> Save	0
25052030	25030578	Removing .aspx extension from sitecore in ExecuteRequest pipeline	var urlOptions = UrlOptions.DefaultOptions;\nurlOptions.AddAspxExtension = true;\n\nLinkManager.GetItemUrl(item, urlOptions);	0
28782007	28609200	How to get data in string from database	SqlConnection conn = new SqlConnection(yourConnectionString);            \n    SqlCommand cmd = new SqlCommand(your query,conn);\n    SqlDataAdapter SDA = new SqlDataAdapter();\n    DataTable dt = new DataTable(DataTableName);\n    conn.Open();\n    SDA.Fill(dt);\n    conn.Close();\n    String xml =  dt.Rows[0].ItemArray[0].ToString();\n    return xml;	0
23850590	23850455	Regular expressions, capture group	HtmlDocument doc = new HtmlDocument();\n doc.LoadHtml("YOUR HTML STRING");\n foreach(HtmlNode node in doc.DocumentElement.SelectNodes("//select/option[@selected='selected']")\n {\n    string text = node.InnerHtml;                  // "American Samoa, United States Dollar (USD)"\n    string value = node.Attributes["value"].Value; // "USD"\n }	0
2365129	2365068	Specific generic interfaces	public interface IRepository<TEntity, TId>\n {\n      TEntity Get(TId id);\n      void Add(T x);\n }\n\npublic class UserRepository : IRepository<User, Guid>\n{\n    public User Get( Guid id ) \n    {\n        // ...\n    }\n\n    public void Add( User entity) \n    {\n        // ...\n    }\n}\n\npublic class OrderRepository : IRepository<Order, string> \n{\n    //...\n}	0
28239535	28239238	Fibonacci with huge numbers in c#	public static int FibHugesUntil(BigInteger huge1, BigInteger huge2, int reqDigits)\n{\n    int number = 1;\n    while (huge2.ToString().Length < reqDigits)\n    {\n        var huge3 = huge1 + huge2;\n        huge1 = huge2;\n        huge2 = huge3;\n        number++;\n    }\n    return number;\n}\n\nstatic void Main(string[] args)\n{\n    Console.WriteLine(FibHugesUntil(BigInteger.Zero, BigInteger.One, 1000));\n}	0
23703256	23702378	Know when a file changes on windows 8	static void StartWatching(string path)\n{\n    var watcher = new FileSystemWatcher();\n    watcher.Path = path;\n    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |\n                           NotifyFilters.DirectoryName;\n    watcher.Changed += watcher_Created;\n    watcher.Created += watcher_Created;\n    watcher.EnableRaisingEvents = true;\n\n    var copier = new Thread(ConsumeOutOfTheFilesToCopyQueue);\n    copier.Start();\n}\n\n    static void watcher_Created(object sender, FileSystemEventArgs e)\n    {\n        if (e.Name.Contains("whatever.dll"))\n            if (!_filesToCopy.Contains(e.FullPath))\n                lock (_syncRoot)\n                    if (!_filesToCopy.Contains(e.FullPath))\n                        _filesToCopy.Enqueue(e.FullPath);\n    }	0
13772775	11251101	Pass URL to XAML at runtime	Microsoft.SilverlightMediaFramework.Core.Media.PlaylistItem mp = new    Microsoft.SilverlightMediaFramework.Core.Media.PlaylistItem();\n            mp.MediaSource = strPath;\n            smf.CurrentPlaylistItem = mp;\n            smf.Play();	0
3140115	3140051	how to find the point exists in the area of any polygon or not?	public void IsVisiblePoint(PaintEventArgs e)\n{\n   // Set clip region.\n   Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));\n   e.Graphics.SetClip(clipRegion, CombineMode.Replace);\n   // Set up coordinates of points.\n   int x1 = 100;\n   int y1 = 100;\n   int x2 = 200;\n   int y2 = 200;\n   Point point1 = new Point(x1, y1);\n   Point point2 = new Point(x2, y2);\n   // If point is visible, fill ellipse that represents it.\n   if (e.Graphics.IsVisible(point1))\n   e.Graphics.FillEllipse(new SolidBrush(Color.Red), x1, y1, 10, 10);\n   if (e.Graphics.IsVisible(point2))\n   e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x2, y2, 10, 10);\n}	0
32143825	32143003	Mac Scanning Code only grabs 1 IP Address in a loop	SendArp(addrInt, srcAddrInt, mac, ref length);	0
7010051	7009958	set Enums using reflection	public class MyObject\n{\n    public LevelEnum MyValue {get;set,};\n}\n\n\nvar obj = new MyObject();\nobj.GetType().GetProperty("MyValue").SetValue(LevelEnum.CDD, null);	0
6261219	6261193	LINQ Query - How to map a resultset into another object using Select	var cities = network.Continents\n    .SelectMany(continent => continent.Countries)\n    .Where(ctry => ctry.Id == "country")\n    .SelectMany(ctry => ctry.Cities)\n    .Select(cty=> new City{Id = cty.Id, Name = cty.Name }).ToList<City>();	0
9402913	9402581	BigInteger string representation with decimal places	public string GetDecimal(BigInteger bigInteger, int divisor)\n{\n    BigInteger remainder;\n    var quotient = BigInteger.DivRem(bigInteger, divisor, out remainder);\n\n    const int decimalPlaces = 2;\n    var decimalPart = BigInteger.Zero;\n    for(int i = 0; i < decimalPlaces; i++)\n    {\n        var div = (remainder*10)/divisor;\n\n        decimalPart *= 10;\n        decimalPart += div;\n\n        remainder = remainder*10 - div*divisor;\n    }\n\n    var retValue = quotient.ToString() + "." + decimalPart.ToString(new string('0', decimalPlaces));\n    return retValue;\n}	0
23647246	23646863	concatenate items in N lists	string item = "a,b,c+1,2,3,4+z,x";\n\nvar lists = item.Split('+').Select(i => i.Split(',')).ToList();    \nIEnumerable<string> keys = null;\n\nforeach (var list in lists) \n{\n    keys = (keys == null) ? \n        list : \n        keys.SelectMany(k => list.Select(l => k + l));\n}	0
4780548	4773202	Deserializing a particular XML string	[System.Xml.Serialization.XmlRootAttribute("CoverDecision", Namespace = "http://atradius.com/connect/_2007_08/", IsNullable = false)]\npublic partial class CoverDecisionType	0
16025748	16025704	c# get specific filename	foreach (var filename in Directory.GetFiles(path, "prefix*.csv)) {\n    var linesFromOneFile = File.ReadAllLines(filename)\n                               .Select(a => a.Split(',')).ToList();\n\n    // Whatever else with 'filename'\n    File.Move(...);\n}	0
7513527	7513426	c# linq keep only matching dictionary values based on list	var newGroupedIndex = GroupedIndex\n    .Select(pair => new { \n                        Key = pair.Key, \n                        Matched = pair.Value.Intersect(TobeMatched).ToList()\n                        })\n    .Where(o => o.Matched.Count != 0)\n    .ToDictionary(o => o.Key, o => o.Matched);	0
11623883	11623843	Adding items to Dictionary without using Add method in C#	Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()\n {\n   { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},\n   { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},\n   { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}\n};	0
27278405	27278342	How to format user input into time	Console.WriteLine("{0}:{1:00}:{2:00}", pHour, pMinutes, Seconds);	0
13665531	13665489	How to get currently focused TextBox?	TextBox focusedTxt = Controls.OfType<TextBox>().FirstOrDefault(x => x.Focused);	0
26503608	26503433	DateTime Current Month in C#	public int NumberTicketsThreeMonthsAgo\n{\n    DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month,\n                                        1).AddMonths(-3);\n    get { return AllTickets.Count(t => dt < t.CreateDateTime); }\n}	0
30009891	30008966	BFS on a non weighted directed graph. How to return a list of the path between A and B	private List<Cell> FindPath(Cell A, Cell B)\n{\n    var parent = new Dictionary<Cell, Cell>();\n\n    List<Cell> queue = new List<Cell>();\n    List<Cell> visited = new List<Cell>();\n\n    queue.Add(A);\n    parent.Add(A, null);\n\n    while (queue.Count != 0)\n    {\n        Cell c = queue[0];\n        queue.RemoveAt(0);\n\n        visited.Add(c);\n\n        if (c == B)\n            break;\n\n        foreach (Cell near in c.NearCells)\n        {                    \n            if (!visited.Contains(near))\n            {\n                parent.Add(near, c);\n                visited.Add(near);\n                queue.Add(near);\n            }\n        }\n    }\n\n    List<Cell> path = new List<Cell>();\n\n    if(parent.ContainsKey(B))\n    {\n        Cell backTrack = B;\n        do\n        {\n            path.Add(backTrack);\n            backTrack = parent[backTrack];\n        }\n        while (backTrack != null);\n        path.Reverse();\n    }\n    return path;\n}	0
10542985	10542947	Extract sub-directory name from URL in ASP.NET C#	var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");\nRequest.Url.Segments[2]; //Index of directory2	0
639503	639493	In C# how can I safely exit a lock with a try catch block inside?	System.Threading.Monitor.Enter(x);\ntry {\n   ...\n}\nfinally {\n   System.Threading.Monitor.Exit(x);\n}	0
8217965	8217867	Treeview C# building Hierarchy WPF	//create treeNode myParent = null;  \nwhile (Reader.Read()) \n{ \n    switch (reader.NodeType) \n    { \n        case XmlNodeType.Element: // The node is an element. \n            var newNode = new TreeViewItem \n            { \n                Header = reader.Name \n            }; \n\n            if(theParent !=null) \n            { \n                theParent.Items.Add(newnode);  \n            } \n            else \n            { \n                treeView.Items.Add(newnode);  \n            } \n            theParent = newnode; \n            break; \n\n        case XmlNodeType.Text: //Display the text in each element. \n            Console.WriteLine(reader.Value); \n            break; \n\n        case XmlNodeType.EndElement: //Display the end of the element. \n            Console.Write("</" + reader.Name); \n            Console.WriteLine(">"); \n            if (theParent != null)\n            {\n                theParent = theParent.Parent;\n            } \n            break; \n     } \n }	0
6924504	6924056	is there a way to read a word document line by line	Word.Document doc = wordApp.Documents.Open(ref file, 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);	0
16825735	16825614	Serialize class to json as array	public class rings\n{\n    List<List<List<double>>> rings;\n}	0
6506062	6489902	How do I wrap a C++ interface (abstract class) in C++/CLI?	interface class IProgressEventSink\n{ ... };\n\nclass ProgressEventForwarder : IProgressEventCB\n{\n    gcroot<IProgressEventSink^> m_sink;\npublic:\n    ProgressEventForwarder(IProgressEventSink^ sink) : m_sink(sink) {}\n\n// IProgressEventCB implementation\n    virtual void OnProgress( ProgressInfo info ) { m_sink->OnProgress(info.a, info.b); }\n};\n\nref class ComputeCLI\n{\n     Compute* m_pimpl;\n // ...\n\npublic:\n     RegisterHandler( IProgressEventSink^ sink )\n     {\n         // assumes Compute deletes the handler when done\n         // if not, keep this pointer and delete later to avoid memory leak\n         m_pimpl->RegisterHandler(new ProgressEventForwarder(sink));\n     }\n};	0
30448235	30447081	Linq Contains Query from Table List	SecondTable.Where(a => FirstTable.Any(b => b.Keyword == a.Keyword))	0
6245513	6245493	How to call a method from a button in C#	StartService("MyService",20000);	0
14846504	14603063	Crystal Report Group sort formula	ParameterFields Fields = new ParameterFields();\nParameterField ItemFd= new ParameterField();\nItemFd.ParameterFieldName = "NewParameter"; \nParameterDiscreteValue DItemFd = new ParameterDiscreteValue();\nDItemFd.Value = SortOrder;// this a sort parameter\nItemFd.CurrentValues.Add(DItemFd);\nFields.Add(ItemFd);	0
15799499	15790372	ResourceManager falls back to default resources instead of reading from satellite assembly	CD "$(ProjectDir)Resources"\nFOR /D %%1 IN (*) DO (\n? ? CD "%%1"\n? ? resgen.exe "Strings.%%1.txt" "MyClassLibrary1.Resources.Strings.%%1.resources"\n? ? if %errorlevel% == 0 (\n? ? ? ? al.exe /t:lib /embed:"MyClassLibrary1.Resources.Strings.%%1.resources" /culture:"%%1" /out:MyClassLibrary1.resources.dll\n? ? ? ? if not exist "$(TargetDir)%%1" md "$(TargetDir)%%1"\n? ? ? ? move /Y "MyClassLibrary1.resources.dll" "$(TargetDir)%%1"\n? ? )\n? ? CD ..\n)	0
5646399	5646138	Examples of functional or dynamic techniques that can substitute for object oriented Design Patterns	Func<T>	0
10994149	10993187	Recursively to call a method to gain Excel sheet values.	public static List<string> GetCellValue(string fileName, string sheetName, string addressName)\n    {\n        List<string> result = new List<String>;\n        object hmissing = System.Reflection.Missing.Value;\n        Application app = new ApplicationClass();\n        Workbook aWb = app.Workbooks.Open(fileName, hmissing, hmissing, hmissing, hmissing,\n            hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing,\n            hmissing);\n        Worksheet aWs = aWb.Worksheets[sheetName] as Worksheet;\n        object[,] values = aWs.UsedRange.get_Value(hmissing) as object[,];\n        foreach (object anObj in values)\n             if (anObj != null)\n                 result.Add(anObj.ToString());  \n        aWb.Close(false, hmissing, hmissing);\n        app.Quit();          \n        return result;\n    }	0
5735847	5735775	How to read from file to stream and display as text?	MemoryStream stream = ... //Your memory stream here\n\nusing (var reader = new StreamReader(stream))\n{\n    textArea.Text = reader.ReadToEnd();\n}	0
21895715	21895678	Add Images to windows form so they work after publish	System.Reflection.Assembly thisExe;\nthisExe = System.Reflection.Assembly.GetExecutingAssembly();\nSystem.IO.Stream file = \n    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");\nthis.pictureBox1.Image = Image.FromStream(file);	0
22044384	22015884	Replace configuration in app.config with code configuration for WCF service	var id = new EntityInstanceId\n {\n     Id = new Guid("682f3258-48ff-e211-857a-2c27d745b005")\n };\n\n var endpoint = new EndpointAddress(new Uri("http://server/XRMDeployment/2011/Deployment.svc"),\n                    EndpointIdentity.CreateUpnIdentity(@"DOMAIN\DYNAMICS_CRM"));\n\n var login = new ClientCredentials();\n login.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;\n\n var binding = new CustomBinding();\n\n //Here you may config your binding (example in the link at the bottom of the post)\n\n var client = new DeploymentServiceClient(binding, endpoint);\n\n foreach (var credential in client.Endpoint.Behaviors.Where(b => b is ClientCredentials).ToArray())\n {\n     client.Endpoint.Behaviors.Remove(credential);\n }\n\n client.Endpoint.Behaviors.Add(login);\n var organization = (Organization)client.Retrieve(DeploymentEntityType.Organization, id);	0
3388997	3388968	Method passed in as parameter to a Method C#2.0	delegate void FunctionX(params object[] args);\n\nprivate void DoOperations(FunctionX executeX) \n{ \n    executeA(); \n    executeB(); \n\n    executeX("any", "number", "of", "params");\n\n    executeC(); \n\n} \nvoid MyFunction(params object[] p)\n{\n      // do stuff\n}\n\n\nDoOperations(MyFunction);	0
19769544	19766061	VS2012 not detecting folders in solution	namespace ActivityLibrary2.Activities\n{\n   public class Test{}\n}	0
22893124	22893097	Change combobox list to clear option	comboBox1.SelectedIndex = -1;	0
6554540	6554407	deserialize "/Date(1309498021672)/" in to DateTime	var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();\nstring json = "\"\\/Date(1309498021672)\\/\"";\nDateTime date = serializer.Deserialize<DateTime>(json);\n// date is 7/1/2011 5:27:01 AM	0
12149634	12149614	Display only captured groups	match.Groups[1].Value;	0
29363499	29363396	C# Get enum in class from dll by its name	public class MyClass\n{\n    public enum MyEnum\n    {\n\n    }\n}\n\nType enu = typeof(MyClass).GetNestedType("MyEnum");	0
15986092	15985253	how to keep in the same cell after refeshing the datagridview c#	Point[] oldSelectedCells = new Point[dataGridView1.SelectedCells.Count];\n        for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)\n        {\n            oldSelectedCells[i].X = dataGridView1.SelectedCells[i].ColumnIndex;\n            oldSelectedCells[i].Y = dataGridView1.SelectedCells[i].RowIndex;\n        }\n\n        // refresh datagridview\n\n        dataGridView1.CurrentCell = null;\n        foreach (Point p in oldSelectedCells)\n            dataGridView1[p.X, p.Y].Selected = true;	0
10378160	10378126	Retrieving a particular string from a sentence using Regular Expressions	Regex Reg = new Regex(@"(KB\d+(?:-[\w\d]+)?)", RegexOptions.IgnoreCase);	0
7254665	7254636	Gridview is not displaying data with code-behind sqldatasource	gridBookings.DataBind();	0
20866197	20866146	Check number of decimal places in numeric string	var input = "10.625";\n\ndouble value;\nif(!double.TryParse(input, out value) || Math.Round(value, 2) != value)\n{\n    Console.WriteLine("Wrong input");\n}	0
10827189	10812475	how to find install dll in C#	string strGacDir = @"C:\Windows\Microsoft.NET\assembly\GAC_32";\nstring[] strDirs1 = System.IO.Directory.GetDirectories(strGacDir);\nstring[] strDirs2;\n\nstring[] strFiles;\n\nforeach (string strDir1 in strDirs1)\n{\n    strDirs2 = System.IO.Directory.GetDirectories(strDir1);\n\n    foreach (string strDir2 in strDirs2)\n    {\n        strFiles = System.IO.Directory.GetFiles(strDir2, "SlimDX.dll");\n        foreach (string strFile in strFiles)\n        {\n            return true;\n        }\n    }\n}	0
29586477	29586458	find out the words with substring in LINQ	var newWord = words.Where(o => o.Contains("ei"));	0
5316283	5316213	VB.NET, C#:I need a stored procedure to return three rows, how should i store them?	class YourDatum \n{\n  int Id { get; set; }\n  string Value1  { get; set; }\n  string Value2 { get; set; }\n\n  public bool Match(string term)\n  {\n      return Value2.ToUpperInvariant() == term.ToUpperInvariant();\n  }\n}\n\nvar cachedResults = new Dictionary<int, YourDatum>();\n\n//your database calls go here\nforeach (var dbRow in dbRows) \n{\n   cachedResults.Add(\n      idFromDb, \n      new YourDatum {Id=idFromDb, Value1=valueFromDb1, Value2=valueFromDb2});\n}\n\n//find a match in the results later on...\nstring searchTerm = "abcdef";\nList<YourDatum> matches= \n    (from datum in cachedResults where \n    datum.Match(searchTerm) select datum).ToList();	0
11884081	11883962	MVVM Data Update	Public Property Busy As Boolean\n    Get\n        Return _busy\n    End Get\n    Set(value As Boolean)            \n        _busy = value\n        NotifyPropertyChanged("Busy")\n    End Set\nEnd Property	0
24041682	24016477	How to calculate FFT using NAudio in realtime (ASIO out)	for (int i = 0; i < e.SamplesPerBuffer * 4; i=i+4)\n{\n    float sample = Convert.ToSingle(buf[i] + buf[i+1] + buf[i+2] + buf[i+3]);\n    sampleAggregator.Add(sample);\n}	0
21388079	21388015	Exclude current object in foreach loop	foreach(Ball i in Pool)\n{\n    if(i <> this)\n        if (Math.Sqrt(Math.Pow(i.pos.X - pos.X, 2) + Math.Pow(i.pos.Y - pos.Y, 2)) < 50)\n        {\n            //do intesect procedure\n        }\n}	0
21303275	21303040	Displaying events from server's event log on web page	var eventLog = new EventLog("logName", "machine", "source");\nforeach(var entry in eventLog.Entries)\n{\n}	0
23687904	23683662	How to access the Exception variable more than once in an injected try catch handler with Mono.Cecil?	var exceptionVariable = new VariableDefinition("e", method.Module.Import(typeof (Exception)));\nmethod.Body.Variables.Add(exceptionVariable);\n\nvar last = method.Body.Instructions.Last();\nInstruction tryEnd;\nil.InsertAfter(last, tryEnd = last = il.Create(OpCodes.Stloc_S, exceptionVariable));\nil.InsertAfter(last, last = il.Create(OpCodes.Ldloc_S, exceptionVariable));\nil.InsertAfter(last, last = anyCallInstructionWithExceptionParamter);\nil.InsertAfter(last, last = il.Create(OpCodes.Ldloc_S, exceptionVariable));\nil.InsertAfter(last, last = otherCallInstructionWithExceptionParamter);\nil.InsertAfter(last, last = leave);\nil.InsertAfter(last, ret);\n\nvar handler = new ExceptionHandler(ExceptionHandlerType.Catch)\n{\n    TryStart = method.Body.Instructions.First(),\n    TryEnd = tryEnd,\n    HandlerStart = tryEnd,\n    HandlerEnd = ret,\n    CatchType = module.Import(typeof (Exception)),\n};	0
11507156	11507110	How to run an executable from memory in another AppDomain?	Process.Start	0
34521213	34506150	Use AutoMapper to map from an interface to a concrete type	Mapper.Initialize(config =>\n{\n    config.CreateMap<IPerson, PersonDto>()\n        .Include<IModelPerson, ModelPersonDto>()\n        .ConstructUsing((IPerson person) => \n        {\n            if (person is IModelPerson) return Mapper.Map<ModelPersonDto>(person);\n\n            throw new InvalidOperationException("Unknown person type: " + person.GetType().FullName);\n        })\n        ;\n\n    config.CreateMap<IModelPerson, ModelPersonDto>();\n});	0
15677270	15677194	Check a value exist in array in unity 3d	public static ArrayList aArray= new ArrayList();\n\nfunction update()\n{\n   if(aArray.Contains(i)==false)\n   {\n      aArray.Add(i);\n   }\n}	0
7878350	7877144	LINQ to SQL: Select count rows for each date in a provided range?	static void Test(DataClasses1DataContext context, DateTime fromDate, DateTime toDate)\n{\n    var result = context.Accounts\n                .Where(p => p.CreatedOn >= fromDate && p.CreatedOn <= toDate)\n                .GroupBy(x => x.CreatedOn.Date)\n                .Select(x => new {\n                   dt = x.Key,\n                   count = x.Count()});\n}\n\nList<DateTime> dates = new List<DateTime>();\nwhile (fromDate <= toDate)\n{\n    dates.Add(fromDate.Date);\n    fromDate = fromDate.AddDays(1);\n}    \n\nvar allDates = dates.Select(x => new {\n                    dt = x,\n                    count = 0});\n\n// Merge both lists and then filter to include highest count\nvar result = rows.Concat(allDates)\n                 .GroupBy(x => x.dt)\n                 .Select(x => new {\n                    dt = x.Key,\n                    count = x.OrderByDescending(c => c.count)\n                             .FirstOrDefault().count});	0
16601551	16601488	Combining parameterised stored procedure values into a single JSON object	return Json(new {Id = id, Items = query.ToArray()}, JsonRequestBehavior.AllowGet);	0
2856623	2856576	Can I ensure, using C#, that an X509Certificate was issued by a trusted authority?	ServicePointManager.ServerCertificateValidationCallback +=\n            new System.Net.Security.RemoteCertificateValidationCallback(customXertificateValidation);\n\n    private static bool customXertificateValidation(\n        object sender, X509Certificate cert,\n        X509Chain chain, System.Net.Security.SslPolicyErrors error)\n    {\n\n        // check here 'cert' parameter properties (ex. Subject) and based on the result \n        // you expect return true or false\n\n        return false/true;\n    }	0
8529793	8529771	Using model data annotation in MVC to ensure a string contains just one word?	[RegularExpression(@"\b*[a-zA-Z0-9_]\b", ErrorMessage = "Enter A Single Word Please")]\nstring FirstName {get; set;}	0
33597315	33596791	How To Parse Xml in c# WPF application	var results = XElement.Load("games.xml")\n        .Element("content.items")\n        .Element("content.head")\n        .Element("content.body")\n        .Elements("results")\n        .Elements("result");\n\n    var query = (from result in results\n        let homeTeam = result.Element("home-team")\n        let awayTeam = result.Element("away-team")\n        let lastScorer = result.Descendants("scorers").Elements("scorer").OrderByDescending(p => (int)p.Attribute("time")).FirstOrDefault()\n        select new\n        {\n              HomeTeam = homeTeam.Element("team-name").Value,\n              AwayTeam = awayTeam.Element("team-name").Value,\n\n              HomeTeamScore = homeTeam.Element("score").Value,\n              AwayTeamScore = awayTeam.Element("score").Value,\n\n              LastScorerName = lastScorer != null ? lastScorer.Element("player-name").Value : string.Empty,\n              LastScoreTime = lastScorer != null ? (int?)lastScorer.Attribute("time") : null\n        }).ToList();	0
22879093	22878214	concatenated columns as action link	grid.Column(header: "YourColumnName", format: (item) =>new HtmlString(\n                        Html.ActionLink("linkText", "actionName","controllerName", new { id = item.yourItemId },null).ToString()))	0
19469516	19469369	Printing two seperate documents without two print dialogues	...\nPrintDocument pd = new PrintDocument(); \npd.PrintPage += new PrintPageEventHandler(pd_PrintPage);\n// Specify the printer to use. You can check its name in control panel\npd.PrinterSettings.PrinterName = "NameofThePrinter";  \npd.Print();\n...	0
16257049	16256986	How can I fill variables with xml node values from a xml file?	var xdoc = XDocument.Load(url);\nvar items = xdoc.Descendants("item")\n            .Select(item => new\n            {\n                Title = item.Element("title").Value,\n                description = item.Element("description").Value,\n                Link = item.Element("link").Value\n            })\n            .ToList();	0
4068162	4068057	how to test a failed moq	_mockRepository.Verify(x => x.InsertRpaData(RPADataEntity), Times.Never());	0
11484061	11483938	How to get value from element attribute, XML Serialization	public class owner\n{\n    [XmlAttributeAttribute]\n    public string username { get; set; }\n}\n\n\n\n[SerializableAttribute] \n[XmlTypeAttribute(AnonymousType = true)] \npublic partial class SearchResponseVideosWrapperVideo \n{ \n    private string _title; \n    private string _id; \n    private string _username; \n\n    [XmlElement()] \n    public string title \n    { \n        get { return _title; } \n        set { _title = value; } \n    } \n\n    [XmlAttributeAttribute()] \n    public string id \n    { \n        get { return _id; } \n        set { _id = value; } \n    } \n\n    [XmlElementAttribute("owner")] \n    public owner owner { get; set; }	0
12755311	12754718	Control's default properties	[DefaultValue(false)]\npublic bool UseWaitCursor\n{\n   // etc..\n}	0
1114211	1114184	WPF Binding issue with updating values	public bool IsTextValid\n{\n    get\n    {\n        return ! string.IsNullOrEmpty( this.CurrentText );\n    }\n}	0
4884679	4884639	Output all command line parameters	String.Join(", ", Environment.GetCommandLineArgs())	0
19143839	19142109	Padding strings that contain accents	var si = new StringInfo(myString);\nint length = si.LengthInTextElements;	0
6831104	6830959	C# Find Midpoint of two Latitude / Longitudes	-(2.1321400763480485 radians) = -122.162628 degrees\n0.65970036060147585 radians = 37.7980464 degrees	0
2616980	2616638	Access the value of a member expression	private object GetValue(MemberExpression member)\n{\n    var objectMember = Expression.Convert(member, typeof(object));\n\n    var getterLambda = Expression.Lambda<Func<object>>(objectMember);\n\n    var getter = getterLambda.Compile();\n\n    return getter();\n}	0
5313142	5312892	How to hide a column but still access its value?	MyGridView.Columns[0].visible = true;\nMyGridView.DataBind();\nMyGridView.Columns[0].visible = false;	0
20093842	20093653	How to let C# windows application start with a default combo box item selected?	private void Form1_Load(object sender, EventArgs e)\n    {\n      if( comboBox1.Items.Count>0)          \n        {\n             comboBox1.SelectedIndex = 0;\n        }\n      else\n        {   \n             comboBox1.Text="No Items";\n        }\n    }	0
19953768	19953495	extract and format string in text file?	foreach(LineOfText line in text)\n{\n    foreach(Word in line)\n    {\n        if(Word is HtmlTag)\n        {\n            mark current line as type1;\n            put current line in string1;\n        }\n        else\n        {\n            mark current line as type2;\n            put current line in string2;\n        }\n    }\n}\n\nSaveString(string1);\nSaveString(string2);	0
21357123	21357049	Combine 2 integer's text not add them together	int x = 5;\nint y = 10;\nint sum;\nsum = Convert.ToInt32("" + x + y);	0
10271674	10271645	Decrypt from SHA256	var password = "1234";\nvar hashedPassword = Sha256encrypt(password);\n\nvar allowLogin = hashedPassword == storedPassword; //storedPassword from Database, etc.	0
25787533	25787402	c# xml show highest value	int highestId = readme\n    .Elements("customers")\n    .Elements("customer")\n    .Select(cust => Convert.ToInt32(cust.Element("customerid").Value.Substring(1))\n    .Max();	0
33660862	33660746	Problems with user selecting value outside of Enum range	Food foodChoice;\nint n;\nstring temp;\nwhile (!(Enum.TryParse<Food>(temp = Console.ReadLine(), true, out foodChoice)) || int.TryParse(temp,out n))\n{\n    Console.WriteLine("Not a valid choice.");\n}	0
756484	756448	How do I test my email settings without sending a message?	HELO Server.Domain.Com\nMail From: validaccount@domain.com	0
20774203	20774158	Order List in LINQ to SQL	var result =   (from x in Table1\n    from y in Table1\n    where x.C == y.A\n    order by x.B\n    select new { A = x.A, B=x.B,C=x.C}).ToList();	0
10664880	10664728	Redirect to Different Url From Asp.net mvc3 Controller	string link = "http://www.google.com";\nreturn Redirect(link);	0
26137072	26136637	asp.net button click event occurs only once	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace DummyTest\n{\n    public partial class WebForm1 : System.Web.UI.Page\n    {\n        static int pom;\n        protected void Page_Load(object sender, EventArgs e)\n        {\n            if (Page.IsPostBack == false)\n            {\n               pom = 0;\n               Label1.Text = Convert.ToString(pom);\n            }\n        }\n\n        protected void Button1_Click(object sender, EventArgs e)\n        {\n           var pom = Int32.Parse(Label1.Text);\n           pom++;\n           Label1.Text = Convert.ToString(pom);\n        }\n\n        protected void Button2_Click(object sender, EventArgs e)\n        {\n           var pom = Int32.Parse(Label1.Text);\n           pom--;\n           Label1.Text = Convert.ToString(pom);\n        }\n    }\n}	0
2058070	2057829	Calculating MD5 of UTF-8 encoded string	require 'digest/md5'\n\ndef encode_password(password)\n  Digest::MD5.hexdigest(password).upcase\nend\n\n# Example:\nputs encode_password('foo bar')\n# => "327B6F07435811239BC47E1544353273"	0
24553999	24553923	display all values from the loop in one window	var stringBuilder = new StringBuilder();\nwhile (eN <= toE)\n{\n    stringBuilder.AppendLine("EN: " + eN.ToString());\n    eN += step;\n}\n\nMessageBox.Show(stringBuilder.ToString());	0
28428259	28428189	Split String by logicals with Regex	String[] result = text.Split(new Char[] { '|', '&' }, StringSplitOptions.RemoveEmptyEntries);	0
27573990	27573855	Retrieving entities as SelectListItems	var wtf = db.Departments.ToList()\nvar dafuq = new SelectList(wtf, "Id", "Name");\nViewBag.Departments = dafuq;\n\nreturn View(model);	0
10259862	10258250	Disabling button from another class	public static Button hit;	0
15686190	15685950	Grouping duplicate items in a list, and adding their totals	var groupedList = shoppingList.GroupBy( item => item.[the property you want to group by on]);\n\nforeach (var g in groupedList)\n{\n   var sum = g.Sum( i => i.[the property you want to sum]);\n}	0
15836810	15835505	How to expand a line to make a rectangle or region	GraphicsPath gfxPath = new GraphicsPath();\ngfxPath.AddLine(line.x1, line.y1, line.x2, line.y2);\ngfxPath.Widen(new Pen(Color.Blue, lineThickness));//lineThinkness is all that matters\nRegion reg = new Region(gfxPath);\n\nif (reg.IsVisible(mousePoint)) // return true if the mousePoint is within the Region.	0
20477225	20477120	How can I launch a local VBScript with arguments from a C# console application?	System.Diagnostics.Process.Start(\n    @"C:\my folder\import.vbs",\n    String.Format("{0} {1}", agr1, agr2));	0
8487230	8487115	To get which object requested this window to show	public class GraphOneWindow:Form\n{\n   public GraphOneWindow(object sender)\n   {\n       InitializeComponent();\n       //cast and use sender here\n   }\n}\n\nprivate void menuItemTemp_Click(object sender, EventArgs e)\n{\n   (new GraphOneWindow(sender)).Show();\n}	0
5047598	5047484	Format a TimeSpan string	string.Format("{0:hh\\:mm\\:dd\\.ff}", yourTimeSpan)	0
32320824	32286007	Offline Search in DataGridView that is binded to a DataTable and Perform an Add or Update	try\n{\n    for (int i = 0; i < dataGridView1.RowCount; i++)\n    {\n        if (dataGridView1.Rows[i].Cells[0].Value.ToString() == txt_FName.Text)\n        {\n            dataGridView1.Rows[i].Cells[2].Value = [any proccess] ; // Update Row\n            return;\n        }\n    }\n}\ncatch(Exception ex)\n{\n    MessageBox.Show(ex.Message);\n}\ndataGridView1.Rows.Add(txt_FName.Text, txt_LName.Text, txt_Number.Text); // New Row	0
29623980	29489693	Generate PDF controlled by action filters?	// look for parameter ?print in the request query string\n// manipulate response to return a filestream instead of json data	0
4522251	4520184	How to detect the character encoding of a text file?	encoding=	0
32867533	32837084	Use Webbrowser control to get and post data?	String postdata = "value1=" + 1 + "&value2=" + 2 + "&value3=" + 3;\nSystem.Text.Encoding encoding = System.Text.Encoding.UTF8;\nbyte[] byte = encoding.GetBytes(postdata);\nstring url = "http://www.domain.com/addSomething";\nwebBrowser1.Navigate(url, string.Empty, byte, "Content-Type: application/x-www-form-urlencoded");	0
3415724	3415657	How to convert a symbol - " ? " to HTML code?	&dagger;	0
19959471	19957630	CRM 2013 - Incident Resolution - Retrieve New Status Reason	Entity incident = localContext.OrganizationService.Retrieve("incident", ((EntityReference)incidentResolution["incidentid"]).Id, colSet);	0
8667163	8666718	How can I insert image in Access table	var oleDbConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\sample.accdb");\nvar oleDbCommand = oleDbConnection.CreateCommand();\noleDbCommand.CommandText = "insert into Table1 (Name, Photo) values (@name, @photo)";\noleDbCommand.Parameters.AddWithValue("@name", "MyName");\nbyte[] yourPhoto = GetYourPhotoFromSomewhere();\noleDbCommand.Parameters.AddWithValue("@photo", yourPhoto);\nusing (oleDbConnection)\n{\n    oleDbConnection.Open();\n    oleDbCommand.ExecuteNonQuery();\n}	0
26479083	26478742	changing contents of a grid in wpf dynamically	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n// first remove the existing content within grid\ngrid1.Children.Clear();\n// then add your user contrl here\ntestapp.UserControl1 usercontrol = new testapp.UserControl1();\ngrd1.Children.Add(usercontrol);\n\n\n    }	0
20900241	20892923	Simplest way to store List of Objects in Windows Phone 8	public class MyList\n{\npublic int IntData {get;set;}\npublic DateTime MyDate {get;set;}\npublic string MyString {get;set;}\n}\n//Create list \nList<MyList> myList = new List<MyList>();\nmyList.add(new MyList{IntData =1,MyDate = DateTime.Now.Date,MyString ="abc"});\nmyList.add(new MyList{IntData =2,MyDate = DateTime.Now.Date,MyString ="bcc"});\nmyList.add(new MyList{IntData =3,MyDate = DateTime.Now.Date,MyString ="agggbc"});\n\n//save myList into IsolatedStorageSettings \n\nIsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n\nsettings.Add("MyDataKey",myList);\nsettings.Save();\n\nList<MyList> getSavedListData = new List<MyList>();\nif(settings.Contains("MyDataKey"))\ngetSavedListData =(List<MyList>)settings["MyDataKey"] ;//Here is the data	0
10936169	10936096	MySQL Casting in C#	finalstring += reader.GetValue(i).ToString() + ",";	0
25780766	25777661	Routing on same URL in MVC4	public override void RegisterArea(AreaRegistrationContext context) \n    {\n        context.MapRoute(\n            "Authentication_Account",\n            "Authentication/SignIn",\n            new\n            { \n                controller = "Account",\n                action = "SignIn",\n                id = UrlParameter.Optional\n            },\n            new[] { "MyApp.Areas.Authentication.Controllers" });\n    }	0
30871906	30871084	How to filter data by LINQ when data is coming from CSV file	var csvlines = File.ReadAllLines(@"M:\smdr(backup08-06-2015).csv");\nvar csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray());\n\n// i am assuming that line[7] is the Party1Name Column\n// now you have a (sorted) group with n "members" (ACC, Sales, ..., n )\nvar groupOfUser = from line in csvLinesData \n                  group line by line[7] into newGroup \n                  orderby newGroup.Key \n                  select newGroup;\n\n// The Key of your userOfGrp is the Name e.g. "ACC"\n// i am assuming that x[4] is the direction Column\n// I count all I or O and put them into the new User\nvar user = (from userOfGrp in groupOfUser\n            select\n                new User()\n                    {\n                        CSRName = userOfGrp.Key,\n                        Incomming = userOfGrp.Count(x => x[4] == "I"),\n                        Outgoing = userOfGrp.Count(x => x[4] == "O")\n                    }).ToList();	0
9863152	9863015	How to access multiple rows in a gridview	string DividendAmount = GVR.Cells[5].Text;\nstring MOP = GVR.Cells[4].Text;	0
21040560	21038615	How to check WPF window open or close	public static T IsWindowOpen<T>(string name = null)\n    where T : Window\n{\n    var windows = Application.Current.Windows.OfType<T>();\n    return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name));\n}\n\nprivate void MenuItem1_OnClick(object sender, RoutedEventArgs e)\n{\n    var window = IsWindowOpen<Window>("TestForm");\n\n    if (window != null)\n    {\n        window.Focus();\n    }\n    else\n    {\n        window = new Window1 { Name = "TestForm", Title = "Welcome", };\n        window1.Show();\n    }\n}	0
6527606	6524749	how to make a query with NHibernate?	// you need an ISession variable -- here let's assume it is called session\nvar operatorNum = 5;\nvar query = session.CreateQuery(\n    @"from Employee emp where emp.OperatorNum = :operatorNum")\n    .SetProperties(new { operatorNum });\nvar employee = query.UniqueResult<Employee>();\n\n// you can now get the collection of production metrics in the\n// employee.ProductionbyEmployee property; note that if you have\n// not mapped this collection to be eagerly fetched, you'll get\n// a second roundtrip to the database to get the collection	0
17771378	17756339	Playing a sound effect in windows phone 7.1 by tapping a canvas	private void PlayDuuuu()\n{\n    StreamResourceInfo stream = Application.GetResourceStream(new Uri("/AppName;component/Untitled.wav", UriKind.Relative));\n    SoundEffect soundeffect = SoundEffect.FromStream(stream.Stream);\n    SoundEffectInstance soundInstance = soundeffect.CreateInstance();\n    FrameworkDispatcher.Update();\n    soundInstance.Play();\n}	0
16695628	16695560	C# regex matching exact string in a line but ignore case	public static bool ExactMatch(string input, string match)\n{\n    return Regex.IsMatch(input, string.Format(@"\b{0}\b", Regex.Escape(match)), RegexOptions.IgnoreCase);\n}	0
32974398	32974002	How to handle DivideByZeroExeption	//Methode zum Geteiltrechnen\n        public int geteiltdurch(int zahl_1, int zahl_2)\n        {          \n           if(zahl_2!= 0)\n            {             \n                return zahl_1 / zahl_2;\n            }     \n           else\n            {\n                Console.WriteLine("Die Division durch 0 ist verboten!");\n                Console.Write("Please enter another divisor: ");\n                zahl_2 = Convert.ToInt32(Console.ReadLine());\n                //You'll want to do some validation here.\n                return geteiltdurch(zahl_1, zahl_2);\n            }\n        }	0
10281930	10281520	Clear Text in RichBox in C#	private void richTextBox1_Click(object sender, EventArgs e)\n{\n  if (richTextBox1.Text == "Input Text Here")\n  {\n    richTextBox1.Clear();\n    richTextBox1.Focus();\n  }\n}	0
4023787	4022995	Printing content of WebBrowser Control in C#	IWebBrowser2.ExecWB(OLECMDID_PRINT)	0
25991777	25989787	How do I make this table shorter?	int _row = 1;\n        int _cell = 0;\n        string[] arr = new string[6] { "ID", import.oCultivationPlan.iID.ToString(), "Description", import.oCultivationPlan.sDescription.ToString(), "DateCreated", import.oCultivationPlan.dDateCreated.ToString() };\n        for (; _row <= 3; _row++)\n        {\n            TableRow tblRow = new TableRow();\n            for (; _cell < _row * 2; _cell++)\n            {\n                TableCell tblc = new TableCell();\n                tblc.Controls.Add(new LiteralControl(arr[_cell]));\n                tblRow.Controls.Add(tblc);\n            }\n\n            tblImportPreview.Controls.Add(tblRow);\n        }	0
5555249	5554845	Can we use generic list instead of array of objects C#	var query = from i in Enumerable.Range(0, 100)\n            where some_condition\n            select new Student() { Id = ids[i], Name = names[i] };\nvar students = query.ToList();	0
22145619	22145543	Asp.net Web Api query string parameter with dash	[DataMember]	0
20537773	20537572	DateTime.ParseExact - iso8601 with time zone offset	DateTime d = DateTime.Parse("2013-12-11T14:36:00+01:00");\n        Debug.Print(d.ToString());\n        Debug.Print(d.ToUniversalTime().ToString());	0
10991906	10991808	Remove set of elements from list A and add into list B using Linq	processedLines.AddRange(lines.Where(x => x.P2.x < sweepPosition));\nlines = lines.Where(x => x.P2.x >= sweepPosition).ToList();	0
30522391	30519036	Lucene.Net - how to retrieve a single Document	doc.Add(new Field("Id", searchResult.Id,Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));	0
11075019	10627217	Get video duration without playing?	media.MediaOpened += new System.Windows.RoutedEventHandler(media_MediaOpened);\n            media.LoadedBehavior = MediaState.Manual;\n            media.UnloadedBehavior = MediaState.Manual;\n            media.Play();\n\nvoid media_MediaOpened( object sender, System.Windows.RoutedEventArgs e )\n        {\n            progress.Maximum = (int)media.NaturalDuration.TimeSpan.TotalSeconds;\n            timer.Start();\n            isPlaying = true;\n        }	0
15489943	15489769	Insert using stored procedure is very slow	INSERT INTO dbo.School_Student(School_ID, Student_ID)\n     SELECT SC.ID, ST.ID\n     FROM dbo.School AS SC\n     JOIN dbo.Student AS ST ON ST.Student_Name = @studentName\n                            AND SC.School_Name = @schoolName;	0
22040849	22040255	Getting the size of a S3 image from Stream using C#	using (var fileTransferUtility = new TransferUtility(client))\n            {\n                var request = new TransferUtilityDownloadRequest();\n                request.BucketName = BucketName;\n                request.FilePath = desination;\n                request.Key = key;\n\n                fileTransferUtility.Download(request);\n            }	0
32896631	32896564	How to return correctly cast IEnumerable	private static ICollection<T> GetSpecificTypeList<T>(Dictionary<string, List<object>> objectListDictionary)\n{\n    Contract.Requires(objectListDictionary != null);\n    Contract.Requires(specificType != null);\n\n    var list = new List<T>();\n    var collection = objectListDictionary.SingleOrDefault(q => q.Key.Equals(typeof(T).FullName)).Value;\n    foreach (var obj in collection.OfType<T>())\n    {\n        list.Add(obj);\n    }\n\n    return list;\n}	0
9848636	9845200	Set selection to view box	public void populateButtons()\n    {\n        double xPos;\n        double yPos;\n\n        UniformGrid grid = new UniformGrid();\n        viewbox1.Child = grid;\n\n        Random ranNum = new Random();\n        foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })\n        {\n            Button foo = new Button();\n            Style buttonStyle = Window.Resources["CurvedButton"] as Style;\n            int sizeValue = 100;\n\n            foo.Width = sizeValue;\n            foo.Height = sizeValue;\n\n            xPos = ranNum.Next(200);\n            yPos = ranNum.Next(250);\n\n\n            foo.HorizontalAlignment = HorizontalAlignment.Left;\n            foo.VerticalAlignment = VerticalAlignment.Top;\n            foo.Margin = new Thickness(xPos, yPos, 0, 0);\n            foo.Style = buttonStyle;\n\n            foo.Click += routedEventHandler;\n\n            grid.Children.Add(foo);\n        }\n    }	0
19850777	19850543	How to know the page break in Excel using C#	foreach (Excel.HPageBreak pageBreak in worksheet.HPageBreaks)\n{\n    int row = pageBreak.Location.Row - 1;\n\n    // ...\n}	0
16688711	16688575	SqlParameters in Repository unit of work pattern	public bool CanLock(int spvId)\n{\n  SqlParameter[] parameter = { new SqlParameter ("spvId", spvId) };\n  bool isLock = ExecuteProcedure("Exec prc_SitePartVrsn_CanLock @spvId", parameter);\n  return false;\n}	0
4406961	4406928	c# string split and combine	string s = "1,4,14,32,47";\nstring r = String.Join(",", s.Split(',').Where((x, index) => index != 1).ToArray());	0
2236038	2236025	How can I Compress a directory with .NET?	string[] MainDirs = Directory.GetDirectories(DirString);\n\nfor (int i = 0; i < MainDirs.Length; i++)\n{\n    using (ZipFile zip = new ZipFile())\n    {\n        zip.UseUnicodeAsNecessary = true;\n        zip.AddDirectory(MainDirs[i]);\n        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;\n        zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");\n        zip.Save(string.Format("test{0}.zip", i));   \n    }\n}	0
25291687	25289792	how will the timer save the application start time and the application end time to text file?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        using (System.IO.StreamWriter streamWriter = new StreamWriter("Report.txt", false)) \n        {\n            streamWriter.WriteLine(string.Format("Start Time : {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));\n        }\n    }\n\n    private void Form_Closed(object sender, EventArgs e)\n    {\n        using (System.IO.StreamWriter streamWriter = new StreamWriter("Report.txt", true)) \n        {\n            streamWriter.WriteLine(string.Format("End Time : {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));\n        }\n    }\n}	0
4371951	4371889	Get characters behind the dot in of a double	stuffToTheRight = value % 1	0
26735471	26735247	How to copy a 1D array to 3D array efficiently in C#?	public static byte[,,] ToBuffer3Da(this byte[] buffer, int w, int h)\n{\n    byte[,,] buff3D = new byte[h, w, 1];\n    Buffer.BlockCopy(buffer, 0, buff3D, 0, h*w);\n    return buff3D;\n}	0
17169153	17168934	Data not displaying in datagrid	SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");\n                thisConnection.Open();    \n                string Get_Data = "SELECT * FROM emp";  \n                SqlCommand cmd = thisConnection.CreateCommand();\n                cmd.CommandText = Get_Data;\n                SqlDataAdapter sda = new SqlDataAdapter(cmd);               \n                DataTable dt = new DataTable("emp");\n                sda.Fill(dt);\n               // Here:                \n               dataGrid1.DataContext = dt.DefaultView;	0
10663790	10663722	Entity framework, insert object based on specific condition	var db = new YourContext();\nvar emp = db.Employees.Find(empID) ?? db.Employees.Add( new Employee { FirstName ="xx" , LastName="xxx"});\ndb.SaveChanges();	0
16439593	16439526	Create one List from several different lists of the same type with C#	var MCS_DocumentFields = headerItems.Concat(drawItem)\n                                .Concat(bodyItems)\n                                .Concat(footerItems)\n                                .ToList();	0
3423837	3423786	How Can I Create a PDF Quotation File from Winform?	// Create a new PDF document\n  PdfDocument document = new PdfDocument();\n  document.Info.Title = "Created with PDFsharp";\n\n  // Create an empty page\n  PdfPage page = document.AddPage();\n\n  // Get an XGraphics object for drawing\n  XGraphics gfx = XGraphics.FromPdfPage(page);\n\n  // Create a font\n  XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);\n\n  // Draw the text\n  gfx.DrawString("Hello, World!", font, XBrushes.Black,\n    new XRect(0, 0, page.Width, page.Height),\n    XStringFormats.Center);\n\n  // Save the document...\n  const string filename = "HelloWorld.pdf";\n  document.Save(filename);\n  // ...and start a viewer.\n  Process.Start(filename);	0
115106	115031	An Issue with converting enumerations in C++\CLI	property System::ServiceProcess::ServiceControllerStatus Status  \n{  \n    System::ServiceProcess::ServiceControllerStatus get()  \n    {  \n        return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState;   \n    }  \n}	0
33383860	33382880	How to use EF7 and connect to SQL Server without startup.cs in ASP.NET 5 Beta 8 console application?	var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNet5;Trusted_Connection=True;";\n\nSampleConsoleDbContext scab = new SampleConsoleDbContext(connection);	0
7928322	7918359	Is there a reason why I cant get the values from the following two elements?	string url = String.Format("http://api.samknows.com/checker.do?user={0}&pass={1}&phone=\n{2}&postcode={3}&buildingnum={4}&checks={5}&options{6}&output{7}"	0
13574275	13574111	How do I move a circle down upon user click? Connect Four C#	while(true)	0
27568089	27511501	Using multiple tables in Index View in MVC	[Authorize(Roles = "ADMINISTRADOR")]\n    public ActionResult Index(SINCO_LOCALIDADE_CONCESSAO model)\n\n         {\n                      return View("Index", db.SINCO_LOCALIDADE_CONCESSAO.Include(s => s.LOCALIDADES_VIEW).Include(s => s.MUNICIPIOS_VIEW));\n\n }	0
31061899	31061633	Custom Union in Linq to Entities	foos.Union(bars).GroupBy(x => new { x.bizId, x.bazId })\n    .Select(g => g.FirstOrDefault())	0
11192606	11180903	Use a storyboard to call a method in a usercontrol created dynamically	CompositionTarget.Rendering	0
33514574	33514306	wcf reference with nested arrays inaccessible due to its protection level	objRetTable.ProcessDataTableMachinery[iIndex].DataTableValues = new RemoteWebService.SingleDataMachinery[1];	0
4124216	4124100	Running a Stored Procedure in C# Button	using (SqlConnection dataConn = new SqlConnection(ConnectionString))\n        {\n            dataConn.Open();\n\n            using (SqlCommand dataCommand = dataConn.CreateCommand())\n            {\n                dataCommand.CommandType = CommandType.StoredProcedure;\n                dataCommand.CommandText = "InsertData";\n\n                dataCommand.Parameters.AddWithValue("@QuoteNumber", quote); \n                dataCommand.Parameters.AddWithValue("@ItemNumber", item); \n\n                dataCommand.ExecuteNonQuery();\n            }\n        }	0
20398043	20397978	syntax error in expression when trying to select from a DataTable	DataRow[] filterRow = Productdt.Select("CATEGORY_ID=" + catID);	0
14260795	14260710	How can I refactor the Switch Statements	Dictionary<string, string> fileMappings =\n   prepareElements.ToDictionary(e => e.MappingName, e => e.FileName);	0
32110073	31646901	String was not recognized as a valid DateTime when string is 13/07/15	DateTime dt = Convert.ToDateTime(date);	0
6261550	6260911	how remove the BOM(???) characters from a UTF 8 encoded csv?	public static void SaveAsUTF8WithoutByteOrderMark(string fileName)\n    {\n        SaveAsUTF8WithoutByteOrderMark(fileName, null);\n    }\n\n    public static void SaveAsUTF8WithoutByteOrderMark(string fileName, Encoding encoding)\n    {\n        if (fileName == null)\n            throw new ArgumentNullException("fileName");\n\n        if (encoding == null)\n        {\n            encoding = Encoding.Default;\n        }\n\n        File.WriteAllText(fileName, File.ReadAllText(fileName, encoding), new UTF8Encoding(false));\n    }	0
13387561	13349836	How to detect reordering of ListView items	ObservableVector<object>	0
4477466	4477284	Controls not allowing to enter new data after databinding statically	myBindingNavigator.BindingSource.AddNew();\nmyBindingNavigator.BindingSource.MoveLast();	0
33411587	33411226	Reading bool values using a list	private void SomeMethod()\n{\n   List<int> inductionList = new List<int>() { 90, 120};\n   int? introTime = 0;\n   bool isEquelToNinety = false;\n   foreach (var items in inductionList)\n   {\n      Console.WriteLine(isEquelToNinety=IsOK(items));\n   }            \n}\n\nprivate bool IsOK(int? introTime)\n{            \n   if (introTime == 90)\n   {\n      return true;\n   }\n   else\n   {\n      return false;\n   }\n}	0
17299778	17283501	Update XML LINQ from ListBox	// Remove all "file" elements from selected record\n            uElem.Descendants("file").ToList().ForEach(i => i.Remove());\n            // Now add the elements from the listbox\n            foreach (string s in lbFilesToProcess.Items)\n            {\n                // Add the new "file" element with the values from the listbox\n                uElem.Element("filestoProcess").Add(new XElement("file", s));\n            }	0
525594	525583	a problem with GUI using C#	button.Enabled = Condition; // Initial value\n\n\n// user clicked on button\nbutton.Enabled= false; \n ... do button's function ...\nbutton.Enabled = Condition	0
12348404	12348104	How to lock read sql server for scheduler in multiple machine	SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\nGO\n\nDECLARE @CURR_JOBID int;\n\nSELECT @CURR_JOBID=top 1 ID FROM JOB_TABLE WHERE Flag=0 and <other condtions>\n\nBEGIN TRANSACTION\n\nUPDATE JOB_TABLE set Flag=1 where ID=@CURR_JOBID \n\nCOMMIT\n\nSET TRANSACTION ISOLATION LEVEL READ COMMITED;\nGO	0
20052750	20034612	How to pass parameters to DbMigration.Sql() Method	MigrationOperation.AnonymousObject	0
23198638	23113991	How to link a windows form in one project to a button in another project using MVC3	Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        SomeForm form1 = new SomeForm();\n        Application.Run(form1);	0
19412557	19412274	Listview double click not working correctly	var inlineHandler = new DoWorkEventHandler ( delegate(object o, DoWorkEventArgs args) \n{\n    BackgroundWorker b = o as BackgroundWorker;\n    pInfo = pInfoClient.DownloadString("get info from web").Trim();\n    bw.DoWork -= inlineHandler;\n\n});\nbw.DoWork += inlineHandler;	0
31378213	31377382	Pass parameters via EF to be available in SQL Server triggers (and connection pooling?)	DbContext.SaveChanges()	0
32872046	32871605	asp.net deny specific user cookie during login	protected void Application_AuthenticateRequest(Object sender, EventArgs e)\n{\n    var context = HttpContext.Current;\n\n    if (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated)\n    {\n        if (SomeClass.UserIsExpired(context.User))\n        {\n            // Clear cookies or whatever you need to do\n            // Throw a 401 to deny access\n            throw new HttpException(401, "User account is expired");\n        }\n    }\n}	0
17032754	17032663	Setting multiple properties with one declaration in Windows Forms (C#)	var someControl = new Control() {\n                         Text = "SomeText",\n                         BackgroundImage "someImage.jpg" };	0
9499055	9498914	How to enable the GridView paging after showing 12 elements?	AllowPaging="True" PageSize="12"	0
12749226	12749019	linq calculated value with group by	var data = new[]\n    {\n        new {GrpField = "RED", Qty = 1, Price = 10},\n        new {GrpField = "RED", Qty = 2, Price = 10},\n        new {GrpField = "RED", Qty = 1, Price = 50},\n        new {GrpField = "BLUE", Qty = 2, Price = 30},\n        new {GrpField = "BLUE", Qty = 2, Price = 50},\n    };\n\nvar grouped =\n    from d in data\n    group d by d.GrpField\n    into g\n    select new {Group = g.Key, Sum = g.Sum(x => x.Qty * x.Price)};\n\nforeach(var g in grouped)\n    Console.WriteLine("{0} - {1}", g.Group, g.Sum);	0
23350734	23348391	Validate TextBox for specific string	int startIndex = 0, remaining = textBox.Text.Length;\n\nwhile ((startIndex = textBox1.Text.IndexOf(startIndex, textBox.Text.Length - startIndex)) > 0)\n{\n    MessageBox.Show("There is a link in here");\n    startIndex++;\n}	0
20964523	18392538	SecureString to Byte[] C#	IntPtr unmanagedBytes = Marshal.SecureStringToGlobalAllocUnicode(password);\nbyte[] bValue = null;\ntry\n{\n    byte* byteArray = (byte*)unmanagedBytes.GetPointer();\n\n    // Find the end of the string\n    byte* pEnd = byteArray;\n    char c='\0';\n    do\n    {\n        byte b1=*pEnd++;\n        byte b2=*pEnd++;\n        c = '\0';\n        c= (char)(b1 << 8);                 \n        c += (char)b2;\n    }while (c != '\0');\n\n    // Length is effectively the difference here (note we're 2 past end) \n    int length = (int)((pEnd - byteArray) - 2);\n    bValue = new byte[length];\n    for (int i=0;i<length;++i)\n    {\n        // Work with data in byte array as necessary, via pointers, here\n        bValue[i] = *(byteArray + i);\n    }\n}\nfinally\n{\n    // This will completely remove the data from memory\n    Marshal.ZeroFreeGlobalAllocUnicode(unmanagedBytes);\n}	0
7325874	7325735	Showing The Output Of Statement In BalloonTipText In NotifyIcon	StringBuilder sb = new StringBuilder();\n\nusing (SqlDataReader rdr = cmd.ExecuteReader())\n{\n  while (rdr.Read())\n  {\n    sb.AppendLine(rdr["name"].ToString() + ' ' + rdr["lname"].ToString());\n  }\n}\n\nnotifyIcon.BalloonTipText = sb.ToString();\nnotifyIcon.ShowBallonTip(30000);	0
34562511	34556127	Run Background Task at specific time - UWP	var task = RegisterBackgroundTask("TaskBuilder",\n                                      "TimeTriggeredTask",\n                                      TimeTrigger(1440, true),//1440 for the number of seconds in a day\n                                      null);	0
13693135	13692844	WebClient.DownloadFile stores a file that is too small	JPEG image data, JFIF standard 1.01	0
20938796	20938528	Reverse way to get double array values from IntPtr	double[] pastPoints = new double[4]; //id,x,y,z\nIntPtr a = Marshal.AllocCoTaskMem(sizeof(double) * pastPoints.Length);  // Allocate memory for result\npath.GetPoint(i, a);    // Generate result.\nMarshal.Copy(a, pastPoints, 0, pastPoints.Length);    // Copy result to array.\nMarshal.FreeCoTaskMem(a);\n\nSystem.Console.WriteLine(pastPoints[0]);\nSystem.Console.WriteLine(pastPoints[1]);\nSystem.Console.WriteLine(pastPoints[2]);\nSystem.Console.WriteLine(pastPoints[3]);	0
11571092	11570427	Given a list of items, each containing a subitem, get the subitems and remove duplicates	var empresaIds = verEmpresa.Select( v => v.empresa ).Distinct().ToList();\nvar emp = from p in db.Empresas\n          where empresaIds.Contains( p.id )\n          select p;	0
5409992	5409833	How to program a command application in visual studio to read a batch file	using(StreamReader batchReader = new StreamReader("path to batch file"))\n{\n    string batchCommand;\n    while(!batchReader.EndOfStream)\n    {\n        batchCommand = batchReader.ReadLine();\n        // do your processing with batch command\n    }\n}	0
16620731	16460935	Sending SMS for a bulk of users	a. The Message and Sender ID/ Sender GSM Number.\n\nb. The Destinations (as a comma delimited list). We'll assume 10,000 destinations	0
25489270	25485250	ZPL passing parameters to the labels prints with misplaced data	//pass the zpl generated from Zebra Designer Pro into this menthod\npublic string replaceParameterValues(string zplForLabel)\n{\n    StringBuilder zpl = new StringBuilder();\n    zpl.Apppend(zplForLabel);\n    //do this for all the paramters\n    zpl = zpl.Replace("<ParemeterName>", valueForTheParamter);\n\n    //pass this zpl to the printer for printing as it will contain \n    //all the values for the parameters \n    return zpl.ToString();\n}	0
26938057	26937642	How can I register IAuthenticationManager in Global.asax with StructureMap	x.For<IAuthenticationManager>().Use(ctx => HttpContext.Current.GetOwinContext().Authentication);	0
4069057	4068971	How to run a set of functions in parallel and wait for the results upon completion?	List<TResult> results = new List<TResults>();\nList<Func<T, TResult>> tasks = PopulateTasks();\n\nManualResetEvent waitHandle = new ManualResetEvent(false);\nvoid RunTasks()\n{\n    int i = 0;\n    foreach(var task in tasks)\n    {\n        int captured = i++;\n        ThreadPool.QueueUserWorkItem(state => RunTask(task, captured))\n    }\n\n    waitHandle.WaitOne();\n\n    Console.WriteLine("All tasks completed and results populated");\n}\n\nprivate int counter;\nprivate readonly object listLock = new object();\nvoid RunTask(Func<T, TResult> task, int index)\n{\n    var res = task(...); //You haven't specified where the parameter comes from\n    lock (listLock )\n    {\n       results[index] = res;\n    }\n    if (InterLocked.Increment(ref counter) == tasks.Count)\n        waitHandle.Set();\n}	0
27581930	27581498	EF6 load a property of related collection member	var acc = db.Accounts.Include(a => a.AccountImages.Select(ai => ai.Image));	0
858930	858887	Write PDF from binary in database	Response.ContentType = "application/pdf";\n        byte[] bytes = YourBinaryContent;\n\n        using (BinaryWriter writer = new BinaryWriter(context.Response.OutputStream))\n        {\n            writer.Write(bytes, 0, bytes.Length);\n        }	0
13606228	13599073	MongoDB Find based on contents of a collection in the record	db.yourCollection.find({Payments.InvoiceNumber: 1234})	0
178595	178578	How to disable "Security Alert" window in Webbrowser control	public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)\n{\n    return true;\n}\n\nServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);	0
9274818	9274732	C#: Retrieving value from DataTable using PrimaryKey	DataRow matchingRow = table.Rows.Find(7.0D);\ndouble value = (double)matchingRow["load"];	0
11293444	11293351	datagrid view select from the list and search from the textbox	foreach (DataGridViewRow row in this.dataGridView1.Rows)\n{                            \n    foreach (DataGridViewCell cell in row.Cells)\n    {\n         /* Your code here */\n    }\n}	0
5577434	5577370	C# DataContractSerializer SerializationException with Enum set in object field	[DataContract]\n[KnownTypeAttribute(typeof(MyEnum))]\npublic class TestClass	0
26628760	26626741	Wcf get raw request from operation	OperationContext.Current.RequestContext.RequestMessage.ToString()	0
20161853	20161768	How To Make A Child Execute Command Button in C#	int count = 1; //count clicks    \n   private void ButtonClick(object sender, EventArgs e)\n        {\n           if(count%2 == 0)\n           {\n              label1.Visible = false;\n              label2.Visible = true;\n              label3.Visible = false;\n           }\n           else if(count%3 == 0){\n              label1.Visible = false;\n              label2.Visible = false;\n              label3.Visible = true;\n           }\n           else{\n             label1.Visible = true;\n             label2.Visible = false;\n             label3.Visible = false;\n           }\n        count++;\n        }	0
9787909	9787276	 GridView1: How to save the selected value from the dropdownlist and make it visible	protected void GridViewRowUpdating(object sender, GridViewUpdateEventArgs e)\n    {\n          var rowIndex = e.RowIndex;\n          var row = GridView.Rows[rowIndex];\n          var ddl = row.FindControl("YOURDROPDOWN") as DropDownList;\n          if(ddl != null)\n          var value = ddl.SelectedValue;\n    }	0
13016158	13015655	How to add controls to datalist in code behind, not in aspx design?	namespace KetBanBonPhuong\n    {\n           [AjaxPro.AjaxNamespace("Default")]\n\n           public partial class Default1 : System.Web.UI.Page\n           {\n               protected void Page_Load(object sender, EventArgs e)\n               {\n                    AjaxPro.Utility.RegisterTypeForAjax(typeof(Default1));\n                    if(!isPostBack)\n                    {\n                DataList dl = new DataList();\n                dl.DataSource = GetList();\n                dl.DataBind();\n                this.liststatus.Controls.Add(dl);\n                dl.DataSource = GetList();\n                dl.RepeatLayout = RepeatLayout.Flow;\n                Literal ltr = new Literal();\n                ltr.Text = "kaldfs";\n\n                dl.Controls.Add(ltr);//Error here\n             }\n          }\n}	0
29802956	29802819	C# method pointer like in C++	Name testName = new Name("Koani");\nAction<Name> showMethod = name => name.DisplayToWindow();\nshowMethod(testName);	0
17358843	17358801	How to get sheetname of the uploaded excel file using C#?	OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0 xml;HDR=YES;'");\n                        connection.Open();\n                        DataTable Sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n           foreach (DataRow dr in Sheets.Rows)\n                    {\n                       string sht = dr[2].ToString().Replace("'", "");\n                        OleDbDataAdapter dataAdapter = new OleDbDataAdapter("select * from [" + sht + "]", connection);\n    }	0
12897057	12110943	Sort and Filter supported list in sync with EF entity	if (f.Value.type == AdvFilterTypes.Contains)\n    tmpList = tmpList.AsQueryable().Where(f.Value.property + ".Contains(\"" + f.Value.condition.Replace(@"\", @"\\").Replace("\"", "\\\"") + "\")");\nelse\n    tmpList = tmpList.AsQueryable().Where(f.Value.property + " " + f.Value.typeSymbole + " " + f.Value.condition);	0
24017926	24003887	How properly implement equalization using band pass filer	// Input signal is in buffer[0] to buffer[buffer.length-1]\n    // accumulator[] and buffer2[] are also pre-allocated to the same length as buffer[].\n\n    // Initialize output accumulator to zero\n    for (int i = 0; i < accumulator.length; ++i)  accumulator[i] = 0;\n    // Apply each bandpass filter to copies of the original input\n    for (int i = _sampleFilters.Count; i-- > 0; ) {\n        // Make a copy of the input\n        for (int j = 0; j < buffer.length; ++j)  buffer2[j] = buffer[j];\n        // Apply this filter in-place\n        _sampleFilters[i].Filters[c].Process(buffer2, buffer2.length);\n        // Accumulate the result\n        for (int j = 0; j < accumulator.length; ++j)\n            accumulator[j] += buffer2[j]\n    }\n    // Copy back into buffer for output\n    for (int i = 0; i < buffer.length; ++i)  buffer[i] = accumulator[i];\n}	0
20816193	20815836	Retrieving data from a second table if it has a record with the Id from another table	using (var _db = new YourDbContext())\n{\n    var movies = _db.Movies;\n    var movieReviews = _db.MovieReviews;\n\n    var results = movies.Join(movieReviews, \n        m => m.Id,\n        mr => mr.MovieId,\n        (m, mr) => new { MovieName = m.Name, ReviewerName = mr.ReviewerName }).ToList();\n}	0
34492459	34492319	How to get Screenshot of Form with UserControl?	private void CaptureForm()\n{\n    var bmp = new Bitmap(MainForm.Width, MainForm.Height, PixelFormat.Format32bppArgb);\n\n    var g = Graphics.FromImage(bmp);\n    g.CopyFromScreen(MainForm.Location.X, MainForm.Location.Y, 0, 0,\n                    MainForm.Size, CopyPixelOperation.SourceCopy);\n\n    //Clipboard.SetImage(bmp);\n\n    pictureBox1.Image = bmp;\n}	0
16333956	16333068	How do I add default null values in a Linq join statement	DateTime start = DateTime.Today.AddDays(-21);\n\n//Sample view data\nvar viewsData = new[] {new {id = "id", date = new DateTime(2013, 4, 12), views = 25}};\n\nvar dates = Enumerable.Range(0, 21)\n                        .Select(d => start.AddDays(d))\n                        .Select(n => new\n                                        {\n                                         Day = n,\n                                         views =viewsData.Any(x => x.date == n)\n                                         ? viewsData.FirstOrDefault(v => v.date == n).views\n                                         : 0\n                         });	0
2170589	2170579	Convert an unsigned 16 bit int to a signed 16 bit int in C#	UInt16 x = 65535;\nvar y = (Int16)x; // y = -1	0
2886937	2886722	compile cs files with mono?	gmcs  Pages/UserProfile.cs   Properties/AssemblyInfo.cs   queues.cs   watch_editor.cs Class1.cs -define:USE_SQLITE -r:System	0
9005467	9005381	Creating a ajaxToolkit TabPanel in Code Behind	TabPanel FirstTab= new TabPanel();  \nFirstTab.ID = "Tab1";  \nFirstTab.HeaderText = "First Tab";  \n\nTabPanel SecondTab = new TabPanel();  \nSecondTab.ID = "Tab2";  \nSecondTab.HeaderText = "Second Tab";  \n\nTabContainer1.Tabs.Add(FirstTab);  //add it to the Tab Container control \nTabContainer1.Tabs.Add(SecondTab);  \n\n//to added content on it you can do like this \nImage _image = new Image();\n_image.ID = "image";\n_image.ImageUrl = "~/images/test.gif";\nFirstTab.Controls.Add(image);\n\nTabContainer1.ActiveTabIndex = 0;  // set your active tab index to display.	0
28307409	28300958	Get row in TableView DevExpress	void TableView_MouseDown(object sender, MouseButtonEventArgs e) {\n    int rowHandle = grid.View.GetRowHandleByMouseEventArgs(e);\n    object wholeRowObject = grid.GetRow(rowHandle);\n    object rowId = grid.GetCellValue(rowHandle, "Id");   // cell value of row-object's Id property \n}	0
19963579	19730610	creating a webservice that accepts a file (Stream) doesnt want other params	public string NewImage(Stream data){\n    NameValueCollection PostParameters = HttpUtility.ParseQueryString(new StreamReader(data).ReadToEnd());\n    string server = PostParameters["server"],\n    string datasource = PostParameters["datasource"], \n    string document = PostParameters["document"];\n    string image_id = PostParameters["image_id"];\n    var img = PostParameters["File"];\n\n    //do other processing...\n}	0
28998777	28998605	How to get the X value from a known Y value for a line chart in C#?	public static int GetX(int y, Point a, Point b)\n{\n    var m = CalculateSlope(a, b);\n\n    // Horizontal line (x-values are always the same)\n    if (m == 0.0)\n        return a.X;\n\n    var c = a.Y - a.X * m;\n\n    return Convert.ToInt32((y - c) / m);\n}\n\npublic static int GetY(int x, Point a, Point b)\n{\n    var m = CalculateSlope(a, b);\n\n    // Vertical line (y-values are always the same)\n    if (double.IsPositiveInfinity(m))\n        return a.Y;\n\n    var c = a.Y - a.X * m;\n\n    return Convert.ToInt32(m * x + c);\n }\n\n\npublic static double CalculateSlope(Point a, Point b)\n{\n    if (b.Y == a.Y)\n        return double.PositiveInfinity;\n\n    if (b.X == a.X)\n        return 0.0;\n\n    return (Convert.ToDouble(b.Y) - Convert.ToDouble(a.Y)) / (Convert.ToDouble(b.X) - Convert.ToDouble(a.X));\n}	0
18621805	18615673	How to get more than 1000 entities from an azure table storage query?	var data = context.CreateQuery<SomeEntity>("table").AsTableServiceQuery<SomeEntity>().Execute();	0
15006219	15005851	Updating controls in Main Thread using EventHandler	private void ShowHourGlassSafe(bool visible) {\n        this.BeginInvoke(new Action(() => something.Visible = visible));\n    }	0
10095939	10095835	Dictionary with array of different data types as value	Dictionary<long, object[]> netObjectArray = new Dictionary<long, object[]>();\nfor (int i = 0; i < 100; i++) netObjectArray[i] = new object[100];//This is what you're missing.\nnetObjectArray[key][2] = val;	0
13175870	13172719	UserControl Loses Data	public ucType UserControlType {\n   set {\n      ViewState["UserControlType"] = value; \n   }\n   get { \n      object o = ViewState["UserControlType"]; \n      if (o == null)\n         return ucType.CustomersWhoHaveAContract; // default value\n      else \n         return (ucType)o; \n   }\n}	0
22504875	22504816	Finding an index in a list of generic objects with multiple conditions	int index = test.FindIndex(item => item.ID == someIDvar\n                                && item.OtherID == someOtherIDvar);	0
2830554	2830073	Detecting a Dispose() from an exception inside using block	bool isInException = Marshal.GetExceptionPointers() != IntPtr.Zero\n                        || Marshal.GetExceptionCode() != 0;	0
5483916	5483872	Read from a file that changes everyday in C#	string filename = "SAPHR_Joiners_" + DateTime.Now.ToString("yyyyMMdd");\nstring[] filecontents = File.ReadAllLines( filename );	0
31344769	31340584	C# - ProgressBar with Marquee style	private void button1_Click(object sender, EventArgs e)\n    {\n        button1.Enabled = false;\n        progressBar1.Style = ProgressBarStyle.Marquee;\n        progressBar1.MarqueeAnimationSpeed = 50;\n\n        BackgroundWorker bw = new BackgroundWorker();\n        bw.DoWork += bw_DoWork;\n        bw.RunWorkerCompleted += bw_RunWorkerCompleted;\n        bw.RunWorkerAsync();\n    }\n\n    void bw_DoWork(object sender, DoWorkEventArgs e)\n    {\n        // INSERT TIME CONSUMING OPERATIONS HERE\n        // THAT DON'T REPORT PROGRESS\n        Thread.Sleep(10000);\n    }\n\n    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n    {\n        progressBar1.MarqueeAnimationSpeed = 0;\n        progressBar1.Style = ProgressBarStyle.Blocks;\n        progressBar1.Value = progressBar1.Minimum;\n\n        button1.Enabled = true;\n        MessageBox.Show("Done!");\n    }	0
15162265	15162152	Troubles with updating ToolstripDropdownButton after window loses focus	private void toolStripDropDownButton1_Click(object sender, EventArgs e) {\n  this.BeginInvoke(new Action(() => MessageBox.Show("Help")));\n}	0
26452697	26452275	Ensuring user input is not a string	// Just to enter the loop the first time....\ndouble pizzaDiameter = 1.0d;\nconst double QUIT_PROGRAM = 0.0d;\n\nwhile (pizzaDiameter != QUIT_PROGRAM) \n{\n     Console.Write("Please enter the diameter of your pizza: (0 to exit) "); \n\n     // Add the NOT operator in front of the TryParse call\n     if(!Double.TryParse(Console.ReadLine(), out pizzaDiameter))\n     {\n        ... false returned by TryParse\n        ... error message....\n     }\n     else if( .... check for diameter min/max .....)\n     {\n        ... diameter not valid error message\n     }\n     else\n     {\n        .... start calculus....\n     }\n     // end while here... \n     // if input is incorrect the loop restart until diameter = 0\n     // So, no need to ask again the pizza diameter in this point\n }	0
22436190	22436169	How to split string variable by multiple characters	var s_mas = s_var.Split(new[] { "   " }, StringSplitOptions.None);	0
27046320	27045841	How to read and write byte array line by line in text file	Convert.ToBase64String	0
5018203	5018135	Automatically Word-Wrapping Text To A Print Page?	Graphics gf = e.Graphics;\n         SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa", \n                         new Font(new FontFamily("Arial"), 10F), 60);\n         gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa", \n                         new Font(new FontFamily("Arial"), 10F), Brushes.Black,\n                         new RectangleF(new PointF(4.0F,4.0F),sf), \n                         StringFormat.GenericTypographic);	0
17459810	17459536	adding an array of data to a dropdown list from multiple databases	List<string> dataList = new List<string>(); // this line is global not inside a closed scoop\n var myDataTable = new System.Data.DataTable();\n using (var conection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source="+foldername+"\\Program\\Ramdata.mdb;Jet OLEDB:Database Password=****"))\n {\n    conection.Open();\n    var query = "Select u_company From t_user";\n    var command = new System.Data.OleDb.OleDbCommand(query, conection);\n    var reader = command.ExecuteReader();                    \n    while (reader.Read())\n    {\n       profselect.Text = reader[0].ToString(); \n       dataList.Add(profselect.Text);\n    }\n }\n myComboBox.DataSource = dataList;\n myComboBox.SelectedText = dataList.Last();	0
16407768	16407729	Creating a big array C#	int[,] array = new int[1600,900];\narray[600,400] = 10;\n\nfor(int x = 0; x < 1600; x++)\n{\n    for(int y = 0; y < 900; y++)\n    {\n        int something = colour[x,y];\n    }\n}	0
9739567	9739303	Check File Extension in Formview	string ext = System.IO.Path.GetExtension(this.File1.PostedFile.FileName);\nif (ext==txt){\nshow icons with navigt\n}	0
5786066	5785919	Help with SelectSingleNode, XML and C#	XmlNode entityTypeCode = xDoc.SelectSingleNode("//c:entityTypeCode", nsmgr);	0
34034754	34033242	how to add listview items in a windows form?	public partial class Form1 : Form\n{\n    Form2 form2;\n    public Form1()\n    {\n        InitializeComponent();\n        form2 = new Form2();\n        form2.Show();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        form2.button1_Click(null, null);\n    }\n}\n\npublic partial class Form2 : Form\n{\n    public Form2()\n    {\n        InitializeComponent();\n    }\n\n    public void button1_Click(object sender, EventArgs e)\n    {\n        listView1.View = View.Details;\n        listView1.Columns.Add("Log");\n        listView1.Items.Add(new ListViewItem(new string[] { "go2" }));\n    }\n}	0
5110656	5109170	EF Code First - Globally set varchar mapping over nvarchar	using System;\nusing System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive;\nusing System.Data.Entity.ModelConfiguration.Conventions.Configuration;\nusing System.Reflection;\n\npublic class MakeAllStringsNonUnicode :\n    IConfigurationConvention<PropertyInfo, StringPropertyConfiguration>\n{\n    public void Apply(PropertyInfo propertyInfo, \n                      Func<StringPropertyConfiguration> configuration)\n    {\n        configuration().IsUnicode = false;\n    }\n}	0
9279206	9279128	Passing generic parameter results in wrong overload being called	internal T CallDoSomething<T, U>(string someString, U ints) where T : class\n{\n    dynamic d = ints;\n    return DoSomething<T>(someString, d);\n}	0
6526235	6526195	how to sort the data before display it to the repeater?	protected void Page_Load(object sender, EventArgs e)\n{\n\n\n    var xNames = new List<OFullName>();\n    string TestString = "123ABCDEFGHIJK";\n    for (int i = 1; i <= 10; i++)\n    {\n        xNames.Add(new OFullName(ShuffleString(TestString), ShuffleString(TestString)));\n    }\n\n    Repeater1.DataSource = xNames.OrderBy(x => x.LastName); // sorts by last name Ascending. Use OrderByDesc to sort descending.\n\n    Repeater1.DataBind();//Bind data\n\n}	0
10391874	10391789	Data reader Display issue	textbox1.Text += reader["Person"].ToString().Trim() + reader["Occur"].ToString();	0
5367948	5367803	Windows report add to datasource list	reportViewer1.ProcessingMode = ProcessingMode.Local;\nreportViewer1.LocalReport.LoadReportDefinition(Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProject.Report1.rdlc"));\nreportViewer1.LocalReport.DataSources.Clear();\nvar dataSourcesNames = (ReadOnlyCollection<string>) reportViewer1.LocalReport.GetDataSourceNames();\nreportViewer1.LocalReport.DataSources.Add(new ReportDataSource(dataSourcesNames[0], objectCollection));//objectCollection is a List<MyObject>\nreportViewer1.RefreshReport();	0
9344216	9344188	File Compare with c#	public string ComputeHash(string filename)\n{\n    using(var sha1 = new SHA1CryptoServiceProvider())\n    {\n        byte[] fileData = File.ReadAllBytes(filename);\n        string hash = BitConverter.ToString(sha1.ComputeHash(fileData));\n\n    }\n}	0
10316942	10316867	Regex to remove consecutive sets of 1-2 characters separated by spaces	\b(.{1,2}\s){4,}	0
26045223	26042917	How can I remove white spaces from source string element in Biztalk?	public string removeWhitespace(string input)\n{\n    return Regex.Replace(input, @"\s+", "");\n}	0
16342290	16339167	C# .net how to deserialize complex object of JSON	using System.Web.Script.Serialization;\n\nJavaScriptSerializer oJS = new JavaScriptSerializer();\nRootObject oRootObject = new RootObject();\noRootObject = oJS.Deserialize<RootObject>(Your JSon String);	0
22717637	22673081	DataGrid Web Forms EditCommand/UpdateCommand. How to get changed value in TextBox	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n        BindData();\n    }\n}	0
11433204	11433122	Regular expression for phone number validation, number starting with 0 or + sign	^[+0]\d+	0
16439890	16438159	Give Specific Space on string	' This is how the first line appears in the string array after the space splitting'\nDim parts = new string() {"BL", "TH", ":", "NO",  "REF.", ":", "1234567890", "R.WAHYUDIYOINO,IR"}\n\n' This array contains the spaces reserved for each word in the string array above'\nDim spaces = new integer () {3,9,2,17,10,2,17,2,28 }\n\n' Now loop on the strings and format them as indicated by the spaces'\n' Attention, the value for space include the string itself'\nDim sb = new StringBuilder()\nDim x As INteger = 0\nFor each s in parts\n    sb.Append(s.PadRight(spaces(x)))\n    x += 1\nNext\nsb.AppendLine()\n' To check the result (it is useful only if the output window has fixed space font)'\nsb.Append("12345678901234567890123456789012345678901234567890123456789012345678901234567890")\nConsole.WriteLine(sb.ToString())	0
7104250	7104179	Problem with a C# csproj log file	System.Diagnostics.Trace	0
2711171	2711140	Visit neighbor of a position in a 2d-array	int[] dx = { 1, 1, 1, 0, 0, -1, -1, -1 };\nint[] dy = { 1, 0, -1, 1, -1, 1, -1, 0 };\nvoid Hit( int x, int y ) {\n    if ( board[x,y] == 0 ) {\n        board[x,y] = 10;\n        for ( int i = 0; i < 8; i++ ) {\n            nx = x + dx[i];\n            ny = y + dy[i];\n\n            // if nx, ny is in bound\n            if ( nx >= 0 && nx < height && ny >= 0 && ny < height )\n                Hit( nx, ny );\n        }\n    }\n}	0
1159604	1159582	How to index a string array	class Time \n{\n    public DateTime StartTime{ get; set; }\n    public DateTime EndTime{ get; set; }\n\n    public String[] ToStringArray() \n    {\n        String[] ret = new String[3];\n        ret[0] = StartTime.ToString();\n        ret[1] = EndTime.ToString();\n        ret[2] = ElapsedTime().ToString();\n        return ret;\n    }\n\n    public TimeSpan ElapsedTime() \n    {\n        return EndTime.subtract(StartTime);\n    }\n}	0
7811537	7811481	How to save doc file using C#	oDoc.SaveAs("MyFile.doc", ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);	0
8472765	8472558	Convert path to UNC path	X:\foo\bar	0
18351874	18272947	DatagridViewComboboxCell value changed in C#	this.columnName.ValueType = typeof(long);	0
13227708	13227669	Populating datagrid by changing data available in datatable	protected void GridViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row .RowType == DataControlRowType .DataRow )\n        {\n           e.Row.Cells[2].Text = (e.Row.Cells[2].Text=="Y" ? "YES" : "NO"); \n        }\n    }	0
5662846	5551903	C# WPF Draggable UserControls in ListBox on Canvas	private static void element_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n        {\n            FrameworkElement element = sender as FrameworkElement;\n            if (element == null) return;\n            Debug.WriteLine(element);\n\n            isDragging = true;\n            element.CaptureMouse();\n            offset = e.GetPosition(element);\n            e.Handled = true;\n        }	0
14333907	14234951	Insert FlowDocument into another FlowDocument at cursor position	byte[] byteArray = Encoding.Default.GetBytes(rtfString);\nMemoryStream stream = new MemoryStream(byteArray);\nthis.selectedRichTextBox.Selection.Load(stream, DataFormats.Rtf);\nstream.Close();	0
17817005	17816567	How to add List<T> containing item of type List<string> ,int,string into another List	var B = A.GroupBy(x => new { x.Name, x.EngineType })\n         .Select(g => new Car\n         {\n             Name = g.Key.Name,\n             EngineType = g.Key.EngineType,\n             Months = g.SelectMany(x => x.Months.Select((y,i) => new { i, y = int.Parse(y) }))\n                       .GroupBy(x => x.i)\n                       .OrderBy(g2 => g2.Key)\n                       .Select(g2 => g2.Sum(x => x.y).ToString()).ToList()\n         }).ToList();	0
18200605	18200552	C# - Convert a string [ Month DD, YYYY ] to DateTime	DateTime dt = DateTime.ParseExact("October 23, 1996",\n                                  "MMMM d, yyyy",\n                                  new CultureInfo("en-US"));	0
917510	863580	HowTo: Highlight the selected node in a UltraTree	pageTree.HideSelection = false;	0
23772047	23770546	How to handle and recover from exceptions within long running subscription thread	while(!ShutdownRequested) {\n    try{...}\n    catch(Exception e) {/*Log and probably do some rate-limiting in case of terminal issue*/}\n}	0
14582493	14582411	Unable to open hyperlink location in gridview	fileName = "http://yourdomain.com/files/a.pdf"	0
32262154	32092932	how to Discover the IP address of Server Socket listening to the Port XX using C# Window	foreach (IPAddress ip in allLocalNetworkAddresses.AddressList)\n        {\n            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n\n\n            //Allow sending broadcast messages\n            client.SetSocketOption(SocketOptionLevel.Socket,\n            SocketOptionName.Broadcast, 1);\n\n            //Bind on port 0. The OS will give some port between 1025 and 5000.\n          //  client.Bind(new IPEndPoint(ip, 0));\n\n            //Create endpoint, broadcast.\n            IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, Port);   \n            byte[] sendData = Encoding.ASCII.GetBytes("1");\n\n            client.SendTo(sendData, AllEndPoint);\n            Console.Write("Client send '1' to " + AllEndPoint.ToString() +\n            Environment.NewLine);	0
14765547	14765132	How can put an array in a datagridview?	List<int> arrays = new List<int>();\n\nfor (int i = 0; i < CaminoHormiga.Length; i++)\n{\n   arrays.Add(CaminoHormiga);\n}\n\nhg.dgHorarioGen.DataSource = arrays;	0
25172152	25163769	Custom GET action in ASP.NET WebAPI 2 OData Controller	[HttpPost]\npublic int DoSth()\n{\n    return 22;\n}	0
26732149	26732121	Filling an array of int at declaration	int[] rows = Enumerable.Repeat(element:1, count: X).ToArray();// named parameter -  X\n                                                              // doesn't tell anything	0
4907399	4907134	Map an unbounded range of values to 10 colors?	private int MapValue(int value, int n)\n{\n    int output = (int)Math.Round((10.0 / (n - 1) * (value - 1)) - 0.5, 0);\n    if (output == -1) return 0;\n    else return output;\n}	0
11969357	11969079	Reordering columns in silverlight datagrid	dgMyGrid.FrozenColumnCount = 2	0
33825529	33824785	Can I get more than 1000 records from a PrincipalSearcher?	// set the PageSize on the underlying DirectorySearcher to get all entries\n((DirectorySearcher)search.GetUnderlyingSearcher()).PageSize = 1000;	0
22717340	22708630	Outlook interop copy appointment items from PST file to other calendar	RDOSession Session = new RDOSession();\n  Session.MAPIOBJECT = Application.Session.MAPIOBJECT;\n  RDOMail rItem = (RDOMail)Session.GetRDOObjectFromOutlookObject(item);\n  RDOFolder rDestination = (RDOFolder)Session.GetRDOObjectFromOutlookObject(destination);\n  rItem.CopyTo(rDestination);	0
6500060	6499986	Localize WP7 application	public static void SetLanguage() {\n    CultureInfo c = null;\n    switch (ViewModel.UserSettings.Language) {\n    case Language.Default:\n        break;\n    case Language.English:\n        c = new CultureInfo("en-US");\n        break;\n    case Language.Chinese:\n        c = new CultureInfo("zh-CN");\n        break;\n    case Language.French:\n        c = new CultureInfo("fr-FR");\n        break;\n    case Language.German:\n        c = new CultureInfo("de-DE");\n        break;\n    }\n\n    if (c != null) {\n        Thread.CurrentThread.CurrentUICulture = c;\n        ApplicationStrings.Culture = c;\n    }\n}	0
4267154	4267144	What's the difference between encapsulating a private member as a property and defining a property without a private member?	[CompilerGenerated]	0
3686434	3686413	C# Linq XML pull out nodes from document	XName wanted = "Wanted";\nXName mostWanted = "MostWanted";\nvar nodes = doc.Descendants()\n               .Where(x => x.Name == wanted || x.Name == mostWanted);	0
9624146	9623903	How can I get the full size of a Tree View in Windows Forms?	TreeNode tn = tv.Nodes[tv.Nodes.Count - 1];\nwhile(tn.IsExpanded)\n    tn = tn.Nodes[tn.Nodes.Count - 1];\nreturn tn.Bounds.Bottom;	0
15553534	15552611	Remove last character in a list	String delimitedList = String.Join(",", yourList);	0
6484402	6482724	Display tabularized data easily?	Html.DisplayForModel("TableTemplateName")	0
28731146	28723699	Selective coloring of the text in TextBox (Windows Store App)	ITextDocument doc = rtb.Document;\nITextRange range = doc.GetRange(2,3);\nrange.CharacterFormat.ForegroundColor = Windows.UI.Colors.Red;\nrtb.Document.ApplyDisplayUpdates();	0
967014	966733	Deserializing XML to Objects defined in multiple schemas	using(XmlReader reader = new XmlNodeReader(element)) {\n    //... use reader\n}	0
22198549	17313578	Display Some Nodes with their weights	Node B  length connection 0     total lenght 0\nNode D  length connection 6     total lenght 6\nNode F  length connection 4     total lenght 10\nNode C  length connection 8     total lenght 18	0
18705066	18411574	Datagridview checkbox column has a dead area	private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if ((e.ColumnIndex == 1) && e.RowIndex != -1)\n        {\n            this.MyGrid[1, e.RowIndex].Value = !(bool)this.MyGrid[1, e.RowIndex].Value;\n            this.MyGrid.EndEdit();\n        }\n    }	0
1655388	1655313	Get the static text contents of a web page	using System;\nusing System.Net;\nusing System.Text.RegularExpressions;\nclass Program\n{\n    private const string url =\n        "http://stackoverflow.com/questions/1655313/get-the-static-text-contents-of-a-web-page";\n    private const string keyword = "question";\n\n    private const string regexTemplate = ">([^<>]*?{0}[^<>]*?)<";\n    static void Main(string[] args)\n    {\n        WebClient client = new WebClient();\n        string html = client.DownloadString(url);\n        Regex regex = new Regex(string.Format(regexTemplate,keyword) , RegexOptions.IgnoreCase);\n        var matches = regex.Matches(html);\n        foreach (Match match in matches)\n            Console.WriteLine(match.Groups[1].Value);\n    }\n}	0
31855955	29159579	Pentaho Authentication Method in Silver light Application.	WebClient webClient = new System.Net.WebClient();\nUri uri = new Uri("http://serverDomain:8080/pentaho/Home");\n//Give user name and password here\nvar plainTextBytes = System.Text.Encoding.UTF8.GetBytes("username:password");\nvar encodedString = System.Convert.ToBase64String(plainTextBytes);\nwebClient.Headers["Authorization"] = "Basic " + encodedString;\nwebClient.Encoding = Encoding.UTF8;\nApp.WindowManager.ConsoleWrite(uri.ToString());\nwebClient.UploadStringAsync(uri, "POST", "");	0
9037212	9036955	How do I get the correct-cased value from a hashset<string>?	static Dictionary<string, string> testD = new Dictionary<string, string>(StringComparer.CurrentCulture);\nstatic bool InputExists(string input, out string correctedCaseString)\n{\n    correctedCaseString = input;\n    if (testD.ContainsKey(input))\n    {\n        correctedCaseString = testD[input];\n        return true;\n    }\n    return false;\n}	0
2945318	2945247	Algorithm for generating an array of non-equal costs for a transport problem optimization	seen = {}\nfor i=0:\n  for j=0:\n    if cost_matrix[i,j] in seen:\n      cost_matrix[i,j] = cost_matrix[i,j]+percentage\n    append cost_matrix[i,j] to seen\n    j++\n  i++	0
10810556	10810365	Find the newest item in a C# generic list using Linq	set.OrderByDesc(x => x.DateTime)\n   .FirstOrDefault();	0
9427393	9427316	How to redirect to other page	int rowsAffected = cmd.ExecuteNonQuery();\n        if (rowsAffected == 1)\n        {\n            //Success notification \n        }\n        else\n        {\n            //Error notification \n        }\n    }	0
22559852	22558173	How to get WPT Autocompletebox selection item reference	private string _selectedSearch;\n\n    public string SelectedSearch\n    {\n        get { return _selectedSearch; }\n        set\n        {\n            _selectedSearch = value;\n            setSearch(_searchValue);\n            RaisePropertyChanged(() => SelectedSearch);\n        }\n    }\n\nprivate void setSearch(string searchValue){ // to do }	0
20378122	20176809	Wix a pushbutton to copy a text into clipboard, use custom action, not working	public class CustomActions\n{\n    [CustomAction]\n    public static ActionResult CopyToClipboard(Session session)\n    {\n        ActionResult ar=ActionResult.Success;\n        session.Log("Begin CopyToClipboard");\n        //MessageBox.Show("Begin Copy");\n        string str="abcde";\n        MessageBox.Show(" "+str);\n        try\n        {\n            Thread th=new Thread(new ParameterizedThreadStart(ClipboardThread));\n            th.SetApartmentState(ApartmentState.STA);\n            th.Start(str);\n            th.Join();\n        }\n        catch(Exception ex)\n        {\n            MessageBox.Show(ex.Message+" \n"+ex.StackTrace);\n            ar=ActionResult.Failure;\n        }\n        //MessageBox.Show("End Copy");\n        return ar;\n    }\n\n    static void ClipboardThread(object s)\n    {\n        try\n        {\n            Clipboard.SetText(s.ToString());\n        }\n        catch(Exception ex)\n        {\n            MessageBox.Show(ex.Message+" \n"+ex.StackTrace);\n        }\n    }	0
8508013	8503869	Using checkbox inside a repeater control	if(!Page.IsPostBack)\n{\n    //Fill repeater with items here\n}	0
16064247	16062820	How to display multiple local database items in listBox?	var results = (from row in dt.AsEnumerable()\n               select new  \n               {\n                   UserID = row.Field<int>("UserPK"), \n                   FirstName = row.Field<string>("FirstName"), \n                   LastName = row.Field<string>("LastName"), \n                   FullName = row.Field<string>("FirstName") + " " + row.Field<string>("LastName") \n               }).ToList();\n\nlistBox1.DataSource = results;\nlistBox1.DisplayMember = "FullName";\nlistBox1.ValueMember = "UserID";	0
15184455	15184244	SQL query to retrieve data using two dates	string sql = @"SELECT [Order].OrderNumber,\n(Customer.Title +SPACE(2)+ Customer.CustomerName) as [Customer Name],\nCustomer.CustomerEbayname, Customer.EmailAddress, Customer.PhoneNumber,\n(Customer.Address1 + SPACE(2) + Customer.Address2 + SPACE(2)+ Customer.City\n + SPACE(2) + Customer.PostCode + SPACE(2) + Customer.Country) as Address,\n[Order].ItemPurchased, Order.PurchasedDate, Order.TotalPrice\nFROM Customer INNER JOIN [Order] ON Customer.[CustomerID] = Order.[CustomerID]\nWHERE [PurchasedDate] >= #" + date1 + "# AND [PurchasedDate] <= #" + date2 + "#";	0
32702643	32701644	How do I globally change the Font Size in C# WPF?	TextElement.FontSize is an inherit property, which means you can simply set the font size at root element, and all the children elements will use that size (as long as you don't change them manually)	0
3801953	3801887	C# - Server-side password protection	byte b[] = new byte[100];\nint k = s.Receive(b, b.Length, 0);\n\nstring packet = Encoding.ASCII.getString(b, 0, k);	0
8455911	8455875	Is it possible to check OR clear session variable in html pages?	Session["UserId"] = null;\nResponse.Redirect("Index.html",true);	0
4771231	4770452	SpicIE - How to get the real address in the address bar?	HostInstance.BrowserRef.LocationURL	0
33491015	32203930	Keep excel cell format as text with "date like" data	ws.Cell(rowCounter, colCounter).SetValue<string>(Convert.ToString(fieldValue));	0
11147008	11146977	DatePicker databinding sets default value to 1/1/0001 WPF c#	public DateTime? DueDate\n{\n    //Need to change the type of the private variable as well\n    get { return dueDate; }\n    set\n    {\n        if (DueDate != null) || !DueDate.Equals(value))\n        {\n            dueDate = value;\n            OnPropertyChanged("DueDate");\n        }\n    }\n}	0
32321199	32321042	How to improve this C# code to count holes in numbers?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    private static Dictionary<int, int> _holeMap = new Dictionary<int, int>\n    {\n        { 0, 1 },\n        { 1, 0 },\n        { 2, 0 },\n        { 3, 0 },\n        { 4, 1 },\n        { 5, 0 },\n        { 6, 1 },\n        { 7, 0 },\n        { 8, 2 },\n        { 9, 1 }                \n    };\n\n    public static void Main()\n    {\n        int numero = 12345678;\n        int check = CountHoles(numero);\n        Console.WriteLine(check);   \n    }\n\n    public static int CountHoles(int num){\n        var digits = num\n            .ToString()\n            .Select(c => int.Parse(c.ToString()));\n\n        return digits.Sum(d => _holeMap[d]);\n    }\n}	0
28578947	28577809	Getting file from Amazon AWS S3 cloud with file name without extension using C# .NET	// Create a client\nAmazonS3Client client = new AmazonS3Client();\n\n// List all objects\nListObjectsRequest listRequest = new ListObjectsRequest\n{\n    BucketName = "SampleBucket",\n};\n\nListObjectsResponse listResponse;\ndo\n{\n    // Get a list of objects\n    listResponse = client.ListObjects(listRequest);\n    foreach (S3Object obj in listResponse.S3Objects)\n    {\n        Console.WriteLine("Object - " + obj.Key);\n        Console.WriteLine(" Size - " + obj.Size);\n        Console.WriteLine(" LastModified - " + obj.LastModified);\n        Console.WriteLine(" Storage class - " + obj.StorageClass);\n    }\n\n    // Set the marker property\n    listRequest.Marker = listResponse.NextMarker;\n} while (listResponse.IsTruncated);	0
20951730	20951667	how to write to kiwi syslog server log c#	_syslogSender = new SyslogUdpSender("localhost",514);\n_syslogSender.Send(\n    new SyslogMessage(\n        DateTime.Now,\n        Facility.SecurityOrAuthorizationMessages1,\n        Severity.Informational,\n        Environment.MachineName,\n        "Application Name",\n        "Message Content"),\n    new SyslogRfc3164MessageSerializer());	0
1355727	1355704	trim all strings in an array	string email = "a@a.com, b@b.com, c@c.com";    \nstring[] emails = email.Replace(" ", "").Split(',');	0
14129540	14128847	Image Matching Algorithm in C#	private void button1_Click_1(object sender, EventArgs e)\n{\n    List<string> images = new List<string>() { "GreyA.png", "YellowA.png", "AOutline.png" };\n    AForge.Imaging.Filters.Edges filter = new AForge.Imaging.Filters.Edges();\n\n    foreach (var filename in images)\n    {\n\n        Bitmap b = new Bitmap(Image.FromFile(Path.Combine(Application.StartupPath, "images", filename)));\n        Bitmap filteredBitmap = b.Clone() as Bitmap;\n\n        PictureBox pb = new PictureBox();\n        pb.SizeMode = PictureBoxSizeMode.AutoSize;\n        pb.Image = b;\n\n        flowLayoutPanel1.Controls.Add(pb);\n\n        pb = new PictureBox();\n\n        // apply the filter\n        filter.ApplyInPlace(filteredBitmap);\n        pb.SizeMode = PictureBoxSizeMode.AutoSize;\n        pb.Image = filteredBitmap;\n        flowLayoutPanel1.Controls.Add(pb);\n\n    }\n}	0
6967105	6966473	How to set metadata options without setting a default value?	public static readonly DependencyProperty MyDependencyProperty =\n    DependencyProperty.Register("MyDependency",\n                                typeof(propertyType),\n                                typeof(ownerType),\n                                new FrameworkPropertyMetadata {\n                                    BindsTwoWayByDefault = true,\n                                    PropertyChangedCallback = OnPropertyChanged,\n                                    ... etc ...\n                                });	0
19158189	19158107	Response redirect with http anchor and parameters result in parameter lost	Response.Redirect("Tickets.aspx?IDTicket=\"" + IDTicket + "\"#point_in_page",false);	0
3560171	3559034	Project generic type into a KeyValuePair	public DropDownListActionResult(IQueryable<T> dataItems, Expression<Func<T, int>> keySelector, Expression<Func<T, string>> valueSelector, int? selectedID)\n{\n    _dataItems = dataItems;\n    _keySelector = keySelector;\n    _valueSelector = valueSelector;\n    _selectedID = selectedID;\n}\n\npublic ActionResult Result()\n{    \n    var items = _dataItems.Select(item => \n                new KeyValuePair<int, string>(_keySelector.Compile().Invoke(item), _valueSelector.Compile().Invoke(item)))\n                .ToDictionary(item => item.Key, item => item.Value);\n\n    items.Add(0, "");\n\n    var list = new SelectList(items.OrderBy(i => i.Value), "Key", "Value", _selectedID);\n\n    return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };    \n}	0
17304136	17269317	Autoscroll CheckedListBox with DragDrop reordering	private void checkedListBox1_DragEnter(object sender, DragEventArgs e) {\n    scrollTimer.Stop();\n}\n\nprivate void checkedListBox1_DragLeave(object sender, EventArgs e) {\n    scrollTimer.Start();\n}\n\nprivate void scrollTimer_Tick(object sender, EventArgs e) {\n    Point cursor = PointToClient(MousePosition);\n    if (cursor.Y < checkedListBox1.Bounds.Top)\n        checkedListBox1.TopIndex -= 1;\n    else if (cursor.Y > checkedListBox1.Bounds.Bottom)\n        checkedListBox1.TopIndex += 1;\n}	0
9073743	9072549	Convert IGrouping to IQueryable	dc.CelebrityLocations.OrderByDescending(x => x.DateTime).AsQueryable().GroupBy(x => x.Celebrity).Select(x => x.First());	0
20202299	20202138	Convert linq requests (queries) into one request without foreach	var query = objs\n    .Where(o => o.cars.Count > maxCars)\n    .SelectMany(o => _carDao.GetQueryable()\n        .Where(v => v.obj.Id == o.Id)\n        .OrderByDescending(v => v.CreatedDate)\n        .Take(o.cars.Count - maxCars));	0
12224571	12218858	Query field values from SQL Server Compact	decimal? Player1Hgt = dsPlayerTeam.PlayerList.Rows.Find(sortedPlayers[counter]).Field<decimal?>("Height");	0
32756304	32755910	Register app for a URI association (Windows Phone 8.1 RT)	protected override void OnActivated(IActivatedEventArgs args)\n{\n    if (args.Kind == ActivationKind.Protocol)\n    {\n        ProtocolActivatedEventArgs protocolArgs =\n           args as ProtocolActivatedEventArgs;\n        var rootFrame = new Frame();\n        rootFrame.Navigate(typeof(BlogItems), args);\n        Window.Current.Content = rootFrame;\n    }\n    Window.Current.Activate();\n}	0
9154131	9154109	Is there anyway to get a graphics object within console program?	Graphics.FromImage()	0
9582845	9582799	Opening PDF or Doc In a winform	Process mydoc= new Process();\n\n            mydoc.StartInfo.FileName   = "path to pdf or word file c:\a.doc";\n\n            mydoc.Start();	0
14511373	14511307	Creating a date range that has a total UTC day	new DateTime(2013, 1, 17, 0,0,0, DateTimeKind.Utc)	0
10522700	10522661	Read a SQLDataReader more than once in C#?	while (reader.Read())\n{\n    var a = reader[2];   // you can skip fields\n    var b = reader[0];   // you don't have to read the fields in order\n    var c = reader[2];   // you can re-read fields\n}	0
2633233	2633220	Find a string within another string, search backwards	int index = some_string.LastIndexOf("something", 1000);	0
34402381	34402302	how to avoid concatenation in combo box	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    combobox2.Items.Clear();\n    combobox3.Items.Clear();\n    . . .\n}\n\nprivate void comboBox2_SelectedIndexChanged(object sender, EventArgs e)\n{\n    combobox3.Items.Clear();\n    . . .\n}	0
11430280	11430028	How to move the cursor to the next word in a rich text box in C#	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        richTextBox1.Focus();\n        SendKeys.SendWait("^{LEFT}");\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        richTextBox1.Focus();\n        SendKeys.SendWait("^{RIGHT}");\n    }\n}	0
16477806	16477505	Error while loading string to xml document in windows c#	xmlSource = System.AppDomain.CurrentDomain.BaseDirectory + "\\Dictionary.xml";	0
25752379	25748338	App closes after phoneCallTask is shown Windows phone 8	phone.Show()	0
25462895	25451408	How to print each object in a collection in a separate page in Silverlight	private List<Label> printLabels;    \nprivate PrintDocument pd;\n\nprivate void PrintButton_Click(object sender, RoutedEventArgs e)\n{\n   // save the labels to a temporary list\n   printLabels = new List<Label>(labels);\n\n   // start the printing\n   pd.Print("Test Print");\n}\n\nprivate void pd_PrintPage(object sender, PrintPageEventArgs e)\n{\n    // print the first element from the temporary list\n    Label labelToPrint = printLabels.First();\n\n    var printpage = new LabelPrint();\n    printpage.DataContext = new LabelPrintViewModel(labelToPrint);\n    e.PageVisual = printpage;\n\n    printLabels.Remove(labelToPrint);\n\n    // continue printing if there's still any labels left\n    e.HasMorePages = printLabels.Any();\n}	0
3919280	3919211	linq datetimeoffset comparison with today	// greater than now, still today            \ncollection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.Date == DateTime.Today);\n\n// expires in the next 24 hours\ncollection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.DateTime < DateTime.Now.AddHours(24));	0
3825225	3825200	How to apply a function to every element in a list using Linq in C# like the method reduce() in python?	var list = Enumerable.Range(5, 3); // [5, 6, 7]\nConsole.WriteLine("Aggregation: {0}", list.Aggregate((a, b) => (a + b)));\n// Result is "Aggregation: 18"	0
29867466	29866989	How to access OrderBy clause from MethodCallExpression	public class QueryContext<T>\n    {\n        void Execute(MethodCallExpression dsQueryExpression)\n        {\n            var orderByFinder = new OrderByFinder();\n            var orderByExpression = orderByFinder.GetOrderBy(dsQueryExpression);\n            // .. Continue on processing the OrderBy expression\n        }\n    }\n\n    internal class OrderByFinder : ExpressionVisitor\n    {\n        MethodCallExpression _orderByExpression;\n\n        public MethodCallExpression GetOrderBy(Expression expression)\n        {\n            Visit(expression);\n            return _orderByExpression;\n        }\n\n        protected override Expression VisitMethodCall(MethodCallExpression expression)\n        {\n            if (expression.Method.Name == "OrderBy") _orderByExpression = expression;\n\n            Visit(expression.Arguments[0]);\n\n            return expression;\n        }\n    }	0
33719179	33699295	Croatian letters in iTextSharp	BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false);\nFont titleFont = new Font(bf,20);\nFont infoFont = new Font(bf,16);	0
14473148	14473101	Finding already existing value in Key Value pair	int newValue = 10;\nDictionary<string, int> dictionary = new Dictionary<string, int>();\nif (dictionary.ContainsKey("key"))\n    dictionary["key"] = dictionary["key"] + newValue;	0
17856769	17856585	Regular expression to match a string that contains only numbers, not letters	Regex numberExpression = new Regex(@"^\d+$");	0
30053976	30053843	getting information from sphereCast's hit	void Update() {\n    RaycastHit[] hits;\n    hits = Physics.RaycastAll(transform.position, transform.forward, 100.0F);\n    int i = 0;\n    while (i < hits.Length) {\n        RaycastHit hit = hits[i];\n        Renderer rend = hit.transform.GetComponent<Renderer>();\n        if (rend) {\n            rend.material.shader = Shader.Find("Transparent/Diffuse");\n            rend.material.color.a = 0.3F;\n        }\n        i++;\n    }\n}	0
750316	748583	Changing EditRowStyle programmatically when Edit is clicked	grdView.SelectedIndex = e.NewEditIndex;	0
4618717	4618611	Export interfaces	internal interface IFoo\n{\n     void Stuff();\n}\n\npublic interface ISomething\n{\n     IFoo GetFoo();\n}	0
6054777	6054756	How to catch specific exceptions when sending mail?	catch (SmtpFailedRecipientException se)\n{\n  using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))\n  {\n    errorfile.WriteLine(se.StackTrace);  \n    // variable se is already the right type, so no need to cast it      \n    errorfile.WriteLine(se.FailedRecipient);       \n    errorfile.WriteLine(se.ToString());\n  }\n}\ncatch (Exception e)\n{\n  wl("Meldingen kunne ikke sendes til en eller flere mottakere.", ConsoleColor.Red);\n  wl(e.Message, ConsoleColor.DarkRed);   \n\n  // for other error types just write the info without the FailedRecipient\n  using (var errorfile = System.IO.File.CreateText("error-" + DateTime.Now.Ticks + ".txt"))\n  {\n    errorfile.WriteLine(e.StackTrace);        \n    errorfile.WriteLine(e.ToString());\n  }\n\n}	0
19600870	19600813	Read user input from console from arrays	namespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            var lottery_numbers = new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };\n            //Asking for user input\n            Console.WriteLine("How many number's you want to display?? ");\n\n            // getting input from user\n            int number = Convert.ToInt32(Console.ReadLine());\n\n            // loop through the number user gave as input\n            for (var i = 0; i < number; i++)\n            {\n                Console.WriteLine("{0}", lottery_numbers[i]);\n            }\n            Console.Read();\n        }\n    }\n}	0
7416600	3047210	EmguCV - MatchTemplate	if (matchScore > 0.75)\n{\n    Rectangle rect = new Rectangle(new Point(x - templateImage.Width ,y - templateImage-Height), new Size(1, 1));\n    imgSource.Draw(rect, new Bgr(Color.Blue), 1);\n}	0
7681766	7681724	String manipulation to truncate string up to a specified expression on C#	var firstColumn = origString.SubString(0, origString.IndexOf("   "));	0
12479539	12479078	Is there a sample using Nelder-Mead solver in Microsoft Solver Foundation?	var solver = new NelderMeadSolver();\n...\nvar param = new NelderMeadSolverParams();	0
27815826	27815288	Setting property value on child instance to a fixed value with Autofixture	[Fact]\npublic void SimplestThingThatCouldPossiblyWork()\n{\n    var fixture = new Fixture();\n    var expectedCity = "foo";\n    var person = fixture.Create<Person>();\n    person.Address.City = expectedCity;\n    Assert.Equal(expectedCity, person.Address.City);\n}	0
7828941	7828721	in Vb6 and c# how do I have multiple of a string	//Repeat "asd" 100 times\nString.Join("", Enumerable.Repeat("asd", 100).ToArray())	0
15371237	15370927	Regex: Match all characters between { and } if a specific string is between them	/\{[^}]*ID1[^}]*\}/	0
11118523	11116290	Event for clicking on row headers in DataGridView	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        var list = new List<Books>\n                       {\n                           new Books() {Title = "Harry Potter", TotalRating = 5},\n                           new Books() {Title = "C#", TotalRating = 5}\n                       };\n        InitializeComponent();\n        dataGridView1.AutoGenerateColumns = true;\n        dataGridView1.DataSource = list;\n        dataGridView1.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(OnRowHeaderMouseClick);\n    }\n\n    void OnRowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        MessageBox.Show("Clicked RowHeader!");\n    }\n}	0
8929814	8929261	How do I tell Entity Framework Function Import that a column returned by a stored procedure is not nullable?	isnull([dbo].[GetBar](T.Col2), 0)	0
16605736	16604846	Get Localize strings dynamically WP8 c#	AppResources.ResourceManager.GetString("ERR_VERSION_NOT_SUPPORTED", \n      AppResources.Culture);	0
23877160	23877125	How is encryption done without encoding the string to byte[]?	swEncrypt.Write(plaintext)	0
23541044	22068111	How to store style information lastingly in a FlowDocument paragraph?	// Storing a FlowDocument\nusing (FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write))\n{\n    XamlWriter.Save(_flowDoc, fs);\n}\n\n// Loading a FlowDocument into a RichTextBox\nusing (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read))\n{\n    _flowDoc = (FlowDocument)XamlReader.Load(fs);\n    _rtb.Document = _flowDoc;\n}	0
23438553	23438236	Iterate through parameters in DbCommand	StringBuilder sb = new StringBuilder();\n\ncommand.Parameters.Cast<DbParameter>()\n                  .ToList()\n                  .ForEach(p => sb.Append(\n                                   string.Format("{0} = {1}{2}",\n                                      p.ParameterName,\n                                      p.Value,\n                                      Environment.NewLine)));\n\nConsole.WriteLine(sb.ToString());	0
11727554	11727497	Strange casting in VB in Math.Pow	long bc = (long)Math.Pow(36, ((IBase36.Length - 1) -i));	0
8207060	8207017	How to rewrite this statement in another way?	var requestToken = new OAuthRequestToken();\nrequestToken.Token = OauthToken;	0
20107861	20106260	How to Sort DataGridView?	//First we need to get all the non-empty cell values in some List<string>\nvar cells = dataGridView1.Rows.Cast<DataGridViewRow>()\n              .Where(row=>!row.IsNewRow)\n              .SelectMany(row=>dataGridView1.Columns.Cast<DataGridViewColumn>()\n                               .Select(col=>row.Cells[col]))\n              .OrderBy(cell=>cell.ColumnIndex)\n              .ThenBy(cell=>cell.RowIndex)\n              .Where(cell=>Convert.ToString(cell.Value)!="").ToList();\n//update the cells to make the grid look like sorted\nfor(int i = 0; i < dataGridView1.ColumnCount; i++){\n  for(int j = 0; j < 8; j++){\n    if(dataGridView1.Rows[j].IsNewRow) continue;\n    int k = i*8+j;\n    dataGridView1[i,j].Value = k < cells.Count ? cells[k] : null;\n  }\n}	0
2532939	2532929	Validate cyclic organization unit	void CheckCycles(IOrganizationUnit unit)\n{\n    var visited = new HashSet<IOrganizationUnit>();\n\n    for (var current = unit; current != null; current = current.ManagedBy)\n    {\n        if (!visited.Add(current))\n        {\n            throw new Exception(); // cycle detected\n        }\n    }\n}	0
15388106	15387923	Remove multiple items from Dictionary at once	toRemove = machine.Array\n              .Select(x => \n                  new KeyValuePair<int, string>((int)x.MachineID, x.PackageID))\n              .ToList();\n\n// create a hash set and initially put all the elements from toRemove in the set\nvar r = new HashSet<KeyValuePair<int, string>>(toRemove);\n\n// go over each element in the clickedList\n//    and check whether it actually needs to be removed\nforeach(var kvp in clickedList.Keys)      // O(n);  n = # of keys/elem. in dictionary\n{\n    if(kvp.Value == OperationType.Remove)\n    {\n       if(r.Contains(kvp.Key)             // O(1)\n          r.Remove(kvp.Key);              //    (1)\n       else\n          r.Add(kvp.Key);                 //   O(1)\n    }\n}\n\nforeach(var key in r)                     // O(m); m = # of keys to be removed \n{\n    clickedList.Remove(key);\n}	0
34235986	34235640	How can i take a photo using canon camera lib and show the taken image photo in the pictureBox? Getting errors	private void Browse_Click(object sender, EventArgs e)\n    {\n        OpenFileDialog OFD = new OpenFileDialog();\n        if (OFD.ShowDialog() == DialogResult.OK)\n        {\n            Bitmap Image = new Bitmap(OFD.FileName);\n            NewUserPictureBox.Image = Image;\n            NewUserPictureBox.SizeMode = PictureBoxSizeMode.Zoom;\n        }\n    }	0
13315764	13315730	How to get incoming InputStream, in controller in ASP.NET MVC	this.Request.InputStream	0
2460416	2460389	ComboBox / ListBox selected item	string result = (string)comboBox1.SelectedItem	0
11116333	11116151	How to show/hide things in the View using role permissions?	public class MyViewModel\n{\n   public bool ShowMycontrol1 { get; set; }\n}	0
10433027	10433007	How do you call a generic method if you only know the type parameter at runtime?	var method = typeof(SomeClass).GetMethod("SomeMethod");\nmethod.MakeGenericMethod(someType).Invoke(...);	0
29437616	29437217	Linq to Entities Getting list of entities by list of variables	public List<User> GetAllUsersByRoleForDashboard(String role)\n{\n    var userNamesFromDB = new HashSet<string>(Roles.GetUsersInRole(role));\n\n    var users = context.aspnet_Users.Where(u => userNamesFromDB.Contains(u.UserName))\n    .Select(u=> new User\n    {\n        // Do your mapping\n    }).ToList();\n\n    return users;\n}	0
1027448	1027360	DataGridView capturing user row selection	private void dgridv_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)\n        {\n            // For any other operation except, StateChanged, do nothing\n            if (e.StateChanged != DataGridViewElementStates.Selected) return;\n\n            // Calculate amount code goes here\n        }	0
8902067	8497230	WCF Rest Service - Gaining Access to HTTP Reponse header	var response = WebOperationContext.Current.OutgoingResponse;\nresponse.Headers.Add("Content-Encoding", "gzip");	0
25111482	25030215	How do load FEEDS youtube apis v3 on windows store c#	private void GetYoutubeChannel(string feedXML)\n    {\n        try\n        {\n            SyndicationFeed feed = new SyndicationFeed();\n            feed.Load(feedXML);\n\n            List<YoutubeVideo> videosList = new List<YoutubeVideo>();\n            YoutubeVideo video;\n\n            foreach (SyndicationItem item in feed.Items)\n            {\n                video = new YoutubeVideo();\n\n                video.YoutubeLink = item.Links[0].Uri;\n                string a = video.YoutubeLink.ToString().Remove(0, 31);\n                video.Id = a.Substring(0, 11);\n                video.Title = item.Title.Text;\n                video.PubDate = item.PublishedDate.DateTime;\n\n                video.Thumbnail = YouTube.GetThumbnailUri(video.Id, YouTubeThumbnailSize.Large);\n\n                videosList.Add(video);\n            }\n\n            MainListBox.ItemsSource = videosList;\n        }\n        catch { }\n    }	0
30833288	30829746	Get 'PL\SQL Table' returned from a function with OracleCommand in C#	using (OracleCommand cmd = new OracleCommand())\n{\n    cmd.Connection = conn;\n    cmd.CommandText = "select * from table(return_table())";\n    cmd.CommandType = CommandType.Text;\n    conn.Open();\n    OracleDataReader rdr = cmd.ExecuteReader();\n    while (rdr.Read())\n    {\n        Console.WriteLine(rdr.GetOracleDecimal(0));\n        Console.WriteLine(rdr.GetOracleString(1));\n    }\n    conn.Close();\n}	0
23418455	23418048	Fixing EF code generated from database	// Primary Key\n<#\n    if (efHost.EntityType.KeyMembers.Count() == 1)\n    {\n#>\n            this.HasKey(t => t.<#= efHost.EntityType.KeyMembers.Single().Name #>)\n            .Property(t => t.<#= efHost.EntityType.KeyMembers.Single().Name #>).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);	0
11160046	11159767	How to convert Listview to DataTable	var listView1 = new ListView();\nDataTable table = new DataTable();\nforeach (ListViewItem item in listView1.Items)\n{\n    table.Columns.Add(item.ToString());\n    foreach (var it in item.SubItems)\n         table.Rows.Add(it.ToString());\n }	0
1704330	1704268	Getting a Method's Return Value in the VS Debugger	? Foo(valueIn)	0
16690771	16690717	returning a null value from database as a string value	string tc = dbread["CustomerAcceptedTerms"] != DBNull.Value ? "Yes" : "Null";	0
436898	436778	Send broadcast message from all network adapters	foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())\n    foreach (var ua in i.GetIPProperties().UnicastAddresses)\n        Console.WriteLine(ua.Address);	0
33884774	33884738	C# How to display all instances of a loop in a label?	bool isPrime = true;\nStringBuilder sb = new StringBuilder();\n\n    for (num1 = count1; num1 <= num2; num1++)\n    {\n        for (int j = 2; j <= 150; j++)\n        {\n            if (num1 != j && num1 % j == 0)\n            {\n                isPrime = false;\n                break;\n            }\n        }\n\n        if (isPrime)\n        {\n            sb.Append("" + num1 + "" + num1);\n        }\n        isPrime = true;\n    }\nlblResult.Text = sb.ToString();	0
2999697	2999338	Marshal structure pointer in VS2010	[DllImport("sampleModule.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n    public static extern int sampleFunc(ref SInfo info, string txt);	0
1345700	1345676	How to get the server IP Address?	Request.ServerVariables["LOCAL_ADDR"];	0
10960994	10946706	Remove Filepath in GridFS	var gfs = new MongoGridFS\ngfs.Upload(@"c:\a.pdf", "a.pdf");\ngfs.Download(@"c:\b.pdf", "a.pdf");	0
29675836	29668621	How to sign value to a field in BizForm in Kentico 8.2	bfCallBack.Data.SetValue("StartDate", startTime)	0
6903536	6903477	Need a string JSON Validator	JObject.Parse	0
21469215	21253251	OpenCV C++ Vector DMatch to C#	vector<Point2f> matched_points1, matched_points2; // these are your points that match\n\nfor (int i=0;i<matches.size();i++)\n{\n    // this is how the DMatch structure stores the matching information\n    int idx1=matches[i].trainIdx; \n    int idx2=matches[i].queryIdx;\n\n    //now use those match indices to get the keypoints, add to your two lists of points\n    matched_points1.push_back(keypoints_1[idx1].pt);\n    matched_points2.push_back(keypoints_2[idx2].pt);\n}	0
3175730	3165574	How do I create an activeX component for a desktop application in C#	[assembly: ComVisible(true)]	0
3598430	3598406	How to update some part of the complex dictionary value in C#	if (DataDic.TryGetValue(trid, out tdi)\n{\n   // already exists in dict, tdi will be initialized with ref to object from dict\n   tdi.TOTSMP = 0;   // update tdi\n}\nelse\n{\n  ....\n}	0
6812185	6807285	DataTable to the set of SQL queries	public static IEnumerable<string> GetInsertQueryFromDataTable(DataTable dataTable)\n    {\n        foreach (DataRow row in dataTable.AsEnumerable())\n        {\n            var s = new StringBuilder(string.Format("INSERT INTO {0} SET ", dataTable.TableName));\n\n            foreach (DataColumn v in dataTable.Columns)\n            {\n                var r = new StringBuilder(row[v.ColumnName].ToString());\n                r.Replace(@"\", @"\\");\n                r.Replace("\"", "\\\"");\n                s.AppendFormat("{0}=\"{1}\", ", v.ColumnName, r);\n            }\n\n            s.Remove(s.Length - 2, 1);\n            s.AppendLine(";");\n            yield return s.ToString();\n        }\n    }	0
5807120	5806675	How To: Dynamically Creating the XML file content and sending as a text file in asp.net c#	System.IO.MemoryStream objStream = new System.IO.MemoryStream();\n    System.Data.DataSet ds = new System.Data.DataSet();\n    ds.Tables.Add("TEST");\n    ds.WriteXml(objStream);\n\n    Response.Clear();\n    Response.Buffer = true;\n    Response.ContentType = "text/xml";\n    Response.AddHeader("Content-Disposition", "attachment; filename=File.xml");\n    Response.BinaryWrite(objStream.ToArray());\n    Response.End();	0
34058958	34058774	Need one block on Regex to be optional	\^CV_((\w+)-){1,2}Base	0
3985429	3985375	Event in User Control	protected void Page_Load(object sender, EventArgs e)\n{\n    if (Request.From[Button1.UniqueID] != null)\n    {\n       // button1 click, handle it\n       ...\n    }\n}	0
7996640	7996616	C# constructor shortcut needed	var r = new PersonViewModel {\n    PageMeta = {\n        DataSource = "abc",\n        TopicID = "def"\n    }\n}	0
5391974	5389899	How to bind an image to a Button in code behind?	Sub Image_MouseEnter() Handles YourImage.MouseEnter\n    YourButton.CaptureMouse()\nEnd Sub\n\nSub Image_MouseLeave() Handles YourImage.MouseLeave\n    YourButton.ReleaseMouseCapture()\nEnd Sub	0
6369556	6369347	Checking one column with same data for reading csv file in C#.net	DataTable dt = new DataTable();\n    .....\n    ....\n   if(dt.Rows.Count > 0)\n     if(dt.Select("ColorCode <> " + dt.Rows[0]["ColorCode"].ToString()).Length > 0)\n       throw new Exception("Two or more different ColorCodes exists");	0
24168057	24167399	How to postpone object deserialization, and just receive the JSON as a single large string object	public ActionResult Catch()\n{\n    var reader = new StreamReader(Request.InputStream);\n    var rawString = reader.ReadToEnd();\n\n    //do something here.\n}	0
32108158	32089243	Setting initial value of PasswordBox	//Storing the Password in String.\nstring pwd = "Password Read from the file";\nPasswordBox.Password = pwd;	0
16430557	16430480	How to get the two last part of string separated by ,	string str1 = "blah, blah, May 08, 2012";\nstring str2 = "blah blah blah, June 19, 2011";\n\nint splitter = str1.Substring(0, str1.LastIndexOf(',')).LastIndexOf(',');\n\nstring newStr1 = str1.Substring(0, splitter);\nstring newStr2 = str1.Substring(splitter + 2, str1.Length - (splitter + 2));\n\nConsole.WriteLine(newStr1);\nConsole.WriteLine(newStr2);\n\nConsole.ReadKey();	0
33823027	33821706	Teechart linechart ,if add string , bottom axis label will change ,C#	tChart1.Axes.Bottom.Labels.Style = Steema.TeeChart.AxisLabelStyle.Value;	0
30376990	30376813	How to get current currency code of current location in Windows Phone 8.1	...\n"US": "USD",\n"UY": "UYU",\n"UZ": "UZS",\n"VA": "EUR",\n"VC": "XCD",\n...	0
848475	848472	How add "or" in switch statements?	switch(myvar)\n{\n    case 2:\n    case 5:\n    ...\n    break;\n\n    case 7:\n    case 12:\n    ...\n    break;\n    ...\n}	0
10984279	10984219	Get handles of ContextMenuStrip submenus	ToolStripMenuItem.DropDown.Handle	0
20639982	20639776	How to assigning a Expression of <T> in a Expression of object?	Expression<Func<TModelMap, TNodeModelMap>> source = ...\n\nvar convertedBody = Expression.Convert(source.Body, typeof(object));    \n\nvar convertedExpression = Expression.Lambda<Func<TModelMap, object>>\n                          (convertedBody, source.Parameters);\n\nRemovedProperties.Add(convertedExpression);	0
28725812	27390507	WPF Arrange Panel Children	private void SetTopImage()\n    {\n        Image NewTopImage = FindIconPriority(); // Finds what Icon I would like to have in front.\n\n        ControlStack.Children.Remove(NewTopImage);\n        ControlStack.Children.Insert(0, NewTopImage);\n    }	0
16142813	16142029	How I can read a cell in excel with C#?	Range range = ( Range ) ws. get_Range ( "E1" , "E1" ) ;	0
2833429	2832327	HTML Text writer	writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Concat(Path 1));\nwriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");\nwriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");\nwriter.RenderBeginTag(HtmlTextWriterTag.Link);\n\nwriter.RenderEndTag();\n\nwriter.AddAttribute(HtmlTextWriterAttribute.Href, string.Concat(Path 2 ));\nwriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");\nwriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");\nwriter.RenderBeginTag(HtmlTextWriterTag.Link);\n\nwriter.RenderEndTag();	0
15960884	15960640	"String or binary data would be truncated" in update statement	glat += result.geometry.location.lat;\nglong += result.geometry.location.lng;\ngPostal += postalCode;	0
31269448	31269336	Getting an object variable from List in C#	listOfItems[0].name;	0
22788628	22787570	how to change another form name in button click event	Form form = Application.OpenForms["frmmaster"];\nform.Text="lol";	0
6512962	6512873	How do I convert multiple WCF RIA Entity types to a single type for use in a ViewModel	ObservableCollection<MyEntity> entities = ...\nObservableCollection<MyEntityInterface> iEntities = new ObservableCollection(entities.Cast<MyEntityInterface>());	0
6847407	6847346	Why is there no DateTime.AddWeeks(), and how can I get a DateTime object for 52 weeks ago?	public static class DateTimeExtensions\n{\n    public static DateTime AddWeeks(this DateTime dateTime, int numberOfWeeks)\n    {\n        return dateTime.AddDays(numberOfWeeks * 7);\n    }\n}	0
3810624	3810603	generating string from exited characters	StringBuilder sb = new StringBuilder();\nRandom random = new Randdom();\nfor(int i=0; i<7; i++) {\n    sb.append(pwdCharArray[random.nextInt(0, pwdCharArray.length -1)]);\n}\nreturn sb.toString();	0
8298032	8297479	How to create Bitmap from file on server - parameter is not valid	WebClient MyWebClient = new WebClient();\n    byte[] BytesImage = MyWebClient.DownloadData("http://www.google.com/intl/en_com/images/srpr/logo3w.png");\n    System.IO.MemoryStream iStream= new System.IO.MemoryStream(BytesImage);\n    System.Drawing.Bitmap b = new System.Drawing.Bitmap(iStream);	0
21553816	21542642	How do we implement permissions in ASP.NET identity?	[SimpleAuthorize(Resource = "UserProfile", Operation = "modify")]\npublic ActionResult ModifyUserProfile()\n{\n    ViewBag.Message = "Modify Your Profile";\n    return View();\n}	0
4554457	4554427	How to get names from expression property?	string propertyName = ((MemberExpression) myParam.Body).Member.Name;	0
29244371	29244139	Pro's & cons to pass data in a project in asp.net MVC	public BaseController: Controller\n {\n       protected string username ;\n\n       protected override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n           // Do authorization here\n          username = // code to get username \n   {\n }	0
8331592	8331462	Using Split and storing in a data table	string Input = "12/nTwelve,13/nThirteen,";\nstring[] InputSplit = Regex.Split(Input, @"(?:/n|\,)");\nfor(int i = 0 ; i < ((InputSplit.Length / 2) * 2) ; i+=2){ \n    //Math in the middle helps when there's a trailing comma in the data set\n    Console.WriteLine(string.Format("{0}\t{1}", InputSplit[i], InputSplit[i+1]));\n}	0
1508167	1508070	With WPF, how to retrieve the controls contained by a DataTemplate?	// Finding textBlock from the DataTemplate that is set on that ContentPresenter\nDataTemplate myDataTemplate = myContentPresenter.ContentTemplate;\nTextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);	0
130805	130748	Best way to swap two .NET controls based on radio buttons	private void OnRadioButtonCheckedChanged(object sender, EventArgs e)\n{\n    Control1.Visible = RadioButton1.Checked;\n    Control2.Visible = RadioButton2.Checked;\n}	0
32621798	32621602	Code in user control breaks design mode in Visual Studio 2015	public static bool IsDesignMode(this object o)\n    {\n        return (bool) DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof (FrameworkElement)).Metadata.DefaultValue;\n    }\n\n    if (!this.IsDesignMode())\n    {\n        Task.Factory.StartNew(GoBack, ... \n        ...\n    }	0
188407	188299	Marshal C++ struct array into C#	[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]\npublic struct LPRData\n{\n/// char[15]\n[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]\npublic string data;\n\n/// int[15]\n[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]\npublic int[] prob;\n}	0
2724614	2724546	How to get Assembly Version (not File Version) for another EXE?	AssemblyName.GetAssemblyName("filename.exe").Version	0
32430150	32429967	How do I split a string on an empty line using .Split()?	String[] people = record.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);	0
30434450	30434426	How to remove duplicates from a list of custom objects, by a property of the object	var distinctItems = myList.GroupBy(x => x.prop1).Select(y => y.First());	0
15375689	15375453	How to remove white background color from Bitmap	Bitmap capcha = new Bitmap(@"C:/image.jpg");\ncapcha.MakeTransparent(Color.White);\npictureBox1.Image = capcha;	0
12097661	12097524	C# creating a string which will be parsed, based on user input fails when they enter a tokenizing character	// -- regex for | not preceded by a \\n        string input = @"1|2|3|This is a string\|type:1";\n        string pattern = @"(?<!\\)[|]";\n        string[] substrings = Regex.Split(input, pattern);\n\n        foreach (string match in substrings)\n        {\n            Console.WriteLine("'{0}'", match);\n        }	0
27721276	27721004	How to make a server reply after receiving a request/data	Socket socket = new Socket(AddressFamily.InterNetwork, ...);\n\n// open and send ID\n\nint dataAvailable = 0;\nwhile (dataAvailable == 0 || dataAvailable != socket.Available)\n{\n    dataAvailable = socket.Available;\n    Thread.Sleep(100); // if no new data after 100ms assume transmission finished\n}\n\nvar data = new byte[dataAvailable];\nsocket.Receive(data);\n\nsocket.Shutdown(SocketShutdown.Both);\nsocket.Close();	0
22749122	22748931	Write a part of the class as XML	[XmlIgnoreAttribute()] \n    public Bitmap Picture { get { return picture; } set { picture = value; } } \n\n    [XmlElementAttribute("Picture")] \n    public byte[] PictureByteArray { \n        get { \n            if (picture != null) { \n                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())\n    ?????       {\n????                 picture.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);\n?????????            return ms.ToArray();\n?????           }\n            } else return null; \n        } \n        set { \n            if (value != null) \n            {\n                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(value))\n?????                           {\n??????????                         picture = new Bitmap(Image.FromStream(ms));\n?????                           } \n            }\n            else picture = null; \n        } \n    }	0
16394643	16394608	Select rows by criteria to fill a list	model = model.Where(r => Users.Contains(r.Username));	0
30967548	30967286	MSIL store a value of structure to return	...\nmIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array\nmIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0\nmIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array\n\nmIL.Emit(OpCodes.Unbox_Any, returnType);\nmIL.Emit(OpCodes.Ret);	0
15565690	15547020	C# Explicit implementation of interface breaks my INotifyPropertyChanged	var example = new Example();\n((INotifyPropertyChanged)example).PropertyChanged += OnAChanged;\n((IExample)example).A = "new string";	0
29798480	29778616	PowerPoint Add-in Write on Slide in Slideshow	private Timer _Ticker = new Timer();\nprivate PowerPoint.SlideShowWindow _SlideshowWindow = null;\n\nprivate void Application_SlideShowBegin(PowerPoint.SlideShowWindow Wn)\n{\n    _SlideshowWindow = Wn;\n    _Ticker.Interval = 30;\n    _Ticker.AutoReset = true;\n    _Ticker.Elapsed += Ticker_Elapsed;\n    _Ticker.Enabled = true;\n}\n\n    private void Ticker_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        if (_Ticker.Enabled)\n        {\n            using (var g = Graphics.FromHwnd((IntPtr)_SlideshowWindow.HWND))\n            {\n                g.DrawLine(new Pen(Color.Red, 10), new System.Drawing.Point(100, 100), new System.Drawing.Point(200, 300));\n                Image img = Properties.Resources.img;\n                g.DrawImageUnscaled(img, new Rectangle(250, 250, img.Width, img.Height));\n            }\n            _Ticker.Enabled = false;\n            _Ticker.Elapsed -= Ticker_Elapsed;\n        }\n    }	0
1705502	1705340	How do I go about getting a page to restart processing in C#?	Response.Clear ();\nServer.Transfer (Request.Url.PathAndQuery, true);	0
22881832	22879262	Convert an IBuffer to a byte array in Windows Phone 8.1, how?	using System.Runtime.InteropServices.WindowsRuntime	0
5419359	5419340	How to convert DataTime Value in specific Culture with c#?	date.ToString(new CultureInfo("de-DE"))	0
32152579	32152542	How to write connection string when ms access database is password protected?	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.mdb;\n      Jet OLEDB:Database Password=MyDbPassword;	0
12119930	12119696	How do I get TextBox in a GridView row when Edit button is clicked if the headers are not databound?	protected void grd_RowEditing(object sender, GridViewEditEventArgs e) \n{\n     GridViewRow selectRow = grd.Rows(e.NewEditIndex);\n     TextBox txtKj=(TextBox)selectRow.Cells[3].FindControl("txtKjId"); \n}	0
7593953	7593932	How an interface can replace a class?	public interface IMyInterface{\n IList<string> SomeList { get; }\n}\n\npublic class MyClass : IMyInterface {\n  public IList<string> SomeList {\n    get { \n      return new List<string>(){ "a", "b" , "c" }; \n    }\n  }\n}	0
10057548	10057499	Overriding method from library	namespace TheDll\n{\n    public class SomeClass\n    {\n        public virtual void TheMethod()\n        { }\n    }\n}\n\nnamespace TheProject\n{\n    public class DerivedClass : SomeClass\n    {\n        public override void TheMethod()\n        { }\n    }\n}	0
4203649	4203591	Why there is a convention of declaring default namespace/libraries in any programming language?	stdio.h	0
704389	704380	.Net: Retrieving data from threads	public static void ResultCallback(int lineCount) {\n  // runs on worker thread\n  Invoke((MethodInvoker)delegate {\n      // runs on UI thread\n      Console.WriteLine(Thread.CurrentThread.Name +\n         ":Independent task printed {0} lines.", lineCount);\n  });\n}	0
22230553	22211432	How to get result in IResultFilter in MVC 4?	void IResultFilter.OnResultExecuting (ResultExecutingContext filterContext)        \n{\n      // code\n      var jsonResult = (JsonResult)filterContext.Result;\n      var model = (ProjectName.Models.ModelName)jsonResult.Data;\n      var propertyValue = model.PropertyName;\n      // code\n}	0
24863734	24863328	How to shutdown outlook programatically Outlook in a 2010 AddIn Project?	public partial class ThisAddIn\n    {\n        private void ThisAddIn_Startup(object sender, System.EventArgs e)\n        {\n            Thread thread = new Thread(p =>\n            {\n                DateTime now = DateTime.Now;\n                DateTime endOfDay = DateTime.Today.AddDays(1);\n                TimeSpan timeLeftForClose = endOfDay.Subtract(now);\n                Thread.Sleep(timeLeftForClose);\n                this.Application.Quit();                    \n            });\n            thread.Start();\n        }\n\n        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)\n        {\n        }\n\n\n        private void InternalStartup()\n        {\n            this.Startup += new System.EventHandler(ThisAddIn_Startup);\n            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);\n        }\n\n\n    }	0
25705673	25705658	Running batch file from C# Force run from file's directory?	psi.WorkingDirectory = "D:\\Bethesda Softworks\\Arena";	0
26897234	26874938	How can I limit my textbox text length takes 9 digits only using regex	else if (!(e.KeyValue >= 48 && e.KeyValue <= 57) || textBox1.Text.Length == 9)\n{\n   e.SuppressKeyPress = !(e.KeyCode == Keys.Back || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right);\n}	0
6203533	6193874	Help with SAPI v5.1 SpeechRecognitionEngine always gives same wrong result with C#	0:\n  Encodingformat = Pcm\n  BitsPerSample = 8\n  BlockAlign = 1\n  ChannelCount = 1\n  SamplesPerSecond  = 16000\n\n  1:\n  Encodingformat = Pcm\n  BitsPerSample = 16\n  BlockAlign = 2\n  ChannelCount = 1\n  SamplesPerSecond  = 16000\n\n  2:\n  Encodingformat = Pcm\n  BitsPerSample = 8\n  BlockAlign = 1\n  ChannelCount = 1\n  SamplesPerSecond  = 22050\n\n  3:\n  Encodingformat = Pcm\n  BitsPerSample = 16\n  BlockAlign = 2\n  ChannelCount = 1\n  SamplesPerSecond  = 22050\n\n  4:\n  Encodingformat = ALaw\n  BitsPerSample = 8\n  BlockAlign = 1\n  ChannelCount = 1\n  SamplesPerSecond  = 22050\n\n  5:\n  Encodingformat = ULaw\n  BitsPerSample = 8\n  BlockAlign = 1\n  ChannelCount = 1\n  SamplesPerSecond  = 22050	0
22857270	22857144	How can i make this method async?	async void OnRegister(object sender, RoutedEventArgs e)\n    {\n        await PrintManager.ShowPrintUIAsync();\n    }	0
7090956	7090671	LINQ to XML in C# where clause	var rez = from item in doc.Descendants("result")\n            let testPairs = item.Elements("test")\n                .Select(t => Tuple.Create((string)t.Attribute("field"), (string)t)).ToArray()\n            where\n                testPairs.Any(t => t.Item1=="aaa" && t.Item2=="value_a") &&\n                testPairs.Any(t => t.Item1=="bbb" && t.Item2=="value_b")\n            select item;	0
30982253	30981866	performance issues executing list of stored procedures	int openThread = 0;\nConcurrentQueue<Type> queue = new ConcurrentQueue<Type>();\nforeach (var sp in lstSps)\n{\n    Thread worker = new Thread(() =>\n        {\n            Interlocked.Increment(ref openThread);\n            if(sp.TimeToRun() && sp.HasResult)\n            {\n                queue.add(sp);\n            }\n            Interlocked.Decrement(ref openThread);\n        }) {Priority = ThreadPriority.AboveNormal, IsBackground = false};\n        worker.Start();\n}\n// Wait for all thread to be finnished\nwhile(openThread > 0)\n{\n    Thread.Sleep(500);\n}\n\n// And here move sp from queue to lstSpsToSend\n\nwhile (lstSpsToSend.Count > 0)\n{\n    //Take the first watchdog in list and then remove it\n    Sp sp;\n    lock (lstSpsToSend)\n    {\n        sp = lstSpsToSend[0];\n        lstSpsToSend.RemoveAt(0);\n    }\n\n    try\n    {\n        //Send the results\n    }\n    catch (Exception e)\n    {\n        Thread.Sleep(30000);\n    }\n}	0
20270557	20270547	c# - calculating decimal numbers from textboxes	txt_WeightGrams.Text = result.ToString();	0
8834122	8834097	String constant delimiters that don't banalize line feeds?	const string myString = @"\n<html>\n  <head>\n  </head>\n  <body>\n  </body>\n</html>";	0
4672037	4671984	Parsing UTF8 encoded data from a Web Service	var input = "??";\nvar bytes = Encoding.GetEncoding("ISO8859-1").GetBytes(input);\nvar realString = Encoding.UTF8.GetString(bytes);	0
5848352	5848337	How can I check if a string exists in another string	if (stringValue.Contains(anotherStringValue))\n{  \n    // Do Something // \n}	0
7957738	7957687	C# For Loop with Random Int Generator locks the program	Random ranNum = new Random();	0
4007440	4007332	get array of table columns in LINQ To SQL	var dataColumns =\n    from member in yourDataContext.Mapping.GetMetaType(typeof(YourMappedType)).DataMembers\n    select new DataColumn {\n        ColumnName = member.MappedName,\n        DataType = (\n            member.Type.IsGenericType && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>)\n                ? new NullableConverter(member.Type).UnderlyingType\n                : member.Type\n        ),\n        AllowDBNull = member.CanBeNull\n    };	0
6495707	6495662	Returning a typed Func as a generic Func	private Func<IEnumerable<T>> FindSource<T>() where T : class\n{\n    if (typeof(CostLedger).IsAssignableFrom(typeof(T)))\n        return ()=>GetCostLedger ().Cast<T> ();\n\n    return null;\n}	0
19359314	19359241	C# Console Formatting	Console.WriteLine(\n  "-|- Name: {0,-10} | Surname: {1,-10} |", \n  myList[i].GetName(),\n  myList[i].GetName());	0
10142108	10141610	In C# how can I deserialize this json when one field might be a string or an array of strings?	var contacts = (new JavaScriptSerializer().DeserializeObject(theAboveJsonString) as Dictionary<string, object>)["contacts"];\n\n  if (contacts is object[])\n  {\n      jobInfo.contacts = String.Join("; ", contacts as object[]);\n  }\n  else\n  {\n      jobInfo.contacts = contacts.ToString(); \n  }	0
11220671	11220632	Getting the Matched number of the two array	String[] arrFirst={"a","b","c","d","e"};\n    String[] arrSecond={"a","b","f","d","g"};\n    String[] arrThird={"a","f","g","h","e"};\n\n    arrFirst.Intersect(arrSecond).Count(); // 3\n    arrFirst.Intersect(arrThird).Count(); //2	0
24970986	24970792	Sending email within .NET Task not working in console application	var task = _emailService.Send(new List<string> { @event.ContactEmail }, subject, body,\n                    new List<Attachment>\n                        {\n                            new Attachment(new MemoryStream(bytes), report.FileName, "application/pdf")\n                        });\n\n                if (task != null)\n                {\n                    task.Wait();\n                }	0
1847943	1847915	How to reinitialize the int array in java	pArray = new int[] {-3, -1, -2, -3, -4};	0
13022313	13022054	Reading lines of text from file with Using and Yield Return	var listOfBufferedLines = ReadLineFromFile(ReadFilePath);\n\n        var listOfLinesInBatch = new List<string>();\n        foreach (var line in listOfBufferedLines)\n        {\n            listOfLinesInBatch.Add(line);\n\n            if (listOfLinesInBatch.Count % 1000 == 0)\n            {\n                Console.WriteLine("Writing Batch.");\n                WriteLinesToFile(listOfLinesInBatch, LoadFilePath);\n                listOfLinesInBatch.Clear();\n            }\n        }\n\n        // writing the remaining lines\n        WriteLinesToFile(listOfLinesInBatch, LoadFilePath);	0
7134944	7134864	How to avoid having a Thread.Sleep(Int32.MaxValue) when waiting for an asynchronous operation to end in a Console app?	webClient.DownloadProgressChanged += (f,a) => ...\nAutoResetEvent resetEvent = new AutoResetEvent(false);\nwebClient.DownloadFileCompleted += (f, a) => resetEvent.Set();\nwebClient.DownloadDataAsync(new Uri(url_to_download), file_name);\nresetEvent.WaitOne();\nConsole.WriteLine("Finished");	0
28051062	28046494	How can I document a method which throws a generic exception in C#?	/// <summary>\n/// Throws any exception.\n/// </summary>\n/// <typeparam name="TException">Type of the exception to throw </typeparam>\n/// <exception>Thrown when\n///     <cref>TException</cref> whatever...\n/// </exception>    \npublic static void Throw<TException>() where TException : Exception\n{\n    throw (TException)Activator.CreateInstance(typeof(TException));\n}	0
12128893	12122012	How to set border of Shapes inside Word Document to None using c#?	oshape.Line.Visible = MsoTriState.msoFalse;	0
24971242	24969997	How to ovveride HardwareButtons_BackPressed of Basic Page in windows phone 8.1	protected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n\n        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;\n    }\n\n    protected override void OnNavigatedFrom(NavigationEventArgs e)\n    {\n        Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;\n    }	0
24593098	24592947	String Convert to JSON object	Class Person \n{\npublic int id {get;set;} \npublic string name {get;set;} \n}\n\nvar person = JsonConvert.DeserializeObject<Person>(jsonString);\n\nif you dont want to create class use JObject \n\ndynamic newObj = JObject.Parse(jsonString);\nstring id= newObj.id ;\nstring name= newObj.name;	0
26356713	26356645	display asp net variable in javascript	b.OnClientClick = "function (s, e) { alert ('" + cpt_test + "'); }";	0
6875487	6875102	c# dynamic json objects with dynamic names question	static void Main(string[] args) {\n\nvar json = @"\n{\n  '2010': [\n  {\n    'type': 'vacation',\n    'alloc': '90.00'\n  },\n  {\n    'type': 'something',\n    'alloc': '80.00'\n  }\n]}";\n\n\nvar jss = new JavaScriptSerializer();\nvar obj = jss.Deserialize<dynamic>(json);\n\nConsole.WriteLine(obj["2010"][0]["type"]);\n\nConsole.Read();\n\n}	0
24632727	24628891	Proper dependency management in a Xamarin project	xpkg.exe restore	0
9792810	9792266	Testing if outlook is installed with C# exception-handling	public static bool IsOutlookInstalled()\n{\n    try\n    {\n        Type type = Type.GetTypeFromCLSID(new Guid("0006F03A-0000-0000-C000-000000000046")); //Outlook.Application\n        if (type == null) return false;\n        object obj = Activator.CreateInstance(type);\n        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);\n        return true;\n    }\n    catch (COMException)\n    {\n        return false;\n    }\n}	0
3075258	3075110	transaction question in SQL Server 2008	read committed	0
16396111	16396017	Select xml element by class name with a regex	var classToRemove = "highlights-tracker";\nvar xml = XDocument.Parse(svg);\nvar elements = doc.Descendants("path")\n                  .Where(x => x.Attribute("class") != null &&\n                              x.Attribute("class")\n                               .Value.Split(' ')\n                               .Contains(classToRemove));\n// Remove all the elements which match the query\nelements.Remove();	0
25520064	25381119	Get the value from two cells and sum it and display in another cell using C# in WPF	int row = Convert.ToInt32(grid_calc.SelectedIndex.ToString());\n            object value = (this.grid_calc.Items[row] as DataRowView)[2];\n            object value1 = (this.grid_calc.Items[row] as DataRowView)[3];\n            int a = Convert.ToInt16(value);\n            int b = Convert.ToInt16(value1);\n            int c = a - b;\n            (this.grid_calc.Items[row] as DataRowView)[4] = c;	0
32381878	32381567	Web Api Method accepting string, int, alphanumeric	[Route("Api/Deliveries/{id}/{StringVal}/{AlphaVal}")]\npublic IEnumerable<Deliveries> GetByAdvanced(int id, string StringVal, string AlphaVal)\n{\n  var deliveries = ...\n\n  return deliveries;\n}	0
32078761	32078453	Using dynamic object fields with a strongly typed model	var order = new {CustomerName = "Bob Smith"};\nvar message = Mapper.DynamicMap<ICreateOrderMessage>(order);\nmessage.CustomerName.ShouldEqual("Bob Smith");	0
860577	859625	Is it possible to initialize a Control's List<T> property in markup?	public class MyControl : Control\n{\n    private readonly HashSet<RenderBehaviors> coll = new HashSet<RenderBehaviors>();\n\n    public IEnumerable<RenderBehaviors> Behaviors { get { return coll; } }\n\n    public string BehaviorsList\n    {\n        get { return string.Join(',', coll.Select(b => b.ToString()).ToArray()); }\n        set\n        {\n            coll.Clear();\n            foreach (var b in value.Split(',')\n                .Select(s => (RenderBehvaior)Enum.Parse(typeof(RenderBehavior), s)))\n            {\n                coll.Add(b);\n            }\n        }\n    }\n}	0
8123478	7861541	C# Web service to accept image and text parameters from iphone	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:urlURL]; // url to hit + parameters\n[request setRequestMethod:@"POST"];\n\n[request appendPostData:imageData]; // image as data\n[request startSynchronous];\nNSError *error = [request error];\n\nif (error) {\n    NSLog(@"error = %@", error);                \n}\nelse\n{\n    // success\n}	0
1138858	1138824	Example to see return value in multithread scenario	//set up your BackgroundWorker\n BackgroundWorker worker = new BackgroundWorker();\n worker.DoWork += new DoWorkEventHandler(worker_DoWork);\n worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);\n worker.RunWorkerAsync();\n\n\n        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n        {\n            if (e.Result != null)\n            {\n                //process your e.Result\n            }\n        }\n\n        void worker_DoWork(object sender, DoWorkEventArgs e)\n        {\n            //do your work here\n\n            e.Result = "testing"; //set the result to any object\n        }	0
9589717	9589589	Deserializing List<int> with XmlSerializer Causing Extra Items	public class ListTest\n{\n    public int[] Array { get; set; }\n    public List<int> List { get; set; }\n\n    public ListTest()\n    {\n\n    }\n\n    public void Init() \n    {\n        Array = new[] { 1, 2, 3, 4 };\n        List = new List<int>(Array);\n    }\n}\n\nListTest listTest = new ListTest();\nlistTest.Init(); //manually call this to do the initial seed	0
19839115	19838910	Using the Selected Item from Combo box in If Statement	if (Convert.ToDouble(cbMoney.SelectedItem.ToString()) < Convert.ToDouble(total))\n{\n  MessageBox.Show("Not Enough Money");\n}	0
30364862	30364799	Browser using c# in windows form applications	using System.Net;\nusing System.Net.Http; \n\nWebRequest req = HttpWebRequest.Create("http://yourwebsite.com");\nreq.Method = "GET";\n\nstring source;\nusing (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))\n{\n    source = reader.ReadToEnd();\n}\n\nSystem.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");\nfile.WriteLine(source);\n\nfile.Close();	0
12371316	12371140	How to allow the user to input only one type of data on the command-line?	float f;\nbool success = Float.TryParse(parameter, out f);\nif(success)\n{\n    ....\n}\nelse\n{\n    ....\n}	0
33475660	33433015	How to convert this sql request to Lambda expression or LINQ	DateTime date = DateTime.Now.AddMonths(1);\n        var prelevements = from pc in set.Where(s => s.DTPROCHAINPREL >= DateTime.Today && s.NOSOC == nosoc && s.DTPROCHAINPREL < date)\n                           join ci in context.Set<ContratIBAN>().Where( g => g.PRELEVEMENTBCA == true) on pc.IDCMPT equals ci.IDCMPT into cileft\n                          from ci in cileft.DefaultIfEmpty()\n                           join co in context.Set<Contrat>() on ci.NOCONTRAT equals co.NOCONTRAT into coleft     \n                          from co in coleft.DefaultIfEmpty()	0
4326586	4326399	Parsing XML Files in .NET	using (FileStream lStream = new FileStream("ConfigurationSettings.xml", FileMode.Open, FileAccess.Read))\n{\n     XElement lRoot = XElement.Load(lReader)\n     string userLogin = "user1";\n     XElement user = lRoot.Element("UserSettings").Elements("user").Where(x => x.Attribute("Key").Value == userLogin).FirstOrDefault();\n      if (user != null)\n      {\n          // returns red\n          string color = user.Element("layout").Attribute("color").Value;\n\n          // returns 5\n          string fontSize = user.Element("layout").Attribute("fontsize").Value;\n      }\n\n}	0
18332021	18331925	Asp.net email validation on button click event	message.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess;	0
23215050	23198671	Use custom conventions when persisting Rebus sagas in MongoDb	var conventions = new ConventionPack();\nconventions.Add(new EnumSerializationConvention(BsonType.String));\nConventionRegistry.Register("Saga conventions", conventions, x => true);	0
10802656	10801356	Datagridview-multiple tables to single table	//public/Global datatable\npublic DataTable myTable = new DataTable();\npublic Form1()\n    {\n        InitializeComponent();\n        //create myTable Columns\n        myTable.Columns.Add("Name");\n        myTable.Columns.Add("Age");\n        myTable.Columns.Add("Number");\n        //add one row\n        myTable.Rows.Add(new object[] {"myName","myAge","myNumber"});\n        bind to the datagridview\n        dataGridView1.DataSource = myTable;\n\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        //display the number or rows in the datatable\n        MessageBox.Show(myTable.Rows.Count.ToString());\n    }\n}	0
413702	413656	Creating a Popup Balloon like Windows Messenger or AVG	private void button1_Click(object sender, EventArgs e)\n        {\n            this.notifyIcon1.BalloonTipText = "Whatever";\n            this.notifyIcon1.BalloonTipTitle = "Title";\n            this.notifyIcon1.Icon = new Icon("icon.ico");\n            this.notifyIcon1.Visible = true;\n            this.notifyIcon1.ShowBalloonTip(3);\n        }	0
3144520	3144492	How do I get .NET's Path.Combine to convert forward slashes to backslashes?	test1/test2\test3\test4	0
32036294	32012870	XML reading issues	Item overview2 = (Item)reader.Deserialize(xml2);	0
5893267	5893255	Most efficient way to count number of weeks between two datetimes	int weeks = (date1 - date2).TotalDays / 7;	0
26529023	26476598	How can I hide columns in GridView?	protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)\n    {\n        if(e.Row.Cells.Count > 2)\n            e.Row.Cells[2].Visible = false;\n    }	0
6697013	6696916	C# Get String from Private void	class MyClass : SomeBaseClass\n{\n   string teamsite;\n   protected override void test ()\n   {\n      string teamsitefinal = teamsite;\n   }\n   private void test2 ()\n   {\n      teamsite = "test";\n   }\n}	0
22411780	22409159	Returning XML from Oracle Procedure to C# restful service	create or replace\nPROCEDURE SP_GETINDIVIDUALFUND(v_fundID IN VARCHAR2,\n                             v_ResultSet OUT sp_GetResultSet.ResultSet) AS\nBEGIN\n  Open v_ResultSet FOR\n  SELECT dbms_xmlgen.getxml('select A.FUNDNAME, \n    substr(A.FundStationFundNumber, 1, 4) AS FundStationFundNumber, \n    A.SHARECLASS, \n    B.ASOFDATE, \n    B.NAV, \n    B.NAVCHANGE, \n    A.INCEPTIONDATE \n  FROM TBL_FUND A, \n       TBL_FUNDDAILYINFO B  \n  WHERE A.FUNDID = B.FUNDID (+) \n    AND A.PRODUCTLINECODE = 3 \n   AND (A.PRODUCTCATEGORYCODE <> 5\n    AND A.PRODUCTCATEGORYCODE <> 6\n    AND A.PRODUCTCATEGORYCODE <> 102)\n  ORDER BY A.FUNDNAME, \n           A.SHARECLASS') \n  xml FROM dual;\nEND;	0
22415183	22413282	How to indicate success with Web API 2?	dataType: 'json',	0
17075656	17075169	Hide the buttton of logout	protected void Page_Load(object sender, EventArgs e)\n {\n        if (!IsPostBack)\n        {\n\n            if (Session["Username"] != null)\n                Logout.Visible = true;\n\n            else\n                 Logout.Visible = false;\n        }\n }	0
18555436	18555423	How to transfer items of one static list to another	list2 = new List<string>(list1);	0
3715283	3698287	How to set DataGridView's Height properties if the control is inside a ToolStripControlHost? C# WINFORMS	ToolStripControlHost tsHost = new ToolStripControlHost(dataGridView1);\ntsHost.AutoSize = false; // Set AutoSize property to false.\ntsHost.Height = 30;      // then set Height property value.\ncontextMenuStrip1.Items.Clear();\ncontextMenuStrip1.Items.Add(tsHost);	0
21699508	21697395	How to get xml Node name and Inner Text and Fill Grid view	XmlDocument doc = new XmlDocument();\n        doc.Load(XmlPath);\n\n\n        DataTable dt = new DataTable();\n        foreach (XmlNode xn in doc.ChildNodes[0])\n        {\n            string tagName = xn.Name;\n            if (!dt.Columns.Contains(tagName))\n            {\n                dt.Columns.Add(tagName);\n            }\n\n        }\n        DataRow dr = dt.NewRow();\n        foreach (XmlNode xn in doc.ChildNodes[0])\n        {\n\n            dr[xn.Name] = xn.InnerText;\n\n\n        }\n        dt.Rows.Add(dr);	0
9148268	9148196	dynamic change jwplayer video path	Var a = "video/" + document.GetElementbyID("textbox2").value + ".mp3";	0
9231566	8433936	DevExpress WPF Grid export to excel - additional rows	public void ExportGridToExcel()\n{\n    TableView.Grid.Columns["*FieldName*"].EditSettings = new TextEditSettings();\n\n    TableView.ExportToXls(@"C:\temp\spreadsheet.xls");\n\n    TableView.Grid.Columns["*FieldName*"].EditSettings = new CheckEditSettings();\n}	0
31483813	31483458	Randomized File (Stream) From List of Checkboxes	var dict = new Dictionary<int, string>();\n        dict.Add(0, "QATestFileGenTools.checkFront1.bmp");\n        dict.Add(1,"QATestFileGenTools.checkFront2.bmp");\n        dict.Add(2, "QATestFileGenTools.checkFront2.bmp");\n\n        Random rnd = new Random(DateTime.Now.Millisecond);\n        int randomInt = rnd.Next(0, 2);\n\n        string resourceName = dict[randomInt];\n        System.IO.Stream file file = thisExe.GetManifestResourceStream(resourceName);	0
16870465	16870413	How to call another controller Action From a controller in Mvc	var result = new ControllerB().FileUploadMsgView("some string");	0
31204259	31197455	MvvmCross, how to register Service in another assembly?	typeof(Reusable.Helpers.MyHelper).Assembly.CreatableTypes()\n       .EndingWith("Helper")\n       .AsInterfaces()\n       .RegisterAsDynamic();	0
20284199	20284157	Escape Character while using @	Console.WriteLine(@"Line 0\nLine 1\nLine 2\nLine 3\n""Escape these quotes!""\nLine 5\n")	0
18109	18097	In C#, do you need to call the base constructor?	using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            MyClass foo = new MyClass();\n\n            Console.ReadLine();\n        }\n    }\n\n    class BaseClass\n    {\n        public BaseClass()\n        {\n            Console.WriteLine("BaseClass constructor called.");\n        }\n    }\n\n    class MyClass : BaseClass\n    {\n        public MyClass()\n        {\n            Console.WriteLine("MyClass constructor called.");\n        }\n    }\n}	0
26111924	26111052	WPF Data Binding without using Entity Data Model Wizard	public partial class MainWindow : Window\n{\n    public ObservableCollection<Customer> Customers { get; set; }\n\n\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        Customers = new ObservableCollection<Customer>();\n\n        var conString = "MyConnectionString";\n\n        using (var con = new SqlConnection(conString))\n        {\n            con.Open();\n            var sql = "Select Name from Customer";\n\n            var cmd = new SqlCommand(sql, con);\n\n            using (var reader = cmd.ExecuteReader())\n            {\n                while (reader.Read())\n                {\n                    var c = new Customer\n                    {\n                        Name = reader[0].ToString()\n                    };\n\n                    Customers.Add(c);\n                }\n            }\n        }\n    }\n}\n\npublic class Customer\n{\n    public string Name { get; set; }    \n}	0
11559169	11559057	Creating a do statement that has the properties of a while statement	if(b)\n{\n    do\n    {\n        s;\n    }\n    while(b);\n}	0
29772648	29772429	How i can find date item in list in C#	for (var day = fromDate.Date; day.Date <= toDate.Date; day = day.AddDays(1))\n{\n    if (!MyList.Any(x => x.Date == day))\n        MyList.Add(day);\n}	0
13097278	13097179	How to prevent EntityFramework deadlock when concurrently running these two statements	using (var scope = new TransactionScope(TransactionScopeOption.Required, new \n    TransactionOptions { IsolationLevel= IsolationLevel.Snapshot }))\n{\n    // do something with EF here\n    scope.Complete();\n}	0
28993665	28887269	Can you create a centralized topic in ZeroMQ?	import zmq\n\ndef main():\n\n    try:\n        context = zmq.Context(1)\n        # Socket facing clients\n        frontend = context.socket(zmq.SUB)\n        frontend.bind("tcp://*:5559")\n\n        frontend.setsockopt(zmq.SUBSCRIBE, "")\n\n        # Socket facing services\n        backend = context.socket(zmq.PUB)\n        backend.bind("tcp://*:5560")\n\n        zmq.device(zmq.FORWARDER, frontend, backend)\n    except Exception, e:\n        print e\n        print "bringing down zmq device"\n    finally:\n        pass\n        frontend.close()\n        backend.close()\n        context.term()\n\nif __name__ == "__main__":\n    main()	0
11296808	11296750	Accessing Navigation Properties in a View	public ActionResult Create(\n    SurveyResponseModel surveyresponsemodel) //, int MemberId, int ProgramId)\n{\n    // MemberId and ProgramId arguments do not need to be defined\n    // They will be picked up my MVC model binder, since there are properties\n    // with the same name in SurveyResponseModel class\n    //surveyresponsemodel.MemberId = MemberId;\n    //surveyresponsemodel.ProgramId = ProgramId;\n    surveyresponsemodel.SurveyProgramModel = new SurveyProgramModel(); // new line\n    return View(surveyresponsemodel); // <- return your view model here\n}	0
28751302	28751185	How can I access the binding properties of a XAML object, from my code behind?	BindingExpression be= txt.GetBindingExpression(TextBox.TextProperty);\n        string format=be.ParentBinding.StringFormat;	0
6688948	6688737	How to use Open With Dialog box when file format not recognized	Process.Start("FullFileNamePath");	0
9497121	9496929	Different content in Footer from the ItemTemplate result	if( e.Item.ItemType == ListItemType.Footer )\n{    Label myLabel = ((Label)e.Item.FindControl("mylabelid"));\n    mylabel.Text="datafrom db";\n}	0
2740214	2739414	Save BLOB to disk as Image C#	v_file_data = Encoding.UTF8.GetBytes(ds.Tables[0].Rows[0]["logo"]);	0
10604265	10604208	Get user name from application string	string userName = string.Format(ApplicationStrings.WelcomeMessage, WebContext.Current.User.DisplayName);	0
17586203	17570488	Instatiate with Unity two objects of same interface in the same class	IUnityContainer container = new UnityContainer()\n    .RegisterType<IRegisterAutoMapper, RegisterAutoMapper>() //default\n    .RegisterType<IRegisterAutoMapper, MobileRegisterAutoMapper>("Mobile")\n    .RegisterType<AutoMapperRegisterFactory>(\n        new InjectionConstructor(\n            typeof(IRegisterAutoMapper), \n            new ResolvedParameter<IRegisterAutoMapper>("Mobile")));	0
1294541	1294470	+ sign in front of a tree node	private void button1_Click(object sender, EventArgs e) {\n        // WARNING: add checks\n        TreeNode[] nodes = treeView1.Nodes.Find("Node2",true);\n        TreeNode node = nodes[0];\n        node.Nodes.Add("child node");\n    }	0
1700657	983726	store a pdf in mysql	BLOB, TEXT                L + 2 bytes, where L < 216\nMEDIUMBLOB, MEDIUMTEXT    L + 3 bytes, where L < 224\nLONGBLOB, LONGTEXT        L + 4 bytes, where L < 232	0
6794610	6794238	Using C# to run a PowerShell script	PSCommand command = new PSCommand(); \ncommand.AddScript( \n    "[System.Net.ServicePointManager]::ServerCertificateValidationCallback+={$true}"\n); \n\nPowerShell powershell = PowerShell.Create();\npowershell.Commands = cmd;\n\nvar results = powershell.Invoke();	0
3506999	3499903	How to get Items count from CollectionViewSource?	private void SetSummary() \n{\n    int initialCount = 0;\n    foreach(var item in _viewSource.View.SourceCollection)\n    {\n        initialCount++;\n    }\n\n    int filteredCount = 0;\n    foreach (var item in _viewSource.View)\n    {\n        filteredCount++;\n    }\n}	0
26071331	26071271	How to make keypress handle Enter	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n{\n     e.SuppressKeyPress = true; \n}	0
21668473	21657799	How do i make a main group directory name for each directories ?	foreach (var map in maps)\n{\n    // This starts a new group\n    var count = "Sat24_".Length;\n    var leafDirectory = htmlFiles[groupId++].Remove(0, count); // e.g. "Africa0"\n    var continent = Regex.Match(leafDirectory, @"[A-Za-z_]+").Value; // e.g. "Africa"\n\n    var downloadDirectory = Path.Combine(BaseDirectory, "Europe", continent, ???leafDirectory);\n    BackgroundWorkerConfiguration.urlsDirectories.Add(downloadDirectory);\n}	0
1618946	1604528	How do I stub a Func<T,TResult> in Rhino Mocks?	public interface IExecute {\n  void Execute(string input)\n}\n_connectionService\n    .Stub(c => c.RemoteCall(null)).IgnoreArguments()\n    .Do(new Func<Action<IExecute>,bool>( func => {\n       var stub = MockRepository.GenerateStub<IExecute>();\n       func(stub);\n       stub.AssertWasCalled(x => x.Execute("test"));\n       return true;\n     }));;	0
4132171	4132137	How to avoid flickering in treeview	try\n{\n    treeView.BeginUpdate();\n\n    // Update your tree view.\n}\nfinally\n{\n    treeView.EndUpdate();\n}	0
33633316	33499481	Append predefined style to a Word bookmark with c#	Selection.ClearCharacterStyle	0
7949029	7946321	drawing a textbox with clipping of the text inside	spriteBatch.GraphicsDevice.RenderState.ScissorTestEnable = true;\n  spriteBatch.GraphicsDevice.ScissorRectangle = myTextBox.GetRectangle();\n  spriteBacth.Begin();\n  spriteBatch.DrawString(...);       \n  spriteBacth.End();\n  spriteBatch.GraphicsDevice.RenderState.ScissorTestEnable = false;	0
13588650	13588298	RegularExpressionValidator for more than one email for only one company	protected void cvtbProduct_Email_OnServerValidate(object sender, ServerValidateEventArgs args)\n    {\n        var emailList = (TextBox) RadGrid1.MasterTableView.GetInsertItem().FindControl("Product_Email");\n\n        if (string.IsNullOrEmpty(emailList.Text))\n        {\n            args.IsValid = false;\n            return;\n        }\n\n        //you don't need to check if it has the seperator in it\n        var emails = emailList.Text.Split(';');\n\n        foreach (var email in emails)\n        {\n            //the @ before a string removes the need to double up on '\'\n            //you were missing a '\' before the .\n            var valid = Regex.IsMatch(email, @"\w+([-+.']\w+)*@ABCCompany\.com");\n\n            if (!valid)\n            {\n                args.IsValid = false;\n                return; //don't check anymore\n            }\n        }\n\n        //all must have passed\n        args.IsValid = true;\n    }	0
4081987	4081957	Converting a list of structs to a byte array	using (FileStream file = File.OpenWrite("FileName.ext")) {\n  using (BinaryWriter writer = new BinaryWriter(file)) {\n    foreach (Data data in theList) {\n      writer.Write(data.FirstShort);\n      writer.Write(data.SecondShort);\n      writer.Write(data.TheByte);\n    }\n  }\n}	0
14400482	14384702	Programmatically Create Wireless Ad-Hoc Network	private bool ConnectToNetwork(\n    string ssid, \n    string passphrase, \n    bool adhoc, \n    AuthenticationMode mode, \n    WEPStatus encryption)\n{\n    // other setup code, etc\n                return m_wzc.AddPreferredNetwork(ssid,  \n                    !adhoc,  \n                    passphrase,  \n                    1,  \n                    mode,  \n                    encryption,  \n                    eap);  \n}	0
9807486	9807047	opening an embedded html in an external browser in C#	var txt = Properties.Resources.sample;\nvar fileName = Path.Combine(Path.GetTempFileName(), ".html");\n\nvar fs = File.CreateText(fileName);\nfs.Write(txt);\nfs.Flush();\nfs.Close();\n\nProcess.Start(fileName);	0
23917749	23916909	Winrt advanced scroll viewer content	ScrollViewer.TopLeftHeader\nScrollViewer.TopHeader\nScrollViewer.LeftHeader	0
14349435	14349219	How can I access a minimized form from another form without creating an instance?	foreach (var f in Application.OpenForms)\n{\n    if (f is MyForm)\n    {\n        // do something...\n        break;\n    }\n}	0
8252178	8224617	ReactiveUI MessageBus and MessageBox with result	(new TestScheduler()).With(sched => {\n    // Write your test here, all the schedulers will be\n    // implicitly set to your 'sched' scheduler.\n});	0
34398621	34398073	Azure WebJob Best Approach	static void Main()\n{\n    SupportService _supportService = new SupportService();\n    _supportService.Initialize();\n    _supportService.SetPoolProvisioningConfigurations();\n    _supportService.RunOnePoolProvisioningCycle();\n}	0
10514898	10514820	Get a delta, using a TimeStamp Column in Linq2SQL	public static class BinaryComparer\n{\n public static int Compare(this Binary v1, Binary v2)\n {\n throw new NotImplementedException();\n }\n}\n\nvar result = from row in MyTable\n             where BinaryComparer.Compare(row.TimeStamp, SomeTarget) > 0\n             select row;	0
9357225	9332455	Builds work on build machine through TFS/Team Build but not TeamCity	+:path/to/ProjectFolder=>.\n+:path/to/libary=>library/path	0
8678990	8678898	How i can making caching feature that work on application level caching through a collection to access or generate the data	Cache.Insert("CacheItem6", "Cached Item 6",\n    null, DateTime.Now.AddMinutes(1d), \n    System.Web.Caching.Cache.NoSlidingExpiration);	0
33751965	33731821	Windows store app error during print operation	private async void printBirth_Click(object sender, RoutedEventArgs e)\n    {\n        await Windows.Graphics.Printing.PrintManager.showPrintUIAsync()\n    }	0
24085664	24085437	Get specific part of string	text = sr.ReadToEnd(); \n string[] xx = text.Split('\"');\n string test = xx[3];	0
17862393	17862030	How do I display query results in the same order they were made in a multithreaded web app?	private static SortedList<long, SearchResult> resultsList = new SortedList<long, SearchResult>();\n...\n    foreach (var v in resultsList.Values)\n    {\n...\npublic static long RequestID = 0;\nprotected void MakeRequest(string text)\n{\n    SearchResult s = new SearchResult\n    {\n        SearchTerm = text,\n        Count = 0\n    };\n    resultsList.Add(System.Threading.Interlocked.Increment(ref RequestID), s);	0
9846418	5889965	Changing discriminator column to int in Entity Framework 4.1	modelBuilder.Entity<ClassBase>()\n        .Map(m => {\n            ...\n            m.Requires("Discriminator").HasValue(1)\n        });	0
29359206	29350903	Linked Table Shows As read only	dd.Execute "CREATE UNIQUE INDEX SomeIndex ON SomeTable (PrimaryKeyColumn) WITH PRIMARY"	0
7349474	6574041	return Array from C# to Classic ASP with COM	public object returnStuff() {\n    return new object[] {'1','2','3'};\n}	0
25985418	25985108	Creating a windows service from a windows forms application	ServiceController service = new ServiceController();\nstring[] args=new string[2];\nargs[0] = "Your first argument";\nargs[1] = "Your second argument";\nservice.DisplayName = "Your Service Display Name";//As it appears in services.msc\nservice.Start(args);	0
16695086	16694851	How to remove the top left cell in DataGrid	myDataGridTableStyle.RowHeadersVisible = false;	0
15820750	15820708	programmatically change left and top image	Canvas.SetLeft(img1, 50);\nCanvas.SetTop(img1, 80);	0
6952537	6952350	Accesing a CheckBox that's inside a Repeater	protected void IsSelected_ChkBx_CheckedChanged(object sender, EventArgs e)\n{\n     var ch = (CheckBox)sender;\n     var txt = ch.Parent.FindControl("Value_TxtBx") as TextBox;\n}	0
25948758	25948454	How to set background color to transparent for a richtextbox in c#	public class TransparentLabel : RichTextBox\n    {\n        public TransparentLabel()\n        {\n            this.SetStyle(ControlStyles.Opaque, true);\n            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);\n            this.TextChanged += TransparentLabel_TextChanged;\n            this.VScroll += TransparentLabel_TextChanged;\n            this.HScroll += TransparentLabel_TextChanged;\n        }\n\n        void TransparentLabel_TextChanged(object sender, System.EventArgs e)\n        {\n            this.ForceRefresh();\n        }\n        protected override CreateParams CreateParams\n        {\n            get\n            {\n                CreateParams parms = base.CreateParams;\n                parms.ExStyle |= 0x20;  // Turn on WS_EX_TRANSPARENT\n                return parms;\n            }\n        }\n        public void ForceRefresh()\n        {\n            this.UpdateStyles();\n        }\n    }	0
7726337	7722975	Checking bit state of lpt port binary	var PortValue = Convert.ToString(PortAccess.Input(889), 2).PadLeft(8, '0');\n   PortV.Text = PortValue;\n   while (PortV.Text[3].ToString() == "1")\n   {\n   //some code\n   }	0
5654603	5652846	C# - Custom Attribute not found from GetCustomAttribute from Interface	Assembly.GetExecutingAssembly();	0
25602584	25602459	C# How To Convert From Int ddmmyy to DateTime?	int year = (date % 100) + 2000;\nint month = (date / 100) % 100;\nint day = (date / 100000);\nDateTime result = new DateTime(year, month, day);	0
3227187	3227128	please help me in using inheritance of object	class Person { }\nclass Employee: Person { }\nclass Member : Employee\n{\n    public IList<Order> Orders { get; private set; }\n}\n\nclass Order\n{\n   public int MemberId { get; private set; }\n}	0
8472641	8472344	A tricky one involving List<T> and object casting	void PrintFamily(Ancestor a)\n{\n    Action<Parent, int> printParent = null;\n    printParent = (parent, level) => \n    {\n        var indentation = new string(' ', level * 4);\n        var indentationChildren = new string(' ', (level + 1) * 4);\n        Console.WriteLine(indentation + parent.Name);\n        foreach(var child in parent.Children)\n        {\n            if(child is Child)\n                Console.WriteLine(indentationChildren + child.Name);\n            else if(child is Parent)\n            {\n                printParent((Parent)child, level + 1);\n            }\n        }\n    };\n\n    printParent(a, 0);\n}	0
25097721	25097387	Send the entire debug console output to clipboard?	EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0");\nTextSelection sel = dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").TextDocument.Selection;\nsel.StartOfDocument(false);\nsel.EndOfDocument(true);\nClipboard.SetText(sel.Text);	0
28118822	28118799	C# How do I log off a Citrix XenApp User Session?	using Citrix.Common.Sdk;\nusing Citrix.XenApp.Sdk;\nusing Citrix.XenApp.Commands;\nusing Citrix.Management.Automation;\n\n    private void logoffUser(string strUser)\n    {\n        GetXASessionByFarm sessions = new GetXASessionByFarm(true);\n\n        foreach (XASession session in CitrixRunspaceFactory.DefaultRunspace.ExecuteCommand(sessions))\n        {\n            if (session.AccountName.ToLower() == objWINSDomainName + "\\" + strUser)\n            {\n                var cmd = new StopXASessionByObject(new[] { session });\n                CitrixRunspaceFactory.DefaultRunspace.ExecuteCommand(cmd);\n            }\n        }\n    }	0
15341974	15306690	How to change the data within elements in a XML file using C#?	XmlDocument xmlDoc = new XmlDocument();\n    xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string\n    string path = "/Installation/ServerIP";\n    XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node\n    node.InnerText = "192.168.1.12"; // update node, replace the inner text\n    xmlDoc.Save("file.xml"); // save updated content	0
18241942	18241806	String array declaration using for loop	var rows = new List<string[]>();\nfor (int i = 0; i < 32; i++)\n{\n    var row = new string[] { Convert.ToString(i), DataBin[i], BitLabels[2, i], BitLabels[1, i], BitLabels[0, i], };\n    rows.Add(row);\n}\n\n// use rows.ToArray() if you need it to be an array or arrays later.	0
7529217	7528415	How I can run MessageBox.Show() from App.xaml.cs	Deployment.Current.Dispatcher.BeginInvoke(() =>\n{\n MessageBox.Show("");\n}\n);	0
13797333	6647977	Custom allocator doesn't work on Windows 7	filterConfig.SetRenderingMode(VMR9Mode.Renderless);\n// QueryInterface on the VMR-9 filter for the IVMRSurfaceAllocatorNotify9 interface.\nIVMRSurfaceAllocatorNotify9 san = (IVMRSurfaceAllocatorNotify9)_vmr9;\n// Call the IVMRSurfaceAllocatorNotify9::AdviseSurfaceAllocator method and pass in a pointer to your allocator-presenter's IVMRSurfaceAllocator9 method.\nsan.AdviseSurfaceAllocator(IntPtr.Zero, allocator);\n// Call your allocator-presenter's IVMRSurfaceAllocator9::AdviseNotify method and pass in a pointer to the VMR-9 filter's IVMRSurfaceAllocatorNotify9 interface.\nallocator.AdviseNotify(san);\n// Change mixer prefs AFTER settings the allocator in order to support YUV mixing (best performance)\nIVMRMixerControl9 mixerControl = (IVMRMixerControl9)_vmr9;\nVMR9MixerPrefs prefs;\nmixerControl.GetMixingPrefs(out prefs);\nprefs &= ~VMR9MixerPrefs.RenderTargetMask;\nprefs |= VMR9MixerPrefs.RenderTargetYUV;\nmixerControl.SetMixingPrefs(prefs);	0
16089391	16089233	Selecting a sub-list with an associated string value	return ListOfAs\n    .SelectMany(a => a.Products,\n                (a, p) => new ClassB\n                                {\n                                    Description = a.Description,\n                                    SingleProduct = p\n                                })\n    .ToList();	0
12765355	12765329	PLINQ query, need to know how many iterations performed	int totalCombosRun=0;\n\n private bool processNextCombo(string combo)\n {\n     Interlocked.Increment(ref totalCombosRun);\n     // do tests to see if combo was a winner\n     if (didWin)\n        return true;\n     return false;\n }	0
5672366	5672236	Generating word list from word	A -> a, A, 4\nB -> b, B, 8\nC -> c, C\nD -> d, D\n// etc.\n1 -> 1, L, l\n2 -> 2\n3 -> 3, e, E\n// etc.	0
6467908	6467802	How to Add an element to the source of a PagedCollectionView	MyObject newO = (MyObject)_PagedList.AddNew(); \nnewO.SetProperty="Make the changes to the object";\n_PagedList.CommitNew();	0
34444042	34441665	Using app.config to connect to a SAP company	// In code\nCompany company = new Company\n{\n    Server = ConfigurationManager.AppSettings["DevServer"],\n    DbUserName = ConfigurationManager.AppSettings["DevDBUser"],\n    DbPassword = ConfigurationManager.AppSettings["DevDBPassword"],\n    CompanyDB = ConfigurationManager.AppSettings["DevDatabase"],\n    UserName = ConfigurationManager.AppSettings["DevSBOUser"],\n    Password = ConfigurationManager.AppSettings["DevSBOPassword"],\n    language = BoSuppLangs.ln_English\n};\n\n// In your app.config\n<appSettings>\n   <add key="DevServer" value="DEV-SAP-SRV"/>\n   <add key="DevDBUser" value="sa"/>\n   <add key="DevDBPassword" value="sapassword"/>\n   <add key="DevSBOUser" value="manager"/>\n   <add key="DevSBOPassword" value="1234"/>\n   <add key="DevDatabase" value="SBO_COMPANY_NAME"/>\n</appSettings>	0
10019808	10019201	How do I persist checked rows on a grid that is populated from Cache instead of Session?	/// <summary>\n/// Iterates through items in the grid and updates the selected vendor \n/// list with any selections or deselections on the current page\n/// </summary>\nprivate void UpdateSelectedItems()\n{\n    var selectedVendors = new List<int>();\n\n    foreach (GridItem Item in grdVendors.Items)\n    {\n        if (Item is GridDataItem)\n        {\n            int VendorID = (int)((GridDataItem)Item).GetDataKeyValue("SupplierID");\n            if (Item.Selected)\n            {\n                if (!selectedVendors.Contains(VendorID))\n                    selectedVendors.Add(VendorID);\n                continue;\n            }\n\n            selectedVendors.Remove(VendorID);\n        }\n    }            \n}	0
27905285	27904268	Equivalent in RxJava	Observable<Integer> sumDeferred = Observable.defer(new Func0<Observable<Integer>>() {\n        @Override\n        public Observable<Integer> call() {\n            return Observable.just(addTwoNumbers(5, 4));\n        }\n    }).subscribeOn(Schedulers.io());\nsumDeferred.subscribe(...);	0
4021720	4021637	IP address of network computer	ping MyPCName	0
4676253	4676204	How to print an isosceles triangle	for (int row = 0; row < peak; row++)\n{\n    Console.WriteLine(new string(character, row + 1));\n}\nfor (int row = 1; row < peak; row++)\n{\n    Console.WriteLine(new string(character, peak - row));\n}	0
15844773	15843683	Remove entity with related entities in EntityFramework	[HttpPost]\npublic ActionResult Eliminar(Usuario usuario)\n{\n    db.Usuarios.Attach(usuario);\n    db.Entry(usuario).Collection("Transacciones").Load();\n    db.Entry(usuario).Collection("Eventos").Load();\n\n    usuario.Transacciones.ToList().ForEach(t => db.Transacciones.Remove(t));\n    usuario.Eventos.ToList().ForEach(e => db.Eventos.Remove(e));\n    db.Usuarios.Remove(usuario);\n    db.SaveChanges();\n\n    return RedirectToAction("Index");\n}	0
29548316	29548142	WPF DataGrid SelectAll Checkbox with two-way binding	internal class BaselineEntity:INotifyPropertyChanged\n{\n    public string EntityId { get; set; }\n\n    private bool isSelected;\n\n    public bool IsSelected\n    {\n        get { return isSelected; }\n        set { isSelected = value; OnPropertyChanged("IsSelected"); }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n    private void OnPropertyChanged(string propName)\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(propName));\n        }\n    }\n}	0
9393689	9393576	Get substring from a string	string text = "Casual Leave:12-Medical Leave :13-Annual Leave :03";\n        string[] textarray = text.Split('-');\n        string textvalue = "";\n        foreach (string samtext in textarray)\n        {\n            if (samtext.StartsWith(<put the selected value from labe1 here>))\n            {\n                textvalue = samtext.Split(':')[1];\n            }\n        }	0
17343775	17343670	C# List removeall taking two arguments in the predicate?	listX.RemoveAll(item => listX.Any(isin => AinB(item, isin)));	0
26851130	26655196	Process multiple T4 templates with custom tool	public class MyCodeGenerator : TemplatedCodeGenerator\n{\n    protected override byte[] GenerateCode(string inputFileName, string inputFileContent)\n    {\n        ProcessTemplate(inputFileName, CodeGenerationResource.TemplateX);\n        ProcessTemplate(inputFileName, CodeGenerationResource.TemplateY);\n\n        // since we're using the MultipleOutputHelper class in the t4 templates, which generates the required files on its own, we don't have to return any bytes\n        return new byte[0];\n    }\n\n    private void ProcessTemplate(string inputFileName, string templateContent)\n    {\n        var fi = new FileInfo(inputFileName);\n        templateContent = templateContent.Replace("Sample.mmd", fi.Name);\n        base.GenerateCode(inputFileName, templateContent);\n    }\n}	0
5356595	1441645	WPF: Dropdown of a Combobox highlightes the text	public override void OnApplyTemplate()\n{\n  base.OnApplyTemplate();\n\n  var element = GetTemplateChild("PART_EditableTextBox");\n  if (element != null)\n  {\n    var textBox = (TextBox)element;\n    textBox.SelectionChanged += OnDropSelectionChanged;\n  }\n}\n\nprivate void OnDropSelectionChanged(object sender, RoutedEventArgs e)\n{\n    // Your code\n}	0
16252691	16243320	Blurring/Hiding windows when a timeout occurs	foreach (Form f in Application.OpenForms)\n        {\n            f.Visible = false;\n        }\n        PasswordPrompt.ShowDialog();\n        PasswordPrompt.Dispose();\n        foreach (Form f in Application.OpenForms)\n        {\n            f.Visible = true;\n        }	0
3593538	3593520	How to use Linq/Lambda with ObservableCollection<T>	var matchingDevices = new ObservableCollection<Device>(allDevices.Where(d => d.ID != 5));	0
14373685	14373446	Draw figures in WPF	PathFigure figure = new PathFigure() \n{ \n    StartPoint = new Point(0, TurboHeight / turboSizeFactor * turboSchaufelFactor),\n    IsClosed = true\n};\n\n\nfigure.Segments.Add(new LineSegment() { Point = new Point(turboWidth, TurboHeight / turboSizeFactor * turboSchaufelFactor) });\nfigure.Segments.Add(new LineSegment() { Point = new Point(turboWidth * 0.85, 0) });\nfigure.Segments.Add(new LineSegment() { Point = new Point(turboWidth * 0.15, 0) });\n\nPathGeometry geo = new PathGeometry();\ngeo.Figures.Add(figure);\n\nPath path = new Path() { Data = geo, Stroke = Brushes.Black, StrokeThickness = 1, SnapsToDevicePixels = true, Fill = Brushes.LightGray };\n\nCnvMain.Children.Add(path);	0
4877471	4877363	how to make my button looks like it is being clicked?	btnName.Enabled = false	0
6401213	6401201	How can I remove elements of a List from a class containing the List?	public void RemoveEmptyChildren() {\n     _ParentDetail.RemoveAll(\n         x => x.Text == null ||\n         string.IsNullOrEmpty(x.Text.TextWithHtml));\n}	0
9595669	9595569	Selecting transactions based on Date Range	if (trans.TransactionDate.Date >= startDate.Date && trans.TransactionDate.Date <= endDate.Date)\n{\n   // do stuff\n}	0
34224908	34223926	Extract Key Value Pairs from a named Collection MVC	for (var i = 0; i < pa.Length; i+=2)\n{\n    payment.Pay = Convert.ToDecimal(pa[i]);                 \n    payment.PayCatId = Convert.ToInt32(pa[i+1]);\n    payment.PayDate = DateTime.Now;\n    db.Payments.Add(payment);\n    db.SaveChanges();\n }	0
20242189	20242035	MediaTypeFormatter serialize enum string values in web api	using Newtonsoft.Json;\n\nprotected void Application_Start()\n{\n   SerializeSettings(GlobalConfiguration.Configuration);\n\n}\n\nvoid SerializeSettings(HttpConfiguration config)\n{\n   JsonSerializerSettings jsonSetting = new JsonSerializerSettings();\n   jsonSetting.Converters.Add(new Converters.StringEnumConverter());\n   config.Formatters.JsonFormatter.SerializerSettings = jsonSetting;\n}	0
370248	370113	Show messagebox over Save dialog in C#	// lead-up code\n\nSaveFileDialog sft = new SaveFileDialog();\nBOOL bDone;\ndo\n{\n  if (DialogResult.OK == sft.ShowDialog())\n    bDone = true;\n  else\n  {\n    DialogResult result = MessageBox.Show("Are you sure you don't want to save the changed file?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\n    bDone = (result == Yes) ? true : false;\n  }\n} while (!bDone);\n\n// carry on	0
4098656	4098618	Dynamic where in LINQ	string paramTitle = "hello";\nvar q =\n    (from vr in Util.db.ValuationsRequests\n     where vr.dtSubmitted != null \n       && ( paramTitle == "" || vr.paramTitle == paramTitle)\n     select vr\n     ).AsEnumerable<ValuationsRequest>();	0
14300517	14297072	How to insert into my sql table in wpf using Dataset	northwindDataSet1.Customers.Rows.Add(newCustomersRow);	0
103668	102213	Repository Pattern Implementation Experience	public class Home {\n  public static IRepository<T> For<T> {\n    get {\n      return Container.Resolve<IRepository<T>>();\n    }\n  }\n}	0
21287755	21287670	On each grid update the dropdownlist on the page appends an additional list of items	if(!IsPostBack){...}	0
1677499	1677488	C# Search and Set Node Values	string yourstring = "01/01/2010";\n\nXmlNodeList allNodes = doc.SelectNodes("/Lessons/Lesson[Date='" + yourstring + "']");	0
1421182	1421166	C# get window handle after starting a process	Process.MainWindowHandle	0
11429106	11428979	Post to facebook wall using c# sdk	var app = new FacebookApp(ACCESSTOKEN);\n        var args = new Dictionary<string, object>();\n        args.Add("message", "Hello you");\n\n        app.Api("/[Friend Id]/feed", args, HttpMethod.Post);	0
8616696	8606163	How to set SharePoint "Author" in silverlight client object model?	listItem["Author"] = 8;\n listItem["Editor"] = 11;	0
11718630	11717853	Percentage using label	private void plusButton_Click(object sender, RoutedEventArgs e)\n{\n    if(percentLength.Height < 100)\n        percentLength.Height = percentLength.Height + 10;\n}\n\nprivate void minusButton_Click(object sender, RoutedEventArgs e)\n{\n    if (percentLength.Height > 0)\n        percentLength.Height = percentLength.Height - 10;\n}\n\nprotected void percentLength_HeightChanged(object sender, EventArgs e)\n{\n    percentLength.Content = percentLength.Height + "%";\n}	0
3968781	3968179	Compare RGB colors in c#	Delta-E	0
16458453	16458412	Select into List<int> from grouped objects	var list = machinesVisited.GroupBy(x=> x.McID).Select(g=>g.Key).ToList();	0
20546812	20528785	How to properly return error message from Console to SQL Server Agent	static int Main(string[] args)\n{\n    try\n    {\n        var x = 0;\n        var y = 1 / x;\n    }\n    catch (Exception ex)\n    {\n        Console.Error.WriteLine(ex);\n        return 1;\n    }\n\n    return 0;\n}	0
2383175	2377429	on button click the visibility of a column in listview should set to false	MyDataModel model = this.objectListView.SelectedModel as MyDataModel;\nif (model != null) {\n    DoSomething(model.FilePath);\n}	0
3554211	3554189	Can we have a body for a default constructor in C# during runtime?	class With<T>\n{\n  T field;\n  string str;\n  With()\n  {\n    field = default(T);\n    str = "";\n  }\n}\n\nclass WithOut<T>\n{\n  T field;\n  string str = "";\n}	0
2362171	2362153	How do I split a string in C# based on letters and numbers	var match = Regex.Match(yourString, "(\w+)(\d+)");\nvar month = match.Groups[0].Value;\nvar day = int.Parse(match.Groups[1].Value);	0
17910374	17910285	How do I send an Image to a web services that takes Stream.IO from iOS?	NSData *imageData = UIImageJPEGRepresentation(image, 1.0);\nNSString *encodedString = [imageData base64Encoding];	0
19192408	19148049	How do I make a custom vertical axis?	let PX = GetPlayerX; //Gets your X\n    let MX = GetClipMaxX; // Gets the max X can be (complete right)\n    let MMX = GetClipMinX; // Gets the min X can be (complete left)\n    let agr = MMX + PX; // Agr = PX in this case\n    let mir = MX - PX; // Takes distance from minX and subtracts it from maxX	0
6451845	6451584	Login verification in asp.net	protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)\n{\n    e.Authenticated = new webservicename().Validate(Login1.UserName, Login1.Password);\n}	0
18390129	18388366	How to Deploy C# .net application with MongoDB	msbuild.exe [your app with necessary options]\nC:/mongodb/bin/mongod.exe [options]	0
27198918	27131425	Check if data reader has rows?	protected void btnNew_Click(object sender, EventArgs e)\n    {\n        Clear();\n        SqlCommand command = conn.CreateCommand();\n        try\n        {\n            command.CommandText = "GetMax";\n            command.CommandType = CommandType.StoredProcedure;\n            conn.Open();\n\n            object cMax = command.ExecuteScalar();\n            if (cMax != DBNull.Value)\n            {\n                int CustMax = (int)cMax;\n                CustMax++;\n                txtCustID.Text = CustMax.ToString();\n            }\n            else\n            {\n                txtCustID.Text = "1";\n            }\n\n        }\n        catch (SqlException)\n        {\n            lblMessage.Text = "Cannot connect to database";\n        }\n        catch (Exception ex)\n        {\n            lblMessage.Text = ex.Message;\n        }\n        finally\n        {\n            command.Dispose();\n            conn.Dispose();\n        }\n    }	0
18026037	18025424	C# OpenXML (Word) Table AutoFit to Window	Table table = ...\n\nTableWidth width = table.GetDescendents<TableWidth>().First();\nwidth.Width = "5000";\nwidth.Type = TableWidthUnitValues.Pct;	0
15275300	15275251	how save array in list by value not reference in C#	List<int[]> lisarr = new List<int[]>();\nint[] a=new int[1];\na[0]=1;\nlisarr.Add(a.ToArray());\na[0]=10;	0
7783394	7781010	Need help refactoring a LINQ statement with a Group By clause?	var query1 = (from p in Cache.Model.Products\n                     join sc in Cache.Model.ShishaCombinations on p.ProductID equals sc.ProductID\n                     where sc.NumberOfMixes == mixes\n                     select new { p.ProductID, p.Name }).Distinct();	0
16900226	12643866	Generate a .Net ticks in Oracle	CREATE OR REPLACE FUNCTION GLOBAL.Get_DotNet_Ticks\n(\n       inTimestamp IN TIMESTAMP\n) RETURN NUMBER AS\n-- **********************************************************************************\n-- File name:         Get_DotNet_Ticks\n-- Original Author:   Roberto Lopes\n-- Creation Date:     October 2012\n-- Description:       Returns the number of ticks for the provided timestamp, based\n--                    on the Microsoft .Net algorithm\n-- **********************************************************************************\nBeginDate TIMESTAMP := TO_TIMESTAMP('0001-01-03', 'YYYY-MM-DD'); --.Net Ticks are counted starting from this date\nBEGIN\n    RETURN (EXTRACT(DAY FROM(inTimestamp - BeginDate)) * 86400000 + (TO_NUMBER(TO_CHAR(inTimestamp, 'SSSSSFF3'))))*10000;\nEND Get_DotNet_Ticks;	0
25278877	25278633	C# How To Update Access Table From Excel?	...    \n\ncmd.CommandText = "UPDATE [MS Access;Database=" + Access + "].[person] set vahedH=?,Bprice=?, Qest=?,mande=?,Date=? WHERE pcode=? SELECT * FROM [result$]";\n...	0
4337303	4336976	C# - Control another application's windows using Thoughtworks White	Application.Attach()	0
8784742	8784227	Cached entities making round trip to database	context.Detach(entity);\ncachedItems.Add(entity);	0
22276451	9666910	Semi Transparent PNG as Splash Screen	bool painted = false\n    protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs e)\n    {\n        if (painted) return;\n        e.Graphics.DrawImage(BackgroundImage, new System.Drawing.Point(0, 0));\n        painted = true;\n    }	0
1137880	1137763	Accessing Excel Custom Document Properties programatically	object properties = workBk.GetType().InvokeMember("CustomDocumentProperties", BindingFlags.Default | BindingFlags.GetProperty, null, workBk, null);\n\nobject property = properties.GetType().InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null, properties, new object[] { propertyIndex });\n\nobject propertyValue = property.GetType().InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty, null, propertyWrapper.Object, null);	0
33282836	33277117	How to make sure I have a "blank" request for home page in mvc	public ActionResult Index(int someValue, string someText)\n{\nreturn View();\n}	0
1519542	1519530	Using reflection to find interfaces implemented	Type.IsAssignableFrom	0
5705721	5705503	Calling a C# opeartion with 'Out' from a managed C++ code	WSHttpBinding ^ binding1 = gcnew WSHttpBinding(); \nEndpointAddress ^ address1 = gcnew EndpointAddress(gcnew String ("http://usatondevlas1.na.praxair.com/Build15/ResourceCenterSVC/ResourceCenter.svc"));\nHelloServiceClient::ServiceReference2::ResourceCenterServiceContractClient ^ client = gcnew HelloServiceClient::ServiceReference2::ResourceCenterServiceContractClient(binding1,address1);\nHelloServiceClient::ServiceReference2::ErrorWarningData ^ objEWData = gcnew HelloServiceClient::ServiceReference2::ErrorWarningsData;\nclient->DoWork("4278779", objEWData);	0
28319007	28318284	Add a button on my winform to run the Snipping Tool application	Process snippingToolProcess = new Process();\n        snippingToolProcess.EnableRaisingEvents = true;\n        if (!Environment.Is64BitProcess)\n        {\n            snippingToolProcess.StartInfo.FileName = "C:\\Windows\\sysnative\\SnippingTool.exe";\n            snippingToolProcess.Start(); \n        }\n        else\n        {\n            snippingToolProcess.StartInfo.FileName = "C:\\Windows\\system32\\SnippingTool.exe";\n            snippingToolProcess.Start();            \n        }	0
8420629	8341272	How to bind crystal report to manually created DataSet	Invoice invoice = new Invoice(); // instance of my rpt file\n                var ds = new DsBilling();  // DsBilling is mine XSD\n                var table2 = ds.Vendor;\n                var adapter2 = new VendorTableAdapter();\n                adapter2.Fill(table2);\n\n\n                var table = ds.Bill;\n                var adapter = new BillTableAdapter();\n                string name = cboCustReport.Text;\n                int month = int.Parse(cboRptFromMonth.SelectedItem.ToString());\n                int year = int.Parse(cboReportFromYear.SelectedItem.ToString());\n                adapter.Fill(table, name,month,year);\n\n                ds.AcceptChanges();\n\n                invoice.SetDataSource(ds);\n                crystalReportViewer1.ReportSource = invoice;\n                crystalReportViewer1.RefreshReport();	0
18675042	18674961	Close winform but keep running in task bar	void myForm_FormClosing(object sender, FormClosingEventArgs e)\n{\n    e.Cancel = true;\n    this.Hide();\n}	0
6692504	6692392	The URL/Endpoint Address of a running WCF service	OperationContext.Current.EndpointDispatcher.EndpointAddress	0
5550323	5550112	how to check the a particular application is install or not in a machine using c#	static void GetInstalled()\n{\n      string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";\n      using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))\n      {\n            foreach (string skName in rk.GetSubKeyNames())\n            {\n                  using (RegistryKey sk = rk.OpenSubKey(skName))\n                  {\n                        Console.WriteLine(sk.GetValue("DisplayName"));\n                  }\n            }\n      }\n}	0
10026022	10025888	WPF Add a png image from resources with C# at runtime	object imguri = new Uri("/MyAssembly;Component/MyImageFolder/MyImage.png", UriKind.Relative);\nBitmapImage ni = new BitmapImage(imguri);\nImage img = new Image();\nimg.Source = ni;\nreturn img;	0
13663410	13662275	How to click a button on website via c# on wp7	wb1.InvokeScript("eval", "document.forms[0].submit();");	0
6415486	6415352	TextBox validation in Windows Forms	private void TextBox5_Validating(object sender, System.EventArgs e)\n{\n    String AllowedChars = @"^a-zA-Z0-9.$";\n    if(Regex.IsMatch(TextBox5.Text, AllowedChars))\n    {\n         e.Handled = true;\n    }\n    else\n    {\n         e.Handled = false;\n    }\n}	0
14541239	14541202	Regex to replace every newline	Regex regex_newline = new Regex("(\r\n|\r|\n)");   // remove the '+'\n // :\n regex_newline.replace(somestring, "X");	0
13121977	13121709	Format Double - show zero or two decimals	Console.WriteLine((d % 1) == 0 ? "{0:F0}" : "{0:F2}", d);	0
19429918	19390176	Hide zero values with StringFormat	{0:#\\%;0:#;#}	0
34507823	34507400	ObservableCollection items - modify property of individual items if a flag is set	private bool _isPostRequest;\n    public bool IsPostRequest\n    {\n        get { return _isPostRequest; }\n        set\n        {\n            _isPostRequest = value;\n            Parameters.ToList().ForEach(x => x.IsPostParameter = value);\n            RaisePropertyChanged("IsPostRequest");\n        }    \n    }	0
24598572	24598461	syntax error in from clause C# and Access	using(OleDbConnection conn = new OleDbConnection(a correct connection string here))\nusing(OleDbCommand cmd = new OleDbCommand(@"select * from Employee \n                                            where username = ? AND [Password] = ?", conn);\n{\n\n    conn.Open();\n    cmd.Parameters.AddWithValue("@p1", this.tbUsername.Text);\n    cmd.Parameters.AddWithValue("@p2", this.tbPassword.Text);\n    using(OleDbDataReader dr = cmd.ExecuteReader())\n    {\n       .....\n    }\n}	0
1281428	1281102	Reading a ASN.1 DER-encoded RSA Public key	0 30  159: SEQUENCE {\n   3 30   13:   SEQUENCE {\n   5 06    9:     OBJECT IDENTIFIER '1 2 840 113549 1 1 1'\n  16 05    0:     NULL\n            :     }\n  18 03  141:   BIT STRING 0 unused bits, encapsulates {\n  22 30  137:       SEQUENCE {\n  25 02  129:         INTEGER\n            :           00 EB 11 E7 B4 46 2E 09 BB 3F 90 7E 25 98 BA 2F\n            :           C4 F5 41 92 5D AB BF D8 FF 0B 8E 74 C3 F1 5E 14\n            :           9E 7F B6 14 06 55 18 4D E4 2F 6D DB CD EA 14 2D\n            :           8B F8 3D E9 5E 07 78 1F 98 98 83 24 E2 94 DC DB\n            :           39 2F 82 89 01 45 07 8C 5C 03 79 BB 74 34 FF AC\n            :           04 AD 15 29 E4 C0 4C BD 98 AF F4 B7 6D 3F F1 87\n            :           2F B5 C6 D8 F8 46 47 55 ED F5 71 4E 7E 7A 2D BE\n            :           2E 75 49 F0 BB 12 B8 57 96 F9 3D D3 8A 8F FF 97\n            :           73\n 157 02    3:         INTEGER 65537\n            :         }\n            :       }\n            :   }	0
4502185	4501691	include in actionscript 3	include "myasfile.as"	0
12940649	12940545	Find process started with arguments	var processName = "MyApplication";\nstring wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", processName);\nManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);\nManagementObjectCollection retObjectCollection = searcher.Get();\nforeach (ManagementObject retObject in retObjectCollection)\n{\n    if (retObject["CommandLine"].Equals("-record"))\n    {\n        //... do something ...\n    }   \n}	0
23893538	23892952	Prevent duplication in ListView?	private void AddToListBtn_Click(object sender, EventArgs e)\n    {\n         string itemTag = HideFolderAddress.Tag.ToString();\n         if (!FolderList.Items.ContainsKey(itemTag ))\n         {\n               ListViewItem itemList = FolderList.Items.Add(itemTag , itemTag , -1);\n               itemList.SubItems.Add(HideFolderAddress.Text);\n         }\n     }	0
2069543	2068923	Validating several linked databound TextBox values in WPF	public decimal SmallerValue\n    {\n        get\n        {\n            return smallerValue;\n        }\n        set\n        {\n            bool fireForBigger = smallerValue > biggerValue && smallerValue < value;\n            smallerValue = value;\n            OnPropertyChanged("SmallerValue");\n            if (fireForBigger)\n            {\n                OnPropertyChanged("BiggerValue");\n            }\n        }\n    }	0
14339824	14339625	Checking, if all enum values were processed	[ExpectedException(typeof(InvalidArgumentException))]\n[Test]\nvoid SomeTestMethod()\n{\n    Direction testValue = (Direction)-1;\n    Assert.IsFalse(Enum.IsDefined(typeof(Direction), testValue));\n    SomeFunction((Direction)-1);\n}	0
23723348	23723318	How to update ListBox from TextChanged event	public void UpdateNamesList(string _searchTerm)\n{\n    IEnumerable<string> names = MethodCallToGetStrings()\n        .Where(x => x.Name.Contains(_searchTerm))\n        .Select(x => x.Name);\n\n    NamesList.Clear();\n    foreach(name in names) \n    {\n       NamesList.Add(name);\n    }\n}	0
10679858	10679838	How to set value of WPF ComboBox Item from C# Code	item.Tag = fx.FunctionValue;	0
1499370	1499354	Find windows folder programatically in c#	Environment.GetEnvironmentVariable("SystemRoot")\n\nEnvironment.GetEnvironmentVariable("windir")	0
1152910	1152887	Can you reverse order a string in one line with LINQ or a LAMBDA expression	new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())	0
10633932	10633805	Continuously Insert Data to Database through asmx Web Service	[WebMethod]\npublic void Insert(int a)\n{\n        string query = "INSERT INTO result (A) VALUES('" + a + "')";          \n        YourClass obj = new YourClass();\n        //Open connection here\n        if (obj.OpenConnection())\n        {\n            MySqlCommand cmd = new MySqlCommand(query, connection);   \n            cmd.ExecuteNonQuery();       \n            this.CloseConnection();\n        }\n        else\n            throw new Exception("Problem in opening connection");\n}	0
4714755	4714596	returning multiple fields back from a Linq lambda	return db.Approved.Where(predicate).Select(x =>new Approved{x.RefNo, x.RefGroup, x.Location });	0
3015118	3007780	iTextSharp - how to open/read/extract a file attachment?	Process.Start("./pdftk", "contains_attachments.pdf unpack_files output \"C:\\output_directory\"")	0
3042493	3042479	how to read strings using c#	string input = "QuoteNo:32586/CustomerNo:ABCDEF/TotalAmount:32/Processed:No";\n\nvar query = from pair in input.Split('/')\n            let items = pair.Split(':')\n            select new\n            {\n                Part = items[0],\n                Value = items[1]\n            };\n\n // turn into list and access by index \nvar list = query.ToList();\n\n// or turn into dictionary and access by key\nDictionary<string, string> dictionary \n    = query.ToDictionary(item => item.Part, item => item.Value);	0
17610043	17609717	Update multiple rows in SQL Server with IN clause	DECLARE @userIds NVARCHAR(MAX)\nSET @userIds ='1,2,3,4,5,6'\n\nCREATE table #TempUser \n(\n    userId Int\n) \nDECLARE @SplitOn VARCHAR(1)\nSET @SplitOn = ','\n\nWhile (Charindex(@SplitOn,@userIds)>0)\nBegin\n    Insert Into #TempUser (userId)\n    Select \n        userId = ltrim(rtrim(Substring(@userIds ,1,Charindex(@SplitOn,@userIds )-1)))\n    Set @userIds = Substring(@userIds,Charindex(@SplitOn,@userIds)+1,len(@userIds))\nEnd\n\nInsert Into #TempUser (userId)\nSelect Data = ltrim(rtrim(@userIds))\n\nSELECT * FROM #TempUser	0
7111507	7111258	How to get variables from .ascx in another .ascx?	protected void Page_Load(object sender, EventArgs e)\n{\n  ParentControl page = (ParentControl)this.Parent;\n\n  if(page != null)  \n    string newVariable = page.GetFunction();\n}	0
30397060	30392629	Retrieve File From Sharepoint Library Using C#	CamlQuery qry = new CamlQuery();\n        qry.ViewXml = "<View></View>";\n        qry.FolderServerRelativeUrl = "/001/API/Asset Optimisation Interface/Asset Technical Data/";	0
22155060	22154978	Already an open DataReader with this connection	using (MySqlConnection conn = new MySqlConnection(connectionString))\n{\n//Your code\n}\n\nusing (MySqlConnection readConn = new MySqlConnection(connectionString))\n{\n//Your code\n}	0
18090972	17934848	How to get the Cell Position of a TableLayoutPanel for a radioButton	private void radio_CheckedChanged(object sender, EventArgs e)\n{\n        var radio = sender as RadioButton;\n        var row = tblPanel.GetRow(radio.Parent);\n}	0
31539973	31539656	c# iterate through json	Track jsonObject = JsonConvert.DeserializeObject<Track >(json);	0
17709775	17709729	How to get the object name of a changed checkbox-item?	CheckBox c = sender as CheckBox;\nMessageBox.Show(c.Name);	0
2325480	2325453	get the integer between the dates	DateTime dt = DateTime.Parse("12/6/2010");\nint i = dt.Day;	0
32415209	32415161	How to extract words from structured string?	var m = "select Car (door, wheel, antenna)";\nRegex r = new Regex(@"select\s+(.*)\s+\((.*)\)");\nvar model = r.Match(m).Groups[1].Value;\n// untrimmmed:\n// var fields = r.Match(m).Groups[2].Value.Split(',');\n// trimmed:\nvar fields = r.Match(m).Groups[2].Value.Split(',').Select(s => s.Trim()).ToArray();	0
14988576	14987958	Store file in SQL Server database using .Net MVC3 with Entity Framework	// model\npublic class UploadedImage\n{\n    public int UploadedImageID { get; set; }\n    public string ContentType { get; set; }\n    public byte[] File { get; set; }\n}\n\n// controller\npublic ActionResult Create()\n{\n    HttpPostedFileBase file = Request.Files["ImageFile"];\n\n    if (file.ContentLength != 0)\n    {\n        UploadedImage img = new UploadedImage();\n        img.ContentType = file.ContentType;\n        img.File = new byte[file.ContentLength];\n\n        file.InputStream.Read(img.File, 0, file.ContentLength);\n\n        db.UploadedImages.Add(img);\n        db.SaveChanges();\n    }\n\n    return View();\n}\n\nActionResult Show(int id) \n{\n    var image = db.UploadedImages.Find(id);\n    if (image != null)\n    {\n        return File(image.File, image.ContentType, "filename goes here");\n    }\n}	0
31814238	31814130	Play Sounds in a Visual Studio Application	System.Media.SoundPlayer player = \n new System.Media.SoundPlayer();\n player.SoundLocation = @"C:\Users\Public\Music\Sample Music\xxxx.wav";\n player.Load();\n player.Play();	0
19602486	19601477	Is it possible to have a critical region based off a condition?	static ConcurrentDictionary<string, object> _locksByUser = new ConcurrentDictionary<string, object>();\n\npublic void Save(string userId) {\n   var lock = _locksByUser.GetOrAdd(userId, new object());\n   if (Monitor.TryEnter(lock)) {\n       try {\n       //do save here\n       }\n       finally {\n           Monitor.Exit(lock);\n       }\n   }\n}	0
26674666	26674601	ASP.NET visible=true doesn?t show buttons	protected void Page_Load(object sender, EventArgs e)\n{\n          switch(MasterPage.hatRolle)\n    {\n        case 0: b_home.Visible = true;\n                b_kontakte.Visible = true;\n                b_profil.Visible = true;\n                b_reservieren.Visible = true;\n                b_verleihhistorie.Visible = true;\n                b_warenausgang.Visible = true;\n                b_wareneingang.Visible = true;\n                b_neueKunden.Visible = true;\n                break;\n\n        //case 1: .....\n        //...........\n    }\n}	0
26522072	26521886	How can you trimend of textbox text from another textbox text	If (textbox2.Text.EndsWith(textbox1.Text))\n    textbox2.Text = textbox2.Text.Substring(0, textbox2.Text.Length - textbox1.Text.Length);	0
4138196	4137855	Creating child nodes for a DynamicNode in MvcSiteMapProvider that have dynamic parameters	public override string Url\n    {\n        get\n        {\n            if (!string.IsNullOrEmpty(this.url))\n                return this.url;\n\n            RequestContext ctx;\n            if (HttpContext.Current.Handler is MvcHandler)\n                ctx = ((MvcHandler)HttpContext.Current.Handler).RequestContext;\n            else\n                ctx = new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData());\n\n            var routeValues = new RouteValueDictionary(RouteValues);\n\n            foreach (var key in DynamicParameters)\n                routeValues.Add(key, ctx.RouteData.Values[key]);\n\n            return new UrlHelper(ctx).Action(Action, Controller, routeValues);\n        }\n        set\n        {\n            this.url = value;\n        }\n    }	0
32488252	32485768	How to replace list value with another value c#	for (int x = 0; x < ms.Count; x++)\n        {\n            if (xl[x] != "")\n            {\n                continue;\n            }\n            else if (xl[x] == "")\n            {\n                for (int y = 0; y<xl.Count; y++)\n                {\n                    if (ms[y] == ms[x])\n                    {\n                        xl[x] = xl[y];\n                        break;\n                    }\n                }\n                continue;\n            }\n        }	0
5164321	5163854	HOW TO MAKE asynchonous call to WCF a synchonous one	public AllViewModel()\n{\n    var task = Task<List<Settings>>.Factory.StartNew(() =>\n                     client.SupplierListWithSettings((s,e) => \n                     {\n                         if (e.Error == null && e.Result != null)\n                         {\n                             var list = new List<Settings>(); \n                             foreach (VCareSupplierDto obj in e.Result)\n                             {\n                                 list.Add(obj);\n                             }\n                             task.SetResult(list);\n                         }\n                     }));\n    this.SettingsList = task.Result;\n}	0
2314798	2314758	Parsing xml with XDocument and XPath	XNamespace ns = "http://pria.org";\nvar affidavits = xDocument.Descendants(ns + "AFFIDAVIT");	0
18735702	13825495	Entity Framework - printing EntityValidationErrors to log	catch (System.Data.Entity.Validation.DbEntityValidationException ex)\n            {\n                Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));\n                throw;\n            }	0
16820545	16820525	How can i check if listbox is connected to a datasource?	if (listbox1.DataSource != null)	0
10740663	10732870	How to pass in a lambda and have access to a particular set of methods	public static class MyStaticClass{\n     public static void MakeCall(Action<Cmds> paramater){\n           Helper(new Cmds(), parameter);\n      }\n\n      private static void Helper(this Cmds, Action<Cmds> invokeThis) {...}\n\n     public static void MakeCallTwo<???>( ??????)\n }	0
2053809	2053724	How to debug with external program launched from .bat not an .exe in VS2005?	' Lifted from Samples.vsmacros '\n' VSDebugger.AttachToCalc '\nSub AttachToCalc()\n    Dim attached As Boolean = False\n    Dim proc As EnvDTE.Process\n\n    For Each proc In DTE.Debugger.LocalProcesses\n        If (Right(proc.Name, 8) = "calc.exe") Then\n            proc.Attach()\n            attached = True\n            Exit For\n        End If\n    Next\n\n    If attached = False Then\n        MsgBox("calc.exe is not running")\n    End If\n\nEnd Sub	0
9600490	9600453	Command line arguments in C# application	class App : Application\n{\n    //Add this method override\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        //e.Args is the string[] of command line argruments\n    }\n}	0
25115336	25115145	How to redirect all pages in my mvc asp.net web app except for one role?	[CheckUserRole]\n  public class YourController : Controller\n  {\n    public ActionResult YourAction()\n    {\n\n    }\n  }\n\n public class CheckUserRoleAttribute : ActionFilterAttribute\n {\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n       // Get the User Id from the session\n       // Get Role associated with the user (probably from database)\n       // Get the permission associated with the role (like Read, write etc)\n\n       // if user is not authenticated then do as :\n\n         filterContext.Result = new RedirectToRouteResult(new\n         RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));\n    }\n }	0
25024899	25024817	Completing a linq to entites query of a tri-level entity source	var entity = context.AspNetUsers.Include(P => P.RegisteredVehicles\n            .Select(P => P.MakeSource)).Include(P => P.RegisteredVehicles\n            .Select(P => P.ModelSource)).Include(P => P.RegisteredVehicles\n            .Select(P => P.YearSource));	0
3146990	3146907	How to delete an item from a Dictonary using LINQ in C#	dict.GroupBy(x => x.Value, x => x.Key)\n.Where(x => x.Count() > 1)\n.SelectMany(x => x.Skip(1))\n.ToList().ForEach(x => dict.Remove(x))	0
15114847	15114668	the code used for list box control , i like to use for gridview	bool isDuplicate = false;\n\nfor (int i = 0; i < count; i++)\n{\n    if (GridViewEfile.Rows[i].Cells[1].Text == FileName)\n    {\n         Label2.Text = "File already in the list";\n         isDuplicate = true;\n         break;\n    }\n}\n\nfor (int j = 0; j < count; j++)\n{\n     dr = dt.NewRow();\n     dr["File Name"] = GridViewEfile.Rows[j].Cells[1].Text;\n     dr["File Size"] = GridViewEfile.Rows[j].Cells[2].Text;\n     dt.Rows.Add(dr);\n}\n\nif (!isDuplicate)\n{\n     if (size == 0)\n     {\n         Label2.Text = "File size cannot be 0";\n     }\n     else\n     {\n         dr = dt.NewRow();\n         dr["File Name"] = FileName;\n         dr["File Size"] = size.ToString() + " KB";\n\n         dt.Rows.Add(dr);\n     }\n}\n\nGridViewEfile.DataSource = dt;\nGridViewEfile.DataBind();	0
1449409	1449391	Linq to SQL - Selecting a new object and performing an update	User curData = dc.Users.Where(? => (?.Login == username) && ?.Active)	0
96240	95850	How to find Commit Charge programmatically?	public static long GetCommitCharge()\n    {\n        var p = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes");\n        return p.RawValue;\n    }	0
7727984	7727873	Retrieve value from GridTemplateColumn in server side (Telerik RadGrid)	var item = rgd_grid.MasterTableView.Items[0] as GridDataItem;\nif (item != null)\n    string text = item["Unique"].Text;	0
14443176	14443131	How can I write MemoryStream to byte[]	byte[] bytes = fs.ToArray();	0
1254277	1254237	COnvert a datetime From GMT to other(Eastern,Mountain,Pacific,Indian,..) formats	TimeZoneInfo mountain = TimeZoneInfo.FindSystemTimeZoneById(\n    "US Mountain Standard Time");\nDateTime utc = DateTime.UtcNow;\nDateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, mountain);	0
2828368	2828276	foreach Control ctrl in SomePanel.Controls does not get all controls	public IEnumerable<Control> GetAllControls(Control root) {\n  foreach (Control control in root.Controls) {\n    foreach (Control child in GetAllControls(control)) {\n      yield return child;\n    }\n  }\n  yield return root;\n}	0
1527515	1527483	Reflection help. Make a collection from a class based on its properties?	List<SimpleAddress> addresses = new List<SimpleAddress>();\n\nstring addressPropertyPattern = "Address{0}";\nstring namePropertyPattern = "Address{0}Name";\nstring descPropertyPattern = "Address{0}Desc";\n\nfor(int i = 1; i <= MAX_ADDRESS_NUMBER; i++)\n{\n    System.Reflection.PropertyInfo addressProperty = typeof(AddressList).GetProperty(string.Format(addressPropertyPattern, i));\n    System.Reflection.PropertyInfo nameProperty = typeof(AddressList).GetProperty(string.Format(namePropertyPattern, i));\n    System.Reflection.PropertyInfo descProperty = typeof(AddressList).GetProperty(string.Format(descPropertyPattern, i));\n\n    SimpleAddress address = new SimpleAddress();\n\n    address.Address = (string)addressProperty.GetValue(yourAddressListObject, null);\n    address.Name = (string)nameProperty.GetValue(yourAddressListObject, null);\n    address.Description = (string)descProperty.GetValue(yourAddressListObject, null);\n\n    addresses.Add(address);\n}	0
22245756	22245569	Instance validation error: * is not a valid value for *	[XmlIgnore]\npublic MyEnum EnumValueReal\n{\n    get { return _myEnum; }\n    set { _myEnum = value; }\n}\n\npublic string EnumValue\n{\n     get\n     {\n         return EnumValueReal.ToString();\n     }\n\n     set\n     {\n         MyEnum result = MyEnum.Unknown;\n         Enum.TryParse(value, true, out result);\n\n         EnumValueReal = result;\n     }\n}	0
33938026	33937700	How to show and hide property key and value based on condition in c#	private static List<dynamic> callingprogram2(List<Item> paramss)\n    {\n        dynamic newList = new List<dynamic>();\n        foreach (var item in paramss)\n        {\n            dynamic dObject = new ExpandoObject();\n            dObject.a = item.a;\n            dObject.b = item.b;\n            if (item.c != 0.0)\n            {\n                dObject.c = item.c;\n            }\n            newList.Add(dObject);\n        }\n\n        return newList;\n    }	0
23247692	23247403	Circular relation one to many	using(var db = new studytree_dbEntities())\n{\n\n    Student s = db.Students\n        .Where(s => s.StudentId == id)\n        .ToList()\n        .Select(s => new Student {\n            FirstName = s.FirstName,\n            LastName = s.LastName,\n            Sessions = s.Sessions.Select(session => new Session {\n                Tutors = session.Tutors\n            }),\n        })\n        .FirstOrDefault();\n    return s;\n}	0
2251328	2251317	Is it possible to pass in more than one generically typed parameter to a method?	public virtual void SetupGrid<T, T2>() \n    where T : class, new()\n    where T2 : class, new()	0
22904041	22903826	Replace with regex/wildcard	for (int i = 0; i < 600; i++)\n{\n    const string original = "href=\"me.get?site.sectionshow&page;"\n    const string replace = "/pages/page";\n    Regex reg = new Regex(original + i.ToString("D3"), RegexOptions.IgnoreCase);\n    reg.Replace(updatedContent, replace + i.ToString("D3") + ".aspx")\n}	0
10813472	10813412	How to cast an 'int' to a 'char' in C#?	StringBuilder onlyNumber = new StringBuilder();\nforeach (char onlyNum in puzzleData)\n{\n    if (Char.IsDigit(onlyNum))\n    {\n        onlyNumber.Append(onlyNum);\n    }\n}	0
7285193	7284575	Getting value from a DataSet into a variable	// Create a table \nDataTable table = new DataTable("users");\ntable.Columns.Add(new DataColumn("Id", typeof(int)));\ntable.Columns.Add(new DataColumn("Name", typeof(string)));\n\ntable.Rows.Add(1, "abc");\ntable.Rows.Add(2, "ddd");\ntable.Rows.Add(3, "fff");\ntable.Rows.Add(4, "hhh d");\ntable.Rows.Add(5, "hkf ds");\n\n// Search for given id e.g here 1\n\nDataRow[] result = table.Select("Id = 1"); // this will return one row for above data \nforeach (DataRow row in result)\n{\n    Console.WriteLine("{0}, {1}", row[0], row[1]);\n}	0
6178551	6176084	How to specify Publish Version in Devenv?	[assembly: AssemblyInformationalVersion("1.2.3.4")]	0
10028387	10028166	How to data bind to a HTML selectbox	securityQuestion1.DataSource = ds.Tables["WEB_SEL_SECURITY_QUESTIONS"];\nsecurityQuestion1.DataTextField = "QUESTION";\nsecurityQuestion1.DataValueField = "KEYCODE"; // Or whatever the value field needs to be.\nsecurityQuestion1.DataBind();	0
23506148	23506024	String pattern find character	ID: (?<id>\d*) NAME: (?<buffer>.*?:) (?<name>.*)	0
33977712	33975143	video encryption using aes	FileInfo info = new FileInfo(@"D:\SomeMovie.avi");\nint bytesToRead = 128 * 1024 * 1024; // 128MB \n\nbyte[] buffer = new byte[bytesToRead]; // create the array that will be used encrypted\nlong fileOffset = 0;\nint read = 0;\nbool allRead = false;\n\nwhile (!allRead)\n{\n    using (FileStream fs = new FileStream(info.FullName, FileMode.Open, FileAccess.Read))\n    {\n        fs.Seek(fileOffset, SeekOrigin.Begin); // continue reading from where we were...\n        read = fs.Read(buffer, 0, bytesToRead); // read the next chunk\n    }\n\n    if (read == 0)\n        allRead = true;\n    else\n        fileOffset += read;\n\n    // encrypt the stuff, do what you need...\n}	0
11401723	11401473	Dynamically modify column DataGrid	class MDRResult : DataGrid\n{\n    public MDRResult(string[] headers, string[][] fields)\n        : base()\n    {\n        for (int i = 0; i < headers.Length; ++i)\n            this.Columns.Add(new DataGridTextColumn()\n            {\n                Header = headers[i],\n                Binding = new Binding("[" + i + "]")\n            });\n        this.AutoGenerateColumns = false;\n        this.ItemsSource = fields;\n    }\n}	0
16777990	16777960	Get last non-empty cell in Excel column	sh = app.Workbooks.get_Item("Workbook1.xlsx").Worksheets.get_Item("Sheet1");\nfullRow = sh.Rows.Count;\nlastRow = sh.Cells[fullRow, 1].get_End(Excel.XlDirection.xlUp).Row; //use get_End instead of End	0
5436817	5436747	Facebook C# Api: Get comment and like data from a post	dynamic stream = fbc.Query("select post_id from stream where permalink  = 'http://www.facebook.com/TeapotParty/posts/134801493258490'");"select post_id from stream where permalink  = 'http://www.facebook.com/TeapotParty/posts/134801493258490'");	0
12987318	12987304	Showing image in Radgrid using datatable	DataTable dt = new DataTable();\ndt.Columns.Add("Image Column");\ndt.Rows.Add("<img src= ../image/image.png   />");\nRadGrid1.DataSource = dt;	0
8104648	8097403	PersistChildren Custom Control	Control control = ControlHelper.GetControlById(mobilePage, "testLabel");\n        if (control is Label)\n        {\n            Label testTekst = control as Label;\n            testTekst.Text = "This is the tekst that comes in the label";\n        }	0
8127504	8127430	LINQ to Objects Join two collections to set values in the first collection	var joinedData = from m in mapped \n                 join r in reasons on m.Id equals r.Id \n                 select new { m, r };\n\nforeach (var item in joinedData)\n{\n    item.m.Reason = item.r.Reason;\n}	0
33522059	33521845	Testing for an SDK in Universal Windows App	if (ApiInformation.IsTypePresent("Windows.Phone.Devices.Notification.VibrationDevice"))\n{\n    ...	0
19755813	19755700	Changing Font Color RTF	richTextBox1.Clear();\n        foreach (Color b in new ColorConverter().GetStandardValues())\n        {\n            richTextBox1.SelectionStart = richTextBox1.TextLength;\n            richTextBox1.SelectionColor = b;\n            richTextBox1.SelectedText = b.ToString() + "\r\n";\n            button1.BackColor = b;\n            Application.DoEvents();\n            Thread.Sleep(10);\n        }	0
18890561	18890232	How to find the strings between $ and /$ using Regex	Regex r = new Regex(Regex.Escape("-$") + "(.*?)"  + Regex.Escape(@"/$"));\n                MatchCollection matches = r.Matches("ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH");\n            foreach (Match match in matches)\n            {\n                Console.WriteLine(match.Groups[1].Value);\n            }	0
28974084	28973663	Converting this list of objects to json using LINQ	class Output\n{\n    public string Name { get; set; }\n    public int[] DupTrans { get; set; }\n}\n\nclass UsageData\n{\n    public string UsageType { get; set; }\n    public int DupTrans { get; set; }\n    public int UniqTrans { get; set; }\n}\n List<UsageData> usageData = new List<UsageData>()\n        {\n            new UsageData(){UsageType = "FIND", DupTrans  = 190, UniqTrans = 55 },\n            new UsageData(){UsageType = "PARTS", DupTrans  = 107, UniqTrans = 51 }\n        };\n\n        var myObj = new { Name = "Duplicate Transactions", DupTrans = usageData.Select(x => x.DupTrans).ToArray() };\n        string str = JsonConvert.SerializeObject(myObj);	0
25994209	25994068	How to get Method Name passing as argument to function?	public void MyMethod([CallerMemberName]string myCallerName = null)\n{\n  //use myCallerName\n}	0
25629557	25629493	VisualStudio 2012 web project - context start - currently selected HTML page	Properties -> Web -> Start Action	0
4164940	4164356	Edit DataGridView via Designer in inherited UserControl	[Designer(typeof(ControlDesigner))]\npublic class InheritableDataGridView : DataGridView\n{\n    public InheritableDataGridView()\n        : base()\n    { }\n}	0
19135466	19135283	How to get difference sum of between keys in a Dictionary object C#	int total = foo.Keys.Max() - foo.Keys.Min();	0
2265884	2263113	How do i seek with bass?	var thetime = Bass.BASS_ChannelSeconds2Bytes(_stream, doubleInSeconds);\nvar success = Bass.BASS_ChannelSetPosition(_stream, thetime);	0
25844611	25844493	Update row in Entity Framework based on input data	[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Create(Employee employee)\n{\n    if (ModelState.IsValid)\n    {\n        switch (employee.DepartmentName)\n        {\n            case "IT":\n                employee.StatusID = 1\n                break;\n            case "HR":\n                employee.StatusID = 2\n                break;\n            default:\n                employee.StatusID = 1\n                break;\n        }\n\n        db.Employee.Add(employee);\n        db.SaveChanges();\n\n        return RedirectToAction("Index");\n    }\n\n    return View(employee);\n}	0
1769470	1769448	Progressbar value based on number of files	Private Sub CopyWithProgress(ByVal ParamArray filenames As String())\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    Dim x As Integer\n    for x = 1 To filenames.Length - 1\n        ' Copy the file and increment the ProgressBar if successful.\n        If CopyFile(filenames(x - 1)) = True Then\n            ' Perform the increment on the ProgressBar.\n            pBar1.PerformStep()\n        End If\n    Next x\nEnd Sub	0
26280850	26278576	how to search xml file and display the string using xpath and display them on dgv	string givenString = "Choose Contact";\nstring language = "fr-FR";\nXmlDocument doc = new XmlDocument();\nstring filePath = "sample.xml";\ndoc.Load(filePath);\nstring path = "//tuv[seg='" + givenString + "']";\nXmlNode rootNode = doc.SelectSingleNode(path).ParentNode.Clone();\nstring childPath= "//tuv[@xmllang='" + language + "']";\nXmlNode node = rootNode.SelectSingleNode(childPath);\nConsole.WriteLine(node.InnerText);	0
13613893	13613856	Binding a List<> to a listview in asp.net c#	public class Visibility\n{\n    public int ShpNo { get; set; }\n    public int QtyShp { get; set; }\n    public int NumPallets { get; set; }\n    public string ETA { get; set; }\n}	0
7280291	7280265	Check if a string contains date or not	string []format = new string []{"yyyy-MM-dd HH:mm:ss"};\nstring value = "2011-09-02 15:30:20";\nDateTime datetime;\n\nif (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.NoCurrentDateDefault  , out datetime))\n   Console.WriteLine("Valid  : " + datetime);\nelse\n  Console.WriteLine("Invalid");	0
7647155	7646983	How do I add row data directly to a DataGrid Class?	dataGrid.ItemsSource = myBindingList;	0
29859421	29859011	Changing Title Font in WPF OxyPlot	plotModel.TitleFont = "Arial";\nplotModel.TitleFont = "Segoe UI";	0
5743567	5743553	how to return type t from a method	public static T Create<T>(T entity, Company company) where T : IEntity\n{\n    entity.Company = company;\n    entity.Key = Guid.NewGuid();\n    entity.Created = DateTime.Now;\n    entity.Modified = DateTime.Now;\n    entity.ModifiedByUserName = "xxx";\n    entity.CreatedByUserName = "xxx";\n    return entity;\n}	0
24595365	24595329	update list with specific object	var idx = preConList.FindIndex(x => x.ID == preConObj.ID);\npreConList[idx] = postConObj; // replace it	0
32034923	32034846	How to extract an image from resources?	public static void Extract(Bitmap imageToExtract, string destination) {\n    System.IO.File.WriteAllBytes(\n        destination, \n        ImageToByte(\n            imageToExtract\n        )\n    );\n}	0
20881401	20855685	connection one time to network Drive when Creating files with Impersonator	using (Impersonator impersonator = new Impersonator("UserName", "UserPwd", "UserDomaine"))\n{\n    File.Create(@"\\IP\Partage\Log\FileName.txt");\n}	0
28370152	28364640	C# run batch file with argument with spaces	ProcessStartInfo info = new ProcessStartInfo();\ninfo.UserName = KIM_USER;\ninfo.Password = ConvertToSecureString(KIM_USER_PASSWORD);\ninfo.FileName = theTask.Path + " \"" + TranslateParameter(theTask.Parameter) + "\"";\n//info.Arguments = "\"" + TranslateParameter(theTask.Parameter) + "\"";\ninfo.Domain = Environment.MachineName;\ninfo.WorkingDirectory = Path.GetDirectoryName(theTask.Path);\ninfo.UseShellExecute = false;\ninfo.CreateNoWindow = true;\nProcess batProcess = Process.Start(info);\nbatProcess.WaitForExit();	0
27636633	27636248	validation of data with sql and c#	private void ValidateLogin()\n        {\n                string uname = "Hsakarp";//I have hard-coded the value to make it simple\n                string pwd = "12345";\n                string sqlS = "Select UserName,Password from Login where UserName = '" + uname + "' and Password = " + pwd;\n        DalAccess dal = new DalAccess();\n                    DataSet ds = dal.GetDataSet(sqlS); //GetDataset is gonna return the ds\n                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n                    {\n                        if (ds.Tables[0].Rows[i]["UserName"].ToString().Trim() == uname && ds.Tables[0].Rows[i]["Password"].ToString().Trim() == pwd)\n//Check whether the username and password exists.\n                            Label1.Text = "Login Successfull";\n                        else\n                            Label1.Text = "Login failed";\n                    }\n}	0
9640804	9640341	How to embed background images and button images into Visual Studio?	Uri uri = new Uri("pack://application:,,,/Background 1.jpg");\nBitmapImage bitmapImage = new BitmapImage(uri);	0
9655710	9645044	HTMLAgillityPack Parsing	List<string> links = new List<string>();\nList<string> names = new List<string>();\nHtmlDocument doc = new HtmlDocument();\n//Load the Html\ndoc.Load(new WebClient().OpenRead("http://geo.craigslist.org/iso/us"));\n//Get all Links in the div with the ID = 'list' that have an href-Attribute\nHtmlNodeCollection linkNodes = doc.DocumentNode.SelectNodes("//div[@id='list']/a[@href]");\n//or if you have only the links already saved somewhere\n//HtmlNodeCollection linkNodes = doc.DocumentNode.SelectNodes("//a[@href]");\nif (linkNodes != null)\n{\n  foreach (HtmlNode link in linkNodes)\n  {\n    links.Add(link.GetAttributeValue("href", ""));\n    names.Add(link.InnerText);//Get the InnerText so you don't get any Html-Tags\n  }\n}\n//Write both lists to a File\nFile.WriteAllText("urls.txt", string.Join(Environment.NewLine, links.ToArray()));\nFile.WriteAllText("cities.txt", string.Join(Environment.NewLine, names.ToArray()));	0
25377190	25282726	How to use fontello icons in cs file?	public void pushPin(Microsoft.Phone.Maps.Controls.Map map, GeoCoordinate position)\n{\n\n    map.Center = position;\n    map.ZoomLevel = 9;\n\n    TextBlock tb = new TextBlock();\n    tb.FontFamily = new FontFamily("/fontello.ttf#fontello");\n    tb.Text = "\uE800";\n\n    var mapOverLay = new MapOverlay();\n    mapOverLay.Content = tb;\n\n    mapOverLay.GeoCoordinate = position;\n\n    var mapLayer = new MapLayer();\n    mapLayer.Add(mapOverLay);\n\n    map.Layers.Add(mapLayer);  \n\n}	0
15259887	15080617	outlook download email body	outlook.Session.SendAndReceive(false);	0
30400866	30334765	MAPPING POCO to Objects[] with property	public Dictionary<object, Action<machine,object>> setters\n = new Dictionary<object, Action<machine,object>>();	0
33060010	33029741	Scrolling GDI pixels in Panel control	using System;\nusing System.Windows.Forms;\n\nclass MyPanel : Panel {\n    public MyPanel() {\n        this.DoubleBuffered = this.ResizeRedraw = true;\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);\n        base.OnPaint(e);\n    }\n}	0
10616171	10616126	How to loop through all text files in a directory C#	foreach (var file in \n  Directory.EnumerateFiles(@"C:\\P\\DataSource2_W\\TextFiles\\Batch1", "*.txt"))\n{\n\n  //your code\n}	0
31274354	31274082	Best way to enumerate all combinations	var byPrefix = list.GroupBy(i => i.First()).ToDictionary(g => g.Key, g => g);\nvar result = \n    from s in byPrefix['S']\n    from r in byPrefix['R']\n    select new { s, r };	0
17890899	17890813	How do I serialize a list of objects with System.Runtime.Serialization.Json?	[DataContract]  \npublic class NodeData {\n  [DataMember]\n  public int NodeID { get; set; }\n  [DataMember]\n  public int ParentID { get; set; }\n  [DataMember]\n  public int Index { get; set; }\n  [DataMember]\n  public string FriendlyName { get; set; }\n\n  public NodeData(int nodeID, int parentID, int index, string friendlyName) {\n    this.NodeID = nodeID;\n    this.ParentID = parentID;\n    this.Index = index;\n    this.FriendlyName = friendlyName;\n  }\n}	0
33963076	33962541	Regex to return different parts if starts with specific string	var regex = new Regex(@"(?<=P0000000S\w+\s\w+\s)\w+|(?<=P)\d+(?=S)");	0
12200452	11955302	Cannot detect if a user is running with elevated privileges, when no UAC popup	WindowsIdentity identity = WindowsIdentity.GetCurrent();\nWindowsPrincipal principal = new WindowsPrincipal(identity);\nreturn principal.IsInRole (WindowsBuiltInRole.Administrator);	0
22685588	22685258	How to read SubRip file content into array of block subtitle?	string subRipContent = ReadTextFileFromUrl();\nstring[] splitData = data.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);	0
8482969	8482923	How to subscribe to change DependencyProperty?	var pd = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox));\n pd.AddValueChanged(myTextBox, OnTextChanged);\n\n\n private void OnTextChanged(object sender, EventArgs e)\n {\n     ...\n }	0
31968426	31968264	Convert ASCII sign into a string	string crown = "\u2655"	0
10106722	10106664	C#, User Control, Events - User Control's Control Event Overriding?	private void button1_Click(object sender, EventArgs e) {\n        this.OnClick(e);\n    }	0
13761594	13761394	How to display all the files from a directory (folder)	Using System.IO\n\nprotected void ListFiles()\n{\n        const string MY_DIRECTORY = "/MyDirectory/";\n        string strFile = null;\n        foreach (string s in Directory.GetFiles(Server.MapPath(MY_DIRECTORY), "*.*")) {\n                strFile = s.Substring(s.LastIndexOf("\\") + 1);\n                ListBox1.Items.Add(strFile);\n        }	0
501203	501194	Is string in array?	using System.Linq;\n\n//...\n\nstring[] array = { "foo", "bar" };\nif (array.Contains("foo")) {\n    //...\n}	0
7700945	7700940	c# - reference to a button	public void changeVis(System.Windows.Forms.Button buto)\n{\n    buto.Visible = True;\n}	0
27262222	27053707	Delivery Status Notification & Read Receipt in SMTP	mm.Headers.Add("Disposition-Notification-To", smtp_user);\n            mm.Headers.Add("Return-Receipt-To", smtp_user);\n\n            SmtpClient smtp = new SmtpClient(smtp_address, smtp_port);\n            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;\n            smtp.Credentials = new NetworkCredential(smtp_user, smtp_password);\n            smtp.EnableSsl = smtp_ssl;\n\n            smtp.Send(mm);	0
11450693	11450590	Access child class object in base abstract class method using Generics	public abstract class TradeBaseModel<T> : INotifyPropertyChanged, IDataErrorInfo where T: TradeBaseModel<T>	0
3068218	3021797	How Moles Isolation framework is implemented?	static struct DateTime \n{\n    static DateTime Now\n    {\n        get \n        {\n            Func<DateTime> d = __Detours.GetDelegate(\n                null, // this point null in static methods\n                methodof(here) // current method token\n                );\n            if(d != null)\n                return d();\n            ... // original body\n        }\n    }\n}	0
31046430	31046310	How to validate negative string number	double number = 0;\nif(double.TryParse(myString,out number)){\n   if (number > 0)\n       \\Do something\n}	0
4470926	4470580	Retrieving keyboard state in C# using DirectInput?	[DllImport("user32.dll")]\nprivate static \nextern short GetAsyncKeyState(System.Int32 vKey);	0
20126743	20126123	C#, How to get HTML generated textbox values during foreach Control loop and then show the result?	protected void ExecuteCode_Click(object sender, EventArgs e)\n{    \n    List<string> tbids = new List<string>();\n    int amount = Convert.ToInt32(DropDownListIP.SelectedValue);\n\n        for (int num = 1; num <= amount; num++)\n        {\n            HtmlGenericControl div = new HtmlGenericControl("div");\n            TextBox t = new TextBox();\n            t.ID = "textBoxName" + num.ToString();\n            div.Controls.Add(t);\n            phDynamicTextBox.Controls.Add(div);\n            tbids.Add(t.ID);\n        }\n        Session["tbids"] = tbids;\n        ButtonRequest.Visible = true;\n}\n\nprotected void ButtonRequest_Click(object sender, EventArgs e)\n    {\n        string str = "";\n        var tbids = (List<string>)Session["tbids"];\n        foreach (var id in tbids)\n        {\n            try\n            {\n                str += Request[id]+" "; //here get value tb with id;\n            }\n            catch\n            {\n\n            }\n        }\n\n        TextBoxFinal.Text = str;\n\n    }	0
29961671	29961623	Check string is numeric by using try parse in c#	bool digitsOnly = s.All(c => char.IsDigit(c));	0
13467338	13467291	How to write xpath for this XDocument?	xdDiffData.XPathSelectElement("//tags/data[@mode='add']") != null &&        xdDiffData.XPathSelectElement("//tags/data[@mode='delete']") != null	0
4516897	4516782	How can I write a binary array to a file in C#?	string content = BitConverter.ToString(data);	0
34464184	34463861	Multiple SQL commands executed via "ExecuteReader" in a system I can only manipulate SQL statements	EXEC('\n    CREATE Procedure ##myTempProcedure(\n        @param1 nvarchar(max)\n    ) as \n    begin\n      insert #tempTable (col1, col2) select aCol, bCol from table2 where col2 = @param1;\n    end;\n');\n\n\nCREATE TABLE #tempTable\n(\n    col1 nvarchar(512),\n    col2 nvarchar(512)\n);\n\nEXEC ##myTempProcedure N'val1';\nEXEC ##myTempProcedure N'val2';\nEXEC ##myTempProcedure N'val3';\nEXEC ##myTempProcedure N'val4';\n\nselect col1, col2 from #tempTable;\n\nEXEC('DROP PROC ##myTempProcedure;');	0
1541106	1540152	How to use the MOQ library to mock an ENum	public virtual bool HasPermission(string name, PermissionType type)\n{\n   // logic\n}	0
11536799	11536535	Check if a Table in Sql Server is locked	if(noLockOnTheTable)\n{\n  // ... something else acquires the lock just at this point\n  updateTable();\n}	0
7432395	7432265	LINQ to JSON: how to get the right format?	JArray a = JArray.FromObject(\n                from u in model.USER\n                select new\n                {\n                    UserID = u.UserID\n                }\n    );	0
2146868	2146787	How to convert Text values to number values in Excel 2003 (Number stored as Text), using C#	Range cellA1 = wSheet.get_Range("A1", System.Type.Missing);\ncellA1.Value2 = "0";\ncellA1.Copy(System.Type.Missing);\nRange cellAll = wSheet.get_Range("A1:AZ500", System.Type.Missing);\ncellAll.PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationAdd,\n        false, false);	0
28214764	28214646	Attempting to share Object between WPF windows	public partial class  Settings: Window\n{\n    Object _object;\n\n    public Settings(Object object)\n    {\n        _object = object\n        InitializeComponent();\n    }\n\n    private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)\n    {\n        // get text in object\n        String name = _object.Text;\n    }	0
8817685	8817308	How to skip a directory while searching directories with iteration? (C#)	void ProcessFolder(string path) {\n\n    // Process the files \n    foreach(var file in Directory.GetFiles(path)) {  \n        // Process each file  \n    }  \n\n    // process the sub folders\n   foreach (var subFolder in Directory.GetDirectories(path).Where(fld => System.IO.Path.GetFilename(fld) != "ORJ")) {\n        ProcessFolder(subFolder);\n    }\n\n}	0
13308657	13306465	MVC Jquery POST data, redirect to url from ActionResult	public string Redirect(string Team)\n{\n\n    var hostName = "http://localhost/test/testpage.aspx?";\n    var team = "&Team=" + Team;\n\n\n    var filterUrl = hostname + Team;\n\n\n    return filterUrl;\n}\n\nfunction RedirectSuccess(data) {\n        if (data != undefined) {\n            window.location = data;          \n             }\n    }	0
19235283	19234791	Return Data Row after Insert with ODBC	addCMD.CommandText = @"INSERT INTO ""users""(""username"") VALUES(?) RETURNING user_id";	0
24013203	23590328	Saving a captured image without using clipboard with WM_CAP_SAVEDIB using C#?	IntPtr hBmp = Marshal.StringToHGlobalAnsi(FinalPath);\nSendMessage(mCapHwnd,WM_CAP_SAVEDIB,0,hBmp.ToInt32());	0
376255	376229	How do I hook the TAB key in a usercontrol so that focus doesn't move to a different control?	protected override bool ProcessDialogKey(Keys keyData)\n        {\n            if (keyData != Keys.Tab)\n            {\n              return base.ProcessDialogKey(keyData);\n            }\n            return false;\n        }	0
17228384	17228325	Display window over full screen application	TopMost = true	0
20121058	20121018	C#: Interface instead of class in variable definition	public ILocation block;\n\npublic Location (int x, int y, ILocation o)\n{\n    X = x;\n    Y = y;\n    block = o;\n}	0
11208969	11208846	converting template field from integer to hh:mm	you can use this code :\n\n    var Hours = Math.floor(Yourvariable/60);\n    var Minutes = Yourvariable%60;\n\nOr you can use this\n\nvar span = System.TimeSpan.FromMinutes(Yourvariable);\nvar hours = ((int)span.TotalHours).ToString();     \nvar minutes = span.Minutes.ToString();	0
3288721	3288681	Viewing variable values at runtime in VisualStudio	System.Diagnostics.Debug.WriteLine(variable);	0
34302487	34302141	Left Outer Join with Multiple On Statements	var clientId = 104;\nvar lang = "fr-FR";\nvar leagueId = 8;\n\n// Find teams in specifiec league\n// Equivalent to this step in SQL: WHERE fbt.league_id = 8\nvar leagueTeams = footballTeams.Where(fbt => fbt.league_id == leagueId).ToList();\n\n// Find teams that fulfill required conditions\n// Equivalent to the On condition in SQL\nvar teams = footballCustomTeams\n.Where(fbct => leagueTeams.Any(fbt => fbct.team_id == fbt.team_id) &&\n                fbct.client_id == clientId &&\n                fbct.language == lang)\n.Select(fbct => new { TeamId = fbct.team_id, ClientId = fbct.client_id });	0
27151487	27151149	Is there a way to execute an exe stored with a temp file name?	System.Diagnostics.Process p = new System.Diagnostics.Process();\n p.StartInfo.FileName = @"c:\tmp\a123.tmp";\n p.StartInfo.UseShellExecute  = false;\n p.Start();	0
1076434	1075323	copy list items from one list to another in sharepoint	string dest= \n siteCollection.Url + "/" + site.Name + list.Name + item.File.Name;	0
5543067	5542986	Math rounding in c# - whole numbers issue	Math.Round(d, decimals)	0
32958825	32952700	How to use wildcards to match directory paths in Sqlite	void printPaths()\n    {\n        string mypath = @"c:\\root\\1";\n        string sql = ("select * from paths where pathdesc like @mypath");\n\n        SQLiteCommand command = new SQLiteCommand(sql,m_dbConnection);\n        command.Parameters.AddWithValue("@mypath", mypath+"%");\n\n        SQLiteDataReader reader = command.ExecuteReader();\n        while (reader.Read())\n            Console.WriteLine("ID: " + reader["pathid"] + "\tpathdesc: " + reader["pathdesc"]);\n        Console.ReadLine();\n    }	0
7660191	7659868	Try Catch, number in a text field	try\n{\n    tblCarBindingSource.Filter = filter;\n}\ncatch\n{\n    MessageBox.Show("Please enter valid values in your text fields.");\n}	0
26477573	26476311	handling large amounts of data to include in an oracle select statement	using (OracleConnection conn = new OracleConnection(BD_CONN_STRING))\n        {\n            conn.Open();\n            using (OracleCommand cmd = new OracleCommand("create global temporary table t1(id number(9))", conn))\n            {\n                // actually this should execute once only\n                cmd.ExecuteNonQuery();\n            }\n\n            using (OracleCommand cmd = new OracleCommand("insert into t1 values (1)", conn)) {\n                cmd.ExecuteNonQuery();\n            }\n\n            // customer table is a permenant table \n            using (OracleCommand cmd = new OracleCommand("select c.id from customer c, t1 tmp1 where c.id=tmp1.id", conn)) {\n                cmd.ExecuteNonQuery();\n            }\n        }	0
13741521	13601753	ACL: How to check, or uncheck options	WindowsIdentity id = WindowsIdentity.GetCurrent();\nvar sid = new SecurityIdentifier(WellKnownSidType.AccountDomainUsersSid, id.User.AccountDomainSid);\nvar security = dir.GetAccessControl();\nvar rule = new FileSystemAccessRule(sid,\n    FileSystemRights.FullControl,\n    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,\n    PropagationFlags.None,\n    AccessControlType.Allow);\nsecurity.AddAccessRule(rule);\ndir.SetAccessControl(security);	0
27622226	27609232	How to call a webapi rest service from WinRT / Store app	using (var httpFilter = new HttpBaseProtocolFilter())\n    {\n        using (var httpClient = new HttpClient(httpFilter))\n        {\n            Uri requestUri = new Uri("");\n            string json = await JsonConvert.SerializeObjectAsync(CredentialsModel);\n            var response = await httpClient.PostAsync(requestUri, new HttpStringContent(json, UnicodeEncoding.Utf8, "application/json"));\n            if (response.StatusCode == HttpStatusCode.Ok)\n            {\n                var responseAsString = await response.Content.ReadAsStringAsync();\n                var deserializedResponse = await JsonConvert.DeserializeObjectAsync<IEnumerable<Appointment>>(responseAsString);\n            }\n        }\n    }	0
33347665	33346519	Prevent API method to be called more then once at a time	private Object myLock= new Object();\n\n    foreach (string fileName in request.Files)\n            {\n                var companyName = request.Form.Get(0);\n                var productId = request.Form.Get(1);\n                if (string.IsNullOrWhiteSpace(companyName))\n                {\n                    throw new Exception("No company found!");\n                }\n                if (string.IsNullOrWhiteSpace(productId))\n                {\n                    throw new Exception("No product picked!");\n                }\n                HttpPostedFileBase file = request.Files[fileName];\n                if (file != null && file.ContentLength > 0)\n                {\n\n                    lock (myLock)\n                    {\n                        //This is the method that calls the API\n                        SaveUploadResource(file, companyName, productId);\n                    }\n                }\n            }	0
8087086	8086705	How to find the starting address of an application for memory editing a process?	Process proc = Process.GetCurrentProcess();\nIntPtr startOffset = proc.MainModule.BaseAddress; \nIntPtr endOffset = IntPtr.Add(startOffset ,proc.MainModule.ModuleMemorySize);	0
24456342	24426648	Changing ConcurrencyMode	ServiceHost.Description.Behaviors	0
11017841	11017670	Datagridview is not displaying anything no column header nor data	datagridviewjobs.Datasource=tempJobsDataset.Tables("MyTable");	0
23200338	23197001	How do I convert this C# lambda expression to VB.Net?	Public Function [Select](Of E As Class)(ParamArray includeExpressions As Linq.Expressions.Expression(Of Func(Of E, Object))()) As IQueryable(Of E)\n        Dim result As IQueryable(Of E) = Nothing\n\n        If includeExpressions.Any() Then\n            result = includeExpressions.Aggregate(Context.[Set](Of E)(), (Function(current, expression) CType(current.Include(expression), DbSet(Of E))))\n        End If\n\n        Return result\n    End Function	0
34438233	34437344	Redirect to login with attribute Authorize using cookies authentication in ASP.NET 5	app.UseCookieAuthentication(new CookieAuthenticationOptions\n{\n    LoginPath = "/account/login",\n\n    AuthenticationScheme = "Cookies",\n    AutomaticAuthenticate = true,\n    AutomaticChallenge = true\n});	0
13771453	13770570	How to detect a MenuStrip's open and close states ?	private void Form1_Load(object sender, EventArgs e)\n  {\n     menuStrip1.GotFocus += new EventHandler(MenuStrip1_GotFocus);\n     menuStrip1.LostFocus += new EventHandler(MenuStrip1_LostFocus);\n  }\n\n  private void MenuStrip1_GotFocus(object sender, EventArgs e)\n  {\n     textBox1.Text = "Has Focus";\n  }\n\n  private void MenuStrip1_LostFocus(object sender, EventArgs e)\n  {\n     textBox1.Text = "Lost Focus";\n  }\n\n  private void menuStrip1_MenuActivate(object sender, EventArgs e)\n  {\n     textBox1.Text = "Has Focus";\n  }\n\n  private void menuStrip1_MenuDeactivate(object sender, EventArgs e)\n  {\n     textBox1.Text = "Lost Focus";\n  }	0
19386754	19386508	Hooking a C# event from C++/CLI	CSClient^ obj = safe_cast<CSClient^>(h.Target);\n   obj->OnOptionsEvent += \n      gcnew CSClient::OnMessageHandler(this, &CSClientWrapper::OnOptions);	0
32268202	32267624	Get Attribute name using position from XElement	XElement rootElement = XElement.Parse(stringXml);\n        DataTable dt = new DataTable();\n        if (rootElement.Attribute("documentID").Value == "CSTrlsEN")\n        {\n             var colNames = from field in rootElement.Elements("field")\n                          where Convert.ToInt32(field.Attribute("pos").Value) >= 5\n                          select field.Attribute("name").Value;\n\n             foreach (var name in colNames)\n             {\n                 dt.Columns.Add(name, typeof(string));\n             }\n        }	0
11565986	11565730	How to convert SelectedListViewItemCollection to ListViewItemCollection	private void PurgeListOfStudies(IEnumerable items)\n{\n    foreach(MyType currentItem in items) //implicit casting to desired type\n    {\n        // process current item in the list...\n    }\n}	0
23309763	23307724	How to Extract Docx Pages according to page range using c#	var range = doc.Range();\nrange.Start = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, pageStart).Start;\n\nif (pageend < doc.ComputeStatistics(WdStatistic.wdStatisticPages, false))\n{\n    range.End = doc.GoTo(WdGoToItem.wdGoToPage, WdGoToDirection.wdGoToAbsolute, pageend + 1).End - 1;\n}\n\nrange.Copy();	0
609278	605012	How do I do a Contains() in DLINQ with a list of items?	var resultSets = (from k in list\n                  select (from b in db.Sites\n                          where b.site_title.Contains(k)\n                          select b.ToBusiness()).ToList<Business>()).ToList();\n\n List<Business> all = new List<Business>();\n\n for (int i = 0; i < resultSets.Count; ++i)\n {\n     all.AddRange(resultSets[i]);\n }	0
15385461	15385301	comparing strings in c#	string line3 = "XXX,AAAAAA,B,CC;Dartw esata garle;3.00;1;1;1;2;0;1;ccc;";	0
15210617	15210535	assert string array not equal but appears to be	CollectionAssert.AreEqual(expected, actual);	0
31719475	31719237	I cant import excel to datagridview	private void button1_Click(object sender, EventArgs e)\n    {\n        String name = "sheet1";\n        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +\n                        "C:\\Sample.xlsx" + \n                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";\n\n        OleDbConnection con = new OleDbConnection(constr);\n        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);\n        con.Open();\n\n        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);\n        DataTable data = new DataTable();\n        sda.Fill(data);\n        grid_items.DataSource = data;\n    }	0
15427526	15426383	How to update azure blob url programatically	CloudBlobContainer container = GetContainerReference('containername');\nvar blobs = container.ListBlobs().Select(p => p.Uri.ToString().Contains(' '));\nforeach (CloudBlob oldBlob in blobs)\n{\n    var newBlobName = oldBlob.Name.Replace(" ", String.Empty);\n    var newBlob = container.GetBlobReference(newBlobName);\n    newBlob.CopyFromBlob(oldBlob);\n\n    oldBlob.Delete();\n}	0
9133119	9132964	linq group by, order by	list1.GroupBy(item => new { Counter = item.Counter, SrvID = item.SrvID })\n     .Select(group => new { \n        ID = group.First().ID, \n        Counter = group.Key.Counter,\n        SrvID = group.Key.SrvID,\n        FirstName = group.First().FirstName})\n     .OrderBy(item => item.ID);	0
17649174	17648803	Pagination of GridView which is inside a DataList	protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)\n    {\n        try\n        {\n            GridView gv = (sender as GridView);\n            DataListItem DLItem= (DataListItem)gv.NamingContainer;\n            //Label Id = (Label)DLItem.FindControl("lblId");\n\n            gv.PageIndex = e.NewPageIndex;\n\n            //Your gridbinding code\n    HiddenField hdn = (HiddenField)DLItem.FindControl("hdnCountryID");\n    //GridView grd = (GridView)e.Item.FindControl("grdDetails");\n\n    objCountries = new Countries();\n    lstCountries = objCountries.getallCountries();\n    gv .DataSource = lstCountries ;//lstOrders;\n    gv .DataBind();\n\n        }\n        catch (Exception ex)\n        {\n\n           // return;\n        }\n\n    }	0
21737131	21734003	Applying default headers to multi-part request content	foreach (var header in client.DefaultRequestHeaders)\n{\n     msg.Headers.Remove(header.Key);\n     msg.Headers.TryAddWithoutValidation(header.Key, header.Value);\n}	0
1823194	1823149	Dynamic method dispatch based on value of variable	fact (value : Int) : Int\n    conditions value < 0\n{\n    { "Illegal input value\n" } astype Message\n    return 0\n}\n\nfact (value = 0) : Int\n{\n    return 0\n}\n\nfact (value = 1) : Int\n{\n    return 1\n}\n\nfact (value : Int) : Int\n{\n    return value * fact(value - 1);\n}	0
7876455	7876385	How to disable items inside the ItemTemplate for a individual columns in asp.net	ImageButton btnEdit = (ImageButton)e.Row.FindControl("imgbtn");\nbtnEdit.Enabled = !status.Equals("No");\nLinkButton btnDelete = (LinkButton)e.Row.FindControl("Lnk_Delete");\nbtnDelete.Enabled = !status.Equals("No");	0
29132862	29132682	Is init in Swift the same as a constructor in C#?	init() {\n    // perform some initialization here\n}	0
8563786	8563666	Getting currency list item values	SPListItem item = ...;\ndouble d = Convert.ToDouble(item["InstallCosts"]);\n// will display the number in the current threads culture. In the US: $ <value>\nstring currency = d.ToString("C");	0
7505007	7504928	Is there a Case invariant way to compare string with a Enum in Enum.IsDefined / Enum.Parse	someType varName = Enum.Parse(typeof(someType), stringToCompare, true);	0
1826374	1826324	How to write a WCF service with in-memory persistent storage?	[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Single)]\npublic class MyService: IService	0
16815786	16815575	Gridview Conditional formatting of a cell	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowType == DataControlRowType.DataRow)\n  {\n if(e.Row.Index=1) //Check your Row index \n  {\n      e.Row.Cells[YOur column index].Attributes.Add("Style", "background: url(../Images/nc.png) no-repeat 5px center;");\n  }\n }\n}	0
32485527	32485431	C# SQLITE - How to pass bound parameters via an array or list?	for(int i = 0; i < sqlParameters.Count; ++i)\n    sqlcommand.Parameters.AddWithValue("@column" + i.ToString(), sqlParameters[i]);	0
1838960	1838619	Relocating app.config file to a custom path	// get the name of the assembly\nstring exeAssembly = Assembly.GetEntryAssembly().FullName;\n\n// setup - there you put the path to the config file\nAppDomainSetup setup = new AppDomainSetup();\nsetup.ApplicationBase = System.Environment.CurrentDirectory;\nsetup.ConfigurationFile = "<path to your config file>";\n\n// create the app domain\nAppDomain appDomain = AppDomain.CreateDomain("My AppDomain", null, setup);\n\n// create proxy used to call the startup method \nYourStartupClass proxy = (YourStartupClass)appDomain.CreateInstanceAndUnwrap(\n       exeAssembly, typeof(YourStartupClass).FullName);\n\n// call the startup method - something like alternative main()\nproxy.StartupMethod();\n\n// in the end, unload the domain\nAppDomain.Unload(appDomain);	0
16334387	16334323	Event handlers on Message box buttons	DialogResult result = MessageBox.Show("text", "caption", MessageBoxButtons.YesNo);\nif(result == DialogResult.Yes){\n   //yes...\n}\nelse if(result == DialogResult.No){\n   //no...\n}	0
7235475	7233195	How to change a printer's PortName using c#	ManagementScope scope = new ManagementScope(@"\root\cimv2");\nscope.Connect();\n\n// Insert your printer name in the WHERE clause...\nManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer WHERE Name='PrinterName");\n\n\nforeach (ManagementObject printer in searcher.Get())\n{\n  printer["PortName"]="LPT1:";\n  printer.Put();  // Important: Call put to save the settings.\n}	0
26979493	26978916	Break stream of digits into smaller chunks for processing	Split('|')	0
4546149	4546097	adding Lines to Xml file At Specific location	XDocument\n    .Load("test.xml")\n    .Root\n    .Add(\n        new XElement(\n            "message", \n            new XAttribute("id", "123"),\n            new XAttribute("name", "foo"),\n            new XAttribute("text", "bar")\n        )\n    )\n    .Save("test.xml");	0
34241396	34240263	How can we multi-select and delete multi rows on a data grid view by Code?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        dataGridView1.MultiSelect = true;\n        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        var selectedRows = dataGridView1.SelectedRows\n            .OfType<DataGridViewRow>()\n            .Where(row => !row.IsNewRow)\n            .ToArray();\n\n        foreach (var row in selectedRows)\n            dataGridView1.Rows.Remove(row);\n\n        dataGridView1.ClearSelection();\n    }\n}	0
27388822	27388405	How to query from XML with SchemaVersion?	StringBuilder sb = new StringBuilder();\n        sb.Append(@"<?xml version=""1.0"" encoding=""us-ascii"" ?>");\n        sb.Append(@"<LoanSetupFile SchemaVersion=""3.0"" NumberOfLoans=""2"" xmlns=""https://www.something.com/schemas"">");\n        sb.Append(@"<Loan ServicerLoanNumber=""1""/>");\n        sb.Append(@"<Loan ServicerLoanNumber=""2""/>");\n        sb.Append(@"</LoanSetupFile>");\n\n        var doc = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString() ?? "")));\n        XNamespace ns = doc.Root.GetDefaultNamespace(); //This gives me the correct namespace\n        var loans = from l in doc.Descendants(ns + "Loan") \n                    select new { ServicerLoanNumber = l.Attribute("ServicerLoanNumber").Value };\n\n        // Temporarily display the values\n        foreach (var l in loans)\n        {\n            MessageBox.Show(l.ServicerLoanNumber);\n        }	0
1048246	1048225	How do I open a file that is opened in another application	using (var stream = new FileStream(\n       @"d:\myfile.xls", \n       FileMode.Open, \n       FileAccess.Read, \n       FileShare.ReadWrite))\n{\n\n}	0
11632359	11632250	Can I get the value of one attached property from another?	private static void HandleKeyDown(object sender, KeyEventArgs e)\n{\n  var param = sender.GetValue(CommmandParameterProperty);\n  GetKeyDownCommand((UIElement)sender).Execute(param);\n}	0
23434230	23379011	Design pattern for between ViewModel and Service / Model	//pseudo code from the top of my head\nvar perperationTask = service.PrepareStuffAsync(parameter);  \nvar parameterATask = service.GetParameterA(value1, value2);  \nvar parameterBTask = service.GetParameterB(value2,value3);  \n\nawait Task.WhenAll(settingsTask, reputationTask, activityTask);  \n\nPreperationSettings settings = perperationTask.Result;  \nint parameterAResult = parameterATask.Result;  \nint parameterBResult = parameterBTask.Result;\n\nawait calulation = service.CalculateAsync(parameterAResult,parameterBResult);	0
24910480	24910133	Create Unique Relationship with additional attributes to the relationship	.CreateUnique("en1-[:sRelationName { category: {category_name} }]->en2")\n.WithParams(new {category_name = "YourCategoryHere"});\n.ExecuteWithoutResults();	0
20217172	20217131	New value on gridview edit mode	TextBox txt= (TextBox)GridView1.Rows[GridView1.EditIndex].Cells[2].Controls[0];\nResponse.Write(txt.Text);	0
27005886	27004844	Formatting dashes in string interpolation	var dob2 = "Customer \{customer.IdNo} was born on \{customer.DateOfBirth : "yyyy-M-dd"}";	0
7569908	7569751	How to use method(s) to add multiple, changing values	public class Skill\n{\n    int ability, rank, misc;\n\n    public Skill(int ability, int rank, int misc)\n    {\n        this.ability = ability;\n        this.rank = rank;\n        this.misc = misc;\n    }\n\n    public int Score { get { return ability + rank + misc; }\n}\n\nSkill balance = new Skill(10, 1, 1);\ntextBalance.Text = balance.Score.ToString();\n\nSkill programming = new Skill(10, 100, 0);\ntextProgramming.Text = programming.Score.ToString();	0
1303053	1303029	How can I measure the performance of a HashTable in C#?	Stopwatch stopWatch = new Stopwatch();\n    stopWatch.Start();\n    Thread.Sleep(10000); //your for loop\n    stopWatch.Stop();\n    // Get the elapsed time as a TimeSpan value.\n    TimeSpan ts = stopWatch.Elapsed;\n\n    // Format and display the TimeSpan value.\n    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",\n        ts.Hours, ts.Minutes, ts.Seconds,\n        ts.Milliseconds / 10);\n    Console.WriteLine(elapsedTime, "RunTime");	0
9171723	9171629	Order of calling constructors case of inheritance in c#	// Demonstrate when constructors are called.\nusing System;\n\n// Create a base class.\nclass A {\n    public A() {\n        Console.WriteLine("Constructing A.");\n    }\n}\n\n// Create a class derived from A.\nclass B : A {\n    public B() {\n        Console.WriteLine("Constructing B.");\n    }\n}\n\n// Create a class derived from B.\nclass C : B {\n    public C() {\n        Console.WriteLine("Constructing C.");\n    }\n}\n\nclass OrderOfConstruction {\n    static void Main() {\n        C c = new C();\n    }\n}\n\nThe output from this program is shown here:\n\nConstructing A.\nConstructing B.\nConstructing C.	0
2594569	2594553	Attribute lost with yield	[Something(123)]\npublic IEnumerable<Foo> GetAllFoos()\n{\n    SetupSomething();\n    return GetAllFoosInternal();\n}\n\nprivate IEnumerable<Foo> GetAllFoosInternal()\n{\n    DataReader dr = RunSomething();\n    while (dr.Read())\n    {\n        yield return Factory.Create(dr);\n    }\n}	0
19566729	19566457	redraw image during excecution WPF	Task.Factory.StartNew(() => {\nvar result = ts.makeTest();\nsetLight1(result);\n\n})	0
17070051	17069869	Deserialize a JSON array that contains an array?	JsonConvert.DeserializeObject<List<List<People>>>	0
29310728	29306213	How To Play Multiple Sounds in Unity 3D	AudioSource[] myNotes;\nmyNotes[0].PlayOnce();\nmyNotes[3].PlayOnce();\n\n//Don't do this. \n// audio.clip = <---- NO!!!	0
22399922	21877312	Plotting incoming serial data on Zedgraph , X Axis starting from 00:00	/*Initial pane settings*/\npane.XAxis.Type = AxisType.Date;\npane.XAxis.Scale.Format = "dd/MM/yy\nH:mm:ss";\npane.XAxis.Scale.Min = (XDate)(DateTime.Now);\n//Shows 25 seconds interval.\npane.XAxis.Scale.Max = (XDate)(DateTime.Now.AddSeconds(25));\npane.XAxis.Scale.MinorUnit = DateUnit.Second;\npane.XAxis.Scale.MajorUnit = DateUnit.Minute;\npane.XAxis.MajorTic.IsBetweenLabels = true;\npane.XAxis.MinorTic.Size = 5;\n\n/*Real time plotting*/\nXDate time = new XDate(DateTime.Now.ToOADate());\nLineItem curve= curve= myPane.CurveList[0] as LineItem;\nIPointListEdit list = list = curve.Points as IPointListEdit;\nlist.Add(time,data);\n//Scale pane if current time is greater than the initial xScale.Max\nScale xScale = zgcMasterPane.MasterPane.PaneList[0].XAxis.Scale;\nif (time.XLDate > xScale.Max)\n{\n  xScale.Max = (XDate)(DateTime.Now.AddSeconds(5));\n  xScale.Min = (XDate)(DateTime.Now.AddSeconds(-20));\n}	0
8521310	8521268	xmlwriter write elements in one line	XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = "\t";\nXmlWriter writer = XmlWriter.Create(savefilepath, settings);	0
7682636	7682628	How to pad a binary string with zeros?	Console.WriteLine( binary.PadLeft(8, '0'));	0
1829676	1829605	How to cast an object programmatically at runtime?	interface MyControlInterface\n{\n    void MyControlMethod();\n}\n\nclass MyControl : Control, MyControlInterface\n{\n    // Explicit interface member implementation:\n    void MyControlInterface.MyControlMethod()\n    {\n        // Method implementation.\n    }\n}\n\nclass MyOtherControl : Control, MyControlInterface\n{\n    // Explicit interface member implementation:\n    void MyControlInterface.MyControlMethod()\n    {\n        // Method implementation.\n    }\n}\n\n\n.....\n\n//Two instances of two Control classes, both implementing MyControlInterface\nMyControlInterface myControl = new MyControl();\nMyControlInterface myOtherControl = new MyOtherControl();\n\n//Declare the list as List<MyControlInterface>\nList<MyControlInterface> list = new List<MyControlInterface>();\n//Add both controls\nlist.Add (myControl);\nlist.Add (myOtherControl);\n\n//You can call the method on both of them without casting\nlist[0].MyControlMethod();\nlist[1].MyControlMethod();	0
13823381	13416434	Open Word document, unless it has password with C#	Application word = new Application();\nword.DisplayAlerts = WdAlertLevel.wdAlertsNone;\ntry\n{\n    word.Documents.OpenNoRepairDialog(@"c:\testfolder\Doc2.docx", ReadOnly: true, PasswordDocument: "RandomButSurelyNotRightPassword");\n    word.ActivePrinter = "TIFF Image Printer 10.0";\n    Doc.PrintOut(); //printout untested for now\n    Doc.Close(false);\n}\ncatch (System.Runtime.InteropServices.COMException ex)\n{\n    if (ex.ErrorCode == 0x12345678)\n    {\n        //skip file and log file name and position for review\n    }\n}	0
5556733	5555054	How do I create a list of classes which always have a predefined value set in AutoFixture?	fixture.Customize<Child>(c => c.With(x => x.ParentId, 42).With(x => x.ChildId, 0));	0
12952545	12952489	get todays date in Web Service application	string StrAttachment = "C:\\" + //your drive letter\n                       DateTime.Today.ToString("yyyyMMdd") +  //your current date\n                       "yourFoldername"; //other name in the folder (if any)	0
4578890	4578547	How do I add multiple joins (Fetches) to a joined table using nhibernate and LINQ?	Session.Query<VacationRequestDate>()\n       .Fetch(r => r.VacationRequest).ThenFetch(p => p.RequestStatus)\n       .Fetch(r => r.VacationRequest).ThenFetch(p => p.Person)	0
802016	802002	Fluent sorting of a List<T> on multiple criteria using extension methods?	using System.Linq;\n\ncollection.OrderBy(t => t.FirstCriteria).ThenBy(t => t.SecondCriteria);	0
12582637	12581891	Redirect to referrer URL but add something to the querystring	[HttpPost]\npublic ActionResult MyAction(MyModel model)\n{\n    //Do stuff.\n\n    UriBuilder uriBuilder = new UriBuilder(Request.UrlReferrer);\n    NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query);\n    query.Add("myparam", "something");\n    uriBuilder.Query = query.ToString();\n\n    return new RedirectResult(uriBuilder.Uri);\n}	0
9410751	9410633	Generic Type with dynamic count of type parameters	var l1 = new List<int>();\nvar l2 = new List<Tuple<int, long>>();\nvar l3 = new List<Tuple<int, long, byte>>();	0
13339763	13339282	How can I open a word document by using CreateObject in C#?	using (FileStream stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n{\n Document Doc = new Document(stream);\n}	0
5647600	5647560	Get all entries in resx file ASP.NET	var allEntries = new ResourceManager(typeof(Tags))\n        .GetResourceSet(CultureInfo.CurrentCulture, false, true);	0
24870974	24869163	Error with testing xamarin app in iOS iPhone device	SecRecord existingRec = new SecRecord (SecKind.GenericPassword) { \n            Service = Keychain.USER_SERVICE, \n            Label = Keychain.USER_LABEL \n        };\n\n        var record = new SecRecord (SecKind.GenericPassword) {\n            Service = Keychain.USER_SERVICE, \n            Label = Keychain.USER_LABEL, \n            Account = username,\n            ValueData = NSData.FromString (password),\n            Accessible = SecAccessible.Always\n        };\n\n        SecStatusCode code = SecKeyChain.Add (record);\n        if (code == SecStatusCode.DuplicateItem) {\n            code = SecKeyChain.Remove (existingRec);\n            if (code == SecStatusCode.Success)\n                code = SecKeyChain.Add (record);\n        }	0
3639979	3639972	A dictionary with multiple entries with the same key - C#	var dict = new Dictionary<int, HashSet<string>>();\ndict.Add(1, new HashSet<string>() { "first", "second" });	0
8641862	8641842	C# - Change index of ComboBox item?	myComboBox.Items.Insert(0, "New item at top");	0
3823319	3823188	How can I sync the scrolling of two multiline textboxes?	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass SyncTextBox : TextBox {\n    public SyncTextBox() {\n        this.Multiline = true;\n        this.ScrollBars = ScrollBars.Vertical;\n    }\n    public Control Buddy { get; set; }\n\n    private static bool scrolling;   // In case buddy tries to scroll us\n    protected override void WndProc(ref Message m) {\n        base.WndProc(ref m);\n        // Trap WM_VSCROLL message and pass to buddy\n        if (m.Msg == 0x115 && !scrolling && Buddy != null && Buddy.IsHandleCreated) {\n            scrolling = true;\n            SendMessage(Buddy.Handle, m.Msg, m.WParam, m.LParam);\n            scrolling = false;\n        }\n    }\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}	0
22231258	22231257	How to generate a CUSIP check digit in C#	public string GenerateCheckDigit(string cusip)\n{        \n    int sum = 0;\n    char[] digits = cusip.ToUpper().ToCharArray();\n    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#";\n\n    for (int i = 0; i < digits.Length; i++)\n    {\n        int val;\n        if (!int.TryParse(digits[i].ToString(), out val))\n            val = alphabet.IndexOf(digits[i]) + 10;\n\n        if ((i % 2) != 0)\n            val *= 2;\n\n        val = (val % 10) + (val / 10);\n\n        sum += val;\n    }\n\n    int check = (10 - (sum % 10)) % 10;\n\n    return check.ToString();\n}	0
11989612	11989567	Create Bitmap object from array	byte[] _data = new byte[]\n{\n    255, 0, 0, 255, // Blue\n    0, 255, 0, 255, // Green\n    0, 0, 255, 255, // Red\n    0, 0, 0, 255,   // Black\n};\n\nvar arrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(_data,\n        System.Runtime.InteropServices.GCHandleType.Pinned);\n\nvar bmp = new Bitmap(2, 2, // 2x2 pixels\n    8,                     // RGB32 => 8 bytes stride\n    System.Drawing.Imaging.PixelFormat.Format32bppArgb,\n    arrayHandle.AddrOfPinnedObject()\n);\n\nthis.BackgroundImageLayout = ImageLayout.Stretch;\nthis.BackgroundImage = bmp;	0
14855665	14854141	Windows service - inject callback?	HostFactory.New(x =>\n                {\n                    x.SetDisplayName("Your service");\n                    x.SetServiceName("yourservice");\n                    x.Service<MyService>(c =>\n                    {\n                        c.SetServiceName("My service");\n                        c.ConstructUsing(name => container.Resolve<MyService>());\n                        c.WhenStarted(s => s.Start());\n                        c.WhenStopped(s => s.Stop());\n                    });\n\n                })\n                    .Run();	0
16225036	16224975	Parsing a string for a particular value	Decaf decafCoffee = null;\nRoast roastCoffee = null;\nif (min.StartsWith("D:")) \n    decafCoffee = new Decaf();\nelse if (min.StartsWith("R:"))\n    roastCoffee = new Roast();\nelse\n    // Give an error or something.	0
16739052	16738029	Finding Log of a large BigInteger not working correctly?	BigInteger bigInt = 10000000000000000000;  // myBigInt is a huge BigInt i want to find the Log of.\ndouble log;\nlog = BigInteger.Log(bigInt, 1000); //Find the Log\nSystem.Diagnostics.Debug.WriteLine(log.ToString());\nSystem.Diagnostics.Debug.WriteLine(((Int32)log).ToString());\nBigInteger bigIntRecreate;\n// unless log is an integer value it will round down and will not recreate to proper value\nbigIntRecreate = BigInteger.Pow(1000, (Int32)log);\nSystem.Diagnostics.Debug.WriteLine(bigInt.ToString("N0"));\nSystem.Diagnostics.Debug.WriteLine(bigIntRecreate.ToString("N0"));\nSystem.Diagnostics.Debug.WriteLine((bigInt - bigIntRecreate).ToString("N0"));	0
20702245	20701844	Multiple Concurrent readers without using lock in C#	public  class SecondClass\n{\n    private readonly List<string> _collection = new List<string>();\n    private string _lastFoldedString;\n    private const string delimiter = ",";\n\n    public virtual void AddString(string text)\n    {\n        // You'll need some synchronization type if more than one concurrent writer\n        // lock(_collection)\n        {\n           _collection.Add(text);\n           // Or Use String.Join, or just have a running appender\n           _lastFoldedString = _collection.Aggregate((i, j) => i + delimiter + j);\n        }\n    }\n\n    public override string ToString()\n    {\n        return _lastFoldedString;\n    }\n}	0
15995843	15987447	Multiple many to many inserts	public virtual ICollection<MemberComment> MemberComments { get; set; }	0
20979761	20975856	C# Wait for file extraction	Process proc = Process.Start("update.exe", "-s"); // extract in the silent mode\nproc.WaitForExit();\nFile.Delete("update.exe");	0
32618537	32618361	c# set active menu on a tree list from bottom up	bool FindAndSet(int id, List<Menu> menu)\n{\n    foreach (var m in menu)\n    {\n        if (m.MenuId == id)    // base case, this is the item we are looking for\n        {\n            m.IsActive = true;\n            return true;\n        }\n        else if (m.Children == null || m.Children.Count == 0)\n        {\n            return false;    // other base case, no more children\n        }\n        var found = FindAndSet(id, m.Children);    // recurse\n        if (found)                                 // if we found it in our descendants\n        {\n            m.IsActive = true;                     // set is active as we unwind\n            return true;\n        }\n    }\n    return false;\n}	0
28272262	28271585	Grouping records that haven't groups values	var weeks = new List<int>{1,2,3,4}\n\n    var q = from w in weeks\n        join rw in (\n            from r in table\n            group r by r.Week into g\n            select new {week = g.Key, count = g.Count()}) on w  equals rw.week into p\n        from x2 in p.DefaultIfEmpty()\n        select new {w, count = (x2 != null ? x2.count : 0)};	0
1579233	1579198	Transfer Byte array from server to browser	Response.Clear();\nResponse.AddHeader("Content-Length", fileContents.Length.ToString());\nResponse.AddHeader("Content-Disposition", "attachment; filename=FILENAME");\nResponse.OutputStream.Write(fileContents, 0, fileContents.Length);\nResponse.Flush();\nResponse.End();	0
11135409	11134789	Comparing strings based on similarity	// Define a helper function to split a string into its words.\nFunc<string, HashSet<string>> GetWords = s =>\n    new HashSet<string>(\n        s.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)\n        );\n\n// Pair up each string with its words. Materialize the second one as\n// we'll be querying it multiple times.\nvar aPairs = ads.Select(a => new { Full = a, Words = GetWords(a) });\nvar fPairs = feedItems\n                 .Select(f => new { Full = f, Words = GetWords(f) })\n                 .ToArray();\n\n// For each ad, select all the feeds that match more than one word.\n// Then just select the original ad and feed strings.\nvar result = aPairs.SelectMany(\n    a => fPairs\n        .Where(f => a.Words.Intersect(f.Words).Skip(1).Any())\n        .Select(f => new { AdHeadline = a.Full, MatchingFeed = f.Full })\n    );	0
20096130	20095321	TestContext is null when it is accessed from base class's virtual method	private static TestContext bingTestContext\n\n    [ClassInitialize]\n    public static void ClassInit(TestContext con)\n    {\n      bingTestContext = con;\n    }	0
33160869	33160837	how to generic type property	public struct MyStruct\n    {\n        public string StringPropertie;\n        public int IntPropertie;\n        public float floatPropertie;\n        public DateTime DatetimePropertie;\n        public bool boolPropertie;\n    }\n\n    public class MyClass\n    {\n        public MyClass()\n        {\n              MyStruct property ;\n              //...\n\n\n              string str = property.StringPropertie;\n\n        }\n   }	0
22917459	22916467	How to Add a Reference to a C# Script	string code = File.ReadAllText("SomeCode/MyScript.cs");\nCSScript.Evaluator.ReferenceAssembliesFromCode(code);       \ndynamic block = CSScript.Evaluator.LoadCode(code);\nblock.ExecuteAFunction();	0
5592990	5592950	Why do I get a FormatException when converting a string to a float?	float.Parse("6.59", CultureInfo.InvariantCulture)	0
3640399	3640367	How to use double quotes in a string when using the @ symbol?	(@"PREFIX rdfs: <" + rdfs + @">\n      SELECT ?s ?p ?o\n        WHERE { ?s ?p rdfs:Literal }\n              {?s rdfs:label ""date""}");	0
13705608	13705394	How to make a PredicateBuilder Not	public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expr)\n    {\n        return Expression.Lambda<Func<T, bool>>\n            (Expression.Not(Expression.Invoke(expr, expr.Parameters.Cast<Expression>())), expr.Parameters);\n    }	0
29752157	29752156	How to get field name in type safe enum	public string StateCode\n{\n    get\n    {\n        return GetType()\n            .GetFields(BindingFlags.Public | BindingFlags.Static)\n            .First(f => f.FieldType == typeof (Statuses) && ToString() == f.GetValue(null).ToString())\n            .Name;\n    }\n}	0
19773038	19772295	Rally Rest API - Returning false data	(FormattedID = abc123)	0
2702106	2701992	Turning on multiple result sets in an ODBC connection to SQL Server	Mars_Connection=yes	0
8933802	8859215	How to make a WPF program match the currently selected Windows Theme	Application.Current.Resources.MergedDictionaries	0
32252373	32252141	How to differentiate archive files from the regular files via .NET framework	bool isArchive(string filename)\n{\n    if (!string.IsNullOrEmpty(filename))\n    {\n        var lowercaseExt = System.IO.Path.GetExtension(filename).ToLowerInvariant();\n        return new[]{ ".zip", ".7z", ".rar"/*, ...*/}.Contains(lowercaseExt);\n    }\n    return false;\n}	0
13936807	13936640	How to capture a time interval while waiting for user input?	var timeToDisplay = Stopwatch.ElapsedMilliseconds > 10000 ? 10 : Stopwatch.ElapsedMilliseconds/1000	0
6746940	6746884	Declaration of a hashtable with key, value	var dictionary = new Dictionary<string, string> {\n    {"key1", "value1"},\n    {"key2", "value2"}\n};	0
26016090	26015666	Issue with adding a new node in XML	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            XDocument document = XDocument.Load(@"C:\Users\amit\SkyDrive\code\WebApplication1\ConsoleApplication1\xml.xml");\n            XElement root = new XElement("sentiment");\n            root.Value = "3";\n            root.Add(new XAttribute("word", "napustiti"));\n            XNamespace nsSys = "RecnikSema.xsd";\n            document.Element(nsSys + "dictionary").Element(nsSys + "sentiments").Add(root);\n            document.Save("c:\newFile.xml");\n        }\n    }\n}	0
29354682	29354663	How can I get rid of dashes in Visual Studio	Edit -> Advanced -> View White Space	0
16874537	16862416	How to find out the right encoding of a webservice respose?	string json = "Podcast del programa de Radio El D&iacute;a. Aqu&iacute; encontrar&aacute;s d&iacute;a a d&iacute;a";\nstring decoded = HttpUtility.HtmlDecode(json);	0
345109	345025	Select unique XElements (by attribute) with a filter using LinqToXml	var distinctOwners = (from item in itemsElement.Element("item") \n where itemElements.Attribute("cat") == 1 \nselect item.Attribute("owner")).Distinct();	0
3027068	3027064	Treat multiple IEnumerable objects as a single IEnumerable	rootSetOfObjects.SelectMany(o => o.childSetOfStrings)	0
18186558	18186521	c# - check for null in a collection initializer	var array = new ArrayList\n{\n      inputJson["abc"] != null ? inputJson["abc"].ToString() : "",\n      inputJson["def"] != null ? inputJson["def"].Value<float>() : 0.0F,\n      inputJson["ghi"] != null ? inputJson["ghi"].Value<float>() : 0.0F\n};	0
4570016	4569786	How do I invoke a method with two arguments (where one of them is params)?	Download(MyEnum.All, "a", "b", "c")	0
15835932	15835533	How to get the value of an input box of the webbrowser control in WPF?	var document = (IHTMLDocument3) webbrowser.Document;\nvar value =\n    document.getElementsByName("username")\n            .OfType<IHTMLElement>()\n            .Select(element => element.getAttribute("value"))\n            .FirstOrDefault();	0
13175654	13175615	How can I implement a login wall for expired or inappropriate pages?	FormsAuthentication.SetAuthCookie(txtUserName.Text, true);\nResponse.Redirect("pagename.aspx");	0
25519128	25519048	How to get the InnerHTML of a div in C#	HtmlWeb web = new HtmlWeb();\nHtmlDocument dc = web.Load("Your_Url");\nvar s = dc.DocumentNode.SelectSingleNode("//div[@id='div_id']").InnerHtml;	0
27764151	27764072	Tree structure with parents and children	public class Node\n{\n    private Node _parent;\n    private List<Node> _children = new List<Node>();\n\n    public Node(Node parent)\n    {\n        _parent = parent\n    }\n\n    public ReadOnlyCollection<Node> Children\n    {\n        get { return _children.AsReadOnly(); }\n    }\n\n    public void AppendChild(Node child)\n    {\n        // your code\n    }\n\n    public void RemoveChild(Node child)\n    {\n        // your code\n    }\n}	0
16464337	16464219	How to get Enum object by value in C#?	ShipmentStatus shipped = (ShipmentStatus)System.Enum.GetValues(typeof(ShipmentStatus)).GetValue(1);	0
11390433	11390389	How to create a reference to System.Array holding strings in C#	// Startup modules \nArray modules = new string[3] \n{\n    "SignalGenerator --local",\n    "DummySignalProcessing --local",\n    "DummyApplication --local"\n};\nok_conn = bci.StartupModules(ref modules);	0
4445830	4445655	how can i C# application call a java application	svcutil.exe	0
10938082	10905270	Get HtmlAgilityPack Node using exact HTML search or Converting HTMLElement to HTMLNode	HtmlNode n = doc.DocumentNode.Descendants().Where(n => n.OuterHtml.Equals(text, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();	0
12451952	12451416	How to detect when the control has moved to the view in MonoTouch?	public override void ViewWillAppear(bool animated) {}	0
2281386	2281345	Two arguments for Process in C#	Arguments = "\"" + serverNameTextBox + "\" \"" + pathToSql + "\"",	0
25359644	25359467	How to pass argument to Event Handler in Xamarin IOS	public event EventHandler<string> ValueChanged;\n\nvoid ResponseCompleted(object sender, CommonCode.ResponseEventArgs e){\n    this.InvokeOnMainThread (delegate { \n\n    var handler = ValueChanged;\n    if (handler != null)\n        handler(this, e.ResponseData);\n    });\n}\n\nrelatedDataSource.ValueChanged += (s, responseData) => {\n    //Your data is in responseData variable\n}	0
24575958	24575733	Getting the parentDirectory of a file in a unc path c# 2010	string path = "\\MyServer\\MySharedDrive\\MyDirectory\\MySubDirectory\\Myfile.csv";\nDirectoryInfo directory = new DirectoryInfo(Path.GetDirectoryName(path));\nstring finalPath = Path.Combine(directory.Parent.FullName, "myNewFile.csv"	0
7029149	7029059	join on multiple criteria	var TheOutput = (from patients in PatientList\n                 where (from prescrips in MyDataContext.Prescriptions\n                        where prescrips.PatientID = patients.PatientID\n                          && prescrips.PrescripStatus == 5\n                        select prescrips).Any()\n                   &&!(from prescrips in MyDataContext.Prescriptions\n                        where prescrips.PatientID = patients.PatientID\n                          && (prescrips.PrescripStatus == 4 || prescrips.PrescripStatus == 6)\n                        select prescrips).Any()\n\n                 select patients);	0
27181967	27181555	Put value in specific index to Char array then copy specific element of an Char array To another Char array in C#	static void Main(string[] args)\n        {\n            char[] ptrArr = new[] { '0','1','0','1','0','1','0','1' };\n            char[] ptrArr2=  new char[0];\n            List<char> ptrArr2temp = new List<char>();\n\n            for (int i = 0; i < ptrArr.Length; i++)\n            {   \n                ptrArr2temp.Add(ptrArr[i]);\n            }\n\n            for (int i = 0; i < ptrArr.Length; i++)\n            {\n                int internalIndex = ((int)(Math.Pow(2, i))) - 1;\n                if (ptrArr2temp.Count > internalIndex)\n                {\n                    ptrArr2temp.Insert(internalIndex, '*');\n                }\n            }\n            ptrArr2 = ptrArr2temp.ToArray();          \n        }	0
8189176	8188987	Testing that a property is read-only using NUnit	typeof(SomeType).GetProperty("ReadOnlyProperty").CanWrite == false	0
15587004	15544182	keyboard event works only once	[DllImport("user32.dll")]\nstatic extern uint keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);\npublic static void KeyDown(System.Windows.Forms.Keys key)\n{\n      keybd_event((byte)key, 0x45, 0x0001 | 0, 0);\n}\n\npublic static void KeyUp(System.Windows.Forms.Keys key)\n{\n      keybd_event((byte)key, 0x45, 0x0001 | 0x0002, 0);\n}	0
23303798	23303775	Double to string with max one digit after dot	double value = 1715.0;\nstring result = (value / 1000.0).ToString("F1", CultureInfo.InvariantCulture) + "K";	0
23842687	23842164	C# Reading any file in Bytes	DialogResult dr = openFileDialog1.ShowDialog();\n        if (dr == DialogResult.OK)\n        {\n            string filename = openFileDialog1.FileName;\n\n            int len= openFileDialog1.FileName.Length;\n            byte[] ATM = File.ReadAllBytes(filename);\n        }	0
15772850	15769629	Refresh only update panel on parent from pop-up window	window.opener.document.getElementById('Container').onclick();	0
21575394	21454621	Add/Remove element from XML file	public static List<string> GetGroupsForGivenUser(XDocument xdoc, string userId)\n        {\n            var users = (from user in xdoc.Descendants("User")\n                         let xElement = user.Element("ID")\n                         where xElement != null && xElement.Value == userId.ToUpper()\n                         select new\n                         {\n                             Id = xElement.Value,\n                             Ldap = user.Elements("LDAP-Groups")\n\n                         }).ToList();\n\n            return (\n                    from user in users\n                    from ldaps in user.Ldap\n                    from ldap in ldaps.Elements("Group")\n                    select ldap.Value\n                ).ToList();\n        }	0
13697878	13697734	found string at exact location in the file	using (var reader = File.OpenText("test.txt"))\n {\n     char[] buffer = new char[16 * 1024];\n     int charsLeft = location;\n     while (charsLeft > 0)\n     {\n         int charsRead = reader.Read(buffer, 0, Math.Min(buffer.Length,\n                                                         charsLeft));\n         if (charsRead <= 0)\n         {\n             throw new IOException("Incomplete data"); // Or whatever\n         }\n         charsLeft -= charsRead;\n     }\n     string line = reader.ReadLine();\n     bool found = line.StartsWith(targetText);\n     ...\n }	0
12743695	12737194	One to Many mapping with an intermediate table	public class CustomerAddressMap : ClassMap<CustomerAddress>\n{\n    public CustomerAddressMap()\n    {\n        Table("CustomerAddress");\n\n        Id(x => x.CustomerAddressId);\n        Map(x => x.FromDate).Not.Nullable();\n        Map(x => x.ToDate);\n        References(x => x.Customer, "CustomerId");\n        References(x => x.Address, "AddressId");\n    }\n}	0
1380846	1380839	How do you get the file size in C#?	FileInfo.Length	0
32780785	32779907	Objectlistview how to change the text in the group header?	olv.AboutToCreateGroups += delegate(object sender, CreateGroupsEventArgs args) {\n    foreach (OLVGroup olvGroup in args.Groups) {\n        int totalTime = 0;\n\n        foreach (OLVListItem item in olvGroup.Items) {\n            // change this block accordingly\n             MyRowObjectType rowObject = item.RowObject as MyRowObjectType;\n             totalTime += rowObject.MyNumericProperty;\n            // change this block accordingly\n        }\n\n        olvGroup.Header += String.Format(" (Total time = {0})", totalTime);\n    }\n};	0
17847729	17847399	Converting string to a line of command? c# mac	object[] parametersArray = new object[] { "Hello" };\nMethodInfo writeLine = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(string)});\nwriteLine.Invoke(null, parametersArray)	0
18061776	18060201	Word to PDF conversion fails on machines other than my development PC	object outputFileName = wordFile.FullName.Replace(".docx", ".pdf");	0
8950566	8950493	Converting XmlDocument to Dictionary<string, string>	XElement xdoc = XElement.Load("yourFilePath");\nDictionary<string, string> result = (from element in xdoc.Elements() select new KeyValuePair<string, string>(element.Name.ToString(), element.Value)).ToDictionary(x => x.Key, x => x.Value);	0
31130477	31129989	Obtaining HDD Serial Number via Drive Letter using WMI query in C#	public static string GetSerialFromDrive(string driveLetter)\n{\n    try\n    {\n        using (var partitions = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_LogicalDisk.DeviceID='" + driveLetter +\n                                            "'} WHERE ResultClass=Win32_DiskPartition"))\n        {\n            foreach (var partition in partitions.Get())\n            {\n                using (var drives = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" +\n                                                        partition["DeviceID"] +\n                                                        "'} WHERE ResultClass=Win32_DiskDrive"))\n                {\n                    foreach (var drive in drives.Get())\n                    {\n                        return (string)drive["SerialNumber"];\n                    }\n                }\n            }\n        }\n    }\n    catch\n    {\n        return "<unknown>";\n    }\n\n    // Not Found\n    return "<unknown>";\n}	0
32854586	32854203	need to extract data from xml contents	var xml = new XmlDocument();\nxml.LoadXml(@"\n    <myXml>\n        <Member AC_NO='1254' \n                PART_NO='12' \n                SLNOINPART='416' \n                Fm_NameEN='Pramod KUMAR' \n                SEX='M' \n                AGE='39' \n                RLN_TYPE='F' \n                Rln_Fm_NmEn='Dharmanath Singh' \n                IDCARD_NO='000310' /> \n    </myXml>");\n\n// Watch out: XPath expressions are case sensitive!\nvar member = (XmlElement)xml.SelectSingleNode("//myXml/Member");\n\n// Display all attributes\nforeach (XmlAttribute attribute in member.Attributes)\n    Console.WriteLine("{0} = {1}", attribute.Name, attribute.Value);\n\n// Display a specific attribute\nConsole.WriteLine(member.GetAttribute("AC_NO"));	0
16788667	16788602	Add new row to gridview that comes from a stored procedure	DataTable dt = GridView1.tables[0];\nDataRow dr = new DataRow();\nDataTable.Rows.InsertAt(dr, 5);\nDataTable.AcceptChanges();\n\ngv_list.DataSource = dt;\ngv_list.DataBind();	0
4257398	4257372	How to force garbage collector to run?	System.GC.Collect()	0
18684480	18684122	EF Sum between 3 tables	int customerId = 1;\nint productId = 1;\nvar query = from orderLine in db.OrderLines\n            join order in db.Orders on orderLine.OrderId equals order.Id\n            where order.CustomerId == customerId && orderLine.ProductId == productId\n            group orderLine by new { order.CustomerId, orderLine.ProductId } into grouped\n            select grouped.Sum(g => g.Quantity);\n\n// The result will be null if there are no entries for the given product/customer.\nint? quantitySum = query.SingleOrDefault();	0
5137143	5131156	Updating Score Label using ListBox	string GetPlayers(){...}	0
15680696	15680662	json to object, how should my object be like?	public class NodeDataArray\n{\n    public string key { get; set; }\n    public string type { get; set; }\n    public string devicename { get; set; }\n    public string imageUrl { get; set; }\n    public string loc { get; set; }\n}\n\npublic class RootObject\n{\n    public string @class { get; set; }\n    public List<NodeDataArray> nodeDataArray { get; set; }\n    public List<object> linkDataArray { get; set; }\n}	0
2030865	2030847	Best way to read a large file into a byte array in C#?	return File.ReadAllBytes(fileName);	0
33097724	33097608	Filter binding source by like syntax with integer value	tbCarBindingSource.Filter =  string.Format("convert(Car_ID, 'System.String') Like '%{0}%' ",Txt_Car_ID_ForAll.Text);	0
22387288	22387032	SingleOrDefault asynchronous in .net application	Enumerable.SingleOrDefault	0
104664	104603	Accessing a Collection Through Reflection	if (item is IEnumerable)\n{\n    foreach (object o in (item as IEnumerable))\n    {\n\n    }\n} else {\n   // reflect over item\n}	0
1247423	1247398	C# XmlDocument SelectNodes	XDocument doc = XDocument.Load("foo.xml");\nXNamespace ns = "bar";\nvar results = doc.Descendants(ns + "result");\n\nforeach (var result in results)\n{\n    ...\n}	0
18636318	18635963	ASP.NET uploading a file to Amazon S3	using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))\n                    {\n\n                         var stream = new System.IO.MemoryStream();\n                         originalBMP.Save(stream, ImageFormat.Bmp);\n                         stream.Position = 0;\n\n                        PutObjectRequest request = new PutObjectRequest();\n                        request.InputStream = stream;\n                        request.BucketName="MyBucket";\n                        request.CannedACL = S3CannedACL.PublicRead;\n                        request.Key = "images/" + filename;\n                        S3Response response = client.PutObject(request);\n                    }	0
5039800	5039403	Aero-Style Windows Explorer Bar for .NET	private void toolStrip1_Paint(object sender, PaintEventArgs e) {\n      e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(227, 239, 240)), 0, 17, toolStrip1.Width, toolStrip1.Height);\n    }	0
720260	720250	Using value from related table in LINQ where clause	var query = from contact in dc.Contacts            \n            where contact.Phones.Any(p => p.PhoneNumber == "5558675309")            \n            select contact;	0
17230898	17230141	How to use one binding for multiple web services of the same type?	var myBinding = new BasicHttpBinding();\n\nvar urlList = GetUrlsFromCustomConfigFile();\n\nvar factoriesOfTheSameType = new List<ChannelFactory<IMyService>>();\n\nforeach(var url in urlList)\n{\n    var myEndpoint = new EndpointAddress(url);\n    var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint);\n    factoriesOfTheSameType.Add(myChannelFactory);\n}	0
2340359	2340297	How divide a string into array	static void Main(string[] args)\n    {\n        string str = "{[\"a\",\"English\"],[\"b\",\"US\"],[\"c\",\"Chinese\"]}";\n        foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(str, @"((\[.*?\]))"))\n        {\n            Console.WriteLine(m.Captures[0]);\n        }\n    }	0
26550168	26545680	how to set DataGridViewButtonCell BackColor using htmlColor?	private void dgvMenuColors_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) \n{ \nforeach (DataGridViewRow row in dgvMenuColors.Rows) \n{ \nrow.DefaultCellStyle.BackColor = ColorTranslator.FromHtml(row.Cells[1].Value.ToString()); \n} \n}	0
9531201	9530465	Handle json error message from REST API through HTTPWebRepsonse	try\n{\n   res = (HttpWebResponse)request.GetResponse();\n   // handle successful response\n   ...\n}\ncatch(WebException ex)\n{\n    if (ex.Status == WebExceptionStatus.ProtocolError)\n    {\n       var response = (HttpWebResponse)ex.Response;\n       // use the response as needed - in your case response.StatusCode would be 403\n       // and body will have JSON describing the error.\n       ..  \n    }\n    else\n    {\n       // handle other errors, perhaps re-throw\n       throw;\n    }\n}	0
1379045	1379009	How to make next step of a string. C#	"a" == 1 -> step("a") == step(1) == 1 + 1 == 2 == "b"	0
26149970	26149255	Selecting entities by a list of conditions	var ownerId = 1;\nvar query =\n   from request in context.ParkingRequests\n   join vehicle in context.Vehicles on request.RegisteredVehicleId equals vehicle.Id\n   where vehicle.ownerId == ownerId\n   select request;	0
4593044	4592992	Conversion failed when converting datetime from character string	m_Command.CommandText = "SELECT ref_dig_pumpcontrol, ref_energy, ref_datetime FROM [molisoftSchema].[Refresh] WHERE ref_pump_id = @id AND ref_datetime BETWEEN @start AND @end ORDER BY ref_datetime ASC";\nm_Command.Parameters.AddWithValue("@id", pump.ID);\nm_Command.Parameters.AddWithValue("@start", start);\nm_Command.Parameters.AddWithValue("@end", end);	0
1600187	1600094	How do you set CacheMode on an element programatically?	image.CacheMode = new BitmapCache();	0
14417206	14417091	10% margin on popup	.modal {\n    display: block;\n    width: 90%;\n    height: 90%;\n    margin: auto;\n}	0
10071291	10071102	Textfield in webservice 	[WebMethod]\npublic string GetEmps(DateTime inputDate)\n{\n    // create a parameterized query\n    string getdays = "Select Emp from WorkingDaysinfo Where date = @inputDate";\n\n    con = new MySqlConnection(conString);\n    con.Open();\n    MySqlCommand cmd = new MySqlCommand(getdays, con);\n    // pass the parameter value \n    cmd.Parameters.Add(new SqlParameter("inputDate", inputDate);\n\n    // rest of the code follows\n    ..	0
33709760	33709699	Grid control can't cover the whole page and leaves a space at the top	var applicationView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();\napplicationView.SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);	0
21503729	21503618	Remove items from list where a match is found	ListOfItemsToControl = ListOfItemsToControl.Where(l => !lstRemoveItems.Any(r => r.sItemName == l.sItemName)).ToList();	0
20760907	20760893	How to check value overlap using LINQ	int checkRange = (from globalSetting in db.GlobalSetting\n                  where ((globalSetting.MinValue >= minValue \n                          && globalSetting.MinValue <= maxValue) \n                          || (globalSetting.MaxValue >= minValue \n                                && globalSetting.MaxValue <= maxValue))\n                  select globalSetting)\n                  .Count();	0
7729852	7729774	Loop from x1,y1 to x2,y2, no matter in which order they are	Point p1 = new Point(1, 1);\nPoint p2 = new Point(3, 3);\n\nint dx = Math.Sign(p2.X - p1.X);\nint dy = Math.Sign(p2.Y - p1.Y);\n\nfor (int x = p1.X; x != p2.X + dx; x += dx)\n{\n    for (int y = p1.Y; y != p2.Y + dy; y += dy)\n    {\n        Console.WriteLine("{0} {1}", x, y);\n    }\n}	0
153310	153266	How to cast a number to a byte?	byte b = (byte) 0x10;	0
31455585	31455373	Parse Xml node with same name	Dictionary<string, string> mapping = new Dictionary<string, string>()\n{\n    {"0","Hp"},\n    {"3","Mp"},\n    {"20","Attack"},\n    {"21","Defence"},\n    {"22","Speed"},\n    {"28","Dexterity"},\n    {"26","Vitality"},\n    {"27","Wisdom"},\n};\n\nvar result = XDocument.Load(filename)\n             .Descendants("ActivateOnEquip")\n             .Select(x => new { stat = x.Attribute("stat").Value, amount = x.Attribute("amount").Value })\n             .ToList();\n\nforeach(var item in result)\n{\n    Console.WriteLine( mapping[item.stat] + ": " + item.amount);\n}	0
30938201	30938139	How can i calculate the difference between a stored DateTime.Now and a current DateTime.Now?	var elapedSeconds = (DateTime.Now-dt).TotalSeconds;	0
31307934	31307878	Extract exact string within a string and append	var uriString = "http://www.somesomesome.com/ShowProduct.aspx?ID=232";\nvar uri = new Uri(uriString);\nvar pathQuery = uri.PathAndQuery; //ShowProduct.aspx?ID=232	0
28686209	28685263	LINQ to return list of Object filtered on a property of a Child object in nested List<>	//creating a new list \nvar answer = (from p in ParentList\n             select new Stage(){\n             Name = p.Name,\n             MyEvaluations = p.MyEvaluations.Where(e => e.ResultType == enumResultType.B).ToList()\n             }).ToList();\n\n//in place replacement               \nParentList.ForEach(p => p.MyEvaluations = p.MyEvaluations.Where(e => e.ResultType == enumResultType.B).ToList());	0
22643952	22643906	DateTime fails to parse 24:00:00 in the HH:mm:ss format	DateTime ParseWithTwentyFourthHourToNextDay (string input) {\n    var wrapped = Regex.Replace(input, @"24:(\d\d:\d\d)$", "00:$1");\n    var res = DateTime.ParseExact(wrapped, "yyyy-MM-dd HH:mm:ss", null);\n    return wrapped != input\n        ? res.AddDays(1)\n        : res;\n}	0
3859408	3859094	How to "Add" two bytes together	var r = (high << 8) | low;	0
27257557	27257346	C# How to save values from a listbox into settings.settings	String value = Settings.Default.Setting1;	0
2427055	2427015	How to do Python's zip in C#?	public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(\n        this IEnumerable<TFirst> first,\n        IEnumerable<TSecond> second,\n        Func<TFirst, TSecond, TResult> func);	0
4682579	4682406	linq query to find distinct combinations of list items taking 2 at a time c#	var exams = timeTable.Exams.ToList();\n\nvar com = exams.Select(x => exams.Where(y => exams.IndexOf(y) > exams.IndexOf(x))\n    .Select(z => new List<Exam> {x, z}))\n    .SelectMany(x => x);	0
17661906	17661558	Access denied - Trying to delete all files in a folder	//you'll need to add this.\nusing System.Runtime.InteropServices;\n\n[DllImport("shell32.dll")]\npublic static extern void SHAddToRecentDocs(ShellAddToRecentDocsFlags flag, IntPtr pidl);\n\npublic enum ShellAddToRecentDocsFlags\n{\n    Pidl = 0x001,\n    Path = 0x002,\n}\n\n//then call this from your method\nSHAddToRecentDocs(ShellAddToRecentDocsFlags.Pidl, IntPtr.Zero);	0
22379760	22379040	How to use GroupBy and Sum in LINQ?	var Rows = allData.SelectMany(u => u._rows.Select(t => new\n{\n  OA = t[4],\n  CD = t[5],\n  PD = t[0],\n  DS = Convert.ToInt32(t[9]),\n  CS = Convert.ToInt32(t[10])\n}))\n// group by the combination of CD, OA, and PD\n.GroupBy(x => new { x.CD, x,OA, x.PD } )\n// sum DS and CS within each group\n.Select (g => new {g.Key.CD, \n                   g.Key.OA, \n                   g.Key.PD,  \n                   DS = g.Sum(u=> u.DS), \n                   CS = g.Sum(u=> u.CS) \n                  } ) \n.OrderBy(u => u.CD)\n.ThenBy(u => u.OA)\n.ThenBy(u => u.PD)	0
5000686	4998567	How to implement a-form-inside-a-form with runtime embedded forms switching?	static public void ReplaceControl(Control ToReplace, Form ReplaceWith) {\n        ReplaceWith.TopLevel=false;\n        ReplaceWith.FormBorderStyle=FormBorderStyle.None;\n        ReplaceWith.Show();\n        ReplaceWith.Anchor=ToReplace.Anchor;\n        ReplaceWith.Dock=ToReplace.Dock;\n        ReplaceWith.Font=ToReplace.Font;\n        ReplaceWith.Size=ToReplace.Size;\n        ReplaceWith.Location=ToReplace.Location;\n        ToReplace.Parent.Controls.Add(ReplaceWith);\n        ToReplace.Visible=false;\n    }	0
19146274	19146243	How to properly use the IF Statement	IsValid()	0
20925439	20925287	Get a list of files that don't contain something from another list	var exclusionList = new List<string> { "string1", "string2", "string3" };\n\n        var files = Directory.GetFiles("C:\\mypath", "*.xml")\n                        .Where(f => !exclusionList.Any(s => f.Contains(s)))\n                        .ToList();	0
16096250	16096160	Find Missing IDs From List<int> in DataTable	var jobIdList = new HashSet<int>(from i in EntryItems select i.JobID.Value);\nvar rows = JobBLL.JobsExist(jobIdList).AsEnumerable();\n\nvar foundIds = (from x in rows select x.Field<int>("JobID")).ToList();\nvar missingIds = jobIdList.Except(foundIds);	0
3069162	3069143	How can i use listDictionary?	ListDictionary ld = new ListDictionary();\nforeach (DataColumn dc in dTable.Columns)\n{\n     MessageBox.Show(dTable.Rows[0][dc].ToString());\n\n     string value;\n     if (int.TryParse(dTable.Rows[0][dc].ToString(), out QuantityInt))\n           value = "integer";\n     else if(double.TryParse(dTable.Rows[0][dc].ToString(), out QuantityDouble))\n           value="double";\n      else\n           value="nvarchar";\n\n     ld.Add(dc.ColumnName, value);\n}	0
6270026	6269995	C# Formating Output for a File?	var line1 = String.Format("{0,20}", s);	0
13838900	13838846	how to write stored procedure in c# if it has more than 300 lines	using (Stream stream = Assembly.GetExecutingAssembly()\n                               .GetManifestResourceStream("Your assembly namespace" + "file.sql"))\nusing (StreamReader reader = new StreamReader(stream))\n{\n    string result = reader.ReadToEnd();\n}	0
14577594	14574904	Starting an application from NUNIT Test	using System.Diagnostics;\nusing System.Threading;\n\n[Test]\npublic void logtest()\n{\n    // ...\n    Process proc = Process.Start(@"c:\windows\system32\notepad.exe");\n    if ( null == proc )\n        Assert.Fail("Could not start process, maybe an existing process has been reused?");\n    Thread.Sleep(50000);\n    proc.Kill();\n    // ...\n}	0
29967683	29961924	Building custom where clause with dynamic column input LINQ	var dynamicQuery = dt.AsEnumerable(); //to add dynamic where clause, first convert datatable to enumerable.\n                    foreach(string name in columnName) //maintaining column names in a seperate list, as list would be dynamic\n                    {\n                        dynamicQuery = dynamicQuery.Where(r => (Convert.ToDecimal(r[name]) <= list[columnName.IndexOf(name)]));\n                    }\n                    int count=dynamicQuery.Count();	0
13540183	13540143	Check if two list have same elements in a single evaluation	if(Foo.Intersect(Bar).Any())\n{\n    //Do Something\n}	0
12822797	12787852	How can I display an image and add it as an attachment to an email	System.IO.MemoryStream ms = new System.IO.MemoryStream(insuranceClaim.Signature, 0, insuranceClaim.Signature.Length);\nSystem.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();\ncontentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;\ncontentType.Name = "signature.jpg";\nSystem.Net.Mail.Attachment imageAttachment = new System.Net.Mail.Attachment(ms, contentType);\nmailMessage.Attachments.Add(imageAttachment);\n\nSystem.IO.MemoryStream embeddedMs = new System.IO.MemoryStream(insuranceClaim.Signature, 0, insuranceClaim.Signature.Length);\nSystem.Net.Mail.LinkedResource signature = new System.Net.Mail.LinkedResource(embeddedMs, new System.Net.Mime.ContentType("image/jpeg"));\nsignature.ContentId = "CustomerSignature";\nSystem.Net.Mail.AlternateView aView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailMessage.Body, new System.Net.Mime.ContentType("text/html"));\naView.LinkedResources.Add(signature);\nmailMessage.AlternateViews.Add(aView);	0
2471893	2470372	How to change Krypton label's color to red in C#	public virtual Color BackColor { get; set; }	0
19428877	19428578	DataGrid sample in WPF using visual studio 2012	private void Delete_Click(object sender, RoutedEventArgs e)\n{\n\n    if (dgsample.SelectedItem != null)\n    {\n        var usr = dgsample.SelectedItem as User;\n\n        if (usr != null)\n        {\n            var deleteMe = Users.FirstOrDefault(us => us.Id == usr.Id);\n            if (deleteMe != null)\n            {\n                Users.Remove(deleteMe);\n            }\n            else\n            {\n                MessageBox.Show(string.Format("User with Id {0} not found to delete", deleteMe.Id);\n            }\n        }\n        else\n        {\n            MessageBox.Show("Unknown type in datagrid")\n        }\n    }\n    else\n    {\n        MessageBox.Show("No user selected to delete");\n    }\n\n}	0
5417155	5417125	How to get Current User who's accessing ASP.net app?	Membership.GetUser()	0
31207460	31207350	How to check if an element is already exists in DataGrid	if (((Teams.Club_Information)grid.Items[i]).name == reader["name"])	0
21950333	21950093	String calculator	using System.Data;//import this namespace\n\n string math = "100 * 5 - 2";\n string value = new DataTable().Compute(math, null).ToString();	0
11665028	11664952	How to change value of XML document in linq by an attribute value?	XAttribute attr = doc.Descendants(ns + "SiEventSchedule").Select(x => x.Attribute("deleteStart")).First();\n        attr.SetValue(attr.Value.Replace(oldValue, newValue));	0
15020137	15019412	show an array of data in windows phone app	var scrollViewer = new ScrollViewer();\nscrollViewer.Content = txt;	0
24061233	24018735	How to remove 1px space between ListViewItem	private void lvMain_MouseUp(object sender, MouseEventArgs e)\n    {\n        if (lvMain.SelectedItems.Count == 0 && (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right))\n        {\n            ListViewItem lvi = lvMain.GetItemAt(e.X, e.Y);\n\n            if (lvi == null)\n            {\n                // Workaround for 1px space between items\n                lvi = lvMain.GetItemAt(e.X, e.Y - 1);\n            }\n\n            if (lvi != null)\n            {\n                lvi.Selected = true;\n            }\n        }\n    }	0
20007621	20007381	Console app scheduled task run two different ways	void Main(string[] args)\n{\n    var firstArg = args.FirstOrDefault();\n    if (firstArg == "option1")\n    {\n        // do stuff\n    }\n    else if (firstArg == "option2")\n    {\n        // do other stuff\n    }\n}	0
7193326	7193015	Finding numbers in a string using C# / Regex	string resultString = null;\ntry {\n    Regex regexObj = new Regex(@"ID (?<digit>\d+)$");\n    resultString = regexObj.Match(subjectString).Groups["digit"].Value;\n} catch (ArgumentException ex) {\n// Syntax error in the regular expression\n}	0
12687476	12679710	Search for a title in LDAP using C#?	search.Filter = "(&(objectClass=person)(sn=Smith)(givenname=John)(title=Janitor))";	0
27378911	27378696	replace words /strings by bold word/string	public string MakeBold(string text, string[] splitwords)\n    {\n        string returnValue = text;\n        foreach (var word in splitwords)\n        {\n            returnValue = returnValue.Replace(word, @"\b" + word + @"\b0");\n        }\n        var finalString = new StringBuilder();\n        finalString.Append(@"{\rtf1\ansi");\n        finalString.Append(returnValue);\n        finalString.Append(@"}");\n        return finalString.ToString();\n    }	0
2057505	2057469	How can I display a pointer address in C#?	Console.WriteLine(new IntPtr(cp));	0
22609054	22609035	Return value from a method if the method throws an exception	var i = 5;\n\ntry\n{\n    i = MyMethodThatThrowsAnException();\n}\ncatch\n{\n    // at this point, the i variable still equals 5.\n}	0
1586772	1574317	How to version a performance counter category?	var missing = counters\n.Where(counter => !PerformanceCounterCategory.CounterExists(counter.Name, CategoryName))\n.Count();\n\nif (missing > 0)\n{\nPerformanceCounterCategory.Delete(CategoryName);\n\nPerformanceCounterCategory.Create(\nCategoryName,\nCategoryHelp,\nPerformanceCounterCategoryType.MultiInstance,\nnew CounterCreationDataCollection(counters.Select(x => (CounterCreationData)x).ToArray()));\n}	0
4452508	4452334	Downloading a 50 MB file from SQL Server in ASP.NET stops in middle for a while	int ChunkSize = 262144;	0
7248894	7248827	How do I Fill a Listbox with a List using a datatable as the source	public class Employee\n{\n    public string LoginId { get; set;}\n}	0
1688023	1688000	How can I calculate how many nights are there in a date range?	(Checkout.Date - Checkin.Date).Days	0
19643149	19643001	How to route EVERYTHING other than Web API to /index.html	routes.MapRoute(\n    name: "Default",\n    url: "{*anything}",\n    defaults: new { controller = "Home", action = "Index" }\n);	0
11968953	11966295	Filling DataTable from GridView in C#	I solved like this\n           if (myGridView.Rows.Count > 0)\n            {\n                var dt = new DataTable();\n                dt.Columns.Add("Column1", typeof(string));\n                dt.Columns.Add("Column2", typeof(Int64));\n                dt.Columns.Add("Column3", typeof(string));\n\n                foreach (GridViewRow row in gd_endYearSchool.Rows)\n                {\n                    var id = row.Cells[1].Text;\n         //for find textbox\n          var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;\n                    int nrord = 0;\n                    if (tb1 != null)\n                    {\n                        var ord = tb1.Text;\n                        if (!Int64.TryParse(ord, out nrord))\n                        {\n                            nrord = 0;\n                        }\n                    }\n                    var text=row.Cell[3].text;\n                    dt.Rows.Add(id,nrord,text);\n                }\n\n            }	0
15880512	15879829	Inserting information from one webpage to two different tables	Session["FirstName"] = FirstNameTextBox.Text;\nSession["LastName"] = LastNameTextBox.Text;	0
28811147	28810803	EF Code First Many-to-Many with Additional Foreign Key	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n     base.OnModelCreating(modelBuilder);\n\n     modelBuilder.Entity<User>().HasMany(b => b.Tenants).WithMany(c => c.Users);\n     modelBuilder.Entity<User>().HasOptional(b => b.CurrentTenant);\n }	0
14573115	14573085	Attaching and Updating with DateTime properties	public void Update(Location location, DateTime locationLastUpdated)\n{\n    using (var context = new EfContext())\n    {\n        location.LastUpdated = locationLastUpdated;\n        context.Locations.Attach(location);\n        context.Entry(location).State = EntityState.Modified;\n        context.SaveChanges();\n    }\n}	0
21324298	21323992	C# Get information from database	SqlDataReader reader = cmd.ExecuteReader();\n    while (reader.Read())\n    {\n        var memberName = reader[0].ToString();\n        var lbl = new Label();\n        Controls.Add(lbl); \n        lbl.Text = memberName;\n    }	0
27157225	27157107	Need to divide string by half. Insert another string between both sides	string s1 = string.Join("",izmers1); // "qwer";\n        string s2 = string.Join("",izmers2); // "TYUI";\n        string result = s1.Insert(s1.Length / 2, s2);	0
20502867	20501622	Load Managed C++ Dll from Unmanaged C Dll?	extern "C" __declspec( dllexport ) void __stdcall PureExportC(\n                                                    const wchar_t* param\n)\n{\n    CSharpAssemblyNamespace::CSharpWorker worker;\n    worker.DoWork( gcnew String(param) );\n}	0
29115219	29115146	how to get the last insert ID in linq	// I suppose that the corresponding's property name is ID.\n// If it is not, you should change it correspondingly.\nstud.studentID = u.ID;	0
9927606	9926716	Making a Toolstripcontainer panel work like an MDI parent	public partial class Form1 : Form {\n\n  public Form1() {\n    InitializeComponent();\n\n    this.IsMdiContainer = true;\n    ToolStripPanel leftPanel = new ToolStripPanel() { Dock = DockStyle.Left };\n    ToolStripPanel topPanel = new ToolStripPanel() { Dock = DockStyle.Top };\n    this.Controls.Add(leftPanel);\n    this.Controls.Add(topPanel);\n\n    ToolStrip ts = new ToolStrip() { Dock = DockStyle.Fill };\n    ToolStripButton tsb = new ToolStripButton("Test", SystemIcons.Application.ToBitmap());\n    ts.Items.Add(tsb);\n\n    topPanel.Controls.Add(ts);\n  }\n}	0
2033431	2032808	How to have a loop in a Windows service without using the Timer	Thread Worker;\n    AutoResetEvent StopRequest = new AutoResetEvent(false);\n\n    protected override void OnStart(string[] args) {\n        // Start the worker thread\n        Worker = new Thread(DoWork);\n        Worker.Start();\n    }\n    protected override void OnStop() {\n        // Signal worker to stop and wait until it does\n        StopRequest.Set();\n        Worker.Join();\n    }\n    private void DoWork(object arg) {\n        // Worker thread loop\n        for (;;) {\n            // Run this code once every 10 seconds or stop right away if the service \n            // is stopped\n            if (StopRequest.WaitOne(10000)) return;\n            // Do work...\n            //...\n        }\n    }	0
12452838	12452806	How to sort an alphanumeric listbox?	var list = listBox.Items.Cast<ListItem>()\n            .OrderBy(item => int.Parse(item.Text.TrimStart('B')));\n\nlistBox.Items.Clear();\nlistBox.Items.AddRange(list.ToArray());	0
15641006	15640838	Using JSON.decode razor webhelper with a number node in C#?	foreach(var p in decodedJsonString.Foo2['123'].goodStuff)	0
14659095	14659018	Search a value in XELement	bool result = element.DescendantsAndSelf().Any(e => e.Value == "cccc");	0
9178968	9177873	Comparing SqlDataType to CLR nullable types in nunit	private static void CompareValues(string k, Dictionary<string, string> propertyMap, TData sourceDal, TEntity entity)\n    {\n        string sourceField = k;\n        string destField = propertyMap[k];\n        object sourceval = sourceDal.GetType().GetProperty(sourceField).GetValue(sourceDal, null);\n        string sSource = sourceval.ToString();\n        object destval = entity.GetType().GetProperty(destField).GetValue(entity, null);\n        string sDest = destval.ToString();\n        Assert.AreEqual(sSource,\n                        sDest,\n                        String.Format("Values not equal on fields {0} ({1}) to {2} ({3})",\n                                      sourceDal.GetType().GetProperty(sourceField).Name, sourceDal.GetType().GetProperty(sourceField).PropertyType,\n                                      entity.GetType().GetProperty(destField).Name, entity.GetType().GetProperty(destField).PropertyType)\n            );\n\n    }	0
17559115	17558777	Access view information from master page	IView view = ((ViewPage)this.Page).ViewContext.View;\nstring viewname = ((WebFormView)view).ViewPath;	0
690372	690242	how to best wait for a filelock to release	const int ERROR_SHARING_VIOLATION = 32;\ntry\n{\n    using (var stream = new FileStream("test.dat", FileMode.Open, FileAccess.Read, FileShare.Read))\n    {\n    }\n}\ncatch (IOException ex)\n{\n    if (Marshal.GetLastWin32Error() == ERROR_SHARING_VIOLATION)\n    {\n        Console.WriteLine("The process cannot access the file because it is being used by another process.");\n    }\n}	0
5503314	5503198	How can I extend a Unity catalog at runtime?	container.RegisterType<IInterface, ConcreteObject>(new ContainerControlledLifetimeManager());	0
3023618	3023521	HOW CAn I Differciate the button click Event	protected void HandleBtnClick(object sender, EventArgs args)\n        {\n            Button btn = sender as Button;\n            if(btn==null){ \n               return; //This is not expected.\n            }\n            if(btn.Name=="button1")\n            {\n                DoFirstTask();\n            }\n            else if (btn.Name == "button2")\n            {\n                DoSecondTask();\n            }\n            ...\n        }	0
30988344	30983990	Case Insensitive Compare with Fluent Validation	RuleFor(x => x.ConfirmEmailAddress)\n    .NotEmpty()\n    .Must((x, confirmEmailAddress) => x.EmailAddress.Equals(confirmEmailAddress, StringComparison.OrdinalIgnoreCase))\n    .WithMessage("Emails must match");	0
22035471	22035338	How can i read txt file and import it to sql database?	using (StreamReader sr = new StreamReader(path)) \n{\n    while (sr.Peek() >= 0) \n    {\n        Match match = Regex.Match(sr.ReadLine(), @"^(?<Index>\d+)\s(?<X>\d+)\s(?<Y>\d+)$");\n        // You can now access the Index, X and Y by using the following statement\n        // match.Groups["Index"];\n        // match.Groups["X"];\n        // match.Groups["Y"];\n    }\n}	0
24557922	4379697	How do I set background color for a datagrid row programmatically	private void dataGridView1_CellFormatting(object sender,         DataGridViewCellFormattingEventArgs e)\n{\n    foreach (DataGridViewRow Myrow in dataGridView1.Rows) \n    {            //Here 2 cell is target value and 1 cell is Volume\n        if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition \n        {\n            Myrow .DefaultCellStyle.BackColor = Color.Red; \n        }\n        else\n        {\n            Myrow .DefaultCellStyle.BackColor = Color.Green; \n        }\n    }	0
763390	763370	How to deal with ThreadPool and member variables?	class Program\n{\n  static void Main(string[] args)\n  {\n    CustomClass customClass = new CustomClass();\n    ThreadPool.QueueUserWorkItem(x => CallBack(customClass, "Hello")); \n    Console.Read();\n  }\n\n  private static void CallBack(CustomClass custom, string text)\n  {\n    customClass.SaveData(text);\n  }\n}	0
6128492	6128067	Listview items not showing	ColumnHeader columnHeader1=new ColumnHeader();\ncolumnHeader1.Text="Column1";\nthis.listView1.Columns.AddRange(new ColumnHeader[] { columnHeader1 });\nListViewItem item = new ListViewItem("1");\nthis.listView1.Items.Add(item);\nthis.listView1.View = View.Details;	0
20698815	20677106	OLEDB read excel cannot process data start with special character apostrophe ( ' )	Dim s As String\nCells(1, 2).Value = "'abc"\ns = Cells(1, 2).Formula\ns = Cells(1, 2).PrefixCharacter	0
6419116	3230500	How to get Block Style Progressbars in Aero / .NET 4	public class ContinuousProgressBar : ProgressBar \n{ \n    public ContinuousProgressBar() \n    { \n        this.Style = ProgressBarStyle.Continuous; \n    }\n    protected override void CreateHandle()\n    {\n        base.CreateHandle();\n        try\n        {\n            SetWindowTheme(this.Handle, "", "");\n        }\n        catch \n        { \n        }\n    }\n\n    [System.Runtime.InteropServices.DllImport("uxtheme.dll")]  \n    private static extern int SetWindowTheme(IntPtr hwnd, string appname, string idlist);\n}	0
9688990	9688438	How to throw 404 in DotNetNuke module	Response.StatusCode = 404;\nResponse.End();	0
8177855	8177806	C# Winforms - How can I dynamically set the selectedItem of combo box?	myComboBox.SelectedValue = item.Id;	0
30411214	30410704	Deserialize JSON to c# object	public class Createdat\n{\n    public List<object> counts { get; set; }\n    public string gap { get; set; }\n    public string start { get; set; }\n    public string end { get; set; }\n}	0
2493871	2493800	How can I tell the Data Annotations validator to also validate complex child properties?	[CompositeField]	0
26867581	26865454	Set Master page content from one content page	void Page_PreRender(object sender, EventArgs e)\n    {\n        var currentUser = System.Web.Security.Membership.GetUser();\n        if (currentUser != null && currentUser.IsOnline)\n            this.lblLoggedUser.Text = currentUser.UserName;\n        else\n            this.lblLoggedUser.Text = "not authenticated";\n\n    }	0
11586892	11586786	Syntax to add objects to a list?	List<ComplexObject> ComplexObjectList = new List<ComplexObject>();	0
26731182	26731001	WinRt: How to add and remove links on RichEditBox?	public void InsertLink(RichEditBox control, string url) \n{\n  //Check some conditions - else property assignment crashes\n  if (string.IsNullOrEmpty(url)) return; \n  if (string.IsNullOrEmpty(control.Document.Selection.Text)) return; \n  control.Document.Selection.Link = "\"" + url + "\"";\n}\n\npublic void RemoveLink(RichEditBox control) \n{\n  //Can only set Link to empty string, if a link is assigned, \n  //else property assignment crashes\n  if (string.IsNullOrEmpty(control.Document.Selection.Link)) return; \n  control.Document.Selection.Link = "";\n}	0
7651827	7651801	Finding an item in a List<T>	public Commands HasCommand(string cmd)\n{\n    return AllowedCommands.FirstOrDefault(c => c.Alias.Contains(cmd, StringComparer.OrdinalIgnoreCase));\n\n}	0
5182279	5182228	Converting a Byte Array into a delimited string	byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];\nSystem.Text.StringBuilder foto=new System.Text.StringBuilder();\n\nforeach (byte b in bytes)\n{\n   foto.AppendFormat(",{0}",b);\n}\nreturn foto.ToString(); /* Or however you're using your string now */	0
6813478	6813377	RegEx help to remove noise words or stop words from string	var input = "This,sure,about,all of our, all, values";\n        var stopWords = new Regex("^(this|is|about|after|all|also)$");\n        var result = String.Join(",", input.Split(',').\n            Where(x => !stopWords.IsMatch(x.Trim())));	0
8158798	8158784	Get & Set Properties	this.LastError = 1;	0
2240628	2238290	Where clause in Fluent NHibernate Many-to-Many	IEnumerable<Image>	0
4005131	4004307	How can I load datatable as ReportDataSource?	this.reportViewer.LocalReport.DataSources.Clear(); \nDataTable dt = new DataTable(); \ndt = this.inputValuesTableAdapter.GetData();     \n\nMicrosoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt); \n\nthis.reportViewer.LocalReport.DataSources.Add(rprtDTSource); \nthis.reportViewer.RefreshReport();	0
31427587	31427050	Remove key value pairs	public string this[string key]\n    {\n        get\n        {\n\n            string value;\n            _settingsDictionary.TryGetValue(key, out value);\n            if (string.IsNullOrEmpty(value)) return string.Empty;\n            return value.Decrypt(ENCKEY);\n        }\n        set\n        {\n            if (string.IsNullOrEmpty(value)) _settingsDictionary.Remove(key);\n            else _settingsDictionary[key] = value.Encrypt(ENCKEY);\n        }\n    }	0
9985049	9984924	as performed query SQL in linq or lambda expression?	var result = ents.T1\n    .Where(x => list.Contains(x.Id))\n    .GroupBy(x => new \n                 { \n                    Id2 = x.T2.Id, \n                    Id3 = x.T3.Id,\n                    ...\n                    // etc group fields \n                 })\n    .Select(x => new\n                 { \n                    Importe = x.Sum(i => i.Importe)\n                    x.Key.Id2,\n                    // other group fields\n                    ...\n                 })\n    .ToArray();	0
14780524	14780015	Returning specific values with Jquery-Ajax request	public static List<DiscoveryForm> GetDiscoveryForms(int[] ids){	0
15773553	15773119	Use PrincipalSearcher to get DFS shares	string domain;\n        using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))\n        {\n            domain = rootDSE.Properties["defaultNamingContext"].Value.ToString();\n        }	0
7393370	7393255	How do I save Object back to the database with a null value for a date parameter?	private DateTime? _ExpectedPromotionDate;\npublic DateTime? ExpectedPromotionDate\n{\n    get\n    {\n        return _ExpectedPromotionDate;\n    }\n    set\n    {\n\n            _ExpectedPromotionDate = value;\n\n    }\n}\n\n\n\n\n\n\nDac.Parameter(CN_ExpectedPromoDate, ExpectedPromotionDate??(object)DbNull.Value),	0
5548558	4293969	Hiding Panorama Title in landscape mode [wp7]	Grid grid = VisualTreeHelper.GetChild(panorama, 0) as Grid;\nFrameworkElement titleLayer = grid.FindName("TitleLayer") as FrameworkElement;\ntitleLayer.Visibility = System.Windows.Visibility.Collapsed;	0
17027461	17027250	C# DataGridView Column Order	dataGridView1.Columns["Park Name"].DisplayIndex = 0; // or 1, 2, 3 etc	0
8044268	8043633	Outlook Filter Items - Get all recurring appointments in a week range	if (item.IsRecurring)\n        {\n            Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();\n            DateTime first = new DateTime(2011, 11, 7, item.Start.Hour, item.Start.Minute, 0);\n            DateTime last = new DateTime(2011, 12, 1);\n            Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;\n\n\n\n            for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))\n            {\n                    recur = rp.GetOccurrence(cur);\n                    Console.WriteLine(cur.ToLongDateString());\n            }\n        }	0
9814802	9814770	Finding CustomerID by matching Customer.UserName to Logged On User	public ActionResult Index()\n    {\n        var CustomerID = from c in Customer\n            where c.UserName == User.Identity.Name  //use double equals for comparison\n            select c.CustomerID;\n\n        return View(CustomerID);  //or whatever your view is -- some typed object?\n    }	0
31585859	31585541	Changing method from Dictionary to Struct	public class yourClass\n{\n    public string ID { get; set; }\n    public string Description { get; set; }\n    public string StockItem { get; set; }\n    public string MinimumStock { get; set; }\n}\n\nList<yourClass> result = new List<yourClass>();\ndb.Extras.ToList().ForEach(c => result.Add(new yourClass { ID="id" , Description="desc" , MinimumStock="minimum" , StockItem="stock" }));	0
8973723	8973612	Formatting string to 10 characters	String.Format("01{0:00000000}", i);	0
22778664	22778428	Save values between page navigation in Windows Phone	public static valueOne = string.Empty;\npublic static valueTwo = string.empty;\n\n//Assign textbox value to variable on page leaving event\nprotected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)\n {\n   if(!string.IsNullOrEmpty(txtBoxOne.Text))\n     App.valueOne = txtBoxOne.Text;\n   if(!string.IsNullOrEmpty(txtBoxTwo.Text))\n     App.valueTwo = txtBoxTwo.text;\n }\n//Get value from page load\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n        {\n          if(!string.IsNullOrEmpty(App.valueOne))\n            string valueFirst =  App.valueOne;\n         if(!string.IsNullOrEmpty(App.valueTwo ))\n            string valueTwo =  App.valueTwo ;\n        }	0
34519675	34519407	parsing text from HTML source	var blocks = YourVariableHoldingSource.Split('{')\nforeach(var block in blocks){\n  var details = blocks.Split('|')    \n  foreach(var data in details){\n     MessageBox.Show(data);\n  }\n}	0
24306951	24249016	Add many rows at once	foreach (Ligne ligne in ListLigne) \n {\n   var _ligne = ligne as Ligne;   \n   _ligneBLL.InsetLigne(ligne); \n }	0
11788560	11788448	how to set the members of a property?	Public float TestVectorX\n{\n    get { return TestVector.X; }\n    set { TestVector.X = value; }\n}\n\nPublic float TestVectorY\n{\n    get { return TestVector.Y; }\n    set { TestVector.Y = value; }\n}	0
9010969	9010957	Get value from dynamic property	object e = d.GetType().GetProperty("value2").GetValue(d, null);\nobject f = e.GetType().GetProperty("value3").GetValue(e, null);	0
12207415	12207361	c# reading xml file	XmlDocument doc = new XmlDocument();\ndoc.Load(@"/path/to/file");\nXmlNode node = doc.SelectSingleNode("/videos/video/thumbnail_large");\nstring URI = node.InnerText;	0
2733433	2733405	How can I get a List<int> from LINQ to XML that produces List<List<int>>?	LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line")\n                select (int)legalText.Attribute("id")).ToList()	0
16708332	16707122	How to handle [Authorize] with {SiteName} in asp.net mvc	public class MyAuthorizeAttribute : AuthorizeAttribute\n{\n    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n    {\n        var sitename = filterContext.RouteData.Values["sitename"] as string;\n        if (!string.IsNullOrEmpty(sitename))\n        {\n            var routeValues = new RouteValueDictionary(new\n            {\n                controller = "account",\n                action = "login",\n                sitename = sitename,\n            });\n            filterContext.Result = new RedirectToRouteResult(routeValues);\n        }\n        else\n        {\n            base.HandleUnauthorizedRequest(filterContext);\n        }\n    }\n}	0
1188419	1188343	Textbox with autocomplete	public partial class Products : System.Web.UI.Page \n   { \n     [System.Web.Services.WebMethod()] \n      [System.Web.Script.Services.ScriptMethod()] \n      public static string[] GetTerms(string prefix) \n      {\n        // Put your logic here\n      }\n   }	0
1523397	1519882	How to create a state-based test for a method that calls other methods within the same class?	public class AppModeImplementationFactory: IAppModeFactory\n{\n   public IAppModeImplementation Create(int appMode)\n   {\n      // switch case goes here to create the appropriate instance\n   }\n}	0
11048992	11047708	C# Manipulating JSON data	dynamic contourManifest = JObject.Parse(input);\nforeach (var feature in contourManifest.features)\n{\n    feature.geometry.Replace(\n            JObject.FromObject(\n                        new { \n                            type = "Point", \n                            coordinates = feature.geometry.coordinates[0][0] \n                        }));\n}\n\nvar newJson = contourManifest.ToString();	0
14455977	14455252	find child node title's text equel a value	var mySiteMap = new SiteMap();\n/* Lots of code for populating your SiteMap here */\n\nvar nodeTitledTest = mySiteMap.RootNode.ChildNodes.Where(x => x.Title == "test").FirstOrDefault();	0
26250926	26250833	linq convert query syntax to method syntax	var results = db.Table1.Join\n    (\n        db.Table1,\n        x=>x.ID,\n        x=>x.ID - 1,\n        (x,y)=>new{OuterTable = x, xid = x.ID, yid = y.ID}\n    )\n    .Where(x=>Convert.ToInt32(x.yid ) >= Convert.ToInt32(x.xid))\n    .Select(x=>x.OuterTable)\n    .OrderBy(x=>x.Name)\n    .Distinct();	0
13124411	13124304	Using IN on a list of objects	var query = comments\n    .Where(c => UsersList.All(id => c.users.Any(u => u.ID == id)));	0
9272048	9271807	how to move a listview item up or down with a button click	listView1.Items.Remove(selectedItem);\nlistView1.Items.Insert(newIndex, selectedItem);	0
25993947	25993902	Get/Set from C# to Java	public Unit[] getUnits() {\n    // Method body\n}\n\npublic void setUnits(Unit[] value) {\n    // Method body\n}	0
7626193	7626187	Any possibility to declare indexers in C# as an abstract member?	public abstract class ClassWithAbstractIndexer \n{\n    public abstract int this[int index]\n    {\n        get;\n        set;\n    }\n}	0
3838835	3838821	Open new tab in IE	Process.Start("http://www.mysite.com");	0
4972921	4971835	How can a Terminal Services aware application retreive the user's private Windows directory?	System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "windows");	0
29702833	29702700	sc.exe how to set up the description for the windows Service?	sc description TestService1 "This is the description of the service.."	0
19887455	19884084	Using ArrayList in C# to create a calculator type web application	public double CalculateCalories(string text, double mass, double time)\n{\n    int index = -1;\n\n    //First we find the index we're interested in\n    for(int i=0; i < activity.count; i++)\n    {\n        string act = activity[i].ToString();\n\n        //If we match the string perfectly, then we know the index\n        if (act.Equals(text))\n        {\n            index = i;\n        }\n\n    }\n\n    if (index.Equals(-1))\n    {\n        //error - throw some sort of exception\n    }\n\n    //Now that we know the index, we'll determine which arrayList we look for\n\n    double calorieCount  = 0;\n\n    if (mass < 130)\n    {\n        //take from the small one\n        calorieCount = rangeSmall[index];\n    }\n    else if (//Follow the same pattern)\n    {\n        //\n    }\n\n    //Then multiply it by time somehow - depending on how your multiplier is set up\n\n    return time*calorieCount;\n\n}	0
5683804	5662518	Unable to display report in ASP.Net page	private void ShowStatements(string agreementId)\n    {\n        //var crvStatements = new CrystalReportViewer(); //created on the page\n        ReportDocument reportDocument = new ReportDocument();\n        reportDocument.Load(Server.MapPath("Statements.rpt"));\n        crvStatements.ReportSource = reportDocument;\n        System.Data.DataTable dt1 = new dsStatements.usp_GetBillDetailsByAgreementIdDataTable();\n        System.Data.DataTable dt2 = new dsStatements.usp_GetTransactionTypesByAgreementIdForBillDataTable();\n        System.Data.DataSet statements = new System.Data.DataSet();\n        statements.Tables.Add(dt1);\n        statements.Tables.Add(dt2);\n        reportDocument.SetDataSource(dsStatements);\n\n        crvStatements.DataBind();\n    }	0
23364324	23360770	How to read COM TypeLib with C# or C++?	class Program\n{\n    static void Main(string[] args)\n    {\n        TypeLibInfo tli = new TypeLibInfo();\n        tli.ContainingFile = @"c:\windows\system32\mshtml.tlb";\n        foreach (TypeInfo ti in tli.TypeInfos)\n        {\n            Console.WriteLine(ti.Name);\n            // etc...\n        }\n    }\n}	0
29097297	29090755	htmlAgilityPack parse table to datatable or array	var query = from table in doc.DocumentNode.SelectNodes("//table")\n                        where table.Descendants("tr").Count() > 1 //make sure there are rows other than header row\n                        from row in table.SelectNodes((".//tr[position()>1]")) //skip the header row\n                        from cell in row.SelectNodes(("./td")) \n                        from header in table.SelectNodes(".//tr[1]/th") //select the header row cells which is the first tr\n                        select new\n                        {\n                            Table = table.Id,\n                            Row = row.InnerText,\n                            Header = header.InnerText,\n                            CellText = cell.InnerText\n                        };	0
22541160	22540747	Saving an array in C# for local scoreboard	string[] names = new string[100];\nStorageFolder folder = ApplicationData.Current.RoamingFolder;\nXmlWriterSettings set = new XmlWriterSettings();\nset.Encoding = Encoding.Unicode;\n\nXmlObjectSerializer serializer = new DataContractSerializer(typeof(string[]));\nStream stream = await folder.OpenStreamForWriteAsync("filename", CreationCollisionOption.ReplaceExisting);\nXmlWriter writer = XmlWriter.Create(stream, set);\nserializer.WriteObject(writer, names);	0
12531577	12530867	How save Windows Form as pdf	using PdfSharp.Pdf;	0
1038629	1038535	How to skip the subsequent byte[] received from socket using c#	IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(port));	0
17653703	17645331	WPF Borderless window resize	handled = true;	0
1298181	1298116	Create element in xml document	XmlDocument doc;\n XmlElement root;\n XmlElement rootnode;\n XmlElement Login;\n\n if (File.Exists(@"C:\Test.xml") == false)\n {\n     doc = new XmlDocument();\n     root = doc.CreateElement("LicenseDetails");\n\n     rootnode = doc.CreateElement("License");\n     Login = doc.CreateElement("Login_Name");\n     Login.InnerText = "KSC";\n     rootnode.AppendChild(Login);\n     root.AppendChild(rootnode);\n     doc.AppendChild(root);\n\n     doc.Save(@"C:\Test.xml");\n }	0
13258196	13258094	How to log Exceptions in Nlog2?	log.FatalException("blah", ex)	0
23827305	23803186	Monte Carlo Tree Search: Implementation for Tic-Tac-Toe	//If this move is terminal and the opponent wins, this means we have \n        //previously made a move where the opponent can always find a move to win.. not good\n        if (game.GetWinner() == Opponent(startPlayer))\n        {\n            current.parent.value = int.MinValue;\n            return 0;\n        }	0
25828001	25827968	Convert TextBox Value to integet in rowcommand event in Grid View	int Sunday = Convert.ToInt32(((TextBox)gvEmployeeTimeSheet.Rows[rowIndex].FindControl("txtSunday")).Text);\n int Monday = Convert.ToInt32(((TextBox)gvEmployeeTimeSheet.Rows[rowIndex].FindControl("txtMonday")).Text);	0
22629409	22628984	How to resize picture on button in C#?	Image img = Image.FromStream(p);\ndevBtn = new Button();\n\ndevBtn.BackgroundImage = img;\ndevBtn.BackgroundImageLayout = ImageLayout.Stretch;\n\ndevBtn.Size = new Size((img.Width + 5), (img.Height + 5));\ndevBtn.Top = positionTOP;	0
17421209	17421120	Convert relative path to full URL	string FullUrl = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + "/PDF/MyFile.pdf"	0
7332814	7331401	DataGridView slow at redrawing	DataLoadOptions options = new DataLoadOptions();\noptions.LoadWith<Customer>(Customer => Customer.Orders);\ndb.LoadOptions = options;	0
21333823	21333760	how to get the value from combobox and pass it to the next step?	Font font = new Font(comboBox1.SelectedItem.ToString(), 60F);	0
4963895	4963881	How do I check a datareader for null?	if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }	0
17707434	17668785	Getting last inserted row id using repository pattern	public class CustomerDetail\n{\n    public int Id{ get; set; }\n    public string Name{ get; set; }\n    public string Address{ get; set; } \n}\nvar customerDetail = new CustomerDetail { Name = "Bubbles", Address = "1 way, city" }\ncustomerDetailRepository.Add(customerDetail)\n\nConsole.WriteLine(customerDetail.Id); // This is the identity value	0
325280	325241	Finding the selected item of list view	foreach (ListViewItem item in lvFiles.SelectedItems)\n{\n....................................\n}	0
13689953	13632625	FileUpload to Amazon S3 results in 0 byte file	asset.Seek(0, SeekOrigin.Begin);	0
17009011	17008583	How to avoid certain fields to be updated in model using asp.net mvc 4	var userFromDb = db.Users.Where(u => u.UserID == user.UserID).First();\nuser.Password = person.Password;\nuser.VerifyPassword = person.VerifyPassword;\n\ndb.Entry(person).CurrentValues.SetValues(user);\ndb.SaveChanges();	0
8289775	8289487	Radius Around Point also known as Geofence in ASP.NET C# With Google Maps	var map;\nvar marker;\n\nfunction initialize() {\n    var optns = {\n        zoom: 6,\n        center: latlng,\n        mapTypeId: google.maps.MapTypeId.HYBRID\n    }\n    map = new google.maps.Map(document.getElementById("myMap"), optns);\n    google.maps.event.addListener(map, 'click', function(event) {\n        setCurrentLocation(event.latLng, 10);\n    });\n}\n\nfunction setCurrentLocation(location, crcl_radius){\n    if(marker)\n        marker.setMap(null);\n\n    var opts = {\n        map: map,\n        position: location,\n        clickable:false\n    };\n    marker = new google.maps.Marker(opts);\n\n    var circle = new google.maps.Circle({\n            map: map,\n            radius: crcl_radius,\n            fillColor:'#efefef',\n            fillOpacity:0.5,\n            strokeColor:'#ff0000',\n            strokeWeight:2\n    });\n   circle.bindTo('center', marker, 'position');\n}	0
7523722	7523688	how to add an OnClick event on DropDownList's ListItem that is added dynamically?	DropDownList changesList = new DropDownList();\n\nListItem item;\nitem = new ListItem();\nitem.Text = "go to google.com";\nitem.Value = "http://www.google.com";\n\nchangesList.Items.Add(item);\nchangesList.Attributes.Add("onChange", "location.href = this.options[this.selectedIndex].value;");	0
11124324	11123985	Getting data from a table to ASP.NET web application	|DataDirectory|	0
33505826	33505551	How do you the sender of outlook messages in C#?	Appointment appointment = new Appointment(service);\n\n// Set the properties on the appointment object to create the appointment.\nappointment.Subject = "Tennis lesson";\nappointment.Body = "Focus on backhand this week.";\nappointment.Start = DateTime.Now.AddDays(2);\nappointment.End = appointment.Start.AddHours(1);\nappointment.Location = "Tennis club";\nappointment.ReminderDueBy = DateTime.Now;\n\n// Save the appointment to your calendar.\nappointment.Save(SendInvitationsMode.SendToNone);\n\n// Verify that the appointment was created by using the appointment's item ID.\nItem item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));\nConsole.WriteLine("\nAppointment created: " + item.Subject + "\n");	0
31911746	31911716	How to use String.Replace method for html string	var documnet = new HtmlDocument();\ndocumnet.LoadHtml("HtmlString");\nforeach (var href in documnet.DocumentNode.Descendants("img").Where(href => !href.OuterHtml.Trim().Contains("http")))\n{\n     try\n     {\n          //here image src URL being changed...\n          href.Attributes["src"].Value = href.Attributes["src"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["src"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["src"].Value.TrimFromStart("//"));\n          href.Attributes["srcset"].Value = href.Attributes["srcset"].Value.Trim().StartsWith("//") ? String.Format("http:{0}", href.Attributes["srcset"].Value.Trim()) : String.Format("{0}/{1}", baseUrl, href.Attributes["srcset"].Value.TrimFromStart("//"));\n     }\n     catch (NullReferenceException ex)\n     {\n         Log(ex);\n     }\n}	0
24562668	24562610	Selecting Keys as SelectedItems in ListView	var keys =  lvUsers.SelectedItems.OfType<KeyValuePair<int, string>>().Select(x => x.Key);	0
15766085	15765462	Adding header rows to Gridview	class MyClass\n{\n    private string CurrentCategory{ get; set; }\n\n    // Load_Page with databinding the GridView{  }\n\n    protected void mygridview_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if(e.Row.RowType == DataControlRowType.DataRow && \n          (e.Row.DataItem as DataRowView)["mycolumn"].ToString() != CurrentCategory))\n        {\n            GridViewRow tr = new GridViewRow(e.Row.RowIndex +1, e.Row.RowIndex + 1, \n                                   DataControlRowType.DataRow, e.Row.RowState);\n            TableCell newTableCell = new TableCell();\n            newTableCell.Text = (e.Row.DataItem as DataRowView)["mycolumn"].ToString();\n            CurrentCategory = (e.Row.DataItem as DataRowView)["mycolumn"].ToString();\n            tr.Cells.Add(newTableCell);\n\n            ((Table)e.Row.Parent).Rows.Add(tr);\n        }\n    }\n}	0
11124466	11124237	How to convert color to code and viceversa	clr.ToArgb().ToString("x").ToUpper()	0
29357860	27914042	How to convert EmguCV Image to Unity3D Sprite?	//Capture used for taking frames from webcam\nprivate Capture capture;\n//Frame image which was obtained and analysed by EmguCV\nprivate Image<Bgr,byte> frame;\n//Unity's Texture object which can be shown on UI\nprivate Texture2D cameraTex;\n\n//...\n\nif(frame!=null)\n    frame.Dispose();\nframe = capture.QueryFrame();\nif (frame != null)\n{\n    GameObject.Destroy(cameraTex);\n    cameraTex = TextureConvert.ImageToTexture2D<Bgr, byte>(frame, true);\n    Sprite.DestroyImmediate(CameraImageUI.GetComponent<UnityEngine.UI.Image>().sprite);\n    CameraImageUI.sprite = Sprite.Create(cameraTex, new Rect(0, 0, cameraTex.width, cameraTex.height), new Vector2(0.5f, 0.5f));\n}	0
8018988	8018766	How to Delete row of unbound data from dataGridView1?	private void button1_Click(object sender, EventArgs e)\n    {\n            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);\n\n    }	0
16468325	16468070	Task.wait in task array	public void BatchStart(List<TaskDefinition> definition)\n{\n    Task.WaitAll(\n        definition.Select\n            (a => Task<TaskResult>.Factory.StartNew(\n                () => (TaskResult)a.MethodTocall.DynamicInvoke(a.ARguments)).ContinueWith(task => RunTaskRetObjResultIns((Task<TaskResult>)task, a.CompleteMethod))\n            ).ToArray()\n        );\n    Console.WriteLine("completed");\n}	0
5821607	5821521	Failed to get MaxValue from data	double maxValue = double.MinValue;\nfor (int i = 0; i < value.GetLength(0); i++)\n{\n    for (int j = 0; j < value.GetLength(1); j++)\n    {\n        if (value[i][j] > maxValue)\n        maxValue = value[i][j];\n    }\n}\nSetText(textBox1, maxValue.ToString());	0
26836893	26836856	remove two or more empty between space in word	string xyz = "1   2   3   4   5";\nxyz = string.Join( "-", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));	0
11750139	11749889	calling dialog and getting values from it in backgroundworker?	bool WaitFor_Input = false; //flag to indicate user input status\n\n    private void ThreadRun()\n    {\n        //THIS IS IN Background worker thread\n        //do task\n        WaitFor_Input = true;\n        //ask for user input\n        Dispatcher.BeginInvoke(new Action(Show_Dialogue), null);\n        while (WaitFor_Input); //Background worker waits untill user input is complete\n        //continue further processing\n    }\n\n    private void Show_Dialogue()\n    {\n        //THIS IS IN UI THREAD\n        //show your dialogue box here, update data variables\n        //finally set\n        WaitFor_Input = false;\n    }	0
28905457	28905415	How to get command line args of a process by id?	var q = string.Format("select CommandLine from Win32_Process where ProcessId='{0}'", processId);\nManagementObjectSearcher searcher = new ManagementObjectSearcher(q);\nManagementObjectCollection result = searcher.Get();\nforeach (ManagementObject obj in result)\n    Console.WriteLine("[{0}]", obj["CommandLine"]);	0
24407680	24407615	How to Compare a string to each item in a file?	for (int i = 0; array[i]; i++){\n\nCompareStrings(mystring, array[i]);\n\n}	0
26909776	26816177	Execute javascript function with 'this' keyword as parameter in WebBrowser C#	var obj=new object[2];\nobj[0]="id1";\nobj[1]=5000;\nwebBrowser.Document.InvokeScript("Social",obj);	0
30193524	30193005	Realtime decoding - stdin to stdout	ffmpeg -i - -f s16le -	0
31015804	31015585	Match two distinct letters	([A-Z])(?!\1)[A-Z]	0
23485526	23485347	Finding all grid coordinates within a 7x7 grid	int x = 10, y = 10;\n\nint lConerX = x - 4, lConerY = y - 4;//coords of top-left conner\n\nfor (int i = lConerX; i < lConerX + 7; i++)\n{\n    for (int j = lConerY; j < lConerY + 7; j++)\n    {\n         arr[i, j] = 1;\n    }\n}	0
13959150	13959117	How to get split along with Linq?	string code=db.command("select cidade from logos ").Split(':').First()	0
19016353	19016286	MS Access SQL Insert Query	queryString = "INSERT INTO daily_prices (time_series_id, [open], high, low, " + \n              "[close], volume, observation_date) VALUES " + \n              "(13, 3036.75, 3045.72, 3023.27, 3027.52, 4894428992, '2013-09-24')";	0
24528968	24528329	datagridview data displayed in smaller area as the size of datagridview c#	dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;	0
32904148	32902125	Processing a Outlook calendars own formula items	For Each p As Microsoft.Office.Interop.Outlook.ItemProperty In item.ItemProperties\n                Try\n                    MsgBox(p.Name & "    " & p.Value.ToString())\n                    'One of thousends of attributes\n                Catch e As System.Exception\n                End Try\n            Next	0
3730317	3730257	Find specific object in list in object in a LINQ query	hour = lessons.SelectMany(l => l.hours).Where(h => h.period == o);	0
6493728	6468538	Save password protected Excel file to XML in C# (I know the password)	//unprotect the workbook\nExcelHelperWorkbook.Unprotect(password);\n\n//unprotect the first worksheet\n((Worksheet)ExcelHelperWorkbook.Worksheets.get_Item(1)).Unprotect(password);	0
7998183	7997917	Remove rows from a DataTable where an entry exist in another DataTable	var badValues = new HashSet<Tuple<int, int>>(\n                  tableReadFromFile.AsEnumerable().\n                                    Select(row => \n                                      new Tuple<int, int>(row.Field<int>("id1"), row.Field<int>("id2"))));\n\nvar result = tableReadFromSql.AsEnumerable().\n                                    Where(row => !(badValues.Contains(\n                                    new Tuple<int, int>(row.Field<int>("id1"), row.Field<int>("id2")))));	0
17917811	17917183	Creating new popup window when click button	ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", "http://www.google.com"));	0
10896995	10896806	C# : Is there any C# function to insert primary key from one table into another	CREATE PROCEDURE procedure1\nAS\nBEGIN\n    DECLARE @id int;\n\n    INSERT INTO [table1] (col1) VALUES ('Foo');\n    SET @id = SCOPE_IDENTITY();\n    INSERT INTO [table2] (col1, col2) VALUES (@id, 'Bar');\n\n    RETURN @id;\nEND	0
9639855	9537868	How to add post with place (location) to user's wall via graph API?	var facebookClient = new FacebookClient(attendee.FacebookToken);\nvar parameters = new Dictionary<string, object>\n                                 {\n                                     {"message", message},\n                                     {"place", placeID}\n                                 };\ndynamic response = facebookClient.Post("me/feed", parameters);	0
2831957	2831947	Date formats in C#	var dt = new DateTime(2010, 20, 1);\nstring s = dt.ToString("MMMM dd, yyyy");	0
25547507	24673376	Unable to find assembly with BinaryFormatter.Deserialize	[Serializable]\n    public class YourClass : SerializationBinder \n    {\n        public override Type BindToType(string assemblyName, string typeName)\n        {\n            Type tyType = null;\n\n            string sShortAssemblyName = assemblyName.Split(',')[0];\n\n            Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();\n\n            foreach (Assembly ayAssembly in ayAssemblies)\n            {\n                if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])\n                {\n                    tyType = ayAssembly.GetType(typeName);\n                    break;\n                }\n            }\n            return tyType;\n        }\n        ...	0
17457480	17457352	setting the fourth decimal place in a number to 1 or 0	ToString( )	0
3584043	3583927	format property in class to return phone number	String.Format("{0:(###) ###-####}", Int64.Parse("8005551212"))	0
22777820	22777585	Child textbox will not stretch when grid in ListBox ItemTemplate is split into two columns	Application.Current.RootVisual.RenderSize.Width/2	0
14425878	14425769	How to upload an image to any web server, local or remote which my application has permissions to	public void UpLoadFile(String serverFilePath, string localFilePath)\n{\n    String serverFullPath = "ftp://" + s_ServerHost + serverFilePath;\n    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(serverFullPath);\n    ftp.Credentials = new NetworkCredential("user", "password");\n    ftp.KeepAlive = true;\n    ftp.Method = WebRequestMethods.Ftp.UploadFile;\n    ftp.UseBinary = true;\n\n    using (FileStream fs = File.OpenRead(localFilePath))\n    {\n        Byte[] buffer = new Byte[fs.Length];\n        fs.Read(buffer, 0, buffer.Length);\n    }\n\n    using (Stream ftpStream = ftp.GetRequestStream())\n        ftpStream.Write(buffer, 0, buffer.Length);\n}	0
29117263	29117187	zip file comming empty in attachement in email sent using c#	zip.AddEntry(FileName + ".csv", stream);\nzip.Save(memoryStreamOfFile);\nmemoryStreamOfFile.Position = 0;	0
29683599	29683499	LINQ find all child entities meet requirements	var RequestsNeedsAction = Requests.Where(r => \n    (r.RequestStatusID == 2 || r.RequestStatusID == 6) \n    && !r.Tasks.Any( t => t.TaskStatusID != 2 && t.TaskStatusID != 5)).ToList();	0
1266496	1266431	Set WPF Resources in C#	ListView view = new ListView();\n    view.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Transparent));\n    view.Resources.Add(SystemColors.ControlBrushKey, new SolidColorBrush(Colors.Transparent));	0
9005828	9004361	Solution-wide namespace dependency graph in NDepend	warnif count > 0 \n\n// Namespaces with suffix Interface\nlet interfacesNamespaces = \n   Application.Namespaces.WithNameLike("Interface$").ToHashSet()\n\n// Match namespaces that are using something else than interfacesNamespaces \nfrom n in Application.Namespaces\nlet nonInterfacesNamespacesUsed = n.NamespacesUsed.Except(interfacesNamespaces)\nwhere nonInterfacesNamespacesUsed.Count() > 0\nselect new { n, nonInterfacesNamespacesUsed }	0
26199902	26199886	Variable Conversion decimal to int	int i = (int)Math.round(d);	0
7849428	7848997	How to set parameters on a Query in MultiQuery ? "The named parameter code was used in more than one query."	int i = 0;\nforeach (string name in names)\n{\n    string paramname = "name" + (++i).ToString();\n    var query = SessionHolder.Current\n        .CreateQuery("select c.Name, c.Surname " +\n                     "from Person as p " +\n                     "where p.Name = :" + paramname + " or " +\n                           "p.Name like ':" + paramname + "/%'")\n        .SetParameter(paramname, name);\n    multiQuery = multiQuery.Add(query);\n}	0
14718165	14718121	Mvc3 - How to call action from static function	var routeData = new RouteData();\nrouteData.Values["controller"] = "Error";\nrouteData.Values["action"] = "General";\nrouteData.Values["exception"] = exception;\n\nIController errorsController = new ErrorController();\nvar rc = new RequestContext(new HttpContextWrapper(Context), routeData);\ntry\n{\n    errorsController.Execute(rc);\n}\ncatch (Exception ex)\n{\n    // Appropriate error handling.\n}	0
16618380	16618341	How to read character in a file 1 by 1 c#	if (Convert.ToInt32(ch) == 34)\n    {\n        Console.Write(@";");\n    }\n    Console.Write(ch);	0
438228	438184	Export to Excel from a Repeater?	Response.Write("<table>");\nResponse.Write(stringWrite.ToString()); \nResponse.Write("</table>");	0
20733976	20733873	Trying to select from a list the first previous eligible index	class Item\n{\n    Item North { get; private set; }\n    Item South { get; private set; }\n    Item West { get; private set; }\n    Item East { get; private set; }\n}	0
27238752	27238607	Use NumericUpDown to select days in month	private void Form1_Load(object sender, EventArgs e)\n    {\n        numericUpDown1.Maximum = DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month);\n    }	0
21292215	21291559	c# async issue with multiple tasks	var taskList = new List<Task>();\nforeach (var myString in listOfStrings)\n{\n    // Avoid closure issue\n    var temp = myString;\n    taskList.Add(Task.Factory.StartNew(async object stringObject => {\n        var currentString = stringObject as string;\n        //creating an object RequestDataObj\n        RequestDataObj request = new RequestDataObj();\n\n        //filling RequestDataObj with some request data based on currentString\n\n        //making async call and getting data in resultDataObj \n        var resultDataObj = await ApiCall.GetDataAsync(request, currentString);\n\n        //saving resultDataObj + currentString to database synchronously\n    }, temp));\n}\n\nawait Task.WhenAll(taskList);\n//doing some other operations here	0
12952872	12952773	Display an object for a few milliseconds in Unity3D	void *AnyTrigger*() // eg. replace with OnTriggerEnter if using triggers\n{\n    StartCoroutine(ShowObject(14f / 1000f));\n}\n\nIEnumerator ShowObject(float timeInSeconds)\n{\n    // Show object here\n    yield return new WaitForSeconds(timeInSeconds);\n    // Hide object\n}	0
7592459	7592431	Detecting DllImportAttribute and its data in an assembly	var pinvokes = from type in Assembly.GetExecutingAssembly().GetTypes()\n               from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)\n               let dllImport = (DllImportAttribute)method.GetCustomAttributes(typeof(DllImportAttribute), false).FirstOrDefault()\n               where dllImport != null\n               select new\n               {\n                   DllName = dllImport.Value,\n                   EntryPoint = dllImport.EntryPoint,\n               };	0
10885091	10884924	C# XML attribute being created improperly	XmlAttribute xRefADLCP = docXMLFile.CreateAttribute(\n     "adlcp","scormtype", "correct-namespace-here");	0
15246299	15246179	How to pass parameters into sql server UDF and have them cached	CREATE FUNCTION myUdf \n(\n    @a INT,\n    @b INT\n)\nRETURNS INT\nAS\nBEGIN\n    DECLARE @c INT\n    SET @c = (SELECT TOP(1) id FROM my_table)\n    RETURN @a + @b + @c\nEND\nGO	0
24992642	24992286	Validate number with currency symbol	float value;\nvar culture = CultureInfo.GetCultureInfo("en-GB");\nbool isValidCurrency = float.TryParse(str, NumberStyles.Currency, culture, out value);	0
30175939	30175412	Set the transparency of a circle on a bitmap	private void setCircleAlpha(int alpha, ref Bitmap b, ColumnVector2 pos, int diameter)\n    {\n        Graphics g = Graphics.FromImage(b);\n        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;\n        SolidBrush sb = new SolidBrush(Color.FromArgb(alpha, 0, 0, 0));\n\n        g.FillEllipse(sb, pos.X, pos.Y, diameter, diameter);\n    }	0
16926078	16925996	How can i create/add an event of contextMenuStrip1 that is connected with notifyIcon?	private void closeApplicationToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        this.Close();\n    }	0
4917771	4909013	Using Linq to group by multiple columns in a list and mark all duplicate items	var theLookup = personList\n  .GroupBy(p => new {p.PersonFirstName, p.PersonLastName, p.PersonDateOfBirth})\n  .ToLookup(g => g.Skip(1).Any() ? "duplicate" : "unique");\n\nforeach(var lookupEntry in theLookup)\n{\n  string stateOfData = lookupEntry.Key;\n  foreach(Person p in lookupEntry.SelectMany(g => g))\n  {\n    p.StateOfData = stateOfData;\n  }\n}	0
4808929	4808907	How to specify timeout for XmlReader?	WebRequest request = WebRequest.Create(url);\nrequest.Timeout = 5000;\n\nusing (WebResponse response = request.GetResponse())\nusing (XmlReader reader = XmlReader.Create(response.GetResponseStream()))\n{\n    // Blah blah...\n}	0
521797	521774	How to import void * C API into C#?	[DllImport(@"zip4_w32.dll",\n        CallingConvention = CallingConvention.StdCall,\n        EntryPoint = "z4ctygetSTD",\n        ExactSpelling = false)]\n    private extern static int z4ctygetSTD(ref CITY_REC args, IntPtr ptr);	0
27544777	27544757	Add TimeSpan to DateTime doesn't work	DateTime newTime = StartDateTime.Add(tsStart);	0
21256464	21256385	Build strings based on maximum length	List<string> valueStrings = new List<string>();\nstring value, valueString;\nwhile (x.Read())\n{\n    value = (string)(x["ROWVALUE"]);    \n\n    if (valueString.Length + value.Length > 300)\n    {\n        valueStrings.Add(valueString);\n        valueString = value;\n    }\n    else\n    {\n        valueString += value;\n    }\n}\nvalueStrings.Add(valueString); //don't forget about the last one	0
13305848	13247756	Get the actual size of an imagebrush control for a canvas background	var ratio = Math.Min(RubCanvas.RenderSize.Width / CanvasBackground.ImageSource.Width, RubCanvas.RenderSize.Height / CanvasBackground.ImageSource.Height);\nvar imageBrushWidth = CanvasBackground.ImageSource.Width * ratio;\nvar imageBrushHeight = CanvasBackground.ImageSource.Height * ratio;	0
8932481	8932415	Month in c# using DateTime	CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int monthNumber);	0
4428350	4428302	compare two files based on datetime upto minute?	public class FileCompareLastwritetime\n        : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo> {\n    public FileCompareLastwritetime() { }\n    public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2) {\n        return ToMinute(f1.LastWriteTime) == ToMinute(f2.LastWriteTime);\n    }\n    public int GetHashCode(System.IO.FileInfo fi) {\n        return ToMinute(fi.LastWriteTime).GetHashCode();\n    }\n    static DateTime ToMinute(DateTime value) {\n        return new DateTime(value.Year, value.Month, value.Day,\n                 value.Hour, value.Minute, 0, value.Kind);\n    }\n}	0
13014948	13013300	Using GraphSharp graph layout WPF library to plot a graph and edit vertex label	string edgeSource = "n3";\n    string edgeTarget = "n4";\n    string newEdgeSource = "n0";\n    string newEdgeTarget = "n4";\n\n    IEnumerator<IEdge<object>> edgeEnumeratoer = g.Edges.GetEnumerator();\n    edgeEnumeratoer.MoveNext();\n    while (edgeEnumeratoer.Current != null)\n    {\n        var edge = edgeEnumeratoer.Current;\n        string source = (string)(edge.Source);\n        string target = (string)(edge.Target);\n        if ((source.CompareTo(edgeSource) == 0) && (target.CompareTo(edgeTarget) == 0))\n        {\n            if (g.RemoveEdge(edge))\n            {\n                IEdge<object> newEdge = new Edge<object>(newEdgeSource, newEdgeTarget);\n                g.AddEdge(newEdge);\n                break;\n            }\n            else\n            {\n                Debug.WriteLine("Could not remove edge from graph.");\n            }\n        }\n        edgeEnumeratoer.MoveNext();\n    }\n\n    graphLayout.Graph = g;	0
5505188	5505119	Access bound object in UserControl code behind with DependencyProperty	public static readonly DependencyProperty EntityProperty = DependencyProperty.Register("Entity",\ntypeof(Entity), typeof(UserEntityControl), new PropertyMetadata(null, EntityPropertyChanged));\n\n    static void EntityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n        var myCustomControl = d as UserEntityControl;\n\n        var entity = myCustomControl.Entity; // etc...\n    }\n\n    public Entity Entity\n    {\n        get\n        {\n            return (Entity)GetValue(EntityProperty);\n        }\n        set\n        {\n            SetValue(EntityProperty, value);\n        }\n    }	0
27731888	27723629	Unity - Running A Pathfinding Algorithm on A Seperate Thread	IEnumerator PathFinding()\n{\n  while(!goalNodeReached)\n  {\n    VisitMaxNodes(maxNodesToVisit); // this function visit only a subset of the graph each frame\n    yield return null;\n  }\n}	0
4374865	4374817	Using Linq Lambda Nested Expression to join two lists	List<MyClass> results = list2.Where(x => x.History.Any(z => (z.Key == eachClass.ID))).ToList();	0
6210287	6210233	SQL server recovery mechanism	var attemptNumber = 0;\nwhile (true)\n{\n    try\n    {\n        using (var connection = new SqlConnection())\n        {\n            connection.Open();\n\n            // do the job\n        }\n        break;\n    }\n    catch (SqlException exception)\n    {\n        // log exception\n        attemptNumber++;\n        if (attemptNumber > 3)\n            throw; // let it crash\n    }\n}	0
21752813	21752700	Convert the code from Foreach loop to Linq	testItemList = testResults.Select(item => \n                                 project.Store.GetTestItem(item.TestId))\n                          .ToList();	0
27361049	26065857	Create list using C# CSOM in a subsite on Office SharePoint O365	TokenHelper.GetAppOnlyAccessToken()	0
157624	157554	How do I convert an XmlNodeList into a NodeSet to use within XSLT?	XsltArgumentList arguments = new XsltArgumentList();\nXmlNodeList nodelist;\nXmlDocument nodesFrament = new XmlDocument();\nXmlNode root = nodesFragment.CreateElement("root");\nforeach (XmlNode node in nodeList)\n{\n    root.AppendChild(node);\n}\nnodesFragment.AppendChild(root);\n\narguments.AddParam("argumentname", string.Empty, nodesFragment.CreateNavigator().SelectChildren(XPathNodeType.All));	0
33912566	33910016	Bitcoin formatting via Blockchain API	var address = 3644624;\nvar t = address * Math.Pow(10,-8);	0
32729597	32729559	How do I write regex to validate EIN numbers?	Regex regex = new Regex("^\\d{2}-?\\d{7}$");	0
5218492	5218395	Reflection: How to get a generic method?	var myMethod = myInstance.GetType()\n                         .GetMethods()\n                         .Where(m => m.Name == "MyMethod")\n                         .Select(m => new {\n                                              Method = m,\n                                              Params = m.GetParameters(),\n                                              Args = m.GetGenericArguments()\n                                          })\n                         .Where(x => x.Params.Length == 1\n                                     && x.Args.Length == 1\n                                     && x.Params[0].ParameterType == x.Args[0])\n                         .Select(x => x.Method)\n                         .First();	0
8015166	8001704	Generic entities to load data from flat file	namespace Data.Entities\n{\n   [FlatFileContainerRecord(RecordLength = 157)]\n    public class FlatFile<FlatFileHeader, DT, FlatFileFooter> \n    {\n       public FlatFileHeader Header { get; set; }\n       public List<DT> Details { get; set; }\n       public FlatFileFooter Control { get; set; }\n       public FlatFile()\n    {\n        Details = new List<DT>();\n    }\n}	0
14514122	14513028	Replace parts of string with objects	private readonly static Dictionary<char, Type> Tokens = new Dictionary<char, Type> { \n        { '\n', typeof(Break) },\n        { '\t', typeof(TabChar) }\n    };\n\nprivate static IEnumerable<OpenXmlElement> Tokenize(string text)\n{\n    var start = 0;\n    var pos = 0;\n\n    foreach (var c in text)\n    {\n        Type tokenType;\n        if (Tokens.TryGetValue(c, out tokenType))\n        {\n            if (pos > 0)\n            {\n                yield return new Text(text.Substring(start, pos));\n            }\n            yield return (OpenXmlElement)Activator.CreateInstance(tokenType);\n            start += pos + 1;\n            pos = 0;\n        }\n        else\n        {\n            pos++;\n        }\n    }\n\n    if (pos > 0)\n    {\n        yield return new Text(text.Substring(start));\n    }\n}\n\nstatic void Main(string[] args)\n{\n    var tokens = Tokenize("This is a test string.\n \t This is a new line with a tab").ToArray();\n\n}	0
7583455	7557498	Check a checkbox inside Gridview	for (int i = 0; i < dataGridView1.RowCount - 1; i++)\n            {\n                dataGridView1.Rows[i].DataGridView[0, i].Value = false;\n            }	0
33752182	33751929	Creating threads in method in Console fails in C#	static void wait()\n    {\n        Console.ReadKey();\n        Thread tt = new Thread(write);\n        tt.Start(count);\n        count++;\n\n        wait(); //Added\n    }	0
12193994	12193076	Bindind Repeater to Stack List	private Control CreateReapeater()\n{\n    Repeater _repeater1 = new Repeater();\n    Stack _stack1 = new Stack();\n    for (int i = 0; i < 7; i++)\n    {\n        _stack1.Push(i);\n    }\n\n    _repeater1.DataSource = _stack1;          \n    _repeater1.DataBind();\n\n    foreach (RepeaterItem repeatItem in _repeater1.Items)\n    {\n        int index = repeatItem.ItemIndex;\n\n        RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);\n        Label lbl = new Label();\n\n        lbl.Text = "Item No :" + index.ToString() + "<br/>";\n        repeatItem.Controls.Add(lbl);\n\n    }\n\n\n\n    return _repeater1;\n}	0
7535012	7534554	Drawing textures with variable transparency	float alpha = desired_alpha;\n\n spritebatch.Draw(texture, pos, source, Color.White * alpha);	0
20802654	20802420	How to compare arrays in a list	private static IList<IList<int>> EqualArrays(List<int[]> list) {\n      IList<IList<int>> result = new List<IList<int>>();\n\n      HashSet<int> proceeded = new HashSet<int>();\n\n      for (int i = 0; i < list.Count; ++i) {\n        if (proceeded.Contains(i))\n          continue;\n\n        int[] item = list[i];\n        List<int> equals = new List<int>() { i };\n\n        result.Add(equals);\n\n        for (int j = i + 1; j < list.Count; ++j)\n          if (item.SequenceEqual(list[j])) {\n            equals.Add(j);\n            proceeded.Add(j);\n          }\n      }\n\n      return result;\n    }\n\n\n   ...\n\n   // Your test case:\n   List<int[]> list = new List<int[]>() {\n     new int[] {1, 2, 3, 4, 5, 5, 7},\n     new int[] {1},\n     new int[] {1, 2, 3},\n     new int[] {1, 2},\n     new int[] {1, 2, 3},\n     new int[] {1, 2, 3},\n     new int[] {1, 3},\n     new int[] {1, 2, 3, 4, 5, 5, 7}\n   };\n\n   // anotherList == {{0, 7}, {1}, {2, 4, 5}, {3}, {6}}\n   IList<IList<int>> anotherList = EqualArrays(list);	0
9613588	9613526	How to know if any items in listview has been double-clicked?	private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)\n    {\n\n    }	0
13534642	13534241	Use interop and c# to count the rows in an Excel spreadsheet's worksheet with data in	private string GetNumberOfRows(string filename, string sheetName)\n{\n    string connectionString;\n    string count = "";\n\n    if (filename.EndsWith(".xlsx"))\n    {\n        connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 12.0;HDR=NO\"";\n    }\n    else if (filename.EndsWith(".xls"))\n    {\n        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=NO;\"";\n    }\n\n    string SQL = "SELECT COUNT (*) FROM [" + sheetName + "$]";\n\n    using (OleDbConnection conn = new OleDbConnection(connectionString))\n    {\n        conn.Open();\n\n        using (OleDbCommand cmd = new OleDbCommand(SQL, conn))\n        {\n            using (OleDbDataReader reader = cmd.ExecuteReader())\n            {\n                reader.Read();\n                count = reader[0].ToString();\n            }\n        }\n\n        conn.Close();\n    }\n\n    return count;\n}	0
27190945	27190902	How to group data from table with multiple columns	var groupedCustomers = listToProcess\n       .GroupBy(cn => new { cn.CUST_NAME, cn.CUST_ADDRESS })\n       .Select(g => g.ToList()).ToList();	0
30397351	30397103	C# numeric onscreen keyboard	InputScope="Number"	0
22761222	22761122	Getting all aliased values with Enum.GetValues	Enum.GetNames(typeof(WhatEverEnum))	0
24670780	24670732	Split a string into a List<string>	myData.Replace(",", "").Split(';').ToList();	0
28927341	28927207	I cant get the values from xml document	string p = @"<Accounts>\n  <Account Id='1'>\n    <UserName>xxx@Hotmail.com</UserName>\n    <Password>xxx</Password>\n    <AddingDate>06 Mart 2015 Cuma</AddingDate>\n    <AccountType>Hotmail</AccountType>\n  </Account>\n</Accounts>";\n//I'm parsing a string instead of loading from a file but you get the same\n// object back so don't worry \nvar xdoc = XDocument.Parse(p);\n\nvar x = xdoc.Root.Elements("Account").Select (r => new { UserName = (string)r.Element("UserName"), Password = (string)r.Element("Password") });	0
33278823	33168932	ComponentOne WinRT finding route on map	WebRequest wc = HttpWebRequest.Create(uri);\ntry {\n   using (HttpWebResponse response = await wc.GetResponseAsync() as HttpWebResponse){\n      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BingMapsRESTService.Common.JSON.Response));\n      return ser.ReadObject(response.GetResponseStream()) as BingMapsRESTService.Common.JSON.Response;\n   }\n}\ncatch(Exception ex){\n   return null;\n}	0
2596405	2596317	Using a linq or lambda expression in C# return a collection plus a single value	public List<ChargeDetail> ChargeBreakdown\n{\n    get\n    {\n        return new List<ChargeDetail>(_chargeBreakdown) {PrimaryChargeDetail};\n    }\n}	0
11793061	11793020	Get the element from hashset where hashset.Count==1	yourHashSet.First();	0
24956857	24790877	Upload/Overwrite SharePoint document without loosing list item metadata from code	using (SPSite site = new SPSite(url))\n                {\n                    using (var web = site.OpenWeb())\n                    {\n                        var lib = web.Lists["Documents"] as SPDocumentLibrary;\n\n                        var file = web.GetFile(string.Format("{0}/Shared Documents/{1}", web.Url, fileName));\n\n                        if (file.Exists)\n                        {\n              file = lib.RootFolder.Files.Add(fileName, newContent, file.Properties, true);\n                        }\n                        else\n                            file = lib.RootFolder.Files.Add(fileName, newContent, true);\n}\n}	0
14085964	14085937	is it safe to apply double-checked locking to Dictionary?	Dictionary<TKey, TValue>	0
5111892	5111461	I need help modifying a C# regular expression	\[([^=]+)[=\x22']*(\S*?)['\x22]*\]|\[/(\1)\]	0
6497906	6497867	Get value of datarow in c#	list[0].MyString;	0
45	39	Reliable timer in a console application	Console.ReadLine()	0
6582352	6582020	Registry access with C# and "BUILD x86" on a 64bit machine	using Microsoft.Win32;\n...\nRegistryKey registryKey = \n    RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).\n    OpenSubKey(@"Software\Microsoft\InetStp\Components");\nobject value = registryKey.GetValue(@"WMICompatibility");	0
3626369	3626328	C#: How to create a generic superclass to be extended by non-generic subclasses	internal Repository(IUnitOfWork unitOfWork)	0
27354273	27347894	How to access children of UIElement to add animation	void animation(CellControl cell)\n{\n    var animation = new DoubleAnimation(0.0, 1.0, TimeSpan.FromSeconds(1.0));\n\n    cell.ellipse.BeginAnimation(UIElement.OpacityProperty, animation);\n}	0
2041480	2041452	How to find if a value is NULL in SQL Server using c#	if (dr.IsNull(dc))	0
33092271	33092171	How can I do an OrderBy with a dynamic string parameter order on a join query	var result2 = result.ToList();\nif (sort == "OrderID"){\n result2 = result.OrderBy(x=>x.OrderID).ToList();\n}	0
2580061	2562485	Serialization for memcached	[Serializable]	0
7177143	7177088	C# - How to open an Excel application?	myApp.Visible	0
6645302	6644787	logic of point of sale?	CREATE Procedure ClientSaleSearch\n(\n    @clientid int\n)\nSELECT saleid\nFrom Sale\nWHERE id=@userid AND isSaleCompleted = '0'	0
2663743	2663730	Visual C# 2008 Control to set a path	var folderBrowserDiaglog = new FolderBrowserDiaglog();\nif ( folderBrowserDiaglog.ShowDialog() == DialogResult.OK )\n{\n  string path = folderBrowserDiaglog.SelectedPath;\n}	0
23755882	23755584	Remove Commas from String Asp.net	string abc = "....abc";\n string trimmedResult = new String(abc.Where(Char.IsLetterOrDigit).ToArray());	0
2179156	2179116	How Can I assert /verify a Moq Protected Method?	[TextFixture]\npublic class CustomerTestFixture\n{\n   var customer = new Customer();\n   var accessor = new Customer_Accessor( new PrivateObject( customer ) );\n\n   Assert.IsTrue( accessor.CanTestPrivateMethod() );\n\n}	0
4503929	4503892	year in 2year format	Console.WriteLine(test.ToString("M/d/yy",dateTimeFormat));	0
4568892	4568884	Easiest way of casting List<Descendant> to List<Base>	List<Descendant> descendants = ...;\n\ndescendants.Cast<Base>().ToList();	0
2797074	2797069	Versioning issues with assemblies	Assembly Binding Redirection	0
1662456	1662216	Return JsonResult using an ActionFilter on an ActionResult in a controller	public class ResultFormatAttribute : ActionFilterAttribute, IActionFilter\n{\n    void IActionFilter.OnActionExecuted(ActionExecutedContext context)\n    {\n        context.Result = new JsonResult\n        {\n            Data = ((ViewResult)context.Result).ViewData.Model\n        };\n    }\n}	0
17536089	17536032	Link help button to help File	//Event-Handler overloading\nthis.HelpBtn.Click += new System.EventHandler(this.HelpBtn_Click);\n\n//The Event-Handler declarion\nprivate void HelpBtn_Click(object sender, EventArgs e)\n{\n    Help.ShowHelp(this, "file://c:\\yourHelpFiles\\help.chm");\n}	0
15679056	15678441	Regex, extracting numbered lists (multi lines)	string input = @"1. This is a text\n    where each item can span over multiple lines\n    2. that I want to\n    extract each seperate\n    item from\n    3. How can I do that?";\nstring pattern = @"([\d]+\. )(.*?)(?=([\d]+\.)|($))";\nvar matches = Regex.Matches(input, pattern, RegexOptions.Singleline);\n\nforeach(Match match in matches)\n{\n    Console.WriteLine(match.Groups[2].Value);\n}	0
15274909	15274833	Modify get/set values populated by JSON C#	public string url_check\n{\n    set\n    {\n        if (!string.IsNullOrEmpty(url))\n        {\n            this._external= "";\n        }\n        else\n        {\n            this._external= "[external]";\n        }\n    }\n\n}	0
6387682	6387578	Serialization no null values	[Serializable()]\npublic class Car\n{\n    public string colour;\n    public string model;\n    public int year;\n\n    [OnDeserialized()]\n    internal void OnDeserializedMethod(StreamingContext context)\n    {\n       if (colour == null)\n       {\n           colour = string.Empty;\n       }\n    }\n}	0
1355115	1355100	Compressing big number (or string) to small value	string xx = IntToString(42, \n            new char[] { '0','1','2','3','4','5','6','7','8','9',\n            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',\n            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'});	0
11630261	11630197	Create array of TimerCallback	using System.Threading;\n\nnamespace ConsoleApplication18\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var callbacks = new TimerCallback[]\n            {    \n              new TimerCallback(Foo),\n              new TimerCallback(Bar),\n              new TimerCallback(FooBar)\n        }\n    }\n}	0
28832427	28831709	Is there any method to Get all Flags that are not of a type in FlagsAttributed enum?	var query= @"select * from colors\nwhere (value & " + (int)Colors.Green + ") = 0";	0
32377006	32361725	Losing char when inserting/updating data at SQLite with C#	Does this work? db.Execute("update People set FirstName = ? where PeopleID = ?", "S??rgio", 2);	0
22261525	22261468	Return item 1 to 3 and 4 to 6 and 7 to 9 in a grouped object with LINQ	List<List<string>> groups = inputList.Select((e, idx) => new { Item = e, Idx = idx })\n    .GroupBy(p => p.Idx / 3)\n    .Select(grp => grp.Select(p => p.Item).ToList())\n    .ToList();	0
27693622	27381034	There is a pending asynchronous operation, and only one asynchronous operation can be pending concurrently	var provider = new MultipartFormDataStreamProvider(root);\n\n            Request.Content.LoadIntoBufferAsync().Wait();\n\n            //// Read the form data and return an async task. \n            await Request.Content.ReadAsMultipartAsync(provider);	0
6645880	6645852	Date Format difference causing crash	DateTime.Parse(ss)	0
24323673	24315186	How to play the SMS alert sound in Windows Phone 8	.Play()	0
25820	25803	How do I intercept a method call in C#?	[Log()]\npublic void Method1(String name, Int32 value);	0
15800109	15800081	blocking screen access from win form	Form1 form1 = new Form1();\n/* Calling ShowDialog instead of Form.Show() will force\n* the user to close that form first */\nform1.ShowDialog();	0
24850417	24846869	Why is it so hard to get route values outside controller context?	[Route("{id}"), HttpGet]\npublic IHttpActionResult Test(int? id) //the easiest way to get route value for {id}\n{\n    // Simple and easy\n    var route1 = Request.GetRouteData().Values["id"];\n\n    // Wat. This is also ~6 times slower\n    var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values["MS_SubRoutes"];\n    var route2 = routeValues.SelectMany(x => x.Values).Where(x => x.Key == "id").Select(x => x.Value).FirstOrDefault();\n\n    return Ok(route1 == route2 == id.Value); // true //should be true, and of course you should add null check since it is int? not int. But that is not significant here so I didn't do it.\n}	0
2360827	2360822	How do I call TryParse from within a Predicate	string[] nums = num.Split('.');\nPexAssume.TrueForAll(nums, x => { int result; return int.TryParse(x, out result); });	0
22263789	22263678	Add data from Textbox to GridView on button click	dt.Columns.Add(new DataColumn("Classification", typeof(string)));	0
30478067	30477759	How to determine the session type in asp.net	System.Web.HttpContext.Current.Session.Mode	0
32179928	32179274	Remove first row contents in excel while export to excel	var rowCounter = 0;\nvar cellCounter = 0;\nforeach (GridViewRow row in grdHorizontalSeatDashboard.Rows)\n{\n    foreach (TableCell cell in row.Cells)\n    {\n        if (rowCounter == 0 && cellCounter == 0) \n        {\n            cell.Text = "";\n        }\n\n        cell.BackColor = row.BackColor;\n        cell.HorizontalAlign = HorizontalAlign.Center;\n        cell.CssClass = "textmode";\n    }\n    cellCounter = 0;\n    rowCounter++;\n}	0
18330927	18330185	Open Context Menu by ctrl+menu	public MainWindow()\n    {\n      InitializeComponent();\n      this.PreviewKeyUp += MainWindow_PreviewKeyUp;\n\n    }\n\n    void MainWindow_PreviewKeyUp(object sender, KeyEventArgs e)\n    {\n      if (e.Key == Key.Apps)\n      {\n        e.Handled = true;\n      }\n    }	0
31085623	31085575	Deleting Folder which Contains Many Sub Folder and Sub Folder Contains Many More	DirectoryInfo dir = new DirectoryInfo(TargetFolder);\n\ndir.Delete(true);	0
7865653	7862824	Activating views in regions in Prism	public void Initialize()\n    {\n        regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => \n            ServiceLocator.Current.GetInstance<Views.Module2View>());\n\n        Button button = new Button() { Content = "Module2" };\n        button.Click += (o, i) =>\n        {\n            var view = ServiceLocator.Current.GetInstance<Views.Module2View>();\n\n            var region = this.regionManager.Regions[RegionNames.MainRegion];\n            if (region != null)\n            {\n                region.Activate(view);\n            }             \n        };\n\n        regionManager.AddToRegion(RegionNames.NavigationRegion, button);\n    }	0
16955055	16954564	Working with access connection string	Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\jaame.accdb;\nPersist Security Info=False;	0
18659760	18614477	How can I implement RS485 2 wires bidirectional communication in .NET?	// Enable send mode\nSerialPort.DtrEnable = false;\nSerialPort.Write(data, 0, data.Length);\n\n// Wait a little, then enable response mode.\nThread.Sleep(15);\nSerialPort.DtrEnable = true;	0
18672893	18670111	Task from cancellation token?	public static Task AsTask(this CancellationToken cancellationToken)\n{\n    var tcs = new TaskCompletionSource();\n    cancellationToken.Register(() => tcs.TrySetCanceled(),\n        useSynchronizationContext: false);\n    return tcs.Task;\n}	0
21390471	21390400	compare the length of two variable	foreach(DataRow row in dt.Rows)\n                {\n                    string url = "http://abcd/<userid>?groups=<userid>";\n                    var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));\n                    System.Diagnostics.Process.Start(url);\n                    string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");\n                    if (client.ToLower() == Convert.ToString(TrackID).ToLower())\n                    {\n                        counter++;\n                    }	0
31791170	31785197	How to place SplitView in the header of a phone in UWP?	DisplayMode="Overlay"	0
4090835	4090776	How to add a custom control on TOP of another one	private void lbRappel_Click(object sender, EventArgs e)\n{\n    NoteCallBack noteCallBack = new NoteCallBack("test");\n    this.Controls.Add(noteCallBack);\n    noteCallBack.Location = new Point(200, 250);\n    noteCallBack.BringToFront();\n}	0
26681622	26680329	Using log4net as a class library?	LogManager.GetLogger("Initialise log4net from the current assembly attributes");	0
7047973	7047936	formatting phone number with linq	var phoneNumber = "4081234567";\nvar phoneFormat = Regex.Replace(phoneNumber, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");	0
11947541	11947526	C# - How to transform a For loop into a Linq expression?	myStringList = myStringList.Select(x => x.ToUpper()).ToList();	0
31135128	31134853	Is it possible to create multiple objects from an XML file?	using System.Xml.Linq;\n\nXDocument xdoc = XDocument.Load(@"...\path\document.xml");\n\nList<xmlvalues> lists = (from lv1 in xdoc.Descendants("instance")\n                       select new xmlvalues\n                       {\n                           id = lv1.Element("id"),\n                           a= lv1.Element("a"),\n                           b= lv1.Element("b"),\n                           c= lv1.Element("c")\n                       }).ToList();	0
17125773	17125642	How to verify a users password?	Membership.ValidateUser(string username, string password)	0
21879009	21878820	How to get max value of a string column of numbers in Entity Framework	LastInvoiceNo = dbContext.InvoiceMaster.ToList().Max(e => Convert.ToInt64(e.InvoiceNo));	0
16670853	16670700	How to remove comma separated value from a string?	List<String> Items = x.Split(",").Select(i => i.Trim()).Where(i => i != string.Empty).ToList(); //Split them all and remove spaces\nItems.Remove("v"); //or whichever you want\nstring NewX = String.Join(", ", Items.ToArray());	0
13844953	13844816	Populate a nested list from a nested list	FilterModel Transfer(Product product)\n{\n    var fm = new FilterModel();\n    fm.Code = product.Code;\n    fm.Children = new List<FilterModel>();\n\n    foreach (var p in product.Children)\n    {\n        fm.Children.Add(Transfer(p));\n    }\n\n    return fm;\n}	0
142263	142252	Test if a floating point number is an integer	d == Math.Floor(d)	0
3888760	3887645	how to use parameter in linq to select different columns	public object GetData (string colName) {\n      NorthwindDataContext db = new NorthwindDataContext();\n      var q = db.Products.Select(colName);\n      List list = new List();\n      foreach (var element in q) {\n        if (!list.Contains(element))\n          list.Add(element);\n      }\n      return list;	0
1525698	1525580	Is there a BinaryReader in C++ to read data written from a BinaryWriter in C#?	int i;\nfin.read((char*)&i, sizeof(int));	0
10356512	10356481	how can I copy arrays with their keys and values with a foreach loop in c#?	foreach (var item in dict) {\n  var key = item.Key;\n  var value = item.Value;\n}	0
31285633	31285309	Fast string insertion at front in c#	var numStrings = 80000;\nvar strings = new List<String>();\nfor(var i = 0; i < numStrings; i++)\n{\n    strings.Add(Guid.NewGuid().ToString());\n}\n\nvar sw = new Stopwatch();\nsw.Start();\nvar sb = new StringBuilder();\nforeach(var str in Enumerable.Reverse(strings))\n    sb.Append(str);\n\nsw.Stop();\nsw.ElapsedMilliseconds.Dump(); // 13 milliseconds\nsb.Dump();\n\nsw = new Stopwatch();\nsw.Start();\nsb = new StringBuilder();\nforeach(var str in strings)\n    sb.Insert(0, str);\n\nsw.Stop();\nsw.ElapsedMilliseconds.Dump(); // 42063 milliseconds\nsb.Dump();	0
14072214	14072148	Find HTML table row which has special text	(<tr><td>Total.*?</tr>)	0
11067054	11065608	How to display text being held in a int variable?	private void button1_Click(object sender, EventArgs e)\n        {\n            var ok = "OK" + (char)0;\n            var ascii = Encoding.ASCII;\n\n            var bin = ascii.GetBytes( ok );\n\n            var sb = new StringBuilder();\n            unsafe\n            {\n\n                fixed (byte* p = bin)\n                {\n                    byte b = 1;\n                    var i = 0;\n                    while (b != 0)\n                    {\n                        b = p[i];\n\n                        if (b != 0) sb.Append( ascii.GetString( new[] {b} ) );\n                        i++;\n                    }\n                }\n            }\n            Console.WriteLine(sb);\n        }	0
34479707	34479633	Efficient Way To Get Line from StreamReader which Matches Regex in C#	Can\nyou\nmatch\nme\nif\nyou\nread\nme\nline\nby\nline?	0
6460528	6460156	Testing paging with Telerik's WebAii framework	[TestMethod]\n    public void TestPagingCauseFailure()\n    {\n        // act\n        OpenPage(true);\n\n        // get the hidden fields on this page\n        IList<HtmlInputHidden> _hiddenFieldsList = Find.AllByAttributes<HtmlInputHidden>("~hfFailureID");\n\n        IList<HtmlAnchor> _pageIndexes = Find.AllByAttributes<HtmlAnchor>("href=~pageid");\n\n        // there are 12 pages (not including page 1)\n        Assert.IsTrue(Equals(12,_pageIndexes.Count));\n\n        // goto last page\n        _pageIndexes.Last().Click();\n\n        //get the hidden fields on this page\n        IList<HtmlInputHidden> _hiddenFieldsList2 = Find.AllByAttributes<HtmlInputHidden>("~hfFailureID");\n\n        string value1 = _hiddenFieldsList.Last().ID;\n        string value2 = _hiddenFieldsList2.Last().ID;\n\n        //compare the two last items in boths lists\n        Assert.IsFalse(Equals(value1, value2));\n\n    }	0
5077054	5074977	how to set checkbox value false in datagridview one row	private void dgvTodaysPlan_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n        {\n            if (dgvTodaysPlan.CurrentCell is System.Windows.Forms.DataGridViewCheckBoxCell)\n            {\n                dgvTodaysPlan.CommitEdit(DataGridViewDataErrorContexts.Commit);\n            }\n\n        }	0
13343318	13343041	Use func<> to return an int to database connector	entity.ID = db.Create(\n    entity.Name,\n    entity.Description,\n    entity.InitialStep != null ? (int?)entity.InitialStep.ID : null,\n    entity.IsPrivate,\n    entity.AllowOnBehalfSubmission,\n    new Func<Type, int?> (type => \n    {\n        if (type == typeof(SomeType))\n            return 1;\n        if (type == typeof(AnotherType))\n            return 2;\n        return null;\n    })(entity.GetType())\n);	0
10659923	10657528	c++/cli calling a native c++ method	// Assembly msxml6\n\n  Location: C:\Windows\System32\msxml6.dll\n  Name: msxml6, 'C:\Windows\System32\msxml6.dll' is not a .NET module.	0
2175385	2175374	how to find modulus of a number in c#	int x = 4545;\nint mod = x % 16;	0
6294383	6293533	Exporting Microsoft Chart to PDF and JPG formats	Chart1.SaveImage(@"C:\MyImage.jpg", System.Web.UI.DataVisualization.Charting.ChartImageFormat.Jpeg);	0
10150483	10147347	Insert data into excel spreadsheet and print	using Excel = Microsoft.Office.Interop.Excel;\n\nExcel.Application xlApp; \nExcel.Workbook xlWorkBook; \nExcel.Worksheet xlWorkSheet; \nobject misValue = System.Reflection.Missing.Value; \n\nxlApp = new Excel.ApplicationClass(); \nxlWorkBook = xlApp.Workbooks.Open(_filename, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); \nxlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); \n\n//Attribute a value to a cell\nvar cell = (Range)xlWorkSheet .Cells[row, column];\ncell.Value2 = "Test";\n\n//This should print\nxlWorkBook.PrintOut (Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);\n\nxlWorkBook.Close(false, misValue, misValue); \nxlApp.Quit();	0
5859090	5857943	Add RotateTransform animation to Storyboard in code-behind	DoubleAnimation dbAscending = new DoubleAnimation(0, 15, new Duration(TimeSpan.FromMilliseconds(300)));\nStoryboard storyboard = new Storyboard();\nstoryboard.Children.Add(dbAscending);\nStoryboard.SetTarget(dbAscending, myImage);\nStoryboard.SetTargetProperty(dbAscending, new PropertyPath("RenderTransform.Angle"));	0
23773817	23773750	How to convert following SQL Query into Lambda Expression?	var lambdaQuery = _dbContext.BackgroundPackages\n    .Join(_dbContext.BkgPackageHierarchyMappings, ep => ep.BPA_ID, e => e.BPHM_BackgroundPackageID, (ep, e) => ep)\n    .Join(_dbContext.BkgOrderPackages, ep => ep.BPHM_ID, t => t.BOP_BkgPackageHierarchyMappingID, (ep, t) => new { ep, t})\n    .Join(_dbContext.BkgOrders, ept => ept.t.BOP_BkgOrderID, s => s.BOR_ID, (ept, s) => new { ept.ep, s })\n    .Where(eps => eps.s.BOR_MasterOrderID  == orderId && eps.s.BOR_IsDeleted == 0)\n    .Select(eps => eps.ep);	0
21619252	21615301	Issue with DateTime extract from SQLite Database C# WPF	DateTime dt = DateTime.ParseExact(out_date, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);	0
25602759	25601624	Checking two attributes in an object	if (!asset.category.Equals("DefaultMapMarker") && asset.userName != User.Identity.GetUserName()))\n{\n    return HttpNotFound();\n}	0
32832145	32830757	How can I get the line of an word in a textbox?	List<string> lines = new List<string>(textBox1.Lines);\n        for(int i = 0; i < lines.Count; i++)\n        {\n            // check for some condition\n            if (lines[i].StartsWith("Di"))\n            {\n                // modify the line somehow\n                lines[i] = lines[i] + ", " + textBox2.Text;\n                break; // optionally break?...or modify other lines as well?\n            }\n        }\n        textBox1.Lines = lines.ToArray(); // update the textbox with the new lines	0
3884067	3884025	Partially Overriding a Virtual Auto-Property in a Child Class	class A\n{\n    public virtual int P1\n    {\n        get { return 42; }\n        set { }\n    }\n}\n\nclass B : A\n{\n    public override int P1\n    {\n        get { return 18; }\n    }\n}	0
12185429	12185387	Advantage of making a List to a ReadOnlyCollection or AsReadOnly	public ReadOnlyCollection<T> AsReadOnly()\n{\n    return new ReadOnlyCollection<T>(this);\n}	0
17059669	17059235	Linq get data as quaternary packs	public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize)\n{\n    for (int i = 0; i < source.Count(); i+=batchSize)\n    {\n        yield return source.Skip(i).Take(batchSize);\n    }\n}	0
9750904	9750814	How to update a value in a column in a datatable which is in a foreachloop?	foreach (DataRow row in myTable.Rows) \n        {\n             Double i = 0;\n             Double j = Convert.ToDouble(row["x"]);\n             int y = 1;\n\n             int aan = Convert.ToInt32(row["year"]);\n\n                 if(y == aan) \n                 {\n                    i = j + 2;\n                 }\n\n             row["x"]=i;\n             row.EndEdit();\n             myTable.AcceptChanges();\n\n        }	0
19860603	19860516	How to change default validation error message?	[Required(ErrorMessage="Your Message")]	0
1011606	1011553	How can I create a control with IPAddress properties that can be edited in the designer?	[Browsable(true)]\n[DisplayName("IPAddress")]\npublic string IPAddressText\n{\n    get { return this.IPAddress.ToString(); }\n    set { this.IPAddress = IPAddress.Parse(value); }\n}\n\n[Browsable(false)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic IPAddress IPAddress\n{\n    get;\n    set;\n}	0
5743161	5743099	Looping through GridView rows and Checking Checkbox Control	foreach (GridViewRow row in grid.Rows)\n{\n   if (((CheckBox)row.FindControl("chkboxid")).Checked)\n   {\n    //read the label            \n   }            \n}	0
692728	692723	XPath: select all A nodes and all B nodes that are not inside an A node	//span[@class='msg'] | //img[@alt!='' and not(ancestor::span[@class='msg'])]	0
31359037	31358740	How to print a CSV file in console?	public class CsvRow\n{\n    public CsvRow()\n    {\n    }\n\n    public CsvRow(string a, string b)\n    {\n        A = a;\n        B = b;\n    }\n    public string A {get; set;}\n    public string B {get; set;}\n\n    public string ToString(int rowNumber)\n    {\n        return String.Format("Row{0}: {1} {2}", rowNumber, A, B);\n    }\n\n}\n\npublic class Program\n{\n    public static void Main()\n    {\n        var results = new List<CsvRow>();\n        results.Add(new CsvRow(DateTime.Now.ToString(), "200"));\n        results.Add(new CsvRow(DateTime.Now.ToString(), "300"));            \n\n        var i = 0;\n        foreach (var result in results)\n        {\n            Console.WriteLine(result.ToString(i));\n            i++;\n        }       \n    }\n}	0
10435186	10434646	Enumerating results view for data in an SSRS report	IEnumerable<XElement> GetCommandText(string file)\n    {\n    XDocument xdoc = XDocument.Load(file);\n    return xdoc.Root.Elements().Where(r => (string)r.Attribute("Name") == "Command Text");\n    }	0
27150502	27150483	how to compare three strings using strig.compare in c#.net?	if (String.Compare(str1, str2) == 0 &&  \n    String.Compare(str2, str3) == 0)	0
11513164	11513122	Examples of Quickbase API in C#	using System;\nusing Intuit.QuickBase.Client;\n\nnamespace MyProgram.QB.Interaction\n{\n    class MyApplication\n    {\n        static void Main(string[] args)\n        {\n            var client = QuickBase.Client.QuickBase.Login("your_QB_username", "your_QB_password");\n            var application = client.Connect("your_app_dbid", "your_app_token");\n            var table = application.GetTable("your_table_dbid");\n            table.Query();\n\n            foreach(var record in table.Records)\n            {\n               Console.WriteLine(record["your_column_heading"]);\n            }\n            client.Logout();\n        }\n    }\n}	0
23798106	23797982	Capture functions using regex	function[\s.]*\(([^\)]*)(\))	0
25942659	25942567	Automatically navigate to another page	await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>\n{\n    Frame.Navigate(typeof(LoginPage));\n});	0
28857887	28857793	How to get the first column value of a selected row in GridView	var cellText= ((GridViewRow)(((System.Web.UI.WebControls.CheckBox)sender).Parent.Parent)).Cells[0].Text;	0
6011274	6011252	How to create a control that has a collection	public class MyControl:WebControl\n{\n    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content),\n    PersistenceMode(PersistenceMode.InnerDefaultProperty)]\n    public List<MySubItems> Items {get; set;}\n}	0
26840014	26805683	How to filter datatable rows in debug mode	Select("ID = 16805552")	0
3647975	3644881	Simulating Keyboard with SendInput API in DirectInput applications	INPUT[] InputData = new INPUT[1];\n\nInputData[0].Type = (UInt32)InputType.KEYBOARD;\n//InputData[0].Vk = (ushort)DirectInputKeyScanCode;  //Virtual key is ignored when sending scan code\nInputData[0].Scan = (ushort)DirectInputKeyScanCode;\nInputData[0].Flags = (uint)KeyboardFlag.KEYUP | (uint)KeyboardFlag.SCANCODE;\nInputData[0].Time = 0;\nInputData[0].ExtraInfo = IntPtr.Zero;\n\n// Send Keyup flag "OR"ed with Scancode flag for keyup to work properly\nSendInput(1, InputData, Marshal.SizeOf(typeof(INPUT)))	0
5902047	5900383	Fluent nHibernate - Mapping Children with Composite Keys Yielding Null References	ChildMap() {\n      CompositeId() //This is is good\n        .KeyReference(x => x.Parent, "ParentId")\n        .KeyReference(x => x.Other, "OtherId");\n  }\n\n  ParentMap(){ //This is the fix\n        HasMany(c => c.Children)\n          .Inverse()\n          .Cascade.All()\n          .KeyColumn("ParentId") //Not needed if Parent Id prop maps to ParentId col\n          .Table("[Test]");\n  }	0
28463994	28461422	Deserializing nested XML into arrays	[Serializable]\n//[XmlRoot("Directories")]\npublic class Directories\n{\n    //[XmlElement("Directory")]\n    public List<Directory> Directory { get; set; }\n}\n\n[Serializable]\npublic class Directory\n{\n    //[XmlAttribute()]\n    public string Path { get; set; }\n\n    //[XmlArray("Files")]\n    //[XmlArrayItem("File")]\n    public List<XmlFileInfo> Files { get; set; }\n}\n\n[Serializable]\npublic class XmlFileInfo\n{\n    //[XmlElement("File")]\n    public string File { get; set; }\n\n    //[XmlAttribute()]\n    public MyobstruficatedEnum Type { get; set; }\n}	0
11135057	11134806	read float pixel data from a file back to C#	Bitmap BytesToBitmap (byte[] bmpBytes, Size imageSize)\n{\n    Bitmap bmp = new Bitmap (imageSize.Width, imageSize.Height);\n\n    BitmapData bData  = bmp.LockBits (new Rectangle (0,0, bmp.Size.Width,bmp.Size.Length),\n        ImageLockMode.WriteOnly,\n        PixelFormat.Format32bppRgb);\n\n    // Copy the bytes to the bitmap object\n    Marshal.Copy (bmpBytes, 0, bData.Scan0, bmpBytes.Length);\n    bmp.UnlockBits(bData);\n    return bmp;\n}	0
17164485	17153739	Connecting to a specific SQL Server instance on another machine	Data Source=192.168.1.50\SQLEXPRESS,1433;Network Library=DBMSSOCN;Initial Catalog=DbName;User ID=SomeUser;Password=SecretPassword;	0
3238281	3238040	Scheduling a single-fire event	void dataLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  \n{  \n    DataLabel.Text = "Database Loaded";  \n    var timer = new System.Windows.Forms.Timer();  \n    timer.Interval = 5000;  \n    timer.Tick += (o, a) =>  \n    {  \n        timer.Stop();\n        DataLabel.Text = "";\n    };\n    timer.Start();\n}	0
2050422	2050396	Getting the date of a .NET assembly	File.GetCreationTime(Assembly.GetExecutingAssembly().Location)	0
2003204	2003176	C# - object-oriented way of writing HTML as a string?	private string getHTMLString()\n{\n    DirectoryInfo di = new DirectoryInfo("some directory");\n    FileInfo[] files = di.GetFiles("*.dll", SearchOption.AllDirectories);\n    StringBuilder sb = new StringBuilder();\n    sb.Append("<table>");\n    foreach (FileInfo file in files)\n    {\n        Assembly assembly = Assembly.LoadFile(file.FullName);\n        string version = assembly.GetName().Version.ToString();\n        sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", file.FullName, version);\n    }\n    sb.Append("</table>");\n    return sb.ToString();\n\n }	0
27872516	27872371	How to create users from old asp.net membership to new MVC .net and send password reset	//loop for each email address from old DB\n\nvar user = new ApplicationUser { UserName = _email, Email = _email };\nvar result = await UserManager.CreateAsync(user, "TempPass123!");\nif (result.Succeeded)\n{\n //reset the password\n}	0
1509257	1509241	Lambda expression with a void input	() => 2	0
11460646	11460558	LINQ query for subset of two parallel arrays	var zipped = xs.Zip(ys, (x, y) => new { x, y })\n               .Where(coord => coord.x > 0.1 && coord.x <= 0.2);	0
22062144	22061684	Problems with creating controls dynamically	new Label() {AutoSize =true, Text = "X", Location = point }	0
1673410	1673315	Save file with double quote	using (StreamWriter strm = new StreamWriter(fileSts, true, Encoding.GetEncoding(1252))) {\n    strm.WriteLine(recno);\n}	0
3550499	3546747	LINQ to XML query	var query = from f in fDoc.Descendants("company")\n                    where ((string)f.Attribute("active")).Equals("1")\n                    orderby f.Element("name").Value\n                    from r in rDoc.Descendants("bill")\n                    where (f.Element("category").Value).Split(',').Contains(r.Element("category").Value)\n                    group new\n                    {\n                        BillTotal = Convert.ToInt32(r.Element("total").Value)\n                    }\n                    by f.Element("name").Value + f.Element("location").Value + f.Element("room").Value into g\n                    select new\n                    {\n                        Name = g.Key,\n                        Total = g.Sum(rec => rec.BillTotal),\n                    };	0
14212639	14205635	How to scroll to selected item in listBox?	ListItem listItem = null;\n\n        while (reader.Read())\n        {\n            listItem = new ListItem(reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString());\n            this.lbxCustomers.Items.Add(listItem);,\n            lbxCustomers.SelectedItem = listItem;\n        }	0
22461707	22461557	Multiple ScreenShot	Bitmap[] screenshot = new Bitmap[10];\nString name = "Screenshot";    \n\nfor(int i = 0; i < 10 ; i++)\n{\n\n screenshot[i] = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);\n screenshot[i].Save("PATH" + name + i);\n\n}	0
13012669	13012585	How I can filter a Datatable?	DataView dv = new DataView(yourDatatable);\ndv.RowFilter = "query"; // query example = "id = 10"	0
11948185	11948108	How to get the mouse position and use it in the client	var pt = listView.PointToClient( Control.MousePosition );	0
4970241	4970225	Setting A String To A .txt's File Contents?	File.ReadAllText	0
2382968	2192544	Programmatically getting SQL Cluster Virtual Name	using System.Management;\n\nManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\MSCluster", "SELECT * FROM MSCluster_Resource"); \n\nforeach (ManagementObject queryObj in searcher.Get())\n{\n    Console.WriteLine("Name: {0}", queryObj["Name"]);\n}	0
18366943	18366882	Application will not launch from command line full path, but will after CDing to directory	Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;	0
6289490	6289451	Catch a mouse click event on a control	private void button1_Click(object sender, System.EventArgs e)\n{\n    if(sender is Button)//MyControl in you case \n    {\n     //your code \n    }\n}	0
4255238	4253438	How to copy the selected image from picture library to the images folder dynamically in the application?	void photoChooserTask_Completed(object sender, PhotoResult e)\n{\n    if (e.TaskResult == TaskResult.OK)\n    {\n        var contents = new byte[1024];\n\n        using (var store = IsolatedStorageFile.GetUserStoreForApplication())\n        {\n            using (var local = new IsolatedStorageFileStream("image.jpg", FileMode.Create, store))\n            {\n                int bytes;\n                while ((bytes = e.ChosenPhoto.Read(contents, 0, contents.Length)) > 0)\n                {\n                    local.Write(contents, 0, bytes);\n                }\n            }\n\n            // Read the saved image back out\n            var fileStream = store.OpenFile("image.jpg", FileMode.Open, FileAccess.Read);\n            var imageAsBitmap = PictureDecoder.DecodeJpeg(fileStream);\n\n            // Display the read image in a control on the page called 'MyImage'\n            MyImage.Source = imageAsBitmap;\n        }\n    }\n}	0
5615127	5614804	How do you implement a Styling for Windows forms Application C#?	using System;\nusing System.Windows.Forms;\n\ninternal class MyButton : Button {\n    public MyButton() {\n        this.FlatStyle = FlatStyle.Flat;\n        // etc..\n    }\n}	0
21046655	21046613	How do I search through a property for a particular value?	PersonRepository.Where(x => x.EmailAddresses\n                             .Any(a => a.Address == "myemail@host.com"))	0
1070557	1070526	How to return anonymous type from c# method that uses LINQ to SQL	public class Person\n{\n    public Person() {\n    }\n\n    public String Name { get; set; }\n    public DateTime DOB { get; set; }\n}\n\n\nPerson p = \n    from person in db.People \n    where person.Id = 1 \n    select new Person { \n        Name = person.Name,\n        DOB = person.DateOfBirth\n    }	0
27957795	27957722	How to Convert List<T[]> to array T[]?	// Namespaces you need\nusing System.Linq;\nusing System.Collections.Generic;\n\n\n////////////////////////////////////////////\n// In your code block                     //\n////////////////////////////////////////////\nList<T[]> myJaggedList = new List<T[]>();\n\n// (Populate here)\n\nT[] flatArray = myJaggedList.SelectMany(m => m).ToArray();	0
7572061	7571736	Silverlight - Close Browser Window	HtmlPage.Window.Invoke("open", new object[] {"", "_self", ""} );\nHtmlPage.Window.Invoke("close");	0
18610915	18610753	How Can i send the email from the MVC4 to my gmail without using my password?	smtp.gmail.com	0
27341892	27341657	How to call my int array class to ad my dropdownlist	var collection = ddDuration();\nint len = collection.length;\nfor(int i=0; i<len; i++){\n    DropDownList1.Items.Insert(i, new ListItem(collection[i].toString(), ""));\n}	0
3896268	3896262	make script to download all Mp3 files from a page	class Program\n{\n    static void Main()\n    {\n        using (var reader = new SgmlReader())\n        {\n            reader.DocType = "HTML";\n            reader.Href = "http://www.example.com";\n            var doc = new XmlDocument();\n            doc.Load(reader);\n            var anchors = doc.SelectNodes("//a/@href[contains(., 'mp3') or contains(., 'wav')]");\n            foreach (XmlAttribute href in anchors)\n            {\n                using (var client = new WebClient())\n                {\n                    var data = client.DownloadData(href.Value);\n                    // TODO: do something with the downloaded data\n                }\n            }\n        }\n    }\n}	0
1445888	1445865	Convert C# DateTime object to libpcap capture file timestamp	DateTime dateToConvert = DateTime.Now;\nDateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\nTimeSpan diff = date - origin;\n\n// Seconds since 1970\nuint ts_sec = Math.Floor(diff.TotalSeconds);\n// Microsecond offset\nuint ts_usec = 1000000 * (diff.TotalSeconds - ts_sec);	0
23880978	23780098	Adding some text in FarPoint while Export To Excel	FpSpread fpproxy = new FpSpread();\n    fpproxy = OriginalFPspread;\n\n    fpproxy .ActiveSheetView.AddColumns(0, 2);// add new column\n\n    fpproxy .Cells[0, 1].Column.Label = "your data";\n    fpproxy .Cells[0, 1].Value = "your value";	0
14392103	14391762	Continue processing in spite of unavailable WCF Service	try \n{\n    ....\n}\nfinally \n{\n    ....\n}	0
29220399	29202151	SSRS DateTime Parameters DefaultValue Format	public partial class ReportingService : DevReportService.ReportingService2010\n{\n\n    /// <summary>\n\n    /// Gets or sets the culture that is used when generating the report.\n\n    /// </summary>\n\n    /// <value>The culture that is used when generating the report.</value>\n\n    public CultureInfo Culture { get; set; }\n\n    protected override WebRequest GetWebRequest(Uri uri)\n    {\n\n        WebRequest request = base.GetWebRequest(uri);\n\n        CultureInfo culture = this.Culture ?? CultureInfo.CurrentCulture;\n\n        request.Headers.Add(HttpRequestHeader.AcceptLanguage, culture.Name);\n\n        return request;\n\n    }\n\n}	0
10961274	10961215	comparing 2 dates	DateTime.Compare()	0
10511633	10511602	Add type restrictions to multiple type parameters?	where T1: IComparable where T2: IConvertible	0
2701904	2697248	Clear text username password authentication in Wcf over https	Sachin said... \nHow does this work in IIS hosted environment with SSL certificate. Also in order to provide interoperability how will the clients using non woindows environment will be able to provide the user credentioals? \n\nFebruary 18, 2009 9:06 PM  \n Yaron Naveh said... \nHi Sachin\n\nWhen SSL is used there is no need for clearUsernameBinding - you can use the out of the box WCF configurations.\n\nAs for interoperability, clearUsernameBinding adheres to the WSS username profile.	0
17270579	17270462	C# Find and show html element in webBrowser	StringBuilder sb=new StringBuilder();\nforeach (HtmlElement elm in webBrowser1.Document.All)\n    if (elm.GetAttribute("className") == "link3")\n        sb.Append(elm.InnerHtml);\nHtmlDocument doc = webBrowser1.Document;\ndoc.Body.InnerHtml=sb.ToString();	0
21604593	21604524	How can I create a Dictionary from an Enum?	Dictionary<int, string> values = \n     Enum.GetValues(typeof(MyEnum))\n         .Cast<MyEnum>()\n         .ToDictionary(e => (int)e, e => e.ToString());	0
20931621	20931534	Entity Framework - Run function after properties are populated	[NotMapped]\nprivate int? _GaterRate;\n\npublic int GaterRate() {\n    if (!_GaterRate.HasValue)\n        GaterRate = GetAllResourceGatherers();//this would have to return the GatherRate of course;\n\n    return _GaterRate.Value;\n }	0
4034414	4034280	C# code to create AutoMapper DDL values (text,value) from *any* Domain Model Object, providing the two field names in the parameters	public object GetProperty(object obj, string propertyName)\n{\n  PropertyInfo pi = obj.GetType().GetProperty(propertyName);\n  object value = pi.GetValue(o, null);\n  //or object value = pi.GetGetMethod().Invoke(obj, null)\n  return value;\n}	0
19418826	19418712	Filtering a Datatable using Select()	dt.Select("StartDate <= #" & todate & "# And EndDate >= #" & fromdate & "#")	0
7155350	7155324	Correct use of IDisposable pattern when using Managed C++ wrapper in C#	class Test : IDisposable {\n    private CppWrapper obj;\n    //...\n    public void Dispose() {\n       if (obj != null) { \n           obj.Dispose();\n           obj = null;\n       }\n    }\n}	0
509012	498474	Ajax Control Toolkit AutoCompleteExtender stripping zeroes and coming up with phantom values	"00056399"\n"00056717"\n"00056721"\n"00056722"\n"00056900"\n...	0
27649086	27648652	Using to WHERE clauses in select statement	string insertSql = @"SELECT Status from User_friend \n                WHERE ((ProfileId1 = @FriendProfileId)\n                AND (ProfileId = \n                    (SELECT ProfileId \n                     FROM User_Profile \n                     WHERE UserId = @UserId))) OR\n                ((ProfileId = @FriendProfileId) \n                    AND (ProfileId1 = \n                        (SELECT ProfileId \n                         FROM User_Profile \n                         WHERE UserId = @UserId)))";	0
17615355	17526938	Create a VS 2012 Extension for a Windows forms project	CommandBars cmdBars = (CommandBars)(_applicationObject.CommandBars);\n\n CommandBar vsBarItem = cmdBars["Item"];	0
343478	343466	Does dot net have an interface like IEnumerable with a Count property?	using System.Linq;\n\nclass X\n{\n   void Y(IEnumerable<int> collection)\n   {\n      int itemCount = collection.Count();\n   }\n}	0
9031748	9031625	Getting punctuation from the end of a string only	var punctuationMap = new HashSet<char>(new char[] { '.', ':', '-', '!', '?', ',', ';' });\nvar endPunctuationChars = aString.Reverse().\n                                  TakeWhile(ch => punctuationMap.Contains(ch));\nvar result = new string(endPunctuationChars.Reverse().ToArray());	0
11420017	11419175	Calling ASMX Service from C# app with Windows authentication?	NetworkCredential credentials = new\nNetworkCredential(UserName,SecurelyStroredPassword,Domain);\n\n// Add the NetworkCredential to the CredentialCache.\ncredentialCache.Add(new Uri(webSrvc.Url), \n                   "Basic", credentials);	0
33844231	33643380	Create new worksheets based on row data values	var uniqueList = dt.AsEnumerable().Select(x => x.Field<string>("ProdType")).Distinct();\n            List<string> myList = new List<string>();\n            myList = uniqueList.ToList();\n\n            DataTable[] array = new DataTable[myList.Count()];\n            int index = 0;\n            foreach (string item in myList)\n            {\n                var Result = from x in dt.AsEnumerable()\n                             where x.Field<string>("ProdType") == item\n                             select x;\n                DataTable table = Result.CopyToDataTable();\n                array[index] = table;\n\n                ExcelWorksheet ws = pck.Workbook.Worksheets.Add(item);\n                ws.Cells["A1"].LoadFromDataTable(table, true);\n                index++;\n            }	0
16381581	16380382	Parsing a JSON Date/Time value using the Windows.Data.Json library in C#/WinRT project	var match = Regex.Match(dateValue, @"/Date\((?<millisecs>-?\d*)\)/");\nvar millisecs = Convert.ToInt64(match.Groups["millisecs"].Value);\nvar date = new DateTime(1970, 1, 1).AddMilliseconds(millisecs);	0
31139046	31138769	combine a string dropdowntextfield	this.ddReturnItem.DataSource = Administration.AdministrationRent.GetAllRents();\nthis.ddReturnItem.DataValueField = "ID";\nthis.ddReturnItem.DataTextField = ReservationWristbandProp.AccountProp.Username;\nthis.ddReturnItem.DataTextFormatString = "Series {0}";\nthis.ddReturnItem.DataBind();\nSMEEvent.Rent rent;	0
33803910	33803708	LINQ with Lambda expression - Join, Group By, Sum and Count	var itens = db.CREDITO\n            .Join(db.BENEFICIARIO, cr => cr.CDBENEFICIARIO, bn => bn.CDBENEFICIARIO,(cr, bn) => new { cr, bn })\n            .GroupBy(x=> new{x.bn.DEUF,x.bn.DESUPERINTENDENCIAREGIONAL, x.cr.SITUACAODIVIDA})\n            .Select(g => new { \n                       g.Key.DEUF,\n                       g.Key.DESUPERINTENDENCIAREGIONAL,\n                       g.Key.SITUACAODIVIDA,\n                       VLTOTAL = g.Sum(x => x.cr.VLEFETIVAMENTELIBERADO),\n                       Count = g.Count() \n                       })\n            .ToList();	0
10476417	10476325	How to change cursor when mouse pointer is over a bold word in RichTextBox?	private void richTextBox2_MouseMove(object sender, MouseEventArgs e)\n        {\n            int c = richTextBox2.GetCharIndexFromPosition(new Point(e.X, e.Y));\n            richTextBox2.Select(c, 1);\n            if (richTextBox2.SelectionFont.Bold)\n            {\n                richTextBox2.Cursor = Cursors.Hand;\n            }\n            else\n            {\n                richTextBox2.Cursor = Cursors.Default;\n            }\n\n        }	0
3305541	3305422	Enum with mvc rendering in checkbox on my view, reaction of my controller?	int newEnumValue = Request.Form["CheckBoxField"].Split(',').Aggregate(0, (acc, v) => acc |= Convert.ToInt32(v), acc => acc);	0
14201792	14201759	Lazy initialized field with changed ctor param?	public MyExpensive GetExpensive()\n{\n    LazyInitializer.EnsureInitialized(ref _expensive, () = > new MyExpensive ());\n    return _expensive;\n}	0
23837661	23837474	How to increment or loop through the folders in a specific directory	string[] folderlist;    \nfolderlist = Directory.GetDirectories("YourStartingDirectory");\nforeach (string FolderName in folderlist)\n{\n      string rfoldername = Path.GetFileName(FolderName);\n}	0
11771251	11759809	C# Metro app How to load image from web	var httpClient = new HttpClient();            \n     var contentBytes = await httpClient.GetByteArrayAsync(uri);                          \n     var ims = new InMemoryRandomAccessStream();                \n     var dataWriter = new DataWriter(ims);\n     dataWriter.WriteBytes(contentBytes);\n     await dataWriter.StoreAsync();\n     ims.Seek(0);\n\n     bitmap = new BitmapImage();                \n     bitmap.SetSource(ims);                \n\n     myImage.Source = bitmap;	0
6946127	6946025	String to decimal parsing C#	var val = double.Parse("$123,345,676.8999", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol);\nval = Math.Round(val, 2);	0
8140383	8140341	How to Convert List<string> to ReadOnlyCollection<string> in C#	var readOnlyList = new ReadOnlyCollection<string>(existingList);	0
30223646	30223619	Check for null in == override	ReferenceEquals()	0
3959442	3959360	Insert data in datagridview gives exception	dataGridView1.Rows.Add("book");\n    dataGridView1.Rows.Add("pen");\n    dataGridView1.Rows.Add("x");\n    dataGridView1.Rows.Add("y");\n    dataGridView1.Rows.Add("z");	0
7182849	7182821	How to enable ALL controls on a form?	private void enableControls(Control.ControlCollection Controls)\n{\n    foreach (Control c in Controls)\n    {\n        c.Enabled = true;\n        if (c is MenuStrip)\n        {\n           foreach(var item in ((MenuStrip)c).Items)\n           { \n              item.Enabled = true;\n           }\n        }\n        if (c.ControlCollection.Count > 0)\n            enableControls(c.Controls);\n\n    }\n}	0
8919127	8919072	Loading DLLs from a folder, C# windows form project	string path = @"D:\Folder\MyDll.dll";\nAssembly assembly = Assembly.LoadFrom(path);	0
23849143	23849087	Using += Or Something Like That In MySql Update Query	cmd.CommandText = "update entities set ConquerPoints = ConquerPoints + 10 where Name ='" + charactername + "';";	0
3045836	3045604	How to efficiently get highest & lowest values from a List<double?>, and then modify them?	var splitValues = new List<double?>();\nsplitValues.Add(Math.Round(assetSplit.EquityTypeSplit() ?? 0));\nsplitValues.Add(Math.Round(assetSplit.PropertyTypeSplit() ?? 0));\nsplitValues.Add(Math.Round(assetSplit.FixedInterestTypeSplit() ?? 0));\nsplitValues.Add(Math.Round(assetSplit.CashTypeSplit() ?? 0));\n\nvar listSum = splitValues.Sum(split => split.Value);\nwhile (listSum != 100)\n{\n  var value = listSum > 100 ? splitValues.Max() : splitValues.Min();\n  var idx = splitValues.IndexOf(value);\n  splitValues.RemoveAt(idx);\n  splitValues.Insert(idx, value + (listSum > 100 ? -1 : 1));\n  listSum = splitValues.Sum(split => split.Value);\n}	0
29827515	29816688	Take a page shoot with Selenium Web Driver	IEDriverServer.exe	0
5178909	5178901	How to cut off the end by converting double to int?	double myDouble = 4.5234234;\nint result = (int)myDouble;\n//at this point result is 4	0
16393440	16393068	Trying to impersonate another user to update Active Directory	using (var dirRoot = new DirectoryEntry("LDAP://cn=user object, dc=domain, dc=com", @"<domain>\<user>", "<password>"))\n        {\n            dirRoot.Properties["l"].Value = "yada";\n            dirRoot.CommitChanges();\n        }	0
12882216	12882201	C# User input needs to be >= 2, but how to make it so?	do {\n    Console.Write("Enter minimum number of sides >2: ");\n    inputminside = Console.ReadLine();\n} while (!int.TryParse(inputminside, out minimumSides) || minimumSides < 2);	0
18976002	18958392	How to connect Azure federated root database and apply federation in entity framework DBContext?	var   customerEntity = new Entities(ConnectionStringCustomerDB());\n                    var connection = new SqlConnection();\n                    connection =(SqlConnection) customerEntity.Database.Connection;\n                    connection.Open();\n                    var command = new SqlCommand();                \n                    string federationCmdText = @"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";\n                    command.Connection = connection;\n                    command.CommandText = federationCmdText;\n                    command.ExecuteNonQuery();\nreturn Entities;	0
12482826	12482492	Linq to SQL data integrity with grouping	var q =\n    from gps in db.gps_data\n    where (from gps2 in db.gps_data\n           group gps2 by gps2.user_id\n           into g\n           select new {a = g.Key, b = g.Max(f => f.server_time)})\n           .Contains(new {a = gps.user_id, b = gps.server_time})\n    select gps;	0
5945986	5945922	how to modify global resource dll's without compiling the code?	/resource:	0
31493150	31493106	Incorrect syntax near ',' on AUTOINCREMENT on table creation	string sqlStatement = "CREATE TABLE " + Table1Name + "" \n                    + " (network_id INTEGER identity(1,1) PRIMARY KEY,"\n                    + "network_full_name VARCHAR(50) NOT NULL)";	0
7258761	7258735	How to set Table/TableRow/TabelCell width by percent in code behind in asp.net?	TableRow.Width = new Unit("25%")	0
10750587	10750532	How to save data in the different database depending on the internet connection	public string GetConnectionString()\n    {\n        string SqlConString1 = value;//Read from config\n        string SqlConString2 = value;//Read from config\n        WebClient client = new WebClient();\n        try\n        {\n            using (client.OpenRead("http://www.google.com"))\n            {\n            }\n            return SqlConString1 ;\n        }\n        catch (WebException)\n        {\n            return SqlConString2 ;\n        }\n    }	0
23192991	23192913	How to remove all the pages from page stack in Windows Phone 7?	while(NavigationService.CanGoBack)\n    NavigationService.RemoveBackEntry();	0
8036655	8036464	Closing a Out of Browser application in silverlight from the code	App.Current.MainWindow.Close();	0
1952242	1952153	What is the best way to find all combinations of items in an array?	static List<List<int>> comb;\nstatic bool[] used;\nstatic void GetCombinationSample()\n{\n    int[] arr = { 10, 50, 3, 1, 2 };\n    used = new bool[arr.Length];\n    used.Fill(false);\n    comb = new List<List<int>>();\n    List<int> c = new List<int>();\n    GetComb(arr, 0, c);\n    foreach (var item in comb)\n    {\n        foreach (var x in item)\n        {\n            Console.Write(x + ",");\n        }\n        Console.WriteLine("");\n    }\n}\nstatic void GetComb(int[] arr, int colindex, List<int> c)\n{\n\n    if (colindex >= arr.Length)\n    {\n        comb.Add(new List<int>(c));\n        return;\n    }\n    for (int i = 0; i < arr.Length; i++)\n    {\n        if (!used[i])\n        {\n            used[i] = true;\n            c.Add(arr[i]);\n            GetComb(arr, colindex + 1, c);\n            c.RemoveAt(c.Count - 1);\n            used[i] = false;\n        }\n    }\n}	0
5170929	5168861	Listview: Bind data from db to label control by column id not name	(((YourObjectType)Container.DataItem)[0])	0
10928173	10927856	I am using a MDI application. I want to set the start position of a formShow	this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; \nthis.Location = new System.Drawing.Point(20, 20); // Or set your desidered location	0
19679350	19679096	Add columns name to datagridview?	dgv.ColumnCount = ivc.Columns.Count-2;	0
30950030	30948840	File Retrieved via FtpWebRequest Is Different Than Source File On Server	using System.Net;\n...\nvar webClient = new WebClient();\nwebClient.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");\nwebClient.DownloadFile("ftp://ftp.sec.gov/edgar/daily-index/2012/QTR4/company.20121003.idx.gz", @"c:\temp\destination.gz");	0
23631057	23626631	How can i add new value Secondary table in Many to many relations of Entity Framework?	modelBuilder.Entity<Course>()\n   .HasMany<Student>(c => c.Students)\n   .WithMany(s => s.Courses)\n   .Map(m => {\n       m.ToTable("StudentCourses");\n       m.MapLeftKey("CourseId");\n       m.MapRightKey("StudentId");\n    });	0
14726241	14726010	Alternative to setting database connection from file	static class Globals\n{\n    public static string DB2ConnStr = String.Empty;\n    public static string MSSQLStr = String.Empty;\n}	0
7018839	7018304	Create a folder only accesible by current logon user	public void CreatePrivateDirectory(string path)\n  {\n     DirectorySecurity directorySecurity = new DirectorySecurity();\n     SecurityIdentifier userSid = WindowsIdentity.GetCurrent().User;\n     directorySecurity.AddAccessRule(new FileSystemAccessRule(userSid, FileSystemRights.FullControl,\n                                                              InheritanceFlags.ContainerInherit |\n                                                              InheritanceFlags.ObjectInherit,\n                                                              PropagationFlags.None, AccessControlType.Allow));\n     if(!Directory.Exists(path))\n     {\n        Directory.CreateDirectory(path, directorySecurity);\n     }\n  }	0
4913966	4913955	Can anyone recommend a method to perform the following string operation using C#	var regEx = new Regex(\n        "(?<intro>.+) in (?<city>.+) on (?<locality>.+) in (?<eventDate>.+)"\n        );\n\nvar match = regEx.Match("My event happens in Baltimore on Main Street in 1876.");\n\nif (!match.Success) return;\nforeach (var group in new[] {"intro", "city", "locality", "eventDate"})\n{\n    Console.WriteLine(group + ":" + match.Groups[group]);\n}	0
32709207	32669812	After converting to Json object data dissapears	String temp = charset.decode(inBuff).toString();\n\nJSONObject obj = new JSONObject(temp);\n\nString action = obj.getString("action");\n\nSystem.out.println(action); //	0
17214638	17212402	Is it possible to include only required properties in context?	public static IQueryable<Mission> MissionWithRequired(this IOrgDatenbankContext context)\n{\n   var requiredProperties = typeof(Mission).GetProperties()\n            .Where(property => Attribute.IsDefined(property, typeof(RequiredAttribute)));\n\n   IQueryable<Mission> result = context.Missions;\n   foreach (var requiredProperty in requiredProperties)\n   {\n      result = result.Include(requiredProperty.Name);\n   }\n\n   return result;\n}	0
13901733	13901687	Error with regex Input string was not in a correct format	string html = @"<span class=""lnk"">?????????&nbsp;<span class=""clgry"">59728</span>";\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar list = doc.DocumentNode.SelectNodes("//span[@class='lnk']/span[@class='clgry']")\n              .Select(x => new\n              {\n                  ParentText = x.ParentNode.FirstChild.InnerText,\n                  Text = x.InnerText\n              })\n              .ToList();	0
6214496	6214396	C# binary data conversion to string	byte[] binaryData ; // assuming binaryData contains the bytes from the port.\n\nstring ascii =  Encoding.ASCII.GetString(binaryData);	0
2753587	2753519	Efficiently draw a grid in Windows Forms	for (int y = 0; y < numOfCells; ++y)\n  {\n    g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);\n  }\n\n  for (int x = 0; x < numOfCells; ++x)\n  {\n    g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);\n  }	0
1866444	1866421	how to compact Msaccess database using c#	public static void CompactAndRepair(string accessFile, Microsoft.Office.Interop.Access.Application app)\n        {\n            string tempFile = Path.Combine(Path.GetDirectoryName(accessFile),\n                              Path.GetRandomFileName() + Path.GetExtension(accessFile));\n\n            app.CompactRepair(accessFile, tempFile, false);\n            app.Visible = false;\n\n            FileInfo temp = new FileInfo(tempFile);\n            temp.CopyTo(accessFile, true);\n            temp.Delete();\n        }	0
957067	956997	Determine location of a UIElement on a Canvas	Canvas.GetTop(element);\nCanvas.GetLeft(element);	0
4665149	4665120	Get list of object's from collection being updated by thread	object dictLock = new object();\n\ninternal List<string> GetListOfEntities()\n{            \n    lock (dictLock)\n    {\n        return ModelFacade._totalListOfStkObjects.Keys.ToList();\n    }\n}	0
11778920	11778780	C# Regex Help replacing patterns	string test = "<2012-01-01>stuff</2012-01-01><2012-05-01>stuff2</2012-05-01>";\n\nvar regex = new Regex(@"<(/?)(\d\d\d\d)-(\d\d)-(\d\d)>");\nvar result = regex.Replace(test, @"<$1date-$2-$3-$4>");\n\nConsole.WriteLine(result);\n\n//output:\n//<date-2012-01-01>stuff</date-2012-01-01><date-2012-05-01>stuff2</date-2012-05-01>	0
28074864	28074812	Regex to replace (void)	\(void\)	0
10183068	10183023	substitute nested foreachs with lambdas c#	return Sections.SelectMany(s => s.Questions.SelectMany(q => q.SurveyAnswers));	0
24287311	24287246	C# Group results from List<T> into another List<T2> with selected fields	List<int> docs = objs.Select(o => o.DOC).Distinct().ToList();	0
22504070	22388767	using long (int64) as a hashCode and still use IEqualityComparer for concurrent Dictionary	public class MyClass \n{\n    Dictionary<uint, Dictionary<uint, Int64>> PartDict;\n\n    Int64 ReadValue(uint id1, uint id2)\n    {\n        return (PartDict[id1])[id2];\n    }\n\n    void AddValue(uint id1, uint id2, Int64 value)\n    {\n        Dictionary<uint, Int64> container;\n        if (!PartDict.TryGetValue(id1, out container))\n        {\n            container = new Dictionary<uint, Int64>();\n            PartDict.Add(id1, container);\n        }\n        container.Add(id2, value);\n    }\n}	0
1045028	1045019	Convert a custom object array to System.Array in C#	MyClass[] myClassArray = new MyClass[2];\nmyClassArray[0] = new MyClass();\nmyClassArray[1] = new MyClass();\nLoad(myClassArray, "some text");	0
30874429	30854724	Replicate property size from domain to fluent api and viewmodel	public class Customer\n{\n    public const int Name_Max = 30;\n\n    private string name;\n\n    public string Name\n    {\n        get { return name; }\n        set\n        {\n            if (value != null && value.Length > Name_Max)\n                throw new ArgumentException();\n\n            name = value;\n        }\n    }\n}	0
15241681	15240650	Searching data of excel using row and column Index	//Set Primary Key for DataTable\ndata.PrimaryKey = new DataColumn[] { data.Columns[0] };\n\n//And use Find Method\nvar myValue = data.Rows.Find("p")["a"];\nvar myValue2 = data.Rows.Find("q")["c"];\nvar myValue3 = data.Rows.Find("r")["b"];	0
4802751	4802737	How to find minimum key in dictionary	int minimumKey = touchDictionary.Keys.Min();	0
1429740	1429719	Need help with ternary operators!	field = string.Format(Str,\n    value1,\n    value2,\n    found ? fieldName : "",\n    found ? "product" : "");	0
4154122	4153799	How to insert DateTime in MySql Database using C# code	string dt;   \n    string dt2;\n    DateTime date = DateTime.Now;    \n    DateTime date2 = DateTime.Now;    \n    dt = date.ToLongTimeString();        // display format:  11:45:44 AM\n    dt2 = date2.ToShortDateString();     // display format:  5/22/2010\n\n    cmd.Parameters.Add("@time_out", SqlDbType.NVarChar,50).Value = dt;\n    cmd.Parameters.Add("@date_out", SqlDbType.NVarChar, 50).Value = dt2;\n    cmd.Parameters.Add("@date_time", SqlDbType.NVarChar, 50).Value = string.Concat(dt2, " ", dt); // display format:  11/11/2010 4:58:42	0
16510284	16510243	remove a element from a StackPanel and add it to other StackPanel	PanelStack1.Children.Remove(RecX);\n PanelStack2.Children.Add(RecX);	0
1692612	1692602	Post in Twitter using C# application	public Twitter(string UserName, string Password, string Source)	0
8324770	8324658	Need to change font size	string myString = "The quick brown fox jumps over the lazy dog";\nstring textToReplace = "fox";\nmyString = myString.Replace(textToReplace, "<span style=\"font-weight: bold;\">" + textToReplace + "</span>");	0
10064676	10064642	C# 2D Animation - From slow to fast	Position.X = TimeSinceStart ^ 2	0
12800940	12800833	Find values under one node in XML	XmlDocument objXmlDoc = new XmlDocument();\nXmlNodeList objXmlNodeList;\nobjXmlDoc.Load(sFilePath);\nobjXmlNodeList = objXmlDoc.SelectNodes("//Word");\nstring s = string.Empty;\nXmlNodeList wordNodes = objXmlNodeList[0].ChildNodes;\nforeach (XmlNode characterNode in wordNodes)\n{\n   s = s + characterNode.InnerText;\n}	0
29694864	29588696	How to fill combobox with list of available fonts in windows 8 metro/store app using c#?	using SharpDX.DirectWrite;\n using System.Collections.Generic;\n using System.Linq;\n\n namespace WebberCross.Helpers\n {\n     public class FontHelper\n     {\n         public static IEnumerable<string> GetFontNames()\n         {\n             var fonts = new List<string>();\n\n             // DirectWrite factory\n             var factory = new Factory();\n\n             // Get font collections\n             var fc = factory.GetSystemFontCollection(false);\n\n             for (int i = 0; i < fc.FontFamilyCount; i++)\n             {\n                 // Get font family and add first name\n                 var ff = fc.GetFontFamily(i);\n\n                 var name = ff.FamilyNames.GetString(0);\n                 fonts.Add(name);\n             }\n\n             // Always dispose DirectX objects\n             factory.Dispose();\n\n             return fonts.OrderBy(f => f);\n         }\n     }\n }	0
7836111	7836080	Set "left" attribute on a for loop name in C#	foreach (var control in new[] { apa1, apa2, apa3 }) \n{\n    int randomSpeed = RandomNumber(2, 10);\n    control.Left -= randomSpeed;\n}	0
462404	462381	Restarting Windows from within a .NET application	// using System.Diagnostics;\n\nclass Shutdown\n{\n    /// <summary>\n    /// Windows restart\n    /// </summary>\n    public static void Restart()\n    {\n        StartShutDown("-f -r -t 5");\n    }\n\n    /// <summary>\n    /// Log off.\n    /// </summary>\n    public static void LogOff()\n    {\n        StartShutDown("-l");\n    }\n\n    /// <summary>\n    ///  Shutting Down Windows \n    /// </summary>\n    public static void Shut()\n    {\n        StartShutDown("-f -s -t 5");\n    }\n\n    private static void StartShutDown(string param)\n    {\n        ProcessStartInfo proc = new ProcessStartInfo();\n        proc.FileName = "cmd";\n        proc.WindowStyle = ProcessWindowStyle.Hidden;\n        proc.Arguments = "/C shutdown " + param;\n        Process.Start(proc);\n    }\n}	0
24868891	24868370	Razor Convert String to DateTimeOffset with long timezone	string str = "2014-07-14T09:13:01.492+02:00:00";\nDateTime dtnew = DateTime.ParseExact(str, "yyyy-MM-ddTHH:mm:ss.fffzzz:00", System.Globalization.CultureInfo.InvariantCulture);\nDateTimeOffset newDate = DateTime.SpecifyKind(dtnew, DateTimeKind.Local);	0
32244472	32244349	Always getting same result from webservice in windows app 8.1 c#?	var webresponse = await response.Content.ReadAsStringAsync();	0
22044060	22043756	reading xaml file from xaml	using(var mystr = File.Open(fileName))\n     DependencyObject rootObject = XamlReader.Load(mystr) as DependencyObject;	0
27634643	27633705	Change application name, icon and assembly info after compilation	#if XYZ\n[assembly: AssemblyTitle("NameXYZ")]\n#elif ABC\n[assembly: AssemblyTitle("NameABC")]\n#endif	0
20854510	20852827	Retrieve Results from NUnit Programmatically	[TearDown]\npublic void TearDown()\n{\n    var context = TestContext.CurrentContext;\n    // context.Test.Name\n    // context.Result.Status\n}	0
6415166	6415010	replacing \n with \r\n in a large text file	private void foo() {\n      StreamReader reader = new StreamReader(@"D:\InputFile.txt");\n      StreamWriter writer = new StreamWriter(@"D:\OutputFile.txt");\n      string currentLine;\n\n      while (!reader.EndOfStream) {\n        currentLine = reader.ReadLine();\n        writer.Write(currentLine + "\r\n");\n      }\n      reader.Close();\n      writer.Close();\n    }	0
24967037	24966963	How can I rewrite a program that was written with abstract class using interface and C#?	public interface ISomeInterface\n{\n    void methodX();\n    string s_dBase { get; set; }\n}	0
22236681	22236082	Create a ContainerControl with padding included	public class MyContainer : Panel {\n\n  public override Rectangle DisplayRectangle {\n    get {\n      int headerHeight = 25;\n      return new Rectangle(\n        this.Padding.Left,\n        this.Padding.Top + headerHeight,\n        this.ClientSize.Width - \n          (this.Padding.Left + this.Padding.Right),\n        this.ClientSize.Height - \n          (this.Padding.Top + this.Padding.Bottom + headerHeight));\n    }\n  }\n}	0
15355063	15354777	Unable to assign selected value to combobox	DisplayMemberPath="Text" SelectedValuePath="Value"	0
9369694	9355384	How do I get WCF to generate a list of proxies?	public interface IRemoteControlGroup {\n     List<string> GetInstances();\n     void Stop(string instanceId);\n     void Start(string instanceId);\n     void GetPID(string instanceId);\n}	0
557899	557836	How do I create an image of a object that has not displayed yet	Bitmap bmp = new Bitmap(panel.Bounds.Width, panel.Bounds.Height);\npanel.DrawToBitmap(bmp, panel.ClientRectangle);\nbmp.Save("c:\\test.bmp");\nbmp.Dispose();	0
5019306	5018975	How to open the redirected page from Iframe to open in the parent window in ASP.NET?	this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myUniqueKey",\n                    "self.parent.location='results.aspx';", true);	0
12462531	12462447	How to run an SQL stored procedure through C# at a specific time?	private const string DummyCacheItemKey = "GagaGuguGigi";\nprotected void Application_Start(Object sender, EventArgs e)\n{\n    RegisterCacheEntry();\n}\n\nprivate bool RegisterCacheEntry()\n{ \n    if( null != HttpContext.Current.Cache[ DummyCacheItemKey ] ) return false;\n\n        HttpContext.Current.Cache.Add( DummyCacheItemKey, "Test", null, \n        DateTime.MaxValue, TimeSpan.FromMinutes(1), \n        CacheItemPriority.Normal,\n        new CacheItemRemovedCallback( CacheItemRemovedCallback ) );\n\n    return true;\n}\n\n\npublic void CacheItemRemovedCallback( string key, \n        object value, CacheItemRemovedReason reason)\n{\n    Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString() );\n\n    // send reminder emails here\n    DoWork();\n}	0
33599265	33599188	Populate DataGridView upon load?	string[] readText = File.ReadAllLines(path);	0
5799216	5699881	MSBuild task to build load my assembly and build a serialised NHibernate Configuration	static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n        {\n            Assembly ayResult = null;\n            string sShortAssemblyName = args.Name.Split(',')[0];\n            Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();\n            foreach (Assembly ayAssembly in ayAssemblies)\n            {\n                if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])\n                {\n                    ayResult = ayAssembly;\n                    break;\n                }\n            }\n            return ayResult;\n        }\n\n        public Constructor()\n        {\n            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n        }	0
25664360	25664218	How to edit SampleData.json - Access denied - Windwos 8 apps	SampleData.json	0
32079971	32079750	How do I run an executable stored on a networked machine on that same machine?	& ".\psexec" -accepteula -i "\\computername" -u "domain\username" -p "password" "command line"	0
18417514	18417123	How to remove COM Exception when retrieving mails from outlook in C#?	string[] mails = new string[4];\n    ListViewItem itm;\n    Private Outlook.Application app = new Outlook.Application();\n\n    private void comboBoxFolder_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (comboBoxFolder.SelectedIndex == 0)\n        {\n\n                Outlook.NameSpace outlookNs = app.GetNamespace("MAPI");\n                Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);\n\n                foreach (Outlook.MailItem item in emailFolder.Items)\n                {\n                    mails[0] = item.SenderEmailAddress;\n                    mails[1] = item.To;\n                    mails[2] = item.Subject;\n                    mails[3] = Convert.ToString(item.ReceivedTime);\n\n                    itm = new ListViewItem(mails);\n                    listViewEmail.Items.Add(itm);\n\n                }\n\n\n\n        }\n    }	0
6676821	6676794	What is the most efficient/elegant way to filter a path list by a base path?	paths.Where(p => p.StartsWith(basePath)).ToList();	0
17910980	17873783	How can I clone microsoft chart control?	Chart chart1 = new Chart();\n//Enter your chart building code here\nSystem.IO.MemoryStream myStream = new System.IO.MemoryStream();\nChart chart2 = new Chart();\nchart1.Serializer.Save(myStream);\nchart2.Serializer.Load(myStream);	0
2840975	2840857	generating thumbnail image for video	var video = new MediaItem(filePath);\nusing (var bitmap = video.MainMediaFile.GetThumbnail(\n    new TimeSpan(0, 0, 5), \n    new System.Drawing.Size(640, 480)))\n{\n    // do something with the bitmap like:\n    bitmap.Save("thumb1.jpg");\n}	0
30206945	30206836	Display blank instead of first item in combobox	cmbItemType.SelectedIndex = -1;	0
12336410	12336304	Next node in xml with same element name	XElement doc=XElement.Load("yourXMLfile.xml");\n\nstring timeleft,mb,msgid,filename,mbleft,id;\n\nforeach(XElement elm in doc.Descendants().Elements("job"))\n{\n\ntimeleft=elm.Element("timeleft").Value;//time left value\nmb=elm.Element("mb").Value;//mb value\nmsgid=elm.Element("msgid").Value;//msgid value\nfilename=elm.Element("filename").Value;//filename value\nmbleft=elm.Element("mbleft").Value;//mbleft value\nid=elm.Element("id").Value;//id value\n\n}	0
6428564	6428526	How does MethodInvoker gets access to members outside its scope?	delegate { ... }	0
14690285	14689324	Unable to update changes of Gridview to database	private void frmDgv_SearchResult_Load(object sender, EventArgs e)\n    {\n        da = new SqlDataAdapter("select * from Measurement", con);\n        da.Fill(ds, "Measurement");\n        dt = ds.Tables["Measurement"];\n        SqlCommandBuilder cb = new SqlCommandBuilder(da);\n\n        cb.GetInsertCommand();\n        cb.GetUpdateCommand();\n        cb.GetDeleteCommand();\n\n        cb.ConflictOption = ConflictOption.CompareAllSearchableValues;\n    }	0
5403945	5402996	Inserting row into table with auto increment value	insert into foo(a, b, c)\n              select x, y, z from T	0
23142498	23142436	How do I pass my XML Dialog.FileName to my StreamReader for deserialization?	public static void DeSerializationXML(string path)\n{\n     ...\n     TextReader txtReader = new StreamReader(path);\n}\n\nprivate void ChangeLotFilePath()\n{\n    using (var dialog = new OpenFileDialog()) {\n        dialog.Filter = "XML files (*.xml) | *.xml";\n\n        if (dialog.ShowDialog() == DialogResult.OK) {\n            DeserializationXML(dialog.FileName);\n        }\n    }\n}	0
23974145	23973984	Is there something funny with async OnNavigatedTo?	public async virtual Task NavigateAsync(Type sourcePageType)\n{\n    await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>\n        {\n            ((Frame)Window.Current.Content).Navigate(sourcePageType);\n        });\n}	0
17391168	17391073	How to Get the number of weeks in a given year	public int GetWeeksInYear(int year)\n{\n      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;\n      DateTime date1 = new DateTime(year, 12, 31);\n      Calendar cal = dfi.Calendar;\n      return  cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, \n                                          dfi.FirstDayOfWeek);\n}	0
22448300	22447928	Using FtpWebResponse to download file - file downloads even after removed from ftp server?	request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNo??Store);	0
7706738	7706455	Send message to all via Dual Binding by specific request?	// Create an instance of your service class\nServiceClass sc = new ServiceClass();\n\n// Instantiate new ServiceHost and pass in the instance as a singleton\nserviceHost = new ServiceHost(sc, "(Service uri here)");\n\n// Call the method on the service (which then calls the clients)\nsc.DoCallbacks();	0
25704785	25704721	How to set static readonly fields dynamically?	public int MyProperty\n{\n   get\n   {\n       return this._tree.CommonValue;\n   }\n}	0
14931007	14930881	BinarySearch how to find the value in the array between the two neighbors?	double[] spline_x = { 0D, 5D, 12D, 34D, 100D };\nint i = Array.BinarySearch(spline_x, 25);\nif (i >= 0)\n{\n    // your number is in array\n}\nelse\n{\n    int indexOfNearest = ~i;\n\n    if (indexOfNearest == spline_x.Length)\n    {\n        // number is greater that last item\n    }\n    else if (indexOfNearest == 0)\n    {\n        // number is less than first item\n    }\n    else\n    {\n        // number is between (indexOfNearest - 1) and indexOfNearest\n    }     \n}	0
2562302	2557551	How get list of local network computers?	using System.Collections;\nusing System.Collections.Generic;\nusing GongSolutions.Shell;\nusing GongSolutions.Shell.Interop;\n\n    public sealed class ShellNetworkComputers : IEnumerable<string>\n    {\n        public IEnumerator<string> GetEnumerator()\n        {\n            ShellItem folder = new ShellItem((Environment.SpecialFolder)CSIDL.NETWORK);\n            IEnumerator<ShellItem> e = folder.GetEnumerator(SHCONTF.FOLDERS);\n\n            while (e.MoveNext())\n            {\n                Debug.Print(e.Current.ParsingName);\n                yield return e.Current.ParsingName;\n            }\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n    }	0
1930781	1930574	Accessing Program Settings by Name	string SettingToChange = WheelID.ToString() + Position.ToString();\n            Settings1.Default[SettingToChange] = NewName;\n            Settings1.Default.Save();	0
13798317	13798286	IP address of the user who is browsing my website	string IPAddress = string.Empty;\nstring SearchName = string.Empty;\n\nString strHostName = HttpContext.Current.Request.UserHostAddress.ToString();\n\nIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();	0
9084215	9084129	getting text between xmlnodes	XDocument doc = XDocument.Parse(@"<company>...</company");\n\nstring result = string.Join(" ",\n    doc.Root\n       .Nodes()\n       .SkipWhile(n => n.NodeType != XmlNodeType.Element ||\n                       (int)((XElement)n).Attribute("id") != 23)\n       .TakeWhile(n => n.NodeType != XmlNodeType.Element ||\n                       (int)((XElement)n).Attribute("id") != 25)\n       .OfType<XText>());\n\n// result == "pet DOCUMENT"	0
28860683	28860134	Add SQL row to a ASP label based on a condition	string specific = "";\nstring generic = "";\n\nforeach (DataRow r in myDataSet.tables[0].Rows){\n    //Add all your conditions here. It seems you want two groups of messages\n    if (r["SpecialtyText"].ToString == ""){\n        generic += r["CreatedDate"] + " - " + r["MessageText"]  + "<br /><br />";\n    }\n    else{\n        specific += r["CreatedDate"] + " - " + r["MessageText"] + "<br /><br />";\n    }\n}\n\nlblMessage.Text = generic + "<hr /><b>SPECIFIC MESSAGES:</b> <br />" + specific;	0
15525460	15525246	Composition from multiple images using C#.NET	var bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);\n\nusing (var graphics = Graphics.FromImage(bmp))\n{\n    // ...\n    graphics.DrawImage(...);\n    // ...\n}\n\nbmp.Save("c:\\test.png", ImageFormat.Png);	0
33251194	33251106	Need convert this code to vb	Public Class BasePage\n    Inherits Page\n    Protected Overrides Sub InitializeCulture()\n        If Session("Lang") IsNot Nothing Then\n            Dim selectlang As String = Session("Lang").ToString()\n            Culture = selectlang\n            UICulture = selectlang\n        End If\n        MyBase.InitializeCulture()\n    End Sub\nEnd Class	0
5342864	5342809	Add items to array within classes	List<T>	0
1495216	1495168	Set cursor in RichTextBox	richTextBox1.SelectionStart = richTextBox1.Text.Length;\n richTextBox1.Focus();	0
10313595	10310087	How can I Replace invalid characters 0x1E in data returning from DB	var newString = new string(\n    str.Select(c => (int)c)\n    .Where(i => i >= 32 || i == 9 || i == 10 || i == 13)\n    .Select(i => (char)i)\n    .ToArray());	0
29234186	29221160	Overriding Title Double Click	private const int WM_NCLBUTTONDBLCLK = 0x00A3;\n\nprotected override void OnSourceInitialized(EventArgs e)\n{\n    base.OnSourceInitialized(e);\n    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;\n    source.AddHook(WndProc);\n}\n\nprivate IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n{\n    if (msg == WM_NCLBUTTONDBLCLK)\n    {\n        //Do stuff here\n    }\n\n    return IntPtr.Zero;\n}	0
7130518	7130485	Split values in arrays	string.Split()	0
19073284	19073267	How to efficiently create derived classes	if (dto.personType == 1)\n    {\n        person = new Student() { .. };\n    }\n    else if (dto.personType == 2)\n    {\n        person = new Teacher() { .. };\n\n    }\n    else if (dto.personType == 3)\n    {\n        person = new Administrator() { .. };\n    }\n\n    person.Name = ""; // I believe these 3 properties will come from dto\n    person.DOB = "";\n    person.Address = "";	0
6209960	6209859	First Item in Grouped List without using Lambda's?	(from t in this.ObjectContext.MYTABLE\ngroup t by t.UniqueIdentifier into theGroup\nselect theGroup.First()).ToList();	0
11966959	11966897	Comparing two large generic lists 	var query = from correct in correctDepotHoldings\n            join ccHolding in ccHoldList\n              on new { correct.ClientNo, correct.Depot,\n                       correct.StockCode, correct.QuantityHeld }\n              equals new { ccHolding.ClientNo, ccHolding.Depot,\n                           ccHolding.StockCode, ccHolding.QuantityHeld }\n            // TODO: Fill in the properties here based on correct and ccHolding\n            select new StocksHeldInCustody { ... };\nvar reportList = query.ToList();	0
16780559	16780534	Reverse iteraction in a tree-like Object	public IEnumerable<ReferenceNode<TItem, TKey>> AllBellow(ReferenceNode<TItem, TKey> node)\n{\n    if (/*some codition that tells me that i can return this*/)\n    {\n        yield return node;\n    }\n    else \n    {\n        foreach (var child in node.Children.Reverse())\n        {\n            foreach (var grandChild in AllBellow(child))\n            {\n                yield return grandChild;\n            }\n        }\n    }\n}	0
28106352	28099582	Passing additional constructor arguments with StructureMap	this.For<IUserService>().Use<UserService>().Ctor<string>("randomParam").Is("YourValue");	0
3397030	3396937	Using WatiN to crawl to next page on google	var ie = new IE();\nie.Link(Find.ByText("1")).Click();	0
5198867	5198804	C# Recommendations for the best way to write text to a file such that if opened in notepad the user wont understand it	string text = "My quasi secret text.";\n\n byte[] buffer = System.Text.UTF8Encoding.GetBytes(text);\n\n string protectedText = Convert.ToBase64String(buffer);\n\n File.WriteAllText(filename, protectedText)	0
33608160	33607668	Update a List of values with empty string and keep value in other fields	group x by new\n      {\n          Date = x.Field<DateTime>("Date"),\n          DateString = x.Field<string>("DateString")\n       } into egroup\nlet isMonday = egroup.Key.Date.DayOfWeek.ToString() == "Monday"\nselect new\n      {\n          Date = egroup.Key.Date,\n          DateString = isMonday ? egroup.Key.DateString : "",\n          ..other properties	0
13212873	13212833	Compiling multiple files in a single directory separately with CSC	for /R %f in (*.cs) do csc %f	0
30311092	30309356	How to Force Visual Studio to Use a Specific Version of DNX	{\n    "sdk": {\n        "version": "1.0.0-beta4"\n    }\n}	0
4936945	4936941	Using a 'using alias = class' with generic types?	namespace N2\n{\n    using W = N1.A;         // Error, cannot name unbound generic type\n    using X = N1.A.B;           // Error, cannot name unbound generic type\n    using Y = N1.A<int>;        // Ok, can name closed constructed type\n    using Z<T> = N1.A<T>;   // Error, using alias cannot have type parameters\n}	0
14394846	14394798	Create a tab delimited string from a list of object	string str = string.Join(Environment.NewLine, person.Select(r=> r.FirstName +@"\t" +\n                                    r.Age + @"\t" +\n                                    r.Phone"))	0
9516560	9516263	Is it possible to return a LPWSTR from C++ DLL to C# app	[DllImport("DLLTest.dll", CharSet = CharSet.Unicode)]\n[return: MarshalAs(UnmanagedType.LPWStr)]\npublic static extern string GetErrorString(int errCode);	0
15930730	15930565	How to make a query string with entity framework	using (System.Data.Common.DbCommand cmd = db.Database.Connection.CreateCommand())\n{\n    cmd.CommandText = "SELECT *...";\n}	0
20688985	20688408	How do you change the text color of a readonly TextBox?	FontDialog fd = new FontDialog();\nfd.ShowColor = true;\nif (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {\n  textBox3.Font = fd.Font;\n  textBox3.BackColor = textBox3.BackColor;\n  textBox3.ForeColor = fd.Color;\n}	0
24982633	24982581	Uneven grid with for loop(s)	for(int index = 0; index < ItemList.Count; ++index)\n    ItemList[index].gridLocation = new Point(index % 7, (int)(index / 7));	0
11609121	11609018	Writing to stream without file path	byte[] result;\n    using (MemoryStream ms = new MemoryStream())\n    using (StreamWriter sw = new StreamWriter(ms))\n    {\n        MyFileWriter.WriteToFile(someData, sw);\n        result = ms.ToArray();\n    }\n\n    // use the result byte[]	0
18246989	18222135	ServiceStack DTO For Dropdown Lists	[Route("/jtip/cases/agencies", "GET")]\npublic class AgencyListRequest : IReturn<List<Agency>>\n{\n}\n\npublic class Agency {\n  public int Id { get; set; }\n  public string Name { get; set; }\n}\n\n[Route("/jtip/cases/services", "GET")]\npublic class ServiceListRequest : IReturn<List<Service>>\n{\n}\n\npublic class Service {\n  public int Id { get; set; }\n  public string Name { get; set; }\n}	0
16539709	16539203	Populate 3 combobox from same table but use filter in all 3 tables	public static DataSet DownDataBind()\n{\n    try\n    {\n        SqlConnection conn = new SqlConnection("Data Source=S1B01689;Initial Catalog=CosmosDB;User Id=sa;Password=Nttdata123");\n        conn.Open();\n\n        SqlDataAdapter adapter = new SqlDataAdapter("SELECT id,categName from CM_Categories",conn);\n        DataSet ds = new DataSet();\n\n        adapter.Fill(ds);\n\n        adapter.Dispose();\n\n        conn.Close();\n\n        return ds;\n    }\n    catch (Exception exp)\n    {\n        string s = exp.Message.ToString();\n        return null;\n    }\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    try\n    {\n        DataSet ds = DownDataBind();\n        comboBox1.DataSource = ds.Tables[0];// use Tables[0] instead of Table Name\n        comboBox1.ValueMember = "Id";\n        comboBox1.DisplayMember = "CategName";\n        comboBox1.SelectedIndex = -1;         \n    }\n    catch (Exception exp)\n    {\n        MessageBox.Show(exp.Message);\n    }\n}	0
3718124	3718006	Bind DataGridView To Results of Access SQL Query String	using System.Data.OleDb;\n\nOleDbConnection conn = new OleDbConnection(@"Provider = Microsoft.Jet.OLEDB.4.0;User Id=;Password=;Data Source=" + fileName);\nconn.Open();\nOleDbDataAdapter dataAdapter = new OleDbDataAdapter(query_txt.Text, conn);\nDataSet ds = new DataSet();\ndataAdapter.Fill(ds);\ndataGridView.DataSource = ds.tables[0];\nconn.Close();	0
8008730	7992447	Prevent KeyDown event bubbling from TextBox to MainWindow in WPF	private Key mPressedKey;\n\nprotected override void OnKeyDown(KeyEventArgs e)\n{\n    base.OnKeyDown(e);\n\n    mPressedKey = e.Key;\n}\n\nprotected override void OnTextInput(TextCompositionEventArgs e)\n{\n    base.OnTextInput(e);\n\n    // ... Handle mPressedKey here ...\n}\n\nprotected override void OnMouseDown(MouseButtonEventArgs e)\n{\n    base.OnMouseDown(e);\n\n    // Force focus back to main window\n    FocusManager.SetFocusedElement(this, this);\n}	0
19686791	19686588	How to pass an interface from C# to C++	[Guid("<a guid>")]\n[ComVisible(true)]\ninterface IMessage\n{\n     DoSomething();\n}	0
8532424	8528331	How to read table - TD content with htmlagilitypack - this table - TD has certain bacgkround image - xpath	//table/tr/td[@background = 'image/acikustart.gif']//text()	0
9871586	9859380	Deserializing json issue - inherited linq2SQL object	[DataContract]\npublic class CategoryEntity : Category\n{\n    [DataMember]\n    public int ActiveAdsCount { get; set; }\n\n    [DataMember]\n    public int DisplaySequence { get; set; }\n\n    [DataMember]\n    public IList<CategoryEntity> SubCategories { get; set; }\n\n    [DataMember]\n    public IList<BasicCategoryInfo> SubCategoriesBasicInfoList { get; set; }\n\n    [DataMember]\n    public string ParentCategoryNameEn { get; set; }\n\n    [DataMember]\n    public int CityID { get; set; }\n}	0
17488415	17485048	Get first week day of specific year-month	public static DateTime GetFirstDay(int year, int month, DayOfWeek day, int occurance)\n    {\n        DateTime result = new DateTime(year, month, 1);\n        int i = 0;\n\n        while (result.DayOfWeek != day || occurance != i)\n        {\n            result = result.AddDays(1);\n            if((result.DayOfWeek == day))\n                i++;\n        }\n\n        return result;\n    }	0
25804843	25804676	C# LINQ getting duplicates from a list	var duplicates = allMyObjects.GroupBy(a => a.MyString)\n                              .Where(a => a.Count() > 1)\n                              .SelectMany(g=>g)\n                              .ToList();	0
9687198	9673358	Sharepoint property updating over multiple pages	FILE: RSRacilityHeaderUserControl.ascx.cs\nRSFacilityHeader parent = (RSFacilityHeader)this.Parent;	0
6019543	6019227	Remove the last character if it's DirectorySeparatorChar with C#	fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);	0
1154535	1153806	Fast sub-pixel laser dot detection	*\n       *  *\n       *  *\n       *  *\n       *  *\n       *  *\n       *  *  *\n    *  *  *  *\n    *  *  *  *\n *  *  *  *  *  *\n------------------\n 2  3  4  5  6  7	0
25351329	25351119	Use one method to convert multiple textboxes to doubles	private double CheckTextBox(TextBox textBox)\n{\n    Double value;\n    if (Double.TryParse(textBox.Text, out value))\n    {\n        return value;\n    } \n    else \n    {\n        logbox.AppendText(string.Format("Box {0} does not contain a double", textBox.Name));\n        textBox.Text = ("NO DOUBLE FOUND");\n        value = double.NaN;\n        return value;\n    }\n}	0
29119884	29119661	Automatically add a row on Data Grid View C#	OpenFileDialog ofd = new OpenFileDialog();\n    ofd.Filter = "XML | *.xml";\n    if (ofd.ShowDialog() == DialogResult.OK)\n    {\n        XmlDocument xDOC = new XmlDocument();\n        xDOC.Load(ofd.FileName);\n\n        //We loop through each person node of our document\n        foreach(XmlNode node in xDOC.SelectNodes("people/person"))\n        {\n            //And add its content to a new row\n            int n = dataGridView1.Rows.Add();\n            dataGridView1.Rows[n].Cells[0].Value = node.InnerText;\n        }\n\n    }	0
2520468	2520421	Alternative Input Device(Midi) doesn't prevent Screen Saver in Winforms application	SetScreenSaverTimeout(GetScreenSaverTimeout())	0
17577082	17576171	Retrieve multiple tables by one Linq-to-Sql query	var batchSql = "select * from Repository; select * from StaffMembersRepository; select * from CategoriesRepository";\n// ...\n// iterate over batch results\nusing(var reader = command.ExecuteReader())\n{\n    var currentResultSet = 0;\n    while(reader.NextResult())\n    {\n        currentResultSet++;\n        switch(currentResultSet)\n        {\n            case 1:\n                while(reader.Read())\n                {\n                    // retrieve row data\n                }\n            case 2:\n                // similar\n            case 3:\n                // similar\n        }\n    }\n}	0
26851322	26849740	Delimit string and put it in listbox	int s = 0, n = 0, len = inputString.Length;\n\nfor (var i = 0; i < len; i++) {\n    if (inputString[i] == ',' && ++n % 4 == 0 || i == len - 1)  {\n        aListBox.Items.Add(inputString.Substring(s, i - s + 1));\n        s = i + 1;\n    }\n}	0
12840477	12840376	How to retrieve all possible server names through C#	SmoApplication.EnumAvailableSqlServers();	0
12341030	12340957	Set SelectionStart of a WinForms TextBox based on mouse location	this.SelectionStart = this.GetCharIndexFromPosition(e.Location);	0
25080746	25080676	Iterate through all days from a given year	public IList<string> GetDays(int year)\n    {\n        var days = new List<string>();\n        var start = new DateTime(year, 1, 1);\n\n        while (start.Year == year)\n        {\n            days.Add(start.ToString("dd.MM.yyyy"));\n            start = start.AddDays(1);\n        }\n\n        return days;\n    }	0
27815203	27815165	C# Deserializing nested xml	[XmlElement("Project", Namespace="http://schemas.microsoft.com/project")]	0
3821474	3815581	Microsoft Unity- Issue With Resolve	var container = new UnityContainer();\ncontainer.AddNewExtension()\n         .Configure()\n         .RegisterFactory(container =>\n                          DependencyFactory.GetValue());	0
30546034	30545878	How to display HashSet<SortedSet<string>> collection in richTextBox?	foreach (SortedSet<string> set in youHashSet)\n{\n    richTextBox.Text = string.Join("", set.ToArray());\n}	0
8647592	8647442	add XML node with formatting	XMLNode.AppendChild( XMLDocument.CreateCDataSection( newFile ) );	0
1154077	1154044	C# foreach over properties of objects contained within a Dictionary<String, ObjectType>	foreach (var data in Fields.Values.Select(x => x.Data))\n{\n}	0
7774223	7773384	Get all windows that have taskbar icon	List<Process> taskBarProcesses = Process.GetProcesses().\n                                         Where(p => !string.IsNullOrEmpty(p.MainWindowTitle))\n                                         .ToList();	0
5968866	5968696	Parsing a regex	string quick = "The quick @brown fox jumps over the lazy @dog @@dog";\nMatchCollection results = Regex.Matches(quick, "@\\w+");\n\nforeach (Match m in results)\n{\n    Literal1.Text += m.Value.Replace("@", "");\n}	0
4706425	4706414	Retrieve integer value of enum	int enumValue = (int)row.MyTime;	0
27230925	27230751	How to make visual timer go x times slower and how to stop it?	Time.timeScale = 1; // The default value.\nTime.timeScale = 0; // Stop the time.\nTime.timeScale = 0.5f; // Slower time.\nTime.timeScale = 2f; // Faster time.	0
31524620	31524343	How to convert base64 value from a database to a stream with C#	var bytes = Convert.FromBase64String(base64encodedstring);\nvar contents = new StreamContent(new MemoryStream(bytes));\n// Whatever else needs to be done here.	0
14541396	14541366	How can i get from a directory string only the file name in the end?	label22.Text = Path.GetFileName(files[_indx]);	0
21491214	21490928	Passing a string from a DLL to C#	if( gp_app == nullptr)\n    return false;	0
6657210	6646443	iText Merge PDF with cropbox	PdfReader reader = null;\nPdfCopy copier = new PdfCopy(outputStream);\nString paths[] = ...;\nfor (String path : paths) {\n  reader = new PdfReader(path);\n  for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); ++pageNum) {\n    copier.addPage(copier.getImportedPage(reader, pageNum) );\n  }\n}	0
9414054	9402224	How to convert a RectangleF to PointF[] for drawing?	private PointF[] GetPoints(RectangleF rectangle)\n    {\n        return new PointF[3]\n        { \n            new PointF(rectangle.Left, rectangle.Top),\n            new PointF(rectangle.Right, rectangle.Top),\n            new PointF(rectangle.Left, rectangle.Bottom)\n        };\n    }	0
10385853	10385354	Reading half million records from Excel workbook in a VSTO project	var firstRow = 2;\nvar lastRow = 500000;\nvar batchSize = 5000;\nvar batches = Enumerable\n    .Range(0, (int)Math.Ceiling( (lastRow-firstRow) / (double)batchSize ))\n    .Select(x => \n        string.Format(\n            "A{0}:AX{1}",\n            x * batchSize + firstRow,\n            Math.Min((x+1) * batchSize + firstRow - 1, lastRow)))\n    .Select(range => ((Array)Globals.shData.Range[range]).Cells.Value);\n\nforeach(var batch in batches)\n{\n    foreach(var item in batch)\n    {\n        //reencode item into your own object collection.\n    }\n}	0
33764009	33763942	How to compare 2 List<string> objects to get the missing value from the List<string>	foo.AddRange(accessories.Except(foo));	0
15451183	15451110	creating an authentication console application using GetTickCount function	...\nConsole.ForegroundColor = ConsoleColor.Black;\nStopWatch sw = new Stopwatch();\nsw.Start();\nstring strPassword = Console.ReadLine();\nsw.Stop()\nTimeSpan ts = sw.Elapsed;\nstring strTPassword = "testpwd";\nif (strPassword == strTPassword)\n{\n    Console.ForegroundColor = ConsoleColor.Gray;\n    Console.WriteLine("You are logged in after " + ts.Milliseconds.ToString() + " milliseconds");\n    Console.ReadLine();\n}\n.....	0
30216220	30210649	how to read local excel file using webapi?	public static void OpenSpreadsheetDocument(string filepath)\n{\n    // Open a SpreadsheetDocument based on a filepath.\n    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false))\n    {\n        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;\n        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();\n        SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();\n        string text;\n        foreach (Row r in sheetData.Elements<Row>())\n        {\n            foreach (Cell c in r.Elements<Cell>())\n            {\n                text = c.CellValue.Text;\n                Console.Write(text + " ");\n             }\n        }\n    }\n}	0
31671728	31671560	How to monitor system-wide "file name change event" by windows explorer effectively in c#	static void Main()\n    {\n        FileSystemWatcher w = new FileSystemWatcher(@"C:\temp");\n\n        w.Renamed += w_Renamed;\n        w.EnableRaisingEvents = true;\n        // Wait for the user to quit the program.\n\n        Console.WriteLine("Press \'q\' to quit the sample.");\n        while (Console.Read() != 'q') ;\n\n    }\n\n    static void w_Renamed(object sender, RenamedEventArgs e)\n    {\n       //Add your logic here\n    }	0
27100206	27099996	How to calculate Duration from start and end time specified in textbox?	protected void txtendtime_TextChanged(object sender, EventArgs e)\n    {\n        try\n        {\n            DateTime startTime, endTime;\n            startTime = Convert.ToDateTime(txtstrtime.Text);\n            endTime = Convert.ToDateTime(txtendtime.Text);\n            if (startTime > endTime)\n                endTime = endTime.AddDays(1);\n            TimeSpan span = (toDate - fromDate);\n            double actualHours = Math.Round(span.TotalHours, 2);\n            txtduration.Text = Convert.ToString(actualHours);\n            txtduration.Focus();\n        }\n        catch\n        {\n        }\n    }	0
27989376	27988791	How to check if old password matches before change it?	//Update login query\n        string sql = "ALTER LOGIN " + login.ToUpper() + " WITH PASSWORD = '" + password + "' OLD_PASSWORD = '" + oldpassword + "'";\n\n        try {\n        //Try connection and execute\n        using (SqlConnection connection = new SqlConnection(GetConnection()))\n        {\n             connection.Open();\n\n             SqlCommand command = new SqlCommand(sql, connection);\n             command.CommandType = System.Data.CommandType.Text;\n             var result = command.ExecuteScalar();\n             connection.Close();\n        }\n    }\n    catch(SQLException)\n    {\n//Do something here to tell the user something went wrong\n    }	0
18833475	18833302	Copying a file after creating directories in c#	string filename = Path.GetFileName(s);\nstring newPath = Path.Combine(result, filename);\nFile.Copy(s, newPath, true);	0
12439189	12433784	C# Access array from pointer from Primera PTRobot SDK	uint numRobots = 5;\nuint numDrives = 5;\nuint[] robotArray = new uint[numRobots];\nuint[] driveArray = new uint[numDrives];\n\n\nDriveInfo arr = new DriveInfo();\nPTRobotReturn rtn;\nRobotInfo rI = new RobotInfo();\nrtn = PTRobot.Initialize();\n\nrtn = PTRobot.EnumRobots(ref robotArray[0], ref numRobots);\n\nrtn = PTRobot.GetRobotInfo(robotArray[0], ref rI);\n\nrtn = PTRobot.EnumDrives(robotArray[0], ref driveArray[0], ref numDrives);\n\nrtn = PTRobot.LoadDrive(robotArray[0], driveArray[0], PrimeraTechnology.DiscLocation.Right_Bin, PrimeraTechnology.ClearDrive.Yes);	0
20662346	20662114	Design pattern for allowing all threads of a certain type to access a data queue while minimizing global mutable state?	using System.Collections.Concurrent;\n\n// somewhere in your code...\nstatic Action GetThreadStarter()\n{\n    var queue = new ConcurrentQueue<Stuff>();\n    return () => {\n        new Thread(() => MyThreadFunc(queue)).Start();\n    };\n}\n\nstatic Action ThreadStarter = GetThreadStarter();\n\n// use it:\nvoid Test() {\n    foreach (...) {\n        ThreadStarter();\n    }\n}	0
7103719	7103587	RouteValueDictionary in a c# library project to support html extension helpers?	.NET 3.5 Client Profile	0
4001702	560734	NHibernate / ActiveRecord: How to set foreign key without getting entire object?	using (new SessionScope()) {\n    var ghostCustomer = Customer.Find(customerId);\n\n    var account = Account.TryFind(accountId);\n    account.Customer = ghostCustomer;\n}	0
25239452	25199719	ComboBox - how to prevent selecting item after dropped down	private void comboBox1_TextUpdate(object sender, EventArgs e)\n    {\n        var savedText = comboBox1.Text;\n        comboBox1.DroppedDown = true;\n        comboBox1.Text = savedText;\n        comboBox1.Select(savedText.Length, 0);\n    }	0
8576641	8576589	Use LINQ to filter dataset for distinct rows based on only one of two columns	DataSet ds = FetchDataSet();\n\nIEnumerable<DataRow> rows =\n    from row in ds.AsEnumerable()\n    group row by row.GetField<string>("columnB") into g\n    select g.First();	0
19488864	19488378	How to add RequiredFieldValidator control with ValidationExpression in code behind?	RegularExpressionValidator regExpressionValidator = new RegularExpressionValidator();\nregExpressionValidator.ValidationExpression = "";	0
3729262	3729153	Printing from ASP.NET to a network printer	Public Class SpecialReportPrintJob\n  Inherits Printing.PrintDocument\n\nProtected Overrides Sub OnBeginPrint(ByVal ev as Printing.PrintEventArgs)\n  MyBase.OnBeginPrint(ev)\n\n  Me.PrinterSettings.PrinterName = "PrinterNameUsedOnServer"\n\n  'setup rest of stuff....\nEnd Sub  \nEnd Class\n'And we then call it like so\nDim printSpecialReport as new SpecialReportPrintJob()\nprintSpecialReport.Print()	0
4596887	4596839	How can I use GetType to access methods/properties of derived classes in C#?	Dog dog = myAnimal as Dog;\nBird bird = myAnimal as Bird;\nif (dog != null)\n   KennelMethod(dog.Kennel);\nelse if (bird != null)\n   NestMethod(bird.Nest);	0
9752960	9752871	How to get Top 10 rows from a sorted DataTable?	DataTable dt2 = dt.Clone();\n\n//get only the rows you want\nDataRow[] results = dt.Select("", "x DESC");\n\n//populate new destination table\nfor(var i=0; i < 10; i++)        \n    dt2.ImportRow(results[i]);	0
12651044	12650466	HTML Textbox showing default value as 0 for int data field	public class MyModel\n{\n   //Nullable integer\n   public int? Ssn {get; set;}  //this should be null by default\n\n   public int SSN {get; set; } //this should be 0 by default\n\n}	0
5704844	5704320	How to show at listbox2 value by select value from listbox1 (by id) c#	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var x =\n        [LINQ query here]\n    DropDownList2.DataSource = x;\n    DropDownList2.DataTextField = "[fieldname]";\n    DropDownList2.DataValueField = "ID";\n    DropDownList2.DataBind();\n}	0
22934358	22934014	Structure to search efficiently pair of strings matching with pair of strings in different text files	struct D : ICompareable\n\n     {\n           decimal latitude,\n           decimal longitude,\n           int km ;\n           public int CompareTo(object a)\n          {\n              D incoming = (D)a;\n             if(incoming.latitude == this.latitude)\n                     return this.longitude.CompareTo(incoming.longitude);\n             return this.latitude.CompareTo(incoming.latitude);\n          }\n     }\n     // load the first file data in the Struct array and do the Binary Search	0
3820565	3820496	How to manage worker thread who wait until they have work to do?	BlockingCollection<T>	0
25163296	25162846	Calling a method of the ASPX page from Web Service	public class MyAspxPage : Page\n{\n    private Object _myObj = new object();\n\n    public object GetObject()\n    {\n        return _myObj;\n    }\n\n    public static object GetAnObject()\n    {\n        return new object();\n    }\n}\n\npublic class MyWebService : WebService\n{\n    public void MyWebServiceMethod1()\n    {\n        MyAspxPage page = new MyAspxPage();\n        object result = page.GetObject();\n    }\n\n    public void MyWebServiceMethod2()\n    {\n        object result = MyAspxPage.GetAnObject();\n    }\n}	0
16315701	16312042	Fill In A Null Column When Data Is Submitted On Sql Server 2008	cn.Open();\n\n    String cmdString = "INSERT INTO tblPurchaseItem(Title, Price, PurchaseID) Select Title, Price, @PurchaseID from tblCart";\n    SqlCommand cmd = new SqlCommand(cmdString, cn);\n    cmd.Parameters.AddWithValue("@PurchaseID", purID);\n    cmd.ExecuteNonQuery();\n\n    String cmdString3 = "DELETE from tblCart";\n    SqlCommand cmd3 = new SqlCommand(cmdString3, cn);\n    cmd3.ExecuteNonQuery();	0
1671191	1671102	how can I convert a string (json) to look like another string	List personList = new List<string>();\npersonList.add("developer");\npersonList.add("kurt");\nList reps2List = new List<string>();\nreps2List.add("plumber");\nreps2List.add("john");\naa[0] = personList;\naa[1] = reps2List;	0
33904457	33904203	How can I create code that loops to change the location of text on screen	class Program\n{\n    static void Main(string[] args)\n    {\n        Menu();\n    }\n\n    static void Menu()\n    {\n      int x = 1;\n      int y = 1;\n      while(true)\n      {\n         PrintToScreendynamic(x, y, "helo");\n         y++;\n      }\n    }\n\n    static void PrintToScreendynamic(int x, int y, string text)\n    {\n        Console.SetCursorPosition(x, y);\n        Console.Write(text);\n    }\n}	0
3657979	3657843	LINQ to SQL query help (string contains any string in string array)	var filter = CreateFilter(staffTermArray);\n\nvar searchResults = \n    from person in SDC.Staff_Persons.Where(filter)\n    orderby person.Surname\n    select person;\n\n\n\nprivate static Expression<Func<Staff_Person, bool>> CreateFilter(\n    string[] staffTermArray)\n{\n    var predicate = PredicateBuilder.False<Staff_Person>();\n\n    foreach (var staffTerm in staffTermArray)\n    {\n       // We need to make a local copy because of C# weirdness.\n       var ping = staffTerm;\n\n       predicate = predicate.Or(p => p.Forename.Contains(ping));\n       predicate = predicate.Or(p => p.Surname.Contains(ping));\n       predicate = predicate.Or(p => p.Known_as.Contains(ping));\n    }\n\n    return predicate;\n}	0
21291944	21291900	Change parentheses within parentheses into brackets using RegEx	static string CorrectBrackets(string strString)\n{\n    var result = new System.Text.StringBuilder(strString);\n    int bracketLevel = 0;\n    for (int i = 0; i < result.Length; i++) {\n        switch (result[i]) {\n            case '(':\n                bracketLevel++;\n                if (bracketLevel >= 2) {\n                    result[i] = '[';\n                }\n                break;\n            case ')':\n                bracketLevel--;\n                if (bracketLevel >= 1) {\n                    result[i] = ']';\n                }\n                break;\n    }\n    return result.ToString();\n}	0
23960972	23959232	Need to get a particular value from XML	Dim result = From d In xml.Descendants("property")\n             Where d.Attribute("name").Value = "Visible" AndAlso\n                   d.Value = "true"\n             From e As XElement In d.Parent.Elements\n             Where e.Attribute("name").Value = "Name"\n             Select e.Value	0
14372032	14371948	Get text from sentence	string startIgnorePart = "Conditions for ";\nstring findBefore = ",";\nstring original = "Conditions for Mersing, MY at 11:00 am MYT";\nstring extracted = original.Substring(startIgnorePart.Length, original.IndexOf(findBefore) - startIgnorePart.Length);\nConsole.WriteLine(extracted);	0
26097847	26096968	Preventing Windows Forms DataGridView moving to next row on pressing ENTER key	if (e.KeyCode == Keys.Enter)\n{\n    if (dgvEmployees.CurrentRow.Cells[0].Value != null)\n    {\n        this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value;\n        this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() { \n            SelectedEmployeeId = this.SelectedEmployeeId, \n            SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString() \n        });\n    }\n\n    e.SuppressKeyPress = true;\n}	0
15040928	15040872	adding enum values to a simple combobox	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        foreach (var item in Enum.GetValues(typeof(Races)))\n        {\n            cbRace.Items.Add(item);\n        }\n    }\n    enum Races\n    {\n        Human = 1,\n        Dwarf,\n        Elf,\n        Orc,\n        Goblin,\n        Vampire,\n        Centaur\n    }	0
17580004	17579508	Monodroid - Set Custom font	Typeface tf = Typeface.CreateFromAsset(Application.Context.Assets, "fonts/gt.otf");\n TextView ExplodeVin = FindViewById<TextView>(Resource.Id.tvExVin);\n ExplodeVin.SetTypeface(tf,TypefaceStyle.Normal);	0
13351579	13351170	c# dropdownlist selectedindexchanged in gridview sets selectedindex of second dropdownlist	protected void ddlAddLabTest_SelectedIndexChanged(object sender, EventArgs e)\n{\n   DropDownList ddlLabTest = (DropDownList)sender;\n   DataGridItem row = (DataGridItem) ddlLabTest.NamingContainer;\n   DropDownList ddlAddLabTestShortName = (DropDownList)row.FindControl("ddlAddShortname");\n\n   ddlAddLabTestShortName.SelectedIndex = intSelectedIndex;\n}	0
11270816	11270804	How can I split and prepend text?	string.Join(" , ", devices.Select(s => "PREFIX = " + s).ToArray());	0
4951250	4951058	Software rendering mode - WPF	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        if (ForceSoftwareRendering)\n        {\n            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;\n            HwndTarget hwndTarget = hwndSource.CompositionTarget;\n            hwndTarget.RenderMode = RenderMode.SoftwareOnly;\n        }\n    }	0
25750355	25749477	Disable creation of Autofilter on DevExpress GridView	foreach ( DevExpress.XtraGrid.Columns.GridColumn item in gridView1.Columns)\n        item.OptionsFilter.AllowFilter = false;	0
13124832	13124713	Creating Value of unknown type at runtime	public class ItemModel<T> : IComparable<ItemModel<T>>, INotifyEXTEND where T : IComparable<T>	0
10065737	10065674	Regex.Split White Space	string pattern = @"(if)|(\()|(\))|(\,)";\n        string str = "IF(SUM(IRS5555.IRs001)==IRS5555.IRS001,10,20)";\n        var substrings = Regex.Split(str, pattern, RegexOptions.IgnoreCase).Where(n => !string.IsNullOrEmpty(n));\n        foreach (string match in substrings)\n        {\n            Console.WriteLine("Token is:{0}", match);\n        }	0
19464762	19464597	convert string to float in function of cultureinfo	string userInput = "56,67";\n    float output;\n    System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;\n    System.Globalization.CultureInfo  info =  System.Threading.Thread.CurrentThread.CurrentCulture;\n\n    if (float.TryParse(userInput, style, info, out output))\n    {\n        // ...\n    }\n    else\n    {\n        // ....\n    }	0
25146160	25145976	Regex Match specific text and date in this format: MM/dd/yyyy	var subject = "Package.Variables[User::ProcessStartDateInput].Properties[Value];12/14/2014";\nvar regex = new Regex(Regex.Escape("Package.Variables[User::ProcessStartDateInput].Properties[Value];")+ @"(?<date>\d{2}/\d{2}/\d{4})");\nvar match = regex.Match(subject);\nif(match.Success)\n{\n    var datePart = match.Groups["date"].Value;\n    DateTime dt;\n    if(DateTime.TryParseExact(datePart,"MM/dd/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))\n    {\n        //In the right format, and also a valid date.\n    }\n}	0
20292250	20292014	Is there anything like SubString or Split function for String Array too?	var betweenNicAndGender = stringArray.SkipWhile(s => !s.Equals("NIC"))\n                                     .Skip(1) // skip NIC\n                                     .TakeWhile(s => !s.Equal("Gender"));	0
16752491	16750714	Context Menu - How can I know which control activated it	ListView lv = resultsContextMenu.Tag as ListView;\nif (lv == null) //listbox was the one to call the mouse down event\n{ //do stuff }	0
1674935	1674179	Setting single user mode to restore backup	private string singleUserCmd = "alter database db-name set SINGLE_USER";\nprivate string multiUserCmd = "alter database db-name  set MULTI_USER";\n\nprivate SqlConnection SetSingleUser(bool singleUser, SqlConnectionStringBuilder csb)\n{\n    string v;\n    if (singleUser)\n    {\n        v = singleUserCmd.Replace("db-name", csb.InitialCatalog);\n    }\n    else\n    {\n        v = multiUserCmd.Replace("db-name", csb.InitialCatalog);\n    }\n    SqlConnection connection = new SqlConnection(csb.ToString());\n    SqlCommand cmd = new SqlCommand(v, connection);\n\n        cmd.Connection.Open();\n        cmd.ExecuteNonQuery();\n\n    return connection;\n}	0
11387086	11387070	Recognizing sender button control in click event	YourCustomButton button = sender as YourCustomButton;	0
3901208	3901090	Get a number of open sockets in C#?	long result = IPGlobalProperties.GetIPGlobalProperties()\n                                .GetTcpIPv4Statistics()\n                                .CurrentConnections;	0
11883591	11883405	Graphics.DrawString - Incorrect drawing of Combining Diacritical Marcs	TextRenderer.DrawText(g, "Test1 T?? T\u0305", fontTahoma, \n                                            new Point(120, 20), Color.Black);	0
15587156	15586990	Changing the content of a form from outside?	static void Main()\n{\n    var main = new MyForm();\n    //Initialize a new thread with the `DoSomething()` method\n    //and pass the form as a parameter\n    var thread = new Thread(() => DoSomething(main)) {IsBackground = true};\n    thread.Start();\n    main.ShowDialog();\n}\n\nstatic void DoSomething(MyForm main) {\n    //Update the form title\n    main.Text = "Hello";\n    //Wait one second\n    Thread.Sleep(1000);\n    //Update the form title again\n    main.Text = "World";\n}	0
2087851	2087767	Registering an Object that has a string array as a parameter using Castle Windsor Fluent Registration API	_container.Register(Component.For<Test>().ImplementedBy<Test>().DependsOn(\n                    Property\n                    .ForKey("C")\n                    .Eq(new string[]{"Value one","Value two"})\n                    ));	0
27556108	27555766	How do I retrieve image properly using ParseFile?	byte[] fileBytes = new byte[ProfileImage.ContentLength];\nfile = new ParseFile(ProfileImage.FileName, fileBytes);\nawait file.SaveAsync();	0
29561824	29561312	how to denormalize a collection which contains a collection using Linq	var source = new List<Tuple<string, string, int[]>> {\n    Tuple.Create("a", "b", new int[] {1,2,3}),\n    Tuple.Create("d", "f", new int[] {1,2,2}),\n    Tuple.Create("y", "z", new int[0])\n};\n\n\nvar destination =\nfrom t in source\nfrom i in t.Item3.Select(x => (int?)x).DefaultIfEmpty()\nselect Tuple.Create(t.Item1, t.Item2, i);	0
1431729	1431597	How to identify file created completely	private static Boolean FileInUse(FileInfo file)\n        {\n                Boolean inUse = false;\n                try\n                {\n                        using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {}\n                }\n                catch (Exception exception)\n                {\n                        inUse = true;\n                }\n\n                return inUse;\n        }	0
2667885	2667846	How to copy items from one DropDownList to another	drpTypesCreateEdit.Items.AddRange(drpTypes.Items.OfType<ListItem>().ToArray());	0
3273704	3273672	how to call RijndaelAlg.CreateEncryptor in C# correctly when saving lots of independent files	Encoding.UTF8.GetBytes(myString)	0
2310572	2290178	Alternative to SetNamedSecurityInfo to force a file to refresh its inheritable permissions	FileInfo fi = new FileInfo(myTargetFile);\nvar acl = fi.GetAccessControl();\nvar rules = acl.GetAccessRules(true, true, typeof(SecurityIdentifier));\n\n//Remove all existing permissions on the file\nforeach (var rule in rules.Cast<FileSystemAccessRule>())\n{\n  acl.RemoveAccessRule(rule);\n}\n\n//Allow inherited permissions on the file\nacl.SetAccessRuleProtection(false, false);\nfi.SetAccessControl(acl);	0
18428369	18428336	How to query a List of Group of T	vm.DataList.SingleOrDefault(g => g.Any(x => x.Name == "Milan"))	0
18136838	18136734	Reading Excel Sheet with OleDb	string conString = "Provider=Microsoft.ACE.OLEDB.12.0;" + \n                    "Data Source=path_to_your_excel_file.xls;" + \n                    "Extended Properties=\"Excel 8.0;HDR=YES\"";	0
20327965	20327832	Write stream of data in a row in a text file	string line = new String('0', 200);\nfor (int i = 0; i < 4; i++)\n{\n    writer.WriteLine(line);\n}	0
761021	761000	best way of converting letters to base-10	if (Char.IsDigit(c))\n    return c - '0';	0
3393737	3393698	to find whether the mouse is moving over particular control or point on screen	if (someControl.RectangleToScreen(someControl.ClientRectangle).Contains(MousePosition))	0
13604184	13603893	Recursively delete files from a Directory but keeping the dir structure intact	fileGenerationDir.GetFiles("*", SearchOption.AllDirectories).ToList().ForEach(file=>file.Delete());	0
7705341	7705251	Custom Control flickers when changing background	protected override CreateParams CreateParams\n    {\n        get\n        {\n            // This eliminates child control flicker when selecting\n            CreateParams cp = base.CreateParams;\n            cp.ExStyle |= 0x02000000;\n            return cp;\n        }\n    }	0
32636477	32629486	How to set combobox first element in winform application in c#	var items = db.Tbl_EmployeeDetails.Where(x => x.IsDeleted == false).ToList();\nitems.Insert(0,new Tbl_EmployeeDetail() { RecordId= 0, Name = "[Please Select an Item]" });\n\ndrpname.DropDownStyle = ComboBoxStyle.DropDownList; //optional\ndrpname.ValueMember = "RecordId";\ndrpname.DisplayMember = "Name";\ndrpname.DataSource = items;\ndrpname.SelectedIndex = 0;	0
18562883	18562857	INotifyPropertyChanged in window 8 app	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    Person person = spPerson.DataContext as Person;\n\n    if(person != null)\n      person.LastName = "ss";\n}	0
9538814	9533370	Lucene.NET Structure for a File Path Indexing Solution	filename:task	0
1462811	1462504	How to make window appear in taskbar?	[DllImport("User32.Dll")]                \npublic static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n\n[DllImport("user32.dll")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nprivate const int SW_HIDE = 0x00;\nprivate const int SW_SHOW = 0x05;\n\nprivate const int WS_EX_APPWINDOW = 0x40000;\nprivate const int GWL_EXSTYLE = -0x14;\n\nprivate void ShowWindowInTaskbar(IntPtr pMainWindow)\n{                       \n    SetWindowLong(pMainWindow, GWL_EXSTYLE, WS_EX_APPWINDOW);\n\n    ShowWindow(pMainWindow, SW_HIDE);\n    ShowWindow(pMainWindow, SW_SHOW);      \n}	0
20224380	20222113	How to programmatically access the d: DesignHeight and d: DesignWidth?	MyControl ctrl=new MyControl();\n    ctrl.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));\n    //ctrl.DesiredSize.Width==design width\n    //ctrl.DesiredSize.Height==design height	0
30841315	30776496	Cannot populate a DropDownList in EditItemTemplate using OnRowCommand	else if (e.CommandName == "UpdateRow")\n{\n    int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;\n    DropDownList ddlshift = (DropDownList)SupportScheduleTable.Rows[rowIndex].FindControl("ddlshiftmanager");\n    DropDownList ddlone = (DropDownList)SupportScheduleTable.Rows[rowIndex].FindControl("ddldispatcherone");\n    DropDownList ddltwo = (DropDownList)SupportScheduleTable.Rows[rowIndex].FindControl("ddldispatchertwo");\n    string manager = ddlshift.SelectedValue;\n    string one = ddlone.SelectedValue;\n    string two = ddltwo.SelectedValue;\n    int supportID = Convert.ToInt32(e.CommandArgument);\n    String sh = shift.Text;\n    String date = resourcedate.Text;\n    db.updateSS(supportID, sh, manager, one, two,date);\n    SupportScheduleTable.EditIndex = -1;\n    shift.Enabled = false;\n    resourcedate.Enabled = false;\n    getSupportSchedule();\n}	0
4538664	4538540	Watin:Get date from textfield	string myDate = browser.TextField(Find.ByName("myTextField")).Value;\nDateTime time =  = new DateTime();\nif(DateTime.TryParse(myDate, out time);) {\n     Console.WriteLine(time.Month);\n}\nelse {\n   //Not a valid date.\n}	0
3135259	3135183	desigining the domain model - need help	Campus.ForEach(c => AddToBrokenRulesList(brokenRules, c.GetBrokenRules()));	0
14953851	14953701	Degrade performance of C# for-loop for bigger range over C for-loop	T = K + XN	0
24999497	24614868	C# BHO return value from Javascript	// Execute method and save return value to a new document property.\nieHtmlWindow2.execScript("document.NewPropForResponse = getElemHtml();");\n\n// Read document property.\nvar property = ((IExpando)ieHtmlDocument2).GetProperty("NewPropForResponse", BindingFlags.Default);\nif (property != null)\n    return property.GetValue(ieHtmlDocument2, null);  // returns return value from getElemHtml.	0
13681367	13681253	Get values from html	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(@"<td><a href=""link"">");\n\nvar links = doc.DocumentNode.SelectNodes("//a[@href]")\n            .Select(a => a.Attributes["href"].Value)\n            .ToList();	0
20684324	20582901	How to write a Cross Forest LDAP Query in C#?	connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;	0
12430945	12400250	Using MSBuild in C#	SET MSBuildEmitSolution = 1	0
21729481	21729382	Implement Paging With SQL Server 2008 in MVC3 C#	SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n\nCREATE PROCEDURE GetDataPageWise                      // Name of the stored procedure\n      @PageIndex INT = 1\n      ,@PageSize INT = 10\n      ,@RecordCount INT OUTPUT\nAS\nBEGIN\n      SET NOCOUNT ON;\n\nSelect Row_Number() Over\n(\n ID\n) as RowNumber\nID, FullName, FullAddress, Coord\ninto #Results// #Results is the temporary table that we are creating\nFrom Names n\ninner join Person p ON n.ID = p.PID\ninner join Address a ON n.AddressID = a.ID\norder by FullName\nSELECT @RecordCount = COUNT(*)FROM #Results\n\nSELECT * FROM #Results\n      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1\n\n      DROP TABLE #Results                      // Dropping the temporary table results as it is not required furthur\nEND\nGO	0
7055824	7054481	how to produce a mix of dll and exe in one C# project in visual studio or other build tools?	copy "$(TargetPath)" "$(TargetDir)$(TargetName).dll"	0
664463	664440	How to handle a massive factory in a cleaner fashion	Dictionary<DropDownType, DropDownDtoDelegate>	0
5160642	5159433	Short way to achieve dynamic objects from LINQ to XML select query?	// Code answer by Jon Skeet.\nvar qClients = xdoc.Root\n       .Element(XKey.clients)\n       .Elements(XKey.client)\n       .Select(client => {\n           dynamic o = new ExpandoObject();\n           o.OnlineDetails = new ExpandoObject();\n           o.OnlineDetails.Password = client.Element(XKey.onlineDetails)\n                                            .Element(XKey.password).Value;\n           o.OnlineDetails.Roles = client.Element(XKey.onlineDetails)\n                                         .Element(XKey.roles)\n                                         .Elements(XKey.roleId)\n                                         .Select(xroleid => xroleid.Value);\n           return o; \n       });	0
20697842	20694443	WPF DataGrid: How to perform column binding using code behind?	DataGridTextColumn dataGridTextColumn = new DataGridTextColumn();\ndataGridTextColumn.Header = " Length ";\ndataGridTextColumn.Binding = new Binding("Length48");\n\nYourDataGrid.Columns.Add(dataGridTextColumn);	0
19499306	19499229	Updating a List<> item with previous items value	for (int i = 1; i < myList.Count; i++)\n{\n   myList[i].Value1 =  myList[i].Value1 ?? myList[i-1].Value1;\n}	0
8692753	8692741	Populate list with the same number	TcData = Enumerable.Repeat(-1d, numberTcs).ToList();	0
12513341	12513297	Json serialisation with newtonsoft	JsonConvert.SerializeObject(yourObj, \n    new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });	0
32706231	32706065	Reading text and variables from text file c#	StreamReader sr = new StreamReader(@"C:\temp\settings.txt");\n        var set = sr.ReadToEnd();\n        var settings = new Regex(@"(?<=\[)(.*?)(?=\])").Matches(set);\n        foreach (var setting in settings)\n        {\n            Console.WriteLine("Parameter read from settings file is " + setting);\n        }\n        Console.WriteLine("Press any key to finish program...");\n        Console.ReadKey();	0
25029762	25029734	How to quote a forward slash in a WebClient url?	data = client.DownloadString("https://myURL" + \n                              HttpUtility.UrlEncode(userID) +\n                              HttpUtility.UrlEncode(password))	0
1798215	1798174	DateTime.ParseExact formats question	{"M d yyyy HHmm", "M d yyyy 0"}	0
14973558	14973484	How to format Excel worksheet?	Microsoft.ACE.OleDb	0
7846914	7846834	Grab a part of text when it matches, get rid of the rest because it's useless	string result = path.Substring(0, path.IndexOf(compare)+compare.Length);	0
3824870	3813346	C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine()	System.Diagnostics.ProcessStartInfo start =\n      new System.Diagnostics.ProcessStartInfo();     \nstart.FileName = dir + @"\Myprocesstostart.exe";\nstart.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;	0
5712344	5712250	LINQ to XML LIKE clause	String.StartsWith()	0
25359517	25355536	How to create SecurityStamp for AspNetUser in ASP .NET MVC 5	var users = new List<ApplicationUser> \n                { \n                    new ApplicationUser\n                        {\n                            PasswordHash = hasher.HashPassword("TestPass44!"), \n                            Email = "informatyka4444@wp.pl", \n                            UserName = "informatyka4444@wp.pl", \n                            SecurityStamp = Guid.NewGuid().ToString()\n                        },\n                    new ApplicationUser\n                        {\n                            PasswordHash = hasher.HashPassword("TestPass44!"),\n                            Email = "informatyka4445@wp.pl", \n                            UserName = "informatyka4445@wp.pl", \n                            SecurityStamp = Guid.NewGuid().ToString()\n                         }\n                };	0
1598480	1565847	Declaring a looooong single line string in C#	if (log.IsDebug) {\n    string s = "blah blah blah" + \n    // whatever concatenation you think looks the best can be used here,\n    // since it's guarded...\n}	0
15821006	15820742	An idiomatic, guaranteed mutex in C# for a data structure?	ConcurrentDictionary<TKey, TValue>	0
19994425	19993657	Winform showing Excel with series names	chartPage.SetSourceData(chartRange, Microsoft.Office.Interop.Excel.XlRowCol.xlColumns);	0
29473612	29473510	WPF combobox value	ComboBox[] comboNameLst = {cbo1, cbo2, cbo3}; \nforeach (ComboBox cbo in comboNameLst)\n{                \n    MessageBox.Show("ID is" + id + "and cbo is" + cbo.Name);\n    MessageBox.Show("selected item" + cbo.SelectedItem  );\n}	0
12767584	12767231	Regular expression, specific string with symbol	"^(test|test2|test3|test4\-5)$"	0
25537926	25537796	Automapper - Map field and calculate with session variable. How?	Mapper.CreateMap<Distance, DistanceViewModel>()\n       .ForMember(a => a.Distance, exp => exp.ResolveUsing(p => p.Meters * (double)HttpContext.Current.Session["Factor"]))	0
14580153	14467066	Inserting new lines into a 'RichTextBox' from a string?	myLongString = myLongString.Replace("@", "" + System.Environment.NewLine);	0
22781125	22780665	Extract part of string from a string?	string pattern = @"(F8-F7-D3-00\S+)";\nstring input = "IP Address         Hardware Address         Lease expiration                Type\n"+\n    "192.168.1.2        00-23-8B-87-9A-6B        Mon Jan 02 01:14:00 2006        Dynamic\n"+\n    "192.168.1.3        F8-F7-D3-00-03-80        Mon Jan 02 01:14:00 2006        Dynamic \n"+\n    "192.168.1.4        F8-F7-D3-00-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic \n"+\n    "192.168.1.5        F0-DE-F1-33-9C-C4        Mon Jan 02 01:14:00 2006        Dynamic";\n\nMatchCollection matches = Regex.Matches(input, pattern);\nforeach (Match match in matches)\n{\n   Console.WriteLine("Hardware Address: {0}", match.Groups[1].Value);\n}	0
5271760	5039955	How to connect to ExchangeServer from ASP.net (using c#)?	service.Url = new Uri("https://mail.domain.com/EWS/exchange.asmx");	0
6273876	6273788	Building Expression Trees	/* build our parameters */\nvar pX = Expression.Parameter(typeof(double?));\n\n/* build the body */\nvar body = Expression.Condition(\n    /* condition */\n    Expression.Property(pX, "HasValue"),\n    /* if-true */\n    Expression.Call(typeof(BitConverter),\n                    "GetBytes",\n                    null, /* no generic type arguments */\n                    Expression.Member(pX, "Value")),\n    /* if-false */\n    Expression.Constant(new byte[] { 0xFF })\n);\n\n/* build the method */\nvar lambda = Expression.Lambda<Func<double?,byte[]>>(body, pX);\n\nFunc<double?,byte[]> compiled = lambda.Compile();	0
19990570	19990356	how to parse multiple file names and get relevant information in C# asp aspx	using System.IO;\n..\n..\n..\n        static void Main(string[] args)\n        {\n            string[] filePaths = Directory.GetFiles(@"c:\", "*.pdf");\n            string result;\n            foreach (var file in filePaths)\n            {\n                result = Path.GetFileNameWithoutExtension(file);\n                Console.WriteLine("GetFileNameWithoutExtension('{0}') return '{1}'",\n                 file, result);\n\n                var sSplitFileName = file.ToUpper().Split('-');\n                var i = 0;\n                foreach (var item in sSplitFileName)\n                {\n                    if (i == 3)\n                        //it is product id\n                    if (i == 7)\n                        //it is chip name\n\n                   i++;\n                }\n            }\n        }	0
21379852	21379764	how to rotate image in File in C# & WPF application	Bitmap bitmap1 = (Bitmap)Bitmap.FromFile(@"C:\test.jpg");\n        bitmap1.RotateFlip(RotateFlipType.Rotate180FlipNone);\n        bitmap1.Save(@"C:\Users\Public\Documents\test rotated.jpg");	0
29366820	29366776	How to add a right click event to an object like button,label,listbox etc	private void btn_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Right)\n        {\n            // do your stuff\n        }\n    }	0
4143350	4143289	split a line of text into two lines using a <br> in c#	private const MinimumLengthForBreak = 12;\nprivate const LineBreakString = "<br />";\n\npublic static string BreakLineIntoTwo(this HtmlHelper helper, string input)\n{\n    if (string.IsNullOrEmpty(input)) return string.Empty;\n    if (input.Length < MinimumLengthForBreak ) return input;\n\n    int pos = input.IndexOf(' ', input.Length / 2);\n    if (pos < 0) return input; // No space found, not checked in original code\n\n    return input.Substring(0, pos) + LineBreakString + input.Substring(pos + 1);\n}	0
401190	401174	How to constrain multiple generic types?	public interface IParentNodeT<TChild, TSelf>\nwhere TChild : IChildNodeT<TSelf, TChild>, INodeT<TChild>\nwhere TSelf : IParentNodeT<TChild, TSelf>\n{\nTChild childRoot { get; set; }\n}	0
34545741	34545519	Problems with deserializing Json from RIOT Api in C# UWP	public class LOL\n{\n    public Gigaxel gigaxel { get; set; }\n}\n\npublic class Gigaxel\n{\n    public int id { get; set; }\n    public string name { get; set; }\n    public int profileIconId { get; set; }\n    public long revisionDate { get; set; }\n    public int summonerLevel { get; set; }\n}	0
32399225	32398886	converting a datetime2 data type to a smalldatetime data type of the value is out of range	public partial class YourEntitiy\n{\n    public YourEntitiy()\n    {\n        DateCreated = DateTime.Now;\n    }\n}	0
23531298	23209101	How do I conditionally set the destination object to null using automapper	config.CreateMap<UrlPickerState, Link>()\n            .ConvertUsing(arg =>\n            {\n                if (string.IsNullOrWhiteSpace(arg.Url))\n                {\n                    return null;\n                }\n                return new Link()\n                {\n                    Url = arg.Url,\n                    OpenInNewWindow = arg.NewWindow,\n                    Title = arg.Title,\n                };\n            });	0
26733535	26733511	Binding same data to multiple dropdownlists using foreach loop	private void bindDropdowns(DataSet ds)\n      {\n       foreach (Control control in form1.Controls)\n            {\n             if ((control.GetType() == typeof(DropDownList)))\n                   {\n                        ((DropDownList)(control)).DataTextField = "InformationReview";\n                        ((DropDownList)(control)).DataValueField="InformationReviewID";\n                        ((DropDownList)(control)).DataSource = ds.Tables[0];\n                        ((DropDownList)(control)).DataBind();\n                        ((DropDownList)(control)).Items.Insert(0, new ListItem("-Select--", "0"));\n                    }\n      }}	0
16464041	16463205	insert multiple rows with parameters in odp.net	OracleConnection connection = OracleConnectionOpen("csEmailManagement");\nOracleCommand command = new OracleCommand();\n\n// Start query string\nstring query = "INSERT ALL ";\nfor (int i = 0; i < emailMessageList.Length; i++)\n{\n    query = string.Format("{0} INTO YS_ES_TO(EMAILID,EMAILTO) VALUES (:{1}, :{2})",\n                          query,\n                          "pEMAILID_"+i,\n                          "pEMAILTO_"+i);\n\n    command.Parameters.Add("pEMAILID_"+i, \n                           OracleDbType.Int32, \n                           emailId, \n                           ParameterDirection.Input);\n    command.Parameters.Add("pEMAILTO_"+i, \n                           OracleDbType.Varchar2, \n                           emailMessageList[i], \n                           ParameterDirection.Input);\n} \ncommand.CommandText = query;\ncommand.Connection = connection;	0
16961045	16758407	Modifying a column in DGV to be a Combobox Bound to DataBase	DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();\n        BindingSource wizardBindingSource = new BindingSource();\n        wizardBindingSource.DataSource = dataSet; \n        wizardBindingSource.DataMember = "protocol"; // This is the table in the set\n        colType.HeaderText = "Type";\n        colType.DropDownWidth = 90;\n        colType.Width = 90;\n        colType.DataPropertyName = "wizardProtocol";\n        colType.DataSource = wizardBindingSource;\n        colType.DisplayMember = "protocolName";\n        colType.ValueMember = "idprotocols"	0
22297235	22297206	What is the fastest way to get the last elements of a list by ID with Datetime?	var output = input\n    .GroupBy(o => o.Code)\n    .Select(g1 => g1.OrderByDescending(g2 => g2.Timestamp).First())\n    .ToList();	0
26265943	26265631	Website doesn't see newest session values until I refresh page, but refreshing resets values of controls	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack){\n       Label1.Text = "Click the button";\n    }\n}	0
14548168	14547902	retrieve footnote of word file with openxml	FootnotesPart footnotesPart = wordDoc.MainDocumentPart.FootnotesPart;\nif (footnotesPart != null)\n{\n    IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();\n    ...\n}	0
1744462	1744433	Linq to XML, only take elements that have a certain child element	IEnumerable<string> links = csprojFile\n        .Element(msbuild + "Project")\n        .Elements(msbuild + "ItemGroup")\n        .Elements(msbuild + "Compile")\n        .Where(element => element.Descendants(msbuild + "Link").Any())\n        .Attributes("Include")\n        .Select(attr => attr.Value);	0
11990563	11983804	Generate some unique numbers and put into array	//Create the list of numbers you want\nvar list = new List<int>();\nfor(var x = 0; x < 10; x++)\n{\n    list.Add(x);\n}\n\nvar random = new Random();\n//Prepare randomized list\nvar randomizedList = new List<int>();\nwhile(list.Length > 0)\n{\n    //Pick random index in the range of the ordered list\n    var index = random.Next(0, list.Length);\n\n    //Put the number from the random index in the randomized list\n    randomizedList.Add(list[index]);\n\n    //Remove the number from the original list\n    list.RemoveAt(index);\n}	0
9913976	9913879	the most efficient way to separate string	var given = "B82V16814133260";\nvar first = given.TrimEnd("0123456789".ToCharArray());\nvar rest = given.Substring(first.Length);\n\nConsole.Write("{0} -> {1} -- {2}", given, first, rest);\n//  B82V16814133260 -> B82V -- 16814133260	0
9357667	9356515	Creating Instance of window from from browser contol	WebBrowser browser;\n...\nbrowser.ObjectForScripting = new ScriptingObject();\n...\nbrowser.DocumentText="<a onclick=\"window.external.WantCookie('Cookie')\">Give some cookie</a>";\n....\n\n\n[System.Runtime.InteropServices.ComVisible(true)]\npublic class ScriptingObject\n{\n    public void WantCookie(String message)\n    {\n        if(message=="Cookie")\n            MessageBox.Show("Thanks");\n        else MessageBox.Show("I want Cookie!");\n    }\n}	0
26288588	26196829	How do you mock an abstract class containing an internal abstract method using Moq?	internal abstract	0
4137530	4137507	printing an image in landscape orientation?	doc.DefaultPageSettings.Landscape = true;	0
9975168	9975121	Writing XML Files in C#?	[XmlRoot("employee")]\npublic class Employee {\n    [XmlElement("name")]\n    public string Name { get; set; }\n\n    [XmlElement("nationality")]\n    public string Nationality { get; set; }\n}\n\nvoid Main() {\n    // ...\n    var serializer = new XmlSerializer(typeof(Employee));\n    var emp = new Employee { /* properties... */ };\n    using (var output = /* open a Stream or a StringWriter for output */) {\n        serializer.Serialize(output, emp);\n    }\n}	0
1528733	1528724	Converting a List<int> to a comma separated list	List<int> list = ...;\nstring.Join(",", list.Select(n => n.ToString()).ToArray())	0
5661603	5661569	Regular expression to match numbers only not starting with zero	string expression = @"^[1-9]\d*$";	0
27245242	27244901	Any way to convert excel cell value in to html format?	StringBuilder html = new StringBuilder();\n    for (int index = 1; index <= cell.Text.ToString().Length; index++)\n    {\n        //cell here is a Range object\n        Characters ch = cell.get_Characters(index, 1);\n        bool bold = (bool) ch.Font.Bold;\n        if(bold){\n                 if (html.Length == 0)\n                      html.Append("<b>");\n                 html.Append(ch.Text);\n         }\n    }\n    if (html.Length !=0) html.Append("</b>")	0
10254023	10253321	rtf to textblock	public MainWindow()\n{\n    InitializeComponent();\n\n    richTextBox.Document = new FlowDocument();\n    flowDocumentScrollViewer.Document = new FlowDocument();\n}\n\nprivate void CopyDocument(FlowDocument source, FlowDocument target)\n{\n    TextRange sourceRange = new TextRange(source.ContentStart, source.ContentEnd);\n    MemoryStream stream = new MemoryStream();\n    XamlWriter.Save(sourceRange, stream);\n    sourceRange.Save(stream, DataFormats.XamlPackage);\n    TextRange targetRange = new TextRange(target.ContentStart, target.ContentEnd);\n    targetRange.Load(stream, DataFormats.XamlPackage);\n}\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    CopyDocument(richTextBox.Document, flowDocumentScrollViewer.Document);\n}	0
6179641	6179610	Break a string down to ASCII numbers	var arr = Encoding.ASCII.GetBytes("Hello");	0
311739	311710	How do I sum a list<> of arrays	var sums = Enumerable.Range(0, myList[0].Length)\n           .Select(i => myList.Select(\n                     nums => nums[i]\n                  ).Sum()\n           );	0
3670111	3669779	Adding new RenderTransforms to WPF Control	Transform t = myObject.RenderTransform;\nMatrix m = t.Value;\nm.ScaleAt(1.1, 1.1, 0, 0);\n\nmyObject.RenderTransform = new MatrixTransform(m);	0
421263	421257	How do I use a C# keyword as a property on an anonymous object?	var @class = new object();	0
33892875	33891492	How to fix foreach in treeview	private void button2_Click(object sender, EventArgs e)\n  {\n      RemoveChecked(treeView1.Nodes);\n  }\n\n  void RemoveChecked(TreeNodeCollection nodes)\n  {\n      foreach (TreeNode checkedNode in FindCheckedNodes(nodes))\n      {\n        nodes.Remove(checkedNode);\n      }\n  }\n\n\n  private List<TreeNode> FindCheckedNodes(TreeNodeCollection nodes)\n  {\n      List<TreeNode> checkedNodes = new List<TreeNode>()\n      foreach (TreeNode node in nodes)\n      {\n        if (node.Checked)\n        {\n          checkedNodes.Add(node);\n        }\n        else\n        {\n          // find checked childs        \n          checkedNodes.AddRange(FindCheckedNodes(node.Nodes));               \n        }\n      }\n      return checkedNodes;\n  }	0
34250930	34250770	C# Using a list of objects to populate combobox and keeping object properties accessible	cmbClass.DataSource = classes;\n    cmbClass.DisplayMember = classroom.DisplayName;	0
202383	202330	What's a nice way of building a wParam or lParam in C#? (Something friendlier than shift operators?)	public static ushort LowWord(uint val)\n{\n    return (ushort)val;\n}\n\npublic static ushort HighWord(uint val)\n{\n   return (ushort)(val >> 16);\n}\n\npublic static uint BuildWParam(ushort low, ushort high)\n{\n    return ((uint)high << 16) | (uint)low;\n}	0
9602125	9601382	How can i add iframe in my master page	function InsertIFrame(path) {                           \n                                var iframe = document.createElement('iframe');\n                                iframe.src = path;\n                                document.body.appendChild(iframe);                                \n                        }	0
14907106	14853362	MongoDB: update only specific fields	var query = Query.EQ("_id","123");\nvar sortBy = SortBy.Null;\nvar update = Update.Inc("LoginCount",1).Set("LastLogin",DateTime.UtcNow); // some update, you can chain a series of update commands here\n\nMongoCollection<User>.FindAndModify(query,sortby,update);	0
12691341	12691244	How to format a windows service with vs template?	public partial class Service1 : ServiceBase \n{ \n    Thread thread1; \n   Boolean running = false;\n\n    public Service1() \n    { \n        InitializeComponent(); \n\n        thread1 = new Thread(function); \n\n    } \n\n    protected override void OnStart(string[] args) \n    { \n        thread1.Start(); \n        running = false;\n    } \n\n    protected override void OnStop() \n    { \n        running = false;\n        thread1.Stop(); \n    } \n\n    public void function() \n    { \n        while (running) \n        { \n            //keep doing something \n        } \n    } \n}	0
11273660	11273485	ASP.net CheckboxList Inserting to DB	for (int i = 0; i < CheckBoxList1.Items.Count; i++)\n        {\n            if (CheckBoxList1.Items[i].Selected)\n            {\n                // if item is checked do something\n            }\n        }	0
2984071	2984050	Configure ListBox in WPF so that I will be possible to select multiple items without holding CTRL key	SelectionMode="Multiple"	0
31186051	31183710	How much repository interfaces must created in Repository Pattern?	interface ICRUDRepo<T> //where T is always a Domain object\n{\n    T get(GUid id);\n    void Add(T entity);\n    void Save(T entity);\n }\n\n//then it's best (for maintainability) to define a specific interface for each case\n\ninterface IProductsRepository:ICRUDRepo<Product>\n{\n    //additional methods if needed by the domain use cases only\n\n    //this search the storage for Products matching a certain criteria,\n    // then returns a materialized collection of products \n    //which satisfy the given criteria\n    IEnumerable<Product> GetProducts(SelectByDate criteria);\n }	0
15822275	15820250	Close Telerik Radgrid Editform If Already Opened	CommandName="Cancel"	0
19867026	19866842	Hidden button won't show when set to visible=true unless browser refreshes	DeleteCommand="DELETE FROM [TableName] WHERE [ColumnName]=@[ParameterName];">\n            <DeleteParameters>\n                <asp:ControlParameter Name="[ParameterName]" ControlId="storyGridView" PropertyName="SelectedValue" />\n            </DeleteParameters>	0
18615506	18614605	UnZip files to the previous folder	using(ZipFile zip = new ZipFile("E:\\Hello\\Hi\\Photos.zip"))\n{\n    zip.FlattenFoldersOnExtract = true;\n    zip.ExtractAll("E:\\Hello\\Hi\\", ExtractExistingFileAction.DoNotOverWrite);\n}	0
33196160	33196111	Using a model that has an implicit conversion to the declared @model in a display template	var extended = (ExtendedMyClass)item;\n@Html.DisplayFor(m => extended)	0
9206701	9206567	making List<string> compatible for datagridview column?	DataGridViewComboBoxColumn d = new DataGridViewComboBoxColumn(); \nList<string> data = new List<string>();        \ndata.Add("a");         \ndata.Add("b");         \ndata.Add("c"); \nd.DataSource = data ;	0
8798278	8798233	Splitting a string and insert into a database	BULK INSERT Contact\nFROM 'c:\TestData.csv'  -- Full path of the Delimited file\nWITH\n(\nFIELDTERMINATOR = ',', --CSV field delimiter\nROWTERMINATOR = '\n'   --Use to shift the control to next row\n)	0
17407824	17407761	Order database entries based on multiple conditions using linq	OrderBy(x => x.IsLocked).ThenBy(...)\n                        .ThenBy(...)	0
14283717	14283349	Matching two Lists of different types together	var query = from fm in dbContext.FamilyMen\n            join bm in dbContext.BusinessMen on \n                new { bm.name, bm.color } equals new { fm.name, fm.color }\n            select new {\n               FamilyMan = fm,\n               BusinessMan = bm\n            };\n\nvar resultList = query.ToList();	0
850323	850306	c# deriving from int32	class RoomId\n{\n    private int Value {get; set;}\n\n    public RoomId(int value)\n    {\n        this.Value = value;\n    }\n\n    public bool Equals(RoomId other)\n    {\n        return this.Value == other.Value;\n    }\n}\n\nRoomId room1 = new RoomId(1);\nRoomId room2 = new RoomId(2);\n\n// To compare for equality\nbool isItTheSameRoom = room1.Equals(room2);\n// Or if you have overloaded the equality operator (==)\nbool isItTheSameRoom = room1 == room2;	0
11745313	11745278	Easy to use strongly-typed JSON library for C#	List<string> names = new List<string>() {"Mike","Joe","Jane"};\n        Dictionary<string, int> ids = new Dictionary<string, int>()\n                                          {\n                                              {"Mike",1},\n                                              {"Joe",2},\n                                              {"Jane",3},\n                                          };\n\n        // ["Mike","Joe","Jane"]\n        string nameJson = Newtonsoft.Json.JsonConvert.SerializeObject(names);\n\n        //{"Mike":1,"Joe":2,"Jane":3}\n        string idsJSon = Newtonsoft.Json.JsonConvert.SerializeObject(ids);	0
6587087	6587044	Dictionary of dates and values, finding value of max date per year in LINQ	var lastValues = records.OrderByDescending(r => r.Date)\n                     .GroupBy(r => r.Date.Year)\n                     .Select(g => g.First().Value);	0
3924835	3924412	How could I emulate a visual analogue scale (VAS) in Winforms?	this.trackBar1.MouseDown += trackBar1_MouseDown;\n\n// ...\n\nvoid trackBar1_MouseDown(object sender, MouseEventArgs e)\n{\n    double leftDelta = e.Location.X - this.trackBar1.Location.X;\n    this.trackBar1.Value = (int)(leftDelta / this.trackBar1.Size.Width * 100);\n}	0
14076609	14076570	How Can I make my PDF exactly fit within 4x6 inches? currently It is printing in regular A4 document	Dim pgSize As New iTextSharp.text.Rectangle(myWidth, myHeight) \nDim doc As New iTextSharp.text.Document(pgSize, leftMargin, rightMargin, topMargin, bottomMargin)	0
2724906	2724744	Removing items from lists and all references to them	public class Node\n{\n    // Has Some Data!\n\n    public List<Branch> BranchesIn;\n    public List<Branch> BranchesOut;  // assuming this is a directed graph\n\n    public void Delete()\n    {\n      foreach (var branch in BranchesIn)\n        branch.NodeB.BranchesOut.Remove(branch);\n\n      foreach (var branch in BranchesOut)\n        branch.NodeA.BranchesIn.Remove(branch);\n\n      BranchesIn.Clear();\n      BranchesOut.Clear();\n     }\n}\n\npublic class Branch\n{\n    // Contains references to Nodes\n    public Node NodeA\n    public Node NodeB\n}	0
3212918	3208439	Access DataContext behind IQueryable	static DataContext GetContext (IQueryable q)\n{\n  if (!q.GetType().FullName.StartsWith ("System.Data.Linq.DataQuery`1")) return null;\n  var field = q.GetType().GetField ("context", BindingFlags.NonPublic | BindingFlags.Instance);\n  if (field == null) return null;\n  return field.GetValue (q) as DataContext;\n}	0
4139376	4139287	Get the Monday and Sunday for a certain DateTime in C#	DateTime d = DateTime.Today;\n\n // lastMonday is always the Monday before nextSunday.\n // When today is a Sunday, lastMonday will be tomorrow.     \n int offset = d.DayOfWeek - DayOfWeek.Monday;     \n DateTime lastMonday = d.AddDays(-offset);\n\n DateTime nextSunday = lastMonday.AddDays(6);	0
1089783	1089774	Dealing with null dates returned from db	calEventDTO.recurrenceID = dr.IsDBNull(9) ? null : (DateTime?) dr.GetDateTime(9);	0
22027514	22027432	Looping around in Enumeration in C#	string today = DateTime.Now.DayOfWeek.ToString();\nstring tomorrow = DateTime.Now.AddDays(1).DayOfWeek.ToString();\nstring yesterday = DateTime.Now.AddDays(-1).DayOfWeek.ToString();	0
26924651	26923143	How to lock the control of textbox?	textbox1.Enabled=false;	0
20546072	20545963	Making variable accessible to all areas of my class	namespace MyApp\n{\n    public class MyClass\n    {\n        public static string MyString { get; set; }\n\n        public MyClass()\n        {\n\n        }\n    }\n\n    public class MyOtherClass\n    {\n        public MyOtherClass()\n        {\n            MyClass.MyString = "Test";\n        }\n    }\n}	0
14941341	14941200	How to create a LINQ request	var result = from i in _dbContext.Users\n             let check1 = i.Services.Any(p => p.UsersSelectMeetingCriteria.Any(k => k.ID == CurrentUserID))\n             let check2 = i.GeographicalAreas.Any(p=>p.UsersSelectMeetingCriteria.Any(o=>o.ID == CurrentUserID))\n             let check3 = i.MultiplyItems.Any(r => (r.UsersSelectMeetingCriteria.Any(q => q.ID == CurrentUserID) && r.ItemType == MultiplyItemKeys.USER_TYPE))\n             let check4 = i.MultiplyItems.Any(s => (s.UsersSelectMeetingCriteria.Any(q => q.ID == CurrentUserID) && s.ItemType == MultiplyItemKeys.COMPANY_INVOLVED))\n             let level = 5 - (check1 ? 1 : 0) - (check2 ? 1 : 0) - (check3 ? 1 : 0) - (check4 ? 1 : 0)\n             where i.ID != CurrentUserID && level <= 4\n             select new {i, level};	0
3881461	3881450	C# Copy a file to another location with a different name	System.IO.File.Copy(oldPathAndName, newPathAndName);	0
20035516	20034752	html5 dropdownlist using FindByValue	ddlStateLegalRes.Items[0] == sdr["STATEOFLEGALRESIDENCE"].ToString());	0
18739535	18738498	Date time picker validations	if (dateInsert.Value.ToString() == "")\n              {\n                MessageBox.Show("Please select date!");\n                dateInsert.Focus();\n                return;\n               }	0
17240781	17240642	Difference between lambda expression and expression lambda	x => M(x)\n(x, y) => M(x, y)\n(int x, int y) => M(x, y)\nx => { return M(x); }\n(x, y) => { return M(x, y); }\n(int x, int y) => { return M(x, y); }	0
28936054	28935989	How to add a parent to every child in a json array?	var data = from result in DCHotel.visHTLReservaciones select new { person =  result };	0
31489376	31444218	How to convert HL7 formatted text to HTML?	OBX_Value = OBX_Value.Replace("\.br\", "<br />");\nOBX_Value = OBX_Value.Replace("\h\"; "<b>");\nOBX_Value = ...	0
16892025	16891469	Regular expression for Replace jSon string	(\"[^"]+\":null,?|,?\"[^"]+\":null)	0
12563671	12563655	Private method parameters	private static int Test(string connection, int retryInfiniteLoopGuard)\n{\n    // The code\n}\n\npublic static int Test(String connection)\n{\n    return Test(connection, 0);\n}	0
28827372	28827348	c# how to write to a text file from list box as a result of proccess	//fill the listBoxes\nfor (double i = 0; i <= 90; i++)\n{\n   k = Math.PI / 180;\n   z = Math.Tan((i / 2 + 45) * k);\n\n   x = (d / 3.141) * (Math.Sin(Math.PI * i / 180) - Math.Log(z));\n   y = d / 3.141 * (Math.Cos((Math.PI * i) / 180) + (3.141 / 2)); \n\n   listBox2.Items.Add(x);\n   listBox1.Items.Add(y);\n   listBox3.Items.Add(z);\n}\n\n// write the text file\nconst string sPath = @"C:\Users\NET\Desktop\deneme.txt";\nusing(StreamWriter SaveFile = new StreamWriter(sPath))\n{   \n  for (int i=0; i<listBox1.Items.Count; i++)\n  {\n    string line = String.Format("{0},{1}", listBox1.Items[i], listBox2.Items[i]);\n    SaveFile.WriteLine(line);\n  }          \n}	0
31201703	31201343	WPF Multibinding - Need to use Relaycommand	new RelayCommand(EnemyPopupTooltipEx, null);\n\npublic void EnemyPopupTooltipEx(object parameter){\n   var values = (object[])parameters;\n}	0
17241569	17241384	How can I list files and directories with them directory levels	string[] words = s.Split('\\');	0
919819	919803	How do I run Command line commands from code	DEVCON ReScan	0
15218254	15218101	WiX bootstrapper: How to access execution path	Application.StartupPath;	0
11973848	11973391	change row background color based on a condition using asp.net C# gridview	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) \n{ \n    e.Row.Attributes.Add("style", "cursor:help;"); \n    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate) \n    {  \n        if (e.Row.RowType == DataControlRowType.DataRow) \n        {                 \n            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'"); \n            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'"); \n            e.Row.BackColor = Color.FromName("#E56E94");                 \n        }            \n    } \n    else \n    { \n        if (e.Row.RowType == DataControlRowType.DataRow) \n        { \n            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'"); \n            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'"); \n            e.Row.BackColor = Color.FromName("gray");                 \n        }	0
7306194	7306071	SELECT with "datetime > string" performance issue in EF4 / SQL Server 2008	'20110825'	0
3897985	3897894	Display Full Name Instead of Username in LoginName Control	LoginName loginName = HeadLoginView.FindControl("HeadLoginName") as LoginName;\n\n        if (loginName != null && session != null)\n        {\n            loginName.FormatString = "Full Name";\n        }	0
6958123	6957659	Yield multiple IEnumerables	// The stream of assets\nIObservable<Asset> assets = ...\n\n// The stream of each asset projected to a DebugAnswer\nIObservable<DebugAnswer> debugAnswers = from asset in assets\n                                        select new DebugAnswer { result = 100 };\n\n// Subscribe the DebugListener to receive the debugAnswers\ndebugAnswers.Subscribe(DebugListener);\n\n// The stream of each asset projected to an Anwer\nIObservable<Answer> answers = from asset in assets\n                              select new Answer { bla = 200 };\n\n// Subscribe the AnswerListener to receive the answers\nanswers.Subscribe(AnswerListener);	0
2530683	2530675	Trouble with Action<T1, T2> and passing multiple parameters	s( (x,y) => x.Open(y) );	0
12992371	12992229	pass gridview name for printing	StringWriter sw = new StringWriter();\nHtmlTextWriter hw = new HtmlTextWriter(sw);\nGridViewErrorReport.RenderControl(hw);\nstring gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");\nStringBuilder sb = new StringBuilder();\nsb.Append("<script type = 'text/javascript'>");\nsb.Append("window.onload = new function(){");\nsb.Append("var printWin = window.open('', '', 'left=0");\nsb.Append(",top=0,width=1000,height=600,status=0');");\nsb.Append("printWin.document.write(\"");\nGridView gv = (GridView)this.FindControl("myGridId");\nsb.Append(gv);\nsb.Append("\");");\nsb.Append("printWin.document.close();");\nsb.Append("printWin.focus();");\nsb.Append("printWin.print();");\nsb.Append("printWin.close();};");\nsb.Append("</script>");\nPage.ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());	0
2702127	2702088	Getting the relative path to the rdlc report in my winform app	using System.IO;\n  ...\n\n     string exeFolder = Path.GetDirectoryName(Application.StartupPath);\n     string reportPath = Path.Combine(exeFolder, @"Reports\report.rdlc");	0
28448259	28448218	Formatting Mail body in C# while sending system generated mail	mailMessage = new MailMessage()\n                    {\n                        From = new MailAddress(senderAddress),\n                        Subject = subject,\n                        Body = message,\n                        IsBodyHtml = true\n                    };	0
13817715	13817556	Negative number conversion to binary form in a byte(8 bits)	var str = Convert.ToString(-3, 2)	0
17708531	17708472	Format int to hex string	int e = 1;\nstring f = e.toString("x2");	0
12324113	12323940	Howto: Parallel.Foreach executes many processes, after each process run a new process (but one at a time)?	var lockObj = new object();\n\nParallel.Foreach(files, file => \n{\n    // Processing file\n    lock(lockObj)\n    {\n        // Generate report.\n    }\n});	0
18099040	18098964	Singleton pattern for a property in c#	private static Rootpdf  _pdfConfiguration ;\n    public static Rootpdf pdfConfiguration\n    {\n        get\n        {\n            try\n            {\n                if (_pdfConfiguration == null)\n                {\n                    //retrieve the configuration file.\n                    //load the configuration and return it!\n                }\n                else\n                {\n                    return _pdfConfiguration;\n                }\n            }\n            catch (Exception e)\n            {\n                Log.Error("An error occurred while reading the configuration file.", e);\n            }\n\n            return _pdfConfiguration;\n        }\n    }	0
12215995	12215891	how to bind a non-boolean property to a boolean property	public bool MyPropertyToBindTo {\n    get { return _myLabel.Color == Color.Red; }\n    set { _myLabel.Color = value ? Color.Red : Color.Black; }\n}	0
9232574	9232548	How to make a loop repeat forever?	if(startIndex == length - 16)\n    startIndex = 0;	0
3927812	3927711	Displaying partially hierarchical data with nested repeaters	DataView dv = new DataView(_ds.Tables["category"]);\ndv.RowFilter = "parent_id is null";\n\ncategoryRepeater.DataSource = dv;	0
5185986	5185205	How to use a SQL connection string with ADO.NET Entity Data Model	string format = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=\"{0}\"";\nstring connectionString = "server=severaddress;database=database1;UserID=test;Password=test1234;"\n\nvar context = ModelContext(String.Format(format, connectionString));	0
24560158	24560061	Formatting a string in a similar style to padding	file.WriteLine(String.Format("{0,-30}; {1}", dataVal1, "First Data Value"));\nfile.WriteLine(String.Format("{0,-30}; {1}", dataVal2, "Second Data Value"));	0
3071154	3070699	How do I get all the <li> elements from within a div using Watin?	var liList = _browser.Div("myDiv").ElementsWithTag("li");	0
18744716	18627285	How can insert Drop Down Box values into cross reference Table?	menteeViewModel.mentee.schoolId = menteeViewModel.SelectedSchoolId.ToString();\ndb.mentees.Add(menteeViewModel.mentee);\ndb.SaveChanges();	0
23291147	23290998	Specify password in mysql connection string	var cn = "Server=srv;Database=db;User Id=user;Password=\"'ktrnhjyyst;\"";	0
30815772	30815214	Binding property of usercontrol to data	public static readonly DependencyProperty SourceImageResourceIdProperty = \n        DependencyProperty.Register("SourceImageResourceId", typeof(string), typeof(WaitingImageControl), new PropertyMetadata( string.Empty, OnSourcePathPropertyChanged ));\n\n\n    private static void OnSourcePathPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n        (d as WaitingImageControl).SourceImageResourceId = e.NewValue.ToString();\n    }	0
9406343	9403423	How can a tree be stored in a database?	CREATE TABLE SUFFIX_ARRAY (\n    ORDER INT PRIMARY KEY, -- Position in the suffix array.\n    START INT NOT NULL, -- Position of the starting character of the suffix within the target string.\n    LONGEST_COMMON_PREFIX INT NOT NULL -- If useful for your application.\n)	0
1069622	1069588	SharePoint list item permissions	// get list item\n        SPListItem item = <your list item>;\n        if (!item.HasUniqueRoleAssignments)\n        {\n            item.BreakRoleInheritance(true);\n        }\n\n        // get principal\n        SPPrincipal principal = <principal to grant permissions to>;\n\n        // get role definition\n        SPRoleDefinition rd = <role that contains the permissions to be granted to the principal>;\n\n        // create role assignment\n        SPRoleAssignment ra = new SPRoleAssignment(principal);\n        ra.RoleDefinitionBindings.Add(rd);\n        item.RoleAssignments.Add(ra);	0
31279075	31262950	Nopcommerce Overriding Controller	public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)\n   {\n      builder.RegisterType<YourPlugin.Controllers.\n      ProductController>().As<Nop.Web.Controllers.ProductController>();\n   }\n   public int Order\n   {\n        get { return 100; }\n   }	0
24882733	24882710	How to parse xml string element?	XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";\nXElement textbox = inputElement.Element(ns + "TextBox");	0
1620409	1620366	Delete files from directory if filename contains a certain word	string rootFolderPath = @"C:\\SomeFolder\\AnotherFolder\\FolderCOntainingThingsToDelete";\nstring filesToDelete = @"*DeleteMe*.doc";   // Only delete DOC files containing "DeleteMe" in their filenames\nstring[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);\nforeach(string file in fileList)\n{\n    System.Diagnostics.Debug.WriteLine(file + "will be deleted");\n//  System.IO.File.Delete(file);\n}	0
1806388	1804645	How to set an FK column value without retrieve it	Concept conceptToUpdate = new Concept() {\n      Id = 1 , \n      ConceptType = new ConceptType {Id = OriginalFKValue}\n};\nConceptType conceptType = new ConceptType() { Id = 5 };\ndb.AttachTo("Concept", conceptToUpdate); \ndb.AttachTo("ConceptType", conceptType);\nconceptToUpdate.ConceptType = conceptType;\ndb.SaveChanges();	0
11285103	11285080	How do I compare string with text in a proper way?	string a = "this is a";\nstring b = a;\nstring c = "this is " + x; //x has the value of 'a'\nstring d = "this is a";\nobject oa = a;\nobject ob = b;\nobject oc = c;\nobject od = d;\n\nconsole.WriteLine(a == b); //will print true\nconsole.WriteLine(a == c); //will print true\nconsole.WriteLine(c == b); //will print true\n\nconsole.WriteLine(oa == ob); //will print true\nconsole.WriteLine(oa == oc); //will print false\nconsole.WriteLine(oa == od); //will print true	0
6997915	6997841	Remove items from an Object [] that are contained in a custom class array	getDuplicates().Cast<Client>();	0
33078923	33078743	Trying to query many text files in the same folder with linq	string startFolder = @"C:\MyFileFolder\";\n    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);\n    IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*",\n    System.IO.SearchOption.AllDirectories);\n    var fileData =\n            from file in fileList\n            where (file.Extension == ".dat" || file.Extension == ".csv")\n        select GetFileData(file, ',')\n;\n\npublic  string GetFileData(string filesname, char sep)\n    {\n       using (StreamReader reader = new StreamReader(filesname))\n       {\n        var recs = (from line in reader.Lines(sep.ToString())\n            let parts = line.Split(sep)\n             select       parts[2]);\n        var multipleyears = recs.Distinct().Count();\n        if(multipleyears > 1)\n        return filename;\n        }\n    }	0
6668058	6667990	How do I make a top-docked control appear *under* the existing top-docked controls?	.SetChildIndex(ctrl, 0)	0
2512902	2512825	LINQ to group objects according to timestamp	// splitting time up into hour intervals\nfooList.GroupBy(f => f.Time.Date.AddHours(f.Time.Hour))\n\n// splitting time up into day intervals\nfooList.GroupBy(f => f.Time.Date)\n\n// splitting time up into month intervals\nfooList.GroupBy(f => f.Time.Date.AddDays(-f.Time.Day))	0
1069548	1069497	How to scroll down in a textbox by code in C#	//move the caret to the end of the text\n        textBox.SelectionStart = textBox.TextLength;\n        //scroll to the caret\n        textBox.ScrollToCaret();	0
32827053	32784176	How do I reuse an Expression on a single object in another Expression	private static Expression<Func<Department, DepartmentDto>> CreateDepartmentDtoUnexpanded = d => new DepartmentDto\n{\n    Manager = CreatePersonDto.Invoke(d.Manager),\n    Employees = d.Employees.Select(employee => CreatePersonDto.Invoke(employee))\n        .ToList(),\n};\npublic static Expression<Func<Department, DepartmentDto>> CreateDepartmentDto = CreateDepartmentDtoUnexpanded.Expand();	0
9645908	9645734	inefficient to efficient way to create subfolder in FTP	private bool EnsureDirectoryExists(string path)\n{\n    // check if it exists\n    if (Directory.Exists(path))\n        return true;\n\n    string parentPath = GetParentPath(path);\n    if (parentPath == null)\n        return false;\n\n    bool result = EnsureDirectoryExists(parentPath);\n\n    if (result)\n    {\n        CreateDirectory(path);\n        return true;\n    }\n\n    return false;\n}	0
1700942	1700804	Response.write in a HTML element c#	"<img src=\"" + item.MainImage.ImageUrl095 + "\" alt=\"\" />"	0
4938124	4938092	Is there a way to get a list of all the users on a domain using ASP.NET with C# as the backend?	var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "x.y.com", "DC=x,DC=y,DC=com"));\nvar searcher = new DirectorySearcher(dirEntry)\n         {\n             Filter = "(&(&(objectClass=user)(objectClass=person)))"\n         };\nvar resultCollection = searcher.FindAll();	0
24062434	24062386	Use AddRange for a new List<string>	List<string> list = new List<string>(File.ReadAllLines(path, Encoding.UTF8));	0
5173078	5173049	Find specific pattern in string using C#	string pattern = @"\*\d*\.txt";\nRegex rgx = new Regex(pattern)\ninput = rgx.Replace(input, "");	0
4378451	3963038	ReportViewer: How to load report as an embeddedresource in another assembly using reflection?	public void PrepareReport(IAppReport report)\n{\n   Viewer.LocalReport.LoadReportDefinition(report.GetStream());\n}	0
5736748	5736704	What is an elegant way to convert IDictionary<string, object> to IDictionary<string, string>	parameters.ToDictionary(k=>k.Key, v=>v.Value!=null?v.Value.ToString():(string)null);	0
28810018	28716193	How to create an C#.Net DLL to use in JavaScript	[Guid("A32AB771-9967-4604-B193-57FAA25557D4"), ClassInterface(ClassInterfaceType.None)]	0
2435190	2434834	ProcessCmdKey - wait for KeyUp?	public partial class Form1 : Form, IMessageFilter {\n    public Form1()  {\n        InitializeComponent();\n        Application.AddMessageFilter(this);\n        this.FormClosed += (s, e) => Application.RemoveMessageFilter(this);\n    }\n    bool mRepeating;\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (keyData == (Keys.Control | Keys.F) && !mRepeating) {\n            mRepeating = true;\n            Console.WriteLine("What the Ctrl+F?");\n            return true;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n    public bool PreFilterMessage(ref Message m) {\n        if (m.Msg == 0x101) mRepeating = false;\n        return false;\n    }\n}	0
6401565	6401551	Find bounds of a array? C#	int bound0 = a.GetUpperBound(0);\nint bound1 = a.GetUpperBound(1);	0
18825922	18822190	How to calculate angle between two 2D matrix transform?	| cos(&theta;)   -sin(&theta;)     0 | \nT = | sin(&theta;)    cos(&theta;)     0 | \n    | 0               0                1 |	0
5619683	5580947	How do you Serialize just one of several Optional Elements in .Net?	[XmlAnyElement]\n    public XmlElement[] AllElements\n    {\n        get\n        {\n            XmlElement[] value = new XmlElement[0];\n            return value;\n        }\n\n        set\n        {\n            if (value != null)\n            {\n                foreach (XmlElement e in value)\n                {\n                    switch (e.Name)\n                    {\n                        case "update_mins":\n                            this.Minutes = Convert.ToInt32(e.InnerText);\n                            break;\n                    }\n                }\n            }\n        }\n    }	0
21749306	21719133	How to Access Parent Window's Control from user control window	Window parentWindow = Window.GetWindow(this);\nobject obj= parentWindow.FindName("Popup1"); \nSystem.Windows.Controls.Primitives.Popup pop = (System.Windows.Controls.Primitives.Popup)obj;\npop.IsOpen = false;	0
25035035	25033004	Dispalying pictures from database in xaml	byte[] yourImageBytesFromDatabase = ......;\nMemoryStream ms = new MemoryStream();\nms.Write(yourImageBytesFromDatabase, 0, yourImageBytesFromDatabase.Length);\nBitmapImage src = new BitmapImage();\nsrc.SetSource(ms);	0
10401329	10401267	Input string was not in a correct format - calculating total of labels	tots += double.Parse(((Label)value[p]).Text);	0
3543812	1076348	How To Get the Range of a Page Using Word Automation	Public Sub DemoPerPageText()\n\n    Dim i As Integer\n    Dim totalPages As Integer\n    Dim bmRange As Range\n\n    totalPages = Selection.Information(wdNumberOfPagesInDocument)\n\n    For i = 1 To totalPages\n      Set bmRange = ActiveDocument.Bookmarks("\Page").Range\n      Debug.Print CStr(i) & " : " & bmRange.Text & vbCrLf\n    Next i\n\nEnd Sub	0
5248732	5248251	Gather all textboxes on a form, generate GUIDs for each of them	protected void Button1_Click(object sender, EventArgs e)\n{\n    foreach (Control MyControl in Form1.Controls)\n    {\n        TextBox MyTextBox = MyControl as TextBox;\n\n        if (MyTextBox != null)\n        {\n            MyTextBox.ID = Guid.NewGuid().ToString();\n        }\n    }	0
25919274	25919193	Sorting a column in a list by considering first three letters of the element in each cell	var res = theList.OrderBy(x => int.Parse(x.Term.Substring(1, 2)))\n                 .ThenBy(x => x.Term.Substring(0, 1)).ToList();	0
20302573	20302424	Foreach and for changes a lot more items then should	var anotherList =\ncollection\n.Where(_ => random.NextDouble() < somedouble)\n.Select(item => item.CreateCopyWithEnum(Enum.Something))\n.ToList();	0
24619838	24618798	Automated downloading of X509 certificate chain from remote host	foreach (X509ChainElement el in chain.ChainElements) {\n var certToCreate = el.Certificate.Export(X509ContentType.Cert);\n  ...\n}	0
21153695	21153532	Detecting words with exactly X uppercase letters	string strTester = "AaaaAA";\n\n        var results = System.Text.RegularExpressions.Regex.Matches(strTester,"(.*[A-Z]{1}.*){3,}");\n        var occuranceCount = results.Count;\n\n        if (occuranceCount >= 1 ) {\n            Console.WriteLine("true");\n        }\n        else {\n            Console.WriteLine("false");\n        }	0
14864317	14863920	How can I query using Entity Framework with an alpha-numeric comparison?	Provider provider = dbContext.Providers.Where(p => p != null && p != "").ToList()\n.Where(p => *Do regex comparison here*).FirstOrDefault();	0
29774624	29774048	Date text format in WPF DataGrid bound to XML file	Binding="{Binding XPath=Birthday, Converter={StaticResource birthdayConverter}}"\n\npublic class BirthdayConverter : IValueConverter\n {\n     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n     {\n         //Convert date to desired format.\n     }\n\n     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n     {\n        // Convert back.\n     }\n }	0
25314340	25258659	How to set the Content-Type header for a RestRequest?	request.AlwaysMultipartFormData = true	0
32750589	32750505	Linq join two List<T> using multiples flags	var arr1Negative = arr1.Select(a => \n    new Articles() \n    { \n        ArticleId = a.ArticleId, \n        CellarId = a.CellarId, \n        ArticleQuantity = -a.ArticleQuantity\n    });	0
16576775	16576736	c# for a group of objects get property and ensure same value for all	public Code\n{\n    get {\n        return Payments.Select(x => x.Code)\n                              .Distinct()\n                              .Single();\n    }\n}	0
25126865	25106525	Trying to get recognize a class instance in roslyn	var doc = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();\nvar model = doc.GetSemanticModelAsync().Result;\nvar symbol = SymbolFinder.FindSymbolAtPosition(model, point, doc.Project.Solution.Workspace);	0
6840106	6837401	c# chart control remove spaces between bars in bar chart	chart1.Series[0]["PointWidth"] = "1";	0
3503523	3503184	How to invoke a method from a workflow in WF 4?	public class TestClass\n{\n    public void StartWorkflow()\n    {\n        var workflow = new Sequence\n                        {\n                            Activities =\n                                {\n                                    new WriteLine {Text = "Before calling method."},\n                                    // Here I would like to call the method ReusableMethod().\n                                    new InvokeMethod {MethodName="ReusableMethod", TargetType = typeof(TestClass)},\n                                    new WriteLine {Text = "After calling method."}\n                                }\n                        };\n        var wf = new WorkflowApplication(workflow);\n        wf.Run();\n        var are = new AutoResetEvent(false);\n        wf.Completed = new Action<WorkflowApplicationCompletedEventArgs>(arg => are.Set());\n        are.WaitOne(5000);\n    }\n\n    public static void ReusableMethod()\n    {\n        Console.WriteLine("Inside method.");\n    }\n}	0
27137697	27137524	Fill one row of a two-dimensional array with a single-dimensional array	var data = new string[rows.Count()][];\n\n// This should be valid, an array of arrays\ndata[0] = GetHeaders();\n\nvar i = 1;\nforeach (var row in rows) {\n    data[i][0] = row.First;\n    data[i][1] = row.Last;\n    data[i][2] = row.Phone;\n    i++;\n}	0
23992409	23991558	Minimum Longest Distance Algorithm, Problems with implementation	private static int recursiveMin(int[] distances, int days) {\n      // check for edge cases (single distance or one day)\n      if(distances.length == 1) {\n         return distances[0];\n      }\n      if(days == 1) {\n         int sum = 0;\n         for(int i=0;i<distances.length;i++) {\n            sum += distances[i];\n         }\n         return sum;\n      }\n\n      // get the last distance\n      int last = distances[distances.length - 1];\n\n      // create the reduced array\n      int[] oneLess = new int[distances.length - 1];\n      for(int i=0;i<oneLess.length;i++) {\n         oneLess[i] = distances[i];\n      }\n\n      // this is the max{M d?1(e1,?,en?1), en} part\n      int right = Math.max( recursiveMin( oneLess, days - 1 ), last );\n\n      // now use the reduced array again but add the last value on at the end\n      oneLess[oneLess.length - 1] += last;\n\n      // this is the Md(e1,?,e?n?1) part\n      int left = recursiveMin( oneLess, days );\n\n      return Math.min( left, right );\n   }	0
9013000	9012946	Comparing on one element of on object in a list?	public class myItems\n{\n    public string itemName;\n    public int count;\n}\n\nList<myItems> items = new List<myItems>();\n\nmyItems e = new myItems();\ne.symbol = "pencil";\ne.count = 3;\nAdd(items, e);\n\nmyItems e1 = new myItems();\ne1.symbol = "eraser";\ne1.count = 4;\nAdd(items, e1);\n\nmyItems e2 = new myItems();\ne1.symbol = "pencil";\ne1.count = 3;\nAdd(items, e5);\n\npublic void Add(List<myItems> list, myItems newItem)\n{\n    var item = list.SingleOrDefault(x => x.symbol == newItem.symbol);\n\n    if(item != null)\n    {\n        item.count += newItem.count;\n    }\n    else\n    {\n        list.Add(newItem);\n    }\n}	0
17390033	17389981	How to Serialize List<CustomClass> into XML	public class Server\n{\n    public string serverName { get; set; }\n    public string dnsIP { get; set; }\n    public Game game { get; set; }\n}\n\npublic class Game\n{\n    public enum Genre { FPS, RTS, RPG, MMO, MOBA, TPS, Sandbox, Other };\n\n    public string gameName { get; set; }        \n    public Genre genre { get; set; }\n}	0
23872736	23858619	How to find current slide in Powerpoint Slideshow Window	SlideShowWindows(1).View.Slide.SlideIndex	0
16811058	16810994	How to select only one checkbox at a time in WPF?	public void MaleOnSelection(object sender, EventArgs e)\n{\n    if(chkFemale.Selected)\n        chkFemale.Selected=false;\n}	0
8578766	8578592	C# string with particular character at end to integer	/// <summary>\n/// Gets the value.\n/// </summary>\n/// <param name="number">The number.</param>\n/// <returns></returns>\npublic static decimal GetValue(string number)\n{\n    char unit = number.Last();\n    string num = number.Remove(number.Length - 1, 1);\n\n    decimal multiplier;\n    switch (unit)\n    {\n        case 'M':\n        case 'm':\n            multiplier = 1000000; break;\n\n        default:\n            multiplier = 1; break;\n    }\n\n    return decimal.Parse(num) * multiplier;\n}	0
23745828	23745554	Accessing a property from an object in same script	mass = SelectedTarget.GetComponent<NameOfScriptThatHasMassProperty>().mass;	0
7899085	7899024	How to set default values for a user control?	[DefaultValue{false)]\npublic bool Marquee\n...	0
7282040	7281995	How can I get this DateTime format in .NET	yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );	0
1418282	1418188	Want a Strongly Typed Result from a JOIN in .netTiers	MyViewParameterBuilder builder = new MyViewParameterBuilder();\nbuilder.AppendEquals(TableColumn.Column, "value");\nDataRepository.MyViewEntityProvider.Find(builder.GetParameters());	0
13608472	13608409	Inserting in Specified cell in Excel using Open XML	excel.Add(new ExcelCell(1, 1, "test1,1"));\nexcel.Add(new ExcelCell(1, 2, "test1,2"));\nexcel.Add(new ExcelCell(2, 2, "test2,2"));\nexcel.Add(new ExcelCell(2, 3, "test2,3"));	0
29998097	29981700	Associated extension doesn't send file name to application on double click	RegistryKey command, defaultIcon, extension;\n        // Create Keys\n        command = Registry.CurrentUser.CreateSubKey(@"Software\Classes\APP NAME\shell\open\command");\n        defaultIcon = Registry.CurrentUser.CreateSubKey(@"Software\Classes\APP NAME\DefaultIcon");\n        extension = Registry.CurrentUser.CreateSubKey(@"Software\Classes\.EXTENSION");\n\n        // Create Values\n        command.SetValue("", "\"" + Application.ExecutablePath + "\" %1", RegistryValueKind.String);\n        defaultIcon.SetValue("", "ICON PATH", RegistryValueKind.String);\n        extension.SetValue("", "APP NAME", RegistryValueKind.String);	0
9327916	9327899	How to pre-set the value in the public struct?	public double total\n{\n    get\n    {\n        return rate * quantity;\n    }\n}	0
5210912	5210903	Parsing a String for Special characters in C#	string str = "Arnstung Chew (20)";\n\nstring replacedString = str.Substring(0, str.IndexOf("(") -1 ).Trim();\n\nstring safeString = System.Web.HttpUtility.HtmlEncode(replacedString);	0
15029833	15029707	Getting average of sums	var avg = list.GroupBy(G => G.Id)\n              .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum)))\n              .Average();	0
2333437	2333279	databind a month list but use numbers instead of names	Dictionary<string, int> myList = new Dictionary<string, int>();\n        myList.Add("Jan", 1);\n        myList.Add("Feb", 2);\n\n        System.Web.UI.WebControls.DropDownList drodown = new System.Web.UI.WebControls.DropDownList();\n        drodown.DataSource = myList;\n        drodown.DataTextField = "key";\n        drodown.DataValueField = "value";\n        drodown.DataBind();\n\n        int monthValue = int.Parse(drodown.SelectedValue);	0
17503325	17502606	Deserializing just a single node of a JSON response	await JsonConvert.DeserializeObjectAsync<ConfigResponse>(jsontoobject, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });	0
5517337	5515886	LINQ - JSON Help needed	string json = "{ \"message\": { \"to\": { \"num\": \"7891234567\", \"name\": \"Jane Doe\" }, \"body\": \"Hello\", \"from\": { \"num\": \"1231234567\", \"name\": \"John Doe\" }, \"type\": 0, \"dateTime\": 1301493974000 } }";\n\nJavaScriptSerializer js = new JavaScriptSerializer();\ndynamic foo = js.Deserialize<dynamic>(json);\nvar message = new {Num = foo["message"]["from"]["num"], Body = foo["message"]["body"]};\n\nConsole.WriteLine("{0}: {1}", message.Num, message.Body);\nConsole.ReadLine();	0
281679	281640	How do I get a human-readable file size in bytes abbreviation using .NET?	string[] sizes = { "B", "KB", "MB", "GB" };\ndouble len = new FileInfo(filename).Length;\nint order = 0;\nwhile (len >= 1024 && order + 1 < sizes.Length) {\n    order++;\n    len = len/1024;\n}\n\n// Adjust the format string to your preferences. For example "{0:0.#}{1}" would\n// show a single decimal place, and no space.\nstring result = String.Format("{0:0.##} {1}", len, sizes[order]);	0
6428951	6428871	WP7: What is the easiest way to convert a group of textboxes from text to a number or decimal value?	foreach(Control c in this.panel1.Controls)\n        {\n            if (c.GetType() == typeof(TextBox) && c.Text != String.Empty)\n            {\n                decimal myValue = Convert.ToDecimal(c.Text);\n            }\n        }	0
27443593	27443447	Parse String to Decimal using any decimal seperator	...\nvalue = "1.345,978";\nstyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;\nculture = CultureInfo.CreateSpecificCulture("es-ES");\nif (Double.TryParse(value, style, culture, out number))\n   Console.WriteLine("Converted '{0}' to {1}.", value, number);\nelse\n   Console.WriteLine("Unable to convert '{0}'.", value);\n// Displays:  \n//       Converted '1.345,978' to 1345.978. \n\nvalue = "1 345,978";\nif (Double.TryParse(value, style, culture, out number))\n   Console.WriteLine("Converted '{0}' to {1}.", value, number);\nelse\n   Console.WriteLine("Unable to convert '{0}'.", value);\n...	0
23951772	23866343	json enum default value c#	public enum YesNoUnknown\n{\n    [EnumString("unknown")]\n    Unknown,\n\n    [EnumString("yes")]\n    Yes,\n\n    [EnumString("no")]\n    No\n}\n\n    [JsonProperty(PropertyName = "property1")]\n    [JsonConverter(typeof(EnumAttributeConverter<YesNoUnknown>))]\n    public YesNoUnknown Property1 { get; set; }	0
13810450	13809997	Serialize property that throws NotImplementedException	var settings = new JsonSerializerSettings();\nsettings.Error += (o, args) => {\n    if(args.ErrorContext.Error.InnerException is NotImplementedException)\n        args.ErrorContext.Handled = true;\n};\n\nvar s = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, settings);	0
5973336	5972699	Reset AutoIncrement in DataTable	dt.Clear();\ndt.Column["id"].AutoIncrementStep = -1;\ndt.Column["id"].AutoIncrementSeed = -1;\n\ndt.Column["id"].AutoIncrementStep = 1;\ndt.Column["id"].AutoIncrementSeed = 1;	0
4931385	4931337	Define a variable of different types	void SomeMethod<T>(T whatever) where T : WebControl, ITextControl {...}	0
9970537	9970522	How to programatically set the content of a Viewbox?	ViewBox.Child = new BlahMaster2000();	0
1471586	1471532	couldn't access registry HKLM keys	private static int GetEnabledStatus()\n{\n    const int defaultStatus = 0;\n    using (var key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\myApp")) // open read-only\n    {\n        int valueInt;\n        var value = (key != null\n            ? key.GetValue("enabled", defaultStatus)\n            : defaultStatus);\n        return (value is int\n            ? (int)value\n            : int.TryParse(value.ToString(), out valueInt)\n                ? valueInt\n                : defaultStatus);\n    }\n}	0
1759129	1759086	DropDownList in C#, getting DropDownList items overflow after every time using selecting an item	if (!Page.IsPostBack)\n{\n    // Populate list\n}	0
23365148	23365091	Sort List<T> with an array	string stringIDs = "8,9,12,11,7";\n\nint[] intArray = stringIDs.Split(',').Select(n => Convert.ToInt32(n)).ToArray();\n\nvar lstLimitedList = (\n        from r in lstAllList \n        where intArray.Contains(r.id) \n        orderby Array.IndexOf(intArray, r.id)   // <--------\n        select r).ToList();	0
26314775	26279745	Bulk insert into SQL table from CSV using C#	builder.Append(" rowterminator='\\n',"); \nbuilder.Append(" fieldterminator = '\\t'");	0
5599056	5584100	How to traverse Directory with Distinguished Names	string GetNewDN(DirectoryEntry deBase, string DN)\n{\n    try\n    {   // Handle the LDAP://example.com:389/DN=string formats\n        return (new Uri(deBase.Path)).GetLeftPart(UriPartial.Authority) + "/" + DN.Replace("/", @"\/");\n    }\n    catch (UriFormatException)\n    {   // Handle the LDAP://DN=string formats\n        return deBase.Path.Substring(0, deBase.Path.IndexOf(":")) + "://" + DN.Replace("/", @"\/");\n    }\n}	0
4946710	4946657	Filtering Sql table Data in Linq	DBSearchDataContext db = new DBSearchDataContext();          \nobject q = from b in db.Articles                    \n           where \n           (b.Tags.Contains(val) ||                    \n           b.NewsTitle.Contains(val) ||                    \n           b.EnglishContent.Contains(val)) && \n           !( b.SomeCategoryList.Containts("videos") || b.SomeCategoryList.Contains("photos") )\n           select b;	0
9531455	9531375	Loading text file into listbox	List<string> lines = new List<string>();\nusing (StreamReader r = new StreamReader(f))\n{\n    string line;\n    while ((line = r.ReadLine()) != null)\n    {\n        lines.Add(line);\n    }\n}	0
1718483	1718389	right click context menu for datagridview	private void dataGridView1_MouseClick(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        ContextMenu m = new ContextMenu();\n        m.MenuItems.Add(new MenuItem("Cut"));\n        m.MenuItems.Add(new MenuItem("Copy"));\n        m.MenuItems.Add(new MenuItem("Paste"));\n\n        int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;\n\n        if (currentMouseOverRow >= 0)\n        {\n            m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));\n        }\n\n        m.Show(dataGridView1, new Point(e.X, e.Y));\n\n    }\n}	0
32852918	32852749	Find all files in first sub directories	var path = Path.Combine(\n    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),\n    @"GameLauncher");\nvar includedExtensions = new HashSet<string> { ".exe", ".lnk", ".url" };\nvar files =\n    from dir in Directory.EnumerateDirectories(path)\n    from file in Directory.EnumerateFiles(dir)\n    let extension = Path.GetExtension(file)\n    where includedExtensions.Contains(extension)\n    select file;	0
17834123	17833602	Retrieving data from two XML that depends on each other	public List<BookDetails> GetBookDetails()\n        {\n            XDocument xDOC = XDocument.Load("FilePath");\n            List<BookDetails> bookdet = (from xele in xDOC.Descendants("Book")\n                                         select new BookDetails\n                                         {\n                                             BookName = (string)xele.Element("BookName"),\n                                             Author = (string)xele.Element("Author")\n                                         }).ToList<BookDetails>();\n            return bookdet;\n        }\n\npublic class BookDetails\n    {\n        public string BookName { get; set; }\n        public string Author { get; set; }\n    }	0
7513522	7512968	remove back color from multiple positions in richTextBox	List<Match> matches = new List<Match> { };\n\n\n void Highlight(string SearchString,Color highlightColor)\n {\n foreach (var match in matches)\n {\n UpdateMatchBgColor(richTextBox1,match.pos,match.length,match.color);\n }\n matches = SearchMatches(SearchString);\n\n foreach (var match in matches)\n {\n UpdateMatchBgColor(richTextBox1,match.pos,match.length,highlightColor);\n }\n\n }	0
11736760	11735003	Club data in a data table into a single row based on a condition in C#	var drdatedisp = from row in dtfullreport.AsEnumerable()\n                  group row by row.Field<string>("Order_Date") into g\n                  select new\n                  {\n                      Order_Date = g.Key,\n                      totalAmt = g.Sum(a => a.Field<int>("Item_Quantity"))\n\n                  };\n DataTable dtdatedisp = new DataTable();\n dtdatedisp.Columns.Add("Order_Date");\n dtdatedisp.Columns.Add("Quantity");\n dtdatedisp.Rows.Clear();\n foreach (var g in drdatedisp)\n {\n     DataRow newRow1 = dtdatedisp.NewRow();\n     newRow1[0] = g.Order_Date;\n     newRow1[1] = g.totalAmt;\n     dtdatedisp.Rows.Add(newRow1);\n }	0
10767733	10767088	how to add items to a 2D array dynamically after comparing? c# windows forms	class Program\n{\n    static void Main(string[] args)\n    {\n        String[] array1 = {"a","b","c","d","e","f"};\n        String[,] array2 = new String[,] {{"a","b","c","d"},{"d","e","f","g"}};\n\n        List<String> array1AsList = array1.OfType<String>().ToList();\n        List<String> array2AsList = array2.OfType<String>().ToList();\n\n        // referring from **Ed S comments below**. Instead of using OFType(...)\n        // alternatively you can use the List<>().. ctor to convert an array to list\n        // although not sure for 2D arrays\n\n        var common = array1AsList.Intersect(array2AsList);\n\n    }\n}	0
1677281	1677200	Sharepoint SPWeb rename - Exception SPException - The security validation for this page is invalid	SPSecurity.RunWithElevatedPrivileges(() =>\n{\n    using (SPWeb thisWeb = site.OpenWeb(webUrl))\n    {  \n        try\n        {\n        thisWeb.AllowUnsafeUpdates = true;\n\n        if (!thisWeb.ValidateFormDigest())\n            throw new InvalidOperationException("Form Digest not valid");\n\n        thisWeb.Title = newName;\n        thisWeb.Update();\n        }\n        finally\n        {\n            if(thisWeb != null)\n                thisWeb.AllowUnsafeUpdates = false;\n        }\n    }\n});	0
20182307	20182195	using log4net for general purposes	log.InfoFormat("Wrote file in {0}ms", elapsed2);	0
7589941	7589772	Change last octet of IP returned by gethostentry	byte[] ipBytes = ip.GetAddressBytes();\nwhile (ipBytes[0]++ < byte.MaxValue)\n{\n  var newIp = new IPAddress(ipBytes);\n  Console.WriteLine("    {0}", ip);\n}	0
16620936	16615776	Windows Phone: Cancel HttpWebRequest and get data	_request.AllowReadStreamBuffering = false;	0
29796213	29796161	Add objects to list in C#	while (sdr.Read())\n{\n    Group groupclass = new Group();\n    groupclass.groupName = sdr.GetString("group_name");\n    groupclass.groupID = sdr.GetString("ID");\n    group.Add(groupclass);\n}	0
29673852	29670897	How to manage different settings for each customer?	app.config\n    app.Release-Internal.config\n    app.Release-CustomerA.config\n    app.Release-CustomerB.config	0
618312	618305	Enum Casting	if(!Enum.IsDefined(typeof(MyEnum), value))\n     throw new ArgumentOutOfRangeException();	0
21147198	21125158	How can an application that has a not visible WinForm be restored from another application?	using System;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;   // Add reference to Microsoft.VisualBasic\n\nnamespace MyApp\n{\n  class Program : WindowsFormsApplicationBase \n  {\n     /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    [STAThread]\n    static void Main(string[] args)\n    {\n      var app = new Program();\n      app.Run(args);\n    }\n    public Program()\n    {\n      this.IsSingleInstance = true;\n      this.EnableVisualStyles = true;\n      this.MainForm = new fMain();\n    }\n    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)\n    {\n      if (this.MainForm.WindowState == FormWindowState.Minimized) {\n        this.MainForm.Show();     // Unhide if hidden\n        this.MainForm.WindowState = FormWindowState.Normal; //Restore\n      }\n      this.MainForm.Activate();\n    }\n  }\n\n}	0
25974579	25969656	Irregular interval on DateTime Axis in OxyPlot	_xAxis = new DateTimeAxis\n{\n    Position = AxisPosition.Bottom,\n    StringFormat = Constants.MarketData.DisplayDateFormat,\n    Title = "End of Day",\n    IntervalLength = 75,\n    MinorIntervalType = DateTimeIntervalType.Days,\n    IntervalType = DateTimeIntervalType.Days,\n    MajorGridlineStyle = LineStyle.Solid,\n    MinorGridlineStyle = LineStyle.None,\n};	0
4319465	4319427	LINQ: How to force a value based reference?	var param = Expression.Parameter(typeof(Foo), "x");\n        var body = Expression.Equal(\n            Expression.PropertyOrField(param, "Name"),\n            Expression.Constant(f.Name, typeof(string)));\n\n        var exp = Expression.Lambda<Func<Foo, bool>>(body, param);\n        filterLst.Add(exp);	0
25911491	25911451	how to check for an empty file in C#	String.IsNullOrWhiteSpace	0
14140125	14140084	Best way to append newline to string except for last	string.Join("\n", errorMessages);	0
4288346	4287623	.NET BUG? SplitContainer Split move selects all text of contained controls	using System;\nusing System.Windows.Forms;\n\nclass MyComboBox : ComboBox {\n    protected override void OnResize(EventArgs e) {\n        if (!this.Focused && this.DropDownStyle == ComboBoxStyle.DropDown) {\n            this.SelectionLength = 0;\n        }\n        base.OnResize(e);\n    }\n}	0
23868684	23861868	C# Reflection: Obtain a list of references to a specific instance?	Object.ReferenceEquals(this, obj2);	0
1123731	1123718	Format XML String to Print Friendly XML String	public static String PrintXML(String XML)\n{\nString Result = "";\n\nMemoryStream mStream = new MemoryStream();\nXmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);\nXmlDocument document   = new XmlDocument();\n\ntry\n{\n// Load the XmlDocument with the XML.\ndocument.LoadXml(XML);\n\nwriter.Formatting = Formatting.Indented;\n\n// Write the XML into a formatting XmlTextWriter\ndocument.WriteContentTo(writer);\nwriter.Flush();\nmStream.Flush();\n\n// Have to rewind the MemoryStream in order to read\n// its contents.\nmStream.Position = 0;\n\n// Read MemoryStream contents into a StreamReader.\nStreamReader sReader = new StreamReader(mStream);\n\n// Extract the text from the StreamReader.\nString FormattedXML = sReader.ReadToEnd();\n\nResult = FormattedXML;\n}\ncatch (XmlException)\n{\n}\n\nmStream.Close();\nwriter.Close();\n\nreturn Result;\n}	0
1265170	1265147	Using reflection to set the value of an Int32	// get the type converters we need\nTypeConverter myConverter = TypeDescriptor.GetConverter(typeof(int));\n\n// get the degrees, minutes and seconds value\nint Degrees = (int)myConverter.ConvertFromString(strVal);	0
20369738	20368175	Cancel insert Command Operation if connection timeouts MySQL	MySqlTransaction trans;\n   trans = connection.BeginTransaction();\n   // Your Code \n   try\n    {\n       //By default, MySQL runs with autocommit mode enabled.\n        cmd.Parameters.Add("@image", MySqlDbType.Blob).Value = bytes;            \n        cmd.CommandText = "INSERT INTO `FileStorage` SET `File` = "+@image"";\n        cmd.executeNonQuery();      \n        trans.Commit();\n    }\n     catch(Exception e)\n      {\n         try\n         {\n            myTrans.Rollback();\n         }\n       catch (MySqlException ex)\n          {\n            if (trans.Connection != null)\n            {\n              //("An exception of type " + ex.GetType() +" was encountered while attempting to roll back the transaction.");\n            }\n           }\n        }	0
25846660	25844492	MongodbCursor , how to iterate through Huge collection?	cursor.SetFlags(QueryFlags.NoCursorTimeout);\nusing (var enumerator = cursor.GetEnumerator())\n{\n    while (enumerator.MoveNext())\n    {\n        var item = enumerator.Current;\n        // logic\n\n        if (shouldPause)\n        {\n            Thread.Sleep(1000);\n        }\n    }\n}	0
10221326	10220797	Regex replace substring from string	public string stripify(string text, List<string> words)\n    {\n        var stripped = words.Aggregate(text, (input, word) => input.Replace(word, ""));\n        return stripped.Replace('.', ' ');\n    }	0
19298153	19298047	Is there any method in which you can pass a mathematical statement and it will give you a result?	Expression e = new Expression("2 + 3 * 5");   \nDebug.Assert(17 == e.Evaluate());	0
12092663	12092332	How can you cast T to a class to match a "where T : class" constraint?	public class Test\n{\n  public T GetInstance<T>() where T : class\n  {\n    return (T)GetInstance(typeof(T));\n  }\n\n  private object GetInstance(Type type) \n  {\n     return Activator.CreateInstance(type);\n  }\n\n  public T GetEvenMoreGenericInstance<T>()\n  {\n     if( !typeof( T ).IsValueType )\n     {\n        return (T)GetInstance(typeof(T));\n     }\n     return default( T );\n  }\n}	0
3197323	3197151	How to match and capture a regular expression in C#	Match m = Regex.Match( "something some stuff in the middle someotherthing", \n         "something (.*) someotherthing" );\nif ( m.Success )\n   Console.WriteLine( "groups={0}, entire match={1}, first group={2}", \n                      m.Groups.Count, m.Groups[0].Value, \n                      m.Groups[1].Value );	0
10903396	10903327	binary formatter to string	var memoryStream = new MemoryStream();\nusing(memoryStream)\n{\n    formatter.Serialize(memoryStream, list);\n}\nHiddenField1.Value = Convert.ToBase64String(memoryStream.ToArray());	0
25238075	25205032	Creating a dynamic table using form1 with textbox1 textbox2 textbox3, Need some suggestion	SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + "\\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");\n con.Open();\n SqlCommand cmd = new SqlCommand();\n cmd.Connection = con;\n cmd.CommandType = CommandType.Text;\n cmd.CommandText = "SELECT * FROM INFORMATION_SCHEMA.TABLES";\n SqlDataAdapter dbAdapter = new SqlDataAdapter(cmd);\n DataTable dtRecords = new DataTable();\n dbAdapter.Fill(dtRecords);\n comboBox1.DataSource = dtRecords;\n comboBox1.DisplayMember = "TABLE_NAME";\n con.Close();	0
5896861	5896823	Concat columns adding data in datatable	newColumn.Expression = "Convert(Day , 'System.String') + Convert(Month , 'System.String') + Convert(Year, 'System.String')";	0
3668335	3668112	How to easily find screen location of form Location in multi-monitor environment?	/// <summary>Returns the location of the form relative to the top-left corner\n/// of the screen that contains the top-left corner of the form, or null if the\n/// top-left corner of the form is off-screen.</summary>\npublic Point? GetLocationWithinScreen(Form form)\n{\n    foreach (Screen screen in Screen.AllScreens)\n        if (screen.Bounds.Contains(form.Location))\n            return new Point(form.Location.X - screen.Bounds.Left,\n                             form.Location.Y - screen.Bounds.Top);\n\n    return null;\n}	0
1193437	1193424	How do I install a C# Windows service without creating an installer?	installutil YourWinService.exe	0
33116889	33116834	Is it necessary to dispose SqlConnection as well as SqlCommand?	SqlCommand.Dispose()	0
6437864	6437788	Dropdownlist to enter and select date	String date = DateTime.Now.ToString("dd-MMM-yyyy"); // Format your Date string\nDropDownList1.Items.Add(new ListItem(date, date)); // Adding formatted date into Dropdownlist	0
19399646	19398261	loading content of XML file	private static string ExtractIngredients(XElement v)\n{\n    var ingredients = v\n        .Elements("ingrediens")\n        .Select(e => \n            e.DescendantNodes().OfType<XText>().First().Value +\n            ": " +\n            e.Element("mangd").Value);\n\n    return String.Join("\r\n", ingredients);\n}	0
11903873	11898614	Using SaveFileDialog with ClosedXML	var saveFileDialog = new SaveFileDialog\n                             {\n                                 Filter = "Excel files|*.xlsx", \n                                 Title = "Save an Excel File"\n                             };\n\n    saveFileDialog.ShowDialog();\n\n    if (!String.IsNullOrWhiteSpace(saveFileDialog.FileName))\n        workbook.SaveAs(saveFileDialog.FileName);	0
15171405	15170903	Hidden ListBox will appear while Typing Words in RichTextBox	private List<string> autoCompleteList = new List<string>();\n\npublic Form1()\n{\n    autoCompleteList.Add("Items for the autocomplete");\n}\n...\n\nprivate void textBox1_TextChanged(object sender, System.EventArgs e)\n{\n    listBox1.Items.Clear();\n    if (textBox1.Text.Length == 0)\n    {\n        hideAutoCompleteMenu();\n        return;\n    }\n\n    Point cursorPt = Cursor.Position;\n    listBox1.Location = PointToClient(cursorPt);\n\n    foreach (String s in autoCompleteList)\n    {\n        if (s.StartsWith(textBox1.Text))\n        {\n            listBox1.Items.Add(s);\n            listBox1.Visible = true;\n        }\n\n    }\n }\n\nprivate void hideAutoCompleteMenu()\n{\n    listBox1.Visible = false;\n}\n\nprivate void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n    textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString();\n    hideAutoCompleteMenu();\n}	0
19959517	19862871	DataGrid with a checkbox column to allow the user to select rows?	private void CheckBox_Checked(object sender, RoutedEventArgs e)\n    {\n        CheckBox chc = sender as CheckBox;\n        try\n        {\n            foreach (var item in mEmployees)\n            {\n                if (item.Dep.ToString() == chc.Content.ToString())\n                {\n                    item.IsSelected = true;\n                    MessageBox.Show(chc.Content.ToString());\n\n                }\n\n            }\n        }\n        catch\n        {\n        }\n }	0
4619154	4443367	Retrieving the MethodInfo of of the correct overload of a generic method	public static MethodInfo GetMethod<T>(\n    Expression<Action<T>> methodSelector)\n{\n    var body = (MethodCallExpression)methodSelector.Body;\n    return body.Method;      \n}\n\n[TestMethod]\npublic void Test1()\n{\n    var expectedMethod = typeof(Foo)\n        .GetMethod("Bar", new Type[] { typeof(Func<>) });\n\n    var actualMethod = \n        GetMethod<Foo>(foo => foo.Bar<object>((Func<object>)null)\n        .GetGenericMethodDefinition();\n\n    Assert.AreEqual(expectedMethod, actualMethod);\n}	0
2908092	2907827	Width of dynamic created Label in runtime on C#	SizeF size = myLabel.CreateGraphics().MeasureString(myLabel.Text, myLabel.Font);	0
4969104	4968720	How to get complex enum value string representation	var result = string.Join(",",\n                 Enum.GetValues(typeof(SomeType))\n                     .Cast<SomeType>()\n                     .Where(v => complexType.HasFlag(v)));	0
5415088	5414563	How to create comparer class with reflection?	Pseudocode\npublic static int Compare(object x, object y)\n{\n    ... handle if one or both are null\n    ... handle if both same type \n    if (IsArray(x))\n    {\n        ?? equal also means same order??\n        for i=0 to min(x.lenght, y.length)-1 {\n            int subcompareresult = Compare(x[i], y[i])\n            if subcompareresult != 0\n                return subcompareresult // difference found\n        }\n\n        // elements compared so far are same\n        ... handle different length\n    } else if IsClass(x)\n                foreach subproperty in x.Properties\n        int subcompareresult = Compare(x[subproperty ], y[subproperty ])\n        if subcompareresult != 0\n            return subcompareresult // difference found\n            else\n        ... handle value compare	0
7388506	7353938	How to get extents in a drafting view in Revit	FilteredElementCollector allElementsInView = new FilteredElementCollector(document, document.ActiveView.Id);\nIList elementsInView = (IList)allElementsInView.ToElements();\n\nList<ElementId> idsOfElementsToMirror = new List<ElementId>();\n\ndouble drawingMaxX = double.MinValue;\ndouble drawingMinX = double.MaxValue;\n\nforeach (Element element in elementsInView)\n{\n  if (element.Category == null)\n    continue;\n\n  if (ElementTransformUtils.CanMirrorElement(document, element.Id) == false)\n    continue;\n\n  BoundingBoxXYZ elementBoundingBox = element.get_BoundingBox(document.ActiveView.Id);\n\n  if(elementBoundingBox == null)\n    continue;\n\n  if (elementBoundingBox.Max.X > drawingMaxX)\n    drawingMaxX = elementBoundingBox.Max.X;\n\n  if (elementBoundingBox.Min.X < drawingMinX)\n    drawingMinX = elementBoundingBox.Min.X;\n\n  idsOfElementsToMirror.Add(element.Id);\n}\n\ndouble xMidpoint = ((drawingMaxX - drawingMinX) / 2.0) + drawingMinX;	0
12050911	12050747	Length of an Access Binary field	OleDbCommand cmd = new OleDbCommand("select data from db", mycon);\nSystem.Data.OleDb.OleDbDataReader dr;\ndr = cmd.ExecuteReader();\ndr.Read();\ntemp = (byte[])dr["data"];\nint len = temp.Length;	0
21075617	21075580	Deleting same elements in array C#	var distinctArray = myArray.Distinct().ToArray();	0
15483822	15483747	Getting a substring 2 characters at a time	List<string> mList = new List<string>();\n\nfor (int i = 0; i < _CAUSE.Length; i = i + 2)\n{\n    mList.Add(_CAUSE.Substring(i, 2));\n}\n\nreturn mList;	0
23926041	23608108	Events not taking correct namespace for EntityDataSource control	using EntityDataSource = Microsoft.AspNet.EntityDataSource.EntityDataSource;\nusing EntityDataSourceSelectingEventArgs = Microsoft.AspNet.EntityDataSource.EntityDataSourceSelectingEventArgs;\nusing EntityDataSourceChangingEventArgs = Microsoft.AspNet.EntityDataSource.EntityDataSourceChangingEventArgs;\nusing EntityDataSourceChangedEventArgs = Microsoft.AspNet.EntityDataSource.EntityDataSourceChangedEventArgs;\nusing EntityDataSourceContextCreatingEventArgs = Microsoft.AspNet.EntityDataSource.EntityDataSourceContextCreatingEventArgs;	0
6221814	6221787	How to turn off a monitor using VB.NET code	Public WM_SYSCOMMAND As Integer = &H112\nPublic SC_MONITORPOWER As Integer = &Hf170\n\n<DllImport("user32.dll")> _\nPrivate Shared Function SendMessage(hWnd As Integer, hMsg As Integer, wParam As Integer, lParam As Integer) As Integer\nEnd Function\n\nPrivate Sub button1_Click(sender As Object, e As System.EventArgs)\n    SendMessage(Me.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2)\nEnd Sub	0
7246648	7246523	Error while doing a lexicographical sort of a word	.OrderBy(s => s.Length < 1 ? s : s.Remove(1, Math.Min(Math.Max(0,s.Length - 3), 3)));	0
12866212	12865445	Custom String Parsing	string[] originals = new[]\n    {\n        "Jacob+Delta+2012_Bio",\n        "Diana_Bio_smith_2011",\n        "Bio_5+10+2012+Steve00"\n    };\n\nstring[] ignoreMe = new[]\n    {\n        "Bio", "bio", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_", "+"\n    };\n\nIEnumerable<string[]> results = originals.Select(\n    o => o.Split(ignoreMe, StringSplitOptions.RemoveEmptyEntries));	0
23297318	23297234	Changing the name of a field displayed in a DataGridView?	this.data_view.Columns["id_num"].HeaderText = "ID";	0
3661837	3661815	Datetime format in C#	lbltakeeffectdate.Text = dtmNextPayment.ToString("MM/dd/yyyy")	0
28680413	28653421	Setting Alpha Channel on new Unity UI	temp.a = (currentThirst % 255) / 255.0f;	0
8573917	8572512	Update in sql Ce in window phone 7	[Column(UpdateCheck = UpdateCheck.Never)]	0
17594727	17594549	Show Percentage of work accomplished on Progress bar	/// <summary>\n/// Start a new worker\n/// </summary>\nvoid StartWork()\n{\n    var backgroundWorker = new BackgroundWorker();\n\n    //make sure the worker reports on progress\n    backgroundWorker.WorkerReportsProgress = true;\n\n    //we want to get notified when progress has changed\n    backgroundWorker.ProgressChanged+=backgroundWorker_ProgressChanged;\n\n    //here we do the work\n    backgroundWorker.DoWork += backgroundWorker_DoWork;\n\n}\n\nvoid backgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n{\n    //do long work\n}\n\nProgressBar _progressBar = new ProgressBar();\nvoid backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n    //when we are notified about progress changed, update the progressbar\n    _progressBar.Value = e.ProgressPercentage;\n}	0
24108435	24107319	Linq create an array of Dto objects, with an array in it	var items = new List<DboPageCountry>(); //list of DboPageCountries\n\nvar items2 = from x in items.GroupBy(x => x.DboThemePage) \n             select new DtoKeywordCountryCode { Keyword = x.First().DboThemePage.Keyword, CountryCodes = x.Select(c => c.DboCountry.CountryCode).ToArray() };	0
7259108	7259067	How to convert string to uniqueidentifier?	new Guid("string to convert");	0
3633530	3633514	Iterating over returned data	List<string> items = testMethod(data);\nforeach (string item in items)\n{\n    // ...\n}	0
11689035	11688863	Can I use LINQ To Search an inner list in a List of Lists?	List<Zone> listOfZone = zoneSet.ZoneList.Where(e => e.Any(p => p.MemberWWPN == inputWWPN)).ToList();	0
19826379	19825875	C# Entity Framework many-to-many relationship with quantity	public class Television\n    {\n        public int TelevisionID { get; set; }\n        public int ModelID { get; set; }\n\n        public virtual ICollection<Room> Rooms { get; set; }\n    }\n\n    public class Room\n    {\n        public int RoomID { get; set; }\n        //\n        public virtual ICollection<Television> Televisions { get; set; }\n\n    }\n\n    public class TelevisionRoom\n    {\n        public int TelevisionID { get; set; }\n        public int RoomID { get; set; }\n        public int Quantity { get; set; }\n    }\n\n    public class Model\n    {\n        public int ModelID { get; set; }\n        public string ModelName { get; set; }\n    }	0
28413410	28412676	How to distinguish Navigation Properties from regular ones when using GetProperties?	using (var db=new YourContext())\n {\n   var workspace = ((IObjectContextAdapter)db).ObjectContext.MetadataWorkspace;\n   var itemCollection = (ObjectItemCollection)(workspace.GetItemCollection(DataSpace.OSpace));\n   var entityType = itemCollection.OfType<EntityType>().Single(e => itemCollection.GetClrType(e) == typeof(YourEntity));\n   foreach (var navigationProperty in entityType.NavigationProperties)\n   {\n      Console.WriteLine(navigationProperty.Name);\n   }\n   foreach (var property in entityType.Properties)\n   {\n      Console.WriteLine(property.Name);\n   }\n}	0
1935906	1935904	Is there any way to make a static method mandatory to be implemented in the implemented/derived class?	Repository<T>	0
9588715	9559255	Determine number of rows per minute using Entity ObjectContext and with For loop iteration	DateTime zeroDate = new DateTime(2008, 1, 1, 0, 0, 0);\n        this.ObjectContext.WMLSLogs.GroupBy(s => SqlFunctions.DateAdd("mi", ((SqlFunctions.DateDiff("mi", zeroDate, s.Date))), zeroDate)).\n            Select(g => new\n                {\n                    Date = g.Key,\n                    count = g.Count()\n                }).OrderBy(x => x.Date);	0
30875670	30870335	Use wildcards in ado.net sybase parameter	using (SAConnection con = new SAConnection(DBConnStr))\n{\n    con.Open();\n    try\n    {\n        string sql = "select * from names where name like ?";\n        SACommand cmd = new SACommand(sql, con);\n        cmd.Parameters.Add("@p1","Se%");\n        SADataReader rdr = cmd.ExecuteReader();\n        while (rdr.Read())\n        {\n            Console.WriteLine(rdr["name"].ToString());\n        }\n        rdr.Close();\n    }\n    finally\n    {\n        con.Close();\n    }\n}\nConsole.ReadLine();	0
6050277	6043025	Facebook C# SDK: Traverse The JsonArray To Get The Value of Tracking Data	requestInfo["data"][0]["data"]	0
29171497	29170399	Deserialize XML Document Fails Using XmlSerializer	XmlSerializer x = new XmlSerializer(typeof(List<FolderPath>));	0
13565333	13429622	Change Resource file at runtime in different class library project in same solution in WPF	var rDictionary = new ResourceDictionary();\n  rDictionary.Source = new Uri(string.Format("pack://application:,,,/Ferhad.Wpf.SystemStyles;component/OStyles.xaml"), UriKind.Absolute);\n  this.Resources.MergedDictionaries.Add(rDictionary);	0
17895296	17895258	Async Controller behaviour	public void NewsAsync(string city)\n{\n    AsyncManager.OutstandingOperations.Increment();\n    NewsService newsService = new NewsService();\n    newsService.GetHeadlinesCompleted += (sender, args) =>\n    {\n        AsyncManager.Parameters["headlines"] = args.Result;\n        AsyncManager.OutstandingOperations.Decrement();\n    };\n    newsService.GetHeadlinesAsync(city);\n}\n\npublic ActionResult NewsCompleted(object headlines)\n{\n    return View("News", new ViewStringModel\n    {\n        NewsHeadlines = (string[])headlines\n    });\n}	0
25806025	25667483	Setting BitmapMetadata.Title in service running on Windows Server 2003 Web Edition throws NotSupportedException	BitmapMetadata jpgData = new BitmapMetadata("jpg");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/object name", "Test Title");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/keywords", "Test Tag");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/date created", "20090512");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/time created", "115300-0800");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/caption", "Test Comment");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/by-line", "Test Author");\njpgData.SetQuery("/app13/irb/8bimiptc/iptc/copyright notice", "Copyright 2009");	0
31381914	31381835	Regex not matching moustache-style placeholders within an HTML template	Groups["key"].Value	0
22473268	22285663	Creating a custom Delegating handler	public class ContentValidationHandler : DelegatingHandler\n{\n\n    private static log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n\n    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n        CancellationToken cancellationToken)\n    {\n\n        var response = await base.SendAsync(request, cancellationToken);\n\n\n        Stream strea = new MemoryStream();\n        await request.Content.CopyToAsync(strea);\n        strea.Position = 0;\n        StreamReader reader = new StreamReader(strea);\n        String res = reader.ReadToEnd();\n        Log.Info("request content: " + res);\n\n        return response;\n\n\n\n\n\n\n\n        //\n    }\n\n\n\n\n\n}	0
9412757	9412715	C# string splitting elegant solution	var result = Regex.Matches(input, @"(\w+)=(\w+)").Cast<Match>()\n    .Select(m => new \n        { \n            Property = m.Groups[1].Value, \n            Value = m.Groups[2].Value \n        });	0
6667739	6667209	Post Multiple Events within One HttpRequest to Google Analytics	google-analytics.com/__utm.gif	0
30148566	30148555	Remove Duplicates from dropdown using Linq	var distinctItems = authorCollection.GroupBy(x => x.Id).Select(y => y.First());	0
15377857	15377770	How to write a new number to the end of a text File	String filePath = @"C:\Mental.txt";\n\nFile.AppendAllText(filePath , "content");	0
26303194	26303094	Use "FindResource" from other classes of the application	using System.Windows;\n\nApplication.Current.FindResource("YOUR-RESOURCE-KEY");	0
3294625	3294099	WPF DataBinding Validation being ignored	Mode="TwoWay"	0
25903609	24879038	Windows phone 8: open facebook specific post in app from code	Launcher.LaunchUriAsync(new Uri("fb:specificpost?id=POST_ID"));	0
6571076	6570691	How To print Space Between Control Creation at Run Time?	this.Controls.Add(new LiteralControl("&nbsp;"));	0
5279312	5278966	Event to update a control in the right moment	popUp.FormClosed += (o, e) => DataReload();	0
7153122	7152063	trying to sorting the data grid view column shows error message	dataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;	0
13251726	13251554	Parse date string .net	DateTimeOffset.ParseExact(date.Substring(0, 33) // remove time zone\n                              .Remove(25,3)     // remove "GMT" before offset\n                              ,"ddd MMM dd yyyy HH:mm:ss zzz"\n                              ,System.Globalization.CultureInfo.InvariantCulture);	0
5103068	5102997	How to download HTML pages with the correct encoding using C#?	using (WebClient client = new WebClient())\nusing (var read = client.OpenRead("http://your.com"))\n{\n    HtmlDocument doc = new HtmlDocument();\n    doc.Load(read, true); // true = get encoding from byte order masks\n    // process doc, extract title\n    var title = doc.DocumentNode.SelectSingleNode("//title").InnerText;\n}	0
20841550	20841487	Read integer from XML with LINQ	xmlDoc.Elements()\n      .Select(x => int.Parse(x.Element("money").Value))\n      .Sum();	0
29811731	29811704	Trying to convert object to integer to show as a percentage, but it only shows 0	public decimal GetPercentage(object value)\n{\n    var percentage = Convert.ToDecimal(value) * 100;\n\n    return percentage;\n}	0
11923713	11923497	How can I compare items in a jagged array?	for (int i = 0; i < arr.Length - 1); i++) {\n    for (int j = 0; j < arr[i].Length && j < arr[i + 1].Length; j++) {\n        arrResult[i][j] = arr[i][j] + arr[i + 1][j];\n    } \n}	0
15097217	15096352	Remove "X" button at the end of a TextBox	input[type=text]::-ms-clear\n{\n            border: 2px solid orange\n}	0
8888407	8888290	Need some tips on how to create a paging mechanism on a single table using Repository pattern	public IQueryable<News> FindNews(int? page)\n{\n    IQueryable<News> news = db.News.OrderByDescending(n => n.PublishDate);\n\n    if (page != null)\n       news = news.Skip(page.Value * 5);\n\n    return news.Take(5);\n}	0
3128541	3127142	How to connect to a SQL Server Compact from a .NET application?	SqlCeCommand command = new SqlCeCommand("SELECT * FROM Names", connection);	0
1808179	1808174	Is there a way in Visual C# to get the maximum of two number?	int max = Math.Max(a,b);	0
20144240	20143878	Display time in seconds by using timer	DateTime startTime;\n    private void button1_Click(object sender, EventArgs e)\n    {\n        timer.Tick += (s, ev) => { label1.Text = String.Format("{0:00}", (DateTime.Now - startTime).Seconds); };\n        startTime = DateTime.Now;\n        timer.Interval = 100;       // every 1/10 of a second\n        timer.Start();\n    }	0
8510359	8510316	How to bound a list by enum	private List<SelectListItem> MapDegree()\n        {\n            var enumerationValues = Enum.GetValues(typeof(Degree));\n            var enumerationNames = Enum.GetNames(typeof(Degree));\n            List<List1> lists = new List<List1>();\n            foreach (var value in Enum.GetValues(typeof(Degree)))\n            {\n                List1 selectList = new List1\n                {\n                    Text = value.ToString(),\n                    Value = ((int)value).ToString(),\n\n                };\n                lists.Add(selectList);\n            }\n            return lists;\n        }	0
13289746	13289692	Remove an item from a LINQ collection	var leadtasktype = _context.LeadTypeTaskTypes.Where(l => l.LeadTypeId == item.Value && l.LeadTypeId != 21);	0
19672242	19671768	How can I Include Multiples Tables in my linq to entities eager loading using mvc4 C#	var cliente = context.Clientes\n       .Include(e => e.Enderecos)\n       .Include(e1 => e1.Enderecos.Select(cep => cep.CEP.Cidade.UF))\n       .SingleOrDefault();	0
32309397	32309110	How to find the first positive integer number that is not in the list	int[] arrayWithNumbers = new int[] {0, 1, 3, 4, 9, 10, 15};\n\nint i = 0;\nwhile (arrayWithNumbers.Contains(i)) //check if number already exists in array\n{\n    i++; //increment by 1\n}\n\nConsole.WriteLine(i);	0
23363620	23362849	Delete row from grid and database with Kendo UI and MVC	this.Context.SaveChanges()	0
16125144	16124461	Detecting garbage in a Unit Test	using (var dumper = new InProcessMemoryDumper(false,false))\n  { \n     var statOld = dumper.GetMemoryStatistics();\n\n     // allocaton code here\n     var diff = dumper.GetMemoryStatisticsDiff(statOld);\n\n    foreach (var diffinst in diff.Where(d => d.InstanceCountDiff > 1))\n    {\n        Console.WriteLine("Added {0} {1}", diffinst.TypeName, diffinst.InstanceCountDiff);\n    }\n  }	0
17825721	17822882	How to configure Conditional Mapping in AutoMapper?	Mapper.CreateMap<Source, Target>()\n        .ForMember(dest => dest.Value, \n                   opt => opt.MapFrom\n                   (src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2));	0
927157	924279	How to double buffer a RichTextBox in c#?	int pos = myTextBox.SelectionStart;\nRichTextBox buffer = new RichTextBox();\nbuffer.Rtf = myRichTextBox.Rtf;\n\n//Do whatever you wanna do in buffer\n\n\nmyTextBox.Rtf = buffer.Rtf;\nmyTextBox.SelectionStart = pos;\nmyTextBox.SelectionLength = 0;	0
12342082	12342032	displaying an array	CArray nums = new CArray(50); //since 50 is the length of your array	0
2771892	2771670	Calculate pixels within a polygon	public bool inPoly(int x, int y)\n    {\n        int i, j = hull.Count - 1;\n        var oddNodes = false;\n\n        for (i = 0; i < hull.Count; i++)\n        {\n            if (hull[i].Y < y && hull[j].Y >= y\n                || hull[j].Y < y && hull[i].Y >= y)\n            {\n                var delta = (hull[j].X - hull[i].X);\n                if (delta == 0)\n                {\n                    if (0 < x) oddNodes = !oddNodes;\n                }\n                else if (hull[i].X + (y - hull[i].X) / delta * delta < x)\n                {\n                    oddNodes = !oddNodes;\n                }\n\n            }\n            j = i;\n        }\n        return oddNodes;\n    }	0
30219881	30214109	IModelBinder: access the raw data of the request	public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n{\n    if (controllerContext.HttpContext.Request.ContentType.ToLowerInvariant().StartsWith("my special content type"))\n    {\n        var body = GetBody(controllerContext.HttpContext.Request);\n        var model = MyCustomConverter.Deserialize(body, bindingContext.ModelType);\n        return model;\n    }\n}\n\nprivate static string GetBody(HttpRequestBase request)\n{\n    var inputStream = request.InputStream;\n    inputStream.Position = 0;\n\n    using (var reader = new StreamReader(inputStream))\n    {\n        var body = reader.ReadToEnd();\n        return body;\n    }\n}	0
27813459	27813261	How to limit Picturebox movement to screen	private void OutsideBusinessHoursTimer_Tick(object sender, EventArgs e)\n    {\n        int x = r.Next(0, this.ClientRectangle.Width - this.pbLifebrokerInactive.Width);\n        int y = r.Next(0, this.ClientRectangle.Height - this.pbLifebrokerInactive.Height);\n        this.pbLifebrokerInactive.Location = new Point(x, y);\n    }	0
27305465	27305437	Set equivalent in C#	HashSet<T>	0
10508242	10508183	how to ensure a List<String> contains each string in a sequence exactly once	private bool ContainsAllCandidatesOnce(List<String> list1)\n{\n    return candidates.All(c => list1.Count(v => v == c) == 1);\n}\n\nprivate IEnumerable<String> MissingCandidates(List<String> list1)\n{\n    return candidates.Where(c => list1.Count(v => v == c) != 1);\n}	0
19516375	19516195	In Rhino Mocks, how to stub a method using a null argument?	IAccessRightsManager stubAccessRights = new \n    MockRepository.GenerateStub<IAccessRightsManager>(); \n\nstubAccessRights.Stub(ar => ar.canUserRead((IUser)null, confidentialDocument))\n    .Return(false);  \nstubAccessRights.Stub(ar => ar.canUserRead((IUser)null, nonConfidentialDocument))\n    .Return(true);	0
21181734	21177679	multiple remove checkedlistbox items	Global.answers.RemoveAt(i);	0
11037377	11037296	What is an efficient way to match items in a large dictionary of phrases within a string (paragraph)	string input = "I wonder if man utd, aston villa andthe toon army will exist in this string";\n List<string> matches = dic.\n                           .Where(kvp => input.Contains(kvp.Key))\n                           .Select(kvp => kvp.Value)\n                           .ToList();	0
29397578	29353263	Exception - A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'	public class PortfolioMap : BaseEntityTypeConfiguration<Portfolio>\n{\n    public PortfolioMap()\n    {\n        //Primary key\n        HasKey(t => t.Id);\n\n        //Map schema name and table\n        ToTable("Portfolio", SchemaConstants.Component);\n\n        //Set property mapping explicit if needed\n        Property(t => t.Name).HasMaxLength(150).IsRequired();\n\n        //Foreign key relationships\n         HasRequired(t => t.Projects).WithRequiredPrincipal(); <<--- Line causing the error\n\n        //Other constraints\n    }\n}	0
5760455	5760327	send complex object using socket in C# but also simple text string	[Serializable]\npublic class EncapsulatedData{\n    public EncapsulatedData(){}\n    public string Message{ get; set; }\n    public ISerializable Object{ get; set; }\n}	0
15890001	15889392	How to programmatically switch between SlideMaster and Default view?	Sub Switch_To_Slidemaster()\n\nDim curSLD As Long\n    curSLD = ActiveWindow.View.Slide.SlideIndex\n\n'switch to SlideMaster\nApplication.Windows(1).ViewType = ppViewSlideMaster\n\n\n'return to default\nApplication.Windows(1).ViewType = ppViewNormal\n\n'set slide\nActiveWindow.Presentation.Slides(curSLD).Select\n\nEnd Sub	0
14810105	14809905	Removing descrepancies from my list	var list = new List<String> { "Hello", "World", "HELLO", "beautiful", "WORLD" };\n\nvar l = list.Distinct(StringComparer.CurrentCultureIgnoreCase).ToList();\n\nConsole.WriteLine(l);	0
7222405	7222356	How do I select the target framework of a CodeDom compiler using C#?	var providerOptions = new Dictionary<string, string>();\nproviderOptions.Add("CompilerVersion", "v3.5");\nvar compiler = new CSharpCodeProvider(providerOptions);\n...	0
34117341	34114988	How to Install socket.io for .NET in MonoDevelop	Unable to resolve dependency 'newtonsoft.json (>= 4.0.8)	0
27177577	27177412	What's the correct way to use Effort with Entity Framework 6?	var existingFrames = from frame in repository.CcdFrames\n                     where frame.Id == newFrame.Id\n                     select frame;	0
2102097	2099767	Wpf TreeView's ScrollViewer Adjustment	TreeViewItem item = new TreeViewItem() {  Header = "test" };\ntreeView1.Items.Add(item);\nitem.BringIntoView();	0
7692694	7692682	Noob Concern: Converting Dec to String C#	tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString();	0
20596577	20596264	Break a line in a TextBox (TextArea) from a Model variable	var model = new NewPostModel() { Text = "First line\r\n\r\nan\\[x \\cdot y\\]" };	0
15799736	15799681	Join two lists with one to many relationship	public class Helper\n{\n    public List<Alpha> Join(List<Alpha> alphaList, List<Bravo> bravoList)\n    {\n        return alphaList.Select(a => new Alpha() { key1 = a.key1, list = bravoList.Where(b => b.key1 == a.key1).ToList() }).ToList();\n    }\n}\n\npublic class Alpha\n{\n    public int key1 { get; set; }\n\n    public List<Bravo> list { get; set; }\n}\n\npublic class Bravo\n{\n    public int key1 { get; set; }\n\n    public string someProp { get; set; }\n}	0
29064724	29064641	Parse JSON Array in C# with Json.NET	"title":"??? "???????..	0
25609764	25607227	Return List of MAX Value after group QueryOver Nhibernate	// group by PortfolioId\n// HAVING for outer 'p.ID'\nvar subquery = QueryOver.Of(() => q)\n    .SelectList(list => list\n        .SelectGroup(() => q.PortfolioId)\n        .SelectMax(() => q.Id)\n    )\n    .Where(Restrictions.EqProperty( // HAVING\n        Projections.Property(() => p.Id),\n        Projections.Max(() => q.Id)))\n     ;\n\n// now select the list of p.Id, prefiltered by above subquery\nvar filter = QueryOver.Of(() => p)\n    .WithSubquery.WhereExists(subquery)\n    .Select(Projections.Property(() => p.Id));\n\n// finally the result as a set of q entities\n// ready for paging\nvar result = session.QueryOver(() => q)\n    .WithSubquery\n        .WhereProperty(() => q.Id)\n        .In(filter)\n    // .Skip(0) -- paging could be used\n    // .Take(25)\n    .List()\n    ;	0
27426695	27426633	Group By Count Objects	x.Count()	0
3421080	3420187	How do I add permissions to an OU using C#?	DirectoryEntry rootEntry = new DirectoryEntry("LDAP://OU=Test OU,DC=test,DC=com");\nDirectorySearcher dsFindOUs = new DirectorySearcher(rootEntry);\n\ndsFindOUs.Filter = "(objectClass=organizationalUnit)";\ndsFindOUs.SearchScope = SearchScope.Subtree;\nSearchResult oResults = dsFindOUs.FindOne();\nDirectoryEntry myOU = oResults.GetDirectoryEntry();\n\nSystem.Security.Principal.IdentityReference newOwner = new System.Security.Principal.NTAccount("YourDomain", "YourUserName").Translate(typeof(System.Security.Principal.SecurityIdentifier));\nActiveDirectoryAccessRule newRule = new ActiveDirectoryAccessRule(newOwner, ActiveDirectoryRights.GenericAll, System.Security.AccessControl.AccessControlType.Allow);\nmyOU.ObjectSecurity.SetAccessRule(newRule);	0
30413140	30412872	Convert Int Value To Bit Value For Grid Display	CONVERT(bit,ColumnValue)	0
30814783	30813883	Reading a remote text file line by line and comparing with inputbox entry	...\n bool valid = false;\n\n using (WebClient client = new WebClient())\n {\n     using (Stream stream = client.OpenRead("http://haha.com/access.txt"))\n     {\n         using (StreamReader reader = new StreamReader(stream))\n         {\n             string line;\n\n             while ((line = reader.ReadLine()) != null)\n             {\n                 if (line.Equals(input))\n                 {\n                     valid = true;\n                     break;\n                 }\n             }\n         }\n     }\n }\n\n if (valid)\n {\n     // password is correct\n     ...\n }\n else\n {\n    MessageBox.Show("This software has been deactivated because of wrong pass", "YOUR ACCESS HAS BEEN LIMITED");\n    appexit();\n }\n ...	0
12749116	12748535	WPF ComboBox culture not being applied to values	return someDouble.ToString(culture);	0
10903980	10903915	gridview button	protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) \n{ \n\n    if (e.CommandName == "edit") \n    { \n        int index = Convert.ToInt32(e.CommandArgument);\n        string fileID = ((GridView)sender).DataKeys[index]["fileID"].ToString(); \n        Response.Redirect("irMain.aspx?@filename=" + fileID); \n    } \n}	0
22950343	22950162	Linq with multiple tables	var viewsById = db.ArticleViews\n    .Where(av => av.ViewCreated >= startDateTime && av.ViewCreated < endDateTime)\n    .GroupBy(av => av.ArticleId)\n    .Select(g => new { ArticleId = g.Key, Count = g.Count() })\n\nvar highestCount = viewsById.Max(v => v.Count);\n\nvar topArticles = viewsById.Where(a => a.Count == highestCount);\n\nvar topArticle = topArticles.First();\n\nvar message = String.Format("Article id: {0}, views: {1}", \n                         topArticle.ArticleId, topArticle.Count);	0
2866699	2866640	Drawing a 2D line on a canvas	int border = 20; //How much of the canvas you *don't* want to use\nint graphHeight = Canvas.Height - border;\nint maxValue = DataList.GetMaxValue();\nint minValue = DataList.GetMinValue();\n\ndouble multiplier = graphHeight / (maxValue - minValue);\n\nforeach(int value in DataList)\n{\n    int distanceFromBottom = value - minValue;\n    double proportionalValue = distanceFromBottom * multiplier;\n    double newValue = proportionalValue  + (border/2) // move it up to the middle of the canvas\n}	0
11000027	10435704	Retrieving`HasMany` Entities in a single query - Fluent-NHibernate	.SetFetchMode("Tags", FetchMode.Eager)\n.SetResultTransformer(Transformers.DistinctRootEntity)	0
10206056	10204040	How to allow file upload for Anonymous user in SharePoint	eevatedWeb.AllowUnsafeUpdates = true;   \nstring targetUrl = SPUrlUtility.CombineUrl(eevatedWeb.ServerRelativeUrl, tempLibrary);                                \nSPFolder target = eevatedWeb.GetFolder(targetUrl);                                   \nSPFileCollection files = target.Files;\nSPFile file = target.Files.Add(fileName, fileStream, overwrite);                                \neevatedWeb.AllowUnsafeUpdates = false;	0
17022541	17022506	Visual Studio doesn't open command window for console application	Console.ReadKey();	0
7031450	7031435	Cast method of LINQ behaves unexpected	Enumerable.Cast	0
14360782	14360713	Cannot login to SQL Server using NHibernate, but with Management Studio or sqlcmd it works	"Data Source=SERVER1\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabase"	0
16376996	16376687	How to convert stream reader response to a class object?	//m is the string based xml representation of your object. Make sure there's something there\nif (!string.IsNullOrWhiteSpace(m))\n    {\n        //Make a new XMLSerializer for the type of object being created\n        var ser = new XmlSerializer(typeof(yourtype));\n\n        //Deserialize and cast to your type of object\n        var obj = (yourtype)ser.Deserialize(new StringReader(m));\n\n        return obj ;\n    }	0
18382600	18382447	Iinq equivalent to stored procedure	from r in context.View\n   where (ValOne == null || r.ColOne.Equals(ValOne)) && \n      (ValTwo == null ||r.ColTwo.Equals(ValTwo)) && \n      (Start == null || (r.ODate >= Start && r.ODate <= End)) \n   select r	0
23940842	23940774	Select one of two different methods in a method chain in C#	var f = product.Status == ProductStatusEnum.Presale\n   ? new Func<Sku, User, CustomPrice>(pricingHelper.GetUserPresalePricing)\n   : pricingHelper.GetUserProductPricing;\n\ndecimal userPrice = f(user, price).UserCustomPrice;	0
6518008	6517741	What is the best way to send xml data to a web service rather than using CDATA?	var xml = new XmlDocument();\nvar node = xml.CreateElement("root");\nnode.InnerText = "<content>Anything</content>";\n\nvar xmlString = node.InnerXml; /// &lt;content&gt;Anything&lt;/content&gt;	0
19585721	19585497	Entity Filter child without include	public class MenuDto\n{\n    public int MenuId { get; set; }\n    public string Name { get; set; }\n    public string Url { get; set; }\n    public List<MenuDto> SubMenus  { get; set; }\n}\n_model.Menus.Where(m => m.Active)\n            .Select(p => new MenuDto\n            {\n                MenuId = p.idField,\n                Name = p.NameField,\n                Url = p.UrlField,\n                SubMenus = p.SubMenus.Where(sb => sb.Active)\n                    .Select(y => new MenuDto\n                    {\n                        MenuId = y.idField,\n                        Name = y.NameField,\n                        Url = y.UrlField,\n                        SubMenuItem = y.SubMenuItems.Where(sbi => sbi.Active)\n                          .Select(z => new MenuDto\n                    {\n                        MenuId = z.idField,\n                        Name = z.NameField,\n                        Url = z.UrlField\n                    })\n                    })\n            }).ToList();	0
5798805	5798524	How to manipulate datagridview columns when using DataSource?	// Sets the ToolTip text for cells in the Rating column.\nvoid dataGridView1_CellFormatting(object sender, \n    DataGridViewCellFormattingEventArgs e)\n    {\n    if ( (e.ColumnIndex == this.dataGridView1.Columns["Rating"].Index)\n        && e.Value != null )\n    {\n        DataGridViewCell cell = \n            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];\n        if (e.Value.Equals("*"))\n        {                \n            cell.ToolTipText = "very bad"; // you can get the value from your other cells using the above technique with .value instead of .index\n        }\n        else if (e.Value.Equals("**"))\n        {\n            cell.ToolTipText = "bad";\n        }\n        else if (e.Value.Equals("***"))\n        {\n            cell.ToolTipText = "good";\n        }\n        else if (e.Value.Equals("****"))\n        {\n            cell.ToolTipText = "very good";\n        }\n    }\n}	0
3466809	3466760	Master-Detail via ComboBox in C#?	protected void Orders_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var orderId = int.Parse(Orders.SelectedValue);\n    // Get items for this order from data store\n    var items = ...\n    // Bind with items grid\n    OrderItems.DataSource = items;\n    OrderItems.DataBind();\n}	0
11380937	11380870	Finding closest block range	Math.Ceiling((float)value / 0x1000) * 0x1000;	0
20511017	20510437	Use C# HttpWebRequest to send json to web service	var webAddr = "http://Domain/VBRService.asmx/callJson";\n        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);\n        httpWebRequest.ContentType = "application/json; charset=utf-8";\n        httpWebRequest.Method = "POST";            \n\n        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))\n        {\n            string json = "{\"x\":\"true\"}";\n\n            streamWriter.Write(json);\n            streamWriter.Flush();\n        }\n\n        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();\n        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))\n        {\n            var result = streamReader.ReadToEnd();\n            return result;\n        }	0
8617704	8617689	Choose file with the most current Date Modified from directory	new DirectoryInfo(path)\n    .EnumerateFiles("*.bak")\n    .OrderByDescending(f => f.LastWriteTime)\n    .Last()	0
27997906	27997224	How to select records for the date range in sqlite	string qry = "select * from [table]";\n        DataTable vt = new DataTable();\n        SQLiteDataAdapter da = new SQLiteDataAdapter(q, connectionString);\n        da.Fill(vt);\n\n        foreach (DataRow row in vt.Rows)\n        {\n            if (Convert.ToDateTime(row["DATE"].ToString()) >= Convert.ToDateTime(FromDate)\n                && Convert.ToDateTime(row["DATE"].ToString()) <= Convert.ToDateTime(ToDate))\n            {\n                continue;\n            }\n            else\n            {\n                row.Delete();\n            }\n        }\n\n        vt.AcceptChanges();	0
14752997	14749242	VLC ActiveX in a local webpage with WPF WebBrowser control	Stream docStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("WpfApplication12.index.html");\nwb.NavigateToStream(docStream);	0
6860461	6860352	Add an X509 certificate to a store in code	var store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser);	0
4285130	4284781	GridView retrieve Data in every Row	e.Row.Cells[x].Text	0
25198001	25197781	how to draw line and Calculate Distance on google map of distance traveled of list longnitude and latitude from	public static double GetTotalDistance(IEnumerable<GeoCoordinate> coordinates)\n{\n    double result = 0;\n\n    if (coordinates.Count() > 1)\n    {\n        GeoCoordinate previous = coordinates.First();\n\n        foreach (var current in coordinates)\n        {\n            result += previous.GetDistanceTo(current);\n        }\n    }\n\n    return result;\n}	0
20832192	20831774	How to Reset A Map Polyline	Map.MapElements.Remove(_line);	0
12121258	12117335	How to hold position of listboxitem when adding/removing items?	void loadItems(){\n//load\n    var t = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };\n            t.Tick += delegate {\n              _ScrollViewer.UpdateLayout();\n              SomethingLoading = false;\n              listmy.ScrollIntoView(listmy.Items[listmy.Items.Count - 10]);\n            };\n            t.Start();\n}	0
25654318	25633574	NHibernate with sqlite throws a GenericADOException "constraint failed\r\nFOREIGN KEY constraint failed" trying to save	public class PermissionMap : ClassMap<Permission>\n{\n    public PermissionMap()\n    {\n        Table("PERMISSION");\n        Id(x => x.Id).Column("PERMISSION_ID");\n        Map(x => x.Name);\n        HasMany(x => x.UserPermissions).LazyLoad();  // Removed this line to fix issue\n    }\n}	0
1389190	1389018	C# Custom Events assigning to different delegates based on parameters	SomePropertyThatIsntARealEvent[new string[] {"event1", "event2"}] += someDelegate\n// or even\nSomePropertyThatIsntARealEvent["event1"]["event2"] += someDelegate	0
5291227	5291173	Searching for data structure with fast search and small size	var mySet = new HashSet<T>(new []{ 1, 2, 3, 3, 4, 5, 4, 5 });\nSerialize(mySet.ToArray());	0
15690508	15690165	C# ClickOnce install folder - how windows generate the folder names	string exeFolder = System.Reflection.Assembly.GetExecutingAssembly().Location;	0
29826778	29826474	XML - Write a single node	XmlElement x = document.SelectSingleNode("Game/Client-Version") as XmlElement;\nx.InnerText = "texttowrite";	0
20711825	20711787	Catch XML with custom Classes	public void createXML<T>(string fileName, string route)\n    {\n        System.Xml.Serialization.XmlSerializer serializador = new System.Xml.Serialization.XmlSerializer(typeof(T));\n        System.IO.FileStream stream = new System.IO.FileStream(@""+ route + fileName + ".xml", System.IO.FileMode.Create);\n    }	0
6354873	6354813	Comparing values of arrays in C#	var equal = responses.SequenceEqual(Person.PersonDetails.Select(PD => PD.correct);	0
11596108	11382361	Send a mouse left click to a sopcast mute button, in c#	using 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 automouse\n{\n    public partial class Form1 : Form\n    {\n        public const int WM_LBUTTONDOWN = 0x0201;\n        public const int WM_LBUTTONUP = 0x0202;\n\n        [DllImport("user32.dll", CharSet = CharSet.Auto)]\n        private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            SendMessage(button2.Handle, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);\n            SendMessage(button2.Handle, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);\n        }\n\n        private void button2_Click(object sender, EventArgs e)\n        {\n            MessageBox.Show("Button2 clicked!");\n        }\n    }\n}	0
15572002	15569977	Excel Worksheet with C#	Chart2.Parent.Parent.Cells(1).Activate	0
19739713	19739690	How to get URL path in C#	String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;\nString parentDirectory = originalPath.Substring(0, originalPath.LastIndexOf("/");	0
10347538	10347455	string.Format with string.Join	string.Concat(Enumerable.Range(1,10).Select(i => string.Format("[{0}]", i)))	0
30724762	30724648	Cant find code to insert into AS access database using c#	Test.SelectCommand = "INSERT INTO DB1 (message) + values ('" + txtpost.Text + "')";	0
21931139	21931103	DataAnnotation to compare two properties	public string EmailAddress {get; set;}\n\n[CompareAttribute("EmailAddress", ErrorMessage = "Emails mismatch")]\npublic string VerifiedEmailAddress { get; set; }	0
22921532	22921437	How do I output everything my program prints to a file?	MyProject.exe > file.txt	0
14695604	14695357	Show tooltip on textbox entry	private void textBox1_Enter(object sender, EventArgs e)\n    {\n        TextBox TB = (TextBox)sender;\n        int VisibleTime = 1000;  //in milliseconds\n\n        ToolTip tt = new ToolTip();\n        tt.Show("Test ToolTip",TB,0,0,VisibleTime);\n    }	0
28939735	28938477	NodaTime usage for datetimepicker	var appointment = LocalDateTime.FromDateTime(dateTimePicker1.Value).Date;\nvar retirement = LocalDateTime.FromDateTime(dateTimePicker2.Value).Date;\nvar difference = Period.Between(appointment, retirement);\nMessageBox.Show(string.Format("{0} years {1} months {2} days",\n   difference.Years, difference.Months, difference.Days));	0
5259330	5258966	Set display name to value of another property - MVC3 Data Annotations	DisplayNameValue { get; }	0
1667932	1667813	dynamically create lambdas expressions + linq + OrderByDescending	MemberInfo member = typeof(AClassWithANameProperty).GetProperty("Name");\n\n//Create 'x' parameter expression\nParameterExpression xParameter = Expression.Parameter(typeof(object), "x");\n\n//Create body expression\nExpression body = Expression.MakeMemberAccess(targetParameter, member);\n\n//Create and compile lambda\nvar lambda = Expression.Lambda<LateBoundGetMemberValue>(\n    Expression.Convert(body, typeof(string)),\n    targetParameter\n);\nreturn lambda.Compile();	0
8084752	8073947	set file permissions for c:\program files\company\app\file for all users	file.SetAccessControl(access);	0
3752506	3752451	Enter key pressed event handler	TextBox tb = new TextBox();\ntb.KeyDown += new KeyEventHandler(tb_KeyDown);\n\nstatic void tb_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Enter)\n    {\n        //enter key is down\n    }\n}	0
7493235	7493146	Linq to Sql result in combobox async	//Set the ComboBox Properties on the Form, not in the worker.\n   comboBoxUsers.ValueMember = "UserId";\n   comboBoxUsers.DisplayMember = "Name";\n\n   BackgroundWorker = new BackgroundWorker();\n   worker.DoWork += Worker_DoWork;\n   worker.WorkerReportsProgress = true;\n   worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);\n\n   private void Worker_DoWork(object sender, DoWorkEventArgs e)\n   {\n        BackgrounderWorker worker = (BackgroundWorker)sender;\n\n        //Query the database\n        //Instantiate a custom-class to contain the results\n        IList<Users> users = userRepository.SelectAll();\n        QueryResults results = new QueryResults(users);\n        worker.ReportProgress(0, results);\n   }\n\n   //Back In the UI Layer\n   private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n   {\n       var result = (QueryResult)e.UserState;\n       comboBoxUsers.DataSource = result.Users;\n   }	0
24558494	24557976	StructureMap - How do I use multiple objects inheriting from the same interface	For<IFoo>().Add<Bar>().Named("bar");\nFor<IFoo>().Add<Baz>().Named("baz");\n\nFor<A>()\n    .Use<A>()\n    .Ctor<IFoo>()\n    .Named("bar");\n\nFor<B>()\n    .Use<B>()\n    .Ctor<IFoo>()\n    .Named("baz");	0
25871104	25871063	Set var based on switch	IEnumerable<IReport> orig = Session["Report"] as IEnumerable<IReport>;\nif (orig != null)\n{\n  var sort = from o in orig\n             where o.ID == ReportID\n             select o;\n\n  Session["SortedReport"] = sort.ToList();\n}	0
33130682	33128777	Deserialise XML into class with attributes	public class MainData\n{\n    public List<Channel> listofChannels { get; set; }\n}\n\n[XmlType("item")]\npublic class Channel\n{\n    [XmlAttribute("type")]\n    public string Type;\n\n    [XmlElement("channelName")]\n    public string Name;\n\n    [XmlElement("channelPort")]\n    public int Port;\n\n    [XmlElement("ServerDetail")]\n    public ChannelDetail details;\n}\n\npublic class ChannelDetail\n{\n    [XmlAttribute("ipaddress")]\n    public string IPAddress { get; set; }\n\n    [XmlAttribute("port")]\n    public int Port { get; set; }\n}	0
2112070	2099092	Using Ninject IOC to replace a factory	Bind<ITokenHandler>().To<YourConcreteTypeHere>().Named(tokenName);	0
3156261	3156221	Storing application settings in Silverlight	private void StoreSetting(string key, string value)\n{\n   IsolatedStorageSettings.ApplicationSettings[key] = value;\n}\n\nprivate string GetSetting(string key)\n{\n   return IsolatedStorageSettings.ApplicationSettings[key];\n}	0
17236040	17234531	How to find out if method was called in a bool value in Rhino mocks?	bool logMethodWasCalled = false;\nmockLogger\n    .Stub(x => x.Log(Arg<string>.Is.Equal(null))\n    .Do(new Action<string>(_ => logMethodWasCalled = true));\n\n// Run test...\n\nreturn logMethodWasCalled;	0
32887459	32886866	How to add items to a DropDownList without reloading page	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        load brands here...\n    }\n}	0
6974192	6974159	Search XML node value without knowing parent node	//price[. > 35.00]	0
17267760	17266048	Constructor chaining passing computed values for parameters	class Frob\n{\n    public Frob (Uri uri)\n    {\n\n    }\n\n    public Frob(string path, string query)\n        : this(TidyUpUri(path, query))\n    {\n\n    }\n\n    private static Uri TidyUpUri(string path, string query)\n    {\n        var uri = new Uri(string.Concat(path, query));\n\n        // etc.\n\n        return uri;\n    }\n}	0
20052097	20051475	Function that finds 3D position of a point given its position in stereo images	Z = (b * f) / (Xleft - Xright)	0
12970702	12970643	How can I use regex to match a character (') when not following a specific character (?)?	(?<!\?)'	0
33000835	32998788	Not all my x axis label are showing when there is a lot of data C# Wnforms	chart1.ChartAreas[0].AxisX.LabelStyle.Angle = -90;\n chart1.ChartAreas[0].AxisX.LabelStyle.Interval = 1;	0
25116818	25116183	Open windows store in a windows phone silverlight app	MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();\nmarketplaceDetailTask.ContentIdentifier = "INSERT_APP_ID";\nmarketplaceDetailTask.ContentType = MarketplaceContentType.Applications;\nmarketplaceDetailTask.Show();	0
106101	106033	How do I call a .NET assembly from C/C++?	[Guid("123565C4-C5FA-4512-A560-1D47F9FDFA20")]\npublic interface IConfig\n{\n    [DispId(1)]\n    string Destination{ get; }\n\n    [DispId(2)]\n    void Unserialize();\n\n    [DispId(3)]\n    void Serialize();\n}\n\n[ComVisible(true)]\n[Guid("12AC8095-BD27-4de8-A30B-991940666927")]\n[ClassInterface(ClassInterfaceType.None)]\npublic sealed class Config : IConfig\n{\n    public Config()\n    {\n    }\n\n    public string Destination\n    {\n    get { return ""; }\n    }\n\n    public void Serialize()\n    {\n    }\n\n    public void Unserialize()\n    {\n    }\n}	0
12598900	12456924	Connection string for addin in Visual Studio 2012	public CurrentlyActiveWndConnectionInfo CurrentlyActiveWndConnectionInfo\n{\n    get\n    {\n        STrace.Params("ScriptFactory", "ScriptFactory.CurrentlyActiveWndConnectionInfo", string.Empty, null);\n        if (ServiceCache.VSMonitorSelection == null)\n        {\n            STrace.LogExThrow();\n            throw new InvalidOperationException();\n        }\n        return this.GetCurrentlyActiveWndConnectionInfo(ServiceCache.VSMonitorSelection);\n    }\n}	0
10574582	10574300	Load DLL Assemblies from file in C# to custom AppDomain	using System;\nusing System.Reflection;\n\nclass AppDomain2\n{\n    public static void Main()\n    {\n        Console.WriteLine("Creating new AppDomain.");\n        AppDomain domain = AppDomain.CreateDomain("MyDomain", null);\n\n        Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);\n        Console.WriteLine("child domain: " + domain.FriendlyName);\n        AppDomain.Unload(domain);\n        try\n        {\n            Console.WriteLine();\n            Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);\n            // The following statement creates an exception because the domain no longer exists.\n            Console.WriteLine("child domain: " + domain.FriendlyName);\n        }\n        catch (AppDomainUnloadedException e)\n        {\n            Console.WriteLine(e.GetType().FullName);\n            Console.WriteLine("The appdomain MyDomain does not exist.");\n        }\n    }\n}	0
1084157	1084098	Creating a tab control with a dynamic number of tabs in Visual Studio C#	TabControl tabControl = new TabControl();\ntabControl.Dock = DockStyle.Fill;\n\nforeach (Char c in lastNameList)\n{\n    TabPage tabPage = new TabPage();\n    tabPage.Text = c.ToString();\n\n    DataGrid grid = new DataGrid();\n\n    grid.Dock = DockStyle.Fill;\n    grid.DataSource = dataForTheCurrentLoop;\n\n    tabPage.Controls.Add(grid);\n    tabControl.Controls.Add(tabPage);\n}\n\nthis.Controls.Add(tabControl);	0
7795719	7795700	Copy a list of objects to another typed list in one line of code	var type2objects = type1objects.Select(o => new MyType2(o)).ToList();	0
32627446	32549699	How to update magento stock directly in MySQL	//set available in stock = 1; out of stock = 0;\n                "update cataloginventory_stock_status set stock_status = '1' " +\n                "where cataloginventory_stock_status.product_id = " +\n                "(select catalog_product_entity.entity_id from catalog_product_entity where sku ='" + sku + "');"	0
9728452	9728351	BindingSource event wont allow me to get index of current dgv row	private void tripsBindingSource_PositionChanged(object sender, EventArgs e)\n{ \n    // something like\n    if(dgvTripGrid.CurrentRow != null)\n    {\n        //get selected row index\n        int index = this.dgvTripGrid.CurrentRow.Index;\n        //get pk of selected row using index\n        string cellValue = dgvTripGrid["pkTrips", index].Value.ToString();\n        //change pk string to int\n        int pKey = Int32.Parse(cellValue);\n        ...\n    }\n}	0
4534241	4534222	Convert DataGridViewRow to String	string.Join("\t", cell.Select(c => c.ToString()).ToArray())	0
5288463	5288447	Accessing a VC++ Dll from C# (compact framework)	extern "C"	0
4836080	4835979	Grouping Logical Operators (Multiple Sets of Conditions) in a do {} while () loop?	public void Test()\n{\n    var separators = new[] { ' ', '\t', '\r', '\x00a0', '\x0085', '?', ',', '.', '!' };\n\n    var input = "Test  string, news112!  news \n next, line! error in error word";          \n    var tokens = new Queue<string>(input.Split(separators, StringSplitOptions.RemoveEmptyEntries));\n\n    string currentWord = null;\n\n    while (tokens.Any())\n    {\n        currentWord = tokens.Dequeue();\n        if (currentWord.All(c => Char.IsLetterOrDigit(c)))\n        {\n            if (!CheckSpell(currentWord))\n            {\n                break;\n            }\n        }\n    }\n}\n\npublic bool CheckSpell(string word)\n{\n    return word != null && word.Length > 0 && word[0] != 'e';\n}	0
8794130	8794105	Multiply two numbers	string.Format("{0:0.##}", number)	0
20152321	20150283	WPF Bing Maps Control slow performance	private void init()   \n{\n\n    Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()\n    {\n        // Background Thread\n        Map map = new Map();\n        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n            new Action(() =>\n            {\n                // Back to the UI Thread\n                var provider = new ApplicationIdCredentialsProvider(MyCredentials);\n                mapElementOnUI = new Map();\n                mapElementOnUI.CredentialsProvider = provider;\n                mapPanel.Children.Add(mapElementOnUI);\n                updateMapLocations();\n            }));\n    }\n    ));\n    thread.SetApartmentState(ApartmentState.STA);\n    thread.Start();\n}	0
8026861	8026509	Smooth character rotation	newdir.y=-135; // depends on which axis you want to turn...\n\ntransform.rotation = Quaternion.Lerp(transform.rotation, newdir, Time.deltaTime * smoothSpeed);	0
27598085	27598054	Reading different data types in a single line in C#	string line = file.ReadLine;\nstring[] elements = line.Split(' ');\n\nint a = Convert.ToInt32(elements[0]);\nint b = Convert.ToInt32(elements[1]);\ndouble c = Convert.ToDouble(elements[2]);	0
10580941	10580461	Performance: While-loop	List<int> data = Enumerable.Range(0, 10000000).ToList();\nint j = -1;\n\n\n\n// Method 1   \n\nwhile (++j < data.Count)\n{\n    // do something\n}\n\nint j = 0;\ndo\n    {\n        //anything\n    } while (++j<data.count);	0
27418251	27418053	uploading to azure storage from memorystream returning an empty file	//...\n\n  //Move the pointer to the start of stream.\n  ms.Position = 0;\n\n  image.Save(ms, imgCodec, encoderParams);\n  //HERE !!!\n  ms.Position = 0;\n\n  blockBlob.UploadFromStream(ms);\n}	0
9036328	9035873	CreationDate of a file is changing according to the context	using (StreamWriter sw = File.CreateText(LocalFile)) { }\n            File.SetCreationTime(LocalFile,DateTime.Now);\n            Thread.Sleep(50);\n\n            using (StreamWriter sw = File.CreateText(UncFile)) { }\n            File.SetCreationTime(UncFile, DateTime.Now);\n            Thread.Sleep(50);\n\n            DateTime UncDate = File.GetCreationTime(UncFile);\n            DateTime OldLocalDate = File.GetCreationTime(LocalFile);\n\n            Assert.IsTrue(UncDate > OldLocalDate);	0
23217867	23216793	Tree structure with a nested observablecollection of children	public class MyModel : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    public int id { get {...} set { OnPropertyChanged("id"); } }\n    public string Name { get {...} set { OnPropertyChanged("Name"); } }\n    public MyModel Parent { get {...} set { OnPropertyChanged("Parent"); } }\n    public ModelCollection Descendants { get {...} set { OnPropertyChanged("Descendants"); } }\n    public ModelCollection Children { get {...} set { OnPropertyChanged("Children"); } }\n\n    private void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = this.PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n}	0
12601160	12588347	SQL Server 2008 R2 Reporting Services - Get Subscription + Schedule Link	var subscriptions = service.ListSubscriptions(report.Path);\n\nforeach (var subscription in subscriptions)\n{\n    ExtensionSettings settings;\n    string description, status, eventType, matchData;\n    ActiveState state;\n    ParameterValue[] parameters;\n    string user = service.GetSubscriptionProperties(subscription.SubscriptionID, out settings,\n                                                    out description, out state, out status, out eventType,\n                                                    out matchData, out parameters);\n    if (matchData == scheduleId)\n    {\n        // Do what I need to do\n    }\n}	0
22307416	22307275	C# adding dynamic variables in loop	const int minimumVote = 1;\nconst int maximumVote = 10;\nint jurorCount;\n\ndo\n{\n    Console.Write("Enter the number of jurors: ");\n} while (!Int32.TryParse(Console.ReadLine(), out jurorCount) || jurorCount < 0);\n\nvar votes = new List<int>();\n\nfor (int i = 0; i < jurorCount; i++)\n{\n    int vote;\n\n    do\n    {\n        Console.Write("Enter juror #{0}'s vote ({1}-{2}): ", i + 1, minimumVote, maximumVote);\n    } while (!Int32.TryParse(Console.ReadLine(), out vote) || vote < minimumVote || vote > maximumVote);\n\n    votes.Add(vote);\n}	0
6701014	6700942	How do I modify a column of fields in a WebControls.GridView?	System.Web.UI.WebControls.GridView() test = new System.Web.UI.WebControls.GridView();\nfor (int i = 0; i < grid.Rows.Count; i++)\n{\n    test.Rows[i].Cells[<yer column index>].Text = "=/"" + test.Rows[i].Cells[<yer column index>].Text + "/"";\n}	0
31247148	31246770	Web API multiple GET action with different query strings	public class UsersController : ApiController\n    {\n\n        // GET api/values/5\n        public string GetUsersByRole(string role)\n        {\n            return "Role: " + role;\n        }\n\n        public string GetUsersByDivision(string division)\n        {\n            return "Division: " + division;\n        }\n    }	0
16811871	16811201	JMS: updating message version / prevent certain message from being queued	mysystem.orders.1_0\nmysystem.orders.1_1	0
13504850	13504797	Iterating through each Enum value needs to be parallelized	public static void TasteAll<Mode>(Action<Mode> Make)\n{\n        foreach (Mode mode in Enum.GetValues(typeof(Mode)))\n        {\n            Mode localMode = mode;\n            Task.Factory.StartNew(() => Make(localMode) );\n            //Make(mode); //<-- Works Fine with normal call\n        }\n    Console.ReadLine();\n}	0
26505120	26505058	How to write in text file from messagebox	System.IO.File.WriteAllText("path", sb1.ToString());	0
22112698	22112624	How to click on a button using WebControl	// Make sure the web browser is on focus\nwebView.Focus();\n// Find and click the button\nwebView.ExecuteJavascript("document.getElementsByName('button.submit')[0].click();");\n// Update the web browser\nWebCore.Update();	0
2861044	2860947	How to reduce size of html rendered from ASP.net?	cscript adsutil.vbs set w3svc/filters/compression/parameters/HcDoDynamicCompression true	0
25325576	25325537	cannot get CPU serial number in C#	string cpuInfo = string.Empty;\n    ManagementClass mc = new ManagementClass("win32_processor");\n    ManagementObjectCollection moc = mc.GetInstances();\n\n    foreach (ManagementObject mo in moc)\n    {\n         cpuInfo = mo.Properties["processorID"].Value.ToString();\n         break;\n    }	0
23867172	23243584	Can i create OwinMiddleware per request instead creating a global object	app.Use((IOwinContext context, Func<Task> next) =>\n        {\n            ILogger logger = {Resolve dependency using Unity};\n            CustomOwinMiddleware middleware = new CustomOwinMiddleware(context,next, logger);\n            return middleware.Invoke();\n        });	0
8453358	6472141	Getting started with Google Adword .net API	AdWordsUser user = new AdWordsUser();\n(user.Config as AdWordsAppConfig).Password = "XXXXX";\n//TODO (Add more configuration settings here.\n\nCampaignService campaignService = (CampaignService) user.GetService(AdWordsService.v201109.CampaignService);\n//TODO (Add your code here to use the service.)	0
18334051	18333908	Use RegEx with IgnoreCase to replace a word but replace using correct found word case	public static string ReplaceAll(string source, string word)\n{\n    string pattern = @"\b" + Regex.Escape(word) + @"\b";\n    var rx = new Regex(pattern, RegexOptions.IgnoreCase);\n    return rx.Replace(source, "<span class='highlight'>$0</span>");\n}	0
19756557	19735773	Parsing custom format to DateTime	var timeStamp = "20131101T210705.282Z";\n   var datetime = timeStamp.Split(new[] { 'T' ,'.'});\n   DateTime dt1;\n\n\n  if (DateTime.TryParseExact(datetime[0],\n                     new string[] { "yyyyMMdd" },\n                    new CultureInfo("en-US"),\n                    DateTimeStyles.None,\n                    out dt1))\n  {\n    Console.WriteLine(dt1.ToShortDateString());\n  }\n\n  DateTime dt2;\n\n\n  if (DateTime.TryParseExact(datetime[1],\n                     new string[] { "ssmmhh" },\n                    new CultureInfo("en-US"),\n                    DateTimeStyles.None,\n                    out dt2))\n  {\n    Console.WriteLine(dt2.ToShortTimeString());\n  }\n\n  Console.WriteLine(dt1.ToShortDateString() + " " + dt2.ToShortTimeString());\n  Console.ReadLine();	0
10206764	10206652	Convert .aspx page to Microsoft Excel Page	Response.End();	0
23900363	23900301	c# creating a instance object of something	var exampleObject = new { Name = "x", PhoneNum = "123456789" };	0
10246213	10246200	Drawing a lot of rectangles in GDI+	FillRectangles(Brush brush, Rectangle[] rects);	0
20789025	20756287	How to make a button appear at the right top of the canvas	//for the screen resolution\n    double screen_resolution_x = double.Parse(HtmlPage.Document.Body.GetProperty\n("clientWidth").ToString());\n    double screen_resolution_y= double.Parse(HtmlPage.Document.Body.GetProperty\n("clientHeight").ToString());\n\n    //to move the botton on the Canvas\n     ((Button)canvas1.FindName("SubmitExperimentBtn")).SetValue\n(Canvas.LeftProperty, screen_reolution_x);\n                ((Button)canvas1.FindName("SubmitExperimentBtn")).SetValue\n(Canvas.TopProperty, screen_reolution_y);	0
13329085	13288647	Build query for IQueryable (EF4) from multiple parameters	public static IQueryable<T> Search<T>(this IQueryable<T> source, List<Expression<Func<T, bool>>> predicates = null)\n            where T : EntityObject\n        {\n            if (predicates == null || predicates.Count == 0)\n                return source;\n            else if (predicates.Count == 1)\n                return source.Where(predicates[0]);\n            else\n            {\n                var query = PredicateBuilder.False<T>();\n                foreach (var predicate in predicates)\n                {\n                    query = query.Or(predicate);\n                }\n\n                return source.AsExpandable().Where(query);\n            }\n        }	0
17477328	17476917	c# HtmlAgilityPack Wrapp taking several images, titles and links Windows Phone	var data = doc.DocumentNode.SelectSingleNode("//div[@class='content']")\n               .Descendants("img")\n               .Select(img => new\n               {\n                   Title = img.Attributes["alt"].Value,\n                   Url = img.Attributes["src"].Value,\n               })\n               .ToList();	0
9096129	9083819	Alt keys and tab don't work in winforms opened from a WPF application	public partial class MyWindow : Window\n{\n    public MyWindow()\n    {\n        InitializeComponent();\n\n        Form winform = new Form();\n        // to embed a winform using windowsFormsHost, you need to explicitly\n        // tell the form it is not the top level control or you will get\n        // a runtime error.\n        winform.TopLevel = false;\n\n        // hide border because it will already have the WPF window border\n        winform.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n        this.windowsFormsHost.Child = winform;\n    }\n\n}	0
1245402	1245210	Generating Comma Separated Values	someStringCollection.Aggregate((first, second) => first + ", " + second);	0
21816130	21815759	Set default global json serializer settings	return Request.CreateResponse(HttpStatusCode.OK, page);	0
17644338	17644119	XPath for complicated documents	//component/section/templateId[@root='3.11']/following-sibling::entry	0
13286862	13285007	How to determine if a point is within an ellipse?	public bool Contains(Ellipse Ellipse, Point location)\n        {\n            Point center = new Point(\n                  Canvas.GetLeft(Ellipse) + (Ellipse.Width / 2),\n                  Canvas.GetTop(Ellipse) + (Ellipse.Height / 2));\n\n            double _xRadius = Ellipse.Width / 2;\n            double _yRadius = Ellipse.Height / 2;\n\n\n            if (_xRadius <= 0.0 || _yRadius <= 0.0)\n                return false;\n            /* This is a more general form of the circle equation\n             *\n             * X^2/a^2 + Y^2/b^2 <= 1\n             */\n\n            Point normalized = new Point(location.X - center.X,\n                                         location.Y - center.Y);\n\n            return ((double)(normalized.X * normalized.X)\n                     / (_xRadius * _xRadius)) + ((double)(normalized.Y * normalized.Y) / (_yRadius * _yRadius))\n                <= 1.0;\n        }	0
4474771	4474670	How to catch the ending resize window?	public MyUserControl()\n{\n    _resizeTimer.Tick += _resizeTimer_Tick;\n}\n\nDispatcherTimer _resizeTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 1500), IsEnabled = false };\n\nprivate void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)\n{\n    _resizeTimer.IsEnabled = true;\n    _resizeTimer.Stop();\n    _resizeTimer.Start();\n}\n\nvoid _resizeTimer_Tick(object sender, EventArgs e)\n{\n    _resizeTimer.IsEnabled = false;    \n\n    //Do end of resize processing\n}	0
3681580	3681552	Reverse case of all alphabetic characters in C# string	string input = "aBc1$";\nstring reversedCase = new string(\n    input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ?\n                      char.ToLower(c) : char.ToUpper(c)) : c).ToArray());	0
13448409	12781059	How to know if the keyboard is active on a text input	GUITHREADINFO lpgui = new GUITHREADINFO();\n    IntPtr fore = GetForegroundWindow();\n    uint tpid = GetWindowThreadProcessId(fore, IntPtr.Zero);\n    lpgui.cbSize = Marshal.SizeOf(lpgui.GetType());\n    bool flag = GetGUIThreadInfo(tpid, out lpgui);\n    WINDOWINFO pwi = new WINDOWINFO();\n    pwi.cbSize = (uint)Marshal.SizeOf(pwi.GetType());\n    GetWindowInfo((IntPtr)lpgui.hwndCaret, ref pwi);\n\n    if (flag)\n    {\n        if (!(lpgui.rcCaret.Location.X == 0 && lpgui.rcCaret.Location.Y == 0))\n        {\n\n\n            //TODO\n\n        }\n    }	0
24953528	24953473	How to get DateTime value from DataRow in C#	DateTime.ParseExact(dr["empDOB"].toString(), "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture)	0
5353239	5353185	Define struct array with values	struct Foo\n{\n   public int Bar { get; private set; }\n   public int Baz { get; private set; }\n\n   public Foo(int bar, int baz) : this() \n   {\n       Bar = bar;\n       Baz = baz;\n   }\n}\n\n...\n\nFoo[] foos = new Foo[] { new Foo(1,2), new Foo(3,4) };	0
11112438	11112212	Cast to Type from Config	if(message.Body != null && message.Body.GetType() == fooType) ...	0
21546649	21545330	DatGridView Header Cell's Background Color	Public Sub VerticalBarHide(ByVal grd As KryptonExtendedGrid, ByVal colname As String(), ByVal e As System.Drawing.Graphics)\n    Dim rectHeader As Rectangle\n    grd.EnableHeadersVisualStyles = False\n    Dim bgColor As Color\n    bgColor = grd.ColumnHeadersDefaultCellStyle.BackColor\n    For Each name As String In colname\n        rectHeader = grd.GetCellDisplayRectangle(grd.Columns(name).Index, -1, True)\n        rectHeader.X = rectHeader.X + rectHeader.Width - 2\n        rectHeader.Y += 1\n        rectHeader.Width = 2 * 2\n        rectHeader.Height -= 2\n        e.FillRectangle(New SolidBrush(bgColor), rectHeader)\n    Next\n\nEnd Sub	0
2837236	2837220	How to perform group by in LINQ and get a Iqueryable or a Custom Class Object?	var data = Goaldata.GroupBy(c => c.GoalId).SelectMany(c => c).ToList();	0
7676828	7673974	Change an Active Directory password	directoryEntry.Invoke("ChangePassword", oldPassword, newPassword); \ndirectoryEntry.Commit();	0
1321689	1312779	ASP.Net - How do I include an embedded JavaScript file from another project?	// Get a ClientScriptManager reference from the Page class.\nClientScriptManager cs = Page.ClientScript;\n\n// Register the client resource with the page.\ncs.RegisterClientScriptResource(rstype, \n     "MyCompany.ControlLibrary.Scripts.MyScript.js");	0
1754309	1754282	How to loop a Console App	While (true)\n{\n   Body\n}	0
14899146	14898834	How to display time from DateTime field in DateTimePicker in C#?	DateTimePicker1.Value = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 5, 30, 0 )	0
7562438	7562355	How can I retrieve a JPEG image codec in F#?	#r "System.Drawing"\nopen System.Drawing.Imaging\nlet jpeg = \n    System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders() \n    |> Seq.find (fun e -> e.FormatID = ImageFormat.Jpeg.Guid)	0
1085126	1077554	How to add/remove many-to-many relation with entity framework by entity key?	User user = new User {UserId = 20};\ne.AttachTo("Users", user);\nRole role = e.Roles.FirstOrDefault();\nrole.Users.Add(user);\ne.SaveChanges();	0
25448381	25448198	ASP.Net C# - Set and display x axis values in Chart	Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;	0
24164442	24158217	Get Outlook Message (using VSTO, EWS or Redemption) with only the Internet Message ID value	RDOFolder.Items.Find(" ""http://schemas.microsoft.com/mapi/proptag/0x1035001F"" = '<SomeValue>' ")	0
22468437	22467846	Capturing key presses in datagridview cells in c#	class exDataGridView : DataGridView\n{\n    private const int WM_KEYDOWN = 0x100;\n    private const int WM_KEYUP = 0x101;\n    private const int KEYUP = 38;\n    private const int KEYDOWN = 40;\n\n    protected override void WndProc(ref Message m)\n    {\n        switch (m.Msg)\n        {\n            case WM_KEYDOWN:\n                if (m.WParam == (IntPtr)KEYDOWN)\n                {\n                    // Do key down stuff...\n                    return;\n                }\n                else if (m.WParam == (IntPtr)KEYUP)\n                {\n                    // Do key up stuff...\n                    return;\n                }\n                break;\n        }\n\n        base.WndProc(ref m);\n    }\n}	0
25105149	25104916	How to download file in c# with its name?	string uri = "http://yourserveraddress/fileName.txt";\nstring fileName = System.IO.Path.GetFileName(uri);\nWebClient client = new WebClient();\nclient.DownloadFile(uri, fileName);	0
16304065	16303871	Sql data access methods oracle	using(OracleConnection conn = new OracleConnection())\n{\n    using(DbTransaction transaction = conn.BeginTransaction())\n    {\n        try\n        {\n            // .... create a command \n            cmd1 = new OracleCommand({sql to get a value});\n            cmd1.Transaction = transaction;\n            cmd1.ExecuteScalar();\n\n            // .... create another command \n            cmd1 = new OracleCommand({sql to update a value});\n            cmd2.Transaction = transaction;\n            cmd2.ExecuteNonQuery();\n\n            transaction.Commit();  \n        }\n        catch (Exception err)\n        {\n            transaction.Rollback();\n            throw err;   // or just throw; to preserve the deeper stack trace\n        }\n    }\n}	0
20864464	20864365	How to change unicode code to char	string result = System.Net.WebUtility.HtmlDecode(System.Text.Encoding.UTF8.GetString(response));	0
116061	116050	Location of My Pictures	Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);	0
1134709	1134678	Getting results from a regular expressions in c#	Regex r = new Regex("([^=;]*)=([^;]*)");\n\nMatchCollection mc = r.Matches("Data Source=server;Initial Database=myDB;foo=bar;");\n\nforeach (Match m in mc)\n{\n    Console.WriteLine(m.Groups[0]);\n    Console.WriteLine(m.Groups[1]);\n    Console.WriteLine(m.Groups[2]);\n}	0
12781456	12781406	Change value in DataGridView directly	dataGridView1.Rows[RowNumber].Cells[CC.Index].Value = newValue;	0
17523180	17523101	Stream is empty from ZipFile	Position = 0;	0
29977551	29976752	Create excel graph with epplus	ExcelChart chart = chartSheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.ColumnClustered);\n            chart.Title.Text = "Category Chart";\n            chart.SetPosition(1, 0, 3, 0);\n            chart.SetSize(800, 300);\n            var ser1 = (ExcelChartSerie)(chart.Series.Add(workSheet.Cells["B4:B6"],\n                workSheet.Cells["A4:A6"]));\n            ser1.Header = "Category";	0
20827984	20827642	Read Multiple Specific Number of Lines in a Text File	using (StreamReader reader = File.OpenText("some file name"))\n{\n    string line;\n    while ((line = reader.ReadLine()) != null)\n    {\n        if (line.StartsWith(textBoxInput.Text, StringComparison.OrdinalIgnoreCase))\n        {\n            // At this point we've already read the keyword and it matches our input\n            StringBuilder description = new StringBuilder(512);\n            string descLine;\n            // Here we start reading description lines after the keyword.\n            // Because every keyword with description is separated by blank line\n            // we continue reading the file until, the last read line is empty \n            // (separator between keywords) or its null (eof)\n            while ((descLine = reader.ReadLine()) != string.Empty && descLine != null)\n            {\n                description.AppendLine(descLine);\n            }\n            textBoxDescription.Text = description.ToString();\n            break;\n        }\n    }\n}	0
3053811	3053807	Random number in a loop	Random r = new Random();\nfor ...\n    string += r.Next(4);	0
2748339	2748331	C# - Check a bool for a value and then flip it	for (int i = 0; i < X; i++)\n    myitem = !(checkedDB = !checkedDB) ? dirtyItem : cleanItem;	0
2651529	2580732	Resharper 4.5: How can I discard an interface and change all references to the only implementation?	"Change all IYourInterfaceName"	0
9164000	9163831	Copy a file with its original permissions	File.Copy(...)\nFileInfo file1 = new FileInfo(@"c:\test.txt");\nFileInfo file2 = new FileInfo(@"c:\test2.txt");\nFileSecurity ac1 = file1.GetAccessControl();\nac1.SetAccessRuleProtection(true, true);\nfile2.SetAccessControl(ac1);	0
7336896	7332840	how to prevent datagridview cell selection at form load	protected override void OnShown(EventArgs e)\n    {\n        if (this.dataGridView1.SelectedCells.Count > 0)\n        {\n            for (int i = 0; i < this.dataGridView1.SelectedCells.Count; i++)\n                this.dataGridView1.SelectedCells[i].Selected = false;\n        }\n    }	0
19377001	19376808	Read and extract from file	using (StreamReader sr = new StreamReader("input"))\n    using (StreamWriter sw = new StreamWriter("output"))\n    {\n        string line = null;\n        while ((line=sr.ReadLine())!=null)\n            sw.WriteLine(line.Split('|')[8]);\n    }	0
26559707	26559691	How to perform functions on keyboard press c#	Control.OnKeyPress	0
33139678	33098267	Making One-Side of One-To-Many Relationship in C# MongoDB know about the Many-Side	DBConnection.database.GetCollection<Log>("Logs").Update(\n                                     Query<Log>.EQ(l => l.Id, UmbrellaLogIdAsObjectId),\n                                     Update<Log>.Push(l => l.logEventsIdList, aLogEvent.Id),\n                                                         new MongoUpdateOptions\n                                                         {\n                                                             WriteConcern = WriteConcern.Acknowledged\n                                                         });	0
14156744	14155642	How to handle a dynamic class differently based on expected return value	class DynamicTest : DynamicObject\n{\n    public DynamicTest(string xyz)\n    {\n        _xyz = xyz;\n    }\n\n    private string _xyz;\n\n    public static implicit operator bool(DynamicTest rhs)\n    {\n        return rhs._xyz != null;\n    }\n\n    public static implicit operator string(DynamicTest rhs)\n    {\n        return rhs._xyz;\n\n    }\n\n    //TODO: what to override to get required behaviour\n}\n\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        dynamic foo = new DynamicTest("test");\n\n\n        if (foo)  // treat foo as boolean\n        { // jump in here when _xyz of foo has a value\n            System.Console.WriteLine((string)foo); //treat foo as string   //Importat: (string)foo to go operatorstring \n        }\n        else\n        { // jump in here when _xyz of foo is null\n            System.Console.WriteLine("No Value In Object");\n        }\n\n\n    }\n}	0
28293663	28264533	Get NEventStore head revision	// Get the latest snapshot\nvar latestSnapshot = _eventStore.Advanced.GetSnapshot(streamId, int.MaxValue);            \n\n// Open the stream from the snapshot if there is one, otherwise open the stream as normal\nusing (var stream = latestSnapshot == null ? \n    _eventStore.OpenStream(streamId) : \n    _eventStore.OpenStream(latestSnapshot, int.MaxValue))\n{\n    // Add events and commit\n    stream.Add(new EventMessage());\n    stream.CommitChanges(Guid.NewGuid());\n\n    // Add a new snapshot (with no payload)\n    _eventStore.Advanced.AddSnapshot(\n        new Snapshot(streamId, stream.StreamRevision, string.Empty));\n}	0
27654983	27653771	Need the details of youtube video in .Net	GET https://www.googleapis.com/youtube/v3/videos?part=snippet&id=k4YRWT_Aldo&key={YOUR_API_KEY}	0
1278354	1278268	How do I pass two namespaces into XSDObjectGen from command line?	XSDObjectGen\XSDObjectGen.exe  AnalyticsDomainModel.xsd /l:cs /d /p /n:dummy /y:"AdaptorAnalyticDomainModel.Primatives|AdaptorAnalyticDomainModel"	0
22279862	22279683	Get the specific dates of moths considering a specific logic	DateTime start = new DateTime(2014, 1, 31);\nfor(int i=0; i<12; i++)\n  Console.WriteLine(start.AddMonths(i));	0
10464563	10463532	Unique Constraint Hack - Entity Framework	Expression<Func<T, bool>>	0
13034218	13033625	Modify a text file on commit for SVN to let my program know of its commit number	svn info	0
9282999	9282988	INSERT INTO two tables at one query	insert into table1 (...) values (...); insert into table2 (...) values (...)	0
1389526	1389513	Converting XML to a DataTable	DataTable myDataTable = new DataTable();\n\nHttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://someplace/somefile.xml");\nmyRequest.Method = "GET";\n\nWebResponse myResponse;\ntry\n{\n   myResponse = myRequest.GetResponse();\n\n   using (Stream responseStream = myResponse.GetResponseStream())\n   { \n      myDataTable.ReadXml(responseStream);\n   }\n}\ncatch\n{ }	0
20715507	20709819	How do I convert to DateTime when the time is a decimal?	DateTime GetDateTime(string date, decimal time)\n{\n    return DateTime.Parse(datetime).AddHours((double)time);\n}	0
15388703	15275468	Access Textbox on Page from User Control in ASP.net	TextBox txt = this.Parent.Parent.FindControl("ContentPlaceHolder2").FindControl("TextBox1") as TextBox;\nif (txt != null) Label1.Text = txt.Text;	0
32398915	32398821	Datatable with Parent and Child to JSON format with Hierarchy	var obj = dt.AsEnumerable()\n            .GroupBy(r => r["Head"])\n            .Select(g => new\n            {\n                Head = g.Key.ToString(),\n                total = g.Sum(x => (int)x["Quantity"]),\n                data = g.Select(r => new\n                {\n                    item = r["Item"].ToString(),\n                    quantity = (int)r["Quantity"]\n                }).ToArray()\n            })\n            .ToList();\n\n\nvar json = JsonConvert.SerializeObject(obj);	0
15765372	15765182	Read file from oracleDB and add/delete/modify data	var lines  = File.ReadLines(@"filename");\nforeach (string line in lines)\n{\n    // Then split each line\n    var str = line.Split('|');  // str contains list of splitted string\n\n    // then save it to db\n   using ( var c = new OracleConnection("connectionString") )\n   {\n      c.Open();\n     // check flag\n     if ( str [2] == 'A' ) \n     {\n      // prepare your sql with splitted array\n      var command = c.CreateCommand();\n      command.Text = "INSERT INTO table(column) values(:col1)";\n      command.Parameters.AddWithValue("col1", str[0])\n      command.ExecuteNonQuery();\n    }\n\n   }\n\n}	0
1440490	1440270	Simple Browser Control in C#	webBrowser.Document.GetElementById("some_id").InnerText = theSearchText;	0
13605220	13604713	Implementing custom exceptions in a Portable Class Library	[ClassInterfaceAttribute(ClassInterfaceType.None)]\n[ComVisibleAttribute(true)]\npublic class Exception	0
919232	919169	C# Generics methods and returning a object of a parameterized type created in the method from xml	class Foo<T> : IFoo {\n\n   public T DoSomething() {\n       ...\n   }\n\n   object IFoo.DoSomething() {\n      return DoSomething();\n   }\n\n}\n\ninterface IFoo {\n   object DoSomething();\n}	0
2692476	2691374	Using Generics to return a literal string or from Dictionary<string, object>	public class WorkContainer:Dictionary<string, object>\n{\n    public T GetKeyValue<T>(string Parameter) \n    {\n        if (Parameter.StartsWith("[? "))\n        {\n            string key = Parameter.Replace("[? ", "").Replace(" ?]", "");\n\n            if (this.ContainsKey(key))\n            {\n                if (typeof(T) == typeof(string) )\n                {\n                    // Special Case for String, especially if the object is a class\n                    // Take the ToString Method not implicit conversion\n                    return (T)Convert.ChangeType(this[key].ToString(), typeof(T));\n                }\n                else\n                {\n                    return (T)this[key];\n                }\n            }\n            else\n            {\n                return default(T);\n            }\n\n        }\n        else\n        {                \n            return (T)Convert.ChangeType(Parameter, typeof(T));\n        }\n    }\n}	0
163717	163611	Changing the DefaultValue of a property on an inherited .net control	public class CustomComboBox : ComboBox\n{\n    public CustomComboBox()\n    {\n        base.DropDownStyle = ComboBoxStyle.DropDownList;\n    }\n\n    [DefaultValue(ComboBoxStyle.DropDownList)]\n    public new ComboBoxStyle DropDownStyle\n    {\n        set { base.DropDownStyle = value; Invalidate(); }\n        get { return base.DropDownStyle;}\n    }\n}	0
12198211	12198131	Looping through a DataTable	foreach (DataColumn col in rightsTable.Columns)\n{\n     foreach (DataRow row in rightsTable.Rows)\n     {\n          Console.WriteLine(row[col.ColumnName].ToString());           \n     }\n}	0
6052967	6052891	C# Set ListBox width so that longest item fits	Graphics graphics = this.createGraphics();\nSizeF mySize = graphics.MeasureString("Ahoy there", this.Font);	0
15492042	15491968	Remove dynamic timer	private void button2_Click(object sender, EventArgs e)\n    {\n      timers[launchTime].Enabled = false;\n      timers.Remove(launchTime);\n    }	0
7769036	7759448	How to give my custom control an overridable default margin?	static OmniBox()\n    {\n        MarginProperty.OverrideMetadata(typeof(OmniBox), new FrameworkPropertyMetadata(new Thickness(0,2,0,2)));\n    }	0
18059608	18059464	Install-Package : Unable to find package 'WebActivator'	PM> Install-Package WebActivator -Version 1.5.3	0
22872058	22868606	Checkbox For using reflection	var param = Expression.Parameter(typeof(T), "p");\n        Expression body = param;\n        body = Expression.MakeMemberAccess(Expression.PropertyOrField(body, pi.Name), pi.PropertyType.GetMember("Value").First());\n        return Expression.Lambda(body, param);	0
9196583	9196442	how to use the return data in json format in c#?	JavaScriptSerializer ser = new JavaScriptSerializer();\nMyClass package = null;   \npackage = ser.Deserialize<MyClass>(item);	0
17172072	17171295	Getting the parameters and values of an attribute	foreach (var reqAttr in (RequiredAttribute[])propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), false))\n{\n    // use reqAttr.ErrorMessage and so on, in here\n}	0
20603979	20559610	How to use Clipper library to enlarge and fill paths	static bool CreateImage(Graphics g, GraphicsPath gp, \n    List<int> offsets, List<Color> colors)\n{\n    const scale = 100;\n    if (colors.Count < offsets.Count) return false;\n\n    //convert GraphicsPath path to Clipper paths ...\n    Clipper.Paths cpaths = GPathToCPaths(gp.Flatten(), scale);\n\n    //setup the ClipperOffset object ...\n    ClipperOffset co = new ClipperOffsets();\n    co.AddPaths(cpaths, JoinType.jtMiter, EndType.etClosedPolygon); \n\n    //now loop through each offset ...\n    foreach(offset in offsets, color in colors)\n    {\n      Clipper.Paths csolution = new Clipper.Paths();\n      co.Execute(csolution, offset);\n      if (csolution.IsEmpty) break; //useful for negative offsets\n      //now convert back to floating point coordinate array ...\n      PointF[] solution = CPathToPointFArray(csolution, scale);\n      DrawMyPaths(Graphics g, solution, color); \n    }\n}	0
5277330	5277291	Implementing interface at run-time: get_Value method not implemented	MethodAttributes getSetAttr = MethodAttributes.Public | \n    MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;	0
14638494	14638462	C# Json Deserialization	var quizObjs = JsonConvert.DeserializeObject<List<QuizObj>>(serializedStringValue);\nstring corr = quizObjs.First().corr;\n// or\nforeach(var quizObj in quizObjs)\n{\n    string corr = quizObj.corr;\n    // etc\n}	0
28245012	28244908	C#: how to get the content of an object as identifier	Color.FromName(setting.background)	0
28211013	27410335	How to access information about the current Spotfire user through the Spotfire API in a custom extension?	Thread.CurrentPrincipal.Identity.Name	0
4043488	4043418	How can I save a foreign key using Entity Framework?	private void CreateNewDepartment()\n    {\n        if ((textBox1.Text != String.Empty) && (comboBox1.SelectedIndex >= 0))\n        {\n            ScansEntities1 db = new ScansEntities1();\n            Person person = new Person() {Id = /*SomeId*/};\n            db.AttachTo("Person", person);\n            Department department = new Department()\n            {\n                Name = textBox1.Text,\n                Person = person\n\n            };\n            db.AddToDepartment(department);\n            db.SaveChanges();\n\n        }\n    }	0
19312499	19269062	Kendo grid, ToDataSouceResult with EF4	public ActionResult ContactsListRead([DataSourceRequest] DataSourceRequest request)\n    {\n        IEnumerable<ContactsModel.ContactsGrid> query = ContactsModel.ContactsService.Get();\n\n        int count = ContactsModel.ContactsService.GetCount();\n\n        query = AjaxCustomBindingExtensions.ApplyOrdersFiltering(query, request.Filters, out count, count);\n\n        query = AjaxCustomBindingExtensions.ApplyOrdersSorting(query, request.Groups, request.Sorts);\n\n        query = AjaxCustomBindingExtensions.ApplyOrdersPaging(query, request.Page, request.PageSize);\n\n        IEnumerable data = AjaxCustomBindingExtensions.ApplyOrdersGrouping(query, request.Groups);\n\n        var result = new DataSourceResult()\n        {\n            Data = data,\n            Total = count\n        };\n\n        return Json(result,JsonRequestBehavior.AllowGet);\n    }	0
7935352	7935044	Programatically creating a content type in Orchard CMS	ContentDefinitionManager.AlterTypeDefinition("BlogPost",\n    cfg => cfg\n           .WithPart("BlogPostPart")\n           .WithPart("CommonPart", p => p\n           .WithSetting("DateEditorSettings.ShowDateEditor", "true"))\n           .WithPart("PublishLaterPart")\n           .WithPart("RoutePart")\n           .WithPart("BodyPart")\n);	0
34483044	34482927	Enity framework with navigation property returning null value?	var images = context.CategoryModel.Include(x=>x.Images).ToList();	0
7707373	7707315	Calling a C++ Function that takes pointers from C#	Private Declare Ansi Sub fPosFirst lib "libraryname" (ByRef aId as Integer, byval aName as StringBuilder, byval aDirectory as StringBuilder)	0
2001040	2000862	How to register a stylesheet on a Master Page within a Web Part	Microsoft.SharePoint.WebControls.CssRegistration.Register("/.../mystyles.css")	0
4500726	4500554	XDocument removing nodes	xml.Descendants().Where(e=>e.Name == "beforeInit" || e.Name == "afterInit").Remove();	0
2393354	2393283	Replace contents WPF grid control by grid in other XAML file	win2.Content = null;\ngridContent.Children.Add(win2.grid2);	0
11006948	11006756	Renaming classes in XML Serialization	[XmlRoot]\npublic class A \n{\n    [XmlElement("NewName")]\n    public List<B> ArrayOfBItems { get;set; }\n\n}	0
28637838	12589777	How to globally cancel post-back events for specific business logic?	Protected Overrides Sub RaisePostBackEvent(sourceControl As IPostBackEventHandler, eventArgument As String)\n    If DoNotProcessPostBack = False Then\n        MyBase.RaisePostBackEvent(sourceControl, eventArgument)\n    End If\nEnd Sub	0
4998383	4998155	Does adding to a method group count as using a variable?	int X;\nint Y;\nvoid SomeMethod()\n{         \n    SomeOtherMethod(this.X);\n}      \nvoid SomeOtherMethod(int x)\n{\n    x += this.Y;\n}	0
2786972	2786928	(C#) download embedded flash from a given URL	Path.Combine	0
26819241	26819144	how to capture user_type asp.net	SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConString"].ConnectionString);\n    con.Open();\n    SqlCommand cmd = new SqlCommand("SELECT User_Type FROM [User] WHERE User_Id =@userid and User_Password=@password", con);\n    cmd.Parameters.AddWithValue("@userid", Convert.ToInt32(txtUserName.Text));\n    cmd.Parameters.AddWithValue("@password", txtPassword.Text);\n    var reader = cmd.ExecuteReader();\n    if (reader.HasRows)\n    {\n    reader.Read();\n    string userType = reader.GetString(0);\n        Session["USER_ID"] = txtUserName.Text;\n        Response.Redirect("Dashboard.aspx");\n    }\n    else\n    {\n        Response.Write("Login Failed");\n    }	0
4716614	4716457	What's the best way to parse XML in the middle of other text	1. Do a string.IndexOf("<Answer>") and then use a substring to chop off the header information.  Then add the substring like this:\nxmlString = "<Answers>" + substringXml + "</Answers>".  Then you could parse the xml as valid XML.\n 2. Use an xmltextreader created with fragment conformance levels and read through the xml.  Only stop on the Answer elements and do processing.\n 3. Add a root element to the document and open it in an XmlDocument and use an xpath expression to read out the Answer elements.	0
8293029	8291391	listview C# sorting by specific column	private void listView1_ColumnClick(object sender, \n                   System.Windows.Forms.ColumnClickEventArgs e)\n{\n   ListView myListView = (ListView)sender;\n\n   // Determine if clicked column is already the column that is being sorted.\n   if ( e.Column == lvwColumnSorter.SortColumn )\n   {\n     // Reverse the current sort direction for this column.\n     if (lvwColumnSorter.Order == SortOrder.Ascending)\n     {\n      lvwColumnSorter.Order = SortOrder.Descending;\n     }\n     else\n     {\n      lvwColumnSorter.Order = SortOrder.Ascending;\n     }\n   }\n   else\n   {\n    // Set the column number that is to be sorted; default to ascending.\n    lvwColumnSorter.SortColumn = e.Column;\n    lvwColumnSorter.Order = SortOrder.Ascending;\n   }\n\n   // Perform the sort with these new sort options.\n   myListView.Sort();\n}	0
12665685	12665661	C# WPF How do i change the content to a random button?	public List<Button> avail = new List<Button>() { button1, button2, button3, button4, button5, button6, button7, button8, button9 };\n\npublic Button Ran()\n{\n    Random b1 = new Random();\n    int index = b1.Next(avail.Count); \n    if (index > 0) {\n        return avail[index];\n    } else {\n        return null;\n    }\n}\n\npublic void buttonchange(Button b)\n{\n    if(b != null) {\n        if (b.Content.ToString() == "") {\n            b.Content = x ? "X" : "O";\n            x = !x;\n        }\n        avail.Remove(b);\n    }\n}	0
2240533	2240176	Store an X509Certificate2 in DB	var cert = new X509Certificate2(filename);\nvar data = cert.RawData;\n\n// save data to database...\n\n// Fetch data from database...\n\ncert = new X509Certificate2(data);	0
25601858	25601751	Issue with namespaces in C#	string pathString = string.Empty;\n\nXmlDocument activeDoc=new XmlDocument();\npublic Form2(string path)\n{\n   pathString = path;\n   InitializeComponent();\n}	0
33117558	33101515	how to set dropdownlist selected value inside a Gridview?	private void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)\n{\n    if ((e.Item is GridDataItem)) {\n        GridDataItem item = e.Item;\n        DropDownList list = (DropDownList)item.FindControl("ddlProgramme");\n        list.SelectedValue = DataBinder.Eval(item.DataItem, "<Datafield_name>").ToString();\n    }\n}	0
2387399	2387381	A single method Accepting 3 arguments or 4 arguments	public static void fillCheckList(string ListType,int RecordNum,CheckBox chkRequired, params TextBox[] txtBoxes)\n{\n   TextBox txtComplete = null;\n   TextBox txtMemo = null;\n   TextBox txtThirdOne = null;\n\n   if(txtBoxes.Length < 1)\n   {\n      throw new Exception("At least the txtComplete-Textbox has to be given");\n   }\n   else\n   {\n      txtComplete = txtBoxes[0];\n\n      if(txtBoxes.Length >= 2)\n          txtMemo = txtBoxes[1];\n\n      if(txtBoxes.Length >= 3)\n          txtThirdOne = txtBoxes[2];\n   }\n\n   // do stuff    \n}	0
401824	401681	How can I get the correct text definition of a generic type using reflection?	public static string GetFriendlyTypeName(Type type) {\n    if (type.IsGenericParameter)\n    {\n        return type.Name;\n    }\n\n    if (!type.IsGenericType)\n    {\n        return type.FullName;\n    }\n\n    var builder = new System.Text.StringBuilder();\n    var name = type.Name;\n    var index = name.IndexOf("`");\n    builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));\n    builder.Append('<');\n    var first = true;\n    foreach (var arg in type.GetGenericArguments())\n    {\n        if (!first)\n        {\n            builder.Append(',');\n        }\n        builder.Append(GetFriendlyTypeName(arg));\n        first = false;\n    }\n    builder.Append('>');\n    return builder.ToString();\n}	0
29107990	29107096	Fill DataGridView from SQLite DB (C#)	private void button1_Click_1(object sender, EventArgs e)\n{\n    conn.Open();\n    SQLiteCommand comm = new SQLiteCommand("Select * From Patients", conn);\n    using (SQLiteDataReader read = comm.ExecuteReader())\n    {\n        while (read.Read())\n        {\n            dataGridView1.Rows.Add(new object[] { \n            read.GetValue(0),  // U can use column index\n            read.GetValue(read.GetOrdinal("PatientName")),  // Or column name like this\n            read.GetValue(read.GetOrdinal("PatientAge")),\n            read.GetValue(read.GetOrdinal("PhoneNumber")) \n            });\n        }\n    }\n\n}	0
33393263	33393096	A few Aliases to map to the same MVC Controller	[Route("/Maps")]\n[Route("/Map")]\n[Route("/Locations")]\n[Route("/Location")]\npublic ActionResult Action () { ... }	0
18163691	18163645	Converting snippet from PHP - how to "convert" preg_replace	string ResultString = null;\ntry {\n    ResultString = Regex.Replace(SubjectString, "[???!??}?\\]/()[{???.,;\":0-9]", "");\n} catch (ArgumentException ex) {\n    // Syntax error in the regular expression\n}	0
19050252	19048346	SqlDataReader for Date data-type into maskedtextbox	string formatted = read.IsDBNull(24) ? string.Empty : read.GetDateTime(24).ToString("MM/dd/yyyy");	0
23858054	23857861	Manage a list of Constants	public static class TicketStatus {\n    public const string Open = "7ae15a71-6514-4559-8ea6-06b9ddc7a59a";\n    public const string Closed = "41f81283-57f9-4bda-a03c-f632bd4d1628";\n    public const string Hold = "41bcc323-258f-4e58-95be-e995a78d2ca8";\n}; // end of TicketStatus\n\nstring strTemp = TicketStatus.Open;\nswitch (strTemp) {\n    case TicketStatus.Open:\n        strTemp = "Jackpot";\n        break;\n}	0
16731445	16731268	Change single ListView item	protected override void OnCreate(Bundle bundle)\n    {\n        base.OnCreate(bundle);\n\n        SetContentView(Resource.Layout.Main);\n\n        lvOnlineAdapter = new CustomAdapter(this, online);\n        lvOnline = FindViewById<ListView>(Resource.Id.lvOnline);\n        lvOnline.Adapter = lvOnlineAdapter;\n\n        lvOnlineAdapter.Add("Test1");\n        lvOnlineAdapter.Add("Test2");\n        lvOnlineAdapter.Add("Test3");\n        lvOnlineAdapter.EditItem(2, "test");\n        for( int i = 0; i < myLayout.getChildCount(); i++ )\n            if( myLayout.getChildAt( i ) instanceof TextView )\n            {\n                TextView tvBold = (TextView) myLayout.getChildAt( i );\n                if(tvBold.getText().ToString() == "test")\n                    tvBold.SetBackgroundColor(Color.Yellow);\n            }\n    }\n\npublic void EditItem(int Position, string Text2)\n{\n    items[Position] = Text2;\n    NotifyDataSetChanged();\n}	0
1363731	1363682	How do I make a non-blocking socket call in C# to determine connection status?	// .Connect throws an exception if unsuccessful\nclient.Connect(anEndPoint);\n\n// This is how you can determine whether a socket is still connected.\nbool blockingState = client.Blocking;\ntry\n{\n    byte [] tmp = new byte[1];\n\n    client.Blocking = false;\n    client.Send(tmp, 0, 0);\n    Console.WriteLine("Connected!");\n}\ncatch (SocketException e) \n{\n    // 10035 == WSAEWOULDBLOCK\n    if (e.NativeErrorCode.Equals(10035))\n        Console.WriteLine("Still Connected, but the Send would block");\n    else\n    {\n        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);\n    }\n}\nfinally\n{\n    client.Blocking = blockingState;\n}\n\n Console.WriteLine("Connected: {0}", client.Connected);	0
5555681	5555553	dynamically call a control	var labels = new Dictionary<int, string>();\nfor (i = 1; i < this.controls.count;i++)\n{\n    var label = FindControl("lblA" + i) as Label;\n    if (label == null)\n    {\n        break;\n    }\n    labels.Add(i, label.Text);\n}	0
1118855	1118833	Can you specify format for XmlSerialization of a datetime?	[XmlIgnore]\npublic DateTime DoNotSerialize {get;set;}\n\npublic string ProxyDateTime {\n    get {return DoNotSerialize.ToString("yyyyMMdd");}\n    set {DoNotSerialize = DateTime.Parse(value);}\n}	0
9485427	9485125	How to pass UserID or UserName into another page in asp.net membership feature using Query String?	NavigateUrl='<%# string.Format("manage-user-detail.aspx?UserID={0}",Eval("UserID")) %>'	0
15834132	15808212	Styling headers on a DialogViewController	var section = new Section () { \n                HeaderView = new UIImageView (UIImage.FromFile     ("caltemplate.png")),\n                FooterView = new UISwitch (new RectangleF (0, 0, 80, 30)),\n            };	0
9973886	9973550	How to get a relational entity-object by Linq-to-Entity?	using (var dataContext = new realtydbEntities())\n{\n      var user =\n      (\n          from aspnet_Roles rol in dataContext.aspnet_Roles.Include("aspnet_Users")\n          from aspnet_Users usr in rol.aspnet_Users.Include("aspnet_Membership")\n          where rol.RoleId == roleID\n          select usr\n      );\n   return user.ToList();\n }	0
20797735	20797538	How to define Array name while returning JSON output	var dictionaryEmail = new Dictionary<string, List<Post>>();\nvar listEmail = var listEmail = new List<Post>();;\n\nforeach (var item in objPosts)\n{\n    var objresult = new Post\n    {\n       Title = item.Title,\n       ImageInfo = item.ImageInfo,\n       ShortDescription = item.ShortDescription\n    };\n\n    listEmail.Add(objresult);\n}\n\ndictionaryEmail.add("Contacts", listEmail);\nstring output = JsonConvert.SerializeObject(dictionaryEmail);\nreturn output;	0
3603537	3603519	Referencing a part of an array in C#	var subArray = array.Skip(5).Take(10);	0
18061475	18060635	Get accurate Rotation Angle in Unity3D C#	void getHdg()\n{\n    float temp = this.transform.eulerAngles.y;\n    craft.ChangeHeading(temp);\n}	0
10264217	10264095	How do I search multiple tables in an MVC application?	var query = _db.Comments.Join(\n    _db.Topics,\n    c => c.TopicId,\n    t => t.Id,\n    (comment, topic) =>\n       new\n       {\n           Comment = comment,\n           Topic = topic\n       });	0
29404496	29404395	How to show a split images into 8x8 pixels?	List<Image> res = new List<Image>();\n        int pembagiLebar = (int)Math.Ceil((float)img.Width / (float)blokX);\n        int pembagiTinggi = (int)Math.Ceil((float)img.Height / (float)blokY);\n\n\n        for (int i = 0; i < pembagiLebar ; i++)//baris\n        {\n            for (int j = 0; j < pembagiTinggi ; j++)//kolom\n            {\n                Bitmap bmp = new Bitmap(blokX, blokY);\n\n                using (Graphics grp = Graphics.FromImage(bmp)) {\n                     grp.DrawImage(img, 0, 0, new Rectangle(i * blokX, j * blokY, blokX, blokY), GraphicsUnit.Pixel);\n                }\n\n                res.Add(bmp);\n            }\n        }\n\n\n        return res;	0
20659724	20659645	Putting each line from a text file into an array C#	string[] lines = null;\n    try\n    {\n        lines = File.ReadAllLines(path);\n    }\n    catch(Exception ex)\n    {\n        // inform user or log depending on your usage scenario\n    }\n\n    if(lines != null)\n    {\n        // do something with lines\n    }	0
28362703	28362473	How to get derived class MEMBERS by name, from base class, in C#?	public void SuperDuperUniversal(CommonClass unknownDerived, string memb_name)\n{\n    var member = unknownDerived.GetType().GetProperty(memb_name).GetValue(unknownDerived, null) as ObjDescr;\n\n    string desc = member.Description;\n}	0
28840000	28486837	How do I Localize a Class Display Name	using System.ComponentModel;\nusing System.Resources;\n\n\nnamespace SCC.Case.Entities\n{\n    /// <summary>\n    /// Provides a class attribute that lets you specify the localizable string for the entity class\n    /// </summary>\n    class DisplayNameForClassAttribute : DisplayNameAttribute\n    {\n        public string Name { get; set; }\n        public override string DisplayName\n        {\n            get\n            {\n                ResourceManager resourceManager = new ResourceManager("SCC.Case.Entities.DisplayNames", typeof(DisplayNameForClassAttribute).Assembly);\n                return resourceManager.GetString(this.Name);\n            }\n        }\n    }\n}	0
10617733	10617617	return the data at webservices	[WebMethod]\npublic List<Employee> GetEmployeeDetails(string userType)\n{\n   //search the member table looking for a matching userType value\n   string sql = "SELECT * FROM member WHERE userType = '" + ?? + "'";\n   SqlCommand cmd = new SqlCommand(sql, conn);\n   conn.Open();\n   List<Employee> employeeList = new List<Employee>();\n   reader = cmd.ExecuteReader();\n\n   while (reader.Read())\n   {\n      var emp = new Employee(\n          { \n              fullName = reader["fullName"].ToString(), \n              password = reader["password"].ToString(), \n              userType = reader["userType"].ToString()\n          });\n\n      employeeList.Add(emp);\n   }\n\n   reader.close();\n   return employeeList;\n}	0
14893683	14893617	How to update with LINQ an object property knowing its name?	obj.GetType( ).GetProperty( "property_name" ).SetValue( obj, "test" );	0
33799221	33795728	How to correctly set up a proxy with Selenium C# PhantomJSDriver?	PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();\nservice.AddArgument(string.Format("--proxy-auth={0}:{1}", proxyUsername, proxyPassword));\nservice.AddArgument(string.Format("--proxy={0}:{1}", proxyAddress, proxyPort));\n\nIWebDriver driver = new PhantomJSDriver(service);	0
954335	953911	Dynamic Linq - Setting orderby expression type at runtime	var result = from item in table.Where("owner = \"joe\"").OrderBy("inserted") select item;\nresult.ToList().ForEach(m => Console.WriteLine("inserted=" + m.Inserted + "."));	0
19281047	19280553	How do I remove multiple offending characters from my string?	Output = Input.Replace("(", "").Replace(")", "").Replace("-", "");	0
10309236	10300161	How do I remove related objects in linq to entity framework	context.OrderItems.Remove(orderitem);\ncontext.SaveChanges();	0
18463000	18462791	Is there any way to get know that catch statement is trigger	global.asax	0
17570956	17570868	Entity Framework 1 - 1 - * - 1 relationships	jobs.where(job=> job.Worker\n     .where(worker=> worker.WorkerRegionGroup.Region == x).Any());	0
28148093	28139054	Windows service fails to install through msi setup in few machines	.config	0
30632970	30495140	Draw debug ray in perspective mode	Ray ray = camera.ScreenPointToRay(Input.mousePosition);\nDebug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);	0
7368502	7368411	how to return values from one class to another?	public static void Main() {\nConsole.WriteLine(GmailF.CheckMail() + AidaF.OnTimedEvent());\n}	0
31497922	31497846	How to get an IEnumerable of child objects that can have child objects	IEnumerable<Test> AllChildren(List<Test) list,Test mytest)\n{\n  foreach(var test in list)\n  {\n    if (test.parentid==mytest.id)\n    {\n       yield return test;\n       foreach(var t in AllChildren(list,test))\n       {\n         yeild return t;\n       }\n    }\n  }\n}	0
23298653	23296937	How do I mock controller context in my unit test so that my partial view to string function works?	var mock = new Mock<ControllerContext>();\nmock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);\nif (userName != null)\n{\n   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);\n   mock.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);\n}\nelse\n{\n   mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(false);\n}\n\nvar routeData = new RouteData();\nrouteData.Values.Add("controller", "BlogController");\nmock.SetupGet(m => m.RouteData).Returns(routeData);\n\nvar view = new Mock<IView>();\nvar engine = new Mock<IViewEngine>();\nvar viewEngineResult = new ViewEngineResult(view.Object, engine.Object);\nengine.Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(viewEngineResult);\nViewEngines.Engines.Clear();\nViewEngines.Engines.Add(engine.Object);\n\nvar controller = new BlogController();\ncontroller.ControllerContext = mock.Object;	0
3122685	3122677	Add zero-padding to a string	var newString = Your_String.PadLeft(4, '0');	0
24359776	24348225	Kendo UI grid template column	columns.ClientTemplate("#: <input type='text' name='MelliCode' class='sel' /> #")...	0
10978407	10960801	itext sharp get total number of bookmarks	int bookmarks = iTextSharp.text.pdf.SimpleBookmark.GetBookmark(pdfReader).Count;	0
1953768	1953665	Detecting a control's focus in Silverlight	bool b = FocusManager.GetFocusedElement() == textBox;	0
6880922	6880288	Finding an item by object value in Combobox	cbVehicleMake.SeletedItem=allMakes.Find(q=>q.Id==selectedMake.Id))	0
5434681	5434606	How to extend a user control without calling base code	public class B\n{\n    private F f;\n\n    public F F\n    {\n        get { return f ?? (f = InitializeF()); }\n        set { f = value; }\n    }\n\n    protected virtual F InitializeF()\n    {\n        return new F();\n    }\n}\n\npublic class X : B\n{\n    protected override F InitializeF()\n    {\n        return new SomeOtherF();\n    }\n}	0
8273678	8273611	Find value inside string	var match = Regex.Match("10days25hours15minutes", @"(\d+)\D+(\d+)\D+(\d+)\D+");\n\nvar result = new TimeSpan(\n    days: int.Parse(match.Groups[1].Value),\n    hours: int.Parse(match.Groups[2].Value),\n    minutes: int.Parse(match.Groups[3].Value),\n    seconds: 0);\n\n// result == {11.01:15:00}	0
22964364	22964170	Call instance declared in Main from outside method on Timer Event	class Program\n{\n    private static Timer aTimer = new Timer(1000);\n\n    //Define your game in the class\n    private static Game game;\n\n    static void Main(string[] args)\n    {\n\n        aTimer.Interval = 1000;\n        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n        aTimer.Start();\n\n        Championship champ = new Championship();\n        game.GenerateTeams();\n        game = new Game(champ.teams[0], champ.teams[1]);\n\n        juego.CrearDisplay();\n        game.CreateField();\n\n        while (true) { int a = 1; }\n    }\n\n    //Actualization\n    static private void OnTimedEvent(object source, ElapsedEventArgs e)\n    {\n        game.DoSomething();\n    }	0
18095886	18095364	How can I move this function into a Class	public string F03_veri_textbox(string veriadi3, mytype browser)\n  {\n      string Veritext;\n      Veritext = browser.Document.GetElementById(veriadi3).GetAttribute("value");\n\n      return Veritext;\n\n  }	0
23006020	23005853	How to solve the issue in using Location services with Async in windows phone?	private void GetCoordinate()\n    {\n        var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)\n        {\n            MovementThreshold = 2\n        };\n        watcher.PositionChanged += this.watcher_PositionChanged;\n        watcher.StatusChanged += this.watcher_StatusChanged;\n        watcher.Start();\n    }\n\nprivate void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)\n    {\n        try\n        {\n            var pos = e.Position.Location;\n            if(position==required one)\n             {\n                //enable disable here  \n             }\n            StaticData.currentCoordinate = new GeoCoordinate(pos.Latitude, pos.Longitude);\n        }\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.Message);\n        }\n    }	0
18265489	18223679	FileNotFoundException from WCF service	private readonly string mSchemaPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "RecordSchema.xsd");\nprivate readonly string mXmlPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "Records.xml");	0
18750104	18750030	returning bool result from sqlcommand	return DbInstance.ExecuteAsSingle<bool>(_command, r => r.GetValueOrDefault<bool>(0));	0
6753188	6753116	Populate form with controls based on int value	for (int i = 0; i < 5; i++)\n{\n  Button newButton = new Button();\n  newButton.Name = "button" + i.ToString();\n  newButton.Text = "Button #" + i.ToString();\n  newButton.Location = new Point(32, i * 32);\n  newButton.Click += new EventHandler(button1_Click);\n  this.Controls.Add(newButton);\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n  if (((Button)sender).Name == "button0")\n    MessageBox.Show("Button 0");\n  else if (((Button)sender).Name == "button1")\n    MessageBox.Show("Button 1");\n}	0
7287938	7284011	Problem querying web page parsed with HTML Agility Pack	var nodes = doc.DocumentNode.SelectNodes("//div[@class=\"discount_tools\"]");\n        var linksCollections = nodes.Select(node => node.Descendants("a"));\n\n        List<string> Locations = new List<string>();\n        List<string> Categories = new List<string>();\n        List<string> Hrefs = new List<string>();\n\n        foreach (var col in linksCollections)\n        {\n            string location, category, href;\n            location = GetAtt("data-address",col);\n            if (!string.IsNullOrEmpty(location))\n            {\n                category = GetAtt("data-kind", col);\n                if (!string.IsNullOrEmpty(category))\n                {\n                    href = GetAtt("data-provider", "href", col);\n                    if (!string.IsNullOrEmpty(href))\n                    {\n                        Locations.Add(location);\n                        Categories.Add(category);\n                        Hrefs.Add(href);\n                    }\n                }\n            }\n\n        }	0
9157775	9157558	Format ListView based on contents	foreach (ListViewItem item in lvTest.Items) \n{\n    if(item.SubItems[1].Text == "OK") \n        item.BackColor = System.Drawing.Color.Green;\n    else \n        item.BackColor = System.Drawing.Color.Red;\n}	0
6538598	6538409	JQuery bring expanded image to front	.css('z-index', parseInt( new Date().getTime()/1000 ));	0
23268005	17948596	New email create event in outlook 2010 using C#	this.Application.NewMailEx += new   Outlook.ApplicationEvents_11_NewMailExEventHandler(olApp_NewMail);\n\nprivate void olApp_NewMail(String itemCollection)\n    {\n     //write some code here\n    }	0
8727283	8727179	set Cursor to desired point c#	Cursor.Position = new Point();	0
21047387	21047216	C# programmatically initializing multidimensional array	int z = ... ;\nint[,] array = new int[get1stDimensionLength(), z];\n// programmatically fill the array\nfor (int i = 0; i < array.GetLength(0); i++) {\n    for (int j = 0; j < array.GetLength(1); j++) {\n        array[i,j] = 18;\n    }\n}	0
20190402	20139340	Generate XML file in C# with XSD file	foreach (Factuur huidigeFactuur2 in e.SelectedObjects)\n            {\n                XmlSerializer serializer2 = new XmlSerializer(typeof(KilometerUpload));\n                TextWriter writer = new StreamWriter(@"C:\test2.xml");\n\n                string chassisnummer = huidigeFactuur2.Wagen.Chassisnummer;\n                string kilometerstatus = huidigeFactuur2.KMStand.ToString();\n\n                KilometerUpload item = new KilometerUpload\n                {\n                    KilometerRegistration = new KilometerUploadKilometerRegistration[] { new KilometerUploadKilometerRegistration{ ChassisNumber = chassisnummer , TypeOfData = "120", KilometerStatus = kilometerstatus} },\n                };\n\n                serializer2.Serialize(writer, item);	0
8720877	8720683	Strange behavior of Windows Forms combobox control	cmbDataType1.DataSource = new BindingSource(datasource, "");\ncmbDataType2.DataSource = new BindingSource(datasource, "");	0
2503896	2501278	Accessing a file on a network drive	\\SERVER\Share\Filename.ext	0
29340509	29340279	Searching folders and subfolders for a file and get its size depending on the name	string adPicturesPath = ConfigurationManager.AppSettings["AdPicturesPath"];\nList<string> files = new List<string> { "235253325_23522.jpg" };\nvar allFiles = files.SelectMany(fn => Directory.EnumerateFiles(adPicturesPath, fn, System.IO.SearchOption.AllDirectories));\nlong allFileSizeBytes = allFiles.Sum(fn => new FileInfo(fn).Length);	0
22976784	22976748	Linq Expressing a query as a Lambda query	var query = students\n            .Where(s => s.DateOfBirth.Year < 1990)\n            .OrderBy(s => s.FirstName);	0
8057095	8056857	How can i emulate the Shift + F5 keystroke?	SendKeys.SendWait("+{F5}");	0
13915893	13915775	filter in subquery in nhibernate query	CurrentSession.Linq<Product>()\n    .Where(p => p.NumberOfProductsInStock > 0 && (p.Orders.Count() == 0 || p.Orders.Count() <= p.NumberOfProductsInStock))\n    .ToList();	0
29040751	29040646	Regex for replacement	Regex.Replace(\n  input, \n  //find expression\n  @"(\w+)(\[)", \n  //replacement expression\n  @"$1()$2")	0
12805292	12804863	How to detect when a WebBrowserTask is closed?	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n{\n    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back && _usedWebBrowserTask)\n    {\n        //Do your stuff here\n\n        _usedWebBrowserTask = false;\n    }\n\n    base.OnNavigatedTo(e);\n}\n\nprivate void LaunchWebBrowserButton_Click(object sender, RoutedEventArgs e)\n{\n    _usedWebBrowserTask = true;\n\n    new WebBrowserTask()\n    {\n        Uri = new Uri("http://www.microsoft.com")\n    }.Show();\n}	0
33555692	33548795	Active Directory - Get All Users Belonging to a Manager	using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry("LDAP://contoso.com")))\n        {\n            searcher.Filter = "(&(objectCategory=person)(objectClass=user)(manager=CN=John Doe,CN=Users,DC=contoso,DC=com))";\n\n            searcher.PropertiesToLoad.AddRange(new string[] { "givenName", "sn", "sAMAccountName" });\n\n            foreach (SearchResult item in searcher.FindAll())\n            {\n                Console.WriteLine(String.Format("User {0} {1} ({2}) works for John Doe", item.Properties["givenName"].ToString(), item.Properties["sn"].ToString(), item.Properties["sAMAccountName"].ToString()));\n            }\n        }	0
4015595	4015407	Determine current domain controller programmatically	using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain))\n{\n    string server = context.ConnectedServer; // "pdc.examle.com"\n    string[] splitted = server.Split('.'); // { "pdc", "example", "com" }\n    IEnumerable<string> formatted = splitted.Select(s => String.Format("DC={0}", s));// { "DC=pdc", "DC=example", "DC=com" }\n    string joined = String.Join(",", formatted); // "DC=pdc,DC=example,DC=com"\n\n    // or just in one string\n\n    string pdc = String.Join(",", context.ConnectedServer.Split('.').Select(s => String.Format("DC={0}", s)));\n}	0
24965900	24965884	How can I change dynamicaly the opacity of a linegraph in D3?	line.LinePen.Opacity = slider.Value;	0
2811838	2811542	Separation of business logic	public DbCommand CreateCommand()\n    {\n        if (this._baseCommand.Transaction != null)\n        {\n            DbCommand command = this._baseConnection.CreateCommand();\n            command.Transaction = this._baseCommand.Transaction;\n            return command;\n        }\n        return this._baseConnection.CreateCommand();\n    }	0
4489191	4489172	Set objects properties from string in C#	YourClass theObject = this;\n PropertyInfo piInstance = typeof(YourClass).GetProperty("PropertyName");\n piInstance.SetValue(theObject, "Value", null);	0
6152642	6152545	How can I get a list of tables in an Access (Jet) database?	connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\access.mdb";    \n\n    connection.Open();\n\n    DataTable userTables = connection.GetSchema("Tables");	0
17859201	17857831	InCorrect XML formats are not Rejecting while Validating XML in C#	string parameters = "<Paramnumber AAA=\"120901\" />";	0
11363588	11363521	How to improve this code using c#	while ((new char[] {' ', ',', '.'}).Contains(txtSource.Text[startPos]))	0
32495705	32494213	how to check automatically a parent	private void OnTreeViewAfterCheck(object sender, TreeViewEventArgs e)\n{\n    var treeView = (TreeView)sender;\n\n    treeView.AfterCheck -= OnTreeViewAfterCheck;\n    SetChildCheckedState(e.Node);\n    treeView.AfterCheck += OnTreeViewAfterCheck;\n}\n\nprivate void SetChildCheckedState(TreeNode treeNode)\n{\n    foreach (TreeNode childNode in treeNode.Nodes)\n    {\n        childNode.Checked = treeNode.Checked;\n\n        // Call recursively if you like\n        SetChildCheckedState(childNode);\n    }\n}	0
19428391	19428096	Checking the validation of Regular expression validator in C# back end	if(dt.Rows.Count > 0)\n{\n    UserId_Label.Text = "Someone already has that username, try another?";\n}\nelseif(!Page.IsValid)\n{\n    // Do what needs to be done when not valid\n    UserId_Label.Text = "Invalid username input";\n}\nelse\n{\n    UserId_Label.Text = "Wow , its a unique username! please fill in the remaining fields of the form";\n}	0
32464906	32463927	How to set MongoDB automatically assign ID to each sub-document?	public class SubDocument {\n    //if using objectId as ID\n    public ObjectId Id = { get; set;}\n\n    public SubDocument(){\n        Id = ObjectId.GenerateNewId()\n    }\n\n}	0
25657927	25657717	i saw a message in eventlog stating ' Global cache sent to client [client id]	/// somewhere on global\nobject loggerLock = new object(); \n\npublic DataTable GetGlobalCache(out Guid serverGUID, Guid clientGUID, string clientIP)\n{\n    lock(loggerLock)\n    {\n        Logger.LogEvent(String.Format("GlobalCache sent to client {0} [IP:{1}]", clientGUID.ToString(), HttpContext.Current.Request.UserHostAddress.ToString()));**\n    }\n\n    if (GlobalEntities.CacheData == null) DBAccess.GetData();\n\n    //Return our server guid\n    serverGUID = GlobalEntities.ServerGUID;\n\n    return GlobalEntities.CacheData;\n}	0
26724603	26724129	Approach to consume stream, transform, then hand to other consumers (without state)	public IObservable<AccelerometerFrame_raw> AccelerometerFrames()\n{\n     return\n        from evt in spatialEvents\n        let e = evt.EventArgs\n        select new AccelerometerFrame_raw\n        (\n           e.spatialData[0].Acceleration[0],\n           e.spatialData[0].Acceleration[1],\n           e.spatialData[0].Acceleration[2],\n           e.spatialData[0].AngularRate[0],\n           e.spatialData[0].AngularRate[1],\n           e.spatialData[0].AngularRate[2]\n        );\n}	0
28769130	28768785	FormatException was unhandled: Input string was not in a correct format	private void button1_Click(object sender, EventArgs e)\n    {\n        float tbox1 = float.Parse(textBox1.Text);\n        float tbox2 = float.Parse(textBox2.Text);\n        float tbox12;\n\n        if (textBox1 != null && textBox2 != null)\n        {\n            tbox12 = tbox1 + tbox2;\n            textBox3.Text = tbox12.ToString();\n        }\n    }\n\n    private void button2_Click(object sender, EventArgs e)    \n    {\n        float tbox3 = float.Parse(textBox3.Text);\n        float tbox4 = float.Parse(textBox4.Text);\n        float tbox34;\n\n        if (textBox3 != null && textBox4 != null)\n        {\n           tbox34 =  tbox3 + tbox4;\n           textBox5.Text = tbox34.ToString();\n        }       \n\n    }	0
14050716	14050194	Using label control inside foreach loop to display multiple value in a single label	label12.Text = ""; // or just delete the text in the designer\nforeach(Mutant mutant in mutants)\n{\n    label12.Text += mutant.displayInfo() + "\n"; //  This will create a seperate line for each displayInfo\n   // label12.Text += mutant.displayInfo();  //This will add them on the same line\n}	0
6199123	6198987	How add the string in listview and strech it in row?	listView1.View=View.List;	0
9732512	9662308	How to create event of Keydown if all the controls are disabled in winforms?	Private void Form1_KeyDown(object sender,KeyEventArgs e)\n               {\n                  if(e.Control && e.Keycode==Keys.N)\n                {\n                 // code goes here.\n                }\n               }	0
31154526	31154066	how to check whether a button is clicked, inside another button click event in windows form application in C#	static CancellationTokenSource cts;\n    static Task t;\n\n    private void Method()\n    {\n        while (!cts.IsCancellationRequested) \n        {\n             // your logic here\n        }\n        t = null;\n    }\n\n    private void stdaq_click (object sender, EventArgs e)\n    {           \n       if(t != null) return;\n       cts = new CancellationTokenSource();\n       t = new Task(Method, cts.Token, TaskCreationOptions.None);\n       t.Start();\n    }\n\n    private void spdaq_Click(object sender, EventArgs e) \n    {\n       if(t != null) cts.Cancel(); \n    }	0
21089368	21089140	JSON.NET: check first key value in Json file	JObject o = JObject.Parse(response);\n\nswitch (o.First.First.Path)\n{\n    case "Players":\n        // do stuff \n        break;\n    // ...\n}	0
21295704	21206684	Decompress ZIP file in isolated storage	using (ZipArchive archive = ZipFile.OpenRead(zipPath))\n{\n    foreach (ZipArchiveEntry entry in archive.Entries)\n    {\n        using (Stream zipStream = entry.Open())\n        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(entry.Name, FileMode.CreateNew, isoStore))\n        {\n            // copy from zipStream to isoStream\n        }\n    }\n}	0
2054847	2054712	send information through a url from desktop based application	StringBuilder sb  = new StringBuilder();\n\n// used on each read operation\nbyte[]        buf = new byte[8192];\n\n// prepare the web page we will be asking for\nHttpWebRequest  request  = (HttpWebRequest)WebRequest.Create("http://www.feefifofum.com/login.aspx?userid=XXX&pass=YYYY");\n\n// execute the request\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n// we will read data via the response stream\nStream resStream = response.GetResponseStream();\n\nstring tempString = null;\nint    count      = 0;\ndo\n{\n    // fill the buffer with data\n    count = resStream.Read(buf, 0, buf.Length);\n\n    // make sure we read some data\n    if (count != 0)\n    {\n        // translate from bytes to ASCII text\n        tempString = Encoding.ASCII.GetString(buf, 0, count);\n\n        // continue building the string\n        sb.Append(tempString);\n    }\n}\nwhile (count > 0); // any more data to read?\n\n// print out page source\nConsole.WriteLine(sb.ToString());	0
33040181	33036030	EntityFramework7 - Conventions, Properties and Configurations	protected override void OnModelCreating(ModelBuilder builder) \n{\n    foreach (var type in builder.Model.EntityTypes.Where(type => type.HasClrType))\n    {\n        foreach (var property in type.Properties)\n        {\n            if (property.ClrType == typeof(DateTime))\n            {\n                builder.Entity(type.ClrType)\n                    .Property(property.ClrType, property.Name)\n                    .HasSqlServerColumnType("datetime2(0)");\n            }\n        }\n    }\n}	0
12974109	12974067	Windows 8 XAML C# implement Page_Error?	Application.UnhandledException	0
19275541	19275460	Concat two dictionaries so that original's shared keys are updated	orig = orig.Keys.ToDictionary(c => c, c=>(orig[c] == "" ? newDict[c] : orig[c]));	0
7817890	7817784	Filtering comma separated String in C#	string[] TrimAll( string[] input )\n{\n    var result = new List<string>();\n    foreach( var s in input )\n        result.Add( s.Trim() );\n    }\n    return result.ToArray();\n}\n\nvar delimiters = new [] { ",", "\t", Environment.NewLine };\nstring result = string.Join(",", TrimAll( input.Split( delimiters, StringSplitOptions.RemoveEmptyEntries ) ) );	0
24928552	24928236	Rounding a number with different resolutions	public decimal MyRound(decimal input)\n{\n    return Math.Round(input*2-0.001M, MidpointRounding.AwayFromZero)/2;\n}\n\nvoid Main()\n{\n    var testvalues = new decimal[]{0M,0.125M,0.25M,0.375M,0.5M,0.625M,0.75M,0.875M,1M};\n    foreach (var value in testvalues)\n    {\n        Console.WriteLine(String.Format("{0} rounds to {1}",value, MyRound(value)));\n    }\n}\n\n\nOutput: \n0 rounds to 0\n0.125 rounds to 0\n0.25 rounds to 0\n0.375 rounds to 0.5\n0.5 rounds to 0.5\n0.625 rounds to 0.5\n0.75 rounds to 0.5\n0.875 rounds to 1\n1 rounds to 1	0
8909117	8908991	Show a progressbar in taskbar while form is minimized	Taskbar.ProgressBar.State = \n(TaskbarButtonProgressState)Enum.Parse(\n        typeof(TaskbarButtonProgressState), \n        (string)comboBoxProgressBarStates.SelectedItem);\n\nif (Taskbar.ProgressBar.State != TaskbarButtonProgressState.Indeterminate)\n   Taskbar.ProgressBar.CurrentValue = progressBar1.Value;	0
5691938	5691902	summarize values on a tree	public void SetNodeValues(Node node)\n{\n    if (node.Name == String.Empty)\n    {\n        //If it has no name it is a leaf, which needs no value\n        return;\n    }\n    else\n    {\n        //Make sure all child-nodes have values\n        foreach (var childNode in node.ChildNodes)\n        {\n            SetNodeValues(childNode);\n        }\n\n        //Sum them up and set that as the current node's value\n        node.Value = node.ChildNodes.Sum(x => x.Value);\n    }\n}	0
19732056	19731962	Math.Round number with 3 decimal	public static void Main()\n   {\n      double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };\n      foreach (double value in values)\n         Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));\n\n   }	0
17482128	17481989	Display a particular row in datagridview based on the selection of the childnode from the treegridview	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)\n{\n    int outva;\n    dataGridView1.ClearSelection();\n\n    if (int.TryParse((e.Node.Text), out outva))\n    {\n        //save=Convert.ToInt16(e.Node.Text);  //not needed\n\n        string filterBy;\n\n        if (e.Node.Parent != null)\n        {\n            filterBy = "GroupId = " + outva;\n        }\n        else\n        {\n            filterBy = "StringId = " outva;\n        }\n\n        //int row = dataGridView1.Rows.Count; // not needed\n\n        ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = filterBy;\n    }\n    else \n    {\n\n    }\n}	0
19422953	19400888	SqlList<DynamicPoco> return dynamic type structure from Stored Procedure	var massiveModel = new DynamicModel(dbConn.ConnectionString);\n    var connection = new SqlConnection(@"Data Source=127.0.0.1;Initial Catalog=TEST;User ID=as;Password=;Application Name=BRUCE_WAYNE");\n        connection.Open();\n    var massiveConnection = connection;\n    var tmp = massiveModel.Query("exec MY_SP 4412 '20131016' ", MassiveConnection).ToList();	0
32493203	32493163	C# Unassigned Local Variables	var width = 0;\nvar height = 0;\n\nif( size > 10){    \n    width = 5;\n    height = 5;    \n}\nelse {\n    width = 6;\n    height = 7;\n}\n\narea = width * height;	0
1635244	1633401	Set a datalist.datasource from inside a usercontrol - asp.net c#	DataList dl = (DataList)yourLoadedusercontrol.FindControl("yourDatalist");\n    dl.DataSource = yourdatasource;	0
9878030	9877999	ASP.NET Webapp -- asp:HyperLink with a background image shows has a border in IE but not FireFox	img { border:none; }	0
25841647	25841586	How can I parse only the float number from the string?	var match = Regex.Match(val, @"([-+]?[0-9]*\.?[0-9]+)");\nif (match.Success)\n  xCoord = Convert.ToSingle(match.Groups[1].Value);	0
8078228	8078082	How to clean up "TreeNode"s with same Text property in a TreeView?	if (newPinGrpNodes.Any(n => n.Text == node.Text)) continue;	0
16318743	16318076	Unsure how to model and architecture this one	public class MyObjectBuilder{\n  // inject the repository\n  public MyObjectBuilder(IMyObjectBuilderRepository repository) \n\n  private Property1 property1;\n  public void SetProperty1(Property1 prop){}\n\n  public MyObject GetMyObject(){\n    MyObject result = new MyObject(); // optional to use constructor injection\n    result.Property1 = this.property1;\n\n    // based on this.property1, set the Property4Set object\n    Property4Set property4 = repository.GetProperty4Set(this.property1);\n\n    result.Property4 = property4;\n    return result;\n  }\n}	0
29708851	29708703	How to put a file in the HttpResponseMessage Content?	// Return archive stream\n        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);\n        result.Content = new StreamContent(fileStream);\n        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");\n        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {\n            FileName = fileName.ToString()\n        };	0
280591	280578	How to work with an interface dynamically loaded from an assembly and invoke its members	private static IEnumerable<T> InstancesOf<T>() where T : class\n{\n    var type = typeof(T);\n    return from t in type.Assembly.GetExportedTypes()\n           where t.IsClass\n               && type.IsAssignableFrom(t)\n               && t.GetConstructor(new Type[0]) != null\n           select (T)Activator.CreateInstance(t);\n}	0
6541951	6541925	Cross-thread operation not valid - listbox Clear statement	private void UpdateHistory()\n{\n   //tbHistory is a listbox\n   myForm.Invoke ((Action) (() =>tbHistory.Items.Clear()));\n}	0
9044317	9044195	Find where in document user clicked in Visual Studio Extension Context Menu	activeDoc.Selection.ActivePoint	0
6803613	5816439	How to find out current version of Outlook from VSTO Addin?	Globals.ThisAddIn.Application.Version	0
15815357	15813098	Projections from Repository in classic and DDD perspective	IQueryable<T>	0
2139303	2139274	Grabbing the output sent to Console.Out from within a unit test?	[TestMethod]\npublic void ValidateConsoleOutput()\n{\n    using (StringWriter sw = new StringWriter())\n    {\n        Console.SetOut(sw);\n\n        ConsoleUser cu = new ConsoleUser();\n        cu.DoWork();\n\n        string expected = string.Format("Ploeh{0}", Environment.NewLine);\n        Assert.AreEqual<string>(expected, sw.ToString());\n    }\n}	0
12611686	12611296	C# - Returning Value From a Method in Another AppDomain	using System;\nusing System.Reflection;\n\npublic class Worker : MarshalByRefObject\n{\n    public void PrintDomain() \n    { \n        Console.WriteLine("Object is executing in AppDomain \"{0}\"",\n            AppDomain.CurrentDomain.FriendlyName); \n    }\n}\n\nclass Example\n{\n    public static void Main()\n    {\n        // Create an ordinary instance in the current AppDomain\n        Worker localWorker = new Worker();\n        localWorker.PrintDomain();\n\n        // Create a new application domain, create an instance \n        // of Worker in the application domain, and execute code \n        // there.\n        AppDomain ad = AppDomain.CreateDomain("New domain");\n        Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(\n            Assembly.GetExecutingAssembly().FullName,\n            "Worker");\n        remoteWorker.PrintDomain();\n    }\n}\n\n/* This code produces output similar to the following:\n\nObject is executing in AppDomain "source.exe"\nObject is executing in AppDomain "New domain"\n */	0
5388987	5388862	Create Image Button using Code-behind	ImageButton imgBtn = new ImageButton();\nimgBtn.ID = "image_id";\nimgBtn.ImageUrl = "your_image_path";\nPanel1.Controls.Add (imgBtn);	0
3157822	3157815	Need to print double as 12.20 instead of 12.2	Console.WriteLine(s.ToString("0.00"));	0
17136107	17136042	Returning JSON from WCF after POST in Android	WebMessageFormat.Json	0
2187646	2186817	iTextSharp + FileStream = Corrupt PDF file	using (MemoryStream myMemoryStream = new MemoryStream()) {\n    Document myDocument = new Document();\n    PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);\n\n    myDocument.Open();\n\n    // Add to content to your PDF here...\n    myDocument.Add(new Paragraph("I hope this works for you."));\n\n    // We're done adding stuff to our PDF.\n    myDocument.Close();\n\n    byte[] content = myMemoryStream.ToArray();\n\n    // Write out PDF from memory stream.\n    using (FileStream fs = File.Create("aTestFile.pdf")) {\n        fs.Write(content, 0, (int)content.Length);\n    }\n}	0
10955797	10955772	How to include Variables in Localized Strings?	Console.Write(String.Format(resourceManager.GetString("USER_COULD_NOT_BE_ADDED_FORMAT"), userNum));	0
12474756	12474436	Populating data to a nested Dictionary Collection	var _isEditable = _empColl.ToDictionary(item => item.EmployeeID,\n                                         item => item.GetType()\n                                                  .GetProperties()\n                                                  .ToDictionary(pro => pro.Name, \n                                                                pro => false));	0
12646336	12646287	image Scaling of picture box	this.PictureBox1.SizeMode = PictureBoxSizeMode.Zoom;	0
9071756	9071701	linq-to-sql grouping with timezone	AsEnumerable()	0
4884370	4884276	Sharepoint access to list ignore user permission	SPSecurity.RunWithElevatedPrivileges(delegate()\n  {\n        // Pur your code here.\n  });	0
11327340	11327103	Maintaining a many-to-many relationship when Xml(De)Serializing	public IEnumerable<Signal> Signals\n  {\n    get\n    {\n      return from signal in Signals\n      from ms in MessageSignals\n      where ms.MessageId == this.MessageId && ms.SignalId==signal.Id\n      select signal;\n    }\n  }	0
19112958	19112122	How can I persist an array of a nullable value in Protobuf-Net?	using ProtoBuf;\nusing ProtoBuf.Meta;\nusing System;\n[ProtoContract]\nclass Foo\n{\n    [ProtoMember(1)]\n    public double?[] Values { get; set; }\n}\nstatic class Program\n{\n    static void Main()\n    {\n        // configure the model; SupportNull is not currently available\n        // on the attributes, so need to tweak the model a little\n        RuntimeTypeModel.Default.Add(typeof(Foo), true)[1].SupportNull = true;\n\n        // invent some data, then clone it (serialize+deserialize)\n        var obj = new Foo { Values = new double?[] {1,null, 2.5, null, 3}};\n        var clone = Serializer.DeepClone(obj);\n\n        // check we got all the values back\n        foreach (var value in clone.Values)\n        {\n            Console.WriteLine(value);\n        }\n    }\n}	0
11912760	11912109	Split XML document apart creating multiple output files from repeating elements	public void test_xml_split()\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load("C:\\animals.xml");\n    XmlDocument newXmlDoc = null;\n\n    foreach (XmlNode animalNode in doc.SelectNodes("//Animals/Animal"))\n    {\n        newXmlDoc = new XmlDocument();\n        var targetNode = newXmlDoc.ImportNode(animalNode, true);\n        newXmlDoc.AppendChild(targetNode);\n        newXmlDoc.Save(Console.Out);\n        Console.WriteLine();\n    }\n}	0
1583301	1583267	C#: Archiving a File into Parts of 100MB	SevenZipCompressor.CustomParameters	0
33188884	33180068	Flipping a bitmap but keeping original file size	Bitmap pic = new Bitmap("example.bmp");\n\n    Bitmap pic2 = new Bitmap(pic.Width, pic.Height, PixelFormat.Format16bppRgb555);\n\n    for (int x = 0; x < pic.Width; ++x)\n    {\n        for (int y = 0; y < pic.Height; ++y)\n        {\n            pic2.SetPixel(x, y, pic.GetPixel(x, y));\n        }\n    }\n\n    pic2.RotateFlip(RotateFlipType.Rotate180FlipX);\n    pic2.Save("test.bmp", ImageFormat.Bmp);	0
8589999	8588869	Applying transforms from DataTemplates in WPF	class ImageToCanvasConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        return -(int)value / 2;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        // Two-way binding not supported\n        throw new InvalidOperationException(); \n    }\n}\n\n<Grid.Resources>\n    <myAssembly:ImageToCanvasConverter x:Key="imageToCanvasConverter" />\n    <DataTemplate ...>\n        <Image Canvas.Left="{Binding Path=Width, Converter={StaticResource imageToCanvasConverter}, Mode=OneTime}"\n               Canvas.Top="{Binding Path=Height, Converter={StaticResource imageToCanvasConverter}, Mode=OneTime}"\n               ... />\n    </DataTemplate>\n</Grid.Resources>	0
14640020	14639379	Code first and changing model class, how to update model without recreate the table?	Code First Migrations	0
1211724	1211707	How to access classes in another assembly for unit-testing purposes?	[assembly:InternalsVisibleTo("MyProjectTests")]	0
2647487	2646606	How do I reclaim the space from the "Grip"	public Form1() {\n  InitializeComponent();\n  statusStrip1.Padding = new Padding(statusStrip1.Padding.Left,\n    statusStrip1.Padding.Top, statusStrip1.Padding.Left, statusStrip1.Padding.Bottom);\n}	0
23619590	23618388	How can a memory leak persist even after the program that caused it has closed?	max server memory	0
1044971	1044951	How to determine what object[] passed as parameter contains?	public void Foo(object[] values)\n{\n    var pairs = values.OfType<KeyValuePairType>().ToArray();\n    var lists = values.OfType<KeyValueListPair>().ToArray();\n\n    pairs = pairs.Length == 0 ? null : pairs;\n    lists = lists.Length == 0 ? null : lists;\n\n    DoSomeWork(pairs, lists);\n}	0
11746105	11746083	How to count the delimiters in a string?	Regex.Matches( s,  "/" ).Count	0
23911375	23910922	Remove items in dictionary(sting,list of object?	//loop dict backwards so we can remove items\n for (int i = dict.Count - 1; i >= 0; i--)\n        {\n            //convert the value to List<>\n            List<TestObjs> objs = dict.ElementAt(i).Value as List<TestObjs>;\n\n            //Loop List<> backwards so we can remove items\n            for (int j = objs.Count - 1; j >= 0; j--)\n            {\n                //if current id in list is value, remove it\n                if (objs[j].id.Equals(1))\n                {\n                    objs.RemoveAt(j);\n                }\n            }\n\n            //if list is now empty remove dict entry\n            if (objs.Count.Equals(0))\n            {\n                //use linq to grab the element at index and pass it's key to Remove\n                dict.Remove(dict.ElementAt(i).Key);\n            }\n        }	0
21535144	21465032	After opening popup, How do I redirect parent page?	protected void Page_Load(object sender, EventArgs e)\n    {         \n\n       if (autoOpenSSO == true)\n       {\n           ccdetails_Click(this, null);\n       }\n\n    }\n\n    protected void ccdetails_Click(object sender, EventArgs e)\n    {\n        ClientScriptManager cs = Page.ClientScript;\n        try\n        {                \n            string link = getSSOlink(ah1.InstitutionUserID, cardnumber).Trim();\n            string s = "var popupWindow = window.open('" + link + "','_blank', 'width=980,height=600,resizable=yes');";\n            string t = "window.location.replace('" + redirectAddress + "')";\n            if (redirectUser == true)\n            {\n                s = s + t;\n            }\n            cs.RegisterStartupScript(this.GetType(), "PopupScript", s, true);\n\n        }\n\n        catch (Exception se)\n        {\n            LogSystem.LogInfo("Access issue - " + se.ToString());\n\n        }\n    }	0
6291485	6291201	DependencyProperty from string	var descriptor = DependencyPropertyDescriptor.FromName(\n    propertyName,\n    dependencyObject.GetType(),\n    dependencyObject.GetType());\n\n// now you can set property value with\ndescriptor.SetValue(dependencyObject, value);\n\n// also, you can use the dependency property itself\nvar property = descriptor.DependencyProperty;\ndependencyObject.SetValue(property, value);	0
16398342	16398193	How can I get single node data using linq	XDocument xDoc = XDocument.Load("test.XML");\nvar item = xDoc.Descendants("category")\n               .FirstOrDefault(r => r.Element("id").Value == "1");\nif(item == null)\n   return;\n\nstring Name = item.Element("name").Value;\nstring Decription = item.Element("description").Value;\nstring active = item.Element("active").Value;	0
944529	944484	Syntax to access variables in viewstate	private int Status\n{\n  get { return (ViewState["MYSTATUS"] != null) ? (int)ViewState["MYSTATUS"] : 0; }\n  set { ViewState["MYSTATUS"] = value; }\n}	0
23486307	22344671	Change focus by Enter don't work with Telerik RadDropDownList	protected override bool ProcessKeyPreview(ref Message m)\n    {\n        if (m.Msg == 0x0100 && (int)m.WParam == 13)\n        {\n            this.ProcessTabKey(true);\n        }\n        //return base.ProcessKeyPreview(ref m);/////problem was with this line and when changet to following line it works Great !!\n        **return true;** \n    }	0
14044261	13996412	Programmatically Changing ReadOnly Mode on DataGridView Rows	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        //dataGridView1.ReadOnly = true;\n        string[] row1 = new string[] { "test", "test1" };\n        string[] row2 = new string[] { "test2", "test3" };\n        string[] row3 = new string[] { "test4", "test5" };\n        dataGridView1.Columns.Add("1", "1");\n        dataGridView1.Columns.Add("2", "2");\n        dataGridView1.Rows.Add(row1);\n        dataGridView1.Rows.Add(row2);\n        dataGridView1.Rows.Add(row3);\n\n        foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            row.ReadOnly = true;\n        }\n\n        dataGridView1.Rows[1].ReadOnly = false;\n    }\n}	0
11382562	11382268	Exception on XML sorting	XDocument doc = XDocument.Load(filename);\nvar ordered = doc.Descendants("Thing")\n                 .OrderBy(thing => thing.Attribute("ID").Value)\n                 .ToList(); // force evaluation\ndoc.Descendants("Thing").Remove();\ndoc.Descendants("Thungs").Single().Add(ordered);\ndoc.Save(filename);	0
19528250	19527873	WPF AutoCompleteBox multiple fields	class MyClass\n{\n    public int Organization_ID{ get; set; }\n    public string Organization_Names{ get; set; }\n}\n\n<controls:AutoCompleteBox x:Name="autoCompleteBox1"    \n      SelectionChanged="autoCompleteBox1_SelectionChanged"      \n      FilterMode="Contains"              \n      IsTextCompletionEnabled="True">\n    <controls:AutoCompleteBox.ItemTemplate>\n        <DataTemplate>\n            <TextBlock Text="{Binding Organization_Names}" />\n        </DataTemplate>\n    </controls:AutoCompleteBox.ItemTemplate>\n</controls:AutoCompleteBox>\n\nprivate void autoCompleteBox1_SelectionChanged(object sender, RoutedEventArgs e)\n{\n   MessageBox.Show(((MyClass)autoCompleteBox1.SelectedItem).Organization_ID);\n}	0
9761621	9761545	Get data from sql query into textbox	SqlCommand command = new SqlCommand(sqlquery, connection);\nfNameTextBox.Text = command.ExecuteScalar().ToString();	0
22616723	22616687	Latest forums posts by date	TPGForumPost.Select(v => v).OrderByDescending(d => d.dateCreated).Take(5);	0
24179380	24179313	EF - pure join table with three or more fields	Activities\n  .Where(a => a.Client.Id == enteredId)\n  .Where(a => a.User.Id == enteredUserId)	0
1685028	1684987	Linq query from 3 tables using Joiner table	var query = from sb in db.Surfboards\n            join csb in db.CustomerSurfBoards on sb.SurfBoardID equals csb.SurfBoardID\n            join c in db.Customers on csb.CustomerID equals c.CustomerID\n            where c.IsActive\n            select sb;	0
13974755	13974507	How to get a control's GUID	void frmMain_CheckedChanged(object sender, EventArgs e)\n{ \n  CheckBox cb = sender as CheckBox;\n  if (cb != null) {\n    MessageBox.Show("Checked " + cb.Name);\n  }\n}	0
9570500	9570422	Incorporate an unmanaged EXE as resource in a managed C# code	Assembly.Load()	0
2852420	2852197	Exporting winform data to .txt file	using(StreamWriter sw = new StreamWriter(filePath)) {\n    string firstLine = string.Concat("\n", string.Format(@"Customer number: {0}, Customer name: {1}", textBox1.Text, textBox2.Text));\n    string secondLine = string.Format(@"Address: {0}", textBox3.Text);\n\n    sw.WriteLine(firstLine);\n    sw.WriteLine(secondLine);\n\n    // Loop through your DataGridView.Rows or Cells and do the same.\n\n    sw.Flush();\n    sw.Close();\n}	0
7620212	7620108	get List<CustomClass> from Page to User Control	filterControl.Categories.Add(new widgets_filter.Category{ category_id = "", category = ""});	0
20145312	20134831	How to ensure that certain methods are invoked periodically?	class Program\n    {\n        static readonly object Locker = new object();\n        static void Main(string[] args)\n        {\n            var importantThread = new Thread(o =>\n            {\n                while (true)\n                {\n                    lock (Locker)\n                    {\n                        Monitor.Wait(Locker, TimeSpan.FromSeconds(3));\n                        // do something really really important\n\n                        // if some condition return;\n                    }\n                }\n\n            }) {Priority = ThreadPriority.Highest};\n            importantThread.Start();\n\n            Console.ReadKey();\n        }\n    }	0
8928323	8928291	How to print out all the base type of an object?	Type type = obj.GetType();\nwhile (type != null)\n{\n    Console.WriteLine(type.Name);\n    type = type.BaseType;\n}	0
1360807	1360758	Modifying opacity of any window from C#	[DllImport("user32.dll")]\nstatic extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey,byte bAlpha, uint dwFlags);\n\npublic const int GWL_EXSTYLE = -20;\npublic const int WS_EX_LAYERED = 0x80000;\npublic const int LWA_ALPHA = 0x2;\npublic const int LWA_COLORKEY = 0x1;\n\n//set the window style to alpha appearance\nprivate void button4_Click(object sender, EventArgs e)\n{\n    SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED);\n    SetLayeredWindowAttributes(Handle, 0, 128, LWA_ALPHA);\n}	0
15305255	15305076	How to make a rectangle move when PictureBox is resized	oldX, oldY // old coordinates of the rectangle should be saved\noldPictureBoxWidth, oldPictureBoxHeight // should be saved too\n\n//and on the PictureBox Paint event You have the new:\nnewPictureBoxWidth and newPictureBoxHeight\n\n//the new coordinates of rectangle: (resize ratio is in brackets)\nnewX = oldX * (newPictureBoxWidth / oldPictureBoxWidth)\nnewY = oldY * (newPictureBoxHeight / oldPictureBoxHeight)	0
28667408	28667331	What exactly would be a better way of writing a tool that changes the values in an ini file?	Dictionary<string, Dictionary<string,string>> Groups = new...\nstring currentGroupName;\nforeach (string line in File.ReadAllLines(iniFile))\n{\n    if (lineStartsWith("[") && line.EndsWith("]"))\n    {\n        currentGroupName = line.Substring(1, line.Length-2);\n        Groups.Add(currentGroupName, new Dictionary<string,string>());\n    }\n    else if (line.Contains("="))\n    {\n        string[] keyValue = line.Split("=");\n        Groups[currentGroupName].Add(keyValue[0], keyValue[1]);\n    }\n\n}	0
30091180	30068155	Kendo Grid populates and posts all of the navigation properties	Hidden()	0
13044101	13043973	Adding hundreds of Images to pdf using itextsharp	Document doc = new Document(PageSize.A4, 10, 10, 30, 30);\nMemoryStream PDFData = new MemoryStream();\nPdfWriter writer = PdfWriter.GetInstance(doc, PDFData);\ndoc.Open();\n\nPdfPTable table = new PdfPTable(1);\ntable.WidthPercentage = 100F;\n\nImage imgLogo = Image.GetInstance(<image_path>);\nPdfPCell cell1 = new PdfPCell { BorderWidth = 0F,  Padding = 3 };\ncell1.AddElement(imgLogo);\ntable.AddCell(cell1);\n\n//Add your more images.\n\ndoc.Add(table );\ndoc.Close();\n\nwriter.Close();	0
22788618	22788175	Launching a C++ project from a .NET project in Visual Studio 2010	using System.Diagnostics;\n\n// Prepare the process to run\nProcessStartInfo start = new ProcessStartInfo();\n// Enter in the command line arguments, everything you would enter after the executable name itself\nstart.Arguments = "readme.txt"; \n// Enter the executable to run, including the complete path\nstart.FileName = "notepad";\n// Do you want to show a console window?\nstart.WindowStyle = ProcessWindowStyle.Hidden;\nstart.CreateNoWindow = true;\n\n//Is it maximized?\nstart.WindowStyle = ProcessWindowStyle.Maximized;\n\n// Run the external process & wait for it to finish\nusing (Process proc = Process.Start(start))\n{\n     proc.WaitForExit();\n\n     // Retrieve the app's exit code\n     exitCode = proc.ExitCode;\n}	0
12432532	12431087	Get Text from DataGridViewComboxBoxCell	void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n    var comboBox = e.Control as ComboBox;\n    if (comboBox != null)\n    {\n        // remove any handler we may have added previously\n        comboBox.SelectionChangeCommitted -= new EventHandler(comboBox_SelectionChangeCommitted);\n        // add handler\n        comboBox.SelectionChangeCommitted += new EventHandler(comboBox_SelectionChangeCommitted);\n    }\n}\n\nvoid comboBox_SelectionChangeCommitted(object sender, EventArgs e)\n{\n    // Allow current dispatch to complete (combo-box submitting its value)\n    //  then EndEdit to commit the change to the row\n    dgv.BeginInvoke(new Action(() => dgv.EndEdit()));\n}	0
5553971	5553831	Manually add binding at run-time	BasicHttpBinding binding = new BasicHttpBinding();\n        EndpointAddress address = new EndpointAddress("Your uri here");\n\n        ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, address);\n        IContract channel = factory.CreateChannel();\n        channel.YourMethod();\n        ((ICommunicationObject)channel).Close();	0
15245157	15245026	How to remove the exact occurence of characters from a string?	string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";\nvar words = str.Split(',');\nstr = String.Join(",", words.Where(word => word != "phani"));	0
22632526	22571019	how to manual call render TreeView Row xamarin studio c#?	var pth = tv.Model.GetPath (iter);\n        store.EmitRowChanged (pth, iter);	0
11689492	11689309	How to filter a linq to sql query by using textbox input	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        var searchValue = textBox1.Text.Trim();//you can add a ToUpper();\n        var qry = (from p in dc.Products\n                   where p.ProductName.StartsWith(searchValue);//you can add a ToUpper() to p.ProductName\n                   select p).ToList();\n        productDataGridView.DataSource = qry;\n    }	0
22757408	22757248	How to copy files across to a new folder in c# console application	File.Copy(sitemap_path,server_path + "\\newFileName.xml", true);	0
33049515	33049460	How to get RGB values from 24-bit Hex (Without .NET Framework)	long color = 0xaabbcc;\n\nbyte red = (byte)((color >> 16) & 0xff);\nbyte green = (byte)((color >> 8) & 0xff);\nbyte blue = (byte)(color & 0xff);	0
6847878	6843820	PLINQ: how to run a ParallelQuery on more than 4 threads?	Console.WriteLine("{0} threads " ,Process.GetCurrentProcess().Threads.Count);	0
6578412	6577825	Remove SOAP Envelepoe and soap Body element from XMLDOCUMENt	XMLDocument document = ...\n XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);\nnsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");\ndocument.loadxml(document.DocumentElement.SelectSingleNode("soap:Body",nsmgr).ChildNodes[0].OuterXml);	0
5596228	5596198	XML Serialization Parent Elements	public class Microsoft\n{\n    public IList<Office> Office {get; set;}\n}\n\npublic class Office\n{ \n    public Student CurrentStudent {get; set;}\n}	0
12900363	12900162	How do I read and parse data from individual rows?	String linestring = streamreader.ReadLine();\nString[] linetokens = linestring.Split(new String[]{":",","}, StringSplitOptions.None);	0
28051502	28051288	Writing a Byte Array to a text file	Byte[] data = (Byte[])FailData.Properties["VendorSpecific"].Value;\nvar sb = new StringBuilder();\n\nfor (int i = 0; i < data[0] - 1; i++)\n{\n    for (int j = 0; j < 12; j++)\n    {\n        sb.Append(data[i * 12 + j] + "\t");\n    }\n    sb.AppendLine();\n}\nFile.WriteAllText("filename.ext", sb.ToString());	0
9288940	9288763	Selecteditem event in an itemtemplate inside a listbox	private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n    {\n        TextBlock t = (TextBlock)sender;\n        string s= t.Text;\n    }	0
9409991	9393764	Retrieve code from ILGenerator	using Mono.Cecil;\nusing Mono.Cecil.Cil;\n\n[...]\n\n\npublic void Print( ) {\n    AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly( this.module_name );\n\n    int i = 0, j = 0;\n    foreach ( TypeDefinition t in assembly.MainModule.Types ) {\n        if ( t.Name  == "FooClass" ) {\n            j = i;\n        }\n        i++;\n    }\n\n    TypeDefinition type = assembly.MainModule.Types[ j ];\n\n    i = j = 0;\n    foreach ( MethodDefinition md in type.Methods ) {\n        if ( md.Name == "BarMethod" ) {\n            j = i;\n        }\n        i++;\n    }\n\n    MethodDefinition foundMethod = type.Methods[ j ];\n\n    foreach( Instruction instr in foundMethod.Body.Instructions ) {\n        System.Console.WriteLine( "{0} {1} {2}", instr.Offset, instr.OpCode, instr.Operand );\n    }\n}	0
26755956	26715927	Windows phone 8.1 proximity device stop answering after lock screen	if (device!= null)\n{\n            device.StopSubscribingForMessage(id);\n            device= null;\n\n            GC.Collect(2, GCCollectionMode.Forced, true);\n}\n\ndevice= ProximityDevice.GetDefault();\nid = device.SubscribeForMessage("NDEF", ReceivedHandler);	0
752731	752303	Update a record in Linq2Sql with an object of the recordType	public bool updateEvent(clubEvent newEvent)\n    {\n        tCon.clubEvents.Attach(newEvent);\n        tCon.Refresh(RefreshMode.KeepCurrentValues, settings)\n        tCon.SubmitChanges();\n        return true;\n    }	0
2044447	2044426	C# / LINQ / get all elements of sub-collection matching a condition?	var result = Items.Where( y => y.MyProperty );\n\nvar biggerResult = x_collection.SelectMany( x => x.Items.Where( y => y.MyProperty ) );	0
24806137	24805798	how to split string into two strings when it finds a number	string a = "aaa333aaa333aaa22bb22bb1c1c1c";\n\n    List<string> result = new List<string>();\n\n    int lastSplitInedx = 0;\n    for (int i = 0; i < a.Length-1; i++)\n    {\n        if (char.IsLetter(a[i]) != char.IsLetter(a[i + 1]))\n        {\n            result.Add(a.Substring(lastSplitInedx, (i + 1) - lastSplitInedx));\n            lastSplitInedx = i+1;\n        }\n        if (i+1 == a.Length-1)\n        {\n            result.Add(a.Substring(lastSplitInedx));\n        }\n    }\n\n    foreach (string s in result)\n    {\n        Console.WriteLine(s);\n    }	0
7770395	7769365	Increase rate of movement	timer1.Interval=1;	0
5413861	5413803	How can I save an enumeration value to a database?	Permission enumValue = (Permission)intValue;	0
13785332	13785282	Detecting property changes on a datacontext	public partial class MainWindow : Window\n{\n\n    public MainWindow()\n    {\n        DataContext = new MyViewModel();\n    }\n\n    private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        MyViewModel viewModel = DataContext as MyViewModel;\n        viewModel.PropertyChanged += MyPropertyChangedEventHandler;\n        viewModel.NotifyPropertyChanged();\n    }\n\n    private void MyPropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)\n    {\n        Console.WriteLine(e.PropertyName);\n    }\n\n}\n\npublic class MyViewModel : INotifyPropertyChanged\n{\n    public void NotifyPropertyChanged()\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs("MyTestPropertyName"));\n        }\n    }\n\n    #region INotifyPropertyChanged Members\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    #endregion\n}	0
19185164	19183566	How to create a program that converts from Euro to Peso and vice versa?	class Program\n{\n    static void Main(string[] args)\n    {\n        double value, peso, euro;\n        Console.Write("Enter the value: ");\n\n        value = double.Parse(Console.ReadLine());\n\n        Console.WriteLine("The value is = {0} peso", peso = ValueToPeso(value));\n        Console.WriteLine("The value is = {0} euro", (euro = ValueToEuro(value)).ToString("f2"));\n    }\n\n    // convert value to Peso\n    public static double ValueToPeso(double value)\n    {\n        return value * 17;\n    }\n\n    // convert value to Euro \n    public static double ValueToEuro(double value)\n    {\n        return value / 17;\n    }\n}	0
25759171	25758767	Calculate point on a B?zier curve according to t	/// <summary>\n    /// Calculate a bezier height Y of a parameter in the range [start..end]\n    /// </summary>\n    public static double CalculateBezierHeightInInterval(double start, double end, double param, double y1, double y2, double y3, double y4)\n    {\n        return CalculateBezierHeight((param - start) / (end - start), y1, y2, y3, y4);\n    }\n\n    /// <summary>\n    /// Calculate a bezier height Y of a parameter in the range [0..1]\n    /// </summary>\n    public static double CalculateBezierHeight(double t, double y1, double y2, double y3, double y4)\n    {\n        double tPower3 = t * t * t;\n        double tPower2 = t * t;\n        double oneMinusT = 1 - t;\n        double oneMinusTPower3 = oneMinusT * oneMinusT * oneMinusT;\n        double oneMinusTPower2 = oneMinusT * oneMinusT;\n        double Y = oneMinusTPower3 * y1 + (3 * oneMinusTPower2 * t * y2) + (3 * oneMinusT * tPower2 * y3) + tPower3 * y4;\n        return Y;\n    }	0
30188917	30188433	Unity3d Local Forward	Rigidbody player = GetComponent<Rigidbody>(); // I really hope you're not doing this every frame, btw\nfloat speed = 2f; // magic numbers are bad, move them to variables, at least\nVector3 movement = transform.forward * speed * Time.deltaTime;\nplayer.MovePosition(transform.position + movement);	0
13816735	13702750	add rule to jQuery validate from code behind	ScriptManager.RegisterClientScriptBlock	0
2051362	2051325	Getting records from between Date X and Date Y from my Access database?	OleDbCommand command = new OleDbCommand(\n    "SELECT * FROM Recharge " + \n    "WHERE Account=@Account and " + \n    "RechargeDate between @RechargeDateStart AND @RechargeDateEnd");\ncommand.Parameters.AddWithValue("@Account", comboBox1.Text);\ncommand.Parameters.AddWithValue("@RechargeDateStart",dateTimePicker1.Value.Date);\ncommand.Parameters.AddWithValue("@RechargeDateEnd"  ,dateTimePicker2.Value.Date);	0
4283856	4283717	Using Regex to replace standalone characters	&(?!amp;)	0
16351961	16351929	Identity cards number validation	string str = "124456789X";\nif ((str.Count(char.IsDigit) == 9) && // only 9 digits\n    (str.EndsWith("X", StringComparison.OrdinalIgnoreCase)\n     || str.EndsWith("V", StringComparison.OrdinalIgnoreCase)) && //a letter at the end 'x' or 'v'\n    (str[2] != '4' && str[2] != '9')) //3rd digit can not be equal to 4 or 9\n{\n    //Valid\n\n}\nelse\n{\n    //invalid\n}	0
8008315	7973480	DataMethod Parameters in SSRS	public static System.Data.DataTable GetContactList(string[] _county){\n    var ranges = new Dictionary<string, object>\n    {\n      {"ContactPerson.1.County", _county}\n    };\n    var dt = Microsoft.Dynamics.Framework.Reports.AxQuery.ExecuteQuery("Select   ContactPerson.1.Name, ContactPerson.1.County from Contactsquery", ranges);\n    return dt;\n}	0
3373843	3373835	Convert string to specific DateTime format	Label1.Text = startTime.ToString("MM/dd/yyyy hh:mmtt");	0
23103181	23103111	DeSerialize Json into Class object	var root = JsonConvert.DeserializeObject<RootObject>(json);	0
5601405	5601397	How to check for null before I use in linq?	myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();	0
16022691	16022469	Using two instances of a custom method results in 'call is ambiguous'	string specialty_code = new GetSpecialtyCode(element);	0
14495503	14495430	allow only one record per date with LOCK	object thisLcok = new object();\nlock (thisLcok)\n{\n    ...\n}	0
13365396	13365007	how to access programmatically to "print preview and print" page in Office Word 2010	SendKeys.Send("^P");	0
28582894	28582590	How to fill combobox with database values with method from DAL	DAL dl=new DAL()\nDatatable dt=DAL.fillDeptCombo()\ncombobox.datasource=dt;\ncombobox.valuemember="deptID" //replace this with your value\ncombobox.displayMember="DeptName" //replace this with your text	0
14252751	14252717	data type casting in Linq to Sql	SqlFunctions.StringConvert((double) t1.field2)	0
31677372	31677305	DateTime ParseExact conversion increasing month by 1	var d = DateTime.ParseExact("7/22/2015 8:08:01 PM", "M/d/yyyy h:m:s tt", CultureInfo.InvariantCulture);	0
1721827	1437146	how to SelectSingleNode in to XmlDataSource?	xNode2.SelectNodes("child::*")	0
34418747	34418425	Update multiple rows in DataGridView C#	private void button1_Click(object sender, EventArgs e)\n{\n    cn.Open();\n    SqlCommand cmd = new SqlCommand(@"UPDATE MEDICINE_REGISTRATION \n                                     SET stock = @RStock \n                                     WHERE id= @id", cn);\n\n    cmd.Parameters.Add("@RStock", SqlDbType.VarChar).Value = "";\n    cmd.Parameters.Add("@id", SqlDbType.Integer).Value = 0;  \n\n    foreach (DataGridViewRow row in Order_Datagridview.Rows)\n    {\n        // Use the row indexer here, not the fixed row at index zero\n        cmd.Parameters["@RStock"].Value = row.Cells["RStock"].Value.ToString();\n        cmd.Parameters["@id"].Value = Convert.ToInt32(row.Cells["id"].Value);\n        cmd.ExecuteNonQuery();\n    }\n    cn.Close();}\n}	0
19833327	19832591	How to invoke a control within a class	public class WebSync\n{\n    private System.Timers.Timer _tmrManifestHandler = new System.Timers.Timer();\n    public WebSync(object id)\n    {\n        _tmrManifestHandler.Elapsed += new System.Timers.ElapsedEventHandler(_tmrManifestHandler_Tick);\n        _tmrManifestHandler.Interval = 100;\n        _tmrManifestHandler.Enabled = false;\n    }\n\n    public delegate void delBeginSync();\n    public event delBeginSync evBeginSync;\n\n    public void PreConnect()\n    {\n        while (true)\n        {\n            if (true /* just for testing*/)\n            {\n                evBeginSync();\n                return;\n            }\n        }\n    }\n\n    public void Connect()\n    {\n        _tmrManifestHandler.Enabled = true;\n        _tmrManifestHandler.Start();\n    }\n\n    private void _tmrManifestHandler_Tick(object sender, EventArgs e)\n    {\n        //NOT BEING 'HIT'\n    }\n}	0
21223719	21223120	Suggestions on a method?	class Flight\n    {\n\n        public string Consonants(string direction)\n        {\n            string[] words = direction.Split('-');\n            // check if the separator is missing\n            if (words.Length!=2) return string.Empty; //missing separator error\n\n            return string.Format("{0}-{1}", Replacer(words[0]),  Replacer(words[1]));\n        }\n        private string Replacer(string arg)\n        { \n            string abr= arg.ToUpper().Replace("A", string.Empty).Replace("E", string.Empty).Replace("I", string.Empty).Replace("O", string.Empty).Replace("U", string.Empty);\n            if (abr.Length < 2)\n                throw new Exception(string.Format("processing error in Replacer input {0} outpur {1}", arg, abr)); // example if you pass: UAE\n\n            return string.Format("{0}{1}", abr[0], abr[abr.Length - 1] );\n        }\n\n    }	0
16738222	16737234	Filtering results of Lucene search	Filter fil= new QueryWrapperFilter(new TermQuery( new Term(field, "5/12/1998")));\nvar hits = indexSearcher.Search(QueryMaker(searchString, searchfields), fil);	0
23898767	23898385	getting value from a list contained within a dictionary value	foreach (KeyValuePair<int, ListClass> pair in MyDictionary)\n{\n    var eighthValue = pair.Value.MyList[7];\n}	0
14842588	14842546	C# repeat button action	Timer timer = new Timer();\n\ntimer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called\ntimer.Interval = (1000) * (10);             // Timer will tick evert 10 seconds\ntimer.Enabled = true;                       // Enable the timer\ntimer.Start();	0
17732303	17732258	Two queries, one view	public class TheViewModel\n{\n    public List<MyApp.Models.Products> Item1 { get; set; }\n    public MyApp.Models.Products Item2 { get; set; }\n}	0
8068912	8062005	How to register open generic type by interface with Castle Windsor?	IncludeNonPublicTypes()	0
6347963	6333300	Exception while trying to load a Berkeley DB DLL	msvcrtd.dll	0
12869609	12869557	Turn Direction for Target Heading	double hdgDiff (double h1, double h2) { // angle between two headings\n   const double diff = fmod(h1 - h2 + 3600, 360);\n   return diff <= 180 ? diff : 360 - diff;\n}\n\nbool isTurnCCW(double hdg, double newHdg) { // should a new heading turn left ie. CCW?\n   const double diff = newHdg - hdg;        // CCW = counter-clockwise ie. left\n   return diff > 0 ? diff > 180 : diff >= -180;\n}	0
31486753	31486287	Sort a DataTable on converted value of a column	dt = dt.Rows.Cast<DataRow>().OrderBy(row => Convert.ToDecimal(row["Price"])).CopyToDataTable();	0
27640477	27637015	sending data when clicking a row in GridView that redirects to another page	foreach (DataRow row in ds.Tables[0].Rows) {\n   ItemImageName = row["ItemName"].ToString();\n   files.Add(new ListItem(ItemImageName,"~/UploadedItems/" + fileName));\n   //files.Add(new ListItem(ItemImageName, "~/UploadedItems/" + fileName));\n}	0
7770868	7770647	How can I get the Status element from the following XML?	var stat = (from n in _xml.Descendants() where n.Name.LocalName == "Status" select n).ToList();	0
1064907	1064901	Random Number Between 2 Double Numbers	public double GetRandomNumber(double minimum, double maximum)\n{ \n    Random random = new Random();\n    return random.NextDouble() * (maximum - minimum) + minimum;\n}	0
10338973	10338266	Getting unique values using Linq to Entities	List<string> carriers = _inventoryContext.Items.GroupBy(i => i.Carrier)\n                                               .Select(i => i.Key)\n                                               .ToList();	0
17043619	17041707	Entity Framework: Many-to-many relationship with self	HasMany(x => x.Referals).WithMany(x => x.Encapsulated).Map(c =>\n            {\n                c.ToTable("DataFieldJoin");\n                c.MapLeftKey("RefId");\n                c.MapRightKey("EncapId");\n            });	0
3805443	3805120	db4o, how to update an object if a field was added?	IObjectContainer container = ...\nvar persons = from Person p in container                  \n              select p;\n\nforeach(var p in persons){\n     p.NewField = true; // new value\n     container.Store(p);\n}\n\n// done	0
8756661	8755623	I wrote an asynchronous class, but I don't kown how to optimize it	private void button1_Click(object sender, EventArgs e) {\n        string value = "aaaaaa";\n        this.Invoke(new Action(() => test4(value, "bbbbbbbb", "cccccccc")));\n    }	0
7016103	7015999	How to get a random integer in given boundaries equal to a given number with a given chance?	Random r = new Random();\nif (r.Next(100) >= chance)\n    return x;\nvar tmp = r.Next(min, max); // take one less than max to "exclude" x\nif (tmp >= x)               // shift up one step if larger than or equal to the exceluded value\n    return tmp + 1;\nreturn tmp;	0
18151218	18150769	data not being save with crlf so it's all one line	dataGridView1.Columns["Message"].DefaultCellStyle.WrapMode = \n                                                      DataGridViewTriState.True;	0
10643263	10640930	Seeking & reading arbitrary file data in Metro	using (var fs = await file.OpenAsync(FileAccessMode.Read))\n        {\n            using (var inStream = fs.GetInputStreamAt(0))\n            {\n                using (var reader = new DataReader(inStream))\n                {\n                    await reader.LoadAsync((uint)fs.Size);\n                    string data = reader.ReadString((uint)fs.Size);\n                    reader.DetachStream();\n                    return data;\n                }\n            }\n        }	0
22890774	22890614	C# - How to pass/skip over data in an array	double n;\nforeach (string line in File.ReadAllLines("test.txt"))\n    {\n        string[] fields = line.Split(',');\n        bool ageIsNumeric = double.TryParse(fields[0], out n);\n        bool districtIsNumeric = double.TryParse(fields[3], out n);\n        if(!ageIsNumeric || !districtIsNumeric)\n            continue;\n        ageData[i] = int.Parse(fields[0]);          \n        districtDataA[i] = int.Parse(fields[3]);	0
28854896	28854194	How to refer to the type of the current class from a static method in C#	public abstract class Base\n{\n    protected static void InitializeTaggedFields(Type aType)\n    {\n        // aType will be of the instantiated type:\n        // When a "StoreThis" is instantiated,\n        // aType.Equals(typeof(StoreThis)) is true,\n        // if a "StoreThat" was instatiated\n        // aType.Equals(typeof(StoreThat)) is true.\n        // etc, etc.\n    }\n\n    public Base()\n    {\n        InitializeTaggedFields(this.GetType());\n    }\n}\n\n// User defined custom class inheriting my Base class\npublic class StoreThis : Base\n{\n    public StoreThis()\n    {\n    }\n}\n\npublic class StoreThat : Base\n{\n    public StoreThat()\n    {\n    }\n}	0
32322103	32310072	Triggering a DTS package in the Integration Services catalogs using C#	Declare @execution_id bigint\nEXEC [SSISDB].[catalog].[create_execution] @package_name=N'PackageName.dtsx', @execution_id=@execution_id OUTPUT, @folder_name=N'YourSSISFirstFolderName', @project_name=N'YourSSISProjectName', @use32bitruntime=False, @reference_id=Null\nSelect @execution_id\n\nDECLARE @var0 sql_variant = N'SomeVariableValue'\nEXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=20, @parameter_name=N'SomePackageParameterName', @parameter_value=@var0\n\nDECLARE @var1 smallint = 1\nEXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id,  @object_type=50, @parameter_name=N'LOGGING_LEVEL', @parameter_value=@var1\nEXEC [SSISDB].[catalog].[start_execution] @execution_id\nGO	0
19723630	19723583	MySql - Remove data after 3 months	delete from history\nwhere start_date < DATE_SUB(now(), interval 3 month)	0
2710147	2710018	WPF, Setting property with single value on multiple subcontrols	public class MyControl {\n\n    // be prepared for some dependency property hell below\n    // this defines a DependencyProperty whose value will be inherited\n    // by child elements in the visual tree that do not override\n    // the value. An example of such a property is the FontFamily\n    // property. You can set it on a parent element and it will be\n    // inherited by child elements that do not override it.\n\n    public static readonly DependencyProperty MyInheritedProperty =\n        DependencyProperty.Register(\n            "MyInherited",\n            typeof(string),\n            typeof(MyControl),\n            new FrameworkPropertyMetadata(\n                null,\n                FrameworkPropertyMetadataOptions.Inherits\n            )\n        );\n\n}	0
2507084	2506942	Convert Delphi Real48 to C# double	private static double Real48ToDouble(byte[] real48)\n    {\n\n        if (real48[0] == 0)\n            return 0.0; // Null exponent = 0\n\n        double exponent = real48[0] - 129.0;\n        double mantissa = 0.0;\n\n        for (int i = 1; i < 5; i++) // loop through bytes 1-4\n        {\n            mantissa += real48[i];\n            mantissa *= 0.00390625; // mantissa /= 256\n        }\n\n\n        mantissa += (real48[5] & 0x7F);\n        mantissa *= 0.0078125; // mantissa /= 128\n        mantissa += 1.0;\n\n        if ((real48[5] & 0x80) == 0x80) // Sign bit check\n            mantissa = -mantissa;\n\n        return mantissa * Math.Pow(2.0, exponent);\n    }	0
6762490	6762376	UPSERT into table with dynamic table name	create table so_test(pk number not null primary key, value varchar2(20));\n\ninsert into so_test(pk, value) values(1, 'one');\n\ndeclare\n  l_SQL varchar2(4000);\n  l_tablename varchar2(4000) default 'so_test';\nbegin\n  l_SQL := 'merge into ' || l_tablename || ' target' ||\n    ' using (select 1 pk, ''eins'' value from dual union all\n             select 2 pk, ''zwei'' value from dual) source\n      on (target.pk = source.pk)\n      when matched then \n        update set target.value = source.value\n      when not matched then\n        insert values(source.pk, source.value)      \n  ';\n  dbms_output.put_line(l_sql);\n  execute immediate l_SQL;\nend;	0
4560119	4560066	IronPython/C# Float data comparison	void Main()\n{\n    object value1 = 1234.5F;\n    object value2 = 1234.5F;\n    Console.WriteLine(AreEqual(value1, value2));\n    Console.WriteLine(AreEqual((float)value1, (float)value2));\n}\n\nbool AreEqual(object value1, object value2) {\n    return value1 == value2;\n}\n\nbool AreEqual(float value1, float value2) {\n    return value1 == value2;\n}	0
12104958	12104786	Exporting data to excel in C# with comma delimited issue	...Append(item.Week2).Append("\",\"").Append(item.Week1).Append("\"").Append(Environment.NewLine);	0
16928680	16924111	How do I access the location of a file in RoleEnvironment.GetLocalResource on the client side	using System.Web;\n\nnamespace HandlerExample\n{\n   public class MyHttpHandler : IHttpHandler\n   {\n      public void ProcessRequest(HttpContext context)\n      {\n        // Get the file from azure storage here and return it using context.Response\n      }\n\n      public bool IsReusable\n      {\n         get { return true; }\n      }\n   }\n}	0
4763681	4763611	Replace multiple words in string	// Define name/value pairs to be replaced.\nvar replacements = new Dictionary<string,string>();\nreplacements.Add("<Name>", client.FullName);\nreplacements.Add("<EventDate>", event.EventDate.ToString());\n\n// Replace\nstring s = "Dear <Name>, your booking is confirmed for the <EventDate>";\nforeach (var replacement in replacements)\n{\n   s = s.Replace(replacement.Key, replacement.Value);\n}	0
5778898	5778823	C# Number to BitMask32 to Values	var val = 513;\nfor(var pos=0;;pos++)\n{\n    var x = 1 << pos;\n    if(x > val) break;\n    if((val & x) == x)\n    {\n        Console.WriteLine(pos);\n    }\n}	0
16742067	16742008	Loop through ado.net sql select to add more rows to datatable	var parameters = new string[PID.Length];\nvar selectAll = new SqlCommand();\n\nfor (int i = 0; i < PID.Length; i++)\n{\n    parameters[i] = string.Format("@Age{0}", i);\n    selectAll .Parameters.AddWithValue(parameters[i], PID[i]);\n}\n\nselectAll.CommandText = string.Format("SELECT * from Property p WHERE p.id IN ({0})", string.Join(", ", parameters));\nselectAll.Connection = connString;\n\nconnString.Open();\n\nSqlDataAdapter adapter = new SqlDataAdapter();\nadapter.SelectCommand = selectAll;\nDataSet ds = new DataSet();\nadapter.Fill(ds);\n\nconnString.Close();\nDataTable table = ds.Tables[0];	0
25434816	25434815	How can I allow cancellation of running work with the IScheduler.SchedulePeriodic method of Rx in .NET 4	public static IDisposable SchedulePeriodic(\n    this IScheduler scheduler,\n    TimeSpan interval,\n    Action<CancellationToken> work) {\n\n    if (scheduler == null) {\n        throw new ArgumentNullException("scheduler");\n    }\n    if (work == null) {\n        throw new ArgumentNullException("work");\n    }\n\n    var cancellationDisposable = new CancellationDisposable();\n\n    var subscription = scheduler.SchedulePeriodic(\n        interval,\n        () => {\n            try {\n                work(cancellationDisposable.Token);\n            } catch (OperationCanceledException e) {\n                if (e.CancellationToken != cancellationDisposable.Token) {\n                    // Something other than the token we passed in threw this exception\n                    throw;\n                }\n            }\n        });\n\n    return new CompositeDisposable(cancellationDisposable, subscription);\n}	0
30664467	30642348	Bulk insert to ElasticSearch with NEST	ElasticType(IdProperty = "<fieldName>")]\n    public class ClassName\n    {	0
22734108	22734011	How to stop unwanted reoccurence using @foreach in MVC4	string[] departureAirports = new string[3] { "Edinburgh,EDI", "London,LTN", "Manchester,MAN" };\nforeach (string airport in departureAirports)\n{\n    string[] data=airport.Split(',');    \n    destinationList.Add(new Destination() { departureName = data[0], departureCode=data[1]});\n}\n\nreturn View(destinationList);	0
7204589	7201495	How do I limit user input in a combobox, So that u can only type words that are within the collection?	ComboBox.IsEditable	0
1956004	1955977	Insert binary data into SQL from c# without a stored procedure	String.Format("update A set B = 0x{0} where C = D", BitConverter.ToString(b.Replace("-", ""))	0
9408204	9407980	Header Message in Flat File Destination	eid, ename, salary	0
2322589	2322575	How do I remove backslashes from URLs?	url = url.Replace("\\", "")	0
31983704	31983580	Format Diffrence time between two DateTime objects	EndTime.Subtract(StartDate).ToString("hh\\:mm\\:ss");	0
29354545	29354354	wpf custom control local property binding - SOLVED	public static readonly DependencyProperty RoomProperty =\n    DependencyProperty.Register(\n        "Room", typeof(RoomData), typeof(RoomAndPersonsAccommodationItem),\n        new FrameworkPropertyMetadata(null)); \n\npublic RoomData Room\n{\n     get { return (RoomData)GetValue(RoomProperty); }\n     set { SetValue(RoomProperty, value); }\n}	0
7134295	7125144	Implementing TEA algorithm using BouncyCastle	e.Init(true, new KeyParameter(Encoding.UTF8.GetBytes("MyPassword123456")));	0
2640518	2640306	How to get DataTable to serialize better?	DataSet ds = new DataSet("Records");\n    DataTable dt = new DataTable("Person");\n    ds.Tables.Add(dt);\n    dt.Columns.Add("ID");\n    dt.Columns.Add("Name");\n\n    dt.Rows.Add(new object[] { 1, "Jack" });\n    dt.Rows.Add(new object[] { 2, "Frank" });\n\n    StringWriter sw = new StringWriter();\n    dt.WriteXml(sw);\n\n    MessageBox.Show(sw.ToString());	0
1019158	1018026	Limit the number of results in a Nested ASP.NET ListView	protected void uxListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n    if (e.Item.ItemType == ListViewItemType.DataItem)\n    {\n        ListViewDataItem item = (ListViewDataItem)e.Item;\n\n        // Get the bound object (KeyValuePair from the dictionary)\n        KeyValuePair<string, List<int>> nestedIntegerList = (KeyValuePair<string, List<int>>)item.DataItem;\n\n        // Get our nested ListView for this Item\n        ListView nestedListView = (ListView)e.Item.FindControl("uxNestedListView");\n\n        // Check the number of items\n        if (nestedIntegerList.Value.Count > 5)\n        {\n            // There are more items than we want to show, so show the "More..." button\n            LinkButton button = (LinkButton)item.FindControl("uxMore");\n            button.Visible = true;\n        }\n\n        // Bind the nestedListView to wahtever you want \n        nestedListView.DataSource = nestedIntegerList.Value.Take(5);\n        nestedListView.DataBind();\n    }\n}	0
33174910	33172995	AutoMapper populate other properties based on another one	Mapper.CreateMap<ObjectViewModel, ObjectModel>()\n        .ForMember(dest => dest.CLI_Isn, src => src.Ignore())\n        .ForMember(dest => dest.EMP_Isn, src => src.Ignore())\n      .ReverseMap();	0
11364840	11364773	Send a reference to a variable instead of it's value	public static bool Count(ref int Progress, int CountToWhat)	0
25443990	25443947	Push the current ItemsSource of a DataGrid to a stack	Stack<object>	0
23891400	23891263	ASP.NET Validator for multiple fields	Custom Validator	0
748071	747991	List all DLL's implementing a specific interface from the GAC	foreach (var type in assembly.GetTypes())\n{\n    var myInterfaceType = typeof(IMyInterface);\n    if (type != myInterfaceType && myInterfaceType.IsAssignableFrom(type))\n    {\n        Console.WriteLine("{0} implements IMyInterface", type);\n    }\n}	0
34281182	34280885	Displaying rich text email in WPF RichTextBox	public void SetRTFText(string text)\n{\n    MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text));\n    this.mainRTB.Selection.Load(stream, DataFormats.Rtf);\n}	0
15851467	15851417	How could I use LINQ to filter out strings starting with a variety of sub-strings?	List<string> exceptions = new List<string>() { "AA", "EE" };\n\n List<string> lines = new List<string>() { "Hello", "AAHello", "BHello", "EEHello" };\n\n var result = lines.Where(x => !exceptions.Any(e => x.StartsWith(e))).ToList();\n // Returns only "Hello", "BHello"	0
7662435	7662360	get values from several dropdownlists	if (item.Selected)\n{\n    DropDownList ddlTimePeriod = (DropDownList) dllPanel.FindControl(item.Text);\n\n    // now use ddlTimePeriod.SelectedItem.Text, ddlTimePeriod.SelectedItem.Value\n\n    cmdTimeToCall.Parameters.Clear();\n    cmdTimeToCall.Parameters.Add("PersonId", personid);\n    cmdTimeToCall.Parameters.Add("DayOfWeekId", Convert.ToInt32(item.Value));\n    cmdTimeToCall.Parameters.Add("TimeToCallId", --VALUE FROM DROPDOWNLIST OF CORRESPONDING ITEM --);\n\n}	0
8752447	8751985	Tables and cells in Word document created by C# - how to change color of only one border?	oTable.Cell(0, 0).Select(); //select the cell\n//set up the left, right and top borders invisible (may be you don't need to do that)\n            oTable.Range.Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.wdLineStyleNone;\n            oTable.Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.wdLineStyleNone;\n            oTable.Range.Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wdLineStyleNone;\n\n//set up the bottom border blue\n            oTable.Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle;\n            oTable.Range.Borders[WdBorderType.wdBorderBottom].LineWidth = WdLineWidth.wdLineWidth050pt;\n            oTable.Range.Borders[WdBorderType.wdBorderBottom].Color = WdColor.wdColorBlue;	0
32686809	32352923	Reducing ZedGraph margin	float leftMargin = 10;\nfloat rightMargin = 10;\nfloat topMargin = 10;\nfloat bottomMargin = 5;\nfloat width = 1920;\nfloat height = 1080;\ngraphPane.Chart.Rect = new RectangleF(leftMargin, topMargin, width - leftMargin - rightMargin, height - topMargin - bottomMargin);	0
24285880	24281315	How to display html text in DevExpress.XtraEditors.RichTextEdit?	richTextEdit.Properties.DocumentFormat = DevExpress.XtraRichEdit.DocumentFormat.Html;\nrichTextEdit.Text = htmlString;	0
6148822	6148740	XDocument get all nodes with attributes	string xml = @"<parameters>\n  <source value=""mysource"" />\n  <name value=""myname"" />\n  <id value=""myid"" />\n</parameters>";\n\nvar doc = XDocument.Parse(xml);\nIDictionary dict = doc.Element("parameters")\n  .Elements()\n  .ToDictionary(\n    d => d.Name.LocalName, // avoids getting an IDictionary<XName,string>\n    l => l.Attribute("value").Value);	0
7967620	7967579	Do I need to use { get; set; } with c# fields that have no special actions when getting and setting	{ get; set; }	0
12226177	12225875	How can I set the default visibility of the main Winform	bool showForm = false;\n\nprotected override void SetVisibleCore(bool value)\n{    \n   base.SetVisibleCore(showForm);\n}	0
3081919	3081916	Convert int to string?	string myString = myInt.ToString();	0
6519026	6518886	How to check if any row is selected from GridView?	if (GridView1.SelectedValue != null)\n{\n     //Row is Selected\n}	0
6372452	6207816	How to define a PrimaryKeyPair for the database in C# (MVC)	HasKey(m => { m.MaterialID, m.ListID });	0
16159523	16159281	Outputting a text file	var toFile = Path.Combine(@"C:\Users\msilliman11\", \n    string.Format("Average{0}.txt", DateTime.Now.ToString("yyyyMMdd")));\nvar dt = DateTime.Now;\nusing (var fs = File.OpenWrite(toFile))\nusing (TextWriter sw = new StreamWriter(fs))\n{\n    sw.Write(string.Join(",", \n        "NA", \n        dt.Hour, \n        dt.Minute, \n        dt.Day,\n        dt.Month,\n        dt.Year,\n        "ALTEST ",\n        "ALTEST ",\n        heatgrade, \n        "    ",\n        "        ", \n        heatname,\n        DT2.Columns[3],\n        heatgrade,\n        "OE2",\n        string.Empty,\n        string.Empty,\n        string.Empty,\n        string.Empty,\n        string.Empty,\n        string.Empty,\n        string.Empty,\n        " ",\n        ","));\n\n    foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))\n    {\n        writeIt.Write(pair.B.ToString() + "," + pair.A.ToString() + ",");\n    }\n}	0
26687949	26687906	Find only child nodes in TreeView C#	List<TreeNode> children = new List<TreeNode>();\n\n foreach(TreeNode node in  TV.Nodes) collectChildren(node);\n\n void collectChildren(TreeNode node)\n {\n    if (node.Nodes.Count == 0) children.Add(node) \n    else  foreach(TreeNode n in node.Nodes) collectChildren(n);\n }	0
21939650	21938920	How to parse / deserialize JSON returned from rest service in C#	var jsonobject = JsonConvert.DeserializeObject<RootObject>(json);\n\npublic class Patient\n{\n    public string patientid { get; set; }\n    public string name { get; set; }\n    public string status { get; set; }\n    public string start { get; set; }\n    public string last { get; set; }\n    public string engagement { get; set; }\n    public string drug { get; set; }\n    public string adherence { get; set; }\n    public string vitals { get; set; }\n    public string last_appointment { get; set; }\n    public string next_appointment { get; set; }\n}\n\npublic class Patients\n{\n    public List<Patient> patient { get; set; }\n}\n\npublic class Pathway\n{\n    public Patients patients { get; set; }\n}\n\npublic class RootObject\n{\n    public Pathway pathway { get; set; }\n}	0
27943201	27942982	LINQ to XML attributes	var result= xdoc.Descendants("image")\n                .Where(x => x.Attribute("size").Value == "large")\n                .Select(x => new User{ Image =  x.Value });	0
17219236	17219180	Alternative to using a ternary operator in Lambda	PhoneNumber = x.PhoneNumbers.Select(pn => pn.PhoneNumber).FirstOrDefault() ?? "",	0
5440562	5420803	Pass nested lists from View to Controller using viewmodels	[HttpPost]\npublic ActionResult EditMonth( EditViewModel model )\n{...	0
21117989	20371313	How to access Sitecore field in Javascript?	var script = String.Format("<script>(function (i, s, o, g, r, a, m) {{i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {{(i[r].q = i[r].q || []).push(arguments)}}, i[r].l = 1 * new Date(); a = s.createElement(o),m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)}})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');ga('create', '{0}', 'auto');ga('send', 'pageview');</script>", Sitecore.Context.Item.Fields["Google Analytics ID Field"]	0
17858438	17858354	Binding data to Template Field in Asp.net	NavigateUrl='<%# String.Format("Default.aspx?id={0}&nextParam={1}", Eval("ID"), Eval("NextColumn")) %>'	0
9213577	9164380	Accessing row items in DataGrid_LoadingRow eventhandler	DataGridRow row = e.Row;\nDataRowView rView = row.Item as DataRowView\nif(rView != null && rView.Item["AssemblySummary"].ToString().Contains("Class"))\n    row.ToolTip = "Class definition...";	0
20888493	20885588	The ability to check the value entered in the custom property using try-catch	private int timeDisplayTip;\n[CategoryAttribute("My properties")]\npublic string TimeDisplayTip\n{\n    get\n    {\n        return timeDisplayTip.ToString();\n    }\n    set\n    {\n        try\n        {\n            if (Convert.ToInt32(value).ToString() != value.ToString())\n                throw new FormatException();\n\n            timeDisplayTip = Convert.ToInt32(value);\n        }\n        catch (Exception e)\n        {\n            MessageBox.Show(e.Message.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);\n        }\n    }\n}	0
1736500	1736494	can you test for a range of values in an IF statement	if((userChoice >= 0 && userChoice <= 32) || userChoice == 99)\n{\n     // do stuff\n}	0
18811333	18810693	DataGridView Backcolors	foreach (DataGridViewRow row in yourDataGridView.Rows)\n        {\n            if (row.Cells[LastColumnIndex].Value == YourValue)\n            {\n                row.Cells[LastColumnIndex].Style.BackColor = Color.Red;\n            }\n        }	0
34403074	34403018	Return a value or null using LINQ in one line?	var item = ll.Fields\n    .Where(x => x.FieldTitle == "Loan Amount")\n    .Select(x => (double?)double.Parse(x.Value))\n    .FirstOrDefault();	0
5833840	5833722	Cast elements on an array of unknown types by using reflection in C#	string[] stringArray = fileContent["Key1"].Value as string[];\nif (stringArray != null) {\n    // the object is a string[] type, it is safe to use the stringArray variable\n}\n\n// and continue for other types that may be stored in the dictionary	0
3624357	3624332	How do you remove all the alphabetic characters from a string?	Regex.Replace(s, "[^0-9.]", "")	0
6496819	6496718	define a web request for the specified URL	WebResponse webResponse = req.GetResponse();	0
1253737	1253725	Convert IEnumerable to DataTable	public static DataTable ToDataTable<T>(this List<T> items)\n{\n    var tb = new DataTable(typeof(T).Name);\n\n    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n    foreach(var prop in props)\n    {\n        tb.Columns.Add(prop.Name, prop.PropertyType);\n    }\n\n     foreach (var item in items)\n    {\n       var values = new object[props.Length];\n        for (var i=0; i<props.Length; i++)\n        {\n            values[i] = props[i].GetValue(item, null);\n        }\n\n        tb.Rows.Add(values);\n    }\n\n    return tb;\n}	0
31400497	31399857	How do i write into a txt file row by row (Unity)	public void savePreset(string doc)\n    {\n        using (StreamWriter writetext = File.AppendText(doc))\n        {\n            writetext.Write(player.transform.position.x + ", " + Environment.NewLine );\n            writetext.WriteLine(player.transform.position.z + ", ");\n            ...\n            ...\n\n            writetext.Close();\n        }\n    }	0
29128634	29128402	Make a list readonly in c#	List<int> _nums = new List<int>();\n\npublic ReadOnlyCollection<int> Nums\n{\n    get\n    {\n        return _nums.AsReadOnly();\n    }\n}	0
12864791	12864572	Open word template and save as	object paramMissing = Type.Missing;\nobject fileFormat = wdSaveFormat.[whatever you want]\nobject filenameOut = @"c:\somefile.extension";\n\ndoc.SaveAs(ref filenameOut, ref fileFormat,\n              ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,\n              ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, \n              ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, \n              ref paramMissing, ref paramMissing);	0
977821	977652	MVVM Inheritance With View Models	public abstract class ViewModelBase<TModel>\n{\n    private readonly TModel _dataObject;\n\n    public CustomObjectViewModel(TModel dataObject)\n    {\n        _dataObject = dataObject;\n    }\n\n    protected TModel DataObject { get; }\n}\n\npublic class CustomObjectViewModel : ViewModelBase<CustomObject>\n{\n    public string Title\n    {\n        // implementation excluded for brevity\n    }\n}\n\npublic class CustomItemViewModel : ViewModelBase<CustomItem>\n{\n    public string Title\n    {\n        // implementation excluded for brevity\n    }\n\n    public string Description\n    {\n        // implementation excluded for brevity\n    }\n}	0
3051534	3051466	Fastest implementation of the frac function in C#	public decimal Frac(decimal value) { return value - Math.Truncate(value); }	0
10769834	10670432	iOS Successive TCP Requests Fail	handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,\n        new AsyncCallback(ReadCallback), state);	0
13914775	13914496	Getting specific data from xml using linq	var xDoc = XDocument.Load(filename);\nXNamespace tva = "urn:tva:metadata:2005";\n\nvar pi = xDoc.Descendants(tva + "ProgramInformation")\n            .Select(p => new\n            {\n                ProgramId = p.Attribute("programId").Value,\n                ChannelName = p.Attribute("ChannelName").Value,\n                Title = p.Descendants(tva+"Title")\n                         .First(a=>a.Attribute("type").Value=="main")\n                         .Value\n            })\n            .ToList();	0
20242598	20242493	Split and get total count from string	var t = "CHF,2$DVC,1$PP,4".Split('$').Select(s=>s.Split(','))\nvar list = t.Select(i=>i[0]).ToList();\nvar sum = t.Sum(i=>int.Parse(i[1]));	0
26907584	26907583	WPF Telerik ScatterPointSeries RenderMode deprecated	RenderOptions = new XamlRenderOptions() { DefaultVisualsRenderMode = DefaultVisualsRenderMode.Batch }	0
34041683	34041361	To delimited string extensions for Unity 3D	using System.Linq;	0
7456779	7456738	how do I pass an argument to a class that inherits UITypeEditor	public class MyEditor: UITypeEditor\n{\n  // new parametrized constructor\n  public MyEditor(string parameterOne, int parameterTwo...)\n  {\n    // here your code\n  }\n\n  ...\n  ...\n}	0
15447573	15446579	Reload Items of dataGridView	this.marjaTableAdapter.FillBy(this.bankDataSet10.marja);	0
18317941	18298108	How to run commands on Mingw from other process with C#?	System.Diagnostics.Process process = new System.Diagnostics.Process();\nSystem.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\nstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\nstartInfo.FileName = "bash.exe";\nstartInfo.Arguments = "-l -c 'ls -l /your/msys/path'";\n# Or other examples with windows path:\n#   startInfo.Arguments = "-l -c 'ls -l /c/your/path'";\n#   startInfo.Arguments = "-l -c 'ls -l C:/your/path'";\n#   startInfo.Arguments = "-l -c 'ls -l C:\\your\\path'";\nprocess.StartInfo = startInfo;\nprocess.Start();	0
4452723	4451592	Password char for RichTextBox	using System;\nusing System.Windows.Forms;\n\nclass RichPassword : RichTextBox {\n    protected override CreateParams CreateParams {\n        get {\n            // Turn on ES_PASSWORD\n            var cp = base.CreateParams;\n            cp.Style |= 0x20;\n            return cp;\n        }\n    }\n}	0
1145105	1145061	Is there a way to to find out if a caller is highly trusted WITHOUT potentially throwing an exception?	var perm = new AspNetHostingPermission( AspNetHostingPermissionLevel.High );\nvar hasPerm = System.Security.SecurityManager.IsGranted( perm );	0
23499941	23472900	Asynchronous custom Dialog in Windows Store App	private TaskCompletionSource<bool> taskCompletionSource;\n\nprivate Task<bool> ShowAsync()\n{\n    //Do Show Stuff\n\n    taskCompletionSource = new TaskCompletionSource<bool>();\n\n    return taskCompletionSource.Task;\n}\n\nprivate void Close()\n{\n    //Do close stuff\n\n    taskCompletionSource.SetResult(true);\n}	0
18085809	18085024	WebRequest and data from label	string postData = "form_name=loginform&username=" + LoginInput.Text + \n  "&password=" + PasswordInput.Text;	0
17242138	17238948	Look for overlapping values in 2 dimensional array and remove one based on x criteria	public static IEnumerable<IEnumerable<int>> Foo(int[][] data)\n{\n    var items = new HashSet<int>();\n    foreach (var array in data)\n    {\n        yield return array.Except(items);\n        items.UnionWith(array);\n    }\n}	0
10194053	10193853	Using ASPNETDB.mdf in a real application. How can it be used with another database?	CREATE TRIGGER myTrigger \n   ON User \n   AFTER INSERT\nAS BEGIN\n   -- INSERT RECORD IN THE User_Score table here\n   -- populating the appropriate fields. Example:\n  INSERT INTO User_Score (username,columna, columnb, columnc) \n  SELECT username, 0,0,0 from inserted\nEND	0
27579492	27579450	Read Data from Excel using OLEDB	conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +\n        ("Data Source=" + _filename + ";" +\n        "Extended Properties=\"Excel 12.0;\";HDR=No"));	0
5270942	5270919	always create new file if file already exists with same location in C#	File.Exists(filePath)	0
5400225	5400173	converting a base 64 string to an image and saving it	public Image LoadImage()\n    {\n        //get a temp image from bytes, instead of loading from disk\n        //data:image/gif;base64,\n        //this image is a single pixel (black)\n        byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");\n\n        Image image;\n        using (MemoryStream ms = new MemoryStream(bytes))\n        {\n            image = Image.FromStream(ms);\n        }\n\n        return image;\n    }	0
1907774	1906858	How to check FtpWebRequest for errors	FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);\n request.Method = WebRequestMethods.Ftp.UploadFile;\n\n FtpWebResponse response = (FtpWebResponse) request.GetResponse();\n request.KeepAlive = false;\n\n byte[] fileraw = File.ReadAllBytes("CompleteLocalPath");\n\n try\n {\n     Stream reqStream = request.GetRequestStream();\n\n     reqStream.Write(fileraw, 0, fileraw.Length);\n     reqStream.Close();\n }  \n catch (Exception e)\n {\n     response = (FtpWebResponse) request.GetResponse();\n     // Do something with response.StatusCode\n     response.Close();\n }	0
2113460	2113421	Closing a stream after an exception	using(Stream stream = File.Open(oFD.FileName, FileMode.Open))\n{\n    bF = new BinaryFormatter();\n\n    sES = (SavedEventSet)bF.Deserialize(stream);\n}	0
16122303	16122285	Checking for null array element in advance	if(boardArray[xIn][yIn] == null)\n//Skip it, do something, print it, whatever you gotta do	0
33471497	33470104	How to send JSON data as parameter from C# to Jersey RESTful Service	var webAddr = "http://localhost:8080/TestWebservice/rest/SetInfo";\n        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);\n        httpWebRequest.ContentType = "application/json; charset=utf-8";\n        httpWebRequest.Method = "POST";\n\n        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))\n        {\n            string json = "{\"Name\":\"MR.X\",\"ID\":\"AH1J4\"}";\n\n            streamWriter.Write(json);\n            streamWriter.Flush();\n        }\n\n        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();\n        using (var streamReader = new         StreamReader(httpResponse.GetResponseStream()))\n        {\n            var result = streamReader.ReadToEnd();\n            Console.Write(result);\n\n        }	0
8513932	8427240	How to print content of selected item in ListView into a textbox when selected?	private void SelectedItem(object sender, ListViewItemSelectionChangedEventArgs e)\n    {\n        if (tabSelectPage.SelectedTab == tabPage1)\n            txtSelected.Text = " User Name:  " + e.Item.SubItems[1].Text +\n                "     Password:  " + e.Item.SubItems[2].Text;\n        else if (tabSelectPage.SelectedTab == tabPage2)\n            txtSelected.Text = " URL:  " + e.Item.SubItems[1].Text +\n                "     User Name:  " + e.Item.SubItems[2].Text +\n                "     Password:  " + e.Item.SubItems[3].Text;\n        else if (tabSelectPage.SelectedTab == tabPage3)\n            txtSelected.Text = " Software Name:  " + e.Item.SubItems[1].Text +\n                "     Serial Code:  " + e.Item.SubItems[2].Text;\n    }	0
26727428	24357963	DbMigrator - verbose code-first migration	MigratorScriptingDecorator scripter = new MigratorScriptingDecorator(migrator);\nstring script = scripter.ScriptUpdate(null, null);	0
16327869	16327535	Selecting a row in Gridview and deleting it - Asp.net	public DataSet myDataSet \n    {\n        get \n        { \n            return ViewState["myDataSet"] != null ? (DataSet)ViewState["myDataSet"] : null; \n        }\n        set \n        {\n            ViewState["myDataSet"] = value;\n        }\n    }	0
18495538	18494576	Editing control inside Row Edit Template	DropDownList ddlMyObjects = (DropDownList)WebDataGrid1.Behaviors.EditingCore.Behaviors.RowEditTemplate.TemplateContainer.FindControl("control_MyObject");	0
16321650	16321604	Get int values of Enum[]	var myInts = channels.Cast<int>();	0
5978897	5978205	Get local printer list to change printer IP and default printer	ManagementScope mscope = new ManagementScope(@"\root\CIMV2", options);\nmscope.Connect();\nSystem.Management.ObjectQuery oQuery = new ObjectQuery("Select * from Win32_TCPIPPrinterPort");\nSystem.Management.ManagementObjectSearcher searcher = new ManagementObjectSearcher(mscope, oQuery);\nManagementObjectCollection moCollection = searcher.Get();\n\nforeach (ManagementObject mo in moCollection)\n{\n    string name = mo["Name"].ToString();\n\n    if (name.Equals(this.portName))\n    {\n        System.Threading.Thread.Sleep(10000);\n        mo["HostAddress"] = this.printerIP;\n        mo.Put();\n        Console.WriteLine("Adjusted Printer Port to new IP address " + this.printerIP);\n        return true;\n    }\n}	0
11837472	11837245	How to CreateObject in C#?	var t = Type.GetTypeFromProgID("Exfo.IcSCPIActiveX.IcSCPIAccess", sHost, true);\n  obj = (IcSCPIAccess)Activator.CreateInstance(t);	0
12461262	12461144	How can I put my exception information into an IEnumerable<string>	public IEnumerable<string> GetErrors(Exception ex)\n{\n    ...\n\n    var results = new List<string>() { ex.Message };\n    var innerEx = ex.InnerException;\n    while (innerEx != null) \n    {\n        results.Add(innerEx.Message);\n        innerEx = innerEx.InnerException;\n    }\n    return results;\n}	0
5103589	5103522	ASP.net c#. How do I parse an atom feed from a blog	static void Main(string[] args)\n{\n    Atom10FeedFormatter formatter = new Atom10FeedFormatter();\n    using (XmlReader reader = XmlReader.Create("http://latestpackagingnews.blogspot.com/feeds/posts/default"))\n    {\n        formatter.ReadFrom(reader);\n    }\n\n    foreach (SyndicationItem item in formatter.Feed.Items)\n    {\n        Console.WriteLine("[{0}][{1}] {2}", item.PublishDate, item.Title.Text, ((TextSyndicationContent)item.Content).Text);\n    }\n\n    Console.ReadLine();\n}	0
481795	481772	Linq to SQl, select same column from multiple tables	var itemCounts = (from hhd in dc.HHD select hhd.ItemNumber)\n                 .Union((from hkb in dc.HKB select hkb.ItemNumber)\n                         .Union(from hmm in dc.HMM select hmm.ItemNumber)) \n                 and so on	0
519486	519403	How to manually raise an event by supplying X, Y and Windowhandle parameters?	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\npublic class Form1 : Form\n{\n   [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]\n   public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);\n\n   private const int MOUSEEVENTF_LEFTDOWN = 0x02;\n   private const int MOUSEEVENTF_LEFTUP = 0x04;\n   private const int MOUSEEVENTF_RIGHTDOWN = 0x08;\n   private const int MOUSEEVENTF_RIGHTUP = 0x10;\n\n   public Form1()\n   {\n   }\n\n   public void DoMouseClick()\n   {\n      //Call the imported function with the cursor's current position\n      mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);\n   }\n\n  //...other code needed for the application\n}	0
24320687	24308777	Add Controls to Control.Collection	Control con = new Control();\nControl.ControlCollection controls = new Control.ControlCollection(con);	0
29984807	29983760	access_type=online vs offline, how to know which one to use	access_type=offline	0
27731279	27730825	Animate ScaleTransform of a Grid inside a UserControl programmatically in WPF	Storyboard.SetTarget(scaleXAnimation, element.MyGrid);\nStoryboard.SetTargetProperty(scaleXAnimation,\n    new PropertyPath("RenderTransform.ScaleX"));\n\nStoryboard.SetTarget(scaleYAnimation, element.MyGrid);\nStoryboard.SetTargetProperty(scaleYAnimation,\n    new PropertyPath("RenderTransform.ScaleY"));	0
13846646	13035320	Subscribe to Prism EventAggregator events with Reflection	Type eventType = assembly.GetType(typeName);\nMethodInfo method = typeof(IEventAggregator).GetMethod("GetEvent");\nMethodInfo generic = method.MakeGenericMethod(eventType);\ndynamic subscribeEvent = generic.Invoke(this.eventAggregator, null);\n\nif(subscribeEvent != null)\n{\n    subscribeEvent.Subscribe(new Action<object>(GenericEventHandler));\n}\n\n//.... Somewhere else in the class\n\nprivate void GenericEventHandler(object t)\n{\n}	0
15428582	15415238	Prevent Visual Studio to add break lines in switch-case statements	Leave statements and member declarations on the same line	0
12214007	12212193	Searching for Office add-ins	using (RegistryKey ExcelLocation = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Office\Excel\Addins"))\n\n        foreach (string subKeyName in ExcelLocation.GetSubKeyNames())\n        {\n            // Open the key.\n            using (RegistryKey subKey = ExcelLocation.OpenSubKey(subKeyName))\n            {\n                // Write the value.\n                Console.Writeline(subKey.GetValue("Description"));\n                Console.Writeline(subKey.GetValue("FriendlyName"));\n                Console.Writeline(subKey.GetValue("Manifest"));\n            }\n        }	0
3861697	3861647	How to get data using ListView Binding via MVVM in wpf?	ItemsSource="{Binding}"	0
29062813	29062683	MySQL select result save into c# variable	try\n        {\n            MySqlDataReader reader = null;\n            string selectCmd = "SELECT * FROM  TabelaUtilizatori";\n\n            MySqlCommand command = new MySqlCommand(selectCmd, _dbConnect.getConnection());\n            reader = command.ExecuteReader();\n\n            while (reader.Read())\n            {\n                string ColumnName = (string)reader["ColumnName"];\n            }\n        }\n        catch (Exception ex)\n        {\n            MessageBox.Show(ex.Message);\n        }	0
3926117	3926079	Getting started with JSON in .net and mono	[DataContract]\npublic class SomeJsonyThing\n{\n    [DataMember(Name="my_element")]\n    public string MyElement { get; set; }\n\n    [DataMember(Name="my_nested_thing")]\n    public object MyNestedThing { get; set;}\n}	0
26026096	26024854	LINQ columns missing in associated dbml table	ICollection<PalletJob>	0
778605	778475	PInvoke an Array of a Byte Arrays	[DllImport("<unknown>", \n           EntryPoint="Generalize", \n           CallingConvention=CallingConvention.StdCall)]\n    public static extern int Generalize(int count, IntPtr[] items);\n\n    public static void CallGeneralize()\n    {\n        var itemCount = 3;\n        var items = new IntPtr[itemCount];\n\n        items[0] = item1; // where itemX is allocated by Marshal.AllocHGlobal(*)\n        items[1] = item2;\n        items[2] = item3;\n\n        var result = Generalize(itemCount, items);\n    }	0
32320339	32320165	Getting Specific Values from string	string input = "@Time:08:30PM,@Date:08/30/2015,@Duration:4,";\nvar dict = Regex.Matches(input, @"@(\w+):(.+?),")\n           .Cast<Match>()\n           .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);\n\nConsole.WriteLine(dict["Time"]);	0
7471712	7471506	XML may not be returned as proper XML	WebRequest restWebRequest = WebRequest.Create(@"C:\TestProjects\WebApplication4\WebApplication4\XMLFile1.xml");\nrestWebRequest.Method = "GET";\nrestWebRequest.ContentType = "application/x-www-form-urlencoded";\n\n// Send the web request, and get the response from\nWebResponse response = restWebRequest.GetResponse();\nStream responseStream = response.GetResponseStream();\n\nStreamReader reader = new StreamReader(responseStream);\nstring responseFromServer = reader.ReadToEnd();\nTextBox1.Text = responseFromServer;	0
33110525	33105706	how to get hidden value with pagination in gridview	int rowIndex = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;	0
3022101	3022075	Passing data to overridden base method in C#	class A\n{\n    public virtual void DoStuff() {\n        DoStuffInternal(0);\n    }\n    protected void DoStuffInternal(int x) {\n        Console.WriteLine(x);\n    }\n}\n\nclass B : A\n{\n    public override void DoStuff() {\n        DoStuffInternal(1);\n    }\n}	0
8587266	8575579	How do compare strings with nhibernate?	Session.CreateCriteria(typeof(VoiceMailNumber))\n                .Add(Expression.Le("From", number))\n                .Add(Expression.Ge("To", number))\n                .UniqueResult<VoiceMailNumber>();	0
113461	113384	How do I determine the value of a generic parameter on my class instance	private static Type SafeGetSingleGenericParameter(Type type, Type interfaceType)\n    {\n        if (!interfaceType.IsGenericType || interfaceType.GetGenericArguments().Count() != 1)\n            return type;\n\n        foreach (Type baseInterface in type.GetInterfaces())\n        {\n            if (baseInterface.IsGenericType &&\n                baseInterface.GetGenericTypeDefinition() == interfaceType.GetGenericTypeDefinition())\n            {\n                return baseInterface.GetGenericArguments().Single();\n            }\n        }\n\n        return type;\n    }	0
20708862	20708225	AJAX Sending Null data when using IE	var mydate= dateFormat(yourdate, "mm/dd/yyyy HH:MM:ss");	0
2772539	2757441	How should Application.Run() be called for the main presenter of a MVP WinForms app?	// view\npublic void StartApplication() // implements IView.StartApplication\n{ \n    Application.Run((Form)this);\n}\n\n// presenter\npublic void StartApplication()\n{\n    view.StartApplication();\n}\n\n// main\nstatic void Main()     \n{     \n    IView view = new View();     \n    Model model = new Model();     \n    Presenter presenter = new Presenter(view, model);     \n    presenter.StartApplication();     \n}	0
606375	594505	Application failure in Release mode	rem (reregister ASP.NET in IIS)\nrem (run as administrator!)\n%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i	0
17406996	17389448	Access url in windows mobile 6	using System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Net;\nusing System.IO;\n\nnamespace wlchrUrl\n{\n    class urlConn\n    {\n        public void DoConnect(string url)\n        {\n           Uri uri = new Uri(url);\n        try\n        {\n            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(uri);\n            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();\n            Stream stream= httpResponse.GetResponseStream();\n\n            httpResponse.Close();\n            stream.Close();\n\n        }\n        catch(Exception ex)\n        {\n            throw ex;\n        }\n\n    }\n}	0
10789438	10789305	Formating a date in the text of a label inside a form view	protected void FormView2_DataBound(object sender, EventArgs e)\n{\nif (FormView2.CurrentMode == FormViewMode.Edit)\n{\n    Label DAT_Label1 = (Label)FormView2.FindControl("DAT_Label1");\n    if (DAT_Label1 != null)\n    {\n        DateTime date = Convert.ToDateTime(DAT_Label1.Text);\n        DAT_Label1.Text = string.Format("{0:d}", date);\n    }\n}	0
980400	980336	What is the best relative-path solution for developing/deploying WPF apps with local XML stores?	#if DEBUG / #endif	0
14130809	14130798	Date as folder name	Directory.CreateDirectory(DateTime.Now.ToString("dd-MM-yyyy"));	0
21823561	21823473	Sending email from Windows Phone 7 application	var date;\nvar title;\nvar ndes;\n\nemailComposeTask.Body = title + "," + ndes + "," + date;	0
9160150	9160059	Set up dot instead of comma in numeric values	System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();\ncustomCulture.NumberFormat.NumberDecimalSeparator = ".";\n\nSystem.Threading.Thread.CurrentThread.CurrentCulture = customCulture;	0
16109127	16109055	Console.Clear() after a timeout	System.Threading.Thread.Sleep(5000);	0
7235460	5917425	Porting code from c++ to c# - Encrypting with RSA PKCS#1 private key	At the begin of the private key: "-----BEGIN RSA PRIVATE KEY-----\r\n"\nAfter each line of my private key : "\r\n"\nAt the end of my private key: "-----END RSA PRIVATE KEY-----"	0
7964571	7964514	Simple Regex needed	Regex regexObj = new Regex(\n    @"\n    (?<=   # Assert that the following can be matched before the current position:\n     \b                         # start of ""word""\n     \d{2}:\d{2}:\d{2}\.\d{3}   # nn:nn:nn.nnn\n     \sMC:                      # <space>MC:\n    )      # End of lookbehind assertion\n    .*?    # Match any number of characters (as few as possible)...\n    (?=    # ...until the following can be matched after the current position:\n     \b                         # start of word\n     \d{2}:\d{2}:\d{2}\.\d{3}   # nn:nn:nn.nnn\n     \b                         # end of word\n    )      # End of lookahead assertion", \n    RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);\nMatch matchResult = regexObj.Match(subjectString);\nwhile (matchResult.Success) {\n    resultList.Add(matchResult.Value);\n    matchResult = matchResult.NextMatch();\n}	0
10634582	10634506	How to Terminate Threads that started within foreach loop in C#	int shouldExit = 0;\n        new Thread(() =>\n        {\n            foreach (MyClass detail in MyclassList)\n            {\n                if(Thread.VolatileRead(ref shouldExit) != 0) break;\n                DoWork(detail);\n            }\n        }).Start();\n        ...\n        // to terminate loop:\n        Thread.VolatileWrite(ref shouldExit, 1);	0
33997708	33997391	Accessing Child control event from parent level wpf	public event EventHandler ButtonLostFocusEvent;\nprivate void Button_LostFocus(object sender, RoutedEventArgs e)\n{\n    EventHandler testEvent = this.ButtonLostFocusEvent;\n\n    // Check for no subscribers\n    if (testEvent == null)\n        return;\n\n    testEvent(sender, e);\n}	0
21474193	21470866	Windows phone 8 signalR connection method	_connection = new HubConnection(websiteUrl);\n    _myHub = _connection.CreateHubProxy("GameManager");\n    InitializeConnection();\n}\n\npublic async Task InitializeConnection()\n{\n    try\n    {\n        var obj = new\n        {\n            header = 0,\n            data = App.login,\n\n        };\n        var result = JsonConvert.SerializeObject(obj, Formatting.Indented);\n\n       _myHub.On<string>("recieved", data =>\n        {\n            if (OnRecieved != null)\n            {\n                OnRecieved(this, new ChatEventArgs { MessageSent = data });\n                System.Diagnostics.Debug.WriteLine("DATA : " + data);\n            }\n        });\n\n\n        await _connection.Start();\n        await _myHub.Invoke("SendConnection", result);\n        IsConnected = true;\n\n\n        if (OnConnected != null)\n        {\n            OnConnected(this, new EventArgs());\n        }\n    }\n    catch(Exception ex)\n    {\n\n    }\n}	0
27979198	27500165	How to get Exchange 2010 database size	getMDB.Parameters.Add("Status", null);	0
22965009	22964839	Generating a SQL view from EF 6.1 code first	public partial class MyMigration: DbMigration \n{ \n    public override void Up() \n    { \n        Sql("CREATE VIEW......"); \n    } \n}	0
17690759	17690112	Windws Store App - Convert String into Color in VB.NET	Public Function FromName(ColName As String) As SolidColorBrush\n        Dim [property] = System.Reflection.RuntimeReflectionExtensions.GetRuntimeProperty(GetType(Windows.UI.Colors), ColName)\n        Return New SolidColorBrush(DirectCast([property].GetValue(Nothing), Windows.UI.Color))\nEnd Function	0
3059508	3059497	How to compare DateTime in C#?	DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);\nDateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);\nint result = DateTime.Compare(date1, date2);\nstring relationship;\n\nif (result < 0)\n   relationship = "is earlier than";\nelse if (result == 0)\n   relationship = "is the same time as";         \nelse\n   relationship = "is later than";\n\nConsole.WriteLine("{0} {1} {2}", date1, relationship, date2);\n// The example displays the following output:\n//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM	0
6199511	6105102	Create a custom collection like BindingList that works with ListBox to create a ListChanging event	BindingList<T>	0
3276996	3276982	hosting a PDF in a c# application	axAcroPDF1.LoadFile("mypdf.pdf");\naxAcroPDF1.Show();	0
31051760	31050899	Web API parameter is always null	{\n  "domain": "dcas",\n  "username": "sample string 2",\n  "password": "sample string 3",\n  "fileName": "sample string 4"\n}	0
13513264	13513100	Starting an app through code with a relative path in c#	var processStartInfo = new ProcessStartInfo(string.Format("cmd /c start some service"))\n            {\n                WorkingDirectory = ==PathWhereApplicationIs==,\n                WindowStyle = ProcessWindowStyle.Hidden,\n                ErrorDialog = false,\n                CreateNoWindow = true,\n                RedirectStandardOutput = true,\n                RedirectStandardError = true,\n                UseShellExecute = false,\n            };	0
22860136	22860014	Data structure to store ip addresses	HashSet<IPAddress>	0
5987321	5986620	Binding of Datasource to Listbox	var categories = new List<KeyValuePair<string, string>>();\nwhile (reader.Read())\n{\n   categories.Add(new KeyValuePair<string, string>(reader["category_id "].ToString(), reader["cat_name"].ToString()));\n}\nProductMainCategory.DataSource = Categories;\nProductMainCategory.DataValueField = "Key";\nProductMainCategory.DataTextField = "Value";\nProductMainCategory.DataBind();	0
9167365	9167208	Send HTML email with Mysql data into a table from within application	var html = new XDocument(\n    new XElement("html",\n        new XElement("body",\n            new XElement("h2", "Your entire inventory:"),\n            new XElement("table",\n                new XElement("tr",\n                    new XElement("th", "Product"),\n                    from item in orders\n                    select new XElement("td", item.ProductName)),\n                new XElement("tr",\n                    new XElement("th", "Quantity"),\n                    from item in orders\n                    select new XElement("td", item.Quantity))))));\n\nmsg.Body = html.ToString();	0
23704450	23704300	Regex in C# Console App	var input = "Fire hose Tweet - TweetID: 436660665219305472 - ActorID: 120706813";\n\nvar output = input.Split().First(x => x.All(char.IsDigit));	0
13973831	13919967	Why can I get SPSite in PowerShell but fails with FileNotFound in c#?	powershell -version 2	0
13544021	13542453	SignalR 1.0 - send data to a specific client	Context.User	0
13647884	13647699	Repetitive tasks in specific time intervals?	blogged about the dangers	0
9835641	9835323	Reading file properties from windows file system?	private static string GetType(string fileName)\n    {\n        string type = "Unknown";\n        string ext = System.IO.Path.GetExtension(fileName).ToLower();\n        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);\n        if (regKey != null && regKey.GetValue("") != null)\n        {\n            string lookup = regKey.GetValue("").ToString();\n            if (!string.IsNullOrEmpty(lookup))\n            {\n                var lookupKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(lookup);\n                if (lookupKey != null)\n                {\n                    type = lookupKey.GetValue("").ToString();\n                }\n            }\n        }\n        return type;\n    }	0
12638419	12636639	Ookii VistaFolderBrowserDialog and getting selected folder	VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();\ndlg.SelectedPath = Properties.Settings.Default.StoreFolder;\ndlg.ShowNewFolderButton = true;\n\nif (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n{\n    string path = dlg.SelectedPath;\n}	0
12458122	12457950	How to make a class for linq queries (EF)	public class  veritabani_islemleriModel{\n public String KolonAdi { get; set; }\n public String En { get; set; }\n public String Boy { get; set; }\n public String Y?kseklik { get; set; }\n public String ID { get; set; }\n}\n\nand then \npublic class veritabani_islemleri\n{\n    public List<veritabani_islemleriModel> kolonlistele()\n    {\n    using(pehkEntities ctx = new pehkEntities())\n\n\n\n        var result =from k in ctx.Kolons\n               select new veritabani_islemleriModel\n               {\n                   KolonAd? = k.KolonAdi,\n                   En = k.En,\n                   Boy = k.Boy,\n                   Y?kseklik = k.Yukseklik,\n                   ID = k.KolonID\n               };\n\n        return result.Tolist();\n    }\n}	0
6692255	6665848	Post on Facebook fan page as an application not user	messagePost.from = "[SOME_Id]";\nmessagePost.to = "[SOME_Id]";	0
26900736	26900587	Variables in buttons in C#	public partial class Form1 : Form\n{\n    Int32 t = 6;\n    Int32 J = 10;\n    public Form1()\n    {\n        InitializeComponent();\n        Random rand1 = new Random();\n        Int32 Fight = rand1.Next(1, 11);\n\n        label4.Text = Convert.ToString(J);\n\n        if (Fight <= t)\n            label3.Text = Convert.ToString(J);\n        else\n            txtDialogBox.Text = ("No Fight in this room");\n    }\n\n    private void Attack_Click(object sender, EventArgs e)\n    {\n        Random rand2 = new Random();\n        Int32 Attack = rand2.Next(1, 4);\n        Int64 y = 1;\n        //opponents hp bar goes down by 1\n        J--;\n\n        label3.Text = Convert.ToString(J);\n\n        // chance for your hp bar to go down\n        if (Attack >= y)\n        {\n            label4.Text = Convert.ToString(t);\n            t--;\n        }\n    }\n}	0
15509646	15508224	ListViewItem Border - Compact Framework	private const uint LVM_FIRST = 0x1000;\nprivate const uint LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;\nprivate const uint LVM_GETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 55;\nprivate const uint LVS_EX_GRIDLINES = 0x00000001;\n\n[DllImport("coredll.dll")]\nprivate static extern uint SendMessage(IntPtr hwnd, uint msg, uint wparam, uint lparam);\n\npublic void EnableGridlines(ListView listView)\n{\n    var style = SendMessage(\n            listView.Handle,\n            LVM_GETEXTENDEDLISTVIEWSTYLE,\n            0,\n            0);\n\n    style |= LVS_EX_GRIDLINES;\n\n    var style = SendMessage(\n            listView.Handle,\n            LVM_SETEXTENDEDLISTVIEWSTYLE,\n            0,\n            style);    \n}	0
12633308	12633292	is it possible to insert a single value to a datatable cell?	mydatatable.Rows[0]["columnname"] = "value" // Provided column is string type	0
5578367	5578266	Parsing HTML - How to get a number from a tag?	string aTag = ...;\nforeach(var splitted in aTag.Split(';'))\n{\n   if(splitted.Contains("="))\n   {\n      var leftSide = splitted.Split('=')[0];\n      var rightSide = splitted.Split('=')[1];\n      if(leftSide == "assignedto")\n      {\n          MessageBox.Show(rightSide); //It should be 244\n          //Or...\n          int num = int.Parse(rightSide);\n      }\n   }\n}	0
32477889	32477370	Missing Columns from Datatable once Grouped C# ODBC Datatable Console App	var accountGroups = completeDT_units.AsEnumerable().GroupBy(x => new { row => row.Field<String>("Account#"), Description = row.Field<string>("Description").ToString() }).Select(grp => new { Account = grp.Key.row,descrpt=grp.Key.Description, Count = grp.Sum(row => row.Field<int>("Cur-Balance....")) });	0
13423308	13423221	Using EntityFramework dbContext to get records with count in another table	.Where(c => c.Orders.Any(order => order.OrderDate > someDate));	0
33130122	33129812	how to make code block evaluating to bool	if(a == 42 || (new Func<bool>(() => \n    {\n        var foo = FiddleFoo(97);\n        foreach(var f in foo) \n        {\n            if (fudge(f) > 42)\n                return true;\n        }\n        return false;\n    })() || p > 2)\n{\n    //...\n}	0
30627579	30489772	How can I successfully extract this substring in C#?	var regex = new Regex(Regex.Escape("orderid")); //replace first occurrence of orderid\nresponse2 = regex.Replace(response2, "", parsecount-1);\n\npublic string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string\n        {\n            logger.Log("String a is: " + a + "String b is: " + b + "String c is: " + c);\n            var offset = c.IndexOf(b);\n\n            //lastcheck will return 0 if it's last element in orderlist, because ending string differs for last\n            return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, offset + lastcheck) - c.IndexOf(a) - a.Length));\n        }	0
18179704	18178990	Finding out installed Metro applications on a machine	IEnumerable<Windows.ApplicationModel.Package> packages = \n        (IEnumerable<Windows.ApplicationModel.Package>)packageManager.FindPackagesForUser("");	0
2506886	2506683	Convert an interface's event from VB.Net to C#	public class Class1 : IMyInterface {\n    public event EventHandler<MyEventArgs> MyEvent;\n    public Class1() {\n      this.Slider.ValueChanged += OnSliderValueChanged;\n    }\n    private void OnSliderValueChanged(object sender, EventArgs e) {\n      var handler = MyEvent;\n      if (handler != null) {\n        handler(this, new MyEventArgs());\n      }\n    }\n  }	0
10124695	10124058	Issue with surrogate unicode characters in F#	Char.ConvertFromUtf32	0
21211528	21211473	How parse with JavaScriptSeiralizer this JSON	public class Size\n{\n    public string src { get; set; }\n    public int width { get; set; }\n    public int height { get; set; }\n    public string type { get; set; }\n}\n\npublic class Likes\n{\n    public int user_likes { get; set; }\n    public int count { get; set; }\n}\n\npublic class Item\n{\n    public int id { get; set; }\n    public int album_id { get; set; }\n    public int owner_id { get; set; }\n    public List<Size> sizes { get; set; }\n    public string text { get; set; }\n    public int date { get; set; }\n    public Likes likes { get; set; }\n}\n\npublic class RootObject\n{\n    public int count { get; set; }\n    public List<Item> items { get; set; }\n}	0
9400482	9400445	How do you correctly escape a document name in .NET?	Uri.EscapeDataString("Hello There.docx")  // "Hello%20There.docx"\n\nUri.EscapeDataString("Hello#There.docx")  // "Hello%23There.docx"	0
29352692	29352208	Cordova WP8 - Push Notifications Callback	this.CordovaView.CordovaBrowser.InvokeScript("eval", new string[] { \n"document.addEventListener('deviceready',function(){/*some script here to callback to the JS level*/ });"\n});	0
15749989	15749935	do all elements from an array satisfy certain condition determined by another string array	var FilteredAreas = \n    ListOfAreas.Where(a => !SkippedAreas.Contains(a)).Take(NumberOfAreas);	0
27630772	27630327	How to parse out quotes from Text to work in a Javascript Confirm Message Box	externalDisclaimerText = HttpUtility.JavaScriptStringEncode(externalDisclaimerText);	0
26880033	26879970	C# Set string value with " " without printing it	string data = string.Format("{0}/{1}",month,day);	0
32135321	32133784	Controller Scaffolding Issue	public byte[] File { get; set; }	0
20893051	20892984	Possible to initialize multiple variables from a tuple?	string firstValue = tupleWithTwoValues.Item1;\nstring secondValue = tupleWithTwoValues.Item2;	0
25211140	25210368	Problems with Oledb and DATETIME	WHERE [_Date] > @Dt	0
11084409	11083087	Call MVC Controller from Windows task scheduler	using (var client = new WebClient())\n{\n    string result = client.DownloadString("http://example.com/somecontroller/someaction");\n}	0
10862951	10862826	How to modify Grid RowDefinitions and ColumnDefinitions in WPF during runtime?	myGrid.Columns.Clear();\nmyGrid.Rows.Clear();\n\nint buttonNumber = 0;\ndouble buttonWidth = GridWidth / numberOfColumns;\ndouble buttonHeight = GridHeight / numberOfRows;\n\nfor (int columnNumber = 0; columnNumber < numberOfColumns; columnNumber++)\n{\n    var column = new ColumnDefinition();\n    myGrid.Columns.Add(column);\n\n    for (int rowNumber = 0; rowNumber < numberOfRows; rowNumber++)\n    {\n        var row = new RowDefinition();\n        myGrid.Rows.Add(row);\n\n        var button = new Button();\n        button.Content = ++buttonNumber;\n        button.Width = buttonWidth;\n        button.Height = buttonHeight;\n        Grid.SetColumn(button, columnNumber);\n        Grid.SetRow(button, rowNumber);\n    }\n}	0
3736898	3732994	How can I filter the events using Throttle	from d in mouseDowns.Timestamp()\nfrom p in pointChanges\n    .TakeUntil(mouseUps)\n    .SkipUntil(Observable.Timer(d.Timestamp + TimeSpan.FromSeconds(1.0)))\nselect p;	0
3221695	3221522	WPF - DataBinding ImageSource	if (bitmap != null)\n{\n    bitmap.Save(ms, ImageFormat.Bmp);\n    ms.Seek(0, SeekOrigin.Begin); // Set position back to the start of the stream\n    bi.BeginInit();\n    bi.StreamSource = ms;\n    bi.EndInit();\n}	0
14242015	14241999	Consume data from pipeline	[Cmdlet(VerbsCommon.Find, "Numbers")]\npublic class FindNumbers: Cmdlet\n{\n    [Parameter(ValueFromPipeline = true)] // The data appear in this variable\n    public int[] Input { get; set; }\n\n    protected override void ProcessRecord()\n    {\n        foreach (var variable in Input)\n        {\n            if (variable % 2 == 0)\n            {\n                WriteObject(variable);\n            }\n        }\n    }\n}	0
27854106	27793734	How do I show balance log in a gridview	(1)Pass Input parameter : EmployeeId, FromDate, ToDate, HandledById (AdminId)\n(2)Join all corresponding table with the help of Primary & foreign key Id.\n(3)Select the appropriate column, Use aggregate function to find the leave.\n(4)Use sub query in case of necessary as per your logic & table structure.	0
7393725	7393678	Displaying a String Multiple times using * operator	body = "Hello" + String.Join("", Enumerable.Range(0, numTimes).Select(i => str));	0
17455216	17455167	How to properly skip a step if 2 conditions are true	if (!ShouldCheckForErrors || !HasErrors)	0
9950809	9950644	Assert.AreEqual for float without delta	(Decimal) 0.1428571f == (Decimal)(1 / 7.0f)	0
3203143	3201556	Marshalling arrays from C# to C++ and back: PInvokeStackImbalance	[DllImport("libQuadProg.dll", CallingConvention = CallingConvention.Cdecl)]\n    private static extern double solveQP(\n        int n, int mE, int mI,\n        double[] p_G,\n        // etc...\n    }	0
27108442	27108264	C# how to properly make a http web GET request	string html = string.Empty;\nstring url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.AutomaticDecompression = DecompressionMethods.GZip;\n\nusing (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\nusing (Stream stream = response.GetResponseStream())\nusing (StreamReader reader = new StreamReader(stream))\n{\n    html = reader.ReadToEnd();\n}\n\nConsole.WriteLine(html);	0
21991509	21989924	Deprecated feature 'INSERT NULL into TIMESTAMP columns' is not supported in this version of SQL Server	modelBuilder.Entity<Patient>().ToTable("Patient").Property(p => p.Version).IsRowVersion().IsConcurrencyToken();	0
22987497	22987446	How to get a compressed zip file size in c# (wpf)	FileInfo f = new FileInfo("yourfile.zip");\nlong filesize = f.Length; // file size in bytes	0
25373656	25372908	Select Table Rows by Grouping them Adjacent to each Other using XPath	foreach (HtmlNode header in headerNodes)\n{\n   string xPath = "following-sibling::tr[contains(@class, 'item') and preceding-sibling::tr[@class='header'][1]='{0}']";\n   HtmlNodeCollection itemRows = header.SelectNodes(String.Format(xPath, header.InnerText));\n}	0
9874994	9874857	How to send each node of an XML file to a new line when i copy it to a richTextbox?	XmlDocument xdoc = new XmlDocument();\nxdoc.Load(filename);\nXmlNode root = xdoc.DocumentElement;\n\n    //Display the contents of the child nodes.\n    if (root.HasChildNodes)\n    {\n      for (int i=0; i<root.ChildNodes.Count; i++)\n      {\n        richTextBox1.AppendText(root.ChildNodes[i].InnerText+"\n");\n      }\n    }	0
30021036	5250210	Without enums, what alternative to a <string, TValue> Dictionary can yield compile-time errors?	let cameras: (left: Camera, right: Camera)	0
22475288	22475169	Filtering and grouping items in a .NET List<>	var list =  lst.GroupBy(x => x.reportTypeId)\n            .Select(x => new \n                     { \n                         reportTypeId = x.Key, \n                         Acronyms = x.SelectMany(t => t.Acrynom).ToArray()\n                     }).ToList();\n\nvar acronymList1 = string.Join(", ", list[0].Acronyms);\nvar acronymList2 = string.Join(", ", list[1].Acronyms);	0
31574879	31574786	How to Update Entity without a DbContext in class library	DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity)\n   where TEntity: class;	0
4197526	4197499	How can I convert a string to a stream?	using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))\n{\n    // Your code here, using stream.\n}	0
23237809	23236855	Converting SQL query to LINQ to Entities Lambda Expression	entities.table1.Where(x=>x.Date>(new DateTime(2014,1,4))).Max(x=>x.Number)	0
981001	980994	How do I get a particular derived object in a List<T>?	foreach(Banana b in fruits.OfType<Banana>())	0
17196771	17196689	Trying to insert into access database via SQL getting ID from another table	String sql = "INSERT INTO tblProblem " + \n    "([MachineID], [ProblemDescription], [ProblemOrder])" +\n    "SELECT tblMachine.[MachineID], @ProblemDescription, @ProblemOrder " +\n    "FROM tblMachine " +\n    "WHERE tblMachine.MachineDescription = @MachineDescription";	0
10622103	10622069	Close C# Console Application after MessageBox click	// Terminates this process and gives the underlying operating system the specified exit code.\nEnvironment.Exit()	0
9794562	9794330	add items properties - c# winform	private void loadMatchingResponsesReports()\n    {\n        listBox2.Items.Clear();\n\n        string[] list = getMatchingReports();\n        foreach (String S in list)\n        {\n            FileInfo fileResponse = new FileInfo(S);\n            string fileResponseNameOnly = fileResponse.Name;\n            listBox2.Items.Add(fileResponseNameOnly);\n            GC.Collect();\n        }\n    }\n\n    public string[] getMatchingReports()\n    {\n        string[] returnR = null;\n        try\n        {\n            returnR = Directory.GetFiles(textBox3.Text + @"\", "*.xls");\n        }\n        catch\n        {\n            MessageBox.Show("Can't get some files from directory " + textBox3.Text);\n        }\n        return returnR;\n    }	0
7385543	7385489	Loading certain data in combobox based on textbox input	List<string> strMale = new List<string>{"Mr.", "Dr. "};\n    List<string> strFMale = new List<string>{"Mrs.", "Miss"};\n\n//make use of Textbox Change Event\npublic void Text1_TextChanged(object sender, EventArgs e)\n\n{\n\n  Combo1.Items.Clear();\n\n  //Bind the values using the text box input value \n  if(Text1.Text=="0")\n   {\n     Combo1.DataSource = strMale ;\n   }\n   else if(Text1.Text=="1")\n   {\n     Combo1.DataSource = strFMale ;\n   }\n  Combo1.SelectedIndex = 0;\n}	0
4025701	4025353	Passing Array to Action from a $.post	jQuery.ajaxSettings.traditional = true;	0
16531846	16531762	Efficient way to pass large number of argments into a constructor	public class CharecterInfo\n{ \n       public string Name {get;set;}\n       public int Power {get;set;}\n       public int Health{get;set;}\n}\n\npublic class Charecter\n{ \n     public Charecter(CharecterInfo charecterInfo)\n     {\n        //import values\n     }\n}	0
31482702	31481867	Convert to html (nested ul li) from list in C#	public class Node {\n    string Name { get; set; }\n    IList<Node> Subnodes { get; private set; }\n}\n\nprivate void BuildList(Node node, StringBuilder sb) {\n    sb.Append("<ul>");\n    foreach (var n in node.Subnodes) {\n        sb.Append("<li>" + n.Name);\n        BuildList(n, sb);\n        sb.Append("</li>");\n    }\n    sb.Append("</ul>");\n}\n\npublic string BiuldList(Node root) {\n    var sb = new StringBuilder();\n    BuildList(root, sb);\n    return sb.ToString();\n}	0
25835691	25835659	How do I reset switch case?	case 3:\n    DoRequest();\n    clickNo = 0;\n    break;	0
11841071	11841017	How to get a collection of lists to a list using Linq?	List<Employee> EmployeeList = EmployeeListCollection.SelectMany(c => c).ToList();	0
13827131	13810144	Fluent NHibernate - Mapping tables which reference an ID from a lookup table	class ProjectVendorPair\n{\n    public virtual int Id { get; set; } \n    public virtual Project Project { get; set; }\n    public virtual Vendor Vendor { get; set; }\n}\n\n// in PaymentMap\nReferences(x => x.Owner, "Project_Vendor_Id");	0
9262374	9259240	How to load an assembly from GAC with wildcards in version number	class Program\n{\n    static void Main(string[] args)\n    {\n        var assemblyName = "SimpleAssembly";\n        var versionRegex = new Regex(@"^12\.");\n        var assemblyFile = FindAssemblyFile(assemblyName, versionRegex);\n\n        if (assemblyFile == null)\n            throw new FileNotFoundException();\n\n        Assembly.LoadFile(assemblyFile.FullName);\n    }\n\n    static FileInfo FindAssemblyFile(string assemblyName, Regex versionRegex)\n    {\n        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "assembly", "GAC_MSIL", assemblyName);\n        var assemblyDirectory = new DirectoryInfo(path);\n\n        foreach (var versionDirectory in assemblyDirectory.GetDirectories())\n        {\n            if (versionRegex.IsMatch(versionDirectory.Name))\n            {\n                return versionDirectory.GetFiles()[0];\n            }\n        }\n\n        return null;\n    }\n}	0
19490311	19471104	WPF/C# DataTemplate changes Layout cause of icon	compList.Add(new compEntry() { id = i, img_src = img, errorOriginal = errText[i].Trim(), errorGerman = trans.Trim() });	0
15875275	15874261	Direct to another xaml user control page when button clicked C# WPF	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        // based on your comments your window is called catergory\n        var catergory = new Catergory();\n        catergory.Show();\n    }	0
11361878	11361631	Excluding rows from collection from Linq Query in MVC .net application	var prebookedRooms = rooms\n    .Where(room => room.Clients.Any(client => \n    (dteFrom >= client.Arrival && dteFrom <= client.Departure) ||\n    (dteTo >= client.Arrival && dteFrom <= client.Departure)   ||\n    (dteFrom <= client.Arrival && dteTo >= client.Departure)));\n\nvar freeRooms = rooms.Except(prebookedRooms);	0
34297507	34297247	Get Clicks per Second for a Button	void main(){\n    timer = new Timer();\n    timer.Interval = 1000; // 1000 miliseconds = 1 second\n    timer.Tick += new EventHandler(timer_Tick);\n    timer.Enabled = true;\n}\nvoid timer_Tick(object sender, EventArgs e)\n{\n    // Do what you need\n    var clicks = _klicks;\n    // method to save clicks to the file\n    _klicks = 0;\n    return clicks;\n}	0
20583414	20583360	How to split string in 2 word string set in c#	var pairs = str.Split(' ')\n    .Select((s,i) => new {s, i})\n    .GroupBy(n => n.i / 2)\n    .Select(g => string.Join(" ", g.Select(p=>p.s)))\n    .ToList();	0
3750762	3750678	Getting attribute value of an XML Document using C#	XmlDocument doc = new XmlDocument();\ndoc.LoadXml("<reply success=\"true\">More nodes go here</reply>");\n\nXmlElement root = doc.DocumentElement;\n\nstring s = root.Attributes["success"].Value;	0
20926931	20926610	Changing the cursor highlight color	Selected Text	0
15649235	15648378	crop image without copying	// Create a CroppedBitmap from the original image.\nInt32Rect rect = new Int32Rect(x * tileWidth + x, y * tileHeight, tileWidth, tileHeight);\nCroppedBitmap croppedBitmap = new CroppedBitmap(originalImage, rect);\n\n// Create an Image element.\nImage tileImage = new Image();\ntileImage.Width = tileWidth;\ntileImage.Height = tileHeight;\ntileImage.Source = croppedBitmap;	0
12341277	12340837	To show hidden windows form at the top of the current opened application	private void ActivateApplication (string briefAppName) \n    {\n        Process[] p=Process.GetProcessesByName (briefAppName);\n        if (p.Length>0)\n        {\n            this.TopMost=true;\n            ShowWindow (p[0].MainWindowHandle, 9);\n            this.TopMost=false;\n            this.Activate ();\n        }\n    }	0
20043049	20042776	Search checkbox values in gridview	protected void btnSearchGroup_Click(object sender, EventArgs e)\n            {\n                string selectedValues = string.Empty;\n\n                foreach (ListItem item in cblGroup.Items)\n                {\n                    if (item.Selected)\n                        selectedValues += "'" + item.Value + "',";\n                }\n\n                if (selectedValues != string.Empty)\n                    selectedValues = selectedValues.Remove(selectedValues.Length - 1);//To remove the last comma;\n\n\n                SqlConnection con = new SqlConnection(strcon);\n                SqlCommand cmd = new SqlCommand("select * from AppInvent_Test where Designation in (" + selectedValues + ")", con);\n                SqlDataAdapter Adpt = new SqlDataAdapter(cmd);\n                DataTable dt = new DataTable();\n                Adpt.Fill(dt);\n                GridView1.DataSource = dt;\n                GridView1.DataBind();\n\n            }	0
30846320	30846003	Deserialize malformed JSON with JSON.NET	var json = "{\"123\":{\"name\":\"test\",\"info\":\"abc\"}}";\n\nvar rootObject = JsonConvert.DeserializeObject<Dictionary<string, User>>(json);\nvar user = rootObject.Select(kvp => new User \n                                    { ID = kvp.Key, \n                                      Name = kvp.Value.Name, \n                                      Info = kvp.Value.Info \n                                    }).First();	0
32349561	32344094	ItextSharp HTML to PDF conversion how to convert text with superscript and subscript as it is	"<span style=\"width:500px;\">" +\n                            "<span>500 m</span>" +\n                            "<span style=\"vertical-align:super;font-size:8px;\">2</span>" +\n                        "</span>" +	0
26768354	26768084	Entity Framework Add User to Role	user.Roles.Add(role);	0
8378965	8378815	export html table to excel file encoding	Response.Clear();\nResponse.AddHeader("content-disposition","attachment;filename=myexcel.xls");   \nResponse.ContentType = "application/ms-excel";\nResponse.ContentEncoding = System.Text.Encoding.Unicode;\nResponse.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());\n\nSystem.IO.StringWriter sw = new System.IO.StringWriter();\nSystem.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);\n\nFormView1.RenderControl(hw);\n\nResponse.Write(sw.ToString());\nResponse.End();	0
2096018	2095964	Data binding fails when changing numbers on numericUpDown	numericUpDown1.DataBindings.Add("Value", myBox1, "Width", false, DataSourceUpdateMode.OnPropertyChanged);	0
7086854	7086674	how to check whether a .config file exist or not in a folder C#?	System.IO.File.Exists(path)	0
31520098	31515591	Compare MySQL Date with c#/Nhibernate Date	data= session.CreateCriteria(typeof(DataModel))\n             .Add(Restrictions.Eq("date", DateTime.Now.Date))\n             .UniqueResult<DataModel>();	0
1683619	1683606	How to conver a string to a enum of type int?	BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something);	0
26251700	26249329	How to know if RESTful request didn't contain some arguments in ASP.Net Web API 2?	namespace TestingAPI.Models\n{\n    public class Operator\n    {\n        public int pkey { get; set; }\n        public string id { get; set; }\n        public int? qty {get; set;}\n        public DateTime datetime_created { get; set; }\n        public DateTime? datetime_updated { get; set; }\n    }\n}	0
24373854	24332454	Mapping EntityFramework One to One without Helper Property	modelBuilder.Entity<Employee>()\n    .HasKey(e => e.Id)\n    .HasRequired(s => s.Department)\n    .WithMany()\n    .Map(a => a.MapKey("DepartmentId"));	0
20204535	20200985	Source file information missing in StackTrace, when PDB loaded from another folder	var appdir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);\nvar pdbdir = System.IO.Path.Combine(appdir, "pdbs");\nEnvironment.SetEnvironmentVariable("_NT_SYMBOL_PATH", pdbdir);	0
11835844	11831882	Windows phone7 custom messagebox with a popup	control.OK_BTN.Click += (s, args) =>\n        {\n            popup.IsOpen = false;\n            this.IsEnabled = true;\n\n            Dispatcher.BeginInvoke(() =>\n                {\n                    MessageBoxResult result = MessageBox.Show("Do you want to reset the settings ?", "Settings", MessageBoxButton.OKCancel);\n\n                    if (result == MessageBoxResult.OK)\n                    {\n                        changeSettings();\n                    }\n                });\n        };	0
18740376	18739396	Schedule a C# console application	// construct a scheduler factory\nISchedulerFactory schedFact = new StdSchedulerFactory();\n\n// get a scheduler\nIScheduler sched = schedFact.GetScheduler();\nsched.Start();\n\n// construct job info\nJobDetail jobDetail = new JobDetail("myJob", null, typeof(DumbJob));\n// fire every hour\nTrigger trigger = TriggerUtils.MakeHourlyTrigger();\n// start on the next even hour\ntrigger.StartTime = TriggerUtils.GetEvenHourDate(DateTime.UtcNow);  \ntrigger.Name = "myTrigger";\nsched.ScheduleJob(jobDetail, trigger);	0
33162166	33162145	How to use groupby with LINQ?	var sorted = from c in mediaInv \n             where c.MediaType == "Movie" \n             orderby c.Rating descending \n             select c;	0
25043128	25043061	OutOfMemoryException paging 150K rows using EF	AsNoTracking()	0
19074672	19072552	Connecting to a remote database via a connection string	Provider=Microsoft.Jet.OLEDB.4.0; \nData Source=\\UNDERFOOT-PC\CalUnderFootDB\CarsDB.mdb;\nUser Id=admin; Password=;	0
7362762	7362704	c# windows can't close the app in the shutdown	SystemEvents.SessionEnding	0
28501629	28501520	How call the Text_Changed Event for multiple text box controls on a form in C# winforms	private void Form1_Load(object sender, EventArgs e)\n{\n    foreach (Control ctrl in this.Controls)\n    {\n        if ((ctrl as TextBox) != null)\n        {\n            (ctrl as TextBox).TextChanged += Form1_TextChanged;\n        }\n    }\n}\nprivate void Form1_TextChanged(object sender, EventArgs e)\n{\n    MessageBox.Show((sender as TextBox).Name);\n}	0
6949521	6949308	How do I uppercase using ItemStringFormat in WPF?	return ((string)value).ToUpper();	0
5591701	5590145	export file with correct encoding	Encoding encoding = Encoding.UTF8;\n    var bytes = encoding.GetBytes("write ? or ? please");\n    MemoryStream stream = new MemoryStream(bytes);\n    StreamReader reader = new StreamReader(stream);\n    Response.Clear();\n    Response.Buffer = true;\n    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename"));\n    Response.Charset = encoding.EncodingName;\n    Response.ContentType = "application/text";\n    Response.ContentEncoding = Encoding.Unicode;\n    Response.Output.Write(reader.ReadToEnd());\n    Response.Flush();\n    Response.End();	0
1553042	1553031	What string concatenation method to use for N number of iterations?	public static string Repeat(this string instance, int times)\n    {\n        if (times == 1 || string.IsNullOrEmpty(instance)) return instance;\n        if (times == 0) return "";\n        if (times < 0) throw new ArgumentOutOfRangeException("times");\n        StringBuilder sb = new StringBuilder(instance.Length * times);\n        for (int i = 0; i < times; i++)\n            sb.Append(instance);\n        return sb.ToString();\n    }	0
26062778	26062742	C# If statement with out of bound array	for(int i =0; i<Temp.count-2;i++)\n{\n\n}	0
24493736	24491669	using open file dialog box on a windows form	string readfilename = txtFindAegonFile.Text;\n\n        try\n        {\n\n\n\n            using (StreamReader sr = new StreamReader(readfilename))\n            using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))\n\n            {	0
18259821	18259432	Save edits from dataGridView to SQL Server database (no DataSet or TableAdapter)	foreach (DataGridViewRow row in this.dataGridView1.Rows)\n{\n     int tagId = Convert.ToInt32(row.Cells["TagID"].Value);\n}	0
31198234	31196925	Compact way of adding label names using a loop	private void btnAdd_Click(object sender, EventArgs e)\n    {\n        string input1 = Interaction.InputBox("Type contents of label:");\n        Label lbl = new Label();\n        lbl.Text = input1;\n        lbl.AutoSize = true;\n        flowLayoutPanel1.Controls.Add(lbl);\n    }\n\n    private void btnRemove_Click(object sender, EventArgs e)\n    {\n        if (flowLayoutPanel1.Controls.Count > 0)\n        {\n            flowLayoutPanel1.Controls.RemoveAt(flowLayoutPanel1.Controls.Count - 1);\n        }\n    }	0
3333833	3333625	How to split a string into an array	Regex.Split(input, "\s(?=[A-Z][A-Za-z]*:)")	0
11259613	11226831	How to set the CascadingDropDown values using java script	int type = Convert.ToInt32(e.CommandArgument.ToString());\n                    Label filename = (Label)grdindirectconsultant.Rows[type].Cells[1].FindControl("lblresume");\n                    string txtfile = grdindirectconsultant.Rows[type].Cells[1].Text.ToString();\n                    CascadingDropDown1.SelectedValue = grdindirectconsultant.Rows[type].Cells[8].Text.ToString();\n\n                    txttechnology.SelectedItem.Value = grdindirectconsultant.Rows[type].Cells[8].Text.ToString();\n                    Fillskills(); //Fill the primary skills depended up on the technology\n                    CascadingDropDown2.SelectedValue = grdindirectconsultant.Rows[type].Cells[8].Text.ToString() + "," + grdindirectconsultant.Rows[type].Cells[9].Text.ToString();	0
29567034	29565573	Select diagonals that pass from a point in 2d array	var t = // selected cell that contains X,Y coordinates\nvar diagonals = cells.Where(n => Math.Abs(t.X - n.X) == Math.Abs(t.Y - n.Y));	0
16487199	16487157	How to show date and time in one label?	lbldatetime.Text = DateTime.Now.ToString("MM-dd-yyyy h:mmtt");	0
3673597	3673538	I want to print the value in sales	while (response == 'A'){\n    Console.WriteLine("Enter Sales");\n    string salesStr = Console.ReadLine();\n    Console.WriteLine(Double.Parse(salesStr) * COMMRATE);\n    Console.WriteLine("Enter A to continue, anything else to quit");\n    response = Convert.ToChar(Console.ReadLine());\n}	0
25238944	25238870	How to know subtract two arrays	var matchingRows = dt.AsEnumerable()\n    .Where(row => dataNames.Contains(row.Field<string>("ColumnName"), StringComparer.OrdinalIgnoreCase))\n    .Select(row => row.Field<string>("ColumnName"));\n\nvar diff = dataNames.Except(matchingRows, StringComparer.OrdinalIgnoreCase);	0
13204004	13203975	How to parse deeply nested using LINQ to XML	var doc = XDocument.Load("file.xml");\nvar query = doc.Descendants("Order")\n               .Concat(doc.Descendants("OrderCancelled"))\n               .Select(x => new {\n                           OrderNumber = (int) x.Element("OrderNumber"),\n                           ShipAddress = (string) x.Element("ShipAddress"),\n                           ShipCity = (string) x.Element("ShipCity"),\n                           ShipState = (string) x.Element("ShipState")\n                       });	0
32276028	32276007	Cannot set/get values to IDictionary<string,string>	public IDictionary<string,string> TagInfo  { get; set; } = new Dictionary<string,string>();	0
7644666	7644478	Fluent NHibernate: Lock row in a multiple user environment	LockMode.UPGRADE_NOWAIT	0
11608874	11608823	How to compile the regularexpression in C#	private bool Set(string stream, string inputdata) \n{\n    var regex = BuildRegex(stream);\n    bool retval = regex.IsMatch(inputdata);\n    return retval;\n}\n\nstatic Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();\n\nprivate static Regex BuildRegex(string pattern)\n{\n    Regex exp;\n\n    if (!regexCache.TryGetValue(pattern, out exp))\n    {\n        exp = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);\n        regexCache.Add(pattern, exp);\n    }\n\n    return exp;\n}	0
7515215	7515062	How should I deal with null objects in a using block?	CreateFoo()	0
18397468	18313673	Programmatically Maximize Window On Half Of Screen	ShowWindow(handle, SW_MAXIMIZE);\n// for a split second you might see a maximized window here\nMoveWindow(handle, 0, 0, Screen.PrimaryScreen.WorkingArea.Width / 2, Screen.PrimaryScreen.WorkingArea.Height, true);	0
22039963	22039352	How insert Image over a Button dynamically	//Get the button instance that raised this event\nButton Source = (Button)sender;\n\n//Craete the Image isntance and set the image to be dispalyed\nImage ButtonPicture = new Image();\nButtonPicture.BaseUri = "MyButtonPicture.jpg"\n\n//Assign it to the buttons content\nSource.Content = ButtonPicture;	0
17877529	17877392	How to display random generated ID into more than 1 textbox	tbPassword.Attributes.Add("value", tal.ToString());	0
20802054	20801728	I have a list of points and would like to determine if they form a circle	public PointF findCenter(PointF a, PointF b, PointF c)\n{\n    float k1 = (a.Y - b.Y) / (a.X - b.X) //Two-point slope equation\n    float k2 = (a.Y - c.Y) / (a.X - c.X) //Same for the (A,C) pair\n    PointF midAB = new PointF((a.X + b.X) / 2, (a.Y + b.Y) / 2) //Midpoint formula\n    PointF midAC = new PointF((a.X + c.X) / 2, (a.Y + c.Y) / 2) //Same for the (A,C) pair\n    k1 = -1*k1; //If two lines are perpendicular, then the product of their slopes is -1.\n    k2 = -1*k2; //Same for the other slope\n    float n1 = midAB.Y - k1*midAB.X; //Determining the n element\n    float n2 = midAC.Y - k2*midAC.Y; //Same for (A,C) pair\n    //Solve y1=y2 for y1=k1*x1 + n1 and y2=k2*x2 + n2\n    float x = (n2-n1) / (k1-k2);\n    float y = k1*x + n1;\n    return new PointF(x,y);\n}	0
33894961	33875260	Entity Framework 6 deep copy/clone of an entity with dynamic depth	public Item DeepCloneItem(Item item)\n{\n    Item itemClone = db.Items.FirstOrDefault(i => i.ItemID == item.ItemID);\n    deepClone(itemClone);\n    db.SaveChanges();\n    return itemClone;\n}\n\nprivate void deepClone(Item itemClone)\n{\n    foreach (Item child in itemClone.ChildrenItems)\n    {\n        deepClone(child);\n    }\n    foreach(Parameter param in itemClone.Parameters)\n    {\n        db.Entry(param).State = EntityState.Added;\n    }\n    db.Entry(itemClone).State = EntityState.Added;\n}	0
16769476	16769302	How to make visible another combo box on selection of a value in current combo box?	Private void CB1_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n    Combobox CB = (ComboBox) sender;\n    if(CB.SelectedIndex != -1)\n    {\n        int x = Convert.ToInt32(CB.Text)\n        if(x == 3)\n        {\n          CB2.Visible = True;\n        }\n    }\n}	0
11774047	11772665	Dynamically change range of FormatCondition	using Microsoft.Office.Interop.Excel;\n\n<...>\n\n        formatConditionObj = (FormatCondition)myRange.FormatConditions\n            .Add(XlFormatConditionType.xlExpression, \n            Type.Missing, true, Type.Missing, Type.Missing, \n            Type.Missing, Type.Missing, Type.Missing);\n\n        formatConditionObj.Interior.ColorIndex = 5;\n\n        Range myNewRange = ws.Range["a10:a15"];\n        formatConditionObj.ModifyAppliesToRange(myNewRange);\n\n <...>	0
18824755	18822672	Moving singleton definition into mixins in C#	public sealed MyClass\n{\n   private MyClass(){}\n   public static MyClass Instance = new MyClass();\n}	0
8148545	8148390	update column1 = column1 + 10 in NHibernate	s.CreateQuery("UPDATE person SET Property1=Property1 + :p1")\n    .SetParameter("p1", myValue)\n    .ExecuteUpdate();	0
5992641	5992503	Is it possible to calculate the execution time of a method in C# with attributes?	public void DoSomething(){\n  Stopwatch stopWatch = new Stopwatch();\n  stopWatch.Start();\n\n  //stuff you want to time\n\n  stopWatch.Stop();\n\n  System.Console.Writeln(String.Format("Total Ticks: {0}", stopWatch.ElapsedTicks))\n}	0
15207001	15206953	saving a json file in a text file	Person person = GetPerson();\n\n\n    using (FileStream fs = File.Open(@"c:\person.json", FileMode.CreateNew))\n    using (StreamWriter sw = new StreamWriter(fs))\n    using (JsonWriter jw = new JsonTextWriter(sw))\n    {\n      jw.Formatting = Formatting.Indented;\n\n      JsonSerializer serializer = new JsonSerializer();\n      serializer.Serialize(jw, person);\n    }	0
7588567	7588539	C# Finding Next Active Day of Week	DateTime nextDay = currentDay.AddDays(1);\nwhile (!profile.IsActive(nextDay.DayOfWeek))\n{\n    nextDay = nextDay.AddDays(1);\n}	0
11034934	11034834	Looping over variable names	foreach (var childButton in buttonsGrid.Children.OfType<Button>())\n// do smth	0
15723260	15723202	How the Application layer will be able to dynamicly query the DB in the DAL layer?	// NOTE: this is an expression, not a method\nprivate static Expression<Func<ClientDataAccessLayer.Client, BusinessLogic.Client>> Convert =\n    x => new BusinessLogic.Client // NOTE: initializer, not a constructor\n    {\n        Id = x.Id,\n        ...\n    };\n\npublic IQueryable<BusinessLogic.Client> Clients()\n{\n    this.MainDB.Clients.Select(Convert);\n}	0
682644	682615	How can I get every nth item from a List<T>?	return list.Where((x, i) => i % nStep == 0);	0
8661071	8660547	WCF MsmqIntegrationBinding - Some XML messages not being picked up	System.ServiceModel.CommunicationObjectAbortedException: The communication object, System.ServiceModel.Channels.TransportReplyChannelAcceptor+TransportReplyChannel, cannot be used for communication because it has been Aborted.	0
2375616	2375594	Compare 7 words to eachother to see if 5 of them are equal. How?	int maxCount = s.GroupBy(x => x).Select(x => x.Count()).Max();	0
7261959	7246641	how to alter valid windows icon programmatically?	//fixed\n[DllImport("user32.dll", SetLastError = true)] static extern bool DestroyIcon(IntPtr hIcon);\n       public Icon MakeRandomIcon()\n       {\n           using (Bitmap bmp = new Bitmap(size, size))\n           using (Graphics g = Graphics.FromImage(bmp))\n           {\n               for (int it = 0; it < 20; it++) this.GetRandomPainter()(g);\n               g.Dispose();\n               IntPtr hIcon = bmp.GetHicon();\n               Icon temp = Icon.FromHandle(hIcon);\n               Icon ico = (Icon)temp.Clone();\n               temp.Dispose();\n               DestroyIcon(hIcon);\n               return ico;\n           }\n       }\n\n\n//thanks Miguel again.	0
29907047	29907019	Menu interfering with my gridview control	z-index	0
27027462	27027307	c# - Iterate through dictionary and attach items to object	PropertyInfo propertyInfo = user.GetType().GetProperty(entry.Key);\npropertyInfo.SetValue(user, entry.Value, null);  //Assumes the value is of the same type as the property.	0
6577420	6568047	Is there a way to control the width of the left task pane holding an add-in?	var control = new TaskPaneControl();\nvar width = control.Width;\nvar taskPane = CustomTaskPanes.Add(control, "Wide");\ntaskPane.Width = width;\ntaskPane.Visible = true;	0
31301442	31301091	How can I tell if a key was ever defined in a deserialized JSON object in .NET?	public class Slide\n{\n    public bool HasTitle { get; private set; }\n\n    public double runningTime\n    {\n        get;\n        set;\n    }\n\n    private string _title;\n\n    public string title\n    {\n        get { return _title;  }\n        set { _title = value; HasTitle = true; }\n    }\n\n    public int id\n    {\n        get;\n        set;\n    }\n}	0
24751353	24719317	Windows Phone 8 - Interstitial Ads Only Display Once	public partial class MainPage : PhoneApplicationPage\n{\n    private InterstitialAd interstitialAd;\n    int Click1 = 0;\n    AdRequest adRequest = new AdRequest();\n\n    public MainPage()\n    {\n        InitializeComponent();          \n\n     }\n    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        Click1++;\n        if (Click1 == 5)\n        {\n            interstitialAd = new InterstitialAd("My APp Id");\n            AdRequest adRequest = new AdRequest();\n\n              interstitialAd.ReceivedAd += OnAdReceived;\n            interstitialAd.LoadAd(adRequest);\n            Click1 = 0;\n        }\n    }\n    private void OnAdReceived(object sender, AdEventArgs e)\n    {\n        System.Diagnostics.Debug.WriteLine("Ad received successfully");\n        interstitialAd.ShowAd();   \n    }\n}	0
3515962	3515939	DataGridView Custom Sort in WinForm	private void radioButtonSortProgram_CheckedChanged(object sender, EventArgs e)\n\n{\n\n    if (this.radioButtonSortProgramAlpha.Checked)\n\n        this.view.PropertyComparers["Program"] = new CustomerProgramComparerAlpha();\n\n    else if (this.radioButtonSortProgramRank.Checked)\n\n        this.view.PropertyComparers["Program"] = new CustomerProgramComparerRank();\n\n    else\n\n        this.view.PropertyComparers.Remove("Program");\n\n}	0
22820060	22819714	WPF Combobox with ItemsSource - What path do I set to access this databinding?	public class Location\n{\n    public Guid LocationID { get; set; }\n    public Guid ParentID { get; set; }\n    public String Name { get; set; }\n    public bool isValid { get; set; }\n}	0
6748291	6747439	Binding ObservableCollection in Custom User Control	public ObservableCollection<StringLineInfo> AllLines\n    {\n        get\n        {\n            return (IObservableCollection<StringLineInfo>)itmCtrol.ItemsSource;\n        }\n        set\n        {\n            itmCtrol.ItemsSource = value;\n        }\n    }	0
23843995	23692438	Getting values from deleted rows in data grids using winforms	var q = dt.AsEnumerable().Select(x => x.Field<string>(colName, DataRowVersion.Original));	0
11831454	11831407	Changing from SQL Server to Oracle database	qry = string.Format(@"SELECT *\n         FROM YourSchemaUser.CIS_TRANS <-- Fix your schema user name\n         WHERE BSA_CD like '%{0}%'", BSA_CD);\n\n  qry = @"SELECT * FROM YourSchemaUser.CIS_TRANS"; <-- Fix your schema user name	0
3640079	3640054	Writing data to a Label	errorMessageLable.Text = "YourErrorMessageHere";	0
22995513	22995214	Create a json formatted object	var outputString = JsonConvert.SerializeObject(new { \n        success=1, \n        error=0, \n        gestor="test", \n        cliente = (from System.Data.DataRow i in com.Execute("select * from utilizadores").Rows \n                  select new { \n                     nome=item["first_name"],\n                     apelido= item["last_name"] \n        }).ToArray()\n});	0
19808430	19808299	Windows Library to play a video file	MediaElement me = new MediaElement();\n// initialize and do other stuff to MediaElement\nthis.Background = new VisualBrush(me);	0
25606947	23455658	web api call from WPF over SSL	X509Certificate2 cert = null;\n        X509Store store = null;\n\n        try\n        {\n            store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);\n            store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);\n            // You can check certificate here ... \n            // and populate cert variable.. \n        }\n        finally\n        {\n            if (store != null) store.Close();\n        }\n\n\n        var clientHandler = new WebRequestHandler();\n        if (cert != null) clientHandler.ClientCertificates.Add(cert);\n\n        var client = new HttpClient(clientHandler) {BaseAddress = new Uri(uri)};	0
29178070	29175232	how to get range of inactive sheets in excel in C#	var wb = Excel.Application.ActiveWorkbook;\nList<Worksheet> sheets = new List<Worksheet();\nforeach(var sheet in wb.Sheets)\n{\n   if(sheet != Excel.Application.ActiveSheet)\n   {\n        sheets.add(sheet);\n   }\n}	0
28848876	28848468	Using foreach statement and switch for checked multiple nodes	foreach (TreeNode node in treeView1.Nodes) RecurseTree(node);\n\nprivate void RecurseTree(TreeNode node)\n{\n    if (node.Checked == true)\n    {\n        switch (node.Name)\n        {\n            case "Trial A":\n                //execute code for Trial A\n                MessageBox.Show("A"); //trial\n                break;\n            case "Trial B":\n                //execute code for Trial B\n                MessageBox.Show("B"); //trial\n                break;\n            case "Trial C":\n                //execute code for Trial C\n                MessageBox.Show("C"); //trial\n                break;\n            default:\n                MessageBox.Show("error");\n                break;\n        }\n    }\n\n    foreach (TreeNode childNode in node.Nodes) RecurseTree(childNode);\n}	0
24824815	24822614	How to make pop up GUITexture?	private boolean displayMusic = false;\nprivate boolean musicOn = true;\nvoid OnGUI() {\n\n    if (GUI.Button (new Rect (Screen.width / 2, Screen.height / 2, 150, 50), "Settings")) {\n        displayMusic = true; //If the settings button is clicked, display the music\n        // Here you could replace the above line with\n        // displayMusic = !displayMusic; if you wanted the settings button to be a\n        // toggle for the music button to show\n    }\n\n    if (displayMusic) { //If displayMusic is true, draw the Music button\n        if (GUI.Button (new Rect (Screen.width / 2, Screen.height / 2 + 50, 150, 50), "Music " + (musicOn ? "On" : "Off"))) {\n            musicOn = !musicOn; //If the button is pressed, toggle the music\n        }\n    }\n}	0
25612718	25611767	C# click html button with same id	IHTMLElementCollection buttonCol = doc.getElementsByTagName("input");\nforeach (IHTMLElement btn in buttonCol)\n{\n    if (btn.getAttribute("value") == "Report")\n    {\n        btn.click();\n        break;\n    }\n}	0
11422977	11422782	Little endian to integer	string input = "8802000030000000C6020000330000000000008000000080000000000000000018000000";\n\nfor (int i = 0; i < input.Length ; i += 8)\n{\n    string subInput = input.Substring(i, 8);\n    byte[] bytes = new byte[4];\n    for (int j = 0; j < 4; ++j)\n    {\n        string toParse = subInput.Substring(j * 2, 2);\n        bytes[j] = byte.Parse(toParse, NumberStyles.HexNumber);\n    }\n\n    uint num = BitConverter.ToUInt32(bytes, 0);\n    Console.WriteLine(subInput + " --> " + num);\n}\n\n88020000 --> 648\n30000000 --> 48\nC6020000 --> 710\n33000000 --> 51\n00000080 --> 2147483648\n00000080 --> 2147483648\n00000000 --> 0\n00000000 --> 0\n18000000 --> 24	0
33222501	33222434	get system name from application	System.Environment.MachineName	0
23745752	23745685	INotifyPropertyChanged with an Enum	private Status _status\npublic enum Status\n{\n    AuthRequired, AuthAttempted, AuthReceived, AuthError, AuthSuccessful\n}\n\npublic Status Status\n{\n    get { return _status; }\n    set\n    {\n        _status = value;\n        RaisePropertyChanged("Status");\n    }\n}	0
1185785	1185560	HttpModule/HttpApplication testing whether url is a request for a file	private void context_BeginRequest(object sender, EventArgs e)\n{\n    HttpApplication application = (HttpApplication)sender;\n    HttpContext context = application.Context;\n\n    string ext = System.IO.Path.GetExtension(context.Request.Path);\n    // ext will always start with dot\n\n}	0
9058009	9051202	C# Best Way to Darken a Color Until Its Readable	double threshold = .8;\n\nfor (int j = 0; j < 3; j++)\n{\n  if (color.GetBrightness() > threshold)\n  {\n    color[j] -= new MyRandom(0, 20/255);\n  }                   \n}	0
18152111	18152057	Application crashes when I switch to a different XAML	if (dummy == A )\n{\n    contentGrid.Dispatcher.BeginInvoke(new Action(() =>\n    {\n        var NEWVIEW = new  VIEW1();\n        contentGrid.Children.Add(NEWVIEW);\n    }));\n}	0
1841851	1841515	C# Tutorial - Binding a DataGridView to a Collection which contains an object	public class Indk?bsKurvReservedele\n{\n    //public Reservedele Reservedel  { get; private set;}\n    private int Rnr;\n    public string Navn { get; private set; }\n    public double Pris { get; private set; }\n    public string Type { get; private set; }\n    public int Antal { get; private set; }\n    public double SPris { get; private set; }\n\n    public Indk?bsKurvReservedele(Reservedele reservedel, int antal, double sPris)\n    {\n        Rnr = reservedel.Rnr;\n        Navn = reservedel.Navn;\n        Pris = reservedel.Pris;\n        Type = reservedel.Type;\n        Antal = antal;\n        SPris = sPris;\n    }\n    public int HenrReservedelsNummer()\n    {\n        return Rnr;\n    }\n}	0
17953031	17929070	Reading Live nodes in Zookeeper Solr	while (zk.State == ZooKeeperNet.ZooKeeper.States.CONNECTING)\n        {\n            Thread.Sleep(TimeSpan.FromSeconds(1));\n        }	0
4423142	4423085	C# full screen console?	Alt-Enter	0
20320212	20319488	How can I insert one register into related tables in SQL Server	declare @id_usuario int\n\n    insert into Usuario \n    ([User], [Password], FristName, Lastname, [EMail], Photo_avatar)\n    values (@User, @Password, @FristName, @Lastname, @EMail, @Photo_avatar)\n\n    set @id_usuario = SCOPE_IDENTITY()\n\n    insert into Imagenes\n    (id_usuario, Picture, Picture_name)\n    values (@id_usuario, @Picture, @Picture_name)	0
11723833	11723708	creating new windows in a threadsafe manner	Application.Current.Dispatcher.Invoke(() => { \n      var win = new Window();\n      win.show(); \n});	0
22992095	22991759	Merge menu items from MDI child into container's menu	public Form2() {\n  InitializeComponent();\n  menuStrip1.Visible = false;\n}	0
29768143	29763137	Prevent webbrowser control loading javascript from certain domain	URLMonInterop.SetProxyInProcess	0
4312879	4312806	How to combine C# code with JavaScript code in onclick?	function MyF()\n{\n    var myvar = '<%= myC#Var %>';\n    ....do something\n\n   window.close()\n\n}\n\n\n<asp:LinkButton ID="lbTest" runat="server"  OnClientClick='MyF()' />	0
7072179	7072155	Identify debugging in VisualStudio	System.Diagnostics.Debugger.IsAttached	0
31513848	31513553	Round down whole number to value	public static int RoundDownToNumber(int value, int modulus)\n{\n    if (value < 0)\n        return modulus*((value-modulus+1)/modulus);\n    else\n        return modulus*(value/modulus);\n}	0
21604649	21604537	HOW TO work with a variable, that is saved in a string content (in C#, WPF)	foreach(control x in this.Control)\n{\n    if(x.Name == A)  // For A means the name of the object\n    { x.Text = B; }  // For B means the string\n}	0
10542846	10542763	HTML Javascript Modal Popup Window with Auto Close	setTimeout(WarnTheUser,10000);//fires after 10 seconds\n\nfunction WarnTheUser()\n{\n     document.getElementById('warningDiv').innerHTML="<H1>This page will auto save in 1 minute</H1>"; //or whatever\n     setTimeout(saveData,60000);\n}\n\nfunction saveData()\n{\n   form.submit();//adjust accordingly\n}	0
9879133	9879060	Need a LINQ query to find string items	string searchString = "Jones";\nstring lowerSS = searchString.ToLower();\n\nList<NameClass> nameClasses; \n\nvar results = nameClasses.Where(nc => nc.Name.ToLower().StartsWith(lowerSS));\n\nif(results != null && results.Count() >= 3)\n{\n    return results;\n}\nelse\n{\n    return null;\n}	0
1770468	1770375	How to write an app-launching application with arguments in C#?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\n\nnamespace Launcher\n{\n  public static class Program\n  {\n    public static void Main(string[] args)\n    {\n\n        Process firefox = new Process();\n\n        firefox.StartInfo.FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe";\n        firefox.StartInfo.Arguments = "-P MyProfile -no-remote";\n\n        firefox.Start();\n\n    }\n  }\n}	0
20631896	20631765	How to check size of image from upload files control before I save it to the server?	fileUpload.PostedFile.ContentLength	0
31086064	31085923	Is there any way I can make an extension method take priority over a generic method?	Method Group	0
13640958	13640800	Check which submenu item was clicked in context menu strip	private void SubmenuItem_Click(object sender, EventArgs e)\n{\n    var clickedMenuItem = sender as MenuItem; \n    var menuText = clickedMenuItem.Text;\n\n    switch(menuText) {\n        case "Tiger":\n           break;\n\n        case "Lion":\n          break;\n         . ...\n    }\n}	0
13610790	13610709	I created a list using button clicks, now i want to display that list using a different button	private void button1_Click(object sender, EventArgs e)\n    {\n        List<string> strlst;\n        StringBuilder sb = new StringBuilder();\n        foreach(string s in strlst)\n        {\n            sb.AppendLine(s);\n        }\n\n        MessageBox.Show(sb.ToString());\n    }	0
24367723	24366674	How to match two values ??in an array?	SortedDictionary<int, int> sd = new SortedDictionary<int, int>();\nsd.Add(1, 54);\nsd.Add(5, 12);\nsd.Add(3, 17);\nsd.Add(9, 1);\nsd.Add(2, 44);\nMessageBox.Show("First: " + sd[sd.Keys.ElementAt<int>(0)].ToString() + "\nLast: " + sd[sd.Keys.ElementAt<int>(sd.Count-1)].ToString());	0
23755684	23754136	Search function for controls at run time	private void textBox1_TextChanged(object sender, EventArgs e)\n     {\n        foreach (Control c in fl_panel.Controls)\n        {              \n            if (c.Name.ToUpper().StartsWith(textBox1.Text.ToUpper().ToString()) && textBox1.Text != "")\n            {\n                Control[] ctrls = fl_panel.Controls.Find(textBox1.Text.ToString(), true);\n                c.Visible = true;  // to restore previous matches if I delete some text\n            }\n\n            else if(textBox1.Text == "")\n            {\n                c.Visible = true;\n            }\n            else\n            {\n                c.Visible = false;\n            }                      \n        }\n    }	0
21310606	21310534	How is AsQueryable() implemented in ASP.NET	/// <summary>\n/// Converts a generic <see cref="T:System.Collections.Generic.IEnumerable`1"/> to a generic <see cref="T:System.Linq.IQueryable`1"/>.\n/// </summary>\n/// \n/// <returns>\n/// An <see cref="T:System.Linq.IQueryable`1"/> that represents the input sequence.\n/// </returns>\n/// <param name="source">A sequence to convert.</param><typeparam name="TElement">The type of the elements of <paramref name="source"/>.</typeparam><exception cref="T:System.ArgumentNullException"><paramref name="source"/> is null.</exception>\n[__DynamicallyInvokable]\npublic static IQueryable<TElement> AsQueryable<TElement>(this IEnumerable<TElement> source)\n{\n  if (source == null)\n    throw System.Linq.Error.ArgumentNull("source");\n  if (source is IQueryable<TElement>)\n    return (IQueryable<TElement>) source;\n  else\n    return (IQueryable<TElement>) new EnumerableQuery<TElement>(source);\n}	0
3560667	3527938	C/C++/C#: how to force repaint of window chrome on windows 7?	RedrawWindow( hWnd, NULL, NULL, RDW_INVALIDATE | RDW_FRAME );	0
17976595	17976501	Switch Case Statement in C#	bool isValid = false;\nswitch(whateverYourVariableIsCalled)\n{\n\n\n    //FIRST CASE STATEMENT\n    case "open chrome":\n        System.Diagnostics.Process.Start(@"C:\Program Files\Google\Chrome\Application\chrome.exe");\n        JARVIS.Speak("Loading");\n        isValid = true;\n        break;\n    //SECOND CASE STATEMENT\n    case "Thanks":\n        if (isValid)\n        {\n            JARVIS.Speak("No problem");\n        }\n        isValid = false;\n        break;\n}	0
9790916	9790749	Check if a string is a palindrome	public static bool getStatus(string myString)\n    {\n        string first = myString.Substring(0, myString.Length / 2);\n        char[] arr = myString.ToCharArray();\n        Array.Reverse(arr);\n        string temp = new string(arr);\n        string second = temp.Substring(0, temp.Length / 2);\n        return first.Equals(second);\n    }	0
4806208	4806178	Correct way to Inherit multiple interfaces with same methods but different signatures?	bool ISet<TObject>.Add(TObject item) \n{\n    return(Add(item));\n}\nvoid ICollection<TObject>.Add(TObject item)\n{  \n    **return(Add(item))**;\n}\npublic new virtual bool Add(TObject item)\n{\n    // my actual add code\n}	0
681490	681474	Backreference in Regular Expression Quantifier	"(.)\1"	0
3232682	3232581	How can i get the instance of a BackgroundWorker from the currently executed method?	private void SetupThread()\n{\n    BackgroundWorker bw = new BackgroundWorker();\n    // Assuming you need sender and e. If not, you can just send bw\n    bw.DoWork += new DoWorkEventHandler(DoTheWork);\n}\n\nprivate void DoTheWork(object sender, System.ComponentModel.DoWorkEventArgs e)\n{\n    MyClass.Callback = () => \n        {\n            ((BackgroundWorker)bw).UpdateProgress(/*send your update here*/);\n            MethodCalledFromEventCallback();\n        };\n\n    MyClass.DoSomething(); // This will produce a callback(event) from MyClass\n}\n\nprivate void MethodCalledFromEventCallback() \n{ \n    // You've already sent an update by this point, so no background parameter required\n}	0
20545826	20534441	Use rails controllers in C#	public static string HttpGet(string URI) \n{\n   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);\n   req.Proxy = new System.Net.WebProxy(ProxyString, true);\n   System.Net.WebResponse resp = req.GetResponse();\n   System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());\n   return sr.ReadToEnd().Trim();\n}	0
10317511	10317211	Checking valid combination of items in list	bool containsA = false, containsB = false, containsC = false;\nfor (int i = 0; i < list.Count; i++)\n{\n    Type itemType = list[i].GetType();\n    if (!containsA) containsA = itemType == typeof(A);\n    if (!containsB) containsB = itemType == typeof(B);\n    if (!containsC) containsC = itemType == typeof(C);\n    if (containsA && (containsB || containsC)) return true;\n}\nreturn (!containsA && !containsB);	0
6335568	6335431	Windows service timer multithread	protected override void OnStart(string[] args)\n    {\n        var aTimer = new Timer(600000);\n        aTimer.Elapsed += ATimerElapsed;\n        aTimer.Interval = 600000;\n        aTimer.Enabled = true;\n        GC.KeepAlive(aTimer);\n    }\n\n    private static currentlyRunning;\n\n    private static void ATimerElapsed(object sender, ElapsedEventArgs e)\n    {\n        if(currentlyRunning) return;\n        currentlyRunning = true;\n        try\n        {\n            Worker.ProcessScheduledAudits();\n        }\n        catch (Exception ex)\n        {\n            EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);\n        }\n        currentlyRunning = false;\n    }	0
6235155	6235081	Getting specific file attributes	public static void Main(string[] args)\n{\n    List<string> arrHeaders = new List<string>();\n\n    Shell32.Shell shell = new Shell32.Shell();\n    Shell32.Folder objFolder;\n\n    objFolder = shell.NameSpace(@"C:\temp\testprop");\n\n    for( int i = 0; i < short.MaxValue; i++ )\n    {\n        string header = objFolder.GetDetailsOf(null, i);\n        if (String.IsNullOrEmpty(header))\n            break;\n        arrHeaders.Add(header);\n    }\n\n    foreach(Shell32.FolderItem2 item in objFolder.Items())\n    {\n        for (int i = 0; i < arrHeaders.Count; i++)\n        {\n            Console.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(item, i));\n        }\n    }\n}	0
28760187	28760120	How can i parse text from string and add it to a List<string> using indexof and substring?	const string openingTag = "a title=\"";\nconst string closingTag = "\" href";\n\nvar html = " sadsffdaf a title=\"???? ????\" href, a title=\" ????\" href, a title=\"???? \" href";\n\nvar names = new List<string>();\n\nvar index = 0;\nvar previousIndex = 0;\n\nwhile (index > -1)\n{\n    index = html.IndexOf(openingTag, previousIndex);\n\n    if (index == -1)\n        continue;\n\n    var secondIndex = html.IndexOf(closingTag, index);\n\n    var result = html.Substring(index + openingTag.Length, secondIndex - (index + openingTag.Length));\n    names.Add(result);\n\n    previousIndex = index + 1;\n}	0
2614304	2614287	GDI+ Problem drawing a table	private void panel1_Paint(object sender, PaintEventArgs e) {\n  e.Graphics.DrawLine(Pens.Black, 0, 0, panel1.Width, 0);\n  // etc...\n}	0
21334157	21333518	upload photo to server	BitmapImage a = new BitmapImage();\na.SetSource(e.ChosenPhoto);\nWriteableBitmap wb = new WriteableBitmap(a);\nMemoryStream ms = new MemoryStream();\nwb.SaveJpeg(ms, a.PixelWidth, a.PixelHeight, 0, 50); //50 is a quality of a photo\nimageBytes = ms.ToArray();\nbase64 = System.Convert.ToBase64String(imageBytes);	0
12818637	12818547	How do I detect in code from which View POST was made, in MVC 3?	public ActionResult TryMeOut()\n{\n   TempData["ReturnPath"] = Request.UrlReferrer.ToString();\n   //return your users to the correct view.\n}	0
21945276	21945011	C#: How do I wait for an event to be set?	using (var evt = new ManualResetEvent()) {\n Action<Result> handler = _ => evt.Set();\n SomethingCompleted += handler;\n evt.WaitOne();\n SomethingCompleted -= handler; //cut object reference to help GC\n}	0
909583	909555	How can I get the assembly file version	System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\nFileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);\nstring version = fvi.FileVersion;	0
33151981	33151171	How to to force a process to have high CPU	private static void Main()\n{\n    for (int i = 0; i < Environment.ProcessorCount; i++)\n    {\n        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));\n    }\n\n    Console.ReadLine();\n}\n\nstatic void ThreadProc(Object stateInfo)\n{\n    while (true)\n    {\n       // do something\n    }\n}	0
24668972	24664138	EF code-first mapping confusions	public class Organisation {\npublic int Id { get; set; }\npublic virtual ICollection<Course> Courses { get; set; }\n}\n\npublic class Course {\n    public int Id { get; set; }\n    public virtual Organisation Organisation { get; set; }\n}\n\n\n\n public class OrganisationSchema : EntityTypeConfiguration<Organisation>\n{\n    public OrganisationSchema()\n    {\n        ToTable(typeof(Organisation).Name);            \n        HasMany(x => x.Courses).WithRequired(x => .Organisation).WillCascadeOnDelete();\n    }\n}	0
10448663	10367582	Converting Kinect Methods from Beta 2, to Version 1	private Point getDisplayPosition(DepthImageFrame depthFrame, Joint joint)\n{ \n    float depthX, depthY;        \n    DepthImagePoint depthPoint = kineticSensor.MapSkeletonPointToDepth(joint.Position, depthImageFormat);\n\n    depthX = depthPoint.X;\n    depthY = depthPoint.Y;\n\n    depthX = Math.Max(0, Math.Min(depthX * 320, 320));\n    depthY = Math.Max(0, Math.Min(depthY * 240, 240));\n\n    int colorX, colorY;\n    ColorImagePoint colorPoint = depthFrame.MapToColorImagePoint(depthPoint.X, depthPoint.Y, sensor.ColorStream.Format);\n    colorX = colorPoint.X;\n    colorY = colorPoint.Y;\n\n    return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));\n}	0
32004500	32004229	How to extract contact numbers from long description field?	using System.IO;\nusing System;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        Regex regex = new Regex(@"\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*");\n        Match match = regex.Match("sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890 sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890");\n        List < string > list = new List < string > ();\n        while (match.Success)\n        {\n            list.Add(match.Value);\n            match = match.NextMatch();\n        }\n        list.ForEach(Console.WriteLine);\n    }\n}	0
14513296	14513267	Best way to check for an XML Element	XDocument doc = XDocument.Parse(XmlResponse)\nXElement firstElement = doc.Root.Elements().First();\nif(firstElement.Name == "ERROR")\n{\n    string errorType = firstElement.Attribute("type").Value;\n    string message = firstElement.Value;\n    // Process error\n}\nelse\n{\n    // It is an info\n}	0
10524452	10524326	Insert multiple object to MySQL	using(MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connStr))\n{  \n    conn.Open(); \n    MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();   \n    cmd.Connection = conn;   \n    cmd.CommandText = "CALL stp_InsertSubject(@param_SubjectId, @param_ProjectId, @param_Used);";  \n    cmd.Parameters.AddWithValue("@param_SubjectId",0 );   \n    cmd.Parameters.AddWithValue("@param_ProjectId", 0);   \n    cmd.Parameters.AddWithValue("@param_Used", false );   \n    foreach(List<object> sub in listSubject)   \n    {   \n        cmd.Parameters["@param_SubjectId"].Value = Convert.ToInt32(sub[0]) ;   \n        cmd.Parameters["@param_ProjectId"].Value = Convert.ToInt32(sub[1]);   \n        cmd.Parameters["@param_Used"].Value = Convert.ToBoolean(sub[2]);   \n        Id = (Int64)cmd.ExecuteScalar();   \n    }   \n}	0
23286957	11129761	Unable to get queue length / message count from Azure	CloudQueue q = queueClient.GetQueueReference(QUEUE_NAME);\nq.FetchAttributes();\nqCnt = q.ApproximateMessageCount;	0
15058402	15034912	How do I skip default JavaScript array serialization for IEnumerable types in Json.Net?	[JsonObject]\npublic class MyCustomEnumerable : IEnumerable<KeyValuePair<int,float>>\n{\n    ...\n}	0
8422971	8422864	Need examples of how to use Repository OrderBy	Func<IQueryable<SomeEntity>, IOrderedQueryable<SomeEntity>> orderBy\n    = q => q.OrderBy(e => e.SomePropertyOfSomeEntity);	0
16581388	16581270	XML file for High Scores in C#	public class HighScore\n    {\n        public int Score\n        {\n            get;\n            set;\n        }\n\n        public string Name\n        {\n            get;\n            set;\n        }\n    }\n\n    public class HighScoreCollection : List<HighScore>\n    {\n        public void SaveToXml(string fileName)\n        {\n            using (XmlWriter writer = XmlWriter.Create(fileName))\n            {\n                XmlSerializer ser = new XmlSerializer(typeof(HighScoreCollection));\n                ser.Serialize(writer, this);\n                writer.Flush();\n                writer.Close();\n            }\n        }\n    }	0
33798910	33798836	call to web api with string parameter	/api/MyController\n\n/api/MyController/string \n\n/api/MyController/1	0
7634539	7634527	How to call C .exe file from C#?	class Program\n{\n    static void Main()\n    {\n        var psi = new ProcessStartInfo\n        {\n            FileName = @"c:\work\test.exe",\n            Arguments = @"param1 param2",\n            UseShellExecute = false,\n            RedirectStandardOutput = true,\n        };\n        var process = Process.Start(psi);\n        if (process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))\n        {\n            var result = process.StandardOutput.ReadToEnd();\n            Console.WriteLine(result);\n        }\n    }\n}	0
19584319	19575110	get people from custom list	string domainUserName = properties.ListItem["user"].ToString();\nstring groupName = "site members"; // Use the group name you want to add the user to\nSPUser user = newWeb.EnsureUser(domainUserName);\nSPGroup group = newWeb.Groups[groupName];\ngroup.AddUser(user);\n// Rinse and repeat for the second web	0
1913852	1913805	LINQ query to detect duplicate properties in a list of objects	class A\n{\n public string Foo { get; set; }\n public string Bar { get; set; }\n public bool HasDupe { get; set; }\n}\n\nvar list = new List<A> { \n            new A{ Foo="abc", Bar="xyz"}, \n            new A{ Foo="def", Bar="ghi"}, \n            new A{ Foo="123", Bar="abc"}  \n           };\n\nvar dupes = \n    list.Where( a => \n                list\n                .Except( new List<A>{a} )\n                .Any( x => x.Foo == a.Foo || x.Bar == a.Bar || x.Foo == a.Bar || x.Bar == a.Foo) \n    ).ToList();\n\ndupes.ForEach(a => a.HasDupe = true);	0
6823710	6823662	How to eager load sub object of a sub object in Entities Framework	var member = context.Members.Include("MemberRoles.Roles").SingleOrDefault(....)	0
13255514	13255484	Convert String to DateTime in C# UK and US format	11/09/2011 10:34	0
20221334	20221315	Creating a List from another List, filtered by certain indexes	var set2 = set1.Skip(2).Take(3).ToList();	0
6482736	6482696	C#: How do i modify this code to split the string with hyphens?	StringBuilder result = new StringBuilder();\nfor (var i = 0; i < data.Length; i++)\n{\n    if (i > 0 && (i % 4) == 0)\n        result.Append("-");\n\n    result.Append(chars[data[i] % (chars.Length - 1)]);\n}\nresult.Length -= 1; // Remove trailing '-'	0
14459547	14459505	Using LINQ .Distinct() with DateTime - Selecting only the first instance of a date	var dates = timetableEvents.GroupBy(x => x.DateTimeStart.Date).Distinct();	0
3659769	3659747	Rounding a Value in the WPF Binding	{Binding Path=ProgressIndex, Mode=OneWayToSource, StringFormat=2N}	0
25769447	25769148	XML to string (C#)	XmlDocument doc = new XmlDocument();\n       doc.LoadXml(reply);\n       XmlNodeList nodes = doc.SelectNodes("//NodeToSelect");\n\n       foreach (XmlNode node in nodes)\n       {\n           //If the value you want is the content of the node\n           label1.Text = node.InnerText; \n           //If the value you want is an attribute of the node\n           label1.Text = node.Attributes["AttibuteName"].Value; \n       }	0
29990451	29990174	How to check if data is added to a table in LinqToSql class and date to TextBox	try \n{      \n     nwe.SubmitChanges();\n     //print: successfully added to the database\n} \ncatch {\n     //print : failure ... \n}	0
1337773	1337750	Get ImageFormat from File Extension	string InputSource = "mypic.png";\n System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);\n Graphics gInput = Graphics.fromimage(imgInput);\n Imaging.ImageFormat thisFormat = imgInput.RawFormat;	0
32507575	32507448	Calculate average return from time series with stock prices	stockRate.price_1month=objects\n  .OrderByDescending(x=>x.date)\n  .First(x=>x.date<=DateTime.Now.AddMonths(-1))\n  .price;	0
3038315	3037294	Create shortcut from vb.net on Windows 7 box (64 bit)	Imports IWshRuntimeLibrary\n\nModule Module1\n\n    Sub Main()\n        Dim WshShell As WshShell = New WshShell\n\n        Dim MyShortcut As IWshRuntimeLibrary.IWshShortcut\n\n        MyShortcut = CType(WshShell.CreateShortcut("C:\Users\Public\Desktop\Dah Browser.lnk"), IWshRuntimeLibrary.IWshShortcut)\n        MyShortcut.TargetPath = "C:\Program Files\Internet Explorer\iexplore.exe" 'Specify target app full path\n        MyShortcut.Description = "IE"\n\n        MyShortcut.Save()\n    End Sub\n\nEnd Module	0
28574587	28574438	Get Controllers index Viewbag title	RouteData route = RouteTable.Routes.GetRouteData(httpContext);\nUrlHelper urlHelper = new UrlHelper(new RequestContext(httpContext, route));\nvar routeValueDictionary = urlHelper.RequestContext.RouteData.Values;	0
28186541	26868350	Delete inbox mail item using Exchange server with C#	ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);\n        service.Credentials = new WebCredentials("xxx@yyy.com", "******");\n        service.AutodiscoverUrl("xxx@yyy.com");\n        FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));\n        if (items.Count() != 0)\n        {\n            IEnumerable<ItemId> itemIds = from p in items.Items select p.Id;\n            service.DeleteItems(itemIds, DeleteMode.MoveToDeletedItems, null, null);\n        }	0
7824459	7824316	ASP.Net Accessing child controls in a FormView control	FreeTextBox textBox = (FreeTextBox)FindControl(myFormView, "myFTB");\n\n...\n\nprivate Control FindControl(Control parent, string id)\n{\n    foreach (Control child in parent.Controls)\n    {\n        string childId = string.Empty;\n        if (child.ID != null)\n        {\n            childId = child.ID;\n        }\n\n        if (childId.ToLower() == id.ToLower())\n        {\n            return child;\n        }\n        else\n        {\n            if (child.HasControls())\n            {\n                Control response = FindControl(child, id);\n                if (response != null)\n                    return response;\n            }\n        }\n    }\n\n    return null;\n}	0
21091256	21091142	How do I convert a list of int to a list of Nullable<int>?	var items = value.Cast<int?>().ToList();	0
29091176	29023967	Finding a column value where columnID equals xxxx in JSON using C#	var test = jObject.SelectToken("columns").Where(t => t["id"].Value<Int64>() == 5283703732627332).FirstOrDefault()["title"].Value<string>();	0
1798149	1798114	VSTO word add-in get docx as byte array	byte[] bytes = File.ReadAllBytes(filename);	0
16816343	16815944	Specifiying the possibles extensions to upload in a asp.net mvc application	var extension = Path.GetExtension(file.FileName);\n    if (extension != null && extension.ToLower() != ".xlsx")\n    {\n       return "please upload file with extension .xlsx";\n    }	0
8308563	8308308	c# get value from registry without parameters	class YourClass\n{\n    public static string acrobatPath;\n    // This static constructor will be called before first access to your type.\n    static YourClass()\n    {\n        acrobatPath = Registry.GetValue(@"HKEY_CLASSES_ROOT\Applications\AcroRD32.exe\shell\Read\command", "", 0).ToString();\n        string[] split = new string[2];\n        split = acrobatPath.Split('"');\n        // mask path with ""\n        acrobatPath = "\"" + split[1] + "\""; //get only path\n    }\n}	0
22217202	22216888	Export Data to excel using C# with separate header fields	private void DumpExcel(DataTable tbl)\n{\n   using (ExcelPackage pck = new ExcelPackage())\n   {\n     //Create the worksheet\n     ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");\n\n\n     //Load the datatable into the sheet, starting from cell A1.\n     ws.Cells["A1"].LoadFromDataTable(tbl, true);\n     ExcelWorksheet.InsertRow(int rowFrom, int rows, intCopyStylesFromRow);\n\n     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n     Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");\n     Response.BinaryWrite(pck.GetAsByteArray());\n    }\n }	0
3965742	3965694	How to resize a button depending on its text	using(Graphics cg =  this.CreateGraphics())\n   {\n       SizeF size = cg.MeasureString("Please excuse my dear aunt sally",this.button1.Font);\n\n       // size.Width+= 3; //add some padding .net v1.1 and 1.0 only\n       this.button1.Padding = 3;\n       this.button1.Width = (int)size.Width;\n\n       this.button1.Text = "Please excuse my dear aunt sally";\n   }	0
4786822	4786576	Trigger event using timer on a specific day and time	private static void SetTimer(Timer timer, DateTime due) {\n        var ts = due - DateTime.Now;\n        timer.Interval = ts.TotalMilliseconds;\n        timer.AutoReset = false;\n        timer.Start();\n    }	0
26665701	26656810	Map is capturing Tap events from MapItemsControl elements	Pin.Tapped += (s,e)=>{\n    e.Handled = true;\n};	0
24685478	24685464	c# String formatting an Integer to a Decimal	decimal d = (decimal)45099 / 100;	0
11027327	11027278	Controlling Display Position And Appearance Of Item In List View	ListViewItem item3 = new ListViewItem("");\nitem3.SubItems.Add("");\nitem3.SubItems.Add("Total");\nitem3.SubItems.Add(odr2["amount"].ToString());\nlistView1.Items.Add(item3);	0
21555970	21555596	Sort Listbox items by user score	string [] items = new string[listBox1.Items.Count];\nlistBox1.Items.CopyTo(items, 0);\nArray.Sort(items, delegate(string a, string b) {\n    // Should add error checking here in case string in wrong format\n    int ascore = Int32.Parse(a.Substring(a.IndexOf(':') + 1));\n    int bscore = Int32.Parse(b.Substring(b.IndexOf(':') + 1));\n    return ascore == bscore ? 0 : (ascore < bscore ? 1 : -1);\n});\nforeach(string s in items) {\n    Console.WriteLine(s.Replace(":", " score: "));\n}	0
4023598	4021595	How to pass parameters to rest web service without using the (?) Symbol?	[ServiceContract]\npublic interface ISearch\n{\n    [OperationContract]\n    [WebGet(UriTemplate = "/Search/{name}", BodyStyle = WebMessageBodyStyle.Bare)]\n    string  GetGreeting(string name);\n}	0
7676717	7676533	What are the steps to convert a large class from static to non-static?	public class Foo \n{\n\n    #region Singleton\n\n    Foo()\n    {\n    }\n\n    public static Foo Instance\n    {\n        get\n        {\n            return Nested.instance;\n        }\n    }\n\n    class Nested\n    {\n        static Nested() { }\n\n        internal static readonly Foo instance = new Foo();\n    }\n\n    #endregion	0
6733077	6731869	chaining a table of object with Linq	from p in Players\njoin m in Matches on p.PlayerID equals m.PlayerID\nselect new { p, m }	0
10101383	10101363	count number of identical elements in two arrays in linq	A1.Intersect(A2).Count()	0
23844929	23753610	windows store adding files in zip archieve dynamically	public async void zipit(StorageFile zipFile, StorageFile file)\n    {\n     using (var zipToOpen = await zipFile.OpenStreamForWriteAsync())\n        {\n            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))\n            {\n                ZipArchiveEntry readmeEntry = archive.CreateEntry(file.Name);\n                using (Stream writer = readmeEntry.Open())\n                {\n                    //writer.WriteLine("Information about this package.");\n                    //writer.WriteLine("========================");\n                    byte[] data = await GetByteFromFile(file);\n                    writer.Write(data, 0, data.Length);\n                }\n            }\n        }\n    }	0
19364908	19364775	Regex Parsing / Splitting WKT (Well Known Text) into Key Value Pairs	([^\[]+?)\[(.*)\]	0
3957777	3957291	Session transfer between window and modal dialog	if(IsPostPostBack)	0
34512111	34511496	XML serialization of a class in another class	public class Drop\n{\n    [XmlText]\n    public string DropInfo;\n}	0
11622241	11622066	Select Multiple Rows or Single Cell only in DataGrid	private void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)\n    {\n        int columnsCount = this.Columns.Count;\n        int selectedCells = SelectedCells.Count;\n        int selectedItems = SelectedItems.Count;\n\n        if (selectedCells > 1)\n        {\n            if (selectedItems == 0 || selectedCells % selectedItems != 0)\n            {\n                DataGridCellInfo cellInfo = SelectedCells[0];\n                SelectedCells.Clear();\n                SelectedCells.Add(cellInfo);\n                CurrentCell = SelectedCells[0];\n            }\n        }\n    }	0
6997062	6996942	C# Sort List of X,Y Coordinates Clockwise	if (aTanA < aTanB) return -1;\nelse if (aTanB > aTanA) return 1;	0
1138852	1138723	TimeSpan to friendly string library (C#)	DateTime dtNow = DateTime.Now;\nDateTime dtYesterday = DateTime.Now.AddDays(-435.0);\nTimeSpan ts = dtNow.Subtract(dtYesterday);\n\nint years = ts.Days / 365; //no leap year accounting\nint months = (ts.Days % 365) / 30; //naive guess at month size\nint weeks = ((ts.Days % 365) % 30) / 7;\nint days = (((ts.Days % 365) % 30) % 7);\n\nStringBuilder sb = new StringBuilder();\nif(years > 0)\n{\n    sb.Append(years.ToString() + " years, ");\n}\nif(months > 0)\n{\n    sb.Append(months.ToString() + " months, ");\n}\nif(weeks > 0)\n{\n    sb.Append(weeks.ToString() + " weeks, ");\n}\nif(days > 0)\n{\n    sb.Append(days.ToString() + " days.");\n}\nstring FormattedTimeSpan = sb.ToString();	0
455985	454147	How can I prompt the user to reboot in a .NET installation?	cscript "C:\Program Files\Microsoft SDKs\Windows\v6.0\Samples\SysMgmt\MSI\scripts\WiRunSQl.vbs" my.msi "INSERT INTO `Property`(`Property`, `Value`) VALUES ('REBOOT', 'F')"	0
25440274	25439631	WCF client configuration from custom location	IServiceContract proxy = ChannelFactory<IServiceContract>.CreateChannel(new WSHttpBinding(),\n                    new EndpointAddress("<you url here>"));	0
24926234	24924949	How to use ShareLinkTask namespace in Windows Phone 8.1?	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    DataTransferManager dtManager = DataTransferManager.GetForCurrentView();\n    dtManager.DataRequested += dtManager_DataRequested;\n}\n\nprivate async void dtManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs e)\n{\n    e.Request.Data.Properties.Title = "Code Samples";\n    e.Request.Data.Properties.Description = "Here are some great code samples for Windows Phone.";\n    e.Request.Data.SetWebLink(new Uri("http://code.msdn.com/wpapps"));\n}\n// Click Button to share Web Link\nprivate void btnShareLink_Click(object sender, RoutedEventArgs e)\n{\n    Windows.ApplicationModel.DataTransfer.DataTransferManager.ShowShareUI();\n}	0
2031313	2031304	What's the easiest way to convert a list of integers to a string of comma separated numbers in C#	string.Join(",", l.ConvertAll(i => i.ToString()).ToArray());	0
3982727	3982673	Force base method call	public virtual void BeforeFoo(){}\n\npublic void Foo()\n{\n\nthis.BeforeFoo();\n//do some stuff\nthis.AfterFoo();\n\n}\n\npublic virtual void AfterFoo(){}	0
6279562	6279503	C#: Searching for a keyword in a txt file	System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");\n\nString line;\nString[] array;\n\nwhile((line = file.ReadLine()) != null)\n{\n   if (line.Contains("myString"))\n   {\n      array = line.Split(',');\n   }\n}\n\nfile.Close();	0
11747215	11747114	complex linq-to-sql join with 4 tables: how many where clauses should there be?	var query  from a in MyDC.Table1 \n           join b in MyDC.Table2 on a.Property1 equals b.Property2\n           join c in MyDC.Table3 on b.Property1 equals c.Property5\n           join d in MyDC.Table4 on c.Property2 equals d.Property1\nselect ...	0
4415052	4415027	nHibernate -> Dependency in the UI layer	public class SessionManager : ISessionManager\n{\n    private  readonly ISessionFactory _sessionFactory;\n\n     SessionManager()\n    {\n        _sessionFactory = CreateSessionFactory();\n    }\n\n    public void OpenSession()\n    {\n        ISession session = _sessionFactory.OpenSession();\n\n        session.BeginTransaction();\n\n        CurrentSessionContext.Bind(session);\n    }\n\n\n    public void CloseSession()\n    {\n        ISession session = CurrentSessionContext.Unbind(_sessionFactory);\n\n\n        if (session == null) return;\n\n\n        try\n        {\n            session.Transaction.Commit();\n        }\n\n        catch (Exception)\n        {\n            session.Transaction.Rollback();\n        }\n\n        finally\n        {\n            session.Close();\n\n            session.Dispose();\n        }\n    }\n}	0
29973890	29973622	Keywords to find good tutorials	HashTable<fromName, List<YourDBObject>>	0
6374425	6373122	How to configure Ninject so that it would inject right instance depending on previously injected instance	interface IRepository {  /* methods and properties */ }\ninterface IUserRepository : IRepository {}\ninterface ICentralRepository : IRepository {}\n\nclass Foo\n{\n   public Foo(IUserRepository userRepo, ICentralRepository centralRepo)\n   {\n      // assign to fields\n   }\n}	0
6141903	6140058	Uncertain of how to implement a specific extension to nHibernate with LINQ	public static IQueryable<Post> MySecurityExtension(this IQueryable<Post> repository, string currentUser)\n    {\n        return repository.Where(p => p.User == currentUser);\n    }	0
31040093	31037019	Shortening or omitting namespace for enum in OData filter	'MyValue'	0
25638860	25600893	Assembly throughout two projects	[assembly: InternalsVisibleTo("NAME_OF_NAMESPACE")]	0
9571133	9569011	converting from dto to polymorphic business object	var factory = new OrderDTOFactory();\nOrderDTO orderDTO = factory.CreateOrder(order);	0
26934035	26931853	Refused to display '' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'	protected void Application_PreSendRequestHeaders()\n    {\n        Response.Headers.Remove("X-Frame-Options");\n         Response.AddHeader("X-Frame-Options", "AllowAll");\n\n    }	0
6713215	6713154	How to name instance variables in VB.NET since not case sensitive	class Person\n{\n    Person friend = new Person();\n    public void GetPencil()\n    {\n        bool pencilFound = \n            friend.AskQuestion(this, "Can I borrow your pencil?")\n            .ToLower().Contains("yes");\n    }\n\n    public string AskQuestion(Person enquirer, string question)\n    {\n        // Analyze question implications.\n        return "Decision made.";\n    }\n}	0
2613594	2613577	Fastest way to check a List<T> for a date	List<DateTime> days = ...;\ndays.Sort();\nDateTime dt = days[0].Date;\nfor (int i = 0; i < days.Length; dt = dt.AddDays(1))\n{\n    if (dt == days[i].Date)\n    {\n        Console.WriteLine("Worked: {0}", dt);\n        i++;\n    }\n    else\n    {\n        Console.WriteLine("Not Worked: {0}", dt);\n    }\n}	0
12141604	12141052	extracting an array from an array in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        int[] array1 = new int[10];\n        var list1 = new List<int>() { 0, 1, 52 };\n        var list2 = new List<string>() { "Mike" };\n\n        func(3, 4, array1, list1, "hello", list2);\n\n    }\n\n    static void func(int x, int y, params object[] arr)\n    {\n        // Gets all lists and arrays from arr\n        IEnumerable<object> listsAndArrays = arr.Where(a => a is IList);\n        // Gets all arrays from arr\n        IEnumerable<object> arrays = arr.Where(a => a is Array);\n        // Gets all lists from arr\n        IEnumerable<object> lists = arr.Where(a => a.GetType().IsGenericType && a.GetType().GetGenericTypeDefinition() == typeof(List<>));\n    }\n}	0
5954632	5954554	Get DateTime for the nth Sunday after today	DateTime sundayInFuture = DateTime.Today.AddDays((n - 1) * 7 + (7 - (int)DateTime.Today.DayOfWeek));	0
15849847	15849814	Entry value of ComboBox1 to label1	label1.Text = label1.Text + " - " + text;	0
9150976	9150944	How to keep and add items in a List of objects during button click events	List<ProdusBon> listaProduseBon\n{\n   get { return (List<ProdusBon>) Session["ProdusBon"]; }\n   set { Session["ProdusBon"] = value; }\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (listaProduseBon == null) listaProduseBon = new List<ProdusBon>();\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    listaProduseBon.Add(new ProdusBon(-1, Int32.Parse(TextBox2.Text), -1, Int32.Parse (ListBox1.SelectedValue)));\n}	0
13220308	13220279	Comparing two Int variables with room/margin for error	int eps = 5;\nif (Math.abs(tempX - headX) <= eps && Math.abs(tempY - headY) <= eps) { \n    // ...\n}	0
15500577	15500508	Select an variable using multi variables	var red = new int[]{0,0,0,0,0,0};\nvar blue = new int[]{0,0,0,0,0,0};\n\nvar arrayToUse = redorblue == "red" ? red : blue;\nfor (int i = 0; i < count; i++)\n{\n    var value = arrayToUse[i];\n    // ....\n}	0
2632376	2632323	how to use Foreign key in L2E or EF?	List<User> users = context.Users.Include("Privilege").ToList();	0
5251780	5249540	c# programmatically reading emails from the Exchange server	service.Url = new Uri("https://hostname/EWS/Exchange.asmx");	0
19428452	19367064	Getting ASP:Menu to center in the middle of the page	nav{\nclear: both;\ntext-align: center;\ndisplay: table;\nmargin: 0 auto;}	0
30299446	30299352	Perform operation on all objects of object's properties	foreach (var property in this.GetType().GetProperties())\n{\n    var propVal = property.GetValue(this) as List<Object>;\n    if (propVal != null)\n    {\n        propVal.Clear();\n    }\n}	0
30967997	30967607	How to use Join and Where to return an IList?	public IList<Promotion> GetRewardsForUser(string userId)\n{\n    //a list of all available promotions\n    IList<Promotion> promos =  _promotionLogic.Retrieve();\n\n    //contains a list of Promotion.objectIds for that user\n    IList<PromotionsClaimed> promosClaimed = _promotionsClaimedLogic.RetrieveByCriteria(t => t.userId == userId);\n\n    //should return a list of the Promotion name and code for the rewards claimed by user, but a complete list of Promotion entities would be fine\n    var selectedPromos =\n        (from promo in promos\n        join promoClaimed in promosClaimed on promo.objectId equals promoClaimed.PromotionId\n        select new { PromoName = promo.Name, PromoCode = promo.Code }).ToList();\n\n    return selectedPromos;\n}	0
5477391	5477357	How to convert RGB int values to string color	int red = 255;\nint green = 255;\nint blue = 255;\n\nstring hexColor = "#" + red.ToString("X") + green.ToString("X") + blue.ToString("X");	0
28967443	28967353	many-to-many relationship with additional value	Create Table CourseStudentTie(\n  [StudentId] int NOT NULL,\n  [CourseId] int NOT NULL,\n  [Order] int NOT NULL --This is where you store the order of the courses.\n)	0
12733847	12733485	DI Castle WCF constructor How Do I	public class MyOwnServiceHostFactory: Castle.Facilities.WcfIntegration.DefaultServiceHostFactory\n{\n\n    public MyOwnServiceHostFactory() : base(CreateKernel())\n    { }\n\n    private static Castle.MicroKernel.IKernel CreateKernel()\n    {\n        var container = new Castle.Windsor.WindsorContainer();\n        container.Install(new WindsorInstaller());\n        return container.Kernel;\n    }\n\n}\n\n\npublic class WindsorInstaller : IWindsorInstaller\n{\n\n    #region IWindsorInstaller Members\n\n    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)\n    {\n        container.AddFacility<Castle.Facilities.WcfIntegration.WcfFacility>();\n        container.AddFacility<Castle.Facilities.TypedFactory.TypedFactoryFacility>();\n\n        container.Kernel.Resolver.AddSubResolver(new Castle.MicroKernel.Resolvers.SpecializedResolvers.ListResolver(container.Kernel));\n        // add your services here...\n    }\n\n}	0
28639947	28639897	Compare two IEnumerable<> Collection data	var workingBag = new List<int>(secondCollection);\nvar results = firstCollection.Select(i => new ClassA(i, workingBag.Remove(i));	0
3355604	3355576	Cell color of WPF DataGrid back to the default	dgc.ClearValue(DataGridCell.BackgroundProperty);	0
14790487	14789998	multithreaded server	private void radButtonStartWCFService_Click(object sender, EventArgs e)\n{\n    try\n    {\n        Thread Trd = new Thread(() => StartWCFServer());\n        Trd.IsBackground = true;\n        Trd.Start();\n\n        radButtonStartWCFService.Enabled = false;\n        radButtonStartWCFService.Text = "WCF Server Started";\n\n    }\n\n    catch(Exception ex)\n    {\n        MessageBox.Show(ex.Message.ToString());\n    }\n}\n\n\nprivate void StartWCFServer()\n{\n\n    try\n    {\n        sHost = new ServiceHost(typeof(WCFService.WCFJobsLibrary));\n        sHost.Open();\n\n    }\n\n    catch (Exception ex)\n    {\n\n        MessageBox.Show(ex.Message.ToString());\n\n    }\n}	0
6413345	6413224	DotNetZip - rename file entry in zip file while compressing	using (ZipFile zip1 = new ZipFile())\n  {\n      zip1.AddFile("myFile.txt").FileName = "otherFile.txt"; \n      zip1.Save(archiveName);\n  }	0
3744720	3743956	Is there a way to check to see if another program is running full screen	[StructLayout(LayoutKind.Sequential)]\n    private 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    private static extern bool GetWindowRect(HandleRef hWnd, [In, Out] ref RECT rect);\n\n    [DllImport("user32.dll")]\n    private static extern IntPtr GetForegroundWindow();\n\n    public static bool IsForegroundFullScreen()\n    {\n        return IsForegroundFullScreen(null);\n    }\n\n    public static bool IsForegroundFullScreen(Screen screen)\n    {\n        if (screen == null)\n        {\n            screen = Screen.PrimaryScreen;\n        }\n        RECT rect = new RECT();\n        GetWindowRect(new HandleRef(null, GetForegroundWindow()), ref rect);\n        return new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top).Contains(screen.Bounds); \n    }	0
4781285	4733186	Seeking keyframes using DirectShowNet	public int SampleCB ( double sampleTime, IMediaSample mediaSample )\n{\n    Console.WriteLine ( "SampleCB Callback" );\n    Console.WriteLine ( mediaSample.IsSyncPoint ( ) + " " );\n\n        /* other code */\n    Marshal.ReleaseComObject ( mediaSample );\n    return 0;\n}	0
11721568	11721396	Expression predicates with field name with a ToUpper	public static Expression<Func<T, bool>> CreatePredicate<T>(string typeSearch, string searchField, string stringToSearch)\n{\n    var parameter = Expression.Parameter(typeof(T));\n    var predicate = Expression.Lambda<Func<T, bool>>(\n        Expression.Call(\n            Expression.Call(Expression.PropertyOrField(parameter, searchField), "ToUpper", null),\n            "Contains", null,\n            Expression.Constant(stringToSearch.ToUpper())), parameter);\n\n    return predicate;\n}	0
9614200	9614077	How to use TIME datatype in SQL Server 2008 and C#?	private static TimeSpan? GetTime(IDataReader rdr, string columnName)\n{\n    int index = rdr.GetOrdinal(columnName);\n    if (rdr.IsDBNull(index))\n    {\n      return null;\n    }\n   return (TimeSpan)rdr[index];\n}	0
7527092	7527047	how to Check datetime entered	if ((string.IsNullOrEmpty(txt_SendAt.Text) == false \n             && DateTime.Parse(txt_SendAt.Text) <= DateTime.Now )	0
2196914	2189301	Cleaner way to cast a C# enum	((Int32)(field.DisplayFormat)).ToString();	0
27847503	27846923	NewtonSoft JSON within strings serialization	var finalString = new JArray(list.Select(JToken.Parse).ToArray()).ToString();	0
28458628	28458586	How to write multiple things to console at once?	Console.Writeline("{0}{1}", a, b);	0
3390085	3390062	List, SortedList, Dictionary to store objects by key and serialize them?	Dictionary<string, MyClass>	0
1891684	1891521	Convert XmlNodeList to XmlNode[]	static void Main(string[] args)\n{\n    XmlDocument xmldoc = new XmlDocument();\n    xmldoc.LoadXml("<a><b /><b /><b /></a>");\n    XmlNodeList xmlNodeList = xmldoc.SelectNodes("//b");\n    XmlNode[] array = (\n        new System.Collections.Generic.List<XmlNode>(\n            Shim<XmlNode>(xmlNodeList))).ToArray();\n}\n\npublic static IEnumerable<T> Shim<T>(System.Collections.IEnumerable enumerable)\n{\n    foreach (object current in enumerable)\n    {\n        yield return (T)current;\n    }\n}	0
19181090	19180919	Select subset of XML	string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +\n        "<root version=\"1\">" +\n        "<targets>" +\n            "<target type=\"email\">" +\n                "<property name=\"to\">b1q23@email.com</property>" +\n            "</target>" +\n            "<target type=\"fob\"/>" +\n        "</targets>" +\n        "<observation uniqueID=\"00A60D\" deviceID=\"308610ea23\">" +\n            "<field name=\"field1\">test1</field>" +\n            "<field name=\"field2\">test2</field>" +\n        "</observation>" +\n        "</root>";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nXmlElement root = doc.DocumentElement;\nvar observationNode = root.SelectSingleNode("/root/observation");\n\nvar observationXml = observationNode.OuterXml;	0
17456154	17455946	Could not find control 'MainContent_DropDownList1' in ControlParameter 'Company'	protected void Page_Init(object sender, EventArgs e)\n{\n    Page.Controls.Add(Gridsource);\n}	0
13995667	13988969	LINQ: Get values with latest date	var query = (from d in Data\n             group d by d.Code into g\n             select g.OrderByDescending(t => t.FromDate).FirstOrDefault());\n\nquery = query.Where(d => d.Name.ToUpper().Contains("BERT") && d.Code != null);\n\nquery.Dump();	0
15779566	15779475	Insert datatable in to sql table	DataTable dt = new DataTable();\n string sql = "";\n for (int i = 0; i < dt.Rows.Count; i++)\n {\n    sql = sql + "insert into InvitationData (Col1, Col2, ColN) values('"\n          + dt.Rows[i]["columnname"].ToString().Trim() + "','"\n          + dt.Rows[i]["columnname"].ToString().Trim() + "','" \n          + dt.Rows[i]["columnname"].ToString().Trim() + "')";\n }	0
5857194	5857159	how to preserve objects across pages	MyType myObject = (MyType)Session["MyObject"];\n\nSession["MyObject"] = myObject;	0
6120825	6097043	Display Currency symbols in a Grid	XmlReader reader = XmlReader.Create(new StringReader(spfield.SchemaXml));\nXmlDocument doc = new XmlDocument();\nXmlNode node = doc.ReadNode(reader);\nstring curSymbol = "";\nif (node.Attributes["LCID"] != null)\n{\n    string lcidValue = node.Attributes["LCID"].Value;\n    CultureInfo ci = new CultureInfo( Convert.ToInt32(lcidValue));\n    curSymbol = ci.NumberFormat.CurrencySymbol;                \n}\nfield.HtmlEncode = false;\nfield.DataFormatString = curSymbol + " {0:#,###.##}";	0
21481880	21481328	Generic Method gets parameter type from superclass	abstract class AbstractClass<T>\nwhere T: AbstractClass<T> //restrict T as a child of AbstractClass<T>\n{\n    bool update()\n    {\n        Connection.Update<T>(this as T);\n    }\n}\n\nclass Entity : AbstractClass<Entity>\n{\n}\n\nclass Connection\n{\n    public static void Update<T>(T obj)\n    {\n        someMethod<T>()\n    }\n}	0
28216623	28216444	WPF update TreeView when source updates for a tree model	public class Node : INotifyPropertyChanged\n{\n    private Node _parent;\n    public Node Parent \n    {\n        get\n        {\n            return this._parent;\n        }\n\n        set\n        {\n            if (value != this._parent)\n            {\n                this._parent= value;\n                NotifyPropertyChanged();\n            }\n        }\n    }\n\n    public ObservableCollection<Node> Children { get; private set; }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n\n}	0
19439413	19439199	Get maximum size of the control without maximizing it, windows forms	using System.Reflection;\nprivate PictureBox DoSomethingWithProperties(PictureBox picturebox)\n{\n    Type pictureboxType = picturebox.GetType();\n    PictureBox instance = (PictureBox)Activator.CreateInstance(pictureboxType)\n    // The above code is only used to create an instance of the picturebox type. \n    // This will enable modification/changes to the picturebox property values during runtime via late-binding.\n    PropertyInfo DefaultSize= instance.GetType().GetProperty("DefaultSize", BindingFlags.Public | BindingFlags.Instance);\n    PropertyInfo ClientSize= instance.GetType().GetProperty("ClientSize", BindingFlags.Public | BindingFlags.Instance);\n    PropertyInfo DefaultMaximumSize= instance.GetType().GetProperty("DefaultMaximumSize", BindingFlags.Public | BindingFlags.Instance);\n    return instance;\n}	0
4209917	4209867	Find the depth of a node in C#	int nodeToFind = 2;\nvar currentNode = list.Single(n => n.Id == nodeToFind);\nint depth = 0;\nwhile ((currentNode = list\n    .FirstOrDefault(i => i.Left == currentNode.Id || i.Right == currentNode.Id)) != null)\n\n    depth++;\nConsole.WriteLine(depth);	0
3147719	3147687	How to prevent a password input from clearing after submit?	string Password = txtPassword.Text;\ntxtPassword.Attributes.Add("value", Password);	0
15506299	15483369	Data Import - Excel to SQL Azure?	Dim dt As DataTable = New DataTable("myData")\nDim DataFile As FileInfo = New FileInfo("c:\myspreadsheet.csv")\n\nDim MyConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & DataFile.Directory.FullName & "';Extended Properties='text;HDR=NO';Jet OLEDB:Engine Type=96;")\nDim oledataAdapter As OleDbDataAdapter\noledataAdapter = New OleDbDataAdapter("SELECT * FROM [" & DataFile.Name & "]", MyConnection)\n\noledataAdapter.Fill(dt) 'Bind the csv to the data table\n\n'LOOP AND INSERT HERE...\nFor Each DataRowObj As DataRow In dt.Rows\n\nNext	0
28387944	28387875	Start WCF service application from another application (C#)	public static void Main()\n{\n  using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))\n  {\n    try\n    {\n      // Open the ServiceHost to start listening for messages.\n      serviceHost.Open();\n\n        // The service can now be accessed.\n      Console.WriteLine("The service is ready.");\n      Console.WriteLine("Press <ENTER> to terminate service.");\n      Console.ReadLine();\n\n      // Close the ServiceHost.\n      serviceHost.Close();\n    }\n    catch (TimeoutException timeProblem)\n    {\n      Console.WriteLine(timeProblem.Message);\n      Console.ReadLine();\n    }\n    catch (CommunicationException commProblem)\n    {\n      Console.WriteLine(commProblem.Message);\n      Console.ReadLine();\n    }\n  }\n}	0
18513679	18513646	How to handle "if conditon" for variable?	var page = (string)IsolatedStorageSettings.ApplicationSettings["qsPage"];	0
19624225	19624167	Using update command in Switch statement	case "1":\n    using(SqlCommand myCmd = new SqlCommand("UPDATE Mytable SET Stage=@myStage", con)\n    {\n       myCmd.Parameters.AddWithValue("@myStage", txtStageLevel.Text);\n       myCmd.ExecuteNonQuery();\n    }\n    break;	0
618300	618259	Remove transparency in images with C#	void RemTransp(string file) {\n    Bitmap src = new Bitmap(file);\n    Bitmap target = new Bitmap(src.Size.Width,src.Size.Height);\n    Graphics g = Graphics.FromImage(target);\n    g.DrawRectangle(new Pen(new SolidBrush(Color.White)), 0, 0, target.Width, target.Height);\n    g.DrawImage(src, 0, 0);\n    target.Save("Your target path");\n}	0
18607153	18606618	Finding the last filled row in Excel sheet in c#	string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\xxxxxx\Desktop\1-8-13-ct.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False";\n    //Create Connection to Excel work book\n    OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);\n    //Create OleDbCommand to fetch data from Excel\n     OleDbCommand cmd = new OleDbCommand("select count(*) from [Sheet1$]", excelConnection);\n    con.Open();\n    int rows = (int)cmd.ExecuteScalar();\n  con.Close();	0
11673842	11673734	SortedList Compare	// list of items where weight was not zero, but its zero in the newlist.\nvar result1 = from o in oldList\n              join n in newList on o.Key equals n.Key \n              where o.Value != 0 && n.Value == 0\n              select new {Old = o, New = n};\n\n// list of items where weight is not zero and has changed from oldlist.\nvar result2 = from o in oldList\n              join n in newList on o.Key equals n.Key\n              where o.Value != 0 && o.Value != n.Value\n              select new { Old = o, New = n };	0
25337411	25337336	How to make text be "typed out" in console application?	static void TypeLine(string line) {\n    for (int i = 0; i < line.Length; i++) {\n        Console.Write(line[i]);\n        System.Threading.Thread.Sleep(150); // Sleep for 150 milliseconds\n    }\n}	0
16159849	16159768	Giving a property two identifiers for deserializing JSON	[JsonProperty("plugin_name")]\npublic string PluginName{get;set;}	0
9445488	9444471	Call Winzip32.exe with parameter with c#	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.FileName = "C:\\Program Files\\WinZip\\winzip32.exe";\nstartInfo.WindowStyle = ProcessWindowStyle.Hidden;	0
12528440	12528304	How to Add an item to a specific index in a PagedCollectionView?	List<String> itemList = new List<String>();\n\n// Generate some items to add to the list.\nfor (int i = 1; i <= 33; i++)\n{\n    System.Text.StringBuilder sb = new System.Text.StringBuilder("Item ");\n    sb.Append(i.ToString());\n    itemList.Add(sb.ToString());\n}\n\n// Add at given index\nitemList.Insert(10, "Extra item");\n\n// Wrap the itemList in a PagedCollectionView for paging functionality\nvar itemListView = new PagedCollectionView(itemList);	0
7832007	7831964	How to prevent C# compiler/CLR from optimizing away unused variables in DEBUG builds?	var tmp = SomeMethod();\n // your other code\n Debug.WriteLine(tmp);	0
30997658	30994697	Adding SQL Server CE files in app_data folder at runtime	// refresh tenant because otherwise it stays in setup mode\nvar tenant = _tenantService.GetTenants().FirstOrDefault(ss => ss.Name == name);\nif (tenant == null) return HttpNotFound();\ntenant.State = TenantState.Disabled;\n_tenantService.UpdateTenant(tenant);\n\nvar tenant2 = _tenantService.GetTenants().FirstOrDefault(ss => ss.Name == name);\nif (tenant2 == null) return HttpNotFound();\ntenant2.State = TenantState.Running;\n_tenantService.UpdateTenant(tenant2);	0
33714059	33710394	Get available app memory with Xamarin iOS	var mem = NSProcessInfo.ProcessInfo.PhysicalMemory;	0
17318700	17318609	How to get all properties with an specific name and create a List<KeyValuePair<string,string>>	SyncJobs_Result job = (SyncJobs_Result)entity.Entity;\nvar properties = typeof(SyncJobs_Result)\n    .GetProperties(BindingFlags.Static | BindingFlags.Public)\n    .Where(p => p.Name.Contains("Role") && p.PropertyType == typeof(string))\n    .Select(p => new KeyValuePair<string, string>(p.Name, p.GetValue(job, null) as string))\n    .ToList();	0
6248074	6248039	How to sort list of Ip Addresses using c#	var unsortedIps =\n    new[]\n    {\n        "192.168.1.4",\n        "192.168.1.5",\n        "192.168.2.1",\n        "10.152.16.23",\n        "69.52.220.44"\n    };\n\nvar sortedIps = unsortedIps\n    .Select(Version.Parse)\n    .OrderBy(arg => arg)\n    .Select(arg => arg.ToString())\n    .ToList();	0
8781006	8780505	How do i add $ref to a JSONSchema?	string oneSchema = @"{ \n    ""id"": ""http://some.where/sub/schema#"", \n    ""type"": ""object"", \n    ""properties"": { \n        ""p1"": { \n            ""type"": ""integer"", \n            ""minimum"": 12 \n        } \n    }     \n} ";\n\nstring main = @"\n{ \n    ""id"": ""http://path.to/base/schema#"", \n    ""type"": ""array"", \n    ""items"": { \n        ""extends"": { \n            ""$ref"": ""http://some.where/sub/schema#/properties/p1"" \n        }, \n        ""divisibleBy"": 5 \n    }     \n}";\n\nvar JObjMain = (JObject)JsonConvert.DeserializeObject(main);\nvar jObjOther = (JObject)JsonConvert.DeserializeObject(oneSchema);\n\nJToken src = JObjMain["items"]["extends"]["$ref"];\nJToken reference = jObjOther["id"];\n\n\nvar path = src.ToString().Replace(reference.ToString(), "").Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);\nJToken j = jObjOther[path[0]];\nfor(int i=1;i<path.Length;i++)\n{\n    j = j[path[i]];\n}\n\nsrc.Replace(j);\n\nConsole.WriteLine(JObjMain);	0
6672438	6671652	FileSystemWatcher stops raising events after a period of time	protected virtual void TimerTick(object sender, EventArgs e)\n{\n    // stop your timer\n    this.timer.Stop();\n\n    try\n    {\n        // TODO: add event handler specifics\n    }\n    catch\n    {\n        // TODO: add some logging to help you see what's going on\n    }        \n\n    // restart your timer\n    this.timer.Start();\n}	0
24532855	24532642	Transaction Scope and Multiple Regions	using (var tx = new TransactionScope()) {\n     process1();\n     process2();\n     tx.Complete();\n}	0
11696438	11696391	Get a count of items with a certain condition within a StackPanel's Children	int FinishedItems = panel.Children.OfType<MyObject>()\n                         .Count(mo => mo.IsFinished);	0
27680932	27679980	Add events to a control C#	Panel p = tmpI.getPanel()\n main.Controls.Add(p);\n main.Controls.SetChildIndex(p, 0);	0
18443210	18443146	How to search through all items of a combobox in C#?	for (int i = 0; i < myComboBox.Items.Count; i++)\n{\n     string value = myComboBox.GetItemText(myComboBox.Items[i]); \n}	0
1017981	1017959	Limit the number of results on a ASP.NET ListView	yourlist.Take(5);	0
9440232	9440170	how do i start many threads in a queue?	public void PasteFromCopy(string source,string dest)\n{\n    lock(this)\n    {\n        if (IsFolder(source))\n        {\n            CopyDirectory(source, dest);\n        }\n        else\n        {\n            CopyStream(source, dest); \n\n        }\n    }\n}	0
28224369	28223462	How can I convert this timestamp function from php to C#?	10100101100110111001011111101000101000110 - 1422560055622\n           110111001011111101000101000110 - 925880646\n        210987654321098765432109876543210\n        333222222222211111111110000000000	0
14371057	14370643	Refresh DataContext in LINQPad	while(1 = 1) \n{     \n    var freshDC = new TypedDataContext();\n    var me = freshDC.MyEntities.FirstOrDefault(); \n    ...\n}	0
11233382	11232214	Linq to sql stored procedure return value	ExecuteScalar(...)	0
8172589	8172565	How to write Linq depending if a value is provided or not	.Where(r=>SiteId == null || r.SiteId == SiteId)	0
3397893	3397862	How to get the sum of list of shorts using the extension method Sum()?	int s = listofshorts.Sum(d => d);	0
13542488	13542005	Create shortcut with Unicode character	string destPath = @"c:\temp";\n    string shortcutName = @"??????.lnk";\n\n    // Create empty .lnk file\n    string path = System.IO.Path.Combine(destPath, shortcutName);\n    System.IO.File.WriteAllBytes(path, new byte[0]);\n    // Create a ShellLinkObject that references the .lnk file\n    Shell32.Shell shl = new Shell32.ShellClass();\n    Shell32.Folder dir = shl.NameSpace(destPath);\n    Shell32.FolderItem itm = dir.Items().Item(shortcutName);\n    Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;\n    // Set the .lnk file properties\n    lnk.Path = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";\n    lnk.Description = "nobugz was here";\n    lnk.Arguments = "sample.txt";\n    lnk.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n    lnk.Save(path);	0
4574327	4574301	accessing picture box on childform, c#	public Image Image\n{\n    get { return pictureBox1.Image; }\n    set { \n        if (pictureBox1.Image != null) pictureBox1.Image.Dispose();\n        pictureBox1.Image = value; \n    }\n}	0
8711020	8710936	How to union two data tables and order the result	var dt1 = new DataTable(); // Replace with Dt1\nvar dt2 = new DataTable(); // Replace with Dt2\n\nvar result = dt1.AsEnumerable()\n            .Union(dt2.AsEnumerable())\n            .OrderBy (d => d.Field<string>("emp_name"));	0
12581824	12581314	How to join multiple tables into one	var mergeTable = dt1.AsEnumerable()\n     .Concat(dt2.AsEnumerable())\n     .Concat(dt3.AsEnumerable())\n     .GroupBy(row => new { \n                        Test1 = row.Field<string>("Test1")\n                        Test2 = row.Field<string>("Test2") \n                        Test3 = row.Field<string>("Test3") \n                        })\n\n     .Select(g => g.First())\n     .CopyToDataTable();	0
18399434	18398996	Reading XML in C# having multiple similar nodes	XmlNode xnode = xd.SelectNodes("/Table/row/queryId[normalize-space(.)='" + id.Trim() + "']").[0];	0
7960604	7479306	Using OutlineTextControl	Pen pop = new Pen(Stroker, StrokeThickness);\npop.LineJoin = PenLineJoin.Round;\npop.MiterLimit = 10;	0
20935866	20586465	How to realize drag and drop pin like in windows 8 maps application	private void PinPointerPressed(object sender, PointerRoutedEventArgs e)\n    {\n        if (BottomAppBar != null) BottomAppBar.IsOpen = false;\n        MapView.CapturePointer(e.Pointer);\n        ...\n    }	0
34253412	34253294	Is it possible to convert a 2-d array to list of objects	var pages = Enumerable.Range(0, array.GetLength(0))\n  .Select(i => { var page = new Page();\n  page.ShowsToPages.AddRange(Enumerable.Range(0, array.GetLength(1))\n  .Where(j => array(i, j) != 0)); return page; }).ToList();	0
9693249	9693223	C# using indexers with templates	Texture2D texture = contentHandler.GetValue<Texture2D>("picture");	0
11787466	11787418	A correct way to create an Id-generation base class for EF entities	public class ChildEntity : IdableEntity\n{\n    // ...\n}	0
28250364	28250249	How to change ad maxCPC in Google AdWords campaign through API	// Get the CampaignService.\nAdGroupAdService adService = (AdGroupAdService)user\n       .GetService(Google.Api.Ads.AdWords\n       .Lib.AdWordsService.v201406.AdGroupAdService);\nList<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();\nAdGroupAd targetAd = new AdGroupAd\n{\n    adGroupId = ad.GroupId,\n    ad = new Ad { id = ad.Id },\n    tatus = ad.IsActive ? AdGroupAdStatus.ENABLED: AdGroupAdStatus.PAUSED\n};\nAdGroupAdOperation co = new AdGroupAdOperation\n{\n    @operator = Operator.SET,\n    operand = targetAd\n};\noperations.Add(ad);\nadService.mutate(operations.ToArray());	0
11862332	11844571	How can I find my service name during startup of a service exe	protected override void OnBeforeInstall(System.Collections.IDictionary savedState) {\n    if (HasCommandParameter("settings")) {\n        // NB: Framework will surround this value with quotes when storing in registry\n        Context.Parameters["assemblypath"] += "\" \"settings=" + CommandParameter("settings");\n    }\n    base.OnBeforeInstall(savedState);\n}\n\nprotected override void OnBeforeUninstall(System.Collections.IDictionary savedState) {\n    if (HasCommandParameter("settings")) {\n        // NB: Framework will surround this value with quotes when storing in registry\n        Context.Parameters["assemblypath"] += "\" \"settings=" + CommandParameter("settings");\n    }\n    base.OnBeforeUninstall(savedState);\n}	0
23796931	23796849	How to update an xml file in project folder	public static void AddData(string message)\n{\n    string file = Properties.Settings.Default.XMLFileFullName;\n\n    var doc = XDocument.Load(file);\n\n    doc.Root.Add(\n        new XElement("Request",\n        new XElement("ID", message.Substring(0, 3)),\n        new XElement("Message", message))\n    );\n\n    doc.Save(file);\n}	0
23443155	23440923	How to find the coordinate points of polygon?	List<Point> points = new List<Point>();\n    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)\n    {\n       if (e.Button == MouseButtons.Left)\n   {\n      points.Add(e.Location);\n\n      pictureBox1.Invalidate();\n       dataGridView1.DataSource = null;\n        dataGridView1.DataSource = points;\n          UpdateTextbox();\n    }\n    }\n\n       private void pictureBox1_Paint(object sender, PaintEventArgs e)\n   {\n       if (points.Count > 1)\n        e.Graphics.DrawPolygon(Pens.DarkBlue, points.ToArray());\n\n       foreach (Point p in points)\n      {\n        e.Graphics.FillEllipse(Brushes.Red,\n        new Rectangle(p.X - 2, p.Y - 2, 4, 4));\n      }\n      }\n\n\n        void UpdateTextbox()\n           {\n        textBox1.Text = "";\n        foreach (Point p in points)\n        {\n            textBox1.Text += (p) + "\n".ToString();\n        }\n    }	0
10957804	10957715	open excel workbook from memorystream	var doc = SpreadSheetDocument.Open(ms, isEditable);	0
6578275	6578254	To get specific part of a string in c#	string b = a.Split(',')[0];	0
19078302	19078072	Best way to protect against SQL injection in SqlDataAdapter	da_services = new SqlDataAdapter("SELECT * from table WHERE column=@column AND column2=@column2", conn);\nda_services.SelectCommand.Parameters.AddWithValue("@column", textBox1.Text);\nda_services.SelectCommand.Parameters.AddWithValue("@column2", somestring);	0
7061622	7061481	How to access the uniqueID property from an HtmlElement?	mshtml.IHTMLUniqueName id = element.DomElement as mshtml.IHTMLUniqueName;\nMessageBox.Show(id.uniqueID);	0
25654625	25654024	How to find credentials on which a Diagnostic.Process is running	public void GetProcessOwner(int processId)\n{\n    string query = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;\n    using (var searcher = new ManagementObjectSearcher("root\\CIMV2", query))\n    {\n        foreach (var queryObj in searcher.Get().OfType<ManagementObject>())\n        {\n            ManagementBaseObject outParams = queryObj.InvokeMethod("GetOwner", null, null);\n            Console.WriteLine("{0} is owned by {1}\\{2}", queryObj["Name"], outParams["Domain"], outParams["User"]);\n        }\n    }\n }	0
6047205	6045094	Deleting From DGV -- Index [x] does not have a value	Grid.ClearSelection(); \nGrid.Refresh();	0
13752700	13752347	Open XML (Microsoft Word): C# Table Justification	Table t = new Table(\n    new TableProperties(\n        ...\n        new TableJustification() { Val =  TableRowAlignmentValues.Center},\n        ...),\n    new TableRow(...),\n);	0
15791056	15790918	Silverlight: binding to the result of a calculation that involes a property	rent.PropertyChanged += (sender, args) => {\n  if (args.PropertyName == "Value")\n    renterInsurance.Value = ((Expense)sender).Value * 0.1;\n};	0
27560175	27559502	Change the working directory for a specific static bound assembly	var currentDir = Environment.CurrentDirectory;\nEnvironment.CurrentDirectory = @"c:\ABC";\ntry\n{\n    // call that external assembly\n}\nfinally\n{\n    Environment.CurrentDirectory = currentDir;\n}	0
11691422	11690869	Split big classes into smaller ones	public class MyTreeView : TreeView\n{\n    public bool GroupContainsSnippet(string group, string snippetName)\n    {\n        return Nodes[group] != null && Nodes[group].Nodes.ContainsKey(snippetName);\n    }    \n}	0
7178454	7178338	Windows Forms Updating Controls from other threads	private delegate void updateUIDelegate();\n\npublic void updateUI()\n{\n    if (lblAirTrack.InvokeRequired)\n    {\n        lblAirTrack.Invoke(new updateUIDelegate(updateUI));\n    }\n    else\n    {\n        lblAirTrack.Text = "Tracking: " + itemList.Count + " items";\n    }\n}	0
27303545	27303406	Using reflection to order properties is slow	var ordFunc = new Func<System.Reflection.PropertyInfo, int>(p => ((OrderAttribute) p.GetCustomAttributes(typeof (OrderAttribute), false)[0]).Order);\n\nif(!objects.Any())\n    return;\n\nvar properties = objects.First().GetType().GetProperties()\n    .OrderBy(ordFunc)\n    .ToArray();\n\nforeach (var obj in objects)\n{\n    fileWriter.WriteLine(String.Join(",", properties.Select(x => x.GetValue(obj).ToString())));\n}	0
21416220	21416138	conversion issue from a Label to int for an ID key	HiddenField myCarId = (HiddenField)item.FindControl("carId");\niCarId = Convert.ToInt32(myCarId.Value);\nSession["carId"] = iCarId;	0
17852245	17852043	Unable to get the updated text of text box	if (!IsPostBack)\n{\n    txtFName.Text = dt.Rows[0][1].ToString();\n}	0
10865022	10865006	How to save a Chart control picture to a file?	Chart.SaveImage()	0
15094382	15094285	Select specific fields from Linq query and populate a DataTable	foreach(var row in query2)\n{\n    var newRow = dt.NewRow();\n    newRow["id"]= row.id;\n    newRow["name"]= row.name;\n    dt.Rows.Add(newRow);\n}	0
22342587	22342559	unable to add data to instance of model object	PersonFullResponse pfr = new PersonFullResponse {educations = new List<EducationsResponse>()};	0
22470414	22470195	Prevent Orientation change in Xamarin Android Application	[Activity (Label = "YourActivityname", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]	0
10827149	10826558	How to get the metadata of a file in SharePoint	file.Item.Name;	0
6028820	6028747	Determine whether a row is selected in a DataGridView	var rows = DGV.Rows;\nfor (int i = 0; i < rows.Count - 2; i++)\n{\n    if (rows[i].Selected)\n    {\n        // do something\n    }\n}	0
4255600	4255388	how can invoke install Applications by c# code?	System.Diagnostics.Process.Start("exe file location");	0
33874427	33871369	Efficiently select rows from 2 datatables matching sum for a column	def knapsack(items) {\n  sums = {0: null}\n  for item in items:\n     for sum, last_item in sum:\n       // Skip if you've already used item or the you can get the sum some other way.\n       if last_item == item or sum + item.value in sums: continue\n       else:\n         sums[sum+item.value] = item          \n  return sums\n\npayable_sums = knapsack(payables)\nreceivable_sums = knapsack(receivables)\nfor sum, item in payable_sums:\n   if sum in receivable_sums:\n      print "Success, you can get ", sum, " on both sides."	0
30673512	30669508	WPF Copy image of control to bitmap	tempWidth = myControl.ActualWidth;\n        tempHeight = myControl.ActualHeight;\n\n        myControl.Width = double.NaN;\n        myControl.Height = double.NaN;\n\n        myControl.UpdateLayout();\n\n        RenderTargetBitmap rtb = new RenderTargetBitmap((int)myControl.ActualWidth, (int)myControl.ActualHeight, 96, 96, PixelFormats.Pbgra32);\n\n        rtb.Render(myControl);\n\n        PngBitmapEncoder pbe = new PngBitmapEncoder();\n        pbe.Frames.Add(BitmapFrame.Create(rtb));\n        MemoryStream stream = new MemoryStream();\n        pbe.Save(stream);\n        image = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(stream);\n\n        CEGrid.Width = tempWidth;\n        CEGrid.Height = tempHeight;	0
10335009	10334976	how many time zones are there?	TimeZoneInfo.GetSystemTimeZones	0
21562198	21114891	Save changes to JSON with SimpleJSON	SimpleJSON.JSONNode node = SimpleJSON.JSONNode.Parse(Resources.Load<TextAsset>\n    ("JSON/Test/test").text);\n\n    node["volume"].AsFloat = 0.5f;\n\n    File.WriteAllText(Environment.CurrentDirectory + "/Assets/Resources/JSON/Test/" + @"\audio.json", node.ToString());	0
2248518	2248506	Is there a way to add an Extension Method to a Lambda?	HelperType.Loop(count, 500, () =>\n{\n   // Code here\n});	0
1000494	1000345	How do I access the children of an ItemsControl?	for(int i = 0; i < itemsControl.Items.Count; i++)\n{\n    UIElement uiElement =\n        (UIElement)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);\n}	0
2633931	2633745	Linq to Xml to Datagridview	var query = from c in db.Descendants("Customer")\n                            select new\n                            {\n                                CustomerNumber = Convert.ToInt32((string)c.Element("CustomerNumber").Value),\n                                Name = (string)c.Element("Name").Value,\n                                Address = (string)c.Element("Address").Value,\n                                Postcode = (string)c.Element("PostCode1").Value + " " + c.Element("PostCode2").Value\n                            };\n                dgvEditCusts.DataSource = query.ToList();	0
33396091	33389896	c# wcf hosted in windows service goes idle after 5 minutes	class Program\n{\n    static void Main(string[] args)\n    {\n        using (var host = new ServiceHost(typeof(Service1)))\n        {\n            ThreadPool.QueueUserWorkItem(\n                new WaitCallback(delegate\n            {\n                while (true)\n                {\n                    Thread.Sleep(TimeSpan.FromSeconds(100));\n                    QueueDummyIOCPWork();\n                }\n            }));\n\n            host.Open();\n            Console.WriteLine("Service running...");\n            Console.ReadKey(false);\n        }\n    }\n\n    private static unsafe void QueueDummyIOCPWork()\n    {\n        Overlapped ovl = new Overlapped();\n        NativeOverlapped* pOvl = null;\n        pOvl = ovl.Pack((a, b, c) => { Overlapped.Unpack(pOvl); Overlapped.Free(pOvl); }, null);\n        ThreadPool.UnsafeQueueNativeOverlapped(pOvl);\n    }\n}	0
24980563	24955257	How to get invoked service method in AfterReceiveRequest	string methodName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;\nMethodInfo info = instanceContext.GetServiceInstance().GetType().GetMethod(methodName);	0
25194965	25194018	Creating a MouseEnter Event for every Button in a window	public static void EnumVisuals(Visual argVisual, Button toModifyButton)\n    {\n        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(argVisual); i++)\n        {\n            Visual childVisual = (Visual) VisualTreeHelper.GetChild(argVisual, i);\n            if (childVisual is Button)\n            {\n                var button = childVisual as Button;\n                button.MouseEnter += (sender, eventArgs) =>\n                {\n                    toModifyButton.Content = "Get the Help text from database if you want";\n                };\n            }\n\n\n            EnumVisuals(childVisual, toModifyButton);\n        }\n    }	0
4433942	4433754	Compare 2 Dictionaries with Inner List into a Diff Dictionary?	var sourceFiles = Directory.GetFiles(source, "*", SearchOption.AllDirectories).Select(o => o.Replace(source, ""));\nvar targetFiles = Directory.GetFiles(target, "*", SearchOption.AllDirectories).Select(o => o.Replace(target, ""));\n\nvar sourceFilesNotInTarget = sourceFiles.Except(targetFiles);\nvar targetFilesNotInSource = targetFiles.Except(sourceFiles);\n\nvar changedFiles = sourceFiles.Join(targetFiles, a => CheckSum(a, source), b => CheckSum(b, target), (a, b) => a);	0
20978233	20978182	Merging two generic lists	from x in dbc1.Concat(dbc2)\ngroup x by x.Name into g\nselect new DBClass(g.Key, g.Sum(x => x.Score))	0
10879193	10879062	enum refuses to convert to String	enum foo {A = 1,B = 2,C = 3};\n    var b = (foo)7;	0
4005557	4005529	How do I convert XML to string and get the element value?	using System;\nusing System.Xml;\n\nclass Test {\n    static void Main ()\n    {\n        string s = "<Example> <Option1>x</Option1> <Option2>y</Option2> <Option3>z</Option3></Example>";\n        XmlDocument doc = new XmlDocument (); \n        doc.LoadXml (s);\n        XmlNode n = doc.SelectSingleNode ("Example/Option1");\n        Console.WriteLine (n.InnerText);\n    }\n}	0
8781049	8778624	Trying to use Google Speech2Text in C#	Request.ContentType = "audio/x-flac; rate=8000";	0
17110165	17110111	Custom objectset extension methods	public static class YourExtensions\n{\n    public static void MyMethod<T>(this DbSet<T> table)\n       where T: class // this constraint is required because DbSet<T> have it\n    {\n        // code here\n    }\n}	0
13085143	13085034	Retrieve data from variable results view	var Result= from x in htmlDoc.DocumentNode.Descendants()\n                   where x.Name == "p" && x.Attributes.Contains("class")\n                   where x.Attributes["class"].Value == "cut"\n\nforeach(var Item in Result){\n//Access Item here.\n}	0
30081052	30080796	Construct a new Dictionary based on value criteria	int i = 4;\nDictionary<int, List<string>> res = new Dictionary<int, List<string>>();\nforeach (var item in dict)\n{\n    int takeItems = i - res.Values.SelectMany(r => r).Count();\n    if (takeItems > 0)\n    {\n        res.Add(item.Key, item.Value.Take(takeItems).ToList());\n    }\n    else\n    {\n        break;\n    } \n}	0
2373035	2372938	How to Moq Setting an Indexed property	[Test]\npublic void MoqUsingSetup()\n{\n    //arrange\n    var index = new Mock();\n    index.SetupSet(o => o["Key"] = "Value").Verifiable();\n    // act\n    index.Object["Key"] = "Value";\n    //assert\n    index.Verify();\n}	0
5785432	5785396	Using SqlCommand with SP and without SP Parameteres but just Values in C#	SqlCommand.DeriveParameters()	0
9691440	9690143	getting active window name based on mouse clicks in c#	StringBuilder windowtitle = new StringBuilder(256);\nif (GetWindowText(hwnd, windowtitle, windowtitle.Capacity) > 0)\n    Console.WriteLine(windowtitle);	0
20993840	20989691	How to Export data from Listview and Save in DataBase	for (int i = 0; i < lvProductInfo.Items.Count; i++)\n    {\n        ProductCode = Convert.ToInt32(lvProductInfo.Items[i].SubItems[1].Text);\n        ProductQuantity = Convert.ToInt32(lvProductInfo.Items[i].SubItems[2].Text);\n        ProductPrice = Convert.ToInt32(lvProductInfo.Items[i].SubItems[3].Text);\n        totalPrice = Convert.ToInt32(lvProductInfo.Items[i].SubItems[4].Text);\n\n\n        sql = "";\n        sql = "INSERT INTO PurchaseLog (ProductCode,ProductQuantity,ProductPrice,TotalPrice)"\n            + " VALUES ('" + ProductCode + "','" + ProductQuantity + "','" + ProductPrice + "','" + totalPrice + "')";\n\n        clsConnection clsCn = new clsConnection();\n        SqlConnection cn = null;\n        SqlCommand cmd = new SqlCommand();\n\n        clsCn.fnc_ConnectToDB(ref cn);\n\n        cmd.Connection = cn;\n        cmd.CommandText = sql;\n        cmd.ExecuteNonQuery();\n\n\n        this.Close();\n    }\n\n}	0
25753468	25753068	splitting the string based on multiple spaces	reader.SetFieldWidths(5, 21, 7, -1)	0
6934493	6934427	Singleton Pattern / Check for Null - While using Asp.Net with Session	public Teacher GetClassTeacher()\n   {\n       var teacher = Session["Teacher"] as Teacher\n       if (teacher == null)\n       {\n            //Get Teacher Info from Database\n       }   \n   }	0
24454622	24440348	Windows Service in C# not starting up in a timely manner	ServiceBase.Run(new SystemMonitorD());	0
7852880	7832973	Entlib5 string validation	private string _address = string.Empty; // IMPORTANT!\n\n[StringLengthValidator(30, "Max. 30 chars")]\npublic string Address {\n    get { return _address; }\n    set { _address = value; }\n}	0
4903214	4903166	Splitting a string on a space and removing empty entries	string[] elements = templine.Split(space).Where((s, i) => i != 1).ToArray();	0
14167389	14167349	How to Instantiate an object in particular location if it has Position animation?	[Empty Parent Node]  (created dynamically)\n |- [Ball]           (created from your prefab)	0
11949973	11949951	working with console writeline c#	Console.WriteLine("Result {0}", d);	0
16809913	16809751	Go to first page in C# WPF	Navigation.GoBack()	0
10355483	10355467	Get all DLLImports from an Assembly?	GetCustomAttributes(typeof(DllImportAttribute))	0
28279299	28278763	How to update my database generated by "code first from database"?	code first from database	0
24209236	24208935	Can ninject be used to configure class based inject (instead of interface)?	kernel.Bind<List<string>>().ToConstant(new List<string>(){"Foo", "Bar"});	0
716266	716247	LINQ: Remove items from IQueryable	obj.RemoveAll(act => isDomainBlackListed(ref dc, act.Referrer));	0
5771598	5771577	Can you have a property name containing a dash	var document = new {\n    conditions = new Dictionary<string, string>() {\n        { "acl", "public-read" },\n        { "bucket", "s3-bucketname" },\n        { "starts-with", "test/path" }\n    }\n};	0
8411053	8411018	SQL Server 2008 DATE type showes me DATE & TIME in visual studio	ContractStartDate_txt.Text = Convert.ToDateTime(reader["ContractStartDate"]).ToString("dd/MM/yyyy");\nMandateValidDate_txt.Text = Convert.ToDateTime(reader["MandateValidDate"]).ToString("dd/MM/yyyy");	0
18838648	18838299	Add full row to DataTable MVC4	var cells = new object[count];\nfor (int i = 0; i < count; i++)\n{                        \n  cells[i] = rdr.GetString(i).Trim() + "\"\n}\ntheTable.Rows.Add(cells)	0
15008954	15003620	Add subview programmatically and make it stretching so if it is was added through XCode	var childView = new UIView(parentView.Bounds) \n{ \n    AutoresizingMask = UIViewAutoresizing.FlexibleDimensions\n};\nparentView.Add(childView);	0
17649320	10915122	Numeric keypad on MonoTouch	private UIView _toolbar;\n    public override UIView InputAccessoryView\n    {\n        get\n        {\n           return _toolbar;\n        }\n    }	0
30557832	30557763	Storing data in an array that is accessed by separate void c#	string[,] info = new string[2, 2];	0
19792100	19730781	How to add linux invisible character in C# for Hive usage?	string delim = "\x01";	0
18993776	18993735	How to read single Excel cell value	var cellValue = (string)(excelWorksheet.Cells[10, 2] as Excel.Range).Value;	0
1265030	1237937	FxCop taking issue with my use of format strings in resources with NON-Team System Visual Studio	[assembly: NeutralResourcesLanguage("")]	0
26181413	26181308	InvalidOperationException with ToolStripDropDown	main.favouritesToolStripMenuItem.DropDownItems.Remove(\n    items.Items.OfType<ToolStripMenuItem>().FirstOrDefault(\n          item => item.Text == listBox1.SelectedItem.ToString()));	0
20481922	20481741	c# Reading XML comment using XDocument	XDocument xdoc = XDocument.Load("");\n       foreach (var node in xdoc.Descendants("servers").Nodes())\n        {\n\n            if (node is XComment)\n            {\n                //THEN  READ YOUR COMMENT \n\n            }\n\n        }	0
5833664	5833569	Showing Javascript from CodeBehind Page NOT Working!	public static void JS_Alert(string message)\n    {\n        // Cleans the message to allow single quotation marks\n        string cleanMessage = message.Replace("'", "\\'");\n        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";\n\n        // Gets the executing web page\n        Page page = HttpContext.Current.CurrentHandler as Page;\n\n        // Checks if the handler is a Page and that the script isn't allready on the Page\n        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))\n        {\n            page.ClientScript.RegisterClientScriptBlock(typeof(Utilities), "alert", script);\n        }\n    }	0
30448170	30448092	How to format numeric string?	string.Format("{0:n0} POINT", 100000)	0
27766702	27763539	goDaddy SMTP-Unable to read data from the transport connection: net_io_connectionclosed	client.Timeout = 10000;//was 1000 initialy	0
15010165	15009976	Convert String to Decimal - leave digits	public bool TryGetPreisAsDecimal(string price, out decimal convertedPrice)\n    { \n        Match match = Regex.Match(price,@"\d+(\.\d{1,2})?");\n\n        if (match != null)\n        {\n            convertedPrice = decimal.Parse(match.Value);\n            return true;\n        }\n        else\n        {\n            convertedPrice = 0.0m;\n            return false;\n        }\n    }	0
14362021	14314594	Get the control of AppDomain.CurrentDomain object in application	Assembly.GetEntryAssembly().GetName().Name	0
14653673	14653627	How to set user agent in GeckoFX?	public Form1()\n{\n    InitializeComponent();\n    Gecko.Xpcom.Initialize("c:\\tools\\xulrunner");\n    myBrowser = new GeckoWebBrowser();\n    myBrowser.Parent = this;\n    myBrowser.Dock = DockStyle.Fill;\n\n    string sUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)";\n     Gecko.GeckoPreferences.User["general.useragent.override"] = sUserAgent;\n}	0
5656235	5656210	How to get the relative filename to a specific directory?	var relative = new Uri(rootPath).MakeRelativeUri(new Uri(filePath));	0
29843082	29842913	Sorting an ObservableCollection<BusinessObject> using a custom sort order	var view = CollectionViewSource.GetDefaultView(businessObjects);\nview.SortDescriptions.Add( SortDescription("NameOfPropertyToSortBy",ListSortDirection.Ascending ));	0
33835226	33834796	how to make a textbox accept only date of birth format c#	private void Form1_Load(object sender, EventArgs e)\n{\n    InitializeComponent();\n    maskedTextBox1.Mask = "00/00/0000";\n}	0
2627743	2627736	How to retrieve the integer value of an enum?	Console.Writeline((int)color.Value);	0
11613142	11612524	Comparing two values Var to obtain a masked list	var masked = storedInvestments.Where(i => i.attachedCards.Any(c => !selected.Contains(i)));	0
2549281	2549240	How to generate scripts using SQL management studio for C# Usage	string script = File.ReadAllText("script.sql");\nMicrosoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server();\nserver.ConnectionContext.LoginSecure = false;\nserver.ConnectionContext.Login = "user";\nserver.ConnectionContext.Password = "pass";\nserver.ConnectionContext.ServerInstance = "instance";\nserver.Databases["master"].ExecuteNonQuery(script);	0
31240143	31232000	How to retrieve IFileOpenDialog interface in C# from IUnknown_QueryService SID_SExplorerBrowserFrame?	[DllImport("shlwapi.dll")]\ninternal static extern int IUnknown_QueryService(IntPtr pUnk, ref Guid guidService, ref Guid riid, out IntPtr ppvOut);\n\n\nGuid g = new Guid("000214F1-0000-0000-C000-000000000046"); // SID_SExplorerBrowserFrame\nGuid g2 = new Guid("d57c7288-d4ad-4768-be02-9d969532d960"); // IFileOpenDialog\n\nIntPtr pp;\nint rrc =  Win32.IUnknown_QueryService(pUnkSite, ref g, ref g2, out pp);\n\nFileDialogNative.IFileOpenDialog dlg = Marshal.GetObjectForIUnknown(pp) as FileDialogNative.IFileOpenDialog;\nMarshal.Release(pp);	0
8239963	8193758	How do I get Media Player to *play* using C#?	SendMessage(WMP.MainWindowHandle, 0xC02B, 0x0000000C, 0x000E0000);	0
15588237	15587836	Load From byte array , Resize And Load To Stream Dosent show image in browser	Image returnImage;\n\nusing (var ms = new MemoryStream(PictureFile))\n{\n    returnImage = Image.FromStream(ms);\n}\n// leaving the using block closes ms\n\nvar img = returnImage.Resize(size);\n\n// create new MemoryStream to save the resized image\nvar resultStream = new MemoryStream();\nimg.Save(resultStream, format);\n\n// rewind the stream\nresultStream.Seek(0, SeekOrigin.Begin);\n\nreturn resultStream;	0
15638797	15638531	Switch application in c# like task manager	[DllImport("user32.dll")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nvoid SwitchDatabase(string mainWindowTitle)\n{\n        try\n        {\n            bool launched = false;\n\n            Process[] processList = Process.GetProcesses();\n\n            foreach (Process theProcess in processList)\n            {\n                ShowWindow(theProcess.MainWindowHandle, 2);\n            }\n\n            foreach (Process theProcess in processList)\n            {\n                if (theProcess.MainWindowTitle.ToUpper().Contains(mainWindowTitle.ToUpper()))\n                {\n                    ShowWindow(theProcess.MainWindowHandle, 9);\n                    launched = true;\n                }\n            }\n        }\n        catch (Exception ex)\n        {\n            ThrowStandardException(ex);\n        }\n}	0
11518581	11518513	How to get values of queried table in hibernate?	var integerids = scope.Session.QueryOver<Person>()\n    .Select(p => p.Id)\n    .List<int>();	0
3925313	3925276	how can i split a string C#	var field1 = myString.Substring(0,8);\nvar field2 = myString.Substring(8,4);	0
14935642	14935562	Updating multi-dimension byte array in C#	int stride = single0.Length; // Or multi.GetLength(1)\nBuffer.BlockCopy(single0, 0, multi, stride * 0, stride);\nBuffer.BlockCopy(single1, 0, multi, stride * 1, stride);\nBuffer.BlockCopy(single2, 0, multi, stride * 2, stride);\nBuffer.BlockCopy(single3, 0, multi, stride * 3, stride);\nBuffer.BlockCopy(single4, 0, multi, stride * 4, stride);	0
30586896	30586782	ASP.NET how to return a string instead of returning the page?	string rtnString = "yourStringHere";\nResponse.Write(rtnString);\nResponse.End();	0
25651614	25651549	How to transform this "Select" into a Lambda Expression	var subQuery = db.OIDPhone.Where(r=> r.City == "New York").Select(r=> r.OIDPhone);\nvar finalQuery = db.Table1.Where(r=> subQuery.Contains(r.OID));	0
6296775	6283409	Keeping a custom cursor on a WPF popup	popBorder.Cursor = _relativeTo.Cursor;	0
6728721	6728599	UTC Timestamp in milliseconds to short datetime string in c#	DateTime UnixStartDate = new DateTime(1970, 1, 1);\nYourDate = UnixStartDate.AddMilliseconds(YourTimestamp).ToShortDateString();	0
6412300	6412214	How to synchronize a TextBox with a ListBox in WPF using IsSynchronizedWithCurrentItem	Text = "{Binding ElementName=listBox1, Path=SelectedValue.Content}"	0
10469338	10469311	Access properties of a type created by reflection	// TODO: Checking that you managed to get the property, that's it's writable etc.\nvar property = type.GetProperty("PropertyName");\nproperty.SetValue(newMember, "new value", null);	0
16455780	16455744	C#, Cycle through TextBlock on button press, So close	public class Foo\n{\n    private int index = 0;\n\n    private string[] arr = new [] { "Hello and Welcome",\n                                    "To the new app",\n                                    "enjoy your stay",\n                                    "press next to continue" };     \n\n    private void ButtonCallback(...)\n    { \n         tbArray.Text = arr[index++]; \n    }\n}	0
31353858	31353734	C# - Network Programming - Verify client before allowing connection	Sock1.Accept()\n\nIf data then\n    Store the received data in "X"\n    If Password match "X" then continue, if not: KickClient()\nEnd If	0
2621645	2621090	Is this a correct way to host a WCF service?	if (_Host.State == CommunicationState.Faulted)\n{\n    _Host.Abort();\n}\nelse\n{\n    _Host.Close();\n}	0
17249455	17107354	issue with child application paths	unfortunately i have to "rewrite" all our links in my code. \n so  i created a function which will automatically add prefix to external links,\n and store base link for other site it configuration. \n I did such project with success.  thank u for all your replies	0
17681202	17680941	Using SmtpClient to send a file attachment	System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();\ncontentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;\ncontentType.Name = "test.docx";\nmsg.Attachments.Add(new Attachment("I:/files/test.docx"), contentType);\n...	0
6164421	6164241	Read a XML tree structure recursively in a List<T> with children lists<T>	public class Unit\n{\n    public string Name { get; set; }\n    public List<Unit> Children { get; set; }\n}\n\nclass Program\n{\n    public static void Main()\n    {\n        XDocument doc = XDocument.Load("test.xml");\n        List<Unit> units = LoadUnits(doc.Descendants("Units").Elements("Unit"));\n    }\n\n    public static List<Unit> LoadUnits(IEnumerable<XElement> units)\n    {\n        return units.Select( x=> new Unit() \n                                 { Name = x.Attribute("Name").Value, \n                                   Children = LoadUnits(x.Elements("Unit")) \n                                 }).ToList();\n    }\n}	0
3930474	3929825	Entity Framework 4 , Extending context of one edmx file to a context of another edmx file	using PersonRepository;\nusing CvRepository;\n\npublic class CvPersonService\n{\n   public CvPerson GetHydratedCvPersonFromTwoRepositories()\n   {\n        var person = personRepository.Find(1); // get a person\n        var cv = cvRepository.Find(1); // get a cv\n\n        return new CvPerson { ThePerson = person, TheCv = cv };\n   }\n}	0
2717396	2717264	Fluent NHibernate Repository with subclasses	Person p = dao.FindById<Person>(23);\nif(p is Teacher)\n{\n   Teacher t = (Teacher)p;\n}\nelse if(p is Student)\n{\n   Studet s =(Student)p;\n}	0
3520413	3520344	When will a property get call create a local copy of a reference type? How to avoid that?	(MySubClass)myInstance\n\nmyInstance as MySubClass	0
4762074	4762050	How to show menu in borderless form in c#?	Form.BorderStyle = None	0
33070645	33070542	C# XDocument - Adding a Value to an existing xml	private void dir_TextBox_TextChanged(object sender, EventArgs e)\n{\n        XDocument _config = XDocument.Load(@"/ProgramData\app\appConfig.xml");\n        _config.Root.Element("node1").Element("value").Value = "a string";          \n        _config.Save(@"/ProgramData\app\appConfig.xml");\n}	0
6582686	6582603	AsyncCallback getting values through reference variable	class User\n{\n    public int Id { get; set; }\n\n    public string Name { get; set; }\n}\n\nvoid GetName(IAsyncResult result)\n{\n    var user = (User)result.AsyncState\n    // ...\n}\n\nAsyncCallback callBack = new AsyncCallback(GetName);	0
11701835	11701749	Append a child to a grid, set it's row and column	Image Box = new Image();\nmyGrid.Children.Add(Box);\nGrid.SetRow(Box, 1);\nGrid.SetColumn(Box, 1);	0
31855706	31855408	Finding invalid data row number while reading csv	bool ContainsOnlyNumbers( string input )\n{\n  // beginning of string, one or more digits, end of string\n  return Regex.IsMatch( input, @"^\d+$" );\n}\n\nbool ContainsOnlyLetters( string input )\n{\n  // beginning of string, one or more letters, end of string\n  return Regex.IsMatch( input, @"^[A-Za-z]+$" );\n}	0
15512536	15512449	SqlBulkCopy to stored procedure using Type Table	// Create a DataTable \nDataTable dt = new DataTable(...)\n// Configure the SqlCommand and SqlParameter.\nSqlCommand insertCommand = new SqlCommand(\n    "your TVP store procedure", connection);\ninsertCommand.CommandType = CommandType.StoredProcedure;\nSqlParameter tvpParam = insertCommand.Parameters.AddWithValue(\n    "@tvp", dt);\ntvpParam.SqlDbType = SqlDbType.Structured;	0
21542832	21542796	display value of database	Global.dbCon.Open();\n\nList<int> idQuestions = new List<int>();\n\nkalimatSql = kalimatSql;\n\nGlobal.reader = Global.riyeder(kalimatSql);\n\nif (Global.reader.HasRows) {\n   while (Global.reader.Read()) {\n       int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));\n\n       idQuestions.Add(idQuestion);\n   }\n}\n\nGlobal.dbCon.Close();\n\nforeach (int id in idQuestions)\n{\n    messageBox.Show(id.ToString());\n}	0
4780139	4779695	Equality comparison of the datatype of two strings value in C#	class StringTypeEqualityComparer : IEqualityComparer<string, string>\n{\n    public bool Equals(string x, string y)\n    {\n        int tempInt;\n        if (Int32.TryParse(x, out tempInt) && (Int32.TryParse(y, out tempInt))\n            return true;\n\n        bool tempBool;\n        if (Boolean.TryParse(x, out tempBool) && Boolean.TryParse(y, out tempBool))\n            return true;\n\n        float tempFloat;\n        if (Single.TryParse(x, out tempFloat) && Single.TryParse(y, out tempFloat))\n            return true;\n\n        // And whatever other types you want to compare...\n\n        return false;\n\n        // But what if two regular strings should also evaluate to equal?\n    }\n}	0
13837014	13834722	String[] to image gets failed	public Image byteArrayToImage(byte[] byteArrayIn)\n{\n     MemoryStream ms = new MemoryStream(byteArrayIn);\n     Image returnImage = Image.FromStream(ms);\n     return returnImage;\n}	0
420633	420623	How to Convert date into MM/DD/YY format in C#	DateTime.Today.ToString("MM/dd/yy")	0
30134621	30134376	SelectedIndex of a ComboBox is always -1	private void cb_SelectedIndexChanged(object sender, EventArgs e) {\n    ComboBox c = sender as ComboBox;\n    if(c == null) return;\n\n    string attribute = c.Items[c.SelectedIndex].ToString();\n    MessageBox.Show( " " + attribute);\n}	0
2575582	2575472	Is there a way to reliably detect the total number of CPU cores?	GetLogicalProcessorInformation()	0
6742651	6741164	Foreach loop and variables with locking	public void Enqueue(T item)\n{\n    SpinWait wait = new SpinWait();\n    while (!this.m_tail.TryAppend(item, ref this.m_tail))\n    {\n        wait.SpinOnce();\n    }\n}	0
24386360	24377081	Sending async mail from SignalR hub	public async Task DoSomething() {\n  using (new IgnoreSynchronizationContext())\n  {\n    var client = new SmtpClient();\n    var message = new MailMessage(/* setup message here */);\n    await client.SendMailAsync(message);\n  }\n}\n\npublic sealed class IgnoreSynchronizationContext : IDisposable\n{\n  private readonly SynchronizationContext _original;\n  public IgnoreSynchronizationContext()\n  {\n    _original = SynchronizationContext.Current;\n    SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());\n  }\n  public void Dispose()\n  {\n    SynchronizationContext.SetSynchronizationContext(_original);\n  }\n}	0
27933325	27932988	How to normalize a float collection such that the sum of all elements is X	int desiredTotal = 300; \n\nfloat[] widths = new float[] { 35f, 63f, 12f };\n\nfloat ratio = desiredTotal / widths.Sum();\nvar normalizedList = widths.Select(o => o * ratio).ToList();\n\nforeach (var item in normalizedList)\n{\n    Console.WriteLine(item);\n}\n\nConsole.WriteLine(normalizedList.Sum());\n\n/* Which prints:\n95.45454\n171.8182\n32.72727\n300\n*/	0
17833974	17833665	Ordering delegates with various datatypes	public IEnumerable<Album> Get<T>(Func<Album, T> orderingDelegate = null)\n{\n    IEnumerable<Album> albums;\n\n    if (orderingDelegate == null)\n        albums = _context.Albums.OrderBy(a => a.Title);\n    else\n        albums = _context.Albums.OrderBy(orderingDelegate);\n\n    return albums;\n}	0
28411528	28411124	URL gets truncated when inserted into mysql database	varchar(30)	0
7713812	7713364	Repository that accesses multiple tables	public CategoryService(CategoryRepository  categoryRepository, ProductRepository productRepository) \n{\n    _categoryRepository = categoryRepository;\n    _productRepository = productRepository;\n}	0
7766551	7765887	Would like to know SQL Azure available space from ASP.Net web application	select\n  sum(reserved_page_count) * 8.0 / 1024\nfrom\n  sys.dm_db_partition_stats\nGO\n\nselect\n  sys.objects.name, sum(reserved_page_count) * 8.0 / 1024\nfrom\n  sys.dm_db_partition_stats, sys.objects\nwhere\n  sys.dm_db_partition_stats.object_id = sys.objects.object_id\ngroup by sys.objects.name	0
13577967	13577958	formula for finding a square of a number	for (int counter = 1; counter <= 10; counter++)\n    {          \n            Console.WriteLine(counter*counter);\n    }	0
17814083	17810658	Using LINQ to get a string from a tab delimited text file into an array in the way I want	Split('\t')	0
17337251	17337023	filter datagirdview on input of two text box	DataView dv = new DataView(table);\nif (!String.IsNullOrEmpty(textBox1.Text))\n{\n   dv.RowFilter = String.Format("vendor like '%{0}%'", textBox1.Text);\n}\n\ndv.RowFilter = dv.RowFilter == "" ? String.Format("model like '%{0}%'", textBox2.Text) : dv.RowFilter + String.Format("AND model like '%{0}%'", textBox2.Text);\n\npurchase_mobile_DG.DataSource = dv;	0
33959400	33959323	checking if parameter is one of 3 values with fluent validation	List<string> Conditions = new List{str1, str2, str3};\nRuleFor(x => x.Parameter).Must(x => Conditions.Contains(x)).WithMessage("Please only use: " + String.Join(",", Conditions);	0
15787745	15787689	Remove XElement from XDocument Error	string sequenceNumberStr = SequenceNumber.ToString();\n\nXDoc.Descendants("PricedItinerary")\n    .Where(node => (string)node.Attribute("SequenceNumber") != sequenceNumberStr)\n    .Remove();	0
28942742	28942677	How can add a text append text to richTextBox only if the text is different from the one already exist?	if(!richTextBox.Text.Contains(combinedString))\n    {\n       richTextBox1.AppendText(combindedString);\n    }	0
6513661	6513633	Convert Transparent PNG to JPG with Non-Black Background Color	// Assumes myImage is the PNG you are converting\nusing (var b = new Bitmap(myImage.Width, myImage.Height)) {\n    b.SetResolution(myImage.HorizontalResolution, myImage.VerticalResolution);\n\n    using (var g = Graphics.FromImage(b)) {\n        g.Clear(Color.White);\n        g.DrawImageUnscaled(myImage, 0, 0);\n    }\n\n    // Now save b as a JPEG like you normally would\n}	0
1877404	1841790	How can a Windows Service determine its ServiceName?	protected String GetServiceName()\n    {\n        // Calling System.ServiceProcess.ServiceBase::ServiceNamea allways returns\n        // an empty string,\n        // see https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=387024\n\n        // So we have to do some more work to find out our service name, this only works if\n        // the process contains a single service, if there are more than one services hosted\n        // in the process you will have to do something else\n\n        int processId = System.Diagnostics.Process.GetCurrentProcess().Id;\n        String query = "SELECT * FROM Win32_Service where ProcessId = " + processId;\n        System.Management.ManagementObjectSearcher searcher =\n            new System.Management.ManagementObjectSearcher(query);\n\n        foreach (System.Management.ManagementObject queryObj in searcher.Get()) {\n            return queryObj["Name"].ToString();\n        }\n\n        throw new Exception("Can not get the ServiceName");\n    }	0
18733001	18729725	How to parse an HTML color name to a SolidColorBrush in a Windows Store App	using System.Reflection;\n\npublic SolidColorBrush ColorStringToBrush(string name)\n{\n    var property = typeof(Colors).GetRuntimeProperty(name);\n    if (property != null)\n    {\n        return new SolidColorBrush((Color)property.GetValue(null));\n    }\n    else\n    {\n        return null;\n    }\n}	0
9120726	9120614	How to reuse code that reopens connection?	private const int MaxRetryCount = 3;\n\npublic static T RestoreConnectionAndExecute<T>(SqlCommand command, Func<SqlCommand, T> func)\n{\n    int retryCount = 0;\n\n    while (retryCount++ < MaxRetryCount)\n    {\n        try\n        {\n            if (command.Connection.State == ConnectionState.Closed)\n                command.Connection.Open();\n            return func(command);\n        }\n        catch(Exception e)\n        {\n            if(!e.Message.ToLower().Contains("transport-level error has occurred"))\n            {\n                throw;\n            }\n        }\n    }\n    throw new Exception("Failed to restore connection for command:"+command.CommandText);\n\n} \n\npublic static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)\n{\n    return RestoreConnectionAndExecute(command, c => c.ExecuteReader());\n}\n\npublic static int RestoreConnectionAndExecuteNonQuery(SqlCommand command)\n{\n    return RestoreConnectionAndExecute(command, c => c.ExecuteNonQuery());\n}	0
29498452	29495525	Html nodes issue with HtmlAgilityPack	doc.DocumentNode.SelectSingleNode("//h4[contains(text(),'uploaded.net')]/following-sibling::ul//a").Attributes["href"].Value	0
20969891	20968286	Put "ALL" on ComboBox[0] so that we filter it. NOTE: ComboBox has data from DB	_con.Open();\n    SqlCommand _viewLandmarks = new SqlCommand("dbo.SelectDevices_AddingForm", _con);\n    _viewDevices.CommandType = CommandType.StoredProcedure;\n    _viewDevices.ExecuteNonQuery();\n\n    SqlDataAdapter da = new SqlDataAdapter(_viewLandmarks);\n    DataTable dTable = new DataTable("LANDMARK");\n    da.Fill(dTable);\n    DataRow fakeRow = dTable.NewRow();\n    fakeRow["Landmark"] = "(ALL)";\n    fakeRow["LandmarkID"] = -1;\n    dTable.Rows.Add(fakeRow);\n\n    comboModel.DataSource = dTable;\n    comboModel.DisplayMember = "Landmark";\n    comboModel.ValueMember = "LandmarkID";\n\n    _con.Close();	0
26867988	26531437	Is there a way to get the free space on an iSCSI drive mounted as a NTFS folder	// iSCSI drive mounted in a NTFS folder\nvar ntfsPath = @"x:\iscsi\volume";\n\n// it's good to know that backspaces must be escaped in WMI queries\nvar cmd = string.Format(\n    "SELECT * FROM Win32_Volume WHERE Name LIKE '{0}%'", \n    ntfsPath.Replace(@"\", @"\\"));\n\nusing (var searcher = new ManagementObjectSearcher(cmd))\n{\n    foreach (ManagementObject queryObj in searcher.Get())\n    {\n        var name = (string)queryObj["Name"];\n        var freeSpaceInBytes = (ulong)queryObj["FreeSpace"];\n    }\n}	0
10443625	10443587	C# -Do I have to add out parameter to parameters collection	CREATE PROCEDURE MyTest\n   @Data1 int\n   ,@Data3 int = null output	0
25849483	25848748	Using different databases with Entity Framework 6	metadata=res://*/DataModel.csdl|c:\dev\program\bin\debug\DataModel.VistaDB.ssdl|res://*/DataModel.msl;	0
11177729	11177587	How can I display images in mail content?	var msg = new System.Net.Mail.Message();\nmsg.isHTML=true;\nmsg.Body ="<img src=\"cid:IMG1CONTENT\">";\n\n\nAttachment mya = new Attachment("file-path-here");\nmya.ContentId="IMG1CONTENT";\nmsg.Attachments.Add(mya);	0
2828438	2825950	Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird	if (attachmentFilename != null)\n{\n    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);\n    ContentDisposition disposition = attachment.ContentDisposition;\n    disposition.CreationDate = File.GetCreationTime(attachmentFilename);\n    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);\n    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);\n    disposition.FileName = Path.GetFileName(attachmentFilename);\n    disposition.Size = new FileInfo(attachmentFilename).Length;\n    disposition.DispositionType = DispositionTypeNames.Attachment;\n    message.Attachments.Add(attachment);                \n}	0
33361101	33360052	How to extract Guid from file name?	var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt\n\nvar arr = str.Select(s=>s.Substring(36)).Where(s=>s.Any()).ToArray();	0
8009543	8009179	Creating a WCF PUT Rest service	Content-Type: application/json	0
9289330	9289279	ArrayList to ListViewDataItem[]	ListViewDataItem[] elements =  (ListViewDataItem[]) yourArrayList.ToArray(typeof (ListViewDataItem));	0
7283818	7283701	setting textBox.MinWidth to largest required space for current culture, font, etc	TextBox textBox = new TextBox();\nSize size = TextRenderer.MeasureText("A", textBox.Font);\ntextBox.Width = size.Width;	0
23789200	23787126	using a DLL from an external vendor that is not thread safe	public class NotThreadSafeClass\n{\n    public int SomeMethod(string x, int y)\n    {\n        return 3;\n    }\n}\n\npublic class ThreadSafeWrapper\n{\n    private TaskScheduler sta = new StaTaskScheduler(numberOfThreads: 1);\n    private NotThreadSafeClass old = new NotThreadSafeClass();\n    public Task<int> SomeMethod(string x, int y)\n    {\n        return Task<int>.Factory.StartNew(() => old.SomeMethod(x,y),\n             CancellationToken.None, TaskCreationOptions.None, sta);\n    }\n}	0
1375289	1375257	How to use C# encode and decode 'Chinese' characters	byte[] buffer = new byte[] { 0xE8, 0x82, 0xB2, 0xE5, 0x84, 0xBF };\nstring s = Encoding.UTF8.GetString(buffer);	0
11824998	11036855	Is there a way to filter UltraGrids based on the value of 2 columns?	UltraGridColumn fooColumn = Grid.DisplayLayout.Bands[0].Columns["Foo"];\nUltraGridColumn barColumn = Grid.DisplayLayout.Bands[0].Columns["Bar"];\nColumnFilter fooColumnFilter = fooColumn.Band.ColumnFilters[fooColumn];\nfooColumnFilter.ClearFilterConditions();\nfooColumnFilter.FilterConditions.Add(FilterComparisionOperator.NotEquals, barColumn);	0
30153283	30151478	How to use sql defined functions as fields?	create table Ticket(\n  Ticket_Id varchar(10) not null,\n  TicketType_Id varchar(3) not null,\n  Ticket_PurchaseDate DateTime null,\n  LottoDraw_Id int null,\n  [User_Id] int null,\n  Ticket_IsWinner bit null\n  Primary Key(Ticket_Id,TicketType_Id)\n)	0
5476520	5169253	How do I generate One time passwords (OTP / HOTP)?	// Use a bitwise operation to get a representative binary code from the hash\n// Refer section 5.4 at http://tools.ietf.org/html/rfc4226#page-7            \nint offset = hashBytes[19] & 0xf;\nint binaryCode = (hashBytes[offset] & 0x7f) << 24\n    | (hashBytes[offset + 1] & 0xff) << 16\n    | (hashBytes[offset + 2] & 0xff) << 8\n    | (hashBytes[offset + 3] & 0xff);\n\n// Generate the OTP using the binary code. As per RFC 4426 [link above] "Implementations MUST extract a 6-digit code at a minimum \n// and possibly 7 and 8-digit code"\nint otp = binaryCode % (int)Math.Pow(10, 6); // where 6 is the password length\n\nreturn otp.ToString().PadLeft(6, '0');	0
12827678	12827636	Linq to SQL Join IQuerable Set Certain Property	var query = from t1 in Repo.GetThing1()\n            join t2 in Repo.GetThing2() on t1.Key equals t2.Key\n            select new { Existing = t1, NewValue = t2.SomeField };\n\nvar list = query.ToList();\n\nforeach (var pair in list)\n{\n    pair.Existing.SomeField = pair.NewValue;\n}	0
11970387	11958350	Troubleshooting a simple proxy server	//rec = 0;\n                //do\n                //{\n                //    if (client.Poll(3000 * 1000, SelectMode.SelectRead))\n                //    {\n                //        rec = client.Receive(buffer, buffer.Length, SocketFlags.None);\n                //        Debug.Print("RECEIVED FROM CLIENT: " + Encoding.ASCII.GetString(buffer, 0, rec));\n\n                //        sent = webserver.Send(buffer, rec, SocketFlags.None);\n                //        Debug.Print("SENT TO WEBSERVER[" + sent.ToString() + "]: " + Encoding.ASCII.GetString(buffer, 0, rec));\n                //        transferred += rec;\n                //    }\n                //    else\n                //    {\n                //        Debug.Print("No data polled from client");\n                //    }\n                //} while (rec == buffer.Length);\n                //Debug.Print("loop-2 finished");	0
1632656	1632586	How to replace multiple different chars with white space?	string myString = string.Join(" ", input.Split(@"\/:*?<>|".ToCharArray()));	0
23020069	23019566	Display view from different controller in action	return View("~/Views/Read/Details.cshtml", vm);	0
3482843	3482567	How to write a single LINQ to XML query to iterate through all the child elements & all the attributes of the child elements?	var allDescendants = myElement.DescendantsAndSelf();\nvar allDescendantsWithAttributes = allDescendants.SelectMany(elem =>\n    new[] { elem }.Concat(elem.Attributes().Cast<XContainer>()));\n\nforeach (XContainer elementOrAttribute in allDescendantsWithAttributes)\n{\n    // ...\n}	0
31426047	31425041	MySQL and C# Getting data from DB and creating an associative array/object	public Foo FetchSomeData(string query)\n    {\n        using (var cn = Connection)\n        {\n            var result = cn.Query(query);\n           //do something with result, and return it\n           return new Foo(result);\n        }\n    }	0
2335662	2335637	Split a List of structs into sublists based on the stucts contents	somelist.ToLookup(x => x.GroupingString)	0
32570470	32569795	NAudio : Read Wav File As Double Array	var floatSamples = new double[read/2];\nfor(int sampleIndex = 0; sampleIndex < read/2; sampleIndex++) {\n   var intSampleValue = BitConverter.ToInt16(bytesBuffer, sampleIndex*2);\n   floatSamples[sampleIndex] = intSampleValue/32768.0;\n}	0
4238933	4238865	How do I find a control I placed inside a panel?	YourPanelName.FindControl()	0
28746421	28738571	Excel Open xml sdk - Copy formula between cells with range modification	//Formula update\nif (cloneFromCell.CellFormula != null && (cloneFromCell.CellFormula.FormulaType == null || !cloneFromCell.CellFormula.FormulaType.HasValue || cloneFromCell.CellFormula.FormulaType.Value == CellFormulaValues.Normal))\n{\n    uint cloneRowIndex = OXMLTools.GetRowIndex(cloneFromCell.CellReference);\n    uint offset = rowIndex - cloneRowIndex;\n    exCell.CellFormula.Text = OXMLTools.GetUpdatedFormulaToNewRow(cloneFromCell.CellFormula.Text, offset);\n}\n\npublic static string GetUpdatedFormulaToNewRow(string formula, uint offset)\n{\n    return Regex.Replace(formula, @"[A-Za-z]+\d+", delegate(Match match)\n    {\n      //Calculate the new row for this cell in the formula by the given offset\n      uint oldRow = GetRowIndex(match.Value);\n      string col = GetColumnName(match.Value);\n      uint newRow = oldRow + offset;\n\n      //Create the new reference for this cell\n      string newRef = col + newRow;\n      return newRef;\n    });\n }	0
24718031	24717782	Create JSON string in c#	var obj = new {tafsir = new Dictionary<string, object>{\n                          {"1_1", new{text="Some text here"}},\n                          {"1_2", new{text="Some text here2"}}\n                        }\n              };\n\nvar json = JsonConvert.SerializeObject(obj,  Newtonsoft.Json.Formatting.Indented);	0
6085235	6085098	regex of any word not preceeded by a period	(?<![.])\b\w+\b	0
8327282	8318681	Gridview Calendar Extender get date	// Find the 2 text boxes within your GridView control\nTextBox toDateTextBox = (TextBox)GV_Rotl_Asgt.FindControl("NodataToDt");\nTextBox fromDateTextBox = (TextBox)GV_Rotl_Asgt.FindControl("NodatafrmDt");\n\n// Grab the values out of those text boxes\nstring toDate = toDateTextBox.Text;\nstring fromDate = fromDateTextBox.Text;	0
22118815	22116500	Exposing ILogger in a loosely coupled fashion	LogManager.LogFactory = new Log4NetFactory(true);	0
20655920	20655797	Disabling and enabling a button during postback in asp.net	/// <summary>\n///  Avoid multiple submit\n/// </summary>\n/// <param name="button">The button.</param>\n/// <param name="text">text displayed on button</param>\npublic void AvoidMultipleSubmit(Button button,string text="wait..." )\n{\n    Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm", "if(this.submitted) return false; this.submitted = true;");\n    button.Attributes.Add("onclick", string.Format("if(typeof(Page_ClientValidate)=='function' && !Page_ClientValidate()){{return true;}}this.value='{1}';this.disabled=true;{0}",\n        ClientScript.GetPostBackEventReference(button, string.Empty),text));\n}	0
8033062	8032996	C# progress bar change color	Application.EnableVisualStyles();	0
15754372	15754319	insert a link in to a email send using c#	String body = "Your message : <a href='http://www.xxx.com'></a>"\n m.Body = body;	0
2517431	2517394	How can I convert this "Tuesday, March 30, 2010 10:45 AM" string to a DateTime practically?	string strDateTime = "Tuesday, March 30, 2010 10:45 AM"; \n\n    DateTime myDateTime = DateTime.Parse(strDateTime);	0
10562272	10558989	Render pubDate with RSS SyndicationFeed api	feed.ElementExtensions.Add("pubDate", "", DateTime.UtcNow.ToString("r"));	0
4760437	4759979	Changing the value of a String in C# WinApp forever?	Properties.Settings	0
32441393	32405001	SqlXml removes XML header when comes from string	public string SqlXmlToString(SqlXml sqlXml)\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load(sqlXml.CreateReader());\n\n    // Create XML declaration with your encoding. \n    XmlDeclaration xmldecl;\n    xmldecl = doc.CreateXmlDeclaration("1.0", null, null);\n    xmldecl.Encoding = "UTF-8";\n\n    // Add to the document the created declaration\n    XmlElement root = doc.DocumentElement;\n    doc.InsertBefore(xmldecl, root);\n\n    return doc.OuterXml;\n}	0
7065663	7065596	C# - select system fonts from menu	FontDialog fontDialog1 = new FontDialog();\nfontDialog1.Font = textBox1.Font;\nfontDialog1.Color = textBox1.ForeColor;\n\nif(fontDialog1.ShowDialog() != DialogResult.Cancel )\n{\n   textBox1.Font = fontDialog1.Font ;\n   textBox1.ForeColor = fontDialog1.Color;\n}	0
30576122	16191106	Export rdl report to a multiple sheets excel file problematically from c#	var bytes = localReport.Render("EXCELOPENXML", string.Empty);	0
16149984	16143726	Removing gridlines from graph	area2.AxisX.MajorGrid.Enabled  = False\narea2.AxisX2.MajorGrid.Enabled = False\narea2.AxisY.MajorGrid.Enabled  = False\narea2.AxisY2.MajorGrid.Enabled = False\narea2.AxisX.MinorGrid.Enabled  = False\narea2.AxisX2.MinorGrid.Enabled = False\narea2.AxisY.MinorGrid.Enabled  = False\narea2.AxisY2.MinorGrid.Enabled = False	0
13269538	13182654	From DataTable to DataGridView including image path	public Form1()\n    {\n        InitializeComponent();\n\n        Random r = new Random();\n        DataTable table = new DataTable();\n        table.Columns.Add("ID", typeof(int));\n        table.Columns.Add("Name", typeof(string));\n        table.Columns.Add("ImageName", typeof(string));\n\n        table.Rows.Add(1, "Row 1", "copy.png");\n        table.Rows.Add(2, "Row 2", "cut.png");\n        table.Rows.Add(3, "Row 3", "folder.png");\n        table.Rows.Add(4, "Row 4", "help.png");\n\n        this.radGridView1.DataSource = table;\n\n        radGridView1.Columns["ImageName"].IsVisible = false;\n\n        GridViewImageColumn col = new GridViewImageColumn("Image");\n        radGridView1.Columns.Add(col);\n\n        foreach (GridViewRowInfo row in radGridView1.Rows)\n        {\n            string path = "..\\..\\"; //here you set your path\n            row.Cells["Image"].Value = Image.FromFile( Path.Combine(path, row.Cells["ImageName"].Value.ToString()));\n\n        }\n    }	0
6055332	6055140	XML serialization in .net	public class Root\n{\n    [XmlElement("custom-attribute")]\n    public Colour Colour { get; set; }\n}\n\npublic class Colour : IXmlSerializable\n{\n    [XmlText]\n    public string Value { get; set; }\n\n    public XmlSchema GetSchema()\n    {\n        return null;\n    }\n\n    public void ReadXml(XmlReader reader)\n    {\n        throw new NotImplementedException();\n    }\n\n    public void WriteXml(XmlWriter writer)\n    {\n        writer.WriteAttributeString("dt:dt", "", "string");\n        writer.WriteAttributeString("name", "Colour");\n        writer.WriteString(Value);\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var serializer = new XmlSerializer(typeof(Root));\n        var root = new Root\n        {\n            Colour = new Colour\n            {\n                Value = "blue"\n            }\n        };\n        serializer.Serialize(Console.Out, root);\n    }\n}	0
32548784	32548696	webapi deserialize JSON request with datetime in controller	var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;\njson.UseDataContractJsonSerializer = true;	0
3870975	3845685	Is it possible to get one of the child node get selected programatically	TreeNode TvNode = tvwACH.SelectedNode.Parent;\n\n            while (TvNode != null)\n            {\n                if (TvNode.Text.EndsWith(".txt", true, System.Globalization.CultureInfo.InvariantCulture))\n                {\n                    tvwACH.SelectedNode = TvNode;\n                    TvNode = null;\n                }\n                else\n                    TvNode = TvNode.Parent;\n            }	0
9282442	9282335	How to filter a collection of a collection in linq?	var tableBs = session.Query<TableA>()\n                     .Where(a => a.TableBs.Any(b => b.Name == "bob"))\n                     .SelectMany(a => a.TableBs);	0
1346324	1320980	How to insert a Combobox value in to a database	((ComboBoxItem)rpcombo.SelectedItem).Content.ToString()	0
15364438	15364068	How to scroll to a specific element in a StackPanel?	StackPanel.MakeVisible(Visual visual, Rect rectangle)	0
7847051	7846718	How to wait for background worker to finish processing?	private object lockObj;\n\nprivate void backgroundWorkerN_RunWorkerCompleted(\n    object sender, \n    RunWorkerCompletedEventArgs e)\n{\n    lock (lockObj)\n    {\n        y = true;\n        if (cb && cr) // if cb and cr flags are true - \n                      // other backgroundWorkers finished work\n        {\n            someMethodToDoOtherStuff();\n        }\n    }\n}	0
2887791	2887773	Self join in Entity Framework	var query = from c1 in db.Category\n            where c1.ParentCategoryId == null\n            join c2 in db.Category on c1.CategoryId equals c2.ParentCategoryId\n            select c2;	0
29318041	29318000	C# How to Print 2 arrays together	for (int j = 0; j < wow.Length; j++)\n{\n     wow1[j] = j + 1;\n     wow2[j] = j + 10;\n     //print wow1 & wow2 here. \n     Console.WriteLine("{0},{1}", wow1[j], wow2[j]);\n}	0
12846664	12846604	Get data from sql server into textbox error message	string sqlquery = ("SELECT Architecture FROM tblServer WHERE ServerName = '" + serverName + "'");	0
13726850	13726778	How to use XmlWriter recursively?	private void generateXml(XmlWriter writer, Control receivedControl)\n{\n    foreach (Control subCtrl in receivedControl.Controls)\n    {\n            writer.WriteStartElement(subCtrl.Name);\n            generateXml(writer, subCtrl);\n            writer.WriteEndElement();\n    }\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    using (XmlWriter writer = XmlWriter.Create("C:\\ui.xml"))\n    {\n        writer.WriteStartDocument();\n        writer.WriteStartElement(this.Name); // This is the document element\n        foreach (Control c in this.Controls)\n        {\n            generateXml(writer, c);\n        }\n        writer.WriteEndDocument(); // Close any open tags\n    }\n}	0
925055	922440	how can i pass a parameter to EnqueueTimer in the .net ccr	var timerPort = new Port<DateTime>();\ndq.EnqueueTimer(TimeSpan.FromMilliseconds(TIMEOUT), timerPort);\ntimerPort.Receive(ignored => MyFunc(myParam));	0
7447222	7446888	Formatting Datasource of Dropdown list	class Node\n    {\n        public string Name { get; set; }\n        public List<Node> Child { get; private set; }\n\n        public Node(string name)\n        {\n            Child = new List<Node>();\n            Name = name;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var listItems = new List<string>();\n        var root = new Node("Root");\n        root.Child.Add(new Node("1"));\n        root.Child.Add(new Node("3"));\n        var node = new Node("4");\n        var nd = new Node("5");\n        nd.Child.Add(new Node("7"));\n        node.Child.Add(nd);\n        node.Child.Add(new Node("6"));\n        root.Child.Add(node);\n\n        GetNames(root, listItems);\n\n        foreach (var listItem in listItems)\n        {\n            Console.WriteLine(listItem);\n        }\n    }\n\n    static void GetNames(Node parent, List<string> result)\n    {\n        result.Add(parent.Name);\n        foreach (var child in parent.Child)\n        {\n            GetNames(child, result);\n        }\n    }	0
20098351	20098173	First page with QueryString	value = "index.aspx?a=22"	0
2482876	2482776	How do I handle editing of custom types in a C# datagridview?	e.Value = new ExDateTime(e.Value.ToString());\ne.ParsingApplied = true;	0
4204156	4203693	Windows Service with AutoResetEvent	while (true)\n{\n  Trace.Write("Starting ProcessQueue")\n  stateTimer.Enabled = false;\n  DateTime start = DateTime.Now;\n\n  // do the work\n\n  // check if timer should be restarted, and for how long\n  TimeSpan workTime = DateTime.Now - start;\n  double seconds = workTime.TotalSeconds;\n  if (seconds > 30)\n  {\n    // do the work again\n    continue;\n  }\n  else\n  {\n     // Restart timer to pop at the appropriate time from now\n     stateTimer.Interval = 30 - seconds;\n     stateTimer.Enabled = true;\n     break;\n  }\n}	0
32581126	32575486	EF6 Get Record where info from two different tables equal x	var firstUnprocessedRecord = (from eur in de.EUReporteds \n                             where !eur.Processed && eur.ReportProcessingCount < 11 \n                             && !(de.ProcessingResults.Any(o=>o.UserId == CurrentUser.UserId && o.id == eur.id))\n                             orderby eur.id\n                             select eur).FirstOrDefault();	0
32360269	32359280	Pass argument from link button to javascript	LinkButton lb = Repeater1.Controls[index of the reapeater item].FindControl("LinkButton2") as LinkButton;\nlb.Attributes.Add("CommandArgument", lb.CommandArgument);	0
8726615	8726407	How To Update Common Properties of Different Type of Entityobjects?	public interface IAuditEntity\n{\n    User CreateUsr { get; set;}\n    DateTime OperationTime { get; set;}\n    User LastOperationUser { get; set;}\n}\n\n public void UpdateEntityObjectsCommonFields(IAuditEntityobj) \n {  /// just i guess\n    obj.CreateUsr  = Session.Usr;\n    obj.OperationTime  = DateTime.Now;\n    obj.LastOperationUser  = Session.Usr;\n }	0
33943824	33943552	How to put an image in a progress bar programmatically (WPF)	FrameworkElementFactory grid = new FrameworkElementFactory(typeof(Grid));\n\nFrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));\nimage.Name = "PART_Track";\nImageSource source = new BitmapImage(...); // create it\nimage.SetValue(Image.SourceProperty, source);\nimage.SetValue(Image.StretchProperty, Stretch.Fill);\n\ngrid.AppendChild(image);\n\nFrameworkElementFactory rectangle = new FrameworkElementFactory(typeof(Rectangle));\nrectangle.Name = "PART_Indicator";\nrectangle.SetValue(Rectangle.FillProperty, new SolidColorBrush(Colors.BlanchedAlmond));\nrectangle.SetValue(Rectangle.HorizontalAlignmentProperty, HorizontalAlignment.Left);\n\ngrid.AppendChild(rectangle);\n\n    ControlTemplate ct = new ControlTemplate(typeof(ProgressBar));\nct.VisualTree = grid;\n\nMyProgressBar1.Template = ct;	0
5235497	5235467	Trying to extract a list of keys from a .NET Dictionary	List<String> myKeys = myDict.Keys.ToList();	0
4375624	4375593	How to access a string variable outside	string casename = "some default value";\nwhile (casetypeMyReader.Read())\n{\n    casename = casetypeMyReader["casename"].ToString();\n}\n// You can access casename here and it's value will either be the default one\n// if the reader returned no rows or the last row being read.	0
8206347	8206306	Two comboBoxes with same members, when one selected, other must be unable to select same member	comboBoxToAccount.DataSource = null;	0
22038602	22038486	Call a virtual method from its overridden	base.MethodName()	0
21716215	21715991	How to get a list of files and folders in the subdirectory	SearchOption.AllDirectories	0
4107600	4107391	How do I call a function without the Main function in C sharp?	Timer timer = new Timer();\npublic void RunMix(object sender, EventArgs e)\n{\n  label1.Text = knob1.Angle.ToString();            \n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n  timer.Interval = 100;\n  timer.Tick += new EventHandler(RunMix);\n  timer.Start();\n}	0
11602670	11602591	Store and Retrieve DateTime to SQL as Integer	public static long ToFileTimeUtc(DateTime dateTime) {\n  return dateTime.ToFileTimeUtc();\n}\n\npublic static DateTime FromFileTimeUtc(long fileTimeUtc) {\n  return DateTime.FromFileTimeUtc(fileTimeUtc);\n}	0
33008141	33008044	How to select Sqlparameter list element by name?	var parameter = para.Where(a=>a.ParameterName == youParameterName).FirstOrDefault();	0
11428835	11428724	How to create inverse png image?	public void ApplyInvert()  \n{  \n    byte A, R, G, B;  \n    Color pixelColor;  \n\n    for (int y = 0; y < bitmapImage.Height; y++)  \n    {  \n        for (int x = 0; x < bitmapImage.Width; x++)  \n        {  \n            pixelColor = bitmapImage.GetPixel(x, y);  \n            A = (byte)(255 - pixelColor.A); \n            R = pixelColor.R;  \n            G = pixelColor.G;  \n            B = pixelColor.B;  \n            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));  \n        }  \n    }  \n}	0
13615089	13594117	How do I get information about a warning from the TFS-API	Workspace.QueryConflicts	0
4359611	4358395	MVC3 + Ninject - How to?	Ninject.MVC3	0
1631542	1631501	Need microsecond delay in .NET app for throttling UDP multicast transmission rate	static void Main(string[] args)\n    {\n        Stopwatch sw;\n        sw = Stopwatch.StartNew();\n        int i = 0;\n\n        while (sw.ElapsedMilliseconds <= 5000)\n        {\n            if (sw.Elapsed.Ticks % 100 == 0)\n            { i++; /* do something*/ }\n        }\n        sw.Stop();\n\n\n    }	0
18964956	18964488	FindAsync with non-primary key value	var userId = ...;\nvar foos = await db.Foos.Where(x => x.UserId == userId).ToListAsync();	0
12996409	12996371	How to add a file to a table in MS SQL Server	varbinary(MAX)	0
32191679	32191632	How can I reuse my explicit column selection?	var q = (from a in context.Accounts\n    join c in context.Contracts\n    on a.Id equals c.AccountId\n    where c.Id == id\n    select a).Select(DefaultColumns);	0
21789752	21787106	Getting the text from a elementhost child text	Microsoft.Office.Interop.Word.dll	0
8771415	8771239	How to replace user control in cell into the Grid. WPF?	public void ReplaceItemAt(Grid grid, FrameworkElement fe, int row, int col)\n{\n    // clear desired cell\n    var items = grid.Children\n        .Where(x => Grid.GetRow(x) == row && Grid.GetColumn(x) == col)\n        .ToArray();\n    foreach(var item in items) grid.Children.Remove(item);\n\n    // make sure the new item is positioned correctly\n    Grid.SetRow(fe, row);\n    Grid.SetColumn(fe, col);\n\n    // insert the new item into the grid\n    grid.Children.Add(fe);\n}	0
14119108	14118993	Facebook Login in sitecore	Sitecore.Security.Authentication.AuthenticationManager.Login("username_here");	0
7990555	7990134	working with the selected DataGridView row in C#	class Client\n{\n   public static explicit operator Client(DataRow dr)\n   {\n      // code to convert from dr to Client\n   }\n}\n\nClient current = (Client)myRow;	0
9252458	9240690	Webbrowser control is not showing Html but shows webpage	FillFrame(webBrowser1.Document.Window.Frames);\n\n\n\nprivate void FillFrame(HtmlWindowCollection hwc)\n        {\n\n\n            if (hwc == null) return;\n            foreach (HtmlWindow hw in hwc)\n            {\n                HtmlElement getSpanid = hw.Document.GetElementById("mDisplayCiteList_ctl00_mResultCountLabel");\n                if (getSpanid != null)\n                {\n\n                    doccount = getSpanid.InnerText.Replace("Documents", "").Replace("Document", "").Trim();\n\n                    break;\n                }\n\n                if (hw.Frames.Count > 0) FillFrame(hw.Frames);\n            }\n\n\n        }	0
20092845	20092710	How to serialize list to XML without parent element	[XmlElement("ListItem")]\npublic List<ListItem> ListItems { get; set; }	0
34029072	34028713	I need a Regex expression pattern for this HTML string	var regex=@"<option value='(?<value>\d+)'>(?<content>[^<]*)";\nvar search=@"Language<option value='32'>Bahasa Indonesia<option value='19'>Dansk<option value='4'>Deutsch<option value='1'>English<option value='2'></option></option></option></option>";\nvar list=System.Text.RegularExpressions.Regex\n  .Matches(search,regex)\n  .Cast<Match>()\n  .Select(match => new { \n    Value=match.Groups["value"].Value, \n    Content=match.Groups["content"].Value});	0
24740688	24740434	Replace using Regular Expression - fixed digit location	// Split into 2 groups of 5 digits and 1 of 6\n string regex = "(\\d{5})(\\d{5})(\\d{6})";\n\n // Insert ABCDEF in the middle of \n // match 1 and match 3\n string replaceRegex = "${1}ABCDE${3}";\n\n string testString = "1234567890999999";\n\n string result = Regex.Replace(testString, regex, replaceRegex);\n\n // result = '12345ABCDE999999'	0
7894872	7894839	C# How to represent an Int as four-byte integer	BitConverter.GetBytes(message.Length);	0
1504340	1504241	Need help debugging: Having trouble getting data to Silverlight App through RIA Services, Entity Framework, MySQL	var qry = this.Context.saw_order.Where(o => o.Wo == intOrder);\nreturn qry;	0
16664014	16663640	Filtering For duplicate entries in ICollectionView	...\n    ObservableCollection<ABC> Items { get;set}\n    ListCollectionView ItemsView { get;set }\n    ...\n    // View filter logic\n    ItemsView.Filter = o =>\n            {\n                var abc = o as ABC;\n                if (abc == null) return false;\n                return abc.Category == "Alphabet" &&\n                       abc == Items.First(i => i.Name == abc.Name);\n            };	0
20331269	20331250	Cast From Arraylist To a String	string s = Solutions[r].ToString(); // you're missing brackets	0
11223638	11223365	Insert Many to Many in EF With Some Logic	foreach (var tg in tags.Split(','))\n{\n    var tag = context.Tags.SingleOrDefault(x => x.TagName == tg);\n    if (tag == null)\n        tag = new Tag() { TagName = tg };\n\n    article.Tags.Add(tag);\n}	0
10185061	10185020	commonly integrate a line of code at many places in c#	public static MySqlConnection Connect() {\n    OldCompatibility.BinaryAsString = true;\n    MySqlConnection conn = new MySqlConnection("User id=root;pwd=root;port=3306;host=localhost;database=test");\n    conn.Open();\n\n    return conn;\n}	0
15681321	15666703	listview display error with List strings in C#	//Clear it\nlistView1.Items.Clear();\n//reload it.\nlistView1.Refresh();	0
6659299	6657923	Scroll to bottom of listbox wp7	void MainPage_Loaded(object sender, RoutedEventArgs e)\n{\n    listmy.SelectedIndex = listmy.Items.Count - 1;\n    listmy.ScrollIntoView(listmy.SelectedItem);\n}	0
5355589	5355173	WPF c# Retrieving a listbox row's contents from a button in the same datatemplate	private void btnDirectoryOpen_Click(object sender, RoutedEventArgs e)\n{\n    var item = ((Button) sender).DataContext;\n    var itemIndex = lbDirectoryTreeBox.Items.IndexOf(item);\n    // ...\n}	0
6028492	6019555	From C#, How to validate whether Table is already exists in MS Access DB	Dim schemaDT As DataTable\nDim thisNull As System.DBNull()\nschemaDT = thisConn.GetOleDbSchemaTable( _\nOleDbSchemaGuid.Tables, thisNull)	0
30664940	30664543	Passing DataSet to Stored Procedure	1) Create Table type in sql server for the DataTable which you want to pass.\n2) Declare input variable for given table type as readonly in stored procedure.\n3) Pass that data table to procedure.	0
30750313	30740659	Getting the length of a row in excel	bool endReach=false;    \nfor (int j = 1; !endReach; j++)\n    {\n      if(excel_getValue("A"+j) == "" && excel_getValue("A"+(j+1)) == "")\n      {\n             endReach=true;\n       }else{\n             list.add(excel_getValue("A"+j)); //ROW A in excel\n       }\n    }	0
608181	608110	Is it possible to deserialize XML into List<T>?	using System;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\n\n[XmlRoot("user_list")]\npublic class UserList\n{\n    public UserList() {Items = new List<User>();}\n    [XmlElement("user")]\n    public List<User> Items {get;set;}\n}\npublic class User\n{\n    [XmlElement("id")]\n    public Int32 Id { get; set; }\n\n    [XmlElement("name")]\n    public String Name { get; set; }\n}\n\nstatic class Program\n{\n    static void Main()\n    {\n        XmlSerializer ser= new XmlSerializer(typeof(UserList));\n        UserList list = new UserList();\n        list.Items.Add(new User { Id = 1, Name = "abc"});\n        list.Items.Add(new User { Id = 2, Name = "def"});\n        list.Items.Add(new User { Id = 3, Name = "ghi"});\n        ser.Serialize(Console.Out, list);\n    }\n}	0
5982934	5982903	Limiting Results in DataGrid	dgRequests.DataSource = GetMyDataSource();\ndgRequests.DataBind();	0
9499061	9498883	How to filter child tables with EF4?	var parents = context.Parents.ToList();\nforeach(var parent in parents)\n{\n    var invalidChildren = parent.CHILD\n        .Where(child => child.CONCLUSION.HasValue())\n        .ToArray();\n    foreach(var invalid in invalidChildren)\n    {\n        parent.CHILD.Remove(invalid);\n    }\n}	0
28149949	28149294	Hybrid windows forms and console app without console window in forms mode	[STAThread]\nprivate static void Main(string[] args)\n{\n   if (args.Length == 0)\n   {\n      Application.EnableVisualStyles();\n      Application.SetCompatibleTextRenderingDefault(false);\n      Application.Run(new Form1());\n   }\n   else\n   {\n      AllocateConsole();\n      Console.WriteLine("I'm a console application");\n      //...\n      FreeConsole();\n   }\n}	0
11212445	11212309	Algorithm to find rectangles	for i in width  \n{  \nfor j in height  \n{  \nif(point[i,j] == 1)  \n{  \n       potentials = searh_in_direction(i,j,graph,width,height,RIGHT,[[i,j]] )  \n     listOfAllRects.append(potentials)  \n}  \n}  \n}\nlist_of_rectangle searh_in_direction(i,j,graph,width,height,direction, listofpoints )  \n{  \n  nextdirection = direction.nextdirection; //Right -> down -> left-> up \n\n\n  //DEVELOP METHOD FOR RECURSION HERE THAT RETURNS ALL SETS OF 4 POINTS THAT\n  for every point in the direction of travel\n  if the point is the origional point and we have 4 points including the point we are looking at, we have a rectangle and we need to return\n  if point on direction of travel is a one travel on the next direction\n  posiblerects.append(searh_in_direction(i,j,graph,width,height,nextdirection , listofpoints.append(currentpoint)))\n\n//after all points in direction have bee searched\nreturn posiblerects.\n}	0
26253883	26253705	Invoking methods based on a string	private Dictionary<string, Func<byte[], int, object>> _dict;\n\n    public void DataTypes()\n    {\n        // create new dictionary\n        _dict = new Dictionary<string, Func<byte[], int, object>>\n        {\n            // fill dictionary with key-value pairs\n            {"uint16", (data, pos) => BitConverter.ToUInt16(data, pos)},\n            {"uint32", (data, pos) => BitConverter.ToUInt32(data, pos)},\n            {"sint16", (data, pos) => BitConverter.ToInt16(data, pos)},\n            {"sint32", (data, pos) => BitConverter.ToInt32(data, pos)}\n        };\n    }\n\n    // converts byte-array to specified type\n    public object getValue(string type, byte[] data, int pos) // e.g. type = "uint16"\n    {\n        if (_dict.ContainsKey(type))\n            return _dict[type](data, pos);\n        return null;\n    }	0
7730369	7729183	Add minutes from one column to datetime column in linq query	System.Data.Objects.EntityFunctions.AddMinutes(emails.Created, emails.Minutes) < DateTime.Now	0
31467342	31467024	C# WinForms: populating datagridview with datasource from two different tables	return Convert.ToInt32(this.dgvBuildings.SelectedRows[0].Cells[0].Value);	0
5754517	5754469	Insert into DataTable from DataTable	using System.Linq;	0
19695025	19694977	How do you shift an array of objects while wrapping without iteration?	static void Rotate<T>(T[] source)\n{\n  var temp = source[source.Length - 1];\n  Array.Copy(source, 0, source, 1, source.Length - 1);\n  source[0] = temp;\n}	0
25775218	25751444	Transform rotation to movement direction in 2D space	transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,transform.position.z), Vector3.up);	0
30860932	30667902	Multiple C# WebAPI API routes - restrict API method to one of the routes	[Route("api/wordpress/shared/AddUser")]\n[HttpPost]\npublic Object AddUser(string username)\n{\n}	0
781849	781832	Will all methods in a logical expressions be executed?	if (Action1(Data))\n{\n    PerformOtherAction();\n} \nelse if (Action2(Data))\n{\n    PerformOtherAction();\n}	0
30583214	30581770	How to add Namespace and Declaration to the existing XML	var doc  = XDocument.Parse(xml);\n\nXNamespace ns = "http://a.com/a";\n\nforeach (var element in doc.Descendants())\n{\n    element.Name = ns + element.Name.LocalName;\n}	0
32187759	32187045	inheriting a class with parameteraized constractor to reuse base properties	public class SharedData\n{\n    internal static string GlobMeta;\n    internal static int GlobValue;\n\n    public SharedData(string meta, int value)\n    {\n        GlobMeta = meta;\n        GlobValue = value;\n    }\n\n    public SharedData(){}\n}\n\npublic class DerivedData: SharedData\n{\n    public DerivedData() : base()\n    {\n        Console.WriteLine("Shared meta = {0}, Shared Value = {1}", GlobMeta, GlobValue);\n    }\n}	0
3999321	3999264	How to get XmlSchema object from XSD which is string in C#?	string content = ".......";\nXmlSchema schema = new XmlSchema();\nschema.Read(new StringReader(content), ValidateSchema);	0
27966734	27966578	Data not inserting to DB through WCF	cmd.Parameters.AddWithValue("@CreateDate", Convert.ToDateTime(dr.CreateDate));\nint result = cmd.ExecuteNonQuery(); // This line is missing\ncon.Close();	0
14047127	14047069	insert image in the database	string sqlcon = "insert into images(imgname,imgpath)values('"+imagename+"','"+imagepath+"')";	0
18750760	18730473	Deleting element from an observableArray	valueHasMutated()	0
22551294	22551252	Regex for a special string pattern on multiple levels	String input = "<%(ddlValue){DropDownList}[SelectedValue]%>";\nString pattern = @"<%\((.+)\)\{(.+)\}\[(.+)\]%>";\n\nMatch m = Regex.Match(input, pattern);\n\nif (m.Groups.Count == 4) \n{\n    string firstpart = m.Groups[1].ToString();\n    string secondpart = m.Groups[2].ToString();\n    string thirdpart = m.Groups[3].ToString();\n}	0
9033731	9033570	how to find .Handle of RichTextBox?	IntPtr hwnd = new WindowInteropHelper(Window.GetWindow(userControlRefernce)).Handle;	0
29035111	29034975	How to store Microsoft's Dynamic Linq's OrderBy in a variable?	Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = t => t.OrderBy( String.Join(",", orderBy));	0
10193833	10105318	Application runs slow when DB logging info is applied to each Crystal Reports Sections	objrpt.PrintToPrinter	0
11626854	11620253	Problems with Schema XML attribute in EDMX file	eset.MetadataProperties["http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator:Type"].Value.ToString(); \n eset.MetadataProperties["http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator:Schema"].Value.ToString();	0
28391869	28391165	How do you show progress in the Taskbar with Winform C# 4.5	System.Windows.Window w = new System.Windows.Window();\n    w.TaskbarItemInfo = new System.Windows.Shell.TaskbarItemInfo() { ProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal };\n    w.Loaded += delegate {\n        Action<Object> callUpdateProgress = (o) => {\n            w.TaskbarItemInfo.ProgressValue = (double) o;\n        };\n\n        Thread t = new Thread(() => {\n            for (int i = 1; i <= 10; i++) {\n                w.Dispatcher.BeginInvoke(callUpdateProgress, 1.0 * i / 10);\n                Thread.Sleep(1000);\n            }\n        });\n        t.Start();\n    };\n\n    System.Windows.Application app = new System.Windows.Application();\n    app.Run(w);	0
2112874	2112850	variable scope - how to decide	public Class B\n{\n    A myA = new A();\n}	0
10754495	10752971	first blank row in excel	int rowIdx = 0;\nint notEmpty = 1;\nwhile (notEmpty > 0)\n{\n    string aCellAddress = "A" + (++rowIdx).ToString();\n    Range row = App.get_Range(aCellAddress, aCellAddress).EntireRow;\n    notEmpty = _App.WorksheetFunction.CountA(row);\n}	0
19355850	19355566	Check if the selected item in a listbox contains specific characters	if (listBox1.SelectedIndex != -1)\n        {\n            int itemAtPostion = listBox1.SelectedIndex;\n            string reserved = "Reserved";\n\n            if (listBox1.Items[itemAtPostion].ToString().Contains(reserved))\n            {\n                MessageBox.Show("We are sorry, but this seat is reserved!");\n                //your code\n            }\n        }	0
14625100	14607868	WPF Fade In / Out only runs once	// Fading animation for the textblock to show that the settings are updated.\nDoubleAnimation fadingAnimation = new DoubleAnimation();\nfadingAnimation.From = 0;\nfadingAnimation.To = 1;\nfadingAnimation.Duration = new Duration(TimeSpan.FromSeconds(1.5));\nfadingAnimation.AutoReverse = true;\n\nUpdateMessage.BeginAnimation(TextBlock.OpacityProperty, fadingAnimation);	0
12944576	12944575	Diagnose communication problems with a Zaber device	IRP_MJ_READ;IRP_MJ_WRITE	0
34013379	34013044	I need help displaying a word (string) from a text file in C#	found = 0;\nString[] tokens = line.Split(new char[] {' '});\nforeach (String token in tokens) {\n    if (token.IndexOf(userText, StringComparison.OrdinalIgnoreCase) != -1) {\n        Console.WriteLine(token); // Do your stuff here\n        found++; //increment to know how many times you found the word in the current line\n    }\n}\ncounter += found; //counter will contains all occurences in lines	0
1936098	1936089	How to run over cells on Excel in C#?	Excel.Application oXL;\n    Excel._Workbook oWB;\n    Excel._Worksheet oSheet;\n    Excel.Range oRng;\n\n\n    //Start Excel and get Application object.\n    oXL = new Excel.Application();\n    oXL.Visible = true;\n\n    //Get a new workbook.\n    oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));\n    oSheet = (Excel._Worksheet)oWB.ActiveSheet;\n\n    //Add table headers going cell by cell.\n    oSheet.Cells[1, 1] = "First Name";	0
2002695	2002535	ComboBox to sorted Xml file. Need help to optimize	public static void Save(ComboBox items) {\n  XElement xmlElements = new XElement("Root");\n  xmlElements.Add(\n    items.Items\n      .Cast<string>()\n      .OrderBy(s => s)\n      .Select(s => new XElement("Child", s))\n      .ToArray()\n  );\n  xmlElements.Save("Output.xml");\n}	0
33411264	33409304	Change the position of Excel rows	var employee = "Employee Name";\n        var month = "October";\n        var year = "2015";\n\n        htw.WriteLine("Year: {0}<br/>Month: {1}<br>Employee: {2}<br/>",year,month,employee);\n        grid.RenderControl(htw);	0
679230	679171	Combining URIs and Paths	Uri apiUri = new Uri("http://www.r-s.co.uk/eproxy.php");\nstring methodPath = "/char/SkillIntraining.xml.aspx";\n\nSystem.UriBuilder uriBuilder = new System.UriBuilder(apiUri);\nuriBuilder.Path += methodPath;\n\nConsole.WriteLine(uriBuilder.Uri.ToString());	0
515536	515381	How to log Trace messages with log4net?	public class Log4netTraceListener : System.Diagnostics.TraceListener\n{\n    private readonly log4net.ILog _log;\n\n    public Log4netTraceListener()\n    {\n        _log = log4net.LogManager.GetLogger("System.Diagnostics.Redirection");\n    }\n\n    public Log4netTraceListener(log4net.ILog log)\n    {\n        _log = log;\n    }\n\n    public override void Write(string message)\n    {\n        if (_log != null)\n        {\n            _log.Debug(message);\n        }\n    }\n\n    public override void WriteLine(string message)\n    {\n        if (_log != null)\n        {\n            _log.Debug(message);\n        }\n    }\n}	0
848404	825714	How to get elements value with Linq To XML	XNamespace ns = "http://www.collegenet.com/r25";\nstring id = doc.Descendants(ns.GetName("space_id").Single().Value;	0
1351673	1351651	How to use C# to add a column for a table of sql server?	using (DbConnection connection = new SqlConnection("Your connection string")) {\n    connection.Open();\n    using (DbCommand command = new SqlCommand("alter table [Product] add [ProductId] int default 0 NOT NULL")) {\n        command.Connection = connection;\n        command.ExecuteNonQuery();\n    }\n}	0
34085002	34084898	How to sort Dictionary of two integers not by using LINQ but using BubbleSort?	var sample = new Dictionary<int, int>\n{\n    {0,5},\n    {1,2},\n    {2,3},\n    {3,1},\n    {4,9}\n};\n\nvar keyValuePairs = sample.Select(p => new Tuple<int, int>(p.Key, p.Value)).ToList();\n\nvar sortedKeyValuePairs = keyValuePairs.OrderBy(t => t.Item2);	0
16136940	16136927	Save as new name each time	Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, \n              Screen.PrimaryScreen.Bounds.Height);\n\nGraphics graphics = Graphics.FromImage(bitmap as Image);\n\n  graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);\n\nbitmap.Save(@"c:tempscreenshot" + DateTime.Now.Ticks + ".bmp", ImageFormat.Bmp);	0
6165670	6028046	Linq: How can I get a result in a grouping query which is value agnostic and has dynamic columns?	from foo in Foo\nlet name = foo.IpsumType.IpsumName\ngroup foo by new\n{\n  Lorem = foo.Lorem,\n  Name = name\n} into g\nselect new\n{\n  Lorem = g.Key.Lorem,\n  Name = g.Key.Name,\n  Count = g.Count()\n};	0
29345712	29336015	Handling the result of a SQLite aggregate function on Windows Phone	var query = @"SELECT time(max(MyTime))\n              FROM YourTable";\nusing (var db = new SQLiteConnection(your connection string))\n{\n    // MaxTime being a string that is bound to the textblock on the view.\n    MaxTime = db.CreateCommand(query).ExecuteScalar<string>();\n}	0
16695072	16692971	How to Loop through multiple Database connections skipping on connection error	Try\n    Me.1TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"\n    'your code here to create HTML table'\nCatch ex As Exception\nEnd Try	0
23358235	23358155	How to add new items to SharePoint List using List.asmx native WebService and client object model?	using System;\nusing Microsoft.SharePoint.Client;\nusing SP = Microsoft.SharePoint.Client;\n\nnamespace Microsoft.SDK.SharePointServices.Samples\n{\n    class CreateListItem\n    {\n        static void Main()\n        {   \n            string siteUrl = "http://MyServer/sites/MySiteCollection";\n\n            ClientContext clientContext = new ClientContext(siteUrl);\n            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");\n\n            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();\n            ListItem oListItem = oList.AddItem(itemCreateInfo);\n            oListItem["Title"] = "My New Item!";\n            oListItem["Body"] = "Hello World!";\n\n            oListItem.Update();\n\n            clientContext.ExecuteQuery(); \n        }\n    }\n}	0
5140140	5140014	design choice for a data structure customizable by the user?	{\n    "ID" : 1,\n    "FirstName" : "Joe",\n    "LastName" : "Bloggs",\n    "FavouriteColour" : "Blue"\n}\n\n{\n    "ID" : 2,\n    "FirstName" : "John",\n    "LastName" : "Smith",\n    "DOB" : "2000-01-01"\n}	0
23110203	23108581	Execute SelectionChangedEvent from code behind	SelectionChanged.Execute(new SelectionChangedEventArgs(ComboBox.SelectionChangedEvent, removeList,addList));	0
23666873	23666806	Add reference to dynamic assembly	Assembly.Load	0
7240079	7240006	Binding Validation without XAML	bindtext.ValidationRules.Add(new NumberRangeRule() { Min = 0, Max = 128 });	0
3258564	78974	How to set the output cache directive on custom controls with no code in front	List<Object> listOfObjects = null;\n//assuming a List of Objects... it doesn't matter whatever type of data you use\n        if (Context.Cache["MyDataCacheKey"] == null)\n        {\n            // data not cached, load it from database\n            listOfObjects = GetDataFromDB();\n//add your data to the context cache with a sliding expiration of 10 minutes.\n            Context.Cache.Add("MyDataCacheKey", listOfObjects, null,\n                System.Web.Caching.Cache.NoAbsoluteExpiration,\n                TimeSpan.FromMinutes(10.0),\n                System.Web.Caching.CacheItemPriority.Normal, null);\n        }\n        else\n            listOfObjects = (List<Object>)Context.Cache["MyDataCacheKey"];\n\n        DropDownList1.DataSource = listOfObjects;\n        DropDownList1.DataBind();	0
3049904	3049825	Given a Member Access lambda expression, convert it to a specific string representation with full access path	public string GetPath<T>(Expression<Func<T, object>> expr)\n{\n    var stack = new Stack<string>();\n\n    MemberExpression me;\n    switch (expr.Body.NodeType)\n    {\n        case ExpressionType.Convert:\n        case ExpressionType.ConvertChecked:\n            var ue = expr.Body as UnaryExpression;\n            me = ((ue != null) ? ue.Operand : null) as MemberExpression;\n            break;\n        default:\n            me = expr.Body as MemberExpression;\n            break;\n    }\n\n    while (me != null)\n    {\n        stack.Push(me.Member.Name);\n        me = me.Expression as MemberExpression;\n    }\n\n    return string.Join(".", stack.ToArray());\n}	0
18143355	18143156	Abstract collection of base class	public class MessageParentBase\n{\n}\n\npublic class ChatMessage : MessageParentBase\n{\n}\n\npublic abstract class ParentMessageWindowBaseViewModel<T> where T : MessageParentBase\n{\n    abstract internal ObservableCollection<T> GridData\n    {\n        get;\n        set;\n    }\n}\n\npublic class Child : ParentMessageWindowBaseViewModel<ChatMessage>\n{\n\n    internal override ObservableCollection<ChatMessage> GridData\n    {\n        get;\n        set;\n    }\n}	0
5437162	5437073	How to get a particular row from a DataRow[]?	String value = (String)rows.Single(\n    row => String.Equals(row["Id"], "0_0_0"))["Value"];	0
17125040	17124829	Cannot get TypeConverter.ConvertFromString to work with a Rectangle	rect.Height = 200;\nrect.Width = 200;\nrect.PointToScreen(new Point(50, 50));	0
31219226	31219191	How to check if a string value is in a correct time format?	private bool IsValidTimeFormat(string timeString)\n{\n    TimeSpan dummyTimeSpan;\n    return TimeSpan.TryParse(timeString, out dummyTimeSpan);\n}	0
26096353	26093753	how to display comparison chart using ajax	decimal[] z = new decimal[dt.Rows.Count];\nz[i] = Convert.ToInt32(dt.Rows[i][2]);\nBarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });	0
34022264	34017996	How can filtering be possible without for loop using LINQ?	var finalConsignments = ConsignmentToAddresses\n    // You group by ConsignmentId, as you want a single record for group\n    .GroupBy(c => c.ConsignmentId)\n    // Then you check if there is in the group a record with AddressTypeId == 5 ...\n    .Select(g => g.Where(x => x.AddressTypeId == 5).Any()\n        // ... if it exists you take it ...\n        ? g.Where(x => x.AddressTypeId == 5).First()\n        // ... otherwise you take the record with AddressTypeId == 2\n        : g.Where(x => x.AddressTypeId == 2).FirstOrDefault()).ToList();	0
2601746	2600789	EventLogAppender write only my app events	var elAppender = new EventLogAppender\n                         {\n                             ApplicationName = **"MyApp"**,\n                             LogName = **"MyLog"**,\n                             Layout = new PatternLayout(default_format),\n                             Threshold = Level.Error\n                         };\n    elAppender.ActivateOptions();	0
31928293	31909989	Multidimensional Array For Grid Based Movement	foreach(var gridSquare in allGridSquares)\n{\n   if( (Mathf.Abs(myX - gridSquare.Xcoord) + (Mathf.Abs(myY - gridSquare.Ycoor) >= myMovementValue)\n   {\n        gridSquare.activate();\n   }\n\n}	0
9440769	9432132	Trying to implement Serializble DIctionary from Keyedcollection, unable to add objects	public class SerialDictionary : KeyedCollection<int, Item>	0
26385974	26385742	How many string2 exist in string1?	string string1 = "#abc##asd###12####";\nstring string2 = "##";\nList<int> indexes = new List<int>();\nint index = -1;\nwhile((index = string1.IndexOf(string2, index + 1)) >= 0)\n{\n    indexes.Add(index);\n}\n\nConsole.WriteLine(indexes.Count);	0
6759693	5402840	Connecting and getting Response from Remote Linux machine using SharpSSH(using C sharp)	SshExec exec = new SshExec("host","eri_sn_admin");\n            exec.Password = "pass";\n            //if (input.IdentityFile != null) exec.AddIdentityFile(input.IdentityFile);\n\n            Console.Write("Connecting...");\n            exec.Connect();\n            Console.WriteLine("OK");\n            while (true)\n            {\n                Console.Write("Enter a command to execute ['Enter' to cancel]: ");\n                string command = "ls";\n                if (command == "") break;\n                string output = exec.RunCommand(command);\n                Console.WriteLine(output);\n            }\n            Console.Write("Disconnecting...");\n            exec.Close();\n            Console.WriteLine("OK");	0
28691886	28690300	Bad characters in output from rss feed	WebClient webClient = null;\nXmlReader xmlReader = null;\n\ntry\n{\n   webClient = new WebClient();\n   webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");\n\n   xmlReader = XmlReader.Create(webClient.OpenRead(url));\n\n   // Read XML here because in a finaly block the response stream and the reader will be closed.\n}\nfinally\n{\n   if (webClient != null)\n   { webClient.Dispose(); }\n\n   if (xmlReader != null)\n   { xmlReader .Dispose(); }\n}	0
27125781	27125406	How to debug Task.Factory	using System;\nusing System.Threading.Tasks;\n\nnamespace Demo\n{\n    public static class Program\n    {\n        [STAThread]\n        private static void Main()\n        {\n            var task = test();\n            Console.WriteLine(task.Result);\n        }\n\n        private static Task<int> test()\n        {\n            return Task<int>.Factory.StartNew(() =>\n            {\n                int x = 10;  // <-- Set a breakpoint here.\n                int y = 5;\n                int z = x/y;\n\n                return z;\n            });\n        }\n    }\n}	0
8036425	8036300	how to Download a single file with multi-Threads in C#	var request = HttpWebRequest.Create(new Uri("http://www.myurl.com/hugefile"));\n\n    request.Method = "GET";\n    request.AddRange(offset_for_this_thread);  // I assume you have calculated this\n                                               // before firing threads\n    Stream reponseStream = request.GetResponse().GetResponseStream();	0
8206853	8206294	Find position of Button/UIElement on screen relative to grid Windows Phone	var transform = button.TransformToVisual(grid);        \nPoint absolutePosition = transform.Transform(new Point(0, 0));	0
6386405	6386354	Retrieving part of a string	string[] textSplit = theWholeTextString.Split(new string[] { "---------------------------------------------------------------------" }, StringSplitOptions.None);\nstring myText = textSplit[2];	0
34167600	22650704	Upload Image to Twitter	using (var stream = new FileStream(imagePath, FileMode.Open))\n            {\n                var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions\n                {\n                    Status = message,\n                    Images = new Dictionary<string, Stream> { { "john", stream } }\n                });\n                lblResult.Text = result.Text.ToString();\n            }	0
8540472	8540204	array passed as parameter to a WCF service to be filled up comes back full of null's	public int GetValues(int connectionId, int readerId, ref values)	0
8816003	8815963	how to get selected item in CheckBoxList in Asp.net	var selectedItems = yourCheckboxList.Items.Cast<ListItem>().Where(x => x.Selected);	0
11270759	11267654	PInvoke C++ function to use in C#	private void DoSomething() \n{ \n\n    string text = "this is a test"; \n    IntPtr ptr = Marshal.StringToHGlobalUni(text); \n\n    uint hr = FOO_Command(ptr, (text.Length + 1) * 2, FOOAPI_COMMAND_CLOSE); \n\n    Marshal.FreeHGlobal(ptr); \n\n}	0
8555803	8547674	passing on KeyValuePair list from backgroundWorker1 to backgroundWorker2	public Form1()\n{\n    InitializeComponent();\n    backgroundWorker1.DoWork += backgroundWorker1_DoWork;\n    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;\n\n    backgroundWorker2.DoWork += backgroundWorker2_DoWork;\n    backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;\n\n    backgroundWorker1.RunWorkerAsync();\n}\n\n\nvoid backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n    e.Result = "a";\n}\n\nvoid backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    string s = (string)e.Result;\n    backgroundWorker2.RunWorkerAsync(s);\n}\n\nvoid backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)\n{\n    e.Result = (string)e.Argument;\n}\n\nvoid backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    Text = (string)e.Result;\n}	0
2260509	2260502	.NET Regular Expressions - Finding, Replace	Match matchResults = null;\ntry {\n    Regex regexObj = new Regex(@"\(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b");\n    matchResults = regexObj.Match(subjectString);\n    if (matchResults.Success) {\n        // matched text: matchResults.Value\n        // match start: matchResults.Index\n        // match length: matchResults.Length\n        // backreference n text: matchResults.Groups[n].Value\n        // backreference n start: matchResults.Groups[n].Index\n        // backreference n length: matchResults.Groups[n].Length\n    } else {\n        // Match attempt failed\n    } \n} catch (ArgumentException ex) {\n    // Syntax error in the regular expression\n}	0
6662250	6661800	Data Access Library: What to return if access isn't allowed or data isn't found?	class DataResult<T>\n{\n   IEnumerable<T> Data;\n   Result ServiceResult;\n}	0
21415077	21414864	XML Tag Prefixes Do Not Add Namespace to the XmlDocument	doc.CreateElement("o:Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")	0
24033573	24033263	Taking certain string characters and returning the string	static void Main(string[] args)\n    {\n        string data = "ABCDABCDABCDABCD";\n\n        Console.WriteLine(StrangeSubstring(data,4, 1));\n        // "AAAA"\n        Console.WriteLine(StrangeSubstring(data,4, 2));\n        // "ABABABAB"\n        Console.WriteLine(StrangeSubstring(data,4, 3));\n        // "ABCABCABCABC"\n    }\n\n    static string StrangeSubstring(string input, int modulo, int length)\n    {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < input.Length; ++i)\n        {\n            if (i % modulo == 0)\n            {\n                for (int j = 0; j<length; ++j)\n                {\n                    if (i+j < input.Length)\n                        sb.Append(input[i+j]);\n                }\n            }\n        }\n        return sb.ToString();\n    }	0
6091231	5040564	What is the best way to retrieve a WindowsIdentity from a ClaimsIdentity	WindowsIdentity winId = S4UClient.UpnLogon(upn);	0
6282048	6281793	Convert linq query expression with multiple froms into extension method syntax	var query = _context.Customer\n  .Where(c => c.Orders.Any(o => o.DateSent == null))\n  .Select(c => new CustomerSummary\n  {\n    Id = c.Id,\n    Username = c.Username,\n    OutstandingOrderCount = c.Orders.Count(o => o.DateSent == null)\n  };	0
12961457	12961380	using Moq to verify a CommandHandler method call with correct Command Parameters	mockCommandHandler.Verify(x => \n   x.Handle(It.Is<RecurringPaymentMarkAsSuccessfulCommand>(c => c.Payment == payment))\n   , Times.Once());	0
34426254	34426193	How to move Items from one list to another by selecting the items in a datagrid	var item = List1[grid1.currentrow.index];\n\nList1.Remove(item);\nList2.Add(item);\n\nGrid1.datasource=list1;\nGrid2.datasource=list2;	0
18385616	18385580	Lambda Expression without Argument	Run(()=>myAction(arg1, arg2));	0
16501527	16501509	Deserializing JSON data to C#	List<QueryResult> qrs = JsonConvert.DeserializeObject<List<QueryResult>>(result);	0
26840606	26840459	How to Generate formatted Alpha Numeric strings in C#	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nvar numbers = "0123456789";\nvar stringChars = new char[5];\nvar random = new Random();\n\nfor (int i = 0; i < 2; i++)\n{\n  stringChars[i] = chars[random.Next(chars.Length)];\n}\nfor (int i = 2; i < stringChars.Length; i++)\n{\n  stringChars[i] = numbers[random.Next(numbers.Length)];\n}\n\nvar finalString = new String(stringChars);	0
19228447	19228393	Most efficient way to read two nodes from multiple XML files?	var query = from file in files\n            let doc = XDocument.Load(file)\n            from customer in doc.Descendants("Customer")\n            select new {\n               Company = (string) customer.Element("Company"),\n               Ship = (string) customer.Element("Ship")\n            };	0
23778913	23778746	Conditional where clause with date parameters raises a has no supported translation to SQL. error in Linq to SQL with C#	var q =\n    from a in dc.GetTable<invoice_in>()\n    join b in dc.GetTable<supplier>()\n        on a.supplier_id equals b.id\n    select a;\n\n//since you compared date_from against null I assume it is Nullable<DateTime>\nif (date_from.HasValue)\n    {\n        q = q.Where(a => a.invoice_date >= date_from.Value);\n    }\n\nvar result = \nq.Select(a => new Invoice_in(a.id, a.amount ?? 0, \n                             a.invoice_number ,\n                             a.supplier_id ?? 0, \n                             a.supplier.s_name,\n                             a.invoice_date ?? System.DateTime.Today))\n .ToList();	0
20123719	20105659	How to write into same xml file from two pages?	XDocument Requestes = XDocument.Load(path_scriprt1);\n                    XElement newElement = new XElement("Single_Request" + Convert.ToString(num),\n                                                        new XElement("numRequest", TxtBlock_numRequest.Text),\n                                                        new XElement("IDWork", TxtBlock_IDWork.Text),\n                                                        new XElement("NumObject", TxtBlock_NumObject.Text),\n                                                        new XElement("lvlPriority", CmbBox_lvlPriority.Text),\n                                                        new XElement("NumIn1Period", TxtBlock_NumIn1Period.Text)\n                                                        );\n                    Requestes.Descendants("Requestes").First().Add(newElement);\n                    Requestes.Save(path_scriprt1);	0
3003706	2990817	What's the correct way to pass parameters from VBScript to COM interface implemented in C#?	public void UseFoo(int x, [MarshalAs(UnmanagedType.IDispatch)] IFoo f) { f.Bar(); }	0
16568394	16567665	Best Way to read specific attributes in XML	var employees = XDocument.Parse(xmlstring) //XDocument.Load(filename)\n                    .Descendants("Record")\n                    .Select(r => new Employee\n                    {\n                        EmployeeId = r.Elements("Item")\n                                      .First(e => e.Attribute("NAME").Value == "EMPLOYEE ID").Value,\n                        EmployeeName = r.Elements("Item")\n                                       .First(e => e.Attribute("NAME").Value == "EMPLOYEE NAME").Value,\n                    })\n                    .ToList();	0
9465456	9465388	only one cell color should be change in row	DataGridViewCell _currentCell = null; // class level variable\n\n... \n\n\n// inside your event, set the current cell back to white\nif(_currentCell != null) _currentCell.Style.BackColor = Color.White;\n\n// now set the current cell to the selected cell\n_currentCell = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex];\n\n_currentCell.Style.BackColor = Color.Red;	0
24820388	24820299	Stop entity framework from creating computed column in db migration	[NotMapped]	0
6291012	6290963	How can i insert data into temporary table by using a dynamic query in MySql	CREATE TEMPORARY TABLE temp_Table SELECT id FROM animals;	0
22456089	22451848	Custom HtmlEncode with HTML entity name, is it possible?	Microsoft.Security.Application.AntiXss.HtmlEncode("?"); \n\nor Microsoft.Security.Application.Encoder.HtmlEncode("?");	0
19464299	19462188	AutoMapper Map Int	[TestMethod]\n        public void Test()\n        {\n            Employee e1 = new Employee { E1 = 7 };\n            Employee e2 = new Employee { E2 = 78 };\n\n            Mapper.CreateMap<Employee, Employee>().ForMember(x => x.E1, x => x.Ignore());\n            var de1 = Mapper.Map<Employee, Employee>(e2, e1);\n\n            //de1.E1 is 7.               \n\n        }	0
27908656	27908630	How to name tuple properties?	public class MyResult\n{\n    public string Nick { get; set; }\n    public string Age { get; set; }\n}	0
5676607	5676546	control if email was already checked in gridview	List<string> lst = new List<string>();\nfor (int i = 0; i < GridView1.Rows.Count; i++)\n{\n    CheckBox ck = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBoxATH");\n    if (ck != null)\n    {\n      Label lblUsrE = (Label)GridView1.Rows[i].Cells[7].FindControl("LabelEmail");\n      string emadr = lblUsrE.Text.ToString();\n      if (ck.Checked == true && !lst.Contains(emadr))\n      {\n        lst.Add(emadr);\n        MailMessage mail = new MailMessage();\n        mail.To.Add(emadr.ToString());\n        ....\n       }\n     }\n}	0
7592964	7592903	How to wait for one task to finish before calling another without blocking?	task1.ContinueWith(t=>Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task2Data, 0, task2Data.Length, null, TaskCreationOptions.AttachedToParent));	0
20215655	20215244	Extract all values between { dynamic } and place in a string array	Regex.Matches(input, @"\{(?<Value>[^{]+)\}").Cast<Match>()\n                 .Select(m=>m.Groups["Value"].Value).ToArray();	0
12217477	12203287	Removing the Drilldown Plus Icon (+) from XtraGrid GridView's MasterRow when ChildRow Has No Data	private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) {\n\n    GridView view = sender as GridView;\n    if(e.Column.VisibleIndex == 0 && view.IsMasterRowEmpty(e.RowHandle))\n        (e.Cell as GridCellInfo).CellButtonRect = Rectangle.Empty;\n    }\n}	0
14069556	14069464	How get list in action from json format?	ko.utils.postJson('@Url.Action("SaveKo", "User")', self.users);	0
2857208	2857183	help me to cheat with numericUpDown1_ValueChanged event	numericupdown1.ValueChanged -= new EventHandler ....\nnumericupdown1.Value = value;\nnumericupdown1.ValueChanged += new EventHandler ....	0
18255998	18255739	How to recognize returning Facebook User using the Facebook Login Widget	User\n  Id (int)    \n  Email (nvarchar(256))\n  FacebookToken (nvarchar(256))\n  GoogleToken (nvarchar(256))	0
3538715	3514823	Using LINQ to SQL group, sum and aggreate all together	Dim query = From st In db.Students _ \n                 Join ori In db.Origami On ori.StudentId Equals st.StudentId _ \n                 Group By key = New With {ori.Student, .MonthYear = (ori.CreationDate.Value.Month & "/" & tr.CreationDate.Value.Year)}  Into TotalOrigami = Sum(ori.NumberOfOrigami) _ \n                 Select key.Student.FirstName,key.Student.LastName,key.MonthYear,TotalOrigami	0
7227651	7227542	Retrieving all rows from sqlce in a single fetch	SqlCeDataAdapter adp = new SqlCeDataAdapter("select mobileNumber from customers where balance > 10000");\nDataSet ds = new DataSet();\nadp.Fill(ds);	0
14051626	14051494	Check all checkboxes in checkboxlist with one click using c#	for (int i = 0; i < checkedListBox1.Items.Count; i++)\n{\n    checkedListBox1.SetItemChecked(i, true);\n}	0
21415929	21415877	Return first XElement in node with greatest number of fields	var res = XDocument.Load(filename)\n                .Descendants("fieldLayout")\n                .OrderByDescending(x => x.Descendants("field").Count())\n                .First();	0
24437645	24436950	Returning data via WCF service	class Point\n{\n    public string Lat {get;set;}\n    public string Lon {get;set}\n}\npublic Point getUsrLocation(string uName)\n{\n    DataClasses1DataContext data = new DataClasses1DataContext();\n    return (from s in data.Users where s.usrName == uName select new Point(){Lat=s.usrLat,Lon=s.usrLong}).Single();\n}	0
13030603	13029782	Adding table rows through For-Loop	bool allFieldsOne = false;\ntable.Rows.Add("0", "0", "0", "0", "0");\nwhile (!allFieldsOne)\n{\n    DataRow lastRow = table.Rows[table.Rows.Count - 1];\n    DataRow currentRow = table.Rows.Add();\n    currentRow[4] = "0";\n    for (int f = 3; f >= 0; f--)\n    {\n        if (lastRow.Field<string>(f) == "0")\n        {\n            currentRow[f] = "1";\n            while (--f >= 0)\n                currentRow[f] = "0";\n            break;\n        }\n        else\n        {\n            currentRow[f] = "1";\n            allFieldsOne = f == 0;\n        }\n    }\n}	0
21496453	21495051	Loop Through Integer Array	foreach(int i in integerarray)\n{\n  if(i==3)\n  {\n   // do your stuf here;\n    break;\n  }\n}	0
33133351	33132292	How to cast an object to a not known generic type?	public static void GetResponse<TDataContract>(Uri uri, Action<TDataContract> callback)\n            where TDataContract : IDataContract, class, new()\n{\n    var contract = new TDataContract();\n    var contractType = contract.GetType();\n\n    var wc = new System.Net.WebClient();\n    wc.OpenReadCompleted += (o, a) =>\n    {\n        if (callback != null)\n        {\n            var ser = new DataContractJsonSerializer(typeof(TDataContract));\n            var obj = ser.ReadObject(a.Result);\n            callback((TDataContract)obj);\n        }\n    };\n\n    wc.OpenReadAsync(uri);\n}	0
3876512	3876456	Find the inner-most exception without using a while loop?	while (e.InnerException != null) e = e.InnerException;	0
1366594	1366584	How do I calculate power-of in C#?	Math.Pow(100.00, 3.00); // 100.00 ^ 3.00	0
3889827	3889816	how to disable "PRINT SCREEN" button while running my Application in WPF?	Print Screen	0
13808139	13805414	Assign a method with default values to Func<> without those parameters?	public void GeneralMethod()\n    {\n        TestMethod(6);\n    }\n\n    public bool TestMethod(int a, int b = 8)\n    {\n        return true;\n    }	0
5644755	5644641	C#: Data Grid View Advanced Operations	dataGridView1.Enabled = false;\ndataGridView1.CurrentCell = null;	0
14494471	14494442	How do I take two integer values from a string then put them back into two separate integers?	//b.Tag =  "0 - 1";    \nstring []arr = b.Tag.ToString().Split('-');    \nint num1 = int.Parse(arr[0].Trim());\nint num2 = int.Parse(arr[1].Trim());	0
33646131	33646022	How to read parts of a file into an object	var p=new Profile();\nusing (StreamReader sr = new StreamReader(filename))\n{\n    while (!sr.EndOfStream)\n    {\n        String line = sr.ReadLine();\n        if (line != null && line.Contains("Student"))\n        {\n            p.studentName=GetLineValue(sr.ReadLine());\n            p.studentLastName=GetLineValue(sr.ReadLine());\n            p.studentUsername=GetLineValue(sr.ReadLine());\n            p.studentPassword=GetLineValue(sr.ReadLine());\n        }\n\n        if (line != null && line.Contains("Teacher"))\n        {\n            p.teacherName=GetLineValue(sr.ReadLine());\n            p.teacherLastName=GetLineValue(sr.ReadLine());\n            p.teacherUsername=GetLineValue(sr.ReadLine());\n            p.teacherPassword=GetLineValue(sr.ReadLine());\n        }\n    }\n}\nprivate string GetLineValue(string line)\n{\n   return line.Substring(line.IndexOf('=')+1);\n}	0
1206659	1206548	Most optimal way to parse querystring within a string in C#	using System.Collections.Specialized;\n\nNameValueCollection query = HttpUtility.ParseQueryString(queryString);\nResponse.Write(query["id"]);	0
7324161	7323982	WPF Method to wait for DocumentCompleted Event	protected ManualResetEvent _resetEvent = new ManualResetEvent(false);\n\n  public void WaitingThread()\n  {\n      _resetEvent.WaitOne();\n\n      // Do stuff after the web browser completes. \n  }\n\n  public void LoadWebPage()\n  {\n      webBrowser.Navigate(new Uri(url));\n      webBrowser.DocumentCompleted = (s, e) => { _resetEvent.Set(); };\n  }	0
3403282	3403247	Dealing with file properties C#	string fileName = "C:\Path\to\file.txt";\nvar fileInfo = new FileInfo(fileName);\n\nConsole.WriteLine("Length = {0} bytes", fileInfo.Length);\nConsole.WriteLine("      or {0} KB", fileInfo.Length / 1024);\nConsole.WriteLine("      or {0} MB", fileInfo.Length / 1024 / 1024);\nConsole.WriteLine("      or {0} GB", fileInfo.Length / 1024 / 1024 / 1024);	0
27945277	27945145	Is there a way to interpret CSV cell splitting symbol in C#?	string[] cells = line.Split(',',';')	0
7382938	7382566	"Clear" window to make room for new user controls?	StackPanel stackPanel = new StackPanel();\n\nstackPanel.Children.Add(new MyUserControl1());\nstackPanel.Children.Add(new MyUserControl2());\n\nthis.Content = stackPanel;	0
28081726	28081672	How can implement an extension method that takes descendants of the base class?	public class ExtentionMethods {\n  public static string ToJson<TContract>(this List<TContract> lst) \n      where TContract : MsgContract\n  {\n     foreach (var item in lst)\n        string entry += item.ToJson();\n\n     return entry;\n  }\n}	0
20789555	20789464	Using an if statement to determine the highest value	int studentcount = 0, i = 0, x = 0, highestScore = 0;\nstring studentname = "", highestScoreStudentName = "";\n\nConsole.WriteLine("Enter how many students there are: ");\n\nstudentcount = Convert.ToInt32(Console.ReadLine());\n{\n    for (i = 1; i <= studentcount; i++)\n    {\n        Console.WriteLine("Enter students name: ");\n        studentname = Convert.ToString(Console.ReadLine());\n        Console.WriteLine("Enter students score: ");\n        x = Convert.ToInt32(Console.ReadLine());\n\n        if (x > highestScore)\n        {\n            highestScore = x;\n            highestScoreStudentName = studentname;\n        }\n    }\n}	0
24756929	24756580	Get memberOf data for a group?	PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ADDomain", "ADContainer");\n        GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, "groupName");\n        PrincipalSearchResult<Principal> groups = grp.GetGroups();	0
24029829	24029706	Sql injection on stored procedure	EXEC sp_ADM_login...	0
11436683	11428662	How to find the SyntaxNode for a method Symbol in a CompilationUnit?	ISymbol.DeclaringSyntaxReferences	0
29133215	29126633	Add attachments in a task using ASANA API in C sharp or VB .Net	using System;\nusing System.Net;\nusing System.Text;\n\nclass AttachFile\n{\n    static void Main ()\n    {\n        Uri uri = new Uri("https://app.asana.com/api/1.0/tasks/<TASK_ID>/attachments");\n        string filePath = @"<FILE_PATH>";\n\n        WebClient client = new WebClient();\n\n        string authInfo = "<API_KEY>" + ":";\n        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));\n        client.Headers["Authorization"] = "Basic " + authInfo;\n\n        client.UploadFile(uri, filePath); \n    }\n}	0
7809437	7809415	Sorting a NameValueCollection by value in c#	var sorted = nvc.OrderBy(kvp => kvp.Value);	0
9631538	9629403	loop to read datagridview columns, even non-visible ones	sb.Clear()	0
1110107	1109902	How to use C# to capture a image of a specific url?	WebBrowser browser = new WebBrowser();\n// this will load up a URL into the web browser:\nbrowser.Navigate(@"http://www.stackoverflow.com");	0
21916194	21916041	Clear data in column	public static FileInfo existingFile =\n    new FileInfo(@"C:\Users\cle1394\Desktop\ExampleExcelFile.xlsx");\n\nusing (ExcelPackage xlPackage = new ExcelPackage(existingFile))\n{\n    ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];\n\n    // clear value\n    worksheet.Cell(iRow, 1).Value = "";\n\n}	0
20327130	20327073	Group a teacher list by School Board and School	var query = teachers.GroupBy(t => new { t.SchoolBoardName, t.SchoolName });\n\nforeach(var schoolGroup in query)\n{\n   Console.WriteLine(schoolGroup.Key.SchoolBoardName);\n   Console.WriteLine(schoolGroup.Key.SchoolName);\n\n   foreach(var teacher in schoolGroup)\n        Console.WriteLine(teacher.TeacherName);\n}	0
8432352	8432179	DropDownList on masterpage - don't want it to update everytime	MyDDL.selectedvalue = session["SelectId"].tostring() OR request.querystring["SelectId"].tostring().	0
27305799	27305116	Project from entity with child collection to flatened collection of dtos	var collection = foos.SelectMany(\n                                l => l.Bar, \n                                (foo, bar) => new FooDto \n                                              { \n                                                  Id = foo.Id, \n                                                  BarName = bar.BarName \n                                              });	0
33959629	33958646	.net Desktop application deployment with database in entity framework	public class BloggingContext : DbContext \n{ \n    public BloggingContext() \n        : base("BloggingCompactDatabase") \n    { \n    } \n}	0
8653857	8653822	Replace all with case Insensitive considering work boundaries in C#	blog = Regex.Replace(blog, "\\b" + wordlist[i] + "\\b", "value to replace", RegexOptions.IgnoreCase);	0
793119	793100	Globally catch exceptions in a WPF application?	Application.DispatcherUnhandledException Event	0
2652840	2652748	How to delete a Dictionary row that is a Double by using an Int?	var filter = dictionary.Where(x => x.Key - rowToEdit < 1).ToArray();\nforeach (var pair in filter)\n{\n    dictionary.Remove(pair.Key);\n}	0
7951291	7950917	Entity Framework 4.1 dynamically retrieve summary for scalar properties from database table column description	Won't fix	0
5829318	5828550	Invoke object method regardless of parameter type	var mem = internalObject.GetType().GetMember(binder.Name);\nif (mem.IsGenericDefinition)\n  mem = mem.MakeGeneric(Array.Convert(args, x => x.GetType()));\nvar result = mem.Invoke(null, internalObject, args);	0
12331840	12310347	Sending custom WCF requests via Sockets	NegotiationConsts.Via via = new NegotiationConsts.Via(uri);\nint arraySize = via.EndpointString.Length + \nNegotiationConsts.DefaultRequestLength;\n\nbyte[] request = new byte[arraySize];\n\nint count = 0;\nrequest[count++] = NegotiationConsts.Version.RECORD_TYPE;\nrequest[count++] = NegotiationConsts.Version.MAJOR_VERSION;\nrequest[count++] = NegotiationConsts.Version.MINOR_VERSION;\n\nrequest[count++] = NegotiationConsts.Mode.RECORD_TYPE;\nrequest[count++] = NegotiationConsts.Mode.DUPLEX;\n\nrequest[count++] = NegotiationConsts.Via.RECORD_TYPE;\nrequest[count++] = via.Length;\nvia.EndpointString.CopyTo(request,count);\ncount+=via.EndpointString.Length;\n\nrequest[count++] = NegotiationConsts.WCFEncoding.RECORD_TYPE;\nrequest[count++] = NegotiationConsts.WCFEncoding.BINARY_ENCODING;\n\nreturn request;	0
21175877	21175782	Replace all string values with another within a project - C#	List<T>	0
18802617	18789217	C# LuaInterface How to get System.String from a Lua string	var output = lua.DoFile(script).First().ToString();\nConsole.WriteLine(output);\nsendQueue.Enqueue(output);	0
21534061	21533998	How to get the list of Enum properties of a class?	if (property.PropertyType.IsEnum)\n    // Celebrate	0
8532333	8532245	Find the North West and South East among bunch of Latitudes and Longitudes	create table #testing (\nResort varchar(20),\nLongitude int,\nLatitude int\n)\n\ninsert into #testing values ('Res 1', 10, 20)\ninsert into #testing values ('Res 2', -12, 30)\ninsert into #testing values ('Res 3', 3, -122)\ninsert into #testing values ('Res 4', 120, 120)\ninsert into #testing values ('Res 5', -2, 230)\ninsert into #testing values ('Res 6', 32, -2)\n\nselect\n    min(Longitude) [Min Longitude],\n    max(Longitude) [Max Longitude],\n    min(Latitude) [Min Latitude],\n    max(Latitude) [Max Latitude],\n    convert(varchar, min(Longitude)) + "," + convert(varchar, max(Latitude)) [NW],\n    convert(varchar, max(Longitude)) + "," + convert(varchar, min(Latitude)) [SE]\n    from #testing\n\ndrop table #testing	0
4409743	4365360	Printing on roll paper	PaperSize pkCustomSize1 = new PaperSize("First custom size", 100, 200);\n\n            printDoc.DefaultPageSettings.PaperSize = pkCustomSize1	0
15088886	15088720	How to show page numbering numerically?	gvData.pagesize=somenumber;\ngvData.pagersettings.Mode=some mode;	0
10560000	10559918	Reading column from local database c#	foreach(DataRow row in MyDataset.Table["TableName"].Rows)\n{\n  yield return row["FieldName"];\n}	0
16384544	16361446	RegEx.Replace is only replacing first occurrence, need all	private string ReplaceBBCode(string inStr)\n{\n    var outStr = inStr;\n    var bbre = new Regex(@"\[(b|i|u)\](.*?)\[/\1\]", RegexOptions.IgnoreCase | RegexOptions.Multiline);\n    while( bbre.IsMatch(outStr))\n        outStr = bbre.Replace(outStr, @"<$1>$2</$1>");\n    outStr = Regex.Replace(outStr, "(\r|\n)+", "<br />");\n    return outStr;\n}	0
1009133	1009019	C# Select unknown item from Multi-dimensional array	IEnumerable<T>	0
26028506	26028464	Match all rows on particular day using LINQ to SQL	// Define your startDate. In our case it would be 9/20/2014 00:00:00\nDateTime startDate = new DateTime(2014,09,20);\n\n// Define your endDate. In our case it would be 9/21/2014 00:00:00\nDateTime endDate = startDate.AddDays(1);\n\n// Get all the rows of SomeTable, whose Time is between startDate and endDate.\nvar query = from t in SomeTable\n            where t.Time>= startDate and t.Time<=endDate\n            select t;	0
26414881	26414834	Type inference in lambdas	List<Project> p = repository.GetOrdered((Project x) => x.Name, 10);	0
3033955	3033925	Is there any extension method which get void returning lambda expression ? 	int[] a = { 1, 23, 4, 5, 3, 3, 232, 32, };\nArray.ForEach(a, x => Console.WriteLine(x));	0
3952627	3931372	special case for update panel	Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_update.Click\n    txt_objectiveSet.Text = "text"\n    pnl_courseFile.Visible = True\n    UpdatePanel1.Update()\nEnd Sub	0
12785916	12785780	SQLite: Insert Into Identity Column	CREATE TABLE [ContentItems] (\n    [Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \n    [Title] TEXT NOT NULL, \n    CONSTRAINT [PK_ContentItems] PRIMARY KEY ([Id])\n )	0
2163058	2162757	how to get parameter names from an expression tree?	Expression<Action<Thing>> exp = o => o.Method(1, 2, 3);\nvar methodInfo = ((MethodCallExpression)exp.Body).Method;\nvar names = methodInfo.GetParameters().Select(pi => pi.Name);	0
12951883	12951409	xpath display data from nodes at different levels	var xDoc = XDocument.Parse(xml); //or XDocument.Load(filename)\nvar books = xDoc.Root.Elements("book")\n            .Select(b => new\n            {\n                Author = b.Element("author").Element("first-name").Value + " " +\n                            b.Element("author").Element("last-name").Value,\n                Books = b.Descendants("book")\n                            .Select(x => new \n                            {\n                                Title = x.Element("title").Value,\n                                Price = (decimal)x.Element("price"),\n                            })\n                            .Concat(new[] { new { Title = b.Element("title").Value, \n                                                Price = (decimal)b.Element("price") } \n                                        })\n                            .ToList()\n\n            })\n            .ToList();	0
1152853	1152784	Capturing KeyDown events in a UserControl	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n{\n    this.OnKeyDown(e);\n}	0
13145155	13144934	DTO property attributes	[DataContract]\npublic class Request\n{\n    [DataMember(Name = "Property 1")]\n    public string Property1 { get; set; }\n}	0
20306735	20306228	Windows Form Application with GMap.NET	gmap.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;\nGMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;\ngmap.SetCurrentPositionByKeywords("Maputo, Mozambique");\ngmap.MinZoom = 1;\ngmap.MaxZoom = 17;\ngmap.Zoom = 5;	0
12411941	12411874	Display a webpage via an iframe	using System;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication10\n{\n    public partial class Form1 : Form\n    {\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        // When the form loads, open this web page.\n        webBrowser1.Navigate("http://www.dotnetperls.com/");\n    }\n\n    private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n    {\n        // While the page has not yet loaded, set the text.\n        this.Text = "Navigating";\n    }\n\n    private void webBrowser1_DocumentCompleted(object sender,\n        WebBrowserDocumentCompletedEventArgs e)\n    {\n        // Better use the e parameter to get the url.\n        // ... This makes the method more generic and reusable.\n        this.Text = e.Url.ToString() + " loaded";\n    }\n    }\n}	0
5469649	5466304	Retrieving large amount of records from Database	void InitQuery(QueryString); // initializes datareader that pulls result out of DB\nYourClass[] GetChunk(int ChunkSize); // puts the next x elements from the reader into array. If it returns null you're done.	0
28970671	28833702	WPF NotifyIcon Crash On First Run - The root Visual of a VisualTarget cannot have a parent	[STAThread]\nstatic void Main()\n{\n    ToolTip tt = new ToolTip();\n    tt.IsOpen = true;\n    tt.IsOpen = false;\n...\n}	0
6239691	6239679	ASPX Control Injected Access	Control control = (Control) placeHolder.FindControl("ControlName");\nObject targetProperty = control.//Target Property ...	0
15789753	15789253	How do I display a tiff image?	var memoryStream = new System.IO.MemoryStream();\nusing (var image = System.Drawing.Image.FromFile("myfile.tif"))\n    image.Save(memoryStream, ImageFormat.Png);\n\nreturn File(memoryStream, "image/png");	0
6794783	6789900	How to assign a same value to entity using LINQ	foreach (var employee in details)\n{\n    var groupCodes = from item in a\n                     where item.EmpID == employee.EmpID\n                     select item.GroupCode;\n\n    // use groupCodes here...\n}	0
12778202	12778031	Best way to implement fluent extension on the enum member	public static T Do<T>(this Enum e) where T : struct\n    {\n        return (T) Convert.ChangeType(e, typeof(T));\n    }	0
27923899	27919976	Serialization/De-serialization of Excel file being passed from Angular client to be stored in directory by WCF	[Route("UploadCFTCFiles")]\n    [HttpPost]\n    public void UploadCftcFiles(HttpRequestMessage request)\n    {\n        Stream stream = new MemoryStream();\n        var task = request.Content.ReadAsByteArrayAsync();\n        task.Wait();\n        var buffer = task.Result;\n        stream.Write(buffer, 0, buffer.Length);\n        _client.UploadCftcFiles(stream);\n    }	0
1002423	1002348	How to build an XDocument with a foreach and LINQ?	var xdoc = new XDocument(\n    new XDeclaration("1.0", "utf-8", null),\n    new XElement("Root",\n        _dataTypes.Select(datatype => new XElement(datatype._pluralCamelNotation,\n            new XElement(datatype._singlarCamelNotation),\n            new XElement("id", "1"),\n            new XElement("whenCreated", "2008-12-31")\n        ))\n    )\n);	0
16509652	16509596	retrieve a second option of a table	using (soforumEntities ctx = new soforumEntities())\n{\n      Article a = ctx.Articles.Where(c => (c.ArticleStatus != null && c.ArticleStatus.HasValue && c.ArticleStatus.Value != true)).OrderBy(x => x.ArticleStatus).Skip(1).Take(1).SingleOrDefault();\n            Console.WriteLine(a.Id + a.Name);\n}	0
3875730	3875695	C# - can binary data be compiled into a module?	Assembly.GetManifestResourceStream	0
2747261	2747182	How do I execute some code in a superclass after all the subclasses have been constructed?	class MyBase\n{\n  // Only if need to do some core initialization\n  public MyBase()\n  {\n  }\n\n  public virtual Initialize()\n  {\n    // do some initialization stuff here\n  }\n}\n\nclass MyDerived : MyBase\n{\n  // Only if need to do some core initialization\n  public MyDerived()\n  {\n  }\n\n  public override Initialize()\n  {\n    // do some initialization stuff here\n\n    // Call the base class initialization function\n    base.Initialize();\n  }\n}	0
811983	811911	Reading XML In Flash From An ASPX Page	public function fileLoaded(event:Event):void{\n     trace('urlLoader.data is ' + urlLoader.data);\n     try{\n          var xmlData:XML = XML(urlLoader.data);\n     } catch (e:Error) {\n          trace('Error creating XML: ' + e);\n     }\n}	0
14890338	14890295	Update label from another thread	private void AggiornaContatore()\n {         \n     if(this.lblCounter.InvokeRequired)\n     {\n         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    \n     }\n     else\n     {\n         this.lblCounter.Text = this.index.ToString(); ;\n     }\n }	0
24097598	21973627	ExecuteSqlCommand on seed to create trigger with EntityFramework throws SqlException	public class ContextInitializer : DropCreateDatabaseAlways<Context> \n{\n     protected override void Seed(Context context)\n     {\n         // Get the file and read the text\n         var execPath = Assembly.GetExecutingAssembly().Location;\n         var createOrderNumPath = Path.Combine(execPath, @"..\SQL\CreateOrderNumber.sql");\n         var sql = File.ReadAllText(createOrderNumPath);\n\n         // Execute the CREATE TRIGGER on the database.\n         // CHANGE emptyparams TO CONTAIN NO ELEMENTS\n         var emptyparams = new SqlParameter[] { };\n         context.Database.ExecuteSqlCommand(sql, emptyparams);\n\n         base.Seed(context);\n     }\n\n}	0
2820072	2820024	Group By store procedure with Linq to Sql	var directclient = ...	0
15551361	15550353	jquery modal not getting selected value from asp drop down list	private void Page_Load()\n{\n    if (!IsPostBack)\n        CancelledDropDownList.DataBind(); // this method will reset the SelectedValue\n}	0
7996373	7660879	How to update the text shown on a status strip's label	MainForm.mainStatusLabel.Text = "Importing data file" //see next line\nApplication.DoEvents()	0
9873083	9828365	cURL call from Console app C#	string url = "https://website.com/events.csv";\n        WebRequest myReq = WebRequest.Create(url);\n\n        string username = "username";\n        string password = "password";\n        string usernamePassword = username + ":" + password;\n        CredentialCache mycache = new CredentialCache();\n        mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));\n        myReq.Credentials = mycache;\n        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));\n\n        WebResponse wr = myReq.GetResponse();\n        Stream receiveStream = wr.GetResponseStream();\n        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);\n        string content = reader.ReadToEnd();\n        Console.WriteLine(content);\n        Console.ReadLine();	0
32452726	32452683	How to fill memory as fast as possible in c#	while (true) Process.Start(Assembly.GetExecutingAssembly().Location);	0
3047872	3047863	How can I use more than one constant for a switch case in C#?	switch( n )\n{\n    case x:\n    case y:\n    case z:\n        DoSomething( );\n        break;\n    case blah:\n        break;\n}	0
25948113	25947758	how can i get the prime numbers (Goldbach's Conjecture in c# windows form application)	bool isprime(int num)\n    {\n        if(num<2)\n        {\n\n            return false;\n\n        }\n        else if(num==2)\n        {\n            return true;\n\n        }\n        else\n        {\n            for(int i=2; i<=num/2;i++)\n            {\n                if(num % i==0)\n                {\n                    return false;\n\n                }\n            }\n            return true;\n        }\n    }	0
19647337	19646945	how to remove duplicate data for group query in Linq	List <bug> bugs = new List<bug>();\n        var lines = System.IO.File.ReadLines(@"/home/bugs");\n        foreach (var line in lines) {\n            string[] items = line.Split('\t');\n            bug bg=new bug();\n            bg.bugid = items[0];\n            bg.list1 = items.Skip(1).OrderBy(f => f).Distinct().ToList();\n            bugs.Add(bg);\n            }	0
6796737	6796659	Fast Re-build C# app under Windows 7	if exist %SYSTEMROOT%\Microsoft.NET\Framework\v3.5 set MSBUILDPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v3.5\n\nif exist %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 set MSBUILDPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\n\nset MSBUILD=%MSBUILDPATH%\msbuild.exe\n\n%MSBUILD% /nologo /m /p:BuildInParallel=true /p:Configuration=Release /p:Platform="Any CPU" "%1.sln"	0
4366708	4366540	How to debug the code in winform	using MFDBAnalyser;\n\nnamespace PrimaryKeyChecker\n{\n    public class PrimaryKeyChecker : IMFDBAnalyserPlugin\n    {\n        public string RunAnalysis(string ConnectionString)\n        {\n            System.Diagnostic.Debugger.Break() \n            return "Srivastava";\n        }\n    }\n}	0
14181151	14181113	How to get the first day and the last day of the current year in c#	int year = DateTime.Now.Year;\nDateTime firstDay = new DateTime(year , 1, 1);\nDateTime lastDay = new DateTime(year , 12, 31);	0
32393527	31989932	Start application to open docx in a comment location	public static void goToBookMark()\n    {\n        Word.Application word = new Word.Application();\n        word.Documents.Open(@"D:\OfficeDev\Word\Edward.docm",true);\n        word.Visible = true;            word.Selection.GoTo(WdGoToItem.wdGoToBookmark,Type.Missing,Type.Missing,"B1");\n    }	0
15799283	4661760	C# equivalent for Java ExecutorService.newSingleThreadExecutor(), or: how to serialize mulithreaded access to a resource	var work = new ConcurrentQueue<Item>();\nvar producer1 = Task.Factory.StartNew(() => {\n    work.Enqueue(item); // or whatever your threads are doing\n});\nvar producer2 = Task.Factory.StartNew(() => {\n    work.Enqueue(item); // etc\n});\nvar consumer = Task.Factory.StartNew(() => {\n    while(running) {\n        Item item = null;\n        work.TryDequeue(out item);\n    }\n});\nTask.WaitAll(producer1, producer2, consumer);	0
5842370	5842339	How to trigger event when a variable's value is changed?	public int MyProperty\n{\n    get { return _myProperty; }\n    set\n    {\n        _myProperty = value;\n        if (_myProperty == 1)\n        {\n            // DO SOMETHING HERE\n        }\n    }\n}	0
9002366	9002206	How to delete a EntityObject, that belongs to a Collection of EntityObjects, from the ObjectContext?	var realList = tempList.ToList();	0
31249180	31248898	How Add-Migration compare current model to find the differences?	Add-Migration	0
8749594	8749507	Excel automation in c# for 2003-2010 version via com interoperability	// work with any version\nType wordType = Type.GetTypeFromProgId( "Word.Application" );\n\ndynamic wordApp = Activator.CreateInstance( wordType );\n\n// late binding + dynamics - always works\nwordApp.Visible = true;	0
4703096	4702626	VSTO Outlook - Contact iteration is SO SLOW!	Microsoft.Office.Interop.Outlook.NameSpace ns = Globals.ThisAddIn.Application.GetNamespace("MAPI");\n  Microsoft.Office.Interop.Outlook.MAPIFolder contactsFld = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts);\n\n  Microsoft.Office.Interop.Outlook.Table tb = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts).GetTable(null, Microsoft.Office.Interop.Outlook.OlItemType.olContactItem);\n\n  tb.Columns.RemoveAll();\n  tb.Columns.Add("Email1Address");\n  tb.Columns.Add("FullName");\n\n  object[,] otb = tb.GetArray(100000) as object[,];\n  int len = otb.GetUpperBound(0);\n\n  for (int i = 0; i < len; i++)\n  {\n    if (otb[i, 0] == null)\n    {\n      continue;\n    }\n    Contacts.Add(new ContactItem() { ContactDisplay = otb[i, 1].ToString(), ContactEmail = otb[i, 0].ToString() });\n\n  }	0
5031543	5031519	Cast nullable bool to bool	IsMaidenNameChecked = AlternateName.IsMaidenName ?? false;	0
22532259	22532044	How to do edit text content keeping it in a CDATA block?	var element = XElement.Parse("<root><![CDATA[pi > 22/7]]></root>");\nvar cdata = (XCData)element.FirstNode;\ncdata.Value = cdata.Value.Replace("> 22/7", "< 22/7");\nelement.Dump();	0
21789101	9822030	Autosize GridViewColumns programmatically by content	var theListView = sender as ListView;\nvar theGridView = theListView.View as GridView;\nforeach (var column in theGridView.Columns)\n{\n    // Set the Width. Then clear it to cause the autosize.\n    column.Width = 1;\n    column.ClearValue(GridViewColumn.WidthProperty);\n}	0
3586746	3522904	Improving a SerialPort Connection	//OnReceive event will only fire when at least 9 bytes are in the buffer.\n    serialPort.ReceivedBytesThreshold = 9; \n    //register the event handlers\n    serialPort.DataReceived += new SerialDataReceivedEventHandler(OnReceive);\n    serialPort.PinChanged += new SerialPinChangedEventHandler(OnPinChanged);	0
29927837	29927078	How to manually run a windows service periodically	using (var sc = new ServiceController("NameOfYourService", "NameOfYourServer"))\n    sc.Start();	0
17581610	17581245	getting content-created-date of an excel file	DSOFile.OleDocumentPropertiesClass oleDocumentPropertiesClass = new DSOFile.OleDocumentPropertiesClass();\noleDocumentPropertiesClass.Open("C:\\My Documents\\MyExcelFile.xls");\nMessageBox.Show(oleDocumentPropertiesClass.SummaryProperties.DateCreated.ToString());	0
6359494	6359458	Creating a label array-Trying it but whats wrong?	Label[] labelxx = new Label[5];\n\n    labelxx[0] = new System.Windows.Forms.Label();\n    labelxx[0].Text = "stuff";\n    labelxx[0].Location = new System.Drawing.Point(250, 250);\n    labelxx[0].ForeColor = Color.White;\n    labelxx[0].BackColor = Color.Yellow;\n    labelxx[0].Size = new System.Drawing.Size(35, 35);\n\n    this.Controls.Add(labelxx[0]);	0
30364504	30364300	Cannot convert string to bool	vars = db.Sales.Select(sl => sl.CustomerRefNbr).ToList();	0
4732284	4732263	how to get selectedvalue from DataGridViewComboBoxColumn?	dataGridView1.Rows["YourRowNumber"].Cells["YourColumnNameOrNumber"].Value;	0
20902458	20902419	Fixing this piece of code to check constraints on a column in formload	com.CommandText = "ALter Table [Veronicas]..[Sales].[Customers] ADD constraint FirstName check (FirstName != 'Farzam' )";	0
16545742	16545318	Regex: how to get words, spaces and punctuation from string	string pattern = @"^(\s+|\d+|\w+|[^\d\s\w])+$";\n        string input = "How was your 7 day - Andrew, Jane?";\n\n        List<string> words = new List<string>();\n\n        Regex regex = new Regex(pattern);\n\n        if (regex.IsMatch(input))\n        {\n            Match match = regex.Match(input);\n\n            foreach (Capture capture in match.Groups[1].Captures)\n                words.Add(capture.Value);\n        }	0
11103338	11103181	A fast way to delete all rows of a datatable at once	string sqlTrunc = "TRUNCATE TABLE " + yourTableName\nSqlCommand cmd = new SqlCommand(sqlTrunc, conn);\ncmd.ExecuteNonQuery();	0
14444190	14444049	Restricting post/pre increment operator over a value rather than a variable, property and indexer	for (int i = 0; i < GetCount() + 1; i++) { }	0
2213283	2213262	Regex to match the first file in a rar archive file set	var regex = new Regex(@"(\.001|\.part0*1\.rar|^((?!part\d*\.rar$).)*\.rar)$", RegexOptions.IgnoreCase | RegexOptions.Singleline);\n    Assert.That(regex.IsMatch("filename.001"));\n    Assert.That(regex.IsMatch("filename.rar"));\n    Assert.That(regex.IsMatch("filename.part1.rar"));\n    Assert.That(regex.IsMatch("filename.part01.rar"));\n    Assert.That(regex.IsMatch("filename.004"), Is.False);\n    Assert.That(regex.IsMatch("filename.057"), Is.False);\n    Assert.That(regex.IsMatch("filename.r67"), Is.False);\n    Assert.That(regex.IsMatch("filename.s89"), Is.False);\n    Assert.That(regex.IsMatch("filename.part2.rar"), Is.False);\n    Assert.That(regex.IsMatch("filename.part04.rar"), Is.False);\n    Assert.That(regex.IsMatch("filename.part11.rar"), Is.False);	0
20797932	20784904	How can I detect ActiveX support?	function IsActiveXSupported() {\n    var isSupported = false;\n\n    if(window.ActiveXObject) {\n        return true;\n    }\n\n    if("ActiveXObject" in window) {\n        return true;\n    }\n\n    try {\n        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");\n        isSupported = true;\n    } catch (e) {\n        if (e.name === "TypeError" || e.name === "Error") {\n            isSupported = true;\n        }\n    }\n\n    return isSupported;\n}	0
31171027	31169333	unable to validate using ajax control	function isNumber(evt) {\n            evt = (evt) ? evt : window.event;\n            var charCode = (evt.which) ? evt.which : evt.keyCode;\n            if (charCode > 31 && (charCode < 48 || charCode > 57)) {\n                return false;\n            }\n            return true;\n        }\n\n        function isAlphabets(evt) {\n            evt = (evt) ? evt : window.event;\n            var charCode = (evt.which) ? evt.which : evt.keyCode;\n            if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))\n                    return true;            \n            return false;	0
13807507	13807429	Running cmd commands with Administrator rights	System.Diagnostics.Process process = new System.Diagnostics.Process();\nSystem.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();\nstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\nstartInfo.FileName = "cmd.exe";\nstartInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";\nprocess.StartInfo = startInfo;\nprocess.Start();	0
17203086	17202895	Add to a table in the c# asp.net using the ASPNETDB.MDF	INSERT INTO BLAH (Fields,,,,) VALUES(Values,,,,,)	0
19872402	19872282	find all links with a specific data attribute and replace the anchor text	string sample = @"<a href=""http://example.com"" style='class' data-foo='' data-special-attr=""new text1"">old text1</a>";\nstring output = Regex.Replace(sample, @"<([^>]+) data-special-attr=""([^""]+)"">[^<]*</a>", "<$1>$2</a>");\n\nConsole.WriteLine(sample);\nConsole.WriteLine(output);	0
5205418	5205358	Caching with Sliding Expiration in ASP.NET Page Methods	System.Web.HttpContext.Current.Cache	0
20612307	20598682	dynamic image in rdlc not appear correctly	ReportViewer1.LocalReport.EnableExternalImages = true;\nReportViewer1.LocalReport.SetParameters(new ReportParameter("image", "file:///" + Server.MapPath("~/images/icon.jpg",true));	0
18935750	18935482	How to change a value of UIElement	((Rectangle)canvas.Children[index]).SetValue(Rectangle.HeightProperty, 15.0);	0
33521669	33518204	How to rotate a local axis of an object to another object?	var rotation = Quaternion.LookRotation(lookPos) * Quaternion.AngleAxis(-90, Vector3.up);	0
11863446	11862890	C#: How to execute a HTTP request using sockets?	var request = "GET /register?id=application/vnd-fullphat.test&title=My%20Test%20App HTTP/1.1\r\n" + \n    "Host: 127.0.0.1\r\n" +\n    "Content-Length: 0\r\n" +\n    "\r\n";	0
25875843	25875642	Rownum in linq to xml	namespace Variatron.Enumerables\n {\n    using System;\n    using System.Collections.Generic;\n\n   public static class SeriesExtensions\n{\n    public static IEnumerable<IEnumerable<T>> SplitToSeries<T>(this IEnumerable<T> source, Int32 seriesSize)\n    {\n        using (var enumerator = source.GetEnumerator())\n        {\n            while (enumerator.MoveNext())\n            {\n                yield return TakeAsSeries(enumerator, seriesSize);\n            }\n        }\n    }\n\n    private static IEnumerable<T> TakeAsSeries<T>(IEnumerator<T> sourceEnumerator, Int32 seriesSize)\n    {\n        var count = 0;\n        do\n        {\n            count += 1;\n\n            yield return sourceEnumerator.Current;\n        }\n        while (count < seriesSize && sourceEnumerator.MoveNext());\n    }\n}	0
6684528	6684191	How do i print a value in my markup from the code behind file	...\nResponse.Redirect ("/_layouts/IrvineCompany.SharePoint.CLM/aspx/Upload.ashx?ProjectApprovalId=" + yourVariableName);\n...	0
13965660	13963379	Is it impossible to cast a string representation of a Page to a Page type?	rootFrame.Navigate(Type.GetType(roamingSettings.Values["CurrentPageType"].ToString()),\n                                roamingSettings.Values["CurrentPageParam"]);	0
11214156	11213923	DataSet used by ReportViewer doesn't use credentials from ConnectionString in App.Config	this.EMPLOYEETableAdapter.Connection.ConnectionString =\n  ConfigurationManager.ConnectionStrings["MCLabor"].ToString();	0
34024237	34024021	C# Reading all nodes inner text under a parent	xml.SelectNodes("root/allnames/*");	0
669883	669336	Restrict LINQ Subquery when databound to a grid	using(NorthwindDataContext db = new NorthwindDataContext()) {\n    var query= from od in db.Order_Details   \n               join o in db.Orders on od.OrderID equals o.OrderID\n               where od.UnitPrice == 14\n               select new {o.OrderId, o.Customer.CustomerName,\n                          od.UnitPrice}; // etc\n\n    ultraGrid1.DataSource = query.Distinct().ToList();\n}	0
12608958	12608776	Can I implement a base GetHashCode() that will work for all extensions of my abstract base class?	public override int GetHashCode()\n{\n    return 1;\n}	0
6127074	6127028	DataTable's Row's First Column to String Array	string[] array = yourTable\n                 .AsEnumerable()\n                 .Select(row => row.Field<string>("ColumnName"))\n                 .ToArray();	0
5076432	5074861	Modifying data with the ListView's EditItemTemplate by programmatically settings its DataSource property and calling its DataBind method	Protected Sub lvList_ItemEditing(sender as Object, e As ListViewEditEventArgs)\n    lvList.EditIndex = e.NewEditIndex\n    lvList.DataSource = SomeData\n    lvList.DataBind()\nEnd Sub	0
24645846	24645587	Returning values from a SQL Server stored procedure?	CREATE PROC usp_MySpecialSP\n  @conditionValue INT, @SPStatus INT OUT\nAS\n  IF EXISTS(SELECT * FROM TableName WHERE column1=conditionValue)\n  BEGIN\n    SELECT @SPStatus=COUNT(*) FROM TableName WHERE column1=conditionValue\n    SELECT Column2, Column3, Column4 FROM TableName WHERE column1=conditionValue\n  END\n  ELSE\n  BEGIN\n    SELECT @SPStatus=0\n  END\nGO	0
7349450	7349345	Array of doubles	int temp = 15;\n\n        string[] titles = new string[] { "Alpha", "Beta", "Gamma", "Delta" };\n        List<double[]> x = new List<double[]>();\n        for (int i = 0; i < titles.Length; i++)\n        {\n            double[] test = new double[15];\n            for (int j = 1; j <= temp; j++)\n            {\n                test[j-1] = j;\n            }\n            x.Add(test);\n        }	0
1471231	1471219	How to write a launching program in C++ or C# for Windows Vista	Process.Start("c:\whatever\somefile.exe", <commandline args>);	0
11449185	11449113	how to add property to dynamic object while it is accessed in C#	public class X : DynamicObject\n{\n    Dictionary<string, object> dictionary = new Dictionary<string, object>();\n\n    public override bool TryGetMember(\n        GetMemberBinder binder, out object result)\n    {\n        string name = binder.Name.ToLower();\n\n        return dictionary.TryGetValue(name, out result);\n    }\n\n    public override bool TrySetMember(SetMemberBinder binder, object value)\n    {\n        dictionary[binder.Name.ToLower()] = value;\n        return true;\n    }\n}\n\n\ndynamic obj = new X();\nobj.SomeProperty = "Test";\nConsole.WriteLine(obj.SomeProperty);	0
7532768	7518931	setting scalar value on collection using introspection	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Object subject = new HasList();\n            Object value = "Woop";\n            PropertyInfo property = subject.GetType().GetProperty("MyList", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);\n            var genericType = typeof (ICollection<>).MakeGenericType(new[] {value.GetType()});\n            if (genericType.IsAssignableFrom(property.PropertyType))\n                genericType.GetMethod("Add").Invoke(property.GetValue(subject, null), new[] { value });\n        }\n    }\n\n    internal class HasList\n    {\n        public List<String> MyList { get; private set; }\n        public HasList()\n        {\n            MyList = new List<string>();\n        }\n    }\n}	0
22783525	22783377	how to change sql query in example?	var result = context.order\n                       .GroupBy(p=>p.title)\n                       .Select(p=> new {title = p.Key, order_number = p.Count()})	0
12286306	12286018	Change the FK column name in EF	modelBuilder.Entity<Product>()\n    .HasOptional(p => p.Category)  // or HasRequired\n    .WithMany()\n    .Map(m => m.MapKey("Cat"));	0
3708182	3707719	XtraGrid. apply filter by enter key	if (e.KeyCode == Keys.Enter)\n{\n// Your filter code.\n}	0
19743363	19743328	How can I include down more than one level in a LINQ expression?	var exam = _examsRepository.GetAll()\n    .Where(e => e.Name == name)\n    .Include(e => e.Objectives)\n    .Include(e => e.Objectives.Select(o => o. ObjectiveDetails))\n    .FirstOrDefault();	0
9745236	9745057	Database First with Bridge Table, How to Keep It Out of Model	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n...\nmodelBuilder.Configurations.Add(new GroupMap());\n...\n}\n\npublic class GroupMap : EntityTypeConfiguration<Group>\n    {\n        public GroupMap()\n        {\n            // Relationships\n            this.HasMany(e => e.Reports)\n              .WithMany(set => set.Groups)\n              .Map(mc =>\n              {\n                  mc.ToTable("groupreporttablename");\n                  mc.MapLeftKey("GroupID");\n                  mc.MapRightKey("ReportID");\n              });\n        }\n    }	0
22053200	22053112	Maximizing console window - C#	using System.Diagnostics;\nusing System.Runtime.InteropServices;\n\n[DllImport("user32.dll")]\npublic static extern bool ShowWindow(System.IntPtr hWnd, int cmdShow);\n\nprivate static void Maximize()\n{\n    Process p = Process.GetCurrentProcess();\n    ShowWindow(p.MainWindowHandle, 3); //SW_MAXIMIZE = 3\n}	0
2644448	2644382	construct hyperlink in wpf C#	TextBlock textBlock = new TextBlock();\nHyperlink link = new Hyperlink();\nlink.Inlines.Add("Click me");\ntextBlock.Inlines.Add(link);	0
3961588	3961369	Inherit from a windows form	Form1 f = new Form1();\n        f.ShowDialog();	0
27526716	27522365	Finding minimum column count from data rows in Excel C#	private int? GetMinimumColumnCount(List <RowEntity> dataRows)\n    {\n        int ? minColumnCount = null;\n\n        for (int i = 0; i < dataRows.Count; i++)\n        {\n            if (minColumnCount == null || minColumnCount > dataRows[i].ColumnValues.Count) \n            {\n                minColumnCount = dataRows[i].ColumnValues.Count; \n            }     \n        }\n        return minColumnCount; \n    }	0
17333397	17332754	How do I write this address of a function from C++ to C#?	public sealed class App : IFrameworkView\n{\n    public virtual void Initialize(CoreApplicationView AppView)\n    {\n        AppView.Activated += new TypedEventHandler <CoreApplicationView, IActivatedEventArgs>(OnActivated);\n    }\n\n    public virtual void SetWindow(CoreWindow Window)\n    {\n    }\n    public virtual void Load(string EntryPoint)\n    {\n    }\n    public virtual void Run()\n    {\n    }\n    public virtual void Uninitialize()\n    {\n    }\n\n    public void OnActivated(CoreApplicationView CoreAppView, IActivatedEventArgs Args)\n    {\n        CoreWindow Window = CoreWindow.GetForCurrentThread();\n        Window.Activate();\n    }\n}	0
29675558	29669746	Kentico media library custom file upload	Content->Media->Security->Media file allowed extensions	0
20014590	19886966	How can I deal with this MEF related ReflectionTypeLoadException exception?	Shell.Core.MappedViewModel1, referenced by the plugins, loaded the ViewModel types. Then, the MEF plugins referenced this project, and during composition, couldn't find the right objects. When I factored View Models out into a separate project, referenced by both	0
536551	536539	How to call MSBuild from C#	Microsoft.Build.Engine	0
11915242	11915173	Execute a Batch File From C#	ProcessStartInfo psi = new ProcessStartInfo(filePath);\npsi.WindowStyle = ProcessWindowStyle.Hidden; \npsi.Arguments = "value1";	0
19265347	19265294	Converting Tif to Jpg takes way too long	foreach (string filePath in Directory.GetFiles(tifPath, "*.tif", SearchOption.AllDirectories))\n{\n    using (var image = System.Drawing.Image.FromFile(filePath))\n    {\n        image.Save(jpgPath + "\\" + Path.GetFileNameWithoutExtension(filePath) + ".jpg", ImageFormat.Jpeg);\n    }\n}	0
25548012	25547940	Linq to Entities filtering out default parameters	var query = ctx.Portal_SurveyRecommendations\n    .Where(c => c.CustNum == insuredNumber);\nif(surveyLocationNumber != -1)\n    query = query.Where(l => l.LocationKey == surveyLocationNumber);\nif(dateIssuedFilter != DateTime.MinValue)\n    query = query.Where(di => di.DateRecIssued == null\n                           || di.DateRecIssued.Value > dateIssuedFilter);\nif(dateCompletedFilter != DateTime.MinValue)\n    query = query.Where(dc => dc.DateRecComplete == null\n                           || dc.DateRecComplete.Value > dateCompletedFilter);\nvar surveys = query.OrderBy(o => o.ReportKey).ThenBy(o => o.RecNumKey).ToList();	0
4212664	4212432	Hide the extra row at the bottom in a DataGridview in a Winform Application	this.dataGridView.AllowUserToAddRows = false;	0
13871317	13871278	Regex matches in Java	Pattern pattern = Pattern.compile(regex);\nMatcher matcher = pattern.matcher(input);\nwhile (matcher.find()) {\n    String match = matcher.group();\n    ...\n}	0
23217308	23212079	Changing connection string from SQL Server to windows authentication	a).Create a SQL Server login for your application's account.\n                 b).Map the login to a database user in the required database.\n                 c). Provide appropriate permissions	0
2174540	2174204	Get a Bound Object from a control	public void MyEvent(Object obj) \n{ \n   Button myButton = (Button) obj; \n   MyBoundClass myObject = myButton.DataContext as MyBoundClass;\n\n   // Do something with myObject. \n}	0
2899005	2898966	Compare Created DateTime to DateTime.Today at 6pm, C#	DateTime created; //get this from wherever\n\nDateTime midnight = DateTime.Today; //DateTime.Today returns today's date at midnight\nDateTime sixpm = midnight.AddHours(18);\n\nif (created >= midnight && created <= sixpm)\n{\n    // created is today and prior to 6pm\n}	0
32967699	32906277	How to use tasks, background threads or another method to solve a hanging issue in Windows Service	IAsyncResult connectResult = this._client.BeginConnectSsl(imapClientSettings.Host, imapClientSettings.Port, null);\n\nif (!connectResult.AsyncWaitHandle.WaitOne(this._connectionTimeout))\n{\n    throw new EmailTimeoutException(this._connectionTimeout);\n}	0
18282998	18282954	Passing parameters into WebBrowserDocumentCompleted	public void TestStuff() \n{\n    string testing = "test";\n    webBrowser2.DocumentCompleted += (s, e) =>\n        {\n            MessageBox.Show(testing);\n        };\n    webBrowser2.Navigate("http://google.com");\n}	0
10344779	10344612	Concurrent Static Queue in C# not keeping my data	static object logAndQueueLock = new object();\npublic static void EnqueueRuleTrigger(Rule rule) \n{ \n    lock(logAndQueueLock)\n    {\n      MyConcurrentQueue._Queue.Enqueue(rule); \n      Log.Message("Enqueued:"+ rule.ToString());\n    } \n} \n\npublic static Rule DequeueRuleTrigger() \n{ \n    lock(logAndQueueLock)\n    {\n      Rule rule = null;\n      if (MyConcurrentQueue._Queue.Enqueue(out rule)){ \n         Log.Message("Enqueued:"+ rule.ToString());\n      }\n      return rule; \n    } \n}	0
2620769	2500191	How to select certain child node in TreeView, C#	private void button2_Click(object sender, EventArgs e)\n    {\n        int grandTotal = CalculateNodes(this.treeView1.Nodes);\n    }\n    private int CalculateNodes(TreeNodeCollection nodes)\n    {\n        int grandTotal = 0;\n        foreach (TreeNode node in nodes)\n        {\n            if (node.Nodes.Count > 0)\n            {\n                int childTotal = CalculateNodes(node.Nodes);\n                node.Text = childTotal.ToString();\n                grandTotal += childTotal;\n            }\n            else\n            {\n                grandTotal += Convert.ToInt32(node.Text);\n            }\n        }\n        return grandTotal;\n    }	0
14876281	14876203	working of linkbutton in repeater	protected void lnkBtnShowDataLabel_Click(Object sender, EventArgs e)\n{\n    lblData.Visible = !lblData.Visible;\n}	0
405154	405140	How to format a Date without using code - Format String Question	DateTime.Now.ToString("ddd dd/MM/yyyy")	0
4286530	4286319	How can I add an unknownn number of dropdownlists programatically to a page and retrieve the selected values with c# on submit	List<DropDownList> ddlList = new List<DropDownList>{};\nfor(int i=0;i<count;i++)\n{\n    //add control to page\n    ddlList.items.add(YourNewlyCreatedDdl);\n}	0
20936417	20936235	C# How to divide the number by equal constant?	List<int> split(int num, int splitBy)\n{\n    List<int> r = new List<int>();\n    int v = Convert.ToInt32(num / splitBy);\n    r.AddRange(Enumerable.Repeat(splitBy, v).ToArray());\n    var remaining = num % splitBy;\n    if (remaining != 0)\n        r.Add(remaining);\n    return r;\n}	0
2870675	2870649	Determine Mouse Button Switch State	MouseButtons.Right	0
3959052	3958997	Setting dateTime.ToString() format centrally	DateTimeFormatInfo format = Thread.CurrentThread.CurrentCulture.DateTimeFormat;\nstring dateTime = DateTime.Now.ToString(format.FullDateTimePattern);	0
5790959	5758049	Working with pointer offsets in C#	int offset = ((int)(((EVENTLOGRECORD)o).StringOffset));\nIntPtr pStrings = IntPtr.Add(pRecord, offset);\nstring sString = Marshal.PtrToStringAuto(pStrings);\nConsole.WriteLine("string : {0}\n", sString);	0
19650582	19650518	How to combine fields in datagridview from Sql field names in c#	cmd = new SqlCommand("SELECT FirstName+' '+MiddleName+' '+LastName as FullName,VCount FROM TableVote WHERE Position='President'", sc);	0
23851381	23851279	adding a textbox dynamically with binding	TextBox t1 = new TextBox();\nt1.text =((YourClass)e.Item.DataItem).YourProperty\np1.Controls.Add(t1);	0
16543494	16543061	How Serialize single value by json.net?	public class StudentJson : Student \n{\n    public bool cheak { get; set; }\n}	0
10612393	10612300	How to get total number of open HTTP connections on a server?	var properties = IPGlobalProperties.GetIPGlobalProperties();\nvar httpConnections = (from connection in properties.GetActiveTcpConnections()\n                       where connection.LocalEndPoint.Port == 80\n                       select connection);	0
27920010	27919762	How to access database from another PC in LAN using C#	ConnectionString="Data Source=192.168.100.199,PortNumber;Initial Catalog=ImageProcessdb;User ID=myUSer;password=myPass;Integrated Security=False;Connect Timeout=30;User Instance=True; providerName="System.Data.SqlClient"	0
11902323	11902261	Get full path of a file stored in sharepint documentlibrary	using (var client = new WebClient())\n{\n    byte[] file = client.DownloadData("http://spstore/sites/appsitename/documentlibraryname/abc.xls");\n    // TODO: do something with the file data\n}	0
4183201	4182942	how to form a 3 digit code after a user enters some value in a textbox asp.net C#	string spclDigit="";\n\nprivate void CompareItems(DataTable dbTable, string value)\n{        \n    for (int j = 0; j < dbTable.Rows.Count; j++)\n    {\n        //In the Below \n        if (dbTable.Rows[j]["ColumnName"].ToString() == value)\n        {\n            string newCorrspndngValue= dbTable.Rows[j]["ColumnName"].ToString();\n            //Generate the 3 Digit No Here.\n            spclDigit=spclDigit +//Add ur logic to Generate the 3 digit number\n        }\n    }\n}	0
26737355	26734891	Include Custom Details While Exporting Rad Grid to Excel	RadGrid1.MasterTableView.Controls.Add(new LiteralControl("<span><br/>Description: Data selected using dates between 1 Jan 2011 to 1 Sep 2011</span>"));\n  RadGrid1.MasterTableView.Caption = "<span><br/>Exported by: John Smith</span>";\n  RadGrid1.ExportSettings.OpenInNewWindow = true;\n  RadGrid1.ExportSettings.ExportOnlyData = false;\n  RadGrid1.MasterTableView.ExportToExcel();	0
13534349	13534252	Get system locale in Windows 8 Metro app	var region = new Windows.Globalization.GeographicRegion();	0
1820307	1820246	How do I get a collection of Session State objects in ASP.NET?	sub session_onStart() \n\n    application.lock() \n    // your logic\n    application.unlock() \n\nend sub \n\nsub session_onEnd() \n\n    application.lock() \n// your logic\n    application.unlock() \n\nend sub	0
27442928	27442147	Assigning FileUpload value to a variable in asp.net	//the filename
\nvar fn = Request.Files[0].FileName;
\n
\n//or save the file to disk
\nRequest.Files[0].SaveAs('c:\somePath');	0
13892741	13892010	Specifying a one-to-many relationship using a different foreign key	[Required]\npublic virtual ICollection<Content> Description { get; set; }	0
6791097	6790956	c# dynamic control name	TextBox tb = new TextBox();\ntb.Name = "DynamicTextbox";\nPanel1.Controls.Add(tb);\n\nTextBox tb = (TextBox)Panel1.Controls["DynamicTextbox"];	0
27653475	26710764	Input string was not in a correct format error in MySQL query	private void UpdateOnline(MySqlConnection mcon, string convertedXml, MemoryStream statment, string fileName, int stmtId)\n    {\n        var convertedStmt = statment.ToArray();\n        var cmd = new MySqlCommand("update user_account_statement set" +\n         " file_name=@fName,statement_file=@stmt, statement_xml=@xml, status='closed' where statement_id=@stmtId", mcon);\n        cmd.Parameters.Add("@fName", MySqlDbType.VarChar);\n        cmd.Parameters.Add("@stmtId", MySqlDbType.UInt32);\n        cmd.Parameters.Add("@xml", MySqlDbType.LongText);\n        cmd.Parameters.Add("@stmt", MySqlDbType.LongBlob);\n        cmd.Parameters["@fName"].Value = fileName;\n        cmd.Parameters["@stmtId"].Value = stmtId;\n        cmd.Parameters["@xml"].Value = convertedXml;\n        cmd.Parameters["@stmt"].Value = convertedStmt;\n        cmd.CommandTimeout = 1000;\n        cmd.ExecuteNonQuery();\n\n    }	0
33190138	33188879	C# Xna achieve a desent scale effect with sprite fonts	var sizeDifference = btnPlay_2.btnRect.Size - btnPlay.btnRect.Size;\nbtnPlay_2.btnRect.Offset(-sizeDifference.X/2, -sizeDifference.Y/2);	0
12306580	11273109	How can I set font for multi lingual text in ms word document in c#?	wordParagraph.Range.Font.NameBi = "B Titr";	0
1034292	1034282	Find highest integer in a Generic List using C#?	int max = MyList.Max();	0
5611740	5611357	trying to highlight words in WebBrowser control	using mshtml;	0
15356312	15356202	Getting date format in C# identical to javascript date function	string.Format("{0:ddd MMM dd yyyy hh:mm:ss \"GMT\"K} ({1})", dt.ToLocalTime(), TimeZoneInfo.Local.StandardName)	0
2163830	2163771	Compare words and get exact match	SqlCommand sqlCmd = new SqlCommand("SELECT Names FROM Machines WHERE Name  Like '%' + @userName", connection);	0
31494470	31494390	Convert date type in c# to match sql server 2008 date type	DateTime date = DateTime.Now;\n\nSqlCommand command = new SqlCommand();\n\ncommand.CommandText = "INSERT INTO table (date) VALUES (@date)";   \ncommand.Parameters.Add("@date",SqlDbType.DateTime).Value = date;	0
14707816	14703514	How to marshal array of bools in C++ to an array of bool in C#	CComSafeArray<VARIANT_BOOL, VT_BOOL> values(3);	0
17974850	17974437	Getting Ptr Value of a Function	[System.Runtime.InteropServices.DllImport("kernel32.dll")]\npublic static extern IntPtr GetProcAddress(IntPtr hModule, string procName);\n\n[System.Runtime.InteropServices.DllImport("kernel32.dll")]\npublic static extern IntPtr GetModuleHandle(string moduleName);\n\n\nvar hModule = GetModuleHandle("kernel32.dll");\nvar procAddress = GetProcAddress(hModule, "GetProcAddress");	0
8391975	8391929	Parallel Programming TPL	Partitioner<T>	0
24574164	24573403	Iterate through a list in sharepoint 2013	using (var ctx = new ClientContext("<site url>"))\n{\n\n    var list = ctx.Web.Lists.GetByTitle("Employee Cars"); //get List by its title\n    var qry = new CamlQuery { ViewXml = "<View><Query><Where><Gt><FieldRef Name='Year_x0020_of_x0020_Production' /><Value Type='Integer'>2005</Value></Gt></Where></Query></View>" };  //construct the query: [Production Year] > 2005, Year_x0020_of_x0020_Production is the internal name for a field \n    var items = list.GetItems(qry);  //get items using the specified query\n    ctx.Load(items); // tell SharePoint to return list items  \n    ctx.ExecuteQuery(); //submit query to the server \n\n    //print results\n    foreach (var item in items)\n    {\n       Console.WriteLine(item.FieldValues["Model"]);\n    }\n }	0
10963859	10953216	How to create and save a serialized and then deserialized entity in EF	var statement = new Statement();\n\nusing (var scope = new TransactionScope())\n{\n    var result = 0;\n    foreach (var statement in arr.Cast<Statement>())\n    {\n        using (var db = new ModelContainer())\n        {\n            db.StatementTypes.Attach(statement.StatementType);\n            db.Entry(statement.StatementType).State = EntityState.Unchanged;\n\n            db.Currencies.Add(statement.Currency);\n            db.Entry(statement.Currency).State = EntityState.Unchanged;\n\n            db.Subjects.Attach(statement.Firm);\n            db.Entry(statement.Firm).State = EntityState.Unchanged;\n\n            db.Statement.Add(statement);\n\n            db.SaveChanges();\n        }\n    }\n    scope.Complete();	0
10097402	10095700	Getting a Leads "Status" from a Leads "Status Reason"	RetrieveAttributeRequest req = new RetrieveAttributeRequest();\nreq.EntityLogicalName = "lead";\nreq.LogicalName = "statuscode";\nreq.RetrieveAsIfPublished = true;\nRetrieveAttributeResponse res = (RetrieveAttributeResponse)yourContext.Execute(req);\n\nStatusAttributeMetadata attribute = (StatusAttributeMetadata)res.AttributeMetadata;\nforeach (StatusOptionMetadata oStatusOptionMetaData in attribute.OptionSet.Options)\n{\n    var state = oStatusOptionMetaData.State.Value;\n    var status = oStatusOptionMetaData.Value.Value;\n}	0
21513289	21513201	Show richTextBox value in MessageBox	string msg = "";\nif ((richTextBox1.Text.Contains("Messagebox "))\n{\n    msg = richTextBox1.Text.Replace("Messagebox ","");\n    MessageBox.Show(msg);\n}	0
2524586	2524568	C# Custom Dictionary Take - Convert Back From IEnumerable	newDict = oldDict.Take(200).ToDictionary(x => x.Key, x => x.Value);	0
7827220	7827183	Adding space to a text box c#	string.replace("|", "    |    ");	0
13429699	13392796	How to read VCard file?	regex = new Regex(@"(?<strElement>(ADR)) (;(?<strAttr>[^\n\r]*))? (:(?<strPo>([^;]*)))  (;(?<strBlock>([^;]*)))  (;(?<strStreet>([^;]*)))  (;(?<strCity>([^;]*))) (;(?<strRegion>([^;]*))) (;(?<strPostcode>([^;]*)))(;(?<strNation>[^\n\r]*))", options);	0
25957700	25957626	How to run Oracle function from C# (vs 2012)	cmd.Parameters.Add("Return_Value", OracleDbType.Int32, ParameterDirection.ReturnValue);	0
24575347	24575047	ASP.Net don't match the Access Date/Time Column	OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dragonfly\\Documents\\Visual Studio 2013\\WebSites\\WebSite2\\App_Data\\calismagunluk.mdb");\nOleDbDataReader oku;\nOleDbCommand sorgu =new OleDbCommand();\nDateTime bugun = DateTime.Now.Date;\nsorgu.CommandText = "select * from calisan where kulID=@ID AND gun=@date";\nsorgu.Parameters.Add("@ID", OleDbType.Integer).Value = susionKulId;\nsorgu.Parameters.Add("@date", OleDbType.DBTimeStamp).Value = bugun;	0
16752406	16752338	Finding 10 characters before a character	string result=string.Empty;\n string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";\n\n    int indexOfStringToSearch = abcd.IndexOf("X");\n    if(indexOfStringToSearch!=-1)\n      { \n        if(indexOfStringToSearch -10 >0)\n            result = abcd.Substring(indexOfStringToSearch-10,10);\n        else\n            result = abcd.Substring(0,indexOfStringToSearch-1);\n     }	0
33954618	33954555	Return data in Json format with object name	return Ok(new { CountryList = list });	0
34567078	34566903	reading data from serial port c#	private void Com_Port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n        char val;\n        try\n        {\n            SerialPort sp = (SerialPort)sender;\n            string data = sp.ReadExisting();\n            val=Your_method_to_process_string(data);\n            label6.Text = Convert.ToString(val);\n        }\n        catch (Exception) { }\n    }	0
16808041	16807955	getting non matched values from two Datatable	DataRow left = table1.Rows[0];\nDataRow right = table2.Rows[0];\n\nIEqualityComparer<DataRow> comparer = DataRowComparer.Default;\nbool bEqual = comparer.Equals(left, right);	0
3409864	1241812	How to move a Windows Form when its FormBorderStyle property is set to None?	/*\nConstants in Windows API\n0x84 = WM_NCHITTEST - Mouse Capture Test\n0x1 = HTCLIENT - Application Client Area\n0x2 = HTCAPTION - Application Title Bar\n\nThis function intercepts all the commands sent to the application. \nIt checks to see of the message is a mouse click in the application. \nIt passes the action to the base action by default. It reassigns \nthe action to the title bar if it occured in the client area\nto allow the drag and move behavior.\n*/\n\nprotected override void WndProc(ref Message m)\n{\n    switch(m.Msg)\n    {\n        case 0x84:\n            base.WndProc(ref m);\n            if ((int)m.Result == 0x1)\n                m.Result = (IntPtr)0x2;\n            return;\n    }\n\n    base.WndProc(ref m);\n}	0
27095500	27095470	multidimensional associative array in C#	var dict = new Dictionary<string, Dictionary<string, object>>();\n\n// Adding a value\ndict.Add("key", new Dictionary<string, object>()\n{\n    { "key1", "value1" },\n    { "key2", "value2" }\n});\n\n// Retrieving value1\nvar result = dict["key"]["key1"];	0
11140279	11139269	Telerik grid date column date off by one day	DateTime date = DateTime.Parse(dbvalue, null, System.Globalization.DateTimeStyles.AdjustToUniversal);	0
9877303	9877218	Calling Monitor.TryEnter without Monitor.Exit at timer elapsed callback shows unexpected behavior	Monitor.Enter	0
25830160	25830020	read yyyy-mm-dd format from XL file	Convert.ToDateTime(dataRow["ServiceDate"]).ToString("yyyy-mm-dd");	0
9167400	9167354	Generic of T for List<T> items	public List<T> GetEntities<T>(OrdinalValue ord)\n{\n    object ret;\n\n    switch(ord)\n    {\n        case OrdinalValue.Career:\n            ret = ByCareer;\n            break;\n        case OrdinalValue.Faculty:\n            ret = ByFaculty;\n            break;\n        case OrdinalValue.Qualification:\n            ret = ByQualification;\n            break;\n        default:\n            throw new ArgumentOutOfRangeException("ord");\n    }\n    return (List<T>) ret;\n}	0
425361	423728	Winform - determine if mouse has left user control	public partial class Form1 : Form {\n    private Timer mTimer;\n    public Form1() {\n      InitializeComponent();\n      mTimer = new Timer();\n      mTimer.Interval = 200;\n      mTimer.Tick += mTimer_Tick;\n      mTimer.Enabled = true;\n    }\n    private void mTimer_Tick(object sender, EventArgs e) {\n      if (!this.DesktopBounds.Contains(Cursor.Position)) this.Close();\n    }\n  }	0
15655523	15655357	Assign random background images to Panel	ImageList images = new ImageList();\nimages.Images.Add(Image.FromFile("C:\\pic1.bmp"));\nimages.Images.Add(Image.FromFile("C:\\pic2.bmp"));\n//Fill with more images\n\n//Make a Random-object\nRandom rand = new Random();\n// This could also be a panel already on the Form\nPanel p = new Panel(); \n\n//Pick a random image from the list\np.BackgroundImage = images.Images[rand.Next(0, images.Images.Count - 1)];	0
27731272	27727751	saving object to IsolatedStorage in windows phone 8	[IgnoreDataMember]	0
16186025	16185961	Find data for latest Inserted date using linq in c#, mysql	var ids = ctx.CommonDatas\n             .Where(c => c.InsertDate == \n                               ctx.CommonDatas\n                                  .Max(c2 => c2.InsertDate)\n                   )\n             .Select(c => c.Id);	0
16721602	16721530	How to ignore source object in Automapper	Mapper.CreateMap<Content, AboutViewModel>();\n Mapper.CreateMap<AboutViewModel, Content>();	0
5475713	5475554	How to sort this?	Year          SortYear  ServiceDescription (or whatever)\n2005          2005.0    Internet Service\n2005          2005.0    Upgraded Cap Limits\nDBNull.Value  2005.5\n2006          2006.0    Internet Service\nDBNull.Value  2006.5\n2007          2007.0    Internet Service\n\n\n\norder by SortYear, ServiceDescription	0
12556036	12555868	Replace a char with a string	// let's pretend this was a char that came to us from somewhere, already as a char...\nchar c = char.Parse("e");\n\n// Here is the string we want to change...\nstring str1 = "Hello World."\n\n// now we'll have to convert the char we have, to a string to perform the replace...\nstring charStr = c.ToString();\n\n// now we can do the replace...\nstring str2 = str1.Replace(charStr,"test");	0
21014328	21014197	How to redirect to mobile page when its mobile or tablet?	Request.Browser["IsMobileDevice"] == "true"	0
7446178	7439189	rebinding a crystal report to a new dataset	foreach(DataTable table in dataSet.Tables){\n        Console.WriteLine(table.TableName);\n    }	0
23360399	23360342	Property with the same name as the subtype name	public enum Status\n{\n     Okay,\n     Wrong,\n     SomethingElse\n};\n\nclass WorkerResult \n{\n    public Status Status {get;set;}\n    public object Data {get;set;}\n}	0
5245019	5244527	How to acess file from another computer in the network	\\machinename\ShareName\filename.txt	0
15624063	15624012	How can I use LINQ to populate a collection inside a class?	foreach (string applicationName in applicationNames)\n {\n _uow.Applications.Add(\n    new Application \n    { \n        Name = applicationName, \n        ModifiedDate = DateTime.Now,\n        TestAccounts = (from  testAccountName in testAccountNames\n                        select new TestAccount\n                        { \n                           Name = testAccountName , \n                           ModifiedDate = DateTime.Now \n                       }).ToList()\n    });\n }	0
3663362	3663080	Consuming WCF Rest 4 From ASP . NET	// User object serialized to XML\nXElement data = new XElement("User",\n  new XElement("UserName", UserName),\n  new XElement("Password", Password)\n);\n\nMemoryStream dataSream = new MemoryStream();\ndata.Save(dataStream);\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(YourServiceUrl);\nrequest.Method = "POST";\nrequest.ContentType = "application/xml";\n// You need to know length and it has to be set before you access request stream\nrequest.ContentLength = dataStream.Length; \n\nusing (Stream requestStream = request.GetRequestStream())\n{\n  dataStream.CopyTo(requestStream);   \n  requestStream.Close();\n} \n\nHttpWebResponse response = request.GetResponse();\nif (response.Status == HttpStatusCode.Unauthorized)\n{\n  ...\n}\nelse\n{\n  ...\n}\nresponse.Close();	0
27480351	27412009	Deserialize JSON to known and unknown types in a class	[Serializable]\npublic class AjaxMsg\n{\n    [DataMember]\n    public string MessageType { get; set; }\n\n    [DataMember]\n    public object MessageData { get; set; }\n}\n\npublic class Data\n{\n    public IList< AjaxMsg> list {get;set;}\n}\n\nvar obj = JsonConvert<Data>(json);	0
11922273	10696185	How to save Image Control Image in Folder in Asp.net	string filepath = img1.ImageUrl;           \nusing (WebClient client = new WebClient())\n{\n       client.DownloadFile(filepath,Server.MapPath("~/Image/apple.jpg"));\n}	0
17628866	17628660	how can I use xbuild to build release binary	xbuild /p:Configuration=Release MySolution.sln	0
18777030	18776796	Return data from related records with Linq to Entities	var query = from a in ctx.People\n            let b = a.EmployeeInfo.FirstOrDefault()\n            orderby a.LastName\n            select new {\n                a.luPersonType.PersonTypeDescription,\n                FullName = a.LastName + ", " + a.FirstName,\n                b.PersonnelNumber,\n                b.StartDate\n            };	0
5673385	5673306	Developing a drawing utility in C#	System.Drawing	0
27464259	27380211	converting Latin characters to Hebrew encoding	Encoding latinEncoding = Encoding.GetEncoding("Windows-1255");\nEncoding hebrewEncoding = Encoding.GetEncoding(862);\nbyte[] latinBytes = latinEncoding.GetBytes(str);\nstring hebrewString = hebrewEncoding.GetString(latinBytes);	0
7877948	7877839	how to add imagebutton in asp.net linkButton?	var linkButton = new LinkButton() {\n  ID = "LinkButton1"\n};\nlinkButton.Controls.Add(new ImageButton() {\n  ID = "ImageButton1",\n  ImageUrl = "~/images/Detail.png"\n});	0
3863053	3862722	Issue opening .aspx page in a new window from inside an ajax modal popup	function openPreview() {\n\n   var recordNo = document.getElementById('<%= lblRecordNo.ClientID %>').innerHTML;\n   var details = document.getElementById('<%= txtQuery.ClientID %>').value;\n   var reason = document.getElementById('<%= ddReason.ClientID %>').value;\n   var fullName= document.getElementById('<%= lblFullName.ClientID %>').innerHTML;\n\n   var url = "emailPreview.aspx?recordNo=" + recordNo + "&details=" + details + "&reason=" + reason + "&fullName=" + fullName;\n\n   window.open(url);\n}	0
9916602	9916485	using Explicit Interface Implementation	public void MethodA(ISample sample)\n{\n  if (sample is SampleA)\n  {\n    string str = ((SampleA)sample).Value.s1;\n  }     \n}	0
21087086	21043165	How to authenticate user via Kentico 7.x API in ASP.NET webpart?	TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);\n\n// Select root at parent\nTreeNode parentNode = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", "en-us");\n\n// Create a new instance of the Tree node\nTreeNode newNode = TreeNode.New("CMS.MenuItem", tree);\n\n// Set the document's properties\nnewNode.DocumentName = "Document name";\nnewNode.DocumentCulture = "en-us";\n\n// Set document type specific fields\nnewNode.SetValue("Field1", "value");\n\n// Insert the document into the content tree\nDocumentHelper.InsertDocument(newNode, parentNode, tree);	0
29268329	29268133	Open a non-static method from one form on the close of another one	private void listaclientes_listbox_DoubleClick(object sender, EventArgs e)\n{\n    EditarCliente ed = new EditarCliente(listaclientes_listbox.SelectedIndex, bib);\n    ed.Closed += (o,e) => { loadlista_clientes(); }\n    ed.Show();\n}	0
16966881	16966731	ArgumentException 'child' is not a child control of this parent	var inputIndex = InputControl.Parent.Controls.GetChildIndex(InputControl);\nvar displayIndex = Display.Parent.Controls.GetChildIndex(Display);	0
24931336	24897299	Cannot change hyperlink style with Word interop without changing the style of the next paragraph	Range r = Paragraph.Range();\nstring headingText = r.Text.Split(' ')[0];\nif (styleString.Contains("Heading"))\n// you shoul probably also tst for an empty paragraph here before inserting anything (I leave it to you)\n{\n    dest = _hyperlinkDestinations.Find(x => x.HyperlinkText == headingText);\n}\n\nif (dest != null)\n{\n    // Move the end of the range one character towards the beginning\n    r.MoveEnd(Word.WdUnits.WdCharacter,-1)\n    Hyperlink link = WordApp.ActiveWindow.Document.Hyperlinks.Add(r, Address: dest.FilePath, SubAddress: dest.bookmarkName, TextToDisplay: r.Text);\n}	0
6088328	6088308	Count the number of characters and words in Array	string s = "My name is ABC XYZ";\n\nint l = s.Length // 18 chars;\nint w = s.Split(' ').Count(); // 5 words	0
5833676	5833178	How to attach an object which is not persisted to an object loaded from DB using NHIbernate	public class Driver\n{\n    private string vehicleTypeName;\n    private IVehicle vehicle;\n\n    public IVehicle Vehicle\n    {\n        get\n        {\n            if (vehicle == null)\n            {\n                vehicle = typeof(IVehicle).Assembly\n                                   .CreateInstance(vehicleTypeName);\n            }\n            return vehicle;\n        }\n    }\n}	0
15019440	15008559	Limit exponent only to specific powers	double exponent = Math.Log10(Math.Abs(val));\n\n        var negcompensator = 0;\n        if (exponent < 0)\n        {\n            negcompensator = -1;\n        }\n        int displayExponent = (int)(Math.Truncate((exponent + negcompensator) / 3)) * 3;\n\n        if (displayExponent==0 || double.IsInfinity(exponent))\n        {\n            return val.ToString("###0.##");\n        }\n        else\n        {\n            var displayValue = (val / Math.Pow(10, displayExponent));\n            return string.Format("{0}e{1}", displayValue, displayExponent);\n        }	0
19559819	19558339	Assign one interface pointer to another interface pointer in C++	QueryInterface()	0
2002490	2002322	How do I save a bitmap as a 16-color grayscale GIF or PNG in ASP.NET?	image.bmp?format=gif&colors=16	0
7826659	7825438	how to convert Dictionary<dynamic, dynamic> to Dictionary<string, string> using Colllection.ToDictionary()	results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName);	0
21159395	21149838	WP7 app that saves user settings	IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n// txtInput is a TextBox defined in XAML.\nif (!settings.Contains(key))\n {\n     settings.Add(key, value);  // adding new value\n     settings.Save();\n }	0
10489136	10488244	Find missing foreign keys	var result = from s in db.tblPersonalRecords\n                         join j in db.tblWorkoutRecords on s.WorkoutRecordID equals j.WorkoutRecordID into PersonalWorkout\n                         from j in PersonalWorkout.DefaultIfEmpty()\n                         where j == null\n                         select new\n                         {\n                             PersonalRecordID = s.PersonalRecordID,\n                             WorkoutRecordIDPR = s.WorkoutRecordID,\n                             WorkoutRecordID = j == null ? 0 : 1\n                         };	0
9818203	9818187	Return an array without creating a variable	return new string[] { "1", "2" };	0
7173647	7173570	convert vb date comparison to c#	_nextContactDate.Date > new DateTime(1900, 1, 1)	0
2628186	2627695	Select TOP 5 * from SomeTable, using Dataview.RowFilter?	public static DataView getLatestFourActive() {\n    DataTable productDataTable = getAll().ToTable();\n    DataTable cloneDataTable = productDataTable.Clone();\n\n    for (int i = 0; i < 4; i++) {\n        cloneDataTable.ImportRow(productDataTable.Rows[i]);\n    }       \n    return new DataView(cloneDataTable);\n}	0
1522271	1522199	How to set the default value of Colors in a custom control in Winforms?	[DefaultValue(...)]	0
26233528	26233333	c# loop on group by key	var solution =\n      finalResult\n      .GroupBy(x => x.Agent);\nforeach (var group in solution)\n        {\n            // group.Key is the agent\n            // All items in group are a sequence of reasons and counts for this agent\n            foreach (var item in group)\n            {\n                // Item has <Agent, Reason, Count> and belongs to the agent from group.Key\n            }\n        }	0
24870009	24869861	Delete query to delete data from multiple tables in sql server and c#	DELETE FROM Products WHERE SubCatId IN (SELECT SubCatID FROM SubCategory WHERE MainCatId = @mainCatId);\nDELETE FROM SubCategory WHERE MainCatId = @mainCatId;\nDELETE FROM MainCategory WHERE MainCatId = @mainCatId;	0
14380817	14281447	Access documents from docset	SPFileCollection docsinproject = properties.ListItem.Folder.Files;\nforeach (SPFile doc in docsinproj) { .... }	0
16828322	16828267	How to run a timer in C# only once?	timer.Tick += (s, e) => \n{ \n  ((System.Windows.Forms.Timer)s).Stop(); //s is the Timer\n  action(); \n};	0
1993083	1988813	Gridview binding to XML	DataSet ds = new DataSet();\nds.ReadXml(MapPath("~/App_Data/mydata.xml"));\nGridView1.DataSource = ds;\nGridView1.DataBind();	0
25630999	25630845	Get a list of duplicate entries in List based on 2 fields using Linq	var duplicates = Persons\n    .GroupBy(key => new { key.Number, key.CompanyId }, a=>a.Name)\n    .Where(y => y.Count() > 1);\n\nvar sb = new StringBuilder();\nforeach (var duplicate in duplicates)\n{\n    sb.AppendLine(String.Format("{0} have been assigned the same Number {1} for Company #{2}",\n                                String.Join(" and ", duplicate), duplicate.Key.Number,\n                                duplicate.Key.CompanyId));\n}\nvar message = sb.ToString();	0
2426414	2426240	Ordering XElements	XDocument xml = System.Xml.Linq.XDocument.Parse(YOUR_XML);\nIEnumerable<XElement> records = xml.Root.Element("RECORDS").Elements();\nIEnumerable<XElement> errors = xml.Root.Element("ERRORS").Elements();\n\nIEnumerable<XElement> elements = from el in records.Concat(errors)\n                                 orderby DateTime.Parse(el.Element("DATETIME").Value)\n                                  select el;\n\nforeach (XElement el in elements)\n{\n    // do something.\n}	0
25610113	25610070	C# implementing abstract class method: I have to make a cast?	public class Parser2 : AbstractParser\n{\n    public override Loop ParseLoop()\n    {\n        return ParseLoopImplementation();\n    }\n\n    private SimpleLoop ParseLoopImplementation()\n    {\n        //not important stuff\n        simpleLoop.simple = ParseLoopImplementation();\n        return simpleLoop;\n\n    }\n}	0
25934485	25933671	Visual Studio Setup Project - one file in two locations	Link file	0
9550283	9550240	Regular expression to replace	Regex.Replace("521;#SouthWest Region", @"\d+;#", "");\n  // results SouthWest Region	0
17389532	17387506	WPF Binding filtered ObservableCollection ICollectionView to Combobox	//create it as static resource and bind your ItemsControl to it\n<CollectionViewSource x:Key="csv" Source="{StaticResource MotionSequenceCollection}" \n                  Filter="CollectionViewSource_Filter">\n    <CollectionViewSource.GroupDescriptions>\n       <PropertyGroupDescription PropertyName="YYY"/>\n    </CollectionViewSource.GroupDescriptions>\n    <CollectionViewSource.SortDescriptions>\n         <scm:SortDescription PropertyName="YYY" Direction="Ascending"/>\n    </CollectionViewSource.SortDescriptions>\n</CollectionViewSource> \n\nprivate void CollectionViewSource_Filter(object sender, FilterEventArgs e)\n{\n    var t = e.Item as ModelBase;\n    if (t != null)\n\n    {\n        //use your filtering logic here\n\n    }\n}	0
16368715	16368215	How to add reference to IRunnableTask	using System.Runtime.InteropServices;\n\nnamespace Your.Namespace\n{\n    [ComImport]\n    [Guid("85788D00-6807-11D0-B810-00C04FD706EC")]\n    interface IRunnableTask\n    {\n        int IsRunning();\n        uint Kill(bool fUnused);\n        uint Resume();\n        uint Run();\n        uint Suspend();\n    }\n\n    class RunnableTaskImpl : IRunnableTask\n    {\n        public int IsRunning() { return 0; }\n        public uint Kill(bool fUnused) { return 0; }\n        public uint Resume() { return 0; }\n        public uint Run() { return 0; }\n        public uint Suspend() { return 0; }\n    } \n}	0
21981307	21970052	RadGrid dynamic columns with FilterTemplate	protected void grid2_ColumnCreated(object sender, GridColumnCreatedEventArgs e)\n    {\n        if (e.Column.UniqueName == "Description")\n        {\n            GridBoundColumn bCol = e.Column as GridBoundColumn;\n            if (bCol != null)\n            {\n                TemplateAutoCompleteFilter template = new TemplateAutoCompleteFilter(\n                                   RadComboBoxFilter.Contains, data.Select(r => r.Name).ToArray());\n                bCol.FilterTemplate = template;\n            }\n        }\n    }	0
33004153	33004143	Parse an IP address string into segments with regular expression in C#	string ip = "100.5.10.15";\nstring[] parts = ip.Split('.');	0
3958118	3958091	C# - Can you loop through types separately in a generic list?	foreach (var bullet in entities.OfType<Bullet>())\n{\n\n}	0
4947612	4947304	Hashtable A equals HashtAble B control	var table1 = new Hashtable {{"A", 1}, {"B", 2}, {"C", 3}};\n        var table2 = new Hashtable {{"B", 2}, {"A", 1}, {"C", 3}};\n\n        bool same = table1.Cast<DictionaryEntry>().Union(table2.Cast<DictionaryEntry>()).Count() == table1.Count;\n\n        Console.WriteLine("Same = " + same);	0
3582749	3530656	iTextsharp - PDF file size after inserting image	PdfWriter writer = PdfWriter.GetInstance(doc, ms);\nPdfContentByte contentPlacer;\n\nwriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);\n\nwriter.CompressionLevel = PdfStream.BEST_COMPRESSION;	0
27750827	27750808	Get IP-address of HTTP client	protected void GetUser_IP()\n{\n    string VisitorsIPAddr = string.Empty;\n    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)\n    {\n        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();\n    }\n    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)\n    {\n        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;\n    }\n    uip.Text = "Your IP is: " + VisitorsIPAddr;\n}	0
1202353	1202348	How do you give a namespace an alias in C#	using Station = Foo.Bar.Space.Station.Bar;	0
18288219	18287028	LINQ: How to convert from ISingleResult<T> to IQueryable<int>	subclasses.Select(a=>a.Subject).AsQueryable();	0
10705533	10705484	how to run multiple LINQ queries on the same datafile	var list = reader.ToList();\n\n// Now run multiple queries over list	0
22354517	22296636	How to write to file in VSS from c# code?	using SourceSafeTypeLib;\n VSSDatabaseClass vssDatabase = new VSSDatabaseClass();\n vssDatabase.Open("VSS database path", "userName", "password");\n VSSItem item = vssDatabase.get_VSSItem("file path as shown in vss", false);\n item.Checkout("Comments", item.LocalSpec, 0);\n using (StreamWriter sw = File.AppendText(lblSourceFile.Text))\n {\n     sw.WriteLine("text");\n }\n item.Checkin("Comments", item.LocalSpec, 0);\n vssDatabase.Close();	0
3911587	3911550	Withou using dynamic keyword, can we do type casting based on generic type parameters?	static class Utility<T, TReturn> {\n        public static TReturn Change(T arg) {\n            return (TReturn)Convert.ChangeType(arg, typeof(TReturn));\n        }\n    }	0
17867449	17867360	Programmatically add and edit controls	StackPanel panel = new StackPanel();\npanel.Children.Add(txt1);\npanel.Children.Add(txt2);\n\nvar tabItem = new TabItem { Header = panel };	0
10147781	10147718	Given a absolute bit number (ex. 24), how do I set the appropriate bit in an array of words?	int N = 24;\nint index = N / 16;\nint bit = N % 16;\n\nwords[index] |= (1 << bit);	0
2735849	2735299	Finding a pattern within a string variable	static string HeadsOrTails()\n    {\n        string guessHistory = String.Empty;\n        // Guess heads or tails 5 times\n        Random random = new Random();\n        for (int currentGuess = 0; currentGuess < 5; currentGuess++)\n        {\n            if (random.Next(2) == 0)\n                guessHistory += 'H';\n            else\n                guessHistory += 'T';\n        }\n        // Analyse pattern of guesses\n        if (guessHistory.Substring(0, 4) == "HHTT" || guessHistory.Substring(1, 4) == "HHTT")\n        {\n            // If guess history contains HHTT then make the 6th guess = H\n            guessHistory += 'H';\n        }\n\n        return guessHistory;\n    }	0
9292200	9292014	display timespan nicely	public static string PrintTimeSpan(int secs)\n{\n   TimeSpan t = TimeSpan.FromSeconds(secs);\n   string answer;\n   if (t.TotalMinutes < 1.0)\n   {\n     answer = String.Format("{0}s", t.Seconds);\n   }\n   else if (t.TotalHours < 1.0)\n   {\n     answer = String.Format("{0}m:{1:D2}s", t.Minutes, t.Seconds);\n   }\n   else // more than 1 hour\n   {\n     answer = String.Format("{0}h:{1:D2}m:{2:D2}s", (int)t.TotalHours, t.Minutes, t.Seconds);\n   }\n\n   return answer;\n}	0
980225	980202	How do I find the current executable filename?	System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName	0
4760543	4760465	How can I access a ButtonFields text, if it's not considered as a TableCell?	protected void myGridView_DataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        // You may have to play with the index of the control\n        // I have found that often a GridView will place a \n        // Literal control as Control[0] and the LinkButton\n        // as Control[1]. Once you find the index, it won't\n        // change.\n        LinkButton btn = (LinkButton)e.Row.Cells[0].Controls[1];\n        string text = btn.Text;\n    }\n}	0
670844	670819	get directory from full path	DirectoryInfo info = new DirectoryInfo(sourceDirectory_);\nstring currentDirectoryName = info.Name;	0
11786012	11785840	how to give values from xml file to datagridviewtextbox in C#?	XElement root = XElement.Load(file);\nvar tables = root.Descendants("Table1")\n                 .Select(t => new\n                 {\n                     Server = t.Element("Server").Value,\n                     Database = t.Element("Database").Value\n                 });\n\nforeach(var table in tables)\n    grid.Rows.Add(new object[] { table.Server, table.Database });	0
835734	835649	How should I convert a number with a text suffix to an integer in c#?	using System;\n\nclass Test\n{\n    static void Main()\n    {\n        Console.WriteLine(ParseLeadingInt32("-1234AMP"));\n        Console.WriteLine(ParseLeadingInt32("+1234AMP"));\n        Console.WriteLine(ParseLeadingInt32("1234AMP"));\n        Console.WriteLine(ParseLeadingInt32("-1234"));\n        Console.WriteLine(ParseLeadingInt32("+1234"));\n        Console.WriteLine(ParseLeadingInt32("1234"));\n   }\n\n    static int ParseLeadingInt32(string text)\n    {\n        // Declared before loop because we need the\n        // final value\n        int i;\n        for (i=0; i < text.Length; i++)\n        {\n            char c = text[i];\n            if (i==0 && (c=='-' || c=='+'))\n            {\n                continue;\n            }\n            if (char.IsDigit(c))\n            {\n                continue;\n            }\n            break;\n        }\n        return int.Parse(text.Substring(0, i));\n    }\n}	0
3204415	3121388	Creating an Entity Data Model from an Empty model	DataTable dt = new DataTable();\n\nusing (iDB2DataAdapter da = new iDB2DataAdapter(cmd))\n{\n    da.Fill(dt);\n}\n\nvar MyObjects = from i in dt.AsEnumerable() select new MyObject() \n    { \n         field1 = i.Field<string>("field1"), \n         field2 = i.Field<decimal>("field2")\n    };\nList<MyObject> temp = MyObjects.ToList();\nreturn temp;	0
17921540	17881358	Get value from Gridview for update	protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)\n  {    \n    GridViewRow row = TaskGridView.Rows[e.RowIndex];\n    String str = ((TextBox)(row.Cells[2].Controls[0])).Text;\n  }	0
7743735	7743697	how to split the string to get date only	a.Substring(7,10)	0
33269907	33269787	Reflection to find classes that implement interface with multiple open generic parameters	var concretes =\n    Assembly\n    .GetAssembly(typeof (Concrete))\n    .GetTypes()\n    .Where(t =>\n        t.GetInterfaces()\n        .Any(i =>\n            i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ITest<,>)))\n    .ToList();	0
4390749	4381672	Use variable from an instance of a class in a converter?	public static class Globals\n{\n    public static MainWindow MainWindow;\n}\n\npublic partial class MainWindow : Window\n{\n    public bool Adam = true;\n\n    public MainWindow()\n    {\n        Globals.MainWindow = this;\n        InitializeComponent();\n    }\n\n    public class NextEnabled : IValueConverter\n    {\n        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n        {\n            return Globals.MainWindow;\n        }\n\n        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n        {\n            return true;\n        }\n    }\n}	0
23664337	23664296	JQuery to hide a button by default	+ "\n    $(\"#" + lnkAdd.ClientID + "\").hide(); "	0
26295937	26292773	Change dicom Transfer Syntax showing no registered codec using mDCM	Dicom.Codec.Jpeg2000.DcmJpeg2000Codec.Register();	0
15425360	15424121	XML deserialize: different xml schema maps to the same C# class	[XmlRoot("customers")]\npublic class CustomerList {\n    [XmlElement("customer")]\n    public Customer[] Customers { get; set; }\n}\n\npublic class Customer {\n    private String _id;\n\n    [XmlElement("name")]\n    public String Name {get; set;}\n\n    [XmlElement("id")]\n    public String Id {get{return _id;} set{_id = value;}}\n\n    [XmlElement("code")]\n    public String Code {get{return _id;} set{_id = value;}}\n}	0
2060501	2060160	How to configure an ObjectDataSource to select rows from a ListView	var data = listView1.Items.Where(i=> i.selected == true);\n\nviewlist2.DataSource = data;\nviewlist2.DataBind();	0
16991544	16991390	How can i add ffmpeg.exe file to my project but two files one for 32bit and one for 64bit?	System.Environment.Is64BitOperatingSystem	0
383596	383587	How do you do *integer* exponentiation in C#?	int IntPow(int x, uint pow)\n{\n    int ret = 1;\n    while ( pow != 0 )\n    {\n        if ( (pow & 1) == 1 )\n            ret *= x;\n        x *= x;\n        pow >>= 1;\n    }\n    return ret;\n}	0
26314788	26314609	How to avoid multiple messageboxes continuous display?	// message box flag.\nbool canIShowMessageBox = true;\n\n// for thread lock.\nobject exLocker = new object();    \n\nvoid cc(object sender, UnhandledExceptionEventArgs e)\n{\n   lock(exLocker)\n   {\n      if (canIShowMessageBox)\n         canIShowMessageBox = false;\n      else\n         return;\n   }\n   Exception ex = e.ExceptionObject as Exception;\n   MessageBox.Show(ex.Message, "Uncaught", MessageBoxButton.OK);\n\n   lock(exLocker)\n      canIShowMessageBox = true;\n}	0
12862128	12839770	Asp.net chart multi-series showing wrong data	var allXvalues = queryResult.select(r=>r.CTB_MONTH).Distinct().OrderBy(month=>month).ToList();\n\n\nallXvalues\n  .ForEach\n   (\n    xvalue=>\n      {\n        var p = approved.Where(o=>o.MONTH==xValue).FirstOrDefault();\n        if(p==null)\n            grafico.Series[0].Points.Add(new DataPoint(p.MONTH,p.AMT_C));\n        else\n            grafico.Series[0].Points.Add(new DataPoint(xvalue,0){IsEmpty=true});\n      }\n   );	0
25446915	25446454	How to make a PictureBox scrollable?	Panel MyPanel = new Panel();\nPictureBox pictureBox1 = new PictureBox();\n\nImage image = Image.FromFile("image.png");\n\npictureBox1.Image = image;\npictureBox1.Height = image.Height;\npictureBox1.Width = image.Width;\n\nMyPanel.Controls.Add(pictureBox1);\nMyPanel.AutoScroll = true;\nthis.Controls.Add(MyPanel);	0
6132326	6132252	How to save a bitmap after setting interpolation with graphics class	using (var medBitmap = new Bitmap(fullSizeImage, newImageW, newImageH))\n{\n  using (var g = Graphics.FromImage(medBitmap))\n  {\n    g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n    g.DrawImage(medBitmap, 0, 0);\n  }\n  medBitmap.Save(HttpContext.Current.Server.MapPath("~/Media/Items/Images/" + itemId + ".jpg"), ImageFormat.Jpeg);\n}	0
29240881	29239800	How can I connect to a Linux hosted database via a Windows Form C# Application?	/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT	0
7638807	7638726	Optimal Entity Framework 4 query for a simple data model and many-to-many relationships	var query = from ev in context.Events\n            select new\n            {\n              Event = ev,\n              AffectedCustomers = (from pr in ev.Products\n                                   from cu in pr.Customers\n                                   select cu).Distinct()\n            };	0
20055411	20054897	LateBinding - how to use it?	public static IEnumerable<Type> GetSubclassesForType(Type baseClassType)\n{\n    List<Type> types = new List<Type>();\n    foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())\n    {\n       types.AddRange(ass.GetTypes().Where(type => type.IsSubclassOf(baseClassType)));\n    }\n    return types;\n}\n\npublic static IEnumerable<Type> GetSubclassesForType(Assembly assembly, Type baseClassType)\n{\n    return from type in assembly.GetTypes() \n                        where type.IsSubclassOf(baseClassType)    \n                        select type;\n}	0
12360398	12360219	How to select all script nodes containing a specific string	System.Xml.XmlNamespaceManager xmlnsManager =\n                 new System.Xml.XmlNamespaceManager(xmldoc.NameTable);\n\nxmlnsManager.AddNamespace("h", "http://www.w3.org/1999/xhtml", xmlnsManager);\n\nresult = xmldoc.SelectNodes('//h:script[contains(., 'blah')]')	0
3409079	3409054	How to raise only 1 Timer event in C#?	private void timerHandler(object sender, TimerElapsedEventArgs e)\n{\n    Timer timer = (Timer)sender;\n    timer.Stop();\n    RunProcess();\n    timer.Start();\n}\n\npublic void RunProcess()\n{\n    /* Do stuff that takes longer than my timer interval */\n}	0
26256139	26255604	Take snapshot of video	ffmpeg.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/ffmpeg.exe");	0
3488178	3487949	calculate centre of batch of locations	var center = new Location\n             {\n                 Latitude = list.Average(loc => loc.Latitude),\n                 Longitude = list.Average(loc => loc.Longitude)\n             };	0
315851	307013	How do I filter all HTML tags except a certain whitelist?	static string SanitizeHtml(string html)\n{\n    string acceptable = "script|link|title";\n    string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>";\n    return Regex.Replace(html, stringPattern, "sausage");\n}	0
6586477	6586432	how to convert ListItemCollection (dropdownlist.items) to a dictionary<string,string>?	collection.Cast<ListItem>().ToDictionary(i => i.Value, i => i.Text);	0
22049905	22049789	How can I use entity framework to get a count of database tables?	var metadata = ((IObjectContextAdapter)db).ObjectContext.MetadataWorkspace;\n\n    var tables = metadata.GetItemCollection(DataSpace.SSpace)\n      .GetItems<EntityContainer>()\n      .Single()\n      .BaseEntitySets\n      .OfType<EntitySet>()\n      .Where(s => !s.MetadataProperties.Contains("Type") \n        || s.MetadataProperties["Type"].ToString() == "Tables");	0
11151251	11151153	change numeric base of negative numbers	int i = -12345;\nstring test = i.ToString("X"); // test will hold: "FFFFCFC7"\nint HexI = Convert.ToInt32(test, 16); // HexI will hold: -12345	0
2300487	2298637	Read typed objects from XML using known XSD	var el_date = (XmlElement)el_root.SelectSingleNode("./DateVal");\n     //WANTED: el_date.Value = 2010-02-18 01:02:03 (as a DateTime Object)\n     var val_date = XmlConvert.ToDateTime(el_date.InnerText);\n     //ACTUAL: el_date.InnerText="2010-02-18T01:02:03"\n\n     var el_duration = (XmlElement)el_root.SelectSingleNode("./TimeVal");\n     //WANTED: el_date.Value = 10 hours, 5 minutes, 3 seconds (as a TimeSpan Object)\n     var val_duration = XmlConvert.ToTimeSpan(el_duration.InnerText);\n     //ACTUAL: el_date.InnerText="PT10H5M3S"	0
8586685	8586614	How to select the data from datatable which not in an IEnumerable	var result = dbcrs.Where(item => res.FirstOrDefault(resItem => resItem.Id == item.Id) == null);	0
10296454	10296420	navigating from one xaml page to another xaml page in silverlight 4?	this.NavigationService.Navigate(new Uri("SelectionPage.xaml", UriKind.Relative));	0
1033463	1033455	Converting a string to an enum in C#	object Enum.Parse(System.Type enumType, string value, bool ignoreCase);\n\nenum TEST_ENUM\n{\n  VALUE1,\n  VALUE2\n}\n\n// To convert from a string to a enum just do the following\nstring sTestEnum = "VALUE2";\n\nTEST_ENUM eDatabase = (TEST_ENUM)(Enum.Parse(typeof(TEST_ENUM), sTestEnum, true));	0
23362835	23362649	How can I add up all the values in a listbox?	decimal total = (from item in listbox.Items.Cast<ListItem>() select Convert.ToDecimal(item.Value)).Sum();	0
20871856	20871776	how to define a connection string using an app.config file in C#	SqlConnection conn = new SqlConnection(\n      ConfigurationManager.ConnectionStrings[\n         "ticketNotification.Properties.Settings.ticketsConnectionString"]\n             .ConnectionString);	0
16856852	16856338	How to Deserialize specific JSON string	string json = @"[""SomeName"",[[""alpha"",""bravo""],[1,6]],[[""John"",""Bob"",""Paul"",""Ringo""],[1,2,1,8]]]";\nvar arr = JArray.Parse(json);\n\nstring name = (string)arr.OfType<JValue>().First();\nvar arrays = arr.OfType<JArray>()\n                .Select(x => x.Select(y=>y.Select(z=>(string)z)\n                                           .ToList())\n                               .ToList())\n                .ToList();	0
16178533	16178429	Understanding Enums - using as constants	public static class MyClass\n{\n    public const string PROD = "PROD";\n    public const string DEV = "DEV";\n}\n\n// elsewhere...\nla.type == MyClass.PROD;	0
5999885	5997683	Loading WPF Image control from byte array	System.IO.File.ReadAllBytes(filepath)	0
25275835	25274096	How to answer a request but continue processing code in WebApi	HostingEnvironment.QueueBackgroundWorkItem	0
24490537	24490456	Exit while loop of mouseDown event	private void Form1_MouseDown(object sender, MouseEventArgs e)\n    {\n        mouseDown = true;\n    }\n\n    private void Form1_MouseUp(object sender, MouseEventArgs e)\n    {\n        mouseDown = false;\n    }\n\n    private void Form1_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (mouseDown)\n        {\n            mouseX = MousePosition.X - 20;\n            mouseY = MousePosition.Y - 40;\n            this.SetDesktopLocation(mouseX, mouseY);\n\n        }\n    }	0
15703356	15701725	How to change the order of columns TableLayoutPanel c#	Control ctr1 = tableLayoutPanel1.GetControlFromPosition(0, 0);\nControl ctr2 = tableLayoutPanel1.GetControlFromPosition(1, 1);\n\ntableLayoutPanel1.SetCellPosition(ctr1, new TableLayoutPanelCellPosition(1, 1));\ntableLayoutPanel1.SetCellPosition(ctr2, new TableLayoutPanelCellPosition(0, 0));	0
12612661	12612514	File upload button with inconsistant behavior	mWebView2.setWebChromeClient(new WebChromeClient()  \n{  \n    //The undocumented magic method override  \n    //Eclipse will swear at you if you try to put @Override here  \n    public void openFileChooser(ValueCallback<Uri> uploadMsg) {  \n\n    mUploadMessage = uploadMsg;  \n    Intent i = new Intent(Intent.ACTION_GET_CONTENT);  \n    i.addCategory(Intent.CATEGORY_OPENABLE);  \n    i.setType("image/*");  \n    MyAwesomeActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);       \n    }  \n});	0
5759757	5759424	C# Gray out a control and draw another on it	Button.DrawToBitmap(Bitmap, Rectangle)	0
17286906	17286789	Serial Port Trigger DataReceived when certain amounts of bytes received	private byte[] rxbyte = new byte[8];\nprivate int rxcount = 0;\n\nprivate void port_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n    rxcount += port.Read(rxbyte, rxcount, 8 - rxcount);\n    if (rxcount < 8) return;\n    rxcount = 0;\n    // Process rxbyte content\n    //...\n}	0
23255573	23255328	Create Datatable from a list of column values	private static void Main(string[] args)\n{\n    var list1 = new List<int>(new[] { 1, 2, 3, 4, 5 });\n    var list2 = new List<string>(new[] { "foo1", "foo2", "foo3", "foo4", "foo5" });\n    var list3 = new List<bool>(new[] {true, false, true, true, false});\n\n    var dt = MakeDataTable(list1, list2, list3);\n\n    Console.ReadLine();\n\n}\n\nprivate static DataTable MakeDataTable(params IEnumerable[] lists)\n{\n    var dt = new DataTable();\n    for (var i = 0; i < lists.Length; i++)\n    {\n        dt.Columns.Add("column" + i);\n    }\n    foreach (var data in CombineList(lists))\n    {\n        dt.Rows.Add(data);\n    }\n\n    return dt;\n}\n\nprivate static IEnumerable<object[]> CombineList(params IEnumerable[] lists)\n{\n    var enumerators = lists.Select(l=>l.GetEnumerator()).ToArray();\n    while (enumerators.All(e => e.MoveNext()))\n    {\n       yield return enumerators.Select(e => e.Current).ToArray();\n    }\n}	0
4325173	4325098	How do I change a ListView dynamically on DataBound?	protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)\n{\n    Label EmailAddressLabel;\n    if (e.Item.ItemType == ListViewItemType.DataItem)\n    {\n        // Display the e-mail address in italics.\n        EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");\n        EmailAddressLabel.Font.Italic = true;\n\n        System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;\n        string currentEmailAddress = rowView["EmailAddress"].ToString();\n        if (currentEmailAddress == "orlando0@adventure-works.com")\n        {\n            EmailAddressLabel.Font.Bold = true;\n        }\n    }\n}	0
31788097	31785290	splitting string and save to xml	XElement ipaddresses = new XElement("ipaddresses");\nstring[] lines = IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);\nforeach (var item in lines) \n{  \n    ipaddresses.Add(new XElement("ipaddress", item));\n}\n\nsettings.Add(ipaddresses);	0
15404993	15175029	Inconsistent behavior in Automapper	public class Gallery : Entity\n{\n    public virtual IList<UIItem> GalleryItems { get; set; }\n}\n\npublic class UIItem : Entity\n{\n    public virtual Gallery Gallery { get; set; }\n}	0
26079356	26078032	How to access labels from loop and change their text	Label[] l = new Label[6];\nint x = 20;\nfor (int i = 0; i < l.Length; i++)\n{\n    l[i] = new Label();\n    l[i].Name = "Hello " + i.ToString();\n    l[i].Text = "Hello " + i.ToString();\n    l[i].Location = new Point(x, 10);\n    x += 100;\n}	0
4260541	4259850	Loop through all controls on asp.net webpage	public void FindTheControls(List<Control> foundSofar, Control parent) \n        {\n\n            foreach(var c in parent.Controls) \n            {\n                  if(c is IControl) //Or whatever that is you checking for \n                  {\n\n                      foundSofar.Add(c);\n\n                      if(c.Controls.Count > 0) \n                      {\n                            this.FindTheControls(foundSofar, c);\n                      }\n                  }\n\n\n            }  \n\n        }	0
14479563	14479548	How to get SelectedValue of DropdownList without postback or updatepanel	AutoPostBack=True	0
16403975	16403768	how to get a database datetime value as a date only?	SelectCommand="SELECT [TripId] FROM [BookingMaster] \n              WHERE ( (cast([PickupDateTime] as date) = @PickupDateTime or @PickupDateTime is null))"	0
22230102	22111537	An algorithm for a number divisible to n	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace main\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine("Enter your number");\n        Int64 x = Convert.ToInt64(Console.ReadLine());\n        Int64 y, j, i, k, z = x;\n        x = x + 5;\n    loop:\n        x++;\n        for (i = 0, y = x; y != 0; i++)\n            y /= 10;\n\n        for (j = x, k = i; k != 0; j /= 10, k--)\n        {\n            if (j % 10 != 9)\n                if (j % 10 != 0)\n                    goto loop;\n        }\n        if (x % z != 0)\n            goto loop;\n        Console.WriteLine("answer:{0}",x);\n        Console.ReadKey();\n    }\n}\n}	0
24615993	24613187	C# Moq Entity Framework 6 Data Context Add Operation	var internals = new Mock<DbSet<InternalTransaction>>();\nvar mockDC = new Mock<IDataContext>();\n\nmockDC.Setup(q => q.InternalTransactions).Returns(internals.Object);\ninternals.Setup(q => q.Create()).Returns(new InternalTransaction());\n\nvar transaction = new ExternalTransaction { [set criteria for Condition A] };\n\nSomeBusinessObject.AddTriggeredInternalTransactions(mockDC.Object, transaction);\n\n// verify the Add method was executed exactly once\ninternals.Verify(e => e.Add(It.IsAny<InternalTransaction>()), Times.Once());	0
23467879	23467446	I need to pass a parameter from request header to the API controller action method. How can I?	IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");\nvar id = headerValues.FirstOrDefault();	0
6682374	6682290	C# Datetimes: Conversion for different time zones	TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");\nDateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);	0
23678445	23678287	How to parse XML elements?	// This:\n((string)trackPointElement.Element (ns1 + "Time").Value) : "",\n(decimal)(trackPointElement.Element (ns1 + "AltitudeMeters") != null ? Convert.ToDouble ((string)trackPointElement.Element (ns1 + "AltitudeMeters").Value) : 0.0),\n\n// is equivalent to:\n(string)trackPointElement.Element (ns1 + "Time") ?? ""\n(decimal?)trackPointElement.Element (ns1 + "AltitudeMeters") ?? 0.0,	0
14584478	14584162	Custom Authentication in ASP.NET MVC 4 app	[AcceptVerbs(HttpVerbs.Post)]\n    public ActionResult Login(YourModel model)\n    {\n        if (!ModelState.IsValid)\n        {\n            return View("Login", model);\n        }\n\n        return RedirectToAction("Index");\n    }	0
12726845	12725002	create a folder and save choosing Multiple image in createfolder using fileopenpicker in windows 8	var files = await openpicker.PickMultipleFilesAsync();\nif (destinationFolder != null && files !=null)\n{\n\nforeach(var fileItem in files)\n{\n    await fileItem.CopyAsync(destinationFolder);\n}\n}	0
8843999	8843932	Flag enum with shared values depending on context?	[Flags]\npublic enum Answer\n{\n    No = 0, \n    Choice1 = 1,\n    Choice2 = 2,\n    Choice3 = 4,\n    Choice4 = 8,\n    Yes = 0x80000000,\n}	0
11220221	11218352	Extracting Data from listview	INSERT INTO ArchivedCustomers SELECT CustomerStatus, CustomerGroup, CustomerFirstName, CustomerLastName, CompanyName, CustomerAddress, CustomerCity, CustomerState, CustomerZipcode, CustomerEmail, CustomerEmail2, CustomerPhoneNumber, CustomerPhoneNumberExt, CustomerType, CustomerSubscriptionType, CustomerCost, CustomerPaymentMethod, CustomerSignUpDate, CustomerPickUpDay, CustomerPickUpDay2, CustomerNotes FROM Customers WHERE CustomerID = @original_CustomerID; DELETE FROM Customers WHERE CustomerId = @original_CustomerId"	0
459042	459034	get computer name from within a windows service	string CurrentMachineName = Environment.MachineName;	0
12586956	12586456	as expressed in vb.net this lambda expression	If CObj(publicProperties) IsNot Nothing AndAlso publicProperties.Any() Then\n        Return publicProperties.All(Function(p)\n                'check not self-references... \n            Dim left = p.GetValue(Me, Nothing)\n            Dim right = p.GetValue(other, Nothing)\n            If GetType(TValueObject).IsAssignableFrom(left.GetType()) Then\n                Return Object.ReferenceEquals(left, right)\n            Else\n                Return left.Equals(right)\n            End If\n        End Function)\n    End If	0
9233770	9233646	Extract partial text from textbox	var beforeDot = new String(textBox.Text.TakeWhile(c => c != '.').ToArray());	0
8073436	8072998	How to detect the status of msbuild from command line or c#	msbuild <args>\nif errorlevel 1 goto errorDone	0
13253864	13253663	How to delete a full row in a ListView if no items are there?	var lst = new  ListView();\n            for (int i = lst.Items.Count - 1; i >= 0; i--)\n        {\n            var itemtoremove = //Put your condition here and get that item\n            lst.Items.Remove(lst.Items.Find("key"));\n        }	0
14084022	14082901	How to edit and save photo in Windows Store App?	ras.Seek(0);\nfileStream.Seek(0);\nfileStream.Size = 0;\nawait RandomAccessStream.CopyAsync(ras, fileStream);\n\nfileStream.Dispose();\nras.Dispose();	0
25585006	25581411	how to show a Form and continue?	if (IsWindowsFormsAppRunning() == false)\n        System.Diagnostics.Process.Start(@"Path\windowsFormApp.exe");\n\n\nprivate static bool IsWindowsFormsAppRunning()\n{\n   //update this function\n   return false;\n}	0
26827405	26804704	How to do bulk save / updates without using HQL?	session.Refresh(entity);	0
12659703	12644864	combining a query part with Lucene and part in database (MySQL)	Text:"traffic control" AND PublishedOn:[00000000 TO 20121001]	0
8703574	8703554	Put SqlCeDataReader output into a string (C#)	List<int> results = new List<int>();\n        com.Parameters.AddWithValue("date", Form1.date);\n        SqlCeDataReader reader = com.ExecuteReader();\n        while (reader.Read())\n        {\n            int resultsoutput = reader.GetInt32(0);\n\n            results.Add(resultsoutput);\n            // I wouldn't use a MessageBox in this loop\n            // MessageBox.Show(resultsoutput.ToString());\n        }	0
7786539	7786498	Something about moving shapes around in Canvas in WPF	Storyboard Animation	0
9857403	9857141	ListView selectedindexchanged	private void listView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n  if(this.listView1.SelectedItems.Count == 0)\n    return;\n\n  string namn = this.listView1.SelectedItems[0].Text;\n\n  // Create the sql statement to retrieve details for the user\n  string sql = string.Format("select * from kunder where fornamn = '{0}', namn);\n\n  // do the same as you do to create a reader and update the controls.\n}	0
366932	366856	How to convert C# StructureMap initialization to VB.NET?	Private Shared Sub Foobar(x As IInitializationExpression)\n    x.AddRegistry(New DataAccessRegistry)\n    x.AddRegistry(New CoreRegistry)\n    x.AddRegistry(New WebUIRegistry)\n    x.Scan(AddressOf Barfoo)\nEnd Sub\n\nPrivate Shared Sub Barfoo(ByVal scanner As IAssemblyScanner) \n    scanner.Assembly("RPMWare.Core")\n    scanner.Assembly("RPMWare.Core.DataAccess")\n    scanner.WithDefaultConventions\nEnd Sub\n\n' ??? '\nObjectFactory.Initialize(AddressOf Foobar)	0
4975128	4975049	Lambda expression with two navigation properties	var test = _allRec.SelectMany(x => x.RecPositions)\n                  .Select(p => p.Person)\n                  .ToList();	0
4605959	4600375	Reading SAML Attributes from SAML Token	foreach (SamlStatement statement in deserializedSaml.Assertion.Statements)\n{\n  SamlAttributeStatement attributeStatement = statement as SamlAttributeStatement;\n  if (null != attributeStatement)\n  {\n    foreach (SamlAttribute attribute in attributeStatement.Attributes)\n    {\n      DoWhateverYouLikeWith(attribute);\n    }\n  }\n}	0
9120454	9120318	Nice, clean cross join in Linq using only extension methods	var z2 = xs.SelectMany(x => ys, (x, y) => new {x, y});	0
14449239	14449181	how to use parameters in code behind to access some controls in my aspx file using C#	if (!IsPostBack)\n{\n    MainGridView.DataSource = GetData("select   GroupCategory, Count(Status1) as TotalCount from  [MasterProject] where Closing_Date >= '"+ txtStartClosingDate.Text +"' and Closing_Date <= '"+ txtEndClosingDate.Text +"' and Status1 is not null group by  GroupCategory");\n    MainGridView.DataBind();\n}	0
18396642	18396247	Deserialize tag with body and attributes to an object	public class Element\n{\n    [XmlAttribute]\n    public string Attr { get; set; }\n\n    [XmlText]\n    public string Body { get; set; }\n}	0
7092965	6213463	Accessing another user's MyDocuments folder.	Environment.SpecialFolder.CommonDocuments	0
16035372	16034965	Masterpage controllist only returns some controls	foreach (Control ctrl in this.form1.Controls)\n{\n    if (ctrl.Controls.Count > 0)\n    {\n        // do recursive call\n    }\n}	0
18441939	18441420	Regular expression find and replace to wrap tags	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string\n            input = "Hello World!",\n            keyword = "Hello";\n\n        var result = Regex\n            .Replace(input, keyword, m => \n                String.Format("<b>{0}</b>", m.Value));\n        Console.WriteLine(result);\n    }\n}	0
6001098	6001063	Convert a decimal to the smallest possible numeric type without any data loss	short res;\n        decimal value = 8913798132;\n        bool s = short.TryParse(value.ToString(), out res); // returns false	0
16665471	16661568	How to crop subsection of 2D array?	int w2 = x2 - x1 + 1;\nint h2 = y2 - y1 + 1;\nbyte[,] array2 = new byte[w2, h2];\nfor (int i = 0; i < w2; i++)\n{\n    Array.Copy(array1, (i+x1)*h + y1, array2, i*h2, h2);\n}	0
32522769	32522634	Ctrl+C Store Clipboard to Variable C#	if (Clipboard.ContainsAudio())\n{\n    var audio = Clipboard.GetAudioStream();\n    [..]\n}\n\nif (Clipboard.ContainsFileDropList())\n{\n    var list = Clipboard.GetFileDropList();\n    [..]\n}\n\nif (Clipboard.ContainsImage())\n{\n    var image = Clipboard.GetImage();\n    [..]\n}\n\n\nif (Clipboard.ContainsText(TextDataFormat.Html))\n{\n    var text = Clipboard.GetText(TextDataFormat.Html);\n    [..]\n}	0
23343308	23342322	Set all xml nodes as CDATA	var doc = new XmlDocument();\ndoc.Load("path_to_xml_file.xml");\nvar elements = doc.DocumentElement.SelectNodes("/rootNode/category/string");\nforeach (XmlNode element in elements)\n{\n    //check if content of <string> is not CData section\n    if(!(element.FirstChild is XmlCDataSection))\n    {\n        XmlCDataSection cdata = doc.CreateCDataSection(element.InnerText);\n        //replace inner text with CData section\n        element.ReplaceChild(cdata, element.FirstChild);\n    }\n}\n\ndoc.Save("path_to_xml_file.xml");	0
33893493	32336183	C# Windows Phone 8.1 runtime: how to make a task survive beyond app lifecycle?	private async void button_Click(object sender, RoutedEventArgs e)
\n{
\n    string myTaskName = "MyBackgroundClass";
\n    // check if task is already registered
\n    foreach (var cur in BackgroundTaskRegistration.AllTasks)
\n        if (cur.Value.Name == myTaskName)
\n        {
\n            await (new MessageDialog("Task already registered")).ShowAsync();
\n            return;
\n        }
\n    // Windows Phone app must call this to use trigger types (see MSDN)
\n    await BackgroundExecutionManager.RequestAccessAsync();
\n    // register a new task
\n    BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "MyBackgroundClass", TaskEntryPoint ="MybackgroundStuff.MyBackgroundClass" };
\n    taskBuilder.SetTrigger(new TimeTrigger(15, true));
\n    BackgroundTaskRegistration myFirstTask = taskBuilder.Register();	0
741540	741520	How to interrupt server Connection in C#	while(readcount > 0 && !cancel)\n{\n   ...\n}	0
15915136	15915055	How to White Part of JPG in PictureBox transparent	Bitmap b = new Bitmap("img.jpg")\nb.MakeTransparent(Color.White);\npictureBox.Image = b;	0
20501449	20501268	How can i convert an html encoded string to a normal string?	string  mystr = "&#72;&#101;&#108;&#108;&#111;&#32;&#87;&#111;&#114;&#108;&#100;";\n        var arr = mystr.Split(';');\n        string newMStr = string.Empty; \n        foreach (var s in arr)\n        {\n            string newS= s.Remove(0, 2);\n           newMStr+= Convert.ToChar(int.Parse(newS));\n        }\n\n         //Print  NewMstr	0
32106673	32106554	Go back to page that needed authentication after successful login	protected void Page_Load(object sender, EventArgs e)\n{\n    if (Session["user"] == null)\n    {\n        Response.Redirect("~/login.aspx?from=ORIGINGPAGE"); //Set parameter here\n    }\n}	0
5230080	5200720	Get Name of ScatterviewItem in a Scatterview with binding	private void MainScatterView_PreviewContactUp(object sender, ContactEventArgs e)\n    {\n        if (e.GetPosition(this).X < 100 && (coordinates.Height - e.GetPosition(this).Y) < 100)\n        {\n            string file = e.OriginalSource.ToString();\n            UserNotifications.RequestNotification("Notification PreviewContactUp", file, TimeSpan.FromSeconds(2));\n        }\n    }	0
24712135	24712130	How to compare two string arrays?	// 1\narray1.Intersect(array2).Any();\n\n// 2\narray1.Except(array2).Count() == array1.Distinct().Count();\n\n// 3.1\narray1.Any(array2.Contains);\n\n// 3.2\narray1.All(x => !array2.Contains(x));	0
9041932	9041780	Determine quicktime version with C#	strComputer = "."\n\nSet objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")\n\nSet colItems = objWMIService.ExecQuery _\n    ("Select * From Win32_Product Where Name = 'QuickTime'")\n\nIf colItems.Count = 0 Then\n    Wscript.Echo "QuickTime is not installed on this computer."\nElse\n    For Each objItem in colItems\n        Wscript.Echo "QuickTime version: " & objItem.Version\n    Next\nEnd If	0
20731753	20731713	Timer to do a Database Auto clean every 24h	Oracle Scheduler	0
28821760	28821718	Avoid XAML Designer error with custom controls	if (DesignerProperties.GetIsInDesignMode(this))\n    {\n        // Design-mode specific functionality\n    }	0
3776514	3776278	LINQ2SQL: how to delete entity by retrieving it from datagridview?	result = db.ExecuteCommand("Delete from Employees WHERE id = '2'")	0
19020416	19020177	Unlock a file locked by regex	string str = System.IO.File.ReadAllText("c:\docs\xyz.log");\n...\n// now use str in the loop\nstart:\n...	0
25386804	25348001	How to auto update the content after fixed intervals in windows phone 8 page that retrieve data from Json	ItemsSource="{Binding Path=YourMatchResults}"	0
1907426	1907406	how to compare two arrays of objects	IEnumerable<T>.Except(...)	0
25259354	25259003	Correct format for DateTime.ParseExact	int endOfTime = text.IndexOf(' ', 16);\nif (endOfTime == -1)\n{\n    throw new FormatException("Unexpected date/time format");\n} \ntext = text.Substring(0, endOfTime);\nDateTime dateTime = DateTime.ParseExact(text, "ddd MMM d yyyy HH:mm:ss",\n                                        CultureInfo.InvariantCulture);	0
12964497	12963903	Unable to modify a dataset before binding to gridview in asp.net	DataSet dsEmployeeOrg = eCorporateStaffMgr.GetEmployeeAccessLevel(oEmp);\nDataTable dt = dsEmployeeOrg[0];\nstring sManagerID = "";\nstring sSupervisorID = "";\nstring sEmployeeID = "";\n\nfor (int i = 0; i < dsEmployeeOrg.Tables[0].Rows.Count; i++)\n{\n   sManagerID = dt.Rows[i].ItemArray[3].ToString().Trim();\n   sSupervisorID = dt.Rows[i].ItemArray[4].ToString().Trim();\n   sEmployeeID = dt.Rows[i].ItemArray[5].ToString().Trim();\n\n   if ((sManagerID.ToString().Trim() != sSupervisorID.ToString().Trim()) && (sManagerID.ToString().Trim() != sEmployeeID.ToString().Trim()))\n   {\n       if (sSupervisorID.ToString().Trim() == sEmployeeID.ToString().Trim())\n       {\n          // This is a Supervisor record\n          dt.Rows[i][2] = "1111";\n       }\n       else if (sSupervisorID.ToString().Trim() != sEmployeeID.ToString().Trim())\n       {\n          //This is a Employee record\n          dt.Rows[i][2] = "0000";\n       }\n   }\n}	0
29510682	29510531	Splitting a string into chunks of a certain nth sizes	string t1 = str.Substring(0, 2);\nstring t2 = str.Substring(2, 2);\nstring t3 = str.Substring(4, 4);	0
11512584	11502155	How to create an index with Distinct operation. RavenDB	var categories = Session.Query<Product>()\n                   .Select(x => x.Category).Distinct().ToList().OrderBy(x=>x);	0
32554511	32553679	wpf modern-ui How can I choose a theme in code behind?	AppearanceManager.Current.ThemeSource = AppearanceManager.LightThemeSource;	0
20112593	20109439	FormCollection missing submit button values	setTimeout()	0
20960063	20959991	Convert string containing numbers separated by spaces into list of doubles c#	var splitted = yourString.Split(new []{" "}, \n                                          StringSplitOptions.RemoveEmptyEntries);\nexistingListOfDoubles.AddRange(splitted.Select(double.Parse));	0
26047349	26047289	Regex cannot accept two numbers followed c#	^(?!.*[0-9]{2}).*	0
9591488	9586714	dynamically populating column headers in a gridview	Dim grouped =\n    From usersAnswers In\n        From result In results\n        Group result By result.userID Into Group\n        Let answers = Group.OrderBy(Function(x) x.QuestionText).ToList()\n        Select\n            answers.First().firstName,\n            Question1 = answers(0).UserResponse,\n            Question2 = answers(1).UserResponse,\n            Question3 = answers(2).UserResponse	0
14374842	10011659	Pass selected ViewModel from WPF datagrid to new TabItem MVVM	private static void OnSelectedMemberPropertyChanged(DependencyObject m, DependencyPropertyChangedEventArgs args)\n{\n  var b = m as OverviewViewModel;\n  if (b == null)\n    return;\n  var selectedMember = m.GetValue(SelectedItemProperty) as MemberViewModel;\n  b.selectedMemberChanged(selectedMember);\n}	0
19402620	19365139	XML not reading specific node	xr.ReadToFollowing("nc:CaseTrackingID");//this will directly get the element name\ncasenumber = xr.ReadElementContentAsString();	0
8991929	8991851	Parse text with date and timestamp using Regex in C#	string[] words = s.Split('-');	0
6120368	6119509	Invalid Characters from XML string	public string PreProcessXml( string xml )\n{\n    // this list could be read from a config file\n\n    List<Tuple<string, string>> replacements = new List<Tuple<string, string>>();\n\n    // Important: if there are VALID uses of an ampersand in your document, \n    // this may invalidate them! Perform a more elaborate check using a \n    // regex, or ensure that there are no valid entities already in the document.\n    replacements.Add( new Tuple<string, string>( "&", "&amp;" ) );\n\n    replacements.Add( new Tuple<string, string>( "\"", "&quot;" ) );\n    replacements.Add( new Tuple<string, string>( "\'", "&apos;" ) );\n\n    foreach( var replacement in replacements )\n    {\n        xml = xml .Replace( replacement.Item1, replacement.Item2 );\n    }\n\n     return xml;\n}	0
28667598	28666971	How to display rows of data from a DataView using a string variable instead of srting builder class	public string DisplayDataRow(DataView dataView)\n{\n    string rows = null;\n    string lineBreak = "<br />";\n\n    foreach(DataRowView rowView in dataView)\n    {\n        for(int index = 0; index < dataView.Table.Rows.Count; index++)\n            rows += rowView.Row[index] + " ";\n        rows+=lineBreak;\n    }\n\n    return rows;\n}	0
8457888	8457770	how to create SELECT query with some conditions	string query = @"SELECT * FROM table WHERE 1=1 "\n                + (string.IsNullOrEmpty(textBox1.Text) ? "" : " AND id='" + textBox1.Text + "' ")\n                + (string.IsNullOrEmpty(textBox2.Text) ? "" : " AND name='" + textBox2.Text + "' ");	0
595142	595125	C# accessing control propertes from static void	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n    }\n\n    public void y()\n    {\n        MessageBox.Show(checkBox1.Checked.ToString());\n    }\n\n    static void x(Form f)\n    {\n        f.y();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        x(this);\n    }\n\n}	0
14848886	14848773	Deleting a key in a dictionary	dict.ToList().ForEach(a => { if (a.Key.Contains('/') dict.Remove(a.Key); });	0
31216469	31216402	Is there a way to require two optional method parameters to be used as a pair?	MyMethod (param1, param2){...\n\nMyMethod (param3){...	0
28792560	28792306	SSIS - how to transform a Recordset as a result of an "Execute SQL Task" into a List<string>	public void Main()\n    {\n        var dt = new DataTable();\n\n        new OleDbDataAdapter().Fill(dt, this.Dts.Variables["User::Names"].Value);\n\n        var list = dt.Rows.OfType<DataRow>().Select(i => i[0].ToString()).ToList();\n\n        this.Dts.Variables["User::NameList"].Value = list;\n\n        this.Dts.TaskResult = (int)ScriptResults.Success;\n    }	0
2682976	2682936	How do I create editable configuration settings in a C# WinForms application?	System.Configuration.ConfigurationManager	0
26506338	26486445	How to use FluentValidation within c# application	public class CustomerValidator: AbstractValidator<Customer> {\n  public CustomerValidator() {\n    RuleFor(customer => customer.Surname).NotEmpty();\n    RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");\n    RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);\n    RuleFor(customer => customer.Address).Length(20, 250);\n    RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");\n  }\n\n  private bool BeAValidPostcode(string postcode) {\n    // custom postcode validating logic goes here\n  }\n}\n\nCustomer customer = new Customer();\nCustomerValidator validator = new CustomerValidator();\nValidationResult results = validator.Validate(customer);\n\nbool validationSucceeded = results.IsValid;\nIList<ValidationFailure> failures = results.Errors;	0
4280218	4280200	How to create the settings file from default options?	[Appname].exe.config	0
24810915	24808950	How to create an event trigger for control programmatically	void SetTrigger(ContentControl contentControl)\n{\n    // create the command action and bind the command to it\n    var invokeCommandAction = new InvokeCommandAction { CommandParameter = "btnAdd" };\n    var binding = new Binding { Path = new PropertyPath("ButtonClickCommand") };\n    BindingOperations.SetBinding(invokeCommandAction, InvokeCommandAction.CommandProperty, binding);\n\n    // create the event trigger and add the command action to it\n    var eventTrigger = new System.Windows.Interactivity.EventTrigger { EventName = "PreviewMouseLeftButtonDown" };\n    eventTrigger.Actions.Add(invokeCommandAction);\n\n    // attach the trigger to the control\n    var triggers = Interaction.GetTriggers(contentControl);\n    triggers.Add(eventTrigger);\n}	0
9413892	9413839	How can I segregate fat interface through implementing adaptern pattern?	interface IAmFat\n{\n    void Method1();\n    void Method2();\n    ...\n    void MethodN();\n}\n\ninterface IAmSegregated\n{\n    void Method1();\n}\n\nclass FatAdapter : IAmSegregated\n{\n    private readonly IAmFat fat;\n\n    public FatAdapter(IAmFat fat)\n    {\n        this.fat = fat;\n    }\n\n    void IAmSegregated.Method1()\n    {\n        this.fat.Method1();\n    }\n}	0
10303053	10302766	speed up parsing in html agility pack	var results = node.Descendants()\n                  .Where(x=> x.Attributes["id"]!= null && \n                             x.Attributes["id"].Value.Contains("panel_") &&  \n                             x.Attributes["id"].Value!= "panel__")\n                  .Select( x=> new Result(URLGoogleLocal, Listing, x, SearchEngine.Google, SearchType.Local, ResultType.GooglePlaces));	0
18251568	18251395	trying to create a list of deserialized data windows phone	CreationDate = news_items[i].CreationDate.Substring(0, news_items[i].CreationDate.IndexOf('T')),\nLastUpdateDate = news_items[i].LastUpdateDate.Substring(0, news_items[i].LastUpdateDate.IndexOf('T')),\nDisplayUntilDate = news_items[i].DisplayUntilDate.Substring(0, news_items[i].DisplayUntilDate.IndexOf('T')),	0
13916808	13916565	Is a method call slower than accessing a private field of a class?	return private field	0
32319320	32319100	How to keep re-launching a windows form from the main program until another window form exits the application?	static class Program\n{\n    static void Main()\n    {\n        do\n        {\n            var formA = new FormA();\n            Application.Run(formA);\n            var formB = new FormB(formA.SelectedConfigurationFile);\n            Application.Run(formB);\n        } while (!IsComplete);\n    }\n\n    public static IsComplete { get; set;}\n}\n\npublic class FormB\n{\n    protected override void OnFormClosed(FormClosedEventArgs e)\n    {\n        base.OnFormClosed(e);\n        if (e.CloseReason == CloseReason.UserClosing)\n            Program.IsComplete = true;\n    }\n\n    private void btnCancel_Click(object sender, EventArgs e)\n    {\n        Program.IsComplete = true;\n        Close();\n    }\n\n    private void btnBack_Click(object sender, EventArgs e)\n    {\n        if (this.Tabs.SelectedIndex == 0)\n        {\n            Program.IsComplete = false;\n            Close();\n        }\n    }\n}	0
1437842	1133533	How to achieve focus-reset to update BindingSource of TextBox before any action	private void BeforeFocusLost(object sender, KeyboardFocusChangedEventArgs e)\n{\n  if (sender is TextBox) {\n    var tb = (TextBox)sender;\n\n    var bnd = BindingOperations.GetBindingExpression(tb, TextBox.TextProperty);\n\n    if (bnd != null) {\n      Console.WriteLine(String.Format("Preview Lost Focus: TextBox value {0} / Data value {1} NewFocus will be {2}", tb.Text, bnd.DataItem, e.NewFocus));\n      bnd.UpdateSource();\n    }\n    Console.WriteLine(String.Format("Preview Lost Focus Update forced: TextBox value {0} / Data value {1} NewFocus will be {2}", tb.Text, bnd.DataItem, e.NewFocus));\n  }\n}	0
12245969	12245833	Cast to generic interface dynamically	public void SetWrapper<T>(Field field, List<T> list) {\n    entity.Set(field, (IList<T>)list);\n}	0
8690961	8690911	Finding timezone in HttpRequest from server side	var timeNow = new Date();\nvar timezone = timeNow.getTimezoneOffset() / 60 * (-1);	0
16654726	16654491	How can I get the GUID value of a new row after inserting it?	INSERT INTO ExampleTable (<Column1>, <Column2>, <Column3>) OUTPUT INSERTED.ID\nVALUES (<Value1>, <Value2>, <Value3>)	0
1548914	1548893	c# how to retrieve post data	if (Page.PreviousPage != null)\n{\n    TextBox SourceTextBox = \n        (TextBox)Page.PreviousPage.FindControl("txtInfo");\n    if (SourceTextBox != null)\n    {\n        Label1.Text = SourceTextBox.Text;\n    }\n}	0
27247494	27247338	replace multiple words by the same word in bold	public string MakeBold(string text, string[] splitwords)\n{\n    var sb = new StringBuilder();\n    var words = text.Split(" ");   \n    sb.Append(@"{\rtf1\ansi");\n    foreach (var word in words){\n      if (splitwords.Contains(word)){\n         sb.Append(@"\b"+word+ @"\b0 ");\n      }\n      else\n      {\n         sb.Append(word);\n         sb.Append(@" ");\n      }\n    }\n    sb.Append(@"}");\n    return sb.ToString();\n}	0
12407237	12407025	Inject one of ViewModels into a View using Unity container	public View(IViewModel1 vm)\n{\n    InitializeComponent();\n    _myViewModel = vm;\n}	0
15414095	15408404	IP Cam live feed from C#	string sourceURL = "http://ipaddress/jpg/image.jpg";\n            byte[] buffer = new byte[100000];\n            int read, total = 0;\n            // create HTTP request\n            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sourceURL);\n            req.Credentials = new NetworkCredential("username", "pass");\n            // get response\n            WebResponse resp = req.GetResponse();\n            // get response stream\n            Stream stream = resp.GetResponseStream();\n            // read data from stream\n            while ((read = stream.Read(buffer, total, 1000)) != 0)\n            {\n                total += read;\n            }\n            // get bitmap\n            Bitmap bmp = (Bitmap)Bitmap.FromStream(\n                          new MemoryStream(buffer, 0, total));\n\n            pictureBox1.Image = bmp;	0
8887370	8887113	Facebook C# SDK Recommend Post Using Access Token	var client = new FacebookClient("ACCESS_TOKEN");\ndynamic throwAwayVariable = client.Get("/POST_ID/likes");\ndynamic result = client.Post("/POST_ID/likes");	0
32960957	32960742	How do I copy an Excel column name to a string using OLEDB with C#?	string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;";\n\nConnectionString = string.Format(ConnectionString, @"FullPathToExcelFile"); //my path replace with your actual file path\n\nOleDbConnection conn = new OleDbConnection(ConnectionString);\nconn.Open();\n\nOleDbCommand cmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);\nOleDbDataAdapter oleDBAdapter = new OleDbDataAdapter();\noleDBAdapter.SelectCommand = cmdSelect;\n\nDataSet myDataset = new DataSet();\noleDBAdapter.Fill(myDataset);\nconn.Close();	0
21191869	21191592	C# - Shoot only once - IsKeyUp & IsKeyDown	bool readytofire = true;\npublic override void Update()\n{\n    KeyboardState newState = Keyboard.GetState();\n\n    readytofire = !newState.IsKeyDown(Keys.Space);\n\n    if (newState.IsKeyDown(Keys.Space) && readytofire)\n    {\n        bulletList.Add(new Bullet(content.Load<Texture2D>(@"bullet"), new Vector2(initialPos.X, initialPos.Y - 28), new Vector2(2, 4), spriteBatch));\n    }\n}	0
9803161	9802993	Asp.net charts- multiple y values	Chart1.Series[0].YValuesPerPoint = 2;	0
4772945	4772159	How can I constrain T to support DataContractJsonSerializer, and not implement ISerializable everywhere?	where T : class, new()	0
28925775	28925689	Checking if String is a proper date and insert it into database	string datestr = "2001-01-01";\n        DateTime date;\n        if (DateTime.TryParse(datestr, out date))\n        {\n            //write date to db\n        }\n        else\n        {\n            //throw an error\n        }	0
12984022	12983816	how to remove xmlnode within a foreach loop?	public static XmlNodeList Scan(XmlNodeList nodeList)\n{\n    List<XmlNode> toRemove = new List<XmlNode>();\n\n    foreach (XmlNode xmlElement in nodeList)\n    {\n        string elementValue = xmlElement.InnerText;\n        if (elementValue.Length < 6 || elementValue.Substring(0, 3) != "999")\n        {\n            toRemove.Add(xmlElement);\n        }\n    }\n\n    foreach(XmlNode xmlElement in toRemove)\n    {\n        XmlNode node = xmlElement.ParentNode;\n        node.RemoveChild(xmlElement);\n    }\n\n    return nodeList;\n}	0
32364022	32338351	Antlr4 semantic predicate to match user-defined delimiters	tag: TBEG \n     ( id expression  // assign etc\n     | expression     // for etc\n     | id             // endfor etc\n     )\n     TEND  // { processTag($tag); } // alternate solution\n   ;	0
2662133	2662090	How to create network interface programatically?	netsh interface ip set address name="Local Area Connection" static 192.168.0.100 255.255.255.0 192.168.0.1 1	0
4784723	4782261	Create a security identifier for the current domain	WindowsIdentity id = WindowsIdentity.GetCurrent();\n   Console.WriteLine(id.User.AccountDomainSid);	0
28994141	28994028	c# write text box to txt file, how to name file?	System.IO.File.WriteAllText(@"C:\Users\Public\Documents\Notes\" + richtextbox1.Text + ".txt", txtbox);	0
11231506	11231456	Serializing classes created with Singleton pattern	Test<T>(T obj)	0
22833910	22833744	Select sqldasource query from dropdownlist	SqlConnection conn = new SqlConnection();\n\nconn.ConnectionString = ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionStri??ng;	0
10050069	10049303	fill datagridview column with images from image path column	private void createGraphicsColumn()\n    {\n        Icon treeIcon = new Icon(this.GetType(), "tree.ico");\n        DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();\n        iconColumn.Image = treeIcon.ToBitmap();\n        iconColumn.Name = "Tree";\n        iconColumn.HeaderText = "Nice tree";\n        dataGridView1.Columns.Insert(2, iconColumn);\n    }	0
1373400	1373361	Create a dropdownlist using ActiveRecord	DropDownList1.DataSource = ProjectRegion.FindAll();\nDropDownList1.DataTextField = "title";\nDropDownList1.DataValueField = "id";\nDropDownList1.DataBind();	0
33078916	33078816	Interface Inheritence & Overloads	void SetValues(ISomethingMoreSpecific specificThing);	0
1543097	1543078	Include external JS file from base page	Page.ClientScript.RegisterClientScriptInclude("coursel", ResolveUrl("FeatureX.js"));	0
12584636	12583616	How to change the position of a video using MediaElement in Windows8?	playbackElement1.AutoPlay = true;\n// Will fire after the media has loaded\nplaybackElement1.MediaOpened += (source, args) =>\n{\n    MediaElement player = (MediaElement) source;\n    if (player.CanSeek)\n    {\n        player.Position = new TimeSpan(0, 0, 0, 0, 5000);   \n    }\n}                     \nplaybackElement1.SetSource(stream, this.m_recordStorageFile.FileType);	0
18868470	18868314	How can I combine fields from two objects into one?	rfc.Select(r=>\n    new AnswerDetail\n    {\n        AnswerId =r.AnswerId,\n        Text=r.Text,\n        Response=r.Response,\n        Correct=afd.Single(c=>c.AnswerId==r.AnswerId).Correct\n    }\n           );	0
16731875	16731852	Linq Multiple OR with a list	listOfId.Contains(T.ReferenceId);	0
11049314	11048768	Can i read through an Argument that is a generic list?	IEnumerable argumentList = args.Arguments[i] as IEnumerable;\n\nif (argumentList != null) {\n  foreach(var item in argumentList){\n    // Do what you want with the item\n  }\n}	0
23137949	23130905	Table valued parameters with reference to other tables	CREATE PROCEDURE EmpAddressSetStatus\n  @empid INT,\n  @statusValue NVARCHAR(2000)\nAS\n\n-- see if there is an existing status\nDECLARE @statusId INT\nSELECT @statusId =  statusId FROM AddrStatus WHERE statusDesc=@statusValue\n\n-- if not then insert the new status\nIF @statusId IS NULL \nBEGIN\n  INSERT AddrStatus (statusDesc) VALUES (@statusValue)\n  SELECT @statusId = SCOPE_IDENTITY()\nEND\n\n-- copy from the input table to the output table, setting the correct status\nINSERT empaddr_verified(empId, empalladdr, statusid)\nSELECT empId, empaddr, @statusId FROM inputtable WHERE empId = @empid\n\nGO	0
7724654	7671961	Modify cell value before it is displayed	protected void RadGrid1_PreRender(object sender, EventArgs e)\n    {\n        foreach (GridDataItem it in RadGrid1.EditItems)\n        {\n            TextBox sv = (TextBox)it["POZ_Stawka_VAT"].Controls[0];\n            if (sv.Text=="-1")\n            sv.Text = "zw";\n        }\n    }\n\n     protected void RadGrid1_DataBinding(object sender, EventArgs e)\n    {\n        for (int i = 0; i < RadGrid1.PageSize; i++)\n        {\n            RadGrid1.EditIndexes.Add(i);\n        }\n\n    }	0
23352823	23200526	OneDrive Downloaded *.jpeg Image File Corrupt in Windows Phone 8	var downloadResult = await client.DownloadAsync(selectedFile.FileID + "/picture?type=full");	0
23182729	23182579	How can I open my default webbrowser in WPF?	public DelegateCommand StartChromeCommand = new DelegateCommand(OnStartChrome);\n\nprivate void OnStartChrome()\n{\n   var process = new Process(new ProcessStartInfo {Arguments = @"http://www.google.com"});\n   process.Start();\n}	0
1945501	1945443	How to implement a LIKE operation in a search form in C#?	var _query = from _v in Classes.Data.getdb().vUsers\n             select v;\n\nif(!txtUsername.IsBlank())\n    _query = _query.Where(x => x.username.Contains(txtUsername.Text));\n\nif(!txtFirstName.IsBlank())\n    _query = _query.Where(x => x.firstname.Contains(txtFirstName.Text));\n\n// etc.\n\ngv.DataSource = _query;	0
11059495	11059456	(C#) How to read all files in a folder to find specific lines?	const string lineToFind = "blah-blah";\nvar fileNames = Directory.GetFiles(@"C:\path\here");\nforeach (var fileName in fileNames)\n{   \n    int line = 1;     \n    using (var reader = new StreamReader(fileName))\n    {\n         // read file line by line \n         string lineRead;\n         while ((lineRead = reader.ReadLine()) != null)\n         {\n             if (lineRead == lineToFind)\n             {\n                 Console.WriteLine("File {0}, line: {1}", fileName, line);\n             }\n             line++;\n         }\n    }\n}	0
9079821	9079755	How to set the width of the cell in the xlsx file created programmatically?	sheet.Columns["D:D"].ColumnWidth = 17.57;	0
10062170	10062157	How can select first 3 item of list<>	List<aspnet_News> allNews = context.aspnet_News.OrderByDescending(i => i.NewsId)\n                                               .Take(3)  // Takes the first 3 items\n                                               .ToList();	0
9221551	9220901	bulk insert with linq-to-sql	Bulk Insert	0
184262	183950	Add ScriptManager to Page Programmatically?	protected override void OnInit(EventArgs e)\n{\n    Page.Init += delegate(object sender, EventArgs e_Init)\n                 {\n                     if (ScriptManager.GetCurrent(Page) == null)\n                     {\n                         ScriptManager sMgr = new ScriptManager();\n                         Page.Form.Controls.AddAt(0, sMgr);\n                     }\n                 };\n    base.OnInit(e);\n}	0
16000647	15597049	How to handle authentication in an ember.js app	[torii][1]	0
1465113	1465029	If Statement Hell, How to check if a date passed matches a date within 3 days but only if the date doesnt match the other conditions	if day > earlierDay && day < laterDay then\n{\n  //day falls within 3 days of selected day\n}	0
29900430	29900249	how do I convert linq to lambda	var res = db.Client.Where(x => db.TimesheetLine.Select(o => o.ClientId).Contains(x.Id));	0
22422191	22421997	Limit Number of Hints a Gamer can Use : Number Guessing Game in C#	int hitcounter = 0;\nint lastHint = -1;\nwhile (!GameOver)\n{ \n    Console.Write("Answer: ");\n    string answer = Console.ReadLine();\n\n    if (answer.ToLower() == "hint")\n    {\n        if (hitcounter < 10)\n        {  \n                       //preveintg double hint. something like that. \n                       //you can use later array or list if you need more hint\n                       int hint = generaterandomhints();\n                       while (hint == lastHint)\n                       { \n                           hint = generaterandomhints();\n                       }\n\n           hitcounter++;\n           //write the hints\n        }\n        else\n        {\n            //write you reached the maximum of the hints\n        }\n    }\n}	0
17986177	17986007	Scale child back in WPF	RectToolTipBorder.LayoutTransform = graphGrid.LayoutTransform.Inverse as Transform;	0
4860145	4858744	C# Silverlight - How do I access a file that I set as a "resource"?	spellChecker.MainDictionary.LoadAsync(new Uri("/yourProjectName;component/yourDictionary.dic",UriKind.Relative));	0
17447575	17423088	Kinect properly statement of drawing function	private void DrawTrackedBoneLine(SkeletonPoint positionFrom, SkeletonPoint positionTo)\n{\n    // Code goes here\n}\n\nprivate void DrawNonTrackedBoneLine(SkeletonPoint positionFrom, SkeletonPoint positionTo)\n{\n    // Code goes here\n}	0
10173711	10173501	Getting an element using HtmlAgilityPack	var nodes = myDocument.DocumentNode.SelectNodes("//div[@style='font-size:16px;padding:4px 8px 0']")	0
11882632	11879915	Customize symbol type of a ZedGraph LineItem	var curve = zgc.GraphPane.AddCurve(null, new[] { 2.1, 2.6, 2.8 }, new[] { 1.8, 1.3, 1.1 }, Color.Blue);\n\ncurve.Symbol = new Symbol(SymbolType.UserDefined, Color.Red);\ncurve.Symbol.UserSymbol = new GraphicsPath(\n    new[]\n        {\n            new PointF(-0.6f, -0.6f), new PointF(-0.6f, 0.6f), new PointF(-1.0f, 0.6f), new PointF(0f, 1.6f), \n            new PointF(1.0f, 0.6f), new PointF(0.6f, 0.6f), new PointF(0.6f, -0.6f),\n            new PointF(-0.6f, -0.6f)\n        },\n    new[]\n        {\n            (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Line,\n            (byte)PathPointType.Line, (byte)PathPointType.Line, (byte)PathPointType.Line,\n            (byte)PathPointType.Line, (byte)PathPointType.Line\n        });	0
859444	859418	copy n k/v pairs from Hashtable	public IEnumerable<object> GetRange(Hashtable ht, int min, int max) {\n    int i = 0;\n    foreach (var key in ht.Keys) {\n    i++;\n    if (i > max) {\n    yield break;\n    }\n    if (i >= min) {\n    yield return ht[key];\n    } else continue;\n    }\n}	0
13308183	13308029	How to solve C# Premature Object Dispose	// if not running, I start it\nMysqlController.StartMysql(Constants.dbexe,Constants.dbopts);\n// wait 10 seconds max.\nint timeout = 10;\nbool mySqlIsRunning = false;\n\nwhile(!MysqlController.CheckMysqlIsRunning(Constants.dbpidfile)) {\n    // wait a while\n    Thread.Sleep(1000);\n    if (timeout-- == 0) {\n        // timeout error\n        // show message to user ...\n    }\n}\n\n// here mysql is running or your timeout is expired.	0
11870568	11569596	Could not find default endpoint element that references contract :connect to WCF endpoint through Powershell cmdlet	internal static class ServiceClass\n{\n\n    internal static Object GetWCFSvc(string siteUrl)\n    {\n\n        Uri serviceUri = new Uri(siteUrl);\n        EndpointAddress endpointAddress = new EndpointAddress(serviceUri);\n\n        //Create the binding here\n        Binding binding = BindingFactory.CreateInstance();\n\n        ServiceClient client = new ServiceClient(binding, endpointAddress);            \n        return client;\n    }\n\n\n}\n\ninternal static class BindingFactory\n{\n    internal static Binding CreateInstance()\n    {\n        BasicHttpBinding binding = new BasicHttpBinding();\n        binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;\n        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;\n        binding.UseDefaultWebProxy = true;\n        return binding;\n    }\n\n}	0
750250	750198	Convert XDocument to Stream	MemoryStream ms = new MemoryStream();\nXmlWriterSettings xws = new XmlWriterSettings();\nxws.OmitXmlDeclaration = true;\nxws.Indent = true;\n\nusing (XmlWriter xw = XmlWriter.Create(ms, xws))\n{\n    XDocument doc = new XDocument(\n        new XElement("Child",\n            new XElement("GrandChild", "some content")\n        )\n    );\n    doc.WriteTo(xw);\n}	0
18417177	18417057	Upload many file to Many Model properties in a single page	[HttpPost]\n    public ActionResult Post(Class Model, IEnumerable<HttpPostedFileBase> Photos, IEnumerable<HttpPostedFileBase> Logos, IEnumerable<HttpPostedFileBase> Videos)\n    { \n        // proceed \n    }	0
15467401	15467174	Multithread programming in WPF	Task.Factory.StartNew\n(\n    () =>\n    {\n        if (BfScrapper.Instance.CanStart)\n            BfScrapper.Instance.StartTask(brwser);\n    },\n    CancellationToken.None,\n    TaskCreationOptions.None,\n    TaskScheduler.FromCurrentSynchronizationContext()\n);	0
16938212	16935492	Data Migration from SQL Server to mongodb Using C#	// ...\nDictionary<string, string> _mapping = new Dictionay<string, string>();\n_mappaing.Add("columnA", "propertyA");\n// and so on\n\n// ...\n\ntry\n{\n    foreach (DataRow dr in dt.Rows)\n    {\n        BsonDocument bson = new BsonDocument();\n\n        for (int i = 0; i < dr.ItemArray.Count(); i++)\n        {\n            // here use the mapped name instead of the colmn name\n            bson.Add(_mapping[dr.Table.Columns[i].ColumnName], dr[i].ToString());\n        }\n        collection.Insert(bson);\n    }\n}	0
15651500	15651422	How can I read the mp3 into bytes array	var bytes = File.ReadAllBytes(fileName);	0
10904455	10904390	How to get a list in a MessageBox?	StringBuilder sb = new StringBuilder();\nforeach (DataGridViewCell cell in dgvC.SelectedCells)\n{\n    sb.AppendLine(cell.Value.ToString()); \n}\nMessageBox.Show(sb.ToString());	0
29214201	29212801	Open InfoPath xml from Sharepoint for xml processing	string Path = @"awesome-valid-url";\n//CopyService is the reference to the webservice\nCopyService.Copy cs = new CopyService.Copy();\ncs.Credentials = System.Net.CredentialCache.DefaultCredentials;\n\nCopyService.FieldInformation myFieldInfo = new CopyService.FieldInformation();\nCopyService.FieldInformation[] myFieldInfoArray = { myFieldInfo };\nbyte[] myByteArray;\n// Call the web service\nuint myGetUint = cs.GetItem(Path, out myFieldInfoArray, out myByteArray);\n\n// Convert into Base64 String\nstring base64String;\nbase64String = Convert.ToBase64String(myByteArray, 0, myByteArray.Length);\n\n// Convert to binary array\nbyte[] binaryData = Convert.FromBase64String(base64String);\n\n// Create a temporary file to write the text of the form to\nstring tempFileName = @"where-to-put-it.xml";\n\n// Write the file to temp folder\nFileStream fs = new FileStream(tempFileName, FileMode.CreateNew, FileAccess.ReadWrite);\nfs.Write(binaryData, 0, binaryData.Length);\nfs.Close();	0
23391173	23391037	How to numerically sort an array of strings?	using System;\nusing System.Collections.Generic;\n\npublic class Test\n{\n    public static void Main()\n    {\n        string[] items = {"10", "1", "30", "-5"};\n        Array.Sort(items, (x, y) => \n        {\n            int xNum = int.Parse(x);\n            int yNum = int.Parse(y);\n            return Comparer<int>.Default.Compare(xNum, yNum);\n        });\n\n        foreach(var item in items)\n            Console.WriteLine(item);\n    }\n}	0
13464437	13464368	What is the proper way to retrieve a value from a single, nested, XElement?	var folder = (string)xdoc.Elements("UserDefinedSettings").Elements("RootFolder").Elements("FolderName").FirstOrDefault();	0
14574761	14562975	How to Add schemaLocation attribute to an XML document	xs:schemaLocation="..."	0
15695930	15694766	How to programatically determine time interval state	state1Time = 40;\nstate2Time = 20;\nduration = 300;\n\nwhile (duration > 0 && duration > state1Time)\n{\n    if (duration >= state1Time)\n    {\n        changeState(1);\n        sleep(state1Time);\n    }\n    duration -= state1Time;\n    if (duration >= state2Time)\n    {\n        changeState(2);\n        sleep(state2Time);\n    }\n    duration -= state2Time;\n}\n\nchangeState(none);	0
2399734	2399710	How to get type of TKey and TValue given a Dictionary<TKey,TValue> type	Dictionary<int, string> dictionary = new Dictionary<int, string>();\nType[] arguments = dictionary.GetType().GetGenericArguments();\nType keyType = arguments[0];\nType valueType = arguments[1];	0
11275306	11275166	How can I find that a record successfuly deleted from Db using LINQ	System.Data.Linq.ChangeSet cs = aspdb.GetChangeSet();\nbool IsDeleted = cs.Deletes.Count() == 0;	0
15679731	15678821	checkbox column value in radGridview	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        radGridView1.Columns.Add(new GridViewCheckBoxColumn() { Name = "CheckBoxCol" });\n        radGridView1.Rows.Add(false);\n        radGridView1.Rows.Add(true);\n        radGridView1.Rows.Add(false);\n        radGridView1.Rows.Add(true);\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        foreach (GridViewRowInfo row in radGridView1.Rows)\n        {\n            Console.WriteLine(row.Cells["CheckBoxCol"].Value);\n        }\n    }\n}	0
24169512	17942726	How do I disabled HttpRequestValidation on HttpRequestBase?	request.Unvalidated["Username"]	0
6373989	6373933	Sorting , searching a dictionary in C#	List<Product> result = new List<Product>();\nvar keys = new [] {64290,64287,59261,50990,50975,50897,68494,68495,51015,68493};\nforeach (var key in keys)\n{\n    result.Add(listOfProducts[key]);\n}\nreturn result;	0
1056676	1054674	Get Repeater's Items	if (Repeater1.Items.Count > 0)\n    {\n        for (int count = 0; count < Repeater1.Items.Count; count++)\n        {\n            CheckBox chk = (CheckBox)Repeater1.Items[count].FindControl("CheckBox1");\n            if (chk.Checked)\n            {\n\n            }\n        }\n    }	0
22227437	22227355	How to write values of __EVENTTARGET and __EVENTARGUMENT in log file of POST request	string target= Request.Params["__EVENTTARGET"];\nstring args= Request.Params["__EVENTARGUMENT"];	0
10243544	10243527	Flags enum with too many items; last value is too large. How can I resolve this?	[Flags]\npublic enum Types : long	0
3681622	3681544	ReportViewer is driving me absolutely nuts	Parameters!MyAbsoluteURL.Value + Fields!ProductId.Value	0
18185804	18185529	Getting a random string from a multidimensional array	Math.Random()	0
23617144	23616675	How to deserealize a List of custom object?	public static List<ModelClass> Deserialize(string xml)\n    {\n        var xmlSerializer = new XmlSerializer(typeof(ModelClass));\n        using (TextReader reader = new StringReader(xml))\n        {\n            return(List<ModelClass>)xmlSerializer.Deserialize(reader);\n        }\n    }	0
30557489	30557287	C# parse array in json	[{\n        "name": "2542",\n        "type": "FOLDER",\n        "size": 0,\n        "time": 0,\n        "items": [{\n            "name": "10-1432927746000.ksf",\n            "type": "FILE",\n            "size": 225,\n            "time": 1433019520,\n            "items": null,\n            "info": {\n                "seller": 10,\n                "count": 2\n            }\n        }],\n        "info": null\n    }]	0
14162634	14161545	C# value switching value without me touching it	using UnityEngine;\nusing System.Collections;\n\npublic class OverlapButton : MonoBehaviour {\n    public string id_;\n    void OnGUI(){\n            if(GUI.Button(new Rect(0,0,50,50),"Touch")){\n                    Debug.Log("I'm object " + id_);\n            }\n    }\n}	0
23672409	23672213	Encrypted whole XML file	Encrypt(doc, doc.DocumentElement.Name, cert)	0
24612998	24612608	Validation on a button click using RequiredFieldValidator	Page.Validate("save");\nif (Page.IsValid) \n{\n//Continue with your logic\n}\nelse\n{\n//Display errors, hide controls, etc.\n}	0
14587256	14587126	C# Application changes picture size on me	grfx.DrawImage(imgPicture1, dstRect, srcRect, GraphicsUnit.Pixel);	0
6071434	6071325	How to filter to all variants of a generic type using OfType<>	var filteredList = myList.Where(\n    x => x.GetType()\n          .GetInterfaces()\n          .Any(i => i.IsGenericType &&\n                    (i.GetGenericTypeDefinition() == typeof(ITraceSeries<>)));	0
3654618	3654453	Get selected radio button not in a list in ASP .NET	private RadioButton GetSelectedRadioButton(string groupName)\n{\n    return GetSelectedRadioButton(Controls, groupName);\n}\n\nprivate RadioButton GetSelectedRadioButton(ControlCollection controls, string groupName)\n{\n    RadioButton retval = null;\n\n    if (controls != null)\n    {\n        foreach (Control control in controls)\n        {\n            if (control is RadioButton)\n            {\n                RadioButton radioButton = (RadioButton) control;\n\n                if (radioButton.GroupName == groupName && radioButton.Checked)\n                {\n                    retval = radioButton;\n                    break;\n                }\n            }\n\n            if (retval == null)\n            {\n                retval = GetSelectedRadioButton(control.Controls, groupName);\n            }\n        }\n    }\n\n    return retval;\n}	0
4117653	4117186	How can I retreive all the text nodes of a HTMLDocument in the fastest way in C#?	HtmlElementCollection collection = pageContent.GetElementsByTagName("HTML");\nIHTMLDOMNode htmlNode = (IHTMLDOMNode)collection[0];\nProcessChildNodes(htmlNode);\n\nprivate void ProcessChildNodes(IHTMLDOMNode node)\n{\n    foreach (IHTMLDOMNode childNode in node.childNodes)\n    {\n        if (childNode.nodeType == 3)\n        {\n            // ...\n        }\n        ProcessChildNodes(childNode);\n    }\n}	0
25386752	25057660	How to put a Fez Panda II to 'Sleep' mode via button control?	using Microsoft.SPOT.Hardware;\nusing System;\n\npublic class Program\n{\n    public static void Main()\n    {\n        var interrupt = new InterruptPort(Cpu.Pin.GPIO_Pin0, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeHigh);\n        interrupt.OnInterrupt += interrupt_OnInterrupt;\n\n        PowerState.Sleep(SleepLevel.DeepSleep, HardwareEvent.OEMReserved1);\n\n        ///Continue on with your program here\n    }\n\n    private static void interrupt_OnInterrupt(uint data1, uint data2, DateTime time)\n    {\n        //Interrupted\n    }\n}	0
26804186	15707859	Loading a C++ DLL in C#	using System;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace Company.Group\n{\n    public class FuncList\n    {\n        [DllImport("MarkEzd.dll", EntryPoint = "lmc1_Initial2", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]\n        public static extern int Initialize(string PathName, bool TestMode);\n    }\n}	0
10229916	10229752	Binding a Panel to a Form	new Form()	0
10441650	10440873	How to get the corresponding DataSet row number after filtering a BindingSource	BindingSource.Current	0
19218811	19218686	How can I make a WebProxy Timeout?	WebClient.DownloadFileAsync()	0
6359611	6358215	Select multiple words in a text box and track them in C#	List<string> _Words;\nprivate void richTextBox1_MouseUp(object sender, MouseEventArgs e)\n{\n    richTextBox1.SelectionBackColor = Color.DeepPink;\n    _Words.Add(richTextBox1.SelectedText);\n}	0
24929628	24928758	Multiple classes against the same interfaces in Unity Container	container.RegisterType(typeof(IRunAtStartup), type, type.AssemblyQualifiedName);	0
11418982	11416367	How to get databounded ComboBox to reflect changes made to a BindingList datasource	private BindingSource bs;\n\nprivate SetupBinding()\n{\n    List<Item> data = new List<Item>();\n\n\n    //Get Data \n\n\n\n    bs = new bindingsource();\n    bs.datasource = data;\n    combobox.datasource = bs;\n    comboBox.DisplayMember="Name";\n    comboBox.ValueMember="IDNumber";\n}\n\nprivate ShowMyMessage()\n{\n    MessageBox.Show(this, message, caption, buttons,\n            MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, \n            MessageBoxOptions.RightAlign);\n if (bs != null)\n {\n   bs.resetbindings(false);\n }\n}	0
19276588	19276475	How can I convert string value to object property name	PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");\nobject value = pinfo.GetValue(YourInstantiatedObject, null);	0
27760940	27488169	How does one change a message for an event in Semantic Logging Application Block	[Event(1, Message = "New Message: {0}", Version = 1)]\npublic void Starting(string name)\n{\n    WriteEvent(1, name);\n}	0
21631834	21631725	How to use groupby in linq sql	var levels = ids.\n    GroupBy(f => f.Id).\n    ToDictionary(\n        g => g.Key,\n        g => g.First(i => i.Name.Last() == g.Max(j => j.Name.Last())).Name);	0
33918489	33917646	Delete column and its values from datatable using C#	dataTableName.Columns.Remove("ColumnName");	0
31294210	31293144	Get the value from ListBox C#	class Program\n    {\n        static void Main(string[] args)\n        {\n            List<string> list = new List<string>();\n            list.Add("First");\n            list.Add("second");\n            list.Add("third");\n\n            Dictionary<int, string> dictionary = new Dictionary<int, string>();\n\n            dictionary.Add( 1,"First");\n            dictionary.Add(2,"second");\n\n            foreach (var li in list)\n            {\n\n                if (!dictionary.ContainsValue(li))\n                {                  \n                    Console.WriteLine(li);\n                }\n            }\n            Console.ReadLine();\n        }\n    }	0
5623762	5623690	How to get value from combobox in c#?	cmb1.SelectedValue = data.ID;	0
8009448	8005770	How do I remove a specific panel through event handling in my FlowlayoutPanel for my Windows Form Application?	void buttonClear_Click(object sender, EventArgs e)\n{\n    var panel = nFlowPanel.Controls["notifyPanel"];\n    panel.Dispose();\n}	0
13607595	13607277	How to convert array of floats to byte array and send them in endianness over UDP?	byte[] array=null;\n    List<float> myData = new List<float>();\n    myData.Add(43.1f);\n    myData.Add(42.1f);\n    myData.Add(41.1f);\n    myData.Add(40.1f);\n    foreach (float a in myData)\n       array = BitConverter.GetBytes(a);\n    //printing\n    for (int i = 0; i < array.Length; i++)\n    {\n        Console.WriteLine(array[i]);\n    }	0
11776342	11773636	How to split a Word document by specific text using C# and the Open XML SDK?	private static void RemoveItem3(Text textfield)\n    {\n        OpenXmlElement element = textfield;\n        while (!(element.Parent is DocumentFormat.OpenXml.Wordprocessing.Body) && element.Parent != null)\n        {\n            element = element.Parent;\n        }\n\n        if (element.Parent != null)\n        {\n            element.Remove();\n        }\n    }	0
13161332	13161285	Replace byte in a int	int ReplaceByte(int index, int value, byte replaceByte)\n{\n    return (value & ~(0xFF << (index * 8))) | (replaceByte << (index * 8));\n}	0
8134090	5890346	Element column length isn't respected when auto mapping a dictionary using Fluent NHibernate	HasMany<MyEntity>(n => n.MyDictionary)\n  .AsMap<string>(\n      index => index.Column("LCID").Type<int>(),\n      element => element.Columns.Clear().Columns.Add("Value", col => col.Length(1000))\n  .Cascade.AllDeleteOrphan();	0
31936631	31928835	Creating an Autocad Solid 3D from a list of vertices	Solid3d.CreateSculptedSolid	0
30529755	30529606	Find Iframe inside div in WatIn	WebBrowser wb = new WebBrowser();\n    wb.Navigate("yourpage");\n    //when document loaded\n\n    wb.Document.Window.Frames[0].Document.GetElementsByTagName("input")[0].InvokeMember("Click");	0
11950914	11950329	How to use Task.WhenAll() correctly	List<Task<BusRoute>> routeRetrievalTasks = new List<Task<BusRoute>>();\n        foreach (BusRouteIdentifier bri in stop.services)\n        {\n            BusRouteRequest req = new BusRouteRequest(bri.id);\n            routeRetrievalTasks.Add(BusDataProviderManager.DataProvider.DataBroker.getRoute(req));\n        }\n\n        foreach (var task in routeRetrievalTasks)\n        {\n            var route = await task;\n            this.routes.Add(route); // triggers events\n        }	0
31919487	31906855	How to send array via Bluetooth Low Energy in Windows Desktop APP?	private async void Discover_Click(object sender, EventArgs e)\n    {\n        var Services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")));\n        GattDeviceService Service = await GattDeviceService.FromIdAsync(Services[0].Id);\n        GattCharacteristic gattCharacteristic = Service.GetCharacteristics(new Guid("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"))[0];\n\n        var writer = new DataWriter();\n        writer.WriteString("#FF00FF");\n        var res = await gattCharacteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);\n    }	0
23618102	23617921	Array to new string	static string GenerateCoupon(Random r)\n    {\n        string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";\n        int size = 4;\n\n        char[] code1 = new char[size];\n        char[] code2 = new char[size];\n        char[] code3 = new char[size];\n        for (int i = 0; i < size; i++)\n        {\n            code1[i] = Alphabet[r.Next(Alphabet.Length)];\n            code2[i] = Alphabet[r.Next(Alphabet.Length)];\n            code3[i] = Alphabet[r.Next(Alphabet.Length)];\n        }\n\n        string code4 = new string(code1);\n        string code5 = new string(code2);\n        string code6 = new string(code3);\n\n        return string.Format("{0}-{1}-{2}", code4, code5, code6);\n    }\n\n    static void Main(string[] args)\n    {\n        Random rnd = new Random();\n        for (int i = 0; i < 100;i++ )\n            Console.WriteLine(GenerateCoupon(rnd));\n         Console.ReadLine();\n\n    }	0
24575193	24574609	How to close a worker thread early	protected Thread tDownloader;\n...\n\nif(tDownloader == null || tDownloader.ThreadState == ThreadState.Unstarted || tDownloader.ThreadState == ThreadState.Stopped)\n{\n    tDownloader = new System.Threading.Thread(() => { \n    ...TODO...\n    });\n    ....\n    tDownloader.Start();\n}	0
11879425	11879291	Finding an element using name/type attribute in DefaultSelenium	Selenium.Click("//div/input[@class='btnSubmit']");	0
3293836	3293739	Repeater ItemTemplate Server Side	rptList.ItemDataBound += rptList_ItemDataBound;\n\nprivate void rptList_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)\n{   \n    if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;\n\n    HtmlControls.HtmlGenericControl RepeaterBG = (HtmlControls.HtmlGenericControl)e.Item.FindControl("RepeaterBG");\n\n    Data.DataRowView dr = (Data.DataRowView)e.Item.DataItem;\n\n    RepeaterBG.Style.Add("background-color", dr("ContentBackground"))\n}	0
27319831	27301977	MVC4 Unit test NSubstitute Could not find a call to return from	var context = Substitute.For<MyCoolApplicationsEntities>();\n\nvar applications = new List<Application>\n{\n    new Application {AppID = 1, ApplicationName = "MyCoolApplication"}\n};\n\nvar mockApplications = Substitute.For<DbSet<Application>, IQueryable<Application>>();\n((IQueryable<Application>)mockApplications).Provider.Returns(applications.AsQueryable().Provider);\n((IQueryable<Application>)mockApplications).Expression.Returns(applications.AsQueryable().Expression);\n((IQueryable<Application>)mockApplications).ElementType.Returns(applications.AsQueryable().ElementType);\n((IQueryable<Application>)mockApplications).GetEnumerator().Returns(applications.AsQueryable().GetEnumerator());\n\nmockApplications.When(q => q.Add(Arg.Any<Application>()))\n    .Do(q => applications.Add(q.Arg<Application>()));\n\nmockApplications.When(q => q.Remove(Arg.Any<Application>()))\n    .Do(q => applications.Remove(q.Arg<Application>()));\n\ncontext.Applications = mockApplications;	0
17116407	17116358	Implicit cast of Func<MyType> to MyType	Func<MyType>	0
24136902	24136745	Insert dates from textbox without error if a date is missing	DateTime date = new DateTime();\n\nif(DateTime.TryParse(textBox1.Text, out date))\n{\n    //The text is a valid date\n    //Insert it\n}	0
12159816	12159538	WebBrowser control has getting odd state	webBrowser1.DocumentCompleted += (d1, d2) => \n                {\n\n\n                    string urlCurrent = d2.Url.ToString();\n                    var browser = (WebBrowser)d1;\n\n                    if (!(urlCurrent.StartsWith("http://") || urlCurrent.StartsWith("https://")))\n                    {\n                        // in AJAX     \n                    }\n                    if (d2.Url.AbsolutePath != browser.Url.AbsolutePath)\n                    {\n                        // IFRAME           \n                    }\n                    else\n                    {\n                        // REAL DOCUMENT COMPLETE\n\n                        Debug.WriteLine("DocumentCompleted " + DateTime.Now.TimeOfDay.ToString());\n                    }\n\n                };	0
24772941	24772882	Selecting an object from a list based on the name	var tableobj = from table in tableOfObjects\n                       where table.ToString().Contains(objName)\n                       select table;	0
6733923	6733740	Reading textareas in datalist within itemcommand	protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)\n{\n if (e.CommandName == "SaveDescription")\n    {\n    DataListItem item = ((DataListItem)((ImageButton)e.CommandSource).NamingContainer);\n    TextBox description = (TextBox)item.FindControl("description");\n    description.Text // return your text \n    }\n}	0
17178215	17178118	Prevent multiple instances in server same username	bool b = true;\nMutex mutex = new Mutex(true, Environment.UserName.ToLowerInvariant() , out b);\nif (!b) throw new InvalidOperationException("Another instance is running");	0
23677661	23677648	Best .net framework version to work with Windows xp,7,8 without installing or updating it seperately	.NET Framework 1.1: Windows Server 2003\n.NET Framework 2.0: Windows Server 2003 R2\n.NET Framework 3.0: Windows Vista, Windows Server 2008\n.NET Framework 3.5: Windows 7, Windows Server 2008 R2\n.NET Framework 4.0: n/a\n.NET Framework 4.5: Windows 8, Windows Server 2012	0
16924693	16924487	Change Web API Response Formatter	public XmlDocument Get(int id)\n{\n    XmlDocument doc;\n    doc = repo.get(id); // simplified\n\n    if(doc != null)\n        return doc;\n\n    throw new HttpResponseExeption(\n        Request.CreateResponse(HttpStatusCode.NotFound, new HttpError("Something went terribly wrong."), Configuration.Formatters.JsonFormatter));\n}	0
3082505	3068303	FileUpload to FileStream	public static byte[] ReadFully(Stream input)\n{\n    byte[] buffer = new byte[input.Length];\n    //byte[] buffer = new byte[16 * 1024];\n    using (MemoryStream ms = new MemoryStream())\n    {\n        int read;\n        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n        {\n            ms.Write(buffer, 0, read);\n        }\n        return ms.ToArray();\n    }\n}	0
1488139	1488099	call an eventhandler with arguments	public void downloadphoto(string struri, string strtitle, string placeid)\n{\n    using (WebClient wc = new WebClient())\n    {\n        wc.DownloadDataCompleted += (sender, args) => \n            DownloadDataCompleted(strtitle, placeid, args);\n        wc.DownloadDataAsync(new Uri(struri));\n    }\n}\n\n// Please rename the method to say what it does rather than where it's used :)\nprivate void DownloadDataCompleted(string title, string id, \n                                   DownloadDataCompletedEventArgs args)\n{\n    // Do stuff here\n}	0
8257785	8257395	Avoiding same key error in dictionary with a suffix	var source = new List<Tuple<string, string>>\n        {\n            new Tuple<string, string>("a", "a"),\n            new Tuple<string, string>("a", "b"),\n            new Tuple<string, string>("b", "c"),\n            new Tuple<string, string>("b", "d"),\n        };\n\n        var groups = source.GroupBy(t => t.Item1, t => t.Item2);\n\n        var result = new Dictionary<string, string>();\n\n        foreach (var group in groups)\n        {\n            int index = 0;\n\n            foreach (var value in group)\n            {\n                string key = group.Key;\n\n                if (index > 0)\n                {\n                    key += index;\n                }\n\n                result.Add(key, value);\n\n                index++;\n            }\n        }\n\n        foreach (var kvp in result)\n        {\n            Console.WriteLine("{0} => {1}", kvp.Key, kvp.Value);\n        }	0
13018372	13018222	How do you take the contents of a combo box and add them to an array?	string[] items = new string[currentComboBox.Items.Count];\n\n   for(int i = 0; i < currentComboBox.Items.Count; i++)\n   {\n       items[i] = currentComboBox.Items[i].ToString();\n   }	0
14370498	14370227	How to copy selected ListBox1 item to ListBox2 list at the same index?	foreach (int selectedItemInd in listBox1.SelectedIndices)\n        {\n            selectedItemIndexes.Add(selectedItemInd);\n        }	0
4164275	4164190	How to save Graphics object as image in C#?	private void button1_Click(object sender, EventArgs e) {\n        using (var bmp = new Bitmap(panel1.Width, panel1.Height)) {\n            panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));\n            bmp.Save(@"c:\temp\test.png");\n        }\n    }	0
10882745	10790700	Cannot add more than one row to datagrid with different colors WPF c#	if ((DateTime.TryParse(item.DueDate.ToString(), out dateValue) == true) && row != null)	0
13876277	13875988	Currency code comes with Unicode while export to excel	Response.Charset = "";\nResponse.ContentEncoding = System.Text.Encoding.Default;	0
24144092	24143451	Splitting a string array based on a word C#	string testCase =  "Number 1 asdf asdfn asfm;lamf --- Information Number 2 asdf asdfn asfm;lamf --- Information Number 3 asdf asdfn asfm;lamf --- Information";\n\n        string[] numbers = Regex.Split(testCase, "Number").Where(s => s.Trim() != "" && s != "Number").Select(x => "Number" + x).ToArray();	0
3455510	3455504	Sum selected rows in datatable only?	dataTable.Compute("sum(amount)", "status = 1")	0
17450137	17450060	Passing a method as an argument in another method	private void sqlQuery(Action action)\n{\n    conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;\n    try\n    {\n        //open SQL connection\n        conn.Open();\n\n        action();\n    }\n    catch (Exception ex)\n    {\n        System.Diagnostics.Debug.Write(ex.ToString());\n    }\n    finally\n    {\n        conn.Close();\n    }\n}	0
19578876	19578858	How to change label font in code behind using c#	label1_Fail.ForeColor = Color.Red;	0
28782979	28782947	adding numbers from and EditText to and TextView	btnCalc.Click += (object sender, EventArgs e) => {\n        totalScore = Convert.ToInt32(input1.Text) + Convert.ToInt32(input2.Text);\n        total.Text = totalScore.ToString();\n    };	0
33529013	33528909	How to get a Nullable<T> instance's type	public static void Main()\n{\n    int? i = 2;\n    Console.WriteLine( type(i) );\n}\n\npublic static Type type<T>( T x ) { return typeof(T); }	0
12920089	12919794	Method that is Recursive that Checks to see if an Employee is a Boss	//Assume managerName is "Mark" and employeeName is "Jim", as in your example above\npublic bool isManagerValid(string managerName, string employeeName)\n{\n    bool valid = true;\n    var manager = getEmployee("Mark"); //The "to-be" manager of Jim\n    var employee= getEmployee("Jim");\n\n    var currentManager = getEmployee(manager.Manager); //Get Marks manager\n    while(currentManager != null && valid)\n    {\n        if(currentManager == employee)\n        {\n            valid = false; //Some manager up the line from Mark is already Jim \n        }\n        else\n        {\n            //Get the next manager up\n            currentManager = getEmployee(currentManager.Manager);\n        }\n    }\n    return valid;\n}	0
27343587	27343192	Access model variables in entire project MVC5 Razor - use Basecontroller to set BaseViewModel and use that in Layout	public override void OnActionExecuting(ActionExecutingContext filterContext)\n{\n    var controller = filterContext.Controller as BaseController;\n\n    // IController is not necessarily a Controller\n    if (controller != null)\n    {\n        ALM_APP objALM_APP = new ALM_APP();\n        objALM_APP = DalContext.getAppInformation();\n\n        controller.ViewBag.ApplicationName = objALM_APP.ApplicationName;\n        controller.ViewBag.AppVersion = objALM_APP.Version;\n\n     }\n}	0
16214628	16184956	Opening a web page in a non-elevated browser from an elevated process C#	public static void GoURL(string url)\n{\n string sysPath = Environment.GetFolderPath(Environment.SpecialFolder.System);\n                string ExplorerPath = Path.Combine(Directory.GetParent(sysPath).FullName,\n                                                      "explorer.exe");\n                string TempDir = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);\n                string shortcutPath = Path.Combine(TempDir, "Mylink.url");\n                urlShortcutToTemp(url, shortcutPath);\n                System.Diagnostics.Process.Start(ExplorerPath, shortcutPath);\n}\n\nprivate static void urlShortcutToTemp(string linkUrl, string shortcutPath)\n        {\n            using (StreamWriter writer = new StreamWriter(shortcutPath))\n            {\n                writer.WriteLine("[InternetShortcut]");\n                writer.WriteLine("URL=" + linkUrl);\n                writer.Flush();\n            }\n        }	0
19257545	19257442	Get newest file from each directory	List<string> list = getNewestFile(path);\nlist.Add(path);              //Add current directory to list as well\nforeach (string dir in list) //..etc	0
13512475	13512274	Search for filename on Server	string folder = Server.MapPath("Upload");\nforeach (var filePath in Directory.GetFiles(folder, "*excel*"), SearchOption.TopDirectoryOnly)\n{\n    FileInfo fi = new FileInfo(filePath);\n    if ((DateTime.Now - fi.CreationTime).TotalDays > 30)\n    {\n        File.Delete(filePath);\n    }\n}	0
8500907	8447780	How to get SearchBoxEx instance to modify its properties?	//get the web part:\nSPLimitedWebPartManager webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);\nSPLimitedWebPartCollection webParts = webPartManager.WebParts;\nvar searchBoxWebPart = (from System.Web.UI.WebControls.WebParts.WebPart webPart in webParts\n                        where (webPart.Title.Equals("Search Box"))\n                        select webPart).First();\n\n//cast:\nSearchBoxEx searchBox = (SearchBoxEx)searchBoxWebPart;	0
26634339	26633690	Unable to Read XML using C# and XmlDocument	XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());\nmgr.AddNamespace("d", "urn:omds20");\nXmlNode XMLContentNodes = doc.SelectSingleNode("/d:OMDS/d:PAKET", mgr); \nXmlNodeList PersonNodeList = XMLContentNodes.SelectNodes("d:PERSON", mgr);	0
10303999	10303941	regex for parsing url from html code	public static bool isValidUrl(ref string url)\n{\n    string pattern = @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";\n    Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);\n    return reg.IsMatch(url);\n}	0
15027007	15017928	DateTime.Now convert to SQLDatetime using Entity Data Model	public class Carton_Details\n{\n    public DateTime DateOfSub { get; set; }\n\n    public Carton_Details()\n    {\n        this.DateOfSub = DateTime.Now;\n    }\n}	0
3771116	3770874	How to return selected items from checkboxlist control in asp.net	protected void Page_Load(object sender, EventArgs e)\n        {\n            if(!IsPostBack)\n            {\n                var dt = new DataTable();\n                dt.Columns.Add("Users");\n\n                const string str = "User {0}";\n                for(var i=1;i<=10;i++)\n                {\n                    //var r = dt.NewRow();\n                    //r.ItemArray=new object[]{string.Format(str,i)};\n                    dt.Rows.Add(new object[] {string.Format(str, i)});\n                }\n                list1.DataSource = dt;\n                list1.DataTextField = "Users";\n                list1.DataBind();\n            }\n        }\n\n        protected void btn_Click(object sender, EventArgs e)\n        {\n            var s = list1.Items.Cast<ListItem>()\n                   .Where(item => item.Selected)\n                   .Aggregate("", (current, item) => current + (item.Text + ", "));\n            lbl.Text = s.TrimEnd(new[] {',', ' '});\n        }	0
28224126	28224043	C# Find offset of byte pattern, check specific byte, change byte, export part of byte array	if(bytes[IndexCamera+2] == 0x08)....	0
18911091	18910787	How to Create Two level enum	public static class MeterType\n{\n    public const int Water = 1001;\n    public const int Electricity = 1004;\n    public const int Gas = 1007;\n\n    public static class Waters\n    {\n        public const int DrinkingWater = 1002;\n        public const int UsageWater = 1003;\n    }\n\n    public static class Gases\n    {\n        public const int SubsidiseGas = 1008;\n        public const int NonSusbsidisedGas = 1009;\n    }\n}	0
4958440	4926235	How to localize SharePoint publishing page title	newPage.Title = \n    SPUtility.GetLocalizedString(\n        "$Resources:MyPage_PageTitle", \n        "MYRESX", \n        web.Language);	0
7081426	7069227	Issue with opening Child window from Main window using WPF with MVVM	public partial class FileListView: Window\n{\n  private FileListViewModel  _ fileListViewModel = new FileListViewModel ();\n  public FileListViewModel () \n  {\n    InitializeComponent();\n    base.DataContext = _fileListViewModel; \n  }\n}	0
4245831	4245816	How to create a subclass in C#?	public class Foo\n{}\n\npublic class Bar : Foo\n{}	0
10200126	10198171	Enable Submit/Cancel button through WPF Command pattern	private bool IsOkToExecute\n    {\n        get { return _isOkToExecute; }\n        set\n        {\n            _isOkToExecute = value;\n            RaisePropertyChanged("IsOkToExecute");\n        }\n    }\n\n     private void myOkExecute (object parameter)\n     {\n        IsOkToExecute = false;\n     }\n\n    private void myCancelExecute(object parameter)\n     {\n         IsOkToExecute = true;\n     }\n\nprivate bool myCanOkExecute(object parameter)\n{\n    return IsOkToExecute;\n}\n\nprivate bool myCanCancelExecute(object parameter)\n{\n    return !IsOkToExecute;\n}	0
13585305	13585036	'Normalizing' Probability Array	double[] doubleArray = new double[] { 25, 25 ,25, 10, 15 }; //or any other array\ndouble temp = 100-doubleArray[4]; //or any other specific value in the array\ndoubleArray[4] = 0;\nfor (int i; i<doubleArray.length; i++) {\n    doubleArray[i] = doubleArray[i]/temp*100;\n}	0
32915700	32902360	How to retrive only specific fields form MongoDB using C#	var db = database.GetCollection<BsonDocument>("cars");\n\n        FieldDefinition<BsonDocument, string> field = "car.manufacture";\n        FilterDefinition<BsonDocument> filter = new BsonDocument();\n\n        var a = db.DistinctAsync(field, filter).GetAwaiter().GetResult().ToListAsync().GetAwaiter().GetResult();	0
4209264	4208438	I want to edit xml file	bool foobar()\n    {\n        XmlDocument doc = new XmlDocument();\n        try\n        {\n            doc.Load(FileName);\n            XmlNodeList ns = doc.SelectNodes("a/d/e/f");\n            if (ns.Count == 1)\n            {\n\n                    ns[0].Attributes["visible"].Value = true;\n                    doc.Save(FileName);\n                    return (true);\n            }\n            else\n                return (false);\n        }\n        catch (Exception e)\n        {\n            return (false);\n        }\n    }	0
13951395	13950598	WatiN c# Validation of page for multiple content	// do this for each rfv\nWatiN.Core.Span rfvAddress1Line1 = Document.Span("ctl00_Container_rfvAddress1Line1");\nAssert.IsTrue(rfvAddress1Line1.Exists);\nAssert.AreEqual("Some Error Message", rfvAddress1Line1.Text);\n\n// alternatively, if all of the messages were the exact same, you could do this\nvar spans = Document.Spans.Where(s => s.Text == "Some Error Message");\nAssert.AreEqual(4, spans.Count());	0
30700151	30700107	How to i make my print command stop print whats after a semi-colon?	String input = TB.Text;\n       if (input.ToLowerInvariant().StartsWith("print: "))\n        {\n            String print = input.Substring(input.IndexOf(' ') + 1);\n\n            MessageBox.Show(print.Split(';')[0], "Console");\n        }	0
26805011	26804968	How to set data-attribues with ASP.NET?	pnl.Attributes("data-attribute") = "200"	0
5124081	5124042	ODBC Schema - How Do I Find Relationships?	'ForeignKeys'	0
6284554	6284508	How can I find all the commented lines in the entire solution?	(^|[^/])//[^/]	0
14587923	14587835	Dropdown list value to Int to database - Invalid Cast Exception was caught	comm.Parameters.Add(comm);	0
5422036	5421972	How to find the 3rd Friday in a month with C#?	DateTime thirdFriday= new DateTime(yourDate.Year, yourDate.Month, 15);\n\nwhile (thirdFriday.DayOfWeek != DayOfWeek.Friday)\n{\n   thirdFriday = thirdFriday.AddDays(1);\n}	0
3757662	3757610	How to get "One -one" permutation string from a List<String> in C# using LINQ	var items = new List<string>{ "A,B" , "C,D,E" , "F,G" };\nvar results = from x in items\n              let y = x.Split(',')\n              from z1 in y\n              from z2 in y\n              where z1 != z2\n              select string.Format("{0}-{1}", z1, z2);	0
568361	568347	How do I use Linq to obtain a unique list of properties from a list of objects?	IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();	0
33438809	33438729	How to get class semantic model from class syntax tree?	SemanticModel.GetDeclaredSymbol()	0
9348433	9348372	How can I increment through an IList collection with more than one loop	foreach (var group in menuItems.GroupBy(item => item.Outer))\n{\n    // begin outer menu "group.Key"\n    foreach (var item in group)\n    {\n        // inner menu "item.Inner"\n    }\n    // end outer menu\n}	0
33599950	33599436	Rhino Mocks Stub with a generic interface causes InvalidOperationException	stubRepo.Stub(x => x.Update(Arg<string>.Is.Equal("1"), Arg<Location>.Is.Anything))	0
20632356	20629050	How to find exact word from word document using Open XML in C#?	IEnumerable<Paragraph> paragraphs = document.Body.Descendents<Paragraph>();\nforeach(Paragraph para in paragraphs)\n{\n    String text = para.Descendents<Text>().FirstOrDefault();\n    //Code to replace text with "#"\n}	0
9727438	9727329	NHibernate many-to-many saves duplicate data	var computerTag = new Tag() { Name = "Computer" });\n\nBook book;\nbook = new Book() { Title = "C#" };\nbook.Tags.Add(new Tag() { Name = "Programming" });\nbook.Tags.Add(computerTag);\nPersistenceManager.Save(book);\n\n//At this point (due to your mapping, the computerTag has been persisted\n//and it will have an ID.\n\nbook = new Book() { Title = "Android" };\nbook.Tags.Add(new Tag() { Name = "OS" });\nbook.Tags.Add(computerTag);\nPersistenceManager.Save(book);	0
8798934	8797114	How to get the number of pages count on radgrid	protected void RadGrid1_PreRender(object sender, EventArgs e)   {\n   string str = RadGrid1.PageCount.ToString();   }	0
22282037	22181023	Mono Entity Framework 6 Duplicates	[Column(TypeName = "Date")]	0
8391227	8390689	Getting values from different classes	class Player: Form\n{\n    public static int myInt = 0;    //This is where the next screen should be.\n\n    /// <summary>\n    /// Constructor.\n    /// </summary>\n    public Player()\n    {\n    }\n\n\n\n    /// <summary>\n    /// Changes MyInt.  Increments myInt so the next corod\n    /// </summary>\n    private void ButtonPressed()\n    {\n        myInt++;\n        //Note, you need to get the screen size and mode it with this to prevent setting the location off screen.\n\n    }\n}\n\nclass Render\n{\n    private Player player;  //Class variable so it persists between calls\n\n    /// <summary>\n    /// Constructor.  Sets player.\n    /// </summary>\n    public Render()\n    {\n        Location = new Point(Player.myInt, Player.myInt);           //Set my coordinate\n    }\n\n    /// <summary>\n    /// Shows the value of this.player.MyInt in a message box.\n    /// </summary>\n    public void rendering_method()\n    {\n        int i = Player.myInt;\n\n        MessageBox.Show("The value is: " + i);\n    }\n}	0
11525054	11524853	Distinct Date with Linq 	var DistinctYearMonthsDays = (from t in db.Billings \n                              where t.DateTime.HasValue \n                              select EntityFunctions.TruncateTime(t.DateTime)).Distinct();	0
32770801	32770658	write text on console and file simultaneously	class Program\n    {\n        static void Main(string[] args)\n        {\n            DualOut.Init();\n            Console.WriteLine("Hello");\n\n\n            Console.ReadLine();\n        }\n    }\n\n    public static class DualOut\n    {\n        private static TextWriter _current;\n\n        private class OutputWriter : TextWriter\n        {\n            public override Encoding Encoding\n            {\n                get\n                {\n                    return _current.Encoding;\n                }\n            }\n\n            public override void WriteLine(string value)\n            {\n                _current.WriteLine(value);\n                File.WriteAllLines("Output.txt", new string[] { value });\n            }\n        }\n\n        public static void Init()\n        {\n            _current = Console.Out;\n            Console.SetOut(new OutputWriter());\n        }\n    }	0
26157885	26155384	Context menu with ListBoxItem	var item = ((MenuItem)sender).DataContext as ItemClass	0
3315476	3315392	Username of a process	public string GetProcessOwner(int processId) \n{ \n    string query = "Select * From Win32_Process Where ProcessID = " + processId; \n    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); \n    ManagementObjectCollection processList = searcher.Get(); \n\n    foreach (ManagementObject obj in processList) \n    { \n        string[] argList = new string[] { string.Empty, string.Empty }; \n        int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); \n        if (returnVal == 0) \n        { \n            // return DOMAIN\user \n            return argList[1] + "\\" + argList[0]; \n        } \n    } \n\n    return "NO OWNER"; \n}	0
29355250	29354644	Add a variable to Layout page MVC	namespace MyApp.Helpers\n{\n    public static class GetIP\n    {\n        public static string AssignedIPName()\n        {//do custom logic\n        }\n     }\n}	0
103057	103006	What's the easiest way to convert latitude and longitude to double values	String hour = "25";\nString minute = "36";\nString second = "55.57";\nDouble result = (hour) + (minute) / 60 + (second) / 3600;	0
1774125	1771740	How to create a criteria in NHibernate that represents an OR between two EXISTS?	DetachedCriteria dCriteria1 = DetachedCriteria.For<Project>("project")\n    .SetProjection(Projections.Property("project.Id"))\n    .Add(Restrictions.EqProperty("doc.projectId", "project.Id"));\n\nDetachedCriteria dCriteria2 = DetachedCriteria.For<Job>("job")\n           .SetProjection(Projections.Property("job.Id"))   \n           .CreateCriteria("Projects", "p")\n           .Add(Restrictions.EqProperty("doc.jobId", "job.Id"))\n           .Add(Restrictions.Eq("p.code", "somecode"));\n\nvar documents = NHibernateSessionManager.Session.CreateCriteria<Document>("doc")\n    .Add(Restrictions.Or(\n            Subqueries.Exists(dCriteria1),\n        Subqueries.Exists(dCriteria2))).List<Document>();	0
1890976	1890955	Getting the same element without changing it using Linq	Traverse(array, e => {});	0
20659789	20625518	How to check web page load on RDP C#	while (IEApp.Busy)\n            {                   \n                Thread.Sleep(1000);\n                Application.DoEvents();\n            }	0
31526204	31525815	Get DataGrid row index of value?	var selectedItem = dataGrid.Items.OfType<People>().FirstOrDefault(q => q.Referrer = _Referrer);\nif (selectedItem != null)\n{\n    // you can get index of this item if you want:\n    // var selectedItemIndex = dataGrid.Items.IndexOf(selectedItem);\n\n    dataGrid.SelectedItem = selectedItem;\n}	0
28847781	28847567	How to iterate date in for loop?	DateTime date=DateTime.ParseExact("04/03/2015","dd/MM/yyyy",CultureInfo.InvariantCulture);\n    DateTime totaldate = date.AddDays(6);\n    for (int i=0; date <= totaldate; date = date.AddDays(1),i++)//total working days \n     {\n\n         if((i/2)%2==0)\n              Console.WriteLine(date+" "+1);\n         else\n              Console.WriteLine(date+" "+2);\n     }	0
8215886	8215833	How to load a type from the type's name and the assembly's name	Type.GetType(string.Concat(typeName, ", ", assemblyName))	0
6283609	6283328	Format String : Parsing	var str = ":  first  :  second  ";\nvar result = Regex.Replace(str, ":\\s{2}(?<word>[a-zA-Z0-9]+)\\s{2}",\n                                                         ":\n${word}\n");	0
4857360	4822952	Decode & from &amp; from XML with ToString()	string amp = "Before & After";\n        XmlDocument doc = new XmlDocument();\n\n        StringBuilder sb = new StringBuilder();\n        StringWriter stringWriter = new StringWriter(sb);\n        XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);\n\n        xmlWriter.WriteStartElement("amp");\n        xmlWriter.WriteString(amp);\n        xmlWriter.WriteEndElement();\n\n        StringReader valueStringReader = new StringReader(sb.ToString());\n        XmlTextReader valueXmlReader = new XmlTextReader(valueStringReader);\n\n        valueXmlReader.MoveToContent();\n\n        global::System.Windows.Forms.MessageBox.Show(valueXmlReader.ReadString());	0
3877567	3876436	Property Injection into an Action Filter	SetAllProperties(x => x.OfType<IMarketService>());	0
1441906	1441870	How to solve base Controller dependency injection for testing purposes?	public HomeController(ISessionHelper session, IUserRepository repo)\n  : base(session, repo)\n    {\n\n    }	0
11064325	11064236	How Start Methods With Arguments Using Thread	Thread thread = new Thread(new ThreadStart(() => WorkThreadFunction(a, b)));	0
19422223	19422172	Dividing a list of strings	list = list.SelectMany(s => new [] { s.Substring(0, 20), s.Substring(20, 20) })\n           .ToList();	0
10829846	10829732	How can I calculate the numbers of month between two dates in C#	int months = (Date2.Year - Date1.Year) * 12 + Date2.Month - Date1.Month;	0
10629808	10629777	ForeColor with codes color	HyperLink hpl = new HyperLink();\nhpl.Text = "SomeText";\nhpl.ForeColor = System.Drawing.ColorTranslator.FromHtml("#5BB1E6");	0
34113271	34113160	How to make cpu-friendly infinite loop for mono when detached from terminal	UnixSignal [] signals = new UnixSignal[] { \n            new UnixSignal(Signum.SIGINT), \n            new UnixSignal(Signum.SIGTERM), \n        };\n\n        // Wait for a unix signal\n        for (bool exit = false; !exit; )\n        {\n            int id = UnixSignal.WaitAny(signals);\n\n            if (id >= 0 && id < signals.Length)\n            {\n                if (signals[id].IsSet) exit = true;\n            }\n        }	0
998520	998506	how can i list every path in a directed graph? (C#)	Step 1. [n1]\nStep 2. [n2(n1), n3(n1)]\nStep 3. [n3(n1), n4(n1,n2)]\nStep 4. [n4(n1, n2), n4(n1, n3)]\nStep 5. [n4(n1, n3), n5(n1, n2, n4), n6(n1, n2, n4), n10(n1, n2, n4)]\nStep 6. [n5(n1, n2, n4), n6(n1, n2, n4), n10(n1, n2, n4), n5(n1, n3, n4), n6(n1, n3, n4), n10(n1, n3, n4)]	0
18654583	18654446	How to get property in code behind in ASP.NET?	public bool iscollect {\n    get {return (bool)(ViewState["iscollect"] ?? false)}\n    set { ViewState["iscollect"] = value; }\n}\n\nprotected void btnContinue_Click(object sender, EventArgs e)\n{\n    iscollect = Convert.ToBoolean(Personal.Attributes["iscollect"]);\n\n    if (iscollect)\n    {\n        Personalcollect.Visible = true;\n        SavecollectDetails();\n    }\n}\n\n\n<table width="100%" border="0" align="center" runat="server" id="Personal" iscollect="<%=iscollect%>">\n    <tr><td><btn:collection ID="collect" runat="server" /></td></tr>\n</table>	0
34286632	34284114	how to concatenate 2 wave files in Stream?	WaveFileReader wavFileReader = new\nWaveFileReader(outputSound);	0
2107864	2107845	Generics in C#, using type of a variable as parameter	// For non-public methods, you'll need to specify binding flags too\nMethodInfo method = GetType().GetMethod("DoesEntityExist")\n                             .MakeGenericMethod(new Type[] { t });\nmethod.Invoke(this, new object[] { entityGuid, transaction });	0
1699184	1698355	Detect marker in 2D image	rho = x*cos(theta) + y*sin(theta)	0
3762807	3760736	Dispay specific items in dropdown list based on condition	Private Sub MyDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyDropDownList.DataBound\n    For x As Integer = MyDropDownList.Items.Count - 1 To 0 Step -1\n        If RemoveToBeReviewed()\n            If MyDropDownList.Items(x).Text = "To Be Reviewed" Then\n                MyDropDownList.Items.RemoveAt(x)\n            End If\n        End If\n    Next\nEnd Sub	0
23911123	23910706	Updating gridview row adds new record instead of updating the row	string query = "update Employee set EmployeeName=@enm,Address=@address, DateOfBirth= \n @dob, Salary=@salary,Gender=@gender where EmployeeID=@EmpID" \n\n                cmd = new SqlCommand(query, con);\n                cmd.Parameters.AddWithValue("@EmpID", EmpID);\n                cmd.Parameters.AddWithValue("@enm", EmpName);\n                cmd.Parameters.AddWithValue("@address", address);\n                cmd.Parameters.AddWithValue("@dob", dob);\n                cmd.Parameters.AddWithValue("@salary", salary);\n                cmd.Parameters.AddWithValue("@gender", gender);\n\n\n                count = cmd.ExecuteNonQuery();	0
26961249	26961009	Get value from a dynamically loaded DLL	Type myType = form.GetType();\nIList<FieldInfo> fields = new List<FieldInfo>(myType.GetFields());\n\nobject fValue;\nforeach (FieldInfo f in fields)\n{\n    if(f.Name == "dllTitle")\n    {\n        fValue = f.GetValue(form);\n        break;\n     }\n}	0
27830222	27829993	How to test if a type is abstract?	using System.Reflection;\ntype.GetTypeInfo().IsAbstract;	0
7669474	7669182	WP7 - Local DB - ManyToMany Linq2SQL	Hotel h = dc.Hotels.First(); // Pick a hotel\nList<ScheduledFlight> l = h.HotelToScheduledFlight.Select(i => i.ScheduledFlight).ToList();	0
28979018	28978999	Using int? as a member variable vs. a local variable	int? mMax = null;\nint? mMin = null;	0
26464955	26464811	A generic GDI+ error occured at ConvertTo	byte[] byteImg = (byte[])converter.ConvertTo(original.Clone(), typeof(byte[]));	0
22398149	22398018	Very last exit point of application	static void OnProcessExit (object sender, EventArgs e)\n{\n    Process.Start("shutdown", "/s /t 00");\n}	0
28169743	28169295	Disabling all Fields on a Form in CRM 2015	Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {    \n    var control = Xrm.Page.getControl(attribute.getName());\n    if (control) {\n        control.setDisabled(true)\n    }\n});	0
20356071	20074175	How to require Username Password and CompanyId on WebSecurity.Login in MVC 4 application using Simple membership	public static bool ValidateUser(string username, string password, string companyName)\n    {\n        int companyId = MyRepository.GetCompanyIdByName(companyName);\n\n        int? userId = companyId == 0 ? null : MyRepository.GetUserId(username, companyId);\n\n        if (userId.HasValue && userId.Value != 0)\n        {\n            var userKey = username + "@" + companyName.ToLower();\n            return WebSecurity.Login(userKey, password);\n        }\n        else\n        {\n            return false;\n        }\n    }	0
23783555	23783420	How to let a Select on a navigationproperty return a array in Linq To Entities	query.Select(p => new {\n    Id = p.Id,\n    TaskIds = p.Tasks.Select(t => t.TaskId)\n})\n.AsEnumerable()  // <-- SQL translation up to here. Anything after is done in-memory\n.Select(p => new DataObject() {\n    Id = p.Id,\n    TaskIds = TaskIds.ToArray()\n})	0
24704958	24703430	Converting decimal number to hexadecimal number using recursive method	static string Int2Hex( int value )\n{\n  if ( value <  0 ) throw new ArgumentOutOfRangeException("value") ;\n  if ( value == 0 ) return "0" ;\n\n  string result = ToHex( (uint) value ).ToString() ;\n  return result ;\n}\n\nstatic StringBuilder ToHex ( uint value )\n{\n  StringBuilder buffer ;\n  if ( value <= 0 )\n  {\n    buffer = new StringBuilder() ;\n  }\n  else\n  {\n    buffer = ToHex( value / 16 ).Append( "0123456789ABCDEF"[ (int)(value % 16 ) ] ) ;\n  }\n  return buffer ;\n}	0
3500583	3500526	XML Lambda query in C#	string input = "<?xml version=\"1.0\" encoding=\"utf-8\"?><S xmlns=\"http://server.com/DAAPI\"><TIMESTAMP>2010-08-16 17:25:45.633</TIMESTAMP><MY_GROUP><GROUP>1 </GROUP><NAME>Amsterdam</NAME>....</MY_GROUP><MY_GROUP><GROUP>2 </GROUP><NAME>Ireland</NAME>....</MY_GROUP><MY_GROUP><GROUP>3 </GROUP><NAME>UK</NAME>....</MY_GROUP></S>";\n\nvar doc = XDocument.Parse(input);\n\nXNamespace ns = "http://server.com/DAAPI";\n\n//The first question\nvar name = (from elem in doc.Root.Elements(ns + "MY_GROUP")\n            where elem.Element(ns  + "GROUP") != null    //Checks whether the element actually exists - if you KNOW it does then it can be removed\n                && (int)elem.Element(ns + "GROUP") == 1  //This could fail if not an integer - insure it is if nessasary\n            select (string)elem.Element(ns + "NAME")).SingleOrDefault();	0
2744097	2446352	Sorting a Data Gridview	private void DataGrid1_SortCommand(object source, \n                       System.Web.UI.WebControls.DataGridSortCommandEventArgs e)\n{\n   dgvBookInfo.Sort = e.SortExpression;\n   DataGrid1.DataBind();\n}	0
21721517	21721277	Where is WPF setting GridViewRowPresenter.Columns for GridView	protected internal override void PrepareItem(ListViewItem item)\n{\n    base.PrepareItem(item);\n\n    // attach GridViewColumnCollection to ListViewItem.\n    SetColumnCollection(item, _columns);\n}	0
19914628	19914610	C# Linq spare a double foreach	polygons.SelectMany(p => p.Points).Distinct()	0
11678520	11676159	JSON.NET how to remove nodes	private void removeFields(JToken token, string[] fields)\n{\n    JContainer container = token as JContainer;\n    if (container == null) return;\n\n    List<JToken> removeList = new List<JToken>();\n    foreach (JToken el in container.Children())\n    {\n        JProperty p = el as JProperty;\n        if (p != null && fields.Contains(p.Name))\n        {\n            removeList.Add(el);\n        }\n        removeFields(el, fields);\n    }\n\n    foreach (JToken el in removeList)\n    {\n        el.Remove();\n    }\n}	0
12392465	12392365	Need help creating a Regex that will match certain c# strings that contain json	(\w+)\\?\"\s*\:\s*(\w+)	0
3528876	3528849	Getting the default constructor of a generic abstract class	typeof(Test<>).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)	0
21316099	21316067	Add string before item in listbox	listBox1.Items.Add(string.Format("Name: {0}", person.Name));	0
20150248	20138052	How to send a brokermessage that is a list of other types	BinaryFormatter formatter = new BinaryFormatter();\n        MemoryStream stream = new MemoryStream();\n        Queue<IYodas> q = new Queue<IYodas>();\n        q.Enqueue(new Yoda());\n        q.Enqueue(new Yoda2());\n\n        formatter.Serialize(stream, q);\n        Byte[] package = stream.ToArray();\n\n       // Send broker message using package as the object to send\n       ....\n\n        // Then on the other end (you will need a byte array to object function)\n        Queue<IYodas> result = (Queue<IYodas>)ByteArrayToObject(package);	0
12530032	12529894	Manage flash picture with C# and xml	// Load your XML into an XmlDocument\nXmlDocument doc = new XmlDocument();\ndoc.Load("your file.xml");\n\n// Create a new element and add attributes\nXmlElement newElem = doc.CreateElement("slide");\nnewElem.SetAttribute("jpegURL", "ethumb/t_0001.jpg");\nnewElem.SetAttribute("d_URL", "ethumb/t_0001.jpg");\n// etc...\n\n// Add the new slide to your album element\ndoc.DocumentElement["album"].AppendChild(newElem);\n\n// Save the file to your filesystem\ndoc.PreserveWhitespace = true;\nXmlTextWriter wrtr = new XmlTextWriter("your file.xml", Encoding.Unicode);\ndoc.WriteTo(wrtr);\nwrtr.Close();	0
4322593	4322488	Array of fixed-length BitArrays	List<BitArray> stack = new List<BitArray>(8);\n\npublic FPU()\n{\n    //initialise the stack\n\n    for (int i = 0; i < stack.Capacity; i++)\n    {\n        stack[i] = new BitArray(80);\n    }\n}	0
663990	663942	WPF can only open one window?	public App()\n{\n    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;\n    while (true)\n    {\n        Thread.Sleep(1000);\n        Window window = new Window();\n        window.Show();\n        Thread.Sleep(1000);\n        window.Close();\n    }\n    //Will never get here with this sample code,\n    //but this would be how you close the app.\n    this.Shutdown();\n\n}	0
24795630	24732358	user account name of computer from ip address in C#	public static string GetIP4Address()\n    {\n        string IP4Address = String.Empty;\n\n        foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))\n        {\n            if (IPA.AddressFamily.ToString() == "InterNetwork")\n            {\n                IP4Address = IPA.ToString();\n                break;\n            }\n        }\n\n        if (IP4Address != String.Empty)\n        {\n            return IP4Address;\n        }\n\n        foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))\n        {\n            if (IPA.AddressFamily.ToString() == "InterNetwork")\n            {\n                IP4Address = IPA.ToString();\n                break;\n            }\n        }\n\n        return IP4Address;\n    }	0
22507809	22505079	Select text from a Richtextbox in C#	int textStart = mRtbxOperations.Text.LastIndexOf(@"{",\n                                                 mRtbxOperations.SelectionStart);\nif (textStart > -1) {\n  int textEnd = mRtbxOperations.Text.IndexOf(@"}", textStart);\n  if (textEnd > -1) {\n    mRtbxOperations.Select(textStart, textEnd - textStart + 1);\n    mRtbxOperations.SelectionBackColor = Color.LightBlue;\n  }\n}	0
16596790	15820930	RichEditBox FontSize C# windows store app unresponsive	string currentTextBoxText = null; \ntextBox.Document.GetText(TextGetOptions.None, out currentTextBoxText); \nint textLength = currentTextBoxText.Length - 1; \ncurrentTextBox.Document.GetRange(textLength, int.MaxValue).CharacterFormat.Size = (float)textBoxFontSize;	0
18910331	18910203	Reading xml which has been converted from a recordset	XNamespace ns = "#RowsetSchema";\n\nvar serialNos = XDocument.Load(fileName)\n                .Descendants(ns + "row")\n                .ToDictionary(r => r.Attribute("SerialNo").Value, \n                              r => r.Attribute("c1").Value);	0
15912718	15912632	Splitting up an array of supertype into arrays of subtypes	class X {\n      private ICollection<A> listOfObjects;\n\n    public List<B> GetBs() {\n      return  listOfObjects.OfType<B>().ToList();\n    }\n    public List<C> GetCs() {\n      return listOfObjects.OfType<C>().ToList();\n    }\n  }\n\n  class A {}\n\n  class B : A {}\n\n  class C : A {}	0
32517560	32501683	C# Flurl and HttpClient, no response from REST API	public async Task<IResponse> BulkEnrollRequest(EnrollmentRequestDto enrollmentRequest)\n    {\n        try\n        {\n            var result = await _bulkEnrollUrl.PostJsonAsync(enrollmentRequest).ReceiveJson<SuccessResponse>();\n            return result;\n        }\n        catch (FlurlHttpTimeoutException)\n        {\n            throw new AppleTimeOutException();\n        }\n        catch (FlurlHttpException ex)\n        {\n            return _errorHandler.DeserializeFlurlException(ex);\n        }\n    }	0
5705713	5705634	C# comparing two object values	var lookup = _logsNonDutyStatusChange.ToLookup(l => l.did);\n\nforeach (Logs log in _logsDutyStatusChange)\n{\n    if (lookup.Contains(log.did))\n    {\n        var maxDate = lookup[log.did].Max(l => l.date);\n        log.date = maxDate;\n    }\n}	0
2770847	2770554	Data Validation for Random varying Phone Numbers	static bool IsValidPhoneNumber(string phoneNumber)\n{\n    return !string.IsNullOrEmpty(phoneNumber)\n        && (phoneNumber.Length <= 25)\n        && phoneNumber.All(c => char.IsNumber(c));\n}	0
21574247	21574202	Best practice for looping a function in C#	var t = new Thread(() => {\n   while(true)\n   {\n     var msg = ApiGetMessage(); // Whatver this method is\n     Thread.Sleep(1000);\n   }\n});\n\nt.Start();	0
10362236	10362152	How to insert text in to a word document from Rich Text Box	using DocumentFormat.OpenXml;\nusing DocumentFormat.OpenXml.Packaging;\nusing DocumentFormat.OpenXml.Wordprocessing;\n\nconst string fileName = @"C:\YourFile.docx";\nstring dataToInsert = txtYourRichTextBox.Text;\n\nusing (var document = WordprocessingDocument.Open(fileName, true))\n{\n   var doc = document.MainDocumentPart.Document;\n   document.Body.Append(dataToInsert);\n   document.Save();\n}	0
24915295	24915068	Sort column headers in datagridview c#	foreach (DataRow rowCol in dsCol.Tables["Columns"].Rows.OrderBy(x => x["Price"].ToString()))\n    dt.Columns.Add(rowCol["Price"].ToString() + " - City");\n\nforeach (DataRow rowCol in dsCol.Tables["Columns"].Rows.OrderBy(x => x["Price"].ToString()))\n   dt.Columns.Add(rowCol["Price"].ToString() + "  - Country");	0
17875126	17874028	Sitecore publishend event, get the item from event args	SitecoreEventArgs eventArgs = args as SitecoreEventArgs;\nItem item = ((Sitecore.Publishing.Publisher)(eventArgs.Parameters[0])).Options.RootItem as Item;//eventArgs.Parameters[0] as Item;\nItem existingItem = item.Database.GetItem(item.ID, item.Language, item.Version);	0
15453461	15452997	how to order with parentID and ordermenu	var result =\n  l.Where(c => c.ParentID == 0)\n   .Select(c => new {Menu = c, Sub = l.Where(ci => ci.ParentID == c.ID).OrderBy(s => s.OrderM)})\n   .OrderBy(ao => ao.Menu.OrderM)\n   .SelectMany(ao => ao.Sub.Count() == 0 ? new List<C> {ao.Menu} : new List<C> {ao.Menu}.Concat(ao.Sub));	0
29103279	29103253	How to change base class and keep same implementation in C#	public partial class PluginControl : ClientTabControlPlugin\n{\n    public Foo DoFoo(Bar bar)\n    {\n        return new Foo(bar);\n    }\n}\n\npublic partial class PluginControl(2) : ContactTabControlPlugin\n{\n    public Foo DoFoo(Bar bar)\n    {   \n        return new Foo(bar);\n    }\n}\n\npublic class Foo\n{\n    public Foo(bar)\n    {\n        // shared implementation\n    }\n}	0
3840176	3840080	How to retrieve data from clipboard as System.String[]	obj.GetData()	0
5676802	5676733	Remove all vowels from a name	string vowels = "aeiouy";\nstring name = "Some Name with vowels";\nname = new string(name.Where(c => !vowels.Contains(c)).ToArray());	0
4994395	4994336	Method comparing two strings never returns proper results	if (String.Equals(symbolList.Rows[vcl][0].ToString().Trim(),\n   symbol, StringComparison.InvariantCultureIgnoreCase))	0
615663	615641	Is this an example of Inversion of Control?	Customer customer = repository.GetCustomer(3);	0
30001718	30001505	how to find decode way to decode a USSD Command's result in c#?	+CUSD: <m>[<str_urc>[<dcs>]]	0
298324	298281	Built-in List that can be accessed by index and key	System.Collections.Specialized.NameValueCollection k = \n        new System.Collections.Specialized.NameValueCollection();\n\n    k.Add("B", "Brown");\n    k.Add("G", "Green");\n\n    Console.WriteLine(k[0]);    // Writes Brown\n    Console.WriteLine(k["G"]);  // Writes Green	0
26531797	26531497	How to order in duplicates of 2?	myList.Select((f,i) => new {f, i})  // add the position in the list\n      .OrderBy(fi => fi.i / n)      // "groups" into n items (2, 4, etc.)\n      .ThenBy(fi => fi.f.Type)      // orders within each group by the Type\n      .Select (fi => fi.f)          // removes the added index	0
28345401	28345354	How to stop data grid adding additional row?	dgvView.AllowUserToAddRows = false;	0
1786306	1786269	How can I associate an event handler with a 'group method'?	public class MyArrayList : IList, ICollection, IEnumerable, ICloneable\n{\n    private ArrayList arrayList = new ArrayList();\n\n    public event System.EventHandler RemovedItem;\n\n    public void RemoveAt(int index)\n    {\n    this.arrayList.RemoveAt(item);\n    if (RemovedItem != null) {\n    RemovedItem(this, new EventArgs());\n    }\n    }\n\n    // implement required interface members...\n}	0
22910735	22910460	Restrict users to upload zip file with folder inside	void Main()\n{\nvar isGood=false;\n\n    using (ZipFile zip = new ZipFile(@"c:\\1.zip"))\n {\n     for (var i=0;i<zip.Count;i++)\n     if (zip[i].Attributes==FileAttributes.Directory) \n      {\n       isGood=false;\n       break;\n      }\n\n }\n\n if (isGood) Console.WriteLine ("ok");\n else\n Console.WriteLine ("error");\n}\n\n// Define other methods and classes here	0
5349502	5349440	C# how to format a value taken from text box?	var number = Decimal.Parse(textBox.Text);\nwriter.Write(number.ToString("{0:0000000.00000}", number));	0
6228021	6227984	How do I trim the following string?	[TestMethod]\n  public void ShouldResultInGet()\n  {\n     string url = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get";\n\n     int indexOfLastSlash = url.LastIndexOf( '/' ) + 1; //don't want to include the last /\n\n     Assert.AreEqual( "Get", url.Substring( indexOfLastSlash ) );\n  }	0
4960920	4960900	How do get a simple string from a database	string value = (string)command.ExecuteScalar();	0
8462537	8462514	How do I split a list of names (with title and surname) where they are only separated by a space?	var result = Regex.Split(input, @" (?=Mr\b|Mrs\b|Ms\b)", RegexOptions.None);	0
7491058	7491012	Performance consideration of destroying dataContext vs. keeping it open for future db access?	public interface IUnitOfWork\n{\n    IRepository<T> GenerateRepository<T>();\n    void SaveChanges();\n}\n\npublic interface IRepository<T> where T : class\n{\n    public IQueryable<T> Find();\n    public T Create(T newItem);\n    public T Delete(T item);\n    public T Update(T item);\n}	0
23670021	23669647	Unable to access text or value of datetime picker of tabpage2 on tabpage1	private void Form1_Load(object sender, EventArgs e)\n    {\n        tabControl1.SelectedTab = tabPage2;\n        dateTimePicker1.Text = "2014-05-14 00:00:00.000";            \n    }	0
20450653	20438867	Cannot deserialize JSON string due to an invalid primitive	"Accept-Encoding","gzip,deflate,sdch"	0
33189882	33175079	'Trigger' property is null when trying to register background task using a TimeTrigger	public sealed class BackgroundTask1 : IBackgroundTask\n{\n    BackgroundTaskDeferral _deferral;\n\n    public async void Run(IBackgroundTaskInstance taskInstance)\n    {\n        _deferral = taskInstance.GetDeferral();\n\n        await ApplicationData.Current.LocalFolder.CreateFileAsync("test.txt"\n        , CreationCollisionOption.ReplaceExisting);\n\n\n        _deferral.Complete();\n    }\n}	0
13806311	13806023	Downloading a file that may take a long time to request	Response.Clear();\nResponse.AddHeader("content-disposition", string.Format("attachment;filename=file_{0}.csv", batchId));\nResponse.ContentType = "text/csv";\n\nusing (SqlDataReader rdr= GetDataForCSV())\n{\n    int i = 0;\n    while (rdr.Read())\n    {\n       Response.Write(CSVFromIDataRecord(rdr));\n       Response.Write("\n");\n       if (i % 50 == 0)\n       {\n           //flush the output stream every now and then\n           Response.Flush();\n       }\n    }\n    rdr.Close();\n}\nResponse.End();	0
3297497	3297484	how to get ID from file	string name = System.IO.Path.GetFileNameWithoutExtension(fileName);\n  int id = int.Parse(name);	0
29404026	29403753	How would I byteswap a ByteArray?	static void SwapByteArray(byte[] a)\n    {\n        // if array is odd we set limit to a.Length - 1.\n        int limit = a.Length - (a.Length % 2);\n        if (limit < 1) throw  new Exception("array too small to be swapped.");\n        for (int i = 0; i < limit - 1; i = i + 2)\n        {\n            byte temp = a[i];\n            a[i] = a[i + 1];\n            a[i + 1] = temp;\n        }\n    }	0
23464874	23464769	How do I display the retrieved data in a grid view	public class MyObject\n{\n    public string Name { get; set; }\n    public string Address { get; set; }\n    //.......\n}\n\n//run this code in OnInit, public override OnInit(....)....\n\nprivate List<MyObject> Items = new List<MyObject>();\nMyObject mObj = new MyObject() { Name="Test", Address="SomeAddress" };\ndataGrid.DataSource = Items;\ndataGrid.DataBind();	0
4275733	4275672	how to use save dialog box for download files	Response.ContentType = "APPLICATION/OCTET-STREAM"	0
11525764	11525678	Is there a way to say an IList<xxx> is both a specific class and an interface	class CustomObj<T> where T : BaseNode, IComplexType\n{\n   IList<T> ComplexTypes { get; }\n}	0
26993975	26955976	Compare two managed references	public static unsafe bool Equals(this TypedReference tr, TypedReference other)\n{\n    IntPtr* a = ((IntPtr*)&tr);\n    IntPtr* b = ((IntPtr*)&other);\n    return a[0] == b[0] && a[1] == b[1];\n}\n\npublic static bool Equals<T>(ref T a, ref T b)\n{\n    return __makeref(a).Equals(__makeref(b));\n}	0
18023614	18023584	ProgressBar issues : copying a folder to destination updates	pbProcessFiles.Value = 0;	0
7503467	7503310	Get the nth string of text between 2 separator characters	string textBetween3rdAnd4thPipe = "zero|one|two|three|four".Split('|')[3];	0
6233280	6233127	Different wcf services for different tasks in server-client application, Sharing data between services	Dictionary<string, UserData>	0
20574981	20574793	how do I find the UTC offset from the TimeZoneID?	TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");\n TimeSpan offset = timeZone.GetUtcOffset(DateTime time);	0
64662	64639	Convert from scientific notation string to float in C#	Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);	0
9479705	9469739	Adding Shapes to a New Visio Document	Visio.Document vDoc = vDocs.Add("MyTemplateFile.vst");	0
21527975	21527903	C# generic class - How to replace a value	PropertyInfo myproperty = typeof(TEntity).GetProperty("last_update");\n    if (myproperty != null)\n        myproperty.SetValue(myobj, DateTime.Now);	0
9414875	9414785	Compressing directly from a stream	public void WriteXml(\n    Stream stream,\n    XmlWriteMode mode\n)	0
3002313	3001593	Random value from Flags enum	var options = Colours.Blue | Colours.Green;\n\nvar matching = Enum.GetValues(typeof(Colours))\n                   .Cast<Colours>()\n                   .Where(c => (options & c) == c)    // or use HasFlag in .NET4\n                   .ToArray();\n\nvar myEnum = matching[new Random().Next(matching.Length)];	0
12666863	12666835	Converting MMDDYYYY to 01-JAN-YY	DateTime dateTime = DateTime.ParseExact("01012012", "MMddyyyy", CultureInfo.InvariantCulture);\nstring newDateString = dateTime.ToString("dd-MMM-yy");	0
29001769	29001672	Json create by JSON.net	public class Paging\n{\n    public int CurPage { get; set; }\n    public int TotalPageCount { get; set; }\n}\n\npublic class Item\n{\n    public int T0 { get; set; }\n    public string T2 { get; set; }\n}\n\nvar lst = new List<object>();\nlst.Add(new Paging());\nlst.Add(new Item());\nJsonConvert.SerializeObject(lst);	0
10004817	10004741	Write Image to SQL Server using Blob Literal String in C#	string imageByteArrayAsString = "0x" + BitConverter.ToString(image).Replace("-", string.Empty);	0
2070264	2070226	How to clear screen area or Redraw screen in C#	bool prev_rev_frame = false;\nRect prev_rev_rect;\n\n...\n\nvoid on_mouse_move() {\n  if(prev_rev_frame)\n    Control.drawReversableFrame(prev_rev_rect);\n  Rect new_rev_rect = ....\n  Control.drawReversableFrame(new_rev_rect);\n  prev_rev_frame = true;\n  prev_rev_rect = new_rev_rect;\n}	0
20406475	20405832	read from file 50 chars at a time C#	int inx = 0;\nvar lines50 = File.ReadAllText(fname)\n                .GroupBy(_ => inx++ / 50)\n                .Select(x => new string(x.ToArray()))\n                .ToList();	0
8819279	8819028	Parameterised Drill down with Gridview	protected void grid_SelectedIndexChanging(object sender, EventArgs e) \n{ \n    GridView grid = (GridView)sender;\n    Response.Redirect("ViewCustomer.aspx?id=" + grid.SelectedRow.Cells[0]); \n}	0
16465254	16410424	Draw on MSChart control	private void AddRectangleAnnotation()\n{\nRectangleAnnotation annotation = new RectangleAnnotation();\nannotation.AnchorDataPoint = Chart1.Series[0].Points[2];\nannotation.Text = "I am a\nRectangleAnnotation";\nannotation.ForeColor = Color.Black;\nannotation.Font = new Font("Arial", 12);;\nannotation.LineWidth = 2;\nannotation.BackColor = Color.PaleYellow;\nannotation.LineDashStyle = ChartDashStyle.Dash;\n\nChart1.Annotations.Add(annotation);\n}	0
13330222	13329631	How to convert a Persian date into a Gregorian date?	public static DateTime GetEdate(string _Fdate)\n{\n    DateTime fdate = Convert.ToDateTime(_Fdate);\n    GregorianCalendar gcalendar = new GregorianCalendar();\n    DateTime eDate = pcalendar.ToDateTime(\n           gcalendar.GetYear(fdate),\n           gcalendar.GetMonth(fdate),\n           gcalendar.GetDayOfMonth(fdate),\n           gcalendar.GetHour(fdate),\n           gcalendar.GetMinute(fdate),\n           gcalendar.GetSecond(fdate), 0);\n    return eDate;\n}	0
33110780	33110275	Project attribute values	var marketInventoryTotalListings = (from totalListings in xe.Descendants("MARKET_INVENTORY")\n                                   where (string)totalListings.Attribute("_Type") == "TotalSales"\n                                   select new MarketInventoryListing()\n                                   {\n                                      Prior7To12Months =\n                                      (\n                                           from thing in totalListings.Parent.Descendants()\n                                           where (string)totalListings.Attribute("_MonthRangeType") == "Prior7To12Months"\n                                           select thing.Attribute("_Count").Value\n                                      ).FirstOrDefault(),\n                                   }).FirstOrDefault();	0
7459372	7459360	Insert values into an Access Database that contain brackets/braces	cmd.CommandText = "INSERT INTO Track (Title,Artist,Album,Path) VALUES (?, ?, ?, ?)";\ncmd.Parameters.Add(title);\ncmd.Parameters.Add(artist);\ncmd.Parameters.Add(album);\ncmd.Parameters.Add(filesFound[i]);	0
19048581	19042741	TFS client QueryHistory - get the earliest changeset	versionControlService.QueryHistory(\n            path, \n            VersionSpec.Latest,\n            0,\n            RecursionType.Full, //look into all subfolders\n            null,\n            null, //version from - first\n            null, //version to - latest => all\n            1, //Return at maximum 1 item\n            boolIncludeChanges, // Include information on changes done\n            false,\n            boolIncludeDLInfo,\n            true //sort ascending - C1, C2, .. CLatest\n)	0
14241075	14240031	Change visibility of a picture when button is pressed	right = false;\n        left = false;	0
966076	965102	asp.net - How can I update a text box asynchronously during a long process	thisTextbox.text = "I know this is silly";\nUpdatePanel1.Update();	0
21264499	21264447	Alternate meaning of SqlCommand's 1st parameter	public SqlCommand(string cmdText, SqlConnection connection) : this()\n{\n    this.CommandText = cmdText;\n    this.Connection = connection;\n}	0
1198860	1198841	Getting new lines from a file with FileSystemWatcher	using (FileStream fs = new FileStream("t.log", FileAccess.Read))\n{\n  fs.Seek(previousSize, SeekOrigin.Begin);\n  //read, display, ...\n  previousSize = fs.Length;\n}	0
14956147	14956088	How to write <%%> in server controls?	btnPrevious.OnClientClick = "location.href='" + PreviousLink + "'"	0
11746021	11743368	Xml searching node issue	XElement root = XElement.Load(path);\nXElement div = root.XPathElement("//div[@id={0}]", 1);\nif(null != div) // which it shouldn't be\n    div.Add(n);	0
30363040	30362969	How to get alert text in jQuery?	Response.Write("<script>var alerttext='Click Checkbox'; alert('Click Checkbox'); </script>");	0
18986427	18986360	How to count the number of matches of files in a directory	int count = Directory.GetFiles(@"c:\temp").Count(path => Regex.IsMatch(path, pattern));	0
25804064	25803979	Caliburn Micro - bind ListBox to property of objects in a collection	public Person(string personName)\n    {\n        this.PersonName  = personName;\n    }	0
6970137	6970070	LINQ Lambda Group By with Sum	query\n.GroupBy(item => item.GroupKey)\n.Select(group => group.Sum(item => item.Aggregate));	0
25144841	25144657	WebApi 'Multiple actions were found that match the request' error after making call in angular	public class WebApiInitializer : IInitializableModule\n{\n    public void Initialize(InitializationEngine context)\n    {    \n        RouteTable.Routes.MapHttpRoute(\n            "CreateJob",\n            "api/msi/SBJob/CreateJob",\n            defaults: new {Controller = "SBKob", Action = "CreateJob"}\n            );\n\n        RouteTable.Routes.MapHttpRoute(\n            "GetJob",\n            "api/msi/SBJob/GetJob",\n            defaults: new {Controller = "SBKob", Action = "GetJob"}\n            );              \n    }\n}	0
11546477	11546318	Get Total of a column from Dataset in Time Format(HH:MM) using C# without using Linq	double total = 0;\nforeach(DataRow r in dataSet.Tables[0].Rows)\n{\n\n    var DurHour = r["Duration"].ToString().Split(':')[0];\n    var DurMinute = r["Duration"].ToString().Split(':')[1];\n    TimeSpan ts = new TimeSpan(int.Parse(DurHour), int.Parse(DurMinute), 0);\n    total += ts.TotalMinutes;\n}\n\nConsole.WriteLine("Total time in minutes: {0}", total);	0
16180066	16179996	How to best clean up a SQLDataReader when using linq	using (System.Data.SqlClient.SqlDataReader reader = CallStoredProcedure())\n{\n    while (reader.Read())\n    {\n        yield return new ObjectModel.CollectorSummaryItem()\n        {\n            CollectorID = (int)reader[0],\n            Name = reader.IsDBNull(1) ? null : reader.GetString(1),\n            Information = reader.IsDBNull(2) ? null : reader.GetString(2)\n        }\n    }\n}	0
33084376	33083685	Select subelements from XElement into new XElement	var objNodes = doc.Descendants("object") .Where(node => node.Attribute("table").Value == idbsObject.Key) .Select(item => new XElement("object", new object[] {item.Attributes(), item.Element("nodes")}));	0
2609537	2609520	How to make text/labels smooth?	public partial class CustomLabel : Label\n{\n    private TextRenderingHint _hint = TextRenderingHint.SystemDefault;   \n    public TextRenderingHint TextRenderingHint\n    {\n        get { return this._hint; }\n        set { this._hint = value; }\n    }        \n\n    protected override void OnPaint(PaintEventArgs pe)\n    {            \n        pe.Graphics.TextRenderingHint = TextRenderingHint;\n        base.OnPaint(pe);\n    }\n}	0
25142381	25121469	Correct Usage of the Singleton Pattern	public class NinjectBindings : NinjectModule\n{\n    public override void Load()\n    {\n        Bind<IBillLineEntities>.To<BillLines.BillLines>().InSingletonScope();\n    }\n}	0
2689425	2689353	Launching another application from C#	Process.Start(@"C:\Path\OtherApp.exe");	0
16005550	16005469	How can I return a string from an ElapsedEvent method	public void ElapsedEvent(object source, ElapsedEventArgs e)\n{\n    string x = OtherClass.DeSerializeXML();\n    frm.Invoke((Action)(() => textBox.Text = x);\n}	0
13001120	13000748	Use string as type of DbSet like DbSet<string> in EF-CodeFirst	DbSet<string>	0
769750	768851	Need help editing multiple cells in a datagridview	private int _keyValue;\nprivate Boolean _checkKeyValue = false;\n\nprivate void Grid1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)\n{\n    DataGridViewCell cell = Grid1.Rows[e.RowIndex].Cells[e.ColumnIndex];\n\n    if (_checkKeyValue)\n    {\n    _checkKeyValue = false;\n\n    if (value != -1)\n    {\n    cell.Value = _keyValue;\n    }\n    }\n}\n\nprivate void Grid1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (Grid1.SelectedCells.Count > 1)\n    {\n    _checkKeyValue = true;\n    _keyValue = (int)e.KeyValue;\n    Grid1.BeginEdit(false);\n    }\n}	0
12258489	12258388	How to change the value of DataGridView Cell when another cell in the same row changed?	dg_invoices_items["Qty", e.RowIndex].Value = Convert.ToString(\n     Convert.ToInt32(dg_invoices_items["Price", e.RowIndex].Value) *\n     Convert.ToInt32(dg_invoices_items["Amount", e.RowIndex].Value));	0
4823521	4823467	using LINQ to find the cumulative sum of an array of numbers in C#	var input=new double[]{ ... }\ndouble sum=0;\n\nvar output=input\n    .Select(w=>sum+=w);	0
7597366	7596865	Input Validation Silverlight	// Text change in Port text box\nprivate void txtPort_TextChanged(object sender, TextChangedEventArgs e)\n{\n    // Only allow numeric input into the Port setting.\n    Regex rxAllowed = new Regex(@"[^0-9]", RegexOptions.IgnoreCase);\n\n    txtPort.Text = rxAllowed.Replace(txtPort.Text, ""); \n    txtPort.SelectionStart = txtPort.Text.Length; \n}	0
18670983	18670822	find and delete whole line in txt file	void FilterFile(string fileName, string newFileName, string itemCode) \n{\n    var mathcedLines = File.ReadLines(fileName).Where(l => !l.StartsWith(itemCode));\n    File.WriteAllLines(newFileName, mathcedLines);\n}	0
24541031	24540822	Using Entity Framework with additional property	public class Product\n{\n    public int Id { get; set; }\n    public virtual IEnumerable<Sample> Samples { get; set; }\n    [NotMapped]\n    public decimal Price\n    {\n        get { return Samples.OrderByDescending(x => x.TimeStamp).First().Price; }\n    }\n}\n\npublic class Sample\n{\n    public int Id {get; set;}\n    public decimal Price { get; set; }\n    [Timestamp]\n    public byte[] TimeStamp {get; set;}\n}	0
8791401	8791312	why it validates locally but fails on the server	Trace.Write("Import schema directory: " + Server.MapPath("~/importSchema"));\n\nsettings.Schemas.Add(null, System.Web.HttpContext.Current.Server.MapPath("~/importSchema/IntialSchema.xsd"));	0
19172476	19083261	Auto-increment Using Dates	CREATE TABLE [dbo].[MainOne](\n[DocketDate] NVARCHAR(8),\n[DocketNumber] NVARCHAR(10),\n[CorpCode] NVARCHAR(5),\nCONSTRAINT pk_Docket PRIMARY KEY (DocketDate,DocketNumber)\n)\nGO\nINSERT INTO [dbo].[MainOne] VALUES('20131003','1','CRH')\nGO\nCREATE TRIGGER AutoIncrement_Trigger ON [dbo].[MainOne]\n instead OF INSERT AS\n BEGIN\n DECLARE @number INT\n SELECT @number=COUNT(*) FROM [dbo].[MainOne] WHERE [DocketDate] = CONVERT(DATE, GETDATE()) \n INSERT INTO [dbo].[MainOne] (DocketDate,DocketNumber,CorpCode) SELECT (CONVERT(DATE, GETDATE    \n ())),(@number+1),inserted.CorpCode FROM inserted\nEND	0
10991519	10991292	Asserting if a NameValueCollection is equivalent	CollectionAssert.AreEquivalent(\n    expectedCollection.AllKeys.ToDictionary(k => k, k => expectedCollection[k]),\n    collection.AllKeys.ToDictionary(k => k, k => collection[k]));	0
34399668	34359036	Window's Authentication to access server	web.config	0
10412861	10349146	How to post a binary image from desktop app to ashx handler and receive it?	Stream gelenResim = context.Request.InputStream;\n            if (gelenResim.Length == 0) e.Resim = "/Content/EmlakDetayImaj/Noimages.jpg";\n            string guidim = Guid.NewGuid().ToString().Substring(0, 4);\n            var KaydetResimDosya = "/Content/EmlakDetayImaj/" + guidim + ".jpg";\n            using (FileStream fileStream = System.IO.File.Create(context.Server.MapPath("~/Content/EmlakDetayImaj/" + guidim + ".jpg"), (int)gelenResim.Length))\n            {\n                byte[] bytesInStream = new byte[gelenResim.Length];\n                gelenResim.Read(bytesInStream, 0, (int)bytesInStream.Length);\n                fileStream.Write(bytesInStream, 0, bytesInStream.Length);\n\n}	0
8259745	8257892	COM Word Selection TypeText with line break	oWord.Selection.TypeText("Hello\r\nWorld".Replace("\r\n", char.ConvertFromUtf32(11)));	0
15405808	15405701	How to combine multiple lists with custom sequence	var lists = new [] { list1, list2, list3 };\nvar combined = new List<string>(lists.Sum(l => l.Count));    \n\nfor (var i = 0; i < lists.Max(l => l.Count); i++)\n{\n   foreach (var list in lists)\n   { \n      if (i < list.Count)\n          combined.Add (list[i])\n   }\n}	0
34459788	34458841	c# SqlCe binary data recovery	try\n            {\n\n                SqlCeConnection con = new SqlCeConnection(@"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");\n                con.Open();\n\n                string strQuery = "select Data where Name = @Name and ContentType = @ContentType";\n                SqlCeCommand cmd = new SqlCeCommand(strQuery, con);\n\n                cmd.Parameters.AddWithValue("@Name", filename);\n\n                cmd.Parameters.AddWithValue("@ContentType", "application/vnd.ms-word");\n\n\n                SqlCeDataReader reader = cmd.ExecuteReader();\n                if (reader != null)\n                {\n                    if (reader.Read())\n                    {\n\n                        byte[] pdf = (byte[])reader["Data"];\n                        File.WriteAllBytes(filename, pdf);\n\n                    }\n                }\n            }\n\n???	0
30922986	30878151	oData SharePoint Add List Item Containing Value Properties	var foodItem = new FoodItem();\ndataContext.AddToFoods(foodItem);   // Add to context before populating fields so the values are tracked.\nfoodItem = Mapper.Map(newFood, foodItem);\n\n// DataValue Properties like StateValue objects can now be added since it is tracked by the context.\nvar state = StateValue.CreateStateValue("Montana");\nfoodItem.StateValue = state;\n\n// Need to link special DataServiceCollection lists like Ingredient using a reference.\nif (newFood.Ingredient != null)\n{\n    newFood.Ingredient.ForEach(c =>\n    {\n        var ingredient = FoodIngredient.CreateFoodIngredientValue(c);\n        dataContext.AttachTo("FoodIngredientValue", ingredient);\n        foodItem.FoodIngredient.Add(ingredient);\n        dataContext.AddLink(foodItem, "FoodIngredient", ingredient);\n    });\n}	0
22415330	22415231	Dynamic Where clause with unknown number of parameters	var results = ctx.MyEntity.AsQueryable();\n\nif(name != null)\n    results = results.Where(a => a.Name == name);\n\n// ... snip ...\n\nif(zip != null)\n    results = results.Where(a => a.ZIP == zip)\n\nreturn results.ToList();	0
11433676	11414824	DotNetOpenAuth - how to uniquely identify Google users?	IAuthenticationResponse.ClaimedIdentifier	0
33221334	32993182	WPF : On screens with different resolution, scroll bar comes even if the window state is maximized	if (screen != null)\n            {\n                window.WindowState = System.Windows.WindowState.Normal;\n                window.Left = screen.WorkingArea.Left;\n                window.Top = screen.WorkingArea.Top;\n                window.ResizeMode = ResizeMode.NoResize; \n                window.WindowStyle = WindowStyle.None;\n                window.WindowState = System.Windows.WindowState.Maximized;\n                window.Height = screen.WorkingArea.Height;\n                window.Width = screen.WorkingArea.Width;\n            }	0
24786811	24776475	How to change the produced type of a Rx Observable from int to double?	var timer = Observable.Timer(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10)).Select(i => i / 10.0);\ntimer.Subscribe(Console.WriteLine, ()=>Console.WriteLine("Completed"));	0
21988257	21988132	How to substring <img src="myimage" /> from a string?	string sMyText = "Lorem ipsum dolor sit amet <img src='http://www.mydomain.com/images/name_surname.jpg' /> Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.";\n\nMatch match = Regex.Match(sMyText, "<img[^>]+>");\n\nif (match.Success)\n    Console.WriteLine(match.Value);	0
6092993	6092628	Redirecting to login page when user clicks a button	using System.Security.Authentication\n\nPublic void IsValidUser()\n{\n   if(User.Identity.Name!=string.empty)\n     Response.Redirect("~login.aspx");\n   else\n   {\n      if(!User.Identity.IsAuthenticated)\n        Response.Redirect("~login.aspx");\n   }\n}	0
4578854	4578809	Is it possible to create a managed byte array from an IntPtr + size?	Marshal.WriteByte(rawBufferPtr, <offset into buffer>, byteValue);	0
9182957	9182858	Validating my money	float num;\nbool isValid = float.TryParse(str, \nNumberStyles.Currency,\nCultureInfo.GetCultureInfo("en-US"), // cached\nout num);	0
25352809	25351844	Get all cells in X distance of another cell. (XY Grid)	List<Tile> exits = tiles.Where(t=>t.type = exit).ToList()\n\n    List<Tile> closeTiles = exits.SelectMany(e=> tiles.Where(t=> ((t.X - e.X) ^ 2) + ((t.X - e.X) ^ 2) <= distance ^ 2)).Distinct().ToList()	0
22255409	22199507	how to edit the nlog config file programmatically	string configFilename = GetConfigFilePath();\n\n\n            XmlDocument doc = new XmlDocument();\n            doc.Load(configFilename);\n\n            XmlNode documentElement = doc.DocumentElement;\n\n            foreach (XmlNode node in documentElement.ChildNodes)\n            {\n                if (ruleDocumentNodeName.Equals(node.Name))\n                {\n                    foreach (XmlNode childNode in node.ChildNodes)\n                    {\n                        if (loggerDocumentNodeName.Equals(childNode.Name))\n                        {\n                            XmlAttribute idAttribute = childNode.Attributes[minLevelAttributeName];\n                            string currentValue = minLogingLevelComboBox.SelectedItem.ToString();\n                            idAttribute.Value = currentValue;\n                            doc.Save(configFilename);\n                            MinLoggingLevelChanged = true;\n                        }\n                    }\n                }\n            }	0
24604357	24604226	Searching for string patterns c#	CompareInfo compInf = CultureInfo.CurrentCulture.CompareInfo;\nint compResult = compInf.IndexOf(searchInString, searchForString, CompareOptions.IgnoreCase);	0
10367189	10367114	Compare a string read by network stream	// init bit variable here\nwhile (!bit.Contains("\r") && !bit.Contains("\n") && !bit.Contains("."))\n{\n    outputString += bit;\n    stream.Read(buffer, 0, 1);\n\n    bit = Encoding.ASCII.GetString(buffer);\n}	0
21658855	21658762	How to use Linq to update fields in a list based on another list joined by id	var deltasById = deltas.ToDictionary(d => d.Id);\n\nforeach (var counter in counters)\n{\n    Delta delta;\n    if (!deltasById.TryGetValue(counter.Id, out delta))\n        continue;\n\n    counter.A += delta.ADelta;\n    counter.B += delta.BDelta;\n}	0
10623555	10623403	I'm Having Trouble With a SQL Query in LINQ	int maxHits = Products.Max( p => p.Hits );\n\nvar query = Products.OrderByDescending( \n                p => p.Hits == maxHits ).ThenByDescending( p => p.DateAdded );	0
21455243	21455167	Texturing a Sphere C#	Mesh\n+----------+----------+----------+ V=1.00\n|0        3|3        5|5        7|\n| vertices |          |          |\n|          |          |          |\n|1        2|2        4|4        6|\n+----------+----------+----------+ V=0.66\n|          |          |          |\n|          |          |          |\n|          |          |          |\n|          |          |          |\n+----------+----------+----------+ V=0.33\n|          |          |          |\n|          |          |          |\n|          |          |          |\n|          |          |          |\n+----------+----------+----------+ V=0.00\nU=0        U=0.33     U=0.66     U=1.00	0
10697508	10697415	No static in generic. But how to achieve this?	[TypePath(@"C:\")]\npublic class classA\n{\n}\n[TypePath(@"D:\")]\npublic class classB\n{\n}\npublic class ReadPath<T>\n{        \n    public static List<T> ReadType()\n    {\n        var attrib = (TypePathAttribute)Attribute.GetCustomAttribute(\n              typeof(T), typeof(TypePathAttribute));\n        var path = attrib.Path;\n        ...\n    }        \n}\n\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct\n    | AttributeTargets.Interface | AttributeTargets.Enum,\n    AllowMultiple = false, Inherited = false)]\npublic class TypePathAttribute : Attribute\n{\n    public string Path { get; private set; }\n    public TypePathAttribute(string path) { Path = path; }\n}	0
20742966	20741206	Update Entity Framework object from another object of same type	using (var context = new MyDBEntities())\n{\n    try\n    {\n        var user = (User)Session["EditedUser"];\n        context.Users.Attach(user);\n        context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);\n        context.SaveChanges();\n        Session["EditedUser"] = null;\n        return "ok";\n    }\n    catch (Exception ex)\n    {\n        return ex.Message;\n    }\n}	0
18815304	18815258	Data is not displaying in datagrid wpf	public class PartsListObjects\n{\n    public int partid {get; set; }\n    public string SPartName {get; set; }\n    public string SPartCode {get; set; }\n    public string SPartLocation {get; set; }\n    public bool SPartActive {get; set; }\n    public string ModelName {get; set; }\n    public string SPartSalePrice {get; set; }\n}	0
728273	728160	How to do a 'ExecuteNonQuery' in Castle Active Record	ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof (object)).ConnectionProvider.GetConnection()	0
7097989	7095359	Putting a .txt file into a DataGridView	var fileName = this.OpenFileDialog1.FileName;\nvar rows = System.IO.File.ReadAllLines(fileName);\nChar[] separator = new Char [] {' '};\nDataTable tbl = new DataTable(fileName);\nif (rows.Length != 0) {\n    foreach (string headerCol in rows(0).Split(separator)) {\n        tbl.Columns.Add(new DataColumn(headerCol));\n    }\n    if (rows.Length > 1) {\n        for (rowIndex = 1; rowIndex < rows.Length; rowIndex++) {\n            var newRow = tbl.NewRow();\n            var cols = rows(rowIndex).Split(separator);\n            for (colIndex = 0; colIndex < cols.Length; colIndex++) {\n                newRow(colIndex) = cols(colIndex);\n            }\n            tbl.Rows.Add(newRow);\n        }\n    }\n}	0
10163859	10163838	Display items from a List 10 string items at a time	Scanner scanner = new Scanner();\nList<string> query = scanner.Parse(parts);\nforeach (string item in query)\n{\n     richTextBox6.Invoke((Action)(() => richTextBox6.AppendText(item))); \n}	0
12256155	12211233	Capturing Kinect Depth Image to a png file	WriteableBitmap wmp;\n            wmp = cis.Bitmap;\n            BitmapEncoder encoder = new PngBitmapEncoder();\n            encoder.Frames.Add(BitmapFrame.Create(wmp));\n            string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"Image 1.png");\n            try\n            {\n                using (FileStream fs = new FileStream(path, FileMode.Create))\n                {\n                    encoder.Save(fs);\n                }\n            }\n            catch (IOException ioe)\n            {\n                Console.WriteLine(ioe.ToString());\n            }\n            return path;	0
19384378	19384193	Get company name and copyright information of assembly	var versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);\n\nvar companyName = versionInfo.CompanyName;	0
15417994	15417135	Resizing a rectangle and snapping to a fixed ratio	if (Height * widthRatio <= Width)\n    Width = Height * widthRatio;\nelse if (Width * heightRatio <= Height)\n    Height = Width * heightRatio;	0
3860290	3860273	using CodeDom to generate an enum with Value as well as Name	foreach (var enumNameAndValue in EnumsCollection[enumName])\n{\n     var codeProperty = new CodeMemberField\n     {\n          Name = enumNameAndValue.Value,\n          InitExpression = new CodePrimitiveExpression(enumNameAndValue.Key); // Uses key for value\n     };	0
8117429	8117338	DateTime and String Validation	string SomeDate = "1/1/2012";\n        DateTime dt;\n        var success = DateTime.TryParse(SomeDate, out dt);	0
10752529	10752487	Inserting a Line at a specific place in a txt using .net	var lines = File.ReadAllLines("file.txt").ToList();\nlines.Insert(location, text);\nFile.WriteAllLines("file.txt", lines);	0
8464638	8464623	C# modifing a string array in a foreach loop and changing the same array	for(int i = 0; i < MyInfo.Length; i++)\n{\n   MyInfo[i] = formatLineHere(MyInfo[i]);       \n}	0
30064221	30063860	Read XML from stream, extract node, base64 decode it and write to file with minimum internal memory required	string xml = "";  //put your string input here
\n            StringReader reader = new StringReader(xml);
\n            XmlReader xreader = XmlReader.Create(reader);
\n???	0
9988030	9987800	change sequence of datagridview columns window C#	DataGridViewCheckBoxColumn col3 = new DataGridViewCheckBoxColumn ();\n//...\nDataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn ();\n//...\nDataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn ();\n//...\n\ndatagridview.columns.add(col3);\ndatagridview.columns.add(col1);\ndatagridview.columns.add(col2);	0
17694197	17694020	update one xml based on another xml with repetitive elements with linq to xml	var source = "<Source><First><Name>Name1</Name></First><First><Name>Name2</Name></First></Source>";\nvar sourceDocument = XDocument.Load(new StringReader(source));\n\nvar target = "<Target><Second><FirstName></FirstName></Second><Second><FirstName></FirstName></Second></Target>";\nvar targetDocument = XDocument.Load(new StringReader(target));\n\nvar sourceNameElements = sourceDocument.Descendants("First").Select(first => first.Element("Name")).ToList();\nvar targetNamesElements = targetDocument.Descendants("Second").Select(second => second.Element("FirstName")).ToList();\n\nfor (var i = 0; i < sourceNameElements.Count; ++i)\n{\n    targetNamesElements[i].SetValue(sourceNameElements[i].Value);\n}\n\nConsole.WriteLine(targetDocument.ToString());	0
727984	727941	Can I access the list of InsertOnSubmit'd records from a linq-to-sql DataContext?	db.GetChangeSet().Inserts	0
21613456	21609362	Avoid repetition in Definition of Regex	// @"^\s*[0-9]+(?:\s*-\s*[0-9]+)?(?:\s*,\s*[0-9]+(?:\s*-\s*[0-9]+)?)*"     \n Regex rx = new Regex(\n   @"\n      ^ \n      \s*     \n      [0-9]+ \n      (?: \s* - \s* [0-9]+ )?\n      (?:\n           \s* , \s* \n           [0-9]+ \n           (?: \s* - \s* [0-9]+ )?\n      )*\n   ", RegexOptions.IgnorePatternWhitespace);	0
6059189	6058802	Game/Quote of the day - how to?	var gameOfTheDay = games[(uint)(DateTime.Today.GetHashCode()) % games.Length];	0
25243238	25242744	how to serialize a point3D using XmlSerializer?	var serializer = new XmlSerializer(typeof(Attribute1), new Type[] { typeof(Placement) });	0
22779997	22779826	stored procedure in sql used in c#	set @qry='select J.idJob,j.DateAdded,j.OpenedByWho,j.JobAddress ,j.final,j.idOrg,j.note\n                          from Job J \n                          inner join Users U on\n                          U.idOrg=J.idOrg\n                          where U.IdUser='+ @idUser+ '\n                          and ISNULL(j.Final,'''')='''' \n                          order by idJob'	0
8697636	8697175	C# closures and access to external variables	/// <exception cref="IOException"></exception>\n    public static void DeleteObject(this AmazonS3Context context, string key)\n    {\n        context = null;\n        AmazonS3Operation(context, ctx => ctx.Client.DeleteObject(\n            new DeleteObjectRequest().WithBucketName(ctx.CurrentBucket)\n                .WithKey(key)));\n    }\n\n    /// <exception cref="IOException"></exception>\n    private static void AmazonS3Operation(AmazonS3Context context, Action<AmazonS3Context> operation)\n    {\n        var shouldDispose = false;\n        try\n        {\n            if (context == null)\n            {\n                context = new AmazonS3Context();\n                shouldDispose = true;\n            }\n\n            operation(context);\n        }\n        catch (AmazonS3Exception e)\n        {\n            throw new IOException(e.Message, e);\n        }\n        finally\n        {\n            if (shouldDispose)\n                context.Dispose();\n        }\n    }	0
7484196	7484150	How can I increment values by assigning different percentage	double[] items = new double[100];\nfor (int i = 0; i < 20; i++)\n    items[i] = 0.04;\nfor (int i = 20; i < 100; i++)\n    items[i] = 0.0025;	0
10431963	10414856	Dynamically creating multiple RadDocks on a button click	RadDockZone dz = (RadDockZone)FindControl(DropDownZone.SelectedItem.Text);\n    //adding the dock to the docklayout and then docking it to the zone to avoid ViewState issues on subsequent postback\n    RadDockLayout1.Controls.Add(dock);\n    dock.Dock(dz);	0
15332059	15331840	How to display videos from xml url for windows phone 7?	XElement rootElement = XElement.Load("Xml.xml");\nstring url=(string)rootElement.Elements("iframe").Single().Attribute("src").Value;	0
11399546	11398175	Add Application Start event handler manually in constructor	public class MyApplication : HttpApplication\n{\n\n    public override void Init()\n    {\n        base.Init();\n    }\n\n}	0
11780138	11779689	Ling to sql join	using (AppDataContext context = data.GetDataContext())\n{\n    docList = (from d in context.Documents\n                join f in context.DocumentFlags on d.docID equals f.docID into flg\n                where f.usrID == userID \n                from fff in flg.DefaultIfEmpty()\n                select new Document\n                {\n                    DocID = d.docID,\n                    DocNr = d.docNr,\n                    ScanTime = d.docScanTime.Value,\n                    UserID = fff.userID,\n                    IsDelete = fff.isDelete.Value,\n                    IsArchive = fff.isArchive.Value,\n                }).ToList<Document>();\n}	0
768530	768513	How to get the number of items in a combobox?	var count = comboBox.Items.Count;	0
22044301	22044211	Getting methods that return a specific type using GetMethods	t.GetMethods(BindingFlags.Static | BindingFlags.Public).Cast<MethodInfo>()\n    .Where(method => method.ReturnType == typeof(int))	0
849027	849001	How do I select tokens from a string using LINQ?	var selected = from token in tokens where token.Contains("Dog") select token;	0
1063799	1063701	StyleCop formatting	this.BeginInvoke(this.updateHandler, new object[] { this.tmpbuf });	0
23544125	23543161	C# & Twitter API: Getting tweets with specific #tag	var searchParameter = Search.GenerateSearchTweetParameter("#my_tag");\n\nsearchParameter.Lang = Language.English;\nsearchParameter.SearchType = SearchResultType.Popular;\nsearchParameter.MaximumNumberOfResults = 200;\nsearchParameter.Since = new DateTime(2013, 12, 1);\n// ... There are many different parameters that can be set\n\nvar tweets = Search.SearchTweets(searchParameter);\ntweets.ForEach(t => Console.WriteLine(t.Text));\n\n// Get number of objects\nvar nbTweets = tweets.Count();	0
1542467	1542409	How to get current regional settings in C#?	class Program\n{\n    private class State\n    {\n        public CultureInfo Result { get; set; }\n    }\n\n    static void Main(string[] args)\n    {\n        Thread.CurrentThread.CurrentCulture.ClearCachedData();\n        var thread = new Thread(\n            s => ((State)s).Result = Thread.CurrentThread.CurrentCulture);\n        var state = new State();\n        thread.Start(state);\n        thread.Join();\n        var culture = state.Result;\n        // Do something with the culture\n    }	0
483362	483341	Regex to match a substring within 2 brackets, e.g. [i want this text] BUT leave out the brackets?	Regex r1 = new Regex(@"\[(.+)\]");\nstring row = "HEADERNAMES[COL1, COL2, COL3, COL4]";\n// Regex puts capture groups (i.e. things captured between ( and ) ) \n// in Groups collection\nstring match = r1.Match(row).Groups[1].Value;\n//match = "COL1, COL2, COL3, COL4"	0
5384816	5384208	IQueryable to non-AD LDAP	DirectorySearcher(entry);	0
8531329	8530993	How to add Schema location and XSI dynamically to an XML file	XmlAttribute attr = doc.CreateAttribute("xsi", "schemaLocation", " ");\n        attr.Value = "http://www.irs.goc/efile ReturnData941.xsd";\n        returnData.Attributes.Append(attr);	0
21102098	21102022	Linq Dictionary for count of items that are in an array	var count = myDict.Values.Intersect(myArray).Count();	0
17349877	17349699	Subsequent displays of custom Tooltip has ugly black edging around border	e.Graphics.SmoothingMode = SmoothingMode.HighQuality;	0
17935137	17934986	Store and access multiple values in c#	public string cdir\n{\n    get\n    {\n       return clientsbox2.SelectedItem.ToString();\n    }\n}\n\n... etc	0
757697	757665	Integer representation for day of the week	(Int32)Convert.ToDateTime("2008-12-31T00:00:00.0000000+01:00").DayOfWeek + 1	0
3109462	3095833	Silverlight Object Binary Serialization to Database	public static class MySerializer\n{\n    public static string Serialize<T>(T data)\n    {\n        using (var memoryStream = new MemoryStream())\n        {\n            var serializer = new DataContractSerializer(typeof(T));\n            serializer.WriteObject(memoryStream, data);\n\n            memoryStream.Seek(0, SeekOrigin.Begin);\n\n            var reader = new StreamReader(memoryStream);\n            string content = reader.ReadToEnd();\n            return content;\n        }\n    }\n\n    public static T Deserialize<T>(string xml)\n    {\n        using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml)))\n        {\n            var serializer = new DataContractSerializer(typeof(T));\n            T theObject = (T)serializer.ReadObject(stream);\n            return theObject;\n        }\n    }\n}	0
16226022	8854701	Disable all Resharper warnings with a comment	// ReSharper disable All	0
32597632	32597611	How to save JSON from an ASP.NET viewmodel into a JavaScript variable?	var yourModel = JSON.parse(@Html.Raw(Json.Encode(Model.PageJson)));	0
3707293	3707283	Binary data within a dll is unmanageable	Assembly.GetManifestResourceStream	0
5666161	5665407	Search Active Directory for all Usernames associated with email address	List<string> usernames = new List<string>();\nif (result != null) \n{\n     foreach (SearchResult sr in result)\n     {\n         usernames.Add((string)sr.Properties["SAMAccountName"][0]);\n     }\n}\nlistBox1.DataSource = usernames; //Where listbox is declared in your markup\nlistBox1.DataBind();	0
33500880	33500838	Find if a decimal is larger than four places	decimal d = decimal.Parse(pReturn);\nif (Decimal.Round(d, 4) != d)	0
17479863	17479540	adding item to a list then have list appear in a Combobox	foreach(...)\n{\n    ...\n}\nprofselect.DataSource = dataList;\nprofselect.SelectedText = dataList.Last();	0
9661005	9596859	Moving object head on click in unity	public body first_body;	0
32501338	32500898	How to add dynamic control to extended GridView that persists past OnPreRender?	protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)\n{\n    int result= base.CreateChildControls(dataSource, dataBinding);\n\n    LinkButton btn = new LinkButton() { Text = "Test" };\n    this.Controls.Add(btn);\n\n    btn.Click += button_Click;\n\n    return result;\n}	0
13125766	13125689	Order properties of object by value of customAttribute	var props = typeof(SampleClass)\n    .GetProperties()\n    .OrderBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().AttribName)\n    .ThenBy(p => p.GetCustomAttributes().OfType<CustomAttribute>().First().Index)\n    .Select(p => p.Name);\n\nvar propNames = String.Join(", ", props);	0
20987504	20987282	Open another window in xaml view in WPF	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    new View2().Show();\n}	0
2170906	2170875	How to delete from the registry using C#	RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect", true);\nkey.DeleteValue("AutoRun", true);	0
21265119	21041140	MVC 4 : Postback returns a array for property of type object in my model	public String StringValue\npublic Bool BooleanValue	0
8240341	8240059	Notification bubbles from nothing in C#	using System.Windows.Forms;\nusing System.Drawing;\n...\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    var item = new NotifyIcon(this.components);\n    item.Visible = true;\n    item.Icon = System.Drawing.SystemIcons.Information;\n    item.ShowBalloonTip(3000, "Balloon title", "Balloon text", ToolTipIcon.Info);\n}	0
1161152	1160442	ASP.NET StateBag and Custom Controls	StateBag mybag = new StateBag();\n(mybag as IStateManager).TrackViewState();	0
26389388	26389309	Issue with AES 256-Bit Encryption Key Size in C#	byte[] key = new byte[] { 0xB3, 0x74, 0xA2, 0x6A, 0x71, 0x49, 0x04 etc. };	0
13383832	13383643	C#: Need to remove last folder from file name path	string path = @"C:\Documents\MasterDocumentFolder\";\nDirectoryInfo parentDir = Directory.GetParent(path);\n// or possibly\nDirectoryInfo parentDir = Directory.GetParent(path.EndsWith("\\") ? path : string.Concat(path, "\\"));\n\n// The result is available here\nvar myParentDir = parentDir.Parent.FullName	0
1098071	1097972	Handling a series of named variables of the same type	foreach (var i in new[] {\n                           new{Dude=john, Booze=beer, Food=nachos},\n                           new{Dude=bob, Booze=cider, Food=chips}\n                        })\n{\n        if (i.Dude != designatedDriver)\n        {\n                i.Booze.Open();\n                i.Dude.Drink(i.Booze);\n                i.Dude.Eat(i.Food);\n        }\n}	0
21699446	21699407	Find and Replace text in html file	string markup = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN""\n    ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">\n<html xmlns=""http://www.w3.org/1999/xhtml"">\n<head>\n<meta name=""generator"" content=""HTML Tidy for Windows (vers 25 March 2009), see www.w3.org"" />\n<meta http-equiv=""Content-Type"" content=""text/html; charset=us-ascii"" />\n<link rel=""stylesheet"" type=""text/css"" href=""styles.css"" />\n<title></title>\n</head>\n<body>\n<p><b>Chapter 1</b></p>\n</body>\n</html>";\n      var html = new HtmlAgilityPack.HtmlDocument();\n      html.LoadHtml(markup);\n      var links = html.DocumentNode.SelectNodes("//link");\n      foreach (var link in links) {\n        link.Attributes["href"].Value = StaticClass.ZipFilePath +\n          "\\OEBPS\\styles.css";\n      }\n\n      var builder = new StringBuilder();\n      using (var writer = new StringWriter(builder)) {\n        html.Save(writer);\n      }\n      markup = builder.ToString();	0
9750401	9750355	How to query for objects with certain enum flag on, using a db int to store it	-- Setup Test Data \nDECLARE @Contacts TABLE (id int, contactType int, name nvarchar(MAX)) \n\nINSERT INTO @Contacts VALUES (1, 0, 'Fred'); -- Not Wanted\nINSERT INTO @Contacts VALUES (2, 3, 'Jim');  -- Wanted\nINSERT INTO @Contacts VALUES (3, 36, 'Mary');  -- Not wanted\nINSERT INTO @Contacts VALUEs (4, 78, 'Jo');  -- Wanted\n\n-- Execute Query\nSELECT *\nFROM @Contacts\nWHERE ContactType & 2 = 2	0
26929600	26908623	Error send image from client to WCF Server C# (Invalid length for a Base-64 char array)	public string ImageToBase64(Image image)\n    {\n        using (MemoryStream m = new MemoryStream())\n        {\n            image.Save(m, image.RawFormat);\n            byte[] imageBytes = m.ToArray();\n            string base64String = Convert.ToBase64String(imageBytes);\n            string a = base64String.Replace('/', '_').Replace('+', '-').Replace('=', ',');\n            base64String = a;\n            return base64String;\n        }\n    }\n\n    public Image Base64ToImage(string base64String)\n    {\n        // Convert Base64 String to byte[]\n        string a = base64String.Replace('_', '/').Replace('-', '+').Replace(',', '=');\n        base64String = a;\n        byte[] imageBytes = Convert.FromBase64String(base64String);\n        MemoryStream ms = new MemoryStream(imageBytes, 0,\n          imageBytes.Length);\n\n        // Convert byte[] to Image\n        ms.Write(imageBytes, 0, imageBytes.Length);\n        Image image = Image.FromStream(ms, true);\n        return image;\n    }	0
21050818	21050605	How to read and update value of nodes in an XElement	var attribute =\n   xDocument.Root.Elements()\n                 .Single(element => element.Attribute("key").Value == "RelativePath")\n                 .Attribute("value");\nstring oldValue = attribute.Value;   // to retrieve\nattribute.Value = newValue;          // to update	0
6305607	6305402	Irregualr behaviour with windows taskbar when making my application 'full screen' (WPF)	this.WindowState = WindowState.Normal;\nthis.WindowStyle = WindowStyle.None;\nthis.WindowState = WindowState.Maximized;	0
19220409	19219413	Popularity decay algorithm for popular website posts	Score = (P-1) / (T+2)^G\n\nwhere,\nP = points of an item (and -1 is to negate submitters vote)\nT = time since submission (in hours)\nG = Gravity, defaults to 1.8 in news.arc	0
26909729	26909571	Insert a variable into SQL database	cmd.CommandText = string.Format("INSERT INTO MSSG(REFERENCE_ID, TIMESTAMP, DEST_MSISDN, MESSAGE, TYPE, HOSTIP) VALUES ('1234567890', SYSDATE,@DEST_MSISDN,@MESSAGE,'0',(SELECT HOSTIP FROM SMPP_TRANSMITTER WHERE STATUS = 1 AND ROWNUM = 1))");\n\nString destMsisdn, message;\n\n//**todo** here, retrieve user input in those two variables\n\n\ncmd.Parameters.AddWithValue("@DEST_MSISDN", destMsisdn);\ncmd.Parameters.AddWithValue("@MESSAGE", message);	0
1325003	1324912	convert Dictionary<int, Enumerable> to Dictionary<int, Enumerable> inverting content	var newDic = dic\n   .SelectMany(pair => pair.Value\n                           .Select(val => new { Key = val, Value = pair.Key }))\n   .GroupBy(item => item.Key)\n   .ToDictionary(gr => gr.Key, gr => gr.Select(item => item.Value));	0
15478395	15477087	Lambda expression or delegate with run-time parameters	method = delegate(params object[] args)\n{\n    ...\n};	0
30730550	30730156	List of alphabet sort to display vertically	var alphabet = new []{'A', 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};\nvar rows = 3;\nvar alphabetIndex = 0;\n\nfor(var row = 0; row < rows; row++) {\n    for(var letter = alphabetIndex; letter < 26; letter += rows) {\n        Console.Out.Write(alphabet[letter] + " ");\n        if(letter + rows >= 26)\n            alphabetIndex = (letter + rows) - 26;\n    }\n    Console.Out.WriteLine();\n}	0
26999807	26980593	See SOAP format into web services with fiddler	Response is encoded and may require decoding before inspection. Click here to transform.	0
3445520	3445466	How to remove datatable column in c#	// index should include zero\nfor( int index=table.Columns.Count-1; index>=0; index-- )\n    {\n        table.Columns.RemoveAt( index );\n    }	0
18066990	5695827	How to get current value of EIP in managed code?	// using System.Runtime.CompilerServices \n// using System.Diagnostics; \n\npublic void DoProcessing()\n{\n    TraceMessage("Something happened.");\n}\n\npublic void TraceMessage(string message,\n        [CallerMemberName] string memberName = "",\n        [CallerFilePath] string sourceFilePath = "",\n        [CallerLineNumber] int sourceLineNumber = 0)\n{\n    Trace.WriteLine("message: " + message);\n    Trace.WriteLine("member name: " + memberName);\n    Trace.WriteLine("source file path: " + sourceFilePath);\n    Trace.WriteLine("source line number: " + sourceLineNumber);\n}\n\n// Sample Output: \n//  message: Something happened. \n//  member name: DoProcessing \n//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs \n//  source line number: 31	0
14235081	12910773	Serializing list of objects to .settings	public sealed class Favorites : ApplicationSettingsBase\n{\n    public Favorites()\n    {\n        this.FavoritesList = new List<Favorite>();\n    }\n\n    [UserScopedSetting]\n    public List<Favorite> FavoritesList\n    {\n        get\n        {\n            return (List<Favorite>)this["FavoritesList"];\n        }\n        set\n        {\n            this["FavoritesList"] = value;\n        }\n    }\n}\n\n[Serializable]\npublic class Favorit\n{\n    // ...\n}	0
4449288	4449159	Changing the src path of html5 audio element using c#	audioElement.Attributes["src"] = "something";	0
23700335	23700270	How to access number of controls as a name in c#?	Button btn = (Button) sender;\nint number = int.Parse(new string(btn.Name\n    .Reverse()\n    .TakeWhile(Char.IsDigit)\n    .Reverse().ToArray()));	0
17148639	17148484	Printing contents of string-variable to local printer ASP.NET	window.print()	0
1285270	1285222	DataTable Select: Expression with a space problem	var searchStr = "Bob Dude";\nvar splitSearchString = searchStr.Split(' ');\nvar columnNameStr = "Name";\nvar expression = new List<string>();\nDataTable table = new DataTable();\n//...  \nforeach (var searchElement in splitSearchString)\n{\n    expression.Add(\n        string.Format("[{0}] LIKE '*{1}*'", columnNameStr, searchElement));\n}\nvar searchExpressionString = string.Join(" OR ", expression.ToArray());\nDataRow[] rows = table.Select(searchExpressionString);	0
12877994	12877903	How to read and use formula from a string in c#?	var a = 6;\nvar b = 4.32m;\nvar c = 24.15m;\nvar result = engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});	0
25709223	25590147	Sql Case Statement implementation in ElasticSearch NEST client	new FilterDescriptor<ListingViewDTO>()\n                        .Or(\n                            fo => fo.Bool(b => b.Must(c => c.And(\n                                    fs => !fs.Term("OrganizationId", compositeFilter.OrganizationId)\n                                    , fs => fs.Query(q => q.Fuzzy(n => n.OnField("ListingAttributeDTO.AttributeName").Value("ListingPublish")))\n                                    , fs => fs.Query(q => q.Fuzzy(n => n.OnField("ListingAttributeDTO.Value").Value("1")))\n                                    , fs => fs.Term("VisibilityId", (int)Visibility.AnyOne)\n                                    , fs => fs.Term("StatusId", 2)\n                                )))\n                            , fo => fo.Term("OrganizationId", compositeFilter.OrganizationId)\n                            );	0
5580208	5579388	Extra White Space on my DataGrid WPF	public class TrimWhiteSpaceValueConverter : IValueConverter\n{\n        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n        {\n                if (value == null)\n                {\n                        return null;\n                }\n                return value.ToString().Trim();\n        }\n        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n        {\n                if (value == null)\n                {\n                        return null;\n                }\n                return value.ToString().Trim();\n        }\n}	0
16991198	16991171	Can I have a folder in my ASP.NET MVC4 project that is a webforms project?	MapPageRoute()	0
20349208	20349126	adding a child node to specific node in c#	private TreeNode FindNode(String name, TreeNode root)\n{\n    if(root.Name == name) return root;\n    Stack<TreeNode> nodes = new Stack<TreeNode>();\n    nodes.Push(root);\n    while(nodes.Count > 0)\n    {\n        var node = nodes.Pop();\n        foreach(TreeNode n in node.Nodes){\n           if (n.Name == name) return n;\n           nodes.Push(n);\n        }\n    }\n    return null;\n}\n//Usage\nvar node = FindNode(someName, treeView1.Nodes[0]);\n//if your treeView has more root nodes, you have to loop through them\nTreeNode node = null;\nforeach(TreeNode node in treeView1.Nodes){\n  node = FindNode(someName, node);\n  if(node != null) break;\n}	0
17252346	17168066	Microsoft Exchange: How To Resolve A Distinguished Name	string dn = "/O=CHEESE/OU=FIRST ADMINISTRATIVE GROUP/" +\n        "CN=RECIPIENTS/CN=LHALA1";\nstring MailAddress=string.Empty;\nstring user = string.Empty;\n\nusing (DirectorySearcher ds = new DirectorySearcher())\n{\n    ds.Filter = string.Format("(&(ObjectClass=User)(legacyExchangeDN={0}))", \n            dn);\n    SearchResultCollection src = ds.FindAll();\n    if (src.Count > 1)\n    {\n        //Oops too many!\n    }\n    else\n    {\n        user = src[0].Properties["samAccountName"][0].ToString();\n        MailAddress = src[0].Properties["Mail"][0].ToString();\n    }\n}	0
16393171	16388771	how to update datagrid view when bringing a form from background to foreground?	public LoginDb()\n    {\n        InitializeComponent();\n        this.Activated += new EventHandler(LoginDb_Activated);\n    }\n\n    void LoginDb_Activated(object sender, EventArgs e)\n    {\n        this.BindData();\n    }\n\n    private void BindData()\n    {\n        MyOleDbConnection.Open();\n        DataSet ds = new DataSet();\n        //DataTable dt = new DataTable();\n        ds.Tables.Add(dt);\n        OleDbDataAdapter da = new OleDbDataAdapter();\n        da = new OleDbDataAdapter("select * from login", MyOleDbConnection.vcon);\n        /*da.Fill(dt);\n        logindb_dataGridView.DataSource = dt.DefaultView;*/\n        da.Fill(dt);\n        logindb_dataGridView.DataSource = dt;\n        logindb_dataGridView.AutoResizeColumns();\n        MyOleDbConnection.Close();\n    }	0
18322740	18176722	How to write async linq	await Task.Factory.StartNew(() => PopulateList());	0
5186461	5186438	substring for words	public static String ParseButDontClip(String original, int maxLength)\n{\n    String response = original;\n\n    if (original.Length > maxLength)\n    {\n        int lastSpace = original.LastIndexOf(' ', original.Length - 1, maxLength);\n        if (lastSpace > -1)\n            response = original.Substring(0, lastSpace);\n    }\n    return response;\n}	0
34148592	34148443	How can I use a graphic object's clear function(which requires a color argument) to clear the graphics of a form?	gr.Clear(BackColor)	0
13513305	13483139	How to make WCF Data Service's entities implement an interface?	[KnownType(typeof(MyEntity1))], [KnownType(typeof(MyEntity2))]	0
8214887	8214842	use TryParseExact to format an integer value as a time	"yyyyMMdd"	0
17066835	17062558	PrintDocument using multiple page sizes	Sub SetPaperSize(ByVal nKind As PaperKind)\n        Dim ps As PaperSize\n\n        For ix As Integer = 0 To DocPrint.PrinterSettings.PaperSizes.Count - 1\n            If DocPrint.PrinterSettings.PaperSizes(ix).Kind = nKind Then\n                ps = DocPrint.PrinterSettings.PaperSizes(ix)\n                DocPrint.DefaultPageSettings.PaperSize = ps\n            End If\n        Next\n    End Sub	0
34041334	34039790	Defining Layout for the View in OnActionExecuted	protected override void OnActionExecuted(ActionExecutedContext filterContext)\n    {\n        base.OnActionExecuted(filterContext);\n        var res = filterContext.Result as ViewResult;\n        if (res != null)\n            res.MasterName = "~/Views/Shared/_FacbookCanvasLayout.cshtml";\n    }	0
13422100	13421604	Binding to User Control Properties in an Items Control	public string Text1 { get; set; }	0
23629967	23627992	Select the content of attribute value of input tag by XPATH	HtmlDocument.DocumentNode.SelectSingleNode("//input[@value]").Attributes["value"].Value;	0
5543088	5543028	WPF Deleting item from listbox	if (lstLocal.SelectedItem != null)\n{\n...\n}	0
24875606	24835104	Deployment of C# console application for Keyboard Listener	public static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)\n{\n    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)\n    {\n        Keys pressedKey = (Keys)Marshal.ReadInt32(lParam);\n\n        if (pressedKey == Keys.F11 || pressedKey == Keys.F12)\n        {\n            // Do something...\n\n            // Don't pass the key press on to the system\n            lParam = null;\n        }\n    }\n    return CallNextHookEx(_hookID, nCode, wParam, lParam);\n}	0
772391	772305	Dynamic Webservice reference from Class Library used in Winforms app (c#)	YourServiceProxy service = new YourServiceProxy();\nservice.Url = ConfigurationManager.AppSettings["YourURLKey"];	0
1890496	1400525	DateTimePicker Default value: How to avoid it?	DateTime dat1 = DateTime.Today;\nDateTime dat2 = dat1.AddDays(1).AddSeconds(-1);\n\ndtpCreatedStart.Value = dat1;\ndtpCreatedEnd.Value = dat2;\ntbc.SelectTab(1);\ndtpModifiedStart.Value = dat1;\ndtpModifiedEnd.Value = dat2;\ntbc.SelectTab(0);	0
25548121	25547955	Save data in a SortedDictionary by a resource file (txt)	public static SortedDictionary<UInt16, string> xTypes = new SortedDictionary<UInt16, string>();\n\nString[] rows = Regex.Split(Resources.ProTypes.ProTypesSource, "\r\n");\n\nforeach (var i in rows){\n    String[] words = i.Split(new[] { ',' });\n    xTypes.Add(UInt16.Parse(words[0]), words[1]);\n}	0
31126159	31125262	Controls from abstract base-Form not shown when inherited by a child Form	public partial class ConcreteForm : AbstractBaseForm\n{\n    public ConcreteForm() : base()\n    {\n         InitializeComponent();\n    }\n}	0
22780954	22779958	How To Give Back Focus From Console Window in C#?	// this should do the trick....\n\n[DllImport("user32.dll")]\npublic static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);\n[DllImport("user32.dll")]\npublic static extern bool SetForegroundWindow(IntPtr WindowHandle);\n\npublic const int SW_RESTORE = 9;\n\nprivate void FocusProcess(string procName)\n{\n    Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName);\n    if (objProcesses.Length > 0)\n    {\n        IntPtr hWnd = IntPtr.Zero;\n        hWnd = objProcesses[0].MainWindowHandle;\n        ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);\n        SetForegroundWindow(objProcesses[0].MainWindowHandle);\n    }\n}	0
9035870	9035817	ASP .NET C# get all text from a file in the web path	string email = File.ReadAllText(Server.MapPath("~/orderforms/email_templates/file_to_include.txt"))	0
8002427	8002418	Lock a previous form when opening a new one	Form2 f = new Form2();\nf.ShowDialog();	0
1503644	1503591	How to get language without country from CultureInfo	CultureInfo ci = CultureInfo.GetCultureInfo ("nl-nl");\n\nif( ci.IsNeutralCulture )\n{\n    Console.WriteLine (ci.EnglishName);\n    Console.WriteLine (ci.NativeName);\n}\nelse\n{\n    Console.WriteLine (ci.Parent.EnglishName);\n    Console.WriteLine (ci.Parent.NativeName);\n}	0
8927446	8927278	How to configure many to many relationship using entity framework fluent API	modelBuilder.Entity<Account>()\n            .HasMany(a => a.Products)\n            .WithMany()\n            .Map(x =>\n            {\n                x.MapLeftKey("Account_Id");\n                x.MapRightKey("Product_Id");\n                x.ToTable("AccountProducts");\n            });	0
8200981	8200801	Silent Printing at default printer in C#	ReportDocument rDoc = new ReportDocument();\nrDoc.Load("SomeReport.rpt");\n\n// Do whatever else you need to setup rDoc here\n// SetDatabaseLogon, VerifyDatabase, Set ParameterFields, etc.\n\n// Find out what the Default Printer Name is\nrDoc.PrintOptions.PrinterName = "Default Printer Name";\nrdoc.PrintToPrinter(1, false, 0, 0) //copies, collated, startpage, endpage	0
96470	94456	Load a WPF BitmapImage from a System.Drawing.Bitmap	ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n   bmp.GetHbitmap(), \n   IntPtr.Zero, \n   System.Windows.Int32Rect.Empty, \n   BitmapSizeOptions.FromWidthAndHeight(width, height));	0
3635269	3635249	Filtering out bad characters using a Regular Expression	s = Regex.Replace(s, @"^[^[\w*\$][\w\s-\$]*((\d{1,})){0,1}]$", "")	0
12258574	12244187	ASP.NET MVC3 Controller Method route variable parameters	public ActionResult myaction(string allsegments)\n{\n    var urlsegments = allsegments.split('/');\n    //...\n}\n\n\nroutes.MapRoute("betterroute",\n        "myaction/{*allsegments}",\n        new { controller = "mycontroller", action = "myaction"}\n        );	0
11303729	11112375	WPF user control not changing	ApplicationBody.Content = new WelcomeBody();	0
7472430	7472406	How to not render a Panel Control as a <div>	use PlaceHolder or  Literal	0
5439159	5439147	C# XNA - I have a Camera looking at a point -- so why do I need a projection matrix as well? Logic Question	x2d = x/z * screenwidth + screenwidth/2;\ny2d = y/z * screenheight + screenheight/2;	0
11331534	11330578	Quartz.Net cron trigger to schedule a job every 45 minutes	ITrigger trigger = TriggerBuilder.Create()\n    .WithIdentity("trigger1", "group1")\n    .WithDailyTimeIntervalSchedule(\n        x => x.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(8, 0))\n                 .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(11, 0))\n                 .WithIntervalInMinutes(45))\n    .Build();	0
2695435	2695385	Setting WCF Endpoint address at runtime?	binding = new WSHttpBinding("WSHttpBinding_IManagementService");	0
25640745	25567949	Adding a Postbuild event to a project	var propertyGroupElement = project.Xml.CreatePropertyGroupElement();\nproject.Xml.AppendChild(propertyGroupElement);\npropertyGroupElement.AddProperty(PreBuildEventFixture, PreBuildEvent);\npropertyGroupElement.AddProperty(PostBuildEventFixture, PostBuildEvent);	0
14022705	14022343	AES Decryption - Porting code from C# to Java	SecretKeySpec key = new SecretKeySpec(aesKey, "AES");	0
3831784	3828290	How to replace an exported part / object in a MEF container?	// first set up the main export provider\nvar mainCatalog = new AggregateCatalog(...); \nvar mainExportProvider = new CatalogExportProvider(mainCatalog);\n\n// now set up a container with mocks\nvar mockContainer = new CompositionContainer();\nmockContainer.ComposeExportedValue<IFoo>(fooMock);\nmockContainer.ComposeExportedValue<IBar>(barMock);\n\n// use this testContainer, it will give precedence to mocks when available\nvar testContainer = new CompositionContainer(mockContainer, mainExportProvider);\n\n// link back to the testContainer so mainExportProvider picks up the mocks\nmainExportProvider.SourceProvider = testContainer;	0
32513980	32513919	How Make a button dynamically?	SimpleButton sb = new SimpleButton();\nsb.Text = catalogo.Nombre;\nsb.Click += (sender, evntArgs) => {\n    //some dynamic mouse click handler here.\n};	0
21933362	21933320	How do I clear duplicate spaces In string	Dim a As String = "     wilcome      to  sa      WeCame    "\nDim cleanedString As String = Regex.Replace(a, "\s{2,}", " ").Trim()	0
4719156	4719109	Efficient/diffrent way to align data series	var combinedSeries = from record in series1\n            join record2 in series2\n            on record.Date == record2.Date  into JoinedLists\n            from joinedRecord in JoinedLists.DefaultIfEmpty()\n            orderby record.Date\n            select (whatever you want out of both records);	0
18658863	18657948	C# asp.net chart control, Get the pie slice color of data points	chart.Palette = ChartColorPalette.None;\nColors[] myColors = {Color.Red, Color.Green, Color.Blue, ...};\nchart.PaletteCustomColors = myColors;	0
2381052	2306573	How to check if the key is an unsaved value in NHibernate	mapping.Identifier.NullValue	0
12555827	12554256	Store the NULL value for a PictureEdit.Image	row[11] = imgData == null || imgData.Length == 0 ? DBNull.Value : imgData as Object;	0
10753697	10753604	search firstname from combination of lastname+", "+firstname using linq	if(LastName!=null)\n  Customer = Customer.Where(c => c.CustName.StartsWith(LastName)).ToList();	0
2841288	2841211	Read from XML > Add to Listview	XDocument xmlDoc = XDocument.Load("emails.xml");            \n\nvar t = from c in xmlDoc.Descendants("dt")\nselect new\n{\n    Name = e.Element("name").Value,\n    EMail = e.Element("email").Value,\n};\n\n\nforeach (var item in t)\n{                   \n    var lvi = listView.Items.Add(item.Name);\n    lvi.SubItems.Add(item.EMail);\n}	0
3700799	3700087	how to use the windows login credentials for proxy authentication using C#	oWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;	0
13642668	13642519	DataGridView - Delete items with ContextMenu	private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n        dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];\n    }\n}	0
19830686	19830235	Getting two excel files into ONE Excel Work Book	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Excel = Microsoft.Office.Interop.Excel;\n\nnamespace MergeBooks\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Excel.Application exApp = new Excel.Application();\n            Excel.Workbook wb1 = exApp.Workbooks.Open(@"C:\wb1.xls");\n            Excel.Workbook wb2 = exApp.Workbooks.Open(@"C:\wb2.xls");\n            Excel.Worksheet worksheet1 = wb1.Worksheets[1];\n            Excel.Worksheet worksheet2 = wb2.Worksheets[1];\n            worksheet1.Copy(worksheet2);\n            wb2.SaveAs(@"C:\wb3.xls");\n\n            wb1.Close(false);\n            wb2.Close(false);\n            exApp.Quit();\n\n        }\n    }\n}	0
21383868	21383825	Convert string to CrmDateTime	public CrmDateTime CRMFormattedDate(string dateValue)\n{\n    CrmDateTime cd = new CrmDateTime();\n    string date_str = "";\n\n    try\n    {\n        if (!isValidYear(dateValue.Substring(6, 4)))\n            date_str = DateTime.Now.Year.ToString();\n        else\n            date_str = dateValue.Substring(6, 4);\n\n        cd.Value = date_str + "/" + dateValue.Substring(3, 2) + "/" + dateValue.Substring(0, 2) + "T00:00:00";\n    }\n    catch (Exception ex)\n    { \n        cd = null; \n    }\n\n    return cd;\n}\n\nprivate bool isValidYear(string year_value)\n{\n    if (Convert.ToInt16(year_value) < 1800)\n        return false;\n\n    return true;\n}	0
13824562	13824428	How to post to the profile of other people using following code	client.Post("/PROFILE_ID/feed", new { message="Hi"});	0
3825015	3824690	C# WPF - ComboBox to also be a TextBox, for example: just like in office where users can choose Font Size or enter it	public partial class MainWindow : Window\n    {\n        public class SomeItem\n        {\n            public int[] Numbers { get; set; }\n            public string ChosenText { get; set; }\n        }\n\n        private SomeItem item;\n\n        public MainWindow()\n        {\n            InitializeComponent();\n            this.item = new SomeItem{Numbers=new[]{7,8,10}, ChosenText="10"};\n            this.testStackPanel.DataContext = item;\n        }\n\n        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)\n        {\n            MessageBox.Show(item.ChosenText);\n        }\n    }\n\n    <StackPanel VerticalAlignment="Center" x:Name="testStackPanel">\n        <ComboBox IsEditable="True" Width="100" ItemsSource="{Binding Numbers}" Text="{Binding ChosenText}"/>\n        <Button Content="Selected Value" Margin="0,10,0,0" Width="100" Click="Button_Click"/>\n    </StackPanel>	0
28942976	28942707	Log BackgroundWorker activity in a different class from the MainWindow	Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n                                           new Action(() => this.TextBoxToUpdate.Text= "Updated"));	0
6386989	6386924	ASP Login Control - Checking login status	if ( HttpContext.Current.User.Identity.IsAuthenticated){\n     do something\n}	0
22303313	22302604	how to get xml attribute values by its name in c#	var xDoc = XDocument.Load(filename);\nvar dict = xDoc.Descendants("Fields")\n            .ToDictionary(f => GetValue(f, "name"), f => GetValue(f, "expected"));\n\n\nstring GetValue(XElement root, string attr)\n{\n    return root.Elements("Field")\n                .First(a => a.Attribute("Name").Value == attr)\n                .Element("Value").Value;\n}	0
22460759	22460543	Filtering DateTime Column of DataTable Causes FormatException	CultureInfo myCultureInfo = new CultureInfo("en-gb");\ndt.Locale = myCultureInfo;\nDataRow[] rowArray = dt.Select("DOB >= #01/01/1997# AND DOB <= #31/01/1997#");	0
4993476	4993452	spliting 6 digit int into 3 parts?	// Assuming a more sensible format, where the logically most significant part\n// is the most significant part of the number too. That would allow sorting by\n// integer value to be equivalent to sorting chronologically.\nint day = date % 100;\nint month = (date / 100) % 100;\nint year = date / 10000;\n\n// Assuming the format from the question (not sensible IMO)\nint year = date % 100;\nint month = (date / 100) % 100;\nint day = date / 10000;	0
21302167	21302090	How can I change the row height some particular row in DataGridView?	DataGridViewColumn column = dataGridView.Columns[2];\ncolumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;	0
28631063	28631044	Convert a list of strings to an array	string[] AllGroupsForMembers = GroupMembersForViewMap .ToArray();	0
24326714	24326609	How to Display Data in C# form mysql table?	// You sql command\nMySqlCommand selectData;\n\n// Create the sql command\nselectData = dbcon.CreateCommand();\n\n// Declare the sript of sql command\nselectData.CommandText = "SELECT user_name, amount, FROM user_table";\n\n// Declare a reader, through which we will read the data.\nMySqlDataReader rdr = selectData.ExecuteReader();\n\n// Read the data\nwhile(rdr.Read())\n{\n    string userName = (string)rdr["user_name"];\n    string amount = (string)rdr["amount"];\n\n    // Print the data.\n    Console.WriteLine(username+" "+amount);\n}\n\nrdr.Close();	0
19703372	19702649	How I can filter my xml to a search value?	string val = x.Descendants("values")\n       .Where(el => el.Attribute("id").Value == btnadd_id)\n       .Elements("value")\n       .Where(l => l.Attribute("value").Value == language)\n       .SingleOrDefault()\n       .Attribute("display").Value;	0
2146831	2146806	Taking a screenshot without screen freeze. C# and WindowsXP	yourBackgroundWorker.RunWorkerAsync()	0
1708663	1707779	A table that shows MySql data, which the user can edit	private void dgColorCodeKey_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{  \n    if (e.RowIndex >= 0)\n    {\n        //if we are binding a cell in the Color column\n        if (e.ColumnIndex == colColor.Index)\n        {\n        //ColorCode is a custom object that contains the name of a System.Drawing.Color\n    ColorCode bindingObject = (ColorCode)dgColorCodeKey.Rows[e.RowIndex].DataBoundItem;\n    dgColorCodeKey[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.FromName(bindingObject.Color);\n\n    //set this property to true to tell the datagrid that we've applied our own formatting\n    e.FormattingApplied = true;\n        }\n    }\n}	0
23119650	23119538	Reuse item from a collection	var itemsGroupedById = creditItems.GroupdBy(item=> item.ID);\n\nforeach(var idGroup in itemsGroupedById)\n{\n    decimal total = idGroup.Sum(item => item.Quantity); // This sums up all quantities of the same ItemId\n    foreach(var item in idGroup) \n        item.Total = total; // This makes sure all items of the same kind store the total\n    Console.WriteLine("The total of item {0} is {1}", idGroup.Key, total);\n\n}	0
8726643	8726474	asp.net c# - combine / format a date and time from separate sources	string date = "20111215";\n        string time = "1417+0500";\n\n        string dateAndTime = date + time;\n\n        string format = "yyyyMMddHHmmzzz";\n\n        CultureInfo provider = CultureInfo.InvariantCulture;\n\n        DateTimeOffset t = DateTimeOffset.ParseExact(dateAndTime, format, provider);	0
22574164	22574039	Serialization Versus Encoding	1. The XML Infoset is the data model WCF uses internally to represent a message.\n2. The XML Infoset is the data model for representing an XML document.	0
19889032	19888911	ASP.NET C# use session data from dropdown	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string item=DropDownList.SelectedItem;\n    Session["selectedItem"]=item;\n    Response.Redirect("TheNextPageURL")\n}\n\npublic partial class TheNextPage : Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if(Session["selectedItem"]!=null)\n        {\n            Label1.Text=Session["selectedItem"].toString();\n        }\n    }\n}	0
13846544	13846163	Base 64 encoding issue	byte[] twiceDecoded = Convert.FromBase64String(Encoding.ASCII.GetString(Convert.FromBase64String(encoded)));	0
3839421	3837216	loading css style background-image url dynamically in c sharp	string imagePath = @"http://" + ConfigurationManager.AppSettings["DomainName"] + "/images/";\n\nstring htmlstring = "<tr style='border-width: 0px; height: 36px; background-image: url('" + imagePath + "cart_top_centbg.jpg');'>";	0
3298747	3298075	Can I expand a string that contains C# literal expressions at runtime	public static string ParseString(string txt)\n    {\n        var provider = new Microsoft.CSharp.CSharpCodeProvider();\n        var prms = new System.CodeDom.Compiler.CompilerParameters();\n        prms.GenerateExecutable = false;\n        prms.GenerateInMemory = true;\n        var results = provider.CompileAssemblyFromSource(prms, @"\nnamespace tmp\n{\n    public class tmpClass\n    {\n        public static string GetValue()\n        {\n             return " + "\"" + txt + "\"" + @";\n        }\n    }\n}");\n        System.Reflection.Assembly ass = results.CompiledAssembly;\n        var method = ass.GetType("tmp.tmpClass").GetMethod("GetValue");\n        return method.Invoke(null, null) as string;\n    }	0
2725396	2725320	How to detect which Windows account is running a .net application?	var id = System.Security.Principal.WindowsIdentity.GetCurrent();\nIdentityReferenceCollection irc = id.Groups;\nforeach (IdentityReference ir in irc)\n     Console.WriteLine(ir.Value);	0
3127519	3127498	C# How to redirect stream to the console Out?	sw = new StreamWriter(Console.OpenStandardOutput());\nsw.AutoFlush = true;\nConsole.SetOut(sw);	0
11376263	11376043	How to loop xmlnodes in parallel	var parallelLoop1 = xnList.Count;\n        Parallel.For(0, parallelLoop1, index =>\n        {\n         String NAME = xnList[index]["name"].InnerText;\n        }	0
637107	636902	serialport.Write() - how to format bytes properly	Byte[] bytes = { 80, 13, 10 };	0
19825228	19714165	Atomic Increment a counter field using DynamoDB in C#	var request = new UpdateItemRequest\n{\n    TableName = "Table",\n    Key = new Dictionary<string, AttributeValue>\n    {\n        { "id", new AttributeValue { N = "5" } }\n    },\n    AttributeUpdates = new Dictionary<string, AttributeValueUpdate>()\n    {\n        {\n            "count",\n            new AttributeValueUpdate { Action = "ADD", Value = new AttributeValue { N = "1" } }\n        },\n    },\n};	0
10973089	10973048	for statement inside a for each in c#	var Service = dsAuthors.Tables["Service"];\nfor (int i = 0; i < Service.Rows.Count; i++)\n{\n    if (Service.Rows[i][1].ToString() == "01")\n    {\n        Shipment.Rows[i][0] = "Service 1";\n    }\n    else if (Service.Rows[i][1].ToString() == "02")\n    {\n        Shipment.Rows[i][0] = "Service 2";\n    }\n}	0
30842016	30841995	Stored Procedure with parameters into DataGridView in C#	cmd.Parameters.AddWithValue("@varCURRENCY", "USD"); // #1\ncmd.Parameters.AddWithValue("@invSTART", "0");\ncmd.Parameters.AddWithValue("@invEND", "399999");\ncmd.Parameters.AddWithValue("@varCURRENCY", "0"); // #2	0
23289378	23274647	Access response nodes after calling a web service in C# console application	int count = 0;\n    int total = result.ForecastResult.Length;\n    foreach (var rs in result.ForecastResult){\n      if (count > 0)\n      {\n        Console.WriteLine("************************");\n      }\n      Console.WriteLine("Date:" + rs.Date);\n      Console.WriteLine("Forecast:" + rs.Desciption);\n      Console.WriteLine("Temperatures:");\n      Console.WriteLine("Morning low - " + rs.Temperatures.MorningLow);\n      Console.WriteLine("Daytime high - " + rs.Temperatures.DaytimeHigh);\n      count++;\n    }\n    Console.WriteLine("------------------------------------------------------------------");\n    Console.Write("ENTER to continue:");\n    Console.ReadLine();	0
1389413	585461	How to get the available translations from a dll	private void SettingsForm_Load(object sender, EventArgs e)\n    {\n   // load default language to the list\n        languageList.Add(new Language("English", "en"));\n        string fileName = "myProgram.resources.dll";\n\n   // load other languages available in the folder\n        DirectoryInfo di = new DirectoryInfo(Application.StartupPath);\n        foreach (DirectoryInfo dir in di.GetDirectories())\n        {\n            if (File.Exists(dir.FullName + "\\" + fileName))\n            {\n                try\n                {\n                    CultureInfo ci = new CultureInfo(dir.Name);\n                    languageList.Add(new Language(ci.NativeName, ci.Name));\n                }\n                catch\n                {\n                    // whatever happens just don't load the language and proceed ;)\n                    continue;\n                }\n            }\n        }\n    }	0
19510150	19477233	Add xml namespace to XDocument	XDocument xDoc = new XDocument(new XElement("root",\n            new XAttribute(XNamespace.Xmlns + "ns1", ns1),\n                new XElement(ns1 + "collection",\n                    new XElement(ns1 + "child1", value1),\n                    new XElement(ns1 + "child2", value2),\n                     new XElement(ns1 + "child3", value3))));	0
21285595	21285477	Best way to get javascript variable value	new Regex("'IS_UNAVAILABLE_PAGE': (?<value>true|false)");	0
7552388	7412853	RibbonControlsLibrary - how to disable minimizing?	public class ExRibbon : Ribbon\n{\n    public override void OnApplyTemplate()\n    {\n         base.OnApplyTemplate();\n\n         if (!IsMinimizable)\n         {\n              IsMinimizedProperty.OverrideMetadata(typeof(ExRibbon), \n                   new FrameworkPropertyMetadata(false, (o, e) => { }, (o,e) => false));\n         }\n    }\n    public bool IsMinimizable { get; set; }\n}	0
7331454	7331399	Save a image from asp.net website	bitmap.Save(HttpContext.Current.Server.MapPath("/img/bitmap.png"));	0
3058220	3010191	export data from WCF Service to excel	[ServiceBehavior(MaxItemsInObjectGraph=2147483646)]\npublic abstract class MyService: IMyService	0
6563312	6563269	How to save the Password in C# .NET?	private bool CheckPassword(string salt, string password) \n{\n   var hash = Encoding.ASCII.GetBytes(salt + password);\n   var sha1 = new SHA1CryptoServiceProvider();\n   var sha1hash = sha1.ComputeHash(hash);\n   var hashedPassword = ASCIIEncoding.GetString(sha1hash);\n\n   return (Properties.Settings.Default.adminPass == hashedPassword);\n}	0
19086025	19085913	sorting array with array.sort	protected void sortImageButton_Click(object sender, ImageClickEventArgs e)\n{        \n    string[] sort = new string[cartListBox.Items.Count];\n\n    for (int i = 0; i < sort.Length; i++)\n    {\n        sort[i] = cartListBox.Items[i].ToString();\n    }\n    Array.Sort(sort);\n\n    for (int i = 0; i < sort.Length; i++)\n    {\n        // reset the order for the cartListBox collection according to the sort array, if needed\n    }\n}	0
8274713	8261974	Get attribute value from HTML element in WebBrowser	webBrowser1.SaveToString()	0
20212928	20212900	executing an object's method from multiple lists using linq	foreach(var item in listA.OfType<I>().Concat(listB.OfType<I>()))\n    item.DoSomething();	0
10219389	10219274	Regex Matching, cascaded tags	counter = 0;\nwhile (m.Success)\n{\n        if( counter % 4 == 0 )\n        {\n            testMatch = "";\n\n            //\n            testMatch += System.Text.RegularExpressions.Regex.Unescape(m.Groups[0].ToString()).Trim();\n\n\n\n            top.Add(new Top(testMatch));\n            m = m.NextMatch();\n\n        }\n        counter++;\n}	0
4025055	4024956	ASP.NET MVC2 - How to call another controller with RenderAction() as well as pass arguments to that controller?	public class NavigationController\n{\n    [ChildActionOnly]\n    public ViewResult Menu(string currentAction, string currentController)\n    {\n        var navigationViewModel = new NavigationViewModel();\n\n        // delegates the actual highlighing to your view model\n        navigationViewModel.Highlight(currentAction, currentController);\n\n        return View(navigationViewModel);\n    }\n}	0
5944982	5944845	C# Using XPATH to select specific element with known values, then delete	"/Manager/SSH/Tunnels/Port[Local=" + _local + " and  Remote=" + _remote + "]"	0
23866782	23864996	How to get count rows in AspxGridView?	int countOnline = 0;\nforeach (DataRow dr in dataTable.Rows)\n{\n    if (dr["Status"].Equals("1"))\n    {\n          countOnline++;\n    }\n}\nint countOffline = dataTable.Rows.Count - countOnline;	0
30445454	30442915	Ror byte array with C#	static byte[] ROR_ByteArray(byte[] arr, int nShift)\n{\n  return ROL_ByteArray(arr, arr.Length*8-nShift);\n}	0
14322549	14293022	How can i sort the directories as they appear on my hard disk?	DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>\n                    {\n                        int i = 0;\n                        if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))\n                        {\n                            string z = d.Name.Substring(("Lightning ").Length);\n                            string f = z.Substring(0, z.IndexOf(" Length"));\n                            if (Int32.TryParse(f, out i))\n                                return i;\n                            else\n                                return -1;\n                        }\n                        else\n                            return -1;\n                    }).ToArray();	0
30139987	29991521	DrawerLayout in Windows Phone	CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;\nawait dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {\n      Frame.navigate(typeof(YourPage));\n});	0
30565207	30565166	Read XML Attribute using C#	XmlNodeList elemList = doc.GetElementsByTagName("Your Element");\nfor (int i = 0; i < elemList.Count; i++)\n{\n    string attrVal = elemList[i].Attributes["ID"].Value;\n}	0
21041977	21041736	Splitting a String using regex in c#	String str = @"tv_rocscores_DeDeP005M3TSub.csv FMR: 0.0009 FNMR: 0.023809524 SCORE: -4  Conformity: True";\n\n  String[] parts = str.Split(' ');\n  parts[0] = Regex.Match(parts[0], @"P\d\d\d").Value; // <- "P005"	0
25878314	25878176	Multiple variables in switch-case statement	Switch (DepartmentID)\n  {\n\n     case  1:\n         Email = classHR.GetEmailAddress(Status);\n         break;\n     case  2: \n         Email = classMarketing.GetEmailAddress(Status);\n         break;\n   }	0
18759811	18759734	How can i provide a consistent value to all the similar nodes using c#	var doc = new XmlDocument();\n            doc.Load("Your XML Path");\n            XmlElement root = doc.DocumentElement;\n            XmlNodeList nodes = root.SelectNodes("Bugs/Bug");                \n            foreach (XmlNode node in nodes)\n            {                 \n                    node["foundInBuild"].InnerText = "Your New Value";                   \n            }	0
31427959	31425754	How to add data to Gridview using specific field name searching	protected void Button3_Click(object sender, EventArgs e)        \n     {          \n        String str = " Select CODE," + DropDownList2.SelectedValu+ " From OthStk Where CODE='a103';";    \n\nSqlConnection con = new SqlConnection(your connection)\n        SqlCommand xp = new SqlCommand(str, con);     \n         con.Open();         \n         SqlDataAdapter da = new SqlDataAdapter();     \n         da.SelectCommand = xp;\n         DataSet ds = new DataSet();\n         da.Fill(ds,"BranchCode");   \n         GridView2.DataSource = ds;\n         GridView2.DataBind();\n         con.Close();\n     }	0
29735895	29709298	How to use Automapper inside GenericRepository to Map Entities to DTO?	var mappedEntities = query\n    .OrderBy(option.orderBy + " " + option.orderByType)\n    .Skip(option.start * option.size)\n    .Take(option.size)\n    .Project().To<U>()\n    .ToList();	0
6064567	6064472	Same Variable Names - 2 Different Classes - How To Copy Values From One To Another - Reflection - C#	Type typeB = b.GetType();\nforeach (PropertyInfo property in a.GetType().GetProperties())\n{\n    if (!property.CanRead || (property.GetIndexParameters().Length > 0))\n        continue;\n\n    PropertyInfo other = typeB.GetProperty(property.Name);\n    if ((other != null) && (other.CanWrite))\n        other.SetValue(b, property.GetValue(a, null), null);\n}	0
8814841	8814811	Remove blank values in the array using c#	test =  test.Where(x => !string.IsNullOrEmpty(x)).ToArray();	0
10951517	10916206	Close a Javascript popup containing silverlight	var openedWindows = new Array();	0
22150123	22149938	Linq to XML Descendants can't read part of xml	xml = "<document>" +\n    "<indexroot>" +\n    "    <type>type</type>" +\n    "    <model>model</model>" +\n    "</indexroot>" +\n    "<root>" +\n    "    <model_type1>model type 1</model_type1>" +\n    "    <model_type2>model type 2</model_type2>" +\n    "</root>" +\n    "</document>";\n\n    XDocument doc = XDocument.Parse(xml);\n\n    var newItem = (from element in doc.Descendants("document")\n                select new \n    {\n        Type = (string)element.Element("indexroot").Element("type") ?? "-",\n        Model = (string)element.Element("indexroot").Element("model") ?? "-",\n        ModelType1 = (string)element.Element("root").Element("model_type1") ?? "-",\n        ModelType2 = (string)element.Element("root").Element("model_type2") ?? "-",\n    }).FirstOrDefault();\n\n    Console.WriteLine(newItem);	0
32250397	32250021	Create HTML Table in C# with foreach loop	StringBuilder body = new StringBuilder();\nbody.AppendFormat (\n    @"Dear all, there is my new table:\n    TableNo: {0} <br /> <br />\n    <table border='1'><tr><th>Line No</th><th>Table</th><th>Description</th><th>Count</th><th>Met</th><th>something</th></tr>"\n    , dataObj.Obj.Table.TableNumber);\nforeach (var item in dataObj.Table.TableLineCollection)\n{\n    body.AppendFormat(\n    @"<tr><td> {0}</td>\n    <tr><td> {1}</td>\n    <tr><td> {2}</td></tr>",\n    item.LineNumber, item.Table, item.Description);\n}	0
147149	146358	Efficiently merge string arrays in .NET, keeping distinct values	string[] result = list1.Union(list2).ToArray();	0
1079316	1079292	Should I use set once variables?	ThingieBuilder tb = new ThingieBuilder();\ntb.FooThingy = 17.23;   // r/w properties\ntb.BarThingy = 42;\ntb.UseExtendedThingamagicAdapter = true;\nThingie t = tb.Create();\nif (t.Bar==42) // r/o property\n  ...	0
12279366	11947927	Facebook feed - remove extra Facebook JS from anchor	searchPattern = "<a(.*?)href=\"/l.php...(.*?)&amp;?(.*?)>(.*?)</a>";\n          string html1 = Regex.Replace(html, searchPattern, delegate(Match oMatch)\n    {\n        return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", HttpUtility.UrlDecode(oMatch.Groups[2].Value), oMatch.Groups[4].Value);\n\n    });	0
4724808	4724671	How to receive event on Panel Controls?	PictureBox pbx = new PictureBox();\n pbx.Click += new EventHandler(pbx_Click);\n //Now assign other properties and then add it to control collection\n //panel1.Controls.Add(pbx);\n\n\n\nprivate void pbx_Click(object sender, EventArgs e)\n{\n     //handle the click event here\n}	0
15851236	15786743	Win8 Javascript Metro App, with C# WinRT Component and SQLite	using myclasslib;	0
4505091	4504829	add a row to a datatable from a row in a different datatable	dt_final.ImportRow(dt.Rows[i]);	0
1607177	1607151	Unable to access jar file	Arguments = "/c java -ms16m -mx512m -jar \"" + pathToJavaApp \n    + "\"/javaApp.jar 3562"	0
21385311	21380812	What is best practice for using Unity with Entity Framework in a MVC 4 application	UnityContainer.Resolve<AutoMapperConfig>().MapAutoMapper();	0
2551190	2550929	Deep copying of tree view nodes	List<TreeNode> tnc = null;\nprivate TypeIn()\n{\n      tnc  = new List<TreeNode>();\n      foreach (TreeNode n in treeView1.Nodes)\n      {\n          tnc.Add((TreeNode)n.Clone());\n      }\n      treeView1.Nodes.Clear();\n\n}	0
15927818	15927437	How do I call a method from within a linq query that is retrieving from an Entity Framework model	return (_entities.Users.AsEnumerable().Select(profile => new ProfileUserListItemDto\n                {\n                    Email = profile.Email,\n                    FirstName = profile.FirstName,\n                    Id = profile.Id,\n                    LastName = profile.LastName,\n                    Role = DtoEntityLookups.EntityRoleToDtoRole(profile.Role),\n                    TimeZone = profile.TimeZone\n                })).ToList();	0
20130815	20130769	Writing File to Temp Folder	string result = Path.GetTempPath();	0
1550555	1536902	How do I generate a Quality Center recordset with C#?	static TDAPIOLELib.Recordset GetRecSet(String Qry, TDAPIOLELib.TDConnection TD)\n        {\n\n            TDAPIOLELib.Command Com;\n            Com = TD.Command as TDAPIOLELib.Command;\n            Com.CommandText = Qry;\n\n            TDAPIOLELib.Recordset RecSet = Com.Execute() as TDAPIOLELib.Recordset;\n            return RecSet;\n\n        }	0
26048739	26047641	XML to LINQ parsing of an XML with namespace in C#	var nmspc = XNamespace.Get(@"http://schemas.xmlsoap.org/soap/envelope/");\nvar ns2 = XNamespace.Get(@"urn:nike:sale:DigitalSalesToSabrix");\n\nvar trans = xdoc.Root.Elements(nmspc + "Body").Elements(ns2 + "DigSales").Elements(ns2 + "Tran");	0
12381432	12381382	c# retrive pdf file from database	b= Encoding.ASCII.GetBytes(dt.Rows[0][0].ToString());	0
20280398	20280160	How to call a function in onclick event in xamarin.studio	btn9.Click += (object sender, EventArgs e) => {\n            Buttonclick (sender, e);\n        };\n        btnadd.Click += (object sender, EventArgs e) => {\n            operationbuttonclick (sender, e);\n        };\n        btnmul.Click += (object sender, EventArgs e) => {\n            operationbuttonclick (sender, e);\n        };\n        btnsub.Click += (object sender, EventArgs e) => {\n            operationbuttonclick (sender, e);\n        };\n        btndiv.Click += (object sender, EventArgs e) => {\n            operationbuttonclick (sender, e);\n        };\n        btneql.Click += delegate {\n            txt1.Text=result.ToString();\n            isfirst=true;\n            hasdecimal=true;\n            shouldclear=true;\n        };\n        btnCE.Click += delegate {\n            txt1.Text="0";\n            result=0;\n            isfirst=true;\n            shouldclear=true;\n            hasdecimal=false;\n        };	0
11781850	11781466	OpenNetCf - C# into VB	Private Sub WatchForDrives()\n    Dim monitor As New DeviceStatusMonitor(DeviceClass.FileSystem, False)\n    monitor.StartStatusMonitoring()\n    AddHandler monitor.DeviceNotification, AddressOf MonitorDeviceNotified\nEnd Sub\n\nPrivate Sub MonitorDeviceNotified(ByVal sender As Object, ByVal e As DeviceNotificationArgs)\n    Dim message As String = String.Format("Disk '{0}' has been {1}.", e.DeviceName, If(e.DeviceAttached, "inserted", "removed"))\n    MessageBox.Show(message)\nEnd Sub	0
18556633	18556586	How to group by month in LINQ query?	.GroupBy(x => SqlFunctions.DatePart("m", x.date))	0
25423735	25423700	Use LINQ to aggregate on a list of lists	dataList\n.SelectMany(x => x.Errors)\n.GroupBy(x => x)\n.Select(g => new { Value = g.Key, Count = g.Count() })	0
29507225	29507001	How to store 2D string array in a session?	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        ToSession();\n        FromSession();\n    }\n}\nprivate void ToSession() \n{ \n    string[,] strTo2D = { {"A"}, {"B"} };\n    Session["str2DArray"] = strTo2D; \n}\nprivate void FromSession() \n{\n    string[,] strFrom2D = (string[,])Session["str2DArray"];\n    Response.Write(strFrom2D[0, 0].ToString()); \n}	0
15300584	15300515	LookUpEdit looses its value after lost focus event	myLookUpOrCombo.DataBindings.Clear();\nmyLookUpOrCombo.DataBindings.Add("EditValue", myObjectSource, "IdOfaForeignKey", true, DataSourceUpdateMode.OnPropertyChanged, null);	0
27550183	27549678	Row Count on Gridview	ds.Tables[0].Rows.Count	0
2310995	2310969	Can I make interfaces or abstract classes in C# that declare methods with a parameter of unknown type?	public abstract class Parameter<T>\n{ \n    public bool IsSet { get; protected set; } \n    protected Parameter() { IsSet = false; } \n    public abstract void Set(T value);\n    public T Value;\n}\npublic class IntParameter : Parameter<int>\n{\n    public override void Set(int value)\n    {\n        Value = value;\n        IsSet = true;\n    }\n}	0
24171269	24171150	how to remove all uncheck items from listview c#	foreach (ListViewItem item in listView_supplierNames.Items)\n            {\n                if (item.Checked)\n                {\n\n                }\n                else\n                {\n                    //Remove unchecked Items\n                     listView1.Items.Remove(item);\n                }\n            }	0
17421886	17416701	Drawing a line in OpenGL	private void drawLine() {\n        GL.glViewport(0, 0, window_width, window_height);\n\n        GL.glMatrixMode(GL_PROJECTION);\n        GL.glLoadIdentity();\n        GL.glOrtho(0, window_width, 0, window_height, -1, 1);\n\n        GL.glMatrixMode(GL_MODELVIEW);\n        GL.glLoadIdentity();\n\n        GL.glClear(GL.GL_COLOR_BUFFER_BIT);\n        GL.glBegin(GL.GL_LINES);\n        GL.glVertex3f(100.0f, 100.0f, 0.0f); // origin of the line\n        GL.glVertex3f(200.0f, 140.0f, 5.0f); // ending point of the line\n        GL.glEnd(); \n\n        GL.glFlush();\n\n        this.SwapBuffer(); // if the form doesn't automatically swap\n    }	0
7773714	7761202	How do I redirect to a page with an ID that doesn't exist yet?	//Excerpt  \n    db.form.Add(ViewModel);\n    return RedirectToAction("Stage2", new {id = ViewModel.id));	0
26296106	26296037	how to sort csv file with two columns in c#	var sorted = data.Select(line => new\n{\n    SortKey = Int32.Parse(line.Split(';')[9]),\n    SortKeyThenBy = Int32.Parse(line.Split(';')[2]),\n    Line = line\n}\n).OrderBy(x => x.SortKey).ThenBy(x => x.SortKeyThenBy)	0
32117119	32116405	Change the hash of a PE executable by changing the checksum header	FileUtils.WriteCheckSum(sourceFile, destFile1, 1);\nFileUtils.WriteCheckSum(sourceFile, destFile2, 2);	0
10597434	10597299	c#, is there OnChange event in ListBox?	Windows Forms	0
14113084	14112689	How can a Windows Store App close itself?	Application.Current.Close()	0
23083954	23055256	Regain focus after flyout closed in a Store App	protected override void OnGotFocus(RoutedEventArgs e)\n    {\n        base.OnGotFocus(e);\n    }	0
26168921	26158625	change the position of X axis Labels with 2 series	Chart1.Series["female"].XAxisType = AxisType.Primary;	0
4318535	4318176	DialogResult in WPF Application in C#	MessageBoxResult result = MessageBox.Show("My Message Question", "My Title", MessageBoxButton.YesNo, MessageBoxImage.Question);\nif (result == MessageBoxResult.Yes)\n{\n    // Do this\n}	0
6059665	6052461	UnityContainer - how register/resolve with dependency chaining	public class AppConfigConnectionFactory : IConnectionFactory\n{\n   public IDbConnection Create() \n   { \n        return new SqlConnection(ConfigurationManager\n             .ConnectionStrings["ApplicationServices"].ConnectionString);\n   }\n}\n\nc.RegisterType<IConnectionFactory, AppConfigConnectionFactory>();\nc.RegisterType<IDepartmentRepository, DepartmentRepository>();	0
18421624	18421375	How do I pass a c# variable to a python script from windows form application	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.FileName = "C:\\Python27\\Scripts\\path\\file.py";\nstartInfo.Arguments = "myvariable";\n\ntry \n{\n    using (Process exeProcess = Process.Start(startInfo))\n    {\n         //dostuff\n         exeProcess.WaitForExit();\n    }\n}\ncatch\n{\n    //log\n    throw;\n}	0
5765399	5765389	List collection that replaces numbers with words	var num = new List<string>();\n\n    for (int n = 0; n < 101; n++)\n    {\n        if( n % 10 == 0)\n        {\n           num.Add("dTen");\n        }\n        else num.Add(n % 2 == 0 ? "dTwo" : n.ToString());\n    }	0
15815826	15815718	How to break a loop by a shorthand "if-else" result?	?: Operator (C#)	0
9106438	9106415	Convert date time with miliseconds to double or int?	var span = DateTime.ParseExact(TimeString,\n                            "yyyy.MM.dd HH:mm:ss.fff",\n                            CultureInfo.InvariantCulture) -\n        new DateTime(2011, 01, 02, 22, 06, 52, 0);\ndouble d = span.TotalMilliseconds/1000.0;	0
32677799	32677680	How to save xml file into xml column	public void SaveXml(int id, string xmlFileName)\n{\n    // read your XML\n    string xmlContent = File.ReadAllText(xmlFileName);\n\n    // set up query\n    string insertQuery = "INSERT INTO pages(BPMNID, XML) VALUES (@BPMNID, @XML)";\n\n    using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))\n    using (SqlCommand cmd = new SqlCommand(insertQuery, conn))\n    {\n        // define parameters\n        cmd.Parameters.Add("@BPMNID", SqlDbType.Int).Value = id;\n        cmd.Parameters.Add("@XML", SqlDbType.VarChar, -1).Value = xmlContent;\n\n        // open connection, execute query, close connection\n        conn.Open();\n        cmd.ExecuteNonQuery();\n        conn.Close();\n    }\n}	0
7646125	7597263	ninject and enterprise library service locator dependant assemblies	var kernel = new StandardKernel();\n//do bindings -> throw error here without reaching below two lines to regiester the service locator\nvar locator = new NinjectServiceLocator(kernel);\nServiceLocator.SetLocatorProvider(() => locator);	0
31982186	31982148	Flashing an image with specific frequency	public static void Main()\n{\n    var timer = new System.Timers.Timer()\n   {\n\n    Elapsed += new ElapsedEventHandler(OnTimedEvent),\n    Interval = 5000,\n    Enabled = true\n   }\n}\n\n private static void OnTimedEvent(object source, ElapsedEventArgs e)\n {\n    //your timer is executing\n     myImageBox.Visible = !myImageBox.Visible\n }	0
23190861	23190829	get keys of KeyValuePair List to int[] array using linq	List<KeyValuePair<int,string>> infos;\n\nint[] keys = infos.Where(kvp => kvp.Value == "Sur").Select(kvp => kvp.Key).ToArray();	0
3472623	3471264	FluentNHibernate One-To-One using a ForeignKey constraint	one-to-one	0
12294292	12294094	how to work with session list<t> in asp.net while refreshing page	public static List<DragAndDropData> getdata()\n {\n         List<DragAndDropData> LeftSideList=new List<DragAndDropData>();\n         if(Session["leftside"]!=null)\n         {\n           LeftSideList=(List<DragAndDropData>)Session["leftside"];\n         }\n         else\n         {\n           LeftSideList.Add(new DragAndDropData { Id = 0, Name = "Item1" });\n           LeftSideList.Add(new DragAndDropData { Id = 1, Name = "Item2" });\n           LeftSideList.Add(new DragAndDropData { Id = 2, Name = "Item3" });\n           LeftSideList.Add(new DragAndDropData { Id = 3, Name = "Item4" });\n           LeftSideList.Add(new DragAndDropData { Id = 4, Name = "Item5" });\n\n    }\n         return LeftSideList;\n }	0
10269214	10265917	find page number of a string in pdf file in c#	// add any string you want to match on\nRegex regex = new Regex("the", \n  RegexOptions.IgnoreCase | RegexOptions.Compiled \n);\nPdfReader reader = new PdfReader(pdfPath);\nPdfReaderContentParser parser = new PdfReaderContentParser(reader);\nfor (int i = 1; i <= reader.NumberOfPages; i++) {\n  ITextExtractionStrategy strategy = parser.ProcessContent(\n    i, new SimpleTextExtractionStrategy()\n  );\n  if ( regex.IsMatch(strategy.GetResultantText()) ) {\n    // do whatever with corresponding page number i...\n  }\n}	0
19673431	19673395	How to achieve a specific format using DateTime in C#?	DateTime dateValue = new DateTime(2008, 6, 11);\nstring result = dateValue.ToString("dd/MM/yy ddd");	0
33439567	33439417	How can I Get the property by name from type and Set Propert value using reflection in C#	//1. Create new instance of Student\nStudent student = new Student();\n\n//2. Get instance type\nvar getType = student.GetType();\n\n//3. Get property FullName by name from type\nvar fullNameProperty = getType.GetProperty("FullName",\n        typeof(string));\n\n//4.  Set property value to "Some Name" using reflection\nfullNameProperty.SetValue(student, "Some Name");	0
27473166	27472907	Get value of an element by javascript in awesomium c#	JSObject ch = br.ExecuteJavascriptWithResult("document");\ndynamic document = (JSObject)ch ;\nif (document == null) return false;\nusing (document)\n{\n   document.getElementById('ltrl').value;\n}	0
24437931	24437813	Change entire zedgraph background color	// This will do the area outside of the graphing area\nGraphPane.Fill = new Fill(Color.FromArgb(222, 224, 212));\n// This will do the area inside the graphing area\nGraphPane.Chart.Fill = new Fill(Color.FromArgb(222, 224, 212));	0
19270183	19269956	The best practice approach for displaying error messages with multi-language interface	string.Format("{0} is unavailable for selected period", _userName);	0
18014187	18014077	C# Finding if a list contains an item duplicated 5 times	var listOfFiveTimers = list.GroupBy(s => s)\n                           .Where(g => g.Count() == 5)\n                           .Select(g => g.Key)\n                           .ToList();	0
2381863	2380751	What to put in Spark SetPageBaseType setting	engine.Settings.PageBaseType = typeof(ApplicationView).FullName;	0
20681727	20681573	How to parse XML without a schema?	XElement node=XElement.Parse(input);\nnode.Element("base").Value;\nnode.Element("alt").Value;\nnode.Element("value").Attributes("type").Value;//attribute value\nnode.Element("value").Value;	0
3167686	3167637	How can I easily exclude certain lines of code from a compile?	[Conditional("DEBUG")]	0
23564774	23564619	What's the best way for maintaining a MySQL connection in WPF?	public class CustomerViewModel : WorkspaceViewModel, IDataErrorInfo\n{\n    ...\n    public void Save()\n    {\n        if (!_customer.IsValid)\n            throw new InvalidOperationException(Strings.CustomerViewModel_Exception_CannotSave);\n\n        if (this.IsNewCustomer)\n            _customerRepository.AddCustomer(_customer);\n\n        base.OnPropertyChanged("DisplayName");\n    }	0
19491365	19489082	Write to a file after it is started as a process causes UnauthorizedAccessException (Access to the path XXX is denied.)	File.Delete("test_a.cmd.bak");\nFile.Move("test_a.cmd", "test_a.cmd.bak");\nfor (int attempt = 0; ; ++attempt) {\n    try {\n       File.WriteAllText("test_a.cmd", "timeout 15");\n       break;\n    }\n    catch (System.UnauthorizedAccessException ex) {\n       if (attempt > 10) throw;\n       System.Threading.Thread.Sleep(1000);\n    }\n}\ntry {\n    File.Delete("test_a.cmd.bak");\n}\ncatch (Exception ex) {}	0
28308417	28308279	Parsing a Custom DateTime string	var ok = DateTime.ParseExact(\n     "Wednesday, March 4, 2015 - 9:00 AM PST", "dddd, MMMM d, yyyy - h:mm tt PST",\n      new CultureInfo("en-us"))\nvar failed = DateTime.ParseExact(\n     "Wednesday, March 4, 2015 - 9:00 AM PST", "dddd, MMMM d, yyyy - h:mm tt PST",\n      new CultureInfo("de-de"))	0
20397240	20397197	Output string with line breaks to file in console application	string outDataString = string.Format(\n"Hi, this is the out data.{0}With a few{0} line breaks.",\nEnvironment.NewLine);	0
20360153	20331722	Same KnownType Attribute For Multiple Abstract Classes	namespace Thing\n\n[KnownType(typeof(Tomato))]\npublic abstract class Fruit : Vegetable { }\n\npublic sealed class Tomato : Fruit{}\n\nnamespace Thing\n\n[KnownType(typeof(Tomato))]\npublic abstract class Vegetable {}\n\npublic sealed class Carrot : Vegetable{}	0
9784365	9784285	How To: Convert anonymous method to VB.NET	AddHandler animation.Completed, _\n    Sub(sender As Object, e As EventArgs)\n      ' '\n      ' When the animation has completed bake final value of the animation '\n      ' into the property. '\n      '\n      animatableElement.SetValue(dependencyProperty, animatableElement.GetValue(dependencyProperty))\n      CancelAnimation(animatableElement, dependencyProperty)\n\n      completedEvent(sender, e)\n    End Sub	0
5164931	5164885	How to implement Redirection to multiple folders using Forms Authentication	If(Role=="Admin")\n    {\n         FormsAuthentication.SetAuthCookie("UserName", true);\n         Response.Redirect("Admin/Default.aspx");\n    }\n    else if(Role=="Category_A_User")\n    {\n         FormsAuthentication.SetAuthCookie("UserName", true);\n         Response.Redirect("Category_A_User/Default.aspx");\n    }	0
18911123	18910067	Add custom windows.postMessage handler	HRESULT AddProperty(SHDocVw::IWebBrowser2* pBrowser, _bstr_t bstrName, _variant_t varValue)\n{\n    CComQIPtr<IHTMLDocument> spDoc = pBrowser->Document;\n    CComPtr<IDispatch> spScript;\n    spDoc->get_Script(&spScript);\n\n    _variant_t varResult;\n    HRESULT hr = spScript.GetPropertyByName(OLESTR("window"), varResult.GetAddress());\n    CComQIPtr<IDispatchEx> spScriptEx = varResult;\n\n    DISPID id;\n    hr = spScriptEx->GetDispID(bstrName), fdexNameEnsure, &id);\n    if (SUCCEEDED(hr))\n    {\n        DISPID propid = DISPID_PROPERTYPUT;\n        DISPPARAMS dp = {NULL, NULL, 1, 1};\n        dp.rgdispidNamedArgs = &propid;\n        dp.rgvarg = &varValue;\n\n        hr = spScriptEx->InvokeEx(id, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dp, NULL, NULL, NULL);\n    }\n    return hr;\n}	0
28020295	28020125	C# Convert tag to link with Regex	\[\{~(.*?)\|(.*?)~\}\]	0
1429606	1429562	Problem with clearing a List<T>	public class MyClassCollection\n{\n    // Private object for locking\n    private readonly object syncObject = new object(); \n\n    private readonly List<MyObject> list = new List<MyObject>();\n    public this[int index]\n    {\n        get { return list[index]; }\n        set\n        {\n             lock(syncObject) { \n                 list[index] = value; \n             }\n        }\n    }\n\n    public void Add(MyObject value)\n    {\n         lock(syncObject) {\n             list.Add(value);\n         }\n    }\n\n    public void Clear()\n    {\n         lock(syncObject) {\n             list.Clear();\n         }\n    }\n    // Do any other methods you need, such as remove, etc.\n    // Also, you can make this class implement IList<MyObject> \n    // or IEnumerable<MyObject>, but make sure to lock each \n    // of the methods appropriately, in particular, any method\n    // that can change the collection needs locking\n}	0
8497734	8497673	HTML Agility pack: parsing an href tag	HtmlDocument htmlDoc = new HtmlDocument();\nhtmlDoc.Load("test.html");\nvar link = htmlDoc.DocumentNode\n                  .Descendants("a")\n                  .First(x => x.Attributes["class"] != null \n                           && x.Attributes["class"].Value == "undMe");\n\nstring hrefValue = link.Attributes["href"].Value;\nlong playerId = Convert.ToInt64(hrefValue.Split('=')[1]);	0
5796599	5796526	Storing User Time Zone in Amazon SimpleDB	// Id for storage in SimpleDB.\nvar exampleTimeZone = TimeZoneInfo.GetSystemTimeZones()[0].Id;\n// CLR instance to use in .NET from stored Id.\nvar timeZoneInstance = TimeZoneInfo.FindSystemTimeZoneById(exampleTimeZone);	0
10325249	10325142	How to limit certain behavior to a subset of instances of a particular class?	class Recipe {\n    public IEnumerable<IIngredient> Ingredients { get; set; }\n\n}\n\nclass UsefulRecipe : Recipe, IIngredient\n{\n    void DoIngredientStuff()\n    {\n        // not all Recipes are ingredients - this might be an illegal call\n    }\n}	0
31472401	31472151	How do I get the hour part with SqlFunctions.DateName	var time = "14:00";\nvar hour = Int32.Parse(time.Substring(0, 2));\nvar minute = Int32.Parse(time.Substring(3, 2));\nvar results = db.Table.Where(item =>\n    SqlFunctions.DateName("hh", item.DateTimeProperty) == hour &&\n    SqlFunctions.DateName("n", item.DateTimeProperty) == minute);	0
16114133	16113524	Converting windows sockets to .NET	Form1()\n{\n    UdpClient client = new UdpClient(987);\n    client.BeginReceive(UDPClient_Callback, client);\n}\n\nvoid UDPClient_Callback(IAsyncResult result)\n{\n\n}	0
15681155	15675145	Unity container register object that receive container in constructor	container.RegisterInstance<IUnityContainer>(container);	0
12360473	12360333	Create Custom Html Tag Html TextWriter	writer.AddAttribute("data-theme", "c");	0
6483248	6481699	Convert Dictionary to List	public static object GetSalesDataBySaleOrderID(SaleOrder sale)\n{\n    return sale.saleOrderItem\n               .Where(s => s != null)\n               .Select(s => new { \n                                  Id = s.Id,\n                                  Username = sale.User.GetSingleUserById(s.UserId).Name,\n                                  Amount = s.Amount \n                                })\n               .ToList();\n}	0
9552454	9552409	How do you parse a JSON file using JSON.net	JsonSerializer se = new JsonSerializer();\n    object parsedData = se.Deserialize(reader);	0
6810517	6799703	Add Items to a drop down list whose datasource is already set in a Windows Form Application	List<...>	0
14839423	14839376	How to translate a vb.net generic class to c#?	public interface SomeInterface<T> : IDisposable where T : class\n{\n}	0
10121816	10121698	How can I send the same email message to more than 3000 customers	List<Customer> customerList = GetAllCustomers();\n\nstring subject = "Hello World";\nstring content = GetContent();\n\n// Loop through all customers and send e-mail to each\nforeach(Customer customer in customerList)\n{\n   MailMessage newMail = new MailMessage("you@yourcompany.com", customer.Email, subject, content);\n\n   newMail.IsBodyHtml = true;\n\n   SmtpClient sender = new SmtpClient();\n\n   sender.Send(newMail);\n}	0
30219857	30196981	Get IIS to load dlls used for reading config from a specified directory	AppDomain.CurrentDomain.AssemblyResolve	0
7488781	7488391	Building an OrderBy expression using the name of a property	Expression.Convert	0
9529041	9528573	How to check if any row is added to Datagridview	private void dataGridView1_NewRowNeeded(object sender,\n    DataGridViewRowEventArgs e)\n{\n    newRowNeeded = true;\n}\n\nprivate void dataGridView1_RowsAdded(object sender,\n     DataGridViewRowsAddedEventArgs e)\n{\n    if (newRowNeeded)\n    {\n        newRowNeeded = false;\n        numberOfRows = numberOfRows + 1;\n    }\n}	0
4696361	4696202	How can I use the Pen tool to draw a simple black line on a PictureBox's Image object?	private void pictureBox1_Paint(object sender, PaintEventArgs e)\n{\n    using (Pen p = new Pen(Color.Black, 2))\n    {\n        e.Graphics.DrawLine(p, new Point(pictureBox1.Width / 2, 0), new Point(pictureBox1.Width / 2, pictureBox1.Height));\n    }\n}	0
12203232	12202357	Prism RegionManager: how to navigate from a current view?	regionManager.Regions[RegionNames.MainContentRegion].Remove(view)\nregionManager.Regions[RegionNames.MainContentRegion].Deactivate(view)	0
11575725	11575683	Copy part of a string to another string in C#	// when textbox contains "ABCDEFGHIJ", the result will be "CDEFG"\nstring result = textBox.Text.Substring(2, 5);	0
12364519	12363470	Using LINQ to construct a list C#	var grouped = ProductCatList.GroupBy(g => new{g.productCatId,g.productCatName})\n                     .Select(g => new ProductCatGroup()\n                                  {\n                                      productCatId = g.Key.productCatId,\n                                      productCatName = g.Key.productCatName,\n                                      ProductList = g.Select(p => new Prroduct()\n                                                    {\n                                                         productid = p.productId,\n                                                         productName = p.productName\n                                                     }\n                                  });	0
32549080	32548867	convert string to integer array C#	intermediateValue = (int)Math.Pow(numberBase, exponent) * (digitalState[digitIndex]-48; \n//The calculation here gives the wrong result, \n//possibly because of the unicode designation vs. true value issue\ndecimalValue += intermediateValue;\n(.....)\nConsole.WriteLine("The decimal equivalent of {0} is {1}", inputString, decimalValue);	0
10831750	10831521	2 hours lost in microseconds	int offset = 2;\n    DateTime d = new DateTime(1979,1,1, offset,0,0);	0
11360637	11360368	Using regular expression (Regex) to strip characters based on length of input string	string value = Regex.Match(input, @"^ROC(\d{3}0)?(\d+)$").Groups[2].Value;	0
9150934	9150855	reading certain digits from binary data	static void Main(string[] args)\n{\n    UInt64 EsnDec = 2161133276;\n    Console.WriteLine(EsnDec);\n    //Convert to String\n    string Esn = EsnDec.ToString();\n    Esn = "80" + Esn.Substring(Esn.Length - 6);\n    //Convert back to UInt64\n    EsnDec = Convert.ToUInt64(Esn);\n    Console.WriteLine(EsnDec);\n    Console.ReadKey();\n}	0
6560816	6560397	How to get acces to json.net array?	Convert.ToDateTime(response["response"][0][i]["date"]);	0
18769440	18769411	Cannot convert string[] to string	string[][] digitsArray = {dd, pp, ff, cc};	0
3247121	3246529	How can I stop this regex from being greedy?	\bthe\b(?:(?!\bthe\b).)*\blanguage\b	0
3229283	3229040	How can I use Rhino Mocks to inspect what values were passed to a method	[Test]\npublic void MyTest()\n{\n    // arrange\n    IDoStuff doer = MockRepository.GenerateStub<IDoStuff>();\n    MyClass myClass = new Myclass(doer);\n    Guid id = Guid.NewGuid();\n\n    // act\n    myClass.Go(new SomeClass(){id = id});\n\n    // assert\n    doer.AssertWasCalled(x => x.DoStuff(\n        Arg<Someclass>.Matches(y => y.id == id)));\n}	0
23143188	23143131	Unassigned local variables	XmlNode nodeRss = null;\n XmlNode nodeChannel = null;	0
14673385	14671586	Resetting a Static Variable at the Beginning of each MSTest Test Method	[TestInitialize()]\npublic void TestInit()\n{\n    MyClass.StaticVariable = 0;\n}	0
20292497	20251183	How to implement a persisting ConcurrentQueue?	add item 1\nadd item 2\nremove item 1\nadd item 3\nremove item 2\nremove item 3\nadd item 4\n...	0
7778324	7778201	Insert a new record in one to one relational tables	Users:\n----\nUserId >> Primary key & Auto increment\nUserName\nPassword\n\nUsersInfo:\n----\nUsersInfoId >> Primary key auto increment\nUserId >> Foreign key & Unique constraint (for one-to-one relation)\nMoreInfo	0
2071734	2071710	C# file still in use after a using statement	using (FileStream f = File.Create(fileName)) {\n   using (XmlWriter w = XmlWriter.Create(f, settings)) {\n      ...\n   }\n}	0
21068755	21068339	Left Outer Join That Returns Null Right Side In Addition To The Matching Rows	(select c.id, c.code, sc.subCode\n from codes c join\n      subcodes sc\n      on c.id = sc.codeid\n) union all\n(select c.id, c.code, NULL\n from codes c\n)	0
12855238	12855191	Change text on a form from within a thread in C#	if (this.InvokeRequired)\n{\n    IAsyncResult result = BeginInvoke(new MethodInvoker(delegate()\n    {\n        // DOSTUFF\n    }));\n\n    // wait until invocation is completed\n    EndInvoke(result);\n}\nelse if (this.IsHandleCreated)\n{\n    // DO STUFF\n}	0
10519292	10519221	get stream of a socket object in c#	// NOTE: This demonstrates disposal of the stream when you are \n// done with it- you may not want that behavior.\nusing (var myStream = new NetworkStream(mySocket)) {\n    my3rdPartyObject.Foo(myStream);\n}	0
5029928	5029735	How to get SPWebApplication from SPWeb?	SPWeb web = properties.Feature.Parent as SPWeb;\nSPWebApplication webApp = web.Site.WebApplication;	0
836960	836806	C# XMLDocument to DataTable?	xmlAPDP = new XmlDocument()\n...\nxmlReader = new XmlNodeReader(xmlAPDP)\ndataSet = new DataSet()\n...\ndataSet.ReadXml(xmlReader)	0
30037854	30037601	filter linq to sql with a entity framework where in	var pemdata = (from pd in db.tblMap \n                          where pd.PID == pid\n                          select pd.EID).ToList();	0
34373073	34365173	Windows Phone - Rate & Review Command	await Launcher.LaunchUriAsync(new Uri("ms-windows-store:reviewapp?appid=" + appid));	0
22652713	22652464	Perform second popup via first popup page in asp.net	z-index	0
9950648	9809913	I must be a heretic for wanting a C# browser with both NewWindow2 and GetElementsByTagName	IHTMLDocument2 webpage = (IHTMLDocument2)webbrowser.Document;\nIHTMLFramesCollection2 allframes = webpage.frames;\nIHTMLWindow2 targetframe = (IHTMLWindow2)allframes.item("name of target frame");\nwebpage = (IHTMLDocument2)targetframe.document;\nIHTMLElementCollection elements = webpage.all.tags("target tagtype");\n\nforeach (IHTMLElement element in elements)\n{\n  if (elem.getAttribute("name") == strTargetElementName)\n   {\n     return element.getAttribute("value");\n   }\n}	0
25035633	25035524	Call to empty constructor and base with parameters	public class Student : Person\n{\n    public Student(string path = null) : base(path)\n    {\n\n    }\n}\n\npublic class Person\n{\n    public Person(string path = null)\n    {\n        path = path ?? "sensible default";\n    }\n}	0
24469606	24469591	Unreachable code detected WP8	private void ExecuteSaveSoundAsRingtone(string soundPath)\n{\n    if (IsDownloaded == false)\n    {\n        MessageBox.Show("Will not download until you short press atleast once");\n        return;\n    }\n    App.Current.RootVisual.Dispatcher.BeginInvoke(() =>\n    {\n\n        SaveRingtoneTask task = new SaveRingtoneTask();\n        task.Source = new Uri("isostore:/" + this.SavePath);\n        task.DisplayName = this.Title;\n        task.Show();\n    }\n       );	0
13102757	13102673	How to filter DataTable with LINQ	// Get all checked id's.\nvar ids = chkGodownlst.Items.OfType<ListItem>()\n    .Where(cBox => cBox.Selected)\n    .Select(cBox => cBox.Value)\n    .ToList();\n\n// Now get all the rows that has a CountryID in the selected id's list.\nvar a = dt.AsEnumerable().Where(r => \n    ids.Any(id => id == r.Field<int>("CountryID"))\n);\n\n// Create a new table.\nDataTable newTable = a.CopyToDataTable();\n\n// Now set the new table as DataSource to the GridView.	0
144441	144439	Building a directory string from component parts in C#	string CombinePaths(params string[] parts) {\n    string result = String.Empty;\n    foreach (string s in parts) {\n        result = Path.Combine(result, s);\n    }\n    return result;\n}	0
3382704	3382693	How can I change character Case?	TextInfo.ToTitleCase	0
2352704	2352215	Microsoft Chart Control - Big Red X (bad) whenever I use financial formulas	priceseries.IsXValueIndexed = true;	0
5384310	5383858	Calling a Java Web Service from a .Net Project	WebReference.ContactUs myService = new WebReference.ContactUs();\n...\n<result data type> _Response = myService.getContactUs(myContactUs);\n...	0
10695522	10695363	Getting Images from S3	using (var response = S3.GetObject(request))\n{\n    using (var responseStream = response.ResponseStream)\n    {\n        context.Response.ContentType = "image/jpeg";\n\n        var buffer = new byte[8000];\n        int bytesRead = -1;\n        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)\n        {\n            context.Response.OutputStream.Write(buffer, 0, bytesRead);\n        }\n    }\n}\n\ncontext.Response.End();	0
34154916	29610380	How to carry out live camera stream for metro apps c#	var properties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;\nvar frame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)properties.Width, (int)properties.Height);\nvar previewFrame = await _mediaCapture.GetPreviewFrameAsync(frame);\nvar previewBitmap = frame.SoftwareBitmap;\nframe.Dispose();\nframe = null;	0
26717936	26663513	Need an efficient way to get JObject from JSON string	private dynamic GetFirstObject(string response)\n{\n    dynamic firstObject = null;\n    if (!String.IsNullOrEmpty(response))\n    {\n        JArray arrResponse = JArray.Parse(response) as JArray;\n        dynamic dyResponse = arrResponse[0];\n        string strValue = JsonConvert.SerializeObject(dyResponse.Value);\n        JArray arrValueList = JArray.Parse(strValue);\n\n        if (arrValueList.Count > 0)\n        {\n            firstObject = arrValueList[0];\n        }\n    }\n    return firstObject;\n}	0
10656989	10590078	Two controls show before the others	If SlowControl.visible = True Then\nFastControl1.visible = True\nFastControl2.visible = True\nEnd If	0
12752999	12752937	ArgumentException: 'Illegal characters in path' in C#	string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\nFileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));	0
12578407	12578355	Implement font menu item in notepad using c#	//Create FontDialog instance\nFontDialog fontDialog1 = new FontDialog();\n// Show the dialog.\nDialogResult result = fontDialog1.ShowDialog();\n// See if OK was pressed.\nif (result == DialogResult.OK)\n{\n    // Get Font.\n    Font font = fontDialog1.Font;\n    // Set TextBox properties.\n    this.textBox1.Text = string.Format("Font is: {0}", font.Name);\n    this.textBox1.Font = font;\n}	0
15049080	15048940	Outputcache for two parameters, custom and Encoding	public override string GetVaryByCustomString(HttpContext context, string arg)\n{\n  // Do something with Request.Headers["Accept-Encoding"] (like checking if gzip is preferred...)\n  return "custom-encoding-key";\n}	0
28584382	28584328	Connect network printer that contains spaces	p.StartInfo.Arguments = string.Format("/c start \"{0}\"", newPrinter);	0
10893183	10893116	ServiceController shows incorrect MachineName	if (scTemp.MachineName.Equals(".")) {\n  dt.Rows.Add(Environment.MachineName, scTemp.DisplayName, scTemp.Status);\n}\nelse {\n  dt.Rows.Add(scTemp.MachineName, scTemp.DisplayName, scTemp.Status);\n}	0
26101966	26099681	TFS: Get the user's name of locked file	TfsTeamProjectCollection coll = YOURTEAMPROJECTCOLLECTION;\n\nPendingSet[] pending = coll\n        .GetService<VersionControlServer>()\n        .QueryPendingSets(new[] { jsonFile  }, RecursionType.None, null, null);	0
6531891	6531473	Conversion problem in datetime parameter in sql server 2008	declare @a int = 15, @b datetime = GETUTCDATE()\n\ndeclare @sql nvarchar(400) = 'select @x, @y'\n\nexec sp_executeSql @sql, N'@x int, @y datetime', @a, @b	0
20553242	20553152	C# VS 2013 how to call programs in DLL	[DllImport("MSA.dll", CharSet = Ansi)]\npublic extern string GetXML(string firstParam, string secondParam, bool thirdParam);	0
2950718	2950658	Remove namespace from generated XML in .NET	XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();\nnamespaces.Add(string.Empty, string.Empty);	0
23010867	23010735	Find a file by file name	Directory.GetFiles(@"c:\", filename, SearchOption.AllDirectories).FirstOrDefault()	0
5412549	5412447	linq to object using a list of tuples	var matches = entities.Where(e => \n       (e.p1 == 3 && e.p2 == 7 && e.p3 == 23)\n    || (e.p1 == 3 && e.p2 == 43 && e.p3 == 45)\n    || (e.p1 == 1 && e.p2 == 232 && e.p3 == 321));	0
14026917	14026870	Highlight text in a box when tapped?	private void bar_Tap(object sender, GestureEventArgs e)\n{\n    bar.SelectAll();\n}	0
2760638	2760629	Using Generics on a Repository base class	public interface IRepository<TEntity, TID> where TEntity : IEntity<TID>\n{\n    void Add(TEntity entity);\n\n    void Delete(TEntity entity);\n}\n\n\npublic interface IProductRepository : IRepository<Product, int>	0
856269	856228	How can I improve this square root method?	eps = 1e-10  // pick any small number\nif (Math.Abs(r-last) < eps) break;	0
23809783	23809003	C# Using Two DataTables in DataGridView without Losing Ability to Update Database	class ViewSaleInfo\n{\n    ViewSaleInfo(DataRow t1, DataRow t2)\n    {\n        this.t1 = t1;\n        this.t2 = t2;\n    }\n\n    public String COL_A\n    {\n        get\n        {\n            return t1["COL A"];\n        }\n        set\n        {\n            t1["COL A"] = val;\n        }\n    }\n\n    // and other properties required for view from both data tables\n}	0
13299741	13299401	Constant Contact C# Wrapper - Add Contact to a List	string nextChunkId;\n    IList<Contact> list = Utility.SearchContactByEmail(AuthenticationData, emailAddress, out nextChunkId);\n    if (list.Count == 0)\n    {\n        // create new Contact\n        Contact contact = GetContactInformation();\n\n        Utility.CreateNewContact(AuthenticationData, contact);\n        Response.Redirect("~/AddContactConfirmation.aspx");\n    }\n    else\n    {\n        throw new ConstantException(String.Format(CultureInfo.CurrentCulture,\n            "Email address \"{0}\" is already a contact", txtEmail.Text.Trim()));\n    }	0
24651798	24651622	Depth scan of substring	List<int> indexes = new List<int>();\nfor (int index = sourceString.indexOf(stringToSearch);\n     index != -1;\n     index = sourceString.indexOf(stringToSearch, index + 1)) {\n  indexes.Add(index);\n}	0
20744916	20663094	XAML WinRT - Factory Pattern for Custom Styles	Application.Current.Resources[CustomStyleVariable];	0
20916422	20916283	PictureBox as a Button	//Common eventhandler assigned to all of your PictureBox.Click Events\nprivate void pictureBox_Click(object sender, EventArgs e)\n{\n    ((PictureBox)sender).Visible = false;\n}\n\nprivate void Form1_Click(object sender, EventArgs e)\n{\n    foreach (var item in this.Controls) // or whatever your container control is\n    {\n        if(item is PictureBox)\n        {\n            PictureBox pb = (PictureBox)item;\n            if (pb.Bounds.Contains(PointToClient( MousePosition)))\n            {\n                pb.Visible = true;\n            }\n        }\n    }\n}	0
12487001	12453800	How to set custom-column-property in xaml file?	private void UI_Loaded(object sender, RoutedEventArgs e)\n{\n    if (sender is GridSplitter)\n    {\n        Grid ParentGrid = this.ParentOfType<Grid>();\n        SetLocation(ParentGrid);\n    }\n}\npublic void SetLocation(Grid p_Layout)\n{\n    int index = Grid.GetColumn(this);\n    ColumnDefinition ColLocation = p_Layout.ColumnDefinitions[index];\n    ColLocation.MinWidth = 10;\n    Left = ColLocation;\n}	0
2460584	2460367	Want to bind querystring in postbackurl of imagebutton in gridview?	PostBackUrl='<%# Eval("SystemEmailID", "Edit_SyatemEmails.aspx?id={0}"\n + "&blogentry=" + Request.QueryString["edit"]) %>'	0
4530900	4522583	How to do the processing and keep GUI refreshed using databinding?	public MyModel Model { get; private set; }\n\npublic MyViewModel() {\n    Model = new MyModel();\n    Model.PropertyChanged += (s,e) => SomethingChangedInModel(e.PropertyName);\n}\n\nprivate HashSet<string> _propertyChanges = new HashSet<string>();\n\npublic void SomethingChangedInModel(string propertyName) {\n    lock (_propertyChanges) {\n        if (_propertyChanges.Count == 0)\n            _timer.Start();\n        _propertyChanges.Add(propertyName ?? "");\n    }\n}\n\n// this is connected to the DispatherTimer\nprivate void TimerCallback(object sender, EventArgs e) {\n    List<string> changes = null;\n    lock (_propertyChanges) {\n        _Timer.Stop(); // doing this in callback is safe and disables timer\n        if (!_propertyChanges.Contain(""))\n            changes = new List<string>(_propertyChanges);\n        _propertyChanges.Clear();\n    }\n    if (changes == null)\n        OnPropertyChange(null);\n    else\n        foreach (string property in changes)\n            OnPropertyChanged(property);\n}	0
28020675	27955230	Building a dynamic JSON response in MVC 5 - How to tack on properties to a result set?	Public Class Album{\n   string PhotoUrl {get; set;}\n   string ThumbnailUrl {get; set;}\n}\n\n\nList<AlbumPicture> pics = db.AlbumPictures.Where(p => p.AlbumID == album.ID).OrderBy(p => p.RankOrder).ToList();\nList<Album> albums = new List<Album>();\nforeach(AlbumPicture p in pics)\n{\n    albums.add(new Album(){\n      PhotoUrl = p.PhotoUrl,//your photo url\n      ThumbnailUrl = p.ThumbnailUrl\n    });\n}\n return Json(albums, JsonRequestBehavior.AllowGet);	0
444404	444210	How do I send emails outside my domain with Exchange 2007 and c#	SmtpClient srv = new SmtpClient("exchsrv2007", 25) {\n    DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,\n    PickupDirectoryLocation = "\\exchsrv2007\PickupFolder"\n}\n...	0
3873806	3873767	Using reflection to get a properties property	Dim bar As WebProxy = WebProxy.GetDefaultProxy\n\nDim scriptEngineProperty = bar.GetType().GetProperty("ScriptEngine", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)\nDim scriptEngineObject as Object = scriptEngineProperty.GetValue(bar, Nothing)\n\nDim acsProperty As PropertyInfo = scriptEngineObject.GetType().GetProperty("AutomaticConfigurationScript", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)\nDim acsObject as Object = acsProperty.GetValue(scriptEngineObject, Nothing)\n\nDim localPathProperty As PropertyInfo = acsObject.GetType().GetProperty("LocalPath", Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)\nDim value As String = localPath.GetValue(acsObject, Nothing).ToString	0
26470864	26469337	c# Remove a dynamically created checkbox based on a button click	StreamReader reader;\nStreamWriter writer;\n\nstring line, newText = null;\n\nusing (reader = new StreamReader(@"..."))\n{\n    while ((line = reader.ReadLine()) != null)\n    {\n        if (line != "checkbox name")\n        {\n            newText += line + "\r\n";\n        }\n    }\n}\n\nnewText = newText.Remove(newText.Length - 2); //trim the last \r\n\n\nusing (writer = new StreamWriter(@"...")) //same file\n{\n    writer.Write(newText);\n}	0
6283083	6282991	ASP.NET application using the wrong file path when publishing to a windows server 2008 machine	filename = MapPath("/images/logo.jpg")	0
6114525	6114476	display values in List string into dataGrid	_dataGridSection.ItemsSource = setList;	0
8877978	8877736	Having upper case, lower case and digits in a GUID	var rand = new Random();\nvar sb = new StringBuilder();\n\nforeach (char c in Guid.NewGuid().ToString("N"))\n{\n    sb.Append(rand.Next(0, 2) == 1 ? Char.ToUpper(c) : c);\n}	0
12135682	12126635	How to create a list from button items and populate them by a list?	var unorderedList = new List<ToolStripItem>();\nfor (int i = 0; i < toolStripDropDownButton1.DropDownItems.Count;i++ )\n{\n    unorderedList.Add(toolStripDropDownButton1.DropDownItems[i]);\n}\n\nvar orderedList = unorderedList.OrderBy(l => l.Text).ToList();\ntoolStripDropDownButton2.DropDownItems.AddRange(orderedList.ToArray());	0
26103058	26102717	How to check if there is some text between 2 chars?	(?<=\>)abc(?=\<)	0
6621722	6621689	Updating data from the DataGridView into the database in C#	this.animalsTableAdapter.Fill(this.animalsDataSet.Animals);	0
21931966	21931468	not able to build in clearcase snapshot csproject	cleartool ls\ncleartool descr -l yourFile.dll	0
25940653	25940603	How can I select a row from the DataGridView equals textbox.Text after clicking a button by C# ?	private void btnChk(object sender, EventArgs e)\n{\n    for (int i = 0; i < dgv.Rows.Count; i++)\n    {\n        if (dgv.Rows[i].Cells[1].Value.ToString()==txtName.Text)\n        {\n           dgv.Rows[i].Cells[1].Selected = true;\n        }\n\n    }\n}	0
29897040	29894362	Underline a single word in List & Label	Formatted Text	0
9741895	9741793	Implementing a Random provider in .Net 3.5	[ThreadStatic]\nprivate static Random _random;\n\nprivate static Random Random\n{\n    get\n    {\n        int seed = Environment.TickCount;\n\n        return _random ?? (_random = new Random(Interlocked.Increment(ref seed)))\n    }\n}	0
2675853	2673938	Add Imagebutton to DataGridView in C#	//check if your clicking on a cell inside the imagecolumn column\nif(e.ColumnIndex == this.colImageColumn.index && e.RowIndex > 0)\n   //Delete Row e.RowIndex	0
19315061	19314939	Open URL with # from WinForms	string pathToExecutable = ...;\nstring url = @"file:///c:\Projects\HTMLTest\Debug\help\index.htm#Modules\Administration\UserInterface\MainWindow\Processing.htm";\nSystem.Diagnostics.Process.Start(pathToExecutable, url);	0
3654195	3399819	Access denied while getting process path	private static string GetExecutablePathAboveVista(UIntPtr dwProcessId)\n    {\n        StringBuilder buffer = new StringBuilder(1024);\n        IntPtr hprocess = OpenProcess(ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, dwProcessId);\n        if (hprocess != IntPtr.Zero)\n        {\n            try\n            {\n                int size = buffer.Capacity;\n                if (QueryFullProcessImageName(hprocess, 0, buff, out size))\n                {\n                    return buffer.ToString();\n                }\n            }\n            finally\n            {\n                CloseHandle(hprocess);\n            }\n        }\n        return string.Empty;\n    }	0
13385117	13384967	How do you create a CheckedListBox WinForm control that is completely unresponsive to keyboard input?	using System.Windows.Forms;\n\npublic class CheckedListBoxIgnoreKeyboard : CheckedListBox\n{\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        return true;\n    }\n}	0
10771284	10771048	how to define an array of textboxes in c#?	TextBox[] array = { firstTextBox, secondTextBox };	0
9869379	9869346	Double string.format	myDouble.ToString("0.00")	0
16872826	16872809	Error in AsyncTask unable to send POST data	textDisplay.setText("Success");	0
17130191	17059667	Class Architecture of Monitoring Log Data	Req Success OrderFunction 5 60ms WebServer2\nReq Failed  OrderFunction 2 176ms WebServer5\nResp Success SuggestFunction 8 45ms WebServer2	0
12506937	12506844	set property for user control	StudentDetail1.UserImg = string.Format("../AdminPanel/StudentsPic/{0}",query.Pictuer);	0
28540074	28539878	C# - How can I block the typing of a letter on a key press?	private void TextBox1KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)\n    {\n        e.SuppressKeyPress = true;\n        Button1Click(this, EventArgs.Empty);\n    }\n}	0
910110	910098	How to get elements from collection A that not in collection B? i.e. A-B	var gone = A.Except(B);	0
3659183	3659131	How to access properties dynamically / late-bound?	dynamic d = a;\nint i = d.B.C.I;	0
16740530	16740487	Generate GUID from a string that is not in guid format	Guid.ParseExact("81a130d2502f4cf1a37663edeb000e9f", "N");	0
27793742	27793423	Linq to XML Querying Data in C#	x.Descendants("Address").First().Element("Street")	0
34405805	34405637	C# - Start a process in background	var info = new ProcessStartInfo ( path , arguments )\n           {\n                Domain = processConfiguration.Domain ,\n                Password = password ,\n                UserName = processConfiguration.UserName ,\n                RedirectStandardOutput = true ,\n                UseShellExecute = false ,\n                CreateNoWindow = true\n           } ;\n\nSystem.Diagnostics.Process proc = new System.Diagnostics.Process () ;\n                           proc.StartInfo = info ;\n                           proc.Start () ;	0
10143047	10142964	c# DataGridView getting contents from a Row/Column	DataGridViewRow row =dataGridView.Rows[0];\n\nstring someStringColumnValue = (string)row.Cells[0].Value;	0
17155726	17155536	Have FluentValidation call a function with multiple parameters	.RuleFor(x => x.UserProfile).Must( (o, userProfile) => { return IsValid(o.promoCode, userProfile); })	0
33025976	33025199	Format unstructured string	var str = "STACR 2015-HQA1 M1  125    120    5   x 1.5   0"; //your data\nvar parts = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();\n\n//we'll use this pattern : <3 part bond name> <bid> <offer/null> <something x ....>\nvar xIsAt = parts.IndexOf("x"); //we'll use x as reference\nif (xIsAt > 2) //first three are BondName\n    parts.RemoveRange(xIsAt - 1, parts.Count - xIsAt + 1); //remove "5 x 1.5 ..."\nvar bond = string.Join(" ", parts.Take(3)); //first 3 parts are bond\nvar bid = parts.Count > 3 ? parts.ElementAt(3) : null; //4th is bid\nvar offer = parts.Count > 4 ? parts.ElementAt(4) : null; //5th is offer	0
7738124	7735358	How to put Unicode in browser title	Page.Title = "//someunicode//"	0
17762843	17762747	Byte array to BitmapImage WP	public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)\n{\n    MemoryStream stream = new MemoryStream(byteArray);\n    BitmapImage bitmapImage = new BitmapImage();\n    bitmapImage.SetSource(stream);\n    return bitmapImage;\n}	0
32406705	32405814	Get the most unmatched values from two List<T> using LINQ by C#	var uniqueItems = matrixList1.Where(l1 => !matrixList2.Any(l2 => l1.Row == l2.Row && l1.Column == l2.Column && l1.Value == l2.Value))	0
11175464	11175434	How to trim and convert a string to integer?	string abc = "15k34";\nint x = 0;\n//abc = "05k34";\nint val;\nif (!string.IsNullOrEmpty(abc) && abc.Length > 1)\n{\n    bool isNum = int.TryParse(str.Substring(0, 2), out val);\n    if (isNum)\n    {\n        x = val;\n    }\n}	0
8596578	8594710	How to Read VPN Login Name?	static void Main(string[] args)\n{\n    string groupName = "Domain Users";\n    string domainName = "";\n\n    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);\n    GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);\n\n    if (grp != null)\n    {\n         foreach (Principal p in grp.GetMembers(false))\n         {\n                Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);\n         }\n\n        grp.Dispose();\n        ctx.Dispose();\n        Console.ReadLine();\n    }\n    else\n    {\n        Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");\n        Console.ReadLine();\n    }\n}	0
10084660	10084385	Get a List instead of a Simple Field Property	mainEntity = (EntityBase)navigationPropertyAnzeigeUserControl.SelectedObject;\n                    IEnumerable<object> collection = (IEnumerable<object>)businnesObject.GetType().GetProperty("Positionen").GetValue(businnesObject, null);\n                    List<object> test = collection.ToList();\n                    test.Add(mainEntity);\n                    businnesObject.GetType().GetProperty(LoescheAlleZeichenNachEinemGewissenZeichen(mainEntity.GetType().Name, '_')).SetValue(businnesObject, collection, null);	0
24202082	24201952	How to remove Node from Treeview by giving Node Name using C#	TreeNode node = this.trvMenu.Nodes.Cast<TreeNode>().FirstOrDefault( x => x.Name == "TestNode" )\nif (node != null)\n{\n    this.trvMenu.Nodes.Remove(node);\n}	0
4883644	4883521	while trying to write data into text file it is showing server doesnot exist in this context	str = System.IO.Path.GetFullPath("/financila_csharp");	0
8407900	8407706	When I add value to SqlDataRecord number is rounding	public SqlMetaData(\n    string name,\n    SqlDbType dbType,\n    byte precision,\n    byte scale\n)	0
5742130	5735887	StructureMap: Injecting a primitive property in a base class	container.Configure(r => r.For<ICommandHandler>()\n    .OnCreationForAll(handler =>\n    {\n        handler.Logger = container.Resolve<ILogger>();\n        handler.SendAsync = true;\n    }));	0
31728119	31726355	Model Validation in Web API	RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);	0
3087256	3086269	Reuse a ToolStripMenu for a ToolStrip or a ContextMenuStrip?	public MainForm()\n{\n    //in your constructor, create all your common methods, actions, etc and save them to private vars\n\n    //Then in your form:\n    ToolStripMenu menu = new ToolStripMenu();\n    AttachCommonFunctionality(menu);\n    Items.Add(menu);\n\n    ContextMenuStrip rightClick = new ContextMenuStrip();\n    AttachCommonFunctionality(rightClick);\n    this.ContextMenu = rightClick;\n    //etc...\n}\n\nprivate void AttachCommonFuntionality(Control c)\n{\n    c.Items.Add(_item1);\n    c.Items.Add(_item2);\n    //etc...\n\n    c.OnClick += _myCommonAction;\n    //etc...\n}	0
3308186	3307499	MsiSetProperty from C# custom action	public class CustomActions \n{ \n    [CustomAction] \n    public static ActionResult action1(Session session) \n    { \n        string xyzProperty = "XYZ";\n\n        session[xyzProperty] = "ABC";\n    } \n}	0
2882390	2847659	C# web cam WM_CAP_CONNECT: Want to force a capture source when multiple capture sources present	SendMessage(_windowHandle, WM_CAP_CONNECT, _videoSourceIndex, 0)	0
34411318	34410896	can't open external Tool from c#	void open_2x()\n{\n    var programfiles = Environment.GetEnvironmentVariable("PROGRAMFILES");\n    string var_2x_apppath = System.IO.Path.Combine(programfiles, "2X", "Client", "TSClient.exe");     \n    string var_2x_parameter = " s!='"+var_ausgabe_serverip+"' a!='"+var_ausgabe_produkt+"' t!='"+var_ausgabe_ServerPort+"' d!='"+var_ausgabe_raum+"' u!='"+var_ausgabe_User+"' q!='"+var_ausgabe_PW+"' m!='"+var_ausgabe_mode+"'";\n\n    MessageBox.Show(var_2x_apppath + var_2x_parameter); //for debug only\n\n    Process p = new Process();\n    p.StartInfo.FileName = "cmd";\n    p.StartInfo.UseShellExecute = false;\n    p.StartInfo.CreateNoWindow = true;\n    p.StartInfo.Arguments = "/c " + var_2x_apppath + var_2x_parameter;\n    p.Start();\n    p.WaitForExit();\n}	0
520182	520160	How to handle null objects in XML coming from SQL Server?	xsi:nil="true"	0
5716363	5714545	C# Regex Validator Validation	[a-zA-Z][a-zA-Z'.\s\-]{0,50}	0
17723069	17615914	How to bind XmlDataProvider property of viewmodel with XmlDataProvider in view?	public class MainViewModel : ViewModelBase {\n\n\n    private  XmlDocument  xDoc;\n    public  XmlDocument  XDoc {\n      get {\n        return xDoc;\n      }\n      set {\n        xDoc = value;\n        RaisePropertyChanged( "XDoc" );\n      }\n    }\n\n    public MainViewModel( ) {\n      Data d = new Data( );\n      d.int1 = 12;\n      d.int2 = 20;\n      d.str = "Hello World";\n\n\n      XmlSerializer serializer = new XmlSerializer( d.GetType( ) );\n      StringWriter strWriter = new StringWriter( );\n      serializer.Serialize( strWriter, d );\n      XDoc = XDocument.Parse( strWriter.ToString( ) ).ToXmlDocument () ;   \n    }\n  }\n\n <TreeView Grid.Row="2" Grid.ColumnSpan="2" Name="xmlTree" \n               ItemsSource="{Binding XDoc}" ItemTemplate="{StaticResource treeViewTemplate}"/>	0
19098228	19056022	How do I get the a string value from url field for a function in a workflow programmatically?	private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)\n    {\n        //Currente item\n        int item = onWorkflowActivated1.WorkflowProperties.ItemId;\n        SPItem current =  onWorkflowActivated1.WorkflowProperties.Item;    \n        //Get url from field\n        SPFieldUrlValue fieldValue = new SPFieldUrlValue(current["Repository"].ToString());\n        string linkTitle = fieldValue.Description;\n        string linkUrl = fieldValue.Url;            \n        string ruta = "Shared Documents/Folder"+item;\n\n        using (SPSite site = new SPSite(linkUrl))\n        {\n            using (SPWeb web = site.OpenWeb())\n            {\n                web.Folders.Add(ruta);\n                workflowProperties.Item["Folder"] = linkUrl + ruta;                   \n                workflowProperties.Item.Update();  \n            }\n        }\n\n    }	0
7926295	7926167	How to set Location of another Control proportionally	private void sizeAbleCTR2_LocationChanged(object sender, EventArgs e)\n{\n    float srcHeightDiff = panel2.Height - sizeAbleCTR2.Height;\n    float dstHeightDiff = panel1.Height - sizeAbleCTR1.Height;\n\n    int locY = (int)(dstHeightDiff * (sizeAbleCTR2.Location.Y / srcHeightDiff));\n\n    float srcWidthDiff = panel2.Width - sizeAbleCTR2.Width;\n    float dstWidthDiff = panel1.Width - sizeAbleCTR1.Width;\n\n    int locX = (float)(dstWidthDiff * (sizeAbleCTR2.Location.X / srcWidthDiff));\n\n    sizeAbleCTR1.Location = new Point(locX, locY);\n}	0
26045862	26045655	How to setup a relational data model?	public class Customer\n    {\n    public int CustomerID { get; set; }\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public string Address { get; set; }\n    public string Zipcode { get; set; }\n    public string City { get; set; }\n    public string Email { get; set; }\n    public string Phone { get; set; }\n    public ICollection<Reservation> Reservations { get; set; }\n    }	0
29736659	29736177	Waiting for Process Response	void main()\n{\n    var psi = new ProcessStartInfo("fileName.exe", "<arguments>");\n    psi.UseShellExecute = false;\n    psi.RedirectStandardOutput = true;\n    psi.RedirectStandardError = true;\n\n    var p = Process.Start(psi);\n    p.OutputDataReceived += p_OutputDataReceived;\n    p.ErrorDataReceived += p_ErrorDataReceived;\n    p.WaitForExit();\n}\nstatic void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n{\n    //react on the received error data in e.Data.\n}\n\nstatic void p_OutputDataReceived(object sender, DataReceivedEventArgs e)\n{\n    //react on the received output data in e.Data.\n}	0
33685238	33685177	Is there a way to connect to Magento Database from c# application?	using Magento_Import.MagentoAPI;\n\nnamespace Magento_Import\n{\n    public partial class _Default : System.Web.UI.Page\n    {\n        Mage_Api_Model_Server_V2_HandlerPortTypeClient handler = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();\n\n        protected void Page_Load(object sender, EventArgs e)\n        {\n            string session = handler.login("username", "password");\n\n            catalogProductEntity[] products;\n            handler.catalogProductList(out products, session, null, null);\n        }\n    }\n}	0
19671874	19671532	Terminate Application on exit in Windows CE 6.0	Process thisProcess = Process.GetCurrentProcess();\nthisProcess.Kill();	0
12935350	12933896	How to embed AssemblyFileVersion in resource/constant/string/other?	// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle("MyProject")]\n...\n[assembly: AssemblyFileVersion(MyProject.AssemblyInfo.AssemblyFileVersion)]\n\nnamespace MyProject\n{\n    static internal class AssemblyInfo\n    {\n        /// <summary>\n        /// The AssemblyFileVersion of this web part\n        /// </summary>\n        internal const string AssemblyFileVersion = "1.0.3.0";\n    }\n}	0
2794124	2794053	how to read value of an xml node (single) using linq to xml	using System;\nusing System.Linq;\nusing System.Xml.Linq;\n\npublic class Example\n{\n    static void Main()\n    {\n        String xml = @"<test>\n                <test1>test1 value</test1>\n                        </test>";\n\n        var test = XElement.Parse(xml)\n                .Descendants("test1")\n                .First()\n                .Value;\n\n        Console.WriteLine(test);\n    }\n}	0
2269627	2269607	How to programmatically download a large file in C#	DateTime startTime = DateTime.UtcNow;\n        WebRequest request = WebRequest.Create("http://www.example.com/largefile");\n        WebResponse response = request.GetResponse();\n        using (Stream responseStream = response.GetResponseStream()) {\n            using (Stream fileStream = File.OpenWrite(@"c:\temp\largefile")) { \n                byte[] buffer = new byte[4096];\n                int bytesRead = responseStream.Read(buffer, 0, 4096);\n                while (bytesRead > 0) {       \n                    fileStream.Write(buffer, 0, bytesRead);\n                    DateTime nowTime = DateTime.UtcNow;\n                    if ((nowTime - startTime).TotalMinutes > 5) {\n                        throw new ApplicationException(\n                            "Download timed out");\n                    }\n                    bytesRead = responseStream.Read(buffer, 0, 4096);\n                }\n            }\n        }	0
14826605	14826049	C# Console application decode urlencoded string	string query = System.Web.HttpUtility.UrlDecode(input);\nNameValueCollection result = System.Web.HttpUtility.ParseQueryString(query);\n\nforeach (var key in result.AllKeys)\n{\n    var value = result[key];\n    Console.WriteLine("{0}: {1}", key, value);\n}	0
12128716	12087676	insert into dataset	DataSetReasons.Data_Tracker_RcodeDataTable GRX =\nnew DataSetReasons.Data_Tracker_RcodeDataTable();\n\nGRX.Rows.Add(13, 28, "C", 5, "A", 2, TextBox2.Text);	0
10155701	10155429	MVC3 custom validation attribute for an "at least one is required" situation	protected override ValidationResult IsValid(object value, ValidationContext validationContext) \n{\n    var viewModel = value as TimeInMinutesViewModel;\n    if (viewModel == null)\n    {\n        //I don't know whether you need to handle this case, maybe just...\n        return null;\n    }\n\n    if (viewModel.Hours != 0 || viewModel.Minutes != 0)\n        return null;\n\n    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); \n}	0
1116439	1116344	UnauthorizedAccessException in my own directory	public static FileInfo[] GetFilesSafe(this DirectoryRoot root, string path) {\n  try {\n    return root.GetFiles(path);\n  } catch ( UnauthorizedAccessException ) {\n    return new FileInfo[0];\n  }\n}	0
385814	385809	Correctly incrementing values using Linq to SQL	var maxId = dc.Logs.Max(s => s.ID);	0
25515548	25513112	How to work with WCF wsHttpBinding and SSL?	ServicePointManager.ServerCertificateValidationCallback = (a,b,c,d) => true	0
16880596	16612230	How do I check if a WatIn parent element 3 levels up is Visible?	string displayValue = _browser.Eval("$('#Make').closest('div.form-row').css('display');");	0
28898169	28897886	How do I read a cookie in another Controller using c#.net?	string username="";\nvar cookie = Request.Headers.GetCookies("MyCookie").SingleOrDefault();\n\nif (cookie != null)\n{\n    username = cookie["MyCookie"].Value;\n}	0
24122995	24122224	Viewing XML output from C#	GetWriterForMessage()	0
1781903	1781869	Get mac address from IP using DHCP?	dhcpexim.exe	0
13837624	13834806	Develop layers first having in mind transition to Dependency Inversion principle and Inversion of Control at a later stage?	public class MyEndClass\n{\n    private readonly IDependency dependency;\n\n    public MyEndClass(IDependency dependency)\n    {\n        this.dependency = dependency;\n    }\n\n    // temporary constructor until we introduce IoC\n    public MyEndClass() : this(new Dependency())\n    {\n    }\n}	0
30807931	30807876	C#: stack with two type item	var stack = new Stack<Tuple<string, int>>();\nstack.Push(Tuple.Create("string", 0));\nvar item = stack.Pop();	0
27987720	27779905	How to Add CRUD Operations to a Second Entity in WPF	public sealed class MainViewModel : INotifyPropertyChanged\n{\n    public ObservableCollection<StudentViewModel> Students {get; set;}\n}\n\npublic sealed class StudentViewModel : INotifyPropertyChanged\n{\n    public ObservableCollection<GradeViewModel> Grades {get; set;}\n\n    public StudentViewModel(){\n        Grades = new ObservableCollection<GradeViewModel>();\n    }\n}\n\npublic sealed class GradeViewModel : INotifyPropertyChanged\n{\n    public string Name { get; set; }\n    public int Value { get; set; }\n}	0
10073781	10073710	Parse Cell Location String into Row & Column	string col = "AB21";\nint startIndex = col.IndexOfAny("0123456789".ToCharArray());\nstring column = col.Substring(0, startIndex);\nint row = Int32.Parse(col.Substring(startIndex));	0
24550013	24549658	Having an evolutive list of stored data, without database	public class Vehicule\n{\n    public int Year { get; set; }\n    public int CarCode { get; set; }\n    public int BikeCode { get; set; }\n\n    public override string ToString()\n    {\n        return string.Format("{0},{1},{2}", Year, CarCode, BikeCode);\n    }\n}\n\npublic class FileStorage\n{\n    public List<Vehicule> GetVehicules(string filePath)\n    {\n        return File.ReadAllLines(filePath).Select(s => s.Split(',')).Select(split => new Vehicule\n        {\n            Year = int.Parse(split[0]),\n            CarCode = int.Parse(split[1]),\n            BikeCode = int.Parse(split[2])\n        }).ToList();\n    }\n\n    public void WriteVehicules(string filePath, IEnumerable<Vehicule> vehicules)\n    {\n        File.WriteAllLines(filePath, vehicules.Select(s => s.ToString()));\n    }\n}	0
8438169	8404489	How to store images in an SQL database on WP7	public static byte[] ConvertToBytes(String imageLocation)\n    {\n        StreamResourceInfo sri = Application.GetResourceStream(new Uri(imageLocation, UriKind.RelativeOrAbsolute));\n        BinaryReader binary = new BinaryReader(sri.Stream);\n\n        byte[] imgByteArray = binary.ReadBytes((int)(sri.Stream.Length));\n\n        binary.Close();\n        binary.Dispose();\n        return imgByteArray;\n    }\n\n    public static WriteableBitmap ConvertToImage(Byte[] inputBytes)\n    {\n        MemoryStream ms = new MemoryStream(inputBytes);\n        WriteableBitmap img = new WriteableBitmap(400, 400);\n\n        img.LoadJpeg(ms);\n\n        return (img);\n    }	0
27859811	27859291	Regex help - domain is not validating	public static void Test()\n        {\n            Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z]{2,}$");\n            var m=re.Match("test.com");\n            Console.WriteLine(m.Groups[0].Value);\n            m=   re.Match("more-messy-domain-0234-example.xx");\n            Console.WriteLine(m.Groups[0].Value);\n       }	0
11943946	11943820	I need to stop a database process from happening after it occurs 10 times	for (int i = 0; i < 5; i++)\n{\n    MyWork();\n    System.Threading.Thread.Sleep(5000);\n}	0
13690485	13689814	Programmatically add a row to datagridview	row.Cells[dataGridView1.Columns["Column1"].Index].Value = "AAAAA";	0
26710453	26710202	c# excel create a button on excel worksheet	Excel.Application xlApp = new Excel.Application();\n    Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE");\n    Excel.Worksheet worksheet = xlBook.Worksheets[1];\n\n    Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;\n    if (selection != null)\n    {\n        Microsoft.Office.Tools.Excel.Controls.Button button =\n            new Microsoft.Office.Tools.Excel.Controls.Button();\n        worksheet.Controls.AddControl(button, selection, "Button");\n    }	0
3538098	3538026	What is the most comfortable datatype I can use to populate a DropDownList with?	fansite.IDTeam = myDropDownList.SelectedValue;	0
25744324	25740813	Manually compile SASS to CSS via C# Action for Customizable Frontend Layouts	string scss = "button.button{background-color: #fff; &:hover{opacity: 0.5;}}"\nvar compiler = new SassCompiler();\nstring compiled = compiler.Compile(source: scss, outputStyle: OutputStyle.Compressed, sourceComments: false); //returns "button.button {background-color:#ffffff;}button.button:hover {opacity:0.5;}"	0
23697489	23697143	How can i sort array: string[]?	string[] strarr = new string[] { @"c:\temp\newimages\Changed_Resolution_By_10\SecondProcess_-Width = 502 Height = 502\animated502x502.gif", @"c:\temp\newimages\Changed_Resolution_By_10\SecondProcess_-Width = 492 Height = 492\animated492x492.gif", @"c:\temp\newimages\Changed_Resolution_By_10\SecondProcess_-Width = 2 Height = 2\animated2x2.gif" };\nIEnumerable<string> strTest = strarr.OrderByDescending(p => p.Substring(p.IndexOf("x"), p.Length - p.IndexOf(".")));	0
15043501	15043438	Run command line tool in new process in Android	try{\n    Process process;            \n    process = Runtime.getRuntime().exec("top -n 1 -d 1");\n    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));\n\n} catch (InterruptedException e) \n{\n    // TODO Auto-generated catch block\n    e.printStackTrace();\n}	0
16611176	16611060	C# MYSQL - I can't insert a boolean value	MySqlCommand command = new MySqlCommand("INSERT INTO Cliente " + \n                      "(nome, email, telefone, blacklist)" + \n                      "VALUES(@nome, @email, @tel, @bl)";\ncommand.Parameters.AddWithValue("@nome",nome_cli.Text);\ncommand.Parameters.AddWithValue("@email", email_cli.Text);\ncommand.Parameters.AddWithValue("@tel", telefone_cli.Text);\ncommand.Parameters.AddWithValue("@bl", 0);\ncommand.ExecuteNonQuery();	0
6859549	6858872	302 redirect still attempting to run original request	new HttpStatusCodeResult(302)	0
17092396	17092078	Windows Store App reading from text file	try\n{\n    var file = await folder.GetFileAsync(path);\n    var lines = await FileIO.ReadLinesAsync(file);\n    foreach (string line in lines)\n    {\n        // "line" variable should contain "account(x) string(x)"\n        // You can then parse it here..\n    }\n}\n...	0
831287	831121	C# RegEx match beginning of string and beginning of word simultaneously	\babc[^e]	0
6286011	6285968	Array creation with constants in c#	public static class Constants\n{\n    public const int CommandArgumentsSize = 3;\n}\n\nstruct Command\n{\n    byte opcode;\n    byte[] arguments = new byte[Constants.CommandArgumentsSize];\n}	0
17639563	17639454	How to implement NextRcord and PreviousRecord button using Linq?	var next = schoolEntities.Students.FirstOrDefault(x => x.Id > currentId);\n  this.StudentName.Text = next.StudentName;	0
2298692	2298672	Need to delete a file, in use by my own app	Rectangle bounds = this.Bounds;\n\nusing (Bitmap ss = new Bitmap(bounds.Width, bounds.Height))\nusing (Graphics g = Graphics.FromImage(ss))\n{\n    this.Opacity = 0;\n    g.CopyFromScreen(this.Location, Point.Empty, bounds.Size);\n\n    using(MemoryStream ms = new MemoryStream()) {\n        ss.Save(ms, ImageFormat.Png);\n\n        this.Opacity = 100;\n        this.BackgroundImage = new Bitmap(ms);\n    }\n\n    g.Dispose();\n}	0
1838387	1837892	Seeking guidance on WPF Prism Multi display application	MyFirstViewModel vm1 = new MyFirstViewModel();\nMySecondViewModel vm2 = new MySecondViewModel();\n\nMyView view1 = new MyView();\nview1.DataContext = vm1;\n\nMyView view2 = new MyView(vm2);\nview2.DataContext = vm2;\n\nview1.Show();\nview2.Show();	0
21171182	21169217	Tiff file compression with C#	myBitmap.Save(new_fileName, myImageCodecInfo, myEncoderParameters);	0
16427048	16426817	Strange control flow	class Base\n{\n    private readonly List<Tuple<string, Action>> steps = new List<Tuple<string, Action>>();\n\n    protected void RegisterStep(string parameter, Action someLogic)\n    {\n        steps.Add(Tuple.Create(parameter, someLogic));\n    }\n\n    protected void Run()\n    {\n        foreach (var step in steps)\n        {\n            var result = RunStep(step.Item1);\n\n            if (result == null)\n            {\n                break;\n            }\n\n            // perform some logic\n            step.Item2();\n        }\n    }\n\n    private object RunStep(string parameter)\n    {\n        // some implementation\n        return null;\n    }\n}\n\nclass Derived : Base\n{\n    public Derived()\n    {\n        RegisterStep("1", () => { });\n        RegisterStep("2", () => { });\n        RegisterStep("3", () => { });\n\n        // etc\n    }\n}	0
6199858	6149117	How to get a reference to patricullar Word Document Paragraphs and then display it into Dsoframer or any Word Processing component for .net?	Object fileName = "C:\\Documents and Settings\\saravanan\\Desktop\\test1.docx";\n  axFramerControl1.Open(fileName, true, 0, "", "");\n\n  Microsoft.Office.Interop.Word.Document wordDoc =     Microsoft.Office.Interop.Word.Document)axFramerControl1.ActiveDocument;\n  Microsoft.Office.Interop.Word.Application wordApp = wordDoc.Application;\n\n  Microsoft.Office.Interop.Word.Range r = wordDoc.Paragraphs[15].Range;\n //object dir = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseStart;\n //r.Collapse(ref dir);\n r.Select();	0
13658975	13658889	read the second line from the text	var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);	0
18180294	18180064	how to structure data that will be fed into dropdown boxes?	declare @name_id int -- input parameter, fill it with id of chosen name\n\n-- filter for type combo\nselect distinct type_id from main_table where name_id = @name_id\n\n-- filter for animal combo\nselect distinct animal_id from main_table where name_id = @name_id	0
6218176	6218147	Enter Data to main form	string username = string.Empty;\nstring password = string.Empty;\n\nusing (LoginForm form = new LoginForm ())\n {\n     DialogResult result = form.ShowDialog();\n     if (result == DialogResult.Ok)\n     {\n         username = form.Username;\n         password = form.Password;\n     }\n }	0
26053454	26018237	how to check which row button is clicked inside Nested Datagrid	protected void BTNBookingReq_Click(Object sender, EventArgs e)\n{\n    Button btnSender = (Button)sender;\n    DataGridItem item = btnSender.NamingContainer as DataGridItem;\n    if (item != null)\n    {\n        TextBox TxtTotalCoLoaderFrom1 = item.FindControl("TxtTotalCoLoaderFrom1") as TextBox;\n        //Do your operation here\n    }\n\n}	0
3608214	3315457	Serialize Datetime without GMT in C#	[System.Xml.Serialization.XmlElementAttribute(DataType="time")]	0
16381892	16377877	HtmlAgilityPack pulling extra text from a block of html	HtmlDocument doc = new HtmlDocument();\ndoc.Load(MyTestFile);\n\nforeach(var node in doc.DocumentNode.SelectNodes("//div[@id='playerStats']/div/span"))\n{\n    Console.WriteLine(node.InnerText + " " + (node.NextSibling != null ? node.NextSibling.InnerText : null));\n}	0
18349971	18349532	An Application which fetches IIS and App Pool details of website hosted in remote server	System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()	0
13321218	13320761	how to get dropdown selecteditem value in server side when i created option in client side	string dropDistSelectedValue = Request.Form[dropDist.UniqueID];	0
24195104	22414813	.NET Group Policy\Machine folder	string[] files;\n    if (Environment.Is64BitOperatingSystem)\n    {\n        files = Directory.GetFiles("C:\\WINDOWS\\SYSNATIVE\\GROUPPOLICY\\MACHINE");\n    }\n    else\n    {\n        files = Directory.GetFiles("C:\\WINDOWS\\SYSTEM32\\GROUPPOLICY\\MACHINE");\n    }\n    foreach (string file in files)\n    {\n        System.Console.WriteLine(file);\n    }	0
2238615	2238334	Defining an extension method for Enum in Silverlight	public static Array GetValues(this Enum enumType)\n   {\n       Type type = enumType.GetType();\n\n       FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);\n\n       Array array = Array.CreateInstance(type, fields.Length);\n\n       for (int i = 0; i < fields.Length; i++)\n       {\n           var obj = fields[i].GetValue(null);\n           array.SetValue(obj, i);\n       }\n\n       return array;\n   }	0
15470033	15469968	Print Dijkstra's Algorithm as a tree	print start.name;\nvar next = start.next;\n\nwhile (next) {\n  print next.name;\n  next = next.next;\n}	0
6421785	6421478	I have Dynamic Property Names and Their Types stored in a Dictionary, how do i build a class dynamically out of it in silverlight?	Dictionary<string, Type> props = new Dictionary<string,Type>();\n        props["Id"] = typeof(int);\n        props["Name"] = typeof(string);\n\n        AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("AsemName"), AssemblyBuilderAccess.RunAndSave);\n        ModuleBuilder mb = ab.DefineDynamicModule("ModuleName");\n        TypeBuilder typeBuilder = mb.DefineType("TypeName", TypeAttributes.Public);\n        foreach(var name in props.Keys){\n            typeBuilder.DefineField(name, props[name], FieldAttributes.Public);\n        }\n        Type type = typeBuilder.CreateType();\n\n        object o = type.GetConstructor(Type.EmptyTypes).Invoke(null);\n\n        //Verfication:\n        Console.WriteLine("Type is: " + o.GetType());\n\n        foreach (var field in o.GetType().GetFields())\n        {\n            Console.WriteLine(" " + field.Name + " of type " + field.ReflectedType);\n        }	0
6399562	6399545	Xml Serialization Dynamic Ignore	public bool ShouldSerializemyChild() {\n     return myChild != null && myChild.Set;\n}	0
31106552	31106387	Argument out of range Listbox	if ( bz < 0 || bz >= listBox1.Items.Count ) {\n    /* Index is out of bound */\n} else {\n    /* You can safely access to elements */\n}	0
33233678	33232793	Back Navigate Button on universal windows 10 app	SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;	0
28331802	28331729	C# running into troubles with TimeSpan. Converting uptime seconds to days/hours	NextValue()	0
15033860	15033822	How to use C# class as data source	IEnumerable<T>	0
5319528	5303113	App.config settings, environment variable as partial path	%ProgramData%\Company...	0
4047336	4047258	C# BackgroundWorker - how should i get rid of DoEvents	private void radioButton_CheckedChanged(object sender, EventArgs e)\n{\n    // ...\n\n    if (backgroundWorker1.IsBusy)\n    {\n        backgroundWorker1.CancelAsync();\n        addJobToQueue();   // Don't wait here, just store what needs to be executed.\n    } else {\n        backgroundWorker1.RunWorkerAsync();\n    } \n}\n\nprivate void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    if (e.Cancelled) {\n        label1.Text = "Canceled";\n    }\n    else {\n        label1.Text = "Complete";\n    }\n\n    // We've finished! See if there is more to do...\n    if (thereIsAnotherJobInTheQueue())\n    {\n         startAnotherBackgroundWorkerTask();\n    }\n}	0
26287946	26226314	Can WPF Data Bind Without Going Through a Windows Control?	public string TempStringBind(string bind)\n    {\n        DummyLabel.SetBinding(Label.ContentProperty, new Binding(bind));\n        return DummyLabel.Content.ToString();\n    }\n\n   public int TempIntBind(string bind)\n    {\n        DummyLabel.SetBinding(Label.ContentProperty, new Binding(bind));\n\n        int newInt;\n        if (DummyLabel.Content != null && int.TryParse(DummyLabel.Content.ToString(), out newInt))\n        {\n            return newInt;\n        }\n        else\n        {\n            return -1;\n        }\n    }	0
1370324	557224	In .Net MVC, how do you access variables from URL Routing outside of the Action?	protected override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n        string agentID = filterContext.RouteData.Values["agentID"].ToString();\n        OtherMethodCall(agentID);\n    }	0
6162242	6086212	Parse Enum with FlagsAttribute to a SqlParameter	private static string GetAlcoholStatuses(Enums.Enums.AlcoholStatus? alcoholStatus)\n{\n    if (alcoholStatus == null)\n        return string.Empty;\n\n    Enums.Enums.AlcoholStatus alcoholStatusValue = alcoholStatus.Value;\n    string alcoholStatuses = string.Empty;\n\n    if (alcoholStatusValue.HasFlag(Enums.Enums.AlcoholStatus.Drinker))\n    {\n        alcoholStatuses = string.Format("{0}{1}{2}", alcoholStatuses, (int)Enums.Enums.AlcoholStatus.Drinker, ",");\n    }\n    if (alcoholStatusValue.HasFlag(Enums.Enums.AlcoholStatus.NonDrinker))\n    {\n        alcoholStatuses = string.Format("{0}{1}{2}", alcoholStatuses, (int)Enums.Enums.AlcoholStatus.NonDrinker, ",");\n    }\n    if (alcoholStatusValue.HasFlag(Enums.Enums.AlcoholStatus.NotRecorded))\n    {\n        alcoholStatuses = string.Format("{0}{1}{2}", alcoholStatuses, (int)Enums.Enums.AlcoholStatus.NotRecorded, ",");\n    }\n\n    return alcoholStatuses;\n}	0
18933417	18913219	Is there a better way to grep a word in a large file (the word can be in the begining or ending of the file)	var rx = new Regex("\bword\b", RegexOptions.Compiled);\n            while ((l = r.ReadLine()) != null)\n                if (rx.IsMatch(l))\n                    break;	0
16329060	16328864	How do I get DataContract attribute from PropertyInfo at the class level?	var attrName = asPropInfo.GetCustomAttributes(typeof(Attribute), true).SingleOrDefault();	0
3267020	3266677	C# Assign a variable that has a certain name	class MyHTTPRequest {\n  public string variableOne { get { return _values["variableOne"]; } }\n  public string variableTwo { get { return _values["variableTwo"]; } }\n  public string variableThree { get { return _values["variableThree"]; } }\n  NameValueCollection _values;\n  public MyHTTPRequest(string queryStringText) { \n    _values = HttpUtility.ParseQueryString(queryStringText); \n  }\n}	0
21093839	21091590	DataGridView don't go into Edit Mode	using (SqlDataAdapter adp = new SqlDataAdapter(SQL, conn)) {\n  adp.Fill(dt);\n}	0
9582300	9582070	linq to xml Select only nodes that have certain elements	from item in xdoc.Descendants("item")\nwhere item.Descendants("category").Any(c => (string)c.Attribute("domain") == "Portal"\n  && (string)c.Attribute("value") == "Events" && c.Elements().Any())\nselect ...	0
30807298	30805443	How to map tapped event for a single object in a canvas control in XAML?	foreach (UIElement ball in playArea.Children)\n       {\n           if(ball is ContentControl)\n                ball.Tapped += ball_Tapped;    \n       }\n    }\n\n    void ball_Tapped(object sender, TappedRoutedEventArgs e)\n    {\n        ContentControl ball = sender as ContentControl;\n        double top = Canvas.GetTop(ball);\n        animateBall(ball, top, playArea.ActualHeight, "(Canvas.Top)");\n    }	0
21951761	21951607	Find words that start with an underscore	(?<!\w)_	0
9805238	9627611	Interface inheritance consistency	abstract class Base : IMethod\n{\n  void IMethod.DoWork()\n  {\n    DoWork();\n  }\n\n  protected virtual void DoWork()\n  {\n    Console.WriteLine("Base.DoWork");\n  }\n}\n\nclass Derived : Base\n{\n  protected override void DoWork()\n  {\n    base.DoWork();\n    //here I where I want to call base.DoWork();\n    Console.WriteLine("Derived.DoWork");\n  }\n}	0
8286142	8285482	Putting a Calendar in a customized vertical tab setting. C# - Winform	MonthCalendar mc1 = new MonthCalendar();\nthis.Controls.Add(mc1);\nmc1.Location = new Point(0, this.ClientSize.Height - mc1.Height);\nmc1.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;\nmc1.BringToFront();	0
19512994	19512814	Need something like Accept Button in User Control	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n  {\n      if (keyData == Keys.Enter) \n      {\n        button.PerformClick();\n        return true;\n      }\n      return base.ProcessCmdKey(ref msg, keyData);\n    }	0
18732167	18731163	How to combine two different strings in one string?	String Player()\n{\n     return gender + name;\n}	0
12215753	12211312	Windows 8 metro apps asign button style programmatically C#	testButton.Style = Resources["DefaultMusicButtonStyle"] as Style;	0
13974269	13974168	How do you create standalone XML nodes in .NET?	public XElement ToXml()\n {\n   XElement element = new XElement("Song",\n                    new XElement("", "foo"),\n                    new XElement("", "bar"));\n\n   return element;\n}	0
11810809	11809697	Lazy- and want all my public members instantiated in constructor	FieldInfo[] fields = this.GetType().GetFields(); //if you're using private fields use GetFields(BindingFlags.NonPublic)\nforeach(FieldInfo f in fields){\n     if(f.FieldType == typeof(ApiParameter)){\n        f.SetValue(this, new ApiParameter());\n     }\n}	0
12534203	12534068	How can I make a groupbox anchor to 3 sides of a panel, but respect its location?	this.groupBox.Anchor = AnchorStyles.Top |\n                       AnchorStyles.Bottom |\n                       AnchorStyles.Left |\n                       AnchorStyles.Right;	0
2158528	2158488	ASP.NET C# Search XML Node on multiple criteria	"//Countries/Country[@Code = 'ZA' and @IsOut = '1']"	0
17878414	17877992	Check if string consists only of valid ISO 8859-1 characters	private static bool IsValidISO(string input)\n    {\n        byte[] bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(input);\n        String result = Encoding.GetEncoding("ISO-8859-1").GetString(bytes);\n        return String.Equals(input, result);\n    }	0
16812840	16812117	Running Page Load multiple times	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private int numClicks = 0;\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        button1.Click += button1_Click;\n        this.Text = numClicks.ToString();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        numClicks++;\n        //try uncommenting and commenting next line of code, and observe the difference:\n        //button1.Click -= button1_Click;\n        Form1_Load(sender, e);\n    }\n\n}	0
2445736	2445716	int.ToString like HH formatted of DateTime	int integer = 5;\n    string str = integer.ToString("00"); // str has "05".	0
22530381	22529752	Is looping through IQueryable the same as looping through a Datareader with Reader.Read() in C#	.ToList()	0
23999238	23959420	CRM 2013: Getting Data from Organization Service with Microsoft.Xrm	try { \n    Entity entity = context.Retrieve(TIME_ENTITY_NAME, GUID, new ColumnSet(TIME_QTY));\n    context.TryRemoveFromCache(entity); // <- This fixed the cache issue.\n    Console.WriteLine(entity.Attributes[TIME_QTY]); \n}	0
5024389	5024316	C# & Dynamic Radio Button List | Incorrect Radio Button Value on Submit	protected void rblContentTypesGetAll_Load(object sender, EventArgs e)\n{\n    if (IsPostBack)\n    {\n        return;\n    }\n\n    var dt = new DataTable();\n    using (var con = new SqlConnection(Global.conString))\n    using (var cmd = new SqlCommand("contentTypeGetAll", con))\n    using (var da = new SqlDataAdapter(cmd))\n    {\n        da.Fill(dt);\n    }\n    //Clear Items before reloading\n    rblContentTypesGetAll.Items.Clear();\n\n    //Populate Radio button list\n    for (int i = 0; i < dt.Rows.Count; i++)\n    {\n        rblContentTypesGetAll.Items.Add(new ListItem(dt.Rows[i]["contentType"].ToString() + " - " + dt.Rows[i]["description"].ToString(),\n            dt.Rows[i]["ID"].ToString()));\n    }\n\n    //Set Default Selected Item by Value\n    rblContentTypesGetAll.SelectedIndex = rblContentTypesGetAll.Items.IndexOf(rblContentTypesGetAll.Items.FindByValue(((siteParams)Session["myParams"]).DefaultContentType.ToLower()));\n}	0
26127495	26126699	Google Chrome displaying special characters for File ActionResult	return Content(htmlResponse, "text/html", System.Text.Encoding.UTF8);	0
11105182	11104910	RegEx For Validating File Names	string RegexBuilder = @"\d\s-\s" + Regex.Escape(Artist) + @"\s-\s" + Regex.Escape(Title);	0
22532462	22525375	How can I use my own application bar with tilt effec?	static TiltEffect()\n    {\n        // The tiltable items list.\n        TiltableItems = new List<Type>() { typeof(ButtonBase), typeof(ListBoxItem), };\n        TiltableItems.Add(typeof(Border));\n        TiltableItems.Add(typeof(TiltEffectAbleControl));\n        UseLogarithmicEase = false;\n    }	0
22444358	22444326	Make an HTTP Request through Proxy	WebClient wc = new Webclient();\nwc.Proxy = new WebProxy(proxyIP, proxyPort);\nvar html = wc.DownloadString(url);	0
16991919	16985418	DataGridView has no columns	FormFields.GridView.Columns[0].Width = (FormFields.GridView.Width / 10) * 6; \nFormFields.GridView.Columns[1].Width = (FormFields.GridView.Width / 10) * 4;	0
8285820	8285677	How to calculate downloading time in c#(FTP)	DateTime t1 =  DateTime.Now;\nwhile (bytesRead > 0)\n{\n    writeStream.Write(buffer, 0, bytesRead);\n    bytesRead = responseStream.Read(buffer, 0, Length);\n}\nDateTime t2 = DateTime.Now;\nTimeSpan diff = t2 - t1;//you can return diff or display it using its properties ..	0
14166057	14166037	Byte array to string - a better method	Encoding.UTF8.GetString(bytearr);	0
33041035	33039633	Silverlight dependancy property is not notifying in custom control	public static readonly DependencyProperty FilterdResourcesProperty =\n        DependencyProperty.Register("SelectedFilterdResources",\n            typeof (ObservableCollection<ResourceItem>),\n            typeof (ResourceSelectionBoxLable),\n            new PropertyMetadata(new ObservableCollection<ResourceItem>(),\n                CaptionCollectionChanged));\n\n\nprivate static void CaptionCollectionChanged(DependencyObject d,\n        DependencyPropertyChangedEventArgs args)\n    {\n        var collection = args.NewValue as INotifyCollectionChanged;\n        if (collection != null)\n        {\n            var sender = d as ResourceSelectionBoxLable;\n            if (sender != null)\n            {\n                collection.CollectionChanged += sender.BoundItems_CollectionChanged;\n            }                \n        }\n    }\n\n    private void BoundItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n    {\n        // Do your control logic here.\n    }	0
2541630	2541628	scrolling two panels at same time c# winForms	private void panel1_Scroll(object sender, ScrollEventArgs e) {\n        panel2.Invalidate();\n    }\n\n    private void panel2_Paint(object sender, PaintEventArgs e) {\n        Point pos = new Point(panel1.AutoScrollPosition.X, 0);\n        TextRenderer.DrawText(e.Graphics, "nobugz waz here", panel2.Font, pos, Color.Black);\n        // Draw something\n        e.Graphics.TranslateTransform(pos.X, pos.Y);\n        e.Graphics.DrawLine(Pens.Black, 0, 0, 100, 100);\n    }	0
14862905	14862258	How do I Create a Collection of Generic Types?	public static BuyerList getBuyerList() {\n  var result = new BuyerList();\n  result.AddRange(one.Get());\n  return result;\n}	0
1766850	1766828	Any way to make a mutable object derived from an immutable object in C#?	interface IReadOnlyObject\n{\n    int Property { get; }\n}\n\nclass DALObject : IReadOnlyObject\n{\n    public int Property { get; set; }\n}	0
6129408	6129370	Generic Replacement for a couple of Funcs	protected X Convert<X>(string value)\n{\n    X val = default(X);\n\n    var tc = TypeDescriptor.GetConverter(typeof(X));\n\n    if (!string.IsNullOrEmpty(value) && tc.CanConvertFrom(typeof(string)))\n    {\n        val = (X)tc.ConvertFromString(value);\n    }\n\n    return val;\n}	0
7125038	7124826	Entity Framework: where field starts with number	var numbers = new string[]{"1","2","3","4","5","6","7","8","9","0"};\nvar b = (from c in dbContext.Companies\n         where numbers.Contains(c.CompanyName.Substring(0,1))\n         select c).ToList();	0
20810623	20742948	dynamic data display chartplotter get current axis values	var v = plotter.Visible;\nint X_left = Convert.ToInt32(v.Left);\nint X_right = Convert.ToInt32(v.Right);	0
15803348	15803215	How to convert any type of Object into byte array in Windows phone 8?	DataContractSerializer serializer = new    DataContractSerializer(typeof(List<Dictionary<String, String>>));\n\nbyte[] byteArr;\n\nusing (var ms = new System.IO.MemoryStream())\n{\n serializer.WriteObject(ms, stringlist);\n byteArr = ms.ToArray();\n}\n return byteArr;	0
7045752	7045501	reading value from memory for pointer location	int intValue = Marshal.ReadInt32(addr);\nlong longValue = Marshal.ReadInt64(addr);	0
23931310	23927275	DevExpress GridView print with my text	private void button1_Click(object sender, System.EventArgs e) \n{ \n  PrintableComponentLink pl = new PrintableComponentLink(new PrintingSystem());\n  pl.Component = gridControl1;\n  pl.CreateAreaEventHandler+= new CreateAreaEventHandler(pl_CreateReportHeaderArea);\n  pl.CreateDocument();\n  pl.ShowPreview();\n}\n\npublic void pl_CreateReportHeaderArea(object sender, CreateAreaEventArgs e)\n{\n        TextBrick brick1 = e.Graph.DrawString("Your text goes here", Color.Black,\n           new RectangleF(0, 0, 620,20), DevExpress.XtraPrinting.BorderSide.None);\n        brick1.HorzAlignment = HorzAlignment.Center;\n        brick1.Font = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);\n}	0
1645582	1645449	Refactor method with multiple return points	public void processStuff()\n    {\n        Status returnStatus = Status.Success;\n        try\n        {\n            if (!performStep1())\n                returnStatus = Status.Error;\n            else if (!performStep2())\n                returnStatus = Status.Warning;\n\n            //.. More steps, some of which could change returnStatus..//\n\n            else if (!performStep3())\n                returnStatus = Status.Error;\n        }\n        catch (Exception ex)\n        {\n            log(ex);\n            returnStatus = Status.Error;\n        }\n        finally\n        {\n            //some necessary cleanup\n        }\n\n        // Do your FinalProcessing(returnStatus);\n\n        return returnStatus;\n    }	0
19586288	19586093	How can I parse a datetime string containing GMT in the end as its timezone?	DateTime parsed = DateTime.ParseExact("Tue, 03 September 2013 02:05:50 GMT", \n                                      "ddd, dd MMMM yyyy HH:mm:ss Z", \n                                       CultureInfo.InvariantCulture);	0
7420996	7420896	Displaying each image from a directory in an Image Control	List<Image> images;\n\nvoid GetImagesIntoAList()\n{\n    List<Image> images = new List<Image>();\n\n    DirectoryInfo dir = new DirectoryInfo(@"D:\somedir");\n                FileInfo[] files = dir.GetFiles();\n\n                foreach (var item in files)\n                {                        \n                   FileStream stream = new FileStream(item.FullName, FileMode.Open, FileAccess.Read);\n                   Image i = new Image();\n                   BitmapImage src = new BitmapImage();\n                   src.BeginInit();\n                   src.StreamSource = stream;\n                   src.EndInit();\n                   i.Source = src;\n                   images.Add(i);\n                }\n\n   Thread rotator = new Thread(rotate);\n   rotator.Start();\n}\n\nvoid rotate()\n{\n   foreach(var img in images)\n   {\n      Dispatcher.BeginInvoke( () => \n      { \n         nameOfImageControlOnAWindow.Source = img;\n\n      }\n      );\n\n      Thread.Sleep(5000);\n   }\n}	0
18081365	18081222	How should I compare these doubles to get the desired result?	private const double DoubleEpsilon = 2.22044604925031E-16;\n\n/// <summary>Determines whether <paramref name="value1"/> is very close to <paramref name="value2"/>.</summary>\n/// <param name="value1">The value1.</param>\n/// <param name="value2">The value2.</param>\n/// <returns><c>true</c> if <paramref name="value1"/> is very close to value2; otherwise, <c>false</c>.</returns>\npublic static bool IsVeryCloseTo(this double value1, double value2)\n{\n    if (value1 == value2)\n        return true;\n\n    var tolerance = (Math.Abs(value1) + Math.Abs(value2)) * DoubleEpsilon;\n    var difference = value1 - value2;\n\n    return -tolerance < difference && tolerance > difference;\n}	0
28032626	28032585	Finding a C# equivalent (that specifies a base parameter) to strtol	long value = Convert.ToInt64(stringVal, base);	0
6252645	6252612	How to trim each string element in the string array without using loop?	var gender = (from row in excel.Worksheet()\n                 select  row["Gender *"].Value.ToString()) ;\n    string[]  genderArray = gender.ToArray().Distinct().Select(g=>g.Trim()).ToArray();	0
23232940	23161929	How do I add a OData key value to my Entity Framework class?	EntityType _vApplicationKey=oDataModelBuilder.Entity<vApplicationKey>()\n_vApplicationKey.HasKey(a => a.ApplicationId);	0
6777882	6777726	Asp.net: Page won't refresh after clicking dynamically generated Button controls	protected void Page_Load(object sender, EventArgs e) {\n   LoadUsers();\n}\n\nvoid b_Click(object sender, EventArgs e) {      \n   Button button = (Button)sender;\n   string firstName = button.CommandArgument;  \n   DbDB.User.Delete(x => x.FirstName == firstName);\n\n   PlaceHolder1.Controls.Remove(button);\n}\n\nvoid LoadUsers() {  \n   DbDB db = new DbDB();\n   List<User> users = db.GetUsers().ExecuteTypedList<User>();\n\n   foreach (User user in Users) {\n      Button button = new Button();         \n      button.CommandArgument = user.FirstName;  // normally the user "id" to identify the user.\n      button.Text = user.FirstName;\n      button.Click += new EventHandler(b_Click);\n      PlaceHolder1.Controls.Add(button);\n   }\n}	0
12746971	12725675	How can I get a list of all the com+ components of a com+ application?	ICOMAdminCatalog2 oCatalog = (ICOMAdminCatalog2) Activator.CreateInstance(Type.GetTypeFromProgID("ComAdmin.COMAdminCatalog"));\n\nICatalogCollection applications = oCatalog.GetCollection("Applications");\napplications.Populate();\nforeach (ICatalogObject applicationInstance in applications)\n{\n    ICatalogCollection comps = applications.GetCollection("Components", applicationInstance.Key);\n    comps.Populate();\n    foreach (ICatalogObject comp in comps)\n    {\n        Console.WriteLine("{0} - {1}", comp.Name, comp.Key);\n    }\n}	0
34204597	34175068	Entity Framework data reading performance	packet size=32768	0
22692977	22692540	Convert JSON string to JsonResult in MVC	using System;\nusing System.Web.Mvc;\nusing Newtonsoft.Json;\n\nnamespace Sandbox\n{\n    class Program\n    {\n        private static void Main(string[] args)\n        {\n            //Added "person" to the JSON so it would deserialize\n            var testData = "{\"result_code\":200, \"person\":{\"name\":\"John\", \"lastName\": \"Doe\"}}";\n\n            var result = new JsonResult\n            {\n                Data = JsonConvert.DeserializeObject(testData)\n            };\n\n            Console.WriteLine(result.Data);\n            Console.ReadKey();\n        }\n\n    }\n}	0
23839937	23837656	MissingMethodException when accessing portable library class in Windows Phone 7	public IMyInterface<in TClass>\n{\n  void DoSomething(TClass value);\n}\n\npublic MyClass : IMyInterface<MyClass>\n{\n  // not important\n}	0
12237844	12237293	how to get Binding of textBox in wpf	BindingExpression bindingExpression = c_textBox1.GetBindingExpression(TextBox.TextProperty);\n    Binding parentBinding = bindingExpression.ParentBinding;\n\n    //make new MultiBinding expression and add parentBinding into it.\n     MultiBinding bindingList = new MultiBInding();\n     bindingList.Bindings.Add(parentBinding);\n    c_textBox1.SetBinding(TextBox.TextProperty, bindingList);	0
5742915	5742754	Fire timer_elapsed immediately from OnStart in windows service	timer.Elapsed += timer_Elapsed;\n        ThreadPool.QueueUserWorkItem((_) => DoWork());\n    ...\n\n    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {\n        DoWork();\n    }\n\n    void DoWork() {\n        // etc...\n    }	0
30481507	30481458	How to remove the data from a string from particular character to particular character?	var splitResult=data.Split(';');\nvar first=splitResult[4];\nvar second=splitResult[5];\nvar third=splitResult[6];	0
27238962	27238911	Make Count reset	private void Reset_Tick(object sender, EventArgs e)\n{\n    if (PerformClick.Enabled == false)\n    {\n        CountTxt.Text = "0";\n        Count = 0;\n    } \n}	0
14735479	14735477	Get return value from stored procedure	// define a new output parameter\nvar returnCode = new SqlParameter();\nreturnCode.ParameterName = "@ReturnCode";\nreturnCode.SqlDbType = SqlDbType.Int;\nreturnCode.Direction = ParameterDirection.Output;\n\n// assign the return code to the new output parameter and pass it to the sp\nvar data = _context.Database.SqlQuery<Item>("exec @ReturnCode = spItemData @Code, @StatusLog OUT", returnCode, code, outParam);	0
8190994	8190824	How to use LINQ to combine two or more collections into one collection	static void Main(string[] args) {\n    var dummys = new List<int>(); dummys.Add(1);\n    var col1 = from dummy in dummys\n               select new { Name1 = "Frank", ID1 = 123, ABC = "abc" };\n    var col2 = from dummy in dummys\n               select new { Name2 = "Harry", ID2 = 456, XYZ = "xyz" };\n    var col3 = from dummy in dummys\n               select new { Name3 = "Bob" };\n\n    var col4 = col1.Select(c=> new { FirstName=c.Name1, Ident=new Nullable<int>(c.ID1)})\n        .Union(col2.Select(c=> new { FirstName=c.Name2, Ident=new Nullable<int>(c.ID2)}))\n        .Union(col3.Select(c=> new { FirstName=c.Name3, Ident=new Nullable<int>()}));\n\n    foreach (var c in col4) {\n        Console.WriteLine(c);\n    }\n    Console.ReadKey();\n}	0
6814063	6813990	How to access a C++ Class in a C# code?	[DllImport("pABC.dll", SetLastError = true, CharSet = CharSet.Auto)]\n        private static extern void func();	0
20533495	20533149	how do i pass a single char value to a string variable after increment from a linQ record data	int asciiCode = ((int)SubMeasurement) + 1;\nSubMeasurement = (char)asciiCode;	0
16942247	16935402	Make Entity Framework use Contains instead of Like and explain 'ESCAPE ~'	using (var context = new BloggingContext())\n{\n    var fishes = context.Fishes.SqlQuery("SELECT * FROM dbo.Fishes WHERE CONTAINS(FishText, @p0)", searchPhrase).ToList();\n}	0
2244748	2244617	How can i add property to a class dynamically	public interface IError { }\n\n        public class ErrorTypeA : IError\n        { public string Name; }\n\n        public class ErrorTypeB : IError\n        {\n            public string Name;\n            public int line;\n        }\n\n        public void CreateErrorObject()\n        {\n            IError error;\n            if (FileNotFoundException) // put your check here\n            {\n                error = new ErrorTypeA\n                    {\n                        Name = ""\n                    };\n            }\n            elseif (InValidOpertionException) // put your check here\n            {\n                error = new ErrorTypeB\n                {\n                    Name = "",\n                    line = 1\n                };\n            }\n        }	0
9859654	9859551	How to insert nested entities using Entity Framework?	context.Invoices.Add(invoice); // invoice contains all invoice details \ncontext.SaveChanges();	0
31685953	31685615	Insert DateTimes of format (yyyy-mm-dd HH:mm:ss +TT:TT) into SQL Server	InsertCommand.Parameters.Add("@TIME1", SqlDbType.DateTimeOffset).Value = DataRow[12];	0
3932580	3932009	UseMnemonic is being affected by FlatStyle on a Button	this.button1.Text = "1&&2";	0
9054992	9054952	Adding a number suffix when creating folder in C#	private void NewFolder(string path) {\n  string name = @"\New Folder";\n  string current = name;\n  int i = 0;\n  while (Directory.Exists(Path.Combine(path, current)) {\n    i++;\n    current = String.Format("{0} {1}", name, i);\n  }\n  Directory.CreateDirectory(Path.Combine(path, current));\n}	0
24444132	24443927	Process each line separately in selected text	string fileToRead = "D:\\temp.txt";    // Temp.txt is the file to read\n\nif (File.Exists(fileToRead))\n{\n    StreamReader reader = new StreamReader(fileToRead);\n    do\n    {\n         textBox1.Text += reader.ReadLine() + "\r\n";    // Read each line and pass it to the TextBox1\n\n    } while (reader.Peek() != -1);\n    reader.Close(); // Close the file \n}	0
2309796	2309759	Launch "background" Windows application	Dim p As New Process\nWith p\n\n    .StartInfo = New ProcessStartInfo\n    .StartInfo.UseShellExecute = True\n    .StartInfo.WorkingDirectory = someFolder\n    .StartInfo.WindowStyle = ProcessWindowStyle.Hidden\n    .StartInfo.FileName = someExeName\n    .Start()\n\nEnd With	0
8204866	8204824	Getting a client-server chat to stream a list of online users in C#	public class Server {\n\n     public void StartAcceptingConnections() {\n\n          while(true) {\n              // accept socket connection\n              // read new user name\n              foreach(Client cl in connectedClients) {\n                  // send new user name to cl.Socket\n              }    \n          }             \n     }\n}	0
17671678	17668733	dropdown in dynamic views mvc4	public class A\n{\n\n    [ScaffoldColumn(false)]\n    public int OrganizationId { get; set; }\n\n\n    [Display(Name="OrganizationId")]\n    [UIHint("DropDownList")]\n    public IEnumerable<SelectListItem> Organizations { get; set; }\n}	0
5225946	5225662	Windows XP a Computer Administrator versus a user with Admin privileges	An application running as a standard user performs operations that require administrator privilege by starting a scheduled task.	0
13320468	13268249	How to convert this json array into list	public class LstFooddtlResult\n{\n    public List<int> food_photo { get; set; }\n    public string food { get; set; }\n    public string qty_uom { get; set; }\n    public string unitcost { get; set; }\n}\n\npublic class RootObject\n{\n    public List<LstFooddtlResult> lstResult { get; set; }\n}	0
5222486	5222374	I am trying to read directory from xml file in c# and have problem	XDocument doc = XDocument.Load(@"test.xml");\nXNamespace _Document_Definition_1 = "http://www.abbyy.com/FlexiCapture/Schemas/Export/Document_Definition_1.xsd";\nXNamespace addData = "http://www.abbyy.com/FlexiCapture/Schemas/Export/AdditionalFormData.xsd";\nstring impagePath = doc.Descendants(_Document_Definition_1 + "_Document_Definition_1")\n                       .First()\n                       .Attribute(addData + "ImagePath")\n                       .Value;	0
19183178	19182432	c# Action<T> How to handle with anonymous methods	public ICollection<string> CheckUserPermissions()\n{\n    List<string> logins = new List<string>();\n\n    Action<OleDbCommand> delCmd = cmd => \n    {\n        cmd.CommandText = "SELECT PERMISSIONS.LOGIN FROM PERMISSIONS";\n        using (var rdr = cmd.ExecuteReader()) \n            while (rdr.Read()) logins.Add(rdr["LOGIN"].ToString());\n    };\n    dbExec(delCmd);\n    return logins;\n}	0
11668309	11668150	Decorator Pattern vs Inheritance with examples	new BorderedDecorator(new ScrollableDecorator(new View()))	0
10457144	9962551	how can i assign ObjectListView Checkbox Value	using BrightIdeasSoftware;	0
7567045	7566865	Problem in reading XML	var doc = XDocument.Load(Application.StartupPath + "\\OrgName.xml");\n var result = doc.Root.Elements("Org").Where(x=>x.Attribute("id").ToString()=="2");	0
6378609	6378590	How to handle values with spaces in Process.Start in C#	private void button19_Click(object sender, EventArgs e)\n{\n    Process.Start("test.exe", "\"" + textBox1.Text + "\"");\n}	0
29838748	29837947	How to convert word to image files in asp.net?	Document doc = new Document(MyDir + "Document.doc");\n\ndoc.Save(MyDir + "Document.ConvertToHtml Out.html", SaveFormat.Html);	0
19020407	19020303	call a JQuery function from code behind in C#	ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "myfunction", "<script type='text/javascript'>myFunction(params...);</script>", true);	0
28460496	28460231	How to swap characters in a string	string s = "ABZBA";\nvar result= s.Select(x=> x == 'A' ? 'B' : (x=='B' ? 'A' : x)).ToArray();\ns = new String(result);	0
1448465	1448458	How to round decimal value up to nearest 0.05 value?	Math.Ceiling(myValue * 20) / 20	0
12948476	12948190	C# How to copy few columns schema from datatable using clone	DataTable newTable = dataTable.DefaultView.ToTable(false, columnsnamearray);	0
12683839	12683637	How do I use an item that's a child of a toolstrip item?	Downloads.DropDown.Items.Add("A File");	0
5996948	5995203	Windows Mobile Internet Explorer History	using Microsoft.Win32;\n\nRegistryKey foldersKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");\nstring historyFolder = foldersKey.GetValue("History");	0
2176323	2176275	C# dictionary, need advice	class PeriodOfTime { \n   public DateTime StartTime {get; set;}\n   public DateTime EndTime {get; set;}\n   public string Description {get; set;} // Use your own enum instead\n}\n// ... \nList<PeriodOfTime> periods = new List<PeriodOfTime>();\n\nvar timeToQuery = DateTime.Now.TimeOfDay;\nvar period = periods.FirstOrDefault(p => timeToQuery >= p.StartTime &&\n                                         timeToQuery <= p.EndTime);	0
1700425	1700280	compact framework 2.0 detecting enter key in a textbox	private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (e.KeyChar == 13)\n        {\n            // Enter\n        }\n    }	0
280478	280406	Bring Windows Mobile 6 forms into the front	[DllImport("coredll.dll")]\nprivate static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n[DllImport("coredll.dll", EntryPoint="SetForegroundWindow")]\nprivate static extern int SetForegroundWindow(IntPtr hWnd);	0
13785731	13785721	Select by key from another list in LINQ	IEnumerable<Apple> query = from ua in usedApples\n                           join a in apples on ua.AppleID equals a.ID\n                           select a;	0
16074683	16074514	some issue in this linq to xml query, while getting value of certain attribute in an element	class Program\n{\n    static void Main(string[] args)\n    {\n        // Create the query \n        var nodes = from appNode in XElement.Load("App.config").Descendants("appSettings").Elements()\n                    where appNode.Attribute("key").Value == "domain"\n                    select appNode;\n\n        var element = nodes.FirstOrDefault();\n        string value = element.Attribute("value").Value;\n\n        Console.WriteLine(value);\n\n        //Pause the application \n        Console.ReadLine();\n    }\n}	0
1584014	1549785	How to resolve bound object from bindingexpression with WPF?	public static T GetValue<T>(this BindingExpression expression, object dataItem)            \n{\n    if (expression == null || dataItem == null)\n    {\n        return default(T);\n    }\n\n    string bindingPath = expression.ParentBinding.Path.Path;\n    string[] properties = bindingPath.Split('.');\n\n    object currentObject = dataItem;\n    Type currentType = null;\n\n    for (int i = 0; i < properties.Length; i++)\n    {\n        currentType = currentObject.GetType();                \n        PropertyInfo property = currentType.GetProperty(properties[i]);\n        if (property == null)\n        {                    \n            currentObject = null;\n            break;\n        }\n        currentObject = property.GetValue(currentObject, null);\n        if (currentObject == null)\n        {\n            break;\n        }\n    }\n\n    return (T)currentObject;\n}	0
10096319	10091767	FaceBook Interests field with asp.net	dynamic result = fb.Get("me/interests");\nvar jsonArray= ((Facebook.JsonArray)result.data);\nvar nvDict = new Dictionary<string,string>();\nforeach(dynamic obj in jsonArray)\n{\n    nvDict.Add(obj.id, obj.name);\n}	0
27472061	27472031	Working with arrays in c#	class MyClass // (pick a more appropriate name, I don't know what kind of data you're handling)\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public decimal Money { get; set; }\n    public string BorP { get; set; }\n}\n\n...\n\nList<MyClass> items = new List<MyClass>();	0
2579895	2578210	how can i extern a variable for a namespace in c#?	// Note: thread safety not implemented...\nnamespace Sample\n{\n    public class GlobalLists\n    {\n        public static List<SomeObject> SomeGlobalObjects;\n    }\n}	0
4559086	4557808	How do I close a form when the ESC key was hit, but only if no Control handled it?	using System;\nusing System.Windows.Forms;\n\nclass MyTexBox : TextBox {\n    protected override bool IsInputKey(Keys keyData) {\n        if (keyData == Keys.Escape) return true;\n        return base.IsInputKey(keyData);\n    }\n    protected override void OnKeyDown(KeyEventArgs e) {\n        if (e.KeyData == Keys.Escape) {\n            this.Text = "";   // for example\n            e.SuppressKeyPress = true;\n            return;\n        }\n        base.OnKeyDown(e);\n    }\n}	0
10582260	10582208	Combine queries at runtime	where (@type = 1 and name = @name) or (@type = 2 and dept = @dept)	0
9414457	9414197	set style to range in first row	Excel.Range rangeCols =  xlWorkSheet.get_Range("1:1");	0
16000371	15999769	How do I set the ContentType in a ServiceStack client?	var response = url.PostToUrl(new { foo = request.foo, bar = request.bar },\n                   acceptContentType = "application/json")\n    .FromJson<MyApiCallResponse>();	0
25803605	25803307	Add some parameter to EventHandler in c#	public void getRankingList(string country,string type)\n    {            \n        WebClient client = new WebClient();\n        client.AllowReadStreamBuffering = true;\n        string url = "......";\n        client.DownloadStringCompleted += (sender, args) => \n        getRankingResult(sender, args, "para");\n        client.DownloadStringAsync(new Uri(url, UriKind.Absolute));\n    }\n\nprivate void getRankingResult(object sender, DownloadStringCompletedEventArgs e, string Para)\n{\n    // .....\n}	0
20691042	20662855	Fetching all mails in Inbox from Exchange Web Services Managed API and storing them as a .eml files	int offset = 0;\nint pageSize = 50;\nbool more = true;\nItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);\n\nview.PropertySet = PropertySet.IdOnly;\nFindItemsResults<Item> findResults;\nList<EmailMessage> emails = new List<EmailMessage>();\n\nwhile(more){\n    findResults = service.FindItems(WellKnownFolderName.Inbox, view);\n    foreach (var item in findResults.Items){\n        emails.Add((EmailMessage)item);\n    }\n    more = findResults.MoreAvailable;\n    if (more){\n        view.Offset += pageSize;\n    }\n}\nPropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here\nservice.LoadPropertiesForItems(emails, properties);	0
8765051	8764991	Linq to XDocument Group by subset	var result = new XDocument(\n    new XElement("Root",\n        from x in doc.Root.Elements()\n        group x by new { x.Name, Attr = (string)x.Attribute("attrname") } into g\n        select g.First()\n    )\n);	0
15153320	15153251	How to programmatically convert a .cal file to a .cg4?	var pathSource = System.IO.Path.Combine(directory, fileNameWithoutExtension, ".cal");\nvar pathDest = System.IO.Path.Combine(directory, fileNameWithoutExtension, ".cg4");\nFile.Move(pathSource, pathDest);	0
13055987	13055357	ASP.NET Gridview Buttons	UpdateCommand="Update COMPANY SET counter=@Counter +1 WHERE CopmanyName=@Company"\n\n\n         <columns> \n              <asp:BoundField HeaderText="counter" DataField="Counter" />             \n          </columns>	0
7552870	7552839	Generate sequence with step value	public static IEnumerable<double> Range(double min, double max, double step)\n{\n    double i;\n    for (i=min; i<=max; i+=step)\n        yield return i;\n\n    if (i != max+step) // added only because you want max to be returned as last item\n        yield return max; \n}	0
5508486	5508424	Convert 2D affine transformation matrix to 3D affine transformation matrix	| a b c |      | a b 0 c |\n| d e f |  =>  | d e 0 f |\n| g h i |      | 0 0 1 0 |\n               | g h 0 i |	0
12525051	12522410	Where to find the EntityList<T> in silverlight ria services?	EntityList<T>	0
10356787	10356598	Updating values in SQL Server database with MVC	Year as (DATEPART('yyyy', Time)) persisted not null,\nMonth as (DATEPART('m', Time)) persisted not null,\nDay as (DATEPART('d', Time)) persisted not null,\nHour as (DATEPART('hh', Time)) persisted not null,\nMin as (DATEPART('mi', Time)) persisted not null,\nTime datetime not null	0
3034076	3033839	Firing MouseLeftButtonDown event programmatically	RaiseEvent( new RoutedEventArgs( UIElement.MouseLeftButtonDownEvent ) )	0
22546121	22544862	Given hostname/Port, how to list all associated IP in Windows Phone SDK 7.1?	private async void getIPs() {\n   HostName serverHost = new HostName("www.stackoverflow.com");\n   var clientSocket = new Windows.Networking.Sockets.StreamSocket();\n   // Try to connect to the remote host\n   await clientSocket.ConnectAsync(serverHost, "http");\n   // Get the HostName as DisplayName, CanonicalName, Raw with the IpAddress.\n   var ipAddress = clientSocket.Information.RemoteAddress.DisplayName;\n   testData.Text += ipAddress;\n}	0
19824900	19824542	EntityFramework transaction rollback with multi table insert	using(var scope = new TransactionScope(\n        TransactionScopeOption.RequiresNew,\n        new TransactionOptions() {\n                IsolationLevel = IsolationLevel.ReadCommitted\n            })) {\n    context.Authors.Add(newauthor);\n    context.SaveChanges();\n    newbook.AuthorID = newauthor.ID\n    context.Books.Add(newbook);\n    context.SaveChanges();\n    scope.Complete();\n}	0
3541115	3540957	How to develop a StopWatch class test first?	class DateTime {\n    public Date getDate() {\n        return System.DateTime.Now();\n    }\n}\n\nclass MockDateTime {\n    public Date getDate() {\n        return this.fakeDate;\n    }\n}\n\nclass StopwatchTest {\n    public void GoneInSixtySeconds() {\n        MockDateTime d = new MockDateTime();\n        d.fakeDate = '2010-01-01 12:00:00';\n        Stopwatch s = new Stopwatch();\n        s.Run();\n        d.fakeDate = '2010-01-01 12:01:00';\n        s.Stop();\n        assertEquals(60, s.ElapsedSeconds);\n    }\n}	0
33822599	33822264	C# - Convert string, to a two dimensional string array	string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";\nvar result = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(foobarString);	0
22623279	22616632	Date Validation problems with JQuery .valid() method	jQuery.validator.methods.date = function (value, element) {\n            var dateRegex = /copyRegexHere/;\n            return this.optional(element) || dateRegex.test(value);\n        };	0
33344793	33344674	calculate time from strings in dropdown lists	DateTime d1 = DateTime.Parse("00:00");\nDateTime d2 = DateTime.Parse("00:05");\nTimeSpan s1 = d2-d1;\nConsole.WriteLine(s1.TotalMinutes + " minutes difference");	0
5984809	5984518	Create bindings of ListView items programmatically	listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());	0
4095910	4095846	Shortest string representation for Int32	int value = 22334;\n    string hex = Convert.ToString(value, 16); // 573e\n    value = Convert.ToInt32(hex, 16);	0
1764921	1764843	How can I construct this string in a nicer fasion?	private void AddValue(StringBuilder time, int units, string unitLabel)\n{\n    if (units > 0)\n    {\n        if (0 < time.Length)\n        {\n            time.Append(" and ");\n        }\n        time.AppendFormat("{0} {1}{2}", units, unitLabel, (1 == units ? String.Empty : "s"));\n    }\n}\n\nprivate void YourExistingMethod()\n{\n    StringBuilder time = new StringBuilder();\n    AddValue(time, Settings.Default.WaitPeriod.Hours, "hour");\n    AddValue(time, Settings.Default.WaitPeriod.Minutes, "minute");\n    AddValue(time, Settings.Default.WaitPeriod.Seconds, "second");\n    this.questionLabel.Text = String.Format("What have you been doing for the past {0}?", time);\n}	0
10652091	10651920	How to parse a math expression	string line = "(((250* 80)/5-(20+3))5) 54";\n\nfor (int i = 0; i < line.Length; i++)\n{\n    //current char is digit, now we should start to collect all digit in this series\n    if (char.IsDigit(line[i]))\n    {\n        StringBuilder builder = new StringBuilder();\n\n        do\n        {\n            builder.Append(line[i]);\n            i++;\n        } while (char.IsDigit(line[i]));\n        //we find whole number, but current index is next to number\n        //for will increment it one more time. We should decrement it\n        i--;\n\n        //here we get need number\n        string number = builder.ToString();\n    }\n    else\n    {\n        //here goes logic for non numbers\n    }\n}	0
2237007	2236996	int array to IEnumerable<MyTestObj>?	myIntArr.Select(i => new MyTestObj(i));\n// or...\nmyIntArr.Select(i => (MyTestObj)i);\n// or...\nmyIntArr.Select(i => new MyTestObj { SomeProperty = i });	0
15020302	15020278	C# How to Insert a Zero date?	// Define an uninitialized date.\n\nDateTime date1 = new DateTime();\nConsole.Write(date1);\nif (date1.Equals(DateTime.MinValue))\nConsole.WriteLine(DateTime.MinValue.ToString() + "  (Equals Date.MinValue)");\n// The example displays the following output:\n//    1/1/0001 12:00:00 AM  (Equals Date.MinValue)	0
759878	759854	How do I run NUnit in debug mode from Visual Studio?	Start External Program: C:\Program Files\NUnit 2.4.8\bin\nunit.exe\n\nCommand line arguments: "<path>\bin\Debug\Quotes.Domain.Tests.dll"	0
31113408	31112572	Replace json brackets using c sharp?how to	string JSON = "{[SAME]}";\n        int startPos=JSON.IndexOf("[") + 1;\n        int LastPos=JSON.LastIndexOf("]");\n        int length = JSON.Length - startPos - (JSON.Length - LastPos);\n        JSON = JSON.Substring(startPos, length);	0
10478707	10478595	how to get xml .text using c#	var doc = XDocument.Parse(@"<TEST>\n  <Project_Name>browser</Project_Name>  \n\n      <Setting BrowserKind =""Firefox"" ></Setting>   \n\n      <ExecuteUrl>http://yahoo.com</ExecuteUrl>\n\n  <caseBox>      \n     <test1>apple</test1>\n  </caseBox>\n</TEST>");\n\n\nvar result = (from test in doc.Elements("TEST")\n              select new { BrowserKind = test.Element("Setting").Attribute("BrowserKind").Value,\n                           ExecuteUrl = test.Element("ExecuteUrl").Value,\n                           CaseBox = test.Element("caseBox").Element("test1").Value });	0
27576685	27573193	How to make object isKinematic	col.rigidbody.isKinematic = true;	0
27585535	27585485	While loop only exiting after conditions are met twice in a row	do{ stuff } while(condition);	0
25042484	25042128	Console Application: Closing Window vs End of Program	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        var prg = new Program();\n        Console.ReadLine();\n    }\n    ~Program() {\n        Console.WriteLine("Clean-up completed");\n        System.Threading.Thread.Sleep(1500);\n    }\n}	0
30094279	30093968	Timeshift an RX sequence into a batch after a quiet period?	IObservable<IList<T>> query =\n    source.Publish(hot => hot.Buffer(() => hot.Throttle(TimeSpan.FromSeconds(1.0))));	0
6524168	6524020	Is there a standard pattern to follow when waiting for N number of async methods to complete?	Task[] tasks = new Task[3]\n{\n    Task.Factory.StartNew(() => MethodA()),\n    Task.Factory.StartNew(() => MethodB()),\n    Task.Factory.StartNew(() => MethodC())\n};\n\n//This will not block.\nTask.Factory.ContinueWhenAll(tasks, completedTasks => { RunSomeMethod(); });	0
21915297	21914917	IntersectWith And RemovesWith with List of Lists	HashSet<Foo> all = listOfLists\n.Skip(1)\n.Aggregate(\nnew HashSet<Foo>(listOfLists.First()),\n(h, e) =>\n{\nh.UnionWith(e);\nreturn h;\n}\n);\n\nHashSet<Foo> diff = all.ExceptWith(same)	0
19290181	18784379	Telerik radgrid paging in webshop, breaks when changing product amount on last page	protected void tbQuantity_TextChanged(object sender, EventArgs e)\n    {\n        if (!_readMode)\n        {\n            RadNumericTextBox tbQuantity = (RadNumericTextBox)sender;\n            GridDataItem dataItem = (GridDataItem)tbQuantity.NamingContainer;\n\n            var shopItemID = (int)dataItem.GetDataKeyValue("ID");\n            var shopItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID);\n\n            if (!shopItem.IsExternal)\n            {\n                _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).Quantity = Convert.ToInt32(tbQuantity.Text);\n                _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).TotalPrice = _sessionHelper.CurrentCart.GetItemCost(shopItemID, false);\n                _shopItemHolder = _sessionHelper.CurrentCart;\n            }\n\n            loadItemsSummary();\n            gvCartItems.Rebind();\n        }\n    }	0
5419022	5418900	Get random users	//Not tested.... may have syntax errors.\nGetRandomUsers(randomUsersCount, existsUsers)\n{\n     var users= (from u in users\n                where existsUsers.Contains(u.Id)\n                select u).Take(randomUserCount);\n\n     return users;\n\n}	0
9035377	9028071	How to get value from number tagged file and compare it?	string[] handle = originalString.Split(new string[] { "\r\n" }, StringSplitOptions.None);\n        List<string> hexa = new List<string>();\n        for (var a = 1; a <= handle.Count() - 1; a++)\n        {\n            if (Regex.IsMatch(handle[a], @"^\s\s5"))\n            {\n                hexa.Add(handle[a + 1]);\n            }\n        }\n\n        List<int> HexaToInt = new List<int>();\n        foreach (string valueHexa in hexa)\n        {\n            int intHexaValue = int.Parse(valueHexa, System.Globalization.NumberStyles.HexNumber);\n            HexaToInt.Add(intHexaValue);\n        }\n\n        int maximumHexa = HexaToInt.Max();\n        string hexValue = maximumHexa.ToString("X");	0
11932583	11932216	How can i check if a text file contain more then one line of text inside?	string path = "test.txt";\nstring valueToWrite = "....";\n\n//only write to the file, if the specified string is not already there\nif(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))\n{\n    File.AppendAllText(path, valueToWrite);\n}	0
6206055	6193984	Show all processes in an AnyCPU application	running[i].MainModule.FileName	0
16297013	16296929	How to open the multiple pdf files in a new windows using asp.net	StringBuilder js = new StringBuilder();\nfor (int i = 0; i < grdAdditionalInsured.Rows.Count; i++)\n{\n    bool checked = ((CheckBox)grdAdditionalInsured.Rows[i].Cells[0].FindControl("chkAdditionalInsured")).Checked;\n    if (checked)\n    {\n        //**some code to get the id based on values**\n        js.AppendFormat(@"WindowPopup('/CertPrints/{0}.pdf');",id));\n    }\n}\nScriptManager.RegisterStartupScript(this, this.GetType(), "filePopup", js.ToString(), true);	0
14648476	14648017	Access child class variable from base class	class a : System.UI.Page\n{\n    protected int c = 0;\n}\n\nclass b : a\n{\n    protected void DoSomething()\n    {\n        c = 1; //Access c from derived class.\n    }\n}	0
16379450	16379348	mvc3 getting a DB model remove error	var servicer = (from s in db.servicers where\n                DateTime.Now >= s.expired select s).ToList();\n\n    if (servicer.Any())\n    {\n        foreach(var s in servicer) \n        {\n            db.servicers.Remove(s);\n        }\n        db.SaveChanges();\n    }	0
16190600	16190525	How to install firebird client into the GAC?	gacutil -i hello.dll	0
6596326	4591423	Desktop Application for youtube(Login and update profile from a desktop appliaction)	Video newVideo = new Video();\n        newVideo.Title = textBoxTitle.Text;// "Smideo Generated Movie";\n        newVideo.Tags.Add(new MediaCategory("Travel", YouTubeNameTable.CategorySchema));\n        newVideo.Keywords = textBoxKeyWords.Text;\n        newVideo.Description = textBoxDescription.Text;\n        newVideo.YouTubeEntry.Private = false;\n        newVideo.Tags.Add(new MediaCategory("Test, Example",\n          YouTubeNameTable.DeveloperTagSchema));\n        try\n        {\n             createdVideo = request.Upload(newVideo);\n        }\n        catch(InvalidCredentialsException c)\n        {\n             doSomethingAboutInvalidCredentials(c);\n        }	0
14489067	14488662	JSON.Net Xml Serialization misunderstands arrays	// Handle JsonConvert array bug\nvar rows = doc.SelectNodes("//Row");\nif(rows.Count == 1)\n{\n    var contentNode = doc.SelectSingleNode("//List/Content");\n    contentNode.AppendChild(doc.CreateNode("element", "Row", ""));\n\n    // Convert to JSON and replace the empty element we created but keep the array declaration\n    returnJson = JsonConvert.SerializeXmlNode(doc).Replace(",null]", "]");\n}\nelse\n{\n    // Convert to JSON\n    returnJson = JsonConvert.SerializeXmlNode(doc);\n}	0
29839666	29003099	Converting a python server request into unity	form.AddField ("username", pUsername);\n    form.AddField ("password", pPassword);\n    form.AddField ("grant_type", "password");\n\n    Hashtable headers = form.headers;\n    byte[] rawData = form.data;\n\n    headers ["Authorization"] = "Basic "+ System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(mS_Client_Id+":"+mS_Client_Secret));\n    string url = "My URL";\n\n    WWW WWWLogin = new WWW(url,rawData,headers);\n    StartCoroutine(Example(WWWLogin));\n}\n\nIEnumerator Example(WWW WWWLogin) \n{\n    yield return WWWLogin;\n\n    if (WWWLogin.error == null)\n    {\n        Debug.Log("WWW Login Success: "+WWWLogin.text);\n    }  \n    else \n    {\n        Debug.Log("WWW Login Error: "+ WWWLogin.error);\n    }  \n}	0
22130416	22129856	IDictionary interface without Remove()	Dictionary<TK,TV>	0
34506464	34506241	Are info messages in sql server localized?	Private Sub _SqlConnection_InfoMessage(sender As Object, e As System.Data.SqlClient.SqlInfoMessageEventArgs) Handles _SqlConnection.InfoMessage\n    If _BackupInProgress Then\n        If e.Errors.Count > 0 Then\n            For Each sqlError As SqlError In e.Errors\n                If sqlError.Number = 3211 Then\n                    Dim rxPercentageDone = New Regex("(\d*)")\n                    Dim match = rxPercentageDone.Match(sqlError.Message)\n                    If match.Success Then\n                        ' match.Groups(1).Value holds the actual progress value\n                        Debug.Print(e.Message)\n                    End If\n                End If\n            Next\n        End If\n    End If\nEnd Sub	0
7905467	7903081	Conditionally add OutputCache Directive	using System.Web;\n\n//......\n//......\n//......\n\nif (someCondition) \n{\nHttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public); //Location="Any"\nHttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddSeconds(1800)); //Duration="1800"\nHttpContext.Current.Response.Cache.SetValidUntilExpires(true); \n}	0
12059117	12058876	Algorithm to display number of views and comments	StringBuilder sb = new StringBuilder();\nif(@Model.Views > 0)\n  sb.AppendFormat("{0:n0} {1}",@Model.Views, _views);\nif(@Model.Comments> 0)\n  sb.AppendFormat("{0:n0} {1}",@Model.Comments, _comments);	0
11205023	11204038	convert a bytearray to a 2-dimensional intarray	internal int[,] JpgToInt(String fileName)\n{\n    Bitmap Bitmap = new Bitmap(fileName);\n\n    int[,] ret = new int[Bitmap.Width,Bitmap.Height];\n\n    for (int i = 0; i < Bitmap.Width; i++)\n    {\n        for (int j = 0; j < Bitmap.Height; j++)\n        {\n            ret[i, j] = Bitmap.GetPixel(i, j).ToArgb();\n        }\n    }\n    return ret;\n}	0
29035691	29034894	an object with the same key already exists in the object statemanager When trying to add the fallowing data Using EF	Id INT IDENTITY (1,1) PRIMARY KEY	0
17406416	17405743	saving a copy of a file being uploaded	string consPath = "C:\\WEB\\DirectiveFiles\\";\n\nprivate string FindExtension(string FileFullName)\n{\n\n    int lastDOT = FileFullName.LastIndexOf(".");\n    string myFileExtension = FileFullName.Substring(lastDOT + 1);\n    myFileExtension = myFileExtension.ToLower();\n    if (myFileExtension != "jpg" && myFileExtension != "pdf" && myFileExtension != "gif" && myFileExtension != "zip")\n        myFileExtension = "Error";\n\n    return myFileExtension;\n}\n\nif (fileUp1.HasFile)\n{\n    fileExtension = FindExtension(fileUp1.FileName);\n    if (fileExtension == "Error")\n    {\n        extFlag = true;\n        lblUpError1.Visible = true;\n        lblUpError1.Text = "Not Proper File " + fileUp1.FileName;\n        goto continueWithoutUpload;\n    }\n    else\n    {\n        filePath1 = consPath + DocID + "." + fileExtension;\n        fileUp1.SaveAs(consPath + fileUp1.FileName);\n        File.Move(@consPath + fileUp1.FileName, @filePath1);\n    }\n}	0
2865137	2864910	C# regularly return values from a different thread	private void startJob(object work) {\n    Thread t = new Thread(\n      new System.Threading.ParameterizedThreadStart(methodToCall)\n    );\n    t.IsBackground = true; // if you set this, it will exit if all main threads exit.\n    t.Start(work); // this launches the methodToCall in its own thread.\n}\n\nprivate void methodToCall(object work) {\n    // do the stuff you want to do\n    updateGUI(result);\n}\n\nprivate void updateGUI(object result) {\n    if (InvokeRequired) {\n        // C# doesn't like cross thread GUI operations, so queue it to the GUI thread\n        Invoke(new Action<object>(updateGUI), result);\n        return;\n    }\n    // now we are "back" in the GUI operational thread.\n    // update any controls you like.\n}	0
3339810	3338699	how make groups(sections) based on column values in gridview?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n       // Display the company name in italics.\n       Session("New_Pair_1") = e.Row.Cells[1].Text\n       Session("New_Pair_2") = e.Row.Cells[2].Text\n\n       If Session("New_Pair_1") <> Session("OLD_Pair_1") OR _\n          Session("New_Pair_2") <> Session("OLD_Pair_2") Then\n             //no pair match with last record's pair\n             //step 1, change the backcolor\n               If e.Row.BackColor = Color.FromName("Gray") Then\n                  e.Row.BackColor = Color.FromName("White")\n               Else\n                  e.RowlBackColor = Color.FromName("Gray")\n               End If\n             //Step 2, reset the "OLD" session vars\n               Session("OLD_Pair_1") = Session("New_Pair_1")\n               Session("OLD_Pair_2") = Session("New_Pair_2")\n       End If\n    }\n}	0
11345818	11345761	How to fill Dataset with multiple tables?	public DataSet SelectOne(int id)\n{\n    DataSet result = new DataSet();\n    using (DbCommand command = Connection.CreateCommand())\n    {\n        command.CommandText = @"\nselect * from table1\nselect * from table2\n        ";\n\n        var param = ParametersBuilder.CreateByKey(command, "ID", id, null);\n        command.Parameters.Add(param);\n\n        Connection.Open();\n        using (DbDataReader reader = command.ExecuteReader())\n        {\n            result.MainTable.Load(reader);\n            reader.NextResult();\n            result.SecondTable.Load(reader);\n            // ...\n        }\n        Connection.Close();\n    }\n    return result;\n}	0
13634131	13633963	Is This Proper Use of GOTO in C#	public static IList<ClientEntity> FilterNoNeedSendBackToClients(IList<ClientEntity> src)\n{\n    if (src == null)\n        return null;\n\n    return (from info in src.AsEnumerable<ClientEntity>()\n            where !(!String.IsNullOrWhiteSpace(info.ProductNumber) &&\n                    info.CancelledByReliantSyncAB01 == (bool?)true)\n            where !(String.IsNullOrWhitespace(info.PartnerContract) &&\n                    String.IsNullOrWhiteSpace(info.ProductNumber))\n            select info).ToList();\n}	0
33552487	33432148	How to format a date in a column using converters?	xmlns:ie="http://infragistics.com/Editors"\n...\n<local:DateTimeFormat x:Key="IncludeTime" />\n...\n<igDP:Field Name="CreatedOn"\n        Label="Label">\n    <igDP:Field.Settings>\n        <igDP:FieldSettings>\n            <igDP:FieldSettings.EditorStyle>\n                <Style TargetType="{x:Type ie:XamDateTimeEditor}" BasedOn="{StaticResource {x:Type ie:XamDateTimeEditor}}">\n                    <Setter Property="ValueToDisplayTextConverter" Value="{StaticResource IncludeTime}" />\n                </Style>\n            </igDP:FieldSettings.EditorStyle>\n        </igDP:FieldSettings>\n    </igDP:Field.Settings>\n</igDP:Field>	0
7330521	7321266	OleDb Connection not reading all the rows from excel file	Properties=\"Excel 12.0;IMEX=1\";"	0
1568361	1568276	What is the appropriate initial value for a ElapsedTime Performance Counter?	Stopwatch.GetTimestamp();	0
5450369	5448410	Is using dynamic types to get values from anonymous objects bad practice?	object anon;\nvoid M1()\n{\n    anon = new { X = 123, Y = 456 };\n}\nvoid M2()\n{ \n    // we want to get anon.X, but it is anonymous. How do we\n    // trick the compiler into it?\n\n    var cast = CastByExample(new { X = 0, Y = 0 }, anon);\n    int x = cast.X;  // gets anon.X!\n}\n\nstatic T CastByExample<T>(T example, object ob) where T : class\n{\n    return (T)ob;\n}	0
10472388	10472213	Connecting a client-Installed C# application to an exported SQL Server database	Server=.\SQLExpress;AttachDbFilename=c:\yourfolder\yourfile.mdf;Database=yourdatabase; Trusted_Connection=Yes;	0
3960330	3959915	Property Should only Be Set by the Serializer	[DataContract]\npublic class SerializeMe\n{\n? ? public SerializeMe(string someString)\n? ? {\n? ? ? ? _someString = someString;\n? ? }\n    [DataMember]\n? ? private string _someString;\n? ? public string TransformedValue\n? ? {\n? ? ? ? get { _someString = TransformToSomething();\n? ? ? ? ? ? ? return _someString; }\n? ? ? ? private set { _someString = value; }\n? ? }\n}	0
8483620	8483471	How to change the size of a picture after inserting it into a word document	Word.Application app = new Word.Application();\nvar doc = app.Documents.Open(@"C:\Users\SomeUserName\Desktop\Doc1.docx");\n\nvar shape = doc.Bookmarks["PicHere"].Range.InlineShapes.AddPicture(@"C:\Users\SomePicture\Pictures\1234.JPG", false, true);\nshape.Width = 150;\nshape.Height = 150;\napp.Visible = true;	0
16864094	16863717	Navigating JSON data in c#	if (stream["stream"].HasValues)\n{\n    print("YIPPEE");\n}else\n{\n    print("No Stream");\n}	0
6931343	6929136	LINQ - join with Group By and get average	var deptRpt2 = from d in ctx.StudInDepartment\n   group d by d.DeptId into grp\n   select new {\n      Dept = grp.Key,\n      AverageMarks = grp.Average(ed=>ed.StudentTb.Marks)\n   };	0
6998639	6998509	How to expose a Model's collection in the ViewModel	class MyViewModel\n{\n  public ObservableCollection<NestedType> MyItems { return Model.Items; }\n}	0
7206278	7206169	How to make TagLib# work on a file with the wrong extension?	string file = @"D:\vs2008\Inetpub\wwwroot\Test\data\AA028578_7_2.jpg";\nTagLib.File tag = TagLib.File.Create(file, "video/mp4", TagLib.ReadStyle.Average);\nConsole.WriteLine(tag.MimeType);	0
5969508	5968592	EF4 how to call a scalar UDF	[EdmFunction]	0
9960107	9960033	parsing XML and GPS data to list	XDocument doc = XDocument.Load("file.xml"); \n\nvar tracks = (from elem in doc.Root.Descendants("Trackpoint") \n               select new track() \n               { \n                   Time = DateTime.Parse(elem.Element("Time").Value, CultureInfo.InvariantCulture),  \n                   positionx = float.Parse(elem.Element("Positition").Element("LatitudeDegrees").Value, CultureInfo.InvariantCulture),  \n                   positiony = float.Parse(elem.Element("Positition").Element("LongitudeDegrees").Value, CultureInfo.InvariantCulture),  \n                   altitude = float.Parse(elem.Element("AltitudeMeters").Value, CultureInfo.InvariantCulture),  \n               });	0
2446797	2445996	How could I click in a control and drag (not Drag and Drop) out of it but still follow the event as long as the button is clicked?	public partial class UserControl1 : UserControl {\n    public UserControl1() {\n      InitializeComponent();\n    }\n    protected override void OnMouseDown(MouseEventArgs e) {\n      if (e.Button == MouseButtons.Left) this.Capture = true;\n      base.OnMouseDown(e);\n    }\n    protected override void OnMouseMove(MouseEventArgs e) {\n      if (e.Button == MouseButtons.Left) {\n        // Your dragging logic here...\n        Console.WriteLine(e.Location);\n      }\n      base.OnMouseMove(e);\n    }\n  }	0
17674956	17674864	Deserialize Json with array	string json = "[[[[{\"string1\":\"AB\",\"date1\":\"01/01/1900 8:59:00\",\"date2\":\"01/01/1900 9:28:00\",\"col\":[\"VO\",\"SC\",\"VD\",\"LF\",\"SR\",\"TT\",\"BN\",\"MM\",\"HH\",\"HH\",\"YY\",\"ZZ\"]}],[{\"string1\":\"AB\",\"date1\":\"01/01/1900 9:02:00\",\"date2\":\"01/01/1900 9:30:00\",\"col\":[\"VO\",\"SC\",\"VD\",\"LF\",\"LP\",\"VV\",\"FF\",\"MM\",\"HH\",\"HH\",\"YY\",\"ZZ\"]}]]]]";\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nvar d = serializer.Deserialize<dynamic>(json);\n\nforeach (dynamic item in d[0][0][0])\n{\n    Console.WriteLine(item["string1"]);\n    Console.WriteLine(item["date1"]);\n    Console.WriteLine(item["date2"]);\n    ...\n}	0
21677052	21676503	Get foreign key(s) of entity from EDMX file	var fk = _entities.MetadataWorkspace.GetItems<AssociationType>(DataSpace.CSpace).Where(a => a.IsForeignKey);\n//check if the table has any foreign constraints for that column\nvar fkname = fk.Where(x => x.ReferentialConstraints[0].ToRole.Name == tablename).Where(x => x.ReferentialConstraints[0].ToProperties[0].Name == columnname);\n//Get the corresponding reference entity column name\nvar refcol = fkname.Select(x => x.ReferentialConstraints[0].FromProperties[0].Name).First();	0
17117923	17117782	Writing into files with editing from a texbox in C#	richTextBox1.SaveFile(Hpath, RichTextBoxStreamType.PlainText);	0
2128626	2126095	Why subscriptions interact with each other?	var keypresses = KeyPresses().ToObservable().Publish();	0
4928052	4928009	How can I suppress a method from getting triggered?	bool flag;\n\nvoid ClickEventHandler(Object server, EventArgs e)\n{\n   if (flag) return;\n   ....\n}	0
8279227	8279174	Get variable from other function	private double totalAmount;\n\nprotected void ReservationForm()\n{\n    double x = 50;\n    double tva = 1.196;\n    this.totalAmount = x * tva;\n    ltrl_showText = "Total Amount is " + this.totalAmount;\n}\n\nprotected void btn_submit_Click(object sender, EventArgs e)\n{\n    ltrl_previewText = "You ordered nameProduct at the price of " + this.totalAmount ;\n}	0
12598178	12597772	Objects with many value checks c#	public class Validator<T>\n{\n    List<Func<T,bool>> _verifiers = new List<Func<T, bool>>();\n\n    public void AddPropertyValidator(Func<T, bool> propValidator) \n    {\n        _verifiers.Add(propValidator);\n    }\n\n    public bool IsValid(T objectToValidate)\n    {\n         try {\n         return _verifiers.All(pv => pv(objectToValidate));\n         } catch(Exception) {\n            return false;\n         }\n    }\n}\n\nclass ExampleObject {\n     public string Name {get; set;}\n     public int BirthYear { get;set;}\n}\n\n\npublic static void Main(string[] args) \n{\n    var validator = new Validator<ExampleObject>();\n    validator.AddPropertyValidator(o => !string.IsNullOrEmpty(o.Name));\n    validator.AddPropertyValidator(o => o.BirthYear > 1900 && o.BirthYear < DateTime.Now.Year );\n    validator.AddPropertyValidator(o => o.Name.Length > 3);\n\n    validator.Validate(new ExampleObject());\n}	0
34129311	34129218	Xml doesn't save to file	XDocument doc = XDocument.Load(filePath);\nvar query = doc.Descendants("Product")\n               .Where(p => (string) p.Attribute("Code") == "{ProductCode}");\nforeach (var element in query)\n{\n    element.SetAttributeValue("Code", Code1);\n}\ndoc.Save(filePath);	0
15843686	15843402	Set List Initial Size	string[] sa = new string[99];\n        sa[71] = "g";	0
754504	742685	select random file from directory	private string getrandomfile2(string path)\n    {\n        string file = null;\n        if (!string.IsNullOrEmpty(path))\n        {\n            var extensions = new string[] { ".png", ".jpg", ".gif" };\n            try\n            {\n                var di = new DirectoryInfo(path);\n                var rgFiles = di.GetFiles("*.*").Where( f => extensions.Contains( f.Extension.ToLower()));\n                Random R = new Random();\n                file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName;\n            }\n            // probably should only catch specific exceptions\n            // throwable by the above methods.\n            catch {}\n        }\n        return file;\n    }	0
2432653	2432591	How to Add cursor files in resources of control Library project	Cursor myCursor;\nusing (var memoryStream = new MemoryStream(Properties.Resources.MyCursorFile))\n{\n    myCursor = new Cursor(memoryStream);\n}	0
12953514	12953397	How to access session from generic handler	application/json	0
5385347	5385292	DateTime to string, formatting a line break into string while preserving culture	string result = string.Format("{0:d}\n{0:T}", timestamp);\n\n// result == "6/15/2009\n1:45:30 PM" (en-US)\n// result == "15.06.2009\n13:45:30"  (de-DE)	0
1672610	1672576	ObjectQuery, passing datetime in Where clause filter	ObjectQuery<Item> _Query = ItemEntities.CreateQuery<Item>("Item");\n_Query = _Query.Where("(it.StartDate >= DATETIME'11/4/2009 17:06:08')");	0
13219025	13218914	Can I use HTML Agility Pack in Windows Forms Applications?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();	0
26724432	26724199	adding a soap header to a web service reference in c#	proxy.APIKeyHeaderValue = new uondev.APIKeyHeader();\n    proxy.APIKeyHeaderValue.Value = "ba97e6a9-3b6d-40ac";\n    test.ProjectMetaData[] nc = test.GetAllProjectMetaData();	0
8399985	8399978	Add two split string values in c#	values.Select(double.Parse).Sum()	0
682410	682227	Check from .NET if Windows Update is enabled	WUApiLib.AutomaticUpdatesClass auc = new WUApiLib.AutomaticUpdatesClass();\nbool active = auc.ServiceEnabled;	0
9890068	9889925	OutOfMemoryException when creating multiple byte arrays	MemoryStream.GetBuffer()	0
2916648	2916583	How to Get a Specific Column Value from a DataTable?	string countryName = "USA";\n        DataTable dt = new DataTable();\n        int id = (from DataRow dr in dt.Rows\n                  where (string)dr["CountryName"] == countryName\n                  select (int)dr["id"]).FirstOrDefault();	0
11771322	11771268	Is there a right-click and scrollwheel click control for a button? C#	private void button1_MouseDown(object sender, MouseEventArgs e) {\n      if (e.Button == MouseButtons.Right) {\n        // Do something\n        //...\n      }\n    }	0
26282429	26282336	DateTime and Stopwatch value comparison	if (myStopwatch.Elapsed >= workDt.TimeOfDay)	0
2535896	2535878	Can I use Html Agility Pack for this?	string str = "<b>Some code</b>";\n// not sure if needed\nstring html = string.Format("<html><head></head><body>{0}</body></html>", str);\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(html);\n\n// look xpath tutorials for how to select elements\n// select 1st <b> element\nHtmlNode bNode = doc.DocumentNode.SelectSingleNode("b[1]");\nstring boldText = bNode.InnerText;	0
12980752	12980640	How to add additional worksheets to an Excel from DataTable	Static void Main()\n{\n\n    var excel = new Microsoft.Office.Interop.Excel.Application();\n    var workbook = excel.Workbooks.Add(true);\n\n    AddExcelSheet(dt1, workbook);\n    AddExcelSheet(dt2, workbook);\n\n    workbook.SaveAs(@"C:\MyExcelWorkBook2.xlsx");\n    workbook.Close();\n\n}\n\nprivate static void AddExcelSheet(DataTable dt, Workbook wb)\n{    \n    Excel.Sheets sheets = wb.Sheets;\n    Excel.Worksheet newSheet = sheets.Add();\n    int iCol = 0;\n    foreach (DataColumn c in dt.Columns)\n    {\n        iCol++;\n        newSheet.Cells[1, iCol] = c.ColumnName;\n    }\n\n    int iRow = 0;\n    foreach (DataRow r in dt.Rows)\n    {\n        iRow++;\n        // add each row's cell data...\n        iCol = 0;\n        foreach (DataColumn c in dt.Columns)\n        {\n            iCol++;\n            newSheet.Cells[iRow + 1, iCol] = r[c.ColumnName];\n        }\n}	0
17592179	17591905	How to Assert Dictionaries in Unit Testing	public string ToAssertableString(IDictionary<string,List<string>> dictionary) {\n    var pairStrings = dictionary.OrderBy(p => p.Key)\n                                .Select(p => p.Key + ": " + string.Join(", ", p.Value));\n    return string.Join("; ", pairStrings);\n}\n\n// ...\nAssert.AreEqual(ToAssertableString(dictionary1), ToAssertableString(dictionary2));	0
6497580	6497466	Insert into MS Access 2007 using C# VS2008 ODBC	cmdnon.CommandText = "INSERT INTO Commonstation...	0
18546029	18545961	Updating wpf parent window after some action on another window	// Inside add button handler open adduser window as dialog box...\n var result = adduser.ShowDialog();\n if(result == true){\n     // user pressed OK button...\n     // insert new user in database\n     // refresh UserManagmentWindow\n }	0
14946763	14946559	Build a model with 2 Foreign Keys to the Same Table	public class Friend\n    {\n        public int FriendID { get; set; }\n        public int RequestorID { get; set; }\n        public int ResponderID { get; set; }\n        public int FriendStatusID { get; set; }\n        public DateTime User1RequestDate { get; set; }\n        public DateTime User2ResponseDate { get; set; }\n        public virtual FriendStatus FriendStatus { get; set; }\n\n        [ForeignKey("RequestorID")] //fixed\n        public virtual User Requestor { get; set; }\n        [ForeignKey("ResponderID")]\n        public virtual User Responder { get; set; }\n    }	0
10639427	10637909	Simulate button click in a Metro Style App	Go_click(this, new RoutedEventArgs());	0
6593460	6454382	Updating the application with a new .net dll gives me FileLoadException?	Could not load file or assembly 'LoadedAssembly, Version=1.0.0.0, Culture=neutral,\nPublicKeyToken=889080b75eb3bad2' or one of its dependencies. The located assembly's manifest\ndefinition does not match the assembly reference. (Exception from HRESULT: 0x80131040)	0
17506802	17504969	Proper way to deliver multiple files to user over internet explorer	Response.Write("<script>");\nResponse.Write("window.open('pdfurl1');");\nResponse.Write("window.open('pdfurl2');");\n...\nResponse.Write("</script>");	0
13259886	13259841	Button press calls method multiple times	bool SpacebarPressed = false;\n\nprivate void KeyDown() {\n    if (!SpacebarPressed) {\n        SpacebarPressed = true;\n        DoSomethingWithSpacebarBeingPressed();\n    }\n}\n\nprivate void KeyUp() {\n    if (SpacebarPressed) SpacebarPressed = false;\n}	0
25742342	25742251	Use non-static method as source for Task	private Task _task;\n\npublic YourClassName()\n{\n   this._task = new Task(this.SomeMethod);\n}	0
2578569	2578560	multiple classes with same methods - best pattern	public interface IFoo { }\n\npublic class A : IFoo {}\npublic class B : IFoo {}\npublic class C : IFoo {}\n\npublic static class FooUtils {\n    public static void Bar(this IFoo foo) { /* impl */ }\n}	0
21544909	18271870	How can the program structure reach Page_PreRender in a page of asp.net	{\n   try\n   {\n    if (RemarkTextBox.Text == string.Empty)\n    {\n        BRMessengers.BRInformation(this, "Remarks Cannot Be left Empty.");\n        return;\n    }\n    else\n    { \n      if (Session["update"].ToString() == ViewState["update"].ToString())\n        {\n            deleteReport(id);\n        }\n   }\n}\ncatch(Exception)\n{\n BrMessanger.BrMessage(this,"server error. Please try again");\n}\nfinally\n{\n  YourGridName.DataSource=loadDetails();\n  YourGridName.DataBind();\n}\n\n}	0
24504837	24504377	Getting selected attribute value of an XML Document using C#	var username = "username2";\nvar xpath = String.Format("Settings/Authentication/auth[@Userame='{0}']", username);\nXmlDoc.SelectSingleNode(xpath)\n      .Attributes["Password"]\n      .Value = password;	0
11157955	10223620	Dapper intermediate mapping	var accounts2 = DbConnection.Query<Account, Branch, Application, Account>(\n                    "select Accounts.*, SplitAccount = '', Branches.*, SplitBranch = '', Applications.*" +\n                    " from Accounts" +\n                    "    join Branches" +\n                    "       on Accounts.BranchId = Branches.BranchId" +\n                    "    join Applications" +\n                    "       on Accounts.ApplicationId = Applications.ApplicationId" +\n                    " where Accounts.AccountId <> 0",\n                    (account, branch, application) =>\n                    {\n                        account.Branch = branch;\n                        account.Application = application;\n                        return account;\n                    }, splitOn: "SplitAccount, SplitBranch"\n                    ).AsQueryable();	0
11250487	11250142	C# COM Interop: Writing to a Cell in an Excel Sheet	Cells[]	0
33211797	33211651	How to get line number of specific word from HTML file	int counter = 0;\nstring line;\n\n// Read the file and display it line by line.\nSystem.IO.StreamReader file = new System.IO.StreamReader("c:\\test.html");\nwhile((line = file.ReadLine()) != null)\n{\n    if ( line.Contains("Subtotal") )\n    {\n        Console.WriteLine (counter.ToString() + ": " + line);\n    }\n\n   counter++;\n}\n\nfile.Close();	0
15205996	15205908	Attribute Properties that accept model expressions	[MyAttribute(BindMethod = "GetBinding")]\npublic string Foo1 { get; set; }\n\npublic Expression GetBinding()\n{\n    Expression<Func<MyModel, string>> expr = m => m.Foo2;\n    return expr;\n}	0
897900	894991	Increase columns width in Silverlight DataGrid to fill whole DG width	void dg_sql_data_SizeChanged(object sender, SizeChangedEventArgs e)\n    {\n        DataGrid myDataGrid = (DataGrid)sender;\n        // Do not change column size if Visibility State Changed\n        if (myDataGrid.RenderSize.Width != 0)\n        {\n            double all_columns_sizes = 0.0;\n            foreach (DataGridColumn dg_c in myDataGrid.Columns)\n            {\n                all_columns_sizes += dg_c.ActualWidth;\n            }\n            // Space available to fill ( -18 Standard vScrollbar)\n            double space_available = (myDataGrid.RenderSize.Width - 18) - all_columns_sizes;\n            foreach (DataGridColumn dg_c in myDataGrid.Columns)\n            {\n                dg_c.Width = new DataGridLength(dg_c.ActualWidth + (space_available / myDataGrid.Columns.Count));\n            }\n        }\n    }	0
21284668	21284582	How to call method inside method	private void button1_Click(object sender, EventArgs e)\n{\n    izra??unaj_ukupne_iznose();\n}	0
1182373	1182362	formating datetime column in a DataSet	foreach (DataRow row in yourDataTable)\n{\n    DateTime dt = DateTime.Parse(row["Date"].ToString());\n    row["Date"] = dt.ToShortDateString();\n}	0
11023646	11022668	WCF Serialization Server configuration	ex.Data.Add("result",criteria);	0
7416828	7416707	C# winform removing and then adding more items to a panel control	mypanel.Controls.clear();	0
21387509	21387235	Saving image shown in web browser	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
10817108	10816488	How to store values of select query in variables in the webservice?	int index = 0;\nwhile (ids.Read())\n{\n    switch (index)\n    {\n        case 0:\n            id1 = ids.GetString(0);\n            break;\n        case 1:\n            id2 = ids.GetString(0);\n            break;\n        case 2:\n            id3 = ids.GetString(0);\n            break;\n    }\n    index += 1;\n}	0
743730	743726	access elements of datagrid view	string s = dataGridView1[0, 0].Value.ToString();\nstring s2 = dataGridView1[0, 1].Value.ToString();	0
12270160	12267711	Create windows console application that mirrors a valid application (Malware Class)	var exeName = @"tasklist.exe";\n    var arguments = "";\n\n    var process = new Process\n    {\n        EnableRaisingEvents = true,\n        StartInfo = new ProcessStartInfo(exeName)\n        {\n            Arguments = arguments,\n            CreateNoWindow = true,\n            UseShellExecute = false,\n            WindowStyle = ProcessWindowStyle.Hidden,\n            RedirectStandardError = true,\n            RedirectStandardOutput = true,\n        },\n    };\n\n    process.OutputDataReceived += \n       (sender, e) => Console.WriteLine("received output: {0}", e.Data);\n\n    process.Start();\n    process.BeginOutputReadLine();\n\n    process.WaitForExit();	0
10202376	10193967	Crystal Report multi table failure	ReportDocument rpt = new ReportDocument(); \nrpt.Load("C:\\Visual Studio 2008\\Projects\\OTW\\OTW\\CrystalReport3.rpt"); \n\nrpt.SetDataBaseLogon("userName", "password", "servername", "database"); \n\ncrystalReportViewer1.ReportSource = rpt;	0
22032384	22032331	C# code to execute an exe file that takes excel file as input	using (p = new System.Diagnostics.Process())\n{\n    p.StartInfo.FileName = "PathTo.exe";\n    // Provide command line argument\n    p.StartInfo.Arguments = "arg1 arg2 arg3 \"Arg with whitespace\"";\n    // You can also try to set the working directory when you run the process\n    p.UseShellExecute = false;\n    p.WorkingDirectory = @"C:\OutputDirectory";\n    p.Start();\n    // In case you want to wait for the process to exit\n    p.WaitForExit();\n}	0
16371327	16239255	How to add a Table in a cell of DataGridView in C# windows application dynamically?	DataTable dt = new DataTable();\ndt.Columns.Add("name");\nfor (int j = 0; j < 10; j++)\n{\n    dt.Rows.Add("");\n}\nthis.dataGridView1.DataSource = dt;\nthis.dataGridView1.Columns[0].Width = 200;\n//add tableLayoutPanel1 into the control collection of the DataGridView\nthis.dataGridView1.Controls.Add(tableLayoutPanel1);\n//resize the row\nthis.dataGridView1.Rows[1].Height = 100;\n//set its location and size to fit the cell\ntableLayoutPanel1.Location = this.dataGridView1.GetCellDisplayRectangle(0,1, true).Location;\ntableLayoutPanel1.Size = this.dataGridView1.GetCellDisplayRectangle(0, 1, true).Size;	0
7267321	7267109	How to write regular expression to get parts from connection string?	var connString = @"metadata=res://*/ent.csdl|res://*/ent.ssdl|res://*/ent.msl;provider=System.Data.SqlClient;provider connection string=""Data Source=1.1.1.1;Initial Catalog={0};Persist Security Info=True;User ID=user;Password=pass;MultipleActiveResultSets=True""";\nRegex metaRegex = new Regex(@"metadata=(?<metadata>[^;]+)");\nRegex connRegex = new Regex(@"provider\sconnection\sstring=""(?<conn>[^""]+)");\nRegex providerRegex = new Regex(@"provider=(?<provider>[^;]+)");\nConsole.WriteLine("MetaData: " + metaRegex.Match(connString).Groups["metadata"]);\nConsole.WriteLine("Connection String: " + connRegex.Match(connString).Groups["conn"]);\nConsole.WriteLine("Provider: " + providerRegex.Match(connString).Groups["provider"]);	0
24792234	24789681	How can I determine if the current time is within a reoccurring time range based on the day of week in C#?	var now = DateTime.Now;\n\n// offset from "Sunday"\nvar i = now.Date.AddDays(-(double) now.DayOfWeek);\n// normalize to this week\nvar s = i.AddDays((double) startDay).AddHours(startTime.TotalHours);\n// normalize to this week\nvar e = i.AddDays((double)((endDay < startDay) ? endDay + 7 : endDay)).AddHours(endTime.TotalHours);\nDebug.Assert(now >= s && now <= e);	0
10100953	10100901	creating simple excel sheet in c# with strings as input	using Excel = Microsoft.Office.Interop.Excel;\n\nExcel.Application excel = new Excel.Application();\nexcel.Visible = true;\nExcel.Workbook wb = excel.Workbooks.Open(excel_filename);\nExcel.Worksheet sh = wb.Sheets.Add();\nsh.Name = "TestSheet";\nsh.Cells[1, "A"].Value2 = "SNO";\nsh.Cells[2, "B"].Value2 = "A";\nsh.Cells[2, "C"].Value2 = "1122";\nwb.Close(true);\nexcel.Quit();	0
27898871	27863525	WPF Row Validation for Primary Key Field	public class DataRowValidation : ValidationRule\n{\n    public List<PersonInfo> People {get; set;}\n    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)\n    {\n        if (value is BindingGroup)\n        {\n            BindingGroup group = (BindingGroup)value;\n            People = PersonClass.personList;\n\n            //Code to loop through list and test for duplicates\n        }\n     }\n}	0
8402999	8402954	Modifying Values in a For Each Loop - Any Way?	foreach (var x in Variables.Keys.ToArray())	0
1667533	1667408	C#: Getting Names of properties in a chain from lambda expression	public void Foo<T, P>(Expression<Func<T, P>> expr)\n{\n    MemberExpression me;\n    switch (expr.Body.NodeType)\n    {\n        case ExpressionType.Convert:\n        case ExpressionType.ConvertChecked:\n            var ue = expr.Body as UnaryExpression;\n            me = ((ue != null) ? ue.Operand : null) as MemberExpression;\n            break;\n        default:\n            me = expr.Body as MemberExpression;\n            break;\n    }\n\n    while (me != null)\n    {\n        string propertyName = me.Member.Name;\n        Type propertyType = me.Type;\n\n        Console.WriteLine(propertyName + ": " + propertyType);\n\n        me = me.Expression as MemberExpression;\n    }\n}	0
10662063	10661967	Saving as jpeg from memorystream in c#	Private void ResizeImage(Image img, double maxWidth, double maxHeight)\n{\n    double srcWidth = img.Source.Width;\n    double srcHeight = img.Source.Height;\n\n    double resizeWidth = srcWidth;\n    double resizeHeight = srcHeight;\n\n    double aspect = resizeWidth / resizeHeight;\n\n    if (resizeWidth > maxWidth)\n    {\n        resizeWidth = maxWidth;\n        resizeHeight = resizeWidth / aspect;\n    }\n    if (resizeHeight > maxHeight)\n    {\n        aspect = resizeWidth / resizeHeight;\n        resizeHeight = maxHeight;\n        resizeWidth = resizeHeight * aspect;\n    }\n\n    img.Width = resizeWidth;\n    img.Height = resizeHeight;\n}	0
17457753	17457721	How to know what kind of arguments an event has	SomeEvent +=	0
1808018	1807975	XMLWriter for HTML creation - how to add simple non-pair tags?	HTML: <img src="..">\n XHTML: <img src=".." />	0
14944313	14941120	Searching if all properties exist in a list of entities using Linq	var query = _entityRepository.Entities.Select(e => e);\nquery = searchTags.Aggregate(query, (current, tag) => current.Where(e => e.Tags.Any(t => t.TagValue == tag)));\nvar result = query.ToList();	0
20321601	20320910	safe usage of Timers in multi-threading	private bool Timing = false;\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Timing = true;\n        Thread th1 = new Thread(updatetimer);\n        th1.IsBackground = true;\n        th1.Start();\n\n        secret = a.Next(0, 101);\n        counter = 0;\n        label2.Text = "";\n        button1.Enabled = false;\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        Timing = false;\n        button1.Enabled = true;\n    }\n\n    public void updatetimer()\n    {\n        Stopwatch aa = Stopwatch.StartNew();\n        TimeSpan ts;\n        while (Timing)\n        {\n            ts = aa.Elapsed;\n            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}:{3:000}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);\n            this.Invoke((MethodInvoker)delegate\n            {\n                label3.Text = elapsedTime;\n            });\n            System.Threading.Thread.Sleep(50);\n        }\n    }	0
20677804	20667798	exception in sqlite transaction c#	public override int ExecuteNonQuery(string query)\n    {\n\n        int register=0;\n        //SQLiteTransaction trx=null;\n        SQLiteCommand com;\n        try\n        {\n            if (con.State == ConnectionState.Closed) this.Open();\n\n                //trx = con.BeginTransaction();//para hacer transaciones para que la base de datos este estable\n                com = new SQLiteCommand(query, con);\n                //com.Transaction = trx;\n                register = com.ExecuteNonQuery();//recien hacemos la coneccion en esta linea\n               // trx.Commit();\n\n            return register;\n        }\n        catch (SQLiteException ex)\n        {\n           // trx.Rollback();//se tiene q deshaser toda la trransaccion hecha\n            throw ex;\n        }\n\n        finally\n        {\n            this.Close();\n        }\n\n    }	0
2801359	2801252	Windows Form - ListView - Removing lines between columns	this.listView1.View = System.Windows.Forms.View.Details;\n        this.listView1.GridLines = false;	0
3908977	3908930	How to draw centered text onto a jpg using system.drawing in c#	using(var sf = new StringFormat()\n{\n    Alignment = StringAlignment.Center,\n    LineAlignment = StringAlignment.Center,\n})\n{\n    gra.DrawString(text, font, brush, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);\n}	0
24727330	24695990	How to get saved date value from Sql Server in dateTimePicker Control in Windows Application	dateTimePickerJoinDate.Value = dt.Rows[0]["JoinDate"].ToString();\n-- or\ndateTimePickerJoinDate.Value = Convert.ToDateTime(dt.Rows[0]["JoinDate"]);	0
507279	507262	How to find if an object is from a class but not superclass?	typeof(SpecifiedClass) == obj.GetType()	0
7238622	7238525	How can I change the text of an existing ToolTip control, in a PictureBox in my WinForm application?	toolTip.SetToolTip(...)	0
15275213	15275166	Can I overwrite a css class in a UserControl?	Panel myPanel = (Panel)this.Parent.FindControl("DescrizionePagina");\nmyPanel.CssClass = "pagina-testo-box-small";	0
25735108	25734903	Forcing the inner part of a form to stay in the same position while changing border style	private void button1_Click(object sender, EventArgs e)\n{\n    var X = (this.Size.Width - this.ClientRectangle.Width) / 2;\n    var Y = (this.Size.Height - this.ClientRectangle.Height) - X;\n    Point p = new Point(Location.X + X, Location.Y + Y);\n    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n    this.Location = p;\n}	0
32573606	32573582	C# API with lots of optional parameters demands values in all of them	DC.Add(dbEditText, "Property", DtaColIn: DC);	0
33677411	33677321	Generating random keys in C#	while (i < length)	0
32097596	32057920	How to replace a ExpressionSyntax by an ArgumentSyntax	var assignmentExpression = root.FindNode(context.Span) as AssignmentExpressionSyntax;\n        var objectCreation = assignmentExpression?.Right as ObjectCreationExpressionSyntax;\n        var argument = objectCreation?.ArgumentList.Arguments[0];\n\n        if (argument == null)\n            return;\n\n        var newRoot = root.ReplaceNode(objectCreation, \n            argument.Expression\n            .WithoutLeadingTrivia()\n            .WithAdditionalAnnotations(Formatter.Annotation));\n        context.RegisterCodeFix(CodeActionFactory.Create(assignmentExpression.Span, diagnostic.Severity, "Remove redundant 'new'", document.WithSyntaxRoot(newRoot)), diagnostic);	0
3776230	3776210	Sending email to a user	html = html.Replace("$user", name)	0
4674009	4673894	DataGridView - DefaultCellStyle, rows and columns priority	dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Lavender;\ndataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Beige;\ndataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Beige;	0
5584825	5563774	Dilemma with using value types with `new` operator in C#	someDate = new Date();	0
10622542	10620969	Redirect response to download file	document.location.href = '/genericHandlers/DownloadFile.ashx?id=' + this.model.get("id");	0
11851718	11851442	Are there any alternatives to OleDb to improve performace?	private void SomeMethod()\n {\n    SqlCommand sqlcmd = new SqlCommand();\n    using (SqlConnection sqlConn = new SqlConnection(ConfigurationSettings.AppSettings["strConnectionString"]))//strConnectionString\n    {\n       sqlConn.Open();\n       sqlcmd.Connection = sqlConn;\n       SqlTransaction transaction;\n       // Start a local transaction.\n       transaction = sqlConn.BeginTransaction("DeleteRecs");\n       sqlcmd.Transaction = transaction;\n       sqlcmd.CommandTimeout = 60;\n       sqlcmd.CommandText = "uf_DeleteWeeks";\n       sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;\n       try\n       {\n          sqlcmd.ExecuteNonQuery();\n          sqlcmd.Transaction.Commit();\n       }\n       catch (SqlException sqle)\n       {\n\n        try\n        {\n           transaction.Rollback("DeleteRecs");\n        }\n        catch (Exception ex)\n        {\n\n        }\n       Console.WriteLine(sqle.Message);\n       }\n      }\n      ((IDisposable)sqlcmd).Dispose();\n   }	0
25380094	25377857	HTMLTextWriter Remove Hyperlinks and formatting in C#	string html2 = Regex.Replace(sw.ToString(), @"(<input type=""javascript""\/?[^>]+>)", @"", RegexOptions.IgnoreCase);\nhtml2 = Regex.Replace(html2, @"(<a \/?[^>]+>)", @"", RegexOptions.IgnoreCase);\nResponse.Write(html2.ToString());	0
17903493	17903415	Reader Nodes from XML	XmlNode node = doc.SelectSingleNode("/whois-resources/objects/object/attributes/attribute[@name=\"descr\"]");\n\nXmlAttribute attrib = node.Attributes["value"];\n\nMessageBox.Show(attrib.Value);	0
1429438	1410113	Pass values from one to another page	ChildWindow myWin = new MyWindow("Test", "Test of shared ui elemnts");\nmyWin.Show();\nmyWin.Closed += new EventHandler(myWin_Closed);\n\nvoid errorWin_Closed(object sender, EventArgs e)\n{\n  ErrorWindow wrr = (ErrorWindow)sender;\n  string mytext = wrr.MyText; // Can access any property that was set ChildWindow\n}	0
28644638	28644611	How can I create a list of objects from data in an enum?	Enum.GetValues(typeof(ERole))\n    .Cast<ERole>()\n    .Select(x => new { Id = (int)x, Name = x.ToString() })\n    .ToList();	0
21657940	21657863	how to set winform checkboxlist items to be semi-checked?	// Adds the string if the text box has data in it. \n  private void button1_Click(object sender, System.EventArgs e)\n  {\n     if(textBox1.Text != "")\n     {\n        if(checkedListBox1.CheckedItems.Contains(textBox1.Text)== false)\n           checkedListBox1.Items.Add(textBox1.Text,CheckState.Checked);  // here you can set CheckState.Indeterminate!\n        textBox1.Text = "";\n     }\n  }	0
16066579	16066296	"Deleted row information cannot be accessed through the row" trying to remove unused rows from my datatable	foreach (DataRow row in table.Rows)\n{\n    if(row.RowState != DataRowState.Deleted) \n    {     \n       if (!currentReadingsNames.Contains(MakeKey(row["ParentID"].ToString(), row["ID"].ToString())))\n            {\n                row.Delete();\n            }\n        }\n    }	0
3122025	3122015	Combine date and time when date is a DateTime and time is a string	DateTime newDateTime = oldDateTime.Add(TimeSpan.Parse(timeString));	0
30759599	30759224	How to set group of a new user?	private void AddUser()\n{\n    using (var context = new AzubiTestEntities())\n    {\n        var user = new Benutzer();\n        var gruppen = context.Gruppen.First(x => x.GruppenID == [group id]);\n\n        user.Name = Username;\n        user.Passwort = GenerateHashPassword();\n\n        user.Gruppen = gruppen;\n\n        user.Anlegedatum = DateTime.Now;\n        user.Loeschdatum = null;\n        user.ErstellerID = 1;\n\n        context.Benutzer.Add(user);\n\n        context.SaveChanges();\n    }\n}	0
26334312	26334092	set a default in C#	private int _theDay = DateTime.Now.Day;\n\npublic int TheDay\n{\n     get \n     {\n         if(Request.QueryString["d"] != null) \n              _theDay =  Convert.ToInt16(Request.QueryString["d"]);             \n\n         return _theDay; \n     }\n     set \n     {\n\n        if ( value <= 31 && value > 0 )\n        {\n            _theDay= value;\n        }\n        else \n        {\n            _theDay= DateTime.Now.Day;\n        }\n    }\n}	0
27905610	27905529	Converting DataView to DataSet	DataSet DS = New DataSet();	0
26973375	26970469	How do I combine two lists to display the needed result?	var stocksCount = items.GroupBy(x => x.ItemID)\n                                 .Select(x => new { ItemID = x.Key, ItemCount = x.Count() }).ToList();\n\nvar result = from item in items\n                             join stock in stocks\n                             on item.ItemID equals stock.ItemID\n                             select new\n                             {\n                                 item.ItemID,\n                                 item.ItemName,\n                                 item.ProcessId,\n                                 item.ReqQTY,\n                                 AllocatedStock = (stock.Stock / stocksCount.First(x => x.ItemID == item.ItemID).ItemCount)\n                             };	0
1718891	1718863	How to iterate all "public string" properties in a .net class	private string[] GetPublicStringProperties()\n{\n    return this.GetType()\n        .GetProperties(BindingFlags.Public | BindingFlags.Instance)\n        .Where(pi => pi.PropertyType == typeof(string))\n        .Select(pi => pi.Name)\n        .ToArray();\n}	0
13335002	13333368	Set img src from SQL	/images/Clear_Flag.png	0
3296945	3296645	Equivalent of Format of VB in C#	iCryptedByte.ToString("D3");	0
10479964	10213689	Microsoft chart grid lines not drawn at 'whole' numbers	myChart.ChartArea[0].AxisX.IsMarginVisible = false;	0
16983920	16983788	c# byte order in a byte array?	ushort word = 0x0001;  // 16bit word with lsb set\nvar bits = new BitArray(BitConvert.GetBytes());\n\nif (bits[0]) {\n    // little endian\n} else if (bits[8]) { \n    // big endian\n}	0
15617051	15549091	Search for a Local user in a local group that does not have Foreign Security policy	protected bool IsUserInLocalGroup(string userName, string group)\n    {\n        using (DirectoryEntry computerEntry = new DirectoryEntry("WinNT://{0},computer".FormatWith(Environment.MachineName)))\n        using(DirectoryEntry groupEntry = computerEntry.Children.Find(group, "Group"))\n        {\n            foreach (object o in (IEnumerable)groupEntry.Invoke("Members"))\n            {\n                using (DirectoryEntry entry = new DirectoryEntry(o))\n                {\n                    if (entry.SchemaClassName.Equals("User", StringComparison.OrdinalIgnoreCase) && entry.Name.Equals(userName, StringComparison.OrdinalIgnoreCase))\n                    {\n                        return true;\n                    }\n                }\n            }\n            return false;\n        }\n    }	0
30246087	30224372	Disable Keybindings in MVVM	this.InputBindings.Add(new KeyBinding(((MainViewModel) this.DataContext).  \n                           SavePartCommand, new KeyGesture(Key.S, ModifierKeys.Control)));	0
21502652	9511984	How to prevent richTextBox to paste images within it?	private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        //if ((Control.ModifierKeys & Keys.Control) == Keys.Control && (e.KeyChar == 'V' || e.KeyChar == 'v'))\n        if (((int)e.KeyChar) == 22)\n        {\n            if(hasImage(Clipboard.GetDataObject()));\n            {\n                e.Handled = true;\n                richTextBox1.Undo();\n                MessageBox.Show("can't paste image here!!");\n            }\n\n\n        }\n    }\n\n    private Boolean hasImage(object obj)\n    {\n        System.Windows.Forms.RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();\n        Object data = Clipboard.GetDataObject();\n        Clipboard.SetDataObject(data);\n        richTextBox.Paste();\n        Clipboard.SetDataObject(data);\n        int offset = richTextBox.Rtf.IndexOf(@"\f0\fs17") + 8; // offset = 118;\n        int len = richTextBox.Rtf.LastIndexOf(@"\par") - offset;\n        return richTextBox.Rtf.Substring(offset, len).Trim().Contains(@"{\pict\");\n    }	0
29421633	29420593	Restsharp - Error attempting to serialize xmlns attribute on root node	request.AddBody(requestBody, "https://someurl.com");	0
21619196	21594402	Excel: Values from Ranges With Multiple Areas	public List<List<object>> \nGetNonContiguousRowValue(Excel.Worksheet ws, string noncontiguous_address)\n{\n    var addresses = noncontiguous_address.Split(','); // e.g. "A1:D1,A4:D4"\n    var row_data = new List<List<object>>();\n\n    // Get the value of one row at a time:\n    foreach (var addr in addresses)\n    {\n        object[,] arr = ws.get_Range(addr).Value;\n        List<object> row = arr.Cast<object>)\n                              .Take(arr.GetLength(dimension:1))\n                              .ToList<object>();\n        row_data.Add(row);\n    }\n    return row_data;\n}	0
6456015	6455979	how to get the image dimensions from the file name	System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:\ggs\ggs Access\images\members\1.jpg");\nMessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);	0
14969559	14969374	EF Select MAX value that is <= 5	Price p = db.Prices\n    .Where(p => p.numdays <= totaldays)\n    .OrderByDescending(p => p.numdays)\n    .First()	0
27945733	27945630	How to add items to a string array from a dropdownlist	string[] strSpecArrayForTopics = new string[Specialty.Items.Count]; //total number of specialty items\nint index = 0;\nforeach (ListItem li in Specialty.Items) //for each item in the dropdownlist\n{\n    strSpecArrayForTopics[index] = li.Value; //add the value to the array (The error happens here)\n    lblSpec.Text = lblSpec.Text + "<br />" + li.Value; //this works fine.\n    index = index + 1;\n}	0
2736196	2736024	How to order a List by the order of another List?	public List<MyType> GetMyTypes(List<int> ids)\n{\n    var unordered = (from myType in db.MyTypes\n                     where ids.Contains(myType.Id)\n                     select new MyType\n                     {\n                         MyValue = myType.MyValue\n                     }).ToList();\n\n    var ordered = (from uo in unordered\n                   orderby ids.IndexOf(uo.Id)\n                   select uo).ToList();\n\n    return ordered;\n\n}	0
9101186	9101070	Is it OK to inject the container into a factory?	Func<IFooService>	0
15693698	15693431	Cycling through DropDownItems in ToolStripSplitButton	private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e) {\n  ToolStripSplitButton tsb = (ToolStripSplitButton)sender;\n  string text = tsb.DropDownItems[0].Text;\n  bool found = false;\n  for (int i = 0; i < tsb.DropDownItems.Count; i++) {\n    if (found) text = tsb.DropDownItems[i].Text;\n    found = (tsb.Text == tsb.DropDownItems[i].Text);\n  }\n  tsb.Text = text;\n}	0
31409780	31409645	Is it possible to create a GUI control that can be accessed from two Threads?	Control.Invoke	0
24768027	24760830	Direct use of gstreamer-sharp (without command line)	var playbin = ElementFactory.Make("playbin", "my-playbin");\nplaybin["uri"] = "file:///a:/test.avi";	0
6614418	6613442	Help moving from one xmlnode to another of the same name	public void CheckTimes\n{\n    MFXProgramme previousProg = null;\n    MFXProgramme nextProg = null;\n    foreach (MFXProgramme prog in Programmes.OrderBy(p => p.Start))\n    {\n        nextProg = prog;\n        if (previous != null)\n        {\n            if (previous.Stop != next.Start)\n            {\n                //Gap\n            }\n        }\n        previousProg = prog;\n    }\n}    \n\nclass MXFProgramme\n{\n    ...\n    public DateTime Start\n    {\n        get\n        {\n            return DateTime.Parse(xProgramme.Attributes["start"].Value);\n        }\n    }\n\n    public DateTime Stop\n    {\n        get\n        {\n            return DateTime.Parse(xProgramme.Attributes["stop"].Value);\n        }\n    }\n}	0
17149542	17149367	C# getting a selected date from calendar and displaying it in a message box	private void submitButton_Click(object sender, EventArgs e)\n    {\n\n        MessageBox.Show("Date they start: " + completionCalendar.SelectionEnd.ToString("dd-mm-yyyy"));\n\n    }	0
16284618	16284398	read xml with same elements name	var drawNo = loadeddata.Root.Element("drawNo").Value;\nvar drawTime = loadeddata.Root.Element("drawTime").Value;\nvar results = loadeddata.Descendants("result").Select(d => d.Value).ToList();	0
10811633	10811596	How to give xml string to XDocument in Xpath	XDocument doc = XDocument.Parse(s);	0
2419693	2419678	How deep do you take the Has-a when it comes to Object Oriented Design?	public class Tire\n{\n    public float Size {get;set;}\n    public string Brand {get;set;}\n}\n\npublic class Car\n{\n    public IList<Tire> Tires {get; private set;}\n}	0
22243267	22227244	wince get notification on resume of device c#	OpenNETCF.WindowsCE.PowerManagement.PowerUp	0
2502978	2500704	WinForms Menu Toolstrip Get Status	var alfa = ((((Application.OpenForms[0].Controls["_menustripMenu"] \n                                             as System.Windows.Forms.MenuStrip).\n                 Items["_settingsToolStripMenuItem"] \n                                      as System.Windows.Forms.ToolStripMenuItem).\n                 DropDownItems["_cameraToolStripMenuItem"] \n                                      as System.Windows.Forms.ToolStripMenuItem).\n                 DropDownItems["_useLocalImageForInitToolStripMenuItem"] \n                              as System.Windows.Forms.ToolStripMenuItem).Checked;	0
32624702	32624434	Convert Image to Memory Stream data in Javascript	public Image Base64ToImage(string base64String)\n{\n  // Convert Base64 String to byte[]\n  byte[] imageBytes = Convert.FromBase64String(base64String);\n  MemoryStream ms = new MemoryStream(imageBytes, 0, \n    imageBytes.Length);\n\n  // Convert byte[] to Image\n  ms.Write(imageBytes, 0, imageBytes.Length);\n  Image image = Image.FromStream(ms, true);\n  return image;\n}	0
961571	961564	variable doesn't exist in current context	FileStream FS = null;\n    try\n    {\n        FS = new FileStream(this.InFile, FileMode.Open, FileAccess.Read);\n        return "";\n    }\n    catch (FileNotFoundException ex)\n    {\n        return ex.Message;\n    }\n\n    finally\n    {\n        if (FS != null) {\n            FS.Close();\n            FS.Dispose();\n        }\n    }	0
27483089	27483005	LongListSelector get selected data	private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n            var selecteditem = MainLongListSelector.SelectedItem as LongListData; \n            MessageBox.Show(selecteditem.ImgText.ToString());\n        }	0
7543654	7543633	How to display messagebox only one time in a loop	try {\n    using (var sr = File.OpenText("test.txt")) {\n        bool flag = true;\n        string newone = 20110501;//date\n        string line;\n        while ((line = sr.ReadLine()) != null) {\n            if (flag) {\n                MessageBox.Show("Buy : " + line);\n                //Its Displaying more than 50 times i want to displayit only\n                //onetime and should dispose for the next Time\n            }\n            flag = false;\n        }\n    }\n} catch { }	0
22648000	22647913	How to define format for output	sb1.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", \n                 c[resultwithindex.Index], resultwithindex.result);	0
1243848	1243717	how to update the value stored in Dictionary in C#?	Dictionary<string, int> list = new Dictionary<string, int>();\nlist["test"] = 1;\nlist["test"] += 1;\nConsole.WriteLine (list["test"]); // will print 2	0
13363679	13362470	Enabling support for multiple user logins with different themes?	protected void Page_PreInit()  {\nif (Roles.IsUserInRole("admin"))\n    {\n        Page.Theme = Profile.Blue;\n    }\n    else if (Roles.IsUserInRole("operations"))\n    {\n        Page.Theme = Profile.Red;\n    }  }	0
10698081	10697940	Application Links item in Open/SaveFileDialog in C#	FileDialog.CustomPlaces	0
5124618	5103087	FFT on WP7 shows two mirrors	for (int i = 0; i < buffer.Length; i+= sizeof(short))\n            {\n                samples[i] = ReadSample(buffer, i);\n            }	0
2123189	2122935	TryFindByPrimaryKey in Castle ActiveRecord	ActiveRecordMediator<T>.FindByPrimaryKey(id, false);	0
27765175	27731262	NHibernate How to add extensions manually?	var query1 = " select * from mySQLView";\n\nvar result1 = this.session.CreateSQLQuery(query1).SetResultTransformer(NhTransformers.ExpandoObject)\n                .List<dynamic>();\n\nforeach (var obj in result1)\n{\n   // some stuff...\n}	0
6363095	6362517	How to disable drag/drop when a dialog box is open	private void MyDragDrop(object sender, DragEventArgs e) {\n    if (CanFocus)\n        MessageBox.Show("dropped");\n}\nprivate void MyDragEnter(object sender, DragEventArgs e) {\n    if (CanFocus)\n        e.Effect = DragDropEffects.Copy;\n    else\n        e.Effect = DragDropEffects.None;\n}	0
15917884	11876405	Printing a PDF in C#	Process process = new Process();\n\nprocess.StartInfo.FileName = pathToPdfOrDocFile; \nprocess.UseShellExecute = true;\nprocess.StartInfo.Verb = "printto";\nprocess.StartInfo.Arguments = "\"" + printerName + "\""; \nprocess.Start();\n\nprocess.WaitForInputIdle();\nprocess.Kill();	0
28244043	28243871	XML reader, export data into a file C# Visual Studio 2012	using (XmlWriter writer = XmlWriter.Create("GiveNameToYourFile.xml"))\n{\n    writer.WriteStartDocument();\n    writer.WriteStartElement("GiveTagNameToYourDocument");\n\n    foreach (proxy.ProjectData som in nc)\n    {\n    writer.WriteStartElement("GiveNameToYourElement");\n\n    writer.WriteElementString("ProjectTitle", som.ProjectTitle);\n    writer.WriteElementString("ProjectID", som.ProjectID);\n    writer.WriteElementString("PublishStatus", som.PublishStatus);\n\n    writer.WriteEndElement();\n    }\n\n    writer.WriteEndElement();\n    writer.WriteEndDocument();\n}	0
21852482	21852411	How to convert the following code to LINQ format?	var items = projectData.TestTypes\n                       .OrderBy(it => it.TestName)\n                       .Select(testType=> new TestList\n                       {\n                           benchTestTypeName = testType.TestName,\n                           DataProvider = this.projectDataService.CurrentDataProvider,\n                           ProjectData = projectData\n                       });\n\nforeach(var item in items)\n   tabItems.Add(new TabItem { Header = item.benchTestTypeName, Content = item });	0
12607178	12607146	Method parameter array default value	public void SomeMethod()\n{\n    SomeMethod(new[] {"value 1", "value 2", "value 3"});\n}\n\n\npublic void SomeMethod(String[] arrayString)\n{\n    foreach(someString in arrayString)\n    {\n        Debug.WriteLine(someString);\n    }\n}	0
14191863	14191830	Issue with string in c#?	string jsVersion = string.format("function getContent() {var content = '{0}'return content; }",documentString);	0
9331057	9331014	what is the most performant way to delete elements from a List<T> in c# while doing a foreach?	for (var i = foo.Count-1 ; i >= 0 ; i--) {\n    if (MustBeRemoved(foo[i])) {\n        foo.RemoveAt(i);\n    }\n}	0
13065239	13062559	Store image url in xml and include them in ASPX page C#	XElement xelement = XElement.Load("path to xml");\nIEnumerable<XElement> images = xelement.Elements();    \n\nforeach (var ad in images)\n{\n   string imagePath = ad.Element("ImageUrl").Value;\n   string imageAlt = ad.Element("AlternateText").Value;\n}	0
9026966	7101854	How to get the title of a video's metadata	public static Dictionary<string, string> GetDetails(this FileInfo fi)\n    {\n        Dictionary<string, string> ret = new Dictionary<string, string>();\n        Shell shl = new Shell();\n        Folder folder = shl.NameSpace(fi.DirectoryName);\n        FolderItem item = folder.ParseName(fi.Name);\n\n        for (int i = 0; i < 150; i++)\n        {\n            string dtlDesc = folder.GetDetailsOf(null, i);\n            string dtlVal = folder.GetDetailsOf(item, i);\n\n            if (dtlVal == null || dtlVal == "")\n                continue;\n\n            ret.Add(dtlDesc, dtlVal);\n        }\n        return ret;\n    }	0
4563007	4562086	How can I export an array from Dynamics AX 2009 via c#?	currentTable = new SysDictTable(tablenum(ledgerJournalTable));\n\nfor(i = 0;i<=currentTable.fieldCntWithoutSys();i++)\n{\n    currentField = new SysDictField(currentTable.id(), currentTable.fieldCnt2Id(i));\n\n    if(currentField.arraySize() > 1)\n    {\n        //your code\n    }\n}	0
28208796	28208587	Extracting Formula from String	Regex regex = new Regex(@"([A-Z])\w+");\n\n        List<string> matchedStrings = new List<string>();\n        foreach (Match match in regex.Matches("(FB1+AB1)/100"))\n        {\n            matchedStrings.Add(match.Value);\n        }	0
3454206	3449687	Crystal 2008 - Supplying a default value for a parameter with static values	if {?StartDate}="Today" then CurrentDate	0
30127488	30106234	How to view the dynamically loaded code of an assembly?	byte[] bytesFromWCF = ... // here I receive the bytes via WCF.\nSystem.IO.File.WriteAllBytes("mylib.dll", bytesFromWCF);\nvar myAsm = Assembly.Load( bytesFromWCF );\n...	0
10520251	10520184	Entity Framework add first row to database from a List?	foreach (StockItem item in StockList)\n{\n    Master master = new Master();\n    master.VoucherNo = BillNo;\n    master.Voucher = "Sales";\n    master.StockName = item.StockName;\n    master.Quantity = item.Quantity;\n    master.Unit = item.Unit;\n    master.Price = item.UnitPrice;\n    master.Amount = item.Amount;\n    dbContext.AddToMasters(master);\n    dbContext.SaveChanges();\n}	0
20029612	20028623	Use Table-Per-Type for all EF context classes with Fluent API	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        base.OnModelCreating(modelBuilder);    \n        modelBuilder.Types().Configure(t =>t.ToTable(t.ClrType.Name));\n    }	0
22089109	22077651	Passing value from one class to another using property	class Program\n{\n    static void Main(string[] args)\n    {\n        Class2 instanceOfClass2 = new Class2();\n\n\n    }\n}\n\nclass Class1\n{\n    public IList<string> MyList { get; set; }\n\n    internal Class1()\n    {\n        MyList = new List<string>();\n        MyList.Add("123");\n    }\n}\n\nclass Class2\n{\n    public Class2()\n    {\n        Class1 c = new Class1();\n        var a = c.MyList;\n    }\n}	0
3420126	3420043	How do you square an uploaded photo without padding with white space, in C#?	public Bitmap CreateThumbnail(Bitmap RawImage)\n    {\n        int width = RawImage.Width;\n        int height = RawImage.Height;\n\n        Size ThumbnailDimensions = new Size();\n        ThumbnailDimensions.Width = 100;\n        ThumbnailDimensions.Height = 100;\n\n        Rectangle cropArea = new Rectangle();\n        if (width > height)\n        {               \n            cropArea.Width = height;\n            cropArea.Height = height;\n            cropArea.X = 0;\n            cropArea.Y = 0;                \n        }\n        else if (width < height)\n        {\n            cropArea.Width = width;\n            cropArea.Height = width;\n            cropArea.X = 0;\n            cropArea.Y = 0;\n        }\n        if(width != height) Bitmap thumbnail = CropImage(RawImage, cropArea);\n\n        thumbnail = ResizeImage(thumbnail, ThumbnailDimensions);\n        return thumbnail;\n    }	0
14450320	14449407	Writing a TEXT file using C#	private void button1_Click(object sender, EventArgs e)\n    {\n        using (var sfd = new SaveFileDialog())\n        {\n            sfd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";\n            sfd.FilterIndex = 2;\n\n            if (sfd.ShowDialog() == DialogResult.OK)\n            {\n                File.WriteAllText(sfd.FileName, textBox_ListDestination.Text);\n            }     \n        }\n    }	0
25794205	25779630	Saving data into multiple collections in DocumentDb	class TeamMember\n{\n   int id {get;set;}\n   string position {get;set;}\n}	0
17875205	17875045	How we put customize Date Format in a label in form application?	while (dr.Read()) \n{ \n  var date = dr["accountPeriodTo"];\n  lblToDate.Text = date.ToString("dd/MM/yyyy");\n}	0
32979556	32974285	How to place an image and a paragraph on PDF document header?	var para = section.Headers.Primary.AddParagraph();\nvar image = para.AddImage("image.jpg");\npara.AddLineBreak();\npara.AddText("title");	0
6749263	6749078	executing a stored proc with datareader instead of dataset	While (dataReader.Read())\n{\n        decExampleColumn1 = Convert.ToDecimal(dataReader["column1"]);\n        decExampleColumn2 = Convert.ToDecimal(dataReader["column2"]);\n}	0
13033655	13033606	Converting string with color name to color"id"	Color.FromName("Blue")	0
9594131	9593892	How to set variable in main Window from modal dialog	public partial class DB_conn_win : Window \n{ \n\n    private void ask_DB_Click(object sender, RoutedEventArgs e) \n    { \n        this.Query = textBox1.Text(); \n    } \n    public string Query;\n..... \n} \n\n\n\npublic partial class MainWindow : Window \n{ \n\n  string DB_query = DB_conn_win.query; \n\n  public SomeButton_Click(object sender, RoutedEventArgs e)\n  {\n     var dialog = new DB_conn_win();\n     if (dialog.ShowDialog() == true)\n     {\n       this.DB_query = dialog.Query;\n     }\n  }	0
23010824	23010649	ASP.NET Link from Mobile Redirect to Desktop Version	if(Request.Browser["IsMobileDevice"] && !String.IsNullOrEmpty(Request.QueryString["OverrideMobileCheck"]){\n    Response.Redirect("/mobile/index.html");\n}	0
17709580	17708845	Quickly redraw tooltip like MPC-HC's seekbar	How to Implement Tracking Tooltips	0
2111381	2111359	textbox text as html for an email in c#	var textBoxText = tbDeliver.Text.Replace(Environment.NewLine, "<br>");	0
22772162	22771768	Exception object as parameter in dll file	System.Object	0
23193425	23193382	EntityType: EntitySet 'Orderlines' is based on type 'Orderline' that has no keys defined	public class Orderline\n{\n    [Key]\n    public int OrderlineId {get; set;}\n\n    [ForeignKey("PizzaId")]\n    public Pizza PizzaId {get; set;}\n    public decimal OrderlinePrice {get; set;}\n}	0
32165467	32165450	Insert string after 4 results	var index = 0;\nwhile(myReader.Read())\n{\n    Console.WriteLine("- " + myReader["name"].ToString());\n    if (++index == 4) {\n        Console.WriteLine("Test value");\n    } \n}	0
20314647	20305336	SlimDX : How to draw multiple objects?	//initializing...\nvar vbb1 = new VertexBufferBinding[] { new VertexBufferBinding(vertexBuffer, 12, 0) };\nvar vbb2 = new VertexBufferBinding[] { new VertexBufferBinding(vertexBuffer2, 12, 0) };\n\n//in the render loop\ncontext.InputAssembler.SetVertexBuffers(0, vbb1);\ncontext.Draw(3, 0);\n\ncontext.InputAssembler.SetVertexBuffers(0, vbb2);\ncontext.Draw(3, 0);	0
18691690	18681630	Radgrid get cell value when in edit mode	protected void rdg_ItemDataBound(object sender, GridItemEventArgs e)\n    {\n        if (e.Item is GridEditableItem && e.Item.IsInEditMode)\n        {\n            GridEditableItem editedItem = e.Item as GridEditableItem;\n            string str = editedItem.GetDataKeyValue("TransazioneID").ToString();\n            TextBox1.Text = str ;\n        }\n    }	0
33031181	33031153	How to get previous day name in c#	string yesterdayname = System.DateTime.Now.AddDays(-1).DayOfWeek.ToString();	0
8221181	8220830	Check if DateTime in specific range	bool IsInDaylightSavingsTime(DateTime date)\n    {\n        // get second sunday in march\n        DateTime _tempDateMar = new DateTime(date.Year, 3, 1);\n        int secondSunDayInMar = (8 - (int)_tempDateMar.DayOfWeek) + 7;\n        _tempDateMar = new DateTime(date.Year, 3, secondSunDayInMar, 2, 0, 0);\n\n        //get first sunday in november\n        DateTime _tempDateNov = new DateTime(date.Year, 11, 1);\n        int firstSunDayInNov = (8 - (int)_tempDateNov.DayOfWeek);\n        _tempDateNov = new DateTime(date.Year, 11, firstSunDayInNov, 2, 0, 0);\n\n        return (date >= _tempDateMar && date <= _tempDateNov);\n    }	0
13405450	13388327	Constant Contact - Update Contact	Contact thisContact = Utility.GetContactDetailsById(authenticationData, myContact[0].Id);\n           // //Add Lists\n            ContactOptInList newList = new ContactOptInList();\n            //thisContact.OptInSource = ContactOptSource.ActionByCustomer;\n            newList.ContactList = new ContactList("39"); //Contact list you want to add them to\n            newList.ContactList = new ContactList("10"); //Contact list you want to add them to\n            thisContact.ContactLists.Add(newList);\n\n            //Update contact\n            Utility.UpdateContactFullForm(authenticationData, thisContact);	0
8574232	8574196	Parameterised query expects a parameter (Not accepting Null string)	db.Execute("Update User SET Name = @0 , Address1 = @1 , Address2 = @2 , Address3 = @3, Address4 = @4 , Postcode = @5 , Title = @6, " +\n                        " Surname = @7 , Forename = @8 , Tel = @9, Fax = @10 , Mobile = @11 , Email = @12  WHERE UserNo = @13",\n                        (Name==null)?"":Name, (Address1==null)?"":Address1, ...);	0
30797148	30796776	Get UITestControl from UITechnologyElement	//When you have the UITechnologyElement, you can create a WinControl from it by using this methode\nWinControl result = (WinControl)UITestControlFactory.FromNativeElement(control.NativeElement, "MSAA");\n//Now you have the WinControl so you can convert it into a special Type, eg. WinButton\nWinButton wb = (WinButton)result;\n//And invoke the Mouse.Click methode\nMouse.Click(wb, MouseButtons.Left);	0
21484432	21040828	Stucture Map using Configuration Manager in ObjectFactory	[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.UI.App_Start.StructuremapMvc), "Start")]\nnamespace Web.UI.App_Start	0
20200	20185	Is there a way to make a constructor only visible to a parent class in C#?	public abstract class AbstractClass\n{\n    public static AbstractClass MakeAbstractClass(string args)\n    {\n        if (args == "a")\n            return new ConcreteClassA();\n        if (args == "b")\n            return new ConcreteClassB();\n    }\n\n    private class ConcreteClassA : AbstractClass\n    {\n    }\n\n    private class ConcreteClassB : AbstractClass\n    {\n    }\n}	0
29539066	29538788	How to add a condition to existing lambda expression?	public void DoSearch(MyViewModel vm)\n{\n    Expression<Func<Customer, bool>> myFilter = x => yourCurrentFilterLogic;\n    var combined = myFilter.And(x => x.GroupId == vm.GroupId);   //PredicateBuilder extension method\n    var customers = Get(combined);\n}\n\npublic Customer Get(Expression<Func<Customer, bool>> where)\n{\n    return customerRepository.Get(where);\n}	0
1121489	1121441	AddEventHandler using reflection	class Program\n{\n    static void Main(string[] args)\n    {\n        var p = new Program();\n        var eventInfo = p.GetType().GetEvent("TestEvent");\n        var methodInfo = p.GetType().GetMethod("TestMethod");\n        Delegate handler = \n             Delegate.CreateDelegate(eventInfo.EventHandlerType, \n                                     p, \n                                     methodInfo);\n        eventInfo.AddEventHandler(p, handler);\n\n        p.Test();\n    }\n\n    public event Func<string> TestEvent;\n\n    public string TestMethod()\n    {\n        return "Hello World";\n    }\n\n    public void Test()\n    {\n        if (TestEvent != null)\n        {\n            Console.WriteLine(TestEvent());\n        }\n    }\n}	0
7194956	7194851	Load local HTML file in a C# WebBrowser	string curDir = Directory.GetCurrentDirectory();\nthis.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));	0
4677003	4676816	WPF download image bytes from Blob Storage	while (stream.Read(buffer, 0, buffer.Length) > 0)\n                img.ImageBytes = buffer;	0
27619256	27618633	Usercontrol that dynamically generates a list of controls on postback	protected override void OnInit(EventArgs e)\n        {\n\n               List<Button> listButtons ;\n\n            base.OnInit(e);\n        }  \n\n\n\n void RefreshPlaceholder()\n    {\n        listButtons = new List<Button>();\n        PHList.Controls.Clear();\n        foreach(var x in SelectedTags) \n        {\n         Button b = new Button();\n         b.Text=x;\n         listButtons.add(b);\n\n\n\n       // generate a label and the "X" button, wiring it with a lambda\n        }\n    }	0
19688829	19688648	enum + IsDefined	public enum SomeTypes {\n    SomeType1 = 1,\n    SomeType2 = 2,\n    SomeType3 = 3\n}\npublic class SomeClass\n{\n    public SomeTypes SomeType { get; set; }\n\n    bool validEnum() {\n        return System.Enum.IsDefined(typeof(SomeTypes), this.SomeType);\n    }\n}	0
30671573	30671132	How to get the first enum value irrespective of the sign?	var min = ((GamePeriod[])Enum.GetValues(typeof(GamePeriod))).Min();	0
14772902	14749750	insert xml node without XmlDomument.Load() in c#+XML	string rootEndTag = "</AppXmlLogWritter>";\n            int rootEndTagLength = Encoding.UTF8.GetBytes(rootEndTag).Length;\n            try\n            {\n                objMutex.WaitOne();\n                if (!File.Exists(_logFilePath))\n                {\n                    File.WriteAllText(_logFilePath, "<?xml version='1.0' encoding='utf-8' standalone='yes'?><AppXmlLogWritter></AppXmlLogWritter>");\n                }\n\n                var fileStream = File.Open(_logFilePath, FileMode.Open);\n                fileStream.Position = fileStream.Length - rootEndTagLength;\n\n                var objStreamWriter = new StreamWriter(fileStream);\n                objStreamWriter.WriteLine(newelement.OuterXml);\n                objStreamWriter.Write(rootEndTag);\n                objStreamWriter.Close();\n                fileStream.Close();\n            }	0
8269551	6256392	WPF Minimize on Taskbar Click	ResizeMode="CanMinimize"	0
4878540	4878502	How to fill an inherited array in C#?	public abstract class Dice\n{\n    private DieFace[] faces;\n\n    protected abstract DieFace[] GetDieFaces();\n    public void FillDieFaces()\n    {\n        faces = GetDieFaces();\n    }\n}\n\npublic class AnimalDice : Dice\n{\n     protected override DieFace[] GetDieFaces()\n     {\n         return new DieFace[] { DieFace.Panda, DieFace.Unicorn };\n     }\n}	0
13377053	13377013	Find index in a long[] array	int index = Array.IndexOf(array, long.Parse("45324"));	0
6818984	6818830	How can I better control behavior on multiple controls at once?	this.Controls.Cast<Control>()\n        .Where(ctl => ctl is TextBox).Cast<TextBox>().ToList()\n        .ForEach(e => e.ReadOnly = true);\n\n    this.Controls.Cast<Control>()\n        .Where(ctl => ctl is DataGridView).Cast<DataGridView>().ToList()\n        .ForEach(e => e.ReadOnly = true);	0
22267204	22259864	RegExp Get substring between tabs and include a special char	(?s)\t(?=[^\t]*[""]+)[^\t]*[\t]{1}	0
3013587	3013573	How to reference dynamically created checkedlistbox items in C#	bool checked = CheckBoxCheckedListBox1.GetItemChecked(i)	0
3839946	3839895	How to check a type of item in ListBox	foreach (var _item in listPhotoAlbum.Items)\n{\n    var radioButton = _item as RadioButton;\n\n    if (radioButton != null)\n    {\n        //Do with radioButton\n        continue;\n    }\n\n    var button = _item as Button;\n\n    if (button != null)\n    {\n        //Do with button\n        continue;\n    }\n}	0
31138734	31136173	How to select a row's text from a UITableView Xamarin.ios c#	public override void RowSelected (UITableView tableView, NSIndexPath indexPath)\n{\n     new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();\n     tableView.DeselectRow (indexPath, true); // iOS convention is to remove the highlight\n}	0
8005284	8003589	Extracting double/decimal number from string?	public bool TryParseDouble(string input, out double value){\n  if(string.IsNullorWhiteSpace(input)) return false;\n  const string Numbers = "0123456789.";\n  var numberBuilder = new StringBuilder();\n  foreach(char c in input) {\n    if(Numbers.IndexOf(c) > -1)\n      numberBuilder.Append(c);\n  }\n  return double.TryParse(numberBuilder.ToString(), out value);\n}	0
30759748	30759447	Excel how to fit text in cell, based on cell witdh	worksheet.Range("K1:K100").WrapText = True;	0
19924561	19924457	concat field values of an array of objects	string.Join(",", this._previousDayPrices.Take(2).Select(d => string.Format("{0}-{1}-{2}-{3}", d.Price, d.Date,d.EuroExchangeRateDate, d.EuroExchangeRate)).ToArray());	0
3635130	3634956	User can press and hold only one keyboard button at a time	private Keys CurrentKey = Keys.None;\n\n    private void Form1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (CurrentKey == Keys.None)\n        {\n            CurrentKey = e.KeyData;\n            // TODO: put your key trigger here\n        }\n        else\n        {\n            e.SuppressKeyPress = true;\n        }\n\n    }\n\n    private void Form1_KeyUp(object sender, KeyEventArgs e)\n    {\n        if (e.KeyData == CurrentKey)\n        {\n            // TODO: put you key end trigger here\n            CurrentKey = Keys.None;\n        }\n        else\n        {\n            e.SuppressKeyPress = true;\n        }\n\n    }	0
2585437	2585413	How to filter a string using c# using the logic of LIKE in SQL?	if(product_name.Contains("BONUS NAME"))\n    // do stuff..	0
6627511	6627451	Use c# Null-Coalescing Operator with an int	UserProfile.BoardID = (dr["BoardID"] is DbNull) ? 0 : Convert.ToInt32(dr["BoardID"]);	0
24659179	24658771	ViewModel subscribing to Model's PropertyChanged event for a specific property	public class ViewModel : INotifyPropertyChanged\n{\n    ...\n\n    public Model MyModel { get; set; }\n\n    public void methodToBeCalledWhenPropertyIsSet() { }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    public ViewModel()\n    {\n        // MyModel would need to be set in this example.\n        MyModel.PropertyChanged += Model_PropertyChanged;\n    }\n\n    private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)\n    {\n        if(e.PropertyName == "Property")\n        {\n             methodToBeCalledWhenPropertyIsSet();\n        }\n    }\n}	0
2534587	2534533	C# object creation from datatable	List<Member> members = new List<Member>();\nusing (SqlConnection connection = new SqlConnection(connectionString))\n{\n    connection.Open();\n\n    using (SqlCommand command = new SqlCommand(queryString, connection))\n    {\n        using (SqlDataReader reader = command.ExecuteReader())\n        {\n            while (reader.Read())\n            {\n                Member member = new Member();\n                member.UserName = reader.GetString(0);\n                member.FirstName = reader.GetString(1);\n                member.LastName = reader.GetString(2);\n                members.Add(member);\n            }\n        }\n    }\n}\n\nforeach(Member member in members)\n{\n    // do something\n}	0
30696443	30695349	Pirate Game in Maths - Solve it with C#	using System;\nusing System.Numerics;\n\nnamespace PirateCoins\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int n = int.Parse(Console.ReadLine());\n            Console.WriteLine(GetTreasure(n));\n        }\n        static BigInteger GetTreasure(int n)\n        {\n            BigInteger result = BigInteger.Pow(n, n + 1) - (n - 1);\n            return result;\n        }\n    }\n}	0
10813933	10797997	How to build group-by dynamically on a list of dictionaries	private void GetValuesGroupedBy(List<Dictionary<string, object>> list, List<string> groupbyNames, List<string> summableNames)\n    {\n        // build the groupby string\n        StringBuilder groupBySB = new StringBuilder();\n        groupBySB.Append("new ( ");\n        bool useComma = false;\n        foreach (var name in groupbyNames)\n        {\n            if (useComma)\n                groupBySB.Append(", ");\n            else\n                useComma = true;\n\n            groupBySB.Append("it[\"");\n            groupBySB.Append(name);\n            groupBySB.Append("\"]");\n            groupBySB.Append(" as ");\n            groupBySB.Append(name);\n        }\n        groupBySB.Append(" )");\n\n        var groupby = list.GroupBy(groupBySB.ToString(), "it");\n    }	0
12655291	12654285	DataTable to Dictionary<string, Dictionary<string,string>>	Dictionary<string, Dictionary<string, string>> result = table.AsEnumerable().ToDictionary(row => row["colA"].ToString(),\n                                                                                          row => new string[] { "colB", "colC" }.ToDictionary(col => col, col => row[col].ToString()));	0
32115284	32115160	Pass null as default value with DropdownFor	listTeam.Add(new SelectListItem() {Text="None", Value=null});	0
20948631	20180562	MVC5 Null Reference with facebook login	[HttpPost]\n[AllowAnonymous]\n[ValidateAntiForgeryToken]\npublic ActionResult ExternalLogin(string provider, string returnUrl)\n{\n    ControllerContext.HttpContext.Session.RemoveAll();\n\n    // Request a redirect to the external login provider\n    return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));\n}	0
15100263	15099892	How to search in a dictionary?	Dictionary<int, string> dict = new Dictionary<int, string>();\n        Dictionary<int, int> temp = new Dictionary<int, int>();\n\n        dict.Add(123, "");\n        dict.Add(124, ""); //and so on\n\n        int[] keys = dict.Keys.ToArray();\n        for (int i = 0; i < dict.Count; i++)\n        {\n            if (dict[keys[i]] == "")\n            {\n                temp.Add(keys[i],0);\n                dict[keys[i]] = "Moved";\n            }\n        }	0
252015	251987	How do I access properties from global.asax in some other page's code behind	((Global)this.Context.ApplicationInstance).Roles	0
16771992	16771834	Can't dynamically add new literal to ASP.NET Panel Control	this.contentViewWebdata.Controls.Add(Page.ParseControl("br"));	0
21058001	21057637	Convert 2 strings into char array and compare them as characters	string valueX = "assdf";\nstring valueY = "assdf";\n\nif (valueX.Length == valueY.Length)\n{\n    Console.WriteLine("Ok, Array is same lenght ... lets check the content");\n\n    for (int i = 0; i < valueX.Length; i++)\n    {\n        if (valueX[i] != valueY[i])\n        {\n            Console.WriteLine("Not the same array!");\n        }\n    }\n}\nelse\n{\n    Console.WriteLine("Array is not equal in lenght");\n}	0
28380181	28377365	Open Buttons ContextMenu on Left Click	private void BtnMessageChannel_Click(object sender, RoutedEventArgs e)\n    {\n        if (!BtnMessageChannel.ContextMenu.IsOpen)\n        {\n            e.Handled = true;\n\n            var mouseRightClickEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Right)\n            {\n                RoutedEvent = Mouse.MouseUpEvent,\n                Source = sender,\n            };\n            InputManager.Current.ProcessInput(mouseRightClickEvent);\n        }\n    }	0
5080249	5080152	find week ending date of last completed week	DateTime StartOfWeek = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);\nDateTime EndOfLastWeek = StartOfWeek.AddDays(-1);	0
21061004	21054247	Using abstract base class properties with IronPython isn't as expected	self.MessageLog = "TEST VALUE"\nprint self.MessageLog	0
11543009	6600254	Get Table Name From DbEntityEntry (Code-First)	private string GetTableName(DbEntityEntry ent)\n        {\n            ObjectContext objectContext = ((IObjectContextAdapter) this).ObjectContext;\n            Type entityType = ent.Entity.GetType();\n\n            if (entityType.BaseType != null && entityType.Namespace == "System.Data.Entity.DynamicProxies")\n                entityType = entityType.BaseType;\n\n            string entityTypeName = entityType.Name;\n\n            EntityContainer container =\n                objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);\n            string entitySetName = (from meta in container.BaseEntitySets\n                                    where meta.ElementType.Name == entityTypeName\n                                    select meta.Name).First();\n            return entitySetName;\n        }	0
11293862	11283688	How can i create a list of elements?	List<AnimationElement> HitElements;\nprivate Preparationanimation Hit4;\n\n public override void LoadContent()\n {\n        HitElements = new List<AnimationElement>();\n        Hit4 = new Preparationanimation(SpriteSheetElements1, new Color(255, 255, 255, 128), 1f, false)\n }\n\n if (IntersectPixels(Player1.HitboxAtt, Player1.playerTextureData, Player2.Hitbox, Player2.playerTextureData))\n {\n     foreach (AnimationElement a in HitElements)\n     {\n       a.PlayAnimation(Hit4, content);\n     }\n }\n\n public override void Draw(GameTime gameTime)\n {\n     foreach (AnimationElement a in HitElements)\n     {\n         a.Draw(spriteBatch, gameTime, positionElement, false, true);\n     }\n\n }	0
21109348	21109126	Conversion from System.Array to List<string> using LINQ, need to keep empty values	xmlData.AddRange(myvals.Cast<object>().Select(O => O == null ? \n                                                      string.Empty : \n                                                      O.ToString()).ToList());	0
21054798	21054666	Generics double interface	public class CarroMontadora<T1, T2>\n    where T2 : IFoo\n    where T1 : ILang<T2>\n{\n}	0
33399995	33399307	How do I annotate my XML to remove the parent node of an array in C#?	// You will have to use System.Xml.Linq library\npublic class Phone // the only class I have\n{\n    public string PhoneType { get; set; }\n    public string Number { get; set; }\n}\n\npublic XElement CreateTelecomNode(List<Phone> phones)\n{\n    var telecom = new XElement("Telecom");\n    foreach (var item in phones)\n    {\n        telecom.Add(new XElement("TeleType", item.PhoneType));\n        telecom.Add(new XElement("TeleNumber", item.Number));\n    }\n    return telecom;\n}	0
10693034	10609162	c# string padded now want it short	devicename = devicename.trim('\0');	0
8060331	8059872	DataTable Array onto a Table Control ASP.NET C#	StringBuilder html = new StringBuilder();\n\nforeach(DataTable aTable in tableList)\n{\n   html.Append("<table>");\n\n   foreach(DataRow row in aTable.rows)\n   {\n      html.Append("<tr>");\n\n      foreach(string cell in row.Items)\n      {\n         html.Append("<td>");\n\n         if (cell == null)\n            html.Append("&nbsp;");\n         else\n            html.Append(cell);\n\n         html.Append("</td>");\n      }\n\n      html.Append("</tr>");\n   }\n\n   html.Append("</table>");\n}	0
14700834	14700161	how to provide links to the words which are same as in wikipedia	[[Programming]]	0
676525	676518	C#: In the keydown event of a textbox, how do you detect currently pressed modifiers + keys?	private void txtShortcut_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Alt || e.Control || e.Shift))\n        {\n            lbLogger.Items.Add(e.ToString() + " + " +\n                "show non-modifier key being pressed here");\n        }\n    }	0
25782238	25769127	How Can I Generate Nhibernate GROUP BY without SELECT the property	var subquery = Session.QueryOver<Table>(() => x)\n                    .SelectList(list => list\n                    .SelectMax(() => x.Date)\n                    .SelectGroup(() => x.Sub.Id))\n                    .List<object[]>().Select(p => p[0]).ToArray();\n\n\n                var CorrespondingIds = Session.QueryOver<Table>(() => x)\n                    .WhereRestrictionOn(() => x.Date).IsIn(subquery)\n                    .Select(p => p.Id).List<int>().ToArray();\n\n                var result = Session.QueryOver<Table>(() => x).WhereRestrictionOn(() => x.Id).IsIn(CorrespondingIds).Left.JoinQueryOver(p => p.Sub).List();	0
8556435	8554554	GridView button control in visual web developer 2010	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)     \n{\n\n    if (e.Row.RowType == DataControlRowType.DataRow)         \n    {\n         // Get The button from which ever cell the button is in\n         Button1.Click += new EventHandler(Button1_Click);\n\n\n    }\n\n}\n\nvoid Button1_Click(object sender, EventArgs e)\n{\n\n}	0
1516923	1516911	How to constrain parameter to Built-In Types	switch (Type.GetTypeCode(type))\n{\n    case TypeCode.Boolean:\n    case TypeCode.Byte:\n    case TypeCode.Char:\n    case TypeCode.DBNull:\n    case TypeCode.DateTime:\n    case TypeCode.Decimal:\n    case TypeCode.Double:\n    case TypeCode.Empty:\n    case TypeCode.Int16:\n    case TypeCode.Int32:\n    case TypeCode.Int64:\n    case TypeCode.SByte:\n    case TypeCode.Single:\n    case TypeCode.String:\n    case TypeCode.UInt16:\n    case TypeCode.UInt32:\n    case TypeCode.UInt64:\n    break;\n    default:\n    if (type.GetType() != typeof(object))\n    {\n    throw new ArgumentException("invalid type.", "type");\n    }\n    break;\n}	0
21657762	21655224	Adding rectangles to a list via a for loop and then drawing them to the screen	for(int i = 0; i <= 10; i++)\n{\n // your code here\n}	0
4479362	4479319	Loading data from DB asynchronously in win forms	// This method can be called on Form_Load, Button_Click, etc.\nprivate void LoadData()\n{\n    // Start a thread to load data asynchronously.\n    Thread loadDataThread = new Thread(LoadDataAsync);\n    loadDataThread.Start();\n}\n\n// This method is called asynchronously\nprivate void LoadDataAsync()\n{\n    DataSet ds = new DataSet();\n\n    // ... get data from connection\n\n    // Since this method is executed from another thread than the main thread (AKA UI thread),\n    // Any logic that tried to manipulate UI from this thread, must go into BeginInvoke() call.\n    // By using BeginInvoke() we state that this code needs to be executed on UI thread.\n\n    // Check if this code is executed on some other thread than UI thread\n    if (InvokeRequired) // In this example, this will return `true`.\n    {\n        BeginInvoke(new Action(() =>\n        {\n            PopulateUI(ds);\n        }));\n    }\n}\n\nprivate void PopulateUI(DataSet ds)\n{\n    // Populate UI Controls with data from DataSet ds.\n}	0
10235995	10235889	How to store textboxes into an array during runtime	List<TextBox> txtbxList = new List<TextBox>();\n\nprivate void txt_TextChanged(object sender, TextChangedEventArgs e)\n    {\n        TextBox t;\n        t = (TextBox)sender;\n        txtbxList.Add(t);\n    }	0
7342107	7321336	How to use mvc-mini-profiler with mysql connection?	var sqlCom = profiledConn.CreateCommand(); \nsqlCom.CommandText = commandText;	0
3084478	3084018	WPF Datagrid not refreshing properly with MethodParameters	private void filter_btn_Click(object sender, RoutedEventArgs e)\n{\n    ObjectDataProvider sitelist_dataobj = this.FindResource("siteListContains") as ObjectDataProvider;\n    using (sitelist_dataobj.DeferRefresh())\n    {\n        sitelist_dataobj.MethodParameters[0] = sitestr.Text.ToString();\n        sitelist_dataobj.MethodParameters[1] = from_timePicker.SelectedTime;\n        sitelist_dataobj.MethodParameters[2] = from_datepicker.SelectedDate;\n        sitelist_dataobj.MethodParameters[3] = to_timePicker.SelectedTime;\n        sitelist_dataobj.MethodParameters[4] = to_datepicker.SelectedDate;\n    }\n}	0
32546302	32546226	Inserting items in listview to database C#	foreach (ListViewItem l in Listview1.Items)\n{\n  string cd = "Insert Into ProductSold(BillNo,DishName,DishRate,Quantity,TotalAmount) VALUES (@d1,@d2,@d3,@d4,@d5)";\n                cmd = new OleDbCommand(cd);\n                cmd.Connection = con;\n                cmd.Parameters.AddWithValue("d1", txtBillNo.Text);\n                cmd.Parameters.AddWithValue("d2", l.SubItems[1].Text);\n                cmd.Parameters.AddWithValue("d3", l.SubItems[2].Text);\n                cmd.Parameters.AddWithValue("d4", l.SubItems[3].Text);\n                cmd.Parameters.AddWithValue("d5", l.SubItems[4].Text);\n                cmd.ExecuteNonQuery();\n\n}	0
8235994	8235639	Time Delay for operations using WinForm App in c#	var thread = new System.Threading.Thread(p =>\n    {\n        lock (YourTabControl)\n        {\n            Action action = () =>\n            {\n                addTab(url);\n            };\n            this.Invoke(action);\n            if(url.Host == "google")\n                System.Threading.Thread.Sleep(5000);\n        }\n    });\n    thread.Start();	0
17253525	17253495	How to get the current size of an image within a picturebox	pictureBox1.ClientSize	0
76085	75978	Accessing App.config in a location different from the binary	using System.Configuration;    \n\nConfiguration config =\nConfigurationManager.OpenExeConfiguration("C:\Test.exe");	0
11559091	11559042	how to convert value of a string to type	string typeName = "System.Int32"; // Sadly this won't work with just "int"\nType actualType = Type.GetType(typeName);	0
30701751	30680969	Error : Winform Icon Hiding from Taskbar on maximizing Screen	this.TopMost = true;\n this.WindowState = FormWindowState.Maximized;	0
25326846	25320352	Redis object serialization backwards compatibility	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);	0
18689412	18689313	displays search items even if there is !=	if (!string.IsNullOrEmpty(SourceTextBox.Text))\n{\n    /* do stuff */\n}	0
10387421	10381867	Programmatically creating a native Outlook Distribution List	set Session = CreateObject("Redemption.RDOSession")\n  set DL = Session.CreateMessageFromMsgFile("c:\temp\TestDL.Msg", "IPM.DistLIst", 1)\n  DL.AddMemberEx "Joe The User", "user@test.demo", "SMTP"\n  DL.Save	0
4464706	4464256	How to set focus to a control after validation in .NET	private delegate void ChangeFocusDelegate(Control ctl);\n\n    private void textBox1_Validating(object sender, CancelEventArgs e) {\n        int value;\n        if (!int.TryParse(textBox1.Text, out value)) e.Cancel = true;\n        else {\n            if (value == 1) this.BeginInvoke(new ChangeFocusDelegate(changeFocus), textBox2);\n            else this.BeginInvoke(new ChangeFocusDelegate(changeFocus), textBox3);\n        }\n    }\n    private void changeFocus(Control ctl) {\n        ctl.Focus();\n    }	0
15642305	15642124	C# How to open a PDF in my project resources?	string locationToSavePdf = Path.Combine(Path.GetTempPath(), "file name for your pdf file.pdf");  // select other location if you want\nFile.WriteAllBytes(locationToSavePdf,Properties.Resources.nameOfFile);    // write the file from the resources to the location you want\nProcess.Start(locationToSavePdf);    // run the file	0
17101995	17101817	How to serialize an XmlDocument to a well-formatted human-readable XML?	//Create a writer to write XML to the console.\nXmlTextWriter writer = null;\nwriter = new XmlTextWriter (Console.Out);\n//Use indentation for readability.\nwriter.Formatting = Formatting.Indented;\nwriter.Indentation = 4;	0
29056307	29056282	Should I cache a comparer in a static field?	static readonly IComparer<string> _IdComparer = Comparer<string>.Create((x, y) => {\n        var curUser = HttpContext.Current.User;\n        if (curUser != null) {\n            var curId = curUser.Identity.GetUserId();\n            if (x == curId)\n                return -1;\n            else if (y == curId)\n                return 1;\n        }\n        return string.Compare(x, y);\n    });\n\n    public static IComparer<string> IdComparer {\n        get {\n            return _IdComparer;\n        }\n    }	0
23448392	23448077	How to join Urdu alphabets in c#	string a = "?";\n string b = "?";\n string c = "?";\n textBox1.Text = a + b + c;	0
6815757	6814960	 to plot two different graphs together on the same chart	foreach (Series chartSeries in kpiChartControl.Series)\n    {\n      chartSeries.ChartType = SeriesChartType.Pie;\n\n      chartSeries["PieLabelStyle"] = "Outside";\n      chartSeries["DoughnutRadius"] = "30";\n      chartSeries["PieDrawingStyle"] = "SoftEdge";\n\n      chartSeries.BackGradientStyle = GradientStyle.DiagonalLeft;\n    }	0
6862992	6862896	How to transform an xml string using a XSLT in C#	MemoryStream oStream = new MemoryStream()\noXslt.Transform(new XPathDocument(new XmlNodeReader(oXml)), null, oStream );\noStream.Position = 0\nStreamReader oReader = new StreamReader(oStream);\nstring output = oReader.ReadToEnd();	0
4232313	4232302	How to select array index after Where clause using Linq?	weekDays.Select((day, index) => new { Day = day, Index = index })\n        .Where(x => x.Day.Contains("s"))\n        .Select(x => x.Index)\n        .ToArray();	0
9288563	9287819	Getting accurate three-minute time values	static private DateTime CurrentTime (DateTime now)\n{\n    return now.Date.AddSeconds((now.TimeOfDay.TotalSeconds + 90) / 180 * 180);\n}	0
25256864	25256780	How to get selected value from DataGridHyperlinkColumn using wpf data grid	private void  Hyperlink_Click(object sender, RoutedEventArgs e)\n        {\n            HyperlinkButton hlb = (HyperlinkButton)sender;\n            if(hlb !=null){\n               var id = hlb.tag\n            }\n\n        }	0
11850979	11850935	How to display how many times an array element appears	int[] values = new []{1,2,3,4,5,4,4,3};\n\nvar groups = values.GroupBy(v => v);\nforeach(var group in groups)\n    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());	0
30347133	30346546	How to get json result with unicode character	wc.Encoding = System.Text.Encoding.UTF8;	0
8838507	8830052	How do I get the Controller and Action names from the Referrer Uri?	// Split the url to url + query string\nvar fullUrl = Request.UrlReferrer.ToString();\nvar questionMarkIndex = fullUrl.IndexOf('?');\nstring queryString = null;\nstring url = fullUrl;\nif (questionMarkIndex != -1) // There is a QueryString\n{    \n    url = fullUrl.Substring(0, questionMarkIndex); \n    queryString = fullUrl.Substring(questionMarkIndex + 1);\n}   \n\n// Arranges\nvar request = new HttpRequest(null, url, queryString);\nvar response = new HttpResponse(new StringWriter());\nvar httpContext = new HttpContext(request, response)\n\nvar routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));\n\n// Extract the data    \nvar values = routeData.Values;\nvar controllerName = values["controller"];\nvar actionName = values["action"];\nvar areaName = values["area"];	0
22266109	22265585	Get Id of a website in IIS-7 and above	using (ServerManager serverManager = new ServerManager()) { \n\nvar sites = serverManager.Sites; \nforeach (Site site in sites) \n{ \n  Console.WriteLine(site.Id); \n}	0
22512194	22501711	How do you give a C# Auto-Property a default value in DynamicProxy?	namespace ConsoleApplication15\n{\n  using System;\n  using Castle.DynamicProxy;\n\n  public class Test\n  {\n    private SubTestClass subTestClass;\n\n    public virtual string Status\n    {\n      get\n      {\n        return this.subTestClass.SubStatus;\n      }\n\n      set\n      {\n        this.subTestClass.SubStatus = value;\n      }\n    }\n\n    public int Data { get; set; }\n  }\n\n  public class SubTestClass\n  {\n    public string SubStatus { get; set; }\n  }\n\n  public class Program\n  {\n    public static void Main(string[] args)\n    {\n      var proxyGenerator = new ProxyGenerator();\n\n      var testObject = proxyGenerator.CreateClassProxy<Test>(new MyInter());\n\n\n      if (testObject.Status != null)\n      {\n        Console.WriteLine("Working");\n      }\n    }\n\n  }\n\n  public class MyInter : IInterceptor\n  {\n    public void Intercept(IInvocation invocation)\n    {\n      if (invocation.Method.ReturnType == typeof(string))\n      {\n        invocation.ReturnValue = string.Empty;\n      }\n    }\n  }\n}	0
7573325	7571754	Get variable & keep changes after postback	ScriptManager.RegisterClientScriptBlock()	0
22505661	22505362	Insert Code c# in a asp:ImageButton tag	Visible='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "Active")) %>'	0
7024149	7024051	Find missing and overlapping numbers in sequences	var missing = \n      Enumerable.Range(1, 200)\n               .Where(i => sequences.All(t => t.Item1 > i || t.Item2 < i));\nvar overlapping = \n      Enumerable.Range(1, 200)\n                .Where(i => sequences.Count(t => t.Item1 <= i && t.Item2 >= i) > 1);	0
12808553	12808329	How would you invoke an event with reflection?	public void TriggerEvent(string handler, EventArgs e)\n    {\n        MulticastDelegate eventDelegate =\n              (MulticastDelegate)this.GetType().GetField(handler,\n               System.Reflection.BindingFlags.Instance |\n               System.Reflection.BindingFlags.NonPublic).GetValue(this);\n\n        Delegate[] delegates = eventDelegate.GetInvocationList();\n\n        foreach (Delegate dlg in delegates)\n        {\n            dlg.Method.Invoke(dlg.Target, new object[] { this, e });\n        } \n    }	0
26739618	26738151	I want to show any selected item from CheckedListBox in a ListBox in C#	private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    if (e.NewValue == CheckState .Checked)\n    {\n        listBox1.Items.Add(ChkBox1.Items[e.Index]);\n    }\n    else\n    {\n        listBox1.Items.Remove(ChkBox1.Items[e.Index]);    \n    }\n}	0
3249519	3249379	Renaming Folders using RegEx	static void SanitizeFolders(DirectoryInfo root)\n{\n    string regPattern = (@"[~#&!%+{}]+");\n    string cleanName = "";\n    Regex regExPattern = new Regex(regPattern);\n\n    foreach (DirectoryInfo sub in root.GetDirectories())\n    {\n        if (regExPattern.IsMatch(sub.Name))\n        {\n            /* set cleanName appropriately... */\n\n            sub.MoveTo(cleanName);\n        }\n    }\n\n    //recurse into subdirectories\n    foreach (DirectoryInfo sub in root.GetDirectories())\n    {\n        SanitizeFolders(sub);\n    }\n}	0
2814099	2813942	.NET app running as either Windows Form or as Console Application	using System;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication1 {\n  static class Program {\n    [STAThread]\n    static void Main(string[] args) {\n      if (args.Length > 0) {\n        // Command line given, display console\n        AllocConsole();\n        ConsoleMain(args);\n      }\n      else {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new Form1());\n      }\n    }\n    private static void ConsoleMain(string[] args) {\n      Console.WriteLine("Command line = {0}", Environment.CommandLine);\n      for (int ix = 0; ix < args.Length; ++ix)\n        Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);\n      Console.ReadLine();\n    }\n\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    private static extern bool AllocConsole();\n  }\n}	0
33448576	33448494	How to Randomize all the entire content inside of array C#	int[] names = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\nRandom rnd = new Random();\nint[] MyRandomArray = names.OrderBy(x => rnd.Next()).Take(10).OrderBy(x => x).ToArray();\n\nforeach (var s in MyRandomArray)\n{\n    Console.WriteLine(s);\n}	0
11503990	11503884	How do I add a simple namespace?	XDocument doc = new XDocument();\nXElement root = new XElement("root", \n    new XAttribute("name", Name)\n    );\ndoc.Add(root);\nXNamespace xmlns = Namespace;\ndoc.Root.Name = xmlns + root.Name.LocalName;	0
3521565	3521329	Mocking without injection	public MyService() : this(new DefaultDep1(), new DefaultDep2())\n{\n}\n\npublic MyService(IDep1 d1, IDep2 d2)\n{\n}	0
18087568	18087444	How I create custom button in a messagebox in .net form application?	MessageBox.Show(this, "Message", "caption", MessageBoxButtons.OKCancel);	0
4222011	4221995	Saving a deleted row in a datatable to be deleted later in a database	row["ColumnName", DataRowVersion.Original]	0
18215520	16997718	Defining/managing >1 constructor parameters of the same type with independent values when using AutoFixture as a SutFactory	public class ClassACustomization: ICustomization\n{\n    public double ParameterA { get; set;}\n    public double ParameterB { get; set;}\n\n    public void Customize(IFixture fixture)\n    {\n         //Note: these can be initialized how you like, shown here simply for convenience.\n         ParameterA = fixture.Create<double>();\n         ParameterB = fixture.Create<double>();\n         fixture.Customize<ClassA>(c => c\n           .FromFactory(() => \n           new ClassA(ParameterA , ParameterB )));\n    }\n}	0
20289283	20289192	How to parse CET/CEST datetime?	string[] formats = new[] \n{\n    "ddd, dd MMM yyyy HH:mm:ss CEST",\n    "ddd, dd MMM yyyy HH:mm:ss CET"\n};\n\nvar processedData = DateTime.ParseExact((string)item.pubDate,\n                                    formats, \n                                    CultureInfo.InvariantCulture, \n                                    DateTimeStyles.None);	0
8072867	8072650	Programmaticaly access files on android device from PC	var drives = DriveInfo.GetDrives();\n\nvar removableFatDrives = drives.Where(\n        c=>c.DriveType == DriveType.Removable &&\n        c.DriveFormat == "FAT" && \n        c.IsReady);\n\nvar andriods = from c in removableFatDrives\n               from d in c.RootDirectory.EnumerateDirectories()\n               where d.Name.Contains("android")\n               select c;	0
912936	912931	How can I databind to a string array?	IEnumerable<T>	0
16517615	16517459	Pausing window wpf application	if (button1.Content.Equals("Play"))\n            {\n                button1.Content = "Pause";\n                mediaElement1.Play();\n            }\n            else\n            {\n                button1.Content = "Play";\n                mediaElement1.Pause();\n            }	0
32344946	32344839	how to change the value of a gridview in row data bound event	protected void gvrequests_RowDataBound(Object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n          // your logic will go here\n        }\n   }	0
1547617	1547594	Cast a variable to a type represented by another Type variable?	public static T Cast<T>(object o) {\n  return (T)o;\n}	0
16481687	16475653	Serializing jagged vs multidimensional arrays	static bool IsJaggedArray(object obj) {\n        var t = obj.GetType();\n        return t.IsArray && t.GetElementType().IsArray;\n    }\n\n    static void Test() {\n        var a1 = new int[42];\n        Debug.Assert(!IsJaggedArray(a1));\n        var a2 = new int[4, 2];\n        Debug.Assert(!IsJaggedArray(a2));\n        var a3 = new int[42][];\n        Debug.Assert(IsJaggedArray(a3));\n    }	0
11389433	11389400	how to check if a control is disabled or not?	if(ddlSectorRailway.Attributes["disabled"]!=null)\n{\n  if(ddlSectorRailway.Attributes["disabled"]=="disabled")\n {\n   //your code \n }\n}	0
14047380	14047288	Am I able to scan a document and extract certain words?	"\[\[(?<tag>[^\]]*)\]\]"	0
4884163	4884043	How to write to Console.Out during execution of an MSTest test	Trace.WriteLine	0
16661044	16660983	Web app, load image into memory to get width	int width;\nusing (Bitmap bmp = new Bitmap(filename))\n{\n    width = bmp.Width;\n}	0
10112395	10112076	List all bit names from a flag Enum	public static IEnumerable<T> MaskToList<T>(Enum mask)\n{\n    if (typeof(T).IsSubclassOf(typeof(Enum)) == false)\n        throw new ArgumentException();\n\n    return Enum.GetValues(typeof(T))\n                         .Cast<Enum>()\n                         .Where(m => mask.HasFlag(m))\n                         .Cast<T>();\n}	0
2865274	2864582	Access ConfigurationSection from ConfigurationElement	var cs = \n    ((SiteConfigurationSection)WebConfigurationManager\n      .GetSection("mySectionTag")).DefaultConnectionString;	0
9363520	9363453	Process start from two strings	var path = Path.Combine(p1, l1);\nProcess.Start(path);	0
33393248	33393109	How to 'select' object field when you only have a string with exact name as the object field	string fieldName = "Field1";\nStuff thing = new Stuff();\n\nthing.GetType().GetField(fieldName).SetValue(thing, "checked");	0
1717185	1716984	datacolumn datagridview replace specific value	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {\n    if (dataGridView1.Columns[e.ColumnIndex].Name == "Column3") {\n        if (e.Value.ToString() == "0") {\n            e.CellStyle.BackColor = Color.Red;\n            e.Value = "False";\n        }\n    }\n}	0
14261286	14260740	LINQ functions for checking if a string exists before entering it into query	IQueryable<Company> query = p.Companies.AsQueryable();\n\nif(!string.IsNullOrEmpty(variable1))\n    query = query.Where(company => company.Name != "" || company.Name.Contains(variable1));\n\nif(!string.IsNullOrEmpty(variable2))\n    query = query.Where(company => company.Description != "" || company.Description .Contains(variable1));\n\nbool result = query.Any();	0
2646663	2646655	How to call other constructors from a constructor in c#?	public Blah(string a, string b) : this(a, b, "")\n{\n}\n\npublic Blah(string a, string b, string c)\n{\n    // etc\n}	0
4163409	4153978	c# app to sync calendar with exchange server?	using Microsoft.Exchange.WebServices.Data;	0
33106839	33105856	How to implement the Model in MVVM	class ViewModelDefault : INotifyPropertyChanged\n{\n    // Bound to your textbox\n    public string TextboxProperty { get; set;}\n\n    // Instantiate modellayer in viewmodel\n    private ModelClass _modelClass = new ModelClass();\n\n    // RelayCommand property -> bound to button on viewmodel\n    // Will execute method "ExecuteCommand" that contains a call to a method in the ModelClass\n    public ICommand ExecuteModelMethod \n    { \n        get {\n            RelayCommand relayCommand = new RelayCommand(ExecuteCommand); \n            return relayCommand; \n        } \n    }\n\n    // Method that the RelayCommand will execute.\n    private void ExecuteCommand() \n    {\n        _modelClass.SaveTextInTextfile(TextboxProperty);\n    }\n\n    ...\n}	0
23109877	23108931	filehelpers - Parsing variable line length	using (MemoryStream stream = new MemoryStream(_fileContent)) //file content can be file as byte array\n            {\n                TextReader reader = new StreamReader(stream);\nstring path = "C:\\Sample.csv";\n                CsvEngine csvEngine = new CsvEngine("Model", ',', path);\n                var dataTable = csvEngine.ReadStreamAsDT(reader);\n//Do whatever with dataTable\n\n}	0
3645205	3645193	Input validation in textbox in windows phone 7	invalid name	0
11019457	11013011	C# Split HexString	public static byte[] ConvertHexStringToByteArray(string hexString)\n        {\n            if (hexString.Length % 2 != 0)\n            {\n                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));\n            }\n\n            byte[] HexAsBytes = new byte[hexString.Length / 2];\n            for (int index = 0; index < HexAsBytes.Length; index++)\n            {\n                string byteValue = hexString.Substring(index * 2, 2);\n                HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);\n            }\n\n            return HexAsBytes;	0
16538291	16538025	Get All Bookmarks from Word Document	foreach (Bookmark bookmark in document.Bookmarks)\n{\n    // Do whatever you want with the bookmark.\n}	0
28639139	28636734	Sliding Effect in Windows Form Application	private void Form1_Load(object sender, EventArgs e)\n    {\n        System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();\n        shape.AddRectangle(new Rectangle(8, 40, 200, 200));\n        // I just picked a shape.  The user will see whatever exists in these pixels of the form.\n        // After you get it going, make sure that things not on the visible area are disabled.  \n        // A user can't click on them but they could tab to them and hit ENTER.\n        // Give the user a way to close it other than Alt-F4, stuff like that.\n        this.Region = new System.Drawing.Region(shape);\n        this.Top = (Screen.PrimaryScreen.WorkingArea.Height - 160) / 2;\n        this.Left = Screen.PrimaryScreen.WorkingArea.Left;\n    }\n\n    private void Form1_MouseHover(object sender, EventArgs e)\n    {\n        this.Region = new Region(new Rectangle(0, 0, this.Width, this.Height));\n    }	0
15541716	15536507	how to resolve a proxy class in Castle Windsor	container.Register(\n    Component.For<IBatchDataService>().AsWcfClient(WCFEndpoint.FromConfiguration("Internal.IBatchDataService")).LifestyeTransient().Named("wcfBatchDataService"),\n    Component.For<IBatchDataService>().ImplementedBy<BatchDataServiceClient>().AsDefault().DependsOn(\n        Dependency.OnComponent("constructorParameterName", "wcfBatchDataService")\n)	0
1294846	1290750	How do I unit test code that uses a Fluent interface?	rule 1: find configured computer with serial number = "whatever" and has-config = true.\nrule 2: find not-config computer with serial number = "whatever and has-config = true.\nrule 3: find configured computer with serial number = "whatever" and has-config = false.\nrule 4: find not-config computer with serial number = "whatever" and has-config = false.\nrule 5: find all computer with serial number = "whatever" and has-config = true.\nrule 6: find all computer with serial number = "whatever" and has-config = false.	0
9830116	9830069	Searching for file in directories recursively	Directory.GetFiles	0
28407090	28406737	Adding PivotItem dynamically to a pivot at particular position in Windows phone 8.1	CalPivot.Items.Insert(0, new PivotItem() { Header = "Position 1" });	0
6098711	6098646	Object cannot be cast from DBNull to other types	var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");\n if(!(outputParam is DBNull))\n     DataTO.Id = Convert.ToInt64(outputParam);	0
14455722	14455675	Trying to return json and populate selectlist	JsonRequestBehavior.AllowGet	0
6089946	6089927	How to test WCF service with TransportWithMessageCredential in VS2010 built-in web server	Use local IIS	0
6703374	6540154	Html Agility Pack/C#: how to create/replace tags?	public string ReplaceTextBoxByLabel(string htmlContent) \n{\n  HtmlDocument doc = new HtmlDocument();\n  doc.LoadHtml(htmlContent);\n\n  foreach(HtmlNode tb in doc.DocumentNode.SelectNodes("//input[@type='text']"))\n  {\n    string value = tb.Attributes.Contains("value") ? tb.Attributes["value"].Value : "&nbsp;";\n    HtmlNode lbl = doc.CreateElement("span");\n    lbl.InnerHtml = value;\n\n    tb.ParentNode.ReplaceChild(lbl, tb);\n  }\n\n  return doc.DocumentNode.OuterHtml;\n}	0
3988201	3988111	Default parameter values in C#'s lambda expressions	public static Func<String, Int32, IEnumerable<String>> SomeFunction = \n                                          (StrTmp, IntTmp) => { ... };\n\npublic static Func<String, IEnumerable<String>> SomeFunctionDefaulted =\n                                  strTmp => SomeFunction(strTmp, 2);	0
17982616	17982497	Regex string for validating Decimal excluding zero	public static string DecimalWithPlaces(int wholePart, int fractionalPart)\n{\n    return @"^-?[1-9]{0," + wholePart + @"}\.[1-9]{1," + fractionalPart + @"}$";\n}	0
32070298	31432491	Can Update a photo tags in existing One	AccessToken = Properties.Settings.Default.FBAccessToken;\n    FacebookClient FbClient = new FacebookClient(AccessToken);\n    var PostInfo = new Dictionary<string, object>();\n    var tags = new[] { new { tag_uid = "870415313026255", tag_text = "Tag updated", x = 90, y = 110 } };\n    PostInfo.Add("tags", tags);\n    var result = FbClient.Post("/"Existing PhotoID"/tags", PostInfo);	0
13835171	13677842	Change the visible position of ROWs of ultragrid programmatically	private void ultraGrid1_AfterCellUpdate(object sender, CellEventArgs e)  \n    {  \n        if (e.Cell.Column.Key == "Select" && Convert.ToBoolean(e.Cell.Value))  \n            {  \n                ultraGrid1.Rows.Move(e.Cell.Row, newPosition);  \n            }  \n        }	0
31225892	31225805	How to open different windows based on command line arguments?	private void Application_Startup(object sender, StartupEventArgs e)\n{\n    if (e.Args.Length > 0)\n    {\n        var window1 = new Window1(e.Args[0]);\n        window1.Show()\n    }\n    else\n    {\n         var window2 = new Window2();\n         window2.Show()\n    }\n}	0
10352141	10351965	How to implement recursive callback pattern?	private void MyWrapperCall(string url, string expectedTitle, Action<MyRequestState> callback)\n{\n    Action<MyRequestState> redirectCallback = null;\n    redirectCallback = new Action<MyRequestState>((state) =>\n    {\n        if(state.DoRedirect)\n        {\n            DoWebRequest(state.Redirect, expectedTitle, redirectCallback);\n        }\n        else\n        {\n            callback(state);\n        }\n    });\n\n    DoWebRequest(url, expectedTitle, redirectCallback);\n}	0
32999000	32998508	Insert data into local database using ado.net in a console application	static void Insert()\n    {\n        try\n        {\n            string connectionString =System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString;\n            using (SqlConnection conn =new SqlConnection(connectionString))\n            {\n                conn.Open();\n                using (SqlCommand cmd = new SqlCommand("INSERT INTO Student(Sid,st_name) VALUES (" +\n                       "@id,@name)", conn))\n                {\n                    cmd.Parameters.AddWithValue("@Id", 111);\n                    cmd.Parameters.AddWithValue("@Name", "nallia");\n\n\n                    int rows = cmd.ExecuteNonQuery();\n\n                    //rows number of record got inserted\n                }\n            }\n        }\n        catch (SqlException ex)\n        {\n            //Log exception\n            //Display Error message\n        }\n    }	0
21731868	21729562	Passing IEnumerable<int> as parameter to WCF service	[XmlRoot("items")]\npublic class MyItems\n{\n    [XmlElement("item")]\n    public List<int> Items { get; set; }\n}	0
600568	596684	How do I limit my date range on an Ajax Calendar?	protected void Calendar_DayRender(object sender, DayRenderEventArgs e)\n{\n   //Get date in past relative to current date.\n   DateTime dateInPast = DateTime.Now.Subtract(TimeSpan.FromDays(10));\n\n   if (e.Day.Date < dateInPast || e.Day.Date > DateTime.Now)\n      {\n         e.Day.IsSelectable = false;\n      }\n}	0
5792127	5792056	Obtains character with string Substring()	var timeCodeArrayString = timeCodeList[i].Substring(3,8)	0
20668430	16412867	A chart element with the name already exists in the 'ChartAreaCollection'	private void createNewSeries(String SeriesName)\n    {\n        if(chart1.Series.IsUniqueName(SeriesName))\n        {\n            chart1.Series.Add(SeriesName);\n        }\n    }	0
725352	725341	How to determine if a File Matches a File Mask?	private bool FitsMask(string sFileName, string sFileMask)\n{\n    Regex mask = new Regex(sFileMask.Replace(".", "[.]").Replace("*", ".*").Replace("?", "."));\n    return mask.IsMatch(sFileName);\n}	0
23018455	23018118	How to detect current display setting (i.e. extended, duplicate etc)	Screen.AllScreens.Length	0
2393736	2393464	Windows Forms + commands from the console in C#	static class Program {\n    [STAThread]\n    static void Main() {\n      Application.EnableVisualStyles();\n      Application.SetCompatibleTextRenderingDefault(false);\n#if DEBUG\n      CreateConsole();\n#endif\n      Application.Run(new Form1());\n    }\n\n    static void CreateConsole() {\n      var t = new System.Threading.Thread(() => {\n        AllocConsole();\n        for (; ; ) {\n          var cmd = Console.ReadLine();\n          if (cmd.ToLower() == "quit") break;\n          // Etc...\n        }\n        FreeConsole();\n      });\n      t.IsBackground = true;\n      t.Start();\n    }\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    private static extern bool AllocConsole();\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    private static extern bool FreeConsole();\n  }	0
12603380	12395819	WCF Parallel Impersonation	IntPtr token = WindowsIdentity.GetCurrent().Token;\n\nParallel.ForEach( Enumerable.Range( 1, 100 ), ( test ) =>\n{\n    using ( WindowsIdentity.Impersonate( token ) )\n    {\n          Console.WriteLine( WindowsIdentity.GetCurrent( false ).Name );\n    }\n} );	0
12274579	12273941	How to prevent slider from stretching?	.ui-slider .ui-slider-handle {\n  position: absolute;\n  z-index: 2;\nwidth:1em !important;\nheight:1em !important;\n cursor: default;\n}	0
23499593	23499442	Save dynamic data to a multidimensional array	string[] lineas = Regex.Split(servicios, "\n");\nstring[] sublineas;\n\nString[][] dataS = new string[lineas.Length][];\n\nfor(int i=0; i<lineas.Length;i++)\n{\n    dataS[i] = Regex.Split(lineas[i], "==");\n}	0
7435688	7435652	Using Linq to XML (C#) how do I find attribute values?	var xml = XElement.Load (@"c:\directory\Data_Config.xml");\nvar query = \n    from e in xml.Descendants("FI")\n    select e.Attribute("name").Value;	0
17154167	17154040	Displaying distinct datetime column in dropdownlist	DropDownList1.DataTextFormatString = "MMMM dd, yyyy";	0
25550234	25549958	The parameters dictionary contains a null entry for parameter of non-nullable type 'System.Int32'	public ActionResult Edit(int id, FormCollection collection)	0
10637462	10621113	How to prevent number from getting to large from wave	private int GetMaxSound(short[] wave)\n    {\n        int maxSound = 0;\n        for (int i = 0; i < wave.Length; i++)\n        {\n            maxSound = Math.Max(maxSound, Math.Abs((int)wave[i]));\n        }\n        return maxSound;\n    }	0
20956934	20956805	Implementing a find system for a ListView in C#	var lviFoundList = new List<ListViewItem>();\nforeach(var item in listItemsList.Items)\n{\n   if(item.Text == findTextBox.Text) lviFoundList.Add(item);\n}	0
23089880	23048605	C# GridView. How to get a value of a selected item?	private async void RemoveButton_Click(object sender, RoutedEventArgs e)\n{\n    GridViewItem selection = (GridViewItem)GridView1.SelectedItem;\n    string ToBeDeleted = selection.Content.ToString();\n    GridView1.Items.Remove(selection);\n    SQLiteAsyncConnection conn = new SQLiteAsyncConnection("people");\n    var query = conn.Table<Person>().Where(x => x.Name == ToBeDeleted);\n    var result = await query.ToListAsync();\n    foreach (var item in result)\n    {\n        await conn.DeleteAsync(item);\n    }\n    MessageDialog msgDialog = new MessageDialog("Category " + ToBeDeleted + " is deleted");\n    msgDialog.ShowAsync();\n}	0
24371802	24367224	Lambda Expression with two IN parameters to Lambda Expression with single IN parameter	public static IQueryable<TEntity> Seed<TSeed, TEntity>(\n    this DbContext context,\n    IEnumerable<TSeed> seeds,\n    Expression<Func<TEntity, TSeed, bool>> predicate)\n{\n    return context.Set<TEntity>()\n            .AsExpandable()\n            .Where(entity => seeds.Any(seed => predicate.Invoke(entity, seed)));\n}	0
8152014	8151981	how to use this definition in c# with dictionaries	Dictionary<string,Dictionary<string,int>>	0
24546995	24546823	Get number of rows deleted and number of rows edited by DbContext.SaveChanges()	var modifiedCount = dbContext.ChangeTracker.Entries().Where(x => x.State == System.Data.EntityState.Modified).Count()	0
17945944	17945635	How to cast a selecteditem in listbox	string colorName = (string) listColor.SelectedItem;\nColor colorValue = ColorConverter.ConvertFromString(colorName);	0
3307321	3307271	How to get the value of non- public members of picturebox?	PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", \n    System.Reflection.BindingFlags.Public | \n    System.Reflection.BindingFlags.NonPublic | \n    System.Reflection.BindingFlags.Instance);\n\nRectangle rectangle = (Rectangle)pInfo.GetValue(pictureBox1, null);	0
14128500	14128378	Click event in blank area of TreeView	private void treeView1_MouseClick(object sender, MouseEventArgs e)\n{\n   // MessageBox.Show("treeView1_MouseClick");\n}\n\nprivate void treeView1_Click(object sender, EventArgs e)\n{\n   // MessageBox.Show("treeView1_Click");\n}\n\nprivate void treeView1_MouseDown(object sender, MouseEventArgs e)\n{\n    MessageBox.Show("treeView1_MouseDown");\n}	0
22683719	22683225	How I can use Windows Phone and Selenium?	RemoteWebDriver driver = RemoteWebDriver(new Uri("http://______:______"), DesiredCapabilities.InternetExplorer());\n\ndriver.Navigate().GoToUrl("https://winphonewebdriver.codeplex.com/");	0
32543370	32543076	Variables are setting each other to the same value?	data= Receive(i);  //Where Receive() returns a newly instantiated object.	0
16099943	16099821	Media player play all files in listbox how?	private bool listbox3job()\n{\n\n    AxWMPLib.AxWindowsMediaPlayer axWmp = wfh.Child as AxWMPLib.AxWindowsMediaPlayer;\n    WMPLib.IWMPPlaylist playlist = axWmp.newPlaylist("myPlaylist", string.Empty);\n\n    foreach (var selected in listBox1.Items)\n    {\n        string s = selected.ToString();\n        if (listBox3Dict.ContainsKey(s))\n        {\n            WMPLib.IWMPMedia temp = axWmp.newMedia(listBox3Dict[s]); //Load media from URL. \n            playlist.appendItem(temp); //Add song to playlist.\n        }\n    }\n    axWmp.settings.autoStart = true; //not necessary\n    axWmp.currentPlaylist = playlist; //Set media player to use the playlist.\n    return true;\n}	0
6500557	6500491	How to Invoke the progress bar in Status strip?	if (toolStripProgressBar1.Parent.InvokeRequired)\n{\n    toolStripProgressBar1.Parent.Invoke(new MethodInvoker(delegate { toolStripProgressBar1.Value= 100; }));\n}	0
10795645	10795557	Joining a HashSet into a LINQ to SQL query	from dataItem in context.DataItems\nwhere dataItem.Latest && SelectedItems.Contains(dataItem.Id)\nselect dataItem;	0
10412325	10411657	Howto bind Views to Viewmodel in a MVVM-Environment with XAML and WPF in C#	DataTemplate temp = new DataTemplate();\ntemp.DataType = typeof (MyViewModel);\n\nFrameworkElementFactory fac = new FrameworkElementFactory(typeof(MyView));\n\ntemp.VisualTree = fac;\n\nView.WindowName.Resources.Add(new DataTemplateKey(typeof(MyViewModel)), temp );	0
6741336	6741331	Log a user in to my front end website using kentico	protected void btnSubmit_Click(object sender, EventArgs e)\n    {\n        CMS.SiteProvider.UserInfo ui = CMS.SiteProvider.UserInfoProvider.AuthenticateUser(txtEmail.Text, txtPassword.Text, CMS.CMSHelper.CMSContext.CurrentSite.SiteName);\n        if (ui != null)\n        {\n            System.Web.Security.FormsAuthentication.SetAuthCookie(ui.UserName, true);\n            CMS.CMSHelper.CMSContext.SetCurrentUser(new CMS.CMSHelper.CurrentUserInfo(ui, true));\n            CMS.SiteProvider.UserInfoProvider.SetPreferredCultures(ui);\n            Response.Redirect("MY_SECURE_PAGE");\n        }\n        else\n        {\n            litMessage.Text = "Email/Password incorrect";\n        }\n    }	0
27579022	27578884	WPF Listbox control	((StackPanel)((ListBoxItem)UserList.SelectedItem).Content).Children.OfType<TextBlock>().FirstOrDefault();	0
8783061	8782907	how to get FileName of process.MainModule?	foreach (Process proc in processlist)\n{\n  try\n  {\n    Console.WriteLine(proc.MainModule.FileName);\n  }\n  catch (Win32Exception e)\n  {\n     Console.WriteLine(proc.ToString() + "  " + e.Message);\n  }\n}	0
19715789	19715709	Get the Row the user Right Clicked on in a Grid before they click on an item in the Context Menu	private void genericView_MouseDown(object sender, MouseEventArgs e)\n{\n    if (e.Button == System.Windows.Forms.MouseButtons.Right)\n    {\n        rowX = e.X;\n        rowY = e.Y;\n    }\n}	0
16662420	16660875	How to bind a list count to a label	public class Person\n    {\n        public int Id { get; set; }\n        public string Name { get; set; }\n    }\n\n    private BindingSource source = new BindingSource();\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        var items = new List<Person>();\n        items.Add(new Person() { Id = 1, Name = "Gabriel" });\n        items.Add(new Person() { Id = 2, Name = "John" });\n        items.Add(new Person() { Id = 3, Name = "Mike" });\n        source.DataSource = items;\n        gridControl.DataSource = source;\n        source.ListChanged += source_ListChanged;\n\n    }\n\n    void source_ListChanged(object sender, ListChangedEventArgs e)\n    {\n        label1.Text = String.Format("{0} items", source.List.Count);\n    }	0
19993364	19993333	C# number formatting	void Main()\n{\ndecimal d = 351.23456M;\nConsole.Write(d.ToString("0.00000000"));\n}	0
4334282	4334258	Add a Linq clause to a Iqueryable object	IQueryable<Foo> newQuery = oldQuery.Skip(20);	0
5502996	5502771	Adding attributes to validator programmatically	newRQValid.Display = ValidatorDisplay.Dynamic;\n newCMValid.Type = ValidationDataType.Date;\n newCMValid.Operator = ValidationCompareOperator.LessThanEqual;	0
20703986	20703752	Modifying numbers in a List	XNamespace foobar = "http://www.april-technologies.com";\nvar prix  = docxx.Descendants(foobar + "CotisationMensuelle").Select(x => new { CotisationMensuelle =(string)x}).ToList();\nvar newPrix = new List<string>();\nforeach (var s in prix)\n{\n    var s1 = s.CotisationMensuelle.Substring(0, s.CotisationMensuelle.Length - 2);\n    var s2 = s.CotisationMensuelle.Substring(s.CotisationMensuelle.Length - 2);\n\n    //add a comma before the last 2 digits (from right)\n\n    var s_total = s1 +","+ s2;\n\n    newPrix.Add(s_total);\n}\nrpMyRepeater1.DataSource = newPrix.Select(x => new {CotisationMensuelle = x}).ToList();\nrpMyRepeater1.DataBind();	0
93877	93832	How does one load a URL from a .NET client application	Process.Start("http://www.yoururl.com/Blah.aspx");	0
16383407	16383383	C#, No overload for method 'ToList' takes 1 arguments	List<TreeNode> views =  res  // new List<TreeNode>();    \n      .Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)   \n      .Select(line => line.Split(','))   // second split, process each line \n      .Select(t => new TreeNode\n      {\n        Text = t[0],\n        ToolTipText = t[1]\n      })\n      .ToList( );	0
14549805	14549766	How to get my project path?	string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));	0
12716616	12716264	Filtering items in InfoPath selectNodes	customerData.selectNodes("tns:customer[not(State = 'FL')]");	0
16119069	16119045	DateTime + Timer Tick?	TimeSpan _elapsed = new TimeSpan();\n\nprivate void timer_Tick(object sender, EventArgs e)\n{\n    _elapsed = _elapsed.Add(TimeSpan.FromMinutes(1));\n    labelTimer.Text = "Elapsed Time: " + _elapsed.ToString();\n}	0
1113690	1113635	How to get MethodInfo of interface method, having implementing MethodInfo of class method?	var map = targetType.GetInterfaceMap(interfaceMethod.DeclaringType);\nvar index = Array.IndexOf(map.InterfaceMethods, interfaceMethod);\n\nif (index == -1)\n{\n    //something's wrong;\n}\n\nreturn map.TargetMethods[index];	0
5827604	5827562	How do i get a list of classes in .NET	List<string> namespaces = new List<string>();\n\n    var refs = Assembly.GetExecutingAssembly().GetReferencedAssemblies();\n\n    foreach (var rf in refs) {\n        if (rf.Name == "System.Core")\n        {\n            var ass = Assembly.Load(rf);\n            foreach (var tp in ass.GetTypes())\n            {\n                if (!namespaces.Contains(tp.Namespace))\n                {\n                    namespaces.Add(tp.Namespace);\n                    Console.WriteLine(tp.Namespace);\n                }\n            }\n        }\n    }	0
3791458	3790084	When i change the datasource on My datagrid the columns dont autofill unless i order a column	dgUnPrinted.Sort(dgUnPrinted.Columns[0], ListSortDirection.Ascending);	0
6214080	6213749	MAPIFolder deprecated so workaround for Outlook programming?	Outlook.Folder oFolder = (Outlook.Folder) olNS.GetDefaultFolder( Outlook.OlDefaultFolders.olFoderDrafts)	0
9579090	9577938	OData with ServiceStack?	IQueryable<T>	0
1912111	1912109	How to get bytes out of a PNG file using C#	System.Convert.ToBase64String(System.IO.File.ReadAllBytes(filePath));	0
2749614	2749418	Is there a way to set a DLL to always follow CultureInfo.InvariantCulture by default, if not specified?	private static readonly IFormatProvider parseFormat = CultureInfo.InvariantCulture;	0
18683166	18674859	Routing to WebApi Remove Localization	routes.MapRoute(\n         "WebApi",\n         "api/{language}/{controller}/{id}",\n         new { controller = "Upload", id = UrlParameter.Optional }\n         ).RouteHandler = new MultiCultureMvcRouteHandler();	0
20641430	20641166	Entity Framework doesn't want to remove rows in table with many-to-many relationship	using (var db = new FIXEntities())\n{\n   db.Database.Log = x => Debug.WriteLine(x);\n   var organizationDto = db.Organizations.First();\n   var contactDto = organizationDto.Contacts.Last();\n   //organizationDto.Contacts.Remove(contactDto); // not necessary\n\n   db.Entry(contactDto).State = EntityState.Deleted;\n   // or, like this if you prefer\n   db.Set<OrganizationContact>().Remove(contactDto);\n\n   db.SaveChanges();\n}	0
4094951	4094940	C# create simple xml file	new XDocument(\n    new XElement("root", \n        new XElement("someNode", "someValue")    \n    )\n)\n.Save("foo.xml");	0
661385	661289	String operations in C#	string input = "011100011";\n\n// add a 0 at the start and end to make the loop simpler\ninput = "0" + input + "0"; \n\nvar integers = (from c in input.ToCharArray() select (int)(c-'0'));\nstring output = "";\nfor (int i = 0; i < input.Length-2; i++)\n{\noutput += integers.Skip(i).Take(3).Sum();\n}\n\n// output is now "123210122"	0
2208898	2208872	How can I make this extension method more generic?	table.NewRow(new  { A = "Hello", B = 1, C = DateTime.Now })	0
22158936	22158847	remove the last second character from string	var q = "where id in (.....,11,)";\nq = q.Remove(q.LastIndexOf(','),1);	0
3017657	3017576	How do I verify/validate a float before storing as decimal(4,1) in SQL?	private bool Validate41Float(float f)\n{\n    float rounded = (float)Math.Round(f, 1);\n    if (rounded > -1000 && rounded < 1000) return true;\n    else return false;\n}	0
6585301	6551741	How can I post to a company Facebook page from an offline app (using the C# SDK)?	// init with a non-expiring access token for an app that can manage the fan page\nvar client = new FacebookClient(fbAppOaToken);\n\n// get accounts, using a Facebook ID for a user who has admin rights to the fan pge\ndynamic accts = client.Get(string.Format("/{0}/accounts", fbAppAdminUser));\n\n// find the access token for the fan page\nstring page_access_token = null;\nforeach (var acct in accts.data)\n{\n    if (acct.id == fbFanPageId)\n    {\n        page_access_token = acct.access_token;\n        break;\n    }\n}\n\n// fill in parameters for the message to post\ndynamic parameters = new ExpandoObject();\nparameters.message = "testing 123";\n\n// and include the access token as retrieved above\nparameters.access_token = page_access_token;\n\ndynamic result = client.Post(fbFanPageId + "/feed", parameters);	0
27176635	27176586	Edit datetime in c#	DateTime d1 = dt1.Date;	0
33031101	33019020	How to display date in UltraWinGrid SummaryRow in MM-dd-yyyy?	SummarySettings SumSummary = new SummarySettings();\n\ne.Layout.Bands[0].Columns["DateColumn"].AllowRowSummaries = AllowRowSummaries.False;\n\nSumSummary = e.Layout.Bands[0].Summaries.Add(SummaryType.Minimum, e.Layout.Bands[0].Columns["DateColumn"]);\n\nSumSummary.DisplayFormat = "{0:dd-MM-yyyy}";	0
443156	442941	Word dialog shown programmatically doesn't respond to mouse clicks	Dialog d = WordApp.Dialogs[WdWordDialog.wdDialogTableInsertTable];\n\nMainApplicationFormInstance.Enabled = false;\nint result = d.Display(ref missing);\nMainApplicationFormInstance.Enabled = true;\n\nif (result == -1)  // user pressed OK\n{\n    d.Execute();\n}	0
27175736	27146528	WebAPI - Log binding information at MessageHandler?	Request.Properties	0
4059947	4004881	Accessing GData Calender from Google Apps account?	var calendarService = new CalendarService("company-app-version");\ncalendarService.setUserCredentials("<email>", "<password>");\nvar eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");\nvar eventFeed = calendarService.Query(eventQuery);\nforeach (var atomEntry in eventFeed.Entries)\n{\n    Console.WriteLine(atomEntry.Title.Text);\n}	0
15512297	15510469	Release vs Debug Build	/filealign	0
33036987	33027429	My treeView populate a strange children : WPF MVVM	public bool HasDummyChild\n    {\n        //get { return this.Children.Count == 1 && this.Children[0] == DummyChild; }\n        get { return Children.Any() && Children.Contains(DummyChild); }\n    }	0
18440699	18440641	How to convert DriveInfo[] to List<string> C#	DriveInfo[] Drive_info = DriveInfo.GetDrives();\n\nList<string> list = Drive_info.Select(x => x.RootDirectory.FullName).ToList();	0
16299258	16299174	Message Box to Show Array and Text	MessageBox.Show(string.Format("Welcome {0}", name));	0
2484280	2484106	How do you return a partial view with spark?	public PartialViewResult ActionName()\n{\n    return PartialView();\n}	0
15623785	15549364	A generic error occurred in GDI+ again	using (System.Drawing.Image img = Image.FromStream(file))\n{\n  imgAnimaha = (System.Drawing.Image)img.Clone();\n}	0
31262936	31261768	Decode byte array	public class ModbusRequest\n{\n    public byte ServerId { get; set; }\n    public byte FunctionCode { get; set; }\n    public string Payload { get; set; }\n}\n\npublic ModbusRequest DecodeMessage(byte[] message)\n{\n    var result = new ModbusRequest();\n\n    // Simply copy bytes 0 and 1 into the destination structure.\n    result.ServerId = message[0];\n    result.FunctionCode = message[1];\n\n    byte stringLength = message[2];\n\n    // Assuming ASCII encoding, see docs.\n    result.Payload = Encoding.ASCII.GetString(message, 3, stringLength);\n\n    // Get the CRC bytes.\n    byte[] crc = new byte[2];\n    Buffer.BlockCopy(message, 4 + stringLength, crc, 0, 2);\n\n    // TODO: verify CRC.\n\n    return result;\n\n}	0
12775142	12775125	Find out how many iterations done by linq	.ToList()	0
20336137	20336075	Find if a view exists using the controller and view names?	public static HtmlString MyHelper(this HtmlHelper html)\n{\n    var controllerContext = html.ViewContext.Controller.ControllerContext;\n    var result = ViewEngines.Engines.FindView(controllerContext, name, null);\n    ...\n}	0
13889424	13889202	Trouble in adding data using set method in C#	private void addBtn_Click(object sender, EventArgs e)\n    {\n\n        string wayName = nameTxtBox.Text;\n\n        double lat = Convert.ToDouble( latTxtBox.Text);\n        float wayLat = (float)lat;\n\n\n        double lon = Convert.ToDouble( longTxtBox.Text);\n        float wayLong = (float)lon;\n\n\n        double ele = Convert.ToDouble(elevTxtBox.Text);\n        float wayEle = (float)ele;\n\n        WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle);\n\n        GPSDataPoint gdp = new GPSDataPoint();\n        gdp.Add(wp);\n\n        //Do something with your gdp variable or use the public on you have declared instead\n        //gpsdp.Add(wp);\n     }	0
5407732	5407636	How to carry text values over to a text box on another form?	//form1:\nForm2 form2;\n\nprivate void button1_Click()\n{\n   if(form2 == null)\n   {\n       form2 = new Form2();\n       form2.Show(); \n   }\n   form2.PassToForm2(textBox1.Text);\n}\n\n//form2:\nprivate void PassToForm2(string msg)\n{\n   textBox1.Text = msg;\n}	0
7966718	7966633	C# Anonymous Type access from other method	private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (myComboBox.SelectedItem != null)\n    {\n        var x = myComboBox.SelectedItem;\n        System.Type type = x.GetType();\n        int id = (int)type.GetProperty("Id").GetValue(obj, null);\n    }  \n}	0
1995261	1995231	Multithread server and communication with SQL	private static IEnumerable<SomeType> GetSomeData(string someInput)\n{\n    IEnumerable<SomeType> result = null;\n    using (SqlConnection conn = new SqlConnection(GetConnectionString()))\n    {\n        // put whatever code is needed to populate the result here\n    }\n    return result;\n}	0
28601319	28601188	Count consequitive numbers in a string C#	public static int Count(string txt)\n{\n    // TODO validation etc\n    var result = 0;\n    char lstChr = txt[0];\n    int lastChrCnt = 1;\n\n    for (var i = 1; i < txt.Length; i++)\n    {\n        if (txt[i] == lstChr)\n        {\n            lastChrCnt += 1;\n        }\n        else\n        {\n            if (lastChrCnt == 3)\n            {\n                result += 1;\n            }\n\n            lstChr = txt[i];\n            lastChrCnt = 1;\n        }\n    }\n\n    return lastChrCnt == 3 ? result + 1 : result;\n}	0
17948605	17948372	How do I build a function in C# that returns a delimited set of string numbers?	public string GetDelimited(int numberOfLoops, string delimiter) \n{\n    var builder = new StringBuilder();\n    for (int i= 1;  i < numberOfLoops + 1; i++)\n    {\n        if (i > 1) builder.Append(delimiter);\n        builder.Append(i.ToString());\n    }\n    return builder.ToString();\n}	0
12579779	12579126	How to deny to a panel to be dragged using WeifenLuo DockPanel Suite	toolPanel.PanelPane.AllowDockDragAndDrop = false;	0
7778381	7777549	MultiColumn Listview items to File	using (StreamWriter writer = new StreamWriter(@"C:\Desktop\test.txt"))\n{\n    StringBuilder line = new StringBuilder();\n    foreach (ListViewItem item in listView1.Items)\n    {\n        line.Clear();\n        for (int i=0; i<item.SubItems.Count; i++)\n        {\n            if (i > 0)\n                line.Append("|");\n            line.Append(item.SubItems[i].Text);\n        }\n        writer.WriteLine(line);\n    }\n}	0
25034925	25034302	Issue when converting or casting Date String to DateTime	var result = DateTime.TryParse(\n      "10. 10. 2014", \n      CultureInfo.CreateSpecificCulture("en-US"), \n      DateTimeStyles.None,\n      out date);	0
18963459	18961886	how to save ASP.NET_SessionId in custom membership providers	....\n\nvar encTicket = FormsAuthentication.Encrypt(authTicket);\nvar cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);\n\nif (authTicket.IsPersistent)\n{\n    cookie.Expires = authTicket.Expiration;\n}\n\nResponse.Cookies.Add(cookie);	0
7376103	7375452	How do I subscribe to raised events and printing together?	private static string timer1Value = string.Empty;\nprivate static string timer2Value = string.Empty;\nprivate static FormWithTimer timer1;\nprivate static FormWithTimer2 timer2;\n\npublic static void Main()\n{\n    timer1 = new FormWithTimer();\n    timer2 = new FormWithTimer2();\n\n    timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);\n\n    timer2.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable);\n    Console.ReadLine();\n}\n\n\nstatic void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e)\n{\n    if (sender == timer1)\n    {\n        timer1Value = e.Value.ToString();\n    }\n    else if (sender == timer2)\n    {\n        timer2Value = e.Value.ToString();\n    }\n\n    if (timer1Value != String.Empty && timer2Value != String.Empty)\n    {\n        Console.WriteLine(timer1Value + timer2Value); \n        // Do the string concatenation as you want.\n    }	0
2047044	2047012	I want my memory back! How can I truly dispose a control?	while(tabControlToClear.Controls.Count > 0)\n{ \n    var tabPage = tabControlToClear.Controls[0];\n    tabControlToClear.Controls.RemoveAt(0);\n    tabPage.Dispose(); \n\n    // Clear out events.\n\n    foreach (EventHandler subscriber in tabPage.Click.GetInvocationList())\n    {\n        tabPage.Click -= subscriber;\n    }\n}	0
15630937	15630845	how to remove special char from the string and make new string?	string input = "4(4N),3(3A),2(2X)";\nstring result = String.Join(",", input.Split(',')\n                                  .Select(s => s.Substring(0, s.IndexOf('('))));\n// 4,3,2	0
17236129	17236048	Pulling a table from a SQL Server database into a List<> in C# using Entity Framework	List<YourTable> list;\nusing (YourDataBaseEntities context = new YourDataBaseEntities())\n{\n    list = context.YourTables.toList();\n}	0
17424132	17423366	Manipulate a list within textbox textchange event in C# desktop application	var data = new[] { "Plate", "Table", "Cap" }; //Place your 'product list' into the IEnumerable<string> data\nlistBox.DataSource = data.Where(item => item.Contains(textBox.Text));	0
29790382	21610451	SMTP server terminates connection before sending QUIT command	354 Start mail input; end with<CR><LF>.<CR><LF>\n\nwe had to send <CR><LF>.<CR><LF>	0
34343935	34343864	remove object from the list if certain statement is true	muObj.Cars.RemoveAll(x => x.Manufacturer.CarFormat != null);	0
19026804	19026608	C# Search for term on a text file and put it in textbox	string line = File.ReadAllLines(filePath).Where(l =>l.Trim().StartsWith("host_bd")).FirstOrDefault();\nstring value = line.Split('=')[1].Trim();	0
20034474	20033788	How to get a month with most dates listed	var query = from d in DateMonth\n            group d by d into g\n            select new {g.Key, Count = g.Count()};\n\nint MostAppearingMonthAmount = query.Max(g => g.Count);\n\nIEnumerable<string> MostAppearingMonth = query\n                                      .Where(g => g.Count == MostAppearingMonthAmount)\n                                      .Select(g => g.Key);	0
29236443	29236237	REGEX for only 'GO' on a line	Regex regex = new Regex(@"^go\s*$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline);\n        foreach(Match match in regex.Matches(input))\n        {\n            ...\n        }	0
31558743	31558575	Is there a more popular way of checking if there are results found in a database	public bool CheckForFieldViewByFieldIDIPAndUser( int fieldID, string ip, string userID )\n{\n    return this.context.FieldViewers.FirstOrDefault( x => \n        x.Field.FieldID == fieldID &&\n        x.Viewer.IPAddress == ip &&\n        x.Viewer.User.Id == userID )!= null;\n}	0
29260037	29258983	Recursively adding values to own parent in a recursive List<T>	public class TransformedData\n{\n    public string Id { get; set; }\n    public string ParentId { get; set; }\n    public string Description { get; set; }\n    public double CurrentYear { get; set; }\n    public double RenameThisProperty\n    {\n        get\n        {\n            return CurrentYear + Children.Sum(child => child.RenameThisProperty);\n        }\n    }\n    public List<TransformedData> Children { get; set; }\n\n    public TransformedData()\n    {\n        this.Children = new List<TransformedData>();\n    }\n}	0
9672577	9672112	Read data from Excel files	using Excel = Microsoft.Office.Interop.Excel;\nExcel.Application xlApp = new Excel.Application();\nExcel.Workbook xlWorkbook = xlApp.Workbooks.Open("somefile.xls");\nExcel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet\nExcel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range\nint value = 0;\nif(Int32.TryParse(xlRange.Cells[1,6].Value2.ToString(), out value)) // get the F cell from the first row\n{\n   int numberOfColumnsToRead = value * 4;\n   for(int col=7; col < (numberOfColumnsToRead + 7); col++)\n   {\n      Console.WriteLine(xlRange.Cells[1,col].Value2.ToString()); // do whatever with value\n   }\n}	0
18483235	18482325	WndProc capture shift+left mouse double click	protected override void WndProc(ref Message m)\n    {\n        const int WM_LBUTTONDBLCLK = 0x0203;\n        switch (m.Msg)\n        {\n            case WM_LBUTTONDBLCLK:\n                {\n                    if (Control.ModifierKeys.HasFlag(Keys.Shift))\n                    { \n                        //Shift plus mouse left button double clicked\n                    }\n                    break;\n                }\n        }\n        base.WndProc(ref m);\n    }	0
12467886	12467557	Multiple Columns in listview	lstView.View = View.Details;	0
33261934	33261012	How to deselect ListViewItem programmatically?	private void myList_ItemClick(object sender, ItemClickEventArgs e)\n{\n    Debug.WriteLine("Clicked item");\n    ListView list = sender as ListView;\n    ListViewItem listItem = list.ContainerFromItem(e.ClickedItem) as ListViewItem;\n\n    if (listItem.IsSelected)\n    {\n        listItem.IsSelected = false;\n        list.SelectionMode = ListViewSelectionMode.None;\n    }\n    else\n    {\n        list.SelectionMode = ListViewSelectionMode.Single;\n        listItem.IsSelected = true;\n    }\n}	0
26997262	26997207	Perform Multiple Async Method Calls Sequentially	var t1 = DoTaskAsync(...);\nvar t2 = DoTaskAsync(...);\nvar t3 = DoTaskAsync(...);\n\nawait Task.WhenAll(t1, t2, t3);	0
20142041	20099520	How to find most expensive (highest) distance/path with QuickGraph Library?	public AdjacencyGraph<string, Edge<string>> Graph { get; private set; }\n    public Dictionary<Edge<string>, double> EdgeCost { get; private set; }\n\n    ......\n\n    public void FindPath(string @from = "START", string @to = "END")\n    {\n        Func<Edge<string>, double> edgeCost = AlgorithmExtensions.GetIndexer(EdgeCost);\n        // Positive or negative weights\n        TryFunc<string, System.Collections.Generic.IEnumerable<Edge<string>>> tryGetPath = Graph.ShortestPathsBellmanFord(edgeCost, @from);\n\n        IEnumerable<Edge<string>> path;\n        if (tryGetPath(@to, out path))\n        {\n            Console.Write("Path found from {0} to {1}: {0}", @from, @to);\n            foreach (var e in path) { Console.Write(" > {0}", e.Target); }\n            Console.WriteLine();\n        }\n        else { Console.WriteLine("No path found from {0} to {1}."); }\n    }	0
16227152	16227026	AbandonedMutexException on single instance app	using (var mutex = new Mutex(false, mutexName))\n{\n    if (mutex.WaitOne(0, false))\n    {\n        base.OnStartup(e);\n    }\n    else\n    {\n        MessageBox.Show("app is already open", "Error", MessageBoxButton.OK, MessageBoxImage.Information);\n        Current.Shutdown();\n    }\n}	0
33970617	33970276	Recursion of Palindrome without using auxiliary function?	public static bool IsPalindrome(string value)\n{\n    if (value == null)\n        return false;\n\n    if (value.Length == 0)\n        return true;\n\n    Func<string, int, int, bool> ip = null;\n    ip = (v, sc, ec) =>\n    {\n        if (v[sc] != v[ec])\n            return false;\n\n        if (sc >= ec)\n            return true;\n\n        return ip(v, sc + 1, ec - 1);\n    };\n\n    return ip(value, 0, value.Length - 1);\n}	0
25639136	25638808	How to get data from serial port?	while ((bytesRead = objSerialPort.Read(buffer, 0, buffer.Length)) > 0)\n{\n    var checksum = buffer[bytesRead - 1];\n\n    if (VerifyChecksum(checksum, buffer, bytesRead))  // Check the checksum\n    {\n        DoSomethinWithData(buffer, bytesRead);  // Do something with this bytes\n    }\n}	0
15295124	15288348	NHibernate transaction commit, what will be committed to database?	using (var session = SessionFactory.OpenSession())\n{\n  using (var tx = session.BeginTransaction())\n  {\n      var entity = session.Get<Entity>(id);\n      entity.Property1 = "new value";\n      entity.Property2 = "new value";\n      tx.Commit();\n  }\n}	0
564993	564742	Allowing a title bar double click to maximize a dialog but without max-min buttons	private const int WM_NCLBUTTONDBLCLK = 0xA3;\n\n    protected override void WndProc(ref Message m)\n    {\n        switch (m.Msg)\n        {\n            case WM_NCLBUTTONDBLCLK:\n                if (this.WindowState==System.Windows.Forms.FormWindowState.Maximized)\n                    this.WindowState=System.Windows.Forms.FormWindowState.Normal;\n                else if (this.WindowState == System.Windows.Forms.FormWindowState.Normal)\n                    this.WindowState = System.Windows.Forms.FormWindowState.Maximized;\n                return;\n        }\n        base.WndProc(ref m);\n    }	0
16802652	16802530	how to referece viewmodel properties from separaete class method	public string StatusMessage\n {\n    get { return _statusMessage; }\n    set \n    {\n        _statusMessage = value;\n        RaisePropertyChanged("StatusMessage"); // you need to implement INotifyPropertyChanged\n    }\n}	0
23351403	23351261	How to Split Street Address String and Replace Individual elements	Dictionary<string, string> replacements = new Dictionary<string, string>()\n{\n    { "DRIVE", "DR" }\n};\n\nstring[] tokens = originalAddress.Split(new char[] { ' ', '\t' });\nStringBuilder normalized = new StringBuilder();\n\nforeach (string t in tokens)\n{\n    string rep;\n    bool found = replacements.TryGetValue(t.ToUpper(), out rep);\n\n    if (found)\n    {\n        normalized.Append(rep);\n    }\n    else\n    {\n        normalized.Append(t);\n    }\n    normalized.Append(' ');\n}\n\n// normalized.ToString() contains the normalized address	0
5706523	5706369	How to set a custom position for a MessageBox	var form = new Form\n                       {\n                           StartPosition = FormStartPosition.Manual, \n                           ShowInTaskbar = false,\n                           Location = new Point(100,100)\n                       };\n        form.ShowDialog();	0
29285389	29285175	Check if string is anagram of palindrome	private static bool IsPalindromeAnagram(string test)\n{\n    var charCount = test.GroupBy(c => c, (c, i) => new\n        {\n            character = c,\n            count = i.Count()\n        });\n\n    return charCount.Count(c => c.count % 2 == 1) <= 1;\n}	0
4140818	4140800	Multiple Regex Replacements in C#	public static string ReplaceArticleTextWithProductLinks(string input)\n{\n    string pattern = @"\(\(MY TOPIC ID: ""(.*?)"" ""(.*?)""\)\)";\n    string replacement = "<a href='/post/$1'>$2</a>";\n\n    return Regex.Replace(input, pattern, replacement);\n}	0
21489257	21488518	How to rewrite SQL Union of two tables with Join in LINQ?	var result = allClassAs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, c.IsEmployed})\n                        .Where(r => r.RoleName == "ADMIN")\n                        .Union(allClassBs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, IsEmployed = "-"})\n                        .Where(r => r.RoleName == "ADMIN"));	0
11984398	11984222	How do I convert an image back from it's binary data stored in a database?	context.Response.ContentType = "image/jpeg";\nstrm = new MemoryStream(ar);   // ar here is your variable from Byte[] ar = (Byte[])(dr[1])\nbyte[] buffer = new byte[4096];\nint byteSeq = strm.Read(buffer, 0, 4096);\nwhile (byteSeq > 0)\n{\n    context.Response.OutputStream.Write(buffer, 0, byteSeq);\n    byteSeq = strm.Read(buffer, 0, 4096);\n}	0
28014354	28013797	XAudio2 - Play generated sine, when changing frequency clicking sound	Math.Sin	0
11152777	11152511	How to associate user account to a domain user	public UserAccount GetUserAccount(string username)\n{\n    using (var context = new PrincipalContext(ContextType.Domain))\n    using (var user = UserPrincipal.FindByIdentity(context, username))\n    {\n        return new UserAccount\n        {\n            Id = user.Guid,\n            FullName = user.Name,\n            Password = "FORGET ABOUT IT, YOU CAN'T RETRIEVE THE PASSWORD",\n            EmployeeId = user.EmployeeId\n        };\n    }\n}	0
17862472	17862402	Split a string by a character	string[] strDataArray = FileNameOrginal.Split('-');	0
12034664	12033386	How to break the registry dependency?	public interface IRegistryService {\n    string GetRegistrySubKey(string path);\n}	0
28752396	28752252	Ignoring comments in Nini	result.AcceptCommentAfterKey = false;\nresult.SetCommentDelimiters (new char[] { ';', '#' });	0
26845141	26844119	Operator overloading with == != > <	public static bool operator ==(Rational op1, Rational op2)\n    {\n        return op1.numerator * op2.denominator == op1.denominator * op2.numerator;\n    }\n    public static bool operator !=(Rational op1, Rational op2)\n    {\n        return op1.numerator * op2.denominator != op1.denominator * op2.numerator;\n    }\n    public static bool operator <(Rational op1, Rational op2)\n    {\n        return op1.numerator * op2.denominator < op1.denominator * op2.numerator;\n    }\n    public static bool operator >(Rational op1, Rational op2)\n    {\n        return op1.numerator * op2.denominator > op1.denominator * op2.numerator;\n    }	0
9267513	9267431	Sliding Puzzle Help in random tiles	maxIndex = array.Length - 1\nfor index in 0 to maxIndex - 1\n    swapIndex = random number between index and maxIndex\n    swap (array, index, swapIndex)	0
3310837	3310800	How to make correct date format when writing data to Excel	Range rg = (Excel.Range)worksheetobject.Cells[1,1];\nrg.EntireColumn.NumberFormat = "MM/DD/YYYY";	0
6276904	6276844	Regex extract numer into group	(\d+\.\d+|\d+) star	0
7363758	7363730	Linq on a nested List - select all Id's	Hotels.SelectMany(h => h.RoomType)\n      .Select(rt => rt.Room.Id)\n      .Distinct()\n      .ToArray();	0
3422686	3422475	Find the items matching any condition from the generic list	public  Patient[] GetPatientsBySearchParams(DataPair[] dataPair)\n{      \n  P = lst_Patient.FindAll(\n delegate(Patient tmp){ \n  if(tmp.FirstName = dataPair[0].OutputValue || tmp.LastName = dataPair[1].OutputValue) \n   return true;\n  else \n   return false;\n }\n);\n\nreturn P.ToArray();\n}	0
17633700	17575447	Delete a image, and delete from Image viewer under Win 8	RandomAccessStreamReference rs= RandomAccessStreamReference.CreateFromUri(new Uri(path));\n        BitmapImage bi = new BitmapImage();\n        var rstream = await rs.OpenReadAsync();\n        bitmapImage.SetSource(rstream);\n        pic.Source = bi;	0
1213975	1194527	How to see windows messages of a dialog shown with a second thread?	void Run()\n{\n    using( MyDialog dialog = new MyDialog() )\n    {\n        Application.AddMessageFilter(new MyMessageFilter());\n        Application.Run(dialog); \n    }\n}	0
2637435	2637408	c# rendering html into text	String result = Regex.Replace(your_text_goes_here, @"<[^>]*>", String.Empty);	0
31448326	31359531	How to POST custom object to web api using C#	// strong typed instance\nvar values = new JObject();\nvalues.Add("FirstName", "John");\nvalues.Add("LastName", "Doe");\n\n// this is not set!!!\nHttpContent content = new StringContent(values.ToString(), Encoding.UTF8,"application/json");\n\nvar response = client.PostAsJsonAsync("api/customer/AddNewCustomer", values).Result;	0
2583896	2583882	How to get ip address from .Net code	internal IPAddress[] GetIPAddresses()\n{\n    string hostName = System.Net.Dns.GetHostName();\n    IPHostEntry ihe = System.Net.Dns.GetHostEntry(hostName);\n    return ihe.AddressList;\n}	0
990386	988361	How to remove local tfs content programmatically?	workspace.Get(\n    new string[] {"C:\\LocalPath"},\n    new ChangesetVersionSpec(1),\n    RecursionType.Full,\n    GetOptions.None);	0
2720749	2720648	working with two combo boxes	for (int i = 0; i < comboBox1.Items.Count;i++)\n    {\n        if ((comboBox1.SelectedIndex)!=i)\n        {\n            comboBox2.Items.Add(comboBox2.Items[i]);\n        }\n    }	0
7740380	7740129	Dynamically programming a grid consisting of 64 buttons (8x8)	int ButtonWidth = 40;\n        int ButtonHeight = 40;\n        int Distance = 20;\n        int start_x = 10;\n        int start_y = 10;\n\n        for (int x = 0; x < 8; x++)\n        {\n            for (int y = 0; y < 8; y++)\n            {\n                Button tmpButton = new Button();\n                tmpButton.Top = start_x + (x * ButtonHeight + Distance);\n                tmpButton.Left = start_y + (y * ButtonWidth + Distance);\n                tmpButton.Width = ButtonWidth;\n                tmpButton.Height = ButtonHeight;\n                tmpButton.Text = "X: " + x.ToString() + " Y: " + y.ToString();\n                // Possible add Buttonclick event etc..\n                this.Controls.Add(tmpButton);\n            }\n\n        }	0
7588338	7505515	Any workaround to get text in an iFrame on another domain in a WebBrowser?	foreach (HtmlElement elm in webBrowser1.Document.GetElementsByTagName("iframe"))\n{\n     string src = elm.GetAttribute("src");\n     if (src != null && src != "")\n     {\n          string content = new System.Net.WebClient().DownloadString(src); //or using HttpWebRequest\n          MessageBox.Show(content);\n     }\n}	0
14723849	14707770	Reading XML nodes attribute as per user input	var feeds = from feed in xDoc.Descendants("name")\n                    where feed.Attribute("id").Value.Equals("Test1")\n                    select new\n                    {\n                        fxfv = feed.Attribute("SharepointGroup").Value\n                    };	0
18451350	18451153	Get Row with Min Date in LINQ?	var uniqueGuys = from d in from d in tests.AsEnumerable()\n                 group d by d.ID into g\n                 select g.OrderBy(p => p.DateTime).First();	0
17816491	17814887	How can I check result of adding to a MemoryStream, before adding to the MemoryStream?	var myUrl = "http://www.stackoverflow.com";\nvar encoding = Encoding.UTF8;\n\nXmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.Encoding = encoding;\nvar SOME_MAX_SIZE_IN_BYTES = 1024;\nMemoryStream ms = new MemoryStream();\nfor(var i=0; i<10; i++)\n{\n    using (XmlWriter writer = XmlWriter.Create(ms, settings))\n    {    \n        // CREATE XML WITH STATEMENTS LIKE THIS\n        writer.WriteStartElement("url", myUrl);\n        writer.WriteEndElement();\n        // in order to get a semi-accurate byte count, \n        // you need to force the flush to the underlying stream\n        writer.Flush();\n        var lengthInBytes = ms.Length;\n        if(lengthInBytes > SOME_MAX_SIZE_IN_BYTES)\n        {\n            Console.WriteLine("TOO BIG!");\n            break;\n        }\n    }\n}\n\nvar xml = encoding.GetString(ms.ToArray());\nConsole.WriteLine(xml);	0
26209058	26208514	Adding object to listbox with name attribute	PlayerListBox1.DisplayMember = "Name";\nEnemyListBox1.DisplayMember = "Name";	0
8191706	8190955	LinqDataSource: How to assign values to where parameters in code?	LinqDataSource1.WhereParameters["Key1"].DefaultValue = "1";\nLinqDataSource1.WhereParameters["Key2"].DefaultValue = "2";	0
20385048	20384842	combobox display object children member	this.comboBox1.ItemsSource =\n        optionList.Select(o=> new{option_id = o.option_id, dish_name =o.dish.dish_name}).ToList();\n\nthis.comboBox1.DisplayMember = "dish_name";\nthis.comboBox1.ValueMember = "option_id";	0
22535307	22535102	XmlDocument - SelectSingleNode with namespace	public class Sample\n{\n public static void Main()\n{\n\n  XmlDocument doc = new XmlDocument();\n  doc.Load("booksort.xml");\n\n  //Create an XmlNamespaceManager for resolving namespaces.\n  XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);\n  nsmgr.AddNamespace("bk", "urn:samples");\n\n  //Select and display the value of all the ISBN attributes.\n  XmlNodeList nodeList;\n  XmlElement root = doc.DocumentElement;\n  nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);\n  foreach (XmlNode isbn in nodeList){\n    Console.WriteLine(isbn.Value);\n  }\n\n}\n\n}	0
19923710	19923640	Testing a function that returns IEnumerable<string>	[TestFixture] // NUnit attribute for a test class\npublic class MyTests\n{\n    [Test] // NUnit attribute for a test method\n    public void fetchFilesTest() // name of a method you are testing + Test is a convention\n    {\n        var files = fetchFiles();\n\n        Assert.NotNull(files); // should pass if there are any files in a directory\n        Assert. ... // assert any other thing you are sure about, like if there is a particular file, or specific number of files, and so forth\n    }\n}	0
15873795	15873679	Remove text from a richtext box if checkbox is checked on button click	private void save_button_Click(object sender, EventArgs e)\n{\n    // Add mandatory lines to a string.\n    if (checkBox1.Checked)\n    {\n         // Append optional lines to the string.\n    }\n    else\n    {\n        // Do something.\n    }\n}	0
13164069	13163447	Detecting arrows keys in winforms	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n     if(keyData == Keys.Left)\n     {\n       MessageBox.Show("You pressed Left arrow key");\n       return true;\n     }\n     return base.ProcessCmdKey(ref msg, keyData);\n}	0
25525839	25523357	Rad window icon not displayed on task bar c# wpf	private void MainWindow_Loaded(object sender, RoutedEventArgs e)\n    {\n        Window window = (sender as RadWindow).ParentOfType<Window>();            \n        if (window != null)\n        {\n            window.ShowInTaskbar = true;\n            window.Icon = BitmapFrame.Create(new Uri("pack://application:,,,/Screener;Component/Images/Screener1.ico", UriKind.RelativeOrAbsolute));\n        }\n        throw new NotImplementedException();\n    }	0
6002410	6002367	How do you iterate through the member variables of an object?	Public Sub DoLoad() \n\n        Dim controls = Me.GetType.GetFields(BindingFlags.Instance Or BindingFlags.NonPublic) _\n             .Where(Function(f) f.FieldType.IsSubclassOf(GetType(AresControl))) _\n             .Select(Function(f) f.GetValue(Me)).Cast(Of AresControl)()\n\n        For Each c In controls\n            Me.Controls.Add(c)\n        Next\nEnd Sub	0
7259318	7259247	How to wait until stream write is done	stream.Write(chunk, \\other params)	0
19582571	19578754	How to get a collection from a linking table Fluent NHibernate	HasManyToMany(user => user.Permissions)\n    .Table("UserPermissions")\n    .ParentKeyColumn("user_id")\n    .ChildKeyColumn("permission_id");	0
21502076	21501264	How to update related entity also when updating one with Attach in EF5?	if (vm.ListAliases != null)\n{\n    foreach (var item in vm.ListAliases )\n    {\n        var eAlias = new PlayerAliases() { CodPlayerAlias = item.CodPlayerAlias };\n        db.PlayerAliases.Attach(eAlias);\n        eAlias.Column1 = item.Column1;\n        eAlias.Column2 = item.Column2;\n    }\n}	0
664048	664031	What's the best way to let a user pick a subdirectory in C#?	// Sets "My Documents" as the initial folder path\nstring myDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\nFolderBrowserDialog1.SelectedPath = myDocsPath;	0
7022281	7021121	Facebook C# SDK + get user's LIKE	var client = new FacebookClient();\ndynamic result = client.Get("me/likes");	0
3139278	3139118	How to initialize a C# string list (List<string>) with many string values	List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });	0
21380706	21302218	Loading NonZero Balance Account in to DevExpress Tree list	Loading NonZero Balance Account in to DevExpress Tree list	0
7476983	7476923	Create file export and save from ASP.NET page	protected void btnExportToExcel_Click(object sender, EventArgs e)    \n{\n        Response.Clear();\n        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");\n\n        Response.Charset = "";         \n        Response.ContentType = "application/vnd.xls";\n        System.IO.StringWriter stringWrite = new System.IO.StringWriter();        \n        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);\n        GridView1.RenderControl(htmlWrite);        \n        Response.Write(stringWrite.ToString());\n        Response.End();\n}	0
13029703	13029543	How insert multiline text into a RichTextBox?	var text = "Line1" + Environment.NewLine + "Line2"\nrichTextBox.Control.Selection.Text = text;	0
34117964	34117789	Split string into struct	List<ParkTime> parktimes = new List<ParkTime>();\nforeach (string line in File.ReadLines("file.txt"))\n{\n    bool isValid = true;\n    string[] times = line.Split(',');  \n    DateTime dtInit;\n    if(!DateTime.TryParseExact(times[0].Trim(), "HH:mm", \n        System.Globalization.CultureInfo.InvariantCulture,\n        System.Globalization.DateTimeStyles.NoCurrentDateDefault,\n        out dtInit))\n        isValid = false;\n\n    DateTime dtEnd;\n    if (!DateTime.TryParseExact(times[1].Trim(), "HH:mm",\n        System.Globalization.CultureInfo.InvariantCulture,\n        System.Globalization.DateTimeStyles.NoCurrentDateDefault,\n        out dtEnd))\n        isValid = false;\n\n    if (isValid)\n        parktimes.Add(new ParkTime() { startTime = dtInit, endTime = dtEnd });\n}\n\npublic struct ParkTime\n{\n    public DateTime startTime { get; set; }\n    public DateTime endTime { get; set; }\n}	0
5248459	5248412	How to use Reflection to retrieve a property?	Type t = typeof(MyType);\nPropertyInfo pi = t.GetProperty("Foo");\nobject value = pi.GetValue(null, null);\n\nclass MyType\n{\n public static string Foo\n {\n   get { return "bar"; }\n } \n}	0
31359140	31351932	Get Thumbnail from mp3 file in c# xaml for windows phone 8.1	var filestream = await receivedFile.OpenStreamForReadAsync();\n            var tagFile = File.Create(new StreamFileAbstraction(receivedFile.Name, filestream, filestream));\n            var tags = tagFile.GetTag(TagLib.TagTypes.Id3v2);\n            var bin = (byte[])(tags.Pictures[0].Data.Data);\n            MemoryStream ms = new MemoryStream(bin);\n           await bitmapImage.SetSourceAsync(ms.AsRandomAccessStream());\nAlbumArt.Source=bitmapImage;	0
11033049	11032928	Query which returns results only if all (non-primitive) values from a compared enumerable are contained in the target enumerable	var requiredIds = RequiredProps.Select(y => y.ID);\n\nvar result = ctx.Units\n                .Where(m => !requiredIds\n                    .Except(m.UnitProps.Select(x => x.Prop.ID)))\n                    .Any())\n                 .ToList();	0
20660535	20660208	LINQ Query with Hashsets from Entity Data Model	var permissions = Context.Users\n    .Where(u => u.UserName == "admin")\n    .SelectMany(u => u.Role)\n    .SelectMany(r => r.Permission)	0
11027433	11027369	How to correctly handle adding new item to dictionary?	public static bool TryAddCacheItem(string key, object data)\n{\n    locker.EnterWriteLock();\n    try\n    {\n        if (cacheItems.ContainsKey(key))\n        {\n            return false;\n        }\n        cacheItems.Add(key, data);\n        return true;\n    }\n    finally\n    {\n        locker.ExitWriteLock();\n    }\n}	0
22325798	22309646	How to remove elements from a document?	foreach (Paragraph P in D.Descendants<Paragraph>()\n         .Where(o=>o.Descendants<Run>().Count() ==0).ToList()	0
15020644	14978612	Get Profile picture using SKYPE4COM	var cmd = new SKYPE4COMLib.Command();\ncmd.Command = string.Format("GET USER {0} AVATAR 1 {1}", userHandle, rootedPathFileName);\nvar skype = new SKYPE4COMLib.Skype();\nskype.SendCommand(cmd);	0
16777518	16763936	Determining starting points of accumulation points	var mostFrequentlyUsedEntriesOfList = inputList\n    .GroupBy(word => word)\n    .Select(wordGroup => new\n    {\n        Word = wordGroup.Key,\n        Frequency = wordGroup.Count(),\n        Position = Enumerable.Range(0, inputList.Count())\n            .OrderByDescending(index => inputList.Skip(index).TakeWhile(current => current == wordGroup.Key).Count())\n            .First() + 1\n    })\n    .OrderByDescending(word => word.Frequency);	0
28475595	28296643	How to get the value of root element (without .Net 4)	static void Main(string[] args) \n{ \n    XmlDocument xdoc = new XmlDocument(); \n    xdoc.Load(@"C:\Temp\emi20154a.xml"); \n    string root_attribure1 = xdoc.DocumentElement.Attributes[0].Value;\n    string root_attribure2 = xdoc.DocumentElement.Attributes[1].Value; \n\n    Console.WriteLine("root_attribure1" + root_attribure1); \n    Console.WriteLine("root_attribure2" + root_attribure2); \n\n    Console.ReadLine(); \n}	0
15998176	15994324	N-tier application configurations retrive/store	.config	0
18120558	18119900	WPF ListBox bind ItemsSource with MVVM-light	public ObservableCollection<Files> Filescollection {get;set;}\n\npublic MainViewModel()\n{\n    this.Filescollection = new ObservableCollection<Files>();\n    SelectFilesAction();\n}\n\nprivate void SelectFilesAction()\n{\n   Filescollection.Add(new Files { Name = "index.html", Path = "C:\\Files"});\n}	0
16839943	16839568	MVVM - A few questions on Models and ViewModels	private DateTime _Date;\npublic DateTime Date\n{\n   get { return _Date; }\n   set \n   { \n      if (value != _Date)\n      {\n         _Date = value;\n         RaisePropertyChanged(() => Date);\n      }\n   }\n}	0
10473652	10469722	How can I insert hard newlines into text where the text wraps in a window?	int width = txtBox.width;\nGraphics g = CreateGraphics();\n\nSizeF size = g.MeasureString(myText, txtBox.Font);\n\nif (size.Width > width)\n{\n    int i = 0;\n    List<string> lines = new List<String>();\n    string str = "";\n    while (i<myText.Length)\n    {\n\n        str = str + myText.SubString(i,1);\n        int w = (int)(g.MeasureString(str, txtBox.Font).Width);\n        while (w<width && i<myText.Length)\n        {\n             i++;\n             str = str + myText.SubString(i,1);\n        }\n        str = str + '\n';\n    }\n\n    // str now contains your newline formatted string\n    return str;\n}\nreturn myText;	0
18401918	18401786	c# add a PayPal donate button in application	private void btnDonate_Click(object sender, System.EventArgs e)\n{\n    string url = "";\n\n    string business     = "my@paypalemail.com";  // your paypal email\n    string description  = "Donation";            // '%20' represents a space. remember HTML!\n    string country      = "AU";                  // AU, US, etc.\n    string currency     = "AUD";                 // AUD, USD, etc.\n\n    url += "https://www.paypal.com/cgi-bin/webscr" +\n        "?cmd=" + "_donations" +\n        "&business=" + business +\n        "&lc=" + country +\n        "&item_name=" + description +\n        "&currency_code=" + currency +\n        "&bn=" + "PP%2dDonationsBF";\n\n    System.Diagnostics.Process.Start(url);\n}	0
26628408	26624306	How to Create a Issue into JIRA thorugh REST api?	Old Url: https://MyCompany.atlassian.net/rest/api/2/issue\nnew url: https://MyCompany.atlassian.net/rest/api/latest/issue	0
18602223	18601822	Binding an ObservableCollection to a DataGrid	public string FileName {\n        get { return fileName; }\n        set\n        {\n            fileName = value;\n            OnPropertyChanged("FileName");\n        }\n    }\n\n public string Path { get;  set; }\n public string Extension { get;  set; }	0
20611989	20500042	Find Control in DataTemplate with a multi selection listbox	IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"	0
6562542	6562503	how to convert string to variable,vb6/ c#/c++?	MyNamespace.MyClass cls = new MyNamespace.MyClass();\nFieldInfo fi = cls.GetType().GetField("FieldName");\nstring value = (string)(fi.GetValue(null, null));\nConsole.Out.WriteLine(value);	0
22019661	18326883	windows phone GPS tutorial showing wrong location	LongitudeTextBlock.Text += e.Position.Location.Longitude.ToString("0.000");	0
140801	140329	How can I redirect to a page when the user session expires?	public void Session_OnStart()\n    {\n        if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null)\n        {\n            HttpContext.Current.Response.Redirect("SessionTimeout.aspx")\n        }\n\n    }	0
33376871	33376627	How to join two objects into array?	var r= new []{op1,op2};	0
31243631	31209860	CheckBoxList Datasource won't set in Program Launch.	foreach (var variable in fileQuery)\n{\n    chkListBox.Items.Add(variable);\n}	0
17367241	17357760	How can I generate a random BigInteger within a certain range?	public static BigInteger RandomIntegerBelow(BigInteger N) {\n    byte[] bytes = N.ToByteArray ();\n    BigInteger R;\n\n    do {\n        random.NextBytes (bytes);\n        bytes [bytes.Length - 1] &= (byte)0x7F; //force sign bit to positive\n        R = new BigInteger (bytes);\n    } while (R >= N);\n\n    return R;\n}	0
21372633	21372439	Regular expression find group match in quotes	public static void ExtractGroup()\n{\n    string input = "Transfer assignee from 'David, Patricia' to '' Transfer group from 'Science Department - Support Group' to 'Science Department - Human Resources '";\n    var match = Regex.Match(input, @" group from '(?<from>[^']*)' to '(?<to>[^']*)'", RegexOptions.IgnoreCase);\n\n    if (match.Success)\n    {\n        Console.WriteLine(match.Groups["from"]); // Science Department - Support Group\n        Console.WriteLine(match.Groups["to"]); // Science Department - Human Resources\n    }            \n}	0
20976505	20950927	To get the data from the list into JSON format	System.Collections.Generic.List<object> dataList = new System.Collections.Generic.List<object>();\nfor (int k = 0; k < 4; k++)\n        {\n            List<HMData> Data_Content = new List<HMData>();\n            for (int l = 0; l < 7; l++)\n            {\n\n                Value_LfromList = LValues.ElementAt((k * 7) + l);\n                Value_IfromList = IValues.ElementAt((k * 7) + l);\n                Value_BfromList = BValues.ElementAt((k * 7) + l);\n                Data_Content.Add(new HMData { x = Value_LfromList, y = Value_IfromList, z = Value_BfromList });\n            }\n            dataList.Add(new {data = Data_Content});\n        } \n  var chart = new\n        {\n            type = ChartType\n        };\nvar series = dataList;\nvar obj = new { chart, series };\nstring result = jSearializer.Serialize(obj);	0
22517123	22509750	Textbox displays line break before plus sign	using System;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nnamespace myNamespace\n{\n    class MyTextBox : TextBox\n    {\n        const int EM_SETWORDBREAKPROC = 0x00D0;\n        const int EM_GETWORDBREAKPROC = 0x00D1;\n\n        delegate int EditWordBreakProc(string lpch, int ichCurrent, int cch, int code);\n\n        protected override void OnHandleCreated(EventArgs e)\n        {\n            base.OnHandleCreated(e);\n            if (!this.DesignMode)\n            {\n                SendMessage(this.Handle, EM_SETWORDBREAKPROC, IntPtr.Zero, Marshal.GetFunctionPointerForDelegate(new EditWordBreakProc(MyEditWordBreakProc)));\n            }\n        }\n\n        [DllImport("User32.DLL")]\n        public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\n        int MyEditWordBreakProc(string lpch, int ichCurrent, int cch, int code)\n        {\n            return 0;\n        }\n    }\n}	0
7201284	7201098	How to Make Tab index work for Radio Buttons which are in same group?	function toggle(obj) {\n    if (obj.value == "Radio1") {\n        document.getElementById('ctl00_ContentPlaceHolder1_Radio2').checked = false;\n    }\n    else if (obj.value == "Radio2") {\n        document.getElementById('ctl00_ContentPlaceHolder1_Radio1').checked = false;\n    }\n}	0
26047766	26046441	Current user in owin authentication	identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));	0
10242703	10235750	How to get values for child objects using Dapper ORM?	var sql = \n@"\nselect * from PROFILES where profileId= @id\nselect * from PROFILEIMAGES where OWNER_PROFILESIDFK = @id";\n\nusing (var multi = connection.QueryMultiple(sql, new {id=selectedId}))\n{\n   var profile = multi.Read<Models.PROFILE>().Single();\n   profile.ProfileImages = multi.Read<Model.PROFILEIMAGES>().ToList();\n}	0
2183706	2183685	RegEx help matching operators	(<=|>=|!=|=|>|<)	0
32661456	32661309	Emojis in XAML & C# on WP8.1 with longer Unicode range	"\U0001F620"	0
30585579	30585483	Cannot set an object to null inside a method	class Program\n{\n    static void Main(string[] args)\n    {\n        Foo foo = new Foo();\n        SetNull(foo);\n\n        Console.WriteLine(foo.ID);// print 2\n    }\n\n    private static void SetNull(Foo foo)\n    {\n        foo.ID = 2;\n        foo = null;\n    }\n}\n\n\nclass Foo\n{\n    public int ID { get; set; }\n}	0
10855731	10855667	Dynamic text box vanishing if another button or link button clicked	DropDownList1.Text.Equals("OFF")	0
18488151	18482985	autofac configuration for strategy factory pattern (resolve already happened)	var builder = new Autofac.ContainerBuilder();\nbuilder.RegisterType<StrategyA>().As<IProcessor>().Keyed<IProcessor>(typeof(ItemA).Name).InstancePerDependency();\nbuilder.RegisterType<StrategyB>().As<IProcessor>().Keyed<IProcessor>(typeof(ItemB).Name).InstancePerDependency();\nbuilder.Register<Func<string, IProcessor>>(c => {\n    var ctx = c.Resolve<IComponentContext>();\n    return (s) => ctx.ResolveKeyed<IProcessor>(s);\n});\nbuilder.RegisterType<MyServiceConsumer>().As<IConsumer>();\n\nvar container = builder.Build();\n\nvar consumer = container.Resolve<IConsumer>().DoStuff(new ItemB()).Dump();	0
30520603	30520442	Convert SQL datetime to C# string	loan._ReturnDate = ((DateTime)dar["ReturnDate"]).ToString();	0
22550937	22550738	How to get json string from the url?	var json = new WebClient().DownloadString("url");	0
24470482	24468526	Dynamically load a new user control with an on click in a WPF	namespace WpfApplication1\n{\n    /// <summary>\n    /// Interaction logic for MainWindow.xaml\n    /// </summary>\n    public partial class MainWindow : Window\n    {\n        public MainWindow()\n        {\n            InitializeComponent();\n        }\n        private void button_clicked(object sender, RoutedEventArgs e)\n        {\n            var btn = (Button) sender;\n            Type newType = Type.GetType("WpfApplication1."+ btn.Name, true, true);\n\n            object o = Activator.CreateInstance(newType);\n            StkPanel.Children.Add((UIElement) o);\n        }\n    }\n}	0
9462574	9156835	Further Command line arguments from c# to an external exe	Process p = new Process();     \np.StartInfo.FileName = "something.exe"; \np.StartInfo.Arguments = "a b"; \n\n**p.StartInfo.UseShellExecute = false;**    \n**p.StartInfo.RedirectStandardInput = true;**\n\np.Start(); \n\n**p.StandardInput.WriteLine("c");** \n**p.StandardInput.WriteLine("d");**\n\np.WaitForExit(); \np.Close();	0
21953144	21946654	How to read/save data from/to XML from/to DataGridView (with no DataSource, only columns set by me)?	myDataGridView.AutoGenerateColumns = true;\nmyDataGridView.DataSource = myList;	0
2032288	2032283	Find the length of only the first dimension in a multi-dimension array	Matrix.GetLength(0)	0
27899849	27899346	Combine multiple picturebox into one retaining its position	Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);\n\n        pictureBox1.DrawToBitmap(bmp, new Rectangle(0,0,pictureBox1.Width, pictureBox1.Height));\n        pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - pictureBox1.Location.X, pictureBox2.Location.Y - pictureBox1.Location.Y, pictureBox2.Width, pictureBox2.Height));\n        pictureBox3.DrawToBitmap(bmp, new Rectangle(pictureBox3.Location.X - pictureBox1.Location.X, pictureBox3.Location.Y - pictureBox1.Location.Y, pictureBox3.Width, pictureBox3.Height));\n\n        bmp.Save(@"C:\Temp\output.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);	0
1447396	1442591	how to overwrite the timezone of the server in a sub application	DateTimeFormatInfo dtfi = new DateTimeFormatInfo();\ndtfi.FullDateTimePattern = "yyyy-MM-ddTHH:mmzzz";\nDateTime s = DateTime.Parse(inputstring, dtfi);\ns = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(s, "AUS Eastern Standard Time");\nTimeZoneInfo tzz = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");\nstring timezone = (tzz.IsDaylightSavingTime(s)) ? tzz.DaylightName : tzz.StandardName;\n\nCultureInfo  culture = CultureInfo.CreateSpecificCulture("en-AU");\nstring output = String.Format("{0} | {1}", s.ToString("f", culture), timezone);	0
33458152	33458082	How to Execute UpdateAsync with Where statement	var updateFlagLog = await con.FindAsync<logon>(u => u.log == 1);\n    if (updateFlagLog != null)\n    {\n         // TODO do the changes you need to updateFlagLog\n\n         // Update the object\n         await con.UpdateAsync(updateFlagLog);\n    }	0
19463177	19463099	Exclude a column from a select using LINQ	var users = from u in context.Users\n\n        where u.UserId == userId\n\n        select u.UserId, u.Watever, etc... ;	0
8973555	8973400	How can I uppercase the first letter of all words in my string?	List<string> cities = new List<string>();\n\nforeach (DataRow row in dt.Rows)\n{\n    string city = row[0].ToString();\n    cities.Add(String.Concat(Regex.Replace(city, "([a-zA-Z])([a-zA-Z]+)", "$1").ToUpper(System.Globalization.CultureInfo.InvariantCulture), Regex.Replace(city, "([a-zA-Z])([a-zA-Z]+)", "$2").ToLower(System.Globalization.CultureInfo.InvariantCulture)));\n\n}\n\nreturn cities;	0
11360614	11360574	LINQ to XML - Update and save a node to XML file	xmlDocuments.Save(filePath);	0
11526947	11526453	Generate Visio compatible XML (VDX) with ASP.NET	System.Xml	0
32287201	32286400	How to store a video file in exe file in c# and play it	private void Form_Load(object sender, EventArgs e)\n{\n    var file=System.IO.Path.Combine(Application.StartupPath, "YourFileName.wmv");\n    if (!System.IO.File.Exists(file))\n        System.IO.File.WriteAllBytes(file, Properties.Resources.YourFileName);\n\n    this.axWindowsMediaPlayer1.URL = file;\n    this.axWindowsMediaPlayer1.Ctlcontrols.play();\n}	0
11277378	11172160	Ideas on building an indented structure from a List?	var sb = new StringBuilder();\nList<Person> list = GetTheList();\nint cnt = 0;\n// The loop is necessary to iterate over the root elements.\nwhile (list.Count > 0)\n{\n    BuildTree(sb, list, 0, ++cnt, string.Empty);\n}\n\nreturn sb.ToString();\n\n\nprivate void BuildTree(StringBuilder sb, List<Person> list, int currIndex, int count, string parentId)\n{\n    string currId = parentId == string.Empty ? count.ToString() : parentId + "-" + count;\n    sb.Append(currId + "<br />");\n\n    if (list.Count > 1)\n    {\n        if (list[currIndex + 1].Position == list[currIndex].Position)\n        {\n            BuildTree(sb, list, currIndex + 1, count + 1, parentId);\n        }\n\n        if (list[currIndex + 1].Position > list[currIndex].Position)\n        {\n            BuildTree(sb, list, currIndex + 1, 1, currId);\n        }\n    }\n\n    list.RemoveAt(currIndex);\n}	0
2691641	2691585	How to get new logs in an EventLogEntyCollection?	WqlEventQuery wqlQuery = new WqlEventQuery(...);\nManagementEventWatcher watcher = new ManagementEventWatcher(wqlQuery);\nwatcher.EventArrived += new EventArrivedEventHandler(_Your_Event_Handler_);\nwatcher.Start();\n\n// Do stuff.\n\nwatcher.Stop();	0
22194334	22193950	Copy list of of objects to another list of another objects within another object	res.Accounts = new List<AccountsList>();\n    foreach (var item in lstAccnts)\n    {\n\n        res.Accounts.Add( new AccountsList(){AccountId =item.AccountId});    \n\n    }	0
25410108	25409825	Assessing Xml node values with xmlnamespace	XDocument xDoc = XDocument.Load(filename);\nXmlNamespaceManager namespaceManager = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);\nnamespaceManager.AddNamespace("shl", "http://www.shl.com");\n\nvar child1 = xDoc.XPathSelectElement("//shl:Scale[@Tag='SHL_VAT_GENERAL_ABILITY_SCREEN_SCORE']/shl:Values/shl:Value", namespaceManager);	0
7724592	7721261	Convert JSON File to C# Object	public Dictionary<string, List<WGS84Coordinate>> DesrialiseForMe(string jsonString)\n{\n    JavaScriptSerializer _s = new JavaScriptSerializer();\n    Dictionary<string, List<WGS84Coordinate>> my_object = _s.Deserialise<Dictionary<string, List<WGS84Coordinate>>>(jsonString);\n    return my_object;\n}	0
9758852	9758402	how to know exact number of elements in C# List collection	var Photos = new List<Photo>(); \n\nforeach (var image in Images) \n{ \n   if(image != null && image.ContentLength > 0)\n   {\n      Photo p = new Photo(); \n      p.ImageMimeType = image.ContentType; \n      p.ImageData = new byte[image.ContentLength]; \n      image.InputStream.Read(p.ImageData, 0, image.ContentLength); \n\n      Photos.Add(p); \n   }\n}	0
869276	869238	Use XslCompiledTransform with cdata-section-elements	XmlWriter results = XmlWriter.Create(new StringWriter(sb), t.OutputSettings);\n//---------------------------------------------------------^^^^^^^^^^^^^^^^	0
9211447	9210899	Trigger UpdatePanel from Dropdownlist in ChildControl	dropDown1.Attributes["onchange"] =   \nPage.ClientScript.GetPostBackEventReference(ParentUpdatePanel, "") + "; return false;";	0
23823151	23823103	Default value in mvc model using data annotation	public class YOURMODEL\n{\n    public int MyId { get; set; }  \n\n    public YOURMODEL()\n    { \n        MyId = 1;       \n    }\n}	0
16548272	16547741	C# Input string was not in a correct format int32	public class InputCapture\n{\n    public string Attribute { get; set; }\n    public int Value { get; set; }\n}\n\npublic class InputParser\n{\n    const string pattern = @"(\w)(\d+)";\n    private static readonly Regex Regex = new Regex(pattern);\n\n    public IEnumerable<InputCapture> Parse(string input)\n    {\n        var inputs = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);\n        var parsedInputs = inputs.Where(i => Regex.IsMatch(i))\n                             .Select(i => Regex.Match(i))\n                             .Select(r =>\n                                new InputCapture\n                                    {\n                                        Attribute = r.Groups[1].Value,\n                                        Value = int.Parse(r.Groups[2].Value)\n                                    });\n\n        return parsedInputs;\n    }\n}	0
33981155	33978603	Using property setting to make additions and retrieval	class Calculation\n{\n\n    public double Amount { get; set; }\n\n    public double run(double y)\n    {\n        // No need to start at 1000.\n        for(int i = 0; i < 300; i++)\n        {\n            Amount += y;\n        }\n        return Amount;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Calculation calculation = new Calculation();\n        // pass your variable as a parameter into a class function.\n        var y = 30.0;\n        Console.WriteLine(calculation.run(y).ToString());\n        //  Console.ReadLine(); use control F5 to prevent console window from closing.\n    }\n}	0
17455622	17455415	Letting the user specify a point on the screen	using (var g = Graphics.FromHwnd(IntPtr.Zero))\n{\n    g.DrawLine(SystemPens.WindowText, 0, 0, 200, 200);\n}	0
22307109	22306989	How do I add the days to a date?	DateTime startDate = DateTime.Parse(txtDateTime.Text);\nint daysToSpend = int.Parse(txtNights.Text);\nDateTime endDate = startDate.AddDays(daysToSpend);	0
1069510	1069426	How can I add OrderBy to this LINQ statement?	// Move this to after the select...\n.OrderBy(pi => pi.DisplayOrder);	0
9947429	9947227	How control specific properties of GridView cells	// Evaluate in the row data bound event.\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            // Evaluate if yes then do whatever you want with the rendered text.\n            if (e.Row.Cells[3].Text == "Yes") {\n                e.Row.Cells[3].Text = string.Format("<span class='bold red'>{0}</span>", e.Row.Cells[3].Text);\n            }\n        }	0
20735126	20735085	Preventing GC from taking my delegate in C#	private static CallbackFunc _callback = new CallbackFunc(MyCallbackFunc);\n\npublic static bool startIFStream(int radioHandle)\n{\n\n\n   bool bStarted = CodecStart(radioHandle, _callback, IntPtr.Zero);\n   return bStarted;\n}	0
21315187	21314259	How to only replace all hyphens after 2nd instance	int firstHyph = all.IndexOf('-'); // find the first hyphen\nint secondHyph = all.IndexOf('-', firstHyph + 1); // find the second hyphen\nvar sb = new StringBuilder(all);\nsb[secondHyph] = '#'; // replace the second hyphen with some improbable character\n// finally, replace all hyphen and whatever you need and change that \n// "second hyphen" (now sharp) to whatever you want\nvar result = sb.ToString().Replace("-", " ").Replace("#", ",");	0
6632946	6454385	How To Update A ListView From A WCF Service?	myListBox.BeginInvoke(new MyDelegate(DelegateMethod), "hi there");\n\npublic void DelegateMethod(ListView myControl, string message)\n{\n   myControl.Items.Add (message);\n}	0
26892934	26892849	Connection String to MySQL Database on LAN Setup	string sConnection = @"Server=192.168.0.1; Port=3306; Database=some_database; Uid=root; Pwd=genericpassword;";	0
8734180	8734110	How to get most presented items in a List of c#?	var MostCommonItem = list.GroupBy(item => item)\n                         .OrderByDescending(g => g.Count())\n                         .Select(g => g.Key).First();	0
11689837	11689780	Set button controls as minimize/maximize/close buttons in NavigationWindow application?	// MainWindow window = new MainWindow();\nthis.WindowState = WindowState.Minimized;	0
23583363	23583339	is a namespace but is used like a 'type'	namespace studentdb\nusing (var context = new studentdb())	0
12017988	12017200	Correction in the following delegate and method for invoking a control	ListView listItems = new ListView();\\In global scope\n\nforeach (ListViewItem item in bufferedListView1.Items)\n{\n   listItems.Items.Add((ListViewItem)item.Clone()); // Copied the bufferedListview's items that are to be accessed in other thread to another listview- listItems\n}	0
19714345	19714280	Return sum of a column using ASP.NET WEB Services	cnMySQL.Open();\nstring sum = mySqlcommand.ExecuteScalar();\ncnMySQL.Close();\nreturn sum;	0
26382248	26375294	Drawing inside a window doesn't redraw and smears	protected override void WndProc(ref Message m)\n    {\n        base.WndProc(ref m);\n\n        switch(m.Msg)\n        {\n            case 0x85: // WM_CPAINT\n            case 0xf:  // WM_PAINT\n            {\n                g = Graphics.FromHwnd(this.Handle);\n                Rectangle r = GetWndRect(this.Handle);\n                g.DrawRectangle(p, r);\n                Trace.WriteLine("WM_PAINT: "+r.ToString());\n            }\n            break;\n\n            case 0x05: // WM_SIZE\n            {\n                InvalidateRect(this.Handle, IntPtr.Zero, true);\n                Trace.WriteLine("WM_SIZE");\n            }\n            break;\n\n            default:\n                Trace.WriteLine("0x" + m.Msg.ToString("X"));\n            break;\n        }\n    }	0
11187159	11187052	ICommand method execute parameter value	Command="{Binding CalculateCommand}" CommandParameter="LCM"/>	0
25132267	25115534	Connection must be valid and open to rollback transaction int C# and MySql DB	MySqlCommand.CommandTimeout=1200	0
10204137	10188050	Seeking for a line i a text file	public string ReadLastLine(string path)\n        {\n            string returnValue = "";\n            FileStream fs = new FileStream(path, FileMode.Open);\n            for (long pos = fs.Length - 2; pos > 0; --pos)\n            {\n                fs.Seek(pos, SeekOrigin.Begin);               \n                StreamReader ts = new StreamReader(fs);\n                returnValue = ts.ReadToEnd();\n                int eol = returnValue .IndexOf("\n");\n                if (eol >= 0)\n                {                    \n                    fs.Close();\n                    return returnValue .Substring(eol + 1);\n                }                \n            }\n            fs.Close();\n            return returnValue ;\n        }	0
16062011	16061447	Getting list of conflicting files after failed TFS check-in	int changesetId = 0;\ntry {\n    changesetId = workspace.CheckIn(PendingChanges);\n} catch(CheckinException exception) {\n    Console.WriteLine(exception);\n    return;\n} catch(VersionControlException exception) {\n    Console.WriteLine(exception);\n    return;\n}\n\nif(changesetId <= 0) {\n    Console.WriteLine("Unknown CheckIn error. Changeset id 0 returned");\n    return;\n}	0
29453834	29453818	How do I make Variable available for every function within the same Window	namespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        //This int and List will be accessible from every function within the Form1 class\n        int myInt = 1;\n        List<string> myList;\n\n        public Form1()\n        {\n            InitializeComponent();\n            myList = new List<string>(); //Lists must be initialized in the constructor as seen here - but defined outside the constructor as seen above\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            myInt = 1; //This function can access the int\n            myList.Add("new item"); //This function can access the list\n        }\n\n        private void button2_Click(object sender, EventArgs e)\n        {\n            myInt = 0; //This function can also access the int\n            myList.Clear(); //This function can also access the list\n        }\n    }\n}	0
31763192	31762085	Display Recipe Name based on ID MVC4	var query1 = from r in db.MyRecipe\n             join c in db.Cuisine\n            on c.Id equals r.Id\n\n select new MyViewModel()\n  {\n       CuisineName = c.Name\n       Price = r.Name,\n       ........\n  };	0
14927965	14904171	Read xml from URL	namespace wfats2\n\n{\n\n  public partial class Form1 : Form\n\n{\n\n public Form1()\n\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n\n            XmlDocument doc1 = new XmlDocument();\n            doc1.Load("http://api.wunderground.com/api/your_key/conditions/q/92135.xml");\n            XmlElement root = doc1.DocumentElement;\n            XmlNodeList nodes = root.SelectNodes("/response/current_observation");\n\n            foreach (XmlNode node in nodes)\n            {\n                string tempf = node["temp_f"].InnerText;\n                string tempc = node["temp_c"].InnerText;\n                string feels = node["feelslike_f"].InnerText;\n\n                label2.Text = tempf;\n                label4.Text = tempc;\n                label6.Text = feels;\n            }\n\n\n\n        }\n    }\n}	0
12978313	12978285	Prevent back button	[NoCache]	0
25135614	25135548	How to get the Identity value from C# object initializer	var cmsque = new CMSQUE\n{\n    queedfcodequestiontype = questionEdfValue.ToString(),\n    quenotes = model.QuestionDescription,\n    queisexternaltext = false,\n    quenumofoptions = model.NoofOptions,\n    queusmrefidcreatedby = Convert.ToInt32(System.Web.HttpContext.Current.Session["usmrefid"]),\n    quescore = model.QuestionScore / model.NoofQuestions,\n    quetime = model.QuestionDuration  \n};\n\ndb.CMSQUEs.Add(cmsque);\ndb.SaveChanges();\ndb.Entry(cmsque).GetDatabaseValues();\n\nvar identityValue = cmsque.ID;	0
16218393	16217893	How to constrait a generic class to work with just two classes	public interface IExclusiveCommand : IBaseCommand\n{\n    void ExclusiveMethod();  //Not necessary if there are no differences between Base and Exclusive\n}\n\npublic class ProtocolEncapsulator<TContainedCommand> : IBaseCommand where TContainedCommand : IExclusiveCommand\n{\n}	0
7643668	7643606	Change assembly version of another .EXE	AssemblyVersion.cs	0
13092793	13092672	How to center a form after programmatically switching screens	private static Point CenterForm(Form form, Screen screen)\n    {\n        return new Point(\n                         screen.Bounds.Location.X + (screen.WorkingArea.Width - form.Width) / 2,\n                         screen.Bounds.Location.Y + (screen.WorkingArea.Height - form.Height) / 2\n                         );\n    }	0
8926614	8926422	XML deserialize getting null	public class tester\n{\n   //The web site name\n   [XmlArray("tester")]\n   [XmlArrayItem("test")]\n   public string[] test { get; set; }\n}	0
3655961	3655919	find name of all classes with their namespace	var myClasses = GetType().Assembly.GetTypes()\n                   .Where(t => t.Namespace.StartsWith("MyProject") && t.Namespace.EndsWith("Attribute"));	0
7760484	7760373	string encoding in C# - strange characters	Encoding.UTF8	0
5788326	5787324	Changing image according to theme	public static void DisablePageCaching() \n{ \n//Used for disabling page caching \nHttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));\nHttpContext.Current.Response.Cache.SetValidUntilExpires(false); \nHttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);\nHttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);\nHttpContext.Current.Response.Cache.SetNoStore(); \n\n}	0
33525770	33523663	Open XML populate excel table	var workbook = new XLWorkbook();\nvar ws = workbook.Worksheets.Add("Demo");\n// Set the values for the cells\nws.Cell(1, 1).Value = "Value";\nws.Cell(2, 1).Value = 1;        \nws.Cell(3, 1).Value = 2;\nws.Cell(4, 1).Value = 3;\nws.Cell(5, 1).Value = true;	0
9800297	9800249	Reading from a file in C# without the newline character	string.Join(" ", File.ReadAllLines("path"));	0
5159926	5159763	DataGridView control scrolls to top when a property changed	int rowIndex = dataGridView.FirstDisplayedScrollingRowIndex;\n\n        // Refresh your DGV.\n\n        dataGridView.FirstDisplayedScrollingRowIndex = rowIndex;	0
8269196	8269095	How do I assign current profile credentials to a WebRequest's Credentials property?	request.Credentials = CredentialCache.DefaultNetworkCredentials;	0
12437935	12437923	Sort List<Tuple<string, Class>> Alphabetically for the string value of tuple, C#	var ordered = myList.OrderBy(t => t.Item1).ToList();	0
22054237	22054197	How do i add to each link the number 10 then 20 30 40 50?	for (int i = 10; i <= 100; i += 10)\n{\n  client.DownloadFile(mainurl + i, htmlFilesDirectory + "\\test\\" + i + ".html");\n}	0
10766683	10766654	AppSettings get value from .config file	string value = System.Configuration.ConfigurationManager.AppSettings[key];	0
26633245	26633131	How to filter elements by a List item in linq?	var usersType1 = users.Where(usr => usr.CommunityRoles.Any(role => \n                              role.RoleType == CommunityRoleType.Type1\n                                   && role.Community.CommunityId == communityID)).ToList();	0
17466499	17466381	Creating parameter for tableName results in exception	string commandText = String.Format("SELECT {0}, {1} FROM {2}", key, value, tableName);	0
1304165	1304152	Shortest method to find Min and Max length of word in array	var min = words.Min(w=> w.Length);  // 5\nvar max = words.Max(w=> w.Length);  // 9	0
20637859	20637748	ASP Page Request Count	sw.Close();	0
18774732	18773920	Finding element using Selenium Web Driver in C#	By.CssSelector("a.PortalLink[href*='launchprogram.jsp']")	0
8494728	8494703	Find a substring in a case-insensitive way - C#	string s = "foobarbaz";\nint index = s.IndexOf("BAR", StringComparison.CurrentCultureIgnoreCase); // index = 3	0
31068699	31068034	Read text file with multiple JSON messages	public List<string> GetJsonItems()\n{\n    int BracketCount = 0;\n    string ExampleJSON = new StreamReader(@"c:\Json.txt").ReadToEnd();\n    List<string> JsonItems = new List<string>();\n    StringBuilder Json = new StringBuilder();\n\n    foreach (char c in ExampleJSON)\n    {\n        if (c == '{')\n            ++BracketCount;\n        else if (c == '}')\n            --BracketCount;\n        Json.Append(c);\n\n        if (BracketCount == 0 && c != ' ')\n        {\n            JsonItems.Add(Json.ToString());\n            Json = new StringBuilder();\n\n        }\n    }\n    return JsonItems;    \n}	0
3108538	3108516	how can i load the contents of an xml file at a url into a string?	WebClient client = new WebClient();\nstring text = client.DownloadString(url);	0
7365234	7358267	NHibernate QueryOver with Left Self Join	ShipPosition shipPosition = null;\nShipPositionType shipPositionType = null;\nRelatedShipPosition relatedShipPosition = null;\n\nvar result = QueryOver.Of<ShipPosition>(() => shipPosition)\n    .JoinAlias(() => shipPosition.ShipPositionType, () => shipPositionType)\n    .JoinAlias(() => shipPosition.RelatedShipPosition, () => relatedShipPosition)\n    .WhereRestrictionOn(() => relatedShipPosition.SystemName).IsInG(positionTypes)\n    .And(Restrictions.Or(\n        Restrictions.Where(() => shipPosition.ModifiedDate).IsBetween(modifiedFrom).And(modifiedTo)),\n        Restrictions.Where(() => relatedShipPosition.ModifiedDate).IsBetween(modifiedFrom).And(modifiedTo));	0
17002966	16974764	Locking a table while inserting and selecting	/*\ncreate table a (id int identity(1,1) primary key, name varchar(max))\ncreate table b (id int identity(1,1) primary key, ParentID int)\nGO\n\ncreate proc Test as\nbegin\n    declare @parentId int\n    begin tran\n    begin try\n        insert into a(name) values('abc')\n        select @parentId = SCOPE_IDENTITY()\n        select 'ScopeID',@parentID\n        insert into b(ParentID) values(@parentid)\n        --Uncomment this to see the rollback happen\n        --raiserror ('Testing what will happen if an error occurred to make sure rollback works.',\n        --       16, -- Severity.\n        --       1 -- State.\n        --       );\n        commit tran\n    end try\n    begin catch\n        rollback tran\n    end catch\nend\ngo\n*/\n\ntruncate table a --TRUNCATE RESET IDENTITY SEED VALUES (UNLIKE DELETE)\ntruncate table b\nexec Test\nselect * from a\nselect * from b	0
10612453	10610892	Efficient method of changing columns in a DataGridView	switch (gridMode){\n  case GridMode.Company:\n   this.AddColumns(userColumnList);\n   gridMode = GridMode.User;\n   break;\n  case GridMode.User:\n   this.AddColumns(userColumnList);\n   gridMode = GridMode.Company;\n   break;\n}\n\nprotected void AddColumns(List<Column> adds){\n  extractDataGrid.Layout.Suspend();\n  extractionDataGrid.Columns.Clear();\n  foreach(Column c in adds){\n   extractionDataGrid.Columns.Add(c); \n  }\nextractDataGrid.Layout.Resume();\n}	0
13879031	13878861	Check authorization from xml userwise	var doc=XDocument.Load(yourXmlFile);\nstring access=doc.Descendants().Elements("user")\n                 .Where(x=>x.Attribute("name").Value=="eu01\bve")\n                                                       ---------\n                 .First().Parent.Attribute("name").Value;	0
9381096	9380289	Korean Virtual keyboard disable WM_IME_ENDCOMPOSITION on mouse click	protected override void WndProc(ref Message m)\n  {\n    switch(m.Msg)\n    {\n      case WM_IME_ENDCOMPOSITION :\n        // Gobble this up or ignore\n        break;\n      default:\n        // Continue as normal\n        base.WndProc (ref m);\n        break;\n    }\n  }	0
34330166	34329892	How to pass parameter between two project asp.net	Response.Redirect("http://url/mobileservice.asmx/kioskOyunKodu?kioskkod="+ kioskID + "&kioskKodEncryped=" + encodedCode + "&okulno=" + txt_StudentID.Text);	0
31146635	31146364	Saving image from "pictureBox1" to a file with a click on a button in C#	// 1. Load a picture into the picturebox\nPictureBox pic = new PictureBox() { Image = Image.FromFile("SomeFile.jpg") };\n\n// 2. Save it to a file again\npic.Image.Save("SomeFilePath.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);	0
27925197	27925140	Load data to few lists	remind = (List<Reminders>)serializer.Deserialize(stream);\nList2 = remind.ToList();	0
685120	685077	How to dynamically access element names in XAML?	TextBox fieldTB = (TextBox)this.FindName("Field_CompanyName");	0
17757496	17757331	Direction Of Light From LightSource RayTracing	+--+--+\n                                      |  |  |\n                                      +--+--+\n                     direction        |  |  |    \nstaring point ----------------------> +--+--+\n                                      |  |  |\n                                      +--+--+\n                                      |  |  |  \n                                      +--+--+	0
9014170	9014108	Regex to extract words that contain digits	\w*\d\w*	0
21114979	21114872	String format, can't display decimals	return string.Format("* First name: {0}\n* Last name: {1}\n* Born: {2}\n* Country: {3}\n* State: {4}\n* Oklahoma: {5}\n* Zip code: {6}\n* Occupation: {7:C}\n* Income:{8} ",\n                            FirstName, LastName, YearOfBirth, Country, City, State, Zip, Occupation, AvarageIncome);	0
14959468	14959369	How can i avoid from showing another Form when closing the program Form1?	DialogResult dr = DialogResult.None;//Increase accessibility domain, setup a good default value\n            if (FormIsClosing != true)\n            {\n              dr = crawlLocaly1.ShowDialog(this);\n            }	0
19899239	19899205	C# is a 'field' but used like a 'type' list	public partial class MainGameWindow : Form\n{ \n    //sets the room ID to the first room as default\n    string roomID = "FirstRoom";\n    //makes a list for the inventory\n\n    //collection initializer way (thanks to Max bellow!)\n    List<string> Inventory = new List<string>()\n    {\n        "A piece of string...Useless!",\n    };\n\n    //constructor way\n    public MainGameWindow()\n    {\n        Inventory.Add("A piece of string...Useless!");\n    }\n\n    //method way\n    public void MethodAddUselessString()\n    {\n        Inventory.Add("A piece of string...Useless!");\n    }\n\n    //function way\n    public bool FunctionAddUselessString()\n    {\n        Inventory.Add("A piece of string...Useless!");\n\n        return true;\n    }    \n}	0
31843025	31842917	Pass N-dimensional array as parameter	System.Array	0
1146100	1146086	How to wait for a Blocking Queue to be emptied by worker	private AutoResetEvent _EmptyEvent = new AutoResetEvent(false);	0
11403288	11402862	how to draw a line on a image?	public void DrawLineInt(Bitmap bmp)\n{\n    Pen blackPen = new Pen(Color.Black, 3);\n\n    int x1 = 100;\n    int y1 = 100;\n    int x2 = 500;\n    int y2 = 100;\n    // Draw line to screen.\n    using(var graphics = Graphics.FromImage(bmp))\n    {\n       graphics.DrawLine(blackPen, x1, y1, x2, y2);\n    }\n}	0
6519903	6519862	Create List<CustomObject> from List<string>	var strList = new List<string>();\nvar coList = strList.Select(item => new CustomObject() {Name = item}).ToList();	0
2521270	2521124	how to search media file in our system by c#?	List<string> mediaExtensions = new List<string>{"mp3", "mp4"};\nList<string> filesFound = new List<string>();\n\nvoid DirSearch(string sDir) \n{\n   foreach (string d in Directory.GetDirectories(sDir)) \n   {\n    foreach (string f in Directory.GetFiles(d, "*.*")) \n    {\n        if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))\n           filesFound.Add(f);\n    }\n    DirSearch(d);\n   }\n}	0
18707143	18706789	What kind of format this cloud be and how I can extackt key:value pairs from this text	(?:RECORD|\G)\s*ROBAGR:(\S+)\s*(\S+)	0
30851215	30850575	how to parse a rgbColor using c#	string colorStr = "rgb(67,134,215)";\n\nRegex regex = new Regex(@"rgb\((?<r>\d{1,3}),(?<g>\d{1,3}),(?<b>\d{1,3})\)");\nMatch match = regex.Match(colorStr);\nif (match.Success)\n{\n    int r = int.Parse(match.Groups["r"].Value);\n    int g = int.Parse(match.Groups["g"].Value);\n    int b = int.Parse(match.Groups["b"].Value);\n\n    //// Create your new object with the r, g, b values\n}	0
6748550	6748320	Log who subscribs to a event	class Syncronizer\n{\n    public delegate void SynchronizatonEventHandler(MyClass myClass);\n    private event SynchronizatonEventHandler onSyncFinished;\n    public event SynchronizatonEventHandler OnSyncFinished\n    {\n        add\n        {\n            var method = new StackTrace().GetFrame(1).GetMethod();\n            Console.WriteLine("{0}.{1} subscribing", method.ReflectedType.Name, method.Name);\n            onSyncFinished += value;\n        }\n        remove\n        {\n            var method = new StackTrace().GetFrame(1).GetMethod();\n            Console.WriteLine("{0}.{1} unsubscribing", method.ReflectedType.Name, method.Name);\n            onSyncFinished -= value;\n        }\n    }\n}	0
12853174	12852866	How to refresh a page in wp7	NavigationService.Navigate(new Uri(string.Format("/MyPage.xaml?Refresh=true&random={0}", Guid.NewGuid()), UriKind.Relative);	0
11412208	11410900	how can i move a way from a dataGridView cell even when the cell value has not passed validation?	if (!string.IsNullOrEmpty(e.FormattedValue.ToString()) &&\n    !decimal.TryParse(e.FormattedValue.ToString(), out qty))\n{\n    e.Cancel = true;\n    ...\n}	0
6032184	6032084	Get users from an AD group	string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);	0
26847512	26847206	Accessing XML data from C#	XDocument xmlDoc = XDocument.Load(@"Your file path");\n\n    var startTimes = xmlDoc.Descendants()\n        .Where(x => x.Attributes().Any(att => att.Name == "Name" && att.Value == "StartTime"))\n        .Select(x => x.Value).ToList();	0
19726123	19726049	Exclude certain items from being added to a list with C#	if(!data.Name.ToString().Contains("Test"))\n{\n//Add Item to List\n}	0
30236420	30232370	Replace text in MailItem Body	Inspector inspector = newMailItem.GetInspector;\nif (inspector.IsWordMail())\n{\n    newMailItem.Display();\n    wordDocument = inspector.WordEditor as Microsoft.Office.Interop.Word.Document;\n\n    Microsoft.Office.Interop.Word.Range range = wordDocument.Range(wordDocument.Content.Start, wordDocument.Content.End);\n    Microsoft.Office.Interop.Word.Find findObject = range.Find;\n    findObject.ClearFormatting();\n    findObject.Text = "old value";\n    findObject.Replacement.ClearFormatting();\n    findObject.Replacement.Text = "new value";\n\n    object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;\n    findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,\n                        ref missing, ref missing, ref missing, ref missing, ref missing,\n                        ref replaceAll, ref missing, ref missing, ref missing, ref missing);\n}	0
15671802	15671600	Add lots of data to SQLite Database in C#	using (var db = new SQLiteConnection(dbPath))\n{\n    db.RunInTransaction(() =>\n    {\n        foreach (var item in items)\n        {\n            db.Insert(item);\n        }\n    });\n}	0
14827321	14827268	Entity Framework Subquery with ANY	Projects.Where(p => p.UniversityId = 1)\n    .SelectMany(pp => pp.ProjectProgress)\n    .SelectMany(pr => pr.Notifications);	0
19245847	18769007	How to get revision date time using sharpsvn (working copy)	using (SvnClient client = new SvnClient())    \n{\n    Collection<SvnLogEventArgs> logEventArgs;\n    SvnLogArgs logArgs = new SvnLogArgs\n        {\n            Limit = 1\n        };\n\n    client.GetLog(target, logArgs, out logEventArgs);\n\n    DateTime revisionTime = logEventArgs[0].Time;\n}	0
841207	841162	How do you programmatically turn off the Windows XP Print Spooler service in C#	ServiceController controller = new ServiceController("Spooler");\ncontroller.Stop();\n...\ncontroller.Start();	0
28332719	28332621	Getting the accurate character from keys pressed	if(e.keychar==(char)keys.[specified key])do some work	0
26194650	26178592	Placemark - icon size GEplugin	KmlIconCoClass icon1 = m_ge.createIcon("low");\nicon1.setHref("http://www.wispresort.com/images/easier.jpg"); \nvar style = m_ge.createStyle("");\nvar iconStyle = style.getIconStyle();\niconStyle.setIcon(icon1);\niconStyle.setScale(98);	0
24987639	24987614	Comma-Separated String to Double C#	var nums = "1,2,3,4,5,6,7,8,9,10";\nvar digits = nums.Split(',').Select(r => Convert.ToDouble(r)).ToArray();\n// the result will be an array of doubles, also this only works with .NET 3.5 or better.	0
3358247	3358184	parse string value from a URL using c#	string result = new Uri(currentURL).Segments[1]\nresult = result.Substring(0, result.Length - 1);	0
13273295	13273205	Need advice on program logic	var method2 = method_2("c", "...");\nif (method2.Count > 0)\n    method2[0].InvokeMember("click");	0
32719066	32718348	C# Download file from URL	WebClient wb = new WebClient();\nwb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");\nwb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");	0
13105277	13088002	How can I rename Excel worksheets using NetOffice?	Excel.Application excelApplication = new Excel.Application();\nExcel.Workbook workBook = excelApplication.Workbooks.Add();\nExcel.Worksheet workSheet = workBook.Worksheets[1] as Excel.Worksheet;\nworkSheet.Name = "AnyNameYouWant";	0
5835341	5835025	How do I draw two objects from a Single Class in C#/Csharp and XNA?	public void Initialize(Texture2D texture, Vector2 position)\n       {\n            pongPaddle1 = texture;\n\n            //Set Paddle position\n            paddle1Position = position;\n       }\n\n\n        public void Draw(SpriteBatch spriteBatch)\n        {\n            spriteBatch.Draw(pongPaddle1, paddle1Position, null, Color.DarkSlateBlue, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);\n        }	0
21939458	21939222	Save the text of a RichTextBox	public void Execute(object parameter)\n{\n    _actionParameterised.Invoke(parameter);\n}	0
1145846	1145771	retrieve 2d array from an object and bind to GridView	string[,] array = (string[,]) o1;	0
19780714	19780316	Capturing a number within curly brackets inside a string c#	int replyno;\n     string Subject = "Re: Hey :) (1)";\n     if (Subject.Contains("Re:"))\n     {\n         try\n         {\n             replyno = int.Parse(Regex.Match(Subject, @"(\d+)").Value);\n             replyno++;\n             Subject = Regex.Replace(Subject,@"(\d+)", replyno.ToString());\n             TextBoxSubject.Text = Subject ;\n         }\n         catch\n         {\n             TextBoxSubject.Text = Subject + " (1)";\n         }\n\n     }\n     else\n     {\n         TextBoxSubject.Text = "Re: " + Subject;\n     }	0
19229081	19229041	ambiguous between two controller methods	[HttpPost]	0
29066971	29066462	How to get list of string values from enum when all values are stored in on database field	[Flags]\npublic enum ObjectFlags\n{\n    None = 0,\n    Red = 1 << 0,   // 1\n    Square = 1 << 1,   // 2\n    Small = 1 << 2,   // 4\n    Fast = 1 << 3,   // 8\n}	0
1034069	1034040	How to create correctly escaped file:// URI in C#?	"C:/Data/Input%20Document.txt"	0
20422948	20412951	How to plot 3d function using IlPanel c#	private void ilPanel1_Load(object sender, EventArgs e) {\n    ilPanel1.Scene.Add(\n        new ILPlotCube(twoDMode: false) {\n            new ILSurface((x,y) => {\n                return (float)Math.Sin(0.1f * x * x + 0.2f * y * y);\n            })\n        }); \n}	0
18921982	18921704	How can I cast my command object to its generic interface?	public static class Extensions\n{\n    private static readonly MethodInfo SetAggregateInternalMethod = typeof(Extensions)\n        .GetMethod("SetAggregateInternal", BindingFlags.Static | BindingFlags.NonPublic);\n\n    private static void SetAggregateInternal<TAggregate>(object item, TAggregate value) where TAggregate : IAggregate\n    {\n        var aggregateCommand = item as IUpdateAggregateCommand<TAggregate>;\n        if (aggregateCommand != null)\n            aggregateCommand.Entity = value;\n    }\n\n    public static void TrySetAggregate(object item, IAggregate value)\n    {\n        SetAggregateInternalMethod\n            .MakeGenericMethod(value.GetType())\n            .Invoke(null, new[] { item, value });\n    }\n}	0
3150406	3150157	calculate the standard deviation of a generic list of objects	public float LatchTimeStdev()\n{\n    float mean = LatchTimeMean();\n    float returnValue = 0;\n    foreach (ValveData value in m_ValveResults)\n    {\n        returnValue += Math.Pow(value.LatchTime - mean, 2); \n    }\n    return Math.Sqrt(returnValue / m_ValveResults.Count-1));\n}	0
24334904	24334540	Pass in a field name at run time using Dynamic LINQ library?	var query = myList.AsQueryable();\n\nswitch(searchType)\n{\n     case "Manger":\n        query = query.where(x=> x.Manager == searchString);\n        break;\n     case "....":\n        break;\n     default:\n        // No search type match in string... an exception? your call\n        break;\n}	0
8039730	8026147	How should I abstract a collection of objects owned by another object?	public abstract class CourseBase<T> where T : SubjectBase\n{\n    public virtual IEnumerable<T> Subjects\n    {\n        get { return new List<T>(); }\n    }\n}\n\npublic abstract class SubjectBase\n{\n    public string Name { get; set; }\n    public string Description { get; set; }\n    public int ValidityPeriod { get; set; }\n}\n\npublic class LocalCourse : CourseBase<LocalCourseSubject>\n{\n    public override IEnumerable<LocalCourseSubject> Subjects\n    {\n        get { throw new NotImplementedException(); }\n    }\n}	0
13350239	13350002	How to determine if a ParameterInfo is a return parameter	ParameterInfo.Position == -1	0
19301521	19301210	Mvc : displaying a List<student> from the database in a text file with click of button	public FileStreamResult CreateReportFile()\n{\n    List<Student> students = GetStudents();\n    StringBuilder sb = new StringBuilder();\n    foreach (Student s in students)\n        sb.AppendLine(s.firstname + ", " + s.lastname + ", " + s.emailAddress);\n\n    var string_with_your_data = sb.ToString();\n    var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);\n    var stream = new MemoryStream(byteArray);\n    return File(stream, "text/plain", "Report" + DateTime.Now + ".txt");\n}	0
15545698	15545638	how to remove the thousand separator using cultureinfo?	CultureInfo ci = CultureInfo.GetCultureInfo("NL-be");\ndouble d = Convert.ToDouble("1.234,45", ci);	0
25500909	25012579	How to download an Html table into excel file using asp.net C#	protected void ExportToXLS(object sender, EventArgs e)\n{\n    Response.Clear();\n    Response.Buffer = true;\n    Response.AddHeader("content-disposition", "attachment;filename=Notifications.xls");\n    Response.Charset = "";\n    Response.ContentType = "application/vnd.ms-excel";\n\n    using (StringWriter sw = new StringWriter())\n    {\n        HtmlTextWriter tw = new HtmlTextWriter(sw);\n\n        repeaterID.DataSource = Session["SomeDataFromSession"] as List<SomeObject>;\n        repeaterID.DataBind();\n\n        rptNotifications.RenderControl(tw);\n\n        Response.Output.Write(sw.ToString());\n        Response.Flush();\n        Response.End();\n    }\n}	0
3974072	3974028	How to create DbCommand	Database db = DatabaseFactory.CreateDatabase();\nDbCommand command = db.GetSqlStringCommand("SELECT Name FROM Customers");\n...	0
810885	810875	Refactoring class to interface without breaking serialization in C#	class A : IFoo {}\nclass B : IFoo {}\nclass C : IFoo {}\n//snip//\n\nIFoo f = new A();\n     f = new B();\n     f = new C();	0
14935081	14917714	Drawing in-game windows with XNA	SpriteBatch.Draw(windowTexture, windowLocation, themeColor);	0
9910886	9910842	To see all the components in a form	Ctrl+W, U	0
3854495	3854479	Remove QueryString Variable in c#	var queryString = Request.QueryString;\n// Handle querystring, then redirect to root\nResponse.Redirect("~/");\nResponse.End();	0
21650244	21650102	Console project fails with console.writeline but not console.readline	while {\n    public int[] int_b = new int[6];\n}	0
1840598	1840551	Return first element in SortedList in C#	SortedList listX = new SortedList();\n\nlistX.Add("B", "B");\nlistX.Add("A", "A");\n\nMessageBox.Show(listX.Values[0]);	0
4397802	4393378	How to convert from AX data (container) to C# collection	using Microsoft.Dynamics.BusinessConnectorNet;\nAxaptaContainer axContainer = (AxaptaContainer)objDAXCn.Call("someClass","someStaticMethod",Var1,Var2,var3);    \nfor (int i = 1; i <= axContainer.Count; i++)\n{ \n    someStr = axContainer.get_Item(i).toString();\n}	0
31449636	19571503	How to do a EntityFramework query against md5 of a column	context.ExecuteStoreQuery<your_user_class>("SELECT * FROM user WHERE md5(email) = '9d6e1c44328f4d628ffb0cacbe6b5c44';");	0
17241988	17241816	C# BackgroundWorker Wait Until Ends	private bool restartOnCancel = false;\n\nprivate void button3_Click_1(object sender, EventArgs e)\n{\n    restartOnCancel = true;\n    backgroundWorker1.CancelAsync();\n}\n\nprivate void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    if ((e.Cancelled == true) && restartOnCancel)\n    {\n        restartOnCancel = false;\n        backgroundWorker1.RunWorkerAsync();\n    }\n}	0
22626455	22626352	C# Console Calculator about if statement	Console.ReadKey();	0
3638643	3638584	SmtpClient Sending bad MessageIDs	MailMessage message = new MailMessage();\nmessage.Headers.Add("Message-ID", "MyMessageID");	0
26637282	26637176	Joining strings in a JArray with LINQ	public static string GiveClientCampaignParam(JArray myArray)\n{\n    return string.Join(",", myArray.Select(j => \n       string.Format("{0}:{1}", j["ClientId"], j["CampaignId"]);\n}	0
20419937	20419841	How to build all projects in one single folder?	..\Build\	0
5900630	5900259	How to Focus an Element in a WPF TreeView If Elements Come From ItemSource?	TreeViewItem tvItem = (TreeViewItem)treeView\n                          .ItemContainerGenerator\n                          .ContainerFromItem(item);\ntvItem.Focus();	0
20695047	20662818	Add a row to an MS Word table using Office.Interop	object oMissing = System.Reflection.Missing.Value;        \n// get your table or create a new one like this\n// you can start with two rows. \nMicrosoft.Office.Interop.Word.Table myTable = oWordDoc.Add(myRange, 2,numberOfColumns)\nint rowCount = 2; \n//add a row for each item in a collection.\nforeach( string s in collectionOfStrings)\n{\n   myTable.Rows.Add(ref oMissing)\n   // do somethign to the row here. add strings etc. \n   myTable.Rows.[rowCount].Cells[1].Range.Text = "Content of column 1";\n   myTable.Rows[rowCount].Cells[2].Range.Text = "Content of column 2";\n   myTable.Rows[rowCount].Cells[3].Range.Text = "Content of column 3";\n   //etc\n   rowCount++;\n}	0
8741549	8729823	C# is there a way to set the scroll position of a console application	Console.SetWindowPosition(0 , currentItem);	0
28767071	28736862	How to programmatically select multiple nodes in RadTreeView in C#	foreach (RadTreeNode node in radTreeView1.Nodes)\n{\n     node.Selected = true;\n}	0
17305131	17305101	distinguish between panel in mouse click	private void myPanel_Click(object sender, EventArgs e)\n{\n    Panel target = sender as Panel;\n    if(target != null)\n        MessageBox.Show(target.Name);\n}	0
2223336	2200943	Email row that has been edited in a gridview	MailMessage feedbackmail = new MailMessage(\n                "joe.bloggs@joebloggsland.co.uk",\n                "joe.bloggs@joebloggsland.co.uk",\n                "Subject",\n                e.NewValues.Values.ToString());\n\n            SmtpClient client = new SmtpClient("SMTP");\n            try\n            {\n                client.Send(feedbackmail);\n            }\n            catch (Exception ex)\n            {\n                Console.WriteLine("Email unable to be sent at this time", ex.ToString());\n            }	0
24930387	24930079	Move data to historical table after delete	CREATE TRIGGER movetohistorical\n        ON dbo.PRODUCT \n        FOR DELETE\n    AS\n\n    INSERT Product_H\n    SELECT * FROM dbo.PRODUCT \n    WHERE PRODUCT.id IN(SELECT deleted.id FROM deleted)\n\n\nGO	0
2287970	2287912	How can I add a FlowDocument to a StackPanel?	StackPanel sp = new StackPanel();\nBorder bd = new Border();\nFlowDocument fd = FlowDocumentParser.GetFlowDocument("You want to {i:always} use this library so it is both {b:easy} and {b:straight-forward} to format documents. Here are some examples of {b:camel-case} strings: {ex:firstName}, {ex:lastName}, {ex:title}, and {ex:allowUserToFilterRows}.");\nFlowDocumentReader fdr = new FlowDocumentReader();\nfdr.Document = fd;\n\nsp.Children.Add(fdr);\nbd.Child = fdr;	0
5950118	5948475	How to remove menu option when right clicking on DevExpress Xtra GridControl Column Header?	GridOptionsMenu.EnableColumnMenu	0
15129801	15129770	One columned datatable to List<string>	List<string> list = dtusers.AsEnumerable()\n                           .Select(r=> r.Field<string>("UserCode"))\n                           .ToList();	0
17433157	17431610	DictionaryEntry to user object	//Search for key in appuser given by de and set appuser property to de.value\npublic void appuserfill(DictionaryEntry de, ref appuser _au) { // <- There's no need in "ref"\n  if (Object.ReferenceEquals(null, de))\n    throw new ArgumentNullException("de");\n  else if (Object.ReferenceEquals(null, _au))\n    throw new ArgumentNullException("_au");\n\n  PropertyInfo pInfo = _au.GetType().GetProperty(de.Key.ToString(), BindingFlags.Instance | BindingFlags.Public);\n\n  if (Object.ReferenceEquals(null, pInfo))\n    throw new ArgumentException(String.Format("Property {0} is not found.", de.Key.ToString()), "de");\n  else if (!pInfo.CanWrite)\n    throw new ArgumentException(String.Format("Property {0} can't be written.", de.Key.ToString()), "de");\n\n  pInfo.SetValue(_au, de.Value);\n}	0
235703	235564	Is it possible to throw a MessageQueueException?	using System.Reflection;\nusing System.Messaging;\n...\n        Type t = typeof(MessageQueueException);\n        ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, \n          null, new Type[] { typeof(int) }, null);\n        MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 });\n        throw ex;	0
26107503	26107437	Capturing data before it's changed in a datagridview?	dgv.CurrentCellDirtyStateChanged += new EventHandler(dgv_CurrentCellDirtyStateChanged);\n\n    void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n    {\n        //Work here, this is called before the cell change has been comitted\n    }	0
1499117	1499074	add indexing to custom list	public int this[int index]\n{\n    get\n    {\n        return this.Skip(index).FirstOrDefault();\n    }\n}	0
17917236	17905817	Loading modules from all assemblies with Ninject and wpf	var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();\nvar loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray();\n\nvar referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");\nvar toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();\ntoLoad.ForEach(path => loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path))));	0
33429679	33428434	How to deserialize LogEvents from Serilog stored in CouchDB	var logEvent = JsonConvert.DeserializeObject<SpecificLogEvent>(doc.Value);	0
2788488	2788473	How does SET works with property in C#?	set\n{\n    if (value < 0)\n        myInt = 0;\n    else\n        myInt = value;\n}	0
16712051	16711958	programmatically show or hide gridview bound fields	int colIndStudID = 1;\n    int colIndUnitID = 2;\n\n    GridView1.HeaderRow.Cells[colIndStudID].Visible = false;\n    GridView1.HeaderRow.Cells[colIndUnitID].Visible = false;\n    foreach (GridViewRow gv in GridView1.Rows)\n    {\n        gv.Cells[colIndStudID].Visible = false;\n        gv.Cells[colIndUnitID].Visible = false;\n    }	0
28605637	28603953	Identifying a shape parent in visio	using Visio = Microsoft.Office.Interop.Visio;\n\nvar visio = (Visio.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Visio.Application");\nvar vsd = visio.ActiveDocument;\nforeach(Visio.Shape shape in vsd.Pages[1].Shapes) {\n  foreach(Visio.Document stencil in visio.Documents) {\n    if (stencil.Type == Visio.VisDocumentTypes.visTypeStencil) {\n      foreach(Visio.Master sh in stencil.Masters) {\n        if (sh.Name == shape.Name) {\n          Console.WriteLine(stencil.Name);\n          break;\n        }\n      }\n    }\n  }\n}	0
9491745	9491698	C# get username from string. split	string s = "L 02/28/2012 - 04:52:05: \"Example<2><VALVE_ID_PENDING><>\" entered the game";\nint start = s.IndexOf('"')+1;\nint end = s.IndexOf('<');\nvar un = s.Substring(start, end-start);	0
24793561	24772694	Custom Fonts With Windows Azure	/* Minification failed. Returning unminified contents.\n(2412,1): run-time error CSS1019: Unexpected token, found '@import'\n(2412,9): run-time error CSS1019: Unexpected token, found 'url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700)'\n */	0
16319413	16319228	C# - Most effective way to periodically read last part of a file	using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))\n{\n    fs.Seek(offset, SeekOrigin.End);\n}	0
5710468	5710336	Distinguish different values from datagrid Silverlight	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    var data = (sender as Button).DataContext as MyDataObject;\n    DoStuff(data.ticketId);\n}	0
7526635	7526569	How to get raw page source (not generated source) from c#	using(var wc = new WebClient())\n{\n    var source = wc.DownloadString("http://google.com");\n}	0
26583719	26583637	WPF application window changes it's size	this.MaxHeight = this.MinHeight = 768;  \nthis.MaxWidth =  this.MinWidth =  1024;	0
31566525	31566456	Adding data to a dB using EF 6.x	Doc document = new Doc();\n...\n...\nUser usr = new User() {Name = "Temp", Info = "Some info.."};\ncontext.Users.Add(usr);\ndocument .Users.Add(usr );\ncontext.AddToDocuments(document);\ncontext.SaveChanges();	0
203490	203456	How can I get the icon from the executable file only having an instance of it's Process in C#	Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);	0
4611728	4611673	How to hide a Windows Forms form in a static context?	internal void HideController()\n{\n    DialogResult dlgResult = MessageBox.Show("Controller will now close.", "Closing...", \n        MessageBoxButtons.OK, MessageBoxIcon.Warning);\n\n    if (dlgResult == DialogResult.OK)\n    {\n        this.Hide();\n    }\n}\n\nstatic UtilScenario()\n{\n    _stkProgramId = ConfigurationManager.AppSettings.Get("stkProgramId");\n\n    if (CheckIfLaunched())\n    {\n        InitAllFields();\n    }\n    else\n    {\n        // a safer cast is recommended\n        ((frmUavController)Form.ActiveForm).HideController();\n    }\n}	0
1499255	1499188	C# DataGridView Color text of single row	dgvRIM.Rows[myRow].Cells[0].Style.ForeColor = Color.Red;	0
7688164	7687972	How to passe table/view entity as a parameter	public ObservableCollection<T> ShowGlasses<T>(ObjectQuery<T> source)\n{\n   ...\n\n  var result = from d in source\n\n   ...\n}	0
4077409	4077392	How to add Column header to a ListView in C#	MyList.ForEach(name => listView1.Columns.Add(name));	0
1605635	1605605	C# - Save ListView contents as XML (With multicolumns) and read on Form_Load	writer.WriteAttributeString("email", **AccountList.Items[i].Text**);\n        writer.WriteAttributeString("password", **AccountList.Items[i].Text**);\n        writer.WriteAttributeString("status", **AccountList.Items[i].Text**);	0
18804855	18797318	How to use EF5 to select items where ID is in list?	items = context.DiscoveryDevices.AsNoTracking().Where(x =>\n                discoveryIdentifiers.Contains(x.DiscoveryIdentifier, StringComparer.OrdinalIgnoreCase)\n                ).ToList();	0
21212540	21212496	Control.Remove only removes every other control	List<Control> removeList = new List<Control>();\nforeach (Control c in splitMain.Panel2.Controls)\n{\n   if (c.GetType() == typeof(CommandLink))\n   {\n      removeList.Add( c);\n   }\n}\n\nforeach(Control c in removeList )\n{\n   splitMain.Panel2.Controls.Remove(c);\n}	0
201847	201436	C# FTP with CD Disabled	if (m_PreviousServerPath != newServerPath) { \n    if (!m_IsRootPath\n        && m_LoginState == FtpLoginState.LoggedIn\n        && m_LoginDirectory != null)\n    { \n        newServerPath = m_LoginDirectory+newServerPath;\n    } \n    m_NewServerPath = newServerPath; \n\n    commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", newServerPath), PipelineEntryFlags.UserCommand)); \n}	0
18943200	18942832	How can I dynamically reference an assembly that looks for another assembly?	AppDomain.CurrentDomain.AssemblyResolve += (sender,args) => {\n\n    // Change this to wherever the additional dependencies are located    \n    var dllPath = @"C:\Program Files\Vendor\Product\lib";\n\n    var assemblyPath = Path.Combine(dllPath,args.Name.Split(',').First() + ".dll");\n\n    if(!File.Exists(assemblyPath))\n       throw new ReflectionTypeLoadException(new[] {args.GetType()},\n           new[] {new FileNotFoundException(assemblyPath) });\n\n    return Assembly.LoadFrom(assemblyPath);\n};	0
20664731	20646424	Payflow API returning null response on multiple asynch requests	PayflowNETAPI.SubmitTransaction	0
10086245	10086204	Optional parameter in the function of c#	public JsonResult GetProductByCatList(string depID, string catID = "0")	0
9734147	9734050	How to rectify the errors in resources files of a form in C#	obj\Debug\myproject.Form1.resources	0
17181146	17179460	Retrieving a Row From a Database Using OleDB	"SELECT ID FROM tblProjects WHERE ID = " & GridView.SelectedDataKey.Value.ToString	0
16340908	16340818	Remove item from dictionary where value is empty list	var foo = dictionary\n    .Where(f => f.Value.Count > 0)\n    .ToDictionary(x => x.Key, x => x.Value);	0
26639385	26639341	Parse CSV data based on Headers then load into Array	var fields = sLine.Split(new char[]{','});	0
11307421	11305825	How to check whether a base class object or derived object?	if (!acc is IAccettableBankAccount)\n{\n     throw new Exception("Not correct derived type");\n}	0
32087805	32087400	How to call manually the onchange event of fileupload control with C#	tt.Attributes["onchange"] = "previewImage(this)";	0
13416130	13415471	BitmapImage - image downloading issue	var bytes = await new WebClient().DownloadDataTaskAsync(url);\n\nvar image = new BitmapImage();\nimage.BeginInit();\nimage.CacheOption = BitmapCacheOption.OnLoad;\nimage.StreamSource = new MemoryStream(bytes);\nimage.EndInit();\nRSSImage.Source = image;	0
23446586	23446450	How to add an XmlDocument to a POCO class?	public string ContentText { get; set; }\n\nprivate _xmlDocuent;    \n[NotMapped] \npublic XmlDocument Content \n{\n  get { return _xmlDocumet ?? (_xmlDocument = new XmlDocuent.Parse(ContentTExt)); }\n}	0
10611673	10611551	Reflection: Set a property of a generic object using delegates	Actions/Funcs	0
13292183	13292148	Casting a double as an int, does it round or just strip digits?	[Test]\npublic void Cast_float_to_int_will_not_round_but_truncate\n{\n    var x = 3.9f;\n    Assert.That((int)x == 3); // <-- This will pass\n}	0
31400022	31339055	ClickOnce deployment fails to run from URL	Process p = new Process();\np.StartInfo.FileName = "iexplore.exe";\np.StartInfo.Arguments = "http://myServer/ReportServer/ReportBuilder/ReportBuilder_3_0_0_0.application?/Folder1/Folder+two/report1";\np.Start();	0
7183808	7183622	I cannot convert this instance in a dictionary	public interface IProblemFactory<out T> where T : IProblem	0
17955894	17955544	Powershell command to change registry value in a subfolder using C#	Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\...", "rname", value);	0
27903825	27903695	Keep an average of x numbers while still adding	//make a linked list and fill it...\nLinkedList<int> list = new LinkedList<int>(Enumerable.Repeat(0,10));\n\nlist.AddLast(0);\nwhile(list.Count > 10)\n{\n    list.RemoveFirst();\n}\nvar avg = list.Average();	0
27597640	27597551	How to Retrieve Name of .lnk (short cut) file	var name = Path.GetFileNameWithoutExtension(<filepath>);	0
30615252	30614859	How to get the data from Excel into C#?	"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=kisiler.xlsx;" + "Extended Properties=Excel 12.0 Xml";	0
9996969	9996875	Switching control backColor fast	int i;\n    public Form1()\n    {\n        InitializeComponent();            \n        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();\n        timer.Interval = 200;\n        timer.Tick += new EventHandler(timer_Tick);\n        this.BackColor = Color.White;\n        timer.Start();\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n        if (this.BackColor == Color.White)\n            this.BackColor = Color.Black;\n        else\n            this.BackColor = Color.White;\n    }	0
1594673	1594315	Enumerate all running databases	using System.Data.Sql;\n\nclass Program\n{\n  static void Main()\n  {\n    // Retrieve the enumerator instance and then the data.\n    SqlDataSourceEnumerator instance =\n      SqlDataSourceEnumerator.Instance;\n    System.Data.DataTable table = instance.GetDataSources();\n\n    // Display the contents of the table.\n    DisplayData(table);\n\n    Console.WriteLine("Press any key to continue.");\n    Console.ReadKey();\n  }\n\n  private static void DisplayData(System.Data.DataTable table)\n  {\n    foreach (System.Data.DataRow row in table.Rows)\n    {\n      foreach (System.Data.DataColumn col in table.Columns)\n      {\n        Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);\n      }\n      Console.WriteLine("============================");\n    }\n  }\n}	0
18203233	18203191	Too many character in character literal	Eval("FirstColorCode")	0
948357	948334	WPF DispatcherTimer and Mouse Button Click Timing	private DateTime mousePressed;\n\nprivate void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n{\n    mousePressed = DateTime.Now;\n}\n\nprivate void txtBlockOnOff_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n{\n    // button released\n\n    TimeSpan difference = DateTime.Now - mousePressed;\n\n    if (difference.TotalSeconds >= 3)\n    {\n        // long press\n    }\n    else\n    {\n        // short press\n    }\n}	0
14064048	14063843	How to add multiple files to a playlist	WMPLib.IWMPPlaylist playlist = wmp.playlistCollection.newPlaylist("myplaylist");\nWMPLib.IWMPMedia media;\nif (ofdSong.ShowDialog() == DialogResult.OK)\n{\n    foreach (string file in ofdSong.FileNames)\n    {\n        media = wmp.newMedia(file);\n        playlist.appendItem(media);\n    }\n}\nwmp.currentPlaylist = playlist;\nwmp.Ctlcontrols.play();	0
25467632	25467615	How to prepare a Windows pc to run a Touch screen Kiosk Shopping Mall App	BorderStyle=None \nTopmost=True	0
5144276	5143882	Create a new app pool and assign it to a site subfolder on a remote host, using C# and IIS7	if (!Directory.Exists(@"C:\inetpub\wwwroot\JohnSite"))\n        {\n            Directory.CreateDirectory(@"C:\inetpub\wwwroot\JohnSite");\n        }\n\n        // Add to my default site\n        var app = mgr.Sites[0].Applications.Add(@"/JohnSite", @"C:\inetpub\wwwroot\JohnSite");\n        app.ApplicationPoolName = "MyAppPool";\n\n        mgr.CommitChanges();	0
300345	299956	Adding an ItemCommand to a CompositeDataBoundControl	protected override bool OnBubbleEvent(object source, EventArgs e)\n{\n    if (e is CommandEventArgs)\n    {\n        RepeaterCommandEventArgs args = new RepeaterCommandEventArgs(this, source, (CommandEventArgs) e);\n        base.RaiseBubbleEvent(this, args);\n        return true;\n    }\n    return false;\n}	0
11859717	11858819	Large amount of objects upload and download from WCF	string GetTokenForDataRequest(string compressionMode, int maxChunkSize); //additional parameters like dates range, account number an other are defined in this method only\nint GetChunkCount(string token);\nbyte[] GetDataChunkAtIndex(string token, int index);	0
4567527	4564936	How to implement Pentago AI algorithm	var marbleMove = new MarbleMove(fromRow, fromCol, toRow, toCol);\nvar boardRotation = new BoardRotation(subBoard, rotationDirection);\nvar move = new Tuple<MarblMove, BoardRotation>(marbleMove, boardRotation);	0
32724158	32681512	ASP.NET MVC Linking two Models in Viewmodel to retrieve matched attributes	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.UnplacedUser = db.Users.Where(p => p.Placed == false).Where(p => p.PlacementYearID > 0).ToList();\n        viewModel.PlacedUser = db.Users.Where(u => u.StudentID == db.Placements.Where(p => p.PlacementID == id.Value).FirstOrDefault().StudentID);	0
19871589	19870116	using HtmlAgilityPack for parsing a web page information in C#	string url = "https://www.google.com";\nHtmlWeb web = new HtmlWeb();\nHtmlDocument doc = web.Load(url);\nforeach (HtmlNode node in doc.DocumentNode.SelectNodes("//a")) \n{\n    outputLabel.Text += node.InnerHtml;\n}	0
12135696	12135402	Export data from database into C# statements	for(int i = 0; i < 100; i++)\n{\n    _context.Projects.Add(new Project() {Name = string.format("Name{0}", i), Description = string.format("Description{0}", i) });\n}	0
11252387	11252320	How to intersect mutliple list with Lambda Expression?	var commonItems = list1.Intersect(list2).Intersect(list3).Intersect(list4);	0
31253781	31251466	Is it possible to relate one table to one of a group of tables based off of id using Entity Framework?	public class Model1Context : DbContext\n{\n    public Model1Context()\n        : base("name=Model1")\n    {\n\n    }\n    // For TPH\n    public virtual DbSet<BaseBO> MainObjects { get; set; }\n\n    // For TPT\n    //public virtual DbSet<A> As { get; set; }\n    //public virtual DbSet<B> Bs { get; set; }\n    //public virtual DbSet<C> Cs { get; set; }\n}\n\npublic class BaseBO\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n}\n\npublic class A : BaseBO\n{\n}\n\npublic class B : BaseBO\n{\n}\n\npublic class C : BaseBO\n{\n}	0
15759737	15759624	How to refresh sitecore tree node after edit that item and publish it	Context.ClientPage.SendMessage(this, "item:load(id=" + item.ID + ")");	0
10852605	10852541	How to zip multiple files in ASP.Net MVC3	using (ZipFile zip = new ZipFile())\n{\n  zip.AddFile("ReadMe.txt");\n  zip.AddFile("Resume.doc");\n  zip.AddFile("Portrait.png");\n  zip.Save("Package.zip");\n}	0
5666215	5666073	C#: Converting String to Sbyte*	string str = "The quick brown fox jumped over the gentleman.";\nbyte[] bytes = Encoding.ASCII.GetBytes(str);\n\n\nunsafe \n{\n    fixed (byte* p = bytes)\n    {\n        sbyte* sp = (sbyte*)p;  \n        //SP is now what you want\n    }               \n}	0
5878159	5878073	Comparing two dates in LINQ to SQL	DateTime start = new DateTime("4/25/2011");\nDateTime end = new DateTime("5/2/2011");\nvar result = db.Meeting.Where(d => d.MeetingDate >= start \n                 && d.MeetingDate <= end);	0
423754	423547	User Login technique C# Win App	Logging In:\n\nif (select count(*) from staff where staff_name = @staff_name and password = 'correct' and (last_logged_at = '' or last_logged_at = @unique_token) ) <> 0 then then\n\n-- allow login\nupdate staff set last_logged_at = @unique_token where staff_name = @staff_name\n\n\n\nelse if (select count(*) from staff where staff_name = @staff_name and password = 'correct' and last_logged_at <> @unique_token) <> 0 then then\n\n-- disallow login\n throw exception "You cannot use the same user name on two or more computers.   Contact the administrator if you have any concerns"\n\nelse\n\n-- disallow login\nthrow exception "Wrong password"\n\nend if\n\n\nLogging Out:\n\nupdate staff set last_logged_at = '' where staff_name = @staff_name	0
10432791	10432647	Parsing json objects	public class UserInfo\n{\n    public string single_token { get; set; }\n    public string username { get; set; }\n    public string version { get; set; }\n}\n\npublic partial class Downloader : Form\n{\n    public Downloader(string url, bool showTags = false)\n    {\n        InitializeComponent();\n        WebClient client = new WebClient();\n        string jsonURL = "http://localhost/jev";\n        source = client.DownloadString(jsonURL);\n        richTextBox1.Text = source;\n        JavaScriptSerializer parser = new JavaScriptSerializer();\n        var info = parser.Deserialize<UserInfo>(source);\n\n        // use deserialized info object\n    }\n}	0
13176526	13176441	Failing to store File In Combobox and Read the Data, Size in WPF	byte[] b;\nFileStream fileStream=new FileStream(FirmwarePath,FileMode.Open);\nusing (BinaryReader br = new BinaryReader(fileStream))\n{\n   b = br.ReadBytes(fileSize);\n}	0
18366004	18365715	More efficient way of implementing a countdown timer/clock?	class MyStopwatch {\n    private DateTime _startTime;\n    private DateTime _stopTime;\n\n    public void start() {\n        _running = true;\n        _startTime = DateTime.Now;\n    }\n\n    public void stop() {\n        _stopTime = DateTime.Now;\n        _running = false;\n    }\n\n    public double getTimePassed() {\n        if(_running) {\n            return (DateTime.Now - _startTime).TotalMilliseconds;\n        } else {\n            return (_stopTime - _startTime).TotalMilliseconds;\n        }\n    }\n}	0
4083345	4046591	Copy Form Fields From One PDF to Another	PdfReader currentReader = new PdfReader( CURRENT_PDF_PATH ); // throws\nPdfReader pdfFromWord = new PdfReader( TWEAKED_PDF_FROM_WORD_PATH ); // throws\nPdfStamper stamper = new PdfStamper( currentReader , outputFile ); //throws\nfor( int i = 1; i <= tempalteReader.getNumberOfPages(); ++i) {\n  stamper.replacePage( pdfFromWord, i, i );\n}\n\nstamper.close(); // throws	0
7932047	7931650	Adding elements to an xml file in C#	XDocument doc = XDocument.Load(spath); \n XElement root = new XElement("Snippet"); \n root.Add(new XAttribute("name", "name goes here")); \n root.Add(new XElement("SnippetCode", "SnippetCode")); \n doc.Element("Snippets").Add(root); \n doc.Save(spath);	0
8293008	8292296	current row returns null in datagridview c#	if (dgSuggest.CurrentRow != null &&\n    dgSuggest.CurrentRow.Index < dgSuggest.Rows.Count - 1)\n{\n    rowIndex = dgSuggest.CurrentRow.Index + 1;\n}	0
20042928	20003520	How can i select all the row in ObjectListView?	olvSongs.FullRowSelect = true;	0
1272218	1272206	Use WCF to receive any XML message from an MSMQ Queue?	MsmqMessage<XmlElement>	0
12540821	12540726	How to initialise a list of arrays in c sharp?	List<Rectangle> rec = new List<Rectangle>();\nfor(int i=0; i<YourCustomSize; i++)\n  rec.Add(new Rectangle(){ Property1 = Value1, Property2 = Value2, ...});	0
11952084	11952035	C#: Selecting a row in DataGridView with parameters	private void selectRow(string studentName, string date)\n    {\n        int i = 0;\n        foreach (DataGridViewRow r in dgvPontengHistory.Rows)\n        {\n            if (r.Cells["student_name"] == null) { throw("can't find cell"); }\n            if(r.Cells["student_name"].Value == null) { throw("cell has no value"); }\n            if(r.Cells["student_name"].Value.ToString().Contains(studentName)) // error in this line\n            {\n                if (r.Cells["date"].Value.ToString().Contains(date))\n                {\n                    dgvPontengHistory.Rows[i].Selected = true;\n                    return;\n                }\n            }\n            i++;\n        }\n    }	0
17100125	17099465	Using NSTimer to call SetNeedsDisplay in Xamarin for iOS	timer = NSTimer.CreateRepeatingScheduledTimer (TimeSpan.FromSeconds (0.1), delegate {\n            pane.SetNeedsDisplay ();\n        });	0
2658312	2647255	How to set up a Bitmap with unmanaged data?	var bmp = new Bitmap(width, height, 0, System.Drawing.Imaging.PixelFormat.Format32bppArgb, data);	0
4117602	4117579	Equivalent of Task Parallel Library in Java	java.util.concurrent	0
21118687	21118495	Getting a console application to allow input multiple times	Console.WriteLine("Please enter the date you wish to specify: (DD/MM/YYYY)");\nstring userInput;\nuserInput = Console.ReadLine();\nwhile (userInput != "0")\n{\n    DateTime calc = DateTime.Parse(userInput);\n    TimeSpan days = DateTime.Now.Subtract(calc);\n    Console.WriteLine(days.TotalDays);\n    Console.WriteLine("Add another date");\n    userInput = Console.ReadLine();\n}	0
7671230	7671083	Keeping DomainContext up to date on SubmitOperation failure	private void deleteOperationCompletedM(SubmitOperation op) {\n  if (op.Error == null) {\n    MessageBox.Show("Delete operation was successfull.");\n    // Some other code here (removed for brevity)\n  }\n  else{\n    op.MarkErrorAsHandled();\n    MessageBox.Show("An error has occured." + op.Error.Message);\n\n    db.RejectChanges();  // call reject changes on the DomainContext\n  }\n}	0
11896176	11895591	Binding to ComplexType result of stored procedure in Entity Framework (WPF C#)	this.myEntities.GetParts(selectedPartShape.attributeID, null)	0
3893617	3893604	Escaping arguments for string.Format in a C# multiline verbatim string	string template = @"   \n          {{   \n            argument1   = ""{0}""; \n            argument2   = {1};   \n          }}";	0
9432792	8340410	Connect to Windows Desktop Search on Remote Machine	"SELECT System.ItemName, System.ItemPathDisplay, System.ItemType, \nSystem.Search.Rank FROM servername.SYSTEMINDEX WHERE \nSCOPE='file://servername/WebContent' AND System.ItemType <> 'Directory' AND\n(CONTAINS(System.Search.Contents,'\"*asdf*\"') or \nCONTAINS(System.FileName,'\"*asdf*\"'))"	0
14856500	14841761	Gap between the first X datetime value and the Y axis	chart.ChartAreas[0].AxisX.Minimum and chart.ChartAreas[0].AxisX.Maximum	0
12989487	12988861	c# How to proceed replacements based on regex patterns from the file	System.IO.StreamReader file = new System.IO.StreamReader(@"d:\test.txt");      \nwhile (file.EndOfStream != true)      \n{\n  string s = file.ReadLine();\n  Match m = Regex.Match(s, "\"([^\"]+)\"\\s+\"([^\"]+)\"", RegexOptions.IgnoreCase);\n  if (m.Success) {\n    richTextBox3.Text = Regex.Replace(richTextBox3.Text, \n      "\\b" + m.Groups[1].Value + "\\b", m.Groups[2].Value);\n  }\n}	0
22705420	22705291	How to create SESSION in Windows Phone	public static string Username;\npublic static string Password;	0
19156549	19156505	Casting IOrderedEnumerable to ICollection	ToList()	0
31058444	31057980	Get variables from .LESS markup	var regex = new Regex(@"(?<name>@\w+)\s*:\s(?<value>[^;]+;");\n\nvar less = File.ReadAllText("style.less"));\n\nvar matches = regex.Matches(less);\nvar parameters = new List<KeyValuePair<string, string>>();\nforeach (var match in matches.Cast<Match>())\n{\n    parameters.Add(new KeyValuePair<string, string>(\n        match.Groups["name"].Value,\n        match.Groups["value"].Value));\n}	0
25251601	25251560	JSON.NET serialize object where property name to name that starts with dot	[JsonProperty(".Name")]\npublic string Name { get; set; }	0
1406125	1406094	Create new XmlDocument from existing XmlDocument Data in Asp.Net	XmlDocument xmlDoc = Object.ReturnsXmlDocument;\nXmlDocument xmlResults = new XmlDocument();\nxmlResults.AppendNode(xmlResults.ImportNode(xmlDoc.SelectSingleNode("/xml/results"));	0
11893980	11893954	how to add multiple conditions in this lambda function?	context.PeriodRepository.Query(a => a.EntityId == selectedEntityId && a.Name != null);	0
7554502	7527799	How do you set up the correct HTTP Response object for a Range request coming from BITS (Background Intelligent Transfer Service)?	_context.Response.StatusCode = 206;\n_context.Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", lower.ToString(), upper.ToString(), view.Content.Length.ToString()));\n_context.Response.AddHeader("Content-Length", length.ToString());\n_context.Response.AddHeader("Accept-Ranges", "bytes");\n_context.Response.OutputStream.Write(view.Content.ToArray(), lower, length);	0
9895123	9895029	Fill just some DataView columns with IEnumerable	[Browsable(false)]\npublic string MyString { get;set;}	0
9076230	9075118	How to arrange this data in a crystal report?	DataTable1.s_code	0
21046353	21046313	Send Oracle Connection State to Label	Label_connectiontest.Text = conn.State.ToString();	0
10317504	10317042	Regular Expression to clear attributes from a html tag	public string RemoveAllAttributesFromEveryNode(string html)\n    {\n        var document = new HtmlAgilityPack.HtmlDocument();\n        document.LoadHtml(html);\n        foreach (var eachNode in this.HtmlDocument.DocumentNode.SelectNodes("//*"))\n            eachNode.Attributes.RemoveAll();\n        html = document.DocumentNode.OuterHtml;\n        return html;\n    }	0
22149326	22147741	Issue with passing DropDownList's selected value to Gridview's data source	user = System.Web.HttpContext.Current.User.Identity.Name;\nconn = new SqlConnection(ConnectionStrings:NB-ReportsConnectionString);\nconn.Open();\nSqlCommand cmd = new SqlCommand(usp_Assets, conn);\ncmd.CommandType = CommandType.StoredProcedure;\ncmd.Parameters.Add("User", user);\ncompanyID = cmd.ExecuteScalar();\ncon.Close();\nSqlDataSource1.SelectParameters("ID").DefaultValue = companyID	0
21687399	21685264	What happens to my DbContext after I run a stored procedure that modifies my entities?	var Context = ((IObjectContextAdapter)_ctx).ObjectContext;\nContext.Refresh(RefreshMode.StoreWins, Context.ObjectStateManager.GetObjectStateEntries());	0
26138553	26138406	c# Delete file in all user in profile	foreach(string userName in userList)\n    File.Delete(userName+@"\MyApplicationName\Directory\FileIWantToAccess\YouFileName");	0
21524206	21518600	Can I use Windows Azure Notification Hub to send push notification from Windows 8 to Windows Phone 8?	Azure.ServiceBus	0
13988009	13987180	Change canvas background - metro app	ms-appx:///Assets/01.jpeg	0
32520365	32501760	Custom data-type not serialized to XML	accidente.salida_via = AccidenteRequestSalida_via.Item1;\naccidente.salida_viaSpecified = true;	0
6032245	6031555	Implementing pattern matching in C#	var title = content.Match()\n   .With<BlogPost>(blogPost => blogPost.Blog.Title + ": " + blogPost.Title)\n   .With<Blog>(blog => blog.Title)\n   .Result<string>();	0
15938183	15621788	Run Only signed powershell scripts from c#	public bool checkSignature(string path)\n    {\n\n        Runspace runspace = RunspaceFactory.CreateRunspace();\n        runspace.Open();\n        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);\n        Pipeline pipeline = runspace.CreatePipeline();\n        pipeline.Commands.AddScript(String.Format("Get-AuthenticodeSignature \"{0}\"", path));\n        Collection<PSObject> results = pipeline.Invoke();\n        Signature check = (Signature)results[0].BaseObject;\n        runspace.Close();\n        if (check.Status == SignatureStatus.Valid)\n        {\n            return true;\n        }\n        return false;\n    }	0
3258864	3258712	Moq: how to verify a function that takes in a object created within a method	objRepMock.Setup(or => or.Save(It.IsAny<object>()).Callback(obj => {\n   // Do asserts on the object here\n}	0
18041958	18041909	How do I prevent crashing from invalid user input?	bool ok = false;\n    int release;\n    while (!ok)\n    {\n        Console.Write("Ange release: ");\n        ok = int.TryParse(Console.ReadLine(), out release);\n        ok = ok && (release >= 1000) && (release <= 2050);\n    }	0
21135808	21135658	How to get the reference to newly constructed instance in expression tree c#	public static Expression<Func<Model, ViewModel>> ToViewModel\n{\n    get\n    {\n        return x => GetViewModel(x);\n    }\n}\n\npublic ViewModel GetViewModel(Model x)\n{\n    var vm = new PositionViewModel\n    {\n        Id = x.Id,\n        Name = x.Name\n    };\n\n    vm.Employees = x.Employees.Select(p => new Employee\n    {\n        Id = p.Id,\n        Name = p.Name,\n        Position = vm\n    }).ToList();\n\n    return vm;\n}	0
27676551	27676519	Upload Name changing image to the database	string inserQuery = @"insert into UserData(YourName,Email,Password,Gender,\n                                            Birthday,AboutMe,Country,ID, ProfilePic) \n                       values (@YName,@REmail,@RPassword,@DDownGender,\n                               @MTextBox,@RAboutMe,@DCountry,@ID, @ProfilePic)";	0
11492562	11492523	c# how to request url parameters and change char	string[] speakers;\nif (Request.QueryString["speakers"] == null)\n    speakers = new string[0];\nelse\n    speakers = Request.QueryString["speakers"].Split('.');	0
7360168	7360039	Custom control property as enum	[Obsolete("User PageName2")\npublic string PageName {\n{\n get { return PageName2.ToString(); }\nset { PageName2 = (PageNameProperty )Enum.Parse(typeof(PageNameProperty), value);\n}\n\npublic PageNameProperty PageName2 { set; get; }	0
16605222	16602554	WPF curpos in textbox databinding to label	private void textbox1_PreviewMouseMove(object sender, MouseEventArgs e)\n    {\n        Point curpos = e.GetPosition(textbox1);\n        int pos1;\n        pos1 = textbox1.GetCharacterIndexFromPoint(curpos, true);\n        label1.Content = pos1.ToString();\n    }	0
20529825	20529559	Read a session variable and delete it after reading the value	if(context.Session["test"] != null)\n{\n    // Read value\n    string sessionValue = context.Session["test"].ToString();\n\n    // Delete value from session\n    context.Session.Remove("test");\n}	0
22134123	22133053	How to extract just the specific directory from a zip archive in C# .NET 4.5?	class Program\n{\n    static object lockObj = new object();\n\n    static void Main(string[] args)\n    {\n        string zipPath = @"C:\Temp\Test\Test.zip";\n        string extractPath = @"c:\Temp\xxx";\n        string directory = "testabc";\n        using (ZipArchive archive = ZipFile.OpenRead(zipPath))\n        {\n            var result = from currEntry in archive.Entries\n                         where Path.GetDirectoryName(currEntry.FullName) == directory\n                         where !String.IsNullOrEmpty(currEntry.Name)\n                         select currEntry;\n\n\n            foreach (ZipArchiveEntry entry in result)\n            {\n                entry.ExtractToFile(Path.Combine(extractPath, entry.Name));\n            }\n        } \n    }        \n}	0
30768501	30767883	String to Ansicode Representation	var s = "??????? ????";\nvar b = Encoding.GetEncoding(1252).GetBytes(s);\nvar fixedString = Encoding.GetEncoding(1251).GetString(b);\nConsole.WriteLine(fixedString); // ??????? ????	0
6559685	6559662	Force derived class to implement base class constructor with parameter(s)	public interface IInit\n{\n   void Init(int someValue);\n}\n\npublic class FooBase : IInit\n{\n   ..\n}	0
4387478	4387444	How to store class object in app config file	static class	0
13043992	13032891	How to sort a data collection of objects using jQuery	var list = [{\n    prop1: 'a',\n    prop2: 5\n}, {\n    prop1: 'b',\n    prop2: 4\n}, {\n    prop1: 'c',\n    prop2: 3\n}, {\n    prop1: 'd',\n    prop2: 2\n}, {\n    prop1: 'e',\n    prop2: 1\n}];\n\nfunction sort(propName, direction) {\n    var dirOffset = direction === 'desc' ? -1 : 1;\n\n    list.sort(function(a, b){\n        a = a[propName];\n        b = b[propName];\n\n        if (a === b) {\n            return 0;\n        }\n\n        var out = a < b ? -1 : 1;\n        return out * dirOffset;\n    });\n}\n\nfunction log(propName) {\n    list.forEach(function(item){\n        console.log(item[propName]);\n    });\n}\n\nfunction sortAndLog(propName, direction) {\n    console.log('Sorted by', propName, direction);\n    sort(propName, direction);\n    log(propName);\n    console.log('------------------------------------');\n}\n\nsortAndLog('prop1', 'desc');\nsortAndLog('prop1', 'asc');\nsortAndLog('prop2', 'asc');\nsortAndLog('prop2', 'desc');	0
22222260	4171140	Iterate over values in Flags Enum?	public static IEnumerable<Enum> GetUniqueFlags(this Enum flags)\n{\n    ulong flag = 1;\n    foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>())\n    {\n        ulong bits = Convert.ToUInt64(value);\n        while (flag < bits)\n        {\n            flag <<= 1;\n        }\n\n        if (flag == bits && flags.HasFlag(value))\n        {\n            yield return value;\n        }\n    }\n}	0
21001284	20967709	Wcf Data Service Client	var serviceRoot = new Uri("http://app-server:123465/");\nvar context = new DataServiceContext(serviceRoot, DataServiceProtocolVersion.V3);	0
8087358	8087318	How to find an Element, not knowing how deep it is nested using Linq to XML?	var node = \n  XElement.Parse(xmlString)\n  .Descendants()\n  .Where(xe => xe.Element("IsCategoryRoot") != null && xe.Element("IsCategoryRoot").Value == "1");	0
21450610	21431330	Parse Json data with multiple detail from twitter	dynamic stuff = JsonConvert.DeserializeObject(twitAuthResponse);\n\nforeach (JObject item in stuff)\n{\n    foreach (JProperty trend in item["user"])\n    {\n        if (trend.Name == "name")\n        {\n             // GET NAME\n        }\n        else if (trend.Name == "followers_count")\n        {\n             // GET COUNT\n        }\n        else if (trend.Name == "profile_image_url")\n        {\n             // GET PROFILE URL\n        }\n    }\n}	0
13548723	13548652	UnauthorizeAccessException when Writing to a file using TextWriter in c#	var pathToFile = Path.Combine(\n  Environment.GetFolderPath(Environment.SpecialFolder.Personal),\n  "my_file_name.txt");	0
22199297	22190038	How to use PictureBox in XNA?	Texture2D BitmapToTexture(Bitmap bmap)\n{\n    Mircosoft.Xna.Framework.Color[] colors = new Color[bmap.Width * bmap.Height];\n    for (int x = 0; x < bmap.Width; x++)\n    {\n        for (int y = 0; y < bmap.Height; y++)\n        {\n            int index = x + y * bmap.Width;\n            System.Color color = bmap.GetPixel(x, y);\n            Vector4 colorVector =\n                new Vector4((float)color.R / 255f,\n                            (float)color.G / 255f,\n                            (float)color.B / 255f, 1);\n            colors[index] = Color.FromNonPremultiplied(colorVector);\n        }\n    }\n\n    Texture2D texture = new Texture2D(GraphicsDevice, bmap.Width, bmap.Height);\n    texture.SetData<Color>(colors);\n    return texture;\n}	0
16038682	16038452	Want gridview to fill only on button click	protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)\n{\n    if (!IsPostBack)\n        e.Cancel = true;\n}	0
12847870	12847596	How to implement the facade pattern in C# AND physically hide the subsystem	public interface IMyService {}\n\npublic static class MyServiceBuilder\n{\n    public static IMyService GetMyService()\n    {\n        //Most likely your real implementation has the service stored somewhere\n        return new MyService();\n    }\n\n    private sealed class MyService : IMyService\n    {\n        //...\n    }\n}	0
18594185	18594024	Setting width in C# ActiveForm has no effect	int width = this.Width;\nint height = this.Height;	0
27085834	27085030	Compare the textbox value with the data in database and update the changes	while (reader.Read())\n        {\n            int unitavailable = reader.GetInt32(0);\n            if (amountkey <= unitavailable)\n            {\n                Response.Write("<script LANGUAGE='JavaScript'> alert('The units available is not enough.')</script>");\n            }\n            else \n            {\n\n                unitavailable1 = unitavailable - amountkey;\n                   SqlCommand   sqlupdateCmd = new SqlCommand("UPDATE StockDetails  set UnitAvailable='"+unitavailable1+"' WHERE StockID = 3", hookUp);\n                   sqlupdateCmd .ExecuteNonQuery(); //Update your db values\n Response.Write("<script LANGUAGE='JavaScript'> alert('The units available is not enough.')</script>");\n    }\n}	0
5935037	5934985	Multibinding issues with ListViewItems	binding4.Source = reportList.ItemsSource;	0
11143796	11143652	Trouble saving a downloaded file to the desktop in WPF C#	Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Webs.exe";	0
17370999	17370957	Downloading file from url with timeout	public class MyWebClient : WebClient\n{\n    protected override WebRequest GetWebRequest(Uri address)\n    {\n        var req = base.GetWebRequest(address);\n        req.Timeout = 15000;\n        return req;\n    }\n}	0
19892277	19892114	Run time control	System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(YourClassType));\nSystem.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\SerializedData.xml");\nwriter.Serialize(file, youClass);\nfile.Close();	0
742353	742350	Determine the name of the variable used as a parameter to a method	MyMethod2(myVar + "! 123");	0
16784903	16777305	Save binary image to SQL-CE in C#	// if the user selects a file\nif(openFileDialog.ShowDialog() == DialogResult.OK)\n{\n    // now open the file ..\n    FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);\n\n    // or you may use \n    // FileStream fs = (FileStream)openFileDialog.OpenFile();\n\n    BinaryReader br = new BinaryReader(fs);\n    Byte[] buffer = br.ReadBytes((Int32)fs.Length);\n    br.Close();\n    fs.Close();\n}\n\n// now copy content of 'buffer' to the correct filed of the recordset	0
7749026	7748817	fill linq null data c# from previous line	Entities context = new Entities();\ncontext.tbl.Where(t=>t.Id == someId)\n    .Select(t=> new() {\n        t.Id, \n        context.tbl2.First(tbl2=>tbl2.Id == t.Id).Value, //This is the subquery\n        t.whatever});	0
10720814	10720688	Don't allow Japanese characters in a TextBox	bool IsValidInput(String input)\n{\n    return input != null && input.All(c => IsValidLetter(c));\n}\n\nbool IsValidLetter(char c)\n{\n     return Char.IsNumber(c) || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');\n}	0
9980182	9979157	Deserialising XML to List	using (var f = File.Open("...", FileMode.Open))\n{\n    XmlSerializer serializer = new XmlSerializer(typeof(List<Programs>));\n    List<Programs> programs = (List<Programs>)serializer.Deserialize(f);\n}	0
4121423	4121070	How to Fill All Results from For each loop to Dataset or Data table?	DataTable dt=new DataTable();  //make it public\n            dt.columns.add("Quantity");\n             dt.columns.add("PartNumber ");\n           foreach(DataRow serverA in dsdata.Rows)\n                {\n                   DataRow dr=dt.NewRow();\n\n                    dr["Quantity"]= Convert.ToInt32(serverA["Variance"].ToString());\n                    dr["PartNumber"] = serverA["PartNumber"].ToString();\n                    dt.Rows.add(dr);\n\n                }\n                dgSerials.DataSource=dt;	0
30388889	30371654	MVC routing with multiple parameter with different parameter name	routes.MapRoute(\n                name: "Admin",\n                url: "{controller}/{action}/{did}/{docType}",\n                defaults: new { controller = "Home", action = "Index2", did = UrlParameter.Optional, docType = UrlParameter.Optional }\n            );\n            routes.MapRoute(\n                name: "User",\n                url: "{controller}/{action}/{uid}/{docId}/{typeId}",\n                defaults: new { controller = "Home", action = "Index3", uid = UrlParameter.Optional, docId = UrlParameter.Optional, typeId = UrlParameter.Optional }\n            );\n            routes.MapRoute(\n                name: "Default",\n                url: "{controller}/{action}/{id}",\n                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }\n            );	0
2788583	2788477	WPF - How do I get an object that is bound to a ListBoxItem back	MyClass item = (MyClass)(sender as Button).DataContext;	0
2161454	2161381	Hide windows mobile app instead of closing	protected override void OnClosing(CancelEventArgs e) {\n  if ( false == this.CanClose ) { // you should check, if form can be closed - in some cases you want the close application, right ;)?\n    e.Cancel = true; // for event listeners know, the close is canceled\n  }\n  base.OnClosing(e);\n  if ( false == this.CanClose ) {\n    e.Cancel = true; // if some event listener change the "Cancel" property\n    this.Minimize();\n  }\n}	0
11493359	11491000	how to call a wcf service in curl?	curl http://your.host.com/app/service.svc	0
10027534	9145667	How to post JSON to the server?	var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");\nhttpWebRequest.ContentType = "text/json";\nhttpWebRequest.Method = "POST";\n\nusing (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))\n{\n    string json = "{\"user\":\"test\"," +\n                  "\"password\":\"bla\"}";\n\n    streamWriter.Write(json);\n    streamWriter.Flush();\n    streamWriter.Close();\n}\n\nvar httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();\nusing (var streamReader = new StreamReader(httpResponse.GetResponseStream()))\n{\n    var result = streamReader.ReadToEnd();\n}	0
2266316	2265759	How to Read the Properties of files using IpropertyStorage?	Shell32.Shell shl = new Shell32.ShellClass();\n  Shell32.Folder dir = shl.NameSpace(@"c:\temp");\n  Shell32.FolderItem itm = dir.Items().Item("test.txt");\n  Shell32.ShellFolderItem itm2 = (Shell32.ShellFolderItem)itm;\n  string prop = (string)itm2.ExtendedProperty("{F29F85E0-4FF9-1068-AB91-08002B27B3D9} 4");\n  Console.WriteLine(prop);	0
10346883	10346374	what is the method to search and remove lower values from arraylist of boxofwidgets in c#	public static ArrayList GetRidOfTheSmallWidgets(ArrayList colBoxesOfWidgets)\n{\n    BoxOfWidgets[] bow = colBoxesOfWidgets.OfType<BoxOfWidgets>().ToArray();\n\n    for (int i = 0; i < bow.Length; i++)\n    {\n        Widget[] warr = bow[i].colWidgets.OfType<Widget>().ToArray();\n        for (int j = 0; j < warr.Length; j++)\n        {\n            if (warr[j].length < 20)\n                bow[i].colWidgets.Remove(warr[j]);\n        }\n    }            \n    return colBoxesOfWidgets;\n}	0
19493952	19493177	How to save excel file without GUI notifications?	private static void saveAndClose(Workbook book, string filename)\n{\n    try\n    {\n        File.Delete(filename);\n    }\n    catch { }\n    if (!File.Exists(filename))\n        book.SaveAs(filename);\n    book.Close(false);\n}	0
16790843	16790592	Displaying content corrsponding to clicked TreeView Item	private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n{\n    switch(e.Node.Text)\n    {\n        case "General":\n        // Do something...\n        break;\n\n        // Etc...\n    }\n}	0
2494262	2439380	Is it possible to parse a URL into it's composite components?	var routedata = RouteTable.Routes.GetRouteData(new HttpContextWrapper(Context));	0
25645945	25626745	c# How to apply empty cell by using StringBuilder	if( !String.IsNullOrEmpty( array[i] ) )\n  {\n       myRange.Value2 = array[i];\n  }	0
5002601	5002487	Getting number of days for a specific month	DateTime.DaysInMonth(int year, int month);	0
26088346	26088188	How to handle switching between two databases	something.com\nlogin.something.com\nadmin.something.com\n\ndev.something.com\ndev.login.something.com\ndev.admin.something.com	0
9596645	9596461	Restricting the number of digits after decimal	decimal num = 20.123456789m;\nSingle x = Convert.ToSingle(String.Format("{0:00.000}", num));	0
34269129	34269063	How to concatenate two IEnumerable's and project them into a grouping	var list3 = List1.Concat(List2)\n                             .GroupBy(x => x.Date)  \n                             .Select(grouping => \n                                 new StatusGroup\n                                 {\n                                     Date = grouping.Key, \n                                     SuccessCount = grouping.Sum(x => x.SuccessCount), \n                                     FailCount = grouping.Sum(x => x.FailCount)\n                                 });	0
12841321	12841265	LINQ to XML: Project to a List<string>	var xDoc = XDocument.Parse(xml);\nList<string> codes = xDoc.Descendants("object")\n                        .Select(o => o.Attribute("code").Value)\n                        .ToList();	0
34323043	34322939	In C# how to call a method in a second class from the first class?	Alpha a = new Alpha();\na.Apple();	0
2933515	2933477	C# parsing txt files IF name format is desired format	foreach (var fileName in fileNames) {\n    if (fileName.Count(c => c == '_') != 3) continue;\n    // etc...\n}	0
674316	674303	How do I create a temp file in a directory other than temp?	Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())	0
17286703	17286597	ASP.net Razor - Sending email from a website using GMail SMTP	public void SendEmail(string from, string to, string subject, string body)\n{\n    string host = "smtp.gmail.com";\n    int port = 587;\n\n    MailMessage msg = new MailMessage(from, to, subject, body);\n    SmtpClient smtp = new SmtpClient(host, port);\n\n    string username = "example@gmail.com";\n    string password = "1234567890";\n\n    smtp.Credentials = new NetworkCredential(username, password);\n    smtp.EnableSsl = true;\n    smtp.UseDefaultCredentials = false;\n\n    try\n    {    \n        smtp.Send(msg);\n    }\n    catch (Exception exp)\n    {\n        //Log if any errors occur\n    }\n}	0
32987254	32987177	Default parameter value for 'postData' must be a compile-time constant	public string MakePostRequest(string url, string Username, string Password, string ForumUrl)\n{\n    string postData = "username=" + Username + "&password=" + Password + "&remember=yes&submit=Login&action=do_login&url=" + ForumUrl + "member.php?action=login"\n    ...\n}	0
15486115	15485601	How to check my windows server is virtual machine or physical machine	gwmi -q "select * from win32_computersystem"	0
9991571	9987353	Displaying polygons on Google Maps from SQL Server geography data type	SqlCommand cmd = new SqlCommand("SELECT STATEMENT",ConnectionString);\nconnectionString.Open();\nSqlDataReader polygon = cmd.ExecuteReader();\n\nWhile (polygon.read())\n{\n  string kmlCoordinates = string.Empty;\n  SqlGeography geo = (SqlGeography)polygon["GeoColumn"];\n  for(int i = 1; i <= geo.STNumPoints(); i++)\n  {\n       SqlGeography point = geo.STPointN(i);\n       kmlCoordinates += point.Long + "," + point.Lat + " ";\n  }\n{\n\nConnectionString.Close();	0
23486998	23486870	Labels with different values and with different coordination in C#	Random rand = new Random();\nint label_amount = 15;\nint xCoor;\nint yCoor;\n\nprivate void btnRun_Click(object sender, EventArgs e)\n{\n    //set the button to show  the labels \n    for (int x = 0; x < label_amount; x++)\n    {\n        xCoor = coor.Next(0, 750);\n        yCoor = coor.Next(0, 500);\n\n        Label nodeLabel = new Label();  \n        nodeLabel.Text = value + " " + xCoor + "," + yCoor;\n        nodeLabel.AutoSize = true;\n        nodeLabel.Location = new Point(xCoor + 10, yCoor + 5);\n        // Add your label to whatever you're adding it\n    }\n}	0
6916074	6915879	Retrieve album art/image from a web service	public class LastFmAlbumArt\n{\n    public static string AbsUrlOfArt(string album, string artist)\n    {\n        Lastfm.Services.Session session = new Lastfm.Services.Session("XXXXXX", "YYYYYY");\n        Lastfm.Services.Artist lArtist = new Lastfm.Services.Artist(artist, session);\n        Lastfm.Services.Album lAlbum = new Lastfm.Services.Album(lArtist, album, session);\n\n        return lAlbum.GetImageURL();\n    }\n\n    public static Image AlbumArt(string album, string artist)\n    {\n        Stream stream = null;\n        try\n        {\n            WebRequest req = WebRequest.Create(AbsUrlOfArt(album, artist));\n            WebResponse response = req.GetResponse();\n            stream = response.GetResponseStream();\n            Image img = Image.FromStream(stream);\n\n            return img;\n        }\n        catch (Exception e)\n        {\n            return null;\n        }\n        finally\n        {\n            if(stream != null)\n                stream.Dispose();\n        }\n    }\n}	0
6288722	6288632	remove from List using Linq	mainList.ForEach(x=>x.bs = x.bs.Where(y=>!listForRemoval.Contains(y)).ToList());	0
28478819	28478097	Object Array, C#, Cannot access individual element inside in array	public object arrayq (int d)\n{\n    if(d=1)\n    {\n        Q2.Visible = true;\n        question2.Visible = true;\n        question1.Visible = false;\n        Q1.Visible = false\n    }\n    else if(d=2){\n        question3.Visible = true\n    }\n    object[] question = new object[3];\n\n    question[0] = Q1.Text;\n    question[1] = Q2.Text;\n    question[2] = Q3.Text ;\n    return question[d];\n}	0
18545159	18542793	EntityFramework update Entity with values of another?	context.Reports.Entry(reportToUpdate).CurrentValues.SetValues(result);\ncontext.SaveChanges();	0
20418693	19320101	Can I detect whether the video display on a windows PC is HDCP enabled in c#	VideoOutputConnector.CanEnableHdcp	0
13564994	13564735	Taking parameters from a ASP.NET textbox and passing them into a URL	MatchCollection matches = Regex.Matches(txtMyTextbox.Text, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.*?", RegexOptions.SingleLine);\n\nforeach(Match ipMatch in matches)\n{\n    //code for sending and receiving data from API here\n}	0
16912833	16898832	JustMock how to ignore a method call made inside the method under test	[TestMethod]\n    public void ShouldArrangeFutureCallToMethod()\n    {\n        // arrange CloseConnection for all future instances of Class2.\n        // "new X()" is equivalent to using .IgnoreInstance()\n        Mock.Arrange(() => new Class2().CloseConnection(Arg.AnyBool)).DoNothing();\n\n        // act\n        var c1 = new Class1();\n        c1.Close();\n        //success: didn't throw\n    }\n\n    public class Class1\n    {\n        private Class2 instanceOfClass2;\n\n        public Class1()\n        {\n            instanceOfClass2 = new Class2();\n        }\n\n        public void Close()\n        {\n            // other code here\n            instanceOfClass2.CloseConnection(true);\n        }\n    }\n\n    public class Class2\n    {\n        public void CloseConnection(bool persist)\n        {\n            throw new NotImplementedException();\n        }\n    }	0
8172142	8172062	Formatting strings into groups of 3 digits by periods	string someNumericValue = "168794521";\nint number = int.Parse(someNumericValue); // error checking might be appropriate\nvalue.ToString("0,0", CultureInfo.CreateSpecificCulture("el-GR"));	0
15007065	15006179	Disposing of Bitmaps used in background thread	Image<Bgr, Byte>	0
15385092	15384736	asp.net manually adding a row from codebehind	DataRow dr = dt.NewRow();\n// set dr fields here\ndt.Rows.Add(dr);	0
21819312	21819232	Add a method to the setup of a Moq test	// mock takes params of constructor args\nvar ctlr = new Mock(Of MyController)(moq.Object);\nctlr.Setup(i => i.GetSourceId()).Returns(5);\n\nvar obj = ctlr.Object;\nvar result = obj.Get();	0
8302704	8302633	How to simulate choosing option from select in someones website using c# and webbrowser control?	document.GetElementsByTagName("select").GetElementsByName("waluta1")[0].SetAttribute("selected", "true");	0
15534536	15534497	Writing code that can work with multiple database objects	if(mode == "PRODUCTION")\n{\n    db = new Database(ConfigurationManager.ConnectionStrings["production-key"]);\n}\nelse\n{\n    db = new Database(ConfigurationManager.ConnectionStrings["dev-key"]);\n}	0
25413014	25412433	How to read and parse an XML file only once on first page load instead of on each page request	public static class oDs\n{\n    private static DataSet _oDs;\n\n    public static DataSet columnsxml\n    {\n        get\n        {\n            if (_oDs == null)\n            {\n                _oDs = new DataSet();\n                _oDs.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/Columns.xml"));\n            }\n            return _oDs;\n        }\n\n    }\n}	0
6338771	4933918	How to bind from a source property to a TARGET method	public static readonly DependencyProperty CurrentItemProperty =\n    DependencyProperty.Register\n    (\n        "CurrentItem",\n        typeof(object),\n        typeof(ListBoxViewModel),\n        new UIPropertyMetadata(null, CurrentItemChanged)\n    );\npublic object CurrentItem\n{\n    get { return (object)GetValue(CurrentItemProperty); }\n    set { SetValue(CurrentItemProperty, value); }\n}\n\nprivate static void CurrentItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    // Update current item logic\n}	0
6457119	6456998	Locking based on parameters	Dictionary<int, object> locks = new Dictionary<int, object>();\nlocks.Add(1, new object());\nlocks.Add(2, new object());\n\nvoid Foo(int bar)\n{\n    lock (locks[bar]) {\n        ?\n    }\n}	0
8699677	8698008	writing out the data for each row in custom gridview control and adding insert row at the bottom using IEnumerable	dataSource.GetType()	0
13793104	13792915	ASP.NET how to bind all elements with certain class to the same data source	private void Page_Load(object sender, System.EventArgs e)\n{\n    LoopDropDownLists(Page.Controls);\n}\n\nprivate void LoopDropDownLists(ControlCollection controlCollection)\n{\n    foreach(Control control in controlCollection)\n    {\n        if(control is DropDownList)\n        {\n            ((DropDownList)control).DataSource = //Set datasource here!\n        }\n\n        if(control.Controls != null)\n        {\n            LoopDropDownLists(control.Controls);\n        }\n    }\n}	0
33209165	33203893	Retrieve omitting object in ReactiveList's Change observable	parents.Changed\n    .SelectMany(_ => parents\n        .Select(parent => parent.Children.Changed.Select(childEvent =>\n            new { parent, childEvent}))\n        .Merge())\n    .Subscribe(x => {\n       // x.parent / x.childEvent\n    });	0
18346637	18346009	Accessing logging functionality from a class library	public class TempClass {\n    private static ILog Log;\n\n    public static void LogSomething(string something) {\n        if (Log == null)\n            Log = LogManager.GetLog(typeof(TempClass));\n\n        Log.Info(something);\n    }\n}	0
13053870	13053763	Return items in one list based upon their matching index in another using Linq	List<string> Lst1 = new List<string> { "a", "a", "b", "a", "b", "c", "a", "c"};\nList<string> Lst2 = new List<string> { "abc1", "abc2", "abc3", "abc4", "abc5", "abc6", "abc7", "abc8" };\n\nvar Lst3 = Lst2.Where((s, i) => Lst1[i] == "a").ToList();	0
7226698	7226614	Find parent or parents directories of a file	LookingFor(new FileInfo(path).Directory));\n\npublic void LookingFor(DirectoryInfo dir)\n{\n   if (dir.Parent == null)\n      return;\n   // Add parent to ListView\n   LookingFor(dir.Parent);\n}	0
31285280	31284921	How can I put another text box in the same row as my other text box?	HTML\n\nABC<br />\n<div id="textbox1"></div>\n<div id="textbox2"></div>\n\nCSS\n\n#textbox1, #textbox2 {\n    display: block;\n    float: left;    \n    width: 100px;    \n    height: 100px;    \n}\n\n#textbox1 {\n    background-color: red;\n}\n\n#textbox2 {\n    background-color: blue;\n}	0
12405556	12389452	RichTextBox IsDocumentEnabled with InlineUIContainers	IsHitTestVisible=true	0
9312184	9312138	How to remap keyboard keys	Dictionary<KeyCode,Integer> keyMap = new Dictionary<KeyCode,Integer>();\n\nvoid Form1_KeyDown( object sender, KeyEventArgs e )\n{\n    if(keyMap.ContainsKey(e.KeyCode) {\n    int boundValue = keyMap[e.KeyCode];\n    // continue with what you want to do here\n    }\n}	0
8643244	8643217	Find out how many Milliseconds a C# program has taken to execute in your debugger	Stopwatch stopWatch = new Stopwatch();\nstopWatch.Start();\nCallYourFunction();\nstopWatch.Stop();\n// Get the elapsed time as a TimeSpan value.\nTimeSpan ts = stopWatch.Elapsed;	0
5034806	5034643	.net listbox add onrowdatabound event - how?	public class ItemDataBoundArgs: EventArgs\n{\n   public object Item;\n}\npublic class MyListBox: ListBox\n{\n    public event EventHandler ItemDataBound;\n    protected override void OnDataBinding(EventArgs e)\n    {\n       base.OnDataBinding(e);\n       if (ItemDataBound != null)\n       {\n           foreach (var item in (IEnumerable)DataSource)\n           {\n                var e= new ItemDataBoundArgs();\n                e.Item=item;\n                ItemDataBound(this,e);\n            }\n        }\n    }\n}	0
7853339	7853221	LINQ Grouping Data Twice	from ca in custList\ngroup ca by new { ca.Name, ca.Account } into g\nselect new {\n    g.Key.Account,\n    g.Key.Name,\n    OrderTotal = g.Sum(o => o.OrderTotal),\n    OrderQty = g.Sum(o => o.OrderQty)\n};	0
16542578	16284488	How to get JSON object by Query string	public JsonResult ValidateVisit(string query)\n {\n    ValidatePinViewModel model = Json.Deserialize<ValidatePinViewModel>(query);       \n    return Json(new InvalidPin());\n }	0
1283279	1283270	Saving a string to a .setting variable	Properties.Settings.Default.Save()	0
15141207	15138803	3rd party utility to convert Outlook MSG files to EML files	RDOSession Session = new RDOSession();\n  RDOMail Msg = Session.GetMessageFromMsgFile("c:\temp\YourMsgFile.msg");\n  Msg.SaveAs("c:\temp\YourEmlFile.eml", rdoSaveAsType.olRFC822);	0
25561493	25560908	Sort list of two types of object with multiple criteria	var result = data.OrderBy( x => x.Date ).ThenBy( x => x.GetType().ToString() ).ThenBy( x => x.Amount ).ThenBy( x => x.Description );	0
29526455	29525772	Reading a text/CSV file from multiple applications at the same time	var csvStream = new FileStream(csvfileName, FileMode.Open, \n                          FileAccess.Read, FileShare.ReadWrite);	0
21850674	21832725	Relative Path, usable in both Console Application and ASP.NET Webapplication	AppDomain.CurrentDomain.BaseDirectory	0
17141058	17140755	Add css class from code behind using literal control	protected void Page_Init(object sender, System.EventArgs e)\n{\n    HtmlGenericControl css;\n    css = new HtmlGenericControl();\n    css.TagName = "style";\n    css.Attributes.Add("type", "text/css");\n    css.InnerHtml = "@import \"/foobar.css\";";\n    Page.Header.Controls.Add(css);\n}	0
46952	46909	Is this the proper use of a mutex?	bool createdNew;\nusing (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))\n{\n    try\n    {\n        mtx.WaitOne();\n\n        MessageBox.Show("Click OK to release the mutex.");\n    }\n    finally\n    {\n        mtx.ReleaseMutex();\n    }\n}	0
28622373	28622284	How to check every 30seconds with dispatchertimer without affect the UI in c#?	public partial class MainWindow : Window\n{\n    System.Threading.Timer timer;\n    public MainWindow()\n    {\n        InitializeComponent();\n        timer = new System.Threading.Timer(OnCallBack, null, 0, 30 * 1000);\n    }\n\n\n    private void OnCallBack(object state)\n    {\n        //code to check report \n        Dispatcher.Invoke(() =>\n        {\n            //code to update ui\n            this.Label.Content = string.Format("Fired at {0}", DateTime.Now);\n        });\n    }\n}	0
6392623	6392599	c# limiting listbox items	tempItems.OrderBy(i => i.Distance)\n           .Take(10)\n           .ToList()\n           .ForEach(z => nearby.Items.Add(z));	0
17546084	17545989	use parentheses in c# calculator	Expression e = new Expression("2 + (3 + 5)*6");\n var result = e.Evaluate();	0
5111628	5111594	Summing particular items of a list of objects	var results = thisData.Aggregate(new Data() \n                                 { \n                                   type = thisData.First().type, \n                                   number = thisData.First().number \n                                 } , (data, item) => data.value += item.value );	0
3472320	3469706	Open WPF Popup on TextBox focus	StaysOpen="{Binding ElementName=text,Path=IsKeyboardFocused}"	0
6931868	6931808	Showing a list of errors in MessageBox show method	List<string> errors = new List<string>();\n        errors.Add("Error 1");\n        errors.Add("Error 2");\n        errors.Add("Error 3");\n\n        string errorMessage = string.Join("\n", errors.ToArray());\n        MessageBox.Show(errorMessage);	0
514585	512984	LINQ to SQL: Complicated query with aggregate data for a report from multiple tables for an ordering system	from pmt in products_mainTable\n    join opt in orders_productsTable on pmt.guid equals opt.products_mainTableGUID into tempProducts\n    from orderedProducts in tempProducts.DefaultIfEmpty()\n    join omt in orders_mainTable on orderedProducts.orders_mainTableGUID equals omt.guid into tempOrders\n    from ordersMain in tempOrders.DefaultIfEmpty()\n    group pmt by new { pmt.sku, orderedProducts.color, orderedProducts.size } into g\n    orderby g.FirstOrDefault().sku\n    select new {\n        g.FirstOrDefault().guid,\n        g.Key.sku,\n        g.Key.size,\n        QTY = g.FirstOrDefault().orders_productsTable.Sum(c => c.qty),\n        SUM = g.FirstOrDefault().orders_productsTable.Sum(c => c.itemprice * c.qty),\n        AVG = g.FirstOrDefault().orders_productsTable.Average(c => c.itemprice * c.qty),\n        Some = g.FirstOrDefault().orders_productsTable.Average(p => p.qty).GetValueOrDefault(0),\n    }	0
6944348	6944261	Accessing Stream at the same time	public static void CopyStream(Stream input, Stream output)\n{\n    byte[] buffer = new byte[32768];\n    while (true)\n    {\n        int read = input.Read (buffer, 0, buffer.Length);\n        if (read <= 0)\n            return;\n        output.Write (buffer, 0, read);\n    }\n}	0
8307523	8300365	MySqlAdapter throwing a Fatal Exception when migrating to a newer version of the connector	Allow User Variables=true	0
22014274	22014054	How to filter in C# LINQ only one string	var result = _Repository.Get()\n                .Skip(query.Skip)\n                .Take(query.Top)\n                .Where(x => \n                      x.disabled == false &&\n                      x.FilterField == query.Filter)\n                )\n                .Select(x => new {\n                    x.Id,\n                    x.Text,\n                    x.Date\n                });\n                return result;\n        }	0
25748648	25748447	How can MSDN Timer.Elapsed example work without user interaction?	using System;\nusing System.Threading;\nusing System.Timers;\nusing Timer = System.Timers.Timer;\n\nprivate static Timer aTimer;\nprivate static ManualResetEventSlim ev = new ManualResetEventSlim(false);\n\npublic static void Main()\n{\n    // Create a timer with a two second interval.\n    aTimer = new System.Timers.Timer(5000);\n    // Hook up the Elapsed event for the timer. \n    aTimer.Elapsed += OnTimedEvent;\n    aTimer.Enabled = true;\n    ev.Wait();\n}\n\nprivate static void OnTimedEvent(Object source, ElapsedEventArgs e)\n{\n    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);\n    ev.Set();\n}	0
32283582	32283581	How to check if the selected text in RichTextBox has bold style	private void rch_SelectionChanged(object sender, EventArgs e)\n{\n  tlButton.Checked = rch.SelectionFont.Bold;\n}	0
6187004	6186980	Determine if a byte[] is a pdf file	0x25 0x50 0x44 0x46	0
14602184	14602086	Get an object by click c# Windows 8	var element = (sender as FrameworkElement);\n  if (element != null)\n  {\n    var project = element.DataContext as Project;\n    if (project != null)\n    {\n      //Implementation\n    }\n  }	0
10003498	10003406	How to get an array in asp (Server side) to javascript?	protected void Page_Load(object sender, EventArgs e)\n{\n  foreach(var f in myFloats)\n     Page.ClientScript.RegisterArrayDeclaration("myFloats", f.ToString());\n}	0
22938909	22936599	Microsoft Office Excel Interop Usage, Copy to local mode	ll need Microsoft Office installed on the target computer to use the Interop. The Interop creates an Excel ActiveX object. That ActiveX object is not part of the Interop, but part of Microsoft Office. There	0
3871492	3871413	LINQ: take a sequence of elements from a collection	static void test(IEnumerable<object> objects)\n{\n    while (objects.Any())\n    {\n        foreach (object o in objects.Take(100))\n        {\n        }\n        objects = objects.Skip(100); \n    }\n}	0
34034718	33990058	How to swap cubemap when game environment changes	// replaces the reflection cubemap for the selected environment (garage or gallery)\npublic void setReflectionMaps(Cubemap cubeMap) \n{\n    // get all of the  mesh renderers\n    var renderers = truckGO.GetComponentsInChildren<Renderer>();\n    foreach (Renderer r in renderers) {\n        // get the material for each renderer\n        Material mat = r.sharedMaterial;\n\n        // check if the material has a cubemap\n        if (mat.HasProperty("_ReflectionMap")) {\n            // replace existing cubemap\n            mat.SetTexture("_ReflectionMap",cubeMap);\n        }\n    }\n\n}	0
7346915	7346846	Open up a Tab Item on a new thread?	Task<double>[] taskArray = new Task<double>[]\n   {\n       Task<double>.Factory.StartNew(() => DoComputation1()),\n\n       // May be written more conveniently like this:\n       Task.Factory.StartNew(() => DoComputation2()),\n       Task.Factory.StartNew(() => DoComputation3())                \n   };\n\ndouble[] results = new double[taskArray.Length];\nfor (int i = 0; i < taskArray.Length; i++)\n    results[i] = taskArray[i].Result;	0
22367716	22367501	How to Extract all IDs from this XML?	var doc = XDocument.Load("path_to_xml_file.xml");\nList<string> Ids = doc.Root\n                      .Elements("Movie")\n                      .Select(o => (string)o.Attribute("imdbID"))\n                      .ToList();	0
10586907	10586809	How to use an editor template with a default object instance	public ActionResult SomeAction()\n{\n\n  if (model.CustomerOrderTrackings == null \n      || model.CustomerOrderTrackings.Count > 0) \n  {\n    // Do Something with model\n  }\n\n  this.View(model)\n}	0
5218988	5218863	Find url in plain text and insert HTML A markups	string mystring = "My text and url http://www.google.com The end.";\n\nRegex urlRx = new Regex(@"(?<url>(http:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase);\n\nMatchCollection matches = urlRx.Matches(mystring);\n\nforeach (Match match in matches)\n{\n    var url = match.Groups["url"].Value;\n    mystring = mystring.Replace(url, string.Format("<a href=\"{0}\">{0}</a>", url));\n}	0
10795418	10795325	DataGridView selection changed event and deleting selected rows from database	private void btn_Delete_Click(object sender, EventArgs e) \n{       \n    if (rdb_Delete.Checked)\n    {\n        foreach (DataGridViewRow row in DataGridView1.SelectedRows)\n        {\n            //delete record and then remove from grid. \n            // you can use your own query but not necessary to use rowid\n            int selectedIndex = row.Index;         \n\n            // gets the RowID from the first column in the grid\n            int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString());\n            string sql = "DELETE FROM Table1 WHERE RowID = @RowID";\n\n            // your code for deleting it from the database\n            // then your code for refreshing the DataGridView\n\n            DataGridView1.Rows.Remove(row);\n        }\n    }\n}	0
1669045	1668985	MOQ - Have a moq valid only once	entity.VerifySet(x => x.Score = 15);	0
708680	708617	klocwork reports issues with concatenation in a loop	strXml+=" "+builder.ToString();	0
27589304	27589276	Cant get the index of the clicked button	private List<Button> buttons;\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    buttons = new [] { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13, btn14, btn15, btn16, btn17, btn18, btn19, btn20, btn21, btn22, btn22, btn23, btn24, btn25, btn26, btn27, btn28, btn29, btn30 }.ToList();\n    buttons.ForEach(x => x.Click += myEventHandler);\n}\n\nvoid myEventHandler(object sender, EventArgs e)\n{ \n    Button button = sender as Button;\n    int idx = buttons.IndexOf(button);\n}	0
1470594	1470195	Dragging items from my C# app into Outlook 2003/2007?	string[] fileList = new string[] { @"c:\temp\myVideo.avi" };\nDataObject fileDragData = new DataObject(DataFormats.FileDrop, fileList);\nbutton1.DoDragDrop(fileDragData, DragDropEffects.All);	0
14370155	14370070	Compare two text files line by line	String directory = @"C:\Whatever\";\nString[] linesA = File.ReadAllLines(Path.Combine(directory, "FileA-Database.txt"));\nString[] linesB = File.ReadAllLines(Path.Combine(directory, "FileB-Database.txt"));\n\nIEnumerable<String> onlyB = linesB.Except(linesA);\n\nFile.WriteAllLines(Path.Combine(directory, "Result.txt"), onlyB);	0
26676993	26676911	Turn string into json C#	var user = itemsList["user"] as IDictionary<string,object>;\nvar url = user["login_url"] as string;	0
6079228	6079179	find 2 neighbours of given object by Linq	var orderedList = list.OrderBy(p => p.Age);\nvar neighbors  = new List<Person> \n                  {orderedList .FirstOrDefault(p => p.Age > phil.Age),\n                          orderedList.LastOrDefault(p => p.Age < phil.Age)};	0
19315988	19315906	Rotate Grid around cursor position?	private void RightTap_Rotate(object sender, RightTappedRoutedEventArgs e)\n{\n    var obj = (CompositeTransform)N.RenderTransform;\n    Point cursorPos = Mouse.GetPosition(yourControl);\n    obj.CenterX = cursorPos.X;\n    obj.CenterY = cursorPos.Y;\n    obj.Rotation += 90;\n}	0
1645380	1626855	MS Chart Control Zoom MinSize issue	chart1.ChartAreas["MyChart"].CursorX.Interval = 0;	0
8214294	8214238	Smart user input processing in Console	while (true)\n{\n     Console.WriteLine(message);\n     var line = Console.ReadLine();\n     if (line == "") break;\n     else DoStuff();\n}	0
7993305	7993208	Reverse engineering an aggregate into a simple for loop	foreach ( string description in sT.Description )\n{\n    text += "<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + description+ "</option>";\n}	0
12004598	12003328	On-screen Keyboard manipulation metro	TextBox.InputScope = new InputScope\n            {\n                Names =\n                {\n                    new InputScopeName(InputScopeNameValue.Number)\n                }\n            };	0
26089810	26069897	How to join two lists?	var clu = children.ToLookup(x => x.ParentName, x => x.ChildName);\n parents.ForEach(p => p.ChildNames = clu[p.ParentName]);	0
15386175	15386077	Concatenate dictionary keys separated by comma's	string.Format("({0})", string.Join(",", myList.Keys));	0
19679410	19679066	How to get - 0 for round off small negative number?	var d = decimal.Round(-0.001M, 2);\nbool isNegativeZero = d == decimal.Zero && decimal.GetBits(d).Last() < 0;	0
16235409	16235237	How to remove newline characters from double quotes?	Match match = Regex.Match(myString, @""".*?""", RegexOptions.Singleline);	0
29221483	29221262	Exe can't write in a XML file in the installation folder	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);	0
24018610	23962178	TFS ISubscriber plugin, how do I access the files checked in?	CheckinEvent ev = notificationEventArgs as CheckinEvent;	0
16583957	16583591	read a very big single line txt file and split it	import os\nwith open('infile.txt') as f_in, open('outfile.txt', 'w') as f_out:\n  f_out.write(f_in.read().replace('ROW_DEL ', os.linesep))	0
19793290	19793137	Use LINQ to SQL to generate SQL based on in-memory list	using (var context = new WidgetContext())\n{\n    var selectedTypeIds = from t in SelectedWidgetTypes\n                          where t.Selected\n                          select t.Id;\n\n    var widgets = from d in context.Widgets\n                  where selectedTypeIds.Contains(d.WidgetTypeId)                 \n                        // other search criteria\n                  select d;\n\n    return widgets.ToList();\n}	0
12589694	12589602	Create user-readable, display-friendly formatted string from List<string>	public static string FormatList(List<string> invalidItems)\n{\n    if(invalidItems.Count == 0) return string.Empty;\n    else if(invalidItems.Count == 1) return string.Format("{0} is an invalid value", invalidItems[0]);\n    else return string.Format("{0} and {1} are invalid values", string.Join(", ", invalidItems.Take(invalidItems.Count - 1)), invalidItems.Last());\n}	0
11489186	11489070	How can you use the enter key to transfer data from a textbox to a label	void textBox1_KeyDown(object sender, KeyEventArgs e) {\n    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {\n        label2.Text = textBox1.Text;\n        label2.Text = "Movies released before " + textBox1.Text;\n    }\n}	0
18716265	18715979	Ambiguity with Action and Func parameter	TaskManager.RunSynchronously<MyObject>(\n    x => fileMananager.BackupItems(x), package);\n\nTaskManager.RunSynchronously<MyObject>(\n    (Action<MyObject>)fileMananager.BackupItems, package);\n\nTaskManager.RunSynchronously<MyObject>(\n    new Action<MyObject>(fileMananager.BackupItems), package);	0
513974	513961	C# - How do I sort a DataTable by date	DataView view = DataTable.DefaultView;\nview.Sort = "DateColumn";	0
8610871	8592050	Dynamic Assemblies and Methods	var d = new DynamicMethod("my_dynamic_get_" + field.Name, typeof(object), new[] { typeof(object) }, type, true);\nvar il = d.GetILGenerator();\nil.Emit(OpCodes.Ldarg_0);\nil.Emit(OpCodes.Ldfld, field);\nif (field.FieldType.IsValueType)\n    il.Emit(OpCodes.Box, field.FieldType);\nelse\n    il.Emit(OpCodes.Castclass, typeof(object));\n\nil.Emit(OpCodes.Ret);\nvar @delegate = (Func<object, object>)d.CreateDelegate(typeof(Func<object, object>));	0
14001346	14001327	How to statically assign Dictionary<TKey, TValue> values	public Dictionary<SettingKey, SettingItem> List =\n    new Dictionary<SettingKey, SettingItem>()\n{\n    {SettingKey.userDBName, new SettingItem { theValue = "user-name", theID  = 1 }},\n    {SettingKey.realName,   new SettingItem { theValue = "real-name", theID  = 2 }}   \n};	0
3887634	3887610	How to dispose timer	private static void OnElapsedTime(Object source, ElapsedEventArgs e)\n{\n    ((Timer)source).Dispose();\n}	0
11442736	11442517	Write LINQ to parse aspx page using HtmlAgilityPack	var pagecontrols = from links in htmlDoc.DocumentNode.Descendants("div")\n                   where links.Attributes.Contains("runat")\n                   select links.Attributes["ID"].Value;	0
2366497	2366440	Parsing xml using XDocument, solr results	XDocument doc = XDocument.Load(yourXmlfilePath);\n\nList<Result> results = doc.Root.Descendants("doc")\n    .Select(e=>new Result\n     {\n           T1= e.Elements("str").First(s=>s.Attribute("name").Value.Equals("T1")).Value,\n           T2= e.Elements("str").First(s=>s.Attribute("name").Value.Equals("T2")).Value,\n           T3= e.Elements("str").First(s=>s.Attribute("name").Value.Equals("T3")).Value,\n           Amount= decimal.Parse(e.Element("float").First(s=>s.Attribute("name").Value.Equals("amount")).Value)\n      }).ToList();	0
5170399	5170186	Mocking interfaces that have 'new' members with Moq	var mock = new Mock<IFoo>();\nvar bar = mock.As<IBar>();\nmock.SetupGet(m => m.Blah).Returns("Blah");\nAssert.That(mock.Object.Blah, Is.EqualTo("Blah"));\nbar.SetupGet(m => m.Blah).Returns("BlahBlah");\nAssert.That(((IBar)mock.Object).Blah, Is.EqualTo("BlahBlah"));\nAssert.That(mock.Object.Blah, Is.EqualTo("Blah"));	0
15876168	14977804	Office Word intertop heading styles not showing in table of contents	paragraph.Range().Select()	0
32538673	32538408	How to Loop through digits and separate them into single or multiple digits?	public static void Main()\n    {\n        string temp = "";\n        int counter = 0;\n        string inputNumber = "15647589654856987458963547589656";\n\n        List<string> batch = new List<string>();\n\n        for(int i = 0; i < inputNumber.Length; i++)\n        {   \n            counter++;\n            temp += inputNumber[i];\n            if(counter >= 16)\n            {\n                batch.Add(MaskedString(temp));\n                counter = 0;\n                temp = "";\n            }\n        }\n\n        foreach(var b in batch)\n        {\n            Console.WriteLine(b);\n        }\n    }\n\n    public static string MaskedString(string unmaskedString)\n    {\n        var stringBuilder = new StringBuilder(unmaskedString);\n\n        for(int i = 4; i < 9; i++)\n        {\n            stringBuilder.Remove(i, 1);\n            stringBuilder.Insert(i, "X");\n        }\n\n        return stringBuilder.ToString();        \n    }	0
13099559	13099467	Parse and store json string into a class using C#	var eventValues = JsonConvert.DeserializeObject<Event>(stringEvent);	0
9255723	9255695	C# How to connect the local database (access)	string connectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;";	0
15511498	15511444	Mapping many-to-many foreign keys without navigation properties	public class Driver\n{\n    public int Id { get; set; }\n    ...\n    public virtual ICollection<Car> Drives  { get; set; }\n}\n\npublic class Car\n{\n    public int Id { get; set; }\n    ...\n    public virtual ICollection<Driver> DrivenBy { get; set; }\n}	0
3173491	3173038	Is there a panel I can use in WPF that will "defeat" SizeToContent?	public class ZeroGrid\n    : Grid\n{\n    protected override Size MeasureOverride(Size constraint)\n    {\n        base.MeasureOverride(constraint);\n        return new Size();\n    }\n}	0
3453690	3453600	AutoMapper: User Specific Mapping	private readonly IUserContext _userContext;\n\npublic MyResolver(IUserContext userContext)\n{\n _userContext = userContext;\n}\n\nprotected override String ResolveCore(object source)\n{                    \n // Calculate display date based on user context\n    return TheDate;\n}	0
23827314	23827221	Trouble in detecting repeated word in string in c#?	string Tests = "Hi,World,Me,Hi,You";\nstring[] Tests_Array = Tests.Split(',');\nstring result = String.Join(",", Tests_Array.Distinct());	0
30184039	25027546	Usage of AggregationContainer in ElasticSearch NEST	var qryRes11 = client.Search<object>(x => x\n.Aggregations(a =>\n{\n    AggregationDescriptor<object> v = new AggregationDescriptor<object>();\n    v.Terms("a", tr =>\n    {\n        TermsAggregationDescriptor<object> trmAggDescriptor = new TermsAggregationDescriptor<object>();\n        trmAggDescriptor.Field("a");\n        trmAggDescriptor.Size(0);\n        return trmAggDescriptor;\n    });\n    return v;\n}));\nvar terms1 = qryRes1.Aggs.Terms("a");	0
30039942	30038991	Superscript + Underline inline in a RichTextBox in WPF	FlowDocument mcFlowDoc = new FlowDocument();\n        Hyperlink hyp = new Hyperlink();\n        hyp.Foreground = Brushes.Black;\n        TextBlock txt = new TextBlock();\n        txt.Foreground = Brushes.Black;\n        txt.Text = "Friday,April 10";           \n        Run rn = new Run("th");\n        rn.BaselineAlignment = BaselineAlignment.Superscript;\n        txt.Inlines.Add(rn);\n        hyp.Inlines.Add(txt);            \n        Paragraph para = new Paragraph();\n        para.Inlines.Add(new Run("The following zip codes are facing a "));\n        para.Inlines.Add(new Underline(new Run("Severe Weather Threat")));\n        para.Inlines.Add(new Run(" on "));\n        para.Inlines.Add(hyp); \n        mcFlowDoc.Blocks.Add(para);\n        RichTextBox mcRTB = new RichTextBox();\n        mcRTB.Width = 560;\n        mcRTB.Height = 100;\n        mcRTB.Document = mcFlowDoc;	0
8713608	8713459	Extract text, hyphen and number from string	System.Text.RegularExpressions.Regex.Match(inputString, @"(?<match>CXL\-[^\s]+)").Groups["match"].Value	0
24043765	24042238	How to capture previous values of columns in a GridView in C#	Session["Name"] = ((Label)gridview1.Rows[0].FindControl("Name")).Text;\nSession["Day"] = ((Label)gridview1.Rows[0].FindControl("day")).Text;	0
34496897	34475445	Uri Scheme for Movie in the Microsoft Store	Launcher.LaunchUriAsync(new Uri(myGrooveDeepLink));	0
4280946	4280904	How do I add a legend to an ASP.NET 3.5 chart control?	chart.Legends.Add(new Legend("Default") { Docking = Docking.Right});	0
27184267	27098059	Get an escaped multi syntax sql update string	/// <summary>\n/// escapes a literal string so it can be inserted using sql\n/// </summary>\n/// <param name="sqlString">the string to be escaped</param>\n/// <returns>the escaped string</returns>\npublic string escapeSQLString(string sqlString)\n{\n    string escapedString = sqlString;\n    switch ( this.repositoryType) \n    {\n        case RepositoryType.MYSQL:\n        case RepositoryType.POSTGRES:\n            // replace backslash "\" by double backslash "\\"\n            escapedString = escapedString.Replace(@"\",@"\\");\n        break;\n    }\n    // ALL DBMS types: replace the single qoutes "'" by double single quotes "''"\n    escapedString = escapedString.Replace("'","''");\n    return escapedString;\n}	0
26226195	14244114	Create a completed Task	Task completedTask = Task.CompletedTask;	0
24688493	24683379	HTML Agility Pack: How to access HTML attributes?	//select all `<tr>` that contains specific `<td>`\nforeach (HtmlNode node in tmlDoc.DocumentNode.SelectNodes("//tr[td[@headers='header1']]"))\n{\n    table.Rows.Add();\n    //get <td headers='header1'> in current <tr>\n    var header1 = node.SelectSingleNode("./td[@headers='header1']");\n\n    table.Rows[i]["Title"] = header1.InnerText;\n    //get <a> in header1 then get it's href attribute value\n    table.Rows[i]["Link"] = header1.SelectSingleNode(".//a").GetAttributeValue("href", "");\n    //get innerText of <td headers='header1'> in current <tr>\n    table.Rows[i]["Post"] = node.SelectSingleNode("./td[@headers='header3']").InnerText;\n    i++;\n}	0
31502045	31501879	Syntax Error in Insert Into Statement C# OleDb	private void btn_Save_Click(object sender, EventArgs e)\n{\n    try\n    {\n        string sqlText = "insert into OrderForm([Size]) values (?)";\n        using(OleDbConnection connection = new OleDbConnection(.....))\n        using(OleDbCommand command = new OleDbCommand(sqlText, connection))\n        {\n            connection.Open();\n            command.Parameters.Add("@p1", OleDbType.VarWChar).Value = sizeBox.Text;\n            int rowsAdded = command.ExecuteNonQuery();\n            if(rowsAdded > 0) \n                MessageBox.Show("Order Inserted into Database");\n            else\n                MessageBox.Show("No Order added to the Database");\n        }\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show("Error " + ex.Message);\n    }\n}	0
20088732	20088672	C# DateTime format for 2013-12-16T11:20:57+0530	DateTimeOffset dto = DateTimeOffset.Now;\nstring dtoString = dto.ToString("yyyy-MM-ddTHH:mm:sszzzz");\ndtoString = dtoString.Remove(dtoString.Length - 3, 1);	0
10316951	10315153	How to rename xml serialization on web service?	public class WebService : System.Web.Services.WebService {\n    [WebMethod]\n    [return: XmlRoot(ElementName = "Projects")]\n    public ProjectDTO[] HelloWorld()\n    {\n        return new ProjectDTO[] { new ProjectDTO(), new ProjectDTO(), new ProjectDTO(), }; \n    }       \n}\n\n[XmlType(TypeName = "Project")]\npublic class ProjectDTO\n{\n    public string Blah { get; set; }\n}	0
29313036	29313017	Console (Input string was not in correct format)	int n = 0;\n        int sum = 0;\n        int i = 0,val = 0;\n        Console.Write("How many numbers do you want calculate: ");\n        var isValidNumber = Int32.TryParse(n, Console.ReadLine());\n        if(!isValidNumber) {\n            Console.WriteLine("Invalid number entered!");\n        }\n        else {\n           '''Use the number\n        }	0
1914106	1914058	How do I get a list of all loaded Types in C#?	List<Type> list = new List<Type>();\nforeach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())\n{\n    foreach (Type t in ass.GetExportedTypes())\n    {\n    if (t.IsEnum)\n    {\n    list.Add(t);\n    }\n    }\n}	0
26881	26857	How do you programmatically fill in a form and 'POST' a web page?	WebRequest req = WebRequest.Create("http://mysite/myform.aspx");\nstring postData = "item1=11111&item2=22222&Item3=33333";\n\nbyte[] send = Encoding.Default.GetBytes(postData);\nreq.Method = "POST";\nreq.ContentType = "application/x-www-form-urlencoded";\nreq.ContentLength = send.Length;\n\nStream sout = req.GetRequestStream();\nsout.Write(send, 0, send.Length);\nsout.Flush();\nsout.Close();\n\nWebResponse res = req.GetResponse();\nStreamReader sr = new StreamReader(res.GetResponseStream());\nstring returnvalue = sr.ReadToEnd();	0
4500068	4499485	Loading a concrete type of a generic class using reflection	public class MockTestControllerRunner : IRunner<Interfaces.ActionSettings>\n{\n    #region IRunner<T> Members\n\n    public ActionSettings Run(string runnerXml)\n    {\n        MvcActionSettings mvcActionSettings = XmlSerialiser.XmlDeserialise<MvcActionSettings>(runnerXml);\n\n        IMvcActionSettingsCreator creator = new MockPassThroughActionSettingsGenerator();\n        Interfaces.ActionSettings v = creator.Create(mvcActionSettings);\n        return v;\n    }\n\n    #endregion\n\n    #region IRunnerWorkflowSubscriber Members\n\n    public void Initialise(IWizardManagerBase manager)\n    {\n\n    }\n\n    #endregion\n}	0
29719878	29719702	Pass values from one method to use them in another method in C#	private void groupBox1_Paint(object sender, PaintEventArgs e)\n{\n\n  //Now those variables can be accessed here.\n\n}\n\nint red_light1,yellow_light1,green_light1,\n       red_light2,yellow_light2,green_light2;\n\npublic void timer_lights_status_Tick(object sender, EventArgs e)\n{\n    red_light1    = Convert.ToInt32(comport.message(4, 8, 32));\n    yellow_light1 = Convert.ToInt32(comport.message(4, 8, 33));\n    green_light1  = Convert.ToInt32(comport.message(4, 8, 34));\n\n    red_light2    = Convert.ToInt32(comport.message(4, 8, 35));\n    yellow_light2 = Convert.ToInt32(comport.message(4, 8, 36));\n    green_light2  = Convert.ToInt32(comport.message(4, 8, 37));\n\n    groupBox1.Refresh();\n}	0
11389753	11387874	How to redirect To another controller with query strings and hash?	public ActionResult Blah(string hash)\n{\n    ... do something\n\n    // Generate the url to redirect to using a hash\n    var url = UrlHelper.GenerateUrl(\n        null,                             // routeName\n        "Foo",                            // actionName\n        "Bar",                            // controllerName\n        null,                             // protocol\n        null,                             // hostName\n        hash,                             // fragment\n        null,                             // routeValues\n        RouteTable.Routes,                // routeCollection\n        ControllerContext.RequestContext, // requestContext\n        false                             // includeImplicitMvcValues\n    );\n\n    return Redirect(url);\n}	0
27695108	27688570	Sort ListBox accoring to filename if Items are filepaths	private void SortFileList()\n{\n    int length = listBoxOpenFiles.Items.Count;\n    string[] keys = new string[length];\n    ListBoxItem[] items = new ListBoxItem[length];\n\n    for(int i = 0; i < length; ++i)\n    {\n        keys[i] = ((listBoxOpenFiles.Items[i] as ListBoxItem).Tag as MyClass).FileName;\n        items[i] = listBoxOpenFiles.Items[i] as ListBoxItem;\n    }\n\n    Array.Sort(keys, items);\n    listBoxOpenFiles.Items.Clear();\n\n    for (int i = 0; i < length; ++i)\n    {\n        listBoxOpenFiles.Items.Add(items[i]);\n    }\n}	0
1559306	1559227	Does a wrapper class calling a COM component through C# need to implement the Dispose pattern?	System.Runtime.InteropServices.Marshal.ReleaseComObject(myRCW);	0
21682372	21447266	Issue with barcode scanner in windows ce application	case Symbol.Barcode.States.WAITING:\n                if (lastScannerStatus != "WAITING" && lastScannerStatus != "INIT" && lastScannerStatus != "IDLE")\n                {\n                    this.myScanner.StopRead();\n                    this.myScanner.StartRead(true);\n                }\n                this.statusBar1.Text = "Waiting- Scan ID Barcode                    " + MacAddress + " | " + strIPAddress + " | " + version;\n\n                break;	0
19030985	19016505	Getting the contents from wpf datagrid control into a data table	public partial class MainWindow : Window\n{\n\n\n\n    public List<TaxWeek> LTaxWeeks { get; set; }\n\n    public TaxWeek SelectedTaxWeek { get; set; }\n\n    **public DataSet oDS = new DataSet();**\n\n\n    public MainWindow()\n\n    {\n        InitializeComponent();\n    }	0
20267791	20247019	Accessing Excel 2013 File in ASP.NET	public class DAL\n{\n    OleDbDataAdapter DbAdap;\n    DataTable dt;\n\n    public DataTable Get_ExcelSheet()\n    {\n        OleDbConnection DbCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Nimit\\ExcelApplication.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"");\n\n        DbAdap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",DbCon);\n        dt = new DataTable();\n        DbAdap.Fill(dt);\n        return dt;\n    }\n}	0
20685163	20598556	Unable to update comboBox from another comboBox	private void tabControl1_Selected(object sender, TabControlEventArgs e)\n    {\n        if (e.TabPage.Name == tabPage2.Name)\n        {\n            table = Items.Get();\n            if (table.Rows.Count > 0)\n            {\n                //Update comboBox1 using table\n                comboBox1.DataSource = table;\n                comboBox1.DisplayMember = "Item_ID";\n\n                //Using 1st row and 1st coloumn in function argument to get colors\n                //Color.Get(string itemID) returns dataTable, which I used for comboBox2 DataSource\n                comboBox2.DataSource = Color.Get(table.Rows[0].ItemArray[0].ToString());\n                comboBox2.ValueMember = "Color_ID";\n                comboBox2.DisplayMember = "Color_Name";\n            }\n        }\n    }	0
3039305	3039096	How do I connect to SQLite db file from c#?	"data source=c:\TestData\StressData.s3db; Version=3;"	0
10033262	10033173	How can I find a specific node in my XML?	XmlNodeList nodes = root.SelectNodes("//games/game")\nforeach (XmlNode node in nodes)\n{\n  listBox1.Items.Add(node["name"].InnerText);\n}	0
31840987	31835088	Mail send using no credentials C#	MailMessage mail = new MailMessage();\nSmtpClient SmtpServer = new SmtpClient();\nmail.To.Add(email);\nmail.From = new MailAddress("mail@domain.com");\nmail.Subject = subject;\nmail.IsBodyHtml = true;\nmail.Body = message;\nSmtpServer.Host = "smtpserver";\nSmtpServer.Port = 25;\nSmtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;\ntry {\n    SmtpServer.Send(mail);\n}\ncatch (Exception ex) {\n    Debug.WriteLine("Exception Message: " + ex.Message);\n    if (ex.InnerException != null)\n        Debug.WriteLine("Exception Inner:   " + ex.InnerException);\n}	0
17193377	17193332	dispatcher timer interval	timeDuration.Text = Timespan.FromSeconds(counter++).ToString();	0
26121976	26121790	Where are assemblies loaded in a C# application?	AppDomain.AssemblyResolve	0
5298297	5282409	How to set the same parameters for every required attribute	protected void Application_Start()\n{\n    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomRequiredAttribute), typeof(RequiredAttributeAdapter));\n    ...	0
15038794	15038744	How to read a textbox from a thread other than the one it was created on?	eLog.Source = text;	0
4366433	4366325	Datagrid columns contains value	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow) \n    {\n        GridViewRow row = (GridViewRow)e.Row.DataItem;\n        if (row["yourColumnName"] == "YourDesiredValue")\n            row["yourColumnName"] = "changevalue";\n    }\n}	0
17201691	17200100	How to Duplicate an Action in same Controller using MVC	routes.MapRoute(\n  name: "SoSomethingAgainRoute",\n  url: "{controller}/SoSomethingAgain/{id}",\n  defaults: new { controller = "Home", action = "DoSomething", id = UrlParameter.Optional }\n);	0
9632503	9632433	Center a label in a UserControl	Label.Margin = String.Format("{0},0,0,0",UserControl.actualWidth/2);	0
32742120	32741658	How to store different GroupBy in one variable with minimal code duplication?	query.GroupBy(s => new { WidgetId = model.allWidgets ? 0 : s.WidgetId, ProductId = s.ProductId });	0
21428388	21427807	parse string in datetime if not valid than set null datetime type of sql in C#	DateTime outUpdatedOn = default(DateTime);\nif (DateTime.TryParse(customerRow.UpdatedOn, out outUpdatedOn)) record.UpdatedOn = outUpdatedOn; else record.UpdatedOn = null;	0
7793535	7790203	How to check ErrorCode for REGDB_E_CLASSNOTREG?	if (e.ErrorCode == -2147287036) // REGDB_E_CLASSNOTREG.\n{\n   // handle this error.\n}	0
17446424	17421559	MS Outlook 2013 deletes custom categories added into MasterCategoryList via Exchange Web Services API	var list = MasterCategoryList.Bind(service);\n\nlist.Categories.Add(\n\nnew Category {\n        Name = "Vacation",\n        Color = CategoryColor.DarkMaroon,\n        KeyboardShortcut = CategoryKeyboardShortcut.CtrlF10,\n        Id = "{" + Guid.NewGuid() + "}";\n\n});	0
2881264	2881242	Is there an additional runtime cost for using named parameters?	var e = new vip(email: "foo", category: 32); //calling\n\n //generated, this is what it's actually saving you from writing\n public vip(string email, int category) : this(email, category, "bar") { }	0
3335509	3335378	How to assign Ctrl+, (control plus comma) as the keyboard shortcut to a WPF menu item?	InputGestureCollection keyInputs = new InputGestureCollection();\nkeyInputs.Add(new KeyGesture(Key.OemComma, ModifierKeys.Control, "Ctrl+,"));\npreferencesCommand = new RoutedUICommand("Preferences...", "Preferences", typeof(MyCommands), keyInputs);	0
5176288	5175945	Making http request from code behind	// Create a request for the URL.        \nWebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");\n// If required by the server, set the credentials.\nrequest.Credentials = CredentialCache.DefaultCredentials;\n// Get the response.\nHttpWebResponse response = (HttpWebResponse)request.GetResponse ();\n// Display the status.\nConsole.WriteLine (response.StatusDescription);\n// Get the stream containing content returned by the server.\nStream dataStream = response.GetResponseStream ();\n// Open the stream using a StreamReader for easy access.\nStreamReader reader = new StreamReader (dataStream);\n// Read the content.\nstring responseFromServer = reader.ReadToEnd ();\n// Display the content.\nConsole.WriteLine (responseFromServer);\n// Cleanup the streams and the response.\nreader.Close ();\ndataStream.Close ();\nresponse.Close ();	0
13438618	13435943	WebRequest on windows phone 7	WebClient wc = new WebClient();\nwc.DownloadStringCompleted += ReadServerResponse;\nwc.DownloadStringAsync(new Uri(url));	0
1831225	1831209	Dictionaries in DataTable	var dic1 = new Dictionary<string, string>() \n{ \n    { "A", "s" },\n    { "B", "d" },\n    { "C", "a" },\n    { "D", "w" },\n};\n\nvar dic2 = new Dictionary<string, string>() \n{ \n    { "A", "z" },\n    { "B", "e" },\n    { "C", "r" },\n    { "D", "t" },\n};\n\nvar dic3 = new Dictionary<string, string>() \n{ \n    { "A", "i" },\n    { "B", "o" },\n    { "C", "u" },\n    { "D", "p" },\n};\n\nvar table = new DataTable();\ntable.Columns.Add("K", typeof(string));\ntable.Columns.Add("c1", typeof(string));\ntable.Columns.Add("c2", typeof(string));\ntable.Columns.Add("c3", typeof(string));\nforeach (var key in dic1.Keys)\n{\n    table.Rows.Add(key, dic1[key], dic2[key], dic3[key]);\n}	0
7873664	7872687	How to get single object when using repository pattern?	Repo.GetMyObject	0
13477947	13476335	Visits by Traffic Type as a metric	var query1 = new DataQuery(dataFeedUrl)\n            {\n                Ids = string.Format("ga:{0}", profileId),\n                Dimensions = "ga:source,ga:medium",\n                Metrics = "ga:visits,ga:newVisits",\n                Sort = "ga:visits",\n                GAStartDate = startDate.ToString("yyyy-MM-dd"),\n                GAEndDate = endDate.ToString("yyyy-MM-dd"),\n                StartIndex = 1\n            };	0
6751687	6751426	Windows 7 - Disable Close Program/Debug Program Dialog, yet crash dump and notify the user	AppDomain.CurrentDomain.UnhandledException	0
12211576	12211444	Get sub-catalogs from registry	string[] subKeyNames = Registry.CurrentUser.OpenSubKey("AnyName").GetSubKeyNames();	0
6700438	6700195	Group item into Parent -> Child -> Grand-child relationship	List<Item> itemlist;\n    List<Item> newItemList;\n\n    public void main()\n    {\n        //Find all root items (aka, no parents)\n        foreach (Item item in itemlist)\n        {\n            if (item.Parent == null) getObjects(item.ID, 0);\n        }\n    }\n\n    public void getObjects(Item me, int deep)\n    {\n        //Store node\n        Console.WriteLine("this is me: " + me.ID);\n        Console.WriteLine("I am this many levels deep: " + deep);\n        newItemList.Insert(me);\n\n        //Find my children\n        foreach (Item item in itemlist)\n        {\n            if (item.Parent == me.ID) getObjects(item.ID, (deep + 1));\n        }\n    }	0
16521184	16521081	Connecting an SQL Project to a database	candordeveloper.com	0
2065213	2064196	Controlling user workflow in Winforms	using System;\nusing System.Windows.Forms;\n\nclass WizardPages : TabControl {\n  protected override void WndProc(ref Message m) {\n    // Hide tabs by trapping the TCM_ADJUSTRECT message\n    if (m.Msg == 0x1328 && !DesignMode) m.Result = (IntPtr)1;\n    else base.WndProc(ref m);\n  }\n}	0
5345449	5345383	How do I load a texture from a path in XNA at runtime?	FileStream filestream = new FileStream("mytexture.jpg");\nTexture2D myTexture = Texture2D.FromStream(graphicsDevice, filestream);	0
33048810	33034828	Resharper: How to find usage of a specific implementation of an interface	ToString()	0
6745279	6742945	Using Listview in C# to Show Information Saved in the Database	string query = "SELECT * FROM company where company_name Like '" + textBoxSearchCompany.Text + "%'";\n                listViewCompany.Items.Clear();\n                DBConn db = new DBConn();\n                DataTable tbl = db.retrieveRecord(query);\n                int x = 0;\n                foreach (DataRow row in tbl.Rows)\n                {\n                    ListViewItem lv = new ListViewItem(row[1].ToString());\n                    lv.SubItems.Add(row[2].ToString());\n                    lv.SubItems.Add(row[28].ToString());\n                    lv.SubItems.Add(row[29].ToString());\n                    listViewCompany.Items.Add(lv);\n                }	0
5655392	5655313	c# database update/insert with tableadapter	IF NOT EXISTS(SELECT customer_nr FROM Customers where customer_nr = @customer_nr)\n    BEGIN\n\n        ...(your query)\n\n    END	0
8095282	8095256	ASP.NET radio button change	AutoPostBack="true"	0
24962682	24962613	How to get all weekends within date range in C#	namespace DatimeApplication\n{\n   class Program\n   {\n       static void Main(string[] args)\n       {\n             DateTime startDate=new DateTime(2011,3,1);\n             DateTime endDate = DateTime.Now;\n\n             TimeSpan diff = endDate - startDate;\n             int days = diff.Days;\n             for (var i = 0; i <= days; i++)\n             {\n                 var testDate = startDate.AddDays(i);\n                 switch (testDate.DayOfWeek)\n                 {\n                     case DayOfWeek.Saturday:\n                     case DayOfWeek.Sunday:\n                         Console.WriteLine(testDate.ToShortDateString());\n                         break;\n                 }\n             }\n           Console.ReadLine();\n       }\n   }\n}	0
33764527	33764402	How to find the first occurance of a string that begins with "COM" in an array	int index = Array.FindIndex(options, s => s.StartsWith("COM"));	0
14142817	14142755	Loading a script by name in Unity3D	var gameObject = ... \n\ngameObject.AddComponent<Script>(); // where Script is the name of your Script's C# class	0
7120951	7120872	Algorithm to calculate nearest location based on longitude & latitude	haversine formula	0
14371514	10610393	How can I Mock HttpRequest[] indexer property	//\n// Set a variable in the indexer collction\n//\nMock<HttpRequestBase> request = new Mock<HttpRequestBase>();\nrequest.SetupGet(r => r["name"]).Returns("Fred Jones");	0
827584	827574	Dynamic updates of objects in a Silverlight application?	int SomeNumber \n{\n    get { return this.m_someInt; }\n    set { if ( value != this.m_someInt ) \n    {\n        this.m_someInt = value;\n        NotifyChange("SomeNumber");\n    } \n}\n\nNotifyChange( string propName )\n{\n.....\n}	0
23144052	23143739	Saving and Loading Strongly-Typed DataSet from Settings	[global::System.Configuration.UserScopedSettingAttribute()]\n[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\npublic global::System.Data.DataSet DocRetrieverDataSource {\n    get {\n        return ((global::FullNamespace.DocRetrieverDataSet)(this["DocRetrieverDataSource"]));\n    }\n    set {\n        this["DocRetrieverDataSource"] = value;\n    }\n}	0
7652526	7652175	Data Custom Array Groupping C#	var dict = new Dictionary<Tuple<bool, bool, bool, bool, int, int, int>, string[]>();\ndict[Tuple.Create(true, true, false, false, 2, 3, 5)] = new[] { "test", "pest" };	0
21238003	21233055	Salesforce datetime issues	_TempAccount.Date_End__c = DateTime.Now;\n_TempAccount.Date_End__c_Specified = True;	0
1078875	1078782	C# Iterate Over DataGridView & Change Row Color	public void ColourChange()\n    {\n        DataGridViewCellStyle RedCellStyle = null;\n        RedCellStyle = new DataGridViewCellStyle();\n        RedCellStyle.ForeColor = Color.Red;\n        DataGridViewCellStyle GreenCellStyle = null;\n        GreenCellStyle = new DataGridViewCellStyle();\n        GreenCellStyle.ForeColor = Color.Green;\n\n\n        foreach (DataGridViewRow dgvr in dataGridView1.Rows)\n        {\n            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))\n            {\n                dgvr.DefaultCellStyle = RedCellStyle;\n            }\n            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("Yes"))\n            {\n                dgvr.DefaultCellStyle = GreenCellStyle;\n            }\n        }\n    }	0
16838574	16838020	Selecting max Date from multiple tables	DbContext.Database.SqlQuery	0
27687748	27687080	Creating string index with Code first	[Column(TypeName = "VARCHAR")]\n[StringLength(n)]\n[Index]\npublic string CreatedBy { set; get; }	0
16541514	16541322	Regular expression, read from start of string	^[a-zA-Z]{2,5}-\d{3,}([,;\s][a-zA-Z]{2,5}-\d{3,})*	0
32582216	32566915	Master Detail Relation based on Information from 3rd Table	using (SqlConnection connection = new SqlConnection(_ConnectionString))\n{\n    connection.Open();\n    using (SqlDataAdapter adapter = new SqlDataAdapter())\n    {\n        using (SqlCommand command = new SqlCommand())\n        {\n            using (SqlCommandBuilder builder = new SqlCommandBuilder())\n            {\n                adapter.SelectCommand = command;// Command;\n                adapter.SelectCommand.Connection = connection;\n                builder.DataAdapter = adapter;\n\n                // here I let the command builder think that the table is myTable in stead of myView\n                adapter.SelectCommand.CommandText = "select * from myTable";\n                adapter.UpdateCommand = builder.GetUpdateCommand(true).Clone();\n                adapter.DeleteCommand = builder.GetDeleteCommand(true).Clone();\n\n                adapter.Update(Table);\n            }\n        }\n    }\n}	0
9565232	9565208	Running a piece of code just once in a class	public static class MyStaticClass\n{\n   public static int MyStaticProperty;\n\n   //no accessors required, as this is never explicitly invoked\n   static MyStaticClass() //no parameters either\n   {\n      MyStaticProperty = 100;\n   }\n}\n....\n//writes: 100\nConsole.WriteLine(MyStaticClass.MyStaticProperty);	0
25212538	25212510	How to use single result in While Loop?	var obj = GetObj();\nwhile(obj  == null || !obj.Initialized ){\n    doStuff();\n    obj = GetObj();\n}	0
10944059	10935114	Get selected value from drop down inside GridView on Update	protected void YourGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)\n {\n  DropDownList ddl= (DropDownList )YourGrid.Rows[e.RowIndex].FindControl("ddlId");\n  string selectedvalue=ddl.selectedvalue;\n  //Your update code goes here\n }	0
21967558	21965858	How to call controller method in global.asax?	protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)\n    {\n        if (User.Identity.IsAuthenticated)\n        {\n            IUnityContainer container = GetUnityContainer();\n            ISecurityService securityService = container.Resolve<SecurityService>();\n            var list = securityService.GetUserRolesandPermissions("1");\n        }\n    }	0
22908	22879	How do you prevent leading zeros from being stripped when importing an excel doc using c#	Provider=Microsoft.ACE.OLEDB.12.0;\n    Data Source=c:\path\to\myfile.xlsx;\n    Extended Properties=\"Excel 12.0 Xml;IMEX=1\";	0
5762008	5761976	.NET C#/VB.NET How to access Form Controls from Module	Module Module1\n    Private m_MyForm As Form1\n    Public ReadOnly Property MyForm() As Form1\n        Get\n            If IsNothing(m_MyForm) Then m_MyForm = New Form1\n            Return m_MyForm\n        End Get\n    End Property\n    Public Sub WriteLog(ByVal txt As String)\n        MyForm.TextBox3.Text += txt + vbNewLine\n    End Sub\nEnd Module	0
6961429	6961226	Variable increment step in WinForm NumericUpDown control depending on whether Shift/Ctrl/etc. are pressed	using System;\nusing System.Windows.Forms;\n\npublic class MyUpDown : NumericUpDown {\n    public override void UpButton() {\n        decimal inc = this.Increment;\n        if ((Control.ModifierKeys & Keys.Control) == Keys.Control) this.Increment *= 10;\n        base.UpButton();\n        this.Increment = inc;\n    }\n    // TODO: DownButton\n}	0
12467741	12467526	Thunking - Windows 7	kernel.dll	0
20826089	20825067	How to save image path in database	public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)\n{\n        using(ImageEntities db = new ImageEntities()){\n        if (file != null)\n        {\n            string pic = System.IO.Path.GetFileName(file.FileName);\n            string path = System.IO.Path.Combine(\n                                   Server.MapPath("~/images/profile"), pic);\n            file.SaveAs(path);\n            tbl_Image img=new tbl_Image();\n            img.imagepath=path;\n            db.tbl_Images.Add(img);\n            db.SaveChanges();\n        }\n\n        return View("FileUploaded", db.tbl_Image.ToList());\n        }\n}	0
3480750	3480730	Get PDF page size with iTextSharp	PdfReader reader = new PdfReader(m);\nPdfImportedPage page = writer.GetImportedPage(reader, i);\n// size information\n//page.PageSize.Width\n//page.PageSize.Height	0
8842507	8842115	Running out of connections in pool	//Clean Up Command Object\nif (mobj_SqlCommand != null)\n{\n  mobj_SqlCommand.Dispose();\n}\n\nif (mobj_SqlConnection != null)\n{\n  if (mobj_SqlConnection.State != ConnectionState.Closed)\n  {\n    mobj_SqlConnection.Close();\n  }\n  mobj_SqlConnection.Dispose();\n}	0
9695769	9695757	How to run a function in every 10 minutes with in the loop using c#?	public static System.Timers.Timer aTimer;\n...\naTimer = new System.Timers.Timer(50000);\naTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\naTimer.AutoReset = false; //This should be true if you want it actually looping\naTimer.Enabled = true;	0
2895246	2895066	Remove duplicate column values from a datatable without using LINQ	public DataTable RemoveDuplicateRows(DataTable dTable, string colName)\n    {\n        Hashtable hTable = new Hashtable();\n        ArrayList duplicateList = new ArrayList();\n\n        //Add list of all the unique item value to hashtable, which stores combination of key, value pair.\n        //And add duplicate item value in arraylist.\n        foreach (DataRow drow in dTable.Rows)\n        {\n            if (hTable.Contains(drow[colName]))\n                duplicateList.Add(drow);\n            else\n                hTable.Add(drow[colName], string.Empty);\n        }\n\n        //Removing a list of duplicate items from datatable.\n        foreach (DataRow dRow in duplicateList)\n            dTable.Rows.Remove(dRow);\n\n        //Datatable which contains unique records will be return as output.\n        return dTable;\n    }	0
11053414	11014189	Download and save image from HTML source	public static Stream DownloadImageData(CookieContainer cookies, string siteURL)\n{\n    HttpWebRequest httpRequest = null;\n    HttpWebResponse httpResponse = null;\n\n    httpRequest = (HttpWebRequest)WebRequest.Create(siteURL);\n\n    httpRequest.CookieContainer = cookies;\n    httpRequest.AllowAutoRedirect = true;\n\n    try\n    {\n        httpResponse = (HttpWebResponse)httpRequest.GetResponse();\n        if (httpResponse.StatusCode == HttpStatusCode.OK)\n        {\n            var httpContentData = httpResponse.GetResponseStream();\n\n            return httpContentData;\n        }\n        return null;\n    }\n    catch (WebException we)\n    {\n        return null;\n    }\n    finally\n    {\n        if (httpResponse != null)\n        {\n            httpResponse.Close();\n        }\n    }\n}	0
31404281	31387430	Select first letter of name with linq query from database	List<string> Capitals = (from u in db.Users\n                                 select u.Name[0].ToString().ToUpper()).Distinct().ToList();\n\n\n        telList.Items.Clear();\n\n        for (int i = 0; i < alpha.Length; i++)\n        {\n\n\n\n\n            ListItem listItem = new ListItem(Convert.ToString(alpha[i]));\n            listItem.Attributes.Add("value", Convert.ToString(i));\n\n            for (int j = 0; j < Capitals.Count; j++)\n            {\n                if (Convert.ToString(alpha[i]) == Capitals[j])\n                {\n                    listItem.Attributes.Add("class", "class1");\n                    break;\n                }\n                else\n                {\n                    listItem.Attributes.Add("class", "class2");\n                }\n            }\n\n\n\n            telList.Items.Add(listItem);\n        }	0
28616417	28616353	Best way to print your arrays in C#?	public static void PrintArray(int[,] arrayParam)\n{\n    for(int i = 0; i< arrayParam.GetLength(0); i++)\n    {\n         for(int j = 0; j < arrayParam.GetLength(1); j++)\n         {\n               Console.Write(" numbers[{0}{{1}}] = {2} ", i, j, arrayParam[i, j]);\n         }\n         Console.WritLine();\n    }\n}	0
8978986	8978870	XmlWriter in non locking mode	var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);\nvar xmlWriter = XmlWriter.Create(fs);	0
1785840	1785811	Programmatically check if a number is a palindrome	def is_palindrome(i):\n    s = str(i)\n    return s[::-1] == s	0
15729220	15729193	C# Action in Foreach	foreach(Fruit f in _Fruits)\n{\n    Fruit tmp = f;\n    field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));\n}	0
7514108	7512004	ActiveMQ with C# and Apache NMS - Count messages in queue	using (IConnection connection = factory.CreateConnection())\n{\n    connection.start ();\n\n     using (ISession session = connection.CreateSession())\n     {\n      //Whatever...\n     }\n\n}	0
2997157	2989400	Store files in C# EXE file	WriteResourceToFile("Project_Namespace.Resources.filename_as_in_resources.extension", "extractedfile.txt");\n\n\npublic static void WriteResourceToFile(string resourceName, string fileName)\n{\n    int bufferSize = 4096; // set 4KB buffer\n    byte[] buffer = new byte[bufferSize];\n    using (Stream input = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))\n    using (Stream output = new FileStream(fileName, FileMode.Create))\n    {\n        int byteCount = input.Read(buffer, 0, bufferSize);\n        while (byteCount > 0)\n        {\n            output.Write(buffer, 0, byteCount);\n            byteCount = input.Read(buffer, 0, bufferSize);\n        }\n    }\n}	0
12461668	12461592	how can i Show Search Time in Result?	Stopwatch Time = new Stopwatch();\nTime.Start();\nSearchDM();\nTime.Stop();\nConsole.WriteLine("Search Took: {0} Seconds", Time.Elapsed)	0
25892668	25875944	IsManipulationEnabled = true prevents touch toggling a togglebutton	private void EnableTouchDownTogglingOfToggleButton()\n{\n  EventManager.RegisterClassHandler( typeof( ToggleButton ), ToggleButton.LoadedEvent, new RoutedEventHandler( TurnOnManipulaitonEnabled ) );\n  EventManager.RegisterClassHandler( typeof( ToggleButton ), ToggleButton.TouchDownEvent, new RoutedEventHandler( EnableTouchDownTogglingHandler ) );\n}\n\nprivate void TurnOnManipulaitonEnabled( object sender, RoutedEventArgs e )\n{\n  // need to make sure all toggle buttons behave the same so we always assume IsManipulationEnabled is true\n  // otherwise it can open then close right after due to it firing again from mousedown being able to go through\n  ToggleButton toggle = sender as ToggleButton;\n  if ( toggle != null )\n    toggle.IsManipulationEnabled = true;\n}\n\nprivate void EnableTouchDownTogglingHandler( object sender, RoutedEventArgs e )\n{\n  ToggleButton toggle = sender as ToggleButton;\n  if ( toggle != null )\n    toggle.IsChecked ^= true;\n}	0
27422189	27422071	How to build an array copyto method	for (int i = 1; i < array.length; i++)\n{\n    array2[i] = array[i];\n}	0
18020685	18019965	Performance Counter Keeping cpuUsage under a certain percentage C#	float usage;\ndo {\n     Thread.Sleep(TimeSpan.FromSeconds(1));\n     usage = cpuUsage.NextValue();\n     Console.WriteLine(usage + " %");\n} while (usage < 50.00);	0
28338733	28338593	How to add new line in c#?	this.pnlInfo.Controls.Add(new LiteralControl("<br>"));	0
13903677	13903621	Convert a text fraction to a decimal	double FractionToDouble(string fraction) {\n    double result;\n\n    if(double.TryParse(fraction, out result)) {\n        return result;\n    }\n\n    string[] split = fraction.Split(new char[] { ' ', '/' });\n\n    if(split.Length == 2 || split.Length == 3) {\n        int a, b;\n\n        if(int.TryParse(split[0], out a) && int.TryParse(split[1], out b)) {\n            if(split.Length == 2) {\n                return (double)a / b;\n            }\n\n            int c;\n\n            if(int.TryParse(split[2], out c)) {\n                return a + (double)b / c;\n            }\n        }\n    }\n\n    throw new FormatException("Not a valid fraction.");\n}	0
5544035	5543972	Get fully-qualified name of an OU	temp.Path	0
4191740	4185371	How do I set Encoding on AlternateView	var alternateView = new AlternateView(fooFileName, fooMediaType)\n {\n      ContentType =\n      {\n           CharSet = Encoding.UTF8.WebName\n      }\n };	0
6716249	6716220	Csharp: Find & Replace string match between specific characters || in a string using Regex	string originalStringBefore = "http://www.abc.com?a=||ThisIsForRndNumber||&qq=hello&jj=||ThisIsForRndNumberAlso||";\n\nRandom r = new Random();\nRegex rgx = new Regex(@"\|\|.*?\|\|");\nConsole.WriteLine(rgx.Replace(originalStringBefore, "||" + r.Next(int.MaxValue) + "||"));	0
8264201	8264168	Where to put database under visual studio solutions for build and click once deployment?	Copy To Output Directory=copy if newer'	0
9868866	9307785	Generic export to CSV with tables	public Matrix<string> ApplyTemplate(object items)\n    {\n        ICollection<T> castedItems = new List<T>();\n        // Cast items as a List<T>\n        if (items is List<T>)\n        {\n            castedItems = (ICollection<T>)items;\n        }\n        else if (items is HashSet<T>)\n        {\n            castedItems = ((HashSet<T>)items).ToList();\n        }\n        // Generate rows\n        foreach (T item in castedItems)\n        {\n            this.Rows.Add(new CSVExportTableRow<T>(item));\n        }\n        // Instantiate the matrix\n        Matrix<string> matrix = new Matrix<string>();\n\n        // Generate matrix for every row\n        foreach (var row in this.Rows)\n        {\n            matrix = GenerateMatrix();\n            // Generate matrix for every sub table\n            foreach (var subTable in this.SubTables)\n            {\n                matrix = matrix.AddMatrix(subTable.ApplyTemplate(this.Link.Compile().DynamicInvoke(row.Item)));\n            }\n        }\n        return matrix;\n    }	0
10439731	10439491	Reading data from a CSV file with mixing data types	using (CsvReader reader = new CsvReader(FilePath, Encoding.Default))\n{\n   while (reader.ReadNextRecord())\n   {\n          sql = " Update Inventory set OnHand = " + reader.Fields[1] + " WHERE Sku = '" + reader.Fields[0] + "'";\n   }\n}	0
20084207	20082661	Set content of custom styled button in user control in XAML on WP8	public static readonly DependencyProperty TextProperty =\n        DependencyProperty.Register("Text", typeof(string), typeof(JapanButton), new PropertyMetadata(OnTextChanged));\n\n    private static void OnTextChanged(DependencyProperty d, DependencyPropertyChangedEventArgs e)\n    {\n        (d as JapanButton).ButtonJapan.Content = Text;\n    }	0
30094017	30093913	How to open a xaml page as a dialog in windows phone 8?	PopUp mypopup = new PopUp();\nmypopup.child = new Uri("Mypage.xaml",Urikind.RelativeOrAbsolute);	0
19304096	19303284	How to accumulate TimeOfDay in c# from strings	string[] times = { "12:00 AM", "12:00 PM", "12:05 AM" };\nconst string timePattern = "h:mm tt";\n\nDateTime[] dates = times.Select(x => DateTime.ParseExact(x, timePattern, null)).ToArray();\n\nTimeSpan totalTimeSpan = new TimeSpan();\n\nfor (int i = 1; i < dates.Length; i++)\n{\n    // Assume that each time is at least the same date as the previous time\n    dates[i] = dates[i - 1].Date + dates[i].TimeOfDay;\n\n    // If this time is earlier than the previous time then assume it must be on the next day\n    if (dates[i - 1].TimeOfDay > dates[i].TimeOfDay)\n        dates[i] = dates[i].AddDays(1);\n\n    totalTimeSpan += dates[i] - dates[i - 1];\n}\n\nConsole.WriteLine("Result is more than 24 hours? {0}", totalTimeSpan.TotalHours > 24);	0
28495907	28495759	How to reference a file in a different folder in a C# solution	string filename = Path.Combine(Environment.CurrentDirectory, "Resources\\spreadsheet.xlsx");	0
16509556	16509081	How to insert unicode (arabic) characters into SQL Server database	// define your INSERT statement with PARAMETERS\nstring insertStmt = "INSERT INTO dbo.Table1(title, datee, post, cat, imageurl) " +\n                    "VALUES(@title, @datee, @post, @cat, @imageurl)";\n\n// define connection and command\nusing(SqlConnection conn = new SqlConnection(yourConnectionStringHere))\nusing (SqlCommand cmd = new SqlCommand(insertStmt, conn))\n{\n     // define parameters and set their values\n     cmd.Parameters.Add("@title", SqlDbType.NVarChar, 100).Value = TextBox1.Text.Trim();\n     cmd.Parameters.Add("@datee", SqlDbType.DateTime).Value = DateTime.Now;\n     cmd.Parameters.Add("@post", SqlDbType.NVarChar, 100).Value = TextBox2.Text.Trim();\n     cmd.Parameters.Add("@cat", SqlDbType.NVarChar, 100).Value = DropDownList1.SelectedItem.Text.Trim();\n     cmd.Parameters.Add("@imageurl", SqlDbType.NVarChar, 250).Value = path;\n\n     // open connection, execute query, close connection\n     conn.Open();\n     int rowsInserted = cmd.ExecuteNonQuery();\n     conn.Close();\n}	0
23229892	23229504	Regex Comparison between two strings	bool isMatch = Operators.LikeString("BankAutoLoanByCustomer1.pdf", "Bank*Loan*1.pdf", Microsoft.VisualBasic.CompareMethod.Text);	0
7515803	7515721	Raising a function by timer	var thread = new Thread(o => {\n    while(true)\n    {\n        DoTick();\n        Thread.Sleep(1000);\n    }\n});	0
14718096	14718095	How do I arrange for VSS history to appear in code?	Keyword_Masks = *.cs, *.sql\nShadow = \n\n[Keyword Comments] \n*.cs = "//"\n*.sql = "--"	0
20206611	20164262	C# and Ubuntu - How do I get size of primary screen?	public Rectangle GetDisplaySize()\n{\n    // Use xrandr to get size of screen located at offset (0,0).\n    System.Diagnostics.Process p = new System.Diagnostics.Process();\n    p.StartInfo.UseShellExecute = false;\n    p.StartInfo.RedirectStandardOutput = true;\n    p.StartInfo.FileName = "xrandr";\n    p.Start();\n    string output = p.StandardOutput.ReadToEnd();\n    p.WaitForExit();\n    var match = System.Text.RegularExpressions.Regex.Match(output, @"(\d+)x(\d+)\+0\+0");\n    var w = match.Groups[1].Value;\n    var h = match.Groups[2].Value;\n    Rectangle r;\n    r.Width = int.Parse(w);\n    r.Height = int.Parse(h);\n    Console.WriteLine ("Display Size is {0} x {1}", w, h);\n    return r;\n}	0
3422676	3422462	tranform a snippet from c in c#	short CalcCrc(string str)\n    {\n        short crc = 0;\n        for (int i = 0; i < str.Length; i++)\n            crc ^= (short)(str[i] << (i % 9));\n        return crc;\n    }	0
20591254	20591155	How to mock An Abstract Base Class	[Test]\npublic void MoqTest()\n{\n    var mock = new Moq.Mock<AbstractBaseClass>();            \n    // set the behavior of mocked methods\n    mock.Setup(abs => abs.Foo()).Returns(5);\n\n    // getting an instance of the class\n    var abstractBaseClass = mock.Object;\n    // Asseting it actually works :)\n    Assert.AreEqual(5, abstractBaseClass.Foo());\n}	0
19454023	19453626	Dynamically setting a DataTable's RowFilter	var filterTerms = new List<string>();\n\n foreach (Control c in this.Controls)\n {\n     if (c is CheckEdit)\n     {\n        if (((CheckEdit)c).Checked)\n        {\n             filterTerms.Add(c.Tag.ToString());\n        }\n     }\n }\n\n dt.DefaultView.RowFilter = string.Join(" AND ", filterTerms);	0
33763973	33763886	My UpdatePanel containing a DropDowList isn't updating after I select an object from my ListView	//Assign the value found to the selectedValue of the ddlConfig\nthis.ddlConfig.SelectedValue =  this.ddlConfig.Items.FindByText(Configurations.Find(d => d.ID == ConfigurationID).Name).Value;	0
19031274	19031118	C# How to get Words From String	string s = "A~B~C~D";\nstring[] strings = Regex.Split(s, @"\W|_");	0
25287004	25286951	String Array Searching	int counts[122 - 97] = {0}; // codes of a - z\nchar a = get_next_char();\nif ( is_capital(a)){\n    counts[a - 65]++;\n}\nelse \n{\n    counts[a - 97] ++;\n}	0
4621138	4620833	Method having an abstract class as a parameter	void Main()\n{\nvar kewl = new X<C>(new C());\nkewl.FunnyMethod(); //calls C.DoJOB()\n\nvar kewl2 = new X<B>(new B());\nkewl2.FunnyMethod(); // calls B.DoJOB()\n\n}\n\npublic class X <T> where T : A<T>\n{\n    private A<T> foo;\n\n    public X(A<T> concrete)\n    {\n        foo = concrete;\n    }\n\n    public void FunnyMethod()\n    {\n        foo.DoJOB();\n    }\n}\n\npublic abstract class A<T> where T : A<T>\n{\n    public abstract void DoJOB();\n}\n\npublic class B : A<B>\n{\n    public override void DoJOB()\n    {\n        Console.WriteLine("B");\n    }\n}\n\npublic class C : A<C>\n{\n    public override void DoJOB()\n    {\n        Console.WriteLine("C");\n    }\n}	0
2254976	2248229	How do you programmatically adjust the horizontal divider of a PropertyGrid control?	private void ResizeDescriptionArea(PropertyGrid grid, int lines)\n{\n    try\n    {\n        var info = grid.GetType().GetProperty("Controls");\n        var collection = (Control.ControlCollection)info.GetValue(grid, null);\n\n        foreach (var control in collection)\n        {\n            var type = control.GetType();\n\n            if ("DocComment" == type.Name)\n            {\n                const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;\n                var field = type.BaseType.GetField("userSized", Flags);\n                field.SetValue(control, true);\n\n                info = type.GetProperty("Lines");\n                info.SetValue(control, lines, null);\n\n                grid.HelpVisible = true;\n                break;\n            }\n        }\n    }\n\n    catch (Exception ex)\n    {\n        Trace.WriteLine(ex);\n    }\n}	0
10342453	10342415	How to Delete folder older than 7 days C# / NET	DirectoryInfo d = new DirectoryInfo(dir);\n   if (d.CreationTime    < DateTime.Now.AddDays(-7))\n       d.Delete();	0
19935981	19935571	Start and stop parsing of a string	String val = "User/Confirmation?=QVNERkFTREY=&code=MTAvMjMvMjAxMyAxMjowMDowMCBBTQ==";\nSystem.Collections.Specialized.NameValueCollection parameters = System.Web.HttpUtility.ParseQueryString(val);\nConsole.Out.WriteLine(parameters[0]);  // QVNERkFTREY=\nConsole.Out.WriteLine(parameters.Get("code"); // MTAvMjMvMjAxMyAxMjowMDowMCBBTQ==	0
22959680	22949449	Binding data from view to ItemsPanelTemplate	public class Node\n{\n    public double ScaleX { get; set; }\n    public double ScaleY { get; set; }\n}	0
1579949	1547029	multithreading in c# compact framework	private readonly object syncRoot = new object();\nprivate object[] responses;\n\npublic void StartThreads(int numberOfThreads)\n{\n    this.responses = new object[numberOfThreads];\n\n    List<Thread> threads = new List<Thread>();\n    for (int i = 0; i < numberOfThreads; ++i)\n    {\n    Thread thread = new Thread(this.DoWork);\n    thread.Name = i.ToString();\n    threads.Add(thread);\n    thread.Start();\n    }\n\n    foreach (Thread thread in threads)\n    {\n    thread.Join();\n    }\n\n    // all threads are done.\n}\n\nprivate void DoWork()\n{\n    // do web call\n    // object response = web.GetResponse();\n    int threadNumber = Convert.ToInt32(Thread.CurrentThread.Name);\n    lock (this.syncRoot)\n    {\n    this.responses[threadNumber] = response;\n    }\n}	0
12110614	12110275	Selecting Soap XML node children in .net	XElement doc = XElement.Load("c:\\dd.xml");\nXNamespace ns1 = "http://schemas.xmlsoap.org/soap/envelope/";\nXNamespace ns2 = "http://api.dgm-uk.com/Publisher/schemas";\n\nvar items = doc.Descendants(ns1 + "Body").Descendants(ns2 + "GetSalesResponse").Descendants(ns2 + "sales").Descendants(ns2 + "sale")\n.Select((x) => new\n{\nsaleid = x.Element(ns2 + "saleid").Value,\ncampaignname = x.Element(ns2 + "campaignname").Value,\ncampaignid = x.Element(ns2 + "campaignid").Value,\nadvertisername = x.Element(ns2 + "advertisername").Value\n});\n\nforeach (var itm in items)\n{\nConsole.WriteLine("saleid:" + itm.saleid);\nConsole.WriteLine("campaignid:" + itm.campaignid);\nConsole.WriteLine("campaignname:" + itm.campaignname);  \nConsole.WriteLine("advertisername:" + itm.advertisername);\n}	0
4352023	4351811	How do I remove files from the application data directory on uninstall?	string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);	0
26944436	26790891	Creating Edges with OrientDB-NET.binary in a transaction	var v1 = new ODocument { OClassName = "TestVertex" };\n        v1.SetField("Name", "First");\n        v1.SetField("Bar", 1);\n\n        var v2 = new ODocument { OClassName = "TestVertex" };\n        v2.SetField("Name", "Second");\n        v2.SetField("Bar", 2);\n\n        var e1 = new ODocument { OClassName = "TestEdge" };\n        e1.SetField("Weight", 1.3f);\n\n        // Add records to the transaction\n        _database.Transaction.Add(v1);\n        _database.Transaction.Add(v2);\n        _database.Transaction.Add(e1);\n\n        // link records\n        v1.SetField("in_TestEdge", e1.ORID);\n        v2.SetField("out_TestEdge", e1.ORID);\n        e1.SetField("in", v1.ORID);\n        e1.SetField("out", v2.ORID);\n\n        _database.Transaction.Commit();	0
13821805	13821616	How to open print dialog box of any application (like word,pdf reader) on the same time while openning the document, Programmitically	Private Sub Workbook_Open()\n\n    Application.Dialogs(xlDialogPrint).Show\n\nEnd Sub	0
16316563	16314945	update asp.net label located on a control in master page from the content page	protected void Page_Load(object sender, EventArgs e)\n{\n    UserControl US = FindControl("CompanyLhsMenu") as UserControl;\n    Literal ltrel;\n\n    try\n    {\n        US = (UserControl)Master.FindControl("menu");\n\n        ltrel = (Literal)US.FindControl("SavedCVLiteral");\n\n        if (ltrel != null)\n        {\n            ltrel.Text = "update it";\n        }\n    }\n    catch (Exception ex)\n    {\n    }\n}	0
31208202	31207067	Firefox driver for selenium	IWebDriver driverOne = new FirefoxDriver();\nIWebDriver driverTwo = new InternetExlorerDriver("C:\\PathToMyIeDriverBinaries\");	0
17877158	17860855	word add-in, KeyDown handling on combobox in customui	private static IntPtr HookCallback(\n                int nCode, IntPtr wParam, IntPtr lParam)\n            {\n                if (nCode >= 0 && wParam == (IntPtr) WM_KEYDOWN)\n                {\n                    int vkCode = Marshal.ReadInt32(lParam);\n                    //Check if the enter key is pressed\n                    if (vkCode == (int) Keys.Enter )\n                        // Do here whatever you need\n                }\n                return CallNextHookEx(_hookID, nCode, wParam, lParam);\n            }	0
6541019	6540989	Get a an item from a IGrouping based on the highest date	.GroupBy(n => n.Name)\n.Select(d => d.OrderByDescending(t => t.LastModified).First())	0
27109515	27107250	Managing Single Quotes while calling on a Stored Procedure	var escapedValue = originalValue.Replase("'","''");	0
7621687	7372272	cant get the printer to print a custom sized paper in C# Windows Form Project	PrintDocument pd = new PrintDocument();\n          PaperSize paperSize = new PaperSize("MyCustomSize", 200, 200 ); //numbers are optional\n\n           paperSize.RawKind = (int)PaperKind.Custom;\n\n           pd.DefaultPageSettings.PaperSize = paperSize;	0
12382353	12382159	Recognize pattern to extract words from C# HTML Encoded String	string strHTMLText=@"&lt;p&gt;Pellentesque habitant [[@Code1]] morbi tristique senectus [[@Code2]] et netus et malesuada fames ac [[@Code3]] turpis egestas.&lt;/p&gt;";\nvar input = HttpUtility.HtmlDecode(strHTMLText);\nvar list = Regex.Matches(input, @"\[\[@(.+?)\]\]")\n    .Cast<Match>()\n    .Select(m => m.Groups[1].Value)\n    .ToList();	0
7899377	7899366	Try-catch creating new array in C# - where to initialize it?	string[] logContent = null; \ntry\n{\n    logContent = File.ReadAllLines(aLogFile);\n}\ncatch\n{\n    // Be careful with the error message here => there might be other reasons\n    // that the ReadAllLines threw an exception\n    throw new Exception("LoggerStandard: Specified Logfile exists but could not be read.");\n}	0
23367982	23367783	How to sort by alphabetically using struct and arraylist with c#	List<Worker> listw = new List<Worker>();\nWorker W;\nStreamReader file= new StreamReader("Workers.txt", Encoding.Default);\n\nwhile (!file.EndOfStream)\n{\n    string[] wtemp = file.ReadLine().Split(',');\n    W = new Worker(wtemp[0],wtemp[1],Convert.ToInt32(wtemp[2]),Convert.ToInt32(wtemp[3]));\n    listw.Add(W);\n}\n\n//Sort by name.\nlistw = listw.OrderBy(x=> x.FIO).ToList();\n\nforeach (Worker outworker in listw)\n{\n    Console.WriteLine(outworker.FIO,outworker.Dolj,outworker.Staj,outworker.Zp);\n}	0
29547980	29547501	Get specific values from XML returned by web service	ForecastReturn fr = new ForecastReturn();\n        Weather service = new Weather();\n        fr = service.GetCityForecastByZIP("44060");\n        string YourMagicVariable = fr.ForecastResult[0].Desciption;	0
3977983	3977834	asp CompareValidator validating after postback	BaseCompareValidator.Type	0
13328600	13328427	how do you display xml data from wcf service in windows form app in datagridview or reportview?	using (nServiceReferenceCustomers.GetCustomerClient svc = new ServiceReferenceCustomers.GetCustomerClient())\n    {\n        XmlNode node = svc.GetAllCustomer();\n        DataSet ds = new DataSet();\n        using (XmlNodeReader reader = new XmlNodeReader(node))\n        {\n            ds.ReadXml(reader);\n        }\n\n\n        DataTable table = ds.Tables["Table"];\n        DataRow row = table.Rows[0];\n        string Lastname= (string) row["lastname"];\n        string Firstname= (string) row["firstname"];\n        string Middlename= (string) row["middlename "];\nstring email= (string) row["emailaddress"];\nstring Phone= (string) row["phonenumber"];\n    }	0
31645978	31645617	Storing Selected CheckedListBox Values in Database	//check if any item is selected\nif (checkedListBox1.SelectedItems.Count > 0)\n{\n    //connect to database\n    string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");\n    NpgsqlConnection conn = new NpgsqlConnection(connstring);\n    conn.Open();\n\n    //loop through all selected items\n    foreach (object item in checkedListBox1.CheckedItems)\n    {\n        //convert item to string\n        string checkedItem = item.ToString();\n\n        //insert item to database\n        NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (@famid)", conn);\n        cmd.Parameters.AddWithValue("@famid", checkedItem); //add item\n        cmd.ExecuteNonQuery();\n    }\n\n    //close connection\n    conn.Close();\n    MessageBox.Show("Data has been saved");\n}	0
21145801	21145770	Background Color, ForegroundColor	static void Main(string[] args)\n{\n var originalColor = Console.BackgroundColor;\n Console.BackgroundColor = ConsoleColor.Red;\n Console.Write("The background color is red. ");\n Console.BackgroundColor = originalColor;\n Console.ForegroundColor = ConsoleColor.Green;\n Console.Write("The foreground color is green");\n Console.ReadKey();\n}	0
11913890	11912920	How to find column existence in data table in C#?	int indx = 6;\n if(dt != null and dt.Columns.Count > indx)\n {\n     Txt_name.Text=dt.Rows[0][indx].ToString();\n }	0
3095061	3094998	split the message into array	string[] messageArray = Request.QueryString["message"].Split(';');\nstring formName = messageArray[0];\nstring[] fieldArray = messageArray[1].Split(',');	0
16715041	16694232	Get all users that have ever logged into a pc with c#	using System.Security.Principal;\nusing System.Management;\nprivate void GetLocalUserAccounts()\n{\n     SelectQuery query = new SelectQuery("Win32_UserProfile");\n     ManagementObjectsSearcher searcher = new ManagementObjectSearcher(query);\n     foreach (ManagementObject sid in searcher.Get())\n     {\n          MessageBox.Show(new SecurityIdentifier(sid["SID"].ToString()).Translate(typeof(NTAccount)).ToString());\n     }\n}	0
5740878	5740772	How to insert xml node using linq2xml?	XElement dataWorkers=  new XElement("worker", \n                                    new XAttribute("name", 1),\n\n                                    new XAttribute("workshop", 2),\n\n                                    new XAttribute("salary",25000)\n\n//another way to add a worker to dataWorkers\nXElement worker = new XElement("worker");\n            XAttribute name = new XAttribute("name",1);\n            XAttribute workshop = new XAttribute("workshop",4);\n            XAttribute salary = new XAttribute("salary",25000);\n            worker.Add(name);\n            worker.Add(workshop);\n            worker.Add(salary);\ndataWorkers.Add(worker);\n\nXDocument myXml= new XDocument( new XDeclaration("1.0", "UTF-8", "true"),\n                                new XElement(dataWorkers));	0
4368830	4131766	Please tell me a architecture to use in a Windows Form project	BO------UI\n|       |\n--------BL\n|       |\n--------DA	0
19097670	19097493	Access Control Template's children inside code in WPF	private static DependencyObject RecursiveVisualChildFinder<T>(DependencyObject rootObject)  \n{  \n    var child = VisualTreeHelper.GetChild(rootObject, 0);  \n    if (child == null) return null;  \n\n    return child.GetType() == typeof (T) ? child : RecursiveVisualChildFinder<T>(child);  \n}	0
14428865	14428733	Programmatically Move a File to Program Files without Admin Rights?	Program Files	0
5651002	5650909	Regex help with extracting certain part of a String	const string str = "Name: music mix.mp3 Size: 2356KB";\nvar match = Regex.Match(str, "Name: (.*) Size:");\nConsole.WriteLine("Match: " + match.Groups[1].Value);	0
17070790	17070583	Releasing a Mutex	bool iOwnTheMutex;\n\ntry {\n    // set up mutex here...\n    iOwnTheMutex = mutex.WaitOne(2000);\n    if (iOwnTheMutex) {\n       // do what you need to do\n    }\n}\nfinally {\n    if (mutex != null && iOwnTheMutex) {\n       mutex.ReleaseMutex();\n    }\n}	0
25787982	25787861	After using a struct from PInvoke, do I need to release the memory?	Marshal.StructureToPtr<TEXTMETRIC>(tm, ptr, true);	0
11939541	11939433	Add routing rules in MVC app	routes.MapRoute(\n            "Search", // Route name\n            "{product}/{page}", // URL with parameters\n            new { controller = "Home", action = "Search", product = UrlParameter.Optional, page = UrlParameter.Optional } // Parameter defaults\n        );	0
22826918	22826193	Getting Table's Row Index Using LINQ	ddlRole.Items[0].Text = RoleName	0
23153912	23153434	Copying variables from one picturebox to another without making them change with each other	public static class MyExtensions\n{\n    public static PictureBox CreateNewWithAttributes(this PictureBox pb)\n    {\n        return new PictureBox { Image = pb.Image, Width = pb.Width };\n    }\n}\n\nPicturebox p2 = p1.CreateNewWithAttributes();\nthis.Controls.Add(p2);	0
34409791	34409023	how to fetch node elements from XML file by using xpath query,	private void Search2_Click_1(object sender, EventArgs e)\n        {\n  string ha = search.Text;\n\nXmlNodeList nodes = myxml.DocumentElement.SelectNodes("/students/student/[contains(s_name,ha)]");\n\n}	0
5602479	5602400	How to Convert IList<SomeObject> to IList<ISomeInterface> where SomeObject implements ISomeInterface using covariance in C# 4.0	IList<Items> GetItems;\nIList<IItems> items = GetItems().Cast<IItems>().ToList();	0
12923698	12923656	Statements after Switch being skipped	try{}catch{}	0
3553036	3551161	How do I block until a thread is returned to the pool?	public class Example\n{\n  private CountdownEvent m_Finisher = new CountdownEvent(0);\n\n  public void MainThread()\n  {\n    m_Finisher.AddCount();\n\n    // Your stuff goes here.\n    // myListener.BeginAcceptSocket(OnAcceptSocket, null);\n\n    m_Finisher.Signal();\n    m_Finisher.Wait();\n  }\n\n  private void OnAcceptSocket(object state)\n  {\n    m_Finisher.AddCount()\n    try\n    {\n      // Your stuff goes here.\n    }\n    finally\n    {\n      m_Finisher.Signal();\n    }\n  }\n}	0
12809486	12809373	WinfForms Maximized Window With Border None Hides Taskbar	this.Width = Screen.PrimaryScreen.Bounds.Width;\nthis.Height = Screen.PrimaryScreen.Bounds.Height - 40;\n\nthis.Location = new Point();\n\nthis.StartPosition = FormStartPosition.Manual;	0
23901972	23901540	How to get source of image in WS app	ImageSource source = img.Source;\nBitmapImage bitmapImage = source as BitmapImage;	0
4326135	4326010	How do I sort a custom array list by the dateTime elements	public class Loan\n{\n    public DateTime date { get; set; }\n\n}\n\npublic class LoanComparer : IComparer\n{\n    public int Compare(object x, object y)\n    {\n        Loan loanX = x as Loan;\n        Loan loanY = y as Loan;\n\n        return loanX.date.CompareTo(loanY.date);\n    }\n}\n\n\nstatic void Main(string[] args)\n{\n    Loan l1 = new Loan() {date = DateTime.Now};\n    Loan l2 = new Loan() { date = DateTime.Now.AddDays(-5) };\n\n    ArrayList loans = new ArrayList();\n    loans.Add(l1);\n    loans.Add(l2);\n\n\n    loans.Sort(new LoanComparer());\n}	0
31670763	31670691	How Do I Convert Strings To Int?	int num1 = int.Parse(TextBox1.Text);\n\ndouble num2 = double.Parse(TextBox2.Text.Replace(".", ",")); // <---- \n\nint num3 = int.Parse(TextBox3.Text;);\nsoln1 = (int)(num1 * num2 * num3); // <----\nMessageBox.Show(soln1.ToString());	0
6748232	6748196	SQLite3.dll for Windows 7 64 bit	System.Data.SQLite	0
19407708	19407627	How to split a txtbox.Text	DateTime time = DateTime.Parse(txt);\ntime.Year;	0
930175	930083	How do I work with an XML tag within a string?	var myString = "This is my <myTag myTagAttrib='colorize'>awesome</myTag> string.";\ntry\n{\nvar document = XDocument.Parse("<root>" + myString + "</root>");\nvar matches = ((System.Collections.IEnumerable)document.XPathEvaluate("myTag|myTag2")).Cast<XElement>();\nforeach (var element in matches)\n{\nswitch (element.Name.ToString())\n{\ncase "myTag":\n//do something with myTag like lookup attribute values and call other methods\nbreak;\ncase "myTag2":\n//do something else with myTag2\nbreak;\n}\n}\n}\ncatch (Exception e)\n{\n//string was not not well formed xml\n}	0
19939111	19938991	getting many messages of a Table change from data gridview in C#	Data Source=SAROTH-PC\SQLEXPRESS	0
13088482	13088436	Preforming a block of code only once	[MethodImpl(MethodImplOptions.Synchronized)]\npublic override MyObject Load()\n{\n   //snip\n}	0
23040573	23040482	How to Get element by class in HtmlAgilityPack	foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//span[@class='" + ClassToGet + "']"))\n{\n    string value = node.InnerText;\n    // etc...\n}	0
34564413	34563514	What to do if i want to get first cell value from telerik Multi combo box?	string text;\n        text = string.Format("Row changed, current Name = {0}", radMultiColumnComboBox3.EditorControl\n                                            .Rows[radMultiColumnComboBox3.SelectedIndex].Cells["id"].Value);	0
906514	906493	How do I access named capturing groups in a .NET Regex?	foreach (Match m in mc){\n    MessageBox.Show(m.Groups["link"]);\n}	0
15321559	15309949	Silverlight, update gui by changing img source c#	public MainPage()\n{\n    InitializeComponent();\n    DispatcherTimer timer = new DispatcherTimer() { Interval = TimeSpan.FromHours(1) };\n    timer.Tick += new EventHandler(timer_Tick);\n    SetImageSource();\n    timer.Start();\n}\n\nvoid timer_Tick(object sender, EventArgs e)\n{\n    SetImageSource();\n}\n\nvoid SetImageSource()\n{\n    int hour = DateTime.Now.Hour;\n    if (hour % 10 == 0)\n        imag1.Source = new BitmapImage(new Uri("img/knapTaand.png", UriKind.Relative));\n    else\n        imag1.Source = new BitmapImage(new Uri("img/knapSluk.png", UriKind.Relative));\n}	0
30258333	30258174	Using value of propertie in his own custom attribute	[Printable(FormatStyle = FormatStyles.XY)]\npublic int MyProperty{ get; set; }	0
12439162	12439121	consuming json webservice in windows phone 7	Content-Encoding: gzip	0
14951787	14951618	Order by anonymous method	var sortedVehicles = vehicleList.OrderBy<Vehicle, string>(c=>\n    {\n        ...\n    });	0
5173219	5172542	WP7 Popup delays opening when used with locations	ShowPoup(); \nif (_watcher == null)\n{\n    _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);\n    _watcher.MovementThreshold = 15; // use MovementThreshold to ignore noise in the signal\n    _watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);\n}\n\nSystem.Threading.ThreadPool.QueueUserWorkItem((ignored) =>\n{\n    if (!_watcher.TryStart(true, TimeSpan.FromSeconds(3)))\n    {\n        Dispatcher.BeginInvoke(() =>\n        {\n            HidePopup();\n            MessageBox.Show("Please turn on location services on device under Settings.");\n        }\n    });\n});	0
11085946	11085907	Get a part of an C# dataset and c opy it into another dataset	DataSet filterResult = new DataSet();\nfilterResult.Merge(inputDataset.Tables[0].AsEnumerable().Where(r => r["Property1"].ToString().Equals("SomeFilter") || r["Property2"].ToString().Equals("Some other filter")).ToArray());	0
33302036	33301907	SelectList with multiple values using C#	public static IEnumerable<MultValoredItem> DropDownList()\n{\n    var brandServices = new BrandService();\n\n    var brandsDTO = brandServices.GetAll().OrderBy(b => b.Name);\n\n    var brandsList = brandsDTO.Select(brand =>\n    new MultValoredItem\n    {\n        Value1 = brand.Id.ToString(),\n        Value2 =  //Another value here\n        Text = brand.Name\n    });\n\n    return brandsList;\n}\n\npublic class MultValoredItem\n{\n    public int Value1 { get; set; }\n    public int Value2 { get; set; }\n    public string Text { get; set; }\n}\n\n<ul id="sch-brand-dropdown">\n  @foreach (var brand in Model.BrandList)\n  {\n    <li data-id1="@brand.Value1" data-id2="@brand.Value2">@brand.Text</li>\n  }\n</ul>	0
8558800	8558763	XElement => Add children nodes at run time	var x = new XElement("root",\n             new XElement("name", "AAA"),\n             new XElement("last", "BBB"),\n             new XElement("children",\n                 from c in family\n                 select new XElement("child",\n                             new XElement("name", "XXX"),\n                             new XElement("last", "TTT")\n                        )\n             )\n        );	0
2001220	2001133	How do I draw an image reflection in WinForms?	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass ImageReflection: Form\n{\n     Image image = Image.FromFile("Color.jpg");\n\n     public static void Main()\n     {\n          Application.Run(new ImageReflection());\n     }\n     public ImageReflection()\n     {\n          ResizeRedraw = true;\n\n     }\n     protected override void OnPaint(PaintEventArgs pea)\n     {\n          DoPage(pea.Graphics, ForeColor,ClientSize.Width, ClientSize.Height);\n     }     \n     protected void DoPage(Graphics grfx, Color clr, int cx, int cy)\n     {\n          int cxImage = image.Width;\n          int cyImage = image.Height;\n\n          grfx.DrawImage(image, cx / 2, cy / 2,  cxImage,  cyImage);\n          grfx.DrawImage(image, cx / 2, cy / 2, -cxImage,  cyImage);\n          grfx.DrawImage(image, cx / 2, cy / 2,  cxImage, -cyImage);\n          grfx.DrawImage(image, cx / 2, cy / 2, -cxImage, -cyImage);\n     }\n}	0
7240045	7239936	How to check Condition for executing Application through Shell propmt using C#	namespace WindowsFormsApplication1\n{\n    static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static void Main()\n        {\n            if (args != null && args.Contains("-nogui"))\n            {\n                // start command shell app version\n            }\n            else\n            {\n                // start UI app version\n                Application.EnableVisualStyles();\n                Application.SetCompatibleTextRenderingDefault(false);\n                Application.Run(new Form1());\n            }\n        }\n    }\n}	0
18988950	18988348	Error in Sending Email via a SMTP Client	MailMessage message = new System.Net.Mail.MailMessage(); \nstring fromEmail = "myaddr@gmail.com";\nstring fromPW = "mypw";\nstring toEmail = "recipient@receiver.com";\nmessage.From = new MailAddress(fromEmail);\nmessage.To.Add(toEmail);\nmessage.Subject = "Hello";\nmessage.Body = "Hello Bob ";\nmessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;\n\nusing(SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))\n{\n    smtpClient.EnableSsl = true;\n    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;\n    smtpClient.UseDefaultCredentials = false;\n    smtpClient.Credentials = new NetworkCredential(fromEmail, fromPW);\n\n    smtpClient.Send(message.From.ToString(), message.To.ToString(), \n                    message.Subject, message.Body);   \n}	0
29030743	29030490	How to copy folder from shared drive to c:\program files in c#	flinfo.CopyTo(Path.Combine(targetPath, flinfo.Name), true);	0
17871341	17870846	Many to many relationship with mocking	var video1 = new Video {EmbedSource = "embedcode", ID = 1};\nvar video2 ...\nvar tag1 = new Tag {ID = 0, Name = "testtestest"};\nvar tag2 ...\nvideo1.Tags = new List<Tag> { tag1, tag2 };\ntag1.Videos = new List<Video> { video1, video2};\n\nMock<IVideosRepository>  mock = new Mock<IVideosRepository>();\n  mock.Setup(m => m.GetVideos).Returns(new List<Video>\n  {\n    video1, video2\n  })	0
22819932	22819060	Loading images into windows phone app from external url	BitmapImage img = new BitmapImage(new Uri("https://www.image.url/address.png"));	0
30073653	30073273	C# showing only the values from sql table with null value	while(reader.Read())\n{\n    Console.WriteLine("{1} , {0}", reader["tabledateandtime"] == DBNull.Value ? "NULL" : reader["tabledateandtime"].ToString(),  reader["tableuser"].ToString()));\n}	0
31846366	31845498	Can't set ItemsSource property without TargetInvocationException	private void textBox_TextChanged(object sender, TextChangedEventArgs e)\n    {\n            if (!grid.IsLoaded)\n            return;\n   //rest of your code\n  }	0
8725431	8725039	IIS pool recycle, pool restart, app restart, web.config update - global asax	iisreset /restart	0
8808694	8808648	Proper Way to Format SQL Query Within C# Application	string sql = @"\n    SELECT * \n    FROM mytable \n    ORDER BY Server";\nOleDbDataAdapter da_ssm_servers = new OleDbDataAdapter(sql, connSSM);	0
24144484	24144047	Making a mulitdimensional jagged array	string[][] data = File.ReadLines(filename)\n    .Where(line => line.Contains("EFIX"))\n    .Select(line => line.Split(delimiterChars))\n    .ToArray();//omit this last call to allow the data to be streamed, \n    //greatly removing the memory footprint of the application at no real \n    //additional cost, assuming you have no compelling reason to eagerly \n    //load the whole file into memory.\n\nforeach(var line in data)\n    Console.WriteLine(line);	0
26138874	26138770	Must declare a scalar variable'@site_name'?	string value=///set the value you want\n...\n cmd = new SqlCommand("select top (1)  Dg_energy_daily, Load_energy_daily, mains_energy_daily,solar_energy_daily  From tbl_energy_report inner join tbl_site_details ON tbl_energy_report.Site_ID=tbl_site_details.site_id where tbl_site_details.site_name=@site_name order by tbl_energy_report.sl_no desc", con);         \n cmd.Paramaters.AddWithValue("@site_name ", value);	0
16802762	16802712	Implementing an Interface at Runtime	using ImpromptuInterface;\n\npublic interface ISimpleClassProps\n{\n  string Prop1 { get;  }\n  long Prop2 { get; }\n  Guid Prop3 { get; }\n}\n\nvar tAnon = new {Prop1 = "Test", Prop2 = 42L, Prop3 = Guid.NewGuid()};\nvar tActsLike = tAnon.ActLike<ISimpleClassProps>();	0
11987699	11987579	How to Generate a new Session ID	SessionIDManager manager = new SessionIDManager();\n\nstring newID = manager.CreateSessionID(Context);\nbool redirected = false;\nbool isAdded = false;\nmanager.SaveSessionID(Context, newID, out redirected, out isAdded);	0
11490518	11490470	C# - app config doesn't change	vshost.exe	0
1980115	1980105	How do I get %LocalAppData% in c#?	Environment.GetEnvironmentVariable("LocalAppData")	0
10372993	10372806	How to send data from .NET Server app to Windows 8 Metro Client app with Sockets?	receive N characters (or bytes, whatever).\ndecode N to get number of characters following, say M.\nreceive M characters.\nrepeat ad nauseam.	0
26181410	26181337	Do I need to close the datareader	using(MySqlConnection myConnection = new MySqlConnection(sConnection))\nusing(MySqlCommand myCommand = myConnection.CreateCommand())\n{\n    myConnection.Open();\n    myCommand.CommandText = query;\n    foreach (var p in sqlParams)\n        myCommand.Parameters.Add(p);\n    using(MySqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection))\n    {\n        dt.Load(myReader);\n    }\n}	0
27435170	26417427	Replicating this PUT request in RestSharp	request.AddBody(new { table = "users", settings = new[] { new { name = "dnd", value = "true" } } });	0
18195460	18195221	Type Data From InvalidCastException	static void Main(string[] args)\n{\n    try\n    {\n        string a = Cast<string>(1);\n    }\n    catch (InvalidCastExceptionEx ex)\n    {\n        Console.WriteLine("Failed to convert from {0} to {1}.", ex.FromType, ex.ToType);\n    }\n}\n\n\n\npublic class InvalidCastExceptionEx : InvalidCastException\n{\n    public Type FromType { get; private set; }\n    public Type ToType { get; private set; }\n\n    public InvalidCastExceptionEx(Type fromType, Type toType)\n    {\n        FromType = fromType;\n        ToType = toType;\n    }\n}\n\nstatic ToType Cast<ToType>(object value)\n{\n    try\n    {\n        return (ToType)value;\n    }\n    catch (InvalidCastException)\n    {\n        throw new InvalidCastExceptionEx(value.GetType(), typeof(ToType));\n    }\n}	0
23152149	23152097	Binding a user control text property in code-behind	Binding binding = new Binding();\nbinding.Path = new PropertyPath("yourPropertyTobeBinded");\nbinding.Source = sourceObject;\nBindingOperations.SetBinding(youTextBox, TextBox.TextProperty, binding);	0
4339631	4317494	How to programmatically add a RibbonTab to WPF Ribbon (October 2010 release)?	Ribbon.Items.Add(new RibbonTab())	0
13585848	13585591	How to divide a number into multiple parts so that the resulting sum is equal to the input?	static IEnumerable<decimal> SplitValue2(decimal value, int count)\n{\n    if (count <= 0) throw new ArgumentException("count must be greater than zero.", "count");\n    var result = new decimal[count];\n\n    decimal runningTotal = 0M;\n    for (int i = 0; i < count; i++)\n    {\n        var remainder = value - runningTotal;\n        var share = remainder > 0M ? Math.Max(Math.Round(remainder / ((decimal)(count - i)), 2), .01M) : 0M;\n        result[i] = share;\n        runningTotal += share;\n    }\n\n    if (runningTotal < value) result[count - 1] += value - runningTotal;\n\n    return result;\n}	0
25675645	25675268	Limit string to eight characters and return it with asterisk	string _backingFieldLastName;\npublic string LastName\n{\n    get\n    {\n        return _backingFieldLastName == null || backingFieldLastName.Length <=8 ? \n               _backingFieldLastName :\n               _backingFieldLastName.Substring(0,8) +"**"; // second parameter of substring is count of chars from the start index (first parameter)\n    }\n    set\n    {\n       _backingFieldLastName = value;\n    }\n}	0
1230914	1230902	How can a string array be databound to a ListBox?	mylistBox.DataSource = this.ProcessNames;	0
11180139	11180082	Word Split Algorithm into Prefix Stem and Suffix	string s="wbAlErbyp";\n\nconst int maxPrefixLength = 4;\nconst int maxSuffixLength = 6;\nconst int minStemLength = 1;\n\nfor(int prefixLength = 0; (prefixLength + minStemLength <= s.Length) && (prefixLength<=maxPrefixLength); prefixLength++)\n    for(int suffixLength = 0; (suffixLength + prefixLength + minStemLength <= s.Length) && (suffixLength<=maxSuffixLength); suffixLength++)\n    {\n        string prefix = s.Substring(0, prefixLength);\n        string suffix = s.Substring(s.Length-suffixLength);\n        string stem   = s.Substring(prefixLength, s.Length-suffixLength-prefixLength);\n        Console.WriteLine("{0} {1} {2}",prefix,stem, suffix);\n    }	0
14731862	14598270	How to Group Data by week in Linq	source.GroupBy(x => SqlFunctions.DatePart("ww", x.MeasurementDate));	0
646886	646838	EntityFramework many-to-many with junction table	public partial class Group\n{\n    public ObjectQuery<Member> Members\n    {\n        get\n        {\n            return (from j in DataModel.MemberGroup\n                    where j.Group.ID == this.ID\n                    select j.Member) as ObjectQuery<Member>;\n        }\n    }\n}	0
13394774	13394730	copy Column value from table to table, skip first 3 rows	for(int i=3; i < excelTb2.Rows.Count; i++) //start the loop with index 3 => Row 4\n{\n    DataRow ex2 = exceltb2.Rows[i];\n    //ex2["ABC"] = ex1["ABC"];      // with skip(3) ?\n    //ex2["Name"] = ex1["Name"];\n    //ex2["ID"] = ex1["ID"];\n}	0
31324213	31323384	How to Convert a C# Dictionary in the code to a Powershell object?	var hashtable = new Hashtable();\nforeach (var kvPair in dict) {\n    var hashtableInner = new Hashtable();\n    foreach (var kvPairInner in kvPair.Value) {\n        hashtableInner.Add(kvPairInner.Key, kvPairInner.Value);\n    }\n\n    hashtable.Add(kvPair.Key, hashtableInner);\n}\n\n# Pass hashtable to PowerShell as even v2 understands .NET hashtables	0
8873784	8871649	LINQ to CheckBoxList data items	IEnumerable<int> allChecked = (from ListItem item in CheckBoxList1.Items.OfType<ListItem>()\n                                   where item.Selected  \n                                   select int.Parse(item.Value));	0
16665764	16665389	How to set new XML document from XML feed	var xDoc = XDocument.Load("http://search.twitter.com/search.atom?q=test&show-user=true&rpp=10");\nXNamespace ns = "http://www.w3.org/2005/Atom";\n\nXElement feeds = new XElement("feed", \n                        xDoc.Descendants(ns + "entry")\n                            .Select(e=>new XElement("entry",\n                                                new XElement("id", e.Element(ns + "id").Value), \n                                                new XElement("author",e.Element(ns + "author").Element(ns + "name").Value),\n                                                new XElement("created_time",e.Element(ns + "published").Value)\n                                        )\n                            )\n                );\n\nstring xmlstr = feeds.ToString();	0
3902155	3902144	Partial Matches in a String[]	int count = find.Count(f => list.Any(s => s.Contains(f)));	0
25760904	25760855	C# Copy one record from one dictionary to another	foreach (int key in firstDict.Keys) \n{\n    if (!secondDict.ContainsKey(key))\n      {\n        secondDict.Add(key, firstDict[key]);\n        break;\n      }\n}	0
29120383	29118815	how to retrieve information from EntityCollection using linq queries?	var q =retrieve.Entities.Where(x=>x.Attributes.Keys== "new_attribute1" && x.Attributes.Values = "avik").Select(x=>x.Attributes.Values)	0
673689	673514	Age in years with decimal precision given a datetime	// birth date\nDateTime birthDate = new DateTime(1968, 07, 14);\n\n// get current date (don't call DateTime.Today repeatedly, as it changes)\nDateTime today = DateTime.Today;\n// get the last birthday\nint years = today.Year - birthDate.Year;\nDateTime last = birthDate.AddYears(years);\nif (last > today) {\nlast = last.AddYears(-1);\nyears--;\n}\n// get the next birthday\nDateTime next = last.AddYears(1);\n// calculate the number of days between them\ndouble yearDays = (next - last).Days;\n// calcluate the number of days since last birthday\ndouble days = (today - last).Days;\n// calculate exaxt age\ndouble exactAge = (double)years + (days / yearDays);	0
14802708	14802681	How to split a string two times with different separators using LINQ?	string toParse = "1\t2\r\n3\t4";\n\nstring[][] parsed = toParse\n    .Split(new string[] {"\r\n"}, StringSplitOptions.None)\n    .Select(s => s.Split('\t'))\n    .ToArray();	0
637025	359612	How to change RGB color to HSV?	System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);\nfloat hue = color.GetHue();\nfloat saturation = color.GetSaturation();\nfloat lightness = color.GetBrightness();	0
8752695	8752682	How to retrieve the latest tweet of a particular user in windows mobile 7.1?	var message = (from tweet in xmlTweets.Descendants("status")\n                      select tweet.Element("text").Value).FirstOrDefault();\n\nif(!String.IsNullOrEmpty(message))\n   textBlock1.Text = message.ToString();	0
30232805	30231043	Importing C++ custom library functions into C#	std::vector<MyClass>	0
8050959	8049796	Data flow component with number of output columns depending on input parameter. SSIS custom data flow component	ComponentMetaData.OutputCollection[0].OutputColumnCollection.RemoveAll();\nstring[] fields = this.ComponentMetaData.CustomPropertyCollection["Fields"].Value.ToString().Split(new Char[] { ',' });\nforeach (string _field in fields)\n{\n     IDTSOutputColumn100 _outputCol = ComponentMetaData.OutputCollection[0].OutputColumnCollection.New();\n     _outputCol.Name = _field;\n     _outputCol.SetDataTypeProperties(DataType.DT_STR, 20, 0, 0, 1252);\n}\n\nbase.OnOutputPathAttached(outputID);	0
33605731	33453509	Changing a Controls Visible Proprety doesn't redraw the Control	htmlLabel2.Invalidate();	0
23910859	23905567	How to use the GridView AutoGenerateDeletebutton	protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)\n{\n    int Part_Numbber= Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);       \n    SqlCommand cmd = new SqlCommand("DELETE FROM XML WHERE Part_Numbber=" + Part_Numbber+ "", con);\n    con.Open();\n    int temp = cmd.ExecuteNonQuery();\n    if (temp == 1)\n    {\n        lblMessage.Text = "Record deleted successfully";\n    }\n    con.Close();\n    FillGrid();\n}	0
18653573	18653519	Calling both a base constructor and a parameterless constructor?	public NotificationCollection() : this(Enumerable.Empty<Notification>())\n{\n}\n\npublic NotificationCollection(IEnumerable<Notification> items)\n    : base(items)\n{\n    this.CollectionChanged += NotificationCollection_CollectionChanged;\n    this.PropertyChanged += NotificationCollection_PropertyChanged;\n}	0
23379991	23379434	How can I copy nodes from one xml file into another?	var prev = XDocument.Load(filename1);\nvar curr = XDocument.Load(filename2);\nprev.Root.Add(curr.Root.Elements());	0
634352	634340	Get current MethodBase through reflection	System.Reflection.MethodBase.GetCurrentMethod()	0
33674598	33674177	How to show messagebox in c# when HttpWebResponse unable to connect to the server/internet	//Include everything that could possibly throw an exception in the try brackets\ntry\n{\n   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);\n   HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n   Stream resStream = response.GetResponseStream();\n}\ncatch (Exception e) // Here we are catching your bug-the unhandled exception\n{\n  MessageBox.Show("You do not have an internet connection");\n}	0
25880093	25875423	Map control: Remove or hide default map layer	for (var i = Map.Children.Count - 1; i >= 0; i--)\n{\n    MapTileLayer tileLayer = Map.Children[i] as MapTileLayer;\n    if (tileLayer != null)\n    {\n        Map.Children.RemoveAt(i);\n    }\n}	0
7395462	7395445	How to execute stored procedure multiple times in C#	SqlConnection conn = new SqlConnection(connString);\nconn.Open();\nSqlCommand cmd = new SqlCommand("insertINOUT", conn);\ncmd.CommandType = CommandType.StoredProcedure;\n\nfor (int j = 0; j < weekDays.Length; j++)\n{\n    **cmd.Parameters.Clear();**\n    cmd.Parameters.Add(new SqlParameter("@UserName", user));\n    cmd.Parameters.Add(new SqlParameter("@In", in));\n    cmd.Parameters.Add(new SqlParameter("@Out", out));\n    cmd.ExecuteReader();\n}\nconn.Close();	0
22590244	22590136	Adding image to a button in WPF C#, image not appearing	Button btn= new Button\n{\n    Width = 30,\n    Height = 30,\n    Content = new Image\n    {\n        Source = new BitmapImage(@"C:\Users\Desktop\Images\download.jpg"))\n    }\n};	0
14978644	14978379	How to convert time to percentage? (Description inside)	//Example initial time to 1 houre == 100%\n    TimeSpan InitialTime = new TimeSpan(1, 0, 0);\n\n    private double getPercentOnTime(TimeSpan currentTime,TimeSpan timeToRemove)\n    {\n\n        //Convert all to minutes\n        double currentTime_minute = currentTime.TotalMinutes;\n        double timeToRemove_minute = timeToRemove.TotalMinutes;\n        double InitialTime_minute = InitialTime.TotalMinutes;\n\n        //Calcul the additional time to remove from InitialTime\n        double totaltimeToRemove = currentTime_minute + timeToRemove_minute;\n\n        //calcul the new percent\n        double percent = (InitialTime_minute / 100.0) * totaltimeToRemove;\n\n        return percent;\n    }	0
2201139	2188480	Sql custom function with Chili's opf3	var functionQuery = String.Format("SELECT sysdba.GetNextAccountExternalId('{0}')", account.Type);\n\nvar functionResult = (string)new SqlRawStorageAccess(Context.Storage as SqlStorageBase).\n                                CreateCommand(new SqlQuery(functionQuery)).ExecuteScalar();	0
10928558	10928273	How to iterate through Dictionary<MyEnum, List<int>> and each time return part of values of each list?	enum ItemType { Type1 = 1, Type2 = 2, Type3 = 3 };\n\nDictionary<ItemType, List<int>> items = new Dictionary<ItemType, List<int>>();\nitems[ItemType.Type1] = new List<int> { 1, 2, 3, 4, 5 };\nitems[ItemType.Type2] = new List<int> { 11, 12, 13, 15 };\nitems[ItemType.Type3] = new List<int> { 21, 22, 23, 24, 25, 26 };\n\n// Define upper boundary of iteration\nint max = items.Values.Select(v => v.Count).Max();\n\nint i = 0, n = 2;\nwhile (i + n <= max)\n{\n    // Skip and Take - to select only next portion of elements, SelectMany - to merge resulting lists of portions\n    List<int> res = items.Values.Select(v => v.Skip(i).Take(n)).SelectMany(v => v).ToList();\n    i += n;\n\n    // Further processing of res\n}	0
23124732	23124627	First or Last element in a List<> in a foreach loop	int counter = 0 ;\n         foreach (string s in List)\n         {\n               if (counter == 0) // this is the first element\n                {\n                  string newString += s;\n                }\n               else if(counter == List.Count() - 1) // last item\n                {\n                newString += s + ", ";\n                }else{\n                 // in between\n               }\n                counter++;\n       }	0
15985000	15888883	Is there a simple way to get query string parameters from a URI in Windows Phone?	public static Dictionary<string, string> ParseQueryString( string uri ) {\n\n    string substring = uri.Substring( ( ( uri.LastIndexOf('?') == -1 ) ? 0 : uri.LastIndexOf('?') + 1 ) );\n\n    string[] pairs = substring.Split( '&' );\n\n    Dictionary<string,string> output = new Dictionary<string,string>();\n\n    foreach( string piece in pairs ){\n        string[] pair = piece.Split( '=' );\n        output.Add( pair[0], pair[1] );\n    }\n\n    return output;\n\n}	0
31705431	31705279	Convert Single column C# DataTable to JSON using JSON.NET	var json = JsonConvert.SerializeObject(\n              new { EFFDATE = dt.AsEnumerable().Select(r => r[0]) }\n           );	0
9912980	9912682	XML Serialization with Different Subclasses	serializer = new XmlSerializer(typeof(T), extraTypes);	0
33383136	33383088	How to deserialize JSON using JSON.Net	public class MainCategory\n    {\n        public string Id { get; set; }\n        public string MainCategoryName { get; set; }\n        public string LastPublished { get; set; }\n        public List<SubCategory> SubCategories { get; set; }\n    }\n\npublic class SubCategory\n    {\n        public string Id { get; set; }\n        public string SubCategoryName { get; set; }\n        public string LastPublished { get; set; }\n    }	0
16750456	16750205	New version of jQuery loads another page instead of replacing div	PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax	0
9087543	9087301	Insert item in a comboBox in WinForms	If DropDownStyle is set to DropDownList, the return value is an empty string ("").	0
24129859	24129858	NMock3 How to Mock a method with out parameter?	_mockObject\n.Expects.One.Method(m =>\n        m.DeletedVideos(-1, -1, out ignoredValue)) //values are ignored\n       .With(0, 20, Is.Out) //set the values manually\n       .Will(new SetIndexedParameterAction(2, 100) , Return.Value(deletedVideos));	0
13327384	13325996	Grouping Dictionary by value using linq	public string FrecquincyWordBuilder()\n  {\n\n      string fromatedWords = string.Empty;\n      this.myWords.SortByFrequency();\n      Dictionary<string, int> wordsAndFec = this.myWords.wordsAsDictionary();\n      return GroupWordsByFercs(wordsAndFec);\n\n\n  }\n\n  private static string GroupWordsByFercs(Dictionary<string, int> wordsAndFec)\n  {\n      String formatedWords = string.Empty;\n      var groups =\n          from w in wordsAndFec\n          group w by w.Value;\n      foreach (var group in groups)\n      {\n          formatedWords += ("\n Words ocurring " + group.Key + " times:\n");\n          foreach (var w in group)\n          {\n              formatedWords += (w.Key + " ");\n          }\n      }\n      return formatedWords;\n  }	0
7403427	6595259	Fans-only content in facebook with asp.net C# sdk	if (Request.Params["signed_request"] != null)\n{\n    string payload = Request.Params["signed_request"].Split('.')[1];\n    var encoding = new UTF8Encoding();\n    var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');\n    var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));\n    var json = encoding.GetString(base64JsonArray);\n    var o = JObject.Parse(json);\n    var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");\n    var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");\n    var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");\n}	0
5085292	5085067	C# Loading assemblies from internal resources	AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, AssemblyResolveEventArgs args) {\n    ...\n};	0
12296786	12295609	Render image without 1-1 effect	[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]	0
8969140	8968504	Invert colors on WinForms	nRow[x * pixelSize] = (byte)(255 - oRow[x * pixelSize + 0]); //B\n        nRow[x * pixelSize + 1] = (byte)(255 - oRow[x * pixelSize + 1]); //G\n        nRow[x * pixelSize + 2] = (byte)(255 - oRow[x * pixelSize + 2]); //R	0
17599097	17582015	c# foreach image in folder	foreach (MagickImage image in images)\n{\n  using (Bitmap bmp = image.ToBitmap())\n  {\n    tessnet2.Tesseract tessocr = new tessnet2.Tesseract();\n    // etc...\n  }\n}	0
9409130	9409016	How can we handle the onselectedindexchanged event of a dropdownlist in a gridview/datalist?	protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)\n{\n   var ddlList= (DropDownList)sender;\n   var row = (GridViewRow)ddlList.NamingContainer;\n   //get the Id of the row\n   var Id = Convert.ToInt32(((Label)row.FindControl("IdColumn")).Text);\n}	0
31781382	31781279	Total Sum with multiple where clause LINQ	dbContext.transactions.Where(trx => trx.response_code.Equals("100"))\n    .Where(trx=>trx.merchant_id.Equals(mid))\n    .ToList() // Or AsEnumerable(), or Select()...\n    .Sum(i => float.Parse(i.amount));	0
10196653	10196445	Switch views in same Window WPF without creating new instances of the pages	public class MainWindow : Window\n{\n    // ...\n    public void SetPage(UserControl page)\n    {\n         this.Content = page;\n    }\n}\n\n// ...\n\npublic static class Pages\n{\n    private FirstUserControl _first;\n    private SecondUserControl _second;\n    private ThirdUserControl _third;\n    private MainWindow _window = Application.Current.MainWindow;\n\n    public UserControl First\n    {\n        get \n        { \n            if (_first == null) \n                _first =  new FirstUserControl();\n            return _first;\n        }\n    }\n    // ...\n}\n\n// Somewhere in B (after A -> B)\n\n    MainWindow.SetPage(Pages.First);	0
27594875	27594773	Linq C#- Get previous element in a collection	menu = _applicationContext.RightMenu.FirstOrDefault(x => x.PageOrder == (currentPageNo-1));	0
8768511	8768489	How can I combine multiple statement in lambda expression	Action<string> custom = (name) =>\n        {\n            lstCutomers.Add(new Customer(name, coutries[cnt]));\n            name = name + " Object Created";\n        };	0
4879466	4879159	Customized column in Linq	var query = from b in books\n            select new\n            {\n                Title = b.Title,\n                StockAvailable = bookexamples.Count(be => \n                        be.BookID == b.BookID && \n                        be.OrderDetailID == null\n                    )\n            };	0
15091581	15091415	lambda expression meaning/modificating	private static Expression<Func<T, bool>> ExpressionLongEquals<T>(string Key, long Value)\n{\n    var param = Expression.Parameter(typeof(T));\n    // create expression for param => param.TEntityNameId == PrimaryKey\n    var lambda = Expression.Lambda<Func<T, bool>>(\n        Expression.Equal(\n            Expression.Property(param, Key),\n            Expression.Constant(Value, typeof(long?)),\n        param);\n    return lambda;\n}	0
14872311	14819394	Any components for working with shared config files?	namespace WindowsFormsApplication1\n{\n    static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static void Main()\n        {\n            using (AppConfig.Change(@"\\myserver\mypath\app.config"))\n            {\n                Application.EnableVisualStyles();\n                Application.SetCompatibleTextRenderingDefault(false);\n                Application.Run(new Form1());\n            }\n        }\n    }\n}	0
3234802	3234341	get distinct rows from datatable using Linq (distinct with mulitiple columns)	Dim query = From q In (From p In dt.AsEnumerable() Select New With {.col1= p("ColumnName1"), .col2 = p("ColumnName2")}) Select q.col1, q.col2 Distinct	0
9949467	9949158	Resizing Custom UITableViewCell in Monotouch	public override float GetHeightForRow(UITableView tableView, NSIndexPath indexPath)\n{\n    return 50f;\n}	0
20837289	20836519	Group Dynamically created objects	private void btnAddTitle_Click(object sender, RoutedEventArgs e)\n{\n\n    CurrentSortItem++;\n    SortItems.Add(CurrentSortItem);\n\n    GroupBox gb = new GroupBox();\n    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };\n\n    ....\n    gb.Content = sp;\n\n    spStandard.Children.Add(gb);\n\n}	0
15387920	15387852	Trouble with custom authorization attribute	[PSAuthorize]\npublic ActionResult Home()\n{\n    return View();\n}	0
17047399	17039905	How to use ADOX to connect to existing Access database	Dim cnn As New ADODB.Connection\nDim cat As New ADOX.Catalog\n\ncnn.Open "Provider='Microsoft.Jet.OLEDB.4.0';" & _\n    "Data Source= 'Northwind.mdb';"\nSet cat.ActiveConnection = cnn\nDebug.Print cat.Tables(0).Type\n\ncnn.Close\nSet cat = Nothing\nSet cnn = Nothing	0
9558668	9558549	Validate decimal value to 2 decimal places with data annotations?	[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Invalid price"]	0
21434213	21402749	How to convert string with property name to Entity framework storage expression?	DBContext.MyStatuses.Select("ModemStatus.Temperature");	0
13024932	13024781	Reading XML using XDocument & Linq	var result = XDocument.Load(yourPath).Descendants("lv1")\n            .Where(x => x.Attribute("value").Value == "a")\n            .Descendants("lv2")\n            .Where(x => x.Attribute("value").Value == "bb")\n            .Descendants("lv3")\n            .Select(x => new\n                {\n                    Name = x.Attribute("name").Value,\n                    Value = x.Attribute("value").Value\n                });	0
18376180	18376012	how to avoid click when I want double click?	private static DispatcherTimer myClickWaitTimer = \n    new DispatcherTimer(\n        new TimeSpan(0, 0, 0, 1), \n        DispatcherPriority.Background, \n        mouseWaitTimer_Tick, \n        Dispatcher.CurrentDispatcher);\n\nprivate void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n{\n    // Stop the timer from ticking.\n    myClickWaitTimer.Stop();\n\n    Trace.WriteLine("Double Click");\n    e.Handled = true;\n}\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    myClickWaitTimer.Start();\n}\n\nprivate static void mouseWaitTimer_Tick(object sender, EventArgs e)\n{\n    myClickWaitTimer.Stop();\n\n    // Handle Single Click Actions\n    Trace.WriteLine("Single Click");\n}	0
30051203	30050165	WMI management scope connect to local instead of remote	ConnectionOptions options = new ConnectionOptions();\noptions.Password = "remoteUserPassword"; // you may want to avoid plain text password and use SecurePassword property instead\noptions.Username = "remote-user"; \nManagementScope scope = new ManagementScope(@"\\remoteMachineHostname\root\cimv2", options);	0
18861032	18860738	Deserialize json utc date from jira api to .net datetime	WebClient wc = new WebClient();\nstring json = wc.DownloadString("https://jira.atlassian.com/rest/api/latest/issue/JRA-9.json");\ndynamic jObj = JObject.Parse(json);\nDateTime dt = (DateTime)jObj.fields.updated;	0
11742457	11742399	Search matched list in dictionary	dict.Where(k =>\n    filter.A.Contains(k.Key.A[0]) //CONTAINS !\n    && k.Key.Start.CompareTo(filter.Start) > 0 \n    && k.Key.Start.CompareTo(filter.End) < 0\n)	0
33017491	33014403	Need to play a sound alert at a certain time in a stopwatch application in C#	Timer Timer15 = new Timer();\n    Timer Timer30 = new Timer();\n    Timer Timer60 = new Timer();\n\n    public void SetupTimers()\n    {            \n        Timer15.Interval = 15 * 60 * 1000;\n        Timer30.Interval = 30 * 60 * 1000;\n        Timer60.Interval = 60 * 60 * 1000;\n\n        Timer15.Tick += Timer_Tick;\n        Timer30.Tick += Timer_Tick;\n        Timer60.Tick += Timer_Tick;\n\n        Timer15.Enabled = true;\n        Timer30.Enabled = true; \n        Timer60.Enabled = true;\n    }\n\n    void Timer_Tick(object sender, EventArgs e)\n    {\n        Timer timer = sender as Timer;\n        // Unsubscribe from the current event. Prevents multuple subscriptions. \n        timer.Tick -= Timer_Tick;   \n        // If 60 minutes then reset all timers. \n        if (timer.Interval == 60 * 60 * 1000)\n        {\n            SetupTimers();\n        } \n\n        //Call sound method here. \n        MakeSound();            \n    }	0
24681278	24681198	Convert delimited string to xml in C# using LINQ	var doc = new XDocument(\n    new XElement("SerialNumbers",\n        (from x in serials select new XElement("Serial", x))\n    )\n);	0
28057621	28057521	Reading a comma delimited CSV that contains currency	//Read the file\nwhile (!fileIn.EndOfStream)\n{\n   String line = fileIn.ReadLine();\n   String[] pieces = line.Split(',');\n   if(pieces.length > 5){\n       String[] newPieces = new String[5];\n       newPieces[0] = pieces[0];\n       newPieces[1] = pieces[1];\n       String currency = "";\n       for(int i = 2; i < pieces.length - 2; i++){\n           if(i == pieces.length -3)\n               currency += pieces[i];\n           else{\n               currency += pieces[i] + ",";\n           }\n       }\n       newPieces[2] = currency;\n       newPieces[3] = pieces[pieces.length-2];\n       newPieces[4] = pieces[pieces.length-1];\n       csvComplete cEve = new csvComplete (newPieces[0], newPieces[1], newPieces[2], newPieces[3], newPieces[4]);// assign to class cEve\n       entries.Add(cEve);\n   }\n   else{\n       csvComplete cEve = new csvComplete (pieces[0], pieces[1], pieces[2], pieces[3], pieces[4]);// assign to class cEve\n       entries.Add(cEve);\n   }\n\n }	0
13056129	12882656	how to calculate conditional sum in devexpress xtrareport	Iif([Result]='P',[TotalMarks],0 )	0
1565717	1456537	WPF Documents: How to create paragraphs of "underlines" on which you can write answers to questionnaires	for (int i = 1; i < pQuestionSpec.NumberOfLines; i++)\n        {\n            Table innerT = new Table();\n            var col1 = new TableColumn();\n\n            col1.Width = new GridLength(1, GridUnitType.Star);\n            innerT.Columns.Add(col1);\n\n            var innerRowGroup = new TableRowGroup();\n            var innerRow = new TableRow();\n\n            var cell2 = new TableCell();\n            cell2.BorderThickness = new Thickness(0, 0, 0, 1);\n            cell2.BorderBrush = Brushes.Black;\n            cell2.Blocks.Add(new Paragraph());\n\n            innerRow.Cells.Add(cell2);\n            innerRowGroup.Rows.Add(innerRow);\n\n            innerT.RowGroups.Add(innerRowGroup);\n\n            cell.Blocks.Add(innerT);\n        }	0
29291010	29290338	C# - how to select * from mysql to dataGridView1	if (!this.IsPostBack)\n    {\n            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;\n            using (MySqlConnection con = new MySqlConnection(constr))\n            {\n                using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers"))\n                {\n                    using (MySqlDataAdapter sda = new MySqlDataAdapter())\n                    {\n                        cmd.Connection = con;\n                        sda.SelectCommand = cmd;\n                        using (DataTable dt = new DataTable())\n                        {\n                            sda.Fill(dt);\n                            GridView1.DataSource = dt;\n                            GridView1.DataBind();\n                        }\n                    }\n                }\n            }\n    }	0
2805757	2805477	Parse XML and populate in List Box	XDocument xmldoc = XDocument.Load(xmlStream);\nvar items = (from i in xmldoc.Descendants("item")\n             select new { Item = i.Element("SEL").Value, Value = i.Element("VALUE").Value }).ToList();\n\nlistBox1.DataSource = items;\nlistBox1.DisplayMember = "Item";\nlistBox1.ValueMember = "Value";	0
9744917	9100118	Using RegEx to split and then truncate lines in a list	private void MultiPasteArrayGenerator()\n    {\n        string[] lines = null;\n\n        if (Clipboard.GetText().Contains('='))\n        {\n\n        }\n        else if (Clipboard.GetText().Contains(':'))             //Strips headers from skip tools run through Agent Toolbox\n        {                \n            string filterLabels = @"(?:\w+\s?)*\:(?:\s?)*";           //Set up RegEx statement\n\n            List<string> replacedLine = new List<string>();\n            List<string> brokenLines = new List<string>();\n\n            lines = Regex.Split(Clipboard.GetText(), filterLabels);  //Divide text on clipboard into one string per line\n            foreach (string line in lines)\n            {\n                brokenLines.Add(line);\n            }\n            brokenLines.Remove("");\n            string[] broken = brokenLines.ToArray();\n            MultiPaste(broken);\n        }\n        else\n        {\n            lines = Regex.Split(Clipboard.GetText(), "\r\n");\n            MultiPaste(lines);\n        }	0
1351432	1351355	Calling C# from IronRuby	require 'C:\Documents and Settings\myUser\My Documents\Visual Studio 2008\Projects\Project1\helloWorldLib\bin\Debug\helloWorldLib.dll'\ngreeter = HelloWorldLib::Greeter.new\ngreeter.say_hello_world "Michael"	0
17291254	17291150	Not able to put a break point for a function being run in Background C#, Visual Studio 2012	public static void main()\n{\n\n    SettingTestThread1();\n    testThread1.RunWorkerAsync();\n\n    System.Threading.Thread.Sleep(2000);\n}	0
17554474	17554383	json schema validation. How can I accept an array or null?	"myProperty": { "type": [ "array", "null" ], "required":false }	0
12249500	12248881	How to get Rootnode Element attribute value in a xml File	XNamespace xn = "kd.gnp.com/Model/1.0";\nXDocument doc= XDocument.Load(path);\n            var q = (from c in doc.Elements(xn +"Datatable")	0
32797840	32774403	Generic base class where T is also a generic base class	public abstract class SomeThingBase<T> where T : class{ }\npublic abstract class ManagerBase<T, U> \n    where T : SomeThingBase<U>\n    where U : class\n{ }	0
4388783	4388718	Rewrite this array manipulation using a lambda function?	sOutputFields = sOutputFields.Select(el => clsSQLInterface.escapeIncoming(el)).ToArray();	0
11647400	11646665	Open PDF in web page of ASP.NET	Response.Clear();\nstring filePath = "myfile.pdf";\nResponse.contentType = "application/pdf";\nResponse.WriteFile(filePath);\nResponse.End();	0
2193761	2193674	How to map null values with AutoMapper for an specific mapping?	Mapper.Initialize( Conf =>\n  {\n    Conf.ForSourceType<MyGreatViewModel>().AllowNullDestinationValues = true;\n  } );	0
26577566	26577456	Passing Button name between pages windows phone 8	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    if (NavigationContext.QueryString.ContainsKey("key"))\n    {\n         string val = NavigationContext.QueryString["key"];\n    }\n}	0
2711074	2711063	How to include parenthesis for AS-IS output in format string	string s = String.Format("{0} {{}}", "Hello");	0
22145477	22143202	Get the multiple selected Row in data-grid in WPF?	//CustomerDTO is the DTO class which has all the column names of Customer Table.\n//dgUsers is the data grid.\nList<CustomerDTO> customerList ;\nfor (int i = 0; i < dgUsers.SelectedItems.Count; i++)\n{\ncustomerList.Add((CustomerDTO)dgUsers.SelectedItems[i]);\n}	0
13159750	13157614	Getting the logged in user when a program is executed as Administrator	Option Explicit\n\nDim objReg, objWMI, colSessions\n\nSet objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")\nSet objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") \n\nSet colSessions = objWMI.ExecQuery("Select * from Win32_LogonSession Where LogonType = 2 Or LogonType = 10") \nIf colSessions.Count <> 0 Then \n    'Some users are logged into Windows.\n    'For example set property \n    'Session.Property("SOMEONELOGGED") = "1"\nEnd If	0
8155726	8155613	Multiplying columns in a datatable	dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]);	0
10139918	10139534	Pull out records from 3 tables in Linq2Sql	return (from c in Context.Companies\nwhere c.BuySells.Any( b=>b.CategoryId == categoryId)\n      || c.Products.Any( p=>p.CategoryId == categoryId)\nselect new\n{\n  c.CompanyId,\n  c.CompanyName,\n  c.Country.Flag,\n  c.Profile,\n  c.IsUsingSMSNotifications,\n  c.IsVerified,\n  c.MembershipType,\n  c.RegistrationDate, c.ShortProfile,\n}).Skip(skip).Take(take).ToList();	0
24745727	24745588	How can I insert in Fluent NHibernate using SQL Server 2012 with sequences?	this.Id(x => x.Id)\n.GeneratedBy.SeqHiLo("mysequence", "1000")\n.Default("next value for mysequence");	0
22320025	22319945	How to read xml node title and it's value?	using System;\nusing System.Xml;\nusing System.IO;\nusing System.Text;\n\npublic class Test\n{\n    public static void Main()\n    {\n        StringBuilder sb = new StringBuilder();\n        string ExceptionDetails="<names><FirstName>John</FirstName><SecondName>White</SecondName></names>";\n        using (XmlReader reader = XmlReader.Create(new StringReader(ExceptionDetails)))\n        {\n            string tagName = string.Empty;\n            while (reader.Read())\n            {\n               if (reader.NodeType == XmlNodeType.Element)\n                   tagName = reader.Name;\n               else if (reader.NodeType == XmlNodeType.Text)\n               {               \n                    sb.Append(tagName);\n                    sb.Append(":"); //Read tag title\n                    sb.Append(reader.Value); sb.Append("<br/>");                      \n               }\n            }\n        }\n        Console.WriteLine(sb.ToString());\n    }\n}	0
10174635	10174584	Working with string and replace	str = str.Substring(str.LastIndexOf('.')+1);	0
24518652	24516440	Deserialize Mixpanel Data API Event JSON C#	public class Data\n{\n    [JsonProperty("series")]\n    public IEnumerable<DateTime> Series { get; set; }\n\n    [JsonProperty("values")]\n    public IDictionary<string, IDictionary<DateTime, int>> Values { get; set; }\n}	0
23813101	23812544	Automatic width of textbox inside a FlowLayoutPanel	public Form1()\n    {\n        InitializeComponent();\n        this.Load +=new EventHandler(Form1_Load);\n    }\n\n    public int MyFlowPanelOriginalSize { get; set; }\n    public int MyFlowPanelNewSize { get; set; }\n    public int DifferenceInSizeOfPanel { get; set; }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        MyFlowPanelOriginalSize = MyFlowPanel.Width;\n        MyFlowPanel.Resize += new EventHandler(MyFlowPanel_Resize);\n        DifferenceInSizeOfPanel = 0;\n    }\n\n\n\n    void MyFlowPanel_Resize(object sender, EventArgs e)\n    {\n        MyFlowPanelNewSize = MyFlowPanel.Width;\n        DifferenceInSizeOfPanel = MyFlowPanelNewSize - MyFlowPanelOriginalSize;\n        var TextBoxDifference = MyTextBox.Width + DifferenceInSizeOfPanel;\n        MyTextBox.Width = TextBoxDifference;\n        MyFlowPanelOriginalSize = MyFlowPanel.Width;\n    }	0
2646376	2646185	How to change the Array Element names in XmlSerialization?	XmlSerializer xs = new XmlSerializer(typeof(Human[]), XmlRootAttribute("MyFavoriteArrayRootName"));	0
11263760	11263251	Programatically get a diff between two versions of a file in TFS	var diff = Encoding.UTF8.GetString(stream.ToArray());	0
29939213	29936898	How to C# linq GroupBy multiple arrays with array values	IDictionary<float, MiniChannel[]> matchingTimes = channel\n    .SelectMany(c => c.times.Select((t, i) => new KeyValuePair<float, MiniChannel>(t, new MiniChannel {axis = c.axis, value = c.values[i]})))\n    .GroupBy(t => t.Key)\n    .ToDictionary(t => t.Key, t => t.Select(c => c.Value).ToArray());	0
18866791	18866750	How to add an image as attachement with SmtpClient?	msg.Attachments.Add(new Attachment(imagePath));	0
30776530	30761732	Apply style on Content Control in a Word Document using OpenXML	// clone element\nvar clonedElement = CloneElementAndSetContentInPlaceholders(datacontext);\n\n// search the first created paragraph on my clonedElement\nParagraph p = clonedElement.Descendants<Paragraph>().FirstOrDefault();\nif (p != null)\n    p.PrependChild<ParagraphProperties>(new ParagraphProperties());\n// get the paragraph properties\nParagraphProperties pPr = p.Elements<ParagraphProperties>().First();\n// apply style\npPr.ParagraphStyleId = new ParagraphStyleId { Val = "FormationTitre2" };\n// set content of content control\nSetContentOfContentControl(clonedElement, item.Value);	0
11017950	11016405	How do I run WPF application from different directory?	var realWD = Environment.CurrentDirectory;\nEnvironment.CurrentDirectory =\n        System.IO.Path.GetDirectory(\n            System.Reflection.Assembly.GetEntryAssembly().Location);\nInitializeComponent();\nEnvironment.CurrentDirectory = realWD;	0
26439301	26439226	concat string var in razor var name	public T GetValue<T>(string propertyName)	0
2535285	2535251	C#, finding the largest prime factor of a number	static private long maxfactor (long n)\n{\n    long k = 2;\n    while (k * k <= n)\n    {\n        if (n % k == 0)\n        {\n            n /= k;\n        }\n        else\n        {\n            ++k;\n        }\n    }\n\n    return n;\n}	0
12158932	12158899	How to loop collections in LINQ and pass on data	foreach(var product in products)\n    product.VariantProducts = variants.Where(x => x.VariantParentID == p.ProductID)\n                                      .ToList();	0
7171572	7171381	How to change the DataTable Column Value without looping?	static void Main(string[] args)\n{\n    DataTable table = new DataTable();\n\n    table.Columns.Add("col1");\n    table.Columns.Add("col2");\n\n    table.Rows.Add(new object[] { "1", "1" });\n    table.Rows.Add(new object[] { "1", "1" });\n    table.Rows.Add(new object[] { "1", "1" });\n    table.Rows.Add(new object[] { "1", "1" });\n\n    foreach (DataRow row in table.Rows)\n        Console.WriteLine(row["col2"].ToString());\n\n    Console.WriteLine("***************************************");\n\n    DataColumn dc = new DataColumn("col2");\n    dc.DataType = typeof(int);\n    dc.DefaultValue = 0;\n\n    table.Columns.Remove("col2");\n    table.Columns.Add(dc);\n\n    foreach (DataRow row in table.Rows)\n        Console.WriteLine(row["col2"].ToString());\n\n\n    Console.ReadKey();\n}	0
26699880	26699793	Parsing HTML page to extract links	href=\"[^\"]+\"	0
23036614	23035964	Reading from a textfile to blacklist urls	string[] url = File.ReadAllText("blacklist.txt")\n        .Split();\nArray.Exists(url, x => x.Contains(value));	0
22836404	22836202	How to bring up printers menu in c# with a button?	var dlg = new PrintDialog();\ndlg.ShowDialog();	0
28207207	28207146	Swap two numbers without using another variable	int a=4 ;\nint b=3 ;\n\na=a+b ;  //  a=7\nb=a-b ;  //  b=7-3=4\na=a-b ;  //  c=7-4=3	0
27159131	27158111	MDIchild windows, not stacking more than the center of the screen. A known limit?	private void Form2_Load(object sender, EventArgs e)\n    {\n        int t = 1, l = 1;\n        int d = this.MdiParent.MdiChildren.GetUpperBound(0) - 1;\n        if (d >= 0)\n        {\n            Form f = this.MdiParent.MdiChildren[d];\n            t = f.Top + 20;\n            l = f.Left + 20;\n        }\n\n        this.Top = t;\n        this.Left = l;\n    }	0
8415663	8404367	How to read a string with UTF8 coding using linq to entities	Encoding.UTF8.GetString(Encoding.Default.GetBytes(yourstring))	0
30791768	30791651	Can I receive a JavaScript Object on an API WITHOUT a Corresponding C# Object?	public void controllerMethod(dynamic myObject)\n    {\n\n    }	0
6940154	6594403	How to write inside an xml file using xmldocument	string targetFileName = "";\nstring[] myWindows = new string[];\n\nusing (XmlTextWriter oXmlTextWriter = new XmlTextWriter(targetFileName , Encoding.UTF8))\n{\n  oXmlTextWriter.Formatting = Formatting.Indented;\n  oXmlTextWriter.WriteStartDocument();\n  oXmlTextWriter.WriteStartElement("tabpage");\n  oXmlTextWriter.WriteStartElement("form");\n\n  foreach( string window in myWindows)\n  {\n     oXmlTextWriter.WriteStartElement("Window");\n\n     oXmlTextWriter.WriteElementString("name", nameValue);\n     oXmlTextWriter.WriteElementString("age", nameValue);\n     oXmlTextWriter.WriteElementString("gender", nameValue);\n\n     oXmlTextWriter.WriteEndElement(); // closing Window tag\n  }\n  oXmlTextWriter.WriteEndElement(); // closing form tag\n  oXmlTextWriter.WriteEndElement(); // closing tabpage tag\n\n  // closing the XML file\n  oXmlTextWriter.WriteEndDocument();\n  oXmlTextWriter.Flush();\n  oXmlTextWriter.Close();\n}	0
9301290	9301268	How can I convert comma separated string into a List<int>	List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();	0
7709581	7708846	How to Get CheckIn-CheckOut time Difference from Punch Machine Attendance Log with Single Row using SQL Query?	declare @t table (EnrollNo int, [Date] datetime, Time varchar(5))\ninsert @t select 1, '8-10-2011 12:00:32', '13:12' \nunion all select 1, '8-10-2011 12:00:32', '23:14' \nunion all select 2, '8-10-2011 12:00:32', '11:12' \nunion all select 2, '8-10-2011 12:00:32', '20:14' \nunion all select 3, '8-10-2011 12:00:35', '12:12' \nunion all select 3, '8-10-2011 12:00:32', '23:14' \nunion all select 4, '8-10-2011 12:00:32', '17:12' \nunion all select 4, '8-10-2011 12:00:32', '23:14'\n\nselect \n  EnrollNo, \n  CAST(CONVERT(varchar, Date, 101) AS DateTime), \n  right('0' + cast(datediff(hour, cast(min(Time) as datetime), \n  cast(max(Time) as datetime)) as varchar(2)),2) + ':' + \n    right('0' + cast(datediff(minute, cast(min(Time) as datetime), \n    cast(max(Time) as datetime)) % 60 as varchar(2)),2),\n  min(Time),\n  max(Time)\nfrom @t group by EnrollNo,CAST(CONVERT(varchar, Date, 101) AS DateTime)	0
22409168	21343938	Delete all pictures of an ID3 tag with taglib-sharp	string title;\n        using (var taglibFile = TagLib.File.Create(file))\n        {\n            title = taglibFile.Tag.Title;\n            taglibFile.RemoveTags(TagTypes.AllTags);\n            taglibFile.Save();\n        }\n\n        using (var tagLibFile = TagLib.File.Create(file))\n        {\n            tagLibFile.Tag.Title = title;\n            tagLibFile.Save();\n        }	0
11514577	11513400	Cast function expression tree from object	public void ProcessGlobal()\n    {\n        var globalType = _global.GetType(); // globalType = Expression<Func<TClass, TProperty>>\n        var functionType = globalType.GetGenericArguments()[0]; // functionType = Func<TClass, TProperty>\n        var functionGenericArguments = functionType.GetGenericArguments(); // v = [TClass, TProperty]\n        var method = this.GetType().GetMethod("AssignToGlobal").MakeGenericMethod(functionGenericArguments); //functionGenericArguments = AssignToGlobal<TClass, TProperty>\n        method.Invoke(this, new[] { this._global }); // Call AssignToGlobal<TClass, TProperty>)(this._global);\n    }	0
33018497	33018299	How to prevent users from typing special characters in textbox	if (!TXT_NewPassword.Text.All(allowedchar.Contains))\n{\n    // Not allowed char detected\n}	0
32026638	32026591	Set an 'int' in one event and use it in another event	private int _yes;\nprivate void BtnYes_Click(object sender, EventArgs e)\n{\n    _yes = 1;\n    int no = 0;\n    timer1.Start();\n}\n\nprivate void timer1_Tick(object sender, EventArgs e) \n {\n    if (_yes == 1) {\n        //EVENT\n }\n}	0
9504899	9504814	Execute UserControl readonly ICommand from ViewModel	public partial class PlayerView : IHaveAPlayCommand\n{\npublic PlayerView()\n{\n      this.DataContext = new ViewModel(this);\n}\n}\n\n\npublic class ViewModel\n{\n      IHaveAPlayCommand view;\n      public ViewModel(IHaveAPlayCommand view)\n      {\n           this.view = view\n      }\n\n}	0
16750460	16750332	How to sum decimal value from a column in a table in html file for C#	// Site Collection Storage Used (GB)\n    sum = (int)doc.DocumentNode.SelectSingleNode("//table")\n        // The sum will be of the row elements\n        .Elements("tr")\n        // Skip this many rows from the top\n        .Skip(1)\n        // .ElementAt(2) = third column\n        // .Last() = last column\n        .Sum(tr => decimal.Parse(tr.Elements("td").ElementAt(3).InnerText)); \n    Console.WriteLine("Site Collection Storage Used (GB): " + sum);	0
14398460	14389999	Getting Ninject to work	public class SiteSettings {\n    public SiteSettings(IUnitOfWorkFactory uowFactory) { .... }\n\n    ....\n}\n\n\npublic class INeedToAccessSiteSettings\n{\n    public INeedToAccessSiteSettings(SiteSettings siteSettings) { .... }\n}\n\nkenrel.Bind<SiteSettings>().ToSelf().InSingletonScope();	0
1310180	1310162	Setting value to a field in the derived class	abstract class A\n{\n    protected A(string name)\n    {\n        Name = name;\n    }\n\n    public abstract string Name\n    {\n        get;\n        protected set;\n    }\n}\n\nclass B: A\n{\n    public B(string name) : base(name)\n    {\n    }\n\n    private string m_name;\n\n    public override string Name\n    {\n        get { return "B Name: " + m_name; }\n        protected set\n        {\n           m_name = value;\n        }\n    }\n}	0
6766924	6766787	Cloning WPF controls and object hierarchies	protected Circle(Circle t)\n{\n    CopyFrom(t);\n}\n\npublic override object Clone()\n{\n    return new Circle(this);\n}\n\nprotected void CopyFrom(Circle t)\n{\n    // Ensure we have something to copy which is also not a self-reference\n    if (t == null || object.ReferenceEquals(t, this))\n        return;\n\n    // Base\n    base.CopyFrom((Shape)t);\n\n    // Derived\n    Diameter = t.Diameter;\n}	0
19591231	19591194	Convert IEnumerable<IGrouping<,>> to array	var remaining = groups.Skip(1).SelectMany(g=>g).ToArray();	0
18776809	18776644	How to generate a bell curve. Gaussian function in programming	import random\n\nsample = random.gauss(mu, sigma)\n# where mu is the center of the bell curve, and sigma is proportional to its "width"	0
18079543	18079478	how to connect exist table in EF	[Table("webpages_Membership", Schema = "my_project")]	0
27848656	27848576	How to get a Roslyn FieldSymbol from a FieldDeclarationSyntax node?	foreach (var variable in node.Declaration.Variables)\n{\n    var fieldSymbol = model.GetDeclaredSymbol(variable);\n    // Do stuff with the symbol here\n}	0
22394416	22394288	Regex 2 groups of characters with question mark quantifier, one of them has to be used	(?=.)([ABEFGIJKLMNOPQRTUVabefgijklmnopqrtuv23456789\\*]?[CDHSWXYZcdhswxyz]?)	0
26862433	26861078	Iterating through string resources in another assembly	public void IterateResourcesInAssembly(string filename)\n        {\n            var assembly = Assembly.LoadFile(filename);\n            string[] resourceNames = assembly.GetManifestResourceNames();\n\n            foreach (var resourceName in resourceNames)\n            {\n                string baseName = Path.GetFileNameWithoutExtension(resourceName);\n                ResourceManager resourceManager = new ResourceManager(baseName, assembly);\n\n                var resourceSet = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);\n                // Exception is thrown!\n            }\n        }	0
519331	519324	Trouble casting results of Select() to a List<T>	List<int> selections = list.Select(i => i*i).ToList();	0
7952645	7952331	C# : edit file access control	using (FileStream fs = \n       File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))\n{\n    // use fs\n}	0
6509893	6509851	How to determine if windows restarted?	DateTime computerLastStarted = Now - Uptime;\n   if (computerLastStarted > storedComputerLastStarted + or - tollerance) {\n      storedComputerLastStarted = computerLastStarted;\n      StartProgram();\n    }	0
10915662	10915611	How to download and compile a source from an apache project if I have the link (svn)?	svn checkout	0
913175	913118	DependencyPropert not set from XAML with DynamicResource as parameter	public static readonly DependencyProperty BackProp =\n    DependencyProperty.Register(\n        "BackTest",\n        typeof(ImageSource),\n        typeof(StateImageButton),\n        new FrameworkPropertyMetadata(OnBackChanged));\n\nprivate static void OnBackChanged(\n    DependencyObject d, \n    DependencyPropertyChangedEventArgs e)\n{\n    var sender = (StateImageButton)d; // Put a breakpoint here\n}	0
14289874	12186579	C# Selenium WebDriver FireFox Profile - using proxy with Authentication	ProfilesIni allProfiles = new ProfilesIni(); \nFirefoxProfile profile = allProfiles.getProfile("WebDriver"); \nprofile.setPreferences("foo.bar",23);\nWebDriver driver = new FirefoxDriver(profile);	0
27829465	27826992	How to index image list by name instead of position?	imageList1.Images[comboBox1.SelectedItem.ToString()];	0
8579188	8576693	Descendants within descendants in LINQ to XML	var xGood = from docVersion in doc.Root.Descendants( "document_version" )\n              where docVersion.Element("docVersionID").Value == vId\n              from d in docVersion.Elements( "stages" )\n                                  .Elements( "stage" )\n                                  .Elements( "approver_list" )\n                                  .Elements( "approver" )\n                                  .Elements( "user" )\n              select d;	0
10007962	10007940	Method that creates new object of the same type, replaces initial object with the new one	public sealed class MyValue\n{\n  public MyValue(int value)\n  {\n    this.Value = value;\n  } \n\n  public int Value { get; private set }\n\n  public MyValue Add(int value)\n  {\n    return new MyValue(this.Value + value);\n  }\n}	0
18176289	18165869	Facebook C# SDK Windows Phone logout	await new WebBrowser().ClearCookiesAsync();	0
20503867	19917056	Best Way to implement Email generation in this scheduled console app	public static void sendMail(string msg)\n    {\n        SmtpClient smtpClient = new SmtpClient();\n        MailMessage message = new MailMessage();\n        MailAddress fromAddress = new MailAddress(emailFrom);\n        smtpClient.Host = smtpHost;\n        message.From = fromAddress;\n        message.Subject = "Test Email";\n        message.IsBodyHtml = true;\n        message.Body = msg;\n        message.To.Add(emailTo);\n        message.Priority = MailPriority.High;\n        smtpClient.Send(message);\n    }	0
4615428	4615410	Random element of List<T> from LINQ SQL	var rand = new Random();\nvar user = users[rand.Next(users.Count)];	0
6520030	6520006	find common items across multiple lists in C#	var CommonList = TestList1.Intersect(TestList2)	0
7806777	7802626	How could I find an application window via it's ClassID?	var wndCalc = appCalc.GetWindow(SearchCriteria.ByNativeProperty(AutomationElement.ClassNameProperty, "Your class name"), InitializeOption.NoCache);	0
19721787	19482315	not able to get value from aspx page to aspx.cs	String passedValue=Request.QueryString["id"] as string;	0
24144912	24144580	How to query for entities with no matching siblings, with LINQ?	(from citation in Citation select citation)\n.Except(\nfrom c in Citation\njoin ci in CitationIdentifier on c.Identifier equals ci.Identifier\nselect c);	0
5595429	5595338	Add the where clause dynamically in Entity Framework	var pr = PredicateBuilder.False<User>();\nforeach (var name in names)\n{\n    pr = pr.Or(x => x.Name == name && x.Username == name);\n}\nreturn query.AsExpandable().Where(pr);	0
30801358	30788064	NHibernate - using CreateMultiQuery	var criteria1 = DetachedCriteria.For<Server>()\n                    .Add(Restrictions.Eq("ServerID", s.ServerID))\n                    .SetFetchMode("Adapters", FetchMode.Eager)\n                    .CreateCriteria("Adapters", JoinType.LeftOuterJoin);\n\nvar criteria2 = DetachedCriteria.For<Server>()\n                    .Add(Restrictions.Eq("ServerID", s.ServerID))\n                    .SetFetchMode("Configurations", FetchMode.Eager)\n                    .CreateCriteria("Configurations", JoinType.LeftOuterJoin);\n\nvar result = Session.CreateMultiCriteria()\n                    .Add(criteria1)\n                    .Add(criteria2)\n                    .List();\n\nIList list = (IList)result[0];\nvar server = list[0] as Server;	0
8688931	8688856	What's a good way to report progress from a Repository to the UI	// Repository\npublic delegate void ReportProgress(int percentage);\n\n  public IEnumerable<X> GetSomeRecords(..., ReportProgress reporter)\n  {\n      ...;\n      if (reporter != null)\n          reporter(i * 100 / totalRecords);  \n  }	0
19649431	19649227	How do I serialize an enum as part of a DataContract from Code First Entity Framework	DataContract(Name = "JobStatus")]\npublic enum JobStatus\n{\n    [EnumMember]\n    New, \n    [EnumMember]\n    Submitted,\n    [EnumMember]\n    Approved,\n    [EnumMember]\n    Returned,\n    [EnumMember]\n    OnHold,\n    [EnumMember]\n    Cancelled,\n}	0
15635608	15635310	Update SQL Server Table Based on User Level Input	SqlCommand sqlCmd = new SqlCommand("UPDATE usr_Table SET description= @description, subject = @subject, text = @text, status = @status WHERE code = @code", connectionString);\nsqlCmd.Parameters.Add(new SqlParameter("description", newDescription));\nsqlCmd.Parameters.Add(new SqlParameter("subject", newSubject));\nsqlCmd.Parameters.Add(new SqlParameter("text", newText));\nsqlCmd.Parameters.Add(new SqlParameter("status", newStatus));\nsqlCmd.Parameters.Add(new SqlParameter("subject", newSubject));\nsqlCmd.Parameters.Add(new SqlParameter("code", code));\n\nsqlCmd.ExecuteNonQuery();	0
16565590	16565269	Save TreeView as xml with attributes and elements	private void SaveNodes(TreeNodeCollection nodesCollection, XmlWriter textWriter)\n    {\n        foreach (var node in nodesCollection.OfType<TreeNode>().Where(x => x.Nodes.Count == 0))\n            textWriter.WriteAttributeString(node.Name, "Attribute value");\n\n        foreach (var node in nodesCollection.OfType<TreeNode>().Where(x => x.Nodes.Count > 0))\n        {\n            textWriter.WriteStartElement(node.Name);\n            SaveNodes(node.Nodes, textWriter);\n            textWriter.WriteEndElement();\n        }\n    }	0
15956408	15956031	How to Compare two histograms of images?	int[] array1 = {0,255,100,200,78 };\nint[] array2 = {255, 0, 250, 15, 34 };\nfloat[] diff = new float[5];\nfor (int i = 0; i < 5; i++)\n{\n    diff[i] = ((float)Math.Abs(array1[i] - array2[i])) / 255;\n}\n\nfloat degreeOfDiff = diff.Sum()/array1.Length*100;\nbool sameDistribution = degreeOfDiff == 0;\n\nDebug.WriteLine(degreeOfDiff + "%");\nDebug.WriteLine(sameDistribution);	0
9641158	9640994	Loop through dataset and add items to a html table in code behind	JobPositionSystemDAL jps = new JobPositionSystemDAL();\n        DataSet ds = jps.OpenJobOpeningByID(1);\n\n        TableRow tableRow;\n        TableCell tableCell;\n        foreach (DataTable dataTable in ds.Tables)\n        {\n            foreach (DataRow dataRow in dataTable.Rows)\n            {\n                tableRow = new TableRow();\n                tableCell = new TableCell();\n                tableCell.Text = dataRow["QUESTIONTEXT"].ToString();\n                tableRow.Cells.Add(tableCell);\n                myTable.Rows.Add(tableRow);\n            }\n        }	0
33947457	33947438	How to spawn object on mouse position?	spawnPoint = cameraPosition + new Vector3(mouseX, mouseY, 0);	0
13133273	13133159	Converting date from mm/dd/yyyy which is read from excel to yyyy/mm/dd before sending it to database	if (ExcelRows[i]["data"] == DBNull.Value)\n    {\n        // Include any actions to perform if there is no date\n    }\n    else\n    {\n        DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;\n        DateTime newDate = Convert.ToDateTime(oldDate).Date;\n        ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");\n    }	0
27654329	27654210	How to get the values within a cookie	var s = Request.Cookies["myvalue"].Value;\ns = HttpUtility.UrlDecode(s ?? string.Empty);\nstring[] values = s.Split(',').Select(x => x.Trim()).ToArray();	0
15883608	15883410	User Login System for Prototype Business Application	User           UserRoles               Roles\n---------       ---------------         ------------\nUserID(PK)          UserID(FK)(PK)         RoleID(PK)\nUserName            RoleID(FK)(PK)         RoleName\nPassword                                   RoleDescription	0
9378827	9378698	How can you inject an asp.net mvc3 custom membership provider using Autofac?	public override bool ValidateUser(string username, string password)\n{\n    var userRepo = DependencyResolver.Current.GetService<IUserRepository>();\n    return userRepo.ValidateUser(username, password);\n}	0
13997232	13996670	Trying to call a C# COM object from VB 6	Private Sub Command1_Click()\n\n    Dim class1 As New COMWorld.COMObject\n    class1.COMModule\n\nEnd Sub	0
10942425	10942204	Is there a way to detect a serial port's fastest speed?	serialPort = new SerialPort(portName);\n   serialPort.Open();\n   object p = serialPort.BaseStream.GetType().GetField("commProp", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(serialPort.BaseStream);\n   Int32 bv = (Int32)p.GetType().GetField("dwSettableBaud", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(p);	0
19214578	19213023	Getting a foreign key in a table	int userID = Membership.GetUser().ProviderUserKey;\n\ndb.UserProfiles.Find(q => q.UserID == userID).LearnedExpressions.ToList();	0
20202644	20202557	Read a linked xml file in Visual Studio 2010 C# project	XDocument.Load(Path.GetFullPath("config.config"))	0
5082967	5082876	Entity Framework - Pulling back related data	var result = \n    from p in ctx.Persons\n    from a in ctx.OtherTable\n    where p.PersonID == personID\n    select new SomeViewModel \n    {\n        Name = p.Person.Name,\n        OtherTableValue = a.OtherValue\n    };	0
10826312	10821273	Domain Model with Nhibernate design issue	Map(x => x.IsBlocked).Access.CamelCaseField(Prefix.Underscore);	0
11830216	11829989	Script for changing DB values of columns with different names from several different tables	1.Selecting 10's of columns from 10's of columns -- select * from tablename is good way.\nBut this is not good when you consider the query for performance point of view.If your reuirement is to get all the columns of a table then you can use select * from tablename.\n\n2.This is quite obvious that you have to use all 10 columns if u have to change their values.\nUPDATE tablename SETcol1=value1,\n       col1=value1,\n       col1=value1,\n       .....	0
25889739	25887534	How to Add Custom variables to SendGrid email via API C# and Template	replacementKey = "*|VERIFICATION_URL|*";\n            substitutionValues = new List<string> { VERIFICATION_URL };\n\n            myMessage.AddSubstitution(replacementKey, substitutionValues);	0
6060427	6060366	Writing to a text file by trimming certain characters using C#?	int errorIndex = line.IndexOf("Raiseerror", StringComparison.CurrentCultureIgnoreCase)\nif (errorIndex  != -1)\n{\n  int start = line.IndexOf('\'', errorIndex) + 1;\n  int finish = line.IndexOf('\'', start);\n  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "           " + line.Substring(start,finish - start));\n}	0
7336752	7336561	Variable wrapper for session-persistance	public int SomeProperty\n {\n     get { return GetValueFor(x => x.SomeProperty); }\n     set { SetValueFor(x => x.SomeProperty, value); }\n }\n\n protected T GetValueFor<T>(Expression<Func<ThisClass, T>> propertySelector)\n {\n     string propertyName = // Get Value from expression.. to loo long to post here\n\n     return (T)_session[propertyName];\n }\n\n protected SetValueFor<T>(Expression<Func<ThisClass, T>> propertySelector, object value)\n {\n     string propertyName = // Get value from expression\n\n     _session[propertyName] = value;\n }	0
4415542	4415519	Best way to remove duplicate entries from a data table	public DataTable RemoveDuplicateRows(DataTable dTable, string colName)\n{\n   Hashtable hTable = new Hashtable();\n   ArrayList duplicateList = new ArrayList();\n\n   //Add list of all the unique item value to hashtable, which stores combination of key, value pair.\n   //And add duplicate item value in arraylist.\n   foreach (DataRow drow in dTable.Rows)\n   {\n      if (hTable.Contains(drow[colName]))\n         duplicateList.Add(drow);\n      else\n         hTable.Add(drow[colName], string.Empty); \n   }\n\n   //Removing a list of duplicate items from datatable.\n   foreach (DataRow dRow in duplicateList)\n      dTable.Rows.Remove(dRow);\n\n   //Datatable which contains unique records will be return as output.\n      return dTable;\n}	0
1547220	1547216	Why do i need to wrap this code in a cast to short?	int operator ?(int x, int y);\nuint operator ?(uint x, uint y);\nlong operator ?(long x, long y); \nulong operator ?(ulong x, ulong y);	0
18112410	18112338	Counting the Words in a String from a file	var count = File.ReadAllText(file).Split(' ').Count();	0
10697092	10696591	Retrieving table data from a doc file using c#	string aCellText;\n    foreach (Row aRow in Application.ActiveDocument.Tables[0].Rows)\n        foreach (Cell aCell in aRow.Cells)\n            aCellText = aCell.Range.Text;	0
30431199	30431133	WPF Detecting Window Close Event and coupling with a button event	private void loadButton_Click(object sender, RoutedEventArgs e)\n{\n    var richWindow = RichTextWindow.GetWindow(new RichTextWindow());\n    richWindow.Closed += (s, e) => loadButton.IsEnabled = true;\n    loadButton.IsEnabled = false;\n    richWindow.Show();\n}	0
32620729	32620226	How to set environment variables and use them in IIS application in Azure 2.5	System.IO.Path.Combine(\n    System.IO.Path.GetPathRoot(\n        System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath\n    ),\n    @"approot\bin\Data"\n);	0
12500621	12500506	LINQ to Entities: nullable datetime in where clause	var Lookup = row.Offenses\n  .Where(x => \n    x.Desc == co.Desc \n    && x.Action == co.Action \n    && x.AppealYN == co.AppealYN \n    && (co.OffDate.HasValue ? x.OffDate == co.OffDate : true)\n  ).ToList();	0
14961551	14961238	How to access resource file's value in code behind	var cityName = Properties.Resources.city;	0
3555241	3554973	How could i load a form corresponding to the cell clicked in datagrid	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        string s = dataGridView1.CurrentCell.RowIndex.ToString();\n        if (Convert.ToInt32(s) == 0)\n        {\n            Form f = new Form();\n            ActivateMdiChild(f);\n            f.Show();\n        }\n        if (Convert.ToInt32(s) == 1)\n        {\n            MessageBox.Show("Hi");\n        }\n    }	0
1660762	1643740	C# WPF Converting english numbers to arabic numbers	CultureInfo ci = CultureInfo.CreateSpecificCulture(Thread.CurrentThread.CurrentCulture.Name);\n        ci.NumberFormat.DigitSubstitution = DigitShapes.NativeNational;\n        Thread.CurrentThread.CurrentCulture = ci;	0
10862792	10862498	Share something in Facebook ASPX	gplus.HRef = "https://plusone.google.com/_/+1/confirm?title=" + HttpUtility.UrlEncode(Page.Title) + "&amp;url=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri);\n    facebook.HRef = "http://www.facebook.com/sharer.php?t=" + HttpUtility.UrlEncode(Page.Title) + "&amp;u=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri);\n    linkedin.HRef = "http://www.linkedin.com/shareArticle?mini=true&amp;title=" + HttpUtility.UrlEncode(Page.Title) + "&amp;url=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri);\n    myspace.HRef = "http://www.myspace.com/Modules/PostTo/Pages/?t=" + HttpUtility.UrlEncode(Page.Title) + "&amp;u=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri);\n    twitter.HRef = "http://twitter.com/share?text=" + HttpUtility.UrlEncode(Page.Title) + "&amp;url=" + HttpUtility.UrlEncode(Request.Url.AbsoluteUri);	0
9273181	9272581	How to merge two objects in C#  asp.net mvc3	object x = new { @class = "aClass", bar = "bar" };\nobject y = new { foo = "foo" };\n\nvar htmlAttributes = new RouteValueDictionary(x);\nforeach (var item in new RouteValueDictionary(y))\n{\n    htmlAttributes[item.Key] = item.Value;\n}\n\n// at this stage htmlAttributes represent an IDictionary<string, object>\n// that will contain the 3 values and which could be passed\n// along to the overloaded versions of the standard helpers \n// for example:\nvar link = htmlHelper.ActionLink("link text", "foo", null, htmlAttributes);\n\n// would generate:\n// <a href="/home/foo" class="aClass" bar="bar" foo="foo">link text</a>	0
12132910	12132878	How do I retrieve the date and time from DateTime string	string date = dateform.ToString("MM/dd/yy");\n    string time = dateform.ToString("hh:mm:ss tt");\n\nMM - month\ndd - day\nyy - year, can also use yyyy if you want it with 4 numbers\n\nhh - hour\nmm - minute\nss - second\nt - one letter as in AM -> A and PM - P\ntt - two letters AM/PM	0
30732004	30725783	Multiple filters via MongoDB C# driver	var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<Contact>();\n    var renderedFilter = result.Render(documentSerializer, BsonSerializer.SerializerRegistry).ToString();\n    Trace.WriteLine("Filter: " + renderedFilter);	0
8264975	8264908	how build a hash table stored object in C#?	Hashtable MyHashTable = new Hashtable();\n    MyHashTable.Add(1, "word");\n    MyHashTable.Add("word", 12);\n\n    // to access 12\n    int MyInt = (int)MyHashTable["word"];	0
26737459	26737083	Update multiple mysql columns using parametarized update command	string constring = string.Format("datasource='{0}';port='{1}';database='{2}';username=claimsprologin;password=gfx)C#G$aD3bL`@;Connect Timeout=180;Command Timeout=180", serveriplable.Text, portno.Text, databasenamelable.Text);\nstring Query = "update claimloans set loannumber= @loannumbertextbox, pool = @loanpooltextbox, disblid = @disbidtextbox, category = @categorytxtbox, subcacategory = @subcategorytxtbox, invoice = @invoicenumbertextbox, invoicedate = @invoicedatetextbox, docs = @docscombobox, where username = @usernamelable;";\nMySqlConnection conwaqDatabase = new MySqlConnection(constring);\nMySqlCommand cmdwaqDatabase = new MySqlCommand(Query, conwaqDatabase);\n\ncmdwaqDatabase .Parameters.AddWithValue("@loannumbertextbox", this.loannumbertextbox.Text.Trim());	0
3354262	3354067	Load Textboxes from array	//Use any collection you prefer instead of 'List' if you want.\nDictionary<String, List> arrays = new Dictionary<String, List>();\n\nprivate void OnTextChanged(object source, EventArgs e)\n{\n    if (source == txtT000)\n        loadTextBoxes(txtT000.Text, txtL000, txtL001, txtL002, \n            txtL003, txtL004, txtL005, txtL006, txtL007, txtL008,\n            txtL009); \n    //etc\n}\n\nprivate void loadTextBoxes(string key, params TextBox[] textboxes)\n{\n    List myList = arrays[key];\n\n    //Check for both constraints on the loop so you don't get an exception\n    //for going outside either index of textboxes array or myList.\n    for (int i = 0; ((i < textboxes.length) && (i < myList.Count)); i++)\n        textboxes[i].Text = myList[i].ToString();\n}	0
3289099	3289087	How to convert hash data to original data?	HashAlgorithm.Create("SHA1");	0
13638083	13637926	How to save a PictureBox image in varying formats?	var fd = new SaveFileDialog();\n        fd.Filter = "Bmp(*.BMP;)|*.BMP;| Jpg(*Jpg)|*.jpg";\n        if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n        {\n            switch (Path.GetExtension(fd.FileName))\n            {\n                case ".BMP":\n                    pictureBox.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);\n                    break;\n                case ".Jpg":\n                    pictureBox.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);\n                    break;\n                default:\n                    break;\n            }\n        }	0
10097020	10096667	Projecting new item that contains lists	var q = db.BusinessObjectsContextProperty.Select(d => d.items)  //eager load the items property\n   .ToList() // get it into memory\n   .Select(d => new BusinessObject { MyList = d.items\n      .Select(item => new MyObject { ... } ) // project the in-memory list\n   );	0
12452745	12452701	Iterating through Datagridview column headers	foreach (DataGridViewColumn column in myDataGridView.Columns)\n{\n   DataGridViewColumnHeaderCell headerCell = column.HeaderCell;\n   string headerCaptionText = column.HeaderText;\n   string columnName = column.Name; // Used as a key to myDataGridView.Columns['key_name'];\n}	0
266139	266116	How to get a screen capture of a .Net control programmatically?	Control c = new TextBox();\nSystem.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);\nc.DrawToBitmap(bmp, c.ClientRectangle);	0
21623194	21622879	How to get rid of the endless loop?	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine("Input Your Exam Score");\n        var examScore = Convert.ToInt32(Console.ReadLine());\n\n        var grade = GetGrade(examScore);\n        Console.WriteLine(grade);\n    }\n\n    private static string GetGrade(int examScore)\n    {\n        if (examScore >= 90)\n            return "Excellent";\n\n        if (examScore >= 70)\n            return "Good";\n\n        return "Satisfactory";\n    }\n}	0
12949204	12949000	How can i get the inner value of a node in xml	var countryElement = XElement.Parse(xml).Element("Country");\n string result = (countryElement != null) ? countryElement.Value : string.Empty;	0
20771713	20771512	How to find all assemblies that reference a specific dll?	string[] fileNames = ...; // get all the filenames\nforeach (string fileName in fileNames) {\n    var assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(fileName);\n    var referencedAssemblies = assembly.GetReferencedAssemblies();\n\n    foreach (var assemblyName in referencedAssemblies) {\n        // do your comparison\n    }\n}	0
32394145	32390758	How To Get Values From Cells In Radgrid C# asp.net	protected void PostRadButton_Click(object sender, EventArgs e)\n            {\n                int p;\n                if (DocStatTxtBox.Text == "2")\n                {\n                    foreach (GridDataItem item in RadGrid1.Items)\n                    {\n\n                            p = item.RowIndex;\n\n                            Label itemparam = (Label)item["ItemCode"].FindControl("ItemCodeLabel");\n                            Label qparam = (Label)item["Quantity"].FindControl("QuantityLabel");\n\n\n                            string itemcodeparam = itemparam.Text;\n                            int quantityparam = Convert.ToInt16(qparam.Text);\n                            Boolean x = Methods.UpdateStock(WhTxtBoxRadDropDownList.SelectedValue, itemcodeparam, -quantityparam);\n\n\n                    }\n                }\n            }	0
8522242	3861946	VS2010 Add-In, adding a command to a context menu?	newCommand = commands.AddNamedCommand2(_addInInstance, commandName, commandText, commandText, true, iconId, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,(int)vsCommandStyle.vsCommandStylePictAndText,vsCommandControlType.vsCommandControlTypeButton);	0
21966602	21896972	Change Default Chart place in excel	excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 150);\nExcel.Range chartPlacementRange = oWorkSheet.get_Range("E15", "E15");\nmyChart.Left = chartPlacementRange.Left;\nmyChart.Top = chartPlacementRange.Top;	0
4190395	4190303	DeepCopy A SortedDictionary	// assuming dict is your original dictionary\nvar copy = new SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>>();\nforeach(var subDict in dict)\n{\n    var subCopy = new SortedDictionary<int, VolumeInfoItem>();\n    foreach(var data in subDict.Value)\n    {\n        var item = new VolumeInfoItem\n                   {\n                       up = data.Value.up,\n                       down = data.Value.down,\n                       neutral = data.Value.neutral,\n                       dailyBars = data.Value.dailyBars\n                   };\n        subCopy.Add(data.Key, item);\n    } \n    copy.Add(subDict.Key, subCopy);\n}	0
1754957	1754908	In WPF / C#, how can I check if the center button is clicked or released?	private void control_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    if (e.ChangedButton == MouseButton.Middle)\n    {\n\n    }\n}	0
32950501	32112731	ClosedXML Format cell to contain formula	//get all rows in my datatable \nint totalRows = dt.Rows.Count;\n\n//set the first that will be filled with data\nint currentRow = 1;\n\n//loop through each row.\nfor(int i = 0; i < totalRows; i++){\n\n//the current cell will be whatever column you wish to format + the current row\nstring currentCell = "F" + currentRow;\n\n//create your formula\nstring AdjustedPriceFormula = "=C" + currentRow + "*" + "D" + currentRow;\n\n//apply your formula to the cell.\ntheSheet.Cells(currentCell).FormulaA1 = AdjustedPriceFormula;\n\n//increment your counters to apply the same data to the following row\ncurrentRow++	0
16538699	16538620	Remove a particular item from a list which is in a session	var list = (List<ShoppingCartView>)Session["ShoppingView"];\nSession["ShoppingView"] = list.Where(x => x.ProductName!= "pname").ToList();	0
8347285	8347182	How to GetType().GetFields with a custom attribute?	public static FieldInfo[] GetFieldsWithAttribute(Type type, Attribute attr, bool onlyFromType)\n{\n    System.Reflection.FieldInfo[] infos = type.GetFields();\n    var selection = \n       infos.Where(info =>\n         (info.GetCustomAttributes(attr.GetType(), false).Length > 0) &&\n         ((!onlyFromType) || (info.DeclaringType == type)));\n\n    return selection.ToArray();\n}	0
29920678	29920226	Converting a file in C# into byte array before parsing it into Java	File.ReadAllBytes(filePathHere).Select(b=>(sbyte)b).ToArray();	0
31192670	31187928	Searching a list and then removing from it C#	public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)\n    {\n        for (int i = targetFileList.Count - 1; i>-1; i--)\n        {\n            sourceFileList.RemoveAll(x => x.fName == targetFileList[i].fName);             \n        }\n    }	0
4501837	4485502	how can I use Moles to redirect select from tables via LINQ?	// using System.Data.Linq.Moles; \n// CM is a namespace alias \nvar subsList = new List<CM.Subscription>{\n  new CM.Subscription() { SubscriptionID = subId1 },\n  new CM.Subscription() { SubscriptionID = subId2 },\n  new CM.Subscription() { SubscriptionID = subId3 }};\n\nvar subsTable = new MTable<CM.Subscription>();\n\nsubsTable.Bind(subsList.AsQueryable());\n\nMTheDataContext.AllInstances.SubscriptionGet = (c) => { return subsTable; };	0
28739147	28738497	Why I am getting two widths and two heights of sprite in Unity 2D	public class Score : MonoBehaviour\n{\nSpriteRenderer renderer;\nTransform player;\n\npublic GameObject obstacle;\npublic int score = 0;\npublic float width;\npublic float height;\n\nvoid Start()\n{\n    player = (Transform)GameObject.Find("Player").GetComponent<Transform>();\n    renderer = GameObject.Find("Crate").gameObject.GetComponent<SpriteRenderer>();\n\n    width = renderer.bounds.size.x;\n    height = renderer.bounds.size.y;\n\n    Debug.Log(width);\n    Debug.Log(height);\n}\n\nvoid Update()\n{\n    if (obstacle != null && obstacle.transform != null)\n    {\n        if (player.position.x >= obstacle.transform.position.x &&\n           player.position.x < obstacle.transform.position.x + (width - 0.9))\n        {\n            score++;\n            //Debug.Log(score);\n        }\n    }\n}\n}	0
34264867	34264307	Nunit: Add Category to specific test cases	[TestFixture]\npublic class TestAddition\n{\n    [TestCase(1, 2, 3, Category = "PreCheckin")]\n    [TestCase(2, 4, 6)]\n    [TestCase(3, 6, 9)]\n    public void AdditionPassTest(int first, int second, int expected)\n    {\n        var adder = new Addition();\n        var total = adder.DoAdd(first, second);\n        Assert.AreEqual(expected, total);\n    }\n}	0
22625813	22625737	How can I include more than one level deep in a LINQ query?	var exams = _examsRepository\n           .GetAll()\n           .Where(q => q.SubjectId == subjectId)\n           .Include(q => q.Tests.Select(t => t.UserTests))\n           .ToList();	0
15811110	15811017	Re-Writing ordinary methods with async and await	await BiginAuthenticate();\n\n\n public async Task BiginAuthenticate()\n {\n\n    if (condtion)\n        await PerformSecondLevelAuthenitcation();\n\n }\n\n public async Task PerformSecondLevelAuthenitcation()\n {\n\n }	0
9793312	9793160	Getting the InnerHtml of an HTMLTable c#	StringBuilder sb = new StringBuilder();\nStringWriter tw = new StringWriter(sb);\nHtmlTextWriter hw = new HtmlTextWriter(tw);\n\nHtmlTable.RenderControl(hw);\nString HTMLContent = sb.ToString();	0
25376451	25278344	Selenium click link multiple times	IWebElement element = driver.findElement(By.id("foobar"));\nPoint point = element.Location;\nIJavascriptExecutor jscript = (IJavascriptExecutor)driver;\njscript.executeScript("$(document.elementFromPoint(arguments[0], arguments[0])).click();", point.X, point.Y);	0
28584190	28582588	Show xml code in page	saveText.Text = Server.HtmlEncode(XmlDoc.InnerXml);	0
17390798	17390687	How in C# to send array/collection in SQL Server	for(...)\n{\n//insert into Book (author, book, genre, pages)\n}	0
22094878	22080082	How to get a function Return Type as a CodeClass2 from a method CodeElement2	((CodeFunction2)codeElement).Type.CodeType as CodeClass2;	0
16396062	16396007	how to avoid the member assignment in LINQ orderby/groupby	var query = (from a in this.db.Servers    \n             where (a.Date >= fromDP.SelectedDate.Value \n                           && a.Date <= toDP.SelectedDate.Value)   \n             group a by EntityFunctions.TruncateTime(a.Date) into p\n             select p.Count()).OrderBy(x => x);	0
15468052	15468015	how to create array in c# for android	string[] strArr = editText.Text.Split('\n');	0
2704480	2704438	How do I sort a list using LINQ?	designers = designers\n  .OrderBy(td => td.FirstName)\n  .ThenBy(td => td.LastName)\n  .ToList();	0
2984266	2984224	how to retrieve userId from membership users table	MembershipUser user = Membership.CreateUser("foo","password");\nuser.ProviderUserKey	0
24465913	24465623	Populate listview with data received from SQL query	string ssConnectionString = "Server connection";\nSqlConnection conn = new SqlConnection(ssConnectionString);\nconn.Open();\nSqlCommand command = conn.CreateCommand();\ncommand.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";     \nSqlDataAdapter da = new SqlDataAdapter(command); \nDataTable dataTable;\nda.Fill(dataTable);   \nlstData.DataSource = dataTable;\nlstData.DataBind();\nconn.Close();	0
1991571	1483323	Handle Button Click in WinForm DataRepeater C# Power Pack	private void button1_Click(object sender, EventArgs e)\n    {\n        Console.WriteLine("DEBUG: CurrentItem: " + dataRepeater1.CurrentItem);\n        Console.WriteLine("DEBUG: CurrentItemIndex: " + dataRepeater1.CurrentItemIndex);\n    }	0
27947940	27947163	Entity Framework table Mapped to an Association with No Table	BulkEntry.Titles.add(TitleToAdd)	0
8794272	8794251	Converting a string to a variable name	var fileSuffixList = new List<string>{ "xyz.jpg" , "abc.png", "qwe.jpg"};\n\nforeach(string fileSuffix in fileSuffixList)\n{\n  ....\n foreach (var item in tabItem)\n  {\n    item.ImagePath.Value = "images1/" + ("filename2_" + fileSuffix);\n    item.ThumbPath.Value = "thumbnails1/" + ("filename2_" + fileSuffix);\n  } \n}	0
11356477	11352796	Delete table record from entity framework driven gridview with view datasource	db.DeleteObject(mgrToDelete);\ndb.SaveChanges();\nMgrGrid.DataBind();\n\ne.Cancel = true;	0
23785085	23784926	How to create textbox at run time and take values from these text box ? in C# . Net	private void get_value_Click(object sender, EventArgs e)\n    {\n        for (i = 1; i <= 3; i++)\n        {\n            string value = this.flowLayoutPanel1.Controls["Text Box" + i].Text;\n            richTextBox1.SelectedText  = "\r\n" + value;\n        }\n    }	0
1306981	1306947	Closures and Lambda in C#	foreach (string name in names.Where(n => n.StartsWith("C") ) ) \n{\n    Console.WriteLine(name);\n}	0
15336482	15290780	Fetch DateTime CRM 2011	string Date_Gather = string.Format(@"         \n      <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>\n         <entity name='new_import'>                       \n                 <attribute name='new_enddate'/>         \n         </entity>\n       </fetch>", entity.Id);\n\nforeach (var b in Date_Gather_result.Entities)\n{\n\n   if (b.Attributes.Contains("new_enddate"))\n      {\n          enddate = ((DateTime)(b["new_enddate"]));\n          Entity.Attributes.Add("scheduledend", enddate);\n      }\n}	0
22189318	22187464	Execute multiple line PowerShell Script from C#	string script = @"\n$Username = 'User'\n$Password = 'Password'\n$SecurePass = ConvertTo-SecureString -AsPlainText $Password -Force\n$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList     $Username,$SecurePass\n$contents = [IO.File]::ReadAllBytes('D:\MyFile.xml')\nInvoke-Command -ComputerName ComputerName -Credential $Cred {[IO.File]::WriteAllBytes('D:\\MyFile.xml',$using:contents)}\n";\n\n pipeline.Commands.AddScript(script);\n Collection<PSObject> results = pipeline.Invoke();	0
14128576	14127920	Windows Phone c#, how to change button image when in pressed state?	private void imLeft_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)\n{\n    _wormDirection = Direction.Left;\n    ((Image)sender).Source = null;\n}\n\nprivate void imLeft_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)\n{\n    System.Threading.Thread.Sleep(25);\n    ((Image)sender).Source = imLeftImageSource;\n}	0
32336867	32336491	How to get image from assets folder in windows phone 8.1 and assign it to a model's property	bi.UriSource = new Uri("ms-appx:///Assets/Icons/noprofilepic.png");	0
14833827	14831846	How to use Max and Group By in an NHibernate query?	var result = from item in session.Linq<Item>()\n                         group item by item.ClientId\n                         into itemGroups\n                         select new\n                             {\n                                 id = itemGroups.Key,\n                                 max = itemGroups.Max(er => er.Id)\n                             };	0
4548075	4548062	How to cast a STRING to a GUID	string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text;\n      Guid myGuidUserId;\n      if (Guid.TryParse(myUserIdContent, out myGuidUserId)\n      {\n          MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId);\n      }\n      else\n      {\n          // throw exception and/or inform user\n      }	0
30586392	30586025	Show drop down list value between max and min value from database	void Page_Load(Object sender, EventArgs e)\n  {\n\n        if (DDLlist==null)\n        {\n          MaxMinSkillLevel minMax = CompetencyManager.GetMaxAndMinSKillLevelBySkillName(lblname.Text);\n\n          DDLlist = new List<string>();\n          for (int i = Int32.Parse(minMax.minimumLevel); i < Int32.Parse(minMax.maximumLevel); i++)\n          {\n            DDLlist.Add((i + 1).ToString());\n          }\n        }\n     // Load data for the DropDownList control only once, when the \n     // page is first loaded.\n     if(!IsPostBack)\n     {\n\n        // Specify the data source\n        YourDropDownList.DataSource = DDLlist;\n\n        // Bind the data to the control.\n        YourDropDownList.DataBind();\n\n        // Set the default selected item, if desired.\n        YourDropDownList.SelectedIndex = 0;\n\n     }\n\n  }	0
25085270	24617801	Is there a way to get the margins previously set by `DwmExtendFrameIntoClientArea`?	MARGINS g_Margins;\ng_Margins.cxLeftWidth = 0;\ng_Margins.cxRightWidth = 0;\ng_Margins.cyTopHeight = 15*fontHeight;\ng_margins.cyBottomHeight = 7*fontHeight;\n\nDwmExtendFrameIntoClientArea(g_hwnd, g_margins);	0
23159253	23158906	Adding all values selected from the Listbox	double total = 0;\n    for (int i = 0; i < listBox1.SelectedItems.Count; i++)\n    {\n        total += Double.Parse(listBox1.SelectedItems[i].ToString());\n    }\n\n    MessageBox.Show("The average is: " + total / listBox1.SelectedItems.Count);	0
13493570	13493416	Scan assembly for classes that implement certain interface and add them to a container	foreach (Type type in scanners)\n{\n    var scanner = Activator.CreateInstance(type) as ITorrentScanner;\n    if(scanner != null)\n         TorrentScannerContainer.Current.Scanners.Add(scanner);\n}	0
955098	955084	How to cast an interface to its sub interface?	void SomeMethod<T>(out T targetVar, IInterfaceX someVarX) where T: IInterfaceX\n{\n       targetVar = (T) someVarX;\n}	0
17995855	17987720	Quickfix/n, how to disable store and log factories?	public class NullLogFactory : ILogFactory\n{\n    SessionSettings settings_;\n\n    #region LogFactory Members\n\n    public NullLogFactory(SessionSettings settings)\n    {}\n\n    public ILog Create(SessionID sessionID)\n    {\n        return new QuickFix.NullLog();\n    }\n\n    #endregion\n}	0
32854687	32854589	Update y-axis maximum in chart	chart1.ResetAutoValues();	0
33010916	33010800	INSERT INTO syntax error in c#	OleDbCommand cmd = new OleDbCommand(@"INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand) \nVALUES(" + Convert.ToInt32(txtinvoice.Text) + ",\"" +          \ndateTimePicker1.Value.ToString("yyyy/MMM/dd") + "\",\"" + \nConvert.ToString(txtcn.Text) + "\",\"" + txtttl.Text + "\",\"" + \nConvert.ToInt32(cmtax.Text) + "\",\"" + txtgrdttl.Text + "\")", con);\ncmd.CommandType = CommandType.Text; \ncmd.ExecuteNonQuery(); \ncon.Close();	0
24108495	24108080	WPF Datagrid, possible to select or focus on row once created?	int recordId = [value of primary key in new record]\nRecords = [select records from database]\nGridItemSource = Records;\nSelectedItem = Records.Where(x => x.RecordId == recordId).FirstOrDefault();	0
8966179	8966108	What is the linq select syntax to check for xml data with null elements?	XDocument doc = XDocument.Load(addressString);\n         XElement results = doc.Root.Element("results");    \nvar makeInfo =\n         (from s in doc.Descendants("quote")\n          let lastTradeDate = s.Element("LastTradeDate")\n          where (lastTradeDate == null || string.IsNullOrEmpty(lastTradeDate.Value))\n          && s.Attribute("symbol") != null\n          select s.Attribute("symbol")).Count();	0
11733457	11733385	convert string to datetime according to Culture	// convert it to a datetime\n// "d" is the required format\nvar date = DateTime.ParseExact("7/23/1997", "d", CultureInfo.InvariantCulture);\n\n// now you can output the date in the user's culture\nvar localizedDateString = date.ToString("d");	0
6066572	6066539	How to get correct pdf size	var fileLengthInKB = f.Length / 1024.0;	0
6538119	6538104	looking for a c++ socket dll to use in c#	System.Net	0
24854110	24853939	XML Deserialization to Class, Add to List	[XmlArray("Profiles ")]\n[XmlArrayItem("Profile", typeof(Profile))]\npublic List<Profile> Profiles = new List<Profile>();	0
12845143	12830421	how to read the names of all custom fields in microsoft project?	CustomFieldDataSet cfDS = new CustomFieldDataSet();\n\nPSLibrary.Filter cfFilter = new Microsoft.Office.Project.Server.Library.Filter();\ncfFilter.FilterTableName = cfDS.CustomFields.TableName;\n\ncfFilter.Fields.Add(new PSLibrary.Filter.Field(cfDS.CustomFields.TableName, cfDS.CustomFields.MD_PROP_NAMEColumn.ColumnName));\ncfFilter.Fields.Add(new PSLibrary.Filter.Field(cfDS.CustomFields.TableName, cfDS.CustomFields.MD_PROP_IDColumn.ColumnName));\ncfFilter.Fields.Add(new PSLibrary.Filter.Field(cfDS.CustomFields.TableName, cfDS.CustomFields.MD_PROP_UIDColumn.ColumnName));\ncfFilter.Fields.Add(new PSLibrary.Filter.Field(cfDS.CustomFields.TableName, cfDS.CustomFields.MD_LOOKUP_TABLE_UIDColumn.ColumnName));\ncfFilter.Fields.Add(new PSLibrary.Filter.Field(cfDS.CustomFields.TableName, cfDS.CustomFields.MD_PROP_TYPE_ENUMColumn.ColumnName));\n\ncfDS = ReadCustomFields(cfFilter.GetXml(), false);	0
4185623	4185195	How to define a route to match 3 parameters, when I'm only interested in the third?	routes.MapRoute(\n    null,\n    "{param1}/{param2}/{mexid}",\n    new { controller = "ShareClass", action = "FundFactsheet" },\n    new { param1 = @".+", param2 = @".+", mexid = @".+" }\n);	0
25094645	25093723	How can I get tr link and content with HtmlAgilityPack?	//select <tr> having child node <td>\nvar tr = doc.DocumentNode.SelectNodes("//div[@class='linear-view']/table/tr[td]");\nforeach (HtmlNode node in tr)\n{\n    //select <td> having child node <a>\n    var td1 = node.SelectSingleNode("./td[a]"); //or using index: ./td[1]\n    var link = td1.FirstChild.Attributes["href"].Value;\n    var title = td1.InnerText;\n    //select <td> not having child node <a>\n    var publisher = node.SelectSingleNode("./td[not(a)]") //using index: ./td[2]\n                        .InnerText;\n}	0
4898582	4898521	how can I copy a file with a certain date in c#	FileInfo[] fis = dir.GetFiles("*", SearchOption.AllDirectories);\nforeach (FileInfo fi in fis)\n{\n    if (fi.LastWriteTime.Date == DateTime.Today.Date)\n    {\n        File.Copy(fi.FullName, target.FullName + "\\" + fi.Name, true);\n    }\n}	0
7325702	7325293	BitmapSource into a stream Windows Phone	WriteableBitmap bmp = new WriteableBitmap((BitmapSource)img);\n\nusing (MemoryStream stream = new MemoryStream()) {\n\n    bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);\n    return stream;\n}	0
19205132	19204611	How to Set DateTime to Current Culture and Time Zone in Windows Phone 8	currentTimeTextBlock.Text = DateTime.Today.ToShortDateString();	0
12230854	12230822	How to deserialize json object in C#	var list = new JavaScriptSerializer().Deserialize<List<FooBar>>(str);\n\npublic class FooBar\n{\n    public string foo;\n    public string bar;\n}	0
9459368	9459318	Getting foreign keys when populating a model from a view to a controller	public class ShowWithTv {\n    public Show { get; set; }\n    public TV { get; set; }\n}\n\npublic ActionResult Index(int ID) {\n    var data = new ShowWithTV();\n    data.Show = new Show();\n    data.TV = new TV().LoadFromId(ID) // put code here to load TV from ID\n    return View(data);\n}	0
8036919	8036906	cannot convert from 'List<string>' to 'string' exception	var query = new List<List<string>>(){\n                    new List<string>{"a", "b","c"},\n                    new List<string> {"a"}};	0
25724853	25721955	Get Data fro a DataSet Based on the Caption property	public virtual int GetIndexByCaption(string caption, DataTable dt)\n        {\n            int columnIndex = -1;\n            try\n            {\n                foreach (DataColumn column in dt.Columns)\n                {\n                    if (column.Caption == caption)\n                    {\n                        columnIndex = dt.Columns.IndexOf(column);\n                        break;\n                    }\n                }\n            }\n            catch(Exception ex)\n            {\n                Console.WriteLine(ex.Message);\n            }\n            return columnIndex;\n        }	0
24304227	24285866	How to get CheckBox "Ticked" inside ListBox on run time	private void CheckBox1_Checked(object sender, RoutedEventArgs e)\n    {\n        CONTACTS data = (sender as CheckBox).DataContext as CONTACTS;\n        string contactId = data.contactId;\n        string isFav = data.isFavourite.ToString();          \n    }	0
19410808	14884173	Using Windows.Automation, can I locate an AutomationElement by regex?	//Example :\nAutomationElement element = FindFirstDescendant( \n    AutomationElement.FromHandle(windows_hWnd), \n    (ele)=>Regex.IsMatch( ele.Current.Name, pattern)\n);\n\n//The generic method to find a descendant element:\npublic static AutomationElement FindFirstDescendant(AutomationElement element, Func<AutomationElement, bool> condition) {\n    var walker = TreeWalker.ControlViewWalker;\n    element = walker.GetFirstChild(element);\n    while (element != null) {\n        if (condition(element))\n            return element;\n        var subElement = FindDescendant(element, condition);\n        if (subElement != null)\n            return subElement;\n        element = walker.GetNextSibling(element);\n    }\n    return null;\n}	0
1311413	1311348	C# - Bogus data when loading a *.wav file to byte array	byte[] bytes = File.ReadAllBytes(filedialog.FileName);	0
15097789	15097650	How to get assembly path at runtime, running either in webserver, service or win app	string codeBase = Assembly.GetExecutingAssembly().CodeBase;\nUriBuilder uri = new UriBuilder(codeBase);\nvar path = Uri.UnescapeDataString(uri.Path);\nvar theDirectory = Path.GetDirectoryName(path);	0
20124458	20124432	Add quotes at the beginning and end of each element in list using LINQ	String.Join(",", myList.Select(x => String.Format("\"{0}\"", x));	0
33160685	33160420	Accessing Information From Drop Down List	this.DropDownList1.DataTextField = "Text";\nthis.DropDownList1.DataValueField = "Value"; \nthis.DropDownList1.DataSource = itemandprice;\nthis.DropDownList1.DataBind();	0
3415590	3035686	Recursive function MultiThreading to perform one task at a time	public class Program\n{\n  private static BlockingQueue<string> m_Queue = new BlockingQueue<string>();\n\n  public static void Main()\n  {\n    var thread1 = new Thread(Process);\n    var thread2 = new Thread(Process);\n    thread1.Start();\n    thread2.Start();\n    while (true)\n    {\n      string url = GetNextUrl();\n      m_Queue.Enqueue(url);\n    }\n  }\n\n  public static void Process()\n  {\n    while (true)\n    {\n      string url = m_Queue.Dequeue();\n      // Do whatever with the url here.\n    }\n  }\n}	0
11074015	11073056	How to build console application in debug mode and windows application in release mode?	public partial class App : Application {\n    private void Application_Startup(object sender, StartupEventArgs e) {\n#if DEBUG\n        AllocConsole();\n        Console.WriteLine("Hello world");\n#endif\n    }\n\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    private static extern bool AllocConsole();\n}	0
8531750	8531715	Cannot pass struct parameters via $.ajax to a controller using ASP.NET (with MVC2)	public struct Localization\n{\n  public int Id {get; set;}\n  public string {get; set;}\n  public string {get; set;}\n  public DateTime {get; set;}\n}	0
33080527	33080397	How to pick a random place from a 2D array?	Random rnd = new Random();\nint row = rnd.Next(mineKategorier.GetLength(0));\nint column = rnd.Next(mineKategorier.GetLength(1));\n\nstring randomKategori = mineKategorier[row, column];	0
19631869	19631336	Write XDocument's attribute value via XPath	using System.Linq;\nusing System.Xml.Linq;\nusing System.Xml.XPath;\n\nforeach (XAttribute attr in ((IEnumerable)\n         yourDocument.XPathEvaluate(yourXPath)).OfType<XAttribute>()) {\n    attr.Value = yourValue;\n}	0
28879200	28878323	Xamarin.Android ViewPager with only ImageViews	((ViewGroup)collection).AddView (i);	0
19401670	19400913	Finding the index of a ComboBoxItem in a WPF Combobox	Combobox comboBox = sender as ComboBox;\n\n if (e.AddedItems.Count > 0)\n    {\n        ComboBoxItem item = e.RemovedItems[0];\n        if (item != null)\n            int index = combobox.Items.IndexOf(item);\n    }	0
2674533	2674419	Create all word variations of 2 character arrays	var one = new [] { "a", "b", "c" };\nvar two = new [] { "x", "y", "z" };\n\nvar ot = from o in one from t in two select o + t;\nvar r = from f in ot from s in ot select f + s;\nvar list = r.ToList();	0
1849836	1848553	read or write ratings from AAC file	static void WriteAACData(FileInfo file, int rating, int playcount)\n{\n    ShellFile so = ShellFile.FromFilePath(file.FullName);\n    uint fileRating = (uint)so.Properties.System.Rating.Value;\n    System.Diagnostics.Trace.WriteLine(String.Format("Rating: {0}", fileRating));\n    so.Properties.System.Rating.Value = (uint)rating;\n}	0
5182011	5181881	Calling functions from within linq statement	newEmployee = (db.employees.Select(emp => new\n                  {\n                      emp.EmployeeID,\n                      emp.Username,\n                      Status = db.TimeTables\n                        .Where(d => d.Employee.Username == emp.Username\n                          && d.DateTime == DateTime.Today)\n                          .Select(x => x.ClockOut == null ? "IN" : "OUT")\n                          .FirstOrDefault()\n                  })).ToList();	0
30943800	30943633	Retrieve data from arrays	Console.WriteLine("Enter one of you student's id number");\n\nuserInput = Console.ReadLine();\nfor (int i = 0; i < studentsid.length; i++)\n{\n  if (studentsid[i].ToUpper() == userInput.ToUpper())\n  {\n      found = true;\n      Console.WriteLine(mark[i]);                           \n  }\n}	0
11492328	11491245	How can I remove ACL from folder that owned by non-existing user	using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))\n            {\n                //create empty directory security\n                var directorySecurity = new DirectorySecurity();\n                //set the directory owner to current user\n                directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);\n                //set the access control\n                Directory.SetAccessControl(directoryInfo.FullName, directorySecurity);\n            }	0
24282694	24282401	Update List Concatanate string	// Get the rooms with OCCUPANCY value equal to 2.\nrooms = rooms.Where(x=>x.OCCUPANCY==2);\n\n// Iterate through the selected rooms.\nforeach(var room in rooms)\n{\n    // Build a list of integers based on the room's list age.\n    List<int> currentListAge = room.ChildAges.Split(',').Select(int.Parse).ToList();\n\n    // Concat the currentListAge with the listAge, order the resulting list and\n    // then build a comma separated value list.\n    room.ChildAges = String.Join(",", currentListAge.Concat(listAge)\n                                                    .OrderBy(x=>x)\n                                                    .Select(x=>x.ToString())\n                                                    .ToList());\n}	0
2697804	2681878	Associate File Extension with Application	public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)\n    {\n        // The stuff that was above here is basically the same\n\n        // Delete the key instead of trying to change it\n        CurrentUser = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.ucs", true);\n        CurrentUser.DeleteSubKey("UserChoice", false);\n        CurrentUser.Close();\n\n        // Tell explorer the file association has been changed\n        SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);\n    }\n\n    [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]\n    public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);	0
31271952	31271781	injecting an generic interface	public class invoice_service<T> where T : class\n{\n   IInvoiceStorage<T> Storage;\n   public invoice_service(IInvoiceStorage<T> storage)\n   {\n     Storage=_storage;\n   }\n}	0
18644243	18644216	Indexer method in an interface	public interface Foo\n{\n    int this[int i] { get; set; }\n}	0
32631692	32631469	How to ignore if var is null c#	public void LinkBuilder(params string[] links)\n{\n    string completeLink = String.Join("&", links.Where(x=>!String.IsNullOrEmpty(x)));\n}	0
881430	881425	Html Agility Pack - Parsing <li>	List<string> facts = new List<string>();\nforeach (HtmlNode li in doc.DocumentNode.SelectNodes("//li")) {\n    facts.Add(li.InnerText);\n}	0
31950465	31950324	IOrderComparer unique ordering situation	[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]\npublic static extern int StrCmpLogicalW(string x, string y);	0
18996254	18995156	Delete XML node that contains a certain value	void Main()\n{   \n    XDocument xml = XDocument.Parse(@"<Stats>\n    <Status>\n        <Desc>something here</Desc>\n        <State>pending - ok</State>\n    </Status>\n    <Status>\n        <Desc>something here</Desc>\n        <State>failed</State>\n    </Status>\n</Stats>");\n\n    xml.Descendants("State").Where (x => x.Value.Contains("fail")).Ancestors("Status").Remove();\n    Console.WriteLine(xml.ToString());  \n}	0
10949128	10936738	How to access old entity value in ASP.NET Entity Framework	db.Users.Attach(user);\nvar current = db.Entry(user).CurrentValues.Clone();\ndb.Entry(user).Reload();\n//Do you user(from db) stuff\ndb.Entry(user).CurrentValues.SetValues(current);\ndb.Entry(user).State = EntityState.Modified;\ndb.SaveChanges();	0
7599497	7521696	Windows Workflow Custom Sequence Activity	using System.Activities;\nusing System.Activities.Statements;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\n\n[Designer("System.Activities.Core.Presentation.SequenceDesigner, System.Activities.Core.Presentation")]\npublic class MySeq : NativeActivity\n{\n    private Sequence innerSequence = new Sequence();\n\n    [Browsable(false)]\n    public Collection<Activity> Activities\n    {\n        get\n        {\n            return innerSequence.Activities;\n        }\n    }\n\n    [Browsable(false)]\n    public Collection<Variable> Variables\n    {\n        get\n        {\n            return innerSequence.Variables;\n        }\n    }\n\n    protected override void CacheMetadata(NativeActivityMetadata metadata)\n    {\n        metadata.AddImplementationChild(innerSequence);\n    }\n\n    protected override void Execute(NativeActivityContext context)\n    {\n        context.ScheduleActivity(innerSequence);\n    }\n\n}	0
21160683	21160514	Ask user to point a location in map Windows Phone	private void Map_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n {\n    GeoCoordinate asd = this.Map.ConvertViewportPointToGeoCoordinate(e.GetPosition(this.Map));\n}	0
5079938	5079607	DataGridView Cell Editing	private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)\n        {\n            this.dataGridView1.CellEnter += new DataGridViewCellEventHandler(myDataGrid_CellEnter);\n        }\n        void myDataGrid_CellEnter(object sender, DataGridViewCellEventArgs e)\n        {\n            if ((this.dataGridView1.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn) ||\n                (this.dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn))\n            {\n                this.dataGridView1.BeginEdit(false);\n            }\n        }	0
5566954	5566228	Remove all Artist node from an XML file	XmlDocument XDoc = new XmlDocument();\n    XDoc.Load(MapPath(@"~\xml\test.xml"));\n\n    XmlNodeList Nodes = XDoc.GetElementsByTagName("ARTIST");\n\n    foreach (XmlNode Node in Nodes)\n        Node.ParentNode.RemoveChild(Node);\n\n    XDoc.Save(MapPath(@"~\xml\test_out.xml"));	0
6998103	6998007	Get and Set Checkbox properties, using checkbox names as strings	((CheckBox)this.Controls["checkBox1"]).Checked = true;	0
8868974	8868664	How to find and modify a TextBox in some word document using Microsoft.Office.Interop.Word	void SearchTextBox(Word.Document oDoc,string name,string newContent)\n    {\n        foreach (Word.Shape shape in oDoc.Shapes)\n            if (shape.Name == name)\n            {\n                shape.TextFrame.ContainingRange.Text = newContent;\n                return;\n            }\n    }	0
1524941	1516752	How to map Type with Nhibernate (and Fluent NHibernate)	public class DataType\n{       \n    ...        \n    private string _typeOfContent;\n    public virtual Type TypeOfContent\n    {\n        get { return Type.GetType(_typeOfContent); }\n        set { _typeOfContent = value.FullName; }\n    }   \n}\n\n...\n\npublic class DataTypeMap : ClassMap<DataType>\n{\n    Map(x => x.TypeOfContent)\n       .Access.CamelCaseField(Prefix.Underscore)\n       .CustomType<string>();\n}	0
18668007	18667928	Export data DataGridView to Excel	private void exportToExcel_Click(object sender, EventArgs e)\n{\n\n    ExportToExcel ex = new ExportToExcel();\n    ex.dt = dtReport2; // set the public class variable here\n    ex.exportToExcel(); // removed the datagrid from your parameter in the exportToExcel() method\n}	0
3263014	3262970	C# web application file transfer	File.Copy	0
8674560	8668126	I have a program in C sharp, can I compile it as an executable for Linux server so that I can run it on the server without installing mono?	--static	0
20436869	20436768	Linq xml query with arguments	var nodes = doc.SelectNodes("//query/results/optionsChain/option[starts-with(@symbol, '--lookup value--')]/StrikePrice");	0
2301658	2298913	How can I make a control lose focus if the user clicks on something that's not focusable?	TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;\n    if (focusedTextBox == null)\n        return;\n\n    BindingExpression textBindingExpr = \n      focusedTextBox.GetBindingExpression(TextBox.TextProperty);\n    if (textBindingExpr == null)\n        return;\n\n    textBindingExpr.UpdateSource();	0
29315325	29315141	Writing random numbers to text file using c#	using System;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.IO;\nusing System.Text;\n\nnamespace UnitTestProject3\n{\n    [TestClass]\n    public class UnitTest1\n    {\n        [TestMethod]\n        public void TestMethod1()\n        {\n            int lowerRange = 1;\n            int upperRange = 10;\n            string filename = @"c:\\development\test.txt";\n            Random r = new Random();\n            int number = 0;\n\n            using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8))\n            {\n                for (int i = 1; i < 500; i++)\n                {\n                    number = r.Next(lowerRange, upperRange);\n\n                    writer.Write(number + ",");\n\n                }\n                writer.Flush();\n                writer.Close();\n            }\n\n        }\n    }\n}	0
1109846	1109839	How do you group by multiple columns in LINQ TO SQL?	group by new { item.Col1, item.Col2 }	0
24133821	24123416	Multiple calender in exchange web service	ExtendedPropertyDefinition PR_Folder_Path = new ExtendedPropertyDefinition(26293, MapiPropertyType.String);\n        PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);\n        psPropSet.Add(PR_Folder_Path);\n        FolderId rfRootFolderid = new FolderId(WellKnownFolderName.Root, mbMailboxname);\n        FolderView fvFolderView = new FolderView(1000);\n        fvFolderView.Traversal = FolderTraversal.Deep;\n        fvFolderView.PropertySet = psPropSet;\n        SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.FolderClass, "IPF.Appointment");\n        FindFoldersResults ffoldres = service.FindFolders(rfRootFolderid, sfSearchFilter, fvFolderView);\n        if (ffoldres.Folders.Count > 0) {\n            foreach (Folder fld in ffoldres.Folders) {\n                Console.WriteLine(fld.DisplayName);\n            }\n        }	0
1658759	1658731	How do I set the expectation of an event when calling a method?	var _mock = MockRepository.GenerateMock<ITimer>();\n_mock.Raise(x => x.Elapsed += null, this, EventArgs.Empty);	0
4299155	4299138	Generate N random and unique numbers within a range	{1, 2, 3, .... 50}	0
11932744	11932385	Is it possible to know if a JPEG image was rotated only from its raw bytes?	if(img.Height == img.Width)\n  return MyAspectEnum.Square;\nif(img.Height > img.Width)\n  return MyAspectEnum.Portrait;\nreturn MyAspectEnum.Landscape;	0
28231250	28230523	Preventing GridView from adding redundant rows	foreach (DataGridViewRow row in form1.dataGridView1.SelectedRows)\n        {\n            bool isnotexist = true;\n            foreach (DataGridViewRow rowgrid2 in dataGridView2.Rows)\n            {\n                if (rowgrid2.Cells[0].Value.ToString() == row.Cells[0].Value.ToString())\n                {\n                    isnotexist = false;\n                    break;\n                }\n            }\n            if (isnotexist)\n            {\n                int index = dataGridView2.Rows.Add(row.Clone() as DataGridViewRow);\n                foreach (DataGridViewCell cell in row.Cells)\n                {\n                    dataGridView2.Rows[index].Cells[cell.ColumnIndex].Value = cell.Value;\n                }\n            }\n        }	0
2318240	1648444	Silverlight plugin to Determine Page Height?	private void Page_SizeChanged(object sender, SizeChangedEventArgs e)\n    {\n        BrowserInformation oInfo = System.Windows.Browser.HtmlPage.BrowserInformation;\n\n        double nHeight=0;\n        if (oInfo.Name.ToLower().Contains("explorer"))\n        {\n            nHeight = (double)HtmlPage.Document.DocumentElement.GetProperty("clientHeight");\n        }\n        else if (oInfo.Name.ToLower().Contains("netscape"))\n        {\n            nHeight = (double)HtmlPage.Window.GetProperty("innerHeight");\n        }\n\n\n        if ((e.NewSize.Height + 160) > nHeight)\n        {\n            HtmlPage.Document.Body.SetStyleAttribute("height", (e.NewSize.Height + 160) + "px");\n        }\n        else\n        {\n            HtmlPage.Document.Body.RemoveAttribute("style");\n        }\n    }	0
14820039	14819426	How to create Hyperlink in MessageBox.show?	if (MessageBox.Show(\n        "test", "Visit", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk\n    ) == DialogResult.Yes)\n{\n    System.Diagnostics.Process.Start("http://www.google.com");\n}	0
9948731	9948631	Is there a more efficient method for omitting for loop instances	for (int i = 0; i < n; i++) \n    { \n        val += DoWork(i); \n    } \n    val -= DoWork(i/2);\n    val -= DoWork(i/3);\n    val -= DoWork(i/4);	0
13130242	13130213	How do I return a dictionary from a grouping operation with the grouping factor as the key?	var query = skuStoreStockLevel.GroupBy(x => x.Item1)\n            .ToDictionary(\n                 g => g.Key,\n                 g => g.Aggregate(new StringBuilder(),\n                                     (sb, x) => sb.AppendFormat("|{0},{1},{2}", x.Item1, x.Item2, x.Item3),\n                                     (sb) => sb.ToString()));	0
28663421	28656656	Getting the File Path from a FileUpload dialog in ASP.NET throws FileNotFound Exception	CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");\n// Create or overwrite the "myblob" blob with contents from a local file.\nblockBlob.UploadFromStream(imageUploader.PostedFile.InputStream);	0
13938843	13930460	C# ListView Label Edit - control selected text	private void listView1_BeforeLabelEdit(object sender, LabelEditEventArgs e)\n{\n    IntPtr editWnd = IntPtr.Zero;\n    editWnd = SendMessage(listView1.Handle, LVM_GETEDITCONTROL, 0, IntPtr.Zero);\n    int textLen = Path.GetFileNameWithoutExtension(listView1.Items[e.Item].Text).Length;\n    SendMessage(editWnd, EM_SETSEL, 0, (IntPtr) textLen);\n}\n\npublic const int EM_SETSEL = 0xB1;\npublic const int LVM_FIRST = 0x1000;\npublic const int LVM_GETEDITCONTROL = (LVM_FIRST + 24);\n\n[DllImport("user32.dll", CharSet = CharSet.Ansi)]\npublic static extern IntPtr SendMessage(IntPtr hWnd, int msg, int len, IntPtr order);	0
15681633	15681338	String was not recognized as a valid DateTime ParseExact Error	DateTime PushinValue = DateTime.Parse(dataRow[0].ToString());\n    String myTime = PushinValue.ToString("HH:mm");	0
15830172	15830062	get only integer value from string	string test = "GS190PA47";\nRegex r = new Regex(@"\d+$");\nvar m = r.Match(test);\n\nif(m.Success == false)\n    Console.WriteLine("Ending digits not found");\nelse\n    Console.WriteLine(m.ToString());	0
7807173	7793340	how to convert regex code in C# to c++	struct MatchInfo\n{\n    string value;\n    int index;\n    int length;\n};\n\nvector<MatchInfo> DoRegex(string data, string pattern)\n{\n    regex patternRegex(pattern);\n    sregex_token_iterator end;\n    vector<MatchInfo> result;\n\n    for (sregex_token_iterator i(data.begin(), data.end(), patternRegex); i != end; ++i)\n    {\n        MatchInfo item;\n\n        item.index = i->first - data.begin();\n        item.length = i->length();\n        item.value = i->str();\n\n        result.push_back(item);\n    }\n\n    return result;\n}	0
31856689	31761322	Split DataTable into multiple DataTables based on column C#	private static DataTable SplitDataTableModule(DataTable d1)\n    {\n\n        DataTable dataTable1;\n        dataTable1 = d1.Copy();\n        dataTable1.Columns.RemoveAt(0); // remove student_no\n        dataTable1.Columns.RemoveAt(1); // remove student surname\n        dataTable1.Columns.RemoveAt(2); // remove student firstname\n        dataTable1.Columns.RemoveAt(5); // remove staff_no\n        dataTable1.Columns.RemoveAt(6); // remove staff surname\n        dataTable1.Columns.RemoveAt(7); // remove staff firstname\n\n        return d1;\n    }	0
26148606	26148271	How to disable appearing of ToolTip text over ToolStripButton?	btn.AutoToolTip = false;\nbtn.ToolTipText = string.empty;	0
4871646	4871601	WPF - Button click on selection within a limited time interval?	var peer = new ButtonAutomationPeer(someButton);\nvar invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;\n\ninvokeProv.Invoke();	0
2336687	2336616	Removing dynamically created controls	phAuto.Controls.Clear();\nphModel.Controls.Clear();\nphMiles.Controls.Clear();\nphVINumber.Controls.Clear();\nphPlateNumber.Controls.Clear();	0
5149369	4624860	Event for TextBox Value Not Matched with any Value in AutoCompleteDataSource	textBox1.Validated += new EventHandler(textBox1_Validated);\n\nvoid textBox1_Validated(object sender, EventArgs e)\n{\n    if(GetAutoCompleteStringCollection().Contains(textBox1.Text) == false )\n    {\n        // Do your Add-New-Item option\n    }\n}	0
11211504	11209852	Cannot Deserialize XmlArray with Namespace	public class MovieRunTimes\n{\n    [XmlElement("ShowDate")]\n    public string ShowDate { get; set; }\n\n    [XmlElement("TicketURI")]\n    public string TicketUri { get; set; }\n\n    [XmlArray("ShowTimesByDate")]\n    [XmlArrayItem(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]\n    public List<string> ShowTimesByDate { get; set; }\n\n}	0
8980111	8979633	Doing a range lookup in C# - how to implement PART DEUX	public static int LookUpTable<TRange, TValue>(IList<TRange> ranges, TValue value, IRangeComparer<TRange, TValue> comparer)\n    where TRange : Range<TValue> // Specify what you know about TRange and TValue\n    where TValue : IComparable<TValue>\n{\n    int indexToTable = BinarySearch(ranges, value, comparer);\n    TRange lookUp = ranges[indexToTable]; // lookUp is TRange, not Range<TRange>\n    return lookUp.Value;\n}	0
9807677	9804209	Will a C# library for the xbox kinect work for the windows kinect SDK?	Kinect for Windows SDK version 1	0
18240642	18240584	Display All MessageBox in Program with TimeStamp method	private void ShowMessage(string message)\n{\n    MessageBox.Show(message + " " + DateTime.Now.ToString());\n}	0
15113404	15113366	How do I convert this string to a DateTime?	Int64 timestamp = Convert.ToInt64("1319556419");\nDateTime newDate = new DateTime(1970,1,1).AddSeconds(timestamp);	0
4470165	4470154	Querying AD for finding all groups of a user - Missing one group	/Tools/DirectoryServices/	0
25010342	24999014	How to prevent nuget from reverting to older versions of dependent packages when updating a package	Update-Package web.CMS -version 6.5.0-develop-140728152 -IgnoreDependencies	0
26205253	26205200	Adding a animal/dog/cat to a animal list results in NullReferenceException?	public AdministrationForm()\n{\n    InitializeComponent();\n    animalTypeComboBox.SelectedIndex = 0;\n    animal = null;\n    admin= new Administration();\n}	0
14968151	14968001	Xml Serialize float value	static CultureInfo ci = CultureInfo.InvariantCulture;\nfloat _TotalInclTax = 0;\n\n[XmlIgnore]\npublic float TotalInclTax \n{\n    get { return _TotalInclTax ; }\n    set { _TotalInclTax  = value; }\n}\n\n[XmlElement("TotalInclTax")]\npublic string CustomTotalInclTax\n{\n    get { return TotalInclTax.ToString("#0.00", ci); }\n    set { float.TryParse(value, NumberStyles.Float, ci, out _TotalInclTax); }\n}	0
6807439	6807108	C# - Using foreach to loop through method arguments	using System;\nusing System.Data;\nusing System.Reflection;\nusing PostSharp.Aspects;\n\nnamespace TestAOP\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            SomeClass someInstance = new SomeClass();\n            someInstance.test(null, null, null, null);\n        }\n    }\n\n\n    public class SomeClass\n    {\n        [CheckForNulls]\n        public void test(string arg1, string arg2, object arg3, DataTable arg4)\n        {           \n            // do the rest...\n        }\n    }\n    [Serializable]\n    public class CheckForNullsAttribute : OnMethodBoundaryAspect\n    {\n        public override void OnEntry(MethodExecutionArgs args)\n        {\n            ParameterInfo[] parameters = args.Method.GetParameters();            \n            for (int i = 0; i < args.Arguments.Count; i++)\n            {\n                if (args.Arguments[i] == null)\n                    throw new ArgumentNullException(parameters[i].Name);\n            }\n        }\n    }\n}	0
12112885	12112687	How to get content via xpath	HtmlWeb hwObject = new HtmlWeb();\nHtmlDocument htmldocObject = hwObject.Load("http://whois.domaintools.com/94.100.179.159");\nforeach (HtmlNode link in htmldocObject.DocumentNode.SelectNodes("//meta"))\n{\n    Console.WriteLine("-META-");\n    var attribDump=link.Attributes.Select(a=>a.Name+" : "+a.Value);\n    foreach (var x in attribDump)\n    {\n        Console.WriteLine(x);\n    }\n}	0
34324768	34324718	How to generate all combinations with replacement using recursive yield? C#	private static IEnumerable<IEnumerable<T>> GetCombinations<T>(IList<T> list, int length)\n{\n    var numberOfCombinations = (long)Math.Pow(list.Count, length);\n    for(long i = 0; i < numberOfCombinations; i++)\n    {\n        yield return BuildCombination(list, length, i);\n    }\n}\nprivate static IEnumerable<T> BuildCombination<T>(\n    IList<T> list, \n    int length, \n    long combinationNumber)\n{\n    var temp = combinationNumber;\n    for(int j = 0; j < length; j++)\n    {\n        yield return list[(int)(temp % list.Count)];\n        temp /= list.Count;\n    }\n}	0
3317474	3317425	How to get the generic type T as object declared in a function C#	Type theType = typeof(T);\nobject obj = Activator.CreateInstance(theType);	0
6501233	6500663	How to Control Buttons via Numpad Keys in Winform?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n        {       \n           if (keyData == Keys.Numpad0)\n                {\n                    Numpad0.PerformClick();\n                    return true;\n                }\n\n            return base.ProcessCmdKey(ref msg, keyData);\n        }	0
2299055	2299037	Abstract constructor in C#	public abstract class Foo\n{\n     public string Name { get; private set; }\n\n     protected Foo( string name )\n     {\n         this.Name = name;\n     }\n}\n\npublic class Bar : Foo\n{\n     public Bar() : base("bar")\n     {\n        ...\n     }\n}	0
13102656	13102436	How to get input from a webservice	public decimal GetTotalCostForAnOrder(int OrderID)\n{\n    XElement doc=XElement.Load("c:\\yourXML.xml");\n    decimal totalPrice=doc.DescendantsAndSelf("Order")\n    .Where(x=>x.Attribute("id").Value==OrderID)\n    .Select(y=>y.Element("Items")).Elements("Item")\n    .Select(z=>decimal.Parse(z.Element("TotalCost").Value)).ToList().Sum();\n    return totalPrice;\n}	0
15775837	14226353	NLog FileTarget wrapped with BufferingTargetWrapper fails to write log if there is a delay	LogManager.Flush()	0
21552606	21524717	How to correctly perform redirections in ASP.NET with WebformsMVP Framework?	public interface IAddToCartView : IView\n{\n    event Action DoPurchase;\n    event Action DoAddToWishList;\n    event Action RedirectToWishListPage; \n    ...\n}	0
7211544	7211446	Overloading .Where extension with IQueryable<T> implementation	IQueryable<T>	0
33335157	33333261	Using Two Views and switch between Views	public class MainViewModel\n{\n    private ViewModel1 _viewModel1 = new ViewModel1();\n    private ViewModel2 _viewModel2 = new ViewModel2();\n\n    public MainViewModel()\n    {\n        //event from ViewModel1 \n        _viewModel1.SwitchViewModel2Request += NavigateToView2;\n    }\n\n    //switch View to ViewModel2\n    private void NavigateToView2(object sender, EventArgs e)\n    {\n        CurrentViewModel = _viewModel2;\n    }\n}\npublic class ViewModel1\n{\n    public ViewModel1()\n    {\n        ButtonOnViewModel1Command = new RelayCommand(Button1Method);\n    }  \n    //some button on child view 1\n    public RelayCommand ButtonOnViewModel1Command { get; set; }\n\n\n    private void Button1Method(object obj)\n    {\n        OnSwitchViewModel2Request();\n    }\n\n    //event that MainViewModel will subscribe to\n    public event EventHandler SwitchViewModel2Request = delegate { };\n    private void OnSwitchViewModel2Request()\n    {\n        SwitchViewModel2Request(this, EventArgs.Empty);\n    }\n}	0
8918254	8918034	Workflow Activity - Save Workflow Activity Name to a variable using the 'Assign' activity	this.activity.displayName	0
1345620	1340670	Subsonic 3 and Linq Group by with Count	var results = from d in _db.Bills\n      group d by d.CustomerId into g\n      select new\n      {\n      CustomerId = g.Key,\n      NoOfBills = g.Count()\n      };\n\nvar results2 = from c in _db.Customers\n       join r in results on c.Id equals r.CustomerId\n       select new\n       {\n       CustomerId = r.CustomerId,\n       CustomerName = c.Name,\n       City = c.City,\n       NoOfBills = r.NoOfBills\n       };	0
15720883	15719711	C# recursively go through items in a List of T where T has a List of T	Stack stack;\nstack.Push(root folder);\nwhile (stack.Count > 0)\n{\n    Folder f = stack.Pop();\n    foreach (Folder subf in f in reverse order)\n        stack.Push(subf);\n}	0
8406916	8406877	ObjectQuery to return object where a child object contains a set value	Routes.Where(x =>x.Flights.Any(p=> p.Airline == airline))	0
15128907	15128861	How to initialize this dictionary	var dic = new Dictionary<string, TimeSpan>()\n          {\n                {"1  Hour", TimeSpan.FromHours(1)},\n                {"Two days", TimeSpan.FromDays(2)}\n          };	0
33763599	33763442	c# null value after deserialize	ref BitCurex_PRV_Ofers B)	0
5842324	5842291	How to know when a button is clicked in form1 but know in form2 C#	// code in form1 might look something like\n\npublic void SubscribeToEvents()\n{\n   // get Form2 reference\n   var form2 = GetForm2Reference();\n   form2.Button.Click += ButtonOnForm2EventHandler;\n}\n\npublic void ButtonOnForm2EventHandler(object sender, EventHandlerArgs e)\n{\n   // some code\n}	0
12038684	12037843	Encrypt AES cipher in CCM with Bouncy Castle in C#	var iv = "7B13E1A17861356401A3C15F4F0525".ToByteArray();	0
9344094	9344076	How to Assign Members of Generic Type in the Constructor of a Generic Type?	public class GeneralWrapper<T> where T : class, new()\n{\n    public GeneralWrapper()\n    {\n       Datas = new T();\n    }\n\n    public T Datas { get; set; }\n}	0
9522690	9522464	Transferring parsed strings to sql server database	String insertQuery = "INSERT INTO TABLENAME (Col1, Col2, Col3...) VALUES (";\n//This is also assuming that your data is in the same order as the columns\nint isFirstLoop = true\nforeach(string word in result)\n{\n    if(!isFirstLoop)\n        insertQuery += ","\n    insertQuery += word;\n    isFirstLoop = false;        \n}\ninsertQuery += ")";\nSqlDataSource.InsertCommand = insertQuery;	0
454896	432100	Dynamic Proxy generation with LinFu	// The interceptor class must implement the IInterceptor interface\nvar yourInterceptor = new YourInterceptor();\nvar proxyFactory = new ProxyFactory();\nIYourInterface proxy = proxyFactory.CreateProxy<IYourInterface>(yourInterceptor);\n// Do something useful with the proxy here...	0
1051568	1051522	Sort of scheduler	Timer aTimer = new System.Threading.Timer(MyTask, null, 0, 10000);\n\nstatic void MyTask(object state)\n{\n  ...\n}	0
28521137	28219361	How to check if an azure active directory user is already in an approle	IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();\n            IAppRoleAssignment a = null;\n            a = assignments.Where(ara => ara.Id.Equals(appRole.Id)).First();\n            if (a != null)\n                Console.WriteLine("Found assignment {0} for user {1}", appRole.Id, user.DisplayName);	0
15250156	15249520	Ultrawingrid - Select row based on unique value	int index;\n            foreach (UltraGridRow row in grid.Rows)\n            {\n                if (Convert.ToInt32(row.Cells["ID"].Value) == index)\n                {\n                    grid.ActiveRow = row;\n                    break;\n                }\n            }	0
1660159	1660087	How to kill a process in Windows Mobile?	Process process Process.GetProcessById(processId);\nprocess.Kill();	0
3011773	3011693	c# winforms - scrollable panel with rectangles	panel1.AutoScrollMinSize = new Size (400, 400)	0
4308060	4308009	EF query with conditions from multiple tables	var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 && \n                                    x.DepartmentName == "ABC" &&\n                                    x.Tasks.Any(t => t.BudgetHours > 120))\n                        .Select (x => x.EmployeeID);	0
16138113	16138048	If x of y values are equivalent	bool match = array.GroupBy(n => n).Any(g => g.Count() >= 3);	0
651338	651283	Reflection & Application Design	Assembly.GetType	0
22131727	22131622	Confused in getting nested elements and values via XmlDocument	foreach (XmlElement element in doc.SelectNodes("//account/systemInfo/ramInfo/ramStick"))\n{\n    string partNumber = element["partNumber"].InnerText;\n}	0
28722057	28721749	How can a C# XSLT extension function return an XML fragment that gets used as unescaped XML?	private XPathNavigator GetFragment(string input)\n{\n  var settings = new XmlReaderSettings()\n  {\n    ConformanceLevel = ConformanceLevel.Fragment\n  };\n\n  var doc = new XPathDocument(XmlReader.Create(new StringReader(input), settings));\n  return doc.CreateNavigator();\n}	0
18856325	18837730	Crystal Report how to sum columns group by date	where datediff(day,@date1,weldingdate) >= 0\n  and datediff(day,weldingdate,@date2) >= 0	0
23127152	23126969	Set taskbar icon of top level usercontrol (Winforms)	Icon icon = this.Icon;\n        if (icon != null && this.TaskbarOwner.Handle != IntPtr.Zero)\n        {\n            UnsafeNativeMethods.SendMessage(this.TaskbarOwner, 128, 1, icon.Handle);\n        }	0
263635	263586	What is the best way of implementing a stack of more than one type of object in C#?	StackEntry { protected virtual void PostPop(); }\nReturn : StackEntry { protected override void PostPop(); }\nBacktrack : StackEntry { protected override void PostPop(); }	0
8692398	8685705	Create sequence consisting of multiple property values	void Main()\n{\n    var list = new List<Tuple<string, string>>\n        { Tuple.Create("dog", "cat"), Tuple.Create("fish", "frog") };\n\n        foreach (var element in GetSingleList(list))\n        {\n            Console.WriteLine (element);\n        }\n}\n\n// A reusable extension method would be a better approach.\nIEnumerable<T> GetSingleList<T>(IEnumerable<Tuple<T,T>> list) {\n\n    foreach (var element in list)\n    {\n        yield return element.Item1;\n        yield return element.Item2;\n    }\n\n}	0
13605536	13602082	C# combobox displays wrong values	OracleDataReader dr;\n        OracleConnection conn = new OracleConnection();\n        conn.ConnectionString = "....string....";\n        string query = "SELECT distinct dd.delivery_bay_code FROM dc_delivery dd, dc_grv dg WHERE delivery_complete_datetime is null AND dd.dc_delivery_id_no = dg.dc_delivery_id_no";\n        OracleCommand cmd = new OracleCommand(query, conn);\n        conn.Open();\n        dr = cmd.ExecuteReader();\n        while(dr.Read())\n        {\n            if (dr[0].ToString().Length > 2)\n                cbDelivery.Items.Add(dr[0].ToString());\n        }\n        conn.Close();	0
9633716	9630205	Uploading video on webserver through POST method in WP7	byte[] data;\nusing (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())\n{\n    using (IsolatedStorageFileStream stream = storage.OpenFile("MyVideo.wmv", FileMode.Open))\n    {\n        data = new byte[stream.Length];\n        stream.Read(data, 0, (int)stream.Length);\n    }\n}\n\nrequest.AddFile("video", data, "MyVideo.wmv");	0
23921690	23920450	Nullable comparisons in expression trees	private static Expression<Func<T, bool>> constructPredicate<T>(SelectionCriteria selectionCriteria)\n{\n    var predicate = PredicateBuilderEx.True<T>();\n    var foo = PredicateBuilder.True<T>();\n\n    foreach (var item in selectionCriteria.andList)\n    {\n        var fieldName = item.fieldName;\n        var fieldValue = item.fieldValue;\n\n        var parameter = Expression.Parameter(typeof (T), "t");\n        var property = Expression.Property(parameter, fieldName);\n        var value = Expression.Constant(fieldValue);\n        var converted = Expression.Convert(value, property.Type);\n\n        var comparison = Expression.Equal(property, converted);\n        var lambda = Expression.Lambda<Func<T, bool>>(comparison, parameter);\n\n        predicate = PredicateBuilderEx.And(predicate, lambda);\n    }\n\n    return predicate;\n}	0
20629566	20629547	How to save datatable first column in array C#	datatable1.AsEnumerable().Select(r => r.Field<string>("Name")).ToArray();	0
24968125	24925943	Attaching an existing method to a dynamic assembly instead of generating IL for it	var queue = new Queue<Expression>();\nvar arguments = Expression.Parameter(typeof(string []), "args");\n\nqueue.Enqueue(Expression.Call(typeof(Console).GetMethod("WriteLine", new Type [] { })));\n\nvar block = Expression.Block(queue);\nvar lambda = Expression.Lambda<Func<string [], int>>(block, new ParameterExpression [] { arguments });\n\nlambda.CompileToMethod(builderMethod);\n// builderMethod is a MethodBuilder instance created earlier.	0
6013017	6012874	Compare two lists that contain a lot of objects (2th part)	public int GetHashCode(MyFile a)\n{\n    int rt = ((a.compareName.GetHashCode() * 251 + a.size.GetHashCode())\n                          * 251 + a.deepness.GetHashCode()) *251;\n\n    return rt;\n\n}	0
32766144	32765435	Simple Injector - Register Compared to Bind in Ninject	container.RegisterCollection(typeof(MyFactory), Assembly.GetExecutingAssembly());\n\nvar namespaceTypes =\n    from type in Assembly.GetExecutingAssembly().GetTypes()\n    where type.Namespace == typeof(MyClass).Namespace\n    select type;\n\nforeach (Type type in namespaceTypes)\n    container.Register(type, type, Lifestyle.Singleton);	0
23800896	23800843	How to Check Server is accepting connections	TcpClient tcpClient = new TcpClient();\n      try\n           {\n                tcpClient.Connect("152.26.53.39", 2775);\n                Console.WriteLine("Port 2775 Open");\n            }\n      catch (Exception){\n\n               Console.WriteLine("Port 2775 Closed");\n       }	0
22963093	22911993	How can I get the port by websites name via C# from IIS?	var site = lServerManager.Sites[lWebsite];\nforeach (var binding in site.Bindings)\n{\n    int port = binding.EndPoint.Port;\n    // Now you have this binding's port, and can do whatever you want with it.\n}	0
12840600	12837824	WPF DataGrid style cells based on index	int c = myDataTable.Rows.Count;\nmyDataGrid.AutoGeneratedColumns += (s, e) =>\n{\n   myDataGrid.Columns[myDataGrid.Columns.Count - 1].CellStyle = this.Resources["myCellStyle"] as Style;\n   myDataGrid.Columns[0].CellStyle = this.Resources["myCellStyle"] as Style;\n};\nmyDataGrid.LoadingRow += (s, e) =>\n{\n   int x = e.Row.GetIndex();\n   if (c - 1 == x) e.Row.Style = this.Resources["myRowStyle"] as Style;\n};	0
29011291	25524227	Update only certain columns in DB using Entity Framework	_context.Configuration.ValidateOnSaveEnabled = false;	0
31192534	31191878	Change enum's displayed value in DataGridView	private void  dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (dataGridView1.Columns[e.ColumnIndex].name=="MyEnumColumnName")\n    { \n       MyEnumType enumValue = (MyEnumType)e.value ;\n       string enumstring = ... ; // convert here the enum to displayed string \n       e.Value = enumstring ;\n     }\n}	0
19871032	19870939	How to stop exception	do {\n    String text = Interaction.InputBox("Enter a number");\n    if( text == "" ) return -1;\n    Int32 number;\n    if( Int32.TryParse( text, out number ) ) return number;\n} while( true );	0
20452753	20452612	Multiple Regex Replace, does it create multiple strings?	string[] corr = {"[5|S]", "[6|G]", "[8|B]", "[4|A]", "[1|I]", "[0|O]"};\n\nRegex reg = new Regex(@"([5S])|([6G])|([8B])|([4A])|([1I])|([0O])");\n\nvar AllVariants = reg.Replace(s, delegate(Match m) {\n    for (int key = 0; key < corr.Length; ++key)\n        if (string.IsNullOrEmpty(m.Groups[key+1].Value) == false) break;\n    return corr[key];\n});	0
4666391	4666229	How to retrieve data from a dialog box?	foreach(var item in vars)\n{\n    Variables.Add((Variable)item.Clone());\n}	0
33628857	33628690	Getting char * from C++ DLL to C# application	int size = 256;\nStringBuilder buffer = new StringBuilder(256);\nfr = info(5, buffer, ref size);	0
2835549	2835396	Enterprise library Rewriting the Code to Save data and return value	int result = 0;\n\nDatabase db = EnterpriseLibraryContainer.Current.GetInstance<Database>("YourDb");\nDbCommand myCommand = db.GetStoredProcCommand("SaveUser");\ndb.AddInParameter(myCommand, "location", DbType.String, objUser.Location);\ndb.ExecuteNonQuery(myCommand);\nresult = Convert.ToInt32(db.GetParameterValue(myCommand, "returnValue"));	0
14888886	14888712	How to display values entered via a TextBox in a GridView on button-click without saving the data to the database?	protected void Page_Load(object sender, EventArgs e)\n{\n        dt = new DataTable();\n        DataColumn dc1 = new DataColumn("FIRST NAME");\n        DataColumn dc2 = new DataColumn("LAST NAME");\n        dt.Columns.Add(dc1);\n        dt.Columns.Add(dc2);\n        DataRow dr1 = dt.NewRow();\n        GridView1.DataSource = dt;\n        GridView1.DataBind();\n}\nDataTable dt;\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    DataRow dr1 = dt.NewRow();\n    dr1[0] = TextBox1.Text;\n    dr1[1] = TextBox2.Text;\n    dt.Rows.Add(dr1); \n    GridView1.DataSource = dt;\n    GridView1.DataBind();\n}	0
22564241	22555222	Change webapi controller action parameter in delegatinghandler	public class ValuesController : ApiController\n{\n    [CustomActionFilter]\n    public string GetAll(string username)\n    {\n        return username;\n    }\n}\n\npublic class CustomActionFilter : ActionFilterAttribute\n{\n    public override void OnActionExecuting(HttpActionContext actionContext)\n    {\n        object obj = null;\n        if(actionContext.ActionArguments.TryGetValue("username", out obj))\n        {\n            string originalUserName = (string)obj;\n\n            actionContext.ActionArguments["username"] = "modified-username";\n        }\n    }\n}	0
22006560	22006500	How to retrieve a columns values using LINQ in C#?	ProductDBContext.Products.Select(p => Product_Name);	0
9319485	9314726	Render Razor View as string resulted in extra formatting tags (tabs, line-breaks)? How to remove?	public virtual ActionResult RenderToString()\n{\n    string html = RenderRazorViewToString(MVC.Markets.Views._RenderToString);\n    html = new StringBuilder(html)\n        .Replace("\n","")\n        .Replace("\r","")\n        .Replace("\t","")\n        .ToString();\n    return Json(new { html = html }, JsonRequestBehavior.AllowGet);\n}	0
12804509	12804437	Windows Store App - how to get watermark in Search Charm textbox	protected override async void OnWindowCreated(WindowCreatedEventArgs args)\n    {\n        SearchPane sp = SearchPane.GetForCurrentView();\n        sp.PlaceholderText = "Enter the name of a town or city";\n    }	0
31937161	31936154	Get Screen Resolution in Win10 UWP App	var bounds = ApplicationView.GetForCurrentView().VisibleBounds;\nvar scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;\nvar size = new Size(bounds.Width*scaleFactor, bounds.Height*scaleFactor);	0
23907446	23906306	LINQ Expression - Dynamic From & Where Clause	public IEnumerable<IEnumerable<T>> Permutation<T>(int count, IEnumerable<T> sequence)\n    {\n        if(count == 1)\n        {\n            foreach(var i in sequence)\n            {\n                yield return new [] { i };\n            }\n            yield break;\n        }\n\n\n        foreach(var inner in Permutation(count - 1, sequence))\n        foreach(var i in sequence)\n        {\n            yield return inner.Concat(new [] { i });\n        }        \n    }\n\nvar foo = Permutation<int>(3, numList.Where(x => x > 10));	0
9000516	9000479	Equivalent of #region for C++	// pragma_directives_region.cpp\n#pragma region Region_1\nvoid Test() {}\nvoid Test2() {}\nvoid Test3() {}\n#pragma endregion Region_1\n\nint main() {}	0
10704915	10704812	Comparing two hashsets	var content = File.ReadLines("textFile1.txt").Select(line => \n{\n    var parts = line.Split('/');\n    return new \n    { \n        Name = parts[0],\n        Content = parts[1]\n    };\n});\n\nHashSet<string> names = new HashSet<string>(content.Select(c=> c.Name));\nHashSet<string> txt2 = new HashSet<string>(File.ReadLines("textFile2.txt"));\nvar uniques = txt2.Where(line => !names.Contains(line.Split('/')[0]));	0
19448290	19448102	dynamically adding buttons and button objects in panel	private void button1_Click(object sender, EventArgs e)\n    {\n        panel1.Controls.Clear();\n        string a = textBox1.Text;\n        int h = Convert.ToInt32(a);\n\n        for (int i = 0; i <= h; i++)\n        { \n            var btn = new Button {Size = new Size(60, 23), Dock=DockStyle.Left, Text=h.ToString() };\n            btn.Click+= delegate(object sender, EventArgs e)  { //your commands }; \n            panel1.Controls.Add(btn);\n        }\n    }	0
11429699	11429459	Facebook App Canvas Resize	FB.Canvas.setSize({ width: 640, height: 480 });	0
19484114	19484107	Remove duplicates in a collection	var somelist = new List<double>{2, 2, 3}.Distinct();\n\n// somelist now contains 2, 3	0
25494497	25494454	xsd.exe is generating XML with "item" prepended to enumerations	enum Test\n{\n    00,\n    01,\n    //etc.\n}	0
9299297	9299153	get the values larger than zero only	protected void gridview_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)\n        {\n            //look at the value of the days column and use e.Row.Style["Display"] = "none"; to hide it.\n        }\n    }	0
30503218	30503020	Combining two LINQ statments into one	var resorts = from r in db.WRESORT \n              where (country != null && r.COUNTRY == country) ||\n                    (country == null && new[] { "AUSTRIA", "FRANCE", "ITALY" }.Contains(r.COUNTRY))	0
24137594	24136006	How to get the button text of dynamically created button in Windows Phone 8 C#	Button button = sender as Button;\nstring buttonText = button.Text;	0
31878726	31874126	How to use dataview to check same Value	var duplicateValues = (from row in dt.AsEnumerable()\n                   orderby row.Field<string>("Id")\n                   select new DuplicateObject\n                   {\n                       Id = row.Field<string>("Id"),\n                       Name = row.Field<string>("Name"),\n                       Skill = row.Field<string>("Skill")\n                   }).Distinct(new DuplicateObjectComparer()).ToList();\n\nstring dupValue = string.Empty;\n\nforeach (var dup in duplicateValues)\n{\ndupValue = dup.Id + " - " + dup.Name + " - " + dup.Skill;\nConsole.WriteLine("Duplicate entry:" + dupValue);\n}\n\nif (duplicateValues.Count == 0)\nConsole.WriteLine("No duplicate entry");\n// Supporting classes\n// Gives a strongly type class from the Linq query    \npublic class DuplicateObject\n{\n  public string Id { get; set; }\n  public string Name { get; set; }\n  public string Skill { get; set; }\n}	0
18756974	18756538	Check Whether Time Falls between Two Time Values in c#	if (start < end) return start < desired AND desired < end\n else return desired < end OR start < desired	0
11478637	11478594	How to add am/pm to datetime	model.ScheduledHour + (model.AmPm == "AM" ? 0 : 12);	0
14114721	14114695	Remove HTML Encoded characters	&[a-z]+;	0
31467536	31467422	can a BackgroundWorker object in c# be ran without a Windows Forms?	using System.Threading;\n\n     // creating new thread and pass it the delegate to run it \n\n    Thread thread = new Thread(new ThreadStart(WorkThreadFunction));\n    // this command to start the thread\n    thread.Start();\n\n    public void WorkThreadFunction()\n    {\n\n        // do any background work\n\n    }	0
11016838	11016409	How to get a control reference from .ascx on a .aspx page?	public static Control FindControlRecursive(Control container, string name)\n{\n    if ((container.ID != null) && (container.ID.Equals(name)))\n        return container;\n\n    foreach (Control ctrl in container.Controls)\n    {\n        Control foundCtrl = FindControlRecursive(ctrl, name);\n        if (foundCtrl != null)\n            return foundCtrl;\n    }\n    return null;\n}	0
19084730	19083008	How can I get my character to aim correctly?	Quaternion yQuaternion = Quaternion.AngleAxis(-rotationY, axisObj.right);	0
20174351	20174245	Set my paragrpah to be write right to left	Paragraph p = doc.InsertParagraph(subject);\n        p.Direction=Direction.RightToLeft;	0
34005694	34005539	Comparing two variable in a structure C#	for (int i = 0; i < length; i++)\n{\n    for (int j = 0; j < length; j++)\n    {\n        if (i == j) continue;\n\n        if (players[i].number == players[j].number)\n        {\n            Console.WriteLine("Same");\n            Console.ReadLine();\n        }\n        else\n        {\n            Console.WriteLine("Not");\n            Console.ReadLine();\n        }\n    }	0
2686582	2686497	Get groups of 4 elements from name value list using LINQ in C#	var abc = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };\n\nvar xyz = abc.Select((e, i) => new { Item = e, Grouping = (i / 4) }).GroupBy(e => e.Grouping);	0
8474255	8474225	How to combine string[] to string with spaces in between	String.Join(" ", array)	0
17439325	17439302	Lambda expression in Java?	final Array<Integer> a = array(1, 2, 3);  \nfinal Array<Integer> b = a.map({int i => i + 42});  \narrayShow(intShow).println(b); // {43,44,45}	0
13830971	13830738	How do I parallelise this with or without PLINQ?	data.AsParallel().ForAll(row =>\n        {\n            Process(row);\n        });\n\n        Parallel.For(0, data.Length, rowIndex =>\n        {\n            Process(data[rowIndex]);\n        });	0
7681409	7666264	How to copy a Azure blob file to Azure local storage	CloudStorageAccount.Parse(...).CreateCloudBlobClient().GetBlobReference("path/of/blob").DownloadFile(RoleEnvironment.GetLocalResource("nameOfLocalResource").RootPath);	0
18127271	18127155	GetHashCode for similar values	public int hashCode() {    // Assuming year and category are String like name.\n    int hash = 31;\n    hash = hash * 331 + (this.year != null ? this.year.GethashCode() : 0);\n    hash = hash * 331 + (this.name != null ? this.name.GethashCode() : 0);\n    hash = hash * 331 + (this.category != null ? this.category.GethashCode() : 0);\n\n    return hash;\n}	0
10718134	10718022	Using two different network adapter simultaniously	string sendingIp = "192.168.0.1";\nint sendingPort = 5000;\nUri uri = new Uri("http://google.com");\nHttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);\nServicePoint sp = ServicePointManager.FindServicePoint(uri);\nsp.BindIPEndPointDelegate =\n    (servicePoint,remoteEp,retryCount) =>\n         {\n             return new IPEndPoint(IPAddress.Parse(sendingIp),sendingPort);\n         };\nvar data = new StreamReader(wr.GetResponse().GetResponseStream()).ReadToEnd();	0
5489787	5489775	Custom Attributes such as Displayname not listed with GetCustomAttribute	TestClass testClass = new TestClass();\n\n   Type type = testClass.GetType();\n\n   foreach (PropertyInfo pInfo in type.GetProperties())\n   {\n       DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pInfo, typeof(DisplayNameAttribute));\n\n       if (attr !=null)\n       {\n           MessageBox.Show(attr.DisplayName);   \n       }\n   }	0
3423981	3416067	How make LINQ query with GroupBy and LEFT JOIN	var query = from pt in model.ProductTypes\n            select new\n            {\n                ProductType = pt,\n                Products = from p in pt.Products\n                           where p.SeasonId == seasonId\n                           select p\n            };	0
29240831	16225909	Dealing with fields containing unescaped double quotes with TextFieldParser	using (TextFieldParser parser = new TextFieldParser(reader))\n{\n    parser.Delimiters = new[] { "," };\n\n    while (!parser.EndOfData)\n    {\n        string[] fields = null;\n        try\n        {\n            fields = parser.ReadFields();\n        }\n        catch (MalformedLineException ex)\n        {\n            if (parser.ErrorLine.StartsWith("\""))\n            {\n                var line = parser.ErrorLine.Substring(1, parser.ErrorLine.Length - 2);\n                fields = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);\n            }\n            else\n            {\n                throw;\n            }\n        }\n        Console.WriteLine("This line was parsed as:\n{0},{1}", fields[0], fields[1]);\n    }\n}	0
17705577	17705472	Serializing in Json.net	string json = "<you json string>";\n\nJObject o = JObject.Parse(json);\n// here is how you would access it\nstring jsonrpc = (string)o["jsonrpc"];\n// access array of you object\nJArray sizes = (JArray)o["<arrayName>"];\nstring arrayEntry = (string)sizes[0];	0
9652540	9652454	Return multiple values in C#	protected static List<string> listSetValues = new List<string>();\n    public static List<string> myfunction()\n    {\n        cmd = new SqlCommand("SELECT * FROM category", con);\n        con.Open();\n        SqlDataReader dr = cmd.ExecuteReader();\n        while (dr.Read())\n        {\n            listSetValues.Add(dr[0].ToString());\n        }\n        con.Close();\n        return listSetValues;\n    }	0
12380235	12380181	Excel Interop - Cancel selection	Application.CutCopyMode = False	0
3670497	3670369	crashes not trapped with MS VS Debugger - how to catch?	// MessageText:\n//\n// A heap has been corrupted.\n//\n#define STATUS_HEAP_CORRUPTION           ((NTSTATUS)0xC0000374L)	0
6907558	6907224	Inserting MatchCollection into datagridview c#	while (!sr.EndOfStream)\n            {\n                string line = sr.ReadLine();\n                line = line.Trim();\n                if (line.StartsWith("addTestingPageContentText"))\n                {\n                    string temp;\n                    string pattern = "\"([^\"]+)\"";\n                    Regex r = new Regex(pattern);\n                    MatchCollection regs = r.Matches(line);\n\n\n                    object[] array1 = new object[2];                    \n\n\n\n                    foreach (Match reg in regs)\n                    {\n\n                        temp = reg.ToString();\n                        temp = temp.Replace("\"", "");\n\n                        if (array1[0] == null)\n                            array1[0] = temp;\n                        else\n                            array1[1] = temp;\n                    }\n\n                    if (regs.Count > 0)\n                        contentTable_grd.Rows.Add(array1);\n                }\n            }	0
15371569	15371540	How to convert razor view to string?	public static string RenderPartialToString(Controller controller, string viewName, object model)\n{\n    controller.ViewData.Model = model;\n\n    using (StringWriter sw = new StringWriter())\n    {\n        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);\n        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);\n        viewResult.View.Render(viewContext, sw);\n\n        return sw.GetStringBuilder().ToString();\n    }\n}	0
10535498	10535073	microsoftreportviewer using multiple tables	private DataTable GetData(string tableName)\n    {\n        DataSet ds = new DataSet();\n        string query = "Select * from something";\n        OdbcDataAdapter da = new OdbcDataAdapter(query, conn);\n        da.Fill(ds);\n        DataTable dt = ds.Tables[tableName];\n        return dt;\n    }\n//You can fill the dataset once and then just get the table by table name. No necessary that you have to fill the dataset every time to get tables \n\n    private void RunReportViewer()\n    {\n        this.ReportViewer1.Reset();\n        this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report.rdlc");\n        ReportDataSource rds = new ReportDataSource("#_your_table_Name", GetData());\n        this.ReportViewer1.LocalReport.DataSources.Clear();\n        this.ReportViewer1.LocalReport.DataSources.Add(rds);\n        this.ReportViewer1.DataBind();\n        this.ReportViewer1.LocalReport.Refresh();\n    }	0
6906834	6906778	How to wait on multiple asynchronous operation completion	var tokenSource = new CancellationTokenSource();\n\nvar task = Task.Factory.StartNew(() =>\n{\n    for (int i = 0; i < 10; i++)\n    {\n        if (tokenSource.IsCancellationRequested)\n        {\n            //you know the task is cancelled\n            //do something to stop the task\n            //or you can use tokenSource.Token.ThrowIfCancellationRequested() \n            //to control the flow                \n        }\n        else\n        {\n            //working on step i\n        }\n    }\n}, tokenSource.Token);\n\ntry\n{\n    task.Wait(tokenSource.Token);\n}\ncatch (OperationCanceledException cancelEx)\n{ \n    //roll back or something\n}\n\n//somewhere e.g. a cancel button click event you call tokenSource.Cancel()	0
34260115	34260097	writing lambda expression in VB.net	foos.Select(Function(o) New Bar().InjectFrom(o))	0
5411349	5411322	C# Parse Date/Time with a unique format I haven't seen before	DateTime.ParseExact("2011-03-08-12.26.27.000000", "yyyy-MM-dd-HH.mm.ss.ffffff", null)	0
27145089	27144469	how to show values from database in a dropdownlist which is inside a gridview?	if (e.Row.RowType == DataControlRowType.DataRow)\n\n\n        { your code }	0
22988417	22988350	How to select a string in list view	ListViewItem item1 = listView1.FindItemWithText("test");\nif (item1 != null)\n     item1.Selected = true;	0
433054	433049	How do I get a list of all currently loaded assemblies?	Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();	0
4423335	4422699	Insert sentence to DB	DataClasses1DataContext db = new DataClasses1DataContext();\nTblConstant tb = new TblConstant();\ntb.Field1 = Value1;\ntb.Field2 = Value2;\n...\ndb.AddToTblConstants(tb);\ndb.SaveChanges();	0
2016509	2016406	Converting Bitmap PixelFormats in C#	Bitmap orig = new Bitmap(@"c:\temp\24bpp.bmp");\n        Bitmap clone = new Bitmap(orig.Width, orig.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);\n        using (Graphics gr = Graphics.FromImage(clone)) {\n            gr.DrawImage(orig, new Rectangle(0, 0, clone.Width, clone.Height));\n        }\n        // Dispose orig as necessary..	0
9552429	9552203	Sharing Entity Framework Library accross multiple projects	Web Services	0
12398899	12398826	HOw to get url contents of weblink	Request.QueryString;	0
14230966	14230657	I get a null value for a non-nullable foreign key with the entity framework	var recs = from a in ctx.REPORTROWS.Include(r => r.REPORTCOLUMNS)\n           where a.REPORTNAMES.NAME == "my report" && a.REPORTDATE == somedate select a;	0
22711206	22710770	Song Information Retrieval	string command = "setaudio MediaFile volume to " + volume.ToString();\nerror = mciSendString(Pcommand, null, 0, IntPtr.Zero);	0
7995848	7979183	Expression Encoder 4 LiveSourceSample. how to capture secondary monitor	deviceSource.ScreenCaptureSourceProperties = new ScreenCaptureSourceProperties()\n            {\n                Left = x,\n                Top = y,\n                Width = w,\n                Height = h,\n            };	0
5776663	5776605	Generic WPF multithread access to Controls	public static void SafeThreadAction<T>(this T control, Action<T> call)\n    where T : System.Windows.Threading.DispatcherObject\n{\n  if (!control.Dispatcher.CheckAccess())\n    control.Dispatcher.Invoke(call, control);\n  else\n    call(control);\n}	0
11673458	11501553	ItemsPanelTemplate in XAML ignores [ContentProperty] attribute	internal virtual void GenerateChildren()\n{\n    IItemContainerGenerator itemContainerGenerator = this._itemContainerGenerator;\n    if (itemContainerGenerator != null)\n    {\n        using (itemContainerGenerator.StartAt(new GeneratorPosition(-1, 0), GeneratorDirection.Forward))\n        {\n            UIElement uIElement;\n            while ((uIElement = (itemContainerGenerator.GenerateNext() as UIElement)) != null)\n            {\n                this._uiElementCollection.AddInternal(uIElement);\n                itemContainerGenerator.PrepareItemContainer(uIElement);\n            }\n        }\n    }\n}	0
1024195	1024123	SQL Insert one row or multiple rows data?	var iCounter = 0;\nforeach (Employee item in employees)\n{\n\n   if (iCounter == 0)\n  {\n    cmd.BeginTransaction;\n  }\n  string sql = @"INSERT INTO Mytable (id, name, salary) \n    values ('@id', '@name', '@salary')";\n  // replace @par with values\n  cmd.CommandText = sql; // cmd is IDbCommand\n  cmd.ExecuteNonQuery();\n  iCounter ++;\n  if(iCounter >= 500)\n  {\n     cmd.CommitTransaction;\n     iCounter = 0;\n  }\n}\n\nif(iCounter > 0)\n   cmd.CommitTransaction;	0
23404849	23401013	C# - WPF: Get UIElement in nested User Control	FrameworkElement loadedRoot = (FrameworkElement)XamlReader.Load(xmlReader);\n loadedRoot.Loaded += new RoutedEventHandler(loadedRoot_Loaded);\n LibovLoad.Children.Add(loadedRoot);\n\n void loadedRoot_Loaded(object sender, RoutedEventArgs e)\n {\n     Canvas canvas = (sender as FrameworkElement).FindName("LibovPhoto"); // not null\n }	0
23552447	23552186	linq seach XML Attribute	var messages = XDocument.Load(args[0])\n                        .Descendants("PreflightResultEntryMessage")\n                        .Where(x => x.Parent != null && \n                               x.Parent.Name == "PreflightResultEntry" &&\n                               x.Parent.Attribute("level") != null &&\n                               x.Parent.Attribute("level").Value == "error")\n                        .Select(x => x.Element("Message").Value);	0
8298319	8289659	Add new subscriber to list in mailchimp	// Subscribe the provided email to a list. \nlistSubscribe(string apikey, string id, string email_address, array merge_vars,\n    string email_type, bool double_optin, bool update_existing,\n    bool replace_interests, bool send_welcome);	0
18493730	18493714	Passing a generic list to a multi-parameter method in C#	private void CreateRow<T>(string key, IDictionary<string, Dictionary<string, int>>\n runningTally, List<T> columns)	0
7323011	7322956	Display xml data into html	var xslt = new XslCompiledTransform(true);\nxslt.Load(styleSheetFile, XsltSettings.TrustedXslt, new XmlUrlResolver());\nxslt.Transform(xmlFile, outputFile);	0
4680484	4680432	C# Populate Radiobuttons in a TreeView on PageLoad with a Database Returned Value	protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)\n{\n           e.Node.Text = "<input type='radio' />" + e.Node.Text;\n}	0
17617114	17567297	How can I read the value of a custom field from my Sitecore Webforms?	/// <summary>\n/// Override the result to get the selected value in the save action\n/// </summary>\npublic override ControlResult Result\n{\n    get\n    {\n        return new ControlResult(this.ControlName, this.textbox.Text, MaxLeadManagerFieldName);\n    }\n}	0
7230511	7230493	Best way to get underlying data from MemoryStream?	ms.ToArray()	0
1539882	1539783	Unit testing a function that outputs via XmlWriter?	public void Save(XmlWriter xmlWriter)\n{\n    XDocument xDoc = new XDocument(new XElement("BookmarkCollection",\n        Items.Select(bookmark => new XElement("Bookmark",\n            new XElement("Name", bookmark.Name),\n            new XElement("Link", bookmark.Link),\n            new XElement("Remarks", bookmark.Remarks),\n            new XElement("DateAdded", bookmark.DateAdded),\n            new XElement("DateLastAccessed", bookmark.DateLastAccessed))\n        )\n    ));\n    xDoc.Save(xmlWriter);\n}\n\npublic void Save()\n{\n    using (XmlWriter xmlWriter = XmlWriter.Create(m_StreamProvider.SaveFileStream(m_FilenameProvider.Filename)))\n    {\n        Save(xmlWriter);\n    }\n}	0
8766023	8759863	Subscribe when two events with preconditions were fired within a timespan	var  updown=down.Zip(up,(d,u)=> d).Timeout( TimeSpan.FromSeconds( 5 ) ).Retry();\n  updown.Subscribe( ar => { Console.WriteLine( "OK" ); } );	0
8195154	8195115	issue with switch inside a do while, control cannot fall through from one case label to another	switch(v) \n    { \n        case "a": \n                mother.incr1(amount); \n                break;\n        case "s": \n               mother.incr10(amount); \n               break;\n        etc.etc. \n    }	0
15599189	15597271	Make all controls inside a GroupBox read-only?	private void button1_Click(object sender, EventArgs e)\n    {\n        SetReadonlyControls(groupBox1.Controls);\n    }\n\n    private void SetReadonlyControls(Control.ControlCollection controlCollection)\n    {\n        if (controlCollection == null)\n        {\n            return;\n        }\n\n        foreach (TextBoxBase c in controlCollection.OfType<TextBoxBase>())\n        {\n            c.ReadOnly = true;\n        }\n    }	0
10391074	10391048	MVC3 Remote validation, validation fires, method is called but the parameter is null	public ActionResult IsUserNameAvailable([Bind(Prefix="Item1")] string username)\n{\n    ...\n}	0
30413648	30370936	How to stay logged in for Awesomium?	private void button1_Click(object sender, EventArgs e)\n {\n\n     Uri link = new Uri("http://www.mywebsite.com");\n     webControl1.Source = link;\n     string Values="";\n     WebSession session = WebCore.CreateWebSession("d:\\temp", WebPreferences.Default);\n     session.SetCookie(link, Values, true, **false**);\n\n}	0
2844518	2844514	Reading Excel file with C# - Choose sheet	public static IEnumerable<string> GetExcelSheetNames(string excelFile)\n{\n    var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +\n          "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";\n    using (var connection = new OleDbConnection(connectionString))\n    {\n        connection.Open();\n        using (var dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))\n        {\n            return (dt ?? new DataTable())\n                .Rows\n                .Cast<DataRow>()\n                .Select(row => row["TABLE_NAME"].ToString());\n        }\n    }\n}	0
27088979	27088748	asp.net grid view gives random page numbers	private DataTable dataTable = getDataTableStructure();	0
1453210	1453190	Does the Enumerator of a Dictionary<TKey, TValue> return key value pairs in the order they were added?	using System;\nusing System.Collections.Generic;\n\nclass Test\n{\n    static void Main(string[] args)\n    {\n        var dict = new Dictionary<int, int>();        \n        dict.Add(0, 0);\n        dict.Add(1, 1);\n        dict.Add(2, 2);\n        dict.Remove(0);\n        dict.Add(10, 10);\n\n        foreach (var entry in dict)\n        {\n            Console.WriteLine(entry.Key);\n        }\n    }\n}	0
11090597	11090545	Hardcoded JsonpResult values	return JsonpResult {\n    Data = new {\n        data = new List<object> {\n           new { T1 = "t1@test.com", T11 = "1234-1234-1234-1234" },\n           new { T2 = "t2@test.com", T22 = "1234-1234-1234-1234" },\n        }\n    }\n};	0
26650885	26650745	how to match "test\w*" but not "tester" with a single regex expression	test(?!er).*	0
22398256	22385954	How to use sp_helptext in Linqpad	sys.sp_helptext ("mySchema.usp_myProc")	0
19746562	19746398	How to change a letter in a textbox	textBox1.Text = textBox1.Text.Replace("?","?");	0
21839049	21838619	Adding Image to an Image List of a control	btn.ImageList = new ImageList();	0
14084879	14084473	Restore Application Settings after restarting the application	Properties.Settings.Default.SymbolScale = 150;\nProperties.Settings.Default.Save();\nProperties.Settings.Default.Upgrade();\nProperties.Settings.Default.Save();	0
7909693	7909601	Display ArrayList entries in multiline TextBox	foreach (Book b in books)\n    {\n        txtBookList.Text += b.authorFirstName;\n        txtBookLIst.Text += b.authorLastName;\n    }	0
4624151	4623882	MouseLeftButtonDown not recognized by a ListBox?	listBox_Faits.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(listBox_Faits_MouseLeftButtonDown), true);	0
13573396	13573343	How do I find my url dynamically ? HttpClient C#	string url = HttpContext.Current.Request.Url.AbsoluteUri;	0
15680999	15678901	insert data in sqlite using dataset in c#	SQLiteConnection m_dbConnection; \n    void createDbAndTable()\n    {\n        SQLiteConnection.CreateFile("MyDatabase.sqlite");\n        m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");\n        m_dbConnection.Open();\n        string sql = "create table myValues (name varchar(20), highScore int)";\n        SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);\n        command.ExecuteNonQuery();\n    }\n\n    void fillTable(DataSet ds)\n    {\n        var dt = ds.Tables[0];\n\n        foreach (DataRow dr in dt.Rows)\n        {\n            var name = dr["name"].ToString();\n            var score = Convert.ToInt32(dr["value"].ToString());\n            string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";\n            SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);\n            command.ExecuteNonQuery();\n        }\n        m_dbConnection.Close();\n    }	0
10464959	10464899	Get specific numbers from string	using System.Linq;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main() {\n        string text = "12 text text 7 text";\n        int[] numbers = (from Match m in Regex.Matches(text, @"\d+") select int.Parse(m.Value)).ToArray();\n    }\n}	0
4158364	1300088	Distinct() with lambda?	IEnumerable<Customer> filteredList = originalList\n  .GroupBy(customer => customer.CustomerId)\n  .Select(group => group.First());	0
1668589	1668470	How can I rotate an image in .NET and output it to the client as a PNG?	var m = new MemoryStream();\nbitmap.Save(m, ImageFormat.Png);\n//might want to set correct mime type here.\nResponse.BinaryWrite(m.ToArray());\nResponse.End();	0
9471574	9394945	Generate and save a PDF file	string MyVal = Request.Form["FieldName"];	0
29671927	29671878	How to define a class in C#	using PointCloud = System.Collections.Generic.List<PointData>;	0
4387543	4387114	How can show the rows of a table as columns in a new table	Data Transposition	0
10986342	10986272	Lambda Max and Max and Max	.Max(x => x.AverageRating * x.ReviewCount - x.DaysSinceLastReview - x.DistanceAway)	0
17148913	17132478	any machine connection to local SQL Server	Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;\nUser ID=myUsername;Password=myPassword;	0
5614026	5611413	Globalization of CultureInfo & DateTimeFormatInfo: How can we change digits format to my language?	// gets Eastern Arabic digits array\n        string[] numerals = CultureInfo.CreateSpecificCulture("ps-AF").NumberFormat.NativeDigits;	0
25335115	25252210	ToProperty and BindTo - Get initial value without Subscribing	// Can't subscribe to (null).Message!\nthis.WhenAnyValue(t => t.ViewModel.Message)	0
2686409	2686289	How to run a .Net Console App in the background	class Program\n{\n    static void Main(string[] args)\n    {\n        // just dont Application.Run(new frmMain(args));\n        //... your code\n    }\n }	0
20971369	20971278	How to get a table into a subclass?	var result = db.Quotes_Items_Suppliers\n            .Include(tbl => tbl.tblItems)\n            .Include(tbl => tbl.tblQuotes)\n            .Include(tbl => tbl.tblSuppliers)\n            .GroupBy(tbl => new { tbl.tblQuotes,tbl.tblSuppliers, tbl.tblItems })\n            .Select(grouped => new QuoteViewModel\n            {\n                Quote = new Quote{ID=grouped.Key.tblQuotes.ID,\n                                  QuoteNo =grouped.Key.tblQuotes.QuoteNo ,\n                                  Date= grouped.Key.tblQuotes.Date},\n                Supplier = grouped.Key.tblSuppliers,\n                Item = grouped.Key.tblItems,\n                Quantity = grouped.Sum(tbl => tbl.Quantity),\n                Price = grouped.Sum(tbl => tbl.Price)\n            });	0
19487801	19487409	Video file not getting saved in the folder	string filename = Path.GetFileName(FileUpload1.FileName);\n        HttpFileCollection MyFileCollection = HttpContext.Current.Request.Files;\n        if (MyFileCollection.Count > 0)\n        {\n            try\n            {\n                MyFileCollection[0].SaveAs(Server.MapPath("~/ProductVideos/") + filename);\n\n             }\n            catch (Exception ex)\n            {\n\n            }\n        }	0
14222476	14222387	No overload for method 'GetTouchPoint' takes 0 arguments	void SurfaceWindow1_TouchDown(object sender, TouchEventArgs e)\n{\n    LoadAnimationControl2 ani1 = new LoadAnimationControl2();\n    ani1.Margin.Left = e.GetTouchPoint(this).Position.X;\n    ani1.Margin.Bottom = e.GetTouchPoint(this).Position.Y;\n    MainGrid.Children.Add(ani1);\n}	0
1491729	1489685	Xml Deserialization - Sequence of Mutiple Types	public class DocumentLink : Link\n{\n}\n\npublic class ImageLink : Link\n{\n}\n\npublic class Link\n{\n    [XmlText]\n    public string Href { get; set; }\n}\n\npublic class Values\n{\n    [XmlArrayItem(ElementName = "ImageLink", Type = typeof(ImageLink))]\n    [XmlArrayItem(ElementName = "DocumentLink", Type = typeof(DocumentLink))]\n    public Link[] Links { get; set; }\n}	0
5194814	5194767	C# User Control custom Properties	public virtual DesignerActionListCollection ActionLists { get; }	0
24594065	24594035	Data fetched from table count-1	if (mySqlDataReader.Read() && mySqlDataReader[0] != DBNull.Value)	0
22027515	22024775	Making a method only available to my tests	[assembly: InternalsVisibleTo("FunctionalTests")]	0
7679669	7679551	Get only users who belong to a specific group	public bool IsInSecurityGroup(string UserName)\n    {\n       bool _isInsecurityGroup;\n                    string GroupName ="GroupName";\n                    System.Security.Principal.WindowsIdentity MyIdentity = \n                    System.Security.Principal.WindowsIdentity.GetCurrent();\n                    System.Security.Principal.WindowsPrincipal MyPrincipal = new \n                    System.Security.Principal.WindowsPrincipal(MyIdentity);\n\n             return (MyPrincipal.IsInRole(GroupName)) ? true : false;\n\n\n    }	0
16406341	16406203	How to add user input together	static void Main(string[] args)\n{\n    const int QUIT = -1;\n    string inputStr;\n    int inputInt = 0,tempint=0;\n    do\n    {\n        Console.Write("Type a number (type -1 to quit): ");\n        inputStr = Console.ReadLine();\n        bool inputBool = int.TryParse(inputStr, out tempint);\n\n        if (inputBool == true)\n        {\n            inputInt += tempint;\n        }\n\n        Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);\n\n    } while (tempint!= QUIT);\n\n\n}	0
3611877	3611073	Data Context's SubmitChanges method causing a entity reference to be set to null	SubmitChanges()	0
9314151	9313600	3D Vector structure from c++ to C#	[StructLayout(LayoutKind.Sequential)] //Required, as default layout is Auto\nstruct Vector3df {\n    public float x, y, z;\n}	0
1594416	1594375	Is there a better way to implement a Remove method for a Queue?	public class SpecialQueue<T>\n{\n    LinkedList<T> list = new LinkedList<T>();\n\n    public void Enqueue(T t)\n    {\n        list.AddLast(t);\n    }\n\n    public T Dequeue()\n    {\n        var result = list.First.Value;\n        list.RemoveFirst();\n        return result;\n    }\n\n    public T Peek()\n    {\n        return list.First.Value;\n    }\n\n    public bool Remove(T t)\n    {\n        return list.Remove(t);\n    }\n\n            public int Count { get { return list.Count; } }\n}	0
2268414	2268381	Testing a Singleton	private readonly static X509Certificate2 _singletonInstance = new X509Certificate2();	0
21635066	21634717	Optimizing a recursive method call	static string DisplayDigits(int value, string after)\n{\n    var t = string.Format("{0}  ", value % 10);\n\n    if (value < 10)\n    {\n        return t + after;\n    }\n\n    return DisplayDigits(value / 10, t + after);\n}	0
20130060	20129850	Get special combinations of string	string str = "LEQN";\nList<char> characters = str.ToCharArray().ToList();\nList<string> combinations = new List<string>();\nfor (int i = 0; i < characters.Count; i++)\n{\n    int combCount = 1;\n    string comb = characters[i].ToString();\n    combinations.Add(comb);\n    for (int j = 1; j < characters.Count - 1; j++)\n    {\n        int k = i + j;\n        if (k >= characters.Count)\n        {\n            k = k - characters.Count;\n        }\n        comb += characters[k];\n        combinations.Add(comb);\n        combCount++;\n    }\n}	0
29776993	29772088	How to bind an image(from resources) given in a propertie to DataGridTemplateColumn?	ImagePath="pack://application:,,,/<your resources>/yourImage.png";	0
22177190	22176513	How to tell if a ThreadPool thread died silently	protected void Enqueue()\n{\n    try\n    {\n        Task.Run(() => Process());\n    }\n    catch (Exception ex)\n    {\n        // Logging code here (no issues)\n    }\n}\n\nprotected void Process()\n{\n    try {\n        Process2();\n    }\n    catch (Exception e)\n    {\n        // Logging code\n    }\n}\n\nprotected void Process2()\n{\n            // Code that calls into offensive DLL\n}	0
20226245	20226092	count the number of datarows per month in a list	(from d in merge\ngroup d by d.month into g\nselect new \n   {\n       Month = g.Key, \n       Total = g.Count, \n       Accepted = g.Count(x => x.event_action_cd =="accept")*100/g.Count\n   }).ToList()	0
17866928	17821468	EntityFramework Generic Repository, multiple include?	public TEntity Item(Expression<Func<TEntity, bool>> wherePredicate, params Expression<Func<TEntity, object>>[] includeProperties)\n    {\n        foreach (var property in includeProperties)\n        {\n            _dbSet.Include(property);\n        }\n        return _dbSet.Where(wherePredicate).FirstOrDefault();\n    }	0
3554197	3553991	Drap and drop selected anchor text from browser window	e.Data.GetData(DataFormats.Html	0
443611	443522	How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke	[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]\npublic static extern int RegSetValueExW(uint hKey, string lpValueName,\n        uint lpReserved,\n        uint lpType,\n        ref int lpData,\n        uint lpcbData);	0
29198585	29198380	WebService how to not wait until task is completed	Task t = Task.Run(()=>\n{\n    Utility.MessageService sqs = new MessageService();\n    sqs.SendMessage("employeeUid=" + employeeUid);\n});	0
11349473	11349427	break enclosing switch statement from inner for loop?	switch(x)\n{\n    case 1:\n        if (ShouldDoMoreStuff())\n            doMoreStuff();\n        break;\n    case 2:\n        doSomeThingElse();\n        break;\n    default: throw new ArgumentOutOfRangeException();\n}\n\n\nprivate bool ShouldDoMoreStuff()\n{\n    for(int i = 0; i < 10; i++)\n    {\n        var val = getValue(i);\n        if (val == 0)\n            return false;\n    }\n\n    return true;\n}	0
15680019	15679869	how to read a file in batches/parts/1000 lines at a time	root\n    item\n        stuff\n    /item\n    item\n        stuff\n    /item\n    item\n        stuff\n    /item\n    item\n        stuff\n    /item\n/root	0
7967166	7955514	getting user details from AD is slow	Dim results = LDAPQuery("(memberOf=CN=Fully,OU=Qualified,DC=Group,DC=Distinguished,DC=Name)", New String() {"mobile", "description"})\n\nDim emps = (from c as System.DirectoryServices.SearchResult in results _\n             Select New Employee() {.Name = c.Properties("description"), .Mobile = c.Properties("mobile")}).ToList()\n\nPublic Function LDAPQuery(ByVal query As String, ByVal attributes As String()) As SearchResultCollection\n    'create directory searcher from CurrentADContext (no special security available)\n    Dim ds As New DirectorySearcher(System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().GetDirectoryEntry())\n    ds.PageSize = 1000\n\n    'set filter string\n    ds.Filter = query\n\n    'specify properties to retrieve\n    ds.PropertiesToLoad.AddRange(attributes)\n\n    'get results\n    Dim results As SearchResultCollection = ds.FindAll()\n\n    Return results\nEnd Function	0
3609864	3609816	Linq to add outer list index to inner elements	var result = outer.SelectMany((inner, index) => inner.Select(item => Tuple.Create(item, index)));	0
4534455	4532528	Manhattan Heuristic function for A-star (A*)	Func<Node, Node, double> estimatedDistanceBetweenTwoNodes = whatever;\nFunc<Node, double> estimatedDistanceToDestination = n=>estimatedDistanceBetweenTwoNodes(n, destination);	0
34482820	33838597	How to create credential object with already having access code and token for Google Drive API	var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer\n    {\n        ClientSecrets = new ClientSecrets\n            {\n                ClientId = ClientId,\n                ClientSecret = ClientSecret\n            },\n            Scopes = new[] { DriveService.Scope.Drive }\n    });\n\nvar credential = new UserCredential(_flow, UserIdentifier, new TokenResponse\n    {\n        AccessToken = AccessToken,\n        RefreshToken = RefreshToken\n    });\nvar service = new DriveService(new BaseClientService.Initializer\n    {\n        ApplicationName = "MyApp",\n        HttpClientInitializer = credential,\n        DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.Exception | ExponentialBackOffPolicy.UnsuccessfulResponse503\n    });	0
2379633	2376701	Linq to entities - How to define left join for grouping?	model.TaskCountByAssignee = (\n        (from t in TaskRepository.List()\n         from tu in t.TaskUsers\n         group tu by tu.UserName into tug\n         select new {Count = tug.Count(), UserName = tug.Key})\n        .Union(from t in TaskRepository.List()\n               where !t.TaskUsers.Any()\n               group t by 1 into tug\n               select new {Count = tug.Count(), UserName = null}).ToList();	0
21289905	21289751	How to Get the Id variable from the XML in c#?	String uniqueId = BusinessNeedNumber + IndustryFocusNumber + Competency + sta + ci + coun+entry.Identity.Value;	0
8654652	8654580	How can I order a list of class based on a value of each class?	classList = classList.OrderBy(cc => cc.value).ToList();	0
3415606	3415591	How to configure a C# application database connection easily for development and production without changing the code and recompiling?	app.config	0
27274045	27273340	How to Select SimpleType from the Base File in XSD while parsing in C#	XDocument doc = XDocument.Load("base.xsd");\nvar element = doc.Descendants()\n                 .FirstOrDefault(e => e.Attributes()\n                 .Any(a => a.Name=="name" && a.Value == "StringNotNull")) as XElement;\n\nvar minLength = element.Descendants()\n                       .FirstOrDefault(e => e.Name.LocalName == "minLength")\n                       .Attribute("value").Value;\nvar maxLength = element.Descendants()\n                       .FirstOrDefault(e => e.Name.LocalName == "maxLength")\n                       .Attribute("value").Value;	0
2105012	2104916	Iterating through a listview for specific ID?	lvSteps.Items(e.NewSelectedIndex).FindControl("lblStepNumber").Text = "whatever"	0
3601244	3601211	Change XML root element name	XmlDocument doc = new XmlDocument();\ndoc.LoadXml(yourString);\nXmlDocument docNew = new XmlDocument();\nXmlElement newRoot = docNew.CreateElement("MasterList");\ndocNew.AppendChild(newRoot);\nnewRoot.InnerXml = doc.DocumentElement.InnerXml;\nString xml = docNew.OuterXml;	0
30682577	30682308	Linq to entities group join on multiple tables	from compUsr in Repository.All<CompanyUser>()\njoin usr in Repository.All<User>() on compUsr.UserId equals usr.Id\njoin usrRole in Repository.All<UserRole>() on usr.Id equals usrRole.UserId\njoin role in Repository.All<Role>() on usrRoles.RoleId equals role.Id\ngroup new { usr, role } by usr into grp\n                    select new\n                    {\n                        Id = grp.Key.Id,\n                        Email = grp.Key.Email,\n                        Roles = grp.Select(r => new RoleDTO()\n                        {\n                            Id = r.role.Id\n                        })\n                    };	0
29638287	29638184	C# Weird Bug when trying to remove Controls from Group Box	for (int i = fieldBox.Controls.Count - 1; i >= 0; i--) // hopefully successful\n            fieldBox.Controls.RemoveAt(i);	0
8628399	8628350	How to store & retrieve password in sql server?	using System;\nusing System.Text;\nusing System.Security.Cryptography;\n\n// Create an md5 sum string of this string\nstatic public string GetMd5Sum(string str)\n{\n// First we need to convert the string into bytes, which\n// means using a text encoder.\nEncoder enc = System.Text.Encoding.Unicode.GetEncoder();\n\n// Create a buffer large enough to hold the string\nbyte[] unicodeText = new byte[str.Length * 2];\nenc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);\n\n// Now that we have a byte array we can ask the CSP to hash it\nMD5 md5 = new MD5CryptoServiceProvider();\nbyte[] result = md5.ComputeHash(unicodeText);\n\n// Build the final string by converting each byte\n// into hex and appending it to a StringBuilder\nStringBuilder sb = new StringBuilder();\nfor (int i=0;i<result.Length;i++)\n{\n    sb.Append(result[i].ToString("X2"));\n}\n\n// And return it\nreturn sb.ToString();\n}	0
1223183	1217350	How do I make an HTML file part of a MonoDevelop project?	string text;\nusing (var stream = typeof(SomeTypeInYourAssembly).Assembly.GetManifestResourceStream (resourceId))\n    using (var sr = new StreamReader (stream))\n        text = sr.ReadToEnd ();	0
16021370	16021302	C# Save text to speech to MP3 file	reader.SetOutputToWaveFile(@"C:\MyWavFile.wav");	0
4923032	4922855	Linq-to-XML explicit casting in a generic method	public static T GetValueFromAttribute<T>(IEnumerable<XElement> fields, String attName)\n{\n  return (from field in fields\n          where field.Attribute("name").Value == attName\n          select (T)Convert.ChangeType(field.Attribute("value").Value, typeof(T))).FirstOrDefault();\n}	0
8666643	8666592	Assigning a System.Action to a BackgroundWorker	public BackgroundWorker GetBackgroundWorker(System.Action doWork)\n{\n   BackgroundWorker bwk= new BackgroundWorker();\n   bwk.DoWork += (sender, args) => { doWork(); };\n   return bw;\n}	0
6494209	6493923	How to receive value in PostBack page, in asp.net?	protected void Page_Load(object sender, EventArgs e)\n{\n    TextBox myTxt = (TextBox)Page.PreviousPage.FindControl("previousPageTextBoxName");\n    currentPageTextBox.text = myTxt.Text;\n}	0
24408560	24406993	How can return a text based on value in database in EF6 using get method	public class ModelSemiWrapperBase<TModel> \n{\n   public ModelSemiWrapperBase(TModel model)\n   {\n       this.Model = model;\n   }\n   public TModel Model\n   {\n       get;\n       private set;\n   }\n}\n\npublic class GoodSemiWrapper : ModelSemiWrapperBase<Good>\n{\n    public String HasTax\n    {\n        get\n        {\n            return (this.Model.HasTax == 0) ? ("Yes") : ("No");\n        }\n        set {...}\n    }\n}	0
22401764	22401712	How to trigger manually and event using ElapsedEventHandler?	// Somewhere else\nOnTimerStatus(null, null);	0
28725306	28725305	Can I force SSL to secure a Dotnetnuke Module Edit Page?	// Force Page to use SSL if it can.\nif (PortalSettings.SSLEnabled && !Request.IsSecureConnection)\n{\n  DotNetNuke.Security.PortalSecurity.ForceSecureConnection();\n}	0
8707504	8707475	Get pointer (IntPtr) of int value	unsafe void foo() {\n   int value = 42;\n   int* ptrToValue = &value;\n   // etc, do not return the pointer!!\n   //...\n}	0
28196802	28196550	Convert string to double using special separators	string s = "2 524,2";\n\nCultureInfo ci = new CultureInfo(1);\nNumberFormatInfo ni = new NumberFormatInfo();\n\nni.NumberGroupSeparator = " ";\nni.NumberDecimalSeparator = ",";\nci.NumberFormat = ni;\n\ndecimal d = decimal.Parse(s, ci);	0
23336475	23336448	how to display .txt file values in textbox or datagrid using c#	string fileTxt = File.ReadAllText(@"c:\.....");\ntextbox.Text = fileTxt;	0
24765556	24765492	How to validate CSV in C#?	using Microsoft.VisualBasic.FileIO;\n...\nvar path = @"C:\YourFile.csv";\nusing (var parser = new TextFieldParser(path))\n{\n    parser.TextFieldType = FieldType.Delimited;\n    parser.SetDelimiters(",");\n\n    string[] line;\n    while (!parser.EndOfData)\n    {\n        try\n        {\n            line = parser.ReadFields();\n        }\n        catch (MalformedLineException ex)\n        {\n            // log ex.Message\n        }\n    }\n}	0
29639775	29639190	Window title is overwritten when using Caliburn's conductor<object> in view model	[Export(typeof (IShell))]\npublic class ShellViewModel : Conductor<IScreen>\n{\n    public ShellViewModel()\n    {\n        DisplayName = "Your window title";\n    }\n}	0
5406113	5406043	Populating GridView using EntityDataSource and QueryString	protected void Page_Load(object sender, EventArgs e)\n        {\n            DataClasses1DataContext db = new DataClasses1DataContext();\n            var te = from p in db.table\n                     where p.entityid=Request.Querystring["EntityID"]\n                     select p;\n            GridView1.DataSource = te;\n            GridView1.DataBind();\n\n        }	0
11984428	11981705	How to combine these two LINQ statements?	var users = repository\n    .GetMany<Letter>(l => l.Priority > (\n        repository.GetMany<Letter>(\n            l2 => l2.UserID = currentUser.ID\n        )\n        .Select(l2 => l2.Priority)\n        .First()\n    )\n    .OrderBy(l => l.Priority)\n    .Select(l => l.User)\n    .Take(1);	0
19243871	19243534	Starting a remote scheduled task	using Microsoft.Win32.TaskScheduler;\n\nusing (TaskService tasksrvc = new TaskService(server.Name, login, domain, password)\n{\n    Task task = tasksrvc.FindTask(taskName);\n    task .Run();       \n}	0
12838780	12838606	read the data from XML Structure using c#	var xElem = XElement.Parse(abcd);\nvar a = xElem.Element("a").Value;\nvar c = xElem.Element("c").Element("c1").Value;	0
4876453	4876307	wpf databinding not updating from a property	private Movie selectedMovie;\n\npublic Movie SelectedMovie\n{\n    get\n    {\n        return selectedMovie;\n    }\n    set\n    {\n        selectedMovie = value;\n        InvokePropertyChanged("SelectedMovie");\n    }\n}	0
1170512	1168419	WPF MultiBinding	public string BillingAddress{\n    set{\n        billingAddress = value;\n        firePropertyChanged("BillingAddress");\n        if(string.isNullOrEmpty(ShippingAddress)\n        {\n            ShippingAddress = value; //use the property to ensure PropertyChanged fires\n        }\n    }\n    get{ return billingAddress; }\n}	0
19528967	19528884	converting object to string	label1.Text = ((object[])b)[0].ToString()	0
1857983	1857967	Using enum as a dependency property in WPF	public enum PriceCategories\n{\n  // ...\n}\npublic static readonly DependencyProperty PriceCatProperty =\n  DependencyProperty.Register("PriceCat", typeof(PriceCategories),\n  typeof(CustControl),  new PropertyMetadata(PriceCategories.First));\n};  // <-- this is probably closing the containing class	0
1840953	1835578	C# copying multiple files with wildcards and keeping file names	if (checkBox3.Checked)\n{\n    string[] lines = File.ReadAllLines(@"C:\NCR.txt");\n\n    foreach (string line in lines)\n    {\n        string[] files = Directory.GetFiles(textBox2.Text, line + "*.txt");\n        foreach (string file in files)\n        {\n             FileInfo file_info = new FileInfo(file);\n             File.Copy(file, @"C:\InPrep\" + textBox1.Text + "\\text\\" + file_info.Name);\n        }\n    }\n}	0
25637661	25501240	How do I add a row to a Datagrid in C# WPF	DataTable dt = new DataTable();\n\n        DataColumn column;\n        DataRow row;\n        DataView view;\n\n        row = new DataRow();\n        dt.Rows.Add(row);\n        column = new DataColumn();\n        column.DataType = System.Type.GetType("System.Int32");\n        column.ColumnName = "id";\n        dt.Columns.Add(column);\n\n        column = new DataColumn();\n        column.DataType = Type.GetType("System.String");\n        column.ColumnName = "item";\n        dt.Columns.Add(column);\n\n        for (int i = 0; i < 10; i++)\n        {\n            row = dt.NewRow();\n            row["id"] = i;\n            row["item"] = "item " + i.ToString();\n            dt.Rows.Add(row);\n        }\n\n        view = new DataView(dt);\n        dataView1.ItemsSource = view;	0
9442504	9442171	A way out from getting SystemOutOfMemoryException while importing from large text file into database	int lineLimit = GetConfiguration("lineLimit"); \nint lineNumber = 0;\nDataTable logZyWall = CreateLogTable();\n\nusing(StreamReader reader=new StreamReader("C:\ZyWall.log")) \n{ \n    while ((line=reader.ReadLine())!=null)\n    {\n        DataRow row = ParseThisLine(line);\n        logZyWall.Rows.Add(row);\n        lineNumber++;\n        if(lineNumber == lineLimit)\n        {\n            WriteWithOracleBulkCopy(logZyWall);\n            logZyWall = CreateLogTable();\n            lineNumber = 0;\n        }\n    }\n    if(lineNumber != 0) WriteWithOracleBulkCopy(logZyWall);\n}	0
14498275	14477192	Mono for Android: XML data to spinner	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
29701444	29701130	LINQ - get parent of parent	IEnumerable<SalesOrderDetail> result = orderDetails.Where(order => order.ProductDetail.Product.ProductCategory.Id == searchedProductCategoryId);	0
4774948	4774918	How to get the char count between two indexes in a string?	for (int i = 0; i < positions.Count-1; i++)\n{\n        string section = content.Substring(positions[i], \n                                           positions[i+1]-positions[i]);\n        Players.Add(ParsePlayer(section));\n}	0
25604421	25514327	Can you skip XML Elements when performing XML Serialization using Complex Objects in a T4 template?	// Assuming the xml looks like the sample you provided\npublic static XElement ToXml(this string text)\n{\n    var xml = XElement.Parse(text);\n    // grab the first parent\n    var parent = xml.Descendants("elements").FirstOrDefault();\n    // grab the Value nodes\n    var nodes = xml.Descendants("Value").Where (x => x.Parent != xml && x.Parent != parent);\n    // add the Value nodes to the first elements node\n    parent.Add(nodes.ToArray());\n    // remove all the branches the Value elements came from\n    nodes.ToList()\n          .ForEach(x=> x.Ancestors()\n            .TakeWhile(a=> a != xml)\n            .Where (a => a != parent)\n            .Remove());\n    return xml;\n}	0
4854017	4840696	Prevent a byte from wrapping back to 0 when incremented over 255	static byte NoWrapIntToByte(int x)\n{\n    return (byte)MathHelper.Clamp(x, 0, 255);\n}	0
10452261	10451541	Extract data from Text	string json = @"{\n                 'id': 'my id',\n                 'name': 'name',\n                 'first_name': 'first name',\n                 'last_name': 'last name',\n                 'username': 'nick',\n                 'gender': 'male',\n                 'locale': 'en_EN'\n                }";\n\nJObject obj = JObject.Parse(json);\n\ntextBoxID.Text = obj["id"].ToString();\ntextBoxName.Text = obj["name"].ToString();\n//and so on	0
10848309	10848190	Convert Kinect ColorImageFrame to Bitmap	Bitmap ImageToBitmap(ColorImageFrame Image)\n{\n     byte[] pixeldata = new byte[Image.PixelDataLength];\n     Image.CopyPixelDataTo(pixeldata);\n     Bitmap bmap = new Bitmap(Image.Width, Image.Height, PixelFormat.Format32bppRgb);\n     BitmapData bmapdata = bmap.LockBits(\n         new Rectangle(0, 0, Image.Width, Image.Height),\n         ImageLockMode.WriteOnly, \n         bmap.PixelFormat);\n     IntPtr ptr = bmapdata.Scan0;\n     Marshal.Copy(pixeldata, 0, ptr, Image.PixelDataLength);\n     bmap.UnlockBits(bmapdata);\n     return bmap;\n }	0
5006075	5005874	How to get the error message with C#	Process p = new Process();\np.StartInfo.FileName = "hello.exe";\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.UseShellExecute = false;\np.Start();\nstring stdout = p.StandardOutput.ReadToEnd(); \np.WaitForExit();	0
6043805	6043612	Custom SQL in a Gridview	SqlConnection con = new SqlConnection("");//put connection string here\n    SqlCommand objCommand = new SqlCommand("SELECT FirstName, LAstName from MyTable where FirstName = '" + "ABC" + "'", con);//let MyTable be a database table\ncon.Open();\n    sqlDataReader dr = objCommandExecuteReader();\nmyGridView.DataSource = dr;//let myGridView be your GridView name\nmyGridView.DataBind();	0
280512	280313	Merge XML files in a XDocument	var MyDoc = XDocument.Load("File1.xml");\nMyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements());	0
2075856	2075746	CreateInstance of a Type in another AppDomain	ObjectHandle handle = domain.CreateInstanceFrom( \n    baseDirectory + @"\SampleClassLibrary.dll", // <- exists in "c:\foo"  \n    "SomeClassInTheDll" );	0
16918325	16918060	Reading the 1st Excel sheet of a workbook by default	const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=no;\";";\nOleDbConnection objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));\nDataSet dsImport = new DataSet();       \ntry\n{\n    objConnection.Open();\n     DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n     if( (null != dtSchema) && ( dtSchema.Rows.Count > 0 ) )\n    {\n        string firstSheetName == dtSchema.Rows[0]["TABLE_NAME"].ToString();\n         new OleDbDataAdapter("SELECT * FROM [" + firstSheetName + "]", objConnection).Fill(dsImport);\n    }\n    catch\n    {\n        throw;\n    }\n    finally\n    {\n        // Clean up.\n        if(objConnection != null)\n        {\n        objConnection.Close();\n             objConnection.Dispose();\n        }\n    }\nreturn (dsImport.Tables.Count > 0) ? dsImport.Tables[0] : null;	0
16110722	16110487	How to Return Database Result based on CASE statements?	if @op='CLERK'\n  begin\n      exec 'insert into ' + @table + '(NUM) values (' + @num + ') where' + @num + 'in    (''000988'',''001508',''003790',''007912'')' \n  end\n  else if @op='HRMANAGER'\n  begin\n      i-- see above\n  end\n  else if @op='HUMANRESOURCES'\n  begin\n    -- see above\n  end\n  else if @op='INFORMATIONTECHNOLOGY'\n  begin\n      -- see above\n  end\n\n  exec 'SELECT NUM from' + @table + 'order by NUM;'	0
23905650	23576294	Application can't scaffold items	base.OnModelCreating(modelBuilder);	0
29266021	29265881	How to create an array of TimeZoneInfo variables	List<string> arrWindowsTimeZones = new List<string>() { "Hawaiian Standard Time", "Alaskan Standard Time", "Pacific Standard Time", "Central Standard Time" };\nList<TimeZoneInfo> arrTimeZoneInfo = new List<TimeZoneInfo>();\n\nforeach (string zoneString in arrWindowsTimeZones)\n{\n    arrTimeZoneInfo.Add(TimeZoneInfo.FindSystemTimeZoneById(zoneString));\n}	0
22928293	22927357	What are the effects of referencing the visual basic namespace from a C# application?	Microsoft.VisualBasic.dll	0
6757886	6757816	How to set a return value if array has some value which is not set	if(i == this.Count) //i reached the end of the loop but no matches found\n{\n return -2;\n}	0
13349712	13349636	Extract number from a string	Regex regex = new Regex(@"\d+");\n\nforeach (Match match in regex.Matches("156234 something 567345 another thing 45789 anything"))\n{\n    Console.WriteLine(match.Value);\n}	0
16818989	16818892	How to fetch record by weekly in entity framework	public List<Customer> ByWeek(int year, int week) {\n   return db.Customers.Where(p => \n                   SqlFunctions.DatePart("week", p.Createon) == week && \n                   SqlFunctions.DatePart("year", p.Createon) == year\n                   );\n\n}	0
2053760	2053742	RegEx for pattern in c#	string input = "12345";\nbool match = Regex.IsMatch(input, "^[a-z0-9]{1,5}$", RegexOptions.IgnoreCase);	0
10184811	10184551	stackpanel highlight on mouse over from code behind	public MainWindow()\n{\n    InitializeComponent();\n\n    StackPanel stackpanel = new StackPanel(); \n    stackpanel.MouseEnter += new MouseEventHandler(stackpanel_MouseEnter);\n    stackpanel.MouseLeave += new MouseEventHandler(stackpanel_MouseLeave);\n}\n\nvoid stackpanel_MouseLeave(object sender, MouseEventArgs e)\n{\n    StackPanel stackpanel = (StackPanel)sender;\n    stackpanel.Background = Brushes.Transparent;\n}\n\nvoid stackpanel_MouseEnter(object sender, MouseEventArgs e)\n{\n    StackPanel stackpanel = (StackPanel)sender;\n    stackpanel.Background = Brushes.LightGray;\n}	0
16492295	16492257	How to make a multiple files with 1 path?	string path = "c:\\File\\File\\"+ Username + ".text";	0
27166967	27165199	Random Generator Creates Same Numbers From A Single Object	private void TesterFunc()\n       {\n        bool isFound = false;\n        int intCounter = 0;\n        int[] arr;\n\n        while (!isFound)\n        {\n            arr = new int[9] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n\n            List<LittleBox> lst = new List<LittleBox>();\n            for (int i = 0; i < 9; i++)\n            {\n                lst.Add(new LittleBox(arr));\n            }\n\n            MainRandomGenerator = new Random(intCounter);\n            BigBox item = new BigBox(lst);\n            item.RandomizeBigBox(MainRandomGenerator);\n            MainRandomGenerator.Next(1, 10);\n            item.CalculateBigBoxScore();\n            if (item.TotalScore == 0)\n            {\n                isFound = true;\n            }\n            intCounter++;\n        }\n     }	0
18577525	18577487	C# converted from VB doesn't work	List<string> Flop = new List<string>();\n\n    for (int x = 0; x <= Dataset9.Tables[0].Rows.Count - 1; x++)\n      {\n         Flop.Add(Dataset9.Tables[0].Rows[x]["Id"].ToString());\n      }\n strAllRoleNames = string.Join(",", Flop.ToArray());	0
9077512	9077284	Main thread showing a form as dialog, how to close it programetically by using worker thread?	form.Invoke(new Action(form.Close));	0
27678907	27678800	How to get the birthday from a windows phone 8.1 (NOT Silverlight) contact	var contactStore = await ContactManager.RequestStoreAsync();\nvar contacts = await contactStore.FindContactsAsync();\n\nforeach (var contact in contacts) \n{   \n   // var list = contact.ImportantDates;\n   // Enumerating this list we can check for ContactDateKind == Birthday\n   // Or even shorter:\n\n   var birthday = contact.ImportantDates.FirstOrDefault(d => d.Kind == ContactDateKind.Birthday);\n\n   // birthday is null if there is no birthday saved for the current contact\n}	0
6516444	6516388	Find function Invoker	StackTrace stackTrace = new StackTrace();\nStackFrame[] stackFrames = stackTrace.GetFrames();\n\nConsole.WriteLine(stackFrames[1].GetMethod().Name);	0
20117256	20116893	How to read namespaces c# LINQ to XML	XNamespace defns = xdoc.Root.GetDefaultNamespace();\nXNamespace es = xdoc.Root.GetNamespaceOfPrefix("es");	0
25662648	25662315	How get a substring after the 3rd occurrence of a string c#	// The directory \n    string dir = "http://TEST.COM/page/subpage";\n    // Split on directory separator\n    string[] parts = dir.Split('/');	0
30940381	30940020	Intersection of two lists using LINQ	public List<User> GetUsers(User admin)\n{\n    var adminCompanyIDs = admin.Companys.Select(c => c.ID);\n    return Users.Where(user=>user.Companys.Select(c => c.ID).Intersect(adminCompanyIDs).Any()).ToList();        \n}	0
21113823	21113766	Excell sheets select first row with c#	xlWorkSheet.Range("A1", "A1").EntireRow.Value;	0
3760073	3759635	WCF Reading Endpoint Behaviors from a web.config file	foreach (OperationDescription operation in base.Endpoint.Contract.Operations)    \n{    \noperation.Behaviors.Find<DataContractSerializerOperationBehavior>().MaxItemsInObjectGraph = 2147483646;                    \n}	0
31701084	31700834	How to create series of string combination of Alphabet and Number?	var result = data.OrderBy(d => d[d.Length - 1])\n                 .ThenBy(d => int.Parse(d.Substring(0, d.Length - 1])));	0
12194005	12193912	Enum Conversion to String	leave.LeaveType=(LeaveReason)Enum.Parse(typeof(LeaveReason),\n                                         dr["id_leave_type"].ToString(),true);	0
1434706	1434674	JQuery in ASP.Net User Control in C#	ctlID.text("Testing");	0
9896280	9895805	ContextMenu in Windows Phone 7	ContextMenu cm = new ContextMenu();\n\ncm.Items.Add( new MenuItem() {\n  Header = "Item 1",\n} );	0
5645415	5628012	Post multipart/form-data in C# to upload photos on facebook	Install-Package Facebook.Sample	0
1829742	1829700	creating a custom attribute to control rounding behavior	[Serializable]\npublic class RoundingAttribute : OnMethodBoundaryAspect\n{\npublic override void OnExit(MethodExecutionEventArgs eventArgs)\n{\nbase.OnExit(eventArgs);\neventArgs.ReturnValue = Math.Round((double)eventArgs.ReturnValue, 2);\n}\n}\n\nclass MyClass\n{\npublic double NotRounded { get; set; }\n\npublic double Rounded { [Rounding] get; set; }\n}\n\nclass Program\n{\nstatic void Main(string[] args)\n{\nvar c = new MyClass\n        {\n        Rounded = 1.99999, \nNotRounded = 1.99999\n        };\n\nConsole.WriteLine("Rounded = {0}", c.Rounded); // Writes 2\nConsole.WriteLine("Not Rounded = {0}", c.NotRounded);  // Writes 1.99999\n}\n}	0
924083	923969	How can i match this text with a regex?	/\*<parameters>\*/(?<value>[^/]*)/\*</parameters>\*/	0
1942299	1936525	Expression/Statement trees	var @foreach = Expression.Block(\n            new ParameterExpression[] { item, enumerator, param },\n            assignToEnum,\n            Expression.Loop(\n                Expression.IfThenElse(\n                    Expression.NotEqual(doMoveNext, Expression.Constant(false)),\n                    assignCurrent,\n                    Expression.Break(@break))\n            , @break)\n        );	0
28354535	28330252	trying to keep a game object within the screen left and right bounds in unity3d	Vector3 playerPosScreen;\nVector3 wrld;\nfloat half_szX;\nfloat half_szY;\nvoid Start () {\n    wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));\n    half_szX = renderer.bounds.size.x / 2;\n    half_szY = renderer.bounds.size.y /2 ;\n}\nvoid Update () {\n    playerPosScreen = transform.position;\n if (playerPosScreen.x >=(wrld.x-half_szX) ) {\n        playerPosScreen.x=wrld.x-half_szX;\n        transform.position=playerPosScreen;\n    }\n    if(playerPosScreen.x<=-(wrld.x-half_szX)){\n        playerPosScreen.x=-(wrld.x-half_szX);\n        transform.position=playerPosScreen;\n    }\n}	0
30235939	30235739	Struggling to populate datagrid from stored procedure with parameters	cmd.Parameters.AddWithValue("@city","" + city + "");	0
2499708	2499672	How to disable edit mode on cells but checkbox column?	private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {\n  if (e.ColumnIndex != 0) e.Cancel = true;\n}	0
22707764	22707697	How to change custom string format to Datetime format in Asp.net mvc	var result = DateTime.ParseExact("03/28/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture)\n                        .ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);	0
26551706	26551163	Asp.net required validator resets on postback	if (chkAssociate.Checked) {\n   rfvAddress.Enabled = False;\n}	0
21034069	21034028	variable name of table in select query	"INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +\n            string.Format("SELECT NOW(), name, lname, score FROM {0} ", tablename) );	0
18445328	18445229	How do I call a SOAP service in ASP.NET	string userName = "Name";\nstring password = "Password";\nvar proxy = new TokenServiceClient();\nvar token = proxy.issueToken(userName, password);\nproxy.Close();	0
2915311	2915035	Need a refresher course on property access	using (MyDataContext dc = _conn.GetContext())\n{\n    var options = new DataLoadOptions();\n    options.LoadWith<Account>(a => a.Email);\n    options.LoadWith<Account>(a => a.Profile);\n    options.LoadWith<Account>(a => a.HostInfo);\n\n    dc.LoadOptions = options;\n\n    try\n    {\n        account = (from a in dc.Accounts\n                   where a.UserName == userName\n                   select a).FirstOrDefault();\n    }\n    catch\n    {\n        //oops\n    }\n}	0
10553495	10553394	value is changing in page life cycle?	1) Is this a postback?\n   -> No: Generate a new value and store it in ViewState. Hold onto this value.\n   -> Yes: Do we have a stored answer value in ViewState?\n         -> No: Error? Something has gone wrong.\n         -> Yes: Fetch that Value and hold on to it\n2) On Button Click, Is the answer you entered the same as the generated value?\n   -> No: Show Error\n   -> Yes: Show Success, Then generate a new value and store it in ViewState	0
17077814	17077703	How to call a function defined in C# with same params,return type and same name but in different case from a VB.NET project	Dim mcls As New [MyClass]\nDim t As Type = mcls.GetType()\nDim x = t.InvokeMember("add", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, mcls, New Object() {1, 2})\nDim y = t.InvokeMember("Add", BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, mcls, New Object() {1, 2})	0
3197649	3197618	Right of a character in C#	string user = User.Identity.Name\nuser= user.Remove(0, user.IndexOf(@"\")+ 1);	0
4323299	4323105	How can I scroll to a specified line number of a RichTextBox control using C#?	void ScrollToLine(int lineNumber)\n    {\n        if (lineNumber > richTextBox1.Lines.Count()) return;\n\n        richTextBox1.SelectionStart = richTextBox1.Find(richTextBox1.Lines[lineNumber]);\n        richTextBox1.ScrollToCaret();\n    }	0
13553815	13552385	How to get the ids of selected slides	Dim oSl As Slide\n    For Each oSl In ActiveWindow.Selection.SlideRange\n        Debug.Print oSl.SlideID\n    Next	0
9519742	9519687	switch style C# construct with double range cases	double a = 1.1;\n\nif (a < 0.0) {\n    // Too low\n    return -1;\n} else if (a < 1.6) {\n    // Range [0.0, 1.6)\n    return 1;\n} else if (a < 2.337) {\n    // Range [1.6, 2.337)\n    return 2;\n} else if (a < 3.2974) {\n    // Range [2.337, 3.2974)\n    return 3;\n} else {\n    // Too high\n    return -1;\n}	0
3808600	3808368	C# - How to copy a single Excel worksheet from one workbook to another?	//Copies sheet and puts the copy into a new workbook\nsheet.Copy(Type.Missing, Type.Missing);\n\n//sets the sheet variable to the copied sheet in the new workbook\nsheet = app.Workbooks[2].Sheets[1];	0
25421357	25421101	Using Generic Repository with TEntity in Unity	container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));	0
11665661	11664753	C# Regular Expression : how to extract content from string?	foreach (Match match in Regex.Matches(inputString, \n                                      @"\[down\](?<content>.+)\[/down\]"))\n{\n    var content = match.Groups["content"].Value;\n\n    var hrefs = new List<string>();\n\n    foreach (Match matchhref in Regex.Matches(t, @"href=""(?<href>[^""]+)"""))\n    {\n        hrefs.Add(matchhref.Groups["href"].Value);\n    }\n}	0
11163506	11163296	Another SQL parameter - UPDATE statement	SqlParameter param3 = new SqlParameter("@param3", SqlDbType.Text);\n    **param3.Value = param2.ToString();**	0
21802481	21802028	get and insert textarea value into database	Request.Form["updateabout"]; gets value from query string but in your case you have a text area. If you are using javascript try to use \nvar updatedabout=document.getElementById('updatedabout').value;	0
29393485	29391179	How to get available space on Storage Device	StorageFolder folder = Windows.Devices.Portable.StorageDevice.FromId(phoneId);\n\nvar data = new List<Tuple<string, UInt64[]>> { };\nIReadOnlyList<StorageFolder> subFolders = await folder.GetFoldersAsync();\nforeach (StorageFolder subFolder in subFolders)\n{\n  var props = await subFolder.Properties.RetrievePropertiesAsync(\n    new string[] { "System.FreeSpace", "System.Capacity" });\n  if (props.ContainsKey("System.FreeSpace") && props.ContainsKey("System.Capacity"))\n  {\n    data.Add(Tuple.Create(\n      subFolder.Name,\n      new UInt64[] {\n        (UInt64) props["System.FreeSpace"],\n        (UInt64) props["System.Capacity"]\n    }));\n  }\n}\nreturn data;	0
15928049	15899197	Parse xmldocument based on permissions	XDocument document = XDocument.Load("c:\\temp\\test.xml");\n    var fields = document.Descendants("Permission")\n                .Where(i => i.Attribute("Name") != null && i.Attribute("Name").Value == "permissionXYZ")\n                .Select(i => i.Descendants("Field"));	0
30762999	30762646	How to successfully implement WPF textbox validation?	public MainWindow()\n    {\n        InitializeComponent();\n        this.DataContext = this;\n    }	0
7232919	7215835	Comparing dynamic objects in C#	//using System.Dynamic;\n//using Dynamitey;\n//using System.Linq;\n\nIEnumerable<string> list1 =Dynamic.GetMemberNames(obj1);\nlist1 = list1.OrderBy(m=>m);\nIEnumerable<string> list2 =Dynamic.GetMemberNames(obj2);\nlist2 = list2.OrderBy(m=>m);\n\nif(!list1.SequenceEqual(list2))\n return false;\n\nforeach(var memberName in list1){\n if(!Dynamic.InvokeGet(obj1, memberName).Equals(Dynamic.InvokeGet(obj2,memberName))){\n    return false;\n }\n}\nreturn true;	0
13857878	4390543	Facebook Real-time Update: Validating X-Hub-Signature SHA1 signature in C#	public void MyAction() {\n    string signature = request.Headers["X-Hub-Signature"];\n    request.InputStream.Position = 0;\n    StreamReader reader = new StreamReader(request.InputStream);\n    string json = reader.ReadToEnd();\n\n    var hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(json), UTF8Encoding.UTF8.GetBytes("MySecret"));\n    var hmacHex = ConvertToHexadecimal(hmac);\n\n    bool isValid = signature.Split('=')[1] == hmacHex ;\n\n}\n\n\nprivate static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody) {\n    using (var hmacAlgorithm = new System.Security.Cryptography.HMACSHA1(keyBody)) {\n        return hmacAlgorithm.ComputeHash(dataToSign);\n    }\n}\n\nprivate static string ConvertToHexadecimal(IEnumerable<byte> bytes)\n{\n    var builder = new StringBuilder();\n    foreach (var b in bytes)\n    {\n        builder.Append(b.ToString("x2"));\n    }\n\n    return builder.ToString();\n }	0
2346460	2346436	How to convert object which receives image in bytes into actual image?	byte[] yourImage;\nMemoryStream ms = new MemoryStream(image);\nImage.FromStream(ms);	0
13293962	13293932	Privileges of an Application	WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();	0
18381675	18380604	How to make a drop down read only inside a grid view after binding	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow))\n    {\n\n        DataRow row = ((DataRowView)e.Row.DataItem).Row;\n\n        DropdownList ddlxxx= (DropDownList)e.Row.FindControl("ddlName");               \n         //This will make your ddl readonly \n         ddlxxx.Enabled = false;\n    }\n}	0
5146074	5146061	C# multiline string with html	string output = @"<object>\n                    <node>\n                    <param value=""test"" />\n                    </node>\n                    </object>\n                    ";	0
29093785	29093055	update json object in c#	var json1 = "{ \"name\" : \"sai\", \"age\" : 22, \"salary\" : 25000}";\n        var json2 = "{ \"name\" : \"sai\", \"age\" : 23, \"Gender\" : \"male\"}";\n\n        var object1 = JObject.Parse(json1);\n        var object2 = JObject.Parse(json2);\n\n        foreach (var prop in object2.Properties())\n        {\n            var targetProperty = object1.Property(prop.Name);\n\n            if (targetProperty == null)\n            {\n                object1.Add(prop.Name, prop.Value);\n            }\n            else\n            {\n                targetProperty.Value = prop.Value;\n            }\n        }\n\n        var result = object1.ToString(Formatting.None);	0
29620999	29619858	manage a secure password	// Hash a new password for storing in the database.\n// The function automatically generates a cryptographically safe salt.\nstring hashToStoreInDb = BCrypt.HashPassword(password);\n\n// Check if the hash of the entered login password, matches the stored hash.\n// The salt and the cost factor will be extracted from existingHashFromDb.\nbool isPasswordCorrect = BCrypt.Verify(password, existingHashFromDb);	0
24590262	24590184	C# - Initialize multidimensional array [,] Using a For-Loop to make 100 * 100 int grid	for (int i = 0; i != rows; i++)\n    {\n\n        for (int j = 0; j != columns; j++)\n        {\n            grid[i, j] = number;\n            number++;\n        }\n    }	0
16160863	16160730	Looping a datatable columnwise	DataTable dt1;\n DataTable dt2;\n DataTable dt3;\n string[] ar=new string....\n\n foreach (DataRow dr in dt1.Rows)\n {\n      foreach (DataColumn clm in dt1.Columns)\n      {\n          //loop through each value of the other table\n          foreach(DataRow drow in dt2.Rows)\n          {\n               string value = drow[0].ToString();\n               if(value==clm)\n               {\n                    //add the column name into a array\n                     DataRow row = dt3.NewRow();\n                     row[0]=clm.ColumnName;\n                     dt3.Rows.Add(row);\n                     break;\n               } \n          }\n      }\n }	0
23161670	23145977	How can I get the value of an attribute for a method that has duplicates?	//find method with testcategory attribute\nif (attrs.Any(x => x is TestCategoryAttribute))\n{\n    var testCategoryAttrs = attrs.Where(x => x is TestCategoryAttribute);\n    if (testCategoryAttrs.Any())\n    {\n        foreach (var testCategoryAttr in testCategoryAttrs)\n        {\n            TestCategoryAttribute attr = (TestCategoryAttribute)testCategoryAttr;\n            testCategories += string.IsNullOrEmpty(testCategories)\n                ? string.Join(", ", attr.TestCategories)\n                : string.Format(", {0}", string.Join(", ", attr.TestCategories));\n        }\n    }                               \n}	0
30493000	30492843	AttachUserPolicy from .NET SDK	public virtual AttachUserPolicyResponse AttachUserPolicy(AttachUserPolicyRequest request)	0
232803	232781	build a string using checkbox	StringBuilder builder = new StringBuilder();\nforeach (CheckBox cb in checkboxes)\n{\n    if (cb.Checked)\n    {\n        builder.AppendLine(cb.Text); // Or whatever\n\n        // Alternatively:\n        // builder.Append(cb.Text);\n        // builder.Append(Environment.NewLine); // Or a different line ending\n    }\n}\n// Call Trim if you want to remove the trailing newline\nstring result = builder.ToString();	0
15627393	15626661	Get data from RotateTransform3D	MessageBox.Show((rotation.Rotation as AxisAngleRotation3D).Angle.ToString());	0
996176	987082	C#: How can Server.Mappath read a file?	filedata = File.ReadAllBytes("../../filefolder/myfile.txt");	0
20097738	8894071	SqlBulkCopy cannot access table	GRANT ALTER ON [dbo].[TABLE_XXX] TO [appuser]	0
17009773	17009568	Windows service to save word document	//Create a new timer that ticks every 5 min\nvar t = new System.Timers.Timer (300000);\n\n//When a tick is elapsed\nt.Elapsed+=(object sender, System.Timers.ElapsedEventArgs e) => \n{\n    //Start a new task (thread) that does something\n    System.Threading.Tasks.Task.Factory.StartNew(()=>\n    {\n        AutoSave();\n    });\n};\n//Start the timer\nt.Start();	0
18639982	18635378	Search a XMLNODE	XmlDocument dddd = new XmlDocument();\n            dddd.Load(@"D:\Development\xxxx\xxxxx.xml");\n            XmlNode xnode = dddd.DocumentElement;\n            for (int i = 0; i < xnode.ChildNodes.Count; i++)\n            { \n               if(xnode.ChildNodes[i].Attributes !=null)\n                   foreach (XmlAttribute a in xnode.ChildNodes[i].Attributes)\n                   {\n                       if (a.Name == "ows_Content_x0020_Description")\n                       {\n                           string nameddd = a.InnerText;\n                       }\n                   }\n\n            }	0
10042769	10042675	How to configure StructureMap in a WPF application?	public partial class App : Application\n{\n    protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n\n        //Do your stuff here\n    }\n}	0
3474155	3474135	Multiple inheritance in C#	interface ICustomerCollection\n{\n      void Add(string customerName);\n      void Delete(string customerName);\n}\n\nclass CustomerCollection : ICustomerCollection\n{\n      public void Add(string customerName)\n      {\n            /*Customer collection add method specific code*/\n      }\n      public void Delete(string customerName)\n      {\n            /*Customer collection delete method specific code*/\n      }\n}\n\nclass MyUserControl: UserControl, ICustomerCollection\n{\n      CustomerCollection _customerCollection=new CustomerCollection();\n\n      public void Add(string customerName)\n      {\n            _customerCollection.Add(customerName);\n      }\n      public void Delete(string customerName)\n      {\n            _customerCollection.Add(customerName);\n      }\n}	0
9588427	9588231	Windows Phone using Grid	var rectangleAtXy = grid.Children.OfType<Rectangle>()\n    .SingleOrDefault(c => Grid.GetColumn(c) == x && Grid.GetRow(c) == y);	0
1314703	1314671	How do I find the port number assigned to a UDP client (in .net/C#)?	int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port;	0
20711663	20710848	Returning a list of objects using a list of Ids with LINQ	IQueryable<Patient> query = \n    from b in dbContext.B\n    from a in dbContext.A\n    where a.B_objs.Contains(pr.Id)\n    select b;	0
24739692	24658265	garbled html email	Attachment attachment = new Attachment(this.Attachment);\n            attachment.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;\n            mail.Attachments.Add(attachment);	0
32638561	32635968	Starting a GameWindow in a thread	public class Program : GameWindow {\n    private static void Main(string[] args) {\n        Program display = null;\n        var task = new Thread(() => {\n            display = new Program();\n            display.Run();\n        });\n        task.Start();\n        while (display == null)\n            Thread.Yield(); // wait a bit for another thread to init variable if necessary\n\n        while (true)\n        {\n            Console.Write("> ");\n            var response = Console.ReadLine();\n            //communicate with the display object asynchronously\n            display.Title = response;\n        }\n    }\n}	0
11881779	11881753	Genericising a repository interface	public interface IRepository<T>\n{\n    T NewEntity();\n    T AddOrUpdate(T entity);\n    T GetById(int Id);\n    T GetByNavigation(string NavigationString);\n    IQueryable<T> All();\n}	0
1703413	1703382	C# protected field to private, add property--why?	public string Domain { get; set; }	0
15609997	15595501	How to grab value of selected objects in ObjectListView	foreach (var selectedObject in objectListView1.SelectedObjects) {\n    encClass.sampleFunction(((MyType)selectedObject).Filename, "output here");\n}	0
6391178	6389722	Toolstrip with check button group	foreach (ToolStripButton item in ((ToolStripButton)sender).GetCurrentParent().Items)\n   {\n       if (item == sender) item.Checked = true;\n       if ((item != null) && (item != sender))\n       {\n          item.Checked = false;\n       }\n   }	0
19973580	19972495	Configurable Windows Service - How and where to store configuration	Environment.SpecialFolder.ApplicationData	0
26619409	26618991	Measure CPU cycles of a Function Call	using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nclass Program {\n    static void Main(string[] args) {\n        ulong start, end;\n        start = NativeMethods.GetThreadCycles();\n        System.Threading.Thread.Sleep(1000);\n        end = NativeMethods.GetThreadCycles();\n        ulong cycles = end - start;\n        Debug.Assert(cycles < 200000);\n    }\n\n    static class NativeMethods {\n        public static ulong GetThreadCycles() {\n            ulong cycles;\n            if (!QueryThreadCycleTime(PseudoHandle, out cycles))\n                throw new System.ComponentModel.Win32Exception();\n            return cycles;\n        }\n        [DllImport("kernel32.dll", SetLastError = true)]\n        private static extern bool QueryThreadCycleTime(IntPtr hThread, out ulong cycles);\n        private static readonly IntPtr PseudoHandle = (IntPtr)(-2);\n\n    }\n}	0
34415172	34414722	C# check html tag inside text with regex	var mtch = Regex.Match(input, \n"<div class[ ]?=[ ]?\"bla[^\"]*\"[ ]?>(?<groupName>[\\w\\W]+</div>");\n    if (mtch.Groups["groupName"].Value.ToLower().Contains("followers"))\n    {\n        //do your stuff\n    }	0
15776088	15776041	How to show a gridview, run something in the background and update the gridview with the results	Maybe it can be done with a web service and a javascript call for each value?	0
1165858	1161283	insert text after dynamicly created table in word using VSTO	object oLineUnit = (object) Word.WdUnits.wdLine;\nobject oCountOne = (object) 1;\nobject oCellUnit = (object) Word.WdUnits.wdCell;\n\noSelection.MoveRight(ref oCellUnit, ref missing, ref missing);\noSelection.MoveDown(ref oLineUnit, ref oCountTwo, ref missing);	0
20599442	20599407	Get value and index first low value in array	var topThreeIndex = array.Select((v, i) => new { Index = i, Value = v })\n                         .OrderBy(e => e.Value)\n                         .Take(3);\n\nforeach (var x in topThreeIndex)\n{\n    Console.WriteLine("The number is: " + x.Value + " , index is: " + x.Index)\n}	0
16788091	16787929	Accessing a method defined as `internal` by a FriendAssembly	[assembly: InternalsVisibleTo("OtherAssemblyName")]	0
21904891	21904630	post data to controller from view using viewModel classes -ASP.NET MVC5	public class QualificationViewModel\n{    \n   public Qualification _Qualification {get; set;}\n\n//public Subject _Subject;\n\n//public FeeScheme _FeeScheme;\n\n}\n\n[HttpGet]\npublic ActionResult CreateNewQualification()\n{\n    var Model = new QualificationViewModel();\n    return PartialView("PartialQualification_Create",model);\n\n}	0
16621831	16621569	Android receiving images over tcp socket from c# server	socket.close();	0
23742405	23741918	Format raw varchar field to phone	Picture(CurrentFieldValue,"(XXX) XXX-XXXX")	0
8553099	8552979	Find if int value crossed 0 fast	(prevx ^ x) < 0	0
17759900	17759693	How do i get an object name from its ID?	class Program\n{\n    static List<Person> persons = new List<Person>();\n    static void Main(string[] args)\n    {\n\n\n        Person Luke = new Person();\n        Luke.Update("Luke", 15);\n        Console.WriteLine(Luke.ToString());\n        Person Daniel = new Person();\n        Daniel.Update("Daniel", 14, "Jones");\n        Console.WriteLine(Daniel.ToString());\n        Person Aimee = new Person();\n        Aimee.Update("Aimee", 18, "Jones");\n        Console.WriteLine(Aimee.ToString());\n        Person Will = new Person();\n        Will.Update("William", 22, "Rae");\n        Console.WriteLine(Will.ToString());\n\n        persons.Add(Luke);\n        persons.Add(Daniel );\n        persons.Add(Aimee );\n        persons.Add(Will );\n\n        var founded = FindPersonById("xxx-x-xxxxx");\n\n        Console.ReadLine();\n    }  \n    static Person FindPersonById(int Id)\n    {\n        return persons.FirstOrDefault(p => p.ID == Id);\n    }\n}	0
3144038	3121652	How can i override a base class's == operator, so the override gets called	public class Task\n{\n  string Name;\n  public static bool operator ==(Task t1, Task t2)\n  { \n    if ((object)t1 == null || (object)t2 == null)\n    {\n      return (object)t1 == null && (object)t2 == null;\n    }\n\n    return t1.Name == t2.Name && t1.GetType() == t2.GetType(); }\n  public virtual bool Equals(Task t2)\n  {\n     return this == t2;\n  }\n}\n\npublic class TaskA : Task\n{\n  int aThing;\n  public static bool operator ==(TaskA t1, TaskA t2)\n  { \n    if ((object)t1 == null || (object)t2 == null)\n    {\n      return (object)t1 == null && (object)t2 == null;\n    }\n\n    return (Task)t1 == (Task)t2 && t1.aThing == t2.aThing;\n  }\n  public override bool Equals(Task t2)\n  {\n    return this == t2 as TaskA;\n  }\n}	0
9580425	9580389	How to select add to selected date 1 day using monthcalendar in c#	MessageBox.Show(monthCalendar1.SelectionStart.AddDays(1).ToString());	0
12469375	12469243	Use a single context container to perform multiple queries simultaneously using threads?	foreach (var employee in context.employees.where(...))\n{\n   var department = employee.departments.FirstOrDefault(...);\n}	0
13901582	13901573	String separating in list	string gh = String.Join(",", listitems); //	0
3926316	3926265	problem with C# printing from a serial buffer	string bufferText = System.Text.Encoding.Default.GetString(buffer);\nConsole.WriteLine(bufferText);	0
31706968	30432552	How do I display time column as hh:mm tt in datagridview which is retrieved from MYSQL time field?	dataGridView1.Columns["LOGINTIME"].DefaultCellStyle.Format = @"hh\:mm";	0
15245222	15245141	How to change the colors of bars in Column chart in asp.net	ChartObject.LoadTemplate("templatefile.xml");	0
8662837	8662737	Change an XML node value	var doc = XDocument.Load("video.xml");\ndoc\n    .Element("XML")\n    .Element("VIDEO")\n    .SetElementValue("MAPTEXTURELEVEL", 6);\ndoc.Save("video_modified.xml");	0
28395890	28395839	How to search a list of objects for a specific string attribute using LINQ in C#	private List<Car> Fleet = new List<Car>()\n{\n   new Car("Toyota", "Corola","YI348J", 2007, 7382.33),\n   new Car("Renault", "Megane","ZIEKJ", 2001, 1738.30),\n   new Car("Fiat", "Punto","IUE748", 2004, 3829.33)\n};\n\npublic void addToFleet(String make, String model, String registration, int year, Double costPrice)\n{\n    if(Fleet.Any(car => car.Registration == registration))\n    {\n       // already in there\n    } \n    else\n    {\n      Fleet.Add(new Car(make, model, registration, year, costPrice));\n    }\n}	0
3205563	3205522	universal parsing of strings into float	string s = "1,23";  // or s = "1.23";\n\ns = s.Replace(',', '.');\ndouble d = double.Parse(s, CultureInfo.InvariantCulture);	0
2950089	2950064	Detect when a users session has exipred	private void Page_Load(object sender, System.EventArgs e)\n{ \n\nResponse.AddHeader(?Refresh?,Convert.ToString((Session.Timeout * 60) + 5)); \nif(Session[?IsUserValid?].ToString()==??) \nServer.Transfer(?Relogin.aspx?);\n\n}	0
4118195	4118150	Image splitting into 9 pieces	for (int i = 0; i < 3; i++)\n    {\n        for (int y = 0; y < 3; y++)\n        {\n            Rectangle r = new Rectangle(i*(pictureBox1.Image.Width / 3), \n                                        y*(pictureBox1.Image.Height / 3), \n                                        pictureBox1.Image.Width / 3, \n                                        pictureBox1.Image.Height / 3);\n\n            g.DrawRectangle(pen,r );\n\n            list.Add(cropImage(pictureBox1.Image, r));\n        }\n    }	0
12974789	12974403	Delete and remove the row matching string?	List<DataRow> rowsToRemove = new List<DataRow>();\nforeach (DataRow dr in resE1.Rows)\n{\n    if (dr["Name"].ToString().IndexOf("null") == 0)\n    {\n        dr.SetField("Name", "");\n    }\n    bool hasValue = false;\n    for (int i = 0; i < dr.ItemArray.Count(); i++)\n    {\n        if (!dr[i].ToString().Equals(String.Empty))\n           hasValue = true;\n    }\n    if (!hasValue) rowsToRemove.Add(dr);\n}\nforeach(DataRow dr in rowsToRemove)\n{\n    dr.Delete();\n}	0
9679196	9679160	copy character from the string in c#	String s1 = "My name is testing.";\nString sub = "name is";\nint index = s1.IndexOf(sub);\nString found = s2.Substring(index, sub.Length);	0
16380972	16380909	Get a scrollbar's maximum scroll value	LargeChange - 1	0
22574170	22574130	My date conversion from textbox is working in localhost but not in online server in asp.net c#	DateTime.ParseExact(txtDOB.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)\n                        .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);	0
22035605	21995812	How to find a user from another forest with UserPrincipal.FindByIdentity?	var ctx = new PrincipalContext(ContextType.Domain);\nvar queryCtx = ctx.GetType().GetProperty("QueryCtx", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ctx, null);\nvar ctxBase = (DirectoryEntry)queryCtx.GetType().GetField("ctxBase", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(queryCtx);\nvar srch = new DirectorySearcher(ctxBase);\nsrch.Filter = "(objectSid=S-1-5-21-.......)";\nvar result = srch.FindOne().GetDirectoryEntry();\nvar adUtils = queryCtx.GetType().Assembly.GetType("System.DirectoryServices.AccountManagement.ADUtils");\nvar up = (UserPrincipal)adUtils.GetMethod("DirectoryEntryAsPrincipal", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { result, queryCtx });	0
9044704	8953639	Controller factory per route	public class RouteControllerFactory : IControllerFactory\n{\n    private readonly DefaultControllerFactory Default = new DefaultControllerFactory();\n\n    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)\n    {\n        return (requestContext.RouteData.Values.TryGetValue("controllerfactory") as IControllerFactory ?? Default).CreateController(requestContext, controllerName);\n    }\n\n    public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)\n    {\n        return (requestContext.RouteData.Values.TryGetValue("controllerfactory") as IControllerFactory ?? Default).GetControllerSessionBehavior(requestContext, controllerName);\n    }\n\n    public void ReleaseController(IController controller)\n    {\n        Default.ReleaseController(controller);\n    }\n}	0
2492968	2492903	How to Send user to two different web pages when login	string userType = Authentication(Login2.UserName, Login2.Password);\nif(userType != string.IsNullOrEmpty)\n{\n  if(userType.Equals("yourType")\n    Response.Redirect("firstSite.aspx");\n  elseif //...etc\n}	0
10400816	10400719	Passing Array of Strings to LINQ Stored Procedure	DataClassDataContext db = new DataClassDataContext();\n//storedProc takes 3 params\nstring[] param = GetStringParams();\ngridview.DataSource = db.storedProc(param[0], param[1], param[2]);\ngridview.DataBind();\n\nprivate string[] GetStringParams()\n{\n    //Perform some logic here to determine which params to pass\n    if (somethingIsTrue)\n        return new string[] { "param1", "param2", "param3" };\n    else if (somethingElseIsTrue)\n        return new string[] { "param1", "param2", "" };\n    else\n        return new string[] { "", "", "" };\n}	0
16536923	16535352	how to call web service in ajax properly?	jQuery.ajax({\n            type: 'POST',\n            contentType: 'application/json;',\n            data: '{keyword:"test"}',\n            dataType: 'json',\n            async: true,\n            url: 'SvcADUser.asmx/GetADUserList',\n            success: function (result) {\n                alert(result.d);\n            }\n        });	0
26484571	26484479	How to generate array type using a given type?	string itemTypeName = "System.Int32";\n\n Type itemType = Type.GetType(itemTypeName);\n\n Console.WriteLine(itemType.MakeArrayType());	0
4462679	4462023	c# how to update a field in a dataTable	foreach (DataRow row in tmp.Rows)\n            {\n                row["Description"] = StripTagsCharArray(row["Description"].ToString());\n            }	0
6935333	6935260	how to make a keygen that writes "-" every four letters in C#	for (int i = 0; i < 24; i++)\n{\n    if (i % 5 == 4) {\n        codeArray[i] = '-';\n    } else {\n        int index = random.Next(tokens.Length - 1);\n        codeArray[i] = tokens[index];\n    }\n}	0
18728106	18727828	How to prevent nlog from using config file?	LoggingConfiguration config = new LoggingConfiguration(); //Create configuration object in code\nLogger Log = LogManager.GetCurrentClassLogger(); //Load configuration from xml file	0
8526957	8520950	How to create method for a dynamically added button. asp.net C#	btnView.Click += (sender, e) => {\n    lblbody.Visible = true;\n};	0
6672970	6672958	Get item from entity framework by ID	Entities.Customer.First(c => c.CustomerId == 20);	0
8794605	8794581	How do you set a component property from within a thread without throwing an error in C# .NET?	someControl.BeginInvoke(new Action(delegate { ... }));	0
22941885	22941726	Ignore property in xml serialization	/// <summary>\n    /// This property does something\n    /// </summary>\n    /// <returns></returns>\n    [XmlIgnore]\n    public string CustomErrorMessageADF { get; set; }	0
21890154	21890066	Insert image in 1 column in datagridview	object[] row = new object[] { image, "string 1", "string 2" };\nmyDataTable.Rows.Add(row);	0
26037583	26037544	How to limit property setter to NOT receive values below zero?	public decimal Balance \n { \n    get { return balance; }\n    private set\n    {\n       if (value < 0)\n          throw new ArgumentOutOfRangeException("Only positive values are allowed");\n\n       balance = value;\n    }\n}	0
10860767	10860222	Shopping Cart Using Cookies	Request.Cookies["UserInfo"]["items"]	0
15593547	15593540	Access variable inside while loop from outside (C#)?	Double MAX = 0;\nwhile (Condition)\n            {    \n\n                MAX = somecode.....\n                                      .....\n            }\n\n            Console.WriteLine("The OPTIMAL Value : " + MAX);	0
18239646	18238561	How to run nested batch file programatically using C#	'.\stop.bat' is not recognized as an internal or external command,	0
18339647	18339366	XAML - How do I programmatically create a Path from mini-markup?	Path o = (Path)XamlReader.Load(String.Format(@"<Path xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Data=""{0}"" />", pathData));	0
16453269	16453237	how to stop data from adding into the database even when the textboxes are empty in asp?	SqlConnection conn = new SqlConnection(\n    if(txtFirstName.Text != "" && txtLastName.Text != "" && txtvercode.Text = "")//And so on...\n    {\n        @"Data Source=(LocalDB)\v11.0; AttachDbFilename='|DataDirectory|\employees.mdf';\n        Integrated Security=True");\n\n        conn.Open();\n\n        SqlCommand cmd = new SqlCommand("INSERT INTO membership (FirstName, LastName, MembershipClass, VerificationCode) VALUES ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + dropmemberclass.Text + "', '" + txtvercode.Text + "')", conn);\n\n        cmd.ExecuteNonQuery();\n\n        txtFirstName.Text = "";\n        txtLastName.Text = "";\n        txtvercode.Text = "";\n        txtMemID.Text = "";\n        txtmemdelete.Text = "";\n        lblMemID.Text = "";\n        lblMemIDSearch.Text = "";\n    }\n}	0
2243222	2243158	delete files from folder	Array.ForEach(Directory.GetFiles(path), File.Delete);	0
20113913	20113864	Regex - replace spaces	string input = "you     string    ";\nstring result = new Regex(@"[ ]+").Replace(input, " ").Trim();	0
8493523	8481372	Outlook Add-on to Add Text to Mail Body	private void ThisAddIn_Startup(object sender, System.EventArgs e)\n{\n   this.Application.NewMailEx += new Outlook.ApplicationEvents_11_NewMailExEventHandler(olApp_NewMail);\n}\n\nprivate void olApp_NewMail(String entryIDCollection)\n{\n   Outlook.NameSpace outlookNS = this.Application.GetNamespace("MAPI");\n   Outlook.MAPIFolder mFolder = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);\n   Outlook.MailItem mail;\n\n   try\n   {\n      mail = (Outlook.MailItem)outlookNS.GetItemFromID(entryIDCollection, Type.Missing);\n      if (mailItem.Subject.StartsWith("ABCDE"))\n      {\n         mailItem.BodyFormat = OlBodyFormat.olFormatHTML;\n         mailItem.HTMLBody = "<html><body>Click <a href='www.google.com'>here</a>.<br><br></body></html>" + mailItem.HTMLBody;\n         mailItem.Save();\n      }\n   }\n   catch\n   {}\n}	0
24067191	24066416	Cannot retrieve explicit interface implemented member	var explicitDispose = myType.GetMembers("System.IDisposable.Dispose").SingleOrDefault();	0
14746098	14744615	DataGridView control must be bound to an IBindingList object to be sorted	class MyDataGridView : DataGridView\n{\n    public MyDataGridView()\n    {\n        base.DataBindingComplete += Sort;\n    }\n\n    public void Sort(object sender, EventArgs e)\n    {\n        Sort(Columns[0], ListSortDirection.Ascending);\n        Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Ascending;\n    }\n}	0
8333465	8333343	Print fibonacci numbers up tp 15,000 C#	static void main() \n    {\n        int num1 = 0;\n        int num2 = 1;\n        int sum = 1;\n        Console.WriteLine(num1);\n        while (sum < 40000)\n        {\n           sum = num1 + num2;\n           num1 = num2;\n           num2 = sum;    \n           Console.WriteLine(num2);\n        }\n    }	0
1996468	1996434	How to select static text with LINQ query?	string[] additionalItems = {"All Items"};\n\nlistbox1.ItemsSource = (from Car c in Cars\n                       select c.Model)\n                       .Union(additionalItems);	0
9789168	9787649	ASP.NET Treeview control always appending nodes to CheckedNodes list	cleanedlists = string.Join(",", tv.CheckedNodes.Cast<TreeNode>().Select(tn => tn.ValuePath).ToArray());	0
13427052	13426996	DataGridView override Painting to set font	dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) { e.Column.HeaderText = e.Column.HeaderText.ToUpper(); }	0
4602516	4602451	How to specify range criterial for field in MongoDb for C# driver	var collection = Database.GetCollection<Type>("collection");\nvar mongoQuery = Query.GT("field", value1).LT(value2);\nvar list = collection.Find(mongoQuery);	0
1977325	1977315	How to save a human readable file	XmlSerializer serializer = new XmlSerializer(typeof(Person));	0
4285482	4285477	Can a class implement two interfaces at the same time?	class Student: IPersonalDetails, IOtherDetails\n{\n      //Code\n}	0
4570170	4570060	Reactive Extensions - Pumping items from one collection to another	list1.ToObservable() // Convert list1 to Observable\n    .Zip(\n        Observable.Interval(TimeSpan.FromSeconds(1)), // Zip it with an observable that ticks every second\n        (list, timerList) => list // select list1 only\n    ).\nSubscribe((item) =>\n{\n    list2.Add(item); // on each tick, add an item to list2\n});	0
4747900	4747874	regex for weak password	"^(?!password)(?!12345)"	0
11655758	11655709	Making a layered frame visible with Frame View	fraSelect_2.Location = fraSelect_1.Location;\n   fraSelect_2.Size = fraSelect_1.Size;\n   ... // move every other groupbox to the same spot....	0
24736694	24736186	Using HttpClient from scriptcs script	#r "System.Net.Http"	0
16965991	16963077	How Can I Move The Window Like I Want With WinApi	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    public struct WINDOWPOS\n    {\n        public IntPtr hwnd;\n        public IntPtr hwndInsertAfter;\n        public int x;\n        public int y;\n        public int cx;\n        public int cy;\n        public uint flags;\n    }\n\n    public const int WM_WINDOWPOSCHANGING = 0x46;\n\n    protected override void WndProc(ref Message m)\n    {\n        switch (m.Msg)\n        {\n            case WM_WINDOWPOSCHANGING:\n                WINDOWPOS wp = (WINDOWPOS)System.Runtime.InteropServices.Marshal.PtrToStructure(m.LParam, typeof(WINDOWPOS));\n                if (true) // ... if somecondition ...\n                {\n                    // modify the location with x,y:\n                    wp.x = 0;\n                    wp.y = 0;\n                }\n                System.Runtime.InteropServices.Marshal.StructureToPtr(wp, m.LParam, true);\n                break;\n        }\n\n        base.WndProc(ref m);\n    }\n\n}	0
29040286	29040136	In Asp.Net 2.0 Identity as I have only enable a role to log in a aplication?	var user = await UserManager.FindByEmailAsync(model.Email);\n\nif (user != null)\n{\n    if(await UserManager.IsInRoleAsync(user.Id, "YourApprovedRole"))\n    {\n        // Sign in\n    }\n    else\n    {\n        // Error\n    }\n}	0
16349049	16348743	Are there any difference in using File.Copy to move a file or to write a stream to the location?	File.Copy	0
13916288	13879038	MarshlDirectiveException in C# when trying to pass BSTR* from COM Component	string someString = "TestME";\n_bstr_t s(someString.c_str());\n*returnme = SysAllocString((BSTR)s);	0
10268457	10268435	Serialize object of multiple classes into a single JSON using Json.NET	JsonConvert.SerializeObject(new {\n    data = new[] { ... },\n    summary = ...\n});	0
25314734	22032290	web browser control + authentication	public static Uri addCredsToUri( Uri u, string user, string pass )\n{\n    UriBuilder uriSite = new UriBuilder( u );\n    uriSite.UserName = user;\n    uriSite.Password = pass;\n    return uriSite.Uri;\n}	0
16925861	16925676	In MVC4, how do I do my own check on user login and password?	Membership.ValidateUser	0
13464572	13464471	How to refactor a sequence of if-then statements?	private class VersionSpec\n    {\n        public string Address { get; private set; }\n        public string CellValue { get; private set; }\n        public string Version { get; private set; }\n\n        public VersionSpec (string address, string cellValue, string version)\n        {\n            Address = address;\n            CellValue = cellValue;\n            Version = version;\n        }\n    }\n\n    public string getVersion(Excel._Worksheet sht)\n    {\n        VersionSpec[] versionSpecs = new []\n        {\n            new VersionSpec("a4", "Changes for Version 24", "24"),\n            new VersionSpec("a1", "Changes for Version 23 (Official)", "23"),\n            new VersionSpec("a2", "Changes for Version 22", "22"),\n            // other versions...\n        }\n\n        foreach(VersionSpec versionSpec in versionSpecs)\n        {\n            if(checkContents(sht, versionSpec.Address, versionSpec.CellValue))\n            {\n                return versionSpec.Version;\n            }\n        } \n    }	0
3490926	3490777	How, for example, to make a binding with constructor arguments to a Bitmap with Ninject?	Bind<IDisposable>().ToConstant(new Bitmap(10, 22));	0
5537288	5537228	Looping through all system files & folders using C++ CLI	static void ScanMyDir( String^ SourceDir)\n{\narray <String^> ^fileEntries = Directory::GetFiles(SourceDir);\nfor each  (String^ fileName in fileEntries)\n{\nConsole::WriteLine(fileName);\n}\narray<String^> ^SubDirEntries = Directory::GetDirectories(SourceDir);\nfor each (String^ subdir in SubDirEntries)\nif ((File::GetAttributes(subdir) & FileAttributes::ReparsePoint)!= FileAttributes::ReparsePoint)\n            ScanMyDir(subdir);\n}\n};	0
24092450	24092366	LINQ XML Document	var xDoc = XDocument.Load("path");\n\nvar pictures = xDoc.Root\n           .Elements("Picture")\n           .Select(x => new \n                        {  \n                            source = (string)x.Element("Source"),\n                            title = (string)x.Element("Title")\n                        }).ToList();	0
25363378	25363233	WP8 Xml parser in C#	XDocument xDoc = XDocument.Load("your xml file");\nforeach (var elem in xDoc.Document.Descendants("artist"))\n{\n    names.Add(elem.Attribute("name").Value);\n}	0
12289899	12289832	Retrieve ODBC table and Insert into SQL Server CE database	commandD.Parameters.Add("@sql",SqlDbType.NVarChar, 5); \nwhile (reader.Read()) \n{ \n  string x = reader[0].ToString();                   \n  commandD.Parameters["@sql"].Value = x ;\n  commandD.ExecuteNonQuery();      \n}	0
11598166	11598094	Returning a Dataset as an Object in a Method	private void GetData()\n    {\n        //from inside some method:\n        DataSet ds = GetProgramList();\n    }\n\n    protected DataSet GetProgramList()\n    {\n        DataSet ds1 = new DataSet();\n        using (SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;"))\n        {\n            using (SqlDataAdapter da = new SqlDataAdapter(@"SELECT ProgramName FROM Program", cn))\n                da.Fill(ds1, "TableName1");\n        }\n        return ds1;\n    }\n    //\n\n\n//1. solution:\nclass YourClass\n{\n    DataSet ds1;\n    protected void GetProgramList()\n    {\n        SqlConnection cn = new SqlConnection("server=Daffodils-PC/sqlexpress;Database=Assignment1;Trusted_Connection=Yes;");\n        SqlCommand cmd = new SqlCommand("SELECT ProgramName FROM Program", cn);\n        SqlDataAdapter da = new SqlDataAdapter(cmd);\n        ds1 = new DataSet();\n    }\n}	0
23072737	23072711	How to convert a two-character string @"\n" into actual char '\n'?	string replaced = original.Replace("\\n", "\n");	0
2113925	2113779	Can someone explain this C# lambda syntax?	class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(GetFunc());   //Prints the ToString of a Func<int, string>\n        Console.WriteLine(Test(5));     //Prints "test"\n        Console.WriteLine(Test2(5));    //Prints "test"\n        Test2 = i => "something " + i;\n        Console.WriteLine(Test2(5));    //Prints "something 5"\n        //Test = i => "something " + i; //Would cause a compile error\n\n    }\n\n    public static string Test(int a)\n    {\n        return "test";\n    }\n\n    public static Func<int, string> Test2 = i =>\n    {\n        return "test";\n    };\n\n    public static Func<int, string> GetFunc()\n    {\n        return Test;\n    }\n}	0
27272761	27272709	Retrieving a generic type value from an object dictionary without exceptions	using System;\nusing System.Collections.Generic;\n\npublic static class DictionaryExtensions\n{\n    public static T GetValue<T>(this Dictionary<string, object> dictionary, string key)\n    {\n        object value = null;\n        if (!dictionary.TryGetValue(key, out value))\n        {\n            throw new KeyNotFoundException(key);\n        }\n\n        return (T)Convert.ChangeType(value, typeof(T));\n    }\n}	0
1502479	1502451	What needs to be overriden in a struct to ensure equality operates properly?	public struct Complex \n{\n   double re, im;\n   public override bool Equals(Object obj) \n   {\n      return obj is Complex && this == (Complex)obj;\n   }\n   public override int GetHashCode() \n   {\n      return re.GetHashCode() ^ im.GetHashCode();\n   }\n   public static bool operator ==(Complex x, Complex y) \n   {\n      return x.re == y.re && x.im == y.im;\n   }\n   public static bool operator !=(Complex x, Complex y) \n   {\n      return !(x == y);\n   }\n}	0
7101701	7100850	how to get xml data from a sp that has for xml using sql helper	SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConStr);\ndtxml = SqlHelper.ExecuteXmlReader(conn, \n      CommandType.StoredProcedure, "dbo.PR_GENERATE_INVOICE_XML", a);	0
15269550	15264996	Save each row in gridview that was built manually	conn.Open();\n\nusing(SqlCommand cmd = new SqlCommand(sql, conn))\n{\n    var now = DateTime.Now;\n\n    foreach (GridViewRow row in GridView1.Rows)\n    {\n        string myPart = row.Cells[0].Text;\n        string myQuantity = row.Cells[1].Text;\n        string myPrice = row.Cells[2].Text;\n        //... etc\n\n        cmd.Parameters.Clear();\n        cmd.Parameters.AddWithValue("@Item", myPart);\n        cmd.Parameters.AddWithValue("@Quantity", myQuantity);\n        cmd.Parameters.AddWithValue("@Price", myPrice);\n        cmd.Parameters.AddWithValue("@ModelID, methodID);\n        cmd.Parameters.AddWithValue("@DateCreatedOn, now);\n\n        cmd.ExecuteNonQuery();\n    }\n}\n\nconn.Close();	0
17008436	17008325	C# Creating A Remember me	Response.Cookies("userName").Value = "mike"\nResponse.Cookies("userName").Expires = DateTime.Now.AddDays(1)	0
3461800	3461729	Adding only new items from one list to another	list1.AddRange(list1.Except(list2));	0
21027225	21005978	SignedXml.CheckSignature only returns true if I verify with private key	rsa.FromXmlString	0
23639804	23639766	Remove item from Observable Collection in Nested Foreach - WPF	foreach (var item1 in ocChoicesinItem.ToList())\n    {\n        foreach (var item2 in temp.ItemsInInvoiceChoices)\n        {\n            if (item1.ChoicesId == item2.ChoicesId)\n                ocChoicesinItem.Remove(item1);\n        }\n    }	0
33658204	33657892	Deleting longest line from txt	foreach (string line in lines)\n     {\n        if (String.IsNullOrWhiteSpace(line)) \n        {\n            lines.Delete(line);\n            Continue;\n        }\n        if (line.Length >= longestLine) // ">=" instead of "==" just to be on the safe side\n        {\n           lines.Delete(line);\n        }\n    }	0
21881194	21881075	Get all items from html select list using ASP.net C#	var ddlArray= new Array();\nvar ddl = document.getElementById('Context');\nfor (i = 0; i < ddl.options.length; i++) {\n    ddlArray[i] = ddl .options[i].value;\n}	0
24865006	24864710	Filtering data row value in column DataGridView with value inside two textbox	DataView dv = ((DataTable)DataGridValue.DataSource).DefaultView;\ndv.RowFilter = "ColumnName < TB1 AND ColumName > TB2"\nAfterwards bind the DataView to your gridView	0
30695844	30695717	Multiple listboxes created dynamically with event	public void LBTest_SelectionChanged(object sender, EventArgs e, int i)\n{\n   ListBox lst = sender as ListBox;\n   if (lst.Name ==  "listBox1")\n    {\n       // do something here according to..        \n    }\n}	0
21353529	21353499	how to set variable value from aspx.cs file to aspx file in asp.net?	protected int PageId;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n   PageId = 12; // some value \n   Image1.ImageUrl ="ImageCSharp.aspx?ImageID=" + PageId;\n}	0
11386115	11386011	C# app blocks when calling method from dll	extern "C" __declspec(dllexport) \nint hello(char* buffer, int bufferSize);	0
12253449	12253082	Generating namespaced XML	XNamespace fed = "http://docs.oasis-open.org/wsfed/federation/200706";\n        XNamespace auth = "http://docs.oasis-open.org/wsfed/authorization/200706";\n\n        XElement root = new XElement(auth + "ClaimType",\n            new XAttribute(XNamespace.Xmlns + "auth", auth.NamespaceName),\n            new XAttribute("Uri", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"),\n            new XAttribute("Optional", "true"),\n            new XElement(auth+"DisplayName", "EmployeeID"),\n            new XElement(auth+"Description", "The employee's designated ID number.")\n        );\n\n        Console.WriteLine(root);	0
3417405	3417367	Using an If statement to determine if a method has been called	class MyClass {\n  private bool m_myFunctionCalled = false;\n\n  public void myFunction() {\n    m_myFunctionCalled = true;\n    return;\n  }\n}	0
26287723	26287686	Return unique values without removing duplicates - C#	var singleOccurrences = array.GroupBy(x => x)\n                             .Where(g => g.Count() == 1)\n                             .Select(g => g.Key)\n                             .ToArray();	0
27651305	27651138	How to correctly use ProcessCmdKey in a calculator windows form application?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n        {\n            int intKey = (int)keyData;\n            if (intKey >= 96 && intKey <= 105) // 96 = 0, 97 = 1, ..., 105 = 9\n            {\n                textBox1.Text = textBox1.Text + (intKey - 96).ToString();\n                return true;\n\n            }\n            // ... and the if conditions for other operators\n            return base.ProcessCmdKey(ref msg, keyData);\n        }	0
7829529	554314	How can I convert an integer into its verbal representation?	public string DecimalToWords(decimal number)\n{\n    if (number == 0)\n        return "zero";\n\n    if (number < 0)\n        return "minus " + DecimalToWords(Math.Abs(number));\n\n    string words = "";\n\n    int intPortion = (int)number;\n    decimal fraction = (number - intPortion)*100;\n    int decPortion = (int)fraction;\n\n    words = NumericToWords(intPortion);\n    if (decPortion > 0)\n    {\n        words += " and ";\n        words += NumericToWords(decPortion);\n    }\n    return words;\n}	0
33066128	33046653	Xamarin subclassed UINavigationController with custom UINavigationBar	public ZooNavigationController () : base (typeof (YourNavigation), typeof(YourBar)) {\n   // Your own initialization goes here\n}	0
21974015	21971432	Update inner list in object with other collection	dailyInputData.Zip(valueToUpdate, (input, val) => new dailyInputData { myProperty = val });	0
27854611	27854527	Get image file name from PhotoChooserTask wp 8	public static string GetFileName(string path)\n{\n    return new Regex(@".+\\(\S+\.\S+)", RegexOptions.IgnoreCase).Match(path).Groups[1].Value;\n}	0
26947243	26947201	Regex to remove all spaces, periods and other non-word characters from a string	string repl = Regex.Replace(title, @"[^\w@-]", "", TimeSpan.FromSeconds(1.5));	0
21259783	21259681	How can i select the whole row/line when clicking on a line in a textbox in C#	// now you need to know what character index starts that line\nvar start = textBox.GetFirstCharIndexOfCurrentLine();\n\n// and with the line already in hand we can calculate the ending index\nvar end = start + textBox.Lines(textBox.GetLineFromCharIndex(start)).Length;\n\n// now select that range\ntextBox.Select(start, end);	0
29622519	29622433	Access static variables by their names	typeof(SomeClass).GetField("radius").SetValue(null, val);	0
9718728	9718590	Access application setting by name	var x = Properties.Settings.Default.Properties["NameXX"];\nif(x != null) {\n //....\n}	0
8116344	8116282	Disabling F10 key from moving focus to menu bar in C# Winforms program	private void form_KeyDown(object sender, KeyEventArgs e)\n{ if(e.KeyData == Keys.F10)\n    {\n        // Do what you want with the F10 key\n        e.SuppressKeyPress = true;\n    }\n}	0
28397205	28397068	4 Vector2 points to top left top right bottom left bottom right	public Vector2[] directions=new Vector2[4];// put your vectors here\n\n\n     void Sort() \n     {\n      Array.Sort(directions, Vector2Compare);    \n     }\n\n\n     private int Vector2Compare(Vector2 value1, Vector2 value2)\n     {\n         // NOTE: THESE DEPENDS ON HOW YOU EVALUATE TOP/LEFT/RIGHT/BOTTOM , X and Y  \n         if (value1.x < value2.x)\n         {\n             return -1;\n         }\n         else if(value1.x == value2.x)\n         {\n             if(value1.y < value2.y)\n             {\n                 return -1;\n             }\n             else if(value1.y == value2.y)\n             {\n                 return 0;\n             }\n             else\n             {\n                 return 1;\n             }\n         }\n         else\n         {\n             return 1;\n         }\n     }	0
5208864	5208806	Using PropertyChanged from reflection	Delegate dg = Delegate.CreateDelegate(et, value, mi);	0
5363683	5363678	Variable name for a 2-valued variable passed as boolean?	enum EntityColors\n{\n  blue,\n  red\n};	0
24891178	24890254	How to insert update multiple data in DB through entity framework	public partial class Contact\n{\n    public int ContactID { get; set; }\n    public string ContactPerson { get; set; }\n    public string EmailID { get; set; }\n}\n\nvar _Contact=new list<Contact>();\n_Contact.add(new Contact(){ContactID=1,ContactPerson="Dev",EmailID="d@gmail.com"});\n_Contact.add(new Contact(){ContactID=2,ContactPerson="Ross",EmailID="a@gmail.com"});\n_Contact.add(new Contact(){ContactID=3,ContactPerson="Martin",EmailID="b@gmail.com"});\n_Contact.add(new Contact(){ContactID=4,ContactPerson="Moss",EmailID="c@gmail.com"});\n_Contact.add(new Contact(){ContactID=5,ContactPerson="Koos",EmailID="q@gmail.com"});\n\n// check by Primary key\ncontext.Contacts.AddOrUpdate(_Contacts)\n// or check by EmailID\ncontext.Contacts.AddOrUpdate(p => p.EmailID, _Contacts)	0
10803351	10803174	server side display string width	using System;\nusing System.Windows.Forms;\nusing System.Drawing;\n\nnamespace TextMeasureExample\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine(TextRenderer.MeasureText("This is some text", new Font("Arial", 0.75f)));\n        }\n    }\n}	0
23641154	23641068	Populating ListBox with predefined layout	public partial class Page\n{\n    public String Name { get; private set; }\n    public String Icon { get; private set; }\n\n    public Page(String name, String icon)\n    {\n        Name = name;\n        Icon = icon;\n    }\n}	0
72908	72556	Hot to commit changes for a TreeView while editing a node (C#)?	treeView.LabelEdit = false;\ntreeView.LabelEdit = true;	0
21463853	21435550	Culture-Specific Handling of Number Pad Decimal Key in Windows Forms	protected override void OnKeyDown(KeyEventArgs e)\n{\n    if (e.KeyData == Keys.Decimal)\n        m_DecimalKey = true;\n}\n\nprotected override void OnKeyPress(KeyPressEventArgs e)\n{\n    ...\n    if (m_DecimalKey || e.KeyChar == CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator)\n    {\n        // this is a decimal separator\n    }\n}\n\nprotected virtual void OnKeyUp(KeyEventArgs e)\n{\n    if (e.KeyData == Keys.Decimal)\n        m_DecimalKey = false;\n}	0
29909634	29909569	Getting Current CultureInfo in a class	CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;	0
2500274	2500223	How to ignore blank elements in linq query	var usersInDatabase =\n    from user in licenseUserTable\n    where \n        (user.FirstName == first_name || first_name == string.Empty) &&\n        (user.LastName == last_name || last_name == string.Empty)\n    select user;	0
5133910	5115397	C# Parse xml Attriubte with name a and write it with name b	XDocument doc = XDocument.Load("<path to input xml document>");\nforeach (var element in doc.Descendants("AttributeA"))\n{\n    element.Name = "AttributeB";\n}\ndoc.Save("<path to output xml document>");	0
24285104	24284976	LINQ with EF6: Losing second reference in two column table	context.NeighbourCountries\n         .Include(m => m.Neighbour)\n         .Include(m => m.Source)\n         .Where(b => b.Neighbour.CountryID == paracountry.CountryID).FirstOrDefault();	0
2404211	2404193	How can I access the next value in a collection inside a foreach loop in C#?	for(int i=0; i<list.Count-1; i++)\n   Compare(list[i], list[i+1]);	0
22749038	22748678	How to get 2 level of directory?	using System;\nusing System.IO;\nusing System.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.BufferHeight = 500;\n            listDirec(@"c:\program files", 1, 2);\n            Console.ReadKey();\n        }\n\n        static void listDirec(string path, int start, int end)\n        {\n            var dirInfo = new DirectoryInfo(path);\n            var folders = dirInfo.GetDirectories().ToList();\n\n            foreach (var item in folders)\n            {\n                Console.WriteLine("".PadLeft(start * 4, ' ') + item.Name);\n\n                if (start < end)\n                    listDirec(item.FullName, start + 1, end);\n            }\n        }\n    }\n}	0
23353727	23353534	How to store language specific text in C#/WPF application	Thread.CurrentThread.CurrentUICulture	0
10871034	10870943	Instantiating custom C# classes from IronPython	import clr\nclr.AddReference('MyAssembly.dll')\nimport MyClass\nobj = MyClass("Hello, World!")\nobj.Write()	0
6703450	6703415	To read a .txt File of a particular Encoding type in C#	StreamReader sr = new StreamReader(@"C:\CreateAsciiFile.txt",true);\nstring LineText= sr.ReadLine();\nSystem.Text.Encoding enc = sr.CurrentEncoding;	0
13452295	13451877	How to navigate in WPF using PRISM and bind DataContext	public event PropertyChangedEventHandler PropertyChanged = delegate {};\n\n\npublic MyDomainObject MyDomainObject\n{\n    get\n    {\n        return myDomainObject;\n    }\n    set\n    {\n        if(value != myDomainObject)\n        {\n            myDomainObject = value;\n            RaisePropertyChanged("MyDomainObject");\n        }\n    }\n}\n\nprivate void RaisePropertyChanged(String p)\n{\n    PropertyChanged(this, new PropertyChangedEventArgs(p));\n}	0
2462597	2462565	how to insert date & time to DateTimePicker in C#?	myDatePicker.Value = new DateTime(2009, 3, 8, 6, 45, 0);	0
4454584	4454019	Get windows group members along with their domain names	public DirectoryEntry FindDomain(DirectoryEntry memberEntry) \n           {\n\n                if(memberEntry.SchemaClassName.ToLower().Contains("domain") \n                {\n                       return memberEntry;\n                }   \n                if(memberEntry.Parent !=null) \n                {\n                         return FindDomain(memberEntry.Parent);\n                }\n                return null;\n           }	0
21034470	20942733	how to post on facebook wall for specific list of users using asp.net c#?	POST graph.facebook.com\nme/feed?message="hello"&privacy={"value": "CUSTOM", "allow": "1234567890"}	0
15833450	15822883	Camera to follow player but 'snap' to screen boarders	public void Move(float x, float y, Camera2D Camera)\n{\n\n    Position.X += x;\n\n    if ((Position.X < Camera.Min.X))\n       Position.X = Camera.Min.X;\n\n    if ((Position.X + Width) > Camera.Max.X)\n       Position.X = Camera.Max.X - Width;\n\n    float centerX = Position.X + (Width / 2);\n\n    if (centerX > (Camera.Min.X + (ScreenDimension.X / 2)))\n    {\n        if (centerX < (Camera.Max.X - (ScreenDimension.X / 2)))\n        {\n            Camera.Move(-x, 0);\n        }\n        else\n        {\n            Camera.SetPosition(-(Camera.Max.X - ScreenDimension.X), Camera.Position.Y);\n        }\n    }\n    else\n    {\n        Camera.SetPosition(Camera.Min.X, Camera.Position.Y);\n    }\n\n    // Removed Y because of code length\n\n}	0
835165	834907	Single click to open menu for tray icon in C#	private void notifyIcon1_Click(object sender, EventArgs e)\n        {\n            contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);\n        }	0
33593043	33592856	C# ASP.NET Passing if else statement string value to another string	public partial class Reports : System.Web.UI.Page\n{\n\n   private string myquery = string.Emplty; //Try use this\n    MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);\n\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n\n       usertype = Session["usertype"].ToString();\n\n            if (usertype == "admin")\n            {\n                myquery = @"SELECT jobId, odometerReading, jobDescription, status  FROM joborder Where truck_id = '" + truck_id + "'";\n            }\n            else\n            {\n                myquery = @"SELECT jobId, odometerReading, jobDescription, status  FROM joborder Where truck_id = '" + truck_id + "' and status = '1'";\n            }\n\n        connectDB();\n     }\n}	0
33002375	25842008	set caret position to last character in masked text box - winform?	''' <summary>\n'''  Set Caret Position to specific location and remove data After given Location\n''' </summary>\n''' <param name="MaskedTb"> Masked textbox</param>\n''' <param name="Loct99">Location (Index) after which remove occured and caret is set</param>\n''' <remarks></remarks>\nPublic Sub FocsToMaskedTb( MaskedTb As MaskedTextBox, ByVal Loct99 As Integer)\n    If MaskedTb.Text.Length >= Loct99 Then\n        MaskedTb.Text = MaskedTb.Text.Remove(Loct99)\n    End If\n    MaskedTb.SelectionStart = MaskedTb.MaskedTextProvider.LastAssignedPosition + 1\n    '' I am using MaskedTextProvider Property\n    '' If there is nothing in TextBox, MaskedTb.MaskedTextProvider.LastAssignedPosition = -1\nEnd Sub	0
6309306	6309254	A way to pretty print a C# object	ToString()	0
23832056	23822527	How to set FxCop installation path using SonarQube's C# plugin	sonar.cs.fxcop.fxCopCmdPath	0
6649218	6649174	How to use $push update modifier in MongoDB and C#, when updating an array in a document	unicorns.Update(Query.EQ("name", "Aurora"), Update.Push("loves", "sugar"));	0
13275413	13275207	Get absolute path of relative path	string mslinepath = ResolveUrl("~/Charts/MSLine.swf")	0
9096052	9095963	Regular Expression For HTML Tag	"</?[a-zA-z]* ?/?>"	0
7372162	7372125	How to add a ListItem into a list while iterating (C#)?	while (true)\n {\n       foreach (T item in new List<T>( list ))\n       {\n          ....\n       }\n       Thread.Sleep(500);\n }	0
21027740	21027157	Export to CSV without writing to file system	using (FileStream file = new FileStream("somename.csv", FileMode.Create, FileAccess.Write)) {\n    myMemoryStream.WriteTo(file);\n}	0
10246088	10245717	Drawing signal with a lot of samples	public IEnumerator<T> GetEnumerator(int start, int count, int skip)\n{\n    // assume we have a field in the class which contains the data as a List<T>, named _data\n    for(int i = start;i<count && i < _data.Count;i+=skip)\n    {\n        yield return _data[i];\n    }\n}	0
5983046	5982819	Loading FlowDocument.xaml that is part of my solution	FlowDocument doc= Application.LoadComponent(new Uri("/Path/FlowDocument.xaml", UriKind.RelativeOrAbsolute)) as FlowDocument;	0
14945683	14945268	Link table in EntityFramework	public virtual ICollection<RoleUser> RoleUsers {get;set;}	0
12494384	12494159	C#, How to count the variables that have values > 0	static void Main(string[] args)\n{\n    var seq = Enumerable.Range(0, 12).Select(i => (decimal)i);\n    Console.WriteLine(GetGreaterThanZero(seq));\n\n    var arr = seq.ToArray();\n    SetMinNull(arr);\n    foreach(var n in arr)\n        Console.WriteLine(n);\n}\n\nstatic int GetGreaterThanZero(IEnumerable<decimal> numbers)\n{\n    return numbers.Count(n => n > 0);\n}\n\nstatic void SetMinNull(decimal[] numbers)\n{\n    decimal min = numbers.Min();\n\n    // edit: credits to daniel for this loop\n    for(int i = 0; i < numbers.Length; i++)\n    {\n        if(numbers[i] == min) numbers[i] = 0;\n    }\n}	0
13638484	13638346	List<string> Custom Sorting	List.Sort((x, y) => x.Substring(x.IndexOf(">") + 1, 1).CompareTo(y.Substring(y.IndexOf(">") + 1, 1)));	0
9327848	9327608	Rhino Mocks. How to add expectation that event handler was subscribed	_viewMock.Expect(x => x.SomeEvent+= Arg<EventHandler<MyEventArgs>>.Is.Anything); \n\nPresenter p = new Presenter(_viewMock);\n\n_mockRepository.ReplayAll();\n\n...\n\n_mockRepository.VerifyAll();	0
11298010	11297757	DataGridView Sort - Keep two in sync	bool Grid1Fired = false;\nbool Grid2Fired = false;\n\nvoid handler_Grid1(..)\n{\n    if(Grid1Fired == false && Grid2Fired == false)\n    {\n        Grid1Fired = true;\n        SortGrids();\n    }\n}\nvoid handler_Grid2(..)\n{\n    if(Grid1Fired == false && Grid2Fired == false)\n    {\n        Grid2Fired = true;\n        SortGrids();\n    }\n}\n\nvoid SortGrids()\n{\n    if(Grid1Fired)\n    {\n        // sort grid 2\n    }\n    else if(Grid2Fired)\n    {\n        // sort grid 1\n    }\n    Grid1Fired = false;\n    Grid2Fired = false;\n}	0
29722484	29722453	C# initializing date with AddDays	DateTime TheDate = DateTime.UtcNow.AddDays(-180).Date;	0
26654398	26653113	TableLayoutPanel Winforms not showing all information	pnlLorries.Controls.Clear();\n  DateTime dt_start = monthView1.SelectionStart;\n  DateTime dt_end = monthView1.SelectionEnd;\n  int rowCounter = 0;\n  for (DateTime dt = dt_start; dt.Date <= dt_end; dt = dt.AddDays(1))\n  {\n    Label lbl = new Label();\n    Font ft = new System.Drawing.Font("Calibri", 12);\n    lbl.Text = dt.ToShortDateString();\n    lbl.Font = ft;\n    pnlLorries.Controls.Add(lbl, 0, rowCounter);\n    rowCounter++;\n    FlowLayoutPanel pnl = new FlowLayoutPanel();\n    pnl.Dock = DockStyle.Fill;\n    pnl.AutoSize = true;\n    DataTable tbl = cDALSettings.DB.GetCannedTable("select * from lorry");\n    // Now we simply add these controls to the panel...\n    foreach (DataRow row in tbl.Rows)\n    {\n      ucLorryDay ld = new ucLorryDay(dt, cTypes.ToInt(row["id"]), this);\n      pnl.Controls.Add(ld);\n    }\n    pnlLorries.Controls.Add(pnl, 0, rowCounter);\n    rowCounter++;\n  }	0
5352291	5336471	Name a ScatterViewItem programatically	foreach(KeyValuePair<int,Node> i in nodes)\n{    \n   ScatterViewItem item = new ScatterViewItem();    \n   item.Content = i.Value.Argument;    \n   item.Tag = i.Value;    \n   item.Name = "NodeID" + i.Key.ToString(); // set the name property\n   ActionArea.Items.Add(item);\n}	0
8692161	8692124	Table generation from Code Behind	GallaryImage g = new GallaryImage();\n    var images = g.GetAll();\n    photos.Style.Add("width","100%");\n    photos.Style.Add("border-style","none");       \n\n    int cntr = 0;\n    TableRow row = new TableRow();\n\n    foreach (var image in images)\n    {\n        cntr++;\n        TableCell cell = new TableCell();\n        Image i = new Image();\n        i.ImageUrl = image.fullThumbPath;\n        cell.Controls.Add(i);\n        row.Cells.Add(cell);\n        if(cntr%3==0)\n        {\n            photos.Rows.Add(row);\n            row = new TableRow();\n        }\n    }\n    if(row.Cells.Count > 0)\n        photos.Rows.Add(row);\n}	0
27440462	27440296	How to compare new and previous value in combobox?	public partial class Form1 : Form \n{\n    public Form1()\n    {\n        InitializeComponent();\n        comboBox1.Enter += comboBox1_Enter;\n    }\n\n    private void comboBox1_Enter(object sender, EventArgs e)\n    {\n        m_cb1PrevVal = comboBox1.SelectedValue;\n    }\n\n    private void RestoreOldValue()\n    {\n        comboBox1.SelectedValue = m_cb1PrevVal;\n    }\n}	0
11236151	11235628	trigger a 12 hours loop	var now=DateTime.UtcNow;\nvar today=now.Date;\nvar tomorrow=today.AddDays(1);\nvar dueTime=tomorrow-now;\n\nSystem.Threading.Timer timer = null;\ntimer = new Timer(_ => {\n    try\n    {\n        //do your thing\n    }\n    finally\n    {\n        timer.Dispose();\n    }\n},null,dueTime,TimeSpan.FromMilliseconds(-1d))	0
17051012	17050757	How to add a zip file to zip file using C# and DotNetZip	_myMemoryStream.Position = 0;	0
30746978	4112543	Fixed Header Gridview with scrollable body in asp.net	table {\n        width: 100%;\n    }\n\n    thead, tbody, tr, td, th { display: block; }\n\n    tr:after {\n        content: ' ';\n        display: block;\n        visibility: hidden;\n        clear: both;\n    }\n\n    thead th {\n        height: 30px;\n\n        /*text-align: left;*/\n    }\n\n    tbody {\n        height: 120px;\n        overflow-y: auto;\n    }\n\n    thead {\n        /* fallback */\n    }\n\n\n    tbody td, thead th {\n        width: 19.2%;\n        float: left;\n    }	0
20847322	20847238	Append custom value to a LINQ statement	var value = (from o in DataContext.Table\n            where o.Active == "Yes"\n            orderby o.Name\n            select o).AsEnumerable()\n                     .Concat(new [] { new TableObject() });	0
162063	162007	Making every pixel of an image having a specific color transparent	ImageAttributes attribs = new ImageAttributes();\nList<ColorMap> colorMaps = new List<ColorMap>();\n//\n// Remap black top be transparent\nColorMap remap = new ColorMap();\nremap.OldColor = Color.Black;\nremap.NewColor = Color.Transparent;\ncolorMaps.Add(remap);\n//\n// ...add additional remapping entries here...\n//\nattribs.SetRemapTable(colorMaps.ToArray(), ColorAdjustType.Bitmap);\ncontext.Graphics.DrawImage(image, imageRect, 0, 0, \n                           imageRect.Width, imageRect.Height, \n                           GraphicsUnit.Pixel, attribs);	0
10794660	10794534	How to schedule a C# code execution	private static CacheItemRemovedCallback OnCacheRemove = null;\n\nprotected void Application_Start(object sender, EventArgs e)\n{\n    AddTask("DoStuff", 60);\n}\n\nprivate void AddTask(string name, int seconds)\n{\n    OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);\n    HttpRuntime.Cache.Insert(name, seconds, null,\n        DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,\n        CacheItemPriority.NotRemovable, OnCacheRemove);\n}\n\npublic void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)\n{\n    // do stuff here if it matches our taskname, like WebRequest\n    // re-add our task so it recurs\n    AddTask(k, Convert.ToInt32(v));\n}	0
29537513	29535205	scanning buttons from grid WPF in c#	public List<Button> GetButtonsFromGrid (Grid grid)\n{\n    return grid.Children.OfType<Button>().ToList<Button>();\n}	0
1551265	1551243	Finding the overlapping area of two rectangles (in C#)	Rectangle.Intersect	0
12280601	12280426	Disabling item in a ComboBox C#	// To remove item with index 0:\ncomboBox1.Items.RemoveAt(0);\n// To remove currently selected item:\ncomboBox1.Items.Remove(comboBox1.SelectedItem);\n// To remove "Tokyo" item:\ncomboBox1.Items.Remove("Tokyo");	0
15434218	15434107	Get Element Filtering by Attribute	thevaluethatiwantvariable  = doc.DocumentElement.SelectSingleNode("//assertion[@name = 'id']/@value").Value;	0
3448296	3448269	Pimp my LINQ: a learning exercise based upon another post	var result =\n        from s in list\n        where s.Count(x => x == '=') == 2\n        select s.Substring(s.LastIndexOf("-") + 1);	0
6910190	6910122	Custom dialog box in C#?	using( MyDialog dialog = new MyDialog() )\n{\n   DialogResult result = dialog.ShowDialog();\n\n   switch (result)\n   {\n    // put in how you want the various results to be handled\n    // if ok, then something like var x = dialog.MyX;\n   }\n\n}	0
1876205	1876197	Why have empty get set properties instead of using a public member variable?	public class Foo {\n  public virtual int MyField = 1; // Nope, this can't\n\n  public virtual int Bar {get; set; }\n}\n\npublic class MyDerive : Foo {\n  public override MyField; // Nope, this can't\n\n  public override int Bar {\n    get {\n      //do something;\n    }\n    set; }\n}	0
19226827	19221807	Get Keys from a ShortCut	var sc = Shortcut.CtrlShiftF1;\n    var txt = new KeysConverter().ConvertToString((Keys)sc);\n    Console.WriteLine(txt);	0
6535192	6535134	how to Create a Transactionscope between saving a file and inserting a record in DB in C#	try\n{\n    // Start DB Transaction\n    // Save To DAtabase code\n    // Save To File Code\n    // Commit DB Transaction\n}\ncatch\n{\n    // Rollback DB Transaction\n}	0
3961837	3961722	Can a Dictionary be sorted by a different key?	var sortedResult = sortedDictionary.OrderBy(kvp => kvp.Value.SortField)\n                                   .ToDictionary(kvp => kvp.Key,\n                                                 kvp => kvp.Value);	0
24797235	24693386	Conditionally show HTML in a DevExpress MVC gridview	settings.Columns.Add(column =>\n            {\n                column.Caption = "archiveren";\n                column.SetDataItemTemplateContent(c =>\n                {\n                    ViewContext.Writer.Write("<input type=\"button\" value=\"archive\" />");\n                });\n\n\n            });	0
28475365	28474611	Type converting a string to a multiline version	string query = "asd \n asd  asd \n asd asd"+ MakeMultiline(subquery) +\n "asd asd asd \n asd asd where id=@id";	0
22657924	22657784	Combined sql statement into linq lamda expression	List<int> valuesOne = new List<int> { 2,3,4,5 };\nList<int> ValuesTwo = new List<int> { 1,2,3 };\n\nvar myLinq = (from k in Kunden\n             where k.a == 1 && k.b == 1 && k.c == 1 &&\n             ((k.d == 1 || ValuesOne.Contains (k.d)) &&\n                         ValuesTwo.Contains (k.e))) ||\n             // now do the same for f	0
29139273	29139181	How to use char array inside Struct in c#?	struct Books\n{\n   public string title;\n   public char[] b_id;\n};\n\nvoid Main()\n{\n\n   Books book1;        /* Declare Book1 of type Book */\n   book1.b_id = new char[3] {'a', 'b', 'c'};\n\n   /* book 1 specification */\n   book1.title = "C Programming";\n\n   /* print Book1 info */\n   Console.WriteLine("Book 1 title : {0}", book1.title);\n   Console.WriteLine("Book att : {0}", book1.b_id[0]);\n\n }	0
10001185	10000798	How can I cancel the selecting Event for a TabControl	private void tabControl1_Deselecting(object sender, TabControlCancelEventArgs e) {\n        if (e.TabPageIndex == 0 && tabControl1.TabCount > 1) {\n            tabControl1.TabPages[1].Dispose();\n            e.Cancel = true;\n        }\n    }	0
2668426	2668405	Convert C# format to VB	Dim name As String\nIf MyStringBuilder Is Nothing Then\n   name = String.Empty\nElse\n   name = MyStringBuilder.ToString()\nEnd If	0
15056533	15055797	Access TextBox Control In ListView Control	TextBox tmpControl = (TextBox)PostsListView.FindControl("AddCommentTextbox");	0
12213595	12213211	Function is called from a UpdatePanel?	string args= Page.Request.Params.Get("__EVENTTARGET");\nif (!String.IsNullOrEmpty(args))\n{\n    //Called From Update Panel(or) UpdatePanel is posting back\n}\nelse\n{\n    //Called From a page with no Update Panel\n}	0
6481827	6481823	find index of an int in a list	.IndexOf()	0
4865146	4864966	Such a thing as a calculation engine for C#?	Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");\n\n  e.Parameters["Pi2"] = new Expression("Pi * Pi");\n  e.Parameters["X"] = 10;\n\n  e.EvaluateParameter += delegate(string name, ParameterArgs args)\n    {\n      if (name == "Pi")\n      args.Result = 3.14;\n    };\n\n  Debug.Assert(117.07 == e.Evaluate());	0
5546798	5546777	Using accessors in C# stack over flow	private int numHighAttacksHit;\npublic int NumHighAttacksHit   // <-- note the pascal case\n    {\n        get { return numHighAttacksHit - handicapHighAttacks; }\n        set { numHighAttacksHit = value; }\n    }\n\nthis.NumHighAttacksHit = 0;	0
4591531	4583873	How to set test TCP connection timeout?	private static bool _TryPing(string strIpAddress, int intPort, int nTimeoutMsec)\n    {\n        Socket socket = null;\n        try\n        {\n            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);\n\n\n            IAsyncResult result = socket.BeginConnect(strIpAddress, intPort, null, null);\n            bool success = result.AsyncWaitHandle.WaitOne(nTimeoutMsec, true);\n\n            return socket.Connected;\n        }\n        catch\n        {\n            return false;\n        }\n        finally\n        {\n            if (null != socket)\n                socket.Close();\n        }\n    }	0
20622453	20621889	Asynchronous callback from web api controller	public string MyAPIMethod(object input)\n{\n    Task.Factory.StartNew(() =>\n    {        \n        //call third-party service and post result to callback url here.        \n\n    });\n\n    return "Success!";\n}	0
3118647	3118626	Assigning each property of every single item of IEnumerable Collection to different textboxes	textbox1.Text = enumerable.First();\ntextbox2.Text = enumerable.Skip(1).First();	0
13346682	13346306	DataGridView Column Sort results in EventArgs being wrong on Double Click	private void dataGV_CellCoubleClick(object sender, DataGridCellEventArgs e)\n{ \n    if (e.ColumnIndex == 0)\n    {\n        string strCaseNo = ((DataGridView)sender).Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString();\n        frmCase fC = new frmCase(strCaseNo);\n        fC.MdiParent = this.MdiParent;\n        fC.Show;\n    }\n}	0
21204453	21204445	How to Notify GUI Changes with INotifyPropertyChanged inmediatelly	UpdateSourceTrigger = PropertyChanged	0
248525	248273	Count number of Mondays in a given date range	static int CountDays(DayOfWeek day, DateTime start, DateTime end)\n    {\n        TimeSpan ts = end - start;                       // Total duration\n        int count = (int)Math.Floor(ts.TotalDays / 7);   // Number of whole weeks\n        int remainder = (int)(ts.TotalDays % 7);         // Number of remaining days\n        int sinceLastDay = (int)(end.DayOfWeek - day);   // Number of days since last [day]\n        if (sinceLastDay < 0) sinceLastDay += 7;         // Adjust for negative days since last [day]\n\n        // If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.\n        if (remainder >= sinceLastDay) count++;          \n\n        return count;\n    }	0
6044281	3999771	Changing Gridview row background color when editing?	GridView1.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;	0
8085969	8085907	How do you rename LINQ's name for when tables have a relationship with themselves?	partial class Person\n{\n   public Person Friend\n   {\n      get { return this.Person1; }\n      set { this.Person1 = value; }\n   }\n}	0
23377381	23377120	should be easy xml deserialization	[DataMember]\n    [XmlArray("settingsList")]\n    [XmlArrayItem("setting")]\n    public List<Setting> SettingsList { get; set; }	0
32723826	32723507	Extract specific nodes from XML	XDocument xdoc = XDocument.Load("File path");//Load XML file\n\n//Delete all elements in company except companyName\nxdoc.Descendants("company").Elements().Where(x => x.Name != "companyName").Remove();\n\n//Delete year\nxdoc.Descendants("year").Remove();\n\nxdoc.Save("File path");//Overwrite the XML file with the new result	0
11554670	11548944	Using Asynchronous Controller to Fill DataTable	public class RunTableStatisticsController : AsyncController \n{\n    public void RunTableStatisticsAsync()\n    {\n        AsyncManager.OutstandingOperations.Increment(2);\n\n        // Create tasks that populate RunTableStatisticsModels DataTables\n\n        Task.Factory.StartNew(() =>\n        {\n            AsyncManager.Parameters["dt1"] = DAL.GetDataTable1();\n            AsyncManager.OutstandingOperations.Decrement();\n        });\n\n        Task.Factory.StartNew(() =>\n        {\n            AsyncManager.Parameters["dt2"] = DAL.GetDataTable2();\n            AsyncManager.OutstandingOperations.Decrement();\n        });\n    }\n\n    public ViewResult RunTableStatisticsComplete(DataTable dt1, DataTable dt2)\n    {\n        var model = new RunTableStatisticsModel\n        {\n            DtTable1 = dt1,\n            DtTable2 = dt2,\n        };\n        return View(model);\n    }\n}	0
4549388	4549081	Rename item in a listview c# WinForms	private void listView1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyData == Keys.F2 && listView1.SelectedItems.Count > 0) {\n            listView1.SelectedItems[0].BeginEdit();\n        }\n    }	0
15208479	15207045	Determining Primary Key columns via GetSchema	var da = factory.CreateDataAdapter();\n    command.CommandText = "select * from Employees";\n    da.SelectCommand = command;\n    da.MissingSchemaAction = MissingSchemaAction.AddWithKey;\n\n    var dtab = new DataTable();\n    da.FillSchema(dtab, SchemaType.Source);\n\n    foreach (DataColumn col in dtab.Columns)\n    {\n        string name = col.ColumnName;\n        bool isNull = col.AllowDBNull;\n        bool isPrimary = dtab.PrimaryKey.Contains(col);\n    }	0
5623755	5623596	XMl deserializer in C#	using System;\nusing System.Linq;\nusing System.Xml.Linq;\nusing System.Xml.XPath;\n\npublic class ProductStream\n{\n    public int Id { get; set; }\n    public int ProductId { get; set; }\n    public string Name { get; set; }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var streams = XDocument\n            .Load("test.xml")\n            .XPathSelectElements("//ProductData[ProductID='1']/Streams")\n            .Select(s => new ProductStream\n            {\n                Id = int.Parse(s.Element("id").Value),\n                ProductId = int.Parse(s.Element("productId").Value),\n                Name = s.Element("name").Value\n            });\n\n        foreach (var stream in streams)\n        {\n            Console.WriteLine(stream.Name);\n        }\n    }\n}	0
20957863	20957576	Iterating over a JSON object on the server-side	JsonConvert.DeserializeObject<Root>(peopleJson);\n\npublic class Root\n{\n    public List<Person> items { get; set; }\n}	0
19463464	19463440	How do I create a shallow copy of an IEnumerable<T>?	IEnumerable<string> newList = listSelectedItems.ToList();	0
6643627	6643591	Best way to add two collections in .net	var xmlNodeList3 = xmlNodeList1.Concat(xmlNodeList2);	0
27073563	27073545	Initialize a generic class with the generic type as a variable	Type genericTypeDefinition = typeof(Rule<>);\nType genericType = genericTypeDefinition.MakeGenericType(_type);\nRule[] array = (Rule[])Array.CreateInstance(genericType, 0);	0
697896	697858	how explicit should I be with my overloads?	System.Missing	0
34328974	34328815	How to launch method when window got focus again in WPF?	private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        var wnd = new Window1();\n        wnd.Closed += wnd_Closed;\n        wnd.Show();\n    }\n\n    void wnd_Closed(object sender, EventArgs e)\n    {\n        MessageBox.Show("Closed");\n    }	0
5835930	5835752	Receiving post data with different encodings	StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding);\nstring xmlData = reader.ReadToEnd();	0
25615111	25615027	Join two 1D Arrays (A[] and B[]) into one 2D array (C[,])	public static double[,] _matrix_byRow(double[] Mat1, double[] Mat2)\n{\n    double[,] newMat = new double[2, 7];\n\n    for (var j = 0; j < 7; j++)\n    {\n        newMat[0, j] = Mat1[j];\n        newMat[1, j] = Mat2[j];\n    }\n\n    return newMat;\n}	0
3832553	3829624	Ensuring data is in date order using 2 paged lists	var dbAllData = Post.All();  //IQueryable\n\n            UserTimelineOptions options = new UserTimelineOptions();\n            options.ScreenName = "USERNAME";\n            options.Count = 5000;\n            options.IncludeRetweets = true;\n\n            TwitterStatusCollection recentTweets = TwitterTimeline.UserTimeline(options);\n\n\n            var dbAllMerged = dbAllData.AsEnumerable().Select((title) => new BlogData { Title = title.Title, Date = title.Date, RelativeDate = title.Date.ToRelativeDate(), Text = title.Text, DBRecord = true });\n\n            dbAllMerged = dbAllMerged.Concat(recentTweets.Where(y => !y.Text.StartsWith("@")).Select((tweet) => new BlogData { Title = "", Date = tweet.CreatedDate, RelativeDate = tweet.CreatedDate.ToRelativeDate(), Text = tweet.Text, DBRecord = false })).OrderByDescending(x => x.Date);	0
6196558	6196526	How to find out whether two string arrays are equal to other	static bool ArraysEqual<T>(T[] a1, T[] a2)\n{\n    if (ReferenceEquals(a1,a2))\n        return true;\n\n    if (a1 == null || a2 == null)\n        return false;\n\n    if (a1.Length != a2.Length)\n        return false;\n\n    EqualityComparer<T> comparer = EqualityComparer<T>.Default;\n    for (int i = 0; i < a1.Length; i++)\n    {\n        if (!comparer.Equals(a1[i], a2[i])) return false;\n    }\n    return true;\n}	0
7737791	7735382	.ASMX weirdness deserializing JSON blob from log4javascript logging?	\"message\":[\"Message 1\"],	0
32760404	32759988	How to debug startup exceptions with service hosted in IIS?	System.Diagnostics.Debugger.Break();	0
31527066	31526704	Move UI component after it was instantiated	panel.transform.position = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);	0
12599770	12580016	VS2010 ReportViewer keeps loading with Windows Azure Reporting Service	if(!IsPostBack){\n    // All my ReportViewer1 stuff goes here\n}	0
17348825	17298665	ASP.NET WebAPI how to make a POST request creating user with all data	{ "Addresses": [ { "StreetName": "Bigfoot Street", "Country": "AB", "ZipCode": "1234", "Cycle": 1, }, { "StreetName": "Woo Way Avenue", "Country": "AC", "ZipCode": "7777", "Cycle": 2, } ], "Phonenumbers": [ { "Number": "99999999", "Cycle": 3, } ], "Emails": [ { "Uemail": "bigfoot@example.com", "Cycle": 4, } ], "Positions": [], "Username": "Bigfoot", "FirstName": "Foo", "LastName": "Bar", "Password": "123", "Headline": "Pro" }	0
5999953	5999419	abstract properties help	public interface IMyObj\n{\n    void myMethod();\n}\n\n\npublic abstract class MyObjBase\n{\n    public string myProperty { get; set; }\n}\n\npublic class myObj : MyObjBase,IMyObj\n{\n    public void myMethod()\n    { }\n}\n\n\npublic void SomeMethod(myObj myobj)\n{\n    myobj.myProperty = "value";         \n}	0
3330017	3328698	How can I tell if an element matches a PropertyCondition in Microsoft UI Automation?	public class ConditionMatcher : IMatchConditions\n{\n    public bool Matches(AutomationElement element, Condition condition)\n    {\n        return new TreeWalker(condition).Normalize(element) != null;\n    }\n}	0
6014223	6014128	Manually selecting web page radio button	var rButton = b.Document.GetElementById("nameOfButton"); \n    if(rButton != null)\n         rButton.checked=true;	0
7966412	7966341	Get Count of an Item of Generic List	int count = list.Count(i => i > 10);// get the count of those which is bigger than 10	0
30069181	30069074	How to display paragraph like content in DataGridView?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        e.Row.Cells[1].Attributes.Add("style", "word-break:break-all;word-wrap:break-word;width:100px");\n    }\n  }\n}	0
10524348	10518307	C# - Windows Mobile - Bluetooth Pairing	BluetoothSecurity.PairRequest	0
7615185	7615050	Validation on a single DataGridView column	private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n{\n    DataGridViewTextBoxCell cell = dataGridView1[2, e.RowIndex] as DataGridViewTextBoxCell;\n\n    if (cell != null)\n    {\n         if (e.ColumnIndex == 2)\n         {\n             char[] chars = e.FormattedValue.ToString().ToCharArray();\n             foreach (char c in chars)\n             {\n                  if (char.IsDigit(c) == false)\n                  {\n                           MessageBox.Show("You have to enter digits only");\n\n                           e.Cancel = true;\n                           break;\n                    }\n              }\n          }\n     }\n}	0
1077778	1077411	Syncronously populating DependencyProperties of a custom control in Silverlight	private Guid? id;\n    private string text;\n\n    public Guid?Id\n    {\n        get { return id; }\n        set { \n            id = value;\n            TrySetValue();\n        }\n    }\n    public string Text \n    { \n        get { return text; }\n        set { text = value;\n        TrySetValue()} \n    }\n\n    private void TrySetValue()\n    {\n        if (id != null && text != null)\n        {\n            SetValue(IdProperty, id);\n            SetValue(TextProperty, text);\n        }\n    }	0
8817005	8816711	C# - Force Excel to ReCalc before Save	xlApp.Calculate()	0
9362988	9362959	Sending and Receiving XML data over TCP	NetworkStream stream = client.GetStream();\nStreamWriter writer = new StreamWriter(stream, Encoding.UTF8);\nwriter.AutoFlush = false;\nwriter.Write(Encoding.UTF8.GetBytes(message).Length);\nwriter.Write(message);\nwriter.Flush();\n\nStreamReader reader = new StreamReader(stream, Encoding.UTF8);\nresponse = reader.ReadLine();\n\nstream.Close();	0
3992720	3992707	Is there a technical reason why an automatic property must define both a get and set accessor	public object Property { get; private set; }	0
19433234	18091036	Make a list containing distinct list items from dataset containing duplicates	IEnumerable<String> GetUnique(IEnumerable<String> list)\n    {\n        HashSet<String> itms = new HashSet<String>();\n        foreach(string itm in list)\n        {\n            string itr = itm;\n            while(itms.Contains(itr))\n            {\n                itr = itr + "_";\n            }\n            itms.Add(itr);\n            yield return itr;\n        }\n    }	0
32533943	32533865	Linq Check if array of string has a partial match in other array	public static string[] FindMatchs(string[] array, string[] filter) {\n    return array.Where(x => filter.Any(y => x.Contains(y))).ToArray();\n}	0
33733674	33733559	Get an image from resources of project	private void button_MouseEnter(object sender, EventArgs e)\n        {\n            button.BackgroundImage = <YourNameSpace>.Properties.Resources.<ResourceName>;\n        }	0
13162123	13150883	WinForms Event Parent scroll	private void newCheckListQuestionPanel_Click(object sender, EventArgs e)\n{\n   newCheckListQuestionPanel.Focus(); //allows the mouse wheel to work after the panel is clicked\n}\nprivate void newCheckListQuestionPanel_MouseEnter(object sender, EventArgs e)\n{\n   newCheckListQuestionPanel.Focus(); //allows the mouse wheel to work after the panel has had the mouse move over it\n}	0
29374170	29374107	getting the index of an array, multiple times, then storing them in an array c#	List<int> Indexes = new List<int>();\n\nfor (int i = 0; i < array.Count(); i++)\n{\n    if (array[i] == "tom")\n    {\n        Indexes.Add(i);\n    }\n}	0
8481237	8481222	How to split a string into numbers?	String[] numbers = "11213,334990829,2234,".Split(',');	0
3457317	3457247	How to set Radio button property corresponding to the Database value	protected void yourGrid_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        RadioButton rdb= e.Row.FindControl("yourRadioButton") as RadioButton;\n        rdb// set here \n    }\n}	0
22867236	22866712	ASP.NET webservice: Obtain value from URL for operation	[WebMethod(Description = "multiply two numbers")]\n    [ScriptMethod(UseHttpGet = true)]\n    public int mul(int num1, int num2)\n    {\n        return num1 * num2;\n\n    }	0
19998401	19998306	what event get's fired when data has been entered in the cell in datagridview	private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    if (e.ColumnIndex==0)\n       {\n        SqlDataAdapter ad = new SqlDataAdapter(@"SELECT id from Customer", connection);\n        DataTable dt = new DataTable();\n        ad.Fill(dt);\n        int value = int.Parse(e.FormattedValue.ToString());\n        DataRow[] dr = dt.Select("id = " + value);\n        if (!dr.Any())\n        {\n              message.show("Foreign key problem");\n         }\n        else {\n        Form2 second = new Form2();\n        this.AddOwnedForm(second);\n        second.Show();\n         }\n        }    \n\n}	0
26376557	26376318	How to set name of month with indonesian language using Culture types	lblTglSuratKeluar.Text = suratKeluarc.TglSurat.ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID"));	0
5519910	5519888	Delete everything in a directory except a file in C#	string[] filePaths = Directory.GetFiles(strDirLocalt);\nforeach (string filePath in filePaths)\n{\n    var name = new FileInfo(filePath).Name;\n    name = name.ToLower();\n    if (name != "index.dat")\n    {\n        File.Delete(filePath);\n    }\n}	0
11939456	11939323	how to make an ItemsSource not in use?	ObservableCollection<TimesheetRecord> records = new ObservableCollection<TimesheetRecord>();	0
105402	105372	How to enumerate an enum?	foreach (Suit suit in Enum.GetValues(typeof(Suit))) {\n    // ...\n}	0
20687405	20687121	ASP.NET MVC CheckBoxList from model with List Property	for (var i = 0; i < Model.UserRoles.Count(); i++)\n{\n    var role = Model.UserRoles[i];\n    @Html.HiddenFor(model => model.UserRoles[i].RoleId)\n    @Html.CheckBoxFor(model => model.UserRoles[i].Selected)\n    @Html.LabelFor(model=> model.UserRoles[i].Name, role.Name)\n}	0
19135437	19135151	Raise event of customized control from class itself	class CustomTabPage : TabPage\n{\n    TextBox tbCode = new TextBox();\n    public CustomTabPage()\n    {\n        SizeChanged += CustomTabPage_SizeChanged;\n    }\n\n    void CustomTabPage_SizeChanged(object sender, EventArgs e)\n    {\n        OnThisControlSizeChanged();\n    }\n\n    public CustomTabPage(string title)\n    {\n        tbCode.Multiline = true;\n        tbCode.Size = this.Size;\n    }\n\n    private void OnThisControlSizeChanged()\n    {\n        tbCode.Size = this.Size;\n    }\n}	0
1889199	1888948	C# How To Update Entity Model Connection String	var connstr = GetConnectionString();\n\nusing (NCIPEntities ctx = new NCIPEntities(connstr))\n{\n    ...\n}	0
34228100	34227950	In a derived class, how to have a property of a derived type from the type of the property in the base class?	public class BaseClass<T> where T : BaseProperty\n{\n    public T Property { get; set; }\n}\n\npublic class DerivedClass : BaseClass<DerivedProperty>\n{\n    public void MethodExample()\n    {\n        AClass aValue = Property.A;\n    }\n}	0
1554161	1554078	Accessing child of ListBoxItem	ComboBox cb = (ComboBox)listBox.ItemTemplate.FindName("IconComboBox", lbi);	0
12407043	12406644	MonoTouch - Reading in a file from the Main Bundle	NSBundle.MainBundle.BundlePath	0
8362854	8362809	Start a process for all items in a listbox	foreach(object itemChecked in checkedListBox1.CheckedItems) {\nProcess.Start("someapp.exe");\n}	0
30731581	30731436	Entity framework - If nullified property, return custom string is affecting real data	public string UserNameToShow\n{\n    get \n    {\n        if( this.username == null )\n        {\n            return "anonymous";\n        }\n\n        return this.username;\n     }\n}	0
19247938	19224062	Populate XML tag more than once	var data = new BrokerConfirmation();\nXmlDocument docSave = new XmlDocument();\ndata.TimeIntervalQuantities = new BrokerConfirmationTimeIntervalQuantity[]\n            {\n               new BrokerConfirmationTimeIntervalQuantity {...}, \n               // More instances here....\n               new BrokerConfirmationTimeIntervalQuantity {...}, \n               new BrokerConfirmationTimeIntervalQuantity {...},\n               // etc...\n            };	0
4784527	3655484	Unable to cast transparent proxy to type from AppDomain	typeof(CompiledTemplate)	0
2540302	2540220	Check for Existence of a Result in Linq-to-xml	bool anyPeople = people.Any();\nif (anyPeople) {	0
20065840	20065659	Extract rows from 2D array within a model	var result = custVm.flag.Select((f, i) => new { f, val = custVm.values[i][0] })\n                        .Where(i => !i.f)\n                        .Select(i => i.val);	0
16008570	16008477	Export DataGridView to HTML Page	private StringBuilder DataGridtoHTML(DataGridView dg)\n{\n  StringBuilder strB = new StringBuilder();\n  //create html & table\n  strB.AppendLine("<html><body><center><" + \n                "table border='1' cellpadding='0' cellspacing='0'>");\n  strB.AppendLine("<tr>");\n  //cteate table header\n  for (int i = 0; i < dg.Columns.Count; i++)\n  {\n     strB.AppendLine("<td align='center' valign='middle'>" + \n                    dg.Columns[i].HeaderText + "</td>");\n   }\n  //create table body\n  strB.AppendLine("<tr>");\n  for (int i = 0; i < dg.Rows.Count; i++)\n  {\n    strB.AppendLine("<tr>");\n    foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)\n    {\n        strB.AppendLine("<td align='center' valign='middle'>" + \n                        dgvc.Value.ToString() + "</td>");\n    }\n    strB.AppendLine("</tr>");\n\n}\n//table footer & end of html file\nstrB.AppendLine("</table></center></body></html>");\nreturn strB;}	0
1887557	1887544	C# value is declared but never used	catch (XmlException)\n{\n    return false; \n}\n\ncatch (XmlSchemaException)\n{\n    return false; \n}\n\ncatch (Exception GenExp)\n{\n     // inspect or use GenExp\n     throw;\n}	0
9559911	9554931	reset count above max time interval, in Rx count-based aggregation	var longGap = source.Throttle(tooLong);\nvar filtered = source\n  .Window(() => { return longGap; })  // Gives a window between every longGap\n  .Select(io => io.Buffer(maxItems).Where(l => l.Count == maxItems))\n  .Switch();  // Flattens the IObservable<IObservable<IList>> to IObservable<IList>	0
5324272	5324168	Icons in rich text box?	private void richTextBox1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (richTextBox1.Text.Contains(":-)"))\n    {\n        richTextBox1.SelectionStart = richTextBox1.Find(":-)", RichTextBoxFinds.WholeWord);\n        richTextBox1.SelectionLength = 3;\n\n        Clipboard.SetImage(im.Images["smile.png"]);\n        this.richTextBox1.Paste();\n    }\n}	0
23321110	23320753	What's a simple way to update a Bitmap with another Bitmap given a top left corner?	public void updateWithSprite(int x, int y, Sprite sprite)\n    {\n\n        Bitmap sprBitmap = sprite.getBitmap();\n        Graphics g = Graphics.FromImage(this.bitmap);\n        g.DrawImage(sprBitmap, x, y, sprBitmap.Width, sprBitmap.Height);\n        g.Dispose();\n    }	0
19560309	19560170	How to convert .docx to .pdf in C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing Microsoft.Office.Interop.Word;\n\npublic partial class Default2 : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();\n        wordDocument = appWord.Documents.Open(@"D:\desktop\xxxxxx.docx");\n        wordDocument.ExportAsFixedFormat(@"D:\desktop\DocTo.pdf", WdExportFormat.wdExportFormatPDF);\n    }\n\n    public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }\n}	0
4393055	4392975	C# application to import excel file content into a text file	string strConn = "Provider=Microsoft.Jet.OleDb.4.0;data source=C:\\Inetpub\\wwwroot\\CS\\HostData.xls;Extended Properties=Excel 8.0;";\nOleDbConnection objConn = new OleDbConnection(strConn);\n\nstring strSQL = "SELECT * FROM [A1:B439]";\nOleDbCommand objCmd = new OleDbCommand(strSQL, objConn);\n\nobjConn.Open();\ndgReadHosts.DataSource = objCmd.ExecuteReader();\ndgReadHosts.DataBind();\nobjConn.Close();	0
5516201	5516111	How to read combobox from a thread other than the thread it was created on?	this.Invoke((MethodInvoker)delegate()\n    {\n        text = combobox.Text;\n    });	0
1360791	1350057	Progress Bar in Setup Application	[DllImport("user32.dll", EntryPoint = "SetWindowPos")]\npublic static extern bool SetWindowPos(\n      IntPtr hWnd, // window handle\n      IntPtr hWndInsertAfter, // placement-order handle\n      int X, // horizontal position\n      int Y, // vertical position\n      int cx, // width\n      int cy, // height\n      uint uFlags); // window positioning flags\n\npublic const uint SWP_NOSIZE = 0x1;\npublic const uint SWP_NOMOVE = 0x2;\npublic const uint SWP_SHOWWINDOW = 0x40;\npublic const uint SWP_NOACTIVATE = 0x10;\n\n[DllImport("user32.dll", EntryPoint = "GetWindow")]\npublic static extern IntPtr GetWindow(\n      IntPtr hWnd,\n      uint wCmd);\n\npublic const uint GW_HWNDFIRST = 0;\npublic const uint GW_HWNDLAST = 1;\npublic const uint GW_HWNDNEXT = 2;\npublic const uint GW_HWNDPREV = 3;\n\npublic static void ControlSendToBack(IntPtr control)\n{\n    bool s = SetWindowPos(\n          control,\n          GetWindow(control, GW_HWNDLAST),\n          0, 0, 0, 0,\n          SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n}	0
13936208	13935117	Application crashes when installed	static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)\n        {\n            MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");\n            // here you can log the exception ...\n        }\n\n        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n        {\n            MessageBox.Show((e.ExceptionObject as Exception).Message +\n                "\r\n\r\nStack Trace:" +\n                (e.ExceptionObject as Exception).InnerException.StackTrace, "Unhandled UI Exception");\n            // here you can log the exception ...\n        }	0
12268767	12219981	WCF Xml/Json serialization of domain objects, what exactly is getting serialized?	public string MyProperty { get; internal set; }	0
8419759	8419484	How can I create a custom MVC3 template or HTML helper for a property of type KeyValuePair<string,string>	public class TestModel \n{\n    [UIHint("NameOfYourDisplayTemplate")]\n    public KeyValuePair<string,string> MyProperty{ get; set; }\n}	0
15354316	15354206	Find file name not present in a directory	var missingFiles = names.Where(x => !File.Exists(x));	0
6277231	6277184	How to convert dictionary<string,int> to double array of their values in c#?	double[] strn = dic.Values.Select(v => (double)v).ToArray();	0
1904255	1864432	WPF - How to set DataContext on virtual branch of logical tree?	myElement.DataContext = this.DataContext	0
947312	947202	C# P/Invoke: How to achieve double indirection for a field of a structured parameter	[StructLayout(LayoutKind.Sequential)\npublic class SomeClass\n{\n    int foo;\n    IntPtr resultPtr;\n    AnotherStruct resultStruct { \n      get { \n        var temp = (IntPtr)Marshal.PtrToStructure(resultPtr, typeof(IntPtr));\n        return (AnotherStruct)Marshal.PtrToStructure(temp, typeof(AnotherStruct));\n      }\n    }\n\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic class AnotherStruct\n{\n    int bar;\n}	0
3456514	3456397	Checking file/folder access permission	AuthorizationRuleCollection acl = fileSecurity.GetAccessRules(true, true,typeof(System.Security.Principal.SecurityIdentifier));\nbool denyEdit = false;\nfor (int x = 0; x < acl.Count; x++)\n{\n    FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];\n    AccessControlType accessType = currentRule.AccessControlType;\n    //Copy file cannot be executed for "List Folder/Read Data" and "Read extended attributes" denied permission\n    if (accessType == AccessControlType.Deny && (currentRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory)\n    {\n        //we have deny copy - we can't copy the file\n        denyEdit = true;\n        break;\n    }\n... more checks \n}	0
2884021	2884016	How to run a bat file from a C# program?	Process.Start("thebatchfile.bat")	0
9777392	9777206	C# read txt file and store the data in formatted array	static void Main(string[] args)\n    {\n        var lines = File.ReadAllLines("filename.txt");\n\n        for (int i = 0; i < lines.Length; i++)\n        {\n            var fields = lines[i].Split(' ');\n        }\n    }	0
24020672	23994495	Exclude range of IP addresses from datatable	DataTable dt; //your datatable here\n        DataView dv = dt.DefaultView;\n        foreach (DataRow dr in dt.Rows)\n        {\n\n            if (Regex.IsMatch(dr["Column name of your IP"].ToString(), "regex to check  IP") == false)\n            {\n               //Delete that row or something\n            }\n            else\n            {\n               //Do something else\n            }\n        }\n        DataTable tempTable = dv.ToTable();\n       //where temptable is your sorted and updated datatable	0
2774110	2722217	WPF Datagrid Get Selected Item	theformats lineobject = (theformats)groups_dataGrid1.CurrentCell.Item;\n   string linetext = lineobject.theformat.ToString();	0
815177	815104	How to block a timer while processing the elapsed event?	timer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;\ntimer.Elapsed = Timer_OnElapsed;\ntimer.AutoReset = false;\ntimer.Start();\n\n\npublic void Timer_OnElapsed(object sender, ElapsedEventArgs e)\n{\n    if (!found)\n    {\n      found = LookForItWhichMightTakeALongTime();\n    }\n    timer.Start();\n}	0
5933912	5932891	Calculating a ASPxGridview Column in DevExpress	protected void ASPxGridView1_Init(object sender, EventArgs e)\n  {\n      GridViewDataTextColumn colTotal = new GridViewDataTextColumn();\n      colTotal.Caption = "Total";\n      colTotal.FieldName = "Total";\n      colTotal.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;\n      colTotal.VisibleIndex = ASPxGridView1.VisibleColumns.Count;\n      colTotal.PropertiesTextEdit.DisplayFormatString = "n0";\n      ASPxGridView1.Columns.Add(colTotal);\n\n  }\n\nprotected void ASPxGridView1_CustomUnboundColumnData(object sender, ASPxGridViewColumnDataEventArgs e)\n  {\n      if (e.Column.FieldName == "Total")\n      {\n          decimal risk = Convert.ToDecimal(e.GetListSourceFieldValue("RISK"));\n          decimal mv = Convert.ToDecimal(e.GetListSourceFieldValue("MV_BERND"));\n          decimal ipotek = Convert.ToDecimal(e.GetListSourceFieldValue("IPOTEK"));\n\n\n          e.Value = risk - mv - ipotek;\n      }\n\n  }	0
5280377	5277889	ActiveRecord custom SQL result automapping	IList<MyObj> reults = Session.CreateQuery("select r.feedname as feedname, count(r.feedurl) as feedcount from rsssubscriptions r group by r.feedname")\n                                                .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(MyObj)))\n                                                .List<MyObj>();	0
12698042	12697619	Using Regular Expression Search to parse and format HTML Tag in Rss	//http://htmlagilitypack.codeplex.com/\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar result = doc.DocumentNode.Descendants()\n                .Where(n => n is HtmlAgilityPack.HtmlTextNode)\n                .Select(n=>new {\n                    IsDate = n.ParentNode.Name=="b" ? true: false,\n                    Text = n.InnerText,\n                })\n                .ToList();	0
16710904	16708533	Serialize Entity Collection in XML in c#	myEntity.MyTable.include("FieldsInfo");	0
5680461	5680343	How to bind a ComboBox to a generic List with deep DisplayMember and ValueMember properties?	private void Form1_Load(object sender, EventArgs e)\n{\n    List<Parent> parents = new List<Parent>();\n    Parent p = new Parent();\n    p.child = new Child();\n    p.child.DisplayMember = "SHOW THIS";\n    p.child.ValueMember = 666;\n    parents.Add(p);\n\n    var children =\n        (from parent in parents\n            select new\n            {\n                DisplayMember = parent.child.DisplayMember,\n                ValueMember = parent.child.ValueMember\n            }).ToList();\n\n    comboBox1.DisplayMember = "DisplayMember";\n    comboBox1.ValueMember = "ValueMember";\n    comboBox1.DataSource = children;     \n}	0
32889826	32861289	Lock screen orientation to portrait when scanning with Zxing library, Xamarin.android app.	var scanner = new MobileBarcodeScanner();\n            scanner.TopText = "Scanning for Barcode...";\n            var result = await scanner.Scan(new MobileBarcodeScanningOptions\n            {\n                AutoRotate = false\n            });\n            if (result != null)\n            {\n                _scan.ScanValue = result.ToString();\n                _scan.Action = "Scan";\n                await CallService();\n            }\n            else\n            {\n                scanner.Cancel();\n                Recreate();\n            }\n        };	0
8085946	8085880	How to OrderBy an integer in a string field in a Linq query	myControl.DataSource = dataFromDB.ToList().OrderBy(o => int.Parse(o.StringHoldingAnInt));	0
17939456	17939418	C# Same Enum Name with Multiple Values	A = 1,\nB = 2,\nC = 2,\nD = 1	0
10195315	10194988	Are there any symbols when compiling a portable class library that can be used with preprocessor directives	// Shared source file\n[ComVisible(true)]\npublic class Foo\n{\n}\n\n// Dummy class in portable project -- exists only to facilitate compilation of the shared source file\nnamespace System\n{\n    [AttributeUsage(AttributeTarget.Class)]\n    public class ComVisibleAttribute : Attribute\n    {\n        public ComVisibleAttribue(bool visible)\n        {\n            // Dummy implementation\n        }\n    }\n}	0
20734686	20734637	Clamp presentable value	float normalizedDistance = distance / maxDistance;	0
13627032	13626454	Timer to close the application	public Form1() {\n        InitializeComponent();\n        DateTime now = DateTime.Now;  // avoid race\n        DateTime when = new DateTime(now.Year, now.Month, now.Day, 23, 0, 0);\n        if (now > when) when = when.AddDays(1);\n        timer1.Interval = (int)((when - now).TotalMilliseconds);\n        timer1.Start();\n    }\n    private void timer1_Tick(object sender, EventArgs e) {\n        this.Close();\n    }	0
26841394	26841312	How to Use Session Like C# page to VB Page Using Page Methods	[System.Web.Services.WebMethod]\npublic static string SetDownloadPath(string strpath)\n{\n        HttpContext.Current.Session["strDwnPath"] = strpath;\n        return strpath;\n}	0
32356528	32356490	create datamember with two types	using System;\n\npublic class Test\n{\n    interface IChat\n    {\n        int Id { get; set; }\n    }\n\n    class User : IChat\n    {\n        public int Id { get; set; }\n        public string first_name;\n        public string last_name;\n        public string username;\n    }\n\n    class GroupChat : IChat\n    {\n        public int Id { get; set; }\n        public string title;\n    }\n\n    class MyClass\n    {\n        public IChat Chat { get; set; }\n    }\n\n    public static void Main()\n    {\n        MyClass foo = new MyClass();\n        foo.Chat = new User();\n\n        MyClass bar = new MyClass();\n        bar.Chat = new GroupChat();\n\n        if(foo.Chat.GetType() == typeof(User))\n            Console.WriteLine("foo has User");\n        else\n            Console.WriteLine("foo has GroupChat");\n\n        if(bar.Chat.GetType() == typeof(User))\n            Console.WriteLine("bar has User");\n        else\n            Console.WriteLine("bar has GroupChat");\n    }\n}	0
31891819	31891615	How to identify the specific cell hovered over in DataGridView	//when mouse is over cell\n    private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)\n        {\n            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Black;\n        }\n    }\n//when mouse is leaving cell\n    private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)\n    {\n        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)\n        {\n            dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;\n        }\n    }	0
8314593	6548752	Embed SVG into PDF programmatically in .NET C#	MyImageStream = new MemoryStream(); \n myChart.SaveImage(MyImageStream);	0
22106043	22105971	Updating a Custom Control's binded Property on its property change	public Brush EnableColor\n    {\n        get { return (Brush)this.GetValue(EnableColorProperty); }\n        set { this.SetValue(EnableColorProperty, value); }\n    }\n    public static readonly DependencyProperty EnableColorProperty = DependencyProperty.Register(\n      "EnableColor", typeof(Brush), typeof(customRadioButton), new PropertyMetadata(default(Brush));	0
15930277	15913592	Preserving non-inserted data for a record	Create Table PhoneTable\n(\n    PhoneID int identity(1,1),\n    PhoneNumber varchar(20)\n)\nGO\n\nCreate Type PhoneType As Table\n(\n    PhoneNumber varchar(20),\n    CorrelationID bigint\n)\nGO\n\nCreate Procedure usp_Phone_Insert\n    @Input PhoneType ReadOnly\nAS\n    Declare @Output Table (\n        PhoneID int, \n        PhoneNumber varchar(20),\n        CorrelationID bigint)\n\n    Insert Phone (PhoneNumber)\n    Output\n        inserted.PhoneID,\n        inserted.PhoneNumber\n    Into @Output\n    Select \n        PhoneNumber\n    From\n        @Input\n\n    Select\n        O.PhoneID,\n        O.PhoneNumber,\n        I.CorrelationID\n    From\n        @Output O\n        Inner Join @Input I on I.PhoneNumber = O.PhoneNumber\nGO	0
6074659	6074268	Sorting data using EF DbSet	private readonly DbContext context;\n...\ncontext.Set<T>().OrderBy(item => item.Property)	0
11319141	11214401	How to write a converter class? How to efficiently write mapping rules?	A.a && B.o && C.y ==> "**A**********************"\nA.a && B.p && C.y ==> "**B**********************"\nA.b && B.o && C.y ==> "*****X*******************"\nA.b && B.o && C.z ==> "*****W*******************"	0
13925819	13919457	C# Winforms: Limit Drag and Drop to within a single control	// prevents dragging from other instances of this form - thanks to Hans Passant\nprivate bool DragDropFromThisForm = false;\n\nprivate void SubFolderTreeView_ItemDrag(object sender, ItemDragEventArgs e)\n{\n    // Initiate drag/drop\n    DragDropFromThisForm = true;\n    DoDragDrop(e.Item, DragDropEffects.Move);\n    DragDropFromThisForm = false;\n}\n\nprivate void SubFolderTreeView_DragEnter(object sender, DragEventArgs e)\n{\n    MyForm form = (MyForm) (sender as TreeView).TopLevelControl;\n\n    if (form.DragDropFromThisForm && e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))\n        e.Effect = DragDropEffects.Move; // Okay, set the visual effect\n    else\n        e.Effect = DragDropEffects.None; // Unknown data, ignore it\n}	0
12086408	12086360	LinqToEntities Grouping	var messages = (from m in mList select new\n{\n   Text = m.Text, \n   User = m.User, \n   Date = m.Date\n})\n.GroupBy(m => m.User)\n.Select(g => g.OrderByDescending(m => m.Date).First())\n.ToList();	0
11943168	11943114	MSTest custom test-pass message	Console.WriteLine("This is a message from my test!");	0
31411807	31411675	C# Console Application: How do I open a textfile maximized?	string notepadPath = Environment.SystemDirectory + "\\notepad.exe";\n\nvar startInfo = new ProcessStartInfo(notepadPath)\n{\n    WindowStyle = ProcessWindowStyle.Maximized,\n    Arguments = "README.txt" \n};\n\nProcess.Start(startInfo);	0
20721784	20721572	Using lock statement to read and save a list?	lock (list)\n{\n    if (!FindObject(list))\n    {\n        MyClass obj = CreateObject();\n        list.Add(obj)\n    }\n}	0
14802847	14802745	how to create multiple clients in one server?	for (i=0;i<3;i++)\n{\n    Client.ClientCode();\n}	0
26266059	26265853	Is a Role Provider implementation necessary?	throw new NotImplementedException();	0
30358500	30204996	How to maintain font properties of word documents when converted to PDF	bool _OpenAfterExport = false;\nbool _KeepIRM = true;\nint _From = 1;\nint _To = 1; //I thought this was odd, setting From and To to 1, but it exported all pages of the document\nbool _IncludeDocProps = true;\n\nWord.Document oDoc = oWord.Documents.Open(inputFile);\noDoc.ExportAsFixedFormat(outputFile,\n                         Word.WdExportFormat.wdExportFormatPDF,\n                         OpenAfterExport,\n                         Word.WdExportOptimizeFor.wdExportOptimizeForPrint,\n                         Word.WdExportRange.wdExportAllDocument,\n                         _From,\n                         _To,\n                         Word.WdExportItem.wdExportDocumentContent,\n                         _IncludeDocProps,\n                         _KeepIRM,\n                         Word.WdExportCreateBookmarks.wdExportCreateHeadingBookmarks)\noDoc.Close();\noWord.Quit();\nSystem.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);	0
4803542	4803449	Print image after it's been generated [c#]	Bitmap b = new Bitmap(100, 100);\nusing (var g = Graphics.FromImage(b))\n{\n    g.DrawString("Hello", this.Font, Brushes.Black, new PointF(0, 0));\n}\n\nPrintDocument pd = new PrintDocument();\npd.PrintPage += (object printSender, PrintPageEventArgs printE) =>\n    {\n        printE.Graphics.DrawImageUnscaled(b, new Point(0, 0));\n    };\n\nPrintDialog dialog = new PrintDialog();\ndialog.ShowDialog();\npd.PrinterSettings = dialog.PrinterSettings;\npd.Print();	0
7757860	7757809	Algorithm to find very common occurences of substrings in a set of short strings	var words = from s in listOfStrings\n            from word in s.Split(new[] { ' ', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)\n            group word by word;\nvar dic = words.ToDictionary(g => g.Key, g => g.Count());	0
21394665	21394573	Gridview Cannot get value control	string myid = string.Empty; \nfor (int i = 0; i < gv_enfant.Rows.Count; i++) \n{ \n    var chbox = gv_enfant.Rows[i].Cells[0].FindControl("CheckBoxenfant") as CheckBox; \n    var codeenfant = gv_enfant.Rows[i].Cells[0].FindControl("codeenfant") as HiddenField\n    if(chbox != null && codeenfant  != null)\n    { \n        if (chbox.Checked) \n        { \n            myid = codeenfant.Value; \n        } \n    }\n}	0
3052860	3052649	Disable Windows service at application launch	ServiceController _ServiceController = new ServiceController([NameService]);\nif (_ServiceController.ServiceHandle != null) \n{\n     _ServiceController.Stop();\n     _ServiceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(uConstante.CtTempoEsperaRespostaServico));\n}	0
1866268	1866236	Add offset to IntPtr	IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2);	0
15298605	15295153	using the OData Queryable with a repository?	public IQueryable<TModel> GetAll(ODataQueryOptions opts)\n    {\n        var db = _repo.GetAll();\n        return (IQueryable<TModel>) opts.ApplyTo(db);\n    }	0
16352447	16351997	To get Two data table data in particular format in third data table in C#	var dt3 = from p in dt1.AsEnumerable()\n                   join q in dt2.AsEnumerable() on p.Field<string>("name") equals q.Field<string>("name") into UP\n                   from q in UP.DefaultIfEmpty()\n                   select new\n                   {\n                        name = p.Field<string>("name"),\n                        m1 = p.Field<string>("m1") + "/" + q.Field<string>("m1"),\n                        m2 = p.Field<string>("m2") + "/" + q.Field<string>("m2"),\n                        m3 = p.Field<string>("m3") + "/" + q.Field<string>("m3")\n                   };	0
12762738	12756629	In C# winforms using telerik assembly references how to export radGridView to pdf ( Im not using MCV or WPF, implementing in normal winforms)	private void button1_Click(object sender, EventArgs e)\n    {\n\n\n        ExportToPDF exporter = new ExportToPDF(this.radGridView1);\n        exporter.FileExtension = "pdf";\n        exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;\n        exporter.ExportVisualSettings = true;\n        exporter.PageTitle = "Directory Details";\n        exporter.FitToPageWidth = true;\n\n        string fileName = "c:\\Directory-information.pdf";\n        exporter.RunExport(fileName);\n\n        MessageBox.Show("Pdf file created , you can find the file c:\\Directory-informations.pdf");                     \n    }	0
27176581	27176217	How to modify $env:VARIABLES from c# cmdlets?	Environment.SetEnvironmentVariable()	0
8050246	8049331	Parsing HTML string in WP7	var image = document.DocumentNode.Descendants("img").First()\nvar source = image.GetAttribute("src", "").Value;	0
6868213	6868138	What's the proper way to comment a constructor in a generic class?	/// <summary>\n/// Initializes a new instance of the <see cref="Repository{T}"/> class.\n/// </summary>	0
14959076	14946381	C# winforms draw to bitmap invalid parameter	private void preview()\n{\n\n    Bitmap bmp1 = new Bitmap(2480, 3508);\n    panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));\n    Image img = pictureBox2.Image;\n    pictureBox2.Image = bmp1;\n    if (img != null) img.Dispose(); // the first time it'll be null\n\n}\n\nprivate void btnUpdate_Click(object sender, EventArgs e)\n{\n    preview();\n    System.GC.Collect();\n    System.GC.WaitForPendingFinalizers();\n}	0
28122756	28122593	How to close an activeMidForm and open another?	Form myForm=new Form();\nmyForm.shown += closeForm;\n...\n\nvoid closeForm(object sender, EventArgs e){\nthis.Dispose(); // as long as within the previous           forms context.\n}	0
3303862	3303829	Create a Guid from an int	int a = 5;\nGuid guid = new Guid(a, 0, 0, new byte[8]);	0
18080446	18079603	Renew Entity Framework ObjectContext connection after changing	ConfigurationManager.RefreshSection("xxx");// config manager needs a kick...	0
25112673	25112446	How to constantly rename a file and move it	var files = new List<string>();\n\nforeach (var file in Directory.GetFiles(@"Your Location"))\n{\n    var fileName = Path.GetFileNameWithoutExtension(file);\n\n    if (fileName.StartsWith("Image"))\n    {\n        files.Add(fileName.Replace("Image",""));\n    } \n}\n\nvar last = int.Parse(files.OrderByDescending(f => f.ToString()).First()) + 1;	0
7774764	7774515	retaining checked items after a databind()	Dim oldSelection = (From item As ListItem In ProductCheckList.Items\n                    Where item.Selected).ToList\n' databinding '\nIf oldSelection.Any Then\n    For Each selectedItem In oldSelection\n        Dim item = ProductCheckList.Items.FindByValue(selectedItem.Value)\n        If Not item Is Nothing Then\n           item.Selected = True\n        End If\n    Next\nEnd If	0
9147172	9147164	OleDB Data not reading from the correct row	ORDER BY	0
19275244	17040529	Share multiple videos on one page onto facebook page wall	string getPagesTokensUrl = string.Format(@"https://graph.facebook.com/me/accounts?access_token={0}",accessToken);\n\n        using (WebClient wc = new WebClient())\n        {\n            var pagesTokens = wc.DownloadString(getPagesTokensUrl);\n\n            JObject o = JObject.Parse(pagesTokens);\n\n            for (int i = 0; i < o["data"].Count(); i++)\n            {\n                if (o["data"][i]["id"].ToString() == ConfigurationManager.AppSettings["YOUR PAGE ID"])\n                {\n                    return o["data"][i]["access_token"].ToString();\n                }\n            }\n        }	0
16730692	16730620	Linq Query Grouping Data table using two columns	var tMainTable = (from System.Data.DataRow b in _tData.data_table.Rows\ngroup b by new { AccessCode = b["ACCESS_CODE"], Date = b["DATE"] } into bGroup\nselect new\n{ bGroup });	0
9048574	9048568	creating custom templated control in asp.net	[TemplateInstance(TemplateInstance.Single)]	0
5975104	5975069	Compact Framework: A problem with reading a file	string dir = Path.GetDirectory(Assembly.GetExecutingAssembly().Location);\nstring filename = Path.Combine(dir, "list.txt");\nStreamReader str = new StreamReader(filename);	0
30287011	30286956	How to order application settings	Properties.Settings.Default.Properties.OfType<SettingsProperty>().OrderBy(s => s.Name)	0
26270369	26270161	EF Fluent API + two column composite uniqueness + autoincrement primary key	modelBuilder.Entity<Foo>() \n            .Property(t => t.X) \n            .HasColumnAnnotation("X", new IndexAnnotation(new IndexAttribute("X") { IsUnique = true }));	0
27417526	27416412	Zoom in to display portion of a window captured by Process	SetParent(appWin, panel1.Handle);\n        SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE);\n        MoveWindow(appWin, -100, -100, panel1.Width+100, panel1.Height+100, true);	0
20387199	20371126	Log out from facebook using the facebook c# sdk on windows phone 8	await new WebBrowser().ClearCookiesAsync();	0
33089231	33089113	prompting a user through C# program	namespace HelloWorld\n{\n    class Hello \n    {\n        static void Main() \n        {\n            Console.WriteLine("Hello World!");\n\n            // Keep the console window open in debug mode.\n            Console.WriteLine("Press any key to exit.");\n            Console.ReadKey();\n        }\n    }\n}	0
12557869	12557860	INSERT query shows data inserted but actually no data is inserted	SqlCommand insertProject = new SqlCommand("Insert into tbl_project \n                (id,project_name,project_desc,creator_user_id) \n          VALUES(@id,@project_name,@project_desc,@creator_user_id)",conn);	0
12498755	12498618	How to open files from a specific route in ASP-NET c#?	string strArchivo = "FileNameHere"; \nstring strExtension = Path.GetExtension(strArchivo).ToLower(); \n\nif (strExtension == ".pdf" || strExtension == ".docx" || strExtension == ".doc"... etc) \n{ \n    //I open a file which is located in a folder called Archivos \n    Response.Write("<script>window.open('/Archivos/" + strArchivo + "');</script>"); \n}	0
16502732	16502609	A more elegant way to change a single element in a struct in C#	public static class FrameUtil{\n     public RectangleF UpdateX(RectangleF frame, float newX){\n          var tempFrame = frame;\n          tempFrame.x = newX;\n          return tempFrame;\n     }\n}	0
9115923	9115643	SqlDataReader and Dynamic Formating Read Data	while (dr.Read())\n{\n    var msg = new AlertMessageData();\n    for (int i = 1; i < 4; i++)\n    {\n         var value = dr["Data" + i];\n         string format = "{0:n0}";\n         if (value is DateTime)\n         {\n            format = "{0:MM/dd/yyyy}";\n         } \n         else if (value is string)\n         {\n            format = "{0}";\n         }      \n\n         var stringValue = string.Format(format, value);\n         if (i == 1) msg.Data1 = stringValue;\n         if (i == 2) msg.Data2 = stringValue;\n         if (i == 3) msg.Data3 = stringValue;\n    }\n    message.MessageText.MessageData.Add(msg);\n}	0
13184149	13183991	Merge Files in a directory, with a newline appended each time	File.WriteAllLines(\n    targetFileName,\n    Directory.GetFiles(srcFolder, "*.txt")\n        .SelectMany(f=>\n            File.ReadLines(f).Concat(new[] {Environment.NewLine})));	0
3333980	3333817	find control in grid view	Label lbl = GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;	0
29326604	29326584	C# Enumerator Assign Value	IEnumerable<short> shortValues = new short[] { 3,6}         \n\n  IEnumerable<int> Values = from value in Enumerable.Range(1, 10) select value;	0
31178297	31168095	How do I get a window context so I can create NavigationOptions in a resharper plugin	var popupWindowContextSource = solution.GetComponent<MainWindowPopupWindowContext>().Source;	0
29264117	29263064	EPPlus To Read 1st Column Of Excel Into Array	var fd = new OpenFileDialog();\nfd.Filter = "Excel Files|*.xlsx";\nfd.InitialDirectory = @"C:\Temp\";\n\nif (fd.ShowDialog() == DialogResult.OK)\n{\n    using (var package = new ExcelPackage(fd.OpenFile()))\n    {\n        var sheet = package.Workbook.Worksheets.First();\n        var columnimport = sheet.Cells["A2:A"];\n        foreach (var cell in columnimport)\n        {\n            var column1CellValue = cell.GetValue<string>();\n        }\n    }\n}	0
9981804	9981577	Call method from Master Page	protected void Page_Load(object sender, EventArgs e)\n{\n    MasterPageClassName MyMasterPage = (MasterPageClassName)Page.Master; \n\n    TextBox t = new TextBox();\n    t.TextChanged += new EventHandler(MyMasterPage.usernameTextBox_TextChanged);\n}	0
30887302	30886737	C# - Passing parameter to stored procedure and return IEnumerable	public IEnumerable ListTop10countries(string mydirection)\n{\n    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCON"].ToString()))\n    {\n         var list = con.Query<OutputCountries>("Usp_GetTop10", new {direction = mydirection}, commandType: CommandType.StoredProcedure).AsEnumerable();\n         return list;\n    }\n}	0
1393806	1393208	How to update all the autoincrement columns in a DataTable?	ComponentsTableAdapter cta = new ComponentsTableAdapter();                    \nforeach (UpdaterDataSet.ComponentsRow r in uds.Components.Rows)\n{                    \n   long origId = r.Id;\n   cta.Update(r);\n\n   foreach (UpdaterDataSet.ComponentsRow s in uds.Components.Rows)\n   {\n      if (s.Id != r.Id && !s.IsComponentIdNull() && s.ComponentId == origId)\n         s.ComponentId = r.Id;\n   }                 \n}	0
13028554	13026451	How to change a Button Icon of a PDF Formular with itextsharp?	AcroFields form = stamper.AcroFields;\nPushbuttonField ad = form.GetNewPushbuttonFromField(buttonFieldName);\nad.Layout = PushbuttonField.LAYOUT_ICON_ONLY;\nad.ProportionalIcon = true;\nad.Image = Image.GetInstance(pathToNewImage);\nform.ReplacePushbuttonField("advertisement", ad.Field);	0
5633312	5633098	How to convert from Varbinary(MAX) into Video or Audio format in c# WPF	File.WriteAllBytes (strng path, byte[] bytes)	0
14680838	14641995	Using MEF correctly in MVVMLight regarding ViewModelLocator	[Import]\npublic TransactionViewModel ViewModel\n{\n    get { return (TransactionViewModel)DataContext; }\n    set { DataContext = value; }\n}	0
5962208	5961954	Fill DataTable from LinqDataSource	IEnumerable<DataRow> query = ...;\n    DataTable.DataSource = query.CopyToDataTable<DataRow>();	0
33093700	33093655	String split parse issue with space in C#	var str = @"cscript ""E:\Data\System Test Performance\Some Tool\script.vbs"" ""AP_TEST"" %%PARM1";\n\nstr.Split('"').Select (s => s.Trim()).Where (s => !string.IsNullOrEmpty(s));	0
30938229	30932723	How to get position from Image in PictureBox	_absoluteImagePositionX = imageBox.Width / 2 - image.Width / 2;\n_absoluteImagePositionY = imageBox.Height / 2 - image.Height / 2;	0
1131359	1131309	Extracting unique keys from key/value pairs, and grouping the values in an array	for (var kv in mylistofnamed) {\n   if (!dict.ContainsKey(kv.Key))\n      dict[kv.Key] = new List<string>();\n   dict[kv.Key].Add(kv.Value);\n}	0
8902784	8900491	Query a Database to Find a Match with MVC 3	var hasZip = db.BannedZipSet.Count(z => z.Zip == userZip) > 0;	0
13285577	13285376	Convert 64base byte array to PDF and show in webBroswer compont	webBrowser.Navigate("data:application/pdf;base64," + X);	0
22610820	22559400	Table __MigrationHistory doesnt update	Database.SetInitializer<MmContext>(new MigrateDatabaseToLatestVersion<MmContext, Configuration>());	0
19486798	19400693	Authentication against ADFS with WCF hosted on Windows service	AppliesTo = new EndpointAddress("net.tcp://localhost:xxxx/Service1/mex")	0
31886093	31840165	Swashbuckle 5 can't find my ApiControllers	// global asax\n    protected void Application_Start(object sender, EventArgs e)\n    {\n        GlobalConfiguration.Configure(WebApiConfig.Register);\n       // ... more stuff\n    }\n\n   //startup.cs\n   public void Configuration(IAppBuilder app)\n    {\n        // This must happen FIRST otherwise CORS will not work.\n        app.UseCors(CorsOptions.AllowAll);\n\n        HttpConfiguration config = new HttpConfiguration();\n\n        ConfigureAuth(app);\n\n        // webapi is registered in the global.asax\n        app.UseWebApi(config);\n\n    }	0
25917378	25917303	Display a button based on a login comparison	string[] lines = File.ReadAllLines(Path.Combine(dataFolder, "Permissions.txt"));\nbool userExists = lines.Any(ln => ln == newName); // or any comparison you like\n\n// use the bool variable to set the visibility\nWidgetForm.Visible = userExists;	0
28009072	28008847	Lists that implement an Interface, and passing a reference to that list	using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;\nusing System.Collections.Generic;\n\npublic interface IDebugPrints\n{\n\n}\n\npublic class Character : IDebugPrints\n{\n\n}\n\npublic class StoreList\n{\n    private List<IDebugPrints> internalList;\n\n    public StoreList(List<IDebugPrints> inList)\n    {\n        internalList = inList;\n    }\n}\n\n[TestClass]\npublic class Test1\n{\n    [TestMethod]\n    public void MyTest()\n    {\n        var characters = new List<IDebugPrints>();\n        characters.Add(new Character());\n        var sl = new StoreList(characters);\n    }\n}	0
3752576	3752408	Put GridView in Edit Mode Programmatically with ASP MERMERSHIP	YourGridView.EditIndex = rowIndex;	0
20684827	20678244	Changing the colour of a row based on a condition	protected void GVResults_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)\n    {\n        if (e.RowType != GridViewRowType.Data) return;\n        int value = (int)e.GetValue("CarrierId");\n        if (value > 0)\n            e.Row.ForeColor = System.Drawing.Color.Red;\n    }	0
5954230	5954120	Retrieve DLL from directory with Windsor Castle	container.Register(AllTypes\n    .FromAssemblyInDirectory(new AssemblyFilter("PlugInFolder"))\n    .BasedOn<IPlugIn>());	0
7068890	7068843	how to use DateTime.Parse() to create a DateTime object	var sDate = "20110815174346225";\nvar oDate = DateTime.ParseExact(sDate, "yyyyMMddHHmmssfff", CultureInfo.CurrentCulture);	0
19555641	19555627	Select multiple row with same id	while (reader.Read())\n{\n    MyOrders order1 = new MyOrders(reader.GetInt32(reader("orderId")));\n    orders.Add(order1);\n}	0
445278	445276	C# - Attribute to Skip over a Method while Stepping in Debug Mode	[DebuggerStepThrough]	0
17857110	17856736	Redirect from www to non-www with using subdomain	string url = Request["HTTP_REQUEST_URL"];  // not sure the exact Constant name of the header\nUri uri = new Uri(url);\nif(uri.Host.StartsWith("www.") && uri.Host.Count(c => (c == '.'))>2)\n{\n    Response.Redirect(url.Replace("www.", ""));\n}	0
17590352	17588450	Can you create a SQL Azure BACPAC from a Remote C# Application	//Set Inputs to the REST Requests in the helper class          \nIEHelper.EndPointUri = @"<address of database endpoint according to its location, e.g. https://by1prod-dacsvc.azure.com/DACWebService.svc for DB located in West US>"; \nIEHelper.ServerName = "<database_server_name>.database.windows.net"; \nIEHelper.StorageKey = "<storage_key>"; \nIEHelper.DatabaseName = "<database_name>"; \nIEHelper.UserName = "<database_user_name>"; \nIEHelper.Password = "<database_password>"; \n\n//Do Export operation \nstring exportBlobPath = IEHelper.DoExport(String.Format(@"https://<storage_name>.blob.core.windows.net/bacpac/{0}.bacpac", IEHelper.DatabaseName)); \nImportExportHelper IEHelper = new ImportExportHelper();	0
17638908	17638843	How do I split a path at specific directory?	string completePath = "X:\Projects\4604-Renovation\Unity\4604_02\Assets\Models\FullBuilding\Materials\";\n      string subPath = completePath.subString(completePath.IndexOf(@"Assets\"));	0
34119678	34119620	How to print array with constant row space in C#?	string.Format("{0:-5}", matrix[i][j].ToString("0.00"))	0
23637198	23635779	Programmatically add hyperlinks to gridview for programmically created gridviews	foreach ( var p in API.Query.GetAccoutsCustomers)\n{\n            var tmpatagridView = new GridView();\n\n            Dataset ds = API.Query.GetCustomerOrders(p.CusId);\n            dt = ds.Tables[0];\n            for (int i = 0; i < dt.Columns.Count; i++)\n            {\n                    HyperLinkField hplnk = new HyperLinkField();\n                    hplnk.DataTextField = dt.Columns[i].ColumnName.ToString();\n                    hplnk.HeaderText = dt.Columns[i].ColumnName.ToString();\n                    tmpatagridView.Columns.Add(hplnk);\n            }\n\n            tmpatagridView.DataSource = ds.Tables[0];\n            tmpatagridView.DataBind();\n            Panel1.Controls.Add(tmpatagridView);\n}	0
2860615	2855783	Using LINQ to isolate a particular object from a list of objects	List<Invader> firstInvaders = invaders\n  .GroupBy(inv => inv.Location.X)\n  .Select(g => g\n     .OrderByDescending(inv => inv.Location.Y)\n     .First())\n  .ToList();\n\nInvader shooter = firstInvaders[r.Next(firstInvaders.Count)];	0
26135404	26132022	c# mvc how to map the root url to a specific view	routes.MapRoute(\n   name: "Default",\n   url: "{controller}/{action}/{id}",\n   defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }\n);	0
24983872	24983790	xml file validating in notepad++ but not in C#	public static bool IsValidXml(string xmlFilePath, string xsdFilePath)\n{\n    var xdoc = XDocument.Load(xmlFilePath);\n    var schemas = new XmlSchemaSet();\n    schemas.Add(namespaceName, xsdFilePath);\n\n    Boolean result = true;\n    xdoc.Validate(schemas, (sender, e) =>\n         {\n             result = false;\n         });\n\n    return result;\n}	0
17048307	17048125	Entity Framework 6 Code First default datetime value on insert	[DatabaseGenerated(DatabaseGeneratedOption.Identity), DataMember]\npublic DateTime?            Registered          { get; private set; }	0
8263347	8263317	I'm using too many dictionaries within dictionaries in my code, is that a code smell?	IDictionary<Guid, List<string>> x;\n\nIDictionary<Guid, IDictionary<Guid, List<string>> y = new Dictionary<Guid, IDictionary<Guid, List<string>>();	0
1120733	1120723	Shortest way to create a List<T> of a repeated element	var l = Enumerable.Repeat('x',5).ToList();	0
15537899	15537863	ASP.Net C# create a cookie that expires at midnight	Response.Cookies["Cookie_SessionID"].Expires = DateTime.Today.AddDays(1);	0
21648080	21646861	Hide DataGridView default Row Selection	dgvCol.CurrentCell = null;	0
15749129	15748580	Mysql C# update int value by 1	string commmandLine = "UPDATE Users SET logins = logins + 1 WHERE id = @id";\ncmd.Set	0
18353314	18353077	How to get the Hidden Field value which is set by JQuery after Page Load	protected void Button_Click(object sender, EventArgs e)\n{\n   var myValue = MyHiddenField.Value \n}	0
1012412	1012400	How do I call a serverside function from javascript?	function RowSelected(sender, args) { \n    var dataKeyValue = args.getDataKeyValue("Order_No");      \n    document.getElementById("txtOrderno").value = dataKeyValue;\n    WebSchedule.Client.RadGrid1_SelectedIndexChanged(sender, args); \n}	0
6110306	6110082	is there any method that will find nearest match	Jaccard similarity coefficient	0
14232327	14232152	Find-Replace pattern in C#	var parts = s.Split(new string[] { "#EPB_IMG", "#", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);\nvar result = string.Join("|", parts);\n\nConsole.WriteLine("#EPB_IMG#" + result + "#EPB_IMG"); // prints your result.	0
17917074	17916841	dropdown list on showing selected item from list	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        DropDown.DataSourceID = Sections;\n        DropDown.DataTextField == "DisplayName";\n        DropDown.DataValueField = "ID"; \n        DropDown.DataBind();           \n\n    }\n}	0
24954247	24954096	Simplest way to calculate anniversary given a date in the past?	//My birthday, feel free to put this date in your calendars!\nvar startDate = new DateTime(1976, 2, 29);\n\n//Get the anniversary date for this year\nDateTime nextAnniversary;\n\ntry\n{\n    nextAnniversary = new DateTime(DateTime.Today.Year, startDate.Month, startDate.Day);\n}\ncatch(ArgumentOutOfRangeException)\n{\n    //DateTime conversion failed, try next day in the year\n    nextAnniversary = new DateTime(DateTime.Today.Year, startDate.AddDays(1).Month, startDate.AddDays(1).Day);\n}\n\n//Check if this year's anniversary has already happened\nif(nextAnniversary < DateTime.Today) nextAnniversary = nextAnniversary.AddYears(1);	0
26542950	26535247	In Umbraco 7, how can i search for all members with a custom property?	Services.MemberService\n\n.GetMembersByPropertyValue("city", "Horsens");\n//Returns all Members, of any type, with a mathcing value in the property with the given property alias	0
3686745	3686524	how to compare two column value in GridView?	if (((Label)e.Row.FindControl("lblProblemName")).Text == "Heart problem") \n     { \n          DropDownList ddlAssignDoc  \n              = (DropDownList)e.Row.FindControl("ddlAssignDoc"); \n          ddlAssignDoc.DataSource = Cardio; \n          ddlAssignDoc.DataBind(); \n\n      }	0
19582963	19582452	Injecting IOrderSender into domain object	public void placeOrder(...) {// method in application service\n        ....//order making\n        orderRepository.store(order);\n        applicationEvents.orderWasPlaced(order);//injected applicationEvents \n        //better move this step out of transaction boundary if not using 2pc commit\n        //make the method returnning order and use decorator to send the message \n        //    placeOrder(...) {\n        //        Order order = target.placeOrder(...);//transaction end here\n        //        applicationEvents.orderWasPlaced(order);\n        //        return order;\n        //    }\n    }\n\n    public class JmsApplicationEvents implements ApplicationEvents {\n        public void orderWasPlaced(Order order) {\n             //sends the message using messaging api of your platform\n        }\n    }	0
8699983	8699772	Row index of LinkButton in GridView	protected void userGridview_RowCommand(object sender, GridViewCommandEventArgs e)\n    {\n         GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);\n            int rowindex = rowSelect.RowIndex;                \n    }	0
30824022	30823479	Unable to extract values from object array, to which javascript array was deserialized	var serializedArray = new JavaScriptSerializer().Deserialize<object[]>(filter);\n\n            foreach (var item in serializedArray)\n            {\n               if (item is string)\n               {\n                  var element = item;\n               }\n               else\n                  foreach (var innerItem in (object[])item)\n                  {\n                     var element = innerItem;\n                  }\n            }	0
17370745	17355440	Mapping from Tuple to ICollection	Audit audit = null;\n            List<AuditItem> auditItemsList = new List<AuditItem>();\n\n            List<Audit> totalAudits = new List<Audit>();\n\n            ulong thisId = 0;\n\n            foreach (Tuple<DbAudit, DbAuditItem> tuple in audits)\n            {\n                if (tuple.Item1.Id == thisId)\n                {\n                    auditItemsList.Add(AuditItemMapper.Map(tuple.Item2));\n                }\n                else\n                {\n                    if (thisId != 0 && audit != null)\n                    {\n                        totalAudits.Add(new Audit(audit.ApplicationToken, audit.AuditKind, audit.DateCreated, audit.ContainerName, audit.ContainerItemId, audit.UserId, auditItemsList));\n                        auditItemsList.Clear();\n                    }\n                    thisId = tuple.Item1.Id;\n                    audit = (AuditMapper.Map(tuple.Item1));\n                    auditItemsList.Add(AuditItemMapper.Map(tuple.Item2));\n                }\n            }	0
8140319	8136072	How to show tooltip on MS Chart	// Set ToolTips for Data Point Series\nchart1.Series[0].ToolTip = "Percent: #PERCENT";\n\n// Set ToolTips for legend items\nchart1.Series[0].LegendToolTip = "Income in #LABEL  is #VAL million";\n\n// Set ToolTips for the Data Point labels\nchart1.Series[0].LabelToolTip = "#PERCENT";\n\n// Set ToolTips for second Data Point\nchart1.Series[0].Points[1].ToolTip = "Unknown";	0
33325252	33325083	C# issue with deserializing text file to list box, pulling all lines	while (input.Position < input.Length) {\n    var record = (RecordSerializable)formatter.Deserialize(input);\n    string[] values = new string[] \n    {\n        record.Name.ToString(),\n        record.StudentID.ToString(),\n        record.Grade.ToString()\n    }; // end string[] values\n\n        // copy string array values to TextBox values\n    SetValuesToListBox(values);\n}	0
21763327	21763231	increase the value of a variable each time that it is called from a controller	public class Location\n{\n    private double latitude;\n\n    public double Latitude\n    {\n        get\n        {\n            latitude += offset;\n            return latitude;\n        }\n\n        set\n        {\n            latitude = value;\n        }\n    }\n}	0
5317047	5316823	Putting tooltips programmatically on ListBox class	LBRangeOfUsers.DataSource = GetSource();\nLBRangeOfUsers.DataBind();\n\nforeach (ListItem item in LBRangeOfUsers.Items)\n    item.Attributes["title"] = item.Value;	0
12599259	12596226	Uploading files to an FTP server	fileStream.Close()	0
2726736	2726693	How to Select two values from one value	var resultList = \n    customers.SelectMany(c => new[] {c.Name, "0"});	0
433879	433846	Access a control inside a the LayoutTemplate of a ListView	((Literal)lv.FindControl("litControlTitle")).Text = "Your text";	0
31187697	31187231	Simple injector equivalent of Unity Func<T,TResult> registration	container.Register<Func<Type, Object>>(() => { return (x) => container.GetInstance(x); });	0
16013324	16013254	Retrieve Email Information from .EML Files	protected CDO.Message ReadMessage(String emlFileName)\n{\n    CDO.Message msg = new CDO.MessageClass();\n    ADODB.Stream stream = new ADODB.StreamClass();\n    stream.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty);\n    stream.LoadFromFile(emlFileName);\n    stream.Flush();\n    msg.DataSource.OpenObject(stream, "_Stream");\n    msg.DataSource.Save();\n    return msg;\n}	0
7963574	7963560	How can i split the string like shown in example below	string[] s = str.Split(',');\nif (s.Length > 0)\n{\n    foreach (char c in s[0])\n        lst.Add(c.ToString());\n    for (int i = 1; i < s.Length; i++)\n        lst.Add(s[i]);\n}	0
16090389	16090064	How to detect click from default context menu (ComboBox)	public partial class TextBoxUsingDefaultContextMenu : TextBox\n{\n    public TextBoxUsingDefaultContextMenu()\n    {\n        InitializeComponent();\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n        const int WM_CONTEXTMENU = 0x007B;\n        const int WM_MENUCOMMAND = 0x0126;\n        const int WM_COMMAND = 0x0111;\n\n        switch (m.Msg)\n        {\n            case WM_CONTEXTMENU:\n                MessageBox.Show("Opening Context Menu");\n                break;\n\n            case WM_MENUCOMMAND:\n                MessageBox.Show("WM Menu Command Event fired");\n                break;\n\n            case WM_COMMAND:\n                MessageBox.Show("WM Command Event fired");\n                break;\n\n        }\n\n        base.WndProc(ref m);\n    }\n\n    protected override void DefWndProc(ref Message m)\n    {\n        base.DefWndProc(ref m);\n    }\n}	0
16504556	16504498	Remove Item from generic list	foreach(int item in removeitems.OrderByDescending(n => n))\n{\n    model.ListItems.RemoveAt(item);\n}	0
6941460	6941103	Access controls inside a repeater inside a user control	public string xmlString\n{\nget\n{\n    var _builder = new StringBuilder();\n\n    var rpt = (IList<Owner>) rptOwners.DataSource; //ADDED A CAST\n    IList<string> ownersRepeater = new List<string>();\n\n    foreach (var item in rpt )\n    {\n        _builder.Append("<Owners>");\n        _builder.Append("<Owner>");\n        _builder.Append(String.Format("<item>{0}</item>", name));\n        _builder.Append(String.Format("<item>{0}</item>", address));\n        _builder.Append(String.Format("<item>{0}</item>", age));\n        _builder.Append("</Owner>");\n        _builder.Append("</Owners>");\n    }\n    return _builder.ToString();\n}	0
3063348	3063270	C# Get Events of a Control inside a Custom Control	public partial class UserControl1 : UserControl {\n    public event EventHandler SelectedIndexChanged;\n\n    public UserControl1() {\n        InitializeComponent();\n    }\n\n    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {\n        EventHandler handler = SelectedIndexChanged;\n        if (handler != null) handler(this, e);\n    }\n    public object SelectedItem {\n        get { return listBox1.SelectedItem; }\n    }\n}	0
30199981	30199397	Wpf Telerik PDFViewer	pdfViewer.DocumentSource = new PdfDocumentSource(new Uri("c:\\temp\\Test.pdf"));	0
12838858	12838799	How to send a key ASCII value 0?	>???????????	0
34112039	34111972	How can i add a menuStrip menus for each item in a listBox?	void menuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n    if(item != null && item.SelectedIndex > -1)\n    {\n        Clipboard.SetText(item.Items[item.SelectedIndex].ToString());\n    }\n}	0
12838737	12838209	Get newest Post of each forum	return View(db.Forums.Select(f => new {\n      Forum = f, \n      FirstPost = f.Posts.OrderBy(x=>x.Date).First() }\n   ).ToList()\n);	0
11312938	11312895	Get string between delimiters from file in C#	string ExtractString(string s, string tag) {\n     // You should check for errors in real-world code, omitted for brevity\n     var startTag = "[" + tag + "]";\n     int startIndex = s.IndexOf(startTag) + startTag.Length;\n     int endIndex = s.IndexOf("[/" + tag + "]", startIndex);\n     return s.Substring(startIndex, endIndex - startIndex);\n}	0
31262973	31262696	Read XML file and return attribute value	foo = (from n in xml.XPathSelectElements("ProfileCollection/Profiles/Profile")\n       where n.Attribute("LibId").Value == libraryID\n       select n.Attribute("ProfileId").Value).FirstOrDefault();	0
15891335	15885750	Silverlight user control databinding	LayoutRoot.DataContext = this;	0
5625836	5625819	What's the best approach to split app.xaml?	ResourceDictionary.xaml	0
25279534	25279284	How can I get some numbers from xml to int?	XDocument xDoc = XDocument.Load(@"your path");\n        int total=0;\n\n\n        foreach (var elem in xDoc.Document.Descendants("test-results"))\n        {\n            total += int.Parse(elem.Attribute("total").Value);\n\n        }	0
9689673	9686622	Exporting a Silverlight grid to Excel sheet only writes 1 row	for (int J = 0; J <= myWorksheet.Table.Rows.Count - 1; J++)	0
12467122	12466290	How to exclude classes from an OpenCover report	-filter:"+[*]* -[*]*.AWebService.*"	0
11079375	11079322	Return a class object from a dll C#	Foo.Bar.SomeClass	0
14647677	14644553	FindOneByIdAs with string representation of ObjectId	var classmap = BsonClassMap.LookupClassMap(typeof(T));\n// // This is an indexed array of all members, so, you'd need to find the Id\nvar member = map.AllMemberMaps[0]; \nvar serOpts = ((RepresentationSerializationOptions).SerializationOptions);\nif (serOpts.Representation == BsonType.ObjectId) { ... }	0
7199948	7199937	How To Give a Space between Label and Textbox in Different <td> tag In A Row C# Web App?	td.style5 { padding-right: 1em; }	0
4858178	4857951	Derive generic method from generic method of non-generic class	public class Base\n{\n    // Base method has a 'class' constraint\n    public virtual List<T> MyMethod<T>() where T : class\n    {\n        return new List<T>();\n    }\n}\n\npublic class Derived : Base\n{\n    // Override does not declare any constraints; constraints are inherited\n    public override List<T> MyMethod<T>()\n    {\n        // base call works just fine\n        return base.MyMethod<T>();\n    }\n}	0
20694668	20694536	Save document immediately after opening program	private void Window_Load(object sender, EventArgs e)\n{\n    System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();\n    saveDlg.DefaultExt = ".rtf";\n    saveDlg.Filter = "RTF Documents (.rtf)|*rtf";\n\n    RetHere:\n    if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.Yes)\n    {        \n        string filename = saveDlg.FileName;\n        System.IO.File.Create(filename);\n    }\n    else {\n       System.Windows.Forms.MessageBox.Show("Your message here!", "Save", System.Windows.Forms.MessageBoxButtons.OK);\n       goto RetHere;\n    }\n}	0
32963139	32962874	Update canvas in WPF	Task.Run(() => {\n    for (var iteration = 0; iteration < iterations; iteration++)\n    {\n        // move ants\n        foreach (var ant in ants)\n        {\n            var x = (random.Next(3) - 1) + ant.Position.X;\n            var y = (random.Next(3) - 1) + ant.Position.Y;\n            ant.Move(x, y);\n        }\n\n        // animate the ant\n        Debug.WriteLine(ants[0].Position.X);\n        this.Dispatcher.Invoke((Action)(() =>\n        {\n            Canvas.SetLeft(ant1, ants[0].Position.X);\n        }));\n    }\n});	0
4760070	4759898	A class for efficient key generation	int[] data = { 0, 1, 2, 3, 4, 5, 6 };\n\nstring value = String.Join(",", Array.ConvertAll<int, string>(data, x => x.ToString()));	0
13509416	13509387	Display each checkbox in new line inside a div on asp page	string[] longMsg = str.Split('*'); //Message contains * character as delimiter\n\n\nfor (int i = 0; i < longMsg.Length; i++)\n{\n  CheckBox cb = new CheckBox();\n  cb.Text = longMsg[i];\n\n  Literal br = new Literal();\n  br.Text = "<br/>";\n\n  Form.Controls.Add(cb);\n  Form.Controls.Add(br );\n}	0
25240033	25239758	Access denied to the path when uploading an image to a picturebox	pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);	0
14087246	14086536	Asp.net Membership Provider shows login information in url	return RedirectToAction("AccountScreen", "Customer", new { id = model.Id });	0
3404820	3404715	C# hashcode for array of ints	int hc=array.Length;\nfor(int i=0;i<array.Length;++i)\n{\n     hc=unchecked(hc*314159 +array[i]);\n}\nreturn hc;	0
12588938	12588858	Get difference from next number divisible by 10	(10-(num%10))%10	0
1892746	1892696	hex number of length 128 which is to be converted to binary in c#	byte b = 123;\nstring s = Convert.ToString(b, 2); // second argument is base\nConsole.WriteLine(s); // prints '1111011'	0
7062287	7062263	How to safely remove list from list in loop	mainList.RemoveAll(x => x.Dead);	0
10882556	10882244	Using HttpRequestHeaders in WinRT & C#	using (var httpClient = new HttpClient())\n  {\n    var url = new Uri("http://bing.com");\n    var accessToken = "1234";\n    using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))\n    {\n      httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),\n        string.Format("Bearer {0}", accessToken));\n      httpRequestMessage.Headers.Add("User-Agent", "My user-Agent");\n      using (var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage))\n      {\n        // do something with the response\n        var data = httpRequestMessage.Content;\n      }\n    }\n  }	0
24290685	24288970	How to use MVVM-Light with IMessenger to pass a value between 2 VMs in WIndows 8.1	public void NavigateToViewByChannelPage(Channel parameter)\n        {\n            //Must create an instance so that the page can recieve the info\nNeeded this -->  SimpleIoc.Default.GetInstance<ViewByChannelPageViewModel>();\n\n            //Sending info to ViewModel\n            _messenger.Send(new IdParameter() {Id = parameter.Id});\n\n            //Going to page\n            this.Navigate(typeof(ViewByChannelPage));\n        }	0
29535286	29535148	How to Pass View Constructor Parameter to View Model	MyView\n{\n   MyView(int id)\n   {\n     InitializeComponent();\n     ((MyViewModel)DataContext).ID = id;\n   }\n }	0
27818940	27818679	Can't add child to WrapPanel from another thread	private void Grid_Loaded(object sender, RoutedEventArgs e)\n{\n    Thread t = new Thread(LoadIcons);\n    t.SetApartmentState(ApartmentState.STA);\n\n    t.Start();\n}\n\nprivate void LoadIcons()\n{ \n    Dispatcher.Invoke(new Action(() => \n    {\n        foreach(Icon present in directory)\n        { \n            present.Width = 16;\n            present.Height = 16;\n            pnlIcons.Width = 50;\n            pnlIcons.Children.Add(present);\n        }\n    }));\n}	0
12060531	12060513	converting a string to Keys in C#	Enum.TryParse	0
663379	663366	How to override a method in another assembly?	public override string FormatTags(string[] tagList) {\n    string result = base.FormatTags(tagList);\n    // do something with result\n    return result;\n}	0
29474167	29420550	Sort direction in GridColumnView Telerik	private void SaveColumnSort(GridViewColumn gridViewColumn, string type)\n  {\n     var sortDirection = string.Empty;\n     switch (gridViewColumn.SortingState)\n     {\n        case SortingState.None:\n           sortDirection = "ASC";\n           break;\n        case SortingState.Ascending:\n           sortDirection = "DESC";\n           break;\n        default:\n           sortDirection = "ASC";\n           break;\n     }\n\n     var sort = string.Format("{0};{1}", gridViewColumn.Header, sortDirection);\n\n     switch (type)\n     {\n        case "Claims":\n           PopulationOverlayInstance.Settings.RegOverlayClaimsColumnSort = sort;\n           break;\n        case "Charges":\n           PopulationOverlayInstance.Settings.RegOverlayChargesColumnSort = sort;\n           break;\n     }\n\n     PopulationOverlayInstance.Settings.Save();\n  }	0
10925185	10925094	Pick files with certain file names in c#	DirectoryInfo di = new DirectoryInfo("SourcePath");\nIEnumerable<FileInfo> fileinfo = di.EnumerateFiles();\nforeach(FileInfo fi in fileinfo)\n{\n    string[] tmp = fi.Name.Split('_');\n    if (tmp.Length == 3)\n    {\n        if (!Directory.Exists("YourPath"))\n        {\n            Directory.CreateDirectory("YourPath" + tmp[0].ToString());\n            fi.MoveTo("YourPath" + tmp[0].ToString() + @"\" + fi.Name);\n\n        }\n        else\n            fi.MoveTo("YourPath" + + tmp[0].ToString() + @"\" + fi.Name);\n\n    }\n    else if (tmp.Length == 2)\n    {\n        //Copy Batch Id and Ftp logic\n    }\n}	0
22954914	22954537	Get values from dataset without column name	result = reader.AsDataSet();\nstring CellValue=result.Tables[0].Rows[4][10];\nreader.Close();	0
23523546	18736901	Convert PNG byte array to JPEG byte array	byte[] jpgImageBytes = null;\nusing (var origImageStream = new MemoryStream(image))\nusing (var jpgImageStream = new MemoryStream())\n{\n    var jpgImage = System.Drawing.Image.FromStream(origImageStream);\n    jpgImage.Save(jpgImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);\n    jpgImageBytes = jpgImageStream.ToArray();\n    jpgImage.Dispose();\n}	0
14027992	14027121	DataTable that can be accessed from Repeater.ItemDataBound	protected void Page_Load(object sender, EventArgs e)\n{\n    int numPages = 3, numItems = 10;\n\n    int[] parentRepeatCnt = Enumerable.Range(0, numPages).ToArray();\n    int[] childRepeatCnt = Enumerable.Range(0, numItems).ToArray();\n\n    ParentRepeater.DataSource = parentRepeatCnt;\n    ParentRepeater.DataBind();\n\n    foreach (int i in parentRepeatCnt)\n    {\n        Repeater ChildRepeater = ParentRepeater.Items[i].FindControl("ChildRepeater") as Repeater;\n        ChildRepeater.DataSource = childRepeatCnt;\n        ChildRepeater.DataBind();\n    }\n}\n\npublic void ChildRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.Header)\n    {\n        Label Label1 = e.Item.FindControl("Label1") as Label;\n        // access DataTable here\n        Label1.Text = myDataTable.Rows[0]["item"].ToString();\n    }\n\n}	0
9749995	9748926	Json deserialization of anonymous array	[CollectionDataContract] \npublic  class Coordinate : List<object> \n{ \n    public decimal Longitude { get { return (decimal)this[0]; } set { this[0] = value; } } \n\n    public decimal Latitude { get { return (decimal)this[1]; } set { this[1] = value; } } \n\n    public ExtensionDataObject ExtensionData { get; set; } \n}	0
423210	423157	How to diff Property Values of two objects using GetType GetValue?	public static List<String> DiffObjectsProperties(object a, object b)\n{\n    Type type = a.GetType();\n    List<String> differences = new List<String>();\n    foreach (PropertyInfo p in type.GetProperties())\n    {\n        object aValue = p.GetValue(a, null);\n        object bValue = p.GetValue(b, null);\n\n        if (p.PropertyType.IsPrimitive || p.PropertyType == typeof(string))\n        {\n            if (!aValue.Equals(bValue))\n                differences.Add(\n                    String.Format("{0}:{1}!={2}",p.Name, aValue, bValue)\n                );\n        }\n        else\n            differences.AddRange(DiffObjectsProperties(aValue, bValue));\n    }\n\n    return differences;\n}	0
34450592	34448790	Get All Specific Tags in XML Web Page To List (C#)	string url = "http://www.topquadcoptersreviews.com/sitemap.xml";\nvar xmlDoc = new XmlDocument();\nvar xmlns  = new XmlNamespaceManager(xmlDoc.NameTable);\n    xmlns.AddNamespace("default", "http://www.sitemaps.org/schemas/sitemap/0.9");\nxmlDoc.Load(url);\n\nvar locs = xmlDoc.SelectNodes("//default:loc", xmlns)\n    .OfType<XmlElement>()\n    .Select(element => element.InnerText)\n    .ToList();	0
905770	905764	c#: copy variable to byte array	BitConverter.GetBytes()	0
3343823	3343776	Is there a way to convert between a Ref parameter type and the non-ref version in C#	var stringRefType = typeof(string).MakeByRefType();\nvar stringType = stringRefType.GetElementType();\nConsole.WriteLine(stringType == typeof(string)); // True	0
24744101	24706316	Nested Gridview Footer Textbox Required Field Validation Firing for Each Row on Nested Gridview Footer Button Click	ValidationGroup='<%# "PC" + Container.DataItemIndex + Eval("ContractProjectCodeID")	0
21270384	21269650	How to make Application ontop of all windows and allow message box to be shown correctly	private void timer1_Tick(object sender, EventArgs e)\n{\n    if (!this.TopMost == true)\n        this.TopMost = true;\n\n    this.Visible = true;\n\n    this.WindowState = FormWindowState.Maximized;\n    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n\n    MessageBox.Show("Some error occured");\n}	0
28915550	28915525	Regex: Identify words that contain 'ing'	Regex.Match(@"(?i)\w+ing(\W|$)")	0
20681582	20681444	Finding the maximum value in a list	subscription.Farms.AsParallel().SelectMany(x => \n          (x.Paddocks.SelectMany(\n              y => y.Mobs.Select(j => j.AnimalMobId))).Max();	0
10335971	10335812	Xml deserialization, perserving order across different tags	var doc = XDocument.Load(...);\n\nvar fixeruppers = doc\n      .Descendants("users")\n      .Elements()\n      .ToList();   // isolate us from any movements in the doc\n\nint id = 1; // base\nforeach (var fixer in fixeruppers)\n   fixer.SetAttributeValue("Id", id++);\n\nXmlReader readerForDeserialize = doc.CreateReader();	0
6302157	6302052	how to give gridview first column left margin from gridview?	table.myGridView\n{\n  color: black;\n  border: solid 1px #999999;\n  background-color: white;\n  width: 439px;\n  font-family: arial;\n}\n\ntable.myGridView th\n{\n  // style your column headings\n}\n\ntable.myGridView td\n{\n  // style your cells\n  padding: 3px;\n}\n\ntable.myGridView tr td:first-child\n{\n  // style the first cell in each row\n  padding-left: 10px;\n}	0
13420449	13419392	microsoft fakes only stub static property of a static class	Globals.greatStations = new List<string>();	0
24754135	24753405	Valiation fires before button click in MVC3	[ChildActionOnly]\n    public ActionResult GetCommodityReportFilter(LikeFilterModel modelObj)\n    {\n        LikeFilterModel model = null;\n        if (Request.HttpMethod != "POST")\n        {\n            ModelState.Clear(); // add this\n            model = new LikeFilterModel();\n            model.ReportName = ReportType.Commodity;\n        }\n        else\n            model = modelObj;\n\n        return GetLikeFilter(model);\n    }	0
3414546	3410020	Delete an object with a many to many relationship from the entities framework?	SET NULL	0
21726223	21725786	How to access object in array( Dynamic DataType) with foreach loop in C#	foreach (dynamic dObject in mArray)\n{\n\n}	0
5589519	5555597	Regex to find GetText strings "<%$ GetText:"	try {\n    Regex regexCard = new Regex(@"([Gg][Ee][Tt]{2}[Ee][Xx][Tt]):\s*(['""""]([^'""""]+)['""""])");\n    Match matchResults = regexCard.Match(subjectString);\n    while (matchResults.Success) {\n\n        //if i is 0 it returns the entire match\n        //if i is 1 it returns the first capture group in this case "gettext" without the quotes.\n        //if i is 2 it returns the second capture group, everything after <:><0-1 whitespace> including the first <' or "> until it hits a <' or "> (also includes this)\n            //if i is 3 it returns the same but without the quotes.\n        //you can move parentheses around or make more to create more capture groups to get the text you want.\n        if(matchResults.Groups[i].Success)\n        {\n            string value = matchResults.Groups[i].Value;\n        }\n        matchResults = matchResults.NextMatch();\n    } \n} catch (ArgumentException ex) {\n    // Syntax error in the regular expression\n}	0
10137055	10137008	How do I get a list of all the assemblies I can reference on my machine?	List<string> gacFolders = new List<string>() { \n    "GAC", "GAC_32", "GAC_64", "GAC_MSIL", \n    "NativeImages_v2.0.50727_32", \n    "NativeImages_v2.0.50727_64" \n};\n\nforeach (string folder in gacFolders)\n{\n    string path = Path.Combine(@"c:\windows\assembly", folder);\n    if(Directory.Exists(path))\n    {\n        Response.Write("<hr/>" + folder + "<hr/>");\n\n        string[] assemblyFolders = Directory.GetDirectories(path);\n        foreach (string assemblyFolder in assemblyFolders)\n        {\n            Response.Write(assemblyFolder + "<br/>");\n        }\n    }\n}	0
861943	861925	Displaying only selected headers in DataGridView	this.dataGridView1.Columns["Age"].Visible = false;	0
1334784	1333683	How to drag and drop dynamically created controls	Button btnTask = new Button();\nbtnTask.Content = _myCustomTasks[iCtr].Description;\nbtnTask.Background = _myCustomTasks[iCtr].TaskColor;\nPlaceHolder1.Controls.Add(btnTask);	0
20677998	20677906	I cannot receive post data from a form in Controller	public ActionResult CreateProduct()\n{\n    Product prd= new Product();\n    return View(prd);\n}	0
1664436	1664395	Select Random Datas From File	using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\n\nnamespace Tests.Console\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string fileName = "c:\\toto.txt";\n            var content = File.ReadAllLines(fileName).ToList();\n            var selected = content[new Random().Next(0, content.Count)];\n\n            Debug.Write(selected);\n\n            content.Remove(selected);\n            File.WriteAllLines(fileName, content.ToArray());\n        }\n    }\n}	0
12704016	12703945	How to compare sequence of two string array	public static bool IsSequenceEqual(string[] a, string[] b)\n{\n    if (a.Length != b.Length)\n        return false;\n    for (int i = 0; i < a.Length; i++)\n    {\n        if (a[i] != b[i])\n            return false;\n    }\n    return true;\n}	0
4713764	4713061	Returning duplicate row in T-SQL	with Numbers(Num)\nas\n(\n    select 1 as Num\n    union all\n    select (Num + 1) as Num\n    from Numbers\n    where Num < 1000\n)\nselect t1.*\nfrom @T1 t1\n    join @T2 t2 on t1.ID = t2.ID\n    join Numbers n on t2.RowCnt >= n.Num option(maxrecursion 1000)	0
4205053	4171658	How to convert pkcs8 key file to DER format in #C?	byte[] dataKey = File.ReadAllBytes(fileName);\n\n        Org.BouncyCastle.Crypto.AsymmetricKeyParameter asp =\n            Org.BouncyCastle.Security.PrivateKeyFactory.DecryptKey(pass.ToCharArray(), dataKey);\n\n        MemoryStream ms = new MemoryStream();\n        TextWriter writer = new StreamWriter(ms);\n        System.IO.StringWriter stWrite = new System.IO.StringWriter();\n        Org.BouncyCastle.OpenSsl.PemWriter pmw = new PemWriter(stWrite);\n        pmw.WriteObject(asp);\n        stWrite.Close();\n        return stWrite.ToString();	0
79675	75577	Databinding ApplicationSettings to Custom Components	[ DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden ),\n  EditorBrowsable( EditorBrowsableState.Advanced ),\n  Browsable( false ) ]\npublic BindingContext BindingContext {\n    ...\n}\n\n[ ParenthesizePropertyName( true ),\n  RefreshProperties( RefreshProperties.All ),\n  DesignerSerializationVisibility( DesignerSerializationVisibility.Content ),\n  Category( "Data" ) ]\npublic ControlBindingsCollection DataBindings {\n   ...\n}	0
4420558	4420524	DateTime Behavior in SQL Server & C#	if (currentApp.Updated - app.Updated < TimeSpan.FromMilliseconds(-3.34))	0
19781408	19781343	How do i capture the current logged on Admin's UserID and show it on another page?	// To save UserID in session\nSession.Add("userID", "123");\n// or\nSession["userID"] = "123";\n\n// Get UserID from session\nstring userID = (string)(Session["userID"]);\n\n// Remove from session\nSession.Remove("userID");	0
27569206	27568970	Can you dynamically cast during runtime inside a linq statement?	dateTimeList = \n    _dataSeriesList.Select(x => { \n        if (x.GetType().Name == "Class1") \n          return ((Class1)x).Time;\n        else\n          return ((Class2)x).Time;\n                   })\n                 .Where(d => d >= min && d <= max)\n                 .OrderBy(t => t)\n                 .Select(d => d)\n                 .ToList();	0
7588344	7587737	Filtering data based on data through multiple relationships	Model.Vendors.Where(v => v.Commodities.Any(c => c.CommodityCategory.Id ==\n                                                          commodityCategory.Id))	0
10917262	10917218	How to make a class where all fields/properties are const by default?	public static class Constants\n{\n    public const int SomeId = 123;\n    public const string SomeName = "foo";\n\n    public static readonly DateTime myDateTime = new DateTime();\n\n    public string notConstant = "test"; //does not compile\n}	0
12075920	12075909	How to remove unused using namespaces	Organise Usings > Remove Unused Usings	0
2589607	2589362	Static Variables somehow maintaining state?	Response.Write("1:" + SharedLibrary.Application.Test);\nSharedLibrary.Application.Test = int.Parse(SharedLibrary.Application.Test) + 1;\nResponse.Write(" 2:" + SharedLibrary.Application.Test);	0
12932354	12932232	How to display special characters - knowing its alt code	private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n   if (e.KeyChar == '[')\n       e.KeyChar = '??';\n   else if (e.KeyChar == '\\')\n       e.KeyChar = '??';\n}	0
6291788	6291678	Convert input string to a clean, readable and browser acceptable route data	var input = "This is some amazing Rexex Stuff!";\n            input = Regex.Replace(input, @"[\W]+", "-").ToLower();\n            input = Regex.Replace(input, @"[-]+$", "");\n            Console.Write(input);\n            Console.Read();	0
7662672	7662568	How to know which button postbacks the page?	/// <summary>\n/// Retrieves the control that caused the postback.\n/// </summary>\n/// <param name="page"></param>\n/// <returns></returns>\nprivate Control GetControlThatCausedPostBack()\n{\n    //initialize a control and set it to null\n    Control ctrl = null;\n\n    //get the event target name and find the control\n    string ctrlName = Page.Request.Params.Get("__EVENTTARGET");\n    if (!String.IsNullOrEmpty(ctrlName))\n        ctrl = Page.FindControl(ctrlName);\n\n    //return the control to the calling method\n    return ctrl;\n}	0
852978	852916	How to create extension methods with lambda expressions	public static decimal ChangePercentage(this IEnumerable<Trade> trades, Func<Trade,bool> pred)\n        {\n            var query = from trade in trades\n                        where pred(trade);\n                        orderby trade.TradeTime descending\n                        select trade;\n            return (query.First().Value - query.Last().Value) / query.First().Value * 100;\n        }\n\n    someTrades.ChangePercentage(x => x.TradeDate >= startDate && x.TradeTime <= endDate);	0
23059974	22296015	Get subitem value in radlistview items	foreach (Telerik.Web.UI.RadListViewItem item in lvAllUsers.Items)\n{\n    if (((System.Web.UI.WebControls.CheckBoxList)(((System.Web.UI.Control)(item)).Controls[1])).Items[0].Selected)\n    {\n        ccUserNames.Add(((System.Web.UI.WebControls.Label)(((System.Web.UI.Control)(item)).Controls[7])).Text);\n    }\n}	0
25594909	25594800	Determining if any flag is set over a certain value	var currentVal = Options.FlagV | Options.FlagW;\n     foreach (Options enumVal in Enum.GetValues(typeof(Options)))\n         if (enumVal > Options.FlagV && (enumVal & currentVal) == enumVal)\n                //Do stuff	0
10573565	10573445	How to bind XAML textbox to custom object?	{Binding Path=CustomObject.SomeProperty, RelativeSource={RelativeSource AncestorType={x:Type local:EditCustomObjectWindow}}, Mode=TwoWay, PresentationTraceSources.TraceLevel=High}	0
33908364	33908213	Declare and Initialize a ToolStripMenuItem with an Event Handler	private ToolStripMenuItem StartButton;\n\npublic Timer()\n{\n    StartButton = new ToolStripMenuItem("Start Timer", null, StartButton_Click);\n}	0
3062637	3061535	XML Serialize and Deserialize Problem XML Structure	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.LoadXml(__XMLDocument);\n\nStringWriter stringWriter = new StringWriter();\nXmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);\nxmlDoc.WriteTo(xmlWriter);\n\nXmlSerializer _XMLSerial = new XmlSerializer(typeof(List<tinfCte>));\nMemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));\n\nstream.Position = 0;\n_XMLDocumentToTInfCTeList = (List<tinfCte>)_XMLSerial.Deserialize(stream);\nreturn _XMLDocumentToTInfCTeList;	0
29418607	29417312	How to sort nested collection in Linq	AsEnumerable()	0
18435697	18435668	Take a link that ends "default.aspx?ID=4" and pass the value 4 as a parameter?	int.Parse(Request.QueryString["id"])	0
5651144	5647419	How can I change part of the composition in MEF after composition?	public static void Main(string[] args)\n{\n    using (var container = new CompositionContainer(...))\n    {\n        // phase 1: compose security service and initialize principal\n        var securityService = container.GetExportedValue<ISecurityService>();\n        securityService.InitializePrincipal();\n\n        // phase 2: compose the rest of the application and start it\n        var form = container.GetExportedvalue<MainForm>();\n        Application.Run(form);\n    }\n}	0
17639712	17639237	ImageList: Disposing the original image removes it from the list	il.Images.Add(test);\nvar dummy = il.Handle;     // <== NOTE: added\ntest.Dispose();            // no problem	0
10002355	10002299	How to upload a file to ASP.NET MVC from a console application	[HttpPost]\npublic ActionResult Test()\n{\n    var file = Request.Files[0] as HttpPostedFile;\n    XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream));\n    var test = new MyTest();\n    return File(test.RunTest(xml), "text/xml", "testresult.xml");\n}	0
3889319	3887726	Swap two variables without using ref/out in C#	class Program\n{\n    static void FunkySwap<T>(T a, T b, Action<T> setA, Action<T> setB)\n    {\n        T tempA = a;\n        setA(b);\n        setB(tempA);\n    }\n    static void Main(string[] args)\n    {\n        string s1 = "big";\n        string s2 = "apples";\n        Console.WriteLine("BEFORE, s1: {0}, s2: {1}", s1, s2);\n        FunkySwap(s1, s2, a => s1 = a, b => s2 = b);\n        Console.WriteLine("AFTER,  s1: {0}, s2: {1}", s1, s2);\n    }\n}	0
1633541	1633501	Receive WM_COPYDATA struct in WPF or Console C# app	private HwndSource hwndSource;\nvoid MyWindowClass_Loaded(object sender, RoutedEventArgs e) \n{\n    hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);\n    hwndSource.AddHook(new HwndSourceHook(WndProc));\n}\nprivate static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n{\n    // Process your windows proc message here          \n}	0
28682168	28669378	How to Move a file to SFTP server using SharpSSH	Tamir.SharpSsh.Sftp client = new Tamir.SharpSsh.Sftp(address, username, password);\nclient.Connect();\nif(client.Connected) {\n    client.Rename("/source/path/file.zip", "/destination/path/file.zip");\n} else {throw new ... }	0
13659905	13647177	Specific search on twitter using tweetsharp	Console.WriteLine(twt.Text);	0
13751445	13750579	Compare rows of a datagridview and remove repeated rows	for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)\n{\n   var rowToCompare = grv.Rows[currentRow]; // Get row to compare against other rows\n\n   // Iterate through all rows \n   //\n   foreach (var row in grv.Rows)\n   {  \n       if (rowToCompare.equals(row) continue; // If row is the same row being compared, skip.\n\n       bool duplicateRow = true;\n\n       // Compare the value of all cells\n       //\n       for (int cellIndex; cellIndex < row.Cells.Count; cellIndex++)\n       {\n           if ((null != rowToCompare.Cells[cellIndex].Value) && \n               (!rowToCompare.Cells[cellIndex].Value.equals(row.Cells[cellIndex].Value)))\n          {\n             duplicateRow = false;\n             break;\n          }\n       }\n\n       if (duplicateRow)\n       {\n           grv.Rows.Remove(row);\n       }\n   }\n}	0
2630654	2630580	Programatically Check if Windows Messaging Installed?	// Setup the query\nManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",\n                    "SELECT * FROM Win32_Service WHERE Name = 'Blah'");\n\n// Execute the query and enumerate the objects\nforeach (ManagementObject queryObj in searcher.Get())\n{\n   // examine the query results to find the info you need.  For example:\n    string name = (string)queryObj["Name"];\n    bool started = (bool)queryObj["Started"];\n    string status = (string)queryObj["Status"];\n}	0
14349017	14348750	Populate a dropdownlist in MVC3 not working	public ActionResult Create()\n    {\n        Cat ca= new Cat();\n\n        IEnumerable<SelectListItem> items = ca.Categories().Select(c => new SelectListItem\n        {\n            Text = c.name,\n            Value = c.id.ToString()\n        });\n        ViewData["Categ"] = items;\n\n        return View("Index");\n    }\n\n[HttpPost]\npublic ActionResult Create(BookEntity ent)\n    {   \n        db.BookEntity.Add(ent);\n        db.SaveChanges();\n        return RedirectToAction("Index");\n    }	0
30405914	30405842	counting occurances of item in IEnumerable using linq in C#	"aqejqkndaasaamd".GroupBy(x => x).OrderByDescending(g => g.Count()).First().Key	0
228060	228038	Best way to reverse a string	public static string Reverse( string s )\n{\n    char[] charArray = s.ToCharArray();\n    Array.Reverse( charArray );\n    return new string( charArray );\n}	0
22429747	22429734	Basic C# How to use power to in for statement?	squareSum += iSquared;	0
6845408	6845275	Checking if user has changed cookie value, manually	private string sign(string hashStr, byte[] secret) \n{\n    // Compute the signature hash\n    HMACSHA1 mac = new HMACSHA1(secret);\n    byte[] hashBytes = Encoding.UTF8.GetBytes(hashStr);\n    mac.TransformFinalBlock(hashBytes, 0, hashBytes.Length);\n    byte[] hashData = mac.Hash;\n\n    // Encode the hash in Base64.\n    string hashOut = Convert.ToBase64String(hashData);\n\n    return hashOut;\n}	0
11146363	11146335	How to swap 2 Dictionary objects without making copy in C#	d1 = d2;\nd2 = new Dictionary<int, int>();	0
1562070	1561806	Looking for .NET Assembly in a different place	static string lookupPath = @"c:\otherbin";\n\nstatic void Main(string[] args)\n{\n    AppDomain.CurrentDomain.AssemblyResolve += \n        new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n}\n\nstatic Assembly CurrentDomain_AssemblyResolve(object sender, \n                                              ResolveEventArgs args)\n{\n    var assemblyname = new AssemblyName(args.Name).Name;\n    var assemblyFileName = Path.Combine(lookupPath, assemblyname + ".dll");\n    var assembly = Assembly.LoadFrom(assemblyFileName);\n    return assembly;\n}	0
9586687	9586625	How to define Indexer behaviour to an Interface?	interface IIndexable<T>\n{\n     T this[string index] {get; set;}\n}	0
3027645	3027597	How can I get all content within <td> tag using a HTML Agility Pack?	HtmlDocument doc = new HtmlDocument();\ndoc.Load("input.html");\nHtmlNode node = doc.DocumentNode\n                   .SelectNodes("//table[@cellspacing='3']/tr[2]/td")\n                   .Single();\nstring text = node.InnerText;	0
16758676	16757910	Inform OS of installation	import psutil\nfor p in psutil.process_iter():\n    print p.name	0
28628981	28628674	Have to pass a single string to multiple regex patterns and on match I want the matched values	var patterns = new string[] { @"Regex 1 Pattern", @"Regex 2 Pattern", @"Regex 3 Pattern" };\nvar rx = new Regex(string.Join("|", patterns), RegexOptions.IgnoreCase);	0
29774940	29774712	How do you check if a storagefolder is null c#	while (theFolder == null)\n{\n    theFolder = await folder.PickSingleFolderAsync(); \n}	0
24882888	24882747	Sum of numbers and cubing numbers in C#	if (i % 2 == 0)\n {\n     while (j <= i * i * i) \n      {\n        if(j % 2 == 0)\n        {\n            Evennums += j; //or sum = sum + j;\n\n        }\n        //increment j\n        j++;\n\n\n      }\n      Console.WriteLine("Even numbers summed together " + Evennums);\n}	0
7691918	7676989	How to cast a generic type at runtime in c#	public static IEnumerable Cast(this IEnumerable self, Type innerType)\n{\n    var methodInfo = typeof (Enumerable).GetMethod("Cast");\n    var genericMethod = methodInfo.MakeGenericMethod(innerType);\n    return genericMethod.Invoke(null, new [] {self}) as IEnumerable;\n}	0
28527239	28525757	Can WCF services running in WcfSvcClient run under a domain account?	securityMode=None	0
24784899	24784012	POST request in fiddler: sending custom object which has another object as a member	{\n"Name" : "testing//moretest//tiredd",\n"Description": "this is a test.",\n"Metadata" : {"Identifier" : 2, "Path" : "Test"}\n}	0
27680642	27680557	c# how to convert IntPtr to struct?	var ver = Marshal.PtrToStructure(ptr, typeof(MathServLib.sVersionStruct));	0
15661911	15637711	The right way to lookup a value from within a table and fill it with data	class Table\n    {\n        Dictionary<String, double> _regionTimeValues;\n        String _region;\n\n        public Table(String region)\n        {\n            _regionTimeValues = new Dictionary<string, double>();\n            _region = region;\n            suckInValues();\n        }\n\n        private void suckInValues()\n        {\n            //Go find the File, get the appropriate Values\n            //for each value found\n        }\n\n\n        internal double locateRelevantValue(string yearQuarter)\n        {\n            double locatedValue = 0.0;\n            _regionTimeValues.TryGetValue(yearQuarter,out locatedValue);\n            return locatedValue;\n\n        }\n    }	0
33008144	33005768	How to merge two tables with computation MS Access?	INSERT INTO [table1] ([Item], [Quantity], [Unit Net Price], [Total Net Price])\nSELECT \n    [Item], \n    [Quantity],\n    [Unit Gross Price] * 1.10 AS [Unit Net Price],\n    [Quantity] * [Unit Gross Price] * 1.10 AS [Total Net Price]\nFROM [table2]	0
23466434	23466409	Compare two dictionaries and store the result in other	var resultDic = dic1.Except(dic).ToDictionary(x => x.Key, x => x.Value);	0
7875130	7737740	how to disable the image in datalist1 after move to datalist2?	protected void dlstImage_ItemDataBound(object sender, DataListItemEventArgs e)// for disabling the image after moving\n    {\n        ImageButton imgctrl = (e.Item.FindControl("Image") as ImageButton);\n        string[] str = imgctrl.CommandArgument.ToString().Split(';');\n        SelImgId = Convert.ToInt32(str[0]);\n        if (newpath.Exists(delegate(ArrayList imageDetails) { return Convert.ToInt32(imageDetails[0]) == SelImgId; }))\n        {\n            imgctrl.Enabled = false;\n            imgctrl.CssClass = "tdDisable";\n        }\n        else\n        {\n            imgctrl.Enabled = true;\n            imgctrl.CssClass = "";\n        }\n    }	0
26810541	26744725	No overload for method take 0 arguments	string subjName = "Dat";\n            string[] stringArray = new string[]{subjName};\n\nInvited.SubjectViewContent[] nc = proxy.GetSubjectViewContents("54f08a8-dcc6-4f3d-8ba6", stringArray, "", "");	0
10035953	9921121	Unable to access table variable in stored procedure	foreach (SqlParameter parameter in dbCommand.Parameters)\n{\n    if (parameter.SqlDbType != SqlDbType.Structured)\n    {\n        continue;\n    }\n    string name = parameter.TypeName;\n    int index = name.IndexOf(".");\n    if (index == -1)\n    {\n        continue;\n    }\n    name = name.Substring(index + 1);\n    if (name.Contains("."))\n    {\n        parameter.TypeName = name;\n    }\n}	0
28916968	28916605	How to calculate distance between a fixture and a point in Box2D/Farseer?	float getDistance(Vector2 point, Fixture fixture)\n{\n    var proxyA = new DistanceProxy();\n    proxyA.Set(fixture.Shape, 0);\n\n    var proxyB = new DistanceProxy();\n    // prepare point shape\n    var pointShape = new CircleShape(0.0001, 1);\n    proxyB.Set(pointShape, 0);\n\n    Transform transformA;\n    fixture.Body.GetTransform(out transformA);\n\n    Transform transformB = new Transform();\n    transformB.Set(point, 0);\n\n    DistanceOutput distance;\n    SimplexCache cache;\n\n    FarseerPhysics.Collision.Distance.ComputeDistance(out distance, out cache,\n                new FarseerPhysics.Collision.DistanceInput(){\n                    UseRadii=true,\n                    ProxyA=proxyA,\n                    ProxyB=proxyB,\n                    TransformA=transformA,\n                    TransformB=transformB\n                });\n}	0
23230199	23230106	Gather data from user in Enum	Color favorite \nif (Enum.TryParse(Console.ReadLine(), out favorite)) {\n   // You're switch goes where\n}\nelse {\n   Console.WriteLine("That's not a color!");\n}	0
6641980	6592830	C# Optional fields in application settings	[ConfigurationProperty("frontPagePostCount"\n    , DefaultValue = 20\n    , IsRequired = false)]	0
6590165	6590150	C# cast - input string was not in the correct format	double bytesSent = 0.0;\nif(double.TryParse(lblBytesSent.Text, out bytesSent))\n{\n    int bytesSentSpeed = (int)(interfaceStats.BytesSent - bytesSent) / 1024;\n}	0
15012462	15012347	Array of sequence	public static IEnumerable<int> Foo(int count, int start, int max)\n{\n    return Enumerable.Range(0, count)\n        .Select(n => (n + start) % (max + 1));\n}	0
6611487	6611442	C# InputSimulator wrapper - how to use it?	Using WindowsInput;	0
29177385	29176997	Using LINQ to convert array object[,] to array	var vSAPdataTemp = Local_SAPtableData.Data;\n\nstring[][] vLinq = (vSAPdataTemp as Object[,]).Cast<string>()\n                .Select(str => str.Split(stcVariables.strSapRfcDelimiterChar)\n                .Select(stra => stra.Trim()).ToArray()).ToArray();	0
1457208	1456815	Problem sending email with SmtpClient in C#	var plainView = AlternateView.CreateAlternateViewFromString(msgBody, new ContentType("text/plain; charset=UTF-8"));\n\nMyMessage.AlternateViews.Add(plainView);\nMyMessage.BodyEncoding = Encoding.UTF8;\nMyMessage.IsBodyHtml = true;\nMyMessage.Subject = subjectLine;\nMyMessage.Body = msgBody;	0
21470171	21466446	Handling MongoDB's ISODate() when attempting to parse a serialized JSON string	var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };\nConsole.WriteLine(document.ToJson(jsonWriterSettings));	0
10904947	10904889	C# content folder path	Path.GetDirectoryName(Application.ExecutablePath);	0
11955060	11950189	How to handle SelectedIndexChanged event for a ComboBox?	private void dataGridView1_EditingControlShowing(object sender, \n    DataGridViewEditingControlShowingEventArgs e)\n{\n    ComboBox cb = e.Control as ComboBox;\n    if (cb != null)\n    {\n        // first remove event handler to keep from attaching multiple:\n        cb.SelectedIndexChanged -= new\n        EventHandler(cb_SelectedIndexChanged);\n\n        // now attach the event handler\n        cb.SelectedIndexChanged += new \n        EventHandler(cb_SelectedIndexChanged);\n    }\n}\n\nvoid cb_SelectedIndexChanged(object sender, EventArgs e)\n{\n    MessageBox.Show("Selected index changed");\n}	0
4261569	4261283	Producer-Consumer with a variation - How to synchronize with thread signal/wait?	void Run ()    \n    {\n        while (true)\n        {\n            Action doit = null;\n\n            lock(_queueLock)\n            {\n                while (_queue.IsEmpty())\n                    Monitor.Wait(_queueLock);\n\n                TimeSpan timeDiff = _queue.First().Key - DateTime.Now;\n                if (timeDiff < 100ms)\n                    doit = _queue.Dequeue();\n            }\n\n            if (doit != null)\n                ; //execute doit\n            else\n             _sync.WaitOne (timeDiff);  \n        }\n    }\n\n\nvoid ScheduleEvent (Action action, DataTime time)\n{\n    lock (_queueLock)\n    {\n        _queue.Add(time, action);\n        // Signal thread to wake up and check again\n        _sync.Set ();\n        if (_queue.Count == 1)\n             Monitor.Pulse(_queuLock);\n    }\n}	0
11834455	11833774	Filtering a collection based on another collection	bo.Where(o => !stringList.Contains(o.MyProperty));	0
4784177	4783571	Weird character 'q' problem with DataGridView Custom DataGridViewColumn cell	public bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey)\n    {\n      // Let the control handle the keys listed.\n      switch (keyData & Keys.KeyCode)\n      {\n        case Keys.Left:\n        case Keys.Up:\n        case Keys.Down:\n        case Keys.Right:\n        case Keys.Home:\n        case Keys.End:\n        case Keys.PageDown:\n        case Keys.PageUp:\n          return true;\n        default:\n         // return false; <--not this\n         return !dataGridViewWantsInputKey; //try this!\n      }\n    }	0
10104188	10104118	Add button column to datatable	DataTable workTable = new DataTable("Customers"); \nDataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));\nworkCol.AllowDBNull = true;	0
10968440	10968205	How to call an asynchronous method?	protected async override void OnNavigatedTo(NavigationEventArgs e)\n{\n\n   TextBlock txt = new TextBlock();           \n   var location = await InitializeLocationServices();\n   txt.Text = location;\n\n   Grid.SetRow(txt, 0);\n   Grid.SetColumn(txt, 1);\n}	0
6112656	6111033	Extension method restricted to objects containing specific properties	public static bool IsAllThat(this object x)\n{\n    dynamic d = x;\n    return d.IsThis || d.IsThat;\n}	0
7867383	7867366	Fetching Xml Attributes	var allAttributes = XDocument.Parse(xmlInString)\n                             .Descendants()\n                             .Where(e => e.HasAttributes)\n                             .SelectMany(e => e.Attributes())\n                             .ToList();	0
13031795	13031362	Upload to database more quickly	using( SqlConnection dataConnection = new SqlConnection(cs) \n{\n    //Code goes here\n}	0
13209456	13209389	How can I convert UTF-8 characters to a string?	WebClient client = new WebClient();\nclient.Encoding = System.Text.Encoding.UTF8;\nstring html = client.DownloadString(SITE_URL).Replace("\"", string.Empty);	0
7875081	7875006	complex string to double conversion	// Read string (if you do not want to use xml)\nstring test = "<voltage>+100mV</voltage>";\nstring measure = test.Substring(test.IndexOf('>')+1);\nmeasure = measure.Substring(0, measure.IndexOf('<')-1);\n\n// Extract measure unit\nstring um = measure.Substring(measure.Length - 1);\nmeasure = measure.Substring(0, measure.Length - 1);\n// Get value\ndouble val = Double.Parse(measure);\n// Convert value according to measure unit\nswitch (um)\n{\n    case "G": val *= 1E9; break;\n    case "M": val *= 1E6; break;\n    case "k": val *= 1E3; break;\n    case "m": val /= 1E3; break;\n    case "u": val /= 1E6; break;\n    case "n": val /= 1E9; break;\n    case "p": val /= 1E12; break;\n}	0
20483366	20483343	How to determine is a variable has increased or decreased/detecting changes dynamically	class Class1\n{\n    private int _counter;\n    private int _counterDirection;\n\n    public int Counter\n    {\n        get { return _counter; }\n\n        set\n        {\n            if (value > _counter)\n            {\n                _counterDirection = 1;\n            }\n            else if (value > _counter)\n            {\n                _counterDirection = -1;\n            }\n            else\n            {\n                _counterDirection = 0;\n            }\n            _counter = value;\n        }\n    }\n\n    public int CounterDirection()\n    {\n         return _counterDirection;\n    }\n}	0
27323301	27247951	How to access to the DBContext used in an EntityManager?	Configuration.AutoDetectChangesEnabled = false;	0
5323077	5322776	UpperCase all Xml element values with LINQ	foreach (var desc in doc.Descendants()) {\n    var nodes = desc.Nodes().Where(p => p.NodeType == XmlNodeType.Text);\n\n    foreach (XText node in nodes) {\n        node.Value = node.Value.ToUpper();\n    }\n}	0
14218460	14217284	Parameter is not valid on Image read write to XML file	CustomerLogo1 = Convert.FromBase64String(xmlDoc.ChildNodes[1].ChildNodes[8].InnerText);	0
2005662	2005649	Threads inside a foreach loop in c#	new Thread(() => {\n    foreach (DataRow dataRow in dataTable.Rows) \n    {\n        sendMails();\n    }\n}).Start();	0
4027375	4027346	use parameter when populating a struct with dataset c#?	IEnumerable<MyStruct>	0
29456928	29446856	Automapper - Mapping subclasses	private static void DefineMappingDomainEntitiesToDatabase()\n{\n    // SellerListing \n    Mapper.CreateMap<SellerListing, Data.SellerListing>()\n          .ForMember(x => x.ListingShippingCost, cfg => cfg.MapFrom(y => y.ListingShippingCostList));\n\n    // ListingShippingCost\n    Mapper.CreateMap<ListingShippingCost, Data.ListingShippingCost>();\n}	0
13044862	13044618	Set Wpf parent to a MDIform	public static void SetOwner(System.Windows.Forms.Form owner, System.Windows.Window wpfWindow)\n    {\n        WindowInteropHelper helper = new WindowInteropHelper(wpfWindow);\n        helper.Owner = owner.Handle;\n    }	0
9166802	9162873	How to get projected angle from quaternion on a certain axis?	public static float DirectionalAngle(Vector3 from, Vector3 to, Vector3 up)\n{\n    // project the vectors on the plane with up as a normal\n    Vector3 f = Vector3.Exclude(up, from);\n    Vector3 t = Vector3.Exclude(up, to);\n\n    // rotate the vectors into y-up coordinates\n    Quaternion toZ = Quaternion.FromToRotation(up, Vector3.up);\n    f = toZ * f;\n    t = toZ * t;\n\n    // calculate the quaternion in between f and t.\n    Quaternion fromTo = Quaternion.FromToRotation(f,t);\n\n    // return the eulers.\n    return fromTo.eulerAngles.y;\n}	0
19622958	19591369	Breaks encoding in richtextbox	public class RichText50W : RichTextBox\n{\n    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]\n    static extern IntPtr LoadLibrary(string lpFileName);\n    protected override CreateParams CreateParams\n    {\n        get\n        {\n            CreateParams prams = base.CreateParams;\n            if (LoadLibrary("msftedit.dll") != IntPtr.Zero)\n            {\n                prams.ClassName = "RICHEDIT50W";\n            }\n            return prams;\n        }\n    }\n}	0
15310277	15310203	How to track checks in checkedListBox C#?	e.NewValue==CheckState.Checked	0
20144753	20143741	How to create JSON file from DataTable in C#	string json = JsonConvert.SerializeObject(table, new Newtonsoft.Json.Formatting());	0
390342	390205	Convert > to HTML entity equivalent within HTML string	Regex.Replace(str, @"\G((?>[^<>]+|<[^>]*>)*)>", "$1&gt;");	0
17696611	17696530	create 10000 2dim arrays with a for loop with c#	int [][,] data = new int[10000][,];\nfor (int i = 0; i < data.Length; i++)\n   data[i] = new int[2,2];\n\ndata[z][x,y] = 123;	0
15029616	15017646	Cascading drop down list Data source	public IList<Example> GetList(string _state)\n{\n\n    IList<Example> cities = new List<Example>();\n\n    Cache cache = HttpContext.Current.Cache;\n\n    if (cache[_state] != null)\n        cities = (IList<Example>)cache[_state];\n\n    else\n    {\n        //Do your calls\n        cache.Insert(_state, cities);\n    }\n\n    return cities;\n}	0
2402554	2402529	substring with linq?	from w in words\nselect new\n{\n  Word = (w.Length > 5) ? w.Substring(0, 5) : w\n};	0
9741623	9741591	Defaulting a DateTimePicker's date to one in the past	dateTimePickerFrom.Value = dateTimePickerFrom.Value.AddMonths(-15);	0
3297572	3297558	Create a List<string> from HashTable keys?	System.Collections.Hashtable ht = new System.Collections.Hashtable();\nList<string> list = ht.Keys.Cast<string>().ToList();	0
11665761	11664710	Impersonation in Asp.net for Upload a file	System.Security.Principal.WindowsImpersonationContext impersonationContext;\nimpersonationContext = \n    ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();\n\n//Insert your code that runs under the security context of the authenticating user here.\n\nimpersonationContext.Undo();	0
22526069	22525942	How to read JSON array data from URL	var persons = JsonConvert.DeserializeObject<List<Person>>(json);	0
8165587	8155771	How to get the Contact Guids from a PartyList in a Plugin?	EntityCollection Recipients;\nEntity entity = (Entity) context.InputParameters["Target"];\n\nIOrganizationServiceFactory serviceFactory \n  = (IOrganizationServiceFactory)serviceProvider.GetService(\n    typeof(IOrganizationServiceFactory)); \nIOrganizationService service = serviceFactory\n  .CreateOrganizationService(context.UserId); \n\nContent = entity.GetAttributeValue<String>("subject"); \nRecipients = entity.GetAttributeValue<EntityCollection>("to"); \n\nfor (int i = 0; i < Recipients.Entities.Count; i++)\n{\n  ActivityParty ap = Recipients[i].ToEntity<ActivityParty>();\n  String contactid = ap.PartyId.Id.ToString();\n  Contact c = (Contact) service.Retrieve(\n    Contact.EntityLogicalName,\n    ap.PartyId.Id,\n    new ColumnSet(new string[]{ "mobilephone" }));\n  String mobilephone = c.MobilePhone;\n  ...\n}	0
17225831	17225675	add text from textbox to listview column	listView1.View = View.Details;\n\n       ListViewItem lvwItem = listView1.Items.Add("my first text");\n       lvwItem.SubItems.Add("my second text");\n       lvwItem.SubItems.Add("my third text");	0
30790464	30790370	Asp.net EF populate panel from database only x elements	List<JobDescriptions> jobs = (from x in db.JobDescriptions select x)\n     .OrderByDescending(y => y.DataAdaugarii)\n     .Take(10) // this limits the result set\n     .ToList();	0
29372660	29372201	Values in dynamically added controls not retained on postback	pnlControls.Controls.Clear();	0
7377388	7377353	Remove dynamic user control	newlyCreatedControl.Parent.Controls.Remove(newlyCreatedControl)	0
19935298	19928239	Access a cell in Excel worksheet with C#	if (xlWorksheet.Cells[k + 5, 0].Text == Convert.ToString(ent.Cells[i, 3].Value   ))\n   { \n     p = k;\n   }	0
2610736	2610646	How do I pass values from a specific row on a DataGrid as a parameter?	DataGridViewRow dgr = dataGridView.Rows[0];\nMyForm myForm = new MyForm(dgr);  // now the form has the Row of information. But it can also access the entire DataGridView as it is available in the DataGridViewRow.	0
18347594	18347350	Execute Page_Load on MAIN.aspx after/while returning from a CHILD (windowed) aspx page	protected void btnExit_Click(object sender, EventArgs e)\n    {\n        // this line allows the capture of selected values \n        gvSelection_SelectedIndexChanged(sender, e); \n        ClientScript.RegisterStartupScript(typeof(Page), "", "window.close();window.opener.location.reload();", true);\n    }	0
10616087	10615926	How to get the value of the selected Item in a Drop down list?	protected void Page_Load(object sender, EventArgs e)\n{\n\n    if (!Page.IsPostBack)\n    {\n        //Please check if you are binding checkbox controls here. \n        //If not bring them in here\n    }\n}	0
18738683	18738661	Regex:find extra space	string pattern =  @"\s\s\[INF\]\s\s";	0
25063721	25063203	webdriver with c# - How do I iterate around an option drop down menu?	IWebElement parent = ie.FindElement(By.Id("rtList"));\nforeach (IWebElement child in parent.FindElements(By.ClassName("menuitem-content")))\n{\n    child.Click();\n}	0
6529952	6522352	How to get back the focus of already opened window in C# Windows forms	else\n{\n    foreach (Process process in processes)\n    {\n        if (process.Id != p.Id)\n        {\n            SwitchToThisWindow(process.MainWindowHandle, true);\n            return;\n        }\n    }\n\n[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);	0
21674693	21674003	Crystal Reports into HTML and sending in mail as body?	MemoryStream oStream; // using System.IO\noStream = (MemoryStream)\nCrystalReportSource1.ReportDocument.ExportToStream(\nCrystalDecisions.Shared.ExportFormatType.HTML40 );\n\noStream.Position = 0;\nvar sr = new StreamReader(ms);\nvar html= sr.ReadToEnd();\n\nsendmail(html); // Use html as your body	0
19237051	19237033	How to disable a button in c# if a value is false	private void textClipboard_TextChanged(object sender, EventArgs e)\n    {\n        copyButton.Enabled = textClipboard.Text.Length > 0;\n    }	0
9933943	9933888	Linq Order by a specific number first then show all rest in order	list.OrderByDescending(i => i == 3).ThenBy(i => i);	0
23406315	23406245	Reading a double number from the console	if (double.TryParse((X).Replace(",", "."), out tmp))\n{\n\n}	0
11729565	11729400	reading repeat xml using xmlnode	string CategoryName = categoryNode.InnerText;	0
1858900	1858823	Can locking a List fail	private readonly object locker = new object();\n\n    // ...\n    lock(locker)\n    {\n         // ...\n    }	0
6821074	6820889	How to determine when a WPF User Control has completed loading	Dispatcher.BeginInvoke(DispatcherPriority.Input,\n    new Action(delegate() { btnApply.IsEnabled = false; } ));	0
26466713	26466363	Change tables loaded in the grid with dropdownlist	protected void radDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)\n{\n    DataTable dt = new DataTable();\n\n    string query = BuildQuery(radDropDownList.SelectedValue);  //Pass in the table name\n    using (var cn = new SqlConnection(connString))\n    {\n        cn.Open();\n        try\n        {\n            SqlCommand cmd = new SqlCommand(query, cn);\n            using (var da = new SqlDataAdapter(cmd))\n            {\n                ad.Fill(dt);\n            }\n        }\n        catch (SqlException e)\n        {\n           //TODO: Handle this exception.\n        }\n    }\n\n    radGrid.DataSource = dt;\n    radGrid.DataBind();\n}\n\nprivate string BuildQuery(string table)\n{\n    //TODO:  Provide your own implementation for your query.\n    return string.Format(\n        @"SELECT * FROM {0}", table);\n}	0
8244543	8244496	Programmatically disconnect network connectivity	var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +\n                                       "WHERE NetConnectionId != null " +\n                                       "AND Manufacturer != 'Microsoft' ");\n        using (var searcher = new ManagementObjectSearcher(wmiQuery))\n        {\n            foreach (ManagementObject item in searcher.Get())\n            {\n                if (((String)item["NetConnectionId"]) == "Local Area Connection")\n                {\n                    using (item)\n                    {\n                        item.InvokeMethod("Disable", null);\n                    }\n                }\n            }\n        }	0
2850061	2850001	Visual Studio - C# Auto Format - Wrapping to 100 columns	string x = "<over 100 characters here>"	0
495054	495038	Can I use a collection initializer for Dictionary<TKey, TValue> entries?	var names = new Dictionary<int, string> {\n  { 1, "Adam" },\n  { 2, "Bart" },\n  { 3, "Charlie" }\n};	0
549789	549751	How do I find what screen the application is running on in C#	listBox1.Items.Clear();\nforeach (var screen in Screen.AllScreens)\n{\n    listBox1.Items.Add(screen);\n}\nlistBox1.SelectedItem = Screen.FromControl(this);	0
19408760	19408431	Including unrelated data in a view model	public class MyModel {\n   public booking Booking {get;set;}\n   public SomeOtherEntityObject EObject{get;set;}\n   public SomePocoObject {get;set;}\n}	0
24544492	24543043	No Boxing Conversion for two type parameters shared Parent and Child	public interface IParent<T, Id> where T : IParent<T, Id>\n{\n    Child<T, Id> GetChild();\n}\n\npublic class Child<T, Id> where T : IParent<T, Id>\n{\n    public T Parent;\n\n    public Child<T, Id> GetChild()\n    {\n        throw new NotImplementedException();\n    }\n}	0
8631595	8550981	Struggling in updating data in DataGridView	private void buttonUpdate_Click(object sender, EventArgs e)\n        {\n            if ((dataGridViewOrderDetails.Rows.Count - 1 > RowCount) == false)\n            {\n                for (int i = 0; i < dataGridViewOrderDetails.RowCount - 1; i++)\n                {\n                    string SQL = "Update OrderLineItems set Quantity = " + dataGridViewOrderDetails.Rows[i].Cells[1].Value +\n                        ", Particular = '" + dataGridViewOrderDetails.Rows[i].Cells[2].Value + "', Rate = " + dataGridViewOrderDetails.Rows[i].Cells[3].Value + " where OrderLineItems.Id = " + dataGridViewOrderDetails.Rows[i].Cells[0].Value;\n                    result = dm.ExecuteActionQuery(SQL);\n                }\n            }	0
25974371	25972948	How to save a datetime (date) in NSUserDefaults.StandardUserDefaults?	// key\nNSString k = new NSString ("key");\n\n// store a date\nNSDate val = DateTime.SpecifyKind (DateTime.Now, DateTimeKind.Utc);\nNSUserDefaults.StandardUserDefaults.SetValueForKey (val, k);\n\n// retrieve a date\nNSDate nsdate = (NSDate) NSUserDefaults.StandardUserDefaults.ValueForKey (k);\nDateTime date = DateTime.SpecifyKind(nsdate, DateTimeKind.Unspecified);	0
6094542	6068212	finding the namespace from an xml stream in C#	string.contains("xmlns")	0
30231210	30231032	How to pass absolute database name,server name as parameter?	DECLARE @ServerName1 varchar(max) = 'MyServer'\nDECLARE @DB1 varchar(max) = 'MyDB'\n\nEXEC('update   ' + @ServerName1 +  '.' + DB1  + '.dbo.table1\n      set CName= (select  CName from ' + @ServerName1 +  '.' + DB1  +           \n                  '.dbo.table1'   where   CID ='+ @CID)	0
20375302	20370854	Specflow use parameters in a table with a Scenario Context	When I visit the URL <base>/<page>/<questionNumber>/<questionName>\nThen the browser contains test <questionNumber>\n\nExamples: \n | base                         | page      | questionNumber | questionName |\n | http://www.stackoverflow.com | questions | 123            | specflow-q1  |\n | http://www.stackoverflow.com | questions | 456            | specflow-q2  |\n | http://www.stackoverflow.com | questions | 789            | specflow-q3  |	0
6470192	6470127	Binding WPF Combobox within Datagrid in MVVM not saving changes	SelectedValue="{Binding MFGCode,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"	0
20224093	20224042	Accessing a string within a list of classes	private void adviShowInfoButton_Click(object sender, EventArgs e)\n{\n    int index = adviListBox.SelectedIndex;\n\n    advInfoDisplayFirst.Text = AdviserList[index].FirstName;\n    advInfoDisplayLast.Text = AdviserList[index].LastName;\n    advInfoDisplayDep.Text = AdviserList[index].Department;\n\n    //this will traverse your StudentsAdvised list\n    foreach (Advisers a in AdviserList[index].StudentsAdvised)\n    { \n         advInfoStudentBox.Items.AddItem(a.LastName + ", " + a.FirstName);\n    }\n\n}	0
31292217	31268882	How to change ReorderableList's element height in Inspector view	list.elementHeight = EditorGUIUtility.singleLineHeight * 2f;	0
15769963	15769735	Code calls for a file to be Downloaded+Dialog Box but Only Dialog Box Shows	client.DownloadFileAsync(new Uri(url),\n           @"C:\Users\PC\Desktop\Medieval Silver Edition\Alexville.zip");	0
13877607	13877528	how to get 8 digits out of a 16 digit guid No?	static class StringExt {\n\npublic static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {\n\n    for (var i = 0; i < s.Length; i += partLength)\n      yield return s.Substring(i, Math.Min(partLength, s.Length - i));\n  }\n}\n\n\nvar parts = System.Guid.NewGuid().ToString().Replace("-","").SplitInParts(8);	0
11182507	11182399	How do you take two datatables and match values, then add something to a column in the matched row values?	DataTable dtSampleOne = new DataTable();\n            DataTable dtSampleTwo = new DataTable();\n\n            foreach (DataRow rowSampleOne in dtSampleOne.Rows)\n            {\n                string zipCodeSampleOne = rowSampleOne["zipCodeToMatchOne"].ToString();\n\n                foreach (DataRow rowSampleTwo in dtSampleTwo.Rows)\n                {\n                    if (rowSampleTwo["zipCodeToMatchTwo"].ToString().Equals(zipCodeSampleOne))\n                    {\n                        // Do your stuff here\n                    }                            \n                }\n            }	0
19280289	18424074	insert data from repeater to the database	protected void btnSave_Click(object sender, EventArgs e)\n{\n    foreach (RepeaterItem item in questionRepeater.Items)\n    {\n        TextBox Qbox = item.FindControl("txtQ") as TextBox;\n        TextBox Ansbox = item.FindControl("txtAns") as TextBox;\n        string Question = Qbox.Text;\n        string Answer =  Ansbox.Text;\n\n        if (!string.IsNullOrEmpty(Answer))\n        {\n            //Perform your insert operation.\n        }\n    }\n    //Bind Repeater again if required\n}	0
11413482	11412565	How to get date values form grid's cell to date time picker control in new form	DateTime dtBookPublishDate = DateTime.Parse (dgvBooksDetails.CurrentRow.Cells[5].Value.ToStrin());                                                                      \nmyBookInformation.dtpBookPublishDateInfo.Value = DateTime.Parse(dtBookPublishDate.ToShortDateString());	0
24090022	24089331	Alternative to using HttpGetAttribute	[HttpGet]	0
9218084	9218071	How can I set a DatePicker's date to yesterday?	dtpFrom.DisplayDate = DateTime.Today.AddDays(-1);	0
2470033	2469597	How can I replace an already declared stub call with a different stub call?	public static class RhinoExtensions\n{\n    /// <summary>\n    /// Clears the behavior already recorded in a Rhino Mocks stub.\n    /// </summary>\n    public static void ClearBehavior<T>(this T stub)\n    {\n        stub.BackToRecord(BackToRecordOptions.All);\n        stub.Replay();\n    }\n}	0
793701	793657	How to find path of active app.config file?	AppDomain.CurrentDomain.SetupInformation.ConfigurationFile	0
21353674	21353555	Best practice for dealing with duplicate classes in separate namespaces	using kb = Microsoft.Xna.Framework.Input;\n\nvar test = kb.Keyboard.GetState(...);	0
33145966	33145696	How could I show a row from the database to a textbox in Visual Studio 2015	private void button1_Click(object sender, EventArgs e)\n   {\n       sc.Open();\n       cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);\n       using (var reader = cmd.ExecuteReader()){\n           if ( reader.Read() )\n           {\n              textBox1.Text = reader.GetString(0);\n           }\n       };\n\n       sc.Close();\n   }	0
11500356	11499893	How to properly read columns from text file	string[] records = File.ReadAllLines(path);\nforeach(string record in records)\n{\n  DataRow r = myDataTable.NewRow();\n  string[] fields = record.Split('\t');\n  /* Parse each field into the corresponding r column\n   * ....\n   */\n  myDataTable.rows.Add(r);\n}	0
19966893	19966305	How do you create an action in MVC with oData	[HttpPost]\npublic ICollection<AppAccount> Service(ODataQueryOptions opts)\n{\n    var results = opts.ApplyTo(db.AppAccounts.Where(aa => aa.AppAccountClass.Name == "Service")) as IQueryable<AppAccount>;\n    if (results != null) return results.ToList();\n    throw new HttpResponseException(HttpStatusCode.BadRequest);\n}	0
20558886	20547402	How to get source HTML from gecko web browser? InnerHtml does not exist any more	GeckoHtmlElement element = null;\nvar geckoDomElement = WebBrowser1.Document.DocumentElement;\nif(geckoDomElement is GeckoHtmlElement)\n{\n  element = (GeckoHtmlElement)geckoDomElement;    \n  var innerHtml = element.InnerHtml;\n}	0
26069945	26069918	How to format decimal with leading zeros and without a separator?	(value * 100).ToString("00000000");\n\nstring.Format("{0:00000000}", value * 100);	0
2667892	2667815	Reading a text file	string data;\nusing(System.IO.StreamReader reader = new System.IO.StreamReader("filepath"))\n{\n    data = reader.ReadToEnd();\n}\n\nstring[] lines = data.Split(Environment.NewLine);\n\nfor(int index = 0; index < lines.Length; index += 7)\n{\n    ListViewItem item = new ListViewItem();\n    for(int innerIndex = 0; innerIndex < 7; innerIndex++)\n    {\n        item.SubItems.Add(lines[index + innerIndex]);\n    }\n\n    listView1.Items.Add(item);\n}	0
31233391	31233130	How to shrink image to disappear gradually in WPF DoubleAnimation	DoubleAnimation anim = new DoubleAnimation(1, 0,(Duration)TimeSpan.FromSeconds(1));\n\nScaleTransform st = new ScaleTransform();\nControl.RenderTransform = st;\nst.BeginAnimation(ScaleTransform.ScaleXProperty, anim);\nst.BeginAnimation(ScaleTransform.ScaleYProperty, anim);	0
4613389	4486221	ScrollBar value set incorrectly	int difference = e.NewValue - e.OldValue;\n        if (e.Type == ScrollEventType.SmallIncrement)\n        {\n            if (difference != scrollBar.SmallChange)\n            {\n                int increase = (scrollBar.SmallChange - difference);\n                scrollBar.Maximum += increase;\n                e.NewValue = scrollBar.Value + increase;\n            }\n        }	0
17554562	17434672	Selecting Particular Node List in XML	XmlDocument log = new XmlDocument();\n        log.Load(@"C:\Users\barranca\Desktop\test.xml");\n       // XmlNodeList xml = log.SelectNodes("//ns1:Alerts");\n\n        var name = new XmlNamespaceManager(log.NameTable);\n        name.AddNamespace("ns1", "Microsoft.SystemCenter.DataWarehouse.Report.Alert");\n        XmlNodeList xml = log.SelectNodes("//ns1:Alert", name);\n\n\n\n        foreach (XmlNode alert in xml)\n        {\n            Console.Write("HERE");\n            XmlNode test = alert.SelectSingleNode("//ns1:AlertName",name);\n            string testing = test.InnerText;\n            Console.Write(testing);\n        }	0
31113342	31110969	How can I use these statement properly?	if((alKeys.Contains(Convert.ToInt32(Keys.F9))==true))	0
5333319	5333018	Can a class library read the app.config file of a Coded UI Test that is being executed?	ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);	0
1859726	1859716	PDF returning a corrupt file	protected void btnGetFile_Click(object sender, EventArgs e)\n        {\n            string title = "DischargeSummary.pdf";\n            string contentType = "application/pdf";\n            byte[] documentBytes = GetDoc(DocID);\n\n            Response.Clear();\n            Response.ContentType = contentType;\n            Response.AddHeader("content-disposition", "attachment;filename=" + title);\n            Response.BinaryWrite(documentBytes);\n            Response.End();\n        }	0
9758229	9744237	How would I do the following NInject registration with Unity IoC?	LogManager.GetLogger()	0
12705762	12705698	Event in Global.asax file that fires only for once	protected void Session_Start(object sender, EventArgs e)\n{\n    // Will fire once when a new user session is created.\n\n    // Contrary to Application_Start this event could run multiple\n    // times during the AppDomain lifetime but that will ensure you \n    // that all users have the required data stored into the session.\n}	0
2384459	2384381	Control that allows dragging of form	Point dragOffset;\n\nprotected override void OnMouseDown(MouseEventArgs e) {\n    base.OnMouseDown(e);\n    if (e.Button == MouseButtons.Left) {\n        dragOffset = this.PointToScreen(e.Location);\n        var formLocation = FindForm().Location;\n        dragOffset.X -= formLocation.X;\n        dragOffset.Y -= formLocation.Y;\n    }\n}\n\nprotected override void OnMouseMove(MouseEventArgs e) {\n    base.OnMouseMove(e);\n\n    if (e.Button == MouseButtons.Left) {\n        Point newLocation = this.PointToScreen(e.Location);\n\n        newLocation.X -= dragOffset.X;\n        newLocation.Y -= dragOffset.Y;\n\n        FindForm().Location = newLocation;\n    }\n}	0
9142496	9141838	Html page to string	"Hello {FirstName},\nPlease visit our site:\n{SiteLink}"	0
31507187	31507167	Convert string into timespan using c#?	DateTime time = DateTime.ParseExact("00:00", "hh:mm", CultureInfo.InvariantCulture);	0
20676912	20676759	How can I run a second application from another one (C#)	static void Main()\n{\n    Application.EnableVisualStyles();\n    Application.SetCompatibleTextRenderingDefault(false);\n\n    bool validated = false;\n    using(frmLogin fLogin = new frmLogin())\n    {\n         if(fLogin.ShowDialog() == DialogResult.OK)\n             validated = true;\n    }\n    if(validated)\n        Application.Run(new Main());\n    else\n        MessageBox.Show("Bye");\n}	0
7640346	7640297	How to boil a list down to least common strings?	string[] strings = { "a", "aa", "aaa", "b", "bb", "bbb", "c", "cc", "ccc" };\nList<string> results = new List<string>(strings);\n\nforeach (string str1 in strings) {\n  foreach (string str2 in strings) {\n    if (str1 != str2) {\n      if (str2.Contains(str1)) {\n        results.Remove(str2);\n      }\n    }\n  }\n}\n\nreturn results;	0
6577951	6577846	Uploading picture to picasa web	using (Stream fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read))\n{\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n    request.Method = "POST";\n    request.ContentType = "image/png";\n    request.ContentLength = fileStream.Length;\n    request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + auth);\n    request.Headers.Add("Slug", "test");\n\n    using (Stream requestStream = request.GetRequestStream())\n    {\n        byte[] buffer = new byte[4096];\n        int bytesRead = 0;\n        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)\n        {\n            requestStream.Write(buffer, 0, bytesRead);\n        }\n\n        fileStream.Close();\n        requestStream.Close();\n    }\n\n    HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n    StreamReader responseReader = new StreamReader(response.GetResponseStream());\n\n    string responseStr = responseReader.ReadToEnd();\n\n}	0
7764662	7764612	Jquery collapse and expand server side control	animatedcollapse.addDiv('<%= jason.ClientID %>', 'fade=1,height=80px')	0
5112032	5111967	Regex to remove a specific repeated character	var reducedString = Regex.Replace(inputString, "-+", "-");\n\nvar finalString = reducedString.Trim('-');	0
16400199	16394051	Best approach to switch PartialView result that is displayed based on configuration	public ActionResult ProductFeature()\n{\n    var prefix = ConfigurationManager.AppSettings["InstanceOwner"];\n    return PartialView(prefix+"ProductFeature");\n}	0
23183184	23183160	how to Convert Lambda expression to Func<> variable	Func<string,bool> lambda = f => formatFile.Contains(f.Split('.').Last().ToLower());	0
28526936	28526288	Read a byte array from a redirected process	var process = new Process();\nprocess.StartInfo.FileName = @"C:\bin\ffmpeg.exe";\n// take frame at 17 seconds\nprocess.StartInfo.Arguments = @" -i c:\temp\input.mp4 -an -f image2 -vframes 1 -ss 00:00:17 pipe:1";\nprocess.StartInfo.CreateNoWindow = true;\nprocess.StartInfo.RedirectStandardError = true;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.StartInfo.UseShellExecute = false;\nprocess.Start();\n\nFileStream baseStream = process.StandardOutput.BaseStream as FileStream;\nbyte[] imageBytes = null;\nint lastRead = 0;\n\nusing (MemoryStream ms = new MemoryStream())\n{            \n    byte[] buffer = new byte[4096];\n    do\n    {\n        lastRead = baseStream.Read(buffer, 0, buffer.Length);\n        ms.Write(buffer, 0, lastRead);\n    } while (lastRead > 0);\n\n    imageBytes = ms.ToArray();\n}\n\nusing (FileStream s = new FileStream(@"c:\temp\singleFrame.jpeg", FileMode.Create))\n{\n    s.Write(imageBytes, 0, imageBytes.Length);\n}\n\nConsole.ReadKey();	0
34226945	34226779	How to await Func<Task<string>>?	Func<Task<string>> id = null;\nid = async () => \n    {\n       ...	0
25814800	25809638	Replacing text in Visio but keep formatting	Dim Chars as Visio.Characters\nSet Chars = o.Characters\nChars.Begin = instr( 1 , o.Text , "123" )\nChars.End = Chars.Begin + Len( "123" )\nChars.Text = "234"	0
20884979	20884669	Reverse the order of space separated words in a string	var line = "5 Damaged batten type fluorescent Luminaire sited adjacent to the Cooler in the Beer Celler C2 No";\nstring[] lineTexts = line.Split(' ').Reverse().ToArray();\nConsole.Write(string.Join(" ",lineTexts));	0
16251774	16251690	Dynamically call variables from a loop?	Dictionary<String, String> dogs = new Dictionary<String, String>();\n\n  dogs.Add("dog1Legs", null);\n  dogs.Add("dog2Legs", null);\n  dogs.Add("dog3Legs", null);\n\n  for(int i = 1; i < 4; i++) {\n    dogs["dogs" + i.ToString() + "Legs"] = "test";\n  }	0
10716774	10716726	C#, lambda, linq	dc.tb_References.Where(item => ids.Contains(item.ID)).ToList();	0
25148843	25142294	Loading a pdf from folder in win8 metro apps	public async Task<StorageFile> GetFileAsync(string directory, string fileName)\n{\n    string filePath = BuildPath(directory, fileName);\n    string directoryName = Path.GetDirectoryName(filePath);\n\n    StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(directoryName);\n    StorageFile storageFile = await storageFolder.GetFileAsync(fileName);\n    return storageFile;\n}\n\npublic string BuildPath(string directoryPath, string fileName)\n{\n    string directory = Path.Combine(Package.Current.InstalledLocation.Path, directoryPath);\n    return Path.Combine(directory, fileName);\n}	0
24339021	24338874	how to add data in a database to variable in C# for Login	cm = new OleDbCommand("select usnam,paswd from signin where usnam = @usnam and paswd = @paswd", cn);\n\n    cm.Parameters.AddWithValue("@usnam", textBox1.Text.ToString());\n    cm.Parameters.AddWithValue("@paswd", textBox2.Text.ToString());\n\n    string un;\n    string pw;\n\n    cn.Open();\n    OleDbDataReader dr = cm.ExecuteReader();\n\n\n\n    if (dr.Read())\n    {\n\n        new Form1().Show();\n    }\n    else\n    {\n        MessageBox.Show("Invalied Username or Password");\n    }	0
7524288	7483645	How to extract the strings between two special characters using Regular Expressions in C#	string str = "My Name is #P_NAME# and \r\n I am #P_AGE# years old";\n\nMatchCollection allMatchResults = null;\nvar regexObj = new Regex(@"#\w*#");\nallMatchResults = regexObj.Matches(str);	0
3356931	3356265	Programmatically Lookup a User in SharePoint	SPUser webUser = web.EnsureUser("SecondaryProvider:" + userName);	0
10101417	10101162	Get the Application Pool Identity programmatically	System.Security.Principal.WindowsIdentity.GetCurrent().Name	0
18701635	18700182	Display tool tip in disabled control	Control control = tableLayoutPanel1.GetChildAtPoint(e.Location);	0
11987777	11987695	Need to convert this code to VB	Public ReadOnly Property AudioCodecs As IEnumerable(Of CodecInfo)\n    Get\n        Return From c In softPhone.Codecs\n               Where c.CodecType = CodecMediaType.Audio\n    End Get\nEnd Property	0
3191352	3191326	remove dot at end of text	string a = "abc.";\nstring b = a.TrimEnd('.');	0
7643842	7643785	LINQ: Group by aggregate but still get information from the most recent row?	var query = from shipment in context.ShippingHistory\n            group shipment by shipment.MemberID into g\n            select new { Count = g.Count(),\n                     MemberID = g.Key,\n                     MostRecentName = g.OrderByDescending(x => x.ShipmentDate)\n                                       .First()\n                                       .ShipmentName };	0
6635036	6408168	Sendkeys from WPF application	Private Declare Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, _\nByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)\n\nPrivate Const kbdDown = 0\nPrivate Const kbdUp = 2\n\n\n\nPrivate Sub SendKey(ByVal Key As Byte)\n    Call keybd_event(Key, 0, kbdDown, 0)\n    Call keybd_event(Key, 0, kbdUp, 0)\n\nEnd Sub	0
29844664	29844575	How to Find Distinct records in LINQ?	var distinctYear = _objCalRepos\n    .GetDetails()\n    .Select(o => o.Mdate.Year.ToString())\n    .Distinct()\n    .AsEnumerable()\n    .Select(o => new CalendarList { Mdate = o }))\n    .ToList();	0
19693281	19692940	How to move a C# project with database to the user computer?	In Back Up Database Window \n\n Check BackUp Component as "Database" RadioButton\n\n If you want to change the name , you can \n\n Check Backup set will expire : as "After" RadioButton and select the value as 0\n\n Set Back Up To location as :\n\n     C:\Program Files\Microsoft Sql Server\MSSQL10.MSSQLSERVER\MSSQL\Backup\YourDatabaeName.bak\n Click OK	0
1468081	1466866	C#: How do I prepend text to each line in a string?	public static string MagicFunctionIO(this string self, string prefix)\n{\n  string terminator = self.GetLineTerminator();\n  using (StringWriter writer = new StringWriter())\n  {\n    using (StringReader reader = new StringReader(self))\n    {\n      bool first = true;\n      string line;\n      while ((line = reader.ReadLine()) != null)\n      {\n        if (!first)\n          writer.Write(terminator);\n        writer.Write(prefix + line);\n        first = false;\n      }\n      return writer.ToString();\n    }\n  }\n}\n\npublic static string GetLineTerminator(this string self)\n{\n  if (self.Contains("\r\n")) // windows\n    return "\r\n";\n  else if (self.Contains("\n")) // unix\n    return "\n";\n  else if (self.Contains("\r")) // mac\n    return "\r";\n  else // default, unknown env or no line terminators\n    return Environment.NewLine;\n}	0
1440132	1439665	How to differentiate "documents" of Folders created by user in Lotus Notes?	...\nNotesDocument folderDoc = folder.getFirstDocument();\nString sForm = folderDoc.getItemValue("form");\nif (sForm == "Memo") {\n // Mail\n}\nif (sForm == "Appointment") {\n // Calendar entry\n}\nif (sForm == "Task") {\n // To Do\n}\n...	0
27542807	27542644	How to run code from UI thread in C#	public void DoSomething(string s)\n    {\n        var form = System.Windows.Forms.Application.OpenForms[0];\n        if (form.InvokeRequired)\n        {\n            Action<string> m = DoSomething;\n            form.Invoke(m, s);\n            return;\n        }\n\n        //do something\n    }	0
3717387	3717167	Image within Silverlight 4 user control is not being set	public static DependencyProperty ImageSourceProperty = \nDependencyProperty.Register("ImageSource", typeof(String), typeof(MediaItemControl), \n    new PropertyMetadata(delegate(DependencyObject sender, DependencyPropertyChangedEventArgs args)\n            {\n                (sender as MediaItemControl).ContentImage.Source = new BitmapImage(new Uri((string)args.NewValue, UriKind.RelativeOrAbsolute));\n            }));	0
1738243	1738211	Get All current file names in directory and write it out in console C#	Path.Combine(Directory.GetCurrentDirectory(), "Uninstallers");	0
455892	455880	How to determine using reflection the generic parameter of the base class	public static Type GetBaseTypeGenericArgument(Type type) {\n  return type.BaseType.GetGenericArguments()[0];\n}\n\n...\nGetBaseTypeGenericArgument(typeof(MyClass));	0
8756682	8715514	FileNotFoundException - Dynamic Discovery	[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetDllDirectory(string lpPathName);\n\nSetDllDirectory(@"C:\SomeDir");	0
25265450	25263174	Get value and name of property of an object	public static Data BuildData<T>(Expression<Func<T>> e, appDetailCategory category)\n    {\n        var member = (MemberExpression)e.Body;\n\n        var name = member.Member.Name;\n        var value = Expression.Lambda<Func<string>>(member).Compile()();\n\n        return new Data\n        {\n            Attribute = name,\n            Value = value\n        };\n    }	0
19557305	19554818	How to figure out what place my item is in, in Sitecore	int position = item.Parent.GetChildren().IndexOf(item.ID);	0
6581203	6539741	A point in 3D space from an angle	transform.RotateAround(Vector3 axis, float degree)	0
18014102	18013949	Splitting up a string based on csv	string[] records = File.ReadAllLines(fileName); // read the file completely line by line\n\n// loop through all lines\nforeach (string record in records)\n{\n    string[] fields = record.Split(splitChar);  // reads all the single values per line. 'splitChar' should be the delimiter.\n}	0
26441480	26441440	How can i compare a string with 3 other strings?	if (!difficulty.Equals("Beginner") && !difficulty.Equals("Amateur") && !difficulty.Equals("Expert"))\n{\n    // do something\n}	0
4828122	4828075	using see cref with < > characters in XML Documentation?	/// <returns>A <see cref="List{T}" /> that</returns>	0
34286709	34286527	How to set an URI from code-behind	Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Resources/Images/ITA.png")).Stream;\n  notifyIcon.Icon = new System.Drawing.Icon(iconStream);	0
23887730	23887403	Selenium: Finding page element in WordPress	Driver.FindElement(By.XPath(""));	0
21981302	21901343	how to handle new files in wpf application?	class BinaryImageConverter : IValueConverter\n{\n    object IValueConverter.Convert( object value, \n        Type targetType, \n        object parameter, \n        System.Globalization.CultureInfo culture )\n    {\n        if(value != null && value is byte[])\n        {\n            byte[] bytes = value as byte[];\n\n            MemoryStream stream = new MemoryStream( bytes );\n\n            BitmapImage image = new BitmapImage();\n            image.BeginInit();\n            image.StreamSource = stream;\n            image.EndInit();\n\n            return image;\n        }\n\n        return null;\n    }\n\n    object IValueConverter.ConvertBack( object value, \n        Type targetType, \n        object parameter, \n        System.Globalization.CultureInfo culture )\n    {\n        throw new Exception( "The method or operation is not implemented." );\n    }\n}\n\n<Image Source="{Binding Path=Image, Converter={StaticResource imgConverter}}" />	0
562110	561998	C# How to print multiple pictureboxes	Pb1.DrawToBitmap	0
31694789	31694520	How to call a Ressource by dynamic String?	var assembly = System.Reflection.Assembly.Load("AssemblyName");\n  var resourceManager = new System.Resources.ResourceManager("Fully.Quallified.Namespace.Name.Resources", assembly);\n  var wantedString = resourceManager.GetString("theStringYouWant");	0
26315516	26314938	Limiting number of checkboxes selected in gridview in c#	function CheckCheck()\n{\n    var chkBoxList = document.getElementById('<%=GridView1.ClientID %>');\n    var chkBoxCount = chkBoxList.getElementsByTagName("input");\n\n    var btn = document.getElementById('<%=btn.ClientID %>');\n    var i = 0;\n    var tot = 0;\n    for (i = 0; i < chkBoxCount.length; i++)\n    {\n        if (chkBoxCount[i].checked)\n        {\n            tot = tot + 1;\n\n            if (tot > 3)\n            {\n                alert('Cannot check more than 3 check boxes');\n                chkBoxCount[i].checked = false;\n                return;\n            }\n        }\n    }\n}	0
26541600	26539961	C# File Upload via POST REST API in a Self-Hosted Web Server Environment	public HttpResponseMessage Post(HttpRequestMessage request) {...}	0
17676527	17670253	How to overcome this situation Windows Services App	protected override void OnStart(string[] args)\n  {\n      CreatFolder();\n  }\n\n  public static void CreatFolder()\n  {\n      //this.myTimer.Enabled = true;\n      string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\n      Directory.CreateDirectory(@"c:\ST\" + userName);\n  }	0
18120770	18118630	Looking for a way to dynamically change field names in PropertyGrid	DynamicTypeDescriptor dtp = new DynamicTypeDescriptor(typeObj);\n\n// get current property definition and remove it\nvar current = dtp.Properties["ThePropertyToChange"];\ndtp.RemoveProperty("ThePropertyToChange");\n\n// add a new one, but change its display name\nDynamicTypeDescriptor.DynamicProperty prop = new DynamicTypeDescriptor.DynamicProperty(dtp, current, obj);\nprop.SetDisplayName("MyNewPropertyName");\ndtp.AddProperty(prop);\n\npropertyGrid1.SelectedObject = dtp.FromComponent(obj);	0
828712	828624	How to refactor these 2 similar methods into one?	public List<SelectListItem> ToSelectList<T>(IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)\n    {\n        var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();\n        items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });\n        return items;\n    }\n\n    // use like\n\n    t.ToSelectList(departments, d => d.Code + " - " + d.Description, d => d.Id.ToString(), "default");\n    t.ToSelectList(functions, f => f.Description, f => f.Id.ToString(), "default");	0
11235334	11234661	How Access FooterText (Telerik-RadGrid) In A DetailTable In CodeBehind?	protected void MasterTableView_DataBinding(object sender, EventArgs e)  <- Pay Attention Here\n{\n    GridBoundColumn TotalPrice = grdCustomers.MasterTableView.DetailTables[0].GetColumnSafe("TotalPrice") as GridBoundColumn;\n    TotalPrice.FooterAggregateFormatString = "<span class=\"AggregateTitleColor\">Sum : </span>" + "{0:#,0 ;#,0- }";\n    TotalPrice.FooterStyle.ForeColor = ColorTranslator.FromHtml("blue");\n}	0
8066065	8059299	Import data from CSV file with comma in string cells	using Microsoft.VisualBasic.FileIO; //Microsoft.VisualBasic.dll\n...\nusing(var csvReader = new TextFieldParser(reader)){\n    csvReader.SetDelimiters(new string[] {","});\n    csvReader.HasFieldsEnclosedInQuotes = true;\n    fields = csvReader.ReadFields();\n}	0
13743092	13740420	FluentNhibernate Mapping Dictionaries Foreign Key Remains Null	using (var session = _sessionFactory.OpenSession())\n{\n    var transaction = session.BeginTransaction();\n    john.Name = "John";\n\n    Phone home = new Phone\n                     {\n                         Type = "Home",\n                         Number = "12345"\n                     };\n     john.PhoneNumbers.Add(home.Type, home);\n     session.Save(john);\n     transaction.Commit();\n}	0
9025584	9025325	XML and IDictionary in C#	dictionary = doc.Root.Elements("state").ToDictionary(\n                s => s.Attribute("name").Value,\n                s => s.Elements("Location").ToDictionary(\n                    loc => loc.Attribute("Name").Value,\n                    loc => new Property\n                    {\n                        address = loc.Element("Address").Value,\n                        datetime = loc.Element("DateNTime").Value\n                    }));	0
13988062	13988004	Using lambda expression in List of Projects [ENVDTE]	Project p  = prjs.LastOrDefault(r=> r.Name == "prj5");	0
21440155	21439741	c#: Add element to second nesting in xml	XmlDocument myDocument = new XmlDocument();\n            myDocument.Load(XMLFile);\n            XmlNode newNode = myDocument.CreateElement("bill");\n            //add values;\n            var requiredNode = myDocument.ChildNodes.OfType<XmlElement>().Where(o => o.Name == "bills").First();\n            requiredNode.AppendChild(newNode);\n            myDocument.Save(XMLFile);	0
23395057	23394441	Rx observable which publishes a value if certain timeout expires	var statusSignal = statusProvider\n            .Subscribe(statusKey)  //returns an IObservable<string>\n            .Select(st => st.ToUpper())\n            .Publish()\n            .RefCount();\n\n// An observable that produces "bad" after a delay and then "hangs indefinately" after that\nvar badTimer = Observable\n    .Return("bad")\n    .Delay(TimeSpan.FromSeconds(30))\n    .Concat(Observable.Never<string>());\n\n// A repeating badTimer that resets the timer whenever a good signal arrives.\n// The "indefinite hang" in badTimer prevents this from restarting the timer as soon\n// as it produces a "bad".  Which prevents you from getting a string of "bad" messages\n// if the statusProvider is silent for many minutes.\nvar badSignal = badTimer.TakeUntil(statusSignal).Repeat();\n\n// listen to both good and bad signals.\nreturn Observable\n    .Merge(statusSignal, badSignal)\n    .DistinctUntilChanged()\n    .Replay(1)\n    .RefCount();	0
21288427	21271118	Detect what has been selected on a Listbox DataTemplate	var myTappedobject = (Sender as FrameworkElement).DataContext as MyObject	0
34306095	34306033	Handle null with C# string Contains in a loop	if( y != null && y.Contains(x) )  {\n  // ...\n}	0
13881992	13867476	FileHelpers -- Only read Nth Columns	private string[] mDummyField;	0
10136439	10136398	Can't read value from textbox into javascript variable	var txtToIncr = document.getElementById('<%=ServerSideTextBox.ClientID%>')	0
27994311	27994085	How do I bind a button and a label	class Button2 : Button\n{\n    public string LabelName = "";\n    public Button2()\n    {\n        this.Click += this.SetLabelName;\n    }\n    private void SetLabelName(object sender, EventArgs e)\n    {\n        this.LabelName = "Something?";\n    }\n//You could also do this instead.\n    protected override void OnClick(EventArgs e)\n        {\n            base.OnClick(e);\n        }\n    }	0
11263512	11263297	Remove trailing zeros from byte[]?	public byte[] Decode(byte[] packet)\n{\n    var i = packet.Length - 1;\n    while(packet[i] == 0)\n    {\n        --i;\n    }\n    var temp = new byte[i + 1];\n    Array.Copy(packet, temp, i + 1);\n    MessageBox.Show(temp.Length.ToString());\n    return temp;\n}	0
8713379	8669612	Monotouch: Create UITabbar with dynamic ViewControllers programmatically	public class test\n    {\n        UITabBarController tabbarController; \n\n        privat void RenderScreen()\n        {\n         ...\n        }\n    }	0
8448952	8448635	Flatten a volume of a 3D array into a 1D array of objects	public IEnumerable<T> this[int x, int y, int width, int length]\n    {\n        get\n        {\n            for (int i = 0; i < length; i++)\n            {\n                for (int j = 0; j < width; j++)\n                {\n                    for (int k = 0; k < map[x + i, y + j].Length; k++)\n                    {\n                        yield return map[x + i, y + j][k];\n                    }\n                }\n            }\n        }\n    }	0
17684579	17684477	Regex to C# regex	var resultString = System.Text.RegularExpressions.Regex.Match(subjectString, "bb:hhhh=\"[^\"]*\"").Value;	0
27790599	22610217	Start WebClient Windows Service from Manual state in code	static void Main(string[] args)\n{\n    string serviceToRun = "WebClient";\n\n    using (ServiceController serviceController = new ServiceController(serviceToRun))\n    {\n        Console.WriteLine(string.Format("Current Status of {0}: {1}", serviceToRun, serviceController.Status));\n        if (serviceController.Status == ServiceControllerStatus.Stopped)\n        {\n            Console.WriteLine(string.Format("Starting {0}", serviceToRun));\n            serviceController.Start();\n            serviceController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 20));\n            Console.WriteLine(string.Format("{0} {1}", serviceToRun, serviceController.Status));\n        }\n    }\n\n    Console.ReadLine();\n}	0
10389515	10389281	Order by clauses coming from two other tables	var query = (from c in Entity.RecentChanges\n        from l in Entity.Logs\n            .FirstOrDefault(log => log.ID == c.LogID).DefaultIfEmpty()\n        from r in Entity.Revisions\n            .FirstOrDefault(rev => rev.ID == c.RevisionID).DefaultIfEmpty()\n        select new\n               {\n                   ActivityDate = l != null \n                       ? l.Timestamp \n                       : r != null\n                           ? r.Timestamp\n                           : DateTime.Now. //what if both are null? catching all eventualities here\n                   //select your other fields here\n\n               })\n        .OrderByDescending(c => c.ActivityDate)\n        .ToList();	0
6866369	6864068	Is it possible to put all the xml-comments of a solution into one xml-file?	copy file1.xml + file2.xml + fileN.xml destinationFile.xml	0
5917016	5916931	Need help with regex to parse expression	output = Regex.Replace(input, @"([^\w\s]|\w(?!\w))(?!$)", "$1 ");	0
9987389	9987344	Get xml node using c#	//Create the XmlDocument.\nXmlDocument doc = new XmlDocument();\ndoc.Load("books.xml");\n\n//Display all the book titles.\nXmlNodeList elemList = doc.GetElementsByTagName("title");\nfor (int i=0; i < elemList.Count; i++)\n{   \n  Console.WriteLine(elemList[i].InnerXml);\n}	0
15202704	15202240	Delete Id that has many values in link table	foreach (var dr in db.tbl_UserServiceAreaDetails.Where(t => (t.tbl_User.UserId == id) && (t.serviceAreaID == id)))\n{\n    dr.tbl_User.Deleted = true;\n}	0
11982074	11981936	Convert List<string> to List<KeyValuePair<string, string>> using Linq	var output = Enumerable.Range(0, input.Count / 2)\n                       .Select(i => Tuple.Create(input[i * 2], input[i * 2 + 1]))\n                       .ToList();	0
23894540	23894460	insert into database other controller	db.Events.Add(reports);\ndb.SaveChanges();\n\nldb.Events.Add(new WhateverTypeYouNeed() {\n    Title = reports.Title,\n    Description = reports.Description,\n    //Anything else you need\n});	0
5995324	5995074	Return List<T> as XML Response from WCF Service?	public string GetColorsXmlRepresentation()\n{\n    var colors = new List<Color>();\n\n    colors.Add(new Color {Name = "Red", Code = 1});\n    colors.Add(new Color {Name = "Blue", Code = 2});\n\n    return Serialize<List<Color>>(colors);\n}\n\n\npublic string Serialize<T>(T instance)\n{\n    var data = new StringBuilder();\n    var serializer = new DataContractSerializer(instance.GetType());\n\n    using (var writer = XmlWriter.Create(data))\n    {\n       serializer.WriteObject(writer, instance);\n       writer.Flush();\n\n      return data.ToString();\n    }\n}	0
5268725	5268601	Combine text file lines c#	var output = File.ReadAllLines(@"D:\\manager.txt")\n    .Select(line => line.Split(','))\n    .GroupBy(line => line[0] + "," + line[1])\n    .Select(group =>\n         group.Key + "," + \n         String.Join("-", group.Select(line => line[2]).ToArray()) + "," +\n         String.Join("-", group.Select(line => line[3]).ToArray())\n    );	0
31625032	31624970	How to select only those records from collection which have relation with another table using Linq	var query=Ryzyko.getListRyzyko().\n          Join(SlownikRyzyk.getListSlownikRyzyk(),\n               r=>r.SlownikRyzykId,\n               s=>s.Id,\n               (r,s)=> new {R=r,S=s} )	0
22405510	21834217	how to get user's event list from Adobe Connect API?	public List<String> getUserAtendedEvents(String userEmail)\n    {\n        // get all upcoming Events Sco ID's\n        var scoIds = getAllEventsDataToClass().ScoIds;\n\n        List<String> userEvents = new List<string>();\n\n        // request Connect for Event info\n        // action=report-event-participants-complete-information&sco-id=1418245799\n        for (int i = 0; i < scoIds.Count; i++)\n        {\n            XDocument req = RequestXDoc("report-event-participants-complete-information", "sco-id=" + scoIds[i]);\n            var emails = req.Descendants().Attributes("login"); // ---- login emails\n\n            foreach (var email in emails)\n            {\n                if (email.Value.Equals(userEmail))\n                {\n                    userEvents.Add(scoIds[i]);\n                }\n            }\n        }\n        return userEvents;\n\n    }	0
27147868	27147770	Marshalling C++ struct with a int* member to C#	System.IntPtr	0
12278931	12278690	C# Possible lambda in array's content declaration	string template = "wallpapers\\{0}.jpg";\n\nstring[] wallpapers =\n    Enumerable.Range(1, 4)\n        .Select(i => string.Format(template, i))\n        .ToArray();	0
25601086	25600873	Passing JSON to a C# method with Dictionary<int, List<int>> as parameter	Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>{\n                {0, new List<int>{1,2}},\n                {1, new List<int>{3,4}}\n            };\n\n            var serializer = new JavaScriptSerializer();\n\n            ViewBag.Message = serializer.Serialize(dict);	0
15599331	15599292	asp.net Dictionary<string,string> update item based on key value	myDict[key] = value;	0
25441991	25441242	Enable Disable Checkbox in Asp.net Gridview Based on DropDownList in C#	protected void DDL_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        for (int i = 0; i < GridView1.Rows.Count; i++)\n        {\n            CheckBox chkSelect = ((CheckBox)GridView1.Rows[i].FindControl("chkSelect"));\n\n            if (DDL.SelectedIndex != 0)\n            {\n                chkSelect.Enabled = true;\n            }\n        }\n    }	0
22464071	22463953	Populating a list based on its element type when passed to a method	static void Populate<T>(List<T> list, ...) where T: new()\n{\n    ... \n    for (int i=0; i<rndNum; i++)\n        list.Add(new T());\n}	0
22631820	22631714	How can I convert this array to c#?	Dictionary<string, List<string>>cards = new Dictionary<string, List<string>>\n    {\n        {"Player", new List<string>()},\n        {"Dealer", new List<string>()}\n    };	0
23847261	23847148	Replace string value in C#?	for (int i = 0; i < Model.Items.Count; i++)\n{\n    string SelectedEvent = "event selected";    \n    if (i > 1)\n    {\n         SelectedEvent = "event"; \n    }\n\n    // here you can use the SelectedEventVariable\n    // its value will be "event selected" on the first and second\n    // iterations and "event" on subsequent \n}	0
29510297	29510139	correct conversion fom Vb to c#	if (cbFilterOnColor.Checked)\n{\n    imgGrayColorFiltered = imgSmoothed.InRange(new Bgr(dblMinBlue, dblMinGreen, dblMinRed), new Bgr(dblMaxBlue, dblMaxGreen, dblMaxRed));\n}	0
25046153	25030204	How to set height width of imageview control in xamarin ios	myImageView.Frame = new RectangleF(x-coordinate, y-coordinate, width, height);	0
31609349	31609289	Complexity of searching in a list and in a dictionary	Dictionary<,>	0
6667502	6667456	how to improve the performance of reading bytes line by line from a filestream	static IEnumerable<byte[]> fread(string fname, Encoding enc) \n{\n  using (var f = File.OpenRead(fname))\n  using (var reader = new StreamReader(f, enc))\n    while (!reader.EndOfStream)\n      yield return enc.GetBytes(reader.ReadLine());     \n}	0
18422113	18421747	How do I process a response from a remote REST API (Paypal)?	dynamic reply= JsonConvert.DeserializeObject(jsonstring)	0
23836252	23836227	How to choose between different if conditions depending on another variable	if ((test && first_condition) || (!test && different_condition)) {\n    callSomeFunction();\n}	0
33185376	33184185	Changing AudioSource volume	public GameObject go = GameObject.Find("MyGameObjectAudioSource");\nvoid Update()\n{\n     go.GetComponent<AudioSource>().volume = 0.5f;\n}	0
27788928	27788848	Includ OptionSetValue in QueryExpression	new ConditionExpression\n    {\n        AttributeName = "neu_appointmentstatus",\n        Operator = ConditionOperator.Equal,\n        Values = 279660000\n    }	0
29150905	29150611	Why does setting a WPF ListCollectionView Filter predicate inside a for loop cause strange behavior?	for (int i = 0; i <= 1; ++i)\n{\n    var localValue = i;\n    _peopleViews[i].Filter = obj => ((Person)obj).Number == localValue;\n}	0
19085335	19085266	how to get partial string seperated by commas?	void Main()\n{\n    string mystring="part1, part2, part3, part4, part5";\n\n    int thirdCommaIndex =  IndexOf(mystring, ',', 3);\n    var substring = mystring.Substring(0,thirdCommaIndex-1);\n    Console.WriteLine(substring);\n}\n\nint IndexOf(string s, char c, int n)\n{\n  int index = 0;\n  int count = 0;\n  foreach(char ch in s)\n  {\n     index++;\n    if (ch == c)\n     count++;\n\n    if (count == n )\n     break;\n  }\n  if (count == 0) index = -1; \n  return index;  \n}	0
32468694	32467804	EF CodeFirst set default string length and override with DataAnnotations?	protected override void OnModelCreating(DbModelBuilder modelBuilder) \n{ \n    modelBuilder.Properties<string>() \n                .Configure(c => c.HasMaxLength(500));\n}	0
9199377	9198818	autocomplete source from Outlook address book	Outlook.ExchangeUser exchUser = addrEntry.GetExchangeUser();\nDebug.WriteLine(exchUser.Name + " " + exchUser.PrimarySmtpAddress);	0
22344318	22341563	Regex to match groups	(\w+)\s+([^\d]+)(\d+)	0
1056853	1042814	Conversion of text data into date	private void button1_Click(object sender, EventArgs e)\n\n      {\n        string s = textBox1.Text;           \n        string DFF = textBox3.Text;          \n\n        //To check whether field is empty\n\n        if (String.IsNullOrEmpty(s))\n        { \n          MessageBox.Show("Please enter correct date");\n          textBox2.Text = "Enter correct date";\n        }           \n        else\n        {\n            DateTime dt = DateTime.ParseExact(s, DFF, null);\n            textBox2.Text = dt.ToShortDateString();\n         }\n\n    }	0
33822763	33822726	How to calculate Previous Week's last date for a given date?	string yourInput = "2015-11-20"; \n\nDateTime reference = DateTime.ParseExact(yourInput , "yyyy-MM-dd", CultureInfo.InvariantCulture);\n\nDateTime lastSaturday  = reference ;\n\ndo \n{\n    lastSaturday = lastSaturday.AddDays(-1) ; \n}\nwhile(lastSaturday.DayOfWeek != DayOfWeek.Saturday); \n\n\nConsole.WriteLine(lastSaturday.ToString("dd-MMM-yyyy")) ;\n// Should print 14-Nov-2015	0
16254525	16253286	Filter double messages from serial	// code to filter out false signals\n    DateTime lastTimeSignalReceived = DateTime.Now;\n    double minimumTimeBetweenSignals = 4.9; // 12 rpm = 5 seconds between signals minimum\n    int turns = 0;\n    private void txtOutput_TextChanged(object sender, EventArgs e)\n    {\n        if (value == 1)\n        {\n            // the if statement is true only if at least 4.9 seconds has past since last signal\n            // which should filter out false signals\n            if ((DateTime.Now - lastTimeSignalReceived).TotalSeconds > minimumTimeBetweenSignals)\n            {\n                // at least 4.9 seconds since last signal\n                textBox6.text = turns.ToString();\n                turns++;\n\n                // set lastTimeSignalReceived to new time\n                lastTimeSignalReceived = DateTime.Now;\n            }\n        }\n    }	0
11932962	11932925	How do I round the number in a textbox to 2 decimals in C#?	decimal.ToString("N");	0
33614288	33613414	How do I assign parameter values to a string using c#	taskAssgTo = c.Value<string>("assignedTo.name");	0
14867495	14867459	How to compare nullable variable in linq?	...\nwhere workingResult.EmployeeCode == employeeCode && \n(workingResult.EffectiveDate.HasValue && \n workingResult.EffectiveDate.Value.Date == date.Date).FirstOrDefault();	0
19146385	19146269	Do formatting helper methods belong in the model, the view model, or a separate class?	public class CompanyIndexViewModel\n{\n    ...\n    public string TaxID { get; set; }\n\n    public string USFormattedTaxID\n    {\n        get { return Utilities.FormatTaxID(TaxID); }\n    }\n}	0
29379450	29379394	Dynamically reading .json file with multiple objects	jQuery.parseJSON(<your string>);	0
22985598	22831107	Custom format for Console Output	Console.ForegroundColor = borderColor;\nConsole.Write("{0,-" + (Console.WindowWidth - message.Length) / 2 + "}", borderChar);\n\nConsole.ForegroundColor = messageColor;\nConsole.Write(message);\n\nConsole.ForegroundColor = borderColor;\nConsole.Write("{0," + ((Console.WindowWidth - message.Length) / 2 + message.Length % 2) + "}", borderChar);	0
14801885	14801815	set value using reflection	var prop = ReflectionObject.GetProperty("Frame");\nprop.SetValue(r, 2);	0
28753134	28753086	How to execute batch file from visual c# application	private void testButton_Click(object sender, EventArgs e)\n{\n    System.Diagnostics.Process.Start(@"..\test.bat");\n}	0
28842337	28842248	How do I use multiple GET methods on the same route in ASP.NET?	public ActionResult Action(string model, string make)\n{\n    if(!string.IsNullOrEmpty(model))\n    {\n        // do something with model\n    }\n\n    if(!string.IsNullOrEmpty(make))\n    {\n        // do something with make\n    }\n}	0
12957580	12738183	Create a Factory with MEF	Lazy<T>	0
33171371	33150851	How can I use basic authentication on a WCF endpoint hosted in IIS over SSL with json?	if (httpContext.User != null) return null;	0
520834	520788	Can I select multiple objects in a Linq query	IEnumerable<Team> drew = (from fixture in fixtures\n                     where fixture.Played \n                        && (fixture.HomeScore == fixture.AwayScore)\n                     select fixture.HomeTeam)\n                     .Union(from fixture in fixtures\n                     where fixture.Played \n                        && (fixture.HomeScore == fixture.AwayScore)\n                     select fixture.AwayTeam);	0
19239355	19239314	How can I get a connection string from a text file?	using System;\nusing System.IO;\n\nclass Test \n{\n\n    public static void Main() \n    {\n        string txtpath = @"c:\textfile.txt";\n        try \n        {\n            if (File.Exists(txtpath)) \n            {\n\n\n\n            using (StreamReader sr = new StreamReader(txtpath)) \n            {\n                while (sr.Peek() >= 0) \n                {\n                    string ss = sr.ReadLine();\n                     string [] txtsplit = ss.Split(';');\n\n                     //now loop through   array\n                     string server=txtsplit[0].Tostring();\n                    string userid= split[1].Tostring(); // user id\n                   string password= split[2].Tostring(); // password\n\n                }\n            }\n          }\n        } \n        catch (Exception e) \n        {\n            Console.WriteLine("Error: {0}", e.ToString());\n        }\n    }\n}	0
29394245	29393700	Create and Show a WinForm	// I'd rather return potentially created form directly (not via "ref")\n// do you need "this" in the method? That's why "static"\nstatic T showOrUpdateForm<T>(T form = null)\n  where T: Form, new() {\n\n  if (null == form) \n    form = new T(); // <- no Activator since "new()" constraint is declared\n\n  form.WindowState = FormWindowState.Normal;\n  form.BringToFront(); // <- if the form is not a foreground one\n\n  if (form.CanFocus) // <- better check than have an exception\n    form.Focus();\n\n  return form;\n}\n...\n// more compact and readable\nmyForm1 form = showOrUpdateForm<myForm1>();	0
4284488	4284345	create CSV file in c#net Window application	string csvString = "";\nfor each column in row\n    csvString += column.value + ","\n\nwriteToFile(csvString,filePath);	0
6683028	6680591	PopupContainerEdit with XtraTreeList as dropdown Demo	PopupContainerEdit edit = new PopupContainerEdit();\n        Controls.Add(edit);\n        PopupContainerControl pControl = new PopupContainerControl();\n        Controls.Add(pControl);\n        TreeList tl = new TreeList();\n        tl.Columns.Add().Visible = true;\n        tl.AppendNode(new object[] { "123" }, null);\n        pControl.Controls.Add(tl);\n        edit.Properties.PopupControl = pControl;	0
16937716	16936549	WebBrowser iframe shows NavigationCancelled	windows-phone-8	0
21040379	21039929	Create DataGrid in codebehind with bindings	var myDataGrid = new DataGrid();\nmyDataGrid.SetBinding(DataGrid.ItemsSourceProperty, new Binding("NewContactList") { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.TwoWay });\nmyDataGrid.SetResourceReference(DataGrid.ItemsPanelProperty, "panelTemplate");\nmyDataGrid.SetResourceReference(DataGrid.ItemTemplateProperty, "ListTemplate");\nmyDataGrid.SetValue(DragDropHelper.IsDragSourceProperty, True);\nmyDataGrid.SetValue(DragDropHelper.IsDropTargetProperty, True);\nmyDataGrid.SetResourceReference(DragDropHelper.DragDropTemplateProperty, "DragTemplate");	0
7486788	7486744	Reset a variable via void function	static int test = 1; \n\nstatic void Main(string[] args)\n{\n\n    resetTest();\n\n    Console.Write(test); // Should be 0\n}\n\nstatic void resetTest()\n{\n    test = 0;\n}	0
1172267	1172178	How to get the data value of an enum in a generic method?	public static object EnumToDataSource<T>() where T : struct, IConvertible\n    {\n    if (!typeof (T).IsEnum) throw new Exception(string.Format("Type {0} is not an enumeration.", typeof (T)));\n    var q =\n    Enum.GetValues(typeof (T)).Cast<T>().Select(x => new {ID = x.ToByte(null), Description = x.ToString()}).OrderBy(\n    x => x.Description).ToArray();\n    return q;\n    }	0
26340571	26340485	How to get inner xml from string containing XMl	List<string> list = XDocument.Parse(xmlString)\n                     .Descendants("author")\n                     .Select(x => x.ToString())\n                     .ToList();	0
1793397	1791831	moving data between Assembler Registers	mov   ecx,319E40h   // probably a value uniquely identifiying the classtype?\ncall  FF9A0AD4      // call a routine on it? puts result in eax probably\nmov   dword ptr [ebp-44h],eax  // save result(eax) to a localvariable\nmov   ecx,dword ptr [ebp-44h]  // reload the local parameter to ecx, probably \n                               // the reference to the new class instance.\ncall  FF9BB058                 // some function on the instantiated class.\nmov   eax,dword ptr [ebp-44h]  // reload the reference\nmov   dword ptr [ebp-40h],eax  // store to another local variable.	0
11122460	11122034	How do I store data from an ObservableCollection into an SQL database?	ObservableCollection<Product> Products = this.listBox1.ItemsSource as ObservableCollection<Product>;\nproxy.AddPayNowOrderCompleted += new EventHandler<AddPayNowOrderCompletedEventArgs>(proxy_AddPayNowOrderCompleted);\nforeach (Product p in Products)\n{\n    proxy.AddPayNowOrderAsync(p.orderdate, p.prodid, p.orderprodname, p.orderprice, p.orderstatus, p.custemail, p.paymentdate);\n}	0
11632430	11632419	how can i make an infinite loop with 5 second pauses	while (true) {\n    // code here\n    Thread.Sleep(5000);\n}	0
4513651	4513257	Parallel Task For Tree structure	void run()\n{\n   do action on parent;\n   DoTasks(parent);\n}\n\nvoid DoTasks(Node node)\n{\n  if (node.Childs == null) return;\n\n  Parallel.Foreach(node.Childs, child => {do action})\n\n  foreach(var child in node.Childs)\n  {\n    DoTasks(child);\n  }\n}	0
3212501	3212491	How to limit a decimal number?	Math.Round(3.44, 1); //Returns 3.4.	0
22229216	22229125	Execute a void in variable with parameters	push(GetGroups, GroupsXML);	0
11448820	11448591	MVC3,PartialViews,Ajax Passing values	ModelState.Clear()	0
2388297	2388287	Case insensitive string search	textTosearch.IndexOf("some", StringComparison.OrdinalIgnoreCase);	0
11477676	11477596	C# Regex take name from string	return Regex.Match(Data, @"""(.+?)<").Groups[1].ToString();	0
5723728	5723685	Getting a lock on a single dictionary entry instead of whole dictionary?	ConcurrentDictionary<TKey,TValue>	0
1732079	1732054	How might I add an item to a ListBox?	list.Items.add(new ListBoxItem("name", "value"));	0
31549519	31548958	Run GTK# Application in Kiosk Mode	using System;\nusing Gtk;\n\nnamespace GtkfullscreenNotdecorated\n{\n    class MainClass\n    {\n        public static void Main (string[] args)\n        {\n            Application.Init ();\n            MainWindow win = new MainWindow ();\n            win.Show ();\n            win.Fullscreen ();\n            win.Decorated = false;\n            Application.Run ();\n        }\n    }\n}	0
15260068	15259905	Load a web page using code behind	WebClient client = new WebClient();\n//client.Credentials = new NetworkCredential("username", "password");\nstring reply = client.DownloadString(address);	0
7781713	7781319	HtmlAgilityPack - How to understand page redirected and load redirected page	var page = "...";\nvar doc = new HtmlDocument();\ndoc.Load(page);\nvar root = doc.DocumentNode;\nvar select = root.SelectNodes("//meta[contains(@content, 'URL')]");\ntry\n{\n    Console.WriteLine("has redirect..");\n    Console.WriteLine(select[0].Attributes["content"].Value.Split('=')[1]);\n}\ncatch\n{\n    Console.WriteLine("have not redirect using HTML");\n}	0
33345938	33345749	Combine ConsoleModifiers and ConsoleKey	ConsoleKeyInfo c;\nwhile ((c = Console.ReadKey()).Modifiers != ConsoleModifiers.Control\n       || c.Key != ConsoleKey.Q) { } //Exit on Ctrl + Q	0
32428221	32428101	Bind HashSet to DataGridView DataSource C#	var book = new BookModel//fill it with your data\n        {\n            Author = "a",\n            Language = "l",\n            Name = "n",\n            PagesCount = 0,\n            Pulbisher = "p",\n            Series = "s",\n            Year = 1990\n        };\n        var list=new List<BookModel>();\n        list.Add(book);\n        var bookContainer = new HashSet<BookModel>(list);//you have to pass list to HashSet constructor\n\n        dataGridViewBookList.DataSource = bookContainer.ToList();	0
5625578	5624614	Get a list of elements by their ID in entity framework	var listOfRoleId = user.Roles.Select(r => r.RoleId);\nvar roles = db.Roles.Where(r => listOfRoleId.Contains(r.RoleId));	0
9865429	9864233	How do I invoke "New Vertical Tab Group" from a VS2010 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 == "MyAddin1.Connect.MyAddin1")\n            {\n                //_applicationObject.ActiveWindow.WindowState.\n                _applicationObject.ExecuteCommand("Window.NewWindow");\n                _applicationObject.ExecuteCommand("Window.NewVerticalTabGroup");\n                handled = true;\n                return;\n            }\n        }\n    }	0
16782932	16782132	Automating the adding in of values from a CSV to a List<class>	var ListOfOrgans = new List<Organ>(); \nString tmp = null;\nString [] tokens = null;\nusing(StreamReader sr = new StreamReader(@"C:\Parameter.csv"))\n{\n   while( !sr.EndOfStream )\n   {\n      tmp = sr.ReadLine();\n      tokens = tmp.Split(' ');\n      Organ foo = new Organ();\n      foo.name = tokens[0];\n      foo.A = Convert.ToDouble(tokens[1]);\n      .\n      .\n      etc.\n\n      ListOfOrgans.Add(foo);\n   }\n}	0
2682159	2682146	Is there a shorthand way to denullify a string in C#?	string y = x ?? "";	0
1984653	1983554	In Gtk#, how do I get a Window's AccelGroup?	AccelGroup glist[] = Accel.GroupsFromObject(mywindow);	0
3685049	2219750	How to use textile.net	string input = "This _text_ is going to be *formatted* using %{color=#f00;}Textile.NET%.";\nstring result = TextileFormatter.FormatString(input);\nConsole.WriteLine(result);	0
24602929	24602693	How do you select multiple aggregates and a non aggregate in LINQ	List<qGroupModel> query = \n                    context.Scores\n                           .Where(p => (p.schoolID == schoolID) && (p.Year == year) && !(p.qGroup.StartsWith("S")))\n                           .GroupBy(p => p.qGroup)\n                           .Select(p => new qGroupModel { p.Average(p2 => p2.Score), p.qGroup })\n                           .ToList();	0
11453551	11453356	Searching a directory, excluding a list of certain file extensions	List<string> fileExtensionsToIgnore = new List<String>(File.ReadAllLines("~/TextFile.txt"));\nList<string> fileList = new List<string>();\nforeach (string filePath in Directory.GetFiles(Path, ".", SearchOption.AllDirectories))\n{\n    if (!fileExtensionsToIgnore.Contains(Path.GetExtension(filePath).ToLower())\n        fileList.Add(filePath);\n}\nstring[] files = fileList.ToArray();	0
4515851	4515847	How to convert List<int> to string[]?	string[] the_array = the_list.Select(i => i.ToString()).ToArray();	0
31672887	31670639	Cast DataGridViewTextBoxCell to DatagridVIewButtonCell WinForms	private void dataGridViewImport_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)\n        {\n            addButtonsToUnactiveRows();\n        }	0
23231658	23231596	How to get a column of a 2D array in C#?	var array = new[] { new[] { "a", "b", "c" }, new[] { "d", "e", "f" }, new[] { "g", "h", "i" } };\n\nvar col1 = array.Select(x => x[1]);\n\n//col1 contains "b", "e" and "h"	0
7134143	7133939	How to set the back color of the row / column header cell in a datagridview - c# winform	public MyForm()\n    {\n        InitializeComponent();\n\n        // insert code here to add columns  ...\n        // ...\n        // ...\n        // ...\n\n        DataGridViewCellStyle oldDefault = dgview.ColumnHeadersDefaultCellStyle.Clone();\n\n        dgview.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;\n\n        foreach (DataGridViewColumn item in dgview.Columns)\n        {\n            item.HeaderCell.Style = oldDefault;\n        }\n    }	0
31491941	31490169	Lookbehind with equal sign	(?<!=)===(?!=)(?<Title>.*?)(?<!=)===(?!=)	0
26440871	26440783	Regex to get all lines past last detected string	\A.*//// CODE ---.*?$\s(.+)\z	0
30285234	30285115	Simple Injector - register IEnumerable of abstract class implementations	// Simple Injector v3.x\ncontainer.RegisterCollection<Animal>(new[] {\n    typeof(Cat), \n    typeof(Dog), \n    typeof(Pig)\n});\n\n// or\ncontainer.RegisterCollection<Animal>(\n    from type in typeof(Animal).Assembly.GetTypes()\n    where type.IsSubclassOf(typeof(Animal))\n    select type);\n\n// Simple Injector v2.x\ncontainer.RegisterAll<Animal>(new[] {\n    typeof(Cat), \n    typeof(Dog), \n    typeof(Pig)\n});	0
3337731	3337486	How to determine if an HTTP response is complete	REQUEST LINE\nHEADERS\n(empty line)\nBODY	0
16836350	16836065	Getting the name,size and url of all files from a directory with c# code	var di=new DirectoryInfo(somePath);\nvar allFiles=di.GetFiles("*",SearchOption.AllDirectories);\nforeach(var file in allFiles)\n{\n    Console.WriteLine("{0} {1}",file.Name,file.Length);\n}	0
27777576	27777411	Show Generated HTML on new page without saving in a file	var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));\nwin.document.body.innerHTML = "Pass your html here";	0
1363651	1363619	Exclusively open/modify an XML file?	stream.Seek(0, SeekOrigin.Begin);\nstream.SetLength(0);	0
34055563	34055493	Windows Application Different Privileges from the User Running it	networkCredential theNetworkCredential = new NetworkCredential(username, password, domain);\nCredentialCache theNetcache = new CredentialCache();\ntheNetCache.Add(@"\\computer", theNetworkCredential, "Basic", theNetworkCredential);\n//then do whatever, such as getting a list of folders:\nstring[] theFolders = System.IO.Directory.GetDirectories("@\\computer\share");	0
13647392	13647255	Assiging an xml query result to a variable	static void Main(string[] args)\n        {\n            XDocument doc = XDocument.Load(xmlFile);\n            IEnumerable<XElement> rows = from row in doc.Descendants("x")\n                                         where row.Attribute("a1").ToString() == "abc" & row.Attribute("a2").ToString() == "xyz"\n                                         select row;\n\n            int first;\n            int second;\n            int third;\n\n            foreach (XElement ele in rows)\n            {\n                Int32.TryParse(ele.Attribute("a3").Value, out first);\n                Int32.TryParse(ele.Attribute("a4").Value, out second);\n                Int32.TryParse(ele.Attribute("a5").Value, out third);\n\n                Console.WriteLine(string.Format("{0} {1} {2}", first, second, third);\n            }\n        }\n    }\n}	0
29644962	29622850	Getting values from mouse hover on a class object C#	double AngleFromPoints(Point pt1, Point pt2)\n{\n    Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);\n    double alpha = 0d;\n    if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;\n    else\n    {\n        double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));\n        alpha = Math.Acos(f) * 180d / Math.PI; \n        if (P.Y > 0) alpha = 360d - alpha;\n    }\n    return alpha;\n}	0
11581793	11581522	Open wpf window from other project	namespace WpfApplication1\n{\n    /// <summary>\n    /// Interaction logic for MainWindow.xaml\n    /// </summary>\n    public partial class MainWindow : Window\n    {\n        WpfApplication2.MainWindow newForm;\n\n        public MainWindow()\n        {\n            InitializeComponent();\n\n        }\n\n        private void button1_Click(object sender, RoutedEventArgs e)\n        {\n            newForm = new WpfApplication2.MainWindow();\n\n            newForm.Show();  // or newForm.ShowDialog();\n        }\n    }\n}	0
7971025	5244687	How to detach a LINQ-to-SQL data object from the DataContext's tracking mechanism?	public void Detach()\n{\n    GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);\n}	0
25732488	25732274	Look for file in directory that contains a certain substring	var xmlFiles = from file in Directory.EnumerateFiles(@"C:\Temp", "*.xml")\n               let fileName = Path.GetFileNameWithoutExtension(file)\n               where fileName.StartsWith("xrefTester_(") && !fileName.EndsWith(".bak")\n               select file;\nforeach(string path in xmlFiles)\n{\n    string dir = Path.GetDirectoryName(path);\n    string newFileName = string.Format("{0}{1}{2}", \n                Path.GetFileNameWithoutExtension(path),\n                ".bak",\n                Path.GetExtension(path));\n    File.Move(path, Path.Combine(dir, newFileName)); // cannot exist due to logic above\n}	0
23332408	23325902	How to register All types of an interface and get instance of them in unity?	// There's other options for each parameter to RegisterTypes()\n// (and you can supply your own custom options)\ncontainer.RegisterTypes(\n    AllClasses.FromLoadedAssemblies().\n        Where(type => typeof(IRunOnEachRequest).IsAssignableFrom(type)),\n    WithMappings.FromAllInterfaces,\n    WithName.TypeName,\n    WithLifetime.Transient);\n\nforeach (var task in container.ResolveAll<IRunOnEachRequest>())\n    task.Execute();	0
6818583	6818057	how to add text in rectangle with code behind wpf	for (int i = 0; i < _RoomX.Count; i++)\n        {\n            _RoomX[i] = (Convert.ToDouble(_RoomX[i]) * 20).ToString();\n            _RoomY[i] = (Convert.ToDouble(_RoomY[i]) * 20).ToString();\n\n            var rectangle = new Rectangle()\n            {\n\n                Stroke = Brushes.Black,\n                Fill = brush,\n                Width = Convert.ToDouble(_RoomX[i]),\n                Height = Convert.ToDouble(_RoomY[i]),\n                Margin = new Thickness(\n                    left: 15,\n                    top: 50,\n                    right: 0,\n                    bottom: 0),\n                HorizontalAlignment = HorizontalAlignment.Left,\n                VerticalAlignment = VerticalAlignment.Top\n\n            };\n\n            Grid grid = new Grid();\n            grid.Children.Add(rectangle);\n            TextBlock textblock = new TextBlock();\n            textblock.Text = "Text to add";\n            grid.Children.Add(textblock);\n\n            mainCanvas.Children.Add(grid);\n        }	0
26787435	26787142	Error only apears while running program as a stand alone C#	private static Array ResizeArray(Array arr, int[] newSizes)\n{\n    // Add next four lines\n    if (newSizes == null)\n        throw new ArgumentNullException("newSizes is null!"); \n    if (arr == null)\n        throw new ArgumentNullException("arr is null!"); \n    if (newSizes.Length != arr.Rank)\n        throw new ArgumentException("arr must have the same number of dimensions " +\n                                    "as there are elements in newSizes", "newSizes");\n\n    var temp = Array.CreateInstance(arr.GetType().GetElementType(), newSizes);\n    int length = arr.Length <= temp.Length ? arr.Length : temp.Length;\n    Array.ConstrainedCopy(arr, 0, temp, 0, length);\n    return temp;\n}	0
4570166	4570158	Replacint single or multiple space to %	str = Regex.Replace(str, " +", "%");	0
12308454	12308422	Serialize XML to byte[] instead of to file	using (var stream = new MemoryStream(buffer))\n{\n    using (TextWriter textWriter = new StreamWriter(stream))\n    { ... }\n}	0
9094399	9089724	Redraw image WPF	MyImage.Source = null;\nMyImage.Source = NewSource;	0
2326262	2326229	What is the best way to convert a string separated by return chars into a List<string>?	List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();	0
19729038	19728935	Recursion to create a Sum Method	Add1(value) {\n  return value + 1;\n}\n\nSub1(value) {\n  return value - 1;\n}\n\nSum(value1 , value2) {\n   if(value2 == 0) {\n       return value1;\n   }\n   value1 = Add1(value1);\n   value2 = Sub1(value2);\n   return Sum(value1, value2);\n}\n\nProd(value1, value2) {\n    if(value2 == 0) {\n       return 0;\n   }\n   value2 = Sub1(value2);\n\n   return Sum(value1, Prod(value1, value2));\n}	0
33025716	33025601	Deleting a directory, recreating it, and adding files to it	if (Directory.Exists(strScriptsDirectory))\n{                \n    DirectoryInfo directoryInfo = new DirectoryInfo(strScriptsDirectory);\n\n    // Delete the files\n    foreach (FileInfo fileInfo in directoryInfo.GetFiles())\n        fileInfo.Delete();\n    // Delete the directories here if you need to.\n}\nelse\n    Directory.CreateDirectory(strScriptsDirectory);	0
8453319	8452224	How to get attribute value for an assembly in Cecil	type.CustomAttributes[0].ConstructorArguments[0].Value	0
3951965	3914880	When using a virtual printer how I can check that print to file is finished?	Do Until _Doc.Application.BackgroundPrintingStatus = 0\n            System.Windows.Forms.Application.DoEvents()\n            System.Threading.Thread.Sleep(750)\n        Loop	0
14816481	13079433	OData (WCF Data Services) Continuation on a query that uses projection	var query = entities.MyObjects.Skip(200).Take(100).Select(x => new {x.MyObjectID, x.Number, x.Name});	0
32197514	32194977	How to save the specific textboxes with special order to a text file?	SaveFileDialog save = new SaveFileDialog();\n     // save.FileName = "Parameters.txt";\n        save.Filter = "Text File | *.txt";\n       if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n       {\n           using (System.IO.StreamWriter File = new System.IO.StreamWriter(save.FileName))\n           {\n               File.Write("===========parameters===========" + "\r\n");\n               File.Write("Number of teeth: " + "\r\n");\n\n               // File.Close();\n               MessageBox.Show("Saving succeed(Parameters)");\n           }\n        }	0
30987190	30987132	How to write text to a specific line in Visual Studio C#	string[] lines = File.ReadAllLines(path);\nlines[index] = newText;\nFile.WriteAllLines(path, lines);	0
16962060	16961987	Partial Matching While Searching in a List of Strings in Linq	AllDegrees.Listt.Where(x => x.Contains("your string")).Any();	0
34131422	34131047	Regex find first and last element within parentheses	String\((?<first>0x[0-9A-Fa-f]+).*?(?<last>0x[0-9A-Fa-f]+)\)	0
13777196	13776648	show the list of usernames inside a div	chat.server.getConnectedUsers().done(function(users) {\n    for(var i = 0; i < users.length; ++i) {\n        // Write javascript here to append users to the list\n    }\n});	0
11665219	11665178	Reading files in particular order?	List<FileInfo> files = directory\n    .GetFiles("*.txt")\n    .OrderBy(f => f.LastWriteTime)\n    .ToList();	0
2269498	2269462	Deserialize flat xml to entities	public class MyDto {\n    public string A {get;set;}\n    public string B {get;set;}\n    public string C {get;set;}\n    public string D {get;set;}\n\n    public FooUnited GetObject() {\n        return new FooUnited {\n            foo1 = new Foo1 { A = this.A, B = this.B },\n            foo2 = new Foo2 { C = this.C, D = this.D },\n        };\n    }\n}	0
18231289	18231081	How to Call Static parameterless constrcutor in structure?	System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(\n    type.TypeHandle);	0
1971175	1971104	MMC custom snap-ins installation	MMC /32	0
25606634	21250279	Send a command to Word without GUI Automation	string command = "Copy";\nbool flag= Globals.ThisAddIn.Application.CommandBars.GetEnabledMso(command);\nif (flag)\n{\n    Globals.ThisAddIn.Application.ActiveDocument.CommandBars.ExecuteMso(command);\n}	0
24311924	24311812	3 Lines of code to 1 line	makeNode(left, right);	0
21871194	21870855	making the image on a picturebox change when a specific name is selected from a listbox in C#	if (lstBxBagType.SelectedItem.ToString() == "Beaded-$45.00")\n        {\n            // do something\n        }	0
18751740	18749543	Tap event on dynamically added custom control is handled by another control of same type	var newWaypoint = new Waypoint(waypointNumber, latitude, longitude);\nnewWaypoint.Name = "wayPoint" + waypointNumber;\nnewWaypoint.Opacity = 100;\ndouble leftMargin = CalculateLeftMargin(longitude);\ndouble topMargin = CalculateTopMargin(latitude);\n\nnewWaypoint.Margin = new Thickness(leftMargin, topMargin, 0, 0);\nLayoutRoot.Children.Add(newWaypoint);	0
455241	455237	Pop off array in C#	List<String>\nQueue<String>\nStack<String>	0
8215614	8202348	Passing cookie to login-page	CookieContainer cookieJar = new CookieContainer();\nHttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mydomain.com/Start.aspx?g=4");\nrequest.CookieContainer = cookieJar;\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\nCookieContainer cookies = new CookieContainer();\nHttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://mydomain.com/Login.aspx");\nrequest1.CookieContainer = cookieJar;\nHttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();\nStreamReader reader = new StreamReader(response1.GetResponseStream());\nstring loginPage = reader.ReadToEnd();\nreader.Close();	0
14398359	14398300	Setting SQL datetime to minimum using C# DateTime	SqlDateTime.MinValue	0
32780636	32780545	Need help making a counting program	for (int count = lowerLimit; count <= upperLimit; count+=stepSizes)\n{\n    Console.WriteLine(count);\n}	0
10638127	10637083	Insert in to a nested array Using C# Official Driver MongoDB	var doc = collection.FindOne(Query.EQ("_id", new ObjectId("4fb4fd04b748611ca8da0d48")));\n\nvar standards = doc["categories"]\n    .AsBsonArray[0]\n    .AsBsonDocument["sub-categories"]\n    .AsBsonArray;\n\nstandards.Add(new BsonDocument());\n\ncollection.Save(doc);	0
11289021	11288893	How to get the name of each day in next month?	DateTime Base = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);\nint x = DateTime.DaysInMonth(Base.Year, Base.Month);\nwhile (Base.Day != x)\n{\n    Console.WriteLine(Base.DayOfWeek.ToString());\n    Base = Base.AddDays(1);\n}	0
25348062	25348042	How can I change an image/bitmap that is already in use?	var m = new MemoryStream(File.ReadAllBytes(filename));\nBitmap thump = (Bitmap)Bitmap.FromStream(m);	0
7943694	7943674	regex to remove everything after a certain character (comment)	tb.Lines = (\n    from l in tb.Lines \n    let x = l.IndexOf (';') \n    select (x >= 0 ? l.SubString (0, x) : l)\n).ToArray();	0
18082852	18082548	How to place a Windows special folder in config file	//string folderKey = ConfigurationManager.AppSettings["Folder"];\n  string folderKey = "%CommonApplicationData%\\Test";\n  var regex = new Regex("([%][^%]+[%])");\n  string folder = regex.Replace(folderKey, (match) => {\n    // get rid of %%\n    string value = match.Value.Substring(1, match.Value.Length - 2);\n    var specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), value, true);\n    return Environment.GetFolderPath(specialFolder);\n  });	0
2066353	2065783	Is there a .NET Polymorphic Data Framework	public interface ICommentable\n{\n   int CommentTypeCode\n   int Id\n   ...\n}	0
3201082	3201072	Reading ID3 tags from the web with C#	WebClient Client = new WebClient ();\nClient.DownloadFile("http://myserver.com/indie/band1.mp3", "band1.mp3");	0
7494765	7494615	How to split a media file	System.Diagnostics.Process p = new System.Diagnostics.Process();\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardError = true;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.CreateNoWindow = true;\np.StartInfo.FileName = ffmpegPath.FullName;\np.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\np.StartInfo.Arguments = "some ffmpeg commands here";\ntry {\n    p.Start();\n} catch (Exception ex) {\n    ' trap error\n}\n\nString out = p.StandardError;	0
4209575	4209167	Convert a stored procedure than contains CASE values?	var test = from c in db.C\nselect new {\n  Period = c.M.Period,\n  Group = c.Code,\n  Code = c.ClientCode,\n  Name = c.ClientName,\n  Status = \n      ((from m0 in db.M\n    where\n      m0.ClientCode == c.ClientCode\n    group m0 by new {\n      m0.ClientCode\n    } into g\n    select new {\n      SumOfAmount = (System.Int32)g.Sum(p => p.Amount)\n    }).First().SumOfAmount) == 0 ? "Balanced" : \n      ((from m0 in db.M\n    where\n      m0.ClientCode == c.ClientCode\n    group m0 by new {\n      m0.ClientCode\n    } into g\n    select new {\n      SumOfAmount = (System.Int32)g.Sum(p => p.Amount)\n    }).First().SumOfAmount) > 0 ? "Pending" : null\n}	0
11888022	11887984	Pass a class gotten from Reflection to a generic method	Type thisType = this.GetType();\n\nvar mi = thisType.GetMethod("TestOpen");\n\nforeach (var x in yy)\n{\n    var gmi = mi.MakeGenericMethod(x.Type);\n    gmi.Invoke(this, null);\n}	0
1420555	1420486	One DI Container for multiple ASP.Net applications	public interface IContainer\n{\n    T Resolve<T>();\n}	0
2280563	2280526	Forcing controls to contain only certain elements, such as ContentTemplate	[ParseChildren(true), PersistChildren(false)]\npublic class Repeater : Control, INamingContainer\n{\n  [PersistenceMode(PersistenceMode.InnerProperty)]\n  public virtual ITemplate HeaderTemplate { get; set; }\n\n  [PersistenceMode(PersistenceMode.InnerProperty)]\n  public virtual ITemplate ItemTemplate { get; set; }\n}	0
3425034	3424999	Getting all of the values for a property for a list of objects	TheClass[] myClasses = GetTheArray();\n\nList<string> = myClasses.Select(c => c.A).ToList();	0
781125	780974	How to work with settings spanning over multiple Solutions and Projects in VS 2008 and .NET	[GeneratedCode(\n"Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator"\n,"9.0.0.0")] \n[CompilerGenerated]\ninternal sealed class Foo : ApplicationSettingsBase\n{\n    private static Settings defaultInstance = \n        ((Settings) SettingsBase.Synchronized(new Settings()));\n\n    public static Settings Default\n    {\n        get { return defaultInstance; }\n    }\n\n\n    [ApplicationScopedSetting]\n    [DefaultSettingValue("Shuggy")]\n    [DebuggerNonUserCode]\n    public string MyName\n    {\n        get\n        {\n            return (string) this["MyName"];\n        }\n    }\n}	0
24680506	24680259	How to route to a default action without it defined in the URL	routes.MapRoute(\n  name: "Brand Details",\n  url: "Brand/{brandName}",\n  defaults: new { controller = "Brand", \n                  action = "Index", \n                  brandName = UrlParameter.Optional }\n);	0
23213920	23213482	c# double screen app, how to change frame of the mainwindow from second window?	var mainWin = Application.Current.MainWindow as MainWindow;\nDebug.Assert( mainWin != null ); //sanity check\n//do things with mainWin	0
18257222	18257069	Hide Taskbar in Windows 8	DllImport("user32.dll")]\nprivate static extern int FindWindowEx(int parent, int afterWindow, string className, string windowText);\n\n// Start with the first child, then continue with windows of the same class after it\nint hWnd = 0;\nwhile (hWnd = FindWindowEx(0, hWnd, "Shell_TrayWnd", ""))\n    ShowWindow(hWnd, SW_SHOW);	0
14755435	14754809	Multiple POST using WebRequest	var response = smsRequest.GetResponse() as HttpWebResponse;	0
33172824	33172327	Webbrowser Control how to change a window javascript property?	var document=webBrowser1.Document.DomDocument as MSHTML.IHTMLDocument2;\nvar expando =(IExpando)document.parentWindow;\nexpando.RemoveProperty(expando.GetMember("navigator",BindingFlags.Instance | BindingFlags.Public));\nexpando.AddProperty("navigator").SetValue(expando,myNavigator);	0
2953705	2953485	using IDataReader to call store procedure with parameters	using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.Common;\nusing System.Data.SqlClient;\nusing System.Text;\nusing Microsoft.Practices.EnterpriseLibrary.Data.Sql;\n\n// ...\n\nSqlDatabase db = new SqlDatabase("YourConnectionString");\nDbCommand cmd = db.GetStoredProcCommand("YourProcName");\ncmd.Parameters.Add(new SqlParameter("YourParamName", "param value"));\n\nusing (IDataReader dr = db.ExecuteReader(cmd))\n{\n    while (dr.Read())\n    {\n        // do something with the data\n    }\n}	0
20406297	20406116	Access Enum custom attributes whilst looping over values	static string GetStringValue2(Enum value) {\n ....\n}\n\npublic static List<SelectListItem> GetFlagsSelectList<T>(int? selectedValue) where T : struct {\n  var items = new List<SelectListItem>();\n  foreach (T value in Enum.GetValues(typeof(T))) {\n    var stringValue = GetStringValue2((Enum)(object)value);\n    items.Add(new SelectListItem {\n      Text = Enum.GetName(typeof(T), value),\n      Value = Convert.ToInt32(value).ToString(),\n      Selected = selectedValue.HasValue && selectedValue.Value == Convert.ToInt32(value)\n    });\n  }\n  return items;\n}	0
24851490	24851306	Update database access , c#	public void EditAlbum (Album newAlbum)\n{\n    command.CommandText = @"UPDATE Album SET [Name]=@Name, \n                            [Description]=@Description, \n                            [Location]=@Location, \n                            [Date]=@Date,\n                            [CoverPhotoURL]=@Cover \n                            WHERE [ID]=@Id";\n\n    command.Parameters.AddWithValue("@Name", newAlbum.Name);\n    command.Parameters.AddWithValue("@Description", newAlbum.Description);\n    command.Parameters.AddWithValue("@Location", newAlbum.Location);\n    command.Parameters.AddWithValue("@Data", newAlbum.Date);\n    command.Parameters.AddWithValue("@Cover", newAlbum.CoverPhoto);\n    // Moved after the Cover parameter\n    command.Parameters.AddWithValue("@Id", newAlbum.ID);\n    command.ExecuteNonQuery();\n}	0
25617727	25617591	Addition for multiple textboxes dynamically when entering a value to a TextBox in C# .NET	private void txtCCA_TextChanged(object sender, EventArgs e)\n{\n    sumNumbers()\n}\nprivate void sumNumbers()\n{\n    float.TryParse(txtGTC.Text, out n1);\n    float.TryParse(txtPF.Text, out n2);\n    float.TryParse(txtbasicsalery.Text, out n3);\n    float.TryParse(txthoserent.Text, out n4);\n    float.TryParse(txtlicrent.Text, out n5);\n    float.TryParse(txtDA.Text, out n6);\n    float.TryParse(txtCCA.Text, out n7);\n    grossalery = n1 + n2 + n3 + n4 + n5 + n6 + n7;\n    txtgrosssalery.Text = Convert.ToString(grossalery);\n}	0
21202756	21202610	Regular expression named group match in any order?	^(?<name>.+?)=(?<value>[^;]+)(?:(?=.*(?:Expires=(?<expires>[^;]+))))?(?:(?=.*(?:Path=(?<path>[^;]+))))?(?:(?=.*(?:Domain=(?<domain>[^;]+))))?(?:(?=.*(?<httponly>HttpOnly)))?(?:(?=.*(?<secure>Secure)))?	0
674338	674225	Calculating point on a circle's circumference from angle in C#?	result.Y = (int)Math.Round( centerPoint.Y + distance * Math.Sin( angle ) );\nresult.X = (int)Math.Round( centerPoint.X + distance * Math.Cos( angle ) );	0
17312567	17312339	ASP.NET MVC 4 - multiple models in one view	public class BaseViewModel\n{\n    public LoginModel LoginModel { get; set; }\n}\n\npublic class ComplexViewModel : BaseViewModel\n{\n    public CartModel CartModel { get; set; }\n}	0
29030775	28979203	[Solved]How to compare values in two wpf datagrid values if already listed?	List<string> results = new List<string>();\nif (results.Contains(sid))\n{\n  System.Windows.Forms.MessageBox.Show("Study Already Listed");\n  return;\n}	0
23580937	23580912	How to call a button click event when i click another button in c#	private void MethodOne()\n{\n    progressBar1.Value = 0;\n    String[] a = textBox7.Text.Split('#');\n    progressBar1.Maximum = a.Length;\n    for (var i = 0; i <= a.GetUpperBound(0); i++)\n    {\n        ansh.Close();\n        progressBar1.Value++;\n    }\n}\n\nprivate void MethodTwo()\n{\n    foreach (string item in listBox2.Items)\n        textBox7.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    MethodTwo();\n    MethodOne();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    MethodTwo();\n}	0
3877043	3877026	How to create an Array or ArrayList of objects in C#?	MyClass[] instances = new MyClass[3];\n\nfor (int i = 0; i < instances.Length; i++)\n   instances[i] = new MyClass();	0
11481922	11476876	Call ReSharper ContextAction from Action	var document = context.GetData(DocumentModel.DataConstants.DOCUMENT);\n  var solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);\n  var psiModule = document.GetPsiSourceFile(solution).GetPsiModule();	0
8530774	8530596	DataGridView combobox cell event in c#	private void grvList_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n        {\n             if (grvList.Columns[grvList.CurrentCell.ColumnIndex].Name.Equals("routing_ID"))\n                {\n                    ComboBox cmbprocess = e.Control as ComboBox;\n                    cmbprocess.SelectedIndexChanged += new EventHandler(grvcmbProcess_SelectedIndexChanged);\n                }\n        }\n\n\n private void grvcmbProcess_SelectedIndexChanged(object sender, EventArgs e)\n        {\n            ComboBox cmbprocess = (ComboBox)sender;\n            if (cmbprocess.SelectedValue != null)\n            {\n               /// Your Code goes here\n            }\n\n        }	0
28485362	28476487	Retrieve specific number of rows in a SQL Server query	with \ndata\nas\n(\nselect *, row_number() over(order by id) as row\nfrom test_data\n  )\n,\npairs\nas\n(\nselect * ,\ncase when row%2=0 then row-1 else row end  as row_group\nfrom data\n )\n\nselect id, name, row_group\nfrom pairs\norder by row_group	0
29719001	29718939	how do i create and insert a node inside another node	NodeItem.AppendChild(NodeNewItem);	0
25726194	25726057	Unable to add Style to last item of Repeater	protected void rptFinalScore_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{             \n        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n        {\n            var Score = e.Item.FindControl("rpt_Score") as Label;\n            var ProgBar = e.Item.FindControl("rpt_proBar") as HtmlGenericControl;\n            string BuildingScore = ((Label)Score).Text;\n            ProgBar.Attributes.Add("style", string.Format("width:{0}%;", BuildingScore));           \n        }\n}	0
6418400	6418311	Overwrite specific XML attributes	var x = @"<outer>\n  <inner>\n    <nodex attr=""value1"">text</nodex>\n    <nodex attr=""value2"">text</nodex>\n  </inner>\n</outer>";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(x);\n\nforeach (XmlNode n in doc.SelectNodes("//nodex"))\n{\n    n.Attributes["attr"].Value = "new" + n.Attributes["attr"].Value.ToString();\n}\n\ndoc.OuterXml.Dump();	0
12921914	12920382	Zipping contents of a list file using DotNetZip library	while ((read = file.ReadLine()) != null)                  \n {              \n   if (read.Contains("*"))                        \n   {\n       zip.AddSelectedFiles(read, true);    \n   }\n   else\n   {\n       zip.AddFile(read);\n   }\n }\n zip.Save("c:\\update.zip");	0
12610073	12610053	List box update with focus on the last line in the listbox	listBoxPacketsSnifferTab.SelectedIndex = listBoxPacketsSnifferTab.Items.Count - 1;	0
5698736	5698696	How to Databind a DataGridView?	List<IncuranceLabel> items = new List<IncuranceLabel>();\nitems.add(oInsurance);\ngrdInsurance.DataSource = items;\ngrdInsurance.Databind();	0
6273285	6273234	How to get the character location of a XmlElement?	var document = XDocument.Load(fileName, LoadOptions.SetLineInfo);\nvar element = document.Descendants("nodeName").FirstOrDefault();\nvar xmlLineInfo = (IXmlLineInfo)element;\nConsole.WriteLine("Line: {0}, Position: {1}", xmlLineInfo.LineNumber, xmlLineInfo.LinePosition);	0
1850405	1786531	C#: Library for editing photo tags, et cetera, compatible with Live Photo Gallery	JpgPhoto photo = new JpgPhoto(@"c:\temp\file.jpg");\n  photo.ReadMetadata();\n\n  photo.Metadata.RegionInfo.Regions.Clear();\n\n  XmpRegion xmp = new XmpRegion();\n  xmp.PersonDisplayName = "esac";\n  xmp.RectangleString = "0.11, 0.25, 0.37, 0.49";\n\n  photo.Metadata.RegionInfo.Regions.Add(xmp);\n  photo.WriteMetadata();	0
23882523	23882370	Regex to extract Date Part from a string	(?:.*)(\d{4}-\d{2}-\d{2})(?:.*)	0
4149412	4149374	Iterating through collection items and checking each property for a valid value	Employees.Where(e => string.IsNullOrEmpty(e.FirstName) || string.IsNullOrEmpty(e.LastName))	0
29040398	29040188	How can I use Dapper with a SELECT stored procedure containing an INNER JOIN between two tables?	SELECT\n            F.Id,\n            F.Title,\n            F.Genre,\n--Rating object starts here\n            R.Id,\n            R.Name\n        FROM\n            dbo.Films as F\n        INNER JOIN\n            dbo.Ratings as R\n        ON\n            F.RatingId = R.Id;	0
2280399	2280327	One word bold inside a text in winform control	private void ListBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)\n{\n  // Draw the background of the ListBox control for each item.\n  e.DrawBackground();\n  // Define the default color of the brush as black.\n  Brush myBrush = Brushes.Black;\n\n  // Determine the color of the brush to draw each item based \n  // on the index of the item to draw.\n  switch (e.Index)\n  {\n      case 0:\n          myBrush = Brushes.Red;\n          break;\n      case 1:\n          myBrush = Brushes.Orange;\n          break;\n      case 2:\n          myBrush = Brushes.Purple;\n          break;\n  }\n\n  // Draw the current item text based on the current Font \n  // and the custom brush settings.\n  e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), \n    e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);\n  // If the ListBox has focus, draw a focus rectangle around the selected item.\n  e.DrawFocusRectangle();\n }	0
5269615	5261434	list of all friends C# Facebook SDK v5	var auth = new CanvasAuthorizer { Perms = "user_about_me,friends_about_me" };\n\n    if (auth.Authorize())\n    {\n        var fb = new FacebookClient(auth.Session.AccessToken);\n        dynamic myInfo = fb.Get("/me/friends");\n        foreach (dynamic friend in myInfo.data  )\n        {\n            Response.Write("Name: " + friend.name + "<br/>Facebook id: " + friend.id + "<br/><br/>");\n        }\n    }	0
7867306	7866607	Linq, lambda expression	book = db.Books.Single(b => b.BookId == book.BookId);\n var bookCopies = db.BookCopies.Where(c => c.BookId == book.BookId).ToList();\n\n foreach (BookCopy c in bookCopies)\n {\n     db.BookCopies.DeleteObject(c);\n }\n\n var authors = db.Authors.Include("Books").Where(author => author.Books.Any(b => b.BookId == book.BookId)).ToList();\n\n foreach (Author a in authors)\n {\n     a.Books.Remove(book);\n }\n\n db.DeleteObject(book);\n db.SaveChanges();	0
16523081	16522903	MonoDroid GetSpans last parameter	Java.Lang.Class.FromType(typeof(StyleSpan))	0
2006559	2006481	RadGrids, DetailTables, and Grouping	theGridDataItemItem.CanExpand = false;	0
10455370	10455343	How to access Default en-US culture, not as defined on a specific system?	this.Add(new WPermission() {\n    WRegion = Convert.ToInt32(details[0], CultureInfo.InvariantCulture),\n    StartDate = Convert.ToDateTime(details[1], CultureInfo.InvariantCulture),\n    EndDate = Convert.ToDateTime(details[2], CultureInfo.InvariantCulture)\n});	0
29694515	29694202	adding PictureBox array into Controls	Label[] l = new Label[15];\nPictureBox[] pic1 = new PictureBox[15];\nint y_value = 47;\n\nfor (int i = 0; i < 6; ++i)\n{\n\n    l[i] = new Label\n    {\n        Text = "Test Text",\n        Font = new System.Drawing.Font("Calibri", 8, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte) (128))),\n        ForeColor = System.Drawing.Color.White,\n        BackColor = System.Drawing.Color.FromArgb(1, 0, 64),\n        Size = new System.Drawing.Size(145, 20),\n        Location = new Point(30, y_value),\n        Anchor = AnchorStyles.Left,\n        Visible = true\n    };\n\n    pic1[i] = new PictureBox\n    {\n        Size = new System.Drawing.Size(400, 20),\n        Location = new Point(2, y_value - 10),\n        Anchor = AnchorStyles.Left,\n        Visible = true,\n        BackColor = Color.FromArgb(y_value/2, 0, 0)\n    };\n\n    y_value += 37;\n}\n\nthis.Controls.AddRange(l);\nthis.Controls.AddRange(pic1);	0
3725448	3725294	Set WCF ClientCredentials in App.config	svc.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings("...")	0
34247072	34246976	How do you assign a storage file to a ByteArray?	private async void Button_Click_2(object sender, RoutedEventArgs e)\n{\n    var picker = new FileOpenPicker();\n    picker.ViewMode = PickerViewMode.Thumbnail;\n    picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\n    picker.FileTypeFilter.Add(".jpeg");\n    picker.FileTypeFilter.Add(".jpg");\n    picker.FileTypeFilter.Add(".png");\n    var file = await picker.PickSingleFileAsync();\n    if (file != null)\n    {\n        var stream = await file.OpenStreamForReadAsync();\n        var bytes = new byte[(int)stream.Length];\n        stream.Read(bytes, 0, (int)stream.Length);\n    }\n}	0
9713516	9713457	Parsing XML Out of the Middle of a String	string result = Regex.Replace(htmlText, @"<(.|\n)*?>", string.Empty);	0
17052066	17051301	Finding Elements in Linq to XML	members.Where(x=> x.Element("AccountName").Value==validationName).Select(x=> x.Element("AccountNumber").Value).FirstOrDefault();	0
7741917	7728444	Programmatically change the Windows Shell	public void embedSoftware()\n{\n    try\n    {\n        // Disable Task Manager\n        regKey = Registry.CurrentUser.OpenSubKey(subKey, true).CreateSubKey("System");\n        regKey.SetValue("DisableTaskMgr", 1);\n        regKey.Close();\n        // Change the Local Machine shell executable\n        regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true);\n        regKey.SetValue("Shell", shell, RegistryValueKind.String);\n        regKey.Close();\n        // Create the Shell executable Registry entry for Current User\n        regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Winlogon", true);\n        regKey.SetValue("Shell", shell);\n        regKey.Close();\n        MessageBox.Show("Embedding Complete");\n\n    }\n    catch (Exception e)\n    {\n        MessageBox.Show(e.Message);\n    }\n}	0
9922366	9921902	XML Deserialization with RestSharp in Windows Phone 7	response.Data	0
20596721	20596650	How to remove all numbers, but keep the ordinals?	string result = Regex.Replace(input, @"\d+(?!\d|th|st|rd|nd)", "");	0
11576232	11576180	Get all <li> elements from inside a certain <div> with C#	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(yourHtml);\n\nif ( doc.DocumentNode != null )\n{\n   var divs = doc.DocumentNode\n                 .SelectNodes("//div")\n                 .Where(e => e.Descendants().Any(e => e.Name == "h4"));\n\n   // You now have all of the divs with an 'h4' inside of it.\n\n   // The rest of the element structure, if constant needs to be examined to get\n   // the rest of the content you're after.\n}	0
9708355	9708266	Assign values from one list to another using LINQ	Dictionary<int, string> map = = sourceList.ToDictionary(x => x.Id, x => x.Name);\n\nforeach (var item in destinationList)\n    if (map.ContainsKey(item.Id))\n        item.Name = map[item.Id];\n\ndestinationList.RemoveAll(x=> x.Name == null);	0
16367035	16366795	How to calculate the size of scroll bar thumb?	var arrowHeight = 25;\nvar viewportHeight = 200;\nvar contentHeight = 600;\n\nvar viewableRatio = viewportHeight / contentHeight; // 1/3 or 0.333333333n\n\nvar scrollBarArea = viewportHeight - arrowHeight * 2; // 150px\n\nvar thumbHeight = scrollBarArea * viewableRatio; // 50px	0
2868160	2866463	List replies in a winform	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        webBrowser1.DocumentText = "<html><body><textarea rows='15' cols='92' name='post-text' id='wmd-input'></textarea></body></html>";\n        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);\n        button1.Click += button1_Click;\n    }\n\n    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n        mshtml.IHTMLDocument2 doc = webBrowser1.ActiveXInstance as mshtml.IHTMLDocument2;\n        doc.designMode = "On";\n    }\n\n    private void button1_Click(object sender, EventArgs e) {\n        var html = webBrowser1.Document.Body.All["post-text"].InnerHtml;\n        // do something with that\n        //...\n    }\n}	0
30645963	30644451	Test my json data parser should return a logger	[Theory]\n[InlineData("MyFileLogger")]\n[InlineData("MyDbLogger")]\n[InlineData("MyDbLogger2")]\n[InlineData("MyConsoleLogger")]\n[InlineData("MyNullLogger")]\n[InlineData("MyMultiplexingLogger")]\n[InlineData("MyFailoverLogger")]\npublic void JSONConfigurationFileParser_Should_Return_A_Logger_Given_A_Name(string expectedLoggerName)\n    {\n        // ARRANGE\n        var currentFilePath = Environment.CurrentDirectory + @"\MyCompanyConfiguration.json";\n        var jsonString = File.ReadAllText(currentFilePath);\n        var jsonConfigurationFileParser = new JSONConfigurationFileParser(jsonString);\n\n        // ACT\n        var actualLoggers = jsonConfigurationFileParser.DeserializeLogger();\n\n        // ASSERT\n        Assert.True(actualLoggers.Any(x=> x.Name == expectedLoggerName));\n    }	0
14991876	14991688	adding items to a list in a dictionary	for (int index = 0; index < 5; index++)\n    {\n        if (testList.ContainsKey(key[index]))\n        {\n            testList[k].Add(val[index]);\n        }\n        else\n        {\n            testList.Add(key[index], new List<long>{val[index]});\n        }\n    }	0
4369665	4369629	Help needed with random code generator	var number_of_chars = 4;\nvar chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; \nvar random = new Random(); \nvar result = new string( \n    Enumerable.Repeat(chars, number_of_chars) \n              .Select(s => s[random.Next(s.Length)]) \n              .ToArray());	0
9728298	9728235	C# How do I determine childnode level in xml	void DeleteNodes(XmlNode root, string deleteName)\n{\n  foreach(XmlNode node in root.ChildNodes)\n  {\n    if (node.Name == deleteName)\n    {\n      root.RemoveChild(node);\n    }\n    else\n    {\n      DeleteNodes(node,deleteName);\n    }\n  }\n}	0
5193780	5191315	asp.net use membership provider to set role	public override string[] GetRolesForUser(string username)	0
21605650	21599977	Store font of button in the constructor	public override Font Font\n    {\n        get\n        {\n            return base.Font;\n        }\n        set\n        {\n            if(_storedFont == null)\n                 _storedFont = Font;\n\n            base.Font = value;\n        }\n    }	0
10133472	10133456	Parsing an HREF from an HTML string using a regular expression	Regex re = new Regex(@"http://nppes\.viva-it\.com/.+\.zip");\n\nre.Match(html).Value // To get the matched URL	0
25686006	25685932	Insert date from view to controller	yourdataentity newentity = new yourdataentity();\n\n //the rest of your implementation may be a bit different, but this is one way to set the date for a new record...\n newentity.createDate = DateTime.Now;\n\n yourentitys.Add(newentity);\n\n if (ModelState.IsValid)\n {\n      db.yourentitys.Add(newentity);\n      db.SaveChanges();\n }	0
17274862	17274717	Effectively detect if a file is being used by an application	Process[] pname = Process.GetProcessesByName("notepad");\n if (pname.Length == 0)\n    MessageBox.Show("nothing");\n else\n    MessageBox.Show("run");	0
18017335	18016816	In C# find the average of displayed value in a textbox that keeps changing its floating value for GPS nav program	...\ndouble reduce_accuracy = 1;\n\nwhile (compassBearing > heading + reduce_accuracy)//compassBearing is current heading, heading is needed\n{\n     Serialport.Write("l"); //turn left Motorcontroller is designed to keep going in a direction till another order is recieved\n    return;\n }\nwhile (compassBearing < heading - reduce_accuracy)\n{\n     Serialport.Write("r");//turn right\n     return;\n}\n...	0
97397	97391	How to get the underlying value of an enum	string value = (string)TransactionTypeCode.Shipment;	0
18202303	18184564	How to update Linq result with in the list, without assign other data table process itself get another one result	dim L1 = (From cm in commontables select cm)\nL1.Where(Function(T) T.Address is nothing).ToList()\nFor i =0 to L1.count-1 step 1\n   L1(i).Address="Address1"\nNext	0
23556578	23556481	How to pass 2 generics types into an extension method	public static T Map<TEntity,T>(this TEntity entity) where TEntity : IEntity\n{\n    return Mapper.Map<TEntity, T>(entity);        \n}\n\npublic static T Map<T>(this ExchangeSet set)\n{\n    // ...\n}	0
7974603	7966493	How to get reference from low level class attribute to some top level attributes within the same class in C#?	public interface ISpecificAttributeProvider\n{\n   object GetSpecificAttribute();\n}\n\npublic class ThirdLevel : SecondLevel, ISpecificAttributeProvider\n{\n   private object _attributeInQuestion;\n\n   public object GetSpecificAttribute()\n   {\n      return _attributeInQuestion;\n   }\n}\n\npublic class TenthLevel: NinthLevel\n{      \n   public void Method()\n   {\n      if (this is ISpecificAttributeProvider)\n         object attribute = GetSpecificAttribute();\n   }\n}	0
7996860	7983173	Recognize a valid youtube url via unobtrusive validation regular expression is not working in MVC 3	(https?://(www\.)?youtube\.com/.*v=\w+.*)|(https?://youtu\.be/\w+.*)|(.*src=.https?://(www\.)?youtube\.com/v/\w+.*)|(.*src=.https?://(www\.)?youtube\.com/embed/\w+.*)	0
3648371	3643754	Efficient Array Normalization of Approximate Values	var a = target1 > words[i] ? target1 - words[i] : words[i] - target1;\nvar b = target2 > words[i] ? target2 - words[i] : words[i] - target2;\n(OR)\nvar as = target1 - words[i];\nvar bs = target2 - words[i];\na = as + (as >> 31) ^ (as >> 31);\nb = bs + (bs >> 31) ^ (bs >> 31);\n\nif (a < b)\n   normalized[i] = target1;\nelse\n   normalized[i] = target2;	0
11218189	11216625	How to resolve a hostname to an IP address in Metro/WinRT?	using Windows.Networking;\nusing Windows.Networking.Sockets;\n\nHostName serverHost = new HostName("www.google.com");\nStreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket();\n\n// Try to connect to the remote host\nawait clientSocket.ConnectAsync(serverHost, "http");\n\n// Now try the clientSocket.Information property\n// e.g. clientSocket.Information.RemoteAddress\n// to get the ip address	0
822234	822155	Is there a better way than String.Replace to remove backspaces from a string?	public string ReplaceBackspace(string hasBackspace)\n{\n    if( string.IsNullOrEmpty(hasBackspace) )\n        return hasBackspace;\n\n    StringBuilder result = new StringBuilder(hasBackspace.Length);\n    foreach (char c in hasBackspace)\n    {\n        if (c == '\b')\n        {\n            if (result.Length > 0)\n                result.Length--;\n        }\n        else\n        {\n            result.Append(c);\n        }\n    }\n    return result.ToString();\n}	0
23954522	23954316	MVC 5 Model properties null but database contains value	public ActionResult Index()\n{\n    return View(db.Inventorys.Include(b => b.Unit_ID).ToList() );\n}	0
17187732	17187561	how to write a query to get distinct studentid	var ids = context.Students.Where(s => s.CreationDate.Month == 1 && s.CreationDate.Year == 2013).Select(s => s.Id).Distinct().ToList();	0
7221006	7220875	How to: sum all values and assign a percentage of the total in Linq to sql	var results = from n in db.Nominees\n              join v in db.Votes on n.VoteID equals v.VoteID\n              select new\n              {\n                  Name = n.Name,\n                  VoteCount = v.VoteCount,\n                  NomineeID = n.NomineeID,\n                  VoteID = v.VoteID\n              };\n\nvar sum = (decimal)results.Select(r=>r.VoteCount).Sum();\nvar resultsWithPercentage = results.Select(r=>new {\n                               Name = r.Name,\n                               VoteCount = r.VoteCount,\n                               NomineeID = r.NomineeID,\n                               VoteID = r.VoteID,\n                               Percentage = sum != 0 ? (r.VoteCount / sum) * 100 : 0\n                            });	0
30207599	30207503	How to return plain/text robots.txt in AngularJS	return Content("whatever you want", "text/plain");	0
3536501	3536465	Debugging a Deadlock with Windbg's !clrstack command	~*e!clrstack	0
1368290	1367496	How can I get the accessible name using win32 from c#?	STDAPI AccessibleObjectFromWindow(\n  __in   HWND hwnd,\n  __in   DWORD dwObjectID,\n  __in   REFIID riid,\n  __out  void **ppvObject\n);	0
5113478	5113453	noob WPF data binding - why isn't my DataGrid autogenerating columns?	dataGrid1.DataContext= new ObservableCollection<Foo>(Data.Foos); \n    dataGrid2.DataContext= new ObservableCollection<Foo>(Data.Foos);	0
4683040	4682827	C#: How to translate the Yield Keyword	class PowerEnumerator : IEnumerator<int>\n{\n  private int _number;\n  private int _exponent;\n  private int _current = 1;\n\n  public PowerEnumerator(int number, int exponent)\n  {\n    _number = number;\n    _exponent = exponent;\n  }\n\n  public bool MoveNext()\n  {\n    _current *= number;\n    return _exponent-- > 0;\n  }\n\n  public int Current\n  {\n    get\n    {\n      if (_exponent < 0) throw new InvalidOperationException();\n      return _current;\n    }\n  }\n}	0
22149801	22149419	Trouble using DataContractSerializer	[DataContract]\npublic class AuthTokenContract\n{\n    [DataMember(Name = "result")]\n    public Result result { get; set; }\n\n    [DataMember(Name = "warnings")]\n    public string[] Warnings { get; set; }\n}\n\n[DataContract]\npublic class Result\n{\n    [DataMember(Name = "token")]\n    public string Token { get; set; }\n}	0
30524647	30509194	Cortana VCD: set command's Navigate target to a Page in a subfolder	protected override void OnActivated(IActivatedEventArgs args)\n{\n    if (args.Kind == ActivationKind.VoiceCommand)\n    {\n        Frame rootFrame = Window.Current.Content as Frame;\n        VoiceCommandActivatedEventArgs vcArgs = (VoiceCommandActivatedEventArgs)args;\n\n        //check for the command name that launched the app\n        string voiceCommandName = vcArgs.Result.RulePath.FirstOrDefault();\n\n        switch (voiceCommandName)\n        {\n            case "ViewEntry":\n                rootFrame.Navigate(typeof(ViewDiaryEntry), vcArgs.Result.Text);\n                break;\n            case "AddEntry":\n            case "EagerEntry":\n                rootFrame.Navigate(typeof(AddDiaryEntry), vcArgs.Result.Text);\n                break;\n        }\n    }\n}	0
30650020	25268299	MVC Modal Validation ErrorMessage for Decimal DataType with Globalization	[Display(Name = "TdPrime", ResourceType = typeof(Resources.Somethings.Something))]       \n[RegularExpression(@"-?(?:\d*[\,\.])?\d+", \n                ErrorMessageResourceName = "DataType_Number", \n                ErrorMessageResourceType = typeof(Validations))]       \n[Range(0, 999.9999, \n          ErrorMessageResourceName = "RangeAttribute_ValidationError",\n          ErrorMessageResourceType = typeof(Validations))]\n[DisplayFormat(DataFormatString = "{0:#.####}", ApplyFormatInEditMode = true)]\npublic decimal? TdPrime { get; set; }	0
34059552	34001294	How to create result for different shared parameters in TFS using API	TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://servername:8080/tfs/DefaultCollection"));\n        ITestManagementTeamProject project = tfs.GetService<ITestManagementService>().GetTeamProject("teamproject");\n\n        ITestCase testcase24 = project.TestCases.Find(24); //24 is the test case id\n\n        foreach (System.Data.DataTable dataTable in testcase24.Data.Tables)\n        {\n            string header = "";\n            foreach (System.Data.DataColumn colume in dataTable.Columns)\n            {\n                header += colume.ColumnName + "\t";\n            }\n            Console.WriteLine(header);\n            foreach (System.Data.DataRow row in dataTable.Rows)\n            {\n                string rowValue = "";\n                foreach (object o in row.ItemArray)\n                {\n\n                    rowValue += o.ToString() + "\t";\n                }\n                Console.WriteLine(rowValue);\n            }\n        }	0
20259129	20070504	How to Display data in textblock after JSON Parsing	this.txt1.DataContext= root1.loginresponse.Accounts.Account;	0
4829390	4829366	Byte to Binary String C# - Display all 8 digits	Convert.ToString(MyVeryOwnByte, 2).PadLeft(8, '0');	0
21599466	21599154	How to get the text from current cell in datagridview textchanged event?	void tb_TextChanged(object sender, EventArgs e)\n{\n    var enteredText = (sender as TextBox).Text\n    ...\n}	0
2144317	2143091	Port Windows CE app to Windows Mobile	using Microsoft.WindowsCE.Forms;\n\nif (SystemSettings.Platform == WinCEPlatform.WinCEGeneric)\n  this.WindowState = FormWindowState.Maximized;\nelse\n  this.WindowState = FormWindowState.Normal; // Pocket PC or Smartphone	0
5261570	5261142	Refreshing text box from a bindingsource from an SQL query	BindingSource _bs;\n\n\nprivate void Form1_Load(object sender, System.EventArgs e) {\n    //  Creamos el objeto BindingSource\n    _bs = new BindingSource();\n    //  Establecemos la conexi?n para recuperar los datos\n    //  de los Clientes.\n    // \n    SqlConnection cnn = new SqlConnection("Data Source=(local);");\n    string sql = "SELECT * FROM Clientes";\n    SqlDataAdapter da = new SqlDataAdapter(sql, cnn);\n    DataSet ds = new DataSet();\n    //  Rellenamos el objeto DataSet\n    da.Fill(ds, "Clientes");\n    //  Le asignamos el origen de datos al objeto BindingSource\n    // \n    _bs.DataSource = ds;\n    //  Objeto DataSet\n    _bs.DataMember = "Clientes";\n    TextBox1.DataBindings.Add("Text", _bs, "IdCliente");\n    TextBox2.DataBindings.Add("Text", _bs, "Nombre");\n    //  Enlazamos el control BindingNavigator\n    // \n    BindingNavigator1.BindingSource = _bs;\n}	0
7094946	7063394	Clicking Confirm Dialog Selenium in .NET	driver.SwitchTo().Alert().Accept();	0
9536299	9536256	Using an absolute path in probing privatePath	app.config	0
3430465	3430425	Request for Comments: fast hashed base class for dictonary keys	public class ObjectWithCachedHashCode : IEquatable<ObjectWithCachedHashCode>\n    {\n        private int _cachedHashCode;\n\n        public object Object { get; private set; }\n\n        public ObjectWithCachedHashCode(object obj)\n        {\n            Object = obj;\n            _cachedHashCode = obj.GetHashCode();\n        }\n\n        public override int GetHashCode()\n        {\n            return _cachedHashCode;\n        }\n\n        public bool Equals(ObjectWithCachedHashCode other)\n        {\n            return other!=null && Object.Equals(other.Object);\n        }\n\n        public override bool Equals(object other)\n        {\n            return Equals(other as ObjectWithCachedHashCode);\n        }\n\n\n    }	0
27703189	27703091	WPF add html string to HTML file and save it	using (FileStream fs = new FileStream("document.html", FileMode.Create)) \n{ \n    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) \n    { \n        sw.WriteLine("<h2><u>TEST</u></h2><div style='margin:0 auto;'>"); \n    } \n}	0
13400354	13400264	Terminating duplicate processes with C#	Process process = Process.GetCurrentProcess();\nvar dupl = (Process.GetProcessesByName(process.ProcessName));\nif( dupl.Length > 1 && MessageBox.Show("Kill?", "Kill duplicates?", MessageBoxButtons.YesNo) == DialogResult.Yes ) {\n    foreach( var p in dupl ) {\n        if( p.Id != process.Id )\n            p.Kill();\n    }\n}	0
19010164	19010069	Check/Uncheck All items in CheckBoxList in ASP.NET	protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string result = Request.Form["__EVENTTARGET"];\n    int index1 = int.Parse(result.Substring(result.IndexOf("$") + 1));\n    if (index1 == 0)\n    {\n        bool tf = CheckBoxList1.Items[index1].Selected ? true : false;\n        CheckUncheckAll(tf);\n    }\n}\nvoid CheckUncheckAll(bool tf)\n{\n    foreach (ListItem item in CheckBoxList1.Items)\n    {\n        item.Selected = tf;\n    }\n}	0
8060772	8060651	issue related to autopostback in DropDownList	if(Page.IsPostBack == false) //page is loading first time\n{\n    //you can do your coding here.\n}	0
9622620	9621736	How to convert PropertyInfo to property expression and use it to invoke generic method?	var parameter = Expression.Parameter(entityType, "entity");\n  var property = Expression.Property(parameter, propertyInfo);\n  var funcType = typeof(Func<,>).MakeGenericType(entityType, propertyInfo.PropertyType);\n  var lambda = Expression.Lambda(funcType, property, parameter);\n\n  structureConfiguration.GetType()\n   .GetMethod("Ignore")\n   .MakeGenericMethod(propertyInfo.PropertyType)\n   .Invoke(structureConfiguration, new[]{lambda});	0
6918590	6917205	How to display a message everytime a single cell is selected in a datagridview. Problem: I have four datagrideviews	public Form1()\n { \n      dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(populateTextBox());\n      dataGridView2.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(populateTextBox());\n      dataGridView3.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(populateTextBox());\n      dataGridView4.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(populateTextBox());\n }\n\nprivate void populateTextBox(object sender, DataGridViewCellEventArgs e)\n{\n    //code here\n    //You can use e.Value (cell value data type dependant) if required\n}	0
14269170	14268886	How can I cange how a Property is diplayed in a GridDataViewer	public string EnumString {\n  get { \n    FilterClass fClass = this.FilterClass;\n    return fClasss.ToString();\n  }\n}	0
1891783	1891767	How can I pass a multi dimensional array as an argument to a worker thread in C#?	class Test\n{\n    static void Main() \n    {\n        Work threadWork = new Work(yourdata);\n        Thread newThread = \n            new Thread(new ThreadStart(threadWork.DoWork));\n        newThread.Start();\n    }\n}\n\nclass Work \n{\n    private double[,] myData;\n    public Work(double[,] data) {\n        myData = data;\n    }\n\n    public void DoWork() { /* use myData */ }\n}	0
19623429	19623206	How to create basic tray icon app?	static class Program\n    {       \n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new TrayApplicationContext());\n        }\n    }\n\n    public class TrayApplicationContext : ApplicationContext\n    {\n        private readonly NotifyIcon _trayIcon;\n        public TrayApplicationContext()\n        {\n            _trayIcon = new NotifyIcon\n                            {\n                                //it is very important to set an icon, otherwise  you won't see your tray Icon.\n                                Icon = Resources.AppIcon,                                \n                                Visible = true\n                            };\n        }        \n    }	0
28191327	28191177	Process.Start opens link instead of folder	Process.Start("explorer.exe", @"C:\users\user1\theFolder\example");	0
14515944	14515841	ASP.NET Custom Server Control not disabled inside a Panel that is disabled	output.AddAttribute(HtmlTextWriterAttribute.Type, "text");\nif (!this.IsEnabled)\n{\n    output.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");\n}\noutput.AddAttribute(HtmlTextWriterAttribute.Value, this.DisplayName);\noutput.RenderBeginTag(HtmlTextWriterTag.Input);\noutput.RenderEndTag();	0
31780420	31470342	DataGridView SortableBindingList for decimal numbers as strings	decimal value;\nif (direction == ListSortDirection.Ascending)\n{\n    // check if element count is not 0 and value is decimal\n    if (query.Count() > 0 &&\n        decimal.TryParse(prop.GetValue(query.ElementAt<T>(0)).ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out value))\n    {\n        // convert to decimal and sort\n        query = query.OrderBy(i => Convert.ToDecimal(prop.GetValue(i)));\n    }\n    else query = query.OrderBy(i => prop.GetValue(i));\n}\nelse\n{\n    if (query.Count() > 0 &&\n        decimal.TryParse(prop.GetValue(query.ElementAt<T>(0)).ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out value))\n    {\n        query = query.OrderByDescending(i => Convert.ToDecimal(prop.GetValue(i)));\n    }\n    else query = query.OrderByDescending(i => prop.GetValue(i));\n}	0
23543210	23543054	Customize Handler context to Class name only	protected void Application_Start(object sender, EventArgs e)\n{\n  RouteTable.Routes.MapHttpHandlerRoute("RoutName", "SimpleHandler", "~/Your handler.ashx");\n}	0
24322987	24322893	Parsing a file best Approach	string originalXml;\n......\n......\n\nstring fixedXml = "<root>" + originalXml + "</root>";\nXDocument doc = XDocument.Parse(fixedXml);	0
4590364	4590310	Is there a difference in the order of equality?	bool foo = (yourVector3 == 5);    // requires the first version\nbool bar = (5 == yourVector3);    // requires the second version	0
11780609	11780293	StructureMap to Ninject conversion	Bind<ISession>().ToMethod(ctx => {\n    var uow = (INHibernateUnitOfWork)ctx.Kernel.Get<IUnitOfWork>();\n    return uow.Session;\n});	0
5905801	5905761	Can there be any difference between Clean+Rebuild and Clean+Build	Rebuild = Clean + Build	0
32936301	32919810	Send Auto messages from whatsapp	WhatsApp wa = new WhatsApp("your number", "your password", "pankaj", false, false);\nwa.OnConnectSuccess += () =>\n{\n    Response.Write("connect");\n    wa.OnLoginSuccess += (phno,data) =>\n    {\n        wa.SendMessage("to", "msg");\n    };\n\n    wa.OnLoginFailed += (data) =>\n    {\n        Response.Write("login failed"+data);\n    };\n    wa.Login();\n};\nwa.OnConnectFailed+= (ex)=>\n{\n    Response.Write("connection failed");\n}	0
22912631	22912571	Add to dictionary some params from request	var dictionary =  new Dictionary<string, string>();\nforeach (var key in Request.Params.AllKeys)\n{ \n     if (key.ToString().Contains("txt"))\n     {\n          //get the text after "txt"\n          var index = Request.Params[key].LastIndexOf("txt");\n          var val = Request.Params[key].SubString(index);\n          Dictionary.Add(key, val);\n     }\n}	0
7655073	7655001	How do I print vertical text in C# that prints up? (StringFormat.DirectionVirtical prints down)	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n    }\n    protected override void OnPaint(PaintEventArgs e) {\n        string text = "Vertical text";\n        SizeF textSize = e.Graphics.MeasureString(text, this.Font);\n        e.Graphics.RotateTransform(-90);\n        e.Graphics.DrawString(text, this.Font, Brushes.Black,\n            new PointF(-textSize.Width, 0));\n    }\n}	0
5847921	5847675	How to find the underlying type in a C# generic class to be used in a generic function?	var type = p_variable.GetType().BaseType.GetGenericArguments()[0];	0
9440186	9440109	how to call my dll from windows service?	Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\<YOUR_SERVICE_NAME_HERE>", true);\nkey.SetValue("FailureActions", new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, Microsoft.Win32.RegistryValueKind.Binary);\nkey.Close();	0
24678685	24627782	Get print page count without printing the document	e.HasMorePages	0
12926357	12925921	convert multi level for loop into linq or lambda expression	var diff = entitiesLargerSet.Where(large => \n    !entitiesSmallerSet.Any(small => \n        small.Key.Equals(large.Key) \n        && small.StringResourceValues.Any(x => \n            x.Culture.Equals(defaultCulture) && x.Value.Length > 0))).ToList();	0
7378608	7378485	Correct way to set time of day to TimeSpan.MaxValue in C#	if (start != null) start = start.Value.Date;\n        if (end != null) end = start.Value.Date.AddDays(1).AddSeconds(-1);	0
16197604	16197115	Using Linq to return the count of items from a query along with its resultset	var result = (from n in mycollection \n              where n.someprop == "some value" \n              select n).ToList();\nvar count = result.Count;	0
3480577	3480550	Self Tracking Entity - Loading Navigation Property of a Navigation Property	EntityA entityA = ctx.EntityA.Include("EntityB.EntityC").Where(x => x.Id == id).SingleOrDefault();	0
16367400	16349960	Unit testing a static class with a private static field that is a common dependency	"TestDataOnly"	0
22974800	22974412	Change the text in the textbox, inside border at row m and column of a grid	for (int i=0; i< MyGrid.Children.Count; i++)\n{\nUIElement child = MyGrid.Children[i /*by the way it should be i?*/]; \n\n\n if ((Grid.GetRow(child) == m) && (Grid.GetColumn(child) == n))\n\n            {\n\n                 ((child as Border).Child as TextBox).Text = "some text";\n            }\n }	0
32465012	32464746	C# label color change	private void label1_TextChanged( object sender, EventArgs e )\n    {\n        if ( this._calories < 0 )\n        {\n            this.lb_Main.BackColor = Color.Red;\n        }\n        else\n        {\n            this.lb_Main.BackColor = Color.Green;\n        }\n    }	0
10043398	10043303	Refresh page repeat database transaction?	public bool IsRefreshed\n    {\n        get\n        {\n            if (Convert.ToString(Session["RefreshTimeStamp"]) == Convert.ToString(ViewState["RefreshTimeStamp"]))\n            {\n                Session["RefreshTimeStamp"] = HttpContext.Current.Server.UrlDecode(System.DateTime.Now.ToString());\n                return false;\n            }\n            else\n            {\n                return true;\n            }\n        }\n    }\n\n\n\n\nprotected override void OnPreRender(EventArgs e)\n    {\n        base.OnPreRender(e);\n        ViewState["RefreshTimeStamp"] = Session["RefreshTimeStamp"];\n    }\n\n\n\nprotected override void OnLoad(EventArgs e)\n    {  \n\n        if (!Page.IsPostBack)\n        {\n            Session["RefreshTimeStamp"] = HttpContext.Current.Server.UrlDecode(System.DateTime.Now.ToString());\n        }\n        base.OnLoad(e);\n    }	0
13648966	13648634	Need to divide a number before parsing it	decimal myValue = decimal.Parse(myString.Substring(0, myString.Length-7) \n                            + "." \n                            + myString.Substring(myString.Length-7, 7));	0
5074593	5074575	what is the best way in C# to convert string into int[]	int[] array = s.Split(',').Select(str => int.Parse(str)).ToArray();	0
2133075	2132791	Reflecting over all properties of an interface, including inherited ones?	GetProperties(BindingFlags bindingFlags)	0
34028369	34027912	Appending text from the file to an output,printing to file C#	using (StreamReader reader = File.OpenText(path1))\n{\n    using (StreamWriter writer = File.AppendText(path2))\n    {\n        writer.Write("User read " + param1 + " as: ");\n\n        while (!reader.EndOfStream)\n        {\n            string line = reader.ReadLine();\n\n            //Console.WriteLine(line); //Uncomment this line if you want to write the line to the console\n\n            writer.WriteLine(line);\n        }\n    }\n}	0
31489395	31486627	How to distribute a cost in a normal distribution	start = (start_year-0.5-median)/stddev;\nend = (end_year+0.5-median)/stddev;\ncost = total_cost*(Phi(end)-Phi(start));	0
3400967	3400950	c# how to print AssemblyFileVersion	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
3629630	3628926	A way to copy xml comments from a set of APIs to another similar set of APIs?	using Jolt;\nusing System.Xml.Linq;\n\nvoid CopyXmlDocComments(Assembly sourceAssembly)\n{\n    XDocument newDocComments = new XDocument();\n    XmlDocCommentReader reader = new XmlDocCommentReader(sourceAssembly);\n\n    foreach(Type t in sourceAssembly.GetTypes())  // implement type filter here\n    {\n        newDocComments.Add(reader.GetComments(t));\n    }\n\n    newDocComments.Save("newAssemblyName.dll.xml");\n}	0
22223626	22099607	creating a login controller in MVC project	db.SaveChanges()	0
24307485	24273551	Cannot export kendo grid data to Excel spreadsheet	ReportPhoneSupportResultTypedView results = new ReportPhoneSupportResultTypedView();\n    string[] userIds = model.UserId.Split(',');\n    foreach (string userId in userIds)\n    {\n        int iUserId = 0;\n        if (Int32.TryParse(userId, out iUserId))\n        {\n\n            RetrievalProcedures.FetchReportPhoneSupportResultTypedView(results, model.FromDate, model.ToDate, iUserId);\n        }\n    }\n\n\n    //Get the data representing the current grid state - page, sort and filter\n    IEnumerable ExcelResults = ((IEnumerable)results).ToDataSourceResult(request).Data;	0
16604461	16600196	How to store user input in a 2D array?	myDomainUpDown.OnChanged += new EventHandler(myDomainUpDown_OnChanged);\n\n     void OnChanged(object sender, EventArgs e) \n      {\n          //save all the information you need in whatever collection/file/db you want \n      }	0
910017	909981	Easy one? Access an object's property by using a variable in C#	var type = myVariable.GetType();\nvar property = type.GetProperty("name");\nproperty.SetValue(myVariable, 1, new object[] {});	0
6280183	6279599	Parse a full datetime string to DateTime type	dt.GetValue().getMonth() + '/' + dt.GetValue().getDate() + '/' + dt.GetValue().getFullYear()	0
821117	820900	How can I use Rhino Mocks to mock a MEF export?	protected override void Context()\n    {\n        MockCache = MockRepository.GenerateStub<ICache>();\n        var metadata = new Dictionary<string, object> ()\n        var cacheDefinition = new FakeInstanceExportDefinition(typeof(ICache), MockCache, metadata);\n        FakeProvider = new FakeExportProvider(f => ((FakeInstanceExportDefinition)f).Instance);\n        FakeProvider.AddExportDefinitions(cacheDefinition);\n        CacheExport = FakeProvider.GetExport<ICache>();\n    }	0
3912049	3912002	changing name with email when sending emails	message.From = new MailAddress("noreplay@domain.com", "Confirmation");	0
5155458	5155049	toolStripComboBox set font style?	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        ComboBox box = (ComboBox)toolStripComboBox1.Control;\n        box.DrawMode = DrawMode.OwnerDrawVariable;\n        box.MeasureItem += new MeasureItemEventHandler(box_MeasureItem);\n        box.DrawItem += new DrawItemEventHandler(box_DrawItem);\n    }\n\n    void box_DrawItem(object sender, DrawItemEventArgs e) {\n        // etc..\n    }\n\n    void box_MeasureItem(object sender, MeasureItemEventArgs e) {\n        // etc..\n\n    }\n}	0
2912507	2912476	Using C# to check if string contains a string in string array	string stringToCheck = "text1";\nstring[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };\nforeach (string x in stringArray)\n{\n    if (x.Contains(stringToCheck))\n    {\n        // Process...\n    }\n}	0
431857	431840	How to render decoded HTML in a (i.e. a <br>) in GridView cell	if (e.Row.RowType == DataControlRowType.DataRow)\n{\n  string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[0].Text);\n  e.Row.Cells[0].Text = decodedText;\n}	0
4862047	4862003	How to obtain a better approach in reading file?	byte[] GetPartialPackage(string filePath, long offset, int count)\n{\n    using (var reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))\n    {\n        reader.Seek(offset, SeekOrigin.Begin);\n        int avaliableCount = Math.Min(count, (int)(reader.Length - offset));\n        byte[] tempData = new byte[avaliableCount];\n        int num = reader.Read(tempData, 0, avaliableCount);\n        return tempData;\n    }\n}	0
5134969	5134955	how do i convert string numbers to int	string str_a = "a1bc2d23ghj2";\nstring str_digits_only = new String(str_a.Where(char.IsDigit).ToArray());\nint in_b = Convert.ToInt32(str_digits_only);	0
406674	405429	How can I overload a C# method by specific instances of a generic type	class Program\n{\n    static void Main(string[] args)\n    {\n        var testA = new Foo<A>();\n        testA.Method();\n        var testB = new Foo<B>();\n        testB.Method();\n        Console.ReadLine();\n        var testString = new Foo<string>(); //Fails\n        testString.Method(); \n        Console.ReadLine();\n    }\n}\n\nclass A { }\nclass B { }\nclass Bar\n{\n    public static void OverloadedMethod(Foo<A> a)\n    {\n        Console.WriteLine("A");\n    }\n    public static void OverloadedMethod(Foo<B> b)\n    {\n        Console.WriteLine("B");\n    }\n}\nclass Foo<T>\n{\n    static Foo()\n    {\n        overloaded = (Action<Foo<T>>)Delegate.CreateDelegate(typeof(Action<Foo<T>>), typeof(Bar).GetMethod("OverloadedMethod", new Type[] { typeof(Foo<T>) }));\n    }\n\n    public void Method()\n    {\n        overloaded(this);\n    }\n\n    private static readonly Action<Foo<T>> overloaded;\n}	0
18149263	18140012	SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column	//--- convert decimal values\nforeach (DataColumn DecCol in DecimalColumns)\n{\n     if(string.IsNullOrEmpty(dr[DecCol].ToString()))\n          dr[DecCol] = null; //--- this had to be set to null, not empty\n     else\n          dr[DecCol] = Helpers.CleanDecimal(dr[DecCol].ToString());\n}	0
6985548	6985411	How can I get tabs to print using this custom Printing class?	StringFormat format = new StringFormat(StringFormatFlags.LineLimit);\nfloat[] formatTabs = { 10.0f, 20.0f };\nformat.SetTabStops(0.0f, formatTabs);	0
23286737	23286685	Remove characters from a string C#	x = Regex.Replace(x, "^90*", "");	0
25940196	25940019	How to re request page on back button click in asp mvc	// disabling caching for all parent pages\n    protected override void OnInit( EventArgs e ) {\n        base.OnInit(e);\n        Response.Cache.SetCacheability(HttpCacheability.NoCache);\n        Response.AppendHeader("Cache-Control", "no-cache, no-store");\n        Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-1));\n    }	0
729532	729527	Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?	object o = new object();\nstring s = (string) o;\nint i = s.Length; // What can this sensibly do?	0
9114363	9114296	Can entity framework be used with a connection string given at runtime?	SqlConnection dbConn = new SqlConnection("your_connection_string");\nEntityConnection entityConnection = new EntityConnection(dbConn);\nvar yourEdmx = new DbModel(entityConnection);	0
9199110	9199080	How to get the integer value of day of week	day1 = (int)ClockInfoFromSystem.DayOfWeek;	0
5902394	5896209	solution for multiple inheritance - with opportunity to change protection lvl	public class PermissionDeniedException : Exception {}\n\nclass MainClass : IInterface_1, IInterface_2 {\n  public string field_1{set;get;}\n  private string field_2{set;get;}\n  string IInterface_1.field_2 {\n    get {throw new PermissionDeniedException();}\n    set {throw new PermissionDeniedException();}\n  }\n  public string field_3{set;get}\n  public string field_4{set;get}\n}	0
7928631	7918890	How to bind a custom control check box	private void BindControls()\n{\n    // Bind the values to from the controls in the group to the properties class\n\n    // When the line below is commented out the control behaves normally\n    this.checkedGroupBox1.DataBindings.Add("Checked", m_TP, "GroupChecked", false, DataSourceUpdateMode.OnPropertyChanged);\n    this.numericUpDown1.DataBindings.Add("Value", m_TP, "SomeNumber", false, DataSourceUpdateMode.OnPropertyChanged);\n    this.textBox1.DataBindings.Add("Text", m_TP, "SomeText", false, DataSourceUpdateMode.OnPropertyChanged);\n    this.checkBox1.DataBindings.Add("Checked", m_TP, "BoxChecked", false, DataSourceUpdateMode.OnPropertyChanged);\n\n    // Bind the values of the properties to the lables\n    this.label4.DataBindings.Add("Text", m_TP, "GroupChecked");\n    this.label5.DataBindings.Add("Text", m_TP, "SomeNumber");\n    this.label6.DataBindings.Add("Text", m_TP, "SomeText");\n    this.label8.DataBindings.Add("Text", m_TP, "BoxChecked");\n}	0
1265060	1263843	Modying Properties of a Class	def get_movement_speed():\n    value = base_movement_speed() # this is intrinsic to the unit\n    for effect in movement_speed_effects_list:\n        value = effect.modify(value)\n    return value	0
32314295	32314185	interChange-Framework - EMP default Datalist sort	//Set Default Sort by DescriptionParent\nstring sort = this.Datalist.GetSortExpression();\nif(string.IsNullOrEmpty(sort))\n   this.Datalist.SetSortExpression(SORT_EXPT_NAME, iC.WebUI.WebControls.DataList.SortOrder.ASC);	0
12048817	12048702	getting hour part and time-zone part from datetime	var date = DateTimeOffset.Parse("2012-08-10T22:00:00-08:00");\ndate.Offset // -08:00:00,  offset from Coordinated Universal Time (UTC)\ndate.DateTime // 10/08/2012 22:00:00,	0
9820790	9820765	Tricky if statement	if (value != DBNull.Value || !skipNullValues) dic.Add(columnName);	0
4485386	4458613	Console app utilizing Facebook offline_access extended permissions and Facebook C# SDK	public class FacebookOAuth\n{\n\n    public static IEnumerable<ExchangeSessionResult> ExchangeSessions(string appId, string appSecret, params string[] sessionKeys)\n    {\n        WebClient client = new WebClient();\n        var dict = new Dictionary<string, object>();\n        dict.Add("client_id", appId);\n        dict.Add("client_secret", appSecret);\n        dict.Add("sessions", String.Join(",", sessionKeys));\n        string data = dict.ToJsonQueryString();\n        string result = client.UploadString("https://graph.facebook.com/oauth/exchange_sessions", data);\n        return Newtonsoft.Json.JsonConvert.DeserializeObject<ExchangeSessionResult[]>(result);\n    }\n\n}\n\npublic class ExchangeSessionResult\n{\n\n    [Newtonsoft.Json.JsonProperty("access_token")]\n    public string AccessToken { get; set; }\n\n    [Newtonsoft.Json.JsonProperty("expires")]\n    public string Expires { get; set; }\n\n}	0
21948259	21947135	iOS Push Notifications AuthenticationException for Certificate	openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem\n\n    openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem	0
24328654	24328466	Formatting TimeSpans	TimeSpan ts = new TimeSpan(5, 10, 44);\nstring test = string.Format("{0:dd\\:hh\\:mm\\:ss\\.ffff}", ts);	0
1492147	1232398	How to programatically format an SD card with FAT16?	DriveInfo[] allDrives = DriveInfo.GetDrives();\nforeach (DriveInfo d in allDrives)\n{\n    if (d.IsReady && (d.DriveType == DriveType.Removable))\n    {\n    ProcessStartInfo startInfo = new ProcessStartInfo();\n    startInfo.FileName = "format";\n    startInfo.Arguments = "/fs:FAT /v:MyVolume /q " + d.Name.Remove(2);\n    startInfo.UseShellExecute = false;\n    startInfo.CreateNoWindow = true;\n    startInfo.RedirectStandardOutput = true;\n    startInfo.RedirectStandardInput = true;\n\n    Process p = Process.Start(startInfo);\n\n    StreamWriter processInputStream = p.StandardInput;\n    processInputStream.Write("\r\n");\n\n    p.WaitForExit();\n\n    }\n}	0
2015748	2015676	iterate through rows in an html table with c#	foreach (TableRow row in table.Rows)\n    {\n        var checkBox = (CheckBox)row.Cells[0].Controls[0]; //Assuming the first control of the first cell is always a CheckBox.\n\n        if (checkBox.Checked)\n        {\n            var col2 = (TextBox)row.Cells[1].Controls[0];\n\n            /* Do Stuff With col2 */\n        }\n        else\n        {\n            /* Do Stuff */\n        }\n    }	0
21239677	21239644	How to return anonymous array?	return new int[] { element1, element2 };	0
6952737	6943078	How to get the cell value from an unbound column directly after updating it?	this.gridView.PostEditor()	0
25642370	25639693	show/hide grid-view column by column name	if (CheckBox3.Checked == false)\n {\n    dt.Columns.Remove("Site_name");\n    GridView1.DataSource = dt;\n    GridView1.DataBind();\n }	0
9307992	9282026	How to save MP3 file from the internet on Windows Phone 7?	wc.OpenReadCompleted += ((s, args) =>\n{\n    using (var store = IsolatedStorageFile.GetUserStoreForApplication())\n    {\n        if (store.FileExists(fileName))\n            store.DeleteFile(fileName);\n\n        using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))\n        {\n            byte[] bytesInStream = new byte[args.Result.Length];\n            args.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);\n            fs.Write(bytesInStream, 0, bytesInStream.Length);\n            fs.Flush();\n        }\n    }\n});	0
3726524	3726159	Regular Expression for splitting string	//RegEx: ^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$\n    string pattern = "^([A-Z\"\\,]+)[\"\\,\\s]+([A-Z\"\\,]+)$";\n    System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(pattern);\n\n    string MyInput;\n\n    MyInput = "\"HELLO\",\"WORLD\"";\n    MyInput = "\"HELL\"O\"\",WORLD\"";\n    MyInput = "\"HELL,O\",\"WORLD\"";\n\n    string First;\n    string Second;\n\n    if (Reg.IsMatch(MyInput))\n    {\n        string[] result;\n        result = Reg.Split(MyInput);\n\n        First = result[1].Replace("\"","").Replace(",","");\n        Second = result[2].Replace("\"","").Replace(",","");\n    }	0
32827984	32789046	Null Exception declaring gridview in codebehind	private GridView gvBFProd;\n    protected void gvBFProd_RowCommand(object sender, GridViewCommandEventArgs e)\n    {\n        gvBFProd = FormView1.Row.FindControl("gvBFProd") as GridView;\n....	0
14557715	14546688	Umbraco display images created from image cropper using razor	var mediaItem = Library.MediaById(Model.Thumbnail);\nvar img = mediaItem.crop.Find("@name", "thumbnail");\n\nif (img != null)\n{\n    <img src="@img.url" />\n}	0
1203771	1203742	How to initialize IDictionary in constructor?	void CreateADictionaryFromAnonymousType() \n   { \n       var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"}); \n       Console.WriteLine(dictionary["Name"]); \n   }\n\nprivate IDictionary MakeDictionary(object withProperties) \n   { \n       IDictionary dic = new Dictionary<string, object>(); \n       var properties = \n           System.ComponentModel.TypeDescriptor.GetProperties(withProperties); \n       foreach (PropertyDescriptor property in properties) \n       { \n           dic.Add(property.Name,property.GetValue(withProperties)); \n       } \n       return dic; \n   }	0
14033895	14033785	How to create a ToolStripMenuItem with several controls on it?	Label newlabel = new Label();\n    newlabel.Text = "Hello World";\n    newlabel.Width = 300;\n    ToolStripControlHost tsHost = new ToolStripControlHost(newlabel);\n\n    contextMenuStrip1.Items.Add(tsHost);	0
20397845	20396517	Updating Textbox in a templateField with button	protected void Button1_Click1(object sender, EventArgs e)\n{\n    // First bind you grid again over here other wise it will lost data\n\n    GridView1.DataSource = you List of Objects or DataTable;\n    GridView1.DataBind();\n\n    foreach (GridViewRow gvr in GridView1.Rows)\n    {\n        if (gvr.RowType == DataControlRowType.DataRow)\n        {\n            // to fill all text boxes\n            TextBox textboxs = gvr.FindControl("textboxs") as TextBox;\n            textboxs.Text = "You text";\n\n\n            // to fill specific text box\n            // use gvr.DataItem to check aging specific data item using if and then\n            // textboxs.Text = "You text";\n        }\n    }\n}	0
17713116	17713069	Is using LINQ against a single object considered a bad practice?	string cfg = ConfigurationManager.AppSettings["myKey"];\ndecimal bla;\nif (!decimal.TryParse(cfg,out bla) || bla < 0 || bla > 10)\n    bla = 0; // 0 is the default value	0
32173966	32173919	Sending a string message to an IRC channel with C#	writer.WriteLine(string.Format("PRIVMSG {0} :{1}", CHANNEL, "Welcome back!"));\nwriter.Flush();	0
21408717	21408020	How to handle value changing	decimal supplierDiscount = decimal.Parse("1.00");	0
8390142	8390040	Allow additional parameters to be passed to a URL	public virtual ActionResult VehicleView(int id, string detailDisplayType)\n{\n    var vehicle = VehicleService.Get(id);\n    return View("VehicleView", new VehicleViewModel { VehicleDetail = vehicle != null ? vehicle.Details : null, Vehicle = vehicle, DetailDisplayType = detailDisplayType??"features" });\n}	0
7786569	7786533	How to Get results from multiple tables using LINQ	var query = from c in dataContext.City\n            where c.Contains(keyword)\n            select c.CityName + ", " + c.State.StateName+ ", "+ c.State.Country.CountryName;	0
7546216	7545877	C# generate a public and private keys for the DSA encryption algorithm	var dsa = new DSACryptoServiceProvider();            \n    var privateKey = dsa.ExportParameters(true); // private key\n    var publicKey = dsa.ExportParameters(false); // public key	0
9838992	9838935	Ninject constructor parameter depending on context	IConfigurationSource source2 = new FileConfigurationSource("Config2.xml");\n\n kernel.Bind<IConfigurationSource>().ToConstant(source2).WhenInjectedInto<ClassB>();	0
6918051	6918035	How to determine the earliest/latest DateTime in a collection?	VideoGame first= allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault();\nVideoGame last = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault();	0
22737089	22737038	Closing a MessageBox but keeping Form Open	if (line != PassWord)\n{\n    var result = MessageBox.Show(message, "Error", MessageBoxButtons.RetryCancel,    MessageBoxIcon.Information);\n    if (result == MessageBoxResult.Cancel)\n    {\n        // User chose cancel, close app or whatever\n    }\n    else\n    {\n        // User pressed retry, nothing really happens\n    }\n}       \nelse if (line == PassWord)\n{\n    Close();\n}	0
29122018	29120918	Reading a part of an XML file using C sharp	if (ofd.ShowDialog() == DialogResult.OK)\n    {\n        XmlDocument xDoc = new XmlDocument();\n        xDoc.Load(ofd.FileName);\n\n        foreach (XmlNode node in xDoc.SelectNodes("JobInfo/Folders/Folder"))\n            dataGridView1.Rows.Add(new object[]{node.Attributes["Path"].InnerText});\n\n    }	0
4246063	4245968	Create a completed Task<T>	private readonly Result theResult = new Result();\n\npublic override Task<Result> StartSomeTask()\n{\n    var taskSource = new TaskCompletionSource<Result>();\n    taskSource.SetResult(theResult);\n    return taskSource.Task;\n}	0
21779689	21778270	Getting deserialized values	public void load()\n    {\n        AlarmSettings alarmSettings;\n        alarmSettings = AlarmSettings.Load(@"C:\Users\jason\Desktop\Booya.txt");\n\n        foreach (var setting in alarmSettings.ProgramSettings)\n        {\n            string pathtext = setting.ProgramPathText;\n            string pathvalue = setting.ProgramPathValue;\n        }\n\n    }	0
5333638	5333611	get values from string	foreach (string item in selectedObjects.Split(';'))\n{\n    // do whatever you want with the items\n}	0
24209779	24209319	cannot convert from 'ref object' to 'tagVARIANT*'	Object^	0
31284151	31283699	Need to read multiple elements from single line from a text file	string input = "start ShooterGameServer.exe TheIsland?QueryPort=27015?SessionName=Cain532?MaxPlayers=10?listen?ServerPassword=12345?ServerAdminPassword=******** -nosteamclient -game -server -log";\n        string[] parts = input.Split('?', ' '); // Split string by '?' and ' '\n        string output = "";\n        foreach(var part in parts)\n        {\n            if(part.StartsWith("ServerAdminPassword")) // Put what you are looking for here\n                output = part.Split('=')[1]; // Get right side of '='\n        }\n        Console.WriteLine(output);	0
10613303	10613219	DLL Import use SYSTEMTIME	[StructLayout(LayoutKind.Sequential)]\nprivate struct SYSTEMTIME {\n    Int16 wYear;\n    Int16 wMonth;\n    Int16 wDayOfWeek;\n    Int16 wDay;\n    Int16 wHour;\n    Int16 wMinute;\n    Int16 wSecond;\n    Int16 wMilliseconds;\n}	0
5855267	5855240	How can I set a button background image on iPhone under Monotouch?	button.SetBackgroundImage (UIImage.FromBundle ("imageFile"), UIControlState.Normal);	0
4631409	4631267	different charset for multiple params with dllimport	[DllImport("my.dll", CharSet=CharSet.Unicode)]\n  void myfunc( [MarshalAs( UnmanagedType.LPStr )] String filename, \n               StringBuilder buffer, int len );	0
3696500	3696493	c# string format	string.Format("{0:#,0}", myDouble);	0
17417263	17414806	Getting the DisplayMemberPath value of combobox in Silverlight	var selectedType = ((AwardType) cboAwardType.SelectedItem).AType;	0
8296547	8296479	Getting info from child pages from masterpage codebehind	(Page as PageEx).LoggedInUserInfo.Somefunction();	0
13683687	13584541	Delete selected items in a GridView	object[] itemsSelected = MyGrid.SelectedItems.ToArray<object>();\n        foreach (object item in itemsSelected)\n        {\n            MyGrid.Items.Remove(item);\n        }	0
16045064	16044990	Check if the value currently in combobox is contained in items of that combo	this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;	0
22558054	22505998	How to get value from dictionary without knowing key?	This code use for get value from dictionary value without knowing key and value..  \n\nvar json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonString );\nvar javSer = new JavaScriptSerializer();\nvar dfi = javSer.Deserialize<Dictionary<string, string>>(json);\nstring dataString= dfi.Values.First();	0
13004405	13003952	C# Parsing XML and XElement	static void Main(string[] args)\n    {\n        XDocument xdoc = XDocument.Parse("<root><object type=\"node\" ><property name=\"id\" value=\"1\" /><property name=\"name\" value=\"ossvc06_node1\" /></object><object type=\"node\" ><property name=\"id\" value=\"2\" /><property name=\"name\" value=\"ossvc06_node2\" /></object></root>");\n\n        var nodes = xdoc.Descendants("object").Where(node => node.Attribute("type").Value == "node").ToList();\n\n        foreach (XElement nodelement in nodes)\n        {\n            List<XElement> nodeles = nodelement.Elements().ToList();\n\n            foreach (var node in nodeles)\n                Console.WriteLine(node);\n        }\n    }	0
21656137	21656029	how to rollback table if any error occur while executing multiple insert query simultaneously	SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;uid=sa;pwd=sa;");\n  myConnection.Open();\n\n  // Start a local transaction\n  SqlTransaction myTrans = myConnection.BeginTransaction();\n\n  SqlCommand myCommand = new SqlCommand();\n  myCommand.Connection = myConnection;\n  myCommand.Transaction = myTrans;\n  try\n  {\n    myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";\n    myCommand.ExecuteNonQuery();\n    myCommand.CommandText = "delete * from Region where RegionID=101";\n\n    // Attempt to commit the transaction. \n    myCommand.ExecuteNonQuery();\n    myTrans.Commit();\n    Response.Write("Both records are written to database.");\n  }\n  catch (Exception ep)\n  {\n    // Attempt to roll back the transaction. \n    myTrans.Rollback();\n    Response.Write(ep.ToString());\n    Response.Write("Neither record was written to database.");\n  }\n  finally\n  {\n    myConnection.Close();\n  }	0
31278535	31278534	EasyPost API - print_custom_1 option won't print on label	Shipment shipment = new Shipment() {\n    to_address = toAddress,\n    from_address = fromAddress,\n    parcel = parcel\n};\n\n//DO THIS BEFORE CREATING!\nshipment.options = new Dictionary<string, object>();\nshipment.options.Add("print_custom_1", "this is some sample text");\nshipment.options.Add("print_custom_2", "abc");\nshipment.options.Add("print_custom_3", "xyz");\n\nshipment.Create();\nvar lowestRate = shipment.LowestRate(includeServices: new List<string>() { "First" }, includeCarriers: new List<string>() { "USPS" });\n\nshipment.Buy(lowestRate);\n\nshipment.GenerateLabel("pdf");	0
19172428	19172251	how to export data into excel	// Content.  \nfor (int i = 0; i < ldt_Temp.Rows.Count; i++)\n{\n for (int j = 0; j < ldt_Temp.Columns.Count; j++)\n  {\n     ws.Cells[i + 2, j + 1] = ldt_Temp.Rows[i][j].ToString();\n     ws.Cells[i + 2, j + 1].NumberFormat = "0.00000000000000000"\n  }\n}	0
9062039	9062007	Elegant allocation of static readonly collection of strings	public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(\n  new [] {\n    "string1",\n    "string2",\n    "string3"\n  }\n);	0
17643169	17643102	Linq to SQL | Top 5 Distinct Order by Date	IEnumerable<DownloadHistory> top5Results = DownloadHistory\n    // group by SongId\n    .GroupBy(row => row.SongId)\n\n    // for each group, select the newest row\n    .Select(grp => \n        grp.OrderByDescending(historyItem => historyItem.DateInserted)\n        .FirstOrDefault()\n    )\n\n    // get the newest 5 from the results of the newest-1-per-song partition\n    .OrderByDescending(historyItem => historyItem.DateInserted)\n    .Take(5);	0
3473799	3465826	How to read the data from Non Adjacent Cells in Excel using C#	Areas objAreas = (Areas)objRange.Areas;\nforeach (Range area in objAreas)\n{\n   string CellAddress = (GetExcelColumnName(area.Column) + "" + area.Row);\n   MessageBox.Show(CellAddress);\n}	0
28803675	28803574	Format a string, clear specific characters in a string?	string FormatString(string text)\n{\n   // Get the last string and replace the "-" to space.\n   string output = text.split('/').Last().Replace("-"," ");\n\n   // convert it into title case\n   output  = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(output); \n   return output;   \n}	0
11931671	11915264	XNA draw model with depthBuffer, but over other models (like 3dMax Gizmo)	_GD.Clear(ClearOptions.DepthBuffer, new Vector4(0), 65535, 0);	0
15172822	15170154	How to model self-referencing object type?	public class Box\n{\n    [Required]\n    [Key]\n    public int BoxId { get; set; }\n\n    public string BoxName { get; set; }\n\n    public int ParentBoxId { get; set; }\n\n    // The foreign key for the Box that points at ParentBox.BoxId  (the [Key])\n    [ForeignKey("ParentBoxId")]\n    public Box ParentBox { get; set; }\n\n    // The foreign key for the Boxes that point at this.BoxId (the [Key])\n    [ForeignKey("ParentBoxId")]\n    public virtual ICollection<Box> Boxes {get; set;}\n}	0
17246851	17246803	Convert instances of objects to be able to loop through	var examples = new List<ExampleObject>()\n{\n   new ExampleObject { ID = 1, Name = "Display" },\n   new ExampleObject { ID = 2, Name = "Display2" },\n};\n\nexamples.ForEach(x => Console.WriteLine("id = {0}, name =  {1}", x.ID, x.Name));	0
890256	890098	Converting from a jagged array to double pointer in C#	double[][] array = //whatever\n//initialize as necessary\n\nfixed (double* junk = &array[0][0]){\n\n    double*[] arrayofptr = new double*[array.Length];\n    for (int i = 0; i < array.Length; i++)\n        fixed (double* ptr = &array[i][0])\n        {\n            arrayofptr[i] = ptr;\n        }\n\n    fixed (double** ptrptr = &arrayofptr[0])\n    {\n        //whatever\n    }\n}	0
22925823	22925766	HttpGet without Accept Header	var httpClient = new HttpClient();\nHttpResponseMessage response = httpClient.GetAsync("http://www.example.com").Result;	0
2291120	2291044	How to call the Click event on a page in the Windows Forms WebBrowser control?	void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n  if (webBrowser1.Url.Host.EndsWith("google.com")) {\n    HtmlDocument doc = webBrowser1.Document;\n    HtmlElement ask = doc.All["q"];\n    HtmlElement lucky = doc.All["btnI"];\n    ask.InnerText = "stackoverflow";\n    lucky.InvokeMember("click");\n  }\n}	0
12798487	12798407	How to call a model from with in a class?	public HoldToken() \n{\n   // Set value of token here\n   // Guessing at how you'd instantiate it.\n   Token = new Token();\n}	0
25151769	25151672	How to mapping value with identifier and variable value in C#	var t = new Table1();\n\nforeach(var animal in a)\n{\n  t.GetType().GetProperty(animal.Name).SetValue(t, animal.Value);\n}	0
18335466	18334839	Check property values with special characters refactor	string specialCharacters = @"\~|!|\@|\#|\$|%|\^|\&|\*|_|\+|\||\{|\}|:\""|\<|\>|\?|\[|\]|;|'|/|=|\\|???";\n\npublic bool ValidateCharacters(string pattern, AddressViewModel model)\n{\n    var reg = new Regex(pattern);\n\n    return reg.IsMatch(model.Index) == false && reg.IsMatch(model.Area) == false;\n}	0
6703497	6703316	Transfer of Databound Datagridview Row To Another Datagridview	private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {\n            if (e.ColumnIndex == myCheckBoxColumnName.Index) {\n                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];\n                string name = row.Cells["Name"].Value.ToString();\n                string amount = row.Cells["Amount"].Value.ToString();\n                dataGridView2.Rows.Add(name, amount);\n            }\n        }	0
23157906	23157795	Safety from SQL injection	SqlCommand com = new SqlCommand("select * from hs where ac between @ac1 and @ac2 and em=@em", con);	0
26772233	26771923	How to create two process and run them simultaneously in C#?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Diagnostics;\n\nnamespace proces\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            create_process__A("Balotelli");\n            create_process__B("Pirlo");\n        }\n\n         static void create_process__A(string t)\n        {\n            Process.Start("http://google.com/search?q=" + t);\n\n        }\n         static void create_process__B(string t)\n         {\n             Process.Start("http://google.com/search?q=" + t);\n\n         }\n    }\n}	0
13771099	13767618	Use different configurations with Simple Injector	container.Options.AllowOverridingRegistrstions = true;	0
8404749	8404394	Is it possible to make a FolderBrowserDialog's default path show up in a library instead of the actual disk?	FolderBrowserDialog dlg = new FolderBrowserDialog();\ndlg.RootFolder = Environment.SpecialFolder.MyComputer;\ndlg.SelectedPath = @"E:\Vetcentric";\ndlg.ShowDialog();	0
28375668	28364168	Execute a function in an open instance of Access from a .NET application	private void button1_Click(object sender, EventArgs e)\n{\n    Microsoft.Office.Interop.Access.Application acApp;\n    this.Activate();\n    acApp = (Microsoft.Office.Interop.Access.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Access.Application");\n    Microsoft.Office.Interop.Access.Dao.Database cdb = acApp.CurrentDb();\n    cdb.Execute("INSERT INTO LogTable (LogEntry) VALUES ('Entry added ' & Now())");\n    acApp.Forms["LogForm"].Requery();\n}	0
14731657	14731399	How to send byte[] as document to the Client?	protected void Page_Load(object sender, EventArgs e)\n        {\n            var byteArray = File.ReadAllBytes("test.pdf");\n\n            Response.ContentType = "application/pdf";\n            Response.AddHeader("content-disposition", "attachment;filename=test.pdf");\n            Response.BinaryWrite(byteArray);\n            Response.Flush();\n\n            Response.End();\n        }	0
1722083	1722013	giving a dataGridView cell a background image in C#	protected override void  OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)\n        {\n             // Your code to insert image/content per cell goes here    \n        }	0
800469	800463	C# Create a hash for a byte array or image	string hash;\nusing(SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())\n{\n    hash = Convert.ToBase64String(sha1.ComputeHash(byteArray));\n}	0
16069007	16068728	Regex Limit the count of charecters in a string	bool isCountExactly2 = Regex.IsMatch("12,34,56", "^([^,]*,){2}[^,]*$");	0
12080225	12079616	is there a straightforward way for a c# application to read a config file with a user specified name and location	ExeConfigurationFileMap m = new ExeConfigurationFileMap();\n        m.ExeConfigFilename = "blah";\n        ConfigurationManager.OpenMappedExeConfiguration(m, ConfigurationUserLevel.None);	0
6819380	6768282	VS2010 Extensibility: Custom document formatting	Region region = service.GetRegionContainingLine((line > 0 ? line - 1 : 0));\n\nif (region != null)\n{\n    using (EditArray mgr = new EditArray(this, service.LastActiveTextView, true, "Reformat Brace"))\n        this.ReformatSpan(mgr, region.ToSpan());\n}	0
328767	328765	ICollection<string> to string[]	string[] array = new string[collection.Count];\ncollection.CopyTo(array, 0);	0
34200450	34200097	Audio play issue on button click	void OnCollisionEnter2D(Collision2D col) {\n    Destroy (col.gameObject);\n    Instantiate (cube,new Vector3(0f,4.19f,0f),Quaternion.identity);\n    isFalling = false;  // here\n}\n\nprivate bool isFalling = false;  // here\npublic void Fall()\n{\n    GameObject.FindGameObjectWithTag ("Player").GetComponent<Rigidbody2D> ().isKinematic = false;\n    if(isFalling == false){\n        source.PlayOneShot(clip);\n        isFalling = true;   // here\n    }\n}	0
17547316	17547026	Name checkboxes in ListView	public class LineViewModel\n{\n   public bool IsChecked\n   {\n     get { return _isChecked;\n   }\n   set\n   {\n   // do something here\n   }\n}\n\n<GridViewColumn.CellTemplate>\n    <DataTemplate>\n        <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" IsThreeState="False"/>\n    </DataTemplate>\n</GridViewColumn.CellTemplate>	0
15587398	15584809	Chart Control add x points	chart1.ChartAreas[0].AxisX.Interval = 1;\nchart1.ChartAreas[0].AxisX.Minimum = 1;\nchart1.ChartAreas[0].AxisX.Maximum = 30;	0
11958047	11957934	Repeater button posting back to page_load instead of my method?	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!IsPostBack){\n      // Your existing stuff\n    }\n}	0
2948249	2948218	Adding values to a Dictionary using reflection	a x = new a();\n\nDictionary dic = (Dictionary) x.GetType()\n                  .GetField("m_Dict",BindingFlags.NonPublic|BindingFlags.Instance)\n                  .GetValue(x);\n\n// do something with "dic"	0
26632226	26632121	Dealing with Nulls in LINQ statement	departments.Where(d => \n      product.DepartmentIDs != null && product.DepartmentIDs.Contains(d.Id)).ToList()	0
33264780	33263659	How to set/use Custom Validator syntax	int count = 0;\n\nusing (SqlConnection con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["FleetManagementConnectionString"].ConnectionString))\n{\n    SqlCommand command = new SqlCommand("Select Count(*) from dbo.UserLoggins where UserName =@User and Password =@Password", con);\n\n    SqlParameter paramName = new SqlParameter("@User", SqlDbType.VarChar, 255) { Value = "HelloWorld1" };\n    command.Parameters.Add(paramName);\n\n    SqlParameter paramName = new SqlParameter("@Password", SqlDbType.VarChar, 255) { Value = "password" };\n    command.Parameters.Add(paramName);\n\n    con.Open();\n    count = (int)cmd.ExecuteScalar();\n    con.Close();\n\n}\n\nargs.IsValid = count > 0;\nreturn;	0
8776828	8776806	how do I access a folder on the shared hosting space?	~/App_Data	0
10108413	10108049	Linq query conversion from C# To VB:NET	Dim orderedData = From d In collezione\n                  Order By d.Gruppo\n                  Group d By d.Gruppo Into g = Group\n                  From d In g\n                  Select New With {\n                      .withChildren = {d}.\n                          Union(g.Where(Function(c) c.Owner = d.Comp))\n                  }\nDim result = (From od In orderedData\n              From wc In od.withChildren\n              Order By wc.Pos\n              Select wc).Distinct	0
11318860	11318779	Implementing IEnumerable with an Array	public class ArrayOrderBook : IEnumerable<PriceLevel>\n{\n    private PriceLevel[] PriceLevels = new PriceLevel[500];\n\n    public IEnumerator<PriceLevel> GetEnumerator()\n    {\n        return PriceLevels.AsEnumerable().GetEnumerator();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return PriceLevels.GetEnumerator();\n    }\n}	0
22025435	21978028	How do I Store application data during a CUIT execution to use later in another test	private WpfText _LoadNumberText = null;\n        public WpfText LoadNumberText\n        {\n            get\n            {\n                if ((this._LoadNumberText == null))\n                {\n                    this._LoadNumberText = new WpfText(this.UIGradeStarpoweredbyExWindow.UIItemCustom2.UIItemCustom1);\n                    #region Search Criteria\n                    this._LoadNumberText.SearchProperties[WpfText.PropertyNames.AutomationId] = "DocNumber";\n                    this._LoadNumberText.WindowTitles.Contains("Window Title");\n                    #endregion\n                }\n                return this._LoadNumberText;\n            }	0
24880682	24880432	How can I make a field in a class be set to false if the value being set is a null?	public class Answer2 {\n    private bool correct;  // This field has no need to be nullable\n    public bool? Correct\n    {\n        get { return correct; }\n        set { correct = value.GetValueOrDefault(); }\n    }\n\n}	0
9262271	9262149	I have a context menu item in Explorer, now how is it best to call my process on the file?	your_file_type\shell\open\command (default) = "c:\yourapp.exe" "%1"	0
5432042	5432003	strange string format + pathname from fileupload in mysql	Server.MpaPath	0
8655975	8655965	How to get data by SqlDataReader.GetValue by column name	Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);	0
29819903	29819825	c#: how to set "Created by" in dll	[assembly: AssemblyCompany("My company")]	0
25547081	25546988	Executing function in a background process using a timer	// Create a 1 min timer \n    timer = new System.Timers.Timer(60000);\n\n    // Hook up the Elapsed event for the timer.\n    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n    timer.Enabled = true;\n\n\n...\n\nprivate static void OnTimedEvent(object source, ElapsedEventArgs e)\n{\n    MessageBox.Show("Hello World!");\n    // Your code\n}	0
5298104	5298066	C# Reading in strings from a Text File	private static IEnumerable<string> LoadWords(String filePath)\n{\n      List<String> words = new List<String>();\n      foreach(String line in ReadAllLines(filePath))\n      {\n\n        string[] tokens = line.Split(new char[] { ' ' });\n        for (int i = 0; i < 500; i++)\n        {\n            words.Add(tokens[random.Next(tokens.Count())]);\n        }\n      }\n      return words;\n}	0
1498892	1498845	C# DbCommand in a loop	DbCommand insert = db.GetStoredProcCommand("Insert");\nforeach (string ID in myIDs)\n{\n    insert.Parameters.Clear();\n    db.AddInParameter(insert, "FileName", System.Data.DbType.String, \n        ID + ".xml");\n    db.ExecuteNonQuery(insert, transaction);\n}	0
22691534	22462466	EF 6 vs EF 5 relative performance issue when deploying to IIS8	from p1 in context.CookSales\n                join p15 in context.Pins on p1.PinId equals p15.PinID\n                where p1.SaleYear == userSettings.SaleYear\n                where ((p1.PinId == pinId) || (pinId == null))\n                orderby p1.Volume, p1.PIN\n                select new SaleView bla bla	0
5013403	5013308	Giving System.FormatException: String was not recognized as a valid DateTime. using datetime.ParseExact in C#	DateTime.ParseExact(..., "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);	0
34136267	34136117	Copy all files from a directory without creating subdirectories	public void CopyRecursive(string path, string newLocation)\n{\n    foreach(var file in DirectoryInfo.GetFiles(path))\n    {\n        File.Copy(file.FullName, newLocation + file.Name);\n    }\n\n    foreach(var dir in DirectoryInfo.GetDirectories(path))\n    {\n        CopyRecursive(path + dir.Name, newLocation);\n    }\n}	0
30338252	30338161	C# - Assembly with code in global namespace	extern alias <alias>	0
11749218	11749121	Custom comparer that groups numbers into 2 groups	int ComareResult(int a, int b)\n{\n   var groupA = a <=20 && a >=1;\n   var groupB = b <=20 && b >=1;\n   return groupA == groupB ? 0 : a <b ? -1 : 1;\n}	0
4860956	4860933	How to make Visual Studio not put { on a new line?	New Line Options for expressions	0
25621391	25619843	Parsing and Increment of IP Addresses	foreach (var item in items)\n{\n    var fromIp = item.From.GetAddressBytes();\n    var toIp = item.To.GetAddressBytes();\n\n    Console.WriteLine("From {0} to {1}", item.From.ToString(), item.To.ToString());\n\n    foreach (byte secondPart in Enumerable.Range(fromIp[1], toIp[1] - fromIp[1] + 1))\n    {\n        foreach (byte thirdPart in Enumerable.Range(fromIp[2], toIp[2] - fromIp[2] + 1))\n        {\n            var ip = new IPAddress(new byte[] {fromIp[0], secondPart, thirdPart, fromIp[3]});\n            yield return string.Format("{0}\t{1}\t{2}\t{2}", item.C1, item.C2, ip.ToString());\n        }\n    }\n}	0
23662858	22637506	NUnit/Mono not printing stack trace line number even with --debug	-runtime=v4.0	0
28327994	28327899	Serialize as array with JSON.NET	public class Url\n{\n    public string name { get; set; }\n    public int size { get; set; }\n    public List<string> outlinks { get; set; }\n}	0
9427893	9426319	is it possible to run a windows form application with the console application?	using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.WriteLine("I'm going to open a form now!");\n            var form = new Form1();\n            form.ShowDialog();\n        }\n    }\n}	0
2229040	2229019	How to dynamically generate a TextBox control.	TextBox txt = new TextBox();\ntxt.ID = "textBox1";\ntxt.Text = "helloo";\nform1.Controls.Add(txt);\n\nLabel lbl = new Label();\nlbl.Text = "I am a label";\nform1.Controls.Add(lbl);	0
6963125	6963055	Trying to set the value of a Drop Down	var text = Clients.MerchandiseType.ToString();\nvar item = ddlMyDropDown.Find(text); //Some method that returns a list item\nddlMyDropDown.SelectedItem = item;	0
9970010	9969814	Instancing with a dictionary	Dictionary<int, List<string>> dictName = new Dictionary<int, List<string>>();\ndictName.Add(0, new List<string>());\ndictName[0].Add("First");\ndictName.Add(1, new List<string>());\ndictName[1].Add("Second");	0
2530822	2530749	Parsing commas and quotemarks in degenerate CSV files with Regular Expressions	str2 = Regex.Replace(str2, "\"[^\"]*\"",\n                     match => match.Value.Trim('\"').Replace(",", ""));	0
13519729	13519667	Initilialising an array of objects that contain an array of other objects?	class Building\n{\n    Building()\n    {\n      floors = new Floor[6];\n      for(int i=0; i<6;++i)\n          floors[i] = new Floor();\n    }\n\n    public Floor[] floors;\n}	0
8199123	8199042	A More Efficient Way to Parse a String in C#	string name = m.Groups["name"].Value; // Or was it m.Captures["name"].Value?	0
26271564	26270990	How to parse JSON objects with numeric keys using JavaScriptSerializer	var transactions = JObject.Parse(json).PropertyValues()\n                                      .Select(o => o.ToObject<Transaction>());	0
16800326	16658272	Consume WCF from unity3D	UnityStoreClient client = new UnityStoreClient(new BasicHttpBinding(), new EndpointAddress(some_url));	0
10285808	10285726	asp.net multiple table update statement	BEGIN TRANSACTION\n\nUPDATE SomeTable\nSET SomeColumn  = 'Foo' \nWHERE SomeID = 123   \n\nUPDATE AnotherTable\nSET AnotherColumn = 'Bar'\nWHERE AnotherID = 456    \n\nCOMMIT	0
4423107	4423034	How save object to HiddenField in ASP.NET?	yourHiddenField.Value = strSerializedVersionOfYourObject;	0
15341079	15339909	Consider marking it with the DataContractAttribute attribute?	static void ShowProperties(object o, int indent = 0)\n{\n    foreach (var prop in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))\n    {\n        if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && prop.PropertyType != typeof(string))\n        {\n            Console.WriteLine("{0}{1}:", string.Empty.PadRight(indent), prop.Name);\n            var coll = (IEnumerable)prop.GetValue(o, null);\n            if (coll != null)\n            {\n                foreach (object sub in coll)\n                {\n                    ShowProperties(sub, indent + 1);\n                }\n            }\n        }\n        else\n        {\n            Console.WriteLine("{0}{1}: {2}", string.Empty.PadRight(indent), prop.Name, prop.GetValue(o, null));\n        }\n    }\n    Console.WriteLine("{0}------------", string.Empty.PadRight(indent));\n}	0
9188240	9188203	Get List of Namespaces available in Project in ASP.NET	IEnumerable<string> GetNamespaces(Assembly assembly)\n{\n    return assembly.GetTypes().Select(type => type.Namespace).Distinct();\n}	0
16936325	16935957	Self referencing interface	public interface IMyInterface\n{\n    List<IMyInterface> GetAll(string whatever);\n}\n\npublic class Program : IMyInterface\n{\n    public string Member { get; set; }\n\n    public List<IMyInterface> GetAll(string whatever)\n    {\n        return new List<IMyInterface>()\n            { new Program() { Member = whatever } };\n    }\n\n    static void Main(string[] args)\n    {\n        List<IMyInterface> all = new Program().GetAll("whatever");\n        Console.WriteLine(all.Count);\n    }\n}	0
11202353	11189988	TCP Communication Behaviour	private byte[] CleanArray(byte[] array)\n    {\n        int i = array.Length - 1;\n\n        while (array[i] == 0)\n        {\n            i--;\n        }\n\n        byte[] cleanedArray = new byte[i + 1];\n        Array.Copy(array, cleanedArray, i + 1);\n\n        return cleanedArray;\n    }	0
2304799	2304745	How to invoke methods with ref/out params using reflection	static void Main(string[] args)\n{\n    var method = typeof (Cow).GetMethod("TryParse");\n    var cow = new Cow();           \n    var inputParams = new object[] {"cow string", cow};\n    method.Invoke(null, inputParams); \n}\n\nclass Cow\n{\n    public static bool TryParse(string s, out Cow cow) \n    {\n        cow = null; \n        Console.WriteLine("TryParse is called!");\n        return false; \n    }\n}	0
8861657	8861624	How to get currently selected node in a treeview	private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)\n    {\n        string selectedNodeText = e.Node.Text;\n    }	0
18622378	18617983	How Do I bind a button Content with a list of numbers in WP8?	public GamePage()\n{\n    InitializeComponent();\n    this.DataContext = GamePageViewModel();\n    for (int x = 1; x <= row; x++)\n    {\n        for (int i = 1; i <= column; i++)\n        {\n            CreateButtons(SeatValue.ToString() + i, locationFirst, locationSecond);\n            locationFirst = locationFirst + 130;\n        }\n        locationFirst = 25;\n        locationSecond = locationSecond + 50;\n    }\n\n}\n\npublic class GamePageViewModel\n{\n   //List of numbers to put e.g. List<int>\n   //Change PropertyNameOfTheViewModel here to properties, say 10 properties e.g, public int Content { get; set; }\n} \n\nButton btnNew = new Button();\nbtnNew.Name = btnName;\nbtnNew.Margin = new Thickness(btnPointFirst, btnPointSecond, 0, 0);\nbtnNew.Width = 100;\nbtnNew.Height = 70;\nbtnNew.SetBinding(Button.ContentProperty,new Binding("PropertyNameOfTheViewModel");	0
29686701	29684089	Refresh DataGridView after INSERT into SQL	public void Insert_Button_Click(object sender, EventArgs e)\n{\n    MyClass.InsertNewClient(fullNametxt.Text, shortNametxt.Text);\n    this.tblClientTableAdapter.Fill(this.DataSetClient.tblClient);\n}	0
30771382	30771199	How to convert a JSON array into a C# List?	return Json.Decode<ShoppingCart>(value);	0
8658603	8658278	A cycle was detected in a LINQ expression exception	private IEnumerable<int> FilterIdsByClient(IEnumerable<int> entityIds) \n{ \n    // The variable entityIds points to whatever was passed in: A List, according to the edited question.\n\n    entityIds =                                    //this is an assignment, changing the referent of entityIds\n        MyObjectContext.CreateObjectSet<TEntity>() \n            .Where(x => x.ClientId == _clientId) \n            .Where(x => entityIds.Contains(x.Id))  //this lambda closes over the variable entityIds\n            .Select(x => x.Id); \n\n    // The query now has a reference to the *variable* entityIds, not to the object that entityIds pointed to originally.\n    // The value of entityIds has been changed; it now points to the query itself!\n    // The query is therefore operating on itself; this causes the "cycle detected" message.\n    // Because of delayed execution, the query is not executed until the next line of code:\n\n    return entityIds.ToList();\n}	0
13599686	13599599	save png file in application image folder without using savedialogfile	if (lastSnapshot != null)//writableBitmap object lastSnapshot\n{\n     using (var pngStream = GetPngStream(lastSnapshot))//return Stream type \n     using (var file = File.Create(Path.Combine("ImageFolder", "ImageName.png")))\n     {\n         byte[] binaryData = new Byte[pngStream.Length];\n         long bytesRead = pngStream.Read(binaryData, 0, (int)pngStream.Length);\n         file.Write(binaryData, 0, (int)pngStream.Length);\n     }\n}	0
24241823	24241600	How to Invalidate cache data manually in ASP.Net WebForm	public void ClearApplicationCache()\n        {\n            List<string> keys = new List<string>();\n\n            IDictionaryEnumerator enumerator = Cache.GetEnumerator();\n\n            while (enumerator.MoveNext())\n            {\n                keys.Add(enumerator.Key.ToString());\n            }\n\n            for (int i = 0; i < keys.Count; i++)\n            {\n                Cache.Remove(keys[i]);\n            }\n        }	0
7480898	7480644	How to subscribe to, but buffer data from, an IObservable until another IObservable has published?	var r = Observable.Create<int>(o =>\n{\n    var rs = new ReplaySubject<int>();\n    var subscription1 = s1.Subscribe(rs);\n    var query = from f in s2.Take(1) select rs.AsObservable();\n    var subscription2 = query.Switch().Subscribe(o);\n    return new CompositeDisposable(subscription1, subscription2);\n});	0
23625032	23624578	Opening a view via another event	private void icon_Add(object sender, RoutedEventArgs e)\n{\n    OpenView(typeof(viewName));\n}\n\nprivate void OpenView(Type newView)\n{\n    if(typeof(Window).IsAssignableFrom(newView)) {\n        Window window = (Window)Activator.CreateInstance(newView);\n        window.Show();\n        window.Close();\n    }\n}	0
16567396	16567259	WinForms, set Input cursor after Text.Replace at the end of text	if (ExpenseValueTB.Text.Contains(',')) {\n        ExpenseValueTB.Text = ExpenseValueTB.Text.Replace(',', '.');\n        ExpenseValueTB.SelectionStart = ExpenseValueTB.Text.IndexOf('.') + 1;\n        ExpenseValueTB.SelectionLength = 0;\n        ExpenseValueTB.Focus();\n    }	0
33570996	33570501	File is created but information wont save in it	infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);\n// zero bytes\ninfodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);\n// works!	0
4117011	4116973	C# fast way to replace text in a html file	string input = File.ReadAllText("<< input HTML file >>");\nstring replacement = File.ReadAllText("<< replacement HTML file >>");\n\nint startIndex = 1000;\nint endIndex = 200000;\n\nvar sb = new StringBuilder(\n    input.Length - (endIndex - startIndex) + replacement.Length\n);\n\nsb.Append(input.Substring(0, startIndex));\nsb.Append(replacement);\nsb.Append(input.Substring(endIndex));\n\nstring output = sb.ToString();	0
5653749	5653703	Can a c# lambda function be more than one line?	List<String> items = new List<string>();\n\nvar results = items.Where(i => \n       {\n                bool result;\n\n                if (i == "THIS")\n                    result = true;\n                else if (i == "THAT")\n                    result = true;\n                else\n                    result = false;\n\n                return result;\n            }\n        );	0
13927939	13927815	switch case with integer expression	int Length = mystring.Length;\nint range = (Length - 1) / 25;\nswitch (range)\n{\n    case 0:\n        Console.WriteLine("Range between 0 to 25");\n        break;\n    case 1:\n        Console.WriteLine("Range between 26 to 50");\n        break;\n    case 2:\n        Console.WriteLine("Range between 51 to 75");\n        break;\n\n}	0
658114	658027	Logout with facebook	FB.logout()	0
8733613	8733555	How can I use a keypress to run a method?	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n\n    switch (keyData)\n    {\n        case Keys.S:\n            Run_Scan();                \n            break;\n        case Keys.E:\n            Application.Exit();\n            break;\n        default:                    \n            MessageBox.Show("I'll only accept 's' or 'e'.");                \n            break;\n\n    }        \n\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
33172453	33172363	Convert List<string> to byte array by lines using c#	byte[] dataAsBytes = Items.SelectMany(s =>\nSystem.Text.Encoding.UTF8.GetBytes(s + Environment.NewLine)).ToArray();	0
30336595	30336231	ObjectListView Set first displayed item	objectListView1.TopItemIndex = n;	0
25392201	25392169	How to assign a value to a DateTimeOffset data type	...\nnew Student {Name = "Bob Smith", DayOfWeek = "Monday", Time = new DateTimeOffset(/*some arguments here*/) }\n...	0
6485747	6484645	how do i convert IEnumerable<MyClass> to DataTable very fast?	public static DataTable ToDataTable<T>(this IEnumerable<T> collection)\n    {\n        DataTable dt = new DataTable();\n        Type t = typeof(T);\n        PropertyInfo[] pia = t.GetProperties();\n        //Create the columns in the DataTable\n        foreach (PropertyInfo pi in pia)\n        {\n            if ((pi.PropertyType.IsGenericType) )\n            {\n                Type typeOfColumn = pi.PropertyType.GetGenericArguments()[0];\n                dt.Columns.Add(pi.Name, typeOfColumn);\n            }\n            else\n                dt.Columns.Add(pi.Name, pi.PropertyType);\n        }\n        //Populate the table\n        foreach (T item in collection)\n        {\n            DataRow dr = dt.NewRow();\n            dr.BeginEdit();\n            foreach (PropertyInfo pi in pia)\n            {\n                dr[pi.Name] = pi.GetValue(item, null);\n            }\n            dr.EndEdit();\n            dt.Rows.Add(dr);\n        }\n        return dt;\n    }\n}	0
7261905	7255226	awesomium.dll crashes my WPF application on XP not Windows 7	Application.SetUnhandledExceptionMode	0
4960218	4960135	How to check if a value is null in T-SQL in parametrized query?	[...] WHERE COALESCE(Title,'') = COALESCE(@Title,'') AND Price = 123	0
21058591	21058464	Adding Context Menu To Desktop Background	var path = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Next";\nMicrosoft.Win32.Registry.LocalMachine.CreateSubKey(path, true); // True makes it writeable\nMicrosoft.Win32.Registry.LocalMachine.OpenSubKey(path).SetValue("@", "Reset", Microsoft.Win32.RegistryValueKind.String);	0
5943768	5943588	Best practises in catching exception from wcf in winforms app	try{\n       ... call service\n    }catch(FaultException<TimeoutFault> ex){\n       .. try one more time\n    }catch(FaultException<InvalidSelection> ex){\n      ... show message to user from ex.Details.InvalidProperty\n    }catch(FaultException){\n      ... handle\n    }catch (CommunicationException ex){\n       ... remember this is WCF so the call itself might fail\n    }catch(Exception ex){\n     ... handle        \n    }	0
1358107	1357853	AutoComplete TextBox Control	this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\n this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;\n\nprivate void textBox1_TextChanged(object sender, EventArgs e)\n{\n    TextBox t = sender as TextBox;\n    if (t != null)\n    {\n        //say you want to do a search when user types 3 or more chars\n        if (t.Text.Length >= 3)\n        {\n            //SuggestStrings will have the logic to return array of strings either from cache/db\n            string[] arr = SuggestStrings(t.Text);\n\n            AutoCompleteStringCollection collection = new AutoCompleteStringCollection();\n            collection.AddRange(arr);\n\n            this.textBox1.AutoCompleteCustomSource = collection;\n        }\n    }\n}	0
13698224	13698127	C# - Remove Key duplicates from KeyValuePair list and add Value	var newList = myList.GroupBy(x => x.Key)\n            .Select(g => new KeyValuePair<string, int>(g.Key, g.Sum(x=>x.Value)))\n            .ToList();	0
877600	877171	Is there a way to get a property value of an object using PropertyPath class?	var path = new PropertyPath("FullName.FirstName");\n\nvar binding = new Binding();\nbinding.Source = new Person { FullName = new FullName { FirstName = "David"}}; // Just an example object similar to your question\nbinding.Path = path;\nbinding.Mode = BindingMode.TwoWay;\n\nvar evaluator = new BindingEvaluator();\nBindingOperations.SetBinding(evaluator, BindingEvaluator.TargetProperty, binding);\nvar value = evaluator.Target;\n// value will now be set to "David"\n\n\npublic class BindingEvaluator : DependencyObject\n{\n    public static readonly DependencyProperty TargetProperty =\n        DependencyProperty.Register(\n            "Target", \n            typeof (object), \n            typeof (BindingEvaluator));\n\n    public object Target\n    {\n        get { return GetValue(TargetProperty); }\n        set { SetValue(TargetProperty, value); }\n    }\n}	0
8584992	8584980	Build(escape) a JavaScript regexp in C#	Regex.Escape	0
13521382	13521119	How to check whether it .mdb file format dragged in WinForms?	string[] FileList;\n\nif (e.Data.GetDataPresent(DataFormats.FileDrop))\n{\n    FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);\n}\nelse if (e.Data.GetDataPresent(DataFormats.StringFormat))\n{\n    FileList = new string[] {e.Data.GetData(DataFormats.StringFormat, false).ToString()};\n}\nelse\n{\n    return;\n}	0
5557316	5557278	How do I get the value from an anonymous expression?	Func<TModel, TValue> method = expression.Compile();\n\nTValue value = method(html.ViewData.Model);\n// might be a slightly different property, but you can get the ViewModel \n// from the HtmlHelper object.	0
3133249	3133199	.NET Global exception handler in console application	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;\n        throw new Exception("Kaboom");\n    }\n\n    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {\n        Console.WriteLine(e.ExceptionObject.ToString());\n        Console.WriteLine("Press Enter to continue");\n        Console.ReadLine();\n        Environment.Exit(1);\n    }\n}	0
3529849	3464806	Rhino Mocks stubbing an event with ref parameter	public virtual void RaiseRequestImportLevelEvent(bool hasYc, bool hasWc, bool hasDc, ref short chosenLevel)\n    {\n        if (RequestImportLevel != null)\n        {\n            RequestImportLevel(hasYc, hasWc, hasDc, ref chosenLevel);\n        }\n    }	0
22946713	22945997	extract data from webservice ?WSDL	ProductsService.DataSetWebService ws = new ProductsService.DataSetWebService();  \nGridView1.DataSource = ws.GetProducts();  \nGridView1.DataBind();	0
19007218	18972295	Hide Childform of MDi	bool found = false;\n    foreach (Form childForm in parent.MdiChildren) {\n        if (form.GetType() = typeof(T)) form.Visible = found = true;\n        else form.Visible = false;\n    }\n    if (!found) {\n       // etc...\n    }	0
20356887	20355515	How to do a mouse over using selenium webdriver to see the hidden menu without performing any mouse clicks?	// this makes sure the element is visible before you try to do anything\n// for slow loading pages\nWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));\nvar element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id(elementId)));\n\nActions action  = new Actions(driver);\naction.MoveToElement(element).Perform();	0
23528756	23527753	How to make combobox accessible to other form	Public ComboBox1\n {\n      get { return this.comboBox1;  }\n      set { comboBox1 = value; }\n }	0
10544801	10544621	How to filter attribute values in XML file?	xmlSkuDescDoc.Descendants("Context")\n                .Where(el => el.Attribute("enabled").Value == "1")\n                .Elements()\n                .ToList()\n                .ForEach(i => newContextElementCollection.Add(new ContextElements { Property = i.Name.ToString(), Value = i.Value }));	0
27146702	27146208	Get properties with reflection	void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        if (this.UsingLogicalPageNavigation())\n        {\n            this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();\n        }\n        var mySelectedItem = e.AddedItems[0];\n\n        MyObject myObject = (MyObject)mySelectedItem;\n\n        // Now you can access your property as follows: myObject.MyProperty;\n\n    }	0
2539421	2537914	Getting a certain node using DataSet	Dim myFile = "c:\test.xml"\n    Dim X As New System.Xml.XmlDocument()\n    X.Load(myFile)\n    Dim N = X.SelectSingleNode("//xml/ObsCont[@xCampo=""field2""]/xTexto")\n    Trace.WriteLine(N.InnerText)	0
1381976	1381968	Setting 32-bit x86 build target in Visual C# 2008 Express Edition?	CorFlags.exe /32BIT+ yourapp.exe	0
11261364	10451823	How to Create a sprite Image	Bitmap originalImage; //  that is your image of 100x100 pixels\nBitmap bigImage; //  this is your 3000x3000 canvas\nint xPut = 0;\nint xPut = 0;\nint maxHeight = 0;\nwhile (someExitCondition) \n{\n    Bitmap imagePiece = GetImagePieceAccordingToSomeParameters(originalImage);\n    if (xPut + imagePiece.Width > 3000)\n    {\n        xPut = 0;\n        yPut += maxHeight;\n        maxHeight = 0;\n    }\n    DrawPieceToCanvas(bigImage, xPut, yPut, imagePiece);\n    xPut += imagePiece.Width;\n    if (imagePiece.Height > maxHeight) maxHeight = imagePiece.Height;\n    //  iterate until done\n}	0
28702719	28702647	Make a Select between two dates captured by JQuery Datepicker with Linq Entities	public ActionResult Index(string searchString, string datepicker, string datepicker2)\n{\n    var transactions = db.transactions.Include(t => t.Client).Include(t => t.DocumentType).Include(t => t.MovementType1);\n    if (!String.IsNullOrEmpty(searchString))\n    {\n        //Get your dates here...\n        var fromDate = Convert.ToDateTime(datepicker);\n        var toDate = Convert.ToDateTime(datepicker2);\n\n        transactions = transactions.Where(s => s.Client.Name.Contains(searchString) && \n                                          s.Date >= fromDate && s.Date < toDate);     \n    }\n    return View(transaccions.ToList());\n}	0
22191640	22191203	How to add some parameters to WorkbookBeforeClose() event of Excel	excelApp.WorkbookBeforeClose += new Excel.AppEvents_WorkbookBeforeCloseEventHandler(\n    (Excel.Workbook wb, ref bool c) => mamed(wb, c, wb.Application)\n    );	0
32464504	32464047	How do i use the force parameter in visual studio package manager console?	enable-migrations -contexttypename AccountingContext -force	0
17773020	17772619	redirect to a new wpf window after 10 seconds?	public MainWindow()\n    {\n        InitializeComponent();\n        Loaded += MainWindowLoaded;\n    }\n    void MainWindowLoaded(object sender, RoutedEventArgs e)\n    {\n        Loaded -= MainWindowLoaded;\n        Window1 window1 = new Window1();\n        window1.Dispatcher.BeginInvoke((SendOrPostCallback) delegate\n            {\n                Thread.Sleep(3000);\n                Hide();\n                window1.Show();\n            }, new object[] {null});\n    }	0
8690931	8690904	How to define a virtual getter and abstract setter for a property?	public abstract class Uniform<T>\n{\n    public readonly int Location;\n    protected T _variable;\n\n    public T Variable\n    {\n        get { return _variable; }\n        set { SetVariable(value); } \n    }\n\n    protected abstract void SetVariable(T value);\n}\n\npublic class UniformMatrix4 : Uniform<Matrix4>\n{\n    public override void SetVariable(Matrix4x4 value)\n    {\n        _variable = value;\n        GL.UniformMatrix4(Location, false, ref _variable);\n    }\n}	0
25830587	25830572	Use of unassigned out parameter	public void MyMethod()\n{\n    List<MyUrl> urls = null;\n    ...\n    ExtractData(out urls);\n}\nprivate static void(out List<MyUrl> urls)\n{\n  urls = new List<MyUrl>();\n   ...\n   foreach(var item in items)\n   {\n       urls.Add(new MyUrl{ Url = item.Url });\n   }       \n}	0
7387469	7387389	Display date from DB adjusted to local daylight settings	// here static text but you can initialize the TimeZoneInfo with any Id, check MSDN for this:\n// http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\n\nstring nzTimeZoneKey = "New Zealand Standard Time";\n\nTimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);\nDateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);	0
7423121	7423065	Generate a filename with number inside parenthesis	public static object lockObject = new object();\nvoid UploadFile(...)\n{\n    //-- other code\n    lock (lockObject)\n    {\n        int i = 1;\n        string saveFileAs = "MyFile.txt";\n        while (File.Exists(saveFileAs))\n        {\n           string fileNameWithoutExt = Path.GetFileNameWithoutExtension(saveFileAs);\n           string ext = Path.GetExtension(saveFileAs)\n           saveFileAs = String.Concat(fileNameWithoutExt, "(", i.ToString(), ")", ext);\n           i++;\n        }\n\n        //-- Now you can save the file.\n    }\n}	0
1068749	1068619	Default parameter values/optional parameters for .NET stored procedures in SQL Server 2005	CREATE PROCEDURE TestProcWrapper\n(\n    @TestIntWrapperParam int = null\n)\nAS\nEXEC TestProc @TestInt = @TestIntWrapperParam	0
19636730	18793959	FileNotFoundException when trying to load Autofac as an embedded assembly	private static Assembly loadEmbeddedAssembly(string name)\n{\n    if (name.EndsWith("Retargetable=Yes")) {\n        return Assembly.Load(new AssemblyName(name));\n    }\n    // Rest of your code\n    //...\n}	0
19635255	19632552	LINQ - XML select node generic	string keep = @"EmpId,Sex,Address,Address\Zip,Address2,Address2\Country";\nstring desStr = "Employee";\nstring[] strArr = keep.Split(',');\n\nvar nodesToDelete = xDoc.Root.Descendants(desStr)\n                .SelectMany(el => el.Descendants()\n                                  .Where(a => \n                                    {\n                                        if (a.Parent.Name == desStr)\n                                        {\n                                            return !strArr.Contains(a.Name.ToString());\n                                        }\n                                        else\n                                        {\n                                            return !strArr.Contains(a.Parent.Name + @"\" + a.Name);\n                                        }\n\n                                    }));\n\nforeach (var node in nodesToDelete.ToList())\n      node.Remove();	0
2690558	2690509	Reading resource file in VSTO Shared Addin	var assembly = Assembly.GetExecutingAssembly();	0
25070046	25047610	Programmatically change jpg in picturebox	pictureBox1.Invalidate()	0
33966652	33966512	c# How to manipulate image array	public partial class Form1 : Form\n    {\n        List<card> deck = new List<card>();\n        public Form1()\n        {\n            InitializeComponent();\n        }\n    }\n       public class card\n    {\n           string suit { get; set; }\n           int rank { get; set; }\n           Bitmap image { get; set; }\n    }\n???	0
7530951	7530201	Getting information if Topmost property is changed	public partial class MainWindow : Window\n{\n    static MainWindow()\n    {\n        Window.TopmostProperty.OverrideMetadata(typeof(MainWindow),\n            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.None,\n                new PropertyChangedCallback(OnTopMostChanged)));\n    }\n    public event EventHandler TopmostChanged;\n    private static void OnTopMostChanged(DependencyObject d,\n        DependencyPropertyChangedEventArgs e)\n    {\n        MainWindow mv = (MainWindow)d;\n        if (mv.TopmostChanged != null)\n            mv.TopmostChanged(mv, EventArgs.Empty);\n    }\n\n    private void ChangeTopmostBtn_Click(object sender, RoutedEventArgs e)\n    {\n        this.Topmost = !this.Topmost;\n    }\n    ...\n}	0
22887175	22887119	How to get a derived class to inherit a variable from the base class to have a different value?	public class Monster\n{\n    public Monster()\n    {\n        this.Score = 1;\n    }\n\n    public int Score\n    {\n        get;\n        set;\n    }\n}\n\npublic class Skeleton : Monster\n{\n    public Skeleton()\n        : base()\n    {\n        this.Score = 2;\n    }\n}	0
13174039	13173915	Search for value in DataGridView in a column	private void btnSearch_Click(object sender, EventArgs e)\n{\n    string searchValue = textBox1.Text;\n\n    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\n    try\n    {\n        foreach (DataGridViewRow row in dgvProjects.Rows)\n        {\n            if (row.Cells[2].Value.ToString().Equals(searchValue))\n            {\n                row.Selected = true;\n                break;\n            }\n        }\n    }\n    catch (Exception exc)\n    {\n        MessageBox.Show(exc.Message);\n    }\n}	0
10775296	10775233	How to get the Id of something i currently inserted into access db	INSERT INTO table(column1, column2, ...) VALUES(value1, value2)\n\nSELECT TOP 1 id FROM table ORDER BY id DESC	0
16405295	16405040	WPF DataGrid : scolling cause controls events to be called	struct NameBool\n{\n    private string name;\n    private bool selected;\n    public string Name\n    {\n        get { return name; }\n        set\n        {\n            if (name == value) return;\n            name = value;\n        }\n    }\n    public bool Selected\n    {\n        get { return selected; }\n        set\n        {\n            if (selected == value) return;  // this is to ignore a no change\n            selected = value;\n        }\n    }\n    public NameBool(string Name, bool Selected) { name = Name; selected = Selected;}\n}	0
20121589	20121505	Make dates in datetimepicker grey?	DateTimePicker2.MinValue = Convert.toDateTime(DateTimePicker1.SelectedDate);	0
179191	179173	Append XML string block to existing XmlDocument	XmlDocument xdoc = new XmlDocument();\nxdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");\n\nXmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();\nxfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";\n\nxdoc.DocumentElement.FirstChild.AppendChild(xfrag);	0
19678156	19654442	Fill DropDownList items by selected item in another DropDownList?	public void NamesToDropdownList()\n{\n        objhatcheryPL.type = ddltype.SelectedItem.Text;\n        DataTable dtname = new DataTable();\n        dtname = objhatcheryBAL.dtnames(objhatcheryPL);\n        ddlname.DataTextField = "Name";\n        ddlname.DataValueField = "Name";\n        ddlname.DataSource = dtname;\n        ddlname.DataBind();\n        ddlname.Items.Add(new ListItem("--select--", "0"));\n        ddlname.SelectedIndex = ddlname.Items.Count - 1;\n }\n\nprotected void ddltype_SelectedIndexChanged(object sender, EventArgs e)\n   {\n    if (ddltype.SelectedItem.Text != "--Select--")\n    {\n        NamesToDropdownList();\n    }\n   }	0
7730412	7730235	Databinding in combobox	binding = new Binding("checked", solution, "InternalFlag", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));	0
21340702	21340658	Changing format of String.Format parameters at run time	DateOfBirth = myTable.DateOfBirth.ToShortDateString();	0
18069922	18068902	Big Tables in Entity Framework	var ncms = repository.VIEWNCM; // this should be IQueryable or IEnumerable - no query yet\n\nif(Request.IsAjaxRequest())\n{\n    if(!string.IsNullOrEmpty(searchString))\n    {\n        switch(typeSearch)\n        {\n                case "cod":\n                    // No query here either!\n                    ncms = ncms.Where(e => e.CODIGO_LEITURA.ToLower().Contains(searchString.ToLower()) || e.CODIGO.ToLower().Contains(searchString.ToLower()));\n                    break;\n                default:\n                    // Nor here!\n                    ncms = ncms.Where(e => e.DESCRICAO.ToLower().Contains(searchString.ToLower()));\n                    break;\n            }\n        }\n    }\n}\n// This is the important bit - what happens if the request is not an AJAX request?\nelse\n{\n    ncms = ncms.Take(1000); // eg, limit to first 1000 rows\n}\n\nreturn PartialView("BuscarNcm", ncms.ToList()); // finally here we execute the query before going to the View	0
25081860	25081766	Read from a JSON file inside a project	using (StreamReader r = new StreamReader(Application.StartupPath + @"/Resources/Settings.json"))	0
26098538	26098291	How to update Checkbox value in dataGridView?	CHECK_LAB.Checked = bool.Parse(dataGridView1.CurrentRow.Cells[3].Value.ToString());	0
5534225	5509172	Apply mask to a string	MaskedTextBox mtb = new MaskedTextBox("FR999_999999");\n        mtb.Text = "123456789";\n        return mtb.Text;	0
10105359	10084824	Reading 2D Barcode from Images	using DataMatrix.net;               // Add ref to DataMatrix.net.dll\n  using System.Drawing;               // Add ref to System.Drawing.\n  [...]\n\n  // ---------------------------------------------------------------\n  // Date      180310\n  // Purpose   Get text from a DataMatrix image.\n  // Entry     sFileName - Name of the barcode file (PNG, + path).\n  // Return    The text.\n  // Comments  See source, project DataMatrixTest, Program.cs.\n  // ---------------------------------------------------------------\n  private string DecodeText(string sFileName)\n  {\n      DmtxImageDecoder decoder = new DmtxImageDecoder();\n      System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(sFileName);\n      List<string> oList = decoder.DecodeImage(oBitmap);\n\n      StringBuilder sb = new StringBuilder();\n      sb.Length = 0;\n      foreach (string s in oList)\n      {\n          sb.Append(s);\n      }\n      return sb.ToString();\n  }	0
10766083	10765904	How to access all the elements within PhoneApplicationPage?	LoopThroughControls(LayoutRoot);\n\nprivate void LoopThroughControls(UIElement parent)\n{\n  int count = VisualTreeHelper.GetChildrenCount(parent);\n  if (count > 0)\n  {\n    for (int i = 0; i < count; i++)\n    {\n      UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);\n      string childTypeName = child.GetType().ToString();\n      LoopThroughControls(child);\n    }\n  }\n}	0
1556847	1556778	How to use a Distinct on a column using Linq	var query = from row1 in table.AsEnumerable()\n                     let time = row1.Field<DateTime>("time")\n                     let uri = row1.Field<string>("cs-uri-stem")\n                     let ip = row1.Field<string>("c-ip")\n                     let questionid = row1.Field<int>("questionid")\n                     where questionid == int.Parse(table.Rows[x]["questionid"].ToString())\n                     group by ip into g\n                     select new\n                     {\n                         time = g.time.First(),\n                         uri = g.uri.First(),\n                         ip = g.Key,\n                         questionid = g.questionid.First()\n                     };	0
27830355	27830337	Replace String with Dictionary c#	var args = new Dictionary<string, string> {\n   {"text1", "name"},\n   {"text2", "Franco"}\n};\n\nsaveText(Regex.Replace("Hi, my {text1} is {text2}.", @"\{(\w+)\}", m => {\n    string value;\n    return args.TryGetValue(m.Groups[1].Value, out value) ? value : "null";\n}));	0
4959948	4959739	How do I return an entity that is a query of multiple tables	userA.Cars.Load()	0
30835503	30835280	C# get object from asyncron task	var results =\nListOfAllDirs\n.AsParallel()\n.Select(dir => new { dir, result = yr.LoadAllFiles(dir) })\n.ToList();	0
1461745	1461723	Setting user account in IIS 6.0 application pool	InvokeSet("WAMUserName", new Object[] { "username" })	0
16977281	16976618	How to make static method thread safe?	static readonly object _lock = new object();\n    static SomeClass sc = new SomeClass();\n    static void workerMethod()\n    {\n        //assuming this method is called by multiple threads\n\n        longProcessingMethod();\n\n        modifySharedResource(sc);\n    }\n\n    static void modifySharedResource(SomeClass sc)\n    {\n        //do something\n        lock (_lock)\n        {\n            //where sc is modified\n        }\n    }\n\n    static void longProcessingMethod()\n    {\n        //a long process\n    }	0
2017929	2017928	How to write this query as lambda expression?	dc.Category.Select(q => new CategoryContainer {\n                       IDCategory = q.IDCategory,\n                   }).ToList();	0
5617172	5617134	how to read an Image from the Database	public class Images\n{\n string imageFilename = null;\n byte[] imageBytes = null;\n SqlConnection imageConnection = null;\n SqlCommand imageCommand = null;\n SqlDataReader imageReader = null;\n public Images() \n {\n    imageConnection = new SqlConnection("server=      (local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");\n   imageCommand = new SqlCommand(@"select imagefile, imagedata from imagetable",        imageConnection);\n  imageConnection.Open();\n  imageReader = imageCommand.ExecuteReader();   }\n\n\npublic Bitmap GetImage() \n{\n  MemoryStream ms = new MemoryStream(imageBytes);\n  Bitmap bmap = new Bitmap(ms);\n  return bmap;\n}\npublic string GetFilename() \n{\n  return imageFilename;\n}\npublic bool GetRow() \n{\n  if (imageReader.Read())\n {\n    imageFilename = (string) imageReader.GetValue(0);\n    imageBytes = (byte[]) imageReader.GetValue(1);\n    return true;\n }\n else\n {\n    return false;\n }\n}\npublic void EndImages() \n{\n  imageReader.Close();\n  imageConnection.Close();\n}	0
9203669	9200314	How to get the last taken picture	WIA.CommonDialog dialog = new WIA.CommonDialog();\nWIA.Device camera = dialog.ShowSelectDevice(WIA.WiaDeviceType.CameraDeviceType, false, true);\nWIA.Item takenItem = camera.ExecuteCommand("{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}");\n\nforeach (string formatId in takenItem.Formats)\n{\n    if (Guid.Parse(formatId) == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)\n    {\n        WIA.ImageFile wiaImage = takenItem.Transfer(formatId);\n\n        var imageData = new MemoryStream( wiaImage.FileData.get_BinaryData());\n        var image = Image.FromStream(imageData);\n        //pictureBox1.Image = image;\n    }\n}	0
13185973	13185317	How can I load list of child elements from XML?	XElement myElement = XElement.Load("Inquiries.xml");\nvar query = from s in myElement.Elements("Inquiry")\n            select new\n            {\n                InquiryId = Convert.ToInt32(s.Element("InquiryId").Value),\n                FirstName = s.Element("FirstName").Value,\n                LastName = s.Element("LastName").Value,\n                LineItems = (from l in s.Element("LineItems").Elements("LineItem")\n                            select new\n                            {\n                                Quantity = Convert.ToInt32(l.Attribute("quantity").Value),\n                                PartNumber = l.Attribute("partnumber").Value\n                            }).ToList()\n\n            };\n\nvar result = query.ToList();	0
4970937	4970854	Validating uploaded images in mvc 3 with IValidatableObject	public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) \n{\n  ValidationResult result = null;\n  try\n    {\n        var img = System.Drawing.Image.FromStream(this.ImageFile.InputStream);\n        if (img.Width != 200) \n            result = new ValidationResult("This picture isn't the right size!!!!");\n    }\n    catch (Exception ex)\n    {\n        result = new ValidationResult("This isn't a real image!") ;\n    }\n\n  if (result != null) \n    yield return result;\n}	0
9311750	9310458	NServiceBus newbie - how do I force generic host to load first subscribers, then handle messages?	Bus.Send()	0
13428453	13425210	Is there a way I can force Telerik RadGrid to always show 5 rows regardless of my datasource has that much rows	protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)\n{\n    String ConnString = @"Data Source=J-PC\SQLEXPRESS;Initial Catalog=AdventureWorks2012;Integrated Security=True";\n    SqlConnection conn = new SqlConnection(ConnString);\n    SqlDataAdapter adapter = new SqlDataAdapter();\n    adapter.SelectCommand = new SqlCommand("select top 3 AddressID,AddressLine1,City,StateProvinceID,PostalCode from Person.Address ", conn);\n\n    DataTable myDataTable = new DataTable();\n\n    conn.Open();\n    try\n    {\n        adapter.Fill(myDataTable);\n    }\n    finally\n    {\n        conn.Close();\n    }\n\n    if(myDataTable.Rows.Count < 5)\n    {\n        DataRow dr = null;\n        for (int i = 0; i <= 5-myDataTable.Rows.Count ; i++)\n        {\n            myDataTable.Rows.Add(new object[]{});\n        }\n    }\n\n    RadGrid1.DataSource = myDataTable;\n}	0
16976844	16976817	Implementing two interfaces having the same function in c#	class TestClass : TestInterface, TestInterface2\n    {\n        void TestInterface.testMethod()\n        {\n\n        }\n\n        void TestInterface2.testMethod()\n        {\n        }\n    }	0
31956904	31956567	Using array to show order of the same RadioButtonList items randomly	private void Page_Load()\n{\n    if (!IsPostBack)\n    {\n        // your randomize code\n    } else {\n        // retrieve the selected item, but don't randomize the items again.\n    }\n}	0
13538398	13538372	Creating an object instance with a button click	BankAccount account = null;\n\npublic void Continue_onClickHandler(EventArgs e) {\n  account = new BankAccount();\n}\n\npublic void RecordTransaction_onClickHandler(EventArgs e) {\n  if (account == null) {\n     throw new Exception("BankAccount has not been instantiated");\n  }\n\n  // do whatever you need to do with account here\n}	0
8215402	8215315	RegularExpression C#, matching group	text = Regex.Replace(\n      text,\n      @"^```c#\r?\n(.*?)```\r?\n", "$1",\n      RegexOptions.Singleline | RegexOptions.Multiline);	0
13754457	13753228	DataContext values in view code behind	var viewModel = (MyViewModel)DataContext;\n\nforeach (var currency in viewModel.Currencies)\n{\n    ...\n}	0
22452942	22452579	How to read xml file c#	XDocument doc = XDocument.Load(xmlFileName);\nXNamespace ns = "http://www.example.org/genericClientProfile";\n\nvar header = doc.Descendants(ns+"header").Single();\n\nH_HEADER header = new H_HEADER();\n\nheader.SERVICEID    = (string)   header.Element(ns + "serviceId");\nheader.VERSIONID    = (double)   header.Element(ns + "versionId");\nheader.BRANDCODE    = (string)   header.Element(ns + "brandCode");\nheader.CREATIONTIME = (DateTime) header.Element(ns + "creationTime");	0
17811288	17787147	Gridview rebind data with new parameters	protected void ReBind(String sParameter)\n{\n   SqlDataSource.SelectParameters.Remove(SqlDataSource.SelectParameters["parameterName"]);\n   SqlDataSource.SelectParameters.Add("parameterName", sParameter);\n   myGridView.DataBind();\n}	0
6330893	6330678	Xpath for element with colon in element name	foreach (XmlNode targetScopeNode in fedMetaDocument.GetElementsByTagName("Address"))\n{\n  targetScopeNode.InnerText = tsakListUrl;\n}	0
18526311	18526192	How to set the background color on a gridview row	if(Condidtion)\n  {\n      e.Row.BackColor =somecolor;\n  }	0
30919343	30918862	Populate DropDownList in Column within grid's ItemDataBound event without accessing the database each time	private IEnumerable<ProductCategory> productCategoryList;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n         productCategoryList = ProductService.GetProductCategories();\n    }\n}	0
2801448	2801264	How to prevent MDI main form closing from MDI Child	private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n    if (e.CloseReason == CloseReason.UserClosing)\n    {\n        foreach (Form frm in this.MdiChildren)\n        {\n            frm.Close();\n        }\n    }\n    e.Cancel = (this.MdiChildren.Length > 0);\n}	0
15852678	15852590	moving a picture box to random X and Y when a timer ticks	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;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        public Random r = new Random();\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n            int x = r.Next(0,925);\n            int y = r.Next(0,445);\n            pictureBox1.Top = y;\n            pictureBox1.Left = x;\n        }\n    }\n}	0
3212723	3212694	c# remove hint over datagridview	dataGrid.ShowCellToolTips = false	0
11203989	11203755	discard file extensions in compressing all from directory using SharpCompress	using (var zip = File.OpenWrite("C:\\test.zip"))\n  using (var zipWriter = WriterFactory.Open(ArchiveType.Zip, zip))\n  {\n\n  FileInfo[] fi = Directory.GetFiles(folderPath);\n  foreach(var f in fi)\n  {\n    if(f.Extension != ".dll")\n      zipWriter.Write(Path.GetFileName(file), filePath);\n  }\n\n}	0
29761514	29761501	implicit and explicit conversion	List<string> listcom = (List<string>)arg[1];	0
32553554	32553411	C# - How to detect + and = pressed characters	if ( e.Shift )  \n{ \n   // the key is +  \n}\nelse \n{ \n  //  the key is = \n}	0
9986684	9986650	wpf canvas background image dynamically	ImageBrush ib = new ImageBrush();\nib.ImageSource = new BitmapImage(new Uri(@"sampleImages\berries.jpg", UriKind.Relative));\nmycanvas.Background = ib;	0
17404676	17404603	c# sorting data from an adjacency tree	IEnumerable<TreeNode> TreeOrder(\n    IEnumerable<TreeNode> nodes)\n{\n    //Find the root node\n    var root = nodes.Single(node => node.parent == null);\n\n    //Build an inverse lookup from parent id to children ids\n    var childrenLookup = nodes\n        .Where(node => node.parent != null)\n        .ToLookup(node => node.parent.Value);\n\n    return TreeOrder(root, childrenLookup);\n}\n\nIEnumerable<TreeNode> TreeOrder(\n    TreeNode root,\n    ILookup<Guid, TreeNode> childrenLookup)\n{\n    yield return root;\n\n    if (!childrenLookup.Contains(root.id))\n        yield break;\n\n    foreach (var child in childrenLookup[root.id])\n        foreach (var node in TreeOrder(child, childrenLookup))\n            yield return node;\n}	0
4484257	4484208	Modify a character before it reaches a TextBox	if (e.KeyCode == Keys.Decimal)\n{\n    e.Handled = true;\n    e.SuppressKeyPress = true;\n    SelectedText = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;\n}\nelse base.OnKeyDown(e);	0
5421081	5413123	StretchRectangle on surface from one device to another	byte[] data = new byte[surfaceByteCount];\nGraphicsStream sourceStream = sourceSurface.LockRectangle(area, LockFlags.ReadOnly);\nsourceStream.Read(data, 0, data.Length);\nsourceSurface.UnlockRectangle();\n\nGraphicsStream targetStream = targetSurface.LockRectangle(area, LockFlags.Discard);\ntargetStream.Write(data, 0, data.Length);\ntargetSurface.UnlockRectangle();\n\ndevice.Present();	0
13091129	13091029	Update EF from an object	var cachedHotel = context.Hotels.Local\n    .FirstOrDefault(h => h.id = editedHotel.id);\nif (cachedHotel != null)\n{\n  context.Hotels.Detach(cachedHotel);\n}\ncontext.Hotels.Attach(editedHotel);\ncontext.Entry(editedHotel).State = System.Data.EntityState.Modified;\ncontext.SaveChanges();	0
13494476	13473281	Update the sqlite from datagrid using c#	private void button3_Click(object sender, EventArgs e)\n    {\n        DataTable dt = dataGridView.DataSource as DataTable;\n        for (int i = 0; i < dt.Rows.Count; i++)\n        {\n            if (dt.Rows[i].RowState == DataRowState.Modified)\n            {\n                MessageBox.Show(dt.Rows[i][3].ToString());\n            }\n        }	0
27404556	27402685	Instantiate gameobject from a script that is on that gameobject	//The canvas is at the path "Assets/Resources/canvas".\n\nfunction Start () { \n    your_canvas = Instantiate(Resources.Load("canvas")); \n}	0
29627838	29627595	Testing for last entry blank objects in a DataGridView	public string sum()\n    {\n        double sum = 0;\n        string test;\n        for (int i = 0; i < dataGridView1.Rows.Count; ++i)\n        {\n            if (dataGridView1.Rows[i].Cells[6].Value != null)\n            {\n                test = dataGridView1.Rows[i].Cells[6].Value.ToString();\n\n                if (test != "")\n                {\n                    sum += double.Parse(test);\n                }\n            }                \n        }\n        return sum.ToString();\n    }	0
16710939	16710488	Multibinding: two colums to one column	public object ValueAorB\n{\n    get\n    {\n        if (values[0] != DependencyProperty.UnsetValue && values[0] != null && !string.IsNullOrEmpty(values[0].ToString()))\n        {\n            Debug.WriteLine("values 0: " + values[0]);\n            return values[0].ToString();\n        }\n        if (values[1] != DependencyProperty.UnsetValue && values[1] != null && !string.IsNullOrEmpty(values[1].ToString()))\n        {\n            Debug.WriteLine("values 1: " + values[1]);\n            return values[1].ToString();\n        }\n    }\n}	0
8349722	8349681	Need info on Parsing XML in .NET 4	var updates = from x in xmlDoc.Root.Element("ProgList").Elements("update")\n              select new\n              {\n                  seq = (int)x.Attribute("sequence"),\n                  amt = (int)x.Attribute("amount"),\n                  lvl = (int)x.Attribute("Lvl"),\n                  grp = (int)x.Attribute("Grp"),\n              };	0
5014731	5014705	How do I find if the file MyFile.03 is in the folder MyTmpFolder?	System.IO.File.Exists("MyTempFolder\\MyFile.02");	0
6723106	6723023	Determining when Listbox has finished loading bound elements	public MyWindow()  \n{  \n    InitializeComponent();  \n\n    ((INotifyCollectionChanged)ListBox.Items).CollectionChanged +=  \n        ListBox_CollectionChanged;  \n}  \n\nprivate void ListBox_CollectionChanged(object sender,   \n    NotifyCollectionChangedEventArgs e)  \n{  \n    if (e.Action == NotifyCollectionChangedAction.Add && ListBox.SelectedItem == null)\n    {\n        ListBox.SelectedItem = e.NewItems[0];\n    }      \n}	0
29033962	29033554	Change value in DataGridView without VirtualMode	private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (e.ColumnIndex != 2) // enum value column\n        return;\n\n    var grid = (DataGridView)sender;\n    MyEnum val = (MyEnum)grid[e.ColumnIndex, e.RowIndex].Value;\n    switch (val)\n    {\n        case MyEnum.Val1: e.Value = "Translation1"; break;\n        case MyEnum.Val2: e.Value = "Translation2"; break;\n    }\n\n    e.FormattingApplied = true;\n}	0
19779157	19779013	Regex to capture parenthesis with hash tag?	\(?#(\w*[A-Za-z_]+\w*)\)?	0
7905571	7893302	Capture Screenshot of entire page with Selenium in IE9	IWebDriver driver;\ndriver = new InternetExplorerDriver();\n// change this line if you want to use an different Browser / WebDriver Implementation\n//driver = new FirefoxDriver();\ndriver.Navigate().GoToUrl("http://www.google.com/");\nIWebElement query = driver.FindElement(By.Name("q"));\nquery.SendKeys("Cheese");\n// TODO: wait\n((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(@"screenIE.png", ImageFormat.Png);	0
7836324	7836163	Finding MAX date in LINQ query join	return (from t1 in db.BU\n            from t2 in db.UserNames\n             .Where(t => (t.User_Username == t1.Username))\n            from t3 in db.Logins\n            .Where(t => (t.username == t1.Username))\n            .OrderBy(u => u.timestamp).First()           // <--------- add this\n            where myBusinessUnits.Contains(t1.BusinessUnit_ID)\n            orderby (t2.Name) descending\n            select new GlobalMyTeamDetailModel\n            {\n                 LastLogin = t3.timestamp,\n                 Name = t2.Name\n\n            });	0
10303655	10303459	How to use SQL Server stored procedure numeric parameter in c#	SqlParameter param = new SqlParameter("@OMarks", SqlDbType.Decimal);\nparam.Direction = ParameterDirection.Output;\nparam.Precision = 3;\nparam.Scale = 1;\ncmd.Parameters.Add(param);	0
9684261	9684112	Start a long time background task	var task = Task.Factory.StartNew(Stuff, TaskCreationOptions.LongRunning);	0
13247392	13247347	Converting Decimal to less accurate Integer as a String	var result = ((Int64)(someDecimal * 1024 * 1024 * 1024)).ToString();	0
31986777	31969848	How to play mp3 memorystream with html5 in asp.net mvc	[HttpGet]\n    public ActionResult GetVnAudioStream(int id)\n    {\n        if (id > 0)\n        {\n            var pronunciation = babbelerRepo.GetVnPronunciationById(id);\n            if (pronunciation != null && pronunciation.Length > 0)\n            {\n                return File(pronunciation, "audio/mp3");\n            }\n        }\n        return null;\n    }	0
13967061	13966722	Need to redirect user from .aspx page to MVC route url	Response.Redirect("/");	0
9404211	9404182	Cutting a String before a special character everytime in C#	string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));	0
8104163	8104158	Population of ComboBox with DisplayMember and ValueMember	try  comboProject.DataSource = ds.Tables["FillDropDown"].DefaultView;	0
701716	701697	Need to use win32 api to copy files in c# - how do I do this?	[DllImport("kernel32.dll",\n           CharSet = CharSet.Unicode,\n           CallingConvention = CallingConvention.StdCall,\n           SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool CopyFile(\n                   [MarshalAs(UnmanagedType.LPStr)] string lpExistingFileName,\n                   [MarshalAs(UnmanagedType.LPStr)] string lpNewFileName,\n                   [MarshalAs(UnmanagedType.Bool)] bool bFailIfExists);	0
27947053	27174270	NHibernate 4 upgrade - Cannot simultaneously fetch multiple bags	var IdsList = new List { /* Some Ids */ };\nvar results = session.Query<A>()\n    .FetchMany(x => x.B_ObjectsList)\n    .Where(x=>IdsList.Contains(x.Id))\n    .ToList();\n\n// initialize C_ObjectsList\nvar bIds = results.SelectMany(x => x.B_ObjectsList).Select(b => b.Id).Distinct().ToList();\nsession.Query<B>()\n    .FetchMany(x => x.C_ObjectsList)\n    .Where(b => bIds.Contains(b.Id))\n    .ToList();\n\nreturn results;	0
31700400	30941765	Search and Add Comment with OpenXML for Word	Paragraph p = Body.Descendants<Paragraph>().Where(p.InnerText.Contains(searchString)).FirstOrDefault();\nif (p != null)\n{\n    // Here follow the link Ron post to create a comment\n    // insert the comment into p with p.InsertAfter() as said in the link\n}	0
4532203	2041765	Prism for Silverlight: How to maintain views in a specific order inside a region	[ViewSortHint("100")]\nclass FirstView : UserControl { }\n\n[ViewSortHint("200")]\nclass SecondView : UserControl { }	0
14157821	12136611	Can I pass a different value as a input from using button but display something else in MVC3	href="/Page/Method/@s.ID"	0
6544089	6542163	Create Clapper software with Naudio	for (int n = 0; n < e.BytesRecorded; n += 2)\n{\n    short sampleValue = BitConverter.ToInt16(e.Buffer, n);        \n}	0
30968843	30968768	Highlight specific string in listbox	index1=_playList.Items.IndexOf(curItem);\n    if(index1 >= 0)\n    {\n    _playList.SetSelected(index1, true);\n    }	0
25092649	25092595	Handle null Json Value in C#. How to handle it here?	foreach (KeyValuePair<string, object> obj in mainList[i])\n{\n    PList[i].Add(obj.Value == null ? "Null" : obj.Value.ToString());\n}	0
10875655	10875644	Create a custom selection of parameters	public enum MyOption\n{\n    Option1,\n    Option2,\n    Option3,\n}\n\npublic void MyMethod(MyOption option)\n{\n    switch (option)\n    {\n        case MyOption.Option1:\n            // do stuff\n            return;\n        case MyOption.Option2:\n            // do stuff\n            return;\n        case MyOption.Option3:\n            // do stuff\n            return;\n    }\n}	0
8608528	8608489	.NET Convert from string of Hex values into Unicode characters (Support different code pages)	Encoding.{YourEncoding}.GetChars(hexBytes);	0
11920645	11920585	Split an array only every third time, when the split char appears	public void Foo(string content)\n{\n    var entries = content.Split('|');\n\n    for(int i = 0; i < entries.Length; i += 3)\n    {\n        var text = entries[0 + i];\n        var name = entries[1 + i];\n        var date = entries[2 + i];\n\n        // TODO: add values to listview.\n    }\n}	0
3009404	3009284	Using RegEx to replace invalid characters	string pattern = "[\\~#%&*{}/:<>?|\"-]";\nstring replacement = " ";\n\nRegex regEx = new Regex(pattern);\nstring sanitized = Regex.Replace(regEx.Replace(input, replacement), @"\s+", " ");	0
32243500	32243372	Binding to simple properties in WPF DataGrid	public class ErrorSeverityConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        Severity severity = (Severity)value;\n        switch(severity)\n        {\n            case Severity.Unknown:\n                return "/error.jpg";\n\n            case Severity.Ok:\n                return "/ok.jpg";\n        }\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        throw new NotImplementedException();\n    }\n}	0
23716157	23710415	C# Populate generated datagrid using Selenium WebDriver	Actions actions = new Actions(driver);\nactions.SendKeys(Keys.Tab).Build().Perform();\nactions.SendKeys("text to enter").Build().Perform();	0
11442999	11435073	Set DataGridView rows after all are created to stop refresh	//Set up the DataGridView either via code behind or the designer\nDataGridView dgView = new DataGridView();\n\n//You should turn off auto generation of columns unless you want all columns of\n//your bound objects to generate columns in the grid\ndgView.AutoGenerateColumns = false; \n\n//Either in the code behind or via the designer you will need to set up the data\n//binding for the columns using the DataGridViewColumn.DataPropertyName property.\nDataGridViewColumn column = new DataGridViewColumn();\ncolumn.DataPropertyName = "PropertyName"; //Where you are binding Foo.PropertyName\ndgView.Columns.Add(column);\n\n//You can bind a List<Foo> as well, but if you later add new Foos to the list \n//reference they won't be updated in the grid.  If you use a binding list, they \n//will be.\nBindingList<Foo> listOfFoos = Repository.GetFoos();\n\ndgView.DataSource = listOfFoos;	0
5017359	5017291	Passing parameters to the constant buffer in SlimDX Direct3D 11	context.PixelShader.SetConstantBuffer(buffer, 0)	0
1543696	1543611	How can you coalesce a datetimeoffset in Linq to SQL?	orderby (item.Date.HasValue ? item.Date : DateTimeOffset.MaxValue) descending	0
13397465	13362663	Webkit embedded browser disable cookies	Application.Exit();	0
9170487	9170406	select random char in string by Index	bool delt1, deltJ, deltQ, deltK, deltA;\nif (card.Length >= 2)\n{\n    delt1 = card[1].Equals('1');\n    deltJ = card[1].Equals('J');\n    deltQ = card[1].Equals('Q');\n    deltK = card[1].Equals('K');\n    deltA = card[1].Equals('A');\n}\nelse\n    throw new Exception("Not enough characters in card to perform this check");	0
12971023	12970947	Add dropdownlist value to database which items add from page load functions	if (!IsPostBack)\n{\n    foreach(pair item in al)  \n    {           \n        pid.Items.Add(new ListItem(item.getTitle(), item.getId()));\n\n    }  \n}	0
21057566	21057404	Convert Date into JSON object in c#	double ticks = Math.Floor(objRemarkData.Date.ToUniversalTime() \n        .Subtract(new DateTime(1970, 1, 1))      \n        .TotalMilliseconds); \nvar newob = new { Date =ticks, Remark = objRemarkData.Remark};\nJS.GetJSON(newob);	0
31671936	31671426	Retrieve Data From Previous Page	protected void Page_Load(object sender, EventArgs e)\n {\n     if (txtData1.Text == string.Empty && Session["pg1"] != null)\n      {\n         txtData1.Text = Session["pg1"].ToString();\n      }\n  }	0
17099646	17099327	How do I run a profile migration using FluentMigrator?	IRunnerContext migrationContext = new RunnerContext(announcer);\nmigrationContext.Profile = "DevMigrator"	0
8995657	8995485	Which C# data structure allows searching a pair of strings most efficiently for substrings?	(ideally, but not required) ELEM will return 291 156TH ELEMENT.	0
22784542	22782996	Loss of Precision from C# to SQL Server	static void Main(string[] args)\n    {\n        decimal d = 34.09090909090909M;\n        Console.WriteLine(d);\n\n        SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();\n        scsb.IntegratedSecurity = true;\n        scsb.DataSource = @".\sql2012";\n\n        using (SqlConnection conn = new SqlConnection(scsb.ConnectionString)) {\n            conn.Open();\n\n            using (SqlCommand cmd = new SqlCommand(\n               "select cast(@d as DECIMAL(20,15))", conn))\n            {\n                cmd.Parameters.AddWithValue("@d", d);\n                decimal rd = (decimal) cmd.ExecuteScalar();\n                Console.WriteLine(rd);\n            }\n        }\n    }	0
10102938	10102813	Getting data into dataGridView	dataGridView1.DataSource = ds.Tables[0];	0
31319620	31319324	How to run web application from a console application in c#	string url = "http://localhost:23423";\nSystem.Diagnostics.Process.Start(url);	0
7840198	7839477	How do i get all public pages in DotNetNuke?	var tabs = TabController.GetTabsByParent(-1, PortalId);\n            foreach (var t in tabs)\n            {\n                if (t.IsVisible)\n                {\n                    Response.Write(t.TabName);\n                    Response.Write("<br />");\n                }\n            }	0
12213789	12213732	How can I compare value from c#(viewbag) in javascript?	var myBoolValue = @Viewbag.MyBoolValue.ToString().ToLower();\nif (myBoolValue)\n    do_sth();	0
20746935	20622141	Populating a C# TreeView with a DataTable	DataRow root = myDataTable.Rows[0];\ntreeView.Nodes.Add(root["ID"].ToString(), root["Name"].ToString());\n\nfor (int i = 1; i < table.Rows.Count; i++)\n{\n    DataRow parentRow = myDataTable.Rows.Find(myDataTable.Rows[i]["ParentID"]);\n    TreeNode[] parent = treeView.Nodes.Find(parentRow["ID"].ToString(), true);\n    parent[0].Nodes.Add(myDataTable.Rows[i]["ID"].ToString(), myDataTable.Rows[i]["Name"].ToString());\n}	0
11312277	11312223	How to convert ref byte into byte[]?	pinned( byte* p = &buffer ) {\n    buffer[4] = 0;\n}	0
12498063	12498035	Need help refining my RegEx for C# style double slash comments	(?![\n\r])\s?//.*?$	0
26644606	26644363	Explicit interface implementation related with an IEnumerable<T> implementation?	// Must implement GetEnumerator, which returns a new StreamReaderEnumerator. \n\npublic IEnumerator<string> GetEnumerator()\n{\n    return new StreamReaderEnumerator(_filePath);\n}\n\n// Must also implement IEnumerable.GetEnumerator, but implement as a private method. \n\nIEnumerator IEnumerable.GetEnumerator()\n{\n    return GetEnumerator();\n}	0
6348943	6348699	Keyword proximity matching - options?	private static void GetMatches (string s)\n{\n   string[] keywords = {"if", "while", "do"};\n   int x = 3; // words before and after\n   string ex =\n      @"(\w+\W+){0," + x + @"}\b(" + string.Join("|", keywords) + @")\b\W+(\w+\W+){0," + x + @"}";\n   Regex regex = new Regex(ex);\n   List<string> matches = new List<string>();\n   foreach (Match match in regex.Matches (s))\n   {\n      matches.Add(match.Value);\n   }\n}	0
9680250	9522895	How to prevent ?Area= from being added to generated URLs	result.RouteValueDictionary.Add("Area", area ?? "");	0
2973360	2973306	C# - Is there any string representation of DateTime.Now()?	public DateTime GetDateTime(string value)\n{\n  if (string.IsNullOrEmpty(value))\n    return DateTime.MinValue;\n\n  if ("{now}".Equals(value, StringComparison.InvariantCultureIgnoreCase))\n    return DateTime.Now;\n\n  return DateTime.Parse(value);\n}	0
12527299	12527254	Skip data when reading a text file	var linesContainsE = File.ReadAllLines(filename)\n    .Where(line => line.Contains("E"))\n    .ToList();	0
26187087	26186742	How to I initialize	Item = new Item\n        {\n            ItemType = "defects",\n            Id = 31\n        }	0
20914275	20914230	How to prevent a Windows Form from being sent to the back or how to keep it on a specific z-order	Form3 obj3 = new Form3();\nprivate void button1_Click(object sender, EventArgs e)\n{\n    if (obj3 != null && obj3.Visible) { obj3.Focus(); return; }\n\n    obj3 = new Form3();\n    obj3.Show(this);            \n}	0
12256906	12256812	Read each file inside different directories stored in an array	string files = "C:\Hello; C:\Hi; D:\Goodmorning; D:\Goodafternoon; E:\Goodevening";\n//Get each path and remove whitespaces\nstring[] paths = files.Split(new[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);\n//Use xmlLoc for adding \ to each file\nList<string> xmlLoc = new List<string>();\n//get the files in directories\nstring[] getFiles;\n\n//Add \ each paths variable and store it in xmlLoc list\nforeach (string s in paths)\n{\n     xmlLoc.Add(s + @"\");\n}\n\n//get the xml files of each directory in xmlLoc and loop it to read the files\nforeach (string directory in xmlLoc)\n{\n     getFiles = Directory.GetFiles(directory, "*.xml");\n     foreach(string files in getFiles)\n     {\n         MessageBox.Show(files);\n     }\n}	0
6905208	6904857	Fetch values from a JSON response in c#	string json = @"{\n  ""Name"": ""Apple"",\n  ""Expiry"": new Date(1230422400000),\n  ""Price"": 3.99,\n  ""Sizes"": [\n    ""Small"",\n    ""Medium"",\n    ""Large""\n  ]\n}";\n\nJObject o = JObject.Parse(json);\n\nstring name = (string)o["Name"];\n// Apple\n\nJArray sizes = (JArray)o["Sizes"];\n\nstring smallest = (string)sizes[0];\n// Small	0
15727760	15703913	How to apply substring-after and substring-before functions	string _result1 = <HtmlNodeNavigator>.Evaluate("substring-after(.//*[contains(@class, 'opps')]/text(), ':')") as string; \nstring _result2 = <XPathNavigator>.Evaluate("substring-before(.//*[contains(@class, 'opps')]/text(), ':')") as string;	0
31410470	31410361	How to calculate percentage in c#	var value = ((double)fsize / tsize) * 100;\nvar percentage = Convert.ToInt32(Math.Round(value, 0));	0
9260554	9216533	How to get Screenshot of WPF Webrowser Control?	PrintDialog p = new PrintDialog();\np.PrintVisual(webBrowser1,"webBrowser1");	0
33792985	33771148	Entity Framework - Including Collections on Derived from Base DBSet	db.Bases\n  .TypeOf<Derived>()\n  .Include(d => d.Lookup)\n  .Where(d => d.Id = someId)\n  .ToList();	0
26529075	26528976	Deserialize JSON Array to object	public IList<Notifications> Notes;\n\nNotes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);	0
10464483	10464401	Create a new object given the Type as a string?	Namespace.MyClass obj = (Namespace.MyClass)Activator.CreateInstance(typeof(Namespace.MyClass), new[] { param1, param2});	0
10394699	10394680	How to create dynamic datatable?	private static DataSet SampleData()\n    {\n        DataSet sampleDataSet = new DataSet();\n        sampleDataSet.Locale = CultureInfo.InvariantCulture;\n        DataTable sampleDataTable = sampleDataSet.Tables.Add("SampleData");\n\n        sampleDataTable.Columns.Add("FirstColumn", typeof(string));\n        sampleDataTable.Columns.Add("SecondColumn", typeof(string));\n        DataRow sampleDataRow;\n        for (int i = 1; i <= 49; i++)\n        {\n            sampleDataRow = sampleDataTable.NewRow();\n            sampleDataRow["FirstColumn"] = "Cell1: " + i.ToString(CultureInfo.CurrentCulture);\n            sampleDataRow["SecondColumn"] = "Cell2: " + i.ToString(CultureInfo.CurrentCulture);\n            sampleDataTable.Rows.Add(sampleDataRow);\n        }\n\n        return sampleDataSet;\n    }	0
13819093	13818994	File being used (without opening it) c#	// Load image\nFileStream filestream;\nfilestream = new FileStream("Filename",FileMode.Open, FileAccess.Read);\ncurrentImage = System.Drawing.Image.FromStream(filestream);\nfilestream.Close();	0
3934566	3933495	Search a MembershipUserCollection	Dim UserRoles As String() = Roles.GetUsersInRole(ddlusertype.SelectedItem.Text) \n\nDim users = From a In UserRoles Where a.Contains(textbox1.text)\n\nDim mem As MembershipUser = Nothing\nDim dt As New MembershipUserCollection\n\n For Each Str As String In users\n      mem = Membership.GetUser(Str)\n      dt.Add(mem)\n next	0
17835824	17835747	Sqlite taking too long to fetch pictures	CREATE INDEX record_id_index ON tbl_pictures(record_id);	0
10450242	10450129	Converting a C++ program into C#	#include	0
25330032	25251094	Stopping Screen Timingout - windows phone 8.1	DisplayRequest displayRequest;\n\npublic MainPage()\n    {\n        displayRequest = new Windows.System.Display.DisplayRequest();\n        displayRequest.RequestActive(); \n...	0
33669443	33669306	Parse LINQ answer in a JSON	var Agr = (from P in database.AGR_FACTURACION\n          where P.DIM_FECHA > 201501\n          select new { P.DIM_FECHA, P.FCT_TOTALFACT}\n          ).ToArray();\n\nvar result = new {DIM_FECHA = Agr.Select(o=>o.DIM_FECHA), FCT_TOTALFACT = Agr.Select(o=>o.FCT_TOTALFACT)};\n...\nContext.Response.Write(js.Serialize(result));	0
18946111	18907915	How to prevent Fluent NHibernate from adding "Parent" table's FK to relationship tables?	.Override<Plugin>(m => m.HasMany(c => c.Settings).KeyColumn("Plugin_Id"))	0
28130989	28130975	C# - Dictionary<String, Action> No overload for method 'Add' takes 1 arguments	private Dictionary<string, Action> worldPackets = new Dictionary<string, Action>\n{\n    { "jr", User.HandleJoinRoom },\n    { "sm", User.HandleSendMessage },\n    { "cr", User.HandleCreateRoom }\n};	0
23350828	23028816	Download .wav files from OneDrive	var downloadOperationResult = await client.DownloadAsync(v.id+"/content" as string);	0
27859050	27843420	Sort DataGridColumn with null values always at bottom	if (date1.HasValue)\n    return -1;\nreturn 1;	0
12977387	12976860	Find the longest sequence of digits in a string	var t = "sfas234sdfsdf55323sdfasdf23";\n\nvar longest = Regex.Matches(t, @"\d+").Cast<Match>().OrderByDescending(m => m.Length).First();\n\nConsole.WriteLine(longest);	0
33557459	33550912	Using IComponentContext to register new component	var registration = RegistrationBuilder\n                       .ForDelegate<UserSession>((c, p) => userSession)\n                       .ExternallyOwned()\n                       .AsSelf()\n                       .InstancePerRequest()\n                       .CreateRegistration();\ncomponentContext.ComponentRegistry.Register(registration);	0
11006883	11006817	Send plain text to Firefox	firefox.exe "data:text/plain,Lorem ipsum dolor sit amet"	0
18720718	18720599	How to create a property on a dynamic object using reflection	dynamic data = new ExpandoObject();\nvar dataDictionary = (IDictionary<string, object>)data;\n\n//add property\ndataDictionary.Add("Name", "AwkwardCoder");\n\n//access\nvar name = data.Name;	0
20713491	20713371	DataGridView - Fill DataSet with Linq	var results = myCourses.Where(c=>c.ID == courseId);\n\ndgvCourseList.DataSource = results.ToList();	0
14583006	14582185	Set SQL command based on textBox text	SqlCommand comm = new SqlCommand();\ncomm.CommandText = "SELECT [columnA] FROM [DB].[dbo].[TABLE] WHERE value = @value";\ncomm.Parameters.AddWithValue("value", Request.QueryString["string"]);	0
13692637	13692617	How to use multiple conditional operators using C#	if (varRequestedDate != "&nbsp;" \n    && varExpectedDate < varTotdayDate\n    && (Approved1 == "Yes" || Approved2 == "Yes")\n)\n    sendEmail();	0
11488560	11488552	Remove a piece of code after a number of execution?	if (Properties.Settings.Default.alreadyExecuted == false)\n{\n     // run one-time code.\n\n     Properties.Settings.Default.alreadyExecuted = true;\n     Properties.Settings.Default.Save();\n}	0
4901780	4901732	How to mask the value of a member variable in a List of objects using LINQ?	public string MaskedVol\n{\n  get \n  { \n    return (Name.IndexOf("SPECIAL", StringComparison.OrdinalIgnoreCase) != -1 ) ? "--" : Volume.ToString();\n  }\n}	0
5087114	5087084	How to have multiple threads processing the same IEnumerable result?	var result = GetFiles(source);\n\nParallel.ForEach(result, current => {\n    ProcessCopy(current);\n});\n\nConsole.WriteLine("Done");	0
6141240	6141205	Disable Serialization for Specific Property	// Property that I don't want to be serialized.\n[XmlIgnore]\npublic Subscriber Subscriber { get; set; }	0
3187684	3187591	Replacing a Stream with a String in a C# program	string xml;\nusing (StringWriter str = new StringWriter()) {\n  using (XmlTextWriter writer = new XmlTextWriter(str)) {\n    // write the XML\n  }\n  xml = str.ToString();\n}	0
27667429	27667176	How to compare two regex matches?	Dictionary<string, string> dict = new Dictionary<string,string>();\n\n        Regex regex = new Regex(@"S?(\d{1,2})[x|e]?(\d{1,2})", RegexOptions.IgnoreCase);\n        foreach (string file in path)\n        {\n            var match = regex.Match(file);\n            if (match.Success)\n            {\n                string key = "S" + match.Groups[1].Value.PadLeft(2, '0') + "E" + match.Groups[2].Value.PadLeft(2, '0');\n                if (dict.ContainsKey(key))\n                {\n                    // .. already in there\n                }\n                else\n                {\n                    dict[key] = file;\n                }\n            }\n        }	0
32823662	32822382	How to add multiple data from listview to database sql server	if(e.CommandName == "SaveAll")\n{\n    foreach (ListViewItem item in ListViewName.Items)\n    {\n      // Code goes here. You can find control using  e.Item.Findcontrol\n    }\n}	0
14698947	14698879	Http Post for Windows Phone 8	// server to POST to\nstring url = "myserver.com/path/to/my/post";\n\n// HTTP web request\nvar httpWebRequest = (HttpWebRequest)WebRequest.Create(url);\nhttpWebRequest.ContentType = "text/plain; charset=utf-8";\nhttpWebRequest.Method = "POST";\n\n// Write the request Asynchronously \nusing (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,          \n                                                         httpWebRequest.EndGetRequestStream, null))\n{\n   //create some json string\n   string json = "{ \"my\" : \"json\" }";\n\n   // convert json to byte array\n   byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);\n\n   // Write the bytes to the stream\n   await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);\n}	0
7058617	7058439	.NET MVC, Remove information from an object serialized with Json()	var traverse = require('traverse');\n\ntraverse(data).forEach(function (x) {\n    var bUpdate = false;\n    for( var key in x )\n    { \n      if( "" === x[key] )\n      {\n        delete x[key];\n        bUpdate = true;\n      }\n    if( bUpdate )this.update(x + 128);\n});	0
8305606	8305461	Alternatives for generating sql server query from lambda expression	var query = from x in context.cmsSearchLog\n            where totalresults != 0 &&\n                  searchterms.BeginsWith("de")\n            group x by x.searchterms into terms\n            select new {\n                           SearchTerms = terms.Key(),\n                           TotalResults = terms.Max(t => t.totalresults)\n                       };	0
14580612	14580370	POST a List<T> to MVC Controller always null	[\n    {\n        "action": true,\n        "FollowsUserId": 123456777\n    },\n    {\n        "action": true,\n        "FollowsUserId": 123456888\n    }\n]	0
24897474	24896912	Display image in picture box from datagridview_selectionchanged event	private void firearmView_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if (!firearmView.Rows[e.RowIndex].IsNewRow)\n        {\n            selectedFirearmPictureBox.Image = Image.FromFile(firearmView.Rows[e.RowIndex].Cells[12].Value.ToString(), true);\n        }\n    }	0
19729138	19728988	How to get values from returned anonymous type	var obj = CurrentInfo();\nSystem.Type type = obj.GetType();\nstring url = (string)type.GetProperty("URL").GetValue(obj, null);	0
729606	729584	Opening a WPF Window in another Thread from a Windows Forms App	System.Windows.Threading.Dispatcher.Run();	0
33512914	33511900	Control bound to property value doesn't update	set\n{\n    _bold = value;\n     OnPropertyChanged("Bold");\n     NotifyPropertyChanged();\n}	0
26947067	26946755	How to add rows to GridView in asp.net c# application	GridView1.DataSource = null;\nGridView1.Refresh();\nServiceReference1.mojWebServiceSoapClient client = new ServiceReference1.mojWebServiceSoapClient();\nvar userList = client.getUsers();\nDataTable dt = new DataTable();\nDataColumn column = new DataColumn();\ndt.Columns.Add("ID", typeof(Int32));\ndt.Columns.Add("Name", typeof(string));\ndt.Columns.Add("Last Name", typeof(string));\nforeach (var user in userList)\n{\n    DataRow row = dt.NewRow();\n    row[0] = user.userID.ToString();\n    row[1] = user.Name;\n    row[2] = user.lName;\n    dt.Rows.Add(row);\n}\nGridView1.DataSource = dt;\nGridView1.DataBind();	0
4761172	4761136	Copy file to other computer using cmd in C#	File.Copy(@"C:\pic1.png", @"\\SOMECOMP\Users\SOMEONE\Shared\pic1.png", true);	0
27295637	27295265	Delete characters from string between 2 characters	int indexUP = myString.IndexOf('+');\nint indexClose = myString.IndexOf('+', indexUP + 1);\nstring results = myString.Substring(0, indexUP ) + myString.Substring(indexClose).Trim();	0
10103811	10103533	background worker and progress bar implementation for additional column in datagridview?	int cellVal = 0;\nforeach (DataGridViewRow row in dgvStock.Rows)\n{\n    row.Cells[newCol.Name.ToString()].Value = cellVal;\n}	0
5112665	5112642	Getting data from a row in a DataTable?	row.Field<DateTime>("DateOfBirth")	0
32299745	32297378	How can I parameterise Azure's TableOperation.Retrieve<TElement> in a method in c# .NET	public async Task<TableResult> Retrieve<T>(string tableReference, string partitionKey, string rowKey) where T : ITableEntity\n    {\n        var tableClient = storageAccount.CreateCloudTableClient();\n        var table = tableClient.GetTableReference(tableReference);\n        TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);\n        TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);\n        return retrievedResult;\n    }	0
15409082	15407981	Using DataGridView with a BindingList<T> where T is an interface and cross-thread updates	public interface IClass : INotifyPropertyChanged \n    {\n        string Name { get; set;}\n    }\n\n\npublic class MyClass: IClass\n    {\n        private string name;\n\n        public event PropertyChangedEventHandler PropertyChanged;\n\n        public string Name\n        {\n            get { return name; }\n            set\n            {\n                name = value;\n                this.NotifyPropertyChanged("Name");\n            }\n        }\n\n        public MyClass(string name)\n        {\n            this.Name = name;\n        }\n\n        private void NotifyPropertyChanged(string caller = "")\n        {\n            if (PropertyChanged != null)\n            {\n                PropertyChanged(this, new PropertyChangedEventArgs(caller));\n            }\n        }	0
34353420	34353351	How to slow down application?	Thread.sleep(1000); //Wait for a time specified in milliseconds (1000 milliseconds=1 second)	0
16639791	16639720	How to update specific values in XML document with C#	player["WinCount"].InnerText = Form1.winCount.ToString();\nplayer["PlayCount"].InnerText = Form1.playCount.ToString();\nplayer["Balance"].InnerText = Form1.decBalance.ToString();	0
16750926	16750877	C# MySQL SELECT with null	var x = 0050;\n Console.Write(x);\n Console.Write(x.ToString("0000"));	0
17179195	17178866	ListView displays certain images but won't display others	right click project -> add existing item -> select your files -> click OK -> put them in the correct folder -> set build action to Resource	0
30227444	30226970	Escape parts of string with a character in c# using regex	public static string QueryEscape(this string str)\n{\n    return Regex.Replace(str.Replace("-", " "), @"[^/]*(\s[^/]*)+", "#$&#");\n}	0
26465332	26465009	bind data to grid view in ASP.net	public void getlbCat()\n{\n    GVDetails.DataSource = new LibraryCatalogueOP().getLibraryCatalogue();\n    GVDetails.DataBind();\n}	0
13280966	11572981	How to XML serialize polymorphic array without wrapping element	private List<BaseCommand> _commands = new List<BaseCommand>();\n[XmlElement(typeof(ExecuteCommand))]\n[XmlElement(typeof(WaitCommand))]\npublic List<BaseCommand> Commands\n{\n    get\n    {\n        return _commands;\n    }\n    set\n    {\n        _commands = value;\n    }\n}	0
18056933	18015730	BootstrapContext in claimsprincipal null	var builder = new StringBuilder();\n\nusing (var writer = XmlWriter.Create(builder)) {\n    new SamlSecurityTokenHandler(new SamlSecurityTokenRequirement()).WriteToken(writer, bootstrapContext.SecurityToken);\n}\n\nvar tokenXml = builder.ToString();	0
11509848	11508525	ImageSource for Icon property must be an icon file - Embedded Resource	using (var iconStream = new MemoryStream())\n{\n    icon.Save(iconStream);\n    iconStream.Seek(0, SeekOrigin.Begin);\n    return BitmapFrame.Create(iconStream);\n}	0
3774658	3773993	How to change email FROM address field?	MailMessage mail = new MailMessage();\n\n//set the addresses\n//to specify a friendly 'from' name, we use a different ctor\nmail.From = new MailAddress("me@mycompany.com", "Steve James" );\nmail.To.Add("you@yourcompany.com");\n\n//set the content\nmail.Subject = "This is an email";\nmail.Body = "this is the body content of the email.";\n\n//send the message\nSmtpClient smtp = new SmtpClient("127.0.0.1");\nsmtp.Send(mail);	0
16743735	16740490	Serialize a class array members as flattened	private static string GetUrlParameters(string json)\n{\n    JsonTextReader reader = new JsonTextReader(new StringReader(json));\n    string path = null;\n    List<string> list = new List<string>();\n    while (reader.Read())\n    {\n        JsonToken tokenType = reader.TokenType;\n        switch (tokenType)\n        {\n            case JsonToken.PropertyName:\n                path = reader.Path;\n                break;\n            case JsonToken.Integer:\n            case JsonToken.Float:\n            case JsonToken.String:\n            case JsonToken.Boolean:\n                string item = string.Format("{0}={1}", path, reader.Value);\n                list.Add(item);\n                break;\n        }\n    }\n    return string.Join("&", list);\n}	0
7744130	7743659	Read contents from SslStream	ReadLine()	0
16383966	16383364	Get and Set ContextMenuStrip Items	public partial class Form1 : Form\n{\n    ContextMenuStrip cms = new ContextMenuStrip();\n\n    public Form1()\n    {\n        InitializeComponent();\n        //cms.Items[;\n    }\n    public ToolStripItemCollection ConItems\n    {\n        get\n        {\n            return cms.Items;\n        }\n        set\n        {\n            cms.Items.Clear();\n            ToolStripItemCollection tsc=(ToolStripItemCollection)value;\n            foreach (ToolStripItem tsi in tsc)\n            {\n                cms.Items.Add(tsi);\n            }\n        }\n    }\n\n}	0
16040256	16040214	Is it possible to change the return value in a finally clause in C#?	static int M()\n{\n    try\n    {\n        try\n        { \n            return 123;\n        }\n        finally\n        {\n            throw new Exception();\n        }\n    }\n    catch\n    {\n        return 456;\n    }\n}	0
25617893	25617639	How can receive data from usb barcode Scanner in Form_KeyPress Event and put it in a textbox Automatically?	private string barcode = string.Empty;\n\nprivate Form_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (ev.KeyChar == '\r')\n    {\n        textBox.Text = barcode;\n        barcode = string.Empty;\n    }\n    barcode += e.KeyChar\n}	0
9056503	9056103	how to open new browser window on button click event	protected void button_Click(object sender, EventArgs e)\n    {\n        // open a pop up window at the center of the page.\n        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);\n    }	0
3492861	3492813	Find whether a List<Point> represents a regular or irregular polygon	get the first point, and the two after it\nfind the angle between them, store it somewhere\nget the second point, and the two after it\nfind the angle between them, make sure it's the same\nrepeat the last two steps for all the points in the list	0
11846901	11846864	How to get list of Visual Studio commands?	...\Microsoft Visual Studio 9.0\Common7\IDE\*.vsk	0
3669568	3666834	How to read dicom tag value using openDicom.net in C#?	string tag = sq[sq.Count - 1].Tag.ToString();\nstring description = sq[sq.Count -1].VR.Tag.GetDictionaryEntry().Description;\nstring val_rep = sq[sq.Count - 1].VR.ToString();	0
4880192	4878501	How to use BindingList of object of different classes sharing same interface as datasource of datagridview	myList = new List<IMyInterface>();\n\nmyList.Add(new Foo());\nmyList.Add(new Bar());\n\nmyDataGridView.DataSource = myList;	0
8775330	8772357	How to replace bitmap white pixels with red using AForge?	EuclideanColorFiltering filter = new EuclideanColorFiltering();            \n filter.CenterColor = new AForge.Imaging.RGB(Color.White); //Pure White\n filter.Radius = 0; //Increase this to allow off-whites\n filter.FillColor = new AForge.Imaging.RGB(Color.Red); //Replacement Colour\n filter.ApplyInPlace(image);	0
6304309	6304279	Dynamic string formatting in c#	public void Log(string formatString, params object[] parameters)\n{\n    Log(String.Format(formatString, parameters));\n}	0
4372377	4372335	How to force IIS to send response headers without sending response body and closing connection	try\n    {\n        request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address));\n        Stream responseStream = (this.m_WebResponse = this.GetWebResponse(request)).GetResponseStream();\n        if (Logging.On)\n        {\n            Logging.Exit(Logging.Web, this, "OpenRead", responseStream);\n        }\n        stream2 = responseStream;\n    }\n    catch (Exception exception)\n    {\n     //	0
25667678	25666229	EntityFramework storing sensitive data	public override int SaveChanges()\n{\n    int result = base.SaveChanges();\n\n    foreach (DbEntityEntry dbEntityEntry in this.ChangeTracker.Entries())\n    {\n        DecryptSecureString(dbEntityEntry.Entity);\n    }\n    return result;\n}	0
8072824	8072721	Creating a manually expanding textblock	Graphics.MeasureString()	0
21546855	21546431	How to bind or get properties from User Control	private void ChangeCanvas_Click(object sender, RoutedEventArgs e)\n{\n   MainCanvas.Background = colorControls.previewColor.Fill;\n}	0
6009842	6009818	take a photo to pc since a application c#?	public void WindowsScreenshot()\n    {\n        // Full\n        Rectangle bounds = Screen.GetBounds(Point.Empty);\n        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))\n        {\n            using (Graphics g = Graphics.FromImage(bitmap))\n            {\n                g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);\n            }\n            bitmap.Save("test_full.jpg", ImageFormat.Jpeg);\n        }\n\n        // Window\n        Rectangle bounds = this.Bounds;\n        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))\n        {\n            using (Graphics g = Graphics.FromImage(bitmap))\n            {\n                g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);\n            }\n            bitmap.Save("test_window.jpg", ImageFormat.Jpeg);\n        }\n    }	0
14621745	14435705	Can not update a PostgreSQL table with auto id under FluentNHibernate	public virtual DataTable GetTables(string catalog, string schemaPattern, string \ntableNamePattern, string[] types){\nvar restrictions = new[] { catalog, schemaPattern, tableNamePattern }; \nreturn connection.GetSchema("Tables", restrictions);\\n}	0
27905852	27905711	HOW TO instantiate and populate a xml object	XmlDocument doc = new XmlDocument();\n        doc.LoadXml(stringWithXmlIn);\n        XmlNode solvableNode = doc.SelectSingleNode("stream/search-result/solvable-list/solvable");\n        string edition = solvableNode.Attributes["edition"].Value;	0
17944338	17943260	Providing 'this' via base constructor	public sealed class MyComplexObjEnum : Enumeration<ComplexObj>\n{\n    public MyComplexObjEnum(ComplexObj enumVal) : base( enumVal) { }\n    public static readonly MyComplexObjEnum EnumVal1 = new MyComplexObjEnum(new ComplexObj("val1", 455, null));\n    public static readonly MyComplexObjEnum EnumVal2 = new MyComplexObjEnum(new ComplexObj("val2", 456, null));\n    public static readonly MyComplexObjEnum EnumVal3 = new MyComplexObjEnum(new ComplexObj("val3", 457, null));\n}\n\npublic class ComplexObj \n{\n    private readonly string _a;\n    private readonly int _b;\n    private readonly string _c;\n\n    public ComplexObj(string a, int b, string c)\n    {\n        _a = a;\n        _b = b;\n        _c = c;\n    }\n}	0
3652174	3615900	How to sign an xml file in a wcf service?	[OperationContract]\nstring GetFooXml();	0
9842391	9842361	How/where to store the current users login name?	Environment.UserName	0
8158931	8158858	Get all parameters combinations possible	void ImplCombinations(List<prmMatrix> plist, string built, int depth, List<string> results)\n{\n    if (depth >= plist.Count()) {\n        results.Add(built);\n        return;\n    }\n\n    prmMatrix next = plist[depth];\n    built += "[" + next.Name + ":";\n    foreach (var option in next.PossibleValues)\n        ImplCombinations(plist, built + option + "]", depth + 1, results);\n}\n\nList<string> GetCombinations(List<prmMatrix> plist)\n{\n    List<string> results = new List<string>();\n    ImplCombinations(plist, "", 0, results);\n    return results;\n}	0
19713062	19711691	Enterprise Library 6 Validation Not Reading From Configuration?	// Bootstrap the block at startup using default configuration file\nValidationFactory.SetDefaultConfigurationValidatorFactory(\n    new SystemConfigurationSource());\n\nAThing bob = new AThing();\nbob.Name = null;\n\nValidationResults vr = Validation.Validate(bob, "default");\nDebug.Assert(!vr.IsValid);	0
22539807	22539748	Array is affecting other array value C#	scorescopy = (int [])scores.Clone();	0
8552726	8552698	How to determine a class has implement a specific interface or not	bool result = typeof(ISampleInterface).IsAssignableFrom(typeof(ImplementationClass));	0
8476713	8476686	How can I mark some lines of my code as it won't run in release?	#if DEBUG\n    Console.WriteLine("Debug version");\n#endif	0
51995	51964	How do I remove items from the query string for redirection?	string url = Request.RawUrl;\n\nNameValueCollection params = Request.QueryString;\nfor (int i=0; i<params.Count; i++)\n{\n    if (params[i].GetKey(i).ToLower() == "foo")\n    {\n        url += string.Concat((i==0 ? "?" : "&"), params[i].GetKey(i), "=", params.Get(i));\n    }\n}\nResponse.Redirect(url);	0
3984337	3984324	C# - Given a string that is representing a numeric percentage, a way to extract the whole percentage?	"39.999%".Split(new char[] { '.' })[0] + "%";	0
23652489	23652418	Select Values from two tables using Linq	var innerJoinQuery =\n    from category in categories\n    join prod in products on category.ID equals prod.CategoryID\n    select new { ProductName = prod.Name, Category = category.Name };	0
2859322	2858882	Getting the validation metadata for built in validators	foreach( var property in model.GetType() )\n{\n     var stringLengthAttr = property.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;\n\n     if( stringLengthAttr != null )\n         return stringLengthAttr.MaximumLength;\n\n}	0
4176670	2154050	How to detect if executable requires UAC elevation (C# pref)	ULONG CheckElevation(\n    __in PWSTR FileName,\n    __inout PULONG Flags, // Have a ULONG set to 0, and pass a pointer to it\n    __in_opt HANDLE TokenHandle, // Use NULL\n    __out_opt PULONG Output1, // On output, is 2 or less.\n    __out_opt PULONG Output2\n    );	0
15518281	15518153	Logout from service	client.Close();	0
10671064	10614224	Timer object in a class library?	private void SetTimer(DateTime remindLater)\n{\n    timer = new System.Timers.Timer();\n    TimeSpan timeSpan = remindLater - DateTime.Now;\n    timer.Interval = (int) timeSpan.TotalMilliseconds;\n    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n    timer.Start();\n}\n\nprivate void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n    timer.Stop();\n    AutoUpdater.Start(appCast, remindLaterAt, remindLaterFormat);\n}	0
1126933	1126915	How do I split a string by a multi-character delimiter in C#?	string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";\nstring[] stringSeparators = new string[] {"[stop]"};\nstring[] result;\n\n// ...\nresult = source.Split(stringSeparators, StringSplitOptions.None);\n\nforeach (string s in result)\n{\n    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);\n}	0
27935088	27934721	How do I make a WP8.1 app start at a different page on launch?	if (youruserdonthavetokenstoredindborlocal)\n        {\n            rootFrame.Navigate(typeof(Login));\n        }\n     else\n        {\n           rootFrame.Navigate(typeof(MainPage));\n        }	0
5985600	5985469	exposing the combobox Items property in a usercontrol	[Description("The items in the UserControl's ComboBox."), \n DesignerSerializationVisibility(DesignerSerializationVisibility.Content), \n Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design", typeof(System.Drawing.Design.UITypeEditor))] \npublic System.Windows.Forms.ComboBox.ObjectCollection MyItems {\n    get { \n        return comboBox1.Items; \n    }\n}	0
29840304	29838684	XML Serialization, Include encoding info and customized namespace	XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));\n\nXmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();\nns1.Add("", "http://www.mydata.org");\n\nEncoding encoding = Encoding.GetEncoding("UTF-8");\n\nusing (StreamWriter sw = new StreamWriter(fileName, false, encoding))\n{\n    xmlSerializer.Serialize(sw, myXMLData, ns1);\n}	0
30144103	30143895	C# remove item from list of integers int[] l = {1,2,3} - or use recursion to add them	static public int sumThisUp(IEnumerable<int> list)\n{\n    return list.FirstOrDefault() + (list.Any() ? sumThisUp(list.Skip(1)) : 0);\n}	0
21643430	21622443	Does anyone know how to style a the PopUp for EditMode="PopUp" in Telerik RadGrid?	.rgEditForm table {\n/*CHANGE FONTS*/\nfont: normal 13px 'Your Font',Arial,Helvetica,sans-serif !important;\nline-height: 22px !important;\n\n/*CHANGE BACKGROUD - FACEBOOK'S BLUE*/\nbackground-color: #3B5999 !important;\n}	0
27081617	27081505	Finding the angle of an GameObject compared to another	Vector3 enemyLookDirection = enemy.transform.forward;\nVector3 playerRelativeDirection = \n    (player.transform.position - enemy.transform.position).normalized;\n\nfloat angle = Vector3.Angle(enemyLookDirection, playerRelativeDirection);\nfloat enemyFov = 45.0f; // Biggest angle that enemy can see from the center of view\nif (angle < enemyFov)\n    EnemyCanSeePlayer();	0
4708297	4708247	When would I want to model a class with a private ctor?	System.IO.Stream	0
9785547	9780470	Match and replace string in text using regular expressions	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml("your html here"); \n// or doc.Load(stream);\n\nvar nodes = doc.DocumentNode.DescendantNodes("div").Where(div => div.Id == "Specs");\n\nforeach (var node in nodes)\n{\n    var classAttribute = node.Attributes["class"];\n    if (classAttribute != null)\n    {\n        classAttribute.Value = string.Empty;\n    }\n}\n\nvar fixedText = doc.DocumentNode.OuterHtml;\n//doc.Save(/* stream */);	0
2489340	2489208	Monotouch stringWithFormat using a URL	string urlString = String.Format(@"http://maps.google.com/maps/geo?q={0}&output=csv", System.Web.HttpServerUtility.UrlEncode(addressField.text))	0
1380220	1380181	C#: Convert a string to an object reference	//code when defining your button...\n{\n     sqlButton.Tag = comboBoxA;  //instead of comboBoxA.Name\n}\n\nprivate void SQLButton(object sender, EventArgs e)\n{\n    Button button = sender as Button;\n    ComboBox comboBox = button.Tag as ComboBox;\n\n    if (comboBox == null ) \n    {...}\n    else\n    {\n        magic(comboBox);\n    }\n}\n\nprivate void magic(ComboBox currentcombo)\n{\n    string CurrentText = currentcombo.Text;\n}	0
18956274	18956006	Pause the program to check variable values in C#	Tools -> Customize -> Commands -> Toolbar -> Debug -> Add Command -> Debug -> Break All	0
17752426	17752390	Foreach loop correctly	foreach (var row in dt)\n    {                \n        //Not sure how you will get ZipCode from the ROW, but you get the idea. \n        code.Add(row["ZipCode"]);                \n\n    }//end foreach loop	0
13522978	13522932	how do i format my nLog layout	fileTarget.Layout =  "${date}  ${message1}  ${message2}  ${message3}  ${message4}";	0
11671839	11671767	Protected Variables for Inheritance (StyleCop SA1401)	public SomeType SomeProperty { get; protected set; }	0
4064993	4055562	Is it possible to programmatically lock a windows phone 7 device?	PhoneApplicationService.Current.ApplicationIdleMode = IdleDetectionMode.Disabled	0
31040590	31040561	remove a char from string or replace it by another in string array	names = names.Select(x => x.Replace("!", "")).ToArray();	0
9898515	9898479	Unable to infer generic type with optional parameters	using System;\n\nclass Test\n{\n    static void Foo<T>(Func<T> func) {}\n\n    static void Main()\n    {\n        // Works fine\n        Foo(() => "hello");\n\n        // Type inference fails\n        Foo(func: () => "hello");\n    }\n}	0
15705310	15705242	C# Regex Port Validation 49152 to 65535	string input = "51204";\nint portNumber;\nif (int.TryParse(input, out portNumber) \n    && portNumber >= 49152 \n    && portNumber <= 65535)\n{\n    // Valid value...\n}	0
28322255	28321709	how to save a primary key value from a table to another table?	public partial class Person1\n{\n    public int PersonID { get; set;     \n    public string Title { get; set; }\n    public string FirstName { get; set; }       \n    public string LastName { get; set; }      \n    public string UserName { get; set; }\n    public Nullable<int> UserAuthRoleId { get; set; }\n    public virtual Password Password { get; set; }\n}	0
17115982	17115950	How to work with specific parameter of a Controller	if (categoryName == "Offers")\n    return View("SomeView", Products.BuildListForHome(categoryId, null));	0
224251	224239	What's the best way to write a short[] array to a file in C#?	static void WriteShorts(short[] values, string path)\n    {\n        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))\n        {\n            using (BinaryWriter bw = new BinaryWriter(fs))\n            {\n                foreach (short value in values)\n                {\n                    bw.Write(value);\n                }\n            }\n        }\n    }	0
3256154	3256100	how to create datagrid at run time through code?	DataGridView dg = new DataGridView();\n\n// set columns (auto or manual)\n\n// set appearance (lots of style options)\n\n// set data source (IEnumerable object)\ndg.DataBind();\n\nplaceHolder1.COntrols.Add(dg); // add to placeholder	0
8855427	8855325	Parsing a text file to CSV using LINQ	var buffer = new List<string>();\nforeach (var line in File.ReadLines(pathToFile))\n{\n    if (String.IsNullOrWhitespace(line))\n    {\n        ProcessSection(outputFile, buffer);\n        buffer.Clear(); // or create a new one\n    }\n    else\n    {\n        buffer.Add(line);\n    }\n}\n\nstatic void ProcessSection(StreamWriter outputFile, List<string> buffer)\n{\n    if (buffer.Count == 0) return;\n    var contents = buffer.Take(3)\n        .Select(line => String.Format("\"{0}\"", line.Substring(line.IndexOf(": ") + 2)));\n    outputFile.WriteLine(String.Join(",", contents));\n}	0
7515592	7515521	How to do a generic call to function based on a Type object?	public IEnumerable GetBoxed(Type type, string param1, string param2)\n{\n    return (IEnumerable)this\n        .GetType()\n        .GetMethod("Get")\n        .MakeGenericMethod(type)\n        .Invoke(this, new[] { param1, param2 });\n}	0
17081786	17081625	String was not recognized as a valid DateTime	CultureInfo GBCultureInfo = new CultureInfo("en-GB"); // dd/MM/YYYY\n// CultureInfo USCultureInfo = new CultureInfo("en-US"); // MM/dd/YYYY\n\ndt = DateTime.Parse(frmtxtdt.Text,GBCultureInfo);	0
18145806	18145605	save file to fix location using openfile dialog	FileCopy(OpenFileDialog1.FileName, System.AppDomain.CurrentDomain.BaseDirectory & "/temp/" & OpenFileDialog1.SafeFileName	0
13902997	13902991	Find coords of mouse cursor position in RichTextBox	Point p = new Point(Cursor.Position.X, Cursor.Position.Y);\nint mx = richTextBox1.PointToClient(p).X;\nint my = richTextBox1.PointToClient(p).Y;	0
5429151	5429089	How to read a range of bytes from a bytearray in c#	var mainArray = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\nvar startPos = 5;\nvar endPos = 10;\nvar subset = new byte[endPos - startPos + 1];\nArray.Copy(mainArray, startPos, subset, 0, endPos - startPos + 1);	0
19324852	19322754	Mousemoving Usercontrol in canvas WPF	IsHitTestVisible="False"	0
24227732	24226522	How update StatusStripLabel from another class?	this.BeginInvoke((MethodInvoker)delegate\n{\n    // update toolstriplabel here\n});	0
12845323	12844672	WebBrowser Control in Web Application C#	IEBrowser.Navigate(url);\n        bool flag = true;\n        int times = 0;\n        while (flag)\n        {\n            Sleep(500);\n            Application.DoEvent();\n\n            if (IEBrowser.ReadyState == WebBrowserReadyState.Complete)\n            {\n                times ++;\n            }\n            else\n            {\n                times = 0;\n            }\n\n            if (times >= 10)\n            {\n                flag = false;\n            }\n        }\n\n        string str = IEBrowser.DocumentText;	0
15608819	15601656	How to expose WhenAny etc	interface ICoolInterface : IReactiveNotifyPropertyChanged\n{\n    /* ... */\n}	0
24250870	24250770	iis Creating new application and enabling Windows Authentication Fails	%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/security/authentication/windowsAuthentication\n%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/security/authentication/anonymousAuthentication	0
14200143	14200043	How to make dynamically added buttons clickable	button.Tag = i;\nbutton.Click += handleTheClick;\n\n...\n\nprivate void handleTheClick(object sender, EventArgs e){\n    Button btn = sender as Button;\n    int row = (int)btn.Tag;\n}	0
31474717	29867415	How to add arrows (direction of the route) for Route in GMap.NET?	'Draw markers\nDim markersOverlay As GMapOverlay = New GMapOverlay("markers")\nDim marker0 As GMarkerGoogle = New GMarkerGoogle(Me.myMap.Position, GMarkerGoogleType.arrow)\nDim marker1 As GMarkerGoogle = New GMarkerGoogle(New PointLatLng(lat, lng), GMarkerGoogleType.arrow)\nmarkersOverlay.Markers.Add(marker0)\nmarkersOverlay.Markers.Add(marker1)\nMe.myMap.Overlays.Add(markersOverlay)	0
11469246	11469176	Variable not saving data in C#	class MainProg\n{\n\n    static void Main()\n    {\n        Register rs = new Register();\n        Register r = (Register)rs;\n\n        r.run();\n        Console.WriteLine(r.name);\n    }\n\n}\n\n\nclass Register : MainProg\n{\n    public string name;\n    public void run()\n     {\n        name = "a";\n     }\n}	0
6090611	6090558	Add vertical scroll bar to panel in .NET	ScrollBar vScrollBar1 = new VScrollBar();\nvScrollBar1.Dock = DockStyle.Right;\nvScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };\npanel1.Controls.Add(vScrollBar1);	0
6357072	6356967	From List<string[]> to String[,]	specialMacroArray = new string[specialMacros.Count, 2];\nfor (int i = 0; i < specialMacros.Count; i++)\n{\n    specialMacroArray[i, 0] = specialMacros[i][0];\n    specialMacroArray[i, 1] = specialMacros[i][1];\n}	0
13503366	13496878	reduce integers if covering 0-9	int[] arr1 = { 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 51, 9876 };\n\n// This is just one reduction step, you would need loop over it until\n// no more reduction is possible.\nvar r = arr1.GroupBy(g => g / 10).\n        SelectMany(s => s.Count() == 10 ? new int[] {s.Key} : s.AsEnumerable());	0
17073743	17073708	Running multiple Tasks from button click (UI thread) - how to know if they all succeeded or some failed?	Task.Factory.ContinueWhenAll(tasks, f =>\n            {\n                if (t1.Exception != null)\n                {\n                     // t1 had an exception\n                }\n                if (t2.Exception != null)\n                {\n                     // t2 had an exception\n                }\n\n                // This is called when both tasks are complete, but is called\n                // regardless of whether exceptions occured.\n                MessageBox.Show("All tasks completed");\n            });	0
7752709	7752586	How to convert string from encoding codes to charactes?	var s = System.Web.HttpUtility.UrlDecode("%D0%A1%D1%82%D1%80%D0%BE%D0%BA%D0%B0");	0
14337012	14336952	Accessing https page	Request.Server["HTTP_REFERER"]	0
5264680	5264396	Changing XML List name for String after a webservice invoke	public class YourObject\n{\n     [XmlArray("picture_list")]  \n     [XmlArrayItem("picture")]\n     public List<string> picture_list { get; set; }\n}	0
8423511	8411119	How can I upload a pdf file?	protected void Button1_Click(object sender, EventArgs e)\n {\n    Label6.Text = ProcessUploadedFile();\n }\n\n private string ProcessUploadedFile()\n {\n    if(!FileUpload1.HasFile)\n        return "You must select a valid file to upload.";\n\n    if(FileUpload1.ContentLength == 0)\n        return "You must select a non empty file to upload.";\n\n    //As the input is external, always do case-insensitive comparison unless you actually care about the case.\n    if(!FileUpload1.PostedFile.ContentType.Equals("application/pdf", StringComparion.OrdinalIgnoreCase))\n        return "Only files of type PDF is supported. Uploaded File Type: " + FileUpload1.PostedFile.ContentType;\n\n    //rest of the code to actually process file.\n\n    return "File uploaded successfully.";\n }	0
4657981	4657974	How to Generate unique file names in C#	var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());	0
5541571	5541543	delete everything from List<string> with specific string	MyFiles.RemoveAll(s => s.Contains("1"));	0
21887981	21887372	Stopping Text to Speech wp8	private SpeechSynthesizer synth = new SpeechSynthesizer();\n      private async void Button_Click(object sender, RoutedEventArgs e) {\n      await synth.SpeakTextAsync("You have an incoming notification from Big Bank.");\n    }\n\n    private void Button_Click_1(object sender, RoutedEventArgs e) {\n      synth.CancelAll();\n    }	0
27102046	27099038	How to set backgroung color to the selected node of DevComponents.AdvTree.AdvTree?	DevComponents.AdvTree.Node node = new DevComponents.AdvTree.Node();\n                node = advTree1.SelectedNode;\n                node.Style = new DevComponents.DotNetBar.ElementStyle(); \n                node.Style.BackColor = Color.Red;	0
14988181	14988128	Refresh data in windows store app	var period = TimeSpan.FromMinutes(5);\n\nvar timer = ThreadPoolTimer.CreatePeriodicTimer((source) =>\n    {\n        //do your query/work here\n        Dispatcher.RunAsync(CoreDispatcherPriority.High,\n        () =>\n        {\n           // Now that work is done, safely access UI components here to update them\n        });\n    }, period);	0
11461583	11461063	Preventing SQL injection when setting a sqldatasource select statement in ASP.NET c#	GetSubInfo.SelectParameters.Add("xparam", txtbox.Text);\n    GetSubInfo.SelectCommand = "SELECT x from x where x_id LIKE @xparam ORDER BY x ASC";	0
8155695	8155539	Populate Combobox with Access Table Names	string[] restrictions = new string[4];\nrestrictions[3] = "Table";    \ncon.Open();\nDataTable tabls=con.GetSchema("Tables",restrictions);	0
16927214	16927047	Initialialize a property in a command	value = _myfile;	0
10870206	10870030	XML De-serialization giving null values	[Serializable]\n    public class FullServiceAddressCorrectionDelivery\n    {\n        [XmlElement("AuthenticationInfo", \n              Namespace = \n              "http://www.usps.com/postalone/services/UserAuthenticationSchema")]\n        public AuthenticationInfo AuthenticationInfo\n        {\n            get;\n            set;\n        }\n    }\n\n    [Serializable]\n    public class AuthenticationInfo\n    {\n        [XmlElement("UserId", Namespace="")]\n        public string UserId\n        {\n            get;\n            set;\n        }\n        [XmlElement("UserPassword", Namespace = "")]\n        public string UserPassword\n        {\n            get;\n            set;\n        }\n    }	0
3764166	3764141	How can I take two bytes and combine them into a single UInt16 in C#?	return (ushort)((memory[address + 1] << 8) + memory[address]);	0
3648671	3648643	C# Regular Expression, Match contents of string	[a-zA-Z0-9]+\["(.+)"\]	0
25528122	25527936	Exception of Adding a new value on Regedit	RegistryKey Localuser= Registry.LocalMachine.OpenSubKey(\n    "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",\n    true);	0
7700036	7699999	Return generic<object> collection on interface method without casting to object in implementation	public interface ISearchable<T>\n{\n    ChunkedList<T> GetAll(int chunkStart, int chunkEnd);\n\n    ChunkedList<T> SearchByValue(string searchValue, int chunkStart, int chunkEnd);\n\n    ChunkedList<T> SearchByValueWithFilters(string searchValue, List<string> filters, int chunkStart, int chunkEnd);\n}\n\nclass myClass: ISearchable<myClass>\n{\n   ChunkedList<myClass> GetAll(int chunkStart, int chunkEnd);\n\n   ChunkedList<myClass> SearchByValue(string searchValue, int chunkStart, int chunkEnd);\n\n   ChunkedList<myClass> SearchByValueWithFilters(string searchValue, List<string> filters, int chunkStart, int chunkEnd);\n}	0
25007954	25007120	Lambda Expression with self reference - what is it doing?	var tempSomeObjects = new List<SomeObjects>();\nforeach(var fk in SomeObjects)\n{\n    foreach(var k1 in lista)\n    {\n        foreach(var k2 in k1.listb)\n        {\n            foreach(var k3 in k2.listc)\n            {\n                foreach(var k4 in k3.listd)\n                {\n                    foreach(var k5 in k4.liste)\n                    {\n                        if ((k4.name1 + k5.name2) == fk)\n                        {\n                            tempSomeObjects.Add(new SomeObjects(k4.name1, k5.name2, string.Empty, "ww"));\n                        }\n                    }\n                }\n            }\n        }\n    }\n}	0
12105412	3587842	How to build a C# project without checking dependencies?	/p:BuildProjectReferences=false	0
29094225	29091240	String.Format Currency for K, M and B	decimal amt = 10000000;\n        Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");     //set up France as current culture\n        NumberFormatInfo NFI = CultureInfo.CurrentCulture.NumberFormat;\n\n        string currencySymbol =  NFI.CurrencySymbol;\n        int currencyPosition = NFI.CurrencyPositivePattern;\n\n        if (amt > 1000000)\n\n        {\n        if (currencyPosition == 3)     // n $  \n        {\n            NFI.CurrencySymbol = "K " + currencySymbol;\n        }\n            decimal d = (decimal)Math.Round(amt / 1000, 0);\n            string output = d.ToString("c");\n        }	0
21303294	21302332	C# listbox to panel and linkbuttons	using (var dReader = cmd.ExecuteReader()) {\n    if (dReader != null) {\n        while (dReader.Read()) {\n            LinkButton btn = new LinkButton();\n            //You should change the offset if you want to edit the query\n            //In your case 0 is name and 1 is link\n            btn.Text = dReader.GetString(0);\n            btn.PostBackUrl = dReader.GetString(1);\n            panel.Controls.Add(btn);\n        }\n    }\n}	0
8741959	8741631	Converting string obtained from database into keypress event	SendKeys.SendWait	0
7349726	7349401	Trying to marshal C++ pointer to unsigned long into a C# ulong	public static extern int Foo(int messageHandle, ref uint tag, StringBuilder part, StringBuilder value);	0
26324262	26271219	WinForm RichTextBox text color changes too many characters	private static void AppendTextColor(RichTextBox box, Color color, string text) {\n        box.SelectionStart = box.Text.Length;   // Optional\n        var oldcolor = box.SelectionColor;\n        box.SelectionColor = color;\n        box.AppendText(text);\n        box.SelectionColor = oldcolor;\n    }	0
374857	374493	Allow users to insert a TAB into a TextBox but not newlines	protected override void WndProc(ref Message m)\n        {\n            if (m.Msg == (int)0x102 && m.WParam.ToInt32() == 13)\n            {\n                return;\n            }\n\n            base.WndProc(ref m);\n        }	0
2168548	2165427	Convert Castle Windsor xml config to C# code	container.Register(Component.For<Consumer>()\n               .DynamicParameters((kernel, parameters) => \n                   parameters["services"] = new Dictionary<string, IService> {\n                     {"one", kernel.Resolve<IService>("service1")},\n                     {"two", kernel.Resolve<IService>("service2")},\n                   }\n               ));	0
6765676	6750116	How to eliminate ALL line breaks in string?	public static string RemoveLineEndings(this string value)\n{\n    if(String.IsNullOrEmpty(value))\n    {\n        return value;\n    }\n    string lineSeparator = ((char) 0x2028).ToString();\n    string paragraphSeparator = ((char)0x2029).ToString();\n\n    return value.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(lineSeparator, string.Empty).Replace(paragraphSeparator, string.Empty);\n}	0
29061252	29061017	Get assembly of code that instantiated object (with inheritance)	var stack = new StackTrace(true);\nvar thisFrame = stack.GetFrame(0); // ExternalResource constructor\nvar parentFrame = stack.GetFrame(1); // Sound constructor\nvar grandparentFrame = stack.GetFrame(2); // This is the one!\n\nvar invokingMethod = grandparentFrame.GetMethod();\nvar callingAssembly = invokingMethod.Module.Assembly;	0
6529580	6529167	ASP.NET Membership profile default value	static SharedMembershipProfile()\n    {\n        Properties["IssuesPageSize"].DefaultValue = 10;\n        Properties["NotificationTypes"].DefaultValue = "Email";\n        Properties["PreferredLocale"].DefaultValue = "en-US";\n    }	0
858797	858756	How to parse a text file with C#	StreamReader reader = File.OpenText("filename.txt");\nstring line;\nwhile ((line = reader.ReadLine()) != null) {\n    string[] items = line.Split('\t');\n    int myInteger = int.Parse(items[1]); // Here's your integer.\n    // Now let's find the path.\n    string path = null;\n    foreach (string item in items) {\n        if (item.StartsWith("item\\") && item.EndsWith(".ddj")) {\n            path = item;\n        }\n    }\n\n    // At this point, `myInteger` and `path` contain the values we want\n    // for the current line. We can then store those values or print them,\n    // or anything else we like.\n}	0
30385364	30385296	How fill combobox using with enum - show integers(values) of enum in combobox	cb_birates.DataSource = Enum.GetValues(typeof(BitRates))\n                            .Cast<BitRates>()\n                            .Select(x => (int)x)\n                            .ToList();	0
27455736	27455671	how to get data in a label to be organized into colums	private void button1_Click(object sender, EventArgs e)\n    {\n        double Celceius = 0;\n        double Fahrenheit;\n        lblOUT.BackColor = Color.Red;\n\n        lblOUT.Text = "Celceius" + "".PadLeft(20) + "Fahrenheit";\n\n        while (Celceius <= 100)\n        {\n\n            Fahrenheit = 32 + (Celceius * 1.8);\n\n            lblOUT.Text += Environment.NewLine + Celceius.ToString().PadLeft(8,' ') + "".PadLeft(20) + Fahrenheit.ToString().PadLeft(10,' ');\n\n            Celceius += 5;\n        } \n    }	0
1551790	1551761	Ref parameters and reflection	ParameterInfo[] parameters = myMethodInfo.GetParameters();\nforeach(ParameterInfo parameter in parameters)\n{\n    bool isRef = parameterInfo.ParameterType.IsByRef;\n}	0
6307683	6305586	How to use /callcap in visual studio 2008 for Visual C#	/callcap	0
3779825	3768656	Problem filling data table with SQL adapter in ASP.NET	protected void btn_Click_Login(object sender, EventArgs e)\n{\n\n   SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RbConnectionString"].ConnectionString);\n    conn.Open();\n    string queryString = "SELECT * FROM [Users] WHERE Username=@username AND Password= @password";\n   SqlCommand command = new SqlCommand(queryString, conn);\n   command.Parameters.AddWithValue("@username", txtUsername.Text);\n   command.Parameters.AddWithValue("@password", txtPassword.Text);\n\n   SqlDataReader reader = null;\n   reader = command.ExecuteReader();\n\n   if (reader.Read())\n   {\n       Session["Username"] = txtUsername.Text;\n       Session["Password"] = txtPassword.Text;\n       Response.Redirect("main.aspx");\n   }\n   else\n   {\n       lblError.Visible = true;\n       lblError.Text = "Incorrect Username/Password Combination";\n   }\n    conn.Close();\n\n}	0
13690027	13690026	New protected member declared in struct	struct Foo {\n    private Object _bar;\n}	0
28308150	28307538	How do I access ServiceStack's Service.Db instance from within a RequestFilter?	public class VerifyRequestedSystemsAttribute : Attribute, IHasRequestFilter\n{\n    public IDbConnectionFactory DbFactory { get; set; }\n\n    private List<int> RetrieveSystemIds(object requestDto)\n    {\n        using (var db = DbFactory.OpenConnection())\n        {\n            //...\n        }\n    }\n}	0
11757593	11757528	C# adding unknown number of values into an array	var input = Console.ReadLine();\nif (input == "") {\n    break;\n}\n\nnumbers[i] = int.Parse(input);\n// etc	0
4520767	4510221	User Control access from code behind problem	MenuItem MaintenanceReports = this.adminMenu.FindItem("Reports/MaintenanceReports");	0
4718904	4718887	Get the information from Dictionary with reflection	dic1.Values.OfType<Class1>()	0
6224150	6223999	Read data in a HTML data	WebClient client = new WebClient();\n        string url = "Your URL";\n        Byte[] requestedHTML;\n        requestedHTML = client.DownloadData(url);\n        string htmlcode = client.DownloadString(url);\n\n        //client.DownloadFile(url, @"E:\test.html");\n\n        UTF8Encoding objUTF8 = new UTF8Encoding();\n        string html = objUTF8.GetString(requestedHTML);           \n\n\n        MatchCollection m1 = Regex.Matches(html, @"(<h3>(.*?)</h3>)",\n        RegexOptions.Singleline);\n\n        foreach (Match m in m1)\n        {\n            string cell = m.Groups[1].Value;\n            Match match = Regex.Match(cell, @"<h3>(.+?)</h3>");\n            if (match.Success)\n            {\n                string value = match.Groups[1].Value;\n            }\n        }	0
13254484	13253232	How to populate treeview with file path which is saved in database	public void ProcessPath(IEnumerable<String> path,  TreeNodeCollection nodes)\n{\n    if (!path.Any())\n        return;\n    var node = nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == path.First());\n    if (node == null)\n    {\n        node = new TreeNode(text: path.First());\n        nodes.Add(node);\n    }\n    ProcessPath(path.Skip(1),node.ChildNodes);\n}\n\npublic void CreateTreeView()\n{\n    foreach (string field in MyDataBase.FieldsInMyColumn())\n        ProcessPath(field.Split('\\'),myTreeView.Nodes);\n}	0
9437734	9437698	How to test a function in Visual Studio 2010?	immediate window	0
13306267	13306152	How can I use a DLL I created when running a simple C# program from the command line?	csc /reference:library1.dll /reference:library2.dll csfile.cs	0
4023028	4022993	How to get a list of week days in a month?	public static List<DateTime> GetDates(int year, int month)\n{\n   return Enumerable.Range(1, DateTime.DaysInMonth(year, month))\n                    .Select(day => new DateTime(year, month, day))\n                    .Where(dt => dt.DayOfWeek != DayOfWeek.Sunday &&\n                                 dt.DayOfWeek != DayOfWeek.Saturday)\n                    .ToList();\n}	0
6994391	1789627	How to change the timeout on a .NET WebClient object	private class MyWebClient : WebClient\n    {\n        protected override WebRequest GetWebRequest(Uri uri)\n        {\n            WebRequest w = base.GetWebRequest(uri);\n            w.Timeout = 20 * 60 * 1000;\n            return w;\n        }\n    }	0
20639897	20522884	Session Expire URL bug	if (!string.IsNullOrEmpty(Request.QueryString["returnUrl"]))\n        {\n            return RedirectToAction("Index", "Login");\n        }	0
6314658	6314573	Trying to upgrade to .NET Framework 4	[DllImport("Shlwapi.dll")]\npublic static extern IntPtr PathGetArgs([In] string path);\n\nfileArgs = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(PathGetArgs(strCmdLine.ToString()));	0
712570	712452	Specialize implementation of GenericType<A,B> for case A == B?	using System;\n\nnamespace Test\n{\n    class Generic<A, B>\n    {\n        public string Method(A a, B b)\n        {\n            return this.DefaultMethod(a, b);\n        }\n\n        protected string DefaultMethod(A a, B b)\n        {\n            return a.ToString() + b.ToString();\n        }\n\n        public string Method(B b, A a)\n        {\n            return b.ToString() + a.ToString();\n        }\n    }\n\n    class Generic<A> : Generic<A, A>\n    {\n        public new string Method(A a, A b)\n        {\n            return base.DefaultMethod(a, b);\n        }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Generic<int, double> t1 = new Generic<int, double>();\n            Console.WriteLine(t1.Method(1.23, 1));\n\n            Generic<int> t2 = new Generic<int>();\n            Console.WriteLine(t2.Method(1, 2));\n        }\n    }\n}	0
2792001	2791947	How to make a program not show up in Alt-Tab or on the taskbar	using System;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication1\n{\n  class Program\n  {\n    [STAThread]\n    static void Main(string[] args)\n    {\n      Application.Run(new MessageWindow());        \n    }\n  }\n\n  class MessageWindow : Form\n  {\n    public MessageWindow()\n    {\n      this.ShowInTaskbar = false;\n      this.WindowState = FormWindowState.Minimized;\n      // added by MusiGenesis 5/7/10:\n      this.FormBorderStyle = FormBorderStyle.FixedToolWindow;\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n      base.WndProc(ref m);\n    }\n  }\n}	0
2953453	2952810	ResXResourceWriter Chops off end of file	public void ExportToResx(Dictionary<string,string> resourceDictionary, string fileName)\n{\n    using(var writer = new ResXResourceWriter(fileName))\n    {\n        foreach (var resource in resourceDictionary)\n        {\n            writer.AddResource(resource.Key, resource.Value);\n        }\n    }\n}	0
8577983	8576308	Optional fields when reading in JSON via DataContracts in C#	[DataContract]\npublic class Geo\n{\n    [DataMember(Name = "coordinates")]\n    public double[] Coordinates { get; set; }\n}	0
17199314	17199286	Average of array with two objects	var average = readings.Average(r => r.value);	0
31521831	31351192	type ahead search in WPF datagrid	TextSearch.TextPath="First"	0
16342572	16088520	Facebook API C# - How to get the result?	dynamic result = fbclient.Get("fql", new\n        {\n            q = new[]\n        {\n            "SELECT unread_count FROM mailbox_folder WHERE folder_id = 0 AND viewer_id = me()",\n            "SELECT is_unread FROM notification WHERE recipient_id = me()",\n            "SELECT unread FROM friend_request WHERE uid_to = me()"\n        }\n        });\n\n        var unread_messages = result["data"][0]["fql_result_set"][0]["unread_count"];\n        var notifications = result["data"][1]["fql_result_set"];\n        var open_friendRequests = result["data"][2]["fql_result_set"];	0
176291	176106	Validate String against USPS State Abbreviations	private static String states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";\n\npublic static bool isStateAbbreviation (String state)\n{\n  return state.Length == 2 && states.IndexOf( state ) > 0;\n}	0
14148957	14148935	Launch Web URL in NON-default browser	Process.Start("C:\Program Files\Mozilla Firefox\firefox.exe", "http://www.somewebsite.com/");	0
17817464	17817414	XML serializer returns null on object deserialization	[XmlAttribute]	0
27258033	27257896	Finding overlapping data in arrays	1 => 2\n2 => 2\n3 => 2\n4 => 2\n5 => 2\n6 => 1\n7 => 1\n...	0
8241927	8233795	Generate a SQL clause using a Linq-to-Sql Expression	string sql = DataContext.GetTable<Customer>().Where(criteria).ToString();	0
4966514	4963423	Creating a sortable string from multiple strings in .Net	public class StringListComparer : IComparer<IList<string>>\n{\n    private StringComparer comparer;\n\n    public StringListComparer()\n        : this(StringComparer.Ordinal)\n    {\n    }\n\n    public StringListComparer(StringComparer comparer)\n    {\n        if (comparer == null) throw new ArgumentNullException("comparer");\n        this.comparer = comparer;\n    }\n\n    public int Compare(IList<string> x, IList<string> y)\n    {\n        int result;\n        for (int i = 0; i < Math.Min(x.Count, y.Count); i++)\n        {\n            result = comparer.Compare(x[i], y[i]);\n            if (result != 0) return result;\n        }\n        return x.Count.CompareTo(y.Count);\n    }\n}	0
17039069	17007501	CLR: Convert a (C#) string into a null-terminated array of char (C)?	char* str2 = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(textBox1->Text);	0
2833447	2833397	How to handle with multiple selection ListBox? asp.net c#	ListBox.SelectionMode	0
32013233	31849562	Correct way to conduct multiple windows in Caliburn Micro?	SystemTrayVM\n      (VM for your notification area, its View is the sys tray icon)\n                                |\n                                |\n                      MultipleDesktopManager\n      (not a VM, not a ConductorBase, no View, not visible)\n                                |\n            .-------------------|------------------.\n            |                   |                  |\n            |                   |                  |\n    SingleDesktopVM      SingleDesktopVM     SingleDesktopVM\n(its View holds child views. If necessary, it can be a ConductorBase)\n                                |\n                  .-------------|------------.------ - - - .\n                  |             |            |\n                  |             |            |\n         SideBarChildVM    MainChildVM   FooterChildVM	0
27391363	27391224	Why can't I access a private static method in one half of a partial class from the other half?	namespace FirstHalf\n{\n    public class Base\n    {\n        protected static void PrintFoo()\n        {\n            Console.WriteLine("Foo");\n        }\n    }\n}\n\nnamespace SecondHalf\n{\n    public class Derived : FirstHalf.Base\n    {\n        public static void Main(string[] args)\n        {\n            PrintFoo();\n        }\n    }\n}	0
31514703	15632956	Check if app runs on Simulator	bool isRemote = Windows.System.RemoteDesktop.InteractiveSession.IsRemote;	0
11385450	11383387	Win7 service with HTTPListener stops responding after one request	private void OnRequestReceive(IAsyncResult result) \n{ \n    HttpListener listener = (HttpListener)result.AsyncState; \n\n    HttpListenerContext context = listener.EndGetContext(result); \n    HttpListenerResponse response = context.Response; \n    byte[] buff = {1,2,3}; \n\n    response.Close(buff, true); \n\n    // ---> start listening for another request\n    listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener); \n}	0
14147538	14135869	RhinoMocks - when a method is called n times, how to test its parameters in the n - k call	GetArgumentsForCallsMadeOn(Action<T>)	0
5050228	5050197	Error in Updating a table using Stored procedure	CONVERT(VARCHAR(10), @AtDate, 101) AS [MM/DD/YYYY]	0
11610623	11610568	Regex syntax with quotes	string regex = @"<li\sclass=""f""(.*?)</li>";	0
20008982	19986927	MySQL equivalent of SQLite SQLiteConnectionContext	context.test_table.Add(myEntity);	0
5441568	5441272	Control resizing mathematics	button1.Left = Math.Min(mouseX, originalMouseX);\nbutton1.Width = Math.Abs(mouseX - originalMouseX);\n\n// the same for Y	0
2304338	2304326	Filtering a list of processes based on a list of string objects	var targetNames = new [] { "processone", "Processtwo" };\n\nvar processes = from p in Process.GetProcesses()\n                where targetNames.Any(n => n == p.ProcessName)\n                select p;	0
1699592	1699543	Stopping timer in its callback method	private void CreatorLoop(object state) \n {\n   if (Monitor.TryEnter(lockObject)\n   {\n     try\n     {\n       // Work here\n     }\n     finally\n     {\n       Monitor.Exit(lockObject);\n     }\n   }\n }	0
3969897	3964517	How do I set up a Silverlight hyperlinkbutton that actually navigates?	NavigationService.Navigate()	0
22806926	22806856	How to substract current url in C#?	var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);	0
3942470	3942299	Dynamically checking each KeyValuePair value of a model	private IEnumerable<ViewModel> GetInvalidModels(ViewModel[] viewModels)\n    {\n        return \n            from viewModel in viewModels \n            from prop in typeof(ViewModel).GetProperties() \n            let ruleType = ((KeyValuePair<object, RuleType>)prop.GetValue(viewModel, null)).Value \n            where ruleType != RuleType.Success \n            select viewModel;\n    }	0
1492129	1492079	Calculate the start-date and name of a quarter from a given date	DateTime date;\nint quarterNumber = (date.Month-1)/3+1;\nDateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber-1)*3+1,1);\nDateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);	0
8692265	8692216	Control position in TableCell	Label l = new Label\n  {\n     Text = "<br>" + image.description                     \n};	0
14627985	14627935	c# inserting variable in JSON string by escaping quotes	string json = @"  \n{\n    ""Request"": \n    {\n       ""ElementList"": \n        {                                         \n        ""id"": "+ idValue + @"""                                        \n        }                         \n     }\n }";	0
12675926	12675887	Regex to match comma in string	,(?=\w+:)	0
32356807	32355476	Is there a way to get each value from entry.Collection in ef code first?	foreach(var x in (IEnumerable) c.CurrentValue){\n  // do something with the entity here\n}	0
29491027	29483582	Formatted text on SelectedIndexChanged in Combobox	private void CmbBx_TextChanged(object sender, EventArgs e)\n    {\n        if (this.cmbBx.Text != string.Empty \n            && !this.cmbBx.Text.Contains(".25")\n            && !this.cmbBx.Text.Contains(".50")\n            && !this.cmbBx.Text.Contains(".75"))\n        {\n            this.cmbBx.Items.Clear();\n\n            this.cmbBx.Items.Add(this.cmbBx.Text + ".25");\n            this.cmbBx.Items.Add(this.cmbBx.Text + ".50");\n            this.cmbBx.Items.Add(this.cmbBx.Text + ".75");\n        }\n\n        if (this.cmbBx.Text == string.Empty)\n        {\n            this.cmbBx.Items.Clear();\n        }\n\n        SendKeys.Send("{F4}");\n    }	0
2871632	2863934	show data in gridview using condition	string query = string.empty;\nif(loginid.equels('admin')) \n{\n    query = "select * from memberlist";         \n}\nelse\n{\n    query = "select * from memberlist where memberid like 'operator%'";\n}\nSqlDataAdapter da = new SqlDataAdapter(query,sqlCon);\nDataSet ds = new DataSet("aa");\nda.Fill(ds, "ww");\ngvData.DataSource = ds.Tables["ww"];\ngvData.DataBind();	0
5673926	5673315	xml parsing need help to solve if xml files are edited manually	var x = XElement.Load(@"C:\Work\ANTScripts_Check_IN.xml");\nvar machine = comboBox1.SelectedValue;\nvar buildStream = comboBox2.SelectedValue;\n\nvar xElement = x.Element("buildmachine" + machine).Elements().First(el => el.Attributes().Any(a => a.Value.Contains(buildStream)));\nvar p = new Process\n{\n    StartInfo = new ProcessStartInfo(xElement.Attribute("exe").Value, xElement.Attribute("folder").Value)\n};\np.Start();	0
11949685	11949035	More complicated URL's in WebAPI controller than basic CRUD	routes.MapHttpRoute(\n    name: "ActionApi",\n    routeTemplate: "api/{controller}/{action}/{id}",\n    defaults: new { id = RouteParameter.Optional }\n);\n\npublic class CampaignsController : ApiController\n{\n    [HttpPost]\n    public void send();\n\n    [HttpPost]\n    public void schedule(DateDto date);\n}	0
14458121	14457632	selected item to Textbox-Exception	myTextBox1.SetBinding(TextBlock.TextProperty, (new Binding("SelectedItem." +   dataGrid1.Columns[5].Header) { ElementName = "dataGrid1" }))	0
2663537	2663528	Returning value of static property from public instance property	public class SomeClass\n{\n   public string GetValue() { return "some string"; }\n   public void SetValue(string arg)\n   { \n       SetValue(arg); // recursively calls itself until stackoverflow\n   }\n}	0
22568290	22568251	How to implement Baudot encoding	public class Baudot {\n    public const char Null = 'n';\n    public const char ShiftToFigures = 'f';\n    public const char ShiftToLetters = 'l';\n    public const char Undefined = 'u';\n    public const char Wru = 'w';\n    public const char Bell = 'b';\n    private const string Letters = "nE\nA SIU\rDRJNFCKTZLWHYPQOBGfMXVu";\n    private const string Figures = "n3\n- b87\rw4',!:(5\")2#6019?&u./;l";\n\n    public static char? GetFigure(int key) {\n        char? c = Figures[key];\n        return (c != Undefined) ? c : null;\n    }\n\n    public static int? GetFigure(char c) {\n        int? i = Figures.IndexOf(c);\n        return (i >= 0) ? i : null;\n    }\n\n    public static char? GetLetter(int key) {\n        char? c = Letters[key];\n        return (c != Undefined) ? c : null;\n    }\n\n    public static int? GetLetter(char c) {\n        int? i = Letters.IndexOf(c);\n        return (i >= 0) ? i : null;\n    }\n}	0
30641177	30640702	unable to convert uploaded image to byte array	public byte[] ConvertToBytes(HttpPostedFileBase image)\n{\n   return image.InputStream.StreamToByteArray();\n}\n\npublic static byte[] StreamToByteArray(this Stream input)\n{\n    input.Position = 0;\n    using (var ms = new MemoryStream())\n    {\n        int length = System.Convert.ToInt32(input.Length);\n        input.CopyTo(ms, length);\n        return ms.ToArray();\n    }\n}	0
12594164	12594072	implement abstract byref method in c#	Main_BO bo = new Main_BO() ;\n// ...\nBase_BO br = bo ;\nbo = (Main_BO) bll.Persist (ref br) ;	0
26779287	26778733	Uploading a file into SQL Server	string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data\nSource={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", \nServer.MapPath(@"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" +\nFileUploadControl.PostedFile.FileName.ToString());\nusing (OleDbConnection connection = new OleDbConnection(excelConnectionString))\n{\n   OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2]  FROM [Sheet1$]"), \n   connection);\n   connection.Open();\n   using (DbDataReader dr = command.ExecuteReader())\n   {\n   }\n}	0
22000945	22000775	Changing Color by Reading from File	private SolidColorBrush ColorNameToBrush(string colorName)\n{\n    Color color = Color.FromArgb(0,0,0,0);\n    if (colorName == "Red")\n    {\n        color = new Color() { R = 255, G = 0, B = 0};\n    }\n    else if ...\n    {\n\n    }\n\n    return new SolidColorBrush(color);\n}	0
2709598	2709575	How to open a large text file in C#	using System;\nusing System.IO;\n\nclass Test \n{\n    public static void Main() \n    {\n        try \n        {\n            // Create an instance of StreamReader to read from a file.\n            // The using statement also closes the StreamReader.\n            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                    Console.WriteLine(line);\n                }\n            }\n        }\n        catch (Exception e) \n        {\n            // Let the user know what went wrong.\n            Console.WriteLine("The file could not be read:");\n            Console.WriteLine(e.Message);\n        }\n    }\n}	0
29130072	29129397	Remove all classes and ids from parsed HTML with HtmlAgilityPack	HtmlNode bodyContent = document.DocumentNode.SelectSingleNode("//body");\nvar all_text = bodyContent.SelectNodes("//div | //ul | //p | //table");\n\nforeach(var node in all_text)\n{\n   node.Attributes.Remove("class");\n   node.Attributes.Remove("id");\n}	0
26169701	26169548	Generate Unique Random Number	NaturalID ObfuscatedID	0
11012268	11012176	Get entry from list by name	List<Form> xxx = new List<Form>();\nint count = xxx.FindAll(x => x.Name.Equals("YourFormName")).Count();	0
20398390	20397226	access the title of a window using vbscript	Dim Tasks\n    Tasks = Split(WScript.CreateObject("WScript.Shell").Exec("tasklist /v /fo csv").StdOut.ReadAll(),vbCrLf)\n\nDim task\n    For Each task In Tasks\n        task = Split(Trim(task),",")\n        If Ubound(task) >= 8 Then\n            WScript.Echo "Process " + task(0) + "ID: " + task(1) + " Title: " + task(8)\n        End If\n    Next	0
2968507	2960103	How do I launch a subprocess in C# with an argv? (Or convert agrv to a legal arg string)	/**\n * Let's assume 'command' contains a collection of strings each of which is an\n * argument to our subprocess (it does not include arg0).\n */\nstring args = "";\nstring curArg;\nforeach (String s in command) {\n    curArg = s.Replace("'", "'\\''"); // 1.) Replace ' with '\''\n    curArg = "'"+curArg+"'";          // 2.) Surround with 's\n    // 3.) Is removal of unnecessary ' pairs. This is non-trivial and unecessary\n    args += " " + curArg;\n}	0
28495027	28478603	Load GUISkin from file?	IEnumerator LoadSkin()\n{\n  var www = new WWW("file:///" + Path.Combine(Path.Combine(Path.Combine(Application.dataPath, "Mods"), "Internal"), "EditorSkin.unity3d"));\n  yield return www;\n  if (www.error != null)\n        yield break;\n\n  GUI.skin = www.assetBundle.mainAsset as GUISkin;\n}	0
5251452	5251159	C# - Regular Expression to split string on spaces, unless a double quote is encountered	('{1}(\w|\s|:|\\|\.)+'{1}|\w)+	0
26510152	26510094	Async await how to use return values	await Task.WhenAll(partNumberCollection, additionalProductDetials);\n\nvar partNumberCollectionResult = partNumberCollection.Result;\nvar additionalProductDetialsResult = additionalProductDetials.Result;	0
519036	518994	Can a base class determine if a derived class has overriden a virtual member?	public interface IHasSharedData\n{\n    void UpdateSharedData();\n}\n\npublic abstract class Task\n{\n    private static object LockObject = new object();\n\n    protected virtual void UpdateNonSharedData() { }\n\n    public void Method()\n    {\n         if (this is IHasSharedData)\n         {\n            lock(LockObject)\n            {\n                UpdateSharedData();\n            }\n         }\n         UpdateNonSharedData();\n    }\n}\n\npublic class SharedDataTask : Task, IHasSharedData\n{\n    public void UpdateSharedData()\n    {\n       ...\n    }\n}	0
18149368	18149110	How to load a PDF into memory then read it via acrobat reader?	//Get the path\nvar path = @"C:\Users\MyUser\My Documents\MyPdf.pdf"\n//Open adobe reader with the file\nProcess.Start(path);	0
11441824	11441735	How to find all empty files recursively	DirectoryInfo di = new DirectoryInfo("c:\\Luke101");\n    FileInfo[] fiArr = di.GetFiles();\n\n    foreach (FileInfo fi in fiArr)\n    {\n        if(fi.Length == 0)\n        {\n            //.. Then do stuff\n        }\n    }	0
18008397	18008065	Using Transactions or Locking in Entity Framework to ensure proper operation	//Object Property:\npublic byte[] RowVersion { get; set; }\n//Object Configuration:\nProperty(p => p.RowVersion).IsRowVersion().IsConcurrencyToken();	0
34354831	34353124	Using Rebus as an ESB	await bus.Publish(yourMessage)	0
18247064	17421978	How to parse a simple list of items with NDesk Options in C#	OptionSet options = new OptionSet()\n        {\n            {"f|file", "a list of files" , v => {\n                currentParameter = "f";\n            }},\n            {"p", @"Parameter values to use for variable resolution in the xml - use the form 'Name=Value'.  a ':' or ';' may be used in place of the equals sign", v => {\n                currentParameter = "p";\n            }},\n            { "<>", v => {\n                switch(currentParameter) {\n                    case "p":\n                        string[] items = v.Split(new[]{'=', ':', ';'}, 2);\n                        Parameters.Add(items[0], items[1]);\n                        break;\n                    case "f":\n                        Files.Add(Path.Combine(Environment.CurrentDirectory, v));\n                        break;\n                }\n            }}\n        };\noptions.Parse(args);	0
1482159	1482034	ExtJS: how to return json success w/ data using asp.net mvc	public JsonResult Index()\n{\n    var json = new\n    {\n        success = true,\n        data = from user in repository.FindAllUsers().AsQueryable()\n               select new\n               {\n                   id = user.Id,\n                   name = user.Name,\n                   ...\n               }\n    };\n    return Json(json);\n}	0
5565488	5565382	How to export gridview to Excel in ASP.net using C#?	System.IO.StringWriter sw = new System.IO.StringWriter();\nHtmlTextWriter htw = new HtmlTextWriter(sw);\nResponse.AddHeader("content-disposition", "attachment; filename=" + strFileName);\nResponse.ClearContent();\n\nResponse.AddHeader("content-disposition", attachment);\n\ndg.RenderControl(htw);\nResponse.Write(sw.ToString());\nResponse.Flush();\nResponse.End();	0
7249318	7249254	Retrieving Inner Text of Html Tag C#	HtmlDocument doc = new HtmlDocument();\nstring html = /* whatever */;\ndoc.LoadHtml(html);\nforeach(HtmlNode td in doc.DocumentElement.SelectNodes("//td[@class='container']")\n{\n    string text = td.InnerText;\n    // do whatever with text\n}	0
1091654	1091570	how to play a mp3 file from the middle	long millisecs = 120000;\nlong status = mciSendString(String.Format("seek MediaFile to {0}", millisecs), null, 0, IntPtr.Zero);	0
11127941	11127488	Change Entity model database at runtime	string training = ConfigurationManager.ConnectionStrings["Train"].ToString();\nstring production = ConfigurationManager.ConnectionStrings["Prod"].ToString();\n\n.....\nEFContext context = null;\nif (InTraining) \n   context = new EfContext(training);\nelse\n   context = new EfContext(production);	0
6437206	6434796	How to open a form within a form?	private void button1_Click(object sender, EventArgs e)\n        {\n            this.IsMdiContainer = true;\n            Form Form2 = new Form();\n            Form2.MdiParent = this;\n            Form2.Show();\n        }	0
3769941	3760639	Any Framework functions helping to find the longest common starting substring of multiple strings?	public static string GetCommonStartingSubString(IList<string> strings)\n    {\n        if (strings.Count == 0)\n            return "";\n        if (strings.Count == 1)\n            return strings[0];\n        int charIdx = 0;\n        while (IsCommonChar(strings, charIdx))\n            ++charIdx;\n        return strings[0].Substring(0, charIdx);\n    }\n    private static bool IsCommonChar(IList<string> strings, int charIdx)\n    {\n        if(strings[0].Length <= charIdx)\n            return false;\n        for (int strIdx = 1; strIdx < strings.Count; ++strIdx)\n            if (strings[strIdx].Length <= charIdx \n             || strings[strIdx][charIdx] != strings[0][charIdx])\n                return false;\n        return true;\n    }	0
10720603	10720498	How can i change the text format of a Excel Cell using C#?	public void SetCustomFormat(string format, int r, int c)\n{\n    ((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;\n}	0
26775047	21043460	C# Prevent WP browser from opening Bing app	private bool _customHeaderRequest = false;\n\nprivate void MainBrowser_Navigating(object sender, NavigatingEventArgs e)\n{\n    string host = e.Uri.Host.ToLowerInvariant().Trim();\n\n    if ((host == "bing.com" || host.EndsWith(".bing.com")) && !_customHeaderRequest)\n    {\n        e.Cancel = true;\n\n        Dispatcher.BeginInvoke(() =>\n            MainBrowser.Navigate(e.Uri, null,\n                "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 710)\r\n"));\n\n        _customHeaderRequest = true;\n        return;\n    }\n\n    _customHeaderRequest = false;\n}\n\nprivate void MainBrowser_Navigated(object sender, NavigationEventArgs e)\n{\n    _customHeaderRequest = false;\n}	0
6044311	5987971	Add custom labels to the yaxis instead of actual values in Zedgraph	...\n    yAxis.ScaleFormatEvent += yAxis_ScaleFormatEvent;\n}\n\nprivate string yAxis_ScaleFormatEvent(GraphPane pane, Axis axis, double val, int index)\n{\n    if (val == 0) return "Min";\n    else if (val == 0) return "Max";\n    else if(val == 0.5) return val.ToString();\n    else return "";\n}	0
12362659	12359444	File Open dialog box is not going to right directory in c# application on windows xp	openFileDialog1.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments)	0
23780948	23780376	Design data structure for Employee-Manager	public class Employee\n{\n\n    public string ID;\n    public Manager Manager;\n\n    public Manager promote() { return new Manager(this); }\n\n    public Employee() { }\n\n}\n\npublic class Manager : Employee\n{\n\n    public List<Employee> Employees;\n\n    public Manager() { }\n    public Manager(Employee employee) {...}\n\n}\n\npublic class EmployeeModel\n{\n\n    private List<Employee> employees;\n    public List<Employee> Employees { get { return this.employees; } }\n\n    public void addEmployee(...) {...}\n    public void removeEmployee(...) {...}\n    public void promoteEmployee(...) {...}\n\n}	0
23917930	23917777	"for" Loop for printing	foreach (DataRow dr in dtaGI.Rows)\n{\n    Label = ARchivos.Clone().ToString();\n    Label=  Label.Replace("[&PRODUCTDESCR]", dr["Description"].ToString())\n     .Replace("[&PRODUCTCODE]", dr["ProductCode"].ToString())\n     .Replace("[&PACKDESC]", dr["PAckDescr"].ToString())\n     .Replace("[&ROTATION]", dr["rotationNum"].ToString())\n     .Replace("[&SIZE]", dr["CaseLOL"].ToString() + "L")\n     .Replace("[&BPC]", dr["CasesPerPallet"].ToString());\n    TotalLabel = "              Total  " +dr["cases"].ToString() +  "c  " + dr["Bottles"] +"b";\n\n    for(int i = 0 ;i<Convert.ToInt32( dr["cases"]);i++)\n    {\n         Labels.Append(Label.Replace("[&TOTALS]", "1 Case   " + TotalLabel )).Append(Environment.NewLine );\n    }\n\n    if (dr["Bottles"].ToString() != "0") {\n         Labels.Append(Label.Replace("[&TOTALS]", dr["Bottles"].ToString() + " Bottles" + TotalLabel)).Append(Environment.NewLine);\n    }\n}	0
6326783	6326776	Input string was not in a correct format - Converting textbox text to Int32	Int32.TryParse()	0
28493258	28491805	ASP ajax gripview ItemTemplate	protected void btnAjax_Click(object sender, EventArgs e)\n{\n\n    try\n    {\n        foreach (GridViewRow gvRow in dgvUserGroup.Rows)\n        {\n            CheckBox chk = (CheckBox)gvRow.FindControl("chkRow");\n            Boolean chkVal = chk.Checked;//Here You can get the value\n        }\n    }\n    catch (Exception ex)\n    {\n    }\n}	0
10485969	10485903	regex extract value from the string between delimiters	string pattern = @"(?<=category = ').*(?=';)";\nstring productCategory = Regex.Match(html, pattern ).Value;	0
29897251	29897182	Compilation Error- Array of byte initialization	var rgbIV = new Byte[] {0x21, 0x43, 0x56, 0x87, 0x10, 0xFD, 0xEA};	0
22405815	22348282	How to read from MongoDB	public static void MongoConnection()\n        {\n            var connectionString = "mongodb://localhost";\n            var mongoClient = new MongoClient(connectionString);\n            var mongoServer = mongoClient.GetServer();\n            var databaseName = "PointToPoint";\n            var db = mongoServer.GetDatabase(databaseName);\n            var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");\n            var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, "4B414D000000011613CD");\n            var foundMongoDB = mongodb.FindOne(mongodbQuery);\n        }	0
30789085	30789037	How can I set Application State expiration?	Application["MyData"] = myData;\n///Do something.\n...\n..\n.\nApplication["MyData"] = myNewData;	0
259146	227187	UAC need for console application	mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"	0
26654912	26653838	`ScrollToCaret` scrolls to the end of the selected text, how can I scroll to the begining of it?	[DllImport("user32.dll")]\nstatic extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);    \n\nint numLines = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);\n//scroll to top\nSendMessage(textBox1.Handle, 0x115, 6, 0); //WM_VSCROLL\n//scroll numLines\nSendMessage(textBox1.Handle, 0xB6, 0, numLines); //EM_LINESCROLL	0
7537452	7533323	How to pass a variable on pushpin button press?	public void BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)\n{\n\n    var item = (sender as Pushpin).Tag as TransitVariables;\n\n    if (item != null)\n    {\n        string id = item.name;\n\n       NavigationService.Navigate(new Uri("/DepBoard.xaml?ListingId=" + id, UriKind.Relative));\n       MessageBox.Show("Bus Stop Number " + id);\n\n    }\n}	0
12047349	11893962	Avalonedit how to programmatically change background of a text	TxtEditCodeViewer.TextArea.TextView.Redraw();	0
20952763	20952653	Getting dates in reverse chronological order in .NET	for (int i = 0; i < 10; i++)\n{\n  DateTime date = DateTime.Now.AddDays(-i);\n  Console.WriteLine(String.Format("{0:d MMMM}",date));\n}	0
28271254	28269959	Auto clear textbox after barcode input and passing the value to a string	private void txtStudentID_TextChanged(object sender, EventArgs e)\n        {\n            timer1.Interval = (700);\n            timer1.Enabled = true;\n            timer1.Start();\n        }\n\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n            timer1.Stop();\n            a = txtStudentID.Text;\n            displayData(a);// i put the txtStudentID.Clear() at the end of the method. I think i need some rest. :)\n        }	0
7282225	7282141	What's the best way to adding a user's signature to a PDF document online?	PdfReader pdfReader = null;\nPdfStamper pdfStamper = null;\n\n// Open the PDF file to be signed\npdfReader = new PdfReader(this.signFile.FullName);\n\n// Output stream to write the stamped PDF to\nusing (FileStream outStream = new FileStream(targetFilename, FileMode.Create))\n{\n  try\n  {\n    // Stamper to stamp the PDF with a signature\n    pdfStamper = new PdfStamper(pdfReader, outStream);\n\n    // Load signature image\n    iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(SIGNATURE_IMAGE_PATH);\n\n    // Scale image to fit\n    sigImg.ScaleToFit(MAX_WIDTH, MAX_HEIGHT);\n\n    // Set signature position on page\n    sigImg.SetAbsolutePosition(POS_X, POS_X);\n\n    // Add signatures to desired page\n    PdfContentByte over = pdfStamper.GetOverContent(PAGE_NUM_TO_SIGN);\n    over.AddImage(sigImg);\n  }\n  finally\n  {\n    // Clean up\n    if (pdfStamper != null)\n      pdfStamper.Close();\n\n    if (pdfReader != null)\n      pdfReader.Close();\n  }\n}	0
3152726	3152699	MVC 2 website - Cant get a list of files in the images folder	string path = Server.MapPath(typeModel.ArtUrl);	0
21763575	21763428	How to handle label as a variable populated with sql query	if (dt.Rows.Count == 0)\n    conSpell.Text = string.Empty;\n\nforeach( ... your code )	0
1065694	1065648	How do I get the values of the controls in the first row of a listview in c# aspnet?	ListViewDataItem theFirstItem = ListView1.Items[0];\nLabel lblStatus = (Label)theFirstItem.FindControl("lblStatus")\nResponse.Write(lblStatus.Text);      // outputs the text of that label	0
2590446	2590334	Creating a Cross-Process EventWaitHandle	// create a rule that allows anybody in the "Users" group to synchronise with us\nvar users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);\nvar rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,\n                          AccessControlType.Allow);\nvar security = new EventWaitHandleSecurity();\nsecurity.AddAccessRule(rule);\n\nbool created;\nvar wh = new EventWaitHandle(false, EventResetMode.AutoReset, "MyEventName", out created, security);\n...	0
31433474	31433438	Can't validate date in c#	if (DateTime.TryParseExact(date, "dd/MM/yyyy", null, DateTimeStyles.None, out Test) == true) {\n    ...	0
30258632	30258394	Drog and Drop TableLayoutPanel in a panel?	private void panel2_DragEnter(object sender, DragEventArgs e) {\n        if (e.Data.GetDataPresent(typeof(TableLayoutPanel))) e.Effect = DragDropEffects.Move;\n    }\n\n    private void panel2_DragDrop(object sender, DragEventArgs e) {\n        var tlp = (TableLayoutPanel)e.Data.GetData(typeof(TableLayoutPanel));\n        tlp.Location = panel2.PointToClient(new Point(e.X, e.Y));\n        tlp.Parent = panel2;\n        tlp.BringToFront();\n    }	0
9494898	9494871	Casting my Class to Int64, Double etc	class MyDouble\n{\n    double value;\n\n    public static explicit operator Int64(MyDouble value)\n    {\n         return (Int64)value.value;\n    }\n}	0
13807361	12397351	SettingsProviderAttribute replacement for application-level custom SettingsProvider	internal sealed partial class Settings {\n\n    public Settings() {\n\n        SettingsProvider provider = CreateAnArbitraryProviderHere();\n\n        // Try to re-use an existing provider, since we cannot have multiple providers\n        // with same name.\n        if (Providers[provider.Name] == null)\n            Providers.Add(provider);\n         else\n            provider = Providers[provider.Name];\n\n        // Change default provider.\n        foreach (SettingsProperty property in Properties)\n        {\n            if (\n                property.PropertyType.GetCustomAttributes(\n                    typeof(SettingsProviderAttribute),\n                    false\n                ).Length == 0\n             )\n             {\n                 property.Provider = provider;\n             }\n         }\n     }\n}	0
32002407	32002383	How do I use lazy with an initializer?	Lazy<Foo[]> f = new Lazy<Foo[]>(() => new[] { new Foo { y = 1 }, new Foo { y = 3 } });	0
2401359	2401311	OWC11 Date Formatting Ignored	cell.set_Value(XlRangeValueType.xlRangeValueDefault, val);	0
6303319	6303266	how to ignore the seconds ToShortTimeString	Value.ToString("HH:mm")	0
22762680	22762417	C# Generic behavior with C++ Templates	template< class T >\nstruct MyGeneric\n{\n    void MyTypeSafeMethod( T& arg1 )\n    {\n        //logic here\n    }\n};\n\nstruct MyImplA : MyGeneric<MyImplA>\n{\n    //Class config etc..\n};\n\nstruct MyImplB : MyGeneric<MyImplB>\n{\n    //Other config etc...\n};\n\nstruct MyCollectionOfGenericImpl\n{\n    static MyImplA A;\n    static MyImplB B;\n};\n\nMyImplA MyCollectionOfGenericImpl::A;\nMyImplB MyCollectionOfGenericImpl::B;\n\nauto main()\n    -> int\n{\n    //Doesn't compile, method is typesafe \n    MyCollectionOfGenericImpl::A.MyTypeSafeMethod( MyCollectionOfGenericImpl::B );\n}	0
17788765	17786368	nhibernate mapping by code: Using interfaces with one to many relationships	using NHibernate;\nusing NHibernate.Mapping.ByCode;\nusing NHibernate.Mapping.ByCode.Conformist;\n\npublic class PersonMapping : ClassMapping<Person>\n{\n    public PersonMapping()\n    {\n        ...\n\n        ManyToOne(x => x.Address, map =>\n                                   {\n                                       map.Column("AddressId");                                           \n                                       map.Class(typeof(Address));\n                                   }\n            );\n\n       ...\n    }\n}	0
1900281	1900191	How to select current menu in master pages?	public class MyMasterPage : MasterPage\n{\n    public string MyMenuProperty { get; set; }\n\n    protected void Page_PreRender(object sender, EventArgs e)\n    {\n        if (MyMenuProperty == "comedy")\n        {\n            /* do your menu stuff */\n        }\n    }\n}\n\npublic class MyContentPage : Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        var myMaster = Page.Master as MyMasterPage;\n        if (myMaster != null)\n        {\n            myMaster.MyMenuProperty = "comedy";\n        }\n    }	0
13461225	12744974	change json object wrapper name returned from wcf service method	[OperationContract]\n    [WebInvoke(UriTemplate = "/Login", Method = "POST",\n        BodyStyle = WebMessageBodyStyle.Wrapped,\n        ResponseFormat = WebMessageFormat.Json,\n        RequestFormat = WebMessageFormat.Json)] \n    [return: MessageParameter(Name = "success")]\n    MyDictionary<string, string> TestMe(string param1, string param2);	0
20409092	20409026	How to remove char '*' from Console Window? Command Console.Write("\b"); didn't work	private static string Password()\n{\n    bool enter = true;\n    string pass = "";\n    do\n    {\n        char letter = Console.ReadKey(true).KeyChar;\n        if (letter == (char)13)\n        { enter = false; }\n        else if (letter == (char)8 && pass.Length >= 1)\n        {\n            pass = pass.Remove(pass.Length - 1);\n            Console.CursorLeft--;\n            Console.Write('\0');\n            Console.CursorLeft--;\n        }\n        //Additionally, don't print backspaces if it's the first character.\n        else if (letter != (char)8)\n        {\n            pass += letter;\n            Console.Write("*");\n        }\n    } while (enter);\n    Console.WriteLine();\n    return pass;\n}	0
23876455	23876425	How to add zero number to some nober with help of Loop?	string str = "12";\nstr.PadLeft(1, '0') // 12\nstr.PadLeft(2, '0') // 12\nstr.PadLeft(3, '0') // 012\nstr.PadLeft(4, '0') // 0012	0
16241482	16241333	specify a value can be a string or null with json schema	"member_region": { "type": [ "string", "null" ] }	0
21122947	21122667	How do I get my context menu to appear in a certain place?	void label1_MouseDown(object sender, MouseEventArgs e) {\n  if (e.Button == MouseButtons.Left) {\n    contextMenuStrip1.Show(label1, e.Location);\n  }\n}	0
11637414	11637348	Encrypt connection string in app.config	System.Configuration.SectionInformation.ProtectSection	0
17352786	17352442	Displaying Raw Data From Image File Using TextBox or RichTextBox?	textbox.Text = data.Replace("\0", @"\0");	0
6847354	6843065	error with SqlCe Parameters	string sqlString = "SELECT " + columnIdName + \n" FROM " +tableName "WHERE " + keyColumnName + "= @key";	0
22849948	22849726	One Dimensional Array to Multidimensional Array	int indexModifier = 0;\n\nfor (int i = 0; i < Math.sqrt(second.Length); ++i)\n{\n    for (int j = 0; j < Math.sqrt(second.Length); ++j)\n    {\n        second[j + indexModifier, j] = first[i + indexModifier);\n    }\n    ++indexModifier;\n}	0
23552072	23552004	Assigning value to string variable	string someName = (string)xdoc.Descendants("name").First();	0
8463035	8456178	How to change backcolor row in Janus Grid with condition	private void Grd_Detail_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)\n{\n    int i = 1;\n    for (i = 0; i < Grd_Detail.RowCount; i++)\n    {\n        string s = Grd_Detail.GetRow(i).Cells["FN"].Value.ToString();\n        if (s == "True")\n        {\n            if (e.Row.RowType == Janus.Windows.GridEX.RowType.Record)\n            {                 \n                Janus.Windows.GridEX.GridEXFormatStyle rowcol = new GridEXFormatStyle();\n                rowcol.BackColor = Color.LightGreen;\n                Grd_Detail.GetRow(i).RowStyle = rowcol;\n            }\n        }\n    }\n}	0
15439597	15439489	Regular expression to extract data from log file	var mkeys = Regex.Match(logLine, @"Summary[^\[]+\[(?<mkeys>[^\]]+\]").Groups["mkeys"].Value	0
13076714	13076646	private variables resetting between methods c#	public int messageID\n{\n   get \n   { \n      int retVal = 0;\n      if(ViewState["messageID"] != null)\n         Int32.TryParse(ViewState["messageID"].ToString(), out retVal); \n\n      return retVal;\n   }\n   set { ViewState["messageID"] = value; }\n}	0
17843972	17843878	Cannot find button element C#	driver.FindElement(By.XPath("//button[@type='submit'][text()='Log in']")	0
10731354	10728720	How to query entities from a collection without using foreach	var ordersAndLine=(from f in myOrders select f).ToList();\n\nvar query=(from f in ORDERS\nfrom s in ordersAndLine\nwhere s.ORDER_ID==f.ORDERS\n&& s.LINE==f.ORDERS_SUFFIX\nselect f).ToList();	0
26107438	26106695	Converting int value to a color in a gradient	Color[] colors = new Color[] { Colors.Black, Colors.Blue, Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Orange, Colors.Red, Colors.White, Colors.Transparent };\n    public Color IntToColor(int i)\n    {\n        float scaled = (float)(i + 148) / 158 * 7;\n        Color color0 = colors[(int)scaled];\n        Color color1 = colors[(int)scaled + 1];\n        float fraction = scaled - (int)scaled;\n        Color result = new Color();\n        result.R = (byte)((1 - fraction) * (float)color0.R + fraction * (float)color1.R);\n        result.G = (byte)((1 - fraction) * (float)color0.G + fraction * (float)color1.G);\n        result.B = (byte)((1 - fraction) * (float)color0.B + fraction * (float)color1.B);\n        result.A = 255;\n        return result;\n    }	0
18458824	18458655	How to get total shipping cost for an order ebay getOrders API	if (order.ShippingServiceSelected.ShippingServiceCost != null)\n{\n    ShippingCost = order.ShippingServiceSelected.ShippingServiceCost.Value\n}	0
30117954	30117915	C# application freezes	private void timer1_Tick(object sender, EventArgs e)\n{\n    Task.Factory.StartNew(() =>\n    {\n        using (SshClient cSSH = new SshClient("ip", 22, "root", "pass")\n        {\n            cSSH.Connect();\n            SshCommand x = cSSH.RunCommand("ssh command");\n        }\n    });\n}	0
25482868	25482660	Update a SQL Server table in one server from another server in C#	ConnectionString1 = @"Data Source=Server1;Initial Catalog=Database1;User ID=UID1;Password=Password1"\nINSERT INTO [DatabaseName1].[dbo].[TableName]\nSELECT FieldName\nFROM OPENDATASOURCE('SQLNCLI',\n'Data Source=Server2;Initial Catalog=Database2;User ID=UID2;Password=Password2')\n.DatabaseName2.dbo.TableName	0
421766	417121	How can I programatically translate a MSSQL server alias to an IP address using .NET?	using Microsoft.Win32;\n\nstatic void Main(string[] args)\n{\n        var Aliases = Registry.LocalMachine.OpenSubKey(\n    @"SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo");\n        Aliases.GetValue("Alias");\n}	0
11418809	11418750	How to implement Method that calls itself?	int num;\nwhile (!int.TryParse(Console.ReadLine(), out num))\n{\n    Console.WriteLine("Your input is not valid, please try again.\n");\n}	0
14882508	14882283	Generate controls at runtime	// generate button at runtime\nButton btn = new Button();\n\n// setting properties\nbtn.Height = 40;\nbtn.Width = 100;\n\n// applying events\nbtn.Clicked += btn_clicked:	0
19322063	19322010	Contain a number just once in an array	HashSet<int>	0
4714108	4714086	C# Regex Help	string filtered = Regex.Replace(expr, "[^A-Za-z]", "");	0
260409	244926	WPF ControlTemplate for scrolling TreeView Control	public class NoScrollTreeView : TreeView\n{\n    public class NoScrollTreeViewItem : TreeViewItem\n    {\n        public NoScrollTreeViewItem() : base()\n        {\n            this.RequestBringIntoView += delegate (object sender, RequestBringIntoViewEventArgs e) {\n                e.Handled = true;\n            };\n        }\n\n        protected override DependencyObject GetContainerForItemOverride()\n        {\n            return new NoScrollTreeViewItem();\n        }\n    }\n    protected override DependencyObject GetContainerForItemOverride()\n    {\n        return new NoScrollTreeViewItem();\n    }\n}	0
17777952	17777914	Private Accessor in C#	class Employee\n{\n     public Employee(string name)\n     {\n         Name = name;\n     }\n\n     private string m_name;\n\n     public string Name\n     {\n         get { return m_name; }\n         protected set { m_name = value; }\n     }\n\n     public void ChangeName(string name)\n     {\n         Name = name;\n     }\n}\n\npublic class Ceo : Employee\n{\n    public Ceo(string name) : base(name)\n    {\n    }\n\n    public void VoteOut()\n    {\n         Name = Name + " (FIRED)";\n    }\n}\n\n\nstatic class MainClass\n{\n    static void Main(string[] args)\n    {\n        var employee = new Employee("Scott Chamberlain");\n\n        Console.WriteLine(employee.Name) //Displays Scott Chamberlain;\n\n        //employee.Name = "James Jeffery"; //Has a complier error if uncommented because Name is not writeable to MainClass, only members of Employee can write to it.\n\n        employee.ChangeName("James Jeffery");\n\n        Console.WriteLine(employee.Name) //Displays James Jeffery;\n    }\n}	0
2453249	2453146	Getting 'this' pointer inside dependency property changed callback	private static void OnCurrentFooChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    FooHolder holder = (FooHolder)d; // <- something like this\n\n    holder.UnwireFoo(e.OldValue as Foo);\n    holder.WireFoo(e.NewValue as Foo);\n}	0
14904925	14904574	Filter a given List based on external List in Linq in one query	var schools = from p in allSchools\n              where (p.LocationId==this.LocationId && p.Students.Any(s => lstStudents.Contains(s)))\n              select p;	0
7268315	7266894	Passing nullable value to a method	if (obj == null) \n    {\n        //// you enter here only if obj is null\n        //Download and Satisfy\n        DeploymentCatalog DC = new DeploymentCatalog("TheXAPfile.xap");\n        DC.DownloadCompleted += (s, e) =>\n        {\n            catalog.Catalogs.Add(f); //catalog is AggregateCatalog\n            //// here you are assuming that obj is not null anymore. Why???\n            obj.Show();\n        };\n        DC.DownloadAsync();\n    }	0
8414365	8414278	Retrieving Column names as per Excel using C#	private static string chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\nprivate static string ConvertNumber(int number)\n{\n  string result;\n  number -= 1;\n  int rest = number % 26;\n  int q = number / 26;\n  if(q == 0)\n  {\n    result = chars[rest].ToString();\n  }else{\n    result = ConvertNumber(q) + chars[rest];\n  }\n  return result;\n}	0
17229241	17229086	is it possible en MVVM use Auto in a property and make binding to the view model?	FrameWorkElement.ActualHeight	0
292317	292307	Selecting Unique Elements From a List in C#	var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };\n\nvar uniqueNumbers =\n    from n in numbers\n    group n by n into nGroup\n    where nGroup.Count() == 1\n    select nGroup.Key;\n\n// { 0, 1, 3, 5 }	0
14446216	14445992	put two shorts to a byte array	buffer.order(ByteOrder.LITTLE_ENDIAN);	0
240560	240531	How do you do end-of-week rounding on a date field in C# (without using LINQ)?	public DateTime WeekNum(DateTime now)\n{\nDateTime NewNow = now.AddHours(-11).AddDays(6);\n\nreturn (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);\n}\n\npublic void Code(params string[] args)\n{\n\nConsole.WriteLine(WeekNum(DateTime.Now));\nConsole.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));\nConsole.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));\nConsole.WriteLine(WeekNum(new DateTime(2008,10,28)));\nConsole.WriteLine(WeekNum(new DateTime(2008,10,25)));\n\n\n}	0
688487	392626	Lost XML file declaration using DataSet.WriteXml(Stream)	MemoryStream stream = new MemoryStream();\nvar writer = XmlWriter.Create(stream);\nwriter.WriteStartDocument(true);\ndSet.WriteXML(stream);	0
18078622	18076984	With Web API, How does Entity Framework know what has changed in an object?	var mypoco = Context.Set<TPoco>.Find(1);  // find and LOAD your poco or sub object poco\n                                          // repeat for graph or use include etc...     \n                                          // now in context and changes can be tracked. (see link)\n// map json fields to poco entity....\nmyPoco.propertyXyz = json.ValuesSent; // some mapping approach to move your values, I use this package \n// <package id="ValueInjecter" version="2.3.3" targetFramework="net45" />\n\n// now tell EF things might have changed.\n// normally not required by default, But incase your are not using tracking proxies , tell ef check for changes\n// Context.Context.ChangeTracker.DetectChanges(); // uncomment when needed\n\nContext.SaveChanged(); // will trigger detect changes in normal scenarios	0
16435672	16365791	Location of WindowsApps folder	using (var appx = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Appx"))\n{\n     var packageRoot = appx.GetValue("PackageRoot");\n}	0
9368474	9368353	Set value property of RadioButton	public class ValueCheckBox : System.Web.UI.WebControls.RadioButton\n{\n    public string Value { get; set; }\n}	0
14014380	14014143	In MVP pattern, how to create a Property of type List<T> in the View, where T is a Data Type generated by Entity Framework?	public class TeamMemberViewModel\n{\n    ...\n}\n\npublic interface IEmployee\n{\n    public List<TeamMemberViewModel> TeamMembers { get; set; }\n}	0
20641084	20640801	Event to add and remove a variable	public event EventHandler<_File> OnFileReceivedEvent;\n\npublic void AddFile(_File file)\n{ \n    // ...\n    // to raise event\n    var handler = OnFileReceivedEvent;\n    if (handler != null)\n        handler(this, file);\n}	0
16904876	16904251	Get default User Account Profile Picture on Windows Vista > 8	using System;\n    using System.Text;\n    using System.Drawing;\n\n    [DllImport("shell32.dll", EntryPoint = "#261", \n               CharSet = CharSet.Unicode, PreserveSig = false)]\n    public static extern void GetUserTilePath(\n      string username, \n      UInt32 whatever, // 0x80000000\n      StringBuilder picpath, int maxLength);\n\n    public static string GetUserTilePath(string username)\n    {   // username: use null for current user\n        var sb = new StringBuilder(1000);\n        GetUserTilePath(username, 0x80000000, sb, sb.Capacity);\n        return sb.ToString();\n    }\n\n    public static Image GetUserTile(string username)\n    {\n        return Image.FromFile(GetUserTilePath(username));\n    }	0
34271284	34271100	Timer in UWP App which isn't linked to the UI	private Timer timer;\npublic MainPage()\n{        \n    this.InitializeComponent();\n    timer = new Timer(timerCallback, null, TimeSpan.FromMinutes(1).Milliseconds, Timeout.Infinite);\n}\n\nprivate async void timerCallback(object state)\n{\n    // do some work not connected with UI\n\n    await Window.Current.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,\n        () => {\n            // do some work on UI here;\n        });\n}	0
4520394	4520357	How would I remove items from a List<T>?	var newList = oldList.Take(oldList.Count / 3).ToList()	0
25485999	25485870	RegEx for multiple line statements	IF (.+?) THEN\R\s+(.+:=.+) (.+:=.+)\s+RETURN TRUE\RENDIF	0
19298840	19296963	Linq: get a custom class joining to tables	var result = context.Groups.Where(g=>g.GroupId == groupId)\n                    .Select(e=> new CustomGroup(e));\n//With your CustomGroup class should looks like this:\n\n[DataContract]\npublic class CustomGroup  //You should consider some inheritance relationship here\n   public CustomGroup(Group g){\n      GroupId = g.GroupId;\n      Name = g.Name;\n      Description = g.Description;\n      City = g.City;\n      Country = g.Country;\n      UsersIds = g.Users.Select(u=>u.UserId).ToList();\n   }\n   //....  \n   [DataMember]\n   public ICollection<int> UsersIds { get; set; }\n}	0
16803464	16801699	Get Index of first 'element' in DataRow array	var row = dt.Rows.Cast<DataRow>().\n                        Select(x => x).\n                        Where(x => x.Field<string>("Column name").Equals("value")).\n                        ElementAt(0);\nint index = row == null ? -1 : dt.Rows.IndexOf(row);	0
2074159	2074107	How to pin the header row in Excel in .NET?	Sub Makro1()\n'\n' Makro1 Makro\n'\n\n'\n    ActiveWindow.SplitRow = 1.1\n    With ActiveWindow\n        .SplitColumn = 0\n        .SplitRow = 1\n    End With\n    ActiveWindow.FreezePanes = True\nEnd Sub	0
18801727	18801699	Match and replace only line breaks in string	string test2 = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n";\n\nif (test2.All(c => c == '\n' || c == '\r'))\n    test2 = "";	0
9400923	9400760	showing thumbnail after image upload	protected void Page_PreRender(object sender, EventArgs e) {\n         //CODE HERE}	0
28951192	28951094	Sending emails with ASP.NET Membership Credentials	SmtpClient smtpClient = new SmtpClient();\n     smtpClient.UseDefaultCredentials = false;\n     MailMessage mailMessage = new MailMessage();	0
3222551	3222515	How to set an int to byte* C#	unsafe\n{\n    byte* igm = stackalloc byte[8];\n    *(int*)(igm + 4) = 4283;\n}	0
12288633	12288612	How to get HTML value from XElement?	.ToString()	0
5178408	5178315	How to render text in Directwrite?	Bitmap bitmap = new Bitmap(100, 100);\nGraphics g = Graphics.FromImage(bitmap);\ng.DrawString("HALLO", new Font("Arial", 12), Brushes.Black, new PointF(10, 10));\nbitmap.Save(<Put Filestream here>);	0
17036786	17036245	Add to List<string> from text file	using (var reader = new StringReader(Properties.Resources.sampleNamesMale))	0
15323761	15323733	Created Button Click Event c#	public MainWindow()\n    {\n        // This button needs to exist on your form.\n        myButton.Click += myButton_Click;\n    }\n\n    void myButton_Click(object sender, RoutedEventArgs e)\n    {\n        MessageBox.Show("Message here");\n        this.Close();\n    }	0
24668552	21158067	How to get page count of pdf byte array generated through SSRS	int pageCount;\nMemoryStream stream = new MemoryStream(pdfContent);\nusing (var r = new StreamReader(stream))\n{\n    string pdfText = r.ReadToEnd();\n    System.Text.RegularExpressions.Regex regx = new Regex(@"/Type\s*/Page[^s]");\n    System.Text.RegularExpressions.MatchCollection matches = regx.Matches(pdfText);\n    pageCount = matches.Count;\n}	0
23831414	23096707	Using Windows form to remote/ active/ Claims based authenticate to on premises MS SharePoint 2013 website in C#	var dc = new subsiteDataContext(new Uri("http://.../subsite/_vti_bin/ListData.svc"))\n            {\n                Credentials = System.Net.CredentialCache.DefaultCredentials\n            };	0
3567126	3565118	how to merge the dataset	DataSet ds1 = new DataSet();\nDataSet ds2 = new DataSet();\n\nds1.Tables.Add(new DataTable());\nds2.Tables.Add(new DataTable());\n\nds1.Tables[0].Columns.Add("tblkey");\nds1.Tables[0].Columns.Add("empkey");\nds1.Tables[0].Columns.Add("empname");\n\nds2.Tables[0].Columns.Add("empkey");\nds2.Tables[0].Columns.Add("empname");\n\nds1.Tables[0].Rows.Add("T101", "E10", "Natraj");\nds1.Tables[0].Rows.Add("T102", "E11", "Siva");\nds1.Tables[0].Rows.Add("T103", "E14", "ganesh");\n\nds2.Tables[0].Rows.Add("E10", "karthi");\nds2.Tables[0].Rows.Add("E11", "thriu");\nds2.Tables[0].Rows.Add("E13", "maran");\n\n// primary keys must be set in order for the merge to work\nds1.Tables[0].PrimaryKey = new DataColumn[] { ds1.Tables[0].Columns["empkey"] };\nds2.Tables[0].PrimaryKey = new DataColumn[] { ds2.Tables[0].Columns["empkey"] };\n\n// this is the critical line\nds1.Merge(ds2, true, MissingSchemaAction.Add);	0
1374313	1373490	Accessing user control on child master page from child master page code behind	protected override void OnLoad(EventArgs e)\n{\n    MyLiteral1.Text= "<p>MyLiteral1 Successfully updated from nested template!</p>";\n    base.OnLoad(e);\n}	0
26711864	26711775	How to add an Attached Property to a combobox?	TextBox textBox = dependencyObject as TextBox;\n    ComboBox comboBox = dependencyObject as ComboBox;\n\n    if (textBox != null && textBox.Name == "firstNameTextBox")\n    {\n        bool newIsTextFormattedValue = (bool)dependencyPropertyChangedEventArgs.NewValue;\n        if (newIsTextFormattedValue) textBox.TextChanged += MyTextChangedHandler;\n        else textBox.TextChanged -= MyTextChangedHandler;\n    }\n\n    if (comboBox != null && comboBox.Name == "genderTextBox")\n    {\n        bool newIsTextFormattedValue = (bool)dependencyPropertyChangedEventArgs.NewValue;\n        if (newIsTextFormattedValue) comboBox.SomeEvent += MyComboBoxChangedHandler;\n        else comboBox.SomeEvent -= MyComboBoxChangedHandler;\n    }	0
2812572	2812545	How do I sum values from two dictionaries in C#?	Dictionary<string, int> result = (from e in foo.Concat(bar)\n              group e by e.Key into g\n              select new { Name = g.Key, Count = g.Sum(kvp => kvp.Value) })\n              .ToDictionary(item => item.Name, item => item.Count);	0
22344460	22344337	how to sort in order using Datatable for Gridview	datatable.DefaultView.Sort = "yourcolumnname ASC"; \n\n\ndatatable = datatable.DefaultView.ToTable();	0
33554241	4837416	High precision sleep or How to yield CPU and maintain precise frame rate	public virtual void LimitFrameRate(int fps)\n{\n   long freq;\n   long frame;\n   freq = System.Diagnostics.Stopwatch.Frequency;\n   frame = System.Diagnostics.Stopwatch.GetTimestamp();\n   while ((frame - fpsStartTime) * fps < freq * fpsFrameCount)\n   {\n      int sleepTime = (int)((fpsStartTime * fps + freq * fpsFrameCount - frame * fps) * 1000 / (freq * fps));\n      if (sleepTime > 0) System.Threading.Thread.Sleep(sleepTime);\n      frame = System.Diagnostics.Stopwatch.GetTimestamp();\n   }\n   if (++fpsFrameCount > fps)\n   {\n      fpsFrameCount = 0;\n      fpsStartTime = frame;\n   }\n}	0
12055585	12055496	How can i hide a column in a gridview dynamically using C#?	GridView1.Columns[YouEventValue].Visible = false;	0
22963620	22962239	How to know if my user is an active directory user	try\n{\n    var credentials = new NetworkCredential(sUserName, sPassword);\n\n    using (var connection = new LdapConnection(domainName))\n    {\n        connection.AuthType = AuthType.Kerberos \n        connection.Bind(credentials);\n    }\n\n    return true;\n}\ncatch\n{\n    //handle errors as you see fit\n    return false;\n}	0
1484960	1475747	Is there an in memory stream that blocks like a file stream	public class EchoStream : MemoryStream {\n\n    private ManualResetEvent m_dataReady = new ManualResetEvent(false);\n    private byte[] m_buffer;\n    private int m_offset;\n    private int m_count;\n\n    public override void Write(byte[] buffer, int offset, int count) {\n        m_buffer = buffer;\n        m_offset = offset;\n        m_count = count;\n        m_dataReady.Set();\n    }\n\n    public override int Read(byte[] buffer, int offset, int count) {\n        if (m_buffer == null) {\n            // Block until the stream has some more data.\n            m_dataReady.Reset();\n            m_dataReady.WaitOne();    \n        }\n\n        Buffer.BlockCopy(m_buffer, m_offset, buffer, offset, (count < m_count) ? count : m_count);\n        m_buffer = null;\n        return (count < m_count) ? count : m_count;\n    }\n}	0
12383551	12383524	matching integers in brackets	(?<=\[\s*)\d+(?=\s*\])	0
18610630	18609757	How to compress image byte[] array to JPEG/PNG and return ImageSource object	private ImageSource GetImage(byte[] imageData, System.Windows.Media.PixelFormat format, int width = 640, int height = 480)\n    {\n        using (MemoryStream memoryStream = new MemoryStream())\n        {\n            PngBitmapEncoder encoder = new PngBitmapEncoder();                                \n            encoder.Interlace = PngInterlaceOption.On;\n            encoder.Frames.Add(BitmapFrame.Create(BitmapSource.Create(width, height, 96, 96, format, null, imageData, width * format.BitsPerPixel / 8)));\n            encoder.Save(memoryStream);\n            BitmapImage imageSource = new BitmapImage();\n            imageSource.BeginInit();\n            imageSource.StreamSource = memoryStream;\n            imageSource.EndInit();\n            return imageSource;\n        }            \n    }	0
9514171	9513990	Drawing a path from c# with relative coordinates	Path p=new Path();\np.Data = Geometry.Parse("M 100,200 c 100,25 400,350 400,175");\np.Stroke =new SolidColorBrush(Colors.Black);	0
2697512	2697492	How to create file of files?	Dictionary<string, byte[]>	0
19006035	19005899	Regular expression for string price with hyphen	"\d+(?:\.\d+)?"	0
2665380	2665362	Convert byte array to wav file	System.IO.File.WriteAllBytes("yourfilepath.wav", bytes);	0
20311858	20311607	After button was pressed, get pixel properties from a picturebox only after mouse was clicked c#	public Form1()\n{\n    InitializeComponent();\n    this.myPictureBox.BackColor = Color.Red;\n}\n\nprivate void startButton_Click(object sender, EventArgs e)\n{\n    if (MessageBox.Show(\n        "Please click the object in the image ",\n        "", \n        MessageBoxButtons.OKCancel, \n        MessageBoxIcon.Exclamation, \n        MessageBoxDefaultButton.Button1) == DialogResult.OK)\n    {\n        this.myPictureBox.MouseClick += this.myPictureBox_MouseClick;\n    }\n}\n\nvoid myPictureBox_MouseClick(object sender, MouseEventArgs e)\n{\n    this.myPictureBox.MouseClick -= myPictureBox_MouseClick;\n    var point = new Point(e.X, e.Y);\n    MessageBox.Show(string.Format("You've selected a pixel with coordinates: {0}:{1}", point.X, point.Y));\n}	0
1509197	1508315	Xpath, retrieving node value	/*[local-name() = 'Result']/*[local-name() = 'row']/@ows_ID	0
18302046	18301542	Keep Temp Data For Each User	Forms Authentication	0
1939959	1939449	serialize HybridDictionary to byte[]	[field:NonSerializedAttribute()]\npublic event MyEventHandler SomeEvent;	0
9105982	9105960	What's a better way to remove a sub folder that attached in the file path in C# 2.0	using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace ConsoleApplication12\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string EV_HOME = @"C:\myprogram\leanrning\anotherfolder\";\n            string parentFolder = new System.IO.DirectoryInfo(EV_HOME).Parent.FullName;\n            string myFilePath = parentFolder + "\\MyFolder\\MySubFolder";\n            Console.WriteLine(myFilePath);\n        }\n    }\n}	0
17867872	17866779	Dynamically change outcome of JOIN using select parameters	protected void viewThemeTypeAssociationsDropDown_OnSelectedIndexChanged(object sender, EventArgs e)\n{\n    if (viewThemeTypeAssociationsDropDown.SelectedIndex == 0)\n    {\n        SqlDataSource6.SelectCommand = "SELECT [Theme].[Name], [ThemeType].[Type] FROM [Theme] Left Outer Join [ThemeType] ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType] ORDER BY [Theme].[Name] ASC";\n    }\n    else if (viewThemeTypeAssociationsDropDown.SelectedIndex == 1)\n    {\n        SqlDataSource6.SelectCommand = "SELECT [Theme].[Name], [ThemeType].[Type] FROM [Theme], [ThemeType] WHERE [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType] ORDER BY [Theme].[Name] ASC";\n    }\n    else\n    {\n        SqlDataSource6.SelectCommand = "SELECT [Theme].[Name], [ThemeType].[Type] FROM [Theme] Left Outer Join [ThemeType] ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType] WHERE [Theme].[ThemeTypeId] IS NULL ORDER BY [Theme].[Name] ASC";\n    }\n}	0
2784729	2784693	How can I create a list of classes in C# to iterate over in a loop	Assembly a = Assembly.GetExecutingAssembly();\n  var types = a.GetTypes().Where(t => t.IsSubclassOf(typeof(Animal)));	0
10601830	10601664	IndexAt with condition	myString.IndexOf("boat arc") + 5;	0
8540229	8539331	Is there an option for flowdocument that allow me to deny splitting blocks to 2 pages when printing?	FlowDocument doc = new FlowDocument();\nforeach (Labels label in labels)\n{\n    Paragraph p = new Paragraph();\n    p.KeepTogether = true;\n    p.Inlines.Add(label.name + "\n");\n    p.Inlines.Add(label.age + "\n");\n    p.Inlines.Add(label.price + "\n");\n    doc.Blocks.Add(p);\n}	0
6309439	6309379	How to check for a valid Base 64 encoded string in C#	'A'..'Z', 'a'..'z', '0'..'9', '+', '/'	0
10551913	10551607	Calculation Columns in DataGridView bounded to an object	private void OnCellFormatting(object sender,\n   DataGridViewCellFormattingEventArgs e)\n{\n\n    if (e.ColumnIndex == grid.Columns["Unbound"].Index)\n    {\n       e.FormattingApplied = true;\n       DataGridViewRow row = grid.Rows[e.RowIndex];\n       e.Value = string.Format("{0} : {1}",\n          row.Cells["SomeColumn1"].Value,\n          row.Cells["SomeColumn2"].Value);\n    }\n}\n\nprivate void OnRowsAdded(object sender,\n   DataGridViewRowsAddedEventArgs e)\n{\n\n   for (int i = 0; i < e.RowCount; i++)\n   {\n      DataGridViewRow row = grid.Rows[e.RowIndex + i];\n      row.Cells["Unbound"].Value = string.Format("{0} : {1}",\n         row.Cells["SomeColumn1"].Value,\n         row.Cells["SomeColumn2"].Value);\n    }\n}	0
16124203	16120370	How open and save( edited) xml file from path in LocalFolder	StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);\nXDocument document = XDocument.Load(storageFile.Path);\n\nvar elementStepOne = document.Elements("StepOne").Single();\nelementStepOne.Value = "delete content";\n\nvar file = await ApplicationData.Current.LocalFolder.CreateFileAsync(\n    SelectFile, \n    CreationCollisionOption.ReplaceExisting);\nusing (var writeStream = await file.OpenStreamForWriteAsync())\n{\n    document.Save(writeStream);\n}	0
2175695	2175669	If User.IsInRole with string array?	bool isAuthorized = \n    this.AuthRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));	0
18330635	18330460	only get the src value	string matchString = Regex.Match(original_text, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;	0
1161885	1161875	setting correct row of dropdownlist not working	ddOffice.SelectedIndex = ddOffice.Items.IndexOf(ddOffice.Items.FindByText(chunks[1]));	0
11112633	11112592	Open HTML file in C# application	webbrowser.Navigate("File location.html")	0
1342753	1341786	Work with DirectoryEntry not on a Domain, set user password never expire	user.Invoke("Put", new object[] {"UserFlags", 0x10000});	0
13610092	13609503	Iterate through array for each value in comma separated string	private void GetColors(string colors)\n    {\n        string[] colorArray = new string[] { "red", "green", "purple" };\n\n        int previousIndex = -1;\n        int currentIndex;\n\n        string[] myColors = colors.Split(',');\n        foreach (string s in myColors)\n        {\n            currentIndex = Array.IndexOf(colorArray, s);\n            if (previousIndex != -1)\n            {\n                if (previousIndex - currentIndex == 1 || previousIndex - currentIndex == -1)\n                {\n                    //do stuff here\n                }\n            }\n\n\n            previousIndex = currentIndex;\n        }\n    }	0
25485152	25476338	Open and edit XML file in web page	ASP.NET	0
7645982	7645643	Operate with date timezone	date.getTime() + (date.getTimezoneOffset() * 60 * 1000)	0
22477544	22472427	Get the centerpoint of an Arc - G-Code Conversion	'--- Compute arc center from radius\n  Dim tang#, w#\n  tang = co1.Tangent(co2)\n  co2.Rotate co1, -tang\n  center.X = (co1.X + co2.X) / 2\n  center.Y = 0\n  w = center.X - co1.X\n  If Abs(mModal.RWord) < w Then\n    '--- R-word too small\n    If mModal.ThrowErr And w - Abs(mModal.RWord) > 0.00\n      Err.Raise 911, , "R-word too small"\n    End If\n  Else\n    center.Y = -Sqr(mModal.RWord * mModal.RWord - w * w\n  End If\n  '--- Choose out of the 4 possible arcs\n  If Not cw Then center.Y = -center.Y\n  If mModal.RWord < 0 Then center.Y = -center.Y\n  center.Y = center.Y + co1.Y\n  center.Rotate co1, tang\n  co2.Rotate co1, tang\n  GetArcCenter = center	0
22844959	22844214	Read the data from XML file into flat files(txt) and with formated data	private static void LoadAndWriteXML()\n    {\n        string headerFiles = "";\n        string values = "";\n        using (XmlReader reader = XmlReader.Create(@"C:\\bank.xml"))\n        {\n            while (reader.Read())\n            {\n                if (reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Bank"))   // we have to skip root node means bank node.\n                {\n                    headerFiles += reader.Name + " ";\n                    values += reader.ReadString() + " ";\n                }\n            }\n        }\n\n        StreamWriter writer = new StreamWriter(@"C:\\Test.txt");\n\n        writer.WriteLine(headerFiles.Trim());\n        writer.WriteLine(values.Trim());\n\n        writer.Close();\n\n\n    }	0
33915993	33913354	Convert Object to List	List<CariHesapEkstre> senderExtractList = GetExtractList((IList)detayManager.GetMutabakatDetayListByMutabakat(oMutabakat, true));\nprivate List<CariHesapEkstre> GetExtractList ( IList tempList )\n{\n    List<CariHesapEkstre> returnList = new List<CariHesapEkstre>();\n\n    foreach ( var item in tempList )\n    {\n        CariHesapEkstre extract = new CariHesapEkstre();\n        foreach ( PropertyInfo prop in item.GetType().GetProperties() )\n        {\n            foreach ( PropertyInfo prop2 in extract.GetType().GetProperties() )\n            {\n                if ( prop2.Name == prop.Name )\n                {\n                    prop2.SetValue(extract, prop.GetValue(item));\n                }\n            }\n        }\n\n        returnList.Add(extract);\n    }\n\n    return returnList;\n}	0
18511402	18504445	Best way to implement navigation in mvvm for wpf application	public ApplicationScreenBase()\n        {\n            this.Loaded +=ApplicationScreenBase_Loaded;\n            this.Unloaded += ApplicationScreenBase_Unloaded;\n            this.Activated += ApplicationScreenBase_Activated;\n            this.Deactivated += ApplicationScreenBase_Deactivated;\n        }\n\n        void ApplicationScreenBase_Deactivated(object sender, EventArgs e)\n        {\n            AppMessenger.Unregister(this, OnMessageToApp);\n        }\n\n        void ApplicationScreenBase_Activated(object sender, EventArgs e)\n        {\n            AppMessenger.Register(this, OnMessageToApp);\n        }	0
620549	620546	C# string manipulation - How to remove the first element of each concatenated string in a collection	foreach (ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items)\n    {\n        string HazPackErrRow = " ";\n\n        bool first = true;\n        foreach (ListViewItem.ListViewSubItem HazPackErrSub in HazPackErrItems.SubItems)\n        {\n            if (first) \n                first = false;\n            else\n                HazPackErrRow += " " + HazPackErrSub.Text + ",";\n        }\n        // Remove comma after last element of string.\n        HazPackErrRow = HazPackErrRow.Substring(0, HazPackErrRow.Length - 2); \n        MessageBox.Show(HazPackErrRow); // List concatenated subitems\n    }	0
25986188	25984687	Setting URI to root directory in application for image source	myImage = new BitmapImage(new Uri("/component/speedline.png", UriKind.Relative));	0
23952736	23952650	Parse price from a string with decimals and currency	Regex.Match(yourString, "\\d+")	0
2903421	2903339	problem while converting object into datetime in c#	DateTime.ParseExact(dateString, "dd/MM/yyyy",           CultureInfo.InvariantCulture);	0
10692584	10692540	How do I do a lua style table of functions in C#?	item.Rules.Add((planItem) => \n { \n     return !string.IsNullOrEmpty(planItem.Name); \n });	0
11634864	11626640	ServiceStack: removing StackTrace from ResponseStatus	if (EndpointHost.UserConfig.DebugMode)\n{\n    // View stack trace in tests and on the client\n    responseStatus.StackTrace = GetRequestErrorBody() + ex;\n}	0
11205393	11203615	How to retreive rows from a sql table and display each item in a label in asp.net by using c#	// SqlCommand cmd=new SqlCommand("ProcedureName","Connection");\n// cmd.CommandType = CommandType.StoredProcedure;\n// SqlDataAdapter da=new SqlDataAdapter(cmd);\n// Dataset ds=new Dataset();\n// da.Fill(ds);\n// Now after Filling the Dataset you can Retrieve it by\n\ndataset.tables["TableName or Index"]	0
13452031	13451021	add current time to chart xaxis	chart1.Series["Example"].Points.AddXY(DateTime.Now.ToLongTimeString(), ms);\n   chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 90;	0
2354486	2354435	How to get the list of all printers in computer	foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)\n{\n    MessageBox.Show(printer);\n}	0
20411548	20411427	Using generics in C# with a "recursive" relationship	class Master<M, S> where S : Slave<S, M> where M : Master<M, S>	0
30762236	30762011	LINQ: Compare List A and B, if in B, select item in A	var tags = db.Tags\n    .Where(x=>db.TagLink\n        .Any(y => y.TagId == x.TagId && y.TopicID == incomingTopicID))\n    .ToList();	0
16460003	16459914	How do I disambiguate an overloaded method	public ImageLinkButton AddToolBarButton(string commandName, \n                                        string text, \n                                        string toolTip, \n                                        string imageUrl, \n                                        string confirmMessage, \n                                        bool defineID = false)\n\npublic ImageLinkButton AddToolBarButton(string commandName, \n                                        string text, \n                                        string toolTip, \n                                        string imageUrl, \n                                        bool causesValidation,//swap this \n                                        string confirmMessage, //and this\n                                        bool defineID = false)	0
23146361	23131058	how to set focus row on XtraGridControl Devexpress?	ColumnView cv = m_wndGridCtrl.MainView as ColumnView;\ncv.FocusedRowHandle = 0;	0
20861301	20860101	How to Read text file to DataTable	public DataTable ConvertToDataTable (string filePath, int numberOfColumns)\n{\n    DataTable tbl = new DataTable();\n\n    for(int col =0; col < numberOfColumns; col++)\n        tbl.Columns.Add(new DataColumn("Column" + (col+1).ToString()));\n\n\n    string[] lines = System.IO.File.ReadAllLines(filePath);\n\n    foreach(string line in lines)\n    {\n        var cols = line.Split(':');\n\n        DataRow dr = tbl.NewRow();\n        for(int cIndex=0; cIndex < 3; cIndex++)\n        {\n           dr[cIndex] = cols[cIndex];\n        }\n\n        tbl.Rows.Add(dr);\n    }\n\n    return tbl;\n}	0
6468490	6468442	PDF content inside XML response file	var buffer = Convert.FromBase64String(xmlStringValue);\nFile.WriteAllBytes(yourFileName, buffer);	0
3176625	3176588	Save files (pictures, music, movies) in a Container file	using (ZipFile zip = new ZipFile())\n {\n     // add this map file into the "images" directory in the zip archive\n     zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");\n     // add the report into a different directory in the archive\n     zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");\n     zip.AddFile("ReadMe.txt");\n     zip.Save("MyZipFile.zip");\n }	0
12431049	12430982	How to combine this foreach loop into a one line lambda / linq	var result = allClaimLineItems\n    .Select(i => i.ClaimLineItemId)\n    .Distinct()\n    .GroupJoin(allClaimLineItems, g => g, i => i.ClaimLineId, (g, matches) => matches)\n    .Select(GetClaimDuplicateItemRuleDataWithHighestDuplicateFlags)\n    .ToList();	0
17754912	17754641	How to search through html table rows?	string value = @"         <table id=tbl>\n              <tbody>\n              <tr>\n                <td>HELLO</td>\n                <td>YES</td>\n                <td>TEST</td>\n              </tr>\n              <tr>\n                <td>BLAH BLAH</td>\n                <td>YES</td>\n                <td>TEST</td>\n              </tr>\n             </tbody>\n             </table>";\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(value);\n\nvar nodes = doc.GetElementbyId("tbl").SelectNodes("tbody/tr/td");\nforeach (var node in nodes)\n{\n    Debug.WriteLine(node.InnerText);\n}	0
9114825	9114350	How do I define constructor argument to take custom object with ninject?	Bind<IGitRepository>().To<GitRepository>();\n        Bind<IGitAuthor>().To<GitAuthor>()\n            .WithConstructorArgument("author", ConfigurationManager.AppSettings["GitAuthor"])\n            .WithConstructorArgument("email", ConfigurationManager.AppSettings["GitEmail"]);\n        Bind<IGitRepositoryPath>().To<GitRepositoryPath>()\n            .WithConstructorArgument("path",ConfigurationManager.AppSettings["GitServerUri"]);	0
3779840	3779708	Programmatically Adding Labels To Newly Created Row?	Label label = new Label();\n    label.Name = "MyNewLabel";\n    label.Text = "Added in my test";\n    tableLayoutPanel1.RowCount++;\n    tableLayoutPanel1.RowStyles.Add(new RowStyle());\n    tableLayoutPanel1.Controls.Add(label, 0, tableLayoutPanel1.RowCount - 1);	0
33516586	33515524	Speed up XML upload to SQL Server with EF. Improve performance by applying schema?	DECLARE @yourXML AS XML=\n(\nSELECT CONVERT(XML, BulkColumn,2) AS BulkColumn\nFROM OPENROWSET(BULK 'PathToFile.xml', SINGLE_BLOB) AS x\n);\nSELECT @yourXML;	0
32127587	32127558	Create new threads in a for loop and pass parameters	for(int i = 0; i < 10; i ++)\n{\n    int tmp = i;\n    new Thread(() => Test(tmp)).Start();\n}	0
16951162	16948962	Can we have two explicit waits in the same program	public void WaitForElementById(string elementId, int timeout = 5)\n{\n    //Where '_driver' is the instance of your WebDriver\n    WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 0, timeout));\n    IWebElement element = _wait.Until(x => x.FindElement(By.Id(elementId)));\n}	0
121107	121059	Conversion from 32 bit integer to 4 chars	int value = 0x48454C4F;\nConsole.WriteLine(Encoding.ASCII.GetString(\n  BitConverter.GetBytes(value).Reverse().ToArray()\n));	0
20578721	20578544	Databind Class property with grid Height	public class Height:INotifyPropertyChanged\n{\n    GridLength _gridheight = new GridLength(200);\n    public GridLength GridHeight\n            {\n                    get{\n                            return _gridheight;\n                       }\n\n                    set{\n                            if(_gridheight==value)\n                               return;\n\n                            _gridheight=value;\n                            NotifyPropertyChanged("GridHeight")\n                        }\n\n         }\n\n  public event PropertyChangedEventHandler PropertyChanged;\n\n    private void NotifyPropertyChanged(string propertyName = "")\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n\n}	0
15867142	15857995	Applying default style for ListViewItem, while using custom behavior	listview.ScrollIntoView(listviewitem);\nlistviewitem.Focus();	0
4117233	4117225	how to get value from a window I window.show();	class Form1 \n{\n    void Function() \n    {\n        newEvent.ExecuteTargets += exacuteNewEvent;\n    }\n\n    void exacuteNewEvent(string message)\n    {\n        Window1 w = new Window1(this);\n        w.ShowDialog();\n    }\n\n    public void ExecuteStuffInOtherWindow() \n    {\n        // do something\n    }\n}\n\nclass Window1 \n{\n    Form _otherForm;\n\n    public Window1(Form f) \n    {\n        _otherForm = f;\n        _otherForm.ExecuteStuffInOtherWindow(); // call code in other form\n    }\n}	0
14392560	14392468	Exporting C++ dll to c#	[DllImport(@"../data/stasm_dll.dll")]\ninternal static extern void AsmSearchDll\n( \n    [Out] out Int32 pnlandmarks,\n    [Out] out Int32[] landmarks,\n    [In, MarshalAs(UnmanagedType.LPStr)] String image_name,\n    [In, MarshalAs(UnmanagedType.LPStr)] String image_data,\n    [In] Int32 width,\n    [In] Int32 height,\n    [In] Int32 is_color,\n    [In, MarshalAs(UnmanagedType.LPStr)] String conf_file0,\n    [In, MarshalAs(UnmanagedType.LPStr)] String conf_file1\n);\n\nIplImage img = cvlib.cvLoadImage(image_name, cvlib.CV_LOAD_IMAGE_COLOR);\nString imageData = Marshal.PtrToStringAnsi(img.imageData);\n\nAsmSearchDll(out nlandmarks, out landmarks, image_name, imageData, img.width, img.height, 1, null, null);	0
17758033	17757314	How to test JsonResult from .NET MVC controller	var result = new JsonResult{ Data = new {details = "This location has not entered any comments or further details for this event."}};\n\nvar det = result.Data.GetType().GetProperty("details", BindingFlags.Instance | BindingFlags.Public);\n\nvar dataVal = det.GetValue(result.Data, null);	0
16966630	16966531	Replacing a specific character with string.replace()	I suspect your string already actually only contains a single backslash, \nbut you're looking at it in the debugger which is escaping it for you into\na form which would be valid as a regular string literal in C#.	0
1318308	1318236	How to disable navigation on WinForm with arrows in C#?	private void Form1_Load(object sender, EventArgs e)\n    {\n        foreach (Control control in this.Controls)\n        {\n            control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDown);\n        }\n    }\n\n    void control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)\n    {\n        if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)\n        {\n            e.IsInputKey = true;\n        }\n    }	0
21090411	21088543	Hyperlinks inside a ASPXGridview	if (e.RowType == GridViewRowType.Data)\n        {              \n            ASPxGridView dgrdResults = sender as ASPxGridView;\n            ASPxHyperLink destinationLink = dgrdResults.FindRowCellTemplateControl(e.VisibleIndex, null, "DestinationLink") as ASPxHyperLink;\n            ASPxHyperLink statusLink = dgrdResults.FindRowCellTemplateControl(e.VisibleIndex, null, "stt_display_order") as ASPxHyperLink;\n\n            if (e.GetValue("bnd_name") != null)\n            {\n                int DrId = Convert.ToInt32((e.GetValue("dr_id")));\n                destinationLink.NavigateUrl = "./included_codes.aspx?mode=Edit&dr_id=" + DrId;\n            }\n            else\n            {\n                destinationLink.Enabled = false;\n                destinationLink.ForeColor = Color.Black;\n            }\n\n        }	0
13830361	13830247	Get data from receipt using regular expressions	class ReceiptItem\n    {\n        public int Quantity { get; set; }\n        public string Description { get; set; }\n\n        public override string ToString()\n        {\n            return string.Format("{0}\t{1}", Quantity, Description);\n        }\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        var matches = Regex.Matches(textBox1.Text, @"(\d+)\s+([A-Z\s\*\#]*[A-Z]+)", RegexOptions.Multiline);\n        var items = (from Match m in matches\n                     select new ReceiptItem()\n                                {\n                                    Quantity = int.Parse(m.Groups[1].Value),\n                                    Description = Regex.Replace(m.Groups[2].Value, @"(\*\#(\s*))|(\r\n\s+)(?=\s)", "")\n                                });\n\n        listBox1.Items.AddRange(items.ToArray());\n    }	0
19858202	19858132	C# How to list an object value	Object entropyResult = ent.entropy(array);\nDouble value = ((Double[,])entropyResult)[0,0]	0
10555037	10554866	How do you transpose dimensions in a 2D collection using LINQ?	public static IEnumerable<IEnumerable<T>> Transpose<T>(\n    this IEnumerable<IEnumerable<T>> @this) \n{\n    var enumerators = @this.Select(t => t.GetEnumerator())\n                           .Where(e => e.MoveNext());\n\n    while (enumerators.Any()) {\n        yield return enumerators.Select(e => e.Current);\n        enumerators = enumerators.Where(e => e.MoveNext());\n    }\n}	0
7719484	7719239	Possible to lock a {portion} of an array in C#? or have dynamic lock array?	var ActiveRow = BatchEntries[ThingToProcess];	0
15359961	15359887	Datetime in C# add days	endDate = endDate.AddDays(addedDays);	0
21420183	21420051	C#: How can I add the DATE in BOLD into a RichTextBox but keep writing in regular font (not BOLD)	richTextBox1.Select(richTextBox1.TextLength, 0);\nrichTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);\nrichTextBox1.SelectionColor = Color.Blue;\n\nrichTextBox1.AppendText(dateTimePicker1.Value.ToShortDateString());\n\nrichTextBox1.Select(richTextBox1.TextLength, 0);\nrichTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Regular);\nrichTextBox1.SelectionColor = Color.Black;\n\nrichTextBox1.Focus();	0
11974177	11974146	Calling a method in a C# class	string result = GetLookupValue<string, int>("tname", "fname", "luname", 42);\n\nMyClass result = GetLookupValue<MyClass, string>("tname", "fname", "luname", "blah");	0
22690560	22690328	Method call to display the name of each button clicked in c#	private void btn_Click(object sender, EventArgs e)\n{\n    Button button = (Button)sender;\n    displayName(button.Name);\n    displayText(button.Text);\n}\nprivate int displayName(string name)\n{\n    MessageBox.Show(name);\n    return 0;\n}\nprivate int displayText(string text)\n{\n    MessageBox.Show(text);\n    return 0;\n}	0
28388931	28388795	Regarding C# Syntax with : and proceeding arguments in class declaration. Online converters failing to convert	Public Class MyProxy\n    Inherits ClientBase(of InterfaceDom)\n    Implements InterfaceDom\n    Public Function add(ByVal num1 as Integer, ByVal num2 as Integer) as Integer\n        Return MyBase.Channel.Add(num1, num2)\n    End Function\nEnd Class	0
2874066	2873843	Retrieving Dictionary from Datatable	var meta = new Dictionary<string,string>(ds.Tables[1]\n                                           .Select("key<>'format'")\n                                           .AsEnumerable()\n                                           .ToDictionary(k=>k.Field<string>(0),\n                                                         v=>v.Field<string>(1)),\n                                         StringComparer.OrdinalIgnoreCase);	0
8186154	8169133	How do I detect lowercase keys using the Keys enum in C#?	[...]\nfor (Keys k = Keys.A; k <= Keys.Z; k++)\n{\n  if (KeyPress(k))\n  {\n      if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift)) //if shift is held down\n          Text += k.ToString().ToUpper(); //convert the Key enum member to uppercase string\n      else\n          Text += k.ToString().ToLower(); //convert the Key enum member to lowercase string\n  }\n}\n[...]	0
26933782	26933311	How to setup Web API controller to route request to method parameter?	Remove the {testName} from the "routeTemplate"\n\nprotected void Application_Start(object sender, EventArgs e)\n{\n    RouteTable.Routes.MapHttpRoute(\n        name: "DefaultApi",\n        routeTemplate: "api/{controller}/{testName}",\n        defaults: new { id = System.Web.Http.RouteParameter.Optional });\n    RouteTable.Routes.MapHttpRoute(\n        name: "DefaultApiWithAction",\n        routeTemplate: "api/{controller}/{action}");\n}	0
22643540	22642938	wpf click button in usercontrol calls event in parent window	public event Button1_ClickedEventHandler Button1_Clicked;\npublic delegate void Button1_ClickedEventHandler(object sender);\n\nprivate void Button1_Click(object sender, EventArgs e)\n{\n    if (Button1_Clicked != null) {\n        Button1_Clicked(this);\n    }\n}	0
21762958	21762879	Filtering a list of HtmlElements based on a list of partial ids	elems.Where(x => ids.Any(id => x.ID.Contains(id)))	0
15345147	15301278	Getting the PropertyGrid CollectionEditor to work with Generic Sorted Lists	IList<CustomItem2> myList = mySortedList.Select(m => m.Value>).ToList();\n// Or\nIList<KeyValuePair<CustomItem1, CustomItem2>> myList = mySortedList.Select(m => m).ToList();	0
15617810	15614712	Ribbon Invalidate makes my outlook add-in crash	the good old divide and conquer	0
10404250	10403748	A good animation library for visualizing the sort algorithms	private static void CreateGraph3(ZedGraphControl zgc)\n    {\n        // get a reference to the GraphPane\n        GraphPane pane = zgc.GraphPane;\n\n        // Set the Titles\n        pane.Title.Text = "Sorting";\n        //Clear current values\n        pane.CurveList.Clear();\n\n        // histogram high\n        double[] values = new double[n];\n\n        //fill values\n        for (int i = 0; i < n; i++)\n        {\n            values[i] = A1[i]; //A1 is an array that is currently sort\n        }\n\n        //create histogram\n        BarItem curve = pane.AddBar("Elements", null, values, Color.Blue);\n\n        pane.BarSettings.MinClusterGap = 0.0F; //set columns references\n\n        // update axis\n        zgc.AxisChange();\n\n        // update graph\n        zgc.Invalidate();\n    }	0
22237341	22236431	Best method to check if a point lies on an arc in c#	// first check if the point is on a circle with the radius of the arc. \n// Next check if it is between the start and end angles of the arc.\npublic static bool IsPointOnArc(Point p, Arc a)\n{\n    if (p.Y * p.Y == a.Radius * a.Radius - p.X * p.X)\n    {\n        double t = Math.Acos(p.X / a.Radius);\n        if (t >= a.StartAngle && t <= a.EndAngle)\n        {\n            return true;\n        }\n    }\n    return false;\n}	0
13377065	13376631	Creating DataTemplate from code behind	var ellipseVisBinding = new Binding("isAdmin");\nellipseVisBinding.Converter = new BooleanToVisibilityConverter();\n\nfef.SetBinding(Ellipse.VisibilityProperty, ellipseVisBinding);	0
11693503	11692166	'particleEngine' being drawn against a vector	batch.Draw(shipLaunch, new Vector2(80, 450) +shipPos, Color.White);\nparticleEngine.Draw(batch);	0
32711644	31727158	How to avoid copying .exe file into nupkg's lib directory	nuget pack <PackageProject.csproj> -outputDirectory <OutputDirectory> -BasePath <OutputDirectory> -Tool	0
8000069	8000028	Find a file in the solution	string exePath = Path.GetDirectory(Assembly.GetExecutingAssembly().Location);\nstring xmlPath = Path.Combine(exePath, "SampleFolder");\nstring fileName = Path.Combine(xmlPath, "SampleXML.xml");	0
20739065	20738538	Enumerated TabPages in a MenuStrip - Click event	private void tabsToolStripMenuItem_DropDownOpening(object sender, EventArgs e)\n{\n    ...\n    //create a menu item\n    ToolStripMenuItem menu = new ToolStripMenuItem(t.Text);\n    //Associate a tab index with a menu item\n    menu.Tag = t.TabIndex;\n    ...\n}\n\nprivate void menu_Click(object sender, EventArgs e)\n{\n    ToolStripMenuItem menu = (ToolStripMenuItem)sender;\n    //Use a tab index associated with a menu item to select a tab\n    tabEditor.SelectedIndex = (int)menu.Tag;\n}	0
16265758	16265641	Regex split with semi-colon gives unexpected results	##{(?<first>.*);(?<second>.*)}##	0
816574	816350	Receiving chunked data from a Socket to a single buffer	using (var resultStream = new MemoryStream())\n{\n    const int CHUNK_SIZE = 2 * 1024; // 2KB, could be anything that fits your needs\n    byte[] buffer = new byte[CHUNK_SIZE];\n    int bytesReceived;\n    while ((bytesReceived = socket.Receive(buffer, buffer.Length, SocketFlags.None)) > 0)\n    {\n        byte[] actual = new byte[bytesReceived];\n        Buffer.BlockCopy(buffer, 0, actual, 0, bytesReceived);\n        resultStream.Write(actual, 0, actual.Length);\n    }\n\n    // Do something with the resultStream, like resultStream.ToArray() ...\n}	0
4980441	4980421	variable declared in master page not available in content page	public string test\n{\n    get; set;\n}	0
30937214	30696838	How to calculate the size of a piece of text in Win2D	private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)\n{\n    CanvasDrawingSession drawingSession = args.DrawingSession;\n    float xLoc = 100.0f;\n    float yLoc = 100.0f;\n    CanvasTextFormat format = new CanvasTextFormat {FontSize = 30.0f, WordWrapping = CanvasWordWrapping.NoWrap};        \n    CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, "Hello World!", format, 0.0f, 0.0f);\n    Rect theRectYouAreLookingFor = new Rect(xLoc + textLayout.DrawBounds.X, yLoc + textLayout.DrawBounds.Y, textLayout.DrawBounds.Width, textLayout.DrawBounds.Height);\n    drawingSession.DrawRectangle(theRectYouAreLookingFor, Colors.Green, 1.0f);\n    drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Yellow);\n}	0
31213176	31212661	Neo4jClient c# Where Has set dynamically	var locale = "en_GB";\n\nvar query = client.Cypher\n               .Match("(store:Store)")\n               .Where(String.Format("has(store.{0})", locale))\n               .Return<Store>("store");\n\n        return query.Results.ToList();	0
24122068	24121700	Parse String to Generate Output String in Specific Format	private static String GetNextNumberInSequence(String inputString)\n    {\n        var integerpart = int.Parse(inputString.Substring(0, 5));\n        var characterPart = inputString[5];\n        if (characterPart == 'Z')\n            return string.Format("{0}{1}", (++integerpart).ToString("D5"), "A");\n\n        var nextChar = (char)(characterPart + 1);\n        return string.Format("{0}{1}", (integerpart).ToString("D5"), nextChar.ToString());\n    }	0
26616846	26615979	AES ECB decryption in WinRT, translating code from .NET Desktop	IBuffer buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);	0
31689767	31689698	Reset backlog after Socket server listen and response client	while(true) {\n    clientSocket = serverSocket.accept();\n    respond to socket in background thread\n}	0
18089550	18089430	Entity Framework 5 - Calling a stored procedure with parameters. Parameter not recognized	this.Database.Database.ExecuteSqlCommand("AddRowToPanelCdClAllData @SubId",\n                                          new SqlParameter("SubId", subId));	0
18432002	18431547	Compare enum with a List<int>	List< int > allowedDays = new List<int> {0,1,4};\n\nif (allowedDays.Contains((int)DateTime.Now.DayOfWeek))\n                // do soemthing	0
9790368	9789466	Showing image in a DataGridViewImageColumn binding text-field	private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (dgv.Columns[e.ColumnIndex].Name == "status")\n    {\n        if (e.Value != null)\n        {\n            if (e.Value.ToString() == "1")\n            {\n                e.Value = imageList1.Images[1];\n            }\n            else\n            {\n                e.Value = imageList1.Images[2];\n            }\n        }\n    }\n}	0
5712179	5711958	WP7 How to add the style in C#	Button btn = new Button();\nbtn.Style= (Style)App.Current.Resources["RoundButton"];	0
12683513	12682525	WinRT - How to get line and column at cursor from a TextBox?	// Returns a one-based line number and column of the selection start\nprivate static Tuple<int, int> GetPosition(TextBox text)\n{\n    // Selection start always reports the position as though newlines are one character\n    string contents = text.Text.Replace(Environment.NewLine, "\n");\n\n    int i, pos = 0, line = 1;\n    // Loop through all the lines up to the selection start\n    while ((i = contents.IndexOf('\n', pos, text.SelectionStart - pos)) != -1)\n    {\n        pos = i + 1;\n        line++;\n    }\n\n    // Column is the remaining characters\n    int column = text.SelectionStart - pos + 1;\n\n    return Tuple.Create(line, column);\n}	0
14876322	14874727	WPF setting IME to hiragana by default	InputMethod.SetPreferredImeState(TargetInputElement, InputMethodState.On)	0
25928351	22380938	Getting Parameters for my Addin	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 == "ProxyClassCreatorAddin.Connect.ProxyClassCreatorAddin")\n    {\n      string filePath = string.Empty;\n      UIHierarchy uih = _applicationObject.ToolWindows.SolutionExplorer;\n      Array selectedItems = (Array)uih.SelectedItems;\n      if (selectedItems != null)\n      {\n        foreach (UIHierarchyItem item in selectedItems)\n        {\n          var x = item.Object.GetType();\n          Project projectItem = item.Object as Project;\n          filePath = projectItem.Properties.Item("FullPath").Value.ToString();\n        }\n      }\n\n      handled = true;\n      CreateProxyClasses.CreateProxyClasses form = new CreateProxyClasses.CreateProxyClasses(filePath);\n      form.ShowDialog();\n    }\n  }\n}	0
5071472	5071424	How to specify two generic parameters for an extension method in C#	public static T GetModelFor<T>(this BusinessBase source)	0
4390976	4390697	Combining two relative Uris	new Uri(Uri baseUri, string relativeUri)	0
907868	907830	How do you prevent a windows form being moved?	protected override void WndProc(ref Message message)\n{\n    const int WM_SYSCOMMAND = 0x0112;\n    const int SC_MOVE = 0xF010;\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    base.WndProc(ref message);\n}	0
24335851	24334451	Unable to select multiple rows in a WPF DataGrid	private void DataGrid_SelectionChanged(object sender,\n    SelectionChangedEventArgs e)\n{\n    // ... Get SelectedItems from DataGrid.\n    var grid = sender as DataGrid;\n    var selected = grid.SelectedItems;\n\n    foreach (var item in selected)\n    {\n        var dog = item as Dog;\n    }\n}	0
32793618	32793574	Changes textbox text value from the array after selecting item from listview	private void ListView1_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e) {    \n        textbox2.Text = price[e.ItemIndex].ToString();    \n    }	0
18749540	18749502	How can I write a route that forces to a single controller/action?	routes.MapRoute(\n  name: "Default",\n  url: "{*url}",\n  defaults: new { controller = "Test", action = "Index"});	0
9747143	9746995	How to read child nodes from XML without knowing their names using C#?	XmlDocument doc = new XmlDocument();\ndoc.LoadXml("yourxml");\n\nXmlNode root = doc.FirstChild;\n\n//Display the contents of the child nodes.\nif (root.HasChildNodes)\n{\n  for (int i=0; i<root.ChildNodes.Count; i++)\n  {\n    Console.WriteLine(root.ChildNodes[i].InnerText);\n  }\n}	0
21710024	21709774	Check integer values in TextBoxes	int prev, today;\n\n        //first check that prev is an int\n        if (int.TryParse(txtPrevious.text, out prev))\n        {\n\n            if (prev == 0 && int.TryParse(txtTodaysTotal.text, out today))\n            {\n                txtThree.Text = (prev + today).ToString();\n            }\n        }	0
8931036	8930952	Setting CertificatePolicy=$TrustAll using C#	using System;\nusing System.IO;\nusing System.Net;\nusing System.Security.Cryptography.X509Certificates;\n\npublic class Program : ICertificatePolicy {\n\n    public bool CheckValidationResult (ServicePoint sp, \n        X509Certificate certificate, WebRequest request, int error)\n    {\n        return true;\n    }\n\n    public static void Main (string[] args) \n    {\n        ServicePointManager.CertificatePolicy = new Program ();\n        WebRequest wr = WebRequest.Create (args [0]);\n        Stream stream = wr.GetResponse ().GetResponseStream ();\n        Console.WriteLine (new StreamReader (stream).ReadToEnd ());\n    }\n}	0
6750504	6749914	How to generate 8 byte GUID value in c#?	using System; \nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace JustForFun\n{\n\n\n    public class UniqueId\n    {   \n        public static string GetUniqueKey()\n        {\n            int maxSize = 8;\n            char[] chars = new char[62];\n            string a;\n            a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";\n            chars = a.ToCharArray();\n            int size = maxSize;\n            byte[] data = new byte[1];\n            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();\n            crypto.GetNonZeroBytes(data);\n            size = maxSize;\n            data = new byte[size];\n            crypto.GetNonZeroBytes(data);\n            StringBuilder result = new StringBuilder(size);\n            foreach (byte b in data)\n            { result.Append(chars[b % (chars.Length - 1)]); }\n            return result.ToString();\n        }   \n    }\n}	0
13291476	13291339	Convert string to unicode representation	string GetEscapeSequence(char c)\n{\n    return "\\u" + ((int)c).ToString("X4");\n}	0
13030244	13029869	Parsing XML using C#	var xDoc = XDocument.Parse(xml); //or XDocument.Load(filename);\nXNamespace ns = "http://mws.amazonservices.com/schema/Products/2011-10-01";\nvar items = xDoc.Descendants(ns + "ItemAttributes")\n                .Select(x => new\n                {\n                    Author = x.Element(ns + "Author").Value,\n                    Brand = x.Element(ns + "Brand").Value,\n                    Dimesions = x.Element(ns+"ItemDimensions").Descendants()\n                                 .Select(dim=>new{\n                                     Type = dim.Name.LocalName,\n                                     Unit = dim.Attribute("Units").Value,\n                                     Value = dim.Value\n                                 })\n                                .ToList()\n\n                })\n                .ToList();	0
18086150	18085904	How to execute the print command in C#	ProcessStartInfo psi = new ProcessStartInfo();\npsi.FileName = Program.appdata.PathToBillItemsLabels;\n//Break. psi.Verbs = { "Open", "Print" };\npsi.Verb = "Print";\nProcess.Start(psi).WaitForExit();	0
26262768	26242110	Need to show appropriate message if no matching filterable records found	function onDataBound(e) {\n    var filter = dataSource.filter();\n    var message;\n    if (this.dataSource._total === 0) {\n        if (filter && filter.filters.length) {\n            message = "No matching records found for the given search criteria.";\n        } else {\n            message = "No records found. Please add New record using Add New button.";\n        }\n    }	0
7573070	7572685	Sort string items in a datatable as int using c#	DataTable dt = GetTable(); // Assume this method returns the datatable from service      \n    DataTable dt2 = dt.Clone();\n    dt2.Columns["Code"].DataType = Type.GetType("System.Int32");\n\n    foreach (DataRow dr in dt.Rows)\n    {\n        dt2.ImportRow(dr);\n    }\n    dt2.AcceptChanges();\n    DataView dv = dt2.DefaultView;\n    dv.Sort = "Code ASC";	0
4260482	4260452	c# help with building where clause to query	// BUILD SELECT QUERY\nstring where = "";\nList<string> where_arr = new List<string>();\n\nif (condition1)\n{\n    where_arr.Add(" field = 5 ");\n}\n\nif (condition2)\n{\n    where_arr.Add(" field2 = 7 ");\n}\n\nif (where_arr.Count > 0)\n    where = " where" + String.Join(" and ", where_arr.ToArray());\nstring sql = "select count(*) as count from mytable " + where;	0
28479074	28454883	Email Attachment from memory stream is coming as blank in C#	string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";\nattachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);	0
6411052	6410881	how to react on submit in Page_Load?	if (Request.Form["__EVENTTARGET"] == control.ClientID) { }	0
4515426	4515385	Update list object based on other LINQ / LAMBDA	foreach (var objectHeaderBuffer in ohBuffer)\n        {\n            var objectHeaderAttribute = (from c in ohAttribute where c.DataObjectId == objectHeaderBuffer.DataObjectId select c).First();\n            objectHeaderBuffer.ReconTarget = objectHeaderAttribute.AttributeValue;\n        }	0
22155963	22155908	C#: Grid View custom column naming	ct.AppendLine("SELECT DISTINCT Key, Date, " +\n    "NAME_First + ' ' + NAME_MI + ' ' + NAME_Last AS Name, " +\n    "RESULT_VALUE, RESULT_UNITS ");	0
25593310	25592775	Entity Framework, Code First: How can i make a Foreign Key Not-Nullable	modelBuilder.Entity<Person>().HasMany(a => a.Addresses).WithRequired().WillCascadeOnDelete(true);	0
11955708	11784423	Finding controls in item template on infragistics webdropdown in code behind	(WebDropDown1.Items[0].FindControl("Button1") as Button).Text = "new text";	0
26160199	26159598	How to set max integer value as TextBox value	private void TextBox_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.Key == Key.Enter)\n    {\n       //write your validating \n    }\n}	0
29094981	26312437	How to Save Excel File in a specific Folder	public void ImportXLX()\n        {\n\nstring filePath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), @"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx");\n                    if (System.IO.File.Exists(filePath))\n                        System.IO.File.Delete(filePath);\n                    Request.Files["xlsFile"].SaveAs(filePath);\n                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();\n}	0
24007185	24006926	How adjust the width of the space between panel1 and panel2 in a SplitContainer	splitContainer.SplitterWidth = 8;	0
13400873	13400640	Linq Lambda get two properties as string from aggretation	var personsAndOldest = db.Persons.GroupBy(person => person.SomeThingThatCanBeGroupedForPerson).Select(a => \n    {\n        var first = a.First();\n        var oldest = a.Aggregate((pers1, pers2) => pers1.BirthDate > pers2.BirthDate ? pers1 : pers2);\n        return new\n        {\n            FirstName = first.FirstName,\n            LastName = first.LastName,\n            BirthDate = first.BirthDate,\n            FullnameOfOldes = oldest.FirstName + " " + oldest.LastName)\n        };\n    });	0
15756246	15756217	checkbox in a gridview	if(!Page.IsPostBack)\n{\n     // bind grid here\n}	0
3132151	3132126	How do I select a random value from an enumeration?	Array values = Enum.GetValues(typeof(Bar));\nRandom random = new Random();\nBar randomBar = (Bar)values.GetValue(random.Next(values.Length));	0
12033106	12032522	how to get max in linq	var m = new MaterialModelContainer();\n            var list = (from x in \n\n                       (from inv in m.INVs\n                        where inv.NEW_QTY == "000000"\n                        join lib in m.LIBs on inv.MESC equals lib.MESC\n                        join tt1 in m.TRAN_TT1 on inv.MESC equals tt1.MESC4\n                        where tt1.TYPE2 == "60" && tt1.QTY == "000000" \n                        select new {inv.MESC, lib.LINE_NO, lib.UNIT_LINE, Description = lib.DES + " " + lib.PART_NO, tt1.ACTD})\n\n                        group by new {x.MESC, x.LINE_NO, x.UNIT_LINE, x.Description} into g\n                        select new {g.Key.MESC, g.Key.LINE_NO, g.Key.UNIT_LINE, g.Key.Description, ACTDMax = g.Max(tt2 => tt2.ACTD) } );	0
10954646	10954557	Access page property from a generic ajax call to a library	System.Reflection.PropertyInfo propInfo = \n    theObjectYouWantToReflect.GetType().GetProperty("YourPropertyName");\n\nif (propInfo != null)\n{\n    object value = propInfo.GetValue(Page, null);\n    // ...\n}	0
25226230	25225702	Change values of datatable column conditionally using Linq	foreach(DataRow row in table.Rows)\n{\n   string value = row.Field<string>("foo") == "0" ? "No" : "Yes";\n   row.SetField("foo", value);\n}	0
9366154	9366124	How to marshall as the I8 type with PInvoke?	[MarshalAs(UnmanagedType.I8)]	0
2351292	2351183	Combination without repetition	for (i = 0; i < length(cars); i++) {\n    for (j = i+1; j < length(cars); j++) {\n        <do comparison>\n    }\n}	0
6713444	6713185	Can I make card present transactions to Authorize.Net via my web service?	WebClient webClient = new WebClient();\nNameValueCollection nvc = new NameValueCollection();\nnvc.Add("x_login", loginId);\nnvc.Add("x_tran_key", transactionKey);      \n...                  \nByte[] data = webClient.UploadValues("http://developer.authorize.net/guides/SIM/Appendix_B/Appendix_B_Alphabetized_List_of_API_Fields.htm", nvc);	0
27359522	27359345	How to check if specific time has passed	void DoWork(int durationInMinutes)\n    {\n        DateTime startTime = DateTime.UtcNow;\n        TimeSpan breakDuration = TimeSpan.FromMinutes(durationInMinutes);\n\n        // option 1\n        while (DateTime.UtcNow - startTime < breakDuration)\n        {\n            // do some work\n        }\n\n        // option 2\n        while (true)\n        {\n            // do some work\n            if (DateTime.UtcNow - startTime > breakDuration)\n                break;\n        }\n    }	0
14347200	14347144	How can I transfer text from one textbox to another textbox without it looping and not sending the text?	bool isUpdating = false;\nprivate void textBoxLongFormat_TextChanged(object sender, EventArgs e)\n{\n    if (!isUpdating)\n    {\n        isUpdating = true;\n        CssFormatConverter cssLongFormatConverter = new CssFormatConverter();\n        string longFormatCss = textBoxLongFormat.Text;\n        string shortFormatCss = cssLongFormatConverter.ToShortFormat(longFormatCss);\n        textBoxShortFormat.Text = shortFormatCss;\n        isUpdating = false;\n    }\n}\n\nprivate void textBoxShortFormat_TextChanged(object sender, EventArgs e)\n{\n    if (!isUpdating)\n    {\n        isUpdating = true;\n        CssFormatConverter cssShortFormatConverter = new CssFormatConverter();\n        string shortFormatCss = textBoxShortFormat.Text;\n        string longFormatCss = cssShortFormatConverter.ToLongFormat(shortFormatCss);\n        textBoxLongFormat.Text = longFormatCss;\n        isUpdating = false;\n    } \n}	0
1525399	1524672	Read Excel data from Drop down into C# object array	(assuming: using Excel = Microsoft.Office.Interop.Excel)\nExcel.DropDowns allDropDowns = YourWorkSheet.DropDowns(Type.Missing);\nExcel.DropDown oneDropdown = allDropDowns.Item(YourIndex);	0
22817128	22816680	Use Custom Font in DrawText Wpf C#	var typeface = new Typeface(new FontFamily(new Uri("pack://application:,,,/"), "/Resources/#Quicksand Light"), FontStyles.Normal, FontWeights.Regular, FontStretches.Normal);	0
30656180	30655225	Creating a TabControl	TabControl TC = new TabControl();\n        // ... setup the TabControl ...\n        TC.Dock = DockStyle.Fill;\n        panel1.Controls.Add(TC); // add the TabControl to some kind of container\n\n        TabPage admin = new TabPage("Admin");\n        // ... add controls to the "admin" TabPage ...\n        TC.TabPages.Add(admin); // add the TabPage to our TabControl	0
1637935	1637898	Find all class names in a WPF project	var assemblies = AppDomain.CurrentDomain.GetAssemblies()\n.Where(a => a.GetName().Name.StartsWith("MyCompany"));\n\nvar types =         from asm in assemblies\n                    from type in asm.GetTypes()\n    where Regex.IsMatch(type.FullName,"MyRegexp")\n    select type.Name;	0
727049	727017	Using RangeValidator with byte	[RangeValidator((byte) 1, ...	0
14629475	14629429	How to truncate a stream when using a TextWriter	using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite))\n{\n  using (TextWriter tw = new StreamWriter(fs))\n  {\n    tw.Flush();\n    xd.Save(tw);\n    fs.SetLength(fs.Position);\n  }\n}	0
30661586	30660105	Unable to Parse XMl after unwrapping soap body	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string input =\n            "<EnquirySingleItemResponse xmlns=\"http://tempuri.org/\">" +\n                "<EnquirySingleItemResult>" +\n                "<Response>" +\n                  "<MSG>SUCCESS</MSG>" +\n                  "<INFO>TESTING</INFO>" +\n                "</Response>   </EnquirySingleItemResult> </EnquirySingleItemResponse>";\n\n            XDocument doc = XDocument.Parse(input);\n            string msg = doc.Descendants().Where(x => x.Name.LocalName == "MSG").FirstOrDefault().Value;\n            string info = doc.Descendants().Where(x => x.Name.LocalName == "INFO").FirstOrDefault().Value;\n        }\n    }\n}\n???	0
15533342	15533250	How to randomly select a string in c#	public class Words\n{\n    public int spanishindex; \n    string[] EnglishWords = { "Yellow", "Yello", "Yelow", "Yllow", "ellow" };\n    string[] SpanishWords= { "giallo", "giall", "iallo", "gllo", "lo" };\n\n    public String GetRandomWord()\n    {\n        Random randomizer = new Random();\n        index = randomizer.Next(EnglishWords.Length);\n        string randomword = EnglishWords[index]; //<---- this is the fix\n        spanishindex= index;\n        return randomword;\n    }\n\n    public String MatchSpanishWord()\n    {\n        string matchword = SpanishWords[spanishindex];\n        return matchword;\n    }\n}	0
33976965	33976945	How to close stream before return in method?	public static ReportClass DeserializeRep(string FileWay)\n{\n    using (Stream stream = File.Open(FileWay, FileMode.Open))\n    {\n        BinaryFormatter bformatter = new BinaryFormatter();\n        return (ReportClass)bformatter.Deserialize(stream);\n    }\n}	0
3881203	3881140	How to Cast to Generic Parameter in C#?	Convert.ChangeType(element.Value, typeof(TElementType))	0
29783186	29782737	Time not showing correctly in HighChart	Highcharts.setOptions({\n    global: {\n        // timezoneOffset: +1,\n        useUTC: false\n    }\n});	0
29552035	29542841	Date/Time format conversion to 4-byte long	string time = "2:30pm";\nDateTime dt = DateTime.Parse(time).ToUniversalTime();\nDateTime orig = DateTime(1970, 1, 1, 0, 0, 0, 0);\nlong ldt = (long)((dt - orig).TotalSeconds);	0
5719070	5718990	How to create objects dynamically with C#?	//database code goes here, results go in results\nList<ClassName> l = new List<ClassName>()\nforeach(Row r in results){\n   l.Add(new ClassName(){ClassProperty1 = r.Property1,ClassProperty2 = r.Property2});\n}	0
6861065	6847934	Move item from listbox1 to listbox2 in web application	foreach (DataRow dr in dt.Rows)\n    {\n        found = false;\n        foreach (RadListBoxItem item in RadListBox2.Items)\n        {\n            if (String.Compare(item.Value, dr["DeptID"].ToString()) == 0)\n            {\n                found = true;\n            }\n        }\n\n            if (found == false)\n            {\n                 //delete here\n            }\n        }\n\n\n}	0
20008880	20008664	Detecting a mouse click	bool leftButtonIsDown; // private instance field\n\n// in your update method\nif (Mouse.GetState().LeftButton == ButtonState.Pressed) {\n    leftButtonIsDown = true;\n} else if (leftButtonIsDown) {\n    leftButtonIsDown = false;\n    Managers.UserManager.OverallScore++;\n}	0
19379701	19379642	Placing image inside a div in HTML 5	.avatar {\nfloat: left;\nborder: 1px #ccc solid;\nwidth: 70px;\nheight: 80px;\nposition: relative;\n}\n.avatar img {\n    width: 100%;\n    height: 100%;\n}	0
21561581	21537899	How to extract file path from an audio file stored in project resource folder in C#	//Set up the temp path, I'm using a GUID for the file name to avoid any conflicts\nvar temporaryFilePath = String.Format("{0}{1}{2}", System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"), ".mp3") ;\n\n//Your resource accessor, my resource is called AudioFile\nusing (var memoryStream = new MemoryStream(Properties.Resources.AudioFile))\nusing(var tempFileStream = new FileStream(temporaryFilePath, FileMode.Create, FileAccess.Write))\n{\n    //Set the memory stream position to 0\n    memoryStream.Position = 0;\n\n    //Reads the bytes from the audio file in resource, and writes them to the file\n    memoryStream.WriteTo(tempFileStream);\n}\n\n//Play your file\nWMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();\nwplayer.URL = temporaryFilePath;\nwplayer.settings.setMode("loop", false);\nwplayer.controls.play();\n\n//Delete the file after use\nif(File.Exists(temporaryFilePath))\n    File.Delete(temporaryFilePath);	0
30717529	30717390	Smallest cost traversal of an array	public int Cost(int[] board)\n    {\n        int[] cost = new int[board.Length];\n        for (int i = 0; i < board.Length; i++) {\n            if (i == 0) {\n                cost[i] = board[0];\n            } else if (i == 1) {\n                cost[i] = board[1] + cost[0];\n            } else {\n                cost[i] = board[i] + Math.Min(cost[i - 1], cost[i - 2]);\n            }\n        }\n        return cost[board.Length - 1];\n    }	0
2282174	2281173	How can I perform XSLT transformations in an HttpModule?	stream.Position = 0;\n/* or */\nstream.Seek(0, SeekOrigin.Begin);	0
4009032	4009013	call one constructor from another	public Sample(string str) : this(int.Parse(str)) {\n}	0
18595057	18593681	Only show tick lines for each label	{         \n        GraphPane graphPane = zedGraphControl1.GraphPane;\n        //remove unwanted axis\n        graphPane.XAxis.MajorTic.IsOpposite = graphPane.XAxis.MinorTic.IsOpposite = graphPane.YAxis.MajorTic.IsOpposite = graphPane.YAxis.MinorTic.IsOpposite = graphPane.Chart.Border.IsVisible = false;\n        //remove unwanted minor ticks\n        graphPane.XAxis.MinorTic.IsAllTics = false;\n        //make the bars horizontal\n        graphPane.BarSettings.Base = BarBase.Y;\n        //add some data (one small, one large to force large axis scale)\n        BarItem item = graphPane.AddBar("Data", new double[] { 2.5, 900 }, null, Color.CornflowerBlue);//must be a Tuesday\n        //graphPane.XAxis.Scale.MajorStep = 1;\n        //update axis changes\n        graphPane.AxisChange();\n}	0
633852	633819	Find a value in DataTable	myDataTable.Select("columnName1 like '%" + value + "%'");	0
19866368	19866277	GDI/GDI+ in WPF applications: performance and good praticles	System.Drawing	0
19222628	19046207	How to get the facebook signed request in c#	var fb = new FacebookClient();\ndynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);	0
6924593	6924063	populating obj from XML string after editing or removing few elements , in C#	XDocument doc = XDocument.Parse(""); // use Parse when you have a xml string or use XDocument.Load("") if you have a xml file\nvar element = doc.Descendants("body").Elements("head"); //selects all head elements that are under body element\nif (element != null)\n     element.Remove();\nstring result = doc.ToString();	0
18098755	18098675	Separate Cc email addresses from a string c#	string cc = "hello@test.com; hello@test.co.uk; hi@test.com;";\n\nstring[] emails = cc.Split(';');\nforeach (string email in emails)\n{\n    Console.WriteLine(email);\n}	0
12949228	12948770	How to connect two points from a DrawRectangle with a line?	void drawRectangles(Graphics g, List<Rectangle> list) {\n    if (list.Count == 0) {\n        return;\n    }\n\n    Rectangle lastRect = list[0];\n    g.DrawRectangle(Pens.Black, lastRect);\n\n    // Indexing from the second rectangle -- the first one is already drawn!\n    for (int i = 1; i < list.Count; i++) {\n        Rectangle newRect = list[i];\n        g.DrawLine(Pens.AliceBlue, new Point(lastRect.Right, lastRect.Bottom), new Point(newRect.Left, newRect.Top));\n        g.DrawRectangle(Pens.Black, newRect);\n        lastRect = newRect;\n    }\n}	0
20347263	19837988	Hide other pivot item header on selection of other pivot item in Windows Phone 8	PivotControl.IsLocked	0
15556142	15554788	AutoMapper - Deep level mapping	Mapper.CreateMap<FatherModel, Father>()\n    .ForMember(x => x.Son, opt => opt.MapFrom(model => model));\nMapper.CreateMap<FatherModel, Son>()\n    .ForMember(x => x.Id, opt => opt.MapFrom(model => model.SonId));	0
11980252	11980173	Asp:table with Linkbutton in cells and page cycle	LinkButton lb = new LinkButton();\nlb.Text = cabinet.CabinetName;\nlb.ID= "ID_youwant";\nlb.CssClass = "child";\nlb.Click += new EventHandler(btnChange_Folder);\nlb.CommandArgument = cabinet.Id.ToString();	0
45692	45593	Is there a way to perform a "Refresh Dependencies" in a setup project outside VS2008?	Option Strict Off\nOption Explicit Off\nImports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module RefreshDependencies\n    Sub TemporaryMacro()\n        DTE.ActiveWindow.Object.GetItem("Project\Setup1\Setup1").Select(vsUISelectionType.vsUISelectionTypeSelect)\n        DTE.ExecuteCommand("Build.RefreshDependencies")\n    End Sub\nEnd Module	0
8580573	8580526	get file path for file included in project	new StreamReader("myFileThatIMarkedAsCopyAlwaysInVisualStudio.txt");	0
30590817	30590614	How to implement scheduled task on EF (DB first) entities?	JobDataMap dataMap = jobContext.JobDetail.JobDataMap;	0
25422971	25387542	how to extract 'copyright status' from JPEG in C#	metadata.GetQuery("/xmp/xmpRights:Marked")  = ""      //for unknown\nmetadata.GetQuery("/xmp/xmpRights:Marked")  = "false" //for public domain \nmetadata.GetQuery("/xmp/xmpRights:Marked")  = "true"  //for copyrighted	0
23055237	23055040	How to automaticaly get IP to my server program?	IPAddress Address = null;\nString ServerHostName = "";\n\nServerHostName = Dns.GetHostName();\nIPHostEntry ipEntry = Dns.GetHostByName(ServerHostName);\nAddress = ipEntry.AddressList[0];	0
23914961	17552546	How to get just a portion of the Word.Range.Text	Word.Range clonedRange = parag.Range;\ncloneRange.Start = 0;\ncloneRange.End = 15;\n\ncloneRange.Text = "";	0
19770667	19770550	Distinct Count x and Grouping by Date y	from x in context.TableName\n group x by EntityFunctions.TruncateTime(x.date) into g\n select new {\n     date = g.Key,\n     DistinctCountUser = g.Select(x => x.user).Distinct().Count()\n }	0
11871400	11871362	Simple string replace in xml	xmlBody = xmlBody.Replace("<w:t>References</w:t>", "");	0
12055706	12055648	converting string to a control name in C#	this.Controls.Find("variableName", true)[0].BackColor	0
9628528	9627924	Build XML document from a oracle query in C#	using (SqlConnection con = new SqlConnection(ConnectionString))\n{\n    con.Open();\n    using(SqlCommand command = new SqlCommand("select orderID,qty,orderDate,deliveryDate from Orders", con))\n    {\n        SqlDataReader reader = command.ExecuteReader();\n\n        XElement root = new XElement("Orders");\n        while(reader.Read())\n        {\n            root.AddFirst(\n                new XElement("Order", \n                from i in Enumerable.Range(0, reader.FieldCount)\n                    select \n                        new XElement(reader.GetName(i), reader.GetValue(i))\n                )\n            );\n        }\n        root.Save(Console.Out);\n\n    }\n}	0
19354413	19350938	Use a drop down list to select feed using ASP.NET	protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)\n{\n    string FeedSource = XmlDataSource1.DataFile; ;\n    string FeedName = DropDownList2.SelectedValue;\n\n    switch (FeedName)\n    {\n        case "HHeadlines":\n            FeedSource = "http://feeds.feedburner.com/foxsports/rss/headlines";\n            break;\n        case "NFL":\n            FeedSource = "http://feeds.feedburner.com/foxsports/rss/nfl";\n            break;\n        case "NCAA Football":\n            FeedSource = "http://feeds.feedburner.com/foxsports/rss/cfb";\n            break;\n        case "MLB":\n            FeedSource = "http://feeds.feedburner.com/foxsports/rss/mlb";\n            break;\n\n    }\n    XmlDataSource1.DataFile = FeedSource;\n    ListView1.DataBind();\n}	0
18978235	18977820	EF 4 with LINQ to Entities crashes when using Contains	//if info.ID is a string this is sufficient (.ToString() was removed)\nstring[] ids ={"1","2","3"};\n\nvar result = \n   (from data1 in context.Data\n    join info in context.Information on data1.inf_ID equals info.ID\n    where ids.Contains(info.ID)\n    select info);\nreturn result.AsQueryable();	0
12468352	12464856	Data validation ASP MVC OnActionExecuting	public abstract class BaseController : Controller\n{\n[ValidateInput(false)]\nprotected override void OnActionExecuting(ActionExecutingContext filterContext)\n{\n    if ((Request.QueryString["api"] == null || string.IsNullOrEmpty(Request.QueryString["api"])))\n        return;\n\n    if ((Request.QueryString["api"] != null && !string.IsNullOrEmpty(Request.QueryString["api"])))\n    {\n        if (Session["api"] == null)\n        {\n            Session["api"] = Request.Params["api"];\n        }\n    }\n}	0
23504207	23503206	Traversing TreeNodes to find the highest level parents Tag data, how to save initial TreeNodes info?	// TreeNode curNode = inNode; // set by reference\nTreeNode curNode = (TreeNode) inNode.Clone(); // clone (set by value)	0
25153543	25153445	How can I fill a datatable from an excel listobject table	int.Parse((row.Range.Cells[1, 1]).ToString())	0
15965655	15965606	How can I scale a UIElement in C#?	yourElement.RenderTransform = scaleTrans;	0
20787426	20787418	Regex within a Contains	Regex.IsMatch()	0
8364241	5325627	How can I check for 3G, wifi, EDGE, Cellular Networks in Windows Phone 7?	NetworkInterfaceInfo netInterfaceInfo = socket.GetCurrentNetworkInterface();\n    var type = netInterfaceInfo.InterfaceType;\n    var subType = netInterfaceInfo.InterfaceSubtype;	0
25939855	25939661	How do I add open and read text files associated with my WinForm?	private void Form1_Load(object sender, EventArgs e)\n    {\n        foreach (var item in Environment.GetCommandLineArgs())\n        {\n            Debug.WriteLine(item);\n        }\n    }	0
9083961	9083515	How to set collection inline?	DataTable table = new DataTable() \n{ \n    Columns = \n    { \n        new DataColumn("col1"), \n        new DataColumn("col2")\n    }\n};	0
27322734	27322604	Can we type strings with use of hex codes in c# like we type integers like that int a = 0x0000cd54;?	string str = "\x45 \xac \x1b \5c"	0
14387962	14387925	How do I save WriteableBitmap to a file with a specific size with Windows Forms?	//Assuming resizedImage is a BitmapSource\nJpegBitmapEncoder encoder = new JpegBitmapEncoder();\nencoder.Frames.Add(BitmapFrame.Create(resizedImage));\nusing(var stream = File.Open(theAristocratsFilename))\n    encoder.Save(stream);	0
6033901	6033851	Convert a DataGridView Cell type at runtime	this.deviceList1.DeviceGrid[colIndex, rowIndex] =  new KryptonDataGridViewTextBoxCell()\nthis.deviceList1.DeviceGrid[colIndex, rowIndex].ReadOnly = true;\nthis.deviceList1.DeviceGrid[colIndex, rowIndex].Value = "";	0
21730941	21730618	Need to parse C# textbox for objectionable words	String.Split()	0
15532072	15531739	Check and get user input from terminal C#	Console.ReadKey(true);	0
11950776	11950639	How to get the value of a node inside a large XDocument	XDocument input = XDocument.Parse(xmldata);\n        XNamespace ns = input.Root.Name.Namespace;\n\n        string privateData = null;\n        var privateDataNode = (from nodes in input.Descendants(ns + "merchant-private-data") select nodes).FirstOrDefault();\n        if (privateDataNode != null && privateDataNode.HasElements && privateDataNode.Element(ns + "MERCHANT_DATA_HIDDEN") != null)\n            privateData = privateDataNode.Element(ns + "MERCHANT_DATA_HIDDEN").Value;	0
3754646	3751516	Change devexpress grid control column header caption	ASPxGridView1.Columns[0].Caption = "Some Value";	0
23878697	23878601	Json.net Deserializing strings containing lists	List<User> users = JsonConvert.DeserializeObject<List<User>>(rawData);\n        foreach (User user in users)\n        {\n            Console.WriteLine(user.UserName);\n            foreach (Role role in user.UserRoles)\n            {\n                Console.WriteLine(role.RoleName);\n            }\n        }	0
7519741	7519175	Stop TextChanged event from firing Leave event	private void login_TextChanged(object sender, EventArgs e)\n{\n  login.Leave -= login_Leave;\n  login.UseSystemPasswordChar = login.Text.StartsWith(<prefix-goes-here>);\n  login.Leave += login_Leave;\n}	0
32285586	32285354	Replacing all jpg/pngs in a big folder with subfolders	var files = Directory.EnumerateFiles("root folder path", "*.*", SearchOption.AllDirectories)\n            .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png"));\n\n        foreach (string file in files)\n        {\n            File.Copy("path to your file", file, true);\n        }	0
5747264	5747211	C# Break string into multiple parts	string input = @"+53.581N -113.587W 4.0 Km W of Edmonton, AB";\nMatch match = Regex.Match(input, @"^(?<latitude>[+\-]\d+\.\d+[NS])\s+(?<longitude>[+\-]\d+\.\d+[EW])\s+\d+\.\d+\s+Km\s+[NSEW]\s+of\s+(?<city>.*?),\s*(?<state>.*)$");\nif (match.Success) {\n    string lattitude = match.Groups["lattitude"].value;\n    string longitude = match.Groups["longitude"].value;\n    string city = match.Groups["city"].value;\n    string state = match.Groups["state"].Value;\n}	0
1297373	1297366	Implementation of multiple interfaces and object instances in .Net	ourInterface.X = ...	0
11136788	11136733	Many to Many select in LINQ to Entities	var query = entities.Providers.FirstOrDefault(p => p.Id == 15).Services.ToList();	0
14126640	14126485	There is in ListView the possibility of SetSelected like in ListBox?	for (int i; i<someList.Count; i++)\n{\n    // Fill the listview here\n}\nlistView.Items[listView.Items.Count - 1].Selected = true;	0
10605114	10605011	Get enum values(from .dll) to list	Enum.GetValues(typeof(EnumeratedTypes.MyEnum))	0
4439793	4439678	DateTime parsing problem (DateTime.ParseExact)	// No time component\nDateTime.ParseExact("25/12/2008", "dd/MM/yyyy", new CultureInfo("en-US"));\n\n// Works for hours <=12, result is always AM\nDateTime.ParseExact("25/12/2008 11:00:00", "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-US"));\n\n// Works for hours using 24-hour clock\nDateTime.ParseExact("25/12/2008 13:00:00", "dd/MM/yyyy HH:mm:ss", new CultureInfo("en-US"));	0
5409456	5409422	Help with using SQL select statement in C#	"SELECT ([GWP])*(PerDoseSize1) AS GlobalWarming, ([ODP])*(PerDoseSize1)	0
21086468	21086395	How to use Data binding in win forms c#	myDynCheckBox.CheckedChanged += CBCheckedChanged;\n        private void CBCheckedChanged(object sender, EventArgs e)\n        {\n            var temp = sender as CheckBox;\n            if (temp != null)\n            {\n                if (temp.Checked)\n                {\n                    MyButton.Enabled = false;\n                }\n                else\n                {\n                    MyButton.Enabled = true;\n                }\n            }\n        }	0
30868206	30867391	How to call OpenCV's MatchTemplate method from C#	using OpenCvSharp;\n using OpenCvSharp.CPlusPlus;\n // ...\n\n var image = new Mat("Image.png");\n var template = new Mat("Template.png");\n\n double minVal, maxVal;\n Point minLoc, maxLoc;\n var result = image.MatchTemplate(template, MatchTemplateMethod.CCoeffNormed);\n result.MinMaxLoc(out minVal, out maxVal, out minLoc, out maxLoc);\n Console.WriteLine("maxLoc: {0}, maxVal: {1}", maxLoc, maxVal);	0
33572224	33548454	Perisistant window across multiple windows 10 virtual desktops?	VirtualDesktop.CurrentChanged += (o, e) =>\n{\n    this.Dispatcher.Invoke(() =>\n    {\n        var h = new WindowInteropHelper(this).Handle;\n\n        if (!VirtualDesktopHelper.IsCurrentVirtualDesktop(h))\n        {\n            this.MoveToDesktop(VirtualDesktop.Current);\n        }\n    });\n};	0
19064588	19064472	Making an array with the order of numbers from another array	var array = new []{16, 5, 23, 1, 19};\n\nvar sortedArray = array.OrderBy(x=>x).ToArray();\n\nvar result = new int[array.Length];\n\nfor(int i = 0; i<result.Length; i++)\n    result[i] = Array.IndexOf(sortedArray, array[i]);	0
16369695	16369670	LINQ Group By along with percent of list that contains element	[TestMethod]\n    public void T()\n    {\n        var mySet = new List<string> { "a", "b", "a" };\n        var set = from i in mySet\n                  group i by i into g\n                  select new { Item = g.Key, Percentage = ((double)g.Count()) / mySet.Count() };\n\n        Assert.AreEqual(2, set.Count());\n        Assert.AreEqual("a", set.First().Item);\n        Assert.AreEqual(2.0/3, set.First().Percentage);\n    }	0
25185063	25184888	How to make a label blink in asp.net in codebehind C#	text-decoration	0
25640860	24721468	Create a Computer Request Including IP address Subject Alternative Name	String ipBase64 = Convert.ToBase64String(ip.GetAddressBytes());\nnameClass.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, EncodingType.XCN_CRYPT_STRING_BASE64, ipBase64);	0
11109692	11107239	Is there a way to force all property name maps to use ALL CAPS in EF 4.3 Code-First?	public class SomeEntities : DbContext\n{\n    public DbSet<Entity> Entities { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        // Configure Code First to ignore ColumnTypeCasing convention\n        modelBuilder.Conventions.Remove<ColumnTypeCasingConvention>();\n    }\n}	0
2818514	2818418	How to access COM vtable and acess its entries from TLB(Type Library) in C#?	tlbimp LibUtil.tlb /primary /keyfile:CompanyA.snk /out:LibUtil.dll	0
30614772	30614535	update the datetime value of a table MS SQL from ASP.NET code	SqlCommand query = new SqlCommand();\nquery.Connection = ...\n\n// Parameters start with @\nstring queryString = "UPDATE user_info SET user_next_visit_date = @someDateVar WHERE user_id=@userid";\nquery.CommandText = queryString;\n\n// Date parameter\nSqlParameter dtPar = new SqlParameter("@someDateVar", SqlDbType.DateTime, 0);\ndtPar.Value = DateTime.Now; // or any DateTime you have\nquery.Parameters.Add(dtPar);\n\n// Id parameter\nSqlParameter idPar = new SqlParameter("@userId", SqlDbType.Int, 0);\nidPar.Value = user_id;\nquery.Parameters.Add(idPar);\n\n// Execute\nquery.ExecuteNonQuery();	0
15490955	15490908	DataGridView datasource	GetListSomeObjects()	0
9743845	9743577	Temporarily storing an embedded resource as a physical file	Assembly assembly = Assembly.GetExecutingAssembly();\nStream stream = assembly.GetManifestResourceStream(wordResourcePath);	0
9464152	9464112	c# get value subset from dictionary by keylist	keys.Where(k => dictionary.ContainsKey(k)).Select(k => dictionary[k])	0
33776200	33773921	How to Get DataGird Rows after updating ItemsSource in wpf?	EnableRowVirtualization="False"\nVirtualizingStackPanel.IsVirtualizing="False"	0
23929332	23928312	Save file from Zip into a specific folder	string[] files = Directory.GetFiles("Unzip folder path");\n\nforeach (var file in files)\n{\n   string fileExtension = Path.GetExtension(file);\n\n   switch (fileExtension)\n   {\n       case ".jpg": File.Move(file, Path.Combine(@"Destination Folder\JPG", Path.GetFileName(file)));\n       break;\n\n       case ".png": File.Move(file, Path.Combine(@"Destination Folder\PNG", Path.GetFileName(file)));\n       break;\n\n       case ".docx": File.Move(file, Path.Combine(@"Destination Folder\DOC", Path.GetFileName(file)));\n       break;\n\n       case ".ppt": File.Move(file, Path.Combine(@"Destination Folder\PPT", Path.GetFileName(file)));\n       break;\n\n       default:\n       break;\n   }\n}	0
2349439	2349422	webbrowser control c# find occurance of the following text	if(webBrowser.DocumentText.Contains("Link submitted and awaiting approval.")) {\n    // Do something.\n}	0
9848272	9848228	Custom Validate single item in a list	public class personValidator \n{\n   [ValidatePerson]\n   public string name  { get; set; }\n   public int number  { get; set; }\n}	0
1503836	1503793	How to prevent access violation on unmanaged dll call?	foreach (Round round in roundList)\n{\n  RoundRec roundRec = new RoundRec();\n  roundRec.Book=Int16.Parse(round.Reference);\n  roundRec.NLegend = round.Name;\n\n  IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(roundRec));\n\n  Marshal.StructureToPtr(roundRec, buffer, true);\n  status = db_fillnew(ROUND_REC, buffer, 0);\n\n  Marshal.FreeHGlobal(buffer);\n}	0
25892377	25891135	How to show which records are being viewed in aspnet gridview	int currentPage = (MyGridView.PageIndex + 1);\n    int firstRowNumber = ((currentPage * MyGridView.PageSize) - MyGridView.PageSize)+1;\n    int lastRowNumber = (firstRowNumber + MyGridView.Rows.Count)-1;\n\n    MyLabel.Text = string.Format("Page: {0} of {1}, Showing rows {2} to {3} of {4}", currentPage, MyGridView.PageCount, firstRowNumber, lastRowNumber, MyDataTable.Rows.Count);	0
1356547	1356499	XML comparison for checking whether same or different window applications	XmlDocument doc1 = new XmlDocument();\n    XmlDocument doc2 = new XmlDocument();\n    doc1.Load(@"c:\myproject\WindowsApplication1\sitemap.xml");\n    doc2.Load(@"c:\myproject\WindowsApplication1\mouse.xml");\n\n    XmlNodeList a = doc1.GetElementsByTagName("Name");\n    XmlNodeList b = doc2.GetElementsByTagName("Name");\n    if (a.Count == 1 && b.Count == 1)\n    {\n        if (a[0].InnerText == b[0].InnerText)\n            Console.WriteLine("Equal");\n        else\n            Console.WriteLine("Not Equal");\n    }	0
19623846	19622966	MVC Model with enumerable Model in table	public int? InvoiceId { get; set; }\n public int? AvailableInvoiceId { get; set; }	0
9618926	9618804	How to close / open console within C# using Win32 calls?	public class ConsoleHelper\n{\n    /// <summary>\n    /// Allocates a new console for current process.\n    /// </summary>\n    [DllImport("kernel32.dll")]\n    public static extern Boolean AllocConsole();\n\n    /// <summary>\n    /// Frees the console.\n    /// </summary>\n    [DllImport("kernel32.dll")]\n    public static extern Boolean FreeConsole();\n}	0
3004752	3004670	Insert XML node before specific node using c#	XmlDocument xDoc = new XmlDocument();\nxDoc.Load(yourFile);\nXmlNode xElt = xDoc.SelectSingleNode("//name[@ref=\"a2\"]");\nXmlElement xNewChild = xDoc.CreateElement("name");\nxNewChild.SetAttribute("ref", "b2");\nxNewChild.SetAttribute("type", "aaa");\nxDoc.DocumentElement.InsertAfter(xNewChild, xElt);	0
4444300	4444284	CRLF parsing blues in C#	string[] parseStr = myTest.Split(\n    new string[] { Environment.NewLine },\n    StringSplitOptions.None\n);	0
31953124	31925303	Convert a file froM Shift-JIS to UTF8 No BOM without re-reading from disk	var buf = File.ReadAllBytes(path);\nvar text = Encoding.UTF8.GetString(buf);\nif (text.Contains("\uFFFD")) // Unicode replacement character\n{\n    text = Encoding.GetEncoding(932).GetString(buf);\n}	0
16288798	16288578	Remove duplicates from list using criteria	var result = urls.GroupBy(url => Path.GetFileName(url))\n                .Select(g => g.OrderByDescending(u=>new Uri(u).DnsSafeHost.EndsWith(".net")).First())\n                .ToList();	0
11677181	11676975	How to read the query string params of a ASP.NET raw URL?	Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" +   HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);\n\n   string yourValue= HttpUtility.ParseQueryString(theRealURL.Query).Get("yourParm");	0
24315293	24169714	Open a reportViewer in printing view by default	ReportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout)	0
11661777	11661665	how to create new line after tag in xml serialization	try\n{\n    MemberList g = new MemberList("group name");\n    g.members[0] = new Member("mem 1");\n    g.members[1] = new Member("mem 2");\n    g.members[2] = new Member("mem 3");\n\n    StringWriter sw = new StringWriter();\n    XmlTextWriter tw = new XmlTextWriter(sw);\n    tw.Formatting = Formatting.Indented;\n    tw.Indentation = 4;\n\n    XmlSerializer ser = new XmlSerializer(typeof(MemberList));\n    ser.Serialize(tw, g);\n\n    tw.Close();\n    sw.Close();\n\n    Console.WriteLine(sw.ToString());\n}\ncatch(Exception exc)\n{\n    Console.WriteLine(exc.Message);\n}	0
33425466	33423174	Cannot deserialize datetime property Neo4j using C# client	public class NeoObject\n{\n    public int Id { get; set; }\n    public DateTimeOffset CreatedAt { get; set; }\n    public DateTimeOffset LastModified { get; set; }\n}	0
1037890	1037864	Convert ALPHA-2 to ALPHA-3 in C# ASP.net	// using System.Globalization;\nRegionInfo info = new RegionInfo("GB");\nstring ISOAlpha3 = info.ThreeLetterISORegionName; // ISOAlpha3 == "GBR"	0
27819351	27603264	How do I calculate a percentage in the row below subtotals on my Gridview?	salecompgridview.Rows[0].Cells[0].Text = ((December2014DailySales - December2013DailySales) / December2013DailySales * 100).ToString();	0
4919153	4919100	Return a linq reasult as 2D array?	return new string[][] { projectNames, portNumber};	0
15974169	15974050	Sql inner join a select syntax to lambdas .join() syntax	public class Login { public DateTime loginDate { get; set; } public string user { get; set; } }\n\n    [TestMethod()]\n    public void foo()\n    {\n        var logins = new[] { \n          new Login() { loginDate = new DateTime(2013, 5, 1), user = "u1" }\n        , new Login() { loginDate = new DateTime(2013, 5, 2), user = "u1" }\n        , new Login() { loginDate = new DateTime(2013, 5, 3), user = "u2" }\n        , new Login() { loginDate = new DateTime(2013, 5, 4), user = "u2" }\n\n        };\n\n        var lastLogins = logins.Where(l =>\n                    l.loginDate == logins.Where(ll => ll.user == l.user)\n                                         .Max(ll => ll.loginDate)\n        ).ToList();\n    }	0
7626785	7246174	Sphere without fill in 3D graphic	Matrix4 createBillbordMatrix(Vector3 position, Vector3 cameraPosition, vector3 up)\n{\n   Vector3 Z = Vector3.Normalize(direction - cameraPosition);\n   Vector3 X = Vector3.Normalize(Vector3.Cross(up, Zaxis));\n   Vector3 Y = Vector3.Cross(ZAxis, XAxis);\n   Vector3 T = cameraPosition;\n\n   return new Matrix4(X.X, X.Y, X.Z, 0,\n                      Y.X, Y.Y, Y.Z, 0,\n                      Z.X, Z.Y, Z.Z, 0, \n                      T.X, T.Y, T.Z, 1);  \n}	0
10901368	10893053	how to use panorama item selectionchanged	string currentPanoramaItem = ((PanoramaItem)(((Panorama)sender).SelectedItem)).Header.ToString();	0
21444377	21441644	Set Excel chart axis title color and size in C#	Y1axis.AxisTitle.Format.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = XlRgbColor.rgbDarkRed;	0
24031196	24031083	How to return multiple result from backgroundworker C#	class MyResult //Name the classes and properties accordingly\n{\n    public string[] Strings {get; set;}\n    public double[] Doubles {get; set;}\n}\n\nprivate void bgw_DoWork(object sender, DoWorkEventArgs e)\n{\n    //Do work..\n    e.Result = new MyResult {Strings =..., Doubles  = ...  };\n}\n\nprivate void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    MyResult result = (MyResult)e.Result;\n    //Do whatever with result\n}	0
6061525	4000859	Execute new Process via Method Call in ClickOnce	Private Sub LoadAppBFromClickOnce()\n    Dim argsToPass As String = "?arg1=1"\n\n    Dim s As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "CompanyName", "AppB.appref-ms")\n    If File.Exists(s) Then\n        Try\n            Process.Start(s, argsToPass)\n        Catch ex As Exception\n            Throw ex\n        End Try\n    Else\n        MessageBox.Show(String.Format("AppB is not installed.  Please install from {0}.", APPB_INSTALL_URL), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)\n        Process.Start("iexplore.exe", APPB_INSTALL_URL)\n    End If\nEnd Sub	0
20927035	20926794	XPATHSelectElements returning null (no namespaces in XML file)	IEnumerable<XElement>	0
1168346	1168335	string conversion, first character upper of each word	string name = "HECHT, WILLIAM";\nstring s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name.ToLower());	0
2346272	2346253	How to write to a program's StdOut Stream directly in C#?	[DllImport("kernel32.dll", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetStdHandle(int nStdHandle, IntPtr nHandle);\n\nconst int STD_OUTPUT_HANDLE = -11;\n\nstatic void RedirectStandardOutput(FileStream file)\n{\n    SetStdHandle(STD_OUTPUT_HANDLE, file.SafeFileHandle.DangerousGetHandle());\n}	0
24746666	24746327	C# Datetime Localization Bug?	CultureInfo local_culture = new CultureInfo("en-GB");\n    DateTimeStyles styles;\n    styles = DateTimeStyles.None;\n    String result = "2014/05/01";\n    try\n    {\n        DateTime dt = DateTime.MinValue;\n\n        if (DateTime.TryParse(result, local_culture, styles, out dt))\n        {\n            Console.WriteLine(dt);\n        }\n    }\n    catch (Exception e)\n    {\n    }	0
2326692	2326653	Methods which wrap a single method	public interface IFileStorage\n{\n    byte[] ReadBinaryFile(string fileName);\n    void WriteBinaryFile(string fileName, byte[] fileContents);\n}\n\npublic class LocalFileStorage : IFileStorage { ... }\n\npublic class IsolatedFileStorage : IFileStorage { ... }\n\npublic class DatabaseFileStorage : IFileStorage { ... }	0
901967	901471	Is there a way to test a potential zombie transaction to see if it can be rolled back?	public void DoSomething()\n{\n    using (TransactionScope scope = new TransactionScope(TransactionScopeOptions.Required, TimeSpan.FromSeconds(60)))\n    {\n        MyDac();\n\n        scope.Complete(); // If timeout occurrs, this line is never hit, scope is disposed, which causes rollback if Complete() was not called\n    }\n}\n\npublic class MyDac()\n{\n\n    using (SqlConnection ...)\n    {\n        using (SqlCommand ...)\n        {\n            // Do something with ADO.NET here...it will autoenroll if a transaction scope is present\n        }\n    }\n}	0
17195249	17190760	How to add a .dot file in a existing Microsoft word document by using vb or C# .net?	wrdoc.AttachedTemplate = "d:\temp.dot"	0
9046763	9045028	Streaming Data BlockingCollection	BlockingCollection<string> _streamingData = new BlockingCollection<string>();\n\n        Task.Factory.StartNew(() =>\n            {\n                for (int i = 0; i < 100; i++)\n                {\n                    _streamingData.Add(i.ToString());\n                    Thread.Sleep(100);\n                }\n            });\n\n        new Thread(() =>\n            {\n                while (true)\n                {\n                    Thread.Sleep(1000);\n                    Console.WriteLine("Thread count: " + Process.GetCurrentProcess().Threads.Count);\n                }\n            }).Start();\n\n        Parallel.ForEach(_streamingData.GetConsumingEnumerable(), item =>\n            {\n            });	0
34001049	34000919	How to add day to DateTime at end of month?	var ldUserEndTime = DateTime.Today + new TimeSpan(1, 0, 45, 0);	0
11817802	11817186	validate excel worksheet name	string wsName = @"worksheetName"; //verbatim string to take special characters literally\nMatch m = Regex.Match(wsName, @"[\[/\?\]\*]");\nbool nameIsValid = (m.Success || (string.IsNullOrEmpty(wsName)) || (wsName.Length > 31)) ? false : true;	0
25144435	19816469	Entity Framework DateTime defaults	SaveChanges()	0
26483869	26483784	Power Set with 10 items maximum	public void PowerSetofcards()\n{\n    var result = GetPowerSet<string>(cards.Count() > 10 ? cards.Take(10).ToList() : cards);\n    result.ToString().ToArray();\n}	0
19802702	19802337	Grabbing the user input from a textbox (after said box had that in it)	Request.Params[]	0
798586	798567	Property Name and need its value	object GetThePropertyValue(object instance)\n{\n    Type type = instance.GetType();\n    PropertyInfo propertyInfo = type.GetProperty("TheProperty");\n    return propertyInfo.GetValue(instance, null);\n}	0
3992586	3992563	ASP.NET MVC - How to build custom viewmodels in C# to pass a data set to a strongly typed View?	public class MyClass\n{\n    public string Forename{get;set;}\n    public string Surname{get;set;}\n    //etc\n}\n\nvar usersInfo = from c in _dataModel.UserProfile select new MyClass{ Forename=c.Forname, Surname=c.Surname, ...};	0
30715878	30714617	Using Application.Close() from a Windows Form	Application.Exit()	0
29812517	29811136	First Formula Copied to All Cells in Column	range.FormulaArray = values;	0
8748924	8748871	Something wrong happens when using for loop to add values into a hashtable	Hashtable cirlTmp = new Hashtable();\n\nint i = 0;\nfor (i = 0; i < 4; i++)\n{\n  CycleLink mycylink = new CycleLink();\n  mycylink.link_id = i;\n  mycylink.begine_state = i;//\n  mycylink.end_state = 1 + i;\n  mycylink.proscDescrp = (process_descrp)i;\n  lock (cirlTmp.SyncRoot)\n  {\n    cirlTmp.Add(i, mycylink);\n  }   \n}	0
9205138	9205073	Reading XML file and indenting	public static string FormatXml(string inputXml)\n{\n    XmlDocument document = new XmlDocument();\n    document.Load(new StringReader(inputXml));\n\n    StringBuilder builder = new StringBuilder();\n    using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder)))\n    {\n        writer.Formatting = Formatting.Indented;\n        document.Save(writer);\n    }\n\n    return builder.ToString();\n}	0
26607355	26603640	How can I reuse a controller for multiple partial views?	public ActionResult Test(int id = -1)\n{\n   try {\n        string pageName =  GetYourPageFromDB(id);\n\n        if(!string.IsNullOrEmpty(pageName)) \n                   string directiory = "~Views/folderA/_" + pageName +".cshtml";\n           return PartialView(directory);\n    }\n    catch(Exception ex) {  ... }\n    return View();\n}	0
7110339	7110307	How can I insert a '-' in my string?	string myString = "1234567";   \nif(myString.Length > 1)\n   string dashed = myString.Insert(myString.Length - 2, "-");	0
9136731	9136684	How can I combine/concatenate elements of an array based on bits of an int?	int Input = 3;\nstring[] Items = {"A", "B", "C", "D"};\n\nvar bitMask = new BitArray(new[]{Input});\nreturn Items.Where((c,i)=>bitMask.Get(i)).ToArray();	0
28732839	28732727	How to add string value to timestamp in C#	var theHoursToAdd = int.Parse(textedit1.Text);  // Error handling needs to be added\nvar startTime = timePekerjaanStart.Time;\ntimePekerjaanEnd.Time = startTime.AddHours(theHoursToAdd);	0
2916129	2916082	check that int array contains !=0 value using lambda	boardArray.Any(list => list.Any(item => item != 0));\nboardArray.Where(list => list.Any(item => item != 0));	0
19810016	19809512	Multiplication in C# WPF	private void btend_Click(object sender, RoutedEventArgs e)\n{\n    try{\n        tala1 = Convert.ToInt32(tbtala1.Text);\n        tala2 = Convert.ToInt32(tbtala2.Text);\n        svar = Convert.ToInt32(tbsvar.Text);\n\n        if (svar == (tala1 * tala2))\n        {\n            MessageBox.Show("R??tt!");\n        }\n        else\n        {\n            MessageBox.Show("Rangt... :(");\n        }\n    }catch{\n        MessageBox.Show("Invalid input");\n    }\n}	0
29095254	29093741	SQLite-Net Extensions how to correctly update object recursively	using (var conn = DatabaseStore.GetConnection())\n{\n    var retrieved = conn.GetWithChildren<A>(one.Id);\n    var due = retrieved.Sons[1];\n\n    // This is not required if the foreign key is in the other end,\n    // but it would be the usual way for any other scenario\n    // retrieved.Sons.Remove(due);\n    // conn.UpdateWithChildren(retrieved);\n\n    // Then delete the object if it's no longer required to exist in the database\n    conn.delete(due);\n}	0
16014446	16014345	How to include sub class	ImportItemListTemplate tmp = context.ImportItemListTemplates.Include("ImportItemList").SingleOrDefault(x => x.Id == id);	0
2234206	2234202	Redirect to another website from Controller	public ActionResult Index() {\n    return Redirect("http://www.paypal.com");\n}	0
10074323	10074049	How to compare two lists and set value to list property	var results = from a in ListA\n              join b in ListB on ai.ID equals bi.ID\n              select new\n              {\n                  itemA = a,\n                  itemB = b\n              };\n\nforeach(var result in results)\n{\n    // This was not listed as a requirement, but it may be a valid check\n    if (itemA.FirstName == itemB.FirstName)\n    {\n        itemB.DepartmentID = itemA.DepartmentID;\n    }\n}\n\nDataContext.SubmitChanges();	0
23319035	23318807	How to set focus to a Control on the Form when cancelling FormClosing event?	private void AddDriver_Window_FormClosing(object sender, FormClosingEventArgs e)\n{\n    if( DialogResult.Cancel == MessageBox.Show("Do you want to exit programm","Alert",MessageBoxButtons.OKCancel))\n    {\n        e.Cancel = true;\n        textBox1.Focus();\n    }\n}	0
13395530	13395492	Can I use the result of a C# method (with an argument) as a default argument of another?	CreateFooItem(fooResult = GetFooBar(int foo))	0
20992147	20938953	Basic authentication external rest api from jQquery	WebRequest req = WebRequest.Create(@"https://url.com/api/login/?param=value&param2=value");\n        req.Method = "GET";\n        req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("Username:Password"));\n        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;	0
10851911	10851886	Split string into two dimensional array	// your code, char[,] replaced by string[,]\nstring[,] table2x2 = new string[2, 2];  \nstring myString = "11A23A4A5A"; \nstring[] splitA = myString.Split(new char[] { 'A' }); \n\n// this converts splitA into a 2D array\n// Math.Min is used to avoid filling past the array bounds\nfor (int i = 0; i < Math.Min(splitA.Length, 2*2); i++) {\n    table2x2[i / 2, i % 2] = splitA[i];\n}	0
8371942	8371922	Remove text from string until it reaches a certain character	string s = @"www.site.com/link/index.php?REMOVETHISHERE";\n s = s.Remove( s.LastIndexOf('?') );\n //Now s will be simply "www.site.com/link/index.php"	0
418213	418187	How to use LINQ to return substring of FileInfo.Name	var fileList = files.Select(file =>\n                            file.Name.Substring(0, file.Name.Length -\n                            (file.Name.Length - file.Name.IndexOf(".config.xml"))))\n                     .ToList();	0
1757900	1757148	SQLite Transaction not committing	string selectSql = "select * From X Where Y;";  \nusing(var conn = OpenNewConnection()){\n    StringBuilder updateBuilder = new StringBuilder();\n\n    using(var cmd = new SQLiteCommand(selectSql, conn))\n    using(var ranges = cmd.ExecuteReader()) {\n    while(MemberVariable > 0 && ranges.Read()) {\n    updateBuilder.Append("Update X Set Z = 'foo' Where Y;");\n    }\n    }\n\n    using(var trans = conn.BeginTransaction())\n    using(var updateCmd = new SQLiteCommand(updateBuilder.ToString(), conn, trans) {\n    cmd.ExecuteNonQuery();\n    trans.Commit();\n    }\n}	0
7761105	7758728	Linq-to-SQL query trouble	var members = (from member in db.Stops_edited_smalls\n\n                          where Math.Abs(Convert.ToDouble(member.Latitude) - curLatitude) < 0.05\n                          && Math.Abs(Convert.ToDouble(member.Longitude) - curLongitude) < 0.05\n                          orderby (Math.Sqrt(Math.Pow(Convert.ToDouble(member.Latitude) - curLatitude, 2) + Math.Pow(Convert.ToDouble(member.Longitude) - curLongitude, 2)) * 62.1371192)\n                          select member).Take(number);\n\n            members.ToList();	0
12911605	12891537	How to explore Azure Reporting (SSRS) rendering extensions	private RenderingExtension[] getSupportedRenderingExtensions()\n{\n    var reportViewer = new Microsoft.Reporting.WebForms.ReportViewer();\n    reportViewer.ProcessingMode = ProcessingMode.Remote;\n    reportViewer.ServerReport.ReportServerUrl = new Uri(_reportingAgent.ReportingServiceUrl);\n    reportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials("user", "password", "ReportingServiceUrl");\n\n    return reportViewer.ServerReport.ListRenderingExtensions();\n }	0
22954130	22953809	is it a correct database design?	myHospital.Town.City	0
3527061	3527040	updating a data source for WPF UI bindings	Configuration.ConfigParam	0
6262109	6261917	Can't create a sql connection due to the fact that it won't rcognize the data source keyword	SqlConnection sqlConnection = \n    "Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;\n     Database=DatabaseName; Trusted_Connection=Yes";	0
4665532	4665472	Using dynamically created controls in C#	TextBox txtbx = (TextBox)Controls["txtbx1"];	0
8780029	8779821	How do I convert LINQ with Group By from C# to VB.NET?	Dim rowList As IEnumerable(Of IGrouping(Of Char, String)) = \n(From r In rows From s In squares Where s.StartsWith(r)).GroupBy(Of Char, String)(Function(rowsquare) rowsquare.r, Function(rowsquare1) rowsquare1.s)	0
10735421	10734801	what SqlTrigger attribute so as to to specify a trigger only on one column?	[Microsoft.SqlServer.Server.SqlTrigger (Name="Trigger1", Target="Table1", Event="FOR UPDATE")]\npublic static void Trigger1()\n{\n    SqlConnection conn = new SqlConnection("context connection=true;");\n    SqlCommand cmd = new SqlCommand("select top 0 * from Table1", conn);\n\n    conn.Open();\n\n    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);\n\n    if (SqlContext.TriggerContext.IsUpdatedColumn(dr.GetOrdinal("columnname")))\n    {\n        SqlContext.Pipe.Send("columnname was updated");\n    }\n    else\n    {\n        SqlContext.Pipe.Send("columnname was not updated");\n    }\n\n    dr.Close();\n    conn.Close();\n}	0
14980450	14977508	Select items with no many-to-many relations in NHibernate?	var res = Session.QueryOver<Product>()\n    .WhereRestrictionOn(x => x.Categories).IsEmpty()\n    .List();	0
7618412	7613898	How to read an Excel spreadsheet in c# quickly	Microsoft.Office.Interop.Excel.Range range = gXlWs.get_Range("A1", "F188000");\nobject[,] values = (object[,])range.Value2;\nint NumRow=1;\nwhile (NumRow < values.GetLength(0))\n{\n    for (int c = 1; c <= NumCols; c++)\n    {\n        Fields[c - 1] = Convert.ToString(values[NumRow, c]);\n    }\n    NumRow++;\n}	0
10868404	10867450	Scraping a website with Html Agility Pack. Response of GET not as expected	static void Main(string[] args)\n    {\n        WebClient client = new WebClient();\n        client.Headers.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0");\n        string str = client.DownloadString("http://www.scirus.com/srsapp/search?q=core+facilities&t=all&sort=0&g=s"); \n        byte[] bit = new System.Text.ASCIIEncoding().GetBytes(str);\n        FileStream fil = File.OpenWrite("test.txt");\n        fil.Write(bit,0,bit.Length);\n    }	0
2597899	2597867	converting string euler number to int in c#	string s = "6.21129e+006";\ndouble d = Double.Parse(s);\nConsole.WriteLine(s);\n\nint i = (int)d;\nConsole.WriteLine(i);	0
19276083	19275867	Is there a reason to use &= rather than just = on a boolean?	bool result = FirstCheck();\nresult &= SecondCheck();\nAssert(result);	0
16840829	16840503	How to compare 2 strings and find the difference in percentage?	void Main()\n{\n    string str1 = "?? ??d f?ks ?z h??g?i";\n    string str2 = "??t ?t foks ?n ?? s?n ?e?i";\n    Console.WriteLine(StringCompare(str1,str2)); //34.6153846153846\n    Console.WriteLine(StringCompare("same","same")); //100\n    Console.WriteLine(StringCompare("","")); //100\n    Console.WriteLine(StringCompare("","abcd")); //0  \n}\n\nstatic double StringCompare(string a, string b)\n{\n    if (a == b) //Same string, no iteration needed.\n        return 100;\n    if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not\n    {\n        return 0;\n    }\n    double maxLen = a.Length > b.Length ? a.Length: b.Length;\n    int minLen = a.Length < b.Length ? a.Length: b.Length;\n    int sameCharAtIndex = 0;\n    for (int i = 0; i < minLen; i++) //Compare char by char\n    {\n        if (a[i] == b[i])\n        {\n            sameCharAtIndex++;\n        }\n    }\n    return sameCharAtIndex / maxLen * 100;\n}	0
15681831	15681809	Copying object to another object but remove certain properties Windows Phone 8	public class B\n{\n    public B(A a)\n    {\n        IsResizeCancel = a.IsResizeCancel;\n        MaxSliderValue = a.MaxSliderValue;\n    }\n    public bool IsResizeCancel { get; set; }\n    public double MaxSliderValue { get; set; }\n}	0
3097715	857244	How can I access DataGridRow from a textbox on that row?	public void txtPrice_TextChanged(object sender, EventArgs e)\n{\n    TextBox txtPrice = (TextBox)sender;\n    DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;\n    markRows(myItem, true);\n}\n\npublic void markRows(DataGridItem myItem, bool toSave)\n{\n    // Prepeare to save this record?\n    CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");\n    thisSave.Checked = toSave;\n    // Establish the row's position in the table\n    Label sNo = (Label)myItem.FindControl("SNo");\n    int rowNum = Convert.ToInt32(sNo.Text) - 1;\n    CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");\n\n    // Update background color on the row to remove/add highlight \n    if (rowSave.Checked == true)\n        grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;\n    else\n    {\n        Color bgBlue = Color.FromArgb(212, 231, 247);\n        grid.Items[rowNum].BackColor = bgBlue;\n        // some code here to refresh data from table?\n    }\n}	0
30502875	30501209	Custom Messagebox not showing in windows phone 8	private async void Save_Click(object sender, EventArgs e)\n{\n    if (!string.IsNullOrEmpty(txtSignby.Text.ToString()) && MyIP.Strokes != null && MyIP.Strokes.Count > 0)\n    {\n        WriteableBitmap wbBitmap = new WriteableBitmap(MyIP, new TranslateTransform());\n        EditableImage eiImage = new EditableImage(wbBitmap.PixelWidth, wbBitmap.PixelHeight);\n\n        cmd = new CustomMessageBox()\n        {\n            Caption = "SAVING....",\n            Message = "Please wait...."\n        };\n        cmd.Show();\n\n        await Task.Delay(10);\n\n        //some code\n        //some code\n        //some code\n        //some code\n\n        cmd.Dismiss();\n\n    }\n}	0
20825323	20825197	Sending emails to multiple adresses using MvcMailer	public virtual MvcMailMessage AdminNotification()\n{\n    string[] userRoles = Roles.GetUsersInRole("Admin");\n\n    IEnumerable<string> emails =\n        userRoles.Select(userName => Membership.GetUser(userName, false))\n                 .Select(user => user.Email);\n\n    var message = new MvcMailMessage {Subject = "AdminNotification", ViewName = "AdminNotification"};\n\n    foreach (string email in emails)\n    {\n        message.To.Add(email);\n    }\n    return message;\n}	0
20529760	20529734	Return list of string from list nested in a list	Counties.SelectMany(c => c.Cities).Select(c => c.CityName)	0
33401558	33401372	JSON deserialize variable number of properties	public class Template\n{\n    public string Name { get; set; }\n    public string RuleName { get; set; }\n    public Dictionary<string,Zone> Zones { get; set; }\n}	0
32248113	32248024	Export to excel from observablecollection C#	private void btnExportExcel_Click(object sender, RoutedEventArgs e)\n{\n    var exporter = new ExportToExcel<T_P>()\n    {\n       dataToPrint = new List<T_P>(_observableCollection);\n    };\n\n}	0
6610790	6609009	decoupling credit card wait window from creditcard reader	DCardArrived _evnt = OnCardArrived; /*presumably declared event*/\n         Delegate[] _iList;\n         DCardArrived _Invoker;\n         if (_evnt != null)\n         {\n             _iList = _evnt.GetInvocationList();\n             for (int i = 0; i < _iList.Length; i++)\n             {\n                  //You could also use BeginInvoke\n                 _Invoker = (DCardArrived)_iList[i];\n                 _Invoker.Invoke(this/*Sender*/,CardData/*class that inherits EventArgs containing the data either informing just the window to close or not or with the data for further processing*/);\n             }\n         }	0
29243471	29237265	Serializing a complex object with BinaryFormatter	NHibernateUtil.Initialize(yourObject);\nNHibernateUtil.Initialize(yourObject.List1);\nNHibernateUtil.Initialize(yourObject.OtherList);\n...etc...\nSerializeObject(yourObject);	0
30317774	30317086	Multi Line Text Area In Editor ExtJs	editor: {\n            xtype: 'textareafield',\n            allowblank: false,\n            maxLength: 165,\n            enforceMaxLength: true,\n            height: 100,\n            grow: true,\n            completeOnEnter: false,\n            enableKeyEvents: true, //Listen to keyevents\n            listeners: {\n                keydown: function(field, e) {\n                    if (e.getKey() == e.ENTER) {\n                        e.stopEvent(); // Stop event propagation\n                    }\n                }\n            }\n        }	0
23664887	23417328	ZeroMQ CLRZMQ - Polling a socket	public static void RaiseOnTimeout(Socket sock, TimeSpan timeout)\n{\n    List<PollItem> pollItemsList = new List<PollItem>();\n    PollItem pollItem = sock.CreatePollItem(IOMultiPlex.POLLIN);\n    pollItemsList.Add(pollItem);\n\n    int numReplies = Context.Poller(pollItemsList.ToArray(), timeout.Value.Ticks * 10);\n\n    if (numReplies == 0)\n    {\n        throw new TimeoutException();\n    }\n}	0
12192950	12192923	How to add List and Dictionary to a List as elements	List<IEnumerable>	0
21784797	21748629	How to use the Dispatcher to run code on UI from within a resuming event handler in a windows store app	/* Set the new handler. */\n  Application.Current.Resuming += (s, e) =>\n  {\n    /* Start a task to wait for UI. */\n    Task.Factory.StartNew(() =>\n    {\n      Windows.Foundation.IAsyncAction ThreadPoolWorkItem = Windows.System.Threading.ThreadPool.RunAsync(\n      (source) =>\n      {\n        Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,\n         () =>\n         {\n           /* Do something on UI thread. */\n         });\n      });\n    });\n  };	0
29469297	29457957	Bind Deedle Frame to DataGridView	dgv.DataSource = dfObjects.ToDataTable(new List<string>() { "Index" });	0
23805209	23804723	How can I write a conditional without any conditional statements or operators?	String.Join	0
13385609	13385450	Multiple Select and Join with LINQ and Lambda	from neg in db.san_negocio\njoin prop in san_proposta\n    on neg.imovel.id equals prop.imovel_id\njoin imo in san_imovel\n    on neg.imovel_id = imo.imovel_id\nwhere neg.credenciadacaptadora_id == null && \n    neg.credenciadavendedora_id == null &&\n    prop.statusproposta_id == 2\nselect new {\n    ImovelID = neg.imovel_id,\n    NegocioID = neg.negocio_id,\n    Imo_CredenciadaID = imo.credenciada_id,\n    PropostaID = prop.proposta_id\n    Prop_CredenciadaID = prop.credenciada_id\n};	0
23419227	23419134	Finding deltatime in C# using stopwatch	Stopwatch timer = Stopwatch.StartNew();\nTimeSpan dt = TimeSpan.FromSeconds(1.0/50.0);\nTimeSpan elapsedTime = TimeSpan.Zero;\nwhile(window.IsOpen())\n{\n    timer.Restart();\n    elapsedTime = timer.Elapsed;\n    while(elapsedTime > dt)\n    {\n        window.DispatchEvents();\n        elapsedTime -= dt;\n        gameObject.FixedUpdate(dt.TotalMilliseconds);\n    }\n }	0
5123907	5123876	Retrieving Assembly version from AssemblyInfo.cs file with Regex	int.TryParse(match.Groups[1].Value, ...)\nint.TryParse(match.Groups[2].Value, ...)\nint.TryParse(match.Groups[3].Value, ...)\nint.TryParse(match.Groups[4].Value, ...)	0
8314190	8313704	FileUpload get file extension	using System.IO;	0
2148287	2148271	.net Format decimal to two places or a whole number	decimal num = 10.11M;\n\nConsole.WriteLine( num.ToString( "0.##" ) );	0
15451839	15451799	Insert into select query	INSERT INTO LMNormal (upc, cert_code, description, ..., unitofmeasure)\nSELECT upc, cert_code, description, ..., unitofmeasure\nFROM   products \nWHERE  (modified >= @now) and (advertised = @false)	0
27863291	27863229	C# error in switch statement using an 2d array variable	string[,] myArray = new string[2, 2];\n...\nmyArray =  new string[2,2] { { "1", "1" }, { "1", "1" } };	0
21533775	21504342	Single table hierarchical data with EF Database First	var query = items.Where(i => i.userid == userId).GroupBy(i => i.originalid).Select(i => new\n                    {\n                        LatestItem = i.OrderByDescending(x => x.id).First(),\n                        History = i.OrderByDescending(x => x.id).Skip(1).Select(x => new\n                        {\n                            id = x.id,\n                            originalid = x.originalid\n                        }).ToList()\n                    }).ToList();	0
32681196	32653094	How to monitor memory alocation from code	private float GetActuratePrivateWorkingSet(Process currentProcess)\n    {\n        // get the physical mem usage for this process\n        var pc = new PerformanceCounter("Process", "Working Set - Private", currentProcess.ProcessName, true);\n        pc.NextValue();\n        Thread.Sleep(1000);\n        var privateWorkingSet = pc.NextValue()/ 1024/1024;\n        return privateWorkingSet;\n    }	0
21109410	21060362	Moving from Ninject.MVC3 to StructureMap	ObjectFactory.Initialize(config => {\n    config.For<ISessionFactory>().Singleton().Use(() => \n      Fluently.Configure()\n        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =>\n        c.FromConnectionStringWithKey("DefaultConnection")))\n        .Cache(c => c.UseQueryCache().ProviderClass<HashtableCacheProvider>())\n        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Post>())\n        .BuildConfiguration()\n        .BuildSessionFactory()));\n    config.For<ISession>().HttpContextScoped()\n      .Use(c => c.GetInstance<ISessionFactory>().OpenSession());\n});	0
2407873	2406972	Problem in passing arrays from C# to C++	[DllImport("your_dll")]\npublic extern void IterateCL([In, MarshalAs(UnmanagedType.LPArray)] int[] arr1, [Out, MarshalAs(UnmanagedType.LPArray)] int[] arr2);	0
24957326	24957227	Removing a subset from a SuperSet based on a criteria using LINQ	superset.RemoveAll(x => subset.Select(y => y.ID).Contains(x.ID));	0
27164037	27163953	Entered correct data but log in keeps failing c# asp.net	if (numofUsers < 1)\n    {\n        //user exists, check if the passwords match\n        query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);	0
31882126	31880336	CheckBoxList Validation	public void Page_Load(Object sender, EventArgs e)\n{\n   // Get items from database table 1\n    var items1 = GetTable1Data();\n    foreach(var item in items1)\n    {\n       this.checkboxList1.Items.Add( new ListItem(item.DisplayMember, item.ValueMember));\n    }\n\n    // Get items from database table 2\n    var items2 = GetTable2Data();\n    foreach(var item in items2)\n    {\n       this.checkboxList1.Items.Add( new ListItem(item.DisplayMember, item.ValueMember));\n    }\n}	0
9504655	9504584	Overriding methods with actions as parameters	Action<T, T>	0
28159828	28159796	Seting value of a property for an item causes NullReferenceException	Customer x = new Customer();\nx.ID   = "MyId";\nx.AccountName = "HelloAccount";\nx.BillToContact = new BillToContact();\nx.BillToContact.FirstName = "Jim";\nx.BillToContact.LastName  = "Bob";	0
29749052	29741260	Alert Window - TakeScreenshot - Selenium C#	driver.SwitchTo().Alert().Accept();	0
22386740	17746552	How to disable multiple column sorting on a wpf DataGrid?	private void ResultsDataGrid_Sorting(object sender, DataGridSortingEventArgs e)\n{\n    if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))\n    {\n        e.Handled = true;\n    }\n}	0
32461699	32406862	How to extract an array of values from a single DataRow element?	User dcUser = new User();\nint[] anSystemIDs = (int[])drUser["system_ids"];\nstring strSystemIDs = "";\ndcUser.UserID = Convert.ToInt32(drUser["user_id"].ToString());\nfor (int i = 0; i < anSystemIDs.Length ; i++)\n{\n    strSystemIDs += anSystemIDs[i].ToString() + ", ";\n}\ndcUser.SystemIDs = strSystemIDs.Substring(0, strSystemIDs.Length - 2);	0
31657843	31657387	Programs listening to mouse don't react to programmatical mouse movement	Cursor.Position	0
17794007	17793202	How can you programatically disable Windows Update in XP using C#	ServiceController sc = new ServiceController("wuauserv");\n        try\n        {\n            if (sc != null && sc.Status == ServiceControllerStatus.Running)\n            {\n                sc.Stop();\n            }\n            sc.WaitForStatus(ServiceControllerStatus.Stopped);\n            sc.Close();\n        }\n        catch (Exception ex)\n        {                \n            Console.WriteLine(ex.Message);\n        }	0
12595720	12595693	How do I determine type of Dictionary comparer in C#?	myDict.Comparer == StringComparer.OrdinalIgnoreCase	0
17224867	17224369	How I refresh a HttpWebRequest object on Windows Phone	Random _rand = new Random();\n\nprivate async Button_Click(object sender, RoutedEventArgs e)\n{\n\n   CookieContainer cookie = new CookieContainer();\n   var result = await this.requestUrl(this.urlBase + "getRandomNum&rubbish=" + _rand.Next(), cookie);\n   ...\n}	0
18609910	18609609	How to navigate to Windows Phone 8 start screen using C#	Application.Current.Terminate();	0
8800340	8800216	How to get file physical location on hard drive	using(var fs = new System.IO.FileStream(@"m:\delme.zip", \n                                        FileMode.Open,\n                                        FileAccess.Write,\n                                        FileShare.None))\n{\n    var zeros = new byte[fs.Length];\n\n    fs.Write(zeros, 0, zeros.Length);       \n}	0
4996771	4987438	RabbitMQ C# connection trouble when using a username and password	ConnectionFactory factory = new ConnectionFactory();\nfactory.UserName = "user";\nfactory.Password = "password";\nfactory.VirtualHost = "/";\nfactory.Protocol = Protocols.FromEnvironment();\nfactory.HostName = "192.168.0.12";\nfactory.Port = AmqpTcpEndpoint.UseDefaultPort;\nIConnection conn = factory.CreateConnection();	0
16533306	16533285	How do I make a static class thread-safe?	public static class Logger\n{\n    private static readonly string LOG_FILENAME = "logfile.txt";\n    private static readonly string LOG_FOLDER = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name");\n    private static readonly string LOG_FULLPATH = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "App name", LOG_FILENAME);\n\n    private static Object theLock=new Object();\n\n    public static void LogMessageToFile(string msg)\n    {\n        msg = string.Format("{0:G}: {1}{2}", DateTime.Now, msg, Environment.NewLine);\n        lock (theLock)\n        {\n            File.AppendAllText(LOG_FULLPATH, msg);\n        }\n    }\n}	0
15283916	15283810	How to write to separate columns in csv	foreach (var i in valueArray)\n{\n   if (i.ToString() == "\n")\n   {\n      sw.Write(sw.NewLine);\n   }\n   else\n   {\n      sw.Write(i.ToString() + ",");\n   }\n}	0
26471044	26469190	Calling an Async Method, from within an Web Method and getting a return	[System.Web.Services.WebMethod]\npublic static string Find_Games(string user)\n{\n    using (var client = new System.Net.WebClient())\n    {\n        return client.DownloadString(String.Concat("http://api.steampowered.com/", "IPlayerService/GetOwnedGames/v0001/?key=my_steam_key&steamid=my_steam_id&include_appinfo=1&include_played_free_games=1&format=json"));\n    }\n}	0
16315946	16315753	While loop jumps unexpectedly while reading XML	using System;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    internal class Program\n    {\n        static void Main()\n        {\n            string xml =\n@"<Item>\n    <GUID>9A4FA56F-EAA0-49AF-B7F0-8CA09EA39167</GUID>\n    <Type>button</Type>\n    <Title>Save</Title>\n    <Value>submit</Value>\n    <Name>btnsave</Name>\n    <MaxLen>5</MaxLen>\n</Item>";\n            XElement elem = XElement.Parse(xml);\n\n            Guid GuidXml = Guid.Parse(elem.Element("GUID").Value);\n            Console.WriteLine(GuidXml);\n\n            string TypeXml = elem.Element("Type").Value;\n            Console.WriteLine(TypeXml);\n\n            string NameXml = elem.Element("Name").Value;\n            Console.WriteLine(NameXml);\n\n            string TitleXml = elem.Element("Title").Value;\n            Console.WriteLine(TitleXml);\n        }\n    }\n}	0
7469892	7468913	C# Get schema information when validating xml	List<XmlElement> errorElements = new List<XmlElement>();\n\n            serializedObject.Validate((x, y) =>\n            {\n                var exception = (y.Exception as XmlSchemaValidationException);\n\n                if (exception != null)\n                {\n                    var element = (exception.SourceObject as XmlElement);\n\n                    if (element != null)\n                        errorElements.Add(new XmlValidationError(element));\n                }\n\n            });	0
4254707	4254520	WPF Datagrid binding to xml	ItemsSource="{Binding Source={StaticResource myXMLDoc}, XPath=row}}" //bind "row" elements to your control	0
22744258	22744185	How to Change C# Code	using num = System.Int32;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            num a = 1 + 1;\n        }\n    }\n}	0
19525779	19525408	easiest way to add title row to log file	if(!System.IO.File.Exists(test.File1)) //if the file doesn't exist\n{   //insert your header at the top\n    File.AppendAllText(test.File1,"My Header Line")\n}	0
4281751	4276077	How to replace an Paragraph's text using OpenXML Sdk	string modifiedString = Regex.Replace(currentParagraph.InnerText, currentString, reusableContentString);\ncurrentParagraph.RemoveAllChildren<Run>();\ncurrentParagraph.AppendChild<Run>(new Run(new Text(modifiedString)));	0
20743902	20743795	Wait for a method to return true	while (!B ()) { }\nvar x = "test";	0
625180	625173	Submit by pressing enter in a windows form	Form.AcceptButton	0
20003746	20003257	How to remove Folders whose contents are empty	private void KillFolders()\n{\n    DateTime to_date = DateTime.Now.AddDays(-1);\n    List<string> paths = Directory.EnumerateDirectories(@"C:\MotionWise\Catalogue\" + Shared.ActiveMac, "*", SearchOption.TopDirectoryOnly)\n        .Where(path =>\n        {\n            DateTime lastWriteTime = File.GetLastWriteTime(path);\n            return lastWriteTime <= to_date;\n        })\n        .ToList();\n\n    foreach (var path in paths))\n    {\n        cleanDirs(path);\n    }\n}\n\nprivate static void cleanDirs(string startLocation)\n{\n    foreach (var directory in Directory.GetDirectories(startLocation))\n    {\n        cleanDirs(directory);\n        if (Directory.GetFiles(directory).Length == 0 && Directory.GetDirectories(directory).Length == 0)\n        {\n            Directory.Delete(directory, false);\n        }\n    }\n}	0
386163	385688	What's a good name for an Enum for Yes & No values	public enum Married\n{\n    YES,\n    NO\n}	0
28148705	28148128	Move large amount of data from old database to new database using Entity Framework 5	_context = new SomeContext();	0
29529174	29519449	How to create a clone object in windows 8.1 universal app?	using System.Reflection;\n\npublic class Test\n{\n  public string Name { get; set; }\n  public int Id { get; set; }\n}\n\nvoid DoClone()\n{\n  var o = new Test { Name = "Fred", Id = 42 };\n\n  Type t = o.GetType();\n  var properties = t.GetTypeInfo().DeclaredProperties;\n  var p = t.GetTypeInfo().DeclaredConstructors.FirstOrDefault().Invoke(null);\n\n  foreach (PropertyInfo pi in properties)\n  {\n    if (pi.CanWrite)\n      pi.SetValue(p, pi.GetValue(o, null), null);\n  }\n\n  dynamic x = p;\n  // Important: Can't use dynamic objects inside WriteLine call\n  // So have to create temporary string\n  String s = x.Name + ": " + x.Id;\n  Debug.WriteLine(s);\n}	0
20965242	20949326	Could not find installable ISAM while filling data in DataSet	var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;';", saved_FileName);	0
8277180	8277147	How to connect to a mysql database in C# and mimic the SELECT, UPDATE and INSERT functions	private void button1_Click(object sender, System.EventArgs e)\n{\n  string MyConString = "SERVER=localhost;" +\n                       "DATABASE=mydatabase;" +\n                       "UID=testuser;" +\n                       "PASSWORD=testpassword;";\n  MySqlConnection connection = new MySqlConnection(MyConString);\n  MySqlCommand command = connection.CreateCommand();\n  MySqlDataReader Reader;\n  command.CommandText = "select * from mycustomers";\n  connection.Open();\n  Reader = command.ExecuteReader();\n  while (Reader.Read())\n  {\n    string thisrow = "";\n    for (int i= 0;i<Reader.FieldCount;i++)\n      thisrow+=Reader.GetValue(i).ToString() + ",";\n    listBox1.Items.Add(thisrow);\n  }\n  connection.Close();\n}	0
3727568	3612181	Merge multiple <Body> (xml) word documents to 1 document	WordProcessingDocument.Create("path_and_name_with_.docx").MainDocumentPart.Document.append(yourBodyList);	0
13824277	13823965	Find Position of an Item in a List- First, Last	public int Add(FruitTrees newItem)\n{\n    if (First == null)\n    return Add_Initialize(newItem);\n\n    FruitTrees item = First;\n    while (item.Next != null)\n    {\n        item = item.Next;\n    }\n\n    item.Next = newItem;\n    Last = newItem;\n    return size++;\n}	0
4235587	4235552	How to read columns and rows with C#?	string myName = "Foo Bar";\nusing (MySqlConnection conn = new MySqlConnection("your connection string here"))\n{\n    using (MySqlCommand cmd = conn.CreateCommand())\n    {\n        conn.Open();\n        cmd.CommandText = @"SELECT * FROM players WHERE name = ?Name;";\n        cmd.Parameters.AddWithValue("Name", myName);\n        MySqlDataReader Reader = cmd.ExecuteReader();\n        if (!Reader.HasRows) return;\n        while (Reader.Read())\n        {\n            Console.WriteLine(GetDBString("column1", Reader);\n            Console.WriteLine(GetDBString("column2", Reader);\n        }\n        Reader.Close();\n        conn.Close();\n    }\n}\n\nprivate string GetDBString(string SqlFieldName, MySqlDataReader Reader)\n{\n    return Reader[SqlFieldName].Equals(DBNull.Value) ? String.Empty : Reader.GetString(SqlFieldName);\n}	0
17194792	17194554	How to determine if MemoryStream is fixed size?	static bool IsExpandable(MemoryStream stream)\n{\n    return (bool)typeof(MemoryStream)\n        .GetField("_expandable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)\n        .GetValue(stream);\n}	0
865226	865205	adding items to an arraylist when a button in gridview is clicked	public partial class _Default : System.Web.UI.Page\n{\n    ArrayList array;\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if(Session["array"] == null)\n        {\n            array = new ArrayList();\n            Session.Add("array", array);\n        }\n        else\n            array = Session["array"] as ArrayList;\n        GridView1.DataSource = array; \n        GridView1.DataBind(); //Edit 2\n    }\n\n    protected void Button1_Click(object sender, EventArgs e)\n    {\n        array.Add(DateTime.Now);\n    }\n}	0
32592007	32590887	Global Thread in WPF C# Application	public MainWindow()\n    {\n        InitializeComponent();\n\n        Task t = Task.Factory.StartNew(() =>\n        {\n            Console.WriteLine("Executing long running thread");\n            int i = 0;\n            while (true)\n            {\n                //update textbox on UI\n                Dispatcher.Invoke(() => textBox.Text = i.ToString());\n                Thread.Sleep(TimeSpan.FromSeconds(5));\n                i++;\n            }\n\n        }, TaskCreationOptions.LongRunning);\n    }	0
2077878	2077870	How to load a C# dll in python?	[ComVisible(true)]	0
15701120	15693033	Offset between colliding objects in Farseer Physics	var ball = BodyFactory.CreateCircle(world, ConvertUnits.ToSimUnits(w / 2), 1);	0
32242847	32242752	c#.net How can I removed duplicate rows from a DATASET	var newtable = oldDS.Tables[0].AsEnumberable().Select(dr => dr).Distinct();\n\noldDS.Tables.Clear();\noldDS.Tables.Add(newtable.CopyToDataTable());	0
21649418	21646224	how to take the immideately selected value of Dropdownlist?	if (!Page.IsPostBack)\n    {\n\n        ddwcategory.DataBind();\n        ddwsubcat.DataBind();\n\n    }\n    else\n    {\n        if (ddwsubcat.Items.Count <= 1)\n        {\n            ddwsubcat.SelectedIndex = -1;\n            ddwsubcat.DataBind();\n        }\n      //  Label1.Text = ddwsubcat.SelectedValue;\n        //ddwsubcat.DataBind();\n    }\n    String subcat = ddwsubcat.SelectedValue;	0
4801391	4801215	How do I use an XmlSerializer to deserialize an object that might be of a base or derived class without knowing the type beforehand?	public class RootElementClass\n{\n    [XmlElement(ElementName = "Derived1", Type = typeof(Derived1BaseType))]\n    [XmlElement(ElementName = "Derived2", Type = typeof(Derived2BaseType))]\n    [XmlElement(ElementName = "Derived3", Type = typeof(Derived3BaseType))]\n    public BaseType MyProperty { get; set; }\n}\n\npublic class BaseType { }\npublic class Derived1BaseType : BaseType { }\npublic class Derived2BaseType : BaseType { }\npublic class Derived3BaseType : BaseType { }	0
28523220	28523197	how to call 2 javascript on client click event in asp.net	return OnClientClick="return validate_1() && validate_2();"	0
31983548	31983188	Blocking anonymous access by default in ASP .NET 5	using Microsoft.AspNet.Mvc;\nusing Microsoft.AspNet.Authorization;\n\nservices.ConfigureMvc(options =>\n{\n   options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));\n});	0
4245259	4245137	Using a c# handler to serve up wav files cuts audio short (only a couple of seconds)	context.Response.ClearContent();\ncontext.Response.ClearHeaders();\ncontext.Response.ContentType = "audio/x-wav";\nbyte[] byteArray = File.ReadAllBytes(fileName);\ncontext.Response.OutputStream.Write(byteArray, 0, byteArray.Length);	0
12902758	12894406	Inflating a compressed byte array in WinRT	using (DeflateStream stream = new DeflateStream(new MemoryStream(compressedBytes, 2, compressedBytes.Length - 2), CompressionMode.Decompress))	0
16544344	16543727	Extract json data from string using regex	// Define the Regular Expression, including the "data="\n// but put the latter part (the part we want) in its own group\nRegex regex = new Regex(\n    @"data=(\[{.*}\])",\n    RegexOptions.Multiline\n);\n\n// Run the regular expression on the input string\nMatch match = regex.Match(input);\n\n// Now, if we've got a match, grab the first group from it\nif (match.Success)\n{\n    // Now get our JSON string\n    string jsonString = match.Groups[1].Value;\n\n    // Now do whatever you need to do (e.g. de-serialise the JSON)\n    ...\n\n    }\n}	0
7754329	7754210	C# List all Folders on a SQL reporting server using ReportingServices	var rs = new ReportingService2005SoapClient();\n\n    CatalogItem[] reports;\n\n    string reportPath = "/ReportPath";\n\n    rs.ListChildren(reportPath, true, out reports);\n\n    foreach (var report in reports)\n    {\n        if (report.Type == ItemTypeEnum.Folder)\n        {\n            // Do something\n        }\n    }	0
5148233	5147838	How To Do Validation in Silverlight/RIA When A Call To Database Is Required?	public static partial class FooRules\n{\n  public static ValidationResult FooIDUnique(Foo foo, ValidationContext context)\n  {\n    bool check = false;\n\n    using (FooEntities fe = new FooEntities())\n    { \n      check = fe.Foo.Any(f => f.FooId == foo.fooId); \n    }\n    if (!check)\n      return ValidationResult.Success;\n\n    return new ValidationResult("FooID error msg,", new string[] { "FooID" });\n  }\n}	0
17050365	17050277	Using regex function to manipulate string in c#	Regex.Replace(text, "jsessionid=[^\\?]+","")	0
11639841	11639708	Retrieving check box name (value) from a table in SQL database into ascx file	protected void Page_Load(object sender, EventArgs e)\n{\n    // do not rebind the list if this is a postback; user input would be lost \n    if (this.IsPostBack)\n    {\n        return;\n    }\n    CheckBoxList1.DataSource = GetValues();\n    CheckBoxList1.DataBind();\n}\n\nprivate string[] GetValues()\n{\n    // get data from database, with 'select <columnName> from Importtabs'\n    // populate array\n    // return values as a string[]\n}	0
33901217	33901106	Double to String with less decimals as possible and at least four	double a = 21.879653;  \n    double b = 21.000000;   \n    double c = 21.020000;   \n\n    Console.WriteLine(a.ToString("#0.####"));\n    Console.WriteLine(b.ToString("#0.####"));\n    Console.WriteLine(c.ToString("#0.####"));	0
3801836	3801795	how to set text property assigned to the control created dynamically usiong reflection?-C#	PropertyInfo piInstance = \n            typeof(Example).GetProperty("InstanceProperty");\n        piInstance.SetValue(exam, 37, null);	0
11785089	11784973	When/How to dispose of a Web Browser Control after Show Print Preview Dialog	void wbForPrinting_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    // Print the document now that it is fully loaded.\n    ((WebBrowser)sender).ShowPrintPreviewDialog();\n    // Dispose the WebBrowser now that the task is complete. \n    ((WebBrowser)sender).Dispose();\n}	0
15872721	15863330	Scheduling using eventwaithandle	// Summary:\n    //     Blocks the current thread until the current System.Threading.WaitHandle receives\n    //     a signal, using a 32-bit signed integer to specify the time interval.\n    //\n    // SNIP SNIP\n    //\n    // Returns:\n    //     true if the current instance receives a signal; otherwise, false.\n    //\n    // SNIP SNIP\n    public virtual bool WaitOne(int millisecondsTimeout);	0
13008164	13007799	Generating a personal id for each user	public string GetPersonalId (int n)\n{\n    char letter1 = (char)('A' + ((n / 10 / 26 / 26) % 26));\n    char letter2 = (char)('A' + ((n / 10 / 26) % 26));\n    char digit1 = (char)('0' + ((n / 10) % 10));\n    char digit2 = (char)('0' + ((n) % 10));\n\n    string dateString = string.Format("{0:yyyyMMdd}", DateTime.Today)\n        .Insert(6, " ")\n        .Insert(3, " ");\n\n    return string.Format("{0}{1} {2}{3} {4}",\n        letter1, letter2, digit1, digit2, dateString);\n}\n\npublic GetNextSequenceForToday()\n{\n    SqlCommand query = new SqlCommand()\n    query.CommandText =\n       "SELECT COUNT(*) FROM [Users] " +\n       "WHERE [Date] >= @today AND [Date] < @tomorrow";\n    query.Parameters.Add("@today", DateTime.Today);\n    query.Parameters.Add("@tomorrow", DateTime.Today.AddDays(1));\n\n    int count = Convert.ToInt32(query.ExecuteScalar());\n\n    return count + 1;\n}	0
30729785	30684608	Changing Type at Runtime with GenericTypeArgument	IList targetList = (IList)listPropertyInfo.GetValue(item);\nType foo = targetList.GetType().GenericTypeArguments.Single();\nType unboundGenericType = typeof(READ<>);\nType boundGenericType = unboundGenericType.MakeGenericType(foo);\nMethodInfo doSomethingMethod = boundGenericType.GetMethod("trigger");\nobject instance = Activator.CreateInstance(boundGenericType);\ndoSomethingMethod.Invoke(instance, new object[] { targetList, f, properties });	0
20353343	20353115	hyperlink in gridview with procedure	void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n  {\n\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n      // Display the company name in italics.\n      e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";\n\n    }\n\n  }	0
30591936	30589887	Remove previous ComboBox SelectedItem from its next appearance bind through List	var Item=combobox.selectedItem as x;\nif(LstProducts.Contains(Item))\nLstProducts.remove(Item);	0
10054724	10054695	How to select Linq elements using FROM..SELECT based on conditions?	var dataSet = from r in something.Elements("chapter")\n               select new dictChapter{\n                   Name = r.Attribute("Name").Value,\n                   Desc1 = ShowDesc1 ? r.Attribute("Description1").Value : String.Empty,\n                   Desc2 = ShowDesc2 ? r.Attribute("Description2").Value : String.Empty,\n                   Desc3 = ShowDesc3 ? r.Attribute("Description3").Value : String.Empty,\n\n               };	0
22193082	22192888	how to customize json feed C#	return serializer.Serialize(new { contacts = rows } );	0
14823809	14823713	Efficient Rolling Max and Min Window	public static class AscendingMinima\n{\n    private struct MinimaValue\n    {\n        public int RemoveIndex { get; set; }\n        public double Value { get; set; }\n    }\n\n    public static double[] GetMin(this double[] input, int window)\n    {\n        var queue = new Deque<MinimaValue>();\n        var result = new double[input.Length];\n\n        for (int i = 0; i < input.Length; i++)\n        {\n            var val = input[i];\n\n            // Note: in Nito.Deque, queue[0] is the front\n            while (queue.Count > 0 && i >= queue[0].RemoveIndex)\n                queue.RemoveFromFront();\n\n            while (queue.Count > 0 && queue[queue.Count - 1].Value >= val)\n                queue.RemoveFromBack();\n\n            queue.AddToBack(new MinimaValue{RemoveIndex = i + window, Value = val });\n\n            result[i] = queue[0].Value;\n        }\n\n        return result;\n    }\n}	0
31183261	31181606	C# WP8.1:Convert image from gallery to base64	public async Task<string> ImageToBase64(StorageFile MyImageFile)\n    {\n        Stream ms = await MyImageFile.OpenStreamForReadAsync();\n        byte[] imageBytes = new byte[(int)ms.Length];\n        ms.Read(imageBytes, 0, (int)ms.Length);\n        return Convert.ToBase64String(imageBytes);\n    }	0
19410096	19409369	Assignation of string with accents to another string, replaces them with "&amp;#243;"	public string Document\n  {\n    get\n    {\n      return HttpUtility.HtmlEncode(txtDocument.Text);\n    }\n    set\n    {\n      txtDocument.Text = HttpUtility.HtmlEncode(value);\n    }\n  }	0
25206387	25206278	ASP.NET format string date	airportItems.ContractReceived_F = dataReader.GetDateTime(1).ToString("yyyy-MM-dd");	0
15101355	15098733	Query executes in 4 seconds directly in SQL Server but takes > 30 seconds in ASP.NET?	CREATE PROCEDURE dbo.MyProcedure\n(\n    @Param1 INT\n)\nAS\n\ndeclare @MyParam1 INT\nset @MyParam1 = @Param1\n\nSELECT * FROM dbo.MyTable WHERE ColumnName = @MyParam1 \n\nGO	0
18081389	18081090	Grouping DateTime by arbitrary time intervals	TimeSpan offset = startTime.TimeOfDay;\nTimeSpan interval = TimeSpan.FromMinutes(45);\nvar selected = from date in item.Dates\n           group date by ((date.Ticks - offset.Ticks) / interval.Ticks) into g\n           select g;	0
12889217	12889130	How can I check an array of strings against an Enum and return the highest value that's found?	public static RoleType GetMaxRole()\n{\n    var userRoles = Roles.GetRolesForUser();\n    var maxRole = userRoles.Max(x => (RoleType)Enum.Parse(typeof(RoleType), x));\n    return maxRole;\n}	0
7321295	7321158	How to check navigation status on WP7	private void TrackNavigationStatus()\n    {\n        var root = Application.Current.RootVisual as PhoneApplicationFrame;\n\n        root.Navigating += (s, e) => _isNavigating = true;\n        root.Navigated += (s, e) => _isNavigating = false;\n        root.NavigationFailed += (s, e) => _isNavigating = false;\n        root.NavigationStopped += (s, e) => _isNavigating = false;\n    }	0
14717008	14716671	Binding BindingList<string[]> to datagridview	var Data = new BindingList<object>((\n    from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers \n    where p[2].Equals(item) \n    select new {\n                Val1 = p[0].ToString(), \n                Val2 = p[3].ToString() \n               }).ToList());	0
1762805	1762326	Windows Mobile: how to hide Size property on a Custom Control	public Size Size\n{\n    get { return base.Size; }\n    set { base.Size = value; }\n}	0
15379494	15379438	convert TextReader to XmlReader	XmlReader.Create(TextReader)	0
19678099	19677560	Find MAX Number from a String List with C#	var myStrings = new List<string>();\n            myStrings.Add("abc9");\n            myStrings.Add("abc100");\n            myStrings.Add("abc999");\n            myStrings.Add("abc");\n\n            var maxNumber = "abc" + (from myString in myStrings let value = Regex.Match(myString, @"\d+").Value select Convert.ToInt32(value == string.Empty ? "0" : Regex.Match(myString, @"\d+").Value) + 1).Concat(new[] { 0 }).Max();	0
13736425	13736407	Compare a List<string> to a SQL column value to decide if a list item appears in the column	//I guess you can get the string representation of the column value\nstring value = "/One/Two/Three/Four/"; \nList<string> parameters = new List<string> { "Two", "Three" };\n\nbool result = value.Split('/')\n                   .Intersect(parameters)\n                   .Any();	0
13236447	13233982	Get Sql server's data using smo	using System.Data.SqlClient;\nusing System.IO;\nusing System.Text;\nusing Microsoft.SqlServer.Management.Common;\nusing Microsoft.SqlServer.Management.Smo;\n\nnamespace SqlExporter\n{\nclass Program\n{\nstatic void Main(string[] args)\n{\n    var server = new Server(new ServerConnection {ConnectionString = new SqlConnectionStringBuilder {DataSource = @"LOCALHOST\SQLEXPRESS", IntegratedSecurity = true}.ToString()});\n    server.ConnectionContext.Connect();\n    var database = server.Databases["MyDatabase"];\n    var output = new StringBuilder();\n\n    foreach (Table table in database.Tables)\n    {\n        var scripter = new Scripter(server) {Options = {ScriptData = true}};\n        var script = scripter.EnumScript(new SqlSmoObject[] {table});\n        foreach (var line in script)\n            output.AppendLine(line);\n    }\n    File.WriteAllText(@"D:\MyDatabase.sql", output.ToString());\n}\n}\n}	0
9087706	9086029	How to retrieve all contacts' details from Windows Contacts programmatically?	//using Microsoft.Communications.Contacts;\n\nContactManager theContactManager = new ContactManager();\nforeach (Contact theContact in theContactManager.GetContactCollection())\n{\n    string theLine = theContact.Names[0].FormattedName;\n    foreach(PhoneNumber theNumber in theContact.PhoneNumbers)\n        theLine += "\t" + theNumber.ToString();\n    listBox1.Items.Add(theLine);\n    //Console.WriteLine(theLine); //Uncomment this if on console\n}	0
4212919	4212847	How can I easily parse the returned JSON object for only the information I require?	System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();\n\nSystem.Collections.Generic.Dictionary<string, object> dict = ser.DeserializeObject(@"{""key"":""value""}") as System.Collections.Generic.Dictionary<string, object>;\n\nConsole.WriteLine(dict["key"].ToString());	0
32767687	32767556	Can't make bitmap out of image without absolute URL	string relativePath = @"images\searching.png";\nstring absolutePath1 = Path.GetFullPath(relativePath);\n\n// Warning! Doesn't work with '..\images\searching.png'\nstring absolutePath2 = Path.Combine(Application.StartupPath, relativePath);	0
16040673	16040545	Comparing values of generic objects	if (obj.PropertyType.IsGenericType &&\n    obj.PropertyType.GetGenericTypeDefinition() == typeof (System.Collections.Generic.List<>))\n{\n\n}	0
19201166	19200796	Search date in a txt file	static void Main(string[] args)\n{\n    string filename = @"E:\Practice\C#\MySchedular.txt";\n    string fileContent;\n    Console.WriteLine("Enter the date to search appointment in (dd/mm/yyyy) format");\n    string date = Console.ReadLine();\n\n    using (StreamReader sr = new StreamReader(filename))\n    {\n        fileContent = sr.ReadToEnd();\n    }\n\n    if (fileContent.Contains(date))\n    {\n        string[] apts = fileContent.Split('\n').Where(x => x.Contains(date)).ToArray();\n\n        foreach (string apt in apts)\n        {\n            Console.WriteLine("\n**Appointment Details**");\n            Console.WriteLine("{0}", apt);\n            Console.WriteLine("\n");\n        }\n    }\n    else\n    {\n        Console.WriteLine("No appointment details found for the entered date");\n    }\n    Console.Read();\n}	0
30412292	30411318	JSON.Net parse Facebook Graph JSON for all messages	var arr = ((JArray) obj["posts"]["data"]).Select(e => (string) ((JValue) e["message"]).Value).ToList();	0
3351406	3351132	Is there a better way to run a c++ makefile from a c# project?	cd ..\.. && armbuild	0
25205374	25203912	Convert currency with symbol to decimal	NumberFormat.CurrencyDecimalSeparator = "."	0
24280894	24280203	Pass a reference of string from C# to C++ function	[DllImport("Library.dll", CallingConvention = CallingConvention.Cdecl)]\npublic static extern uint Read([MarshalAs(UnmanagedType.LPStr)] StringBuilder temp);	0
25427903	25427717	Parsing Json String in C#	MethodLogJson m = JsonConvert.DeserializeObject<MethodLogJson>(result);	0
23291620	23291359	Parse xml in c#.net	XmlDocument doc = new XmlDocument();\n             doc.Load(filePath);\n             XmlNode PackagesListNode = doc.SelectSingleNode("/Packages");\n             XmlNodeList Packages = PackagesListNode.SelectNodes("Package");\n             foreach (XmlNode node in Packages)\n             {\n                 TableLoadInstruction instruction = new TableLoadInstruction();\n                 instruction.PackageName = node.SelectSingleNode("PackageName").InnerText;\n                 instruction.Sequence = Convert.ToInt16(node.SelectSingleNode("SequenceID").InnerText);\n                 instruction.AlwaysRun = Convert.ToBoolean(node.SelectSingleNode("AlwaysRun").InnerText);\n                 loadInstructions.Add(instruction);\n             }	0
5080041	5079970	Storing 2-dimensional ints as Readonly/const in separate class whilst keeping non-exposed	private YourType[,] internalArray; // Create and set this up in constructor or elsewhere...\n\n\npublic YourType this[int row, int column]\n{\n     get \n     {\n          return internalArray[row,column];\n     }\n{	0
6333235	6333167	Detecting Ctrl key being held down on application startup?	if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)\n    PromptForMarketSelection();	0
3309725	3309661	C# Convert Byte Array with nulls to string	byte[] yourByteArray = new byte[] { 83, 0, 72, 0, 75, 0, 86, 0 };\n\nstring yourString = Encoding.Unicode.GetString(yourByteArray));\n\nConsole.WriteLine(yourString);    // SHKV	0
13040485	13040427	Update a class property using reflection and the name of the property as a string	propInfo.SetValue(yourinstance, dataModel[propInfo.Name], null);	0
11829683	11829294	Rendered Size of Printed Page using CSS @Page	return new ViewAsPdf()\n    {\n        FileName = "TestView.pdf",\n        PageSize = Size.A3,\n        PageOrientation = Orientation.Landscape,\n        PageMargins = { Left = 0, Right = 0 }, // it's in millimeters\n        PageWidth = 122, // it's in millimeters\n        PageHeight = 44\n    };	0
23143628	23143498	404 error with MapPageRoute() routing a aspx page within a folder	routes.MapPageRoute("ProfilePage",\n                    "Manager/Profile",\n                    "~/Manager/Profile.aspx");	0
24843968	24843872	iterate through two lists	var joined = from ct in CashTransactions\n             join ca in CashAccounts\n                 on ct.CashAccountId equals ca.id\n             select new { CashTransaction = ct, CashAccount = ca };\n\nforeach (var item in joined)\n{\n    //Do whatever with item.CashAccount and item.CashTransaction\n}	0
7797740	7797582	Entity Framework proper use of joining tables?	ctx.Nominations.Join(ctx.Nominees, \n                     n=>n.NominationId, \n                     c=>c.NominationId, \n                     (n,c)=>new {c, n})\n               .Where(x=>x.c.NomineeADUserName == Username)\n               .Select(x.n);	0
4447997	4447967	How to make partial virtual property?	abstract class A {\n    public int Value {get; protected set;}\n}\nclass R : A { }\nclass W : A {\n    new public int Value {\n        get { return base.Value; }\n        set { base.Value = value; }\n    }\n}	0
26425200	26425003	Need to read response of 403 Forbidden with WebClient C#	try\n{\n    request.GetResponse();\n}\ncatch (WebException e)\n{\n    if (e.Response != null)\n        return getResponseBody(e.Response);\n    else\n        throw;\n}	0
19037995	19037261	Image showing only in debug	var path = System.IO.Path.GetFullPath("cover.jpg");\nMyImage.Source = new BitmapImage(new Uri(path, UriKind.Absolute));	0
4271581	4269800	WebBrowser Control in a new thread	private void runBrowserThread(Uri url) {\n    var th = new Thread(() => {\n        var br = new WebBrowser();\n        br.DocumentCompleted += browser_DocumentCompleted;\n        br.Navigate(url);\n        Application.Run();\n    });\n    th.SetApartmentState(ApartmentState.STA);\n    th.Start();\n}\n\nvoid browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n    var br = sender as WebBrowser;\n    if (br.Url == e.Url) {\n        Console.WriteLine("Natigated to {0}", e.Url);\n        Application.ExitThread();   // Stops the thread\n    }\n}	0
7470931	5813427	'Share Publicly' in Google Storage using SharpGs	var acl = o.Acl;\nacl.CleanEntries();\nacl.AddEntry(SharpGs.Acl.AclPermission.FULL_CONTROL, SharpGs.Acl.ScopeType.AllUsers);\nacl.Save();	0
10639642	10639575	Finding a reference to an Object among a list of Objects based on the name of a property	var customClass = listOfCustomClass.Where(c => c.name == "foo").SingleOrDefault();	0
19988012	19987952	How to properly use a QueryString in .NET ASP C#?	if(!IsPostBack && !String.IsNullOrEmpty(Request.QueryString["ProdID"]))\n{\n    ddlProduct.SelectedIndex = ddlProduct.Items.IndexOf(ddlProduct.Items.FindByValue(Request.QueryString["ProdID"]));\n}	0
5054757	5045046	How do I UrlEncode a group match value using Regex.Replace in C#	regex.Replace(text, delegate(Match match)\n{\n    return string.Format(@"src=""/relative/image.ashx?imageUrl={0}""", HttpUtility.UrlEncode(match.Groups[1].Value));\n});	0
12740016	12739914	Stored procedure output parameter returning rounded value	SqlParameter parm = new SqlParameter("@GrandTtl", SqlDbType.Decimal); \nparm.Precision = 19;\nparm.Scale = 3;\nparm.Direction = ParameterDirection.Output; \ncmd.Parameters.Add(parm);	0
25898845	25887682	Add UITextField to UIAlertView in C#	UIAlertView alert = new UIAlertView ();\n\n    alert.AlertViewStyle = UIAlertViewStyle.LoginAndPasswordInput;\n    alert.Title = "Alert";\n    alert.GetTextField (1).SecureTextEntry = false;\n    alert.GetTextField (1).Placeholder = "Input 2";\n    alert.GetTextField (0).Placeholder = "Input 1";\n\n    alert.Show ();	0
3563994	3563948	Restrict user from selecting old dates in asp.net calendar.	protected void SomeCalendar_DayRender(object sender, DayRenderEventArgs e)\n{\n    if (e.Day.Date < DateTime.Now)\n    {\n        e.Cell.Text = e.Day.Date.Day.ToString();\n    }\n}	0
32586054	32525003	Retrive javascript properties from html page using C#	var match = Regex.Match(content, "ibleID: \"(?<id>\\w+)\"");\n\nif (match.Success)\n{\n    var id = match.Groups["id"].Value;\n}\nelse \n{\n    // id not found\n}	0
16238965	16238860	How to prevent StackOverflow error when changing values of two dependent DateTimePickers?	var dtm = startDP.Value.AddSeconds(seconds);\nif (dtm != finalDP.Value)\n    finalDP.Value = dtm;	0
1788505	1788490	How can I iterate through all checkboxes on a form?	foreach(Control c in this.Controls)\n{\n   if(c is CheckBox)\n   {\n   // Do stuff here ;]\n   }\n}	0
12919410	12918698	Which Windows Print API to call from .net program	ProcessStartInfo psi = new ProcessStartInfo(documentFileName);\npsi.Verb = "Print";\nProcess.Start(psi);	0
29347557	29347422	Insert-select mistake with 'WITH' keyword	WITH XMLNAMESPACES ('uri' as inf)\nINSERT INTO dbo.tabla_XML (XMLFile) values((\nSELECT field1 as [inf:field1],field2 as [inf:field2] FROM dbo.table FOR XML PATH('inf:table_path'), ELEMENTS, ROOT('inf:table_root')))	0
23353303	23353147	Dividing a textfile and show it into listbox, where each line in the listbox will have 30 lines of textfile seperated by comma	string[] text = System.IO.File.ReadAllLines(file);\n\nvar iteration = 0;\nvar bunch_size = 30;\nvar times_to_loop = text.Length / bunch_size;\n\nwhile (iteration <= times_to_loop ) {\n    listBox7.Items.Add(\n           string.Join(",", \n               // Next 2 lines will add the next bunch size (30 in your case)\n               text.Skip(iteration*bunch_size)\n                   .Take(bunch_size))            \n           );\n    iteration++; // so loop ends\n}	0
27204729	27195916	How to bind byte array as image in windows 8 app	public async Task<byte[]> ImageFileToByteArrayAsync(StorageFile file)\n{\n    var buffer = await FileIO.ReadBufferAsync(file);\n    return buffer.ToArray();\n}	0
7763358	7763275	Show form again if password wrong	while (!securityManager.DoLogin()) { }	0
3473516	3473509	How to limit an SQL query to return at most one of something?	var latestProducts = db.Releases\n    .GroupBy(p => p.PlatformID)\n    .Select(grp => new {\n        Platform = grp.Key,\n        Latest = grp.OrderByDescending(p => p.Date).FirstOrDefault()\n    })\n    .OrderByDescending(entry => entry.Latest.Date);\n\nforeach (var entry in latestProducts)\n{\n    Console.WriteLine("The latest product for platform {0} is {1}.",\n        entry.Platform,\n        entry.Latest.ProductID);\n}	0
998499	998073	Compare two lists or arrays of arbitrary length in C#; order is important	string[] list1 = {"a", "c", "b", "d", "f", "e"};\nstring[] list2 = {"a", "d", "e", "f", "h"};\nint i = 0;\nvar list1a = list1.Intersect(list2).Select(l=> new { item = l, order= i++});\nint j = 0;\nvar list2a = list2.Intersect(list1).Select(l=> new { item = l, order= j++});\n\nvar r = from l1 in list1a join l2 in list2a on l1.order equals l2.order\n    where l1.item != l2.item\n    select new {result=string.Format("position {1} is item [{0}] on list1  but its [{2}] in list2", l1.item, l1.order, l2.item )};\n\nr.Dump();	0
3952189	3952160	Setting EntitySet<t> properties to default using reflection	public void Detach()\n{\n  GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);\n}	0
22622227	22620928	Changing a label based on selected item of combobox	private void buttonGetVendor_Click(object sender, EventArgs e)\n    {\n        int vendorID = (int)comboBoxVendor.SelectedValue;\n        var selectVendor =\n                (from vendor in payablesSet.Vendors\n                 where vendor.VendorID == vendorID\n                 select vendor).First();\n        label5.Text = selectVendor.Name;\n        label6.Text = selectVendor.City;\n        label7.Text = selectVendor.ZipCode;\n    }	0
14234956	14234774	How I can find a user in Active Directory Group with SubGroups?	(&(objectClass=user)(sAMAccountName=*" + username + "*)(memberof:1.2.840.113556.1.4.1941:=CN=GastzugangUser,OU=SubFolderB,OU=FolderB,DC=company,DC=com))";	0
23524912	23522500	c# XDocument XML format	public static List<CatPict> feed()\n    {\n        CatPict tempcat = new CatPict();\n        string xml = XDocument.Load("XMLFile1.xml").ToString();\n\n        using (XmlReader reader = new XmlTextReader(new StringReader(xml)))\n        {\n            while (reader.Read())\n            {\n                //put your logic here\n            }\n        }\n        return Listpict;\n    }	0
31553833	31553119	Casting pointer to float	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace ConsoleApplication2\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            float  input = 123.45F;\n            byte[] array = new byte[4];\n            WriteFloat(input, ref array, 0);\n            float output = ReadFloat(array, 0);\n        }\n        static public void WriteFloat(float v, ref byte[] m_Buffer, int m_Offset)\n        {\n            BitConverter.GetBytes(v).CopyTo(m_Buffer, m_Offset);\n        }\n        static public float ReadFloat(byte[] m_Buffer, int m_Offset)\n        {\n            return BitConverter.ToSingle(m_Buffer, m_Offset);\n\n        }\n    }\n}\n???	0
16492987	16492793	How do you inject with parameters using AutoFac?	container.Register(c => \n        new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString,\n                SqlServerDialect.Provider)).As<IDbConnectionFactory>();	0
34253665	34253574	How To Sum Tuition of Each Student: What Query?	context.DbSet<Student>().Select(o => new { \n    Student = o, \n    TotalTution = o.Payments.Sum(p => p. Tution)\n)}	0
19952292	19952196	Error when trying to insert data to a SQL Server database through a C# application	da.InsertCommand = new SqlCommand("INSERT INTO tblContacts(FIRSTNAME,LASTNAME) VALUES (@FIRSTNAME,@LASTNAME)", cs);	0
14687423	14686835	Lambda expression - OR Operator evaluating both sides	string cultureToMatch = "en-US";\nIEnumerable<string> cultures = new string[] { "en-US", "en-**", "fr-**", "en-KH", "ar-AR" };\n\nfor (int i = 0; i < cultureToMatch.Length; i++)\n{\n    char searchChar = cultureToMatch[i];\n    var tempFilter = cultures.Where(w => w.IndexOf(searchChar, i, 1) >= 0);\n    if (!tempFilter.Any())\n        tempFilter = cultures.Where(w => w.IndexOf('*', i, 1) >= 0);\n    cultures = tempFilter.ToList();\n}	0
27437644	27437552	What's the proper way to create a global array constant?	private static readonly string[] words = { "Easy", "Medium", "Hard" };\npublic static IReadOnlyCollection<string> Words\n{\n    get\n    {\n        return Array.AsReadOnly(words);\n    }\n}	0
887756	886680	How can I tell if a network cable has been unplugged?	using System.Runtime.InteropServices;\nclass Program\n{\n    [DllImport("sensapi.dll")]\n    static extern bool IsNetworkAlive(out int flags);\n\n    static void Main(string[] args)\n    {\n        int flags;\n        bool connected = IsNetworkAlive(out flags);\n\n    }\n}	0
14452367	14448917	send email with attachments	mailto:	0
12080548	12080392	Download file from dropbox failing when name contains spaces	temp = temp.Replace("+", "%20");	0
33891970	33891578	Change control property located in Window.Resources from code-behind	private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        Border b = (Border)this.Template.FindName("BORDERCONTROL", this);\n        b.Background = new SolidColorBrush(Colors.Yellow);\n    }	0
7039227	7038901	How to list installed features of Windows Server 2008 in c#	ManagementClass objMC = new ManagementClass(\n            "Win32_ServerFeature");\nManagementObjectCollection objMOC = objMC.GetInstances();\nforeach (ManagementObject objMO in objMOC)\n{\n    string featureName = (string)objMO.Properties["Name"].Value;\n\n}	0
25846316	25845904	Converting csv strings to a dictionary	var csv = "Mark,2014-09-15 14:31:43 \nJohn,2014-09-15 14:38:29 \nKennedy,2014-09-15 13:49:13 \nJolly,2014-09-15 13:49:18 \nDiana,2014-09-15 13:49:22 \nHenry,2014-09-15 14:33:21 \n";\n\nvar csvItems = csv.Split('\n');\nvar dictionary = new Dictionary<string, DateTime>();\n\nforeach (var item in csvItems)\n{\n    if (!string.IsNullOrWhiteSpace(item))\n    {\n        var itemParts = item.Split(',');\n        dictionary.Add(itemParts[0], Convert.ToDateTime(itemParts[1]));\n    }\n}	0
17710100	17709384	How can I find the last row of a group in a DevExpress gridview?	int rowHandle = view.FocusedRowHandle;\nint groupRow = view.GetParentRowHandle(rowHandle);\nvar childRows = GetChildRowsHandles(view, groupRow);\nif (childRows.Count > 0 && childRows.Last() == rowHandle)\n{ \n    //selected row is the last datarow of its GroupRow\n}\n\npublic List<int> GetChildRowsHandles(GridView view, int groupRowHandle)\n    {\n        List<int> childRows = new List<int>();  \n\n        if (!view.IsGroupRow(groupRowHandle))\n        {\n            return childRows;\n        }\n\n        int childCount = view.GetChildRowCount(groupRowHandle);\n        for (int i = 0; i < childCount; i++)\n        {\n            int childHandle = view.GetChildRowHandle(groupRowHandle, i);\n            if (view.IsDataRow(childHandle))\n            {\n                if (!childRows.Contains(childHandle))\n                    childRows.Add(childHandle);\n            }\n        }\n\n        return childRows;\n    }	0
18281725	18280298	Insert items from list of TVP via stored procedure only if record doesn?t exists - slow performance	INSERT INTO CARS (CAR_ID, CARNAME)\nSELECT C.CAR_ID, C.CARNAME\nFROM @CARS C\nLEFT JOIN Cars ON Cars.CAR_ID = C.CAR_ID\nWHERE Cars.Car_ID IS NULL -- the car does not already exist	0
14460537	14453691	Get Tables (workparts) of a sheet of excel by OpenXML SDK	// true for editable\nusing (SpreadsheetDocument xl = SpreadsheetDocument.Open("yourfile.xlsx", true))\n{\n    foreach (WorksheetPart wsp in xl.WorkbookPart.WorksheetParts)\n    {\n        foreach (TableDefinitionPart tdp in wsp.TableDefinitionParts)\n        {\n            // for example\n            // tdp.Table.AutoFilter = new AutoFilter() { Reference = "B2:D3" };\n        }\n    }\n}	0
4671179	4670720	Extremely fast way to clone the values of a jagged array into a second array?	// 100 passes on a int[1000][1000] set size\n\n// 701% faster than original (14.26%)\nstatic int[][] CopyArrayLinq(int[][] source)\n{\n    return source.Select(s => s.ToArray()).ToArray();\n}\n\n// 752% faster than original (13.38%)\nstatic int[][] CopyArrayBuiltIn(int[][] source)\n{\n    var len = source.Length;\n    var dest = new int[len][];\n\n    for (var x = 0; x < len; x++)\n    {\n        var inner = source[x];\n        var ilen = inner.Length;\n        var newer = new int[ilen];\n        Array.Copy(inner, newer, ilen);\n        dest[x] = newer;\n    }\n\n    return dest;\n}	0
16801565	16800630	Rest service messing up strings with double quotes	"this is a " test	0
21331134	21328855	launching multiple forms from one application	[STAThread]\nstatic void Main()\n{\n  var classObject = new APACMiscUM();\n  var someReturnTyoe = classObject.SomeMethod(SomeArgument)\n}	0
1426742	1426715	factorial of n numbers using c# lambda..?	Func<int, int> factorial = null; // Just so we can refer to it\nfactorial = x => x <= 1 ? 1 : x * factorial(x-1);\n\nfor (int i = 1; i <= range; i++)\n{\n    Console.WriteLine(factorial(i));\n}	0
28847028	28846723	display the display member of a combo box for a Given integer Value member	comboBox1.SelectedValue = "2"; // it will show you respected display member	0
1893297	1892019	debug c# managed application: how to set a breakpoint when it opens a file	1) Attach the VS Debugger to the process you are running and\n   immediately hit pause/break\n2) Open the file you want the debugger to break in VS editor\n3) Set the breakpoint at the desired location, optionally you\n   can add conditions if you like (right click on the breakpoint)\n4) Hit Run (F5)	0
20110403	20110071	Count the number of children in my JSON file using JSON.NET with LINQ	token["root"]["paramFile"].Count();	0
9082048	9081925	Selecting session variable with an IF statement	if (Session["para1"] != null) \n    {\n      int AgentCode = Convert.ToInt32(Session["para1"].ToString());\n\n      //Search by AgentCode \n           GridView1.DataSource = ws.GetJobsByAgencyID(AgentCode );\n            GridView1.DataBind();\n\n    }\n\n   else if (Session["para2"] != null)\n    {\n      string title = Session["para1"].ToString();\n\n       //Search by title\n       GridView1.DataSource = ws.GetJobsByAgencyID(title );\n        GridView1.DataBind();\n    }\n   else\n   {\n      // your default parameters\n    }	0
6903051	6903001	Oracle Date Column NULL	WHERE date_I_care_about\n  BETWEEN nvl(start_date,to_date('19000101','YYYYMMDD'))\n      AND nvl(start_date,to_date('30000101','YYYYMMDD'))	0
15083212	15082824	Fastest way to read 3 bytes at a given pointer address?	int Pix = *(int*)((byte*)bmpScan0 + (y * bmpStride) + (x * 3)) & 0x00FFFFFF;	0
1864540	1864537	C#, Is there a map structure?	SortedDictionary<Double,Int>	0
26223755	26186391	How to Clear/Remove an ActiveDirectory property with ExtensionSet	[DirectoryProperty("facsimileTelephoneNumber")]\n    public string FaxNumber\n    {\n        get\n        {\n            if (ExtensionGet("facsimileTelephoneNumber").Length != 1)\n                return null;\n            return (string)ExtensionGet("facsimileTelephoneNumber")[0];\n        }\n        set\n        {\n            ExtensionSet("facsimileTelephoneNumber", string.IsNullOrEmpty(value) ? new string[1] {null} : new string[1] {value});\n        }\n    }	0
7612338	7611992	C# regulate number of emails sent	bool ServiceWasDown = false;\nDateTime ServiceDownTime = DateTime.Now;\nDateTime LastEmailTime = DateTime.Now;\n\nvoid OnTimerElapsed()\n{\n   if(IsServiceDown())\n      ServiceDown();\n   else\n      ServiceUp();\n}\n\nvoid ServiceDown()\n{\n   if(ServiceWasDown)//already know about service\n   {\n      //if LastEmailTime more than 10 minutes ago send another email and update LastEmailTime\n   }\n   else//service just went down\n   {\n      //send new email\n      LastEmailTime = DateTime.Now;\n      ServiceWasDown = true;\n      ServiceDownTime = DateTime.Now;\n   }   \n}\n\nvoid ServiceUp()\n{\n   ServiceWasDown = false;   \n}	0
11794777	11794751	C# increase length of a string array	List<string>	0
7915218	7914858	Fire CheckedChanged in gridview by clicking anywhere in gridview row	e.Row.Attributes.Add("onclick", string.Format("document.getElementById('{0}').checked = !document.getElementById('{0}').checked; {1}", checkbox.ClientID, ClientScript.GetPostBackEventReference(checkbox, "")));	0
8048385	8048264	Get Specific Text in a Range of Excel cells using C#	Microsoft.Office.Interop.Excel.Range range = myworksheet.UsedRange;\n        //Start iterating from 1 not zero, 1 is the first row after notation of the current coloumn\n        for (int i = 1; i <= range.Rows.Count; i++)\n        {\n            Microsoft.Office.Interop.Excel.Range myrange = myworksheet.get_Range(/*your column letter, ex: "A" or "B"*/ + i.ToString(), System.Reflection.Missing.Value);\n            string temp = myrange.Text;\n            if(temp.Contains("YES"))\n            {\n                //Do your YES logic\n            }\n            else if(temp.Contains("NO"))\n            {\n                //Do your No Logic\n            }\n        }	0
3615359	3615339	Reading xml file and accessing optional nodes	XmlDocument doc = new XmlDocument();\n    doc.Load("C:\\Books.xml");\n    XmlElement root = doc.DocumentElement;\n    XmlNodeList nodes = root.SelectNodes("/NewDataSet/booksdetail");\n\n    foreach (XmlNode node in nodes)\n    {\n        string pages = node["pages"].InnerText;             \n        string description = null;\n        if(node["Description"]!= null)\n        {\n           description = node["Description"].InnerText;\n        }\n    }	0
11477315	11477188	How to get dot product between -1 and 1 in Objective-C	float mag1 = sqrt(point1.x*point1.x + point1.y*point1.y);\nfloat mag2 = sqrt(point2.x*point2.x + point2.y*point2.y);\ndotProduct = (dotProduct)/(mag1*mag2);	0
14777832	14777736	Getting DISTINCT values from a JOIN	.Distinct()	0
776045	775950	Currency Library	CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);\nIEnumerable<string> currencySymbols = cultures.Select<CultureInfo, string>(culture => new RegionInfo(culture.LCID).ISOCurrencySymbol);	0
6046465	6046406	splitting string from listbox items	string firsWord = sentence.SubString(0, sentence.IndexOf(' '));\nstring remainingSentence = sentence.SubString(sentence.IndexOf(' '), sentence.Length);	0
30297726	30295052	CMSEditableRegion inside a code loop	// Let's assume that 'plc' is a placeholder. But it can be any control.\nplc.Controls.Add(new LiteralControl("<li class=\"htab-list__item--fininfo active\">"));\nplc.Controls.Add(new LiteralControl("<a href=\"#financial-result\" class=\"htab-list__link tab-link\">"));\nplc.Controls.Add(new CMSEditableRegion { ID = "someid", RegionType = CMSEditableRegionTypeEnum.TextBox, RegionTitle = "sometitle" });\nplc.Controls.Add(new LiteralControl("</li>"));	0
5058150	5058133	Hbitmap from image	Bitmap.GetHBitmap	0
9864029	9809488	How to generalise access to DbSet<TEntity> members of a DbContext?	var dbSet = _dbContext.Set<T>	0
10487730	10484499	Add links to all cells in gridview	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        foreach (TableCell cell in e.Row.Cells)\n        {\n            HyperLink myLink = new HyperLink();\n            myLink.NavigateUrl = "somewhere.aspx";\n            if (cell.Controls.Count > 0)\n            {\n                while (cell.Controls.Count > 0)\n                {\n                    myLink.Controls.Add(cell.Controls[0]);\n                }\n            }\n            else\n            {\n                myLink.Text = cell.Text;\n            }\n            cell.Controls.Add(myLink);\n        }\n    }\n}	0
20537593	20536957	Sort item before group by in C#	Model.GroupBy(item=>item.page)\n    .Select(group=>group.OrderBy(I=>I.priority))	0
22476917	22476302	Create Objects from Datatable data C#	public static IEnumerable<T> ToIEnumerable<T>(this DataTable dt)\n{\n    List<T> list = Activator.CreateInstance<List<T>>();\n    T instance = Activator.CreateInstance<T>();\n    var prop = instance.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);\n    foreach (DataRow dr in dt.Rows)\n    {\n        T ins = Activator.CreateInstance<T>();\n        foreach (var p in prop)\n        {\n            try\n            {\n                p.SetValue(ins, dr[p.Name], null);\n            }\n            catch { }\n        }\n        list.Add(ins);\n    }\n    return list;\n}	0
2000835	2000772	Using C#, how do I set tab positions in a multiline textbox?	static class NativeMethods {\n    [DllImport("user32.dll")]\n    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, ref int lParam);\n}\nstatic void SetTabs(TextBox box) {\n    //EM_SETTABSTOPS - http://msdn.microsoft.com/en-us/library/bb761663%28VS.85%29.aspx\n    int lParam = 16;  //Set tab size to 4 spaces\n    NativeMethods.SendMessage(box.Handle, 0x00CB, new IntPtr(1), ref lParam);\n    box.Invalidate();\n}	0
12047231	12047210	How to compare two hexadecimal numbers	int a = int.Parse("3E", System.Globalization.NumberStyles.HexNumber);\nint b = int.Parse("32", System.Globalization.NumberStyles.HexNumber);\n\nif (a > b)\n    MessageBox.Show("a is greater");	0
4875764	4832131	How do I insert an element in a .docx file at a specific location using the OpenXML SDK in .NET	IDictionary<String, BookmarkStart> bookMarkMap = new Dictionary<String, BookmarkStart>();\n            foreach (BookmarkStart bookMarkStart in wordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())\n            {\n                bookMarkMap[bookMarkStart.Name] = bookMarkStart;\n            }\n\n            foreach (BookmarkStart bookMarkStart in bookMarkMap.Values)\n            {\n                if (bookMarkStart.Name == "MyBookmarkName")\n                {\n                    //do insert here   \n                    var parent = bookMarkStart.Parent;\n\n                    //create paragraph to insert\n                    parent.InsertAfter(MyNewParagraph);         \n                }\n            }	0
12265584	11780829	How do you get the X,Y of a DevExpress TreeList node?	/// <summary>\n    /// Get the position and size of a displayed node.\n    /// </summary>\n    /// <param name="node">The node to get the bounds for.</param>\n    /// <param name="cellIndex">The cell within the row to get the bounds for.  Defaults to 0.</param>\n    /// <returns>Bounds if exists or empty rectangle if not.</returns>\n    public Rectangle GetNodeBounds(NodeBase node, int cellIndex = 0)\n    {\n        // Check row reference\n        RowInfo rowInfo = this.ViewInfo.RowsInfo[node];\n        if (rowInfo != null)\n        {\n            // Get cell info from row based on the cell index parameter provided.\n            CellInfo cellInfo = this.ViewInfo.RowsInfo[node].Cells[cellIndex] as CellInfo;\n            if (cellInfo != null)\n            {\n                // Return the bounds of the given cell.\n                return cellInfo.Bounds;\n            }\n        }\n        return Rectangle.Empty;\n    }	0
26880847	26880523	string value does not match C# with dictionary value	string s="TextBox1.Text= \"Hello 1\""; //1\n    Dictionary<string, string> dictionary = //2\n        new Dictionary<string, string>();\n    dictionary.Add("Button", "TextBox1.Text= \"Hello 1\"");//3\n    dictionary.Add("TextBox","TextBox1.Text= \"Hello 1\"");//4\n\nforeach(KeyValuePair<string,string> pair in dictionary)\n{\n   if(s==pair.Value.ToString())\n   {\n       // some code\n   }\n}	0
5752864	5752838	Change in application configuration without application restart	var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);\nstring myConfigData = appConfig.AppSettings.Settings["myConfigData"].Value;	0
3939771	3895883	Crystal Reports: ParamerterValue dialog appears despite of the values are set programmatically	ReportDocument reportDocument = new ReportDocument();\nParameterFields paramFields = new ParameterFields;\nParameterField paramField;\nParameterDiscreteValue paramDiscreteValue;\n\n\nparamField = crystalreportviewer1.ParameterFieldInfo["HeaderColumn1"];\nparamDiscreteValue = new ParameterDiscreteValue();\nparamDiscreteValue.Value = "Customer Code";\nparamField.CurrentValues.Add(paramDiscreteValue);\n\n\nparamFields.Add(paramField);\n\n\ncrystalReportViewer1.ReportSource = reportDocument;\ncrystalReportViewer1.ParameterFieldInfo = paramFields;\ncrystalReportViewer1.RefreshReport();	0
22084090	22083903	Generic implicit cast of Func<T, T> to T	public delegate int Contacts(int a, int b);\n\n    public static class TestClass\n    {\n        public static void Test()\n        {            \n            Contacts contactsFunc = (Contacts)((a, b) => a + b);\n            contactsFunc(2, 3);\n            //less verbose mode\n            ((Contacts)((a, b) => a + b))(2,3);\n        }\n    }	0
10734251	10734212	static variables are they class-instance variables?	public class BaseClass\n{\n    private static Dictionary<Type, object> ClassInstVarsDict = new Dictionary<Type, object>();\n\n    public object ClassInstVar\n    {\n        get\n        {\n            object result;\n            if (ClassInstVarsDict.TryGetValue(this.GetType(), out result))\n                return result;\n            else\n                return null;\n        }\n        set\n        {\n            ClassInstVarsDict[this.GetType()] = value;\n        }\n    }\n}\n\npublic class DerivedClass1 : BaseClass\n{\n}\n\npublic class DerivedClass2 : BaseClass\n{\n}	0
351936	351915	Custom Linq Extension Syntax	public static IEnumerable<T> GetRandom<T>( this Table<T> table, int count) where T : class {\n  ...\n}	0
5074509	5074155	Date validation using regular expression	DateTime dt;\n\nbool bSuccess = DateTime.TryParse("2009-05-01 14:57:32", out dt);\nif(bSuccess)\n    Console.WriteLine("it's a date!");	0
6786125	6777168	C# - Attach file saved in database to an email	SqlCommand cmdSelect=new SqlCommand("Select file_name, file_content " + \n              " from Attachments where Email_ID=@ID",this.sqlConnection1);\n        cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);\n        cmdSelect.Parameters["@ID"].Value=333;\n\nDataTable dt = new DataTable();\n        this.sqlConnection1.Open();\n        SqlDataAdapter sda = new SqlDataAdapter();\n            sda.SelectCommand = cmdSelect;\n            sda.Fill(dt);\n     if(dt.Rows.Count > 0)\n{\n        byte[] barrImg=(byte[])dt.Rows[0]["file_content"];\n        string strfn= "Your File Directory Path" + Convert.ToString(dt.Rows[0]["file_name"]);\n        FileStream fs=new FileStream(strfn, \n                          FileMode.CreateNew, FileAccess.Write);\n        fs.Write(barrImg,0,barrImg.Length);\n        fs.Flush();\n        fs.Close();\n   //now you can attache you file to email here your file is generate at path stored in "strfn" variable\n}	0
9123944	9101759	how to call sql server express command line using c# to run a .sql file	FileInfo file = new FileInfo(Path.Combine(Path.GetDirectoryName(Environment.GetCommandLineArgs().ToString()), "HotelReservationScript.sql"));	0
24565120	24565057	How do you get a image through external source in Web API and return it in base64?	[HttpGet()]\n[Route("test")]\npublic async Task<string> GetValidationImage()\n{\n   string base64String;\n   client.BaseAddress = new Uri(TestBaseAddress);\n   client.DefaultRequestHeaders.Accept.Clear();\n   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/png"));\n\n   var response = await client.GetAsync(TestString);\n\n   using (var ms = new MemoryStream())\n   {\n      var image = System.Drawing.Image.FromStream(await response.Content.ReadAsStreamAsync());\n      image.Save(ms, ImageFormat.Png);\n      var imageBytes = ms.ToArray();\n      base64String = Convert.ToBase64String(imageBytes);\n   }\n\n   return base64String;\n}	0
6345910	6345108	How to embed/attach SQL Database into Visual C#?	using System.Data.SqlServerCe;\n\nnamespace ConsoleApplication6\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            using (var cn = new SqlCeConnection("Data Source=MyDB.sdf"))\n            {\n                cn.Open();\n                using (var cmd = cn.CreateCommand())\n                {\n                    cmd.CommandText = "select * from MyTable where Field2 like '%AB%'";\n                    using (var reader = cmd.ExecuteReader())\n                    {\n                        while (reader.Read())\n                        {\n                            Console.WriteLine("Field1: {0}", reader[0]);\n                        }\n                    }\n                }\n            }\n            Console.ReadKey();\n        }\n    }\n}	0
24887735	24886781	TreeView with check boxes and radio buttons	private void createRadioButtonsChildren(string content, TreeViewItem item)\n    {\n        TreeViewItem childRadio = new TreeViewItem()\n        {\n            Header = new RadioButton()\n            {\n                GroupName="Group1",\n                Content = content\n            }\n        };\n        item.Items.Add(childRadio);\n    }	0
9462890	9462812	Can two ElapsedEvent's, from the same System.Timers.Timer, run at the same time	If the SynchronizingObject property is Nothing, the Elapsed event is raised on a ThreadPool thread. If the processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.	0
22077759	22077331	Send information stored in a repeater to email recipient?	ValidateRequest="false"	0
5202684	5202652	how to run a in memory created DLL and retrieve value from it using C# and reflection	Assembly a = cr.CompiledAssembly;\n    try {\n        Type type = a.GetType("dynamic_scripting.DynScripting");\n        int result = (int) type.GetMethod("executeScript").Invoke(\n            null, new object[] {"CSharpScript" });\n    }\n    catch(Exception ex) {\n        MessageBox.Show(ex.Message);\n    }	0
22273332	22273131	Close childForm when Open a New childForm in MDI Parent?	private Form1 myform1 = null;\nprivate Form2 myform2 = null;\n\nprivate void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {\n   string selectedNodeText = e.Node.Text;\n\n   if (selectedNodeText == "1" && myform1 == null) {\n       myform1 = new Form1()\n       // ... some code ...\n       if (myform2 != null) {\n           myform2.Close();\n           myform2 = null;\n       }\n   }\n   if (selectedNodeText == "2" && myform2 == null) {\n       myform2 = new Form2()\n       // ... some code ...\n       if (myform1 != null) {\n           myform1.Close();\n           myform1 = null;\n       }\n   }\n}	0
27023792	27023228	Converting a VB code with an Aggregate clause to C#	IEnumerable<DataRow> newRows = dsNew.Tables["parts"].Rows.OfType<DataRow>();\nIEnumerable<DataRow> oldRows = dsOld.Tables["parts"].Rows.OfType<DataRow>();\n\nDataRow[] rowsNotFound = newRows\n.GroupJoin(oldRows, \n    o => new \n        { \n            Transaction = o.Field<int>("TRANSACTION"), \n            Description = o.Field<string>("DESCRIPTION"), \n            Quantity = o.Field<int>("QTY"), \n            PartNumber = o.Field<string>("PART_NUM") \n        },\n    i => new \n        { \n            Transaction = i.Field<int>("TRANSACTION"), \n            Description = i.Field<string>("DESCRIPTION"), \n            Quantity = i.Field<int>("QTY"), \n            PartNumber = i.Field<string>("PART_NUM") \n        },\n    (o, i) => new {NewRow = o, OldRows = i})\n.SelectMany(g => g.OldRows.DefaultIfEmpty(), (g, oldRow) => oldRow == null ? g.NewRow : null)\n.Where(r => r != null)\n.ToArray();	0
6303226	6289672	ListView included in custom control	this.myListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {\n        this.myColumnHeader1,\n        this.myColumnHeader2,\n        this.myColumnHeader3});\n\n        // \n        // myColumnHeader1\n        // \n        this.myColumnHeader1.Text = "My Column Header1";\n        this.myColumnHeader1.Width = 100;\n        // \n        // myColumnHeader2\n        // \n        this.myColumnHeader2.Text = "My Column Header 2";\n        this.myColumnHeader2.Width = 100;\n        // \n        // myColumnHeader3\n        // \n        this.myColumnHeader3.Text = "My Column Header 3";\n        this.myColumnHeader3.Width = 100;	0
22182667	22181991	Strange if-statement behavior with zero value double	...\nTimer.Start(Handle_Tick)\n...\n\npublic void Handle_Tick(...)\n{\n    //Check to see if we're already busy. We don't need to "pump" the work if\n    //we're already processing.\n    if (IsBusy)\n        return;\n\n    try\n    {\n        IsBusy = true;\n\n        //Perform your work\n    }\n    finally\n    {\n        IsBusy = false;\n    }\n}	0
110769	110749	Regular expression to convert mark down to HTML	private string DoItalicsAndBold (string text)\n{\n    // <strong> must go first:\n    text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1", \n                          new MatchEvaluator (BoldEvaluator),\n                          RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n\n    // Then <em>:\n    text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1",\n                          new MatchEvaluator (ItalicsEvaluator),\n                          RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n    return text;\n}\n\nprivate string ItalicsEvaluator (Match match)\n{\n    return string.Format ("<em>{0}</em>", match.Groups[2].Value);\n}\n\nprivate string BoldEvaluator (Match match)\n{\n    return string.Format ("<strong>{0}</strong>", match.Groups[2].Value);\n}	0
19747409	19747349	set up range on EF5 CF	[Range(1, 40)]\n public int SpaceUnits { get; set; }	0
20221934	20221747	How to import a C++ function with int** and double** parameters	public unsafe int _SetPointers(IntPtr ID, IntPtr BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);	0
21706686	21706636	How to remove list items comparing with another list items of same type	var oListBHashSet = new HashSet<Detail>(ListB);\nListA.RemoveAll(v => oListBHashSet.Contains(v));	0
32390635	32377838	Create appointment with custom properties in EWS	PropertySet YourProperyset = new PropertySet(BasePropertySet.FirstClassProperties);\n        var extendendProperty = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Address, "organizer",MapiPropertyType.String);\n        YourProperyset.Add(extendendProperty);\n        var folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(userName));\n        var calendar = CalendarFolder.Bind(service, folderId);\n        var calendarView = new CalendarView(start, stop);\n        calendarView.PropertySet = YourProperyset;\n        return calendar.FindAppointments(calendarView).ToList();	0
11402890	11402355	XDocument Determine Last Child of Parent	XDocument doc = XDocument.Parse("xmlPath");\nforeach (XElement element in doc.Root.Descendants())\n{\n    bool hasChildren = element.HasElements;\n    bool hasSiblings = element.ElementsBeforeSelf().Any() || element.ElementsAfterSelf().Any();\n    bool isLastChild = hasSiblings && !element.ElementsAfterSelf().Any();\n}	0
19231774	19231746	How to Remove the last char of String in C#?	YourString = YourString.Remove(YourString.Length - 1);	0
13440263	13440098	How to set value of progress bar	private void StartBackgroundWork() {\n    if (Application.RenderWithVisualStyles)\n        progressBar.Style = ProgressBarStyle.Marquee;\n    else {\n        progressBar.Style = ProgressBarStyle.Continuous;\n        progressBar.Maximum = 100;\n        progressBar.Value = 0;\n        timer.Enabled = true;\n    }\n    backgroundWorker.RunWorkerAsync();\n}\n\nprivate void timer_Tick(object sender, EventArgs e) {\n    progressBar.Value += 5;\n    if (progressBar.Value > 120)\n        progressBar.Value = 0;\n}	0
14004657	14004091	RichTextBox in WPF - Getting last block of text	box.Document.Blocks.Remove(box.Document.Blocks.LastBlock)	0
23739367	23738158	I get a FormatException when I'm trying to parse a Double	double item = 0;\nif(double.TryParse(tbx_TotalVikt.Text, out item))\n            {\n                totalWeight += item;\n            }\ntbx_TotalVikt.Text = totalWeight.ToString();	0
2673565	2673514	how to prevent sorting in DataGridView?	for (int i = 0; i < this.dataGridView1.ColumnCount - 1; i++)\n    {\n        this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;\n    }	0
28607135	28606059	Retrieve all files from a server side folder	public string GetSoundFile()\n{\n    var files = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/sounds"));\n    return String.Join("|",files);\n}	0
30734974	30713664	How to flatten pdf with Itext in c#?	public static void RemoveAcroFields(String filename)\n    {\n        if (filename != null && File.Exists(filename))\n        {                \n            byte[] pdfFile = File.ReadAllBytes(filename);\n            PdfReader reader = new PdfReader(pdfFile);\n            PdfStamper stamper = new PdfStamper(reader, new FileStream(filename, FileMode.Create));\n\n            stamper.FormFlattening = true;\n            stamper.Close();                                             \n\n            reader.Close();\n        }              \n    }	0
346550	346546	How to set the name of the file when streaming a Pdf in a browser?	Content-Disposition: inline; filename=foo.pdf	0
23895208	23895142	DropDownList not population from SQL Database	string IDSel = "SELECT Value, [Text] FROM DDL1 WHERE Value = @Value";	0
14257587	14256823	How to delete control boxes when maximized	protected override CreateParams CreateParams\n{\n    get\n    {\n        CreateParams param = base.CreateParams;\n        const int CS_DROPSHADOW = 0x00020000;\n        const int WS_CAPTION    = 0xC00000;\n        param.ClassStyle = param.ClassStyle | CS_DROPSHADOW; // Turn on window shadow.\n        param.Style = param.Style & ~WS_CAPTION; // Turn off caption.\n        return param;\n    }\n}	0
18245659	18245555	How to Add an item to ArrayList and Dictionary using reflection	var dictProp = properties.Single(t => t.Name = "MyDictionary");\nvar myDict = (Dictionary<string,string>)dictProp.GetValue(model, null);\nmyDict.Add("MyKey", "MyValue");	0
10073584	10073406	Pass a list of types as Generic parameter	private void someMethod() {\n    var genericSave = repository // This can be done during initialization\n        .GetType()\n        .GetMethods()\n        .Where(m => m.Name == "Save" && m.IsGenericMethodDefinition);\n    var t = MyCollectionViewSource.CurrentItem.GetType();\n    genericSave\n        .MakeGenericMethod(new[] {t})\n        .Invoke(new object[] {MyCollectionViewSource.CurrentItem});\n}	0
890786	890763	How to serialize a list of lists with the type of custom object?	class Program\n{\n    static void Main(string[] args)\n    {\n        XmlSerializer s = new XmlSerializer(typeof(FooContainer));\n\n        var str = new StringWriter();\n        var fc  = new FooContainer();\n\n        var lst = new List<Foo>() { new Foo(), new Foo(), new Foo() };\n\n        fc.lst.Add( lst );\n\n        s.Serialize(str, fc);\n    }\n}\n\n[XmlRoot("Foo")]    \npublic class Foo    {        \n    [XmlElement("name")]        \n    public string name = String.Empty;    }    \n\n[XmlRoot("FooContainer")]    \npublic class FooContainer    {\n\n    public List<List<Foo>> _lst = new List<List<Foo>>();\n    public FooContainer()\n    {\n\n    }\n\n    [XmlArrayItemAttribute()]\n    public List<List<Foo>> lst { get { return _lst; } }\n}	0
34232128	34211341	Insert into database using Entity Framework from C#	String TxnLOC = null;\n                IsTransactionLocation= false;\n                if (line.Contains("TRANSACTION LOC:"))\n                {\n                    IsTransactionLocation = true;\n                    if (IsTransactionLocation)\n                    {\n                        TxnLOC = line.Replace("TRANSACTION LOC:", String.Empty).Trim();\n                        Console.WriteLine("The Transaction Location: ********");\n                        Console.WriteLine(TxnLOC);\n\n                    //Database insertion fot TTransaction Table\n                    TTransaction txn = new TTransaction();\n\n                    txn.TRN = txnNo;\n                    txn.Amount = Convert.ToDecimal(Amount);\n                    txn.TransactionLocation = TxnLOC;\n\n                    context.TTransaction.Add(txn); //Adding to the database\n                    context.SaveChanges();\n\n                    IsTxnSection = false;//For 1 to many relationship\n\n\n                }\n\n\n               }	0
6713453	6713438	Add an interface to a class that extends another class	public class MyClass : BaseClass, INotifyPropertyChanged { }	0
27776627	27776521	XmlSerializer gives xml declaration after every product in the file	var emptyNs = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });\nwriter.Serialize(file, backupDeviceLocationData, emptyNs);	0
31526849	31526711	Sum of selected elements in 2d array (box shape?)	private int BoxSum(int x, int y, int x1, int y1, int[,] arrayM)\n    {\n        int lowestX = (x1 > x) ? x : x1;\n        int lowestY = (y1 > y) ? y : y1;\n\n        int highestX = (x1 > x) ? x1 : x;\n        int highestY = (y1 > y) ? y1 : y;\n\n        int sum = 0;\n\n        for (int i = lowestX; i < highestX; i++)\n        {\n            for (int j = lowestY; j < highestY; j++)\n            {\n                sum += arrayM[i, j];\n            }\n        }\n\n        return sum;\n    }	0
10539471	10539438	Majority vote from string[] using LINQ?	string majority = yourArray.GroupBy(x => x)\n                           .OrderByDescending(g => g.Count())\n                           .First()\n                           .Key;	0
32037106	32036789	Get HTML via URL in Xamarin Forms	System.Net.Http	0
31202628	31117411	odata action accepting list parameter is always null	public IHttpActionResult SetCoordinatesOnAddressList(IEnumerable<Address> addresses)\n{\n    //Do stuff\n}	0
29671296	29669600	Passing parameter ID in URL from GridBoundColumn (GridView) with JS	var routeId = eventArgs.getDataKeyValue('RouteNo');	0
10801769	10801681	Downloading a file via an HTTP Post, where am I going wrong?	private static void DownloadDatacashData(int howManyDays)\n{\n    var url = "https://reporting.datacash.com/reporting2/csvlist";\n    using (var client = new WebClient())\n    {\n        var values = new NameValueCollection\n        {\n            { "group", "123456" },\n            { "user", "autoreport" },\n            { "password", "foobar" },\n            { "start_date", DateTime.Now.AddDays(howManyDays).ToString("yyyy-MM-dd") },\n            { "end_date", DateTime.Now.ToString("yyyy-MM-dd") },\n            { "type", "stl" },\n        };\n        byte[] result = client.UploadValues(url, values);\n        File.WriteAllBytes("C:\\foo\\bar.csv", result);\n    }\n}	0
6775137	6769358	Print using epson esc/p2 on TM U325D	serialPort.Write(new byte[] { 27, 33, 9 }, 0, 3);	0
33500174	33499944	How can I prevent a Form_activated event from looping?	private void Form1_Activated(object sender, EventArgs e)\n{\n    this.Activated -= Form1_Activated;\n    // Do other stuff here. \n}	0
18189866	18189771	Concatenate variable number of strings	string.Format(sql, "'" + string.Join("', '", arrOfStrings) + "'")	0
18029198	18029151	EF Parent Child Inserts	NorthwindCustEntities context = new NorthwindCustEntities();\n\nTeacher t1 = new Teacher() { Name = "Jane Smith" };\n\nSubject s1 = new Subject() { Name = "Math" };\nSubject s2 = new Subject() { Name = "Science" };\n\ncontext.Subjects.Add(s1);\ncontext.Subjects.Add(s2);\n\nt1.Subjects.Add(s1);\nt1.Subjects.Add(s2);\ncontext.Teachers.Add(t1);\n\ncontext.SaveChanges();	0
29176499	29150447	Wav to bitmap conversion in C#	// Setup 24 bit bmp encoder\nSystem.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.ColorDepth; \nmyEncoder = System.Drawing.Imaging.Encoder.ColorDepth;\nEncoderParameters myEncoderParameters = new EncoderParameters(1);\nEncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 24L);\nmyEncoderParameters.Param[0] = myEncoderParameter;\nvar codec = GetEncoderInfo("image/bmp");	0
12182936	12182494	Formatting String from Data	var designationsByDate = allianceDesignations.GroupBy(designation => designation.UpdateDue).OrderBy(values => values.Key);\nstring[] rowsOfData = designationsByDate.Select(designationByDate => {\n    string annual = designationByDate.Aggregate(string.Empty, (acc, designation) => acc + "/" + designation.Name);\n    return string.Format("Annual {0} Update {1}", annual, designationByDate.Key);\n}).ToArray();	0
4214664	4205195	Can i add a RadGrid to a NestedViewTemplate	RadGrid temp = (RadGrid)sender;	0
20865993	20865817	how to render datetime from database and convert it into seperate integer like day,month,year	protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)\n{\n    dr = cmd.ExecuteReader();\n    dr.Read();\n    dt= (DateTime)dr[0];\n    if(dt!= null)\n    {       \n        if(dt == e.Day.Date)\n          {\n             e.Cell.BackColor = System.Drawing.Color.Red;\n          }\n    }\n}	0
910561	910546	Serializing a List<T> to XML with inheritance	using System;\nusing System.Collections.Generic;\nusing System.Xml.Serialization;\n[XmlInclude(typeof(IncomeProfile))]\n[XmlInclude(typeof(CostProfile))]\n[XmlInclude(typeof(InvestmentProfile))]\npublic class Profile {\n    public string Foo { get; set; }\n}\npublic class IncomeProfile : Profile {\n    public int Bar { get; set; }\n}\npublic class CostProfile : Profile { }\npublic class InvestmentProfile : Profile { }\nstatic class Program {\n    static void Main() {\n        List<Profile> profiles = new List<Profile>();\n        profiles.Add(new IncomeProfile { Foo = "abc", Bar = 123 });\n        profiles.Add(new CostProfile { Foo = "abc" });\n        new XmlSerializer(profiles.GetType()).Serialize(Console.Out, profiles);\n    }\n}	0
15366478	15366294	listview in c# with images	private void Form10_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                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
1248211	1248177	How to use a defined brush resource in XAML, from C#	var brush = this.Resources["KeyDownBrush"] as LinearGradientBrush;	0
10579193	10578983	Inserting XML node at specific position	String xmlString = "<?xml version=\"1.0\"?>"+"<xmlhere>"+\n    "<somenode>"+\n    " <child> </child>"+\n    " <children>1</children>"+ //1\n    " <children>2</children>"+ //2\n    " <children>3</children>"+ // 3, I need to insert it\n    " <children>4</children>"+  //4,  I need to insert this second time\n    " <children>5</children>"+\n    " <children>6</children>"+ \n    " <child> </child>"+\n    " </somenode>"+\n    "</xmlhere>";\n\n    XElement root = XElement.Parse(xmlString);\n    var childrens = root.Descendants("children").ToArray();\n    var third = childrens[3];\n    var fourth = childrens[4];\n    third.AddBeforeSelf(new XElement("children"));\n    fourth.AddBeforeSelf(new XElement("children"));\n\n    var updatedchildren = root.Descendants("children").ToArray();	0
7833892	7822852	.NET C# - MigraDoc - How to change document charset?	PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);\nrenderer.Document = document;	0
21362574	21362341	Connection Pooling in Entity Framework 6	Pooling=False;	0
5370137	5364533	Drawing a focus rectangle only when control receives focus via keyboard	InputManager.Current.MostRecentInputDevice is KeyboardDevice	0
23932049	23931937	Asynchronous tasks, waiting in main thread for completition	...\n\n    // Start async.\n    var task1 = Task.Factory.StartNew(Accept, s1);\n    var task2 = Task.Factory.StartNew(Accept, s2);\n\n    Task.WhenAll(task1, task2).Wait();    \n\n    Log("Nothing left to do, stopping service.");\n}	0
6779739	6771995	How to parse .Net Webservice on iphone with Authentication	- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge\n{\n    NSURLCredential *myCreds = [[NSURLCredential alloc] initWithUser:@"**USERNAME**" password:@"**PASSWORD**" persistence:NO];\n\n    [challenge.sender useCredential:myCreds forAuthenticationChallenge:challenge];\n    [myCreds release];\n}	0
13954709	13954544	How to iterate through two date ranges and display in ASP.NET Calendar?	protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)\n{\n  foreach (DataRow dr in ds.Tables[0].Rows)\n  {\n    DateTime df = (DateTime)dr.Field<DateTime?>("DateFrom");\n    DateTime dt = (DateTime)dr.Field<DateTime?>("DateTo");\n\n    if (e.Day.Date == dt.Date)\n    {\n        Label lbl = new Label();\n        lbl.BackColor = System.Drawing.Color.Gray;\n        lbl.Text = "Booked From";\n        e.Cell.Controls.Add(lbl);\n     }\n\n    if (e.Day.Date == df.Date)\n    {\n        Label lbl = new Label();\n        lbl.BackColor = System.Drawing.Color.Gray;\n        lbl.Text = "Booked To";\n        e.Cell.Controls.Add(lbl);\n    }\n\n    //Added Code\n    if(e.Day.Date > df.Date && e.Day.Date < dt.Date)\n    {\n        Label lbl = new Label();\n        lbl.BackColor = System.Drawing.Color.Gray;\n        lbl.Text = "Day inbetween";\n        e.Cell.Controls.Add(lbl);\n    }\n}	0
26189717	26189540	How to check if value in list is not in another IList	IList<Role> rolesToBeAdded = new List<Role>();\n   IList<Role> rolesToBeDeleted = new List<Role>();\n\n   foreach(Role role in existingRoles)\n   {\n       if(! selectedRoles.contains(role))\n       rolesToBeDeleted.Add(role);\n   }\n\n   foreach(Role role in selectedRoles)\n   {\n       if(! existingRoles.contains(role))\n       rolesToBeAdded.Add(role);\n   }	0
24566051	24563493	How to display errors with asp.net vnext	app.UseErrorPage(ErrorPageOptions.ShowAll);	0
16332766	16332597	Print a string in Hex representation or print control characters as literals	"some text \t some text".Replace("\t",@"\t");	0
24519109	24518882	Something similar to an abstract with a definition c#	//translation of java code to proper C#\npublic abstract class EventHandler ...\n{\n    public void Handle (BankingEvent e) \n    {  \n        HouseKeeping(e); //this is required by the base class.\n        DoHandle(e); //Here, control is delegated to the abstract method.\n    }\n\n    protected abstract void DoHandle(BankingEvent e);\n}\n\npublic class TransferEventHandler: EventHandler\n{\n    protected override void DoHandle(BankingEvent e) \n    {\n       initiateTransfer(e);\n    }\n}	0
18661710	18661626	Go to new line on enter keypress in Console	while ( true )\n     {\n        var button = Console.ReadKey();\n        if ( button.Key == ConsoleKey.Enter )\n        {\n           Console.WriteLine();\n        }            \n     }	0
17433536	17433470	Extracting an int among a line of text and splitting	int release;\nbool didParse;\nwhile (true)\n{\n    string line = infil.ReadLine();\n    if (line == null) break;\n\n    string[] parts = line.Split('\t');\n\n    Movie movie = new Movie();\n    movie.title = parts[0];\n    movie.genre = parts[1];\n    didParse = Int.TryParse(parts[2], out release);\n    movie.release = (didParse) ? release: -1;\n    movie.actor = parts[3];\n    movie.director = parts[4];\n\n    AddMovie(movie);\n}	0
34137521	31974581	Unable to maximize window of an external process	[DllImport("user32.dll")]\n    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n    private const int SwShowmaximized = 3;\n    private void Run()\n    {\n        Process[] processlist = Process.GetProcesses();\n\n        foreach (Process process in processlist.Where(process => process.ProcessName == "wfica32"))\n        {\n            ShowWindow(Process.GetProcessById(process.Id).MainWindowHandle, SwShowmaximized);\n        }\n    }	0
9444619	9444424	WCF programmatic incorporation of service endpoint address	string svcUri = String.Format("net.tcp://localhost:{0}", port);\nServiceHost host = new ServiceHost(typeof(MyService));\nBinding tcpBinding = new NetTcpBinding( );\nhost.AddServiceEndpoint(typeof(IMyOtherContract),tcpBinding,\nsvcUri);\nhost.Open( );	0
16891102	16890864	Passing variables to timer event in a class	public void PID(decimal _actualSpeed, Decimal _speedRequest, out Decimal _pwmAuto, out decimal _preValReg)\n{\n    _pwmAuto = valReg;\n    _preValReg = valReg - 1;\n\n     // Because we cannot use [out] variables inside the anonymous degegates,\n     // we make a value copy\n     Decimal pwmAutoLocal = _pwmAuto;\n     Decimal preValRegLocal = _preValReg;\n\n    _timer = new System.Timers.Timer();\n    _timer.Interval = (3000);\n    _timer.Elapsed += (sender, e) => { HandleTimerElapsed(_actualSpeed, _speedRequst, pwmAutoLocal, preValRegLocal); };        \n    _timer.Enabled = true;\n    // {....}\n\n}\n\nstatic void HandleTimerElapsed(Decimal actualSpeed, Decimal speedRequst, Decimal pwmAuto, Decimal preValReg)\n{\n   // (...)\n}	0
4004434	4004348	C#:Conversion of Dictionary<String,String> to Dictionary<String, Dictionary<String,String>>	var result = ParentDict.GroupBy(p => p.Key[0].ToString())\n                        .ToDictionary(g => g.Key, g => g.ToDictionary(x => x.Key, x => x.Value));	0
26430533	26429708	Changing an FSharpList in C#	List<int> newImageList = new List<int>();\n\nfor(int i = 0; i < CurrentImage.Header.Height)\n{\n   newImageList.AddRange(PPMImageLibrary.GrayscaleImage(CurrentImage.ImageListData)); // I am assuming your GrayscaleImage method might return multiple records.\n\n}	0
4602241	4427473	How to parse the JSON Array value in C# (Windows phone 7)?	string MyJsonString ="{your JSON here}"; //JSON Result\n var ds = new DataContractJsonSerializer(typeof(City[]));\n var msnew = new MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));\n City[] items = (City[])ds.ReadObject(msnew);\n foreach (var ev in items)\n {\n   ComboCityBox.Items.Add((ev.name.ToString()));// binding name in to combobox\n }	0
6658077	6657993	Pulling data out from a DateTime object that is inside of a DataRow?	//step 0: make sure there's at least one DataRow in your results\nif (foundRows.Length < 1) { /* handle it */ }\n\n//step 1: get the first DataRow in your results, since you're sure there's one\nDataRow row = foundRows[0];\n\n//step 2: get the DateTime out of there\nobject possibleDate = row["TheNameOfTheDateColumn"];\n\n//step 3: deal with what happens if it's null in the database\nif (possibleDate == DBNull.Value) { /* handle it */ }\n\n//step 4: possibleDate isn't a DateTime - let's turn it into one.\nDateTime date = (DateTime)possibleDate;	0
26851559	26851299	Ternary operator in actualization of a loop	for (int i = ((asc) ? 0 : calendar.Length - 1);\n      ((asc) ? i < calendar.Length : i >= 0); \n      i += (asc) ? 1 : -1)	0
4471755	4469279	Select all shapes in word automation with C sharp	Sub langconvPL()\nDim mystoryrange As Range\nFor Each mystoryrange In ActiveDocument.StoryRanges\nmystoryrange.LanguageID = wdPolish\nmystoryrange.NoProofing = False\nNext mystoryrange\n\nscount = ActiveDocument.Shapes.Count\n\nFor x = 1 To scount\nActiveDocument.Shapes(x).Select\nIf ActiveDocument.Shapes(x).TextFrame.HasText = True Then\nActiveDocument.Shapes(x).TextFrame.TextRange.Select\nSelection.LanguageID = wdPolish\nEnd If\nNext x\nEnd Sub	0
7837636	7836882	How do I execute code after a certain checkbox is selected	private void CustomersDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n\n    if (e.ColumnIndex.ToString() == "9")\n    {\n        DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)CustomersDataGridView.Rows[e.RowIndex].Cells[9];\n        DataGridViewRow row = CustomersDataGridView.Rows[e.RowIndex] as DataGridViewRow;\n\n        if (Convert.ToBoolean(checkCell.EditedFormattedValue) && CustomersDataGridView.IsCurrentCellDirty)\n        {\n            //Do Work here.\n            var z = row.Cells[0].Value; // Fill in the brackets with the column you want to fetch values from\n            //z in this case would be the value of whatever was in the first cell in the row of the checkbox I clicked\n        }\n    }\n}	0
13148929	13148912	A filter/search query where results must contain all queryTerms	var people = AllPeople;\n\nforeach (var queryTerm in queryTermsList)\n{\n    people = people.Intersect(FindPerson(queryTerm));\n}	0
34001340	34001327	Is there another way to get a property of a foreach loop item?	foreach (string name in listOfItems.Select(item => item.Name))\n{\n    // ...\n}	0
29546544	29546377	Regex in between characters	string input = "<<<441234567895,ASCII,4,54657379>>>";\nstring match = input.Substring(3, input.Length - 6).Split(',')[3];	0
24312794	24311586	Casting from DataGridViewRowCollection to child of DataGridViewRow	public class MyRowData { }\npublic class MyCellData { }\npublic class MyColumnData { }\npublic static class Extender\n{\n    static Dictionary<DataGridViewRow, MyRowData> dictRow = new Dictionary<DataGridViewRow, MyRowData>();\n    static Dictionary<DataGridViewCell, MyCellData> dictCell = new Dictionary<DataGridViewCell, MyCellData>();\n    static Dictionary<DataGridViewColumn, MyColumnData> dictColumn = new Dictionary<DataGridViewColumn, MyColumnData>();\n    public static MyRowData GetMyRow(this DataGridViewRow row)\n    {\n        MyRowData myRow;\n        if (dictRow.TryGetValue(row, out myRow))\n            return myRow;\n        return null;  // or throw error or return blank MyRow...\n    }\n    public static void SetMyRow(this DataGridViewRow row, MyRowData myRow)\n    {\n        dictRow[row] = myRow;\n    }\n}	0
18671902	18671831	How to access a particular label text in Gridview	protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n{\n    Label label = (Label)this.GridView1.Rows[e.NewEditIndex].FindControl("Label4");\n    string value = label.Text;\n}	0
10036756	10036424	Custom icon for IE9 Toolbar buttons	mydll.dll,0	0
14968769	14968550	Check for negative numbers with TryParse	UInt32.TryParse(DisplayTop, out defaultTop)	0
17038505	17037472	Windows form button displays textbox and enter name to create new button	using Microsoft.VisualBasic;\n\n\n  // Click-Event\n  private void btn_GetName_Click(object sender, EventArgs e)\n  {\n        string btnTxt = Interaction.InputBox("Title", "Message", "defaultValue", 10, 10);\n\n        Button button1 = new Button();\n        button1.Location = new Point(20, 10);\n        button1.Text = btnTxt;\n        this.Controls.Add(button1);\n  }	0
17272515	17272425	Changing settings in config-file so they take immediate effect	ConfigurationManager.RefreshSection("AppSettings");	0
6129148	6128988	Getting unique data from ISingleResult	int[] uniqueHotelIds = results.Select(x => x.HotelID).Distinct();	0
20846225	20845742	How to select value of a column and add to a list?	public void LoadSearchHistory()\n{\n    var load1 = (from SearchHistory s in BookDB.SearchHistorys select s.ByAny).Distinct(_ => _.ByAny);\n    DataSearch.Items.Clear();\n    DataSearch.Items.AddRange(load1);\n}	0
1736395	1736362	How to create Simple HLSL Silverlight filter for blending/playing with/mixing 2 images?	uniform extern texture Image1;\nuniform extern texture Image2;\nsampler2D BG_Image1_Sampler = sampler_state\n{\n    Texture = (Image1);\n    MinFilter = LINEAR;\n    MagFilter = LINEAR;\n    MipFilter = LINEAR;\n};\nsampler2D BG_Image2_Sampler = sampler_state\n{\n    Texture = (Image2);\n    MinFilter = LINEAR;\n    MagFilter = LINEAR;\n    MipFilter = LINEAR;\n};\n\nfloat4 MyCalcFunction(float2 TexCoords : TEXCOORD0) : COLOR0\n{\n    float4 outColor;\n    //calculations here\n\n    return outColor;\n}\n\ntechnique BlurGlow\n{\n    pass P0\n    {\n        PixelShader = compile ps_2_0 MyCalcFunction();\n    }\n}	0
6407265	6407239	How to change the DataTable Column Name?	dataTable.Columns["Marks"].ColumnName = "SubjectMarks";	0
31853993	31830772	iOS:OCMapper: Deserialize date from json	// Convert NSString to NSDate if needed\n                    if ([propertyTypeString isEqualToString:@"NSDate"])\n                    {\n                        if ([value isKindOfClass:[NSDate class]])\n                        {\n                            nestedObject = value;\n                        }\n                        else if ([value hasPrefix:@"/Date("]){\n                            nestedObject = [self myCustomDateConversion:value];\n                        }\n                        else if ([value isKindOfClass:[NSString class]])\n                        {\n                            nestedObject = [self dateFromString:value forProperty:propertyName andClass:class];\n                        }\n                    }	0
11658603	11658084	How to return a MySqlDataReader before the reader is closed	public DataTable CreateQuery(string queryString, string connectionString )\n    {\n        DataTable results =  new DataTable("Results");\n        using (MySqlConnection connection = new MySqlConnection(connectionString))\n        {\n            using (MySqlCommand command = new MySqlCommand(queryString, connection))\n            {\n                command.Connection.Open();\n                command.ExecuteNonQuery();\n\n                using (MySqlDataReader reader = command.ExecuteReader())\n                    results.Load(reader);\n            }\n        }\n       return results;\n    }	0
16390176	16390048	Group by in Linq to Sql	var groupName = "abcd";\nvar query =\n    from submitTask in db.submit_task\n    join student in db.student\n        on submitTask.student_id equals student.id\n    join studyGroup in db.study_group\n        on student.study_group_id equals studyGroup.id\n    where studyGroup.g_name == groupName\n    group submitTask by student.s_name into g\n    let suma = g.Sum(st => st.evaluation)\n    orderby suma descending\n    select new\n    {\n        s_name = g.Key,\n        suma = suma,\n    };	0
13730121	13729997	Retrieving "images" from a JSON string retrived from Instagram API	dynamic dyn = JsonConvert.DeserializeObject(json);\nforeach (var data in dyn.data)\n{\n    Console.WriteLine("{0} - {1}",\n            data.filter,\n            data.images.standard_resolution.url);\n}	0
18984282	18983768	Culture Not Being Set In App	FrameworkElement.LanguageProperty.OverrideMetadata(\n  typeof(FrameworkElement), \n  new FrameworkPropertyMetadata(\n    XmlLanguage.GetLanguage(\n      System.Globalization.CultureInfo.CurrentCulture.IetfLanguageTag)));	0
8361674	8361580	Split string in a new line after the N word	string text = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.";\n\nint startFrom = 50;\nvar index = text.Skip(startFrom)\n                .Select((c, i) => new { Symbol = c, Index = i + startFrom })\n                .Where(c => c.Symbol == ' ')\n                .Select(c => c.Index)\n                .FirstOrDefault();\n\n\nif (index > 0)\n{\n    text = text.Remove(index, 1)\n        .Insert(index, Environment.NewLine);\n}	0
16799961	16799225	Modify StylusPoints of an InkCanvas	for(int i=0;i<INKCanvas1.Strokes.Count;i++)\n{\n   for(int j=0;j<INKCanvas1.Strokes[i].StylusPoints.Count;j++)\n   {\n      // since StylusPoint[j] is returning a reference to\n      // a struct you need to set it to a variable\n      var y = INKCanvas1.Strokes[i].StylusPoint[j].Y;\n\n      //Set it to x=200 and y= stroke y value\n      INKCanvas1.Strokes[i].StylusPoint[j] =  new StylusPoint(200,y)\n\n\n   }\n}	0
23086970	23086848	Have trouble reading a null returned from stored procedure	if (dr.Read())\n{\n    if (dr.IsDBNull(0))\n    {\n        return null;\n    }\n    else\n    {\n        region = (String)dr["region"];\n    }\n}\nelse\n{\n    // do something else as the result set is empty\n}	0
11772357	11772072	MVC Calling a view from a different controller	public class CommentsController : Controller\n{\n    public ActionResult Index()\n    { \n        return View("../Articles/Index", model );\n    }\n}\n\npublic class ArticlesController : Controller\n{\n    public ActionResult Index()\n    { \n        return View();\n    }\n}	0
3526455	3526405	How to display data from related tables in a WPF datagrid	myDataGrid.ItemsSource = myTable.DefaultView;	0
8695088	8692712	I want to Store Date specific to "Arabian Standard Time" irrespective of the time zone on web server	TimeZoneInfo UAETimeZone = TimeZoneInfo.FindSystemTimeZoneById("Arabian Standard Time");  DateTime utc = DateTime.UtcNow; \nDateTime UAE = TimeZoneInfo.ConvertTimeFromUtc(utc, UAETimeZone); \nResponse.Write("<brUTC : " + utc); \nResponse.Write("<br>Arabian Standard Time UAE : " + UAE);	0
5346288	5346158	Parse string using format template?	private List<string> reverseStringFormat(string template, string str)\n{\n    string pattern = "^" + Regex.Replace(template, @"\{[0-9]+\}", "(.*?)") + "$";\n\n    Regex r = new Regex(pattern);\n    Match m = r.Match(str);\n\n    List<string> ret = new List<string>();\n\n    for (int i = 1; i < m.Groups.Count; i++)\n    {\n        ret.Add(m.Groups[i].Value);\n    }\n\n    return ret;\n}	0
5566234	5566186	Print Pdf in C#	Process p = new Process( );\np.StartInfo = new ProcessStartInfo( )\n{\n    CreateNoWindow = true,\n    Verb = "print",\n    FileName = path //put the correct path here\n};\np.Start( );	0
24932342	24932071	Function for splitting by substring	string[] separators = {"<b>", "</b>", "\\n"};\nstring value = "Hi, my name is <b>Dan</b> and i need \\n to separate string";\nstring[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);	0
5573207	5573170	C# Editing a string to add newlines at certain lengths	string[] words = myString.Split(' ');\nStringBuilder sb = new StringBuilder();\nint currLength = 0;\nforeach(string word in words)\n{\n    if(currLength + word.Length + 1 < 30) // +1 accounts for adding a space\n    {\n      sb.AppendFormat(" {0}", word);\n      currLength = (sb.Length % 30);\n    }\n    else\n    {\n      sb.AppendFormat("{0}{1}", Environment.NewLine, word);\n      currLength = 0;\n    }\n}	0
3813277	3813240	Read date using system locale and convert it to a new format	using System.Globalization;\n\nDateTime now = DateTime.Today;\nstring local = now.ToString(CultureInfo.CurrentCulture);\nstring custom = now.ToString(new CultureInfo("ru-RU"));	0
1901680	907882	Cast a property to its actual type dynamically using reflection	using System.Reflection;\n\nnamespace TempTest\n{\n    public class ClassA\n    {\n        public int IntProperty { get; set; }\n    }\n\n    public class ClassB\n    {\n        public ClassB()\n        {\n            MyProperty = new ClassA { IntProperty = 4 };\n        }\n        public ClassA MyProperty { get; set; }\n    }\n\n    public class Program\n    {\n        static void Main(string[] args)\n        {\n            ClassB tester = new ClassB();\n\n            PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty");\n            //get a type unsafe reference to ClassB`s property\n            dynamic property = propInfo.GetValue(tester, null);\n\n            //casted the property to its actual type dynamically\n            int result = property.IntProperty; \n        }\n    }\n}	0
4462850	4462772	How can I get the size of scrollbars on a DataGridView control?	SystemInformation.HorizontalScrollBarHeight;\nSystemInformation.VerticalScrollBarWidth;	0
10657508	10657470	Event Handler for a dynamically created control	rb.CheckedChanged += rb_CheckedChanged	0
1560950	1559800	Get Custom Attributes from Lambda Property Expression	public static class ExpressionHelpers\n{\npublic static string MemberName<T, V>(this Expression<Func<T, V>> expression)\n{\nvar memberExpression = expression.Body as MemberExpression;\nif (memberExpression == null)\nthrow new InvalidOperationException("Expression must be a member expression");\n\nreturn memberExpression.Member.Name;\n}\n\npublic static T GetAttribute<T>(this ICustomAttributeProvider provider) \nwhere T : Attribute\n{\nvar attributes = provider.GetCustomAttributes(typeof(T), true);\nreturn attributes.Length > 0 ? attributes[0] as T : null;\n}\n\npublic static bool IsRequired<T, V>(this Expression<Func<T, V>> expression)\n{\nvar memberExpression = expression.Body as MemberExpression;\nif (memberExpression == null)\nthrow new InvalidOperationException("Expression must be a member expression");\n\nreturn memberExpression.Member.GetAttribute<RequiredAttribute>() != null;\n}\n}	0
13467628	13454505	get value of textbox from a another form	List<String> texts = new List<String>();\nforeach(Form form in Application.OpenForms){\n    if (form.Name == "bookForm"){\n        TextBox textbox= form.Controls[<your textbox namr>] as TextBox;\n        texts.Add(textbox);\n    }\n}	0
6200638	6199642	Leaving out <constructor-arg/> in spring framework when there's a default parameter value	Class SimpleClass\n{\n  public SimpleClass(Type1 arg1) : this(arg1, 1000)\n  {}\n\n  public SimpleClass(Type1 arg1, int interval = 1000)\n  { \n    // ...\n  }\n}	0
16299065	16299010	formatting the key value of a dictionary	dictcatalogue = dictcatalogue.ToDictionary\n       (t => t.Key.ToString().ToLower() + "-ns", t => t.Value);	0
20518685	20518606	How to connect two comboboxes in c# dynamically?	ComboBox.Items.Clear();	0
33278949	33278916	How to validate correct email address on textbox	private void txtEmail_Leave(object sender, EventArgs e)    \n {    \n    Regex mRegxExpression;    \n    if (txtEmail.Text.Trim() != string.Empty)    \n     {\n       mRegxExpression = new Regex(@"^([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$");\n\n        if (!mRegxExpression.IsMatch(txtEmail.Text.Trim()))    \n         {    \n           MessageBox.Show("E-mail address format is not correct.", "MojoCRM", MessageBoxButtons.OK, MessageBoxIcon.Error);    \n           txtEmail.Focus();    \n         }    \n     }    \n }	0
18140895	18140860	Itextsharp rendering html as html source	FontFactory.RegisterDirectories();\n        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader("<html><head></head><body><div style='font-family: Cambria'>" + text + "</div></body></html>"), null);\n        for (int k = 0; k < htmlarraylist.Count; k++)\n        {\n            cell.AddElement((IElement)htmlarraylist[k]);\n        }\n       Tbl.AddCell(cell);	0
16353862	16353828	select all fields from ilist, contains list of objects	IList<string> nameList = YourCollection.Select(item=> item.name).ToList();	0
947761	946475	Sort ListView by Date	ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);\nview.SortDescriptions.Add(new SortDescription("Date", ListSortDirection.Descending));	0
5999949	5999929	ASCII char to hexa value in C#	String.Format("{0:X}", Convert.ToInt32(letter));	0
2333157	2333114	How to add a "select all" value to a parametrized query in C# and MS SQL	IF (@Field2 = 'SomeWildcardValue')\n    SELECT Field1, Field2, Field3 FROM SomeTable\nELSE\n    SELECT Field1, Field2, Field3 FROM SomeTable WHERE Field2 = @Field2	0
2165730	2164819	How to programmatically read and change slide notes in PowerPoint	string s = slide.NotesPage.Shapes[2].TextFrame.TextRange.Text\nslide.NotesPage.Shapes[2].TextFrame.TextRange.Text = "Hello World"	0
3479273	3478874	How do I retrieve items that are tagged with all the supplied tags in linq?	List<int> myTags = GetTagIds();\nint tagCount = myTags.Count;\n\nIQueryable<int> subquery =\n  from tag in myDC.Tags\n  where myTags.Contains(tag.TagId)\n  group tag.TagId by tag.ContentId into g\n  where g.Distinct().Count() == tagCount\n  select g.Key;\n\nIQueryable<Content> query = myDC.Contents\n  .Where(c => subQuery.Contains(c.ContentId));	0
16443150	16442945	Application cannot locate resource file in Visual Studio 2010 designer	e.Graphics.DrawImage(WindowsFormsApplication1.Properties.Resources.reservoir_img, new Point(0, 0));	0
30224743	30224655	Assign Predefined Variable's Value To Object Type Variable In Boxing And UnBoxing Actions	class foo\n{  \n    public int I = 123; // is okay\n    /*The following line boxes i.*/ \n    public object O = new object();\n\n    foo()\n    {\n        // operations in a body\n        O = 123;\n        I = (int)O;  // unboxing\n    }\n}	0
23003589	23003322	how to set window location with variable in template builder format	templateBuilder.Append("function link(){\r\n");\ntemplateBuilder.Append("var a ='/productlist.aspx?wd=' + document.getelementById('abc').value;\r\n"); //assume that the value is cc\ntemplateBuilder.Append("window.location=a");	0
5761767	5761502	C# Regular Expression to find annotations	string str = "John[1234]is [2]a foo[944]l";\n        string o = Regex.Replace(str, @"\[[0-9]+\]","");\n        Console.WriteLine(o);	0
24526240	24506833	Filtering data between dates - how to get data between months?	private void dtpEndDate_ValueChanged(object sender, EventArgs e)\n{\n    //dtpStartDate and dtpEndDate are my DateTimePickers\n    string start = Convert.ToDateTime(dtpStartDate.Value).ToString("yyyy-MM-dd HH:mm:ss.ff");\n    string end = Convert.ToDateTime(dtpEndDate.Value).ToString("yyyy-MM-dd HH:mm:ss.ff");\n    dateFilter = string.Format("([{0}] >= #{1}# AND [{0}] <= #{2}#)", "Date", start, end);\n    dataTable.DefaultView.RowFilter = dateFilter;\n}	0
7797745	7797698	How to dynamic bind a Control in a GridView	Dictionary<int, int> result = new Dictionary<int, int>();\n\nuxContentByYearMonths.DataSource = from item in result \n                      select new { Key = item.Key, Value = item.Value };\n\nuxContentByYearMonths.DataBind();	0
5027347	5027301	C# clear Console last Item and replace new? Console Animation	Console.WriteLine("Searching file in...");\n        foreach(var dir in DirList)\n         {\n           Console.SetCursorPosition(1,0);\n           Console.WriteLine(dir);\n         }	0
9724328	9724246	Convert Date to Milliseconds	double milliseconds = (end - start).TotalMilliseconds;	0
909538	909521	How to store values persistenly of files in a directory?	string[] files = Directory.GetFiles(@"C:\My Directory\", "TestAssembly*.dll");	0
7188808	7188783	trying to get the number of products with same product id	products.GroupBy(x => product_id).Select(gr => new { Id = gr.Key, Count = gr.Count() }	0
15944800	14324748	Is there a ReaderWriterLockSlim equivalent that favors readers?	class AutoDispose : IDisposable \n{ \n  Action _action; \n  public AutoDispose(Action action) \n  { \n    _action = action; \n  }\n  public void Dispose()\n  {\n    _action();\n  }\n}\n\nclass Lock\n{\n  SemaphoreSlim wrt = new SemaphoreSlim(1);\n  int readcount=0;\n\n  public IDisposable WriteLock()\n  {\n    wrt.Wait();\n    return new AutoDispose(() => wrt.Release());\n  }\n\n  public IDisposable ReadLock()\n  {\n    if (Interlocked.Increment(ref readcount) == 1)\n        wrt.Wait();\n\n    return new AutoDispose(() => \n    {\n      if (Interlocked.Decrement(ref readcount) == 0)\n         wrt.Release();\n    });\n  }\n}	0
9308343	9291385	Accessing USB camera controls with AForge	VideoCaptureDevice Cam1;\nFilterInfoCollection VideoCaptureDevices;\n\nVideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);\nCam1 = new VideoCaptureDevice(VideoCaptureDevices[0].MonikerString);\nCam1.DisplayPropertyPage(IntPtr.Zero); //This will display a form with camera controls	0
27256567	27256389	Foreach loop will not read XML	foreach (XElement value in _xml.Elements("effect"))\n{\n  .....\n}	0
29416756	29416146	c# Deserialize json into List	List<RootObject> rootobject = new List<RootObject>();\n    using (var webclient = new WebClient())\n    {\n        var Ids = webclient.DownloadString(" https://api.guildwars2.com/v2/commerce/listings");\n        foreach (var id in Ids.Substring(1, s.Length-2).Split(','))\n        {\n            string url = string.Format("{0}/{1}","https://api.guildwars2.com/v2/commerce/listings",id);\n            var res = webclient.DownloadString(url);\n            var jsonObject = JsonConvert.DeserializeObject<RootObject>(res);\n            rootobject.Add(jsonObject);\n        }\n\n\n    }	0
6580383	6580061	Saving image file using Fileupoad Control and sqldatasource	private void sqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)\n{\n    e.Command.Parameters["File"].Value = bytes;\n}	0
11866600	11866453	how to loop through asp.net control dynamically?	for (int i = 1; i <= 4; i++)\n{\n PlaceHolder myControl = FindControl("placeHolder" + i) as PlaceHolder;\n //Do whatever with control;\n}	0
23687475	23687318	Nudge WPF Window	public  void NudgeWindow(Window window)\n{\n    var maxOffset = 9;\n    var minOffset = 1; \n    var originalLeft = (int) window.Left;\n    var originalTop = (int) window.Top;\n    var rnd = 0;\n\n    var RandomClass = new Random();\n    for (int i = 0; i <= 500; i++)\n    {\n        rnd = RandomClass.Next(originalLeft + minOffset, originalLeft + maxOffset);\n        window.Left = rnd;\n        rnd = RandomClass.Next(originalTop + minOffset, originalTop + maxOffset);\n        window.Top = rnd;\n    }\n    window.Left = originalLeft;\n    window.Top = originalTop;\n}	0
17497713	17497124	ViewBag and Formatting	class ManageController\n{\n    public ActionResult Password(...)\n    {	0
10511705	10511528	Query the Description Value of a Picklist in Dynamics CRM 4.0	RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();\nattributeRequest.EntityLogicalName = <your entity name>;\nattributeRequest.LogicalName = <your picklist attribute name>;\nattributeRequest.RetrieveAsIfPublished = true;\n\nRetrieveAttributeResponse response = (RetrieveAttributeResponse)metaService.Execute(attributeRequest);\nPicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;\n\n\nforeach (Option o in picklist.Options)\n{\n    // do something e.g. take o.ValueValue\n}	0
16300284	16300092	Getting the correct info from an XML document	var episodes = doc.SelectNodes(@"/Show/Episodelist/Season/episode");\nList<Episode> episodesList = new List<Episode>();\nforeach (XmlNode episode in episodes)\n{\n    episodesList.Add(new Episode()\n    {\n        Season = Int32.Parse(episode.ParentNode.Attributes["no"].Value.ToString()),\n        Title = episode.SelectNodes("title")[0].InnerText\n    });\n}	0
8061141	8061119	HTML Parser for local HTML files	HtmlDocument.LoadHtml(string html)	0
9372693	9348288	How to show database values on textboxes?	SqlConnection con = new SqlConnection(connstring);\n        con.Open();\n        SqlCommand mycomm=new SqlCommand ("SP_ShowUse",con);\n        mycomm.CommandType=CommandType.StoredProcedure;\n        mycomm.Parameters.Add("@employeeName", SqlDbType.VarChar).Value = "Anil";\n        SqlDataAdapter showdata = new SqlDataAdapter(mycomm);\n        DataSet ds = new DataSet();\n        showdata.Fill(ds);\n        txtEmployeename.Text = ds.Tables[0].Rows[0]["Emp_Username"].ToString();\n        txtBranchName.Text = ds.Tables[0].Rows[0]["Branch_BranchName"].ToString();\n        txtApprvdby.Text = ds.Tables[0].Rows[0]["Approval_ApprovedBY"].ToString();\n        binddropdownlist();\n        con.Close();	0
23580807	23575034	How do I change dynamically a background color of a WPF:s button	var eelement = gridMain.Children\n                       .OfType<Button>()\n                       .Where(b => vb.Name.Equals(_buttonName))\n                       .FirstOrDefault();\neelement.Background = Brushes.Yellow;	0
29040802	29040763	C# change 2D arrays	mapData[0, 4] = 3;	0
19395877	19395604	asp.net chart control showing incorrect tool tip date time value	MyChart.Series[Seriesname].Points[i].MapAreaAttributes = "onmouseover=\"showTooltip('#VALX',#VALY,event);\"";	0
24236782	24236683	Split Crystal Report Into Separate Files by Page	Dim rdoc As New ReportDocument    \n'------------------------------------    \n'Add your code to set rdoc object    \n'--------------------------------------    \nDim exportOpts As ExportOptions = New ExportOptions()\nDim pdfRtfWordOpts As PdfRtfWordFormatOptions = ExportOptions.CreatePdfRtfWordFormatOptions()\nDim destinationOpts As DiskFileDestinationOptions = ExportOptions.CreateDiskFileDestinationOptions()\nFor li_count As Integer = 1 To pagecount\n    pdfRtfWordOpts.FirstPageNumber = li_count\n    pdfRtfWordOpts.LastPageNumber = li_count\n    pdfRtfWordOpts.UsePageRange = True\n    exportOpts.ExportFormatOptions = pdfRtfWordOpts\n    exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat\n\n    destinationOpts.DiskFileName = "D:\report File" & li_count & ".pdf"\n    exportOpts.ExportDestinationOptions = destinationOpts\n    exportOpts.ExportDestinationType = ExportDestinationType.DiskFile\n    rdoc.Export(exportOpts)\n\nNext	0
5229455	5229258	child node removing from treeview in c#	//This will remove login\nTreeNode tn = TreeView1.FindNode("home/login"); // find particular node\nTreeView1.Nodes[0].ChildNodes.Remove(tn); // then remove from TreeView\n//This will remove register\ntn = TreeView1.FindNode("home/register"); // find particular node\nTreeView1.Nodes[0].ChildNodes.Remove(tn); // then remove from TreeView	0
13267693	13153245	How to excecute method after a delay in threading .timer?	object lockObject = new object();\n\nprivate void ProcessTimerEvent(object state) \n {\n  if (Monitor.TryEnter(lockObject))\n  {\n   try\n   {\n   // Work here\n   }\n   finally\n    {\n   Monitor.Exit(lockObject);\n    }\n   }\n  }	0
11269741	11269510	ignore file extesion in webforms routehanlder	routes.Ignore("{*images}", new { images = @".*\.(jpg|JPG|gif|GIF|png|PNG|ico|ICO)(\?.*)?" });	0
22877581	22876827	SpecFlow Step - view all	specflow.exe stepdefinitionreport MyProj.csproj /out:MySteps.html	0
4854593	4854583	How to cast string to SqlXml	CAST(MyVarcharString AS xml)	0
26930879	26929322	How to collect data table result in string array?	private void timer1_Tick(object sender, EventArgs e)\n    {\n\n        alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter EM;\n        EM = new alertDataSetTableAdapters.tbl_AutoAssignCadTeamTableAdapter();\n        DataTable dt = new DataTable();\n        dt = EM.GetEmpMail();\n\n        string[] emails = dt.AsEnumerable().Select(x => x.Field<String>("Email")).ToArray();\n\n        MailMessage loginInfo = new MailMessage();\n        foreach (var email in emails)\n        {\n            loginInfo.To.Add(email);\n        }\n\n        loginInfo.From = new MailAddress("fromID@gmail.com");\n        loginInfo.Subject = "Hai";\n\n        loginInfo.Body = "Hai";\n        loginInfo.IsBodyHtml = true;\n        SmtpClient smtp = new SmtpClient();\n        smtp.Host = "smtp.gmail.com";\n        smtp.Port = 587;\n        smtp.EnableSsl = true;\n        smtp.Credentials = new System.Net.NetworkCredential("fromID@gmail.com", "***");\n        smtp.Send(loginInfo);\n\n    }	0
11253196	11252979	Add Controls to GroupBox which was created dynamically	GroupBox groupBox1 = new GroupBox();\nGrid grid1 = new Grid();\nTextBlock MyTextBlock = new TextBlock {Text = "test"};\ngroupBox1.Width = 185;\ngroupBox1.Height = 160;\ngrid1.Height =  185;\ngrid1.Width =  160;\ngrid1.Children.Add(MyTextBlock);\ngroupBox1.Content = grid1;\nmainWindow.canvas.Children.Add(groupBox1);	0
1913044	1913027	How can you force the browser to download an xml file?	protected void DisplayDownloadDialog()\n{\n    Response.Clear();\n    Response.AddHeader(\n        "content-disposition", string.Format("attachment; filename={0}", "filename.xml"));\n\n    Response.ContentType = "application/octet-stream";\n\n    Response.WriteFile("FilePath");\n    Response.End();\n}	0
25002055	25001813	Entity Framework Ambient Transactions	using (TransactionScope scope123 = new TransactionScope())\n    {\n        using (SqlConnection connection1 = new SqlConnection(connectString1))\n        {\n            // Do some work\n            using (SqlConnection connection2 = new SqlConnection(connectString2))\n            {\n                // Do some more work\n            }\n        }	0
13019134	13011972	Acceptance testing MVC4 website with SpecFlow	using OpenQA.Selenium;\nusing OpenQA.Selenium.Chrome;\nusing NUnit.Framework;\n\nnamespace Tests.UI\n{\n    [TestFixture]\n    public class TestGoogleSearch\n    {\n        IWebDriver _driver;\n\n        [SetUp]\n        public void Setup()\n        {\n                                       //path to chrome driver exe\n            _driver = new ChromeDriver(@"C:\MyProject\lib\");\n        }\n\n        [TearDown]\n        public void Teardown()\n        {\n            _driver.Quit();\n        }\n\n        [Test]\n        public void TestSearchGoogleForTheAutomatedTester()\n        {          \n            //Given\n\n            //When\n            _driver.Navigate().GoToUrl("http://www.google.com");\n            IWebElement queryBox = _driver.FindElement(By.Name("q"));\n            queryBox.SendKeys("stack overflow");\n            queryBox.SendKeys(Keys.ArrowDown);\n            queryBox.Submit();\n\n            //Then\n            Assert.True(_driver.Title.Contains("stack overflow"));\n        }\n    }\n}	0
29306648	29306428	How can I split a string into tokens in C#?	string x="2+3-45.3+9";\nstring pattern = @"([+\-*/])";\nvar tokens = Regex.Split(x, pattern).Where(i => !string.IsNullOrEmpty(i)).ToList();	0
20699399	20699059	How to find label controls in an asp.net page	Label lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString()));\n        lblResult.Text = lblString[mylbl].ToString();	0
3782669	3782491	Convert a byte array from a C# web service in to a file using AIR 2 (AS3)	function done(serviceRespone:XML):void{\n    var d = serviceRespone.children()[0].children()[0].children()[0];\n    var bytes:ByteArray = Base64.decode(d);\n    var newFile:File = File.desktopDirectory.resolvePath("MyNewFile.txt");\n    var fileStream:FileStream = new FileStream();\n    fileStream.open(newFile, FileMode.WRITE);\n    fileStream.writeBytes(bytes);\n    fileStream.close();\n}	0
17594586	17594565	How to write a C# Regex to ensure a string starts with one char followed by 6 digits	var regex = new Regex(@"^[SRV]\d{6}$");	0
14464997	14458800	Entity Framework Many To Many between two classes	public class Game\n{\n    public int Id { get; set; }\n    public virtual ICollection<Score> Scores { get; set; }\n}\n\npublic class Player\n{\n    public int Id { get; set; }\n    public string FirstName { get; set; }\n    public string Surname { get; set; }\n    public virtual ICollection<Score> Scores { get; set; }\n}\n\npublic class Score\n{\n    public int ScoreId { get; set; }\n    public virtual  Player Player { get; set; }\n    public virtual Game Game { get; set; }\n    public int Score { get; set; }\n}	0
2124287	2124283	What's the best way to create a percentage value from two integers in C#?	mappedItems * 100.0 / totalItems	0
3831864	3831174	Getting Exception while working with multiple endpoints	StockServiceSS2Client client = new StockServiceSS2Client();	0
1804788	1804768	Get field names returned from any sql statement	Reader.GetName(columnNumber)	0
22196635	22196381	can't sort files from folder in String[] Array	IEnumerable<string> sorted = from filename in array1\n                             orderby int.Parse(Path.GetFileNameWithoutExtension(filename))\n                             select filename;	0
17748471	17748421	Play song from computer during runtime	System.IO.FileStream fs = new System.IO.FileStream(@"C:\Myfile.wav", System.IO.FileMode.Open);\n    SoundEffect mysound = SoundEffect.FromStream(fs);\n    fs.Dispose();	0
9409989	9325418	How to write a query for "orderby" in Mongo driver for C# to sort?	using (MongoDbContext dbContext = new MongoDbContext(_dbFactory))\n        {\n            var query = new QueryDocument();\n\n            var cursor =\n                dbContext.Set<TEntity>().Find(query).SetSortOrder(SortBy.Descending("ModifiedDateTime")).SetLimit(5);\n\n            foreach (TEntity entity in cursor)\n            {\n                entities.Add(entity);\n            }\n        }	0
14759875	14759633	Find row with max value for each key	var result = db.SomeTable.GroupBy(x => x.ID).Select(g => g.OrderByDescending(x => x.ID2).First());	0
25650572	25631003	How to read into an XElement a continuous stream of XML over HTTP	XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment });\n\nwhile (reader.Read())\n{\n  using (XmlReader subTreeReader = reader.ReadSubtree())\n  {\n    XElement xmlData = XElement.Load(subTreeReader);\n    Process(xmlData);\n  }\n}	0
3695872	3694439	Implementing Nhibernate one to many mapping	HasMany(x => x.Teachers).Inverse().Cascade.All();	0
2552727	2552072	Marshal struct to unmanaged array	[DllImport("blah.dll")]\nprivate static extern void Cross(ref Vector a, ref Vector b, ref Vector c);	0
1258686	1258404	Verifying a signature in java using a certificates public key	String algorithm = "MD5withRSA";\n\n// Initialize JCE provider    \nSignature verifier = Signature.getInstance(algorithm);\n\n// Do the verification   \nboolean result=false;\n\ntry {\n    verifier.initVerify(cert); // This one checks key usage in the cert\n    verifier.update(data);\n    result = verifier.verify(sigBytes);\n}\ncatch (Exception e) {\n    throw new VerificationException("Verification error: "+e, e);\n}	0
6735842	6734668	Xml Serialization of a custom XSD type	public class Case\n{\n    [XmlIgnore] public string ID;\n    [XmlIgnore] public string JuristictionID;\n\n    [XmlElement("CaseTrackingID")]\n    public CaseTrackingID SerializedCaseTrackingID\n    {\n      get \n      { \n          return new CaseTrackingID \n          { \n              ID = this.ID, \n              JuristictionID = this.JuristictionID,\n          }; \n      }\n      set \n      { \n          this.ID = value.ID; \n          this.JuristictionID = value.JuristictionID;\n      }\n    }\n}\npublic class CaseTrackingID \n{\n    [XmlElement("ID")]\n    public string ID;\n\n    [XmlElement("IDJurisdictionText")]\n    public string JurisdictionID;\n}	0
27230019	27222226	RavenDB Nested Object Projection from Static Index	public class TestIndex : AbstractIndexCreationTask<CardApplication>\n{\n   public TestIndex()\n   {\n        Map = apps =>\n            from app in apps\n            select new { State = app.State, IdentityDetails_Applicant_FirstName = app IdentityDetails.Applicant.FirstName};\n\n        Sort(c => c.State, Raven.Abstractions.Indexing.SortOptions.String);\n Store("IdentityDetails_Applicant_FirstName", FieldStorage.Yes);\n   }\n}	0
2026595	2026546	Override Get, But Not Set	public override double MyPop\n{\n    get { return _myPop; }\n}\n\npublic void SetMyPop(double value)\n{\n    _myPop = value;\n}	0
2993024	2992998	Setting a property from one collection to another collection	foreach(var pair in from m in myApps\n                    join y in yourApps on m.Key equals y.Key\n                    select new { m, y }) {\n    pair.m.Description = pair.y.Description;\n}	0
1097011	1096960	Designing a generic data class	private string FormatForListbox(object m_value)\n{\n    if (m_value is Car)\n        return "Car";\n    else if (m_value is User)\n        return "Human";\n    else\n        return "Not defined: " + m_value.GetType().ToString();\n}\n\nprivate void listBox1_Format(object sender, ListControlConvertEventArgs e)\n{\n   e.Value = FormatForListbox(e.ListItem);\n}	0
9668946	9668863	Predict the byte size of a base64 encoded byte[]	long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);	0
29428455	29368212	How to read input byte array in chunks in javascript	var chunk = file.slice(offset, offset + chunkSize);	0
6313850	6313813	LINQ find max/min value with corresponding time fields	let maxTemp = c.Max(c=>c.Temp)\nlet minTemp = c.Min(c=>c.Temp)\nselect new {\n    LogDate = g.Key,\n    MaxTemp = maxTemp,\n    MinTemp = minTemp,\n    MaxTime = g.FirstOrDefault(c=>c.Temp = maxTemp).Time,\n    MinTime = g.FirstOrDefault(c => c.Temp = minTemp).Time,\n    Rain = g.Max(c => c.Rain_today),\n       };	0
32457700	32455521	C# Recognizing Open Applications on Combobox	System.Diagnostics.Process[] procArray;\nDictionary<string,int> applications = new Dictionary<string,int>();\nprocArray = System.Diagnostics.Process.GetProcesses();\nfor (int i = 0; i < procArray.Length; i++)\n{\n     if (procArray[i].MainWindowTitle.Length > 0)\n     {\n            applications.Add(procArray[i].MainWindowTitle, procArray[i].Id);\n     }\n}\nforeach (KeyValuePair<string, int> app in applications)\n{\n    comboBox.Items.Add(app.Key);\n}	0
12991583	12991502	WP 7 multithreading, invalid cross-thread access	Deployment.Current.Dispatcher.BeginInvoke(() => { <Put your UI logic here> });	0
18936754	18936408	Starting another project within main project in a solution for windows phone	NavigationService.Navigate(new Uri("/ProjectB;component/SettingsPage.xaml", UriKind.Relative));	0
9701123	9701106	What is the syntax for a default constructor for a generic class?	public class Cell<T> \n{\n    public Cell()\n    {\n    }\n}	0
8679281	8679242	Read/writing to a file which is definitely going to be in use at random times	System.IO.FileShare.Read	0
16824343	16822956	Getting WPF Data Grid Context Menu Click Row	private void Context_Delete(object sender, RoutedEventArgs e)\n{\n    //Get the clicked MenuItem\n    var menuItem = (MenuItem)sender;\n\n    //Get the ContextMenu to which the menuItem belongs\n    var contextMenu = (ContextMenu)menuItem.Parent;\n\n    //Find the placementTarget\n    var item = (DataGrid)contextMenu.PlacementTarget;\n\n    //Get the underlying item, that you cast to your object that is bound\n    //to the DataGrid (and has subject and state as property)\n    var toDeleteFromBindedList = (YourObject)item.SelectedCells[0].Item;\n\n    //Remove the toDeleteFromBindedList object from your ObservableCollection\n    yourObservableCollection.Remove(toDeleteFromBindedList);\n}	0
2954759	2954708	Delete all files and folders in multiple directory but leave the directoy	public void DeleteDirectoryFolders(DirectoryInfo dirInfo){\n    foreach (DirectoryInfo dirs in dirInfo.GetDirectories()) \n    { \n        dirs.Delete(true); \n    } \n}\n\npublic void DeleteDirectoryFiles(DirectoryInfo dirInfo) {\n    foreach(FileInfo files in dirInfo.GetFiles()) \n    { \n        files.Delete(); \n    } \n}\n\npublic void DeleteDirectoryFilesAndFolders(string dirName) {\n  DirectoryInfo dir = new DirectoryInfo(dirName); \n  DeleteDirectoryFiles(dir)\n  DeleteDirectoryFolders(dir)\n}\n\npublic void main() {\n  List<string> DirectoriesToDelete;\n  DirectoriesToDelete.add("c:\temp");\n  DirectoriesToDelete.add("c:\temp1");\n  DirectoriesToDelete.add("c:\temp2");\n  DirectoriesToDelete.add("c:\temp3");\n  foreach (string dirName in DirectoriesToDelete) {\n    DeleteDirectoryFilesAndFolders(dirName);\n  }\n}	0
18098200	18098016	searching from list search value may contains null value	List = ListAssetDetail.Where( e => \n            (string.IsNullOrEmpty(SelectedAsset) || SelectedAsset.Equals(e.AssetName)) &&\n            (string.IsNullOrEmpty(SlectedBroad) || SlectedBroad.Equals(e.BroadcasterName)) &&\n            (string.IsNullOrEmpty(SelectedAssetfor) || SelectedAssetfor.Equals(e.AssetFrom)) &&\n            (string.IsNullOrEmpty(SelectedGenre) || SelectedGenre.Equals(e.GenreName)) &&\n            (string.IsNullOrEmpty(SelectedBoque) || SelectedBoque.Equals(e.Subcategory)) &&\n            (string.IsNullOrEmpty(SelectedContentType) || SelectedContentType.Equals(e.AssetFor)));	0
4674101	4674048	How to get DataGrid row data after user has finished editing row?	private void DataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)\n{\n  YourObject obj = e.Row.Item as YourObject;\n  if (obj != null)\n  {\n     //see obj properties\n  }\n}	0
18192947	18192763	Take the information from json	var myVids = (from vids in myJObject["response"].Skip(1)\n               where vids["vid"] != null\n               select vids["vid"])\n/*  JSON\n\n{"response":\n   [2,\n    {"vid":165971367},\n    {"vid":165971350}\n   ]\n}\n\n*/	0
1305236	1304979	2-dimensional arrays in C# and how to return the array	for(int fDim = 0; fDim < ffm.ProgramData.GetLength(0); fDim++)\n    for(int sDim = 0; sDim < ffm.ProgramData.GetLength(1); sDim++)\n        ffm.ProgramData[fDim, sDim] = "";	0
15435993	15430295	Creating a Simple ListBox	listBox.ItemSource = names;	0
23013309	22992334	Attach to process with VS2010 for CPU profiling	VSPerfCLREnv /sampleon	0
12724897	12724846	Add decimal hours to timespan	myTimeSPan + TimeSpan.FromHours((double)decimalHours);	0
6626119	6626064	Deserializing XML File using XmlSerializer.Deserialize from MemoryStream not working	ms.Seek(0, SeekOrigin.Begin)	0
30497466	30496893	Show & Hide Webbrowser in C#	this.SuspendLayout();\nthis.ShowInTaskbar = false;\nthis.WindowState = System.Windows.Forms.FormWindowState.Minimized;\nthis.ResumeLayout(false);	0
25311295	25200003	Calling a webservice from a custom sharepoint webservice	using (WebServiceClient serviceClient = new WebServiceClient(new BasicHttpBinding(), \n        new EndpointAddress("endpointAddress")))\n{\n}	0
20934785	20934727	How to populate a List<T> from a source string separated by commas and newlines	List<justme> justmes = new List<justme>();\nforeach(var line in Regex.Split(strsource, "\r\n")) {\n  string[] fields = line.Split(',');\n\n  justmes.Add(new justme {\n    field1 = fields[0];\n    field2 = fields[1];\n    // field3 = ...\n    // etc...\n  });\n}	0
10232053	10231913	Iterate a list for first half no of items	var categories = Model.Categories.OrderBy(i => i.CategoryName).ToList();\nint noOfCategories = categories.Count();\nint half = noOfCategories/2;\n\nfor (int x = 0; x < half; x++)\n{\n    var category = categories[x];\n    //your logic here\n}\nfor (int x = half; x < noOfCategories; x++)\n{\n    var category = categories[x];\n    //your logic here\n}	0
5479886	5479867	Click on button to pop-up new window with passing URL in .net c# web application	target="_blank"	0
7678415	7678217	Different colored lines in a DataGridView (DGV)	void dataGridView1_RowPrePaint(object sender,\n        DataGridViewRowPrePaintEventArgs e)\n{\n    if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == "YourConditionalValue")\n    {\n        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;\n    }\n}	0
15834728	15833525	Exception during xml processing	private static void convert(object source, FileSystemEventArgs f)\n    {\n        string FileName;\n        FileName = f.FullPath;\n        string FilePath;\n        FilePath = f.Name;\n                 var watcher = source as FileSystemWatcher;\n             string destinationFile = @"D:/GS/" + FilePath;\n\n        Thread.Sleep(1000);\n\n        //...	0
6837160	6837143	Problem with Dictionary<string, string>	node.Attributes["Titulo"].InnerText	0
19540097	19539822	Exclude items of one list in another with different object data types, LINQ?	List<Human> humans = _unitOfWork.GetHumans();\nList<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();\n\n// Get all anotherHumans where the record does not exist in humans\nvar result = anotherHumans\n               .Where(ah => !humans.Any(h => h.LastName == ah.LastName\n                               && h.Name == ah.Name\n                               && h.Birthday == ah.Birthday\n                               && (!h.PersonalId.HasValue || h.PersonalId == ah.PersonalId)))\n               .ToList();	0
11796714	11796437	Write arrays into excel file	Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();\n    xlApp.Visible = true;\n    xlApp.Workbooks.Add(misValue);\n    int nWS = xlApp.ActiveWorkbook.Worksheets.Count;\n    for (int i = nWS; i < l.Count; i++)\n        xlApp.ActiveWorkbook.Worksheets.Add(misValue, misValue, misValue, misValue);\n    int iWS = 1;\n    foreach (float[] ff in l)\n    {\n        Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.ActiveWorkbook.Worksheets[iWS++];\n        int idxRow = 1;\n        foreach (float aFloat in ff)\n            ws.Cells[idxRow++, 1] = aFloat;\n    }	0
2930951	2930627	How to extract a GUID from a Win32 DLL or OCX	Imports TLI 'from c:\windows\system32\tlbinf32.dll\n\nDim reglib As TLI.TLIApplication = New TLI.TLIApplicationClass()\nDim DLLPath As String = "c:\mycomponent.ocx"\nMsgBox(reglib.TypeLibInfoFromFile(DLLPath).GUID.ToString())	0
13890202	13890125	Retrieve String Containing Specific substring C#	string input = "ABCDED 0000A1.txt PQRSNT 12345";\n string filename = input.Split(' ').FirstOrDefault(f => System.IO.Path.HasExtension(f));	0
11877709	11877688	Int.Parse in C# throwing a Format Exception	int x = int.parse(value.TrimStart('0'));	0
13006958	13006931	C#: WriteFile with Line Breaks	List<string> list = new List<string>(\n                    File.ReadAllLines(fileName,\n                                      Encoding.GetEncoding(1252))\n                                );\n// ... do something (editing) ... \nFile.WriteAllLines(fileName, list);	0
29544703	29544275	C# finding percent of matched words between two string	var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);\n\n    var res1 = (from string part in l\n        select new\n        {\n            list = part,\n            count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)\n\n        }).OrderByDescending(p=> p.count).First();\n\n    Console.Write(res1.count);	0
740354	740342	Best way to create a folder and upload a image to that folder in ASP.NET?	public void EnsureDirectoriesExist()\n        {\n\n                // if the \pix directory doesn't exist - create it. \n                if (!System.IO.Directory.Exists(Server.MapPath(@"~/pix/")))\n                {\n                    System.IO.Directory.CreateDirectory(Server.MapPath(@"~/pix/"));\n                }\n\n        }\n\n        protected void Button1_Click(object sender, EventArgs e)\n        {\n\n\n                if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")\n                {\n                    // create posted file\n                    // make sure we have a place for the file in the directory structure\n                    EnsureDirectoriesExist();\n                    String filePath = Server.MapPath(@"~/pix/" + FileUpload1.FileName);\n                    FileUpload1.SaveAs(filePath);\n\n\n                }\n                else\n                {\n                    lblMessage.Text = "Not a jpg file";\n                }\n\n\n        }	0
2564644	2564630	How can I add the column data type after adding the column headers to my datatable?	loadDT.Column[1].DataType = typeof(int);	0
3904753	3904623	Deleting double-entries from ListBox	foreach(int item in yourList)\n{\nif(!listBox1.Items.Contains(item))\n{\n//add\n}\n}	0
17335074	17289853	Exception of Unauthorized while using MostRecentlyUsedList in metro apps	The source of code describes writes bytes of file in ZipArchiveEntry,\nhence I used a helper method GetByteFromFile(), which takes  StorageFile object and returns me byte[] array.	0
23832002	23831367	Is it safe to put TryDequeue in a while loop?	while(cq.IsEmpty())\n{\n    // Maybe sleep / wait / ...\n}\n\nif(cq.TryDequeue(out retValue))\n{\n...\n}	0
32995624	32987119	Validate model on specific string values	using System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.ComponentModel.DataAnnotations;    \n\nnamespace MyProject.Models.Validation\n{\n\n    public class StringRangeAttribute : ValidationAttribute\n    {\n        protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n        {\n\n            if(value.ToString() == "M" || value.ToString() == "F")\n            {\n                return ValidationResult.Success;\n            }\n\n\n            return new ValidationResult("Please enter a correct value");\n        }\n    }\n}	0
9557887	9556871	how to implement generic repository pattern and UoW in NHibernate 3.2	public interface IRepository<T>\n{\n    IEnumerable<T> GetAll();\n    T GetByID(int id);\n    T GetByID(Guid key);\n    void Save(T entity);\n    void Delete(T entity);\n}\n\npublic class Repository<T> : IRepository<T>\n{\n    protected readonly ISession Session;\n\n    public Repository(ISession session)\n    {\n        Session = session;\n    }\n\n    public IEnumerable<T> GetAll()\n    {\n        return Session.Query<T>();\n    }\n\n    public T GetByID(int id)\n    {\n        return Session.Get<T>(id);\n    }\n\n    public T GetByID(Guid key)\n    {\n        return Session.Get<T>(key);\n    }\n\n    public void Save(T entity)\n    {\n        Session.Save(entity);\n        Session.Flush();\n    }\n\n    public void Delete(T entity)\n    {\n        Session.Delete(entity);\n        Session.Flush();\n    }\n}	0
1675433	1675400	XML Timezone - Daylight Saving	TimeZoneInfo.Local	0
30351918	30351400	Excel interop doesn't accept ranges with commas	using Microsoft.Office.Interop.Excel;\n\npublic void RangeWithCommas() {\n    var excel = new Application();\n    var wb = excel.Workbooks.Add(xlWBATemplate.xlWBATWorksheet);\n    var ws = (Worksheet)wb.Worksheets[1];\n\n    var rangestring = String.Join((string)excel.International[XlApplicationInternational.xlListSeparator], new [] {"A1","A2"});\n\n    var range = ws.Range[rangestring];\n    Console.WriteLine(range.Address[false,false]);\n\n    ws.Delete();\n    wb.Close(false);\n    excel.Quit();\n}	0
25873475	25873395	retrieving identical rows of some columns from a list	var result = from row in listStructures \n             group row by new {row.Code, row.Range, Row.Unit, Row.Type} into grp\n             let Item = grp.Key\n             select new {Code=Item.Code, Range=Item.Range, Unit=Item.Unit, Type=Item.Type, Repeated=grp.Count()}	0
13697754	13697315	How to Stream an image to a client app in asp.net web api?	stream.Position = 0;\nresponse.Content = new StreamContent(stream);	0
24725959	24725263	How to check for user's first access to site?	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            //take HttpContext.Current.User.Identity.Name here\n            //and rebuild values in Session if session is empty\n        }\n    }\n}	0
34130511	34130459	Sort my IEnumerable<Group> in alphabetical order	return View(_service.List().OrderBy(o=>o.Name).ToList());	0
7904724	7904656	Reflection: Invoke method, passing a delegate as parameter	//here you pass the methods Action1 and Action2 as parameters\n//to the delegates - if you need to construct these by reflection\n//then you need to reflect the methods and use the\n//Delegate.CreateDelegate method.\nvar param1 = new Action<Args1>(Action1);\nvar param2 = new Action<Args1>(Action2);\n//instance of Host on which to execute\nvar hostInstance = new Host();\nvar method = typeof(Host).GetMethod("Method1", \n  BindingFlags.Public | BindingFlags.Instance);\n\nmethod.Invoke(hostInstance, new object[] { param1, param2 });	0
28142884	28142850	Reverse the order of comma separated string of values	var reversedStr = string.Join(",", strSubjectIDs.Split(',').Reverse());	0
4016494	4016462	How can I parse the information from this XML?	/ipb/profile/contactinformation/contact[title='AIM']/value	0
13681100	13681052	Formatting the BackColor of a gridview	if (e.Row.RowType == DataControlRowType.DataRow)\n {\n        //DataBinder.Eval(e.Row.DataItem,"Column to check"))\n        // based on that you can set the value\n        e.Row.BackColor = Drawing.Color.Yellow\n }	0
9120227	9120088	How to join 3 tables with lambda expression?	var myList = Companies\n    .Join(\n        Sectors, \n        comp => comp.Sector_code,\n        sect => sect.Sector_code,\n        (comp, sect) => new { Company = comp, Sector = sect })\n    .Join(\n        DistributionSectorIndustry.Where(dsi => dsi.Service == "numerical"), \n        cs => cs.Sector.Sector_code,\n        dsi => dsi.Sector_code,\n        (cs, dsi) => new { cs.Company, cs.Sector, IndustryCode = dsi.Industry_code })\n    .Select(c => new {\n        c.Company.Equity_cusip,\n        c.Company.Company_name,\n        c.Company.Primary_exchange,\n        c.Company.Sector_code,\n        c.Sector.Description,\n        c.IndustryCode\n});	0
3839414	3839309	How can I group a List<K> by a List<T>, depending on the results of an expression<T, K>?	IDictionary<Period, IEnumerable<Interval>> dictionary = \n     periods.ToDictionary(p => p, \n                          p => intervals.Where(i => PeriodApplies(p, i.Date)));	0
8544525	8544480	How to sort datatable on occurance of string	var strings = new[] { "ccc", "asaa", "asaa", "aaa", "aaa", "aaa" };\nvar sortedStrings = strings\n  .GroupBy(s => s)\n  .OrderByDescending(g => g.Count())\n  .SelectMany(g => g);	0
196963	196518	Problem with dynamic controls in .NET	protected override void OnPreRender(EventArgs e)\n{\n    base.OnPreRender(e);\n    ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2]        \n    tempLink.ID = "valueLinkButton"; // Not persisted to ViewState\n    Controls.Clear();\n    Controls.Add(tempLink);\n    tempLink.Value = "new value";  // Persisted to ViewState\n    tempLink.Text = "Click";       // Persisted to ViewState\n}	0
6875713	6875631	Max length of base64 encoded salt/password for this algorithm	(n + 2 - ((n + 2) % 3)) / 3 * 4	0
24633247	24632703	Failure sending e-mail in asp.net	MailMessage msg = new MailMessage();\n        msg.From = new MailAddress(email);\n        msg.To.Add(new MailAddress("To_address"));\n        msg.Subject = "You have a WebMail!!";\n        msg.IsBodyHtml = true;\n        msg.Body = "Message";\n        SmtpClient smtp = new SmtpClient();\n        smtp.Credentials = new NetworkCredential("your mail address", "your password");\n        smtp.Host = "host name";\n        smtp.Port = "host number";\n        smtp.EnableSsl = false;\n        smtp.Send(msg);	0
8289277	8287738	How can I enforce a contract within a struct	struct NonNullInteger\n{\n    private readonly int _valueMinusOne;\n\n    public int Value\n    {\n        get { return _valueMinusOne + 1; }\n    }\n\n    public NonNullInteger(int value)\n    {\n        if (value == 0)\n        {\n            throw new ArgumentOutOfRangeException("value");\n        }\n\n        _valueMinusOne = value - 1;\n    }\n}	0
2524938	2524906	How do I invoke a static constructor with reflection?	myClass.TypeInitializer.Invoke(null, null)	0
22679841	22678796	How to get an email from SQL Server using C#	strSQL = @"SELECT TOP 1 ContactEmail FROM vwApprenticeshipContactDetails WHERE ApprenticeshipID = @ApprenticeshipID";\nSqlCommand cmd2 = new SqlCommand(strSQL, cnn);\ncmd2.Parameters.Add("@ApprenticeshipID", SqlDbType.Int).Value = wsAppID;\nusing (SqlDataReader rdr = cmd2.ExecuteReader())\n{\n  string fldEmail = "support@domain.com.au";   //this is as a default in case the sql above does not return a value\n  while (rdr.Read())\n  {\n    fldEmail = rdr.GetSqlValue(0).ToString();\n  }\n}	0
5304138	5303632	Change local windows user properties using C#	DirectoryEntry localDirectory = new DirectoryEntry("WinNT://"Environment.MachineName.ToString());\nDirectoryEntries users = localDirectory.Children;\nDirectoryEntry user = users.Find("userName");	0
14794341	14794146	Check if list contains all words in string	KeyWords.Clear();	0
17757335	17757284	Return some values from a database query	User user=null;\nif (reader.Read())\n{\n        int UserID = Convert.ToInt32(reader["UserID"]);\n        int IsAdmin = Convert.ToInt32(reader["IsAdmin"]);\n        int IsActivated = Convert.ToInt32(reader["IsActivated"]);\n        string Nickname = reader["Nickname"].ToString();\n        string FirstName = reader["FirstName"].ToString();\n        string LastName = reader["LastName"].ToString();\n        string Email = reader["Email"].ToString();\n        string Password = reader["Password"].ToString();\n        string DateRegistered = reader["DateRegistered"].ToString();\n\n        user = new User(UserID, IsAdmin, IsActivated, null, Nickname, FirstName, \n}\nelse \n{\n\n  // handle error no user\n}\n\nif (reader.Read())\n{\n   // handle more than one user error\n}\n\n// other stuff close connect and reader etc.\n\nreturn user;	0
11149016	11148974	Need C# Regex for replacing spaces inside of strings	str = Regex.Replace(str, @"""[^""]+""", m => m.Value.Replace(' ', '|'));	0
13618779	13564246	Logout with facebook not working in monotouch app	NSHttpCookieStorage storage = NSHttpCookieStorage.SharedStorage;\n\nforeach (NSHttpCookie cookie in storage.Cookies) \n{\n    if(cookie.Domain == ".facebook.com")\n    {\n        storage.DeleteCookie(cookie);\n    }\n}	0
25803016	25802930	Access arraylist from another method in C#	namespace Crossword\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n                ArrayList array = DataFileReader.DataFile(args[0]);\n                String characters = args[0];\n                ArrayList wordLength = WordLength(characters,array); // this will pass the variables to your method\n        }\n        public static ArrayList WordLength(String characters, ArrayList array)\n        {\n\n            ArrayList wordLength = new ArrayList();\n            foreach (string line in array)\n                if (line.Length == characters.Length){\n                    wordLength.Add(line);\n                    Console.WriteLine(line);\n          }\n\n            return wordLength;\n        }\n}	0
15028740	15028630	How i Show DateTime in Label	Double days = 0;\nDateTime cs= DateTime.Now;\nbool daysOk = Double.TryParse(textbox1.Text, out days);\nif (daysOk) \n{\n   cs = cs.AddDays(days);\n}\nelse\n{\n   textbox1.Text = "invalid days";\n}	0
2854713	2854669	how do i read strings from text files?	using System;\nusing System.IO;\n\nclass Test \n{\n\n    public static void Main() \n    {\n        string path = @"c:\temp\MyTest.txt";\n        try \n        {\n            if (File.Exists(path)) \n            {\n\n\n\n            using (StreamReader sr = new StreamReader(path)) \n            {\n                while (sr.Peek() >= 0) \n                {\n                    string s = sr.ReadLine();\n                     string [] split = s.Split(';');\n\n                     //now loop through split array\n                     //split[0] is server\n                    // split[1] is user id\n                }\n            }\n          }\n        } \n        catch (Exception e) \n        {\n            Console.WriteLine("The process failed: {0}", e.ToString());\n        }\n    }\n}	0
2835525	2835438	Data table in win form	private void pasteToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        // create dataset to hold csv data:\n        DataSet ds = new DataSet();\n        ds.Tables.Add();\n        ds.Tables[0].Columns.Add();\n        ds.Tables[0].Columns.Add();\n        ds.Tables[0].Columns.Add();\n        ds.Tables[0].Columns.Add();\n        ds.Tables[0].Columns.Add();\n        ds.Tables[0].Columns.Add();\n\n        string[] row = new string[1];\n\n        // read csv data from clipboard\n        IDataObject t = Clipboard.GetDataObject();\n        System.IO.StreamReader sr =\n                new System.IO.StreamReader((System.IO.MemoryStream)t.GetData("csv"));\n\n        // assign csv data to dataset      \n        while (!(sr.Peek() == -1))\n        {\n            row[0] = sr.ReadLine();\n            ds.Tables[0].Rows.Add(row);\n        }\n\n        // set data source\n        dataGridView1.DataSource = ds.Tables[0];\n    }	0
4763408	4763376	How do I programmatically access data about my database?	using(var connection = new SqlConnection(connectionString)) {\n    connection.Open();\n    using(var command = connection.CreateCommand()) {\n        command.CommandText = "SELECT * FROM SYS.TABLES";\n        using(var reader = command.ExecuteReader()) {\n            while(reader.Read()) {\n                Console.WriteLine(reader["name"]);\n            }\n        }\n    }\n}	0
11387200	11387181	What is the name of a pair of brackets inside a C# function that only exists for an extra level of scope?	if (...)	0
10398869	10398836	Convert byte data to string output like in hex editor	public static string ToString(byte[] buffer)\n{\n    return BitConverter.ToString(buffer);\n}	0
10821419	10820273	Regex to extract initials from Name	Regex initials = new Regex(@"(\b[a-zA-Z])[a-zA-Z]* ?");\nstring init = initials.Replace(nameString, "$1");\n//Init = "JD"	0
25883873	25883817	How to check a variable holds Instance or Type in c#	if (object2 is Test) { ... }\nif (object2 is Type) { ... }	0
30245497	30245464	c# remove string with quotes from string	return textWriter.ToString().Replace(@"xmlns=""http://www.rar.org/xyz/""", "");	0
4415555	4415526	How do I merge the following 4 SPs to make it one or may be 2?	CREATE PROCEDURE [Schema1].[SuperDuperProcedure]\n(\n  @UserID             bigint = NULL,\n  @UserAddDetailID    bigint = NULL,\n  @IsB                bit,\n  @IsSh               bit\n)\nAS\nBEGIN\n  UPDATE\n    Schema1.UserAddDetails\n  SET\n    IsDefault = 0\n  WHERE\n    UserID = @UserID\n    AND\n    (IsB = @IsB OR IsSh = @IsSh)\n\n  UPDATE\n    Schema1.UserAddDetails\n  SET\n    IsDefault = 1\n  WHERE\n    UserAddDetailID = @UserAddDetailID\n    AND\n    (IsB = @IsB OR IsSh = @IsSh)\nEND	0
20831267	20462920	Unable to Set Values for unbound columns in C1 Flexgrid	Hashtable _hash = new Hashtable();\n\n    private static DataTable CreateTable<T>(List<T> List)\n    {\n        DataTable OutTable = new DataTable();\n        using (var reader = ObjectReader.Create(List))\n        {\n            OutTable.Load(reader);\n        }\n        return OutTable;\n    }\n\n    private void c1FlexGrid1_GetUnboundValue(object sender, C1.Win.C1FlexGrid.UnboundValueEventArgs e)\n    {\n        DataRowView drv = (DataRowView)c1FlexGrid1.Rows[e.Row].DataSource;\n\n        e.Value = _hash[e.Row.ToString() + "|" + e.Col.ToString()];\n    }\n\n    private void c1FlexGrid1_SetUnboundValue(object sender, C1.Win.C1FlexGrid.UnboundValueEventArgs e)\n    {\n        DataRowView drv = (DataRowView)c1FlexGrid1.Rows[e.Row].DataSource;\n        _hash[e.Row.ToString() + "|" + e.Col.ToString()] = e.Value;\n    }	0
25537266	25537124	Log4net use the same appender config in xml to log to multiple files	Log4net.Appender.AppenderSkeleton	0
13948342	13948299	Linq grouping items	var query = from x in Mylist\n            group x by new { x.SiteName, x.PersonName } into g\n            select new { \n               g.Key.SiteName,\n               g.Key.PersonName,\n               totalnumberOfClicks = g.Sum(i => i.numberOfClicks)\n            };	0
15932483	15903678	Change page in chm file via command line	private void btnHelpTopic1_Click(object sender, EventArgs e)\n    {\n        // sHTMLHelpFileName_ShowWithNavigationPane = "CHM-example_ShowWithNavigationPane.chm"\n        // This is a HelpViewer Window with navigation pane for show case only \n        // created with Microsoft HTMLHelp Workshop\n        helpProvider1.HelpNamespace = Application.StartupPath + @"\" + sHTMLHelpFileName_ShowWithNavigationPane;\n        Help.ShowHelp(this, helpProvider1.HelpNamespace, @"/Garden/tree.htm");\n    }\n\n    private void btnHelpTopic2_Click(object sender, EventArgs e)\n    {\n        helpProvider1.HelpNamespace = Application.StartupPath + @"\" + sHTMLHelpFileName_ShowWithNavigationPane;\n        Help.ShowHelp(this, helpProvider1.HelpNamespace, @"/Garden/flowers.htm");\n    }	0
20517700	20495105	Basic authentication in php webservice with C #	public class serverBasicAuthentication : br.com.cra21.cramg.servercra\n    {\n        protected override WebRequest GetWebRequest(Uri uri)\n        {\n            HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri);\n            if (PreAuthenticate)\n            {\n                NetworkCredential networkcredential = base.Credentials.GetCredential(uri,"Basic");\n                if (networkcredential != null)\n                {\n                    Byte[] credentialBuffer = new UTF8Encoding().GetBytes(networkcredential.UserName + ":" + networkcredential.Password);\n                    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);\n                }\n                else\n                   throw new ApplicationException("No network credentials") ;\n            }\n            return request; \n        }\n    }	0
24656688	24656398	How to calculate resolution based on megapixels and aspect ratio	int nXPixels=5000;  // original image Width\nint nYPixels=4000;  // original image Height\n//float fRatio=5000/4000;    // original image aspect ratio\nint nNewPixelResolution=600000; // 0.6mpx new resolution\nint nOldPixelResolution=nXPixels*nYPixels;\ndouble conv = Math.sqrt((double)nNewPixelResolution/(double)nOldPixelResolution);\nint nNewXPixels= (int)Math.round(nXPixels*conv);\nint nNewYPixels= (int)Math.round(nYPixels*conv);	0
19398057	19397771	How to get only revised words from word document?	using Word = Microsoft.Office.Interop.Word;\n\n//...\n\nforeach (Word.Section s in final.Sections)\n{\n    foreach (Word.Revision r in s.Range.Revisions)\n    {\n             counter += r.Range.Words.Count;\n             if (r.Type == Word.WdRevisionType.wdRevisionDelete) // Deleted\n                delcnt += r.Range.Words.Count;\n             if (r.Type == Word.WdRevisionType.wdRevisionInsert) // Inserted\n                inscnt += r.Range.Words.Count;\n             if (r.Type == Word.WdRevisionType.wdRevisionProperty) // Formatting (bold,italics)\n                inscnt += r.Range.Words.Count;\n    }\n}	0
9416186	9416069	Get child node value from xml which have single attributes	var xml = @"<?xml version=""1.0""?>\n<Root>\n    <Response ID=""xyx66860512"" PID=""13681839"" ERROR=""0"" STATUS=""5""/>\n</Root>";\n\nvar doc = XDocument.Parse(xml);\n\nvar element = doc.Root.Element("Response");\nvar id = element.Attribute("ID").Value;\nvar pid = Int32.Parse(element.Attribute("PID").Value);\nvar error = element.Attribute("ERROR").Value;\nvar status = element.Attribute("STATUS").Value;	0
5726747	5726680	Is there a throws keyword in C# like in Java?	/// <exception cref="InvalidOperationException">Why it's thrown.</exception>	0
17947243	17947149	Check bitwise flags that cannot co-exist with each other	bool check(int flags) {\n    int A = 1;\n    int B = 2;\n    int C = 4;\n\n    return \n        flags == 0 ||\n        flags == A ||\n        flags == B ||\n        flags == C;\n}	0
9839899	9839802	How to get to the maximum value before executing code in C#?	Boolean doIt = false;\n\n// your outer loop\n{\n  if (varA ==8.0f) {\n    doIt = true;\n  }\n\n  if ((doIt) && (varA <= 8.0f)) {\n    varA -= 2.0f;\n  }\n}	0
3313083	3312706	format a url address in asp.net	yourUrl = String.Format("<A href=../category/{0}.aspx>{1}</a>,",category.Titulo.Trim().ToLower(),category.Nombre.Trim());	0
1686958	1686943	opening a new page?	onclick="window.open('default.aspx','','height=300,width:220,scrollbars=yes,resizable=yes,top=0,left=0,status=yes');"	0
20116899	20116771	Better way to get all enum constants from combined enum value	List<Type> types = Enum\n                     .GetValues(typeof(Type))\n                     .Cast<Type>()\n                     .Where(val => (val & type) == val)\n                     .ToList();	0
20881153	20881076	Convert a long string to List<string[]> in C#	var list = "c,c,c,c,c,c\r\nc,c,c,c,c,c\r\n.....c,c,c,c,c\r\n"\n    .Split('\n')\n    .Select(s => s.Trim().Split(','));	0
12302318	12302289	Convert from object {object[]} to List<int>	List<int> intList = objectArray.OfType<int>().ToList();	0
12826149	12825787	Building a grid defining specific columns and rows from a stored procedure	DataRowCollection rowCollection = spDataTable.Rows; \nDataTable dt = new DataTable(); \n\nforeach(DataRow dr in spDataTable.Rows)\n{\n        object projectId = dr["ProjectID"];\n        if (projectId == null)\n        {\n            dt.Rows.Add(dr);\n        }\n     }	0
4506756	4506705	Deserialize json string	class A\n{\n     public object[] terms {get; set; }\n}	0
16082688	16057446	How to print a PDF file displayed in the WPF WebBrowser control	private void Print_Click(object sender, RoutedEventArgs e)\n{\n    // Try to print it as Html\n    var doc = webBrowser.Document as IHTMLDocument2;\n    if (doc != null)\n    {\n        doc.execCommand("Print", true, 0);\n        return;\n    }\n\n    // Try to print it as PDF\n    var pdfdoc = webBrowser.Document as AcroPDFLib.AcroPDF;\n    if (pdfdoc != null)\n    {\n        pdfdoc.Print();\n    }\n}	0
10203779	10187636	How can I implemente Save/Discard functionality with NHibernate?	session.IsDirty	0
10007744	10007480	Adding options to a selectfield ExtJS	Ext.getCmp('category_id').getStore().loadData(data, true);	0
34539735	34515749	How can I display the full image a when user clicks the thumbnail image ASP.NET	function Test2(url) {
\n            var img = new Image();
\n            var bgDiv = document.getElementById("divBackground");
\n            var imgDiv = document.getElementById("divImage");
\n            var displayFull = document.getElementById("displayFull");
\n            var imgLoader = document.getElementById("imgLoader");
\n            imgLoader.style.display = "block";
\n            img.onload = function() {
\n              displayFull.src = img.src.replace("Thumbs/", ""); <--- Here
\n              displayFull.style.display = "block";
\n              imgLoader.style.display = "none";
\n            };
\n
\nimg.src = url;	0
17144153	17144081	Is it possible to use a variable number in the name of a variable name?	var dict = new Dictionary<int,string>();\ndict.Add(1,"String Number 1");\ndict.Add(2,"String Number 2");\ndict.Add(3,"String Number 3");\n\nint test = int.Parse(textBox1.Text);\nMessageBox.Show(dict[test]);	0
235274	234268	Custom MembershipProvider Initialize method	string configPath = "~/web.config";\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(configPath);\nMembershipSection section = (MembershipSection)config.GetSection("system.web/membership");\nProviderSettingsCollection settings = section.Providers;\nNameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;\nInitialize(section.DefaultProvider, membershipParams);	0
12982017	12964647	Using a C# dll in Borland C++	CoInitialize(NULL);\n_MyClassPtr obj;\nHRESULT ptr = obj.CreateInstance(__uuidof(MyClass));	0
14620146	14619990	Are multiple last used paths in a FileDialog possible?	var myDirectory = Properties.Settings.Default.Directory;	0
27017014	27016930	Consuming a webservice returning array in C #	WS_FUNCSPONTO.TESTEARRAY[] qwert = new WS_FUNCSPONTO.TESTEARRAY[10];\nqwert = Recebe_Cadastro.PEGAINFORM("00");	0
8198619	8198187	Finding results using the EF4 in a table where they don't exist or don't match a value	var query = (from a in ctx.TransactionTable\n              from b in ctx.MappingTable.Where(x => x.TransactionId== a.TransactionId).DefaultIfEmpty()\n                 where a.StoreID!=storeID\n                     select new\n                               {\n                                  Transactions = a,\n                                  Mapping = b\n                               }).ToList();	0
9497103	9496276	Bind to grid by selecting data from tow different tables?	CREATE procedure SP_GetEmployeeRequests\n(\n     @ApproverName varchar (50)\n)\nAS\nBEGIN\n\nSELECT PTS_Employee.Emp_Username, PTS_Requests.Request_RequestedAmount, PTS_Requests.Request_Description, PTS_BalanceTracker.Balance_BalanceAmount, PTS_BalanceTracker.Balance_LastApproval, PTS_BalanceTracker.Balance_LastUpdated\nFROM PTS_Employee  JOIN PTS_Requests  ON PTS_Employee.Emp_ID = PTS_Requests.Emp_ID \nJOIN PTS_BalanceTracker  ON PTS_BalanceTracker.Emp_ID = PTS_Requests.Emp_ID\nJOIN PTS_Approval  ON PTS_Approval.Approval_ApprovedID  = PTS_Requests.Approval_ApprovedID\nWHERE PTS_Approval.Approval_ApprovedBY = @ApproverName \n\nEND\nGO	0
13807351	13807298	how to remove <br> tag using C#?	string txt = WebUtility.HtmlDecode(text);\n    txt = txt.Replace("<br>", Controlchars.NewLine);\n    txt = txt.Replace("<br/>", Controlchars.NewLine);\n    txtb_Description.Text = txt;	0
13842902	13842822	Extract XML From Binary	using (var stream = new MemoryStream(<byte[] here>))\n    using (var reader = new StreamReader(stream))\n    {\n        var buffer = new char[41];\n        stream.Seek(<offset where string begins>, SeekOrigin.Begin);\n        reader.Read(buffer, 0, 41);\n        <mystringVariable> = new string(buffer);\n    }	0
3567135	3566623	Get element by ClientInstanceName	var grid = eval("MyClientInstanceName");\nif(grid) { \n  // your code\n}	0
25761329	25758410	do you want to open or save from localhost while trying to upload the file	return Json("FileUploaded successfully", "text/html", System.Text.Encoding.UTF8,\n                    JsonRequestBehavior.AllowGet);	0
6467147	6459589	How do you get an email address within a string	public static MatchCollection CheckEmail(string email)\n{\n  Regex regex = new Regex(@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", RegexOptions.IgnoreCase);          \n  MatchCollection matches = regex.Matches(email);\n\n  return matches;\n}	0
4332823	4332577	Retriving Values from a datable to another datatable using C#	string[] columnsToCopy = { "id" };\n        DataTable tableNew = dtSource.DefaultView.ToTable("NameOfTableToCreate", false, columnsToCopy);	0
15790242	15790007	Mock a method with List<int> as parameter and return List<> with Moq	mock.Setup(users => users.GetListAll(It.IsAny<List<int>>()))\n            .Returns<List<int>>(ids =>\n                {\n                    return _users.Where(user => ids.Contains(user.Id)).ToList();\n                });	0
10893972	10893860	How to filter gridview from textbox?	protected void Button1_Click(object sender, EventArgs e)\n{\n\n    DataSet ds = new DataSet();\n    SqlConnection myCon = new SqlConnection(connectionstring);\n    SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);\n    adapter.Fill(ds);\n    DataView view = new DataView();\n    view.Table = ds.Tables[0];\n    view.RowFilter = "ColumnName = " + TextBox1.Text.Trim();\n    GridView1.DataSource = view;\n    GridView1.DataBind();\n}	0
13730444	13729072	Find a point C on line segment AB such that line segment DC is perpendicular to AB. D is a point outside the line segent in C#	Point intersectionPoint(Point A, Point B, Point C) {\n    //check for slope of 0 or undefined\n    if (A.Y == B.Y) return new Point (C.X, A.Y);\n    if (A.X == B.X) return new Point (A.X, C.Y);\n    //slope = (y1 - y2) / (x1 - x2)\n    double slopeAB = (A.Y - B.Y) / (A.X - B.X);\n    //perpendicular slope is the negative reciprocal\n    double slopeCD = -1 / slopeAB;\n    //solve for b in y = mx + b of each line\n    //  b = y - mx\n    double bAB = A.Y - slopeAB * A.X;\n    double bCD = C.Y - slopeCD * C.X;\n    double dX, dY;\n    //intersection of two lines is m1x + b1 = m2x + b2\n    //solve for x: x = (b2 - b1) / (m1 - m2)\n    //find y by plugging x into one of the equations\n    dX = (bCD - bAB) / (slopeAB - slopeCD);\n    dY = slopeAB * dX + bAB;\n    return new Point(dX, dY);\n}	0
9004785	8991389	Conversion of Google Map webpart into Bing Map webpart	System.Web.UI.ClientScriptManager csm = Page.ClientScript;\n StringBuilder builder = new StringBuilder();\n string SCRIPT_NAME = "MapScript" + this.ID;\n    {// your java script}\ncsm.RegisterClientScriptBlock(this.GetType(), SCRIPT_NAME, builder.ToString(), false);	0
33028335	33028292	Add a Css Class to Ajax Tab Container In C#	container.CssClass = "ClassName";	0
12384577	12384532	How design an entity to entity relation in my SQL database	GROUP\nName\n...\n\n\nGROUPTOGROUP\nBaseGroupID\nConnectedToGroupID\nTrue/False	0
9236920	9235812	How to read the selected item from a listpicker in WP7?	Categories selectedCategory = CategoryPicker.SelectedItem as Categories;	0
21028582	21028472	Nomalize Two Strings Then Compare	var array1 = a.Where(x =>char.IsLetterOrDigit(x)).ToArray();\nvar array2 = b.Where(x => char.IsLetterOrDigit(x)).ToArray();\nvar normalizedStr1 = new String(array1).ToLower();\nvar normalizedStr2 = new String(array2).ToLower();\n\nString.Compare(normalizedStr1,normalizedStr2);	0
20757420	20756463	Restoring Previous cell value in c# datagridview	if (string.IsNullOrEmpty(e.FormattedValue.ToString()))\n{\n     dataGridView1.CancelEdit();\n}	0
13348822	13348781	How to get UI elements in diffrent Thread?	TextBox.Text	0
9644408	9644311	Sending ctrl-space with SendKeys in C#?	SendKeys.SendWait("^( )");	0
19619826	19619575	C#, Sorting a LINQ result alphabetically then, sort it according to Search Key	var products = this.databaseManager.Products.Where(x => x.Name.Contains(searchKey)).Select(x => new {Name=x.Name,Index=x.Name.IndexOf(searchKey)}).OrderBy(a=>a.Index).ToList();	0
31552169	31552021	My program closes as soon as it opens	class Program\n{\n    int answer;\n    int number;\n    int numbera;    \n    public void detail()\n    {\n        Console.WriteLine("Multiplication Calculator.");    \n\n        string input;\n\n        Console.WriteLine("Number 1: ");\n        input = Console.ReadLine();\n        Int32.TryParse(input, out number);\n\n        Console.WriteLine("Number 2: ");   \n        input = Console.ReadLine();\n        Int32.TryParse(input, out numbera);\n    }\n    public void calculations()\n    {\n        answer = number * numbera;\n    }\n    public void display()\n    {\n        Console.WriteLine();\n        Console.WriteLine(answer);\n    }\n}\nclass call\n{\n    static void Main()\n    {\n        Program r = new Program();\n        r.detail();\n        r.calculations();\n        r.display();\n    }\n}	0
20244044	20243646	Polling database to print out files	static void Main(string[] args) {\n    System.Timers.Timer DatabaseTimer = new System.Timers.Timer();\n    //set the inteval to 20 seconds. Interval is in milliseconds so 20 sec = 20000 milisec\n    DatabaseTimer.Interval = 20000;\n    //start the timer\n    DatabaseTimer.Enabled = true;\n    //set the eventhandler, which is called every 20 seconds\n    DatabaseTimer.Elapsed += new System.Timers.ElapsedEventHandler(DatabaseTimer_Elapsed);\n}\nstatic void DatabaseTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {\n    //Your database query / printing here\n}	0
9250568	9250238	Detecting text view change in Gtk and Mono	bool changed = false;\n\ntxtEditor.Buffer.Changed += new EventHandler(onChangeEvent); \n\npublic void onChangeEvent(object sender,EventArgs e)   {\n  changed = true;\n}	0
3696167	3696004	How to prohibit comma as decimal separator	using System;\nusing System.Globalization;\n\nclass Test\n{\n    static void Main(string[] args)\n    {\n        string text = "19,2";\n        double value;\n        bool valid = double.TryParse(text, NumberStyles.Float,\n                                     CultureInfo.InvariantCulture,\n                                     out value);\n        Console.WriteLine(valid); // Prints false\n    }\n}	0
4236317	4236303	I want to make my own c# debugger - how would one do that? What tools should I be using?	csc.exe	0
1325413	1325400	Parsing DateTime strings	DateTime.ParseExact("6/15/2009", "d", CultureInfo.GetCultureInfo("en-US"));	0
14546499	14434767	how to set the default text value on the data-grid view particular column	if (dataGridView1.Columns[i].ValueType == typeof(DateTime))\n{\n    dataGridView1.Columns[ColumnIndex].DefaultCellStyle.Format = "dd/MM/yyyy";\n}	0
5168579	5168499	Unmanaged DLL project and managed WinForms application in one solution	Project properties>Build events>Post build event command line	0
18986521	18962330	How can I cancel a ColumnChanging event and have the bound control show the original value instead of the rejected change?	private void MyTable_ColumnChanged(object sender, DataColumnChangeEventArgs e) {\n   if (e.Column == MyTrueFalseColumn)\n      CheckboxChanged(e);\n}\n\nprivate void CheckboxChanged(DataColumnChangeEventArgs e) {\n   if (!(bool)e.ProposedValue && MustRemainChecked()) {\n      MyCheckbox.Checked = true;\n      MyCheckbox.DataBindings[0].WriteValue();\n   }\n}	0
21728435	21728385	What is the use of XML comments in C#	/// <summary>\n///  This class performs an important function.\n/// </summary>\npublic class MyClass{}	0
29387590	29082169	Paging in nested gridview webforms	protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)\n{\n\n    GridView gv = (GridView)sender;               \n    gv.PageIndex = e.NewPageIndex;        \n    BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);\n\n\n}	0
288529	288513	How do I determine if a given date is the Nth weekday of the month?	private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){\n  int d = date.Day;\n  return date.DayOfWeek == dow && (d-1)/7 == (n-1);\n}	0
24085068	24083242	LINQ for two tables where date range between two values	// Declaration of start and end date.\nvar StartDate = DateTime.Now;\nvar EndDate = DateTime.Now.AddDays(1);\n\n// Get the items in db.Ttem that are reserved in the time period\n// between StartDate and EndDate.\nvar query = from i in db.Ttem\n            join ir in db.ItemReserved\n            on i.ItemID equals ir.ItemId \n            where ir.StarDate >= Start && ir.EndDate<= End\n            select i.ItemID;\n\n// Get the items in db.Ttem that are not reserved in the time period\n// between StartDate and EndDate.\nvar result = db.Ttem.Where(x=>!query.Contains(x));	0
9165432	9164118	How to get the ID of button contained in parent page from User Control?	protected void Page_Load(object sender, EventArgs e)\n{\n\n    Button btnFound = (Button)this.FindControl("myButton");\n    if (btnFound != null)\n    {\n        Response.Write("Found It!");\n    }\n}\n\nprotected void Page_Init(object sender, EventArgs e)\n{\n    Button btn = new Button()\n    {\n        ID = "myButton",\n        Text = "Click Me"\n    };\n\n    this.Controls.Add(btn);\n}	0
2527744	2527700	Change color of text within a WinForms RichTextBox	int length = richTextBox.TextLength;  // at end of text\nrichTextBox.AppendText(mystring);\nrichTextBox.SelectionStart = length;\nrichTextBox.SelectionLength = mystring.Length;\nrichTextBox.SelectionColor = Color.Red;	0
12347521	12325611	how to set VS2010 settings considering utf8 so i could send data to mysql database as they are	string cs = @"server=localhost;userid=root;password=xxx;database=table;CharSet=UTF8";	0
31202970	31202236	XSD to describe a web page for parsing into C# objects	public class Element\n{\n    public string Name { get; set; }\n    public string Id { get; set; }\n    public string XPath { get; set; }\n\n    [XmlElement(ElementName="TextBox", Type = typeof(TextBox))]\n    [XmlElement(ElementName="Page", Type = typeof(Page))]\n    [XmlElement(ElementName="Button", Type = typeof(Button))]\n    [XmlElement(ElementName="Dialog", Type = typeof(Dialog))]\n    public Element Parent { get; set; }\n\n    [XmlArray("Children", IsNullable = false)]\n    [XmlArrayItem(Type = typeof(TextBox))]\n    [XmlArrayItem(Type = typeof(Page))]\n    [XmlArrayItem(Type = typeof(Button))]\n    [XmlArrayItem(Type = typeof(Dialog))]\n    public Collection<Element> Children { get; set; }\n}	0
7011855	7011177	Hide DropDownList in ComboBox	public class NoDropDownBox : ComboBox\n{\n    public override bool PreProcessMessage(ref Message msg)\n    {\n        int WM_SYSKEYDOWN = 0x104;\n\n        bool handled = false;\n\n        if (msg.Msg == WM_SYSKEYDOWN)\n        {\n            Keys keyCode = (Keys)msg.WParam & Keys.KeyCode;\n\n            switch (keyCode)\n            {\n                case Keys.Down:\n                    handled = true;\n                    break;\n            }\n        }\n\n        if(false==handled)\n            handled = base.PreProcessMessage(ref msg);\n\n        return handled;\n    }\n\n    protected override void WndProc(ref Message m)\n    {            \n        switch(m.Msg)\n        {\n            case 0x201:\n            case 0x203:\n                break;\n\n            default:\n                base.WndProc(ref m);\n                break;\n        }\n    }\n}	0
13033789	13030664	Handle Pinch, Zoom, Rotate Gestures in WinRT App	ManipulationMode =\n    ManipulationModes.TranslateX |\n    ManipulationModes.TranslateY |\n    ManipulationModes.Rotate |\n    ManipulationModes.Scale |\n    ManipulationModes.TranslateInertia;	0
1527119	1526594	Access all Data from databound RadGrid?	for (int i = 0; i < Ragrid.Pagecount; i ++)\n{\n    RadGrid.CurrentPageIndex = i;\n    RadGrid.Rebind;\n\n    foreach(GridDataItem item in RadGrid.Items)\n    {\n         do stuff\n    }\n}	0
14861832	14861665	What would be the Regex to match a word wrapped in double brackets	string input = "I love to [[verb]] while I [[verb]].";\nstring pattern = @"(\[\[.+?\]\])";\n\nstring[] matches = Regex.Split( input, pattern );\n\nforeach (string match in matches)\n{\n    Console.WriteLine(match);\n}	0
8878121	8877946	WPF , MVVM , MasterDetailPage , Designing	MasterDetailsViewModel\n{\n  MenuViewModel\n  CurrentPageViewModel\n  SliderViewModel\n}	0
26966415	26860596	Removal of Duplicate Rows from Data table Based on Multiple columns	dt_Barcode = dt_Barcode.AsEnumerable().GroupBy(r => new { ItemID = r.Field<Int64>("ItemID"), PacktypeId = r.Field<Int32>("PackTypeID") }).Select(g => g.First()).CopyToDataTable();	0
33818710	33817635	What is the regex expression that will add some character after my match.Value	Text = line.Substring(match.Index, Math.Min(line.Length - match.Index, 30))	0
10274367	10274151	select nodes with specific child node when xml can be different	DateTime date;\nvar nodes = allNodes.Descendants("updatedDate")\n                    .Where(x => DateTime.TryParse(x.Value, out date)\n                                && date > dateToCompare)\n                    .Select(x => x.Parent);\n\nXElement updatedNodes = new XElement("UpdatedNodes", nodes);	0
20264653	20264343	How to get values of WPF ComboBox by index	var v = cmbSubject.Items.GetItemAt(0);\n            DataRowView dv = (DataRowView)v;\n            string strCmbItem = dv[1].ToString();	0
14482840	14482742	How to make a information image	picture.BorderStyle = BorderStyle.None;	0
5322044	5299652	Creating a class for storing extra information and linking it to a host class	class LayerItem\n{\n    public string Name { get; set; }\n\n    public event EventHandler ItemEvent;\n    protected virtual void OnItemEvent(EventArgs e)\n    {\n    if (this.ItemEvent != null)\n        this.ItemEvent(this, e);\n    }\n}\n\nclass ImageLayerItem : LayerItem\n{\n    private Image _image;\n\n    public ImageLayerItem()\n    {\n        //here create Image element and think of rendering it.\n        _image = new Image();\n        //attach event handlers.\n        _image.Click += ... //don't forget to call LayerItem.OnItemEvent() inside the event handler.\n    }\n}	0
24653048	24652791	Getting a direct reference to a private member name instead of using string	public string GetMemberName<T>(Expression<Func<T>> memberExpression)\n    {\n        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;\n        return expressionBody.Member.Name;\n    }	0
30832693	30809180	Validating currency allows more than two decimal places	decimal value = 123.456m;\nif (GetDecimalPlaces(value) > 2)\n{\n    // Error\n}\n\nint GetDecimalPlaces(decimal d)\n{\n    int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];\n}	0
3824536	3824484	Create object of parameter type	public interface ISettable\n{\n    string ID { get; set; }\n    string Val { get; set; }\n}\n\npublic void LoadData<T>(string id, string value) where T : ISettable, new()\n{\n    this.Item.Add(new T { ID = id, Val = value });\n}	0
31156597	31155974	How to get installed apps list with Unity3D?	AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");\nAndroidJavaObject currentActivity = jc.GetStatic<AndroidJavaObject>("currentActivity");\n\nAndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");\n\nint flag = pluginClass.GetStatic<int>("GET_META_DATA");\n\nAndroidJavaObject[] arrayOfAppInfo = packageManager.Call<AndroidJavaObject[]>("getInstalledApplications", flag);	0
27885591	27885511	Can someone please suggest a better naming scheme when class variables are same as formal parameters received by a constructor in c#	class Sample\n{\n    private int m_varOne;\n    private int m_varTwo;\n\n    Sample(int varOne, int varTwo)\n    {\n        this.m_varOne = varOne;\n        this.m_varTwo = varTwo;\n    }\n}	0
18860161	18766412	MongoDB C# driver - how to query a property on an array of subdocuments	var ancestorsQuery = Query<ProjectRef>.EQ(pr => pr.Id, rootProjectId);\nvar finalQuery = Query<Project>.ElemMatch(p => p.Ancestors, builder => ancestorsQuery));	0
17153593	17153544	List Conversion in C# with null values	var result = yourlist.Select(x=> string.IsNullOrEmpty(x) ? (double?)null : Convert.ToDouble(x)).ToList();	0
26178883	26178790	How to resize the datagridview on button click?	private void btnResize_Click(object sender, EventArgs e)\n{\n  dataGridView1.Height = //set an int  desired height;\n  dataGridView1.Width = //set an int desired Width;\n}	0
19519704	19517707	Sort list based on group count	var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())\n                       .SelectMany(x => x).ToList();	0
31944587	31944410	Best way to pass a SQL query other than a stored procedure	QueryKey Query\n-------- --------------------------------------\nquery1   SELECT A, B, C FROM MyTable1 WHERE ...\nqueryX   SELECT X, Y, Z FROM MyTable2 WHERE ...	0
5853223	5853141	Collection requiring two keys to a unique value 	Dictionary<Tuple<int, int>, char>	0
20982454	20982318	Search and select multiples with where linq/lambda expressions	var clientsNamedMax = db.Clients.Include(x => x.FirstNames).Include(x => x.Addresses).Where(x => x.FirstNames.Any(y => y.Name.ToLower().Trim() == "max")).ToList();	0
2979953	2979927	How do I split a short into its two bytes?	IPAddress.HostToNetworkOrder	0
25791827	25791671	Foreach in a Hashset	public class Team : IEnumerable<HeroStats>\n{\n    private HashSet<HeroStats> stats = new HashSet<HeroStats>();\n\n    public IEnumerator<HeroStats> GetEnumerator()\n    {\n        return stats.GetEnumerator();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return stats.GetEnumerator();\n    }\n}	0
4352707	4352697	Cant cast float to int if object	int fd = (int)(float)jf;	0
27928572	27928338	Implement Custom DateTime Converter with JSON.NET	public class CurrentAlarms\n{\n    public string Desc { get; set; }\n    public string Station { get; set; }\n    [JsonConverter(typeof(InvalidDataFormatJsonConverter))]\n    public DateTime When { get; set; }\n\n    public CurrentAlarms() { }\n\n    public CurrentAlarms(string desc, string station, DateTime when)\n    {\n        Desc = desc;\n        Station = station;\n        When = when;\n    }\n}\n\nclass InvalidDataFormatJsonConverter : JsonConverter\n{\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        // implement in case you're serializing it back\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue,\n        JsonSerializer serializer)\n    {\n        var dataString = (string) reader.Value;\n        DateTime date = parseDataString;             \n\n        return date;\n    }\n\n    public override bool CanConvert(Type objectType)\n    {\n        return true;\n    }\n}	0
25405063	25404414	PhantomJS getScreenshot() gets only part of page	_driver.Manage().Window.Size = new Size(1366, 2732);	0
27334258	24661011	Prevent Window Centering in XNA	g.ApplyChanges	0
7527831	7521516	C# images inside of a ListView	**Fill ListView :**   \n For(int i=0; i<fileLocationArray.Count();i++)\n    {\n    System.Windows.Controls.Image imgControl=new System.Windows.Controls.Image();\n    BitmapImage imgsrc = new BitmapImage();\n   imgsrc.BeginInit();\n   imgsrc.UriSource=fileLocationArray[i];\n                    imgsrc.EndInit();\n    imgControl.source=imgsrc;\n    listView.Items.Add(imgControl);\n\n    }\n\n    **After filling ListView control  create event  listView SelectionChanged**\n    **imgContolShow   // this control show selected image**\n\n    void listw_SelectionChanged(object sender, SelectionChangedEventArgs e)\n        {\n           imgContolShow.Source = ((System.Windows.Controls.Image)listwiev.SelectedItem).Source;  \n        }	0
11232483	11232442	Validate a textbox in a windows form	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n   button1.Enabled = !(textBox1.Text == String.Empty);\n}	0
21626241	21625539	Dynamic casting to a generic type	var switchType = activity.GetType();\nvar prop = switchType.GetProperty("Cases", System.Reflection.BindingFlags.Public \n            | System.Reflection.BindingFlags.Instance); //move it outside of the method and use the same property for every time you call the method since it's performance expansive.\nbool isSwitch = (switchType.IsGenericType && switchType.GetGenericTypeDefinition() == typeof(Switch<>));\n\nif (isSwitch)\n{\n        IEnumerable dictionary = prop.GetValue(activity,null) as IDictionary;\n        foreach (var item in dictionary.Values)\n        {\n            ProcessActivity(item, dataSets, context);\n        }\n}	0
32641820	32641559	Unable to encode byte array to UTF8 then decode it back to bytes	var salt = Convert.ToBase64String(encryptedPassword.Salt);\nvar key = Convert.ToBase64String(encryptedPassword.Key);\n...\nvar saltBytes = Convert.FromBase64String(salt);\nvar keyBytes = Convert.FromBase64String(key);	0
20069006	13414320	To open outlook new email window with content already filled	Example: \n\n<a href="mailto:someone@example.com?Subject=Hello%20again&body=This%20is%20body">\nSend Mail</a>	0
10235043	10234910	Changing the colour of certain ListView columns	ListViewItem item1 = new ListViewItem( "Item 1"); \nitem1.SubItems.Add( "Color" ); \nitem1.SubItems[1].ForeColor = System.Drawing.Color.Blue;\nitem1.UseItemStyleForSubItems = false; \nlistView1.Items.Add( item1 );	0
3138461	3138416	C# in VS2005: is there set style notation for integers?	if (Enumerable.Range(2, 8).Concat(new [] { 1, 12 }).Contains(number)) {\n    ....\n}	0
33084889	33084456	How to write an array data base on polymorphism subclass detail in c#	if (choice == 3)\n        {\n            Console.WriteLine("=====Payroll Summary=====");  \n            Console.WriteLine("You need to pay " + (project[0].paY) + " Baht for " + project[0].EmpName);\n            Console.WriteLine("You need to pay " + (salary[0].Pay(salary[0].Hour) + " Baht for " + salary[0].EmpName);\n        }	0
25359687	25358286	Retain time stamp of a downloaded file in FTP	File.SetCreationTime("File1.gz", someDate);	0
2737606	2737595	Adding a TimeSpan to a given DateTime	Console.WriteLine("A day after the day: " + date.Add(t).ToString());	0
8625300	8625187	Executing a SQL command using Entity Model	var ris= dc.ExecuteStoreQuery<goodType>("select * from good where goodcode in (select good ref from goodgroup where goodgroupref=263))");	0
20323290	20323231	Append mutiple tables to one datatable in c#	dt1.Merge(dt2);	0
16705888	16705809	Binary file writing the same data format in VB6 and C#	Const fileName As String = "C:\Temp\fromVB.bin"\nDim stringVal As String = ""\nDim stringVal2 As String = "Hello"\nDim i As Integer = 25\n\nUsing writer As New BinaryWriter(File.Open(fileName, FileMode.Create))\n    writer.Write(stringVal)\n    writer.Write(stringVal2)\n    writer.Write(i)\nEnd Using	0
26135001	26134177	How to get user from Kentico	var users = UserInfoProvider.GetUsers();\n                DataTable dt = new DataTable();\n                dt.Columns.AddRange(new DataColumn[2] { new DataColumn("FullName"), new DataColumn("UserName") });\n\n            foreach (UserInfo aUser in users.TypedResult)\n            {\n                DataRow newRow = dt.NewRow();\n                newRow["FullName"] = aUser.FullName;\n                newRow["UserName"] = aUser.UserName;\n                dt.Rows.Add(newRow);\n            }\n\n            GridView1.DataSource = dt;\n            GridView1.DataBind();	0
20109547	20109014	Build Linq Expression to return all questions that have keywords assigned to it that match a list of keyword ids?	var keywordIdsArray = keywordIds.Select(x => x.Id).ToArray();\n\nExpression<Func<QuestionEntity, bool>> expression = \n    q => q.QuestionsKeywords.Any(qk => keywordIdsArray.Contains(qk.Keyword.Id));	0
5577735	5570368	c# - Yes / No value of System	class Program {\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);\n    [DllImport("kernel32")]\n    static extern IntPtr LoadLibrary(string lpFileName);\n    static void Main(string[] args) {\n        StringBuilder sb = new StringBuilder(256);    \n        IntPtr user32 = LoadLibrary(Environment.SystemDirectory + "\\User32.dll");\n        LoadString(user32, 805, sb, sb.Capacity);\n        YES = sb.ToString().Replace("&","");\n        LoadString(user32, 806, sb, sb.Capacity);\n        NO = sb.ToString().Replace("&","");\n    }            \n    public static string YES;\n    public static string NO;\n}	0
19727268	19726862	Unity3d: clamp magnitude to only x axis	Vector3 clampVel = rigidBody.velocity;\nclampVel.x = Mathf.Clamp(clampVel.x, min, max);\n\nrigidBody.velocity = clampVel;	0
18505298	18483354	Get Assembly of program from a DLL	Assembly assembly = Assembly.LoadFrom("Uranium.exe");\nType type = assembly.GetType("Uranium.Util");\nMethodInfo methodInfo = type.GetMethod("SendClient");\n\nmethodInfo.Invoke(null, new object[] { Packet.GetData() });	0
8986618	8986555	how to write javascript validation for dropdown selected index changed event in c#	protected void drpdes_SelectedIndexChanged(object sender, EventArgs e)\n    {\n         int flgchk = 0;\n          if(drpdes.selectedvalue == "0")\n           {\n                flgchk = 1;\n              /// this will call your alert method. \n                string errorScript = "<script type=\"text/javascript\">" + \n                      "YourFunctionNameHere() " + \n                      "</script>";\n                    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", errorScript);\n           }\n        // my code for binding second dropdown\n    }	0
14293803	14293036	Launching the Windows Store listing from Win RT / Windows 8 app	Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store:REVIEW?PFN=PACKAGENAME"));	0
21162556	21160149	Prevent unwanted close of program on crash (including with TRY-CATCH)	(Exception ex)	0
26313263	26311138	How to handle SQL Exception for Logon failure	public void combobox_SelectedIndexChanged()\n    {\n        string selectedCountry = "country"; //build actual connection string as you do now.\n        string connectionString = string.Format("Data Source={0};Initial Catalog=Detrack;Integrated Security=True;", selectedCountry);\n        var sqlCon = new SqlConnection(connectionString);\n        using (sqlCon)\n        {\n            // Disable some controls\n            try\n            {\n                sqlCon.Open();\n            }\n            catch (SqlException ex)\n            {\n                MessageBox.Show(ex.Message);\n                // Disable "OK"/"Next" button\n                return;\n            }\n            finally\n            {\n                ///Enable controls\n            }\n\n            sqlCon.Close();\n\n            // "OK"/"Next" button\n        }\n    }	0
6800362	6800243	Access the Body of Request (text/xml)	byte[] bytes = Request.BinaryRead(Request.ContentLength);\nSystem.Text.Encoding enc = System.Text.Encoding.UTF8;\n_XmlData = enc.GetString(bytes);	0
4994107	4994059	BeginUpdate() EndUpdate for a UserControl	private void BeginUpdate()\n{\n  this.SuspendLayout();\n  // Do paint events\n  EndUpdate();\n}\n\nprivate void EndUpdate()\n{\n   this.ResumeLayout();\n   // Raise an event if needed.\n}	0
6434613	6434601	How do I rewrite this to be more LINQy?	foreach (var ev in e)\n{\n    ev.EventGroups = g.Where(groups => ev.EventID == groups.EventID)\n                      .ToList();\n}	0
3959291	3959281	How to show date in specific format?	Date.ToString("dd MMMM yyyy dddd");	0
18639424	18639391	How to use the array of strings and display it line by line	aTextbox.Text = string.Join(Environment.NewLine, list.ToArray());	0
13076492	13076336	Compare data from two columns from data table against variables in ASP.NET C#	foreach (object obj in (ShoppingCart)Session["cart"].Values)\n{\n  DataTable dt = new DataTable();\n  int productID = (int)obj;\n  string query = "SELECT * FROM Products WHERE ProductID = ?";   //yuck, oledb params\n  using (OleDbConnection conn = new OleDbConnection (connStr))\n  {\n     //dont hold me to this syntax, its from my head\n     OleDbCommand cmd = new OleDbCommand(query, conn);\n     cmd.Parameters.Add(productID);\n     OleDbDataAdapter da = new OleDbDataAdapter();\n     da.SelectCommand = cm;   \n     da.Fill(dt);\n  }\n  //do something with the data table\n}	0
27030581	27030556	pass data to custom class in list	while(reader.Read())\n{ \n  event = new Events();\n  event.eventID = reader["EventID"].ToString();\n  ...\n  eventList.add(event);\n}	0
20148883	20148703	Implementing Progress Bar Winform	private int emailLength;\n        private ProgressBar ProgressBar1 = new ProgressBar();\n\n         public void Main()\n         {\n            emailLength = 16;\n            progressBar1.Maximum = emailLength;\n            sendEmails();\n         }\n         public void sendEmails()\n         {\n             for (int i = 0; i <= emailLength; i++)\n             {\n                //Send Emails Here\n                progressBar1.Increment();\n             }\n         }	0
16122044	16121998	JSonNet object serialization	[JsonIgnore]\npublic Faculty Faculty { get; set; }\n\n[JsonProperty("Faculty")]\npublic string FacultyName { get { return Faculty.Name; } }	0
8136829	8135945	How to two-way bind object to combo Box in windows application	List<T> won't do the job, you want BindingList<T>	0
18647917	18647801	Generic Method That Inverts Booleans	public T Filter<T>(string target, string actual, T value)\n    {\n        return _match(target, actual) ? value : default(T);\n    }\n\n    public bool Filter(string target, string actual, bool value) \n    { \n        return _match(target, actual) ? value : !value;\n    }\n\n    private bool _match(string target, string actual)\n    { \n        return !string.IsNullOrEmpty(target)\n            && !string.IsNullOrEmpty(actual)\n            && string.Equals(target, actual, StringComparison.CurrentCultureIgnoreCase);\n    }	0
7017405	7004470	Monotouch - CancelLocalNotification	foreach(UILocalNotification sNote in UIApplication.SharedApplication.ScheduledLocalNotifications)\n    {\n        if(sNote.FireDate == DateTime.Now)\n        {\n            //Cancel the Notification'\n            UIApplication.SharedApplication.CancelLocalNotification (sNote);\n        }\n    }	0
24284790	24284724	closing a pop-up when clicking elsewhere windows phone 7	private void UserControl_LostFocus(object sender, RoutedEventArgs e)\n    {\n        Popup test = this.Parent as Popup;\n        test.IsOpen = false;\n    }	0
31245954	31245654	How to stop a timer running inside a class C#	public volatile System.Timers.Timer theTimer1;	0
29588031	29578611	Getting specific columns from Database with EF	var user = db.Users\n             .Where(u => u.login.Equals(login))\n             .Select(usr => new {\n                 login = usr.login,\n                 email = usr.email,\n                 friends = usr.Friends.Select(fr => new {\n                     // your friend info here Ex.:\n                     email = fr.email,\n                 })\n              }).FirstOrDefault();	0
10130417	10130169	How can I accomplish decorating @Model items more efficiently?	public static MvcHtmlString DisplayDeleteCheckFor<TModel, TValue>(\n    this HtmlHelper<TModel> html,\n    Expression<Func<TModel, TValue>> expression, bool condition) {\n\n     var value = html.DisplayFor(expression).ToString();\n     var style=condition ? "style=\"background-color:gray\"" : string.Empty;\n\n     return MvcHtmlString.Create(\n         string.Format("<span {0}>{1}</span>", style, value));\n}	0
8322762	8322464	Converting TreeNode to DataTable Dynamically	private void getNodeList()\n{\n    //This will hold your node text\n    List<string> nodeTextList = new List<string>();\n    //loop through all teeview nodes\n    foreach(TreeNode rootNode in treeView.Nodes)\n    {\n       //Add root node to list\n       nodeTextList.Add(rootNode.Text);\n       //Do recursive getter to get child nodes of root node\n       getChildNodes(rootNode, nodeTextList);\n\n    }\n    //Do with nodeTextList what ever you want, for example add to datatable.\n}\n\nprivate void getChildNodes(TreeNode rootNode, List<string> nodeTextList)\n{\n   foreach(TreeNode childNode in rootNode.Nodes)\n   {\n       //Add child node text\n       nodeTextList.Add(childNode.Text);      \n       getChildNodes(childNode, nodeTextList);\n   }\n}	0
2283685	2283629	creating actions based on specific fields having specific values	class ConditionalCallback()\n{\n     public Predicte<Item>   Predicate {get; set;}\n     public Action<Item>     Callback  {get; set;}\n}\n\nList<ConditionalCallback> callbacks = new List<ConditionalCallback>();\n\npublic AddCallBack(Predicte<Item> pred, Action<Item> callback)\n{\n    callbacks.Add(new ConditionalCallback { \n                              Predicate = pred, \n                              Callback = callback\n                               });\n}\n\n\nvoid HandleItem(Item item)\n{\n     foreach(var cc in callbacks)\n         if (cc.Predicate(item))    \n             cc.Callback(item);\n}\n\n// \n\nAddCallBack( i=> i.ID1 = 2 && i.ID2 = 160 && i.ID3 = anything", MyCallback);	0
24624036	24620639	Windows Phone 8 - Pass data from a textbox to a textblock on another page	Page1.xaml.cs\n\n        private void Button_Click(object sender, RoutedEventArgs e)\n        {\n            NavigationService.Navigate(new Uri("/Page2.xaml?myNumber=" + TextBox1.Text, UriKind.Relative));\n        }\n\nPage2.xaml.cs\n\n        protected override void OnNavigatedTo(NavigationEventArgs e)\n        {\n            base.OnNavigatedTo(e);\n            string QueryStr = "";\n            NavigationContext.QueryString.TryGetValue("myNumber",out QueryStr);\n            TextBlock1.text = ((int.Parse(QueryStr)) / 2).ToString();\n    }	0
30217113	30216525	running c# console application from excel and wait for app to finish	Dim id As Integer\nDim wsh As Object\nSet wsh = VBA.CreateObject("WScript.Shell")\nDim waitOnReturn As Boolean: waitOnReturn = True\nDim windowStyle As Integer: windowStyle = 1\n\nid = wsh.Run("""C:\MyFolder\bin\Debug\MyApp.exe"" /PARA1 " & p1 & " /PARA2 " & p2, windowStyle, waitOnReturn)	0
1349861	1349856	How do you add a separator to a WinForms menu in C#?	ContextMenu.MenuItems.Add("-");	0
5252024	5251979	linq on nullable datetime	Time2 = (a.Time2).Value	0
11552396	11550095	How to print title page with printdocument?	// set to false before calling PrintDocument.Print()\nbool firstPagePrinted = false;\nprivate void printdocument_PrintPage(object sender, PringPageEventArgs e)\n{\n  if(!firstPagePrinted)\n  {\n    // TODO: whatever you want\n    e.Graphics.DrawString("Header page", printFont, \n      Brushes.Black, e.MarginBounds.left, e.MarginBounds.Top, new StringFormat();\n    firstPagePrinted = true;\n    e.HasMorePage = true;\n  }\n  // do 2nd and subsequent pages here...\n}	0
1995571	1995527	How might I create and use a WebBrowser control on a worker thread?	var thread = new Thread(objThreadStart);\nthread.SetApartmentState(ApartmentState.STA);\nthread.Start();	0
33737951	33737925	How can I add 1 minute to current time that I get? webdriver c#	string date1 = System.DateTime.Now.AddMinutes(1).ToString("HH:mm");	0
33889154	33888817	Multiply matrix by user input	n = userinput;\ni=0;\nint[,] result;\n\ndo\n  i+=1;\n  result = MultiplyMatrix(result, n);\nwhile i<n\n\n\nint[,] MultiplyMatrix(adjmatrix, n){\n   (multiply)  \n   return resultMatrix };	0
943192	943171	expose and raise event of a child control in a usercontrol in c#	public class UserControl1 : UserControl \n{\n    // private Button saveButton;\n\n    public event EventHandler SaveButtonClick\n    {\n        add { saveButton.Click += value; }\n        remove { saveButton.Click -= value; }\n    }\n}	0
14638452	14637891	How to get the ActualWidth without scrollbar of a ListView	ScrollViewer.ViewportWidth	0
9822984	9822900	How to write all build details in a text file	:: Test build script\n:: Setup command line for build\nif "%DevEnvDir%=="" (\n   echo "Setting up PATH"\n   :: use VS80 for VS2005 solution, VS90 for VS2008 solution,\n   :: or VS100 for VS2010 solution\n   call %VS90COMNTOOLS%vsvars32.bat" x86\n)\nmsbuild YourProject.sln /t:Rebuild /propertyConfiguration=release > Log.txt\nif %ERRORLEVEL%==0 echo "Build Succeeded"\nif not %ERRORLEVEL%==0 echo "Build Failed, See Log.txt"	0
21333544	21330158	How to find the active child form of MDI parent from User control which is loaded in MDI Parent at runtime in C#.net?	Form activeChild = this.ActiveMdiChild;	0
15582939	15582807	How do you find and extract information from a table of a website?	var item = doc.DocumentNode.SelectSingleNode("//table//tr//tr//td//div//tr//img");\nstring imageSrc = item.GetAttributeValue("src", "");\nConsole.WriteLine(imageSrc);	0
936247	936210	How to resize image in C# without smoothing	graphics.SmoothingMode = SmoothingMode.None;\ngraphics.DrawImage( barCodeImage, new Point( 0, 0 ) );	0
16314575	16313747	Sending a string over Python server to C# client returns a number of the chars in the string	int numReceived = clientSock.Receive(buffer);\nstring msg = Encoding.ASCII.GetString(buffer, 0, numReceived);	0
2606498	2606465	Exception catching from base of the class	public abstract class Base\n{\n    protected abstract void InternalFoo();\n    protected abstract void InternalBar();\n\n    public void Foo()\n    {\n        try { this.InternalFoo(); }\n        catch { /* ... */ }\n    }\n\n    public void Bar()\n    {\n        try { this.InternalBar(); }\n        catch { /* ... */ }\n    }\n}	0
9959948	9959927	Catching the return of window	private void fnc (object sender, RoutedEventArgs e)\n{\n    MyWindow nw = new MyWindow();\n\n    nw.Show();\n\n    // inline\n    nw.Closed += (s1, e1) => Debug.WriteLine("Closed");\n\n    // or\n    nw.Closed += (s1, e1) =>\n                        {\n                            Debug.WriteLine("Closed");\n\n                        };\n\n    // or\n    w.Closed += OnWindowClosed;\n}\n\nprivate void OnWindowClosed(object s, EventArgs e)\n{\n    Debug.WriteLine("Closed");\n}	0
7829596	7829518	Dynamic parameter causes compiler to think method return is dynamic	(MethodResult)IsValid(someObject));	0
17483665	16834447	how to extracting a part of an expression	private static LambdaExpression GetRootMemberExpression(LambdaExpression lambda1)\n    {\n        var expr = lambda1.Body;\n        while (!FindRoot(ref expr)) ;\n        if (!(expr is MemberExpression))\n            throw new Exception("MemberExpression required");\n        return Expression.Lambda(expr, (expr as MemberExpression).Expression as ParameterExpression);\n    }\n\n\n    private static bool FindRoot(ref Expression expr)\n    {\n        if (expr is MemberExpression)\n            return FindRoot(ref expr, (expr as MemberExpression).Expression);\n        if (expr.NodeType == ExpressionType.Call)\n            return FindRoot(ref expr, (expr as MethodCallExpression).Object);\n        throw new Exception("Unexpected Expression type encountered (" + expr.NodeType + ")");\n    }\n\n    private static bool FindRoot(ref Expression expr, Expression expr2)\n    {\n        if (expr2.NodeType == ExpressionType.Parameter)\n            return true;\n        expr = expr2;\n        return false;\n    }	0
29196820	29196561	Fill a listview from a combobox	SqlDataAdapter alegsectie = new SqlDataAdapter("SELECT C.denumire,OC.Data,OC.ora_inc,OC.ora_sf FROM cabinete AS C INNER JOIN orar_clinica AS OC ON c.id_cabinet = OC.id_cabinet INNER JOIN medici AS M ON OC.id_medic = M.id_medic and M.nume ='" + medic.SelectedValue + "'", conn);	0
9016757	9003282	Listview selectedItem	if (myListView.SelectedItems.Count > 0)\n{\n    foreach ([Class] cl in [List])\n    {\n        if (myListView.SelectedItems[0].SubItems[0].Text == cl.[Field].ToString())\n        {\n            RichTextBox.Text = cl.[Field];\n        }\n    }\n}	0
17072908	17072775	Changing the dimensions of a BitMapImage in WPF, and what kind of objects can I put in an <Image> element?	Uri uri = new Uri("pack://application:,,,/Images/DeployWiz_Network.png");\nBitmapImage source = new BitmapImage();\nsource.BeginInit();\nsource.UriSource = uri;\nsource.DecodePixelHeight = 10;\nsource.DecodePixelWidth = 10;\nsource.EndInit();\n\nreturn source;	0
17740433	17740287	How to use a field in another form file?	public partial class Form3 : Form\n{\n    int _port;\n    public int Port\n    {\n       get { return _port; }\n       set { _port = value; }\n    }\n}\n\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n       InitializeComponent();\n    }\n\n    void menu1_Click(object sender, EventArgs e)\n    {\n        Form2 frq = new Form2();\n        frq.Show();\n        Form3 frm3 = new Form3();\n        frm3.Port = 8080;\n\n        MessageBox.Show("{0} server is online ", frm3.Port);\n    }\n\n}	0
32897143	32896855	Remove Duplicate Captures from List	list.Distinct().ToList();	0
11150897	9136285	Adding parameter sets to my custom C# cmdlet with no parameter mandatory	[Cmdlet(VerbsCommon.New, "Customcmd", DefaultParameterSetName = Set1)]	0
4326982	4326724	C# Implementing Abstract factory pattern	QuestaoBaseResposta qs = new QuestaoFactory().CreateQuestao();	0
21082781	21082746	How to use WebClient.DownloadString on a website that uses SSL?	System.Net.WebClient.DownloadString()	0
30075473	30075430	How to increment DateTime? nullabe value in C#	DateTime? startDate = new DateTime();\nfor (int i = 0; i < 10; i++)\n{\n    startDate = startDate.Value.AddDays(1);\n}	0
10353027	10352773	How to use no fill for background color of a excel cell using c#?	xlRange.Interior.ColorIndex = 0;	0
11980741	11980564	MailMerge from arrays or lists	MailMerge.Execute()	0
948876	948303	Is there a better way to count string format placeholders in a string in C#?	int count = Regex.Matches(templateString, @"(?<!\{)\{([0-9]+).*?\}(?!})")  //select all placeholders - placeholder ID as separate group\n                 .Cast<Match>() // cast MatchCollection to IEnumerable<Match>, so we can use Linq\n                 .Max(m => int.Parse(m.Groups[1].Value)) + 1; // select maximum value of first group (it's a placegolder ID) converted to int	0
21593928	21593292	Get the value from Request.QueryString into another method	public partial class AttedanceManagementJT : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        int nom = Convert.ToInt32(Request.QueryString["ActivityId"]);\n        Session["nom"] = nom;\n    }\n\n    [WebMethod(EnableSession = true)]\n    public static object StudentListByFilter()\n    {\n        return ApplyMethods.StudentAttendanceList(\n            Convert.ToInt32(HttpContext.Current.Session["nom"]));\n    }\n}	0
19802340	19802257	Trying to understand Data transfer in byte[] Array C#	int bufferSize = 2048;\nint readCount;\nbyte[] buffer = new byte[2048]; // a buffer is created\n\n// bytes are read from stream into buffer. readCount contains\n// number of bytes actually read. it can be less then 2048 for the last chunk.\n// e.g if there are 3000 bytes of data, first Read will read 2048 bytes\n// and second will read 952 bytes\nreadCount = responseStream.Read(buffer, 0, bufferSize); \n\nwhile (readCount > 0) // as long as we have read some data\n{\n  writer.Write(buffer, 0, readCount); // write that many bytes from buffer to file               \n  readCount = responseStream.Read(buffer, 0, bufferSize); // then read next chunk               \n}	0
10187478	10187401	How can you display textbox1 value in textbox2 using keystokes	private void textBox2_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.PageDown ||\n        e.KeyCode == Keys.PageUp ||\n        e.KeyCode == Keys.Oemplus ||\n        e.KeyCode == Keys.Add ||\n        (e.KeyCode == Keys.D0 && e.Shift))\n    {\n        textBox2.Text = textBox1.Text;\n        e.Handled = true;\n        e.SuppressKeyPress = true;\n    }\n}	0
29663956	27439345	ASP.Net Application Crashes because of Web Service	e.g.\n    using(SqlCommand CMD = new SqlCommand())\n    {\n      **code here**\n    }	0
31551399	31550791	Very poor performance for array access manipulation in C#	int count = 0;\n\nfor (int i = 0; i < 100; i++)\n    for (int j = 0; j < i; j++)\n        for (int k = 0; k < 10000; k++)\n        {\n            count++;\n        }	0
14917622	14917550	Split String and multiply 8	string phrase = "The quick brown fox jumps over the lazy dog";\nstring[] words = phrase.Split(' ');\nvar wc = from word in words\n         group word by word.ToLowerInvariant() into g\n         select new {Word = g.Key, Freq = (float)g.Count() / words.Length * 100};	0
23289951	23224687	Skeleton Tracking With Multiple Kinect Sensors	foreach (var sensor in KinectSensor.KinectSensors)\n{\n    if (potentialSensor.Status == KinectStatus.Connected)\n    {\n       //add binding and events.\n    }\n}	0
1943313	1943197	Linq Lambda Expression	return categories = from c in oldCategories select new Category \n{  \nCategoryName = c.CategoryName, \nId = c.CategoryId, \nTeams = CombineTeam(c.Team.ToList(), coreTeam)\n};	0
29797277	29796377	Adding a row into a sheet using NetOffice	Worksheets("Sheet1").Rows(3)	0
11661873	11661842	How can I get the name and location of a sound file resource in C#?	Properties.Resources	0
9406625	9406539	decoupling from future APIs - first-timer discovering need for dependency injection	interface IDeliveryService<F> where F : Freight\n{\n    void Deliver();\n}\n\nclass RollerBladesDeliveryService<F> : IDeliveryService<F> where F: Freight\n{\n    public RollerBladesDeliveryService(RollerBladesDeliveryInformation<F> information){ ... }\n\n    void Deliver() { ... }\n}\n\nclass RollerBladesDeliveryInformation<F> where F: Freight\n{\n    public RollerBladesDeliveryInformation(F freight, double centerOfMass) { ... }\n}	0
23400222	23258669	Linq query on EF, Include() is ignored with a query that only contains a where clause	ObjectQuery<Dispatch> query = (from item in entities.Dispatches select item) as ObjectQuery<Dispatch>;\n\n            foreach (string s in includes)\n                query = query.Include(s);\n\n            var res = from d in query\n                      where d.Route.Legs.Any(x =>\n                      x.StartPoint.ArrivalTime >= start && x.StartPoint.ArrivalTime <= end ||\n                      x.StartPoint.DepartureTime >= start && x.StartPoint.DepartureTime <= end ||\n                      x.EndPoint.ArrivalTime >= start && x.EndPoint.ArrivalTime <= end ||\n                      x.EndPoint.DepartureTime >= start && x.EndPoint.DepartureTime <= end)\n                      select d;	0
24034053	23619256	Can I Change Default Behavior For All Shims In A Test	using (ShimsContext.Create())\n{\n     ShimBehaviors.Current = ShimBehaviors.NotImplemented;\n\n     var myShim = new ShimMyClass\n     { \n         ... \n     }\n}	0
11509318	11508286	Bullet points in Word with c# Interop	Paragraph assets = doc.Content.Paragraphs.Add();\n\n    assets.Range.ListFormat.ApplyBulletDefault();\n    string[] bulletItems = new string[] { "One", "Two", "Three" };\n\n    for (int i = 0; i < bulletItems.Length; i++)\n    {\n        string bulletItem = bulletItems[i];\n        if (i < bulletItems.Length - 1)\n            bulletItem = bulletItem + "\n";\n        assets.Range.InsertBefore(bulletItem);\n    }	0
6061301	6061261	DataBinding DataSet to GridView yields infinite loop	OnDataBinding="RebindGrid"	0
4721972	4720082	How can I programmatically find the scale, rotate, and translate values when using the MultiTouchBehavior in a Silverlight/WP7 app?	var transform = this.MyImage.RenderTransform as CompositeTransform;\nvar currentScaleX = transform.ScaleX;\nvar angle = transform.Rotation;\nvar offsetX = transform.TranslateX;	0
19324623	19315445	Printing a control Form	private void Print_Test()\n        {\n            PrintDialog dlg = new PrintDialog();\n            if (dlg.ShowDialog() == false) return;\n            int i = 1;\n\n            Size pageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight); //I found this Size object very important.  Without it I only got an empty page\n            ReportPrintForm rf;\n            foreach (KeyValuePair<String, Report> kvp in ((App)Application.Current).Reports)\n            {\n                rf = new ReportPrintForm(kvp.Value);\n                rf.Measure(pageSize);\n                rf.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));\n                dlg.PrintVisual(rf, "Job_" + i);\n                i++;\n            }\n        }	0
1495860	1495782	Convert T-SQL to LINQ-to-SQL	//Lets say you have database called TestDB which has your ContentHistory table\nTestDBContext db = new TestDBContext();\n\n\n//This will return as IQueryable. \nvar result = db.ContentHistory.Select(p=>p.Content).Where(p=>p.Content == <your filter>);	0
25496162	25496036	How to represent bits in structure in c#	class myPacket {\n  public byte packed = 0;\n  public int seqNumber {\n    get { return value >> 7; }\n    set { packed = value << 7 | packed & ~(1 << 7); } \n  }\n  public int content {\n    get { return value & ~(1 << 7); }\n    set { packed = packed & (1 << 7) | value & ~(1 << 7); } \n  }\n}	0
33930537	33930389	Automapper unsupported mapping int16 to enum	public enum WebsitePropertyEnum : short\n{\n    thing1 = 0,\n    thing2 = 1\n}	0
8602147	8601725	Hijri and Gregorian DateTime constructor 	HijriCalendar hijri = new HijriCalendar();\nDateTime firstDayInMonth = new DateTime(1433, 10, 11, hijri);\nConsole.WriteLine(hijri.GetEra(firstDayInMonth)); // 1\nConsole.WriteLine(hijri.GetYear(firstDayInMonth)); // 1433\nConsole.WriteLine(hijri.GetMonth(firstDayInMonth)); // 10\nConsole.WriteLine(hijri.GetDayOfMonth(firstDayInMonth)); // 11	0
15413857	15391095	Error Based on Stored Procedure Return Value	protected void Page_Load(object sender, EventArgs e)\n    {\n        //Runs query to determine if returnValue is greater then 1 then redirects if true \n        SqlConnection sqlConnection1 = new SqlConnection("ConnectionString");\n        SqlCommand cmd = new SqlCommand();\n        cmd.CommandText = "SELECT COUNT(UID) FROM Table WHERE (USER = @USER)";\n        cmd.CommandType = CommandType.Text;\n        SqlParameter UserID = new SqlParameter("@USER", Request.QueryString["usr"]);\n        UserID.Direction = ParameterDirection.Input;\n        cmd.Parameters.Add(UserID);\n        cmd.Connection = sqlConnection1;\n\n        sqlConnection1.Open();\n        int returnValue;\n        returnValue = Convert.ToInt32(cmd.ExecuteScalar());\n        sqlConnection1.Close();\n\n        if (returnValue > 0)\n        {\n            Response.Redirect("morethanone?usr=" + Request.QueryString["usr"]);\n        }\n    }	0
3762170	3762098	Return custom values from WPF dialog	window.ShowDialog();\nTuple<string, string> value = window.InputValue;	0
25102817	25102116	Input string was not in a correct format. in timespan	TimeSpan newEventStartTime = TimeSpan.ParseExact("12:44",@"hh\:mm",CultureInfo.InvariantCulture);	0
16045199	16045156	How to search a downloaded string of a website?	if (downloadedString .Contains("fun"))\n    {\n        // Process...\n    }	0
7256924	7256361	How to change property Enable32BitAppOnWin64 of Application Pool on IIS 7 on Windows Azure?	%windir%\system32\inetsrv\appcmd set config -section:applicationPools -applicationPoolDefaults.enable32BitAppOnWin64:true	0
31696227	31472533	Closing WPF Application Via WCF Takes Too Long	[ServiceBehavior(UseSynchronizationContext = false)]	0
6138554	6138469	How to save image stream in c#?	Image.FromStream(file.InputStream, false).Save(location, System.Drawing.Imaging.ImageFormat.Png);	0
22972610	22971407	Irregular xml file processing	xsd file.xml	0
9131284	9131225	C# Convert to Byte Array	byte[] Bytes = (byte[]) SQLreader("ImageList"); \npicStudent.Image = jwImage.ByteToImage(Bytes);	0
19553495	13427707	Loading large images into image control	Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();\nopenFileDialog.ShowDialog();\nImageSource imageSource = new BitmapImage(new Uri(openFileDialog.FileName));\nimage1.Source = imageSource;	0
3232119	3231373	Editing a cell in a datagrid and bind to a command in a MVVM .Is this possible	public class RowViewModel\n{\n    private bool _IsModified = false;\n\n    private string _FirstName;\n    public string FirstName\n    {\n        get { return _FirstName; }\n        set { _FirstName = value; _IsModified = true; }\n    }\n\n    private string _LastName;\n    public string LastName\n    {\n        get { return _LastName; }\n        set { _LastName = value; _IsModified = true; }\n    }\n}	0
34137886	34136950	Use modelbuilder to change default string from type nvarchar to varchar for specific fields in EF	[Column(???BlogDescription", TypeName="ntext")]	0
31684780	31683018	Faking A Keyboard or Mouse Event	WindowsInput.Native	0
27985256	27985217	Is Roslyn a full compiler?	csc.exe	0
23993433	23993078	bind grid view with selected date list with selected days	DECLARE @startDate DATETIME\nDECLARE @endDate DATETIME\nSET @startDate = '2014-06-02'\nSET @endDate = '2014-06-26'\n;WITH dates AS \n(\n    SELECT @startdate as Date,DATENAME(Dw,@startdate) As DayName\n    UNION ALL\n    SELECT DATEADD(d,1,[Date]),DATENAME(Dw,DATEADD(d,1,[Date])) as DayName\n    FROM dates \n    WHERE DATE < @enddate\n)\n\nSELECT Date,DayName frOM dates where DAYNAME in('Monday','Tuesday','Wednesday')	0
6014830	5979827	Count the number of visible rows in a DataGrid	private bool IsUserVisible(FrameworkElement element, FrameworkElement container) {\n    if (!element.IsVisible)\n        return false;\n    Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));\n    Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);\n    return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);\n}	0
11222045	11221645	Autofac two properties with the same type	builder.RegisterType<A>()\n    .As<IA>()\n    .OnActivating(e =>\n{\n    e.Instance.PropertyB = e.Context.Resolve<BImpl1>();\n    e.Instance.PropertyC = e.Context.Resolve<BImpl2>();\n});	0
31862095	31860582	How to add multiple endpoints to adfs	app.UseWsFederationAuthentication(\n    new WsFederationAuthenticationOptions\n    {\n        Wtrealm = realm,\n        MetadataAddress = adfsMetadata,\n        Notifications = new WsFederationAuthenticationNotifications\n        {\n            RedirectToIdentityProvider = context =>\n            {\n                context.ProtocolMessage.Wreply = <construct reply URL from context.Request>;\n                return Task.FromResult(0);\n            }\n        }\n    });	0
26712566	26298889	Costumize DbContext using connection string from ServiceConfiguration (Azure)	public RAActivityContext()\n    : base((new SqlConnectionStringBuilder(\n            CloudConfigurationManager.GetSetting("dbRAActivity")).ToString()))\n{            \n\n}	0
5084187	5083834	Return recordset using a Web Service	Microsoft.XMLDOM	0
3476075	3475993	Aggregate a Dataset	DataTable source = // whatever\nDataTable dest = source.Clone();\n\nvar aggregate = source\n    .AsEnumerable()\n    .GroupBy(row => row.Field<int>("Row1"))\n    .Select(grp => new { Row1 = grp.Key, Row2 = grp.Select(r => r.Field<int>("Row2")).Sum() });\n\nforeach(var row in aggregate)\n{\n    dest.Rows.Add(new object[] { row.Row1, row.Row2 });\n}	0
25060111	25058485	Disable Validation in View	[RegularExpression(@"[^/\\""\|<>:\?'\*\[\]\=%\$\+,;~#&\{\}]*", \n ErrorMessage = @"Illegal characters: / \ | "" ' < > [ ] {{ }} : ; , ~ ? = + * % $ #")]	0
5977410	5977345	Display tip on home page by day number in asp.net	public static int GetTipNumber()\n{\n     int tipNo = 1;\n     if (DateTime.Now.Day > 0 && DateTime.Now.Day <= 30)\n     {\n         tipNo = DateTime.Now.Day;\n     }\n     else \n     {\n         tipNo = 1; // \n     }                \n\n     return tipNo;\n}	0
5667071	5666549	convert string to int32 while adding datagrid items	int outValue;\nlist.Add(new Row()\n            {\n                Column1 = int.TryParse(strCols[0].Substring(2), out outValue) ? outValue : 0;,\n                 ...	0
26591522	26591232	How to get string resources from specific resource file in C#	System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB"); \nResourceManager resourceManager = new ResourceManager("YourResource", Assembly.GetExecutingAssembly()); \nstring bodyResource = resourceManager.GetString("yourText", ci);	0
16243704	16241450	Update CLOB using a textbox in C#	using (OracleConnection connection = new OracleConnection(<VALID CONN STRING GOES HERE>)) {\n    connection.Open();\n    using (OracleCommand command = new OracleCommand()) {\n         command.Connection = connection;\n         command.CommandText = "UPDATE testing SET COMMENTS = :COMMENTS, DATEMODIFIED = sysdate WHERE ID = :ID";\n         command.CommandType = CommandType.Text;\n         command.Parameters.Add("COMMENTS", OracleDbType.Clob, ParameterDirection.Input).Value = comments.Text;\n         command.Parameters.Add("ID", OracleDbType.Int32, ParameterDirection.Input).Value = 1;\n         command.ExecuteNonQuery();\n    }\n}	0
25221444	25221074	How do i map a column to another table in entity framework?	public class UserPosts\n {\n     [Key]\n     public int PostId { get; set; }\n\n     [ForeignKey("User")]\n     public string CreatedBy { get; set; }\n     public virtual UserBio User { get; set; }\n\n     public string Description { get; set; }\n }	0
22454777	22454673	reading datagridview row and creating folders	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    Directory.CreateDirectory(@"I:\smrithi\hhh\" + row.Cells[2].Value);\n}	0
30378107	30378068	How to convert a date value from sql server with c#?	DataManager.NotificationManager obj = new DataManager.NotificationManager();\nDataTable dt1 = obj.GetListExpiryDate();\nDateTime currendate = DateTime.Today;\n\nforeach(DataRow row in dt1.Rows)\n{  \n    if (DateTime.Parse(row.ItemArray[41].ToString().Date) == currendate) \n    { \n         MessageBox.Show("Expired carte for the employee" + row["EmpFName"]); \n    }\n    else \n    { \n         MessageBox.Show(" not Expired carte for the employee"+row["EmpFName"]); \n    }\n}	0
17579161	17579091	Faster way to check if a number is a prime?	public static bool IsPrime(int number)\n    {\n        if (number < 2) return false;\n        if (number % 2 == 0) return (number == 2);\n        int root = (int)Math.Sqrt((double)number);\n        for (int i = 3; i <= root; i += 2)\n        {\n            if (number % i == 0) return false;\n        }\n        return true;\n    }	0
12222918	12222873	How can I use SOS.dll within a C# program for automated debugging purposes?	procdump -s 5 -n 3 notepad.exe notepad.dmp	0
8132438	8132413	C# incrementing static variables upon instantiation	public class SavingsAccount\n{\n    private static int accountNumber = 1000;\n    private bool active;\n    private decimal balance;\n    private int myAccountNumber;\n\n    public SavingsAccount(bool active, decimal balance, string accountType)\n    {\n        myAccountNumber = ++accountNumber;\n        this.active = active;\n        this.balance = balance;\n        this.accountType = accountType;\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings");\n        SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings");\n        Console.WriteLine(potato.ToString());\n        Console.WriteLine(magician.ToString());\n    }\n}	0
27138064	27137054	Rebinding a Xceed DataGrid column to accept special characters	foreach (var c in grid.Columns)\n        {\n            var column = c as Xceed.Wpf.DataGrid.Column;\n            column.DisplayMemberBinding = new System.Windows.Data.Binding("[" + column.FieldName + "]");\n        }	0
1376305	1375997	Group by variable integer range using Linq	var ceilings = new[] { 10, 100, 500 };\nvar groupings = items.GroupBy(item => ceilings.First(ceiling => ceiling >= item));	0
542791	542766	C# convert string into its byte[] equivalent	byte[] fileC = File.ReadAllBytes(dialog.FileName);	0
31690068	31689516	Map an object to a KeyValuePair	public class Node\n    {\n        public Dictionary<string, string> dict = new Dictionary<string, string>();\n        public List<Node> children = new List<Node>();\n    }	0
33711054	33707884	How to Get Header Info from Wav Stored in MemoryStream?	byte[] headers = byte[36];\nmemorystream.Position = 0;\nmemorystream.Read(headers,0,headers.Length);\n/** doing your meta data extraction **/\n String mode;\n if(headers[22] ==  1)\n    mode = "mono";\n else if(headers[22] == 2)\n    mode = "stereo";\n else \n    mode = "unknown";\n/*************************************/\nmemorystream.Position = 0;	0
14552118	14551516	If a transmitter wants to send 4k of data and the serial port receives 32 byte of data at a time how to save these bytes in the same memory stream?	int offset = 0;\nfor(int i = 0; i < total; i++){\n    for(int j = 0; j < 32; j++){\n        offset = i * 32;\n        jpg[offset + j] = (byte)CamPort.ReadByte();\n    }\n }	0
16955266	16954972	Pass a variable directly into a Lambda Method?	string a = "test";\nnew Thread((s) => { s = "newTest"; }).Start(a);	0
33765147	33545972	Use WatiN in windows Form to Automate Clicking and Writing in Internet Explorer C#	using(var ie = new IE){\n   ie.GoTo("http://www.yourwebpage.com");\n   TextField entry = ie.TextField(Find.ById("myEntryBox"));\n   Button btn = ie.Button(Find.ById("submit"));\n   SelectList menu = ie.SelectList(Find.ById("selectList"));\n\n   entry.Value ="Hello world");\n   menu.SelectByValue("2");\n   btn.Click();\n}	0
11293477	11293348	How to run a code only if a Cell, not a Header, in DataGridView is doubleClicked?	private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {\n            if (e.RowIndex != -1) {\n                //do work\n            }\n        }	0
4585136	4585105	save application configurations	app.config	0
1325508	1325341	Reverse many-to-many Dictionary<key, List<value>>	var newDict = new Dictionary<int, List<int>>();\nvar dict = new Dictionary<int, List<int>>();\ndict.Add( 1, new List<int>() { 1, 2, 3, 4, 5 } );\ndict.Add( 2, new List<int>() { 1, 2, 3, 4, 5 } );\ndict.Add( 3, new List<int>() { 1, 2, 6 } );\ndict.Add( 4, new List<int>() { 1, 6, 7 } );\ndict.Add( 5, new List<int>() { 8 } );\n\nvar newKeys = dict.Values.SelectMany( v => v ).Distinct();\n\nforeach( var nk in newKeys )\n{\n   var vals = dict.Keys.Where( k => dict[k].Contains(nk) );\n   newDict.Add( nk, vals.ToList() );\n}	0
13045696	13045662	Store a simple table in memory in ASP.NET?	DataTable yourDataTable = new DataTable();\nCache["yourTable"] = yourDataTable;\n\n//to access it\nDataTable dt = Cache["yourTable"] as DataTable;	0
18858715	18857772	ASP Entity Framework - Code FIrst - Data Design - Keys	protected override void Seed(Insight.Data.InsightDb context)\n{\n    var product1 = new Product{ Name = "Product 1"};\n    var product2 = new Product{ Name = "Product 2"};\n    var reports1 = new List<Report>\n    {\n        new Report { Name = "Report A", Product = product1, },\n        new Report { Name = "Report B", Product = product1, },\n        new Report { Name = "Report C", Product = product1, },\n        new Report { Name = "Report D", Product = product2, },\n        new Report { Name = "Report E", Product = product2, }\n    };\n\n    context.Products.AddOrUpdate(p => p.ProductID,\n        product1,\n        product2\n    );\n\n    context.Reports.AddOrUpdate(p => p.ReportID,\n        reports1\n    );\n\n    context.Users.AddOrUpdate(u => u.UserID,\n        new User { FirstName = "Frank", LastName = "Reynolds", Reports = reports1 },\n        new User { FirstName = "Dee", LastName = "Reyonolds" },\n    );\n}	0
3289235	3289198	Custom attribute on property - Getting type and value of attributed property	public object GetIDForPassedInObject(T obj)\n    {\n        var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)\n                   .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1);\n        object ret = prop !=null ?  prop.GetValue(obj, null) : null;\n\n        return ret;\n    }	0
4587670	4587642	how do i add text to image in c# or vb.net	var bmp = Bitmap.FromFile("orig.jpg");\n    var newImage = new Bitmap(bmp.Width, bmp.Height + 50);\n\n    var gr = Graphics.FromImage(newImage);\n    gr.DrawImageUnscaled(bmp, 0, 0);\n    gr.DrawString("this is the added text", SystemFonts.DefaultFont, Brushes.Black ,\n        new RectangleF(0, bmp.Height, bmp.Width, 50));\n\n    newImage.Save("newImg.jpg");	0
3940644	3940601	How to draw a circle on a form that covers the whole working area?	Invalidate()	0
23890738	23889091	How to aassign list values to scrollbar in c#	ListBox lines = new ListBox(); \n            ScrollViewer scrollViewer = new ScrollViewer();            \n            scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;\n            foreach (var item in param.Component.Attributes.Items)\n            {\n                lines.Items.Add(item);    \n                scrollViewer.Content = lines;                            \n            }                \n\n        Grid.SetColumn(scrollViewer, 1);\n        Grid.SetRow(scrollViewer, LoopCount);\n        childGrid.Children.Add(scrollViewer);	0
10141919	10121737	Save docx as pdf in c#, fails to export excel charts properly	wrdInlineShape.Range.Cut();\n            shapeBookMark.Range.Paste();\n            Thread.Sleep(2000);	0
24277722	24277668	How to print two list results together	foreach (var a in _teams.Zip(_wins, (t, w) => new { t, w }))\n{\n    Console.WriteLine(a.t + " " + a.w);\n}	0
8443599	8443412	Easy way to insert rows of dataTable to database	using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleApplication3.Properties.Settings.daasConnectionString"].ConnectionString))\n{\n  cn.Open();\n\n  using (SqlBulkCopy copy = new SqlBulkCopy(cn))\n  {\n    copy.ColumnMappings.Add(0, 0);\n    copy.ColumnMappings.Add(1, 1);\n    copy.ColumnMappings.Add(2, 2);\n    copy.ColumnMappings.Add(3, 3);\n    copy.ColumnMappings.Add(4, 4);\n\n    copy.DestinationTableName = "tNorthwind";\n\n    copy.WriteToServer(dt);\n  }\n}	0
31179698	31179649	Linq Contains with array of enum	return ctx.Tickets.Where(t => states.Any(s => t.State == s)).AsEnumerable();	0
5848797	5848790	convert URL's hex digits into a string	Uri.UnescapeDataString	0
2369845	2369826	WPF DisplayMemeberPath on ListBox	listBox.Items.Add(new Test { S = "Hello World" });	0
23489339	23489039	Replace all matches of regex with manipulation on specific capturing group	string regex = "(?<=<ns1:AcctId>).*?(?=</ns1:AcctId>)";\nXml = Regex.Replace(Xml, regex, delegate(Match m) {\n                           return IBANHelper.ConvertBBANToIBAN(m.Value);\n                         });	0
5589675	5589658	Monitor running apps in .NET?	Process.GetProcesses()	0
6420796	6420701	Loading CSV into DataGridView	OdbcDataAdapter da = new OdbcDataAdapter("Select * from [" + path + "]", conn);	0
15384535	15217222	How to give DataGridView cell intellisense?	public List<Type> GetTypesFromAssembly()\n        {\n            List<Type> listOfAllTypes = new List<Type>();\n            Assembly[] allAssembliesInCurrentDomain = AppDomain.CurrentDomain.GetAssemblies();\n\n            foreach (Assembly assembly in allAssembliesInCurrentDomain)\n            {\n                listOfAllTypes.AddRange(assembly.GetTypes());\n            }\n\n            return listOfAllTypes;        \n        }\n\npublic List<string> GetSystemNamespaces()\n        {\n            List<string> namespaces = new List<string>();            \n\n            List<Type> types = GetTypesFromAssembly();\n\n            foreach (Type type in types)\n            {\n                if (type.Namespace != null)\n                {\n                    namespaces.Add(type.Namespace.ToString());\n                    namespaces = namespaces.Distinct().ToList();\n                }\n            }\n            return namespaces;\n        }	0
34391080	34390995	Test value fist character of string - C#	if (description.StarstWith(","))\n{\n    //...\n}	0
6252651	6252603	how to remove the listening of callback on anonymous method?	private EventHander _handler = null;\n\npublic A()\n{        \n    _handler = delegate( object sender, EventArgs ee)\n        {          \n            ServiceAdapter.CompletedCallBackEvent -= _handler;\n        };\n    ServiceAdapter.CompletedCallBackEvent += _handler;\n}	0
3456125	3454837	Using C# to Select from SQL database Table	CREATE PROCEDURE GetSelectedItems\n(\n@SelectedItemsID  Varchar(MAX) -- comma-separated string containing the items to select\n)\nAS\nSELECT * FROM Items\nWHERE ItemID IN (SELECT Value FROM dbo.fn_Split(@SelectedItemsIDs,','))\n\nRETURN\nGO	0
23665085	23656175	finding end date from start date with removing a delay	// ----------------------------------------------------------------------\npublic void FinalDateProvider()\n{\n    DateTime now = new DateTime( 2014, 5, 16, 9, 0, 0 );\n    TimeSpan offset = new TimeSpan( 15, 0, 0 );\n    Console.WriteLine( "{0} + {1} = {2}", now, offset, CalcFinalDate( now, offset ) );\n} // FinalDateProvider\n\n// ----------------------------------------------------------------------\npublic DateTime? CalcFinalDate( DateTime start, TimeSpan offset )\n{\n    CalendarDateAdd dateAdd = new CalendarDateAdd();\n    dateAdd.AddWorkingWeekDays();\n    dateAdd.WorkingHours.Add( new HourRange( 8, 12 ) );\n    dateAdd.WorkingHours.Add( new HourRange( new Time( 12, 30 ), new Time( 17 ) ) );\n    return dateAdd.Add( start, offset );\n} // CalcFinalDate	0
7768870	7768795	WPF UserControl Dependency Property value	public int AgreementID\n{\n    get { return (int) GetValue(AgreementIDProperty ); }\n    set { SetValue(AgreementIDProperty, value); }\n}	0
13716458	13716345	Writing a method that reports progress	// Error checking elided for expository purposes.\npublic interface IProgressReporter \n{\n    void ReportProgress(int progress, object status);\n}\n\npublic class BackgroundWorkerProgressReporter : IProgressReporter\n{\n    private BackgroundWorker _worker;\n    public BackgroundWorkerProgressReporter(BackgroundWorker worker)\n    {\n        _worker = worker;\n    }\n\n    public void ReportProgress(int progress, object status)\n    {\n        _worker.ReportProgress(progress, status);\n    }\n}	0
27053257	27053196	Serializing and deserializing a DateTime string doesn't work in UTC	DateTime bar = DateTime.ParseExact(foo, "O", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);	0
24565808	24564137	Using a cookie to store and call an integer	if(testCookie == null)	0
10103401	10102537	how to stop and resume a XNA game for windows phone?	timer.Stop();\ntimer.Start();	0
23777200	23777133	Use of multiple Regular Expression in C# web crawler	(pattern1)|(pattern2)|(...)	0
22884285	22877171	Colspan=2 in a gridview	protected void gridList_RowCreated(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.Header)\n        {\n            e.Row.Cells[2].Visible = false;\n            e.Row.Cells[1].Attributes.Add("colspan", "2");\n        }\n}	0
28697040	28454886	Find a locator from an element in Selenium	public void Start()\n    {\n        List<IWebElement> elements = _seleniumAdapter.AllElementsOnPage();\n        Debug.WriteLine("Elementcount: " + elements.Count);\n        int i = _random.Next(elements.Count);\n        IWebElement element = elements[i];\n\n        Debug.WriteLine(element.TagName + "," + element.Text);\n        try\n        {\n        element.Click();\n        }\n        catch(StaleElementReferenceException ex)\n        {\n           elements = _seleniumAdapter.AllElementsOnPage();\n           element = elements[i];\n           element.Click()\n\n        }\n        catch(Exception ex)\n        {\n            Debug.WriteLine(ex.Message);\n            element = null;\n        }\n        if(element != null)\n       {\n        if (element.GetAttribute("type").Contains("text"))\n        {\n            Debug.WriteLine("text!");\n            element.SendKeys(randomLetter());\n        }\n        Start();\n       }\n\n    }	0
4146967	4139888	How can I set the values of a chart series in SpreadsheetGear programmatically?	IWorkbook workbook = Factory.GetWorkbook(@"C:\chart.xlsx");\nSpreadsheetGear.Charts.IChart chart = workbook.Worksheets["Sheet1"].Shapes["Chart 1"].Chart;\nISeries series1 = chart.SeriesCollection[0];\nseries1.Values = "={10,20,30,40,50,60}";\nworkbook.Save();	0
12536995	12536956	How can I store a string of encrypted data in an xml element?	byte[] encryptedBytes = ...;\nvar asBase64 = Convert.ToBase64String(encryptedBytes);\nvar asBytes = Convert.FromBase64String(asBase64);	0
2393135	2393089	How to transcribe SQL to LINQ	var carteAutors = db.Carte.Join( db.CarteAutor, (o,i) => o.ID_Carte == i.ID_Carte )\n                    .Select( (o,i) => new { ID_Autor = i.ID_Autor, ...et al... } );\n\nvar q = db.Autors\n          .Join( carteAutors, (o,i) => o.ID_Autor == i.ID_Autor )\n          .Select( (o,i) => new { ID_Autor = o.ID_Autor, ...et al... )\n          .GroupBy( a => a.ID_Autor );	0
9084594	9083798	Regular expression to find CreateGraphics calls that do not have a using block	^~(:Wh*using).*CreateGraphics	0
5552854	5552774	How can I open Event Viewer from a web page using c#?	EventLogSession session = new EventLogSession(\n        "RemoteComputerName",// Remote Computer\n        "Domain",// Domain\n        "Username",// Username\n        pw,\n        SessionAuthentication.Default);	0
16520158	16519956	How to store date from text box in SQL Server through C# ASP.net	CultureInfo provider = CultureInfo.InvariantCulture;\nSystem.Globalization.DateTimeStyles style = DateTimeStyles.None;\nDateTime dt;\nDateTime.TryParseExact(txt_dob.Text, "m-d-yyyy", provider, style, out dt);\nmycom = new SqlCommand("insert into mytable(dtCol1) values(@datevalue)", mycon);\ncmd.Parameters.Add("@datevalue",SqlDbType.DateTime).Value =dt;\nmycom.ExecuteNonQuery();	0
12757270	12757138	Remove duplicates from combobox which is bind to dataset	DataSet ds = new DataSet();\nds.ReadXml(@"..\..\stock.xml");\nDataTable dt = ds.Tables[0].DefaultView.ToTable(true, "productname");\ncbProduct.DataSource = dt;\ncbProduct.DisplayMember = "productname";	0
10994045	10993441	Monochrome Bitmap to Binary array in C#	Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\n        BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);\n\n        // Get the address of the first line.\n        IntPtr ptr = bmpData.Scan0;\n\n        // Declare an array to hold the bytes of the bitmap.\n        int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;\n        byte[] rgbValues = new byte[bytes];\n\n        // Copy the RGB values into the array.\n        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);\n\n        // Unlock the bits.\n        bmp.UnlockBits(bmpData);	0
9621538	9621474	Find Invoker Method Name	public string SendError(string Message, [CallerMemberName] string callerName = "")\n{\n    Console.WriteLine(callerName + "called me.");\n}	0
13448866	13448820	Assigning the result of group by to items in a list with linq	var sumDictionary = query.ToDictionary(pair => pair.intid, pair => pair.expsum);\nforeach (var item in result)\n{\n    // We don't know which property you actually want to assign to\n    item.Sum = sumDictionary[item.id];\n}	0
13274251	13274113	Variables that accept values with pipe | as separator	AccessRights rights = 0;\n\nif (bool.Parse(mht_ReadAccess))\n    rights |= AccessRights.ReadAccess;\n\nif (bool.Parse(mht_WriteAccess))\n    rights |= AccessRights.WriteAccess;\n\n// do the same for all other variables\n\nvar grantAccessRequest = new GrantAccessRequest\n{\n    PrincipalAccess = new PrincipalAccess\n    {\n        AccessMask = rights,\n        Principal = userreference\n    },\n    Target = recordentityreference\n};	0
4354216	4343492	Unity Application Block, How pass a parameter to Injection Factory?	// Definition\npublic interface IProfileFactory\n{\n    IProfile CreateProfileForUser(string username);\n}\n\n// Usage\nvar profile = Container.Resolve<IProfileFactory>()\n    .CreateProfileForUser("John");\n\n// Registration\nContainer.RegisterType<IProfileFactory, ProfileFactory>();\n\n// Mock implementation\npublic class ProfileFactory : IProfileFactory\n{\n    public IProfile CreateProfileForUser(string username)\n    {\n        IUser user = Container.Resolve<IUserManager>()\n            .GetUser(username);\n\n        return new UserProfile(user);\n    }\n}	0
2373558	2373146	Reflection & Parameters in C#	Type.GetType(string)	0
31948829	31946949	Is it possible to serve static files from outside the wwwroot folder?	app.UseStaticFiles(new StaticFileOptions() {\n    FileProvider = new PhysicalFileProvider(@"C:\Path\To\Files"),\n    RequestPath = new PathString("/somepath")\n})	0
16415624	16415470	cant send data from jquery to c# server	var params = JSON.stringify({\n             username:user,\n            firstname :firstname,\n            lastname:lastname,\n            birthdate: birthdate,\n            pic:123,\n            carowned:car,\n            email:email,\n            password: password,\n            home: home,\n            cell: cell\n           });	0
2039009	2038988	linq extension methods: Is there a way to add an OR clause to a where method	foreach (var container in modelEntities.\n    Where(me => me.Value.ModelEntityType == (int)EntityType.Container ||\n      me.Value.ModelEntityType == (int)EntityType.SubForm))	0
578630	554709	C# - Store and then update a property	table.Update();	0
32655966	32655775	Entity Framework SaveChanges each 100 inserts	SaveChanges()	0
15541998	15497460	How to filter a datagridview by a textbox after loading an excel file into it	BindingSource bs = new BindingSource();\n  bs.DataSource = dataGridView1.DataSource;\n  bs.Filter = sColumnaDoPrzeszukania + " like '%" + textBox1.Text + "%'";\n  dataGridView1.DataSource = bs;	0
3008111	3008085	Recursively getting files in a directory with several sub-directories	class Program\n{\n    static IEnumerable<String> Visitor(String root, String searchPattern)\n    {\n        foreach (var file in Directory.GetFiles(root, searchPattern, SearchOption.TopDirectoryOnly))\n        {\n            yield return file;\n        }\n\n        foreach (var folder in Directory.GetDirectories(root))\n        {\n            foreach (var file in Visitor(folder, searchPattern))\n                yield return file;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (var file in Visitor(args[0], args[1]))\n        {\n            Console.Write("Process {0}? (Y/N) ", file);\n\n            if (Console.ReadKey().Key == ConsoleKey.Y)\n            {\n                Console.WriteLine("{1}\tProcessing {0}...", file, Environment.NewLine);\n            }\n            else\n            {\n                Console.WriteLine();\n            }\n        }\n    }\n}	0
8213232	8213188	Count number of individual lines from a txt file c#	var lines = File.ReadAllLines("FileToRead.txt").Distinct().Count();	0
9669149	9668872	How to get window's position?	[DllImport("user32.dll", CharSet = CharSet.Auto)]\npublic static extern IntPtr FindWindow(string strClassName, string strWindowName);\n\n[DllImport("user32.dll")]\npublic static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);\n\npublic struct Rect {\n   public int Left { get; set; }\n   public int Top { get; set; }\n   public int Right { get; set; }\n   public int Bottom { get; set; }\n}\n\nProcess[] processes = Process.GetProcessesByName("notepad");\nProcess lol = processes[0];\nIntPtr ptr = lol.MainWindowHandle;\nRect NotepadRect = new Rect();\nGetWindowRect(ptr, ref NotepadRect);	0
17492476	17492441	How can I make an image enlarge on a javascript event when its size is set through css?	this.style.width="50px"	0
6062929	6062829	Pulling String from Database. Says Cannot Implicitly Convert to 'string'	DataTable dt   = pdb.getBuyNowText(pID);\ncustomBuyNowText.Text = dt.Rows[0]["your_column_name"].ToString();	0
2885792	2885697	C#, LINQ. How to find an element within group of elements	data.Where((val, index)=>(index == 0 || val > data[index - 1]) \n                      && (index == data.Length - 1 || val > data[index + 1]));	0
26493132	26452862	Specific Draw region within Game Window	// Create the rectangle\n            var clipRectangle = new Microsoft.Xna.Framework.Rectangle(0,0,100,100);\n\n            // Set the rectangle when you call SpriteBatch.Begin:\n            mSpriteBatch.Begin(SpriteSortMode.Immediate, renderStates.BlendState,\n                samplerState,\n                depthStencilState,\n                rasterizerState,\n                null, matrix, \n                clipRectangle);	0
30393962	30393789	C# Regex to remove appropriate part of text	var isTrue = true;\nvar str = "The company <is> <is not> a co-owner of other accounts in the Bank.";\nvar segment = Regex.Match(str, @"<(.*?)>\W<(.*?)>");\nvar replacement = str.Replace(segment.Value, isTrue ? segment.Groups[1].Value : segment.Groups[2].Value);	0
1302300	1300122	Marshalling BSTRs from C++ to C# with COM interop	HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse)\n{\n    char* pszResponse = BuildResponse(CW2A(request));\n    *pResponse = A2BSTR(pszResponse);\n    delete[] pszResponse;\n    return S_OK;\n}	0
21340222	20624085	Deserialize Json when variable quantity of entry	IDictionary<string, JToken> jsondata = JObject.Parse(json);\n\n foreach (KeyValuePair<string, JToken> innerData in jsondata) {\n    Console.WriteLine("{0}=> {1}",innerData.Key, innerData.Value.ToString()); \n }	0
17869489	17869406	XML parsing with LINQ, has 2 tags with the same name but different level and not always has a value	name = i.Element("name") == null ? null : i.Element("name")	0
24792890	24792839	DateTime.ParseExact strings to datetime	string date = "11/07/14 18:19:20";\n\n        string dateformat = "dd/MM/yy H:mm:ss";\n        DateTime converted_date = DateTime.ParseExact(date,\n                 dateformat, CultureInfo.InvariantCulture);	0
17226848	17226782	PHP able to read Object list of a webservice generated by Asp.net C#	Using System.Xml.Serialization.XmlSerializer	0
304120	304109	Getting the icon associated with a running application	Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);	0
16816485	16816272	Post subset of the Model to the Controller from Razor view	[HttpPost]\npublic ActionResult MatchLines(SupplierInvoiceMatchingVm viewModel)\n{\n    var list = viewModel.Lines;\n    // ...\n}	0
27491849	27453783	How to iterate through listview cells C#	for (int x = 0; x < arrayList.Count; x++)\n{\n    //if x is 0 it's the first iteration so we want "IF"; otherwise we want ""\n    ListViewItem item = new ListViewItem(x == 0 ? "IF" : "");\n    //add the rest of the empty sub-elements with a loop\n    for (int y = 1; y < x; y++)\n    {\n        item.SubItems.Add("");\n    }\n    item.SubItems.Add("ID");\n    item.SubItems.Add("EX");\n    item.SubItems.Add("MEM");\n    item.SubItems.Add("WB");\n    for (int k = 5; k < ccNum; k++)//Set rest of row cells ""\n        item.SubItems.Add("");\n    listView5.Items.Add(item);\n}	0
3738296	3738250	How to get the next and previous node	var previous = Current.PreviousNode;\nvar next = Current.NextNode;	0
1477164	1477075	Load XML Data (Key/Value Pairs) into Data Structure	var doc = XDocument.Parse(xmlAsString);\nvar dict = new Dictionary<string, int>();\nforeach (var section in doc.Root.Element("Sections").Elements("Section"))\n{\n    dict.Add(section.Attribute("Folder").Value, int.Parse(section.Attribute("TabIndex").Value));\n}	0
26526396	26526048	HTTP URL splitting fails	Regex tileRegex = new Regex(@"/MapServer/tile/([0-9]+)/([0-9]+)/([0-9]+)");\n\nvar matches = tileRegex.Match(p.http_url);\n\nif (matches.Success)\n{\n    string path = "../MapServer/tile/{0},{1},{2}.png";\n\n    path = string.Format(path, matches.Groups[1].Captures[0], \n                               matches.Groups[2].Captures[0],\n                               matches.Groups[3].Captures[0]);\n\n    Bitmap bmap = new Bitmap(path);\n\n    ...\n}	0
25520057	24256320	Nopcommerce Error- "Page not Found" while redirecting from admin to plugin pages	var route = routes.MapRoute(RouteName,\n                  "admin/Plugins/PluginName/ControllerName/ActionName",\n                  new { controller = "ControllerName", action = "ActionName" },\n                  new[] { TheNamespaceOfControllerClass }\n             );\n\nroute.DataTokens.Add("area", "admin");	0
3315493	3309935	Correct way to move to another page in my app	NavigationService.Navigate()	0
20660675	20660614	How Collections with Read Only Modifier became Modifiable in C#?	public class ReadOnlyCollectionHolder\n{\n    private List<string> _innerCollection=new List<string>();\n\n    public ReadOnlyCollectionHolder()\n    {\n        ItemList = new ReadOnlyCollection<String> (_innerCollection);\n    }\n\n    public readonly ReadOnlyCollection<String> ItemList {get;private set;}\n}	0
34247853	34247507	Show Error Message if Nothing is selected from any of the Drop Down List's	if( DropDownList2.Text == "0" && DropDownList3.Text== "0" &&\n        DropDownList4.Text == "0" && DropDownList5.Text == "0"\n    || DropDownList6.Text == "0" && DropDownList7.Text == "0" )\n    {\n   Response.Write("Please select the quantity of the ticket.");\n    }	0
4073625	4073533	How do I make it so my .NET 4 console app is automatically checked with the "run as administrator" requirement	HKLM\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\layers	0
12446807	12446770	How to compare multidimensional arrays in C# ?	var equal =\n    data1.Rank == data2.Rank &&\n    Enumerable.Range(0,data1.Rank).All(dimension => data1.GetLength(dimension) == data2.GetLength(dimension)) &&\n    data1.Cast<double>().SequenceEqual(data2.Cast<double>());	0
15068258	15065053	Read a Word Document Using c#	Word.Application word = new Word.Application();\n       Word.Document doc = new Word.Document();\n       object fileName = @"C:\wordFile.docx";\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        string ReadValue = string.Empty;\n            // Activate the document\n        doc.Activate();\n\n         foreach (Word.Range tmpRange in doc.StoryRanges)\n         {\n            ReadValue += tmpRange.Text;\n         }	0
8938725	8938635	Create an Excel Add In Application in C#	private void UnloadBadAddins(bool unloadAddin)\n{\n    const string badAddin = "iManage Excel2000 integration (Ver 1.3)";\n\n    foreach(Office.COMAddIn addin in this.ExcelApp.COMAddIns)\n    {\n        if (addin.Description.ToUpper().Contains(badAddin.ToUpper()))\n        {\n            if (addin.Connect == unloadAddin)\n            {\n                addin.Connect = !unloadAddin;\n                return;\n            }\n        }\n    }\n}	0
10185083	10185046	Use the WPF toolkit messagebox using custom name	using MeBox = Xceed.Wpf.Toolkit.MessageBox;	0
25777651	25734469	How to define value of nested object at runtime in Autofac	var containerBuilder = new ContainerBuilder();\ncontainerBuilder.RegisterType<PersonWithJacket>();\n\nvar childContainer1 = new MultitenantContainer(new NullTenantIdStrategy(), containerBuilder.Build());\nchildContainer1.ConfigureTenant(null, builder => builder.Register(context => new Jacket("Hugo Boss")));\n\nvar childContainer2 = new MultitenantContainer(new NullTenantIdStrategy(), containerBuilder.Build());\nchildContainer2.ConfigureTenant(null, builder => builder.Register(context => new Jacket("H&M")));\n\nvar personWithHugoBossJacket = childContainer1.Resolve<PersonWithJacket>();\nvar personWithHandMJacket = childContainer2.Resolve<PersonWithJacket>();	0
29147430	29147259	Divide X by Y, return number of items in last, partial set	int population = 100;\nint numberOfGroups = 7;\nint groupSize = (population + numberOfGroups - 1)/numberOfGroups;\n\nConsole.WriteLine(groupSize);\n\nint remainder = population%groupSize;\n\nConsole.WriteLine(remainder);	0
14461766	14461663	list min index value c# from a class	TT.IndexOf(TT.Min());	0
12760182	12760126	How to create a smooth jumping movement?	y = k * t * (1 - t)	0
6646077	6646032	All elements before last comma in a string in c#	string new_string = s.Remove(s.LastIndexOf(','));	0
34087710	34087438	How to round down 0.005 to 3 decimal max in C#	var x  = 0;\nif((latitude*100) - Math.Truncate((latitude*100)) >=0.5)\n{\nx = (Math.Truncate((latitude*100))/100)+0.005;\n}\nelse\n{\nx = (Math.Truncate((latitude*100))/100);\n}	0
7364165	6313025	How can I programmatically determine the width of Y-axis section of a WPF chart?	MyChart.Loaded += (sender, e) =>\n{\n    // MyChart is about to be rendered\n    // it's now safe to access the ActualWidth properties of the chart components\n    MyRectangle.Left = MyChart.ActualWidth/2;\n}	0
11450385	11450227	How to handle json object in codebehind	string name = String.Empty;\nstring city = String.Empty;\nforeach (object item in userEnteredDetails)\n{\n Dictionary<string, object> details = item as  Dictionary<string, object>;\nif (details.ContainsKey("customerName"))\n name = details["customerName"] as string;\nif (details.ContainsKey("city"))\n city= details["city"] as string;\n}	0
31769268	31769222	Splitting string with dots and spaces	string input = "Hey. This is a test. Haha.";\nstring result = input.Replace(". ", ".\n");	0
1556273	1556175	Referring to ASP.NET controls from Business Logic	// Interface definition\npublic ISearchForm\n{\n    String Keywords { get; set; }\n    int ItemsPerPage { get; set; }\n    Action<string> SearchButtonClicked;\n    // ...\n}\n\n// Implementation\npublic SearchForm : ISearchForm\n{\n    public String Keywords\n    {\n        get { return txtKeywords.Text; }\n        set { txtKeywords.Text = value; }\n    }\n\n    // ...\n}	0
9782172	7401999	Set texture in effect file	texture Texture;\nsampler Texture2 = sampler_state\n{\n    texture = <Texture>;\n    magfilter = LINEAR;\n    minfilter = LINEAR;\n    mipfilter = LINEAR;\n    AddressU = mirror;\n    AddressV = mirror;\n};	0
25111698	25111629	Dictionary <string, uint> to comma-separated string?	var abcArray = abc.Split(',');\nmasterData.ToDictionary(p => p, p => (uint)(abcArray.Contains(p) ? 1 : 0));	0
12656081	12655975	How to get comparison of variable in lists as objects of class contained in another list?	List<Artists> artists = //the list of artists\nvar tags = artists.SelectMany(x => x.Tags).Distinct();\nforeach (var tag in tags)\n{\n    var artistsWithThisTag = artists.Where(x => x.Tags.Contains(tag));\n    //do something with artistsWithThisTag\n}	0
24631294	24613576	Initialize jagged arrays of different length automatically	public class PattRec\n{\n    public int[] neurone;\n    private double[][][] W = new double[3][][];\n\n    public PattRec()\n    {\n        neurone = new int[] { 3, 5, 1 };\n\n        W[0] = new double[][] {new double[1],new double[neurone[1]]};\n        W[1] = new double[][] {new double[neurone[1]],new double[neurone[0]] };\n        W[2] = new double[][] {new double[neurone[2]],new double [neurone[1]] };\n\n        foreach (double[][] array in W)\n        {\n            foreach (double[] item in array)\n            {\n                for (int i = 0; i < item.GetLength(0); i++)\n                {\n                    item[i] = 0;\n                }    \n            }\n\n        }\n    }\n\n  // Rest of the class, some other methods here, etc.\n}	0
8960591	8960509	Website never loads in awesonium	while (!loadFinished.WaitOne(100))\n            {\n                WebCore.Update();\n            }	0
29178617	29159794	login authentication with HttpClient returns status 463	var resp = await "http://ahpra.testnet.com/api/login"\n    .WithHeader("cache-control", "no-cache")\n    .PostUrlEncodedAsync(new {\n        j_username = "scott",\n        j_password = "xxxx"\n    });	0
26054459	26054264	Adding rows to a DataGridView with data from text Boxes	FilesGrid.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text,textBox4.Text);	0
18626378	18625618	How to get the Matlab workspace associated with the current Matlab project in C#?	save test.mat	0
6462300	6462091	How to use XmlElementAttribute for List<T>?	public class Test\n{\n    [XmlArray("Levels")]\n    [XmlArrayItem("L")]\n    public LevelList CalLevelList { get; set; }\n}	0
28235752	28235527	How to read multiple element(Columns) in xml	List<YourClass> objectForValuesAndComments=new List<YourClass>();\nXmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(@"C:\Location To XML\File.xml");\nforeach (XmlNode subnode in xmlDoc.DocumentElement.ChildNodes)\n{\n    YourClass objectToInsert=new YourClass();\n    foreacht(XmlNode SubSubNode in subnode.ChildNodes)\n    {\n       if (SubSubNode.Name == "value")\n       {\n          objectToInsert.Value = SubSubNode.InnerText;\n       }\n       else if (SubSubNode.Name == "comment")\n       {\n          objectToInsert.Comment= SubSubNode.InnerText;\n       }\n    }\n    objectForValuesAndComments.Add(objectToInsert);\n }	0
5092344	5092061	how to get a value and not the formula	Formula = "=Max(B2:" + bottomRight + ")"	0
4252992	4252983	What is the syntax to tell C# I want my number to be considered as a decimal?	MyMethod(4.6m)	0
11351542	11157272	Stored Procedure in sql server 2005	Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;	0
20619668	20556419	Parse HTML Table using HTML Agility Pack - No ID's for Table	//table[@cellpadding='0' and @cellspacing='0']/tr[1]	0
30038997	29974227	check html if a specific message appears	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(webBrowser.DocumentText);\nHtmlNode n = doc.DocumentNode.SelectSingleNode("//*[contains(@class, 'noticeBox')]");	0
30343125	30326645	MenuViewModel with Catel	protected override async Task Initialize.	0
22708996	22708727	ASP.Net Identity Check for multiple roles to get access	[Authorize(Roles="members")]\n[Authorize(Roles="admin")]	0
8833313	8832929	c# how to put several groups of words from textfile into arrays	string[] tmp = Regex.Split(originalString, @"(PEOPLE|ENTERPRISE|HOME)");\n\nList result = new List();\nfor(var i = 1; i < tmp.Count() - 1; i += 2) {\n    result.Add(tmp[i] + tmp[i+1]);\n}	0
27183358	27183286	How to remove all characters from a string before a specific character	string A = "Hello_World";\nstring str = A.Substring(A.IndexOf('_') + 1);	0
17146995	17146673	Set Size of an ActiveX Control in MS Access	public DummyCtrl()\n{ \n    this.Size = PreferredSize;\n    InitializeComponent();\n}	0
10485507	10485412	row count on dataset different than row count on datagridview	grid.DataSource = ds.Tables[0];	0
27573452	27561133	Prevent window from showing in alt tab	protected override CreateParams CreateParams\n{\n    get\n    {\n        CreateParams cp = base.CreateParams;\n        // turn on WS_EX_TOOLWINDOW style bit\n        cp.ExStyle |= 0x80;\n        return cp;\n    }\n}	0
720798	720779	How to create mutlidimensional list for this in C#?	List<List<int>> table = new List<List<int>>();\n        List<int> row = new List<int>();\n        row.Add(21);\n        row.Add(22);\n        row.Add(23);\n        row.Add(33); // and so on\n        table.Add(row);\n\n        row = new List<int>();\n        row.Add(1001);\n        row.Add(1002);\n        table.Add(row);\n\n        MessageBox.Show(table[0][3].ToString());	0
2456942	2456857	C#.NET How to access fields in user control dynamically?	Foreach(Control target in panel.Controls) {\n   if (target.GetType() == typeof(RadioButton) {\n      ((RadioButton)target).Checked = true;\n      //etc...\n   }\n}	0
20333644	20329848	Web application - getting path from class library to another	Assembly.GetManifestResourceStream	0
4836227	4836138	How setup my mono app from unix?	mono myapp.exe	0
3059407	3054266	How to use keywordsearch query in c#	using (KeywordQuery keywordQuery = new KeywordQuery(context))\n        {\n            keywordQuery.ResultTypes = ResultType.RelevantResults;\n            keywordQuery.EnableStemming = true;\n            keywordQuery.TrimDuplicates = true;\n            keywordQuery.StartRow = 0;\n            keywordQuery.SortList.Add(filterField, SortDirection.Ascending);\n\n           keywordQuery.QueryText = string.Format(CultureInfo.InvariantCulture, "scope:\"{0}\"", "people");\n            keywordQuery.SelectProperties.Add("FirstName");\n\n\n            ResultTableCollection resultsCollection = keywordQuery.Execute();\n\n            ResultTable resultsTable = resultsCollection[ResultType.RelevantResults];}	0
12256435	12256426	Convert Date MMDDYY to Date for database Insert	DateTime.ParseExact(text, "MMddyy", CultureInfo.InvariantCulture);	0
24685411	24685228	How to return an enemy to original position after losing aggro [issues[	private readonly float maxDistanceToHomePosition = 0.3f; // change this value as you like\n\n...\n\nif((transform.position - enemyHomePosition).magnitude > maxDistanceToHomePosition)\n{\n    ...\n} \n\n...	0
6972204	6963103	Is it possible to eagerly load a foreign natural key with NHibernate?	Session.CreateQuery	0
3468952	3468928	How to create a shorter name for a type in C#?	using SomeShorterName = A.B;	0
29439941	29437824	How to disable WebRTC in GeckoFX C#	GeckoPreferences.Default["media.peerconnection.enabled"] = false;	0
11863661	11863590	List to Datatable and add column	DataTable dt = ToDataTable(your list); // Get DataTable From List\n\ndt.Columns.Add(new Column("StatusText", typeof(string))); // Add New Column StatusText\n\n\n//Iterate All Rows \nforeach(DataRow row in dt.Rows)\n{\n   //Check Status value, and set StatusText accordingly. \n   row["StatusText"] = int.Parse(row["Status"])==1 ? "InActive" : "Active";\n}	0
20762051	20761679	How to detect that a text is wrapped in a label?	bool multiline = label.Height - label.Padding.Top - label.Padding.Bottom > label.Font.Size*2;	0
10167298	10167199	Leave desicion of creating an object to constructor in C#	bool TryCreate(parameters ..., out Result)	0
32767756	32767576	C# Can't get values from Listview items	Game game = e.AddedItems[0] as Game;\nMessageBox.Show("Selected: " + game.Name);	0
8977433	8977053	Cant get the couchbase .net memcache client to run, complains it's strong name validation failed	sn -Vr *,cec98615db04012e	0
8374522	8374310	Use selected text instead of selectedIndex	combobox.SelectedValue = "Computer";	0
21433035	21432999	Call a method in the declaration of a foreach	using(var iter = GetItemDetails(item).GetEnumerator())\n{\n    while(iter.MoveNext()\n    {\n        var item = iter.Current;\n        // ...\n    }\n}	0
26604014	26603117	How can we delete table items from redis?	keys urn:idbclients:*	0
31593696	31592946	C# Linq XML get text from multiple elements with the same name	return from product in doc.Descendants(ns + "ListOrderItemsResult")\n    from order in product.Element(ns + "OrderItems").Elements(ns + "OrderItem")\n    select new Address\n    {\n       Title = (string)order.Element(ns + "Title"),\n       ItemPrice = (string)order.Element(ns + "ItemPrice").Element(ns + "Amount"),\n       ShippingPrice = (string)order.Element(ns + "ShippingPrice").Element(ns + "Amount"),\n       Quantity = (string)order.Element(ns + "QuantityOrdered"),\n       P_OrderId = (string)product.Element(ns + "AmazonOrderId"),\n    };	0
5860661	5860628	Looking for a better way to get a collection of items by ID	var employees = (from e in MyDBDataContext.Employees\n                 join de in MyDBDataContext.DepartmentEmployees\n                     on e.EmployeeID equals de.EmployeeID\n                 where de.DepartmentID == this.DepartmentID\n                 select e).ToList();	0
13959892	13959864	Inserting a valid html link into a string for an email	String mailstring = "Blah blah blah blah. Click <a href=\"http://www.example.com\">here</a> for more information."	0
10228791	10228688	Saving html file from server	Response.AppendHeader("content-disposition", "attachment; filename=test.html");\n Response.TransmitFile(Server.MapPath("~/SentinelOperationsUI/SoFaXML.html"));\n Response.End();	0
20712262	20712214	Using Regex Inside Property Setter	public string NameFormal        \n{       \n    get {return nameFormal;}    \n    set     \n    {   \n        string pattern = "^\\d{3}-\\d{3}-\\d{4}$"; //input your regex here\n        if (Regex.IsMatch(value, pattern))\n        {\n            nameFormal = value;\n        }\n        else\n        {\n            //didn't match\n        }\n    }   \n}	0
9197060	9196777	Print XML that is going to be returned from web service	MyReturnObject retVal = new MyReturnObject(myParam)\nvar serializer = new DataContractSerializer(retVal.GetType());\n\nusing (var xmlData = new StringWriter())\nusing (var writer = XmlWriter.Create(xmlData))\n{\n    serializer.WriteObject(writer, retVal);\n    Console.WriteLine(xmlData.ToString());\n}	0
714312	714123	Odbc Paradox Driver WHERE clause Date	...where   [Date] = {d 'yyyy-MM-dd'} AND...	0
8377464	8377053	LINQ XML obtaining child nodes of parent node	var result = from x in doc.Root.Descendents("node")\n             where (string)x.Attribute("url") == "#"\n                && (string)x.Attribute("title") == "item 1"\n                && (string)x.Attribute("key") == "Item1"\n             from y in x.Elements("node")\n             where (string)x.Attribute("key") == "Sub1"\n                || (string)x.Attribute("key") == "Sub2"\n             select y;	0
7474661	7474613	Get the order of bytes by value	byte[] byteArray = new byte[4] { 42, 5, 17, 39 };\n\nvar results = byteArray.Select((b, i) => new { Value = b, Index = i})\n                    .OrderBy(p => p.Value)\n                    .Select((p, i) => new { Index = p.Index, SortedPosition = i + 1 })\n                    .OrderBy(p => p.Index)\n                    .Select(p => p.SortedPosition);	0
6227366	6225670	Regular expression to read tags in a HTML	String h1Regex = "<h1[^>]*?>(?<TagText>.*?)</h1>";\n\nMatchCollection mc = Regex.Matches(Data, h1Regex, RegexOptions.Singleline);\n\nforeach (Match m in mc) {\n    Console.Writeline (m.Groups["TagText"].Value);\n}	0
13292160	13292108	How to launch a JVM from C#	System.Diagnostics.Process.Start("yourPath\java.exe", "Command Line Arguments");	0
26613161	26612835	Convert XML to Json Array when only one object	var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >\n             <Item json:Array='true'>\n                <Name>name</Name>\n                 <Detail>detail</Detail>    \n            </Item>\n            </Items>";	0
21995701	21995506	RibbonToggleButton displays image badly	RenderOptions.BitmapScalingMode="HighQuality"	0
1307523	1307516	Is it possible to "cancel" a dependency-property assignment from an IValueConverter, if there was no change in the property value?	Binding.DoNothing	0
8768650	8745383	How can I stop a postback from refreshing the page at the client	System.Web.HttpContext.Current.Response.StatusCode = 204;	0
9672329	9641659	What's the best way to run a regex against an MS Excel file in C#?	static void ReadMSOffice2003ExcelFile(string file) {\n        FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);\n        ReadMSOfficeExcelFile(file, ExcelReaderFactory.CreateBinaryReader(stream));\n    }\n\n\n    static void ReadMSOffice2007ExcelFile(string file) {\n        FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);\n        ReadMSOfficeExcelFile(file, ExcelReaderFactory.CreateOpenXmlReader(stream));\n    }\n\n\n    static void ReadMSOfficeExcelFile(string file, IExcelDataReader xlsReader) {\n        string xlsRow;\n        while (xlsReader.Read()) {\n            xlsRow = "";\n            for (int i = 0; i < xlsReader.FieldCount; i++) {\n                xlsRow += " " + xlsReader.GetString(i);\n            }\n            CheckLineMatch(file, xlsRow);\n        }\n    }	0
8392963	8392413	ASP.NET Returning JSON with ASHX	context.Response.Write(\n    jsonSerializer.Serialize(\n        new\n        {\n            query = "Li",\n            suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },\n            data = new[] { "LR", "LY", "LI", "LT" }\n        }\n    )\n);	0
11025536	11024383	How to quickly batch save Bitmaps?	(6 * 60) / 20 = 18 times slower\n4 * 4         = 16 times the image size	0
8609883	8609805	Removing properties of an inherited object in C#	public class MyException : Exception\n{\n    public new System.Reflection.MethodBase TargetSite\n    {\n        get { return null; }\n    }\n\n    public MyException() : base()\n    {\n\n    }\n}	0
33726687	33353863	Cannot access SQL Azure DB from Azure website but same connection string works from local website	SQL Server	0
8825308	8825133	How to hide an excel column?	CloseFile()	0
24391156	24373602	Check if a list of objects contains another list (only have a property) in C# Linq	bool hasAllItems = UserList.All(s => SystemList.Any(mo => mo.Id == s));	0
18847483	18847283	all value from query string after some specific character in asp.net	string result = link.Substring(link.IndexOf("/id/") + 4);	0
6959627	5564359	Saving List<CartItem> to a Session in ASP.NET	public class ShoppingCart\n{\n    public List<CartItem> Items { get; private set; }\n    public static SqlConnection conn = new SqlConnection(connStr.connString);\n    public static readonly ShoppingCart Instance;\n\n    static ShoppingCart RetrieveShoppingCart()\n    {\n        if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)\n        {\n                Instance = new ShoppingCart();\n                Instance.Items = new List<CartItem>();\n                HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;  \n        }\n        else\n        {\n            Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];\n        }\n\n        return Instance;\n    }\n}	0
26228551	26228505	How to use environment variables in Path.Combine()?	var path = Environment.ExpandEnvironmentVariables(value);	0
8193050	8192953	Control the computer's volume in C#	winmm.dll	0
13733981	13733874	How to get all words over a specified length from a string?	static IEnumerable<string> getWordsWithMinLength(string text, int minLength)\n{\n    string[] words = text.Split();\n    return words.Where(w => w.Length >= minLength);\n}	0
34206441	34206373	Accessing a bool from a different script in Unity C#	target.getComponent<BallController>().isGrounded	0
10234428	10233578	Import unmanaged code import to delphi from C#	function ABSOpen(pszDsn: PAnsiChar; var phConnection: Cardinal): Integer; \n    stdcall; external 'bsapi.dll';	0
21562262	21560563	Get value from threaded method	public class AlbumViewModel: BaseViewModel // BaseViewModel is your code that implements INotifyPropertyChanged\n{\nprivate string name\npublic string Name\n{\n   get{ return name;}\n   set\n   {\n      if(name != value)\n      {\n          name = value;\n          FirePropertyChanged("Name");\n          LoadBackgroundImageAsync(value);\n      }\n   }\n\n}\n\nprivate ImageSource backgroundImage;\npublic ImageSource BackgroundImage\n{\n     get{return backgroundImage;}\n     private set\n     {\n       if(backgroundImage != value)\n       {\n           background = value;\n           FirePropertyChanged("BackgroundImage");\n       }\n     }\n}\nprivate Task LoadBackgroundImageAsync(string name)\n{\n    var retv = new Task(()=>\n    {\n        var source = GlobalDB.GetImage(name, 400);\n        source.Freeze();\n        BackgroundImage = source;\n    });\n    retv.Start();\n    return retv;\n}\n}	0
155597	153438	Retrieving the original error number from a COM method called via reflection	private void button1_Click(object sender, EventArgs e)\n    {\n        try\n        {\n            var f_oType = Type.GetTypeFromProgID("Project1.Class1");\n            var f_oInstance = Activator.CreateInstance(f_oType);\n            f_oType.InvokeMember("Test3", BindingFlags.InvokeMethod, null, f_oInstance, new object[] {});\n        }\n        catch(TargetInvocationException ex)\n        {\n            //no need to subtract -2147221504 if non custom error etc\n            int errorNumber = ((COMException)ex.InnerException).ErrorCode - (-2147221504);\n            MessageBox.Show(errorNumber.ToString() + ": " + ex.InnerException.Message);\n        }\n        catch(Exception ex)\n        { MessageBox.Show(ex.Message); }\n    }	0
32308755	32307222	Converting a byte[]-Array to ANSI	// Create a temporary file, delete if it already exists\nstring MyFile = Path.GetTempPath() + v_fexpd.Dateiname;\nif (File.Exists(MyFile)) {\n    File.Delete(MyFile);\n}\n\nusing (TextWriter tw = new StreamWriter(MyFile.ToString(), true, System.Text.Encoding.GetEncoding(1252)))\n    tw.WriteLine(v_Inhalt);\n\ncontext.Response.Clear();\ncontext.Response.AddHeader("Content-Disposition", "attachment; filename=" + v_fexpd.Dateiname);\ncontext.Response.AddHeader("Content-Type", "text/csv; charset=windows-1252");\n\n// Write the file - which at this point is correctly-encoded - \n// directly into the output.\ncontext.Response.WriteFile(MyFile);\n\ncontext.Response.End();\n\n// Leave no traces\nFile.Delete(MyFile);	0
9118556	9118143	FluentAssertion fail to compare enumerable of strings	[Test] \npublic void foo()  \n{ \n  var collection = new[] { "1", "2", "3" }; \n  collection.Should().Equal(new[] {"1", "2", "3"});              \n}	0
17459630	17459592	Access a member of a class in c#?	var addr = new addresses();\nvar created = addr.date_created;\n//same for date_modofied	0
20212203	20212162	In clause in lambda expression	.Where(x => charids.Contains(x.Attribute("id").Value)	0
2516797	2498572	How to compress a directory into a zip file programmatically	using (var zip = new Ionic.Zip.ZipFile())\n{\n    zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");\n    zip.Save("MyFile.zip");\n}	0
16843693	16843410	Linking to control panel in C# (Run advertised programs and Configuration Manager)	var cplPath = System.IO.Path.Combine(Environment.SystemDirectory, "control.exe");\nSystem.Diagnostics.Process.Start(cplPath, "/name Microsoft.ProgramsAndFeatures");	0
4087941	4087847	Read XML file just like python's lxml with C#?	void GetNodeList()\n{\n    var connection = this.doc.Descendants("Connections").First();\n    var cons = connection.Elements("Connection");\n\n    foreach (var con in cons)\n    {\n        var id = (string)con.Attribute("ID");\n    }\n}	0
1881463	1819243	Adding values to an InfoPath XML schema	doc.Load("copiedFile.xml");	0
9090981	9090962	How to unbox an array of string?	string[] someVarArray = obj as string[] \nif(someVarArray!=null)\n{\n //do something\n}	0
9018994	9018742	Change CssClass of a textbox if validation failed in asp.net using  validators	if(!RequiredFieldValidator1.IsValid){\n    //You might have to adjust where its looking for the control\n    TextBox txt = form1.FindControl(RequiredFieldValidator1.ControlToValidate) as TextBox;\n    if (txt != null)\n    {\n        txt.CssClass = "txtbox300Comment";\n    }\n\n}	0
3303095	3302956	Design Pattern Options for Same Return Object but Different Enum Type Value and Parameter Value Types	public static bool TryGetIntIntAction(\n    ActionType type, out Func<int, int, int> func)\n{\n    switch (type)\n    {\n    case ActionType.Action1:\n        func = (val1, val2) => new ActionClass1(val1, val2).DoAction();\n        return true;\n    default:\n        func = null;\n        return false;\n    }\n}\n\npublic static bool TryGetStringAction(\n    ActionType type, out Func<string, int> func)\n{\n    switch (type)\n    {\n    case ActionType.Action2:\n        func = val1 => new ActionClass2(val1).DoAction();\n        return true;\n    case ActionType.Action3:\n        func = val1 => new ActionClass3(val1).DoAction();\n        return true;\n    default:\n        func = null;\n        return false;\n    }\n}	0
6397249	6397235	Write bytes to file	public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)\n{\n   try\n   {\n      // Open file for reading\n      System.IO.FileStream _FileStream = \n         new System.IO.FileStream(_FileName, System.IO.FileMode.Create,\n                                  System.IO.FileAccess.Write);\n      // Writes a block of bytes to this stream using data from\n      // a byte array.\n      _FileStream.Write(_ByteArray, 0, _ByteArray.Length);\n\n      // close file stream\n      _FileStream.Close();\n\n      return true;\n   }\n   catch (Exception _Exception)\n   {\n      // Error\n      Console.WriteLine("Exception caught in process: {0}",\n                        _Exception.ToString());\n   }\n\n   // error occured, return false\n   return false;\n}	0
5905617	5903193	How to programmatically create pause in Windows Service app?	System.Threading.Thread.Sleep(1000); // sleep for 1 second	0
3734622	3734521	How to determine path of exlorer.exe in .NET?	string windir = Environment.GetEnvironmentVariable("windir");\nstring explorerPath = windir + @"\explorer.exe";	0
6291279	6291260	Is possible with LINQ to extract from an array of objects the value of one property and create a new array?	string[] _cProperties = _array.Select(x => x.C).ToArray();	0
10147668	10048239	Finding each page's relative location in a website directory structure using a master page?	string[] urlArray = Page.AppRelativeVirtualPath.Split('/');\n\nint depth = urlArray.Length-2;\n\n\nstring pathToTop = "";\n\nfor (int j = 1; j <= depth; j++) pathToTop = pathToTop + "../";\n\n\nstring currentpage = urlArray[depth+1];   \n\nstring currentdir = "";\nstring backdir = "";\nstring twobackdir = "";\n\ncurrentdir = urlArray[depth];\nif (depth > 1) backdir = urlArray[depth-1];\nif (depth > 2) twobackdir = urlArray[depth - 2];	0
9155733	9155608	Disable an asp:RequiredFieldValidator if a checkbox is checked	var ctrl1 = document.getElementById('<%=rfvID.ClientID%>');\n                    ValidatorEnable(ctrl1, false);	0
4086195	4086161	Removing object from IEnumerable	IEnumerable<T>	0
7027765	7027701	Convert this 20110811T131446+0200 to C# dateTime object	DateTime dateTime;\n\nif (DateTime.TryParseExact(text, "yyyyMMdd'T'HHmmsszzzz",\n                           CultureInfo.InvariantCulture, out dateTime))\n{\n    // All was okay\n}\nelse\n{\n    // Handle failure\n}	0
4380034	4377946	Is it possible to create a custom control property only settable at design time?	private Boolean IsCreated = false;\n\n    private String myVar1;\n    public String MyVar1\n    {\n       get { return myVar1; }\n       set {\n              if (LicenseManager.UsageMode ==  LicenseUsageMode.Designtime \n                    || !IsCreated)\n              {\n                  myVar1 = value;\n                  IsCreated = true;\n              }\n    }	0
25511863	25511653	Trouble setting camera follow target up	GameObject.Find("Camera").GetComponent<SmoothFollow>().target = myPlayerGO.transform;	0
15169789	15169469	Accessing task contents from await	await rootPage.LoadPixelData("mypic.png");\nmyobject.pixelData = rootPage.ImageDictionary["mypic.png"];\nloadedFlag = true;	0
11798538	11786640	How to maximize window in XNA	var form = (Form)Form.FromHandle(Window.Handle);\nform.WindowState = FormWindowState.Maximized;	0
3091060	3090319	How to adapt a simple String Extension to support SQL	public IEnumerable<String> Example()\n{\n     var query = from f in foos\n            where f.Id == 'myId'\n            select f;\n\n     var result = query.AsEnumerable();\n\n     return from r in result\n            select r.Url.ToUrlString();\n}	0
15257549	15257398	Access specific frame via Watin	Frame frame = browser.Frame(Find.ByClass("yourClassName")); //or by id or name...\nframe.TextField(Find.ById("ctl00_MainContent_txtUsername")).TypeText("FakeUsername");\n//and etc...	0
18840107	18839473	Parsing table rows into nested collections	var list3 = list1.AsEnumerable()\n                 .GroupBy(x=>x.Field<string>("facility"))\n                 .Select(g=> new Facility{ Facility=g.Key,       \n                             Services = g.GroupBy(x=>x.Field<string>("Role"))\n                                         .Select(g1=> new Service{\n                                                    Service = g1.Key,\n                                                    Roles = g1.GroupBy(x=>x.Field<string>("RWP"))\n                                                              .Select(g2=> new Role{\n                                                                  H = g2.Key\n                                                               }).ToList()\n                                                 }).ToList()\n                        }).ToList();	0
14925937	14903904	Strip Adobe Reader and Version requirements from PDF before outputting it to browser	n-400.pdf	0
28032745	28032537	Handle an array inside a list an infragistics ignite datagrid	public string PhoneNumbers1\n    {\n        get\n        {\n            if ((PhoneNumbers != null) && (PhoneNumbers.Length > 0))\n            {\n                return PhoneNumbers[0].Number;\n            }\n            else\n            {\n                return string.Empty;\n            }\n        }\n    }	0
18560900	18555312	Setting Buffer Size in GZipStream	private static string DecompressGzip(Stream input, Encoding e)\n    {\n\n        using (Ionic.Zlib.GZipStream decompressor = new Ionic.Zlib.GZipStream(input, Ionic.Zlib.CompressionMode.Decompress))\n        {\n\n            int read = 0;\n            var buffer = new byte[4096];\n\n            using (MemoryStream output = new MemoryStream())\n            {\n                while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)\n                {\n                    output.Write(buffer, 0, read);\n                }\n                return e.GetString(output.ToArray());\n            }\n\n\n        }\n\n    }	0
16150991	16150767	Create List with anonymous objects	var dummyData = new[]\n        {\n            Tuple.Create(1, 1, true, "Yes?", "int"),\n        }.ToList();\n        ViewBag.Header = dummyData;	0
3158739	3157524	C# - Parsing partial dates in different formats	public static string SimplifyDateFormat(DateTimeFormatInfo DTFI)\n{\n    StringBuilder SB = new StringBuilder(DTFI.ShortDatePattern.ToLower());\n\n    SB.Replace("m y", "m/y").Replace(" '?.'", "").Replace(" ", "").Replace("dd", "d")\n    .Replace("mm", "m").Replace("yyyy", "y").Replace("yy", "y");\n\n    if (SB[SB.Length - 1] == '.') SB.Remove(SB.Length - 1, 1);\n    return SB.ToString();\n}	0
825741	825651	How can I send the F4 key to a process in C#?	using System;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nnamespace TextSendKeys\n{\n    class Program\n    {\n        [DllImport("user32.dll")]\n        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n        static void Main(string[] args)\n            {\n                Process notepad = new Process();\n                notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";\n                notepad.Start();\n\n                // Need to wait for notepad to start\n                notepad.WaitForInputIdle();\n\n                IntPtr p = notepad.MainWindowHandle;\n                ShowWindow(p, 1);\n                SendKeys.SendWait("ABC");\n            }\n    }\n}	0
23050535	23050500	Error in ListView: InvalidArgument = Value of '0' is not valid for 'index'	if(list_answers.SelectedIndex == -1)\n    return;\n\nor\n\nif(list_answers.SelectedItems.Count == 0)\n    return;	0
25550368	25532245	Windows 8 App - LINQ search results	string search = TBSearch.Text;\n\n                var custSearchQuery = from c in db.Table<Customers>()\n                                      where c.customerName.Contains(search)\n                                      select c;	0
13199872	13199729	How to solve this Timeslot issue in C#	// Store a list of attempts\nvar attempts = new List<DateTime>();\n\n// Determine if 10 or more attempts have been made in the last 5 minutes\nbool lockout = attempts.Where(a => (DateTime.Now - a).TotalMinutes <= 5).Count() >= 10;\n\n// Register an attempt\nattempts.Add(DateTime.Now);\n\n// Remove attempts older than 5 minutes\nattempts.Where(a => (DateTime.Now - a).TotalMinutes > 5).ToList()\n    .ForEach(a => attempts.Remove(a));	0
19799536	19799385	How can I get the GPS location for use in a website?	navigator.geolocation.getCurrentPosition	0
28113461	28112864	WPF: Several two way bindings to same property	private string someproperty\npublic string SomeProperty1 \n{\n     get { return someproperty; };\n     set\n     {\n         if (someproperty == value) return;\n         someproperty = value;\n         NotifyPropertyChanged("SomeProperty1");\n         NotifyPropertyChanged("SomeProperty2");\n     }\n}\npublic string SomeProperty2 \n{\n     get { return someproperty; };\n     set\n     {\n         if (someproperty == value) return;\n         someproperty = value;\n         NotifyPropertyChanged("SomeProperty1");\n         NotifyPropertyChanged("SomeProperty2");\n     }\n}\n\n<TextBox Text="{Binding SomeProperty1, Mode=TwoWay}"></TextBox>\n<TextBox Text="{Binding SomeProperty2, Mode=TwoWay}"></TextBox>	0
5108390	5108319	C# Can a base class property be invoked from derived class	class baseTest \n{\n    private string _t = string.Empty;\n    public virtual string t {\n        get{return _t;}\n        set\n        {\n            Console.WriteLine("I'm in base");\n            _t=value;\n        }\n    }\n}\n\nclass derived : baseTest\n{\n    public override string t {\n        get { return base.t; }\n        set \n        {\n            Console.WriteLine("I'm in derived");\n            base.t = value;  // this assignment is invoking the base setter\n        }\n    }\n}\n\nclass Program\n{\n\n    public static void Main(string[] args)\n    {\n        var tst2 = new derived();\n        tst2.t ="d"; \n        // OUTPUT:\n        // I'm in derived\n        // I'm in base\n    }\n}	0
13749879	13749480	how to run code on program process end	class Program\n{\n    static void Main(string[] args)\n    {\n        var startInfo = new ProcessStartInfo("notepad.exe");\n        var process = Process.Start(startInfo);\n        process.WaitForExit();\n        //Do whatever you need to do here\n        Console.Write("Notepad Closed");\n        Console.ReadLine();\n    }\n}	0
29324722	29313666	how to use one function of a script in another script in unity using c#	PlayerController myCharactersScript;\nvoid Start(){\n     myCharactersScript = GameObject.Find("myCharactersName").GetComponent<PlayersController>();\n\n\n}\n\npublic void OnTriggerEnter2D(Collider2D target){\nif (target.gameObject.tag == "Deadly") {\n    Destroy (gameObject);\n   myCharactersScript.BulletCount();\n}\n\n}	0
34494122	34494021	Regular expression to capture between two words	using System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n {\n    public static void Main()\n    {\n        var equivalentSentence = "[[at the Location ]] [[Location at]] [[Location]]";       \n\n        Regex regex = new Regex(@"\[\[(?<location>(.*?)) \]\]");\n\n        Match match = regex.Match(equivalentSentence);\n\n        if (match.Success)\n        {\n            var location = match.Groups["location"].Value;\n            Console.WriteLine(location);\n        }\n    }\n}	0
12350315	12164716	InvalidOperationException when trying to assign an XmlElementAttribute to a custom IXmlSerializable object under .NET CF	public class ClassB<TKey, TValue>\n    : NonSerializableClassC<TKey, TValue>, IXmlSerializable\nwhere TKey : IXmlSerializable\nwhere TValue : IXmlSerializable	0
15850734	15850690	MaxReceivedMessageSize in WCF Hosted Service in console application	Uri baseAddress = new Uri("http://localhost:8080/Test");\nvar serviceHost = new ServiceHost(typeof(TestService));\nvar basicHttpBinding = new BasicHttpBinding();\nbasicHttpBinding.MaxReceivedMessageSize = int.MaxValue;\nserviceHost.AddServiceEndpoint(typeof(IService), basicHttpBinding, baseAddress);	0
6073903	6073807	Create DateTime from string without applying timezone or daylight savings	DateTime clientsideProfileSyncStamp =\n  DateTime.Parse(\n    "20-May-2011 15:20:00",\n    CultureInfo.CurrentCulture,\n    DateTimeStyles.AssumeUniversal\n  );	0
17200536	17199500	JsonConvert string to integer about digit grouping symbol	public class FormatConverter : JsonConverter\n{\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        throw new NotImplementedException();\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        if (objectType == typeof(int))\n        {\n            return Convert.ToInt32(reader.Value.ToString().Replace(".", string.Empty));\n        }\n\n        return reader.Value;\n    }\n\n    public override bool CanConvert(Type objectType)\n    {\n        return objectType == typeof(int);\n    }\n}\n\n\n[Test]\npublic void ConvertJson()\n{\n    const string Json = "{\"ProductCalcKey\":\"xxx\",\"PaperType\":\"1\",\"Quantity\":\"3.500\"}";\n    var o = (UnitPrice)JsonConvert.DeserializeObject(Json, typeof(UnitPrice), new FormatConverter());\n    Assert.AreEqual(3500, o.Quantity);\n}	0
23681232	23680261	Using ASP.NET how can I create a zip file from an array of strings?	ZipFile zipFile = new ZipFile();\nint fileNumber = 1;\n\nforeach(string str in strArray)\n{\n    // convert string to stream\n    byte[] byteArray = Encoding.UTF8.GetBytes(contents);\n    MemoryStream stream = new MemoryStream(byteArray);\n\n    stream.Seek(0, SeekOrigin.Begin);\n\n    //add the string into zip file with a name\n    zipFile.AddEntry("String" + fileNumber.ToString() + ".txt", "", stream);\n}\n\nResponse.ClearContent();\nResponse.ClearHeaders();\nResponse.AppendHeader("content-disposition", "attachment; filename=strings.zip");\n\nzipFile.Save(Response.OutputStream);\nzipFile.Dispose();	0
18397537	18397269	Print Image One by one C#	var files = Directory.GetFiles(@"C:\temp\", "*.jpg");\n\n        foreach (var i in files)\n        {         \n            var objPrintDoc = new PrintDocument();\n            objPrintDoc.PrintPage += (obj, eve) =>\n                {\n                    System.Drawing.Image img = System.Drawing.Image.FromFile(i);\n                    Point loc = new Point(100, 100);\n                    eve.Graphics.DrawImage(img, loc);\n                };\n            objPrintDoc.Print();       \n        }	0
4009777	4009603	How to check and extract string via RegEx?	string temp = "//something//img/@src";\nvar match = Regex.Match(tmp, @"/@([\w]+)$", RegexOptions.RightToLeft);\nif (match.Success)\n{\n   string extracted = match.Groups[1].Value;\n   ...\n}\nelse\n{\n   ...\n}	0
8912213	8911794	How to find a nested control inside of asp repeater	public void RssFeedItemDataBound(object sender, RepeaterItemEventArgs e)\n    {\n\n        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n        {\n\n            HtmlGenericControl listControl = (HtmlGenericControl)e.Item.FindControl("socialListItem");\n\n            if (listControl != null)\n            {\n                if (!ShowSource)\n                {\n                    HtmlGenericControl spanControl = (HtmlGenericControl)listControl.FindControl("source");\n                    spanControl.Visible = false;\n                }\n\n                listControl.Attributes["class"] += ((XmlFeedItem)e.Item.DataItem).XmlFeedType;\n            }\n        }\n    }	0
6612170	6612139	Comparing DateTime objects	if (dt2 > dt1) {\nprint dt2 is newer than dt1 }	0
21637372	21637172	C# - split string	for (int i = 0; i < S.length; i++) {\n    string back = S.substring(i);\n    string front = S.substring(0,i);\n    if (T.equals(back + front))\n         result = true;\n}	0
24222100	24221251	Need guidance on best way to approach a curriculum database	Keyword table\n[KeywordId] INT NOT NULL,\n[Keyword] NVARCHAR(max_size_of_keyword)\n\nCoureKeyword table\n[CourseKeywordId] INT NOT NULL,\n[CourseId] INT NOT NULL,\n[KeywordId] INT NOT NULL	0
6614029	6613940	How to add different icons/images to datagridview row header in c#?	protected virtual void OnRowDataBound(GridViewRowEventArgs e) {\n   if (e.Row.RowType == DataControlRowType.Header) {\n       // process your header here..\n    }\n}	0
5499578	5499459	How to get DisplayAttribute of a property by Reflection?	public static string GetPropertyName<T>(Expression<Func<T>> expression)\n{\n    MemberExpression propertyExpression = (MemberExpression)expression.Body;\n    MemberInfo propertyMember = propertyExpression.Member;\n\n    Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);\n    if(displayAttributes != null && displayAttributes.Length == 1)\n        return ((DisplayAttribute)displayAttributes[0]).Name;\n\n    return propertyMember.Name;\n}	0
10343510	10343471	Get a character from alt code (without keyboard events)?	char aaaa = (char)i;\n//i is any alt code	0
21139751	21139136	Is it possible to inject a control into the body of the page from the code behind?	runat="server"	0
33087304	33087177	Compare object with an array with another array	var result = groups.Where(g => g.FocusAreas.All(f => focusSelected\n              .Any(fs => (FocusEnum)Enum.Parse(typeof(FocusEnum), fs, true) == f.Focus)));	0
26002742	26001380	Set a culture on c# backend page	protected override void InitializeCulture()\n    {\n\n        HttpCookie cookie = Request.Cookies["CurrentLanguage"];\n        if (!IsPostBack && cookie != null && cookie.Value != null)\n        {\n            if (cookie.Value.ToString() == "en-CA")\n            {\n               // currently english\n                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-CA");\n                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-CA");\n                base.InitializeCulture();\n            }\n            else\n            {\n               //currently french\n                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA");\n                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");\n                base.InitializeCulture();\n            }\n        }\n    }	0
2026790	2026743	accessing Frames rendered in webbrowser control in C#.net	webBrowser1.Document.Window.Frames	0
14049305	13949366	ASP.net failing to add role to user	oncreateduser="CreateUserWizard1_CreatedUser"	0
11723700	11718248	My own taskbar for Win CE	%WINCEROOT%\PUBLIC\SHELL\OAK\HPC\EXPLORER\TASKBAR\taskbar.cpp	0
11729717	11729647	How to only show some of the values in an array in an textbox?	List<int> indices = new List<int>();\nfor (int i=0; i<myarray.Length; i++)\n{\n    if (myarray[i] == "reserved") indices.Add(i);\n}	0
9080656	9080620	FIPS validated application with HMAC function based on SHA512?	public class MyHMACSHA512 : HMAC\n{\n    public MyHMACSHA512(byte[] key)\n    {\n        HashName = "System.Security.Cryptography.SHA512CryptoServiceProvider";\n        HashSizeValue = 512;\n        BlockSizeValue = 128;\n        Key = key;\n    }\n}	0
6357505	6357440	how to keep one List with saved entries after page_load?	public IList<string> QuestionIDs\n{\n   get\n   {\n      var obj = ViewState["QuestionIDs"];\n      if(obj == null)\n      {\n         obj  = new List<string>();\n         ViewState["QuestionIDs"] = obj;\n      }\n      return (IList<string>)obj;\n   }\n}	0
23852999	23851606	Repeating a method call	private static Timer _Timer;\n\npublic static void Main()\n{\n        // Create a timer with a 8 second interval.\n        _Timer= new System.Timers.Timer(8000);\n\n        // Hook up the Elapsed event for the timer. \n        _Timer.Elapsed += OnTimedEvent;\n        _Timer.Enabled = true;\n\n       // Start you other stuff here\n }\n\n private static void OnTimedEvent(Object source, ElapsedEventArgs e)\n {\n        // Call your web service here\n }	0
15204449	15204198	Run multiply instances of the same method simultaneously in c# without data loss?	namespace ConsoleApplication9\n{\n  using System.Collections.Generic;\n  using System.Threading.Tasks;\n\n  class Program\n  {\n    static void Main()\n    {\n      var numbers = new List<int>();\n\n      for(int a=0;a<=70;a++)\n      {\n        for(int b=0;b<=6;b++)\n        {\n          for(int c=0;c<=10;c++)\n          {\n            var unmodifiedA = a;\n            var unmodifiedB = b;\n            var unmodifiedC = c;\n\n            Task.Factory.StartNew(() => MyMethod(numbers, unmodifiedA, unmodifiedB, unmodifiedC));\n          }\n        }\n      }\n    }\n\n    private static void MyMethod(List<int> nums, int a, int b, int c)\n    {\n      //Really a lot of stuffs here\n    }\n  }\n}	0
13267259	13266916	How to pause a Threading.timer to complete a function	object lockObject = new object();\n\nprivate void ProcessTimerEvent(object state) \n {\n   if (Monitor.TryEnter(lockObject))\n   {\n     try\n     {\n       // Work here\n     }\n     finally\n     {\n       Monitor.Exit(lockObject);\n     }\n   }\n }	0
23251054	23250992	Insertt value to database from GridView	cmd.CommandText = ("INSERT INTO rezerwacje [miejsca] VALUES(@nm)");\ncmd.Parameters.Add(new SqlParameter("nm", nm));	0
13218694	13218631	How to call this javascript function from code behind	string script2 = String.Format("var ctl; ctl = new jGauge();  ctl.init('{0}','{1}');", param1, param2);\nthis.Page.ClientScript.RegisterStartupScript(this.GetType(), "initialize control", script2, true);	0
5723473	5709859	How to disable mailto popup in WebBrowser for Pocket PC .NET CF 3.5?	TextReader tr = File.OpenText(e.Url.LocalPath);\n  htmlFile = tr.ReadToEnd();\n  tr.Close();\n  tr.Dispose();\n\n  if (htmlFile.Contains("mailto:support@website.com"))\n  {\n      htmlFile = htmlFile.Replace("mailto:support@website.com", @"about:blank");\n\n      //Recreate new file with fixed html\n      File.Delete(e.Url.LocalPath);\n      TextWriter tw = File.CreateText(e.Url.LocalPath);\n      tw.Write(htmlFile);\n      tw.Flush();\n      tw.Close();\n      tw.Dispose();\n\n      Refresh();\n  }	0
3594565	3594558	looking for a C# mocking framework that allows mocking static methods	Isolate.WhenCalled(() => MyClass.MethodReturningZero()).WillReturn(1);	0
7197030	7195146	How can I write a route to catch *.php?	routes.MapRoute("php", "{*allphp}", new { ... }, new { allphp = @".*\.php" });	0
13964890	13964462	Cannot open SQLite database	private void InsertPlatypiRequestedRecord(string platypusId, string platypusName, DateTime invitationSentLocal)\n{\n    using (var db = new SQLiteConnection(SQLitePath))\n    {\n        db.CreateTable<PlatypiRequested>();\n        db.RunInTransaction(() =>\n        {\n            db.Insert(new PlatypiRequested\n            {\n                PlatypusId = platypusId,\n                PlatypusName = platypusName,\n                InvitationSentLocal = invitationSentLocal\n            });\n        });\n    }\n}	0
26040237	14047754	How to add cross domain support to WCF service	protected void Application_BeginRequest(object sender, EventArgs e)\n{\n    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");\n    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")\n    {\n        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");\n        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");\n        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");\n        HttpContext.Current.Response.End();\n    }\n}	0
12623206	12604303	C# Datagridview make mandatory cell on new row	private void dgvUsers_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)\n        {\n            if (e.ColumnIndex != 0)\n            {\n                if ((e.RowIndex == dgvUsers.NewRowIndex) && (dgvUsers[0, e.RowIndex].Value == null))\n                {\n                    e.Cancel = true;\n                }\n            }\n        }	0
9110973	9110792	Render a control in a RowDataBound context to insert directly into cell	...\nforeach (string ship in shipIds)\n        {\n            shipsUL.Items.Add(ship.Trim());\n        }\n\ne.Row.Cells[4].Controls.Add(shipsUL);\n...	0
11485205	11484847	How to remove transform attribute of svg document?	transform="translate(350,250)"	0
13717781	13717355	Non-static method requires a target	public ActionResult MNPurchase() {\n    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];\n\n    if (calculationViewModel != null) {\n        decimal OP = landTitleUnitOfWork.Sales.Find()\n                                        .Where(x => x.Min >= calculationViewModel.SalesPrice)\n                                        .FirstOrDefault()\n                                        .OP;\n\n        decimal MP = landTitleUnitOfWork.Sales.Find()\n                                        .Where(x => x.Min >= calculationViewModel.MortgageAmount)\n                                        .FirstOrDefault()\n                                        .MP;\n\n        calculationViewModel.LoanAmount = (OP + 100) - MP;\n        calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);\n\n\n        return View(calculationViewModel);\n    } else {\n        // Do something else...\n    }\n}	0
204508	204468	Invoking a method using reflection on a singleton object	string methodName = "DoSomething"; // e.g. read from XML\nMethodInfo method = typeof(Singleton).GetMethod(methodName);\nFieldInfo field = typeof(Singleton).GetField("instance",\n    BindingFlags.Static | BindingFlags.Public);\nobject instance = field.GetValue(null);\nmethod.Invoke(instance, Type.EmptyTypes);	0
17170170	17169987	Correct way to convert Xml to Objects?	XDocument xdoc = XDocument.Load("myXml.xml");\n\nList<Item> items = (from item in xdoc.Descendants("item")\n                    select new Item {\n                    Name = item.Element("name").Value,\n                    Price = item.Element("price").Value\n                    }).ToList();	0
13866528	13866423	Turn off windows box C#	Shell32.Shell shell = new Shell32.Shell();\n shell.ShutdownWindows();	0
4459679	4459571	How to recognize if a string contains unicode chars?	public void test()\n    {\n        const string WithUnicodeCharacter = "a hebrew character:\uFB2F";\n        const string WithoutUnicodeCharacter = "an ANSI character:??";\n\n        bool hasUnicode;\n\n        //true\n        hasUnicode = ContainsUnicodeCharacter(WithUnicodeCharacter);\n        Console.WriteLine(hasUnicode);\n\n        //false\n        hasUnicode = ContainsUnicodeCharacter(WithoutUnicodeCharacter);\n        Console.WriteLine(hasUnicode);\n    }\n\n    public bool ContainsUnicodeCharacter(string input)\n    {\n        const int MaxAnsiCode = 255;\n\n        return input.Any(c => c > MaxAnsiCode);\n    }	0
15869352	15869324	main arguments change my default location	Path.Combine(Path.GetDirectory(typeof(Program).Assembly.Location), "test.txt")	0
10887342	10887290	Find the position of a List Item in a List based upon specifice criteria using LINQ	public static IEnumerable<int> GetIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate)\n{\n    return items.Select( (item, index) => new { Item = item, Index = index })\n                     .Where(p => predicate(p.Item))\n                     .Select(p => p.Index);\n}	0
12220665	11836032	Setting Image source programatically in Metro app, Image doesn't appear	myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");\n\npublic static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)\n{\n    var uri = new Uri(parent.BaseUri, path);\n    BitmapImage result = new BitmapImage();\n    result.UriSource = uri;\n    return result;\n}	0
11081415	11081256	Serializing only some properties of parent and children to JSON	data.Select(x => new\n    {\n        x.Id,\n        x.Name,\n        Children = x.Children.Select(y => new\n            {\n                y.Id,\n                y.Name\n            })\n    });	0
32813366	32813123	Add to database dynamically using dbcontext	public void insert(object data)\n{\n    var db = new TestDbEntities();\n    db.Set(data.GetType()).Add(data);\n}	0
24958854	24958033	Ignoring parent node in XML using XMLReader in C#	XElement root = XElement.Load("file.xml");\nIEnumerable<XElement> productsWithoutNothing = from product in root.Elements("product")\n                                               where (string)product.Element("description") != "Nothing"\n                                               select product;	0
8101289	8101199	how to split string using regex	string str = "aaa\n   \nbbb\n   \nccc\n   \n   \nddd";\nstring[] result = Regex.Split(str, "\n\\s*");	0
4597504	4597472	Check IEnumerable<T> for duplicate values	public static bool ContainsDuplicates<T>(this IEnumerable<T> source, Func<T, T1> selector)\n{\n    var d = new HashSet<T1>();\n    foreach(var t in source)\n    {\n        if(!d.Add(selector(t)))\n        {\n            return true;\n        }\n    }\n    return false;\n}	0
31875238	31874502	Get 100 shades of blue color in Textbox	for (int i = 0; i < 100; i++)\n{\n  byte r = 0;\n  byte g = 0;\n  byte b = (byte)(255 - i);\n\n  var color = System.Windows.Media.Color.FromRgb(r, g, b);\n  var brush = new System.Windows.Media.SolidColorBrush(color);\n  // Use brush here...\n}	0
12517720	12513791	How to forbid TreeView.ExpandAll method scrolling automatically to the end of tree?	treeView1.BeginUpdate();\nfor (int i = 0; i < 4; ++i) {\n  TreeNode tn = new TreeNode("Node #" + i.ToString());\n  tn.Expand();\n  for (int j = 0; j < 250; ++j) {\n    tn.Nodes.Add("Child #" + j.ToString());\n  }\n treeView1.Nodes.Add(tn);\n}\ntreeView1.EndUpdate();	0
13604280	13531192	DataModel validation in c#	public Boolean IsModelValid()\n    {\n        Boolean isValid = true;\n        PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n        foreach (PropertyInfo p in properties)\n        {\n            if (!p.CanWrite || !p.CanRead)\n            {\n                continue;\n            }\n            if (this[p.Name] != null)\n            {\n                isValid = false;\n            }\n        }\n        return isValid;\n    }	0
2609175	2609084	How can I subsample data from a time series with LINQ to SQL?	int nth = 100;\nvar points = db.DataPoints\n           .Where(p => p.ExperimentId == myExperimentId)\n           .OrderBy(p => p.Time)\n           .Where( (p, index) => index % nth == 0 )\n           .Select( p => new { X = p.Time, Y = p.Value } );	0
16088858	16088799	How do I call a derived class method from the base class?	public class WireLessDevice\n{ // base class\n    protected virtual void ParseMessage()\n    {\n        // Do common stuff in here\n    }\n}\n\npublic class WiFi : WireLessDevice\n{ // derived class\n    override void ParseMessage()\n    {\n        base.ParseMessage();//Call this if you need some operations from base impl.\n        DoGPSStuff();\n    }\n    private void DoGPSStuff()\n    {\n        //some gps stuff\n    }\n    GPSLoc Loc;\n}	0
14780923	14779976	NHibernate -- Rolling back a transaction and closing session causes a GenericADOException to be thrown	ITransaction.Commit()	0
25937328	25937178	twice attaching same entity	var someEntity =\n                context.Set<SomeEntity>.FirstOrDefault(\n                    x => x.EntityId == 2) ?? new ProcedureBillingOptionRecord();\n\ncontext.Entry(someEntity).State = someEntity.EntityId == 0 ? \n                                   EntityState.Added : \n                                   EntityState.Modified; \nsomeEntity.Foo="foo";\nsomeEntity.Bar="Bar";\n//...\ncontext.SaveChanges();	0
34557152	34545619	How to insert in a multiple many-to-many table the best way?	string sql="";\n        case "St_I_accessoryId":\n            sql =  string.Format(@"\n            IF EXISTS(SELECT 1 FROM ClothStore.dbo.StoringRooms_Items WHERE St_I_serviceid = {0}\n            BEGIN\n              UPDATE ClothStore.dbo.StoringRooms_Items \n              SET ser_I_accessoryId= {1}\n              WHERE St_I_serviceid = {0}\n            END\n            ELSE\n            BEGIN\n              INSERT INTO ClothStore.dbo.StoringRooms_Items VALUES ('{0}', '{1}',null,null,null)\n            END    \n            ",serviceId,Id)\n            cmd = new SqlCommand(sql, db);\n            break;	0
16883650	16883337	Isometric, draw only on screen tiles	tileX = sTileX + col + (int)((row / 2) + (row%2));	0
28177337	28177269	Trying to add a string value to a SQL database - help and advice	SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES('" + txtProductName.Text + "');", sqlConnect);	0
9263552	9263479	Readable unit testing of a yielded sequence?	var expectedFibSequence = new[] {0,1,1,2,3,5};\nCollectionAssert.AreEqual(\n    expected,\n    MyClass.Fibonacci().Take(expected.Length).ToList());	0
7119979	7119868	How to write decryption code in c#	public string Base64Decode(string data)\n{\n    byte[] byteArray = Convert.FromBase64String(data);\n    var message = System.Text.Encoding.UTF8.GetString(byteArray);\n    return message;\n}	0
10523497	10523481	C#, How to tell if first element of array is null, when array could possibly have no elements?	if (myArray != null && myArray.Length > 0 && myArray[0] != null)\n{\n    //Do Something\n}	0
26646663	26646532	Query data in certain period of time, and group by each date and count total data for each date	var query = logs.Where(x => x.LogDate > new DateTime(2014, 09, 20) && x.LogDate < new DateTime(2014, 10, 12))\n                                .GroupBy(x => x.LogDate).Select(x => new { LogDate = x.Key, Count = x.Count() });	0
12075197	12074631	deserialize json c# get value of variable	JObject a = JObject.Parse(answer);\n\nvar val = a["response"][0];	0
7334140	7334067	How to get Properties and their value from a static class in referenced assembly	class Program\n    {\n        static void Main(string[] args)\n        {\n            Type t = typeof(A7);\n            FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);\n\n            foreach (FieldInfo fi in fields)\n            {\n                Console.WriteLine(fi.Name);\n                Console.WriteLine(fi.GetValue(null).ToString());\n            }\n\n            Console.Read();\n        }\n    }	0
9514467	9512936	How to get GridView's LinkButton ForeColor in RowCommand Event?	GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;\n\n        LinkButton lstText = (LinkButton)row.FindControl("lnkReturn");\n\n        string text = lstText.ForeColor.ToString();	0
631575	631371	Can I use <asp:dataGrid> pager with database paging performance?	mygrid.VirtualItemCount = pageCount; \nmygrid.DataSource = mysource; \nmygrid.DataBind();	0
15708268	15706509	How would you emit the default value of a type?	clearMethodILGen.Emit(OpCodes.Ldfld, localField);\nclearMethodILGen.Emit(OpCodes.Initobj, localField.FieldType);	0
2967074	2967047	C# ProgressBar design pattern	interface IProgressBar\n{\n     int MinValue { get; set; }\n     int MaxValue { get; set; }\n     int Value { get; set; }\n}	0
29851904	29850924	Get all property expressions from a type lambda expressions	foreach (var p in stage.GetType().GetProperties())\n        {\n\n        }	0
27914182	27914168	How do I get a number with two digits after the decimal using double type numbers in C#?	TxtResult.Text = (Math.Round(_quotient, 2)).ToString();	0
8417695	8417649	Storing ref in c#	TabControl m_TabRef;\n\npublic FindAndReplace(TabControl launguageTabs)\n{\n    m_TabRef = languageTab;\n\n    // from now m_TabRef references the object instance\n    // passed as launguageTabs reference\n}	0
28239262	28238772	Find First File in a Branching Directory	var inputDir = @"c:\\temp";\n\n        var files = Directory\n            .EnumerateFiles(inputDir, "*.dcm", SearchOption.AllDirectories)\n            .Select(f => new FileInfo(f))\n            .GroupBy(f => f.Directory.FullName, d => d, (d, f) => new { Directory = d, FirstFile = f.ToList().First() })\n            .ToList();\n\n        files.ForEach(f => Console.WriteLine("{0} {1}", f.Directory, f.FirstFile));	0
16091888	16090704	How to parse Twitter Trends Json response	dynamic dynObj = JsonConvert.DeserializeObject(jsonString);\n\nforeach (var trend in dynObj[0].trends)\n{\n    Console.WriteLine(trend.name);\n}	0
7779262	7779238	How to execute/open whatever file in .NET	Process proc = new Process();\nproc.StartInfo.FileName = "file.doc";\nproc.StartInfo.UseShellExecute = true;\nproc.Start();	0
6996950	6996916	is it possible to pass to a function a generic IEnumerable?	private void Pager<T>(IEnumerable<T> tEnum)\n{\n   // here T can be anything\n}\n\n// you can call it like:\nPager(new int[]{10,20});\nPager(new string[]{"meep","x"});	0
14345372	14344442	Getting Cell Values from Excel API C#	#using Microsoft.Office.Interop;\n\nExcel.Application xlApp;\nExcel.Workbook xlWorkBook;\nExcel.Worksheet xlWorkSheet;\n\nxlApp = new Excel.ApplicationClass();\nxlWorkBook = xlApp.Workbooks.Add(1);\nxlWorkSheet = Excel.Worksheet xlWorkBook.ActiveSheet;\n\n// Notice the index starting at [1,1] (row,column)\nfor (int i=1; i<DataGridView.Columns.Count+1; i++)\n    xlWorkSheet.Cells[1, i] = DataGridView.Columns[i - 1].HeaderText;\n\nfor each(DataGridViewRow row in DataGridView.Rows)\n{\n    for each (DataGridViewColumn column in DataGridView.Columns)\n    {\n        xlWorkSheet.Cells[row.Index+2,column.Index+1] = DataGridView.Rows[row.Index].Cells[column.Index].Value;\n    }\n}	0
15235730	15235661	Using Linq to do a Contains with multiple values	var meds = (from m in Medications \n            where names.Any(name => name.Equals(m.BrandName) || m.GenericName.Contains(name)) \n            select m);	0
10081965	10081939	Changing StreamReader file extension in c#	TextReader textReader\n    = new StreamReader(String.Format(@"C:\ITRS_equipment_log\{0}.txt", textBox1.Text));	0
22459677	22459554	Using MVC3 Webgrid, how do I preserve the grid in the session so I can return to the page I was on before?	public int PageNumber { get; set; }	0
621506	621493	C# unsafe value type array to byte array conversions	public static byte[] ToByteArray(this float[] floatArray) {\nint len = floatArray.Length * 4;\nbyte[] byteArray = new byte[len];\nint pos = 0;\nforeach (float f in floatArray) {\nbyte[] data = BitConverter.GetBytes(f);\nArray.Copy(data, 0, byteArray, pos, 4);\npos += 4;\n}\nreturn byteArray;\n}	0
28490588	28489895	String manipulation can't keep up with sockets	using System.Text.RegularExpressions;\n\nprivate Regex regex = new Regex("[QWXYZ]");\n\nprivate void OnAddMessage(string message)\n{\n    using (StringReader sr = new StringReader(message))\n    {\n        string line;\n\n        while ((line = sr.ReadLine()) != null)\n        {\n            string[] splitContents = regex.Split(line);\n\n            //do something with the parsed contents ...\n        }\n    }\n}	0
26300189	26298340	Searching in datagridview using c#	private void btnCrudSearch_Click(object sender, EventArgs e)\n    {\n\n        dgvLoadTable.CurrentCell = null;\n        dgvLoadTable.AllowUserToAddRows = false;\n        dgvLoadTable.ClearSelection();\n        dgvLoadTable.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\n        dgvLoadTable.ReadOnly = true;\n\n        try\n        {\n            foreach (DataGridViewRow row in dgvLoadTable.Rows)\n            {\n                var cellValue = row.Cells[cboCrudSearchColumn.SelectedIndex].Value;\n                if (cellValue != null && cellValue.ToString() == txtCrudSearch.Text.ToUpper())\n                {\n                    row.Selected = true;\n                    row.Visible = true;\n                }\n                else\n                    row.Visible = false;\n\n            }\n        }\n        catch (Exception exc)\n        {\n            MessageBox.Show(exc.Message);\n        }\n\n    }	0
23990524	23990419	Is it possible to override a base method with a more specific (by return type) method?	public class Base\n{\n    public Base Clone() { return CloneImpl(); }\n    protected virtual Base CloneImpl() { ... }\n}\n\npublic class Derived : Base\n{\n    public new Derived Clone() { ... }\n    protected override Base CloneImpl() { return Clone(); }\n}	0
7151141	7131206	Getting Image from stream in Windows Mobile in C#	using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n        {\n            IPAddress IP = IPAddress.Parse("192.168.1.2");\n            IPEndPoint IPE = new IPEndPoint(IP, 4321);\n            s.Connect(IPE);\n            byte[] buffer = new byte[55296];\n            int rec = s.Receive(buffer, SocketFlags.None);\n            using (MemoryStream ms = new MemoryStream(buffer, 0, rec))\n            {\n                Image im = new Bitmap(ms);\n                pictureBox1.Image = im;\n            }\n        }	0
25430571	25430415	Datagridview Dynamic Buttons text disappearing after header sort	MoreInfoCol.UseColumnTextForButtonValue = true; \nMoreInfoCol.Text = "My Value Goes here";	0
2701080	2701008	What's the most efficient way to pull culture information out of a resx's filename in c#?	string GetCulture(string s)\n{\n  var arr=s.Split(".");\n  if(arr.Length>2)\n    return arr[1];\n  else\n    return "Default";\n}	0
32824057	32823391	setting the encoding of a System.Net.Mail.MailMessage body while getting text from xml using c#	XmlSerializer xSerializer = new XmlSerializer(typeof(App));\n\nusing (StreamReader srXml = new StreamReader(_sFileName, Encoding.GetEncoding("iso-8859-1")) )\n{\n    _oAppConfig = (App)xSerializer.Deserialize(srXml);\n}	0
18351135	18350959	Rename property names from WCF service generated model	How about adapter pattern?	0
18613705	18601547	How to retrieve physical path for virtual directory	System.Web.Hosting.HostingEnvironment.MapPath(virtualDirectoryPath)	0
4971106	4970899	LINQ to SQL query where a string StartsWith an element from a generic list	string prodSKU = TextSKU.Text.Trim(); \nList<string> skuList = prodSKU.Split(new char[] { ', ' }).ToList();  \n\nvar results = from c in db.Products                 \n   where c.is_disabled ==false                  \n   && c.dom >= startDate                  \n   && c.dom <= endDate                  \n   &&  skuList.Any(sl=>c.sku.StartsWith(sl))                 \n      select c;	0
877821	877811	C# string insertions confused with optional parameters	myClass = new MyClass(string.Format("abc{0}ghi", toInsert));	0
32515188	32515133	Error join table with lambda expression c#	class NewVehicleFuelReportViewModel\n{\n   public int Index { get; set; }\n   public MaintenanceDate { get; set; }\n}\n\nvar data = maintenance.Join(mDetail,\n   m => m.Id,\n   md => md.MaintenanceId,\n   ( m, md) => new VehicleFuelReportViewModel { \n      MaintenanceDate = m.MaintenanceDate \n   });\n   int i = 0;\n   var dataWithIndex = data.select(d=>{\n   var tempdata = new NewVehicleFuelReportViewModel();\n   tempdata.Indx = i++;\n   tempdata.MaintenanceDate = d.MaintenanceDate;\n   return tempdata;\n}).ToList();	0
15518896	15504337	C# - Excel 2013 how to change chart style	workChart.ChartStyle = 209;	0
8777003	8776923	username and password always wrong, even if they are true in the database	using(SqlConnection con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True"))\n{\n    string query = "SELECT TOP 1 Username FROM Users WHERE Username=@UserName AND Password=@Password";\n\n    using (SqlCommand command = new SqlCommand(query, con))\n    {\n        command.Parameters.AddWithValue("@UserName", UserName);\n        command.Parameters.AddWithValue("@Password", Password);\n        con.Open();\n        string username = (string)command.ExecuteScalar(); //Add Null Check\n        // Do stuff if username exists         \n    }\n}	0
6091822	6091803	C# Select all items in ListBox - pause event handling	listBox.SelectIndexChanged -= listBox_selectIndexChanged;\n\nfor (int i = 0; i < listBox.Items.Count; i++)\n  listBox.SetSelected(i, true);\n\nlistBox.SelectIndexChanged += listBox_selectIndexChanged;	0
27867731	27867029	Binding DataGrid columns to a SQL database doesnt work	StringFormat=\{0:d\}}"	0
6201377	6201306	How to convert List<string> to List<int>?	listofIDs.Select(int.Parse).ToList()	0
5723479	5722499	How to disable subclassing for a specific abstract base class using Fluent NHibernate auto mapping	public class EntityMap : ClassMap<Entity>\n{\n    public EntityMap()\n    {\n        Id(n => n.Id);\n    }\n}	0
8211042	8211002	How to encode an object to a long string in C#?	Convert.ToBase64String	0
14783185	14783120	Clean memory after using a large list of data in WCF Service	var q = from EventLogEntry e in eventLog.Entries\n        where (e.InstanceId == m_EventNumber) && e.TimeGenerated >= fromDate orderby e.TimeGenerated\n        order by e.TimeGenerated desc\n        let r = ParseMessage(e.Message)\n        where r != null\n        select r;\n\nreturn new List<Data>(q);	0
10283443	10279652	Fetching parent object from child object in fluent nhibernate	var childId = "..."; \n\nChild childAlias = null;\nsession.QueryOver<Parent>\n  .JoinAlias(parent => parent.Children, () => childAlias)\n  .Where(() => childAlias.Id == childId)\n  .TransformUsing(Transformers.DistinctRootEntity)\n  .SingleOrDefault();	0
2112692	2112674	Get Alphabetical List Of Items in Collection Using Lambda/Linq?	list.Select(o => o.DisplayName[0].ToString())\n    .Where(s => Char.IsLetter(s, 0))\n    .Distinct().ToList();	0
11511186	11479228	How to data bind nested ListView ItemTemplates in Metro/WinRT?	{Binding RelativeSource={RelativeSource TemplatedParent},\n                         Path=DataContext.InnerCollection}	0
6876432	6876391	How can I optimize this method?	int count = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;	0
33679999	33667308	Convert IHtmlContent/TagBuilder to string in C#	public static string GetString(IHtmlContent content)\n{\n    var writer = new System.IO.StringWriter();\n    content.WriteTo(writer, new HtmlEncoder());\n    return writer.ToString();\n}	0
8906978	8906619	How to resize Windows Icon Overlay?	*pdwFlags = ISIOI_ICONFILE;	0
24561600	24561567	Datetime Format Convert C#	var dt = DateTime.Parse(Dr["DATE"].ToString());\n\nltrlNotlar.Text = dt.ToString("dd.MM.yyyy");	0
22970439	22970234	How to replace in a array of list of string just what changed	File.WriteAllText(@"C:\Users\Marius\Desktop\GameMachineWF\GameMachineWF\Player.csv", String.Empty);\n            foreach (Player p in players)\n            {\n                p.Write();\n            }	0
14520396	14520294	Moq - Verify the last call to a method	[Test]\npublic void AfterOperationCursorIsArrow()\n{\n    string lastMethod = null;\n    Cursor lastCursor = null;\n\n    var mock = new Mock<IMouseTraits>();\n\n    mock.Setup(m => m.ForceCursor(It.IsAny<Cursor>()))\n        .Callback((Cursor c) => lastMethod = "ForceCursor");\n\n    mock.Setup(m => m.SetCursor(It.IsAny<Cursor>()))\n        .Callback((Cursor c) => { \n            lastMethod = "SetCursor";\n            lastCursor = c; \n        });\n\n    var w = new WindowOperation(mock.Object);\n    w.Execute();\n\n     Assert.That(lastMethod, Is.EqualTo("SetCursor"));\n     Assert.That(lastCursor, Is.EqualTo(Cursors.Arrow));\n}	0
11309265	11309212	Is it possible to force an interface implementation to be virtual in C#?	abstract class VirtualBuilder<T> : IBuilder<T>\n{\n  abstract T Build();\n}	0
33780419	33777618	C# Access registry of another user	WindowsIdentity.GetCurrent().User.ToString();	0
19456813	19456161	Serialize ObservableCollection which defined opening element	var codes = new Codes { CodeCollection = codeCollection };\n    XmlSerializer _serializer = new XmlSerializer(typeof(Codes));\n    using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))\n    {\n        _serializer.Serialize(_writer, codes);\n    }	0
21042424	21042314	c sharp mysql underscore, space table name error	"SELECT * From `" + ID + "_" + objectName + "` ORDER BY date DESC LIMIT 1"	0
22696621	22696448	Accessing Data in a String List Array	List<string> qustions = new List<string>();\nforeach(var id in questionId)\n{\n           Query = "SELECT *  FROM QuestionsTable WHERE Id = '" + id + "'";\n           theReader = conn.ExecuteStatement(Query);\n           while(theReader.Read())\n           {\n              question = theReader["Question"].ToString();\n              qustions.add(question);\n           }\n\n}	0
25958179	25957668	how a dataset is disconnected?	StorageEnum store = Storage.Oracle;\nstring stUpdate=  "update customer set name = 'Faizan' where ID = 5";\nDbDataAdapter da = null;\nswith (store)\n{\n    case StorageEnum.SqlServer:\n       da= new SQLDataAdapter(stUpdate, SQLCONNECTIONOBJECT)\n    break;\n    case StorageEnum.Oracle:\n       da= new OracleDataAdapter(stUpdate, ORACLECONNECTIONOBJECT)\n    break;\n    default:\n       da= new OleDBDataAdapter(stUpdate, OLEDBCONNECTIONOBJECT)\n    break;\n};\nDataSet ds = new Dataset();\nda.Fill(ds, "tablename")	0
32213548	32211577	How to display bytes received per second in C#	// If the category does not exist, create the category and exit.\n// Performance counters should not be created and immediately used.\n// There is a latency time to enable the counters, they should be created\n// prior to executing the application that uses the counters.\n// Execute this sample a second time to use the category.	0
13310259	13310212	Dump properties of HttpRequest	SaveAs()	0
1866950	1866903	Shorten a line by a number of pixels	double dx = x2 - x1;\ndouble dy = y2 - y1;\ndouble length = Math.Sqrt(dx * dx + dy * dy);\nif (length > 0)\n{\n    dx /= length;\n    dy /= length;\n}\ndx *= length - radius;\ndy *= length - radius;\nint x3 = (int)(x1 + dx);\nint y3 = (int)(y1 + dy);	0
16362158	16362067	Hiding a dropdown in C#	if (checkbox1.CheckState == CheckState.Checked)\n{\n this.combobox2.Visible = True;\n}\n\nelse (checkbox1.CheckState == CheckState.Unchecked)\n{\n this.combobox2.Visible = False;\n}	0
12210241	12210021	Is there a way to turn this small method into a lambda or linq statement?	return MethodBase.GetCurrentMethod().GetParameters().ToArray <object>();	0
24147276	24147257	How to insert lines in a paragraph in Interop Word using C#	r.Text = r.Text + line.name.ToString()+":"+line.value.ToString();	0
5856605	5856238	listBox selected item	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        switch(comboBox1.SelectedItem.ToString())\n        {\n            case "Fruit":\n                FruitSelected();\n                break;\n            case "Vegetables":\n                VegetableSelected();\n                break;\n            default:\n                NoneSelected();\n                break;\n        }\n    }\n    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        // Similar code as above\n    }\n    protected void FruitSelected()\n    {\n        comboBox2.Items.Clear();\n        comboBox2.Items.Add("Orange");\n        comboBox2.Items.Add("Apple");\n    }\n    protected void VegetableSelected()\n    {\n        comboBox2.Items.Clear();\n        comboBox2.Items.Add("Tomato");\n        comboBox2.Items.Add("Cucumber");\n    }\n    protected void NoneSelected()\n    {\n        comboBox2.Items.Clear();\n        comboBox3.Items.Clear();\n    }\n}	0
12531217	12530822	How do I check if a selected item has changed from the previously selected item?	public void clearText()\n    {\n        textBox1.Clear();\n        textBox2.Clear();\n        textBox3.Clear();\n        textBox4.Clear();\n        textBox5.Clear();\n        textBox6.Clear();\n        textBox7.Clear();\n        textBox8.Clear();\n        textBox9.Clear();\n        textBox10.Clear();\n        textBox11.Clear();\n        textBox12.Clear();\n    }	0
7485040	7484965	Get last 'N' quarters in C#	for (int i = generateQuater; i > 0; i--)\n{\n    lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater, currentYear));\n    if (--currentQuater == 0)\n    {\n        currentQuater = 4;\n        currentYear--;\n    }\n}	0
15680447	15679542	How to arrange datatable using C#	var result = (from dr1 in dt.Select()\n                  join dr2 in dt.Select() on dr1["Question"].ToString() equals dr2["Question"].ToString()\n                  select new { q = dr1["question"], u1 = dr1["User1"], u2 = dr2["User2"] }\n                 ).Where(row => row.u1.ToString().Length > 0 && row.u2.ToString().Length > 0).ToList();	0
17470127	17431572	Can't upload filename with special character to google drive REST	var request = new HttpRequestMessage(HttpMethod.Post, uri);\nstring strData = new JavaScriptSerializer().Serialize(jsonObject);\n\nvar content = new StringContent(strData, Encoding.UTF8, "application/json");\ncontent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");\nrequest.Content = content;	0
26783249	23798114	How to find a keyword over mulitiple files using VsVim	Tools -> Options -> VsVim -> Keyboard	0
4324883	4324759	Web: View raw content of a file from the FileName and the FileContent	public static string GetRegistryContentType(string fileName)\n    {\n        if (fileName == null)\n            throw new ArgumentNullException("fileName");\n\n        // determine extension\n        string extension = System.IO.Path.GetExtension(fileName);\n\n        string contentType = null;\n        using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension))\n        {\n            if (key != null)\n            {\n                object ct = key.GetValue("Content Type");\n                key.Close();\n                if (ct != null)\n                {\n                    contentType = ct as string;\n                }\n            }\n        }\n        if (contentType == null)\n        {\n            contentType = "application/octet-stream"; // default content type\n        }\n        return contentType;\n    }	0
16857156	16856582	C# update a boolean value in an Access database	using (var conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;"))\n{\n    conn.Open();\n    using (var cmd = new OleDbCommand(\n            "UPDATE Ontwikkeldossier SET [In mail]=? WHERE OntwikkeldossierID=?",\n            conn))\n    {\n        cmd.Parameters.AddWithValue("?", false);\n        cmd.Parameters.AddWithValue("?", 1);\n        cmd.ExecuteNonQuery();\n    }\n    conn.Close();\n}	0
30765773	30765313	InvalidArgument=Value of '1' is not valid for 'index'	if (Date1 >= 0 && Date2 <= 0)\n{\n    listView1.Items.Add(dataReader.GetValue(0).ToString());\n    listView1.Items[i].SubItems.Add(dataReader.GetValue(1).ToString());// The error appears on this line\n\n    listView1.Items[i].SubItems.Add(dt0.ToShortDateString());\n    listView1.Items[i].SubItems.Add(dataReader.IsDBNull(3) ? "0" : dataReader.GetString(3));\n    listView1.Items[i].SubItems.Add(dataReader.IsDBNull(4) ? "0" : dataReader.GetDouble(4).ToString("n2"));\n    listView1.Items[i].SubItems.Add(dataReader.IsDBNull(5) ? "-" : dataReader.GetString(5));\n    i++;\n}	0
21070521	21070468	How to get datagrid to ignore unwanted columns	datagrid.AutoGenerateColumns = false	0
27871055	27870933	parsing xml string and getting the value out	var validXml = "<root>" + value + "</root>";\nvar doc = XDocument.Parse(validXml);\n\nvar ns = XNamespace.Get("ns:iqn:cwm:1.0");\nConsole.WriteLine(doc.Root.Element(ns.GetName("CDFValue")).Value);	0
7764142	7738787	Using ouput parameter of type SYS_refcursor	cmd.Parameters["REC_CUR"].value	0
6578050	6577988	How To Put Data At Run Time In a Table i.e Table Also Create At The Run Time?	DataTable dt = new DataTable();\n        Table mytable = new Table();\n        this.Controls.Add(mytable);\n        mytable.DataBind(dt);	0
7003233	6984407	How to get a stack trace when exception handling in Windows Workflow 3.5?	private void onGeneralFault(object sender, EventArgs e)\n{\n    CodeActivity thisActivity = (CodeActivity)sender;\n    Exception exception = ((FaultHandlerActivity)thisActivity.Parent).Fault;\n...	0
4714150	4713341	Get elements to add up in C#	private int SumOfCSV(string filePath)\n{\n        string csvContent = String.Empty;\n        int returnValue = 0;\n\n        try\n        {\n            StreamReader reader = new StreamReader(filePath);\n            csvContent = reader.ReadToEnd();\n            reader.Close();\n\n            foreach(string value in csvContent.Split(';'))\n            {\n                returnValue += Convert.ToInt32(value);\n\n            }               \n\n        }\n        catch (Exception)\n        {\n            Console.WriteLine("Reading " + Path.GetFileName(filePath) + " Failed.");\n        }\n\n        return returnValue;\n}	0
4963469	4963416	Get Tag property from ToolStripMenuItem and Button in click event handler	internal static object GetTag(object sender)\n{\n  Button button = sender as Button;\n  ToolStripItem tsi = sender as ToolStripItem;\n\n  if (button != null)\n    return button.Tag;\n  if (tsi != null)\n    return tsi.Tag;\n\n  throw new ArgumentException("Unexpected sender");\n}	0
16321039	16320976	Removing All Nulls From Collections	collection.Where(i => i != null).ToList();	0
12568152	12568041	ASP.NET form with repeaters that dynamically generate input controls	if(!Page.IsPostback)	0
29976874	29976645	Using Unity DI container in WPF application	protected override void OnStartup(StartupEventArgs e)\n    {\n        IUnityContainer container = new UnityContainer();\n        container.RegisterType<IMailSender, Model.Concrete.GmailSender>();\n        var mainWindow = container.Resolve<MainWindow>();            \n        Application.Current.MainWindow = mainWindow;\n        Application.Current.MainWindow.Show();\n    }	0
2023246	2023218	Replacing a regular method with an anonymous method in C#/LINQ	return\n(\n    from \n        f in foos \n    join\n        b in bars \n        on f.BarId equals b.Id \n    select \n        new {f, b}\n).select(foobar => {foobar.f.BarId = foobar.b.Id; return foobar.f});	0
4397552	4389261	Rotate text / Vertical text in itextsharp	Imports System.Drawing, System.Drawing.Drawing2D\nDim transf as new Matrix\ntransf.RotateAt(30,New PointF(100,100), MatrixOrder.Append)\nwriter.DirectContent.Transform(transf)\n\ntransf.Invert()\nwriter.DirectContent.Transform(transf)	0
8033748	8033660	Stopping an thread application in C# Windows Application?	while (true) {...}	0
5593809	5593748	Comparing two Lists	c = A.Except(B).Union(B.Except(A)).ToList();	0
11017917	11001877	How to explicitly fail a test case with Coded-UI	Assert.IsTrue(FileExistsStatus)	0
25787806	25783530	Allow page extraction in a password security pdf with itextsharp	bit 1:  Not assigned\nbit 2:  Not assigned\nbit 3:  Degraded printing: ALLOW_DEGRADED_PRINTING\nbit 4:  Modify contents: ALLOW_MODIFY_CONTENTS\nbit 5:  Extract text / graphics: ALLOW_COPY\nbit 6:  Add / Modify text annotations: ALLOW_MODIFY_ANNOTATIONS\nbit 7:  Not assigned\nbit 8:  Not assigned\nbit 9:  Fill in fields: ALLOW_FILL_IN\nbit 10: **Deprecated** ALLOW_SCREEN_READERS\nbit 11: Assembly: ALLOW_ASSEMBLY\nbit 12: Printing: ALLOW_PRINTING	0
2007969	2007038	LINQ-NHibernate - Selecting only a few fields (including a Collection) for a complex object	using( var session = sessionFactory.OpenSession() )\n        {\n            session.BeginTransaction();\n\n            var foos =\n                session.CreateCriteria(typeof(Foo))\n                       .List<Foo>();\n\n            var miniFoos = \n               foos.Select(f => new { f.email, f.bars })\n                   .Where(f => f.email.Equals("foo@bar.com)\n                   .ToList();\n\n            session.Close();\n         }	0
19044400	19044298	Resize columns of a ASP.NET Gridview beyond its data length	min-width:0;	0
15267874	15267512	Use a other Method in a static method	if(this.InvokeRequired) {\n   BeginInvoke(\n       new MethodInvoker(delegate { label.Text+="."; }));\n} else {\n    label.Text+="."; \n}	0
626020	619028	Enable/Disable BindingNavigatorItems based on selected row	var member = teamRoleBindingSource.Current as TeamRole;\n\nif (member != null && member.RoleCode == "KEY_ACCOUNT_MANAGER")\n{\n    bindingNavigatorDeleteItem.Enabled = false;\n    bindingNavigatorChangeItem.Enabled = false;\n}	0
5882579	5882536	How to use ScrollIntoView in DataGrid?	dataGrid.Items[ dataGrid.Items.Count-1 ]	0
4560030	1245923	Linq2Sql: How to handle tables with the same name and different schema names	[global::System.Data.Linq.Mapping.TableAttribute(Name="a.target")]\npublic partial class target\n{ //... class implementation snipped\n}\n\n[global::System.Data.Linq.Mapping.TableAttribute(Name="b.target")]\npublic partial class target1\n{ // ... class implementation snipped\n}	0
5962825	5962770	Look for words in strings with LINQ	words.Split(' ').Any(someText.Contains)	0
23066953	23066467	Writing a windows forms application in c#, which is actually a server, I want to display messages such as "Server Listening", "Connected" etc,	textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Waiting for a connection... "; });	0
19925030	19924760	XML get value of tag without childrens value	var textValues = element.Nodes()\n                        .Where(n => n.NodeType == XmlNodeType.Text)\n                        .Select(n => n.ToString().Trim());\n\nstring value = string.Join("", textValues); // value is:   This is a test value	0
4806647	4806512	Working with dialog boxes in C#	private bool _isClicked = false;\n\npublic void Button1_OnClick(object sender, EventArgs e)\n{\n   if(!_isClicked)\n   {\n        // do show the message box here \n        _isClicked = true;\n        return;\n   }\n\n   //generate the report here   \n   _isClicked = false;   \n}	0
14977922	14977697	how to read data from one column of datagridview	string data = (string)DataGridView1[iCol, iRow].Value;	0
6677421	6677349	No Application Quit event in Outlook?	Process.Exited	0
430709	430403	Display ? on a C# .NET application	static void DumpString (string value)\n{\n    foreach (char c in value)\n    {\n        Console.Write ("{0:x4} ", (int)c);\n    }\n    Console.WriteLine();\n}	0
22693109	22692586	How to make a Stopwatch without rewrite line for each display	Stopwatch chrono = new Stopwatch();\nchrono.Start();\nbool isMyComputerOn = true;\nwhile (isMyComputerOn)\n{\n   Console.SetCursorPosition(1,1);\n   Console.WriteLine("Time : "+chrono.Elapsed);\n}	0
24475314	24475280	Reuse created controls	new Label(???)	0
3448304	3448267	PInvokeStackImbalance - invoking unmanaged code from HookCallback	public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, IntPtr dwExtraInfo);	0
2609847	2603148	Map a column to be IDENTITY in db	var connection = GetUnOpenedSqlConnection();       // Any connection that inherits\n                                                   // from DbConnection is fine.\n\nvar builder = new ContextBuilder<ObjectContext>(); // I actually had my own class\n                                                   // that inherits from \n                                                   // ObjectContext, but that was \n                                                   // not the issue (I checked).\n\nbuilder.Configurations.Add(EntryConfiguration);    // EntryConfiguration is the \n                                                   // class in the question\n\nvar context = builder.Create(connection);\n\nif (context.DatabaseExists())\n{ context.DeleteDatabase(); }\n\ncontext.CreateDatabase();	0
16766870	16766731	How to get title, description from html agility?	var title= (from item in doc.DocumentNode.SelectNodes(\n "//div[@class='section sectionMain recentNews']//a[@class='newsTitle']")\n select item).ToList();\n\nvar des= (from item in doc.DocumentNode.SelectNodes(\n     "//div[@class='section sectionMain recentNews']//div[@class='newsText']") \n     select item).ToList();\n\nvar items = title.Zip(des, (t, d) => new {Title = t, Description = v })	0
12617665	12614163	How to get option set values from sql server in an application outside crm	select\n    *\nfrom\n    StringMap s \n    inner join EntityLogicalView e on\n        s.ObjectTypeCode = e.ObjectTypeCode\nwhere\n    e.Name = 'new_entityname'\n    and s.AttributeName = 'new_optionsetname'	0
9636444	9636258	Find stores within 10 miles of postcode?	DECLARE @home GEOGRAPHY\nSELECT @home = GeoLocation \nFROM dbo.PostCodeData \nWHERE OutwardCode = 'AB12' AND InwardCode = '3CD' -- Postcode entered by user\n\n-- find all stores within 10 miles of the entered postcode\nSELECT *\nFROM dbo.Stores\nWHERE GeoLocation.STDistance(@home) <= (10 * 1609) -- 1609 = approx metres in 1 mile	0
8213939	8213886	sum of an element of items using one linq command	int stock = ListOfGames.Where(x=>x.Id == GameID).Sum(x=>x.Instock);	0
4435838	4435350	How do I access innerText of a specific XMLnode	XmlDocument doc = new XmlDocument();\n        doc.Load(@"sample.xml");\n        XmlNodeList firstNameNodes =  doc.GetElementsByTagName("firstName");\n        foreach (XmlNode node in firstNameNodes)\n        {\n            string firstName =  node.InnerText;\n        }	0
23167332	21061224	How do I pass custom header through web browser for Windows Phone 8?	private bool firstload = true; \n//Define the headers\nstring AdditionalHeaders = "USER_MODEL:" + phoneModel + "USER_DEVICE_WIDTH:" + deviceWidth + "USER_NAME:" + USERNAME + "\r\User_Password=" + PASSWORD; \n\npublic void loadsite() \n{ \n  webBroswer.Navigate(new Uri("http://www.xhaus.com/headers"), null, AdditionalHeaders); \n  webBrowser.Navigating += webBrowser_Navigating; \n} \n\n//  This is done so that when navigating to any pages, the header will still be attached to the webbrowser.\nvoid webBroswer_Navigating(object sender, NavigatingEventArgs e) \n{ \n  if (firstload == true) \n    { \n      // This is to prevent it from looping the same page\n      firstload = false; \n    } \n  else \n  { \n    string url = e.Uri.ToString(); \n\n    webBroswer.Navigate(new Uri(url, Urikind.Absolute), null, AdditionalHeaders); \n    firstload= true;\n  }\n}	0
874654	874640	Edit Xml Node	XmlDocument doc = new XmlDocument();\ndoc.Load(@"Test.xml");\nXmlNodeList elem = doc.GetElementsByTagName("Data");\nforeach (XmlNode tag in elem)\n{\n //do whatever you want to the attribute using SetAttribute method\n}	0
11291121	11291050	Proper way to delete an image on a live server	FileInfo myfileinf = new FileInfo(deletePath);\nmyfileinf.Delete();	0
30023008	30022887	Combine two list data into single list C#	var sn = one.Zip(two, (x, y) => new One{\n  ID = x.ID,\n  Name = x.Name,\n  LastName = x.LastName,\n  MainName = y.MainName\n});	0
7894948	7881507	Finding the parameters with tokens (IndexOf or IndexOfAny)	var regex = new Regex("{:.+?}");\n        var input =\n            "This is a test to merge item {:/MyTest/TestTwo/Text1:} and {:/MyTest/TestTwo/Text2:} on the same line.";\n        var matches = regex.Matches(input);	0
29471100	29470970	Insert values in both related tables MySQL	LAST_INSERT_ID()	0
25411843	23520773	Button databinding in list doesn't behave correctly	public MainWindow()\n    {\n        InitializeComponent();\n        CompositionTarget.Rendering += OnRendering;\n    }\n\n    void OnRendering(object sender, EventArgs e)\n    {\n        Application.Current.Dispatcher.BeginInvoke(\n           DispatcherPriority.Background,\n           new Action(CommandManager.InvalidateRequerySuggested));\n    }	0
5010376	5010191	Using DataContractSerializer to serialize, but can't deserialize back	public static string Serialize(object obj) {\n        using(MemoryStream memoryStream = new MemoryStream())\n        using(StreamReader reader = new StreamReader(memoryStream)) {\n            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());\n            serializer.WriteObject(memoryStream, obj);\n            memoryStream.Position = 0;\n            return reader.ReadToEnd();\n        }\n    }\n\n    public static object Deserialize(string xml, Type toType) {\n        using(Stream stream = new MemoryStream()) {\n            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);\n            stream.Write(data, 0, data.Length);\n            stream.Position = 0;\n            DataContractSerializer deserializer = new DataContractSerializer(toType);\n            return deserializer.ReadObject(stream);\n        }\n    }	0
11085659	11085538	Model binding error with custom property getter	get \n{\n    return _drivers ?? new List<Claimant>();\n}	0
27521041	27520766	How to get a GridViewColumn by its header's name in WPF?	((GridView) _lvContacts.View).Columns.FirstOrDefault(x => (string) x.Header == "Name");	0
21748392	21748348	Adopt method parameters from constructor	public void Add(Animal animal)\n{\n    if(animal == null) throw new ArgumentNullException("animal");\n    Animals.Add(animal);\n}\n...\nzoo.Add(new Animal("Fred", 27));	0
10021633	10021188	In Nhibernate, can I further restrict what goes in a one to many using other criteria in the mapping besides the foreign key column?	Set<TableBObject>(x => x.TableBRecordsABCDOnly, map =>\n            {\n\n                map.Inverse(true);\n                map.Cascade(Cascade.All);\n                map.Key(k => k.Column(c => c.Name("TableAFKey")));\n                map.Where("TableBColumn1 = 'ABCD'");\n\n            },\n            action => action.OneToMany());	0
2937854	2937179	Communication between Multiple Threads in a WPF Application	public class MyWindow : UserControl{\nBindingList<MyObject> ObjectList = new BindingList<MyObject>;\n    public MyWindow(){\n        ObjectList.AllowAdd = true;\n        ObjectList.AllowDelete = true;\n        ObjectList.AllowEdit = true;\n    }\n    public void LoadObjects(){\n       ThreadPool.QueryUserItem( (s)=>{\n           // load your objects in list first in different thread\n           List<MyObject> list = MyLongMethodToLoadObjects();\n           Dispatcher.BeginInvoke( (Action)delegate(){\n               list.RaiseEvents = false;\n               foreach(MyObject obj in list){\n                   ObjectList.Add(obj);\n               }\n               list.RaiseEvents = true;\n               list.ResetBindings();\n           });\n       });\n    }\n}	0
5860730	5860714	Using Lambda expressions and the In Restrictor	return context.Clients.Where(c => extractIds.Contains(c.ExtractId)).ToList();	0
9990653	9990610	String present in Data Table or not in c#	using System.Linq;\n\nstring columnName = "SomeColumnName;"\nstring matchPattern = "matchPattern";\n\n// returns rows which contains pattern in specific columns\nvar result = tbl.AsEnumerable()\n                .Select(f => f.Field<string>(columnName))\n                .Where(c => c.Contains(matchPattern));\n\n\n// returns true if all rows contains pattern in specific column\nvar result = tbl.AsEnumerable()\n                .Select(f => f.Field<string>(columnName))\n                .All(c => c.Contains(matchPattern));	0
33230832	33230672	Find and Replace characters in a string based on two arrays in c#	string strValue = "MyString[]{"; \nchar[] findArray = {'[',']','{'};\nchar[] replaceArray = { '(', ')', '-' };\n\nFunc<char, int, char> GetC = (x, c) => c > -1 ? replaceArray.ElementAt(c) : x;\nstring Result = string.Concat(strValue.Select(x => GetC(x, Array.IndexOf(findArray, x))));	0
33581011	33580885	WMPLib Console app exception on media play	using System.Windows.Media;\n\npublic void PlaySoundAsync(string filename)\n{\n    // This plays the file asynchronously and returns immediately.\n    MediaPlayer mp = new MediaPlayer();\n    mp.MediaEnded += new EventHandler(Mp_MediaEnded);\n    mp.Open(new Uri(filename));\n    mp.Play();\n}\n\nprivate void Mp_MediaEnded(object sender, EventArgs e)\n{\n    // Close the player once it finished playing. You could also set a flag here or raise another event.\n    ((MediaPlayer)sender).Close();\n}	0
18737695	18737354	Issue while converting linq result to JSON in MVC4 using JavaScriptSerializer	Departments= jss.Serialize(\n              db.Departments.Select(d => new{\n                    DepartmentId = d.DepartmentId,\n                    DepartmentName = d.DepartmentName\n                })\n            );	0
18213685	16098210	How to set a property value to auto increment in visual studio lightswitch 2012	private void Customers_Inserted(Customer entity)\n{\n    if (entity.Customer_ID == null) {\n        entity.Customer_ID = entity.ID;\n    }\n}	0
23807130	23805765	Web Service to save the received string array list from android to a file	public void SaveDataToFile(string[] array)\n{\n    using (StreamWriter writer = new StreamWriter("C:\temp\file.txt", true))\n    {\n        writer.WriteLine(array.Join(",", array); //save it as a comma separated list\n    }\n}	0
8167774	8167689	How can I recreate the behavior of MSN Messenger with regards to opening new chat windows	Dictionary<Guid, Form> dic = new Dictionary<Guid, Form>();\n    public Form ShowForm(Guid userId)\n    {\n        Form form;\n        if (!dic.TryGetValue(userId, out form))\n        {\n            form = new Form();\n            dic.Add(userId, form);\n        }\n        return form;\n    }	0
26034958	26034620	binding property of two instances of same class, non wpf	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        var a = new MyClass ();\n\n        var b = new MyClass();\n        a.DependentObj = b;\n        a.Symbol = "A";\n        //b.Symbol = a.Symbol;    // Not work!\n        a.Symbol = "B";\n        MessageBox.Show(b.Symbol);\n    }\n\n\n}\n\n   public class MyClass\n\n{\n\n    private MyClass _dependentObj;\n    private string _symbol;\n\n    public MyClass DependentObj\n    {\n        get { return _dependentObj; }\n        set\n        {\n            _dependentObj = value;\n\n        }\n    }\n\n    public string Symbol\n    {\n        get { return _symbol; }\n        set\n        {\n            _symbol = value;\n            //Here add the update code\n            if(DependentObj !=null)\n            {\n                DependentObj._symbol = value;\n            }\n        }\n    }\n}	0
18592919	18592737	Null value after json deserialization on windows phone	string json = @"{""Service Provider"":""Test""}";\nvar obj = JsonConvert.DeserializeObject<TempObject>(json);\n\n\npublic class TempObject\n{\n    [JsonProperty("Service Provider")]\n    public string ServiceProvider;\n}	0
22234013	22232759	How to get value from Parent Gridview using C#	using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)\n    {\n        Integer idx = row.RowIndex + 1;\n        if (idx < gridView1.Rows.Count) {\n            GridViewRow theRow = gridView1.Rows[idx];\n            //string myvar = row.Cells[0].Text;\n            string myvar = theRow.Cells[0].Text;\n        }	0
11129878	11129792	Saving Flag attribute enum in settings file	VisibilitySwitchesSaves |= VisibilitySwitchesFlags.ReferenceLinesChecked;	0
11130128	11125843	How to create C# Event to handle MFC Windows message from PostMessage()	protected override void WndProc(ref System.Windows.Forms.Message message)\n{\n    if (message.Msg == MY_CUSTOM_WINDOW_MSG_ID)\n    {\n        // PROCESS EVENT HERE\n    }            \n    base.WndProc(ref message);\n}	0
5013930	5013747	What are the responsibilities of the components in an MVC pattern for a simple login	[HttpPost]	0
3778464	3777551	How to minimize owner window when a modal is showing?	void btnLogin_Click(object sender, RoutedEventArgs e)\n{\n    MyLoginDialog dialog = new MyLoginDialog();\n    dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;\n    dialog.WindowState = WindowState.Normal;\n\n    this.WindowState= WindowState.Minimized;\n    // Can also do this to completely hide the main window:\n    // this.Visibility = Visibility.Collapsed;\n\n    dialog.ShowDialog();            \n}	0
12723079	12722854	How to set file version comment	[assembly: AssemblyDescription("The assembly does xxx by yyy")]	0
18649870	18649844	How to connect WPF Application project to Windows Game project?	System.Diagnostics.Process.Start(@"c:\game\Game1.exe");	0
1993374	1993273	DI Framework: how to avoid continually passing injected depencies up the chain, and without using a service locator (specifically with Ninject)	Bind().To().WithConstructorArgument()	0
8781950	8781649	Make sure that target inherit some interface for custom attribute	[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=false)]\npublic class PluginAttribute : Attribute\n{\n    public string DisplayName { get; set; }\n    public string Description { get; set; }\n    public string Version { get; set; }\n}\n\npublic interface IPlug\n{\n    void Run(IWork work);\n}\n\n[Plugin(DisplayName="Sample Plugin", Description="Some Sample Plugin")]\npublic class SamplePlug : IPlug\n{\n    public void Run(IWork work) { ... }\n}	0
25239058	25239006	How can I make a function to Add Control in C#?	public void CreateControl(Control control)\n{\n    this.Controls.Add(control);\n}	0
7210628	7206786	Validating single Property in model which is binded customly	public ActionResult Rate([Bind(Exclude="Score")]RatingModel model)\n{    \n    model.Score = ParseScore( Request.Form("score"));\n    if(TryValidateModel(model))\n    {\n        ///validated with all validations\n    }\n\n}	0
2629717	2629705	Is it possible to enumerate for all permutations of two IEnumerables using linq	var query = from item1 in enumerable1\n            from item2 in enumerable2\n            select new { Item1 = item1, Item2 = item2 }	0
13287463	13287314	Find string in text, remove the first and last char	"(OK) ([0-9]+) ([A-Za-z_0-9]+) \"((?:(?!\";).)*)\";"	0
18140063	18137768	Split string into list of N-length strings using LINQ	var result = s.Select((x, i) => i)\n              .Where(i => i % 4 == 0)\n              .Select(i => s.Substring(i, s.Length - i >= 4 ? 4 : s.Length - i));	0
2579813	2579780	Complete if statement with strings and array of strings	checkString.Split('|').Contains(currentHeader) && Headers.Contains(currentHeader)	0
11324872	11324612	Removing Selected rows in a datagridview in C#?	for (int i = 0; i < dataGridView1.Rows.Count; i++)\n{\n    if (Convert.ToBoolean(dataGridView1.Rows[i]\n                          .Cells[yourCheckBoxColIndex].Value) == true)\n    {\n        dataGridView1.Rows.RemoveAt(i); \n    }\n}	0
12518466	12517969	How to use PasswordBox as TextBox?	private void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n    if (checkBox1.Checked == true)\n    {\n        TextBox.UseSystemPasswordChar = true;\n    }\n    else \n    {\n        TextBox.UseSystemPasswordChar = false;\n    }\n}	0
16846102	16844311	how do I configure a (MVC using entity framework) controller in a web api project	public DbSet<Note> Notes { get; set; }	0
656114	656072	How to create a string from bits?	// Fixed version of GetBits, with padding.\npublic static string GetBits(string input)\n{\n    StringBuilder sb = new StringBuilder();\n    foreach (byte b in Encoding.Unicode.GetBytes(input))\n    {\n        string lowBits = Convert.ToString(b, 2);\n        string eightBits = lowBits.PadLeft(8, '0');\n        sb.Append(eightBits);\n    }\n    return sb.ToString();\n}\n\npublic static string UnicodeBitsToString(string input)\n{\n    return Encoding.Unicode.GetString(ParseHex(input));\n}\n\npublic static byte[] ParseHex(string input)\n{\n    byte[] ret = new byte[input.Length/8];\n    for (int i=0; i < input.Length; i += 8)\n    {\n        ret[i/8] = Convert.ToByte(input.Substring(i, 8), 2);\n    }\n    return ret;\n}	0
324837	324831	Breaking out of a nested loop	// goto\n        for (int i = 0; i < 100; i++)\n        {\n            for (int j = 0; j < 100; j++)\n            {\n                goto Foo; // yeuck!\n            }\n        }\n    Foo:\n        Console.WriteLine("Hi");\n\n        // anon-method\n        Action work = delegate\n        {\n            for (int x = 0; x < 100; x++)\n            {\n                for (int y = 0; y < 100; y++)\n                {\n                    return; // exits anon-method\n                }\n            }\n        };\n        work(); // execute anon-method\n        Console.WriteLine("Hi");	0
11501772	11501716	XMLDocument GetElementByID returning null	id="_1"	0
8417606	8416413	Create new file with specific size	using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))\n        {\n            fs.SetLength(oFileInfo.FileSize);\n        }	0
14972938	14972395	Make into child of a object in unity 3d in c#	mainpumpkinclone.transform.parent = GameObject.Find("prickle" + i).transform;	0
3223337	3223331	WPF Styling a Cell Dynamically	typeof(ListViewItem)	0
12584437	10800315	how slow down speed of UIPanGestureRecognizer in Monotouch	var factor =2;\n\ngestureRecognizer.View.Center = new PointF (gestureRecognizer.View.Center.X + (translation.X/factor), gestureRecognizer.View.Center.Y + (translation.Y/factor));	0
10211521	10211470	How can I order a List<string>?	ListaServizi =ListaServizi.OrderBy(q => q).ToList();	0
30276522	30276472	Convert loop to linq expression	var result = persons.Where(p => !items.Any(x => x.ItemOneId == p.ItemOneId && x.ItemTwoId == p.ItemTwoId);	0
25969563	25968195	Replace/match sentence in large text	Regex.Replace(Your_html, @"<div\s+class\s*=\s*['|""]main['|""]\s*>((\r\n)*\s*\w+\s*(\r\n)*)+</div>","new text")	0
13753928	13753815	Return html format on wcf service instead of json or xml	[System.ServiceModel.Web.WebGet( UriTemplate = "c" , BodyStyle = WebMessageBodyStyle.Bare )]\n[OperationContract]\npublic System.IO.Stream Connect()\n{\n    string result = "<a href='someLingk' >Some link</a>";\n    byte[] resultBytes = Encoding.UTF8.GetBytes(result);\n    WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";\n    return new MemoryStream(resultBytes);\n}	0
3039673	3039545	Login to a Remote Service (ruby based) from iPhone	def login_from_api_key\n  self.current_user = User.find_by_api_key(params[:api_key]) unless params[:api_key].empty?\nend\n\ndef current_user\n  @current_user ||= (login_from_session || login_from_api_key || login_from_basic_auth || login_from_cookie) unless @current_user == false\nend	0
1476715	1476674	Comparing two files	byte b;  \n\n// ....\n\nif (Char.IsWhiteSpace((char) b))\n{\n   // skip...\n}	0
12025158	12024886	NumericUpDown Allows User To Type A Number Greater Than Maximum	/// <summary>\n    /// Checks for only up to 4 digits and no negatives\n    /// in a Numeric Up/Down box\n    /// </summary>\n    private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (!(e.KeyData == Keys.Back || e.KeyData == Keys.Delete))\n            if (numericUpDown1.Text.Length >= 4 || e.KeyValue == 109)\n            {\n                e.SuppressKeyPress = true;\n                e.Handled = true;\n            }\n    }	0
21672924	21672659	How to clear form data	foreach(Control c in layoutControl1.Controls) {\n    var edit = c as DevExpress.XtraEditors.BaseEdit; // base class for DX editors\n    if(edit != null)\n        edit.EditValue = null;\n    var listBox = c as DevExpress.XtraEditors.CheckedListBoxControl;\n    if(listBox != null) \n        listBox.UnCheckAll();\n}	0
18583385	18582852	Async Task to divide workload	for (int i = 0; i < taskCount; i++)\n{\n    GetRanges(ref startRange, ref endRange, total, i, startIndex);             \n    Console.WriteLine("startRange {0} EndRange {1}", startRange, endRange);             \n    var tempStartRange = startRange;\n    var tempEndRange = endRange;\n    tasks[i] = Task.Factory.StartNew(() => StartWork(tempStartRange, tempEndRange));\n}	0
3126137	3126118	Creating a custom ODBC / OLE driver in C#	OLE DB Provider	0
30658075	30657907	Display Chart (Histogram) Bars with real time data	chartPractice.Refresh();	0
27221181	27221126	How to return index as a negative	catch(Exception e)\n{\n    Console.WriteLine(e.Message);\n    insertIndex = -1;\n    // or\n    return -1;    \n}	0
12209089	12170944	How can you programmatically detect if javascript is enabled/disabled in a Windows Desktop Application? (WebBrowser Control)	const string DWORD_FOR_ACTIVE_SCRIPTING = "1400";\n    const string VALUE_FOR_DISABLED = "3";\n    const string VALUE_FOR_ENABLED = "0";\n\n    public static bool IsJavascriptEnabled( )\n    {\n        bool retVal = true;\n        //get the registry key for Zone 3(Internet Zone)\n        Microsoft.Win32.RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3", true);\n\n        if (key != null)\n        {\n            Object value = key.GetValue(DWORD_FOR_ACTIVE_SCRIPTING, VALUE_FOR_ENABLED);\n            if( value.ToString().Equals(VALUE_FOR_DISABLED) )\n            {\n                retVal = false;\n            }\n        }\n        return retVal;\n    }	0
30959480	30957042	WP 8.1 - How to save an image to Isolated Storage if know it's URL	private async void SaveFile()\n{\n    try\n    {\n        StorageFolder folder = ApplicationData.Current.LocalFolder;\n        if(folder != null)\n        {\n            StorageFile file = await folder.CreateFileAsync("imagefile", CreationCollisionOption.ReplaceExisting);\n            byte[] fileContnet = null; // This is where you set your content as byteArray\n            Stream fileStream = await file.OpenStreamForWriteAsync();\n            fileStream.Write(fileContent, 0, fileContent.Length);\n            fileStream.Flush();\n            fileStream.Close();\n        }\n    }\n    catch (Exception ex)\n    {\n        // Some Exception handling code\n    }\n}	0
8750307	8750290	How can I check multiple textboxes if null or empty without a unique test for each?	foreach (Control c in this.Controls)\n{\n    if (c is TextBox)\n    {\n        TextBox textBox = c as TextBox;\n        if (textBox.Text == string.Empty)\n        {\n            // Text box is empty.\n            // You COULD store information about this textbox is it's tag.\n        }\n    }\n}	0
15599737	15599643	Remove Items From a CheckBox List	List<ListItem> toBeRemoved = new List<ListItem>();\nfor(int i=0; i<chkItems.Items.Count; i++){\n    if(chkItems.Items[i].Selected == true)\n        toBeRemoved.Add(chkItems.Items[i]);\n}\n\nfor(int i=0; i<toBeRemoved.Count; i++){\n    chkItems.Items.Remove(toBeRemoved[i]);\n}	0
13236606	13235626	C# DateTime Convert from String	string myString = dateVal.ToString("yyyy-MM-dd");	0
199797	199718	Can you Instantiate an Object Instance from JSON in .NET?	T deserialize<T>(string jsonStr, T obj) { /* ... */}\n\n var jsonString = "{FirstName='Chris', LastName='Johnson, Other='unused'}";\n var person     = deserialize(jsonString, new {FirstName="",LastName=""});\n var x          = person.FirstName; //strongly-typed	0
11244100	10507416	Parsing JSON API in C#	WebClient client = new WebClient();\nvar data = client.DownloadString("");\nvar jArray = JArray.Parse(data);	0
8479756	8479712	Pause and Resume a Foreach Loop	foreach (var line in theCP4UnknownList.Distinct()) \n{ \n    var splitUnknowns = line.Split(' '); \n    KTS_Save saveForm = new KTS_Save(splitUnknowns[0], splitUnknowns[1], splitUnknowns[3], splitUnknowns[4], openFile.FileName); \n\n    saveForm.ShowDialog(); \n}	0
8156182	8155928	How to automate the format for numbers in wpf textbox	Text="{Binding YourProperty, StringFormat=n}"	0
27991905	27991838	How do I retrieve data from my dynamic textboxes?	lblScope.Text = "";\n\nforeach (Control control in PlaceHolder1.Controls)\n{\n    if (control is TextBox)\n    {\n        TextBox txt = (TextBox)control;\n        lblScope.Text += string.Format("<li>{0}</li>", txt.Text);\n    }\n}	0
9702960	9702893	How to return IEnumerable<T> for a single item	IEnumerable<T> getItems()\n{\n    if ( someCondition.Which.Yields.One.Item )\n    {\n        yield return MyRC;\n    }\n    else\n    {\n        foreach(var i in myList)\n            yield return i;\n    }\n}	0
32925699	32925674	Deleting Object From List<> in C#	List<CV_details> deleteList = new List<CV_details>();\nforeach (var person in list){\n    if (person.getID()==id)\n    {\n        //...\n        n = Int32.Parse(Console.ReadLine());\n        if (n == 1)\n        {\n            deleteList.Add(person);\n        }\n    }\n}\n\nforeach (var del in deleteList)\n{\n    list.Remove(del);\n}	0
11961783	11961682	C# MySQL second DataReader in DataReader while loop	MultipleActiveResultSets=true;	0
4084833	4076001	Activating custom feature using FBA in sharepoint	SPSecurity.RunWithElevatedPrivileges(delegate() {\n    SPWeb _web = properties.Feature.Parent as SPWeb; \n    SPUserToken sysAdmin = _web.Site.SystemAccount.UserToken;\n    using (SPSite elevatedSite = new SPSite(_web.Site.ID, sysAdmin)) {\n        using (SPWeb web = elevatedSite.OpenWeb(_web.ID)) {\n            //Code goes here...\n        }\n    }\n});	0
9292135	9292084	How do I import quickgraph library to my project	PM> Install-Package QuickGraph	0
10782283	10782253	Find out if a process is using an Internet Connection	netstat -ob	0
12471356	12470873	Having trouble trying to implement a query on dataset/datatable	var ds = new DataSet();\nvar tranDtls = new DataTable("tran_dtls");\ntranDtls.Columns.Add("gl_code", typeof(string));\ntranDtls.Columns.Add("amt", typeof(int));\nvar row = tranDtls.NewRow();\nrow["gl_code"] = "a";\nrow["amt"] = 1;\ntranDtls.Rows.Add(row);\nds.Tables.Add(tranDtls);\n\nvar result = ds.Tables["tran_dtls"].AsEnumerable()\n    .Where(r => (string)r["gl_code"] == "a")\n    .Select(r => (int)r["amt"])\n    .Sum();	0
3726823	3726809	Correcting characters in a string?	public string UrlCorrection (string text)\n{\n    StringBuilder correctedText = new StringBuilder (text);\n\n    return correctedText.Replace("?", "c")\n                        .Replace("?", "i")\n                        .Replace("?", "u")\n                        .Replace("?", "g")\n                        .Replace("?", "o")\n                        .Replace("?", "s")\n                        .ToString ();\n}	0
16586691	16586607	Binding CheckBoxList to a Generic List	public class MyProduct\n{\n   public int Id { get; set; }\n   public string ProductName { get; set; }\n   public bool selected { get; set; }\n\n   ...\n}	0
1973315	1973272	SyncRoot for IList	List<string> list = new List<string>();\nlock (((IList)list).SyncRoot)\n{\n}	0
20535727	20535370	How to Select an XML Node with a Namespace in LINQ to XML	var doc = XDocument.Parse(data);  \nvar names = new XmlNamespaceManager(new NameTable());\nnames.AddNamespace("emtpy", "http://qusetons.com/Cdc/AbcSchema.xsd");\nConsole.WriteLine(doc.XPathSelectElement("/emtpy:Abc/emtpy:xxx", names).Value);	0
14538670	14538614	Generating at least 3 different random values within a small range of tries	int count = 0;\nwhile (count < 3)\n{\n    int x = r.Next(0, 3);\n    int y = r.Next(0, 3);\n\n    if (matrix[x, y] != 1)\n    {\n        matrix[x, y] = 1;\n        count++;\n    }\n}	0
13948532	13948432	Find the difference of two folders and delete files	var common = from f1 in Directory.EnumerateFiles(folderA, "*.*", SearchOption.AllDirectories)\n             join f2 in Directory.EnumerateFiles(folderB, "*.*", SearchOption.AllDirectories)\n             on Path.GetFileName(f1) equals Path.GetFileName(f2)\n             select f1;\n\nforeach (string file in common)\n{\n    File.Delete(file);\n}	0
2647854	2647829	Convert text box text into Argb argument	someTextBox.Text = "AAFFBBDD";\nint param = int.Parse(someTextBox.Text, NumberStyles.AllowHexSpecifier);\nSolidBrush trnsRedBrush = new SolidBrush(Color.FromArgb(param));	0
29041550	29011387	How to keep line breaks while saving to SQL database and retrieving it to show inside a label	white-space: pre-wrap;	0
30605517	30605396	Converting dates in C#	var s = temp.ToUniversalTime().ToShortDateString();	0
16011784	16011351	Throw single custom exception from Class Library	AppDomain.CurrentDomain.UnhandledException += (sender, e) =>\n    {\n        var exception = e.ExceptionObject as Exception;\n        if (exception != null && exception.Source == "MyLib")\n        {\n            // Do stuff here\n        }\n    };	0
12902753	12902674	Equivalent for validateRequest in mvc3	[ValidateInput(false)]\npublic ActionResult Index(string InputText)\n{\n    return View();\n}	0
28117056	28116318	Using ConcurrentDictionary as a cache and handling update	public bool UpdateSetting<T>(string key, T value)\n{\n    lock \n    {\n        T oldValue;            \n        if (this.cachedValues.TryGetValue(key, out oldValue)\n        {\n            if (oldValue != value)\n            {\n                this.cachedValues[key] = value;\n                settingRepository.Update(key, value);\n            }\n            return true;\n        } \n        else \n        { \n           return false;\n        }            \n    }\n}	0
27910651	27909842	StreamWriter encoding string incorrectly	Encoding.ASCII	0
10618246	10617870	Generate xml attributes	const string ns = "http://test2";\nconst string si = "http://test3";\nconst string schema_location = "http://test.xsd";\n\nXNamespace xns = ns;\nXNamespace sinsp = si;\n\n     XElement xe = new XElement(xns + "element",\n           new XAttribute(XNamespace.Xmlns + "xsi", si),\n           new XAttribute(sinsp+ "schemaLocation", schema_location),\n           new XElement(xns + "sometag", "somecontent")\n        );\n\n     return xe;	0
11556981	11556935	Reading values from DataTable	DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];\n\nfor (int i = 0; i < dr_art_line_2.Rows.Count; i++)\n{\n    QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);\n    //Similarly for QuantityInIssueUnit_uom.\n}	0
21471564	21471543	How do I create a List<> from all the data in my DataGridView ?	List<MyItem> items = new List<MyItem>();\n        foreach (DataGridViewRow dr in dataGridView1.Rows)\n        {\n            MyItem item = new MyItem();\n            foreach (DataGridViewCell dc in dr.Cells)\n            { \n                ...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value  \n            }\n\n            items.Add(item);\n        }	0
4758111	4757883	Get a file list from TFS	var server = RegisteredTfsConnections.GetProjectCollection(new Uri("http://hostname:8080/"));\n        var projects = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(server);\n        var versionControl = (VersionControlServer)projects.GetService(typeof(VersionControlServer));\n\n        var newestDate = DateTime.MinValue;\n        Item newestItem = null;\n        var items = versionControl.GetItems("$/theproject/trunk/setup/*.msi");\n        foreach (var item in items.Items)\n        {\n            if (item.ItemType != ItemType.File)\n                continue;\n\n            if (item.CheckinDate > newestDate)\n            {\n                newestItem = item;\n                newestDate = item.CheckinDate;\n            }\n        }\n        newestItem.DownloadFile("C:\\temp\\" + Path.GetFileName(newestItem.ServerItem));	0
5841350	5841335	concatinating int[] to same size string[]	int[] numbers = { 1, 2, 3};\nstring[] words = { "one", "two", "three" };\n\nvar list = numbers.Zip (words, (n, w) => n + "=" + w);	0
34141639	34138235	How to use roslyn c# compiler with visual studio 2015?	Microsoft.CodeAnalysis	0
24221680	24221552	Get seed of Random object without passing in the seed?	long seed = System.currentTimeMillis();\nRandom rand = new Random(seed);\nSystem.out.println(seed);	0
7369418	7369414	how to restrict validatin check on gridview button click in c#?	CausesValidation='false'	0
24394802	24394723	How to have events in WPF user control	public event RoutedEventHandler MyEvent;\nprivate void button_Clicked(object sender, RoutedEventArgs e)\n{\n    if (MyEvent != null)\n        MyEvent(this, e);\n}	0
1300736	1300670	Matching numbers in a string of a certain length with regex	Regex regexObj = new Regex("\d\d");\nMatch matchObj = regexObj.Match(subjectString);\nwhile (matchObj.Success) {\n    matchObj = regexObj.Match(subjectString, matchObj.Index + 1); \n}	0
31713713	31713513	Restoring/Verifying In-App Purchases in Windows 10	LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;\n\n// get the license info for one of the app's in-app offers\nProductLicense inAppOfferLicense = \n    licenseInformation.ProductLicenses["MyFavoriteInAppOffer"];\n\n// get the expiration date of this in-app offer\nDateTimeOffset expirationDate = inAppOfferLicense.ExpirationDate;	0
5571260	5571180	filter array with integer values	var array = new[]{"01.0", "01.4", "01.5", "02.0", "02.5", "02.6", "03.0", "03.2"};\n\narray.Select(i => Decimal.Parse(i)).Where(d => Decimal.Remainder(d, 1) == 0);	0
1582577	1582555	Initialize int[][,] in C#	int[][,] a = new int[][,]\n{\n    new int[,]\n    {\n        {1, 1, 1, 1},\n        {1, 1, 1, 1},\n        {1, 1, 1, 1},\n        {1, 1, 1, 1},\n\n    },\n    new int[,]\n    {\n        {1, 1, 1, 1},\n        {1, 0, 0, 1},\n        {1, 0, 0, 1},\n        {1, 1, 1, 1},\n    }\n};	0
1131726	1131687	how to upcast object array to another type of object array in C#?	using System.Linq;\n\nnewObjects = objects.Select(eachObject => (ClassA)eachObject).ToArray();	0
12532630	12525032	Add attachment for new contact in salesforce using c#	salesforce.SessionHeaderValue = new SforceService.SessionHeader();\nsalesforce.SessionHeaderValue.sessionId = loginResult.sessionId;\nsalesforce.Url = loginResult.serverUrl;\n...\nString contactId = mySFervive.UserRegistration(....);\nAttachment a = new Attachment();\na.Body = readFileIntoByteArray(someFile);\na.parentId = contactId;\na.Name = "Order #1";\n\nSaveResult sr = salesforce.create(new SObject [] {a})[0];\nif (sr.success){ \n// sr.id contains id of newly created attachment\n} else {\n //sr.errors[0] contains reason why attachment couldn't be created.\n}	0
7875266	5973370	Showing the alert on moving through one page to another by Unsave Change	function ValueChanged() {\n     var textvalue;\n\n     textvalue = removeHTMLTags(tinyMCE.get('<%=txbText.ClientID %>').getContent());\n     if (textvalue != tinyText) {\n         var ssave = window.confirm('Your changes are not saved. Do you want to save your changes before you exit.')\n         if (ssave == true) {\n             document.getElementById('<%=btnSave.ClientID%>').click();\n             return false;\n         }\n         else\n             return true;\n         }\n     }	0
25098663	25098239	parse xml that contain colon	XmlDocument doc = new XmlDocument();\n\n    doc.Load(PATH);\n\n    XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);\n    ns.AddNamespace("test", "http://www.test.com/");\n    XmlNode node = doc.SelectSingleNode("//test:solution//test:question", ns);	0
9138390	9137434	How to update label control on the page using QueryStringParameter value?	if(Request.QueryString["doc_family"] == "CR") DocumentNameLabel.Text = "CleanRoom";	0
14462027	14461900	How to alternate between bold and regular font in System.Drawing	var fontCollection = new List<KeyValuePair<int, string>>();\nfontCollection.Add(new KeyValuePair<int, string>(10, "Bold"));\nfontCollection.Add(new KeyValuePair<int, string>(12, "Regular"));\nfontCollection.Add(new KeyValuePair<int, string>(14, "Bold"));\nforeach (var item in fontCollection)\n{\n    var font = new Font("Verdana", item.Key, (FontStyle)Enum.Parse(typeof(FontStyle), item.Value));\n    // use font\n}	0
24277261	24276550	Saving images to a project folder in asp.net/c#	string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)	0
22419097	22416280	Change Culture in Web.Config Programmatically	XmlDocument config = new XmlDocument();\nconfig.Load("C:\\inetpub\\wwwroot\\MyProject\\web.config");\n\nvar node = config.SelectNodes("system.web/globalization")[0];\nnode.Attributes["culture"].Value = "new value";\n\nconfig.Save("C:\\inetpub\\wwwroot\\MyProject\\web.config");	0
19486334	19486168	IDisposable implementation in C# - is optional disposal of an injected IDisposable OK?	using(var myConn = new Connection(connectionString))\n{\n}	0
1558012	1557968	Responding to HTML hyperlink clicks in a C# application	private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n    {\n        e.Cancel = true;\n        SeeAlsoFrm seeAlso = new SeeAlso();\n        seeAlso.showDialog();\n    }	0
15739106	15738986	Using Stored Procedure to Insert parameters from DataTable	con.Open();\nSqlTransaction trans = con.BeginTransaction();\n\ntry {\n    // Execute the SP here\n    // After all SP executed, call the commit method\n    trans.Commit();\n} catch (Exception ex) {\n    // An error happened, rollback\n    trans.RollBack();\n}\ncon.Close();	0
15470434	15470303	Can you select all child collections of a collection of entities as a single collection?	var children=parents.SelectMany(p=>p.Children)	0
18904503	18904398	Get list from enum	var doNotUse = new[] { MyEnum.Ab, MyEnum.Abc };\nvar enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>()\n    .Where(me => !doNotUse.Contains(me))\n    .ToList();	0
17892584	17892237	Occurrences of a List<string> in a string C#	private int stringMatches(string textToQuery, string[] stringsToFind)\n{\n  int count = 0;\n  foreach (var stringToFind in stringsToFind)\n  {\n    int currentIndex = 0;\n\n    while ((currentIndex = textToQuery.IndexOf(stringToFind , currentIndex, StringComparison.Ordinal)) != -1)\n    {\n     currentIndex++;\n     count++;\n    }\n  }\n  return count;\n}	0
19019779	19019718	Checking Date format from a string in C#	string inputString = "2000-02-02";\n    DateTime dDate;\n\n    if (DateTime.TryParse(inputString, out dDate))\n    {\n        String.Format("{0:d/MM/yyyy}", dDate); \n    }\n    else\n    {\n        Console.WriteLine("Invalid"); // <-- Control flow goes here\n    }	0
16606494	16606469	C# convert datetime to custom format	ord.invoiceDate = ((DateTime)dt.Rows[i]["invoicedate"]).ToString("dd-MM-yyyy");	0
26063652	26015703	How to unwrap an element if it exists with CsQuery?	var dom = CQ.CreateFromUrl("http://www.myurl.com");\nstring result = dom[".link a"].Text();	0
30725278	30724901	Multiple Consoles in a Single Console Application	using (var process1 = new Process())\n{\n    process1.StartInfo.FileName = @"..\..\..\ConsoleApp1\bin\Debug\ConsoleApp1.exe";\n    process1.Start();\n}\n\nusing (var process2 = new Process())\n{\n    process2.StartInfo.FileName = @"..\..\..\ConsoleApp2\bin\Debug\ConsoleApp2.exe";\n    process2.Start();\n}\n\nConsole.WriteLine("MainApp");\nConsole.ReadKey();	0
13542826	13542805	Int to string conversion with leading 0s	int num = 1;\n// pad with 0 up to 4 places\nstring str = num.ToString("D4");	0
2605055	2559422	DataBinding and ErrorProvider - How to provide custom error messages?	textBox1.DataBindings.Add("Text", bindingSource1, "IntValue", false, \n    System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged);	0
5855786	5855712	LINQ Method Syntax - how to accomplish dynamic Linq statements	var query = dc.agenda;\nif(!String.IsNullOrEmpty(group))\n    query = query.Where(a => a.no_group == group)\nif(!activityType.Equals("ALL"))\n    query = query.Where(a => a.type_manifestation == activityType)\n// and so on for all your conditions...\n\nif (Language == ConfBouwHelper.LanguageEnum.French)\n    query = query.Where(a => (a.langue == "FRENCH" || a.langue == "B"));\nelse\n    query = query.Where(a => (a.langue == "DUTCH" || a.langue == "B"));\n\nlistAgendaItems = query.ToList<agenda>();	0
4868292	4868166	Binding ObervableCollection to ListBox	public class MyViewModel\n{\n    public ObservableCollection<ContactListModel> ContactLists{get;set;}\n\n    public MyViewModel()\n    {\n        var data = new ContactListDataAccess();\n        ContactLists = data.GetContacts();\n\n    }\n}	0
29459106	29458967	Unity 2D spawn variables won't update	public class SpawnPoint : MonoBehaviour\n{\n    void OnTriggerEnter2D(Collider2D other)\n    {\n        if (other.tag == "Player")\n        {\n            var playerController = other.GetComponent<PinkPlayerControler>();\n            playerControler.spawnPosition = transform.position;\n        }\n    }\n}	0
875370	875355	Storing reader information in C#	public IEnumerable<Category> GetCategories()\n{\n    using (var connection = new MySqlConnection("CONNECTION STRING"))\n    using (var command = new MySqlCommand("SELECT name FROM categories", connection))\n    {\n        connection.Open();\n        using (var reader = command.ExecuteReader())\n        {\n            while (reader.Read())\n            {\n                yield return new Category { name = reader.GetString(0) };\n            }\n        }\n    }\n}	0
11864286	11864226	Optional Parameters with default values in VB6	Private Sub ChangeTab(ByVal tabName As String, Optional ByVal clearAll As Boolean = True)	0
18690477	18690438	C# : Removing an item from a List<T> without knowing its index?	List<FileItem> folder = new List<FileItem>();\nfolder.Remove(folder.SingleOrDefault(x=>x.Name == "myname"));\nfolder.Remove(folder.SingleOrDefault(x => x.Path == "mypath"));	0
32119879	32119761	Substring in linq	var query = (from tab in MyTable\n             where tab.DATA.TrimStart(new [] {' ', '0', '\t'}).StartsWith("1")\n             select new\n             {\n                tab.ID,\n                tab.DATA\n             }).ToList();	0
33233767	33232835	Read XML file parse it into a class list	using (FileStream f = new FileStream(<pathtoxml>, FileMode.Open, FileAccess.Read))\n            {\n                DataContractSerializer dcs = new DataContractSerializer(typeof(List<Animal>));\n                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(f, new XmlDictionaryReaderQuotas());\n\n                List<Animal> listfromxml = (List<Animal>)dcs.ReadObject(reader);\n            }	0
19602129	19602125	exclude an element from a grouping	var dict = new Dictionary<long, MyClass>(...);\nvar duplicates = from d in dict\n                 group d by d.Value.some_property into g\n                 where g.Count() > 1\n                 select new {Key= g.Key, Values = g.Skip(1)};	0
604876	604862	Passing sql statements as strings to mssql with C#?	using (SqlConnection conn = new SqlConnection(databaseConnectionString))\n{\n    using (SqlCommand cmd = conn.CreateCommand())\n    {\n        cmd.CommandText = "StoredProcedureName";\n        cmd.CommandType = CommandType.StoredProcedure;\n\n        cmd.Parameters.AddWithValue("@ID", fileID);\n\n        conn.Open();\n        using (SqlDataReader rdr =\n                   cmd.ExecuteReader(CommandBehavior.CloseConnection))\n        {\n            if (rdr.Read())\n            {\n                // process row from resultset;\n            }\n        }\n    }\n}	0
33478354	33478158	How to make sure that stream is read completely?	Stream.Copy	0
19294846	19294747	Want to deserialize XML to object in a specific way	[Serializable]\npublic class MyObject : ISerializable \n{\n  public int n1;\n  public int n2;\n  public String str;\n\n  public MyObject()\n  {\n  }\n\n  protected MyObject(SerializationInfo info, StreamingContext context)\n  {\n    n1 = info.GetInt32("i");\n    n2 = info.GetInt32("j");\n    str = info.GetString("k");\n  }\n[SecurityPermissionAttribute(SecurityAction.Demand, \nSerializationFormatter =true)]\n\npublic virtual void GetObjectData(SerializationInfo info, StreamingContext context)\n  {\n    info.AddValue("i", n1);\n    info.AddValue("j", n2);\n    info.AddValue("k", str);\n  }\n}	0
32871974	32871261	c#-how to delete vowels in an array of string?	string[] names = new string[5];\nnames[0] = "john";\nnames[1] = "samuel";\nnames[2] = "kevin";\nnames[3] = "steve";\nnames[4] = "martyn";\n\nList<char> vowels = new List<char>("AaEeIiOoUuYy".ToCharArray());\n\nfor(int i = 0; i < names.Length; i++) {\n    string name = names[i];\n    string trimmedName = name;\n\n    foreach(char vowel in vowels) {\n        int vowelIndex;\n        while((vowelIndex = trimmedName.IndexOf(vowel)) != -1) {\n            trimmedName = trimmedName.Substring(0, vowelIndex) + trimmedName.Substring(vowelIndex + 1);\n        }\n\n    }\n    name = trimmedName;\n}	0
2230849	2230826	Remove invalid (disallowed, bad) characters from FileName (or Directory, Folder, File)	public string MakeValidFileName(string name) {\n  var builder = new StringBuilder();\n  var invalid = System.IO.Path.GetInvalidFileNameChars();\n  foreach ( var cur in name ) {\n    if ( !invalid.Contains(cur) ) {\n      builder.Append(cur);\n    }\n  }\n  return builder.ToString();\n}	0
9429038	9428685	Sprite in wrong direction	// Change it to +MathHelper.PiOver2 if it goes the wrong way\nspriteBatch.Draw(texture, position, null, Color.White, rotation-MathHelper.PiOver2, origin, scale, SpriteEffects.None, 0f);	0
29904597	29904529	Gaining access to a variable in another class	public string MemType { get; private set }	0
13502427	13502088	Two Picture Boxes that cycle through images on each button click	//global int\nint count = 0;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n  count++;\n  switch(count)\n  {\n     case 1:\n       //load image 1 and 2\n       break;\n     case 2:\n       //load image 3 and 4\n       break;\n     case 3:\n       //load image 5 and 6\n       break;\n     case 4:\n       //load image 7 and 8\n       break;\n     case 5:\n       //load image 9 and 10\n       break;\n     default: \n       break;\n  }\n}	0
24329968	24326702	linq to specific part of xml document	applicant = (from q in theCases.Descendants("applicants").Descendants("applicant")//.Descendants("applicant-name")\n      where ((string)q.Attribute("data-format") == "original")// && (q.Element("name") != null)\n      select q.Value).FirstOrDefault()	0
3500421	3500368	Link button changing color when any data pager event takes place	void lbtnCharacter_Command(object sender, CommandEventArgs e)\n{\n    // redirect to self with tag as qs parameter\n    Response.Redirect(string.Format("{0}?tag={1}", Request.Url.GetLeftPart(UriPartial.Path), e.CommandArgument));\n}\n\nprotected void Page_PreRender(object sender, EventArgs e) \n{\n    if (Request.QueryString["tag"] != null) {\n        LinkButton lbtnSelected = (LinkButton)divAlphabets.FindControl("lbtnCharacter" + Request.QueryString["tag"]);\n        lbtnSelected.CssClass = "firstCharacter highlighted";\n    }\n}	0
33322781	33322719	Locking a Resource and generating Time Stamps according to lock time	public class HiResDateTime\n{\n   private static long lastTimeStamp = DateTime.UtcNow.Ticks;\n   public static long UtcNowTicks\n   {\n       get\n       {\n           long original, newValue;\n           do\n           {\n               original = lastTimeStamp;\n               long now = DateTime.UtcNow.Ticks;\n               newValue = Math.Max(now, original + 1);\n           } while (Interlocked.CompareExchange\n                        (ref lastTimeStamp, newValue, original) != original);\n\n           return newValue;\n       }\n   }\n}	0
24994227	24994101	How can I search a Substring in a List	string[] langs = new string[] { "C++", "Java", "Perl", "Prolog", "Microsoft office Professional Plus 2013", };\n\nvar lang_list = new List<string>(langs);\n\nstring search_word = "office";\n\n// finding first language that has your search word\nvar lang = lang_list.First(l => l.IndexOf(search_word, StringComparison.InvariantCultureIgnoreCase) > -1).ToArray();\n\n// find all matching lang\nvar all_lang = lang_list.Where(l => l.IndexOf(search_word, StringComparison.InvariantCultureIgnoreCase) > -1).ToArray();	0
8795084	8795036	storing int32 in a byte array	byte temp[4];\ntemp[3] = value & 0xFF;\ntemp[2] = (value >> 8) & 0xFF;\ntemp[1] = (value >> 16) & 0xFF;\ntemp[0] = (value >> 24) & 0xFF;\nfor(int i = 0; i < 4; i++)\n    message[offset+i] = temp[i];	0
17461028	17458850	Validating an XML file without an xsd file	try\n{\n    var file = "Your xml path";\n\n    var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = null };\n\n    using (var reader = XmlReader.Create(new StreamReader(file), settings))\n    {\n        var document = new XmlDocument();\n        document.Load(reader);\n    }\n}\n\ncatch (Exception exc)\n{\n    //show the exception here\n}	0
20909374	20909161	using C# for creating a stored procedure	com.CommandText = "CREATE PROCEDURE dbo.Facebook( @PostID int,@PersonalID int) AS "+\n                  " INSERT dbo.[Like] (PostID) VALUES (@PersonalID); " +\n                  " UPDATE C SET Counter = (SELECT COUNT(*) FROM dbo.[Like] WHERE PostId = @PersonalID)" +\n                  " FROM dbo.Counter AS C " +\n                  " WHERE C.PostID = @PersonalID  ";	0
9022889	9021829	C# WindowsForm GridView - How to add class into GridView?	BindingList<PurchaseOrderItem>	0
6703553	6703516	can i redirect from the global.asax to controller action?	protected void Application_Error()\n{\n    var exception = Server.GetLastError();\n    // TODO: Log the exception or something\n    Response.Clear();\n    Server.ClearError();\n\n    var routeData = new RouteData();\n    routeData.Values["controller"] = "Home";\n    routeData.Values["action"] = "ErrorPage";\n    Response.StatusCode = 500;\n    IController controller = new HomeController();\n    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);\n    controller.Execute(rc);\n}	0
19736773	19735372	How to pass IEnumerable<SelectListItem> collection to a MVC Partial View with only one database lookup per request	public class PurchaseItemViewModel\n{\n  public string ItemName { get; set; }\n  public decimal Cost { get; set; }\n  public string Category { get; set; }\n  public IEnumberable<Category> Categories { get; set; }\n\n  public PurchaseItemViewModel(PurchaseItemModel item, List<Category> categories)\n  {\n       //initialize item and categories\n  }\n}	0
25983179	25983076	Find numbers in string	static void Main()\n        {\n            var input = "content: ($$)^1 OR title: ($$)^15 OR url: ($$)^20";\n            foreach(Match m in Regex.Matches(input, @"(?<name>\S+): \(\$\$\)\^(?<digits>\d+)"))\n            {\n                Console.WriteLine(m.Groups["name"] + " : " + m.Groups["digits"]);\n            }\n        }	0
11574617	11574587	Display a running date and time in a textbox in C#	System.Windows.Forms.Timer tmr = null;\nprivate void StartTimer()\n{\n    tmr = new System.Windows.Forms.Timer();\n    tmr.Interval = 1000;\n    tmr.Tick += new EventHandler(tmr_Tick);\n    tmr.Enabled = true;\n}\n\nvoid tmr_Tick(object sender, EventArgs e)\n{\n    myTextBox.Text = DateTime.Now.ToString();\n}	0
8844067	8843954	Best way to continously update data in Windows Phone?	System.Windows.Threading.DispatcherTimer dt;\n\n    public MainPage()\n    {\n        InitializeComponent();\n        dt = new System.Windows.Threading.DispatcherTimer();\n        dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds\n        dt.Tick += new EventHandler(dt_Tick);\n    }\n\n    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)\n    {\n        dt.Stop();\n    }\n\n    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\n    {\n        dt.Start();\n    }\n\n    void dt_Tick(object sender, EventArgs e)\n    {\n        listBox1.Items.Add(listBox1.Items.Count + 1); // for testing\n    }\n\n    private void PageTitle_Tap(object sender, GestureEventArgs e)\n    {\n        NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative)); // for testing\n    }	0
18900970	18900505	Need command to lauch Outlook, then close it when I'm done	Outlook.Application p_objOutlook = new Outlook.Application();\nif (p_objOutlook.Explorers.Count == 0)\n{\n  Outlook.Namespace ns = p_objOutlook.GetNamespace("MAPI")\n  ns.Logon();\n  Outlook.MAPIFolder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.OlFolderInbox)\n  inbox.Display();\n}	0
535501	517461	Creating a header row with buttons in a Custom GridView	void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)\n  {\n\n    if(e.Row.RowType == DataControlRowType.Header)\n      {\n         ...your code here\n\n      }	0
32405534	32405280	Passing null into a SQL command	CommandText = @"UPDATE thetable SET Yes = @yesFlag, NoFlag = @noflag, NextValue = 10";\n    Command.Parameters.AddWithValue("@yesFlag", list.yesFlag);\n    Command.Parameters.AddWithValue("@noFlag", list.previous);	0
24381217	24381199	How to get the Radwindow from a page in wpf	var wnd = RadWindow.GetParentRadWindow(this);	0
26912782	26911811	C# Using BinaryReader to read color byte values of a bitmap image	unsafe\n{\n    var bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);\n\n    byte* first = (byte*)bitmapData.Scan0;   \n    byte a = first[0];\n    byte r = first[1];\n    byte g = first[2];\n    byte b = first[3];\n\n    ...\n\n    bmp.UnlockBits(bitmapData);\n}	0
24607980	24607611	How to check sequence in string using regular expression	var pattern = @"^(\d+(-|\.))*\d+$";	0
5135181	5135013	How do you find the owner of a lock (Monitor)?	private int lockOwner;\nprivate object lockObject = new object();\n...\nvoid foo() {\n    lock(lockObject) {\n        lockOwner = Thread.CurrentThread.ManagedThreadId;\n        // etc..\n    }\n}	0
980218	979635	Programmatically instantiate a web part page in Sharepoint	string newFilename = "newpage.aspx";\nstring templateFilename = "spstd1.aspx";\nstring hive = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");\nFileStream stream = new FileStream(hive + templateFilename, FileMode.Open);\nusing (SPSite site = new SPSite("http://sharepoint"))\nusing (SPWeb web = site.OpenWeb())\n{\n    SPFolder libraryFolder = web.GetFolder("Document Library");\n    SPFileCollection files = libraryFolder.Files;\n    SPFile newFile = files.Add(newFilename, stream);\n}	0
8058776	8058695	c# datetime hour minute validation	string dateString = "11/11/2011 15:04"; // <-- Valid\nstring format = "dd/MM/yyyy HH:mm";\nDateTime dateTime;\nif (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))\n{\n  Console.WriteLine(dateTime);\n}	0
25629727	25629584	Why can't you have a lambda in a conditional breakpoint in Visual Studio 2013?	if (result.Any(i => i.Any(j => j < 0)))\n    System.Diagnostics.Debugger.Break();	0
22781747	22781695	How to differentiate between actionresults	[Authorize]\n    public ActionResult StepTwo(PostcodesModel model)\n    {\n        return View();\n    }\n\n    [ActionName("StepTwo")]\n    [Authorize]\n    [HttpPost]\n    [ValidateAntiForgeryToken]\n    public ActionResult StepTwoPost(PostcodesModel model)\n    {\n        return View();\n    }	0
22864224	22863665	EF loop to update with async await	private async void button2_Click(object sender, EventArgs e)\n{\n  var customerIDs = File.ReadAllLines(@"c:\temp\customerids.txt").ToList();\n  var updates = customerIDs.Select(id => DoSomethingWithTheCustomerAsync(id));\n  var results = await Task.WhenAll(updates);\n  MessageBox.Show("Done");\n}	0
9905839	9905588	Datagridview Refresh window c# desktop application	DataGridView1.CurrentCell = DataGridView1[0, 1]	0
7321226	7321012	Moq on 2 interfaces with same function	Mock<I1> menuServiceMock = new Mock<I1>();\nvar i2Mock = menuServiceMock.As<I2>();\n\n// Verifies that I2.Foo was called on the object\ni2Mock.Verify(x => x.Foo("foo"), Times.Once());\n// Verifies that I1.Foo was called on the object:\nmenuServiceMock.Verify(x => x.Foo("foo"), Times.Once());	0
18917479	18916744	Change color of particular location in tab control	private int activeButton = -1;\n\nprivate void tabControl1_MouseMove(object sender, MouseEventArgs e)\n{\n    int button;\n    for (button = this.tabControl1.TabPages.Count-1; button >= 0; button--)\n    {\n        Rectangle r = tabControl1.GetTabRect(button);\n        Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);\n        if (closeButton.Contains(e.Location)) break;\n    }\n    if (button != activeButton) {\n        activeButton = button;\n        tabControl1.Invalidate();\n    }\n}	0
6837904	6837853	C# DateTime strange behaviour	for (int i = 2000; i < 2100; i++)\n {\n       string year = i + "0101";\n       DateTime pt = DateTime.ParseExact(year, "yyyyMMdd", null);\n       Console.WriteLine("{0}. {1}", (i-1999), pt.ToShortDateString());\n }	0
15879212	15879113	Using replace function with regex in C Sharp	imageSrc  = Regex.Replace(image, "data:image/(png|jpg|gif|jpeg|pjpeg|x-png);base64,", "");	0
26228242	26227936	How to format datarow content for a put request	public string DataRowToJSON(System.Data.DataRow row)\n    {\n        System.Collections.Generic.List<string> Fields = new System.Collections.Generic.List<string>();\n        foreach (System.Data.DataColumn item in row.Table.Columns) Fields.Add(string.Format("\"{0}\":\"{1}\"", item.ColumnName, row[item].ToString()));\n        return string.Format("{{{0}}}", string.Join(",", Fields));\n    }	0
21279022	21278827	How to create a text file & write data to it using C#?	scheduled task	0
21485299	21434280	Issue with Update Command in gridview	LinkButton lb = (LinkButton) GridView1.Rows[GridView1.EditIndex].FindControl("LinkButton1");\nif(lb!=null){\n  //Now check what is the Text of your link button. Depending on Enable or disable you set the parameter value as needed\n  e.InputParameters["value"] = lb.Text=="Disable"? 0 : 1;\n}	0
17710578	17710324	How change variable value depending on architecture	Environment.Is64BitProcess	0
1331095	1331052	Check Control.Value for data	DateTimePicker dtp = control as DateTimePicker;\nif(dtp !=null)\n{\n   //here you can access dtp.Value;\n}	0
19087579	19087443	How To shows Two column values ,when i selected location Maps	google.maps.event.addListener(marker, "click", function(e) {\n                    infoWindow.setContent('<p>' + data.FarmerName \n                            + ', ' + data.Area + '</p>');\n                    infoWindow.open(map, marker);\n                });	0
308962	308954	How to make a method to return random string in the format A1A 1A1?	private static readonly Random rng = new Random();\n\nprivate static RandomChar(string domain)\n{\n    int selection = rng.Next(domain.Length);\n    return domain[selection];\n}\n\nprivate static char RandomDigit()\n{\n    return RandomChar("0123456789");\n}\n\nprivate static char RandomLetter()\n{\n    return RandomChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ");\n}\n\npublic static char RandomStringInSpecialFormat()\n{\n    char[] text = new char[6];\n    char[0] = RandomLetter();\n    char[1] = RandomDigit();\n    char[2] = RandomLetter();\n    char[3] = RandomDigit();\n    char[4] = RandomLetter();\n    char[5] = RandomDigit();\n    return new string(text);\n}	0
13501591	13501458	Compare objects loaded from different assemblies	public bool Equals(Type t1, Type t2)\n{\n    var t1Constructors = t1.GetConstructors();\n    var t2Constructors = t2.GetConstructors();\n    //compare constructors\n    var t1Methods = t1.GetMethods();\n    var t2Methods = t2.GetMethods();\n    //compare methods\n    //etc.\n}	0
410446	340568	Suggestions for a cheap/free .NET library for doing Zip with AES encryption?	using (ZipFile zip = new ZipFile())\n  {\n    zip.AddFile("ReadMe.txt"); // no password for this entry\n\n    // use a password for subsequent entries\n    zip.Password= "This.Encryption.is.FIPS.197.Compliant!";\n    zip.Encryption= EncryptionAlgorithm.WinZipAes256;\n    zip.AddFile("Rawdata-2008-12-18.csv");\n    zip.Save("Backup-AES-Encrypted.zip");\n  }	0
31156923	31156416	Comparing times with LINQ to sql dynamically	var wdStart = TimeSpan.FromHours(8.5);\nvar wdEnd = TimeSpan.FromHours(17.25);\n\nvar result = elementsOturums.Where(t => t.EntryTime.HasValue)\n    .Where(t => t.EntryTime.Value.TimeOfDay >= wdStart\n             && t.EntryTime.Value.TimeOfDay <= wdEnd);	0
14283844	14257496	FreeAgent API (OAuth) From c#	req.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17";	0
6456836	6452409	How to show Double grouped report	Color    size    week    amt\n\nBlack      x       1      1\nBlack      x       2      2\nBlack      x       3      3\nwhite      xx      1      1    \nwhite      xx      2      1\nwhite      xx      3      0\nyellow     large   1      2\nyellow     large   2      1\nyellow     large   3      0	0
24752434	24752341	How to have text with bold and normal words for same label?	using (Graphics g = Graphics.FromImage(pictureBox1.Image))\n    {\n\n        Font drawFont = new Font("Arial", 12);\n        Font drawFontBold = new Font("Arial", 12, FontStyle.Bold);\n        SolidBrush drawBrush = new SolidBrush(Color.Black);\n\n        // find the width of single char using selected fonts\n        float CharWidth = g.MeasureString("Y", drawFont).Width;\n\n        // draw first part of string\n        g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200));\n        // now get the total width of words drawn using above settings\n        float widthFirst = ("this is normal").Length() * CharWidth;\n\n        // the width of first part string to start of second part to avoid overlay\n        g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f + widthFirst, 250f, 647, 200));\n    }	0
9674214	9673872	Explanation of Josh Smith Article	class Foo\n{\n   private static int f;\n\n   private class Bar  // nested class\n   {\n       void B() \n       { \n          int b = f;  // access to private member of containing class\n       }\n   }\n}	0
15974767	15973264	Translating a batch with java commands for xml to C#	string commandLine = "-Xmx1224m -classpath .\xalan.jar org.apache.xalan.xslt.Process -IN  In.xml -XSL Convert.xslt -OUT Out.xml";\nSystem.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(commandLine);\nprocStartInfo.WorkingDirectory = @"C:\Program Files (x86)\Java\jre7\bin\java";\nprocStartInfo.RedirectStandardOutput = true;\nprocStartInfo.UseShellExecute = false;\nprocStartInfo.CreateNoWindow = true;\nSystem.Diagnostics.Process proc = new System.Diagnostics.Process();\nproc.StartInfo = procStartInfo;\nproc.Start();\nstring result = proc.StandardOutput.ReadToEnd();\nConsole.WriteLine(result);	0
25186123	25166948	Check input of DataGridView cell while writing	private void dgUpitnik_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n    {\n        dgUpitnik.Rows[e.RowIndex].ErrorText = "";\n        int newInteger;\n\n        if (e.ColumnIndex == 2)\n        {\n            if (dgUpitnik.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)\n            {\n                if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger > 3)\n                {\n                    e.Cancel = true;\n                    dgUpitnik.Rows[e.RowIndex].ErrorText = "Ocjena mora biti u rasponu od 0 do 3!";\n                }\n            }\n        }\n    }	0
4824695	4824669	C# extracting value from string	Regex.Match(s, @"(?<=/test\.php\?aed=)[^""&]+").Value	0
19509044	19509010	Need help to get DataColumn of a DataTable	DataColumn dc = dt.Columns["YourColumnName"];	0
3901845	3901805	How to use C# object from F#?	open MyMath\nlet arith = Arith() // create instance of Arith\nlet x = arith.Add(10, 20) // call method Add	0
28369863	28368784	Keep focus on a row after DataGrid.ItemsSource changed	public void UpdateItemsSource()\n{\n    IdentifySelectedError(); //get "selectedRowIndex"\n    using (var context = new Context())\n    {\n        DataGrid.ItemsSource = context.Error.Take(100).ToList();\n    }\n    MainDataGrid.SelectedItem = MainDataGrid.Items[indexOfRow];\n    MainDataGrid.ScrollIntoView(MainDataGrid.Items[indexOfRow]);\n}	0
21552238	21552008	Best way to find all values of two variables that have a certain sum	var sum = 99999999;\nvar max = 60000000;\nvar min = 10000000;\n\nvar i = max;\nvar j = sum - max;\n\nvar result = new List<Tuple<int, int>>();\nwhile (j >= min && j =< max)\n{\n    result.Add(new Tuple<int, int>(i, j));\n    i--;\n    j++;\n}	0
16060176	16060089	Regexp find the number with start number 8	var input= "hello world, the number i want call is 84553741. help me plz.";\nvar matches = Regex.Matches(input, @"(?<!\d)8\d*");\nIEnumerable<String> numbers = matches.Cast<Match>().Select(m=>m.Value);\nforeach(var number in numbers)\n{\n    Console.WriteLine(number);\n}	0
26914686	26912757	How do I escape a single quote using C# string.Replace to use in HighCharts?	strDescription = reader1.GetString(0).Replace("'", "\\'");	0
1042986	1036713	Automatically start a Windows Service on install	public ServiceInstaller()\n{\n    //... Installer code here\n    this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);\n}\n\nvoid ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)\n{\n    using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))\n    {\n         sc.Start();\n    }\n}	0
12179927	12179879	Two ways of declaring properties in VB - what is the difference?	public string UserName { get; set; }	0
2457135	2457063	String format or REGEX	var pattern = @"^(\(x[+-]\d+(\.\d+)?\)){2}$";\nvar input = "(x-0.123)(x+5)";\nvar result = System.Text.RegularExpressions.Regex.IsMatch(input, pattern);\n\nif (result) { \n  Console.Write("YAY IT MATCHES");\n}	0
29100130	29100007	How to use foreach if iterating collection is changed in this loop?	foreach(myClass obj in myList.ToArray())\n{\n      ...\n}	0
25831244	25831225	how to avoid bypass SQL server injection	var query = "SELECT * FROM employ WHERE name = @name AND Snumber = @number";\nSqlCommand cmd = new SqlCommand(query, cn);\ncmd.CommandType = CommandType.Text;\ncmd.Parameters.AddWithValue("@name",  textBox1.Text);\ncmd.Parameters.AddWithValue("@number",  textBox2.Text);\nda = new SqlDataAdapter(cmd);\nda.Fill(dt);\n...	0
16360456	16360381	Can a Form be used as a user control?	YourFormClassName FormForUser = new YourFormClassName();\nFormForUser.Show();\nFormForUser.ShowDialog();	0
3804816	3804784	C#: Is it possible to get the index of a DropDownItem in a menu item?	private void item_Click(object sender, EventArgs e)\n{\n    ToolStripMenuItem item = sender as ToolStripMenuItem;\n    if (item != null)\n    {\n        int index = (item.OwnerItem as ToolStripMenuItem).DropDownItems.IndexOf(item);\n    }\n}	0
6608121	6608080	convert from GPS week number,time of week to datetime	DateTime GetFromGps(int weeknumber, int seconds)\n{\n    DateTime datum = new DateTime(1980,1,6,0,0,0);\n    DateTime week = datum.AddDays(weeknumber * 7);\n    DateTime time = week.AddSeconds(seconds);\n    return time;\n}	0
9325593	9320854	Custom Buttons in C# WinForms	private void button1_MouseLeave(object sender, EventArgs e)\n    {\n        this.button1.Image = Properties.Resources._default;\n    }\n\n    private void button1_MouseEnter(object sender, EventArgs e)\n    {\n        this.button1.Image = Properties.Resources._hover;\n    }        \n\n    private void button1_MouseDown(object sender, MouseEventArgs e)\n    {\n        this.button1.Image = Properties.Resources._clicked;\n    }\n\n    private void button1_MouseUp(object sender, MouseEventArgs e)\n    {\n        this.button1.Image = Properties.Resources._default;\n    }	0
22763780	22757188	Open files with mono gtk# on Mac OSX	ApplicationEvents.OpenDocuments+= delegate (object sender, ApplicationDocumentEventArgs e) {\n    if (e.Documents != null && e.Documents.Count > 0) {\n        // e.Documents holds the files\n    }\n    e.Handled = true;\n};	0
22791928	22791906	Splitting string on unique partrs, sort and concatenate again	Console.WriteLine(string.Join(",",myStr.Split(',').Distinct().OrderBy(x=>x)));	0
32817685	32817607	How add NLog Class Library project in other projects	NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration( "<your path>" + "\\NLog.config", true);	0
26533500	26228134	Sitefinity related items and DynamicContent with Babaganoush model	// Single related item\nvar sfEvent = sfContent.GetOriginal().GetRelatedItems<Event>("Event").FirstOrDefault();\nif (sfEvent != null)\n{\n    Event = new EventModel(sfEvent);\n}\n\n// List of related items\nSessions = sfContent.GetOriginal().GetRelatedItems<DynamicContent>("Sessions")\n    .Select(x => new SessionModel(x))\n    .ToList();	0
2137021	2137000	Use SMO to locate a backup file to restore	exec xp_dirtree 'c:\sqlbackups\', 1, 1	0
6264960	6264909	How to override default(int?) to obtain NULL instead 0	GetValue<int?>(value);	0
86341	86292	How to check for valid xml in string input before calling .LoadXml()	public class MyXmlDocument: XmlDocument\n{\n  bool TryParseXml(string xml){\n    try{\n      ParseXml(xml);\n      return true;\n    }catch(XmlException e){\n      return false;\n    }\n }	0
9096371	8236060	How Can I Retrieve All XmlEntityReference Objects In An XmlDocument Object?	XmlTextReader reader = new XmlTextReader(stream);\nreader.EntityHandling = EntityHandling.ExpandCharEntities;\nXmlDocument doc = new XmlDocument();\ndoc.Load(reader);\n\nList<XmlEntityReference> entityRefs = new List<XmlEntityReference>();\nRetrieveEntityRefs(doc.DocumentElement, doc, entityRefs);\n\nprivate void RetrieveEntityRefs(XmlNode parentNode, XmlDocument doc, List<XmlEntityReference> entityReferences) {\n    foreach (XmlNode node in parentNode.ChildNodes)\n    {\n        if (node.NodeType == XmlNodeType.EntityReference) {\n            XmlEntityReference entityRef = node as XmlEntityReference;\n            entityReferences.Add(entityRef);\n        }\n        else if (node.HasChildNodes) {\n            RetrieveEntityRefs(node, doc, entityReferences);\n        }\n    }\n}	0
9311317	9299884	Adding row to binded datagridview	DataRow newRow =test.Tables[0].NewRow();\n\n\nnewRow.ItemArray = Cache.getRowValues(child);\n test.Tables[0].Rows.InsertAt(newRow, c.Index+1);\n\n public string[] getRowValues(int index)\n        {\n            List<string> temp = new List<string>();\n            foreach (KeyValuePair<int, CustomDataGridViewRow> dic in _cache)\n            {\n                if (dic.Key == index)\n                {\n                    foreach (DataGridViewCell cell in dic.Value.Cells)\n                        temp.Add(cell.Value.ToString());\n                }\n            }\n            string[] result = temp.ToArray();\n\n            return (result);\n        }	0
5266441	5266230	VSTO/Word: How to freeze a document window?	Sub YourSub()\n    Application.ScreenUpdating = False\n    'do your thing\n     Application.ScreenUpdating = True\nEnd Sub	0
9936788	9936698	Preventing registry entry code from requiring admin previliges	RegistryKey startupapp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n\nstartupapp.SetValue("App", "\"" + Assembly.GetExecutingAssembly().Location + "\"" +" -start");	0
20555222	20555028	Implementing an ICollection<ISomething> with a concrete type to satisfy Entity Framework	public interface IFoo\n{\n    IEnumerable<IBar> Bars { get; }\n}\n\npublic class Foo : IFoo\n{\n    public virtual ICollection<Bar> Bars { get; set; }\n    IEnumerable<IBar> IFoo.Bars\n    {\n       return this.Bars;\n    } \n}	0
25757859	25757437	C# replace in long variable	var a = 10000000L;\nvar pows = Enumerable.Range(0, 16).Select(x => (long)Math.Pow(10, x));\nvar d = pows.First(x => a / x == 0);\nvar thirdDigit = (a / (d / 1000)) % 100;\na += (long)((3 - thirdDigit) * (d / 1000));	0
10755981	10755924	How can I access the Header information from a HTTP Post in C#?	Request.Headers	0
8891740	8891717	Get out of multiple loops?	return;	0
812272	812232	how to load a hashtable from a simple xml file using xmltextreader	// Load the whole document into memory, as an element\nXElement root = XElement.Load(xmlReader);\n\n// Get a sequence of users\nIEnumerable<XElement> users = root.Elements("user");\n\n// Convert this sequence to a dictionary...\nDictionary<string, string> userMap = users.ToDictionary(\n      element => element.Attribute("name").Value, // Key selector\n      element => element.Value);                 // Value selector	0
25334890	25334776	Making a static object method call itself at a set interval	using System;\nusing System.Timers;\n\npublic static class TheStaticObject\n{\n    private static Timer _timer;\n\n    public static void InitializeTheObject()\n    {\n        _timer = new Timer\n        {\n            AutoReset = true,\n            Interval = TimeSpan.FromMinutes(10).TotalMilliseconds\n        };\n\n        _timer.Elapsed += RunEvery10Minutes;\n        _timer.Start();\n    }\n\n    public static void RunEvery10Minutes(object sender, ElapsedEventArgs e)\n    {\n        // do something\n    }\n}	0
19964371	19964221	How to cast selectedvalue of combobox to an integer?	int fid;\nbool parseOK = Int32.TryParse(comboBox_Degree.SelectedValue.ToString(), out fid);	0
23841766	23841737	Manipulate data in model	/// <summary>\n/// Gets actual percentage.\n/// </summary>\npublic decimal DisplayPercentage\n{\n    get\n    {\n        return (this.Percentage / 100);\n    }\n}	0
26525373	26525187	Deserialize XML does not populate array	public class TaskItem\n{\n    public string Name { get; set; }\n    public string Instruction { get; set; }\n    public bool IsTlc { get; set; }\n}\n\n[XmlRoot("TaskList")]\npublic class TaskList\n{\n    public string Name { get; set; }\n    public string Revision { get; set; }\n    public bool Optional { get; set; }\n\n    [XmlArray("TaskItems")]\n    [XmlArrayItem("TaskItem")]\n    public List<TaskItem> TaskItems { get; set; }\n}	0
3237705	3237597	Add Ellipse Position within Canvas	Canvas.SetTop(el2, 100);\nCanvas.SetLeft(el2, 100);	0
7707748	7707705	How to return a byte[] to C# in C++ CLR	array<System::Byte>^	0
11327819	11322713	How much capacity should a static hash table have to minimize collisions?	hash = <31 bit hash code>\npr = <least prime number greater than or equal to current dictionary capacity>\nbucket_index = hash modulus pr	0
15308441	15308166	Simulating CTRL+C with Sendkeys fails	Thread.Sleep(1000);	0
13536606	13536535	Using FileSystemWatcher in detecting a xml file, using Linq in reading the xml file and prompt the results error "Root Element is Missing"	Thread.Sleep(100);	0
24613884	24592858	how to Insert update delete mysql database from datagridview	this.id = string.Empty;\n using (MySqlConnection mysqlConn = new MySqlConnection(this.connString))\n {\n   string mysqlQuery = @"SELECT * from Student";\n   using (MySqlDataAdapter ad = new MySqlDataAdapter(mysqlQuery, this.connString))\n     {\n       DataSet ds = new DataSet();\n       ad.Fill(ds);\n       dgvStudentDelete.DataSource = ds.Tables[0];\n     }\n }	0
8665434	3392268	How can I bind an asp:chart (from microsoft) to a Dictionary<string,string>?	var employees = new Dictionary<int, string>\n{\n    {10,"Employee 1"},{20,"Employee 2"},{30,"Employee 3"}\n};\n\nChart1.Series[0].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Bar;\n\nforeach (KeyValuePair<int, string> employee in employees)\n    Chart1.Series[0].Points.AddXY(employee.Value, employee.Key);	0
9976137	9975828	Singleton implementation for VSTO/COM	public sealed class WordSingleton \n{     \n\n  public static readonly Word.Application Instance = new Word.Application();      \n\n  private WordSingleton() { } \n\n}	0
15481887	15394815	How to read a text file in blocks to return specific lines	static void Main(string[] args)\n    {\n        ReadFile();\n    }\n\n    private static void ReadFile()\n    {\n        StreamReader SR = new StreamReader(@"C:\Users\bharrison\Desktop\test.txt");\n        Console.WriteLine("Reading file");\n        while (!SR.EndOfStream)\n        {\n           string ReturnedValue = AnalyzeString(SR.ReadLine());\n           Console.WriteLine(ReturnedValue);\n        }\n        Console.ReadLine();\n    }\n\n    private static string AnalyzeString(string line)\n    {\n        string TempLine = line;\n\n        if (TempLine != null && TempLine != "")\n        {\n\n            if (TempLine.Contains("source"))\n            {\n                return TempLine;\n            }\n\n            if (TempLine.Contains("MRU"))\n            {\n                return TempLine;\n            }\n\n            if (TempLine.Contains("MRU Time"))\n            {\n                return TempLine;\n            }\n        }\n        else\n        {\n            return " ";\n        }\n        return " ";\n    }	0
4084677	4084499	Best way to Architect Azure Worker Role to Process Data from ~10 Queues	while(true)\n{\n   var msg = q1.GetMessage();\n   if (msg != null) { ... }\n   msg = q2.GetMessage();\n   if (msg != null) { ... }\n}	0
11815332	11814069	how to copy a file from application bundle to documents directory in ios using monotouch	string docPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);	0
28050288	28049817	Trying to make sense of how to use method in a little different use case	for (int i = 0; i < 100; i++)\n{\n    Task<SomeClass> task = SomeMethod(param);\n    await task;\n\n    // if get back something useful then set tasks[i] to this task\n    task[i] = task;\n}	0
20888928	20885833	Task Scheduler Not Launching Excel in Application	Directory.GetCurrentDirectory()	0
26921937	26921725	Linq to XML - Trying to select multiple nodes	var doc = XDocument.Parse(xmlString);\nvar groups = doc.Descendants("SECTION").Elements().Where(e => e.Name.LocalName.StartsWith("GROUP"));\nConsole.Write(groups.Count());	0
2871496	2871480	.NET regex inner text between td, span, a tag	var doc = new HtmlDocument();\ndoc.LoadHtml("...your sample html...");\n\n// all <td> tags in the document\nforeach (HtmlNode td in doc.DocumentNode.SelectNodes("//td")) {\n    Console.WriteLine(td.InnerText);\n}\n\n// all <span> tags in the document\nforeach (HtmlNode span in doc.DocumentNode.SelectNodes("//span")) {\n    Console.WriteLine(span.InnerText);\n}\n\n// all <a> tags in the document\nforeach (HtmlNode a in doc.DocumentNode.SelectNodes("//a")) {\n    Console.WriteLine(a.InnerText);\n}	0
29895755	29895657	C# remove an int from a List<int>	list.RemoveAll(item => item == 1);	0
10284402	10284373	Method parameter type to pass a lambda expression prior to execute	base.CommonExecute(Action lambdaExpression )\n{\n    _commandObjectFromThirdPartyLibrary.Execute( lambdaExpression );\n}	0
1816872	1816859	Using conditional operator in lambda expression in ForEach() on a generic List?	items.ForEach(item => {\n    if (item.Contains("I Care About")) \n        whatICareAbout += item + ", ";\n});	0
18595741	18595337	Mixing two linq statement into one?	var result = list3.Where(obj => {\n                              var dt = DateTime.ParseExact(obj.LeftColumn, dateFormat, CultureInfo.InvariantCulture);\n                              return (list4.Any(x => x == obj.Srodek.category1) &&\n                              (obj.Srodek.Source.Device == _text || obj.Srodek.ID.Device == _text)) ||\n                              (dt >= czas11 && dt <= czas22);})       \n                  .ToList();	0
15618161	15615209	How do you add imaginary tokens for a separated ANTLR lexer & parser?	tokens{}	0
3750986	3750937	Cast versus parse	object variable = 1234;	0
14292628	14292533	How to find numbers in List with condition?	var indexes = lifeField.Select((x,i) => new {Index = i, Element = x})\n    .Where(x => \n        ((x.Element % (10 * currentMove)) == 1) || \n        ((x.Element % (10 * currentMove)) == 2))\n    .Select(x => x.Index)\n    .ToList();	0
4441891	4441537	Create an array of arrays with Linq	var xmlStr = "<table><dataRow><dataCol>1</dataCol><dataCol>2</dataCol></dataRow><dataRow><dataCol>5</dataCol><dataCol>6</dataCol></dataRow></table>";\nvar rows = from r in XElement.Parse(xmlStr).Elements("dataRow") select r;\n\nint[][] intJagArray = (from r in rows select (from c in r.Elements("dataCol") select Int32.Parse(c.Value)).ToArray()).ToArray();	0
5838907	5838811	Deserializing JSON result with Json & JavaScriptSerializer	var result = JsonConvert.DeserializeObject<getAvailableHotelResponse>(json);\n\npublic class getAvailableHotelResponse\n{\n    public int responseId;\n    public availableHotel[] availableHotels;\n    public int totalFound;\n    public string searchId;\n}\n\npublic class availableHotel\n{\n    public string processId;\n    public string hotelCode;\n    public string availabilityStatus;\n}	0
24714361	22715958	How to do ASP.NET Web API integration tests with custom authentication and in-memory hosting	request.GetRequestContext().Principal = principal;	0
25352551	25352493	List of variables(XML) in combo box C#	foreach(var item in collection)\n    Combobox.Items.add (item)	0
8362947	8362835	Web Service built in C# to retrieve data from mySQL database	[System.Web.Services.WebMethod]\npublic DataTable connectoToMySql()\n{\n    string connString = "SERVER=localhost" + ";" +\n        "DATABASE=testdatabase;" +\n        "UID=root;" +\n        "PASSWORD=password;";\n\n    MySqlConnection cnMySQL = new MySqlConnection(connString);\n\n    MySqlCommand cmdMySQL = cnMySQL.CreateCommand();\n\n    MySqlDataReader reader;\n\n    cmdMySQL.CommandText = "select * from testdata";\n\n    cnMySQL.Open();\n\n    reader = cmdMySQL.ExecuteReader();\n\n    DataTable dt = new DataTable();\n    dt.Load(reader);\n\n\n    cnMySQL.Close();\n\n    return dt;\n}	0
1405316	1405219	Is there any way to get newly added rows in datagridview?	public Form1()\n    {\n        InitializeComponent();\n        this.dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);\n    }\n\n    private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)\n    {\n        DataGridViewRow newRow = this.dataGridView1.Rows[e.RowIndex];\n    }	0
23810386	23810227	How to overload ! operator for an enum?	public static Direction Not(this Direction direction) {\nswitch (direction) {\n        case Direction.Left: return Direction.Right;\n        case Direction.Right: return Direction.Left;\n        case Direction.Up: return Direction.Down;\n        default: return Direction.Up;\n    }\n}	0
5665267	5662546	How can I change Skype user status from online to away using skype4com?	var skype = new Skype();\nskype.Attach(5, true);\nskype.ChangeUserStatus(TUserStatus.cusAway);	0
2007441	2007429	Inherit from a generic base class, apply a constraint, and implement an interface in C#	class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar\n{\n    ...\n}	0
10492146	10492076	Reading custom control properties returns 0 in a constructor	public void RemakeGrid()\n{\n    this.ClearGrid();\n\n    for(int c = 0; c < this.Columns; ++c)\n    {\n        for(int r = 0; r < this.Rows; ++r)\n        {\n            HexCell h = new HexCell();\n            h.Width = 200;\n            h.Height = 200;\n            h.Location = new System.Drawing.Point(c*200, r*200);\n            this.Controls.Add(h);\n        }\n    }\n}\n\nprivate int m_rows;\n\n[Browsable(true), DescriptionAttribute("Hexagonal grid row count."), Bindable(true)]\npublic int Rows\n{\n    get\n    {\n        return m_rows;\n    }\n    set\n    {\n        m_rows = value;\n        this.RemakeGrid();\n    }\n}\n\n// Same goes for Columns...	0
26260044	26258196	Wrong encoding in ZipFile comment	using (ZipFile zipFile = new ZipFile(path))\n{\n  byte[] bytes = Encoding.GetEncoding(437).GetBytes(zipFile.Comment);\n  comment = Encoding.Default.GetString(bytes);\n}	0
7178769	7178510	WPF TPL Restart a canceled Task	private void Start_Click(object sender, RoutedEventArgs e)\n{\n    cts = new CancellationTokenSource();           \n    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();\n    CancellationToken token = cts.Token;\n...	0
7316406	7316083	Extending the Oulook 2010 attachment context menu	var attachmentSelection = (control.Context as AttachmentSelection).OfType<Attachment>();	0
5479135	5478984	TreeView with CheckBoxes in c#	bool busy = false;\n\n    private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {\n        if (busy) return;\n        busy = true;\n        try {\n            checkNodes(e.Node, e.Node.Checked);\n        }\n        finally {\n            busy = false;\n        }\n    }\n\n    private void checkNodes(TreeNode node, bool check) {\n        foreach (TreeNode child in node.Nodes) {\n            child.Checked = check;\n            checkNodes(child, check);\n        }	0
31080217	31079658	how to reset counter when objetive is reached	idx = i++ % 12	0
6606286	6606020	Set credentials for Entity Framework in code, without using Integrated Security and only storing User ID in config file	EntityConnection entityConnection = (EntityConnection)context.Connection;\nentityConnection.StoreConnection.ConnectionString = "YourConnectionString";	0
14112473	14112432	list finding with 2 list	var inx = aaa.IndexOf("2");\nif (inx >= 0)\n{\n    var result = bbb[inx];\n}	0
27456776	27245392	WCF Custom Authorization	message inspector	0
2411374	2411346	How do I add functionality to a winforms program in C#?	TextBox1.Text = "Hello World!";	0
18382862	18382747	How to remove specific url parameter in Regex?	string originalUri = "http://www.example.org/etc?query=string&query2=&query3=";\n\n// Create the URI builder object which will give us access to the query string.\nvar uri = new UriBuilder(originalUri);\n\n// Parse the querystring into parts\nvar query = System.Web.HttpUtility.ParseQueryString(uri.Query);\n\n// Loop through the parts to select only the ones where the value is not null or empty  \nvar resultQuery = query.AllKeys\n                       .Where(k => !string.IsNullOrEmpty(query[k]))\n                       .Select(k => string.Format("{0}={1}", k, query[k]));\n\n// Set the querystring part to the parsed version with blank values removed\nuri.Query = string.Join("&",resultQuery);\n\n// Done, uri now contains "http://www.example.org/etc?query=string"	0
10841459	10365458	Write variable shortcut	protected void Page_Init(object sender, EventArgs e)\n{ \n    HtmlLink css = new HtmlLink();\n    css.Href = String.Format("{0}/css/style.css", GlobalVar.BasePath);\n    css.Attributes["rel"] = "stylesheet";\n    css.Attributes["type"] = "text/css";\n    css.Attributes["media"] = "all";\n    Page.Header.Controls.Add(css); \n}	0
9319609	9319532	Return value from SQL Server Insert command using c#	using (var con = new SqlConnection(ConnectionString)) {\n    int newID;\n    var cmd = "INSERT INTO foo (column_name)VALUES (@Value);SELECT CAST(scope_identity() AS int)";\n    using (var insertCommand = new SqlCommand(cmd, con)) {\n        insertCommand.Parameters.AddWithValue("@Value", "bar");\n        con.Open();\n        newID = (int)insertCommand.ExecuteScalar();\n    }\n}	0
24110984	24107141	How to convert html into doc without losing paragraphs?	string yeni = nodlar.Replace("<p>", "    ").Replace("</p>","\n");\n           yeni = System.Text.RegularExpressions.Regex.Replace(yeni, "<div(.*)</div>", string.Format(""));\n           yeni = System.Text.RegularExpressions.Regex.Replace(yeni, "<div(.*)</a>", string.Format(""));\n            yeni = Regex.Replace(yeni, @"<[^>]*>", String.Empty);	0
8747040	8746762	Unit-testing of a constructor	[TestMethod]\n[ExpectedException(typeof(ArgumentNullException))]\npublic void Cannot_Create_Passing_Null()\n{\n   new Triangle(null);\n}\n[TestMethod]\n[ExpectedException(typeof(ArgumentException))]\npublic void Cannot_With_Less_Than_Three_Points()\n{\n   new Triangle(new[] { new Point(0, 0), new Point(1, 1) });\n}\n[TestMethod]\n[ExpectedException(typeof(ArgumentException))]\npublic void Cannot_Create_With_More_Than_Three_Points()\n{\n   new Triangle(new[] { new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3) });\n}\n[TestMethod]\n[ExpectedException(typeof(ArgumentException))]\npublic void Cannot_Create_With_Two_Identical_Points()\n{\n   new Triangle(new[] { new Point(0, 0), new Point(0, 0), new Point(1, 1) });\n}\n[TestMethod]\n[ExpectedException(typeof(ArgumentException))]\npublic void Cannot_Create_With_Empty_Array()\n{\n   new Triangle(new Point[] { });\n}	0
9378206	9377136	Coding for a selected item in listView	void listView1_MouseDoubleClick(Object^  sender, MouseEventArgs^  e) \n{\n     ListViewItem^ item = this->listView1->GetItemAt(e->X, e->Y);\n}	0
11637813	11637772	Extracting phrases from a string	int last = source.IndexOf(end-keyword, first + start-keyword.Length ) \n           + end-keyword.Length;	0
17262541	17262517	Finding average file size in MB in given directory	string filePath = @"DesiredFilePath";\n           var getFiles = Directory.GetFiles(filePath);\n           var avg = getFiles.Select(f =>\n                           new FileInfo(f).Length).Average();\n\n           Console.WriteLine("The Average file size in {0} directory is {1} MB",\n            filePath,Math.Round(avg/1048576,1));	0
7927970	7927950	To open exe of SQL Server Management Studio	System.Diagnostics.Process.Start("IExplore.exe");//change this to path of your exe file	0
32754915	32753805	Retrieve all mobile devices Google Directory API in .NET Application	var listReq1 = service.Mobiledevices.List(customerId);\nMobileDevices allUsers = listReq1.Execute();	0
967782	924449	How to create a simple c# http monitor/blocker?	class Program\n{\n    static void Main(string[] args)\n    {\n        try\n        {\n            byte[] input = BitConverter.GetBytes(1);\n            byte[] buffer = new byte[4096];\n            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);\n            s.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.91"), 0));\n            s.IOControl(IOControlCode.ReceiveAll, input, null);\n\n            int bytes = 0;\n            do\n            {\n                bytes = s.Receive(buffer);\n                if (bytes > 0)\n                {\n                    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));\n                }\n            } while (bytes > 0);\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex);\n        }\n    }\n}	0
30644568	30644054	Invalid input - format string ASP.NET	using (SqlConnection edytuj = new SqlConnection("Data Source=MICHA??-KOMPUTER;Initial Catalog=ProjektNet_s10772;Integrated Security=True"))\nusing (SqlCommand cmd = new SqlCommand("Update Klient SET Imie=@imie, Nazwisko=@nazwisko, Adres_Email=@email, Telefon=@telefon, Miasto=@miasto WHERE Klient_ID=@id", edytuj))\n{\n\n    cmd.Parameters.AddWithValue("@imie", txtimie2.Text);\n    cmd.Parameters.AddWithValue("@nazwisko", txtNazwisko.Text);\n    cmd.Parameters.AddWithValue("@email", txtemail2.Text);\n    cmd.Parameters.AddWithValue("@telefon", txttelefon2.Text);\n    cmd.Parameters.AddWithValue("@miasto", txtmiasto2.Text);\n    cmd.Parameters.AddWithValue("@id", ""); //set proper id\n    cmd.ExecuteNonQuery();\n    GridView3.DataBind();\n}	0
26650683	26646546	How to add a third party DLL to a CSharp Project using Roslyn?	NameSyntax name = SyntaxFactory.IdentifierName("your namespace");\n UsingDirectiveSyntax obj = SyntaxFactory.UsingDirective(name);\n var newusing = newDocRoot.Usings.Add(obj);\n root = root.WithUsings(newusing);	0
29357837	29339330	ADO.NET TableAdapter Updating on CellValueChanged Event for a DataGridView	private void uiPersonGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n{\n    if (uiPersonGridView.IsCurrentCellDirty)\n    {\n        uiPersonGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);\n           DataRowView drv = uiPersonGridView.CurrentRow.DataBoundItem as DataRowView;\n            drv.Row.SetModified();\n    }\n}	0
12735382	12734899	Application settings fom custom XML file, loading and error-handling	XmlDocument doc = new XmlDocument();\ndoc.Load("Settings.xml");\nappSettings.LogType = doc.SelectSingleNode("/appSettings/configuration/API/log/type").InnerText;	0
2637190	2636371	WPF c# Listbox external scrollbuttons	private void buttonUp_Click(object sender, RoutedEventArgs e) {\n   if (listBox1.SelectedIndex > 0) \n     listBox1.SelectedIndex--;\n   listBox1.ScrollIntoView(listBox1.SelectedItem);\n\n  }\n\n  private void buttonDown_Click(object sender, RoutedEventArgs e) {\n   if (listBox1.SelectedIndex < listBox1.Items.Count - 1) \n     listBox1.SelectedIndex++;\n   listBox1.ScrollIntoView(listBox1.SelectedItem);\n  }	0
20814180	20814046	How can I obtain a vertical bar that fills, like a progress bar?	using System;\nusing System.Windows.Forms;\n\nclass VerticalProgressBar : ProgressBar {\n    protected override CreateParams CreateParams {\n        get {\n            var cp = base.CreateParams;\n            cp.Style |= 4;   // Turn on PBS_VERTICAL\n            return cp;\n        }\n    }\n}	0
31170667	31170263	Handling similar checkbox values in .NET Web App	List<char> errorList = new List<char>();\nint totalErrors = 13; //change accordingly\nchar[] errorId = new char['M', 'S', 'T', 'P', 'O', 'V', 'C', 'W', 'U', 'A', 'I', 'D', 'B'];\nfor(int i = 0; i < totalErrors; i++)\n{\n    string controlId = "error" + i.ToString();\n    Control errorButton = FindControl(controlId);\n    if(errorButton.Checked)\n         errorList.add(char[i]);\n}	0
25368163	25368036	Passing GUID to WebMethod from jQuery	[System.Web.Services.WebMethod()]\npublic static string SaveLike(string ID)\n{\n    //\n    ActivityFeed.clsFeed objAF = new ActivityFeed.clsFeed();\n    ActivityFeed.clsFeeds objAFS = new ActivityFeed.clsFeeds();\n    int i;\n    string oLikes = "";\n    string oSTR;\n\n    objAF = new ActivityFeed.clsFeed();\n    objAF.SubFeedItemID = ID_IN;\n    objAF.SubFeedEmployeeID = HttpContext.Current.Session["globalEmpID"].ToString();\n    objAF.SubFeedIndicatorID = 1;\n    objAF.SubFeedComment = "";\n    objAF.SubFeedItemDate = DateTime.Now;\n    objAF.SaveActivityFeedLike();\n}	0
32068170	32067881	Linq query require for a join	from e in context.IB_Right_Master\nwhere  !(from e2 in context.IB_Group_Rights\n     where e2.GroupID == 3\n     select e2.RightID).ToList().Contains(e.id)\nselect e;	0
27208133	27208041	C# Update label from static method	Dispatcher.BeginInvoke(new Action(() => \n    lblFreeSize.Text = string.Format(\n        "Free size: {0}", Helper.SizeSuffix(App.free_space.arguments.sizebytes)))));	0
6648752	6648724	How to connect to the connection string written in the web.config of the web services	public string connectionstring\n{\n  get\n  {\n    return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;\n  }\n}	0
9989093	9989049	Use lambda to check if an string value is in string array or List in C#	Names.Contains(target)	0
10741352	10740956	Getting Database Tables in combobox	string CommandText = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_TYPE='Base Table'"\nusing (SqlConnection sqlConn = new SqlConnection(connectionString))\n{\n    sqlConn.Open();\n    SqlCommand sqlCmd = new SqlCommand(CommandText, sqlConn);\n    SqlDataAdapter da = new SqlDataAdapter(sqlCmd);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n}	0
27467431	27467336	Turning off a script from a script in Unity	Behaviour walkScript = (Behaviour)GameObject.FindWithTag ("Player").GetComponent ("CharacterMotor");	0
33026185	33001915	How to Determine Whether C# App Running Under Citrix	0 for console sessions\n1 for ICA sessions\n2 for RDP sessions	0
17377547	17363284	Silverlight - get updated cell content value from a textbox inside a datagrid	private void txtFirstName_KeyUp(object sender, KeyEventArgs e)\n        {\n            List<Users> _lstTemp = dataGrid1.ItemsSource as List<Users>;\n            var selectedrow = dataGrid1.SelectedItem as Users;\n            TextBox _TextFirstName = dataGrid1.Columns[1].GetCellContent(selectedrow) as TextBox;\n\n            (from value in _lstTemp\n             where value.EmailID == selectedrow.EmailID\n             select value).ToList().ForEach(value => value.FirstName = _TextFirstName.Text);\n\n            dataGrid1.ItemsSource = _lstTemp;\n        }	0
4454044	2276613	called generated web test code from console application	public class tester\n{\n   public tester()\n   {\n       //setup timer logic here\n       //..\n       //..\n\n       var ts = new ThreadStart(run);\n       var thread = new Thread(ts);\n       thread.start();\n   } \n\n   public void run()\n   {\n       while (ShouldContinue);\n       {\n           //do nothing execute keep app going\n       }\n   }\n}	0
10455388	10441768	Using a Picture Box as a button, how do I ignore/disable double-click events?	using System;\nusing System.Windows.Forms;\n\nclass MyButton : PictureBox {\n    public MyButton() {\n        this.SetStyle(ControlStyles.StandardDoubleClick, false);\n    }\n}	0
15896468	15883598	Access an XSLT file as resource from same project?	using (var reader = new StringReader(Resources.OrderOverview)) {\n  using (XmlReader xmlReader = XmlReader.Create(reader)) {\n    myXslTransform.Load(xmlReader);\n    myXslTransform.Transform(fileName, arguments, xmlTextWriter);\n  }\n}	0
24998021	24873627	How to get distinct values by using c# MongoCursor?	CommandDocument distinctCmd = new CommandDocument{\n          {"distinct", "capped"},\n          {"query", new BsonDocument("x", 27)},\n          {"key", "x"}            };\n      CommandResult r = database.RunCommand(distinctCmd);	0
126807	126781	C++ union in C#	[StructLayout(LayoutKind.Explicit)] \npublic struct SampleUnion\n{\n    [FieldOffset(0)] public float bar;\n    [FieldOffset(4)] public int killroy;\n    [FieldOffset(4)] public float fubar;\n}	0
11492206	11492197	Regular Expression for any characters between a text	\\Network Interface (.*) \\Bytes Sent/sec	0
87641	87621	How do I map XML to C# objects	xsd.exe dependency1.xsd dependency2.xsd schema.xsd /out:outputDir	0
25488042	25478922	How to trigger event when clicking on a selected tab page header of a tab control	private void tabControl1_MouseDoubleClick(object sender, MouseEventArgs e) {\n        for (int ix = 0; ix < tabControl1.TabCount; ++ix) {\n            if (tabControl1.GetTabRect(ix).Contains(e.Location)) {\n                // Found it, do something\n                //...\n                break;\n            }\n        }\n    }	0
7968321	7950610	Install SQL Server CE database in separate folder [Windows Mobile 6 Smart device ap]	namespace DBTest1 {\n\n  public partial class Form1 : Form {\n\n  const readonly string MYDATABASE = "\\Application Data\\DBTest1\\sqlce.db";\n\n  private void Form1() {\n    InitializeComponent();\n    CreateIfNotThere(DBTest1.Properties.Resources.sqlcedb, MYDATABASE);\n  }\n\n  void CreateIfNotThere(object data, string filename) {\n    if (String.IsNullOrEmpty(filename)) {\n      filename = string.Format(@"{0}{1}{2}",\n      Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),\n      Path.DirectorySeparatorChar, "sqlCe.db");\n    }\n    if (data != null) {\n      byte[] array = (byte[])data;\n      FileInfo file = new FileInfo(filename);\n      if (!file.Exists) {\n        using (FileStream fs = file.Create()) {\n          fs.Write(array, 0, array.Length);\n        }\n      }\n    }\n  }\n  // other code\n}	0
33709563	33708747	Download image from JSON	productname.Text = firstitem["post_title"];\nprice.Text = firstitem["price"] + " ???";\nweight.Text = firstitem["weight"] + "?";\n\nBitmap productImage = GetImageBitmapFromUrl1(firstitem["img_url"]);	0
21342236	21342155	C# Combine Regex Expressions	var elements = string.Split('|');	0
33175611	33033650	How to handle One-to-Many relationship in OData Client?	var Teacher = from c in Container.Teachers\n                      select new\n                      {\n                         Name = c.Name,\n                         FatherName = c.FatherName,\n                         ContactNo = c.ContactNo,\n                         Address = c.Address,\n                         Religion = c.Religion,\n                         CNIC = c.CNIC,\n                         Status = c.Status,\n                         UserName = c.UserName,\n                         //I had made changes in the following code:\n                         Subjects = c.Subjects.Select(s=>s.Subject_Name).FirstOrDefault()\n                      };	0
4268579	4267444	Read Lotus Notes documents and items from NSF file with C#	Domino.NotesDocument doc = col.GetFirstDocument(doc);\nwhile (doc != null) {\n\n     string subject = doc.GetItemValue("subject")[0];\n     string who = doc.GetItemValue("sendto")[0];\n\n     Domino.NotesDocument doc = col.GetNextDocument(doc);\n}	0
3819522	3736972	Using XDocument to create schema ordered XML	// Create a reader for the existing control block\nvar controlReader = controlBlock.CreateReader();\n\n// Create the writer for the new control block\nXmlWriterSettings settings = new XmlWriterSettings {\n    ConformanceLevel = ConformanceLevel.Fragment, Indent = false, OmitXmlDeclaration = false };\n\nStringBuilder sb = new StringBuilder();\nvar xw = XmlWriter.Create(sb, settings);\n\n// Load the style sheet from the assembly\nStream transform = Assembly.GetExecutingAssembly().GetManifestResourceStream("ControlBlock.xslt");\nXmlReader xr = XmlReader.Create(transform);\n\n// Load the style sheet into the XslCompiledTransform\nXslCompiledTransform xslt = new XslCompiledTransform();\nxslt.Load(xr);\n\n// Execute the transform\nxslt.Transform(controlReader, xw);\n\n// Swap the old control element for the new one\ncontrolBlock.ReplaceWith(XElement.Parse(sb.ToString()));	0
17790767	17749384	C# Custom Attribute code -> Look at the field that it was associated with	[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]\npublic class DbFieldAttribute : Attribute\n{\n    private string fieldName = "";\n\n    public DbFieldAttribute() { }\n\n    public DbFieldAttribute(string fieldName)\n    {\n        this.fieldName = fieldName;\n    }\n\n    public string FieldName(PropertyInfo pi)\n    {\n        if (this.fieldName != "") return this.fieldName;\n        else return pi.Name;\n    }\n\n    public string FieldName(FieldInfo fi)\n    {\n        if (this.fieldName != "") return this.fieldName;\n        else return fi.Name;\n    }	0
1422533	1422520	C# with SharpZipLib - Compatibility of SharpZipLib with Winzip and XP?	UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off	0
21214721	21214113	Quest' remarks on getting data from request	StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(1255));	0
1240181	1240135	How to tag an XML DateTime attribute with XmlDateTimeSerializationMode?	public DateTime DateField;\n\n[System.Xml.Serialization.XmlAttribute("DateField")]\nprotected DateTime UtcDateField\n{\n    get\n    {\n        //Convert DateField to UTC\n    }\n\n    set\n    {\n        DateField = //Convert value from UTC\n    }\n}	0
30080325	30080197	Convert to decimal direct	decimal dec = decimal.Parse("153565") / 100;	0
7232283	7231880	i created a modified pacman, how to make him breath fire?	class Mob\n{\n  float XPos;\n  float YPos;\n  float XVel;\n  float YVel;\n}\nList<Mob> EveryThingMovable = new List<Mob>();\n\nvoid GameLoop() //This loop is called 30 times every second... use a timer or whatever, there are far more sophisticated models, but for a first attaempt at a game it's easiest. \n{\n  MoveEverybody(); //make a function that moves everything that can move\n  //Later you will have to add collision detection to stop pacman from moving through walls\n  CollideFireballs(); //Check if a fireball hits the bad guys\n  //More game stuff...\n\n\n\n}\n\nvoid MoveEverybody()\n{\n  foreach(Mob dude in EverythingMovable)\n  { \n     ifDoesntHitWall(dude)\n     {\n       dude.XPos += dude.XVel;\n       dude.YPos += dude.YVel;\n     }\n  }\n}	0
12368825	12368428	Convert array of strings to Dictionary<string, int> c# then output to Visual Studio	string[] arr = new string[] { "Board1", "ISR Count682900312", ... };\n\nvar numAlpha = new Regex("(?<Alpha>[a-zA-Z ]*)(?<Numeric>[0-9]*)");\n\nvar res = arr.ToDictionary(x => numAlpha.Match(x).Groups["Alpha"], \n                           x => numAlpha.Match(x).Groups["Numeric"]);	0
4874031	4873984	How to get distinct with highest value using Linq	var query = yourData\n    .GroupBy(x => x.Name,\n             (k, g) => g.Aggregate((a, x) => (x.Priority > a.Priority) ? x : a));\n\n// and a quick test...\nforeach (var result in query)\n{\n    Console.WriteLine(result.Name + " " + result.Priority);\n}	0
28476964	28476899	c# Linq to entities select case to a string	string str= string\n         .Join(",", grupos.Select(x => x.BLOCKED? x.ID_BLOCKED.ToString() : x.GRP_ID.ToString())\n         .ToArray());	0
5621192	5621161	Change row colour in a datagrid based on the date	datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;	0
22922726	22911694	bug in my Recursive method	public ViewResult Index()\n   {\n       var items = _repo.GetAll().ToList();\n       var categories = items.Select(c => new CategoryViewModel\n       {\n           Id = c.Id,\n           Name = c.Name,\n           Parent = c.Parent.HasValue ? c.Parent.Value : (Guid?) null,\n           Products = c.Product.ToList(),\n           ChildList = new List<CategoryViewModel>()\n       }).OrderBy(o => o.Parent).ToList();\n\n      var sortedCategories = categories.First();\n      sortedCategories.ChildList = categories.Where(o => o.Parent != null && o.Parent == sortedCategories.Id).ToList();\n\n      foreach (var l in categories.Where(l => l.Parent != null))\n      {\n          l.ChildList = categories.Where(o => o.Parent != null && o.Parent == l.Id).ToList();\n      }\n\n       return View(sortedCategories);\n   }	0
17705600	17705525	Some clarity on LINQ/LAMBDA to retrieve data from an intersection table please?	var result = Orders.Where(o => o.OrderItems.Any(oi => oi.ProductId == 100));	0
10118734	10118581	??ow to get 2 to 4 of the object element	Dictionary<string, int> viewBusinesAndCountLeft = grptemp.Take(4).ToDictionary(x => x.BusinessCategoryName, x => x.Count);	0
8657806	8657773	efficient way to search for string in list of string?	HashSet<string>	0
31148502	31148383	Finding numbers in text and displaying them	displayLabel2.Text=(x.ToString().Replace(".","").TrimStart(new Char[] {'0'})+"00").Substring(0,2) ;	0
9401291	8142045	Generic Method, Generic Type, Generic Parameter	public static string Serialize<T>(T o)\n    {\n        eConnectType e = new eConnectType();\n        T[] myMaster = { o };\n\n        // Populate the eConnectType object with the schema object \n        typeof(eConnectType).GetField(typeof(T).Name).SetValue(e, myMaster);\n        return MemoryStreamSerializer(e);\n    }	0
22275005	22274984	using base class in interface	public interface IClass<T> where T : BaseClass\n{\n   T GetValue();\n}\nclass Child: BaseClass, IClass<Child>\n{\n   Child GetValue(); \n}	0
720243	720221	invoke stored procedure in the server side in ASP.net	using (OracleConnection connection = GetConnection)\n{\n  OracleCommand command = new OracleCommand("insert_into_pop");\n  command.Connection = connection;\n  command.CommandType = CommandType.StoredProcedure;\n  command.Parameters.AddWithValue("@Param", value);  // 0 or more parameters passed in here\n  command.ExecuteNonQuery();\n}	0
12619806	12619582	Concatenate various dropdownlists in single date format in an XML file	var date = string.Join("-", drpmm.SelectedItem.Text, \n                            drpdte.SelectedItem.Text,\n                            drpyyyy.SelectedItem.Text)	0
14667965	14666840	What would be the better way of getting linked models values from db	Include("sProfile.Group")	0
24654227	24634524	Chart legend with row style cuts off	crtMain.Legends["Default"].IsTextAutoFit = true;\ncrtMain.Legends["Default"].MaximumAutoSize = 100;	0
11745845	11745714	How to add items to Combobox from Entity Framework?	using (InventoryEntities c = new InventoryEntities(Properties.Settings.Default.Connection))\n    {\n        comboBox1.DataSource    = c.Customers;\n        comboBox1.ValueMember   = "id";\n        comboBox1.DisplayMember = "name";\n    }	0
6902131	6902103	Elegant way to negate a numeric value based on a boolean value	decimal amount = 500m;\nbool negate = true;\n\n// ...\n\nif (negate)\n    amount *= -1;	0
625763	625701	Need help with an Opposite to Inner join Query using LINQ	var query = from c in T1\n            where !(from o in T2 select o.CustomerID)\n            .Contains(c.CustomerID)\n            select c;	0
33693382	33693294	Validation of DateTime against another DateTime	DateTime start = new DateTime(2015, 12, 25);\n  if (start > DateTime.UtcNow.AddDays(28))\n  {\n      // Do something\n  }	0
30897486	30894162	How do I prevent any button click events from queuing until the event handle is finished with the first call	private void button1_Click(object sender, EventArgs e) {\n        button1.Enabled = false;\n        button1.Update();\n        '' long running code\n        ''...\n        Application.DoEvents();\n        if (!button1.IsDisposed) button1.Enabled = true;\n    }	0
2995820	2995766	How to display in a form the next object of a collection?	//on button-click -->i++\nfor(int i=0;i<Products.size();)\n{\n//filling fields --> Products.get(i)\n//reload page\n}	0
32740575	32739708	AutoFixture: how to create polymorphic objects with ISpecimenBuilder	public IX CreateSampleMessage(ISpecimenContext context)\n{\n    var rm = this.types.ElementAt(this.random.Next(0, this.types.Length));\n    return (IX)context.Resolve(rm);\n}	0
13937382	13937198	ConfigurationSection with nullable element	MyElement.ElementInformation.IsPresent	0
28474686	28474321	Get parameters from text file c#	public int getParameter(string data, string param) {\n        var expr = "^" + param + @"=(\d+)\r?$";\n        var match = Regex.Match(data, expr, \n                                  RegexOptions.Multiline | RegexOptions.IgnoreCase);\n         // NB - can remove the option to IgnoreCase if desired\n        return match == null || !match.Success ? default(int) : int.Parse(match.Groups[1].Value);\n    }	0
6304758	6304721	Is it possible to step through the members of a C++ struct?	operator<<	0
5059282	5058412	Mocking method with Action<T> parameter	Action<List<MeetingRoom>> _getRoomsCallback = null;\nIMeetingRoomService _meetingRoomServiceFake;\n\n\nprivate void SetupCallback()\n{\n     Mock.Get(_meetingRoomServiceFake)\n         .Setup(f => f.GetRooms(It.IsAny<Action<List<MeetingRoom>>>()))\n         .Callback((Action<List<MeetingRoom>> cb) => _getRoomsCallback= cb);\n}\n\n[Setup]\npublic void Setup()\n{\n     _meetingRoomServiceFake = Mock.Of<IMeetingRoomService>();\n     SetupCallback();\n}\n\n[Test]\npublic void Test()\n{\n\n      var viewModel = new SomeViewModel(_meetingRoomServiceFake)\n\n      //in there the mock gets called and sets the _getRoomsCallback field.\n      viewModel.GetRooms();\n      var theRooms = new List<MeetingRoom>\n                   {\n                       new MeetingRoom(1, "some room"),\n                       new MeetingRoom(2, "some other room"),\n                   };\n\n     //this will call whatever was passed as callback in your viewModel.\n     _getRoomsCallback(theRooms);\n}	0
22665582	22665329	Why XmlSerializer cannot deserialize xml with schema specified in the root element	[XmlRoot(ElementName = "person", Namespace = "somenamespace")]\npublic class Person {\n  [XmlElement(ElementName = "firstName", Namespace = "")]\n  public string fistName { get; set; }\n  [XmlElement(ElementName = "lastName", Namespace = "")]\n  public string lastName { get; set; }\n}	0
23648296	23624865	Convert Base64 string to BitmapImage C# Windows Phone	public static BitmapImage Base64StringToBitmap(string  base64String)\n{\n    byte[] byteBuffer = Convert.FromBase64String(base64String);\n    MemoryStream memoryStream = new MemoryStream(byteBuffer);\n    memoryStream.Position = 0;\n\n    BitmapImage bitmapImage = new BitmapImage();\n    bitmapImage.SetSource(memoryStream);\n\n    memoryStream.Close();\n    memoryStream = null;\n    byteBuffer = null;\n\n    return bitmapImage;\n}	0
5410631	5410436	How to create hierarchical classes / enums to be used as a key in collection in .NET C#	public class App\n{\n   public Account[] Accounts {}\n}\n\npublic class Account\n{\n   public decimal ApprovedAmount {get;set;}\n   public int ContractLength {get;set;}\n}	0
18081605	18080802	Devexpress GridControl row backcolor	gridPackages.gridView.RowCellStyle += gridView_RowCellStyle;\n\nprivate void gridView_RowCellStyle(object sender, RowCellStyleEventArgs e)\n        {\n            Package pac = Packages[e.RowHandle];\n            if (PackagesInRoom.SingleOrDefault(t => t.PackageID == pac.PackageID) != null)\n            {\n                e.Appearance.BackColor = Color.Green;\n            }\n        }	0
8714885	8714784	How to dynamically run process in asp.net	public void MyEventHasFired()\n{\n     DateTime dateLastProcessed = ... //Database? Session data? Anything goes.\n     if(dateLastProcessed < DateTime.Now.AddMinutes(-10))\n     {\n          //calculate\n\n          ...\n\n          dateLastProcessed = DateTime.Now;\n     }\n}	0
14703631	14702868	Serial number of phone (device)	object uniqueId;\nvar hexString = string.Empty;\nif (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))\n    hexString = BitConverter.ToString((byte[])uniqueId).Replace("-", string.Empty);	0
13718704	13718660	where is the method body of builtin assemblies methods	[from metadata]	0
17718316	17718117	getting specific pdf page number in asp.net C#	"#page=4"	0
30081504	30081379	Read values from file into multidimensionnal array	int [,] locations = new int [noLoc, 3]\nvar rowIndex = 0;\nusing(StreamReader sr = new StreamReader(myTextFile))\n{\n    while(\n      rowIndex < noLoc && // if using array you have to read no more than allocated\n       (line = sr.ReadLine()) != null)\n    {\n      locations[rowIndex,0] = locationTrain1;\n      locations[rowIndex,1] = locationTrain2;\n      locations[rowIndex,2] = distanceBetweenThem;\n      rowIndex++;\n    }\n}	0
18443766	18443411	C# copy function richtextbox with formatting	if (richTextBox1.SelectionLength > 0)\n// Copy the selected text to the Clipboard\nClipboard.SetText(richTextBox1.SelectedText, TextDataFormat.Text);	0
9772003	9771718	How to update querystring in C#?	var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());\nnameValues.Set("sortBy", "4");\nstring url = Request.Url.AbsolutePath;\nstring updatedQueryString = "?" + nameValues.ToString();\nResponse.Redirect(url + updatedQueryString);	0
13705890	13705839	Duplicate an object in a list	public class MyObject\n{\n    public string first\n    {\n        get;\n        set;\n    }\n    public string second\n    {\n        get;\n        set;\n    }\n\n    public MyObject DeepClone()\n    {\n        return new MyObject{ first = this.first, second = this.second;}\n    }\n}\n\n// Then you can do this:\n\nList<MyObject> list = new List<MyObject>();\nlist.Add(new MyObject{first = "one", second = "two"});\nlist.Add(new MyObject{first = "here", second = "there"});\nlist.Add(new MyObject{first = "car", second = "plane"});\n\nlist.Add(list[list.Count-1].DeepClone());	0
6550485	6550409	How to add attributes to a base class's properties	[MetadataType(typeof(MyModelMetadata))]\npublic class MyModel : MyModelBase {\n  ... /* the current model code */\n}\n\n\ninternal class MyModelMetadata {\n    [Required]\n    public string Name { get; set; }\n}	0
13390025	13389861	Using reflection to compare a property value to a string representation of that value	return string.Compare(value, propvalue.ToString()) == 0;	0
933784	933782	Finding out subclass type of an instance declared as a superclass	Console.WriteLine(_a1.GetType());	0
9720276	9719653	How to prevent open my application more than one time?	bool onlyInstance = false;\n\nMutex m = new Mutex(true, "MyUniqueMutextName", out onlyInstance);\nif (!onlyInstance)\n{\n    return;\n}\n\nGC.KeepAlive(m);	0
25221614	25220745	How to remove the last character typed in a textbox	public partial class MainWindow : Window\n{\n    private ICollection<TextChange> _latestChange = null;\n\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        myTextBox.TextChanged += (o, a) =>\n        {\n            _latestChange = a.Changes;\n        };\n    }\n\n    private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        if (_latestChange != null)\n        {\n            var change = _latestChange.FirstOrDefault(); // Just take first change\n            if (change.AddedLength > 0) // If text was removed, ignore\n            {\n                myTextBox.Text = myTextBox.Text.Remove(change.Offset, change.AddedLength);\n            }\n        }\n    }\n}	0
3876085	3875826	How to get the name of Sitemap file from Sitemap provider in ASP.NET	public static string GetFilename(this XmlSiteMapProvider provider)\n{\n    Type type = provider.GetType();\n    FieldInfo filenameField = type.GetField("_filename", BindingFlags.Instance | BindingFlags.NonPublic);\n    return (string)filenameField.GetValue(provider);\n}	0
1445319	1445292	How does one import multiple plugin/parts using MEF?	[ImportMany]\npublic IEnumerable<Intertface.ICalculate> Calculators { get; set; }	0
8182347	8182098	How do I test a method which has database queries to update data?	class Bar {\nprivate DataAccessService service\n\npublic void Foo()\n{\n    // some data validation logic here\n\n    if (some_criteria_is_true)\n    {\n        // Call to a method which uses sql queries to update some records\n        service.updateBarRecords();\n    }\n    else\n    {\n        // Call to a method which uses sql queries to delete some records\n        service.deleteBarRecords();\n    }\n}\n\n}	0
16918538	16917336	current time in Console C# but countinuously change as system time change	while(true)\n{\n\n    Console.Clear();\n    Console.WriteLine(DeteTime.Now);\n    Thread.Sleep(1000);\n\n}	0
6940306	6940234	How do you multiply numbers in C# through the cmd?	Console.WriteLine("Enter first number: ");\nint m = Int32.Parse(Console.ReadLine());\nConsole.WriteLine("Enter second number: ");\nint n = Int32.Parse(Console.ReadLine());\nConsole.Write("The multiplication of numbers entered = "+ m * n);\nConsole.ReadLine();	0
11128056	11125883	Property Dependency Injection used in Constructor using Unity	Logger.Error("PRINT AN ERROR");	0
25531077	25530768	Send byte[] continuously from server to client?	class Program\n{\n    static void Main(string[] args)\n    {\n        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n        server.Connect("127.0.0.1", 8000);\n        byte[] buffer = new byte[1024];\n        while (true)\n        {\n            int bytes = server.Receive(buffer);\n            Console.WriteLine(System.Text.Encoding.Default.GetString(buffer, 0, bytes));\n        }\n    }\n}	0
874760	874746	How can I get a value of a property from an anonymous type?	public T AnonymousTypeCast<T>(object anonymous, T typeExpression) { \n  return (T)anonymous;\n}\n\n...\nobject obj = GetSomeAnonymousType();\nvar at = AnonymousTypeCast(obj, new { Name = String.Empty, Id = 0 });	0
1025819	1025803	How to identify abstract members via reflection	PropertyInfo pi = ...\n\nif( pi.GetSetMethod().IsAbstract )\n{\n}	0
15537558	15534027	MonoMac WebView - Show Console or Web Inspector?	var defaults = NSUserDefaults.StandardUserDefaults;\ndefaults.SetBool (true, "WebKitDeveloperExtras");\ndefaults.Synchronize();	0
5530271	5528894	C# Get properties from SettingsPropertyCollection	string[] props = ProfileBase.Properties.Cast<SettingsProperty>()\n            .Select( p => p.Name ).ToArray();	0
24680014	24679944	Using linq to find duplicates in List<Vector2>	list.GroupBy(x => new {x.X, x.Y})\n.Where(g => g.Count() > 1)\n.Select(g => new {g.Key.X, g.Key.Y})\n.ToList();	0
2903199	2901987	C# Image saving from onPaint method	GraphicsUnit units = GraphicsUnit.Pixel;\n        System.Drawing.Imaging.ImageAttributes imageAttr = new System.Drawing.Imaging.ImageAttributes();\n\n        Graphics gx = Graphics.FromImage(lol);\n\n\n        int width = testing.Width / 3;\n        int height = testing.Height / 3;\n        Rectangle destrect1 = new Rectangle(0, 0, width, height);\n           //1.1.jpg//\n        gx.DrawImage(testing, destrect1, 0, 0, width, height, units, imageAttr);\n\n        pictureBox2.Image = lol;\n        lol.Save(@"Pictures\\hahaha.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);\n       // pictureBox2.Image = gx.(lol); \n\n    }	0
32190666	32190098	Two apps reading/writing the same text file	string folderPath1 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n// or \nstring folderPath2 = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);	0
2050828	2044535	help in extracting a tag out of a DOM of a web page	IHTMLDocument3 currDocument3 = (IHTMLDocument3)webBrowser.Document.DomDocument; // Cast browser document\n  IHTMLElement element = currDocument3.getElementById("f15188");	0
16084760	15160680	export chart to image high quality	FileFormat.Metafile	0
29292192	29292015	How can I do float:right in Windows Form Application?	public Form1() {\n        InitializeComponent();\n        string prefix = "Welcome ";\n        linkLabel1.Text = prefix + Environment.UserName;\n        linkLabel1.LinkArea = new LinkArea(prefix.Length, linkLabel1.Text.Length - prefix.Length);\n    }	0
30899928	30899682	Generate DateTime Stamp on Session Timeout c#	protected void Session_End(object sender, EventArgs e)\n{\n   //your logic goes here\n}	0
19738355	19738295	Listing files into listbox by date modified	foreach(FileInfo fi in di.GetFiles("*.txt").OrderBy (d => d.LastWriteTime))\n{\n    listBox1.Items.Add(fi.Name.Substring(0, fi.Name.Length - 4));\n}	0
10716017	10713063	How to Perform Reflection Operations using Roslyn	public static IEnumerable<MethodDeclarationSyntax> BobsFilter(SyntaxTree tree)\n    {\n        var compilation = Compilation.Create("test", syntaxTrees: new[] { tree });\n        var model = compilation.GetSemanticModel(tree);\n\n        var types = new[] { SpecialType.System_Boolean, SpecialType.System_Void };\n\n        var methods = tree.Root.DescendentNodes().OfType<MethodDeclarationSyntax>();\n        var publicInternalMethods = methods.Where(m => m.Modifiers.Any(t => t.Kind == SyntaxKind.PublicKeyword || t.Kind == SyntaxKind.InternalKeyword));\n        var withoutParameters = publicInternalMethods.Where(m => !m.ParameterList.Parameters.Any());\n        var withReturnBoolOrVoid = withoutParameters.Where(m => types.Contains(model.GetSemanticInfo(m.ReturnType).ConvertedType.SpecialType));\n\n        return withReturnBoolOrVoid;\n    }	0
6223298	6148550	Parse Excel sheet dynamically (cells range not provided, as the location of data in sheet may dynamically vary)	DataTable dt = new DataTable();\ntry\n{\n   OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=yes;IMEX=1""", excelPath));\n   OleDbDataAdapter da = new OleDbDataAdapter("select * from [sheetname$]", con);\n\n   da.Fill(dt);\n}\ncatch (Exception ex)\n{\n   MessageBox.Show(ex.Message);\n   return;\n}\n//now you can use dt DataTable\nforeach (DataRow dr in dt.Rows)\n{\n  //....\n}	0
3262547	3262438	Is there any way to assign to a variable by a Type object in C#?	private static void ElemInitializer(int ElType, out Element E1)\n{\n    E1 = new Element();\n    Type typeofElement = typeof(Element);\n    Type[] assemblyTypes = Assembly.GetAssembly(T1).GetTypes();\n    foreach (Type elementType in assemblyTypes )\n    {\n      if (elementType.IsSubclassOf(typeofElement))\n      {\n        FieldInfo field = elementType.GetField("ElemType");\n        int elementId = (int)field.GetValue(elementType);\n        if (elementId == ElType)\n        {\n           E1 = (Element)Activator.CreateInstance(elementType);\n           return;\n        }\n      }\n    }\n}	0
12344843	12344708	Castle Windsor - IoC registration for open generic interfaces?	container.Register(Component\n             .For(typeof(IAdapterFactory<,>))\n             .ImplementedBy(typeof(AdapterFactory<,>))\n             .LifestylePerWebRequest());	0
13068007	13067398	change specific column header color only in datagridview	DataGridViewColumn dataGridViewColumn = dataGridView1.Columns[0];\n        dataGridViewColumn.HeaderCell.Style.BackColor = Color.Magenta;\n        dataGridViewColumn.HeaderCell.Style.ForeColor = Color.Yellow;	0
10415664	10415545	C# culture info/setting up a specific tostring for currency	ToString("#,###.00##", myFormatProvider)	0
14504206	14503317	Taking a copy of an Excel template that is saved in the Solution	Assembly asm = Assembly.GetExecutingAssembly();\nstring file = string.Format("{0}.Template.xlsx", asm.GetName().Name);\nvar ms = new MemoryStream();\nStream fileStream = asm.GetManifestResourceStream(file);	0
9091444	9089452	Need to prevent access to a certain feature while an upgrade is being installed	static void Main(string[] args)\n    {\n        try\n        {\n            Mutex mutex = Mutex.OpenExisting(@"Global\_MSIExecute");\n            if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))\n            {\n                Console.WriteLine("Installation in progress!");\n                return;\n            }\n        }\n        catch (AbandonedMutexException)\n        {\n            Console.WriteLine("Mutex was abandoned");\n        }\n        catch (WaitHandleCannotBeOpenedException)\n        {\n            Console.WriteLine("MSI installer not running");\n        }\n\n        // Perform operation here\n    }	0
23661419	23657073	Storing colors in ApplicationDataContainer in a Windows Store app	private Color GetColorFromString(string colorHex)\n    {\n        var a = Convert.ToByte(colorHex.Substring(1, 2),16);\n        var r = Convert.ToByte(colorHex.Substring(3, 2),16);\n        var g = Convert.ToByte(colorHex.Substring(5, 2),16);\n        var b = Convert.ToByte(colorHex.Substring(7, 2),16);\n        return Color.FromArgb(a, r, g, b);\n    }	0
10895478	10893650	Apply localization through resource files to DisplayAttribute 	[Display(Name = "Remember me?", ResourceType = typeof(YourResourcesType))]\npublic bool RememberMe { get; set; }	0
32179433	32179197	Register hotkey with modifiers from keyboard input	int mod = 0;\nif (e.Alt) mod |= 1;\nif (e.Control) mod |= 2;\nif (e.Shift) mod |= 4;\nRegisterHotKey(this.Handle, 1, mod, S_HOTKEY);	0
3164411	3164324	Variable scope and performance	StringBuilder sb = new StringBuilder();\n\nforeach (MySampleClass c in dictSampleClass)\n{\n    sb.Append(c.VAR1);\n    sb.Append(c.VAR2);\n    sb.Append(c.VAR3);\n    sb.Append("|");\n}\n\nstring[] results = sb.ToString().Split('|');\n\nfor (int i = 0; i < dictSampleClass.Count; i++)\n{\n    string s = results[i];\n    MySampleClass c = dictSampleClass[i];\n    PerformSomeTask(s,c.VAR4); \n}	0
16623812	16622557	Exclude cache if specific URL parameter exist	protected override void OnPreInit(EventArgs e)\n    {\n        if (HttpContext.Current.Request.QueryString.AllKeys.Contains("traceid"))\n            HttpContext.Current.Response.CacheControl = "no-cache";\n        base.OnPreInit(e);\n\n    }	0
27178817	27178700	A for loop is stuck when trying to get a pair number (even number)	Random rnd = new Random();\nint tamanoAlt = rnd.Next(tamMinHabAlt, tamMaxHabAlt) & ~1;	0
9472192	9469068	Simulating Key Presses in WPF	UserControl1.InsertCharacter(string character)\n{\n    textBox1.Text = textBox1.Text.Insert(textBox1.CaretIndex, character); \n    this.ValidateInput();\n}\n\nUserControl1.ValidateInput()\n{\n    // Perform validation\n}\n\nUserControl1.OnKeyDown()\n{\n    // Perform validation\n    this.ValidateInput();\n}\n\nUserControl2.AppendCharacter(string clickedCharacter)\n{\n    this.userControl1.InsertCharacter(clickedCharacter); \n}	0
15238513	15238322	Controls in the same DataGridView column dont render while initializing grid	protected override void OnLoad(EventArgs e)\n    {\n        ControlsInGridViewColumn();  //<- does correctly render controls\n        base.OnLoad(e);\n    }	0
14578214	14578135	how to add value to array in the next postion	class DigitalCamera\n{\n    static int currentPhotoNumber = 0;\n    private Random rnd = new Random();\n\n    public override void TakePhoto()\n    {\n        int photo = rnd.Next(1, 10);\n        MemoryCard.buffer[currentPhotoNumber++] = photo;\n    }\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n\n        DigitalCamera digitalCamera = new DigitalCamera("kodak", 43, newMemoryCard, 3);\n\n        digitalCamera.TakePhoto();\n        digitalCamera.TakePhoto();\n        digitalCamera.TakePhoto();\n\n    }\n}	0
13162079	13162057	Retrieving ids from a LINQ query result	var ids = theCollectionReturned.SelectMany(info => info.Ids);	0
11097713	11095361	How to write functionality using DDD / CQRS	public class AccountService : IAccountService\n{\n    private IAccountRepository _accountRespository;\n\n    public void FreezeAllAccountsForUser(Guid userId)\n    {\n        IEnumerable<IAccount> accounts = _accountRespository.GetAccountsByUserId(userId);\n\n        using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())\n        {\n            foreach (IAccount account in _accounts)\n            {\n                account.Freeze();\n                _accountRespository.Save(account);\n            }\n        }\n    }\n}	0
2944496	2942928	Is it not possible to show a FolderBrowserDialog from a non-UI thread?	private void button1_Click(object sender, EventArgs e) {\n        var t = new Thread(() => new FolderBrowserDialog().ShowDialog());\n        t.IsBackground = true;\n        t.SetApartmentState(ApartmentState.STA);\n        t.Start();\n    }	0
26471273	26471230	How to code for cancel button in OpenFileDialog box	if (ofd.ShowDialog() == DialogResult.OK)\n    {\n        filename_noext = System.IO.Path.GetFileName(ofd.FileName);\n        path = Path.GetFullPath(ofd.FileName);\n        img_path.Text = filename_noext;\n        //MessageBox.Show(filename_noext, "Filename");\n        // MessageBox.Show(full_path, "path");\n        //move file from location to debug\n        string replacepath = @"E:\Debug";\n        string fileName = System.IO.Path.GetFileName(path);\n        string newpath = System.IO.Path.Combine(replacepath, fileName);\n        if (!System.IO.File.Exists(filename_noext))\n            System.IO.File.Copy(path, newpath);\n\n    }\nelse\n{\nreturn String.Empty;\n}	0
25425525	25425220	C# button animation	private void button2_Click(object sender, EventArgs e)\n{\n    timer1.Interval = 100;\n    //start the timer\n    timer1.Start();\n}\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    button1.Left += 20;\n    //check position of button. When it is outside the width of form stop the timer.\n    if(button1.Left >= this.Width) \n    {\n        timer1.Stop();\n    }\n}	0
11800366	11799727	zed graph: how to make my graph start at 0,0	//static ZedGraph.ZedGraphControl graph = new ZedGraph.ZedGraphControl();\nZedGraph.GraphPane pane = graph.GraphPane;\npane.XAxis.Scale.Min = 0.0;\ngraph.AxisChange();\ngraph.RestoreScale(pane);\ngraph.ZoomOut(pane);	0
23571402	23571365	Entity Framework 6 - Select Parents Where Children Equal	from p in context.Parents\nwhere p.Children.Any(c => c.PlaySoccer == true)\nselect p	0
22206396	22206340	C# Show dialog over another dialog in winforms?	err.ShowDialog(this);	0
3026055	3026036	Convert OracleParameter.Value to Int32	existsCount = int.Parse(cmd.Parameters["successCount"].Value.ToString());	0
11852067	11851088	how to open a folder that opens in the middle of the screen and at a certain size	process.handle //to get the handle of the window.\n\n[DllImport("user32.dll", SetLastError=true)]\npublic static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int W, int H, uint uFlags);	0
5074791	5074754	How do you get the template type from a List Type?	Type genericType = listOfStrings.GetType().GetGenericArguments()[0];	0
10738614	10738508	Adding div after each 4 loops	foreach (var page in images)\n {\n    int b = 100 ;\n    bool first=true;\n    bool wroteDivEnd = false;\n    for (int a = 0 ; a = b ; a++)\n    {\n        wroteDivEnd=false;\n        if (a% 4==0)\n        {\n           if (!first)\n           { \n              // as long as this is not the first time we have written a \n              //start div, then we need to write and end one\n              //write previous div end </div>\n              wroteDivEnd=true;\n           }\n           //write new div start <div>\n           //set the flag so we know we have written the first start div\n           first=false;\n        }\n        // write out the images\n        <img src="page.name" alt="page.alt" /> \n\n    }\n    //make sure your last </div> is written\n    if(!wroteDivEnd)\n    { \n     //write out the final missing </div>\n    }\n }	0
11169379	11169345	getting Schema of one Table in C#	string[] restrictions = new string[4];\nrestrictions[2] = "Petro";\nDataTable table = conn.GetSchema("Tables",restrictions);	0
30525060	30524723	How to redirect to another server in mvc using post method?	You can use the HttpWebRequest class to make the post to the other server and then redirect as normal\n\n    //code would be something like this\n    var httpRequest = (HttpWebRequest)WebRequest.Create("http:your url");\n    httpRequest.Method = "POST";\n    httpRequest.ContentType = "application/x-www-form-urlencoded";\n\n    string data = "key=value&key2=value2";\n    byte[] dataArray = Encoding.UTF8.GetBytes(data);\n    httpRequest.ContentLength = dataArray.Length;\n\n    //actual code to call another server\n     using(Stream requestStream = httpRequest.GetRequestStream())\n    {\n        requestStream.Write(dataArray, 0, dataArray.Length);\n        var webResponse = (HttpWebResponse)httpRequest.GetResponse();\n    }	0
14658563	14573560	how to wait for filesystemwatcher event to finish	...\n    me.WaitOne();\n    main_engine.processCreatedFile();\n}\n\n...\n\nvoid OnFileCreation(object sender, FileSystemEventArgs e) {\n// do some file processing\n// takes time based on size of file and whether file is locked or not etc.\n...\nme.Set();\n}\n\nManualResetEventSlim me = new ManualResetEventSlim(false);	0
3996326	3996266	Recover from using bad code page in C#	string Recover(string input)\n{\n   return Encoding.GetEncoding("iso-8859-2").GetString(Encoding.GetEncoding(1251).GetBytes(input));\n}	0
20271483	20271444	try catch with if null statement	try\n{\n   if (user == null || job == null)\n   { \n       throw new Exception("user or job is null"); \n\n   }\n}\ncatch(Exception ex )\n{\n   //here your code \n}	0
2534767	2534750	C#: Specify that a function arg must inherit from one class, and implement an interface?	interface IGameObjectController\n{\n    // Interface here.\n}\n\ninterface ICombatant : IGameObjectController\n{\n    // Interface for combat stuff here.\n}\n\nclass GameObjectController : IGameObjectController\n{\n    // Implementation here.\n}\n\nclass FooActor : GameObjectController, ICombatant\n{\n    // Implementation for fighting here.   \n}	0
8571636	8566352	IoC: Create a Unity extension to override dependencies?	var container = new UnityContainer();\n  container.AddNewExtension<SemanticGroupExtension>();\n\n  container.RegisterGroup<IVehicle, Car>("Car").Use<IWheel, CarWheel>().Use<IEngine, CarEngine>();\n  container.RegisterGroup<IVehicle, Motorcycle>("Motorcycle").Use<IWheel, MotorcycleWheel>().Use<IEngine, MotorcycleEngine>();\n\n  var car = container.Resolve<IVehicle>("Car");\n  Assert.IsInstanceOfType(car.Wheel, typeof(CarWheel));\n  Assert.IsInstanceOfType(car.Engine, typeof(CarEngine));\n\n  var motorcycle = container.Resolve<IVehicle>("Motorcycle");\n  Assert.IsInstanceOfType(motorcycle.Wheel, typeof(MotorcycleWheel));\n  Assert.IsInstanceOfType(motorcycle.Engine, typeof(MotorcycleEngine));	0
6929133	6910146	Transfer string from C# app to OPEN Excel 2003 worksheet cell	Workbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(FileName);	0
22001264	21990524	Regex match parentheses and curly brackets	bool squareBrackets = false;\nbool quotes = false;	0
1029317	1029268	How do I move items from a list to another list in C#?	var selected = items.Where(item => item.Something > 10).ToList();\nselected.ForEach(item => items.Remove(item));\notherList.AddRange(selected);	0
821033	821017	Simulating a locked/hung application	while(true) { } // busy waiting\nThread.Sleep(time); // blocking	0
9976522	9931511	MSWord automation merge prints template document too	//open the data file\nmrgDoc.MailMerge.OpenHeaderSource(pathToHdr);\nmrgDoc.MailMerge.OpenDataSource(pathToDB);\nmrgDoc.MailMerge.SuppressBlankLines = true;\nmrgDoc.MailMerge.ViewMailMergeFieldCodes = 0;\n\nmrgDoc.Application.ActiveDocument.Range(0, 0).Select();                \ntry\n{\n    if (!string.IsNullOrWhiteSpace(pathToDestinationFile) && Directory.Exists(Path.GetDirectoryName(pathToDestinationFile)))\n    mrgDoc.SaveAs(pathToDestinationFile);\n}\ncatch\n{\n    wrdApp.Visible = true;\n}	0
9105814	9105438	how to add numbers in various textboxs and the sum displayed in a label	private void textBox1_TextChanged(object sender, TextChangedEventArgs e)\n{\n    SumAndDisplay();\n}\n\nprivate void textBox2_TextChanged(object sender, TextChangedEventArgs e)\n{\n    SumAndDisplay();\n}\n\nprivate void SumAndDisplay()\n{\n    int a;\n    int b;\n    if (Int32.TryParse(textBox1.Text, out a) && Int32.TryParse(textBox2.Text, out b))\n    {\n        label1.Content = (a + b).ToString();\n    }\n}	0
5103418	5103370	matching event date column to todays date	db.TimeSet.Where(e => e.EventDate.Day == DateTime.Today.Day && e.EventDate.Month == DateTime.Today.Month && e.EventDate.Year == DateTime.Today.Year)	0
3511091	3511071	Making a class available only to a single other class	/// <summary>\n///    blah blah, what this interface is for\n/// </summary>\n/// <remarks>\n///   This interface should only be implemented by inheritors of Operation.\n/// </remarks>\npublic interface IRepositoryWriter{}	0
31307473	31307176	How to add parent node in XML using c#	string xml = @"<person>\n  <name>prane</name>\n  <age>19</age>\n</person>\n<person>\n  <name>neeth</name>\n  <age>20</age>\n</person>";\n            XElement root = XElement.Parse(string.Format("{0}{1}{2}", "<persons>", xml, "</persons>"));	0
15052863	15051245	Changing Desktop Wallpaper Periodically	using System;\nusing System.Runtime.InteropServices;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        [DllImport("user32.dll", CharSet = CharSet.Auto)]\n        private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String         pvParam, UInt32 fWinIni);\n        private static UInt32 SPI_SETDESKWALLPAPER = 20;\n        private static UInt32 SPIF_UPDATEINIFILE = 0x1;\n        private static String imageFileName = "c:\\test\\test.bmp";\n\n        static void Main(string[] args)\n        {\n            SetImage(imageFileName);\n            Console.ReadKey();\n        }\n\n        private static void SetImage(string filename)\n        {\n            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, filename, SPIF_UPDATEINIFILE);\n        }\n    }\n}	0
1881101	1881058	Retrieving lambda expressions from a collection	var list = new List<Func<int, int>>();\nfor (int i = 0; i < 10; i++)\n{\n    var temp = i;\n    Func<int, int> func = x => x + temp;\n    Console.WriteLine("a) " + func.Invoke(0)); //returns 0,1,2,3,4,5,6,7,8,9\n\n    list.Add(func);\n    Console.WriteLine("b) " + list[i].Invoke(0)); //returns 0,1,2,3,4,5,6,7,8,9\n}\n\nforeach (var func in list) //returns 0,1,2,3,4,5,6,7,8,9\n    Console.WriteLine("c) " + func.Invoke(0));\n\nfor (int i = 0; i < list.Count; i++) //returns 0,1,2,3,4,5,6,7,8,9\n    Console.WriteLine("d) " + list[i].Invoke(0));	0
20071016	19945006	MySql Connectors 6.7.4 on a medium trust shared environment	Driver={MySQL ODBC 5.1 Driver};Server=myServerAddress;Database=myDataBase; User=myUsername;Password=myPassword;Option=3;	0
19480582	19480565	Get values from if/else statements?	double shippingAmount;\n\nif (shippingInput == 1)\n{\n    shippingAmount = shippingDetails * 3;\n}\nelse if (shippingInput == 2)\n{\n    shippingAmount = shippingDetails * 4;\n}\nelse\n{\n    shippingAmount = shippingDetails * 5.5;\n}	0
18478190	18459677	How to bind a model to a dynamically created class nancyfx	dynamic model = this.Bind<DynamicDictionary>();	0
25528937	25528757	How to retrieve records for a given date (regardless of time) using C#?	WHERE DateDiff("d",@MyDateParameter,[DATE_SALE])=0	0
12303809	12303740	Public methods outside of an interface in a class	public class SendWelcomeEmailComposer\n{\n    MailMessage Compose(User user)\n}\n\npublic class EmailSender\n{\n    void SendEmail(MailMessage);\n}\n\npublic class EmailService\n{\n    void SendWelcomeEmail(User user)\n    {\n        // compose email\n        // and send using the classes above.\n    }\n}	0
18476755	18475930	Filtering rows in datatable	DataTable.Select	0
14054864	8516701	How to get windows service name from app.config	public string GetServiceNameAppConfig(string serviceName)\n{\n    var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(MyServiceInstaller)).Location);\n    return config.AppSettings.Settings[serviceName].Value;\n}	0
31653708	31404354	MVC 4, Displaying data from multiple tables & association in a view as a list	public ActionResult GetThreatControls(int ThreatID)\n        {\n            RiskAssessmentApplicationEntities _DBContext = new RiskAssessmentApplicationEntities();\n            ThreatHasControl ViewModel = new ThreatHasControl();\n            ViewModel.Threat = _DBContext.Threats.Single(x => x.ID == ThreatID);\n            ViewModel.Controls = _DBContext\n                                        .ThreatHasControl\n                                        .Include("ThreatHasControl.Control")\n                                        .Where(x => x.ThreatID == ThreatID)\n                                        .Select(x => x.Control);\n\n            return View(ViewModel);                                   \n        }	0
10155953	10155412	Display dialog box in landscape	GraphicsDevice.PresentationParameters.DisplayOrientation = DisplayOrientation.LandscapeRight;	0
4367515	4367088	Word Automation - File is in use by another application or user	_wordApplication.NormalTemplate.Saved = true;	0
24009524	24009201	Close old instance of application	if (pname.Length > 1)\n{\n    pname.Where(p => p.Id != Process.GetCurrentProcess().Id).First().Kill();\n}	0
25879342	25878983	Show Preferred DNS and Alternate DNS on a label	IPInterfaceProperties.DnsAddresses	0
7444389	7444042	Umbraco - How can I get Publish at/Remove at date using C#	var doc = new Document(nodeId);\nvar publishAt = doc.ReleaseDate;\nvar removeAt = doc.ExpireDate;	0
7174508	7174403	How do I access this XML structure using Linq in C#?	var items = from data in document.Descendants("data")\n\n            let taskId =\n                data.Elements("item")\n                .Where(i => (string)i.Attribute("key") == "taskId")\n                .FirstOrDefault()\n\n            where taskId != null\n\n            let taskSubject = \n                data.Elements("item")\n                .Where(i => (string)i.Attribute("key") == "taskSubject")\n                .FirstOrDefault()\n\n            where taskSubject != null\n\n            select new {\n                TaskId = taskId.Element("value").Value.Trim(),\n                TaskSubject = taskSubject.Element("value").Value.Trim()\n            };	0
21206907	21206744	Xamarin IOS hide bar back button	public override void ViewDidLoad ()\n{\n    base.ViewDidLoad ();\n\n    this.NavigationItem.SetHidesBackButton (true, false);\n}	0
27133037	27132878	How to join deep data in the Entity Framework?	IEnumerable<COM_Order> data = ctx.COM_OrderItem\n                                 .Join(ctx.CMS_Tree, \n                                       co => co.OrderItemSKUID,\n                                       t => t.NodeSKUID, \n                                       (orderitem,tree) => {myOrder = orderitem.COM_Order })\n                                 .Select(o => o.myOrder)\n                                 .AsEnumerable();	0
16879664	16879597	string similarity and pattern matching	(.+) is (Boy|Girl)	0
11654597	11654562	How convert byte array to string	var str = System.Text.Encoding.Default.GetString(result);	0
8883203	8882917	How do I find the intersect of two sets of non-contiguous Times?	// Finds ones with absolutely no overlap\nvar unmodified = shifts.Where(s => !exceptions.Any(e => s.Start < e.End && s.End > e.Start));\n\n// Finds ones entirely overlapped\nvar overlapped = shifts.Where(s => exceptions.Any(e => e.End >= s.End && e.Start <= s.Start));\n\n// Adjusted shifts\nvar adjusted = shifts.Where(s => !unmodified.Contains(s) && !overlapped.Contains(s))\n                        .Select(s => new Shift\n                        {\n                            Start = exceptions.Where(e => e.Start <= s.Start && e.End > s.Start).Any() ? exceptions.Where(e => e.Start <= s.Start && e.End > s.Start).First().End : s.Start,\n                            End = exceptions.Where(e => e.Start < s.End && e.End >= s.End).Any() ? exceptions.Where(e => e.Start < s.End && e.End >= s.End).First().Start : s.End\n                        });\n\nvar newShiftSet = unmodified.Union(overlapped).Union(adjusted);	0
3414624	3414551	How to sort the list with duplicate keys?	using System.Linq;\n\n...\n\nvar mySortedList = myList.Orderby(l => l.Key)\n                         .ThenBy(l => l.Value);\n\nforeach (var sortedItem in mySortedList) {\n    //You'd see each item in the order you specified in the loop here.\n}	0
21057889	21057849	Call method from MultiView control on MasterPage	protected void Page_Load(object sender, EventArgs e)\n{\n    MultiView1.DataBind();\n}\n\npublic int test()\n{\n    return 0;\n}	0
27378997	27378767	Hiding Borderless Window from ALT+TAB menu	this.Opacity=0;	0
10720921	10720771	How to add background image to a Windows form gridview?	private void dataGridView1_Paint(object sender, PaintEventArgs e)\n    {\n         DataGridView dgv = (DataGridView) sender;\n        int i = dgv.Rows.GetRowsHeight(DataGridViewElementStates.Visible);\n        e.Graphics.DrawImage(Properties.Resources.BackGround, new Rectangle(0, i, dgv.Width, (dgv.Height - i)));\n    }	0
21009618	21008935	Swapping two elements in a list covariantly	public static void Swap<T>(this List<T> list, int pos1, int pos2)\n{\n    T tmp = list[pos1];\n    list[pos1] = list[pos2];\n    list[pos2] = tmp;\n\n}	0
25188189	25188146	How can I check for a NullReferenceException in this C# LINQ to XML statement?	XElement doc = XElement.Load("test.xml");\n\nvar nodes =\nfrom node in doc.Elements("Customer")\nselect new \n{\n  Name = node.Element("FullName") !=null ? node.Element("FullName").Value : null,\n  Zip = node.Element("ZipCode") !=null ? node.Element("ZipCode").Value : null,\n  Active = node.Element("ActiveCustomer") !=null ? node.Element("ActiveCustomer").Value : null\n};	0
24994945	24994840	Retrieve the week number from a date	public int GetWeek(DateTime date)\n    {\n        var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);\n        return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);            \n    }\n\npublic string GetWeekFormatted(DateTime date)\n{\n    return GetWeek(date).ToString("00");\n}	0
26055135	26055090	How to insert only date into database	str=mas.empdetadd(ddid.SelectedItem.Text,Convert.ToDateTime(txtdate.Text).Date);	0
18719522	18719463	How to go about splitting strings with multiple splitter values	string input = "0Days0hours51Minutes32Seconds";\nvar nums = Regex.Matches(input, @"\d+").Cast<Match>()\n                .Select(m => int.Parse(m.Value))\n                .ToList();	0
34171826	34171470	Open a wpf Page using Path/URI	System.Uri resource =  new System.Uri(@"Views\MyPage.xaml", System.UriKind.RelativeOrAbsolute);\n    Something.Content = System.Windows.Application.LoadComponent(resource);	0
30477073	30477022	Constructor injection, avoid non-dependency parameters	MyClassBase(IOneService oneService, ITwoService twoService, ISettings set)\n{\n    _setting = set;\n    ....\n}	0
12537587	12536705	Adding a default where clause to a linq-to-sql table	Primary Key	0
33551700	33551681	How can I get a value to expand over multiple rows in Excel?	private int curDescriptionTopRow = 8;\n. . .\nprivate void AddDescription(String desc)\n{\n    int curDescriptionBottomRow = curDescriptionTopRow + 3;\n\n    var range =\n        _xlSheet.Range[_xlSheet.Cells[curDescriptionTopRow, 1], _xlSheet.Cells[curDescriptionBottomRow, 1]];\n    range.Merge();\n\n    range.Font.Bold = true;\n    range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;\n    range.Value2 = desc;\n}	0
17037730	17037207	Loading a tab delimited textfile and displaying it in a listview c#	//Holders.\nstring line = "";\nstring[] items;\nListViewItem listItem;\n\n//While there are lines to read.\nwhile((line = reader.ReadLine()) != null)\n{\n    items = line.Split('\t') //Split the line.\n    listItem = new ListViewItem(); //"Row" object.\n\n        //For each item in the line.\n        for (int i = 0; i < items.Length; i++)\n        {\n            if(i == 0)\n            {\n                listItem.Text = items[i]; //First item is not a "subitem".\n            }\n            else\n            {\n                listItem.SubItems.Add(items[i]); //Add it to the "Row" object.\n            }\n        }\n\n    listView1.Items.Add(listItem); //Add the row object to the listview.\n}	0
31515219	31507656	How to use an API on an android apps?	var auth = new OAuth2Authenticator (\n               clientId: "CLIENT_ID",\n               scope: "basic",\n               authorizeUrl: new Uri ("https://api.instagram.com/oauth/authorize/"),\n               redirectUrl: new Uri ("REDIRECT_URL"));\n\nauth.AllowCancel = allowCancel;\n\n// If authorization succeeds or is canceled, .Completed will be fired.\nauth.Completed += (s, ee) => {\n    var token = ee.Account.Properties ["access_token"];\n};\n\nvar intent = auth.GetUI (this);\nStartActivity (intent);	0
34128280	34128207	how to add delimiter to end of the each word in string using c#	string input = "4 4 4100100001063D 1CBSME 150312 40001063ANTE LECO METERING C 3460025.57LKR";\nstring pattern = "\\s+";\nstring replacement = "|";\nRegex rgx = new Regex(pattern);\nstring result = rgx.Replace(input, replacement) + replacement;	0
8967980	8967953	Extract a specifc portion of a string in C#	var result = HttpUtility.ParseQueryString(new Uri(src).Query);	0
30847255	30847033	MySQL database to combo box using mysqldatareader in c#.net	MySQL database to combo box using mysqldatareader in c#.net\n\nMySqlCommand cmd = new MySqlCommand("select * from product", connection);\nMySqlDataReader dread = cmd.ExecuteReader();\nwhile (dread.Read())\n{\n    cbProducts.Items.Add(dread("description");\n}	0
21987781	21940241	How can I read the values of the defaultProxy settings from the system.net section in a web.config?	var proxy = System.Web.Configuration.WebConfigurationManager.GetSection("system.net/defaultProxy") as System.Net.Configuration.DefaultProxySection  \nif (proxy != null) { /* Check Values Here */ }	0
10348561	10348505	Windows Phone 7 Navigate To URL	NavigationService.Navigate(new Uri("/Views/YourPage.xaml", UriKind.Relative));	0
14149071	14148160	Set focus to NewItemRow after row inserted from a NewItemRow	protected override void OnDataChanged(bool rebuildVisibleColumns)\n{\n    base.OnDataChanged(rebuildVisibleColumns);\n    Dispatcher.BeginInvoke(new Action(() =>\n    {\n        this.FocusedRowHandle = GridControl.NewItemRowHandle;\n    }), null);\n}	0
2808145	2808111	Parse XML and populate in List Box	XmlDocument doc = new XmlDocument();\n    doc.LoadXml(@"<LISTBOX_ST>\n     <item><CHK></CHK><SEL>00001</SEL><VALUE>val01</VALUE></item>\n     <item><CHK></CHK><SEL>00002</SEL><VALUE>val02</VALUE></item>\n     <item><CHK></CHK><SEL>00003</SEL><VALUE>val03</VALUE></item>\n     <item><CHK></CHK><SEL>00004</SEL><VALUE>val04</VALUE></item>\n     <item><CHK></CHK><SEL>00005</SEL><VALUE>val05</VALUE></item>\n     </LISTBOX_ST>");            \n\n    List<Item> _lbList = new List<Item>();\n   foreach (XmlNode node in doc.DocumentElement.ChildNodes)\n    {\n        string chk = node.ChildNodes[0].InnerText;\n        int sel = int.Parse(node.ChildNodes[1].InnerText);\n        string value = node.ChildNodes[2].InnerText;\n\n        Item item = new Item();\n        item.CHK = chk;\n        item.VALUE = value;\n        item.SEL = sel;\n\n        _lbList.Add(item);\n    }\n   listBox1.DataSource = _lbList;\n   listBox1.DisplayMember = "VALUE";\n   listBox1.ValueMember = "SEL";	0
21889579	21886207	How to automatically download an executable with Selenium and Firefox?	FirefoxProfile profile = new FirefoxProfile();\n\nprofile.setPreference("browser.download.manager.alertOnEXEOpen", false);\nprofile.setPreference("browser.download.manager.closeWhenDone", true);\nprofile.setPreference("browser.download.manager.focusWhenStarting", false);\nprofile.setPreference("browser.download.manager.showWhenStarting",false);\nprofile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/x-msdownload");\n\nFirefoxDriver driver = new FirefoxDriver(profile)	0
12141300	12141149	get value of a property by its path in asp.net	public object GetPropertyValue(object o, string path)\n{\n    var propertyNames = path.Split('.');\n    var value = o.GetType().GetProperty(propertyNames[0]).GetValue(o, null);\n\n    if (propertyNames.Length == 1 || value == null)\n        return value;\n    else\n    {\n        return GetPropertyValue(value, path.Replace(propertyNames[0] + ".", ""));\n    }\n}	0
9293710	9293598	How to redirect after File upload?	window.location.reload()	0
25824475	25824255	Replacing a substring with given form with another in C#	private string MyReplace(string inStr, string leaveStr)\n    {\n        string pattern = @"(.*?)(" + leaveStr + ")(.*)";\n        string repl = @"*$2*";\n\n        Regex rgx = new Regex(pattern);\n        return rgx.Replace(inStr, repl);\n\n    }\n\n    string x = MyReplace(@"\textbf\{atext\}", "atext");\n    x = MyReplace(@"\textbf\{1\}", "1");	0
6767216	6766505	Adding a row after adding columns using TableLayoutPanel	private void AddTLP()\n{\n  List<string> headers = new List<string>();\n  headers.Add("Column 1");\n  headers.Add("Column 2");\n  headers.Add("Column 3");\n\n  TableLayoutPanel tlp = new TableLayoutPanel();\n  tlp.Size = new Size(356, 120);\n  tlp.BackColor = Color.Gray;\n\n  for (int i = 0; i < headers.Count; i++)\n  {\n    Label l = new Label();\n    l.Text = headers[i].ToString();\n\n    ColumnStyle cStyle = new ColumnStyle(SizeType.AutoSize);\n    tlp.ColumnStyles.Add(cStyle);\n    tlp.Controls.Add(l, i, 0);\n  }\n\n  tlp.GrowStyle = TableLayoutPanelGrowStyle.AddRows;\n\n  // Add controls to test growth:\n  tlp.Controls.Add(new Button(), 0, 1);\n  tlp.Controls.Add(new TextBox(), 1, 2);\n\n  this.Controls.Add(tlp);\n}	0
2269780	2269489	C# - User Settings broken	Settings.Reset	0
10793199	10793149	Mail sent in spam	relay-hosting.secureserver.net	0
6272044	6271971	How to avoid "There is already an open DataReader associated with this Connection which must be closed first." in MySql/net connector?	var TimestampedList = (from t in dataContext.TrendRecords\n                                         where t.TrendSetting_ID == trendSettingID\n                                         select t).ToList();\nTimestampedDictionary = timestampedList.ToDictionary(m => m.Timestamp,\n                    m => (from j in dataContext.TrendSignalRecords\n                          where j.TrendRecord_ID == m.ID\n                          select j).ToDictionary(p => p.TrendSignalSetting.Name,\n                    p => (double?)p.Value))	0
28076648	28074966	Determine If Uploaded Photo is Portrait or Landscape with ImageResizer	.Build()	0
33545045	33544787	Check if user input is a valid date	var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};\n\nbool validate = true;\nwhile (validate) // Loop indefinitely\n{\n    Console.Write("\nSet your date: "); // Prompt\n    string readAddMeeting = Console.ReadLine(); // Get string from user\n\n    DateTime scheduleDate;\n    if(DateTime.TryParseExact(readAddMeeting,dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out scheduleDate))\n    {\n        Console.ForegroundColor = ConsoleColor.Green;\n        Console.WriteLine("Valid date");\n        validate = false;\n    }\n    else\n    {\n        Console.ForegroundColor = ConsoleColor.Red;\n        Console.WriteLine("Invalid date: \"{0}\"", readAddMeeting);\n    }\n    Console.ForegroundColor = ConsoleColor.White;\n}	0
13653089	5841896	0MQ: How to use ZeroMQ in a threadsafe manner?	sendQueue = new BlockingCollection<MyStuff>(new ConcurrentQueue<MyStuff>());\n// concurrent queue can accept from multiple threads/handlers safely\nMyHandler += (MyStuff stuffToSend) => sendQueue.Add(stuffToSend);\n\n// start single-threaded data send loop\nTask.Factory.StartNew(() => {\n    using(var socket = context.Socket()) {\n        MyStuff stuffToSend;\n        // this enumerable will be blocking until CompleteAdding is called\n        foreach(var stuff in sendQueue.GetConsumingEnumerable())\n            socket.Send(stuff.Serialize());\n    }\n});\n\n// break out of the send loop when done\nOnMyAppExit += sendQueue.CompleteAdding;	0
1928022	1928005	C# Display in XML Format	Response.ContentType = "text/xml";\n  Response.ContentEncoding = Encoding.UTF8;	0
31022258	31021596	Get all same scripts that attached in scene's gameobjects and store its into array, using c#	ScrollingBackgroundScript[] scrollingObjects = FindObjectsOfType (typeof(ScrollingBackgroundScript)) as ScrollingBackgroundScript[];	0
32216962	32216637	How to programically change ScaleY RenderTransform of a control in a XAML C# Windows App?	var transform = (CompositeTransform)arrowSection_Lec_1.RenderTransform;\ntransform.ScaleY = -1;	0
7591924	7591902	Get largest value from array without sorting	var largest = -1;\n  var player = -1;\n  for (var i = 0; i < allPlayers.Length; ++i)\n  {\n       if (allPlayers[i] > largest)\n       {\n           player = i;\n           largest = allPlayers[i];\n       }\n  }\n\n  Console.WriteLine( "Player {0} wins, with score {1}", player, largest );	0
12652145	12652007	Windows 8 XAMl C# add watermark to textbox?	Brushes.Transparent	0
28829009	28828911	Transform a sync method to async with C#	public class JobRunner\n{\n    public async Task<string> Run(bool fireAndForget)\n    {\n        await ShortMethodIAlwaysWantToWait();\n        string jobId = Guid.NewGuid().ToString("N");\n        if (fireAndForget)\n            HostingEnvironment.QueueBackgroundWorkItem((token) => LongMethodICouldWantToWaitOrNot(jobId));\n        else\n            await LongMethodICouldWantToWaitOrNot(jobId);\n        return jobId;\n    }\n\n    private async Task LongMethodICouldWantToWaitOrNot(string jobId)\n    {\n        await Task.Delay(5000);\n    }\n\n    private async Task ShortMethodIAlwaysWantToWait()\n    {\n        await Task.Delay(2000);\n    }\n}	0
33204673	33204369	Combining Multiple Drop Down List Selections Into 1 Variable	var ddlist = new List<DropdownList>();\nddlist.Add(dropdownlist1);//repeat this for all drowdowns.\nvar selectedTexts = ddlist.Where(x=>x.SelectedIndex > -1).Select(y=>y.SelectedItem.Text);\nvar fullselection = String.Join(",",selectedTexts.ToArray());	0
29917532	29915125	EF6/MVC 5: How to bind a list of many-to-many resolver entities to an object in a create view?	private void UpdateInstructorCourses(string[] selectedCourses, Instructor \n\ninstructorToUpdate)\n{\n   if (selectedCourses == null)\n   {\n      instructorToUpdate.Courses = new List<Course>();\n      return;\n   }\n\n   var selectedCoursesHS = new HashSet<string>(selectedCourses);\n   var instructorCourses = new HashSet<int>\n       (instructorToUpdate.Courses.Select(c => c.CourseID));\n   foreach (var course in db.Courses)\n   {\n      if (selectedCoursesHS.Contains(course.CourseID.ToString()))\n      {\n         if (!instructorCourses.Contains(course.CourseID))\n         {\n            instructorToUpdate.Courses.Add(course);\n         }\n      }\n      else\n      {\n         if (instructorCourses.Contains(course.CourseID))\n         {\n            instructorToUpdate.Courses.Remove(course);\n         }\n      }\n   }\n}	0
7804624	7804539	How to ignore case when comparing string?	var something= from x in y \n                   where string.Compare(x.Subject, searchQuery, true) >= 0\n                   select x;	0
18762522	18762259	C# Linq Column Name as variable	void BindGridTypeSafe()\n    {\n        NorthwindDataContext northwind = new NorthwindDataContext();\n\n        var query = from p in northwind.Products\n                    where p.CategoryID == 3 && p.UnitPrice > 3\n                    orderby p.SupplierID\n                    select p;\n\n        GridView1.DataSource = query;\n        GridView1.DataBind();\n    }\n\n    void BindGridDynamic()\n    {\n        NorthwindDataContext northwind = new NorthwindDataContext();\n\n        var query = northwind.Products\n                             .Where("CategoryID = 3 AND UnitPrice > 3")\n                             .OrderBy("SupplierID");\n\n        GridView1.DataSource = query;\n        GridView1.DataBind();\n    }	0
594627	439086	Get Entity From Table Using Reflection From Abstract Type	public BuilderInclusionsForm(Product p) : this()\n{\n    IEnumerable<Product> ps = db2.GetTable(p.GetType()).Cast<Product>();\n    product = ps.SingleOrDefault(a => a.ProductID == p.ProductID);\n}	0
19825820	19647244	How can I get all documents from RavenDB?	public class AllDocumentsById : AbstractIndexCreationTask\n{\n    public override IndexDefinition CreateIndexDefinition()\n    {\n        return\n            new IndexDefinition\n            {\n                Name = "AllDocumentsById",\n                Map = "from doc in docs \n                      let DocId = doc[\"@metadata\"][\"@id\"] \n                      select new {DocId};"\n            };\n    }\n}\n\ndocStore.DatabaseCommands.DeleteByIndex("AllDocumentsById", new IndexQuery());	0
29919498	29919255	Custom html helper drop down list	public static MvcHtmlString TruncateDropDown(this HtmlHelper helper, string name, ListItem[] values, Object htmlAttributes)\n{\n\n   List<SelectListItem> Textes = new List<SelectListItem>();\n   foreach (ListItem item in values)\n   {\n       SelectListItem selItem = new SelectListItem();\n       if (item.Text.Length <= 20) \n          selItem.Text = item.Text;\n       else \n          selItem.Text = item.Text.Substring(0, 20) + "...";\n                Textes.Add(selItem);\n   }\n\n   return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper,\n                                                            name, \n                                                            Textes,\n                                                            htmlAttributes);\n\n}	0
435528	435379	C# Clear all items in ListView	DataSource = null;\nDataBind();	0
6428984	6428940	How to flatten nested objects with linq expression	myBooks.SelectMany(b => b.Chapters\n    .SelectMany(c => c.Pages\n        .Select(p => b.Name + ", " + c.Name + ", " + p.Name)));	0
22501229	22497946	Multi Date selecter in Asp.Net Calendar	public static List<DateTime> list = new List<DateTime>();\n\nprotected void calDate_DayRender(object sender, DayRenderEventArgs e)\n{\n        if (e.Day.IsSelected == true)\n        {\n            list.Add(e.Day.Date);\n            e.Cell.BackColor = Color.Orange;\n        }\n        Session["SelectedDates"] = list;\n}\n\n\nprotected void calDate_SelectionChanged(object sender, EventArgs e)\n{\n        if (Session["SelectedDates"] != null)\n        {\n            List<DateTime> newList = (List<DateTime>)Session["SelectedDates"];\n            foreach (DateTime dt in newList)\n            {\n                calDate.SelectedDates.Add(dt);\n            }\n            list.Clear();\n        }\n}	0
11989038	11988841	convert website's xml to memory stream	WebRequest request = WebRequest.Create("http://localhost/syn/rss.aspx");\nWebResponse response = request.GetResponse();\nConsole.WriteLine(((HttpWebResponse)response).StatusDescription);\nStream dataStream = response.GetResponseStream();\nreturn dataStream;	0
2048010	2047994	Finding a Particular Word in Querystring	if (Request.QueryString["property"] != null) { ...	0
19973416	19973217	How could you save the text from a Textbox or Label in winforms as an image?	var bitmap = new Bitmap(this.textbox.Width, this.textbox.Height);\nthis.textbox.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));	0
6328268	6292126	Return a recordset as HTML for Oracle	drop table tab1 purge;\ncreate table tab1(col1 char(1), col2 char(1), col3 char(1));\n\ninsert into tab1 values('a','1','A');\ninsert into tab1 values('b','2','B');\ninsert into tab1 values('c','2','C');\ncommit;\n\nselect xmlagg(xmlelement("TR",\n    xmlforest(col1 as "TD",col2 as "TD",col3 as "TD"))).getclobval()\nfrom tab1	0
18792349	18792278	How to to Use Reflection in C# to Execute Method by name?	string MyFunction = "GetAverages";\nMethodInfo mi;\n\nmi = typeof(MyGoldClass).GetMethod(MyFunction);\nint res = (int)mi.Invoke(new MyGoldClass(), null);	0
13275801	13275780	Method to check if a point is in array's bounds	Check<T>(T[,] arr, Point p)	0
29220523	29220302	Find difference between two objects in C#	if (prop.PropertyType.IsGenericType)\n        {\n            if (prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))\n            {\n                Type typeParameter = prop.PropertyType.GetGenericArguments()[0];\n\n                var i = prop.GetValue(initial);\n                var f = prop.GetValue(final);  \n                if(object.Equals(i,f))\n                {\n                    //...\n                }\n            }\n        }	0
10848031	10845898	About Page on Windows 8 application	var settingsFlyout = new SettingsFlyout();\nsettingsFlyout.Content = new YourSettingsControl(); //this is just a regular XAML UserControl\nsettingsFlyout.IsOpen = true;	0
9671480	9670906	Fluent NHibernate DateTime UTC	public class MyClass\n{\n   ...\n\n   //Don't map this field in FluentNH; this is for in-code use\n   public DateTime MyDate \n   {\n      get{return MyDateUTC.ToLocalTime();} \n      set{MyDateUTC = value.ToUniversalTime();}\n   }\n\n   //map this one instead; can be private as well\n   public DateTime MyDateUTC {get;set;} \n}\n\n...\n\npublic class MyClassMap:ClassMap<MyClass>\n{\n   public MyClassMap()\n   {\n      Map(x=>x.MyDateUTC).Column("MyDate");\n\n      //if you made the UTC property private, map it this way instead:\n      Map(Reveal.Member<DateTime>("MyDateUTC")).Column("MyDate");\n   }\n}	0
24558848	24558585	Accessing Managed C++ Struct from C#	public ref class ClassContainingStruct : MyBase\n{\npublic:\n   StructOuter m_strucOuter_InClassContainingStruct;   // Note: no hat\n};	0
21490021	21489799	Foreign Key Mapping	private string _country;\n    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Country", CanBeNull=false)]\n    public string Country\n    {\n        get\n        {\n            return this._country;\n        }\n        set\n        {\n            if ((this._country != value))\n            {\n                this._country = value;\n            }\n        }\n    }	0
26167264	26164975	Manage EF6 database first many to many relationship	[HttpPost]\npublic ActionResult Add(Perfil perfil)\n{\n    if (ModelState.IsValid)\n    {\n        perfil.funcionalidad.Add(db.Funcionalidad.First());\n        db.Perfil.AddObject(perfil);\n        db.SaveChanges();\n        return RedirectToAction("Index");\n    }\n    return View(perfil);\n}	0
18637935	18636218	Redirecting console output to listbox from another thread throws InvalidOperationException	public class ListBoxWriter : TextWriter\n    {\n        private ListBox list;\n        private StringBuilder content = new StringBuilder();\n\n        public ListBoxWriter(ListBox list)\n        {\n            this.list = list;\n        }\n\n        public override void Write(char value)\n        {\n            base.Write(value);\n            content.Append(value);\n            if (value == '\n')\n            {\n                list.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => list.Items.Add(content.ToString())));                    \n                content = new StringBuilder();\n            }\n        }\n\n        public override Encoding Encoding\n        {\n            get { return System.Text.Encoding.UTF8; }\n        }\n    }	0
9618494	9618242	Migradoc Coverpage Picture	var myImage = section.Headers.FirstPage.AddImage("ImageLocation");\nmyImage.Height = "29.7cm";\nmyImage.Width = "21cm";\nmyImage.RelativeVertical = RelativeVertical.Page;\nmyImage.RelativeHorizontal = RelativeHorizontal.Page;\nmyImage.WrapFormat.Style = WrapStyle.Through;	0
19346956	19346899	Constraints on method declared in Interfaces	abstract class MybaseClass()\n{\n    protected virtual int MyMethodInternal(int a, int b){ //this method is not visible to the outside\n     // implementors override this\n    }\n\n    public sealed int MyMethod(int a, int b){ // users call this method\n    var res = MyMethodInternal(a,b);\n    if(res < 10)\n        throw new Exception("bad implementation!");\n    }\n}	0
7267628	7267592	Separating numbers from other signs in a string	string text = "(54&&1)||15";\nRegex pattern = new Regex(@"\(|\)|&&|\|\||\d+");\nMatch match = pattern.Match(text);\nwhile (match.Success)\n{\n    Console.WriteLine(match.Value);\n    match = match.NextMatch();\n}	0
23739728	23739543	WPF Printing window in pdf format	dlg.PrintTicket.PageOrientation = System.Printing.PageOrientation.Landscape;	0
15902058	15901716	The purpose of using both <value> and <summary> tags in Visual Studio XML documentation	List<T>.IList.IsFixedSize Property	0
24503532	24502858	Strange drawing behavior with labels	for (int i = 0; i < ClientLabel.Length; i++)\n   {    \n        // Web browsers\n        WebBrowser wb = new WebBrowser()\n        {\n            ScrollBarsEnabled = false,\n            Height = 12,\n            Width = 12,\n            Location = new Point(2 + WBoffsetX, 2 + WBoffsetY),\n            ScriptErrorsSuppressed = true\n        };\n\n        WBoffsetX += 13;\n        Clients[i] = wb;\n\n        // Labels\n        Label label = new Label()\n        {\n            Name = "label_" + i,\n            Text = "Data",\n            AutoSize = true,\n            Location = new Point(50 + lbloffsetX, 50 + lbloffsetY),\n            Width = 100,\n            Height = 20,\n            Font = new Font("Arial", 12),\n            ForeColor = System.Drawing.Color.White,\n        };\n\n        label.Click += new EventHandler(lbl_click);\n        ClientLabel[i] = label;\n        lbloffsetX += 30;\n    }\n\n    this.Controls.AddRange(Clients);\n    this.Controls.AddRange(ClientLabel);	0
6474014	6473882	Save Color to ViewState	public Color BackColor\n{\n    get { return (Color)(ViewState["BackColor"] ?? Color.White); }\n    set { ViewState["BackColor"] = value; }\n}	0
20097227	19953615	Possible to have wkhtmltopdf log in to umbraco as a member?	// Authentication\nparamsBuilder.Append("--cookie " + System.Web.Security.FormsAuthentication.FormsCookieName + " " + umbraco.library.RequestCookies(System.Web.Security.FormsAuthentication.FormsCookieName) + " ");	0
2262523	2262407	In Gtk, how can I dynamically set a Window's height and width?	Resize (int width, int height)	0
31286967	31281847	Convert VBColor value to HEX value in C#	public static string VBColorToHexConverter(string vbColor) \n{\n  string hexValue;\n  string r = "", g = "", b = "";\n\n  char[] vbValue = vbColor.ToCharArray();\n\n  for (int i = 0; i < vbValue.Length; i++) \n  {\n    r = vbValue[6].ToString() + vbValue[7].ToString();\n    g = vbValue[4].ToString() + vbValue[5].ToString();\n    b = vbValue[2].ToString() + vbValue[3].ToString();\n  }\n\n  hexValue = "#" + r + g + b;\n\n  return hexValue;\n}	0
852968	851683	Finding all non-last sequences in a sequence	data\n    .GroupBy(x => new\n        {\n            x.Col1,\n            x.Col2,\n        })\n    .Select(x => x.MaxBy(y => y.Col3)\n    .ForEach(x =>\n        {\n            x.Col5 = x.Col4,\n        });	0
25812912	25812456	efficiently removing duplicate xml elements in c#	using System.Xml.Linq;\n\nXDocument xDoc = XDocument.Parse(xmlString);\nxDoc.Root.Elements("annotation")\n         .SelectMany(s => s.Elements("image")\n                           .GroupBy(g => g.Attribute("location").Value)\n                           .SelectMany(m => m.Skip(1))).Remove();	0
27364162	27364042	How to Access a Variable in Multiple Methods	private SerialPort seriovyport;\n\npublic void openportbtn_Click(object sender, EventArgs e)\n{\n    seriovyport = new SerialPort(COMtb.Text);\n    seriovyport.Open();\n}\n\npublic void closeportbtn_Click(object sender, EventArgs e)\n{\n    seriovyport.Close();\n}	0
8232413	8232319	Using LINQ to populate a collection from a property that has n elements	var query = from b in originalItems\n            where b.Color == color\n            from item in b.MyItems\n            select new A\n            {\n                MyItems = b.MyItems,\n                Color = b.Color,\n                MyItem = item,\n            };\n\nvar result = query.ToList();	0
23781132	23780833	C# very simple string encryption for game	for (int i = 0; i < message.Length(); i++)\n{\n    if (message[i] < 123 && message[i] > 96)\n    {\n        // 97 to 122 are 'a' to 'z'\n        message[i] += 3;\n\n        if (message[i] > 122)\n        {\n            message[i] -= 26;\n        }\n    }\n}\n\nEDIT: XOR-encryption:\n\nstring codeword = "word";\nstring res = "";\nfor (int i = 0; i < message.Length(); i++)\n{\n    res += (char)(message[i] ^ codeword[i % codeword.Length()]);\n}	0
24968635	24963602	Updating WPF window labels while loading a new window	Private async void DoLoadingTasks()\n{\n     IsBusy = true;\n     await Function1();\n     Status = "step complete";\n     ....\n     IsBusy = false;\n}	0
977178	977159	LINQ to SQL and Null strings, how do I use Contains?	from a in this._addresses\nwhere (a.Street != null && a.Street.Contains(street)) || (a.StreetAdditional != null && a.StreetAdditional.Contains(streetAdditional))\nselect a).ToList<Address>()	0
2375337	2374654	How do you create an indented XML string from an XDocument in c#?	XDocument doc = XDocument.Parse(xmlString);\nstring indented = doc.ToString();	0
18832700	18832623	How to Save Temp Data in MVC	Session["name"] = yourObj;	0
27529740	27528401	Export excel from visul c#	for (int i = 1; i <= 6; i+=2)                 // only for odd rows.\n{\n    string c1 = "A" + i.ToString();\n    string c2 = "J" + i.ToString();\n    oSheet.get_Range(c1, c2).Borders.LineStyle = true;\n}	0
29936167	29936003	Converting datetime format without using SAP RFC with C#	// Parse date and time with custom specifier.\n  string format = "dd.mm.yyyy hh:mm:tt";\n  DateTime date;\n  try {\n     date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);\n  }\n  catch (FormatException e) {\n     throw new ArgumentException("argDate", e);\n  }	0
29636816	29636755	Remove duplicated row from datagridview c#	if(r.Cells[0].Value.ToString() == txtNamn.Text)  // txtnamn is a textbox\n{\n    dublett = true;\n    MessageBox.Show("Varan finns redan, g??r om!");    \n    break;                \n}	0
27386218	27386140	Is it possible to get an item's current index position in a list?	List<ListItem> parentList;\npublic ListItem(List<ListItem> parentList)\n{\n    this.parentList = parentList;\n}\n\npublic override string ToString()\n    { return parentList.IndexOf(this).ToString(); }	0
2127524	2127406	Get Non-Distinct elements from an IEnumerable	var distinctItems = \n    from list in itemsList\n    group list by list.ItemCode into grouped\n    where grouped.Count() > 1\n    select grouped;	0
21621932	21621870	How to prevent user from deleting item by pressing "backspace"?	void OnComboPreviewKeyDown(object sender, KeyEventArgs e) { \n  if (e.Key == Key.Back) { \n    e.Handled = true;\n  }\n}	0
11721810	11721749	String.Format with SelectMany	String.Format("All Strings : {0} on {1}",\n     String.Join(", ", MyObject.MyDictionary.Select(x => x.Key)),\n     MyObject.Type);	0
24697017	24696991	Linq datetime date match in query c#	LevyServiceHelper.GetAllLevyFee().\nList.Where(s=>s.ValidDate.Year == DateTime.Today.Year).ToList();	0
664842	664819	C# Windows Mobile datagrid data	myTable.Rows.Add(dRow);	0
25714463	25714373	Convert a List<int> to a List<Point> with LINQ	var points = coords.Select((v,i) => new {v,i})\n    .GroupBy(x => x.i/2)\n    .Select(x => new Point(x.First().v, x.Last().v))\n    .ToList();	0
12998736	12998718	Convert date retrieved from SQL server to string in MM/dd/yyyy	string date1= date.ToString("dd-MM-yyyy");	0
16506105	16505648	Extracting a URL in the query part of another URL	using System;\nusing System.Web;\n\n\nclass MainClass\n{\n    public static void Main (string[] args)\n    {\n        Uri uri = new Uri("https://www.google.com/url?q=http://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX");\n        Uri doc = new Uri (HttpUtility.ParseQueryString (uri.Query).Get ("q"));\n        Console.WriteLine (doc);\n    }\n}	0
7153921	1335419	How can I make sure that FirstOrDefault<KeyValuePair> has returned a value	var matchedDays = days.Where(x => sampleText.Contains(x.Value));\nif (!matchedDays.Any())\n{\n    // Nothing matched\n}\nelse\n{\n    // Get the first match\n    var day = matchedDays.First();\n}	0
15112263	15111612	sort a list using a comparison list	matrix.Sort(delegate(List<double> l1, List<double> l2)\n            {\n               return l1[0].CompareTo(l2[0]);\n            });	0
21981683	21981510	How to download a zip file from link (ftp) and pass username and password?	using (var client = new WebClient())\n{            \n  client.Credentials = new NetworkCredential(ftpUserName, ftpPassword);\n  client.DownloadFile(url, filename);\n}	0
10596386	10596367	Generics: how to implement: "where T derives from xxx"	public class Manager<T> where T : BaseClass	0
1544698	1544647	How do I test a third party framework when I need to pass in an HttpResponse	var fake = Isolate.Fake.Instance<HttpResponse>();\nIsolate.WhenCalled(() => HttpContext.Current.Response).WillReturn(fake);	0
27615190	27615116	Find the nth element in a tribonacci series	private static int NTerm_Tribonacci(int term)\n    {\n        int a = 0;\n        int b = 1;\n        int c = 1;\n        int result = 0;\n\n        if (term == 0) result = a;\n        if (term == 1) result = b;\n        if (term == 2) result = c;\n\n        while(term > 2)\n        {\n            result = a + b + c;\n            a = b;\n            b = c;\n            c = result;\n            term--;\n        }\n\n        return result;           \n    }	0
23198045	23198010	How to check if a Folder exists in Computer desktop from C#?	if (!Directory.Exists(Path.Combine(desktopPath, "Test"))\n{\n     //directory doesn't exist\n}	0
28043084	28036946	In WPF two-way binding, how can you check if it was a UI element or ViewModel that triggered the binding change?	bool _isBeingSetByVM;\n\npublic int Number\n{\n    get { return _number; }\n    set\n    {\n        if (_isBeingSetByVM)\n        {\n            // ViewModel has set the property\n            // Do whatever you need to do...\n            _isBeingSetByVM = false;\n        }\n\n        if (_number != value)\n        {\n            _number = value;\n            OnPropertyChanged("Number");  // generate PropertyChanged event\n        }\n    }\n}\nint _number;\n\nvoid SomeMethodInVM()\n{\n    _isBeingSetByVM = true;\n    Number = 42;\n}	0
34247054	34247016	Connection string to connect to MySql database?	server=localhost;uid=root;pwd=YOURPASSWORDHERE;database=YOURDATABASENAMEHERE;	0
22065244	22011897	Format Excel Pie of Pie Chart with C#	myChart.Activate();\n        Excel.ChartGroup group = chartPage.ChartGroups(1);\n        //put the last 3 values in the second pie\n        group.SplitValue = 3;	0
28437250	28437096	How do I programmatically change the Title in a wpf window?	this.Title = "Something new";	0
31462217	31460653	Quote original message in a reply using mailkit	string QuoteMessageBody (MimeMessage message)\n{\n    using (var quoted = new StringWriter ()) {\n        quoted.WriteLine ("On {0}, {1} wrote:", message.Date.ToString ("f"), message.From.ToString ());\n        using (var reader = new StringReader (message.TextBody)) {\n            string line;\n\n            while ((line = reader.ReadLine ()) != null) {\n                quoted.Write ("> ");\n                quoted.WriteLine (line);\n            }\n        }\n\n        return quoted.ToString ();\n    }\n}	0
12919069	12919045	Control event to distinguish designer from runtime	if(!DesignMode)\n{\n\n\n}	0
20973361	20972756	Wait until a BlockingCollection queue is cleared by a background thread, with a timeout if it takes too long?	var timeout = TimeSpan.FromMilliseconds(10000);\nT item;\nwhile (_blockingCollection.TryTake(out item, timeout))\n{\n     // do something with item\n}\n// If we end here. Either we have a timeout or we are out of items.\nif (!_blockingCollection.IsAddingCompleted)\n   throw MyTimeoutException();	0
31201577	31201454	Create wave file from a string	byte[] waveBytes = System.Convert.FromBase64String(base64EncodedData);	0
7197216	7196692	How to set the BackImage of a ChartArea at run time?	Chart.ChartAreas[0].BackImage = imagePath;	0
6860430	6844098	When using windbg is there a way to break on a specific CLR exception	!soe System.AppDomainUnloadedException 1	0
15844582	15830572	XML Parsing with same tag	var values = doc.Descendants("step")\n            .Where(step => new[] { "1", "2" }.Contains(step.Attribute("id").Value)) //only step 1 & 2\n            .Select(step => step.Descendants("text").Select(text => text.Value).ToList());	0
3538787	3535714	I have .H file, how to open its public methods to .Net library?	namespace MyNamespace\n{\n    public ref class VideoEncoder\n    {\n        // Existing contents of VideoEncoder class\n    }\n}	0
12685663	12685369	Filter List from comparing two List with some condition	var CampList  = from data in str\n                from offer in sploffer\n                where offer.CampaignId != data.CampaignId\n                select offer;\n\n//in case you want to materialize it,\n//or in case you really need a list,\n//but this could be unnecessary\nCampList = CampList.ToList();	0
13067754	13066246	DataGridview search: show only searchresult and hide other rows?	for (int i = 0; i < dgTest.Rows.Count; i++)\n{\n    if (dgTest.Rows[i].Cells[0].Value.ToString() == "search")\n    {\n        dgTest.Rows[i].Selected = true;\n        dgTest.Rows[i].Visible = true;\n    }\n    else\n    {\n        dgTest.Rows[i].Visible = false;\n        dgTest.Rows[i].Selected = false;\n    }\n}	0
3907605	3907548	LINQ- Ordering a list of objects based on a particular value	var passed = StudList.Where(student => student.StatusResult == ResultStatus.Passed);\nvar failed = StudList.Where(student => student.StatusResult == ResultStatus.Failed);\n\nConsole.WriteLine("Passed...");\nforeach(var student in passed)\n   Console.WriteLine(student.Detail.Name);\n\nConsole.WriteLine("Failed...");\nforeach(var student in failed)\n   Console.WriteLine(student.Detail.Name);	0
9220954	9220920	C# lambda simplification	var player = players.Find(p => p.Id == tempId);\nplayer.shots.Add(new Shot(player.yPos));	0
2325294	2325289	concatenate characters and convert to int	int i1 = Convert.ToInt32(s1.Substring(0, 2));\nint i2 = Convert.ToInt32(s2.Substring(0, 2));	0
8927765	8927309	Retrieving custom Active Directory properties of users	DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");\n\n//Create a searcher on your DirectoryEntry\nDirectorySearcher adSearch= new DirectorySearcher(directoryEntry);\nadSearch.SearchScope = SearchScope.Subtree;    //Look into all subtree during the search\nadSearch.Filter = "(&(ObjectClass=user)(sAMAccountName="+ username +"))";    //Filter information, here i'm looking at a user with given username\nSearchResult sResul = adSearch.FindOne();       //username is unique, so I want to find only one\n\nif (sResult.Properties.Contains("company"))     //Let's say I want the company name (any property here)\n{\n    string companyName = sResult.Properties["company"][0].ToString();    //Get the property info\n}	0
23017508	23017452	How to unit test overloaded constructor for ArgumentNullException where each constructor only has one parameter	var c = new MyClass((Entity)null);\nvar cl = new MyClass((IList<Entity>)null);	0
22040369	22040152	Showing a selected value in combobox fetched from database	comboBox1.SelectedIndex = comboBox1.FindString("Sold");	0
30231	30188	How can I format a javascript date to be serialized by jQuery	string dateString = "5/1/2008 8:30:52 AM";\nDateTime date1 = DateTime.Parse(dateString, CultureInfo.InvariantCulture);	0
10095383	10095360	How do I add another where clause on this foreach?	foreach (Point point in _Points.Where(x => x.Name == "Test" && !x.Asset.StartsWith("INV"))\n{	0
8763264	8762523	How do you let the arrow keys move your focus around in WinForms TableLayoutPanel?	using System;\nusing System.Windows.Forms;\n\nclass MyLayoutPanel : TableLayoutPanel {\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        var ctl = this.FindForm().ActiveControl;\n        if (ctl.Parent == this) {\n            int col = this.GetColumn(ctl);\n            int row = this.GetRow(ctl);\n            if (keyData == Keys.Left && col > 0) {\n                var newctl = this.GetControlFromPosition(col - 1, row);\n                if (newctl != null) newctl.Focus();\n                return true;\n            }\n            // etc..\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n}	0
29968597	29967880	Access tmp directory in iOS 8 with Xamarin.iOS	var documents = NSFileManager.DefaultManager\n    .GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0].Path;\n\nvar tmp = Path.Combine(documents, "../", "tmp");	0
17094589	17094518	How can i use a where clause within a select statement in linq. (ie. on a property.)	Cato = c.dcKey == 6 ? c.totalOnHandQuantity : 0,\nKerry = c.dcKey == 7 ? c.totalOnHandQuantity : 0	0
4138613	4138469	Can't get value from selected item in listview WPF	var selectedStockObject = lvwInventory.SelectedItems[0] as StockObject;\nif(selectedStockObject == null)\n{\n   return;\n}\n\nkey = selectedStockObject.ID; //I'm assuming you want the ID as your key	0
3834435	3834257	How to detect if application is activated by clicking in the taskbar	protected override void WndProc(ref Message m) {\n        base.WndProc(ref m);\n        // Trap WM_ACTIVATE when we get active\n        if (m.Msg == 6 && m.WParam.ToInt32() == 1) {\n            if (Control.FromHandle(m.LParam) == null) {\n                Console.WriteLine("activated from another process");\n            }\n        }\n    }	0
11259499	11259483	I can't find "Include" method with lambda expression in Entity framework?	using System.Data.Entity	0
33557047	33556437	Running Sql Server Agent Jobs from C#	job.Start();\n        do\n        {\n            Thread.Sleep(1000);\n            job.Refresh();\n        } while (job.CurrentRunStatus == JobExecutionStatus.Executing);	0
9926284	9926095	Get dates from the current calendar month and the next 11 coming months	var acceptableFirstDate = DateTime.Today;\nif (DateTime.Today.Day > 1)\n{\n    acceptableFirstDate = DateTime.Today.AddDays(-DateTime.Today.Day + 1);\n}\nvar acceptableLastDate = acceptableFirstDate.AddMonths(12).AddDays(-1);\n\nvar result = dates\n    .Where(x => x >= acceptableFirstDate && x <= acceptableLastDate)\n    .GroupBy(x => x.Month);	0
3176776	3176769	Encrypting a string over network, c#	Convert.ToBase64String	0
18792501	18791686	How to manage resources in a console app that creates main window in main()?	ResourceDictionary dict = new ResourceDictionary();\n            dict.Source = new Uri("../Resources/PageDictionary.xaml", UriKind.Relative); \n            Application.Current.Resources.MergedDictionaries.Add(dict);	0
11005696	11005640	HTML Agility Pack issue finding divs	from completeHomepage in document.DocumentNode.Descendants("div")\nwhere completeHomepage.Attributes["class"] != null &&\n      completeHomepage.Attributes["class"].Value == "content" &&\n      completeHomepage.Attributes["class"].Value != null\nselect completeHomepage.InnerHtml;	0
9896579	9895428	Linq - How to get all children	join fetch	0
16952915	16950615	Async Socket receiving data in the wrong order or missing	.NET receive message 1\n.NET receive message 2\n.NET finish receive message 2\n.NET finish receive message 1	0
28798972	28798631	Pass the Selected Value in DataGridView to ComboBox	int index = cboSection.FindString(row.Cells["section"].Value.ToString());\nif(index > -1)\n{\n   cboSection.SelectedIndex = index;\n}\nelse\n{\n        object newSection = row.Cells["section"].Value.ToString();\n        cboSection.Items.Add(newSection);\n        cboSection.SelectedItem = newSection;\n}	0
29790200	29790137	c# Regex- Remove string which developed only combination of special charter	.*[A-Za-z0-9].*	0
1528852	1526813	AutoMapper - setting destination string to null actually makes it string.Empty	Mapper.Initialize(x =>\n{\n    x.AddProfile<UIProfile>();\n    x.AddProfile<InfrastructureProfile>();\n    x.AllowNullDestinationValues = true; // does exactly what it says (false by default)\n});	0
1227745	1227716	How to call javascript function on a select elements selectedIndexChange	riskFrequencyDropDown.Attributes.Add("onchange",\n             "updateRiskFrequencyOfPointOnMap('"\n                  + riskFrequencyDropDown.ID.Substring(8)\n                  + "','"\n                  + riskFrequencyDropDown.SelectedValue +"');");	0
21585852	21569019	kendo ui grid column names at 90 degree vertical in grid header	#grid .k-grid-header {\n  padding-left: 17px;\n}\n\n#grid .k-grid-header tr:first{\n  height: 150px;\n}\n\n#grid .k-grid-header .k-header{\n  -webkit-transform: rotate(-90deg);\n  -moz-transform: rotate(-90deg);\n  -ms-transform: rotate(-90deg);\n  -o-transform: rotate(-90deg);\n  height: 150px !important;\n  width: 130px !important;\n}	0
13464025	13440185	Search for files in machine in metro app using C#	async Task<IEnumerable<StorageFile>> FindMusicFiles()\n{\n    var folderPicker = new FolderPicker()\n    {\n        CommitButtonText = "Yippie!",\n        SuggestedStartLocation = PickerLocationId.ComputerFolder,\n        ViewMode = PickerViewMode.List\n    };\n\n    folderPicker.FileTypeFilter.Add("*");\n    StorageFolder folder = await folderPicker.PickSingleFolderAsync();\n\n    if (folder != null)\n    {\n       StorageFileQueryResult queryResult = folder.CreateFileQuery();\n       queryResult.ApplyNewQueryOptions(new QueryOptions(CommonFileQuery.OrderByName, new[] { ".mp3" }));\n       IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();\n       return files;\n    }\n\n    return new StorageFile[] { };\n}	0
6349733	6349526	How to put three files into one in c#?	static void Append(Stream source, Stream target)\n    {\n        BinaryWriter writer = new BinaryWriter(target);\n        BinaryReader reader = new BinaryReader(source);  \n        writer.Write((long)source.Length);\n        byte[] buffer = new byte[1024];\n        int read;\n        do\n        {\n            read = reader.Read(buffer, 0, buffer.Length);\n            writer.Write(buffer, 0, read);\n        }\n        while (read > 0);\n        writer.Flush();\n    }\n\n    static Stream ReadNextStream(Stream packed)\n    {\n        BinaryReader reader = new BinaryReader(packed);\n        int streamLength = (int)reader.ReadInt64();\n\n        MemoryStream result = new MemoryStream();\n        byte[] buffer = new byte[streamLength];\n        reader.Read(buffer, 0, buffer.Length);\n\n        BinaryWriter writer = new BinaryWriter(result);\n        writer.Write(buffer, 0, buffer.Length);\n        writer.Flush();\n\n        result.Seek(0, SeekOrigin.Begin);\n        return result;\n    }	0
20635855	20635396	How to deserialize a client xml of class type defined in WCF service	string xml = "<NafDetails>"+\n                  "<NafInfo_NafNumber>Test</NafInfo_NafNumber>"+\n                   "<NafInfo_CFAcctNum>New</NafInfo_CFAcctNum>"+\n                   "<NafInfo_RepNum>Demo</NafInfo_RepNum>"+\n                     "<NafInfo_FASIRIA>0</NafInfo_FASIRIA>"+\n                  "<NafInfo_OutsideRIA>0</NafInfo_OutsideRIA>"+\n                "</NafDetails>";\n\n    NafDetails nafdetail;\n    XmlSerializer serializer = new XmlSerializer(typeof(NafDetails));\n    nafdetail = (NafDetails) serializer.Deserialize(XmlReader.Create(new StringReader(xml)));	0
4352052	4352035	Am I doing something wrong with my orders of operations?	Debug.WriteLine(((((programdirs.Length * (float)100) / totaldirs) * (float)100) / this.Height) * (float)100);	0
2316637	1277691	How to retrieve the scrollbar position of the webbrowser control in .NET	Dim htmlDoc As HtmlDocument = wb.Document\nDim scrollTop As Integer = htmlDoc.GetElementsByTagName("HTML")(0).ScrollTop	0
20797911	20797866	How to add arithmetic operator in SQL reader in C#	string UniIDSQL = "SELECT ISNULL(MAX(CAST(INV_TRANS_ID AS INT)),0) + 1 AS TRANSID FROM  CIMProRPT01.dbo.OTH_INV_TRANSACTION";	0
20925692	20925638	Add integer to name	TabPage tab = new TabPage();\ntab.Name = "tab" + tabs;//"tab"+tabIndex maybe more meaningful	0
442785	442699	Returning a variable sized array of doubles from C++ to C# - a simpler way?	Marshal.Copy( source, destination, 0, size );	0
31656081	31655565	Howto fix Backgroundcolor bleeding in bordered ToolStripStatusLabel	private void toolStripStatusLabel1_Paint(object sender, PaintEventArgs e)\n{\n    // Use the sender, so that you can use the same event handler for every label\n    ToolStripStatusLabel label = (ToolStripStatusLabel)sender;\n    // Background\n    e.Graphics.FillRectangle(new SolidBrush(label.BackColor), e.ClipRectangle);\n    // Border\n    e.Graphics.DrawRectangle(\n        new Pen(label.ForeColor),  // use any Color here for the border\n        new Rectangle(e.ClipRectangle.Location,new Size(e.ClipRectangle.Width-1,e.ClipRectangle.Height-1))\n    );\n    // Draw Text if you need it\n    e.Graphics.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), e.ClipRectangle.Location);\n}	0
1663812	1650357	How can I underline some part of a multi-line text with GDI?	Dim fntNormal As New Font(myFontFamily, myFontSize, FontStyle.Regular, GraphicsUnit.Pixel)\n  Dim fntUnderline As New Font(myFontFamily, myFontSize, FontStyle.Underline, GraphicsUnit.Pixel)\n\n  g.DrawString("This is ", fntNormal, Brushes.Black, rctTextArea)\n  w1 = g.MeasureString("This is ", fntNormal).Width\n  w2 = g.MeasureString("underlined", fntUnderline).Width\n  If w1 + w2 > rctTextArea.Width Then\n     yPos = rctTextArea.Y + g.MeasureString("This is ", fntNormal).Height + 5\n     xPos = rctTextArea.X\n  Else\n     yPos = rctTextArea.Y\n     xPos = 0\n  End If\n\n  g.DrawString("underlined", fntUnderline, Brushes.Black, xPos, yPos)\n\n  w1 = g.MeasureString("underlined", fntUnderline).Width\n  w2 = g.MeasureString(", and this is not.", fntNormal).Width\n\n  If w1 + w2 > rctTextArea.Width Then\n     yPos += g.MeasureString("underlined", fntUnderline).Height + 5\n     xPos = rctTextArea.X\n  Else\n     xPos = 0\n  End If\n\n\n  g.DrawString(", and this is not.", fntNormal, Brushes.Black, xPos, yPos)	0
2151707	2151654	Searching in side an object's list of objects using lambda expressions?	string tagName = "tag-to-search-for";\nvar query = Blog.Where(blog => blog.Tag.Any(tag => tag.Name == tagName));	0
24577448	24573337	C# Deedle sort by multiple columns	FrameExtensions.SortRows	0
27569199	27551768	Unable to display image from Sqlite to wpf window	using (MemoryStream ImgMs = new MemoryStream(ResultBytes))\n{\n    BImg.BeginInit();\n    BImg.CacheOption = BitmapCacheOption.OnLoad;\n    BImg.StreamSource = ImgMs;\n    BImg.EndInit();\n}	0
19243148	19242046	Split a text into words: Separators	char.IsSeparator()	0
23128024	23127788	How to reload a Windows phone application page without creating a new copy in the memory?	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n   if (NavigationContext.QueryString.ContainsKey("logedin"))\n   {\n       NavigationService.RemoveBackEntry();\n   }\n}	0
17507840	17389403	Windows search - full text search in c#	string connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";\nOleDbConnection connection = new OleDbConnection(connectionString);\n\nstring query = @"SELECT System.ItemName FROM SystemIndex " +\n   @"WHERE scope ='file:" + System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "' and FREETEXT('dummy')";\nOleDbCommand command = new OleDbCommand(query, connection);\nconnection.Open();\n\nList<string> result = new List<string>();\n\nOleDbDataReader reader = command.ExecuteReader();\nwhile (reader.Read())\n{\n    result.Add(reader.GetString(0));\n}\n\nconnection.Close();	0
13412639	13409179	How to add a column to a database table using Subsonic?	del /q "DAL\*.*"\n"..\..\ExternalResources\lib\sonic.exe" generate /out "DAL"\npause	0
15446343	15446174	how do get rowindex from Gridview Textbox in focus event in asp.net C#	private void getCurrentCellButton_Click(object sender, System.EventArgs e)\n{\n  string msg = String.Format("Row: {0}, Column: {1}",\n    dataGridView1.CurrentCell.RowIndex,\n    dataGridView1.CurrentCell.ColumnIndex);\n  MessageBox.Show(msg, "Current Cell");\n}	0
5169721	5169680	Unquote string in C#	.Trim('"')	0
8671674	8671525	Dynamic property evaluation	public class MissingPropertyChain : DynamicObject\n{\n    private string property;\n\n    public MissingPropertyChain(string property)\n    {\n        this.property = property;\n    }\n\n    public override bool TryGetMember(GetMemberBinder binder, out object result) \n    {\n        if(binder.Name == "ToString")\n            result = "Missing property: " + property;\n        else\n            result = new MissingPropertyChain( property + "." + binder.Name;\n\n        return true;\n    }\n}	0
16580011	16579937	A Recipe Database Model Advice	RecipieIngredients -> Recipe (FK), Ingredient (FK), IngredientQuantity\n                      Key over (Recipe, Ingredient)	0
5810907	5810879	Change Colour of Group Box Group Title Name	groupBox1.ForeColor = Color.Red;	0
21856505	21856448	DateTime to Datetime2	DateTime value = dtCastFrom.Value;	0
3016263	3014170	How to handle bitmaps in WPF?	byte[] pixelData = DrawYourPicture();\n\n int stride = width * PixelFormats.Pbgra32.BitsPerPixel/8;\n BitmapSource bmpSource = BitmapSource.Create(width, height, 96, 96,\n                PixelFormats.Pbgra32, null, pixelData, stride);	0
27316989	27316393	Rotate a bitmap stored in a 1D array	// _pixelData is the source array _pixelDataRotated the target array\nfor (int x = 0; x < width; x++)\n  for (int y = 0; y < height; y++)\n     _pixelDataRotated[y + x * height] = _pixelData[x + y * width];	0
3862678	3862589	Tricky one here - Trying to go through a loop and only return values where them values are equal to another loop	foreach (Admin.DTO.SiteMap t in sites)\n    {\n        flg = false;\n        for each (Admin.DTO.SmallSites f in smallsites)\n            if (t.Title == f.Title) flg = true;\n        if (flg)\n        {\n            myString1.Append(" <input type='checkbox'  checked='yes' value='"     +           t.Title + "'/> ");\n            myString1.Append(t.Title);\n        }\n        else {\n\n            myString1.Append(" <input type='checkbox'  value='" + t.Title +        "'/> ");\n            myString1.Append(t.Title);\n        }\n    }	0
27991547	27971654	SQL Server SUM function with single precision	[Serializable]\n[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(\n    Format.Native,\n    IsInvariantToDuplicates = false,\n    IsInvariantToNulls = true,\n    IsInvariantToOrder = true,\n    IsNullIfEmpty = true,\n    Name = "SumReal")]\npublic struct SumReal\n{\n    private Single sum;\n\n    public void Init()\n    {\n        sum = 0;\n    }\n\n    public void Accumulate(SqlSingle Value)\n    {\n        if (!Value.IsNull)\n        {\n            sum += (Single)Value;\n        }\n    }\n\n    public void Merge(SumReal Group)\n    {\n        sum += (Single)Group.sum;\n    }\n\n    public SqlSingle Terminate()\n    {\n        // Put your code here\n        return sum;\n    }\n}	0
20608486	20607511	Trouble with Comboboxes	private void cboSelectEmp_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (!string.IsNullOrEmpty(cboSelectEmp.Text))\n            SelectEmployeeInfo();\n    }\n\n    private void SelectEmployeeInfo()\n    {\n        string input = cboSelectEmp.Text.Trim();\n        string[] inputs = input.Split(' ');\n        string formFirstNameValue = inputs[0];\n        string formLastNameValue = (inputs.Count() > 1) ? inputs[1].Replace(",", "") : string.Empty;\n        txtFirstName.Text = formFirstNameValue;\n        txtLastName.Text = formLastNameValue;\n    }	0
21644838	21644612	How to add sumarry to method	csc yourclass.cs /doc:out_file.xml	0
10874594	10858229	Silverlight Gridview - Update Groups upon property change	// The following will fail to regroup\n        //(MyItems[3] as TestClass).Category = "D";\n\n        // The following works\n        MyItems.EditItem(MyItems[3]);\n        (MyItems[3] as TestClass).Category = "D";\n        MyItems.CommitEdit();\n\n        // The following will also fail to regroup            \n        //(MyItems[3] as TestClass).Category = "D";\n        //items[3] = items[3];\n\n        // fails as well, surprisingly\n        //(MyItems[3] as TestClass).Category = "D";\n        //TestClass tmp = items[3];\n        //items.RemoveAt(3);\n        //items.Insert(3, tmp);	0
9841892	9841485	WCF Application & WCF Service Library understanding	var host = new ServiceHost(typeof(ServiceClassToHost));\n host.Open();	0
5346764	5346743	Is there an easier way of writing base 2 numbers in Flags?	public enum Foo\n    {\n        Bar  = 1 << 0,\n        Baz  = 1 << 1,\n        Quux  = 1 << 2,\n        Etc  = 1 << 3\n    }	0
11289370	11288569	Crystal report in C # need log on	ReportDocument rpt = new ReportDocument();\n        rpt.Load(@"C:\CrystalReport1.rpt");\n\n        ConnectionInfo crConnectionInfo = new ConnectionInfo();\n        crConnectionInfo.ServerName = "SERVERNAME";\n        crConnectionInfo.DatabaseName = "DATABASENAME";\n        crConnectionInfo.UserID = "USERNAME";\n        crConnectionInfo.Password = "PASSWORD";\n        crConnectionInfo.IntegratedSecurity = false;\n\n        TableLogOnInfos crTableLogonInfos = new TableLogOnInfos();\n        TableLogOnInfo crTableLogonInfo = new TableLogOnInfo();\n        Tables CrTables;\n        CrTables = rpt.Database.Tables;\n\n        foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in CrTables)\n        {\n            crTableLogonInfo = crTable.LogOnInfo;\n            crTableLogonInfo.ConnectionInfo = crConnectionInfo;\n            crTable.ApplyLogOnInfo(crTableLogonInfo);\n        }\n        crystalReportViewer1.ReportSource = rpt;\n        crystalReportViewer1.Refresh();	0
20033781	20033133	ASP MVC API IEnumerable JSON array missing key name	return new { inventory = from i in db.Inventories\n        select new InventoryDTO() { id = i.InventoryId, createdate = i.CreateDate ?? DateTime.MinValue, descrip = i.Descriptions,\n            itemid = i.ItemDetail, gtin = i.GTIN, lastcost = i.LastCost };	0
19535283	19535033	Fill Listbox with values from TextFile	// Open the file to read from. \n string[] readText = File.ReadAllLines(fileName);\n        foreach (string fileText in readText)\n        {\n            _commandList.Add(fileText);\n        }	0
10900078	10899568	Count distinct values of a column in dataGridView using linq in .NET	var result = dataGridView1.Rows.Cast<DataGridViewRow>()\n    .Where(r => r.Cells[0].Value != null)\n    .Select (r => r.Cells[0].Value)\n    .GroupBy(id => id)\n        .OrderByDescending(id => id.Count()) \n        .Select(g => new { Id = g.Key, Count = g.Count() });	0
9249137	9000555	Timer triggering update panel update causing loss of focus	if(!isPostback)\n{\n   txtBox.Focus();\n}	0
5764025	5763877	how to remove blank lines from richbox	rtb.Text = Regex.Replace(rtb.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);	0
28307536	28307367	Save Collection As JSON with Entity Framework	public class Company\n{\n\n    public int Id {get;set;}\n\n    public string Name {get;set;}\n\n    [NotMapped]\n    public List<DateTime> Times {get;set;}\n\n    [Column("Times")]\n    public string TimesSerialized\n    {\n        get\n        {\n            return JsonConvert.SerializeObject(Times);\n        }\n        set\n        {\n            Times = string.IsNullOrEmpty(value)\n                    ? new List<DateTime>()\n                    : JsonConvert.DeserializeObject<List<DateTime>>(value);\n        }\n    }\n}	0
940217	938896	Flickering in listview with ownerdraw and virtualmode	protected override void WndProc(ref Message m) {\n    switch (m.Msg) {\n        case 0x0F: // WM_PAINT\n            this.isInWmPaintMsg = true;\n            base.WndProc(ref m);\n            this.isInWmPaintMsg = false;\n            break;\n        case 0x204E: // WM_REFLECT_NOTIFY\n            NativeMethods.NMHDR nmhdr = (NativeMethods.NMHDR)m.GetLParam(typeof(NativeMethods.NMHDR));\n            if (nmhdr.code == -12) { // NM_CUSTOMDRAW\n                if (this.isInWmPaintMsg)\n                    base.WndProc(ref m);\n            } else\n                base.WndProc(ref m);\n            break;\n        default:\n            base.WndProc(ref m);\n            break;\n    }\n}	0
22630777	22630598	Stop the background worker from other project	for(int i=0; i<newDataCount; i++)\n{\n  if(backgroundWorker.CancellationPending)\n  {\n    return;\n  }	0
1530914	1530748	A case-insensitive list	public class Set<T> : KeyedCollection<T,T>\n{\n    public Set()\n    {}\n\n    public Set(IEqualityComparer<T> comparer) : base(comparer)\n    {}\n\n    public Set(IEnumerable<T> collection)\n    {\n        foreach (T elem in collection)\n        {\n            Add(elem);\n        }\n    }\n\n    protected override T GetKeyForItem(T item)\n    {\n        return item;\n    }\n}	0
13930991	13930874	How correctly sort a list<string> with numbers?	List<string> tab_num = new List<string>();\n        tab_num.Add("A.3.2.1");\n        tab_num.Add("A.3.3.1");\n        tab_num.Add("A.1.0.1");\n        tab_num = tab_num.OrderBy(num => num).ToList();	0
5071355	5071288	Regular Expression to extract Shipping Cost	var regPattern = "stock\":\"(.*?)\",\".*?shipping\":\"(?:(?:\\$([0-9]*\\.[0-9]*)|(free Shipping)).*?)\",\".*?finalPrice\":\"(.*?)\"";\n\nstring val1 = data.Groups[1].Value.ToString();  // In stock. Limit 5 per customer.\nstring val2 = data.Groups[2].Value.ToString();  // 19.99 \nstring val3 = data.Groups[3].Value.ToString();  // free Shipping            \nstring val4 = data.Groups[4].Value.ToString();  // 139.99	0
20978246	20977955	Remove a single Special Character from a String	mystring = mystring.Replace("\x92", "");	0
704113	703668	Advantages and usefulness of adding an XML file to a Visual Studio 2008 project	Assembly a = Assembly.GetExecutingAssembly();\nif(a != null)\n{\n  Stream s = a.GetManifestResourceStream(typeof(yourType), "YourXmlName.xml");\n\n  if (s != null)\n  {\n    String xmlContents = new StreamReader(s).ReadToEnd();\n  }\n}	0
17328577	17328106	C# Interop.Word 2013 replacing substring format MULTIPLE TIMES within one line	int i = 0;\nint index = text.IndexOf("color", i);\nwhile (index > 0) \n{\n    object oStart = parag.Range.Start + index;\n    object oEnd = parag.Range.Start + index + 4;\n\n    Range subRange = doc.Range(oStart, oEnd);\n    subRange.Bold = 1;\n\n    i = index + 4;\n    index = text.IndexOf("color", i);\n}	0
2118459	2118452	How to identify whether folder is opened?	bool iHaveAccess = CheckAccess(folder);\nif (iHaveAccess)\n{\n    RenameFolder(folder,newFolderName);\n}	0
5398670	5398647	How can I verify a socket listener?	netstat -an	0
29847373	29810875	Adding a custom attribute to a return value using a ParameterBuilder; attribute doesn't show when reflected -- why?	var returnCustomAttributes = type.GetMethod("Invoke").ReturnParameter.GetCustomAttributes(typeof(MarshalAsAttribute), false);	0
34076894	34075880	Encode string URL without using HttpServerUtility	var urlAbsoluteSample = "http://stackoverflow.com/questions/34075880/encode-string-url-without-using-httpserverutility?noredirect=1#comment55905829_34075880";\nvar labelText = "Encoded absolute URL: " + Uri.EscapeDataString(urlAbsoluteSample);	0
16942134	16941974	Implement C# interface in an unmanaged cpp dll	public interface IDirectory\n{\n    bool IsDirectoryEmplty(string path);\n}\n\npublic class Directory : IDirectory\n{\n    [DllImport("Shlwapi.dll", EntryPoint = "PathIsDirectoryEmpty")]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    public static extern bool IsDirectoryEmplty([MarshalAs(UnmanagedType.LPStr)]string directory);\n\n    bool IInterface.IsDirectoryEmplty(string path)\n    {\n        return IsDirectoryEmplty(path);\n    }\n}	0
13774012	13773909	Getting the name of the node and its corresponding values in xml using linq to xml in c#?	var doc = XDocument.Parse(@"\n         <root>\n            <firstname>Lucas</firstname>\n            <lastname>Ontivero</lastname>\n         </root>");\n    var qry = from element in doc.Element("root").Descendants() select element;\n    var result = qry.ToDictionary(e => e.Name, e => e.Value);\n    result.ToList().ForEach(x=> Console.WriteLine("{0}:{1}", x.Key, x.Value ));	0
7237244	7237197	Reading attribute of a property using reflection	using System;\nusing System.Reflection;\n\npublic class Myproperty\n{\n    private string caption = "Default caption";\n    public string Caption\n    {\n        get{return caption;}\n        set {if(caption!=value) {caption = value;}\n        }\n    }\n}\n\nclass Mypropertyinfo\n{\n    public static int Main(string[] args)\n    {\n        Console.WriteLine("\nReflection.PropertyInfo");\n\n        // Define a property.\n        Myproperty Myproperty = new Myproperty();\n        Console.Write("\nMyproperty.Caption = " + Myproperty.Caption);\n\n        // Get the type and PropertyInfo.\n        Type MyType = Type.GetType("Myproperty");\n        PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");\n\n        // Get and display the attributes property.\n        PropertyAttributes Myattributes = Mypropertyinfo.Attributes;\n\n        Console.Write("\nPropertyAttributes - " + Myattributes.ToString());\n\n        return 0;\n    }\n}	0
4392460	4392147	TreeView Control similar to that of utorrent	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass MyTreeView : TreeView {\n    protected override void OnHandleCreated(EventArgs e) {\n        if (Environment.OSVersion.Version.Major >= 6) {\n            SetWindowTheme(this.Handle, "Explorer", null);\n        }\n        base.OnHandleCreated(e);\n    }\n    [DllImportAttribute("uxtheme.dll", CharSet = CharSet.Auto)]\n    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);\n}	0
21432702	21432253	How to delete text between two bookmarks in word with c#	_Application app = new Application();\n        try\n        {\n            _Document doc = app.Documents.Open("c:\\xxxx\\doc.doc");\n            try\n            {\n                Range delRange = doc.Range();\n                delRange.Start = doc.Bookmarks.get_Item("HTML_SECTION_START").Range.End;\n                delRange.End = delRange.Bookmarks.get_Item("HTML_SECTION_END").Range.Start;\n                delRange.Delete();\n                doc.Save();\n            }\n            finally\n            {\n                doc.Close();\n            }\n        }\n        finally\n        {\n            app.Quit();\n        }	0
3078329	3078311	How to use ? keyword for string	decimal x;\nif (!decimal.TryParse(textbox1.Text, out x))\n{\n    // throw an exception?\n    // set it to some default value?\n}	0
9585382	9585329	Correct format to add data to web service	ws.addNewProduct(new www.AddProductRequest {\n   CorrelationId = "id here",\n   Products = ...	0
5222390	5221725	Get intersection point of rectangle and line	/// <summary>\n    /// Get Intersection point\n    /// </summary>\n    /// <param name="a1">a1 is line1 start</param>\n    /// <param name="a2">a2 is line1 end</param>\n    /// <param name="b1">b1 is line2 start</param>\n    /// <param name="b2">b2 is line2 end</param>\n    /// <returns></returns>\n    public static Vector? Intersects(Vector a1, Vector a2, Vector b1, Vector b2)\n    {\n        Vector b = a2 - a1;\n        Vector d = b2 - b1;\n        var bDotDPerp = b.X * d.Y - b.Y * d.X;\n\n        // if b dot d == 0, it means the lines are parallel so have infinite intersection points\n        if (bDotDPerp == 0)\n            return null;\n\n        Vector c = b1 - a1;\n        var t = (c.X * d.Y - c.Y * d.X) / bDotDPerp;\n        if (t < 0 || t > 1)\n            {\n            return null;\n        }\n\n        var u = (c.X * b.Y - c.Y * b.X) / bDotDPerp;\n        if (u < 0 || u > 1)\n        {\n            return null;\n        }\n\n        return a1 + t * b;\n    }	0
10320304	10319752	How to select a specific item from a collection of items?	string value = "runtime seven";\n\nDataContext = App.ViewModel.Items.FirstOrDefault(item => item.LineOne == value);	0
11511636	11511229	Unzipping two different zip files with sharpziplib to the same directory	protected void SubmitButton_Click(object sender, EventArgs e)\n{\n\nString savePath = @"C:\Users\James\Documents\Visual Studio 2012\WebSites\CourseImport\CourseTelerik\";\n\nString unZipPath = @"C:\Users\James\Documents\Visual Studio 2012\WebSites\CourseImport\CourseTelerikExtract\";\n\n\nforeach (UploadedFile file in RadUpload1.UploadedFiles)\n{\n   string fileName = file.GetName();\n\n   UnZip((savePath + fileName),  (unZipPath + fileName) );\n}\n\n}	0
14475384	14475360	Passing text from one textBox to another in a same form using C# Windows Form	textBox2.Text = textBox1.Text;	0
6591858	6591559	TryParse datetime from invidivual time elements	public static DateTime? GetFieldAsDateTime(int y, int m, int d, \n    int h, int mi, int s)\n{\n    DateTime result;\n    var input = \n        string.Format("{0:000#}-{1:0#}-{2:0#}T{3:0#}:{4:0#}:{5:0#}", \n        y, m, d, h, mi, s);\n\n    if (DateTime.TryParse(input, CultureInfo.InvariantCulture, \n        System.Globalization.DateTimeStyles.RoundtripKind, out result))\n    {\n        return result;\n    }\n\n    return null;\n}	0
10587427	10587212	Can the width of a WinForm automatically adjust to the total width of a DataGridView?	public Form1()\n{\n    InitializeComponent();\n\n    dataGridView1.AutoSize = true;\n    dataGridView1.SizeChanged += new EventHandler(dataGridView1_SizeChanged);\n    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;\n}\n\nvoid dataGridView1_SizeChanged(object sender, EventArgs e)\n{\n    Width = dataGridView1.Width + 10;\n}	0
6766874	6766783	Printing Selected Row in Gridview	#MyGrid TR {display:none;}\n#MyGrid TR.printMe {display:block; }	0
378036	377927	c# console, Console.Clear problem	static void Clear(int x, int y, int width, int height)\n{\n    int curTop = Console.CursorTop;\n    int curLeft = Console.CursorLeft;\n    for (; height > 0;)\n    {\n        Console.SetCursorPosition(x, y + --height);\n        Console.Write(new string(' ',width));\n    }\n    Console.SetCursorPosition(curLeft, curTop);\n}	0
12254702	12254669	How to pass enum value into @Html.ActionLink	public ActionResult ExportToCSV(int cellSeparator)\n{\n  CellSeparator separator = (CellSeparator)cellSeparator;\n}	0
21893234	21893140	Radio Button Isenabled trouble	private void Cont_OnChecked(object sender, RoutedEventArgs e)\n{\n    if (Cf != null)\n       Cf.IsEnabled = false;\n\n}\n\nprivate void Disc_OnChecked(object sender, RoutedEventArgs e)\n{\n    if (Cf != null)\n       Cf.IsEnabled = true;\n}	0
22695617	22695434	Random a unique number to five objects	var allNumbers = Enumerable.Range(1, 10000).ToList();\nvar randomNumbers = new List<int>();\nvar random = new Random();\nconst int studentCount = 5;\n\nfor (int i = 0; i < studentCount; i++)\n{\n    int randomIndex = random.Next(0, allNumbers.Count);\n\n    randomNumbers.Add(allNumbers[randomIndex]);\n    allNumbers.RemoveAt(randomIndex);\n}	0
22171869	22171686	Reading textfile parsing rows into a Datatable	DataTable data = new DataTable("CSV");\nvar fileInfo = new System.IO.FileInfo("Path");\nusing (var reader = new System.IO.StreamReader(fileInfo.FullName, Encoding.Default))\n{\n    // use  reader.ReadLine(); to skip all lines but header+data\n    Char quotingCharacter = '\0';//'"';\n    Char escapeCharacter = quotingCharacter;\n    using (var csv = new CsvReader(reader, true, '\t', quotingCharacter, escapeCharacter, '\0', ValueTrimmingOptions.All))\n    {\n        csv.MissingFieldAction = MissingFieldAction.ParseError;\n        csv.DefaultParseErrorAction = ParseErrorAction.RaiseEvent;\n        //csv.ParseError += csv_ParseError;\n        csv.SkipEmptyLines = true;\n        // load into DataTable\n        data.Load(csv, LoadOption.OverwriteChanges, csvTable_FillError);\n    }\n}	0
8359395	8359307	xml parse multiple words in single node?	var listOfStringsYouWant = new List<string>();\n         var doc = XDocument.Load("placeXMLHere");\n         // finds every node of item\n         doc.Descendants("item").ToList()\n            .ForEach(item =>\n                        {\n                           listOfStringsYouWant.Add(item.Element("name").Value.Replace('-', '\r\n'));\n                        });	0
15557404	15556144	WPF insert grid column at particular place	var index = 1; //column index to insert\nvar colDef = new ColumnDefinition() { Width=new GridLength(200) };\nMyGrid.ColumnDefinitions.Insert(index, colDef);	0
9726294	9726080	Filtering User Changes to a Radio Button?	public Form1() {\n  InitializeComponent();\n\n  radioButton1.Checked = true;\n  radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);\n  radioButton2.CheckedChanged += new EventHandler(radioButton_CheckedChanged);\n}\n\nprivate void radioButton_CheckedChanged(object sender, EventArgs e) {\n  RadioButton rb = (RadioButton)sender;\n  if (rb.Checked)\n    MessageBox.Show("User checked " + rb.Text);\n}	0
12531714	12530081	Loading dll from resources fails	Dictionary<string, Assembly>	0
21622186	21621343	Sorting an array of ints using an array of floats	float[] f = new float[] { 1.4f, 2.4f, 1.9f };\nDictionary<float, int> origPos = new Dictionary<float, int>();\nfor (int i = 0; i < f.Length; i++)\n{\n    origPos[f[i]] = i;\n}\nArray.Sort(f);\n\nint pos = origPos[f[1]];  // this way you can get the position of a float in the original array	0
16661820	3288883	how to pass List<Object> to WCF	[ServiceContract]\n[XmlSerializerFormat]\npublic class BankingService\n{\n[OperationContract]\n    public void ProcessTransaction(BankingTransaction bt)\n    {\n        // Code not shown.\n    }\n\n}\n\n//BankingTransaction is not a data contract class,\n//but is an XmlSerializer-compatible class instead.\npublic class BankingTransaction\n{\n    [XmlAttribute]\n    public string Operation;\n    [XmlElement]\n    public Account fromAccount;\n    [XmlElement]\n    public Account toAccount;\n    [XmlElement]\n    public int amount;\n}\n//Notice that the Account class must also be XmlSerializer-compatible.	0
27581831	27581762	How can i delete a file from my ftp server when selecting the file in a treeView?	string url = @"ftp://ftp.test.com/root\B\a-new-beginning.jpg";\nurl = url.Replace('\', '/');\n\n// now, backslashes are replaced with slashes\n// ftp://ftp.test.com/root/B/a-new-beginning.jpg\n\nUri serverUri = new Uri(url);	0
13258841	13258697	Removing request validation from page	public static string DecodeFrom64(this string encodedData)\n{\n    var data = Convert.FromBase64String(encodedData);\n    string result = System.Text.ASCIIEncoding.ASCII.GetString(data);\n    return result;\n}	0
24071131	24039640	HttpHandler - Large Xml - markup is corrupted	public class SimpleTestCase : IHttpHandler\n{\n    public void ProcessRequest(HttpContext context)\n    {\n        context.Response.ContentType = "application/xml";\n\n        context.Response.Write("<?xml version=\"1.0\"?>" + Environment.NewLine);\n\n        context.Response.Write("<root>");\n        for (var i = 0; i < 400010; i++)\n        {\n            context.Response.Write("<amount>5</amount>" + Environment.NewLine);\n        }\n        context.Response.Write("</root>");\n\n        context.Response.Flush();\n        context.Response.End();\n    }\n\n    public bool IsReusable\n    {\n        get { return false; }\n    }\n}	0
23184601	23184475	how to add value in 'y' on same 'x' point in c# chart	var DTCs = new [] {"abc", "def", "abc"};\nvar points = DTCs.GroupBy(str => str).Select(group => new\n    {\n        x = group.Key,\n        y = group.Count()\n     });\n\n// loop through points adding them to the chart\nforeach (var p in points)\n{    \n    // Assume this is correct for your chart object\n    chart3.Series.Add(p.x);\n    chart3.Series[p.x].Points.AddY(p.y);\n}	0
11815072	11814633	How to convert the month name in english text in Datetime to arabic text in C#?	var dateTime = DateTime.Now;\nvar dateString = dateTime.ToString("dd MMMM yyyy", System.Globalization.CultureInfo.GetCultureInfo("ar"));	0
19209523	19209355	C# recalling method leads to program exit	string whatToDo = "null";\nbool exitApp = false;\nwhile (!exitApp)\n{\n    whatToDo = AdvTime.MainMenu();\n    if (whatToDo.Contains("play"))\n    {\n        Menu("null", false);\n    }\n    if (whatToDo.Contains("options"))\n    {\n        AdvTime.OptionMenu();\n    }\n    if (whatToDo.Contains("exit"))\n    {\n        exitApp = true;\n    }\n    if (whatToDo.Contains("null"))\n    {\n        AdvTime.MMError("OM");\n    }\n}	0
8321926	8321871	How to make a TextBox accept only alphabetic characters?	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]"))\n    {\n        MessageBox.Show("This textbox accepts only alphabetical characters");\n        textBox1.Text.Remove(textBox1.Text.Length - 1);\n    }\n}	0
6144054	6143999	asp.hyperlink in gridview Format 0 as null	e.Result = db.sp_MainMenuTest( (Int16)Session["myid"]).Select(i => new\n{\n    Field = (i.Field == 0) ? null : i.Field\n});	0
27625395	27625251	Using MySQL PASSWORD() with Entity Framework	where employeeRow.id.Equals(username_txt.Text) && employeeRow.password.Equals(hashedPassword)	0
30720962	30719572	Obtaining value from Calendar control without selecting a day	private DateTime newdate = DateTime.Now;\n\nprivate void Window_Loaded(object sender, RoutedEventArgs e)\n{\n   calctl.SelectedDate = DateTime.Now;\n   calctl.DisplayMode = System.Windows.Controls.CalendarMode.Year;\n}\nprivate void calctl_DisplayModeChanged(object sender, CalendarModeChangedEventArgs e)\n{\n        if (calctl.DisplayMode == System.Windows.Controls.CalendarMode.Month)\n        {\n             newdate = calctl.DisplayDate;\n             calctl.DisplayMode = System.Windows.Controls.CalendarMode.Year;\n        }\n}	0
5154144	5153942	FindControl doesn't work with my ChangePassword control	public static Control FindControlRecursive(Control Root, string Id)\n{\n    if (Root.ID == Id)\n        return Root;\n\n    foreach (Control Ctl in Root.Controls)\n    {\n        Control FoundCtl = FindControlRecursive(Ctl, Id);\n        if (FoundCtl != null)\n            return FoundCtl;\n    }\n\n    return null;\n}	0
1383888	1286746	Open link in new TAB (WebBrowser Control)	private void InitializeBrowserEvents(ExtendedWebBrowser SourceBrowser)\n    {\n        SourceBrowser.NewWindow2 += new EventHandler<NewWindow2EventArgs>(SourceBrowser_NewWindow2);\n    }\n\n    void SourceBrowser_NewWindow2(object sender, NewWindow2EventArgs e)\n    {\n\n        TabPage NewTabPage = new TabPage()\n        {\n            Text = "Loading..."\n        };\n\n        ExtendedWebBrowser NewTabBrowser = new ExtendedWebBrowser()\n        {\n            Parent = NewTabPage,\n            Dock = DockStyle.Fill,\n            Tag = NewTabPage\n        };\n\n        e.PPDisp = NewTabBrowser.Application;\n        InitializeBrowserEvents(NewTabBrowser);\n\n        Tabs.TabPages.Add(NewTabPage);\n        Tabs.SelectedTab = NewTabPage;\n\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n        InitializeBrowserEvents(InitialTabBrowser);\n\n    }	0
9201632	9201372	Does having a public field with private accessors make sense?	private List<Dipendente> dipendenti = new List<Dipendente>();\n\n    public ReadOnlyCollection<Dipendente> ReadOnlyDipendenti\n    {\n        get\n        {\n            return dipendenti.AsReadOnly(); \n        }\n    }	0
5596670	5596604	Using LINQ to find duplicates across multiple properties	var duplicates = items.GroupBy(i => new {i.ValueA, i.ValueB})\n  .Where(g => g.Count() > 1)\n  .Select(g => g.Key);	0
1690121	1690048	Returning Output Param from SQL Connection	conn.CommandText = select SUM (pts) \n                    from cars \n                    where completedDate is not null \n                           and customerID = @customerID";\n\nobj count=cmd.ExecuteScaler();	0
26946666	26946604	fill asp:CheckBoxList from database	cmd.CommandType=CommandType.Text;	0
18030148	18029676	Close PopupJqueryDialogue with Iframe	Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jain", "<script type='text/javascript' language='javascript'>parent.location.replace('../test.aspx?Q=123456');</script>");	0
20943677	20943545	In C#, how can I convert a string time (formatted as HH:mm) into a DateTime variable?	string ds = "8:15";\nstring[] parts = ds.Split(new[] { ':' });\nDateTime dt = new DateTime(\n                   DateTime.Now.Year,\n                   DateTime.Now.Month,\n                   DateTime.Now.Day,\n                   Convert.ToInt32(parts[0]), \n                   Convert.ToInt32(parts[1]));	0
4694453	4694136	get Invalid object name while executing a UDF	var _result = from w in vdc.simple_Search(searchStr)\n            select w;\n    var test = _result.ToList();	0
18846927	18846888	defining and assigning list of strings using inline statement	public List<string> Keywords = new List<string>(){"lorem", "ipsum", "root page"};	0
22950950	22949170	save date-picker date in access database	var invoiceDate = datePicker.SelectedDate.Value.ToString("MM/dd/yyyy");	0
11956068	11955979	How to get PDF from http request/response stream	const string FILE_PATH = "C:\\foo.pdf";\n             const string DOWNLOADER_URI =  "https://site.com/cgi-bin/somescript.pl?file=12345.pdf&type=application/pdf";\n\n            using (var writeStream = File.OpenWrite(FILE_PATH)) \n            {\n                var httpRequest = WebRequest.Create(DOWNLOADER_URI) as HttpWebRequest;\n                var httpResponse = httpRequest.GetResponse();\n                httpResponse.GetResponseStream().CopyTo(writeStream);\n                writeStream.Close();\n            }	0
1321314	1321265	webbrowser printing	string keyName = @"Software\Microsoft\Internet Explorer\PageSetup";\nusing (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) {\n    if (key != null) {\n          string old_footer = key.GetValue("footer");\n          string old_header = key.GetValue("header");\n          key.SetValue("footer", "");\n          key.SetValue("header", "");\n          Print();\n          key.SetValue("footer", old_footer);\n          key.SetValue("header", old_header);\n    }\n}	0
23711460	17890257	C#, Metro, Stream Socket, SSL Untrusted Host, Squid	_streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);\n_streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);	0
16975230	16972580	Inserting large amount of records into Sqlite database	foreach (var item in body3)\n{\n    db.RunInTransaction(() =>\n    {\n        db.Insert(new Site\n        {\n            siteName = item.siteName,\n            siteAddress = item.siteAddress,\n            siteCity = item.siteCity,\n            siteState = item.siteState,\n            siteID = item.siteID\n        });\n    });\n    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>\n    {\n        progressBar.Value = i;                                \n        i++;\n    });\n}	0
6885197	6885087	Unable to change DataRow value	DT2[0][3] = 3;	0
22983656	22981641	How to give a value / get a value from a timer	_random=new Random();\n_timer=new Timer(_random.Next(1,1000000));\n_timer.Elapsed += new ElapsedEventHandler(_notifyUser);\n_timer.Enabled = true;	0
19997714	19997618	Regular expression to match specific filename pattern containing underscores	abcd_Service_11234_15112013_Log.txt	0
510243	510240	Getting the parent name of a URI/URL from absolute name C#	static string GetParentUriString(Uri uri)\n{\n    return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);\n}	0
3324001	3323985	Trying to convert an int[] into int[,] using C#	public static T[,] Convert<T>(this T[] source, int rows, int columns)\n{\n  int i = 0;\n  T[,] result = new T[rows, columns];\n\n  for (int row = 0; row < rows; row++)\n    for (int col = 0; col < columns; col++)\n      result[row, col] = source[i++];\n  return result;\n}	0
12873600	12860848	get host but while the host application is closed	Dim obj As Object\nDim app As c.Application\n\nobj = GetObject("", "CorelDRAW.Application")\napp = CType(obj, c.Application)	0
14623273	14368245	Reuse NSpec specification in outer context	void ItShouldRequestExactly(int n)\n{\n    it["should do " + n + " request"] = () => sendTimes.should_be(n);\n}	0
17076356	17076074	Creating PPT in C++ /cli	PowerPoint::Presentation ^pptPreso = appPPT->Presentations->Add();	0
20540464	20534574	Using Fonts in System with iTextSharp	public static iTextSharp.text.Font GetTahoma()\n{\n    var fontName = "Tahoma";\n    if (!FontFactory.IsRegistered(fontName))\n    {\n         var fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\tahoma.ttf";\n         FontFactory.Register(fontPath);\n    }\n    return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); \n}	0
25878522	25878492	How to detect a certain increment in a for-loop without a separate variable?	for (int i = 0; i < 70; i++)\n{\n    if (i % 7 == 0)\n        // Do stuff\n}	0
1048063	1048045	c# console application - prevent default exception dialog	public static void Main()   \n    {   \n        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);\n\n        //some code here....\n    }   \n\n    /// <summary>\n    /// Occurs when you have an unhandled exception\n    /// </summary>\n    public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)   \n    { \n        //here's how you get the exception  \n        Exception exception = (Exception)e.ExceptionObject;  \n\n        //bail out in a tidy way and perform your logging\n    }	0
32055692	32055086	Regular Expression to find out <a> tag and get the value of HREF using C#	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(htmlstring);\n\nvar links = doc.DocumentNode.SelectNodes("//a")\n               .Select(a => a.Attributes["href"].Value)\n               .ToList();	0
12882166	12882147	How to export the contents of the string or textbox to txt file that remains the same format (If string has 5 lines, txt file will has 5 lines)?	foreach (var line in Richtextbox.Lines)\n{\n    wri.WriteLine(line);\n}	0
21350076	21349939	How do I change my applications initial screenlocation?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Xna.Framework;\n\nnamespace MonoGameExtensions {\n    public static class GameWindowExtensions {\n        public static void SetPosition(this GameWindow window, Point position) {\n            OpenTK.GameWindow OTKWindow = GetForm(window);\n            if (OTKWindow != null) {\n                OTKWindow.X = position.X;\n                OTKWindow.Y = position.Y;\n            }\n        }\n\n        public static OpenTK.GameWindow GetForm(this GameWindow gameWindow) {\n            Type type = typeof(OpenTKGameWindow);\n            System.Reflection.FieldInfo field = type.GetField("window", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n            if (field != null)\n                return field.GetValue(gameWindow) as OpenTK.GameWindow;\n            return null;\n        }\n    }\n}	0
1311792	1311768	Why does a variable turn null after initialized in the Page_Init?	public TextBox[,] tx\n{\n   get { return ViewState["tx"] as TextBox[,]; }\n   set { ViewState["tx"] = tx; }\n}	0
9286806	9286721	Use a struct as a multidimensional array index	class MyArray<T>\n{\n    private T[,,] array;\n\n    public MyArray(int xSize, int ySize, int zSize)\n    {\n        array = new T[xSize,ySize,zSize];\n    }\n\n    public T this[XYZ xyz]\n    {\n        get { return array[xyz.x, xyz.y, xyz.z]; }\n        set { array[xyz.x, xyz.y, xyz.z] = value; }\n    }\n}	0
18734383	18727864	How do I re-initiate AutoComplete on a WinForm Text Box, after a successful initial AutoComplete?	TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend	0
7301828	7301825	Windows Forms: How to hide Close (x) button?	private const int CP_NOCLOSE_BUTTON = 0x200;\nprotected override CreateParams CreateParams\n{\n    get\n    {\n       CreateParams myCp = base.CreateParams;\n       myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;\n       return myCp;\n    }\n}	0
22297607	22297297	How to make timer event start on button click in aspx website	Timer.Start()	0
17656158	17656104	How to subtract 2 nullable DateTimes in C#?	if(yourDateTime != null) {\n   DateTime dateTime = yourDateTime.Value; // You can run .ToDays etc on this\n\n}	0
3363715	3363664	Calculate number of rows from dataset	dsDataSet.Tables[0].Select("COMPLEATED_ON is not null").Length;	0
11474537	11474469	How do I get a lambda query that is like this tsql query?	var latestProducts = ProductsDBContext.Products\n    .GroupBy(p => p.ProductNumber).Select(g => new \n    {\n        ProductNumber = g.Key,\n        MaxProductRevNumber = g.Max(p => p.ProductRevNumber))\n    });	0
3878574	3877550	Modifying a resource in C#?	myPath.SetResourceReference("myPoint", myPointReference)	0
1432241	1432205	Reverse a single chained List	public void Reverse() {\n    Node current = Initial, previous = null;\n    while (current) {\n        Node next = current.Next;\n        current.Next = previous;\n        previous = current;\n        current = next;\n    }\n    Initial = previous;\n}	0
973972	973952	Migrating tiny C# console app to something running on Ubuntu Server 9.04	private static string configFile = Path.Combine(Directory.GetCurrentDirectory(), "LoadCell.config");\n// Or...\nprivate static string configFile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "LoadCell.config";	0
29701892	29701491	Copy byte array into clipboard	var temp = Environment.ExpandEnvironmentVariables("%TEMP%");	0
17196372	17196179	How to make a foreign key in T-SQL to null	string sql = "INSERT INTO TableA (tableId, attributeA) values (@tableId, @attributeA)";\nconn.Open();\nSqlCommand cmd = new SqlCommand(sql, conn);\ncmd.Parameters.Add("@tableId", SqlDbType.Int);\ncmd.Parameters["@tableId"].Value = tableId > 0 ? tableId : (object)DBNull.Value;\ncmd.Parameters.Add("@attributeA", SqlDbType.VarChar);\ncmd.Parameters["@attributeA"].Value = tableId;\ncmd.ExecuteNonQuery();	0
5312285	5312211	How to remove a defined part of a string?	var s = @"NT-DOM-NV\MTA";\nvar r = s.Substring(s.IndexOf(@"\") + 1);\n// r now contains "MTA"	0
12819667	12819481	C# asp.net SQL how to add new value to database by dropdownlist?	AddCommand.Parameters.AddWithValue("@a", TextBox1.Text);\nAddCommand.Parameters.AddWithValue("@d", DropDownList1.Text);	0
9608640	9608591	Regex C# console app	case 1:\ndouble[] myArrai1 = new double[3];\nfor (int i=0; i < myArrai1.length; i++) {\n    Console.WriteLine("Insert a number");\n    while (!double.TryParse(Console.Readline(), out myArrai1[i])) {\n        Console.WriteLine("Invalid entry. Please enter a number.");\n    }\n}\nbreak;	0
10250455	10191275	Search for equivalent Fluent Nhibernate Mapping - Mapping Map as Dictionary	HasMany(x => x.Bundle).Table("bundles").KeyColumn("MainArticle").AsEntityMap("ChildArticle").Element("Amount", part => part.Type<decimal>());	0
33515247	33515219	How to extract number values from string mix with numbers and characters in C#?	string strRegex = @"\d+";\nRegex myRegex = new Regex(strRegex, RegexOptions.None);\nstring strTargetString = @"000745 TO 000748,00050-00052";\n\nforeach (Match myMatch in myRegex.Matches(strTargetString))\n{\n  if (myMatch.Success)\n  {\n    // Add your code here\n  }\n\n}	0
20877969	20877892	How to get value from database to a label?	protected void Page_Load(object sender, EventArgs e)\n{\nstring query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";\n        SqlConnection con = new SqlConnection(query);\n        con.Open();\n        string query1 = "select prodName from ProductMaster where @name='Bar Counter' ";\n        SqlCommand cmd = new SqlCommand(query1, con);\n\n        SqlDataReader dr = cmd.ExecuteReader();\n        while (dr.Read()) {\n\n            label1.Text = dr.GetValue(1).ToString();\n            textBox1.Text = dr.GetValue(0).ToString();\n}	0
27503052	27502458	How to use RouteConfig to append a page URL	public class FormController : Controller\n{\n    public ActionResult Index(string MyType)\n    {\n        return RedirectToAction("Index", "MyProperController", new { MyType });\n    }\n}	0
1055250	1055130	C# Set the visibility of a label using the result of String.IsNullOrEmpty	MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text.Trim());	0
15353080	15349819	Multi-tenancy web application with filtered dbContext	private void AddBindings()\n{\n    //Modified to inject session variable\n    ninjectKernel.Bind<EFDbContext>().ToMethod(c => new EFDbContext((int)HttpContext.Current.Session["thisTenantID"]));\n\n    ninjectKernel.Bind<IAppUserRepository>().To<EFAppUserRepository>();\n    ninjectKernel.Bind<IEmployeeRepository>().To<EFEmployeeRepository>().WithConstructorArgument("tenantID", c => (int)HttpContext.Current.Session["thisTenantID"]);\n}	0
32810963	32810752	Return index of longest substring	public static int IndexOfLongestRun(string str)\n{\n  if (string.IsNullOrEmpty(str)) return -1;\n\n  int currentStartIndex = 0;\n  int longestIndex = 0;\n  int longestLength = 0;\n  int currentLenght = 0;\n\n  for (int i = 0; i < str.Length - 1; i++)\n  {\n    if (str[i] != str[i + 1])\n    {\n      currentStartIndex = i + 1;\n      currentLenght = 1;\n    }\n    else\n    {\n      currentLenght++;\n    }\n\n    if (currentLenght > longestLength)\n    {\n      longestLength = currentLenght;\n      longestIndex = currentStartIndex;\n    }\n  }\n\n  return longestIndex;\n}	0
15714362	15714328	Returning one of many types from a string	private T Blah<T> () where T : IConvertible\n  {            \n     if (!String.IsNullOrEmpty(source))\n          return (T)Convert.ChangeType(source, typeof(T));\n     return default(T);\n  }	0
4780226	4780193	Adding a Click event handler programmatically to a radio button	radioButton1.Click += new RoutedEventHandler(radioButton1_Click);\n\n\n private void radioButton1_Click(object sender, RoutedEventArgs e)\n {\n\n }	0
2401858	2401230	Converting listview to a composite control	var link = new HyperLink();\nlink.NavigateUrl = GetUrl(dataItem);\nlink.ImageUrl = GetImage(dataItem);	0
13839661	13825772	How to move a DataTable row to the first position of its DataTable	DataRow[] dr = dtable.Select("column1 ='" + valueToSearch +"'");\n            DataRow newRow = dtable.NewRow();\n            // We "clone" the row\n            newRow.ItemArray = dr[0].ItemArray;\n            // We remove the old and insert the new\n            ds.Tables[0].Rows.Remove(dr[0]);\n            ds.Tables[0].Rows.InsertAt(newRow, 0);	0
30453405	30442141	Generic Interface, of Generic Interface with Generics	var result = commandBus.Publish<CreateItemCommand, CreateItemResult>(command);	0
2599365	2599097	String Matching	str1 = str1.Insert(0, "///");\nstr1=str1.Insert(str1.Length,"///");\n\nbool Result = mainString.Contains(str1);	0
11342235	11342087	Retrieving data in DataGridView using SELECT on MySQL	string s = "select * from newadm where firstname like @term OR lastname like @term";\nMySqlCommand cmd = new MySqlCommand(s, conn);\ncmd.CommandType = CommandType.Text;\ncmd.Parameters.Add("@term", MySqlDbType.VarChar,40).Value = "%" + txtSearch.Text + "%";	0
11232870	11232688	C# string replace from postiion X to Y only	public static class StringExtension\n{\n    public static string Replace(this string baseValue, int start, int length, string oldValue, string newValue)\n    {\n        return baseValue.Substring(0, start) + baseValue.Substring(start, length).Replace(oldValue, newValue) + baseValue.Substring(start + length, baseValue.Length - (start + length));\n    }\n}	0
8032829	8032787	Date conversion - seconds to hour/minutes/seconds	TimeSpan  duration = Timespan.FromSeconds(t);	0
9895437	9895394	How to insert an item at the beginning of an ObservableCollection?	collection.Insert(0, item);	0
12840633	12840421	Remove all items from a List<T> if variations of T occur	class Program\n    {\n        static void Main(string[] args)\n        {\n            var list = new List<Product>\n                {\n                    new Product() {Name = "Cornflakes", Price = 100},\n                    new Product() {Name = "Cornflakes", Price = 200},\n                    new Product() {Name = "Rice Krispies", Price = 300},\n                    new Product() {Name = "Cornflakes", Price = 400}\n                };\n\n            var uniqueItems = list.Where(w => (!list.Any(l=>l.Name.Equals(w.Name) && l != w)));\n\n        }\n\n        public class Product\n        {\n\n            public string Name { get; set; }\n            public decimal Price { get; set; }\n        }\n    }	0
23470765	23470607	Expression cannot contain lambda expressions	var entity = entityvDetails.Where(e => e.sad_id == item.sad_id).FirstOrDefault();	0
20638580	20497798	Taking the HOG descriptor of an image using HOGDescriptor from EMGU CV C#	public Image<Bgr, Byte> Resize(Image<Bgr, Byte> im)\n        {\n            return im.Resize(64, 128, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);\n        }\n        public float[] GetVector(Image<Bgr, Byte> im)\n        {\n            HOGDescriptor hog = new HOGDescriptor();    // with defaults values\n            Image<Bgr, Byte> imageOfInterest = Resize(im);\n            Point[] p = new Point[imageOfInterest.Width * imageOfInterest.Height];\n            int k = 0;\n            for (int i = 0; i < imageOfInterest.Width; i++)\n            {\n                for (int j = 0; j < imageOfInterest.Height; j++)\n                {\n                    Point p1 = new Point(i, j);\n                    p[k++] = p1;\n                }\n            }\n\n            return hog.Compute(imageOfInterest, new Size(8, 8), new Size(0, 0), p);\n        }	0
2678574	2616515	How to make the arrows keys act as another keys?	private void textBox1_KeyUp(object sender, KeyEventArgs e)\n        {\n            if (sender is TextBox)\n            {\n                TextBox textBox = (TextBox)sender; \n                if (e.Key == Key.Left || e.Key == Key.Right)\n                {\n                    e.Handled = true; \n                    char insert; \n                    if (e.Key == Key.Left) \n                    { \n                        textBox1.SelectionStart = textBox1.Text.Length + 1; \n                        insert = '.';\n                    }\n                    else\n                    { \n                        insert = '-';\n                    } \n                    int i = textBox.SelectionStart;\n                    textBox1.Text = textBox1.Text.Insert(i, insert.ToString());\n                    textBox1.Select(i + 1, 0);\n                }\n            }\n        }	0
16855562	16854273	Deletion of a file used by another processes	Process tool = new Process();\n    tool.StartInfo.FileName = "handle.exe";\n    tool.StartInfo.Arguments = fileName+" /accepteula";\n    tool.StartInfo.UseShellExecute = false;\n    tool.StartInfo.RedirectStandardOutput = true;\n    tool.Start();           \n    tool.WaitForExit();\n    string outputTool = tool.StandardOutput.ReadToEnd();\n\n    string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";\n\n    foreach(Match match in Regex.Matches(outputTool, matchPattern))\n    {\n        Process.GetProcessById(int.Parse(match.Value)).Kill();\n    }	0
26999002	26998096	filesystemwatcher check last detection	Public Class MyClass\n    Dim NextValidTime as DateTime\n\n    public sub Some_Event_Handler()\n        If Now() > NextValidtime Then\n            'do stuff\n            NextValidTime = DateAdd(DateInterval.Second, 1, Now)\n        Else\n            ' Not enough time has passed - do nothing\n        End If\n    end sub\nEnd Class	0
25817298	25812808	Check all check boxes in DataGridView at the same time	if (mTargets.IsCurrentCellInEditMode)\n{\n    mTargets.EndEdit();\n}	0
24767744	24767515	Application stays in memory after exit	public void OnExit() {\n try {\n    foreach(System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())\n          if (myProc.ProcessName == "process name")\n            myProc.Kill();\n   } catch(Exception ex) {} \n }	0
9927457	9926912	Changing string colour	private void btnTrans_Click(object sender, EventArgs e)     \n{\n    var abrvStr = inputBx.Text;\n\n    foreach (var kvp in d)\n\n    {            \n        abrvStr = abrvStr.Replace(kvp.Key, kvp.Value);\n        int start = abrvStr.IndexOf(kvp.Value);\n        if(start >= 0) \n        {\n            richTextBox1.Text = abrvStr;\n            richTextBox1.Select(start, kvp.Value.Length);\n            richTextBox1.SelectionColor = Color.Red;\n        }\n    }\n}	0
564237	564229	How handle an exception in a loop and keep iterating?	for (...)\n{\n    try\n    {\n        // Do stuff\n    }\n    catch (Exception ex)\n    {\n        // Handle (or ignore) the exception\n    }\n}	0
9396174	9395763	Change RadGrid columns headers	var masterTableView = RadGrid1.MasterTableView;\nvar column = masterTableView.GetColumn("idAgir");\ncolumn.HeaderText = "Num??ro";\nmasterTableView.Rebind();	0
10748637	10748252	Using Console.WriteLine during Console.ReadLine	int fooCursorTop = Console.CursorTop + 1;\n\n        var timer2 = new System.Timers.Timer(1000);\n        timer2.Elapsed += new System.Timers.ElapsedEventHandler(delegate\n            {\n                int tempCursorLeft = Console.CursorLeft;\n                int tempCursorTop = Console.CursorTop;\n                Console.CursorLeft = 0;\n                Console.CursorTop = fooCursorTop;\n                Console.WriteLine("Foo");\n                Console.CursorLeft = tempCursorLeft;\n                Console.CursorTop = tempCursorTop;\n                fooCursorTop++;\n            });\n        timer2.Start();\n\n        string input = string.Empty;\n        while (input != "quit")\n        {\n            input = Console.ReadLine();\n            Console.CursorTop = fooCursorTop;\n            Console.WriteLine(input);\n            fooCursorTop += 2;\n        }	0
29549656	29481890	How can I add JSON data to my file upload in Web API?	------WebKitFormBoundary9j1TS9WuwcTWV7OX\nContent-Disposition: form-data; name="RecordTypeId"\n\n120\n------WebKitFormBoundary9j1TS9WuwcTWV7OX\nContent-Disposition: form-data; name="RecordId"\n\n1251857\n------WebKitFormBoundary9j1TS9WuwcTWV7OX\nContent-Disposition: form-data; name="Tags"\n\n------WebKitFormBoundary9j1TS9WuwcTWV7OX\nContent-Disposition: form-data; name="Resource"; filename="sampleUpload1.txt"\nContent-Type: text/plain\n\nSample upload file 1\n------WebKitFormBoundary9j1TS9WuwcTWV7OX--	0
1438153	1438030	infix to postfix converter	public static string[] InfixToPostfix( string[] infixArray )\n{\nvar stack = new Stack<string>();\nvar postfix = new Stack<string>();\n\nstring st;\nfor ( int i = 0 ; i < infixArray.Length ; i++ )\n{\nif ( !( "()*/+-".Contains( infixArray[ i ] ) ) )\n{\npostfix.Push(infixArray[i]);\n}\nelse\n{\nif ( infixArray[ i ].Equals( "(" ) )\n{\nstack.Push( "(" );\n}\nelse if ( infixArray[ i ].Equals( ")" ) )\n{\nst = stack.Pop();\nwhile ( !( st.Equals( "(" ) ) )\n{\npostfix.Push( st );\nst = stack.Pop();\n}\n}\nelse\n{\nwhile ( stack.Count > 0 )\n{\nst = stack.Pop();\nif ( RegnePrioritet( st ) >= RegnePrioritet( infixArray[ i ] ) )\n{\npostfix.Push(st);\n}\nelse\n{\nstack.Push( st );\nbreak;\n}\n}\nstack.Push( infixArray[ i ] );\n}\n}\n}\nwhile ( stack.Count > 0 )\n{\npostfix.Push(stack.Pop());\n}\n\nreturn postfix.Reverse().ToArray();\n}	0
7796096	7795753	How to rename the text of tree view child node programatically	// rename all child nodes within parent to "ChildX"\nprivate void RenameNodes(TreeNode parent)\n{\n    for(int i = 0; i < parent.Nodes.Count; i++)\n    {\n        parent.Nodes[i].Text = "Child" + (i + 1).ToString();\n    }\n}	0
11294279	11293991	split values separated by comma's in different lines	;with tmp(ImageURL,Rest) as\n (\n\nselect  LEFT(ImageURL, CHARINDEX(',',ImageURL+',')-1),\n    STUFF(ImageURL, 1, CHARINDEX(',',ImageURL+','), '')\nfrom Images where HeritageId=@HeritageId\nunion all\nselect  LEFT(Rest, CHARINDEX(',',Rest+',')-1),\n    STUFF(Rest, 1, CHARINDEX(',',Rest+','), '')\nfrom tmp\nwhere Rest > ''\n)\nselect  ImageURL\nfrom tmp	0
9885386	9875835	C# openxml removal of paragraph	MainDocumentPart mainpart = doc.MainDocumentPart; \nIEnumerable<OpenXmlElement> elems = mainPart.Document.Body.Descendants().ToList(); \n\nforeach(OpenXmlElement elem in elems){ \n    if(elem is Text && elem.InnerText == "##MY_PLACE_HOLDER##") \n    { \n        Run run = (Run)elem.Parent; \n        Paragraph p = (Paragraph)run.Parent; \n        p.RemoveAllChildren(); \n        p.Remove(); \n    } \n}	0
12563944	12563918	How do I get the user input to hit a certain method in my mvc controller?	public JsonResult YourActionName(int id)\n{\n    // Fetch your data from DB, or create the model\n    // in whatever way suitable\n    var model = new YourModel {\n        UserName = "Something"\n    };\n\n    // Format the response as JSON\n    return Json(model);\n}	0
25275874	25222277	web api get route template from inside handler	var routeTemplate = ((IHttpRouteData[]) request.GetConfiguration().Routes.GetRouteData(request).Values["MS_SubRoutes"])\n                                    .First().Route.RouteTemplate;	0
30485372	30479736	Log4net set EventLogAppender size	public static void setEventLogAppenderMaximumSize(log4net.ILog aLogger)\n{\n    log4net.Appender.IAppender[] logAppenders = aLogger.Logger.Repository.GetAppenders();\n    if (logAppenders != null && logAppenders.Length > 0)\n    {\n        string logName = ((log4net.Appender.EventLogAppender)logAppenders[0]).LogName;\n\n        EventLog[] eventLogs = EventLog.GetEventLogs();\n        foreach (EventLog e in eventLogs)\n        {\n            if (e.Log == logName)\n            {\n                int newLogSizeInKB = 102400;    //10MB\n\n                if (e.MaximumKilobytes < newLogSizeInKB)\n                {\n                    e.MaximumKilobytes = newLogSizeInKB;\n                }\n                return;\n            }\n        }\n    }\n}	0
20457792	20457089	Is there a maximum size for application settings?	using System;\n\nnamespace ConsoleApplication1\n{\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(Properties.Settings.Default.test.Length);\n        Console.ReadKey();\n    }\n}\n}	0
25499495	25485026	How to create sprites, programatically without using prefeb?	public int numberOfTiles=16;\nVector3 TilePosition;\n\nvoid Start () \n{\n    TilePosition = Vector3.zero;\n    for (int i = 1; i<=numberOfnumberOfTiles; i++) \n    {\n        GameObject temp = GameObject.CreatePrimitive(PrimitiveType.Plane);\n        temp.name = "Tile_"+i;\n        temp.transform.position = TilePosition;\n        temp.transform.Rotate(90f,180f,0,Space.World);\n        temp.transform.localScale = new Vector3(0.66f,1f,0.66f);\n        temp.transform.parent = transform;\n        Texture2D tex =(Texture2D) Resources.LoadAssetAtPath("Assets/Resources/Texture/Tile"+i,typeof(Texture2D));\n        temp.renderer.material.mainTexture = new Texture2D (640, 960, TextureFormat.ARGB32, false);\n        temp.renderer.material.mainTexture = tex;\n        TilePosition = new Vector3(TilePosition.x,TilePosition.y+(temp.transform.localScale.y*6.59f),TilePosition.z);\n    }\n\n}	0
10504449	10215354	How to prevent form.target from causing all HTTP GET in history from doing another roundtrip to the server?	Response.AppendHeader("Cache-Control", "private, max-age=600");	0
3585352	3585344	How can I add stringbuilder (semi colon delimited) values to arraylist in C#?	myStringBuilder.ToString().Split(';').ToList()	0
8638288	8638224	google maps javascript api - get location on click	GEvent.addListener(map, "click", function(overlay, latlng) {\n          if (latlng) {\n            marker = new GMarker(latlng, {draggable:true});\n                var latlng = marker.getLatLng();\n                var lat = latlng.lat();\n                var lng = latlng.lng();\n              //send these lat and lng to server side save location method through ajax\n\n          }\n            map.addOverlay(marker);\n          });	0
28587031	28586607	How to Access list of JSON objects	var json = @"{\n                        ""version"": ""2"",\n                        ""valuestore"": [\n                            {\n                                ""name"": ""abcd1"",\n                                ""type"": ""string"",\n                                ""value"": {\n                                    ""value"": ""0002""\n                                }\n                            },\n                            {\n                                ""name"": ""abcd2"",\n                                ""type"": ""string"",\n                                ""value"": {\n                                    ""value"": ""001""\n                                }\n                            }\n                        ]\n                    }";\n\n        dynamic jsonTemp = JsonConvert.DeserializeObject(json);\n        foreach (var i in jsonTemp.valuestore)\n        {\n            Console.WriteLine("name: {0}, value: {1} \n", i.name, i.value.value);\n        }	0
7232944	7232866	Asp repeater accessing each line from an sql datasource	((DataRowView)e.Item.DataItem)["YourKey"]	0
5376962	5376938	Linq unwrap a nested foreach	var plans = plannings.SelectMany(p => p);	0
26150858	26150819	Suggested structure to maps some strings to some other strings	Dictionary<string, string>	0
18587430	18587402	c# anonymous method in a if statement?	Func<bool> func = () =>\n{\n    // Code in here\n};\n\nif (func())\n{\n    ...\n}	0
5313249	5264981	Telerik/radgrid Equivalent (Find row items/values)?	myRadgrid.MasterTableView.DataKeyValues[myradgrid.SelectedIndex]["YourDataKeyName"]	0
23933847	23933475	HardwareButton BackPressed Doesnt Work properly in windows phone 8.1	e.Handled = true;	0
33687283	33687027	Extra Line Breaks Detected with Visual Studio	var alllines =  File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory +  "myfile.txt")\n\n var validlines = alllines.Where(l=>!string.IsNullOrEmpty(l));	0
2689000	2688923	How to close all running threads?	Thread myThread = new Thread(...);\nmyThread.IsBackground = true; // <-- Set your thread to background\nmyThread.Start(...);	0
17599069	17598958	C# sorting a List of Strings by a List of Doubles	var tuples = from dc in GetDashboardData\n            group dc by dc.serviceType into g\n            select new{\n                Cost = g.Sum(sc=>sc.serviceCost),\n                Type = g.Key,\n            };\nvar sorted = tuples.OrderByDescending(t=>t.Cost).Select(t=>t.Type);\nreturn sorted.ToList();	0
2904928	2904735	post row where radio button is checked	[HttpPost]\npublic ActionResult Numbers(FormCollection fc)\n{\n\n    foreach (string key in fc.Keys)\n    {\n        int i = Convert.ToInt32(key);\n        // i = the number of the item that was selected.\n    }\n\n    return View();\n\n}	0
14712648	14712546	How can I call a method from a Template?	var methodInfo = typeof(T).GetMethod("IsValid", BindingFlags.Static|BindingFlags.Public);\nif (methodInfo != null)\n{\n    object[] parameters = new object[] { genericStructItem, null };\n    if ((bool)methodInfo.Invoke(null, parameters))\n    {\n        // It's valid!\n    }\n    else\n    {\n        string error = (string)parameters[1];\n    }\n}	0
1989690	1989674	How to use orderby with 2 fields in linq?	MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);	0
32081486	32081371	Simple way to have dynamically set readonly text boxes in gridview rows?	protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)\n{\n    foreach (Control ctrl in e.Row.Controls)\n    {\n        MakeTextboxesReadonly(ctrl);\n    }\n\n}\n\nprivate static void MakeTextboxesReadonly(Control parent)\n{\n    foreach (Control ctrl in parent.Controls)\n    {\n        if (ctrl is TextBox)\n        {\n            (ctrl as TextBox).Enabled = false;\n        }\n    }\n}	0
10376932	10376749	String compression for repeated chars	from itertools import groupby\nuncompressed = "(A(2),I(10),A,A,A,A(3),R,R,R,R,A,A)"\ncounted = [(k, len(list(g))) for k, g in groupby(uncompressed.split(','))]\ncompressed = ','.join(k if cnt==1 else str(cnt)+k for k, cnt in counted)	0
19030990	18408272	WCF ChannelFactory with Custom Endpoint Behavior (Json-Rpc)	public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)\n    {\n        string jsonText = SerializeJsonRequestParameters(parameters);\n\n        // Compose message\n        Message message = Message.CreateMessage(messageVersion, _clientOperation.Action, new JsonRpcBodyWriter(Encoding.UTF8.GetBytes(jsonText)));\n        message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));\n        _address.ApplyTo(message);\n\n        HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();\n        reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";\n        message.Properties.Add(HttpRequestMessageProperty.Name, reqProp);\n\n        UriBuilder builder = new UriBuilder(message.Headers.To);\n        builder.Query = string.Format("jsonrpc={0}", HttpUtility.UrlEncode(jsonText));\n        message.Headers.To = builder.Uri;\n        message.Properties.Via = builder.Uri;\n\n        return message;\n    }	0
13031291	13031112	Console application can't connect to sql server instance from server, but can from local machine	telnet <ip>, 1433	0
21941305	21940786	Repository without Entity framework	public interface IWidgetRepository\n{\n    // Query methods\n    Widget GetById(string id);\n    IEnumerable<Widget> GetFeaturedWidgets();\n    IEnumerable<Widget> GetRecommendedWidgetsForUser(string userId);\n\n    // Update methods\n    void RenameWidget(string id, string newName);\n    void UpdateWidgetPrice(string id, decimal newPrice);\n}	0
5026189	5024199	How To Count Associated Entities using Where In Entity Framework	var queryResult = (from post in posts\n                           join comment in comments.Where(x=> x.IsPublic) on post.Id equals comment.Post.Id into g\n                    select new\n                               {\n                                   post,\n                                   post.Author,\n                                   post.Tags,\n                                   post.Categories,\n                                   Count = g.Count()\n                               })	0
16495893	16267643	Drop Down List make list item requery entitydatasource	if (ddlvalue == 1)\n        {\n            CLogsysEntities = new LogsysEntities();\n\n            var ledig =\n                from laan in CLogsysEntities.Laans\n                where laan.Returnertdato != null\n                select laan;\n            LaanGridView.DataSourceID = null;\n            LaanGridView.DataSource = ledig.ToList();\n            LaanGridView.DataBind();	0
2559625	2559583	C#: Need one of my classes to trigger an event in another class to update a text box	public class CommManager()\n{\n    delegate void FramePopulatedHandler(object sender, EventArgs e);\n\n    public event FramePopulatedHandler FramePopulated;\n\n    public void MethodThatPopulatesTheFrame()\n    {\n        FramePopulated();\n    }\n\n    // The rest of your code here.\n}\n\npublic partial class Form1 : Form      \n{      \n    CommManager comm;      \n\n    public Form1()      \n    {      \n        InitializeComponent();      \n        comm = new CommManager();      \n        comm.FramePopulated += comm_FramePopulatedHander;\n    }      \n\n    private void updateTextBox()      \n    {      \n        //get new values and update textbox      \n    }\n\n    private void comm_FramePopulatedHandler(object sender, EventArgs e)\n    {\n        updateTextBox();\n    }\n}	0
25232281	25232249	Android Xamarin programmatically generated Button Click	for(int i = 0; i < 3; i++) {\n    ...\n    Button b = new Button(this);\n    var j= i;\n    b.Click += delegate {\n        processClick(j);\n    };\n    ...\n}	0
7826073	7825130	Passing lots of variables between threads for logging purposes efficiently	Clear()	0
8734141	8734059	Program that sends an email notification if url is down	System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();\nmessage.To.Add("luckyperson@online.microsoft.com");\nmessage.Subject = "This is the Subject line";\nmessage.From = new System.Net.Mail.MailAddress("From@online.microsoft.com");\nmessage.Body = "This is the message body";\nSystem.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");\nsmtp.Send(message);	0
26761802	26756897	Where is location that Debug info (break point, etc) was stored in VS2013, native C++ dll project?	'<your-exe>.exe': Loaded '<path-to-dll>\<your-dll>.dll', Symbols loaded.	0
31690673	31678512	Handling app.config connection strings, when running multiple instances of an app	AppDomain.CurrentDomain.SetData ("APP_CONFIG_FILE", "path to config file")	0
11788993	11788507	control windows 7 taskbar grouping for my application	TaskbarManager.Instance.SetApplicationIdForSpecificWindow(window, guid);	0
11585004	11544798	Focus wpf listbox without changing selected item	Loaded += ((sender, e) =>\n{\n   ListBoxItem item = myListbox.ItemContainerGenerator.ContainerFromItem(myListbox.SelectedItem) as ListBoxItem;\n   item.Focus();\n});	0
2592717	2592637	How can we copy the column data of one datatable to another,even if there is different column names of different datatable?	foreach (DataRow sourcerow in NameAdressPhones.Rows)\n{\n    DataRow destRow = NameAdress.NewRow();\n    destRow["Name"] = sourcerow["Nm"];\n    destRow["Address"] = sourcerow["Add"];\n    NameAdress.Rows.Add(destRow);\n}	0
12201031	12200167	How to find out which panel in split container is clicked on mouse click?	public Form1() {\n  InitializeComponent();\n\n  splitContainer1.Panel1.MouseClick += Panel_MouseClick;\n  splitContainer1.Panel2.MouseClick += Panel_MouseClick;\n  splitContainer2.Panel1.MouseClick += Panel_MouseClick;\n  splitContainer2.Panel2.MouseClick += Panel_MouseClick;\n  splitContainer3.Panel1.MouseClick += Panel_MouseClick;\n  splitContainer3.Panel2.MouseClick += Panel_MouseClick;\n  splitContainer4.Panel1.MouseClick += Panel_MouseClick;\n  splitContainer4.Panel2.MouseClick += Panel_MouseClick;\n}\n\nvoid Panel_MouseClick(object sender, MouseEventArgs e) {\n  SplitterPanel sp = sender as SplitterPanel;\n  SplitContainer sc = sp.Parent as SplitContainer;\n  MessageBox.Show(sc.Name + " - " + sp.Tag.ToString());\n}	0
10918195	10918117	Use properties to refer derived class member variables to base class member variables	class DerivedClass2 : BaseClass2\n{\n    public DerivedClass1A objA\n    {\n        get\n        {\n            return (DerivedClass1A)base.list[0];\n        }\n        set\n        {\n            base.list[0] = value;\n        }\n    }\n\n    public DerivedClass1B objB\n    {\n        get\n        {\n            return (DerivedClass1B)base.list[1];\n        }\n        set\n        {\n            base.list[1] = value;\n        }\n    }\n}	0
9485423	9484711	How to handle CreateUserWizard Steps in Asp.Net?	protected void YourCreateUserWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)\n    {\n        if (e.CurrentStepIndex == YourStepIndex)\n        {\n            ...\n        }\n    }	0
27294858	27294536	XmlDocument get sub items	XmlDocument xmlReader = new XmlDocument();\nxmlReader.PreserveWhitespace = false;\nxmlReader.Load(strfilename);\n\nXmlNodeList elemList = xmlReader.SelectNodes("//RUNNABLES/RUNNABLE-ENTITY/SHORT-NAME");\nstring value = elemList.Item(0).InnerText;	0
6053682	6053577	Update XAttribute Value where XAttribute Name = X	var doc = XDocument.Load("FileName.xml");\nvar element = doc.Descendants("Order")\n    .Where(arg => arg.Attribute("Id").Value == "jason")\n    .Single();\nelement.Attribute("Quantity").Value = "3";\ndoc.Save("FileName.xml");	0
692711	692708	Is it possible to declare and use an anonymous function in a single statement?	XmlNode myOtherNode = new Func<XmlNode>( () => { return myNode; } )();	0
10674116	10638195	Display labels for marker Google Map API	marker = new Marker( centerLL );  \nmarker.icon = new LabelSprite();\nmarker.icon.visible = false;\nmarker.addEventListener(MapMouseEvent.CLICK, onMapClick); \nmap.addOverlay( marker );\n\nfunction onMapClick( e:Event ):void\n{\n  if(selectedMarker) \n     selectedMarker.icon.visible = false;\n\n  selectedMarker = e.currentTarget as Marker;\n  selectedMarker.icon.visible = true;\n}\n\n\npublic class LabelSprite extends Sprite\n{\n  private var labelTextField:TextField;\n\n  public function LabelSprite()\n  {\n    labelTextField = new TextField();\n    addChild(labelTextField);\n  }\n\n  public function set labelText(value:String):void\n  {\n    labelTextField.text = value;\n  }\n}	0
386511	385796	Sync Framework : Can I Sync only a subset of my tables?	public class SampleSyncAgent : Microsoft.Synchronization.SyncAgent\n {\n\n     public SampleSyncAgent()\n     {\n\n         SqlCeClientSyncProvider clientSyncProvider = new SqlCeClientSyncProvider(Properties.Settings.Default.ClientConnString, true);\n         this.LocalProvider = clientSyncProvider;\n              clientSyncProvider.ChangesApplied += new EventHandler<ChangesAppliedEventArgs>(clientSyncProvider_ChangesApplied);    \n\n         this.RemoteProvider = new SampleServerSyncProvider();    \n\n         SyncTable customerSyncTable = new SyncTable("Customer");\n         customerSyncTable.CreationOption = TableCreationOption.DropExistingOrCreateNewTable;\n         customerSyncTable.SyncDirection = SyncDirection.DownloadOnly;**\n\n         this.Configuration.SyncTables.Add(customerSyncTable);\n         this.Configuration.SyncParameters.Add(new SyncParameter("@CustomerName", "Sharp Bikes"));\n     }\n\n}	0
6310105	6310083	C# SQL: How can I increment an integer value in a database by one on multiple records?	declare @newpage int\nset @newpage = 25\nupdate pages set pageorder = pageorder +1 where pageorder >= @newpage and bookid = @bookid	0
28915919	28915403	Tracking other applications running time	static void Main(string[] args)\n    {\n\n        var p = Process.GetProcesses();\n\n        foreach (var process in p)\n        {\n            try\n            {\n                // you can add the process to your process list, chack existence and etc...\n                process.EnableRaisingEvents = true;\n                process.Exited += Program_Exited;\n\n            }\n            catch (Exception)\n            {\n                //any process that you don't have credantial will throw exception...\n            }\n\n        }\n\n        Console.ReadLine();\n\n    }\n\n    private static void Program_Exited(object sender, EventArgs e)\n    {\n        var process = (Process) sender;\n\n        var startTime = process.StartTime;\n        var endTime = process.ExitTime;\n\n\n    }	0
10278660	10278610	Datatype for submit to database	public void OnButtonClick(object sender, EventArgs e) {\n    int value;\n\n    bool isValid = int.TryParse(textBox.Text, out value);\n\n    if (isValid) {\n        // send to WCF\n    }\n    else {\n        // display a message\n    }\n}	0
1140405	1133945	Customizing WinForms ErrorProvider to display its icon inside control's entry	this.errorProvider.SetIconPadding(this.textBox, -20);	0
7414992	7414961	C# - Program to add an extra ' where a ' is found	insertStatement = insertStatement.Replace("'","''");	0
380249	380240	How to set selected index of dropdown to 0 when text of textbox is changed?	function ResetDropDown(id) {\n    document.getElementById(id).selectedIndex = 0;\n}\nfunction ResetTextBox(id) {\n    document.getElementById(id).value = '';\n}\n<select id="MyDropDown" onchange="ResetTextBox('MyTextBox');">\n    <option value="0">0</option>\n    <option value="1">1</option>\n    <option value="2">2</option>\n</select>\n<input id="MyTextBox" type="text" onkeypress="ResetDropDown('MyDropDown');"/>	0
12735130	12734763	Prohibit or at least detect Excel shape movement	Worksheet.Protect DrawingObjects:=True, Contents:=False, AllowFormattingColumns:=True, _\n    AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows :=True	0
5856416	5856382	How to use arrays for comparisons using lambdas in C#	lfilteredItemlist = litemList.Where(m => filterArray.Contains(m.Key))\n                         .ToDictionary(m => m.Key, m => m.Value);	0
26413038	26412998	c# how to take data_type as input in "foreach" clause	public static void print_any_array01<T>(T[] any_array)\n{\n    int count = 0;\n\n    foreach (T element in any_array)\n    {\n        count += 1;\n        Console.WriteLine("Element #{0}: {1}", count, element);\n    }\n}	0
30501321	30501240	Remove ListViewItem using its tag property and without a foreach loop	ListView.Remove(ListView.Items.First(item => item.Tag == id));	0
13569556	13526755	how to create paging in a dynamic gridview	gv.AllowPaging = true;\ngv.PageSize =10;\ngv.PageIndexChanged+= new EventHandler(grid1_PageIndexChanged);\n\nprotected void grid1_PageIndexChanged(object sender, GridViewPageEventArgs e)\n{\ngv.PageIndex = e.NewPageIndex;\ngv.Databind();\n}	0
19920336	19920122	Lambda loop thru ICollection failed to find object property	var item = listA.FirstOrDefault(x=>x.ID == varB.ID);\nif (item != null)\n    varB.someDesc = item.someDesc;	0
12863851	12862831	Partial application of an expression tree	public class Foo\n{\n    public string Value { get; set; }\n}\n\npublic class ReplaceVisitor<T> : ExpressionVisitor\n{\n    private readonly T _instance;\n    public ReplaceVisitor(T instance)\n    {\n        _instance = instance;\n    }\n\n    protected override Expression VisitParameter(ParameterExpression node)\n    {\n        return Expression.Constant(_instance);\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Expression<Func<Foo, bool>> predicate = t => t.Value == "SomeValue";\n        var foo = new Foo { Value = "SomeValue" };\n        Expression<Func<bool>> result = Convert(predicate, foo);\n\n        Console.WriteLine(result.Compile()());\n    }\n\n    static Expression<Func<bool>> Convert<T>(Expression<Func<T, bool>> expression, T instance)\n    {\n        return Expression.Lambda<Func<bool>>(\n            new ReplaceVisitor<T>(instance).Visit(expression.Body)\n        );\n    }\n}	0
5141654	5140376	making a description text !	public static string Strip(string source)\n{\n    char[] array = new char[source.Length];\n    int arrayIndex = 0;\n    bool inside = false;\n\n    for (int i = 0; i < source.Length; i++)\n    {\n        char let = source[i];\n        if (let == '<')\n        {\n            inside = true;\n            continue;\n        }\n        if (let == '>')\n        {\n            inside = false;\n            continue;\n        }\n        if (!inside)\n        {\n            array[arrayIndex] = let;\n            arrayIndex++;\n        }\n    }\n    string text =  new string(array, 0, arrayIndex);\n    return System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ").Trim();\n}	0
31859528	31857354	Unconfirmed writes to ElasticSearch from ASP.NET app	var task = client.IndexAsync(doc); // doc is the object you want to index	0
33641893	33636233	WCF Custom Username and Password Validator using a Repository Database c#	WebServiceHost host = new ServiceHost(typeof(CloudService), httpUri);\nhost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication\n    .UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;\nhost.Description.Behaviors.Find<ServiceCredentials>().UserNameAuthentication\n    .CustomUserNamePasswordValidator = new ServiceUserNamePasswordValidator(repositoryConnectionString);	0
18921958	18921897	How Convert date culture VB.NET	myobject.ToString("MY_DATE_FORMAT", CultureInfo.CreateSpecificCulture("en-US"))	0
5579645	5579498	How to stop a blocking StreamReader.EndOfStream on a NetworkStream	try/catch	0
27698566	27698510	How can I start external programs in C#?	string strProg= @"full file name of your program";\nSystem.Diagnostics.Process.Start("CMD.exe",strProg);	0
32960953	32960804	Save dynamic variables in text file without closing it using C#	while (true)\n{\n    file.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);\n    file.WriteLine("Comma Separated Version of Variables in String");\n    file.Flush();\n}	0
20608086	20606560	How to run Main() method from C# program in the thread pool?	static void Function(){\n    //Do stuff\n}\nstatic void Main(){\n  TaskFactory.StartNew(Function).wait();\n}	0
5658813	5658799	Is it wrong to compare a double to 0 like this: doubleVariable==0?	double d1 = 1.000001; double d2 =0.000001;\nConsole.WriteLine((d1-d2)==1.0);	0
3936411	3936176	How close Html window when click asp.net button?	protected void ContineButton_Click(object sender, EventArgs e)\n{\n    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close()", true);\n}	0
3215793	3215605	LINQ 2 SQL Return Multiple as Single String	var business = from businesse in context.tblBusinesses \n               where businesse.BusinessID == businessID \n               select new\n               {\n                   businesse.BusinessName,\n                   businesse.ContactName,\n                   Phone = businesse.tblPhones.Select(p=>p.PhoneNumber)\n                       .FirstOrDefault() ?? string.Empty\n               }.Single();\nreturn (business.BusinessName ?? string.Empty) +\n    (business.ContactName ?? string.Empty) +\n    (business.Phone ?? string.Empty);	0
22803773	22803639	Find product objects where the product names contains a searchstring AND ignores case sensivity	products.Where(p => p.Name.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0);	0
9020887	9020100	How to read xml data into a DataSet in c#?	System.Data.DataSet reportData = new System.Data.DataSet();\nSystem.Net.WebRequest request= System.Net.WebRequest.Create(reportDataPath);\n\nusing (System.Net.WebResponse response =   (System.Net.HttpWebResponse)request.GetResponse()) {\n    using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8)) {\n        reportData.ReadXml(sr);\n    }\n}	0
5623808	5621703	AOP: Custom Model Binder Attribute using Ninject	public class MyModelBinder : IModelBinder\n{\n    Func<IAuthenticationService> _resolveAuthService;\n\n    public MyModelBinder(Func<IAuthenticationService> resolveAuthService)\n    {\n         _resolveAuthService = resolveAuthService;\n    }\n\n    public override object Bind(Context c)\n    {\n        var authService = _resolveAuthService();\n\n        authService.GetSomething();\n\n        // etc...\n    }\n}	0
17335191	17335119	Mapping with automapper to an object with one aditional field results in exception	Mapper.CreateMap<GetUpcomingLessons_Result, UpcomingLessonDTO>()\n.ForMember(dest => dest.TeacherOfficialName, opt => opt.Ignore());	0
17559670	17559634	JavaScript within Razor with wrong encoding	"@Html.Raw(product.productName)",	0
25384051	25383955	Checking a cell in DataGridView for any Char	if (crozzleDisplay[i, j].Value != null && !String.IsNullOrEmpty(crozzleDisplay[i, j].Value.toString()))\n                    FormatCell(i, j);	0
356096	354836	UnityContainer, child container injection	public class ChildContainer2 : IChildContainer\n{\n    private IUnityContainer _container;\n\n    public ChildContainer(IUnityContainer parent)\n    {\n        _container = parent.CreateChildContainer();\n    }\n\n    public IUnityContainer Container { get { return _container; } }\n}	0
9969221	9969008	Is there a way to remove certain elements from a List<T> with LINQ?	public void Test()\n{\n List<Point> points = new List<Point>\n {\n  new Point(0, 10),\n  new Point(1, 12),\n  new Point(2, 16),\n  new Point(3, 16),\n  new Point(4, 16),\n  new Point(5, 13),\n  new Point(6, 16),\n };\n var subSetOfPoints = points.Where(p=> !IsInTheMiddleX(p, points));\n}\n\nprivate bool IsInTheMiddleX(Point point, IEnumerable<Point> points)\n{\n return points.Any(p => p.X < point.X && p.Y == point.Y) && \n        points.Any(p => p.X > point.X && p.Y == point.Y);                        \n}	0
30773972	30773092	changing the order of records in dataset	var temp = dsWinners.Tables[0].Rows[index];         \\getting row\nvar newrow = dsWinners.Tables[0].NewRow();     \\ creating new row to insert\nnewrow.ItemArray = temp.ItemArray;            \\ copying data from old to new row\ndsWinners.Tables[0].Rows[index].Delete(); \\deleting old row.\n dsWinners.Tables[0].Rows.InsertAt(newrow, index - 1); \\ adding new row.	0
8415789	8415149	Filter control keys from KeyEventArgs	using System;\nusing System.Text; \nusing System.Windows.Input;\n\npublic void KeyDownSink(object sender, System.Windows.Input.KeyEventArgs e)   \n{  \n    string keyPressed = _keyConv.ConvertToString(e.Key);\n\n    if (keyPressed != null && keyPressed.Length == 1) \n    {\n        if (char.IsLetterOrDigit(keyPressed[0]))\n        {\n            _textRead.Append(keyPressed[0]);\n        }\n    }\n}\n\nprivate StringBuilder _textRead = new StringBuilder();   \nprivate KeyConverter _keyConv = new KeyConverter();	0
12763714	12763394	Use proxy in webBrowser without editing registry	private void SetSessionProxy(strin ProxyAddress, string BypassList)\n{\n    var proxyInfo= new INTERNET_PROXY_INFO {\n        dwAccessType = 0x3,\n        lpszProxy = ProxyAddress,\n        lpszProxyBypass = BypassList\n    };\n    int structSize = Marshal.SizeOf(proxyInfo);\n    const uint SetProxy = 0x26;\n\n    if (Win32Native.UrlMkSetSessionOption(SetProxy, structure, dwLen, 0) != 0)\n        throw new Win32Exception();\n}\n\n[StructLayout(LayoutKind.Sequential)]\nprivate class INTERNET_PROXY_INFO\n{\n    public uint dwAccessType;\n    [MarshalAs(UnmanagedType.LPStr)]\n    public string lpszProxy;\n    [MarshalAs(UnmanagedType.LPStr)]\n    public string lpszProxyBypass;\n}\n\n[DllImport("urlmon.dll", CharSet=CharSet.Unicode, SetLastError=true)]\nprivate static extern int UrlMkSetSessionOption(uint dwOption, INTERNET_PROXY_INFO structNewProxy, uint dwLen, uint dwZero);	0
8382625	8382519	Append xml string into Existing xmlfile using c#	class Program\n{\n    static void Main()\n    {\n        var xdoc = new XmlDocument();\n        xdoc.LoadXml(@"<name><class></class></name>");\n        xdoc.DocumentElement.SetAttribute("xmlns:tia", "http://tia.com");\n        var node = xdoc.CreateElement("tia", "Demographic", "http://tia.com");\n        var xfrag = xdoc.CreateDocumentFragment();\n        xfrag.InnerXml = @"<Age/><DOB/>";\n        node.AppendChild(xfrag);\n        xdoc.DocumentElement.FirstChild.AppendChild(node);\n        xdoc.Save(Console.Out);\n    }\n}	0
6573681	6572750	Find Max() Value from DataTable - Varchar() Column?	int x;\n    var maxVal = MyDtb1.AsEnumerable()\n      .Max (r => int.TryParse(r.Field<string>("sl_no"), out x) ? (int?)x : null);	0
25101416	25099859	xamarin load data into label from list	partial class nextView : UIViewController\n{\n        public nextView (IntPtr handle) : base (handle)\n        {\n        }\n\n        public override void ViewDidLoad()\n        {\n            base.ViewDidLoad();\n\n            //perform initialization here\n            lastLabel.Text = Core.getdata ();\n        }\n}	0
7965428	7965335	Changing font in GridView	text-weight:bold	0
13629851	13629684	Custom Delegating Handler specific to a Controller in ASP.NET Web API	config.Routes.MapHttpRoute(\n        name: "MyCustomHandlerRoute",\n        routeTemplate: "api/MyController/{id}",\n        defaults: new { controller = "MyController", id = RouteParameter.Optional },\n        constraints: null,\n        handler: HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new MyCustomDelegatingMessageHandlerA());\n    );	0
1902182	1901866	How can I create a single event handler for many many pictureBoxes on MouseEnter?	void HeroMouseEnter(object sender, EventArgs e)\n{\n    //My picture box is named Andromeda. I'm going use that name \n    // as a key is a Dictionary and pull the picture according to the name.\n    //This is to make a generic event to handle all movements.\n    //Any help?\n    ((PictureBox)sender).Image =  GetImage(((PictureBox)sender).Name)           \n}	0
19310480	19310431	how to convert datetime in format 23:59:59	toDate.ToString("yyyy-MM-dd 23:59:59.000");	0
32322552	32322438	Programmatically insert image to word with link to file	InlineShape AddPicture(\n    string FileName,\n    ref Object LinkToFile,\n    ref Object SaveWithDocument,\n    ref Object Range\n)	0
15020256	15019876	get value from c# enums	((int)ProductionStatus.Validated).ToString("D3");	0
34272725	34272173	Delete all folders and subdirectories that doesn't have a file of certain extension	private static bool processDirectory(string startLocation)\n{\n    bool result = true;\n    foreach (var directory in Directory.GetDirectories(startLocation))\n    {\n        bool directoryResult = processDirectory(directory);\n        result &= directoryResult;\n\n        if (Directory.GetFiles(directory, "*.dvr").Any())\n        {\n             result = false;\n             continue;\n        }\n\n        foreach(var file in Directory.GetFiles(directory))\n        {\n            try\n            {\n               File.Delete(file);\n            }\n            catch(IOException)\n            {\n               // error handling\n               result = directoryResult = false;\n            }\n        }\n\n        if (!directoryResult) continue;\n        try\n        {\n            Directory.Delete(directory, false);\n        }\n        catch(IOException)\n        {\n            // error handling\n            result = false;\n        }\n    }\n\n    return result;\n}	0
386217	386189	Get the source of some website from asp.net code	class Program\n{\n    static void Main(string[] args)\n    {\n        using (WebClient client = new WebClient())\n        using (Stream stream = client.OpenRead("http://www.google.com"))\n        using (StreamReader reader = new StreamReader(stream))\n        {\n            Console.WriteLine(reader.ReadToEnd());\n        }\n    }\n}	0
1158542	1158519	Crash when using C# Assembly from Managed C++ DLL	MyCSharpAssembly.dll	0
8418981	8418274	Asp.Net c# logging in to another website	var driver = new ChromeDriver();\n\n        driver.Navigate().GoToUrl(LOGON_URL);\n\n        driver.FindElement(By.Id("UserName")).SendKeys("myuser");\n        driver.FindElement(By.Id("Password")).SendKeys("mypassword");\n\n        driver.FindElement(By.TagName("Form")).Submit();\n\n        driver.Navigate().GoToUrl(SECRET_PAGE_URL);\n\n        // And now the html can be found as driver.PageSource. You can also look for\n        // different elements and get their inner text and stuff as well.	0
977369	977300	How can I know if a string represents a valid MIME type?	using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap"))\n{\n    PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];\n    foreach(IISOle.MimeMap mimeType in propValues) \n    //must cast to the interface and not the class\n    {\n      //access mimeType.MimeType to get the mime type string.\n    }\n}	0
8205388	8205347	Get unique ID records from a List<T> of a collection	var list= loadList();\n\n    list = list \n        .GroupBy(i => i.id)\n        .Select(g => g.First())\n        .ToList();	0
20908147	20902682	How do I set a property on a base class for all classes that subclass it, using structuremap?	// during the ObjectFactory.Initialize\nx.SetAllProperties(set => set.OfType<ICacheProvider>());\n\n// something more...\n// this way the instance could be shared \nx.For<ICacheProvider>()\n    // as a singleton\n    .Singleton()\n    .Use<DefaultCacheProvider>();	0
6555409	6555367	how to change datetimepicker font color when disabled & enable?	DateTimePicker.OnEnabledChanged	0
32282139	32282086	storing the result of a for loop into array and revrse it?	Console.Write("Number: ");\nvar num = int.Parse(Console.ReadLine());   // parse console input\nvar range = Enumerable.Range(1, num);   //generate array of values from 1 to num\nvar str = String.Concat(range.Select(x => x.ToString()));   //concatenate array of values\nConsole.WriteLine(str);     // write string\nvar sum = range.Sum(); // get sum of array\nConsole.WriteLine("\nThe sum is: {0}", sum);   // write sum\nConsole.ReadLine();   // pause	0
21167726	21166135	load image files from folder without use opendialog in c#	using System.Linq;\n\n\nFileInfo[] files = new System.IO.DirectoryInfo().GetFiles(@"D:\pic\*.bmp").OrderBy(file => file.Name).Skip(1).ToArray()	0
21655156	21655132	How to show/display message box in C# asp.net forms?	string display = "Pop-up!";\n            ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + display + "');", true);	0
13455980	13454506	Custom splitting operation	(?<=^.*\][^\[]*|^[^\[\]]*)/base:_entity	0
20188341	20188172	How to handle row double click in GridView?	private void ???????GridControlDoubleClick(object sender, EventArgs e) {\n\nGridView view = (GridView)sender;\n\nPoint pt = view.GridControl.PointToClient(Control.MousePosition);\n\nDoRowDoubleClick(view, pt);\n\n}\n\n   private static void DoRowDoubleClick(GridView view, Point pt) {\n\nGridHitInfo info = view.CalcHitInfo(pt);\n\nif(info.InRow || info.InRowCell) {\n\n    string colCaption = info.Column == null ? "N/A" : info.Column.GetCaption();\n\n    MessageBox.Show(string.Format("DoubleClick on row: {0}, column: {1}.", info.RowHandle, colCaption));\n\n}	0
25120144	25119899	Send Attachment in Emails	System.Net.Mail.Attachment attachment;\nattachment = new System.Net.Mail.Attachment(HttpContext.Current.Server.MapPath(applicant.CVFilePath));\nrblemail.Attachments.Add(attachment);	0
17469673	17469602	Application not to be shown in task bar	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        this.ShowInTaskbar = false;\n    }\n}	0
3414759	3413170	How to simulate Paste in a WPF TextBox?	ApplicationCommands.Paste.Execute(this, pastedText)	0
9079229	9079107	Getting object type from datagrid	datagrid.SelectedItem.GetType()	0
34099683	34099156	Calculate From DataGridView	int total= 0;\nfor (int i = 0; i < dataGridView.Rows.Count; ++i)\n{\n    sum += Convert.ToInt32(dataGridView.Rows[i].Cells[x].Value); //x=column index \n}\nlabel.text = sum.ToString();	0
19594429	19591666	Get PageFactory IWebElement By locator	private By GetLocator(IWebElement element)\n    {\n        // Retrieve a FieldInfo instance corresponding to the field\n        FieldInfo field = element.GetType().GetField("bys", BindingFlags.Instance | BindingFlags.NonPublic);\n\n        // Retrieve the value of the field, and cast as necessary\n        return ((List<By>)field.GetValue(element))[0];\n    }	0
9928322	9927590	Can I set a value on a struct through reflection without boxing?	var item = new MyStruct { X = 10 };\n\n  item.GetType().GetField("X").SetValueForValueType(ref item, 4);\n\n\n[CLSCompliant(true)]\nstatic class Hlp\n{\n  public static void SetValueForValueType<T>(this FieldInfo field, ref T item, object value) where T : struct\n  {\n    field.SetValueDirect(__makeref(item), value);\n  }\n}	0
18561175	18560974	Print a table with LINQ	static void Main(string[] args)\n{\n  using (AcumenProjectsDBDataContext acumenResponse = new AcumenProjectsDBDataContext()) \n  {\n    IEnumerable<Response> responseData = from response in acumenResponse.Responses select response; \n    //added code\n     foreach (Response response in responseData)\n     {\n        foreach (PropertyInfo prop in response.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n        {\n          object value = prop.GetValue(response, new object[] { });\n          Console.WriteLine("{0} = {1}", prop.Name, value);\n        }\n      }\n      Console.ReadKey();\n   }\n\n}	0
350374	344479	How can I get the expiry datetime of an HttpRuntime.Cache object?	private DateTime GetCacheUtcExpiryDateTime(string cacheKey)\n{\nobject cacheEntry = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { cacheKey, 1 });\nPropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);\nDateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);\n\nreturn utcExpiresValue;\n}	0
28470733	28470141	Cant Deserialize json string with JavaScriptSerializer	[Serializable]\npublic class srFilterData\n{\n    public String filterType { get; set; }\n    public UserData data { get; set; }\n}\n\n\n[Serializable]\npublic class UserData\n{\n    public String firstName { get; set; }\n    public String lastName { get; set; }\n}	0
13547422	13547394	Convert Human readable date into an epoch time stamp	epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;	0
2883340	2883289	C# input dialog as a function	ShowDialog()	0
9081198	9081001	How to ignore parameter serialization in C#	[XmlElement(IsNullable = true)]\npublic NodeConfigurationSerialize ? NodeConfiguration { get; set; }	0
4795202	3834398	How to exclude viewmodel properties from CA1811	/nowarn:1811	0
33565923	33565790	How to fill the gap with %20 in Url in windows phone 8.1?	string imageUrl = Uri.EscapeUriString(url);	0
1937379	1907479	How can I detect if an NUnit test is running from within TeamCity?	private static bool IsOnTeamCity() \n{ \n    string environmentVariableValue = Environment.GetEnvironmentVariable("TEAMCITY_VERSION"); \n    if (!string.IsNullOrEmpty(environmentVariableValue)) \n    { \n         return true; \n    } \n    return false; \n}	0
17330364	17329154	How to call httphandler through jquery ajax in an aspx page?	public class MyStreamHandler : IHttpHandler {\n\npublic void ProcessRequest (HttpContext context) {\n\n    MyServiceClient tcpClient = new MyServiceClient();\n    Image img = Image.FromStream(tcpClient.GetMyStream(30,100));\n    img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)  \n        img.Dispose()\n    }\n\n    public bool IsReusable {\n    get {\n        return false;\n    }\n   }\n}	0
9755664	9755636	C# abstract class calling base with generics	public abstract class Page<T> where T : class \n{ \n    public Func<T, object> SortBy { get; private set; } \n\n    public Page(Func<T, object> sortBy) \n    { \n        this.SortBy = sortBy; \n    } \n} \n\npublic class ProductGridPage : Page<ProductGrid> \n{ \n    public ProductGridPage() : base(pg => pg.Title) \n    {  \n\n    } \n}\npublic class ProductGrid\n{\n  public string Title;\n}	0
9017958	9017924	Cheapest way to make a single object Enumerable?	public IEnumerable<MyObject> IMyInterface.GetMyObjects()\n{\n    yield return _myObject;\n}	0
606084	606043	Shutting down a WPF application from App.xaml.cs	protected override void OnStartup(StartupEventArgs e)\n    {\n        base.OnStartup(e);\n\n        bool doShutDown = ...;\n\n        if (doShutDown)\n        {\n            Shutdown(1);\n            return;\n        }\n        else\n        {\n            this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);\n        }\n    }	0
24877048	24876991	Inaccessable due to protection level	Aneas.NetTools.ConfirmIPSyntax(ScanAddress)\nAneas.NetTools.ScanPorts(ScanIPAddress, Port)	0
19072017	19071419	C# regex building	var regex = new Regex("</a>(.*?)<br />");\nvar matches = regex.Matches("<a href=\"/product.aspx?zpid=564\">American Arborvitae</a>-10 - 10<br /><a href=\"/product.aspx?zpid=647\">Black Walnut </a>-1 - 1<br /> <br />");\nforeach (Match match in matches)\n   Console.WriteLine(match.Groups[1].Value);\nConsole.ReadLine();	0
1618251	1618236	How do I give a method as an attribute argument?	[SomeAttribute(typeof(SomeClass), @"SomeStaticMethod")]	0
7414438	7414315	To perform Grouping in Excel sheet	this.Application.get_Range("data2001", missing)\n.Group(missing, missing, missing, missing);	0
29072610	29007326	Retrieving entities from a one to many relationship (Odata)	var dataServiceQuery = (DataServiceQuery<WhseEmployee>)_context.Company.Where(c => c.Name == companyName)\n                                                                           .SelectMany(c => c.WhseEmployee);	0
1369169	1367987	Databinding, dataset with datarelations, and refreshing single DataTable from DB	data.Tables["tableName"].Rows.Add(e.RowItems);	0
13678787	13678744	How to match a string pattern in a string contained in array	string[] stringArrayToBlock = { "#", "/", "string1:", "string2" };\nstring SearchString = "String1:sdfsfsdf";\nstring lowerCaseString = SearchString.Trim().ToLower();\nif (stringArrayToBlock.Any(s => lowerCaseString.Contains(s)))    \n{\n    //Do work\n}	0
7317313	7292931	Wildcards in XPath attributes	//th[matches(@salary,'^border-bottom-color: #[0-9a-fA-F]{6}; text-align: left; line-height: 25px$')]	0
10515693	10515449	Generate all combinations for a list of strings	private IEnumerable<int> constructSetFromBits(int i)\n{\n    for (int n = 0; i != 0; i /= 2, n++)\n    {\n        if ((i & 1) != 0)\n            yield return n;\n    }\n}\n\nList<string> allValues = new List<string>()\n        { "A1", "A2", "A3", "B1", "B2", "C1" };\n\nprivate IEnumerable<List<string>> produceEnumeration()\n{\n    for (int i = 0; i < (1 << allValues.Count); i++)\n    {\n        yield return\n            constructSetFromBits(i).Select(n => allValues[n]).ToList();\n    }\n}\n\npublic List<List<string>> produceList()\n{\n    return produceEnumeration().ToList();\n}	0
26707144	26706916	converting a user inputed string into a new object	Dictionary<String,Cashiers) dictCashiers = new Dictionary<String,Cashiers>();\nConsole.WriteLine("Enter new login name:");\nString CashierLogInName = Console.ReadLine();\nCashiers newCashier = new Cashiers();\n\ndictCashiers.Add(CashierLogInName,newCashier);\n//replace constants in the next line with actual user's data, probably input from more ReadLine queries to user?\ndictCashiers[CashierLogInName].SetNewCashier(1,2,"Jane","Doe");	0
1374741	1374729	Illegal characters in path error while parsing XML in C#	XmlTextReader reader = new XmlTextReader(new StringReader(strURL));	0
3906386	3906356	MSMQ - can a queue survive a queue process restart/server restart	using System.Messaging;\n\nMessage recoverableMessage = new Message();\nrecoverableMessage.Body = "Sample Recoverable Message";\nrecoverableMessage.Recoverable = true;\nMessageQueue msgQ = new MessageQueue(@".\$private\Orders");\nmsgQ.Send(recoverableMessage);	0
24807796	24794810	Parsing tags which are not closed from web page with HtmlAgilityPack	//select[@name='cccc']/descendant::option[@value]	0
3773228	3773189	a days's worth of data in diff local times	event 1      event 2       +---- service request\n         |            |          v\n\n|---------------|---------------|-  days in Central Europe\n\n--------|-----------------|-------  days in the US (Pacific time)\n\n---------------|---------------|--  UTC day boundaries	0
23309234	23309136	Unable to remove list item from list inside a for each loop C#	var count  = _interestList.RemoveAll(x => x.active == false);	0
27479117	27478930	How to toggle the visibility of two buttons using DataTrigger Behavior in XAML, WP 8.1?	public FooViewModel()\n    {\n        this.OCollection += this.OCollectionChanged;\n    }\n\n    private void OCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n    {\n        var collection = sender as System.Collections.Generic.List<Bar>;\n        if (collection != null && collection.Count > 1)\n        {\n            this.IsButtonVisible = true;\n            base.RaisePropertyChanged(() => this.IsButtonVisible);\n        }\n    }	0
4848761	4848753	Get executing assembly name using reflection	System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location)	0
3140837	3140686	Lists with MarkerStyle = Disc in a WPF-FlowDocument	l.Padding = new Thickness(20, double.NaN, double.NaN, double.NaN);	0
27440399	27318838	Windows Service start from logged in user c#	public ProjectInstaller()\n{\n    InitializeComponent();\n    serviceProcessInstaller1.Username = ".\\" + Environment.UserName;\n}	0
1723514	1721399	Show Date Selected in ASP Calendar on Button Click Event	DateTime newDate = Calendar1.SelectedDate.AddMonths(1);\nCalendar1.VisibleDate = newDate;\nCalendar1.SelectedDate = newDate;	0
27130505	27130245	Inserting a decimal into sql cause inserting a zero number Instead of a decimal number near zero	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n     modelBuilder.Entity<Class1>().Property(rec => rec.Rate).HasPrecision(20, 15);\n}	0
22328764	22327787	Using a control from the main form on subforms	public class Utility\n{\n    public static Action<string> SetNotePadValue\n    {\n        get;\n        set;\n    }\n}\n\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        Utility.SetNotePadValue = (s) =>\n        {\n            // textBox1 is a control on this form\n            this.textBox1.AppendText(s + "\r\n");\n        };\n    }\n}\n\npublic partial class Form2 : Form\n{\n    public Form2()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        // this will set value in Form1's textBox1\n        Utility.SetNotePadValue("Some text");\n    }\n}	0
13746390	13729590	Process Exits immediately if I redirect a Console Application written in Delphi in C# winform application	Reset(Input);\n  Rewrite(Output);\n  StdIn := TTextRec(Input).Handle;\n  StdOut := TTextRec(Output).Handle;	0
20888052	20887411	C# Validating date pattern	static bool ValidateFormat(string customFormat)\n{\n    return !String.IsNullOrWhiteSpace(customFormat) && customFormat.Length > 1 && DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().Contains(customFormat);\n}\n\nstatic bool ValidateFormat(string customFormat)\n{\n    try\n    {\n        DateTime.Now.ToString(customFormat);\n        return true;\n    }\n    catch\n    {\n        return false;\n    }\n}	0
20083904	19159801	C# DataGridViewButtonCell set buttons text	DataGridViewButtonCell b = new DataGridViewButtonCell();\n        int rowIndex = MainTable.Rows.Add(b);\n        MainTable.Rows[rowIndex].Cells[0].Value = "name";	0
17796021	17795605	Using RestSharp Api with GustPay	request.AddParameter(...)	0
15405887	15084446	Get macro command names for menu items in Word	var id = // Obtain from downloaded bundle\nvar name = // Obtain from downloaded bundle\nvar control = Application.CommandBars.FindControl(Id:id);\nvar description = control.DescriptionText;\nvar caption = control.Caption;\nvar shortcut = control.accKeyboardShortcut;\nvar parentControl = control.Parent;	0
30397080	30396919	Convert DataTable to object[,]	uint rows = (uint)table.Rows.Count; \nuint columns = (uint)table.Columns.Count;\n\nvar data = new object[rows, columns];\nint i = 0;\nforeach (System.Data.DataRowView drv in table.DefaultView)\n{\n    for( int x = 0; x<columns; x++)\n{\n    System.Data.DataRow ViewRow = drv.Row;\n    data[i, x] = drv[x];\n\n    i++;\n}\n}	0
12872527	12872488	show date in three combo boxes	DateTime.DaysInMonth(int year, int month);	0
25239730	25239603	How to get the line number of specific text in string in c#	public static int GetLineNumber(string text, string lineToFind, StringComparison comparison = StringComparison.CurrentCulture)\n{\n    int lineNum = 0;\n    using (StringReader reader = new StringReader(text))\n    {\n        string line;\n        while ((line = reader.ReadLine()) != null)\n        {\n            lineNum++;\n            if(line.Equals(lineToFind, comparison))\n                return lineNum;\n        }\n    }\n    return -1;\n}	0
33630168	33629804	Get the exact value from Rad Month Year Picker	DateTime.ToString("yyyy-MM-dd")	0
2378565	2378010	Creating a shape using series of Vector2 - XNA	int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)\n{\n  int i, j, c = 0;\n  for (i = 0, j = nvert-1; i < nvert; j = i++) {\n    if ( ((verty[i]>testy) != (verty[j]>testy)) &&\n     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )\n       c = !c;\n  }\n  return c;\n}	0
10315143	10315073	How to get property name and its value?	foreach (PropertyInfo pi in t.GetProperties())\n    {\n        myDict[pi.Name] = pi.GetValue(data,null).ToString();\n\n    }	0
26801919	26778446	product feeds for Amazon MWS	1 product per feed = 10 minutes\nequals\n500 products per feed = 5000 minutes	0
19390193	19389899	set LanguageID of powerpoint presentation	Presentation.DefaultLaguageID	0
784235	784220	Get a List of available Enums	Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();	0
26919814	26918505	C# Removing entire elements from XMLDocument based on list of unwanted attribute values	var notNeededBarNames = new List<int>() { 1, 3 };\nvar xDoc = XDocument.Load(filename);\n\nxDoc.Descendants("Bar")\n    .Where(bar => notNeededBarNames.Contains( (int)bar.Attribute("name")) )\n    .Remove();\n\nvar newXml = xDoc.ToString();	0
6863671	6269867	ASP.NET Chart - Databound Value, Custom Label	using System.Windows.Forms.DataVisualization.Charting;\n...\n\n// Show data points values as labels\nchart1.Series["Series1"].IsValueShownAsLabel = true;\n\n// Set axis label \nchart1.Series["Series1"].Points[2].AxisLabel = "My Axis Label\nLabel Line #2";\n\n// Set data point label\nchart1.Series["Series1"].Points[2].Label = "My Point Label\nLabel Line #2";	0
20915105	20915071	html tagging without effects	string newText = String.Format("<b>{0}</b>",textBox1.SelectedText);\ntextBox1.Text = textBox1.Replace(textBox1.SelectedText, newText);	0
806058	798684	Programmatically set identity on WCF EndpointAddress	DnsEndpointIdentity identity = new DnsEndpointIdentity("Some value");	0
16088881	16088609	Connecting to a wsdl in .net	Add Service Reference/Advanced/Add Web Reference	0
6339308	6267552	Message box under the main window	public class Win32Window : IWin32Window\n{\n    public Win32Window(IntPtr val)\n    {\n        _handle = val;\n    }\n\n    readonly IntPtr _handle;\n\n    public IntPtr Handle\n    {\n        get { return _handle; }\n    }\n}	0
12318273	12318123	Selection Start Row in DatagridView	Int32 selectedRowCount = \n        dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);\ndataGridView1.SelectedRows[selectedRowCount - 1 ].Index.ToString();	0
7269519	7269484	Getting filenames from a directory	listbox1.Items.Add(eleman.Substring(eleman.LastIndexOf('\\') + 1);	0
745222	745167	How do I refactor multiple similar methods of this sort into a single method?	string propertyName = "BoolProperty";\nFoo myFoo = new Foo();\nType myFooType = myFoo.GetType();\nPropertyInfo prop = myFooType.GetProperty(propertyName);\nprop.SetValue(myFoo, !((bool)prop.GetValue(myFoo, null)), null);	0
32011340	32011267	How to select column from child table in linq	var quiz = db.Quiz\n             .Include(a => a.Questions.Select(q => q.Options))\n             .ToList();	0
11649359	11649257	repeater with postback	l1.CheckedChanged = (sender, e) => { if (l1.Checked) ModalPopupExtender1.Show(); };	0
19712502	19711672	Combine two tables using Entity Framework	var ret = \n    (from taRec in TableA.GetAll()\n    join tc1 in TableC.GetAll on taRec.FK_PersonA equals tc1.Id\n      into tcRecs1\n    from tcRec1 in tcRecs1.DefaultIfEmpty()\n    join tc2 in TableC.GetAll on taRec.FK_PersonB equals tc2.Id\n      into tcRecs2\n    from tcRec2 in tcRecs2.DefaultIfEmpty()\n    select new {\n        taRec.Id, APerson = tcRec1.FullName, BPerson = tcRec2.FullName\n    }).Union(\n        from tbRec in TableB.GetAll()\n        select new {\n            tbRec.Id, APerson = tbRec.FullName, BPerson = tbRec.FullName\n    });	0
19162639	19162528	Creating objects with reflection	public static T Create<T>() where T : ICreateEmptyInstance, new()\n{\n    return (T) Create(typeof (T));\n}\n\nprivate static object Create(Type type)\n{\n    var instance = Activator.CreateInstance(type);\n\n    var properties = type.GetProperties();\n    foreach (var property in properties.Where(property => typeof(ICreateEmptyInstance).IsAssignableFrom(property.PropertyType)))\n    {\n        var propertyInstance = NullObject.Create(property.PropertyType);\n        property.SetValue(instance, propertyInstance);\n    }\n\n    return instance;\n}	0
12756213	12756129	How To Count Number Of Items In XML Doc	XDocument doc = //your xml document\n\n//to get the count of comments with the first id:\nvar blogs = doc.Descendants("blogId");\nvar firstId = blogs.First().Attribute("id").Value;\nint count = blogs.Count(x => x.Attribute("id").Value == firstId);\n\n//this seems more useful to me:\nvar commentsByBlogId = doc.Descendants("blogId").GroupBy(x => x.Attribute("id").Value);	0
9279187	9279152	Run output of existing VS Console project without a console window	Program.Main()	0
34086786	34086318	Most efficient way to retrieve from table storage a range of partition keys	var start = "2015-12-04";\n        var end = "2015-12-14";\n        var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);\n        var tableClient = account.CreateCloudTableClient();\n        var table = tableClient.GetTableReference("MyTableName");\n        var queryExpression = "PartitionKey ge '" + start + "' and PartitionKey le '" + end + "'";\n        TableQuery<DynamicTableEntity> query = new TableQuery<DynamicTableEntity>().Where(queryExpression).Take(250);\n        TableContinuationToken token = null;\n        List<DynamicTableEntity> allEntities = new List<DynamicTableEntity>();\n        do\n        {\n            var queryResult = table.ExecuteQuerySegmented<DynamicTableEntity>(query, token);\n            var entities = queryResult.Results.ToList();\n            token = queryResult.ContinuationToken;\n            allEntities.AddRange(entities);\n            Console.WriteLine("Fetched " + allEntities.Count + " entities so far...");\n        }	0
10734613	10734411	DAL methods with lots of parameters	Class SerachAllProformaParameter\n{\n//All Properties.\n}\n\nSerachAllProformaParameter parameter= new SerachAllProformaParameter();\nparameter.PropertyName="value";\n\npublic Collection<RoIVProforma> SearchAllProforma(parameter);	0
4371020	4371008	Check Format of a string	private static readonly Regex boxNumberRegex = new Regex(@"^\d-\d{5}$");\n\npublic static bool VerifyBoxNumber (string boxNumber)\n{\n   return boxNumberRegex.IsMatch(boxNumber);\n}	0
20807870	20747707	Metro : Getting strings from Resources with globalization	loader.GetString("Pause/Label");	0
31291494	31288916	c# WPF Automate GridViewColumnHeader Click event	list.RaiseEvent(new RoutedEventArgs(GridViewColumnHeader.ClickEvent, header));	0
15936832	15936687	Best way to modify a variable by a list of objects in C#	someStatModifed += StatChangers.Sum(stat => stat.valueChange);	0
5386885	5386795	How to safely save data to an existing file with C#?	File.Replace(tempFile, fileName, backupFileName);	0
17581559	17581519	Do default values for optional parameters have to be static?	private string CreateMessageFromTemplate(string templateId, Contact contact, string email = null)\n{\n    email = email ?? contact.emails.FirstOrDefault()) \n    ... \n}	0
6422107	6422032	how to get records from database based on date range in asp.net linq	var dates = new List<DateTime> { new DateTime(2011, 1, 1), new DateTime(2010, 1, 1), new DateTime(2009, 1, 1) };\nvar result1 = from x in dates where x < new DateTime(2011, 1, 1) && x > new DateTime(2009,1,1) select x;\nvar result2 = dates.Where(x => x < new DateTime(2011, 1, 1) && x > new DateTime(2009,1,1));	0
4036138	4026202	How to augment anonymous type object in C#	obj.NewProperty = newValue	0
17623347	17623291	Correct way to search between dates	WHERE (Debito_Cuenta = @Acct OR Credito_Cuenta = @Ncct) \n AND FechaDeSistema BETWEEN @Start AND @Final	0
11331343	11331039	Button.Click in Custom control	class NewUC : UserControl\n{\n    public event EventHandler CloseClicked;\n\n    public override void OnApplyTemplate()\n    {\n        Button btn = this.FindName("SomeButton") as Button;\n\n        if (btn == null) throw new Exception("Couldn't find 'Button'");\n\n        btn.Click += new System.Windows.RoutedEventHandler(btn_Click);\n    }\n\n    void btn_Click(object sender, System.Windows.RoutedEventArgs e)\n    {\n        OnCloseClicked();\n    }\n\n    private void OnCloseClicked()\n    {\n        if (CloseClicked != null)\n            CloseClicked(this, EventArgs.Empty);\n    }\n}	0
14033959	14033920	How to get distincts from a list inside a list and remove that (master)listitem?	var result = listOflists.GroupBy(l => l[0])\n                        .Select(g => g.First())\n                        .ToList();	0
1815068	1815066	Techniques For Application Deployment In C#	.application	0
1171464	659898	Difficulty with BugzScout.net from behind a proxy	WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;\nWebRequest request = WebRequest.Create(fogBugzUrl);\nrequest.ContentType = "application/x-www-form-urlencoded";\nrequest.Method = "POST";\nrequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;     \nStream requestStream = request.GetRequestStream();\nrequestStream.Write(bytes, 0, bytes.Length);\nrequestStream.Close();	0
4490552	4490441	SQL data retrieve - C#	DataTable table = new DataTable();\n    using ( SqlCommand command = new SqlCommand() )\n    {\n           // TODO: Set up your command here\n        using (SqlDataAdapter adapter = new SqlDataAdapter(command))\n        {\n            adapter.Fill(table);\n        }\n    }\n\n    // Use your DataTable like this...\n\n    if ( table.Rows.Count >= 5 ) {\n        DataRow firstRow = table.Rows[0]; // #1 row\n        DataRow fifthRow = table.Rows[4]; // #5 row\n        DataRow secondRow = table.Rows[1]; // #2 row\n    }	0
33829968	33829064	Index and count must refer to a location within the string. Parameter name: count	Usuario = Request.ServerVariables["LOGON_USER"];\n    Usuario = Usuario.Remove(0, 13);	0
23518631	23504226	Stored Procedure don't work in nHibernate	IList<Produkt> sss = _session\n                    .GetNamedQuery("sp_retrieveAllProductCategory")\n                    .SetResultTransformer(\n                            Transformers.AliasToBean(typeof(Produkt))).List<Produkt>();	0
2920251	2920159	How can i convert a string into byte[] of unsigned int 32 C#	byte[] data =\n  Key\n  .Split(new string[]{", "}, StringSplitOptions.None)\n  .Select(s => Byte.Parse(s.Substring(2), NumberStyles.HexNumber))\n  .ToArray();	0
5608077	5608054	How to redirect to a view from a buddy class asp.net MVC?	protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n{\n    filterContext.Result = new ViewResult \n    { \n        ViewName = "SomeUnauthorizedViewName" \n    };\n}	0
4058602	4058571	send additional strings to Event handler function	a.MouseClick += (sender, e) => HandleLabelMouseClick(sender, e, "whatever1", "whatever2");\n\nprivate void HandleLabelMouseClick(object sender, MouseEventArgs e, string whatever1, string whatever2)\n{\n    MessageBox.Show(whatever1 + "\n" + whatever2);\n}	0
19547037	19546565	Autocomplete textbox based on querystring	[System.Web.Script.Services.ScriptMethod()]\n[System.Web.Services.WebMethod]\npublic static List<string> GetRoomList(string prefixText, int count, string site)\n{\n    ...\n}	0
12691115	12691057	Find in Files C#	public static IEnumerable<string>  GetFiles(string path)\n  {\n        foreach (string s in Directory.GetFiles(path, "*.extension_here"))\n        {\n              yield return s;\n        }\n\n\n        foreach (string s in Directory.GetDirectories(path))\n        {\n              foreach (string s1 in GetFiles(s))\n              {\n                    yield return s1;\n              }\n        }\n  }	0
10177653	10177538	Remotely delete a file through SFTP using a C# program	using Renci.SshNet;\nusing Renci.SshNet.Sftp;\n\npublic void DeleteFile(string server, int port, string username, string password, string sftpPath)\n{\n    using (SftpClient sftpClient = new SftpClient(server, port, username, password))\n    {\n        sftpClient.Connect();\n        sftpClient.DeleteFile(sftpPath);\n        sftpClient.Disconnect();\n    }\n}	0
8467579	8467193	Detect user controls inner controls focus	public partial class UserControl1 : UserControl\n{\n    public UserControl1()\n    {\n        InitializeComponent();\n\n        if (!this.DesignMode)\n        {\n            RegisterControls(this.Controls);\n        }\n\n    }\n    public event EventHandler ChildControlGotFocus;\n\n    private void RegisterControls(ControlCollection cControls)\n    {\n        foreach (Control oControl in cControls)\n        {\n            oControl.GotFocus += new EventHandler(oControl_GotFocus);\n            if (oControl.HasChildren)\n            {\n                RegisterControls(oControl.Controls);\n            }\n        }\n    }\n\n    void oControl_GotFocus(object sender, EventArgs e)\n    {\n        if (ChildControlGotFocus != null)\n        {\n            ChildControlGotFocus(this, new EventArgs());\n        }\n    }\n}	0
13599942	13599773	Generic Controllers	public interface IMyFirstSetOfMethods<TEntity> { /*... */ }\npublic interface IMySecondSetOfMethods<TEntity> { /*... */}\n\npublic class FirstImpl \n{\n\n}\n\npublic class SecondImpl\n{\n}\n\n\npublic class MyController : IMyFirstSetOfMethods<First> , IMySecondSetOfMethods<Second>\n{\n    FirstImpl myFirstImpl = new FirstImpl();\n    SecondImpl mySecondImpl = new SecondImpl();\n\n    // ... implement the methods from the interfaces by simply forwarding to the Impl classes\n}	0
12425010	12424970	How to parse number with multiple possible thousandsseparators?	using System.Globalization;\n\n...\n\nstring number; // Contains number to parse\nint parsedNumber;\nList<CultureInfo> cultures = new List<CultureInfo>()\n{\n    Cultureinfo.InvariantCulture,\n    new CultureInfo("en-US"),\n    ... // Insert other cultures here\n};\nCultureInfo matchingCulture = cultures.FirstOrDefault(cultureInfo =>\n    Int.TryParse(number, out parsedNumber, \n        NumberStyles.AllowThousands, cultureInfo));\nif(matchingCulture != null)\n{\n    // parsedNumber contains the parsed number and matchingCulture contains \n    // the culture that parsed it\n}	0
8272301	8212186	Populating a AutoCompleteBox with a list of anonymous types	private string metaInput { get; set; }\n    public string MetaInput \n    {\n        get\n        {\n            return metaInput;\n        }\n\n        set \n        {\n            string x = value;\n            if (x.Length > 3)\n            {\n                if (x.EndsWith(" "))\n                {\n\n                string z = x.Replace(" ", "");\n                x = z.Replace(",", "");\n                int l = x.Length;\n\n                    if (l > 2)\n                    {\n                        metaInput = null;\n                        SaveMetaWord(x);\n                    }\n\n                    else \n                    {\n                        metaInput = null;\n                    }\n                }\n\n            }\n\n            else \n            {\n                metaInput = value;\n            }\n\n        }\n    }	0
13649761	13649676	Sorting a Collection by result of	selection.AddRange(\n    all.Select(c=>new {Val = c, Count = c.Description.KeywordCount(query))\n       .Where(t => t.Count > 0))\n       .OrderBy(t => t.Count)\n       .Select(t => c.Val);	0
3090033	3090024	How to add seconds to the value of DateTimePicker?	this.dtPicAdmitDate.Value = this.dtPicAdmitDate.Value.AddSeconds(seconds);	0
27016738	27016713	Get the text from a radiobuttonlist instead of the value	RadioButtonList1.SelectedItem.Text	0
7665392	7665290	how to find out whats the nodeType?	string[] valuesOfType = myXElement.Elements()\n   .Where(e => e.Name.LocalName == "type")\n   .Select(e => e.Value).ToArray();	0
22066914	22002617	Calculating KCV with DES Key	public static string GetKCVDES()\n{\n    byte[] key = new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };\n    byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n    byte[] data = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n    DES des = new DESCryptoServiceProvider();\n\n    using (MemoryStream memoryStream = new MemoryStream())\n    {\n        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))\n        {\n            cryptoStream.Write(data, 0, data.Length);\n            cryptoStream.FlushFinalBlock();\n            return ByteArrayToString(memoryStream.ToArray()).Remove(6);\n        }\n    }\n}	0
9897313	9896887	Creating and comparing dates from current week to a cell.innertext string value	DateTime cellValue = DateTime.Now;\nvar beginweek = DateTime.Now.Date.AddDays( (int)DateTime.Now.DayOfWeek *-1);\n\nvar endweek = beginweek.AddDays(6);\n\nif (cellValue.Date >= beginweek.Date && cellValue.Date <= endweek.Date)\n{\n    //do something\n}	0
22181783	22181721	Generic type to declare a list	void Main()\n{\n    int myInt = 0;\n    Type myType = myInt.GetType();\n\n    var listType = typeof(List<>).MakeGenericType(new Type[]{myType});\n    var list = Activator.CreateInstance(listType); \n}	0
14359660	14355854	How to create a new user in Tridion 2011 using core services?	public void CreateUser(string userName, string friendlyName, bool makeAdministrator)\n{\n    var defaultReadOptions = new ReadOptions();\n\n    using (var client = GetCoreServiceClient())\n    {\n        var user = (UserData)client.GetDefaultData(ItemType.User, null);\n        user.Title = userName;\n        user.Description = friendlyName;\n        user.Privileges = makeAdministrator ? 1 : 0;\n        client.Create(user, defaultReadOptions);\n    }\n}	0
21422975	21422939	how to read external app.config as xml file in winforms?	var element = XDocument.Load("filepath")\n                       .Descendants("connectionStrings")\n                       .FirstOrDefault();\nvar connStrings = new Dictionary<string,string>();\nif(element != null)\n{\n   foreach(var item in element.Elements("add"))\n   {\n      var name = (string)item.Attribute("name");\n      var connString = (string)item.Attribute("connectionString");\n      connStrings.Add(name,connString);\n  }\n}	0
12027367	12027345	How to convert a list of string to a list of a class in C#?	var cats = (from sub in Subs\n            select new Category\n            {\n                Name = sub\n            }).ToList();	0
20374769	20374733	is there a regex for parsing a string possible?	(\d{5})(\d{4})(\d{7})(\d{4})	0
14353219	14353066	How to implement both generic and non-generic version of a class?	public class ServerSentEvent : IServerSentEvent\n{}\n\npublic class ServerSentEvent<ClientInfo> : ServerSentEvent\n{}	0
18217556	18217504	Datatable updating without using datarow loop	foreach (DataRow Row in dt.Rows)\n    Row["Value"] = (DynamicControlsHolder1.FindControl(Row["ID"]) as TextBox).Text;	0
5324011	5323954	how to bind two dimensional array with excel range in vsto	Excel.Range rng = myWorksheet.get_Range("A1:D4", Type.Missing);\n\n//Get a 2D Array of values from the range in one shot:\nobject[,] myArray = (object[,])rng.get_Value(Type.Missing);	0
6492425	6491696	maximum file upload size in sharepoint	private ListItem UploadDocumentToSharePoint(RequestedDocumentFileInfo requestedDoc, ClientContext clientContext)\n    {\n        try\n        {\n            using(var fs = new FileStream(string.Format(@"C:\[myfilepath]\{0}", Path.GetFileName(requestedDoc.DocumentWithFilePath)), FileMode.Open))\n            {\n                File.SaveBinaryDirect(clientContext, string.Format("/{0}/{1}", Helpers.ListNames.RequestedDocuments, requestedDoc.FileName), fs, true);\n            }\n        }\n        catch (Exception exception)\n        {\n            throw new ApplicationException(exception.Message);\n        }\n        return GetDocument(requestedDoc.SharepointFileName + "." + requestedDoc.FileNameParts.Extention, clientContext);\n    }	0
6745620	6745193	How can i make WinForms TabPage header width fit it's title?	using System;\nusing System.Windows.Forms;\n\nclass MyTabControl : TabControl {\n    protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n        // Send TCM_SETMINTABWIDTH\n        SendMessage(this.Handle, 0x1300 + 49, IntPtr.Zero, (IntPtr)10);\n    }\n    [System.Runtime.InteropServices.DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}	0
31065621	31065496	How Remove values from Session in Asp.Net	var sessionIds = Session["ID"].Split(',').ToList();\n        sessionIds.Remove("1");\n        sessionIds.Remove("5");\n        Session["ID"] = string.Join(",", sessionIds);	0
26934430	26933069	How to implement "Find, Replace, Next" in a String on C#?	string yourOriginalString = "ab cd ab cd ab cd";\n        string pattern = "ab";\n        string yourNewDescription = "123";\n        int startingPositionOffset = 0;\n        int yourOriginalStringLength = yourOriginalString.Length;\n\n        MatchCollection match = Regex.Matches(yourOriginalString, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);\n\n        foreach (Match m in match)\n        {\n            yourOriginalString = yourOriginalString.Substring(0, m.Index+startingPositionOffset) + yourNewDescription + yourOriginalString.Substring(m.Index + startingPositionOffset+ m.Length);\n            startingPositionOffset = yourOriginalString.Length - yourOriginalStringLength;\n        }	0
25508085	25507698	How to use cursors to navigate a collection of twitter data scraped using a twitter API call	using TweetSharp;\n\n // In v1.1, all API calls require authentication\n var service = new TwitterService(_consumerKey, _consumerSecret);\n service.AuthenticateWith(_accessToken, _accessTokenSecret);\n\n var tweets = service.ListTweetsOnHomeTimeline(\n                      new ListTweetsOnHomeTimelineOptions());\n\n foreach (var tweet in tweets)\n {\n     Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);\n }	0
1028864	1028843	Windows Forms: Change application mainwindow at runtime	MyForm1 f = new MyForm1();\nf.Close += OnOpenOverviewWin();\nApplication.ShutdownMode = ShutdownMode.OnLastWindowClose;\nApplication.Run(f);\n\nvoid OnOpenOverviewWin()\n{\n  MyOverViewForm f = new MyOverViewForm ();\n  f.Show();\n}	0
6138374	6138296	regular expression needed to remove C/C# comments	var regex = new Regex("/\*((?!\*/).)*\*/", RegexOptions.Singleline);\n\nregex.Replace(input, "");	0
8045204	8045134	c# inheritance trickery with a hierachy	public class District : Conference\n    {\n       public virtual string ConferenceName {get;set;}\n       public virtual string DistrictId {get;set;}\n    }	0
7255827	7255797	How to convert this sql to Linq C#	var query = from a in db.MPhoneParts\n            where a.Field3 == "Batteri" &&\n                  !db.MPhoneParts.Any(b => b.Field3 == "cover" &&\n                                           a.Field2 == b.Field2 &&\n                                           a.Field4 == b.Field4 &&\n                                           b.Field6 == "Production354")\n            select a;	0
4136377	4136283	How do I print an image that is in the clipboard using C#?	void PrintBitmap(Bitmap bm)\n{\n    PrintDocument doc = new PrintDocument();\n    doc.PrintPage += (s, ev) => {\n        ev.Graphics.DrawImage(bm, Point.Empty); // adjust this to put the image elsewhere\n        ev.HasMorePages = false;\n    };\n    doc.Print();\n}	0
3513374	3513343	C# Regexp: How to extract $1, $2 variables from match	var regex = new Regex(@"(a+)(\d+)");\nvar match = regex.Match("a42");\nConsole.WriteLine(match.Groups[1].Value); // Prints a\nConsole.WriteLine(match.Groups[2].Value); // Prints 42	0
17603414	17603137	Bring dialog window to front	AddItemView dialog;\n\nprivate void showWindow(object obj)\n{\n\n    if ( dialog == null )\n    {\n       dialog = new AddItemView();\n       dialog.Show();\n       dialog.Owner = this;\n       dialog.Closed += new EventHandler(AddItemView_Closed);\n    }\n    else\n       dialog.Activate();\n}\n\nvoid AddItemView_Closed(object sender, EventArgs e)\n    {\n\n        dialog = null;\n    }	0
12181143	12181074	Remove some characters from an string	Regex.Replace(s, "[^\d,]+", "")	0
32527469	32527034	Dividing one DataTable into many	IEnumerable<DataTable> tables =\n            table.AsEnumerable().GroupBy(t => t.Field<int>("ID")).Select(t => t.CopyToDataTable());	0
17337329	17336749	joining 3 tables using inner join in SQL server	SELECT\n      bill.bill_no AS BillNo\n    , COUNT(room_no_info.room_number) AS TotalRoom\n    , CONVERT(VARCHAR(11), room_no_info.in_date, 106) AS InDate\n    , CONVERT(VARCHAR(11), room_no_info.out_date, 106) AS OutDate\n    , bill.total AS Amount\n    , ISNULL(Advance_cost.total_amount, 0) AS Advance\n    , ISNULL(Advance_cost.total_amount, 0) AS Paid\n    , bill.Balance AS Balance\nFROM room_no_info\nINNER JOIN bill ON bill.bill_no = room_no_info.bill_no\nLEFT JOIN Advance_cost ON bill.bill_no = Advance_cost.room_bill_no \n     AND bill.Date = '26-Jun-13'\nGROUP BY\n      bill.bill_no\n    , room_no_info.in_date\n    , room_no_info.out_date\n    , bill.total\n    , Advance_cost.total_amount\n    , bill.Balance	0
28198634	28198193	Sent an support e-mail through gmail	"Username: " + UserInformation.Name + "\nPassword: " + UserInformation.Password	0
16590170	16466645	format number with 3 trailing decimal places, a decimal thousands separator, and commas after that	String.Format("{0:#,0.000}", value)	0
20097690	20096090	Regex Email with 2 characters after @	using System.ComponentModel.DataAnnotations;\nclass EmailValidationAttribute : RegularExpressionAttribute\n{\n    public EmailValidationAttribute()\n        : base("^[a-zA-Z0-9_\\+-]+(\\.[a-zA-Z0-9_\\+-]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.([a-zA-Z]{2,4})$") { }\n}\n\n\nclass EmailTest\n{\n    [EmailValidation(ErrorMessage="Please Enter a valid email address")]\n    public String Email { get; set; }\n\n}	0
10144858	10144826	How can I raise a custom Routed Event from user control?	RaiseEvent(new RoutedEventArgs(AddClickEvent));	0
20801518	20801418	How to insert numbering without changing other variables	int i = 1;\nforeach (FileInfo f in fiArr)\n{\n   Console.WriteLine("{0}. {1} ({2}) ",i , f.Name, f.Length);\n   i++;\n}	0
6392036	6391912	How can I use reflection to map a list<objects> that include enum values	var partNames=Enum.GetNames(typeof(PartToModify));\nvar parts = from pi in partObj.GetType.GetProperties()\n            where partNames.Contains(pi.Name)\n            select new UpdatePart { \n                         PartToModify = (partToModify)Enum.Parse(typeof(PartToModify),pi.Name),\n                         NewValue=pi.GetValue(partObj,null)\n                       };\nforeach (var part in parts) UpdateList.Add(part);	0
19896519	19894626	How to add data to an existing xml file in c#	XmlDocument xd = new XmlDocument();\nxd.Load("employees.xml");\nXmlNode nl = xd.SelectSingleNode("//Employees");\nXmlDocument xd2 = new XmlDocument();\nxd2.LoadXml("<Employee><ID>20</ID><FirstName>Clair</FirstName><LastName>Doner</LastName><Salary>13000</Salary></Employee>");\nXmlNode n = xd.ImportNode(xd2.FirstChild,true);\nnl.AppendChild(n);\nxd.Save(Console.Out);	0
1725692	1637400	Silverlight 3 - Data Binding Position of a rectangle on a canvas	public class CustomItemsCollection\n    : ItemsControl\n{\n    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n    {\n\n        FrameworkElement contentitem = element as FrameworkElement;\n        Binding leftBinding = new Binding("Left"); // "Left" is the property path that you want to bind the value to.\n        contentitem.SetBinding(Canvas.LeftProperty, leftBinding);\n\n        base.PrepareContainerForItemOverride(element, item);\n    }\n\n}	0
5023015	5022949	Is there a way to set the WebClientProtocol.Timeout default at the application level for a client application?	public HelloWorldService()\n{\n   //some code...\n   this.Timeout = Miliseconds;\n}	0
31995578	29137875	How to tell if a DXVA decoder has fallen back to software decoding	IDirectXVideoDecoderService::CreateVideoDecoder	0
5934368	5933636	how to control the xml output during serialization	Regex.Replace()	0
2266032	2266012	check if an array contains any item from another array	array1.Intersect(array2).Any()	0
3928735	3928722	Moq a function but don't have access to the arguments	mock.Setup(mock => mock.Insert(It.IsAny<FooBar>()));	0
585768	585733	struggling with programmatically adding user controls	foreach (ITask task in tasks)\n{\n  TaskListItem taskListItem = LoadControl("~/TaskListItem.ascx") as TaskListItem;\n\n  taskListItem.Task = task;\n  taskListItem.TaskCompleteChanged +=\n      taskListItem_TaskCompleteChanged;                        \n\n  taskListItemHolder.Controls.Add(taskListItem);\n}	0
14639293	12645458	Make a specific column only accept numeric value in datagridview in Keypress event	private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n    e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);\n    if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column\n    {\n        TextBox tb = e.Control as TextBox;\n        if (tb != null)\n        {\n            tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);\n        }\n    }\n}\n\nprivate void Column1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))\n    {\n        e.Handled = true;\n    }\n}	0
16555073	16552120	How to Copy Local Storage Image to Clipboard WinRT	StorageFile storageFile = await folder.GetFileAsync("Circulo 2_Atomo.png")	0
23309865	23309849	Sort list by property, but with random order of that property	var random = new Random();\nvar result = myCars.GroupBy(c => c.Man)\n                   .OrderBy(g => random.Next())\n                   .SelectMany(g => g);	0
5876460	5876416	Match first part of filepath strings	public static string GetCommonStart(string fp1, string fp2, string fp3)\n{\n    int idx = 0;\n    int minLength = Math.Min(Math.Min(fp1.Length, fp2.Length), fp3.Length);\n    while (idx < minLength && fp1[idx] == fp2[idx] && fp2[idx] == fp3[idx])\n       idx++;\n    return fp1.Substring(0, idx);\n}	0
6988831	6988730	Convert to Method Group Resharper	internal static IList<EmpowerTaxView> GetEmpowerTaxViewsByLongAgencyAndAgencyTaxTypes(\n    IList<EmpowerCompanyTaxData> validEmpowerCompanyTaxDatas,\n    IList<EmpowerTaxView> empowerTaxViews)\n{\n    var results =\n        from empowerCompanyTaxData in validEmpowerCompanyTaxDatas\n        from etv in GetEmpowerTaxViewsByLongAgencyAndTaxType(\n            empowerCompanyTaxData, empowerTaxViews)\n        select etv;\n    return results.ToList();\n}	0
33273689	33273542	Are there any "hacks" to be able to return a long from main()?	Console.Write(	0
23638176	23638150	Get consecutive n values from array offset	var slice = arr.Skip(5).Take(4);	0
8058758	8058584	Alert on Back Key Press, Confirm Exit	protected override void OnBackKeyPress(CancelEventArgs e)\n{\n    if(MessageBox.Show("Are you sure you want to exit?","Exit?", \n                            MessageBoxButton.OKCancel) != MessageBoxResult.OK)\n    {\n        e.Cancel = true; \n\n    }\n}	0
15848916	15848787	How to use Messagebox in class library c#?	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace MessageBoxes\n{\n    class ShowInfo\n    {\n        public void ShowMessage(string msg)\n        {\n            MessageBox.Show(msg);\n        }\n    }\n}	0
20739040	20730333	How to build EF query expression for persistence model using specification for domain model	public class TaskSelectionCriteria\n{\n      public Guid? Id {get;set;}\n      public string TaskText {get;set;}\n}	0
17060228	17060106	How to use methods from another class in switch?	Person pr = null;\n\n    switch (choice)\n       {\n           case "1": \n               pr = new Person("FNAME", "LNAME", "012345678");\n               pr.AddPerson();\n               break;\n\n\n       }	0
15147414	15137213	WPF ListView inside Grid, scrolling error - An ItemsControl is inconsistent with its items source	lv_emails.ItemsSource = emails;	0
4595323	4595288	Reading a key from the Web.Config using ConfigurationManager	string userName = WebConfigurationManager.AppSettings["PFUserName"]	0
11865597	11865556	How to place a value in a dropdown if the database has a null field C#	value="<%# DataBinder.Eval(Container.DataItem, "URL") ?? "#" %>"	0
14236380	14236309	Unexpected Behavior from a Linq Contains() Method	var trueSelectedIds = selectedIDs.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);\nquery = query.Where(x => trueSelectedIds.Contains(x.CustomerID.ToString()));	0
2609475	2599778	How to merge two icons together? (overlay one icon on top of another)	public Icon AddIconOverlay(Icon originalIcon, Icon overlay)\n{\n    Image a = originalIcon.ToBitmap();\n    Image b = overlay.ToBitmap();\n    Bitmap bitmap = new Bitmap(16, 16);\n    Graphics canvas = Graphics.FromImage(bitmap);\n    canvas.DrawImage(a, new Point(0, 0));\n    canvas.DrawImage(b, new Point(0, 0));\n    canvas.Save();\n    return Icon.FromHandle(bitmap.GetHicon());\n}	0
33865231	33865185	how to move current word caret position into previous word in richtextbox wpf?	EditingCommands.MoveLeftByWord.Execute(null, richTextBox);	0
12708535	11995228	How to write an linq statement to get the last of a group of records	// Retrieve only the latest (greatest value in timestamp field) record for each Access Code\nvar last = AccessCodeUsages.Where(u1 => !AccessCodeUsages\n                           .Any(u2 => u2.LocationId == u1.LocationId &&\n                                      u2.AccessCode == u1.AccessCode &&\n                                      u2.Timestamp > u1.Timestamp));	0
21983985	21983938	Need a help on how to sort the list based on volume	listOfBoxes = listOfBoxes.OrderBy(x => x.volume).ToList();	0
17877677	17877544	Expected behaviour with white space in the command line	public void Compile()\n{\n    try\n    {\n        Process compile = new Process();\n\n        string outputExe = fileName.Text;\n        string compiler = compilerFolder + "\csc.exe";\n\n        // add double quotes around path with spaces in it.\n        string arGs = output + "\"" + outputFolder + "\"" + @"\" + outputExe + " " + projectFile; \n\n        compile.StartInfo.FileName = compiler;\n        compile.StartInfo.Arguments = arGs;\n        compile.StartInfo.RedirectStandardOutput = true;\n        compile.StartInfo.UseShellExecute = false;\n        compile.Start();\n\n        string stdOutput = "";\n        while (!compile.HasExited)\n        {\n            stdOutput += compile.StandardOutput.ReadToEnd();\n            MessageBox.Show(stdOutput);\n        }\n    }\n\n    catch (Exception errorMsg)\n    {\n        MessageBox.Show(errorMsg.Message);\n    }\n}	0
12313912	12313672	Convert IList to SomeType[]	public static class ListExtensions\n{\n    public static T[] ConvertToArray<T>(IList list)\n    {\n        return list.Cast<T>().ToArray();\n    }\n\n    public static object[] ConvertToArrayRuntime(IList list, Type elementType)\n    {\n        var convertMethod = typeof(ListExtensions).GetMethod("ConvertToArray", BindingFlags.Static | BindingFlags.Public, null, new [] { typeof(IList)}, null);\n        var genericMethod = convertMethod.MakeGenericMethod(elementType);\n        return (object[])genericMethod.Invoke(null, new object[] {list});\n    }\n\n}\n[TestFixture]\npublic class ExtensionTest\n{\n    [Test]\n    public void TestThing()\n    {\n        IList list = new List<string>();\n        list.Add("hello");\n        list.Add("world");\n\n        var myArray = ListExtensions.ConvertToArrayRuntime(list, typeof (string));\n        Assert.IsTrue(myArray is string[]);\n    }\n}	0
23356837	23356778	breaking infinite loop / proper loop setting	while (true)\n{\n  // some code\n\n  if (condition)\n    break; // HERE\n\n  // some other code\n}	0
33007691	33007273	EF ignoring fluent API for ON DELETE CASCADE	modelBuilder\n         .Entity<Product>()\n         .HasMany(p => p.Details)\n         .WithRequired()\n         .WillCascadeOnDelete(false);	0
11773611	11773543	How to add styles to the datatable	void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\nif (e.Row.RowType == DataControlRowType.DataRow)\n{            \n   e.Row.CssClass="your css class";\n}\n}	0
3825794	3825749	How can I tell if my program is running on a Domain Controller?	public static ArrayList EnumerateDomainControllers()\n{\n    ArrayList alDcs = new ArrayList();\n    Domain domain = Domain.GetCurrentDomain();\n    foreach (DomainController dc in domain.DomainControllers)\n    {\n        alDcs.Add(dc.Name);\n    }\n    return alDcs;\n}	0
10983875	7732876	Data I add to a table in DataSet is not shown in XtraReport	Davide Piras	0
18691805	18690897	how can I use String.IndexOf method to find the correct value?	string sentence = @"CREATE SEQUENCE 'MY_TEST_SEQUENCE' MINVALUE -8 MAXVALUE 999 INCREMENT BY 1 START WITH 55 CACHE 20 NOORDER NOCYCLE";\nstring pattern = @".*\s+MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[ ]*(?<MaxValue>[\d]*)";\nRegex rgx = new Regex(pattern);\nMatch match = rgx.Match(sentence);\nGroup gp1 = match.Groups[1];//-8 or 8 (both valid).\nGroup gp2 = match.Groups[2];//Value after MAXVALUE.\nif (gp1.Value.StartsWith("-") == false)//No minus sign,that must be a positive value.\n{\n  string s2 = string.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999  INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE", gp1.Value);\n  MessageBox.Show(s2);\n}\n\nelse if (gp1.Value.StartsWith("-") == true)//No need for further checking, a value with - will always be smaller.\n{\n  string s2 = string.Format(@"CREATE SEQUENCE ""MY_TEST_SEQUENCE"" MINVALUE 8 MAXVALUE 999 INCREMENT BY 1 START WITH {0} CACHE 20 NOORDER NOCYCLE", gp2.Value);\n  MessageBox.Show(s2);\n}	0
19952855	19952760	Testing a web service by returning a string of data in a web application form	[WebMethod]\npublic void SayHello()\n{\n   return "Hello";\n}	0
32839960	32839873	Loop Through All DataTable in DataSet Using A For Loop	DataSet  dt = new DataSet();\n//Populate dataset here\n//Iterate throuh datatables inside the dataset\nfor(int i=0;i<dt.Tables.Count;i++)\n    {\n      DataTable temptable = dt.Tables[i]; // this will give you the datatable in each iteration level\n        //Do your doce here\n    }	0
28431551	28431450	How to read xml element from the following file?	XNamespace ns = "http://www.microsoft.com/networking/WLAN/profile/v1";\nXElement name = xdoc.Root.Element(ns + "name");	0
34253206	34250844	How to subtract two numbers and add the result to the third number in a sequence?	private void button1_Click(object sender, EventArgs e)\n{\n    int x = Convert.ToInt32(textBox1.Text);\n    listBox1.Items.Clear();\n    listBox1.Items.Add("1".ToString());\n    double numerator = 1, Fact = 1, firstNum = 1, result=0;\n    for (int i = 1; i <= 20; i++)\n    {\n        Fact = 1;       // Reinitialising every time for new denomerator.\n        numerator = Math.Pow(x, i);     // This is how power is calculated.\n        for (int j = 1; j<=i; j++)      // One more inner loop is needed for Factorial.\n            Fact = Fact * j;\n        result = numerator / Fact;\n        firstNum = firstNum + (Math.Pow(-1, i) * result);   // This is the main logic for alternate plus minus.\n        listBox1.Items.Add(firstNum.ToString());\n    }\n}	0
27956573	27956513	DataColumn set a default value	dt.Columns["Column1"].DefaultValue = "testing";\ndt.Columns["Column2"].DefaultValue = "blah";\ndt.Columns["Column3"].DefaultValue = "";\n\nThen, when you do\n\nDataRow dr = dt.NewRow();	0
5838407	5838323	Alternatives to XDocument	HtmlDocument doc = new HtmlDocument();\n doc.Load("file.xml");\n\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n {\n    HtmlAttribute att = link["href"];\n    att.Value = FixLink(att);\n }\n doc.Save("file.htm");	0
19741125	19741105	How to smooth a line ( point array ) in c#?	Graphics.DrawCurve(...)	0
17480573	17480279	Populating a ListBox from database	Application.Current.Dispatcher.BeginInvoke(\n         DispatcherPriority.Background,\n            new Action(() =>\n            {\n                listBox1.ItemsSource = daoActivity.GetAll();\n                listBox1.DisplayMemberPath = "ActivityName";\n                listBox1.SelectedValuePath = "ActivityID";\n            }));	0
1707992	1707818	I want a small regex that accepts a var(int,enum1,enum2) in C#	(var_1|var_2|var_3)\(((par1_1|par1_2|par1_3),)?((par2_1|par2_2,)?((par3_1|par3_2)?\)	0
6538438	6538366	Access to the value of a Custom Attribute	var attribute =\n   (MethodTestingAttibute)\n   typeof (Vehicles)\n      .GetMethod("m1")\n      .GetCustomAttributes(typeof (MethodTestingAttibute), false).First();\nConsole.WriteLine(attribute.Value);	0
26823794	26823770	Creating a LINQ statement from this SQL to get the latest edit of each original record in the database	var lastEditedVideo = _videos.GroupBy(x => x.originalid ?? x.id)\n                             .Select(g => g.OrderByDescending(m => m.id).FirstOrDefault())\n                             .ToList();	0
13118438	13117464	how to get real IE work Area with C#	this.HTMLDocument.documentElement.offsetHeight;	0
14177153	14175538	Storing LAB colors as integers	def rgb_xyz(r, g, b): # 2o. D65\n    triple = [r, g, b]\n\n    v, d = 0.04045, 12.94\n    for i, c in enumerate(triple):\n        triple[i] = 100 * (c / d if c <= v else ((c + 0.055)/1.055)**2.4)\n\n    multipliers = (\n            (0.4124, 0.3576, 0.1805),\n            (0.2126, 0.7152, 0.0722),\n            (0.0193, 0.1192, 0.9505))\n\n    x, y, z = [sum(row[i] * triple[i] for i in range(3))\n            for row in multipliers]\n    return x, y, z\n\ndef xyz_cielab(x, y, z):\n    triple = [x, y, z]\n\n    t0, a, b = 0.008856, 7.787, 16/116.\n    ref = (95.047, 100.0, 108.883)\n    for i, c in enumerate(triple):\n        triple[i] /= ref[i]\n        c = triple[i]\n        triple[i] = c ** (1/3.) if c > t0 else a * c + b\n\n    l = 116 * triple[0] - 16\n    a = 500 * (triple[0] - triple[1])\n    b = 200 * (triple[1] - triple[2])\n    return l, a, b	0
27747936	27747935	Write lambda statement to select items from a list where a property of an item (enum) is found in a list of enum values?	var myProjects = myCache.Where(p => states.Contains(p.state)).ToList();	0
20805425	20805226	How to handle calls in Windows Phone 8 application	// Code to execute when the application is activated (brought to foreground)\n// This code will not execute when the application is first launched\nprivate void Application_Activated(object sender, ActivatedEventArgs e)\n{\n    //start timer here\n}\n\n// Code to execute when the application is deactivated (sent to background)\n// This code will not execute when the application is closing\nprivate void Application_Deactivated(object sender, DeactivatedEventArgs e)\n{\n    //stop timer here      \n}	0
14726885	14703293	Call linked server procedure	getOutput.CommandText = "EXEC myLinkedServer.Database.dbo.myProcedure";\ngetOutput.CommandType = CommandType.Text;	0
21755373	21753466	Changing the Default Property in ASP.NET	public abstract class BasePage : Page    \n    {    \n        protected override void OnLoad(EventArgs e)    \n        {    \n            //Handling autocomplete issue generically    \n            if (this.Form != null)    \n            {    \n                this.Form.Attributes.Add("autocomplete", "off");    \n            }\n\n            base.OnLoad(e);    \n        }    \n   }	0
22492774	22488368	Nancy show model data in view	Model.Id	0
27092026	27091781	How to bind datalist from code behind in asp.net	List<string> r_items_grid = (List<string>)Session["recent_items"];\n\nstring items_id= string.Join(",", r_items_grid);// items_id may be like 1,2,3,4,5.\n\nOleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id IN ("+ items_id + ")",con); \nr_items_reader=cmd_r_items.ExecuteReader();\n\nDataList3.DataSource = r_items_reader;\nDataList3.DataBind();	0
25138754	25138733	Evaluating a Property value on one line versus if else statement	lblPercentText.ForeColor = PercentageFooterValue == 100 ? System.Drawing.Color.Black : System.Drawing.Color.Red;	0
1670617	1670582	TimeSpan in lambda expressions	DateTime startDate = DateTime.Now - new TimeSpan(0,1,0);\nvar items = Items.Where( i => i.Date >= startDate );	0
4660427	4660403	LINQ to DataSet to get generic list from DataTable	DataTable table = DataProvider.GetTable()\n\nvar clientIds = (from r in table.AsEnumerable()\n                select r.Field<string>("CLIENT_ID")).ToList();	0
8176615	8176585	Unsafe code to change length (by mutation!) of a String object?	public static unsafe void SetLength(string s, int length)\n{\n    fixed(char *p = s)\n    {\n        int *pi = (int *)p;\n        if (length<0 || length > pi[-2])\n            throw( new ArgumentOutOfRangeException("length") );\n        pi[-1] = length;\n        p[length] = '\0';\n    }\n}	0
18146908	18145398	ListView with images and datatriggers don't displayed	items[m_InstallationSteps.ActiveStepIndex].Active = true;	0
10006654	10006626	How to delete item from listbox at particular location in C#	myListBox.Items.RemoveAt(2);	0
25874218	25873972	How can I successfully post JSON via C# to a Python Flask route that authenticates via the JSON content?	WebRequest.Create("yoururl")	0
7845591	7845562	Reading a Non txt file in C#	string jsp = File.ReadAllText("page.jsp");	0
20240211	20239912	How to get the Microsoft Template folder using C#	Environment.GetFolderPath(Environment.SpecialFolder.Templates)	0
32863208	32863133	regex split and filter construction	(?<=@T\().*?(?=\))\n\nstring strRegex = @"(?<=@T\().*?(?=\))";\nRegex myRegex = new Regex(strRegex, RegexOptions.None);\nstring strTargetString = @"test test test @T(Test1)  sample text @T(Test2) Something else @T(Test3) ";\n\nforeach (Match myMatch in myRegex.Matches(strTargetString))\n{\n   if (myMatch.Success)\n   {\n    // Add your code here\n  }\n}	0
14078104	14077988	Rectangle wont draw over a panel	private void CreatePanel()\n{\n    Panel panel = new Panel();\n    panel.Width = 600;\n    panel.Height = 100;\n    panel.Controls.Add(....);\n\n    panel.Paint += (sender, e) =>\n    {\n        string color = "#FFE80000"; //*getting the hexa code*\n        int argb = Int32.Parse(color.Replace("#", ""), NumberStyles.HexNumber);\n        Color clr = Color.FromArgb(argb);\n        Pen p = new Pen(clr);\n        Rectangle r = new Rectangle(1, 1, 578, 38);\n        e.Graphics.DrawRectangle(p, r);\n    };\n\n    Controls.Add(panel);\n}	0
25431112	25430978	Get selected item from databound ListBox	listBox1.Text	0
7028027	7017418	How to get IP Address from a FTP request in C#	private string GetFTPAddress(string uri)\n{\n    try\n    {\n       // IPHostEntry host;\n        string localIP = null;\n        var entries = uri.Split('/');\n        var host = Dns.GetHostAddresses(entries[2]);\n        foreach (IPAddress ip in host)\n        {\n            // we are only interested in IPV4 Addresses\n            if (ip.AddressFamily == AddressFamily.InterNetwork)\n            {\n                localIP = ip.ToString();\n            }\n        }\n\n        return localIP;\n    }\n    catch (Exception exception)\n    {\n        throw;\n    }\n}	0
32959479	32954086	Convert C# to TypeScript	let dict:{[key:string]:string} = {\n    'foo':'bar',\n    'john':'doe'\n}\nlet jo = dict;	0
3928714	3928651	Trying to read non-ending byte stream asynchronously in C#	IOException \nThe stream is closed or an internal error has occurred.	0
14262968	14262257	Page.Validate() with a custom validator. err.IsValid returns true after being set to false	if (IsPostBack)\n{\n    Page.Validate();\n    var valid = CustomValidate();\n\n    if(valid && Page.IsValid)\n    {\n    }               \n}\n\nprotected bool CustomValidate()\n{\n     var valid = true;\n     ///do your validation here\n\n     var validator = new CustomValidator();\n     validator.IsValid = false;\n     valid = validator.IsValid;\n     Validator.ErrorMessage = "Error....";        \n     this.Page.Validators.Add(validator);\n     return valid;\n}	0
17142821	17142766	How to parse a xml and read its values	XDocument xDoc = XDocument.Parse(str)\n XElement login = xDoc.Root;\n string res = (string)login.Attribute("res");\n string encstatus = (string)login.Attribute("encstatus");\n int usedquota = (int)login.Attribute("usedquota");	0
23111838	23109301	How can I rotate a GameObject based on slider input?	using UnityEngine;\nusing System.Collections;\n\npublic class Rotator : MonoBehaviour \n{\n    private float currentRotation = 20.0f;\n\n    void OnGUI() \n    {\n        currentRotation = GUI.HorizontalSlider(new Rect(35, 75, 200, 30), currentRotation , 0.0f,  50.0f);\n        transform.localEulerAngles = new Vector3(0.0f, currentRotation, 0.0f);\n    }\n\n}	0
4885948	4885878	Need to get application folder	string myDir = System.Reflection.Assembly.GetExecutingAssembly().Location;\nmyDir = System.IO.Path.GetDirectoryName(myDir);\nString kofaxTextFilePath = System.IO.Path.Combine(myDir, "KofaxBatchHistory.txt");	0
21868668	21847367	Ajax control toolkit combobox showing weird bullets in dropdown	.ComboBoxStyle .ajax__combobox_itemlist\n{\n    border: 1px solid YellowGreen;\n    font-size: medium;\n    font-family: Courier New;\n    padding-left: 0px;\n    list-style-type: none !important; /* Add the important here */\n}	0
30760013	30759071	unable to display contents byte[] properly on to a text box in c#	private string ReadFile(string filename)\n    {\n        var sb = new StringBuilder();\n        if (System.IO.File.Exists(filename))\n        {\n            using (var f = System.IO.File.OpenRead(filename))\n            {\n                var b = new byte[f.Length];\n                var len = f.Read(b, 0, b.Length);\n                while ((-1 < len) && (len == b.Length))\n                {\n                    sb.Append(System.Text.Encoding.UTF8.GetString(b, 0, len));\n                    len = f.Read(b, 0, b.Length);\n                }\n            }\n        }\n        return sb.ToString();\n    }\n\n    private void WriteFile(string filename, string data)\n    {\n        using (var f = System.IO.File.OpenWrite(filename))\n        {\n            var b = System.Text.Encoding.UTF8.GetBytes(data);\n            f.Write(b, 0, b.Length);\n        }\n    }	0
5442603	5441657	How can I lock a private static field of a class in one static method and then release it in some other instance method?	// Provide a way to wait for the value to be read;\n// Initially, the variable can be set.\nprivate AutoResetEvent _event = new AutoResetEvent(true);\n\n// Make the field private so that it can't be changed outside the setter method\nprivate static int _yourField;\n\npublic static int YourField {\n    // "AutoResetEvent.Set" will release ALL??the threads blocked in the setter.\n    // I am not sure this is what you require though.\n    get { _event.Set(); return _yourField; }\n\n    // "WaitOne" will block any calling thread before "get" has been called.\n    // except the first time\n    // You'll have to check for deadlocks by yourself\n    // You probably want to a timeout in the wait, in case\n    set { _event.WaitOne(); _yourField = value; }\n}	0
7606620	7606589	LDAP : Check if a user is member of a group	WindowsIdentity identity =     WindowsIdentity.GetCurrent();\nWindowsPrincipal principal = new WindowsPrincipal(identity);\nprincipal.IsInRole("role name");	0
27403991	27403810	How to switch form1 and form2 by each button?	public partial class Form2 : Form\n{\n    private Form1 m_frm\n\n    public Form2(Form1 frm)\n    {\n        InitializeComponent();\n        m_frm = frm;\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        this.Visible = false;\n        m_frm.Show();\n        m_frm.Visible = true;\n    }\n}	0
29566137	29565991	GridView -out of range only in second page	int index = int.Parse(e.CommandArgument.ToString()) % GridView1.PageSize	0
21590413	21590211	Client/Screen Coordinate Conversion	var mainPosition = this.PointToClient(screenPosition);\nmainPosition = new Point(\n               mainPosition.X + SystemInformation.VerticalResizeBorderThickness,\n               mainPosition.Y + SystemInformation.CaptionHeight + SystemInformation.HorizontalResizeBorderThickness);	0
23293490	23291753	How to stop invoking of Firefox browser before opening any othre browser in selenium web driver cross browser testing	new FirefoxDriver();	0
709015	708952	How to instantiate an object with a private constructor in C#?	// the types of the constructor parameters, in order\n// use an empty Type[] array if the constructor takes no parameters\nType[] paramTypes = new Type[] { typeof(string), typeof(int) };\n\n// the values of the constructor parameters, in order\n// use an empty object[] array if the constructor takes no parameters\nobject[] paramValues = new object[] { "test", 42 };\n\nTheTypeYouWantToInstantiate instance =\n    Construct<TheTypeYouWantToInstantiate>(paramTypes, paramValues);\n\n// ...\n\npublic static T Construct<T>(Type[] paramTypes, object[] paramValues)\n{\n    Type t = typeof(T);\n\n    ConstructorInfo ci = t.GetConstructor(\n        BindingFlags.Instance | BindingFlags.NonPublic,\n        null, paramTypes, null);\n\n    return (T)ci.Invoke(paramValues);\n}	0
2132214	2132198	Filtering out bad characters using a Regular Expression	myString = myString.Replace("^","");	0
326574	325375	Dropdown items on a ToolstripmenuItem and seeing if their items are checked	ToolStripMenuItem it = (ToolStripMenuItem)item.DropDownItems.Add(element);\nit.Name = element;\n// etc..	0
15643168	15643138	Wildcard Search in XElement	where item.Element(ns + text).Value.Contains(queryString.Text)	0
12261807	12261749	Remove permissions from a windows folder	dirinfo.SetAccessControl(dsec);	0
30367265	30359912	Python to C# StongBox[Single]	import clr\nimport System\ntempValue = clr.Reference[System.Single]()	0
34094221	34094165	How to combine 2 columns from database in DropDownList c# OleDb	string sql1 = "select *, ProductManufacturer + ' ' + ProductModel as someField  from ProductsTable";\n\nProductsList.DataTextField = "someField";	0
11552744	11552498	Apply changes for bound datagridview back to SQL Server CE	productsTableAdapter.Update(testDBDataSet2);	0
32695539	32660392	No Form to add fields to on a Syncfusion PDF	//Load the existing PDF document.\nPdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputfile);\n\n//Create the form if the form does not exist in the loaded document\nif (loadedDocument.Form == null)\n    loadedDocument.CreateForm();	0
16278724	16278474	Is there a better way to handle SOAP POST response - traversing XML	XmlDocument doc = new XmlDocument;\n   doc.Load(response.GetResponseStream);\n\n   XmlNode node = doc.SelectChildNode("/AddAgentResponse/agentLocalID");\n   if(node != null) { .... }	0
3669111	3668884	JSON serialization in WCF - Are object properties ordered alphabetically?	[DataContract]\npublic class MyClass\n{\n     [DataMember(IsRequired = true, Order = 1)]\n     public int Id { get; set; }\n}	0
16410173	16410112	Selecting A Property With a Given Value from an XML Object	element.Descendants("property").Where(x => x.Attribute("name").Value == "mdisk_grp_name" && x.Attribute("value").Value != "many").First();	0
25602713	25602508	Detect Single Windows Process Exit Event C#	Process process = new Process();\nProcessStartInfo startInfo = new ProcessStartInfo();\nprocess.StartInfo = startInfo;\n\nstartInfo.FileName = exeToRun;    \nprocess.Start();\nprocess.WaitForExit();	0
965501	965480	Can I have a Switch Statement with more than one Case Criteria?	switch (temp) {\n    case "NW":\n    case "New":\n       temp="new stuff";\n       break;\n}	0
25373339	25373284	Finding where a string is in a string	string longString = "the stirng with zeros and ones";\nstring searchString = "111000";\nint startIndex = longString.IndexOf(searchString);	0
32168872	32168737	crash on SetValue for grids wp8.1 universal	more_3rdrow.SetValue(RowDefinition.HeightProperty, new GridLength(172));	0
18364562	18364528	How to convert int/string in h.(fraction of day) format to Timespan	TimeSpan ts = TimeSpan.FromDays(value);	0
27438764	27438659	DataBinding a Radiobutton group	private void RadioButton_Bind()\n    { cmdstr = "select ID,ProfileRbnName from Profile_RbnFilter";\n        DataSet ds = new DataSet();\n        SqlDataAdapter adp = new SqlDataAdapter(cmdstr, con);\n        adp.Fill(ds);\n        RbnFilter.DataSource = ds.Tables[0];\n        RbnFilter.DataValueField = "ID";\n        RbnFilter.DataTextField = "ProfileRbnName";\n        RbnFilter.DataBind();\n    };	0
22025481	22025374	Consuming XML WebApi	studlist = response.Content.ReadAsAsync<List<Student>>().Result;\n       foreach (Student s in studlist)\n       {\n           Console.WriteLine("{0}\t{1}\t{2}\t{3}", s.Id, s.FName, s.LName, s.Email);\n       }	0
11019641	11018291	How to download email attachments in c#	MailClient oClient = new MailClient("TryIt");\n\n//ServerProtocol.Pop3 to ServerProtocol.Imap4 in MailServer constructor\n\nMailServer oServer  = new MailServer(sServer, \nsUserName, sPassword, bSSLConnection, \nServerAuthType.AuthLogin, ServerProtocol.Imap4);\n\n//by default, the pop3 port is 110, imap4 port is 143, \n//the pop3 ssl port is 995, imap4 ssl port is 993\n//you can also change the port like this\n//oServer.Port = 110;\n\n oClient.Connect(oServer);\n MailInfo [] infos = oClient.GetMailInfos();\n int count = infos.Length;\n if(count!=0)\n {\n   MailInfo info = infos[i];\n   Mail oMail = oClient.GetMail(info);\n   Attachment [] atts = oMail.Attachments;          \n }	0
3919385	3909540	Using Expression.Dynamic to generate a converter for value types	public static Converter<Object, T> CreateDynamicConverter<T>()\n    {\n        var param = Expression.Parameter(typeof(object)); \n        var expression = Expression.Lambda<Converter<object, T>>(\n            Expression.Condition(\n                Expression.Equal(\n                    param,\n                    Expression.Constant(\n                        DBNull.Value\n                    )\n                ),\n                Expression.Default(\n                    typeof(T)\n                ),\n                Expression.Dynamic(\n                    Binder.Convert(\n                        CSharpBinderFlags.ConvertExplicit, \n                        typeof(T), \n                        typeof(MyApplicationNameHere)\n                    ), \n                    typeof(T), \n                    param\n                )\n            ),\n            param\n        );\n        return expression.Compile();\n    }	0
26639854	26535732	Bejeweled Clone flame gem upward movement troubles	for (int gy = j - 1; gy <= j + 1; gy++)\n{\n    if (gy >= 0 && gy < gems.GetLength(0))\n    {\n        for (int gx = i; gx >= 0; gx--)\n        {\n            if (gy == j)\n            {\n                gems[gx, gy].MoveTowardsPosition(gems[gy, gx].Position.Swap() + new Vector2(0, -70), gemMoveSpeed * 1.8f, true, softMove: true);\n            }\n            else gems[gx, gy].MoveTowardsPosition(gems[gy, gx].Position.Swap() + new Vector2(0, -45), gemMoveSpeed * 1.8f, true, softMove: true);\n            moveTimer = 0;\n        }\n    }\n}	0
9712722	9712698	Get data type of a SQL Server column using C#	/* ... code .... */\n\nSystem.Type type = rdr.GetFieldType(c);\n\nswitch (Type.GetTypeCode(type))\n{\n    case TypeCode.DateTime:\n        break;\n    case TypeCode.String:\n        break;\n    default: break;\n}\n\n/* ... code .... */	0
23280455	23280412	Accessing elements of an Array of an Array of Objects	(from itemset1 in itemarr1\n from itemset2 in itemarr2\n from itemset3 in itemarr3\n select new[] { itemset1, itemset2, itemset3 }).ToList();	0
17299348	17299134	How can i get the center of a circleF in Emgu (C#)	PointF point = circle.Center;	0
19960110	19937072	how to can View information on the second DataGridView	private void gridCustomer_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if(e.RowIndex >= 0)\n        {\n            DataGridViewRow row = this.gridCustomer.Rows[e.RowIndex];\n            var selectedItme = row.Cells["Id"].Value;\n            var objOrder = orderBusiness.OrderFindById(Convert.ToInt32(selectedItme));\n\n            /* Add This */\n            BindingList<Order> bl = new BindingList<Order> { objOrder };                \n\n            gridOrder.DataSource = bl;\n\n        }\n    }	0
30457986	30455866	How can I cast an Object to a generic List I don't know the type parameter of in C++/CLI?	auto olist = (System::Collections::IList^)o;	0
9561800	9561717	Use created DLL in a console app?	var foo = new ApplicationCheck.ApCkr();\nConsole.WriteLine(foo.Netframeworkavailable());	0
23547867	23547637	Generic Parsing with default value	public static TOuput TryGenericParse<TInput, TOuput>(TInput input)\n{\n    var converter = TypeDescriptor.GetConverter(typeof(TOuput));\n    if (!converter.CanConvertFrom(typeof (TInput)))\n        return default(TOuput);\n    return (TOuput)converter.ConvertFrom(input);\n}\n\nbool bl = TryGenericParse<string, bool>("True");\ndouble dbl = TryGenericParse<string, double>("3.222");	0
10789423	10789214	How to not convert double to int C#?	public static int ToInt32(double val)\n{\n    if (val % 1 != 0)\n        throw new FormatException("The value is not an integer.");\n    return Convert.ToInt32(val);\n}	0
7572227	7572109	regular expression : find all digit in a string	var digits = someString.Where(c => char.IsDigit(c)).ToArray();	0
12716033	12713157	Creating View Models consisting of objects of other models in MVC3	public class MyViewModel\n{\n\n\n    public MyViewModel()\n    {\n        Customer= new CustomerViewModel ();\n        Address = new AddressViewModel();\n    }\n\n    public int OrderNumber{ get; set; }\n    public CustomerViewModel Customer  { get; set; }\n    public AddressViewModel Address { get; set; }\n\n}	0
13733534	13733160	Search rows in a table and compare them to other rows	var dspStartsWithR = From row in myDataTable.Rows\n                     Where (string)row("DSP Name").StartsWith("R|")\nvar dspStartsWithS = From row in myDataTable.Rows\n                     Where (string)row("DSP Name").StartsWith("S|")	0
17345797	17337821	iTextSharp remove line	PdfDictionary pg = reader.GetPageN(1);\n        PdfArray annotsArray = pg.GetAsArray(PdfName.ANNOTS);\n        if (annotsArray != null)\n        {\n            for (int k = 0; k < annotsArray.Size; k++)\n            {\n                PdfDictionary annot = (PdfDictionary) PdfReader.GetPdfObject(annotsArray[k]);\n                if(annot.GetAsName(PdfName.SUBTYPE).ToString() =="/Line")\n                {\n                    annotsArray.Remove(k);\n                }\n            }\n        }	0
6308210	6308183	C# format currency with leading spaces?	Console.WriteLine(string.Format("Blah Blah.....${0,10:#,##0.00}", number));	0
29562848	29562501	Converting JSON string to DataTable	{\n    "DatabaseName": "Employees",\n    "Rows": [\n        {\n            "FullName": "John Smith",\n            "Address": [\n                "123 Main St",\n                "Apt 202"\n            ],\n            "City": "NYC"\n        }\n    ]\n}	0
10667535	10667420	Counting number of files on a drive	kernel32.dll	0
11543634	11543563	Looping through a Listbox created on the fly	MaterialDB materials = new MaterialDB();\nDropDownList listBoxMaterials = new DropDownList();\nlistBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);\nlistBoxMaterials.DataTextField = "MaterialName";\nlistBoxMaterials.DataTextValue = "MaterialID";\nlistBoxMaterials.DataBind();\n\nstring materialString = "";    \n\nforeach (ListItem i in listBoxMaterials.Items)\n{\n    if (i.Value == row["MaterialTypeID"].ToString())\n    {\n        materialString = i.Text;\n    }\n}	0
14689946	14688583	Excel - Getting cell formatting is slow	ExcelPackage ep = new ExcelPackage(new FileStream(path, FileMode.Open, FileAccess.Read));\nvar sheet = ep.Workbook.Worksheets[1];\nforeach (var cell in sheet.Cells[sheet.Dimension.Address])\n{\n    var txt = cell.Text;\n    var font = cell.Style.Font;\n    if (!font.Bold || font.Italic || font.UnderLine)\n        txt = "";\n    var borderBottom = cell.Style.Border.Bottom.Style;\n    var borderTop = cell.Style.Border.Top.Style;\n    var borderLeft = cell.Style.Border.Left.Style;\n    var borderRight = cell.Style.Border.Right.Style;\n    // ...\n}	0
17511406	17511257	Save List to IsolatedStorageSettings	public class LyricsItem\n{\n    public LyricsItem()\n    {\n\n    }\n\n    public LyricsItem(LyricsItem item)\n    {\n        this.searchUrl = item.searchUrl;\n        this.croppingRegex = item.croppingRegex;\n    }\n\n    private string _searchUrl;\n    private string _croppingRegex;\n\n    public string searchUrl\n    {\n        get { return _searchUrl; }\n        set { _searchUrl = value; }\n    }\n\n    public string croppingRegex\n    {\n        get { return _croppingRegex; }\n        set { _croppingRegex = value; }\n    }\n}	0
32587688	32584550	How to programmatically create users in asp.net 5 using identity	var userManager=new HttpContextAccessor()\n     .HttpContext.ApplicationServices.GetService(typeof(UserManager<ApplicationUser>));	0
3022223	3022044	How to use IWindowsUpdateAgentInfo::GetInfo Method	WindowsUpdateAgentInfoClass WUAInfo = new WindowsUpdateAgentInfoClass();\n(int)WUAInfo.GetInfo("ApiMajorVersion");	0
7791832	7791783	passing parameters from asp.net to javascript	GridView1.Attributes.Add("onclick", "javascript:test('" + e.Row.ClientID + "')");	0
30552872	30552829	Working with a List of Lists as a Class in C#	Add(control);\nAdd(interaction);	0
18658797	18656599	datagridview with datasource and combobox	DataGridViewComboBoxColumn colbox = new DataGridViewComboBoxColumn();\ncolbox.DataSource = products_list.ToList();\ncolbox.ValueMember = "Key";\ncolbox.DisplayMember = "Value";\ndgvQuoteLines.Columns.Add( colbox );	0
21373081	21372957	How to loop through a list and also ignore specific item in the list based on condition before appending to string builder?	for (int i = 0; i < myList.Count; i++)\n        {\n            if (i == myList.Count - 1)\n                Assembler.AppendLine(myList[i]);\n            else\n            {\n                if (myList[i] != null)\n                    Assembler.AppendLine("(" + bullet++ + ") " + myList[i]);\n            }\n\n        }	0
13092566	13092353	How do I search for a word in the entire XML using Regex?	if (Regex.IsMatch(XMLString," Text=\"")==false)\n           XMLString = Regex.Replace(XMLString,@"(?<=<Run[^<]*)>", " Text=\"",RegexOptions.IgnoreCase);	0
1344242	1344221	How can I generate random alphanumeric strings in C#?	public static string RandomString(int length)\n  {\n    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";\n    var random = new Random();\n    return new string(Enumerable.Repeat(chars, length)\n      .Select(s => s[random.Next(s.Length)]).ToArray());\n  }	0
23340580	23328197	Databinding for ItemsControl not working after retargeting to WP8 from WP8.1	public async void SetMenuDataContent()\n{\n    this.DataContext = groups;\n}	0
3711313	3711224	Combine Elements in a List based on Type and Summate their Values, LINQ	items.GroupBy(i => i.Name)\n   .Select(g => new Item { Type= g.First().Name, Value = g.Sum(i => i.Value)})\n   .ToList()	0
17582902	17582793	C#/MEF don't work with [ImportingConstrutor] with default values	public Prim([Optional, DefaultParameterValue(0)] int val)\n{	0
3514704	3498506	Visual Studio 2010 keeps changing my winforms control	namespace WinFormTestX\n{\n    public class WinFormTestX\n    {\n        public int ID { get; set; }\n    }\n}	0
6410830	6410738	ASP.net c# help with chart control	Chart1.Series[1].Points.DataBindXY(dataView, "NAME", dataView, "TARGET");	0
12278426	12260524	How should the '\t' character be handled within XML attribute values?	var xmlDoc = new XmlDocument { PreserveWhitespace = false, };\nxmlDoc.LoadXml("<test><text attrib=\"Tab'\t'space' '\">Tab'\t'space' '</text></test>");\n\nusing (var xmlWriter = XmlWriter.Create(@"d:\TabTest.Encoded.xml"))\n{\n    xmlDoc.Save(xmlWriter);\n}	0
21996417	21996143	How to find and prioritize words from a given Enum list?	var Tokens = Regex.Split(myString, @"\s+");	0
7959121	7959005	Update UI from background Thread	delegate void Func<T>(T t);\nFunc del = delegate\n{\n\n  // UI Code goes here\n};\nInvoke(del);	0
32712681	32712257	Parse mysql datetime to c# DateTime	DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(1442915520000);	0
19919825	19919439	C#: Convert Japanese text encoding in shift-JIS and stored as ASCII into UTF-8	var badstringFromDatabase = "?`???l???p[?g?i[???I??";\nvar hopefullyRecovered = Encoding.GetEncoding(1252).GetBytes(badstringFromDatabase);\nvar oughtToBeJapanese = Encoding.GetEncoding(932).GetString(hopefullyRecovered);	0
11391240	11391024	Adding property changed event to a custom control	private bool _data;\npublic ButtonData Data {\n    get { return _data; }\n    set {\n        if (value != _data) {\n            // Unhook previous events\n            if (_data != null)\n                _data.PropertyChanged -= HandleButtonDataPropertyChanged;\n            // Set private field\n            _data = value;\n            // Hook new events\n            if (_data != null)\n                _data.PropertyChanged += HandleButtonDataPropertyChanged;\n            // Immediate update  since we have a new ButtonData object\n            if (_data != null)\n                Update();\n        }\n    }\n}\n\nprivate void HandleButtonDataPropertyChanged(object sender, PropertyChangedEventArgs e) {\n    // Handle change in ButtonData\n    Update();\n}\n\nprivate void Update() {\n    // Update...\n}	0
9798706	9798297	c# populating and using the value from a combo box with MySQL in a Windows Form Application	string val = ((DataRowView)dreturnCbox1.SelectedItem).Row[1];	0
15820334	15820255	Add style to data that is set within case statement in sql query	void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n  {\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n      switch (e.Row.Cells[3].Text)\n        {\n            case "Panding":\n                e.Row.Cells[3].ForeColor = System.Drawing.Color.Red;\n                break;\n            case "Complete":\n                e.Row.Cells[3].ForeColor = System.Drawing.Color.Green;\n                break;\n            case "In Review":\n                e.Row.Cells[3].ForeColor = System.Drawing.Color.Yellow;\n                break;\n            default:\n                e.Row.Cells[3].ForeColor = System.Drawing.Color.Black;\n                break;\n        };\n\n     }\n  }	0
4769394	4769381	how to add available COM ports to ComboBox useing C#	SerialPort.GetPortNames	0
29923136	29923073	Drop reference when only a single link to it	.Clear()	0
29094074	29094064	How to insert values from a table in another along with other values in sql server?	INSERT INTO table1 (col1,col2) \nSELECT @constant, col2 \nFROM table2	0
8884526	8884411	Any C# code to get resulset of a SQL query similar to that of SSMS output window	/// <summary>\n/// Read in all rows from the Dogs1 table and store them in a List.\n/// </summary>\nstatic void DisplayDogs()\n{\n    List<Dog> dogs = new List<Dog>();\n    using (SqlConnection con = new SqlConnection(\n    ConsoleApplication1.Properties.Settings.Default.masterConnectionString))\n    {\n    con.Open();\n\n    using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1", con))\n    {\n        SqlDataReader reader = command.ExecuteReader();\n        while (reader.Read())\n        {\n        int weight = reader.GetInt32(0);    // Weight int\n        string name = reader.GetString(1);  // Name string\n        string breed = reader.GetString(2); // Breed string\n        dogs.Add(new Dog() { Weight = weight, Name = name, Breed = breed });\n        }\n    }\n    }\n    foreach (Dog dog in dogs)\n    {\n    Console.WriteLine(dog);\n    }\n}	0
8921560	8921460	How can I specialize argument types for inheritors of a class?	abstract class Server<T> where T : IConnection\n{\n    public abstract void Initialize(ref IConnection conn);\n    public abstract void DataSent(T conn, byte[] data);\n    public abstract void DataReceived(T conn, byte[] data);\n}\n\nclass SpecialServer : Server<SpecialConnection>\n{\n    public override void Initialize(ref IConnection conn)\n    {\n        conn = new SpecialConnection(conn);\n    }\n\n    public override void DataSent(SpecialConnection conn, byte[] data)\n    {\n        //things\n    }\n\n    public override void DataReceived(SpecialConnection conn, byte[] data)\n    {\n        //stuff\n    }\n}	0
17445690	17422290	Programmatically retrieve version of an installed application	RegistryKey rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");\n\n            List<string> insApplication = new List<string>();\n\n            if (rKey != null && rKey.SubKeyCount > 0)\n            {\n                insApplication = rKey.GetSubKeyNames().ToList();\n            }\n\n            int i = 0;\n\n            string version = "";\n\n            foreach (string appName in insApplication)\n            {\n\n                RegistryKey finalKey = rKey.OpenSubKey(insApplication[i]);\n\n                string installedApp = finalKey.GetValue("DisplayName").ToString();\n\n                if (installedApp == "Google Chrome")\n                {\n                    version = finalKey.GetValue("DisplayVersion").ToString();\n                    return;\n                }\n                i++;\n            }	0
1142476	1142458	How can I create a windows service that is a standalone exe application?	public static void Main(string[] args)\n {\n      Service service = new Service();\n      if (args.Contains("-c", StringComparer.InvariantCultureIgnoreCase) || args.Contains("-console", StringComparer.InvariantCultureIgnoreCase))\n      {\n           service.StartService(args);\n           Console.ReadLine();\n           service.StopService();\n           return;\n      }\n      ServiceBase[] ServicesToRun = new ServiceBase[] \n                                    { \n                                    service \n                                    };\n      ServiceBase.Run(ServicesToRun);           \n  }	0
31546055	31545539	Parameter action<T> to an instance	class Car\n  : ICustomizeCar\n{\n   ICustomizeCar::Color {get;set;} \n\n    static Car MakeCustomCarWithColor(string color)\n    {\n        return new Car(c => c.Color = color);\n    }\n    public Car(Action<ICustomizeCar> customization)\n    {\n        customization(this);\n        Console.WriteLine(myCustom.Color);\n    }\n\n    public interface ICustomizeCar\n    {\n        string Color { get; set; }\n    }\n}	0
15823163	15823076	Button to return changes made to a property?	public Edit_Details(Student student)\n    {\n        InitializeComponent();\n        nameLabel.Text = student.Forename;\n        savebutton.Click+=(sender,e)=>\n          {\n             savebutton.Text=student.ChangeName(editNameTextBox.Text);\n          };\n    }	0
650762	336654	How to detect CPU speed on Windows 64bit?	Microsoft.Win32.RegistryKey registrykeyHKLM = Microsoft.Win32.Registry.LocalMachine;\nstring cpuPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor";\nMicrosoft.Win32.RegistryKey registrykeyCPUs = registrykeyHKLM.OpenSubKey(cpuPath, false);\nStringBuilder sbCPUDetails = new StringBuilder();\nint iCPUCount;\nfor (iCPUCount = 0; iCPUCount < registrykeyCPUs.SubKeyCount; iCPUCount++)\n{\n    Microsoft.Win32.RegistryKey registrykeyCPUDetail = registrykeyHKLM.OpenSubKey(cpuPath + "\\" + iCPUCount, false);\n    string sMHz = registrykeyCPUDetail.GetValue("~MHz").ToString();\n    string sProcessorNameString = registrykeyCPUDetail.GetValue("ProcessorNameString").ToString();\n    sbCPUDetails.Append(Environment.NewLine + "\t" + string.Format("CPU{0}: {1} MHz for {2}", new object[] { iCPUCount, sMHz, sProcessorNameString }));\n    registrykeyCPUDetail.Close();\n}\nregistrykeyCPUs.Close();\nregistrykeyHKLM.Close();\nsCPUSpeed = iCPUCount++ + " core(s) found:" + sbCPUDetails.ToString();	0
11830387	11829035	Newton Soft Json JsonSerializerSettings for object with Property as byte array	var json = JsonConvert.SerializeObject(new MyTestClass());\n\npublic class MyTestClass\n{\n    public string s = "iiiii";\n\n    [JsonConverter(typeof(ByteArrayConvertor))]\n    public byte[] buf = new byte[] {1,2,3,4,5};\n}\n\npublic class ByteArrayConvertor : Newtonsoft.Json.JsonConverter\n{\n\n    public override bool CanConvert(Type objectType)\n    {\n        return objectType==typeof(byte[]);\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        throw new NotImplementedException();\n    }\n\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        byte[] arr = (byte[])value;\n        writer.WriteRaw(BitConverter.ToString(arr).Replace("-", ""));\n    }\n}	0
8046464	8045370	How can I show messagebox when user register successfully and redirect him to Login page?	Response.Redirect("Login.aspx");	0
8326757	8326549	How do I implement my special ordering as CompareTo	public struct Foo : IComparable<Foo>\n{\n    public readonly int FirstLevel;\n    public readonly int SecondLevel;\n    public readonly int ThirdLevel;\n    public readonly int FourthLevel;\n\n    public int CompareTo(Foo other)\n    {\n        int result;\n\n        if ((result = this.FirstLevel.CompareTo(other.FirstLevel)) != 0)\n            return result;\n        else if ((result = this.SecondLevel.CompareTo(other.SecondLevel)) != 0)\n            return result;\n        else if ((result = this.ThirdLevel.CompareTo(other.ThirdLevel)) != 0)\n            return result;\n        else \n            return this.FourthLevel.CompareTo(other.FourthLevel);\n    }\n}	0
21778306	21776021	Using ServiceStack.Redis, how can I run strongly-typed read-only queries in a transaction	var cacheClient = new RedisClient();\n\ncacheClient.Watch("Users", "Groups");\n\nvar userHash = cacheClient.As<User>().GetHash<string>("Users");\nvar groupHash = cacheClient.As<Group>.GetHash<string>("Groups");\n\nusing (var trans = cacheClient.CreateTransaction())\n{\n    trans.QueueCommand(x =>\n    {\n        user = x.As<User>().GetValueFromHash(userHash, userKey);\n    });\n\n    trans.QueueCommand(y =>\n    {\n        group = y.As<Group>().GetValueFromHash(groupHash, groupKey);\n    });\n\n    trans.Commit();\n}	0
9739711	9739674	Get string[] elements with index of int[] indices	string[] result = indices.Select(i => stringArray[i]).ToArray()	0
2488472	2488426	How to play a MP3 file using NAudio	class Program\n{\n    static void Main()\n    {\n        using (var ms = File.OpenRead("test.mp3"))\n        using (var rdr = new Mp3FileReader(ms))\n        using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))\n        using (var baStream = new BlockAlignReductionStream(wavStream))\n        using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))\n        {\n            waveOut.Init(baStream);\n            waveOut.Play();\n            while (waveOut.PlaybackState == PlaybackState.Playing)\n            {\n               Thread.Sleep(100);\n            }\n        }\n    }\n}	0
28064803	28064760	Switch Collection In a Foreach	public interface IExternalIds\n    {\n        public IEnumerable<SomeType> ExternalIds { get; }\n    }\n\n    public class Album: IExternalIds\n    {\n        ...\n    }\n\n    public class Track: IExternalIds\n    {\n        ...\n    }\n\n    public ActionResult Details(string id, int type)\n    {\n       IEnumerable<Album> collection1 = ASR.Albums;\n       IEnumerable<Track> collection2 = TSR.Tracks;\n       var collectionToUse = ((type == 1) ? collection1 : collection2)\n        as IEnumerable<IExternalIds>;\n\n       foreach (var item in collectionToUse)\n       {\n           var result = item.ExternalIds.SingleOrDefault(x => x.Id == id);\n           if (result != null)\n           {\n               return View(item);\n           }\n       }\n       return View();\n    }	0
24807576	24807525	Regular expression of a string containing file path ending with [Number]x[Number].jpg (Thumbnail file)	string file = @"D:\Developer\Gallery\Maria-Menounos-at-Screen-Actors-Guild-Awards-2013--05-560x841.jpg";\n\nbool b = Regex.IsMatch(file, @"\d+x\d+\.jpg$");	0
2884401	2884360	Force all ASP.NET cache to expire	var enumerator = HttpRuntime.Cache.GetEnumerator();\nDictionary<string, object> cacheItems = new Dictionary<string, object>();\n\nwhile (enumerator.MoveNext())\n    cacheItems.Add(enumerator.Key.ToString(), enumerator.Value);\n\nforeach (string key in cacheItems.Keys)\n    HttpRuntime.Cache.Remove(key);	0
3668631	3668496	Most efficient way to parse a flagged enum to a list	public void SetRoles(Enums.Roles role)\n{\n  List<string> result = new List<string>();\n  foreach(Roles r in Enum.GetValues(typeof(Roles))\n  {\n    if ((role & r) != 0) result.Add(r.ToString());\n  }\n}	0
5168777	5168503	How to change the committing value in dataGridView?	void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n{\n   object new_value = e.FormattedValue;\n   // Do something\n   // If you dont like what you did, cancel the update\n   if(nope_didnt_like_it)\n   {\n      e.Cancel = true;\n   }\n}	0
19404068	19403839	Selecting table after selected one	foreach (var table in doc.DocumentNode.SelectNodes("//table[@class='KnownClass']/following-sibling::table[1]"))\n{\n    ...\n}	0
31029964	27825901	Get value of umbraco datatype in code	string val = umbraco.library.GetPreValueAsString(node.GetProperty<int>("countries"));	0
27483180	27483093	Reading in a CSV file	if(values.length < 2)\n{\n    //do what ever is needed in your case\n}	0
1882925	1882823	Need help trying to figure out to grab a column of data	foreach (Control c in Controls)\nif (c.Tag == "MyTag")\n{\n    //Do required actions\n}	0
3146995	3146762	Converting the datetime format	string newValue = DateTime.ParseExact(oldValue, "MM'/'dd'/'yyyy", null)\n                          .ToString("yyyy'-'MM'-'dd");	0
33270324	33259192	Fill a select box using geckofx c#	var document = GeckoWebBrowser1.Document;\nvar selectElement = (GeckoSelectElement)document.GetElementById("OA0001_dob_month");\nselectElement.SelectedIndex = 2;	0
7556077	7430467	How do I remove/unregister event handler from an event?	public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)\n{\nvar cell = tableView.DequeueReusableCell("reuseThis");\nif(cell == null)\n{\ncell = new UITableViewCell(UITableViewCellStyle.Default, "reuseThis");\n}\n\ncell.TextLabel.Text = Convert.ToChar(dash.oneToHundred[indexPath.Row]).ToString();\n\nvar button = UIButton.FromType(UIButtonType.RoundedRect);\nbutton.Frame = new System.Drawing.RectangleF(40f, 0f, 280f, 40f);\nbutton.SetTitle(dash.oneToHundred[indexPath.Row].ToString(),UIControlState.Normal);\nbutton.AddTarget (this, new Selector ("MySelector"), UIControlEvent.TouchDown);\nbutton.Tag = indexPath.Row;\ncell.ContentView.AddSubview(button);\n\nreturn cell;\n}\n\n[Export ("MySelector")]\nvoid ButtonEventHere (UIButton button)\n{\n\nConsole.WriteLine ("Hello! - Button clicked = " + button.Tag );\nConsole.WriteLine ( Convert.ToChar(dash.oneToHundred[button.Tag]).ToString() );\n}	0
26780775	26780731	How to find number of days from two string type dates?	DateTime date1 =   DateTime.ParseExact(dateString1, "d/M/yyyy", CultureInfo.InvariantCulture);\nDateTime date2 =   DateTime.ParseExact(dateString2, "d/M/yyyy", CultureInfo.InvariantCulture);\nvar days = (int)(date2-date1).TotalDays;	0
29599540	29599248	Checked items in a CheckedListBox	if(this.m_CheckedListbox.CheckedItems.Contains("Item1")\n{\n   //make an action, if it's checked.\n}\n\nif(this.m_CheckedListbox.CheckedItems.Contains("Item2")\n{\n   //make an action, if it's checked.\n}\n\n// etc...\n\n// this.m_CheckedListbox should be the name of your checked list box.	0
19805795	19805631	C# minimax algorithm implementation returning values such as -1000, -3000, -8000, etc	score += Minimax(...	0
11950133	11930917	How to select entire row on clicking the row header?	private void RadGridView_PreviewMouseDown(object sender, MouseButtonEventArgs e)\n{\n    if(e.RightButton == MouseButtonState.Pressed)\n        return;\n\n    var source = e.OriginalSource as DependencyObject;\n    if(source == null)\n        return;\n\n    var cell = source.FindVisualParent<GridViewCell>();\n    if(cell != null)\n    {\n        ((RadGridView)sender).SelectionUnit = GridViewSelectionUnit.Cell;\n    }\n    else\n    {\n        var row = source.FindVisualParent<GridViewRow>();\n        if(row != null)\n        {\n            ((RadGridView)sender).SelectionUnit = GridViewSelectionUnit.FullRow;\n        }\n    }\n}	0
3261006	3260935	Finding position of an element in a two-dimensional array?	public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)\n{\n    int w = matrix.GetLength(0); // width\n    int h = matrix.GetLength(1); // height\n\n    for (int x = 0; x < w; ++x)\n    {\n        for (int y = 0; y < h; ++y)\n        {\n            if (matrix[x, y].Equals(value))\n                return Tuple.Create(x, y);\n        }\n    }\n\n    return Tuple.Create(-1, -1);\n}	0
10084833	10083532	Convert xmlstring into XmlNode	XmlDocument doc = new XmlDocument();\n  XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);\n  doc.AppendChild(docNode);\n  XmlNode rootNode = doc.CreateElement("StatusList");\n  doc.AppendChild(rootNode);\n\n  //Create a document fragment and load the xml into it\n  XmlDocumentFragment fragment = doc.CreateDocumentFragment();\n  fragment.InnerXml = stxml;\n  rootNode.AppendChild(fragment);	0
33557964	33557863	Trying to execute something after a page is rendered not just loaded in wpf	private void OnWindowLoaded(object sender, RoutedEventArgs e)\n {\n     Dispatcher.BeginInvoke(new Action(() => YOUR_THING_HERE), DispatcherPriority.ContextIdle, null);\n }	0
14221098	14220173	Want a .Net Socket Event Handler for incoming data	void waitForData(SocketState state)\n    {\n        try\n        {\n            state.Socket.BeginReceive(state.DataBuffer, 0, state.DataBuffer.Length, SocketFlags.None, new AsyncCallback(readDataCallback), state);\n        }\n        catch (SocketException se)\n        {\n            //Socket has been closed  \n            //Close/dispose of socket\n        }\n    }\n\n    public void readDataCallback(IAsyncResult ar)\n    {\n        SocketState state = (SocketState)ar.AsyncState;\n        try\n        {\n            // Read data from the client socket.\n            int iRx = state.Socket.EndReceive(ar);\n\n            //Handle Data....\n\n            waitForData(state);\n        }\n        catch (ObjectDisposedException)\n        {\n            //Socket has been closed  \n            //Close/dispose of socket\n        }\n        catch (SocketException se)\n        {\n            //Socket exception\n            //Close/dispose of socket\n        }\n    }	0
11523825	11523766	Setting inner exception with activator, C#, Postsharp	throw (Exception)_convertToType\n    .GetConstructor(new Type[]{ typeof(string), typeof(Exception) })\n    .Invoke(new object[]{ _catchExceptionType });	0
19677434	19677273	How to modify only select parameters/attributes of an XML file with C#?	string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>\n        <configuration>\n          <!-- The xml file itself contains many other tags -->\n          <ConfigSection>\n            <GeneralParams>\n              <parameter key=""TableName"" value=""MyTable1"" />\n            </GeneralParams>\n          </ConfigSection>\n        </configuration>";\n\nvar xdoc = XDocument.Parse(xml);\nxdoc.Descendants("parameter")\n    .Single(x => x.Attribute("key").Value == "TableName" && x.Attribute("value").Value == "MyTable1")\n    .Attributes("value").First().Value = "MyTable2";	0
2922442	2921837	Asp.net Dictionary - Replace hard coded values with database values	// SQL Select Command\n    SqlConnection conn = new SqlConnection(connectionString);\n    SqlCommand mySqlSelect = new SqlCommand("SELECT TOP (100) PERCENT Tag, COUNT(Tag) AS Counter FROM dbo.CtagCloud GROUP BY Tag HAVING (COUNT(Tag) > 3) ORDER BY Counter DESC", conn);\n    mySqlSelect.CommandType = CommandType.Text;\n    SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);\n    DataSet myDataSet = new DataSet();\n    mySqlAdapter.Fill(myDataSet);\n\n    // create an instance for ArrayList\n    ArrayList myArrayList = new ArrayList();\n\n    // foreach loop to read each DataRow of DataTable stored inside the DataSet\n    foreach (DataRow dRow in myDataSet.Tables[0].Rows)\n    {\n        // add DataRow object to ArrayList\n        myArrayList.Add(dRow);\n    }	0
2613289	2594440	How should I store Dynamically Changing Data into Server Cache?	List<T>	0
18650232	18633096	Allocating memory for a rich text box in C#	private void button1_Click(object sender, EventArgs e)\n    {\n        string fullPath = "C:\\report.txt";\n        byte[] byteArra = System.IO.File.ReadAllBytes(fullPath);\n        textBox1.Text = Encoding.UTF8.GetString(byteArra);\n    }	0
451862	451529	Best way to parse string of email addresses	String str = "Last, First <name@domain.com>, name@domain.com, First Last <name@domain.com>, \"First Last\" <name@domain.com>";\n\nList<string> addresses = new List<string>();\nint atIdx = 0;\nint commaIdx = 0;\nint lastComma = 0;\nfor (int c = 0; c < str.Length; c++)\n{\nif (str[c] == '@')\n    atIdx = c;\n\nif (str[c] == ',')\n    commaIdx = c;\n\nif (commaIdx > atIdx && atIdx > 0)\n{\n    string temp = str.Substring(lastComma, commaIdx - lastComma);\n    addresses.Add(temp);\n    lastComma = commaIdx;\n    atIdx = commaIdx;\n}\n\nif (c == str.Length -1)\n{\n    string temp = str.Substring(lastComma, str.Legth - lastComma);\n    addresses.Add(temp);\n}\n}\n\nif (commaIdx < 2)\n{\n    // if we get here we can assume either there was no comma, or there was only one comma as part of the last, first combo\n    addresses.Add(str);\n}	0
8238799	8238755	How to display byte array hex values?	String.Format("{0,10:X}", hexValue)	0
8495432	8495403	Model View Controller implementation in C#	public class Controller	0
24062459	24062287	how to tell app to stop processing after exception is thrown	if(OpenCon())\n{\n            //Excecute the command\n            //This is where the exception is thrown when the computer is offline, by the data reader.\n            rdr = cmd.ExecuteReader();\n            //Show the confirmation message\n            Xceed.Wpf.Toolkit.MessageBox.Show("Saved");\n\n            //CLose the connection\n            CloseCon();\n}	0
32713353	32712256	How to expedite switching between iFrames in Selenium Webdriver with Java code?	var frameExample = driver.FindElement(By.className("myFrame"));\ndriver.switchTo().frame(frameExample);	0
17109974	17109688	How can I create an abstract Host property in a T4 template base class with VS2010?	private ITextTemplatingEngineHost _host;\nprivate ITextTemplatingEngineHost HostProperty {\n    get\n    {\n        if (_host == null)\n        {\n            _host = (ITextTemplatingEngineHost)this.GetType().GetProperty("Host").GetValue(this, null);\n        }\n        return _host;\n    }            \n}	0
5435874	5435820	Problems with passing Lambda LINQ statement as Func<>	RunTheMethod(name => dic.Where(entry => entry.Value == name)\n                         .Select(entry => entry.Key),\n              "John");	0
10059848	10055363	Caching Data Returned From a WebService MVC	public class CacheClass {\n    private static object DictLock = new Object();\n    private static Dictionary<K, V> CachedData;\n\n    public static V ReadDictionary(K key) {\n         V temp;\n         lock (DictLock) {\n              temp = CachedData[key];\n         }\n\n         return temp;\n    }\n    public static void SetDictionaryValue(K key, V value) {\n         lock (DictLock) {\n             CachedData.Add(key, value);\n         }\n    }\n}	0
5855302	5854645	Binding a datatable to a aspxgridview combobox column	(ASPxGridView1.Columns["SomeFieldName"] as GridViewDataComboBoxColumn).PropertiesComboBox.DataSource = yourDataTable;	0
3626554	3626361	how to set folder ACLs from C#	DirectoryInfo dInfo = new DirectoryInfo(strFullPath);\n\nDirectorySecurity dSecurity = dInfo.GetAccessControl();\n\n//check off & copy inherited security setting \ndSecurity.SetAccessRuleProtection(true, true); \n\ndInfo.SetAccessControl(dSecurity);	0
17459961	17459913	Read First Line of XML	if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "DiagReport")\n{\n// Good to go\n}	0
27656451	27645055	Unable to display data in gridview in asp.net	SqlConnection conobj=new SqlConnection;\nSqlCommand cmdobj=new SqlCommand(""Select BATSMAN_NAME from RUNS_STATS", conobj);\nSQlDataAdapter sdaobj=new SqlDataAdapter(cmdobj);\nDataTable dtobj=new DataTable();\nsdaobj.Fill(dtobj);\nGridView2.DataSource=dtobj;\nGridView2.DataBind();	0
29159286	29158980	Cookies expiring too quickly enough in c# asp.net webpages	timeout="0"	0
6637479	6637455	How to use XDocument to Read Multiple Embeded Elements	// untested\nList<string> genres = doc.Root\n      .Element("genre")\n      .Elements("name")\n      .Select(x => x.Value).ToList();	0
19547224	19546736	How to read complex XML in C#?	var reader = new XmlTextReader(<XmlPathFileName>);\nvar doc = new XmlDocument();\ndoc.Load(reader);\nreader.Close();\n\nvar root = doc.DocumentElement;\n        if (root == null)\n            return;\n\nvar node = root.SelectSingleNode("/Results/Product[Model='LB621120S']/Prices/Price[@StoreName='StoreF']");	0
9010064	9009986	How to cast an object to a Type extracted at runtime	If exp.Split(".").Count Then\n  Dim tp As Type = Nothing\n  tp = x.GetType\n  tp = tp.GetProperty(exp.Split(".").ElementAt(0)).PropertyType()\n  'Line below works, gets the right type, and now I need both x and y values passed in to be cast to this type.\n  Dim typ As Type = tp.GetType\n  x = Convert.ChangeType(x, typ)\nEnd If	0
9412027	9411310	Attaching a disconnected entity to entity framework	string containerName = context.DefaultContainerName;\nstring setName = context.CreateObjectSet<X>().EntitySet.Name;\nEntityKey key = new EntityKey(String.Format("{0}.{1}", containerName, setName), \n                              "KeyProperty", x.KeyProperty);\nif (context.ObjectStataManager.GetObjectStateEntry(key) != null)\n{\n    // Apply current values\n}\nelse\n{\n    // Attach and set state\n}	0
3827418	3827367	How can I take a picture from screen?	// the surface that we are focusing upon\n     Rectangle rect = new Rectangle();\n\n     // capture all screens in Windows\n     foreach (Screen screen in Screen.AllScreens)\n     {\n        // increase the Rectangle to accommodate the bounds of all screens\n        rect = Rectangle.Union(rect, screen.Bounds);\n     }\n\n     // create a new image that will store the capture\n     Bitmap bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);\n\n     using (Graphics g = Graphics.FromImage(bitmap))\n     {\n        // use GDI+ to copy the contents of the screen into the bitmap\n        g.CopyFromScreen(rect.X, rect.Y, 0, 0, rect.Size, CopyPixelOperation.SourceCopy);\n     }\n\n     // bitmap now has the screen capture	0
2490231	2490126	Create an XML file using Datasets Using info from XML Schema	var dataSet = new DataSet();\ndataSet.ReadXmlSchema(new StringReader(@"schema goes here or something"));	0
7758668	7751972	Fill DataTable having one column as DateTime value and bind with DataGridView	DataTable dt = new DataTable();\ndt.Columns.Add("name", typeof(string));\ndt.Columns.Add("dayofbirth", typeof(DateTime));\n\n// Fill your data table\n...\n\n// Bind your data table against the grid view.    \ndataGridView1.DataSource = dt;\n\n// Set format styles for your date columns (after binding)\nCultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");\ndataGridView1.Columns[1].DefaultCellStyle.FormatProvider = ci;\ndataGridView1.Columns[1].DefaultCellStyle.Format = ci.DateTimeFormat.LongDatePattern;	0
1606988	1606966	Generic Method Executed with a runtime type	typeof(ClassExample)\n.GetMethod("DoSomething")\n.MakeGenericMethod(p.DisplayType)\n.Invoke(this, new object[] { p.Name, p.Value });	0
21065474	21065419	Regular expressions: Get all matching strings matching a pattern	string strRegex = @"x=\d+'>\d+<";\nRegex myRegex = new Regex(strRegex, RegexOptions.None);\nstring strTargetString = @"Some data ..... x=123'>555< ... Some Data x=5433'>4212<";\n\nforeach (Match myMatch in myRegex.Matches(strTargetString))\n{\n  if (myMatch.Success)\n  {\n    // Add your code here\n  }\n}	0
28179339	28177444	MYSql with C# in Visual Studio. How to return a boolean if a database exists	public bool DatabaseExists(string dbname)\n{\nstring connStr = "server=localhost;database=INFORMATION_SCHEMA;";\n\nusing (MySqlConnection myConnection = new MySqlConnection(connStr))\n{\n string sql = "show databases";\n MySqlCommand myCommand = new MySqlCommand(sql, myConnection);\n myConnection.Open();\n MySqlDataReader myReader = myCommand.ExecuteReader();\n while (myReader.Read())\n {\n   string db =  myReader["Database"].ToString();\n   if (db == dbname)\n     return true;\n }\n}\nreturn false;\n}	0
7822349	7822316	Non-Nullable String Initializes as Null	String.Empty	0
28808706	28808545	Get an enumerator for the implemented interface from a class array	public IEnumerator<IReadonlyAssignedTasks> GetEnumerator()\n{\n    return _assignedTasks.Cast<IReadonlyAssignedTasks>().GetEnumerator();\n}	0
17677352	17673437	WP7 app, MethodAccessException on WP7 device but works fine on WP8 device	[assembly: InternalsVisibleTo("Facebook")]	0
25352880	25352462	How to send XML content with HttpClient.PostAsync?	var httpContent = new StringContent(workItem.XDocument.ToString(), Encoding.UTF8, "application/xml");	0
33308894	33307397	Concatenating Text and Hyperlink in same Table Cell C#	Literal lit = new Literal();\n   string myURL = "http://www.google.com";\n   lit.Text = "If you need help... contact <a onclick=\"javascript:void(window.open('" + myURL + "'\";>Help Link</a>)";	0
11724648	11724614	Passing uniqueidentifier parameter to Stored Procedure	myCommand.Parameters.Add("@BlogID", SqlDbType.UniqueIdentifier).Value = new Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04");	0
16496974	16496906	How to call load event in button click event	Form_Load(this, null);	0
29244450	29241013	How to validate a parameter's type in method when using Roslyn	SemanticModel.GetTypeInfo()	0
32161408	32161335	Convert short to int	int myInt = (int)BitConverter.ToInt16(data, 2);	0
8647418	8647359	DateTime in sql in different localizations	IDbCommand db = \n    new SqlCommand("insert into table (myDateField) values (@myDateParam)");\ndb.Parameters.Add(new SqlParameter("@myDateParam", DateTime.Now));	0
3888911	3888150	toolstripbutton with images for each state	private void Button1_OnMouseHover\n{\n   BackGroundImage = "test.png";\n}	0
8618589	8592990	Silverlight on Windows Phone: IValueConverter is never called for a custom bound property	public partial class ChartEx : UserControl\n{\n    public event EventHandler DataSourceChanged;\n\n    public object DataSource\n    {\n        get { return GetValue(DataSourceProperty); }\n        set { SetValue(DataSourceProperty, value); }\n    }\n\n    public static readonly DependencyProperty DataSourceProperty =\n        DependencyProperty.Register(\n            "DataSource",\n            typeof(object),\n            typeof(ChartEx),\n            new PropertyMetadata(true, OnDataSourcePropertyChanged));\n\n    private static void OnDataSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n        ChartEx source = d as ChartEx;\n\n        if (source.DataSourceChanged != null)\n            source.DataSourceChanged(source, new EventArgs());\n    }	0
11038884	11038786	How to unit test that a list inputed to a method is less than 100	itemMasterBusinessClientMock.Verify(x => x.SaveInventoryItemLoad(It.Is<List<InventoryItemLoadProxy>>(l=>l.Count < 100)), Times.Once());	0
4674870	4674839	Check if a string start with any character in a list	char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };\n private bool startWithColumn(string toCheck)\n {\n     return toCheck != null\n                && toCheck.Length > 0\n                && columnChars.Any( c => c == toCheck[0] );\n }	0
23210896	23200032	DynamicLINQ - Escaping double quotes inside strings	Context.Users.Where("FirstName == @0", "\"Bob\"");	0
20471539	20441950	How to perform Unbound Expression and set that value in bounded column?	private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)\n{\n    var row = gridView1.GetFocusedDataRow();\n\n    // Calculating the dicsount %\n    if (e.Column == colDiscountAmout)\n    {\n        var productPrice = Convert.ToDecimal(row["Price"]);\n        var discountAmout = Convert.ToDecimal(row["DiscountAmout"]);\n        row["DiscountPercent"] = (discountAmout * 100) / productPrice;\n    }\n\n    // Calculating the discount amount\n    if (e.Column == colDiscountPercent)\n    {\n        var productPrice = Convert.ToDecimal(row["Price"]);\n        var discountPercent = Convert.ToDecimal(row["DiscountAmout"]);\n        row["DiscountAmout"] = productPrice * (discountPercent / 100);\n    }\n}	0
9404941	9395009	Define optional self-referencing one-many relationship with Fluent Api	public int ? ValueAttributeId { get; set; }	0
27313923	26762516	Treeview from dictionary	this.mappen = new List<Map>(DatabaseHelper.GetAllMaps());\n            this.mappen.ForEach(delegate(Map pI)\n            {\n                pI.Childs = this.mappen.Where(delegate(Map pCh)\n                {\n                    return pCh.ParentMap.Mapnr == pI.Mapnr;\n\n                }).ToList();\n\n            });	0
23970448	23970391	Calling a method from WS, parameter input type issue	service.getVCardsAsync(new ObservableCollection<int>(cardList))	0
25756677	25756534	How do I add a new line under a font.DrawText line?	font.DrawText(null, String.Format("{0:N0} fps \n {1}",\n    this.FPS.GetFPS(),\n    DateTime.Now.ToString()), 5, 5, SharpDX.Color.Red);	0
17100930	17100237	WPF using Animation to move a component	public static readonly DependencyProperty MarginProperty	0
3885973	3833440	Infragistics UltraGrid: How to force a CellUpdate event after user selects from drop down	grid.AfterCellListCloseUp += delegate { grid.UpdateData(); };	0
783149	783119	How do you determine when a filename was last changed in C#?	FileInfo fi1 = new FileInfo(path);	0
23164136	23164106	List to datagridView datasource	class TermekRendeles\n{\n  public int TermekID {get; set;}\n  public string TermekNev {get; set;}\n  public int Mennyiseg {get; set;}\n}	0
12706259	12701783	Launch the vba editor from excel by code	Application.Goto "MarcoName"	0
16699537	16399151	How to get the profile picture from facebook, gmail, twitter by using DotNetOpenAuthentication?(Description Indside)	graph.Link.AbsoluteUri.Replace("www.facebook", "graph.facebook") + "/picture"	0
19469871	19469260	Inheritance in ViewModel Design on MVVM	public PasswordModel\n{\n    public string Password { get; set; }\n\n    public string PasswordConfirm { get; set; }\n}\n\npublic UserSettingViewModel\n{\n    public PasswordModel Password { get; set; }\n\n}	0
17320791	17320595	Replacing the task scheduler in C# with a custom-built one	System.Threading.Tasks	0
8280503	8279963	XNA Beginner: How do I merge arrays of vertices into a single vertex buffer	int NumVerts = Objects.Sum(o => o.Vertex.Length);\nint NumIndexes = Objects.Sum(o => o.Index.Length);\n\nVertexPositionColor[] Vertex = new VertexPositionColor[NumVerts];\nint[] Index = new int[NumIndexes];\n\nint VertexOffset = 0;\nint IndexOffset = 0;\nforeach (Object object in Objects)\n{\n    for (int v=0; v<object.Vertex.Length; v++)\n    {\n        Vertex[VertexOffset+v] = object.Vertex[v] + VertexOffset;\n    }\n\n    for (int i=0; i<object.Index.Length; i++)\n    {\n        Index[IndexOffset+i] = object.Index[i] + VertexOffset;\n    }\n\n    VertexOffset += object.Vertex.Length;\n    IdnexOffset += object.Index.Length;\n}	0
18661182	18661112	Normalize a vector with one fixed value	ratio = (1-fixedElement) / sumOfAllOtherElements;\n\nEachNonFixedElement *= ratio;	0
7109434	7108125	Generating RouteUrl in MVC3 returns null in one case	routes.MapRoute(\n    "Date-ByDay", // Route name\n    "Date/{year}/{month}/{day}", // URL with parameters\n    new { controller = "Date", action = "Index" } // Parameter defaults\n  );\n\n  routes.MapRoute(\n    "Date-ByMonth", // Route name\n    "Date/{year}/{month}", // URL with parameters\n    new { controller = "Date", action = "Index", month = UrlParameter.Optional } // Parameter defaults\n  );\n\n  routes.MapRoute(\n    "Date-ByYear", // Route name\n    "Date/{year}", // URL with parameters\n    new { controller = "Date", action = "Index", year = UrlParameter.Optional } // Parameter defaults\n  );	0
29072388	29072211	E.F. lambda expression for a List<string> with StartsWith	predicate = (e =>\n                e.USED == 0\n            && codes.Any(x => x.StartsWith(e.CODE))\n            && e.CHINA_CODES_HEADER_ID == batch.Id\n            && e.CODE_LEVEL == codeLevel\n            && (e.BATCH_ID == batch.Id || e.BATCH_ID == null));	0
10191194	10190813	how to delete a specific text / message showed in a ListView ?	void DeleteIfNecessary(string message)\n{\n    ListViewItem listViewItem = FindListViewItemForMessage(message);\n    if (listViewItem == null)\n    {\n        // item doesn't exist\n        return;\n    }\n\n    this.listView1.Items.Remove(listViewItem);\n}\n\nprivate ListViewItem FindListViewItemForMessage(string s)\n{\n    foreach (ListViewItem lvi in this.listView1.Items)\n    {\n        if (StringComparer.OrdinalIgnoreCase.Compare(lvi.Text, s) == 0)\n        {\n            return lvi;\n        }\n    }\n\n    return null;\n}	0
22308784	22308257	Find records that were active in a certain date range using linq c#	(d.DateActivation == null || dtStart < d.DateDeactivation) && dtEnd > d.DateActivation	0
398750	398651	VB to C# Translate Event Handler that Implements Interface Event	public event PropertyChangedEventHandler PropertyChanged;	0
12127565	12127498	Access TextBox from Static method in C#?	class MyForm : Form\n{\n    Database db;\n\n    public Form()\n    {\n        db = new Database(this);\n    }\n\n    public void DoSomething()\n    {\n        var errors = db.Login("", "");\n        if (errors.Any())\n            label1.Text = errors.First(); // Or you can display all all of them\n    }\n}\n\nclass Database\n{    \n    public List<string> Login(string username, string password)\n    {\n        var errors = new List<string>();\n\n        if (string.IsNullOrEmpty(username))\n            errors.Add("Username is required");\n\n        if (string.IsNullOrEmpty(password))\n            errors.Add("Password is required");\n\n        [...]\n\n        return errors;\n    }\n}	0
29020699	29020553	Configuration Specific Variable Values in Windows Phone 8 Apps	public class ConfigurationLoader()\n{\n    private readonly string _configFile;\n\n    public ConfigurationLoader()\n    {\n        #if DEBUG \n            _configFile = "app.Debug.config"; \n        #else \n            _configFile = "app.Release.config";\n        #endif\n    }\n\n    public UniversalAppConfig LoadCofig()\n    {\n        // Read file\n\n        // Create UniversalAppConfig\n    }\n}\n\npublic class UniversalAppConfig()\n{\n    public int ConfigurationValueA { get; set; }\n\n    public int ConfigurationValueB { get; set; }\n}	0
752987	752946	performance issues with finding nth occurence of a character with a regular expression	public static int NthIndexOf(this string target, char testChar, int n)\n{\n   int count = 0;\n\n   for(int i=0; i<target.Length; i++)\n   {\n      if(target[i] == testChar)\n      {\n         count++;\n         if(count == n) return i;  \n      }\n   }\n\n   return -1;\n}	0
2329957	2329930	Problem with copy byte[] into another byte[]	byte[] result = new byte[salt.Length + password.Length];\n    salt.CopyTo(result, 0);\n    password.CopyTo(result, salt.Length);	0
7889002	4830939	How to pass a instance of XmlDocument to argumentTransformList?	XmlDocument xmlDoc = new XmlDocument();\nobject param = xmlDoc.CreateNavigator().Evaluate("/");\nmyXmlControl.TransformArgumentList.AddParam("xml_document_content",param );	0
6049442	6049373	Checking if all numbers in a List are repeated	public bool Check(String number)\n{\n   return number.Distinct().Count() > 1;\n}	0
10433714	10433647	How to load XML Elements using LINQ from XDocument into a class (not using Descendants)	XElement settings = GvXMLDoc.Element("Backup").Element("Settings");\n\nBackupSettings GvBackupSettings = new BackupSettings\n{\n    IncludeDateStamp = (bool)settings.Element("IncludeDateStamp"),\n    DatePrefix = (bool)settings.Element("DatePrefix"),\n    ...\n};\n\nvar s = GvBackupSettings.DateSuffix;\nvar t = GvBackupSettings.DateFormat;	0
24939368	24939172	lambda expressions improve cod	protected void Process1(List<SomeClass>mylist) {\n    Process (mylist, item => !SomeClass.Validate (item));\n}\n\nprotected void Process2(List<SomeClass>mylist) {\n    Process (mylist, item => !SomeClass.Validate (item) || item.Value == 0);\n}\n\nprivate void Process(List<SomeClass>mylist, Func<SomeClass, bool> validator)\n{\n    foreach (var item in mylist) {\n        if (validator (item)) {\n            continue;\n        }\n        DoStuff (item);\n        DoMoreStuff (item);\n        DoEvenMoreStuff (item);\n    }\n}	0
9000430	9000396	How to add multiple Anonymous Type in c#?	var source = new [] { new {  Id = "1", Name = "Name1"},\n                      new {  Id = "2", Name = "Name2"}};	0
29437587	29332926	How should a refresh be handled after a redirect on ModelState failure using the strict PRG pattern?	[ImportModelStateFromTempData]	0
21479540	21479348	Find and replace/remove two words from a string using regex c#	string pattern =  @"\b(USE|GO|MORE|FEW_MORE|AND_SO_ON)\b";	0
21421252	21421174	How do I make a text box in a form not visible until after I click compute in C#?	private void ResetControls()\n{\n   txtMyControl.Visible=false;\n   //here comes more logic for what to do upon reset.\n}\n\nprivate void form_load(...\n{\n  ResetControls();\n}\n\nprivate void btnReset_Click(...\n{\n  ResetControls();\n}	0
28364815	28364116	Window shown as dialogue losts its focus - wpf	var item = new addItem();\n item.Owner = this;\n item.ShowDialog();	0
24035961	23994964	Print List string in new line in chart legends	LegendItem firstItem = new LegendItem();\n        Font f = new Font("Serif", 14, FontStyle.Bold);\n\n        LegendCell firstCell = new LegendCell();\n\n\n        for (int l = 0; l < list.Count;l++ )\n        {\n\n            firstCell.Text = list[l] + Environment.NewLine  +firstCell.Text;\n\n            firstCell.Font = f;\n\n        } firstItem.Cells.Add(firstCell);	0
4270065	4270008	Recursion ??? Printing a Sequence of Numbers	public void Numbers(int iteration, int number, int limit)\n{\n  if(iteration < limit) {\n    Console.WriteLine(number);\n    Numbers(iteration + 1, number + iteration);\n  }\n}\n\nNumbers(0,1,5);	0
10549704	10549316	Get all country names used in Bing Maps SOAP Services	GeoServiceReference.GeocodeServiceClient client = new GeoServiceReference.GeocodeServiceClient();\n\n        var countries = new List<string>();\n\n        for (double lat = 0; lat < 360; lat+=0.1)\n            for(double lon = 0; lon < 360; lon+=0.1)\n        {\n            var result = client.ReverseGeocode(new GeoServiceReference.ReverseGeocodeRequest\n            {\n                Location = new GeoServiceReference.Location\n                {\n                    Latitude = lat,\n                    Longitude = lon\n                }\n            });\n\n            if (!countries.Contains(result.Results.First().Address.CountryRegion))\n            {\n                Console.WriteLine(result.Results.First().Address.CountryRegion);\n                countries.Add(result.Results.First().Address.CountryRegion);\n            }\n        }	0
30359370	30359322	Add mutliple Lists to one list	var joined = GetList1()\n    .Concat(GetList2())\n    .Concat(GetList3().RunFilter())\n    ...\n    ;	0
4997006	4996458	How to apply a filter in a LINQ to SQL expression only if results exist when the filter is applied?	var customerData = \n    from c in db.Customers\n    let orders = db.Orders.Where(o => o.OrderNumber == c.orderNumber &&\n        o.Group.GroupTypeId != (int)GroupTypeId.INTERNAL &&\n        !o.Deleted)\n    let orders2 = orders.Where(o => o.ProductAreaId == c.productAreaId)\n    select new \n    {\n        id = c.Id,\n        name = c.Name,\n        lastOrder = c.productAreaId != null && orders2.Any() ?\n            orders2.FirstOrDefault() :\n            orders.FirstOrDefault() \n    };	0
17012358	17012323	How to make class truly Immutable?	IReadOnlyList<T>	0
17946648	17946431	How to Export Crystal Report to Excel using CrystalReport Object and TableAdapter?	CrystalDecisions.CrystalReports.Engine.ReportClass rpt=new ReportClass();\n rpt.ExportToDisk(ExportFormatType.Excel, "FilePath");	0
25723164	25723101	Order list by parameter and position in second list	var firstListDic = firstList.ToDictionary(o => o.id);\nvar secondListSet = new HashSet<int>(secondList);\nvar result = secondList.Select(i => firstListDic[i])\n                       .Concat(firstList.Where(o => !secondListSet.Contains(o.id)))\n                       .ToList();	0
25601010	25600980	How do I use the || operator in a lambda expression	db.assets.Where(u => u.userName.Equals(userName)\n                     || u.category.Equals("DefaultMapMarker"))	0
8227050	8226975	c# : selecting a variable from several, randomly	int value1 = 3;\nint anotherValue = 5;\nint value2 = 1;\n\nint[] selectableInts = new int[3] { value1, anotherValue, value2 };\n\nRandom rand = new Random();\n\nint randomValue = selectableInts[rand.Next(0, selectableInts.Length)];	0
11395428	11393344	I need load load the array of items from an xml file but the top level does not read listed items	public class rootname\n{\n    public rootname() { }\n\n    [XmlElement("AListItem")]\n    public List<AListItem> DataList { get; set; } // <<< public!\n\n    public string Name { get; set; }\n}	0
10903521	10903452	C# Passing a class type as a parameter	public void FillWsvcStructs<ClassType>(DataSet ds) where ClassType : IElemRequest, new()\n{\n    IFoo.Request = ds.DataTable[0].Request;\n    IFoo.Modulebq = string.Empty;\n    IFoo.Clasific = string.Empty;\n    IFoo.Asignadoa = ds.DataTable[0].Referer;\n    IFoo.Solicita = "Jean Paul Goitier";\n\n\n    // Go with sub-Elems (Also "Interfaceated")\n    foreach (DataSet.DataTableRow ar in ds.DataTable[1])\n    {\n        if ((int) ar.StatusOT != (int)Props.StatusOT.NotOT)\n        {\n            IElemRequest req = new ClassType();\n\n            req.Id = string.Empty;\n            req.Type = string.Empty;\n            req.Num = string.Empty;\n            req.Message = string.Empty;\n            req.Trkorr = ar[1];\n            TRequest.Add(req);\n        }\n    }\n}	0
2854514	2854372	Recursive QuickSort suffering a StackOverflowException	...\n        for (i = 1; i <= highPos; i++)\n        {\n            if (i == pivot) continue; // Add this\n            if (this[i].CompareTo(this[pivot]) <= 0)\n        ...\n        for (i = 1; i <= leftList.Count; i++)\n            tempList.Add(leftList[i]);\n        tempList.Add(this[pivot]); // Add this\n        for (i = 1; i <= rightList.Count; i++)\n            tempList.Add(rightList[i]);\n        ...	0
1169257	1169170	Pass Additional ViewData to a Strongly-Typed Partial View	Html.RenderPartial(\n      "ProductImageForm", \n       image, \n       new ViewDataDictionary { { "index", index } }\n);	0
4154654	4154605	How to loop within a Linq to XML statement	packagedProduct.Installs.Select( item => new XElement("File ").. );	0
26811057	26810605	SQL select parameter contains apostrophe	string commandText = "SELECT * FROM " + toDB + ".dbo.Product WHERE Name= @prodName and SKU=@sku;";\n\n        using (SqlConnection c = new SqlConnection(cs))\n        {\n            SqlCommand command = new SqlCommand(commandText, c);\n            command.Parameters.Add("@prodName", SqlDbType.VarChar);\n            command.Parameters["@prodName"].Value = productName;\n\n            command.Parameters.Add("@sku", SqlDbType.VarChar);\n            command.Parameters["@sku"].Value = newsku;\n\n            c.Open();\n            object o = (object)command.ExecuteScalar();\n            c.Close();\n            if (o != null)\n                result = true;\n        }	0
21831711	21831605	Write cookies from subdomain and read from another subdomain without changing web.config	.mydomain.com	0
8535351	8533858	select one value of checkboxCombobox	private void PreDefSerials_SelectedValueChanged(object sender, EventArgs e)\n{\n  if (!one_select)\n    return;\n  else\n  {\n    if (PreDefSerials.SelectedIndex > -1)\n    {\n      //only uncheck items if the current item was checked:\n      if (PreDefSerials.CheckBoxItems[PreDefSerials.SelectedIndex].CheckState == CheckState.Checked)\n      {\n        // stop firing event for now:\n        PreDefSerials.SelectedValueChanged -= PreDefSerials_SelectedValueChanged;\n\n        for (int i = 0; i < PreDefSerials.CheckBoxItems.Count; i++)\n        {\n          if (i != PreDefSerials.SelectedIndex)\n          {\n            PreDefSerials.CheckBoxItems[i].CheckState = CheckState.Unchecked;\n          }\n        }\n\n        // wire event again:\n        PreDefSerials.SelectedValueChanged += PreDefSerials_SelectedValueChanged;\n      }\n    }\n  }\n}	0
29222801	29222356	i want to convert from int64 to byte	com.Parameters.Add("@name", SqlDbType.TinyInt).Value = this.phone;	0
31240171	31239897	How to get total number of table elements having ID inside a DIV tag using Selenium Webdriver and C#	WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]"));\n\n//Get list of table elements using tagName\nList<WebElement> list = webElement.findElements(By.tagName("table"));	0
22671227	22671180	How to check effectively if one path is a child of another path in C#?	if (!Path.GetFullPath(A).TrimEnd(Path.DirectorySeparatorChar).Equals(Path.GetFullPath(B).TrimEnd(Path.DirectorySeparatorChar), StringComparison.CurrentCultureIgnoreCase)\n    && (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B) + Path.DirectorySeparatorChar, StringComparison.CurrentCultureIgnoreCase)\n    || Path.GetFullPath(B).StartsWith(Path.GetFullPath(A) + Path.DirectorySeparatorChar, StringComparison.CurrentCultureIgnoreCase)))\n   { /* ... do your magic ... */ }	0
16771504	16771291	How can I check if text file is in use?	Process[] pList = Process.GetProcessesByName("notepad");\nforeach(Process p in pList)\n{\n    if(p.MainWindowTitle.Contains("MyFilename.txt")\n       ......\n}	0
16787133	16786655	Remove an object in a List after several seconds XNA C#	//Declares a timespan of 2 seconds\nTimeSpan timeSpan = TimeSpan.FromMilliseconds(2000);\n\n\npublic override void Update(GameTime gameTime)\n{\n    // Decrements the timespan\n    timeSpan -= gameTime.ElapsedGameTime;\n\n    // If the timespan is equal or smaller time "0"\n    if (timeSpan <= TimeSpan.Zero )\n    {\n        // Remove the object from list\n        scoreList.RemoveAt(1);\n        // Re initializes the timespan for the next time\n        timeSpan = TimeSpan.FromMilliseconds(2000);\n\n    }\n\n    base.Update(gameTime)\n}	0
26293882	26289515	Convert list of jpgs to pdf with ghostscript	% Usage example:\n%   (jpeg-6/testimg.jpg) viewJPEG	0
13012498	12981472	Expression to convert a Guid to a string	if (sourceProperty.PropertyType == typeof(Guid) && targetProperty.PropertyType == typeof(string))\n{\n    Expression callExpr = Expression.Call(Expression.Property(sourceParameter, sourceProperty), typeof(Guid).GetMethod("ToString", new Type[] { }));\n    bindings.Add(Expression.Bind(targetProperty, callExpr));\n}	0
17589763	17589362	Copy paste from clipboard in c# windows text box in the same format	string data = Clipboard.GetText(TextDataFormat.Html);	0
15090173	15089205	Set Focus on Dynamically added control in AJAX Update Panel	label.Text = "SomeText";\n    label.ID = "lblMessage" + messageNumber;\n    if (heading)\n    {\n        label.Attributes.Add("style", "font-weight: bold;")                \n    }\n    UpdatePanel1.ContentTemplateContainer.Controls.Add(label);\n    plcHolder.Controls.Add(label);\n    label.Focus();	0
1541042	1541016	How to tell if a PropertyInfo is of a particular enum type?	static void DoWork()\n{\n    var myclass = typeof(MyClass);\n    var pi = myclass.GetProperty("Enum");\n    var type = pi.PropertyType;\n\n    /* as itowlson points out you could just do ...\n        var isMyEnum = type == typeof(MyEnum) \n        ... becasue Enums can not be inherited\n    */\n    var isMyEnum = type.IsAssignableFrom(typeof(MyEnum)); // true\n}\npublic enum MyEnum { A, B, C, D }\npublic class MyClass\n{\n    public MyEnum Enum { get; set; }\n}	0
12390557	12390387	storing or appending contents (array) of a for loop to pass to another function - encapsulation	class MyClass\n{\n    List<Webservice.Information> _webServiceInformation = new List<Webservice.Information>()\n\n    public void LogonAndStoreInfo()\n    {\n        Webservice.Information[] pubinfo = myflo.LogOn(username, password, ref ticket, out settings, out users,out terms, out currentUser);\n\n        for (int i=0; i < pubInfo.Length; i++)\n        {\n            StorePubInfo(pubinfo);\n        }\n\n        Webservice.Information[] myPubInfo = GetPubInfo();\n    }\n\n    void StorePubInfo(Webservice.Information info)\n    {\n        _webServiceInformation.Add(info);\n    }\n\n    Webservice.Information[] GetPubInfo()\n    {\n        return _webServiceInformation.ToArray();\n    }\n}	0
13023171	13023147	How to write contents of an array to a text file? C#	System.IO.File.WriteAllLines("scores.txt",\n    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));	0
4699990	4699942	ushort array to byte array	unsigned incursor, outcursor;\nunsigned inlen = length(inputarray);  // not literally\nfor(incursor=0,outcursor=0;incursor < inlen; incursor+=2,outcursor+=3{\n   outputarray[outcursor+0] = ((inputarray[incursor+0]) >> 4) & 0xFF;\n   outputarray[outcursor+1] = ((inputarray[incursor+0] & 0x0F)<<4 | ((inputarray[incursor+1]>>8) & 0x0F);\n   outputarray[outcursor+2] = inputarray[incursor+1] & 0xFF;\n}	0
23493549	23492601	C# pInvoke with long in both 32 & 64 Bit Linux:	using System.Runtime.InteropServices;\n\n[StructLayoutAttribute(LayoutKind.Sequential)]\nstruct sysinfo_t\n{\n    System.UIntPtr  _uptime;             /* Seconds since boot */\n    public ulong uptime {\n        get { return (ulong) _uptime; }\n        set { _uptime = new UIntPtr (value); }\n    }\n\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst=3)]\n    System.UIntPtr [] _loads;  /* 1, 5, and 15 minute load averages */\n    public ulong[] loads {\n        get { return new ulong [] { (ulong) _loads [0], (ulong) _loads [1], (ulong) _loads [1]) };\n        set { _loads = new UIntPtr [] { new UIntPtr (value [0]), new UIntPtr (value [1]), new UIntPtr (value [2]) }; }\n    }\n\n    // etc\n}	0
18564569	18501675	How to access files in a webapp when querying IIS using System.DirectoryServices	ManagementObjectSearcher searcher =\n            new ManagementObjectSearcher("root\\MicrosoftIISv2", "SELECT * FROM IIsWebVirtualDirSetting");\n\n        foreach (ManagementObject queryObj in searcher.Get())\n        {\n           result.Add(queryObj["Path"]);\n        }	0
1733322	1732890	Smooth movement of icon displayed on a Panel	public class TestPanel : Panel\n{\n  public TestPanel()\n  {\n     DoubleBuffered = true;\n  }\n}	0
22860416	22851860	AutoMapper: two-way, deep mapping, between domain models and viewmodels	BiMapper.CreateProfile<Client, ClientNotificationsViewModel>()\n    .Map(x => x.NotificationSettings.ReceiveActivityEmail, x => x.ReceiveActivityEmail)\n    .Map(x => x.NotificationSettings.ReceiveActivitySms, x => x.ReceiveActivitySms)\n    .Map(x => x.ContactDetails.Email, x => x.Email)\n    .Map(x => x.ContactDetails.MobileNumber, x => x.MobileNumber);\n\nBiMapper.PerformMap(client, viewModel);\nBiMapper.PerformMap(viewModel, client);	0
10863867	8932469	How can I non-recursively browse the contents of a directory with the AWS S3 API?	var request = new ListObjectsRequest()\n.WithBucketName("bucketname")\n.WithPrefix(@"folder1/")\n.WithDelimiter(@"/");\n\nusing (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))\nusing (var response = client.ListObjects(request))\n{\n    foreach (var subFolder in response.CommonPrefixes)\n    {\n        /* list the sub-folders */\n    }\n    foreach (var file in response.S3Objects) {\n         /* list the files */\n    }\n}	0
26762925	26762586	How to edit URL with Fiddler(script)?	oSession.url = oSession.url.Replace("1.2","1.0");	0
7412867	7049989	How to determine whether my application is active (has focus)	[System.Runtime.InteropServices.DllImport("user32.dll")]\nstatic extern IntPtr GetForegroundWindow();\n\nprivate static bool IsActive(Window wnd)\n{\n    // workaround for minimization bug\n    // Managed .IsActive may return wrong value\n    if (wnd == null) return false;\n    return GetForegroundWindow() == new WindowInteropHelper(wnd).Handle;\n}\n\npublic static bool IsApplicationActive()\n{\n    foreach (var wnd in Application.Current.Windows.OfType<Window>())\n        if (IsActive(wnd)) return true;\n    return false;\n}	0
30793038	30792767	Function to XOR two 128 bits. How do I generate 128 bit values?	using System.Linq \n\nbyte[] key = BitConverter.GetBytes(25).Concat(BitConverter.GetBytes(284)) ;	0
33516896	33516864	How to Deserialise Array into List without using Foreach?	JsonConvert.DeserializeObject<List<MyObject>>(response);	0
23866002	23865345	How to find Mouse movement direction?	protected override void OnMouseMove(MouseEventArgs e)\n{\n    if (e.LeftButton == MouseButtonState.Pressed)\n    {\n        double deltaDirection = currentPositionX - e.GetPosition(this).X;\n        direction = deltaDirection > 0 ? 1 : -1;\n        currentPositionX = e.GetPosition(this).X;\n    }\n    else\n    {\n        currentPositionX = e.GetPosition(this).X;\n    }\n}	0
22536891	22536818	How to write to a JSON file using C#?	UserData user = Call Method Here\n\nstring json = JsonConvert.SerializeObject(user, Formatting.Indented);\nFile.WriteAllText(@"c:\user.json", json);	0
10558522	10558418	How do I access the host application's web.config file from a class library/assembly?	//open the webconfig\n Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(@"~/web.config");\n\n // Get mail settings\n mailSettings = webConfig.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;	0
14918060	14917702	Removing data after query	var myList = mt.ToList();\nforeach (var mtype in myList)\n{\n    foreach (var mess in mtype.LibMessages.ToList())\n    {\n        if (mess.VisibleEndDate < DateTime.Now)\n        {\n            // remove expired message. \n            mtype.LibMessages.Remove(mess);\n        }\n    }\n}	0
20017353	20016630	Create a table in a generated PDF	PdfPTable table = new PdfPTable(5);\nfloat[] widths = new float[] { 1f, 2f, 2f, 2f, 1f };\ntable.SetWidths(widths);\nPdfPCell cell;\ncell = new PdfPCell(new Phrase("S/N"));\ncell.Rowspan = 2;\ntable.AddCell(cell);\ncell = new PdfPCell(new Phrase("Name"));\ncell.Colspan = 3;\ntable.AddCell(cell);\ncell = new PdfPCell(new Phrase("Age"));\ncell.Rowspan = 2;\ntable.AddCell(cell);\ntable.AddCell("SURNAME");\ntable.AddCell("FIRST NAME");\ntable.AddCell("MIDDLE NAME");\ntable.AddCell("1");\ntable.AddCell("James");\ntable.AddCell("Fish");\ntable.AddCell("Stone");\ntable.AddCell("17");	0
4440290	4440193	How to provide a plugin with data capabilities?	public MyCustomPlugin(PluginId id, SettingsRepostiory settingsRepository)\n{\n    _id = id;\n    _settingsRepository = settings;\n}\n\npublic void SomePluginMethod()\n{\n    PluginSettings setting = settingsRepository.Settings.WithId(_id);\n    //...\n}	0
20551611	20551573	string[] args length is zero in command line argument	program.exe args0 args1 args2	0
16460678	16460532	How to get ProcessStartInfo with arguments from a java process By using C#?	Dictionary<IntPtr, string> processArguments = new Dictionary<IntPtr,string>();\n\n        ProcessStartInfo startInfo = new ProcessStartInfo();\n        startInfo.FileName = javahome + "\\bin\\java.exe";\n        startInfo.Arguments = "-jar Example.jar port=88888";\n        startInfo.WorkingDirectory = "\\testFolder";\n        startInfo.UseShellExecute = false;\n        startInfo.CreateNoWindow = true;\n        Process proc = new Process();\n        proc.StartInfo = startInfo;\n        proc.Start();\n\n        processArguments.Add(proc.Handle, javahome + "\\bin\\java.exe");\n\n....\n\n        Process[] processes = Process.GetProcessesByName("java");\n        foreach (Process proc in processes)\n        {\n            var arguments = processArguments.Where(x => x.Key.Equals(proc.Handle)).FirstOrDefault().Value;\n        }	0
2203872	2203675	Count lines in files in folders recursively	string path = @"C:\TonsOfTextFiles";\nint totalLines = (from file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)\n                    let fileText = File.ReadAllLines(file)\n                    select fileText.Length).Sum();	0
28172903	28172703	Assign the value in a cell of a DataGridView to a variable	private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n    {\n        string value = "";\n        value = dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString();\n    }	0
913597	913374	How to subscribe to other class' events in c#?	public class EventThrower\n        {\n            public delegate void EventHandler(object sender, EventArgs args) ;\n            public event EventHandler ThrowEvent = delegate{};\n\n            public void SomethingHappened()\n            {\n                ThrowEvent(this, new EventArgs());\n            }\n        }\n\n        public class EventSubscriber\n        {\n            private EventThrower _Thrower;\n\n            public EventSubscriber()\n            {\n                _Thrower = new EventThrower();\n                //using lambda expression..could use method like other answers on here\n                _Thrower.ThrowEvent += (sender, args) => { DoSomething(); };\n            }\n\n            private void DoSomething()\n            {\n               //Handle event.....\n            }\n        }	0
12650078	12632427	I'm trying to Preserve/Protect certain fields in a View Model	if (ModelState.IsValid)\n{\n    var existingUser = db.Users.Single(p => /* query to find your user */);\n\n    existingUser.From = user.From;\n    existingUser.CC = user.CC;\n    // etc.\n\n    db.SaveChanges();\n\n    return RedirectToAction("Index");\n}	0
21129774	21129733	Convert linq query to lambda expression	_dbNavigation.Table1\n             .Join(_dbNavigation.Table2, t1 => t1.PropName, t2 => t2.PropName, (t1, t2) => new { t1, t2 })\n             .Where(x => x.t1.IsDeleted == false && x.t2.UserName == "REX")\n             .Select(x => x.t2);	0
11241154	11240933	Extract table from DOCX	Table table = doc.MainDocumentPart.Document.Body.Elements<Table>().First();	0
1532823	1532814	How to loop through a collection that supports IEnumerable?	foreach (var item in collection)\n{\n    // do your stuff   \n}	0
32645796	32645126	Control lost focus	private void picSnap_MouseMove(object sender, MouseEventArgs e)\n{\n            this.Activate();\n            this.KeyPreview=true;\n}	0
33095723	33095582	How to skip showing the first item in the ItemsSource that bound with a ItemsControl?	return new ObservableCollection<ConditionElement>(ConditionElementList.Skip(1));	0
20860919	20860701	how to add label text from data table	string label_te = null;\n   int i = 0;\n   foreach (DataRow dr in obj_dt.Rows)\n   {\n       i++;\n       label_te = dr.Field<string>("val");\n       Label l = this.FindControl("Label"+i.ToString()) as Label;\n       if(l!=null)\n       {\n         l.Text = label_te.ToString();\n       }\n   }	0
6060445	6060416	NewLine in object summary	/// <summary> \n/// Your Main comment \n/// <para>This is line 1</para> \n/// <para>This is line 2</para> \n/// </summary> \npublic bool TestLine { get; set; }	0
30318883	30318676	I am trying to retrieve the index of a value in array 1 and use that index to find the value to same index in array 2	string[] temp = new string[]{ "1", "2", "3", "4", "5" };\nint a = Array.IndexOf(temp, "3");	0
17987803	17987548	How to add mouse selected text from a textbox to list	using System;\nusing System.Collections.Generic;\nusing System.Windows.Forms;\n\nnamespace TextBoxLines\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        public List<string> PtagName = new List<string>();\n\n        private void textBox1_MouseUp(object sender, MouseEventArgs e)\n        {\n            if (e.Button == MouseButtons.Left)\n            {\n                if (textBox1.SelectedText.Length > 0)\n                {\n                    string[] lines = textBox1.SelectedText.Split('\n');\n                    foreach (var line in lines)\n                    {\n                        PtagName.Add(line);\n                    }\n                }\n                foreach (var line in PtagName)\n                    MessageBox.Show(line);\n\n                PtagName.Clear();\n            }\n        }\n    }\n}	0
4649624	4642851	Using Moq to Validate Separate Invocations with Distinct Arguments	mock.Verify(m => m.SomeOtherMethod(It.Is("baz")), Times.Exactly(1));\nmock.Verify(m => m.SomeOtherMethod(It.Is("bag")), Times.Exactly(1));	0
33901504	33901115	log all SQLDataReader fields	while (reader.Read())\n        {\n            log.Info("New record found");                \n            Object[] values = new Object[reader.FieldCount];\n            int fieldCount = reader.GetValues(values);\n            log.Debug(values);\n         }	0
22699915	22699783	Razor Html in JSON String	"<td><div style=\"background-color:#00F;width:@width%;height:10px;border:1px solid #000;\"></td>"	0
16295769	16295568	How to filter elements from the list by checking elements' powers?	pointsInCircleRange =PointsInSpace.Where(d => Math.Pow(d.x, 2) + Math.Pow(d.y, 2) <= Math.Pow(r,2));	0
32031048	32030909	Is it possible to disable the "close" button while still being able to close from elsewhere?	bool ExitApplication = false;\n\nprivate void Form1_FormClosing(Object sender, FormClosingEventArgs e) \n{\n    switch(ExitApplication)\n    {\n      case false:\n      this.Hide();\n      e.Cancel = true;\n      break;\n\n      case true:\n      break;\n    }\n}	0
9542222	9541527	How to add a new item to a datasource with a combobox?	private void comboBox1_Validating(object sender, CancelEventArgs e)\n    {\n        if (comboBox1.SelectedItem == null)\n        {\n            IList list = comboBox1.DataSource as IList;\n            if (list != null)\n            {\n                TargetGroup group = new TargetGroup(comboBox1.Text);\n                list.Add(group);\n                comboBox1.DataSource = null;\n                comboBox1.DataSource = list;\n                comboBox1.DisplayMember = "Caption";\n                comboBox1.SelectedItem = group;\n            }\n        }\n    }	0
10676392	10671531	Perform string search with Linq to Entities	GetContacts().Where(c => searchTerms.Any(term => c.FullName.Contains(term)))	0
8922218	8912250	Windows Azure - Access Denied in approot path	fileStream = new FileStream(rulePath, FileMode.Open, FileAccess.Read);	0
22435151	22434441	Linq many to many select query with Distinct	var hobbies = (from h in hobbies\n                where h.people.Any(p => p.location.locationName == "Dallas")\n                select h);	0
25534260	23696651	How to use the same virtual memory block each time program is run in C#	[DllImport("kernel32", SetLastError = true)]\nstatic extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType lAllocationType, MemoryProtection flProtect);\n\n// use same virtual address in all processes\nconst uint reserveAddress = 0x00CF0000;\n\n// reserve 160MB at that address immediately at the start of the program\nVirtualAlloc(new IntPtr(reserveAddress), new UIntPtr(160*1024*1024), AllocationType.RESERVE, MemoryProtection.EXECUTE_READWRITE);\n\n// now just pass that same address to my external process when needed\nint result = StartExternalProcess(reserveAddress);	0
29390248	29387915	Find the bars indexes in the largest Rectangular Area in a Histogram	int getMaxArea(int hist[], int n)\n{\n// ..\nint rindex=0;\nint lindex=0; \n while (i < n)\n{\n//..\n            if (max_area < area_with_top)\n            {max_area = area_with_top;\n            lindex=i-(max_area/hist[tp])+1;\n            rindex=i;\n            }\n//..\n}\nwhile (s.empty() == false)\n{\n//..\n            if (max_area < area_with_top)\n            {max_area = area_with_top;\n            lindex=i-(max_area/hist[tp])+1;\n            rindex=i;\n            }\n//..\n}\n//..\ncout << "indexs: " << lindex << " " << rindex << "\n"; // u may pass them to main method, if needed\nreturn max_area;\n}	0
17695080	17694893	how do i convert Dictionary string string to array of key value pair of string and string using linq and c#	ArrayOfKeyValueOfstringstringKeyValueOfstringstring[] array =\n                  valuePairs.Select(pair =>  \n                     new ArrayOfKeyValueOfstringstringKeyValueOfstringstring(){\n                         Key= pair.Key, Value= pair.Value}).ToArray();	0
31194987	31194902	How do I open window inside another window after	public MainWindow()\n{\n    InitializeComponent();\n    this.ContentRendered+= Window_ContentRendered;\n}\n\nprivate void Window_ContentRendered(object sender, RoutedEventArgs e)\n{\n    OpenProjectsView();\n}	0
34018647	34018370	How to randomize XML Elements	public class Xml\n{\n    public static string XmlString = @"<Configuration>\n<Elements>\n    <SubElement1></SubElement1>\n    <SubElement2></SubElement2>\n    <SubElement3></SubElement3>\n</Elements>\n</Configuration>";\n\n    public static XDocument Randomize()\n    {\n        //rather keep a static random if u can\n        var rand = new Random();\n\n        var xdoc = XDocument.Parse(XmlString);\n        var ele = xdoc.Root.Element("Elements");\n\n        var shuffle = new XElement("Elements", ele.Elements().OrderBy(x => rand.Next()));\n\n        ele.ReplaceWith(shuffle);\n        return xdoc;\n    }\n}	0
11344923	11344666	Collect attributes from a XML file by XMLReader	var chapters = new List<string>();\n        using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))\n        {\n            reader.ReadToFollowing("CHAPTER");\n            reader.MoveToFirstAttribute();\n            string chapterNumber = reader.Value;\n            chapters.Add("Chapter " + chapterNumber);\n        }	0
1715828	1715798	Subtract date returns negative	using System;\n\nclass Program\n{\n    static void Main()\n    {\n        DateTime start = new DateTime(2009, 11, 11, 8, 0, 0);\n        DateTime end = new DateTime(2009, 11, 11, 16, 0, 0);\n\n        Console.WriteLine(end.Subtract(start).Hours);\n    }\n}	0
11723924	11722519	How can I use non-standard namespaces with SyndicationFeed?	var xmlDoc = new XmlDocument();\n        xmlDoc.Load(@"http://www.co.frederick.va.us/dev/scrapewarning.xml");\n        var nsm = new XmlNamespaceManager(xmlDoc.NameTable);\n        nsm.AddNamespace("s", "http://www.w3.org/2005/Atom");\n        nsm.AddNamespace("cap", "urn:oasis:names:tc:emergency:cap:1.1");\n        var nodes = xmlDoc.SelectNodes("//s:entry[cap:event]", nsm);	0
24679664	24679325	Find all GameObjects in the scene containing scripts, which are derived from an abstract class	UnityEngine.Object.FindObjectsOfType< IAbstractInterface >();	0
2223522	2223503	How can I parse a string that lacks delimiters to a DateTime using c#?	DateTime.ParseExact(\n      "20100205 162206",\n      "yyyyMMdd HHmmss",\n      CultureInfo.InvariantCulture);	0
1325512	1325444	Parsing slightly off-kilter XML in C# with XmlSeralizer	[XmlElement]\npublic class Image { ... }\n\n[XmlRoot(ElementName="Series")]\npublic class Series\n{\n        public Series() { }\n\n        [XmlElement]\n        public string Metadata1;\n\n        [XmlElement]\n        public string Metadata2;\n\n        [XmlElement(ElementName="Image")]\n        public Image[] Images;\n}	0
18608588	18598391	Turn Off ServiceStack Logging	LogManager.LogFactory = new NullLogFactory();	0
21646413	21626589	getting past event for Google Analytics	Google Analytics generally updates your reports every 24 hours, so it can take at least\nthat long for data to appear in your account after you first install the tracking code.	0
3971213	3971208	What is the result if all parameters in a null coalescing operation are null?	if (null == null)\n    myObject = yourObject;\nelse\n    myObject = null;	0
9368439	7368542	Is it possible to fail triggering the AppDomain's unhandled exception handler from a Task continuation?	Application.OnThreadException()	0
1404043	1403986	How to handle buffering data read from the network?	const int ChunkSize = 4096;\nint bytesRead;\nbyte[] buffer = new byte[ChunkSize];\nwhile ((bytesRead = socket.Receive(buffer, 0, ChunkSize, SocketFlags.None)) > 0)\n{\n    byte[] actualBytesRead = new byte[bytesRead];\n    Buffer.BlockCopy(buffer, 0, actualBytesRead, 0, bytesRead);\n    // Do something with actualBytesRead, \n    // maybe add it to a list or write it to a stream somewhere\n}	0
19624663	19624622	membership provider - Syntax error in update statement	OleDbCommand updateCmd = new OleDbCommand("UPDATE [" + tableName + "]" +\n            " SET [Password] = ?, LastPasswordChangedDate = ?" +\n            " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn);	0
23916200	23892703	How to get parameter names in view by route values?	var assembly = AppDomain.CurrentDomain.GetAssembliesFromApplicationBaseDirectory(\n            x => x.GetName().Name == "XXXX").Single();\n\n    var controllerTypes = assembly.GetTypes().Where(x => x.Name == Model.Controller + "Controller");\n\n    var controllerType = controllerTypes.Where(x => x.Namespace.Contains(Model.Area)).Single();\n\n    var action = controllerType.GetMethod(Model.Action);\n\n    var parameters = action.GetParameters();	0
23212290	23133154	Contracts With Multiple Arguments	ISet<Tuple<A,B> set;\nContract.Invariant(Contract.ForAll(set, s => s != null && Contract.ForAll(set, t => t != null && ((s.Item1 != t.Item1)||(s.Item2 == t.Item2)))));	0
27466145	27466002	Properly displaying an array using C#	using (SqlDataAdapter adapter = new SqlDataAdapter(comm))\n{\n    adapter.Fill(table);\n}\n\nforeach(var row in table.Rows)\n{\n    Console.WriteLine(String.Join(",", row.ItemArray));\n}	0
13990413	13990390	Mark the last item in ListBox	listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);	0
26886814	26886688	Detect calling platform	if(HttpRuntime.AppDomainAppId != null)\n{\n  //if it's not null it is a web app\n}\nelse\n{\n  //if it's null it is a desktop app\n}	0
23906867	23905731	How to show all the rows in datagridview?	DataTable dt = db.getProductIdFromCategoriesId(categories_id);\n\nDataTable dt5 = new Datatable();\n\n foreach (DataRow row in dt.Rows)\n {\n     string products_id = row["products_id"].ToString();\n     dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));\n }\n\nshow_products.ItemsSource = dt5.DefaultView;	0
31339927	31339708	Object de-serializing from base64 in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        var account = new ExternalAccount() { Name = "Someone" };\n        string json = JsonConvert.SerializeObject(account);\n        string base64EncodedExternalAccount = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));\n        byte[] byteArray = Convert.FromBase64String(base64EncodedExternalAccount);\n\n        string jsonBack = Encoding.UTF8.GetString(byteArray);\n        var accountBack = JsonConvert.DeserializeObject<ExternalAccount>(jsonBack);\n        Console.WriteLine(accountBack.Name);\n        Console.ReadLine();\n    }\n}\n\n[Serializable]\npublic class ExternalAccount\n{\n    public string Name { get; set; }\n}	0
9605620	9598444	Facebook: wall post 'picture' element is ignored	var pictureLink = "http://mydomain.com" + Url.Action("ImageFile", "Files", new {sizes = "400x650", fileName = file.FileName});\n pictureLink = Server.UrlDecode(pictureLink);\n args["picture"] = pictureLink;	0
13107850	13107808	Create new SQL Server 2008 R2 login from C# program	CREATE LOGIN <login_name> WITH PASSWORD = '<password>' MUST_CHANGE	0
16933471	16933220	How we increase the width of the column by using bootstrap	Name: \n<asp:TextBox id="Text1" \n  Text="Enter a value" \n  runat="server"/>\n\n<asp:RequiredFieldValidator id="RequiredFieldValidator1"  \n  ControlToValidate="Text1" CssClass="alert-error"\n  Text="Required Field!" \n  runat="server"/>	0
32342234	32342159	subtract datetime.now from a datetime.now and truncat the millisecond	var result = string.Format("{0:D2}:{1:D2}:{2:D2}", duration.Hours, duration.Minutes, duration.Seconds);	0
3907682	3907454	How can i join Master-Detail-Detail Tables with Linq in Entity Framework	var query = from recordA in context.TableA\n            join recordB in context.TableB\n            on recordA.Id equals recordB.aId\n            join recordC in context.TableC\n            on recordB.cId equals recordC.Id\n            select new \n            {\n               // whatever columns are appropriate\n            };	0
30277950	30270776	Combining Coroutines and Reflection in Unity	RobotBehaviour robotBehaviour = getRobotBehaviour()\nType type = robotBehaviour.GetType();\nMethodInfo methodInfo = type.GetMethod((string)sentences[lineNo]);\nrobotBehaviour.StartCoroutine(methodInfo.Name, 0);  // <-- Solved!	0
15605028	15582450	Too many arguments in BeginXXX for FromAsync?	result = Task<string>.Factory.FromAsync(\n                instance.BeginGetMyNumber("foo", "bar", "bat", 1, null, null),\n                instance.EndGetMyNumber);	0
5774468	5774408	Custom ShowDialog with more information than DialogResult	CustomDialog d = new CustomDialog();\n\n  if(d.ShowDialog() == DialogResult.OK)\n  { \n      CustomDialogResult foo = d.CustomDialogResult;\n      DoStuff(foo.CustomString); \n  }	0
28579325	28578821	Intersystems cach? - read variable in global using .net - c#	using System;\nusing InterSystems.Globals;\n\nclass FetchNodes {\n  public static void Main(String[] args) {\n    Connection myConn = ConnectionContext.GetConnection();\n    try {\n      myConn.Connect("User", "_SYSTEM", "SYS");\n      NodeReference nodeRef = myConn.CreateNodeReference("myGlobal");\n      // Read both existing nodes\n      Console.WriteLine("Value of ^myGlobal is " + nodeRef.GetString());\n      Console.WriteLine("Value of ^myGlobal(\"sub1\") is " + nodeRef.GetString("sub1"));\n      nodeRef.Kill();   // delete entire array\n      nodeRef.Close();\n      myConn.Close();\n    }\n    catch (GlobalsException e) { Console.WriteLine(e.Message); }\n  } // end Main()\n} // end class FetchNodes	0
5891067	5891035	Converting a boolean array into a string using c#	string input = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n\nstring result = new String(input.ToCharArray()\n                      .Take(status.Length)\n                      .Where((c, i) => status[i]).ToArray());	0
4774282	4774151	Improve efficiency of multiple string comparison (regex?)	var r = new Regex("something|whatever|blah", RegexOptions.IgnoreCase);\nreturn ! r.ismatch(productName);	0
17604113	17603791	How can I get a list of Groups and User names for a given folder in C#	// Variables:\nstring folderPath = "";\nDirectoryInfo dirInfo = null;\nDirectorySecurity dirSec = null;\nint i - 0;\n\ntry\n{\n     // Read our Directory Path.\n     do\n     {\n          Console.Write("Enter directory... ");\n          folderPath = Console.ReadLine();\n     }\n     while (!Directory.Exists(folderPath));\n\n     // Obtain our Access Control List (ACL)\n     dirInfo = new DirectoryInfo(folderPath);\n     dirSec = dirInfo.GetAccessControl();\n\n     // Show the results.\n     foreach (FileSystemAccessRule rule in dirSec.GetAccessRules(true, true, typeof(NTAccount)))\n     {\n          Console.WriteLIne("[{0}] - Rule {1} {2} access to {3}",\n          i++,\n          rule.AccessControlType == AccessControlType.Allow ? "grants" : "denies",\n          rule.FileSystemRights,\n          rule.IdentityReference.ToString());\n      }\n}\ncatch (Exception ex)\n{\n     Console.Write("Exception: ");\n     Console.WriteLIne(ex.Message);\n}\n\nConsole.WriteLine(Environment.NewLine + "...");\nConsole.Read();	0
32978626	32978522	Regex.Matches error cannot convert from char to string	while ((line = file.ReadLine()) != null)\n{\n     String pattern = @"(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)";\n\n     foreach (Match m in Regex.Matches(line, pattern))\n     {                        \n        double value = Double.Parse(m.Groups[5].Value);\n     }            \n}	0
11206177	11205981	Error in converting string to datetime in C#.net	dd-MMM-yy hh:mm:ss tt	0
23824540	23813187	Windows phone app, Windows.Web.Http.HttpClient post sample	Windows.Web.Http.HttpClient oHttpClient = new Windows.Web.Http.HttpClient();\nUri uri= ... // some Url\nstring stringXml= "...";  // some xml string\nHttpRequestMessage mSent = new HttpRequestMessage(HttpMethod.Post, uri);\nmSent.Content = \n  new HttpStringContent(String.Format("xml={0}", stringXml), \n                        Windows.Storage.Streams.UnicodeEncoding.Utf8);\n\nHttpResponseMessage mReceived = await oHttpClient.SendRequestAsync(mSent,\n                                   HttpCompletionOption.ResponseContentRead);\n\n// to get the xml response:\nif (mReceived.IsSuccessStatusCode)\n{\n  string strXmlReturned await mReceived.Content.ReadAsStringAsync();\n}	0
2881718	2881585	c# Find value in a range using lambda	values.FindLast(x => amount >= x.Value);	0
6651770	6614553	Service Request/Response Contract Guideline For Multiple Results	Customer[] getCustomers(Customer customerFilter) {\n    Query q; // = new query on customer table\n    if(customerFilter.isSetCustomerID()) {\n        // add where clause to the query: \n        //     Customer.CUSTOMER_ID = customerFilter.getCustomerID()\n    }\n    // for each field\n}\n\nCustomer[] getCustomers(Customer[] customerFilters) {\n    Query q; // = new query on customer table\n    // add where clause to the query for each field: \n        //    Customer.CUSTOMER_ID IN \n        //       [customerFilter : customerFilters].getCustomerID()\n\n}	0
15275193	15275058	Splitting parts of a List<T> into 2 List<T>'s and joining those 2	var allItemsList = new List<allItems>() { ... fill in items ... };\nvar asItems = \n    from item in allItemsList\n    group item by new { week = item.weekNumber, month = item.monthNumber } into byWeekMonth\n    select new items()\n    {\n        weekNumber = byWeekMonth.Key.week,\n        monthNumber = byWeekMonth.Key.month,\n        days = byWeekMonth.Select(si => \n            new subItems()\n            {\n                punchedInLate = si.punchedInLate,\n                punchedOutLate = si.punchedOutLate,\n                // etc, other fields\n            }).ToList()\n    };	0
4344830	4344730	Select Max value from sublist with LINQ	var max = mps.SelectMany(x => x.Vals)\n    .Aggregate((a, x) => (x.Date > a.Date) ||\n                         ((x.Date == a.Date) && (x.Val > a.Val)) ? x : a);	0
4461553	4442018	Export a parameterized SSRS report from C# code	string outputPath = "C:\Temp\PdfReport.pdf";\n\nReportViewer reportViewer = new ReportViewer();\nreportViewer.ServerReport serverReport = new ServerReport();\nreportViewer.ServerReport.ReportPath = @"path/to/report";\nreportViewer.ServerReport.ReportServerUrl = new Uri(@"http://...");\nreportViewer.ProcessingMode = ProcessingMode.Local;\n\nreportViewer.ServerReport.ReportServerCredentials.NetworkCredentials = new \n    System.Net.NetworkCredential(username, password, domain)\n\nList<ReportParameter> parameters = new List<ReportParameter>();\nparameters.Add(new ReportParameter("parameterName", "value"));\n\nstring mimeType;\nstring encoding;\nstring extension;\nstring[] streams;\nWarning[] warnings;\nbyte[] pdfBytes= serverReport.Render("PDF", string.Empty, out mimeType, \n    out encoding, out extension, out streams, out warnings);\n\n// save the file\nusing (FileStream fs = new FileStream(outputPath, FileMode.Create))\n{\n    fs.Write(pdfBytes, 0, pdfBytes.Length);\n    fs.Close();\n}	0
27008282	27008179	WPF UI Freezing	Control.Invoke()	0
20572702	20572588	XML grab attribute from specific element node	var myVariable = "Direct Access Site";\nXDocument doc = XDocument.Load(your file);\nvar result = doc.Descendants("sitesEQ")\n               .Where(i => i.Element("nameEQ").Value == myVariable )\n               .Select(i => i.Attribute("sitePathEQ").Value);\n\nforeach (string item in result)\n{\n    Console.WriteLine(item);\n}	0
28001786	28001488	How create 100% copy local object?	[TestMethod]\npublic void FunctionExtention_CombinePredicates_Should_Avoid_Closure()\n{\n        var value = 0;\n        var copy = value;\n        var predicates = new Predicate<int>[]\n        {\n            x => x > copy\n        };\n\n        var result = FunctionExtentions.CombinePredicates(predicates);\n        value = 1000;\n        Assert.IsTrue(result(2));\n}	0
30753758	30753700	Windows Store Apps, download multiple files with threads	var t1 = DownloadFileService("file1", "1");\nvar t2 = DownloadFileService("file2", "2");\nvar t3 = DownloadFileService("file3", "3");\n\nTasks.WaitAll(t1, t2, t3);	0
8031935	8031452	Reading children tags in xaml (similar to ListBox's)	[ContentProperty("Items", true)]	0
31495684	31495394	How to keep a reference to another object in current object	public class WrapperClass\n{\n   public OtherClass Input;\n}\n\n\npublic class CLass1\n    {\n        WrapperClass _wrapper;\n        public Bind(ref WrapperClass wrapper)\n        {\n                wrapper = new WrapperClass();\n                wrapper.Input = new OtherClass(); // instantiating the object\n                _wrapper = wrapper; // keeping a reference of the created object for later usage!\n        }\n        public void Unbind()\n        {\n            _wrapper.Input= null;\n        }\n    }	0
2551975	2551740	Is there a way to synchronize Silverlight Child Window (make it like MessageBox)?	ChildWindow1 wnd1 = new ChildWindow1;\n wnd1.Closed += (s, args) =>\n {\n    ChildWindow2 wnd2 = new ChildWindow2;\n    wnd2.Show();\n }\n wnd1.Show();\n\n // Note code here will run as soon as wnd1 has displayed, Show does not block.	0
21219581	21218915	How do I get the Image location?	// Calculate the size and position of the zoomed rectangle.\ndouble zoomFactorX = picturBox1.Width / mRect.Width;\ndouble zoomFactorY = picturBox1.Height / mRect.Height;\nSize newSize;\nPoint newLocation;\nif (zoomFactorX < zoomFactorY) { // Fit image portion horizontally.\n    newSize = new Size(picturBox1.Width, (int)Math.Round(zoomFactorX * mRect.Height));\n\n    // We have a top and a bottom padding.\n    newLocation = new Point(0, (picturBox1.Height - newSize.Height) / 2);\n} else {  // Fit image portion vertically.\n    newSize = new Size((int)Math.Round(zoomFactorY * mRect.Width), picturBox1.Height);\n\n    // We have a left and a right padding.\n    newLocation = new Point((picturBox1.Width - newSize.Width) / 2, 0);\n}	0
23231359	23231253	Is there such a thing as a chained NULL check?	var obj = msg?.Content?.AccountMarketMessage?.Account?.sObject;\nif (obj == null) return;	0
29928467	29914513	Exception from HRESULT: 0x800A03EC Error triying to PasteSpecial a datagridview-excel	//Get DataGridView into a DataTable:\nvar bindingSource = (BindingSource)dataGridView.DataSource;\nvar dataView = (DataView)bindingSource.List;\nvar dataTable = dataView.Table;\n\n//Create a Spreadsheet\nusing (ExcelPackage excelPackage = new ExcelPackage())\n{\n    ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("DataExport");\n    ws.Cells[1,1].LoadFromDataTable(dataTable, PrintHeaders:true);\n\n\n    //Write to an outputstream:\n    excelPackage.SaveAs(outputStream);\n    //or filesystem:\n    excelPackage.SaveAs(new FileInfo(@"C:\Temp\Export.xlsx"));\n}	0
27613886	27613437	How to add values for searching dynamically in Dapper.NET	string query = "SELECT PurchaseDate, InvoiceNo, Supplier, Total FROM PurchaseOrder     WHERE 1 = 1";\n\n if (!string.IsNullOrEmpty(purchaseOrder.InvoiceNo))\n {\n     sql += " AND InvoiceNo = @InvoiceNo";\n }\n if (purchaseOrder.PurchaseDate != DateTime.MinValue)\n {\n    sql += " AND PurchaseDate = @PurchaseDate";\n }\n\n\n  return this._db.Query<PurchaseOrder>(sql, new {InvoiceNo = new DbString { Value =     YourInvoiceNoVariable, IsFixedLength = true, Length = 10, IsAnsi = true });	0
18703573	18703531	XAML Variables displayed in TextBlock	TextBox.Text = debt;	0
17230087	17230024	How to save C# xml to an existing file	XmlDocument doc = new XmlDocument();\n    doc.Load(@"D:\Highscores.xml");\n    var name = doc.SelectSingleNode("/highscore/score/name");\n    if (name != null)\n        name.InnerXml = "ojlovecd";\n    var points = doc.SelectSingleNode("/highscore/score/points");\n    if (points != null)\n        points.InnerXml = "12345";\n    doc.Save(@"D:\Highscores.xml");	0
8276934	8276892	select items in a checkbox list based on their text	string[] array = { "Dress", "Pen", "Table"};\n\n    for (int i = 0; i < chkbx.Items.Count; i++)\n    {\n        if (array.Contains(chkbx.Items[i].Text))\n        {\n            chkbx.Items[i].Selected = true;\n        }\n    }	0
14760694	14663926	Excel Interop - Draw All Borders in a Range	private void AllBorders(Excel.Borders _borders)\n    {\n        _borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;\n        _borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;\n        _borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;\n        _borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;\n        _borders.Color = Color.Black;\n    }	0
5177794	5177647	Adding a png to clipboard	Image image = Image.FromFile(@"D:\Documents\Projects\....\myimage.png");\n        DataFormat format = DataFormats.GetDataFormat(typeof (Image).FullName);\n\n        IDataObject dataObj = new DataObject();\n        dataObj.SetData(format.Name, image);\n\n        Clipboard.SetDataObject(dataObj);\n\n        IDataObject clipboardObj = Clipboard.GetDataObject();\n        Image clipboardImage = (Image)clipboardObj.GetData(format.Name);	0
14077266	14055794	WPF TreeView restores its focus after double click	(...)\n\n//Editor.Show();\nAction showAction = () => Editor.Show();\nthis.Dispatcher.BeginInvoke(showAction);	0
8164475	8164430	Instantiate new object based on type parameter	throw (T)Activator.CreateInstance(typeof(T),message);	0
23743871	23743771	How to convert one type of list with objects to another?	List<TargetType> targetList = new List<TargetList>();\n\nforeach (var grouping in originalList.GroupBy(o => o.Module))\n{\n    TargetType target = new TargetType { Module = grouping.Key };\n    targetList.Add(target);\n    target.Screen = grouping.Select(o => new Screen\n       {\n          ScreenName = o.Screen,\n          Permission = o.Permission\n       }).ToList();\n}	0
28098561	28056986	Entity framework entities to json	internal class Entity\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n        public IEnumerable<Order> Orders { get; set; }\n\n        internal class Order\n        {\n            public string Id { get; set; }\n            public DateTime Date { get; set; }\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var customers = new List<Entity>\n        {\n            new Entity\n            {\n                Id = "test1",\n                Name = "test2",\n                Orders = new[] {new Entity.Order\n                                {\n                                    Id = "testprop", \n                                    Date = DateTime.UtcNow\n                                }}\n            }\n        };\n        var json = JObject.FromObject(new {Customers = customers});\n        Console.WriteLine(json);\n    }	0
16807142	16806983	How to get Session's value in a class object?	Services oldObj = (Services)Session["ServiceObj"];	0
9268855	9268763	c# readonly DataGridView with one enabled cell	private void dataGridView1_DoubleClick(object sender, EventArgs e)\n {\n    dataGridView1.Cells[3].ReadOnly = false;\n    this.dataGridView1.CurrentCell = dataGridView1.Cells[3];\n    dataGridView1.BeginEdit(true);\n}	0
3889782	3694883	How to prevent a ListView from expanding the window dimension?	private void Window_Loaded(object sender, RoutedEventArgs e)\n    {\n        this.SizeToContent = SizeToContent.Manual;\n    }	0
3598418	3598403	How to get MAC ID of a system using C#	public string FetchMacId()\n{\n    string macAddresses = "";\n\n    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())\n    {\n        if (nic.OperationalStatus == OperationalStatus.Up)\n        {\n            macAddresses += nic.GetPhysicalAddress().ToString();\n            break;\n        }\n    }\n    return macAddresses;\n}	0
2101787	2101777	Creating an IPEndPoint from a hostname	public static IPEndPoint GetIPEndPointFromHostName(string hostName, int port, bool throwIfMoreThanOneIP)\n{\n    var addresses = System.Net.Dns.GetHostAddresses(hostName);\n    if (addresses.Length == 0)\n    {\n        throw new ArgumentException(\n            "Unable to retrieve address from specified host name.", \n            "hostName"\n        );\n    }\n    else if (throwIfMoreThanOneIP && addresses.Length > 1)\n    {\n        throw new ArgumentException(\n            "There is more that one IP address to the specified host.", \n            "hostName"\n        );\n    }\n    return new IPEndPoint(addresses[0], port); // Port gets validated here.\n}	0
212436	212257	ListView with LINQ Datasource insert template	protected void ListView1_ItemInserting(object sender, System.Web.UI.WebControls.ListViewInsertEventArgs e)\n        {\n            e.Values["BranchID"] = DropDownList1.SelectedValue;\n        }	0
31129816	31129773	How to convert List to observablecollection	ObservableCollection<string> myCollection = new ObservableCollection<string>(Result);	0
10823047	10812780	Can you create Spark view engine bindings with plain html in?	"&lt;element name=\"searchbox\"&gt;&lt;div class=\"searchbox\"&gt;&lt;input type=\"text\"/&gt;&lt;img src=\"/content/images/cross.png\" placeholder=\"@placeholder\"/&gt;&lt;/div&gt;&lt;/element&gt;"	0
11713714	11710835	How to highlight a datagridview row when a character is typed in the search textbox	try\n        {\n            productDataGridView.ClearSelection();   //or restore rows backcolor to default\n            for (int i = 0; i < (productDataGridView.Rows.Count); i++)\n            {\n                if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))\n                {\n                    productDataGridView.FirstDisplayedScrollingRowIndex = i;\n                    productDataGridView.Rows[i].Selected = true; //It is also possible to color the row backgroud\n                    return;\n                }\n            }\n        }\n        catch (Exception) \n        { \n        }	0
5669425	5669272	how to cache reflection in C#	var cache = new Dictionary<Type, IEnumerable<Attribute>>();\n\n // obj is some object\n var type = obj.GetType();\n var attributes = type.GetCustomAttributes(typeof(MyAttribute), true);\n cache.Add(type, attributes);	0
29884861	29882556	Model in Windows Phone using Sqlite	parent.Children = conn.Table<Children>().Where(c => c.ParentID == parentId).ToList();	0
32652386	32652305	Dataset add new empty row	// create new row\nvar newR = mydataset.Tables[0].NewRow();\n// set 1 value\nnewR[0] = "Firstentry";\n// add to table\nmydataset.Tables[0].Rows.Add(newR);	0
14362449	14352729	How to create a writeablebitmap image from an image file in windows8	using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))\n            {\n                WriteableBitmap image = new WriteableBitmap(1, 1);\n                image.SetSource(stream);\n                WriteableBitmapImage.Source = image;\n            }	0
32091590	32091349	How to get all element from div block which contains type=radio?	By divBlock = By.CssSelector("input[class='textboxDate hasDatepicker']");\nWebElement divElement = driver.findElement(divBlock);\n\n//xpath to get all direct child nodes use "//" to get all child nodes and child of child nodes\nString xpathExpression = "./*";\nList<WebElement> elements = driver.findElements(By.xpath(xpathExpression));\n\nfor(WebElement element : elements) {\n    if(element.getAttribute("type").equals("radio")) {\n        element.click();\n    }\n}	0
33485150	33473117	How To get the custom field value in DNN	User.Profile.GetPropertyValue("CustomFieldName");	0
15333528	15333457	Dragging files into rich textbox to read text in file	public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n            richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);\n            richTextBox1.AllowDrop = true;\n        }\n\n        void richTextBox1_DragDrop(object sender, DragEventArgs e)\n        {\n            object filename = e.Data.GetData("FileDrop");\n            if (filename != null)\n            {\n                var list = filename as string[];\n\n                if (list != null && !string.IsNullOrWhiteSpace(list[0]))\n                {\n                    richTextBox1.Clear();\n                    richTextBox1.LoadFile(list[0], RichTextBoxStreamType.PlainText);\n                }\n\n            }\n        }	0
21785569	18643524	Message header and XML	public class StringXmlDataWriter : BodyWriter\n{\n    private string data;\n\n    public StringXmlDataWriter(string data)\n        : base(false)\n    {\n        this.data = data;\n    }\n\n    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)\n    {\n        writer.WriteRaw(data);\n    }\n}\n\npublic void ProcessHeaders()\n    {\n        string headers = "<soapenv:Header xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\"> <wsa:MessageID>1337</wsa:MessageID> </soapenv:Header>";\n\n        var headerXML = XElement.Parse(headers);\n\n        foreach (var header in headerXML.Elements())\n        {\n            var message = Message.CreateMessage(OperationContext.Current.IncomingMessageVersion, header.Name.LocalName, new StringXmlDataWriter(header.ToString()));\n            OperationContext.Current.OutgoingMessageHeaders.CopyHeadersFrom(message);\n        }\n    }	0
26327868	26286353	Open a link in webBrowser control in external browser?	Process.Start("iexplore.exe",e.Url.ToString());	0
7788908	7788784	How to create multidimensional array in C#?	var ccdata = rptdata\n               .Select( i => new object[]{ i.Key, i.Value } )\n               .ToArray();	0
24750126	24749782	Inserting Images to a Grid in Code Behind	for (int rowIndex = 0; rowIndex < ScrabbleBoard.RowDefinitions.Count; rowIndex++)\n{\n    for (int columnIndex = 0; columnIndex < ScrabbleBoard.ColumnDefinitions.Count; columnIndex++)\n    {\n        var imageSource = new BitmapImage(new Uri("pack://application:,,,/YourProjectName;component/YourImagesFolderName/YourImageName.jpg"));\n        var image = new Image { Source = imageSource };\n        Grid.SetRow(image, rowIndex);\n        Grid.SetColumn(image, columnIndex);\n        ScrabbleBoard.Children.Add(image);\n    }\n}	0
26361861	26361493	Linking a resource file to an existing .NET assembly using Assembly Linker	assembly.dll	0
28884372	28884055	How get value and text of selected item in dropdownlist on server&	[HttpPost]\n public ActionResult View2(NorthOrder q,int drop, string button)\n {\n              if (button == "Add")\n       {\nstring strDDLValue= db.Products.FirstOrDefault(_=>_.ProductID == drop).ProductName;\n\n                       return View();\n   }\n}	0
29411432	29410147	lambda expression for finding differences	private static void compareFolders(Folder folder1, Folder folder2, List<Folder> newFolders) {\n        if (folder2.childs != null) {\n            if (folder1.childs != null) {\n                // check for folder 2 childs not in folder 1\n                newFolders.AddRange(folder2.childs.FindAll(f => !folder1.childs.Select(f2 => f2.title).ToList().Contains(f.title)));\n                // for similar folders go one deeper\n                folder1.childs.FindAll(f => folder2.childs.Select(f2 => f2.title).ToList().Contains(f.title)).ForEach(f1 => compareFolders3(f1, folder2.childs.Find(f2 => f2.title == f1.title), newFolders));\n            } else {\n                // folder 1 doesn't have childs so add all of folder2\n                newFolders.AddRange(folder2.childs);\n            }\n        }\n    }	0
11190904	11153712	How to mimic Guice's MapBinder using Windsor?	class FormattersInstaller : IWindsorInstaller\n{\n    public void Install(IWindsorContainer container, IConfigurationStore store)\n    {\n        container.Register(\n            Component\n                .For<IFormatter>()\n                .ImplementedBy<XmlFormatter>()\n                .Named(Format.Xml.ToString()));\n        container.Register(\n            Component\n                .For<IFormatter>()\n                .ImplementedBy<JsonFormatter>()\n                .Named(Format.Json.ToString()));\n    }\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var container = new WindsorContainer();\n        container.Install(new FormattersInstaller());\n        var xmlFormatter = container.Resolve<IFormatter>(Format.Xml.ToString());\n        var jsonFormatter = container.Resolve<IFormatter>(Format.Json.ToString());\n        // use the formatters...\n    }\n}	0
6337500	6337476	How to create a readable date and time from a string?	string date = "2011-06-13T21:15:19Z";\nDateTime dt = DateTime.Parse(date);	0
12650054	12649804	What is life scope of lambda expression?	EventHandler myEvent= (s, e) => { /*Do something; */};  \n    //Subscribe\n    button1.Click += myEvent;\n    //Unsubscribe\n    button1.Click -= myEvent;	0
24408433	24397203	Is there a maximum number of request you can put into one request message set using QBFC?	string too long	0
2587984	2587930	Ramifications of CheckForIllegalCrossThreadCalls=false	var myData = LoadData();\nthis.Invoke( new Action( () =>\n    {\n        // Just set all of your data in one shot here...\n        this.textBox1.Text = myData.FirstName;\n        this.textBox2.Text = myData.LastName;\n        this.textBox3.Text = myData.NumberOfSales.ToString();\n    }));	0
29218534	29217815	Enemies in a list: issue with colliding the enemies with the other enemies	foreach (EnemyClass enemy in enemies)\n{\n    if (enemy.position.X < myPlayer.position.X - 10 && !enemy.stopMoving)\n    {\n        enemy.position.X += enemy.amountToMove;                   \n    }\n\n    if (enemy.position.X > myPlayer.position.X - 50 && !enemy.stopMoving)\n    {\n        enemy.position.X -= enemy.amountToMove;\n    }\n    enemy.Update(graphics.GraphicsDevice);\n} \n\nfor (int i = 0; i < enemies.Count; i++)\n{\n    for (int j = i + 1; j < enemies.Count; j++)\n    {\n        if (enemies[i].collisionBox.Intersects(enemies[j].collisionBox))\n        {\n            System.Console.WriteLine("Collision Detected");\n        }\n    }\n}	0
32609305	32609164	How can we specify the return type of a SOAP webservice as JSON format?	DataTable dt11 = ds1.Tables[0];\n\n    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();\n    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();\n\n\n    Dictionary<string, object> row;\n    foreach (DataRow dr in dt11.Rows)\n    {\n        row = new Dictionary<string, object>();\n        foreach (DataColumn col in dt11.Columns)\n        {\n           row.Add(col.ColumnName, dr[col]);\n       }\n        rows.Add(row);\n    }\n    return serializer.Serialize(rows);	0
18912371	18912012	Get datatable and filling model from it	public IEnumerable<T> Fill<T>(DataTable dt)\n    where T : new()\n{\n    return dt.AsEnumerable().Select(row =>\n    {\n        var obj = new T();\n        var properties = \n            from p in obj.GetType().GetProperties()\n            join c in dt.Columns.Cast<DataColumn>() on p.Name equals c.ColumnName\n            select new {p, c};\n        foreach (var item in properties)\n            item.p.SetValue(obj, row[item.c]);\n        return obj;\n    });\n}	0
4443156	4379918	How do you test whether Silverlight can play a stream?	void yourPage_Loaded(object sender, RoutedEventArgs e)\n{\n  ME.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(ME_MediaFailed);\n}\n\nvoid ME_MediaFailed(object sender, ExceptionRoutedEventArgs e)\n{\n  add your code to handle the exception here.\n}	0
5262365	5262201	How to use LINQ to select all descendants of a composite object	var result = composite.Children.OfType<Composite>().SelectMany(child => child.GetDescendants()).Concat(composite.Children);\nreturn result.ToList();	0
12885594	12885288	How to set the default browser to my application?	reg add HKEY_CLASSES_ROOT\http\shell\open\command /ve /d "path\to\app \"%1\"" /f	0
25009367	25005642	How to use file in file system for HttpPostedFile	private static IList<Thumbnail> GetThumbnails(System.IO.File pdfFile) \n{ \n    string unique = Guid.NewGuid().ToString(); \n\n    using(System.IO.Stream stream = pdfFile.OpenRead())\n    {\n        int n = Thumbnail.GetPageCount( stream ); \n        List<Thumbnail> thumbnails = new List<Thumbnail>();\n\n        for ( int i=1; i<=n; i++ )   // Note: please confirm the loop should really start from the index 1 (instead of 0?)\n        { \n            Thumbnail thumbnail = new Thumbnail(); \n            thumbnail.SessionKey = unique; \n            thumbnail.Index = i; \n            thumbnails.Add( thumbnail ); \n        }\n\n        return thumbnails;\n    }\n}	0
6152390	6152076	Adding Images that are located on a website to a listview on c#	private void PopulateListView()\n    {\n        ImageList images = new ImageList();\n        images.Images.Add(\n            LoadImage("http://www.website.com/892374_838.jpg"));\n        images.Images.Add(\n            LoadImage("http://www.website.com/23431_838.jpg"));\n\n        listView1.SmallImageList = images;\n        listView1.Items.Add("An item", 0);\n        listView1.Items.Add("Another item item", 1);\n    }\n\n    private Image LoadImage(string url)\n    {\n        System.Net.WebRequest request =\n            System.Net.WebRequest.Create(url);\n\n        System.Net.WebResponse response = request.GetResponse();\n        System.IO.Stream responseStream =\n            response.GetResponseStream();\n\n        Bitmap bmp = new Bitmap(responseStream);\n\n        responseStream.Dispose();\n\n        return bmp;\n    }	0
7657657	7643560	How to call a method on image button click dynamically created in C Sharp?	}\nprotected void img_Click(object sender, ImageClickEventArgs e)\n{\n    ClientScript.RegisterClientScriptBlock(this.GetType(), "img",\n    "<script type = 'text/javascript'>alert('ImageButton Clicked');</script>");\n}>	0
7844304	7839000	How to order by columns from an inner join with QueryOver?	Entity2 e2Alias = null;\nEntity3 e3Alias = null;\nSomeEntity s = null;\nreturn NHibernateHelper.Session.QueryOver<SomeEntity>()\n    .JoinAlias(() => s, () => e2Alias.SomeEntityReference) //here you need to specify the other  side of the relation in the other entity that refernces th SomeEntity\n    .JoinAlias(() => s, () => e3Alias.SomeEntityReference)\n    .Where(() => s.Id > 10)\n    .OrderBy( () => e3Alias.SortOrder).Asc //or Desc\n    .List<SomeEntity>();	0
32019621	32018042	How to change background color and text of notifyIcon component	var notifyIcon = new NotifyIcon();\nnotifyIcon.BalloonTipText = "Your string here";	0
4455263	4455218	Remove specific character from a string based on Hex value - C#	stringVar.Replace((char)0xA0, ' ');	0
34055096	34054740	Adding to a boolean array after sending an email - C#	using System.Collections.Concurrent;\n\n\npublic static class Email\n{\n    private\n    static\n    readonly\n    ConcurrentDictionary<int, bool> dict =\n    new ConcurrentDictionary<int, bool>()\n    ;\n\n    public static bool TrySend(DateTime timestamp, int SensorID)\n    {\n\n        if (!dict.TryAdd(SensorID, true)) return false;\n\n        var client = new SmtpClient("smtp.gmail.com", 587)\n        {\n            Credentials = new NetworkCredential("@gmail.com", ""),\n            EnableSsl = true\n        };\n\n        client.Send("@gmail.com",\n                    "@gmail.com",\n                    "Alarm Alert!",\n                    "There was an alarm today at: " +\n                    timestamp  +\n                    " on Sensor: " +\n                    SensorID.ToString());\n\n        Console.WriteLine("Sent SensorID: " + SensorID.ToString());\n        return true;\n\n    }\n\n    public static void ClearSensorIDs()\n    {\n        dict.Clear();\n    }\n}	0
1679680	1679667	How do I convert a DateTime object to YYMMDD format?	DateTime.Now.ToString("yyMMdd")	0
7694209	7693215	Open excel workbook but set calculations to manual	static void Main(string[] args)\n    {\n        string cName = "";\n\n        var xlApp = new Application();\n\n        var xlWB = xlApp.Workbooks.Open("youpathgoeshere", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);\n        xlApp.Calculation = XlCalculation.xlCalculationManual; \n\n        var xlWS = new Worksheet();\n\n        xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);\n        cName = xlWB.FullName;\n        xlWB.Close();\n\n\n        xlApp.Quit();\n\n\n    }	0
28722167	28721938	to send hex codes to serial port	sp.PortName = "COM6";\nsp.BaudRate = 9600;\nsp.Parity = Parity.None;\nsp.DataBits = 8;\nsp.StopBits = StopBits.One;\nsp.Open();\nbyte[] bytestosend = { 0x14, 0x0E };\n\nsp.Write(bytestosend, 0, bytestosend.Length);\nsp.Close();\nsp.Dispose();\nsp = null;	0
32850589	32850530	How to dynamically resize an array?	public static Array ResizeArray (Array oldArray, int newSize)\n    int oldSize = oldArray.Length;\n    Type elementType = oldArray.GetType().GetElementType();\n    Array newArray = Array.CreateInstance(elementType,newSize);\n    int preserveLength = System.Math.Min(oldSize,newSize);\n    if (preserveLength > 0){\n        Array.Copy (oldArray,newArray,preserveLength);\n    }\n    retuen newArray;\n}	0
1192829	1192813	LINQ Modelling Column Name Same As Table Name	[Column(Name = 'Business')] public string BusinessCol { get; set; }	0
18282614	18282552	How to detect current color of ellipse in C# wpf	public bool IsRed {get;set;}\n\n\nvoid Ellipse1_Tapped(object sender, etcetera)\n{\n    Ellipse1.Fill = IsRed ? Brushes.Red : Brushes.White;\n    IsRed = !IsRed;\n}	0
21088164	21085229	html agility how to process table in a hyperlink	var rows = doc.DocumentNode.SelectNodes("//tr");\nforeach (var row in rows)\n{\n    var links = row.SelectNodes(".//a");\n    var artistLink = links[0].Attributes["href"];\n    var artistName = links[0].SelectSingleNode(".//strong/text()").InnerText;\n\n    var artistTypeLink = links[1].Attributes["href"];\n    var artistTypeName = links[1].SelectSingleNode(".//text()").InnerText;\n\n    // Store the results...\n}	0
19860533	19840168	Remove a row from the DataGrid	private void ValidateAndSave()\n{\n    //Check for validation errors\n    if ((this.Details.ValidationResults.HasErrors == false)) {\n        //Save the changes to the database\n        try {\n            this.DataWorkspace.DatabaseNameData.SaveChanges();\n        } catch (Exception ex) {\n            this.ShowMessageBox(ex.ToString());\n        }\n    } else {\n        //If validation errors exist,\n        string res = "";\n        //Add each one to a string,\n        foreach (object msg_loopVariable in this.Details.ValidationResults) {\n            msg = msg_loopVariable;\n            res = res + msg.Property.DisplayName + ": " + msg.Message + "\r\n";\n        }\n\n        //And display them in a message box\n        this.ShowMessageBox(res, "Validation error", MessageBoxOption.Ok);\n    }\n}	0
4247588	4247570	In linq, how do I take specific parameter out of a list and build new list of different type?	List<long> ids = genesisRepository.Entry2Cats\n                 .Where(x => x.streamEntryID == id)\n                 .Select(a => a.catID)\n                 .ToList();	0
20206343	20205501	I am trying to make a to create a delegate from property setter	ilgen.Emit(OpCodes.Ldarg, 1);\n    if (property.PropertyType.IsValueType)\n         ilgen.Emit(OpCodes.Unbox_Any, property.PropertyType);\n    else ilgen.Emit(OpCodes.Castclass, property.PropertyType);	0
22093752	22093427	windows authentication to get a list of users in MVC4	protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        if (httpContext == null)\n        {\n            throw new ArgumentNullException("httpContext");\n        }\n\n        IPrincipal user = httpContext.User;\n        if (!user.Identity.IsAuthenticated)\n        {\n            return false;\n        }\n\n        //_usersSplit = ListOfAuthorizedNames\n        if ((_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) && (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)))\n        {\n            return false;\n        }\n\n        return true;\n    }	0
13734003	13715601	sql create string variable with column names	CREATE FUNCTION funcReturnAllColumns\n(\n    @tableName VARCHAR(50)\n)\nRETURNS VARCHAR(500)\nBEGIN\n\nDECLARE @ID INT\nDECLARE @ALLColumns VARCHAR(500)\n\nSET @ALLColumns = ''\n\nSELECT @ID = id\nFROM sys.sysobjects\nWHERE name = @tableName\n\n\nSELECT @ALLColumns = @ALLColumns + '+' + name \nFROM sys.syscolumns\nWHERE id = @ID\n\nRETURN SUBSTRING(@ALLColumns,2,LEN(@ALLColumns))\n\nEND\n\n\nSELECT dbo.funcReturnAllColumns('table_name')	0
12556833	12556763	how to add white space into conditional regex	[RegularExpression(@"A|B|C|(A and B)", ErrorMessage = "You must select one.")]	0
17564922	17564734	Takind a value from linked list in C#	int size_linked = linked.Count();\n        int offff = 1;\n        int s = 0;\n        foreach (var item in linked)\n        {\n            string[] parts = item.Split(',');\n            my_array2[s] = parts[offff];\n            //if you want to take only first splitted string for every parts you comment this:\n            //offff += 6;\n            s++;\n        }	0
11153881	11153618	changing cell bgcolor on mouseover	.trAlt:hover td{\n   background: red;\n}	0
12266972	12266952	How to make ToString() method for a list of customs struct	public class EntryList : List<entry>\n{\n   public override string ToString()\n   {\n      //return what you want\n      //EDIT:  accessing items\n      foreach (entry e in this)\n         //...\n   }\n}	0
18071397	18071302	How can I add an index to a LINQ query when there is a grouping?	.Select((groupings, index) => expression)	0
1244977	1244953	Internal abstract class: how to hide usage outside assembly?	public abstract class MyClass\n{\n    internal MyClass() { }\n}	0
13511798	13511753	How can i switch from a boolean switch an OR operator on/off	private string getFromDB(bool decision)\n{\n    return db.Where(p => (Types.Contains(p.CurrentOwner) == decision));\n}	0
33565354	33478518	Silverlight OpenRIA - duplicated requests	reg add HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\WebProjects /v Use64BitIISExpress /t REG_DWORD /d 1	0
1155999	1155840	Winform keyboard management	private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n    if (this.ActiveControl == listBox1)\n        e.Handled = true;\n}	0
19714888	19504731	How to make Excel cell a combobox using c#?	Excel.Application App = null;\nExcel.Workbook Book = null;\n\nExcel.Worksheet Sheet = null;\n\nobject Missing = System.Reflection.Missing.Value;\n\ntry\n{\n    App = new Excel.Application();\n    Book = App.Workbooks.Add();\n\n    Sheet = (Excel.Worksheet) Book.Worksheets[1];\n\n    Excel.Range Range = Sheet.get_Range("B2", "B2");\n\n    Range.Validation.Add(Excel.XlDVType.xlValidateList\n        , Excel.XlDVAlertStyle.xlValidAlertStop\n        , Excel.XlFormatConditionOperator.xlBetween\n        , "Item1,Item2,Item3"\n        , Type.Missing);\n    Range.Validation.InCellDropdown = true;\n    Range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(255, 217, 217, 0)); \n\n    App.Visible = true;\n}\nfinally\n{\n    Base.ReleaseObject(Sheet);\n    Base.ReleaseObject(Book);\n    Base.ReleaseObject(App);\n}	0
23082796	23082539	How to set the endian of a byte array in c#	System.Convert	0
3101782	3101048	XSLT transformation on Large XML files with C#	5 * text-size	0
25231150	25230024	Get DbContext from Entity in Entity Framework	public static DbContext GetDbContextFromEntity(object entity)\n{\n    var object_context = GetObjectContextFromEntity( entity );\n\n    if ( object_context == null )\n        return null;\n\n    return new DbContext( object_context, dbContextOwnsObjectContext: false );\n}\n\nprivate static ObjectContext GetObjectContextFromEntity(object entity)\n{\n    var field = entity.GetType().GetField("_entityWrapper");\n\n    if ( field == null )\n        return null;\n\n    var wrapper  = field.GetValue(entity);\n    var property = wrapper.GetType().GetProperty("Context");\n    var context  = (ObjectContext)property.GetValue(wrapper, null);\n\n    return context;\n}	0
12490500	12387127	EmguCV Skin Detection	Image<Bgr, Byte> img = ....\n\n for (i = 0; i < img.Height; i++)\n {\n     for (k = 0; k < img.Width; k++)\n     {\n         // Get \n         // Color ( R, G, B, alpha) \n         Color c = img[i, k];\n\n         // Set \n         img[i,k] = new Bgr();\n      }\n }	0
449581	449523	Excluding System Databases while excecuting sp_databases in SQL Server	create table #t (db_name varchar(255), db_size int, remarks text) \n\ninsert #t \nexec sp_databases\n\nselect * from #t\nwhere db_name not in ('master', 'model', 'tempdb', 'msdb')	0
23266134	23263089	Register multiple components with multiple services in Castle Windsor	container.Register(\n    // we want all concrete classes in this assembly\n    Classes.FromThisAssembly()\n    // but we filter them to keep only the ones in a specific namespace\n    .InSameNamespaceAs<RootComponent>()\n    // we register thoses classes to interfaces that match the classes names\n    .WithService.DefaultInterfaces()\n    // setting the lifestyles for all components in this batch\n    .LifestyleTransient()\n);	0
9029648	9029615	How to do a simple OR query with LINQ?	var links = _entityContainer.Links\n    .Where(x => \n        x.Tags.Any(y => tags.Contains(y.Name)) ||\n        searchTerms.Any(y => x.Title.Contains(y)));	0
18346909	18346880	How do I pass a class object containing this and call a method from that class	public partial class settingsForm : Form\n{\n    private formControlTracker _cTracker;\n\n    public settingsForm()\n    {\n        //set the field value in the constructor.\n        _cTracker = new formControlTracker(this);\n\n    }\n\n    public void lDirtyControls()\n    {\n        //use the field variable here\n        /*foreach (string con in _cTracker.getDirtyControls())\n        {\n            MessageBox.Show(con);\n        }*/\n    }\n}	0
17829339	17829291	C#: Gets unmatched elements between 2 collections with Linq & Lambda	var result = collection1.Except(collection2).Concat(collection2.Except(collection1)).ToArray();	0
33766540	33766513	Adding multiple values to arraylist from user input	library.Add(new Books(textbox1.text, textbox2.text, textbox3.text));	0
7858577	7858488	How to cancel long-running operations that require to start on the server side (rather than initiated by the client)	CancelAsync()	0
14083179	14083158	How to display a some records in ChekedListBox	CheckedListBox1.DataSource = tempDataSet.Tables("Cat")\nCheckedListBox1.DisplayMember = "Color"\nCheckedListBox1.ValueMember = "ID"	0
3359925	3359916	Format to two decimal places	Console.WriteLine("{0:N2}", ((double)n) / 1450);	0
6634709	6426067	Task Parallel Library - building a tree	var A = Task.Factory.StartNew(\n  () => Console.WriteLine("A"));\nvar B = Task.Factory.StartNew(\n  () => Console.WriteLine("B"));\nvar E = Task.Factory.StartNew(\n  () => Console.WriteLine("E"));\nvar C = Task.Factory.StartNew(\n  () => { Task.WaitAll(A, B); Console.WriteLine("C"); });\nvar D = Task.Factory.StartNew(\n  () => { Task.WaitAll(C, E); Console.WriteLine("D"); });\nTask.Factory.StartNew(\n  () => { Task.WaitAll(E, D); Console.WriteLine("F"); })\n    .ContinueWith(a => Console.WriteLine("G"));	0
10050319	10049645	Parallel Partition Algorithm in C#: How to Maximize Parallelism	.Concat()	0
16812575	16791106	asp:RequiredFieldValidator validation based on conditions	ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or\nValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);	0
33783468	33769221	DataGridView, always keep first column visible whilst horizontally-scrolling?	dataGridView1.Columns[0].Frozen = true;	0
30799289	30799075	How can I replace script contents of html in a StringBuilder	siteCode.Replace("s.property1=\"||property1||\"", "");	0
4346310	4346261	Ado dot netconnection String with Access 2007	Microsoft.ACE.OLEDB.12.0	0
6624689	6598857	DbSet table name	string name = (context as IObjectContextAdapter).ObjectContext.CreateObjectSet<MyClass>().EntitySet.Name;	0
3891315	3887424	How to Configure SQLCE connection on Smart Device Application using Emulator?	\storage card\myfile.sdf	0
5479129	5474210	Reading PDF Annotations with iText	PdfDictionary pageDict = myPdfReader.getPageN(firstPageIsOne);\n\nPdfArray annotArray = pageDict.getAsArray(PdfName.ANNOTS);\n\nfor (int i = 0; i < annotArray.size(); ++i) {\n  PdfDictionary curAnnot = annotArray.getAsDict(i);\n\n  int someType = myCodeToGetAnAnnotsType(curAnnot);\n  if (someType == THIS_TYPE) {\n    writeThisType(curAnnot);\n  } else if (someType == THAT_TYPE) {\n    writeThatType(curAnnot);\n  }\n}	0
25276761	25274291	Export datatable to csv and import to client without saving in server	Response.Clear();\n        Response.AddHeader("content-disposition", "attachment; filename=data.csv");\n        Response.ContentType = "text/csv";\n        Response.Write(stringContainingCSVData);\n        Response.End();	0
25697965	25697866	add the count of child node in each branch of asp.net treeview	void Page_Load(Object sender, EventArgs e)\n{\n    // Iterate through the root nodes in the Nodes property.\n    for(int i=0; i<YourTreeView.Nodes.Count; i++)\n    {\n        // Set the text to include children count.\n        SetChildNodeText(YourTreeView.Nodes[i]);\n    }\n}\n\nvoid SetChildNodeText(TreeNode node)\n{\n    if(node.ChildNodes.Count > 0)\n    {\n        node.Text += ' (' + node.ChildNodes.Count.ToString() + ')'; // append child node count to the text\n    }\n\n    for(int i=0; i<node.ChildNodes.Count; i++)\n    {\n        // recursion\n        SetChildNodeText(node.ChildNodes[i]);\n    }\n}	0
7375097	7374988	finding daylight saving indication based on offset and suffix of time zone	var offSet = -7;\nvar utcDateTimeStr = "2011-09-10 22:15:38";\nvar localWithDSStr = "10 Sep 2011 15:15:38";\n\n// utc time\nDateTime utcDateTime = DateTime.SpecifyKind(\n                           DateTime.Parse(utcDateTimeStr), DateTimeKind.Utc);\n// time taking into account daylight savings\nDateTime localWithDS = DateTime.SpecifyKind(\n                           DateTime.Parse(localWithDSStr), DateTimeKind.Local);\n// time not taking into account daylight savings\nDateTime localWithoutDS = utcDateTime.AddHours(offSet);\n\n// is the time given adjusted for daylight savings\nTimeSpan diff = (localWithoutDS - utcDateTime);\nbool isDayLightSaving = diff.Hours != offSet;	0
1612160	1612118	NUnit and TestCaseAttribute, cross-join of parameters possible?	[Test, Combinatorial]\npublic void Test1( \n    [Values(1,2,3,4)] Int32 a, \n    [Values(1,2,3,4)] Int32 b, \n    [Values(1,2,3,4)] Int32 c\n)\n{\n    ...\n}	0
5064893	5064317	How to searching and change XML if needed?	// Load the XML from file\nXElement docElem = XElement.Load(path);\n// Get the Connections element. This code assumes there will always be exactly one.\nXElement connectionsElem = docElem.Elements("Connections").Single();\n\n// Check if there is already a Conn element with the required attribute value combination\nif (!connectionsElem.Elements("Conn").Any(connElem =>\n    (string)connElem.Attribute("ServerName") == serverName &&\n    (string)connElem.Attribute("DataBase") == dataBase &&\n    (string)connElem.Attribute("User") == user &&\n    (string)connElem.Attribute("Pass") == pass)) {\n\n    // Otherwise add such a Conn element\n    connectionsElem.AddFirst(\n        new XElement("Conn",\n            new XAttribute("ServerName", serverName),\n            new XAttribute("DataBase", dataBase),\n            new XAttribute("User", user),\n            new XAttribute("Pass", pass)\n        )\n    );\n}\n\n// Write the XML to file again.\ndocElem.Save(path);	0
10288246	10279844	SSL endpoint on a WCF service with only XML configuration file	netsh http add sslcert ipport=0.0.0.0:8732 certhash=4745537760840034c3dea27f940a269b7d470114 appid={00112233-4455-6677-8899-AABBCCDDEEFF}	0
23705578	23705554	Join strings without repeating delimiter	Path.Combine()	0
2295694	2279591	Need help to create playlist from DB for JW Player	flashvars="playlistfile=http://localhost/templatesNew/MultimediaPlayList.aspx?	0
11071877	11071857	Using OnInit property in aspx page	public void ConfigureDashboardList(object sender,EventArgs e){}	0
25416467	25395793	Adding new data to JSON file with file's original formatting in C#	string json = File.ReadAllText(filePath);\n\n    JObject jo = JObject.Parse(json);\n    JObject profiles = (JObject)jo["profiles"];\n\n    profiles.AddFirst(\n        new JProperty("MinecraftSparta 1.7.10",\n            new JObject(\n                new JProperty("name", "MCS 1.7.10"),\n                new JProperty("gameDir", directory),\n                new JProperty("lastVersionId", " 1.7.10-forge10.13.0.1205"),\n                new JProperty("javaArgs", "-Xms:2G -XX:PermSize=128m"),\n                new JProperty("useHopperCrashService", false)\n            )\n        )\n    );\n\n    File.WriteAllText(filePath, jo.ToString());	0
3222313	2916177	How do I determine if a packet is RTP/RTCP?	0                   1                   2                   3\n 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|V=2|P|X|  CC   |M|     PT      |       sequence number         |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|                           timestamp                           |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|           synchronization source (SSRC) identifier            |\n+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n|            contributing source (CSRC) identifiers             |\n|                             ....                              |\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+	0
22238317	22072043	In AtTask, how can I get a list of documents not in a folder?	attask/api-internal/docu/search?projectID=5314e38b00000003b76ff5980a142082&folders:name_Mod=isnull&&folders_Join=allowingnull	0
6344434	6344323	set desktop to extend/clone in dual display in windows	EnumDisplaySettingsEx()	0
5468717	5468342	How to modify my App.exe.config keys at runtime?	System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\nconfig.AppSettings.Settings["UserId"].Value = "myUserId";     \nconfig.Save(ConfigurationSaveMode.Modified);	0
7026378	7016739	how to combine two dataset to one xml file	dsView2.Tables[0].TableName="TableName";\ndsView1.Tables.Add(dsView2.Tables[0].Copy());	0
15184867	15184835	how to decreasing the size of the font by click in C#	Font font = richTextBox1.Font;\nfloat newSize = font.Size;\nnewSize -= 2.0F;\nrichTextBox1.Font = new Font(font.FontFamily, newSize, font.Style);	0
22451146	22449183	Merge 2 consecutive elements in a List<string>	public static List<string> combine_list_elements(List<string> lst_original, int i, int j)\n{\n   if (lst_original.Count > i && lst_original.Count > j)\n   {\n       lst_original[i] += " " + lst_original[j];\n       lst_original.RemoveAt(j);\n   }\n   else\n   {\n       throw new Exception("One of these 2 items does not exist in this list.");\n   }\n   return lst_original;\n}	0
18032718	18032699	How to get a certain string from text. C#	string[] results = yourstring.split(':');\n  yourtextbox.Text = results[1]+ ":" + results[2];   //results1 will give depreciated and results 2 will give UsErname	0
19372754	19372642	KeyCode Value for Alt is showing up as Shift	if (e.Modifiers == Keys.Alt)\n{\n    MessageBox.Show("You pressed the Alt key.");\n}	0
20144783	20144162	How to add mp3 files to a MediaPlayer.Queue, or otherwise play a list of mp3 files sequentially on Windows Phone?	foreach (var track in _tracks)\n{\n    var name = track.Item1;\n    var uri = new Uri(string.Format("{0}/{1}", "/Resources/raw", name), UriKind.Relative);\n\n    var song = Song.FromUri(name, uri);\n\n    Thread.Sleep(2000); // this value has to be longer than the track\n\n    FrameworkDispatcher.Update();        \n    MediaPlayer.Play(song); \n\n}	0
16054902	15872315	Using a repeater with Entity Framework	List<TagObject>	0
23578348	23578298	guid in file uploading	if (FileUpload1.HasFile == true)\n{\n    string filename = Guid.NewGuid().ToString(); // you used one extra new before Guid.NewGuid().ToString();\n    FileUpload1.SaveAs(Server.MapPath("~/upload/") + filename);\n}	0
4388434	4388396	how to change the value of dictionary during looping	foreach (var key in dtParams.Keys.ToArray())\n{\n   dtParams[key] = dtParams[key].Replace("'", "''");\n}	0
4809476	4808797	Using NHibernate, how can I retrieve a list of composite-element objects given a parent's ID?	session.CreateQuery("SELECT elements(e.Items) FROM Event e WHERE e.Id = :id")\n   .SetParameter("id", eventId)\n   .List<EventItem>();	0
28613490	28613462	How do you get all X objects in all Y objects?	IEnumerable<Cell> cells = this.rows.SelectMany(r => r.Cells);	0
1793625	1793607	how to copy a list to a new list, or retrieve list by value in c#	List<MyType> copy = new List<MyType>(original);	0
33055648	33055589	Simple Windows Application program in C# confusion	// populate the array\nnums[0] = Int32.Parse(textBox1.Text);\nnums[1] = Int32.Parse(textBox2.Text);\nnums[2] = Int32.Parse(textBox3.Text);\nnums[3] = Int32.Parse(textBox4.Text);\nnums[4] = Int32.Parse(textBox5.Text);\n\n// sort the array from lowest to highest\nArray.Sort(nums);\n\n// declare a variable to hold the sum\nint sum = 0;\n\n// iterate over the first (smallest) three\nfor(int i=0;i<3; i++)\n{\n   sum += nums[i];\n}\n\nConsole.WriteLine("The sum of the three smallest is: " + sum);	0
3091096	3090736	How to Set Screen Resolution At run time in wpf	SystemParameters.FullPrimaryScreenHeight\nSystemParameters.FullPrimaryScreenWidth	0
5685392	5685362	play sound in c# without using Media Namespace	[DllImport("kernel32.dll")]\npublic static extern bool Beep(UInt32 frequency, UInt32 duration);	0
11696043	11695981	Show/Hide button on MouseOver	private void Form_MouseMove(object sender, MouseEventArgs e) {\n    if(settingButton.Bounds.Contains(e.Location) && !settingButton.Visible) {\n        settingButton.Show();\n    }\n}	0
30127809	30127703	How to output only a part of values from ListBox?	lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];	0
23711861	23711557	Windows Form to Send email	public static MailAddress from = new MailAddress("myAddress@gmail.com","Ramy Mohamed");\n    string password = "balabala";\n    var smtp = new SmtpClient\n        {\n            Host = "smtp.gmail.com",\n            Port = 587,\n            EnableSsl = true,\n            UseDefaultCredentials = false,\n            DeliveryMethod = SmtpDeliveryMethod.Network,\n            Credentials = new NetworkCredential(from.Address, password)\n        };\n\n       using (var message = new MailMessage(from, SendToAddress.Text)\n                {\n                    Subject = MySubjectText.Text,\n                    Body = MyContentText.Text\n                })\n                {\n                    smtp.Send(message);                        \n                }	0
28054815	27988854	Generate Oulook Email From Server	var theApp    //Reference to Outlook.Application \nvar theMailItem   //Outlook.mailItem\n//Attach Files to the email, Construct the Email including     \n//To(address),subject,body\nvar subject = sub\nvar msg = body\n//Create a object of Outlook.Application\ntry\n{\n    var theApp = new ActiveXObject("Outlook.Application")\n    var theMailItem = theApp.CreateItem(0) // value 0 = MailItem\n      //Bind the variables with the email\n      theMailItem.to = to\n      theMailItem.Subject = (subject);\n      theMailItem.Body = (msg);\n      //Show the mail before sending for review purpose\n      //You can directly use the theMailItem.send() function\n      //if you do not want to show the message.\n      theMailItem.display()\n  }\ncatch(err)\n{\n    alert("Error");\n}	0
26854637	26852056	Accessing Contacts From .OST File Office 2010/2013	Items items = contacts.Items;\nfor (int i = 1; i <= items.Count; i++)\n{\n    ContactItem contact = items[i] as ContactItem;\n    if (contact !=null)\n    {\n       ...\n    }\n}	0
1876848	1829269	Efficient way to send images via WCF?	"a simple protocol for remote access to graphical user interfaces. Because it works at the framebuffer level it is applicable to all windowing systems and applications, including X11, Windows and Macintosh. RFB is the protocol used in VNC (Virtual Network Computing)."	0
16491082	16490916	How can I get a nested IN clause with a linq2sql query?	List<int> IDs = new List<int>();\nIDs.Add(3);\nIDs.Add(4);\n\nvar ACTIVITY_VERSION_IDs = ACTIVITY_TOPIC\n      .Where(AT => IDs.Contains(AT.TOPIC_ID))\n      .Select(AT=>AT.ACTIVITY_VERSION_ID)\n\nvar results = ACTIVITY_VERSION\n      .Where(AV => ACTIVITY_VERSION_IDs.Contains(AV.ACTIVITY_VERSION_ID))	0
3192511	3192389	What's the quickest, cleanest way to remove parent pathing from a URL string?	var url = "/foo/bar/../bar.html";\nvar ubuilder = new UriBuilder();\nubuilder.Path = url;\nvar newURL = ubuilder.Uri.LocalPath;	0
24425250	24424085	How to prevent to run an exe from two different computers	private static Stream lockFile;\npublic static void Main()\n{\n  try\n  {\n    try\n    {\n      lockFile = File.OpenWrite(@"\\server\folder\lock.txt");\n    }\n    catch (IOException e)\n    {\n      int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();\n      if (err == 32)\n      {\n        MessageBox.Show("App already running on another computer");\n        return;\n      }\n      throw; //You should handle it properly...\n    }\n\n    //... run the apps\n  }\n  finally\n  {\n    if (lockFile != null)\n      lockFile.Dispose();\n  }\n}	0
20307612	20307592	WCF Json Service Parameters are Null	{"member1":\n{\n"first_name":"shaw",\n"last_name":"levin",\n"gender":0,\n"Grad_Year":2015,\n"personality":3,\n"campus":1,\n"social":0,\n"cleaning":1,\n"diet":1,\n"religious":3,\n"roomamate_prefs":"Hello",\n"hs_engagement":"World"\n}}	0
13075250	13071652	Storing RTSP to a file location	Vlc.DotNet.Core.Medias.MediaBase media1\n= new Vlc.DotNet.Core.Medias.PathMedia("rtsp://192.168.137.73:554/live.sdp");\n\nmedia.AddOption(":sout=#transcode{vcodec=theo,vb=800,\nscale=1,acodec=flac,ab=128,channels=2,samplerate=44100}:std{access=file,mux=ogg,\ndst=D:\\123.mp4}");\n\nVlcControl control = new VlcControl();\ncontrol.Media = media;\ncontrol.Play();	0
7993715	7993110	How can I fill a gridview using a connection to a ACCESS DB	OleDbConnection myConnection = default(OleDbConnection);\n         OleDbCommand myCommand = default(OleDbCommand);\n         string strSQL = null;\n         strSQL = "SELECT * FROM tblLoginInfo " + "WHERE username='" + CustID.Replace("'", "''") + "' " + "AND password='" +\n CustPass.Replace("'", "''") + "';";\n         myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source="\n + Server.MapPath("login.mdb") + ";");\n        myConnection.Open();\n         myCommand = new OleDbCommand(strSQL, myConnection);\n\n         OleDbDataAdapter adp=new OledbDataAdapter(myCommand);\n         dataset ds=new dataset();\n         adp.fill(ds);\n        gridview.datasource=ds;\n        gridview.databind();	0
7915909	7915091	Access DataLists inside the ListView	for each item As ListViewDataItem in lvSection.Items\n    Dim list As DataList = item.FindControl("dlQuestion")\n    If (list IsNot Nothing) Then\n        For Each dlItem As DataListItem In quest.Items\n\n            Dim questionId As HiddenField = dlItem.FindControl("hfQuestionId")\n\n        Next\n    End If\nNext	0
5568083	5568034	How to create a string with special characters in C#	string temp = "<Object type=\"System.Windows.Forms.Form"	0
22293835	22293721	Getting Top 3 from Mysql table based on Condition/Value	(SELECT Name, PositionId, TScore FROM Soccerplayers WHERE PositionID = 1 ORDER BY TScore LIMIT 3)\nUNION\n(SELECT Name, PositionId, TScore FROM Soccerplayers WHERE PositionID = 2 ORDER BY TScore LIMIT 4)\nUNION\n(SELECT Name, PositionId, TScore FROM Soccerplayers WHERE PositionID = 3 ORDER BY TScore LIMIT 3)	0
3287417	3287372	string Format - how to change negative sign position	string Test = string.Format("{0:#,0;#,0-}", NegativeNumber);	0
27843350	27842864	Regular expression for tokenizing connection string	(?<key>[^=;,]+)=(?<val>[^;,]+(,\d+)?)	0
6811906	6811790	C# Loading dates from XML file	XElement root = new XElement("Root",new XElement("Child", "child content"));\nroot.Save("Root.xml");	0
10402532	10402256	Cant get resource from application level	res = this.FindResource("myBrush"); // this 'walks' the tree and will find it\nres = Application.Current.Resources["myBrush"]; // or reference app resources directly\nres = App.Current.TryFindResource("myBrush");	0
21857486	21856420	Create or replace node in an XML without root in C#	var fragment = @"<Something>abc</Something>\n<Another>def</Another>\n<Other>ghi</Other>";\n\nvar xDoc = XDocument.Parse("<TempRoot>" + fragment + "</TempRoot>");\n\nxDoc.Descendants("Another").First().Value = "Jabberwocky";\nxDoc.Root.Add(new XElement("Omega", "Man"));\n\nvar fragOut = \n   string.Join(Environment.NewLine, xDoc.Root\n                                        .Elements()\n                                        .Select (ele => ele.ToString()));\n\nConsole.WriteLine (fragOut);\n/* Prints out\n<Something>abc</Something>\n<Another>Jabberwocky</Another>\n<Other>ghi</Other>\n<Omega>Man</Omega>\n*/	0
21268618	21206844	How to expand calling expressions other than predicates?	var statusFromSomeFunkyEntity = GetStatusFromSomeFunkyEntity();\n\nvar query =\n    from i in this.DbContext.MyFunkyEntities.AsExpandable()\n    select new SomeFunkyEntityWithStatus()\n    {\n        FunkyEntity = i,\n        Status = statusFromSomeFunkyEntity.Invoke(i)\n    };	0
21157194	21136069	save greyscale image as color JPEG	FormatConvertedBitmap convertImg = new FormatConvertedBitmap(img, PixelFormats.Bgra32, null, 0);\nJpegBitmapEncoder encoder = new JpegBitmapEncoder();\nencoder.Frames.Add(BitmapFrame.Create(convertImg));\nencoder.Save(stream);	0
4946666	4946592	How can I navigate any JSON tree in c#?	IDictionary<string, object> deserializedJson = jsonText.ToDictionary();	0
31195223	31195202	strange behavior of Contains() in a list of arrays	Equals()	0
13658096	13657994	Converting single dimensional array to 2D array in c#	int[] arrayRow;\nint[] arrayCol;\n\nint[,] myArray = new int[Math.Max(arrayRow.Length, arrayCol.Length), 2];\n\nfor (int i = 0; i < arrayRow.Length; i++)\n  myArray[i, 0] = arrayRow[i];\n\nfor (int i = 0; i < arrayCol.Length; i++)\n  myArray[i, 1] = arrayCol[i];	0
20204691	20204590	How to sort DataTable based on multiple column?	dv.Sort = "Name, Date";	0
25148139	25148098	Make client proxy variable global	public class MyProxySingleton\n{\n\nprivate static Service1Client  _proxy = null;\n\npublic static Service1Client Instance \n{ \n  get\n  {\n    if (_proxy == null)\n    {\n        _proxy = new Service1Client();\n    }\n\n    return _proxy;\n  }\n}\n}	0
20483365	20482053	Cannot create controller with Entity framework - Unable to retrieve metadata	public class EFDbContext : DbContext\n{\n    public DbSet<Product> Products { get; set; }\n}	0
31881670	31880439	Converting arrays - from VBA to C# (Best Practice)	public class CustomArray {\n      private Double[] myArray;\n      private int spread;\n\n      public CustomArray(){\n        setSize(5,100);\n      }\n\n      public void setSize (int lowerIndex, int upperIndex){\n        myArray = new Double[(upperIndex-lowerIndex)+1]\n        spread = lowerIndex\n      }\n\n      public Double getElement(int index){\n        return myArray[index-spread];\n      }\n\n      public void setElement(int index, Double element){\n        myArray[index-spread] = element;\n      }\n    }	0
32131708	32130907	Changing Docked Scrollbar Spacing/Margin	protected override void OnSizeChanged(EventArgs e) {\n    base.OnSizeChanged(e);\n    hbar.MaximumSize = new System.Drawing.Size(this.ClientSize.Width - SystemInformation.VerticalScrollBarWidth, int.MaxValue);\n}	0
13555441	13555274	FTP Dynamically create folders while uploading	myFtpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory	0
26027937	26027913	adding token to <a href	Guid newId = Guid.NewId();\nstring html = string.Format("<p>Your password has been reset.Please click the link to create new password.</p><a href=\"http://somewebsite.azurewebsites.net/ResetPassword.aspx?token={0}\">Reset Password Link</a>",newId);	0
4452542	4452497	combining insert sql statment with select statement for more than 1 value	INSERT INTO dbo.sessions (se_user, se_ip)\nSELECT user_id, @ipAddress FROM dbo.users WHERE username = @username	0
18584789	18584707	How to add items in a datatable to a listview?	private void button1_Click(object sender, EventArgs e)\n{\n    listView1.View = View.Details;\n    SqlConnection con = new SqlConnection("connectionstring");\n    SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);\n    DataTable dt = new DataTable();\n    ada.Fill(dt);\n\n    for (int i = 0; i < dt.Rows.Count; i++)\n    {\n        DataRow dr = dt.Rows[i];\n        ListViewItem listitem = new ListViewItem(dr["pk_Location_ID"].ToString());\n        listitem.SubItems.Add(dr["var_Location_Name"].ToString());\n        listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());\n        listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());\n       listView1.Items.Add(listitem);\n    }	0
7487595	7487551	No argument names in abstract declaration?	abstract member createEmployee : firstName:string -> lastName:string -> Employee	0
12260372	12260304	How can I get a string without a SubString?	String.Remove	0
22010087	21965605	How to call a Stored Procedure inside an oracle package with Entity Framework?	var param1 = new OracleParameter("personnel_Id_in", OracleDbType.VarChar, "c5eb5589-8fee-47b6-85ad-261a0307cc16",  ParameterDirection.Input);\nvar param2 = new OracleParameter("base_date_in", OracleDbType.VarChar, "1112", ParameterDirection.Input);\nvar param3 = new OracleParameter("is_current_in", OracleDbType.Number, 1, ParameterDirection.Input);\nvar param4 = new OracleParameter("result", OracleDbType.Cursor, ParameterDirection.Output);\n\nvar ATests =\ndb.Database.SqlQuery<ATest>(\n"BEGIN PKG_TRAINING_SP.GETPERSONNELTRAINIGLIST(:personnel_Id_in, :base_date_in, :is_current_in, :result); end;", \nparam1,  param2, param3, param4).ToList();	0
12645783	12645705	C#-Bitmap to Byte array	using (Bitmap bitmap = new Bitmap(500, 500))\n{\n    using (Graphics g = Graphics.FromImage(bitmap))\n    {\n        ...\n    }\n\n    using (var memoryStream = new MemoryStream())\n    {\n        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);\n        return memoryStream.ToArray();\n    }\n}	0
190297	188892	glob pattern matching in .NET	Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );	0
9702531	9702439	Starting a new thread with a constructor	Func<Manager> asyncConstructor;\n    private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)\n    {\n        asyncConstructor = new Func<Manager>(() => new Manager());\n\n        asyncConstructor.BeginInvoke(ManagerConstructed, null);\n    }\n\n    private void ManagerConstructed(IAsyncResult result)\n    {\n        Manager mgr = asyncConstructor.EndInvoke(result);\n        //we can only access form controls from the GUI thread, \n        //if we are not on the gui thread then\n        //do the changes on the gui thread.\n        if (this.InvokeRequired)\n        {\n            this.Invoke(new Action(() =>\n            {\n                sl.Text = mgr.test();\n                txtLog.Text = mgr.output();\n            }));\n        }\n    }	0
3521198	3521119	C# Format String as Date	public static string GetDateString(string date)\n{\n    DateTime theDate;\n    if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss", \n            CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))\n    {\n        // the string was successfully parsed into theDate\n        return theDate.ToString("yyyy'/'MM'/'dd");\n    }\n    else\n    {\n        // the parsing failed, return some sensible default value\n        return "Couldn't read the date";\n    }\n}	0
9447319	9447203	Connection String management for a desktop application	Ildasm.exe	0
10249642	10014026	Can a single schema.ini definition cover multiple files	[file1.csv]\nFORMAT = Delimited(#)\nColNameHeader = True\nMaxScanRows=10\nCol1=...\nCol2=...\nColN=...\n\n[File2.csv]\nFORMAT = Delimited(#)\nColNameHeader = True\nMaxScanRows=10\nCol1=...\nCol2=...\nColN=...	0
8113687	8113546	how to determine whether an IP address in private?	private bool isIPLocal(IPAddress ipaddress)\n{\n    String[] straryIPAddress = ipaddress.ToString().Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries);\n    int[] iaryIPAddress = new int[] { int.Parse(straryIPAddress[0]), int.Parse(straryIPAddress[1]), int.Parse(straryIPAddress[2]), int.Parse(straryIPAddress[3]) };\n    if (iaryIPAddress[0] == 10 || (iaryIPAddress[0] == 192 && iaryIPAddress[1] == 168) || (iaryIPAddress[0] == 172 && (iaryIPAddress[1] >= 16 && iaryIPAddress[1] <= 31)))\n    {\n        return true;\n    }\n    else\n    {\n        // IP Address is "probably" public. This doesn't catch some VPN ranges like OpenVPN and Hamachi.\n        return false;\n    }\n}	0
21479891	21479122	How to check if a byte array ends with carriage return	byte[] fileContent = File.ReadAllBytes(openFileDialog.FileName);\nbyte[] endCharacter = fileContent.Skip(fileContent.Length - 2).Take(2).ToArray();\n\nif (!(endCharacter.SequenceEqual(Encoding.ASCII.GetBytes(Environment.NewLine))))\n{\n     fileContent = fileContent.Concat(Encoding.ASCII.GetBytes(Environment.NewLine)).ToArray();\n     File.AppendAllText(openFileDialog.FileName, Environment.NewLine);\n}	0
33010061	33006617	How to create an 1 pixel wide window using C# and WinForm	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        this.FormBorderStyle = FormBorderStyle.None;\n    }\n    protected override void OnLoad(EventArgs e) {\n        this.Width = 1;\n        base.OnLoad(e);\n    }\n}	0
31851502	31851416	How can I use space according to variables value?	mystring = "A:\"" + (!String.IsNullOrEmpty(var1) ? (var1 + " ") : "") + (!String.IsNullOrEmpty(var2) ? (var2 + " ") : "") + (!String.IsNullOrEmpty(var3) ? (var3 + " ") : "") + "\"";	0
2023561	2023507	C# Output XML from Linq to Response.OutputStream	var result = myView.ToArray();\nvar serializer = new XmlSerializer(result.GetType());\nserializer.Serialize(Response.OutputStream, result);	0
6989786	6989700	How to enable two different C# applications accessing the same directory in a continuous thread?	Mutex m = new Mutex(false, "MySpecialMutex");	0
23557664	23533113	Error when sending http POST request from C# client to python server	import cherrypy\nfrom cherrypy import request\n\nclass test:\n    @cherrypy.expose\n    def index(self, **params):\n        # all the request parametes goes into the params dictionary.\n        # in case that no port is defined return None\n        print params.get('port', None) \n        return "Done";\n\n\nif __name__ == "__main__":\n    cherrypy.config.update( {'server.socket_host':"0.0.0.0",\n                             'server.socket_port':8181 })\n    cherrypy.quickstart(test())	0
11421935	11421791	How to use generics with the current type	public abstract class Parent<T> : IParent\n{\n    public void DoSomething() {\n        var c=new GenericClass<T>();\n        c.DoYourThing();\n    }\n}\n\npublic sealed class Child : Parent<Child>\n{\n}	0
8074624	8074553	How can I share values across classes (or get a variable from another class) without instantiating twice. 	class Theatre\n    {\n        public Theatre(int numberOfSeats)\n        {\n            NumberOfSeats = numberOfSeats;\n        }\n        public int NumberOfSeats { get; private set; }\n    }\n\n    class Show\n    {\n        List<Seats> listOfSeats = new List<Seats>();\n\n        public Show(Theatre theatre)\n        {\n            for (int i = 0; i < theatre.NumberOfSeats; i++) //  <---- And here is my problem!!\n            {\n                //Code to add to list\n            }\n        }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Theatre myTheatre = new Theatre(100);\n            Show myShow = new Show(myTheatre);\n        }\n    }	0
4624413	4624113	Start a .Net Process as a Different User	System.Diagnostics.Process proc = new System.Diagnostics.Process();\nSystem.Security.SecureString ssPwd = new System.Security.SecureString();\nproc.StartInfo.UseShellExecute = false;\nproc.StartInfo.FileName = "filename";\nproc.StartInfo.Arguments = "args...";\nproc.StartInfo.Domain = "domainname";\nproc.StartInfo.UserName = "username";\nstring password = "test";\nfor (int x = 0; x < password.Length; x++)\n{\n    ssPwd.AppendChar(password[x]);\n}\nproc.StartInfo.Password = ssPwd;\nproc.Start();	0
5054325	5053847	string.Format alternatives	EscapeCurlies(String Input)\n{\n    String Temp = Input.Replace("{", "{{");\n    Temp = Temp.Replace("}", "}}");\n\n    Temp = Regex.Replace(Temp, @"{{(\d+)}}", "{$1}");\n\n    return Temp;\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    String buttonName = "bob";\n\n    String FormatString = \n@"<script type=""text/javascript"">\n$(document).ready(function() {\n$('#{0}').click(function() {\nalert('Handler for .click() called.');\n});\n});\n</script>";\n\n    String Test = string.Format(EscapeCurlies(FormatString), buttonName);\n}	0
34370091	34352616	Alert message if data is existed in MS ACCESS DB using c#	int Count;\n    con.Open();\n        OleDbCommand cmd = new OleDbCommand("SELECT * FROM TABLENAME WHERE   COLUMNNAME= '" + TXT1.Text + "'", con);\n        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);\n        DataTable dt = new DataTable();\n        adapter.Fill(dt);\n        if (dt.Rows.Count == 0)\n        {\n//Insert Query\n           Response.Write("<script>alert('Added Successfully!!')</script>");\n         }else\n         {\n            Response.Write("<script>alert('Data is Exist!!')</script>");\n\n        }	0
14254312	14250387	BDD/TDD with Revit API	Assembly.Load(byte[])	0
6067984	6067651	How to apply transaction roll back in database object in .net c#	try    \n{   \n    using (TransactionScope scope = new TransactionScope())     \n    {                                   \n        m_test = CreateTest();          \n        scope.Complete(); // Commit transaction     \n    }    \n}    \ncatch (Exception ex)    \n{\n    // Transaction is automatically rolled back\n}	0
23809500	23809183	Get custom attributes from an c# event	Console.WriteLine("Attr: {0}",\n    Attribute.GetCustomAttribute(\n        typeof(TestClass).GetEvent("TestEvent"),    // This line looks up the reflection of your event\n        typeof (TestAttribute))\n    != null);	0
29811331	29810556	Error using Data Source relative path in Excel Data Driven Unit Test	connectionString="Dsn=Excel Files;Dbq=ExcelDataSource.xlsx;Defaultdir=|datadirectory|\;driverid=790;maxbuffersize=2048;pagetimeout=5"	0
25210001	25209757	How can I detect invalid JSON containing a trailing comma with c#?	if Regex.IsMatch(badJson, "^.*,\s*]\s*}$") \n   throw new Exception("hey that's bad json");	0
33834371	33834307	How to retrieve all values in dictionary	foreach (var term in termDocumentIncidenceMatrix)\n{\n    // Print the string (your key)\n    Console.WriteLine(term.Key);\n\n    // Print each int in the value\n    foreach (var i in term.Value)\n    {\n        Console.WriteLine(i);\n    }\n}	0
12628353	12591896	Disable WPF Window Focus	protected override void OnActivated(EventArgs e)\n    {\n        base.OnActivated(e);\n\n        //Set the window style to noactivate.\n        WindowInteropHelper helper = new WindowInteropHelper(this);\n        SetWindowLong(helper.Handle, GWL_EXSTYLE,\n            GetWindowLong(helper.Handle, GWL_EXSTYLE) | WS_EX_NOACTIVATE);\n    }   \n\n    private const int GWL_EXSTYLE = -20;\n    private const int WS_EX_NOACTIVATE = 0x08000000;\n\n    [DllImport("user32.dll")]\n    public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\n\n    [DllImport("user32.dll")]\n    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);	0
9693822	9693791	How to get size of set of certain files?	using System;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static void Main()\n    {\n        long size = Directory\n            .EnumerateFiles(@"c:\work", "*d.*")\n            .Select(x => new FileInfo(x))\n            .Sum(x => x.Length);\n        Console.WriteLine(@"The size of files in c:\work\*d.* is {0} bytes", size);\n    }\n}	0
21342471	21342457	C# Check if any int in list matches any int in another list	bool isAnyItemInBothLists = list1.Intersect(list2).Any();	0
2941944	2941899	How do I initialize a fixed byte array?	unsafe struct ...	0
19972985	19971143	How to get MemoEdit and Store in Access Database?	'Suppose you have 2 columns , A - a Memo one, B a DateTime one:\ndim SIRCON as string = "your connection string"\nUsing conn As New OleDbConnection(SIRCON)\n  conn.Open()\n  Try\n  Using cmd As New OleDbCommand("INSERT INTO MYTABLE (A, B)  VALUES (?,  ?)", conn)\n    cmd.Parameters.AddWithValue("P_A", textEdit12.Text.ToString())\n    cmd.Parameters.AddWithValue("P_B", DateEdit1.EditValue)\n\n    cmd.ExecuteNonQuery()\n  End Using\nFinally\n conn.Close()\nEnd Try	0
8135087	8121804	How to bind a dictionary to MSChart	public Form1()\n{\n    InitializeComponent();\n    InitialiseDictionary();\n    Series ser1 = new Series("My Series", 10);\n    chart1.Series.Add(ser1);\n    chart1.Series["My Series"].Points.DataBindXY(dict1.Keys, dict1.Values);\n}	0
2574198	2213541	Vietnamese character in .NET Console Application (UTF-8)	class Program\n{\n    [DllImport("kernel32.dll")]\n    static extern bool SetConsoleOutputCP(uint wCodePageID);\n\n    static void Main(string[] args)\n    {\n        SetConsoleOutputCP(65001);\n        Console.OutputEncoding = Encoding.UTF8;\n        Console.WriteLine("t?st, ????, ????, ????????????, B?i vi?t ch?n l?c");\n        Console.ReadLine();\n    }\n}	0
8508958	8508865	Can I set a C# preprocessor directive from a central file?	/define	0
16379649	16379469	Get PDF page from SWF Offer Avis	WebClient wb = new WebClient();\n        var data = new NameValueCollection();\n        data["publicationID"] = "6dce3366"; //Netto ID\n        data["selectedPages"] = "all";\n\n\n        byte[] responsebytes = wb.UploadValues("http://viewer.zmags.com/services/DownloadPDF", "POST", data);\n        System.IO.File.WriteAllBytes(@"C:\Tilbudsavis.pdf", responsebytes);	0
921267	921251	Method to count all items in Hierachical object list	public class MyClass\n{\n    public List<MyClass> SubEntries { get; set; }\n\n    public int SubEntryCount\n    {\n        get { return 1 + SubEntries.Sum(x => x.SubEntryCount); }\n    }\n}	0
23558179	22930420	window size sometimes changed while rotating the surface	Microsoft.Win32.SystemEvents.DisplaySettingsChanging	0
18137401	18137064	Bind DropDownList to a collection in a collection of Objects	dropDownList.DataSource = myObjectList\n    .Select(item => new { Title = item.Properties["Title"] })\n    .ToList();\ndropDownList.DataValueField = "Title";	0
15015277	14905274	How to programmatically access Public Recorded TV?	string PublicRecordedTV = Path.Combine(new DirectoryInfo(\n  Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)\n).Parent.FullName, "Recorded TV");	0
4140802	4140723	How to remove new line characters from a string?	string replacement = Regex.Replace(s, @"\t|\n|\r", "");	0
7726831	7726714	Trim all string properties	var stringProperties = obj.GetType().GetProperties()\n                          .Where(p => p.PropertyType == typeof (string));\n\nforeach (var stringProperty in stringProperties)\n{\n    string currentValue = (string) stringProperty.GetValue(obj, null);\n    stringProperty.SetValue(obj, currentValue.Trim(), null) ;\n}	0
21272150	21272033	Different models taking data from different tables from the same database ASP.NET MVC 4	public class ApplicationDBContext : DbContext\n{\n    public DbSet<Movie> Movies { get; set; }\n    public DBSet<Actor> Actors { get; set; }\n}	0
13596027	13596000	String.format has no effect	docStrXml = String.Format(docStrXml, newVersion.ToString(), oldVersion.ToString());	0
11586902	11586769	How to make a selected path to save an XML file?	saveFile.InitialDirectory = "C:\\MyXMLs\\";	0
7849316	3366673	ASP - Prompt save file dialog from streamwriter	String FileName = filename;\nString FilePath = filepath;\nSystem.Web.HttpResponse response = System.Web.HttpContext.Current.Response;\nresponse.ClearContent();\nresponse.Clear();\nresponse.ContentType = "text/plain";\nresponse.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");\nresponse.TransmitFile(FilePath + FileName);\nresponse.Flush();\nresponse.End();	0
33502131	33501796	Creating a Extension Method for a DataGrid => AutoScroll?	if (dataGrid.Items.Count > 0)\n        {\n            var border = VisualTreeHelper.GetChild(dataGrid, childIndex: 0) as ScrollViewer;\n            if (border != null)\n            {\n                border.ScrollToEnd();\n            }\n        }	0
1357331	1357308	How can I close the browser from an XBAP?	using System.Windows.Interop;\nusing System.Runtime.InteropServices;\n\n[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto)]\nprivate static extern IntPtr GetAncestor(IntPtr hwnd, int flags);\n\n[DllImport("user32", CharSet = CharSet.Auto)]\nprivate static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n\nprivate void button1_Click(object sender, RoutedEventArgs e)\n{\n       WindowInteropHelper wih = new WindowInteropHelper(Application.Current.MainWindow);\n       IntPtr ieHwnd = GetAncestor(wih.Handle, 2);\n       PostMessage(ieHwnd, 0x10, IntPtr.Zero, IntPtr.Zero);      \n}	0
17870996	17870854	The string was not recognized as a valid DateTime (Formating)	DateTime dt = DateTime.ParseExact(dr["category"].ToString().Trim(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);	0
5000143	5000129	how to make gridview empty	yourGridViewId.DataSource = null;\nyourGridViewId.Databind();	0
32544275	32544114	How do i check the number of time i clicked against List size?	files.RemoveAt(i);	0
19340055	19339986	How to write a program that finds the greatest and smallest fractions?	List<double> finals = new List<double> { };	0
5926894	5924342	Create a single delegate for all objects instead of one delegate per object	class Poolable\n{\n    public virtual void Free() { }\n    public virtual void OnFree() { }  // naming not according to BCL std\n}\n\nclass Light : Poolable\n{\n    public override void Free() { }\n    ...\n}	0
30734859	30669384	Background thread in Windows Phone 8.1 app	System.Threading.Timer myTimer = new System.Threading.Timer(async (state) => { if (UserLoggedIn) await Task.Delay(1000); }, null, 0, 5 * 1000);	0
18082879	18082756	How to insert images into image array in visual studio?	public sealed partial class MainPage : Page\n{\n   Image[] imgs;\n   public MainPage()\n   {\n      imgs = new Image[] { img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12, img13, img14};\n   }\n }	0
13862984	13660175	Access to custom field in user registration wizard	(TextBox)RegisterUser.WizardSteps[0].FindControl("CreateUserStepContainer").FindControl("LastName");	0
24105710	24098843	Change Access report RecordSource and then OutputTo PDF from C#	accessApp.DoCmd.OpenReport(\n        "Report1", \n        Microsoft.Office.Interop.Access.AcView.acViewDesign);\n\nMicrosoft.Office.Interop.Access.Report rpt = accessApp.Reports["Report1"];\nrpt.RecordSource = "SELECT * FROM Clients WHERE ID<=3";\n\naccessApp.DoCmd.OutputTo(\n        Microsoft.Office.Interop.Access.AcOutputObjectType.acOutputReport,\n        "",\n        "PDF Format (*.pdf)",\n        @"C:\Users\Gord\Desktop\zzzTest.pdf",\n        false,\n        null,\n        null,\n        Microsoft.Office.Interop.Access.AcExportQuality.acExportQualityPrint);\n\n// now close the report without saving the change to the RecordSource property\naccessApp.DoCmd.Close(\n        Microsoft.Office.Interop.Access.AcObjectType.acReport,\n        "Report1",\n        Microsoft.Office.Interop.Access.AcCloseSave.acSaveNo);	0
6822763	6822706	How to properly replace objects in an array - C#	int index = 5;\narray[index] = new Foobar(); // whatever your class is	0
27982138	27982037	Multiple BackGroundWorker components in a single Windows Form C#	private object threadUnsafeObject;\n    private object locker = new object();\n\n    private void RunMulitpleThread()\n    {\n        object pass_your_parameter_here = "";\n        for (int iCount = 0; iCount < 5; iCount++)\n        {\n            System.Threading.Thread thread = new System.Threading.Thread(DoWork);\n            thread.Start(pass_your_parameter_here);\n\n        }\n    }\n\n    private void DoWork(object parameters)\n    {\n        lock (locker)\n        {\n            threadUnsafeObject = parameters;\n        }\n    }	0
23802091	23801965	Replace particular occurence of a word in string	static void Main(string[] args)\n    {\n        string test = "word1 word1 word1 word1";\n        Console.WriteLine(test);\n        // Replace words\n        test = ReplaceWords(test, "word1", "test");\n        Console.WriteLine(test);\n        Console.ReadLine();\n    }\n\n    static string ReplaceWords(string input, string word, string replaceWith)\n    {\n        // Replace first word\n        int firstIndex = input.IndexOf(word);\n        input = input.Remove(firstIndex, word.Length);\n        input = input.Insert(firstIndex, replaceWith);\n\n        // Replace last word\n        int lastIndex = input.LastIndexOf(word);\n        input = input.Remove(lastIndex, word.Length);\n        input = input.Insert(lastIndex, replaceWith);\n\n        return input;\n    }	0
19138816	19138695	How to select Sum of values of list inside another list	Account accountObj = new Account();\nvar result = accountObj.AccountRecords\n                       .SelectMany(r => r.AccountValues)\n                       .GroupBy(r => r.ID)\n                       .Select(grp => new\n                       {\n                           ID = grp.Key,\n                           Sum = grp.Sum(t => t.value)\n                       });	0
629190	629178	Conversion from List<T> to array T[]	MyClass[] myArray = list.ToArray();	0
21185057	21184935	How to save string in a cookie?	if(Request.Cookies["Location"] != null)\n      {\n           ltlLocation.Text = Request.Cookies["Location"].Value;\n      }	0
10021035	10020872	Dynamically create a c# generic type with self referenced constraints	AssemblyName assemblyName = new AssemblyName("TestAssembly");\nAssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);\n\nModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);\n\nTypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public);\n\nType entityType = typeof(Entity<>).MakeGenericType(typeBuilder);\n\ntypeBuilder.SetParent(entityType);\n\n\nType t = typeBuilder.CreateType();	0
4418510	4418279	Regex remove special characters	public static string RemoveSpecialCharacters(string input)\n{\n    Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);\n    return r.Replace(input, String.Empty);\n}	0
16061860	16061724	How to Exclude protected Operating system files in search	var list = new DirectoryInfo(@"C:\").GetFiles()\n                .Where(f => !f.Attributes.HasFlag(FileAttributes.System))\n                .Select(f => f.FullName)\n                .ToList();	0
6027364	6027251	Get data from RowCommand	protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n    if (e.CommandName == "Edit")\n    {\n        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);\n        // row contains current Clicked Gridview Row\n        String VersionId = row.Cells[CellIndex].Text;\n        .............\n        .............\n        //e.CommandArgument  -- this return Data Key Value\n    }\n}	0
1601145	1601099	Discard Chars After Space In C# String	string result = Regex.Match(TrimMe, "^[^ ]+").Value;\n// or\nstring result = new string(TrimMe.TakeWhile(c => c != ' ').ToArray());	0
32112327	32112113	how to pass textbox value to @"somestring"	string htmlPage = @"<div class=" + "\"wecome\"" + " id=" + "\"about\"" + ">" +\n                       "<h3>Welcome " + TexName.Text + "</h3>" +\n                     "</div>";	0
7071436	7071363	Imgur ID match using Regex in ASP.NET C#	Regex imgurRegex=new Regex(@"http://(?:i\.imgur\.com/(?<id>.*?)\.(?:jpg|png|gif)|imgur\.com/(?:gallery/)?(?<id>.*))$");\nMatch imgurMatch = imgurRegex.Match(URL);\nif(imgurMatch.Success)\n   id = imgurMatch.Groups["id"].Value	0
8911078	8910422	How to set checked to false if check state is indeterminate	bool reallyChecked = checkBox1.CheckState == CheckState.Checked;	0
3068248	3061741	MEF: Satisfy part on an Export using and Export from the composed part	public class Client\n{\n    [Export("PluginDelegate")]\n    IPlugin GetPlugin()\n    {\n        return new SamplePlugin();\n    }\n\n    [Import]\n    public INotificationService NotificationService { get; set; }\n}\n\n[PartCreationPolicy(CreationPolicy.NonShared)]\npublic class ClientNotificationService : INotificationService\n{\n    [Import("PluginDelegate")] Func<IPlugin> PluginDelegate;\n}	0
3617755	3617482	Access Javascript function on Default.aspx from web Control	OnClientClick="return ShowAvailability()"	0
22554264	22554135	Iterate array in c#	string[,] op1 = new string[9, 9];\nstring[,] op2 = new string[9, 9];\nstring[,] op3 = new string[9, 9];\n\nforeach (var item in new[] { op1, op2, op3 })\n{\n     //...\n}	0
33500422	33497716	Create array of images from array of objects in WCF web service	string firstText = "Hello";\nstring secondText = "World";\n\nPointF firstLocation = new PointF(10f, 10f);\nPointF secondLocation = new PointF(10f, 50f);\n\nstring imageFilePath = @"path\picture.bmp"\nBitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file\n\nusing(Graphics graphics = Graphics.FromImage(bitmap))\n{\n   using (Font arialFont =  new Font("Arial", 10))\n   {\n       graphics.DrawString(firstText, arialFont,Brushes.Blue,firstLocation);\n       graphics.DrawString(secondText,arialFont,Brushes.Red,secondLocation);\n    }\n}\n\nbitmap.Save(imageFilePath);//save the image	0
32639935	32638766	Can ServiceStack do a query by System.DateTime value?	var byDate = request.ByDate.Value.Date;                \norders = Db.Select<Order>(order => order.OrderDate == byDate);	0
32239278	32239100	How to add a pause between executing tasks in C#	using (var fs = new FileStream("C:\\test.txt", FileMode.Open, FileAccess.Read))\n{\n    using (var sr = new StreamReader(fs))\n    {\n        int nRead = 0;\n        while (nRead < settings.Total)\n        {\n            for (int i = 0; i < settings.ReadLimit && nRead < settings.Total; ++i, nRead++)\n            {\n                Console.WriteLine(sr.ReadLine());\n                if (i + 1 < settings.ReadLimit)\n                {\n                    Thread.Sleep(settings.Delay * 1000);\n                }\n            }\n            if (nRead < settings.Total)\n            {\n                Thread.Sleep(settings.GlobalDelay * 1000);\n            }\n        }\n    }\n}	0
1709708	1709597	C# - get event from SetWindowText	protected override void WndProc(ref Message m)\n{\n    switch (m.Msg)\n    {\n        case WM SETWINDOWTEXT:\n            // Custom code here\n            break;\n    }\n    base.WndProc(ref m);\n}	0
9219056	9203478	DigestValue in XMLSignature in Java is different from C#	TransformerFactory transfac = TransformerFactory.newInstance();\n            Transformer trans = transfac.newTransformer();\n\n\n            //CREAR STRING DEL ARBOL XML\n            StringWriter sw = new StringWriter();\n            StreamResult result = new StreamResult(sw);\n            DOMSource source = new DOMSource(doc);\n            trans.transform(source, result);\n            String xmlString = sw.toString();\n            System.out.println(xmlString);\n\n            dbfac = DocumentBuilderFactory.newInstance();\n            dbfac.setNamespaceAware(true);\n            doc = dbfac.newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));	0
11982258	11949901	Logon failed. Details: 28000:[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'user'	public ReportClass ConfigureReportClass(string strReportPath, object[] objParameters)\n    {\n        ReportClass rptH = new ReportClass();\n        rptH.FileName = strReportPath;\n        int Count = 0;\n        rptH.Load();\n        rptH.SetDatabaseLogon("myusername", "mypassword");\n        try\n        {\n            if (objParameters == null)\n                return rptH;\n            foreach (object obj in objParameters)\n            {\n                ParameterField param = rptH.ParameterFields[Count++];  // first param \n                param.AllowCustomValues = true;\n                ParameterDiscreteValue Disparam = new ParameterDiscreteValue();\n                Disparam.Value = obj;\n                param.CurrentValues.Add(Disparam);\n            }\n        }\n        catch (Exception ex)\n        {\n            throw ex;\n        }\n        return rptH;\n    }	0
4021540	4021437	How to replace value in string array	List<string> list = new List<string>();\n list.Add("AA");\n list.Add("BB");\n list.Add("CC");\n list.Add("DD");\n list.Add("EE");\n list.Add("FF");\n list.Add("GG");\n list.Add("HH");\n list.Add("II");\n\n MessageBox.Show(list.Count.ToString());\n list.Remove("CC");\n MessageBox.Show(list.Count.ToString());	0
1143690	1143664	assign an enum value to an enum based on a condition in c#	public enum FileType { None, ReadOnly, ReadWrite, System}\n\nFileType myFileType = FileType.None;\n\nif( //check if file is readonly)\n    myFileType = FileType.ReadOnly;	0
13590392	13590154	Stop Threads created with ThreadPool.QueueUserWorkItem that have a specific task	for (int i = 0; i < 100; i++)\n{\n    ThreadPool.QueueUserWorkItem(s =>\n    {\n        Console.WriteLine("Output");\n        Thread.Sleep(1000);\n    });\n}\n\nCancellationTokenSource cts = new CancellationTokenSource();\n\nfor (int i = 0; i < 100; i++)\n{\n    ThreadPool.QueueUserWorkItem(s =>\n    {\n        CancellationToken token = (CancellationToken) s;\n        if (token.IsCancellationRequested)\n            return;\n        Console.WriteLine("Output2");\n        token.WaitHandle.WaitOne(1000);\n    }, cts.Token);\n}\n\ncts.Cancel();	0
21822927	21822573	EF: Restriction on data types mapping	[RegularExpression(@"^\d+$",ErrorMessage="the value entered on ID's field must be integer")]\npublic int MyInt { get; set; }	0
31708640	31708340	LINQ - How to Group By with Dictionary <string, string[]>?	Dictionary<string, string[]> dic = new Dictionary<string,string[]>(){\n            {"A", new string [] {"1", "2", "$", "3", "4"}},\n            {"B", new string [] {"5", "6", "$", "7", "8"}},\n            {"C", new string [] {"9", "10", "@", "11", "12"}}\n        };\n\nvar res = dic.Select(p => new KeyValuePair<string, string[]>(\n                              p.Value[2], \n                              p.Value.Select((v,i) => i == 2 ? p.Key : v).ToArray()))\n             .GroupBy(p => p.Key)\n             .ToDictionary(g => g.Key, g => g.Select(p => p.Value).ToList());	0
3684000	3683938	Pass through XML from another website	string sURL = ".....";\n// Create a request for the URL. \nWebRequest oRequest = WebRequest.Create(sUrl);\n// Get the response.\nWebResponse oResponse = oRequest.GetResponse();\n// Get the stream containing content returned by the server.\nStream oDataStream = oResponse.GetResponseStream();\n// Open the stream using a StreamReader for easy access.\nStreamReader oReader = new StreamReader(oDataStream, System.Text.Encoding.Default);\n// Read the content.\nstring sXML = oReader.ReadToEnd();\n// Convert string to XML\nXDocument oFeed = XDocument.Parse(sXML);	0
9264788	9264573	Writing case statements using LINQ (with GROUP BY)	var query = from link in db.Links\n            join host in db.Hosts on link.HostID equals host.ID\n            group link by host.Url into links\n            select new\n            {\n                Url = links.Url,\n                IntLinks  = links.Count(link => link.ExtFlag == 0),\n                IntBroken = links.Count(link => link.ExtFlag == 0 &&\n                                                link.ResponseCode >= 400),\n                ExtLinks =  links.Count(link => link.ExtFlag == 1),\n                ExtBroken = links.Count(link => link.ExtFlag == 1 &&\n                                                link.ResponseCode >= 400),\n            };	0
14200416	14199049	CollectionViewSource with Sort get sorted Items	// using System.Linq;\n\nvar list = collectionView.View.Cast<object>().ToList();\nvar firstItem = list[0];	0
15408711	15408667	Inherit from struct	public struct PersonName\n{\n    public PersonName(string first, string last)\n    {\n        First = first;\n        Last = last;\n    }\n\n    public string First;\n    public string Last;\n}\n\n// Error at compile time: Type 'PersonName' in interface list is not an interface\npublic struct AngryPersonName : PersonName\n{\n    public string AngryNickname;\n}	0
25415438	25346892	Web API - Self close tag instead of i:nil	[DataContract(Namespace = "")]\npublic class Status\n{\n    [DataMember]\n    public DateTime Date { get; set; }\n\n    [DataMember]\n    public int ID { get; set; }\n\n    [DataMember]\n    public string Option { get; set; }\n\n    private string value;\n\n    [DataMember]\n    public string Value\n    {\n        get { return this.value ?? ""; }\n        set { this.value = value; }\n    }\n}	0
3023019	3022852	How can I create a SQL table using excel columns?	System.Data.DataTable dt;\ndt = new System.Data.DataTable();\nforeach(System.Data.DataColumn col in dt.Columns)\n{\n     System.Diagnostics.Debug.WriteLine(col.ColumnName);\n}	0
2185187	2184751	Can I reassign from code an object declared as a resource in XAML?	public class MainWindow {\n\n...\n  void UpdateResource()\n  {\n     myDataInstance = (myData)serializer.Deserialize(fileStream);\n     this.Resources["myDataInstance"] = myDataInstance;\n  }   \n}	0
6503045	6496914	Data Loading Strategy/Syntax in EF4	var query = db.Leagues\n                      .Where(l => l.URLPart.Equals(leagueName))\n                      .Select(l => new \n                          {\n                              League = l,\n                              Events = l.LeagueEvents.Where(...)\n                                                     .OrderBy(...)\n                                                     .Take(3)\n                                                     .Select(e => e.Event)\n                              ... \n                          });	0
4475906	4475067	Problem creating correct path concatenating left to right with right to left sections	joinOutputString = string.Join("\\\x200E", joinOutputString, myStrings[i]);	0
20129854	20129794	C#: how to return a list of the names of all properties of an object?	var propNames = foo1.GetType()\n                    .GetProperties()\n                    .Select(pi => pi.Name)	0
1212362	1212330	Can I get any terser with lambdas?	return _schema.GetAll<Node>().Where(n => n.Type == NodeType.Unmanaged).Cast<Shape>();	0
3958266	3958145	Accessing Textbox selected value in c#	// Get selected character.\nint charIndex = textbox.SelectionStart;\n\n// Get line index from selected character.\nint lineIndex = textbox.GetLineFromCharIndex(charIndex);\n\n// Get line.\nstring line = textbox.Lines[lineIndex];	0
9098533	9098498	Get only the first value from XPathNavigator?	var node = navigator.SelectSingleNode("/bookstore/book/title");\n\nConsole.WriteLine(node);	0
16837824	16837771	C# ActionLink MVC4 - Pass multiple parameters to ActionResult	return false	0
20296437	20296377	C# parse XML in a predefined format	void Main()\n{\n    string file = "<AAA><BBB specName=\"A\" delimiters=\",\" commentChars=\"#\" titleLines=\"1\"><DDD name=\"SSS\" col=\"0\"/><EEE key=\"XXX\">model</EEE></BBB><CCC fName=\"Test\" specName=\"TestRange\">Bol</CCC></AAA>";\n    var doc = XDocument.Parse(file);\n\n    var a = doc.Element("AAA").Element("BBB").Attribute("specName").Value;\n    var b = doc.Element("AAA").Element("BBB").Element("EEE").Attribute("key").Value;\n    var c = doc.Element("AAA").Element("BBB").Element("EEE").Value;\n    var d = doc.Element("AAA").Element("CCC").Value;    \n\n\n    Console.WriteLine (a);\n    Console.WriteLine (b);\n    Console.WriteLine (c);\n    Console.WriteLine (d);\n}	0
17835037	17831875	Change axis values on Chart Winforms	chart1.ChartAreas[0].AxisY.CustomLabels.Add(-0.5, 0.5, "Success");\nchart1.ChartAreas[0].AxisY.CustomLabels.Add(0.5, 1.5, "Failure");	0
13608449	13608073	How do I capture the first character typed in a cell of a DataGridView with EditMode.EditProgrammatically?	protected override void OnKeyPress(KeyPressEventArgs e) {\n  if (!IsCurrentCellInEditMode) {\n    BeginEdit(true);\n    SendKeys.Send(e.KeyChar.ToString());\n  }\n  base.OnKeyPress(e);\n}	0
5184366	5183385	HtmlAgilityPack: Get whole HTML document as string	HtmlDocument doc = new HtmlDocument();\n// call one of the doc.LoadXXX() functions\nConsole.WriteLine(doc.DocumentNode.OuterHtml);	0
679837	679829	Firing event on application close	System.Windows.Forms.Application.ApplicationExit +=new System.EventHandler(this.shutdownHandler);	0
25323541	25323439	send datagridview item to another form	try {\n    if (e.ColumnIndex > -1 && e.RowIndex > -1)\n        new Form6(int.Parse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString())).Show();\n}\ncatch (Exception ex) {\n    MessageBox.Show("Error: " + ex.Message);\n}	0
21838110	21837984	Replace repeated char with something else in a string	var str = "abcdefgabfabc";\nvar chars = str.Select((c, index) =>\n        {\n            int count = str.Substring(0, index).Count(x => c == x);\n            if (count > 0) return c.ToString() + (count+1);\n            else return c.ToString();\n        }).SelectMany(c => c).ToArray();\nvar result = new string(chars); // abcdefga2b2f2a3b3c2	0
9541001	9535320	Amazon Marketplace XML parsing	xmlDoc = XDocument.Parse(sr.ReadToEnd());\n\nXNamespace ns = "w3.org/2001/XMLSchema-instance";\n\nvar query = from order in xmlDoc.Descendants(ns + "Order")\n            from orderItem in order.Elements(ns + "OrderItem")\n            select new\n            {        \n                amazonOrdeID = order.Element(ns + "AmazonOrderID").Value,\n                merchantOrderID = order.Element(ns + "MerchantOrderID ").Value,\n                orderStatus = order.Element(ns + "OrderStatus ").Value,\n                asin = orderItem.Element(ns + "ASIN").Value,\n                quantity = orderItem.Element(ns + "quantity").Value\n            };	0
3375818	3375716	Run JAR file with PSExec and CMD	psexec \\somemachine -i  /accepteula -i -u domain\user -p password  cmd /c "java -jar c:\mydir\myjar.jar [my jar args here]"	0
5187536	5187476	Press enter to click a LinkLabel	public class LinkLabelEx : LinkLabel\n{\n\n    protected override void OnKeyUp(KeyEventArgs e)\n    {\n        if (e.KeyCode == Keys.Enter)\n        {\n            e.SuppressKeyPress = true;\n            e.Handled = true;\n            OnLinkClicked(new LinkLabelLinkClickedEventArgs(new Link(0, this.Text.Length)));\n        }\n        else\n        {\n            base.OnKeyUp(e);\n        }\n    }\n\n}	0
11836411	11836354	How can you programmatically retrieve the number of pages in an Excel worksheet?	ActiveSheet.PageSetup.Pages.Count	0
9392048	8970807	C# Graphics DrawString VerticalDirection start from the bottom	Rectangle rec = new Rectangle();\nrec.Height = 2 * po.medF.Height;\nrec.Width=100;\nrec.X = 0;\nrec.Y = 0;\nSizeF s;\nString str = "your Text";\nStringFormat strf = new StringFormat();\nstrf.Alignment = StringAlignment.Center;    \nrec.X = 0;\nrec.Y = 0;\ne.Graphics.TranslateTransform(X1, Y1);\ne.Graphics.RotateTransform(90);\ne.Graphics.DrawString(str, po.medF, Brushes.Black, rec, strf);\ne.Graphics.ResetTransform();	0
16646554	16646431	Using LINQ to obtain dependencies of tasks stored in a table	from d in Sys_JobDependantTasks\nwhere d.TaskId == t.DependantTaskid\nselect d.TaskId	0
6296803	6296634	WPF Multiple ItemSources?	Command=?{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=CheckCommand}?	0
11375443	11375417	How can I use get to return a boolean from a C# class?	public bool UseRowKey { get { return RowKey.StartsWith("X"); }}	0
15512530	15510324	Minimized WinForms app restoring to Normal on second launch	protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {\n    //...\n    switch (command.ToLowerInvariant()) {\n        // etc..\n        default:\n            base.OnStartupNextInstance(e);   // Brings it to the front\n            System.Windows.Forms.MessageBox.Show("Argument not supported");\n            break;\n    }\n}	0
16979302	16979120	calling javascript function on OnClientClick event of a Submit button	//use this code in BUTTON  ==>   OnClientClick="return SomeMethod();"\n\n//and your function like this\n<script type="text/javascript">\n  function SomeMethod(){\n    // put your code here \n    return false;\n  }\n</script>	0
12261289	11958754	AsParallel crashing a MonoTouch app	var items = new object [] { 1, 2, 3 };\nvar twice = (\n    from x in items.AsParallel()\n    select 2 * x\n).ToArray();	0
8269205	8269168	How to calculate the number of years between 2 dates?	public bool CheckDate(DateTime date1, DateTime date2)\n{\n    return date1.AddYears(-18) < date2;\n}	0
8968331	8967735	LINQ with ManyToMany: Filtering based on multiple selection	var ids = new int[]{ ... }; \n// if ids is null or ids.Length == 0 please return null or an empty list, \n//do not go further otherwise you'll get Relays without any function filter\n\nvar query = Relays.AsQueryable(); \nforeach (var id in ids)    \n{\n     var tempId = id;\n     query = query.Where(r=>r.RelayConfigs.Any(rc=>rc.ProtFuncID == tempId)); \n}\nvar items  = query.ToList();	0
9281510	9281354	Use reflection to get all extended types with Serializableattriubte	var types = typeof(BaseClass).Assembly.GetTypes().Where(t =>\n    t.IsClass && t.BaseType == typeof(BaseClass)\n    && Attribute.IsDefined(t, typeof(SerializableAttribute))).ToArray();	0
5422780	5324370	save Datatable values as empty string instead of null	public static DataTable RemoveNulls(DataTable dt)\n    {\n        for (int a = 0; a < dt.Rows.Count; a++)\n        {\n            for (int i = 0; i < dt.Columns.Count; i++)\n            {\n                if (dt.Rows[a][i] == DBNull.Value)\n                {\n                    dt.Rows[a][i] = "";\n                }\n            }\n        }\n\n        return dt;\n    }	0
29413309	29413183	Pull all duplicate keys from list of key value pairs	List<KeyValuePair<int,DataDetailValues>> result = data.Where(x => x.Key == 1).ToList();	0
44579	44337	preferred way to implement visitor pattern in dynamic languages?	def accept(x)\n  send "accept#{x.class}".to_sym, x\nend	0
11914544	11914243	Convert timestamp(Datetime.ticks) from database to Datetime value before displaying it in DataGridView	resultDataTable.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));\nforeach (DataRow r in dt.Rows)\n{\n    r["DateTime"] = new DateTime(Convert.ToInt32(r["Timestamp"]);\n}\ndt.Columns.Remove("Timestamp");	0
10538433	10538185	Is there such a thing as a virtual keyboard component/library for Winforms?	//Simulate Shift\npublic void btn_Shift(object sender, EventArgs e)\n{\n   InputSimulator.SimulateKeyPress(VirtualKeyCode.SHIFT);\n}	0
15489103	15489000	Exposing common values from a custom structure/type	public static VideoFormat H264Format\n{\n   get{\n         // This if statement can be added in the future without breaking other programs.\n         if(SupportsNewerFormat)\n             return VideoFormat.H265;\n\n         return VideoFormat.H264;\n    }\n}	0
20758941	20753536	Check if the RadButton was clicked from code behind	Protected Sub btnAddNewPerson_Click(ByVal sender As Object, ByVal e as ButtonClickEventArgs) Handles butAddNewPerson.Click\n...your code here to open Rad Window\nEnd Sub	0
27725733	27694513	How to list users in all domains running code from a non-domain computer?	for(int i = 0; i < domains.Length; i++)\n        {\n            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domains[i], ?Login1?, ?pass1?))\n            {\n                using (UserPrincipal searchPrincipal = new UserPrincipal(pc))\n                {\n                     searchPrincipal.Name = "*";\n                     using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))\n                     {\n\n                            using (PrincipalSearchResult<Principal> principals = searcher.FindAll())\n                            {\n                                 foreach (UserPrincipal principal in principals)\n                                  {\n                                      Console.WriteLine(principal.Name);\n                                  }\n                            }\n                     }\n                }\n            }\n        }	0
1674657	1674575	How can I initialize a new string array from the values contained in a char array?	string[] arrStrings = Array.ConvertAll(arrChars, c => c.ToString());	0
21918116	21916988	How can I get underlying object for DbUpdateConcurrencyException.Entry	try \n{\n  item.Reload();\n  //TODO: re-process property on underlying object here\n}\ncatch (DbUpdateConcurrencyException ex) \n{\n  // process on ex.Entries[0].Entity or\n  // ex.Entries[0].Entity.OriginalValues\n  ((DataType)ex.Entries[0].Entity).Property = value;\n\n  // if your object context is still open, you could try to re-submit after trying the \n  // entity\n  ctx.Attach(ex.Entries[0].Entity);\n  ctx.SaveChanges();\n}	0
6145017	6144307	Use Facebook C# SDK to Search for Places	Dictionary<string,object> searchParams = new Dictionary<string,object>();  \nsearchParams.Add("q", "coffee");     \nsearchParams.Add("center", "37.76,-122.427");     \nsearchParams.Add("type", "place");     \nsearchParams.Add("distance", "1000");\n\nFacebookClient fbClient = new FacebookClient(token);\nvar searchedPlaces = fbClient.Get("/search", searchParams);	0
7212738	7036289	Access object properties from lists via asp .net object data source	this[int index]	0
5601796	5601679	How can I unit test that Windsor can resolve Asp.net MVC3 controller dependencies?	[TestMethod]\npublic void Windsor_Can_Resolve_HomeController_Dependencies()\n{\n    // Setup\n    WindsorContainer container = new WindsorContainer();\n    container.Install(FromAssembly.Containing<HomeController>());\n\n    // Act\n    HomeController controller = container.Resolve<HomeController>();\n}	0
9008700	8973771	How do i send an email when i already have it as a string?	MailBee.Mime.MailMessage message = new MailMessage();\n            message.LoadMessage(filestream);\n            MailBee.SmtpMail.Smtp.QuickSend(message);	0
20335283	20334883	updating a record in Access table	string str = \n        "UPDATE [MIX] SET " + \n        "[Stock quantity] = ?, " +\n        "[Retail price] = ?, " +\n        "[Original price] = ? " +\n        "WHERE [Brand name] = ?";\nOleDbCommand comd = new OleDbCommand(str, conn);\ncomd.Parameters.AddWithValue("?", comboBox1.Text);  // [Stock quantity]\ncomd.Parameters.AddWithValue("?", comboBox4.Text);  // [Retail price]\ncomd.Parameters.AddWithValue("?", comboBox5.Text);  // [Original price]\ncomd.Parameters.AddWithValue("?", comboBox3.Text);  // [Brand name]\ncomd.ExecuteNonQuery();	0
15089999	15083214	How to raise an event inside a UserControl to handle it outside, in another project?	private void UserControl1_Click(object sender, MouseEventArgs e)\n{\n    // Raise MouseClick event for this control\n    base.OnMouseClick(e);\n}	0
17749563	17749421	SqlCommand for Ior filling values to ComboBox from multiple columns	spojeni.Open();\nvar cb4 = new SqlCommand("SELECT cena1,cena2,cena3 FROM zajezd WHERE akce="+zakce.Text,spojeni);\n\n        SqlDataReader dr4 = cb4.ExecuteReader();\n        while (dr4.Read())\n        {\n            comboBox4.Items.Add(dr4["cena1"].ToString() + dr4["cena2"].ToString() + dr4["cena3"].ToString());\n\n\n        }\n        dr4.Close();\n        dr4.Dispose();	0
24457596	24457455	Get Type of Parameter from Generic Delegate functions	obj.GetType().GetGenericArguments().First();	0
6709532	6709502	C# Binary Array "{ 84, 01, 00, 00 }" changed to "54 01 00 00" in Windows Registry	0x54 == 84	0
11755728	9804401	how to use FileSystemWatcher to change cache data?	FileDependency cacheFileDependency = new FileDependency("\\mynetworkpath\abc.txt");\ncacheMgr.Add(cacheName, cacheValueList, \n             Microsoft.Practices.EnterpriseLibrary.Caching.CacheItemPriority.Normal,\n             null, cacheFileDependency);	0
9302802	9302749	LINQ to SQL GroupBy Max() lambda	var userIDs = new[] {14287, };\n\nvar results =\ndataContext.UserHistories\n.Where(user => userIDs.Contains(user.userID))\n.GroupBy(user => user.userID)\n.Select(\n     userGroup =>\n         new \n         {\n             UserID = userGroup.Key,\n             Created = userGroup.Max(user => user.Created),\n         });	0
32001184	31983561	Unit Tests, Build Configuration and Internals	[InternalsVisibleTo()]	0
15703977	15702031	get thumbnail image of video file in C#	public static Bitmap GetThumbnail(string video, string thumbnail)\n{\n    var cmd = "ffmpeg  -itsoffset -1  -i " + '"' + video + '"' + " -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 " + '"' + thumbnail + '"';\n\n    var startInfo = new ProcessStartInfo\n    {\n        WindowStyle = ProcessWindowStyle.Hidden,\n        FileName = "cmd.exe",\n        Arguments = "/C " + cmd\n    };\n\n    var process = new Process\n    {\n        StartInfo = startInfo\n    };\n\n    process.Start();\n    process.WaitForExit(5000);\n\n    return LoadImage(thumbnail);\n}\n\nstatic Bitmap LoadImage(string path)\n{\n    var ms = new MemoryStream(File.ReadAllBytes(path));\n    return (Bitmap)Image.FromStream(ms);\n}	0
6544654	6532426	how to validate textbox for NRIC	using System;\nusing System.Windows.Forms;\n\nnamespace ValidateSimple\n{\n  using System.Text.RegularExpressions;\n\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void ValidateButton_Click(object sender, EventArgs e)\n    {\n        string strRegex = @"^(S\d{7}[a-zA-Z])$";\n\n        Regex myRegex = new Regex(strRegex);\n\n        string strTargetString = textBox1.Text;\n        if (myRegex.IsMatch(strTargetString))\n        {\n            MessageBox.Show(@"The NRIC is correct!");\n        }\n        else\n        {\n            MessageBox.Show(@"The NRIC is incorrect!");\n\n        }\n\n    }\n  }\n}	0
3772811	3769879	OpenRasta return list via JsonDataContractCodec	namespace OpenRastaApp\n{\n    public class Configuration : IConfigurationSource\n    {\n        public void Configure()\n        {\n            using (OpenRastaConfiguration.Manual)\n            {\n                ResourceSpace.Has.ResourcesOfType<List<Foo>>()\n                    .AtUri("/foos")\n                    .HandledBy<FooHandler>()\n                    .AsJsonDataContract();\n                ResourceSpace.Has.ResourcesOfType<Foo>()\n                    .AtUri("/foos/{id}")\n                    .HandledBy<FooHandler>()\n                    .AsJsonDataContract();\n            }\n        }\n    }\n}	0
2003193	1977405	Microsoft Enterprise Logging Application Block - Reading Log File	FileStream fs = new FileStream(@"c:\trace.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);	0
30634118	30634097	c# datetime.parseexact string was not recognized as a valid datetime	DateTime date = DateTime.ParseExact("01/06/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture);	0
1434999	1434951	C# WPF App to read data from a pipe	class Program\n{\nstatic void Main(string[] args)\n{\nstring s;\nwhile ((s = Console.ReadLine()) != null)\n{\nConsole.WriteLine(s);\n}\n\n}\n}	0
16814317	16814232	Timer event to increase the value of a variable	private int myVar= 0;//private field which will be incremented\n\nvoid timer_Tick(object sender, EventArgs e)//event on timer.Tick\n{\n            myVar += 1;//1 or anything you want to increment on each tick.\n}	0
19288055	18847248	Add Control to PictureEdit	picEdit.CreateControl();	0
25851053	25850979	Configuring a WCF REST service as a client?	WebHttpBinding binding = new WebHttpBinding();\nbinding.MaxReceivedMessageSize = 2147483647;	0
25670808	25669447	code for subscribe a user to a list in mailchimp	MCApi mc = new MCApi(ConfigurationManager.AppSettings["MCAPIKey"], false);\n\nvar subscribeOptions = new Opt<List.SubscribeOptions>(new List.SubscribeOptions { SendWelcome = true, UpdateExisting = true });\nvar merges = new Opt<List.Merges>(new List.Merges { { "FNAME", [Subscriber FirstName here] }, { "LNAME", [Subscriber lastName here] } });\n\nif (mc.ListSubscribe(ConfigurationManager.AppSettings["MCListId"], [Subscriber email ], merges, subscribeOptions))\n    // The user is subscribed Do Something	0
31454539	31454300	I am making a visual C# winform application. I want to store data in it	public static void WriteSomeText(string text) \n{\n    string path = Path.Combine(AppDomain.BaseDirectory, "mytextfile.txt");\n    using (StreamWriter sw = File.CreateText(path)) \n    {\n        sw.WriteLine(text);\n    }\n}	0
19123385	19123305	How to get multiple selected items in listbox wpf?	foreach (var item in listBox1.SelectedItems)\n{\n\n}	0
15248839	15248622	How to filter links and pictures in tweets?	public static async Task<bool> IsUriImageAsync(Uri uri)\n{\n        try\n        {\n            System.Net.WebRequest wc = System.Net.WebRequest.Create(uri); \n            //masquerade as a browser\n            ((HttpWebRequest)wc).UserAgent = \n              "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19";\n            wc.Timeout = 1000;\n            wc.Method = "HEAD";\n            using(WebResponse res = await wc.GetResponseAsync())\n            {\n                return \n                  res.ContentType\n                   .StartsWith("image/",StringComparison.InvariantCulture);\n            }\n\n\n        }\n        catch (Exception ex)\n        {\n            return false;\n        }   \n}	0
7790378	7790344	efficient remove of row from dataset linked to SQL database	var itemsToBeRemoved = listingDataTable.Where(x=>x.stock == key).ToList();\nforeach (var item in itemsToBeRemoved) \n              listingDataTable.RemoveListingRow(item);	0
7438929	7438273	Return the location data from GeoCoordinateWatcher.StatusChanged event in Windows Phone 7	private void GeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)\n{\n    var currentLatitude = e.Position.Location.Latitude;\n    var currentLongitude = e.Position.Location.Longitude;\n}	0
2631841	2631731	How do I search for a string with quotes?	string biocompany = "Santarus Inc???";\nstring html_string = "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=" + biocompany;\nusing (WebClient client = new WebClient())\n{\n    string html = client.DownloadString(html_string);\n    int d = html.IndexOf(@"<!--m--><li class=""g w0""><h3 class=r>");\n    Console.WriteLine(d);\n}	0
26388529	26388481	extract information from a dictionary	if (myDictionary.ContainsKey(myKey))\n{\n    var theValue = myDictionary[myKey].SomeProperty\n}	0
31042762	31042541	How can I make this SQL query work in LINQ lambda expression	from x in table1\nwhere !(from y in table2 select y.Deptno).Distinct().Contains(x.Deptno)\nselect x	0
20241289	20240936	GetFiles() - Search pattern	FileInfo[] files = nodeDirInfo.GetFiles("*", SearchOption.TopDirectoryOnly).\n            Where(f=>f.Extension==".sbs").ToArray<FileInfo>();	0
2988158	2988106	Enumerable Contains Enumerable	public IEnumerable<Post> GetPostsWithTags(IEnumerable<string> tags)\n{\n  return posts.Where(post => tags.All(tag => post.Tags.Contains(tag)));\n}	0
19121408	19121081	Read matching records from hashtable into class object	Dictionary<string, string> studentTeachers = new Dictionary<string, string>();\nstudentTeachers.Add("Student #1", "Instructor #1");\nstudentTeachers.Add("Student #2", "Instructor #1");\nstudentTeachers.Add("Student #3", "Instructor #1");\nstudentTeachers.Add("Student #4", "Instructor #1");\nstudentTeachers.Add("Student #5", "Instructor #2");\nstudentTeachers.Add("Student #6", "Instructor #2");\nstudentTeachers.Add("Student #7", "Instructor #2");\nstudentTeachers.Add("Student #8", "Instructor #2");\n\nvar instructors = new List<ClassInstructor>();\n\ninstructors.Add(new ClassInstructor() { InstructorID = 1, InstructorName = "Instructor #1" });\ninstructors.Add(new ClassInstructor() { InstructorID = 2, InstructorName = "Instructor #2" });\n\nforeach (var instructor in instructors)\n    instructor.Students = studentTeachers.Where(x => x.Value == instructor.InstructorName).Select(x => x.Key).ToList();	0
16573325	16524609	Combine Sliding and Absolute Expiration	object data = new object();\n        string key = "UniqueIDOfDataObject";\n        //Insert empty cache item with absolute timeout\n        string[] absKey = { "Absolute" + key };\n        MemoryCache.Default.Add("Absolute" + key, new object(), DateTimeOffset.Now.AddMinutes(10));\n\n        //Create a CacheEntryChangeMonitor link to absolute timeout cache item\n        CacheEntryChangeMonitor monitor = MemoryCache.Default.CreateCacheEntryChangeMonitor(absKey);\n\n        //Insert data cache item with sliding timeout using changeMonitors\n        CacheItemPolicy itemPolicy = new CacheItemPolicy();\n        itemPolicy.ChangeMonitors.Add(monitor);\n        itemPolicy.SlidingExpiration = new TimeSpan(0, 60, 0);\n        MemoryCache.Default.Add(key, data, itemPolicy, null);	0
33792853	33792200	Regular expression in C# parsing RegexOptions	string flags = "/x/i/m";\n\n            RegexOptions regExOpts = RegexOptions.None;\n\n            if (flags.Contains('x')) {\n                regExOpts |= RegexOptions.Multiline;\n            }\n\n            if (flags.Contains('i')) {\n                regExOpts |= RegexOptions.IgnoreCase;\n            }\n\n            if (flags.Contains('s')) {\n                regExOpts |= RegexOptions.Singleline;\n            }\n\n            if (flags.Contains('m')) {\n                 regExOpts |= RegexOptions.ExplicitCapture;\n            }\n\n            MessageBox.Show(regExOpts.ToString());	0
22854729	22854337	Get Entity Model from stored procedure?	"NamespaceName.TypeName,AssemblyName"	0
2525055	2524253	Append XML File	XDocument document = XDocument.Parse(xml);\n    XElement element = XElement.Parse(xmlToAdd);\n\n    document.Root.Element("Section").Add(element);	0
16823932	16820731	Parsing String to DateTime with TryParseExact in C#	public override bool IsValid(DateTime value)\n{\n    DateTime today = DateTime.Today;\n    int age = today.Year - value.Year;\n    if (value > today.AddYears(-age)) age--;\n\n    if (age < 18)\n    {\n        return false;\n    }\n\n    return true;\n}\n\npublic override bool IsValid(string value)\n{\n    string format = "dd/MM/yyyy HH:mm:ss";\n    DateTime dt;\n    if (DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))\n    {\n        return IsValid(dt);\n    }\n    else\n    {\n        return false;\n    }\n\n}\n\npublic override bool IsValid(object value)\n{\n    return IsValid(value.ToString());   \n}	0
28042179	28042008	Deleting an item in ListView from a file C#	private void button3_Click(object sender, EventArgs e) {\n  var toDelete = listView1.SelectedItems.ToList();\n\n  foreach(var item in toDelete) {\n    listView1.Items.Remove(item);\n    File.Delete(path + "//Lyrics//" + item.Text + ".txt");\n  } \n}	0
14165641	14058878	GeckoFX: Cast GeckoNode to GeckoHTMLElement	GeckoNode node = geckoWebBrowser.Document.GetElementsByClassName("button")[0].FirstChild;\nif (NodeType.Element == node.NodeType)\n{\n  GeckoElement element = (GeckoElement)node;\n  element.Click();\n}\nelse\n{\n // Even though GetElementByClassName return type could contain non elements, I don't think\n // it ever would in reality.\n Console.WriteLine("First node is a {0} not an element.", node.NodeType);\n}	0
27719082	27718097	How to convert JavaScript(UnityScript) to C# and implement a low pass filter?	Vector3.Lerp()	0
16119452	16115554	EntityFramework 6 Connection Closed	db.Database.Connection.Open();	0
6962656	6962615	How can I align a form that has been generated by MVC3 Html Helper methods?	.editor-label {\n     clear:both;\n}\n\neditor-label label {\n    float:left;\n    width:150px\n}\n\neditor-label input {\n    float:left;\n}	0
10964645	10964260	How do I put a guard property in this code?	public class StudentViewModel: PropertyChangedBase\n{\n    public StudentModel Student { get; set; }\n\n    public void SaveStudent()\n    {\n        MessageBox.Show(String.Format("Saved: {0} - ({1})", Student.FirstName, Student.GradePoint));\n    }\n\n    public StudentViewModel()\n    {\n        Student = new StudentModel { FirstName = "Tom Johnson", GradePoint = 3.7 };\n        Student.PropertyChanged += delegate { NotifyOfPropertyChanged( () => CanSaveStudent)};\n    }\n\n    public Boolean CanSaveStudent\n    {\n        get \n        {\n            return Student.GradePoint >= 0.0 || Student.GradePoint <= 4.0;\n        }\n    }\n}	0
2991031	2990964	Is it possible to add an attribute to HtmlTextWriter WriteBreak	writer.WriteBeginTag("br");\nwriter.WriteAttribute("class", "className");\nwriter.Write(HtmlTextWriter.SelfClosingTagEnd);	0
6674589	6674555	Export gridview data into CSV file	protected void btnExportCSV_Click(object sender, EventArgs e)\n{\n    Response.Clear();\n    Response.Buffer = true;\n    Response.AddHeader("content-disposition",\n     "attachment;filename=GridViewExport.csv");\n    Response.Charset = "";\n    Response.ContentType = "application/text";\n\n    GridView1.AllowPaging = false;\n    GridView1.DataBind();\n\n    StringBuilder sb = new StringBuilder();\n    for (int k = 0; k < GridView1.Columns.Count; k++)\n    {\n        //add separator\n        sb.Append(GridView1.Columns[k].HeaderText + ',');\n    }\n    //append new line\n    sb.Append("\r\n");\n    for (int i = 0; i < GridView1.Rows.Count; i++)\n    {\n        for (int k = 0; k < GridView1.Columns.Count; k++)\n        {\n            //add separator\n            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');\n        }\n        //append new line\n        sb.Append("\r\n");\n    }\n    Response.Output.Write(sb.ToString());\n    Response.Flush();\n    Response.End();\n}	0
11719243	11719001	Linq To XML: Find XElement by name in XML and get parent attribute	XApplication[] appList = (from xapp in applicationXml.Elements("category").Elements("app")\n                           where xapp.Element("name").Value.ToLower().Contains(txtSearch.Text.ToLower())\n                           select new XApplication\n                           {\n                                Name = xapp.Element("name").Value,\n                                Category = xapp.Parent.Attribute("cat").Value\n\n                           }).ToArray();	0
10071008	10060826	How to plot a chart with both primary and secondary axis in c#	ChartArea chartarea = new ChartArea();\n\nSeries Memory = new Series();\n\nRepeatsMemoryPlot.Series.Add(Memory);\n\n//Add points to series Memory\n\nMemory.Points.AddXY(a, b);\n\nSeries Time = new Series();\n\nRepeatsMemoryPlot.Series.Add(Time);\n\nTime.ChartArea = Memory.ChartArea;\n\nTime.YAxisType = AxisType.Secondary;\n\n\n//Add Points to time series\nTime.Points.AddXY(a, b);	0
7499978	7499914	Outlook Flagging and make E-mail Important Using C#	oMsg.Importance = Outlook.OlImportance.olImportanceHigh; \n\noMsg.Importance = Outlook.OlImportance.olImportanceNormal;\n\noMsg.Importance = Outlook.OlImportance.olImportanceLow;	0
1397786	1397394	How linq 2 sql is translated to TSQL	var companyData =\n    from c in db.Companies\n    where c.Name.StartsWith("Roy")\n    select new { c.ID, c.Name, c.Location };\n\nvar companies =\n    from c in companyData.AsEnumerable()\n    select new Company(c.ID, c.Name, c.Location);	0
8563878	8563828	VBA : Changing Windows 7 Default Printer temporarily	public void DoPrint()\n{\n    var printDialog = new PrintDialog();\n    if (printDialog.ShowDialog() == DialogResult.OK)\n    {\n        var printDocument = new PrintDocument\n            {\n                DefaultPageSettings = { PrinterSettings = printDialog.PrinterSettings }\n            };\n        printDocument.PrintPage += OnPrintPage;\n    }\n}\n\nprivate void OnPrintPage(object sender, PrintPageEventArgs e)\n{\n    e.Graphics.DrawString("Hello");\n}	0
19610283	19610198	Entity Framework DbEntityEntry> 'Does not contain a definition for Where	using System.Linq	0
5418982	5418938	How to Convert system.windows.controls.image to byte[]	public byte[] imageToByteArray(System.Drawing.Image imageIn)\n{\n MemoryStream ms = new MemoryStream();\n imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);\n return  ms.ToArray();\n}	0
17895519	17895493	How to correct this bug of href in asp.net	protected string GetHRef()\n{\n   string ret = "";\n   ret = Eval("Id", "Play.aspx?lfs=Workout&Id={0}");      \n   return ret;\n}	0
7171581	7171306	SQLCE: How to join tables from different SQLCE databases programmatically in C#?	var q = from c in db1Context.personList\n\n        join p in db2Context.personAttendances on c.personID equals p.seenPersonID\n\n        select new { Category = c, p.ProductName };	0
13867884	13867259	Show current search paths for a view	var searchedLocations = ViewEngines.Engines.[0]\n    .FindPartialView(this.ControllerContext, "MyModel", false)\n    .SearchedLocations\n    .ToArray();	0
1612865	1612826	fastest algorithm to get average change	total change = difference between time on last day and time on first day\n average change = total change / number of days	0
9585516	9585363	How to reset custom Performance Counter	public void Reset()\n{\n    perfCounter.RawValue = 0;\n}	0
7274877	6697333	Open Source library / tool for converting PDF to HTML?	Public Shared Function GetTextFromPDF(PdfFileName As String) As String\n    Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)\n\n    Dim sOut = ""\n\n    For i = 1 To oReader.NumberOfPages\n        Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy\n\n        sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)\n    Next\n\n    Return sOut\nEnd Function	0
18305394	18305337	How to initiate class with interface if you only know the class name in string	public int CalcUsing(IClass myClass, int x)\n{\n     int result = myclass.Calculate(x);\n     return result;\n}\n\nclass SomeClass : IClass\n{\n     //Implement the Calculate(int) method here\n}\n\n//Then the user of your class can do this with an instance of your form due to \n//SomeClass inheriting the IClass type\nMainForm.CalcUsing(new SomeClass(), x);	0
14165557	14165543	Unable to Delete Folder Containing Invisible Files	Directory.Delete(parentFolderPath, true);	0
14155334	14155311	How to continue application when its getting error 404 or timeout	public static string getSourceCode(string url)\n{\n       string sourceCode = string.Empty;\n       try\n       { \n        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);\n        req.ContentType = "text/html; charset=ISO-8859-15";\n        //ERROR in here 404 or timeout\n        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n        StreamReader sr = new StreamReader(resp.GetResponseStream()); \n        sourceCode = sr.ReadToEnd();\n        sr.Close();\n        resp.Close();\n\n      }\n      catch(Exception ex){}\n      return sourceCode;\n}	0
286999	286964	How do I "cut" out part of a string with a regex?	Regex regex = new Regex( @"\d+" );\n        MatchCollection matches = regex.Matches( "changed from 1 to 10" );\n        int num1 = int.Parse( matches[0].Value );\n        int num2 = int.Parse( matches[1].Value );	0
18827920	18827863	How to call reflection method	Assembly asm = Assembly.Load("Test");\nType t = asm.GetType("test.myclass");\ndynamic obj = Activator.CreateInstance(t);\nConsole.WriteLine("output {0}", obj.Foo(10, 70));	0
22607310	22606963	How to read an xml and write it back when you understand only part of its structuer	String FileContent = null;\nusing (StreamReader streamReader = new StreamReader(@"TheFile.xml"))\n{\n    FileContent = streamReader.ReadToEnd();\n}\nXmlDocument Doc = new XmlDocument();\nDoc.LoadXml(FileContent);	0
18010158	18010022	Adding scrolling to text C#	textBox1.ScrollBars = ScrollBars.Vertical;	0
23968126	23968072	Single responsibility principle confusion	using (IModemConnection modemConnection = new IsdnModem())\n{\n    IModemDataExchange dataExchange = modemConnection.Dial("123456")\n    dataExchange.Send("Hello");\n}	0
15975707	15975664	Unable to compile a struct	public LimitfailureRecord(string sampleCode) : this()\n{\n    SampleCode = sampleCode;\n}	0
11248210	11248164	ComboBox Dropdown Appears Beneath Window	AllowTransparency=TRUE	0
18024655	18024420	Correct permissions to write file to disk inside SharePoint's EventReceiver	SPSecurity.RunWithElevatedPrivileges(delegate()\n{\n    // open/write/close file here. \n    // Avoid touching SPxxxx objects from outside of this delegate\n});	0
12601366	12599762	How to connect Azure federated root database and apply federation in entity framework?	using (DemoEntities db = new DemoEntities())\n{\n   db.Connection.Open();\n   string federationCmdText = @"USE FEDERATION ProdutosFed(ID = 110) WITH RESET, FILTERING=OFF";\n   db.ExecuteStoreCommand(federationCmdText); \n}	0
3880270	3861554	How to encapsulate from a thread in a method?	public class ProcessRequestThread\n{\n  private Thread ProcessThread;\n  private HttpListenerContext Context;\n\n  public ProcessRequestThread()\n  {\n    ProcessThread = new Thread( ProcessRequest );\n    ProcessThread.Start();\n  }\n\n  private void ProcessRequest(object contextObject)\n  {\n    Context = (HttpListenerContext)contextObject;\n\n    // handle request\n    if (someCondition())\n    {\n      EncapsulateMe(400, "Missing something");\n    }\n    else\n    {\n      EncapsulateMe(200, "Everything OK");\n    }\n  }\n\n  private void EncapsulateMe(int code, string description)\n  {\n    Context.Response.StatusCode = code;\n    Context.Response.StatusDescription = description;\n  }\n}	0
19343523	19343252	base64string to string back to base64string	namespace ConsoleApplication1\n{\n    using System;\n    using System.Text;\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string profilepic = "/9j/4AAQ";\n            string New = Convert.ToBase64String(Encoding.Unicode.GetBytes(profilepic));\n            byte[] raw = Convert.FromBase64String(New); // unpack the base-64 to a blob\n            string s = Encoding.Unicode.GetString(raw); // outputs /9j/4AAQ\n            Console.ReadKey();\n        }\n    }\n}	0
16140347	16139468	how to get text file rows with no delimiter into array	string[] lines = File.ReadAllLines(path);\n\nfor (int index = 4; index < lines.Length; index += 5)\n{\n    Event special = new Event();\n    special.Day = Convert.ToInt32(lines[index - 4]);\n    special.Time = Convert.ToDateTime(lines[index - 3]);\n    special.Price = Convert.ToDouble(lines[index - 2]);\n    special.StrEvent = lines[index - 1];\n    special.Description = lines[index];\n    events.Add(special);\n}	0
19567219	19567015	How to loop parents before Child records in a nested collection?	private void Loop(PreviewObject po)\n{\n    Queue<PreviewObject> queue = new Queue<PreviewObject>();\n    queue.Enqueue(po);\n\n    while(queue.Count != 0)\n    {\n        PreviewObject next = queue.Dequeue();\n        foreach(PreviewObject obj in next.Childrens)\n            queue.Enqueue(obj);\n\n        // Replace with the actual processing you need to do on the item\n        Console.WriteLine(next.Name);\n    }\n}	0
24530290	24530210	Linq way of finding all lists with numbers going up	yourLists\n .Where(list => list\n .Select((x, idx) => new {x, idx}).Skip(1).All(n => n.x > list[n.idx - 1]));	0
9001395	9001155	Cloning an instance of object to its base type	string SerializeToXmlAsParent()\n{\n    return base.SerializeToXml();\n}	0
8580917	8580871	Wrong decimal places after parsing	float.Parse(word, System.Globalization.CultureInfo.InvariantCulture);	0
22145255	21585825	Get Data from Database Where UserID is equal to value from asp:label	using (var GetName = new SqlCommand("SELECT Name FROM Ticket WHERE UserID='" + lblID.Text + "'", conn))	0
13781533	13781474	How to get integer from string returned as ajax response	var updated = result.match(/\d/);	0
3481683	3481669	Connecting to Oracle from F#	#if INTERACTIVE\n  #r "System.Data"\n  #r "Oracle.DataAccess"\n#endif\n\nopen System.Data\nopen Oracle.DataAccess.Client\n\nlet conn = OracleConnection("User Id=scott;Password=tiger;Data Source=oracle")\nconn.Open()\n\nlet cmd = conn.CreateCommand()\ncmd.CommandText = "select * from emp"\n\nlet rdr = reader = cmd.ExecuteReader()\n\nlet empIds = \n  [while reader.Read() do\n     yield reader.GetInt32(0)]	0
9258783	9258704	How to [group by] the datatable and put the result in another datatable?	var dataTable = new DataTable();\ndataTable.Columns.Add("id", typeof(Int16));\ndataTable.Columns.Add("name_in", typeof(string));\nforeach (var group in groups)\n{\n  dataTable.Rows.Add(group.Key, (group.First())["name_in"]);\n}	0
6587659	6587633	How to create a class dynamically	dynamic dataTransferObject = new System.Dynamic.ExpandoObject();\ndataTransferObject.Property1 = "someValue";\ndataTransferObject.Property2 = "someOtherValue";	0
1610276	1610051	Complex string matching with LINQ to Entity Framework	var results = from a in mycontainer.users\n              where a.fullname.Contains(newString)\n              select a.fullname;	0
11153361	11153130	Getting index for multiple selected item in ListBox in c#	if (productListBox.SelectedItems.Count >= 0)\n {\n    for (int i = 0; i < productListBox.SelectedItems.Count; i++)\n       {\n            MessageBox.Show(productListBox.SelectedIndices[i].ToString());\n       }\n  }	0
28373397	28363614	Redirect with post data - WITHOUT query string	var formBuilder = new StringBuilder();\n        formBuilder.AppendLine("<html><head>");\n        formBuilder.AppendLineFormat("</head><body onload=\"document.{0}.submit()\">", formName);\n        formBuilder.AppendLineFormat("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", formName, Method.ToString(), Url);\n        for (int i = 0; i < _inputValues.Keys.Count; i++) {\n            formBuilder.AppendLineFormat("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", \n                HttpUtility.HtmlEncode(_inputValues.Keys[i]), HttpUtility.HtmlEncode(_inputValues[_inputValues.Keys[i]]));\n        }\n        formBuilder.AppendLine("</form>");\n        formBuilder.AppendLine("</body></html>");\n\n        _httpContext.Response.Clear();\n        _httpContext.Response.Write(formBuilder.ToString());\n        _httpContext.Response.End();	0
31325758	31325120	C# Read XML Multiple Nested	XElement report = XElement.Load("file.xml");\n\nXNamespace ns = "urn:crystal-reports:schemas";\n\nvar formattedAreaPair = report\n    .Descendants(ns + "FormattedAreaPair")\n    .Where(elem => elem.Attribute("Level").Value == "2" && elem.Attribute("Type").Value == "Details")\n    .First();\n\nforeach (var elem in formattedAreaPair.Descendants(ns + "FormattedReportObject"))\n{\n    Console.WriteLine(elem.Element(ns + "ObjectName").Value);\n    Console.WriteLine(elem.Element(ns + "FormattedValue").Value);\n    Console.WriteLine();\n}	0
8575933	8574118	how to set the navigationUrl of a hyperlinkField in SPGridView	HyperLinkField hyplink = new HyperLinkField();\n\nhyplink.DataTextField = "Name";\nhyplink.DataNavigateUrlFields = new string[] { "Url" };\nhyplink.SortExpression = "Name";\nhyplink.HeaderText = "Workspaces";\ngrid.Columns.Add(hyplink);	0
13167276	13148468	Use Autofac with WCF service with InstanceContextMode = PerSession	ServiceBehavior.InstanceContextMode = InstanceContextMode.PerSession	0
17370526	17370441	TextBox Truncates Strings at '\0' Character	TextBox1.Text = File.ReadAllText(filename).Replace("\0", "");	0
23761097	23760436	C# count paragraphs in div from a website's html source code	//get the maximum number of paragraph\nint maxNumberOfParagraph = \n            doc.DocumentNode\n               .SelectNodes("//div[.//p]")\n               .Max(o => o.SelectNodes(".//p").Count);\n\n//get divs having number of containing paragraph equals maxNumberOfParagraph \nvar divs = doc.DocumentNode\n              .SelectNodes("//div[.//p]")\n              .Where(o => o.SelectNodes(".//p").Count == maxNumberOfParagraph);	0
4085688	4085613	Parse assembly qualified name without using AssemblyName	List<string> parts = name.Split(',')\n                         .Select(x => x.Trim())\n                         .ToList();\n\nstring name = parts[0];\nstring assembly = parts.Count < 2 ? null : parts[1];\nstring version = parts.Count < 3 ? null : parts[2];\nstring culture = parts.Count < 4 ? null : parts[3];\nstring token = parts.Count < 5 ? null : parts[4];\n\nif (version != null && !version.StartsWith("Version="))\n{\n    throw new ArgumentException("Invalid version: " + version);\n}\n// etc	0
3249716	3249503	CFString to string?	Encoding.ASCII.GetString(value, 9, value.Length - 9);	0
1161051	1161017	performing http methods using windows application in c#	WebClient webclient= new WebClient();\n\nusing (StreamReader reader = new StreamReader(webclient.OpenRead("http://www.google.com")))\n{\n        string result = reader.ReadToEnd();\n         // Parse web page here\n}	0
25139859	25136411	Bind 1 GridView to sql connection string array	DataTable dtFinal = new DataTable();\nforeach (string conString in arr)\n{\n    DataTable dtTemp = new DataTable();\n\n    using (SqlConnection con = new SqlConnection(conString))\n    {\n        using (SqlCommand cmd = new SqlCommand("SELECT * from some sys.dm", con))\n        {\n            con.Open();\n\n            dtTemp.Load(cmd.ExecuteReader());\n            dtFinal.Merge(dtTemp);\n        }\n    }\n}\n\nGridView1.DataSource = dtFinal;\nGridView1.DataBind();	0
17434837	17434796	Entering data with a ' (apostrophy) into SQL Server CE table	// I'm assuming you're opening the connection already\nstring sql = "INSERT INTO ShowDB(ITEM) VALUES (@Name)";\nusing (var command = new SqlCommand(sql, connection))\n{\n    command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = "John's shoes";\n    command.ExecuteNonQuery();\n}	0
7027713	6989113	How to combine a collection that's an object property (for collectionviewsource)	viewModel.Items = new ObservableCollection<Item>(Container.SelectMany(x => x.Items));	0
22558984	22533489	Transform xml using xsl in c# displays empty file	MemoryStream stm = new MemoryStream();\nxslt.Transform(docXML, null, stm);\n\nstm.Position = 1;\nStreamReader sr = new StreamReader(stm);\nResponse.Write(sr.ReadToEnd());	0
33395820	33395674	Add a {0} variable to an Excel spreadsheet name	Response.AddHeader("content-disposition", string.Format("attachment; filename=Activity_{0}_{1}.xls",strUser, DateTime.Now.Date.ToString("MMddyyyy")));	0
599282	599275	How can I download HTML source in C#	using System.Net;\n//...\nusing (WebClient client = new WebClient ()) // WebClient class inherits IDisposable\n{\n    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");\n\n    // Or you can get the file content without saving it:\n    string htmlCode = client.DownloadString("http://yoursite.com/page.html");\n    //...\n}	0
6472366	6472290	converting .net DateTime object to Javascript Date object	function toDateFromJson(src) {\n    return new Date(parseInt(src.substr(6)));\n}	0
28106585	28106400	SQL Server 2008 clr integration	CustomMarshalers\nMicrosoft.VisualBasic\nMicrosoft.VisualC\nmscorlib\nSystem\nSystem.Configuration\nSystem.Data\nSystem.Data.OracleClient\nSystem.Data.SqlXml\nSystem.Deployment\nSystem.Security\nSystem.Transactions\nSystem.Web.Services\nSystem.Xml\nSystem.Core.dll\nSystem.Xml.Linq.dll	0
30903736	30903090	In RouteConfig, how can I IgnoreRoute for this "Rejected-By-UrlScan" path?	routes.IgnoreRoute("{reject}", new { reject = @"(.*/)?Rejected-By-UrlScan(/.)?" })	0
12211321	12211286	try catch in a try block - exception should call same function	public static void DoSomething()\n{\n  try\n  { \n    //some code\n  }\n\n  catch (ExceptionA e)\n  {\n    // exception is ExceptionA type\n    log.Error("At the end something is wrong: " + e);\n    FunctionA(); //same function as in the first exception    \n  }\n  catch (ExceptionB e)\n  {\n    // exception is ExceptionB type\n    log.Error("At the start something wrong: " + e);\n    FunctionA(); //same function as in the first exception    \n  }\n  finally\n  {\n        //you can do something here whether there is an exception or not\n  }\n}	0
1370360	1370158	(Console.BufferHeight) I can't see/scroll to see all the console output with Console.WriteLine	Console.BufferHeight = Int16.MaxValue - 1; // ***** Alters the BufferHeight *****\nList<string> myList = new List<string>();\nfor (int x = 0; x < 100000; x++) \n    myList.Add(x.ToString()); \nforeach (string s in myList) { \n    Console.WriteLine(s); \n}	0
9065997	9065861	Transfer data between unbound DataGridViews	public Form2(DataGridView dgvFromFom1) {\n  InitializeComponent();\n\n  foreach (DataGridViewColumn dc in dgvFromForm1.Columns) {\n    dataGridView1.Columns.Add(dc.Name, dc.HeaderText);\n  }\n\n  foreach (DataGridViewRow dr in dgvFromForm1.Rows) {\n    Object[] newRow = new object[dr.Cells.Count];\n\n    for (int i = 0; i < newRow.Length; i++) {\n      newRow[i] = dr.Cells[i].Value;\n    }\n    dataGridView1.Rows.Add(newRow);\n  }      \n}	0
1341844	1341821	Storing default value in Application settings (C#)	if(string.IsnullOrEmpty(Settings.Default.FileDirectory))\n{\nSettings.Default.FileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nSettings.Default.Save();\n}	0
7556177	7556059	How to perform a PDF conversion in Event Receiver?	docObject.ExportAsFixedFormat("Yourdoc.pdf", WdExportFormat.wdExportFormatPDF, false,\n                        WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0,\n                        WdExportItem.wdExportDocumentContent, true, true,\n                        WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, false, false, ref oMissing);	0
24744523	24471096	How to create a Facebook fitness:course object using Facebook SDK for .NET	if (ShareSplits)\n{\n    courseParams.Add("fitness:splits:unit", unitText);\n\n    if (RideModel.IntervalPoints.Count > 1)\n    {\n        JsonArray splitParams = new JsonArray();\n        for (int i = 0; i < (RideModel.IntervalPoints.Count - 1); i++)\n        {\n            JsonObject splitPointParams = new JsonObject();\n            splitPointParams.Add("values:value", RideModel.IntervalPoints[i].IntervalTime.TotalSeconds);\n            splitPointParams.Add("values:units", "s");\n            splitParams.Add(splitPointParams);                            \n        }\n        courseParams.Add("fitness:splits", splitParams);\n    }\n}	0
25468934	25468477	Validation Logic	private Boolean validateRadioBtns()\n{\n    if (radAll.Checked == false && radOther.Checked == false)\n        return true;\n    else if(radOther.Checked == true && txtExt.Text.Trim().Length == 0 ) //just a quick sample of how you can trim the spaces and check for length \n        return true;\n    return false;\n}	0
23191530	23191298	Multiplying the sum of numbers in a column with the sum of numbers in another column? Access to C#	decimal total = 0; //declare outside the foreach\n\nforeach (DataRow currentRow in itemDS.Tables[0].Rows)\n                {\n                    // add to data grid view\n                    invoiceDataGridView.Rows.Add(currentRow[1].ToString(),   currentRow[2].ToString(), currentRow[3].ToString());\n\n                    var itemQuant = Convert.ToDecimal(currentRow[1]);\n                    var priceEach = Convert.ToDecimal(currentRow[3]);\n\n                    decimal subTotal = itemQuant * priceEach;\n\n                    total += subTotal;\n                }\n\n//do something with total here, after for each finishes	0
6790337	6790235	How can I know the storage space provided by WINDOWS OS for Isolated Storage?	using System;\nusing System.IO;\nusing System.IO.IsolatedStorage;\n\npublic class CheckingSpace\n{\n    public static void Main()\n    {\n        // Get an isolated store for this assembly and put it into an\n        // IsolatedStoreFile object.\n        IsolatedStorageFile isoStore =  IsolatedStorageFile.GetStore(IsolatedStorageScope.User |\n            IsolatedStorageScope.Assembly, null, null);\n\n        // Create a few placeholder files in the isolated store.\n        new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);\n        new IsolatedStorageFileStream("Another.txt", FileMode.Create, isoStore);\n        new IsolatedStorageFileStream("AThird.txt", FileMode.Create, isoStore);\n        new IsolatedStorageFileStream("AFourth.txt", FileMode.Create, isoStore);\n        new IsolatedStorageFileStream("AFifth.txt", FileMode.Create, isoStore);\n\n        Console.WriteLine(isoStore.AvailableFreeSpace + " bytes of space remain in this isolated store.");\n    } // End of Main.\n}	0
32187269	32186963	Iterating through my Datagridview	foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n     if(row.Cells[0].Value!=null)\n      {\n      //code\n      }\n    }	0
12941171	12940671	Traverse Windows directory tree and retrieve permissions for each folder	i:\MyDirectory\SomeDirectory BUILTIN\Administrators:F \n                         BUILTIN\Administrators:(OI)(CI)(IO)F \n                         NT AUTHORITY\SYSTEM:F \n                         NT AUTHORITY\SYSTEM:(OI)(CI)(IO)F \n                         NT AUTHORITY\Authenticated Users:C \n                         NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)C \n                         BUILTIN\Users:R \n                         BUILTIN\Users:(OI)(CI)(IO)(special access:)\n\n                                                   GENERIC_READ\n                                                   GENERIC_EXECUTE	0
18522531	18368715	multi-page text drawing to a pdf with monotouch	if(-yOffset >= UIGraphics.PDFContextBounds.Height) {\n    // Start a new page if needed\n    //g.EndPage ();\n    UIGraphics.BeginPDFPage ();\n\n    **g = UIGraphics.GetCurrentContext();\n    g.ScaleCTM (1, -1);**\n\n    yOffset = -marginTop - fontSize;\n}	0
459468	459392	Problems tranforming a REST response to a XDocument	string myResult = "<?xml blahblahblah>";\nXDocument doc = XDocument.Parse(myResult);	0
17700849	17700440	Dynamically adding columns to DataGridView as it gets expanded	int columnsToShow = (int)(dataGridView.Size.Width / columnWidth);	0
31631509	31631095	Fill ComboBox with data from ObservableCollection from other ViewModel	private ObservableCollection<Location> _allLocations;\npublic ObservableCollection<Location> AllLocations\n{\n    get { return _allLocations; }\n    set { _allLocations = value; RaisePropertyChanged("AllLocations"); }\n}\n\npublic ViewModel1(ViewModel2 vm2 )\n{\n\n    AllLocations = vm2.Locations;\n}	0
11386798	11386774	array of custom type arrays	List<Hotspot>[] arrays = new List<Hotspot>[]{items, locations};	0
15155602	15155490	Find a control style in C#	string value = divCorporateId.Style["Key"]	0
18830274	18830113	Update multiple rows in datatable without loop	DataTable recTable = new DataTable();\n\n// do stuff to populate table\n\nrecTable.Select(string.Format("[code] = '{0}'", someName)).ToList<DataRow>().ForEach(r => r["Color"] = colorValue);	0
17854184	17854104	how to retrieve all the values from the selected checkboxes in a checkboxlist in asp.net?	string values = string.Join(",", checkboxlist.Items.Cast<ListItem>()\n                                             .Where(i => i.Selected)\n                                             .Select(i => i.Value));	0
15584206	15584166	how to get network system DateTime using ip of that system	public static DateTime GetNistTime()\n{\n    DateTime dt = DateTime.MinValue;\n\n    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://....");\n    req.Method = "GET";\n    req.Accept = "text/html, application/xhtml+xml, */*";\n    req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";\n    req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); //No caching\n    HttpWebResponse res = (HttpWebResponse)req.GetResponse();\n    if (res.StatusCode == HttpStatusCode.OK)\n    {\n        StreamReader st = new StreamReader(res.GetResponseStream());\n        string html = st.ReadToEnd().ToUpper();\n        string time = Regex.Match(html, @">\d+:\d+:\d+<").Value; //HH:mm:ss format\n        string date = Regex.Match(html, @">\w+,\s\w+\s\d+,\s\d+<").Value; //dddd, MMMM dd, yyyy\n        dt= DateTime.Parse((date + " " + time).Replace(">", "").Replace("<", ""));\n    }\n\n    return dt;\n}	0
16556635	16543437	Outlook Addin - How can I set ?High Importance? on email sent using C# in VSTO	private void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n  Outlook.MailItem myMailItem = (Outlook.MailItem)this.OutlookItem;\n  myMailItem.Importance = Outlook.OlImportance.olImportanceHigh\n}	0
1157022	1157009	Application exit even not firing in c# windows application	[STAThread]\nstatic void Main()\n{\n    Taskbar.Hide();\n    Form1 TargerForm = new Form1();\n    Application.ApplicationExit += new EventHandler(Application_ApplicationExit);\n    Application.EnableVisualStyles();\n    Application.Run(TargerForm);\n    Taskbar.Show();\n}	0
23507212	23507052	How to select xaml object by x:Name	var thisellipse = (Ellipse)this.FindName("f03");	0
27255576	27255399	MonthCalendar C# winforms highlight dates color	custom contro	0
7328742	7328703	How write values to a string then return?	System.Text.StringBuilder sb = new System.Text.StringBuilder();\n                 while (reader.Read())\n                    {\n                        using (var fragmentReader = reader.ReadSubtree())\n                        {\n                            if (fragmentReader.Read())\n                            {\n                                reader.ReadToFollowing("value");\n                                //Console.WriteLine(reader.ReadElementContentAsString() + ",");\n\n\n                                sb.Append(reader.ReadElementContentAsString()).Append(",");\n                            }\n                        }\n                    }\n                    Console.WriteLine(sb.ToString());	0
1096222	1096043	C# Winforms Suppress a Mouse Click event on a Text Box	public partial class MyTextBox : TextBox\n{\n    int WM_LBUTTONDOWN = 0x0201; //513\n    int WM_LBUTTONUP = 0x0202; //514\n    int WM_LBUTTONDBLCLK = 0x0203; //515\n\n    public MyTextBox()\n    {\n        InitializeComponent();\n    }\n\n    protected override void WndProc(ref Message m)\n    {\n\n        if (m.Msg == WM_LBUTTONDOWN || \n           m.Msg == WM_LBUTTONUP || \n           m.Msg == WM_LBUTTONDBLCLK // && Your State To Check\n           )\n        {\n            //Dont dispatch message\n            return;\n        }\n\n        //Dispatch as usual\n        base.WndProc(ref m);\n    }\n}	0
4890507	4890418	TextBoxFor extension HTMLHelper	// the user has no permission => render a readonly checkbox\nvar mergedHtmlAttributes = new RouteValueDictionary(htmlAttributes);\nmergedHtmlAttributes["disabled"] = "disabled";\nreturn htmlHelper.TextBox(name, DateTime.Now, mergedHtmlAttributes);	0
3558583	3558325	is it possible to make a combobox not visible on a certain row in a gridview?	gvAirSegment.Rows[e.RowIndex].Cells[2].ReadOnly = true;	0
13666254	13636751	Is there a global exception handler in Windows store apps?	async void	0
20700804	20700658	How to go to the function definition in Jquery?	/// <reference path="~/Scripts/lib/jquery/jquery-1.10.2-vsdoc.js"/>	0
11685828	11685675	How can I have 2 instances of dll function yet still use both of them?	[DllImport("user32.dll")]\npublic static extern bool PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);	0
11096530	11094378	Word File savings without closing are Not Uploaded to the server	string tmp = Path.GetTempFileName();\n\nusing(Stream s = new FileStream(filePath,\n    FileMode.Open, FileAccess.Read,\n    // following option will let you open\n    // opened file by other process\n    FileShare.ReadWrite)){\n\n   using(FileStream fs = File.OpenWrite(tmp)){\n      // this will copy file to tmp\n      s.CopyTo(fs);\n   }\n\n}\n\n// upload  tmp  file...	0
1540186	1540118	How to execute SQL with comments and GO statements using SqlConnection?	string connectionString, scriptText;\nSqlConnection sqlConnection = new SqlConnection(connectionString);\nServerConnection svrConnection = new ServerConnection(sqlConnection);\nServer server = new Server(svrConnection);\nserver.ConnectionContext.ExecuteNonQuery(scriptText);	0
444226	444151	How do I pull the clientID of an asp:button inside an asp:listview for use with jQuery?	var button = (Button)e.Item.FindControl("Button1");\nbutton.OnClientClick = "ShowEditDialog(" + Eval("ItemId") + ")";	0
11226003	10613101	Disable control for a single page when the control runs from masterpase in asp.net	Control c = Master.FindControl("Footer1");\n c.Visible = false;	0
3715394	3715380	How to get Type of Exception in C#	try \n{\n    // Try sending a sample SQL query\n} \ncatch (SQLException ex) \n{\n    // Print error message\n}	0
12520150	12429212	How do you call a stored procedure in MVC3 C#	[HttpPost]\n    public ActionResult Edit(int id, AuditScheduleEdit viewModel)\n    {            \n        if (ModelState.IsValid)\n        {\n            var addGlassCutting = new SqlParameter("@AuditScheduleID", id);\n            _db.Database.SqlCommand\n            ("EXEC AddGlassCutting @AuditScheduleID", addGlassCutting);\n            viewModel.PopulateCheckBoxsToSpacerType();\n            _db.Entry(viewModel.AuditScheduleInstance).State = System.Data.EntityState.Modified;\n            _db.SaveChanges();\n            return RedirectToAction("Audit", new {id});\n        }\n        else\n        {\n            return View(viewModel);\n        }\n\n    }	0
8726668	8726156	How to do join in ADO.NET Entity Framework	public List<Student> GetStudentsByProject(int pgid)\n{\n    return this.ObjectContext.ProjectGroup.Where(pg => pg.pgid == pgid)\n               .SelectMany(pg => pg.Students).ToList();\n}	0
19410031	19409947	How to get the children of a UIElement	ControlTypeIWantToFind result = \n                FindVisualChild<ControlTypeIWantToFind>(myPropertyInspectorView);\n\npublic static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject\n{\n    if (depObj != null)\n    {\n        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)\n        {\n            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);\n            if (child != null && child is T)\n            {\n                return (T)child;\n            }\n\n            T childItem = FindVisualChild<T>(child);\n            if (childItem != null) return childItem;\n        }\n    }\n    return null;\n}	0
4827041	4827003	Begin to use EDMX Immediately	var objectRepresentingSingleRow = yourDataContext.theTable.First(t => t.Id == someId);	0
4729937	4729532	cast problem from class to interface	typeof(ISearchQueryManager).Assembly.Location\ntypeof(SlovenianSearchQueryManager).Assembly.Location	0
14657015	14656699	How to get a value from a session in ASP.NET 4.0 and store it to a textbox/ label	txt_loggedas.Text = Session["user"].ToString();	0
8614667	8614624	How to differentiate between value-type, nullable value-type, enum, nullable-enum, reference-types through reflection?	Console.WriteLine(propInfoOne.PropertyType.IsPrimitive); //true\nConsole.WriteLine(propInfoOne.PropertyType.IsValueType); //false, value types are structs\n\nConsole.WriteLine(propInfoThree.PropertyType.IsEnum); //true\n\nvar nullableType = typeof (Nullable<>).MakeGenericType(propInfoThree.PropertyType);\nConsole.WriteLine(nullableType.IsAssignableFrom(propInfoThree.PropertyType)); //true	0
3234867	3234833	How do I allow my class to be implicitly converted to a string in C#?	public class A\n{\n    public string Content { get; set; }\n    public static implicit operator string(A a)\n    {\n        return string.Format("<span>{0}</span>", a.Content);\n    }\n}	0
12156072	12155999	How to pass the asp.net dropdown selected item as an input to a stored procedure in c#?	//get dropdown selected value and store in a variable \nvar eventId = dropdown.SelectedValue; \n\n//pass this variable in the GetDaysForEvents method to get DataSet.\nvar dataSet = GetDaysForEvents(eventId);	0
27370082	27369559	Incorrect Lambda Expression Indentation	Hello World!	0
5764072	5763811	best way to copy Data from one DataTable to another DataTable with diffrent structure	IEnumerable<DataRow> query = from vendInv in VendorInvoiceStagingTable.AsEnumerable()\n                             where vendInv.Field<string>(VendInvoice.Number) == InvoiceHeader\n                             select vendInv;\n\n// Would this be ok?\nVendorInvoiceTable.Rows.Add(query.First().ItemArray);\n\n// ...or if not, how about this?\nobject[] sourceData = query.First().ItemArray;\nobject[] targetData = new object[sourceData.Length];\nsourceData.CopyTo(targetData, 0);\nVendorInvoiceTable.Rows.Add(targetData);	0
33800949	33798441	Any way to instruct Entity Framework to map from column to Model property in code-first, table-per-hierarchy approach?	public class BaseClass\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n}\n\npublic class SubClassOne : BaseClass\n{\n    [Column("Volume1")]   \n    public double Volume { get; set; }        \n}\n\npublic class SubClassTwo : BaseClass\n{\n    [Column("Volume2")] \n    public double Volume { get; set; }\n}\n\npublic class SubClassThree : BaseClass\n{\n    public int Number { get; set; }\n}	0
10287740	10287643	ASP.net with C# Keeping a List on postback	public List<string> Code\n{\n    get\n    {\n        if(HttpContext.Current.Session["Code"] == null)\n        {\n            HttpContext.Current.Session["Code"] = new List<string>();\n        }\n        return HttpContext.Current.Session["Code"] as List<string>;\n    }\n    set\n    {\n        HttpContext.Current.Session["Code"] = value;\n    }\n\n}	0
3813729	3806762	ProgressBar for multiple WebBrowser instances	if (currentProgressBar != null)\n        {\n            (currentProgressBar as ToolStripProgressBar).Maximum = (currentProgressBar as ToolStripProgressBar).Maximum;\n            (currentProgressBar as ToolStripProgressBar).Value = preValue + ((100 * (Int32)e.CurrentProgress) / (Int32)e.MaximumProgress);\n            if (e.CurrentProgress >= e.MaximumProgress)\n            {\n                preValue = (currentProgressBar as ToolStripProgressBar).Value;\n            }\n        }	0
10990744	10988616	Null, int? and lambda expressions with EF 4.1	if(organisationId.HasValue)\n    return memberRepository.GetSingleOrDefault(m => m.Email == email && m.OrganisationId == organisationId);\nelse\n    return memberRepository.GetSingleOrDefault(m => m.Email == email && m.OrganisationId == null);	0
13641888	13473869	sql statement to nhibernate criteria	ICriteria criteria = Session.CreateCriteria<User>()\n            .CreateAlias("SecurityGroups", "SecurityGroups")\n            .CreateAlias("SecurityGroups.Permissions", "Permissions")\n            .Add(Restrictions.Eq("Permissions.Active", true))\n            .Add(Restrictions.Eq("Active", true))\n            .Add(Restrictions.In("Permissions.Site", ids.ToArray()))\n            .Add(Restrictions.Eq("Permissions.Perm" + Enum.GetName(typeof(Perm.Types), accessRight), Perm.Level.Allow));\n        return criteria.List<User>();	0
34233689	34233660	Split a line/sentence in two in C#	sSentence.Replace(";", ", Amount: ");	0
9805745	9805168	Inserting a striped line onto an Excel chart through COM Interop	- add a data series with a steady value ( of 50 in your case )\n- move the new data series to the secondary Y axis\n- synchronize the maximum for both Y axes\n- set Chart Type for the new data series to Line\n- set the Line Style for the new data series to a dash type	0
7825074	7825019	How to Find Checkbox within Asp.net panel?	// if(!Page.IsPostBack){\nforeach (var chk in chks)\n{\n   PlSettings.Controls.Add(new LiteralControl("<div class=\"Controls\">"));\n\n   PlSettings.Controls.Add(chk);\n\n   PlSettings.Controls.Add(new LiteralControl("</div>"));\n}\n//}	0
33564743	33564361	Adding multiple pushpins to bing map	public void AddIcon()\n    {\n\n        for (int i = 0; i < pushPin.Items().Count; i++)\n        {\n            MapIcon myIcon = new MapIcon();\n            myIcon.NormalizedAnchorPoint = new Point(0.5, 1.0);\n            myIcon.Title = "Apartment here";\n            MyMap.MapElements.Add(myIcon);\n            myIcon.Location = pushPin.MyGeopoint(i);\n        }\n    }	0
6921024	6920994	Named parameters confusion	[WebMethod(cacheDuration: 300)]	0
22611467	22611386	Reading file in C# based on new line	string[] lines = File.ReadAllLines(path);\nfor(int i = 0; i < lines.Length; i++)\n{\n    string line = lines[i];\n    string[] tokens = line.Split(new char[]{'-', ' '});\n    int number = int.Parse(tokens[0]);\n    string text = tokens[1];\n    lines[i] = number + "-" + text;\n}\n\nFile.WriteAllLines(path2, lines);	0
565451	565425	How can I get a username and password from my database in C#?	using (SqlCommand myCommand = new SqlCommand("SELECT * FROM USERS WHERE USERNAME=@username AND PASSWORD=HASHBYTES('SHA1', @password)", myConnection))\n    {                    \n        myCommand.Parameters.AddWithValue("@username", user);\n        myCommand.Parameters.AddWithValue("@password", pass);\n\n        myConnection.Open();\n        SqlDataReader myReader = myCommand.ExecuteReader())\n        ...................\n    }	0
7086531	7083355	Using Enterprise Library's ExecuteSprocAccessor method with generics	public static T SelectSingle<T>(string sprocName, int id)    \n    where T : new()  // <---- here's the constraint\n{\n    return db.ExecuteSprocAccessor<T>(sprocName, id).First();    \n}	0
9263094	9263028	Linked list using a list	LinkedList<T>	0
69372	69352	Is there a way to programmatically minimize a window	private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n     if(e.KeyChar == 'm')\n         this.WindowState = FormWindowState.Minimized;\n}	0
33283229	33282932	multiply textbox value by factor from combobox?	int i = Int32.Parse(textBox1.Text);	0
5838167	5838043	Hiding columns but not page number in grid view asp.net	if (e.Row.RowType == DataControlRowType.DataRow)\n{\n    e.Row.Cells[0].Visible = false;\n}	0
4681593	4681519	How can I add default value to a RadComboBox?	result.Items = (new List<RadComboBoxItemData> \n  { \n    new RadComboBoxItemData { Text = "All", Value = "" }\n  }).Concat(allList).ToArray();	0
17363723	17363516	Regular Expression - get value from string based on criteria	Regex regex = new Regex(".*_(.*)_x_.*");\n        string incomingValue = @"123_NAME_x_dev";\n        string inside = null;\n        Match match = regex.Match(incomingValue);\n\n        if (match.Success)\n        {\n            inside = match.Groups[1].Value;\n        }	0
24468365	24467721	I want to use Entity Framework + ASP Identity but I don't want EF to generate tables for me	public SecurityContext()\n    : base("DefaultConnection")\n{\n    Database.SetInitializer<SecurityContext>(null);\n}	0
33320670	33319936	Characters are not escaped properly in a Dictionary	var conversion = new Dictionary<string, string> {\n    { @"[00]", "00" }\n};\n\nvar allLines = "Hello[00]\r\nWorld[00]";\nvar conversionRegex = new Regex(string.Join("|", conversion.Keys.Select(key => Regex.Escape(key))));\nvar textConverted = conversionRegex.Replace(allLines, n => conversion[n.Value]);\nConsole.WriteLine(textConverted);	0
3408809	3408655	Indexing into arrays of arbitrary rank in C#	int[,,,] array = new int[10, 10, 10, 10];\n\nfixed (int* ptr = array)\n{\n    ptr[10] = 42;\n}\n\nint result = array[0, 0, 1, 0];  // == 42	0
23898250	23897797	How can I explain that data won't cross threads?	DoWork(data1);\nDoWork(data2);	0
14170171	14170116	Validate names for folders created using code behind	Path.GetInvalidPathChars	0
27847751	27847665	How to update anonymous objects property using LINQ and Contains	var people = from p in persons\n    let year = ages.Any(a=>a.NewYear==p.Year) ? ages.Single(a => a.OldYear == p.Year).NewYear : p.Year\n    select new { Name = p.Name, Year = year; };	0
22302308	22301735	How can I convert a ControlTemplate to a XAML string in WPF?	// Create an XmlWriter\nStringBuilder sb = new StringBuilder();\nXmlWriterSettings xmlSettings = new XmlWriterSettings\n    { Indent = true, IndentChars = "    ", NewLineOnAttributes = true };\nXmlWriter writer = XmlWriter.Create(sb, xmlSettings);\n\nXamlWriter.Save(RadPane.BottomTemplate, writer);	0
17375180	17375134	NotSupportedException when inserting with Dapper	...\nOutlineUri = fogbugzCase.OutlineUri.OriginalString\n...	0
30195949	30195716	Print same number multiple times to form rectangle of given size	//For each row (y)\nfor (int y = 0; y < fieldSizeY; y++)\n{\n    //For each column (x)\n    for (int x = 0; x < fieldSizeX; x++)\n    {\n        //Now you need to repeat the same number for each x, but no new line.\n        Console.Write(fieldNumber)\n    } \n    //Stick the new line on the end of the row to start the next row\n    Console.WriteLine();\n}	0
28993180	28993106	DataGridView, How to use if statement for a cell that starts with a string	if (DGV_Points.Rows[x].Cells[2].Value.ToString().StartsWith("Manual"))\n{\n\n}	0
3451836	3451810	Auto-generate an interface implementation in C#?	public class MyClass : MyInterface	0
18591478	18591389	Define structure of flags	[FlagsAttribute]\n    public enum mystruct: byte\n    {\n        first= 1,\n        second =2\n    }	0
17507720	17111647	Posting a tweet with TweetSharp in C# is taking much time	// this is a better way to run something in the background\n// this queues up a task on a background threadpool\nawait Task.Run(() => {\n    twitterService.SendTweet(new SendTweetOptions { Status = status });\n});\n\n// this method of running a task in the background creates unnecessary overhead\nTask.Factory.StartNew(() => {\n    twitterService.SendTweet(new SendTweetOptions { Status = status });\n});	0
550738	550694	Generic implementation of interface	public abstract class PointList<T> : IPointList where T : IPoint\n    {\n        public IList<T> GetPoints\n        {\n            get\n            {\n                return GetPointsCore ();\n            }\n        }\n\n        IList<IPoint> IPointList.GetPoints\n        {\n            get\n            {\n                return GetPointsCore () as IList<IPoint>;\n            }        \n        }\n\n        protected abstract IList<T> GetPointsCore();        \n    }	0
29239810	29239809	Updating attached entries in Entity Framework 6 without modifying foreign keys	// [...] from previous sample\npassenger.CarId = 9001; // it's over 9000\ndbEntry.Property(e => e.CarId).IsModified = false; // we didn't change the Foreign Key\ncontext.SaveChanges(); // works!	0
29131087	29130689	Architecture for Interface/Abstraction	public interface IMovement\n{\n    int speed { get; set; }\n}\n\npublic class Worker\n{\n    speed = 5;\n    IMovement Movement;\n   public Warrior(IMovement m)\n    {\n        this.Movement = m;\n    }\n    public void Move()\n    {\n      this.Movement.Move();\n    }\n}\n\npublic class Warrior\n{\n    speed = 3;\n    IMovement movement;\n\n    public Warrior(IMovement m)\n    {\n        this.Movement = m;\n    }\n\n    public void Move()\n    {\n      this.Movement.Move();\n    }\n}\n\nvoid foo()\n{\n     IMovement m = new FlyingMovement();\n     Worker w = new Worker(m);\n\n    IMovement swimmingMovement = new SwimmingMovement();\n     SwimmingWorker sw = new SwimmingWorker (swimmingMovement);\n}	0
14618886	14618420	how to get unique records from data table randomly using c#?	DataTable distinctTable = new DataView(dtRandom).ToTable(\n  true, new string[] { "column1", "column2", "etc." });	0
25544322	25543110	sorting not all of columns in datagridview	private void dataGridView1_Sorted(object sender, EventArgs e)\n{\n   dataGridView1.SuspendLayout();\n   int yourindex = 0; // whichever column your index is at\n   foreach (DataGridViewRow row in dataGridView1.Rows) \n                            row.Cells[yourindex].Value = row.Index;\n   dataGridView1.ResumeLayout();\n\n}	0
26564409	26564329	Find largest Dictionary<int,string> key whose value is less than the search value	int myKey = myDictionary.Where(x => x.Key < myValue)\n                        .OrderByDescending(x => x.Key)\n                        .First().Key;	0
29918827	29915271	How to avoid duplicate urls with same key/value query-string at different places?	private static string SanitizeUrl(string url)\n    {\n        var uri = new Uri(url);\n        var path = uri.GetLeftPart(UriPartial.Path);\n        path += path.EndsWith("/") ? "" : "/";\n        var query = uri.ParseQueryString();\n        var dict = new SortedDictionary<string, string>(query.AllKeys\n            .Where(k => !string.IsNullOrWhiteSpace(query[k]))\n            .ToDictionary(k => k, k => query[k]));\n        return (path + ToQueryString(dict)).ToLower();\n    }\n\n    private static string ToQueryString(SortedDictionary<string, string> dict)\n    {\n        var items = new List<string>();\n        foreach (var entry in dict)\n        {\n            items.Add(string.Concat(entry.Key, "=", Uri.EscapeUriString(entry.Value)));\n        }\n        return (items.Count > 0 ? "?" : "") + string.Join("&", items.ToArray());\n    }	0
2696745	2682239	Programmatically controlling Chart in Silverlight toolkit	//Line to be inserted\nLineSeries Series1 = chart.Series[0] as LineSeries;\n\nSeries1.IndependentValuePath = "Val1";\nSeries1.DependentValuePath = "Val2";\nSeries1.ItemsSource = ObjectList;	0
11317883	11317782	How can I convert a string to int?	j = Convert.ToInt32(GetKey((keys + i).ToString()));	0
5953262	5953217	How to avoid getting a negative value?	DataGrid.Height = Math.Max(0.0, x - 485.0);	0
21722775	21722703	How to add html tags using C#	string script = @"< h1>\n                            This is heading one\n                            < /h1>\n                            < p>\n                             This is paragraph.\n                            < /p>";\n        string sciptAfter = "<html>" + script + "</html>";	0
26534572	26527817	How to keep all CodeIt.Right custom rules in one project for sharing with other users?	[CodeIt.Right - Publishing Custom Configured Coding Standards to Your Team][1]	0
9777410	9777155	Getting Parent Member from Expression	public static IHtmlString RenderList<TModel, TItem>(\n    this HtmlHelper<TModel> html, \n    Expression<Func<TModel, IEnumerable<TItem>>> dataExpression\n)\n{\n    var parentEx = ((MemberExpression)dataExpression.Body).Expression;\n    var lambda = Expression.Lambda<Func<TModel, object>>(parentEx, dataExpression.Parameters[0]);\n    var value = ModelMetadata.FromLambdaExpression(lambda, html.ViewData).Model;\n\n    ...\n}	0
3414974	3407669	De-serializing some XML (via a Stream) into Parent/Child objects	[XmlType("enquiry")]\n[XmlRoot("enquiry")]\npublic class Enquiry\n{\n    private List<Vehicle> vehicles = new List<Vehicle>();\n\n    [XmlElement("enquiry_no")]\n    public int EnquiryNumber { get; set; }\n\n    [XmlArray("vehicles")]\n    [XmlArrayItem("Vehicle", typeof(Vehicle))]\n    public List<Vehicle> Vehicles\n    {\n        get { return this.vehicles; }\n        set { this.vehicles = value ?? new List<Vehicle>(); }\n    }\n\n    [XmlAnyElement]\n    public XmlElement[] AnyElements;\n    [XmlAnyAttribute]\n    public XmlAttribute[] AnyAttributes;\n}\n\npublic class Vehicle\n{\n    [XmlElement("vehicle_type")]\n    public string VehicleType { get; set; }\n    [XmlElement("vehicle_make")]\n    public string VehicleMake { get; set; }\n    [XmlElement("vehicle_model")]\n    public string VehicleModel { get; set; }\n}	0
6311392	6311358	Efficient way to combine multiple text files	const int chunkSize = 2 * 1024; // 2KB\nvar inputFiles = new[] { "file1.dat", "file2.dat", "file3.dat" };\nusing (var output = File.Create("output.dat"))\n{\n    foreach (var file in inputFiles)\n    {\n        using (var input = File.OpenRead(file))\n        {\n            var buffer = new byte[chunkSize];\n            int bytesRead;\n            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)\n            {\n                output.Write(buffer, 0, bytesRead);\n            }\n        }\n    }\n}	0
2965958	2964473	How can I implement String.Concat(object, object) to L2E framework?	var query = from foo in db.Foo\n            select new { foo.X, foo.Y };\n\nvar result = from foo in query.AsEnumerable()\n             select foo.X.ToString() + foo.Y.ToString();	0
2420186	2420122	Using SecureString	"fizzbuzz".ToCharArray ().ToList ().ForEach ( p => secureString.AppendChar ( p ) );	0
928685	928665	C# Create objects with Generics at runtime	MethodInfo[] baseMethods = obj.GetType().BaseType.GetMethods();\nobject retObj = baseMethods[0].Invoke(obj, new object[] {"paramVal1", 3, "paramVal3"});	0
7264977	7264947	How to put a node in a dictionary using LINQ to XML	var doc = XDocument.Load(fileName);\nvar dictionary =\n    doc.Root\n        .Element("Level1")\n        .Elements("Foo")\n        .ToDictionary(\n            e => (int)e.Attribute("Id"),\n            e => (int)e.Attribute("Count"));	0
3732273	3732105	Regex match everything but 	(?!(quick|brown|fox|the lazy))(\b\w+|[^\w])	0
11704285	11704212	How to schedule message popups and show only the last message?	int signal = 0;\nSystem.Timers.Timer t = new System.Timers.Timer(3000);\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    //----------------------- other parts of code ---------------------\n\n    // at last\n    t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);\n    t.Start();\n}\n\nvoid t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n    if (signal == 0)\n        return;\n\n    t.Stop();\n    MessageBox.Show("You clicked: " + signal + " before " + t.Interval + " Seconds");\n    signal = 0;\n    t.Start(); //move this to top of msgbox if you want timer to be reset right after poppin the msgbox.\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    signal = 1;\n    t.Stop();\n    t.Start();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n    signal = 2;\n    t.Stop();\n    t.Start();\n}\n\nprivate void button3_Click(object sender, EventArgs e)\n{\n    signal = 3; \n    t.Stop();\n    t.Start();\n}	0
32816195	32638471	Button click of .NET application needs to tell an external service to start processing from a queue (msmq)	static void Main(string[] args)\n{\n    //create an event\n    MessageQueue msmq = new MessageQueue("queuename");\n    //subscribe to the event\n    msmq.ReceiveCompleted += msmq_ReceiveCompleted;\n    //start listening\n    msmq.BeginReceive();\n}\n\n//this will be fired everytime a message is received\nstatic void msmq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)\n{\n    //get the MessageQueue that we used \n    MessageQueue msmq = sender as MessageQueue;\n\n    //read the message\n    //and process it\n    Message msg = msmq.EndReceive(e.AsyncResult);\n\n    //because this method is only fired once everytime\n    //a message is sent to the queue\n    //we have to start listening again            \n    msmq.BeginReceive();\n}	0
8775180	8764338	How to run Timer inside of Timer?	private void Space(object sender, EventArgs e)\n    {\n        SendKeys.Send(txtText.Text.Substring(b++, 1));\n\n        tmrSpace.Interval = random.Next(50, 150);\n\n        if (b == txtText.TextLength)\n        {\n            tmrSpace.Enabled = false;\n            SendKeys.Send("{enter}");\n        }\n    }\n\n    private void Interval(object sender, EventArgs e)\n    {\n        if (cbPause.Checked)\n        {\n            b = 0;\n\n            tmrSpace.Interval = random.Next(50, 150);\n            tmrSpace.Enabled = true;\n        }\n        else\n        {\n            SendKeys.Send(txtText.Text + "{enter}");\n\n            if (tbType.SelectedTab == tbRange) tmrInterval.Interval = random.Next(int.Parse(nudMin.Value.ToString()), int.Parse(nudMax.Value.ToString()));\n        }\n    }	0
2814684	2813979	Error messages for model validation using data annotations	public class Book\n{\n    public PrimaryContact PrimaryContact { get; set; }\n    public SecondaryContact SecondaryContact { get; set; }\n\n    [Required(ErrorMessage = "Book name is required")]\n    public string Name { get; set; }\n}\n\npublic class Contact\n{\n    [Required(ErrorMessage = "Name is required")]\n    public string Name { get; set; }\n}\n\n[MetadataType(typeof(PrimaryContactMD))]\npublic class PrimaryContact : Contact\n{\n    class PrimaryContactMD\n    {\n        [Required(ErrorMessage = "Primary Contact Name is required")]\n        public string Name { get; set; }\n    }\n}\n\n[MetadataType(typeof(SecondaryContactMD))]\npublic class SecondaryContact : Contact\n{\n    class SecondaryContactMD\n    {\n        [Required(ErrorMessage = "Secondary Contact Name is required")]\n        public string Name { get; set; }\n    }\n}	0
1174670	1174635	assign type to variable, use variable with generic static class	[TestFixture(typeof(MySnazzyType))]\n[TestFixture(typeof(MyOtherSnazzyType))]\npublic class Tests<T>\n{\n    [Test]\n    public void PoolCount_IsZero()\n    {\n        Assert.AreEqual(0, ConnectionPool_Accessor<T>._pool.Count);\n    }\n}	0
18265817	18265744	App.Config escaping	app.config	0
7406753	2973079	C# String Resource Values as Enum String Part values?	public enum EventType\n    {\n        NewVersion = 1,\n        Accepted = 2,\n        Rejected = 3,\n        BruteForce = 4\n    }\n\n    public static class EventTypeExtension\n    {\n        public static string Display(this EventType type)\n        {\n            return Strings.ResourceManager.GetString("EventType_" + type);\n        }\n    }	0
30263331	30252322	Load an Excel cell value with a leading apostrophe	string text = cell.Value.ToString();\nif (cell.PrefixCharacter == '\'')\n    text = "'" + text;	0
31231356	31231033	Using SmtpClient to send an email from Gmail	try\n{\n    new SmtpClient\n    {\n        Host = "Smtp.Gmail.com",\n        Port = 587,\n        EnableSsl = true,\n        Timeout = 10000,\n        DeliveryMethod = SmtpDeliveryMethod.Network,\n        UseDefaultCredentials = false,\n        Credentials = new NetworkCredential("MyMail@Gmail.com", "MyPassword")\n    }.Send(new MailMessage {From = new MailAddress("MyMail@Gmail.com", "MyName"), To = {"TheirMail@Mail.com"}, Subject = "Subject", Body = "Message", BodyEncoding = Encoding.UTF8});\n    erroremail.Text = "Email has been sent successfully.";\n}\ncatch (Exception ex)\n{\n    erroremail.Text = "ERROR: " + ex.Message;\n}	0
30598463	30598143	Uploading excel file to DataGridView	"Select * from [" + textBox2.Text + "$[A1:C100]"	0
15300355	15274719	Outlook Add In get Item after Property_Change Event	public class MailItemWrapper\n{\n  public MailItem item;\n  public MailItemWrapper(MailItem OutlookItem)\n  {\n    item = OutlookItem;\n    item.PropertyChange += new System.EventHandler(PropertyChangeHandler);\n  }\n  private PropertyChangeHandler(string Name)\n  {\n    MessageBox.Show(string.Format("Property named {0} changed on item {1}", name, item.Subject))\n  }\n}	0
16118767	16118296	How to send a single quote to an input element with Selenium?	IWebDriver driver = new FirefoxDriver();\n        driver.Navigate().GoToUrl("http://www.google.com");\n        var element = driver.FindElement(By.Name("q"));\n        element.Clear();\n        element.SendKeys("one quote: ', double quote \"");	0
26529117	26528615	deploying windows service make	You must have compiled your exe either for .Net 4.5 or for 64-bit architecture (or both). This is the explanation of error code you run into from WinError.h:\n\n// %1 is not a valid Win32 application.\n//\n#define ERROR_BAD_EXE_FORMAT             193L\nMake sure you have compiled it for x86 platform or Any CPU, and whatever version of .Net Framework you compiled against is installed on the machine.	0
6343918	6343881	How to convert date time in standard format	yourDate.ToString("dd-MM-yyyy HH:mm:ss");	0
18585572	18554160	Binding to DataGridView Datasource property with List(Of Entity) throw a null reference exception	public class FinalClassScoreModel\n{\n    private readonly FinalClassScore _finalClassScore;\n    private readonly Enroll _enroll;\n\n    public FinalClassScoreModel(FinalClassScore finalClassScore, Enroll enroll)\n    {\n        this._finalClassScore = finalClassScore;\n        this._enroll = enroll;\n    }\n\n    public int EnrollId\n    {\n        get\n        {\n            return this._finalClassScore.EnrollId;\n        }\n    }\n\n    public string StudentNo\n    {\n        get\n        {\n            return this._enroll.StudentNo;\n        }\n    }	0
12398248	12394351	c# Using GeckoFx 14 How to get started?	//Gecko.Xpcom.Initialize("C:\\tools\\xulrunner");	0
32161483	29550699	How do I display a Milkshape model?	foreach (var milkshapeGroup in Groups)\n        {\n            milkshapeGroup.verticesPhone = null;\n            var vertList = new List<VertexPositionNormalTexture>();\n            foreach (var ver in milkshapeGroup.vertices)\n            {\n                vertList.Add(new VertexPositionNormalTexture(ver.Position, ver.Normal, ver.texCoord1));\n            }\n            milkshapeGroup.verticesPhone = vertList.ToArray();\n        }	0
5779822	5779568	Reading column value in cell change event	UltraGridColumn ugc = myGrid.DisplayLayout.Bands[0].Columns[@"myColumnKey"];\n\nprivate void mygrid_CellChange(object sender, CellEventArgs e)\n{\n    if (StringComparer.OrdinalIgnoreCase.Equals(e.Cell.Column.Key, @"myColumnKey"))\n    {\n         //something like this\n         ugc [@"myColumnKey"][index];\n    }\n}	0
32489557	32489343	How to copy C# 3D jagged array	Foo[][][] firstFoo = new Foo[10][][];\nFoo[][][] fooToCopy = new Foo[firstFoo.Length][][];\n\ncopyFooArray(firstFoo, ref fooToCopy);	0
3802777	3802650	C#: How do i position a menuitem	Alignment = ToolStripItemAlignment.Right	0
33779087	33778879	How to fetch table records by table name?	var table = (IEnumerable)context.GetType().GetProperty(tableName).GetValue(context, null);\n\nList<object> results = new List<object>();\n\nforeach(var line in table)\n{\n    var value = line.GetType().GetProperty(propertyName).GetValue(line, null);\n\n    if(value == searchValue) {\n        results.Add(line);\n    }\n}	0
30344059	30343396	Parsing of Message field of Event Log entry c#	string fieldName = "Workstation Name";\nvar expression = new Regex(string.Format(@"\s*{0}:\s*-\s*(.+)\r\n", fieldName));\nMatch match = expression.Match(fileText);\n\nif (match.Success)\n{\n  string workstationName = match.Groups[1];\n  ...\n}	0
31704013	31701663	Using a comma in a 'double' with Math Round	ToString("N2")	0
25446729	25446364	How to identify missing ConfigurationElement?	var sections = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections;\nvar exists = sections.Cast<ConfigurationSection>()\n                .Any(x => x.SectionInformation.Type.StartsWith("MissingConfigElementTest.MyConfigurationSection"));	0
32709461	32709031	Compare two list items together	var supervisorStudents = researchers.Where(r => r.supervisor_id == 0).\n            ToDictionary(supervisor => supervisor.id, supervisor => \n                researchers.Where(student => student.supervisor_id == supervisor.id).Select(student => student.id).Count());	0
19643625	19631164	How can i open an existing model from external application	PdCommon.Application    pdApplication;\n PdPDM.Model             pdModel;\n\n pdApplication = new PdCommon.Application();\n pdModel = (PdPDM.Model)pdApplication.OpenModel(@"C:\SVN\RAS_DB_Control\trunk\Northwind - MS\Model\Northwind.pdm");	0
15756020	15755996	bind data to telerik datagrid in asp.net	gridCommon.DataSource = DbContext.MTO_General_Commons.ToList();\ngridCommon.DataBind();	0
4117816	4117757	c# simple xml reader skips every other element	case "tilecol": \n{ \nConsole.WriteLine("col found");\nreader.Read();\nfloat.TryParse(reader.Value, out currentTexture);\ncurrentCol = currentCol + 1;\nbreak;\n}	0
17179257	17179191	Get properties with attribute	myObject.GetType().GetProperties()	0
3016433	3015797	asp.net server controls	[ParseChildren(true, "Parameters")]	0
24139772	24139471	How to login in app using facebook WP8?	Facebook.Client.FacebookSessionClient.LoginWithApp()	0
23259848	23257771	passing input text from view to contoller with FacebookContext using Facebook app	[HttpPost]\n[FacebookAuthorize("email", "user_photos")]\n    public async Task<ActionResult> Index(FormCollection form,FacebookContext context)\n    {\n        if (ModelState.IsValid)\n        {\n            string temp = form["txt"].ToString();\n            var user = await context.Client.GetCurrentUserAsync<MyAppUser>();\n\n// my code , I use txt here\n\n            return View(user);\n        }\n        return View("Error");\n    }	0
3924982	3924948	How to query a DataSet and set the result as a DataSource for some control? (C# winforms)	DataTable table = new DataTable();\ntable.Columns.Add("Fruit");\ntable.Columns.Add("ID", typeof(int));\ntable.Rows.Add(new object[] { "Lemon", 1 });\ntable.Rows.Add(new object[] { "Orange", 1 });\ntable.Rows.Add(new object[] { "Apple", 2 });\ntable.Rows.Add(new object[] { "Pear", 2 });\n\nBindingSource bs = new BindingSource();\nbs.DataSource = from row in table.AsEnumerable()\n                           where row.Field<int>("ID") == 1\n                           select new {Fruit = row.Field<string>("Fruit"), ID = row.Field<int>("ID")};\n\ndataGridView1.DataSource = bs;	0
4925769	4925730	A 'Binding' cannot be set on the 'Source' property of type 'Binding'	{Binding Path=Data, XPath=*, Converter={StaticResource stringToXmlDataProviderConverter},ConverterParameter=/root}	0
29249945	29249829	C# - How do I remove a file from the recent documents list in word?	object oMissing = System.Reflection.Missing.Value;\nobject oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ \n\n//Start Word and create a new document.\nWord._Application oWord;\nWord._Document oDoc;\noWord = new Word.Application();	0
13127655	13127597	XML - From SQL Server to LINQ to XML	XDocument doc = XDocument.Parse(dataTable.Rows[r]["info"].ToString());	0
29438305	29430879	Xamarin custom UITableViewCell throws System NullReferenceException	public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)\n{\n    var cell = (MainMenuCell)tableView.DequeueReusableCell("MainMenuCell");\n    cell.SetCellData();\n\n    return cell;\n}	0
2983856	2983810	Does MS Test provide a default value equals comparison?	Assert.AreEqual(orderA.ID, orderB.ID);    \nAssert.AreEqual(orderA.CustomerID, orderB.CustomerID);\nAssert.AreEqual(orderA.OrderDate, orderB.OrderDate);	0
13856198	13853045	how to show progress bar in monotouch while reading json file using http request	this.View.Add (loadingOverlay);\nThreadPool.QueueUserWorkItem (() =>\n{\n    Getjsondata("http://polarisnet.my/polaristouchsales/Import/Products/product.json");\n    BeginInvokeOnMainThread (() =>\n    {\n        loadingOverlay.Hide ();\n    });\n});	0
31047641	31047433	Generic repository with generic Id - how to retrieve when int	return Context.Set<TDomainObject>().Find(id);	0
31248835	31248759	How to add a event handler to a ToolStripButton in C# code?	pluginButton.Click += StartPlugin; // not StartPlugin()\nprivate void StartPlugin(object sender, EventArgs e)\n{\n    PluginPage plgp = new PluginPage();\n    plgp.Show();\n    plgp.Text = PlgTitle2;\n}	0
4173660	4173567	How can I make a delegate refer to a specific version of a method?	Reflection.Emit	0
12830494	12830383	Select all nodes	XmlNodeList XList = XDoc.SelectNodes("//*");	0
27513534	27513416	Does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument	....\nforeach (DataRow dr in dt.Rows)\n{\n    dataclass dc = new dataclass();\n    dc.idd = dr["idd"].ToString();\n    dc.datetime = dr["datetime"].ToString();\n    dc.col1 = dr["col1"].ToString();\n    dc.col2 = dr["col2"].ToString();\n    dc.col3 = dr["col3"].ToString();\n    returndata.Add(dc);\n}\n...	0
1299738	1299723	c# function, validate url within mvc app	if (!string.IsNullOrEmpty(inputUrl))	0
7269077	7269004	Share a variable to be used by two function without making it global	public class ClosureProvider {\n  private Foo shared;\n\n  public Func<object> GetFirst() {\n    return new Func<object>(() => { /* Use shared and whatever else */ });\n  }\n\n  public Action<Bar> GetSecond() {\n    return new Action<Bar>(bar => { /* Use shared and whatever else */ });\n  }\n}	0
9248257	9247756	Custom textbox control	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        if (textBox1.Text == "")\n            ChangeTextBoxtoWatermark();\n    }\n\n    private void textBox1_MouseEnter(object sender, EventArgs e)\n    {\n        if (textBox1.Text == "username")\n        {\n            textBox1.Text = "";\n            textBox1.Font = new Font(this.Font, FontStyle.Regular);\n            textBox1.BackColor = Color.White;\n        }\n    }\n\n    private void textBox1_MouseLeave(object sender, EventArgs e)\n    {\n        if (textBox1.Text == "")\n            ChangeTextBoxtoWatermark();\n    }\n\n    private void ChangeTextBoxtoWatermark()\n    {\n        textBox1.Font = new Font(this.Font, FontStyle.Italic);\n        textBox1.BackColor = Color.LightYellow;\n        textBox1.Text = "username";\n    }	0
26368754	26368681	Sorting an array of strings containing dates by dates descending	var orderedList = listOfItems\n    .OrderByDescending(item => {\n        if (item.Name.Length < 15)\n            return DateTime.MinValue;\n\n        var datePart = item.Name.Substring(item.Name.Length - 15, 10);\n        DateTime date;\n        if (!DateTime.TryParse(datePart, out date))\n            return DateTime.MinValue;\n\n        return date;\n    })\n    .ToList();	0
2786221	2786208	How can we create a parameterized properties in C#	public class MyConnectionStrings\n{\n    private string GetConnectionString(string connectionName) { ... }\n\n    public string this[string connectionName]\n    {\n        get { return GetConnectionString(connectionName); }\n    }\n}	0
24562351	24562314	DefaultHttpControllerSelector does not contain a constructor that takes 0 arguments	public NamespaceHttpControllerSelector(HttpConfiguration config)\n    : base(config)\n{\n}	0
19164707	19164635	Can you set/update a value in real-time within a LINQ statement during iteration?	sourceList.Reverse()\n    .TakeWhile(o =>  { \n             ... fairly arbitrary code here\n             return someValue;\n         })\n    .FirstOrDefault(o => ...);	0
17713867	17713613	Is this instance of B a property of an instance of A?	public class ZZZ\n{\n  public string foo() { return ImAPropertyOfAnAAADerivedClass ? "yes" : "no"; }\n\n  bool ImAPropertyOfAnAAADerivedClass \n  {\n      get { return TestForAAA is AAA; }\n  }\n\n  public object TestForAAA { get; set; }\n}	0
12769999	12729909	Paragraph shows as child of another element even after RichTextbox clear	foreach (Paragraph item in paras)\n        {\n            Page1.Blocks.Remove(item);\n        }	0
30378981	30378779	Use one instance in multiple components with Autofac	builder.RegisterType<ApplicationDbContext>()\n       .AsSelf() \n       .As<IApplicationDbContext>()\n       .InstancePerRequest();	0
2158184	2158160	Prevent other classes from altering a list in a class	public class SomeClass()\n{\n    private List<string> someList;\n    public IList<string> SomeList { \n        get { return someList.AsReadOnly(); }\n    }\n}	0
16831320	16831248	Changed database from SQL Server 2005 to SQL Server 2008	using System;	0
6032362	5950757	Uninstall software via the registry	msiexec /x {GUID}	0
24425659	24425631	Select items from List A where the property is not in List B	List<Guid> excludeGuid = ..... // You init guids you want to exclude\nList<Broadcast> result = Broadcasts.Where(x => !excludeGuid.Contains(x.Guid)).ToList() ;	0
13413452	13339957	Automatic serialization with Linq to Sql	public sealed class SettingsModel\n{\n    // ...\n\n    public static SettingsModel Parse(string source)\n    {\n        SettingsModel res;\n\n        // Deserialise the object\n\n        return res;\n    }\n}	0
30639653	30639288	How do I get list of all users in TFS 2013	TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("url"));\n        tfs.EnsureAuthenticated();\n\n        IGroupSecurityService gss = tfs.GetService<IGroupSecurityService>();\n\n        Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, "Project Collection Valid Users", QueryMembership.Expanded);\n\n        Identity[] UserId = gss.ReadIdentities(SearchFactor.Sid, SIDS.Members, QueryMembership.None);\n\n        foreach (Identity user in UserId)\n        {\n            Console.WriteLine(user.AccountName);\n            Console.WriteLine(user.DisplayName);\n        }	0
13455078	13454699	How to register areas for routing	public static void RegisterRoutes(RouteCollection routes)\n{\n    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n    AreaRegistration.RegisterAllAreas();\n    ....\n}	0
23798267	23797968	Data structure for this type of object	int[110,14] myItems = new int[110,14];\n                //to increment certain object like ith object with jth object of object\n                 myitems[i,j]++;\n                 //finally loop like this to print\n                for(int i = 0 ; i < 110 ; i++)\n                   for(int j = 0 ; j < 14 ; j++\n                      Console.WriteLine(myitems[i,j];	0
7333054	7328459	LINQ2SQL Updating Database but only when I view in SQL Server	PositionAttachment positionAttachment = new PositionAttachment(); \n    positionAttachment.Position = positionModel; \n    positionAttachment.Attachmen = attachment;	0
723349	684438	MS Word Plugin, Adding a button which pops up on right click on selected text	Microsoft.Office.Core.CommandBar cellbar = diff.CommandBars["Text"];\nMicrosoft.Office.Core.CommandBarButton button = (Microsoft.Office.Core.CommandBarButton)cellbar.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 0, "MYRIGHTCLICKMENU", Missing.Value, Missing.Value);\nif (button == null)\n{\n   // add the button\n   button = (Microsoft.Office.Core.CommandBarButton)cellbar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Missing.Value, Missing.Value, cellbar.Controls.Count + 1, true);\n   button.Caption = "My Right Click Menu Item";\n   button.BeginGroup = true;\n   button.Tag = "MYRIGHTCLICKMENU";\n   button.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(MyButton_Click);\n}	0
13557790	13557733	How to Send Ctrl+Shift+F1 to an application using send keys	System.Windows.Forms.SendKeys.Send("^+{F1}");	0
1024223	1024211	Get Value of Row in Datatable c#	for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)\n{\n    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;\n}	0
22971612	22923132	Generic Deserialization of ContractData: returning a type of 'T' from the exception handler	public T DeserializeContractData<T>(HttpContext context) where T: new()\n    {\n        try\n        {\n            using (var inputStream = new StreamReader(context.Request.InputStream))\n            {\n                var json = inputStream.ReadToEnd();\n                return JsonConvert.DeserializeObject<T>(json);\n            }\n        }\n        catch (JsonSerializationException e)\n        {\n            //maybe do some logging...\n            return default(T);\n        }\n    }	0
21321771	21321474	Search SQL Server database with multiple text box values with search button	var query = db.Swims;\n\n// ID overrides all others, since it is unique no point adding more filters unless\n// you want to not return the row if the other filters don't match?\nif (IdTextBox.Text.Length > 0)\n{\n    int id = Convert.ToInt32(IdTextBox.Text);\n    query = query.Where(s => s.Id == id);\n}\nelse\n{\n    if (FirstNameTextBox.Text.Length > 0)\n    {\n        query = query.Where(s => s.FirstName.Contains(FirstNameTextBox.Text));\n    }\n    if (LastNameTextBox.Text.Length > 0)\n    {\n        query = query.Where(s => s.LastName.Contains(LastNameTextBox.Text));\n    }\n    if (PhoneTextBox.Text.Length > 0)\n    {\n        query = query.Where(s => s.Phone.Contains(PhoneTextBox.Text));\n    }\n}\n\nGridView1.DataSource = query.ToList();	0
28274842	28237745	How to ignore destination member with AutoMapper?	Mapper.CreateMap<MyModel, MyDto>()\n.ForMember(model=> model.IgnoreModel, option => option.Ignore());\n\nMapper.CreateMap<MyDto, MyModel>()\n.ForMember(model=> model.IgnoreDto, option => option.Ignore());	0
7385885	7385836	LINQ to SQL omit field from results while still including it in the where clause	(from record in db.table\nwhere record.z == 35\nselect new table {\n    a = record.a,\n    b = record.b,\n    c = record.c\n}).Distinct();	0
19488678	19488379	Saving ArrayList values to XML C#	ArrayList sampleList = new ArrayList();\n    sampleList.Add(" ");\n    //Add your elements\n\n    //StreamWriter initialized with append mode\n    StreamWriter streamwriter = new StreamWriter(" INSERT PATH OF XML HERE ", true);\n\n    for (int i = 0; i < sampleList.Count; i++)\n    {\n        //Elements are written into the file here, remember not to forget the xml structure \n        streamwriter.WriteLine(sampleList[i]);\n    }\n\n    //You have to close the streamwriter or you have to flush to make sure the text is saved\n    streamwriter.Close();	0
9218728	9218467	Out of these two ways to chain extension methods, is there any reason to use one over the other?	public class Foo\n{\n    public void MyExtensionMethod(Bar bar)\n    {\n        Console.WriteLine("instance method");\n    }\n}	0
3052837	3051039	Building a QueryExpression where name field is either A or B	ColumnSet columns = new ColumnSet();\ncolumns.Attributes = new string[]{ "event_name", "eventid", "startdate", "city" };\n\nConditionExpression eventname1 = new ConditionExpression();\neventname1.AttributeName = "event_name";\neventname1.Operator = ConditionOperator.Equal;\neventname1.Values = new string[] { "Event A" };\n\nConditionExpression eventname2 = new ConditionExpression();\neventname2.AttributeName = "event_name";\neventname2.Operator = ConditionOperator.Equal;\neventname2.Values = new string[] { "Event B" };\n\nFilterExpression filter = new FilterExpression();\nfilter.FilterOperator = LogicalOperator.Or;\nfilter.Conditions = new ConditionExpression[] { eventname1, eventname2 };\n\nQueryExpression query = new QueryExpression();\nquery.ColumnSet = columns;\nquery.EntityName = EntityName.mbs_event.ToString();\nquery.Criteria = filter;\n\nRetrieveMultipleRequest request = new RetrieveMultipleRequest();\nrequest.Query = query;\n\nreturn (RetrieveMultipleResponse)crmService.Execute(request);	0
9828368	9827798	Team Foundation Server 2010 API	TfsTeamProjectCollection projectCollection = new TfsTeamProjectCollection(new Uri("http://tfs.mycompany.com:8080/tfs/DefaultCollection"));\nVersionControlServer vc = projectCollection.GetService<VersionControlServer>();\n\n/* Get all pending changesets for all items (note, you can filter the items in the first arg.) */\nPendingSet[] pendingSets = vc.GetPendingSets(null, RecursionType.Full);\n\nforeach(PendingSet set in pendingSets)\n{\n    /* Get each item in the pending changeset */\n    foreach(PendingChange pc in set.PendingChanges)\n    {\n        Console.WriteLine(pc.ServerItem + " is checked out by " + set.OwnerName);\n    }\n}	0
9678013	9677919	URL Encoding with capital letters	public static string UpperCaseUrlEncode(this string s)\n{\n    char[] temp = HttpUtility.UrlEncode(s).ToCharArray();\n    for (int i = 0; i < temp.Length - 2; i++)\n    {\n        if (temp[i] == '%')\n        {\n            temp[i + 1] = char.ToUpper(temp[i + 1]);\n            temp[i + 2] = char.ToUpper(temp[i + 2]);\n        }\n    }\n    return new string(temp);\n}	0
6908308	6908124	Modify rows added into dataset	if (dataset1.Tables[0].Rows[0][0].ToString() == "Y")\n{\n    for (int i = 0; i < dataset2.Tables[0].Rows.Count - 1; i++)\n    {\n        dataset1.Tables[0].ImportRow(dataset2.Tables[0].Rows[i]);\n    }\n}	0
25157759	25157488	Using firefox to open c# url button not default browser	System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe", "http://yoursite.com/dummy.htm");	0
4600809	4600700	How to Read texfile etch.. from Application folder where Application is Installed?	string StartPath = Application.StartupPath; //or what SilverbackNet suggested\nstring FileName = "YourFileName.txt"\n\nTextreader tr = new StreamReader(StartPath+ "\\" + FileName);\n\nConsole.WriteLine(tr.ReadLine());\n\ntr.Close();	0
15186560	15186470	How do I prevent my app from launching over and over again	static void Main() \n{\n    Process currentProcess = Process.GetCurrentProcess();\n    var runningProcess = (from process in Process.GetProcesses()\n                          where\n                            process.Id != currentProcess.Id &&\n                            process.ProcessName.Equals(\n                              currentProcess.ProcessName,\n                              StringComparison.Ordinal)\n                          select process).FirstOrDefault();\n    if (runningProcess != null)\n    {\n        ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);\n       return; \n    }\n}	0
8347216	4080939	MOQ - setting up a method based on argument values (multiple arguments)	mock.Setup(x => x.Method(It.IsAny<int>(), It.IsAny<int>()).Returns<int, int>((a, b) => \n     {return a < b;});	0
21579191	21578810	Flashing GameObject in Unity	public GameObject flashing_Label;\n\npublic float interval;\n\nvoid Start()\n{\n    InvokeRepeating("FlashLabel", 0, interval);\n}\n\nvoid FlashLabel()\n{\n   if(flashing_Label.activeSelf)\n      flashing_Label.SetActive(false);\n   else\n      flashing_Label.SetActive(true);\n}	0
7335641	7335474	extjs/c# - how to save data from a form to a database?	url: 'update.ashx',\nparams: {action: 'update'},\nsuccess: function (form, action) {	0
15723889	15723559	Displaying results in table of data in a ListBox from TextBoxes	listbox.Items.Add("Day 1, Approximate Population:" + txtStartingNumberOfOrganisms.Text);\n        int ApproximatePopulation = Convert.ToInt16(txtStartingNumberOfOrganisms.Text);             \n\n        for (int i = 2; i <= numOfDays; i++)\n        {\n            ApproximatePopulation = ApproximatePopulation + ((ApproximatePopulation * Convert.ToDouble(txtDailyIncrease.text)) / 100);\n            listbox.Items.Add("Day " + Convert.ToString(i) + ", Approximate Population:" + Convert.ToString(ApproximatePopulation));\n        }	0
16253773	16253424	How to add string elements in dropdown list in Windows form c#?	class Enum1\n{\n    public class UnderGraduate\n    {\n        public static string[] EducationUG=new string[]{\n            "Bachelor of Arts (B.A)",\n            "Bachelor of Arts (Bachelor of Education (B.A. B.Ed)",\n            "Bachelor of Arts (Bachelor of Law (B.A.B.L)",\n            "Bachelor of Arts (Bachelor of Law (B.A.LLB)",\n            "Bachelor of Ayurvedic Medicine and Surgery (B.A.M.S)",\n            "Bachelor of Applied Sciences (B.A.S)"}\n    }\n}\n\n\nprivate void edulvlcb_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (edulvlcb.SelectedItem.ToString() == "UnderGraduate")\n    {         \n        educb.Items.Clear();\n        foreach (string ug in Enum1.UnderGraduate.EducationUG)\n            educb.Items.Add(ug);\n    }\n}	0
7168286	7168192	Default class name showing up when no data is present in DataGrid	ItemsSource="{Binding}"	0
9143874	9143814	Two for loops written as a while loop for assign values to a symmetric matrix	int k=0;\nfor (int i = 0; i < size; i++){\n     for (int j = 0; j <= i && reader.Read(); j++){                \n          Q[i, j] = Q[j, i]= reader.GetDouble(1);\n     }\n}	0
2535069	2535007	Selecting columns with linq with nested dictionary	Dictionary<int, Dictionary<int, string>> _cells;\nvar cols = _cells.Select(p => p.Value)\n                 .Where(d => d.Key == 2)\n                 .SelectMany(d => d.Select(p => p.Value));	0
25148343	25148184	Storing a collection of entities without traversing the collection	using (DBEntities context = new DBEntities())\n        {\n            foreach (var singular in plural)\n            {\n                context.EntitiDB.Add(singular); \n            }\n            context.SaveChanges();\n        }	0
6399745	6399692	How do I get ReSharper to stop placing explicit access modifiers on my MSpec members?	Use explicit private modifier	0
4636436	4636413	Split an IP address into four separate values	string ip = "192.168.0.1";\n        string[] values = ip.Split('.');	0
10608056	10607831	Unstoppable Timer	class Program\n{\n    public static int t = 2;\n    static System.Timers.Timer aTimer = new System.Timers.Timer();\n\n    public static void Main()\n    {\n\n        // Hook up the Elapsed event for the timer.\n        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n        aTimer.Interval = 1000;\n        aTimer.Enabled = true;\n\n        Console.ReadLine();\n    }\n    public static void OnTimedEvent(object source, ElapsedEventArgs e)\n    {\n        Console.WriteLine("Time remianing..{0}", t);\n        t--;\n\n        if (t == 0)\n        {\n            Console.WriteLine("\a");\n            Console.WriteLine("Time to check their vitals, again!");\n            Console.WriteLine("Press any key to exit...");\n            aTimer.Stop();\n            Console.ReadLine();\n        }\n    }\n}	0
9606524	9606447	How to open a new page using sessionid and response object	public ActionResult Foo()\n{\n    HttpCookie mycookie = new HttpCookie("xyz");\n    mycookie.Value = sessionId;\n    mycookie.Expires = DateTime.Now.AddHours(9);\n    Response.AppendCookie(mycookie);\n    ...\n}	0
18410822	18410799	How send a command to command prompt from a console application	Process.Start("shutdown", "-s");	0
14695485	14695243	Editing HTML via asp.net	if (Security.IsLoggedIn())\n{\n  myIncludeFile.Visible = true;\n}\nelse\n{\n  myIncludeFile.Visible = false;\n}	0
28752039	28752009	c# create a method where default parameters do not need to be entered	methodName(c: 8);	0
27163279	27163091	How can I get the sum total of a column in the gridview to a textbox outside the gridview?	private void GrandTotal()\n    {\n     float GTotal = 0f;\n     for (int i = 0; i < GridView1.Rows.Count; i++)\n     {\n        String total = (GridView1.Rows[i].FindControl("lblTotal") as Label).Text;\n        GTotal += Convert.ToSingle(total);\n     }\n     txtTotal.text=GTotal.toString();\n    }	0
10992048	10976026	Get Data From .docx file like one big String in C# 	using (ZipFile zip = ZipFile.Read(filename))\n{\n    MemoryStream stream = new MemoryStream();\n    zip.Extract(@"word/document.xml", stream);\n    stream.Seek(0, SeekOrigin.Begin); \n    XmlDocument xmldoc = new XmlDocument();\n    xmldoc.Load(stream);\n    string PlainTextContent = xmldoc.DocumentElement.InnerText;\n}	0
26333902	26333770	how to redirect from a page in a folder to the page in root directory?	Response.Redirect("~/mainhome.aspx");	0
29613692	29569711	Download from the Alfresco to a local folder	BufferedStream document = (BufferedStream)content.Stream;\n\n        string path = @"C:\Windows\Temp\" + docx.Name;\n\n        using (FileStream stream = File.Create(path))\n        {\n            document.CopyTo(stream);\n        }	0
32153916	32153688	how do i print letters like AAA001 to zzz999 in C#	for (int i1 = 'A'; i1 <= 'Z'; i1++)\n{\n    for (int i2 = 'A'; i2 <= 'Z'; i2++)\n    {\n        for (int i3 = 'A'; i3 <= 'Z'; i3++)\n        {\n            for (int i4 = '0'; i4 <= '9'; i4++)\n            {\n                for (int i5 = '0'; i5 <= '9'; i5++)\n                {\n                    for (int i6 = '0'; i6 <= '9'; i6++)\n                    {\n                        Console.WriteLine(new string(new Char[] { (Char)i1, (Char)i2, (Char)i3, (Char)i4, (Char)i5, (Char)i6 }));\n                    }\n                }\n            }\n        }\n    }\n}	0
800404	495380	C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account)	public static bool ThisPointIsOnOneOfTheConnectedScreens(Point thePoint)\n{\nbool FoundAScreenThatContainsThePoint = false;\n\nfor(int i = 0; i < Screen.AllScreens.Length; i++)\n{\nif(Screen.AllScreens[i].Bounds.Contains(thePoint))\nFoundAScreenThatContainsThePoint = true;\n}\nreturn FoundAScreenThatContainsThePoint;\n}	0
1617265	1617260	C# - Count string length and replace each character with another	string newString = new string('*', oldString.Length);	0
11693875	11689240	LINQ: List of tuples to tuple of lists	Tuple<List<A>, List<B>> Unpack<A, B>(List<Tuple<A, B>> list)\n{\n    return list.Aggregate(Tuple.Create(new List<A>(list.Count), new List<B>(list.Count)),\n                          (unpacked, tuple) =>\n                          {\n                              unpacked.Item1.Add(tuple.Item1);\n                              unpacked.Item2.Add(tuple.Item2);\n                              return unpacked;\n                          });\n}	0
9360428	8572100	How to increase the font size in a pdf using c# with wkhtmltopdf?	switches +="--disable-smart-shrinking";	0
27760035	27759726	How to draw completely monocolor text with use of Graphics.DrawString?	Bitmap bmp = new Bitmap(300, 50);\n        Graphics gfx = Graphics.FromImage(bmp);\n\n        gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;\n        gfx.DrawString("Why I have black outer pixels?", new Font("Verdana", 14),\n            new SolidBrush(Color.White), 0, 0);\n        gfx.Dispose();\n        bmp.Save(Application.StartupPath + "\\test.png", ImageFormat.Png);	0
1309304	1295417	AccExplorer doesn't find new controls / thinks old controls are still around	AutomationElement a, b;\nProcess p;\nProcess[] existingProcesses;\nIAccessible c;\n\nexistingProcesses = Process.GetProcessesByName("OurApp");\nif (existingProcesses.Length > 0) {\n  p = existingProcesses[0];\n  a = AutomationElement.FromHandle(p.MainWindowHandle);\n  b = a.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "LeftNavExplorerBarGroups"));\n  c = MSAA.GetAccessibleObjectFromHandle(new IntPtr(b.Current.NativeWindowHandle));\n}	0
9803013	9802977	Fixed Table in Winforms c#	TableLayoutPanel panel = new TableLayoutPanel();\npanel.Controls.Add(new TextBox(), 1, 1);	0
32395467	32395391	How to map tinyint to c# byte using entityframework code first migration	[Column("AuthorisationStatus")]\npublic byte AuthorisationStatusByte\n{\n    get { return (byte) AuthorisationStatus; }\n    set { AuthorisationStatus = (TriState) value; }\n}	0
2891738	2891686	Set form backcolor to custom color	this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish	0
20249187	20248664	Pull out replaceable fields from a string	static void Main(string[] args)\n    {\n        String str = "{dog} and the {cat}";\n        String[] ret = ExtractTagValue(str);\n    }\n\n    public static String[] ExtractTagValue(String input)\n    {\n        List<String> retLst = new List<string>();\n\n        String pattern = "(\\{.*?\\})";\n        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);\n\n        System.Text.RegularExpressions.MatchCollection matches = regex.Matches(input);\n        if (matches.Count > 0)\n        {\n\n\n            foreach (Match match in matches)\n            {\n                retLst.Add(match.Value);\n            }\n        }\n\n        return retLst.ToArray();\n    }	0
29063281	29062295	Access vector3 from another script in unity c#?	using UnityEngine;\nusing System.Collections;\n\npublic class Movement : MonoBehaviour {\n\n    public Vector3 thumbStickInput;\n    public PlayerInput gcPlayerInput;\n\n    Vector3 targetRotation;\n    public GameObject TankTurret, TankBase, Player;\n\n\n    // Use this for initialization\n    void Start () {\n\n\n        gcPlayerInput = Player.GetComponent<PlayerInput>(); // removed var\n        // now it's cached and you can use it on update    \n\n    }\n\n    // Update is called once per frame\n    void Update () {\n\n        // var gcPlayerInput = Player.GetComponent<PlayerInput>(); // <-- BAD! ---- removed\n        thumbStickInput = gcPlayerInput.thumbStickInput; <-- BAD.\n\n\n\n        if (thumbStickInput != Vector3.zero) {\n\n            targetRotation = thumbStickInput;\n            TankTurret.transform.rotation = Quaternion.LookRotation(targetRotation);\n\n            print (thumbStickInput);\n        }\n}\n}	0
11935915	11932237	Show toolbar via ToolStripDropDownButton.DropDownItems?	((ToolStripDropDownMenu)myToolbar.DropDown).ShowCheckMargin = false;\n  ((ToolStripDropDownMenu)myToolbar.DropDown).ShowImageMargin = false;	0
25397950	25397851	Windows application - Just Starting	.Net framework	0
27860709	27860678	How to append double quote character to a string?	string csProperty = string.Format("public string {0} {{ get {{ return {1}; }} }}", propName, quote + propVal + quote);	0
15934567	15933155	Validation error being thrown on valid input in MVC 4 App	[HttpPost]\npublic ActionResult AddQuantity(Quantity model)	0
26842100	26841074	Not able to retrieve text from the textbox using webdriver	findElement(By.id("someid")).getAttribute("value");	0
3082168	3082145	Get the window from a page	var wnd = Window.GetWindow(this);	0
8612351	8611800	How to read xml With .Net 2.0	DataSet dst = new DataSet();\n    dst.ReadXmlSchema("C:\\sdn.xsd");\n    dst.ReadXml("C:\\sdn.xml");\n\n    // Now you have list of tables that contain all information you need.\n    // For example punlishinformation\n    DataTable dtPubInfo  = dst.Tables["publshInformation"];\n    string publishdateInfo = dtPubInfo.Rows[0]["Publish_Date"].ToString();\n    string recordCount = dtPubInfo.Rows[0]["Record_Count"].ToString();\n\n    DataTable dtsdnEtry = dst.Tables["sdnentry"];\n    // GEt all SDN entry\n    DataColumnCollection colColumns = dtsdnEtry.Columns;\n        foreach(DataRow dr in dtsdnEtry.Rows)         \n                {\n                    foreach(DataColumn dc in colColumns){\n                            Console.WriteLine(dc.ColumnName + " - "  + dr[dc.ColumnName].ToString());\n                        }\n                    Console.WriteLine("--------------------------------------------------");\n                }	0
3782665	3780607	How do you get a different Context Menu if you Lt-Click or Rt-Click on a notify icon?	private void niTrayIcon_MouseClick(object sender, MouseEventArgs e)\n{\n    if (e.Button == System.Windows.Forms.MouseButtons.Left)\n    {\n        niTrayIcon.ContextMenuStrip = cmsTrayLeftClick;\n        MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);\n        mi.Invoke(niTrayIcon, null);\n        niTrayIcon.ContextMenuStrip = cmsTrayRtClick;\n    }\n}	0
11545592	11545543	Pass in default value as optional parameter in C#	private void DoSomething();	0
28010264	28010090	Update multiple colums into one column as string	INSERT INTO Table2(NUM, Columnc)\nSELECT num, GROUP_CONCAT(DISTINCT CONCAT(columna,',',columnb)) name\nFROM table1\ngroup by num	0
13662643	13662603	match regex character to function call	Regex.Matches("0129384927377","7").Count	0
23022354	23022256	How to use async await in asp.net membership provider ValidateUser method?	public Task SleepAsync(int millisecondsTimeout) \n{ \n    return Task.Run(() => Sleep(millisecondsTimeout)); \n}	0
11061660	11061537	How to get status of HP Scanner 5590 Flatbed in c#.net?	ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_PnPEntity");\n            ManagementObjectCollection coll = searcher.Get();\n\n            foreach (ManagementObject any in coll)\n            {\n                   // Check for device name\n            }	0
10927497	10927366	how to get count of the repeated values xml element in wpf	var count = student.GetElementsByTagName("Chandru").Count;	0
31236366	31236254	Find the average. largest, smallest number and mode of a int array	public static double LargestNumber(int[] Nums, int Count)\n{\n    double max = Nums[0];\n\n    for (int i = 1; i < Count; i++)\n        if (Nums[i] > max) max = Nums[i];\n\n    return min;\n}\npublic static double SmallestNumber(int[] Nums, int Count)\n{\n    double min = Nums[0];\n\n    for (int i = 1; i < Count; i++)\n        if (Nums[i] < min) min = Nums[i];\n\n    return min;\n}\npublic static double Mode(int[] Nums, int Count) \n{\n    double mode = Nums[0];\n    int maxCount = 1;\n\n    for (int i = 0; i < Count; i++) \n    {\n       int val = Nums[i];\n       int count = 1;\n       for (int j = i+1; j < Count; j++)\n       {\n          if (Nums[j] == val) \n             count++;\n       }\n       if (count > maxCount) \n       {\n            mode = val;\n            maxCount = count;\n       }\n    }\n    return mode;\n}	0
11853678	11853645	Save text from textbox to memorystream?	MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(myTextBox.Text))	0
1943293	1943273	Convert all first letter to upper case, rest lower for each word	string s = "THIS IS MY TEXT RIGHT NOW";\n\ns = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.toLower());	0
33445088	33291043	Stored procedure with multiple result sets very slow	var cmd = db.Database.Connection.CreateCommand();\ncmd.CommandText = "[dbo].[GetAllBlogsAndPosts]";\ndb.Database.Connection.Open();\nvar reader = cmd.ExecuteReader();\n\n// Read first result set\nvar blogs = ((IObjectContextAdapter)db).ObjectContext.Translate<EFStoredProcJit.Blog>(reader, "Blogs", MergeOption.AppendOnly);\n\n// Read 2nd result set\nreader.NextResult();\nvar posts = ((IObjectContextAdapter)db).ObjectContext.Translate<EFStoredProcJit.Post>(reader, "Posts", MergeOption.AppendOnly);	0
2168817	2168798	C# 4.0: Can I use a TimeSpan as an optional parameter with a default value?	void Foo(TimeSpan? span = null) {\n\n   if (span == null) { span = TimeSpan.FromSeconds(2); }\n\n   ...\n\n}	0
25208480	25207267	How to return data from two tables in one resource with Web API, MVC5 via Repository	[HttpGet, Route("activities/{id:int}/assignments")]\npublic List<Assignment> List(int id, int page = 1, int pageSize = 50) {\n     List<Assignment> assignments = new List<Assignment>();\n     assignments.AddRange(Repository.GetStudentAssignments(id).ToExternal(page, pageSize));\n     assignments.AddRange(Repository.GetTeacherAssignments(id).ToExternal(page, pageSize));\n\n     return assignments;\n}	0
11976285	11976248	Using variables to refer to array indices in C#	public string A { get { return letters[0]; } }	0
19505225	19500946	Cannot set some values of an usercontrol from the VS properties Window	Using g as Graphics = Graphics.FromWhereEver, \n           P as New Pen(ProgressBar_BorderColor), \n           Br as New SolidBrush(ProgressBar_BackColor)\n\n    ... draw and paint\n    ... paint and draw\nEnd Using          ' Graphics, Pen and Brush properly disposed of	0
8909699	8909317	DropdownList validation with AutoPostBack set to true inside updatepanel	if (ddlName.selectedValue == "-1")\n{\n    lblErr.text = "You have to select...";\n    lblErr.visible = true;\n}	0
18917406	18917270	How to use Linq to order within groups	var ordered = list.GroupBy(grp => grp.groupCode)\n   .SelectMany(g => g.OrderBy(grp => grp.item));	0
3050376	3050357	casting, converting, and input from textbox controls	Console.WriteLine(strawberryp_Textbox.Text);	0
31049764	26708647	how to send message to whatsapp number programmatically using C#	//Send ( button_click )\n        string from = "9199********";\n        string to = txtTo.Text;//Sender Mobile\n        string msg = txtMessage.Text;\n\n        WhatsApp wa = new WhatsApp(from, "BnXk*******B0=", "NickName", true, true);\n\n        wa.OnConnectSuccess += () =>\n        {\n            MessageBox.Show("Connected to whatsapp...");\n\n            wa.OnLoginSuccess += (phoneNumber, data) =>\n            {\n                wa.SendMessage(to, msg);\n                MessageBox.Show("Message Sent...");\n            };\n\n            wa.OnLoginFailed += (data) =>\n            {\n                MessageBox.Show("Login Failed : {0}", data); \n            };\n\n            wa.Login();\n        };\n\n        wa.OnConnectFailed += (ex) =>\n        {\n            MessageBox.Show("Connection Failed...");\n        };\n\n        wa.Connect();	0
8369938	8369903	Splitting a string by another string	var start = s.IndexOf("<TEXT>");\nvar end = s.IndexOf("</TEXT>", start+1);\nstring res;\nif (start >= 0 && end > 0) {\n    res = s.Substring(start, end-start-1).Trim();\n} else {\n    res = "NOT FOUND";\n}	0
5724652	5724639	Casting generics	public partial class FObjectSet<T> : ObjectSet<T> where T : class\n{\n...\n}\n\npublic partial class FContext : IContext, IDisposable\n{\n    public ObjectSet<T> CreateObjectSet<T>() where T : class\n    {\n        var fakeObjectSet = new FObjectSet<T>();\n        return fakeObjectSet;\n    }\n}	0
4503534	4503512	How to manage all unhandled errors in MVC controller	protected override void OnException(ExceptionContext filterContext)\n    {\n      //Build of error source.\n      string askerUrl = filterContext.RequestContext.HttpContext.Request.RawUrl;\n      Exception exToLog = filterContext.Exception;\n      exToLog.Source = string.Format("Source : {0} {1}Requested Path : {2} {1}", exToLog.Source, Environment.NewLine, askerUrl);\n      //Log the error\n      ExceptionLogger.Publish(exToLog, "unhandled", filterContext.RequestContext.HttpContext.Request.ServerVariables.ToString(), askerUrl);\n      //Redirect to error page : you must feed filterContext.Result to cancel already executing Action\n      filterContext.ExceptionHandled = true;\n      filterContext.Result = new ErrorController().ManageError(ErrorResources.GeneralErrorPageTitle, ErrorResources.GeneralErrorTitle, ErrorResources.GeneralErrorInnerBody, exToLog);\n      base.OnException(filterContext);\n    }	0
15873847	15873644	Save file from Richtextbox using Invoke	delegate void SaveNoteCallback(string path);\n\npublic void SaveNote(string path)\n{\n    if(_rtbContent.InvokeRequired)\n    {\n        SaveNoteCallback d = new SaveNoteCallback(SaveNote);\n        this.Invoke(d, new object[] {path});\n    }\n    else \n    {\n        _rtbContent.SaveFile(path, RichTextBoxStreamType.RichText);    \n    }\n}	0
30311489	30310134	Convert comma delimited string to int array	string nums = string.Join(",", Array.ConvertAll(s.Split(','), int.Parse));	0
24385191	24384851	How to create custom additional fields in UserProfile	[HttpPost]\n[AllowAnonymous]\n[ValidateAntiForgeryToken]\npublic async Task<ActionResult> Register(RegisterViewModel model)\n{\n    if (ModelState.IsValid)\n    {\n        var user = new ApplicationUser() { UserName = model.UserName, City = model.City  };\n        var result = await UserManager.CreateAsync(user, model.Password);\n        if (result.Succeeded)\n        {\n            await SignInAsync(user, isPersistent: false);\n            return RedirectToAction("Index", "Home");\n        }\n        else\n        {\n            AddErrors(result);\n        }\n    }\n\n    // If we got this far, something failed, redisplay form\n    return View(model);\n}	0
13338322	13338040	Combine two LINQ queries from different sources into single object	var jobList = from x in XDocument.Load(...\n              where ...\n              let clientId = getClientId((string)x.Element("name"))\n              select new SampleClient\n              {\n                  ClientId = clientId,\n                  JobName = (string)x.Element("name"),\n                  JobUrl = (string)x.Element("url"),\n                  Version = (string)XDocument\n                      .Load(GetSecondQueryUrl(clientId))\n                      .Root\n                      .Element(pom4 + "properties")\n                      .Element(pom4 + "product.version")\n              };	0
11117905	11117839	How can i use Function MenuItem in Function buttonCreate_Click	private string patheto = @"C:\temp";\n\nprivate void buttonCreate_Click(object sender, EventArgs e)\n{\n\n    string MyFileName = "Car.txt";\n\n    string newPath1 = Path.Combine(patheto, MyFileName);\n    // Create a folder in the active Directory\n    Directory.CreateDirectory(newPath1);\n}\n\nprivate void DirectoryPathToolStripMenuItem_Click(object sender, EventArgs e)\n{\n    Process.Start(patheto);\n}	0
5356440	5356257	Regex for find all start of method lines in .cs files in visual studio	public static Tuple<int, string, List<Tuple<int, string>>> DoSomething(<arbitrarily complex parameter list>)\n{\n}	0
3173913	3173750	Deleting previously written lines in Console	public static void ClearArea(int top, int left, int height, int width) \n{\n    ConsoleColor colorBefore = Console.BackgroundColor;\n    try\n    {\n        Console.BackgroundColor = ConsoleColor.Black;\n        string spaces = new string(' ', width);\n        for (int i = 0; i < height; i++)\n        {\n            Console.SetCursorPosition(left, top + i);\n            Console.Write(spaces);\n        }\n    }\n    finally\n    {\n        Console.BackgroundColor = colorBefore;\n    }\n}	0
40497	40465	How to get an array of distinct property values from in memory lists?	var bars = Foos.Select(f => f.Bar).Distinct().ToArray();	0
19226954	19226894	Replace \" in a string	var replaced = myString.Replace(@"\""", @"""")	0
424677	424669	How do I overload the [] operator in C#	public int this[int key]\n{\n    get\n    {\n        return GetValue(key);\n    }\n    set\n    {\n        SetValue(key,value);\n    }\n}	0
21988193	21988010	Regular expression to filter 2 urls	(http:\/\/www\.domain\.com\/owner\/Marketing | http:\/\/www\.domain\.com\/owner\/getinfo)	0
4671196	4671074	C# (Unit Testing): I need to make it impossible to write to a file through code	public interface IStorage\n{\n  bool StoreToFile(string path, string file, byte[] data);\n}\n\npublic class Storage : IStorage\n{\n  public bool StoreToFile( ... )\n  {\n     return WriteToFile( ... );\n  }\n}\n\npublic class StorageMock : IStorage\n{\n   public bool StoreToFile (...)\n   {\n      return false;  //or true, depends on you test case\n   }\n}	0
25686394	25686223	Is there something similar in C# to fflush() from C?	private string _lastValueSearched;\n\nprivate void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e)\n  {\n    if (e.Key == Key.Enter && _lastValueSearched != TxtBoxAddress.Text)\n      {\n        //TxtBoxAddress.LoseFocus();\n        btnSearch_Click(sender, e);\n        _lastValueSearched = TxtBoxAddress.Text;\n      }\n  }\n\n\nprivate void queryTask_Failed(object sender, TaskFailedEventArgs e)\n {\n    //throw new NotImplementedException();\n    MessageBox.Show("*", "*", MessageBoxButton.OK);\n    isMapNearZoomed = false;\n }	0
12488447	12488347	linq group data	(from data in dataInToday\ngroup data by data.StrDateTime into grp\nlet srvrs = string.Join(", ", (from i in grp select i.ServerName))\nselect new\n    { \n       grp.Key,\n       srvrs\n    }).Take(20).Dump();	0
29223698	29223439	I used regex to remove all extra white space in my string, but when it executes, it removes extra white spaces but leaves 1 space at the end	string s = "[       na    me      ]";\n    var s2 = s.Replace(" ", "");\n    Console.WriteLine(s);\n    Console.WriteLine(s2);	0
799225	799118	LINQ: Get the Parent object properties and a single child property as a flat structure	IQueryable<Branch> branches = GetBranches();\n\nvar result = braches.\n   SelectMany(b => b.Addresses.\n      DefaultIfEmpty().\n      Select(a => new { Branch = b, Address = a }));	0
7921734	7907508	Using FakeItEasy, how to get the value set on a property on a fake?	var myObject = A.Fake<ISomeInterface>();\n\nSomeMethod (myObject);\nAssert.That (saved.MyProperty, Is.EqualTo(100));	0
24108633	24108538	How to retrieve number of items being returned?	var tweetCount = tweets.Count(t => t.HashTag == hashtag);\nConsole.Writeline(String.Format("Viewing {0} number of tweets containing the hashtag {1}",\n     tweetCount, hashtag));	0
1363206	1363183	Problem creating regex to match filename	string fileRegex = "(?<trackNo>\\d{1,3})\\.(?<artist>[a-z]+)\\s-\\s(?<title>[a-z]+)\\.mp3";	0
16895387	16895227	Need to convert date format in different way in c#?	DateTime date = DateTime.ParseExact("d/MM/yyyy h:mm:ss tt", text, CultureInfo.InvariantCulture);\nstring newText = date.ToString("dd MMM yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);	0
20021824	20021669	Open Windows Mictrain by c#	private void btnMicTrain_Click(object sender, RoutedEventArgs e)\n{          \n\nProcessStartInfo info = new ProcessStartInfo();\ninfo.FileName = Environment.SystemDirectory+@"\Speech\SpeechUX\SpeechUXWiz.exe";\ninfo.Arguments = "MicTraining";\n\nProcess.Start(info);\n}	0
30056325	30055013	Cant use ItemTemplateSelector with Flipview	protected override DataTemplate SelectTemplateCore(object item,DependencyObject container)	0
15392189	15392016	c# MySql data to list	List<int> values = new List<int>();\n\nstring sql = "SELECT Values_To_Add FROM table";\ncommand.CommandText = sql;\nMySqlDataReader reader = command.ExecuteReader();\n\nwhile(reader.Read())\n{\n  values.Add(reader["Values_To_Add "]);\n}	0
4398603	4398570	overriding a virtual method, but with a new signature: so custom model binder can be used	routes.MapRoute(\n                "IndexWithCartRoute",\n                "Cart",\n                new { controller = "Cart", action = "IndexWithCart" }\n            );	0
1178452	1178249	How to highlight or change the color of some words in a label dynamically at runtime?	myLabel.Text="Some normal text <span style='color: red;'>some red text</span>"	0
2656574	2656272	LINQ - How to query a range of effective dates that only has start dates	var result = source\n  .OrderBy(x => x.start)\n  .GroupBy(x => x.start < startDate)\n  .SelectMany((x, i) => i == 0 ? new[] {new { value = x.Last().value, start = x.Last().start }} : x.Where(y => y.start < endDate));	0
26423379	26422950	How to read from lineX to lineY C#	string input = File.ReadAllText("C:/log.txt");\nMatch m = Regex.Match(input, @"GetConventionalDataTask\s-\s(.*).GetConventionalDataTask", RegexOptions.Singleline);\nConsole.WriteLine(m.Groups[1]);	0
8619888	8619867	How to expose Command classes to XAML views through View Models	// Constructor\npublic MyViewModel()\n{\n    this._injectedModel = SetModel();\n\n    this.MyCommand = new MyCommand(_injectedModel); \n}\n\nICommand MyCommand { get; private set; }	0
2089410	2070240	How to check if a webservice is available using an asynchronous call	Thread testThread = new Thread( () => {\n    SetStatusDelegate d = new SetStatusDelegate(SetTestStatus);\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("yoururl");\n    request.Timeout = new TimeSpan( 0, 1, 30 );\n    try\n    {\n        request.GetResponse();\n    }\n    catch( TimeoutException )\n    {\n         this.Invoke(d, new object[] { TestStatus.Failure});\n    }\n    this.Invoke(d, new object[] { TestStatus.Success});\n});	0
19569833	19247111	How to create a Google account programmatically?	using Google.GData.Apps;\n\nAppsService appService = new AppsService("example.com","mailid","Password");\n\ntry\n{\n    var a = appService.CreateUser(UserName,GivenName,FamilyName,Password);\n}\ncatch (AppsException ex)\n{\n    response = ex.Reason.ToString() + " " + ex.ErrorCode.ToString();\n}	0
30945733	30945700	Regex replace with string that contains a character from the origianal	Regex.Replace(str, @"X\(#\d+\((\d+)\)\)", "X([0-9]{$1})[0-9]*");	0
5590729	5590691	How can i improve my webpage performance?	Control UserControl = LoadControl("usercontrolascx");\nPlaceHolder.Controls.Add(FeaturedProductUserControl);	0
10752802	10751373	How do I extract child nodes from XML file using XPath when both child nodes must exist?	XmlDocument attrsXML = new XmlDocument();\nattrsXML.LoadXml(dbReader["SampleXml"].ToString());\n\n\nXmlNodeList nodeList = attrsXML.SelectNodes("/a/b[c and d]");\n\nforeach (XmlNode xmlNode in nodeList)\n{\n  string cText = xmlNode.SelectSingleNode("c").InnerText;\n  string dText = xmlNode.SelectSingleNode("d").InnerText;\n}	0
19495051	19494808	How do I get month names from this Linq group by query?	Month3Name = english.GetAbbreviatedMonthName(currentMonth - 3)	0
16872617	16872575	How to read key/value in xml file	XDocument doc = XDocument.Load( "c://web.config" );\n       var elements = doc.Descendants( "AppSettings" );\n        Dictionary<string, string> keyValues = new Dictionary<string, string>();\n            for (int i = 0; i < elements.Count; i++)\n            {\n               string key = elements[i].Attributes["key"].Value.ToString();\n               string value = elements[i].Attributes["value"].Value.ToString();\n               keyValues.Add(key,value);\n            }	0
22651986	22651747	How to reference an element in an array to multiple other values?	Dictionary<string, List<int>> bookMapping = new Dictionary<string, List<int>>();\nbookMapping.Add("youruserkey", new List<int> { 1, 2, 3, 4, 5 });	0
9256074	9256022	Creating a generic extension method to provide filtering functionality	public static IQueryable<T> PriceLow<T>(...)\n  where T : ICommonInterface	0
1559138	1559117	How Can I Avoid Invoking Every Event From My External Library?	public Setup(DiscoveryReader reader)\n{\n    download = new DownloadFilesIndividual(Reader.ip, DateTime.Today);\n    download.OnDownloadStatus += new DownloadStatusHandler(download_OnDownloadStatus);\n}\n\nvoid download_OnDownloadStatus(DownloadStatus status)\n{\n   if(InvokeRequired)\n   {\n    Invoke(new Action<DownloadStatus>(download_OnDownloadStatus),status);\n   } else {\n   // Do UI stuff here\n   }\n}	0
1651467	1651444	Modifying parameter values before sending to Base constructor?	public class DerivedClass : BaseClass\n{\n    public DerivedClass(int i)\n        : base(ChooseInputType(i))\n    {\n    }\n\n    private static InputType ChooseInputType(int i)\n    {\n        // Logic\n        return InputType.Number;\n    }\n}	0
3398355	3398172	DataPager jump back to first pages	lstview1.DataBind();	0
27250923	27250847	Editing text of multiple textboxes with function	TextBox txtSender = (TextBox)sender;	0
12622105	12621723	Intersection - Envelope	private static bool Intersects(Envelope e1, Envelope e2)\n{\n    return e1.MinX >= e2.MinX && e1.MaxX <= e2.MaxX && e1.MinY >= e2.MinY && e1.MaxY <= e2.MaxY;\n}\n\nList<Envelope> intersectedTiles = extents.SelectMany(es => es)\n    .Where(e => Intersects(e, bounds))\n    .ToList();	0
11679372	11677369	How to calculate pi to N number of places in C# using loops	public static class BigMath\n{\n    // digits = number of digits to calculate;\n    // iterations = accuracy (higher the number the more accurate it will be and the longer it will take.)\n    public static BigInteger GetPi(int digits, int iterations)\n    {\n        return 16 * ArcTan1OverX(5, digits).ElementAt(iterations)\n            - 4 * ArcTan1OverX(239, digits).ElementAt(iterations);\n    }\n\n    //arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - ...\n    public static IEnumerable<BigInteger> ArcTan1OverX(int x, int digits)\n    {\n        var mag = BigInteger.Pow(10, digits);\n        var sum = BigInteger.Zero;\n        bool sign = true;\n        for (int i = 1; true; i += 2)\n        {\n            var cur = mag / (BigInteger.Pow(x, i) * i);\n            if (sign)\n            {\n                sum += cur;\n            }\n            else\n            {\n                sum -= cur;\n            }\n            yield return sum;\n            sign = !sign;\n        }\n    }\n}	0
9076945	9076903	How to make folder as image database?	using System.IO; \n... \nforeach(string file in Directory.EnumerateFiles(folderPath, "*.jpeg")) \n{     \n    //do the job \n}	0
26533586	26533302	Get yesterday's date from the date entered	DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);\n  Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));	0
10312283	10312248	Compare two IEnumurable Collections using Lambda Expression	var result = AvailablePacks.Join(RecommendedPacks,\n                                 ap => ap.PackID,\n                                 rp => rp.PackID,\n                                 (ap, rp) => new { PackQuantity = ap.Quantity });	0
3273470	3273319	reading data from response	XmlDocument rdsDocument;\n\nHttpWebRequest request = WebRequest.Create("https://www.google.com/accounts/o8/id") as HttpWebRequest;\nrequest.Accept = "application/xrds+xml";\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\nrdsDocument = new XmlDocument();\nrdsDocument.Load(response.GetResponseStream());	0
5856025	5855813	NPOI : How To Read File using NPOI	using NPOI.HSSF.UserModel;\nusing NPOI.SS.UserModel;\n\n//.....\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    HSSFWorkbook hssfwb;\n    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))\n    {\n        hssfwb= new HSSFWorkbook(file);\n    }\n\n    ISheet sheet = hssfwb.GetSheet("Arkusz1");\n    for (int row = 0; row <= sheet.LastRowNum; row++)\n    {\n        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells \n        {\n            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));\n        }\n    }\n}	0
3037940	3037922	Grabbing Just The Top Entry From A LINQ Query	var first = Result.First();	0
2184622	2184578	How to retrieve pair of columns from a DataTable as a Dictionary 	var dict = DataTable.AsEnumerable().ToDictionary(\n                r => r.Field<string>("KeyColumn"), \n                r => r.Field<DateTime>("ValueColumn")\n);	0
23703234	23702668	Joining Tables Using Entity Framerwork Fluent Syntax	var results = db.Table1s\n              .Join(db.Audits.Where(a => a.Username == "jdoe"),\n              t => t.Id,\n              a => a.TableRecordId,\n              (t, a) => new { Table1 = t, Audit = a });\n\nvar results = from t in db.Table1s\n              join a in db.Audits\n              on t.Id equals a.TableRecordId\n              where a.Username == "jdoe"\n              select new { Table1 = t, Audit = a};	0
2660686	2660656	Printing entire array in C#	static string ArrayToString<T>(T[,] array)\n{\n    StringBuilder builder = new StringBuilder("{");\n\n    for (int i = 0; i < array.GetLength(0); i++)\n    {\n        if (i != 0) builder.Append(",");\n        builder.Append("{");\n\n        for (int j = 0; j < array.GetLength(1); j++)\n        {\n            if (j != 0) builder.Append(",");\n            builder.Append(array[i, j]);\n        }\n\n        builder.Append("}");\n    }\n\n    builder.Append("}");\n\n    return builder.ToString();\n}	0
21784440	21784202	Combobox filled with Enum	this.myComboBox.DisplayMember = "Value";\n this.myComboBox.ValueMember = "Key";\n this.myComboBox.DataSource = \n      Enum.GetValues(typeof(EduTypePublicEnum))\n          .Cast<EduTypePublicEnum>()\n          .Select(e => new { \n               Key = e.ToString(), // possibly read localized string\n               Value = e\n           }).ToList();	0
1073697	1073615	How can I get a list of child processes for a given sevice in C#?	static List<Process> GetChildPrecesses(int parentId) {\n  var query = "Select * From Win32_Process Where ParentProcessId = "\n          + parentId;\n  ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\n  ManagementObjectCollection processList = searcher.Get();\n\n  var result = processList.Select(p =>\n    Process.GetProcessById(Convert.ToInt32(p.GetPropertyValue("ProcessId")));\n  ).ToList();\n\n  return result;\n}	0
11841385	11841352	ADODB Command only retrieves one field	rsStbDetails.MoveNext();	0
1002178	1001994	Storing license details	Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);	0
21881611	21881291	Get back information from combo box in .NET WinForms	class SingleItem\n{\n    public int val1 { get; set; }\n    public int val2 { get; set; }\n    public string str { get; set; }\n    public override string ToString()\n    {\n        return str;\n    }\n\n}\n\n...\n\n private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var obj = ((SingleItem)comboBox1.SelectedItem).val1; \n}	0
27567234	27567170	How to use params of object	int summ=0;\nforeach (car i in list)\n{\n   summ += i.value\n}	0
11682296	11682203	XPATH returns null for XML with namespace	XmlNamespaceManager xmlnsmgr = new XmlNamespaceManager(INISRecordXMLdoc.NameTable);\nxmlnsmgr.AddNamespace("ns", "http://localhost/gsainis/GsaInisWebService");\n\nforeach (XmlNode node in INISRecordXMLdoc.SelectNodes("//ns:ArrayOfString/ns:string/ns:gsafeed/ns:group/ns:record", xmlnsmgr))\n{\n   // Do something\n}	0
1613547	1613480	Find any literal with a Regular Expression	Regex countOccurances = new Regex(Regex.Escape(foundWord));	0
27097444	27097432	cannot convert from 'object' to 'string'	private string Val(string val)\n       {\n         int vId;\n         bool isNumeric = Int32.TryParse(val, out vId);\n         return string.Empty;\n        }	0
11480875	11472883	Ninject - Creating a Custom NinjectWebServiceHost	public class OAuthHostFactory : NinjectWebServiceHostFactory\n{\n    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)\n    {\n        var host = base.CreateServiceHost(serviceType, baseAddresses);\n        host.Authorization.ServiceAuthorizationManager = new OAuthAuthorizationManager();\n        return host;\n    }\n}	0
1263494	1263489	How do I upcast a collection of base class in C#?	using System.Linq;\n\nList<B> bList = foo.GetListOfA().Cast<B>().ToList();	0
18960376	18959797	How to parse CSV that is passed as a parameter to a method	using (MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data)))\n        using (StreamReader reader = new StreamReader(mStream))\n        {\n            IEnumerable<Data> datas = cc.Read<Data>(reader, inputFileDescription);\n        }	0
7527723	7431179	WCF right solution for Publish/subscribe pattern implementation	// duplex session enable http binding\n            WSDualHttpBinding httpBinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);\n            httpBinding.ReceiveTimeout = TimeSpan.MaxValue;\n            httpBinding.ReliableSession = new ReliableSession();\n            httpBinding.ReliableSession.Ordered = true;\n            httpBinding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;	0
28757242	28725024	Convert from IList to List<T>	ObservableCollection<object> _bindSelectedItems;\n    public ObservableCollection<object> BindSelectedItems\n    {\n        get { return _bindSelectedItems; }\n        set\n        {\n\n            _bindSelectedItems = value;\n            _bindSelectedItems.CollectionChanged += _bindSelectedItems_CollectionChanged;\n            RaisePropertyChanged("BindSelectedItems");\n        }\n    }\n\n    void _bindSelectedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n    {\n        ObservableCollection<object> items = sender as ObservableCollection<object>;\n\n    }	0
33685501	33685311	C# retrieving data from DataSet	DataSet ds =new DataSet();\n\nif (File.Exists(@"C:\Computers\config.xml"))\n{\n            ds.ReadXml(@"C:\Computers\config.xml");\n\n            //comboBox.Items.Add(ds.Tables[0].Rows[0][0].ToString()); doesn't work\n            comboBox.Items.Add(ds.Tables[0].Rows.Count);  //this counts 3 rows\n}	0
7769807	7769772	Expose method as a property in user control	public string OnClientClick\n{\n    get { return Button1.OnClientClick; }\n    set\n    {\n        Button1.OnClientClick = value;\n    }\n}	0
29891060	29890811	C# How to Generate Random Number Depends on Probabilities	// Do not re-create Random! Create it once only\n  // The simplest implementation - not thread-save\n  private static Random s_Generator = new Random();\n\n  ...\n  // you can easiliy update the margin if you want, say, 91.234%\n  const double margin = 90.0 / 100.0; \n\n  int result = s_Generator.NextDouble() <= margin ? 1 : 0;	0
16053646	16051561	Ideal number of Object Instances to pass Via View Model constructor (dependency injection)	public MyViewModel(IocContainer container) {\n   // resolve dependencies via the container\n}	0
16647724	16647386	Routing POST with Query Parameters in MVC Web API	public string Post(int id, [FromBody]string content, [FromUri] string user)\n    {\n        return "content = " + content + "user = " + user;\n    }	0
8479613	8479560	Best way to access images outside of a project?	ImageSource="pack://application:,,,/MyProject;component/Images/MyImage.png"	0
15743221	15737474	iOS changing outlets -- Monotouch	key value coding-compliant	0
9084497	9084415	Visual Studio: How to access to items from a class?	class myClass\n{\n    public myClass(Window1 instance)\n    {\n        instance.myGrid.Width= 512;\n\n        //Window1 .myGrid.Width= 512; will not work because myGrid is not static.\n    }\n}\n\npublic partial class Window1 : Window\n{\n    public Window1 ()\n    {\n         myClass m = new myClass(this);\n    }\n}	0
20084505	20040240	Windows Phone ScheduleAgent grabbing images on set period	private async void DownloadImagefromServer(string imgUrl)\n{\n    Debug.WriteLine("Attempting to Get Image from Server...");\n    WebClient client = new WebClient();\n\n    var result = await client.OpenReadTaskAsync(new Uri(imgUrl, UriKind.Absolute));\n\n    BitmapImage bitmap = new BitmapImage();\n    bitmap.SetSource(result);\n    //img.Source = bitmap;\n\n    ... rest of your code from OpenReadCompleted goes here\n}	0
1427296	1426054	How to get "Data Type" value of Body of a Lotus Notes Item using .NET?	...\ndim itemBody as notesItem, nType as integer\nset itemBody = doc.getItem ("Body")\nnType = itemBody.Type\n...	0
5944934	5943622	Capturing exceptions from a Page in a usercontrol	protected void Page_Load(object sender, EventArgs e)\n{\n    Page.Error += new EventHandler(Page_Error);\n}\n\nvoid Page_Error(object sender, EventArgs e)\n{\n    Exception exception = Server.GetLastError();\n\n    Response.Write(exception.ToString());\n\n    HttpContext.Current.ClearError();\n}	0
540075	540066	Calling a function from a string in C#	Type thisType = this.GetType();\nMethodInfo theMethod = thisType.GetMethod(TheCommandString);\ntheMethod.Invoke(this, userParameters);	0
12756037	12755982	using statements	SqlConnection connection1 = \nnew SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());	0
4303683	4303570	Help split the string	public static List<string> SplitAndCombine(IEnumerable<string> source,\n                                           string delimiter)\n{\n    List<string> result = new List<string>();\n    StringBuilder current = null;\n\n    // Ignore anything before the first delimiter\n    foreach (string item in source.SkipWhile(x => x != delimiter))\n    {\n        if (item == delimiter)\n        {\n            if (current != null)\n            {\n                result.Add(current.ToString());\n            }\n            current = new StringBuilder();\n        }\n        current.Append(item);\n    } \n\n    if (current != null)\n    {\n        result.Add(current.ToString());\n    }\n    return result;\n}	0
24996383	24996293	Regex syntax in a C# application	[^\w\s-]|_	0
28425419	28423386	How to save severel image(.png,.jpg) file in same folder without SavefileDialog in C#	private void timer1_Tick(object sender, EventArgs e)\n{\n    Graphics GH = Graphics.FromImage(Form1.bm as Image);\n    GH.CopyFromScreen(0, 0, 0, 0, Form1.bm.Size);\n    this.pic_box.SizeMode = PictureBoxSizeMode.StretchImage;\n    pic_box.Image = Form1.bm;\n    timer1.Enabled = false;\n    Form1.bm.Save("cap(#).png");\n    this.Close();\n}	0
2933551	2933538	A Solution For (IEnumerable<Base>)Derive; Yet?	var ls = (IEnumerable<B>)(cond ? lsD1.Cast<B>() : lsD2.Cast<B>());	0
4945941	4945769	Regex Problems, extracting data to groups	string myString = @"<Category>DIR</Category><Location>DL123A</Location><Reason>Because</Reason><Qty>42</Qty><Description>Some Desc</Description><IPAddress>127.0.0.1</IPAddress>";\n\nvar values = new Dictionary<string, string>();\nvar xml = XDocument.Parse("<root>" + myString + "</root>");\nforeach(var e in xml.Root.Elements()) {\n    values.Add(e.Name.ToString(), e.Value);\n}	0
1702728	1702716	Free way to convert PDF to XPS with C#	virtual void Save(Stream stream)	0
10058971	10058887	opening a document and waiting for a user to finish editing it	private IObservable<List<string>> ImportWords()\n    {\n        Subject<List<string>> contx = new Subject<List<string>>();\n        new Thread(new ThreadStart(() =>\n            {\n                //waits for the user to finish formatting his words correctly\n                for (; ; ) \n                { \n                    if (FormatWindowOpen != true) \n                    {\n                        contx.OnNext(ExtractWords(FormattedText));\n                        contx.OnCompleted();\n                        break;\n                    }\n                }\n            })).Start();\n        return contx;\n    }	0
15381998	15380730	Foreach every Subitem in a MenuStrip	List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();\nforeach (ToolStripMenuItem toolItem in menuStrip.Items) \n{\n    allItems.Add(toolItem);\n    //add sub items\n    allItems.AddRange(GetItems(toolItem));\n}  \nprivate IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item) \n{\n    foreach (ToolStripMenuItem dropDownItem in item.DropDownItems) \n    {\n        if (dropDownItem.HasDropDownItems) \n        {\n            foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))\n                yield return subItem;\n        }\n        yield return dropDownItem;\n    }\n}	0
34402003	34401934	Automatically create a copy of a static variable for each derived class	public class Parent\n{\n    private Texture2D texture;\n\n    public Parent(Texture2D texture) {\n        this.texture = texture;\n    }\n\n    public Texture2D Picture { get {\n            return texture;\n        }\n    }\n}\n\npublic class SubClass1 : Parent\n{\n    public SubClass1(Texture2D texture) : base(texture) {\n\n    }\n}	0
20078818	20078741	Regex Find Text Between Tags C#	Match m = collection[0];\nvar stripped = m.Groups[1].Value;	0
6543370	6542944	Pumping Bytes Directly into Response.OutputStream - how to deal with byte count?	content-length	0
12993479	12993430	TreeView that holds Objects	TreeNode node;\nnode.Tag = myObject;	0
30614797	30614662	How do I display the columnnames of an sql table with C#	string colName = rst.GetName(i);	0
1433605	1433596	byte[] to ArrayList?	ArrayList list = new ArrayList(bytearray);	0
8358346	8358237	Translating textbox input to spanish, chinese, deutsch	public static string Translate(string input, string languagePair, Encoding encoding)\n{\nstring url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);\n\nstring result = String.Empty;\n\nusing (WebClient webClient = new WebClient())\n{\nwebClient.Encoding = encoding;\nresult = webClient.DownloadString(url);\n}\n\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(result);\nreturn doc.DocumentNode.SelectSingleNode("//textarea[@name='utrans']").InnerText;\n}\n\n//Get the HtmlAgilityPack here: http://www.codeplex.com/htmlagilitypack	0
28861679	28859252	How do i conditionally add a list to a ViewData.Model if 2 data values from two different DB tables are equal in ASP.NET MVC 4?	public ActionResult Index()\n{\n  _db = new IntegrationWebDBEntities();\n\n  ViewData.Model = (from r in _db.Requests\n                    from j in _db.Jobs\n                    where r.id == j.RequestID\n                    select r).toList();\n  return View();\n}	0
10626466	10626396	How to bypass Form_closing Event	//unsubscribe the mean "don't let me close" handler\nthis.FormClosing -= form1_closing; \n//close form\nthis.Close();	0
13532257	13530398	RowsAdded Event made a Strange behavior when changing back color of row in DataGridView	private void dgvPayment_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)\n        {\n            for (int index = e.RowIndex; index <= e.RowIndex + e.RowCount - 1; index++)\n            {\n                DataGridViewRow row = dgvPayment.Rows[index];\n                Payment lPayment = row.DataBoundItem as Payment;\n                if (lPayment != null && lPayment.IsLocked)\n                {\n                    row.DefaultCellStyle.BackColor = Color.Pink;\n                    row.ReadOnly = true;\n                }\n                else\n                {\n                    row.DefaultCellStyle = null;\n                    row.ReadOnly = false;\n                }\n\n\n            }\n        }	0
29166689	29165210	How to form nested json from sql parent child relation table	public class Person\n{\n    public int Id {get; set;}\n    public string Name {get; set;}\n    public string Value {get; set;}\n    public PersonAttributes attributes {get; set;}\n    public List<Person> Children {get; set;}\n}\n\npublic class PersonAttributes\n{\n    public bool HasChild {get; set;}\n    public bool HasParent {get; set;}\n    public int ParentId {get; set;}\n}	0
3682595	3682578	Bitmap cant find a pixel on itself!	private const int Threshold = 10;\n...\nif (c.R < Threshold && c.G < Threshold && c.B < Threshold)	0
5897096	5897062	excel cell coloring	ws.Cells[row, clmn].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)	0
1676451	1636151	How to get the response stream on a non 201 status code	catch(WebException ex)\n{\n     ex.Response.GetResponseStream();\n}	0
12769008	12765835	How to determine the language of a RESX file	[assembly:NeutralResourcesLanguageAttribute]	0
6156890	6156831	Showing only last 4 digits in a textbox	// create 4 less x's than the credit card length.\n// then append that to the last 4 characters of the credit card\nnew string('x', creditcard.Length - 4) + creditcard.Substring(creditcard.Length - 4);	0
7076925	7076841	How to round to two decimal places in a string?	Math.Round(Convert.ToDecimal(strTemp), 2);	0
8305159	8304920	How do I insert data into MS Access file using SQL?	"INSERT INTO PersonalData ([Type], UserName, [Password]) VALUES ...	0
20614531	20614396	How to Send a Object name as argument to function?	private void button_click(object sender, EventArgs e)\n{    \n    string pBoxName = textbox1.Text;\n    // I don't quite understand what you mean by 'location number'\n    int newPos = int.Parse(textbox2.Text);\n    // boxList is a List<PictureBox>\n    PictureBox pBox = boxList.Where(x => x.Name.Equals(pBoxName)).FirstOrDefault();\n    if(pBox != null)\n    {\n        MoveTheBox(pBox, newPos);\n    }\n}\n\nprivate void MoveTheBox(PictureBox box, int newPos)\n{\n    // move the box\n}	0
26886892	26886674	Loop through a C# enum's keys AND values	foreach(int i in Enum.GetValues(typeof(stuff)))\n{\n    String name = Enum.GetName(typeof(stuff), i);\n    NewObject thing = new NewObject\n    {\n        Name = name,\n        Number = i\n    };\n}	0
29124510	29124320	Set BackColor RGB values via trackbar	this.BackColor = Color.FromArgb(trb_R.Value, trb_G.Value, trb_B.Value);	0
12226744	12226691	Replace multiple words in a string from a list of words	string cleaned = Regex.Replace(input, "\\b" + string.join("\\b|\\b",BAD_WORDS) + "\\b", "")	0
9922370	9909161	Is there a way to disable copy paste for editor column in devexpress xtraGrid?	ContextMenu emptyMenu = new ContextMenu();\n        this.components.Add(emptyMenu);\n\n    private void gridView1_ShownEditor(object sender, System.EventArgs e) {\n        DevExpress.XtraGrid.Views.Grid.GridView view = \n                           sender as DevExpress.XtraGrid.Views.Grid.GridView;\n        if(!view.IsFilterRow(view.FocusedRowHandle)) return;\n        view.ActiveEditor.ContextMenu = emptyMenu;\n    }	0
20266929	20264314	Create COM interface returning a pointer that is marshalled as IntPtr in C#	ref byte	0
7165442	7165313	.Net library to move / copy a file while preserving timestamps	public static void CopyFileExactly(string copyFromPath, string copyToPath)\n{\n    var origin = new FileInfo(copyFromPath);\n\n    origin.CopyTo(copyToPath, true);\n\n    var destination = new FileInfo(copyToPath);\n    destination.CreationTime = origin.CreationTime;\n    destination.LastWriteTime = origin.LastWriteTime;\n    destination.LastAccessTime = origin.LastAccessTime;\n}	0
23463438	23463400	Select columns using LINQ but without a ModelView	var userObject = DB.Users.OrderBy(r => r.UserName).Skip(skip).Take(pageSize)\n                         .Select(r => new { r.UserName, r.user_Status })\n                         .ToList();	0
33122021	33121731	How to work around multiple inheritance missing in c#	public class ModelClass : BaseModel, IUser\n{\n    public string Name { get; set; }\n    string IUset<string>Id { get { return this.Id.ToString(); } }\n}	0
13940978	13940870	How to get the users domain to create a principalcontext asp.net	string domain = "defaultDomain";\nstring[] splittedAuth = Request.ServerVariables["LOGON_USER"].Split('\\');\ndomain = (splittedAuth.Count() > 1) ? splittedAuth[0] : domain;\nPrincipalContext context = new PrincipalContext(ContextType.Domain, domain);	0
11982526	11982405	Windows 8 metro apps Switching between 2 cameras	private async void EnumerateWebcamsAsync()\n    {\n        try\n        {\n            ShowStatusMessage("Enumerating Webcams...");\n            m_devInfoCollection = null;\n\n            EnumedDeviceList2.Items.Clear();\n\n            m_devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);\n            if (m_devInfoCollection.Count == 0)\n            {\n                ShowStatusMessage("No WebCams found.");\n            }\n            else\n            {\n                for (int i = 0; i < m_devInfoCollection.Count; i++)\n                {\n                    var devInfo = m_devInfoCollection[i];\n                    EnumedDeviceList2.Items.Add(devInfo.Name);\n                }\n                EnumedDeviceList2.SelectedIndex = 0;\n                ShowStatusMessage("Enumerating Webcams completed successfully.");\n                btnStartDevice2.IsEnabled = true;\n            }\n        }\n        catch (Exception e)\n        {\n            ShowExceptionMessage(e);\n        }\n    }	0
10384073	10383945	Using LINQ to SQL to get distinct value of an IQueryable resultset	return data.Distinct(new YourEqualityComparer()).OrderBy(strOrderBy).Select("New(" + strItems + ")");	0
21878121	21877984	Update property from MainWindow to userControl	public double ZoomSlider\n{\n   get { return (double)GetValue(ZoomSliderProperty); }\n   set { SetValue(ZoomSliderProperty, value); }\n}\n\n// Using a DependencyProperty as the backing store for ZoomSlider.  This enables animation, styling, binding, etc...\npublic static readonly DependencyProperty ZoomSliderProperty =\n            DependencyProperty.Register("ZoomSlider", typeof(double), typeof(MainWindow), new PropertyMetadata(2d));	0
30238526	30238416	Replace little c sharp depreciation	if (Input.GetMouseButton (1) && (!requireLock || controlLock || Cursor.lockState == CursorLockMode.Locked))\n// If the right mouse button is held, rotation is locked to the mouse\n{\n    if (controlLock)\n    {\n        Cursor.lockState = CursorLockMode.Locked;\n        Cursor.visible = false;\n    }\n\n    rotationAmount = Input.GetAxis ("Mouse X") * mouseTurnSpeed * Time.deltaTime;\n}\nelse\n{\n    if (controlLock)\n    {\n        Cursor.lockState = CursorLockMode.None;\n        Cursor.visible = true;\n    }\n}	0
12195379	12195339	Request a key from web.config to a .cs file	var value = ConfigurationManager.AppSettings["stylet"];\nresponse.Write(@"<link href='"+ value +"' type='text/css' />");	0
8013202	8009787	MarshalAsAttribute array of strings	[StructLayout(LayoutKind.Sequential)]\npublic struct InstancePathDefinition {\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]\n    public string path;\n}	0
9219259	9219169	What's the appropriate method for marshalling an array of strings?	[return: MarshalAs(UnmanagedType.I1)]\n[DllImport("myDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]\nprivate static unsafe extern bool GetStrings(IntPtr sourceFile,\n    [Out] out byte* ptrToStrings,\n    [Out] out uint numberOfStrings);\n\n\n[SecuritySafeCritical]\nprivate static unsafe string[] ManagedMethod(IntPtr sourceFile)\n{\n    uint size;\n    byte* array;\n    if (!GetStrings(sourceFile, out array, out size))\n    {\n        throw new Exception("Unable to read strings.");\n    }\n\n    string[] retval = new string[size];\n    for (int i = 0, p = 0; i < size; i++, p += 8)\n    {\n        retval[i] = Marshal.PtrToStringAnsi(new IntPtr(&array[p]));\n    }\n\n    return retval;\n}	0
9390751	9390418	How to handle application close events using C#	bool completed = false;\ntry\n{\n   Thread thread = new Thread(() => startConfig.StartProcessCommmandLine(args));\n   thread.IsBackground = true;\n   thread.Start();\n   bool completed = thread.Join(60000); // 60s timeout\n}\nfinally\n{\n   semaphore.Release(1);\n}\nEnvironment.Exit(completed ? 0 : 1);	0
16581583	16394767	Filter WinForms DataGridView by date range	if (lbSearchByTime.Items.Count == 2)\n        {\n            DateTime start = stringToDateTime(lbSearchByTime.Items[0].ToString().Trim());\n            DateTime end = stringToDateTime(lbSearchByTime.Items[1].ToString().Trim());\n\n            Filter = "(DATE101 >= #" + start + "# and DATE101 <= #" + end + "#)";\n        }	0
28174421	28174131	In C#, How do you find out whether an Object is of a Generic Base Type	namespace Program {\n\n  class MyGeneric<T> { }\n\n  class MyDerived : MyGeneric<String> { }\n\n  class Program {\n    public static void Main() {\n      MyDerived item = new MyDerived ();\n      Boolean isIt = typeof(MyGeneric<>).BaseType.IsAssignableFrom (item.GetType());\n      Console.WriteLine (isIt); // Output: "True"\n\n      foreach (Type type in item.GetType().BaseType.GetGenericArguments())\n        Console.WriteLine(type.Name);\n    }\n  }\n}	0
6222068	6219348	What to use for playing sound effects in silverlight for wp7	public partial class MediaPage : PhoneApplicationPage\n{\n  // ...\n\n  SoundEffectPlayer _player = null;\n\n  private void playButton_Click(object sender, RoutedEventArgs e)\n  {\n    var resource = Application.GetResourceStream(new Uri("alert.wav", UriKind.Relative));\n    var effect = SoundEffect.FromStream(resource.Stream);\n    _player = new SoundEffectPlayer(effect);\n    _player.Play();\n\n  }\n}	0
3150284	2732927	Getting shortest path between 2 nodes in quickgraph	QuickGraph.Algorithms.ShortestPath.AStarShortestPathAlgorithm<TVertex,TEdge>	0
5442224	5442067	Change color and font for some part of text in WPF C#	TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);\n  rangeOfText1.Text = "Text1 ";\n  rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);\n  rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);\n\n  TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);\n  rangeOfWord.Text = "word ";\n  rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);\n  rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);\n\n  TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);\n  rangeOfText2.Text = "Text2 ";\n  rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);\n  rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);	0
22567408	22567251	variable conflicts with declaration function.form1.userseqq	int iid;\nint iid;\nint itemseqq;\n[...]	0
21642794	21642711	How can i download all the htmls and save them one one loop?	var files = new Dictionary<int, string> {\n   { 0, "Sat24_Temperature_Europe.html" },\n   { 1, "Sat24_Rain_Europe.html" },\n   { 2, "Sat24_Wind_Europe.html" },\n   { 3, "Sat24_Lightnings_europe.html" },\n   { 4, "Sat24_Cloudtypes_Europe.html" }\n};\n\nconst string urlFormat = \n                  "http://www.sat24.com/foreloop.aspx?type={0}&continent=europa#";\nforeach (var kv in files)\n{\n    string url = string.Format(urlFormat, kv.Key);\n    client.DownloadFile(url, localFilename + "\\" + kv.Value);\n}	0
12826631	12826597	How to check if a file exists on the web server	if(System.IO.File.Exists([path goes here]))\n{\n  // do something\n}	0
25693332	25693300	How to do something if cancel button on save file dialog was clicked?	if (mySaveDialog.DialogResult == DialogResult.OK) { /* show saved ok */ }	0
32828528	32827945	Linq Contains without considering accents	string[] result = {"hello there", "h?llo there","goodbye"};\n\nstring word = "h?llo";\n\nvar compareInfo = CultureInfo.InvariantCulture.CompareInfo;\n\nvar filtered = result.Where(\n      p => compareInfo.IndexOf(p, word, CompareOptions.IgnoreNonSpace) > -1);	0
4661736	4661663	How to export a List<t> to Excel as the result of a web request	Response.ContentType = "application/vnd.ms-excel";\nResponse.AddHeader("Content-Disposition", "attachment;filename=myfilename.xls");\n\nvar grid = new DataGrid();\ngrid.DataSource = myList;\ngrid.DataBind();\ngrid.Render(writer);\n\nResponse.End();	0
18798136	18797995	Multidimensional array sum	Dictionary<int, string> wordList = new Dictionary<int, string> {\n            {1, "Cat"},\n            {2, "Dog"},\n            {4, "Mouse"},\n            {8, "House"},\n            {16, "Ball"},\n            {32, "Music"},\n        };\n\n        int number = 7;\n\n        StringBuilder builder = new StringBuilder();\n        foreach (KeyValuePair<int, string> word in \n            wordList.Where(pair => pair.Key <= number)) {\n            builder.Append(word.Value);\n            builder.Append(", ");\n        }	0
16792423	16792166	Concatenate many rows into a single text string in Entity framework	var result = StudentSubjects\n                .GroupBy(x => x.SubjectID)\n                .Select(x => new \n                    { \n                        Subject = x.Key, \n                        Names = String.Join(", ", x.Select(n => n.Name)) \n                    });	0
20537217	20537017	How can I prevent FolderBrowserDialog to crash?	private void openSlideShowFolder_Click(object sender, EventArgs e)\n{\n    if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)\n    {\n    string[] pics1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");\n    string[] pics2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");\n    string[] pics3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.bmp");\n    folderFile = new string[pics1.Length + pics2.Length + pics3.Length];\n    Array.Copy(pics1, 0, folderFile, 0, pics1.Length);\n    Array.Copy(pics2, 0, folderFile, pics1.Length, pics2.Length);\n    Array.Copy(pics3, 0, folderFile, pics1.Length + pics2.Length, pics3.Length);\n    selected = 0;\n    showImage(folderFile[selected]);\n    }\n}	0
1961551	1961536	Why should I use a private variable in a property accessor?	{ get; set; }	0
31791932	31791473	Programmatically added items to FlowLayoutPanel aren't aligned like those at design time	newLabel.AutoSize = true;	0
5258942	5254464	DDD - Mapping Value Objects with Fluent nHibernate in separate tables	public class CustomerMap : IAutoMappingOverride<Customer>\n{\n    public void Override(AutoMapping<Customer> mapping) {\n        mapping.Not.LazyLoad();\n        mapping.Id(x => x.Id, "CustomerID")\n            .GeneratedBy.Assigned();\n\n        mapping.HasMany(hm => hm.Orders).KeyColumn("CustomerID");\n    }\n}	0
4544478	4544464	How can I define an array without a fixed size?	List<T>	0
13746452	13746321	How to get the index of an element in a singly linked list?	public SLElement Remove(int index)\n{\n    SLElement prev = _root;\n    if(prev == null) return null; //or throw exception\n    SLElement curr = _root.next;\n    for(int i = 1; i < index; i++)\n    {\n      if(curr == null) return null; //or throw exception\n      prev = curr;\n      curr = curr.next;\n    }\n    prev.next = curr.next; //set the previous's node point to current's next node\n    curr.next = null;\n    return curr;\n}	0
21826727	21809978	parameter in my Rule in fluentvalidation	public class FieldModelValidator : AbstractValidator<FieldViewModel> {\n  { \n    public FieldModelValidator()\n    {\n         RuleFor(x => x.FieldValue ).Must(RangeValidation).When(w => w.Validations.Any(x =>       x.Validations.Contain(2)))\n    }\n\n    private bool RangeValidation(FieldViewModel field, String value)\n    {\n                int val  =int.Parse(value);\n\n             if(val >= field.MinRange && val <= field.MaxRange )\n             {\n              return true;\n             }\n           return false;\n\n\n    }\n\n\n  }	0
6736875	6736838	Initialize container from Control	public class Configuration {\n    private Control container;\n    public Control Container {\n        get {\n            var result = this.container;\n            if ( null == result ) {\n                this.container = result = new Container();\n            }\n        }\n        set { this.container = value; }\n    }\n}\n\n// ... elsewhere ...\nvar cfg = new Configuration();\ncfg.Container.Controls.Add(new Button());	0
9199720	9198689	Converting EditorTemplate into HtmlHelper	public static MvcHtmlString CustomEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n{\n    var idString = htmlHelper.IdFor(expression);\n    var items = // get items\n\n    var param = Expression.Parameter(typeof(TModel), "m");\n    var member = Expression.Property(\n                     Expression.Property(param, ExpressionHelper.GetExpressionText(expression))\n                 , "Id");\n\n    var isNullable = Nullable.GetUnderlyingType(member.Type);\n    if (isNullable != null) {\n        var expr2 = Expression.Lambda<Func<TModel, int?>>(\n                        member, new[] { param }\n                    );\n\n        return htmlHelper.DropDownListFor(expr2, items, new { id = idString });\n    }\n\n    var expr = Expression.Lambda<Func<TModel, int>>(\n                   member, new[] { param }\n               );\n\n    return htmlHelper.DropDownListFor(expr, items, new { id = idString });\n}	0
14599096	14598765	How to combine multiple click events that pass value into one?	string buttonName = ((Button)sender).Name;\n\n            switch (buttonName)\n            {\n                case "button1":\n                    MessageBox.Show("Button1 pressed");\n                    break;\n                case "button2":\n                    MessageBox.Show("Button2 pressed");\n                    break;\n            }	0
11520898	11519845	Working with checkboxes in asp.net mvc3 plus mass update	Html.CheckBoxFor	0
6046875	6046336	C# Model Object For a Report	public class ReportModel \n{\n  public int ID {get; private set;}\n  public DateTime Date {get; private set;}\n  public int Value {get; private set;}\n\n  private ReportModel() {}\n\n  public static ReportModel FromDataRow(DataRow dataRow)\n  {\n       return new ReportModel\n       {\n            ID = Convert.ToInt32(dataRow["id"]),\n            Date = Convert.ToDateTime(dataRow["date"]),\n            Value = Convert.ToInt32(dataRow["value"])\n       };\n  } \n\n  public static List<ReportModel> FromDataTable(DataTable dataTable)\n  {\n       var list = new List<ReportModel>();\n\n       foreach(var row in dataTable.Rows)\n       {\n            list.Add(ReportModel.FromDataRow(row);\n       }\n\n       return list;\n  }\n}	0
3575882	1272820	Customizing InfoPath Hyperlink Addresses	private string ChangeXmlContent(Uri url, XmlDocument xdoc, string description)\n{\n    XmlNode group91 = xdoc.SelectSingleNode("//my:group91", NamespaceManager);\n\n    group91.SelectSingleNode("//my:Url1", NamespaceManager).InnerText = url.ToString();\n}	0
5856598	5848827	Getting data by widget's name in monodev	if (!string.IsNullOrEmpty (entry.Text))\n    //do stuff	0
13176564	13173530	How to retrieve data from my Entitiy Model in code-behind	ShellEntities entities = new ShellEntities(); //initiate\n        List<User> users = entities.User.Where(w => w.Email == "test@gmail.com").ToList();\n        foreach (var item in users)\n        {\n            Response.Write(item.Username);\n        }	0
25340223	25340120	LinqToXML: accessing child elements	var evt = (from el in doc.Descendants("test")\n           where el.Parent.Name == "Event_1"\n           group el by el.Parent.Element("NameOfEvent").Value into g\n           select new {\n               Name = g.Key,\n               Tests = g.Select(x => new {\n                   XPath = x.Element("xpath").Value,\n                   Value = x.Element("value").Value,\n                   TagName = x.Element("tagName").Value\n               })\n           }).FirstOrDefault();\n\nConsole.WriteLine("Event name: " + evt.Name);\nforeach (var test in evt.Tests)\n{\n    Console.WriteLine(test.XPath);\n    Console.WriteLine(test.Value);\n    Console.WriteLine(test.TagName);\n}	0
12321339	12321259	fastest way to check to see if a certain index in a linq statement is null	var someRecords = someRepoAttachedToDatabase.Where(p=>true); \nParallel.Foreach(someRecords, record=>DoSomethingWithRecord(record));	0
18917544	18917408	C# String to date with CultureInfo	string dateText = rows[row][4].ToString();\nDateTime date = DateTime.ParseExact(dateText, "yyyyMMdd", CultureInfo.InvariantCulture);\nstring result = date.ToShortDateString(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern);	0
1987093	1987079	How can I determine the amount of time a set of operations in C# require to execute?	Stopwatch sw= new Stopwatch();\n    sw.Start();\n    DoTimeConsumingOperation();\n    sw.Stop();\n    Console.WriteLine(sw.Elapsed); // in milliseconds	0
7546952	7546931	determine if array of bytes contains bytes in a specific order	public static bool ContainsSequence(byte[] toSearch, byte[] toFind) {\n  for (var i = 0; i + toFind.Length < toSearch.Length; i++) {\n    var allSame = true;\n    for (var j = 0; j < toFind.Length; j++) {\n      if (toSearch[i + j] != toFind[j]) {\n        allSame = false;\n        break;\n      }\n    }\n\n    if (allSame) {\n      return true;\n    }\n  }\n\n  return false;\n}	0
17175397	16981842	XNA - Losing application-icon when returning from full screen	System.Windows.Forms.Form MyGameForm = (System.Windows.Forms.Form)System.Windows.Forms.Form.FromHandle(Window.Handle);\nMyGameForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;	0
20969795	20969689	how to store the value in list	public List<TimesheetError> Validate(Client client)\n    {\n        List<TimesheetError> listerror=new List<TimesheetError>();\n        if (client.Name.IsEmpty())\n        { \n            TimesheetError error = new TimesheetError();\n            error.Messsage = "Bad request";\n            error.ListErrors = "name is not enterd";\n            error.Status = "Not Found";\n            error.IsNotValid = true;\n            listerror.Add(error);\n        }\n         if (client.Contact.FirstName.IsEmpty())\n        {\n            TimesheetError error = new TimesheetError();\n            error.Messsage = "Bad Request";\n            error.ListErrors = "Contact name is not entered";\n            error.Status = "Not Found";\n            error.IsNotValid = true;\n            listerror.Add(error);\n        }\n        return listerror\n   }	0
5973991	5973952	Grouping the list by a field and add items to a dictionary	var countByCustomer = complaints.GroupBy(row => row.CustomerNumber)\n    .ToDictionary(grp => grp.Key, grp => grp.Count());	0
14128129	13802134	Passing items From DataTable to SQL Where Clause c#	SqlConnection conn = new SqlConnection("Server=ax12d;Database=DemoDataAx;Trusted_Connection=True;");\n\nSqlCommand cmd = new SqlCommand(@"Select Level2 as Category \n                                  from Mtq_RetailHierarchy \n                                  Where Level1 IN (SELECT Department \n                                                   From @Depts)", conn);\n\ncmd.Parameters.Clear();\nSqlParameter param cmd.Parameters.AddWithValue("@Depts", _Depts);\nparam.SqlDbType = SqlDbType.Structured;\nparam.TypeName = "dbo.Departments"; //This can either be a table or a User Defined Type\n\n\nSqlDataAdapter da = new SqlDataAdapter(cmd);\nDataTable SelectedCatsData = new DataTable();\nda.Fill(SelectedCatsData);\nreturn SelectedCatsData;	0
19543160	19540246	How to turn ON/OFF an XmlWriter Indent property?	XmlWriterSettings.Indent = false	0
8001524	8001450	C# wait for user to finish typing in a Text Box	onChange()	0
11261658	11260529	WinRT/Metro Animation in code-behind	doubleAnimation.EnableDependentAnimation = true;	0
6554872	6554869	Byte[] to ASCII	System.Text.Encoding.ASCII.GetString(buf);	0
20215420	20214638	How to stop animation at particular state	storyboard.Completed += StoryboardCompleted;\nstoryboard.Begin(this, true);\n\nvoid StoryboardCompleted(object sender, EventArgs e)\n{\n   storyboard.Stop(this);\n}	0
25318445	25318416	Padding so always 12 digits long	string result = "PSS1".PadRight(12 - string1.Length,'0') + string1;	0
5971732	5971686	How to create a task (TPL) running a STA thread?	var scheduler = TaskScheduler.FromCurrentSynchronizationContext();\n\nTask.Factory.StartNew(...)\n            .ContinueWith(r => AddControlsToGrid(r.Result), scheduler);	0
11760605	11749604	How to validate properties in 2 different situations in mvc 2 app?	public class BankPageModel : System.ComponentModel.DataAnnotations.IValidatableObject\n{\n    public bool AccountRequired { get; set; }\n    public Account NewAccount { get; set; }\n\n    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n    {\n        // only perform validation here if account required is checked\n        if (this.AccountRequired)\n        {\n            // check your regex here for account\n            if (!RegEx.IsMatch(this.NewAccount.AccountCode, "EXPRESSION"))\n            {\n                yield return new ValidationResult("Error");\n            }\n        }\n    }\n}	0
28982923	28982571	How do I make sure my external process creates a new file instead of overwriting it?	//Save file if one does not exist\nif (!File.Exists("Your File"))\n{\n   //Save file code here\n}\n\n//if file exist then add a datetime stamp to the file name so it does not overwrite the old one\nelse\n{\n  string newFileName =\n  Path.Combine(Path.GetDirectoryName("path of the file"),\n  string.Concat(Path.GetFileNameWithoutExtension("your file"), \n  DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"), \n  Path.GetExtension("your file")));\n  //Save new file code here\n }	0
4614321	4612315	How Can i Print Array of Images in Winform App in c#	WebSupergoo.ABCpdf7.Doc doc = new WebSupergoo.ABCpdf7.Doc();\n\ndoc.SetInfo(0, "License", "[your license code || trial license"]);    \ndoc.Page = doc.AddPage();\n\ndoc.AddImageBitmap(myPanel.DrawToBitmap(), false);\n\ndoc.PageNumber = 1;\ndoc.Flatten();\n\ndoc.Save("myfile.pdf");	0
2317133	2317108	How to get the first element of IEnumerable	var firstImage = imgList.Cast<Image>().First();	0
2941865	2941698	Protocol communication help	message Person {\n  required string name = 1;\n  required int32 id = 2;\n  optional string email = 3;\n\n  enum PhoneType {\n    MOBILE = 0;\n    HOME = 1;\n    WORK = 2;\n  }\n\n  message PhoneNumber {\n    required string number = 1;\n    optional PhoneType type = 2 [default = HOME];\n  }\n\n  repeated PhoneNumber phone = 4;\n}	0
8648427	8648312	I would like filter DataGridView by DataView	DataGridView1.DataSource = view;	0
1487865	1487845	Create SQL Server CE database file programmatically	string connectionString = "DataSource=\"test.sdf\"; Password=\"mypassword\"";\nSqlCeEngine en = new SqlCeEngine(connectionString);\nen.CreateDatabase();	0
2260419	2260383	Setting XML nested nodes from C# with XElement	//Get collection of productPerson elements\nIEnumerable<XElement> prodPersons = productReport.Elements("productPerson");\nforeach(XElement pp in prodPersons)\n{\n  //Set values\n  pp.Element("productPersonId").Value = "1";\n  pp.Element("productPersonName").Value = "xxx";\n}\n\n//Add a productPerson element\nXElement prodPersonEle =\n     new XElement("productPerson",\n          new XElement("productPersonId","3"),\n          new XElement("productPersonName", "Somename")\n     );\n\n\n//Add prodPersonEle to whatever parent it belongs.	0
32780524	32780523	When attempting to enable Multilingual app toolkit on a project, nothing happens	[assembly: NeutralResourcesLanguage("en")]	0
29326133	29285412	Opening a downloaded Word document with VSTO in edit mode by default	if (doc.ProtectionType != Word.WdProtectionType.wdNoProtection)\n{\ndoc.ActiveWindow.View.Type = Word.WdViewType.wdPrintView; \ndoc.Unprotect("password"); \n}	0
1030091	1030090	How do you pass multiple enum values in C#?	[Flags]\nenum DaysOfWeek\n{\n   Sunday = 1,\n   Monday = 2,\n   Tuesday = 4,\n   Wednesday = 8,\n   Thursday = 16,\n   Friday = 32,\n   Saturday = 64\n}\n\npublic void RunOnDays(DaysOfWeek days)\n{\n   bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;\n\n   if (isTuesdaySet)\n      //...\n   // Do your work here..\n}\n\npublic void CallMethodWithTuesdayAndThursday()\n{\n    this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);\n}	0
21515270	21514128	Import data from another table and mapping in xml file	XmlDocument doc = new XmlDocument();\ndoc.Load("xmlfile1.xml");\n\nstring databasename = doc.DocumentElement.Name;\n\nforeach (XmlNode node in doc.SelectNodes("/" + databasename + "/*[starts-with(name(), 'SourceTableName')]"))\n{\n    string tablename = node.Attributes["targetTable"].Value;\n    string Columns = "";\n    string Values = "";\n\n    foreach (XmlNode field in node.SelectNodes("Field"))\n    {\n        Columns += (!string.IsNullOrEmpty(Columns) ? ", " : "") + field.Attributes["targetField"].Value;\n        Values += (!string.IsNullOrEmpty(Values) ? ", " : "") + "'" + field.InnerText + "'";\n    }\n\n    //Generate insert statement\n    string statement = string.Format("Insert Into {0}.{1} ({2}) Values ({3})",\n                                    databasename,\n                                    tablename,\n                                    Columns,\n                                    Values);\n\n    Console.WriteLine(statement);\n}	0
19551702	19551308	ErrorMessage does not work in Validation Application Block 6	[NotNullValidator(MessageTemplate="Name must be not null")]	0
335563	335517	A Dictionary API for C#?	List<string> words = System.IO.File.ReadAllText("MyWords.txt").Split(new string[]{Environment.NewLine}).ToList();\n\n// C# 3.0 (LINQ) example:\n\n    // get all words of length 5:\n    from word in words where word.length==5 select word\n\n    // get partial matches on "foo"\n    from word in words where word.Contains("foo") select word\n\n// C# 2.0 example:\n\n    // get all words of length 5:\n    words.FindAll(delegate(string s) { return s.Length == 5; });\n\n    // get partial matches on "foo"\n    words.FindAll(delegate(string s) { return s.Contains("foo"); });	0
15232617	15232512	Data entered in a form doesn't get insert in the table	cmdInsert.Parameters.AddWithValue("@t1", textBox1.Text);\ncmdInsert.CommandText = "insert INTO table_name (Column1) VALUES (@t1)";	0
30631554	30551763	WinJS app with C# background task for push notifications	var bg = Windows.ApplicationModel.Background;\nvar taskBuilder = new bg.BackgroundTaskBuilder();\nvar trigger = new bg.PushNotificationTrigger();\ntaskBuilder.setTrigger(trigger);\n// Must match class name and registration in the manifest\ntaskBuilder.taskEntryPoint = "LibraryName.myPushNotificationBgTask";\ntaskBuilder.name = "pushNotificationBgTask";\ntaskBuilder.register();	0
13009562	13008970	Convert Textvalue String(Seconds) Value into Double (Second) using TimeSpan	double time = 780.0000000656558;\n        TimeSpan ts = TimeSpan.FromSeconds(time);\n        Console.WriteLine(ts.Minutes);\n        //Console.WriteLine(ts.TotalMinutes);  // this will give u mintes.fractionalpart\n        Console.ReadLine();	0
17410527	17410299	Limiting the current value of NumericUpDown control to another NumericUpDown	private void numericUpDownChartMin_ValueChanged(object sender, EventArgs e)\n    {\n         numericUpDownChartMax.Minimum = numericUpDownChartMin.Value + 1;\n    }\n\n    private void numericUpDownChartMax_ValueChanged(object sender, EventArgs e)\n    {\n         numericUpDownChartMin.Maximum = numericUpDownChartMax.Value - 1;\n    }	0
20849078	20847827	Repository pattern with generic database context	public class GenericRepository<TContext, TEntity> \n        where TContext : DbContext\n        where TEntity : class\n    {\n        internal TContext context;\n        internal DbSet<TEntity> dbSet;\n\n        public GenericRepository(TContext context)\n        {\n            this.context = context;\n            this.dbSet = context.Set<TEntity>();\n        }\n ...	0
8476066	8476011	How to set Onfocus on a text box (Inside a Modal Popup) when a button is clicked in asp.net website	protected void Page_Load(object sender, EventArgs e)\n{\n      if (!Page.IsPostBack)\n      {\n            if (!this.ClientScript.IsStartupScriptRegistered("startup"))\n            {\n                  StringBuilder sb = new StringBuilder();\n                  sb.Append("&lt;script type='text/javascript'>");\n                  sb.Append("Sys.Application.add_load(modalSetup);");\n                  sb.Append("function modalSetup() {");\n                  sb.Append(String.Format("var modalPopup = $find('{0}');", popupEntry.BehaviorID));\n                  sb.Append("modalPopup.add_shown(SetFocusOnControl); }");\n                  sb.Append("function SetFocusOnControl() {");\n                  sb.Append(String.Format("var textBox1 = $get('{0}');", txtValue.ClientID));\n                  sb.Append("textBox1.focus();}");\n                  sb.Append("&lt;/script>");\n                  Page.ClientScript.RegisterStartupScript(Page.GetType(), "startup", sb.ToString());\n             }\n      }\n}	0
12745097	12725699	How to make a save as dialog appear "early"? Or: How to make Flush() behave correctly?	// Padding to circumvent IE's buffer*\nResponse.Write(new string('*', 256));  \nResponse.Flush();	0
19816896	19813885	Updating UI with invoke or a background worker	public Form1()\n    {\n        InitializeComponent();\n\n        w = new SemaphoreSlim(1);\n        e = new SemaphoreSlim(0);\n        b = new SemaphoreSlim(6);\n\n        this.Load += new EventHandler(Form1_Load);\n    }\n\n    void Form1_Load(object sender, EventArgs e)\n    {\n        Thread t1 = new Thread(randomNr);\n        t1.Start();\n\n        Thread t2 = new Thread(gennemsnit);\n        t2.Start();\n    }	0
11484417	11484330	Removing blank space from the dictionary key name	Dictionary<string, int> dict = new Dictionary<string, int>(new Comparer());\ndict.Add("aa ", 10);\nint i = dict[" aa"];\n\npublic class Comparer : IEqualityComparer<string>\n{\n    public bool Equals(string x, string y)\n    {\n        return x.Trim().Equals(y.Trim());\n    }\n\n    public int GetHashCode(string obj)\n    {\n        return obj.Trim().GetHashCode();\n    }\n }	0
30115877	30115844	Check if a string contains a character ignoring case	foreach(string character in this.alphabeticChars)\n     if(text.ToLower().Contains(character)) \n            return true;	0
24448469	24447808	Template'd Interfaces Conflicting	public interface IFoo<T> where T : class\n{\n  T Bar();\n}\n\npublic interface IFoo<T> where T : struct\n{\n  void Bar(T x);\n}	0
32749	32747	How do I get today's date in C# in 8/28/2008 format?	DateTime.Now.ToString("M/d/yyyy");	0
9564055	9564003	list<T> property with private set	//here you are declaring a private field of class\nprivate List<FixedTickProvider> minorTickProviders;\n//and only exposing get to rest of the code\npublic List<FixedTickProvider> MinorTickProviders { get { return minorTickProviders; } }\n\n//here you are declaring a public property which can only be set by the class which is declaring it\npublic List<FixedTickProvider> MinorTickProviders { get; private set; }	0
29876019	29871686	How to Change the color of each pixel in a image by using Magick.Net	using (MagickImage image = new MagickImage())\n{\n  image.Read(@"C:\.....\test1.png");\n  image.Evaluate(Channels.Red, EvaluateOperator.Set, Quantum.Max);\n  image.Write(@"C:\.....\test2.png");\n}	0
19447420	19446956	Stackpanel remove with button click	var dc = (sender as Button).Parent as StackPanel;\n\n        (dc.Parent as StackPanel).Children.Remove(dc);	0
24465153	24450782	Umbraco - Select node by URL	UmbracoContext.Current.ContentCache.GetByRoute(string url)	0
6050136	6050096	Writing a unit test for a function with a web request	public WebRequest GetRequest(string url);\npublic object DeSerializeJSON(WebRequest request, Type type);	0
17961209	17961161	Split string with colon (:) and separate the numbers with colon	var input = "D93:E93 E98 E9:E10 E26 D76:E76 D83:E83 D121:D124";\nvar list = input.Split(' ');\n\nvar result = new List<String>();\nforeach (var item in list)\n{\n    var parts = item.Split(':');\n    if (parts.Length == 1) result.Add(parts[0]);\n    else\n    {\n        if (parts[0].Substring(0, 1).CompareTo(parts[1].Substring(0, 1)) == 0)\n        {\n            var i = Convert.ToInt32(parts[0].Substring(1));\n            var j = Convert.ToInt32(parts[1].Substring(1));\n\n            while (i < j)\n            {\n                result.Add(parts[0].Substring(0, 1) + i);\n                i++;\n            }\n\n            if (i == j)\n            {\n                result.Add(parts[0].Substring(0, 1) + i);\n            }\n        }\n        else\n        {\n            result.Add(parts[0]);\n            result.Add(parts[1]);\n        }\n    }\n}\nConsole.WriteLine(string.Join(", ", result));\n\n//output\nD93, E93, E98, E9, E10, E26, D76, E76, D83, E83, D121, D122, D123, D124	0
5964788	5964607	Starting internet explorer in open tab	Process.start(url)	0
19506309	19506177	Use Foreach in LIST for 2 Fields	for (int i = 0; i < tagsList.Count; i += 2)\n     Messagebox.Show(tagsList[i] + " " + tagsList[i + 1]);	0
23035109	23034991	Parsing JSON Files with JSON.NET	WebClient client = new WebClient();\nstring getString =  client.DownloadString("http://media1.clubpenguin.com/play/en/web_service/game_configs/furniture_items.json");\n\n\nJavaScriptSerializer serializer = new JavaScriptSerializer(); \nvar listOfFurniture = serializer.Deserialize<List<Furniture>>(getString);\n\n\npublic class Furniture\n{\n    public int furniture_item_id { get; set; }\n}	0
9134290	9133998	List only contains first two items	var testNumbers = new List<object>();\ntestNumbers.Add(15);\ntestNumbers.Add("AUUUGHH");\ntestNumbers.Add(42);\n\nforeach (var i in testNumbers)\n    Console.WriteLine(Microsoft.VisualBasic.Information.IsNumeric(i));	0
17192923	17192650	How to let a datagridview automatically generate new rows to fill the empty space	private void Form1_Resize(object sender, EventArgs e)\n    {\n        dataGridView1.Rows.Clear();\n        while ((dataGridView1.Rows.Count == 0) || (dataGridView1.Rows[0].Height * dataGridView1.Rows.Count < (dataGridView1.Height - dataGridView1.ColumnHeadersHeight)))\n        {\n            dataGridView1.Rows.Add(/*Your generated row information*/);                \n        }\n    }	0
20716312	20709764	RSA C# encryption with public key to use with PHP openssl_private_decrypt(): Chilkat, BouncyCastle, RSACryptoServiceProvider	Object obj;\nusing (TextReader sr = new StringReader(publicKey))\n{\n    PemReader pem = new PemReader(sr);\n    obj = pem.ReadObject();               \n}\nvar par = obj as Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters;\n\nRSACryptoServiceProvider csp = new RSACryptoServiceProvider(1024);        \n//var pp = csp.ExportParameters(false); //works on native .NET, doesn't work on monotouch\nvar pp = new RSAParameters();\npp.Modulus = par.Modulus.ToByteArrayUnsigned(); //doesn't work with ToByteArray()\npp.Exponent = par.Exponent.ToByteArrayUnsigned();                          \ncsp.ImportParameters(pp);\nvar cspBytes = csp.Encrypt(bytes, false);	0
9810640	9810565	Adding a property to list<T> at runtime	var locations = mlaLocations.ToList().Select(x => new {\n        where = x.Address.Street1 + ", " + x.Address.City,\n        email =x.Email }\n);	0
11684608	11684571	C#, how to get only GET parameters?	var someValueFromGet = Request.QueryString["YourGetPara"];\nvar someValueFromPost = Request.Form["YourPostPara"];	0
1703408	1703387	What's the best way to implement a search?	Full-text Search	0
24469976	24457067	Call Navigation/Maps/Drive with an Address in WP8.1 Application	string locationName = "Empire State Building";\nstring address = "350 5th Avenue, New York City, New York 10018";\n\nvar locFinderResult = await MapLocationFinder.FindLocationsAsync(\n    address, new Geopoint(new BasicGeoposition()));\n\n// add error checking here\n\nvar geoPos = locFinderResult.Locations[0].Point.Position;\n\nvar driveToUri = new Uri(String.Format(\n     "ms-drive-to:?destination.latitude={0}&destination.longitude={1}&destination.name={2}", \n     geoPos.Latitude, \n     geoPos.Longitude, \n     locationName));\n\nLauncher.LaunchUriAsync(driveToUri);	0
3512122	3481041	Generate an concatenated SMS UDH and prepend it to message text	private string BuildUdh(byte messageId, byte partCount, byte partId)\n{\n    var udg = new byte[6];\n    udg[0] = 0x05;      // Overall length of UDH\n    udg[1] = 0x00;      // IE Concat \n    udg[2] = 0x03;      // IE parameter Length\n    udg[3] = messageId;\n    udg[4] = partCount;\n    udg[5] = partId;\n[..]	0
1860829	1860816	C# Ending Regex statement	Regex.Match(contents, "Security=(?<Security>[^;]+)").Groups["Security"].Value	0
10984944	10948731	Page truncate in right side for landscape orientation with trimmargins using PdfSharp	page = document.AddPage();\n//page.Size = PdfSharp.PageSize.A4;\nXSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);\nif(page.Orientation == PageOrientation.Landscape)\n{\n   page.Width  = size.Height;\n   page.Height = size.Width;\n}\nelse\n{\n   page.Width  = size.Width;\n   page.Height = size.Height;\n}\n\n// default unit in points 1 inch = 72 points\npage.TrimMargins.Top = 5;\npage.TrimMargins.Right = 5;\npage.TrimMargins.Bottom = 5;\npage.TrimMargins.Left = 5;	0
1221756	1221140	Read a sound backward with DirectSound	public static void ReverseWaveFile(string inputFile, string outputFile)\n    {\n        using (WaveFileReader reader = new WaveFileReader(inputFile))\n        {\n            int blockAlign = reader.WaveFormat.BlockAlign;\n            using (WaveFileWriter writer = new WaveFileWriter(outputFile, reader.WaveFormat))\n            {\n                byte[] buffer = new byte[blockAlign];\n                long samples = reader.Length / blockAlign;\n                for (long sample = samples - 1; sample >= 0; sample--)\n                {\n                    reader.Position = sample * blockAlign;\n                    reader.Read(buffer, 0, blockAlign);\n                    writer.WriteData(buffer, 0, blockAlign);\n                }\n            }\n        }\n    }	0
2073808	2073751	Winforms Wait to draw Until Controls Added	class DrawingControl\n{\n    [DllImport("user32.dll")]\n    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);\n\n    private const int WM_SETREDRAW = 11; \n\n    public static void SuspendDrawing( Control parent )\n    {\n        SendMessage(parent.Handle, WM_SETREDRAW, false, 0);\n    }\n\n    public static void ResumeDrawing( Control parent )\n    {\n        SendMessage(parent.Handle, WM_SETREDRAW, true, 0);\n        parent.Refresh();\n    }\n}	0
29876258	28502585	OpenGL deferred rendering: point light implementation	vec3 distance = toLight * (1.0 / LightRadius);\nfloat attenuation = clamp(1 - dot(distance, distance), 0, 1);\nattenuation = attenuation * attenuation;	0
27886873	27275098	IEnumerable Select statement with ternary operator	public class SomeClass\n    {\n        public int X { get; set; }\n        public int Y { get; set; }\n\n        public void Test()\n        {\n            //Here I'm creating a List of Some class\n            var someClassItems = new List<SomeClass> { \n                new SomeClass { X = 1, Y = 1 }, \n                new SomeClass { X = 2, Y = 2 } \n            };\n\n            //Here I'm creating a Query\n            //BUT, I'm not executing it, so the query variable, is represented by the IEnumerable object\n            //and refers to an in memory query\n            var query = someClassItems.\n                Select(o => o.X);\n\n            //Only once the below code is reached, the query is executed.\n            //Put a breakpoint in the query, click the mouse cursor inside the select parenthesis and hit F9\n            //You'll see the breakpoint is hit after this line.\n            var result = query.\n                ToList();\n\n        }\n    }	0
8588117	8588022	How do I get Friday date if it is Monday today	public DateTime GetPreviousWorkingDay(DateTime date)\n{\n    switch(date.DayOfWeek)\n    {\n        case DayOfWeek.Sunday:\n            return date.AddDays(-2);\n        case DayOfWeek.Monday:\n            return date.AddDays(-3);\n        default:\n            return date.AddDays(-1);\n    }\n}	0
17304510	17304400	Make windows service run as if it was run from a specific user	Process.Start(path + "HelloWorld.exe", args, uname, password, domain);	0
16911710	16911660	Disable right click in Win form app	private void uc_MouseClick(object sender, MouseEventArgs e)\n{\n    if (e.Button == System.Windows.Forms.MouseButtons.Left)\n    {\n         //more logic here\n    }\n}	0
20401832	20401688	String Format wrong format for %	chart.ChartAreas[series.Name].AxisY.LabelStyle.Format =\n     "{0.# '" + unit + "';-0.# '" + unit + "';0 '" + unit + "'}";	0
22386589	22386184	How to show all data results to listview?	while (objRead.Read())\n    {\n        ListViewItem list = new ListViewItem(basa["FID"].ToString());\n        list.SubItems.Add(objRead["FullName"].ToString());\n        list.SubItems.Add(objRead["Age"].ToString());\n        list.SubItems.Add(objRead["Gender"].ToString());\n        list.SubItems.Add(objRead["Relationship"].ToString());\n        list.SubItems.Add(objRead["SkillnOccupation"].ToString());\n        lvlist.Items.Add(list);\n    }	0
11883565	11882815	Preparing table in C# as PHP?	var table =  new {\n    function = "saveStats",\n    data = new  {\n        id = "6079f20ac3_1344412683016_427" , \n        stat = new List<dynamic>  {\n                          new {  n461 = "1834!:!606113;263..." },\n                          new {  n462 = "947679;1976657;14..." }\n                        },\n        userAgent = "Mozilla/5.0 (Windows NT 6.1; rv:14.0) Gecko/20100101 Firefox/14.0.1",\n        ip = "::1",\n        referer = "Brak",\n        limit = 1\n    }\n };	0
15878148	15877607	DateTimePicker selection only with DropDown	private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)\n    {\n        e.SuppressKeyPress = true;\n    }	0
24227279	24227071	How to apply outer border for a GraphicsPath	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        this.Load += new System.EventHandler(this.Form1_Load);\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);\n    }\n\n    private void Form1_Paint(object sender, PaintEventArgs e)\n    {\n        GraphicsPath graphicsPath = new GraphicsPath();\n        Point[] pts = new Point[] { new Point(20, 20), \n                                    new Point(120, 20), \n                                    new Point(120, 50), \n                                    new Point(60, 50),        \n                                    new Point(60, 70), \n                                    new Point(20, 70) };\n\n        graphicsPath.AddPolygon(pts);\n\n        e.Graphics.FillPath(Brushes.LightGreen, graphicsPath);\n        e.Graphics.DrawPath(Pens.DarkGreen, graphicsPath);\n    }\n}	0
10081792	10036858	Change ToolStripDropDownButton Text by Selecting Item	private void changeGridSizeDropDownButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)\n    {\n        if (e.ClickedItem != null)\n        {\n            changeGridSizeDropDownButton.Text = e.ClickedItem.Text;\n            // This line converts my list gridsize options like 64, 32, and 16\n            // and Parses that text into the new selected gridsize.\n            gridSize = Int32.Parse(e.ClickedItem.Text);\n        }\n    }	0
20974310	20974179	Select and updating data from datatable	DataRow[] HRow = dataSet1.Tables["Human"].Select("Size >= 230 AND Sex = 'm'");\n\nHRow[0]["Size"] = 230;\n\nHRow[0]["Sex"] = "m";	0
29295718	29285394	Read from a manually writen .txt file. Windows Phone 8 Silverlight	var store = IsolatedStorageFile.GetUserStoreForApplication();\ntry\n{\n    if (store.FileExists(path))\n    {\n        using (var stream = store.OpenFile("fileName", FileMode.Open))\n        {\n            //Read your file\n        }\n    }\n}\ncatch (Exception e)\n{\n    //Handle Exception\n}	0
4073282	4073244	how to parse out image name from image url	string fileName = Path.GetFileName(@"http://www.google.com/test/test23/image1.jpg");	0
24149961	24149841	Group by column. If null, group by other column	db.EntityValues.GroupBy(v => v.Entity.OriginalEntityID ?? v.Entity.EntityID);	0
14712647	14708098	Generating random numbers for solar energy harvesting using Markov models	// The line addEntry('h', "e 50 a 23 i 12 o  7 @ 100") shows the the letter\n// 'h' is followed by 'e' 50% of the time, 'a' 23% of the time, 'i' 12% of \n// the time, 'o' 7% of the time and otherwise some other letter, '@'.\n//\n// Figures are taken from Gaines and tweaked. (see 'q')\nprivate void initMarkovTable() {\n    mMarkovTable = new HashMap<Character, List<CFPair>>(26);\n\n    addEntry('a', "n 21 t 17 s 12 r 10 l  8 d  5 c  4 m  4 @ 100");\n    addEntry('b', "e 34 l 17 u 11 o  9 a  7 y  5 b  4 r  4 @ 100");\n    addEntry('c', "h 19 o 19 e 17 a 13 i  7 t  6 r  4 l  4 k  4 @ 100");\n    addEntry('d', "e 16 i 14 a 14 o 10 y  8 s  6 u  5 @ 100");\n    addEntry('e', "r 15 d 10 s  9 n  8 a  7 t  6 m  5 e  4 c  4 o  4 w 4 @ 100");\n    addEntry('f', "t 22 o 21 e 10 i  9 a  7 r  5 f  5 u  4 @ 100");\n    addEntry('g', "e 14 h 14 o 12 r 10 a  8 t  6 f  5 w  4 i  4 s  4 @ 100");\n    addEntry('h', "e 50 a 23 i 12 o  7 @ 100");\n    // ...\n}	0
32464867	32464748	C# WIndows phone disable button after one press	Button myButton = FindName("ButtonName") as Button;\n myButton.IsEnabled = false;	0
19813592	19813461	Insert data into multiple table using linq	ent.tbltels.AddObject(tbltel);	0
9015593	6351425	Get rid of d2p1 in XML created with DataContract in Serialized Class	namespace PostIt\n{\n    [DataContract(Name = "ResultRequest", Namespace = "YourNamespace")]\n    public class Result\n    {\n        [DataMember]\n        Models.Core.Order order;\n        [DataMember]\n        int ErrorCode;\n        [DataMember]\n        String Message;\n        ...\n    }\n    namespace Models.Core\n    {\n        [Serializable]\n        [DataContract(Name = "Order", Namespace = "YourNamespace"]\n        public partial class Order\n        {\n            ...	0
21589966	21589451	Load multiple images to a wpf image control	void Ps_Sample_Apl_CS_ShowSilhouette(MemoryStream buff)\n{\n    BitmapImage bitmapImage = new BitmapImage();\n    bitmapImage.BeginInit();\n    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n    bitmapImage.StreamSource = buff;\n    bitmapImage.EndInit();\n    ImagePic.Source = bitmapImage;\n}	0
13608871	13605493	Save content of a canvas with serialization to WPF	public static void SerializeToXML(MainWindow window, Canvas canvas, int dpi, string filename)\n    {\n        string mystrXAML = XamlWriter.Save(canvas);\n        FileStream filestream = File.Create(filename);\n        StreamWriter streamwriter = new StreamWriter(filestream);\n        streamwriter.Write(mystrXAML);\n        streamwriter.Close();\n        filestream.Close();\n    }	0
8497491	8497475	C# Variable length string array	string[][] str =\n{\n    new string[] { "Item1", "Item2" },\n    new string[] { "Item1", "Item2", "Item3", "Item4" }\n};	0
29887811	29887785	How to get hard drive unique serial number in C#	searcher = new\n    ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");\n\n   int i = 0;\n   foreach(ManagementObject wmi_HD in searcher.Get())\n   {\n    // get the hard drive from collection\n    // using index\n    HardDrive hd = (HardDrive)hdCollection[i];\n\n    // get the hardware serial no.\n    if (wmi_HD["SerialNumber"] == null)\n     hd.SerialNo = "None";\n    else\n     hd.SerialNo = wmi_HD["SerialNumber"].ToString();\n\n    ++i;\n   }	0
7644046	7643985	Model binder woes	public class ExpertsVM\n{\n    public string GivenName {get;set;}\n    public string Surname {get;set;}\n}	0
16457591	16456608	aChartEngine shows two charts instead one	multiRenderer.setInScroll(true);	0
5657517	2642141	How to Create Deterministic Guids	Guid guid = GuidUtility.Create(GuidUtility.UrlNamespace, filePath);	0
9634994	9634363	assign data from table to labels using c#	SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);\nstring qry="select * from personal,Intrebari where personal.cod_numeric_personal=@cnp AND Intrebari.id_intrebare IN (14,15);\n\nSqlCommand cmd = new SqlCommand(qry, con);\ncmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);\ntry\n{  \n   con.Open();    \n   SqlDataReader rdr= cmd.ExecuteReader();\n   if(rdr.HasRows)\n   {    \n        while (rdr.Read())\n        {\n            lbl1.Text = rdr["Nume"].ToString();\n            intrebare6.Text = rdr["Intrebari"].ToString();\n            intrebare7.Text = rdr["Intrebari"].ToString();\n        }\n   }\n}\ncatch(SQLException ex)\n{\n   lblStatus.Text="An error occured"+ex.Message;\n   throw ex;\n}\nfinally\n{\n   con.Close();\n   con.Dispose();\n}	0
20002609	20002432	Unable to Parse this Json string in c#	JArray values = JArray.Parse(json);\n\nstring key;\nvar keyObject = values.FirstOrDefault(p => (int)p["id"] == 1);\nif (keyObject != null)\n{\n     key = (string)keyObject["key"];\n}	0
34044155	34043689	Need help getting camera to follow instantiated GameObject (player)	GameObject player = (GameObject)Network.Instantiate(playerPrefab, Vector3.up * 5, Quaternion.identity, 0);\ntarget = player.transform;\noffset = transform.position - target.position;	0
915055	915024	String array to notepad	string[] array = { "a", "b", "c" };\nstring lines = string.Join(Environment.NewLine, array);	0
12528189	12528186	How do I get a unique identifier for a machine running Windows 8 in C#?	private string GetHardwareId()  \n{  \n    var token = HardwareIdentification.GetPackageSpecificToken(null);  \n    var hardwareId = token.Id;  \n    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);  \n\n    byte[] bytes = new byte[hardwareId.Length];  \n    dataReader.ReadBytes(bytes);  \n\n    return BitConverter.ToString(bytes);  \n}	0
21264454	21264096	Issue with Delete button in GridView in Visual Studio	delcmd.CommandText = "DELETE FROM SuperCars WHERE Car Like '%" +dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";	0
6419268	4254371	Enabling Foreign key constraints in SQLite	data source=C:\Dbs\myDb.db;foreign keys=true;	0
12001848	12001194	Using GPU to speed up BigInteger calculations	C = A + B means allocating 100MB for C (this is what BigInt does)\nA = A + B means you no longer have the original A, but a much faster calculation	0
7181535	7180755	Deploy & consume static content for use with a Windows Service	string connStr = "server=.;database=AdventureWorksLT;integrated security=true;";\nstring currentPath=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));\nusing (CustomDataContext context = new CustomDataContext(connStr, XmlMappingSource.FromUrl(currentPath+"\\CustomerMapping.xml")))\n{\n\n}	0
2583104	2581301	Converting WCF binding from wsHttpBinding to netTcpBinding	net.tcp://......	0
8240440	8240402	How to get intellisense for custom created classes?	/// <summary>\n    /// \n    /// </summary>\n    /// <param name="sender"></param>\n    /// <param name="e"></param>\n    void Method(object sender, EventArgs e)	0
21505039	21504627	Draw smooth line in InkCanvas WPF with Kinect	line.StrokeDashCap = PenLineCap.Round; \nline.StrokeStartLineCap = PenLineCap.Round; \nline.StrokeEndLineCap = PenLineCap.Round;	0
17358034	17357951	string not converting to integer	Double d;\n\nif (Double.TryParse(test.Class, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) {\n  Int32 i = (Int32) d;\n  // <- Do something with i\n}\nelse {\n  // <- test.Class is of incorrect format\n}	0
33939282	33938280	Load multiple 'nodes' from JSON and store into array	{\n    "Game": [\n        {\n            "Room": "Vault111FreezeChamber",\n            "Attributes": {\n                "Description": "Thefreezechamberofthevaultyouenteredafterthenuclearfallout.",\n                "Exits": "North.Vault111: MainHallway"\n            },\n            "Room": "Vault111MainHallway",\n            "Attributes": {\n                "Description": "Themainhallwayofthevault.",\n                "Exits": "South.Vault111: FreezeChamber"\n            }\n        }\n    ]\n}	0
11760457	11760428	Remove domain name from machine name	string fullName = "MYMACHINE.mydomain.com";\nstring resolvedMachineName = fullName.Split('.')[0];	0
8395397	8393462	Remove line segments that are shared between rectangles	// create a pen with a width of 2px (half of it will be blanked out so it will\n// essentially be a width of 1px)\nPen pen = new Pen(Color.Blue, 2f);\n\n// build a GraphicsPath with the rectangles\nGraphicsPath gp = new GraphicsPath();\ngp.AddRectangle(...);\ngp.AddRectangle(...);\ngp.AddRectangle(...);\n\n// g is our Graphics object\n// exclude the region so the path doesn't draw over it\nRegion reg = new Region(gp);\ng.ExcludeClip(reg);\n\n// now draw path, it won't show up inside the excluded clipping region\ng.DrawPath(pen, gp);\n\n// clean up\ng.ResetClip();\npen.Dispose();\ngp.Dispose();\nreg.Dispose();	0
24741739	24741023	How to get multiple selected items from ListPicker and display them in MessageBox	private void btnAddLocation_Click(object sender, RoutedEventArgs e)\n{\n    string r = "";\n    for (int i=0; i<this.lstPickerType.SelectedItems.Count; i++)\n    {\n        r += ((ListPickerItem)this.lstPickerType.SelectedItems[i]).Content;\n        if (i != this.lstPickerType.SelectedItems.Count - 1) \n            r += ", ";\n    }\n    MessageBox.Show(r);\n}	0
11461536	11461376	Obtaining InnerText of just the current node with XmlNode	socialTagNode.ChildNodes[0].Value	0
8034664	8000253	C# & Nhibernate - Persist a List of itens of one entity to another	Previa PreviaOld = PreviaBLL.Search(Convert.ToInt32(txtPreviaOld.Text));\nif (objPreviaOld != null) \n{\n      foreach (ItemPrevia itemPrevia in objPreviaOld.ListItemPrevia)\n      {\n          PreviaNew.ListItemPrevia.Add(new ItemPrevia\n          {\n              Previa = PreviaNew,\n              Prop1 = itemPrevia.Prop1,\n              Prop2 = itemPrevia.Prop2,\n              Prop3 = itemPrevia.Prop3,\n              Prop4 = itemPrevia.Prop4,\n          });\n      }\n      PreviaBLL.Alter(PreviaNew);\n}	0
19429703	19429230	Flip grouping in LINQ	changesets.SelectMany(x => x.workitems.Select(y => new {\n                                                         changeset = x.id,\n                                                         workitem=y.id})\n          .GroupBy(x => x.workitem)\n          .Select(x => new {\n                              workitem = x.Key, \n                              Changesets = x.Select(y = > y.changeset).ToArray()\n                           }).ToArray();	0
1683249	1683184	ASP.NET - Dynamically added button contains extra value property	case 1:\n   myControl = new Button();\n   ((Button)myControl).Text="Submit me!";\n   myControl.Attributes.Add("type","submit");\n   break;	0
2818510	2818436	How do I dispatch to a method based on a parameter's runtime type in C# < 4?	private Dictionary<Type, Action<I>> _mapping = new Dictionary<Type, Action<I>>\n{ \n  { typeof(A), i => MethodA(i as A)},\n  { typeof(B), i => MethodB(i as B)},\n  { typeof(C), i => MethodC(i as C)},\n};\n\nprivate void ExecuteBasedOnType(object value)\n{\n    if(_mapping.ContainsKey(value.GetType()))\n       _mapping(value.GetType())(value as I);\n}	0
24401151	24400956	Quickbook Data in to Sql server using SDK	SQL Server Integration service (SSIS)	0
7386528	7384117	How to access a class from a listbox item?	//All\nforeach(Books book in theBookListBox.Items)\n{\n}	0
630278	630263	C#: Compare contents of two IEnumerables	A.Except(B).Count() == 0 && B.Except(A).Count() == 0\nA.Count() == B.Count() && A.Intersect(B).Count() == B.Count()\netc	0
33282196	33281862	Saving to database, then reading from database, data is not there	public void Page_Load() {\n    // ...\n\n    if (!IsPostBack) {\n        // code read the data\n    }\n}	0
9807657	9807295	Loop through for each key in Multi key dictionary	Dictionary<int, Dictionary<int, List<int>>> outer = new Dictionary<int, Dictionary<int, List<int>>>();\nforeach(var outerKey in outer.Keys.OrderBy(x => x))\n{\n    foreach(var innerKey in outer[outerKey].Keys.OrderBy(x => x))\n        Console.WriteLine(outer[outerKey][innerKey]);\n}	0
3801289	3801275	How to convert image in byte array	public byte[] imageToByteArray(System.Drawing.Image imageIn)\n{\n   using (var ms = new MemoryStream())\n   {\n      imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);\n      return  ms.ToArray();\n   }\n}	0
7777526	7777417	C# How can i split a string correctly?	var lst = new List<string>();\nfor (int i=0;i<str.Length;i++)\n{\n\n if (char.IsDigit(str[i])\n {\n    var tmp = new string(new []{str[i]});\n    i++;\n    while(i<str.Length && char.IsDigit(str[i]))\n       { tmp+= str[i]; i++}\n    i--;\n    lst.Add(tmp);\n }\n else\n  lst .Add(new string(new []{str[i]}));\n}	0
12240902	12240857	How to get content from file from this URL?	var webRequest = WebRequest.Create(@"http://yourUrl");\n\nusing (var response = webRequest.GetResponse())\nusing(var content = response.GetResponseStream())\nusing(var reader = new StreamReader(content)){\n    var strContent = reader.ReadToEnd();\n}	0
10543691	10543117	convert ip ranges to ip with subnet	byte[] ip1 = {1, 1, 1, 0};\nbyte[] ip2 = {1, 1, 1, 255};\nbyte[] omask = \n{\n    (byte)(ip1[0] ^ ip2[0]), \n    (byte)(ip1[1] ^ ip2[1]), \n    (byte)(ip1[2] ^ ip2[2]),\n    (byte)(ip1[3] ^ ip2[3])\n};\nstring mask = Convert.ToString(omask[0], 2) + Convert.ToString(omask[1], 2)\n              + Convert.ToString(omask[2], 2) + Convert.ToString(omask[3], 2);\n// count the number of 1's in the mask. Substract to 32:\n// NOTE: the mask doesn't have all the zeroes on the left, but it doesn't matter\nint bitsInMask = 32 - (mask.Length - mask.IndexOf("1")); // this is the /n part\nbyte[] address = \n{\n    (byte)(ip1[0] & ip2[0]), \n    (byte)(ip1[1] & ip2[1]), \n    (byte)(ip1[2] & ip2[2]),\n    (byte)(ip1[3] & ip2[3])\n};\nstring cidr = address[0] + "." + address[1] + "." \n    + address[2] + "." + address[3] + "/" + bitsInMask;	0
21537019	21489121	How do I search for a type in .NET, disregarding the assembly version?	type = Type.GetType(typename,\n    assemblyName =>\n    {\n        return AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName.Name);\n    },\n    (assembly, typeName, caseInsensitive) =>\n    {\n        if (caseInsensitive)\n            return assembly.GetTypes().SingleOrDefault(t => t.FullName.Equals(typeName, StringComparison.InvariantCultureIgnoreCase));\n        else\n            return assembly.GetTypes().SingleOrDefault(t => t.FullName == typeName);\n    });	0
32816821	32816704	how to change the filename to save in particular folder	var filename = postedFile.FileName;\nvar FileNameOnly  =  Path.GetFileNameWithoutExtension(fileName);\nVar fileExt = Path.GetExtension(fileName);\nvar ModFileName = FileNameOnly + DateTime.Now + fileExt;\nvar filePath = HttpContext.Current.Server.MapPath("~/" + ModFileName);\npostedFile.SaveAs(filePath);	0
17708501	17708430	Make own datatype without new modifier	public MyClass()\n{\n     _money = new Money();\n}	0
3674608	3674564	Javascript to validate password	if (password.length < 6) {\n  alert("password needs to be atleast 6 characters long"); \n}\n\nvar count = 0;\n//UpperCase\nif( /[A-Z]/.test(password) ) {\n    count += 1;\n}\n//Lowercase\nif( /[a-z]/.test(password) ) {\n    count += 1;\n}\n//Numbers  \nif( /\d/.test(password) ) {\n    count += 1;\n} \n//Non alphas( special chars)\nif( /\W/.test(password) ) {\n    count += 1;\n}\nif (count < 3) {\n  alert("password does not match atleast 3 criterias"); \n}	0
16714369	16714269	Obtain selected value from dropdown in code behind	ListItem li = Select1.Items.FindByText("Three");\nListItem li = Select1.Items.FindByValue("3");\nli.Selected = true;	0
27268076	27267879	How can i check every alphabet inside one string variable?	foreach (var item in sentence)\n{\n    ....\n}	0
14186193	14186165	partition a number range based on a size and then find the start of a partition for a given number in that range	int page = 56;\nint partition_size = 10;\n\nint starting_number = (page / partition_size) * partition_size + 1;	0
3716506	3712017	How to identify what state variables are read/written in a given method in C#	method A( ) {  Object q=this;\n                     ...\n                     ...q=that;...\n                     ...\n                     foo(q);\n               }	0
16572062	16307157	Kendo Grid Custom Add Popup, Value in Controller Post Action is null	[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult KendoEmailAdd([DataSourceRequest] DataSourceRequest request, ContactEmail newEmail, int id)\n{\n  if (newEmail != null)\n  {\n    ContactEmail email = new ContactEmail();\n\n    email.DescriptionOf = newEmail.DescriptionOf;\n    email.Email = newEmail.Email;\n    email.EntityID = id;\n    email.PrimaryEmail = newEmail.PrimaryEmail;\n\n    db.ContactEmails.Add(email);\n    db.SaveChanges();\n  }\n\n  return Json(new[] { newEmail }.ToDataSourceResult(request, ModelState));\n}	0
16240625	16240581	How to get a Brush from a RGB Code?	var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));\nmyGrid.Background = brush;	0
10348685	10348452	resize bitmap image in cell of datagridview	bool isReadOnly = myImage.IsSealed;	0
3259028	3258824	OOP style inheritance in Haskell	data A = A {field1 :: Int, field2 :: Int, ..., field9999 :: Int}\ndata B = B {a :: A, field10000 :: Int}\n\nclass ABC a where\n    f :: a -> Int\n\ninstance ABC A where\n    f a = field1 a + field101 a\n\ninstance ABC B where\n    f b = f (a b) + field10000 b	0
25312432	25312311	String formatting with braces	string.Format("{{{0}}}", x.ToString("C"))	0
20519307	20519089	Passing listBox to a new form	public Form2(ListBox listBox)\n{\n    InitializeComponent();\n    listBox1.Items.AddRange(listBox.Items);\n}	0
20478580	20474130	Converting [string].ToString([custom format])	public string FormatString(string value, string format = "")\n{\n    if (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(format))\n        return value;\n\n    var newValue = new StringBuilder(format);\n\n    for (int i = 0; i < newValue.Length; i++)\n    {\n        if (newValue[i] == '#')\n            if (value.Length > 0)\n            {\n                newValue[i] = value[0];\n                value = value.Substring(1);\n            }\n            else\n            {\n                newValue[i] = '0';\n            }\n    }\n\n    return newValue.ToString();\n}	0
7816089	7816036	Trouble with using predicatebuilder in a foreach loop	foreach (SomeOtherType t in inputEnumerable) \n{ \n    SomeOtherType localT = t;\n    Predicate = Predicate.Or( x => x.ListInSomeType.Contains(localT) ) \n}	0
1585151	1585127	Starting a process with Windows start-up (can not find supporing files)	Directory.SetCurrentDirectory(\n    Path.GetDirectoryName(\n        Assembly.GetExecutingAssembly().Location\n    )\n);	0
19688770	19688335	How to write distinct and count in a linq query?	int? startFilter = 10;\n\n\n        var test1 = items.Where(i => startFilter.HasValue == false || i.Starts == startFilter.Value)\n                         .GroupBy(i => i.Keyword).Select(grp => new { Keyword = grp.Key, Count = grp.Count()})\n                         .ToList();	0
14461446	14230354	Save and Save As in Telerik RichText Editor	string variable	0
8829226	8829171	Conversion of double to datetime always fails	static DateTime ConvertFromUnixTimestamp(double timestamp)\n{\n    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);\n    return origin.AddSeconds(timestamp);\n}	0
31320682	31320049	C# MultiThreading: pool of calculators	Calculator calc = null;\nlock(calculators)\n{\n    calc = calculators[0];\n\n}\nlock(calc)\n{\n    // ... do stuff\n}	0
1287028	1286354	How to make my application copy file faster	class Downloader\n{\n    const int size = 4096 * 1024;\n    ManualResetEvent done = new ManualResetEvent(false);\n    Socket socket;\n    Stream stream;\n\n    void InternalWrite(IAsyncResult ar)\n    {\n        var read = socket.EndReceive(ar);\n        if (read == size)\n            InternalRead();\n        stream.Write((byte[])ar.AsyncState, 0, read);\n        if (read != size)\n            done.Set();\n    }\n\n    void InternalRead()\n    {\n        var buffer = new byte[size];\n        socket.BeginReceive(buffer, 0, size, System.Net.Sockets.SocketFlags.None, InternalWrite, buffer);\n    }\n\n    public bool Save(Socket socket, Stream stream)\n    {\n        this.socket = socket;\n        this.stream = stream;\n\n        InternalRead();\n        return done.WaitOne();\n    }\n}\n\nbool Save(System.Net.Sockets.Socket socket, string filename)\n{\n    using (var stream = File.OpenWrite(filename))\n    {\n        var downloader = new Downloader();\n        return downloader.Save(socket, stream);\n    }\n}	0
2913973	2911347	How do I serialize an object to xml but not have it be the root element of the xml document	//Result:\n<MyClass>\n<Id>1</Id>\n<Name>My Name</Name>\n</MyClass>	0
30027625	30027430	Windows Phone Offline routing	However, mapping services also work without Internet connectivity when maps are downloaded for offline use.	0
20782677	20782578	match Email Regular expression from html string	emailregex.Match(istr).Groups["mail"].Value	0
30074061	30073887	morelinq distinct by multiple properties	list = list\n           .GroupBy(a=> new { a.id, a.parentid})\n           .Select(a=> a.first());	0
3096316	3088629	Call Function Import from custom ObjectContext	public int LogOn(global::System.String UserName, global::System.String Password)\n{\n    ObjectParameter UserNameParameter;\n    if (UserName != null)\n    {\n        UserNameParameter = new ObjectParameter("USERNAME", UserName);\n    }\n    else\n    {\n        UserNameParameter = new ObjectParameter("USERNAME", typeof(global::System.String));\n    }\n\n    ObjectParameter UserpasswordParameter;\n    if (Password != null)\n    {\n        UserpasswordParameter = new ObjectParameter("USERPWD", Password);\n    }\n    else\n    {\n        UserpasswordParameter = new ObjectParameter("USERPWD", typeof(global::System.String));\n    }\n\n    return base.ExecuteFunction("LogOn", UserNameParameter, UserpasswordParameter);\n}	0
11690427	11657320	How can I configure a grid view column to hold a hyperlink myself?	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n       {\n        String Process = e.Row.Cells[0].Text;\n        HyperLink link = new HyperLink();\n        link.Text = Process;\n        link.NavigateUrl = String.Format("~/IndexSummary.aspx?Process={0}&Machine={1}&Date={2}", Process, Request.QueryString["Machine"], Request.QueryString["Date"]);\n        e.Row.Cells[0].Controls.Add(link);\n\n       }	0
2300178	2300147	C# How to replace parts of one string with parts of another	long number = 2221239876;\nstring result = number.ToString("(###) ### ####");    // Result: (222) 123 9876	0
10506571	10504394	uploading a video file to Facebook with description and action links	var description = "Bring your conversations to life on Facebook. With face-to-face video calling, now you can watch your friends smile, wink and LOL.\n\nTo get started, visit http://www.facebook.com/videocalling"; \n\nstring fullurl = string.Format("https://graph-video.facebook.com/me/videos?title={0}&description={1}&access_token={2}", HttpUtility.UrlEncode(title), HttpUtility.UrlEncode(description ), accessToken);	0
5603939	5603910	c# good style - internal enums in a method	public class TheClass\n{\n    private enum TheEnum \n    {\n       stHeader, \n       stBody, \n       stFooter\n    }\n\n    // ...the rest of the methods properties etc... \n}	0
24567634	24550938	Getting Cycle names from Releases in HP ALM?	foreach (TDAPIOLELib.Release rl in listRel)\n        {\n\n            string RelStartDate = Convert.ToString(rl.StartDate);\n            string RelEndDate = Convert.ToString(rl.EndDate);\n            CycleFactory CyF = rl.CycleFactory;\n\n            foreach (TDAPIOLELib.Cycle Cyc in CyF.NewList(""))\n             {\n                    string CycleStartDate = Convert.ToString(Cyc.StartDate);\n                    string CycleEndDate = Convert.ToString(Cyc.EndDate);\n\n             }\n\n\n\n        }	0
28355379	28355314	Linq query to compare 2 List<string> for distinct matches	List1.Zip(List2, (item1, item2) => item1 == item2 ? 1 : 0).Sum();	0
16386608	16386464	Prevent control's Size-property to be set?	public class FixedPanel : Panel\n{\n    public new Size Size { get; private set; }\n}	0
24338727	24338693	Fetch data from MySql to C# application	MySqlDataReader rdr = selectData.ExecuteReader();\n\n// Check whether the result set is empty.\nwhile (!rdr.HasRows)\n{\n    rdr.Close();\n\n    // Pause before trying again if appropriate.\n\n    rdr = selectData.ExecuteReader();\n}\n\nwhile (rdr.Read())\n{\n    // Read data here.\n}	0
8027711	8027692	How can I create a variable from another variable but without spaces in C#	someString.Replace(" ", "")	0
4565852	4565661	How to deal with a class than encapsulates a disposible instance?	interface IMyInterace : IDisposable { }\n\nsealed class MyImplementation : IMyInterface \n{   \n   public void Open() { /* instantiates disposible class */ }\n\n   public void Close() { /* calls _myField.Dispose(); */ }\n\n   public void Dispose() { Close(); }  // only use this short form in a sealed class\n\n}	0
19108430	19108342	Substring when a string contains, Linq syntax	td.InnerText.Replace("&amp;", "&").Substring(0, td.InnerText.IndexOf("+") > -1 ? td.InnerText.IndexOf("+") : 0);	0
14980118	14978820	Move a rectangle on a canvas in WPF from code behind	private void Button1Click(object sender, RoutedEventArgs e)\n{\n  //Point relativePoint = buttonAnimation.TransformToAncestor(this).Transform(new Point(0, 0));\n  Point relativePoint = buttonAnimation.TransformToVisual(CanvasAnimation).Transform(new Point(0, 0));\n\n  var moveAnimX = new DoubleAnimation(Canvas.GetLeft(rectAnimation), relativePoint.X, new Duration(TimeSpan.FromSeconds(10)));\n  var moveAnimY = new DoubleAnimation(Canvas.GetTop(rectAnimation), relativePoint.Y, new Duration(TimeSpan.FromSeconds(10)));\n\n  rectAnimation.BeginAnimation(Canvas.LeftProperty, moveAnimX);\n  rectAnimation.BeginAnimation(Canvas.TopProperty, moveAnimY);\n}	0
395302	395275	Trying to design an object model - using enums	interface IPet { }\n\nclass Cat : IPet\n{\n    public void eat(CommonFood food) { }\n    public void eat(CatFood food) { }\n}\n\nclass Dog : IPet\n{\n    public void eat(CommonFood food) { }\n    public void eat(DogFood food) { }\n}\n\ninterface IFood { }\n\nabstract class CommonFood : IFood { }\n\nabstract class CatFood : IFood { }\n\nabstract class DogFood : IFood { }\n\nclass Milk : CommonFood { }\n\nclass Fish : CatFood { }\n\nclass Meat : DogFood { }\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n    Dog myDog = new Dog();\n    myDog.eat(new Milk()); // ok, milk is common\n    myDog.eat(new Fish()); // error\n    }\n}	0
24538945	24538796	Create global keypress from C# application	var wshType = Type.GetTypeFromProgID("wscript.shell");\nvar wsh = Activator.CreateInstance(wshType);\n\nvar whatEver = \n    wsh.GetType().InvokeMember(\n        "sendKeys", \n        System.Reflection.BindingFlags.InvokeMethod, \n        null, \n        wsh, \n        new string[] { "^C" });	0
16121958	16121813	Regex for handling values with surrounding characters?	var pattern = @"\|\|(.+?)\|\|";\nvar replacement = @"<a href=""#"">$1</a>";\nvar input = "you can get ||more info|| here";\n\nvar result = Regex.Replace(input, pattern, replacement);\nConsole.WriteLine (result);	0
24554944	24554832	C# Create byte array in code from copied SQL value?	MyObject.filebytes = File.ReadAllBytes("default.bin");	0
8798510	8798471	DDay iCalendar DTEND in UTC	string sValue = DateTime.Now.ToUniversalTime().ToString(@"yyyyMMdd\THHmmss\Z");	0
11185719	11184074	Prevent debugger from stopping on an Exception in a Compiled LambdaExpression	Debug > Exceptions	0
19589479	19589351	How to store Id (primary key) of newly inserted row into a variable using C#	int NewNameId = (int)sqlCommand.ExecuteScalar();	0
29679893	29679769	Getting the last child in a self-referencing hierachical tree	var LeafNodes = YourItemsList.Where(x => !YourItemsList.Any(y => y.ParentID == x.Id));	0
16918051	16917810	Cross-thread InvalidOperationException while trying to access SerialPort dynamically	sp.DataReceived += delegate \n     {\n         if (tb.InvokeRequired)\n         {\n            tb.Invoke(new Action(() =>\n            {\n                tb.Text += sp.ReadExisting(); \n            }));\n         }\n         else\n         {\n            tb.Text += sp.ReadExisting(); \n         }\n     }	0
31398402	31398184	Unable to get Dictionary key , value in string in C#	foreach (var numberObj in req.numbers)\n        {\n            var key = numberObj.Key;\n            var value = numberObj.Value;\n\n            var status = value.status;\n            var date = value.date;\n            var descr = value.desc;\n        }	0
6553551	6553447	Is there any way to prevent a dependency between two assemblies from being "seen" from a third assembly unless it is completely necessary?	IHeader<T>	0
23921076	23838482	Bootstrap modal dialog requires two clicks to get focus in textbox	tabindex="-1"	0
17925513	17924789	C# Progress Bar in background worker + Socket - Progress bar only updates after socket comm is done	WebSwitchHandler.GetDeviceStats(NewRoom);	0
33410359	33410230	Make Ms Word file part of dll	byte[] fileData = ProjectsNamespace.Properties.Resources.file;	0
8656298	8656208	Usage of Arraylist in DropDownList	var makes = new List<string> {\n    "Audi",\n    "BMW",\n    "Ford",\n    "Vauxhall",\n    "Volkswagen"\n};\nmakes.Sort(); \n\nDropDownList1.DataSource = makes;\nDropDownList1.DataBind();	0
8833407	8832026	How to disable and Enable ItemTemplate LinkButton based on GridView first and last row?	// Bind\ngv.DataSource = datasource;\ngv.DataBind();\n\n// Disable Up/Down LinkButtons\nif (gv.Rows.Count > 0)\n{\n    // With FindControl() if you know the IDs:\n    ((LinkButton)gv.Rows[0].Cells[0].FindControl("lb_up").Enabled = false; // Disable up LinkButton \n    ((LinkButton)gv.Rows[gv.Rows.Count - 1].Cells[0].FindControl("lb_down").Enabled = false; // Disable down LinkButton \n\n    // -- OR --\n\n    // Directly index the controls, assuming Up is at 0, and Down is at 1:\n    ((LinkButton)gv.Rows[0].Cells[0].Controls[0]).Enabled = false; // Disable up LinkButton \n    ((LinkButton)gv.Rows[gv.Rows.Count - 1].Cells[0].Controls[1]).Enabled = false; // Disable down LinkButton \n}	0
1027040	1026192	How to make a DateTimePicker increment/decrement on mouse wheel	private void dateTimePicker1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)\n{\n    if (e.Delta > 0) \n    {\n        System.Windows.Forms.SendKeys.Send("{UP}");\n    } \n    else \n    {\n        System.Windows.Forms.SendKeys.Send("{DOWN}");\n    }\n}	0
9956511	9956486	Distributed probability random number generator	Random.NextDouble()	0
395516	395430	Preventing a second instance from running except in a specific case	program start\n  try to acquire mutex (or semaphore)\n  if failed\n     send message via message queue to running program\n     exit\n  else\n\n  set up listener for message queue\n\n  run rest of program	0
17701909	17701198	SqlCommand INSERT INTO only for rows selected by checkBox issue	foreach (DataGridViewRow row in dtg_ksluzby.Rows)\n        {\n            if (Convert.ToBoolean(row.Cells[3].Value) == true) // check this line here\n            {\n                SqlCommand prikaz2 = new SqlCommand("INSERT INTO klisluz(text,pocet,akce,subkey) values(@val1,@val2,@val3,@val4) ", spojeni); \n                prikaz2.Parameters.AddWithValue("@val1", row.Cells["text"].Value);\n                prikaz2.Parameters.AddWithValue("@val2", row.Cells["pocet"].Value);\n                prikaz2.Parameters.AddWithValue("@val3", row.Cells["akce"].Value);\n                prikaz2.Parameters.AddWithValue("@val4", max + 1);                     \n                spojeni.Open();\n                prikaz2.ExecuteNonQuery();\n                spojeni.Close();\n            }\n        }	0
7447739	7447623	How to retain the value of a global variable List<object> after postbacks	private ArrayList GlobalList\n{ \n  get \n  { \n     return ViewState["GlobalList"]; \n  } \n  set \n  { \n    ViewState["GlobalList"] = value; \n  } \n}	0
24912568	24912473	Adding to Values of a Dictionary	// This is the list to which you would ultimately add your value\nList<MyClass> theList;\n// Check if the list is already there\nif (!myDict.TryGetValue(key, out theList)) {\n    // No, the list is not there. Create a new list...\n    theList = new List<MyCLass>();\n    // ...and add it to the dictionary\n    myDict.Add(key, theList);\n}\n// theList is not null regardless of the path we take.\n// Add the value to the list.\ntheList.Add(newValue);	0
29454201	29454167	Merging lists of IEnumerable type using a common attribute's value	var resultList = FabricCost.Concat(AccessoryCost)  // append together\n                           .Concat(FOBRevenue)     // append together\n                           .Concat(StockCost)      // append together\n                           .Concat(StockRevenue)   // append together\n                           .Concat(FixedCost)      // append together \n                           .GroupBy(x => x.Year)   // group by year\n                           .Select(g => new SalesSummaryDAO ()\n                            {\n                              Year = g.Key,\n                              Cost = g.Sum(x => x.Cost)\n                            }) // project to SalesSummaryDAO \n                           .ToList(); // make it a real list!	0
18317380	18302092	Building URI with the http client API	[Fact]\n    public void SOQuestion18302092()\n    {\n        var link = new Link();\n        link.Target = new Uri("http://www.myBase.com/get{?a,b}");\n\n        link.SetParameter("a","1");\n        link.SetParameter("b", "c");\n\n        var request = link.CreateRequest();\n        Assert.Equal("http://www.myBase.com/get?a=1&b=c", request.RequestUri.OriginalString);\n\n\n    }	0
23414239	23414181	How to get the name of a Windows message inside WndProc method?	Dictionary<int,string>	0
25030243	25024531	Entity Framework Relationship Matching - No Foreign Keys In DB	There aren't any foreign keys, and the parent table doesn't reference the children tables and the children tables don't reference the parent table.	0
21888918	21886869	WPF call a method that takes parameters from another dll	var method = paymentObjectInstance.GetType().GetMethod("MethodNameHere",\n                  BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);\n\n if (method == null)\n {\n    return null;\n }\n\n var result = method.Invoke(paymentObjectInstance, null);	0
3781344	3781245	How to allow user to move a control on the form	public void Form1_MouseDown(object sender, MouseEventArgs e)\n{\n    if(e.Button != MouseButton.Left)\n        return;\n\n    // Might want to pad these values a bit if the line is only 1px,\n    // might be hard for the user to hit directly\n    if(e.Y == myControl.Top)\n    {\n        if(e.X >= myControl.Left && e.X <= myControl.Left + myControl.Width)\n        {\n            _capturingMoves = true;\n            return;\n        }\n    }\n\n    _capturingMoves = false;\n}\n\npublic void Form1_MouseMove(object sender, MouseEventArgs e) \n{\n    if(!_capturingMoves)\n        return;\n\n    // Calculate the delta's and move the line here\n}\n\npublic void Form1_MouseUp(object sender, MouseEventArgs e) \n{\n    if(_capturingMoves)\n    {\n        _capturingMoves = false;\n        // Do any final placement\n    }\n}	0
19552514	19552448	How to synchronize parallel actions in .NET?	void Method()\n{\n    var intermediates = new Intermediate[100];\n    Parallel.For(0, 100, i =>\n    {\n        // ...\n        intermediates[i] = ...;\n    });\n\n    Parallel.For(0, 100, i =>\n    {\n        var intermediate = intermediates[i];\n        // ... use intermediate\n    });\n}	0
20453626	20453479	C# .NET Window won't show in front after double clicking on listview row	private void editContact()\n{\n   using(Window1 win = new Window1("edit"))\n   {\n      DatabaseHandler handler = new DatabaseHandler();\n      List<Contact> listie = handler.GetContactList();\n      var selected = listview_contacts.SelectedItem as Contact;\n      win.textbox_id.Text = selected.cId.ToString();\n      win.textbox_name.Text = selected.Name.ToString();\n      win.textbox_address.Text = selected.Address.ToString();\n      win.textbox_email.Text = selected.Email.ToString();\n      win.textbox_name.Focus();\n      win.textbox_name.SelectionStart = win.textbox_name.Text.Length;\n      win.ShowDialog();\n      // do something with whatever win1 did.\n      // if its say OK Cancrl form\n      // if (win.ShowDialog() == DialogResult.OK) { // do something }\n   }\n}	0
8419532	8419425	Is there a good way to find the bottleneck in your app?	// load XML Method\nvar stopWatch = new Stopwatch();\nstopWatch.Start();\n// run XML parsing code\nstopWatch.Stop();\n\nvar xmlTime = stopWatch.Elapsed;\n\n\n// SQL Server dump Method\nvar stopWatch = new Stopwatch();\nstopWatch.Start();\n// dump to SQL Server\nstopWatch.Stop();\n\nvar sqlTime = stopWatch.Elapsed;	0
19330354	19318577	how to wait till a button is getting clicked in selenium webdriver c#?	new WebDriverWait(driver,60).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_the_new_element")));	0
14044742	14044643	time regex for 12hr am and pm	Regex.IsMatch(input, @"^(0[1-9]|1[0-2]):[0-5][0-9] [ap]m$", RegexOptions.IgnoreCase);	0
27387412	27374307	How to remove a string from a flowdocument paragraph without disturbing the MarkUp?	// Read paragraph upto and including first ":"\n        string text =  (paragraph.Inlines.FirstInline as Run).Text;\n        int r = text.IndexOf(":")+1;\n        string Title = text.Substring(0,r).Trim();\n\n        // Remove Title from text;\n        string newtext = text.Substring(r).Trim();\n\n        // Insert new inline and remove the old inline.\n        Inline z = paragraph.Inlines.FirstInline;\n        Run runx = new Run(newtext);\n        paragraph.Inlines.InsertBefore(z, runx);\n        paragraph.Inlines.Remove(z);\n\n        this.Note = paragraph;	0
33703079	33675360	Making a combination of non-primitive properties unique in Entity Framework	public class Person\n{\n    public int Id { get; set; }\n\n    [Required]\n    [Index("IX_Person_PersonCategory", 1, IsUnique = true)]\n    [MaxLength(100)]\n    public string ExternalId { get; set; }\n\n    [Index("IX_Person_PersonCategory", 2, IsUnique = true)]\n    public int CategoryId { get; set; }\n\n    public PersonCategory Category { get; set; }\n\n    ...\n}	0
28015138	28015043	Looping through list of entities in a ViewModel	return View(model);	0
1226559	1226529	How to create WinForms components based on the type of an object	UserControl CreateControl(IVehicle vehicle) \n{\n    if (vehicle is Car)\n    {\n        return new CarControl();\n    }\n    else if (vehicle is Boat)\n    {\n        return new BoatControl();\n    }\n    ...\n}	0
25400507	25400459	Multithreaded Windows Service	Thread t = new Thread(() => {  \n   // Do some work  \n});	0
27624144	27623967	how to calculate speed using samples in c#	StopWatch watch;\nTimer tmr;\n\nList<double> samples;\n\nvoid initSampling()\n{\n\n    samples = new List<double>();\n    watch = new Stopwatch();\n    tmr = new Timer();\n    tmr.Tick += tmr_Tick;\n    tmr.Interval = 1000;\n    tmr.Start();\n    watch.Start();\n}\n\nvoid tmr_Tick(object sender, EventArgs e)\n{\n\n    double items = ...;//store the number of items created\n    watch.Stop();\n\n    double itemsPerSec = items / watch.ElapsedMilliseconds;\n\n    double timePerItem = 1.0 / itemsPerSec;\n\n    samples.Add(timePerItem);\n\n    watch.Restart();\n}	0
7682485	7682408	How to remove decorators out of order in C#	public interface IAccessoryHandler\n{ \n  bool CanHandle( UserOption option );  // UserOption is an enum of Electric Window etc.\n\n  Handle( Car car ); \n}	0
11836901	11836826	Pass value from grid view to new page ASP.NET C#?	int customerID = (int) Session["customerID"];\n      // or\nint customerID = Convert.ToInt32( Session["customerID"].ToString());\n     // or\nint customerID = int.Parse( Session["customerID"].ToString());	0
32666740	32666646	For loop removes only one row of DataGridView per run	int result = 0;\n        if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out result))\n        {\n            for (int i = dataGridView1.RowCount - 1; i >= 0; i--)\n            {\n                int parse;\n                if (int.TryParse(txtLessThanFollowersCount.Text.Trim(), out parse))\n                {\n                    if (Int32.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString()) < parse)\n                    {\n                        dataGridView1.Invoke(new Action(() => dataGridView1.Rows.RemoveAt(i)));\n                    }\n                }\n            }\n        }\n        else\n        {\n            MessageBox.Show("Error in the follower count selection", "Error");\n        }	0
10256374	10256351	Sum a list of BigIntegers	var bigInts = new List<System.Numerics.BigInteger>(); \nbigInts.Add(new System.Numerics.BigInteger(1));\n\nvar result = bigInts.Aggregate((currentSum, item)=> currentSum + item));	0
4785405	4785391	Count number of files in a Zip File with c#	int count;\nusing (ZipFile zip = ZipFile.Read(path))\n    count = zip.Count;	0
26887510	26887421	Copy Bytes from a byte array to a specific position of another Byte array in C#	// Init array2 to 0xff\nfor (int i = 0; i < array2.Length; i++)\n    array2[i] = 0xff;\n\n// Copy\nArray.Copy(array1, 0, array2, 3, array2.Length);	0
251929	251924	string.split returns a string[] I want a List<string> is there a one liner to convert an array to a list?	string s = ...\nnew List<string>(s.Split(....));	0
17157666	17156118	How to set color or background with "excelpackage"	using (var range = worksheet.Cells[1, 1, 1, 5]) \n    {\n        range.Style.Fill.PatternType = ExcelFillStyle.Solid;\n        range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);\n    }	0
19781747	19768930	Telerik window automatically opens after every page refresh	protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)\n  {\n            if (e.Item.Text == "About")\n            {\nstring script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"; \n    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);  \n\n            }\n  }	0
6183487	6183379	check alphanumeric characters in string in c#	public static Boolean isAlphaNumeric(string strToCheck)\n{\n    Regex rg = new Regex(@"^[a-zA-Z0-9\s,]*$");\n    return rg.IsMatch(strToCheck);\n}	0
19682606	19682526	Retrieving selected row in dataGridView as an object	AdressBokPerson currentObject = (AdressBokPerson)dataGridView1.CurrentRow.DataBoundItem;	0
18125300	18124826	Changing values in XML file	XmlDocument doc = new XmlDocument();\ndoc.Load(path);\n\nvar nm = new XmlNamespaceManager(doc.NameTable);\nnm.AddNamespace("jb", "urn:jboss:domain:1.2");\n\nforeach (XmlNode selectNode in doc.SelectNodes("jb:server/jb:system-properties/jb:property", nm))\n{\n    if (selectNode.Attributes["name"].Value == "teststudio.pwd")  // tsuser1\n    {\n        selectNode.Attributes["value"].Value = "new password";  // changes password value for "FTP_USER".\n    }\n\n    if (selectNode.Attributes["name"].Value == "watson.git_pwd")   //github\n    {\n        selectNode.Attributes["value"].Value = "new passwordx";  // changes password value for "FTP_READ_USER".\n    }\n\n    if (selectNode.Attributes["name"].Value == "FTP_READ_PASS")   // wtsntro\n    {\n        selectNode.Attributes["value"].Value = "new_passwordy";  // changes password value for "FTP_PASSWORD".\n    }\n}\n\ndoc.Save(path);  // Save changes.\nConsole.WriteLine("Password changed successfully");	0
13853509	13853475	Export to PDF from Gridview	Document pdfDoc = new Document(PageSize.A3, 7f, 7f, 7f, 0f);\nDocument pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);\nDocument pdfDoc = new Document(PageSize.A1, 7f, 7f, 7f, 0f);	0
33103059	33102385	Compare String dates from mysql database with entity framework c#	//It's important that this is done here and not inline with the Linq query\nvar nowInterval = timeStamp.ToString("yyyy-MM-dd HH:mm:ss");\n\nvar query = from r in db.route\n            where string.Compare(r.timestamp, nowInterval, StringComparison.Ordinal) > 0\n            select r;	0
8026825	8026712	Getting image size without locking the file in WPF	using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))\n{\n   BitmapFrame frame = BitmapFrame.Create(fileStream , BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);\n   Size s = new Size(frame.PixelWidth, frame.PixelHeight); \n}	0
1555455	1555397	Formatting Large Numbers with .NET	double number = 4316000;\n\nint mag = (int)(Math.Floor(Math.Log10(number))/3); // Truncates to 6, divides to 2\ndouble divisor = Math.Pow(10, mag*3);\n\ndouble shortNumber = number / divisor;\n\nstring suffix;\nswitch(mag)\n{\n    case 0:\n        suffix = string.Empty;\n        break;\n    case 1:\n        suffix = "k";\n        break;\n    case 2:\n        suffix = "m";\n        break;\n    case 3:\n        suffix = "b";\n        break;\n}\nstring result = shortNumber.ToString("N1") + suffix; // 4.3m	0
2451609	2451569	How to set focus to a brand new TextBox which was created as a result of a databinding in WPF?	this.Dispatcher.BeginInvoke(new Action( ()=>{\n    // MoveFocus takes a TraversalRequest as its argument.\n    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Previous);\n\n    // Gets the element with keyboard focus.\n    UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;\n\n    // Change keyboard focus.\n    if (elementWithFocus != null)\n    {\n        elementWithFocus.MoveFocus(request);\n    }\n\n\n}), DispatcherPriority.ApplicationIdle);	0
10084255	10072510	Regex match and replace in C#	trannsformContent = Regex.Replace(trannsformContent, @"\${1}(?<cont>.*?)\${1}\\prime\${1}(?<cont1>.*?)\${1}", @"$$${cont}\prime${cont1}$", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);	0
6799240	6799167	Add new row to table	...\nHtmlTableRow headers = new HtmlTableRow();\nheaders.Cells.Add(new HtmlTableCell("sat"));\n...\n\nbaseCalendar.Rows.Insert(1, headers);	0
13680347	13680032	build an array in C#	string[] a1 = new string[] { "a1", "b1", "c1", "d1" };\nstring[] a2 = new string[] { "a2", "b2", "c2", "d2" };\nstring[] a3 = new string[] { "a3", "b3", "c3", "d3" };\nList<String[]> campaigns = new List<String[]>();\nfor (int i = 0; i <4; i++)\n        {\n            campaigns.Add(new String[]{\n        a1[i],a2[i],a3[i]});\n        }	0
17262001	17260174	How to delete user created by websecurity	((SimpleMembershipProvider)Membership.Provider).DeleteAccount(userName); // deletes record from webpages_Membership table\n((SimpleMembershipProvider)Membership.Provider).DeleteUser(userName, true); // deletes record from UserProfile table	0
17190732	17186339	Reading html from online website C#	String content = "Your content goes here";\n\nvar regex = new Regex("<div(?:.*?)class=\"item\"[^>]*>(.*?)</div>");\nforeach (Match div in regex.Matches(content))\n{               \n    Console.WriteLine(div.Groups[0].Value);\n}	0
27698206	27697881	Printing Resolution	GraphicsUnit.Display	0
22672372	22671921	Remove or add items in DataGridComboboxColumn on row add or delete	public List<string> MyItemsSource\n{\n    get \n    {\n        var myNewList = MyMasterList.ToList(); //create a (reference) copy of the master list (the items are not copied though, they remain the same in both lists)\n        if (PropertyA != null)\n            myNewList.Remove(PropertyA);\n\n        return myNewList;\n    }\n}	0
19704868	19704571	UPDATE every record in SQL database from list	"UPDATE COMPLETED SET random_code = '"+ unRaCo +"'  "+"WHERE student_ID ="+ _studentidvariable_	0
19091826	19091672	select value from array at desired index using LINQ	public IEnumerable<fields> ConvertTList(List<string[]> rows)\n{\n    return rows.Select(x => StringsToField(x));\n}\n\nfields StringsToField(string[] source)\n{\n    return new fields\n    {\n        date = source[0],\n        user = source[1],\n        campaign = source[2],\n        adgroup = source[3],\n        changes = source[4],\n    };\n}	0
21105834	21103094	Resetting the context and accessing a query from a previous one	using(var context = new Context())\n{\n    context.Entry(new Entity { Id = 5} ).State = Deleted;\n    context.SaveChanges();\n}	0
5949635	5949607	Console output from web applications in Visual Studio	Debug.WriteLine	0
6007390	5949459	user control v/s custom control for image viewer	WPF Imaging Component\nWPF Image Formats\nDisplaying Images in WPF\nImage Metadata\nCodec Extensibility\nRelated Topics	0
17621945	17621872	How to get the value of isChecked property of a Checkbox in a data template	class Person //Model\n{\n    public string Name {get;set;}\n    public string ImgPath {get;set;}\n}\n\nclass PersonViewModel : INotifyPropertyChanged\n{\n    readonly Person _person;\n\n    public string Name {get {return _person.Name;}}\n    public string ImgPath {get {return _person.ImgPath; }}\n\n    public bool IsChecked {get;set;} //implement INPC here\n\n    public PersonViewModel(Person person)\n    {\n        _person = person;\n    }\n}\n\nclass ParentViewModel\n{\n    IList<PersonViewModel> _people;\n\n    public ParentViewModel(IList<PersonViewModel> people)\n    {\n         _people = people;\n         foreach (var person in people)\n         {\n             person.PropertyChanged += PropertyChanged;\n         }\n    }\n\n    void PropertyChanged(object sender, PropertyChangedEventArgs e)\n    {\n        //Recreate checked people list\n    }\n}	0
13197094	13187632	Enterprise Library 5 Validation Type Safe?	class Options\n{\n    [TypeConversionValidator(typeof(bool), MessageTemplate = "IsRed value must be a true/false")]\n    public dynamic IsRed { get; set; }\n    [TypeConversionValidator(typeof(bool), MessageTemplate = "IsBlue value must be a true/false")]\n    public dynamic IsBlue { get; set; }\n}\n\n    private ValidationResults LoadOptions()\n    {\n        _options.IsRed = ConfigurationManager.AppSettings["IsRed"];\n        _options.IsBlue = ConfigurationManager.AppSettings["IsBlue"];\n\n        var valFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>();\n        var cusValidator = valFactory.CreateValidator<Options>();\n        var optionValidator = cusValidator.Validate(_options);\n\n        if (optionValidator.IsValid)\n        {\n            _options.IsBlue = Convert.ToBoolean(_options.IsBlue);\n            _options.IsRed = Convert.ToBoolean(_options.IsRed);\n        }\n\n        return optionValidator;\n    }	0
17150118	17149894	MVC4 lambda expression for SimpleMembership	var result = db.UserProfiles.Join(db.webpages_UsersInRoles, u => u.UserId, ur => ur.UserId, (u, ur) => new {u, ur})\n            .Join(db.webpages_Roles, t => t.ur.RoleId, r => r.RoleId, (t, r) => new\n                {\n                    t.u.UserName,\n                    r.RoleName,\n                    t.u.UserId,\n                    r.RoleId\n                });	0
31510706	31510592	C# - Replacing multiple text	Dictionary<string, string> replaceWords = new Dictionary<string, string>();\nreplaceWords.Add("1", "number1");\n...\n\nStringBuilder sb = new StringBuilder(myString);\n\nforeach(string key in replaceWords.Keys)\n    sb.Replace(key, replaceWords[key]);	0
32870662	32870418	file filter in open file dialog	Filter = @"All Files|*.txt;*.docx;*.doc;*.pdf*.xls;*.xlsx;*.pptx;*.ppt|Text File (.txt)|*.txt|Word File (.docx ,.doc)|*.docx;*.doc|PDF (.pdf)|*.pdf|Spreadsheet (.xls ,.xlsx)|  *.xls ;*.xlsx|Presentation (.pptx ,.ppt)|*.pptx;*.ppt"	0
11961806	11961610	Code-first - get child entity by key	var entry = context.Set<LogEntry>().Find(entryId);	0
23705207	23705109	Exception of casting of delegates in a ternary expression	calcul = (moyenneAnnee < moyenneBac) ? (CalculerMoyenneGenerale)CalculerSansVightcinq : CalculerAvecVightcinq;	0
29822187	29821495	How to pass JSON string from ASP.Net to WebAPI Get Method?	using (HttpClient hc = new HttpClient())\n            {\n                var myModel = new Model()\n                {\n                prop1 = "prop1", prop2 = 1, prop3 = "prop3"\n                };\n                HttpResponseMessage response = await client.PostAsJsonAsync("api/Employee/", myModel);\n                if (response.IsSuccessStatusCode)\n                {\n\n                }\n            }	0
11394604	11393871	I want to select all and copy it to clipboard	webBrowser1.Document.ExecCommand("SelectAll", true, null);\nwebBrowser1.Document.ExecCommand("Copy", true, null);	0
32034096	32034048	Check a Label Value in Windows Forms	if(int.Parse(Lbl_Money.Text) >= 120)\n{\n}	0
17332936	17332457	How to find a name in a datagridview?	if (row.Cells["Name"].Value.ToString().ToUpperInvariant().Contains(textBox3.Text.ToUpperInvariant()))\n{\n// do something\n}	0
9981285	9981243	Assigning value to a dynamic int variable	int[] gateCount = new int[3];\nint gateIndex = someInt;\ngateCount[gateIndex]++;	0
19765849	19761334	wp7 Help Parse Xml	private readonly XNamespace dataNamspace = "urn:ietf:params:xml:ns:icalendar-2.0";\n\n    public void webClient_OpenReadCompleted(object sender,\n                                            OpenReadCompletedEventArgs e)\n    {\n        XDocument unmXdoc = XDocument.Load(e.Result, LoadOptions.None);\n\n        this.Items = from p in unmXdoc.Descendants(dataNamspace + "vevent").Elements(dataNamspace + "properties")\n                     select new ItemViewModel\n            {\n                LineOne = this.GetElementValue(p, "summary"),\n                LineTwo = this.GetElementValue(p, "description"),\n                LineThree = this.GetElementValue(p, "categories"),\n            };\n\n        lstData.ItemsSource = this.Items;\n    }\n\n    private string GetElementValue(XElement element, string fieldName)\n    {\n        var childElement = element.Element(dataNamspace + fieldName);\n\n        return childElement != null ? childElement.Value : String.Empty;\n    }	0
849360	849184	How to catch clicks in a Gtk.TreeView?	[GLib.ConnectBefore]\nvoid OnTreeViewButtonPressEvent(object sender, ButtonPressEventArgs e)\n{\n    if (e.Type == Gdk.EventType.TwoButtonPress)\n    {\n        // double click\n    }\n}	0
3332406	3332132	How can you retrieve all records of certain subtype dynamically with Linq to Entities?	var query = from o in _objects.AsQueryable()\n            where o.Project.Id == projectId\n            select o;\n\nvar ofType = typeof (Queryable).GetMethod("OfType").MakeGenericMethod(oType);\nvar list = (IQueryable)ofType.Invoke(\n            null, new object[] {query}).Cast<WritingObject>().ToList();	0
13220526	13219761	Convert email attachment to base64	open System\nopen System.IO\n\nlet stream = // Some stream, for example: new MemoryStream([| 1uy; 2uy; 3uy; 4uy |])\nlet buffer = Array.zeroCreate (int stream.Length)\nstream.Read(buffer, 0, buffer.Length)\nConvert.ToBase64String(buffer)	0
7433607	7432753	Sitecore webforms for marketers save item action	__Display name	0
16190494	16190405	On variable value change.	if (hipDepthPoint.X < 100)\n{\n    Xvariabel = 1;\n}\nelse \n{\n    Xvariabel = 2;\n}\n\n\npublic int Xvariabel \n{\n    get { return _xvariabel ; }\n    set\n    {\n        if (_xvariabel != value)\n        {\n            _xvariabel = value\n            //do some action\n        }\n    }\n}	0
33407043	33406592	How can I use comparing strings for my program to work properly	if(userChoice == 1 && computerChoice == 2)\n{\nMessageBox.Show("You win!")\n}\nelse if(userChoice == 2 && computerChoice == 3)\n{\nMessageBox.Show("You lose!")\n}\nelse if(userChoice == 3 && computerChoice == 1)\n{\nMessageBox.Show("You lose!")\n}	0
13579738	13578225	How to build a highly scaleable global counter in Azure?	Interlock.Increment	0
23277031	23276784	Dynamic Number of Enum Flags Using Binary OR For FontStyles	string fontName = "Arial";\nFontStyle style = FontStyle.Regular;\n\nif (myFont.Bold)\n    style |= FontStyle.Bold;\n\nif (myFont.Underline)\n    style |= FontStyle.Underline;\n\nif (myFont.Italic)\n    style |= FontStyle.Italic;\n\nFont font = new Font(fontName, style);	0
21906922	21891006	get and set attribute value for element in awesomium in C#	webctrl.ExecuteJavascript("$(#txtFileNo).attr('value', '12345');");\nwebctrl.ExecuteJavascript("$(#BTN).trigger('click');");	0
9498990	9498318	Custom Context Menu	contextMenuStrip1.Show(Cursor.Position);	0
27857735	27857692	Get value from specific ObservableCollection item	if(e.AddedItems != null && e.AddedItems.Length >=1)\n {\n  var myItems  = e.AddedItems[0] as LastList;\n }	0
24430801	24430696	Unable to retrieve value of templatefield textbox in a gridview	Dim temp As String = CType(grdGeneratedOrderForms.Rows(rowIndex).FindControl("txtRenewalDate"), System.Web.UI.WebControls.TextBox).Text	0
3907564	3906865	Implementing a generic interface	public interface IUnauthorizedRequestRespondable<T> where T:IUnauthorizedRequestRespondable<T>\n{\n    T GetResponseForUnauthorizedRequest();\n}	0
14989287	14988949	Deserialize fragment of JSON using JavaScriptSerializer ASP.NET	var dictObj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonData);\nvar jsonNew = new JavaScriptSerializer().Serialize(dictObj["forcast"]);	0
12640630	12640544	How do I convert RTF to plain text?	class ConvertFromRTF\n{\n    static void Main()\n    {\n\n        string path = @"test.rtf";\n\n        //Create the RichTextBox. (Requires a reference to System.Windows.Forms.dll.)\n        using(System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox());\n        {\n\n            // Get the contents of the RTF file. Note that when it is \n           // stored in the string, it is encoded as UTF-16. \n            string s = System.IO.File.ReadAllText(path);\n\n            // Convert the RTF to plain text.\n            rtBox.Rtf = s;\n            string plainText = rtBox.Text;\n\n            // Now just remove the new line constants\n            plainText = plainText.Replace("\r\n", ",");\n\n            // Output plain text to file, encoded as UTF-8.\n            System.IO.File.WriteAllText(@"output.txt", plainText);\n        }\n    }\n}	0
20068688	20068210	MSSQL Connection from IIS7	user id=test;password=test;server=server01;TrustServerCertificate=true;database=test;connection timeout=5	0
920175	920102	Databound DataGridView - IDataError	foreach(DataGridViewRow row in view.Rows)\n    {\n        IDataErrorInfo dei = row.DataBoundItem as IDataErrorInfo;\n        if (dei != null && !string.IsNullOrEmpty(dei.Error))\n        {\n            if(row.Cells.Count > 0) view.CurrentCell = row.Cells[0];\n            view.FirstDisplayedScrollingRowIndex = row.Index;\n            break;\n        }\n    }	0
13024639	13024594	How to verify if Parallel.Foreach is working correctly	System.Net.ServicePointManager.DefaultConnectionLimit = 1000;	0
5071148	5071076	DownloadStringAsync wait for request completion	var client = new WebClient();\nclient.DownloadStringCompleted += (sender, e) => \n{\n   doSomeThing(e.Result);\n};\n\nclient.DownloadStringAsync(uri);	0
15295469	15295255	Export joined tables to listView, anonymous type data	public class modelData\n{\n    public string CUSTOMERID { get; set; }\n    public string NAME { get; set; }\n    public string ADRESA { get; set; }\n    public string ORDERID { get; set; }\n    public string DATA { get; set; }\n    public string VALOARE { get; set; }\n    public string PRODUS { get; set; }\n    public string VALOARE2 { get; set; }\n    public string SERIAL { get; set; }\n};\n\nvar results = (\n    from a in db.CUSTOMERs\n    join b in db.ORDERs on a.CUSTOMERID equals b.CUSTOMERID\n    join c in db.ORDERDETAILS on b.ORDERID equals c.ORDERID\n    select new modelData\n    {\n       CUSTOMERID = a.CUSTOMERID,\n       NAME = a.NAME,\n       ADRESA = a.ADRESA,\n       ORDERID = b.ORDERID,\n       DATA = b.DATA,\n       VALOARE = b.VALOARE,\n       PRODUS = c.PRODUS,\n       VALOARE2 = c.VALOARE,\n       SERIAL = c.SERIAL\n    })\n    .ToList();	0
1494904	1494812	Why can't I retrieve an item from a HashSet without enumeration?	public enum SoonilsDataType {\n      A, B, C;\n\n      // Just an example of what's possible\n      public static SoonilsDataType getCompositeValue(SoonilsDataType item1,\n           SoonilsDataType item2) {\n           if (item1.equals(A) && \n                     item2.equals(B)) {\n                return C;\n           }\n      }\n }	0
17438369	17438021	Are all threads killed after a Parallel.ForEach loop terminates?	Parallel.ForEach()	0
12171181	12171051	ObjectDisposedException unhandled called from BackgroundWorker	appendMessage("Status: " + (int)e.UserState); <-- there is no (int)e.UserState	0
5313223	4149398	Unexpected RegexStringValidator failure in ConfigurationProperty in custom ConfigurationElement	[ConfigurationProperty("startTime", IsRequired = false, DefaultValue = "00:00:00")]\n[RegexStringValidator(@"\d{2}:\d{2}:\d{2}")]\npublic string StartTime\n{\n    get \n    {\n        return (string) this["startTime"];\n    }\n\n    set\n    {\n        this["startTime"] = value;\n    }\n}	0
4186492	4186101	Draw an image out of a control	protected override void OnParentChanged(EventArgs e)\n  {\n     base.OnParentChanged(e);\n     base.Parent.Paint += new PaintEventHandler(Parent_Paint);\n  }\n\n  private void Parent_Paint(object sender, PaintEventArgs e)\n  {\n    if (base.Enabled && string.IsNullOrEmpty(base.Text))\n    {\n       e.Graphics.DrawImage(requiredIcon, 0, 0);\n    }\n  }	0
26585535	26545614	windows phone 8.1 header bar icon colours	public MainPage()\n    {\n        StatusBar statusBar = StatusBar.GetForCurrentView();\n        statusBar.ForegroundColor = new Windows.UI.Color() { A = 0xFF, R = 0xFF, G = 0x00, B = 0xAA };\n        this.InitializeComponent();\n    }	0
20724975	20724903	Get only unique elements from a list	results = results.GroupBy(r => r.DeviceId)\n                 .Where(g => g.Key != 1 && g.Count() == 1)\n                 .Select(g => g.First())\n                 .ToList();	0
6870368	6861708	How to Serialize XML to a JSON object with Json.NET	var xml = new XmlDocument();\nxml.LoadXml("<person><name>John</name></person>");\nResponse.ContentType = "application/json";\nResponse.Write(Newtonsoft.Json.JsonConvert.SerializeObject(xml));	0
22607993	22607521	Open and pass values from DataGrid to Form by CheckBox	private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n        {\n\n\n            if (dataGridView1.CurrentCell.GetType()==typeof(DataGridViewCheckBoxCell)\n            && (bool)(dataGridView1.CurrentCell.Value)==true)\n          {\n                Form2 x =new Form2();\n                x.label1.Text = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value);\n                x.Show ();\n          }\n\n        }	0
25417931	25148980	How to limit instances of a C# program in Citrix to 1-per-user	string globalMutexName = string.Format(\n    CultureInfo.InvariantCulture,\n    "Global\\AppName~{0}~{1}~some-unique-guid",\n    Environment.UserDomainName,\n    Environment.UserName);\n\n_machineLocalAppInstanceMutex = new System.Threading.Mutex(true, globalMutexName, out mutexIsNew);\n\nif (!mutexIsNew)\n{\n    Shutdown();\n}	0
20819950	20819791	Compare image against an array of images	Bitmap img2 = new Bitmap(@"C:\ImageOne.png");\nImageConverter converter = new ImageConverter();\nbyte[] img2Bytes = (byte[])converter.ConvertTo(img2, typeof(byte[]));\n\nforeach (string s in Directory.GetFiles(@"C:\Images"))\n{\n    Bitmap img1 = new Bitmap(s);\n    byte[] img1Bytes = (byte[])converter.ConvertTo(img1, typeof(byte[]));\n    if (CompareImages(img1Bytes,img2Bytes))\n    {\n        Logging("Identical");\n    }\n    else\n    {\n        Logging("Not Identical");\n    }\n    img1.Dispose();\n}\n\npublic bool CompareImages(byte[] b1, byte[] b2)\n{\n   EqualityComparer<byte> comparer = EqualityComparer<byte>.Default;\n   if (b1.Length == b2.Length)\n   {\n       for (int i = 0; i < b1.Length; i++)\n       {\n           if (!comparer.Equals(b1[i], b2[i])) return false;\n       }\n    } else { return false; }\n\n     return true;\n}	0
14220262	14219893	C# Custom Validation - Change div border colour	this.divId.Style.Add(HtmlTextWriterStyle.BorderColor, System.Drawing.ColorTranslator.ToHtml(is_valid ? System.Drawing.Color.LightSlateGray : System.Drawing.Color.Crimson));	0
9841531	9841405	Change content of WPF Window	this.Content = new ctlFinanz(login);	0
25733683	25733656	Get enum char value	char charValue = (char)type;	0
2598755	2598708	Export data as Excel file from ASP.NET	'Send response with content type to display as MS Excel\ncontext.Response.Clear()\ncontext.Response.Buffer = True\n\ncontext.Response.AddHeader("content-disposition", String.Format( "attachment;filename={0}", fileName))\ncontext.Response.ContentEncoding = Encoding.UTF8\n\ncontext.Response.Cache.SetCacheability(HttpCacheability.Private)\ncontext.Response.ContentType = "application/vnd.ms-excel"\n\n'Write to response\ncontext.Response.Write("csv,data,goes,here")\n\ncontext.Response.End()	0
8067001	8066872	Is it possible to retrieve the username and password in one page to another page in asp.net?	lblUser.Text = "Welcome " + User.Identity.Name;	0
12433963	12433891	Block Website in https	private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n { \n    e.Cancel = e.Url.ToString().Contains("google"); \n }	0
2633424	2585852	Google Charts of SSL	private void GoogleChart(HttpContext cxt)\n    {            \n        const string csPrefix = "?act=chrt&req=chart&";\n\n        HttpRequest     req = cxt.Request;\n        HttpResponse    rsp = cxt.Response;\n        string          sUrl = cxt.Request.RawUrl;\n        int             nStart = sUrl.IndexOf(csPrefix,  StringComparison.OrdinalIgnoreCase);\n\n        rsp.Clear();\n\n        if (nStart > 0)\n        {\n            sUrl = "http://chart.apis.google.com/chart?" + sUrl.Substring(nStart + csPrefix.Length);\n\n            System.Net.WebClient    wc = new System.Net.WebClient();\n\n            byte[] buffer = wc.DownloadData(sUrl);\n\n            cxt.Response.ClearContent();\n            cxt.Response.ClearHeaders();\n            cxt.Response.ContentType = "application/octet-stream";\n            cxt.Response.AppendHeader("content-length", buffer.Length.ToString());              \n\n            cxt.Response.BinaryWrite(buffer);\n        }\n    }	0
21881087	21879653	Null and Space char decoding in ASCII 8-bit encoded file	byte[] data = File.ReadAllBytes(filePath);	0
29117838	29117321	Compare 2 List<int> and find 5 int numbers in a row C#	public static void Main()\n{\n    List<int> list1 = new List<int> { 2, 6, 1, 8, 9, 4, 12, 24, 23, 3, 11, 15 };        \n    List<int> list2 = new List<int> { 6, 9, 4, 12, 24, 23, 5, 16, 18, 2, 7, 14 };\n\n    CommonSublist(5, list1, list2).Dump();\n}\n\nprivate static List<int> CommonSublist(int length, List<int> list1, List<int> list2) {\n    for (int i=0;i<list1.Count-length;i++) {\n        for (int j=0;j<list2.Count-length;j++) {\n            List<int> output = new List<int>();\n            for (int k=0;k<length;k++) {\n                if (list1[i+k]==list2[j+k]) {\n                    output.Add(list1[i+k]);\n                }\n                else {\n                    break;\n                }\n            }\n            if (output.Count == length) {\n                return output;\n            }\n        }\n    }\n    return null;\n}	0
17578876	17578346	generating xml from object tree issue	XElement xml = new XElement("Root", \n      ps.GroupBy(x => x.ID).Select(\n        y => new XElement("Child", new XAttribute("ChildID", y.Key),\n                          y.Select(z => z.Childs.Select(\n                                   k => new XElement("ChildName", k.ChildName))))));	0
8930695	8917814	Modifying connection string of an ASP.NET GridView -> BLL -> DAL at runtime	public class PDFDocumentsBLL {\n  private PDFTableAdapter _pdfdocumentsadapter = null;\n  public string PDFDB = "PDF_TEMPLATE";\n  protected PDFTableAdapter Adapter {\n    get {\n      if ( _pdfdocumentsadapter == null ) {\n        _pdfdocumentsadapter = new PDFTableAdapter();\n\n        _pdfdocumentsadapter.Connection = new System.Data.SqlClient.SqlConnection(\n          ConfigurationManager.ConnectionStrings["pdf"].ConnectionString.Replace( "PDF_TEMPLATE", PDFDB )\n          );\n      }\n      return _pdfdocumentsadapter;\n    }\n  }\n}	0
11155433	10579242	Displaying a content page as popup in asp.net,using	function OpenWindow(strChildPageUrl) {\n          var testwindow = window.open(strChildPageUrl, "Child", "width=700px,height=650px,top=0,left=0,scrollbars=1");\n          testwindow.moveTo(100, 0);\n      }\n\n  </script>	0
513481	513443	WPF event when a window is no longer on top	public Window1()\n{\n    InitializeComponent();    \n    this.Deactivated += new EventHandler(Window1_Deactivated);\n}\n\nvoid Window1_Deactivated(object sender, EventArgs e)\n{\n    Visibility = Visibility.Collapsed;\n}	0
33785720	33783733	Event pass parameter	private EventHandler<AxisChangedEventArgs> axisChangedEventHandler;\n\npublic void AddEvent(CFDBOX CFDBOX) {\n    // keep a reference of the event handler to remove it later\n    axisChangedEventHandler = (o, args) => {\n        // parameter CFDBOX bound to the event handler\n        Console.WriteLine("Working " + CFDBOX); \n    };\n    // register event handler\n    CFDBOX.PlotModel.Axes[0].AxisChanged += axisChangedEventHandler;\n}\n\npublic void RemoveEvent() {\n    // unregister event handler\n    CFDBOX.PlotModel.Axes[0].AxisChanged -= axisChangedEventHandler;\n}	0
13636091	13336555	How to set root path for static files in ServiceStack self-host	Config.WebHostPhysicalPath	0
15774364	15774164	Format a label in a gridview to hide first 5 digits of a social security number	public static string GetMaskedNumber(string number)\n{\n    if (String.IsNullOrEmpty(number))\n        return string.Empty;\n\n    if (number.Length <= 5)\n        return number;\n\n    string last5 = number.Substring(number.Length - 5, 5);\n    var maskedChars = new StringBuilder();\n    for (int i = 0; i < number.Length - 5; i++)\n    {\n        maskedChars.Append(number[i] == '-' ? "-" : "#");\n    }\n    return maskedChars + last5;\n}	0
8382192	8381590	Custom Stylecop rule to ensure use of format specifier for the double convertions	using D = System.Double;	0
15213471	15213327	Cast static readonly property from id	int id = 1;\nType type = typeof(TaskType);\nBindingFlags privateInstance = BindingFlags.NonPublic | BindingFlags.Instance;\nvar name = type\n    .GetFields(BindingFlags.Public | BindingFlags.Static)\n    .Select(p => p.GetValue(null))\n    .Cast<TaskType>()\n    .Where(t => (int)type.GetField("value", privateInstance).GetValue(t) == id)\n    .Select(t => (string)type.GetField("name", privateInstance).GetValue(t))\n    .FirstOrDefault();\n\n// Output: Bug	0
6608875	6608817	 How to retrieve the value of a number of properties?	thing.GetType().Properties(propname).GetValue(thing,null);	0
29790235	29649986	Trying to read data in nodejs with mongodb which is persisted using C# with GUIDs	module.exports = function(uuid) {\n    var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters\n    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);\n    var b = hex.substr(10, 2) + hex.substr(8, 2);\n    var c = hex.substr(14, 2) + hex.substr(12, 2);\n    var d = hex.substr(16, 16);\n    hex = a + b + c + d;\n    var buffer= new Buffer(hex, "hex");\n    return new Binary(buffer, Binary.SUBTYPE_UUID_OLD);\n};	0
22070346	22069595	ThreadAbortException with await	try\n{\n    for (int j = 0; j < 10000000000; j++) ;\n}\ncatch (Exception e)\n{\n    Console.Write(2);\n    throw;\n}	0
7731377	7731304	How to merge two lists based on a property?	from f in fake\njoin r in real\non f.Year equals r.Year\ninto joinResult\nfrom r in joinResult.DefaultIfEmpty()\nselect new\n       {\n           ID = r == null ? f.ID : r.ID,\n           Year = f.Year,\n           X = r == null ? f.X : r.X\n       };	0
29732054	29731958	Can't seem to find how to take a value out of my table column and put it on a label C#	SqlCommand command6 = new SqlCommand("SELECT ([QuestionID]) FROM Questions", connect);\n\n    String s = "";\n\n    using (SqlDataReader reader = command6.ExecuteReader())\n    {\n        while (reader.Read())\n        {\n        for (int i = 0; i < reader.FieldCount; i++)\n        {\n            s += (reader.GetValue(i));\n        }\n        }\n    }\n\n    QuestionNum.Text = s;	0
6585504	6458158	GridView with too much text	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
19702898	19702743	Load XML into dropdownlist C#	XElement country= XElement.Load(Server.MapPath("myXML.xml"));\n\nforeach (XElement name in country.Elements("city").Elements("cityname"))\n{\n  dropdownList.Items.Add(name.Value);\n}	0
6182304	6148448	SharpSSH - setting connection "trust" to true	Hashtable config = new Hashtable();\nconfig.Add("StrictHostKeyChecking", "no");\nSFTPSession.setConfig(config);	0
18763009	18762175	Converting DateTime to String Entity Framework	var dataobjects = query\n.ToList()\n.Select(d => new DataBindingProjection { DeceasedName = (d.LastName + Environment.NewLine + d.FirstName),\n            DOBDOD = Convert.ToString(d.DateOfBirth)})\n.ToList();	0
24263733	24263451	Username and password input code validation	Console.ForegroundColor = ConsoleColor.Cyan;\n        Console.Write("\nEnter username: ");\n        Console.ForegroundColor = ConsoleColor.Yellow;\n        var username = Console.ReadLine();\n        if (username != null && username.Length > 0)\n        {\n            Console.ForegroundColor = ConsoleColor.Cyan;\n            Console.Write("Enter password: ");\n            Console.ForegroundColor = ConsoleColor.Yellow;\n            var password = getPassword();\n            Console.WriteLine("\n");\n        }\n        else\n        {\n            Main();\n        }	0
2788492	2788305	Searching in XML using Xpath	List<String> rangeNames = new List<String>();\n        XmlDocument document = new XmlDocument();\n        document.Load(strConfigFile);\n        XmlNodeList fieldInfoList = null;\n        fieldInfoList = document.GetElementsByTagName("FieldInfo");\n\n        foreach (XmlNode fieldInfo in fieldInfoList)\n        {\n\n            rangeNames.Add(fieldInfo["RangeName"].InnerText);\n\n        }	0
23637137	23636472	Exception thrown in System.Data.SQLite while trying to create a db in wpf	SQLiteConnection con = new SQLiteConnection("Data Source=ExamLog.sqlite;Version=3");\n\nstring sql = "CREATE TABLE EmpInfo (id int, firstName varchar(20), lastName varchar(20))";	0
20058301	20053358	Fluent NHibernate Composite Mapping <long, string>	CompositeId()\n    .KeyReference(x => x.Alert, "IDALERT")\n    .KeyProperty(x => x.Email, "EMAIL");	0
6121106	6119690	How to structure a partially dynamic LINQ statement?	public int GetMessageCountBy_Username(string username, bool sent)\n {\n     Func<Message, string> userSelector = m => sent ? m.Sender : m.Recipient;\n     var query =\n     _dataContext.Messages.AsQueryable()\n     .Where(x => userSelector(x).ToLower() == username.ToLower());\n     return query.Count();\n }	0
14584365	14574273	exiting console app by pressing enter twice without inputting data	while (true) {\n    Console.Write("Enter Morse Code: \n");\n    userInput = Console.ReadLine();\n    if (userInput = "") {\n        break;\n    }\n    // Process input here ....\n}	0
29334060	29333935	Creating a new directory in c#	string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\nvar myDir = Path.Combine(myDocs, "newFolder");\nDirectory.CreateDirectory(myDir);\nvar savedFile = Path.Combine(myDir, patWithoutExtension + "_" + date + ".xml");	0
9850315	9850179	how to copy custom properties when making clone	public override object Clone() \n{\n    var clonedColumn = base.Clone() as CustomColumn;\n    clonedColumn.CustomProp = this.CustomProp;\n    return clonedColumn;\n}	0
32461940	32461755	Exporting to excel programmatically from button click	ExcelExport.RunSample1(outputDir);	0
11913958	11913914	Combo Box Update in c#	updateCombo.Items.Clear();	0
27042292	27041870	DataGridView Row selection and variable saving wierd issue	string yourVariable = dataGridView1.CurrentRow.Cells[0].Value.ToString();	0
14653633	14640496	Inserting into ObjectDataSource with an object	if (IsValid)\n{\n  Incident i = new Incident();\n  i.CustomerID = Convert.ToInt32(ddlCustomer.SelectedValue);\n  i.ProductCode = ddlProduct.SelectedValue;\n  i.DateOpened = DateTime.Today;\n  i.Title = txtTitle.Text;\n  i.Description = txtDescription.Text;\n\n  try\n  {\n    IncidentDB.InsertIncident(i);\n  }\n  catch (Exception ex)\n  {\n  }\n}	0
29874419	29874275	No value given for required parameters, with value	var madeForCommand = "SELECT ItemName as Name,ItemPicture as Picture,ItemHeroModif as Assistance,ItemTroopModif as Charisma, HerbCost as Herbs, GemCost as Gems FROM Item WHERE ";\n\n        OleDbCommand command = new OleDbCommand();\n\n        for (int ii = 0; ii < items.Count; ii++)\n        {\n            madeForCommand += "ItemId = ?  OR ";\n            command.Parameters.AddWithValue("value" + ii, items[ii].ID);\n        }\n\n        madeForCommand = madeForCommand.Substring(0, madeForCommand.Length - 3);	0
18522851	18522463	Send Image using POST	byte[] imb = File.ReadAllBytes(ImageName + ".png")));	0
24343987	24343473	To parse JSON data from text file using c# winforms	static string ExtractJSON(string path)\n{\n    var file = File.ReadAllText(path);\n    var brackets = 0;\n    var json = "";\n\n    foreach (var c in file)\n    {\n        if (c == '{') // if { encountered, go in a level\n            brackets++;\n        else if (c == '}') // if } encountered go out a level\n        {\n            brackets--;\n            if (brackets == 0) \n                json += c.ToString(); // get the last bracket\n        }\n\n        if (brackets > 0) // ignore everything that isn't within the brackets\n            json += c.ToString();\n    }\n    return json;\n}	0
21221333	21221309	How to drop C# results from google when searching for C	c string concatenation -c#	0
32511434	32509007	using a referenced project's WCF service in another project c#	ChannelFactory<T>.CreateChannel()	0
13078048	12901090	SharePoint Service Application with multiple Service Endpoints	//context below is your SPServiceLoadBalancerContext\nvar endpointAddress = new EndpointAddress(new Uri(context.EndpointAddress.AbsoluteUri.Replace("dummy.svc", this.EndpointSvcFile)), new AddressHeader[0]);	0
33540171	33438312	Resolving InvalidOperationException from AppDomain	Evidence evidence = AppDomain.CurrentDomain.Evidence\nAppDomain appDomain = AppDomain.CreateDomain("MyDomain", evidence);	0
24573718	24573272	Deserialize JSON object	var data = JsonConvert.DeserializeObject<Boards>(json);	0
24829262	24828823	Best pattern to control the return of a method	var invoice = GetInvoiceFromMongoDb(id) \n       ?? GetInvoiceFromSql(id)\n       ?? GetOldSystemInvoice(id);\n\nreturn invoce.ToJson();	0
10836726	10836676	Regular Expression - Finding 4 digits in a string	\b\d{4}\b	0
11499272	11499190	how I write a windows service to manage other windows service?(can I?)	var Service = new ServiceController(servicetowach);\n                    if (Service.Status != ServiceControllerStatus.Running\n                        && Service.Status != ServiceControllerStatus.StartPending)\n                    {\nService.Start();\n}	0
20918752	20909927	CsQuery: how to iterate over all elements?	protected static CQ GetElementByIdPattern(CQ doc, string contains)\n    {\n        string select = string.Format("*[id*={0}]", contains);\n        return doc.Select(select).First();\n    }	0
9007209	9007152	Showing a spinner while a Windows Forms program is "processing", similar to ajaxStart/ajaxStop?	Cursor.Current = Cursors.WaitCursor;	0
9640126	9640098	DateTime Format Day of Year	new DateTime(2012, 1, 1).DayOfYear.ToString("000");\nnew DateTime(2012, 2, 1).DayOfYear.ToString("000");\nnew DateTime(2012, 12, 31).DayOfYear.ToString("000");\nnew DateTime(2011, 12, 31).DayOfYear.ToString("000");	0
6836689	6836519	C# - Addition on a string and replace with new string	double d = double.Parse(xDisplacementTextBox.Text);\nstring[] Lines = xRichTextBox.Text.Split('\n');\n\nfor(int i = 0; i < Lines.Length; ++i)\n{\n    Match lineMatch = Regex.Match(lines[i], @"^(?<p>.*)(?<x>-?\d+\.\d+)(?<y>\s+-?\d+\.\d+\s+-?\d+\.\d+)$");\n    if (lineMatch.Success)\n    {\n        double xValue = double.Parse(lineMatch.Groups["x"].Value) + d;\n        lines[i] = lineMatch.Groups["p"] + xValue + lineMatch.Groups["p"];\n    }\n }\n xRichTextBox.Text = string.Join(lines, '\n');	0
32522522	32522421	Adding element to a list in class, which is a part of List<class>, based on condition	if (!FinalList.Any() || index == -1)\n    ...\nelse\n{\n    FinalList[index].SampleList.Add(NewItem);\n}	0
33420050	33419964	group list by first four letters of a field and set the value	var result=list.GroupBy(o=>o.prodCode.Substring(0,4))\n  .Select(o=>new OrderStatus {prodCode=o.Key,Issue=o.Any(o2=>o2.Issue)});	0
19217845	19217343	How to insert Serial Number to Unpivoted Column	Create Table #Tempbatch2\n   (\n     pk_bid int,  \n     No_of_batches int,  \n     Batchname Varchar(max),  \n     [Batches] Varchar(max)  \n   )\n\n    Insert Into #Tempbatch2 \n    Select * from  \n    (  \n      Select pk_batchid,No_of_batches,Batch1,Batch2,Batch3,Batch4 from #tempbatch   \n    ) as p  \n   Unpivot(Batchname for [Batches] in([Batch1],[Batch2],[Batch3],[Batch4])) as UnPvt\n\n  Select Row_number() OVER(ORDER BY (Batchaname)) as     S_No,pk_bid,No_of_batches,Batchname,[Batches] from #Tempbatch2	0
23413477	23409970	How to show the console on a C# program with Windows application output type	class Program\n{\n    private const string Kernel32_DllName = "kernel32.dll";\n\n    [DllImport(Kernel32_DllName)]\n    private static extern bool AllocConsole();\n    static void Main(string[] args)\n    {\n\n        if (args[0] == "/")\n        {\n            AllocConsole();\n\n\n            Console.WriteLine("Details");\n            Console.ReadKey();\n            //cases and such for your menu options\n        }	0
969561	969555	Extracting first token from a delimeted string	YOUR_STRING.Split('_')[0]	0
7907045	7906932	MVC dealing with multiple LINQ Queries in a single View	public class MyModel\n{\n    public List<ListAEntity> ListA {get;set;}\n    public List<ListBEntity> ListB {get;set;}\n}\n\n\npublic class HomeController : Controller\n{\n    private readonly MyDataContext _context = new MyDataContext();\n\n    public ActionResult Index()\n    {\n        var model = new MyModel()\n        {\n            ListA = _context.Get<ListAEntity>().ToList(),\n            ListB = _context.Get<ListBEntity>().ToList()\n        };\n\n        return View(model);\n    }\n}	0
25061950	25048960	How do I set up an arraylist to it's child components in XML Deserializing?	[DataContract(Namespace = "")]\n    public class Plan\n    {\n        [DataMember(Order = 0)]\n        public string Id { get; set; }\n\n\n        [DataMember(Order = 1)]\n        public List<Zone> Zones { get; set; }\n\n        public Plan()\n        {\n            this.Id = string.Empty;\n            this.Zones = new List<Zone>();\n        }\n    }\n\n    [DataContract(Namespace = "")]\n    public class Zone\n    {\n        [DataMember(Order = 0)]\n        public string Id { get; set; }\n\n\n        public Zone()\n        {\n            this.Id = string.Empty;\n        }\n    }	0
1735018	1729531	regex to trap img tag, both versions	string html = @"\n<h1>\n<img src="" ... >\n</img>\n<img></img>-bad\n<img/>-bad\n<img src="" ... />\n</h1>";\n            string result = Regex.Replace(html, @"<img\s[^>]*>(?:\s*?</img>)?", "", RegexOptions.IgnoreCase);	0
673058	673020	What is a correct way to initiate user control from code behind	var comment = (IncidentHistoryGroupComment)Page.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx");	0
16237012	16236840	How to Access a Textbox Value from Page to UserControl	TextBox txt= (TextBox)this.Parent.FindControl("txtid");	0
30915876	30915817	Giving a string a null value	set { _stockCode = (value == null ? null : value.ToUpper()); }	0
27766861	27766600	How to call paint event from a button click event?	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        using (var g = Graphics.FromImage(pictureBox1.Image))\n        {\n            g.DrawEllipse(Pens.Blue, 10, 10, 100, 100);\n            pictureBox1.Refresh();\n        }\n    }\n}	0
15108627	15108539	How to remove duplicate code if I create array with different number of elements?	1- move the export and simple display functionality into 2 different methods.\n 2- Create a Client Object exactly once by using Singleton Pattern.	0
14084843	14084569	Cannot Use Generic version of EventHandler in Monotouch properly	public delegate void GEventHandler<T>(object sender, T args);	0
20883602	20883175	How to protect ASP.NET Web API 2	[Authorize]	0
19829804	19829777	copying one Array value to another array	RateInfos[] rt = hr.Select(item => item.RateInfo).ToArray();	0
7915437	7915405	How to read a text file from last line to first line in c#	List<string> lines = new List<string>();\n    using (var sr = File.OpenText("C:\\test.txt"))\n    {\n        string line;\n        while ((line = sr.ReadLine()) != null)\n        {\n            lines.Add(line); \n        }\n    }\n\n    lines.Reverse();	0
3666752	3666260	Xquery to get all nodes that has a particular attribue	//*[@href = 'ABC.jpg']	0
11619666	11619617	Multiple replace	var input = "a__b_c_____d__e_f__";\nvar output = Regex.Replace(input, "_+", "_");	0
7880371	7880331	Is it possible to instantiate objects with variable names, or access variable names at runtime?	// Or use arrays...\nList<Cat> cats = new List<Cat>();\ncats.Add(new Cat(...)); // Add the cats however you want to set them up\n// Ditto dogs, goats etc\n\nList<BackyardObject> backyardObjects = new List<BackyardObject>();\nfor (int i = 0; i < 10; i++)\n{\n    backyardObjects.Add(new BackyardObject(cats[i], dogs[i],\n                                           goats[i], piglets[i]));\n}	0
29013186	29013078	.NET C# Console Application How do I get more detailed exception information from a production environment	try\n{\n\n}\ncatch (exception ex)\n{\n     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@".\error.log",true))\n     {\n         sw.Write(String.Format("{0}/t {1}", DateTime.Now, ex.ToString()));\n         sw.Write(String.Format("{0}/t {1}", DateTime.Now, ex.StackTrace.ToString()));\n     }\n}	0
1301362	1301316	C# equivalent of rotating a list using python slice operation	var newlist = oldlist.Skip(1).Concat(oldlist.Take(1));	0
3164040	3164016	using LINQ in C# to convert a List<string> to a List<char>	var list = new List<string> { "Foo", "Bar" };\n\nvar chars = list.SelectMany(s => s.ToCharArray());\nvar distinct = chars.Distinct();	0
12395868	12395778	How to code a good Offline-Online Dispatcher	public class DispatcherProxy<TOnline, TOffline, TContract>\n    where TOnline : class, new()\n    where TOffline : class, new()\n    where TContract : class //isn't TContract an interface?\n{\n    public TContract Instance { get; set; }\n\n    public bool IsConnected { get; set; }\n\n    public DispatcherProxy()\n    {\n        // Asume that I check if it's connected or not\n        if (this.IsConnected)\n            this.Instance = new TOnline() as TContract;\n        else\n            this.Instance = new TOffline() as TContract;\n    }\n}	0
29910095	29909870	how to sort list of object? OrderBy c#	class Album : List<Track>\n{\n    public Album() : base() { }\n\n    public Album(IEnumerable<Track> tracks) : base(tracks) { }\n\n    /// <summary>\n    /// Sort in place the album of tracks alphabetically by name \n    /// </summary>\n    public void SortByAlphabet()\n    {\n        Sort((t1, t2) => t1.Name.CompareTo(t2.Name));\n    }\n\n    /// <summary>\n    /// Return a new Album with tracks sorted alphabetically by name.\n    /// </summary>\n    /// <returns></returns>\n    public Album OrderByAlphabet()\n    {\n        return new Album(this.OrderBy(t => t.Name));\n    }\n}	0
1041715	1037902	How to make source code a part of XML documentation and not violate DRY?	/// <summary>\n/// Says hello world in a very basic way:\n/// <code>\n///     Code block 1\n/// </code>\n/// </summary>\nstatic void Main() \n{\n    // Code block 1 start\n    System.Console.WriteLine("Hello World!");\n    System.Console.WriteLine("Press any key to exit.");\n    System.Console.ReadKey();\n    // Code block 1 end\n}	0
1642234	1642231	How to kill a C# process?	Process[] ps = Process.GetProcessesByName("nameOfProcess");\n\nforeach (Process p in ps)\n    p.Kill();	0
8525682	8525383	Regular expression match doesn't include space	(?<box_id>\d{1,19})","file_name":"(?<box_name>[^"]{1,19})  //1 to 19 non " chars.	0
7717714	7717624	Linq to SQL: Where clause comparing a Nullable<DateTime> with a SQL datetime null column	Object.Equals(row.StartDate, aDateTime)	0
13842037	13841920	Generic List data insert in C#	foreach (DataRow tmp in dtAllColumnData.Rows)\n{\n    WhereColumnValue val = new WhereColumnValue();\n    val._columnName = tmp["COLUMN_NAME"];\n    val._setValue = tmp{"SET_VALUE"];\n    ....\n    lstColumn.Add(val);\n}	0
13360547	13360309	Using Fiddler with Windows Store Unit Test	[TestMethod]\npublic async Task Example()\n{\n    var result = await GetSomeData(); //<-- breakpoint\n    Assert.IsNotNull(result);\n}\n\nprivate async string GetSomeData()\n{\n    //TODO something that makes a web request with, say, HttpClient\n}	0
649946	649900	Detecting the launch of a application	class WMIEvent {\n    public static void Main() {\n        WMIEvent we = new WMIEvent();\n        ManagementEventWatcher w= null;\n        WqlEventQuery q;\n        try {\n    q = new WqlEventQuery();\n    q.EventClassName = "Win32_ProcessStartTrace";\n    w = new ManagementEventWatcher(q);\n    w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArrived);\n    w.Start();\n    Console.ReadLine(); // block main thread for test purposes\n        }\n    finally {\nw.Stop();\n    }\n }\n\n    public void ProcessStartEventArrived(object sender, EventArrivedEventArgs e) {    \n    foreach(PropertyData pd in e.NewEvent.Properties) {\n    Console.WriteLine("\n============================= =========");\n    Console.WriteLine("{0},{1},{2}",pd.Name, pd.Type, pd.Value);\n    }\n  }	0
20565018	20564048	Windows 8 store app - swipe gesture to navigate	Point start;\n\nvoid ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e) {\n    start = e.Position;\n}\n\nvoid ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) {\n    if (e.IsInertial) {\n        if (start.X - e.Position.X > 500) //swipe left\n        {\n            e.Complete();\n        }\n    }\n}	0
3479244	3479190	Regex - Match any sequence of characters except a particular word in a URL	^http://([a-z0-9\-\.]+(?<!gateway))\.ovid\.com$	0
6942362	6942208	How to insert row at any desired position in datatable?	DataTable dt = new DataTable();\n    dt.Columns.Add("Name", typeof(string));\n\n    DataRow dr;\n    dr = dt.NewRow();\n    dr[0] = "A";\n    dt.Rows.Add(dr);\n\n    dr = dt.NewRow();\n    dr[0] = "C";\n    dt.Rows.Add(dr);\n\n    dr = dt.NewRow();\n    dr[0] = "B";\n    dt.Rows.InsertAt(dr,1);\n\n    foreach (DataRow d in dt.Rows)\n    {\n        Console.WriteLine(d[0].ToString());\n\n    }\n\n    Console.Read();	0
30934714	30919552	crystal report formula to filter between dates for bar chart	{tblFaultyDevice.date} >= {?dateFrom} and {tblFaultyDevice.date} <= {?dateTo}	0
24143903	24143701	How to get c# to run windows form functions alongside console app	static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new Form1());\n\n            //Some more things to do here\n        }\n    }	0
2451080	2449633	Convert System.DateTime to Javascript DateString	var d = new Date(2010, 2, 15);	0
29032673	26917221	ElasticSearch and NEST: How do you purge all documents from an index?	var node = new Uri("http://localhost:9200");\nvar settings = new ConnectionSettings(node);\nvar client = new ElasticClient(settings);\n\nclient.DeleteByQuery<ElasticsearchProject>(del => del\n            .Query(q => q.QueryString(qs=>qs.Query("*"))\n        ));	0
11685099	11685022	Get names from Dictionary's value as Comma separated value string	String names = String.Join(", ", fooDic.Select(x => x.Value._barName));	0
9535323	9533612	C# Populating treeview with pdf files	public TreeNode[] CreateChildNodes(){\n      return (from directory in Directory.GetDirectories(node.FullPath)\n             let directoryName = Path.GetDirectoryName(directory)\n             let pdfFiles = from file in Directory.GetFiles(directory,"*.pdf")\n                            select new TreeNode(Path.GetFileName(file))\n             select new TreeNode(directoryName,pdfFiles.ToArray()).ToArray();\n}	0
13393723	13393565	How to get index of a number in linked list	public static class LinkedListExt\n{\n    public static int IndexOf<T>(this LinkedList<T> list, T item)\n    {\n        var count = 0;\n        for (var node = list.First; node != null; node = node.Next, count++)\n        {\n            if (item.Equals(node.Value))\n                return count;\n        }\n        return -1;\n    }\n}	0
24383270	24383082	Get the resource in the MainWindow in WPF	var elementhand = Application.Current.MainWindow.Resources["OpenHand"] as FrameworkElement;	0
937153	937135	Is there a way to dynamically create and dispose of Webbrowser control?	this.Controls.Remove(webBrowser2);\nthis.Controls.Add(w);	0
26557935	26557608	How to wrap a WCF client in a shared library	ChannelFactoryClient.ServiceReference1.DocToPDF client = ChannelFactory<ChannelFactoryClient.ServiceReference1.DocToPDF>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.tcp://..."));	0
32960564	32957109	Offsetting a DateTime using Entity Framework Migrations	DateTime timeUtc = DateTime.UtcNow;\ntry\n{\n   TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");\n   DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);\n   Console.WriteLine("The date and time are {0} {1}.", \n                     cstTime, \n                     cstZone.IsDaylightSavingTime(cstTime) ?\n                             cstZone.DaylightName : cstZone.StandardName);\n}\ncatch (TimeZoneNotFoundException)\n{\n   Console.WriteLine("The registry does not define the Central Standard Time zone.");\n}                           \ncatch (InvalidTimeZoneException)\n{\n   Console.WriteLine("Registry data on the Central Standard Time zone has been corrupted.");\n}	0
22818226	22817920	how to run a method in csharp exactly ten times and then go to another method	private volatile int _loadImageCount = 0;\n\npublic void LoadImage_Click_1(object sender, RoutedEventArgs e)\n{\n    _loadImageCount += 1;\n\n    if (_loadImageCount > 10)\n    {\n        UpdateImage();\n    }\n    else\n    {\n        UpdateRandomImage();\n    }\n}\n\nprivate void UpdateRandomImage()\n{\n    Random rand = new Random();\n    int pic = rand.Next(1,0)\n    myImage.Source = new BitmapImage(new Uri("ms-appx:///img/" + pic +".jpg"));\n}\n\nprivate void UpdateImage()\n{\n    ...\n}	0
17722980	17522853	WPF application fail to load C++ dll	Assembly.LoadFile(path);	0
24616065	24611336	C# LINQ groupBy with multiple colunms from string array	dictShort = dsShort.Tables[0].AsEnumerable()\n// This where selects elements if and only if all fields are not null\n.Where(x => ListAnd(tokens.Select(t => x[t] != DBNull.Value && IsFilledIn(x[t].ToString())).ToArray()))\n.GroupBy(x => String.Join("+", tokens.Select(t => x[t].ToString()).ToArray()))\n//.GroupBy(x => x[block]) // TODO\n.Where(g => exp.GroupSizeOk((uint)g.Count()))\n.OrderBy(g => g.Count())\n.ToDictionary(g => g.Key/*.ToString()*/, g => g.ToList());	0
20604918	20601321	How to set default value to CustomControl inherited?	/*\n** In your custom control class\n*/\n\nusing Microsoft.Windows.Design.Features;\n// ...\n\n[Feature(typeof(CustomTextBoxDefaults))]\npublic class CustomTextBox : TextBox\n{\n    /* ... */\n}\n\n/*\n** CustomTextBoxDefaults provides default values for designer\n*/\n\nusing Microsoft.Windows.Design.Model;\n// ...\n\nclass CustomTextBoxDefaults : DefaultInitializer\n{\n    public override void InitializeDefaults(ModelItem item)\n    {\n        item.Properties["Width"].SetValue(120);\n        // Setup other properties\n    }\n}	0
19025555	18920174	Composing a Message in IClientMessageFormatter.SerializeRequest (HTTP GET)	public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)\n    {\n        string jsonText = SerializeJsonRequestParameters(parameters);\n\n        // Compose message\n        Message message = Message.CreateMessage(messageVersion, _clientOperation.Action);\n        _address.ApplyTo(message);\n\n        HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();\n        reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";\n        reqProp.Method = "GET";\n        message.Properties.Add(HttpRequestMessageProperty.Name, reqProp);\n\n\n        UriBuilder builder = new UriBuilder(message.Headers.To);\n        builder.Query = string.Format("jsonrpc={0}", HttpUtility.UrlEncode(jsonText));\n        message.Headers.To = builder.Uri;\n        message.Properties.Via = builder.Uri;\n\n        return message;\n    }	0
7036461	7036412	how can I use a color dialog to only apply color to the selected text in C#	richTextBox1.SelectionStart=startPosition;\nrichTextBox1.SelectionLength=length; \nrichTextBox1.SelectionColor=myColorDialog.Color;	0
22636576	22635826	Extra characters in XML file after XDocument Save	XDocument doc; // declare outside of the using scope\nusing (IsolatedStorageFileStream stream = isf.OpenFile("inventories.xml", \n           FileMode.Open, FileAccess.Read))\n{\n    doc = XDocument.Load(stream);\n}\n\n// change the document here\n\nusing (IsolatedStorageFileStream stream = isf.OpenFile("inventories.xml", \n       FileMode.Create,    // the most critical mode-flag\n       FileAccess.Write))\n{\n   doc.Save(stream);\n}	0
25848509	25771347	WebBrowser control won't navigate to URL when the call is via a timer	private void goHome()\n{\n        Dispatcher.InvokeAsync(() => { webBrowser.Navigate(URI_home); });\n}	0
12641352	12641351	Adding a sub item based on time	PlannedEvents.Last(pe => pe.StartTime <= BobArrivalTime)	0
10337391	10337331	I keep crashing with Inserting a record using OleDbConnection and OleDbCommand	cmd.Parameters.Add("@ProblemDate", OleDbType.Date).Value = DateTime.Parse(labelProblemDate.Text.Trim());\n\ncmd.Parameters.Add("@userIDNumber", OleDbType.Integer).Value = Convert.Int32(userID.ToString());	0
10386072	10385820	How to add only xmlns="http://url.com" to an xml file in C#?	var prefix = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<content>";\n\nvar xml = File.ReadAllText(pathToXmlFile);\n\nif (!xml.StartsWith(prefix))\n{\n    throw new Exception("Wrong format");\n}\n\nxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +\n      "<content xmlns=\"http://url.com/path_v1_0\">" +\n      xml.Substring(prefix.Length);\n\nFile.WriteAllText(pathToXmlFile, xml);	0
4242518	4242483	How to populate nodes of a TreeView? (C# winforms)	var tv = new TreeView();\nusing(var conn = new SqlCeConnection("Data Source=" + connString))\nusing(var cmd = new SqlCeCommand(conn,"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES"))\n{\n   conn.Open();\n   if(conn.State != ConnectionStatus.Open) return;\n   cmd.CommandType=CommandType.Text;\n   using(var rdr = cmd.ExecuteReader())\n   {\n      while(rdr.Read())\n      {\n         tv.Nodes.Add(new TreeNode(rdr.GetString(0));\n      }\n   }\n}	0
7459884	7417738	Store hashtable in a session	Hashtable ht = new Hashtable();\n         if(condition){\n\n        ht.Add("id", 1);\n        ht.Add("name", "ram");\n        Session["hashtab"] = ht;  \n        }\n\n        ht.Clear();	0
3586815	3580443	Adding a RadDatePicker to a custom RadGrid Form Template	DbSelectedDate='<%# Bind("Date") %>'	0
11975585	11975483	how render string to html link	string link = String.Format("<a href=\"http://localhost:1900/ResetPassword/?username={0}&reset={1}\">Click here</a>", user.UserName, HashResetParams( user.UserName, user.ProviderUserKey.ToString() ));	0
31771120	31771031	How to get the value of last column cell in grid view	int LastRow = gridinvoice.Rows.Count-1;\nstring Balance = gridinvoice.Rows[LastRow].Cells[5].Text;	0
34220337	34220323	send integer parameters to a process in C#	int X = 100;\nmyProcess.StartInfo.Arguments = X.ToString();	0
20674449	20668413	Reading an XML File With Linq	var xdoc = XDocument.Load("Guardian.re"); // load your file\nvar items = xdoc.Root.Elements().Select(e => (string)e).ToList();	0
7349445	7349068	Why won't my WPF application close properly after it displays a WinForms dialog?	System.Environment.Exit(0)	0
5809460	5809309	How to Create Generic Get Custom WebConfig Section Extension Method	public T GetSection<T>(string sectionName) where T : class\n{\n    Configuration config = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath + "/ExternalConfig");\n    return config.GetSection(sectionName) as T;\n}	0
31662936	31662679	c# how to read the certificate information from an untrusted server	request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { \n    // investigate certificate parameter\n    X509Certificate2 x509 = new X509Certificate2(certificate);\n    Console.WriteLine("Certificate expired on: {0}", x509.NotAfter);\n    return true; // true to bypass, false otherwise\n};\n...\nrequest.GetResponse();	0
17478526	17478215	How to convert Int To String in C# without using library functions?	void Main()\n{\n    Console.WriteLine(Convert(-5432));\n}\n\nString Convert(int i)\n{\n    return String.Join("",Digits(i).Reverse());\n}\n\nIEnumerable<char> Digits(int i)\n{\n    bool neg = false;\n    if(i==0) {yield return '0'; yield break;}\n    if(i<0) { i = -i; neg = true;}\n    while (i!=0)\n    {\n        char digit = (char)(i % 10 + '0');\n        i = i / 10;\n        yield return digit;\n    }\n    if(neg) yield return '-';\n\n    yield break;\n}	0
12324412	12323405	InvalidOperationException with BackgroundWorker in WPF	void worker_DoWork(object sender, DoWorkEventArgs e)\n    {\n        for (double x = 0; x < 10000000000; )\n        {\n            x++;\n        }\n    }\n\n\n    private void test_Click(object sender, RoutedEventArgs e)\n    {\n        test.Background = Brushes.Orange;\n\n        worker.RunWorkerCompleted += (_,__) =>  test.Background = Brushes.Red; \n        worker.RunWorkerAsync();\n\n    }	0
25621966	25619326	EF6 foreign key constraint in simple model	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<House>()\n        .HasRequired(c => c.item)\n        .WithMany()\n        .WillCascadeOnDelete(false);\n\n    modelBuilder.Entity<Room>()\n        .HasRequired(s => s.item)\n        .WithMany()\n        .WillCascadeOnDelete(false);\n}	0
27665989	27662580	How to change the icon of the form	Bitmap bmp = new Bitmap(email.Properties.Resources.run);  \nIntPtr Hicon = bmp.GetHicon();  \nIcon myIcon = Icon.FromHandle(Hicon);	0
30150630	30150459	Triangular random number generator	if (rand < f(a,b,c)) { x = a + Math.Sqrt(rand * (b-a) * (c-a)); } else { x = b - Math.Sqrt((1 - rand) * (b-a) * (b-c));}	0
4870260	4868972	Best Free Ordinary Differential Equation Library in .net	[DllImport()]	0
3909507	3900495	Acess controls on ContentPages via Javascript by MasterPage	var HiddenButtonID = '<%= MainContent.FindControl("btnLoadGridview")!=null?    \nMainContent.FindControl("btnLoadGridview").ClientID:"" %>';\nif (HiddenButtonID != "") {\n    var HiddenButton = document.getElementById(HiddenButtonID);\n    HiddenButton.click();\n}	0
6196516	6196413	How to recursively print the values of an object's properties using reflection	public void PrintProperties(object obj)\n{\n    PrintProperties(obj, 0);\n}\npublic void PrintProperties(object obj, int indent)\n{\n    if (obj == null) return;\n    string indentString = new string(' ', indent);\n    Type objType = obj.GetType();\n    PropertyInfo[] properties = objType.GetProperties();\n    foreach (PropertyInfo property in properties)\n    {\n        object propValue = property.GetValue(obj, null);\n        if (property.PropertyType.Assembly == objType.Assembly && !property.PropertyType.IsEnum)\n        {\n            Console.WriteLine("{0}{1}:", indentString, property.Name);\n            PrintProperties(propValue, indent + 2);\n        }\n        else\n        {\n            Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);\n        }\n    }\n}	0
1588672	1534718	Get object that user control is bound to when within items control?	MyDataBoundEntity mdbe = this.DataContext as MyDataBoundEntity;	0
21407284	21406939	Enabling desktop experience from C# on windows 2008 / 2012	Add-WindowsFeature Desktop-Experience	0
22797376	22794656	How can i incrementally build my application	...    \n    <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n           Other similar extension points exist, see Microsoft.Common.targets.-->    \n    <Target Name="BeforeBuild" Inputs="@(Compile)" Outputs="$(OutputPath)$(AssemblyName).dll">\n      <CreateProperty Value="true">\n        <Output TaskParameter="Value" PropertyName="NewFile" />\n      </CreateProperty>\n    </Target>\n    <Target Name="AfterBuild" Condition=" '$(NewFile)' == 'true' ">\n      <MakeDir Directories="$(IncrementalBuildRoot)$(BuildNumber)" Condition="!Exists('$(IncrementalBuildRoot)$(BuildNumber)')" />\n      <Copy SourceFiles="$(OutputPath)$(AssemblyName).dll" DestinationFolder="$(IncrementalBuildRoot)$(BuildNumber)" />\n    </Target>\n </Project>	0
25505947	25505497	How to get all supported ldap controls in .Net C#	LdapConnection lc = new LdapConnection("ldap.server.name");\n// Reading the Root DSE can always be done anonymously, but the AuthType\n// must be set to Anonymous when connecting to some directories:\nlc.AuthType = AuthType.Anonymous;\nusing (lc)\n{\n  // Issue a base level search request with a null search base:\n  SearchRequest sReq = new SearchRequest(\n    null,\n    "(objectClass=*)",\n    SearchScope.Base,\n    "supportedControl");\n  SearchResponse sRes = (SearchResponse)lc.SendRequest(sReq);\n  foreach (String supportedControlOID in\n    sRes.Entries[0].Attributes["supportedControl"].GetValues(typeof(String)))\n  {\n    Console.WriteLine(supportedControlOID);\n  }\n}	0
5511005	5510932	Outlook Add-in insertion at the end	mail.HTMLBody = mail.HTMLBody.Replace("</BODY>", sHtml);	0
2769152	2769087	How to make a ToolStripComboBox to fill all the space available on a ToolStrip?	private void toolStrip1_Resize(object sender, EventArgs e) {\n        toolStripComboBox1.Width = toolStripComboBox2.Bounds.Left - toolStripButton1.Bounds.Right - 4;\n    }\n    protected override void OnLoad(EventArgs e) {\n        toolStrip1_Resize(this, e);\n    }	0
34116839	34116791	Reading uploaded Excel file without saving it	if (Request != null)\n{\n   HttpPostedFileBase file = Request.Files[0];\n   if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))\n   {\n        string fileName = file.FileName;\n        string fileContentType = file.ContentType;\n        string fileExtension = System.IO.Path.GetExtension(Request.Files[0].FileName);\n\n        if (fileExtension == ".xls" || fileExtension == ".xlsx")\n        {\n            IExcelDataReader excelReader;\n            if (fileExtension == ".xls")\n                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);\n            else\n                excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);\n\n            excelReader.IsFirstRowAsColumnNames = true;\n            DataSet ds = excelReader.AsDataSet();\n\n            DataTable Dt = ds.Tables[0];	0
12330382	12330361	How to loop data from a table in sql server and using the returned data to query another table. Please see	var myMainTable = new DataTable();\n\nforeach(var itemId in itemIds)\n{\n  var currentTable = new DataTable();\n  // submit new query\n  myAdapter.Fill(currentTable)\n  myMainTable.Merge(currentTable);\n}	0
10725130	10725024	HTTP Post from ASP.NET to jsp	stream = webRequest.GetRequestStream();\nstream.Write(bytes, 0, bytes.Length);\nstream.Flush\nvar rsp = webRequest.GetResponse();\nusing(var sr = new StreamReader(rsp.GetResponseStream())\n    var result = sr.ReadToEnd(); // you might want to see what this is to debug	0
32790262	32789902	Getting value by key from Exception.Data c#	var yourObj = ex.Data["your_key"];	0
12165862	12165701	Converting array to string looping issue	var sEmailList = String.Join(",", \n      GetUserReportsToChain.Rows\n      .Cast<DataRow>()\n      .Select(m => m["usrEmailAddress"].ToString())\n      .Where(x => !string.IsNullOrWhiteSpace(x)));	0
4356230	4356185	String formatting: negative/positive floating point numbers	String.Format("{0,10:F3}", -123.321)	0
21077705	21077468	Cannot retrieve result of a stored procedure	using(SqlConnection conn = new  SqlConnection(connString))\nusing(SqlCommand command = new SqlCommand(ProcName, conn))\nusing(SqlDataAdapter da = new SqlDataAdapter(command))\n{\n  command.CommandType = CommandType.StoredProcedure;\n  da.Fill(dt);\n}	0
10268888	10239544	Select distinct set of values from related table in NHibernate	var result = _Session.CreateQuery("select distinct profile.UserName from Log as l inner join l.UserProfile as profile order by profile.UserName asc")\n    .List<string>();	0
6905952	6905849	A Custom ComboBox Style	Default WPF Themes	0
9598960	9598799	Rest sharp be sure that the asynchronous method is finished	EventWaitHandle Wait = new AutoResetEvent(false);\n\nclient.ExecuteAsync(request, response =>\n{\n    if (response.ResponseStatus == ResponseStatus.Completed)\n    {\n        RestResponse resource = response;\n        string content = resource.Content;\n        resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));\n        Wait.Set();\n    }\n});\n\nWait.WaitOne();	0
8122799	8122731	How to create OR statements from a list in Nhibernate Criteria	Expression.In("name", weaponAndTriggerList.ToArray());	0
7412689	7384134	Order a set of translations, according to a specific language	FROM Product AS product\nINNER JOIN FETCH product.Translations ordered_trans\nINNER JOIN FETCH product.Translations trans\nWHERE ordered_trans.language = 'en'\nORDER BY ordered_trans.Title ASC	0
16106585	16105718	DataGridView changing cell background color	private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (e.ColumnIndex != color.Index)\n        return;\n\n    e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));\n}	0
26721455	26549950	Load items asynchronously to a ListView after navigation to Page Windows Phone 8.1	DatabaseService.GetList();	0
21385201	21384696	how to have Web Api send Json.net Serialized string object back to client Correctly?	[HttpGet]\npublic HttpResponseMessage GetDegreeCodes(int id)\n{\n    StringContent sc = new StringContent("Your JSON content from Redis here");\n    sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");\n\n    HttpResponseMessage resp = new HttpResponseMessage();\n    resp.Content = sc;\n\n    return resp;\n}	0
28385017	28366236	How can Windows Runtime Component written in C++ be referenced from Class Library written in C#?	...\n    <ItemGroup>\n        <Reference Include="WindowsRuntimeComponent.winmd" />\n    </ItemGroup>\n...	0
29317868	29295374	How to work with fm radio?	// Create an instance of the FMRadio class.\nFMRadio myRadio = FMRadio.Instance;\n// Turn the radio on.\nmyRadio.PowerMode = RadioPowerMode.On;	0
1076260	1075623	NHibernate: Getting single column from an entity	ICriteria c = session.CreateCriteria(typeof(Tribble));\nc.SetProjection(Projections.ProjectionList().Add(Projections.Property("Name")));\nIList<string> names = c.List<string>();	0
20095995	20093929	How to check if column value is null before inserting data from text box	if (ds.table[0].rows.count==0)//insert\n        {\n\n        }\n        else// update\n        }	0
8208842	8208631	C# Xml deserialization with custom type member	[Serializable]\n[XmlRoot("Fields")]\npublic class FieldCollection\n{\n    [XmlAttribute("lang")]\n    public string Lanuage { get; set; }\n    [XmlElement("Item")]\n    public FieldTranslation[] Fields { get; set; }\n}\n\n[Serializable]\npublic class FieldTranslation\n{\n    [XmlAttribute("name")]\n    public string Name { get; set; }\n\n    public string Tooltip { get; set; }\n\n    public string Label { get; set; }\n\n    public string Error { get; set; }\n\n    public string Language { get; set; }\n}	0
11574259	11574189	Accessing Item property using C#	var myButton = myButtonsArray[0];	0
6456364	6456315	Build a string with spaces with either String builder or string class	string.Format("{0,-5}{1,-5}{2,-5}", val1, val2, val3);	0
7278165	7277967	how to position an object using variables	private void Form1_Load(object sender, EventArgs e)\n        {\n            int x = 0;\n            int y = 0;\n\n            for (int i = 0; i < 81; i++)\n            {\n                PictureBox p = new PictureBox();\n                p.BorderStyle = BorderStyle.Fixed3D;\n                p.Height = 80;\n                p.Width = 80;\n                p.Location = new Point(x, y);\n\n                x += 85;\n\n                if (x > 425)\n                {\n                    x = 0;\n                    y += 85;\n                }\n\n                this.Controls.Add(p);\n            }\n\n        }	0
9102561	9102367	Regex Replace - TextBox Text to ONLY Include Floating Values	using System;\nusing System.Collections.Generic;\nusing System.Text.RegularExpressions;\n\nnamespace ConsoleApplication4\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Regex rx = new Regex(@"^-{0,1}\d{0,3}(?:\.{0,1}(?<=\.)\d{0,3})?$");\n            List<string> testStrings = new List<string>()\n            {\n                "100",\n                "100.100",\n                "1000.0000",\n                "100000",\n                "-1",\n                "-1.234",\n                "--",\n                "100.100ab",\n                "1,234.1",\n                "1,234",\n                "abc",\n                "abc123.123",\n                "abc.def"\n            };\n            foreach(var str in testStrings)\n            {\n                Console.WriteLine(string.Format("{0} = {1}", str, rx.IsMatch(str)));\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
27134772	27134740	how to update an attribute of an object (which is fetched based on a condition) in a list using linq	offer = offers.FirstOrDefault(o => o.attribute.Equals("Match"));\noffer.Property1 = "NewValue";\n............................;	0
19398430	19398339	Get X random elements from table in database using Linq or lambda in C#	Random rnd = new Random();\nuserList = userList.OrderBy(user => rnd.Next()).Take(usercount).ToList();	0
27047847	27047803	Sort a list alphabetically excluding a letter	.OrderBy(o => o.Name.StartsWith("D") ? 1 : 0)\n.ThenBy(o => o.Name)	0
2577699	2565783	WPF FlowDocument - Absolute Character Position	// Get starting pointer\nTextPointer navigator = flowDocument.ContentStart;\n\n// While we are not at end of document\nwhile (navigator.CompareTo(flowDocument.ContentEnd) < 0)\n{\n    // Get text pointer context\n    TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);\n\n    // Get parent as run\n    Run run = navigator.Parent as Run;\n\n    // If start of text element within run\n    if (context == TextPointerContext.ElementStart && run != null)\n    {\n        // Get text of run\n        string runText = run.Text;\n\n        // ToDo: Parse run text\n    }\n\n    // Get next text pointer\n    navigator = navigator.GetNextContextPosition(LogicalDirection.Forward);\n}	0
10033917	10033114	Select a substring from a string in C#	string originalString = "Jungle #welcome to the Juncle";\nstring subString = originalString.Substring(originalString.IndexOf("#"));\nsubString = subString.Substring(0, subString.IndexOf(" "));	0
910471	910421	How can I save global application variables in WPF?	public static class ApplicationState \n{ \n    private static Dictionary<string, object> _values =\n               new Dictionary<string, object>();\n\n    public static void SetValue(string key, object value) \n    {\n        _values.Add(key, value);\n    }\n\n    public static T GetValue<T>(string key) \n    {\n        return (T)_values[key];\n    }\n}	0
863011	862930	Update or inserting a node in an XML doc	public void UpdateNodes(XmlDocument doc, string newVal)\n        {\n            XmlNodeList folderNodes = doc.SelectNodes("folder");\n\n            if (folderNodes.Count > 0)\n            foreach (XmlNode folderNode in folderNodes)\n            {\n                XmlNode updateNode = folderNode.SelectSingleNode("nodeToBeUpdated");\n                XmlNode mustExistNode = folderNode.SelectSingleNode("nodeMustExist"); ;\n                if (updateNode != null)\n                { \n                    updateNode.InnerText = newVal;\n                }\n                else if (mustExistNode != null)\n                {\n                    XmlNode node = folderNode.OwnerDocument.CreateNode(XmlNodeType.Element, "nodeToBeUpdated", null);\n                    node.InnerText = newVal;\n                    folderNode.AppendChild(node);\n                }\n\n            }\n        }	0
22943087	22941353	Line breaks being removed from email body	IsBodyHtml = true	0
15921400	15921233	Save remainder in variable	TimeSpan span = TimeSpan.FromSeconds(5400);	0
14506573	14506507	Generic read/write to byte array	public T Read<T>()\n{\n    var byteSize = Marshal.SizeOf(typeof(T));\n    using (var ms = new MemoryStream())\n    {\n        ms.Write(SerializedParams, 0, SerializedParams.Length);\n        var bf = new BinaryFormatter();\n        ms.Position = 0; // this line should do the trick\n        var x = bf.Deserialize(ms); \n        return (T)x;\n    }\n}	0
34378085	34371428	Efficient way to find list of common items based on condition	permisionLists.ForEach(permissions => permissions.Where(p => !p.HasPermission).ToList().ForEach(permission =>\n{\n    if (!permisionLists.Where(permissionList => permissionList.Where(p => p.Id == permission.Id).FirstOrDefault().HasPermission).Any())\n    {\n           if (disabledPermissions.All(p => p.Id != permission.Id))\n           disabledPermissions.Add(permission);\n    }\n}));	0
6890060	6889992	String List Sort based on Integer order	newZipCodesList.Sort(new Test());\n\n   public class Test : IComparer<string>\n    {\n        public int Compare(string x, string y)\n        {\n            //return 1 when first is greater than second\n            if(Convert.ToInt32(x) > Convert.ToInt32(y))\n                return 1;\n            //return -1 when first is less than second\n            else if (Convert.ToInt32(x) < Convert.ToInt32(y))\n                return -1;\n            //return 0 if they are equal\n            else\n                return 0;\n        }\n    }	0
5005764	5005726	string into arrays	string s = "dog cat horse mouse";\n        string[] stringArray = s.Split(' ');\n        Console.WriteLine(stringArray[1]);  // cat	0
11927189	11927176	Using a LINQ variable in another method?	private Dictionary<string, string> m_settings;  \n\npublic void ShowSettingsGui()\n{\n    var dialog = new OpenFileDialog()\n    {\n        Multiselect = true,\n        Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*"\n    };\n    if (dialog.ShowDialog() != DialogResult.OK) return;\n    var paths = dialog.FileNames;\n    m_settings = paths.ToDictionary(filePath => filePath, File.ReadAllText);\n}\n\nprotected override void SolveInstance(IGH_DataAccess DA)\n{\n    if (m_settings == null)\n    {\n        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You must declare some valid settings");\n        return;\n    }\n\n    DA.SetData(0, m_settings);\n}	0
5902174	5901086	Setting Listbox VirtualizationMode (Data)	public class MyCollection<T> : ListCollectionView\n{\n    public MyCollection(List<T> list)\n        : base(list)\n    {\n    }\n\n    public override object GetItemAt(int index)\n    {\n        Debug.WriteLine(index);\n        return base.GetItemAt(index);\n    }\n}	0
29511622	29511460	Add WPF Controls Dynamically using Code	var panel = new WrapPanel() { Height = 39 };\n            panel.Children.Add(new TextBox() { Width = 93, Margin = new Thickness(-1, 5, 0, 0) });\n            panel.Children.Add(new TextBox() { Width = 76, Margin = new Thickness(0, 5, 0, 0) });\n            panel.Children.Add(new TextBox() { Width = 70, Margin = new Thickness(0, 5, 0, 0) });\n            panel.Children.Add(new TextBox() { Width = 70, Margin = new Thickness(0, 5, 0, 0) });\n            panel.Children.Add(new TextBox() { Width = 127, Margin = new Thickness(0, 5, 0, 0) });\n            panel.Children.Add(new TextBox() { Width = 100, Margin = new Thickness(0, 5, 0, 0) });\n            this.Content = panel;	0
22542039	22541957	Insert Break Line After Specific Character in File	string text = File.ReadAllText(@"T:\data.txt");\nstring newText = string.Join("Z\", \r\n", \n            text.Split(new[] { "Z\"," }, StringSplitOptions.RemoveEmptyEntries));\n\nFile.WriteAllText("path", newText);	0
18401327	18314763	Set selectedValue in DataGridViewComboBoxColumn	comboBoxColumn.DataPropertyName = "Table_ID";	0
939069	938991	Creating a 'New File Windows' behavior	FileInfo finfo = new FileInfo(fullOutputPath);\nint iFile = 1;\nwhile (finfo.Exists)\n{\n    finfo = new FileInfo(\n        Path.GetFileNameWithoutExtension(fullOutputPath) +\n        "(" + iFile + ")" +\n        Path.GetExtension(fullOutputPath));\n    iFile++;\n}\n// Optionally add fullOutputPath = finfo.Name; if you want to record the final name used	0
25235607	25235603	How do I find out what button was clicked?	Button btnClicked = (Button)sender;	0
1122002	1121917	Local database, I need some examples	public void ConnectListAndSaveSQLCompactExample()\n    {\n        // Create a connection to the file datafile.sdf in the program folder\n        string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";\n        SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);\n\n        // Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)\n        SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);\n        DataSet data = new DataSet();\n        adapter.Fill(data);\n\n        // Add a row to the test_table (assume that table consists of a text column)\n        data.Tables[0].Rows.Add(new object[] { "New row added by code" });\n\n        // Save data back to the databasefile\n        adapter.Update(data);\n\n        // Close \n        connection.Close();\n    }	0
32270097	32269809	How can i make a button that pastes what's on my clipboard to any location?	private void button1_Click(object sender, EventArgs e)\n    {\n        Clipboard.SetText(textBox1.Text);\n        Deactivate += Form1_Deactivate; //next click will invoke the Form's Deactivate event\n    }\n\n    private void Form1_Deactivate(object sender, EventArgs e)\n    {\n        SendKeys.Send("^v");\n        Deactivate -= Form1_Deactivate;\n    }	0
13038690	13038510	Read SQL Table into Dictionary<string, List<string[]>>	var dict = new Dictionary<string, List<string[]>>();\n while (rdr.Read())\n {\n     // TODO: extract field1, field2, field3\n     if(dict.ContainsKey(field1))\n     {\n         // Add the values to the existing list\n         dict[field1].Add(new string [] {field2 , field3});\n     }\n     else\n     {\n         //Create a new list and set the initial value\n         dict[field1] = new List<string[]> { new string[] { field2 , field3 } };\n     }\n }	0
6116973	5877251	Lookup property in object graph via a string	object result = DataBinder.Eval(myPerson, "PersonsAddress.HousePhone.Number");	0
24381900	24380383	How to modify retrieve from dataset/database	if(RadTextBox2.Text!=""||RadTextBox3.Text!="")\n{\nRadTextBox2.Text="";\nRadTextBox3.Text="";\n}\nSqlConnection con = new SqlConnection("Your connection");\ncon.Open();\nSqlCommand cmd = new SqlCommand("Select * from Trial where FirstColumn = '"+RadTextBox1.Text+"'",con);\nSQlDataReader dr = cmd.ExecuteReader();\nwhile(dr.Read())\n{\n  if(dr.HasRows())\n  {\n\n     RadTextBox2.Text = dr.GetString(1);\n     RadTextBox3.Text = dr.GetString(2);  \n  }\n  else\n  {\n\n\n  }\n}\ncon.Close();	0
9404722	9404683	get a length of Row/column in c#	matrix.GetLength(0)  -> Gets the first dimension size\n\nmatrix.GetLength(1)  -> Gets the second dimension size	0
27145943	27145664	Applying a override to the validation in MVC code	if(civ2_annualLeave_al.AL_IsUnpaid == true){\n    return true;\n}	0
7099254	7099217	How to open a new window in Windows Forms in .NET?	MyEditForm form = new MyEditForm();\nform.Show();	0
4915355	4911920	C# Deferred Property Setting	interface Setter {\n    void Apply();\n}\nclass Setter<T> : Setter {\n    public T Data;\n    public Action<T> SetFn;\n    public void Apply() {\n        SetFn(Data);\n    }\n}\n\nList<Setter> changeQueue = new List<Setter>();\n\nvoid SetValue<T>(Action<T> setFn, T data){\n    changeQueue.Add(new Setter<T> {\n        Data = data,\n        SetFn = setFn,   \n    });\n}\n\nvoid ApplyChanges(){\n    foreach (var s in changeQueue){\n        s.Apply();\n    }\n}\n\n// .. later on\nSetValue(x => System.Console.WriteLine(x), "hello world!");\nApplyChanges();	0
13961147	13957536	MVC4 - how to use EditorFor() with dynamic form data from a database	...\n<tr>\n    @foreach(var fld in Model)\n    {\n        <td>\n            @Html.EditorFor(m => fld)\n        </td>\n    }\n</tr>\n...	0
3445181	3445169	How to convert a string with date and time to DateTime data type?	var date = DateTime.ParseExact(\n                       "201004224432", \n                       "yyyyMMddHHmmss",\n                       CultureInfo.InvariantCulture);	0
12031729	12031690	How to use IN with Dapper	//string categoriesJoined = string.Join(",", cats);\n using (var conn = new SqlConnection())\n {\n      conn.Open();\n\n      //make this a union all\n      return _categories = conn.Query<Category>("select Id, ParentId, Name from [Meshplex].[dbo].Category where Id IN @joined", new { joined = cats}).ToList();\n  }	0
11444892	11444780	Using Regular Expression for assigning multiple variables	var result = Regex.Match(s, @"(\d*)H(\d*)M(\d*.\d*)");\nhour = int.Parse(result.Groups[1].Value);\nminute = int.Parse(result.Groups[2].Value);\nsecond = double.Parse(result.Groups[3].Value);	0
30605650	30560722	Local settings in Windows Phone 8.1 app are not stored	Windows.Storage.ApplicationData.Current.LocalSettings.Values["key"] = value;	0
27225722	27190140	Remove white space from xml node not to attribute value	var bpsResponseXml = new XElement("BPSResponse");         \n\nbpsResponseXml.Add(new XElement("Response",\n                                    new XElement("Code", "804"),\n                                    new XElement("Text", "TagID value is not genuine")));\n\nvar outPutXml = bpsResponseXml.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);	0
26860739	26859060	SendKeys in c# - not able to send multiple keys	startInfo = new ProcessStartInfo();\n   startInfo.FileName = @"C:\New\MyProj.exe";\n   Process process = Process.Start(startInfo);\n   process.WaitForInputIdle();\n   SetForegroundWindow(h);\n   SendKeys.SendWait("%h");	0
11670503	11670325	How to split into sublists using LINQ?	public static IEnumerable<IEnumerable<T>> SplitColumn<T>( IEnumerable<T> source ) {\n    return source\n        .Select( ( x, i ) => new { Index = i, Value = x } )\n        .GroupBy( x => x.Index % 3 )\n        .Select( x => x.Select( v => v.Value ).ToList() )\n        .ToList();\n}	0
2973770	2973755	How to implement SQL "in" in Entity framework 4.0	var users = from e in context.Users where idList.Contains(e.UserId)	0
9645107	9644818	Read a Text File in Windows 8	Package.Current.InstalledLocation.GetFileAsync	0
12064708	12064636	parsing CDATA in XElement	"<Text>&lt;[CDATA[Sample Text &lt;b&gt;BoldText&lt;/b&gt; ]]&gt;</m:FormText>"	0
1366816	1366711	Issue while reading a xml file in WCF service	System.IO.FileStream fs = new System.IO.FileStream(@"D:\Test.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read);	0
9531864	9531781	Lambda expressions for arrays?	public sealed class RectangularArrayView<T> : IList<T>\n{\n    private readonly int row;\n    private readonly T[,] array;\n\n    public RectangularArrayView(int row, T[,] array)\n    {\n        this.row = row;\n        this.array = array;\n    }\n\n    public T this[int column]\n    {\n        get { return array[row, column]; }\n        set { array[row, column] = value; }\n    }\n\n    // etc for other IList<T> methods; use explicit interface implementation\n    // for things like Add which don't make sense on arrays\n}	0
19323218	19322532	Updating a detached entity in Entity Framework with related entites	notifier.MyCaseID = MyCaseID;\nnotifier.NotifierType = null;\nnotifier.NotifierTypeID = notifierView.NotifierTypeID;	0
3104494	3100345	How to read processing instruction from an XML file using .NET 3.5	XmlProcessingInstruction instruction = doc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;	0
2073365	2072506	ASP.NET - Proper way to initialize a user control created in a repeater?	public int IdBers\n {\n     set { VeiwState["IdBers"] = value; }    \n     get { \n             int idBerVal = 0;\n             if(VeiwState["IdBers"] != null)\n             {\n                 int.TryParse(VeiwState["IdBers"].ToString(), out idBerVal);\n             }\n             return idBerVal; \n         }\n }\n\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    txtTest.Text = IdBers.ToString();\n}	0
27184944	27184708	Attaching PDF file in email	attachment = new System.Net.Mail.Attachment(HttpContext.Current.Server.MapPath("~/users/Receipts/abc-414.pdf"));	0
19190576	19034528	game in Unity3d scaling objects with mouse in c sharp	public float maxScale = 10.0f;\npublic float minScale = 2.0f;\npublic float shrinkSpeed = 1.0f;   \n\nprivate float targetScale;\nprivate Vector3 v3Scale;\n\nvoid Start() {\n   v3Scale = transform.localScale;   \n}\n\nvoid Update()\n{\n   RaycastHit hit;\n   Ray ray;\n\n   if (Input.GetMouseButtonDown (0)) {\n     ray = Camera.main.ScreenPointToRay(Input.mousePosition);\n     if (Physics.Raycast(ray, out hit) && hit.transform == transform) {\n      targetScale = minScale;\n      v3Scale = new Vector3(targetScale, targetScale, targetScale);\n     }\n\n   }\n\n   if (Input.GetMouseButtonDown (1)) {\n     ray = Camera.main.ScreenPointToRay(Input.mousePosition);\n     if (Physics.Raycast(ray, out hit) && hit.transform == transform) {\n      targetScale = maxScale;\n      v3Scale = new Vector3(targetScale, targetScale, targetScale);\n     }\n   }\n\n   transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime*shrinkSpeed);\n}	0
832740	832360	How to serialize classes that were not designed to be serialized?	public class Unserializable\n{\n  public int Age { get; set; }\n  public int ID { get; set; }\n  public string Name { get; set; }\n}\n\npublic class Program\n{\n  static void Main()\n  {\n    var u = new Unserializable\n            {\n              Age = 40,\n              ID = 2,\n              Name = "Betty"\n            };\n    var jser = new JavaScriptSerializer();\n    var jsonText = jser.Serialize( u );\n    // next line outputs {"Age":40,"ID":2,"Name":"Betty"}\n    Console.WriteLine( jsonText );\n  }\n}	0
12328880	12328438	OpenCv: Finding multiple matches	// after your call to MatchTemplate\nfloat threshold = 0.08;\ncv::Mat thresholdedImage;\ncv::threshold(result, thresholdedImage, threshold, 255, CV_THRESH_BINARY);\n// the above will set pixels to 0 in thresholdedImage if their value in result is lower than the threshold, to 255 if it is larger.\n// in C++ it could also be written cv::Mat thresholdedImage = result < threshold;\n// Now loop over pixels of thresholdedImage, and draw your matches\nfor (int r = 0; r < thresholdedImage.rows; ++r) {\n  for (int c = 0; c < thresholdedImage.cols; ++c) {\n    if (!thresholdedImage.at<unsigned char>(r, c)) // = thresholdedImage(r,c) == 0\n      cv::circle(sourceColor, cv::Point(c, r), template.cols/2, CV_RGB(0,255,0), 1);\n  }\n}	0
15419400	15418918	XML file couldn't be detected after windows service setup	Environment.CurrentDirectory = new FileInfo(Assembly.GetExecutingAssembly().FullName).DirectoryName;	0
4566349	4566129	Try to play MP3 audio file with NAudio	var pStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(mp3Reader);\nvar inputStream = new NAudio.Wave.BlockAlignReductionStream(pStream);	0
21701189	21700929	Unable to format data taken from web-service	txthistoryD.Text += ddlCode.SelectedValue.ToString() + "\n";	0
18424114	18424060	Double filter with lambda expression	if(products.Any(x=>x.code.Equals(Code.Text) && !x.id.Equals(Id.Text))){\n     CodeExists = true;\n}	0
1969907	1969812	How I could assign a preset set of string values to a field of table in SQL Server 2008?	public enum DayOfWeek { Monday, Tuesday, Wednesday, /*etc*/ }	0
24375500	24375480	SQL - convert query to linq to sql and to lambda expression	var result = db.TABLE1\n               .Where(x => x.Status == 1)\n               .GroupBy(x => x.MID)\n               .Select(g => new {\n                    MID = g.Key,                \n                    Date = g.Max(x => x.CreatedDate)\n               }).ToList();	0
3524957	3494757	Elegant Solution to Parsing XElements in a Namespace	public static XElement\n      GetNamespaceElement(this XElement element, string ns, string name)\n      {\n          XNamespace n = new XNamespace();\n          n.NamespaceName = ns;\n          return element.Element(n + name);\n      }	0
11932438	11932328	Getting integer from textbox	int midtermInt;\nif (!int.TryParse(textBox1.Text, out midtermInt))\n{\n    labelError.Text = "Icorrect value in field 'textBox1'".\n    return;\n}	0
16902725	16902024	c# Console App with self-tracking entities: Where shall I store the EF5 DbContext instead in the HttpContext?	private static CmsCoreContext _coreContext;\n\nprotected static CmsCoreContext CoreContext\n{\n   get\n   {\n      if (!System.Web.Hosting.HostingEnvironment.IsHosted)\n      {\n         return _coreContext ?? (_coreContext = new CmsCoreContext());\n      }\n\n      var context = HttpContext.Current;\n      if (context == null) throw new InvalidOperationException();\n\n      if (!context.Items.Contains("CoreContext"))\n      {\n         context.Items.Add("CoreContext", new CmsCoreContext());\n      }\n\n      return (CmsCoreContext)context.Items["CoreContext"];\n   }\n}\n\n// The Application_EndRequest event won't fire in a console application.\npublic static void ConsoleCleanup()\n{\n   if (_coreContext != null)\n   {\n      _coreContext.Dispose();\n   }\n}	0
18869931	18869857	Get sender of mouseDown event	string dragSourceName = null;\n\n\n private void pbxMinotaur_MouseDown(object sender, MouseEventArgs e)\n        {\n            pbxMap.AllowDrop = true;\n            pbxMinotaur.DoDragDrop(pbxMinotaur.Name, DragDropEffects.Copy |\n            DragDropEffects.Move);\n            Control c = (sender as Control);\n            if(c != null)\n                 dragSourceName = c.Name;\n        }\n\n    private void pbxMap_DragDrop(object sender, DragEventArgs e)\n    {\n        if (dragSourceName == pbxMinotaur.Name)\n        {\n            myDetectMouse.setMinotaur(e, myMap.myCells);\n        }	0
24449557	24449510	Cannot assign <null> to an implicitly-typed local variable	string[] AllBranch_IDs = null;\n\nif (radioButton_QP.Checked == true)   \nAllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<string>("BusinessSectorID")).ToArray();\nelse\n\nAllBranch_IDs = dt_branches_global.AsEnumerable().Select(x => x.Field<int>("BusinessSectorID").ToString()).ToArray();	0
2591623	2591564	how to merge xml string to main xml document object	string xmlString = "<employee><name>cliff</name></employee>";\nXmlDocument xmlDoc = new XmlDocument();\nXmlElement xmlCompany = xmlDoc.CreateElement("Company");\nxmlCompany.InnerXml = xmlString;	0
4250759	4250745	Date formatting yyyymmdd to yyyy-mm-dd	tdrDate = DateTime.ParseExact(dateString, "yyyyMMdd", null).ToString("yyyy-MM-dd");	0
13490552	13489832	How to get the IPAddress from HostName in c# windows 8 Metro App?	await clientSocket.ConnectAsync(serverHost, "https");	0
6237761	6237734	How to request only the HTTP header with C#?	webRequest.Method = "HEAD";	0
17226660	17223063	Continuous input to switch case until i press exit c#	using System;\n\nnamespace LoopUntilSelectionTester\n{\n    class Program\n    {\n        static void Main()\n        {            \n            string key;\n            while((key = Console.ReadKey().KeyChar.ToString()) != "6")            \n            {\n                int keyValue;                \n                int.TryParse(key, out keyValue);\n\n                ProcessInput(keyValue);\n            }    \n        }\n\n        private static void ProcessInput(int keyValue)\n        {\n            switch (keyValue)\n            {\n                case 1:\n                    DoApps(reqObj);\n                    break;\n                case 2:\n                    DoDrivers(reqObj);\n                    break;\n                case 3:\n                    DoOS(reqObj);\n                    break;\n                case 4:\n                    DoPackages(reqObj);\n                    break;\n                case 5:\n                    DoAll(reqObj);\n                    break;\n            }\n        }\n    }\n}	0
7839415	7839299	GridVew column with checkbox field with SQL	protected void GVRowDataBound(object sender, GridViewRowEventArgs e)\n        {\n            var check = (CheckBox) e.Row.FindControl("ID"); // ID is id of the checkbox\n            var lable = (Label) e.Row.FindControl("LableID");\n            if(check != null && lable != null)\n            {\n                if(check.Checked)\n                {\n                    lable.Visible = false;\n                }\n            }\n         }	0
21100927	21097312	Android XAMARIN : Camera intent is returning with null data in callback	intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(_file));	0
22193459	22168701	Set ZeroMQ reconnect interval C#	public static void DisableReconnect(this ZmqSocket socket)\n{\n   socket.ReconnectInterval = TimeSpan.FromMilliseconds(-1);\n}	0
13206868	13205105	Set checked items in checkedlistbox from list or dataset	List<tableClass> list = MyCheckedList();\nfor (int count = 0; count < checkedListBox1.Items.Count; count++)\n{\n  if (list.Contains(checkedListBox1.Items[count].ToString()))\n  {\n    checkedListBox1.SetItemChecked(count, true);\n  }\n}	0
7299266	7299220	Can't retrieve nested information from eBay API	XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services"\n\nXElement ack = doc.Root.Element(ns + "ack");\nXElement version = doc.Root.Element(ns + "version");\nIEnumerable<string> itemIds = doc.Root.Elements(ns + "searchResult")\n                                      .Element(ns + "item")\n                                      .Element(ns + "itemId")\n                                      .Select(x => (string) x);	0
3365015	3364961	Windows Forms: How to extend a button?	class ToggleButton : Button {\n// Add your extra code\n}	0
2948855	2948805	How can I send an array of strings from one ASP.NET page to another?	string1=&string2=	0
12439290	12439228	Get Dopdownlist value based on SelectedIndex	string item4 = DropDownList1.Items[3].Value;\n\n item4 = DropDownList1.SelectedIndex = 3; is not correct.	0
13165787	12897815	WebBrowser control doesn't populate on first iteration if loading two controls	myBrowser.NavigateToString("");	0
12178754	12178585	Get Child elements through linq to xml	var doc = XDocument.Load(fileName);\nvar lis = (from e in doc.Descendants("li")\n          where e.Parent.Attribute("Type").Value == "Company"\n          select e.Value).ToArray();	0
507349	507317	Relative filepath with HttpWebRequest object	var basePath = Path.GetDirectoryName(typeof(MyType).Assembly.Location);\nvar fullPath = Path.Combine(basePath, @"TestData\test.html");\nreturn new Uri(fullPath);	0
14841961	14697658	RX Observable.TakeWhile checks condition BEFORE each element but I need to perform the check after	public static IObservable<TSource> TakeUntil<TSource>(\n        this IObservable<TSource> source, Func<TSource, bool> predicate)\n{\n    return Observable\n        .Create<TSource>(o => source.Subscribe(x =>\n        {\n            o.OnNext(x);\n            if (predicate(x))\n                o.OnCompleted();\n        },\n        o.OnError,\n        o.OnCompleted\n    ));\n}	0
20971315	20967872	MediaElement doesn't play after resuming app	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    beepSound.Source = new Uri("/Sounds/beep.mp3", UriKind.Relative);\n}	0
3035530	3034614	WPF- Is there a way to make a TabContol ignore CTRL-Tab and still fire CTRL-TAB keybindings on the parent window?	public class TabControlIgnoresCtrlTab : TabControl\n{\n  protected override void OnKeyDown(KeyEventArgs e)\n  {\n    if(e.Key == Key.Tab) return;\n    base.OnKeyDown(e);\n  }\n}	0
6992544	6992164	Manipulating a String: Removing special characters - Change all accented letters to non accented	string s = "#Hi this          is  r??ally/ special str??ng!!!";\nstring normalized = s.Normalize(NormalizationForm.FormD);\n\n\nStringBuilder resultBuilder = new StringBuilder();\nforeach (var character in normalized)\n{\n    UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory(character);\n    if (category == UnicodeCategory.LowercaseLetter\n        || category == UnicodeCategory.UppercaseLetter\n        || category == UnicodeCategory.SpaceSeparator)\n        resultBuilder.Append(character);\n}\nstring result = Regex.Replace(resultBuilder.ToString(), @"\s+", "-");	0
714764	714653	best way to turn a post title into an URL in c#	static Regex regStripNonAlpha = new Regex(@"[^\w\s\-]+", RegexOptions.Compiled);\nstatic Regex regSpaceToDash = new Regex(@"[\s]+", RegexOptions.Compiled);\n\npublic static string MakeUrlCompatible(string title)\n{\n    return regSpaceToDash.Replace(\n      regStripNonAlpha.Replace(title, string.Empty).Trim(), "-");\n}	0
28251594	28249555	Download and encode HTML page into file	System.IO.File.WriteAllText(fileName, pageHtml, Encoding.UTF8);	0
9382432	9382216	get methodinfo from a method reference C#	var methodInfo = SymbolExtensions.GetMethodInfo(() => Program.Main());	0
7503904	7503799	How do I do a sub-select in LINQ?	var query = from cl in context.BaCodeLibrary\n            where cl.code_id == 25468 && cl.isactive == 1\n            orderby cl.Plan_num\n            select new\n            {\n              Level = (from ba in context.baLevel\n                       where ba.ba_level_code == ("0" + ba.Level_Num)\n                       select ba.ba_level_code + " - " + ba.ba_level_desc).Take(1),\n\n              Column = (from ba in context.baPlanColumnStructure \n                        where ba.Column_Num == cl.Column_Num\n                        select ba.ba_level_code + " - " + ba.ba_level_desc).Take(1),\n\n               Sort_Order = cl.Sort_Order\n            }	0
23464004	23463201	How to be able to control the movement of a panel on a UserControl?	PreviewKeyDown += PreviewKeyDownHandler;\n\npublic void PreviewKeyDownHandler(object sender, PreviewKeyDownEventArgs e)\n{\n    switch (e.KeyData)\n    {\n        case Keys.Right:\n            panel1.Location = new Point(panel1.Location.X + 5, panel1.Location.Y);\n            Invalidate();\n            break;\n    }\n}	0
18218998	18218451	SSIS Getting Execute Sql Task result set object	DataTable dt = new DataTable();\nOleDbDataAdapter oleDa = new OleDbDataAdapter();\noleDa.Fill(dt, Dts.Variables["User::objShipment"].Value);	0
5148647	5148601	How to determine the size of each dimension of multi-dimensional array?	moreInts.GetLength(0);\nmoreInts.GetLength(1);\nmoreInts.GetLength(2);	0
11198665	11198471	Filtering results within a DataTable (date column between date1 and date2)	Datarow[] products = prices.Select(string.Format("'{0}'>='{1}' AND '{0}'<='{2}'", mydate, startdate, finaldate));	0
5861147	5861102	What is the default highlight color of a menu in C#?	SystemColors.MenuHighlight	0
9965532	9964115	Accessing user via C#	IPage currentPage; /* Initialize with the current page */ \nvar permissions = \n   PermissionsFacade.GetPermissionsForCurrentUser(currentPage.GetDataEntityToken());	0
17280918	17279057	How to remove duplicate nodes in an XML document in C#?	XmlNodeList nodes = doc.SelectNodes("//bmtactionlog/transaction/action[@type='SetActiveLocale']");\nXmlNode actionNode = doc.SelectSingleNode("//bmtactionlog");\nfor(int i = 1; i < nodes.Count; i++)\n{\n    actionNode.RemoveChild(nodes[i]);\n}	0
25013774	25013630	Read data once and use later	Lazy<T>	0
32540674	32539477	C# Mongodb Driver - How to insert an element into an array at position 0	var filter = Builders<ChatRoom>.Filter.Eq(Keys.MongoId, ObjectId.Parse(chatRoomId));\nvar update = Builders<ChatRoom>.Update.PushEach(Keys.Comments, new List<Comment>() { comment }, position: 0);\nawait MongoCollections.GetChatRoomCollection().UpdateOneAsync(filter, update);	0
12465131	12378176	Sftp from SharpSSH and public key	ftp = new Sftp(config.SftpServer, config.SftpUsername, config.SftpPassowrd);\n fpt.AddIdentityFile("file");\n ftp.Connect();	0
31400116	31393887	Wrong results with CAML Query	var camlQuery = Camlex.Query().WhereAny(expressions).ToCamlQuery();	0
6442111	6442098	How to clear all data in a listBox?	listbox1.Items.Clear();	0
16842475	16842152	How create Ninject factory	kernel.Bind<IModelValidator>()\n      .ToProvider<ModelValidatingFactory>();\nkernel.Bind<ModelValidatingFactory>()\n      .ToConstant(new ModelValidatingFactory(/*pass your parameter */));	0
14869167	14869067	Datetime formats automatically on Email	DateTime.Now.ToShortDateString()	0
3956239	3956216	Dynamic Fetch an Inheritance in Entity Framework 4 POCO	context.C              // all C's (including all A's and all B's)\n\ncontext.C.OfType<A>()  // all A's\n\ncontext.C.OfType<B>()  // all B's	0
4251752	4251694	How to start a external executable from c# and get the exit code when the process ends	public virtual bool Install(string InstallApp, string InstallArgs)\n    {\n        System.Diagnostics.Process installProcess = new System.Diagnostics.Process();\n        //settings up parameters for the install process\n        installProcess.StartInfo.FileName = InstallApp;\n        installProcess.StartInfo.Arguments = InstallArgs;\n\n        installProcess.Start();\n\n        installProcess.WaitForExit();\n        // Check for sucessful completion\n        return (installProcess.ExitCode == 0) ? true : false;\n    }	0
11120826	11119893	Unreliable parallel loop fails 4 out of 400 times	private static void GenerateIcons(Effects effect)\n{\n    var dir     = new DirectoryInfo(HttpContext.Current.Server.MapPath(@"~\Icons\Original\"));\n    var mappath = HttpContext.Current.Server.MapPath(@"~\Icons\");\n    var ids     = GetAllEffectIds(effect.TinyUrlCode);\n\n    var filesToProcess = dir\n        .EnumerateFiles()\n        .AsParallel()\n        .Select(f => new { info = f, generated = File.Exists(mappath + @"Generated\" + ids + "-" + f.Name) })\n        .ToList();\n\n    Parallel.ForEach(filesToProcess.Where(f => !f.generated), file =>\n    {\n        new ApplyEffects(effect, file.info.Name, mappath).SaveIcon();\n    });\n\n    //Zip icons!\n    ZipFiles(filesToProcess.Select(f => f.info), effect.TinyUrlCode, ids, effect.General.Prefix);\n}	0
21753019	21752902	VB to C# how to convert if param and 1	if ((param & 1) != 0)\n{\n    ..\n}	0
15580123	15579946	SQL bigint hash to match c# int64 hash	System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create();\nbyte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com"));\nlong value = BitConverter.ToInt64(b, 12);\nvalue = IPAddress.HostToNetworkOrder(value);\n\nDebug.WriteLine(value);\n// writes 2172193747348806725	0
7107917	7061104	Initiating objects with mutual dependency	public class Film {\n    ...\n    public readonly IEnumerable<Director> Directors = _repository.GetDirectors(this.iD);\n}	0
18915627	18915530	asp.net mvc datetime didn't display their value	[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]	0
13001336	13000257	Return NULL datetime value from T-SQL into C# DataTable ==> DataRow instead of empty string	DateTime? temp = String.IsNullOrEmpty(row[10].ToString())? null : DateTime.Parse(temp0);	0
29549441	29549238	Using regex to split string by Non Digit and Digit	string[] results = Regex.Split("FGG217H5IJ1", @"(?<=\d)(?=\D)|(?<=\D)(?=\d)");\nConsole.WriteLine(String.Join(" ", results)); //=> "FGG 217 H 5 IJ 1"	0
1206071	1206023	How to get current property name via reflection?	class Program\n    {\n        static void Main(string[] args)\n        {\n            Program p = new Program();\n            var x = p.Something;\n            Console.ReadLine();\n        }\n\n        public string Something\n        {\n            get\n            {\n                return MethodBase.GetCurrentMethod().Name;\n            }\n        }\n    }	0
2328139	2327383	WPF Listbox.selecteditems returns items in the order they were selected	foreach (<yourobject> item in listForSelection.Items)\n            {\n                if (listForSelection.SelectedItems.Contains(item))\n                {\n                     \\code here\n                }\n            }	0
33737442	33737224	Ignore nested quote marks with RegEx	(?!["]).*(?<!["])	0
1357390	1126545	Is it possible to programatically log access to a windows share (SMB share) using the .Net framework?	using System.Management;\n ManagementObjectSearcher search =\n             new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_ConnectionShare"); \n        foreach (ManagementObject MO in search.Get())\n        {\n            string antecedent = MO["antecedent"].ToString();\n            ManagementObject share = new ManagementObject(antecedent);\n\n\n            string dependent = MO["dependent"].ToString();\n            ManagementObject server = new ManagementObject(dependent);\n\n\n            string userName = server["UserName"].ToString();\n            string compname = server["ComputerName"].ToString();\n            string sharename = server["ShareName"].ToString();\n        }	0
21848042	21847904	Use a WPF Window in two ways	Visibilty.Collapsed	0
19181922	19181824	select all children of an element	XDocument xd = XDocument.Parse(xmlString);\nvar query = xd.Root.Elements("Total")\n    .Descendants()\n    .Where(x=>x.Name.LocalName.StartsWith("Total"));	0
22143176	22143066	DatePicker to text on navigated in Windows Phone	dateData.Value=your value;	0
634814	634777	C# Extension Method - String Split that also accepts an Escape Character	public static IEnumerable<string> Split(this string input, \n                                        string separator,\n                                        char escapeCharacter)\n{\n    int startOfSegment = 0;\n    int index = 0;\n    while (index < input.Length)\n    {\n        index = input.IndexOf(separator, index);\n        if (index > 0 && input[index-1] == escapeCharacter)\n        {\n            index += separator.Length;\n            continue;\n        }\n        if (index == -1)\n        {\n            break;\n        }\n        yield return input.Substring(startOfSegment, index-startOfSegment);\n        index += separator.Length;\n        startOfSegment = index;\n    }\n    yield return input.Substring(startOfSegment);\n}	0
28882150	28880730	Bing Maps Force MapIcon to always show	IsLocationInView()	0
8660668	8660432	How to repair UnsupportedImageFormatException PixelFormat Format32bppArgb?	// Convert to Format24bppRgb\nprivate static Bitmap Get24bppRgb(Image image)\n{\n    var bitmap = new Bitmap(image);\n    var bitmap24 = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);\n    using (var gr = Graphics.FromImage(bitmap24))\n    {\n        gr.DrawImage(bitmap, new Rectangle(0, 0, bitmap24.Width, bitmap24.Height));\n    }\n    return bitmap24;\n}	0
23974466	19740975	Get Microsoft Account Id from Windows 8 desktop application	public static string GetAccoutName()\n{\n    var wi= WindowsIdentity.GetCurrent();\n    var groups=from g in wi.Groups                       \n               select new SecurityIdentifier(g.Value)\n               .Translate(typeof(NTAccount)).Value;\n    var msAccount = (from g in groups\n                     where g.StartsWith(@"MicrosoftAccount\")\n                     select g).FirstOrDefault();\n    return msAccount == null ? wi.Name:\n          msAccount.Substring(@"MicrosoftAccount\".Length);\n}	0
1550568	1550560	Encoding an integer in 7-bit format of C# BinaryReader.ReadString	Remaining integer                 encoded bytes\n1001011000100110011101000101101\n100101100010011001110100          00101101\n10010110001001100                 10101101 01110100\n1001011000                        10101101 11110100 01001100\n100                               10101101 11110100 11001100 01011000\n0                                 10101101 11110100 11001100 11011000 00000100	0
34504482	34468738	Replacement matching regex with anchor tag?	var content =    doc.DocumentNode.SelectSingleNode("//div[@class='main-content']");\nvar items = content.SelectNodes(".//text()[normalize-space(.) != '']");\nforeach (HtmlNode node in items)\n {\n       if (!matchLegals.IsMatch(node.InnerText) || node.ParentNode.Name == "a")\n{\n                               continue;\n }\n\n  var texts = node.InnerHtml.Trim();\n  node.InnerHtml = matchLegals.Replace(texts, a => string.Format("<a href='/search?q={0}'>{0}</a>",a.Value));\n\n }	0
21319572	21314067	Connecting to a Restful Web Service using Basic Authentication	string basic = "Basic ENCRYPTEDSTRING";\n   HttpClient client = new HttpClient();\n   client.DefaultRequestHeaders.Add("Authorization", basic);	0
15685032	15638761	Find url name in XML document	XmlDocument xmlDocument = new XmlDocument();\n\n        xmlDocument.Load(Server.MapPath("~/App_Data/menu.xml"));\n\n        XmlNodeList levelOneElements = xmlDocument.SelectNodes("root/menu[contains(@type,'" + Title.Text.ToLower() +  "')]/L1");\n\n        for (int i = 0; i < levelOneElements.Count; i++)\n        {\n            XmlNode levelOne = levelOneElements.Item(i);\n            if (levelOne.OuterXml.Contains(_menu))\n            {\n                _index = i;\n                break;\n            }\n        }	0
12558142	12558078	SQL Server : stored procedure challenge	CREATE PROCEDURE UpdatePrice\n    @Polenless BIT,\n    @Height BIT,\n    @Organic BIT,\n    @Lifecycle BIT,\n    @color NVARCHAR(50),\n    @seedType NVARCHAR(50)\n\nAS\nBEGIN\n   UPDATE SunflowerSeeds\n   SET Price = Price +  \n                        ((Price * 0.1) * @Polenless)+\n                        ((Price * 0.08) * @Height)+\n                        ((Price * 0.15) * @Organic)+\n                        ((Price * 0.12) * @Lifecycle)\n    WHERE Color = @color  AND SeedType = @seedType\n\nEND\nGO	0
14779325	14749549	syntax error in insert into mdb	INSERT INTO [Reports] (\n    docid, biopsy, normal, [section], subsection, title, items, [text])\nVALUES (\n    21, False, False, 'Recommendation', 'a', 'Injection', 'a', 'a');	0
26397707	26397208	How to update a List when binded to a ListView	public class A : INotifyPropertyChanged\n    {   \n        private IList<int> _lists;\n        IList<int> List { \n            get {\n               return _lists;\n            }; \n            set {\n               _lists = value;\n               OnPropertyChanged("List");\n            }\n          }\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n    private void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = this.PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n}	0
786743	784005	Code to add a host header to an IIS Website	static void Main(string[] args)\n{\n    AddHostHeader(1, "127.0.0.1", 8080, "fred");\n    AddHostHeader(1, null, 8081, null);\n}\n\nstatic void AddHostHeader(int? websiteID, string ipAddress, int? port, string hostname)\n{\n    using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + websiteID.ToString()))\n    {\n        var bindings = directoryEntry.Properties["ServerBindings"];\n        var header = string.Format("{0}:{1}:{2}", ipAddress, port, hostname);\n\n        if (bindings.Contains(header))\n            throw new InvalidOperationException("Host Header already exists!");\n\n        bindings.Add(header);\n        directoryEntry.CommitChanges();\n    }\n}	0
21394869	21394593	How do i add all the lines to the SetupText(new string[] {?	const int maxLines = 5;\n\nvar lines = Regex.Split(readableRss, "\r\n")\n                   .Where(str => !string.IsNullOrEmpty(str))\n                   .ToList();\nthis.newsFeed1.NewsTextFeed = new string[maxLines];\nSetupText(lines\n             .Skip(Math.Max(0, lines.Count() - maxLines))\n             .Take(maxLines)\n             .ToArray());	0
18910180	18909540	Querying a datatable with top clause	DataTable MyTable = new DataTable();// Yur Table here\n  var FirstResult = from Row in MyTable.AsEnumerable()\n                    orderby Row.Field<int>("Index")\n                    select new\n                    {\n                      KioskId = Row.Field<string>("KioskId"),\n                      Index = Row.Field<int>("Index"),\n                      FileName = Row.Field<string>("FileName")\n                    };\n  var AfterRowNumbering = FirstResult.Select((x, index) => new  {\n                      KioskId=x.KioskId,\n                      Index=x.Index,\n                      FileName = x.FileName,\n                      Row_Number = index\n                      }).Take(5);\n var FinalResult = from row in AfterRowNumbering\n                   where row.Row_Number > 10\n                   select row;	0
25146995	25146905	PropertyInfo.GetValue unable to compare datetimes?	private bool CompareObj(Visit object1, Visit object2)\n{\n    foreach (var obj1PropertyInfo in object1.GetType().GetProperties())\n    {\n        foreach (var obj2PropertyInfo in object2.GetType().GetProperties())\n        {\n            if (obj1PropertyInfo.Name == obj2PropertyInfo.Name\n            && !Equals(obj1PropertyInfo.GetValue(object1, null),\n            obj2PropertyInfo.GetValue(object2, null)))\n            {\n                return false;\n            }\n        }\n    }\n    return true;\n}	0
27308630	27308266	How do I remove elements from an array in First In First Out manner	class Program\n    {\n        static void Main(string[] args)\n        {\n            const int CAPACITY = 10;\n            Queue<int> queue = new Queue<int>(CAPACITY);\n            for (int i = 0; i < 50; i++)\n            {\n                if (queue.Count == CAPACITY)\n                    queue.Dequeue();\n                queue.Enqueue(i);\n            }\n            queue.ToArray();\n            Console.WriteLine(queue.Count);\n            Console.ReadKey();\n        }\n\n    }	0
12426560	12422290	ASP.NET Chart how to display all XValues	myArea.AxisX.Interval=1;	0
15245905	15245786	WPF - Hosting a content control inside a Data Template via code	FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));\n\nBinding placeBinding = new Binding();\n\nfef.SetBinding(TextBlock.TextProperty, placeBinding);\n\nplaceBinding.Path = new PropertyPath("Name");\n\ndataTemplate = new DataTemplate();\n\ndataTemplate.VisualTree = fef;	0
15829145	15828774	Old printer text format c#	using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))\n{\n   writer.WriteLine(s);\n}	0
8589412	8588254	How to pass List of int value to SP from code behind?	for (int i = 0; i < IDList.Count; i++)\n {\n    Cmd.Parameters.Clear();\n    Cmd.Parameters.AddWithValue("@ImageId", IDList[i]);\n }	0
5862181	5862122	casting BindList<Classname> to BindingList<Interface>	BindingList<I> funcName(){\n   ...\n   return new BindingList<I>(C.listA);\n}	0
26970931	26970762	Check Session timeout on invoking constructor of a controller in MVC 4	protected void Application_AcquireRequestState(object sender, EventArgs e)\n{\n     if (HttpContext.Current.Handler is IRequiresSessionState)\n     {\n         var usrobj = HttpContext.Current.Session["User"];\n         if(usrobj == null)\n         {\n             Response.Redirect("~/Login/Index");\n         }\n     }\n}	0
6660633	6660400	Runtime appconfig value changes	ConfigurationManager.RefreshSection(sectionName);	0
34125163	34124978	How can I remove any footnote or notes or end notes in my Xpathselectelement	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml.XPath;\nusing System.Xml.Linq;\nusing System.Xml;\n\nnamespace Test\n{\n    class Program\n    {\n        static int Main(string[] args)\n        {\n            String xml = "<h3>Blah blah<sup><a>1</a></sup></h3>";\n            XDocument xDoc = XDocument.Parse(xml);\n            var h3 = xDoc.XPathSelectElement("//h3");\n            String tmp = h3.DescendantNodes().Where(node=>node.NodeType == XmlNodeType.Text).First().ToString();\n            Console.WriteLine(tmp);\n            return 1;\n        }\n\n    }\n}	0
14698477	14697789	How should I parse this json response in c#?	private struct MyStruct\n{\n  public System.Collections.ArrayList jquery { get; set; }\n}\n\nstring testJson = "{\"jquery\": [[0, 1, \"call\", [\"body\"]], [1, 2, \"attr\", \"find\"], [2, 3, \"call\", [\".status\"]], [3, 4, \"attr\", \"hide\"], [4, 5, \"call\", []], [5, 6, \"attr\", \"html\"], [6, 7, \"call\", [\"\"]], [7, 8, \"attr\", \"end\"], [8, 9, \"call\", []], [0, 10, \"call\", [\"body\"]], [10, 11, \"attr\", \"captcha\"], [11, 12, \"call\", [\"uIP22Wow9xa68aLQ0tl1e9Uiiinracdj\"]]]}";\nMyStruct generic = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<MyStruct>(testJson);	0
5730761	5728885	How do I draw an image based on a simple polygon?	for (int y = 0; y < destHeight; y++) {\n    for (x=0; x < destWidth; x++) {\n        Color c = Transform(x, y, sourceImage, sourceTransform);\n        SetPixel(destImage, x, y, c);\n    }\n}	0
1349558	1349492	Access/Set controls on another form	Dim window1 as new Form2()\nDim window2 as new Form2()\n\nwindow1.Show()\nwindow2.Show()	0
3922421	3916891	silverlight communication between client and server	...\nserviceClient.YourOperationAsync(formName);\n...\n\nvoid serviceClient_YourOperationCompleted(object sender, YourOperationCompletedEventArgs e)\n{\n    if (e.UserState != null && e.UserState is string)\n    {\n       string formToUpdate = (string)e.UserState;\n       ...\n       ... update formToUpdate ...\n       ...\n    }\n}	0
12575837	12573450	ASP.NET - Master Page Disables Validator Error Message	ValidationGroup="RequiredFieldValidator1"	0
899636	899629	Cast object to T	if (readData is T) {\n    return (T)readData;\n} else {\n    try {\n       return (T)Convert.ChangeType(readData, typeof(T));\n    } catch (InvalidCastException) {\n       return default(T);\n    }\n}	0
16456118	16456036	How to sum of value in gridview select data from database in asp.net	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n   if (e.Row.RowType == DataControlRowType.DataRow)\n   {\n      Label lblPrice = (Label)e.Row.FindControl("lblPrice");\n      Label lblUnitsInStock = (Label)e.Row.FindControl("lblUnitsInStock");\n\n      decimal price = Decimal.Parse(lblPrice.Text);\n      decimal stock = Decimal.Parse(lblUnitsInStock.Text);\n\n      totalPrice += price;\n      totalStock += stock;\n\n      totalItems += 1;\n   }\n\n   if (e.Row.RowType == DataControlRowType.Footer)\n   {\n      Label lblTotalPrice = (Label)e.Row.FindControl("lblTotalPrice");\n      Label lblTotalUnitsInStock = (Label)e.Row.FindControl("lblTotalUnitsInStock");\n\n      lblTotalPrice.Text = totalPrice.ToString();\n      lblTotalUnitsInStock.Text = totalStock.ToString();\n\n      lblAveragePrice.Text = (totalPrice / totalItems).ToString("F");\n   }\n}	0
33298112	33297957	Contains matches on pairs of items	var mapQuery = from p in pairs \n               join m in context.Mappings\n               on new { p.Id, p.Type } equals new { m.ReferenceId, m.ReferenceType}\n               select m;\nList<Mapping> maps = mapQuery.ToList();	0
18599859	18599796	How can I access winForm Common control inside helper class?	// HelperClass method\npublic static void UpdateCommentLines(RichTextBox richTextBox)\n{\n    List<string> commentLines = richTextBox.Lines.ToList();\n}\n\n// WinForm Code\npublic void DoSomething()\n{\n    HelperClass.UpdateCommentLines(this.richTextBox1);\n}	0
17235896	17235193	ASP.NET maintaining static variables	public interface IMyConfig {\n  string Var1 { get; }\n  string Var2 { get; }\n}\n\npublic class MyConfig : IMyConfig {\n  private string _Var1;\n  private string _Var2;\n\n  public string Var1 { get { return _Var1; } }\n  public string Var2 { get { return _Var2; } }\n\n  private static object s_SyncRoot = new object();\n  private static IMyConfig s_Instance;\n\n  private MyConfig() {\n    // load _Var1, _Var2 variables from db here\n  }\n\n  public static IMyConfig Instance {\n    get {\n      if (s_Instance != null) {\n        return s_Instance;\n      }\n      lock (s_SyncRoot) {\n        s_Instance = new MyConfig();\n      }\n      return s_Instance;\n    }\n  }\n}	0
12978283	12900194	Select Workbook Excel already Open with a Button Click Method	using Excel = Microsoft.Office.Interop.Excel;\nusing Microsoft.Office.Tools.Excel;\nusing Office = Microsoft.Office.Core;\nusing Microsoft.VisualStudio.Tools.Applications.Runtime;\nExcel.Worksheet wsheet =\n  (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet;	0
26949609	26949561	How to get the value using XPath and using Parameter?	var xPathQuery = String.Format("//a[contains(.,'{0}')]", p0);\ndriver.FindElement(By.XPath(xPathQuery)).Click();	0
8945152	8944681	How does an application launcher update itself?	Updater A checks if its the newest version\nIf launcher isnt the newest version\n    Download the differences (to save bandwidth) to file B\n    Apply the delta to own code into file C\n    Launch file C.\n    Close\nIf file C exists (update happened recently)\n    Try to delete C  (update was previous launch, delete temporary file)\n    If delete fails  (We are C, means A is out of date)\n        Copy C over A  (update launcher)\n        Note that you can keep going, don't have to restart even though we are C.\nIf game isnt newest version\n    Download the differences (to save bandwidth) to file B\n    Apply the delta to game into file D\n    delete game\n    Rename D -> game\nRun game	0
26425866	26425760	ASP.NET: Remove specific item in Dropdownlist	for (int x = _intDiff -1; x > -1; x--)\n{  \n  DropDownList3.Items.Remove(DropDownList3.Items[x]);\n}	0
16776841	16776177	Dynamic model binding with ASP.NET WEB API	Content-Type: application/json	0
26579114	26578989	Deleting a section from a UITableView. NSIndexSet parameter?	tableView.DeleteSections( NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Fade);	0
28278280	28278167	How to retrive Property Name using DisplayName?	PropertyInfo[] properties = typeof(DoctorInfo).GetProperties();\n            foreach (PropertyInfo prop in properties)\n            {\n                object[] attrs = prop.GetCustomAttributes(true);\n\n                foreach (object attr in attrs)\n                {\n                    DisplayNameAttribute displayName = attr as DisplayNameAttribute;\n                    if (displayName != null)\n                    {\n                       var attributeName = displayName.DisplayName; // check if this matches what you want\n                    string propertyName = prop.Name;                        }\n                }\n            }	0
25705854	25705636	I'm using a project that capture screenshots from games but breakpoints never work why?	miliseconds = 1000 / fps	0
26075838	26071743	How do you get the Oauth2 AccessToken after its creation from the Owin Api?	public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)\n    {\n        var accessToken = context.AccessToken;\n        return Task.FromResult<object>(null);\n    }	0
24310036	24309945	Concat a enum with a string in a linq query	var q = (from income in context.Incomes\n         join order in context.Orders \n         on income.OrderId equals order.OrderId\n         select new \n         {\n             VoucherType = order.VoucherType,\n             VoucherSeries = order.VoucherSeries,\n             VoucherNumber = order.VoucherNumber,\n             IncomeAmount = income.IncomeAmout\n         }).AsEnumerable()\n           .Select(x=> new\n           {\n               Voucher = x.VoucherType + "-" + x.VoucherSeries + "-" +x.VoucherNumber,\n               Amount = x.IncomeAmount\n           };	0
33445068	33444528	How to prevent controllers in wrong areas from being used in MVC5	routes.MapRoute(\n    "Default",\n    "{controller}/{action}/{id}",\n    new { controller = "Home", action = "Index", id = UrlParameter.Optional },\n    namespaces: new [] { "AreaProblem.Controllers" }\n    ).DataTokens["UseNamespaceFallback"] = false;	0
8465213	8465179	C# easy way to convert a split string into columns	string startString = "Operations\t325\t65\t0\t10\t400"\nstring[] splitStart = startString.Split('\t');\n\nList<string> result = new List<string>();\n\nif(splitStart.Length > 1)\n   for(int i = 1; i < splitStart.Length; i++)\n   {\n      result.Add(splitStart[0] + "|" + splitStart[i]);\n   }	0
1026271	1026220	How to find out next character alphabetically?	char letter = 'c';\n\nif (letter == 'z')\n    nextChar = 'a';\nelse if (letter == 'Z')\n    nextChar = 'A';\n\nelse\n    nextChar = (char)(((integer) letter) + 1);	0
31691990	31691891	If User Input is equal to any value of an array	for (int i=0; i<4; i++)\n{\n    int input = int.Parse(Console.ReadLine());\n    if (numberSets[i].Contains(input))\n    {\n        // SUCCESS\n    }\n}	0
33865371	33804208	Update to latest FluentAssertions breaks my unittests	readObject.ShouldBeEquivalentTo(item, \n  options => options.Excluding(\n    p => p.SelectedMemberInfo.DeclaringType.GetProperty(p.SelectedMemberInfo.Name).GetCustomAttributes(typeof(IgnoreDataMemberAttribute), true).Length != 0));	0
12220397	12219246	Submit, Show Results, delay 3 seconds and redirect	protected void Button1_Click(object sender, EventArgs e)\n{\n    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "success", "alert('Submitted Successfully.'); setInterval(function(){location.href='http://www.google.com';},3000);", true);\n}	0
17600235	17599122	Getting Duplicate Id values from XML	var xDoc = XDocument.Load(fileName);\n            XElement vehicleCollection = xDoc.Element("Root").Element("VehicleCollection").Element("ModelInfo");\n            var vehicle = vehicleCollection.Descendants("Vehicle").ToList();\n            foreach (var v in vehicle)\n            {\n                Console.WriteLine(v.Element("Id"));\n            }\n            vehicleCollection = xDoc.Element("Root").Element("VehicleCollection").Element("PriceInfo");\n            vehicle = vehicleCollection.Descendants("Vehicle").ToList();\n            foreach (var v in vehicle)\n            {\n                Console.WriteLine(v.Element("Id"));\n            }	0
67530	67370	Dynamically Create a generic type for template	string elementTypeName = Console.ReadLine();\nType elementType = Type.GetType(elementTypeName);\nType[] types = new Type[] { elementType };\n\nType listType = typeof(List<>);\nType genericType = listType.MakeGenericType(types);\nIProxy  proxy = (IProxy)Activator.CreateInstance(genericType);	0
7642759	7632540	How to add new items to combobox which is bound to Entities?	private void FillCombobox()\n        {\n            using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities())\n            {\n                List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();              \n                DataTable dt = new DataTable();\n                dt.Columns.Add("id");\n                dt.Columns.Add("Name");\n                dt.Rows.Add(-1, "test row");\n                foreach (usepurpose usepurpose in usepurposes)\n                {\n                    dt.Rows.Add(usepurpose.id, usepurpose.Name);\n                }\n                usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName;\n                usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName;\n                usepurposeComboBox.DataSource = dt;\n            }\n        }	0
20672855	20672775	How to populate a dictionary of dictionaries of dictionaries?	ClientsData[0].Doctors[Reader["DocID"].ToString()].Add("Name", new List<string>(){ Reader["DocName"].ToString()});	0
6105259	6105144	How can I turn an anonymous type into a key value pair object	var items = new[]\n{\n    new Item { Id = 1, Name = "test1" }, \n    new Item { Id = 2, Name = "test2" }\n};\n\nvar dataTable = new DataTable();\nvar propeties = typeof(Item).GetProperties();\nArray.ForEach(propeties, arg => dataTable.Columns.Add(arg.Name, arg.PropertyType));\nArray.ForEach(items, item => dataTable.Rows.Add(propeties.Select(arg => arg.GetValue(item, null)).ToArray()));\nreturn dataTable;	0
8802812	8800743	Configure WCF service client with certificate authentication programmatically	service.ClientCredentials.ClientCertificate.Certificate	0
6734381	6734352	Store SQL field as a variable?	firstName = (string) _check.ExecuteScalar()	0
1347253	1347225	C# - Writing a log using a textbox	textBox1.Text +=  "new Log Message" + Environment.NewLine;	0
24778865	24778571	ToggleSwitch in the WP8	xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"\n         <toolkit:ToggleSwitch x:Name="ToggleSwitch" Header="Toggle Switch" IsChecked="false" Content="Content Goes here" Checked="switch_Checked" Unchecked="switch_Unchecked"/>	0
15785410	15785287	Dynamically changing multiple check boxes ID with C#	for (int i = 1; i < some_number; i++) \n{    \n    Control myControl = FindControl("CheckBox" + i.ToString());\n\n    if(myControl != null && myControl.GetType() == typeof(CheckBox)) \n    {\n        ((CheckBox)myControl).ID = "chckbx_" + i.ToString();\n        ((CheckBox)myControl).CssClass = "newClass";\n    }\n}	0
6445150	6445125	how to overwrite data in a txt file?	using (StreamWriter newTask = new StreamWriter("test.txt", false)){ \n        newTask.WriteLine(name[i].ToString());\n}	0
11456592	11456440	How to resize a bitmap image in C# without blending or filtering?	g.InterpolationMode = InterpolationMode.NearestNeighbor;	0
6258029	6257900	Little help with XLinq	XNamespace ns = "http://schemas.microsoft.com/ado/2007/08/dataservices";\nvar elements = xmlDoc.Descendants(ns + "element");	0
20970098	20969257	How to read data from oracle stored procedure value into dropdownlist in asp.net	con.Open();\nOracleCommand cmd = new OracleCommand("Frm_Dealer_list_Prc_2_4", con);\ncmd.Parameters.Add("DlrID", OracleType.Cursor).Direction = ParameterDirection.Output;\nDataSet ds = new DataSet();\nOracleDataAdapter da = new OracleDataAdapter();\nda.SelectCommand = cmd;\nda.Fill(ds);\ncomboBox1.DataSource = ds.Tables[0];\ncomboBox1.ValueMember = ds.Tables[0].Columns["DlrCODE"];\ncomboBox1.DisplayMember = ds.Tables[0].Columns["DlrNAME"];\ncomboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;	0
27820373	27820312	Trim a string in c# to go from this = 1:"Transmitters" to this = Transmitters	str = str.Trim('1',':','"');	0
20802919	19963570	How to combine more than one field in a column in DevExpress MVC?	settings.Columns.Add(c =>\n{\n    c.Caption = "Nurse Name";\n    c.SetDataItemTemplateContent(t =>\n    {\n        Html.DevExpress().Label(\n            l => {\n                l.Text = String.Format("{0} {1}", DataBinder.Eval(t.DataItem, "NurseFirstName"), DataBinder.Eval(t.DataItem, "NurseLastName"));\n            }).Render();\n    });\n});	0
1089336	1076964	How To Add A SyndicationElementExtension To A SyndicationItem	feed.ElementExtensions.Add(new XElement("xElementExtension",\n        new XElement("Key", new XAttribute("attr1", "someValue"), "Z"),\n        new XElement("Value", new XAttribute("attr1", "someValue"), \n        "15")).CreateReader());	0
8728900	8725407	C# program to replicate slide content in one .pptx file to another one	Dim oSh as Shape \nFor Each oSh in oSldSource.Shapes\n  .Copy\n  oSldTarget.Shapes.Paste\nNext	0
23514822	23514762	How to declare array of strings with string index?	public Dictionary<string, string> s;	0
24912097	24885666	How to use cloudinary url2png within asp.net web application	cloudinary.Api.UrlImgUp\n  .Type("url2png")\n  .Transform(new Transformation().Crop("fill").Width(150).Height(200).Gravity("north"))\n  .Signed(true)\n  .BuildUrl("http://en.wikipedia.org/wiki/Jpg");	0
21007310	20990509	How can a component provide other components?	builder.Register(c => new SourceDirectoryWrapper { \n        Directory = c.Resolve<IConfiguration>().SourceDirectory \n    });\n\nbuilder.Register(c => new TargetDirectoryWrapper { \n        Directory = c.Resolve<IConfiguration>().SourceDirectory \n    });	0
21832012	21831963	How to find the position(not Id) of an Item in a sorted Linq list	int index = ItemList.FindIndex(item => item.Id== mainItem.Id);	0
1386819	1386797	C# Access Modifiers with Inheritance	public class ReadUserInfo : UserInfo\n{\n    internal ReadUserInfo()\n    {\n    }\n    new public int ID { get; internal set; }\n    new internal string Password { get; set; }\n    new public string Username { get; internal set; }\n}	0
7914360	7914292	Where to place 'Type' specific functions whilst using a generic repository	public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository\n{\n    public CustomerRepository(ObjectContext context) : base(context) { }\n\n    public IList<Customer> NewlySubscribed()\n    {\n        var lastMonth = DateTime.Now.Date.AddMonths(-1);\n\n        return GetQuery().Where(c => c.Inserted >= lastMonth)\n        .ToList();\n    }\n\n    public Customer FindByName(string firstname, string lastname)\n    {\n        return GetQuery().Where(c => c.Firstname == firstname && c.Lastname == lastname).FirstOrDefault();\n    }\n}	0
27156528	27156341	Sorting using a custom alphabet order	public class CustomSorter : IComparer\n{\n    public int Compare(object x, object y)\n    {\n        var chars = "YNSD";\n        if (chars.IndexOf((char)x) < chars.IndexOf((char)y))\n            return -1;\n        return chars.IndexOf((char)x) > chars.IndexOf((char)y) ? 1 : 0; \n    }\n}	0
8595448	8595394	Iterating through c# array & placing objects sequentially into other arrays	var workArrays = new[] { \n    threadOneWork,\n    threadTwoWork,\n    threadThreeWork,\n    threadFourWork, \n};\n\nfor(int i=0; i<routingData.Length; i++) {\n    workArrays[i%4][i/4] = routingData[i];\n}	0
635667	635479	Using Rhino Mocks how can I set a property of a parameter for a Mocked method	[TestMethod]\n    public void Should_update_foo_to_active_inside_of_repository()\n    {\n        // arrange\n        var repo = MockRepository.GenerateMock<IRepository>();\n        var foo = new Foo() { ID = 1, IsActive = false };\n        var target = new Presenter(repo);\n        repo.Expect(x => x.ActivateFoo(foo)).\n            Do(new ActivateFooDelegate(ActivateFooDelegateInstance));\n        // act\n        target.Activate(foo);\n\n        // assert\n        Assert.IsTrue(foo.IsActive);\n        repo.VerifyAllExpectations();\n    }\n\n    private delegate bool ActivateFooDelegate(Foo f);\n\n    public bool ActivateFooDelegateInstance(Foo f)\n    {\n        f.IsActive = true;\n        return f.IsActive;\n    }	0
10806803	10760729	Windows service status stays at starting for ever even when it has actually started	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.ServiceProcess;\nusing System.Text;\nusing IndexLoader;\nusing System.Threading;\n\nnamespace myNameSpace\n{\n    public partial class LoaderService : ServiceBase\n    {\n        Thread newThread;\n        public LoaderService()\n        {\n            InitializeComponent();\n        }\n\n        protected override void OnStart(string[] args)\n        {\n\n            Loader loader = new Loader();\n\n            ThreadStart threadDelegate = new ThreadStart(loader.StartProcess);\n            newThread = new Thread(threadDelegate);\n            newThread.Start();\n\n        }\n\n        protected override void OnStop()\n        {\n            if ((newThread != null) && (newThread.IsAlive))\n            {\n\n\n                Thread.Sleep(5000);\n                newThread.Abort();\n\n            }\n        }\n    }\n}	0
779577	778601	How can I keep a Button/TextBox/etc in session?	public partial class MainControl : UserControl\n{\n    private Button myButtonToKeepAroundAllTheTime;\n\n    protected void TriggerButton_Click(object sender, EventArgs e)\n    {\n        myButtonToKeepAroundAllTheTime = new Button()\n        {\n            Content = "Click Me",\n            Height = 20\n        };\n    }\n}	0
4614152	4614014	How to view changes in EF-CodeFirst before they are committed?	public ObjectContext UnderlyingContext\n{ \n    get\n    {\n        return ((IObjectContextAdapter)this).ObjectContext;\n    }\n}	0
12982147	12733812	Export Data To Excel Sheet Which Already Contains Some Predefined Data And Send As Email Attachment	EmailMessage msg = new EmailMessage();\n    FileStream fs = new FileStream(@"c:\Test.xls", FileMode.OpenOrCreate);  \n    Exporter.WriteXls(fs);\n    msg.AddAttachment("c:\Test.xls");\n    msg.Send();\n    fs.Close();	0
18609693	18609184	DataSet, SqlDataAdapter, Multiple select returns one table	DataSet ds = new DataSet();\n\nSqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);\n\nString qry="SELECT topic_ID,topic_title FROM FPL2012_TOPIC WHERE topic_isEnabled = 1; SELECT itemExplanationType_ID, itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE ";\n\nSqlDataAdapter da = new SqlDataAdapter(qry, connection);\n\nda.Fill(ds)\n\ntopicDropDownList.DataValueField = "topic_ID";\ntopicDropDownList.DataTextField = "topic_title";\ntopicDropDownList.DataSource = ds.Tables[0];\ntopicDropDownList.DataBind();\n\nexplanationTypeDropDownList.DataValueField = "itemExplanationType_ID";\nexplanationTypeDropDownList.DataTextField = "itemExplanationType_type";\nexplanationTypeDropDownList.DataSource = ds.Tables[1];\nexplanationTypeDropDownList.DataBind();\n\nconnection.Close();	0
16287664	16287566	Regex to extract data on some lines while discarding others	static void Main(string[] args)\n{\n    string query = \n@"CREATE TABLE dbo.t_MyType\n(\n    ID INTEGER PRIMARY KEY IDENTITY,\n    TypeName VARCHAR(16) NOT NULL\n)\nCREATE UNIQUE INDEX IndexMyType ON dbo.t_MyType (TypeName)\n\nCREATE TABLE dbo.t_MyType2\n(\n    ID INTEGER PRIMARY KEY IDENTITY,\n    TypeName VARCHAR(16) NOT NULL\n)\nCREATE UNIQUE INDEX IndexMyType ON dbo.t_MyType2 (TypeName)";\n\n    string matchString = @"CREATE TABLE ([\w\.]+)";\n\n\n    var matches = Regex.Matches(query, matchString);\n\n    StringBuilder sb = new StringBuilder();\n\n    foreach (Match match in matches)\n    {\n        sb.AppendFormat("GRANT SELECT ON {0} TO db_read", match.Groups[1]).AppendLine();\n    }\n\n    Console.WriteLine(sb.ToString());\n\n    Console.ReadLine();\n\n}	0
5475652	5470963	How to get the mobile number and work number from iPhone contacts using MonoTouch?	IEnumerable<ABMultiValueEntry<string>> workPhoneEntries = person.GetPhones()\n        .Where(p => p.Label == ABLabel.Work);\nIEnumerable<string> workNumbers = workPhoneEntries.Select(p => p.Value);	0
26075753	26074817	Excel column is clicked in VSTO	Worksheet.SelectionChange	0
15676176	15676153	Replacing more than one line breaks by only one line break	clearstring = Regex.Replace(clearstring, @"(\r\n)+", "\r\n\r\n", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);	0
2300273	2300257	How to put data into clipboard on a Windows Mobile device written in .NET?	Clipboard.SetDataObject()	0
13201113	13201045	Linq and work with Datetime?	context.Ads.Where(c => c.PublishedDate.HasValue && c.EndDate.HasValue && c.AdStatusMail.Where(b => b.StatusKey != (int)AdStatusMailKey.EndedRemainder && b.StatusKey != (int)AdStatusMailKey.MiddleRemainder).Count() < 1)\n           .AsEnumerable()\n           .Where (c => c.EndDate.Value.AddTicks(c.PublishedDate.Value.Ticks) > currentTime)\n           .ToList();	0
5728238	5728092	Extracting specific data from a file	using (StreamReader sr = new StreamReader("TabDelimited.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          int idx = line.IndexOf(' ');\n          if (idx < 0)\n             continue;\n\n          // get the uid\n          string uid = line.Substring(0, idx - 1);\n      }\n }	0
21872263	21871630	Clean way of passing parameters	public EmployeeProcessOutput RetrieveEmployee(EmployeeProcessInput input)\n{     \n      var employee = input.Employee;\n      if (input.EmployeeId == null)\n          CreateEmployee(ref employee);\n\n      return new EmployeeProcessOutput\n            {\n                Employee = employee,\n                State = "Stored" \n            };\n}\n\nprivate void CreateEmployee(ref Employee employee)\n{\n      //Call a service to create an employee in the system using the employee \n      //info such as name, address etc and will generate an id and other \n      //employee info.\n      var output = Service(employee)\n      employee = output.Employee;\n }	0
4548725	4548513	How do i copy files from a referenced assembly's structure to the local structure	.ribbonGroupLeft {\n    width: 3px;\n    height: 85px;\n    background-image: url(<%=WebResource("MyAssembly.images.RibbonGroupLeft.png") %>);\n    background-repeat: no-repeat;\n    overflow: hidden;\n    margin: 0px 0px 0px 0px;\n    padding: 0px 0px 0px 0px;\n}	0
31158868	31156713	?# read xml datatable in datatable	XElement xmlDoc = XElement.Load("SO-Question.xml"); // initialize your .xml document to read from\nforeach (var handle in xmlDoc.Elements().Where(e => e.Name.ToString().StartsWith("Dev"))) // traverse each node of the .xml doc, based on a match condition, here : every node that starts with "Dev"\n{\n    // retrieve the value of every Element in the Node (mark the nestings)\n    var devName = handle.Name;\n    var port = handle.Element("port").Value;\n    var addrs = handle.Element("addrs").Value;\n    var addr = handle.Element("SupplyVoltageMeasurement").Element("addr").Value;\n    var channel = handle.Element("SupplyVoltageMeasurement").Element("channel").Value;\n}	0
3606447	3604708	Launching ClickOnce App from C#	string shortcutName = \n  string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),\n  "\\", PublisherName, "\\", ProductName, ".appref-ms");\nprocess.Start(shortcutName);	0
28448953	28433623	Trying to implement grouping in IEnumerable to stream from Database	foreach (COM_GenericTransactionItemsDS.COM_GenericTransactionItemsRow row in com_GenericTransactionItemsDS.COM_GenericTransactionItems.Rows)\n{\n  lastUID = row.UID;\n  COM_GenericTransactionItemsDS.COM_GenericTransactionItemsRow newRow = com_GenericTransactionItemsDS.COM_GenericTransactionItems.NewCOM_GenericTransactionItemsRow();\n  newRow.ItemArray = row.ItemArray;\n  yield return newRow;\n}	0
268353	268344	C#: Could anyone give me good example on how anchoring controls at runtime is done?	textBox1.Multiline = true;\n        textBox1.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom;	0
13760696	13736485	Creating Pivot Item in Runtime, with ListBoxWithCheckBoxes	private void MyPivotItem_Loaded(object sender, RoutedEventArgs e)\n{\n    MyPivotItem pivotItem = sender as MyPivotItem;\n    pivotItem.myListBox.IsInChooseState = true;\n}	0
22034329	22034275	How do I add the graph control in the Visual Studio toolbox	System.Web.UI.DataVisualization.Charting\n\nSystem.Windows.Forms.DataVisualization.Charting	0
561119	561111	how do I copy a file that is being used by another process in C#	using (var file = new FileStream(\n   @"C:\path\to\file.txt", \n   FileMode.Open, \n   FileAcces.Read, \n   FileShare.Read) {\n  // ...\n}	0
29941149	29941002	Telephone number validation	public static bool validTelephoneNo(string telNo)\n{\n    return Regex.Match(telNo, @"^\+\d{1,7}$").Success;\n}	0
4047909	4046058	Wait for HttpWebRequest.BeginGetResponse to finish in Windows Phone 7	Dispatcher.BeginInvoke( () => { /* your UI update code */ } )	0
31494419	31487203	How to compare element values between two Ordered Dictionaries	DictionaryEntry card1 = player1.Hand.Cast<DictionaryEntry>().ElementAt(0);	0
21880262	21880081	Cast Int Array to Enum Flags	var tt = (DataFiat)selected.Aggregate((i, t) => i | t);	0
13785684	13468264	filtering datagrid using combobox	private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)\n        {\n\n            try\n            {\n                if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)\n                {\n\n                    tbl_DestinationData.DataSource = dt;\n                }\n\n                else\n                {\n                    ((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";\n\n                }\n\n\n\n            }\n            catch (Exception )\n            {\n                throw;\n            }\n\n    }	0
1944776	1944765	Need SELECT WHERE COUNT = INT in LINQ	where s.Count()==8	0
33233775	33232939	Export DataGridVeiw to excel in C# with cell background colors	Range range = \n            oSheet.get_Range("A" + redRows.ToString(), "J"\n                                    + redRows.ToString());\n\n    range.Cells.Interior.Color = System.Drawing.Color.Red;	0
11426948	11426461	Sort a List in C# by a Columncollection	var orderesProp = from i in prop\n                          select new { i = i, o = columns.FirstOrDefault(x => i.Name == x.Name) } into merge\n                          orderby merge.o == null ? int.MaxValue : merge.o.DisplayIndex\n                          select merge.i;	0
11885745	11885547	validating web site credentials	// create a "principal context" - e.g. your domain (could be machine, too) \n\nusing(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")) \n{     \n\n// validate the credentials    \n bool isValid = pc.ValidateCredentials("myuser", "mypassword"); \n}	0
24085003	24084129	Read Image From Excel File Using NPOI	var lst = originalWorkbook.GetAllPictures();\nfor (int i = 0; i < lst.Count; i++)\n{\n    var pic = (XSSFPictureData) lst[i];\n    byte[] data = pic.Data;\n    BinaryWriter writer = new BinaryWriter(File.OpenWrite(String.Format("{0}.jpeg", i)));\n    writer.Write(data);\n    writer.Flush();\n    writer.Close();\n}	0
26130065	26129951	Average a list of Drawing.Point	var avgPoint = new System.Drawing.Point \n{\n    X = (int)Math.Round(MyList.Average(p => p.X)),\n    Y = (int)Math.Round(MyList.Average(p => p.Y))\n};	0
32550635	32550440	Updating data of selected row in datagridview	using (var connect = sqlcon.getConnection())\n{\n    string updateRecordCmd = String.Format( "UPDATE pending SET status='1' WHERE ID={0}",row.Cells[0].Value.toString());  \n    using (SqlCommand cmd = new SqlCommand(updateRecordCmd))\n    {\n        cmd.Connection = connect;\n        connect.Open();\n        //cmd.ExecuteNonQuery();\n        //connect.Close();\n\n    }\n}	0
26186199	26186164	How to implement Property Change Notification	private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")\n    {\n        var handler = PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }	0
26578573	26578537	How can i keep write text in the code in a new line?	toolTip1.SetToolTip(this.checkBox2, "Create automatic animated gif " +\n                                    "after rain event " + \n                                    "text to add");	0
31974836	31974476	XmlTextReader for XDocument source	var xDoc = new XDocument(...);\nvar textReader = new XmlTextReader(new System.IO.StringReader(xDoc.ToString()));	0
10583220	10583170	How can I get the next month End Date from the given Date	int quarter = (int)Math.Ceiling(qrtrDate.Month / 3.0);\nint lastMonthInQuarter = 3 * quarter;\nDateTime lastDayOfQuarter = new DateTime(qrtrDate.Year, lastMonthInQuarter, DateTime.DaysInMonth(qrtrDate.Year, lastMonthInQuarter));	0
31428432	31137374	Active Directory Authentication Library with Windows Universal App	var p = new PlatformParameters(PromptBehavior.Always, false); \nAuthenticationResult result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectURI, p);	0
5201810	5201770	Need help converting PHP to C#	Dictionary<string, TComposite>	0
12950282	12950230	Parsing json value from string	var errors = o["results"][0];\nstring errorMessage = (string)errors["error"];	0
13723089	13722987	How I can use a Image as Background for my html mail in ASP.NET	System.Net.Mail.MailMessage Mensaje = new System.Net.Mail.MailMessage("mail@host.com",DireccionCorreo);\n\nSystem.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(Body, null, "text/html");\n\n\nSystem.Net.Mail.LinkedResource logo = new System.Net.Mail.LinkedResource("logoimage.jpg");\nlogo.ContentId = "logoimage";\nhtmlView.LinkedResources.Add(logo);\n\nSystem.Net.Mail.LinkedResource logoExchange = new System.Net.Mail.LinkedResource("logoexchange.png");\nlogoExchange.ContentId = "logoexchange";\nhtmlView.LinkedResources.Add(logoExchange);\n\nSystem.Net.Mail.LinkedResource tut1 = new System.Net.Mail.LinkedResource(Application.StartupPath + "/OutlookGuide/tut1.jpg");\ntut1 .ContentId = "tut1";\nhtmlView.LinkedResources.Add(tut1 );\n\nSystem.Net.Mail.LinkedResource tut2 = new   System.Net.Mail.LinkedResource(Application.StartupPath + "/OutlookGuide/tut2.jpg");\ntut2.ContentId = "tut2";\nhtmlView.LinkedResources.Add(tut2);\n\n\nMensaje.AlternateViews.Add(htmlView);	0
2641693	2634449	Is there a way to pass a parameter to a command through a keybinding done in code?	InputBindings.Add(new KeyBinding(ChangeToRepositoryCommand, new KeyGesture(Key.F1)) { CommandParameter = 0 });	0
34474919	34474734	asp.net fileupload control, uploading file to ftp	static string yourSuperSecretDirectory = @"C:\ApplicationName\Uploads";\nprotected void btnUpload_Click(object sender, EventArgs e)\n{\n    if(FileUploadControl.HasFile)\n    {\n        string filename = Path.Combine(yourSuperSecretDirectory, FileUploadControl.FileName);\n        FileUploadControl.SaveAs(filename); //actually save/upload the file\n\n        string temp = ftp + ftpFolder + filename\n\n        try\n        {\n            using (WebClient client = new WebClient())\n            {\n                client.Credentials = new NetworkCredential(loginName, password);\n                client.UploadFile(temp, "STOR", FileUploadControl.FileName); // ???\n            }\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.StackTrace);\n        }\n    }\n}	0
23696582	23696502	How can i get specific file name from all subdirectotires?	Directory.EnumerateFiles(mainPath, "animated*", SearchOption.AllDirectories);	0
4220500	4220135	WCF - How to send GUIDs efficiently (not as strings)	[DataContract(Namespace = Constants.OrgStructureNamespace)]\npublic class EntityInfo : IExtensibleDataObject\n{\n    public Guid EntityID { get; set; }\n\n    [DataMember(Name="EntityID")]\n    byte[] EntityIDBytes\n    {\n        get { return this.EntityID.ToByteArray(); }\n        set { this.EntityID = new Guid(value); }\n    }\n\n    [DataMember]\n    public EntityType EntityType { get; set; }\n    [DataMember]\n    public IList<Guid> EntityVersions { get; set; }\n    [DataMember]\n    public IList<Guid> OrganisationStructures { get; set; }\n\n    #region IExtensibleDataObject Members\n    // ...\n    #endregion\n}	0
18010092	18009634	OrderByDescending with Skip and Take in LINQ shows error	public virtual IQueryable<TPoco> GetSortedPageList<TSortKey>(Expression<Func<TPoco, bool>>    predicate,\n        Expression<Func<TPoco, TSortKey>> sortBy,\n        bool descending,\n        int skipRecords, int takeRecords) {\n        if (!descending) {\n            return Context.Set<TPoco>()\n                 .Where<TPoco> predicate)\n                .OrderBy(sortBy)\n                .Skip(skipRecords)\n                .Take(takeRecords);\n        }\n        return\n            Context.Set<TPoco>()\n                .Where<TPoco>(predicate)\n                .OrderByDescending(sortBy)\n                .Skip(skipRecords)\n                .Take(takeRecords);\n    }	0
14135713	14135467	Linq to Entities - JOIN a list with an entity set	var query = listName.Join(repository.GetQuery<MyCustomType>(),\n list => list.CustomTypeId,\n customType => customType.id,\n (list, customType) => new { l = list, c = customType } );	0
860661	860652	C# Keywords as a variable	string @string = "";	0
23435672	23435417	Set value in 2D array fom keyboard	data[intCoordinates[0],intCoordinates[1]]	0
32957432	32955666	Keeping track of votes in a c# Windows Form app	public partial class Form1 : Form \n{ \n\n    private int Yes_Tally = 0;\n    private int No_Tally = 0;\n\n    public Form1() \n    { \n        InitializeComponent(); \n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        UpdateTally();\n    }\n\n    private void Eyes1_Click(object sender, EventArgs e)\n    {\n        Yes_Tally++;\n        UpdateTally();\n    }\n\n    private void Eyes2_Click(object sender, EventArgs e)\n    {\n        No_Tally++;\n        UpdateTally();\n    }\n\n    private void UpdateTally()\n    {\n        lblTally.Text = String.Format("Yes: {0}, No: {1}", Yes_Tally, No_Tally);\n    }\n\n}	0
6250371	6250284	Send JSON data to highcharts pie from asp.net MVC controller in C#	class SimpleClass{\n       public int x{set; get;}\n       public double y{set; get;}\n   } \n\n    var results = new List<SimpleClass>();\n    results.Add(new SimpleClass{x="test3", y=42});        \n    results.Add(new SimpleClass{x="test2", y=99});	0
2659878	2659709	Receiving an object in a unmanaged callback function	void MyCallback(IntPtr anObject)\n{\n    GCHandle gch = GCHandle.FromIntPtr(anObject);\n    MyClass myObject = (MyClass)gch.Target;\n}	0
8309495	8308772	MonoTouch can't open new window from AccessoryButtonTapped	public class MyTableSource : UITableViewSource\n{\n\n    private BasisViewController controller;\n    public MyTableSource(BasisViewController parentController)\n    {\n        this.controller = parentController;\n    }\n\n    //use like this in a method:\n    //this.controller.NavigationController.PushViewController(opskrift, true);\n}	0
31593640	31593471	BinaryFormatter OptionalField with ISerializable	foreach (SerializationEntry entry in info) \n    { \n        switch (entry.Name) \n        { \n            case "firstname": \n                Firstname = (string)entry.Value; \n            break; \n            case "secondname": \n                Secondname = (string)entry.Value;\n            break; \n        }\n    }	0
19074318	19074236	need help on regex or string replace	var regex = @"\[\[REQUEST_Data\]\](\n|\r|\r\n|.)*\[\[\/REQUEST_Data\]\]"\nvar replaced = Regex.Replace(input, regex, "");	0
31547873	31545957	How to get the Language ID of Word dynamically	oCustDict.LanguageID = (Microsoft.Office.Interop.Word.WdLanguageID)WordApp.Language;	0
7243062	7242928	change ordering of dropdownlist	ListItem lioak = new ListItem("Oak Pre-finished", "pre-finished oak");\ndd1Finish.Items.Insert(0,lioak);	0
13286693	13281914	How to update a single graph in chart from multiple async threads?	Parallel.ForEach(list, a=>  \n{\n    // do some operation \n    chart1.Dispatcher.Invoke(new Action(() => { chart1.Series[0].Points.AddXY(x, y); }));\n});	0
6094733	6094664	How to cast this date and save to database	DateTime myDate = Convert.ToDateTime("Thu, 18 Mar 2004 14:52:56-07:00");	0
672526	672506	How can I programatically limit access to a Webservice?	[WebMethod]\npublic bool IsAlive()\n{\n     string callingAddress = HttpContext.Current.Request.UserHostAddress;\n     return (callingAddress == allowedAddress);\n}	0
15907976	15571047	Unable to create a constant value of type 'Anonymous type'	var t2s = _ent.Products.Where(t => t.Row_Num == 1).Select(t =>t.ProductID);\n\nvar _query = _ent.brands.Where(b => t2s.Contains(b.Prod_ID));	0
10678328	10675451	IObservable of keys pressed	IObservable<System.ConsoleKeyInfo> keys =\n            Observable\n                .Defer(() =>\n                    Observable\n                        .Start(() =>\n                            Console.ReadKey()))\n                .Repeat();	0
26040501	26040424	accessing a whole row in an array at once	List<int> extract = Enumerable.Range(0, example.GetLength(1))\n       .Select(x => example[0,x])\n       .ToList();	0
23960347	23960295	keeping an instance of an object avaliable throughout an entire application	public class MyGlobalClass\n{\n    private Lazy<MyGlobalClass> _instance = new Lazy<MyGlobalClass>();\n    public static MyGlobalClass Instance { get { return _instance.Value; } }\n\n    //Whatever else, accessed by MyGlobalClass.Instance.<Whatever>\n}	0
30405583	30405512	Is there a dumb "all" in linq that evaluate all element?	var allValid = array.Aggregate(true, (acc, o) => acc & Validate(o));	0
17658813	17658772	Draw power grid network topology	System.Drawing	0
206829	206775	How do I get the URLs from any tab in any open browser	float GetCalcResult(void)\n{\n    float retval = 0.0f;\n\n    HWND calc= FindWindow("SciCalc", "Calculator");\n    if (calc == NULL) {\n        calc= FindWindow("Calc", "Calculator");\n    }\n    if (calc == NULL) {\n        MessageBox(NULL, "calculator not found", "Error", MB_OK);\n        return 0.0f;\n    }\n    HWND calcEdit = FindWindowEx(calc, 0, "Edit", NULL);\n    if (calcEdit == NULL) {\n        MessageBox(NULL, "error finding calc edit box", "Error", MB_OK);\n        return 0.0f;\n    }\n\n    long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1;\n    char* temp = (char*) malloc(len);\n    SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp);\n    retval = atof(temp);\n    free(temp);\n\n    return retval;\n}	0
21576436	21576267	XML element - Formatting Tag	new XElement("InstdAmt", new XAttribute("Ccy", "Eur"), "1000");	0
4337065	4336783	How to emulate Vector3.TransformNormal	public Vector3 TransformNormal(Vector3 normal, Matrix matrix)\n{    \n    return new Vector3\n    {\n        X = normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31,\n        Y = normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32,\n        Z = normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33\n    };\n}	0
5678626	5678415	Unable to assign a Dataset to ReportDataSource in C#	LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("dsProductReorder_dtProductReorder", d.Tables[0]));	0
28906219	28902589	How to Unshelve from TFS without preserving shelveset?	Workspace.Unshelve(shelveName, versionControlServer.AuthorizedUser);\nversionControlServer.DeleteShelveset(shelveName);	0
24488593	24488448	Linq retrieve a summary list in a query	var query = \n    from pair in \n    (from p in db.persons\n    join l in db.personLanguages on p.personId equals l.personId\n    select new {p, l})\ngroup pair by pair.p into g\nselect new {Person = g.Key , Langs = string.Join(" " ,g.Select(gr=> gr.l.name).ToArray())}	0
3909544	3909520	How to manage custom fonts in web application (system.drawing)	PrivateFontCollection collection = new PrivateFontCollection();\n    // Add the custom font families. \n    // (Alternatively use AddMemoryFont if you have the font in memory, retrieved from a database).\n    collection.AddFontFile(@"E:\Downloads\actest.ttf");\n    using (var g = Graphics.FromImage(bm))\n    {\n        // Create a font instance based on one of the font families in the PrivateFontCollection\n        Font f = new Font(collection.Families.First(), 16);\n        g.DrawString("Hello fonts", f, Brushes.White, 50, 50);\n    }	0
2619145	2618998	Declare private static members in F#?	namespace CsFsTest\n\nopen System\n\ntype Test1 =\n    val mutable private greet : string\n    [<DefaultValue>]\n    val mutable public a : int\n    [<DefaultValue>]\n    static val mutable private vv : int\n\n    static member v with get() = Test1.vv \n                    and set(x) = Test1.vv <- x\n\n    member this.b = this.a*2\n    static member hi(greet:string) = Console.WriteLine("Hi {0}", greet)\n    member this.hi() = Console.WriteLine("Hi {0} #{1}", this.greet, Test1.v)\n\n    new() = { greet = "User" }\n    new(name : string) = { greet = name }\n\n    member this.NotSTATIC() = Test1.v	0
31191766	31191054	Remove elements from two lists based on another list	for (var i = list1.Count - 1; i >= 0; i--)\n{\n    if (list3.Contains(list1[i]))\n    {\n        list1.RemoveAt(i);\n        list2.RemoveAt(i);\n    }\n}	0
6147209	6146595	How to access created enum in C# from code behind to aspx file	namespace Test\n{\n    public enum MYENUM\n    {\n        One,\n        Two\n    }\n}\n\n<% Response.Write(Test.MYENUM.One.ToString()); %>	0
24092928	24092652	WPF Dictionary using DataTemplates on a DataTemplateSelector always having a null value for the key	public class NodePropertyGridTemplateSelector : DataTemplateSelector\n{\n    private readonly Dictionary<string, DataTemplate> _dictionary = new Dictionary<string, DataTemplate>();\n\n    public override DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)\n    {\n        if (item != null)\n        {\n            DataTemplate dt;\n            if (_dictionary.TryGetValue("PageLoaded", out dt))\n                return dt;\n        }\n        return base.SelectTemplate(item, container);\n    }\n\n    public DataTemplate PageLoadedDataTemplate\n    {\n        get\n        {\n            DataTemplate dt;\n            return _dictionary.TryGetValue("PageLoaded", out dt) ? dt : null;\n        }\n\n        set\n        {\n            if (value == null) _dictionary.Remove("PageLoaded");\n            else _dictionary["PageLoaded"] = value;\n        }\n    }\n}	0
6136242	6136006	Showing single dialog from multiple threads	private DialogResult threadedDialogResult;\nprivate bool dialogShown;\n\npublic string Show(string key, Action<DialogBuilder> action)\n{\n    lock (this) //now 4 threads are waiting here\n    {\n        if (!dialogShown)\n        {\n            //marshal the dialog to the UI thread  \n            return _dispatcher.Send(() => { dialogShown = true; this.threadedDialogResult = new MyDialogForm().ShowDialog(); });\n        }\n        else\n        {\n            // Use the cached dialog result as we know it was shown\n            return threadedDialogResult.ToString();\n        }\n    }\n}	0
6349771	6348339	C# Trying to access the location of a panel's parent	//Code for the main form:\nnamespace WinAlignTest {\n    public partial class Form1 : Form {\n        public Form1() {\n            InitializeComponent();\n            tabControl1.TabPages[0].Controls.Add(new SomeApplication());\n        }\n    }\n}\n\n//Code that shows the option window\nnamespace WinAlignTest {\n    public partial class SomeApplication : UserControl {\n        private ApplicationOptions Options;\n        public SomeApplication() {\n            InitializeComponent();\n            Options = new ApplicationOptions();\n        }\n\n        private void button1_Click(object sender, EventArgs e) {\n            Options.Show();\n\n            // You might need to use PointToScreen here\n            Options.Location = this.Location;\n        }\n    }\n}	0
14883015	14882532	deserialize the following json response in c#	JObject jObject = JObject.Parse(@"{\n'legend_size': 1,\n'data': {\n    'series': [\n        '2013-02-05', '2013-02-06', '2013-02-07', '2013-02-08', '2013-02-09', '2013-02-10', '2013-02-11', '2013-02-12', '2013-02-13', '2013-02-14'\n    ],\n    'values': {\n        'CampaignHit': {\n            '2013-02-14': 0,\n            '2013-02-13': 0,\n            '2013-02-12': 0,\n            '2013-02-11': 0,\n            '2013-02-10': 0,\n            '2013-02-08': 11,\n            '2013-02-05': 0,\n            '2013-02-07': 14,\n            '2013-02-06': 0,\n            '2013-02-09': 0\n        }\n    }\n}\n}");\n\nvar  campaignHit = jObject["data"]["values"]["CampaignHit"];\n\nDictionary<string,int> campaignHitDic = new Dictionary<string,int>();\n\nforeach(JProperty c in campaignHit){\ncampaignHitDic.Add(c.Name,(int)c.Value);\n}	0
8623328	8623177	Google Search Position Regex	string lookup = "(<h3 class=\"r\"><a href=\")(\\w+[a-zA-Z0-9.\\-?=/]*)";	0
22098868	22098665	How to send a database that is being used by another process to email c#	Stream stream = File.Open("DataBase\\USBrowser.accdb", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n            StreamReader streamReader = new StreamReader(stream);	0
21354199	21354150	Reading File as hexadecimal	foreach (string line in File.ReadLines(filename))\n{\n    string[] part = line.Split(',');\n    // Deal with each part. Consider using Convert.ToInt32(part, 16)\n    // to parse a value as hex...\n}	0
24612166	24611311	How can I map a user-given string to an object property at runtime?	private void Input_ListTokens(string filterType, string filterValue)\n{\n IEnumerable<string> result = null;\n   Type t = typeof(IToken);\n   PropertyInfo f = t.GetProperty(filterType);\n   if (f!=null)\n            result = from t in Tokens\n                        where t.GetValue(t)== filterValue\n                        select t.ToString();\n}	0
8508941	8508688	Check to see if Day of Month exists between two DateTime, regardless of year	bool IsDateContained(DateTime startDate, DateTime endDate, int month, int day) {\n    bool retVal = false;\n    if (startDate < endDate) {\n        do {\n            if (startDate.Month == month && startDate.Day == day) {\n                retVal = true;\n                break;\n            }\n            startDate = startDate.AddDays(1);\n        } while (startDate < endDate);\n    } else {\n        //crazy world!!\n    }\n    return retVal;\n}	0
13698879	13698844	Generate RESX files from CSHTML	[Visual Studio Install Directory]\Common7\IDE\ItemTemplates\\n[CSharp | VisualBasic]\Web\MVC\CodeTemplates\	0
13238639	13238606	How MessageBox.Show make loop wait	MessageBox.Show()	0
4128298	4128263	Format a Social Security Number (SSN) as XXX-XX-XXXX from XXXXXXXXX	string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-");	0
14035199	14034898	calculate (complicated) array of decimal numbers in C#	double[] input = double[5]; //Pretend the user has entered these\nint[] counters = int[input.Length]; //One for each "dimension"\nList<double> sums = new List<double>();\n\nfor (int i = 0; i < counters.Length; i++)\n   counters[i] = -1; //The -1 value allows the process to begin with sum of single digits, then pairs, etc..\n\nwhile (true)\n{\n    double thisSum = 0;\n    //Apply counters\n    for (int i = 0; i < counters.Length; i++)\n    {\n        if (counters[i] == -1) continue; \n\n        thisSum += input[counters[i]];\n    }\n\n    //Increment counters\n    counters[0]++; //Increment at base\n    for (int i = 0; i < counters.Length; i++)\n    {\n        if (counters[i] >= counters.Length)\n        {\n            if (i == counters.Length - 1) //Check if this is the last dimension\n               return sums; //Exhausted all possible combinations\n\n            counters[i] = 0;\n            counters[i+1]++;\n        }\n        else\n           break;\n    }\n}	0
25102877	24991665	Organizing a solution, need tips	.entrypoint	0
24258519	24233266	how to select div class with same names?	ie.TextField(Find.ById("someid")) --> This will return first element which has 'someid' as id of the lement.\nie.TextField(Find.ById("someid") && Find.ByIndex(1)) --> This will return you the second element of 'someid'.	0
801058	801029	Get All Values of Enums	public enum Family\n    {\n        Brother,\n        Sister,\n        Father\n    }\n\n    public enum CarType\n    {\n        Volkswagen,\n        Ferrari,\n        BMW\n    }\n\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(GetEnumList<Family>());\n        Console.WriteLine(GetEnumList<Family>().First());\n        Console.ReadKey();\n    }\n\n    private static List<T> GetEnumList<T>()\n    {\n        T[] array = (T[])Enum.GetValues(typeof(T));\n        List<T> list = new List<T>(array);\n        return list;\n    }	0
20002895	20002833	Use linq query to display literal in repeater rather than database value C# web app	var linqQuery = from nn in interestList\n                ...\n                select new\n                {\n                    CaseNumber = nn.CaseNumber == 0 ?\n                        "All" :\n                        nn.CaseNumber.ToString(),\n                    ...\n                };	0
1309025	1309003	Converting from byte[] to string	for (int i = 0; i < b.Length; i++)\n{\n  byte curByte = b[i];\n\n  // Assuming that the first byte of a 2-byte character sequence will be 0\n  if (curByte != 0)\n  { \n    // This is a 1 byte number\n    Console.WriteLine(Convert.ToString(curByte));\n  }\n  else\n  { \n    // This is a 2 byte character. Print it out.\n    Console.WriteLine(Encoding.Unicode.GetString(b, i, 2));\n\n    // We consumed the next character as well, no need to deal with it\n    //  in the next round of the loop.\n    i++;\n  }\n}	0
27397599	27397550	LINQ expression to check against a collection and set a default value when the check fails	var item = msStatus.Find(m => m.Value == UserRequest.Status.ToString());\n\nif(item == null)\n{\n    // set selected item to New\n    msStatus.Find(m => m.Value == "New").Selected = true; \n}\nelse \n{\n    item.Selected = true;\n}	0
31693183	31692971	String spliting using ChunksUpto	var str =  "0009000A000B000C";\n\nvar splitgroup2 = ChunksUpto(str , 4);\n\npublic string[] ChunksUpTo(string str, int count)\n{\n   if(count == 0)\n      return null;\n\n   List<string> result = new List<string>();\n   int chunkCount = str.Length / count;\n   for(int i = 0; i < temp; i++)\n        result.Add(new string(str.Take(count).ToArray()))\n\n   return result.ToArray();\n}	0
18857353	15442169	OpenSearch Autocomplete with ASP.net	public object Get(string id)\n    {\n        List<ResultObject> resultValues = new List<ResultObject>();\n\n        foreach (string val in ***SQLQUERYRESULTS***)\n        {\n            test singleResult = new ResultObject();\n            singleResult.Name = val;\n            singleResult.Description = "Server";\n            singleResult.Url = "***CUSTOMURL***?ServerName=" + val;\n            resultValues.Add(singleResult);\n\n        }\n        var entities = resultValues;\n        var names = entities.Select(m => m.Name);\n        var description = entities.Select(m => m.Description);\n        var urls = entities.Select(m => m.Url);\n        var entitiesJson = new object[] { id, names, description, urls };\n\n        return entitiesJson;\n    }\n}\n\n\npublic class ResultObject\n{\n    public string Name { get; set; }\n    public string Description { get; set; }\n    public string Url { get; set; }\n\n}	0
7093668	7093628	How to pass a string to child form?	private string _hostname = "";\n\n...\n\npublic SiteForm(string hostname)\n{\n    _hostname = hostname;\n    InitializeComponent();\n}	0
11831778	11831329	Binary Search on the first element in a multiple dimensional array	// initialize the array and the indexes array\nvar a2D = new int[2][];\na2D[0] = new[] { 3, 14, 15, 92, 65, 35 }; // <-- your array (fake data here)\na2D[1] = Enumerable.Range(0, a2D[0].Length).ToArray(); // create the indexes row\n\n// sort the first row and the second one containing the indexes\nArray.Sort(a2D[0], a2D[1]);\n\n// now a2D array contains:\n//  row 0: 3, 14, 15, 35, 65, 92\n//  row 1: 0,  1,  2,  5,  4,  3\n\n// and you can perform binary search on the first row:\nint columnIndexOf35 = Array.BinarySearch(a2D[0], 35);\n// columnIndexOf35 = 3\n// \n// a2D[0][columnIndexOf35] = 35 <- value\n// a2D[1][columnIndexOf35] = 5  <- original index	0
1644686	1643213	Converting Byte received from the registry to String	RegistryKey key = Registry.Users.OpenSubKey(e.RegistryValueChangeData.KeyPath);\n\n            Byte[] byteValue = (Byte[])key.GetValue(e.RegistryValueChangeData.ValueName);\n\n            string stringValue = "";\n\n            for (int i = 0; i < byteValue.Length; i++)\n            {\n                stringValue += string.Format("{0:X2} ", byteValue[i]);\n            }	0
5625128	5625058	How do I retrieve attributes on properties in C#?	System.Reflection.MemberInfo info = typeof(Student).GetMembers()\n                                                   .First(p => p.Name== "Id");\nobject[] attributes = info.GetCustomAttributes(true);	0
20237074	20237007	How to populate a combo box based on the selection made from another combo box	if (ComboVehicleMake.SelectedValue != null && Convert.ToInt32(ComboVehicleMake.SelectedValue) == 27)\n    {\n        try\n        {\n        .......// bind the other combobox	0
10118852	10118812	Getting and setting defalut property value in c#	class Log {\n    public Log() {\n        LocationId = 1;\n    }\n\n    public int LocationId { set; get; }\n}	0
17998337	17998172	csv to datagridview in c# windows application	var lines = File.ReadAllLines("yourcsvfile.csv").Select(a => a.Split(',')).ToList();\n\n        foreach (string[] s in lines)\n        {\n            dataGridView1.Rows.Add(s[5], s[6], s[7]);\n        }	0
32746317	32746214	Open file with blank spaces in filename	...\n\nstring result = ...;\n\nresult = " \"" + result + " \"";\n\n...	0
6987248	6987125	Remove all the objects from a list that have the same value as any other Object from an other List. XNA	result = block.Positions.Except(block.Floor)	0
9070101	9070009	c# getting a sporadic results	double result = (m*(double)r.X) + b - (double)r.Y;\n\n  if ((result > -0.0001) && (result < 0.0001))\n     return 0.0;\n  else\n     return result;	0
12716689	12715738	Querying xml child elements with prefixed namespace using LINQ to XML	var data = XElement.Parse(theXml);  \n    XNamespace ns = "urn:com.foo.bar/GetResults";  \n    var result = data.Descendants(ns + "Result")\n                     .Elements()\n                     .Select(x => new KeyValuePair<string, string>(x.Name.LocalName, x.Value))\n                     .ToList();	0
3242454	3241114	Show Form with PInvoke	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\nusing Microsoft.VisualBasic.ApplicationServices;\n\nnamespace WindowsFormsApplication1 {\n    class Program : WindowsFormsApplicationBase {\n        [STAThread]\n        static void Main(string[] args) {\n            var prg = new Program();\n            prg.EnableVisualStyles = true;\n            prg.IsSingleInstance = true;\n            prg.MainForm = new Form1();\n            prg.Run(args);\n        }\n\n        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {\n            var main = this.MainForm as Form1;\n            main.WindowState = FormWindowState.Normal;\n            main.BringToFront();\n            // You could do something interesting with the command line arguments:\n            //foreach (var arg in e.CommandLine) {\n            //    main.OpenFile(arg);\n            //}\n        }\n    }\n}	0
12441600	12440352	Sum of groups in WPF	var groupSumsQuery = from model in myList\n                     group model by model.ModelName into modelGroup\n                     select new \n                         {\n                             Name = modelGroup.Key,\n                             Sum = modelGroup.Sum(model=>model.UnitCost)\n                         };\n\nforeach(var group in groupSumsQuery)\n{\n    Console.WriteLine("Total price for all {0}: {1}", group.Name, group.Sum);\n}	0
12625637	12625588	How can I serialize a Dictionary<string, object> to javascript?	public class PuntoMappa\n{\n    public string Lat { get; private set; }\n    public string Lng { get; private set; }\n\n    public PuntoMappa(string Lat, string Lng)\n    {\n        this.Lat = Lat;\n        this.Lng = Lng;\n    }\n}	0
7481665	7481084	Populate filter by union of years from 3 tables	ctx.AccountHeaders.GroupBy(x=>x.accountdate.Year).Select(x=>x.Key).Union(\n  ctx.AccountDocuments.GroupBy(x=>x.accountdate.Year).Select(x=>x.Key)).Union(\n     ctx.AccountNumbers.GroupBy(x=>x.accountdate.Year).Select(x=>x.Key));	0
15370990	14994812	Unable to find control in BottomPagerRow of GridView	/// <summary>\n/// Special method to handle the Drop down list value changing \n/// but ASP not accurately modifying the controls\n/// </summary>\nprivate void HandlePossibleBottomRowEvents()\n{\n    var page = associatedGridView.Page;\n    var request = page.Request;\n\n    var possibleCall = request.Form["__EventTarget"];\n    if (possibleCall != null)\n    {\n        if (possibleCall.Contains("pagerDDL"))\n        {\n            var newPageSize = request[possibleCall];\n            var newSize = int.Parse(newPageSize);\n            if (associatedGridView.PageSize != newSize)\n                UpdatePageSize(newSize);\n        }\n    }\n}	0
13018021	13017360	Setting individual entity properties based on list of entity properties	var bindingFlags = BindingFlags.Public | BindingFlags.Instance;\nvar blockProperties = typeof(FixedLengthBlock).GetProperties(bindingFlags);\nvar newObj = Activator.CreateInstance(typeof(FixedLengthBlock))\nforeach (var property in blockProperties)\n{\n    if (block.Properties.ContainsKey(property.Name))\n    {\n        var propertyInfo = newObj.GetType().GetProperty(property.Name, bindingFlags);\n        if (propertyInfo == null) { continue; }\n        propertyInfo.SetValue(newObj, block.Properties[property.Name]);\n    }\n}	0
26206717	26206612	Set DataContext in XAML Rather Than in Code Behind	public MainWindow()\n    {\n        PersonList = new ObservableCollection<Person>();\n        InitializeComponent();\n        PersonList.Add(new Person(16, "Abraham", "Lincoln"));\n        PersonList.Add(new Person(32, "Franklin", "Roosevelt"));\n        PersonList.Add(new Person(35, "John", "Kennedy"));\n        PersonList.Add(new Person(2, "John", "Adams"));\n        PersonList.Add(new Person(1, "George", "Washington"));\n        PersonList.Add(new Person(7, "Andrew", "Jackson"));\n    }	0
8365082	3369635	How can I crop the PDF page	public static void CropDocument(string file, string oldchar, string repChar)\n{\n    int pageNumber = 1;\n    PdfReader reader = new PdfReader(file);\n    iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(\n    Globals.fX,\n    Globals.fY,\n    Globals.fWidth,\n    Globals.fHeight);\n    Document document = new Document(size);\n    PdfWriter writer = PdfWriter.GetInstance(document,\n    new FileStream(file.Replace(oldchar, repChar),\n    FileMode.Create, FileAccess.Write));\n    document.Open();\n    PdfContentByte cb = writer.DirectContent;\n    document.NewPage();\n    PdfImportedPage page = writer.GetImportedPage(reader,\n    pageNumber);\n    cb.AddTemplate(page, 0, 0);\n    document.Close();\n}	0
2996859	2996835	Reading membership section from web.config in C#	int i = Membership.MinRequiredPasswordLength;	0
3705716	3705707	A String manipulation Question for .NET	if( comments.StartsWith(", ") && comments.Length > 2 ) {\n  comments = comments.Substring(2);\n}	0
8956026	8955635	how to access output value of Special Select SQL Query in the C# program	DataClassesDataContext data = new DataClassesDataContext();\nvar Results = data.StrPC_BDPathData_CustomSelectDistance(10);\nint Distance =int.Parse(Results(0).Dstc);	0
1613134	1599025	Get IP of my machine C# with virtual machine installed	public static ArrayList getThisCompIPAddress()\n    {\n        ArrayList strArrIpAdrs = new ArrayList();\n        ArrayList srtIPAdrsToReturn = new ArrayList();\n        addresslist = Dns.GetHostAddresses(Dns.GetHostName());\n        for (int i = 0; i < addresslist.Length; i++)\n        {\n            try\n            {\n                long ip = addresslist[i].Address;\n                strArrIpAdrs.Add(addresslist[i]);\n            }\n            catch (Exception ex) \n            {\n                Console.WriteLine(ex.Message);\n            }\n\n        }\n\n        foreach (IPAddress ipad in strArrIpAdrs)\n        {\n\n            lastIndexOfDot = ipad.ToString().LastIndexOf('.');\n            substring = ipad.ToString().Substring(0, ++lastIndexOfDot);\n            if (!(srtIPAdrsToReturn.Contains(substring)) && !(substring.Equals("")))\n            {\n                srtIPAdrsToReturn.Add(substring);\n            }\n        }\n\n        return srtIPAdrsToReturn;\n    }	0
10062036	10062004	Encrypting Data with RSA in .NET	rsa = (RSACryptoServiceProvider) certificate.PublicKey.Key;\nencryptedText = rsa.Encrypt(msg, true);	0
8230552	7922911	Creating NSMenuItems programmatically in MonoMac	fileMenuItem.Submenu = fileMenu;	0
22308555	22308481	How to force child of class to override field with child of field's type?	public abstract class EmergencyWorker<T> where T : Vehicle\n{\n    protected T vehicle;\n}\n\npublic class EMT : EmergencyWorker<Ambulance>\n{\n}\n\npublic class Firefighter : EmergencyWorker<FireTruck>\n{ \n}	0
15360753	15359750	Updating Model using MVC4 + Entity Framework 4	[HttpPost]\n    public ActionResult Edit(int articleId, FormCollection collection)\n    {\n        var result = from i in db.Articles\n                     where i.Id == articleId\n                     select i;\n\n        if (TryUpdateModel(result.First()))\n        {\n\n            db.SaveChanges();\n            return RedirectToAction("Index");\n        }\n\n        return View(result.First());\n\n    }	0
12799790	12799619	How to get actual language in a WinRT app?	Windows.Globalization.Language.CurrentInputMethodLanguageTag	0
24158700	24158373	Detect all the Key Pressed in keyboard	if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) // Is Alt key pressed\n        {\n            if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.A))\n            {\n                MessageBox.Show("Key pressed"); \n            }\n       }	0
17318788	17318645	How to convert a double in a string, if the string has to meet length requirements?	int value = 324;\n\nvar paddedValue = value.ToString().PadLeft(4,'0'));	0
17282859	17282830	Calling a public method from a different class	var myInstance = new YourClassName();\n var theString = myInstance.IsProviderSameAsPCP;	0
4675849	4675754	C#:inheritance for a child class that does have a property from parent	public class C\n{\n    // Other methods from class A than MethodA()\n}\n\npublic class A\n{\n    public void MethodA()\n    {\n        // Some code\n    }\n}\n\npublic class B : C\n{\n     // Some code\n}	0
34369859	34369802	How to append text to file	using(StreamWriter str = new StreamWriter("c:\\file.txt", true))\n{\n//todo\n}	0
20712698	20712200	Make footer visible on all existing ListViews	public partial class WinShowFooterController : ViewController<ListView>\n{\n    public WinShowFooterController()\n    {\n        InitializeComponent();\n        RegisterActions(components);\n        // Target required Views (via the TargetXXX properties) and create their Actions.\n    }\n\n    protected override void OnViewControlsCreated()\n    {\n        base.OnViewControlsCreated();\n        // Access and customize the target View control.\n    }\n\n    protected override void OnActivated()\n    {\n        base.OnActivated();\n\n        bool shouldSetFooterToVisible = this.View != null && this.View.Model != null;\n\n        if (shouldSetFooterToVisible)\n        {\n            this.View.Model.IsFooterVisible = true;\n        }\n    }\n\n    protected override void OnDeactivated()\n    {\n        base.OnDeactivated();\n    }\n}	0
30613956	30613495	extract lines from a flowdocument in a richtextbox starting with specific words WPF	private List<string> CollectLines()\n{\n    TextRange textRange = new TextRange(\n        // TextPointer to the start of content in the RichTextBox.\n        TestRichTextBox.Document.ContentStart,\n        // TextPointer to the end of content in the RichTextBox.\n        TestRichTextBox.Document.ContentEnd);\n\n    // The Text property on a TextRange object returns a string \n    // representing the plain text content of the TextRange. \n    var text = textRange.Text;\n\n    List<string> resultList = new List<string>();\n\n    // Collect all line that begin with INT or EXT\n    // Or use .Contains if the line could begin with a tab (\t), spacing or whatever\n    using (StringReader sr = new StringReader(text))\n    {\n        var line = sr.ReadLine();\n        while (line != null)\n        {\n\n            if (line.StartsWith("INT") || line.StartsWith("EXT"))\n            {\n                resultList.Add(line);\n            }\n\n            line = sr.ReadLine();\n        }\n    }\n\n    return resultList;\n}	0
30796969	30775079	Function to convert double to string with given options	NumberFormatInfo nfi = new NumberFormatInfo();\nnfi.NumberDecimalSeparator = decimalMark;\nnfi.NumberDecimalDigits = decimalDigits;\nreturn value.ToString("F" + decimalDigits.ToString(), nfi);	0
2886015	2882306	How to log correct context with Threadpool threads using log4net?	ThreadPool.QueueUserWorkItem(x => NDC.Push("nameStr")); log.Debug("From threadpool Thread: " + nameStr));	0
24975471	24975441	How to have a Game Object remove itself from a list? (Unity3d)	List<GameObject> enemies = new List<GameObject>();\nenemies.Add(enemy1);\nenemies.Remove(enemy1);	0
26184704	26184606	LINQ with grouping and summation	var query8 =\n    from q8 in query7\n    group new { q8.q7.allCount, q8.q7.openCount, q8.q7.closedCount }\n       by new { q8.q7.dept, q8.needWeek }\n       into g\n    select new\n    {\n        g.Key.dept,\n        g.Key.needWeek,\n        sum = g.Sum(x => x.allCount),\n        open = g.Sum(x => x.openCount),\n        closed = g.Sum(x => x.closedCount),\n    };	0
16240031	16221772	Set all RadTreeList items to edit mode	protected void RadTreeList1_PreRender(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        foreach (TreeListDataItem item in RadTreeList1.Items)\n        {\n            if (item is TreeListDataItem)\n            {\n                item.Edit = true;\n            }\n        }\n        RadTreeList1.Rebind();\n    }\n}	0
142823	142820	Design Time viewing for User Control events	[Browsable(true)]\npublic event EventHandler MyCustomEvent;	0
25958072	25956898	How to access( set or get or bind ) controls in rad grid?	protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)\n{\n    if (e.Item is GridEditFormItem && e.Item.IsInEditMode)\n    {\n        GridEditFormItem item = e.Item as GridEditFormItem;\n        TextBox txt_lect_in = item.FindControl("txt_lect_in") as TextBox;\n        //Access your textbox heer\n    }\n}\n//OR\nprotected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)\n{\n    if (e.Item is GridEditFormItem && e.Item.IsInEditMode)\n    {\n        GridEditFormItem item = e.Item as GridEditFormItem;\n        TextBox txt_lect_in = item.FindControl("txt_lect_in") as TextBox;\n        //Access your textbox heer\n    }\n}	0
21520254	21520013	How to get maximum degree of parallelism for task parallel library usage?	Environment.ProcessorCount	0
26729170	26728891	Trouble writing a Greatest Common Divisor method	public static int gcd(int dividend, int divisor)\n    {\n        while (divisor != 0)\n        {\n            int pervremainder = divisor;\n            divisor = dividend % divisor;\n            dividend = pervremainder;\n        }\n        return dividend;\n    }	0
17719728	17719550	Entity framework use already selected value saved in new variable later in select sentance	var query = context.MyTable\n   .Select(a => new\n   {\n      count = a.OtherTable.Where(b => b.id == id).Sum(c => c.value),\n      total = a.OtherTable2.Where(d => d.id == id)\n   })\n   .Select(x => new \n   {\n      count = x.count,\n      total = x.total * x.count\n   };	0
13158438	13157384	How to add Combobox as ContextMenu Item for Label Control. WPF app	ContextMenu contextmenu = new ContextMenu();\n        ComboBox CmbColorMenu = new ComboBox();\n        CmbColorMenu.ItemsSource = FontColors;// FontColors is list<objects>\n        CmbColorMenu.DisplayMemberPath = "Text";\n        contextmenu.Items.Add(CmbColorMenu);	0
27367332	27367274	Tidying up if statements	firstForceInt = string.IsNullOrEmpty(firstForceTextBox.Text) ? 0 : Convert.ToInt16(firstForceTextBox.Text);\nsecondForceInt = string.IsNullOrEmpty(secondForceTextBox.Text) ? 0 : Convert.ToInt16(secondForceTextBox.Text);	0
26418571	26418145	Get Atttribute value from XDocument	XmlNamespaceManager nsm = new XmlNamespaceManager(new NameTable());\nnsm.AddNamespace("def", "http://www.fake.org/namespace/");\nXDocument doc = XDocument.Parse(xml);\nstring code = \n    doc\n    .XPathSelectElement(@"/def:IDMResponse/def:ARTSHeader/def:Response", nsm)\n    .Attribute("ResponseCode")\n    .Value;	0
3625481	3625440	Web Service Date Time Parameter won't accept UK format DD/MM/YYYY	yyyy-MM-dd	0
9851342	9851308	List of byte[] to one big byte[]	listOfBytes.SelectMany(x => x).ToArray();	0
26093250	26093152	Visual Studio 2013, Reset configuration manager settings to default/factory settings	/ResetSettings (devenv.exe)	0
29104172	29102706	Adding a root node to Xml Document having a existing root node in C#	using System;\nusing System.Xml.Linq;\n\nstring inputXml = "<Stuff><SomeStuff></SomeStuff></Stuff>";\nXDocument firstLossRootNode = XDocument.Parse("<Root />");\nXDocument economyDocument = XDocument.Parse(inputXml);\n\nfirstLossRootNode.Root.Add(economyDocument.FirstNode);	0
17033913	17025338	Stop receiving messages from SubscriptionClient	SubscriptionClient.Close()	0
33151451	33151307	ADO.net insert a new row into a table that has a IDENTITY column, how to do that correctly?	DataTable tblAdded = dataSet.Tables[0].GetChanges(DataRowState.Added) ?? new DataTable();\nrow["id"] = -1 * (tblAdded.Rows.Count + 1);	0
26198132	26198123	Pick out every word beginning with a capital letter	if (strWord.Length > 0 && Char.IsUpper(strWord[0]))	0
13182464	13152823	allow just number in a gridviewcell on editing	public Form1()\n    {\n        InitializeComponent();\n        MyDataGridViewInitializationMethod();\n    }\n\n    private void MyDataGridViewInitializationMethod()\n    {\n        gvFactorItems.EditingControlShowing +=\n            new DataGridViewEditingControlShowingEventHandler(gvFactorItems_EditingControlShowing);\n    }\n\n    private void gvFactorItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress); ;\n    }\n\n    private void Control_KeyPress(object sender, KeyPressEventArgs e)\n    {\n\n        if (!char.IsDigit((char)(e.KeyChar)) &&\n            e.KeyChar != ((char)(Keys.Enter)) &&\n            (e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&\n            e.KeyChar != (char)(Keys.Back))\n        {\n            e.Handled = true;\n        }\n    }	0
15193221	15192226	Deserialize JSON to dictionary using LINQ to JSON	string json = "{\"Context\":{\"Test\": \"Test\"}}";\nvar obj = JObject.Parse(json);\nvar dict = obj["Context"].ToObject<Dictionary<string,string>>();	0
1233005	1232608	How do I get the MySQL Connector/NET driver version programmatically?	Version version = System.Reflection.AssemblyName.GetAssemblyName("MySQL.Data.dll").Version;	0
13712953	13706935	Returning a single parameter as part of multi mapping query	var sql = \n    @"select *, p.Status AS ID from #Posts p \n    left join #Users u on u.Id = p.OwnerId\n    Order by p.Id";\n\n    var data = connection.Query<Post, User, int, Post>(sql, (post, user, status) => { \n        post.Owner = user;\n        post.SetSomeStatus(status);\n        return post;\n    });\n\n    var post = data.First();	0
25774745	25774661	How to make verifiable all methods with Moq	var factory = new MockFactory(MockBehavior.Strict) { DefaultValue = DefaultValue.Mock };\n\nvar fooMock = factory.Create<IFoo>();\nvar barMock = factory.Create<IBar>();\n\n// Verify all verifiable expectations on all mocks created through the factory\nfactory.Verify();	0
8521799	8513850	fluent nhibernate PrimaryKeyConvention for property names	public class AutomappingConfiguration : DefaultAutomappingConfiguration\n{\n    public override bool IsId(Member member)\n    {\n        return member.Name == member.DeclaringType.Name + "Id";\n    }\n}	0
16436950	16436872	Download file from server using URL	Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(res.DownloadPath));	0
26307846	26307691	Using OpenXML SDK to replace text on a docx file with a line break (newline)	using (WordprocessingDocument doc =\n                WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))\n        {\n            var body = doc.MainDocumentPart.Document.Body;\n            var paras = body.Elements<Paragraph>();\n\n            foreach (var para in paras)\n            {\n                foreach (var run in para.Elements<Run>())\n                {\n                    foreach (var text in run.Elements<Text>())\n                    {\n                        if (text.Text.Contains("text-to-replace"))\n                        {\n                            text.Text = text.Text.Replace("text-to-replace", "");\n            run.AppendChild(new Break());\n                        }\n                    }\n                }\n            }\n        }	0
5842994	5842938	How to create buttons in taskbar menu Windows 7 C#?	ThumbnailToolbarButton infoButton = new ThumbnailToolbarButton(SystemIcons.Information, "Information");\ninfoButton.Click += delegate {\n    // Action\n};\n\nTaskbarManager.Instance.ThumbnailToolbars.AddButtons(this.Handle, infoButton);	0
5530620	958953	Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand?	;Allow User Variables=True	0
26553509	26553131	Save interface type object to IsolatedStorageSettings, serialization	public interface IAnimal\n{\n   string Name { get; }\n}\n\n  [KnownType(typeof(Cat))]\n  [KnownType(typeof(Dog))]\npublic class Animal: IAnimal\n{\n  string Name { get; }\n}\n\npublic class Cat : Animal\n{\n  string Name { get; set; }\n}\n\n\npublic class Dog: Animal\n{\n  string Name { get; set; }\n}	0
30846903	30846244	LINQ : two separate queries in a single distinct result	var brandIDsPerCat = (from cats in CarCategories\n                join ctts in CategoryTypes on cats.CatID equals ctts.CatID\n                join tps in Types on ctts.TypeID equals tps.TypeID\n                join tpbs in TypeBrands on tps.TypeID equals tpbs.TypeID\n                group new {cats, tpbs} by cats.CatTitle into g\n                select new\n                {\n                  catTitle = g.Key\n                  brandId = g.Select(x => x.tpbs.BrandId)\n                             .Distinct()\n                             .OrderBy(x => x)//if you need ordering in groups\n                }	0
218677	218556	Send document to printer with C#	System.Drawing.Printing	0
2720723	2720617	How to get all methods from WCF service?	MethodInfo[] methods = typeof(TypeOfTheService).GetMethods();\nforeach (var method in methods)\n{\n    string methodName = method.Name;\n}	0
7119011	7118636	Need a regular expression for wpf lostfocus events	LostFocus=:q	0
2359041	2358779	How to connnect GridView DataSource over Webpart class?	public object DataSource\n{\n   get \n   {\n       this.EnsureChildControls();\n       return gv.DataSource; \n   }\n   set \n   { \n       this.EnsureChildControls();\n       gv.DataSource = value; \n   }\n}	0
19846537	19842392	Divide a value in gridview	protected void Gridview2_SelectedIndexChanged(object sender, EventArgs e)\n{\n    TextBox txtboxtotal = (TextBox)Gridview2.SelectedRow.FindControl("txtboxtotal");\n    txtboxtotal.Text = (Convert.ToDecimal(txtboxtotal.Text) / 2).ToString();\n}	0
3986399	3986379	C# - Check filename ends with certain word	Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")	0
15831227	15831171	Get index of first detected space after a certain index in a string	var start = myString.IndexOf("%");\nvar spaceIndex = myString.IndexOf(" ", start)	0
10130545	10130504	How to get the name of current function?	System.Reflection.MethodBase.GetCurrentMethod().Name	0
5782906	5782642	WPF C#, Get informations from audio file	myString = myString.Replace("\0", "")	0
13672484	13671749	how to insert row in entity 3.5 in detail table?	Table1 t1 = new Table1();\nTable2 t2 = new Table2();\nt1.add(t2);	0
5249859	2281972	How to get a list of properties with a given attribute?	var props = from p in this.GetType().GetProperties()\n            let attr = p.GetCustomAttributes(typeof(MyAttribute), true)\n            where attr.Length == 1\n            select new { Property = p, Attribute = attr.First() as MyAttribute};	0
5313336	5309836	How to link two checklistbox items?	checkedListBox1.Items.Add("test");\ncheckedListBox1.ItemCheck += new ItemCheckEventHandler(checkedListBox1_ItemCheck);\n\n....\n\nvoid checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    Console.WriteLine(((CheckedListBox)sender).Name + " is the father of item nr: " + e.Index);\n    Console.WriteLine("The value of element nr " + e.Index + " is " + ((CheckedListBox)sender).Items[e.Index].ToString());\n}	0
523692	492391	How to get domain controller IP Address	using System;\n    using System.Collections.Generic;\n    using System.Text;\n    using System.Net;\n    using System.Net.Sockets;\n    using System.DirectoryServices.AccountManagement;\n    using System.DirectoryServices.ActiveDirectory;\npublic doIt()\n        {\n            DirectoryContext mycontext = new DirectoryContext(DirectoryContextType.Domain,"project.local");\n            DomainController dc = DomainController.FindOne(mycontext);\n            IPAddress DCIPAdress = IPAddress.Parse(dc.IPAddress);\n        }	0
16833811	16833764	casting a list<baseclass> to a list<derivedclass>	myList.Cast<BaseClass>	0
4185228	4185171	Use cookies from CookieContainer in WebBrowser	public partial class WebBrowserControl : Form\n{\n     private String url;\n\n     [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]\n     public static extern bool InternetSetCookie(string lpszUrlName, string    lbszCookieName, string lpszCookieData);\n\n     public WebBrowserControl(String path)\n     {\n          this.url = path;\n          InitializeComponent();\n\n          // set cookie\n          InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID); \n\n          // navigate\n          webBrowser.Navigate(url); \n     }\n}	0
15598249	15598140	Getting client information in C#	static void Main(string[] args)\n        {\n\n            Thread worker = new Thread(DoBackgroundWork);\n        }\n\n        public static void DoBackgroundWork()\n        {\n\n\n            while (true)\n            {\n                //Sleep 10 seconds\n                Thread.Sleep(10000);\n\n                //Do some work and than post to the control using Invoke()\n\n            }\n\n        }	0
19500178	19473781	Ways to make a 2D physics simulator for a side scrolling game	float currentYspeed;\nfloat GRAVITY = 5;\nbool playerFlying;\n\n// In Update():\nif (isUpArrowKeyDown() && !playerFlying) { playerFlying = true currentYspeed = 50; }\nplayerY += currentYspeed;\ncurrentYspeed -= GRAVITY;\nif (playerCollidesWithFloor())\n{\n  currentYspeed = 0; // We came back to ground.\n  playerFlying = false;\n}\nelse if (playerCollidesWithSomethingElse())\n{\n  currentYSpeed = 0; // We hit obstacle in-air.\n}	0
16916833	16916819	C# Replace all elements of List<string> with the same pattern with LINQ	var resultList = list.Select(x => string.Format("({0})", x)).ToList();	0
33019654	33019312	Need a Regular Expression for	string myString = "(((1))) - 1";\nmyString = myString.Replace("(", "").Replace(")", "");	0
17253059	17253040	C# - Convert SqlDataReader to ArrayList	DataTable dt = new DataTable();\nif (rdr.HasRows == true)\n     dt.Load(rdr);	0
5330657	5330557	SQL syntax, and c# table entry into database	insert into WallPostings\n(userID, WallPosting)\nvalues\n(1, 'data goes here')	0
1621603	1618778	Clarification on how to properly declare interop interfaces	[Guid("fab51c92-95c3-4468-b317-7de4d7588254"), ComImport,  InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IDerivedComInterface\n{\n    void method1(); \n    void method2();\n    void method3();\n    void method1_2(); //Decorated to distinguish from base interface method.\n    void method4();\n    void method5();\n}	0
1862024	1861997	How do I parse a string into a DateTime, with a specific format?	DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)	0
21054339	21053995	JPG corrupted on upload in silverlight	if (bitmapImage != null) {\n    // create WriteableBitmap object from captured BitmapImage\n    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);\n\n    using (MemoryStream ms = new MemoryStream())\n    {\n        writeableBitmap.SaveJpeg(ms, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);\n\n        ms.Position = 0;\n        imageBuffer = new byte[ms.Length];\n        ms.Read(imageBuffer, 0, imageBuffer.Length);\n        ms.Dispose();\n    }                \n}	0
14764200	14762270	How to pass the file name of an uploaded file into a SQL Value in ASP.NET C#?	e.Values["Picture"] = pu.FileName;	0
34033924	34032569	How can I format a formulaic result in C# Excel Interop?	totalTotalPackageCountCell.NumberFormat = "#,##0";\ntotalTotalPackageCountCell.Formula = string.Format("=SUM(O10:O{0})", curDelPerfRow);	0
2365488	2358677	C# WPF - Application Icon + ShowInTaskbar = False	private void Window_Loaded(object sender, RoutedEventArgs e) {\n    SetParentIcon();\n}\n\nprivate void SetParentIcon() {\n    WindowInteropHelper ih = new WindowInteropHelper(this);\n    if(this.Owner == null && ih.Owner != IntPtr.Zero) { //We've found the invisible window\n        System.Drawing.Icon icon = new System.Drawing.Icon("ApplicationIcon.ico");\n        SendMessage(ih.Owner, 0x80 /*WM_SETICON*/, (IntPtr)1 /*ICON_LARGE*/, icon.Handle); //Change invisible window's icon\n    }\n}\n\n[DllImport("user32.dll")]\nprivate static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);	0
7588073	7588032	XML and C# - WriteEndElement	WriteStartElement("A");\nWriteStartElement("B");\n// ... attributes or content added here will become part af B element\nWriteEndElement(); // Closes the open B element.\nWriteEndElement(); // Closes the open A element.	0
33606063	33604554	How change data grid view datasource with ObjectDataSource?	protected void lbnChangeInfo1_Click(object sender, EventArgs e)\n{\n   gdvList.DataSource = null;\n   gdvList.DataSourceID = null;\n   gdvList.DataSource = odsWork1;\n   gdvList.DataBind();\n}	0
31541810	31541729	Need to convert JSON to datatable	var dt = JObject.Parse(json)["users"].ToObject<DataTable>();	0
2456783	2456755	inserting null values in datetime column and integer column	if(H1N_ID != null)\n{\n   cmd.Parameters.Add(new SqlParameter("H1N_ID",HIN_ID);\n}\nelse\n{\n   cmd.Parameters.Add(new SqlParameter("H1N_ID",DBNull.Value);\n}	0
22810143	22809385	update master page control in click on client page control how can do this	protected void ImageButton1_Click(object sender, ImageClickEventArgs e)\n{\n  var c=  this.Master.FindControl("lbl_cart") as System.Web.UI.HtmlControls.HtmlGenericControl;      \n  c.InnerText = "12122112";\n}	0
25623186	25616219	Mapping List<T> to a model in ASP.NET MVC5	return \n    db.halls\n      .Take(30)\n      .Select(h => \n          new havvViewModel\n          {\n              Name = h.name\n          });	0
20003832	20003600	Screen Resizing C# 2010	public Game1()\n    {\n        graphics = new GraphicsDeviceManager(this);\n        graphics.PreferredBackBufferHeight = 1080;   //Height\n        graphics.PreferredBackBufferWidth = 1920;  //Width\n        graphics.IsFullScreen = true;    //Fullscreen On/off\n        graphics.ApplyChanges();   //Execute Changes!!!IMPORTANT!!!\n        //if you want use/change the PresentationParameters.BackBufferWidth, you could do it with the GraphicsDevice which could be found in the GraphicsDeviceManager Class\n        graphics.GraphicsDevice.PresentationParameters.BackBufferWidth;\n    }	0
14449485	14449471	create function visual studio 2010 with optional parameters	public static void setString()\n{\n    setString("asd");\n}	0
8193989	8193826	How implement a Model to force clients fill at least one of two inputs in ASP.NET MVC	public class PhoneNumber : IValidatableObject {\n\n    public long Id { get; set; }\n    public string Tel1 { get; set; }\n    public string Tel2 { get; set; }\n\n\npublic IEnumerable<ValidationResult> Validate(ValidationContext validationContext) \n{\n\n        var field1 = new[] { "Tel1" };\n        var field2 = new[] { "Tel2" };\n\n        if (string.IsNullOrEmpty(Tel1))\n            if (String.IsNullOrEmpty(Tel2))\nyield return new ValidationResult("At least Fill one of Tel1 or Tel2???", field1);\n\n        if (string.IsNullOrEmpty(Tel2))\n        if (String.IsNullOrEmpty(Tel1))\nyield return new ValidationResult("At least Fill one of Tel1 or Tel2", field2);\n    }\n}	0
10242609	10242395	Add values from datagridview cells	dataGridView1[3, 0].Value = Convert.ToDouble(dataGridView1[1, 0].Value) + Convert.ToDouble(dataGridView1[2, 0].Value);	0
33737234	33661292	Export Formats for CSV File in Stimulsoft	config.DataExportMode = StiDataExportMode.Data;\nconfig.DataExportMode = StiDataExportMode.DataAndHeadersFooters;\nconfig.DataExportMode = StiDataExportMode.AllBands;	0
11575232	11563593	implicit cast from enum to another type (CloudBlobContainer)	public static CloudBlobContainerExtensions {\n    public static CloudBlobContainer GetContainer(this EnumTypes.BlobContainerNames BlobContainerName)\n    {\n        return CloudStorageAccount.DevelopmentStorageAccount.CreateCloudBlobClient().GetContainerReference(Enum.GetName(typeof(EnumTypes.BlobContainerNames), BlobContainerName));\n    }\n}\n\n//elsewhere\nvar myContainer = EnumTypes.BlobContainerNames.somename.GetContainer();	0
15256397	15256068	Set Conditional IconSets in Excel	cfIconSet.IconSet = cfIconSet.IconSet(Excel.XlIconSet.xl3Flags);	0
728269	728241	How can I add an attribute to a return value in C++/CLI?	[returnvalue: MarshalAs(UnmanagedType::IUknown)]	0
10105560	10083299	Detect which childwindow of the foreground window has been clicked?	InPtr hwnd = GetForegroundWindow();\n\n      public static void GetAppActiveWindow(IntPtr hwnd)\n    {\n        uint remoteThreadId = GetWindowThreadProcessId(hwnd, IntPtr.Zero);\n        uint currentThreadId = GetCurrentThreadId();\n        //AttachTrheadInput is needed so we can get the handle of a focused window in another app\n        AttachThreadInput(remoteThreadId, currentThreadId, true);\n        //Get the handle of a focused window\n        IntPtr focussed = GetFocus();\n\n        StringBuilder activechild = new StringBuilder(256);\n        GetWindowText(focussed, activechild, 256);\n        string textchld = activechild.ToString();\n        if (textchld.Length > 0)\n        {\n            Console.WriteLine("The active Child window is " + textchld + " .");\n\n        }\n        //Now detach since we got the focused handle\n        AttachThreadInput(remoteThreadId, currentThreadId, false);\n    }	0
12963076	12950592	ServiceStack returning typed response in XML format	this.ServiceExceptionHandler = (req, ex) =>\n{\n    var responseStatus = ex.ToResponseStatus();\n    var errorResponse = ServiceStack.ServiceHost.DtoUtils.CreateErrorResponse(req, ex, responseStatus);\n    return errorResponse;\n};	0
6333154	6333120	How can I pre-populate a simple class with data?	public class TextFiller\n{\n    public TestFiller()\n    {\n        Text = new HtmlText();\n        Details = "";\n    }\n\n    public HtmlText Text { get; set; }\n    public string Details { get; set; }\n}\n\npublic class HtmlText\n{ \n    public HtmlText()\n    {\n        TextWithHtml = "";\n    }\n\n    [AllowHtml]\n    public string TextWithHtml { get; set; } \n}	0
8929369	8928608	Fluent NHibernate: Table Per Class - Inheritance, how to define other FK-Name?	public class ChildMap : SubclassMap<Child>\n{\n    public ChildMap ()\n    {\n        KeyColumn("ParentId")\n        Map(x => x.ChildName);\n    }\n}	0
25393290	25392951	C# representation of hex in byte array	ASCIIEncoding asciiEncoding = new ASCIIEncoding();\n\nstring msg= "003,000";\nbyte[] msgBytes = asciiEncoding.GetBytes(msg);\n\nbyte[] bytesToSend = new byte[msgBytes.Length +2];\nbytesToSend[0] = 0x05;\nbytesToSend[bytesToSend.Length -1] = 0x03;\nBuffer.BlockCopy(msgBytes, 0, bytesToSend, 1, msgBytes.Length);	0
27333363	27333313	Using The @ symbol for a Directory so two backslashes aren't needed	Globals.directoryRoute	0
6944286	6944230	Pass state data in to a Parallel.ForEach without using anonymous delegates	var someState = GetSomeState();\nParallel.ForEach(MyIEnumerableSource, \n\n    () => new DataTable(),\n\n    (record, loopState, localDataTable) =>\n       OtherClass.Process(record, loopState, LocalDataTable, someState),\n\n    (localDataTable) => { ... }\n);\n\nstatic class OtherClass\n{\n    public static DataTable Process(MyRecordType record, ParallelLoopState loopState, DataTable localDataTable, someStateType someState)\n    {\n        localDataTable.Rows.Add(someState.Value, record);\n        return localDataTable\n    }\n}	0
12347983	12347881	Renaming files in folder c#	DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess");\nFileInfo[] infos = d.GetFiles();\nforeach(FileInfo f in infos)\n{\n    File.Move(f.FullName, f.FullName.ToString().Replace("abc_",""));\n}	0
16116257	16109503	How to click a non ID java button in my c# browser?	private void Form1_Load(object sender, EventArgs e)\n    {\n        webBrowser1.DocumentText = "<td class=\"submit\"><br><button   class=\"fixedSizeBigButton\" type=\"submit\"></td>";\n        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);\n    }\n\n    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n    {\n        foreach (HtmlElement btn in webBrowser1.Document.GetElementsByTagName("button"))\n        {\n            if (btn.GetAttribute("ClassName") == "fixedSizeBigButton")\n            {\n                btn.InvokeMember("Click");\n            }\n        }\n    }	0
15038621	15038599	How to get the unique of datatable under specific condition	var list = dataTable.Select("selected = 1");\n\nvar uniqueList = list.Distinct().ToList();	0
26948752	26948716	Random string from list of strings	Console.WriteLine(fruits[r1.Next(fruits.Length)]);	0
16417181	16401947	Draw a circle in an Emgu ConvolutionKernelF	Image<Gray, float> kernel = new Image<Gray, float>(radius * 2 + 1, radius * 2 + 1);\nkernel.Draw(new CircleF(new Point(radius, radius), radius), new Gray(1.0), 1);\nCvInvoke.cvFilter2D(A, B, kernel, new Point(-1, -1));	0
9413639	9413575	Custom IAuthorizationFilter injected with Ninject stops other ActionFilterAttribute from being executed	filterContext.Result = ...	0
16151617	16151459	Mouse click object in canvas	e.OriginalSource	0
5338160	5338141	array to dictionary	_valueAdds.ToDictionary(t => t, t => false);	0
14997451	14992475	How can I intersect multiple query with EntityFramework for a search?	var selectedRecipies = new List<IEnumerable<Recipy>>();\n\n        foreach(...)\n        {\n            ...\n            selectedRecipies.Add(recipesTemp);\n        }\n\n        var recipies = selectedRecipies.Aggregate((a, i) => a.Intersect(i));	0
32181055	32180976	How to split a string with non-numbers as delimiter?	string input = "44sugar1100";\nstring pattern = "[a-zA-Z]+";            // Split on any group of letters\n\nstring[] substrings = Regex.Split(input, pattern);\nforeach (string match in substrings)\n{\n    Console.WriteLine("'{0}'", match);\n}	0
19368916	19368284	NLog auto truncate messages	[LayoutRenderer("truncate")]\n[ThreadAgnostic]\npublic sealed class TruncateLayoutRendererWrapper : WrapperLayoutRendererBase\n{\n    public TruncateLayoutRendererWrapper()\n    {\n        this.Truncate = true;\n        this.Ellipsis = true;\n        this.Limit = 1000;\n    }\n\n    [DefaultValue(true)]\n    public bool Truncate { get; set; }\n\n    [DefaultValue(true)]\n    public bool Ellipsis { get; set; }\n\n    [DefaultValue(1000)]\n    public bool Limit { get; set; }\n\n    /// <summary>\n    /// Post-processes the rendered message. \n    /// </summary>\n    /// <param name="text">The text to be post-processed.</param>\n    /// <returns>Trimmed string.</returns>\n    protected override string Transform(string text)\n    {\n        if (!Truncate || Limit <= 0) return text;\n\n        var truncated = text.Substring(0, Ellipsis ? Limit - 3 : Limit);\n        if (Ellipsis) truncated += "...";\n\n        return truncated;\n    }\n}	0
28858632	28858455	entity framework linq get values except same values	List<string> thirdList = firstList.Concat(secondList).Distinct().ToList();	0
9070936	9070327	Is there a textboxlist control available somewhere?	foreach(Control ctl in myPanel.Controls)\n{\n  //check control type and handle\n  if (ctl is TextBox)\n  {\n     //handle the control and its value here\n  }\n}	0
2972190	2898627	Datagrid results do not make sense	IEditableCollectionView ecv = new ListCollectionView(myRecordCache);\nbool b = ecv.CanAddNew;   // dummy access\nMyGrid.DataContext = ecv;	0
32971705	32967546	Font Size issue with a popup shown at design-time in a WinForms UserControl	public void About()\n{\n    float width, height;\n    using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))\n    {\n        width = graphics.DpiX / 96;\n        height = graphics.DpiY / 96;\n    }            \n    About form = new About();            \n\n    if (width != 1 || height != 1)\n        form.Scale(new SizeF(width, height));\n\n    form.ShowDialog();\n}	0
10447392	10447305	how to put validation for radiobuttonlist's radiobutton ?	protected void GVRowDataBound(object sender, GridViewRowEventArgs e)\n {\n       var radioList= (RadioButtonList) e.Row.FindControl("ID");     \n }	0
1213152	1197786	How do I clear out a user object attribute in Active Directory?	string adPath = "LDAP://server.domain.com/CN=John,CN=Users,dc=domain,dc=com";DirectoryEntry userEntry = Settings.GetADEntry(adPath);\nuserentry.Properties["mail"].Clear();\nuserentry.CommitChanges();	0
12115747	12115679	Deployed Code Cannot Find A Library Reference	Copy Local = true	0
33297038	33296939	Get xml attribute value from an associated attribute value	string color = MyData.Descendants("Red").Elements("Shade").Where(y => (int)y.Attribute("id") == 3).FirstOrDefault().Attribute("group");	0
6723319	6719722	silverlight - opening a file	public MainPage()\n        {\n            InitializeComponent();\n\n            GetFileContent("http://localhost/test/myjson.txt", ProcessResult, error => { throw error; });\n        }\n\n        private void ProcessResult(String result)\n        {\n            //Do stuff here\n        }\n\n        private void GetFileContent(String uri, Action<String> onData, Action<Exception> onError)\n        {\n            var wc = new WebClient();\n\n            DownloadStringCompletedEventHandler handler = null;\n\n            handler = (s, args) =>\n            {\n                wc.DownloadStringCompleted -= handler;\n                if(args.Error != null)\n                {\n                    if(onError != null)\n                        onError(args.Error);\n                    return;\n                }\n\n                if(onData != null)\n                    onData(args.Result);\n            };\n            wc.DownloadStringCompleted += handler;	0
4791603	4339167	How to Read a Configuration Section from XML in a Database?	public class MyConfig : ConfigurationSection\n{\n    public MyConfig()\n    {\n        // throw some code in here to retrieve your XML from your database\n        // deserialize your XML and store it \n        _myProperty = "<deserialized value from db>";\n    }\n\n    private string _myProperty = string.Empty;\n\n    [ConfigurationProperty("MyProperty", IsRequired = true)]\n    public string MyProperty\n    {\n        get\n        {\n            if (_myProperty != null && _myProperty.Length > 0)\n                return _myProperty;\n            else\n                return (string)this["MyProperty"];\n        }\n        set { this["MyProperty"] = value; }\n    }\n}	0
7725988	7725895	How can I make a download link which downloads data directly from a DB in ASP.NET?	using System.IO;\nusing System.Web;\n\npublic class Docs : IHttpHandler \n{\n    public void ProcessRequest (HttpContext context) \n    {\n        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";\n        using (var streamReader = new StreamReader("fileSourceForDemonstration.docx"))\n        {\n            streamReader.BaseStream.CopyTo(context.Response.OutputStream);\n        }\n    }\n\n    public bool IsReusable \n    {\n        get { return false; }\n    }\n}	0
18109914	18109874	C# reference variable, does making one null make the other null?	m_MyClass = new MyClass();\nDispatcher.m_MyClass = m_MyClass;\n\nm_MyClass.MyProp = null;\n// Dispatcher.m_MyClass.MyProp == null	0
5950110	5949869	Same line,extracting 2 keywords	string line = textReader.ReadLine();\nvar reader = new StringReader(line);\nwhile (line != null)\n{\n    var ip = reader.ReadWord();\n    reader.SkipWhitespaces();\n    var date = reader.ReadQuotedString();\n    reader.SkipWhitespaces();\n    var uri = reader.ReadQuotedString();\n    reader.ReadUntil('"');\n    var uri2 = reader.ReadQuotedString();\n\n    line = textReader.ReadLine();\n    reader.Assign(line);\n}	0
8659887	8659402	Get currently selected option in dropdown box in selenium	var selectedItemText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].options[arguments[0].selectedIndex].text;", element);\nvar selectedItemValue = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].options[arguments[0].selectedIndex].value;", element);\nvar selectedItemIndex = (long)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].selectedIndex;", element);	0
24146494	24146350	Browse directory of the website aspnet	string rootFolder = Server.MapPath("~/App_Data");\nstring[] folders = Directory.GetDirectories(rootFolder);	0
17485726	17482437	Process often exiting prematurely	NetOffice.WordApi.Application wordApp = new NetOffice.WordApi.Application();\nwordApp.Visible = true;\nNetOffice.WordApi.Document doc = wordApp.Documents.Open(path);	0
22365350	22365199	How to Add More Complex Powershell Commands to Pipeline	PowerShell shell = PowerShell.Create().AddScript(String.Format("(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection(\"{0}\")",strShare ));	0
21106077	21102307	Require c# Normalising Math Formula based on attached array which generates bar chart % value output?	int[] array = { 25, 35, 55, 5, 60, 200, 18, 18, 30, 10 };\nint selectdVal = 5;\n\nint barMin = 1;\nint barMax = 100;\n\ndecimal rangeMin = array.Min();\ndecimal rangeMax = array.Max();\n\ndecimal ratio = (barMax - barMin) / (rangeMax - rangeMin);\n\nint bar = barMax - (int)(ratio * (selectdVal - rangeMin));	0
31908665	31908323	Asterix in C# console	static void Main(string[] args)\n    {\n        int n = 3;\n        for (int i = 1; i < 2 * n; i++)\n        {\n            if (i <= n)\n                for (int j = 1; j <= i; j++)\n                    Console.Write('*');\n\n            else\n                for (int j = 1; j <= 2 * n - i; j++)\n                    Console.Write('*');\n\n            Console.WriteLine();\n        }\n\n        Console.ReadLine();\n    }	0
24331043	24330787	Can I deserialize a JSON object by object in C#?	string json = File.ReadAllText(PathFile);\n jsonData obj = JsonConvert.DeserializeObject<jsonData>(json);	0
25550475	25549215	How to validate the text inside Uploaded file in asp.net	string temp = inputline;\n\nbool saveFile = true;\n// check for amount of comma in line\nif(temp.Split(',').Length - 1 != 2) {\n    saveFile = false;\n}\n\nif(saveFile) {\n    // your save code     \n}	0
4254833	4254217	Retrieving the COM class factory for component with CLSID	HKLM\Software\Classes\CLSID\{your guid}	0
7841488	7770358	Checking that a user has correctly entered an IP Address	string ip = "127.0.0.1";\nstring[] parts = ip.Split('.');\nif (parts.Length < 4)\n{\n    // not a IPv4 string in X.X.X.X format\n}\nelse\n{\n    foreach(string part in parts)\n    {\n        byte checkPart = 0;\n        if (!byte.TryParse(part, out checkPart))\n        {\n            // not a valid IPv4 string in X.X.X.X format\n        }\n    }\n    // it is a valid IPv4 string in X.X.X.X format\n}	0
17683086	17682595	iterating over a DataGridView in C# - Object reference not set to an instance of an object	foreach (DataGridViewRow r in DataGridObject.Rows)\n        {\n            MyDataSource.ForEach( \n                delegate( Product p)\n                {\n                    if(r.Cells["Product"]!=null)\n                     {\n                      if(r.Cells["Product"].Value!=null)\n                      {\n                        if (r.Cells["Product"].Value.ToString() == p.Title)\n                        {\n                          tally += p.Price;\n                        }\n                      }\n                    }\n                }\n            );\n        }	0
28591618	28591362	Returning pointer to a class variable in C#	public Func<int> getProc(int id)\n{\n    switch (id)\n    {\n        case 1:\n            return () => proc1tasks;\n        case 2:\n            return () => proc2tasks;\n    }\n}	0
32249060	32248713	Dynamicaly set byte[] array from a String of Ints	string datas = "123, 234, 123, 234, 123, 123, 234";\nbyte[] byteArr = Regex.Matches(datas, @"\d+").Cast<Match>()\n                .Select(m => byte.Parse(m.Value))\n                .ToArray();	0
20051703	20050975	How to add the content of Xml files to a SQL Server database	DECLARE @input XML\n\nSELECT @input = XTbl.XEmp\nFROM OPENROWSET(BULK 'C:\Testmail.xml', SINGLE_CLOB) XTbl(XEmp);\n\nINSERT INTO Mitarbeiter (ID, Vorname, Nachname, Gehalt)\nSELECT XEmp.value('(ID)[1]', 'int'), XEmp.value('(Vorname)[1]', 'varchar(50)'), XEmp.value('(Nachname)[1]', 'varchar(50)'), XEmp.value('(Gehalt)[1]', 'int')\nFROM @input.nodes('/Mitarbeiter/Mitarbeiter') AS XTbl(XEmp);	0
6416581	6416268	Split a ICollection<T> with a delimiter sequence	private static IEnumerable<IEnumerable<T>> Split<T>\n    (IEnumerable<T> source, ICollection<T> delimiter)\n{\n    // window represents the last [delimeter length] elements in the sequence,\n    // buffer is the elements waiting to be output when delimiter is hit\n\n    var window = new Queue<T>();\n    var buffer = new List<T>();\n\n    foreach (T element in source)\n    {\n        buffer.Add(element);\n        window.Enqueue(element);\n        if (window.Count > delimiter.Count)\n            window.Dequeue();\n\n        if (window.SequenceEqual(delimiter))\n        {\n            // number of non-delimiter elements in the buffer\n            int nElements = buffer.Count - window.Count;\n            if (nElements > 0)\n                yield return buffer.Take(nElements).ToArray();\n\n            window.Clear();\n            buffer.Clear();\n        }\n    }\n\n    if (buffer.Any())\n        yield return buffer;\n}	0
18599319	18599146	Dynamic EF Where Clause raising ArgumentNullException	IQueryable<Pesquisa> temp = db.Pesuisas;\n\n// your code follows.	0
11854400	11854072	How to start a new application instance from within the application?	Process p = new Process();\np.StartInfo.FileName = \n    System.Reflection.Assembly.GetExecutingAssembly().Location;\np.Start();	0
14826266	14826058	Set checkbox value from database in C# asp.net	if(!Page.IsPostBack)\n{\n     var isChecked = dbvalue.ToLower() == "submitted" ? true : false;\n     for (var i = 0; i < 8;i++ )\n     {\n         CheckBox chk = (CheckBox)Form.FindControl("chk" + i);\n         if(chk != null) chk.checked = isChecked;\n     }\n}	0
28008115	28008066	How would I grab certain information from HTML scraping, if the website returns it as not loaded?	string data  = "";\n        using (WebClient client = new WebClient())\n        {\n            data = client.DownloadString(url);\n        }\n        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n        MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data));\n        doc.Load(stream);	0
19132798	19132774	In a collection of objects, how do i extract one attribute from each to new list?	var newList = source.Select(item=>item.TypeId).ToList();	0
13641566	13641371	entity has some invalid arguments when trying to perform an INSERT with EF	sistema_UsersCertified dbEntity = new sistema_UsersCertified();\ndbEntity.CertType = ...\ncontext.sistema_UsersCertified.Add(dbEntity);	0
32277923	32277738	True merge statement in Entity Framework	var sourceIds = source.Select(s=>s.Id);\nvar notFounds = context.Target.Select(s=>!sourceIds.Contains(s.Id));\nforeach (var notFound in notFounds) {\n  context.Target.DeleteObject(notFound);\n}	0
15783338	15781909	RegEx Replace that adds brackets around phrases	string input = "Milly Barry Molly,Joe Sandy Mary";\n\nRegex regex = new Regex(\n    @"(?<=^|,)\s*(?>[^\s,]+\s*){2,}(?=,)|(?<=,)\s*(?>[^\s,]+\s*){2,}$" );\nstring result = regex.Replace(input, "($&)");\n\nConsole.WriteLine(result);\n// (Milly Barry Molly),(Joe Sandy Mary)	0
10470079	10469920	c# getting informaion from xml file	var query  = from t in doc.Descendants("forecast_conditions")\n                         select t;	0
6775568	6775444	String Manipulation with regular expression	/\bA[a-z]*\b/	0
25964506	25940214	Utilize model methods and properties in another model	public HomeModel(IMxUser mxUser, ILocalizer localizer)\n  : base(mxUser, localizer)\n{\n    // ...\n}	0
24367019	24366981	Open my own C# desktop app from C# website	//magnet link\nmagnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C\n\n//team speak\nts3server://ts.forcekillers.com/?port=9987	0
15242095	13198090	Adding HttpClient headers generates a FormatException with some values	var http = new HttpClient();\nhttp.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");	0
17806943	17806897	How can I distinguish between editing and creating a new item in my validation method?	bool IsUnique()\n{\n    return !repository.Any(x => x.ID != this.ID && x.URL == this.URL);\n}	0
23928792	23928503	Trigger unable to find Button inside GridView	protected void OrderGrid_RowDataBound(object sender, GridViewRowEventArgs e)  \n{  \n   if (e.Row.RowType != DataControlRowType.DataRow) return;\n\n   Button lb = e.Row.FindControl("MarkAsCompleteButton") as Button;  \n   ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lb);  \n}	0
7646937	7639135	using google oauthutill in a desktop application to retrieve contacts	Service service = new ContactsService("My Contacts Application");\n        service.setUserCredentials("mail@gmail.com", "password");\n        var token = service.QueryClientLoginToken();\n        service.SetAuthenticationToken(token);\n        var query = new ContactsQuery(@"https://www.google.com/m8/feeds/contacts/mail@gmail.com/full?max-results=25000");\n        var feed = (ContactsFeed)service.Query(query);\n        Console.WriteLine(feed.Entries.Count);\n        foreach (ContactEntry entry in feed.Entries)\n        {\n            Console.WriteLine(entry.Title.Text);\n        }	0
23943151	23942907	How to find a button by name	object item = LayoutRoot.FindName(buttonName);\nif(item is Button)\n{\n  Button btn=(Button)item;\n}	0
26804006	26803638	EPPlus load custom value	long serialDate = long.Parse(sheet.Cells[r, c].Value.ToString());\ncellValue = DateTime.FromOADate(serialDate).ToString("dd-MM-yyyy");	0
4669826	4669731	Property Type from variable	public class ShortName<T>\n{     \n     public string ValueString { get; set; }      \n     private Type ValueType { get; }      \n     public T Value<T>  \n     { \n         get {  return /*Something cast to a T */ ; }     \n     }\n}	0
7460194	7453903	read user profile by username	foreach (string name in q)\n{\n     ProfileBase pb = ProfileBase.Create(name);\n     string s = pb.GetPropertyValue("Fullname").ToString();\n}	0
4304356	4304281	Create web service proxy in Visual Studio from a WSDL file	>wsdl.exe [path To Your WSDL File]	0
5729869	5729572	Eliminate consecutive duplicates of list elements	List<string> results = new List<string>();\nforeach (var element in array)\n{\n    if(results.Count == 0 || results.Last() != element)\n        results.Add(element);\n}	0
12140540	12140456	Change text in regex to upper-case	a = Regex.Replace(a, @"<(.|\n)*?>", m=>m.Value.ToUpper());	0
5869262	2203054	Loading Bloomberg Api Data Using VBA Access Program	Element fields = request.GetElement("fields");\nfields.AppendValue("PX_LAST");\nfields.AppendValue("VOLUME_AVG_30D");\nsession.SendRequest(request,null);	0
12833387	12833329	i want to find out how many threads maximum use in dual core using C#	Environment.ProcessorCount	0
6251217	6250998	c# Ordering Variable data using a drop down list	List<DT_Product> products = new List<DT_Product>();\n        if (DDL_Order.SelectedIndex == 0) { \n            products = product.OrderByDescending(v => v.Sale_Price).ToList(); \n        } else if (DDL_Order.SelectedIndex == 1) {\n            products = product.OrderBy(v => v.Sale_Price).ToList(); \n        }\n\n\n        LV_Products.DataSource = products; \n        LV_Product.DataTextField = "ProductName"; \n        LV_Product.DataValueField = "ProductID";\n        LV_Products.DataBind();	0
2303162	2303023	Linq to Entities : How to filter master table rows based on child rows properties	var q = from p in db.Persons\n        join ev in db.Events on p.Id equals ev.PersonId\n        where ev.SomeId == 4\n        select p;	0
28706076	28670913	Local Database for Windows Phone 8	public class MyDataContext : DataContext\n{\n    private static MappingSource mappingSource = new AttributeMappingSource();\n\n    public Table<Person> People;\n    public Table<Item> Items;\n\n    // pass the connection string to the base class.\n    public MyDataContext() : base("DataSource=isostore:/data.sdf", mappingSource)\n    {\n    }\n\n    ~MyDataContext()\n    {\n        Dispose(false);\n    }\n}\n\nMyDataContext db = new MyDataContext();\n\n// do stuff here\n\ndb.SubmitChanges();	0
8133132	8120008	Cell border in table	for (int n = 0; n < currentRow.Cells.Count; n++ ) \n{ \n    currentRow.Cells[n].BorderThickness = new Thickness(0, 2, 1, 0); \n    currentRow.Cells[n].BorderBrush = Brushes.Black; \n}	0
11729496	9993281	Visio Page Find Shape by Name without exceptions	Shape waterMarkRect = null;\ntry { \n    waterMarkRect = page.Shapes["DraftText"];\n}\ncatch (Exception){\n}\n\nif (waterMarkRect == null)\n{\n   waterMarkRect = page.DrawRectangle(0, 0, 50, 15);\n   waterMarkRect.Name = "DraftText";\n   waterMarkRect.NameU = waterMarkRect.Name;\n   waterMarkRect.Text = "INCONSISTANT";\n\n   Layer wMarkLayer = page.Layers["WMark"] ?? page.Layers.Add("WMark");\n   wMarkLayer.Add(waterMarkRect, 0);\n}	0
25121400	25121250	Create a new browser session using jQuery	if (Session["someData"] != null)\n        Session.Remove("someData");	0
11728641	11726501	How do I implement a circular buffer in a List of SelectListItems?	List<SelectListItem> month = Framework.Enums.Month_List().Select(T => new \n     SelectListItem() { Text = T.Key, Value = T.Value.ToString() }).ToList();\n        //make the previous month as "selected"\n        int currentMonth = DateTime.Now.Month;\n        if(currentMonth == 1){\n            month.Find(x=>x.Value == 12).Selected = true;\n        }else{\n           month.Find(x=>x.Value == ((currentMonth - 1).ToString())).Selected = true;\n        }\n        return month;	0
14260287	14195477	how to generate a .txt file from sql server and then print it	EXEC xp_cmdshell 'bcp "SELECT * FROM [yourDatabase]..[yourTable]" queryout "C:\Folder\archive.txt" -T -w  -t ,'	0
5806282	5806238	Connecting arrow shape in to a String	String str = "MSFT (26.00) ?)";\n   Console.WriteLine(str);	0
31051110	31042478	Passing two parameters to controller with @Hml.ActionLink, but the second parameter value is always null	[Route("{itemID:int}/{scaleID:int}", Name = "DeleteItemTest")]\npublic ActionResult DeleteItemTest(int? itemID, int? scaleID)	0
3122618	3122342	How to parse a SQL Query statement for the names of the tables	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing gudusoft.gsqlparser;\n\nnamespace GeneralSqlParserTest\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            TGSqlParser sqlparser = new TGSqlParser(TDbVendor.DbVMssql);\n\n            sqlparser.SqlText.Text = "SELECT * FROM Customers c, Addresses a WHERE c.CustomerName='foo'";\n            sqlparser.OnTableToken += new TOnTableTokenEvent(OnTableToken);\n\n            int result = sqlparser.Parse();\n            Console.ReadLine();\n        }\n\n        static void OnTableToken(object o, gudusoft.gsqlparser.TSourceToken st, gudusoft.gsqlparser.TCustomSqlStatement stmt)\n        {\n            Console.WriteLine("Table: {0}", st.AsText);\n        }\n    }\n}	0
11269062	11264455	Automapper with base class and different configuration options for implementations	Mapper.CreateMap<BaseModel, DataDastination>()\n    .Include<Car, DataDastination>()\n    .Include<Camper, DataDastination>();//.ForMember(general mapping)\nMapper.CreateMap<Car, DataDastination>();//.ForMember(some specific mapping)\nMapper.CreateMap<Camper, DataDastination>();//.ForMember(some specific mapping)	0
20879976	20879834	Parse date of ISO 8601 value 24:00:00 fails	using System;\nusing NodaTime;\nusing NodaTime.Text;\n\nclass Test\n{\n    static void Main()\n    {\n        string text = "2007-04-05T24:00";\n        var pattern = LocalDateTimePattern.CreateWithInvariantCulture\n             ("yyyy-MM-dd'T'HH:mm");\n        var dateTime = pattern.Parse(text).Value;\n        Console.WriteLine(pattern.Format(dateTime)); // 2007-04-06T00:00\n    }\n}	0
18527382	18527271	Date validation startdate to from date	var startdatevalue = "07/03/2013".split('/');\nvar todatevalue = "05/06/2013".split('/');\nvar t=Date.parse(todatevalue[2]+"/"+todatevalue[1]+"/"+todatevalue[0]);\nvar f=Date.parse(startdatevalue[2]+"/"+startdatevalue[1]+"/"+startdatevalue[0]);\nif (f > t) {\n console.log("here");\n}	0
28351899	28351256	What's wrong with this route	namespace Foo.Controllers\n{\n    [RoutePrefix("api/route")]\n    public class SnoconesFooBarController : BaseApiController\n    {\n        /// <summary>\n        /// Asks for a new foo to be created to the given subnet with the specific bar named\n        /// </summary>\n        /// <param name="fooData"></param>\n        /// <returns></returns>\n        [Route("newFoo/")]\n        public async Task<IHttpActionResult> PostNewFooForSpecificBar(FooRequestObject fooData)\n        {\n        }\n}	0
16414993	16413115	C# wpf proper way to bind DisplayIndex property of datagrid column	Mode=TwoWay	0
28854510	28853105	Customize DataGrid for Win CE Device	public void AddColumn(string hdr, string colName, int colWidth)\n{\n    DataGridTextBoxColumn tbc = new DataGridTextBoxColumn();\n    tbc.HeaderText = hdr;\n    tbc.MappingName = colName;\n    tbc.Width = colWidth;\n    myTblStyle.GridColumnStyles.Add(tbc);\n}	0
10458135	10458118	Wait one second in running program	dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;\ndataGridView1.Refresh();\nSystem.Threading.Thread.Sleep(1000);	0
10829937	10829524	How can I stop a dialog window from getting hidden	MyDialog d = new MyDialog();\nd.Owner = Application.Current.MainWindow;//or your owning window\nd.ShowDialog();	0
32366027	32365913	Number pyramid loops in c#	int altura; string space = ""; \nint cont2 = 0;\nConsole.Write("Dar altura: ");\naltura = int.Parse(Console.ReadLine());\nfor (int i = 1; i <= altura; i++)\n{\n    space = "";\n    for (int j = 1; j <= i; j++)\n    {\n        space = space + Convert.ToString(j);\n    }\n    for (int k = i - 1; k >= 1 ; k--)\n    {\n        space = space + Convert.ToString(k);\n    }\n    Console.WriteLine(space);\n}\nConsole.ReadKey();	0
4916619	4916578	How to mark the current method in a log file?	[MethodName("WriteXMLData")]	0
30069383	30069150	How to add data in array of strings in C#	var url = "http://www.amazon.com/black-series-650"; \n// var url = txt_OriginalUri.Text;\n\nvar tempUrl = url.Replace("http://", string.Empty);\nvar lastSlashIndex = tempUrl.IndexOf('/');\n\nvar resultUrl = "http://" + tempUrl.Insert(lastSlashIndex + 1, "en/");	0
26799285	26798977	Windows Phone- How to set LocalSettings first time?	var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;\n\n// Create a simple setting\n\nlocalSettings.Values["exampleSetting"] = "Hello Windows";\n\n// Read data from a simple setting\n\nObject value = localSettings.Values["exampleSetting"];\n\nif (value == null)\n{\n    // No data\n}\nelse\n{\n    // Access data in value\n}\n\n// Delete a simple setting\n\nlocalSettings.Values.Remove("exampleSetting");	0
26357506	26357358	Generic Dictionary as Parametre	private static void WriteSourceCredential<TValue>(XmlWriter pXmlWriter, string key, IDictionary<string, TValue> sourceCredentials, string value)\n{\n    TValue tempKeyValue;\n    pXmlWriter.WriteStartElement("SourceCredentials"); //Start HotelCredential\n    pXmlWriter.WriteElementString("Key", key);\n    sourceCredentials.TryGetValue(value, out tempKeyValue);\n    pXmlWriter.WriteElementString("Value", tempKeyValue.ToString()); // API Key\n    pXmlWriter.WriteEndElement(); //End HotelCredential\n}	0
29075273	29062144	make EF map byte array to binary instead of varbinary	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n        {\n            base.OnModelCreating(modelBuilder);\n\n            modelBuilder.Entity<MyEntity>().Property(x => x.BinaryProperty).HasMaxLength(LengthOfBinaryField).IsFixedLength();          \n        }	0
9738609	9738525	Upload PDF files through FTP in C Sharp	String uriString = Console.ReadLine();\n\n// Create a new WebClient instance.\nWebClient myWebClient = new WebClient();\nmyWebClient.Credentials=new NetworkCredential(username, password);\nConsole.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");\nstring fileName = Console.ReadLine();\nConsole.WriteLine("Uploading {0} to {1} ...",fileName,uriString);\n\n// Upload the file to the URI.\n// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.\nbyte[] responseArray = myWebClient.UploadFile(uriString,fileName);	0
28030522	28030440	Add items to list from IEnumerable using LinQ	vm.Role.AddRange(query.Roles.Select(r => new CreateUserViewModel.Item\n            {\n                Label = r.Label,\n                RoleNumber = r.RoleNumer\n            }));	0
12817458	12817035	How to get inner text from span which include other hidden span?	String inner = (from x in doc.DocumentNode.Descendants()\n                where x.Name == "span"\n                && x.Attributes["class"].Value == "r_rs"\n                select \n                      (from y in x.ChildNodes\n                       where y.Name == "#text"\n                       select y.InnerText).FirstOrDefault()\n                ).FirstOrDefault();	0
12020662	11985564	PowerShell Select-Object propertyName over an array of objects	this.WriteObject(stuff.ToArray(), true);	0
24024027	24018650	Color tracking using EMGUcv	// 1. Convert the image to HSV\nusing (Image<Hsv, byte> hsv = original.Convert<Hsv, byte>())\n{\n    // 2. Obtain the 3 channels (hue, saturation and value) that compose the HSV image\n    Image<Gray, byte>[] channels = hsv.Split(); \n\n    try\n    {\n        // 3. Remove all pixels from the hue channel that are not in the range [40, 60]\n        CvInvoke.cvInRangeS(channels[0], new Gray(40).MCvScalar, new Gray(60).MCvScalar, channels[0]);\n\n        // 4. Display the result\n        imageBox1.Image = channels[0];\n    }\n    finally\n    {\n        channels[1].Dispose();\n        channels[2].Dispose();\n    }\n}	0
16868646	16868409	C# - Click event sending a value	PictureBox[] picboxes = new PictureBox[result];\nfor (int i = 0; i < results; i++)\n{\n    picboxes[i] = new PictureBox();\n    picboxes[i].Name = (i+1).ToString();\n    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i);\n    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);\n}\n\nprivate void PictureBoxes_Click(object sender, EventArgs e)\n{\n    PictureBox p = (PictureBox)sender;\n    string j = p.Name;\n    label1.Text = j;\n}	0
29671326	29671219	how to store listbox values in a string variable in c#	string projectnames = "";\nbool firstValue = true;\n\nfor (int i = 0; i < ListBox2.Items.Count; i++)\n            {\n\n                if (ListBox2.Items[i].Selected == true || ListBox2.Items.Count > 0)\n                {\n                   if(!firstValue)\n                   {\n                      projectnames += ", " + ListBox2.Items[i].ToString();\n                   }\n                   else\n                   {\n                      projectnames += ListBox2.Items[i].ToString();\n                      firstValue = false;\n                   }\n\n                }\n\n            }	0
1263311	1263281	C# implement two different generic interfaces	public class MyClass : IEnumerable<KeyValuePair<string, string>>,\n                   IEnumerable<KeyValuePair<MyEnum, string>>\n{\n    IEnumerator<KeyValuePair<MyEnum, string>> IEnumerable<KeyValuePair<MyEnum, string>>.GetEnumerator()\n    {\n        // return your enumerator here\n    }\n\n    IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()\n    {\n        // return your enumerator here\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        var me = this as IEnumerable<KeyValuePair<string, string>>;\n        return me.GetEnumerator();\n    }\n}	0
29942568	29942275	Encrypting datagridview values C#	private void encryptAccounts()\n{\n    SimpleAES simpleAES1 = new SimpleAES();\n\n    // iterate over all DGV rows\n    for (int r = 0; r < dataGridViewAccounts.Rows.Count; r++)\n    {\n        if (dataGridViewAccounts[4, r].Value != null)\n        {\n          string password = dataGridViewAccounts[4, r].Value.ToString();\n          dataGridViewAccounts[4, r].Value = simpleAES1.EncryptToString(password);\n        }\n    }\n\n    // OR\n\n    foreach (DataGridViewRow row in dataGridViewAccounts.Rows)\n    {\n        if (row.Cells[4].Value != null)\n        {\n          string password = row.Cells[4].Value.ToString();\n          row.Cells[4].Value = simpleAES1.EncryptToString(password);\n        }\n    }\n}	0
12170178	12170110	How to insert a character after every n characters in a huge text file using C#?	void InsertACharacterNoStringAfterEveryNCharactersInAHugeTextFileUsingCSharp(\n    string inputPath, string outputPath, int blockSize, string separator)\n{\n    using (var input = File.OpenText(inputPath))\n    using (var output = File.CreateText(outputPath))\n    {\n        var buffer = new char[blockSize];\n        int readCount;\n        while ((readCount = input.ReadBlock(buffer, 0, buffer.Length)) > 0)\n        {\n            output.Write(buffer, 0, readCount);\n            if (readCount == buffer.Length)\n                output.Write(separator);\n        }\n    }\n}\n\n// usage:\nInsertACharacterNoStringAfterEveryNCharactersInAHugeTextFileUsingCSharp(\n    inputPath, outputPath, 3, Environment.NewLine);	0
26812072	26811151	How to force the designer to redraw the re-sizing rectangle?	this.BehaviorService.SyncSelection();	0
13482859	13482520	LINQ - Can't add column to result without changing multi-table grouping	var result = from v in vendor\n             from l in location\n             where l.Mnemonic == v.StMnemon\n             group v by new { l.State, v.Rating } into grp\n             orderby grp.Key.Rating ascending, grp.Key.State\n             select new {State = grp.Key.State, Rating = grp.Key.Rating, Kinds = grp.Sum(p=>p.Items)};\n\nforeach (var item in result)\n        Console.WriteLine("{0}\t{1}\t{2}", item.State, item.Rating, item.Kinds);	0
14105283	14105243	How do I put a textbox entry into while loop? C#	int counter = 1;\nint UserSuppliedNumber = 0;\n\n// use Int32.TryParse, assuming the user may enter a non-integer value in the textbox.  \n// Never trust user input.\nif(System.Int32.TryParse(TextBox1.Text, out UserSuppliedNumber)\n{\n   while ( counter <= UserSuppliedNumber)\n   {\n       Process.Start("notepad.exe");\n       counter = counter + 1;  // Could also be written as counter++ or counter += 1 to shorten the code\n   }\n}\nelse\n{\n   MessageBox.Show("Invalid number entered.  Please enter a valid integer (whole number).");\n}	0
4999747	4999734	How to add browse file button to Windows Form using C#	private void button1_Click(object sender, EventArgs e)\n{\n    int size = -1;\n    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.\n    if (result == DialogResult.OK) // Test result.\n    {\n       string file = openFileDialog1.FileName;\n       try\n       {\n          string text = File.ReadAllText(file);\n          size = text.Length;\n       }\n       catch (IOException)\n       {\n       }\n    }\n    Console.WriteLine(size); // <-- Shows file size in debugging mode.\n    Console.WriteLine(result); // <-- For debugging use.\n}	0
32965421	32965310	How to get active window that is not part of my application?	[DllImport("user32.dll")]\nstatic extern IntPtr GetForegroundWindow();\n\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
5060275	5056838	Getting valid IP from IPHostEntry	foreach (var addr in Dns.GetHostEntry(string.Empty).AddressList)\n{\n    if (addr.AddressFamily == AddressFamily.InterNetwork)\n        Console.WriteLine("IPv4 Address: {0}", addr)\n}	0
6179100	6178686	selecting a range of columns in database	StringBuilder query = new StringBuilder("Select ID,Name ")\n    DateTime begindate=DateTime.Parse("2-1-2011");\n    DateTime enddate=DateTime.Parse("6-1-2011");\n    DateTime tempDate = begindate;\n    while(tempDate<=enddate )\n    {\n        if(tempDate.DayOfWeek!=DayOfWeek.Sunday)\n        {\n            if (tempDate==begindate )\n            {\n                query.Append(",");\n            }\n            query.Append(","+tempDate.ToString("dd-MM-yyyy"));\n        }\n        tempDate = tempDate.AddDays(1);\n    }\n    query.Append(" From table Name");	0
22518861	22518724	SqlDataReader to populate struct	while (reader.Read())\n{\nnewEmp.eid = (int)reader("EID");\nnewEmp.firstname = (string)reader("FirstName");\n....\n}	0
18774769	18774748	Aligning string with spaces	str.PadLeft(35);\nstr.PadRight(35);\n\nstr = "BBQ and Slaw";\nConsole.WriteLine(str.PadLeft(15));  // Displays "   BBQ and Slaw".\nConsole.Write(str.PadRight(15));     // Displays "BBQ and Slaw   ".	0
32096557	32096417	How to retrieve the TFS queries of a user?	TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("Uri"));\ntfs.EnsureAuthenticated();\n\nWorkItemStore workitemstore = tfs.GetService<WorkItemStore>();\nQueryHierarchyProvider queryProvider = new QueryHierarchyProvider(workitemstore);\nProject project = workitemstore.Projects["MyProject"];\nvar queries = queryProvider.GetQueryHierarchy(project);	0
12462398	12461820	Flyout Control for Header menu Windows 8 using XAML	var frame = Window.Current.Content as Frame;	0
20664539	20664038	i need that on selection of drop down list value the check box controls should change dynamically in asp.net	protected void ddlStream_SelectedIndexChanged(object sender, EventArgs e)\n   {          \n    SqlConnection Con = new SqlConnection("connectionString");\n    string query = "select [column name] from [table name] where [column name] ="+ddlStream.SelectedItem.Value;\n\n    SqlCommand com = new SqlCommand(query, Con);\n    chkStream.DataValueField = "Columnname";\n    chkStream.DataTextField = "Columnname";\n    conn.Open();\n    DataReader reader1 = comm.ExecuteReader();\n    chkStream.DataSource = reader1;\n    chkStream.DataBind();   \n  }	0
21707156	21706747	Drag and drop files into my listbox	private void Form1_Load(object sender, EventArgs e)\n{\n    listBoxFiles.AllowDrop = true;\n    listBoxFiles.DragDrop += listBoxFiles_DragDrop;\n    listBoxFiles.DragEnter += listBoxFiles_DragEnter;\n}\n\nprivate void listBoxFiles_DragEnter(object sender, DragEventArgs e)\n{\n    if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;\n}\n\nprivate void listBoxFiles_DragDrop(object sender, DragEventArgs e)\n{\n    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n    foreach (string file in files)\n        listBoxFiles.Items.Add(file);\n}	0
21321452	21321327	Read bytes of a USB mass storage device	public static long getBytes(string letter)\n    {\n        ManagementObject disk = new ManagementObject(String.Format("win32_logicaldisk.deviceid=\"{0}:\"", letter));\n        disk.Get(); \n        return long.Parse(disk["Size"].ToString());\n    }	0
31345835	31343822	Is there a way to add tooltip to excel cell data in c#	Range.AddComment	0
1048980	1048888	How to update a BindingSource based on a modified DataContext	dbc.Refresh(RefreshMode.OverwriteCurrentValues, dbc.Customer);\nCustomers = dbc.Customer.ToDictionary(c => c.Id, c => c);\nbsJob.DataSource = jobManager.Jobs.Values.ToList();  //Assuming this statement was correct	0
25401631	25401147	C# Remove duplicates from two lists with multiple properties	var databaseList = database.Repository.GetAllElements();\nvar keys = databaseList.Select(x => new {x.key0, x.key1, x.key2}); \n\nlistOfElements.RemoveAll(\n                x =>\n                keys.Any(\n                k => k.key0 == x.key0 && \n                k.key1 == x.key1 && \n                k.key2 == x.key2 ));	0
1530656	1530572	How to do a long polling client in C#?	WebClientProtocol.Timeout	0
14044604	14044386	Using a BindingSource to link a DataSet to a DataGridView, but there's no data	var TableAdapter = new Reports2.ReportTest2TableAdapters.paymentsTableAdapter();\nTableAdapter.Fill(dsReportData.payments);	0
18194971	18182029	How to export dataGridView data Instantly to Excel on button click?	private void copyAlltoClipboard()\n    {\n        dataGridView1.SelectAll();\n        DataObject dataObj = dataGridView1.GetClipboardContent();\n        if (dataObj != null)\n            Clipboard.SetDataObject(dataObj);\n    }\n    private void button3_Click_1(object sender, EventArgs e)\n    {\n        copyAlltoClipboard();\n        Microsoft.Office.Interop.Excel.Application xlexcel;\n        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;\n        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;\n        object misValue = System.Reflection.Missing.Value;\n        xlexcel = new Excel.Application();\n        xlexcel.Visible = true;\n        xlWorkBook = xlexcel.Workbooks.Add(misValue);\n        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];\n        CR.Select();\n        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          \n    }	0
22916092	22914928	No action was found on the controller that matches the request	config.Routes.MapHttpRoute(\n  name: "ApiByAction",\n  routeTemplate: "api/products/GetListOfStudents/{username}/{password}",\n  defaults: new { controller = "products", action = "GetListOfStudents" }\n);	0
25872153	15576037	how to catch "previous/next" track change event in media player	if (e.newState == 8) // media ended\n\nif (e.newState == 6) // buffering\n\nelse if (e.newState == 3) // playing	0
19389050	19387018	Establishing a relationship between ViewModels in different windows	DataContext = childWindowViewModel(ParentViewModel);	0
5108751	5106497	get url from string	string adress = "hello www.google.ca";\n// Size the control to fill the form with a margin\nMatchCollection ms = Regex.Matches(adress, @"(www.+|http.+)([\s]|$)");\nstring testMatch = ms[0].Value.ToString();	0
29420132	29419514	Rotate a gameobject in Unity	void Update()\n{\n    var playerMapPos = GameObject.FindWithTag ("Player");\n    var playerWorldPos = GameObject.FindWithTag ("PlayerCube");\n    playerWorldPos.transform.rotation = playerMapPos.transform.rotation;\n}	0
1987466	1987379	Break out of a while loop that contains a switch statement	bool done = false;\nwhile (!done) \n{ \n    switch (MLTWatcherTCPIP.Get().ToUpper()) \n    { \n        case "": //scroll/display next inventory location \n            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown(); \n            break; \n        case "P": //scroll/display previous inventory location \n            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown(); \n            break; \n        case "D": //DONE (exit out of this Do Loop) \n            done = true;\n            break; \n        case "Q": //QUIT (exit out to main menu) \n            return; \n        default: \n            break; \n    } \n}	0
17884947	17884911	Get Data from Session["DTable"] in Next Page and Display in Gridview	DataTable newDataTable = (DataTable)Session["DTable"];\nnewDataTable.Rows[0]["<ColumnName>"].ToString();	0
7887919	7887899	cannot convert string to target type system nullable datetime	if(SubscriptionStartDate.HasValue)\n{\n    String myValue = SubscriptionStartDate.Value.ToString();\n}	0
4058877	4058738	How to convert hex to string?	string input="20|3d|43|46|3d|46|30|3d|45|38|3d|45|32|3d|45|35|3d|46|32|0d|0a|0d|0a|2e|0d|0a";\nbyte[] bytes=input.Split('|').Select(s=>byte.Parse(s, System.Globalization.NumberStyles.HexNumber)).ToArray();\nstring text = Encoding.GetEncoding(1251).GetString(bytes);\n\nStringBuilder text2=new StringBuilder();\nfor(int i=0;i<text.Length;i++)\n{\n  if (text[i]=='=')\n  {\n    string hex=text[i+1].ToString()+text[i+2].ToString();\n    byte b=byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);\n\n    text2.Append(Encoding.GetEncoding(1251).GetString(new byte[]{b}));\n    i+=2;\n  }\n  else\n  {\n    text2.Append(text[i]);\n  }\n}	0
16084420	16067977	AVIReader - taking too long to save frames	AVIReader reader = new AVIReader();\n List<Bitmap> ImagemMain = new List<byte[]>();\n reader.Open(_rootPath + Path.GetFileName(_arqs[0]));\n while (reader.Position - reader.Start < reader.Length)\n {\n        using (var aux = reader.GetNextFrame())\n        {\n             using (var r = new Bitmap(640, 480))\n             {\n                   using (var g = Graphics.FromImage(r))\n                   {                                               \n                       g.DrawImage(aux, new Rectangle(0, 0, aux.Width, aux.Height));                                                   \n                       ImagemMain.Add((Bitmap)r.Clone());\n                   }\n\n             }\n         }\n  }	0
12406785	12406750	Find item in generic list by specifying multiple condition	CartItem Item = Items.Find(c => (c.ProductID == ProductID) && (c.ProductName == "ABS001"));	0
1009006	1008966	C# How to add placement variable into a resource string	var newString = String.Format(resources.jimstring, xmlscript);	0
489876	489805	c# reference variable mem allocation	String s = "123";	0
3923113	3923082	How to add data to DataGridView	this.dataGridView1.Rows.Add("1", "XX");	0
16080422	16066510	Send files between wp8 and windows rt	Windows.Networking.Sockets.StreamSocketListener listener = new Windows.Networking.Sockets.StreamSocketListener();                    \nlistener.ConnectionReceived += async (_, args) =>\n{\n    var w = new Windows.Storage.Streams.DataWriter(args.Socket.OutputStream);\n    w.WriteInt32(42);\n    await w.StoreAsync();\n};\nawait listener.BindEndpointAsync(new Windows.Networking.HostName("127.0.0.1"), "55555");\nvar clientSocket = new Windows.Networking.Sockets.StreamSocket();\nawait clientSocket.ConnectAsync(new Windows.Networking.HostName("127.0.0.1"), "55555");\n\nvar r = new Windows.Storage.Streams.DataReader(clientSocket.InputStream);\nawait r.LoadAsync(4);\nvar res = r.ReadInt32();\nclientSocket.Dispose();\nSystem.Windows.MessageBox.Show(res.ToString(), "The Ultimate Question of Life, the Universe, and Everything", System.Windows.MessageBoxButton.OK);	0
14162134	14161648	Linq expression to select rows when no other row in the table matches a condition	var items = itemsTable.Where(o => !o.Test2 && \n    !itemsTable.Any(x => x.Name == o.Name && x.Group == o.Group && x.Test2));	0
8094610	8093029	Generated CS class from xml schema	StringReader sr = new StringReader(xml); \n    //XmlTextReader xtr = new XmlTextReader(sr); \n    XmlReaderSettings settings = new XmlReaderSettings(); \n    settings.Schemas.Add("", "schemas\\SimWniosekApl_v2.0.xsd"); \n    settings.ValidationType = ValidationType.Schema; \n\n    XmlReader reader = XmlReader.Create(xtr,settings); \n    XmlDocument document = new XmlDocument(); \n    document.Load(reader); \n\n    ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler); \n    document.Validate(eventHandler);	0
4626464	4626016	How to detect if T is IEnumerable<T2>, and if so get type of T2?	Type enumerableType = type.GetInterfaces()\n            .Where(t => t.IsGenericType)\n            .Where(t => t.GetGenericTypeDefinition() == typeof(IEnumerable<>))\n            .Select(t => t.GetGenericArguments()[0])\n            .FirstOrDefault();	0
11824391	11824362	C# get and set property by variable name	var propInfo = info.GetType().GetProperty(propertyName);\nif (propInfo != null)\n{\n    propInfo.SetValue(info, value, null);\n}	0
3197858	3197849	How do I specify multiple generic type constraints on a single method?	public void foo<TTypeA, TTypeB>() where TTypeA : class, A \n                                   where TTypeB : class, B	0
15229831	15156776	Removing .Diffuse colours from an FBX model	((Model)flagNode.Model).UseInternalMaterials = true;	0
20870971	20870884	Update the model from the view model	class ViewModel:INotifyPropertyChanged\n{\n private DefineAddinModel model;\n\n    public string URL\n    {\n        get { return model.URL;  }\n        set\n        {\n            if (value != model.URL)\n            {\n                model.url = value;\n                OnPropertyChanged("URL");\n            }\n        }\n    }\n\n    public string TemplateType\n    {\n        get { return model.TemplateType;  }\n        set\n        {\n            if (value != model.TemplateType)\n            {\n                model.TemplateType = value;\n                OnPropertyChanged("TemplateType");\n            }\n        }\n    }	0
1114693	1114679	Two Dimension NSMutableArray help?	NSString *hello = @"Hello World";\nNSMutableArray *insideArray = [[NSMutableArray alloc] initWithObjects:hello,nil];\nNSMutableArray *outsideArray = [[NSMutableArray alloc] init];\n[outsideArray addObject:insideArray];\n// Then access it by:\nNSString *retrieveString = [[outsideArray objectAtIndex:0] objectAtIndex:0];	0
12305103	12302683	Create a custom address book for Outlook 2010 programmatically	Outlook.Folder contacts = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;\nOutlook.Folder addressBook = contacts.Folders.Add("Business Contacts", Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;\naddressBook.ShowAsOutlookAB = true; // force display in Outlook Address Book\nOutlook.ContactItem contact = addressBook.Items.Add();\ncontact.FullName = "Custom Industries, Inc.";\ncontact.Email1Address = "sales@customindustries.com";\ncontact.Save();	0
9163746	9163503	Display dynamic images in a flash file	var imgLoader:Loader = new Loader();\nimgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageHasBeenLoaded);\nimgLoader.load(new URLRequest("imagePath/from/database.jpg"));\n\npublic function imageHasBeenLoaded(e:Event) {     \n      //Get the loaded bitmap image, do what you want with it from here.\n      var img:Bitmap = Bitmap(e.target.content); \n}	0
18813399	18813007	Change button state located in style resources from codebehind	//button can be reused everywhere (including inside your OnShowPopupButtonClick function)\nButton myPopupButton;\n\npublic myPopupButton_Loaded(object sender, RoutedEventArgs e) { \n    myPopupButton=sender as Button;\n    if ((this.myPopup.IsOpen))\n    {\n        VisualStateManager.GoToState(myPopupButton, "Pressed", true);\n    }\n}	0
10892878	10892633	How to Read dates in text file using C#	//init datetime list for log entries\nList<DateTime> logDates = new List<DateTime>();\n\n//Define regex string\nstring pattern = @"(?<logDate>(\d){4}-(\d){2}-(\d){2}\s(\d){2}:(\d){2}:(\d){2})";\nRegex reg = new Regex(pattern);\n\n//read log content\nstring logContent = File.ReadAllText("test.log");\n\n//run regex\nMatchCollection matches = reg.Matches(logContent);\n\n\n//iterate over matches\nforeach (Match m in matches)\n{\n    DateTime logTime = DateTime.Parse(m.Groups["logDate"].Value);\n    logDates.Add(logTime);\n}\n\n//show first and last entry\nConsole.WriteLine("First: " + logDates.First());\nConsole.WriteLine("Last: " + logDates.Last());	0
5043559	5043521	insert javascript only on page postback	ClientScriptManager.RegisterClientScriptBlock	0
1776767	1776739	How to expose internal System.Array	instance.SetX(int index, T value);\nT val = instance.GetX(int index);	0
18918775	18918532	Adding data to an existing xml file	XmlDocument xd = new XmlDocument();\nxd.Load("ServerPaths.xml");\n\nXmlNode rootNode = xd.DocumentElement;\nXmlNode serverPathNode = xd.CreateElement("ServerPath");\nserverPathNode.InnerText = txtNewServerPath.Text; // Your value\n\nrootNode.AppendChild(serverPathNode);\n\nxd.Save("ServerPaths.xml");	0
27550385	27550255	How to unit test string extension method	StringExtensions.Replace(str, dict)	0
3458902	3457514	Specific change-info in a sharepoint list/listitem	public static void AddEvent(MyCustomBeanClass e, SPSite site)\n{\n    StringWriter sw = new StringWriter();\n    XmlSerializer xs = new XmlSerializer(typeof(MyCustomBeanClass));\n    xs.Serialize(sw, e);\n    site.Audit.WriteAuditEvent(SPAuditEventType.Custom, "MyCustomAuditing", sw.ToString());\n}	0
7705553	7705234	How to Clear() controls without causing a memory leak	for (int ix = Controls.Count-1; ix >= 0; --ix) Controls[ix].Dispose();	0
7696523	7696369	Loading a page with non-default constructor into Frame	//xaml\n<Page x:Class="WpfApplication1.Something"\n        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n        Title="MainWindow">\n    <StackPanel>\n        <Button Click="Button_Click" Content="click"/>\n        <Frame Content="{Binding}"/>\n    </StackPanel>\n</Page>\n\n//codebehinde\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    // Instantiate the page to navigate to\n    Page1 page = new Page1("Hello!");\n    this.DataContext = page;\n}	0
8500168	8487549	The query contains references to items defined on a different data context	Func<PageDBDataContext,int,int,string, IQueryable<SepiaWEB.Models.Pages.Page>> s_compiledQuery2 = CompiledQuery.Compile<PageDBDataContext, int,int,string, IQueryable<SepiaWEB.Models.Pages.Page>>(\n            (ctx, OrganizationId, pagesids,filte) => from pag in ctx.Pages\n                        join pgmt in ctx.PagesMeta\n                       on pag.int_PageId equals pgmt.int_PageId\n                       where (pag.int_OrganizationId == OrganizationId && pag.int_PageId == pagesids\n                        && pag.int_PostStatusId == 2) &&\n                        (pgmt.vcr_MetaKey.ToLower().Contains(filte) && pgmt.vcr_MetaValue.Contains("true"))\n                        select pag );	0
1078553	1078537	C# Check a word exists in a string	string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));\nif (Regex.IsMatch(yourString, regexPattern)) {\n    // word found\n}	0
10265818	10265785	how to update a field table by linq in C#?	var result = db.tables\n    .Where(x => (x.B!=null || x.B.Length > 0)\n    .Select(x => \n        new \n        {\n           A = x.A, \n           B = x.B[0]\n        });	0
5003791	4652347	Dynamically binding of Dataset to RDLC Reports	if (!Page.IsPostBack)\n{\n//your binding codes here\n}	0
23544746	23543636	Get value from dataset cell	string val = null;\nforeach (DataTable dt in ds.Tables)\n{\n    foreach (DataRow dr in dt.Rows)\n    {\n        foreach (DataColumn dc in dt.Columns)\n        {\n            if(dc.ColumnName=="Name")\n              {\n                    //save\n              }\n        }\n    }\n}	0
4450666	4450650	Using foreach loop to iterate through two lists	foreach(object o in a.Concat(b)) {\n o.DoSomething();\n}	0
17933322	17902628	How to reset form values after closing?	private void LoginBtn_Click(object sender, EventArgs e)\n{\n     Welcome NewWelcomeForm = new Welcome();\n     his.Hide();\n     NewWelcomeForm.ShowDialog();\n}	0
6325714	6325443	Silverlight: IsolatedStorageSettings to persist data between page refresh	IsolatedStorageSettings.ApplicationSettings.Save();	0
13631442	13630967	Difference between two bubble sort algorithms	for (int j = 0; j < input.Length - 1 - i; j++)	0
30937938	30936465	C# - If I use backgroundWorker nothing is displayed in the treeView control	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n{\n    int[] numbers = new int[5];\n    numbers[0] = 1;\n    numbers[1] = 2;\n    numbers[2] = 3;\n    numbers[3] = 4;\n    numbers[4] = 5;\n\n    treeView1.Invoke((Action)delegate \n    {\n       foreach (int element in numbers)\n       {\n           treeView1.Nodes.Add(element.ToString());\n       }\n   });\n\n   button1.Invoke((Action) delegate { button1.Enabled = true; });\n}	0
23572518	23562092	Getting a byte array from ImageView	// Find image view.\n    var imgView = this.FindViewById<ImageView>(Resource.Id.imageView);\n    // Set some image\ncontent.imgView.SetImageDrawable(this.Resources.GetDrawable(Resource.Drawable.Icon)); imgView.BuildDrawingCache ();\n\n    // Get the bitmap content of the image view.\n    Bitmap bitmap = imgView.DrawingCache;\n    // Save as PNG to disk.\n    string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "image.png");\n    using (var stream = File.OpenWrite(path))\n    {\n        bitmap.Compress (Bitmap.CompressFormat.Png, 100, stream);\n    }\n    Console.WriteLine("Image saved to {0}", path);	0
2247808	2247744	Find duplicates between arrays	int[] same = a.Intersect(b).ToArray(); ;\nint[] diff = a.Union(b).Except(same).ToArray();\nint[] c = new int[] { diff[0], same[0], same[1], diff[1] };	0
1510920	1510585	Get users full name from Machine Context	public static UserPrincipal GetUserPrincipal(String userName)\n        {\n            UserPrincipal up = null;\n\n            PrincipalContext context = new PrincipalContext(ContextType.Domain);\n            up = UserPrincipal.FindByIdentity(context, userName);\n\n            if (up == null)\n            {\n                context = new PrincipalContext(ContextType.Machine);\n                up = UserPrincipal.FindByIdentity(context, userName);\n            }\n\n            if(up == null)\n                throw new Exception("Unable to get user from Domain or Machine context.");\n\n            return up;\n        }	0
11395130	11390750	hand writing recognition in c# metro style app	IReadOnlyList<String> text;\n    string finalt = "";  //for space\n    private async void Recognize_Click(object sender, RoutedEventArgs e)\n    {\n        IReadOnlyList<InkRecognitionResult> x = await _inkManager.RecognizeAsync(InkRecognitionTarget.All);\n        foreach (InkRecognitionResult i in x)\n        {\n            text = i.GetTextCandidates();\n            finalt += " " + text[0];\n            res.Text = finalt;  //res is the x:Key for the text block\n        }\n    }	0
951	930	How do I connect to a database and loop over a recordset in C#?	using System.Data.OleDb;...using (OleDbConnection conn = new OleDbConnection()){    conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";    using (OleDbCommand cmd = new OleDbCommand())    {        conn.Open();        cmd.Connection = conn;        cmd.CommandText = "Select * from yourTable";        using (OleDbDataReader dr = cmd.ExecuteReader())        {            while (dr.Read())            {                Console.WriteLine(dr["columnName"]);            }        }    }}	0
9522385	9521161	How do I get the Hwnd / Process Id for a Word Application, and set as Foreground Window	System.Diagnostics.Process[] processArray =  System.Diagnostics.Process.GetProcessesByName("WinWord");\n        System.Diagnostics.Process word = processArray[0];\n        SetForegroundWindow(word.MainWindowHandle);	0
7939179	7939146	How to 'foreach' a column in a DataTable using C#?	DataTable dtTable;\n\nMySQLProcessor.DTTable(mysqlCommand, out dtTable);\n\n// On all tables' rows\nforeach (DataRow dtRow in dtTable.Rows)\n{\n    // On all tables' columns\n    foreach(DataColumn dc in dtTable.Columns)\n    {\n      var field1 = dtRow[dc].ToString();\n    }\n}	0
15887727	15887583	Getting image from web	Image i = new Image();\nBitmapImage src = new BitmapImage();\nsrc.BeginInit();\nsrc.UriSource = new Uri("http://i.stack.imgur.com/glbMA.jpg");\nsrc.EndInit();\ni.Source = src;	0
26167868	26163321	How to specify an ETag in the .Net client library of the YouTube API v3	gapi.client.request	0
8632361	8632264	Find all words that have all characters of a given word	var signature = 0;\nforeach (var c in word.ToUpperCase()) {\n    signature |= (1<<(c-'A'));\n}	0
31995143	31978477	Create webjobs programmatically in Azure	d:\home\site\wwwroot\App_Data\jobs\{webjob type}\{webjob name}	0
32314788	32314045	Bind linq data to dropdownlist	notesdd = new DropDownList();\nnotesdd.DataSource = querydd.ToList();\nnotesdd.DataBind();	0
4420834	4420822	how to calculate the working days in between two different dates in asp.net	DateTime start = new DateTime(2010, 12, 1);\nDateTime end = new DateTime(2010, 12, 31);\n\nint workdays = 0;\nDateTime aux = start;\nwhile(aux <= end)\n{\n    aux = aux.AddDays(1);\n    if (aux.DayOfWeek != DayOfWeek.Sunday)\n        workdays++;\n}\nyourLabel.Text = workdays.ToString();	0
6188002	6187944	How can i create dynamic button click event on dynamic button?	Button button = new Button();\nbutton.Click += (s,e) => { your code; };\n//button.Click += new EventHandler(button_Click);\ncontainer.Controls.Add(button);\n\n//protected void button_Click (object sender, EventArgs e) { }	0
14219209	14218539	How to insert data from csv to access db if the column names and order is different	INSERT INTO EMP_DOWNLOAD (ID, Forename, LastName, Address, Zip_Code ) \nSELECT  ID, FName, LName, Address, Zipcode\nFROM [Text;Database=z:\docs\;HDR=yes].[importfilename.csv]	0
30762821	30762702	System.UnauthorizedAccessException occurs under Admin privileges with full access to folder	File.WriteAllText	0
5035853	5035731	How to create objects dynamically with arbitrary names?	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;\n\nnamespace WindowsFormsApplication6\n{\n    public partial class Form1 : Form\n    {\n        int i = 1;\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            var button = new Button { Text = string.Format("Button {0}", i) };\n            button.Click += new EventHandler(button_Click);\n            flowLayoutPanel1.Controls.Add(button);\n            i += 1;\n        }\n\n        void button_Click(object sender, EventArgs e)\n        {\n            Button button = (Button)sender;\n            button.Text = " clicked!";\n        }\n    }\n}	0
16252707	16252476	Trying to create a recursive method to list Logical dependencies in hierarchical order	public static List<DependencyObject> ListLogical( DependencyObject parent)\n{\n    var depList = new List<DependencyObject>\n    {\n        parent\n    };\n    foreach ( var child in LogicalTreeHelper.GetChildren( parent ).OfType<DependencyObject>() )\n    {\n        depList.AddRange( ListLogical( child ) );\n    }\n    return depList;\n}	0
29674679	19080778	Troubles with dynamic c# asp.net controls update	protected override void OnInit(EventArgs e)\n{\n     base.OnInit(e);\n     CreateControls();\n}	0
5739275	4550010	WCF UriTemplate for RESTful resource	[OperationContract(Name="Op1")]\n[WebGet(UriTemplate = "DoWork/")]\nint[] DoWork();\n\n[OperationContract(Name = "Op2")]\n[WebGet(UriTemplate = "DoWork/{id}")]\nint[] DoWork(string id);	0
25634826	25634668	Postback from Dynamic Content	public void Test()\n    {\n        System.Web.UI.HtmlControls.HtmlGenericControl p = new System.Web.UI.HtmlControls.HtmlGenericControl("p");\n        p.InnerHtml = @"<strong>Test</strong>";\n        // ...\n        ListItems.Controls.Add(p);\n        Button b = new Button();\n        b.ID = "cmdTest";\n        b.Text = "Test";\n        b.Click += new EventHandler(test_Click);\n        p.Controls.Add(b);\n    }\n\n    protected void test_Click(object sender, EventArgs e)\n    {\n       // ListItems.InnerHtml = "Test button clicked";\n        txtTestResults.Text = "Test button clicked at " + DateTime.Now.ToShortTimeString();\n    }	0
9109094	9100209	How can I get Appearance properties vlaues of my custom web part in sharepoint 2010	Unit width = this.Width;	0
17612924	17612853	Read text file block by block	ReadLine()	0
6081039	6081026	How to bind combobox to linq result value only?	DataTable acc= accessory.GetData();\n\nvar query = (from t in acc.AsEnumerable()\n\nselect new {\n\n       description=string.Format("{0},{1}",t["type"].ToString(), color = t["color"].ToString()) \n\n      }).Distinct().ToList();\ncmbAccessoryName.DataSource = query;	0
21792604	21792574	2D boolean array, check if array contains a false	bool[,] a = new bool[4,4]\n    {\n        {true, true, true, true},\n        {true, true, false, true},\n        {true, true, true, true},\n        {true, true, true, true},\n    };\n\n    if(a.Cast<bool>().Contains(false))\n    {\n        Console.Write("Contains false");\n    }	0
12201457	12201365	Programmatically remove a service using C#	ServiceInstaller ServiceInstallerObj = new ServiceInstaller(); \nInstallContext Context = new InstallContext("<<log file path>>", null); \nServiceInstallerObj.Context = Context; \nServiceInstallerObj.ServiceName = "MyService"; \nServiceInstallerObj.Uninstall(null);	0
13127299	13127196	XmlTextReader blocks application	public async void SOQuestion(string query)\n{\n    var searchUrl = "http://weather.service.msn.com/find.aspx?outputview=search&src=vista&weasearchstr=" + query;\n\n    WebClient wc = new WebClient();\n    string xml = await wc.DownloadStringTaskAsync(searchUrl);\n\n    var xDoc = XDocument.Parse(xml);\n\n    var results = xDoc.Descendants("weather")\n                        .Select(w => new\n                        {\n                            Location = w.Attribute("weatherlocationname").Value,\n                            Temp = w.Element("current").Attribute("temperature").Value,\n                            SkyText = w.Element("current").Attribute("skytext").Value,\n\n                        })\n                        .ToList();\n\n    dataGridView1.DataSource = results;\n}	0
11786751	11785837	Exception import Excel data to SQL Server	public static bool saveFile(this Byte[] fileBytes, string filePath, string fileName, int category, string uploadedBy)\n{\n    try\n    {\n        FileStream fileStream = new FileStream(filePath + "/" + fileName, FileMode.Create, FileAccess.ReadWrite);\n        fileStream.Write(fileBytes, 0, fileBytes.Length);\n        fileStream.Dispose();\n        fileStream.Close();\n        FileUpload fileUpload = new FileUpload();\n        return fileUpload.createFileUpload(fileName, category, filePath, uploadedBy, DateTime.Now);\n    }\n    catch (Exception ex)\n    {\n        mLog.logMessage(ex, HttpContext.Current.Request.Url.ToString(), 1);\n        return false;\n    }\n}	0
24367700	24367189	How to apply binding to ApplicationBarMenuItem text in wp7?	public MainPage()\n{\n    InitializeComponent();\n\n    ApplicationBar = new ApplicationBar();\n\n    ApplicationBar.Mode = ApplicationBarMode.Default;\n    ApplicationBar.Opacity = 1.0; \n    ApplicationBar.IsVisible = true;\n    ApplicationBar.IsMenuEnabled = true;\n\n    ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem();\n    menuItem1.Text = "menu item 1";\n    ApplicationBar.MenuItems.Add(menuItem1);\n}	0
10937299	10937181	How to converting back from number format?	var text = (1234,567).ToString("c");\n\nvar number = double.Parse(text, System.Globalization.NumberStyles.Currency, cultureInfo);	0
19940920	19940813	How to query a child object	var query = QueryableSQL().Where(employee => \n    employee.Interests.Any(interest => interest.Name ==  "Chess"));	0
17173235	17173061	Is there a way to set a variable accessible for different class and function in C#?	string path = Properties.Settings.Default.PathToExport;	0
31294377	31279560	Post image into Slack using Incoming Webhook C#	string json = new JavaScriptSerializer().Serialize(new\n            {\n                username = userName,\n                text = message,\n                icon_emoji = icon,\n                channel = channelName,\n                attachments = new []{ new {image_url = "www.imageurl.com", title = "image as of " + DateTime.Now}}\n            });	0
7406489	7406346	join using lambda expressions and retrieving the data	member_Id = a.b.c.member_Id	0
33609920	33609772	C# - Getting file names starting with a specific format in a directory	string pattern = @"^sly_";\n\n  var matches = Directory\n    .GetFiles(@"D:\mypath")\n    .Where(path => Regex.IsMatch(Path.GetFileName(path), pattern));\n\n  Console.Write(String.Join(Environment.NewLine, matches));	0
32892737	32892736	How do I upload a resource file and then access that file in an Azure Cloud Service?	string appRoot = Environment.GetEnvironmentVariable("RoleRoot");\n\n  string pathToFiles = Path.Combine(appRoot + @"\", @"approot\" + "anyFolderNameIUsed\");	0
20817512	20817263	How can i add item in listbox each time that an button was clicked?	**Constructor**\n    public Form1() \n    {\n        InitializeComponent();\n        button2.Click += new EventHandler(button1_Click);\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        listBox1.Items.Add(textBox1.Text);\n    }	0
7225931	7223796	WebBrowser Control & Navigate help	void WaitBrowserLoading()\n    {\n        while (webBrowser1.IsBusy)\n            Application.DoEvents();\n        for (int i = 0; i < 500; i++)\n            if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)\n            {\n                Application.DoEvents();\n                System.Threading.Thread.Sleep(10);\n            }\n            else\n                break;\n        Application.DoEvents();\n    }	0
30491637	30491365	How do I move a Rigidbody towards target without adding force or velocity?	double magnitude = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y,2) + Math.Pow(z, 2));	0
29197749	29197648	enter carriage return but don't break a word	StringBuilder s = new StringBuilder();\n            char[] t = txtString.ToArray();\n            int i = 0;\n            foreach (char c in t)\n            {\n                s.Append(c);\n                if (i > 4 && c == ' ')\n                {\n                    s.Append("\n");\n                    i = 0;\n                }\n                i++;\n            }\nreturn s.ToString();	0
21910504	21910328	What method / How to replace two consecutive same characters with the single character has different condition	builder.Replace("a", "aa");\nbuilder.Replace("b", "b");\nbuilder.Replace("bb", "b");\nbuilder.Replace("cc", "~");\nbuilder.Replace("c", "");\nbuilder.Replace("~", "cc");	0
17056834	17056495	xml conditional XElement creation	from ph in p.PhoneNumbers where !String.IsNullOrEmpty(ph)	0
9835737	9827414	Excel Bar chart show Y Axes C#	Axis yAxes = (Axis)xlChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary);\nyAxes.MajorTickMark = XlTickMark.xlTickMarkCross;\nyAxes.TickLabelPosition = XlTickLabelPosition.xlTickLabelPositionLow;	0
33301905	33301484	C# download file from web using URL and xpath	WebClient client = new WebClient();\nstring resource = client.DownloadString("http://photography.nationalgeographic.com/photography/photo-of-the-day/");\nHtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();\nhtml.LoadHtml(resource);\nvar imgDiv = html.DocumentNode.SelectSingleNode("//*[contains(@class,'primary_photo')]");\nvar imgSrc = imgDiv.SelectSingleNode("//img/@src");\nstring relativePath = imgSrc.GetAttributeValue("src", "");	0
13142187	13137892	Raise an event after ListBox.Items has changed	private void IngredientsListBox_LayoutUpdated(object sender, EventArgs e)\n    {\n        if (ingredientsListLoaded)\n        {\n            activatePieceQuantity();\n            ingredientsListLoaded = false;\n        }\n    }	0
11028393	11028206	Open associated documents (PDFs, DOCS, etc) from Browser	Protected Sub gE_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gE.RowDataBound\n    Dim lapt_Trig As New AsyncPostBackTrigger\n    lapt_Trig.ControlID = e.Row.FindControl("MyButton").ID     \n    up_UpdatePanel.Triggers.Add(lapt_Trig)    \nEnd Sub	0
485983	455018	Extending the list of supported image formats in GDI+	Software\Microsoft\Imaging\Codecs	0
11698961	11698908	Trimming down a switch statement	switch (e.ClickedItem.Text.ToLower())\n{\n    case "find":\n        Find find = new Find(customTextBox1);\n        find.Show();\n        break;\n    case "undo": case "redo": case "cut": case "copy": case "paste": case "select all":\n        Type thisType = customTextBox1.GetType();\n        MethodInfo theMethod = thisType.GetMethod(e.ClickedItem.Text.ToLower());\n        theMethod.Invoke(customTextBox1, userParameters);\n        break;\n    case "delete":\n        customTextBox1.SelectedText = "";\n        break;\n    case "refresh":\n        RefreshData();\n        break;\n}	0
33755798	33755132	generate array of object with json and ASP MVC	var liste = new List<Dictionary<string, string>>();\nforeach(var site in sitesList)\n{\n    liste.Add(new Dictionary<string, string> { {site.Id.ToString(), site.RaisonSociale } } );\n}\n\nreturn Json(liste,\n  JsonRequestBehavior.AllowGet);	0
25765395	25764921	To compare Date and Datetime in ASP.NET mvc 3?	List<Meeting> meetings = db.Meetings.Where( m.date_meeting.Day.Equals(DateTime.Now.Day) &&\n                                     m.date_meeting.Month.Equals(DateTime.Now.Month) &&\n                                     m.date_meeting.Year.Equals(DateTime.Now.Year) && && x.langId == lang).ToList();	0
15330038	15329860	In C#, what is the best way to find gaps in a DateTime array?	public bool AreSameWeekdayEveryMonth(IEnumerable<DateTime> dates)\n{\n    var en = dates.GetEnumerator();\n    if (en.MoveNext())\n    {\n        DayOfWeek weekday = en.Current.DayOfWeek;\n        DateTime previous = en.Current;\n        while (en.MoveNext())\n        {\n            DateTime d = en.Current;\n            if (d.DayOfWeek != weekday || d.Day > 7)\n                return false;\n            if (d.Month != previous.Month && ((d - previous).Days == 28 || (d - previous).Days == 35))\n                return false;\n            previous = d;\n        }\n    }\n    return true;\n}	0
23652030	23652006	Add item to an anonymous list	myList.Insert(0, new { ProductName = "--All--", ProductId = 0, Priority = 0});	0
3310355	3310186	Are there any reasons to use private properties in C#?	private string _password;\nprivate string Password\n{\n    get\n    {\n        if (_password == null)\n        {\n            _password = CallExpensiveOperation();\n        }\n\n        return _password;\n    }\n}	0
4548646	4548636	Deactivating Outlook window for a custom form	ShowDialog()	0
19668945	19668636	Need help writing to a SQL Server CE table	Server Manager	0
5497703	5497572	Disable XML validation when using XDocument	// this line throws exception like yours\nXDocument xd = XDocument.Load(@"C:\test.xml");\n\n// works\nXDocument xd = XDocument.Load(new System.IO.StreamReader(@"C:\test.xml"));	0
3676921	3652451	Access remote registry key with C# in .Net MVC2	private static string GetLogonFromMachine(string machine)\n    {\n        //1. To read the registry key that stores this value. \n        //HKEY_Local_Machine\Software\Microsoft\Windows NT\CurrentVersion\WinLogon\DefaultUserName\n\n        RegistryKey rHive;\n\n        try\n        {\n            rHive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine);\n        }\n        catch (IOException)\n        {\n            return "offline";\n        }\n\n        var rKey = rHive.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon\\");\n\n        if (rKey == null)\n        {\n            return "No Logon Found";\n        }\n\n        var rItem = rKey.GetValue("DefaultUserName");\n\n        return rItem==null ? "No Logon Found" : rItem.ToString();\n    }	0
914284	912985	Modifying XMP data with C#	byte[] data = File.ReadAllBytes(path);\n... find & replace bit here ...\nFile.WriteAllBytes(path, data);	0
1749026	1748988	c# httpwebrequest to a web page iphone version	Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3	0
1589349	1589021	Passing parameters to crystal reports in C#	// Set datasource first\nmyDataReport.SetDataSource(...)\n// Assign Paramters after set datasource\nmyDataReport.SetParameterValue("MyParameter", "Hello");	0
21484489	21473427	Create a WCF Client wihout Configuration File	using System.ServiceModel;\n\nvar factory = new ChannelFactory<IMyServiceInterface>(\n    new BasicHttpBinding(), <-- or whatever binding your service uses\n    new EndpointAddress("http://MyServiceUrl"));\n\nvar proxy = factory.CreateChannel();	0
12419701	12419405	converting datetime from json to readable format	var dateString = "/Date(1346997005000)/";\nvar dx = new Date(parseInt(dateString.substr(6)));\n\nvar dd = dx.getDate();\nvar mm = dx.getMonth() + 1;\nvar yy = dx.getFullYear();\n\nif (dd <= 9) {\n    dd = "0" + dd;\n}\n\nif (mm <= 9) {\n    mm = "0" + mm;\n}\n\nvar displayDate = dd + "." + mm + "." + yy;	0
3492357	3492338	check if a values has been selected from dropdown in c#	if(ddCountries.SelectedIndex > -1)	0
3600638	3600589	RadioButton value to be changed everytime a linkbutton is clicked	protected void lnkAddLoc_Click(object sender, EventArgs e)\n{\n    if (rdoLoc1.Checked)\n        rdoLoc5.Checked = true;\n    else if (rdoLoc2.Checked)\n        rdoLoc1.Checked = true;\n    else if (rdoLoc3.Checked)\n        rdoLoc2.Checked = true;\n    else if (rdoLoc4.Checked)\n        rdoLoc3.Checked = true;\n    else if (rdoLoc5.Checked)\n        rdoLoc4.Checked = true;\n}	0
28012885	28012784	xml descendants looping issue in c#	XDocument doc;\n\n        using (Stream input = System.IO.File.OpenRead("XMLFile1.xml"))\n        {\n            doc = XDocument.Load(input);\n\n            XmlNamespaceManager nm = new XmlNamespaceManager(new NameTable());\n            XNamespace ns = doc.Root.GetDefaultNamespace();\n            nm.AddNamespace("ns", ns.NamespaceName);\n\n            foreach (var hostedService in doc.Root.XPathSelectElements("ns:HostedService",nm)) // loop through all events\n            {\n                if (hostedService.XPathSelectElement("ns:ServiceName", nm) != null)\n                {\n                    var service = hostedService.XPathSelectElement("ns:ServiceName",nm).Value;\n                }\n                if (hostedService.XPathSelectElement("ns:Url",nm) != null)\n                {\n                    var url = hostedService.XPathSelectElement("ns:Url",nm).Value;\n                }\n            }\n        }	0
30638916	30638763	Rotate MainCamera by z-angle after using an item	override public void Update(){\n    base.Update ();\n    if (this.activated) {       \n        Camera.main.transform.Rotate(Vector3.forward, 180);\n        this.activated = false;\n    }\n}	0
30281459	30281387	C# in Async Task change Label Text	private void setLabel1TextSafe(string txt)\n  { \n       if(label1.InvokeRequired)\n       {label1.Invoke(new Action(()=>label1.Text=txt)));return;}\n       label1.Text=txt;\n  }	0
5634609	5584005	MS Chart control - pie chart transparency	protected void Page_Load(object sender, EventArgs e)\n    {\n        pieChart.Series[0].Palette = ChartColorPalette.SemiTransparent;\n    }	0
31533585	31533389	Refresh IEnumerable to update month in Calendar	class ClassTest : INotifyPropertyChanged\n{\n    private IEnumerable<Day> myList;\n    public IEnumerable<Day> MyList\n    {\n        get { return myList; }\n        set\n        {\n            if (value != myList)\n            {\n                myList= value;\n                OnPropertyChanged("MyList");\n            }\n        }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n            handler(this, new PropertyChangedEventArgs(propertyName));\n    }\n}	0
32339142	32336489	How to get route name in htmlhelper?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nnamespace MvcApplication1\n{\n    public static class RouteCollectionExtensions\n    {\n        public static Route MapRouteWithName(this RouteCollection routes, string name, string url, object defaults)\n        {\n            Route route = routes.MapRoute(name, url, defaults);\n            route.DataTokens = new RouteValueDictionary();\n            route.DataTokens.Add("RouteName", name);\n\n            return route;\n        }\n    }\n\n\n    public class RouteConfig\n    {\n        public static void RegisterRoutes(RouteCollection routes)\n        {\n            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n            routes.MapRouteWithName(\n                "myRouteName",\n                "{controller}/{action}/{username}",\n                new { controller = "Home", action = "List" }\n\n                );\n        }\n    }\n}	0
22807186	22806933	Email validation expression	ValidationExpression="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@\n(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"	0
22358692	22337778	Upload image with textual information json and wcf	void Main()\n{   \n    string json = "{Title: 'Image title', Description: 'Description', Base64Data : 'iVBORw0KGgoAAAANSUhEUgAAAA0AAAAQCAYAAADNo/U5AAAACXBIWXMAAA......'}";\n    JavaScriptSerializer js = new JavaScriptSerializer();\n    var picture = js.Deserialize<Picture>(json);\n\n\n\n    // Now deserialize the Base64 encoded picture.\n    picture.Data = Convert.FromBase64String(picture.Base64Data);\n\n    File.WriteAllBytes(@"C:\test.png", picture.Data);\n}\n\nclass Picture\n{\n    public string Title {get; set;}\n    public string Description {get; set;}\n    public byte[] Data {get; set;}\n    public string Base64Data {get; set;}\n}	0
25012747	25011479	refresh Tab in Browser if already open, using a c# application	using System;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var browserPath = @"chrome";\n        RefreshBrowserTab(browserPath);\n    }\n\n    private static void RefreshBrowserTab(string browserPath)\n    {\n        var processName = Path.GetFileNameWithoutExtension(browserPath);\n        var processes = Process.GetProcessesByName(processName);\n        foreach (var process in processes)\n        {\n            SetForegroundWindow(process.MainWindowHandle);\n        }\n        SendKeys.SendWait("^r");\n    }\n\n    [DllImport("user32.dll")]\n    private static extern bool SetForegroundWindow(IntPtr hWnd);\n}	0
7362114	7362082	how to translate buttons in DialogResult in compact framework?	MessageBox.Show	0
4829139	4829110	C# - how to do encoding on string or char?	var myString = System.Text.Encoding.Unicode.GetString(myByteArray);	0
8850596	8850353	Deleting object from DB in Silverlight 4 RIA (Entities framework)	this.columnValidationRulesDomainDataSource.Load()	0
20612912	20612468	Making GTK# File Chooser to Select File Only	private void OpenOFD()\n{\n    Gtk.FileChooserDialog filechooser =\n        new Gtk.FileChooserDialog("Choose the file to open",\n            this,\n            FileChooserAction.Open,\n            "Cancel",ResponseType.Cancel,\n            "Open",ResponseType.Accept);\n\n    if (filechooser.Run() == (int)ResponseType.Accept) \n    {\n        System.IO.FileStream file = System.IO.File.OpenRead(filechooser.Filename);\n        file.Close();\n    }\n\n    filechooser.Destroy();\n}	0
32125798	32125385	Retrieving Windows device's DPI	Windows.Graphics.Display.DisplayInformation	0
30816615	30816513	How do I store an array of strings into another array of strings?	string[] newStringArray = new string[10];\nfor (int i = 0; i < oldStringArray.Length && i < newStringArray.Length; i++)\n{\n    newStringArray[i] = oldStringArray[i].firstName;\n    //             ^\n}	0
7299552	7299541	how to get variable from form load to action?	public partial class showCategory : Form\n{\n    string categoryId = null;\n\n    private void showCategory_Load(object sender, EventArgs e)\n    {\n        this.categoryId = "100";\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        textBox1.Text = this.categoryId;\n    }\n}	0
30622930	30621416	Lambda not equal on join	var match = categorys.Join(filterCategorys, x => x.Id, y => y.CategoryId, (x, y) => new { Id = x.Id });\nvar filteredList = categorys.Where(x => !match.Contains(new {Id = x.Id}));	0
25192360	25192316	How to check if a cell value is within 7 days from today	if (DateTime.Parse(e.Row.Cells[3].Text).Date < DateTime.Now.AddDays(inDateOffset).Date)	0
28545477	28544903	How to check suceeding records of datagriview	if (dgv.CurrentCell == null) return;\n\nvar spaces = new string(' ', 5);\nvar start = dgv.CurrentCell.RowIndex;\n\nif (start == dgv.Rows.Count) return;\n\nList<int> rowsToDelete = new List<int> { start };\n\nstart++;\n\nfor (int i = start; i < dgv.Rows.Count; i++)\n{\n    // Uncommitted new rows cannot be removed programatically\n    if (dgv.Rows[i].IsNewRow == false\n        && dgv.Rows[i].Cells[0].Value.ToString().StartsWith(spaces))\n    {\n        rowsToDelete.Add(i);\n    }\n    else\n    {\n        break;\n    }\n}\n\nrowsToDelete.Reverse(); // List.Reverse() reverses the list in place and returns void\n\nforeach (var rowIndex in rowsToDelete)\n{\n    dgv.Rows.RemoveAt(rowIndex);\n}	0
7426031	7425962	Adding a CUDA dll as a reference to a C# project showing an error	[DllImport("your_dll_name")]  public static extern int add_gpu_cu(IntPtr a, int size, int nblock, int ntrheac);	0
5178686	5178617	Avoid exceptions from module in the application	Application.DispatcherUnhandledException	0
30835307	30834565	Sending a dictionary of javascript parameters to MVC Controller via JSON	public ActionResult Test(string model)\n{\n  Request.InputStream.Seek(0, SeekOrigin.Begin);\n  string jsonData = new StreamReader(Request.InputStream).ReadToEnd();\n  var dynamicObject = JObject.Parse(jsonData);\n  ...\n}	0
1344754	1344693	Best pattern for creating large number of C# threads	Socket sock = GetSocket();\nState state = new State() { Socket = sock, Buffer = new byte[1024], ThirdPartyControl = GetControl() };\n\nsock.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ProcessAsyncReceive, state);\n\nvoid ProcessAsyncReceive(IAsyncResult iar)\n{\n    State state = iar.AsyncState as State;\n\n    state.Socket.EndReceive(iar);\n\n    // Process the received data in state.Buffer here\n    state.ThirdPartyControl.ScrapeScreen(state.Buffer);\n\n    state.Socket.BeginReceive(state.buffer, 0, state.Buffer.Length, 0, ProcessAsyncReceive, iar.AsyncState);\n}\n\npublic class State\n{\n    public Socket Socket { get; set; }\n    public byte[] Buffer { get; set; }\n    public ThirdPartyControl { get; set; }\n}	0
4420119	4420112	How do I format the Y axis to show 2000 instead of 2 with a label of MyLabel(10^3)?	YAxis y = myPane.YAxis;\n y.Scale.Format = "#";\n y.Scale.Mag = 0;	0
22665686	22665118	adding total columns value in datagrid view	decimal requests = 0;\n    decimal CFee = 0;\n    decimal CLAIMAMT = 0; \n    for (int i = 0; i < dataGridView1.Rows.Count; i++)\n    {           \n        CLAIMAMT +=  Convert.ToDecimal(dataGridView1.Rows[i].Cells["CLAIMAMT"].Value); \n        CFee +=  Convert.ToDecimal(dataGridView1.Rows[i].Cells["CFee"].Value); \n        requests++;\n    }     \n\n\n    lblClaimAmountTotal.Text = CLAIMAMT.ToString().PadLeft(10, '0');\n    lblCFeeTotal.Text = CFee.ToString().PadLeft(9, '0');\n    lblRequestTotal.Text = requests.ToString().PadLeft(5, '0');	0
646478	646468	How to Rotate a 2D Array of Integers	int [,] newArray = new int[4,4];\n\nfor (int i=3;i>=0;--i)\n{\n    for (int j=0;j<4;++j)\n    {\n         newArray[j,3-i] = array[i,j];\n    }\n}	0
7332582	922132	Use C# to interact with Windows Update	using WUApiLib;\nprotected override void OnLoad(EventArgs e){\n    base.OnLoad(e);\n    UpdateSession uSession = new UpdateSession();\n    IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();\n    uSearcher.Online = false;\n    try {\n        ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");\n        textBox1.Text = "Found " + sResult.Updates.Count + " updates" + Environment.NewLine;\n        foreach (IUpdate update in sResult.Updates) {\n                textBox1.AppendText(update.Title + Environment.NewLine);\n        }\n    }\n    catch (Exception ex) {\n        Console.WriteLine("Something went wrong: " + ex.Message);\n    }\n}	0
1061310	1061294	Passing information to a constructor without using a parameter in C#	class OuterClass {\n    private class BadClassBase {\n        // whatever BadClass does \n    }\n    private class BadClass : BadClassBase {\n        public BadClass(T item) {\n            ...\n        }\n    }\n}	0
5626909	5626781	in c# I would like to compare datatables	static bool AreTablesEqual(DataTable t1, DataTable t2)\n{\n    // If the number of rows is different, no need to compare the data\n    if (t1.Rows.Count != t2.Rows.Count)\n        return false;\n\n    for (int i = 0; i < t1.Rows.Count; i++)\n    {\n        foreach(DataColumn col in t1.Columns)\n        {\n            if (!Equals(t1.Rows[i][col.ColumnName], t2.Rows[i][col.ColumnName]))\n                return false;\n        }\n    }\n    return true;\n}	0
21261071	21260708	Converting VB code to C# for use in pdf generation	stream.Write(new byte[]{0xc7, 0xec, 0x8f, 0xa2}, 0, 4)	0
8400420	8400371	Select with linq two object from SQL Server database	DataLoadOptions dataLoadOptions = new DataLoadOptions();\ndataLoadOptions.LoadWith<Log>(l => l.Creator);\nmyDataContext.LoadOptions = dataLoadOptions;	0
11746607	11746450	Create objects dynamically when knowing part of classname in C#	class Program {\n    static void Main( string[] args ) {\n\n        string prefix = "p22";\n        IEnumerable<Type> types = Assembly.LoadFrom("c:\\Sample.Assembly.dll").GetTypes();    \n        Type baseClass = typeof(foo);\n        Type foundType = types.Where(\n            t => t.Name.StartsWith( prefix ) &&\n                t.IsSubclassOf( baseClass )\n                ).SingleOrDefault();\n        foo myClass = (foo)Activator.CreateInstance( foundType );\n                //Do Stuff with myClass \n    }\n}\nabstract class foo { }\nclass p22_notMyClass { }\nclass p22_myclass : foo { }\n}	0
7574586	7571538	Authentication in a multi layer architecture	FormsAuthentication.SetAuthCookie	0
29410833	29409859	Ways to Improve generic Dictionary performance	static void Main(string[] args)\n    {\n        var loopLength = 100000000;\n\n        var d = new Dictionary<int, int>();\n        for (var i = 0; i < 5000000; i++)\n        {\n            d.Add(i, i + 5);\n        }\n        var ignore = d[7];\n\n        var a = new int[5000000];\n        for (var i = 0; i < 5000000; i++)\n        {\n            a[i] = i + 5;\n        }\n        ignore = a[7];\n\n        var s = new Stopwatch();\n        var x = 1;\n        s.Start();\n\n        for (var i = 0; i < loopLength; i++)\n        {\n            x = (x * 1664525 + 1013904223) & (4194303);\n            var y = d[x];\n        }\n\n        s.Stop();\n        Console.WriteLine(s.ElapsedMilliseconds);\n        s.Reset();\n        x = 1;\n        s.Start();\n        for (var i = 0; i < loopLength; i++)\n        {\n            x = (x * 1664525 + 1013904223) & (4194303);\n            var y = a[x];\n        }\n\n        s.Stop();\n        Console.WriteLine(s.ElapsedMilliseconds);\n        Console.ReadKey(true);\n    }	0
22151100	22150216	How to Check Single URL WebTraffic in C#	private void Form1_Load(object sender, EventArgs e)\n        {\n            Fiddler.FiddlerApplication.AfterSessionComplete += Fiddler_AfterSessionComplete;\n            Fiddler.FiddlerApplication.Startup(0, Fiddler.FiddlerCoreStartupFlags.Default);\n\n         }\n\n    private void Fiddler_AfterSessionComplete(Fiddler.Session osession)\n        {\n            listWatch.Invoke(new UpdateUI(() =>\n            {\n\n               if(osession.fullUrl == "Your Url")\n                {\n                 //bind data\n                }\n\n           }));\n\n\n        }	0
31557505	31535020	SqlBulkCopy inserting in a table with Identity	sbc.ColumnMappings.Clear();\nint i = hasTableIdentity ? 1 : 0;\nDataColumn dc;\nforeach (Tables.BulkColumn bc in columns)\n{\n    dc = new DataColumn();\n    dc.DataType = bc.ColumnValueType;\n    dc.ColumnName = bc.Name;\n    dc.Unique = false;\n    sbc.ColumnMappings.Add(dc.ColumnName, i);\n    actualDataTable.Columns.Add(dc);\n    i++;\n}	0
9368028	9351821	Convert URLs into Regular Expression	new Regex(@"http://localhost:50788/catalog\.aspx\?VendorID=\d+&CategoryID=\d+");\n\nnew Regex(@"http://localhost:50788/Product\.aspx\?ProductID=\d+");	0
3848635	3848550	Inheritance of button	public class MyButton : Button\n{\n    public MyButton() : base()\n    {\n        // set whatever styling properties needed here\n        ForeColor = Color.Red;\n    }\n}	0
3852420	3852268	C# implementation of Google's 'Encoded Polyline Algorithm'	public static string Encode(IEnumerable<GeoLocation> points)\n{\n    var str = new StringBuilder();\n\n    var encodeDiff = (Action<int>)(diff => {\n        int shifted = diff << 1;\n        if (diff < 0)\n            shifted = ~shifted;\n        int rem = shifted;\n        while (rem >= 0x20)\n        {\n            str.Append((char)((0x20 | (rem & 0x1f)) + 63));\n            rem >>= 5;\n        }\n        str.Append((char)(rem + 63));\n    });\n\n    int lastLat = 0;\n    int lastLng = 0;\n    foreach (var point in points)\n    {\n        int lat = (int)Math.Round(point.Latitude * 1E5);\n        int lng = (int)Math.Round(point.Longitude * 1E5);\n        encodeDiff(lat - lastLat);\n        encodeDiff(lng - lastLng);\n        lastLat = lat;\n        lastLng = lng;\n    }\n    return str.ToString();\n}	0
13223328	13223190	DbContext trying to create tables	// static constructor\nstatic MyDbContext()\n{\n    Database.SetInitializer<MyDbContext>(null);\n}	0
17388835	17387509	How to convert 1D byte array to 2D byte array which holds a bitmap?	public int[,] ConvertArray(int[] Input, int size)\n    {\n        int[,] Output = new int[(int)(Input.Length/size),size];\n        System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\OutFile.txt");\n        for (int i = 0; i < Input.Length; i += size)\n        {\n            for (int j = 0; j < size; j++)\n            {\n                Output[(int)(i / size), j] = Input[i + j];\n                sw.Write(Input[i + j]);\n            }\n            sw.WriteLine("");\n        }\n        sw.Close();\n        return Output;\n    }	0
7190333	7190219	Threading in C# with limited number of jobs and limited number of active threads	Parallel.For(0, wantedNumberOfJobs, i => {\n                var resource = ... //gets the resource   \n                DoWork(Resource);\n            });	0
22192704	22192446	How to set start page in windows phone 8 app programmatically?	private void Application_Launching(object sender, LaunchingEventArgs e)\n    {\n        RootFrame.Navigated += RootFrame_Navigated;\n        var logined = Singleton.Instance.User.Load();\n        var navigatingUri = logined ? "/View/PageMainPanorama.xaml" : "/View/Account/PageLoginRegister.xaml";\n        ((App)Current).RootFrame.Navigate(new Uri(navigatingUri, UriKind.Relative));\n    }	0
27479490	27479470	Having trouble iterating through a session key and comparing the value to database	.Where(s => id.Contains(s.id));	0
17475341	17249911	How can I decode PDU with GSMComm or PduBitPacker?	IncomingSmsPdu sms = IncomingSmsPdu.Decode("0791893905004100640C9189398978168400003160915151238110050003110202C26735B94D87DF41", true);\n\nConsole.WriteLine(sms.UserDataText);	0
3424191	3423435	How do I find a HTML div contains specific text after a text prefix?	prefix<div>([^<]*<(?!/div>))*[^<]*text3([^<]*<(?!/div>))*[^<]*</div>	0
20483838	20461954	How to stop Cisco Services Application objects from stacking	App:Close:0	0
1687836	1687811	Manually putting together parts of a date	DateTime date = new DateTime(year.HasValue ? year.Value : 1900, month, day)	0
19289405	19289148	Write data to CSV file	StreamReader sr = new StreamReader(@"C:\CSV\test.csv")\nStreamWriter sw = new StreamWriter(@"C:\CSV\testOut.csv")\nwhile (sr.Peek() >= 0) \n{\n    string line = sr.ReadLine(); \n\n\ntry\n{\n       string[] rowsArray = line.Split(';');\n       string row = rowsArray[0];\n       string resultIBAN = client.BBANtoIBAN(row);\n       if (resultIBAN != string.Empty)\n       {\n           line +=";"+ resultIBAN;\n       }\n       else\n       {\n            line +=";"+"Accountnumber is not correct.";\n       }\n\n }\n catch (Exception msg)\n {\n     Console.WriteLine(msg);\n }\n sw.WriteLine(line) \n }\nsr.Close();\nsw.Close();	0
17751616	17751594	Choose to show a button or not in Page_Load	try\n  {\n      webResponse = webRequest.GetResponse();\n  }\n  catch \n  {\n      ImageExists = false;\n      Button1.Visible = false;\n  }	0
16395528	16395066	How Can I read From Line number() to line Starts with in C#	string[] lines = System.IO.File.ReadAllLines("test.txt");\n        List<double> results = new List<double>();\n        foreach (var line in lines.Skip(4))\n        {\n            if (line.StartsWith("<pre>"))\n                break;\n            Regex numberReg = new Regex(@"\d+(\.\d){0,1}");  //will find any number ending in ".X" - it's primitive, and won't work for something like 0.01, but no such data showed up in your example\n            var result = numberReg.Matches(line).Cast<Match>().FirstOrDefault();  //use only the first number from each line. You could use Cast<Match>().Skip(1).FirstOrDefault to get the second, and so on...\n            if (result != null)\n                results.Add(Convert.ToDouble(result.Value, System.Globalization.CultureInfo.InvariantCulture));  //Note the use of InvariantCulture, otherwise you may need to worry about , or . in your numbers\n        }	0
6654168	6654077	Using anonymous types - one variable choose two different queries	var dsakj = (type == "mix") ?\n            (from el in objDC.WGamesTickets\n             where el.ticket.time == DTtemp\n                 //&& el.typeOfGame == "mix"\n             select new myCustomObject()\n             {\n                 id = el.id,\n                 name = el.name,\n             })\n             :\n             (from el in objDC.AllGamesTickets\n              where el.ticket.time == DTtemp\n              //&& el.typeOfGame == "eng"\n             select new myCustomObject()\n             {\n                 id = el.id,\n                 name = el.name,\n             });	0
10926577	10926506	how to get current application path in wpf	System.AppDomain.CurrentDomain.BaseDirectory	0
3399736	3399677	Im trying to make a Repeater table visible = false	Repeater collectorData = (Repeater)item.FindControl("CollectedTableRepeater1");\nRepeater contactedData = (Repeater)item.FindControl("ContactedTableRepeater2");\nif( collectedDocuments.Tables[0].Rows.Count > 0 ){\n        //if there is data(more than 0 rows), bind it\n        collectorData.DataSource = collectedDocuments;\n        collectorData.DataBind();\n\n        contactedData.DataSource = contactedDocuments;\n        contactedData.DataBind();\n} else {\n        collectorData.Visible = False;\n        //optional display "No data found" message\n        contactedData.Visible = False;\n}	0
767732	767715	Trying to make a dialog window remember its last position	Form form= new Form();   \n\n form.StartPosition = FormStartPosition.Manual;\n\n form.Location = ptSavedLocation;\n //now form.Location is correct\n\n form.ShowDialog();\n //now form.Location is default again, and form is displayed where I don't want it.	0
23912910	23912761	How to change ListBox selection based on CheckBox status and vice versa?	checkBox1.CheckedChanged -= checkBox1_CheckedChanged;\ncheckBox1.Checked = true;\ncheckBox1.CheckedChanged += checkBox1_CheckedChanged;	0
2915032	2914984	Pattern for managing object state/settings?	public class Car\n{\n    private CarSettings settings;\n\n    public Car(CarSettings settings) \n    {\n        settings = settings ?? CarSettings.Default;\n    }\n\n    public string Color { get {return settings.Color;} }\n}\n\npublic class CarSettings \n{\n     public string Color {get; private set;}\n     public static CarSettings Default = new CarSettings {Color = "Red"};\n}	0
31235895	31181233	Writing a HLSL shader for rescaling floating point textures	SurfaceFormat.Rg32	0
2388268	2388245	Double to String keeping trailing zero	d.ToString("0.00");	0
32425278	32424948	C# - Convert Bytes Representing Char Numbers to Int16	const byte Negative = (byte)'-';\n    const byte Zero = (byte)'0';\n    static Int16 BytesToInt16(byte[] bytes)\n    {\n        if (null == bytes || bytes.Length == 0)\n            return 0;\n        int result = 0;\n        bool isNegative = bytes[0] == Negative;\n        int index = isNegative ? 1 : 0;\n        for (; index < bytes.Length; index++)\n        {\n            result = 10 * result + (bytes[index] - Zero);\n        }\n        if (isNegative)\n            result *= -1;\n        if (result < Int16.MinValue)\n            return Int16.MinValue;\n        if (result > Int16.MaxValue)\n            return Int16.MaxValue;\n        return (Int16)result;\n    }	0
24214847	23943166	How use xaml to access Canvas.Left property of a ContentControl stored in DataContext?	Text="{Binding Path=CurrentDesignerItem.(Canvas.Left)}"	0
8428825	8413448	Message Box popping on wrong page wp7	catch (Exception x)\n            {\n                Deployment.Current.Dispatcher.BeginInvoke(() =>\n                {\n                    var currentPage = ((App)Application.Current).RootFrame.Content as PhoneApplicationPage;\n                    if ((currentPage.ToString()).Equals("MumbaiMarathon.Info.News"))\n                    {\n                        MessageBox.Show("Connection Error");\n                    }\n                });\n            }	0
16436994	16436879	Get time left on session until timeout	DateTime.Now	0
1978440	1978412	How can I get the value of all the selected cells in a DataGridView?	foreach (DataGridViewCell cell in dataGridView1.SelectedCells)\n{\n    MessageBox.Show(cell.Value.ToString());\n}	0
11148077	11128820	How can I make the column name ALL CAPS when mapped from a property that uses a complex type?	public class MyDbContext : DbContext {\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.ComplexType<Minutes>().Property(x => x.Value);\n        modelBuilder.Entity<MyEntity>().Property(x => x.MyMinutes.Value).HasColumnName("MYMINUTES");\n    }\n}	0
8965850	8965443	c# radiobuttonlist control	protected void Option_SelectedIndexChanged(object sender, EventArgs e)\n{\n    RadioButtonList sourceRadioButtonList = (RadioButtonList)sender;\n\n    string selectedOption = sourceRadioButtonList.SelectedValue;\n}	0
26969367	26968775	How to parse an xml node with large value?	long curr = 0;\nint read = 0;\ndo {\n    char[] buffer = new char[bufferLength];\n    int read = reader.ReadValueChunk(buffer, curr, bufferLength);\n    WriteData(buffer); // Do something with the data you got\n} while(read == bufferLength);	0
21664512	21660375	Pass associative array of objects	function NormalizeItemsArray() {\n    var result = new Array();\n\n    for (var i in items) {\n        i = items[i];\n        var item = new Item();\n        item.ItemId = i.ItemId;\n        item.Title = i.Title;\n        item.Questions = new Array();\n\n        for (var q in i.Questions) {\n            q = i.Questions[q];\n            var question = new Question();\n            question.QuestionId = q.QuestionId;\n            question.Description = q.Description;\n            question.Values = new Array();\n\n            for (var v in q.Values) {\n                v = q.Values[v];\n                var questionValue = new QuestionValue();\n                questionValue.ValueId = v.ValueId;\n                questionValue.Description = v.Description;\n                questionValue.IsCorrect = v.IsCorrect;\n\n                question.Values.push(questionValue);\n            }\n            item.Questions.push(question);\n        }\n        result.push(item);\n    }\n\n    return result;\n}	0
20445743	20445077	How to Read a List<>? Windows Phone 8	MessageBox.Show(items.Count.ToString());	0
10164158	10150697	button click event inside in external method?	public static void MainMenu()\n{\n    frmMain.MainForm.ScreenTextClear();\n\n    frmMain.MainForm.ButtonEnable(true, false, false, false, false, false);\n    frmMain.MainForm.ScreenText(true, "Welcome to the alpha of this game.");\n    frmMain.MainForm.ScreenText(true, "Hi");\n    frmMain.MainForm.ButtonText("New Game", "Load Game", "About", "---", "---", "---");  \n\n    // Potential solution.\n    frmMain.MainForm.btn1.Click += delegate(object sender, EventArgs e)\n        {\n            NewGame();\n        };    \n}	0
6866340	6773866	Download file and automatically save it to folder	private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)\n    {\n        e.Cancel = true;\n        WebClient client = new WebClient();\n\n        client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);\n\n        client.DownloadDataAsync(e.Url);\n    }\n\n    void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)\n    {\n        string filepath = textBox1.Text;\n        File.WriteAllBytes(filepath, e.Result);\n        MessageBox.Show("File downloaded");\n    }	0
11149646	11149602	Given a start and end date... find all dates within range in C#	DateTime begin = //some start date\nDateTime end = //some end date\nList<DateTime> dates = new List<DateTime>();\nfor(DateTime date = begin; date <= end; date = date.AddDays(1))\n{\n    dates.Add(date);\n}	0
8734537	8734413	Declaring and Using Global Arrays c#	public static class GlobalData\n{\n    public static string[] Foo = new string[16];\n};\n\n// From anywhere in your code...\nConsole.WriteLine(GlobalData.Foo[7]);	0
23478618	23478550	C# Import data from text file to text boxes	// Show the OpenFileDialog and wait for user to close with OK \n  if(filechooser.ShowDialog() == DialogResult.OK)\n  {\n       // Check if the file exists before trying to open it \n       if(File.Exists(filechooser.FileName))\n       {\n           // Enclose the streamreader in a using block to ensure proper closing and disposing\n           // of the file resource....\n           using(StreamReader fileReader = new StreamReader(filechooser.FileName))\n           {\n                string inputrecord = fileReader.ReadLine();\n                string[] inputfields;\n                ....\n                // The remainder of your code seems to be correct, but a check on the actual\n                // length of the array resulting from the Split call should be added for safety\n           }\n       }\n  }	0
31152650	31126193	How can I hide vertical line	chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;	0
24557689	24557543	How to ping from a Windows Service	System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();\ntry\n{\n    System.Net.NetworkInformation.PingReply reply = p.Send("127.0.0.1", 3000);\n    if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)\n        return true;\n}\ncatch(Exception ex) \n{\n\n}	0
11137259	11136293	Checking for a batch file executing or not via windows service	while(_running)\n{\n    if(!File.Exists("..."))\n    { \n        // start batch job\n    }\n    Thread.Sleep(5 * 60 * 1000);\n}	0
1104818	1102863	linq - how combine conditions in a join statement	var data=\n  from details in h_details.Descendants("ROW")\n  join inst in instance.XPathSelectElements("//Row")\n  on new {\n    x = details.Element("ID").Value,\n    y = details.Element("LANGUAGE").Value\n  } equals new {\n    x = inst.XPathSelectElement("Field[@Name=\'h_id\']").Value,\n    y = inst.XPathSelectElement("Field[@Name=\'h_lang\']").Value\n  }\n  select ... ;	0
19230163	19229077	Search in Windows Phone Store by developer name	// using Microsoft.Phone.Tasks;\nMarketplaceSearchTask moreAppsSearch = new MarketplaceSearchTask();\nmoreAppsSearch.ContentType = MarketplaceContentType.Applications;\nmoreAppsSearch.SearchTerms = "YOUR_DEVLOPER_NAME";\nmoreAppsSearch.Show();	0
1188360	954481	RSS 2.0 feed - set update limit for Outlook 2007	feed.AttributeExtensions.Add(new XmlQualifiedName("sy", "http://www.w3.org/2000/xmlns/"), "http://purl.org/rss/1.0/modules/syndication/");\nfeed.ElementExtensions.Add("updatePeriod", "http://purl.org/rss/1.0/modules/syndication/", "daily");\nfeed.ElementExtensions.Add("updateFrequency", "http://purl.org/rss/1.0/modules/syndication/", 6);\nfeed.ElementExtensions.Add("updateBase", "http://purl.org/rss/1.0/modules/syndication/", DateTime.UtcNow);	0
18015349	18015284	Join 2 DataTables into 1 in C#	sum = one.Copy();\nsum.Merge(two);	0
16431651	16431625	Cast troubles while using LINQ to filter a Dictionary by values	someDictionary = someDictionary.Where(pair => pair.Value > 500)\n                               .ToDictionary(p => p.Key, p => p.Value);	0
6827426	6827393	Instantiate a generic list from object	Type genericListType = typeof(List<>).MakeGenericType(new Type[] { myClass.GetType() });\nobject list = Activator.CreateInstance(genericListType);	0
22684593	22564831	Download files and folders as a ZIP file using C# doesn't work in Mac	string SourceFolderPath = System.IO.Path.Combine(FolderPath, "Initial");\n\n    Response.Clear();\n    Response.ContentType = "application/zip";\n    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", nameFolder + ".zip"));\n\n    bool recurseDirectories = true;\n    using (ZipFile zip = new ZipFile())\n    {\n        zip.AddSelectedFiles("*", SourceFolderPath, string.Empty, recurseDirectories);\n        zip.Save(Response.OutputStream);\n    }\n    Response.End();	0
13349997	13347670	MVVMLight: RelayCommand seems not working in Windows 8 App	public string Manufacturer {\n          get { return _Manufacturer; }\n          set {\n            _Manufacturer = value;\n            RaisePropertyChanged( "Manufacturer" );\n            CmdAddTransportationUnit.RaiseCanExecuteChanged(); \n        }\n    }	0
13900235	13896322	Programmatically Removing N2 CMS Nodes from the Trash	var trash = new ItemList<TrashContainerItem>(N2.Find.RootItem.Children, new TypeFilter(typeof(TrashContainerItem))).FirstOrDefault();\nif (trash != null)\n{\n  var detailToPermDelete = new ItemList<TargetDetailModel>(trash.Children, new TypeFilter(typeof(TargetDetailModel)));\n  for (int permDeleteCount = 0; permDeleteCount < detailToPermDelete.Count; permDeleteCount++)\n  {                            \n    N2.Context.Current.Persister.Delete(detailToPermDelete.ElementAt(permDeleteCount));\n  }\n}	0
12369920	12369572	Need to bind DataList with Two DataSources	DataTable customTable = new DataTable();\n        customTable.Columns.Add("Column1");\n        customTable.Columns.Add("Column2");\n\n        DataRow drNew = null;\n        foreach(DataRow dR in 1stDataSource)\n        {\n            foreach(DataRow dR1 in 2ndDataSource)\n            {\n                if(dR["ID"] == dR1["ID"])\n                {\n                    drNew = customTable.NewRow();\n                    drNew["Column1"] = dR["Column1"];\n                    drNew["Column2"] = dR1["Column2"];\n                    customTable.Rows.Add(drNew);\n                    break;\n                }\n            }\n        }\n\n        myDataList.DataSource = customTable;\n        myDataList.DataBind();	0
27600976	27592226	How can I select data from SQL server to gridview in asp.net C#	private void button1_Click(object sender, EventArgs e)\n{\n\n    string strConnString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;\n    SqlConnection objConn = new SqlConnection(strConnString);\n\n    string strSQL = "SELECT * FROM ADMS_Machining ";\n    SqlDataAdapter sda = new SqlDataAdapter(strSQL, objConn);\n    DataSet ds = new DataSet();\n    sda.Fill(ds);\n\n    GridView1.DataSource = ds;\n    GridView1.DataBind();\n\n}	0
20734843	20734731	foreach Controls in C# in descending order	pictureBox1.Controls.Cast<Control>().Reverse()	0
21311786	21311704	convert byte array to hex in c#	byte[] bytes = new byte[] { 0, 0, 0, 0, 0, 0, 13, 191 };\ncmd.Parameters.Add("@myPKRowVersion", SqlDbType.Binary).Value = bytes;	0
22741589	22732721	how to get location using Latitude and Longitude in windows phone 8	WebClient client = new WebClient();\n        string strLatitude = " 13.00";\n        string strLongitude = "80.25";\n        client.DownloadStringCompleted += client_DownloadStringCompleted;\n        string Url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + strLatitude + "," + strLongitude + "&sensor=true";\n        client.DownloadStringAsync(new Uri(Url, UriKind.RelativeOrAbsolute));\n        Console.Read();\n\nstatic void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)\n {\n    var getResult = e.Result;\n        JObject parseJson = JObject.Parse(getResult);\n        var getJsonres = parseJson["results"][0];\n        var getJson = getJsonres["address_components"][1];\n        var getAddress = getJson["long_name"];\n        string Address = getAddress.ToString();	0
12199675	12199644	How to get difference of dates	TimeSpan span = date1.Subtract(date2);\nlong hours = (long)span.TotalHours;	0
3244786	3244774	ASP.NET MVC-2 How can you recieve a POST from another website?	[HttpPost]\npublic ActionResult TestReceive(string sessionId) \n{\n    ...\n}	0
11010988	11010802	TreeView feature to uncheck all other nodes	using System;\nusing System.Windows.Forms;\n\nclass MyTreeView : TreeView {\n    protected override void OnAfterCheck(TreeViewEventArgs e) {\n        if (checking) return;\n        checking = true;\n        if (e.Node.Checked && (Control.ModifierKeys & Keys.Control) == Keys.Control) {\n            uncheckNodes(this.Nodes, e.Node);\n        }\n        checking = false;\n        base.OnAfterCheck(e);\n    }\n\n    private void uncheckNodes(TreeNodeCollection nodes, TreeNode except) {\n        foreach (TreeNode node in nodes) {\n            if (node != except) node.Checked = false;\n            uncheckNodes(node.Nodes, except);\n        }\n    }\n    private bool checking;\n}	0
29913665	29874994	2D Monogame: Rectangle collision detection, side specific	Player.Rectangle.Left > Map.Rectangle.Left	0
2643815	2643752	Defining DateDiff for a calculated column in a datatable	DataColumn colExpirationDate = new DataColumn("DateTimeExpired", typeof(DateTime));\nDataColumn colExpired = new DataColumn("Expired", typeof(string),\n    String.Format("IIF(DateTimeExpired > #{0}#,'No','Yes')",\n    DateTime.Now.ToString("dd/MMM/yyyy")));	0
7331235	7331156	How Can I Get the Current Short DateTime Format in C#?	using System.Globalization;\n\n...\n...\n...\n\nvar myDTFI = CultureInfo.CurrentCulture.DateTimeFormat;\n\nvar result = myDTFI.FullDateTimePattern;	0
3791851	3791833	help with linq to sql many to many query	query = query.Where(a => a.AB_Entities.Any(ab => ab.BId == BId));\nreturn query;	0
30095442	29429797	Force EPPLUS to read as text	var ws = MainExcel.Workbook.Worksheets.First();\n DataTable tbl = new DataTable();\n for (var rowNum = 1; rowNum <= ws.Dimension.End.Row; rowNum++)      \n {\n     var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];\n     var array = wsRow.Value as object[,];\n\n     var row = tbl.NewRow();\n     int hhh =0;\n\n     foreach (var cell in wsRow)\n          {\n           cell.Style.Numberformat.Format = "@";\n           row[cell.Start.Column - 1] = cell.Text;\n          }\n     tbl.Rows.Add(row);\n }	0
2453236	2410779	Network Authentication when running exe from WMI	Process proc = new Process();\nproc.StartInfo.FileName = "PsExec.exe";\nproc.StartInfo.Arguments = string.Format("\\\\{0} -d -u {1}\\{2} -p {3} {4}",\n                                         remoteHost,\n                                         domain,\n                                         username,\n                                         password,\n                                         commandLine);\nproc.StartInfo.CreateNoWindow = true;\nproc.StartInfo.UseShellExecute = false;\nproc.Start();	0
5890506	5890500	How can I get the value from the normal select in .net c# web application?	Request.Form["test"];	0
2420767	2420725	C# 2 ComboBox DropDownList showing same values	ddlTo.DataSource	0
587155	587077	How do I stop a windows service application from a thread?	private static MyService m_ServiceInstance;\n\npublic static MyService ServiceInstance\n{\n    get { return m_ServiceInstance; }\n}\n\npublic MyService()\n{\n    InitializeComponents();\n    //Other initialization\n    m_ServiceInstance = this;\n}	0
14641612	14641215	Data grid View ( winform ) not populating properly	var main = new SRMEntities();\nvar query = from f in main.Faculty\n            join d in main.Department on f.Sno equals d.Faculty.Sno\n            select new { d.Sno, d.Name, d.Status, Faculty = f.Name };\n\nDepartmentGrid.DataSource = query.ToList();	0
1579413	1579382	WPF DataGrid - row for new entry not visible	WordsDataGrid.CanUserAddRows = true;	0
3439721	3439690	Why lock when reading from a dictionary	Dictionary<TKey, TValue>	0
23290320	23281720	Trello.Net: how to access Action list?	var card = trello.Cards.WithId(cardId);\nvar actions = trello.Actions.ForCard(card);	0
27599358	27597691	Reading a Text File without disturbing Game Logic and Its execution	public class ExampleClass : MonoBehaviour {\npublic string url = "File download URL here";\nIEnumerator Start() {\n    WWW www = new WWW(url);\n    yield return www;\n    //retreive the file content using www.text\n    //write your code here\n}	0
10400166	10400156	How can I encode string with http web request?	var values = HttpUtility.ParseQueryString(string.Empty);\nvalues["key"] = "INSERT-YOUR-KEY";\nvalues["q"] = "hello world";\nstring queryString = values.ToString();\n// at this stage queryString="key=INSERT-YOUR-KEY&q=hello+world"	0
9757162	9750078	Get value from anonymous type	string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);	0
13651754	13650397	getting last month visits total	declare @FromDate date\n,@ToDate date\nset @FromDate = '11/01/2012'\nset @ToDate = '11/30/2012'\n\nSELECT     COUNT(VisitTracking.customerID) AS #VISIT\nFROM         VisitTracking \nWHERE VisitTracking.DateVisited  BETWEEN DATEADD(m, datediff(MM, 0, @FromDate)-1, 0)  and  DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@ToDate),0))	0
21449606	21449316	How to start a new instance of Windows Service using ServiceController in C#	protected override void OnStart(string[] args)\n{\n    _thread1 = new Thread(DoWork);\n    _thread1.Start();\n    _thread2 = new Thread(DoWork);\n    _thread2.Start();\n}	0
21220687	21187912	How to Invoke a Verb on a ShellFile/ShellFolder/ShellObject objects using Windows API Code Pack?	' some file we got from the recycle bin iterating through the IShellItems:\n    Dim sParsing As String = _\n      "E:\$RECYCLE.BIN\S-1-5-21-2546332361-822210090-45395533-1001\$RTD2G1Z.PNG"\n    Dim shex As New SHELLEXECUTEINFO\n    shex.cbSize = Marshal.SizeOf(shex)\n\n    ' Here we want ONLY the file name.\n    shex.lpFile = Path.GetFileName(sParsing)\n\n    ' Here we want the exact directory from the parsing name\n    shex.lpDirectory = Path.GetDirectoryName(sParsing)\n    shex.nShow = SW_SHOW  ' = 5\n    '' here the verb is undelete, not restore.\n    shex.lpVerb = "undelete"\n\n    ShellExecuteEx(shex)	0
13121381	13121351	Check if a interface is implemented by a type in compile time	private static Type currentType = null;\n\npublic static void Initalize <T>() where T: ITest {\n     currentType = typeof(T);\n}	0
5903881	5903770	.NET Listbox: in ItemChecked event know if item was clicked	if(ManualRaise) \n{\n// this was manual event raise\nManualRaise = False\n} \nelse \n{\n}	0
19978471	19975394	how to insert dynamically created label text into sql server in asp.net c#	using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(@EventDay,@EventStatus)", con))\n{\n    var paramDay = cmd2.Parameters.Add("@EventDay", SqlDbType.DateTime);\n    var paramStatus = cmd2.Parameters.Add("@EventStatus", SqlDbType.Int);\n    for (int i = 0; i < n; i++)\n    {\n        Label NewLabel = new Label();\n        NewLabel.ID = "Label" + i;\n\n        var eventDate = Calendar1.SelectedDate.Date.AddDays(i);\n        NewLabel.Text = eventDate.ToLongDateString();\n        NewLabel.CssClass = "h1size";\n\n        CheckBox newcheck = new CheckBox();\n        newcheck.ID = "CheckBox" + i;\n\n        this.Labeldiv.Controls.Add(NewLabel);\n        this.Checkboxdiv.Controls.Add(newcheck);\n        this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));\n\n        paramDay.Value = eventDate;\n        paramStatus.Value = newCheck.Checked ? 1 : 0;\n        cmd2.ExecuteNonQuery();\n    }\n}	0
27800034	27796399	How to read Custom Attributes from Exchange mailbox in Outlook Add-in	var prope = user.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x8032001E");	0
5193109	5193078	How to avoid ViewBag (or ViewData) in favor of a Model?	var model = new ChangeSecurityQuestionModel() {\n      PasswordQuestion = user.PasswordQuestion,\n      QuestionList = new SelectList(membershipRepository.GetSecurityQuestionList(), "Question", "Question"),\n      PasswordLength = MembershipService.MinPasswordLength;\n    };	0
8035156	8034743	How to extract numeric values from string?	static readonly Regex VectorRegex = new Regex(@"a:(?<A>[0-9]+\.[0-9]+);b:(?<B>[0-9]+\.[0-9]+);c:(?<C>[0-9]+\.[0-9]+)", RegexOptions.Compiled);\n\n    static Tuple<double, double, double> ParseVector(string input)\n    {\n        var m = VectorRegex.Match(input);\n\n        if (m.Success)\n        {\n            double a, b, c;\n            a = double.Parse(m.Groups["A"].Value, System.Globalization.NumberFormatInfo.InvariantInfo);\n            b = double.Parse(m.Groups["B"].Value, System.Globalization.NumberFormatInfo.InvariantInfo);\n            c = double.Parse(m.Groups["C"].Value, System.Globalization.NumberFormatInfo.InvariantInfo);\n            return new Tuple<double, double, double>(a, b, c);\n        }\n        else\n            throw new FormatException("Invalid input format");\n    }	0
13761556	13761124	Editing Combobox item in Datagridview in C#	private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n    if (DataGridView1.CurrentCell.ColumnIndex == yourComboBoxColum)\n    {\n        ComboBox combo = e.Control as ComboBox;\n\n        if (combo == null)\n            return;\n\n        combo.DropDownStyle = ComboBoxStyle.DropDown;\n    }\n}	0
4389599	4389565	How to decode (shifting and xoring) a massive byte array in a fast way?	private static byte[] DecodedBytes = PrecomputeDecodedBytes();\n\npublic static byte[] DecodeVOQ(byte[] data)\n{\n    for (int i = 0; i < data.Length; i++)\n    {\n        data[i] = DecodedBytes[data[i]];\n    }\n    return data;\n}	0
2426669	2425221	Prevent MDI window to appear in the Window menu list	MenuStrip ms = new MenuStrip();\nToolStripMenuItem windowMenu = new ToolStripMenuItem("Window");\nms.MdiWindowListItem = windowMenu;\n\nwindowMenu.DropDownOpening += (sender, e) =>\n        {\n            if (windowMenu.DropDownItems.Count > 0)\n                windowMenu.DropDownItems.RemoveAt(0);\n        };\n\nms.Items.Add(windowMenu);\nms.Dock = DockStyle.Top;            \nthis.MainMenuStrip = ms;\nthis.Controls.Add(ms);	0
2210343	2207709	convert font to string and back again	var cvt = new FontConverter();\n        string s = cvt.ConvertToString(this.Font);\n        Font f = cvt.ConvertFromString(s) as Font;	0
22840732	22820529	Fluent NHibernate can't set Time columns on DB2400 to a value before 10 am	public SqlType[] SqlTypes\n{\n    get\n    {\n        SqlType[] types = new SqlType[1];\n        types[0] = new SqlType(DbType.Int32);\n        return types;\n    }\n}	0
24827182	24826874	Unreachable code detected in C# Controller	string filename = HttpContext.Server.MapPath("~/Content/cvs/worddoc/test.docx");\nvar doc = DocX.Create(filename);\nstring headLine = "Test fingers crossed";\ndoc.InsertParagraph(headLine);\ndoc.Save();	0
7488706	7488678	To add an external css file from the code behind	Page.Header.Controls.Add(\n    new System.Web.UI.LiteralControl("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + ResolveUrl("~/Styles/SomeStyle.css") + "\" />"));	0
20024812	20024777	NullReferenceException - Set Image property of PictureBox - Winforms	public TestImageForm(Image img)\n{\n    InitializeComponent();\n    bevImg = img;\n    displayImage();\n}	0
1720811	1720790	Removing files that are older than some number of days	var files = new DirectoryInfo(@"c:\log").GetFiles("*.log");\nforeach (var file in files)\n{\n    if (DateTime.UtcNow - file.CreationTimeUtc > TimeSpan.FromDays(30))\n    {\n        File.Delete(file.FullName);\n    }\n}	0
16073333	16073044	SSRS report won't launch if multiple parameters in URL	script += "OpenLink1('" + params + "');";	0
12902619	11169396	C# send a simple SSH command	using (var client = new SshClient("hostnameOrIp", "username", "password"))\n{\n    client.Connect();\n    client.RunCommand("etc/init.d/networking restart");\n    client.Disconnect();\n}	0
30020335	30019596	Unable to use C# COM object from Perl	Dim obj\nSet obj = CreateObject("ExampleCom.ComClass")\nMsgBox TypeName(obj)	0
19045830	19045568	Testcases using Nunit with global variables	[Test]\npublic void TestUser()\n{\n    MyClass myClass = new MyClass();\n    MyClass.userid = "test value";\n    Assert.IsTrue(IsEntryExist())\n}	0
14060942	7679601	Remove words from string c#	public static string RemoveHTML(string text)\n{\n    text = text.Replace("&nbsp;", " ").Replace("<br>", "\n").Replace("description", "").Replace("INFRA:CORE:", "")\n        .Replace("RESERVED", "")\n        .Replace(":", "")\n        .Replace(";", "")\n        .Replace("-0/3/0", "");\n        var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");\n        return oRegEx.Replace(text, string.Empty);\n}	0
17116059	17116045	Open File Dialog, One Filter for Multiple Excel Extensions?	OpenFileDialog of = new OpenFileDialog();\nof.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";	0
12574293	12561534	passing char*[] from c++ dll Struct to c#  	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct Name\n{\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]\n    public string FirstName;\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]\n    public string LastName;\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]\n    public string[] Array;\n};	0
548476	548462	How do I Validate a User Using LINQ to SQL?	public bool ValidateApplicationUser(string userName, string password)\n{\n    //Get Database Context\n    var AuthContext = new DataClasses1DataContext();\n\n    //We Are Only Going To Select UserId, Notice The Password .ToLower Is Removed (for security)\n    var query = from c in AuthContext.Users\n                where (c.Username == userName.ToLower() && c.Password == password)\n                select c;\n\n    if (query.Count() != 0) {\n       return true;\n    }\n\n    return false;\n}	0
34511594	34511443	how to select max in List<> using Linq	var Max = collection.Where(x => x.Percentvalue == collection.Where(a=>a.Percentvalue>=0.5 && a.Percentvalue<=90 ).Max(y => y.Percentvalue));\nvar Min = collection.Where(x => x.Percentvalue == collection.Where(a=>a.Percentvalue>=0.5 && a.Percentvalue<=90 ).Min(y => y.Percentvalue));	0
25459199	25449509	FFMPEG When joining an audio track to a longer video track the audio loops	ffmpeg -i videofile.mp4 -i audiofile.wav -filter_complex " [1:0] apad " -shortest output.mp4	0
1388846	1378484	WPF Toolkit, How to apply date format in C# for datepicker control?	System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("en-us");\n\nSystem.Globalization.DateTimeFormatInfo dtinfo = new System.Globalization.DateTimeFormatInfo();\n\ndtinfo.ShortDatePattern = "dd-Mon-yyyy";\n\ndtinfo.DateSeparator = "-";	0
1720261	1720160	How to create a bitmap programmatically	using (Graphics gfx = Graphics.FromImage(Bmp))\nusing (SolidBrush brush = new SolidBrush(Color.FromArgb(redvalue, greenvalue, bluevalue)))\n{\n    gfx.FillRectangle(brush, 0, 0, width, height);\n}	0
24446701	24446534	Open xml cannot get a drawing element	List<Drawing> sdtElementDrawing = wordDoc.MainDocumentPart.Document.Descendants<Drawing>()\n    .Where(element => element.Descendants<DocProperties>().Any(\n        prop => prop.Title.Value.ToUpper().Contains("IMAGE")\n    )).ToList();	0
21825599	21825582	how to take the part of a string	XElement element = XElement.Parse(text);\nstring value = element.Value;\nbyte[] bytes = Convert.FromBase64String(value);	0
23974234	23974173	Ranking with tiebreakers	driversList.Sort(\n    delegate(Driver d1, Driver d2)\n    {\n        if (d1.championshipPoints == d2.championshipPoints)\n        {\n            return d1.name.CompareTo(d2.name);\n        }\n        return d1.championshipPoints.CompareTo(d2.championshipPoints);\n    }\n);	0
353827	353773	How can I determine when control key is held down during button click	private void button1_Click ( object sender, EventArgs e )\n{           \n    if( (ModifierKeys  & Keys.Control) == Keys.Control )\n    {\n        ControlClickMethod();    \n    }\n    else\n    {\n        ClickMethod();\n    }\n}\n\nprivate void ControlClickMethod()\n{\n    MessageBox.Show( "Control is pressed" );\n}\n\nprivate void ClickMethod()\n{\n    MessageBox.Show ( "Control is not pressed" );\n}	0
21038349	21037816	Giving starting value to the Query in SQL Server	string startingValue = "S110911";\nstring endingValue = "S110915";\nstring query = "Select * From Units Where UnitSerialNumber Between startingValue And endingValue";	0
11992373	11992003	Json.net linq to json cast null to JObject throw exception	bool hasCustomer = false ;\n\n    JsonSerializer s = new JsonSerializer() {\n        NullValueHandling = NullValueHandling.Ignore\n    };\n    JObject j = JObject.FromObject( new {\n        customer = hasCustomer ? new {\n            name = "mike" ,\n            age = 48\n        } : null\n    }, s );\n\n\n    JObject c = (JObject)j[ "customer" ];	0
10892942	10892854	Data Transfer Objects and Reporting	class AggregatedReportField {\n     public string FieldName { get; set; }\n     public decimal FieldValue { get; set; }\n }\n\n class ItemReportDTO {\n\n     public Dictionary<string, AggregatedReportField> ReportFields { get; private set; }\n\n     public ItemReportDTO()\n     {\n         ReportFields = new Dictionary<string, AggregatedReportField>();\n     }\n\n     public void Add(AggregatedReportField field)\n     {\n         if (!ReportFields.ContainsKey(fieldl.FieldName))\n              ReportFields.Add(field.FieldName, field);\n     }\n }	0
27000747	26999861	ENUM Alternate for displaying value	private enum Days\n{\n    [Description("Saturday")]\n    Sat,\n    [Description("Sunday")]\n    Sun,\n    [Description("Monday")]\n    Mon,\n    [Description("Tuesday")]\n    Tue,\n    [Description("Wednesday")]\n    Wed,\n    [Description("Thursday")]\n    Thu,\n    [Description("It's Friday, Friday, gotta get down on Friday")]\n    Fri\n};\n\npublic static string DescribeEnum(Enum value)\n{\n    var field = value.GetType().GetField(value.ToString());\n    var descriptionAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(\n        field, typeof(DescriptionAttribute));\n\n    return (descriptionAttribute == null)\n               ? value.ToString()\n               : descriptionAttribute.Description;\n}\n\nprivate static void Main()\n{\n    Console.WriteLine(DescribeEnum(Days.Fri));\n    // Output:\n    // It's Friday, Friday, gotta get down on Friday\n}	0
15644379	15643846	Listing all children of a process	ManagementClass mngcls = new ManagementClass("Win32_Process");\nforeach (ManagementObject instance in mngcls.GetInstances())\n{\n    Console.Write("ID: " + instance["ProcessId"]);\n}	0
18605295	18605211	ListBox items TextBlock changes based on condition	foreach (Product currentProduct in rootObject ) // Loop through List with foreach\n{\n        if(Product.realdata == 1) Price = "";\n            else {Gender =""; Age="";}\n}	0
245174	245168	Linq-to-SQL ToDictionary()	var dictionary = db\n    .Table\n    .Select(p => new { p.Key, p.Value })\n    .AsEnumerable()\n    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)\n;	0
24578075	24577781	Do overridden actions inherit action filters from the base action?	[System.AttributeUsage(System.AttributeTargets.All,\n                   AllowMultiple = false,\n                   Inherited = false)]	0
13937962	13922342	How to open up a zip file from MemoryStream	public ActionResult L2CSV()\n{\n    var posts = _dataItemService.SelectStuff();\n    string csv = CSV.IEnumerableToCSV(posts);\n    // These first two lines simply get our required data as a long csv string\n    var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));\n    var cd = new System.Net.Mime.ContentDisposition\n    {\n        FileName = "LogPosts.zip",\n        // always prompt the user for downloading, set to true if you want \n        // the browser to try to show the file inline\n        Inline = false,\n    };\n    Response.AppendHeader("Content-Disposition", cd.ToString());\n    return File(fileData, "application/octet-stream");\n}	0
1798557	1798545	How to escape a double-quote in inline c# script within javascript?	var inputId = '<%= applicationForm.FindControl("myInput").ClientID %>';	0
14369267	14369232	C# Member variable inheritance	public class MapTile\n{\n    public Texture2D Texture { get; set; }\n    public Rectangle MapRectangle { get; set; }\n\n    public MapTile(Rectangle rectangle)\n    {\n        MapRectangle = rectangle;\n    }\n}\n\npublic class GrassTile : MapTile\n{    \n    public GrassTile(Rectangle rectangle) : base(rectangle)\n    {\n        Texture = Main.GrassTileTexture;\n    }\n}	0
29218431	29218014	How can i sort two integer arrays parallel with quick sort in C#?	System.Threading.Tasks.Task.Run(() => quick_sort(a1,0,100));\nSystem.Threading.Tasks.Task.Run(() => quick_sort(a2,0,100));	0
8000187	8000165	Dynamically creating a Type	var actionType = typeof(Action<,>).MakeGenericType(type1,type2);	0
2189928	2189813	Need help for a more beautiful LINQ to SQL query	var query = from product in dc.Products\n            let groupMaxPricesQuery = dc.Products.GroupBy(p => p.ProductSubcategoryID)\n                                                 .Select(g => g.Max(item => item.ListPrice))\n            where groupMaxPricesQuery.Any(listPrice => listPrice <= product.ListPrice)\n            select product.Name;\n\n// or\nvar query = dc.Products\n              .Select(product => new {\n                  Product = product,\n                  GroupedMaxPrices = dc.Products.GroupBy(p => p.ProductSubcategoryID)\n                                                .Select(g => g.Max(item => item.ListPrice))\n            })\n            .Where(item => item.GroupedMaxPrices.Any(listPrice => listPrice <= item.Product.ListPrice))\n            .Select(item => item.Product.Name);	0
6716861	6715626	Anyone familiar with Helicon URL rewriter here? I need to know if we can create MapFiles in some drive	RewriteMap examplemap txt:C:/path/to/file/map.txt	0
21905542	21904906	Right way to make a donation button in desktop application which will navigate a user to the paypal website	private void btnDonate_Click(object sender, System.EventArgs e)\n    {\n        string url = "";\n\n        string business     = "my@paypalemail.com";  // your paypal email\n        string description  = "Donation";            // '%20' represents a space. remember HTML!\n        string country      = "AU";                  // AU, US, etc.\n        string currency     = "AUD";                 // AUD, USD, etc.\n\n        url += "https://www.paypal.com/cgi-bin/webscr" +\n            "?cmd=" + "_donations" +\n            "&business=" + business +\n            "&lc=" + country +\n            "&item_name=" + description +\n            "&currency_code=" + currency +\n            "&bn=" + "PP%2dDonationsBF";\n\n        System.Diagnostics.Process.Start(url);\n    }	0
14556908	14556842	Query to detect duplicate rows	var rows = table.AsEnumerable();\nvar unique = rows.Distinct(DataRowComparer.Default);\nvar duplicates = rows.Except(unique); // , DataRowComparer.Default);	0
819122	819036	How would you solve this data parsing problem?	type Message =\n    | Message1 of string * DateTime * int * byte //name,timestamp,size,options\n    | Message2 of bool * short * short * byte[]  //last,blocknum,blocksize,data\n    ...	0
10823210	10823107	c# How can i show an image while my application is loading	private void form1_Load(object sender, EventArgs e)\n{    \n        Form f = new Form();\n        f.Size = new Size(400, 10);\n        f.FormBorderStyle = FormBorderStyle.None;\n        f.MinimizeBox = false;\n        f.MaximizeBox = false;\n        Image im = Image.FromFile(path);\n        PictureBox pb = new PictureBox();\n        pb.Dock = DockStyle.Fill;\n        pb.Image = im;\n        pb.Location = new Point(5, 5);\n        f.Controls.Add(pb);\n        f.Show();        \n        methode1();\n        f.Close();\n}	0
6097777	6092135	Castle Windsor Proxy Abstract Class with Interface	Component.For<IFoo, Foo>().Interceptors<MyInterceptor>()	0
22163531	22163467	how to know whether it is default page or not from master page	string s = this.Page.Request.FilePath;	0
12357047	12356944	how to detect the (Shift+Delete) key press?	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.Shift && e.KeyCode == Keys.Delete) e.Handled = true;\n}	0
26324445	26324404	Using commands in a text file	StreamReader sr = new StreamReader("file1.txt");\n\nwhile ( !sr.EndOfStream )\n{\n    string line = sr.ReadLine();\n\n    string[] parts = line.Split(' ');\n    string command = parts[0].Trim();\n\n    //Use parts[x] where x > 0 to extract other items of the line\n}	0
33044206	33044052	c# service to listen to a port	WorkerThreadFunc()	0
21833406	21833185	Insert selected values from one Table to another	SqlCommand cmd2 = new SqlCommand("INSERT INTO Orders (ISBN, Title, Author, Price) "+ \n                                 "SELECT ISBN, Title, Author, Price "+\n                                 "FROM BooksInfo "+\n                                 "WHERE BooksInfo.ISBN=@Id", con);	0
25521213	25515356	Deserialize objectstring convert string to bool	Deserializing also works but it sets a field that is the XML "true" to false (probably because it can not convert to boolean true.	0
3900411	3897206	how to increment y axis values by 15 minutes using ms chart controls	Chart1.ChartAreas[0].AxisY.Minimum = (new DateTime(2010, 10, 31, 16, 00, 00)).ToOADate();\nChart1.ChartAreas[0].AxisY.Maximum = (new DateTime(2010, 10, 31, 21, 00, 00)).ToOADate();\nChart1.ChartAreas[0].AxisY.IsReversed = true;\nChart1.ChartAreas[0].AxisY.IntervalType = System.Web.UI.DataVisualization.Charting.DateTimeIntervalType.Minutes;\nChart1.ChartAreas[0].AxisY.Interval = 15;	0
24054172	24053681	How to Start the timer in the reminder app	Reminder reminder = new Reminder(name);\nreminder.Title = titleTextBox.Text;\nreminder.Content = contentTextBox.Text;\nreminder.BeginTime = beginTime; // it is the time when remider will start reminding(e.g remind me after 8 days and 2 AM hours you will set it DateTime.Now.Date.AddDays(8).AddHours(2)\nreminder.ExpirationTime = expirationTime;\nreminder.RecurrenceType = recurrence;\nreminder.NavigationUri = navigationUri;\n\n// Register the reminder with the system.\nScheduledActionService.Add(reminder);	0
5702040	5701876	Want to add Controls at Runtime in IPhone Application C#, Monotouch	// create new control\n    var control = new UIView(); // or UIButton, etc.\n\n    // set control props ..\n    control.Hidden = false;\n    control.Frame = x // = Bounds\n    // ...\n\n    // add control to parent\n    window.AddSubview(control);	0
29808751	29808718	JSON.NET: How to Serialize Nested Collections	public class Property\n{\n    [JsonProperty("alias")]\n    public string Alias { get; set; }\n\n    [JsonProperty("value")]\n    public string Value { get; set; }\n}\n\npublic class Fieldset\n{\n    [JsonProperty("properties")]\n    public Property[] Properties { get; set; }\n\n    [JsonProperty("alias")]\n    public string Alias { get; set; }\n\n    [JsonProperty("disabled")]\n    public bool Disabled { get; set; }\n}\n\npublic class Response\n{\n    [JsonProperty("fieldsets")]\n    public Fieldset[] Fieldsets { get; set; }\n}	0
11106752	11106482	DateTime.Now in C# to yield Datetime2(3) in SQL Server datatype	var format = "yyyy-MM-dd HH:mm:ss:fff";\nvar stringDate = DateTime.Now.ToString(format);\nvar convertedBack = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);	0
22742667	22742399	Hex to String Conversion & Use Part of a string	var hex = \n  data.Split(new[] {'\n','\r'}, StringSplitOptions.RemoveEmptyEntries).Last();	0
18802439	18802380	C# multiple events on a single button click?	btn1.Click += MainEvent;\nbtn2.Click += MainEvent;\nbtn3.Click += MainEvent;\n\nprotected void MainEvent(object sender, EventArgs e)\n{\n    string example;\n    if(sender == btn1)\n    {\n        example = a\n    }\n    else if(sender == btn2)\n    {\n        example = b\n    }\n    else if(sender == btn3)\n    {\n        example = c\n    }\n\n    //Do whatever with example\n}	0
11473931	11473619	Custom Authorization Attribute catch requested Role	public class AuthAttribute : AuthorizeAttribute\n{\n    protected override bool AuthorizeCore(HttpContextBase httpContext)\n    {\n        var roles = this.Roles;\n    }\n}	0
16597539	16597507	How to get combine string list from list object?	var result = LocationList.Select(x => x.ID + ";" + x.LocationName);	0
18454824	18453695	No codec available for format GIF in Ubuntu	public static byte[] ImageToByte(Image img)\n    {\n        ImageConverter converter = new ImageConverter();\n        return (byte[])converter.ConvertTo(img, typeof(byte[]));\n    }\n\nbyte[] trytry = ImageToByte(bitmap);\n                memoryStream.Write(trytry,0,trytry.Length );\n                base.Response.ClearContent();\n                base.Response.ContentType = "image/Gif";\n                base.Response.BinaryWrite(memoryStream.ToArray());	0
14094241	14094163	How to set position(margin) of BlockArrow in windows phone via c#	var margin = indic.Margin;\nmargin.Left = 400d;\nindic.Margin = margin;	0
22381767	22380428	How to make a piece of code to be executed only after the line before? (Android C#)	protected override async void OnResume()\n    {\n        base.OnResume ();\n\n        StartAnimate ();\n\n        await RunAsync (TimeSpan.FromSeconds (4));\n\n        StopAnimate ();\n    }\n\n    private async Task RunAsync(TimeSpan span)\n    {\n        await Task.Delay (span);\n    }\n\n    private void StartAnimate()\n    {\n        // put animation here\n    }\n\n    private void StopAnimate()\n    {\n        // stop animating after the thread has ended\n    }	0
7735386	7735291	Entity Framework 4.1 - How to "Force" EF To Go To DB Instead of Using Graph?	Context.Entry<T>(entity).Reload()	0
11758349	11758306	Best Class to Hold Fixed Amount of Data in C#	public void addToQueue(Object obj){\n    if (myQueue.Count > 100)\n        myQueue.Dequeue();\n\n    myQueue.Equeue(obj);\n}	0
12785102	12784588	How to implement page refresh (fetch data from server and losing all changes made) functionality in backbone.js?	Backbone.View.extend({\n\ninitialize: function(){\n    _.bindAll(this,'restore_collection');\n    this.collection.bind('reset',this.render);\n    this.originalModels = this.collection.models;    \n},\n\nevents: {   \n    "click #cancel" : "restore_collection"   \n},\n\nrestore_collection: function(){   \n    this.collection.reset(this.originalModels);    \n}	0
8563137	8563088	Opening two SQLConnections with the same ConnectionString	SqlConnection.Open()	0
21230617	21229741	Customer application icon is not showing in taskbar - why?	One assembly icon, which is specified by using the <ApplicationIcon> property\nin the application's project build file. This icon is used as the desktop\nicon for an assembly.\n\nOne icon per window that is specified by setting Icon. For each window,\nthis icon is used in its title bar, its task bar button, and\nin its ALT-TAB application selection list entry.	0
27893275	27117384	Shake Gestures Windows Phone	using ShakeGestures;  //Add the reference\n\npublic MainPage()\n{\n InitializeComponent();\n\n ShakeGesturesHelper.Instance.ShakeGesture += Instance_ShakeGesture; \n ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 10;\n ShakeGesturesHelper.Instance.Active = true;\n}\n\nvoid Instance_ShakeGesture(object sender, ShakeGestureEventArgs e)\n{\n Deployment.Current.Dispatcher.BeginInvoke(() =>\n {\n\n  //Perform the required tasks.\n });\n\n\n}	0
5689154	5689033	Method overloading in webservices	[WebMethod(MessageName = "MaxInt", Description = "Compare two int values \nand return the max value", EnableSession = true)]\npublic int MaxValue(int a, int b)\n{\n   return (a > b ? a : b);\n}\n[WebMethod(MessageName = "MaxFloat", Description = "Compare two float values \nand return the max value", EnableSession = true)]\npublic float MaxValue(float a, float b)\n{\n   return (a > b ? a : b);\n}	0
2566444	2566126	Double buffering with C# has negative effect	private void Form1_Paint(object sender, PaintEventArgs e)\n{\n    Graphics g = e.Graphics;\n    Pen pen = new Pen(Color.Blue, 1.0f);\n    Random rnd = new Random();\n    for (int i = 0; i < Height; i++)\n        g.DrawLine(pen, 0, i, Width, i);\n}	0
16922851	16906456	Display Current Video in Windows Phone 8 using AudioVideoCaptureDevice?	using Microsoft.Devices;	0
23515227	23514465	Entity Framework initializer in console/library app	public void AddFile(string fileName){\n    using(var ctx = new MyDbContext() ){\n        ctx.Files.Add(new File() { FullPath = fileName });\n        ctx.SaveChanges();\n    }\n}	0
9176515	9176221	Substring a bound String	public class DelimiterConverter : IValueConverter\n{\n    public object Convert(Object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        string[] values = ((string)value).Split("|");\n        int index = int.Parse((string)parameter);\n        return values[index];\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        return "";\n    }	0
6013356	6013334	How do you order by Greatest number in linq	var data = products.OrderByDescending(x => x.Total);	0
17949485	17949390	Log all button clicks in Win Forms app	public static void AttachButtonLogging(Control.ControlCollection controls)\n{\n    foreach (var control in controls.Cast<Control>())\n    {\n        if (control is Button)\n        {\n           Button button = (Button)control;\n           button.Click += LogButtonClick;\n        }\n        else\n        {\n            AttachButtonLogging(control.Controls);\n        }\n    }\n}	0
5868073	5868042	Instantly disable Button on click	var button = document.getElementById('yourButton');\nbutton.disabled = true;	0
11630994	11630850	converting a negative value to 0	private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    DataGridViewCell currentCell = \n        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];\n    int cellValue = Convert.ToInt32(currentCell.Value);\n    if (cellValue < 0)\n        currentCell.Value = 0.ToString();\n}	0
4674786	4674696	How to handle Url encoding in HttpListenerRequest?	public NameValueCollection QueryString\n{\n    get\n    {\n        NameValueCollection nvc = new NameValueCollection();\n        Helpers.FillFromString(nvc, this.Url.Query, true, this.ContentEncoding);\n        return nvc;\n    }\n}	0
22435214	22435146	DropDownList Showing First Item Empty	cb.SelectedIndex = 0;	0
18705261	18705219	How do I create a generic class that takes as its generic type a generic class?	public class DelayedAddConnection<T, U> where T : ICollection<U>\n{\n\n}	0
18271451	18270527	search xml using xpath - Treeview	XmlArticle.XPath = "/articles/folder/article[contains(body,'" + txbSearch.Text + "')]";	0
6983826	6983801	How to use disposable view models in WPF?	public static void HandleDisposableViewModel(this FrameworkElement Element)\n    {\n        Action Dispose = () =>\n            {\n                var DataContext = Element.DataContext as IDisposable;\n                if (DataContext != null)\n                {\n                    DataContext.Dispose();\n                }\n            };\n        Element.Unloaded += (s, ea) => Dispose();\n        Element.Dispatcher.ShutdownStarted += (s, ea) => Dispose();\n    }	0
6783578	6783509	Clear the text in multiple TextBox's at once	private void button1_Click(object sender, RoutedEventArgs e)\n    {\n        foreach (UIElement control in myGrid.Children)\n        {\n            if (control.GetType() == typeof(TextBox))\n            {\n                TextBox txtBox = (TextBox)control;\n                txtBox.Text = null;\n            }\n        }\n    }	0
31465987	31465534	Serializing a class containing a WPF Brush using `DataContractSerializer`	// example of writing\nusing (var outfile = File.CreateText("Brush.xaml"))\n{\n    XamlWriter.Save(brush, outfile);\n}\n\n// example of reading\nusing (Stream s = File.OpenRead("Brush.xaml"))\n{\n    Brush b = XamlReader.Load(s);\n}	0
2786762	2786532	change application windows style	SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd) & ~WS_CAPTION);	0
975540	975531	How to get the MonthName in c#?	using System;\nusing System.Globalization;\n\nclass Program\n{\n    static void Main()\n    {\n\n        Console.WriteLine(DateTime.Now.ToMonthName());\n        Console.WriteLine(DateTime.Now.ToShortMonthName());\n        Console.Read();\n    }\n}\n\nstatic class DateTimeExtensions\n{\n    public static string ToMonthName(this DateTime dateTime)\n    {\n        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);\n    }\n\n    public static string ToShortMonthName(this DateTime dateTime)\n    {\n        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);\n    }\n}	0
28147689	28147639	How to handle a StackOverflowException	public string Recursive(int value, int counter)\n{\n    if (counter > MAX_RECURSION_LEVEL) throw new Exception("Too bad!");\n\n    Recursive(value, counter + 1);\n    return string.Format("You entered: {0}", value);\n}	0
11698853	11698172	How to set a field of a struct type on an object in Windows Phone 7	MyStruct val = ...\nobject boxedVal = val;\nfieldInfo.SetValue(boxedVal, newValue);\nval = (MyStruct)boxedVal;	0
3899997	3899993	How to use an "&" character in a C# button text property to display properly	button.Text = text.Replace("&","&&");	0
5730672	5729888	Using StructureMap with derived interfaces	Forward<IVideoStreamTypeA, IVideoStream>();\nForward<IVideoStreamTypeB, IVideoStream>();	0
26671087	26671031	How to remote connect mysql on raspberry PI?	[mysqld]\nskip-name-resolve	0
7027564	7027519	Passing variable from view to the controller without query string	[AcceptVerbs(HttpVerbs.Post)]	0
2476388	2476374	How can i obtain in C# a specific operator's function?	Func<int, int, int> func = (val1, val2) => val1 + val2;	0
13299331	13298187	C# Winform Messy/blurry text in Datagrid	dataGridViewCellStyle30.BackColor = System.Drawing.Color.Transparent;	0
22631807	22092760	Get the index from sorted DataView	DataView dv = inputDataTable.DefaultView;\ndv.Sort = dv.Table.Columns[2].ColumnName + " ASC";\nDataTable dT = dv.ToTable();	0
16882435	16882379	Getting GetDecimal to work	using (var con = new MySqlConnection("host=*;user=*;password=*;database=*;"))\nusing (var cmd = con.CreateCommand())\n{\n    cmd.CommandText = "SELECT username, Pain FROM members WHERE username = @UserName AND password = @Password";\n    cmd.Parameters.AddWithValue("@UserName", textBox2.Text);\n    cmd.Parameters.AddWithValue("@Password", textBox3.Text);\n\n    con.Open();\n    using (var reader = cmd.ExecuteReader())\n    {\n        if (reader.Read())\n        {\n            var username = reader.GetString(0);\n\n            if (!reader.IsDBNull(1))\n            {\n                var pain = reader.GetInt32(1);\n                if (pain == 1)\n                {\n                    MessageBox.Show("NO");\n                }\n                else\n                {\n                    MessageBox.Show("YES");\n                }\n            }\n        }\n        else\n        {\n            MessageBox.Show("You Login Information is incorrect!");\n        }\n\n    }\n\n}	0
4079307	4070524	How to popup a message box in SharePoint 2010	string script = "<script language='javascript'>alert('" + errorMessage + "')</script>";\nPage.ClientScript.RegisterClientScriptBlock(GetType(), "Register", script);	0
16013751	16013556	2 POCO's with inheritance creates one table instead of two	DbSet<Employee> Employees	0
18942352	18942335	c# check if list of strings contains certain strings	IEnumerable<string> except = listOfStrings.Except(forbiddenStrings)	0
15767602	15767318	Get only http status code with sockets	i = sock.Receive(bytes, 20);	0
11212151	11212109	How to make a library method call asynchronous?	Task.Run	0
10606801	10606757	Loop through all properties of a variable. Including complex types	public Gender Mf { get; set; }	0
16968812	16968781	How can i set that the ffmpeg.exe will work as process from the directory i run my application exe file?	ffmpeg.exe	0
6409193	6409119	How can obtain mac address of the system where the application is to be installed?	var mac =\n    (from item in NetworkInterface.GetAllInterfaces()\n    where item.OperationalStatus == OperationalStatus.Up\n    select item.GetPhysicalAddress()).FirstOrDefault();	0
19994374	19994144	Remove datagrid rows based on a cell value	for(int i=dgv.Rows.count-1;i>=0;i--)\n{\n    if ((Convert.ToDateTime(row.Cells[7].Value) - DateTime.Today).Days <= 90)\n     {\n         row.DefaultCellStyle.BackColor = Color.Green;\n     }\n     else\n     {\n         dgv.rows.removeAt(i);\n     }\n}	0
31484304	31479451	MVC 6 VNext How to set same layout from different areas	Layout = "~/Views/Shared/_Layout.cshtml";	0
30688646	30688622	Specific Date Format in C#	formattedDate = dateTime.ToString("yyyy'?'MM'?'dd'?'");	0
8750606	8750484	Make controls and their font bigger	this.Font = new Font(this.Font.FontFamily, 1.25f * this.Font.Size);	0
12296039	12295937	Decoding a string in C#	public static String Decode(String query) {\n    return query.Replace("_", " ").Replace("@46@", ".");\n}	0
11976283	11976168	Need DataGridView Update	public partial class Form1 : Form \n    { \n        OleDbConnection baglanti = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Burak YE??LYURT\Desktop\secret.accdb"); \n        OleDbCommand komutcu; \n        OleDbDataAdapter adpt; \n        DataSet ds; \n        public Form1() \n        { \n            InitializeComponent(); \n            baglanti.Open(); \n            komutcu = new OleDbCommand("SELECT * FROM todo", baglanti); \n            adpt = new OleDbDataAdapter(komutcu); \n            ds = new DataSet(); \n            adpt.Fill(ds); \n            dataGridView1.DataSource = ds.Tables[0]; \n\n        } \n\n        private void button1_Click(object sender, EventArgs e) \n        { \n            OleDbCommandBuilder komut = new OleDbCommandBuilder(adpt); \n            DataSet yeni = new DataSet(); \n            yeni = ds.GetChanges(DataRowState.Modified); //here i get the error\n            adpt.Update(yeni.Tables[0]); \n        } \n    }	0
14420800	14420764	Multiple threads to write to Array	Thread.Join	0
16469660	16469256	Changing access modifier of CreateRow method of GridView	// Get your DataSet from the database\nDataSet data = getMyDataSomeHow();\n// Create a blank row\nobject[] newRow = new object[3]; // where "3" is the number of columns in your table\nnewRow[0] = "";\nnewRow[1] = "";\nnewRow[2] = "";\n//Add the blank row\ndata.Tables["myTable"].BeginLoadData();\ndata.Tables["myTable"].LoadDataRow(newRow, true);\ndata.Tables["myTable"].EndLoadData();	0
8809409	8809354	Replace first occurrence of pattern in a string	var regex = new Regex(Regex.Escape("o"));\nvar newText = regex.Replace("Hello World", "Foo", 1);	0
10908787	10904113	Select specific cell in Excel and go to next row	Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();\nexcel.Workbooks.Add(System.Reflection.Missing.Value);\nint rowIdx = 2;\nforeach (CFolderType ft in FolderTypes) \n{\n    Microsoft.Office.Interop.Excel.Range aCell = excel.get_Range("A" + rowIdx.ToString(), System.Reflection.Missing.Value); \n    aRange.Value = ft.name;\n    rowIdx++;\n}	0
4417066	4417043	In .NET Windows Forms, how can I send data between two EXEs or applications?	.NET Remoting	0
10818864	10818391	Sending large data from WCF Server to Delphi Client	[OperationContract]\nstring DownloadFile(string filePath);	0
16344283	16343844	how to add custom parameters to membership create user wizard?	{\n    FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie: false);\n\n    //If user is created, get it by UserName\n    MembershipUser createdUser = Membership.GetUser(RegisterUser.UserName);       \n    Guid userID = new Guid(createdUser.ProviderUserKey.ToString());\n\n    TextBox ImageUrl = RegisterUserWizardStep.ContentTemplateContainer.FindControl("ImageUrl") as TextBox;\n\n    //Use the userID from the above code\n    UserProfile.SaveNewProfileInformation(userID, ImageUrl.Text);\n}	0
10903177	10903122	Calling method with linq syntax based on condition	somelist.Where(i => i.DeptType == 1 && i != null)\n           .ToList()\n           .ForEach( i=> MyMethod(i.someInt));	0
16021125	16020547	Parse String into a DateTime Object in C#	string dtObjFormat = "dd MMM yyyy HH:mm";\nstring mydatetimemash = e.Date + " " + e.Time; // this becomes 25 May 2013 10:30\nDateTime dt;\n\nif (DateTime.TryParseExact(mydatetimemash, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))\n{\n    Console.WriteLine(dt);\n} else \n{\n    dt = DateTime.Now;\n    Console.WriteLine(dt);\n}	0
9206104	9203943	run shell command for third party application, pass file arguements	string args = String.Format(@"{0}", "A File Arg");\nproc.StartInfo.Arguments = args;	0
9594668	9594649	Test for multiple values in an if statement in C#	if ((new[]{1, 2, 5, 13, 14}).Contains(x)) ...	0
20655805	20655763	Distinct a list with objects by id	var ListOfUsers = ListOfAllUsers.GroupBy(x => x.Id)\n                                  .Select(g => g.First())\n                                  .ToList();	0
13193506	13193212	Using .DrawToBitmap - how to change resolution of image?	Bitmap CreateBitmapImage(string text, Font textFont, SolidBrush textBrush)\n    {\n        Bitmap bitmap = new Bitmap(1, 1);\n        Graphics graphics = Graphics.FromImage(bitmap);\n        int intWidth = (int)graphics.MeasureString(text, textFont).Width;\n        int intHeight = (int)graphics.MeasureString(text, textFont).Height;\n        bitmap = new Bitmap(bitmap, new Size(intWidth, intHeight));\n        graphics = Graphics.FromImage(bitmap);\n        graphics.Clear(Color.White);\n        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n        graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;\n        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n        graphics.DrawString(text, textFont, textBrush,0,0);\n        graphics.Flush();\n        return (bitmap);\n    }	0
12044736	12044499	Calling one event method from another event method with passing a parameter	private static bool UserConfirmedToLogout() \n{\n    return MessageBox.Show("Bla, bla?", "Logout", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK;\n}\n\nprivate void FormMain_FormClosing(object sender, FormClosingEventArgs e)\n{\n    e.Cancel = !UserConfirmedToLogout();\n}\n\nprivate void btnLogOut_Click(object sender, EventArgs e)\n{            \n    Close();\n}	0
3351913	3351878	How to check for existence of an element with XElement?	return (from p in ontology.Elements(rdf + "Property") \nlet xRange = p.Element(rdfs + "range") \nselect new MetaProperty \n{ \n    About = p.Attribute(rdf + "about").Value, \n    Name = p.Element(rdfs + "label").Value, \n    Comment = p.Element(rdfs + "comment").Value, \n    RangeUri = xRange == null ? null : xRange.Attribute(rdf + "resource").Value \n}).ToList();	0
4510026	4509965	C# How to derive the relative-filepath of file located in grand-parent folder?	../../image.png	0
23842662	23842533	Getting NotSupportedException when trying to set image from isolated storage	new Uri(@"isostore:" + filePath, UriKind.Absolute);	0
9699500	9699181	Retrieve database content without linebreak	LitContent.Text = textService.GetText("ContactInfo").Replace("<br />", " ");	0
9911921	9904190	Set Ajax ConfirmButtonExtender ConfirmText value dynamically	if(!isPostBack)\n{\n   cbe_btnVoid.ConfirmText = Utils.setConfirmTextValue();\n}	0
3855159	3854679	How to make application stop and run debugger?	Debugger.Break()	0
23584549	23584363	TCP StreamSocket data receiving	byte[] data   = SomeData();\nbyte[] length = System.BitConverter.GetBytes(data.Length);\nbyte[] buffer = new byte[data.Length + length.Length];\nint offset = 0;\n\n// Encode the length into the buffer.\nSystem.Buffer.BlockCopy(length, 0, buffer, offset, length.Length);\noffset += length.Length;\n\n// Encode the data into the buffer.\nSystem.Buffer.BlockCopy(data, 0, buffer, offset, data.Length);\noffset += data.Length;  // included only for symmetry\n\n// Initialize your socket connection.\nSystem.Net.Sockets.TcpClient client = new ...;\n\n// Get the stream.\nSystem.Net.Sockets.NetworkStream stream = client.GetStream();\n\n// Send your data.\nstream.Write(buffer, 0, buffer.Length);	0
14242654	14242439	How can I disable the Caps Lock warning with a password control?	protected override void WndProc(ref Message m)\n{\n  if (m.Msg != 0x1503) //EM_SHOWBALOONTIP\n     base.WndProc(ref m);\n}	0
12409384	12407732	Binding Variable in List to Textblock INotifyPropertyChanged	Binding b = new Binding("CurrentTitle");\nb.Source = c;\nxTitel.SetBinding(TextBlock.TextProperty, b);	0
11155832	7981843	How to determine if there is a valid Lync user by email using Lync SDK?	lyncClient.ContactManager.GetContactByUri()	0
26184583	26184549	Performing a JOIN in LINQ in C#	var results = from address in addresses\n              join store in stores\n              on address.ID equals store.AddressID\n              where (address.City == 'Seattle')\n              select store;	0
5410911	5410838	Sequence of writing a File in C#	BinaryWriter.Write	0
29732917	29732864	str.Substring(n,2) How to bypass ArgumentOutOfRangeException	if(n + 2 > str.Length)\n    return str.Substring(0,2);\nelse \n    return str.Substring(n,2);	0
17260290	6990347	How to decode "\u0026" in a URL?	System.Text.RegularExpressions.Regex.Unescape(str);	0
29911765	29890396	How do I fade a picturebox image to another on mousehover event?	int opacity = 0;\n\nprivate void tmrFadeOut_Tick(object sender, EventArgs e)\n{\nif (opacity < 255)\n{\n    Image img = myImage.Image;\n    using (Graphics g = Graphics.FromImage(img))\n    {\n        Pen pen = new Pen(Color.FromArgb(opacity, 255, 255, 255), img.Width);\n        g.DrawLine(pen, -1, -1, img.Width, img.Height);\n        g.Save();\n    }\n    myImage.Image = img;\n    opacity++;\n}\nelse\n{\n    timer1.Stop();\n}\n}	0
13051031	13050995	how to create an instance of class and set properties from a Bag object like session	Type myType = Type.GetType(className);\nvar instance = System.Activator.CreateInstance(myType);\nPropertyInfo[] properties = myType.GetProperties();\n\nforeach (var property in properties)\n{\n    property.SetValue(instance, session[property.Name], null);\n}	0
13086068	13082848	Error changing a file's access control at install time	SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);\nstring pathVersioningDat = ConfigurationManager.GetPath("versioning.dat", true);\nFileSystemAccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow);\nFileSecurity fSecurity = File.GetAccessControl(pathVersioningDat);\nfSecurity.SetAccessRule(rule);\nFile.SetAccessControl(pathVersioningDat, fSecurity);	0
32179708	32176651	Visit and modify all documents in a solution using Roslyn	var solution = await msWorkspace.OpenSolutionAsync(solutionPath);\n\nforeach (var projectId in solution.ProjectIds)\n{\n    var project = solution.GetProject(projectId);\n    foreach (var documentId in project.DocumentIds)\n    {\n        Document document = project.GetDocument(documentId);\n\n        if (document.SourceCodeKind != SourceCodeKind.Regular)\n            continue;\n\n        var doc = document;\n        foreach (var rewriter in rewriters)\n        {\n            doc = await rewriter.Rewrite(doc);\n\n        }\n\n        project = doc.Project;\n    }\n    solution = project.Solution;\n}\nmsWorkspace.TryApplyChanges(solution);	0
15900849	15900784	How to View Data from MS Access in Data Grid View?	string strProvider = "@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";\nstring strSql = "Select * from score";\nOleDbConnection con = new OleDbConnection(strProvider);\nOleDbCommand cmd = new OleDbCommand(strSql, con);\ncon.Open();\ncmd.CommandType = CommandType.Text;\nOleDbDataAdapter da = new OleDbDataAdapter(cmd);\nDataTable scores = new DataTable();\nda.Fill(scores);\ndataGridView1.DataSource = scores;	0
22800078	22798274	How to access third Nested ListView properties	protected void lv2_ItemDataBound(object sender, ListViewItemEventArgs e) {\n    ListView lv3 = (ListView)e.Item.FindControl("lv3");\n}	0
1822509	1822262	Sorting a DataGridView by DataGridViewComboxBoxColumn	public partial class Form1 : Form\n{\n\n    public Form1()\n    {\n        InitializeComponent();\n        DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn) dataGridView1.Columns[1];\n        DataGridViewComboBoxColumn col2 = (DataGridViewComboBoxColumn)dataGridView1.Columns[2];\n        List<string> items = new List<string>(){"B", "C", "E", "A"};\n        col.DataSource = items;\n        col.SortMode = DataGridViewColumnSortMode.Automatic;\n        col2.DataSource = items;\n        col2.SortMode = DataGridViewColumnSortMode.Automatic;\n\n        dataGridView1.Rows.Add(new string[] {"A", "B", "C", "D"});\n        dataGridView1.Rows.Add(new string[] { "B", "C", "C", "F" });\n        dataGridView1.Rows.Add(new string[] { "C", "B", "A", "A" });\n    }        \n}	0
3214848	3208509	WinForms: Cannot get ValidateChildren to raise Validating event of a child control	SetStyle(ControlStyles.Selectable, true);	0
25728667	25728541	Looping through a model to check for propery that is null	foreach (PropertyInfo pinfo in obj.GetType().GetProperties())\n{\n    object value = pinfo .GetValue(obj, null);\n}	0
12035073	12032973	Setting Application.Resources through C#	App.Current.Resources.Add("Key",Value);	0
8186489	8184951	WCF 4.0 - Get Parameter from URL or POST Body	OperationContext.Current.RequestContext.RequestMessage.GetBody<string>();	0
22645092	22644737	How to clear or update the content of an element in a grid in WPF	foreach (UIElement control in MyGrid.Children)\n{\n    if (Grid.GetRow(control) == row && Grid.GetColumn(control) == col)\n    {\n        MyGrid.Children.Remove(control);\n        break;\n    }\n}	0
24038896	24038754	Displaying 5 strings from an array	footlockerArray\n        .Where(o => o.StartsWith("F"))\n        .Reverse()\n        .Take(5)\n        .Reverse()\n        .ToList()\n        .ForEach(o => footlockerExistingBlogTextBox.Text += o);	0
30541235	30541199	Instantiating all possible combinations of enums	public class foo\n{\n    private enumA enumAfoo;\n    private enumB enumBfoo;\n\n    public foo()\n    {\n    }\n    public foo(enumA A, enumB B)\n    {\n        enumAfoo = A;\n        enumBfoo = B;\n    }\n    public override string ToString()\n    {\n        return enumAfoo.ToString() + "," + enumBfoo.ToString();\n    }\n}	0
5013453	5013416	combobox contains specified value	if (comboBox1.Items.Contains("some value"))\n{\n\n}	0
26561639	26559939	C# Collection Get True of False by matching items	IDictionary<string, HashSet<string>> sets = new Dictionary<string, HashSet<string>>();\n        sets.Add("Stage 1", new HashSet<string>{ "A","B","C"});\n        sets.Add("Stage 2", new HashSet<string>{ "D","E"});\n\npublic static bool GetAllowed(string stage,string status, IDictionary<string,HashSet<string>> allowedSets)\n    {\n        return allowedSets[stage].Contains(status);\n    }\n\nConsole.WriteLine(GetAllowed("Stage 1", "A", sets)); // returns true\nConsole.WriteLine(GetAllowed("Stage 2", "A", sets)); //returns false	0
699433	699418	LINQ: Select data from a single column in IQueryable<>	public IQueryable<string> FindSomeObject()\n{\n    return from myObj in db.TableName\n        orderby myObj.colName\n        select myObj.colName;\n}	0
10579614	10579446	Capturing Application exit event - WinForms	[STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.ApplicationExit += new EventHandler(Application_ApplicationExit);\n        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);\n        Application.Run(new MainForm());\n    }	0
27327511	27301117	Is there a way to set time portion of DateTime to 0:00:00 in the result set using LinqToSql?	var result = from t in db.table select DateCreated = System.Data.Entity.DbFunctions.TruncateTime(t.DateCreated)	0
14498330	14487522	How to launch multiple instances of a console application in separate app domains?	var appDomain = AppDomain.CreateDomain("a name");\n\nappDomain.ExecuteAssembly("ConsoleApplicationB.exe"); //Update with the path to consolse application B.          \n\nAppDomain.Unload(appDomain);	0
15562970	15541600	Inserting the content to the colume in sqlite	using (SQLiteTransaction SQLiteTrans = connection.BeginTransaction())\n               {\n                   using (SQLiteCommand cmd = connection.CreateCommand())\n                   {\n                     cmd.CommandText = ("update contents set content_1 ='" + paraNode + "' where content_id ='" + Count + "'");\n\n\n                       SQLiteParameter Field1 = cmd.CreateParameter();\n                       SQLiteParameter Field2 = cmd.CreateParameter();\n                       cmd.Parameters.Add(Field1);\n                       cmd.Parameters.Add(Field2);\n                       cmd.ExecuteNonQuery();\n                   }\n                   SQLiteTrans.Commit();\n               }	0
8143082	8142910	How to perform a hierarchical LINQ to XML query?	var input = @"<root>\n    <parent name=""george"">\n        <child name=""steve"" age=""10"" />\n        <child name=""sue"" age=""3"" />\n        <pet type=""dog"" />\n        <child name=""jill"" age=""7"" />\n    </parent>\n</root>";\n\nvar xml = XElement.Parse(input);\nvar query = from p in xml.Elements("parent")\n            select new XElement("node",\n                new XAttribute("type", p.Name),\n                new XAttribute("label", p.Attribute("name").Value),\n                from c in p.Elements("child")\n                select new XElement("node",\n                    new XAttribute("type", c.Name),\n                    new XAttribute("label", c.Attribute("name").Value),\n                    new XAttribute("years", c.Attribute("age").Value)));	0
32598877	32598209	How to parse the this text and build an object	private void ParseXML()\n{           \n    string xml = "<root><NAME>Robert</NAME> <TYPE>Type 2</TYPE><ADDRESS>Address 1</ADDRESS><ADDRESS>Address 2</ADDRESS><CITY>City For Address 1</CITY><CITY>City For Address 2</CITY><ZIP>Zip For City 1</ZIP><ZIP>ZIP For City 2</ZIP></root>";\n    var xDoc = XDocument.Parse(xml);\n    int count = xDoc.Descendants("ADDRESS").Count();\n    var addressDict = new Dictionary<XElement, Dictionary<XElement, XElement>>();\n    int skipIndex = 0;\n    for (int takeIndex = 1; takeIndex <= count; takeIndex++)\n    {\n        var cityAndZIPDict = new Dictionary<XElement,XElement>();\n        cityAndZIPDict.Add(xDoc.Descendants("CITY").Skip(skipIndex).Take(takeIndex).First(),xDoc.Descendants("ZIP").Skip(skipIndex).Take(takeIndex).First() );\n        addressDict.Add(xDoc.Descendants("ADDRESS").Skip(skipIndex).Take(takeIndex).First(), cityAndZIPDict);\n        skipIndex++;\n    }\n}	0
4151222	1987507	How to deploy after a build with TeamCity?	/p:Configuration=QA  \n/p:OutputPath=bin  \n/p:DeployOnBuild=True  \n/p:DeployTarget=MSDeployPublish  \n/p:MsDeployServiceUrl=https://myserver:8172/msdeploy.axd  \n/p:username=myusername  \n/p:password=mypassword  \n/p:AllowUntrustedCertificate=True  \n/p:DeployIisAppPath=ci  \n/p:MSDeployPublishMethod=WMSVC	0
9535191	9535153	How to format a string in a linq expression?	var customers = db.Customers\n                  .Where(c => c.CstCompanyName.Contains(prefixText))\n                  .Select(c => new { c.CstCompanyName, c.CstPhone })\n                  .AsEnumerable() // Switch to in-process\n                  .Select(c => c.CstCompanyName + \n                               " (Phone: " +            \n                               Convert.ToInt64(Customers.CstPhone)\n                                      .ToString("###-###-#### ####") + ")");	0
9669304	9668905	Can I save a postback status and restore it?	protected void Page_Load(object sender, EventArgs e)\n{\n btnBackButton.Attributes.Add("onClick", "javascript:window.history.go(-1);return false;");\n}	0
1406853	1406808	Wait for file to be freed by process	public static bool IsFileReady(String sFilename)\n    {\n        // If the file can be opened for exclusive access it means that the file\n        // is no longer locked by another process.\n        try\n        {\n            using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))\n            {\n                if (inputStream.Length > 0)\n                {\n                    return true;\n                }\n                else\n                {\n                    return false;\n                }\n\n            }\n        }\n        catch (Exception)\n        {\n            return false;\n        }\n    }	0
13840467	13639261	How do I retrieve the list from said pointer?	var offset = (int)Marshal.SizeOf(typeof(DHCP_OPTION_DATA));\nvar alignment = 4; \nvar remainder = offset % alignment;\nif(remainder != 0)\n    offset += alignment - remainder;\n\noptionArray.Options = (IntPtr)((int)optionArray.Options + offset);	0
5136428	5136418	listbox Refresh() in c#	listBox1.DataBind()	0
5464974	5461564	Need domain modeling advice - hopefully common scenario	public class PersonMap:ClassMap<Person>\n{\n    public PersonMap()\n    {\n        Table("Person");\n        Id(x=>Id).Column("PersonID");\n        References(x=>x.Student).KeyColumn("StudentID")\n            Nullable().Cascade.All();\n        References(x=>x.Teacher).KeyColumn("TeacherID")\n            Nullable.Cascade.All();\n    }\n}\n\n\npublic class TeacherMap:ClassMap<Teacher>\n{\n    public TeacherMap()\n    {\n        Table("Teacher");\n        Id(x=>Id).Column("TeacherID");\n        References(x=>x.Person).KeyColumn("PersonID")\n            .Not.Nullable().Cascade.None();        \n    }\n}\n\npublic class StudentMap:ClassMap<Student>\n{\n    public StudentMap()\n    {\n        Table("Student");\n        Id(x=>Id).Column("StudentID");\n        References(x=>x.Person).KeyColumn("PersonID")\n            .Not.Nullable().Cascade.None();        \n    }\n}	0
10231068	10208798	wpf, c#, renderTargetBitmap of viewport3D without assigning it to a window	int width = 500;\nint height = 300;\nCurViewport3D.Width = width;\nCurViewport3D.Height = height;\nCurViewport3D.Measure(new Size(width, height));\nCurViewport3D.Arrange(new Rect(0, 0, width, height));	0
5395840	5394540	Best pattern for a monthly billing cycle	bool NeedToBill = ((DateTime.UTCNow ??? LastBillDate) >= 30 Days)	0
733252	733210	How do I loop backwards from SiteMap.CurrentNode to SiteMap.RootNode	SiteMapNode currentNode = SiteMap.CurrentNode;\nSiteMapNode rootNode = SiteMap.RootNode;\nStack<SiteMapNode> nodeStack = new Stack<SiteMapNode>();\n\nwhile (currentNode != rootNode)\n{\n    nodeStack.Push(currentNode);\n\n    currentNode = currentNode.ParentNode;\n}\n\n// If you want to include RootNode in your list\nnodeStack.Push(rootNode);\n\nSiteMapNode[] breadCrumbs = nodeStack.ToArray();	0
14973481	14973293	How to create Array of matchcollection	var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";\nvar allInput = piWorkitem.ResponsibleConsultant + " " + piWorkitem.SupplierConsultant;\nvar emailCollection = Regex.Matches(allInput , patternEmail);\nforeach (Match mail in emailCollection.Cast<Match>().Where(mail => emailaddresses.Contains(mail.Value.ToString())))\n{\n    emailaddresses.Add(mail.Value);\n}	0
1470644	1470612	Dymanic Controls C# Accessing without Name property	foreach(Control control in myPanel.Controls)\n  control.Backcolor=Color.Black;	0
24775802	24775658	How to extract specific number in a string surrounded by numbers and text C#	string rx = "Q23-00000012-A14"\n string numb = int.parse(rx.Split('-')[1]).ToString();//this will get 12 for you\n\n txtResult.Text = numb;	0
24987581	24987379	Convert one byte to signed byte or int	byte b = 0xfc;\nsbyte s = unchecked((sbyte)b);	0
20032439	20032397	Group or extract elements from Tupled list by their names c#	var result = input.GroupBy(t=>t.Item3, (key,items)=>items.ToList()).ToList();\n// \n//list1 = result[0];\n//list2 = result[1]; ...	0
4162797	4162776	Accessing a Private Constructor from Outside the Class in C#	var constructor = typeof(Bob).GetConstructor(BindingFlags.NonPublic|BindingFlags.Instance, null, new Type[0], null);\nvar instance = (Bob)constructor.Invoke(null);	0
30322948	30322849	Deserialize a JSON object with Ref property	public class PushEvent\n{\n    public string @ref { get; set; }	0
18267513	18264407	Session Getting Lossed after Hyperlink Clicked	NavigateUrl = Response.ApplyAppPathModifier(yoururl);	0
23442706	23442671	Extract Parameter from Url	string url = "http://www.mysite.com/itm/Sector-Watch/271443634510?pt=Orologi_da_Polso&hash=item3f334d294e";\n    Uri uri = new Uri(url);\n    var whatYouWant = uri.Segments[3];	0
9210790	9210728	dynamically resolving types from an Assembly loaded through Reflection	ISomeInterface obj = Activator.CreateInstance(typeOfClass) as ISomeInterface;	0
24010368	24010292	How to check from which action I came in asp.net mvc	Request.UrlRefferer	0
10485015	10484295	Image Resizing from SQL Database on the fly with MVC2	public FileContentResult ShowPhoto(int id)\n    {\n       TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();\n       tempImageUpload = _service.GetImageData(id) ?? null;\n       if (tempImageUpload != null)\n       {\n          byte[] byteArray = tempImageUpload.TempImageData;\n          using(var outStream = new MemoryStream()){\n              using(var inStream = new MemoryStream(byteArray)){\n                  var settings = new ResizeSettings("maxwidth=200&maxheight=200");\n                  ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);\n                  var outBytes = outStream.ToArray();\n                  return new FileContentResult (outBytes, "image/jpeg");\n              }\n          }\n       }\n       return null;\n    }	0
20731397	20730886	Entity Framework incremented index property for groups	var query = _data.Quotes\n    .GroupBy(x => x.Person.Name)\n    .ToList()\n    .Select\n    (\n        x => x.Select((y, i) => new { y.Person.Name, y.Text, Index = i + 1 })\n    )\n    .SelectMany(x => x);	0
13330400	13330365	Web API with EF 5 - JSON Response Explanation	public IEnumerable<Vehicle> Get()\n{\n   return Uow.Vehicles.GetAll().Include(v => v.VehicleMake)\n           .OrderBy(v => v.VehicleMake.Description);\n}	0
180678	179480	Creating local users on remote windows server using c#	DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://ComputerName" & ",computer", "AdminUN", "AdminPW");\nDirectoryEntry user = directoryEntry.Children.Add("username", "user");\nuser.Invoke("SetPassword", new object[] { "password"});\nser.CommitChanges();	0
9701664	9701309	Get app relative url from Request.Url.AbsolutePath	// create an absolute path for the application root\nvar appUrl = VirtualPathUtility.ToAbsolute("~/");\n\n// remove the app path (exclude the last slash)\nvar relativeUrl = HttpContext.Current.Request.Url.AbsolutePath.Remove(0, appUrl.Length - 1);	0
5807307	5807134	WCF Data Service : Many to many query	var qry =  service.StudentClasses\n              .Expand("Classes")\n              .Where(x=>x.StudentId==1)\n              .First()\n              .Classes.Select(t=>t);	0
31257183	31256829	Action route optional id parameter	[Route("tasks/{id?}")]\npublic ActionResult Index(string id =null)	0
8724794	8724676	How to use multiple models in MVC3 asp	public class SomeViewModel\n{ \n   public User CurrentUser { get; set; }\n   public IEnumerable<mymodel.CarsForHire> Cars { get; set; }\n}	0
32518271	32517954	Download pdf and mp3 from libsyn	Process.Start();	0
1212774	1212738	Validate Linq2Sql before SubmitChanges()	ChangeSet changes = dataContext.GetChangeSet();\n\n// An IList<Object>\nchanges.Deletes;\nchanges.Inserts;\nchanges.Updates;	0
3059102	3059093	How would I make a datetime into a specific custom format?	yourdatetimeObj.ToString("yyyyMMdd");	0
7207842	7207732	How to read a relative web path with Server.MapPath with space character in filename or path in C#	src = Request.QueryString["imgsrc"];//src = "images/file 15.jpeg";\n\nstring tempPath = Server.MapPath(src);\n\nDebug.Assert(System.IO.File.Exists(tempPath);\n\nSystem.Drawing.Image image = System.Drawing.Image.FromFile(tempPath);	0
11188962	11187642	Removing style from a string retrieved from WordDocument with Open XML Office SDK	String str = Matches[i].ToString();\nstr = Regex.Replace(str, @"<(.|\n)*?>", "");\nlb.Text  = str;	0
17358962	17358379	dataGridView Controlled context menu click	int RowIndex = 0;\nprivate void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n{\n    if (dataGridView1.CurrentRow == null)\n        return;           \n\n    if (e.Button == MouseButtons.Right)\n    {\n        RowIndex = dataGridView1.CurrentRow.Index ;               \n    }\n}\n\nprivate void testToolStripMenuItem_Click(object sender, EventArgs e) //MenuStrip item click event\n{\n    if (RowIndex == 0)\n    {\n\n    }\n    else if (RowIndex == 1)\n    {\n\n    }\n}	0
19778755	19778633	Trying to make a synchronous task into an asynchronous task	public async Task<List<CustomerEmail>> GetCustomerDropDownList()\n{\n    try\n    {\n        using (YeagerTechEntities DbContext = new YeagerTechEntities())\n        {\n            DbContext.Configuration.ProxyCreationEnabled = false;\n            DbContext.Database.Connection.Open();\n\n            var customers = await DbContext.Customers.Select(s =>\n            new CustomerEmail()\n            {\n                CustomerID = s.CustomerID,\n                Email = s.Email\n            }).ToListAsync();\n        }\n\n        return customers;\n    }\n    catch (Exception ex)\n    {\n        throw ex;\n    }\n}	0
24799346	24799298	Bridge method with a generic interface to a number of overloaded methods	return (T) (object) 5.0;	0
3514781	3514740	How to split an array into a group of n elements each?	int i = 0;\nvar query = from s in testArray\n            let num = i++\n            group s by num / 3 into g\n            select g.ToArray();\nvar results = query.ToArray();	0
11026627	11026590	How to call a WCF service Synchronously	var client = new MyService.MyServiceClient();\nclient.DoSomething();	0
1703032	1690093	Winforms Disabling Control Box from showing up	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n { \n   if (keyData == (Keys.RButton | Keys.ShiftKey | Keys.Alt))\n         { return true; }\n    return base.ProcessCmdKey(ref msg, keyData); \n  }	0
13699890	13626124	How to ignore the automatic page breaks?	PageSetup.Zoom = false;	0
8234423	8234397	Is it possible to build a query based on values in a String list?	// This is the declaration for an array:\nint[] artList = new int [] {14891, 14989, 14899}; \n// And your query is just fine! Of course, you knew that, right? :)\nvar query = from c in classTable where artList.contains(c.classID) select c;	0
25042328	24845536	3D animation with bones and their matrices	Matrix[] BoneTransforms = animtionPlayer.GetWorldTransforms();\nfor (int i = 0; i < BoneTransforms.Length; i++)\n{\n    Vector3 v3 = new Vector3(BoneTransforms[i].M41, BoneTransforms[i].M42, BoneTransforms[i].M43);\n    v3 = Vector3.Transform(v3, GetWorld(Position, Rotation, Scale));//GetWorld is the models world matrix: position, rotation and scale.\n    Game1.DrawMarker(v3); //v3 is the position of the current Bone.\n}	0
14321565	14320884	how to configure a local database so that it works in all computers	msiexec /i SqlLocalDB2012.msi /qn IACCEPTSQLLOCALDBLICENSETERMS=YES	0
26629935	26629753	how do i fix this simple windows forms application	private void button1_Click(object sender, EventArgs e)\n{\n    double answer;\n    double num;\n    double Filename \n    if (double.TryParse(File.ReadAllText(@"C:/temp/hinnat.txt"), out Filename)\n       && double.TryParse(textBox1.Text, out num))\n    {\n        answer = Filename * num;\n        textBox2.Text = answer.ToString();\n    }\n}	0
33593686	33592851	Aggregate function on multiple columns in DataTable	DataTable dtNew =new DataTable("NewDataTable");\ndtNew.Columns.Add("Date");\ndtNew.Columns.Add("Date1");\ndtNew.Columns.Add("Visits",typeof(int));\ndtNew.Columns.Add("M",typeof(int));\ndtNew.Columns.Add("F",typeof(int));\n\n\ndt.AsEnumerable()\n  .GroupBy(grp => new\n    {\n       Date = grp.Field<string>("Date"),\n       Date1 = grp.Field<string>("Date1")\n    })\n   .Select(d =>\n       {\n         DataRow dr = dtNew.NewRow();\n         dr["Date"] = d.Key.Date;\n         dr["Date1"] = d.Key.Date1;\n         dr["Visits"] = d.Sum(r => r.Field<int>("Visits"));\n         dr["M"] = d.Sum(r => r.Field<int>("M"));\n         dr["F"] = d.Sum(r => r.Field<int>("F"));\n         return dr;\n       })\n    .CopyToDataTable(dtNew, LoadOption.OverwriteChanges);	0
9266837	9266709	How to download a file from my webserver to my desktop?	const string fName = @"C:\picture.bmp";\n  FileInfo fi = new FileInfo(fName);\n  long sz = fi.Length;\n\n  Response.ClearContent();\n  Response.ContentType = Path.GetExtension(fName);\n  Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(fName)));\n  Response.AddHeader("Content-Length", sz.ToString("F0"));\n  Response.TransmitFile(fName);\n  Response.End();	0
13961867	13961735	Losing formating when displaying text as a label	label.Text = myText.Replace("\r\n", "<br>").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");	0
25389016	25381007	Json to google charts	var google_data = {\n        "cols": [{\n            "type": "string"\n        }, {\n            "type": "number"\n        }],\n        rows: []\n    };\n\n    for(var i=0;i<jsonData.length;i++){\n        google_data.rows.push({c:[{v:jsonData[i].ESTADO}, {v:jsonData[i].CNT}]});\n    }\n\n\n\n\n    var data = new google.visualization.DataTable(google_data);	0
32149457	32121338	How to remove item from listbox and have changes reflected in entity	private void Form1_Load(object sender, EventArgs e)\n    {\n        list1 = new List<Person>();\n\n        using (SportsClubEntities spe = new SportsClubEntities())\n        {\n            list1 = (from p in spe.People\n                      select p).ToList();\n        }\n\n        bs = new BindingSource();\n        bs.DataSource = list1;\n\n        listBox1.DataSource = bs;\n        listBox1.DisplayMember = "FirstName";\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Person p1 = (Person)listBox1.SelectedItem;\n        list1.Remove((Person)listBox1.SelectedItem);\n        bs.ResetBindings(false);\n\n        using (SportsClubEntities spe = new SportsClubEntities())\n        {\n            Person p2 = (from p in spe.People\n                     where p.BusinessEntityID == p1.BusinessEntityID\n                     select p).FirstOrDefault();\n\n            spe.People.Remove(p2);\n            spe.SaveChanges();\n        }\n    }	0
2588154	2588135	How do I include a newline in a text message sent as email from an ASP.Net application?	.AppendLine(stuff);	0
31745975	31745199	Redirect to a page after a pop up opens	var btnVerify = document.getElementById("btnVerify");\nbtnVerify.addEventListener("click", function() {\n    window.open('GetDocs.aspx', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');\n    window.location.href = "somewebpage.aspx";\n});	0
15142835	15142742	How do i fix the if statement in a SignUp page?	// if exists, show a message error\nif (exists)\n{\n    MessageBox.Show("Username: " + txtUsername.Text + "  already Exists");\n           //errorPassword.SetError(txtUsername, "This username has been using by another user.");\n}\nelse\n{\n    // does not exists, so, persist the user\n    using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] values (@Forename, @Surname, @Username, @Password)", con))\n    {\n         cmd.Parameters.AddWithValue("@Forename", txtForename.Text);\n         cmd.Parameters.AddWithValue("@Surname", txtSurname.Text);\n         cmd.Parameters.AddWithValue("@UserName", txtUsername.Text);\n         cmd.Parameters.AddWithValue("@Password", txtPassword.Text);\n\n         cmd.ExecuteNonQuery();\n    }\n    MessageBox.Show("Sucessfully Signed Up");\n    Form1 signin = new Form1();\n    signin.Show();\n    this.Close();\n}\ncon.Close();	0
9376812	9376700	how to store repeater control value to database	foreach (RepeaterItem item in RepeatInformation.Items)\n{\n    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)\n    {\n        TextBox textBox = (TextBox)item.FindControl("TextBox1");\n\n        //Now you have your textbox to do with what you like\n        //You can access the .Text property to find the new value that needs saving to the database\n    }\n}	0
29087595	29087405	Converting Pointers in C to C#	private static unsafe void PrintBufferAsLongArray(byte[] buffer)\n{\n    fixed (byte* pBuffer = buffer)\n    {\n        long* longData = (long*)pBuffer;\n        for (int index = 0; index < 64; index++)\n            Console.WriteLine(" {0:X}", longData[index]);\n    }\n}	0
10141487	10141440	Open a excel file and Add cell value	Excel.Application xlApp;\nExcel.Workbook xlWorkBook;\nExcel.Worksheet xlWorkSheet;\nobject misValue = System.Reflection.Missing.Value;\n\nxlApp = new Excel.ApplicationClass();\nxlWorkBook = xlApp.Workbooks.Open(_filename, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);\nxlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);\n\n//You can loop through all cells and use i and j to get the cells\nxlWorkSheet.Cells[1,1].Value2 = Convert.ToInt32(xlWorkSheet.Cells[1,1].Value2) + 1;\n\nxlWorkBook.Close(false, misValue, misValue);\nxlApp.Quit();	0
2806440	2806414	can I have an abstract base class with the key attribute being generic	public abstract class Class<T> \n{\n    T value;\n    T Prop { get; set;} \n}	0
13641690	13641627	String encoding - German umlaut	Encoding.UTF8.GetByteCount(l_stest)	0
20710045	20709953	Model property not to be mapped with the database table in MVC4	[NotMapped]	0
15497850	15497427	Multiple Window Problems - C# WPF	private void btnForward_Click(object sender, RoutedEventArgs e)\n{\n    var p2 = new Presentation_2();\n    this.Close();\n    p2.Show();\n}	0
33163376	33162787	How can I create memcpy method in C#	public void MemCpy(byte[] destination, byte indexOfStartDestination, byte[] source, byte indexOfStartSource, byte numberOfBytes)\n    {\n        for (int i = 0; i < numberOfBytes; i++)\n        {\n            destination[indexOfStartDestination + i] = source[indexOfStartSource + i];\n        }\n    }	0
8510406	8510365	Getting a string preview	s.Substring(0,Math.Min(s.Length,50))	0
447225	447189	String.Split variation in C#	public IEnumerable<string> SplitAndKeepPrefix(this string source, string delimeter) {\n  return SplitAndKeepPrefix(source, delimeter, StringSplitOptions.None);\n}\n\npublic IEnumerable<string> SplitAndKeepPrefix(this string source, string delimeter, StringSplitOptions options ) {\n  var split = source.Split(delimeter, options);\n  return split.Take(1).Concat(split.Skip(1).Select(x => delimeter + x));\n}\n\nstring result = htmlStr.SplitAndKeepPrefix("<a");	0
15432963	15432804	Replace two bytes in a generic list	public static void RemoveEscapeSequences(List<byte> message)\n{\n    var replaceBytes = new Dictionary<byte, byte>()\n    {\n        {0x00, 0xF8}, {0x01, 0xFB}, {0x02, 0xFD}, {0x03, 0xFE}\n    };\n\n    // skipped parameter checks\n    for (int index = 0; index < message.Count - 1; ++index)\n    {\n        if (message[index] == 0xF8)\n        {\n            if(replaceBytes.ContainsKey(message[index + 1]))\n            {\n                message[index] = replaceBytes[message[index + 1]];\n                message.RemoveAt(index + 1);\n            }\n        }\n    }\n}	0
29852434	29851800	DataGrid column bind to a item of the List	Text = "{Binding MyClasses[0]}"\n\nText = "{Binding MyClasses[1]}"	0
19661908	19661326	XNA - Farseer Physics 3.5 - Collision Detection Issues - No/Zero Gravity - Space Game	SleepingAllowed = false	0
29374057	29367906	DataList grouping items by category	String previousName = "";\n\n    protected void MyDataList_ItemDataBound(object sender, DataListItemEventArgs e)\n    {\n        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n        {\n            Label Label1 = (Label)e.Item.FindControl("Label1");\n            System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;\n            string currentName = rowView["Name"].ToString();\n            if (currentName == previousName)\n            {\n                Label1.Text = "";\n            }\n            else\n            {\n                Label1.Text = currentName;\n            }\n            previousName = currentName;\n        }\n\n    }	0
22425765	22425724	Using C# and Linq to create an array containing unique items from two input arrays	var elements = array1.Union(array2).Except(array1.Intersect(array2));	0
28254908	28252231	How to get data from JSON file?	var result = o["albums"]["items"][0]["uri"];	0
4587322	4587242	find all occurrences of comparison with == in visual studio	namespace System.Net\n{\n    class IPAddress\n    {\n        [Obsolete]\n        public static bool operator ==(IPAddress a, IPAddress b) { return true; }\n        [Obsolete]\n        public static bool operator !=(IPAddress a, IPAddress b) { return true; }\n    }\n}	0
29971372	29970552	How to programmatically cancel .Net webforms ListView edit?	ListView.EditIndex = -1	0
153014	152774	Is there a better way to trim a DateTime to a specific precision?	static class Program\n{\n    //using extension method:\n    static DateTime Trim(this DateTime date, long roundTicks)\n    {\n        return new DateTime(date.Ticks - date.Ticks % roundTicks);\n    }\n\n    //sample usage:\n    static void Main(string[] args)\n    {\n        Console.WriteLine(DateTime.Now);\n        Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));\n        Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));\n        Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));\n        Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));\n        Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));\n        Console.ReadLine();\n    }\n\n}	0
22716287	22714716	How do I find a specific symbol or character in Word using c#?	object findSymbol = "\u00A3";\nobject replaceSymbol = "\u2264";\nquestionRange.Find.Execute(ref findSymbol,\n    true, true, true, ref missing, ref missing, ref missing,\n    ref missing, ref missing, ref replaceSymbol, Word.WdReplace.wdReplaceAll,\n    ref missing, ref missing, ref missing, ref missing);	0
2464747	2464727	C#: Easy access to the member of a singleton ICollection<>?	var levelName = worldMapLinks.Single().Value;	0
4388935	4385779	How do I use a regex to replace an Id in the middle of a Url?	string newCategoryId = "333";\nRegex regex = new Regex(@"/category/\w+\?");\nstring inputString = "http://localhost:1876/category/6?sortBy=asc&orderBy=Popular";\nstring replacementString = string.Format("/category/{0}?", newCategoryId);\nstring newUrl = regex.Replace(inputString, replacementString);	0
1562452	1562417	Read binary data from Console.In	using (Stream stdin = Console.OpenStandardInput())\n    using (Stream stdout = Console.OpenStandardOutput())\n    {\n        byte[] buffer = new byte[2048];\n        int bytes;\n        while ((bytes = stdin.Read(buffer, 0, buffer.Length)) > 0) {\n            stdout.Write(buffer, 0, bytes);\n        }\n    }	0
12905375	12905346	how to play a specific windows error sound in c#	SystemSounds.Hand.Play()	0
29342591	29342452	Using Alias matches domain level object	using SystemTask = System.Threading.Tasks.Task;	0
6956605	6956439	How to retrieve column value of sql server 2005 table and store it in label.Text of c# ASP.Net	String fname = ""\n// Create a new SqlCommand with your query to get the proper name and the connection string\nSqlCommand getFnameCommand = New SqlCommand("SELECT TOP 1 fname FROM profile ORDER BY fname DESC;", New SqlClient.SqlConnection"Your Connection String"))\ngetFnameCommand.Connection.Open() // Open the SqlConnection\nfname = getFnameCommand.ExecuteScalar() // This pulls the result from the first column of the first row of your query result\ngetFnameCommand.Connection.Close() //Close the SqlConnection\nlabel1.text=fname; //Set your label text to the data you just pulled	0
18327046	18326946	StoredProcedure in C#, passing parameters from text boxes	protected void Button1_Click(object sender, EventArgs e)\n    {\n        DataSet ds = new DataSet();\n        SqlConnection con = new SqlConnection(connectionString);\n        SqlCommand cmd = new SqlCommand("InsertIntoEmployee", con);\n        cmd.CommandType = CommandType.StoredProcedure;            \n        cmd.Parameters.Add("@LastName", SqlDbType.NVarChar(MAX)).Value = LastName.Text;\n         cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar(MAX)).Value = FirstName.Text;\n          cmd.Parameters.Add("@Phone1", SqlDbType.NVarChar(MAX)).Value = Phone1.Text;\n         cmd.Parameters.Add("@Phone2", SqlDbType.NVarChar(MAX)).Value = Phone2.Text;\n        con.Open();\n        cmd.ExecuteNonQuery();\n        con.Close();\n\n      //  gvQuarterlyReport.DataBind();\n    }	0
4996958	4996778	How to clear FormView data between inserts	this.fvw.DataSource = null;\nthis.fvw.DataBind();	0
26031002	26028760	How to retrieve mail message body with Exchange 2010 in C#	PropertySet Props = new PropertySet(BasePropertySet.IdOnly);\n        Props.Add(ItemSchema.Body);\n        Props.Add(ItemSchema.Subject);\n        FindItemsResults<Item> fiitems = null;\n        do\n        {\n            fiitems = service.FindItems(Folder.Id, "from:*", iv);\n            if (fiitems.Items.Count > 0)\n            {\n                service.LoadPropertiesForItems(fiitems.Items, Props);\n                foreach (Item item in fiitems)\n                {\n                    if (item is EmailMessage)\n                    {\n                        Console.WriteLine("subject");\n                        Console.WriteLine((item as EmailMessage).Subject);\n\n                        Console.WriteLine("body");\n                        Console.WriteLine((item as EmailMessage).Body);\n                    }\n                }\n            }\n            iv.Offset += fiitems.Items.Count;\n        } while (fiitems.MoreAvailable);	0
28673501	28673168	How to get position of every instantiated GameObject Unity 2D	clone = Instantiate (crate, new Vector3 (startingPositionX, startingPositionY, 0f), Quaternion.identity) as GameObject;	0
20333038	20332966	Searching on Date Fields when some date rows are NULL on the back-end	WHERE  t1.From_Date IS NULL OR\n       t1.To_Date   IS NULL OR\n       ( t1.From_Date >= @from_date AND t1.To_Date <= @to_date )	0
4011892	4011403	Ajax.BeginForm Displays Partial as a New Page	Ajax.ActionLink	0
23327259	23326233	C# how to get access to folders created in your solution explorer	AppDomain.CurrentDomain.BaseDirectory	0
23533802	23533643	What is the Sql command to get selected column names from a database table?	...WHERE (TABLE_NAME = 'MyTable') AND COLUMN_NAME='column1'\nor\n...WHERE (TABLE_NAME = 'MyTable') AND COLUMN_NAME IN ('column1','column2)\nor\n...WHERE (TABLE_NAME = 'MyTable') AND COLUMN_NAME LIKE '%column%'	0
12098741	12098414	compare dimensions of image asp.net	if (i.Width.Value < j.Width.Value)	0
6035020	6034892	WPF/C# - Create FlowDocument Programatically from XAML?	var flowDocument = \n    (FlowDocument)Application.LoadComponent(\n        new Uri(@"SomeFlowDocument.xaml", UriKind.Relative));\n\nflowDocument.DataContext = this;\n\nDispatcher.CurrentDispatcher.Invoke(\n    DispatcherPriority.SystemIdle,\n    new DispatcherOperationCallback(arg => null ), null);	0
4959269	4959253	Converting SQL Server varBinary data into string C#	byte[] binaryString = (byte[])reader[1];\n\n // if the original encoding was ASCII\n string x = Encoding.ASCII.GetString(binaryString);\n\n // if the original encoding was UTF-8\n string y = Encoding.UTF8.GetString(binaryString);\n\n // if the original encoding was UTF-16\n string z = Encoding.Unicode.GetString(binaryString);\n\n // etc	0
20613790	20612101	Row command with Link button in GridView	GridViewRow gRow = GridView2.Rows[0]\nRadioButtonList rdbtnPlans = (RadioButtonList)gRow.FindControl("rdbPlans");	0
21334600	21226877	C# , receiving data from serial port using readto()	sp.readto("\u0003")	0
19605215	19605153	How can I check if a value exists in a list using C#	if(identityStore.DbContext.Set<User>().Any(u => UserName == "yourUserName"))\n{\n    // user exists\n}\nelse\n{\n    // user does not exist\n}	0
21177702	21177597	c# determine how long the computer has been to sleep for & then convert this to an integer	TimeSpan time = timeOnWake - timeOnSleep;\nvar hours = time.TotalHours;	0
12481931	12481686	How do I add an iframe to a WebPart in order to render a seperate HTML page?	this.Controls.Add(new LiteralControl("<iframe src='externalpage.htm'></iframe> "));	0
3938662	3938648	List<T> to string[]	List<Foo> l = GetMyList();\n string[] myStrings = l.Select(i => i.Bar).ToArray();	0
27625223	27625154	Linq to Sql including 2 children sets	.Include(e=>e.CoreClass.Select(i=>i.CoreBooks))\n.Include(e=>e.CoreClass.Select(i=>i.CorePersons.Select(o => o.Person)))	0
16977085	16976769	How to resolve "Exception from HRESULT: 0x800A03EC" while coloring specific cells of an Excel sheet?	((Range)worksheet.Cells[i + 2, j + 1]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);	0
14197907	14197657	How to drop the virtual keyboard after keydown event on pressing enter in textbox	private void tbox_KeyDown_1(object sender, System.Windows.Input.KeyEventArgs e)\n{\n    if (e.Key == Key.Enter)\n    {\n        this.Focus();\n    }\n}	0
22664674	22664475	wrong using variable in regexp	string pattern = @"set zone ""([\w-]+)"" vrouter """+v;	0
17939481	17939443	Lambda expression select and combine fields as single string	var result = string.Join(",", tableOne.Select(x=>string.Format("{0} ({1})", x.Name, x.Age)));	0
6736109	6735521	Set Number format in excel using interop	_range.NumberFormat = "@";	0
6828520	6828483	unable to connect to the configured development web server	six steps	0
1857525	1857513	Get Substring - everything before certain char	static void Main(string[] args)\n    {\n        string s = "223232-1.jpg";\n        Console.WriteLine(sep(s));\n        s = "443-2.jpg";\n        Console.WriteLine(sep(s));\n        s = "34443553-5.jpg";\n        Console.WriteLine(sep(s));\n\n    Console.ReadKey();\n    }\n\n    public static string sep(string s)\n    {\n        int l = s.IndexOf("-");\n        if (l >0)\n        {\n            return s.Substring(0, l);\n        }\n        return "";\n\n    }	0
28124558	28123825	Get the path between two items in array	public static List<int> GetPath(int a,int b,int[] array) {\n    Stack<int> stacka=GetPathToRoot(a,array);\n    Stack<int> stackb=GetPathToRoot(b,array);\n    int lastCommonNode=-1;\n    while(stacka.Count>0&&stackb.Count>0&&stacka.Peek()==stackb.Peek()) {\n        lastCommonNode=stacka.Pop();\n        stackb.Pop();\n    }\n    List<int> list=new List<int>();\n    while(stacka.Count>1) {\n        list.Add(stacka.Pop());\n    }\n    list.Reverse();\n    if(stacka.Count>0&&stackb.Count>0) {\n        list.Add(lastCommonNode);\n    }\n    while(stackb.Count>1) {\n        list.Add(stackb.Pop());\n    }\n    return list;\n}\nprivate static Stack<int> GetPathToRoot(int a,int[] array) {\n    Stack<int> stack=new Stack<int>();\n    for(;;) {\n        stack.Push(a);\n        if(array[a]==a) {\n            break;\n        }\n        a=array[a];\n    }\n    return stack;\n}	0
6725473	6722788	I want to add only one sheet after creating an Excel workbook through C#	Excel.Application appC = new Excel.Application();    \nappC.SheetsInNewWorkbook = 1;       \nappC.Visible = true;     \nExcel.Workbook bookC = appC.Workbooks.Add();    \nExcel.Worksheet sheetC = appC.Sheets.get_Item(1);   \nsheetC.Name = "name-of-sheet";	0
2711003	2710891	How to make a stored procedure return the last inserted id	DECLARE @CriteriaItem TABLE (\n        ID INT IDENTITY (1,1),\n        CriteriaGroupID INT\n)\ninsert into @CriteriaItem (CriteriaGroupID)\nOUTPUT INSERTED.ID\nVALUES(1)	0
22073720	22073498	Setting TextBlock Visibility on selection Change	private void Selection(object sender, SelectionChangedEventArgs e)\n{\n    if(DateAutoCompleteBox == null)\n    {\n        MessageBox.Show("DateAutoCompleteBox   is null"); return;\n    }\n    if(Pf == null)\n    {\n        MessageBox.Show("Pf  is null"); return;\n    }\n    if(Pf.Text == null)\n    {\n        MessageBox.Show("Pf.Text  is null"); return;\n    }\n    if (Findpf() == 12)\n    {\n        DateAutoCompleteBox.Visibility = System.Windows.Visibility.Collapsed;\n    }\n    else\n    {\n        DateAutoCompleteBox.Visibility = System.Windows.Visibility.Visible;\n    }\n}	0
23000084	22997304	How to validate a .NET formatting string?	public bool IsInputStringValid(string input)\n    {\n        //If there are no Braces then The String is vaild just useless\n        if(!input.Any(x => x == '{' || x == '}')){return true;}\n\n        //Check If There are the Same Number of Open Braces as Close Braces\n        if(!(input.Count(x => x == '{') == input.Count(x => x == '}'))){return false;}\n\n        //Check If Value Between Braces is Numeric\n\n        var tempString = input; \n\n        while (tempString.Any(x => x == '{'))\n        {\n            tempString = tempString.Substring(tempString.IndexOf('{') + 1);\n            string strnum = tempString.Substring(0, tempString.IndexOf('}'));\n\n            int num = -1;\n            if(!Int32.TryParse(strnum, out num))\n            {\n                    return false;\n            }       \n        }\n\n        //Passes Validation\n        return true;\n    }	0
10990776	10988930	ups calculation is wrong in asp.net app	Residential Indicator	0
17761516	17761488	How can I export GridView to MS Access in C#	using ADOX;  // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security" \n\nstatic void CreateMdb(string fileNameWithPath)\n{\n  ADOX.Catalog cat = new ADOX.Catalog();\n  string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";\n  cat.Create(String.Format(connstr, fileNameWithPath));\n  cat = null;\n}	0
24940443	24939755	c# encryption/progress bar - increase speed of encryption	TotalBlocksEncrypted/TotalBlocks	0
699474	699410	Make UserControl remove itself	this.Parent.Controls.Remove(this);	0
29729495	29729081	How to Enable/Disable MenuStrip Items and Item's Drop Down Collection Items In C#	menuitemAccountDepartment.Enabled = false;	0
15392194	15257865	Install a Service as x64	1. Open the resulting .msi in Orca from the Windows Installer SDK.\n2. Select the Binary table.\n3. Double click the cell [Binary Data] for the record InstallUtil.\n4. Make sure "Read binary from filename" is selected and click the Browse button.\n5. Browse to %WINDIR%\Microsoft.NET\Framework64\v2.0.50727.\n6. The Framework64 directory is only installed on 64-bit platforms and corresponds to the 64-bit processor type.\n7. Select InstallUtilLib.dll.\n8. Click the Open button.\n9. Click the OK button.	0
8815134	8805319	ASP.NET Date Format	using (Html.BeginForm("DailyReport", "Reports", FormMethod.Post, new { id = "ActivityReport" }))	0
10773984	10773930	Absolute path directories are created during a zip file download application using ASP.NET	ZipEntry entry = new ZipEntry(Path.GetFileName(filename)); // just the file name	0
31691029	31573715	String comparison with QuickConverter	Binding="{qc:Binding '$P==\'Verified\'',P={Binding Path=Idea.Status}}"	0
27367003	27366713	Remove Duplicate values from a list while keeping track of the removed items' indexes	public class Player\n{\n    public string name { get; set; }\n    public int value { get; set; }\n}\n\npublic void MyTest()\n{\n    var myList = new List<Player>\n    {\n        new Player { name = "Player 1", value = 5 },\n        new Player { name = "Player 1", value = 10 },\n        new Player { name = "Player 1", value = 13 },\n        new Player { name = "Player 2", value = 3 },\n        new Player { name = "Player 2", value = 4 },\n        new Player { name = "Player 2", value = 6 }\n    };\n\n    var mySummedList = myList.GroupBy(x => x.name).Select(x => new Player { name = x.Key, value = x.Sum(y => y.value)});\n\n    foreach(var val in mySummedList)\n    {\n        Debug.WriteLine(String.Format("{0}: {1}", val.name, val.value));\n    }\n}\n\n//Output:\n//Player 1: 28\n//Player 2: 13	0
3998716	3998685	How to determine if an object is a DateTime in VB.NET	If TypeOf(value) Is DateTime Then	0
18873661	18873152	Deep Copy of OrderedDictionary	Object DeepClone(Object original)\n{\n    // Construct a temporary memory stream\n    MemoryStream stream = new MemoryStream();\n\n    // Construct a serialization formatter that does all the hard work\n    BinaryFormatter formatter = new BinaryFormatter();\n\n    // This line is explained in the "Streaming Contexts" section\n    formatter.Context = new StreamingContext(StreamingContextStates.Clone);\n\n    // Serialize the object graph into the memory stream\n    formatter.Serialize(stream, original);\n\n    // Seek back to the start of the memory stream before deserializing\n    stream.Position = 0;\n\n    // Deserialize the graph into a new set of objects\n    // and return the root of the graph (deep copy) to the caller\n    return (formatter.Deserialize(stream));\n}	0
2648477	2648442	Implementing IComparer<T> For IComparer<DictionaryEntry>	public class TimeCreatedComparer : IComparer<DictionaryEntry> \n{\n    public int Compare(DictionaryEntry x, DictionaryEntry y)\n    {\n        var myclass1 = (IMyClass)x.Value;\n        var myclass2 = (IMyClass)y.Value;\n        return myclass1.TimeCreated.CompareTo(myclass2.TimeCreated);\n    }\n}	0
15421600	15421515	Clearing a line in the console	Console.Write(new String(' ', Console.BufferWidth));	0
17611063	17610921	Convert a string beginning with a point to its decimal value	if (SessionHelper.Culture == "id-ID")\n    {\n\n        objGuestInvoiceDetail.DPSTransactionFee = Convert.ToDecimal(String.Format("0{0}",objParameter.ParameterValue));\n        //objGuestInvoiceDetail is ="0.80"\n    }\n\n\n//objParameter.ParameterValue contains value=".80"	0
17122969	17122489	Convert time into Timer Interval using C#	TimeSpan ts = new TimeSpan(new DateTime(2013,06,15,04,00,00).Ticks- DateTime.Now.Ticks);\n        long ticks = ts.Ticks;\n        long divide=    (long)Math.Pow(10, 7);\n        long span = ticks / divide;\n        timer.Interval = (int)span*1000;\n        timer.Tick += timer_Tick;\n        timer.Start();	0
6928891	6928736	Split a text box in one form to multiple labels into another form	var fullname = StringReceivedFromFirstForm;\nvar names = fullname.split(" ");\nFirstNameLabel.Text = names[0];\nSurnameLabel.Text = names[1];	0
3658898	3658796	C# array with capacity over Int.MaxValue	BigArray<T>	0
8484591	8269094	CSharpCodeProvider Conform to Interface	var location = Assembly.GetExecutingAssembly().Location;\ncompilerParameters.ReferencedAssemblies.Add(location);	0
30675011	30674702	Sending Declared Strings as query to write in SQL Server Using .NET	using (SqlConnection connection = new SqlConnection(SQLConnectionString))\n{\n    SqlCommand command = new SqlCommand();\n    command.Connection = connection;\n\n    command.CommandType = System.Data.CommandType.Text;\n    command.CommandText = @"INSERT INTO [myfriends] ([Friend], [Age]) VALUES ( @hisname, @hisage)";\n    command.Parameters.Add("@hisname", SqlDbType.VarChar, 10).Value =  hisname;\n    command.Parameters.Add("@hisage", SqlDbType.Int).Value =  hisage;\n    connection.Open();\n\n    command.ExecuteNonQuery();\n}	0
22565741	22519164	OAuthException #100 when creating custom object with facebook sharp SDK	var obj = new\n    {\n        app_id = appId,\n        type = app_name:object_type",\n        url = Url,\n        title = Name,\n        image = Image,\n        video = Video,\n        description = Description\n    };\n\n    var vars = new NameValueCollection {{"object", JsonConvert.SerializeObject(obj)}, {"format", "json"}, {"access_token", AppToken}};\n\n    var url = "https://graph.facebook.com/app/objects/"+ _appName + object_type;\n    return HttpTools.Post(url, vars);	0
28412542	28411552	Dynamic LINQ with datetime	var parsedDt = DateTime.Parse(txtCrudSearch.Text);\nvar nextDay = parsedDt.AddDays(1);\n\ntruncatedData = ((IQueryable<object>)rawData)\n                 .Where(columnName + ">= @0 && " + columnName + " < @1", parsedDt, nextDay)\n                 .ToList();	0
5583917	5582940	FileStream with querystring in filename?	private static FileStream GetFileStream()\n{\n    string url = @"http://www.someurl.com/shell.swf?Filename=actualfile.swf";\n\n    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);\n    WebResponse response = request.GetResponse();\n\n    byte[] result = null;\n    int byteCount = Convert.ToInt32(response.ContentLength);\n    using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))\n        result = reader.ReadBytes(byteCount);\n\n    return new FileStream(result);\n}	0
16468881	16468704	C# Json.NET WCF Rest DateTime Format	var settings = new JsonSerializerSettings() {DateFormatHandling= DateFormatHandling.MicrosoftDateFormat};\nvar json = JsonConvert.SerializeObject(test, settings);	0
9367658	9350955	Reading Serialized MFC CArray in C#	// Deriving from the IMfcArchiveSerialization interface is not mandatory\npublic class CArray : IMfcArchiveSerialization {\n    public Int16 size;\n    public List<float> floatValues;\n\n    public CArray() {\n        floatValues = new List<float>();\n    }\n\n    virtual public void Serialize(MfcArchive ar) {\n        if(ar.IsStoring()) {\n            throw new NotImplementedException("MfcArchive can't store");\n        }\n        else {\n            // be sure to read in the order in which they were stored\n            ar.Read(out size);\n\n            for(int i = 0; i < size; i++) {\n                float floatValue;\n                ar.Read(out floatValue);\n                floatValues.Add(floatValue);\n            }\n        }\n    }\n}	0
1124781	1124747	How do I select a TreeNode by name?	treeView1.Nodes.Add("RootNode", "Root Node");	0
20380872	20380612	WPF add Paragraph into TableCell by code	//I did not test this code\nTableCell firstCell = new TableCell();\nfirstCell.Blocks.Add(new Paragraph(new Run("first")));	0
11673966	11673731	parse a string with name-value pairs	string input = "StudentId=J1123,FirstName=Jack,LastName=Welch,StudentId=k3342,FirstName=Steve,LastName=Smith";\n\nDictionary<string,string> keyValuePairs = input.Split(',')\n  .Select(value => value.Split('='))\n  .ToDictionary(pair => pair[0], pair => pair[1]);\n\nstring StudentID = keyValuePairs[StudentId];	0
22189429	22176965	Resolution-time arguments of same type in Castle Windsor	_container.Resolve<IPercentage>(new Arguments(new { part, total }));	0
18684355	18681150	Graphics object making blank images	return new Bitmap(newImage, labelSize.Width, labelSize.Height);	0
30921163	30921127	How to assign list to generic list	public List<State> GetApprovedStateList(DateTime effectiveDate)\n{\n    using ( var db = new Context())\n    {\n        return (from a in db.StateProductList\n                     join b in db.States on a.stateID equals b.stateID\n                     where a.effectiveDate <= effectiveDate\n                     select b).ToList();\n    }\n}	0
20380745	20374524	Convert string with HASH MD5 to ToBase64String	public static string ConvertHexStringToBase64(string hexString)\n    {\n        byte[] buffer = new byte[hexString.Length / 2];\n        for (int i = 0; i < hexString.Length; i++)\n        {\n            buffer[i / 2] = Convert.ToByte(Convert.ToInt32(hexString.Substring(i, 2), 16));\n            i += 1;\n        }\n        string res = Convert.ToBase64String(buffer);\n        return res;\n    }	0
17503887	17503727	How to filter datagridview across field name which has space character?	(datagridview.DataSource as DataTable).DefaultView.RowFilter =\n                string.Format("[M??TER? ADI] LIKE '%{0}%'", textbox.Text.ToUpper());	0
4265479	4265427	Programmatically Set Proxy Address, Port, Username, Password	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\npublic struct WINHTTP_PROXY_INFO\n{\n    public AccessType AccessType;\n    public string Proxy;\n    public string Bypass;\n}\n\npublic enum AccessType\n{\n    DefaultProxy = 0,\n    NamedProxy = 3,\n    NoProxy = 1\n}\n\nclass Program\n{\n    [DllImport("winhttp.dll", CharSet = CharSet.Unicode, SetLastError = true)]\n    public static extern bool WinHttpSetDefaultProxyConfiguration(ref WINHTTP_PROXY_INFO config);\n\n    static void Main()\n    {\n        var config = new WINHTTP_PROXY_INFO();\n        config.AccessType = AccessType.NamedProxy;\n        config.Proxy = "http://proxy.yourcompany.com:8080";\n        config.Bypass = "intranet.com";\n\n        var result = WinHttpSetDefaultProxyConfiguration(ref config);\n        if (!result)\n        {\n            throw new Win32Exception(Marshal.GetLastWin32Error());\n        }\n        else\n        {\n            Console.WriteLine("Successfully modified proxy settings");\n        }\n    }\n}	0
16681274	16680928	Using Regex in C#	List<string> widgets = new List<string>();\n\nMatchCollection matches = Regex.Matches(yourHTMLCode, "<widget:([^/][^>])*/>");\nforeach (Match match in matches)\n{\n    foreach (Capture capture in match.Captures)\n    {\n        widgets.Add(capture.Value);\n    }\n}	0
839628	839599	Find a key in a dictionary using IEqualityComparer	AvailableBoxes.Keys.Contains(CUrrentBox.Name, StringComparer.OrdinalIgnoreCase);	0
18408545	18408466	Creating IEnumerable of T in method header	public static BatchInfo CreateBatch(IEnumerable<IEnumerable<object>> rows)\n{	0
21122220	21121010	how to set DateTime.now as current time in Access DataBase - c# windows forms app	string query = "insert into table(data) values('"+DateTime.Now.ToString("yyyy-MM-dd")+"')";\n\nOleDbConnection conexao = new OleDbConnection();\nconexao.ConnectionString = this.string_conexao;\nconexao.Open();\n\nOleDbCommand comando = new OleDbCommand();\ncomando.CommandText = query;\ncomando.Connection = conexao;\ntry\n{\ncomando.ExecuteNonQuery();\n}\ncatch\n{\n}	0
11111334	11111282	Cannot open generated database from EF Code first	public class MyContext : DbContext\n{\n    static private Initializer DbInitializer;\n    static MyContext()\n    {\n        DbInitializer = new MyContext.Initializer();\n        Database.SetInitializer<MyContext>(DbInitializer);\n    }\n}\npublic class Initializer : IDatabaseInitializer<MyContext>\n{\n    public void InitializeDatabase(MyContext context)\n    {\n        string ddl = "(Some SQL command to e.g. create an index or create a user)";\n        context.Database.ExecuteSqlCommand(ddl);\n    }\n}	0
7973173	7973100	How to get calendar events for specific date?	if ((StartDate <= InputDate) && (EndDate >= InputDate))	0
2193261	2192762	ASP.NET Routing - Adding a route only if numeric?	routes.Add("Category1Archive", new Route("{CategoryOne}/{Year}/{Month}/", new CategoryAndPostHandler()) { Constraints = new RouteValueDictionary(new { Year = @"^\d+$", Month = @"^\d+$" }) });\nroutes.Add("Category2Archive", new Route("{CategoryOne}/{CategoryTwo}/{Year}/{Month}/", new CategoryAndPostHandler()) { Constraints = new RouteValueDictionary(new { Year = @"^\d+$", Month = @"^\d+$" }) });	0
24374929	24374764	lock(variable) - conflicting explanation of the variable	ICollection.SyncRoot	0
2846305	2838384	How do I set a member field to a value using codeDom namespace	field.InitExpression = new CodePrimitiveExpression("some Random String");	0
18057964	18057937	Sending email via C#	client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");	0
391174	391002	Draw Text Over Video in Managed DirectX with C#	System.Drawing.Graphic	0
12454565	12454533	How to call a function	EncryptText<System.Security.Cryptography.Aes>("hello world")	0
20701211	20687742	Office interop - copy a table 2 lines below existing table	oWord.Selection.Tables[1].Select();\noWord.Selection.Copy();\noWord.Selection.MoveDown(WdUnits.wdLine, 2);\noWord.Selection.Paste();	0
20569402	20569278	How to dynamically load VB 6.0 dll in C#?	obj.InvokeMember("PrintDemo", BindingFlags.InvokeMethod, null, obj, null);\n\n// To...\nobj.InvokeMember("PrintDemo", BindingFlags.InvokeMethod, null, ins, null);	0
10181145	10181073	How to get a list of matched ID's using Linq?	var matches = _clientList\n            .Where(c => c.Value.BuddyList.Any(b => b.ProfileID == c.Value.ProfileID))\n            .Select(c => c.Key)\n            .ToList();	0
85706	85702	How can I make a ComboBox non-editable in .net?	stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;	0
17039569	17039518	sender void value as into antoher void	CheckValue(sender,  e);	0
16690379	16600739	How to change bar chart value on each bar to custom value?	Chart1.Series["Series1"].Points[counter].Label = "2";	0
2258102	2256048	Store a reference to a value type?	sealed class Ref<T> \n{\n    private Func<T> getter;\n    private Action<T> setter;\n    public Ref(Func<T> getter, Action<T> setter)\n    {\n        this.getter = getter;\n        this.setter = setter;\n    }\n    public T Value\n    {\n        get { return getter(); }\n        set { setter(value); }\n    }\n}\n...\nRef<string> M() \n{\n    string x = "hello";\n    Ref<string> rx = new Ref<string>(()=>x, v=>{x=v;});\n    rx.Value = "goodbye";\n    Console.WriteLine(x); // goodbye\n    return rx;\n}	0
1837836	1834055	How to I manipulate cell data being displayed in WPF Toolkit DataGrid at runtime?	...\nDataGridTextColumn dgtc2 = new ExtendedDataGridTextColumn(); \ndgtc2.Header = "Zip Code"; \n...\n\npublic class ExtendedDataGridTextColumn : DataGridTextColumn \n{\n    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)\n    {\n        TextBlock element = (TextBlock)base.GenerateElement(cell, dataItem);\n        element.Text = ((Customer)dataItem).ZipCode + "-0000";\n        return element;\n    }\n}	0
24672697	24672095	Entity Framework 6 - foreign key issue	public partial class ContentArticleHOAsubdivision\n{\n    public int Id { get; set; }\n\n    ...\n\n    public virtual ICollection<SubdivisionHOA> SubdivisionsHOAs { get; set; }\n}\n\npublic partial class SubdivisionHOA\n{\n    public short Id { get; set; }\n\n    ...\n\n    public int ContentArticleHOAsubdivisionId { get; set; }\n\n    [ForeignKey("ContentArticleHOAsubdivisionId")]\n    public virtual ContentArticleHOAsubdivision ContentArticleHOAsubdivision { get; set; }\n}	0
16900841	16900413	Finding drop down list control from a stored procedure in edit item template of gridview in asp.net c#	(DropDownList)gvLocationArea.Rows[gvLocationArea.EditIndex].Cells[INDEX OF THE DDL].Controls[0]	0
6100081	6076961	Pass Date Values from Ajax Call to MVC	var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");	0
8875533	8536838	Add text from font to video frame	CString out = "My String";\n\nLOGFONT LogFont;\nmemset( &LogFont, 0, sizeof( LOGFONT ) );\nLogFont.lfStrikeOut = 0;\nLogFont.lfUnderline = 0;\nLogFont.lfHeight = 12;\nLogFont.lfEscapement = 0;\nLogFont.lfQuality = CLEARTYPE_QUALITY;\nLogFont.lfItalic = FALSE;\nstrcpy(LogFont.lfFaceName, "Arial");\n\nHFONT font = CreateFontIndirect(&LogFont);\n\nHDC dc = // Get your DC from the Raw Bitmap\nSelectObject(dc, font);\nSetTextColor(dc, RGB(255, 255, 255) );\nSetBkMode(dc, TRANSPARENT);\nTextOut(dc, 0, 0, out.GetBuffer(), out.GetLength() );\nDeleteObject( font );\n\n// Release the Raw Bitmap DC	0
5656886	5656069	EF4 CTP5 - Many To One Column Renaming	modelBuilder.Entity<SomeEntity>()\n    .HasOptional(m => m.Parent)\n    .WithMany()\n    .Map(c => c.MapKey("Entity_Id"));	0
1861003	1860984	Load XML file into DataTable (not from a Database)	DataSet ds = new DataSet();\n    ds.ReadXml("xml file path");	0
6436528	6174584	Call C# dll from Delphi	[Guid("7DEE7A79-C1C6-41E0-9989-582D97E0D9F2")]\n[ComVisible(true)]\npublic class ServicesTester\n{\n    public ServicesTester()\n    {\n    }\n\n    //[ComVisible(true)]\n    public void TestMethod()\n    {\n        MessageBox.Show("You are in TestMEthod Function");\n    }\n}	0
1498688	1497866	How can I get the regular expression correct?	Matrix\s+"[^"]*"\s+SPRING\s+\d+\s+\d+\s+{[^}]*}	0
21513135	21512230	Where clause with multiple unknown conditions	var predicate = PredicateBuilder.False<Staff>();\npredicate = predicate.Or(s => s.Name.Contains(data));\npredicate = predicate.Or(s => s.Age > 30);\nreturn dataContext.Staff.Where(predicate);	0
4638560	4638551	Store multiple values in a session variable	using(SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where id=(select id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]) + ")", con))\n{\n\n    SqlDataReader dr1 = cmd1.ExecuteReader();\n    var yourList = new List<int>();\n    if (dr1.HasRows)\n    {\n        while (dr1.Read())\n        {\n           yourList.Add(Convert.ToInt32(dr1[0]));\n        }\n    }\n    Session["edp1"] = yourList;\n    dr1.Close();\n}	0
4656080	4656024	Splitting with Regex	splitArray = Regex.Split(myString, @"(?<=\p{L})(?=\p{N})");	0
17437639	17437570	How can I perform this type of JOIN in Entity framework with LINQ	db.Badges.Where(b=>!myUser.UserBadges.Contains(b));	0
11090196	11089942	EF and Linq with self referential table	int dependentIdToSearch = 1;\n\nvar q = from something in db.mytable\n        where something.DependentId == dependentIdToSearch\n        select new { something.Id, something.Name, something.Value };	0
17885113	17748129	How do I dynamically add an Actionlink from the Controller in MVC 4	grid.Column(format: (item) => new HtmlString(string.Format("<a href='{0}'>{1}</a>", Url.Action("Edit", "User", new {userId = item.id}), "Edit"))\n                                              )));	0
5431903	3048876	Fluent Nhibernate - Mapping two entities to same table	public class ReadonlyAdressMap : ClassMap<ReadonlyAdress>\n{\nReadonlyAdressMap()\n{\n    Schemaaction.None();\n    [...]\n}\n}	0
29999317	29980462	How can I get installed apps list in Windows Phone?	Other App Mangement	0
16300274	16209426	Pivot list of data in silverlight	List<MyData> lstData = new List<MyData>();\n\nList<dynamic> lst = new List<dynamic>();\n\n            foreach (var item in lstData.Select(a => a.Date).Distinct())\n            {\n                dynamic obj = new ExpandoObject();\n                obj.Date = item;\n                lst.Add(obj);\n            }\n\n            foreach (string item in lstData.Select(a => a.Name).Distinct())\n            {\n                foreach (var objitem in lst)\n                {\n                  string header = item;\n                    ((IDictionary<String, Object>)objitem).Add(header, lstData.Where(d => d.Date == objitem.Date && d.Name == item).FirstOrDefault().Value);\n                }\n            }\n\ngridView.Itemssource = lst;	0
33045848	33045122	Fluent Validation with ASP.NET MVC 5	public class BusinessBase<T>\n{\n   [UIHint("First Name")]\n   public string FirstName { get; set; }\n   public DateTime Dob { get; set; }\n}	0
9165645	9165286	Convert type int[] to int**	private int[,] pixelData = new int[w, h];\n\n// (Might have confused some variables here)\nprivate int[][] pixelData = new int[w][];\nfor (int i = 0; i < w; i++) pixelData[i] = new int[h];	0
7771584	7762975	Update a property only when the new value is different from the current value	protected void UpdateIfChanged(Field field, string value)\n{\n    if (field.Value != value)\n    {\n        field.Value = value;\n    }\n}\n\nUpdateIfChanged(langItem.Fields["Type"], updateNode.SelectSingleNode("./Type").InnerText);	0
22936472	22931187	Windows 8 Store App navigation with binding?	this.Frame.Navigate(Type.GetType("Namespace.PageName"));	0
6602371	6602342	Multiple arrays count comparison C#	var min = arrays.Min(x => x.Length);	0
14194266	14194113	How To Get The Size Of A File (Hosted On A Web Server)?	private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)\n{\n     progressBar.Max = (int)e.TotalBytesToReceive;\n    progressBar.Value = (int)e.BytesReceived;\n\n}	0
21787657	21787230	Updating Oracle database throws illegal variable name/number exception	db.AddParameter(":stateCode", stateCode);\ndb.AddParameter(":id", id);	0
6273119	6273059	C# - Ping server with ICMP disabled	PingOptions.Ttl	0
6128263	6127203	c# How to load a memory stream to an xmldocument without BOM? (My memory stream is generated from XMLTextWriter without BOM)	XDocument.Save(XmlWriter writer)	0
3204708	3204377	how to get a labels width before it is rendered in WPF	var l = new Label() { Content = "Hello" };\nl.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));\n\nSize s = l.DesiredSize;	0
30969535	30967363	asp conversion of a varchar data type to a datetime error SQL aspx	fieldValue = row.Cells[0].Text;\nDateTime timeNow = DateTime.Now;\n\nstring constring = System.Configuration.ConfigurationManager.ConnectionStrings["ITCConnectionString"].ConnectionString;\nusing (SqlConnection connection = new SqlConnection(constring)) {\n// timeNow = Convert.ToDateTime(timeNow);  (not needed)\nusing (SqlCommand cmd = new SqlCommand("UPDATE AktywneZgloszenia SET Data_przyjecia_do_realizacji= @pTimeNow  WHERE Nr_zgloszenia = @pFieldValue;", connection)) {\n    using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {\n        connection.Open();\n    cmd.Parameters.AddWithValue("@pTimeNow", timeNow); // <-- 'pass' timenow\n    cmd.Parameters.AddWithValue("@pFieldValue", fieldValue); // <-- 'pass' fieldValue\n        cmd.ExecuteNonQuery(); // <--executeNon\n        connection.Close();\n        GridView1.DataBind();\n    }\n}	0
5596935	5596899	How to introduce Let keyword inside Linq statement with Group by	var completionTimeModels =\nfrom timeline in processTimelines\n\ngroup timeline by timeline.LifecycleEventId into grouping\nlet foo = lifecycleEvents.First(i => i.LifecycleEventId == grouping.Key)\nselect new CompletionTimeViewModel()\n{\n    Name = foo.LifecycleEventName,\n    DisplayName = foo.LifecycleEventDisplayName\n};	0
33024494	33023754	Map LANGID from Win32_OperatingSystem to C# CultureInfo	int lcid;\n\nif (int.TryParse(currentValue, NumberStyles.HexNumber,\n    NumberFormatInfo.InvariantInfo, out lcid)) {\n  currentValue = CultureInfo.GetCultureInfo(lcid).Name;\n}	0
6684927	6682274	Change WPF window's label content from child user control	private void btnNext_Click(object sender, RoutedEventArgs e)\n    {\n        var gt = Window.GetWindow(this) as GetStarted;\n        if (gt != null)\n        {\n            gt.image0.Visibility = Visibility.Visible;\n            gt.lblSteps.Content = "Step 2 of 5";\n        }\n    }	0
18628904	18626160	Using C# to retrieve a file saved in a SQL Binary field by a VB6 application	var newPath = Path.ChangeExtension(T.FullPath, ".Zip");\nFile.Move(T.FullPath, newPath);	0
3412438	3412424	Truncate e-mail text string at the @ portion in C#	email = email.Substring(0, email.IndexOf('@'));	0
22052398	22052356	How to get n followers with Linq To Twitter	Followers = f.Users.Where(t => !t.Protected).Take(n).ToList()	0
6532189	6531811	Guid converted to int32	LinqDataSource2.Where = "UserID = @UserID";	0
652593	652467	Silverlight Programmatically select text	private void SelectText()\n    {\n        TextBox tb = this.txtFirstName;\n        tb.SelectionStart = 0;\n        tb.SelectionLength = 3;\n        // tb.Select(0, this.txtFirstName.Text.Trim().Length - 1);\n        // tb.SelectAll();\n        // tb.Text = String.Empty;\n        tb.Focus();\n    }	0
5702315	5702227	Deserialize int arrays from XML file	class Player\n{\n   public string Name;\n\n   [XmlIgnore]\n   public int[] Spells;\n\n   [XmlElement("Spells")\n   public string SpellsString\n   {\n     get\n     {\n        // array to space delimited string\n     }\n     set\n     {\n       // string to array conversion\n     }\n   }\n}	0
2210453	2195938	How do I Immediately Validate a Newly Inserted Row in a Silverlight 3 Datagrid?	DataGridRow newRow = this._dataGrid.ChildrenOfType<DataGridRow>().FirstOrDefault();\nif (newRow != null)\n{\n    newRow.Loaded += (sender, e) =>\n    {\n        this._dataGrid.CurrentItem = newItem;\n        this._dataGrid.BeginEdit();\n    };\n}	0
20728229	20727787	Deserialize JSON string to Dictionary<string,object>	Dictionary<string, object> values = \nJsonConvert.DeserializeObject<Dictionary<string, object>>(json);	0
10055680	10055516	Scheduling tasks with 'schtasks' without admin privileges C#	ProcessStartInfo psi = new ProcessStartInfo("schtasks");\n    psi.UseShellExecute = false;\n    psi.UserName = "Username";\n    psi.Password = "password";\n\n    Process.Start(psi);	0
171974	171970	How can I find the method that called the current method?	using System.Diagnostics;\n// Get call stack\nStackTrace stackTrace = new StackTrace();\n\n// Get calling method name\nConsole.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);	0
14447319	14447237	Insert DataTable into table in StoredProcedure	CREATE TYPE dbo.MyTableType AS TABLE \n(   Name    VARCHAR(5),\n    Code    VARCHAR(5)\n);\nGO;\nCREATE PROCEDURE dbo.MyProcedure (@MyTableType dbo.MyTableType READONLY)\nAS\n    INSERT dbo.MyTable (Name, Code)\n    SELECT Name, Code\n    FROM    @MyTableType;\n\nGO;	0
4328992	4328461	How does one dynamically add a new datalist or a row to a gridview?	public partial class Basket : System.Web.UI.Page {\n    protected void Page_Load(object sender, EventArgs e) {\n        List<BasketClass> cart = (List<BasketClass>)Session["CartSess"];\n\n        foreach (BasketClass BookID in cart)  {\n           GridView1.DataSource = cart.Where(i => i.BookID == 1);\n            AccessDataSource1.SelectCommand = "SELECT * FROM [tblBook]";\n        }\n    }\n}	0
32998603	32998506	How to restrict a child class from overriding parent class method in C#?	public abstract class Base\n{\n    public void TemplateMethod()\n    {\n        //do sth\n        OtherMethod();\n        //do sth more\n    }\n\n    protected abstract void OtherMethod();\n}\n\npublic class Child : Base\n{\n    protected override void OtherMethod()\n    {\n        //provide implementation\n    }\n}	0
17790053	17789271	get xelement attribute value	var xml = @"<User ID=""11"" \n                  Name=""Juan Diaz"" \n                  LoginName=""DN1\jdiaz"" \n                  xmlns=""http://schemas.microsoft.com/sharepoint/soap/directory/"" />";\n\nvar user = XElement.Parse(xml);\nvar login = user.Attribute("LoginName").Value; // "DN1\jdiaz"	0
20363984	20363948	C# Multiple Regex Replace	string strReplaceHtml = Regex.Replace(html, @"(< *?/*)strong( +?|>)", @"(< *?/*)bold( +?|>)", RegexOptions.IgnoreCase);\nstrReplaceHtml = Regex.Replace(strReplaceHtml , @"(< *?/*)em( +?|>)", @"(< *?/*)italic( +?|>)", RegexOptions.IgnoreCase);	0
12193890	12193782	cannot find database server on client machine	Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;User Instance=True	0
31246013	31239950	By a RadGridView, how can I get to show detail information?	GridViewRelation gvrConfigurations = new GridViewRelation();\n          gvrConfigurations.ChildColumnNames.Add("colConfigurationId");\n          gvrConfigurations.ChildTemplate = this.gridViewTemplate1;\n          gvrConfigurations.ParentColumnNames.Add("colConfigurationId");\n          gvrConfigurations.ParentTemplate = this.gvConfiguration.MasterTemplate;\n          gvConfiguration.Relations.Add(gvrConfigurations);	0
2455662	2455609	How to create a generic type that takes either T or IEnumerable<T>?	public Transformer(Func<T, TResult> transformer)\n{\n    _transformer = t => Convert(t, transformer);\n}\n\nprivate static IEnumerable<TResult> Convert(T value, Func<T, TResult> transformer)\n{\n    yield return transformer(t);\n}	0
8403247	8403056	How to add a hyperlink column in the devexpress ASPxGridView control?	public void PopulateColumns() {\n    GridViewDataTextColumn colID = new GridViewDataTextColumn();\n    colID.FieldName = "ID";\n    ASPxGridView1.Columns.Add(colID);\n\n    GridViewDataHyperLinkColumn colItemName = new GridViewDataHyperLinkColumn();\n    colItemName.FieldName = "ItemName";\n    colItemName.PropertiesHyperLinkEdit.NavigateUrlFormatString ="~/details.aspx?Device={0}";\n    colItemName.PropertiesHyperLinkEdit.TextFormatString = "Device {0}";\n    colItemName.PropertiesHyperLinkEdit.TextField = "ItemName";\n    ASPxGridView1.Columns.Add(colItemName);\n}	0
15316499	15316395	Do HttpWebRequest have any vulnerabilities that can infect OS	using (System.Net.WebClient webClnt = new System.Net.WebClient())\n    {\n       webClnt.proxy = proxy;\n       var srResult = webClient.DownloadString(srQueryRequest);\n    }	0
4371958	4371907	how to open usercontrol and close 2 seconds	public void MyFunction()\n{\n    firstForm.ShowDialog();\n    secondForm.Show();\n}\n\npublic void firstForm_Load(object sender, EventArgs e)\n{\n    Timer timer = new System.Windows.Forms.Timer() { Interval = 2000 };\n    timer.Tick += delegate { timer.Stop(); Close(); };\n    timer.Start();\n}	0
21518324	21518179	Opening my connection in C# to SQL	public bool OpenDBConnection(string ConnectionString)\n{\n    attempt = 0;          \n    if(ConnectionString == null)\n        ConnectionString = cConn.SetConnectionString();             \n    isCurrentOpen = (dConnection.State == ConnectionState.Open);   \n\n    if (!isCurrentOpen) //to keep up with your logic in case a connection is already opened.\n         dConnection = new SqlConnection(ConnectionString); //Initialize Database connection with the Connection String    \n     ...	0
22560712	22560264	Expression to match human readable print format	var match = Regex.Match(\n   YOUR_STRING,\n   @"(?<printer>.+?)(\s+on\s+(?<server>.+?))?\s+\(from\s+(?<client>.+?)\s*\)");\nvar result = String.Format(\n   @"\\{0}\{1}",\n   match.Groups["server"].Success\n    ? match.Groups["server"].Value\n    : match.Groups["client"].Value,\n   match.Groups["printer"].Value);	0
12543028	12542933	Is there a way to refactor attaching events to a separate static method?	e.add_MouseOver(Delegate)\ne.remove_MouseOver(Delegate)	0
7929140	7928800	Add an Icon To WPF TreeView's ContextMenu Code Behind	menuItem.Icon = new BitmapImage(new Uri("images/sample.png", UriKind.Relative));	0
13059413	13058609	counting page breaks in a word doc using word interp	int totalPageBreaks = 0;\n            Microsoft.Office.Interop.Word.Range rng;\n\n            rng = doc.Range();\n            rng.Collapse(WdCollapseDirection.wdCollapseStart);\n\n            while (true) {\n                rng.Find.ClearFormatting();\n                rng.Find.Text = "^012";\n                rng.Find.Forward = true;\n                rng.Find.Wrap = WdFindWrap.wdFindStop;\n                rng.Find.Format = false;\n                rng.Find.MatchCase = false;\n                rng.Find.MatchWholeWord = false;\n                rng.Find.MatchWildcards = false;\n                rng.Find.Execute();\n\n                if (!rng.Find.Found)\n                    break;\n\n                // increment counter\n                totalPageBreaks++;\n\n                // do some processing here if you'd like\n\n                // reset the range\n                rng.Collapse(WdCollapseDirection.wdCollapseEnd);\n            }	0
17553121	17551047	Adding a new field in the DhtmlX library	var scheduler = new DHXScheduler(this);\n        var select = new LightboxSelect("type", "Type");\n        select.AddOptions(new List<object>{\n            new { key = 1, label = "Job" },\n            new { key = 2, label = "Family" },\n            new { key = 3, label = "Other" }\n        });\n        scheduler.Lightbox.Add(select);	0
13203563	13155619	Getting user access_token from Facebook	FacebookClient client = new FacebookClient();\ndynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });\nif (result.error == null)\n{\n    Session["AccessToken"] = client.AccessToken = result.access_token;\n    dynamic user = client.Get("me", new { fields = "name,username,email" });\n    string userName = user.username;\n\n    mu = Membership.GetUser(userName);\n    if (mu == null)  // Register\n    {\n        RegisterModel rm = new RegisterModel();\n        rm.Email = user.email;\n        rm.UserName = userName;\n        return View("Register", rm);\n    }\n    else\n    {\n        FormsAuthentication.SetAuthCookie(userName, true);\n        return RedirectToAction(MVC.Home.Index());\n    }\n}	0
25992866	25992202	C# View tables in datagridview based upon combobox item selection	var context = new NameEntities();\n    BindingSource bi = new BindingSource();\n    //here, instead of putting tablename is there a way to put \n    //combox item name? I have tried combobox.Text.ToString(), \n    //but it doesn't work, shows error \n    var TableName = combobox.Text.ToString();\n    bi.DataSource = context.GetType().GetProperty(TableName).GetValue(obj, null);\n    dgvLoadTable.DataSource = bi;\n    dgvLoadTable.Refresh();	0
28844079	28843993	How to wrap a streamreader with the using directive?	using (StreamReader objStreamReader = File.OpenText(FILENAME))\n{\n   //code here\n}	0
19827187	19827148	easy way to loop over months and years from a given date	Date target = new Date(2011, 4, 1);\nwhile (target < Date.Today) {\n  // do something with target.Month and target.Year\n  target = target.AddMonths(1);\n}	0
31709795	17759613	Has anyone been able to use successfully PredicateBuilder from albahari.com against MongoDB?	var test = this.MongoConnectionHandler.MongoCollection.AsQueryable().AsExpandable<Message>().Where(predicate).ToList();	0
3385772	3385652	How to run C# Desktop Application with extension .exe in Mac OSX?	mono my_cool_program.exe	0
11472264	11467094	How do I tell my .NET assembly where a COM object's details are stored in the registry?	HKCR\Interface\{guid}	0
7937624	7937599	Get custom windows form button event	public event EventHandler TheButtonClicked;\n\n// Constructor\npublic CustomWindow()\n{\n  theButton.Click += FireTheButtonClicked;\n}\n\npublic void FireTheButtonClicked(object sender, EventArgs e)\n{\n  if(TheButtonClicked != null) TheButtonClicked(this, e);\n}	0
4589815	4589639	Subsonic Delete With Fluent Query Tool	public static void DeleteTable(DatabaseTable table)\n{\n     new Delete<object>(table, table.Provider).Execute();\n}	0
19258984	19225841	Enumerating Datatable rows in batches efficiently	public static IEnumerable<DataTable> EnumerateRowsInBatches(DataTable table,\n                                                            int batchSize)\n{\n    int rowCount = table.Rows.Count;\n    int batchIndex = 0;\n    DataTable result = table.Clone(); // This will not change, avoid recreate it\n    while (batchIndex * batchSize < rowCount)\n    {\n        result.Rows.Clear(); // Reuse that DataTable, clear previous results\n        int batchStart = batchIndex * batchSize;\n        int batchLimit = (batchIndex + 1) * batchSize;\n        if (rowCount < batchLimit)\n            batchLimit = rowCount;\n\n        for (int i = batchStart; i < batchLimit; i++)\n            result.Rows.Add(table.Rows[i].ItemArray); // Avoid ImportRow\n\n        batchIndex++;\n        yield return result;\n    }\n}	0
2048234	2041386	Looking for a RegEx Find and Replace Visual Studio addons	Sub RegexReplace()\n    Dim regex As String = InputBox("Enter regex for text to find")\n    Dim replace As String = InputBox("Enter replacement pattern")\n\n    Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection\n    Dim editPoint As EnvDTE.EditPoint\n\n    selection.StartOfDocument()\n    selection.EndOfDocument(True)\n\n    DTE.UndoContext.Open("Custom regex replace")\n    Try\n        Dim content As String = selection.Text\n        Dim result = System.Text.RegularExpressions.Regex.Replace(content, regex, replace)\n        selection.Delete()\n        selection.Collapse()\n        Dim ed As EditPoint = selection.TopPoint.CreateEditPoint()\n        ed.Insert(result)\n    Catch ex As Exception\n\n    Finally\n        DTE.UndoContext.Close()\n        DTE.StatusBar.Text = "Regex Find/Replace complete"\n    End Try\n\nEnd Sub	0
21004053	21002920	Find filename from Application Assembly manifest	tools.dll	0
11540530	11531633	Combobox with selected value and Autocomplete	private void cboCategories_SelectedValueChanged(object sender, EventArgs e)\n{\n    int val = Convert.ToInt32(cboCategories.SelectedValue);\n    ModifGrid(val);\n}\nprivate void ModifGrid(int ModifiedValue)\n{\n    if (Convert.ToInt32(productBindingSource.Count)>0)\n    {\n        ((Product)productBindingSource.Current).CategoryID = ModifiedValue;\n    }\n}	0
15590521	15590469	add user input in database	Console.WriteLine("Enter Name: ");\nthis.name = Console.ReadLine();\nstring sql1 = "INSERT INTO tableName (columnName) VALUES ('" + this.name + "');"\nDataAccess.ExecuteSQL(sql1);	0
27002337	26998366	How do I consume this xml web service in c#?	var webServiceSoapClient = new  Q26998366_ConsumeAsmx.Dixon.WebServiceSoapClient ("WebServiceSoap");\nforeach (Dixon.User user in  webServiceSoapClient.Data()) \n{\n    Console.WriteLine(String.Format("Name: {0}\nPass: {1}\nSalt: {2}\n"\n        , user.username, user.password, user.salt)); \n}	0
19108687	19108548	How to use orderby for Arraylist?	OrderByDescending(x => x.Date!=null? DateTime.ParseExact(x.Date, @"dMyyyy", culture):DateTime.MinValue)	0
13287080	13284732	How to edit DateEdit input format	editmask = "y";	0
32011803	32011619	Public List without Add	public class RegistrationManager\n{\n  private List<object> _registeredObjects;\n  ReadOnlyCollection<object> _readOnlyRegisteredObjects;\n\n  public RegistrationManager()\n  {\n      _registeredObjects=new List<object>();\n      _readOnlyRegisteredObjects=new ReadOnlyCollection<object>(_registeredObjects);\n  }\n\n  public IEnumerable<object> RegisteredObjects\n  {\n     get { return _readOnlyRegisteredObjects; }\n  }\n\n\n  public bool TryRegisterObject(object o) \n  {\n    // ...\n    // Add or not to Registered\n    // ...\n  }\n}	0
12540332	12501310	how do I create a DbSyncForeignKeyConstraint to a table with a composite Primary Key	var sqlConn = new SqlConnection(@"Data Source=(local)\SQLExpress; Initial Catalog=Test; Integrated Security=True");\n        var sqlConn2 = new SqlConnection(@"Data Source=(local)\SQLExpress; Initial Catalog=Test2; Integrated Security=True");\n\n        var parent = SqlSyncDescriptionBuilder.GetDescriptionForTable("Users", sqlConn);\n        var child = SqlSyncDescriptionBuilder.GetDescriptionForTable("UsersRoles", sqlConn);\n\n        var parentPKColumns = new Collection<string> {"UserId"};\n        var childFKColumns = new Collection<string> {"UserId"};\n\n        child.Constraints.Add(new DbSyncForeignKeyConstraint("FK_UsersRoles_Users", "Users", "UsersRoles", parentPKColumns, childFKColumns));\n\n        var fKTestScope= new DbSyncScopeDescription("FKTestScope");\n\n        fKTestScope.Tables.Add(parent);\n        fKTestScope.Tables.Add(child);\n\n        var scopeProvisioning = new SqlSyncScopeProvisioning(sqlConn2, fKTestScope);\n\n        scopeProvisioning.Apply();	0
27388513	27388449	SQL SET Statement C# Parameters	MySql.Data.MySqlClient.MySqlCommand cmd;\ncmd = new MySql.Data.MySqlClient.MySqlCommand();\n\ncmd.CommandText = "UPDATE pay_control SET payroll_type_cd = @payroll_type_cd)";\ncmd.Prepare();\n\ncmd.Parameters.AddWithValue("@payroll_type_cd", 1);	0
15566466	15566358	PCL - Can't convert from Func<IThing<T>> to Func<Object> for some targets	protected void Register<T>(string name, Func<IThing<T>> resolver) where T : IModel<T>\n    {\n        Func<object> wrapper =  () => resolver();\n        _registrations.Add(name, wrapper);\n    }	0
33646445	31745522	unreadable fields in VisualFoxPro	BINTOC(71965)+'078'	0
16612711	16612086	Compare very large numbers stored in string	public static int CompareNumbers(string x, string y)\n    {\n        if (x.Length > y.Length) y = y.PadLeft(x.Length, '0');\n        else if (y.Length > x.Length) x = x.PadLeft(y.Length, '0');\n\n        for (int i = 0; i < x.Length; i++)\n        {\n            if (x[i] < y[i]) return -1;\n            if (x[i] > y[i]) return 1;\n        }\n        return 0;\n    }	0
28811457	28810244	Sharepoint SiteUserInfoList get all keys and values	Console.WriteLine("Tile: {0}:{1}", it.Title, f[it.Title]);	0
4097734	4097364	C# ListBox from a lists of lists of objects (and deeper)	//ViewModelBase should be a base class that implements INotifyPropertyChanged\npublic class MyViewModel : ViewModelBase\n{\n     public readonly IDataProvider _provider;\n\n     public MyViewModel(IDataProvider provider)\n     {\n         _provider = provider ?? (some default provider);\n     }\n\n     public IList<String> Titles\n     {\n         get\n         {\n              var q = from shelves in _provider.GetBookShelves()\n                      from books in shelves.booksOnThisShelf\n                      select books.Title;\n\n              return q as List<String>;\n         }\n     }\n}	0
30031767	30031269	How can i find the Line that Contains the exception when Using methods that Parse the Data in C# WinForms	static public decimal ToDecimal(this string str){\n   decimal dec;\n   if (decimal.TryParse(str, out dec))\n   {\n      return dec;\n   }\n   else\n   {\n      MessageBox.Show(str);\n      return 0.0;\n   }\n}	0
5405158	5405051	ListBox ItemsSource Doesn't Update	private ColumnsModel _columns;\npublic ColumnsModel Columns \n{ \n  get { return _columns; } \n  set \n  { \n    _columns = value; \n    PropertyChanged("Columns"); \n  }\n}	0
7425626	7425595	How do I log a user out of my FB app but not Facebook site?	FB.api({ method: 'Auth.revokeAuthorization' });	0
398792	398781	How do I implement this type of OOP structure?	Interface Car\n{\nvoid Drive(int miles);\n}\n\nclass Honda : Car\n{\n...\n}\nclass Toyota : Car\n{\n...\n}	0
32974326	32973967	where's implementation of OracleCommand class's methods?	System.Data.OracleCient	0
27077659	26803287	how to sort date column in grid obout	DataType = System.Type.GetType("System.DateTime")	0
1109551	1109542	How to scan a directory for assemblies and load them?	AppDomain.GetAssemblies	0
26831288	26831212	how to sort data from database in listview using c# and entity framework	var query = from x in db.userList\n               orderby x.Name\n               select new\n               {\n                   ID = x.UserID,\n                   name = x.Name,\n                   lName = x.LastName,\n                   age = x.Age,\n                   club = x.Club,\n                   price = x.Price\n               };	0
5446256	5446241	How to read a web page synchronously using WP7	WebClient::BeginDownloadString()	0
28791741	28787639	Using a Singleton in Unity3D	using UnityEngine;\n\npublic abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>\n{\n    public static T Instance { get; private set; }\n\n    protected virtual void Awake()\n    {\n        if (Instance == null)\n        {\n            Instance = (T) this;\n        }\n        else\n        {\n            Debug.LogError("Got a second instance of the class " + this.GetType());\n        }\n    }\n}	0
7202188	7202111	How do I make a property throw an exception on set with a Moq mock?	mock.SetupSet(foo => foo.Name = "foo").Throws<ArgumentException>();	0
32071525	32070914	Update a value for an entire set without using foreach	using (Entities db = new Entities())\n    {\n        int changed = Entities.Database.ExecuteSqlCommand("Update Contact set IsCustomer = 0");\n    }	0
21154205	21154115	Select From DataTable with Multiple Conditions	DateTime currentDateTime = firstDate;\n    while (firstDate <= lastDate)\n    {\n         foreach (AccountCategory a in db.AccountCategories)\n         {\n             var result = Settings.dtCurrent.AsEnumerable()\n                   .Where(b => b.Field<string>("Account") == a.Account \n                             && (b.Field<DateTime>("Date") <= currentDateTime).OrderByDescending(b=> b.Field<DateTime>("Date")).FirstOrDefault();\n\n\n   }\n}	0
20566480	20566255	Use phoneapplicationpage in .cs file : Windows Phone	ApplicationBar = new ApplicationBar();\n    ApplicationBar.Mode = ApplicationBarMode.Default;\n    ApplicationBar.Opacity = 1.0; \n    ApplicationBar.IsVisible = true;\n    ApplicationBar.IsMenuEnabled = true;\n\n    ApplicationBarIconButton button1 = new ApplicationBarIconButton();\n    button1.IconUri = new Uri("/Images/YourImage.png", UriKind.Relative);\n    button1.Text = "button 1";\n    ApplicationBar.Buttons.Add(button1);\n\n    ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem();\n    menuItem1.Text = "menu item 1";\n    ApplicationBar.MenuItems.Add(menuItem1);	0
5243491	5243471	sort datetime range	DateTime Start = YourStartValue;\nDateTime End = YourEndValue;\nlong Range = End.Ticks - Start.Ticks;	0
9642164	9642072	How to use C# .net 4 to get webserver header time	var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");\nvar response = myHttpWebRequest.GetResponse();\nConsole.WriteLine("\nThe HttpHeaders are \n\n\tName\t\tValue\n{0}", response.Headers);	0
2186145	2186105	C# - Remove ToolTip only supplying in which Control is the ToolTip	ToolTip.SetToolTip(TextBox1, null);	0
12253789	12203320	Commiting changes in DataGridView before Row Change	private void dgvPlayers_CellValidated(object sender, DataGridViewCellEventArgs e)\n    {\n         this.Validate();\n    }	0
5991531	5991363	Selecting multiple children using where clause in linq for xml	var feeds = from feed in doc.Descendants("message")\nselect new\n{\n  Message = feed.Value\n};	0
32286194	32286082	Getting NullReferenceExeption in unity using dreamlo scoreboards	if (string.IsNullOrEmpty(this.highScores)) return null;	0
26732943	26731022	unable to receive full file in tcp client server	int size = 3190551; // I know the file size is about 30 mb	0
20001695	20001672	Combobox items from mysql query refresh each second	comboBox1.Items.Clear();	0
20835906	20835880	Convert.ChangeType How to convert from String to Enum	public static T Convert<T>(String value)\n{\n    if (typeof(T).IsEnum)\n       return (T)Enum.Parse(typeof(T), value);\n\n    return (T)Convert.ChangeType(value, typeof(T));\n}	0
4630442	4630391	Get all controls of a specific type	foreach(var pb in this.Controls.OfType<PictureBox>())\n{\n  //do stuff\n}	0
25257570	25257496	How do I specify a picture-box through adding two strings?	PictureBox pictureBox = (PictureBox)this.Controls.Find(string.Concat("Tile","20")).FirstOrDefault();\n\nif (pictureBox != null)\n{\n   if (pictureBox.Tag == "Hello")\n   {\n     rest of the code...\n   }\n}	0
4503750	4280600	Find all consecutive numbers in an int[]	static IEnumerable<IEnumerable<int>> Sequences(IEnumerable<int> input, bool ascen = false, int min = 3)\n    {\n        int ord = ascen == false ? -1 : 1;\n\n        input = ord == -1 ? input.OrderByDescending(x => x) : input.OrderBy(x => x);\n\n        var seq = new List<List<int>>();\n        foreach (var i in input)\n        {\n            var existing = seq.FirstOrDefault(lst => lst.Last() + ord == i);\n            if ((existing == null) || (seq.Last().Count == 5) || i == 7 || i == 15 || i == 23)\n\n                seq.Add(new List<int> { i });\n            else\n                existing.Add(i);\n        }\n        return min <= 1 ? seq : seq.Where(lst => lst.Count >= min);\n    }	0
12626084	12625929	Multiple includes using Entity Framework and Repository Pattern	public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate, param string[] include)\n{\n    IQueryable<T> query = this._ObjectSet;\n    foreach(string inc in include)\n    {\n       query = query.Include(inc);\n    }\n\n    return query.Where(predicate);\n}	0
12837284	12837022	Identifying X close event of a popup window using javascript	var MyPopup = {\n\n  _win : null,\n\n  _userClosingWindow : true,\n\n  open : function() {\n    var _this = this;\n    this._win = window.open(...);\n    this._win.onbeforeunload = function() {\n      if( _this._userClosingWindow ) {\n         // closed by user\n      }\n      else {\n        // closed in code\n      }\n    };\n  },\n\n  close : function() {\n    this._userClosingWindow = false;\n    this._win.close();\n  }\n\n};	0
516207	516174	How do i get detailed info from a HttpWebResponse	try \n{\n    // Do WebRequest\n}\ncatch (WebException ex) \n{\n    if (ex.Status == WebExceptionStatus.ProtocolError) \n    {\n        HttpWebResponse response = ex.Response as HttpWebResponse;\n        if (response != null)\n        {\n            // Process response\n        }\n    }\n}	0
15613719	15613699	CSharp virtual method and parameters	public abstract class State<T>\n{\n    public virtual Enter(T item)\n    {\n        // an empty method\n    }\n}\n\npublic class PlayerState : State<Player>\n{\n    public override Enter(Player pl)\n    {\n        // method implementation\n    }\n}\n\npublic class GoalkeeperState : State<Goalkeeper>\n{\n    public override Enter(Goalkeeper gk)\n    {\n        // method implementation\n    }\n}	0
13545607	13545566	c# - How to catch a COMException in asp.net?	catch (Microsoft.SharePoint.SPException) {\n  // do stuff\n}	0
17962158	17962131	How to Get Data from index of String	string a = taxNumber.Substring(0, 1);\nstring b = taxNumber.Substring(1, 4);\n// etc	0
23278128	23077873	Nancy slow to start accepting requests	public class Bootstrapper : DefaultNancyAspNetBootstrapper\n{\n    protected override void ConfigureApplicationContainer(TinyIoCContainer container)\n    {\n        // Register our app dependency as a normal singleton           \n\n    }\n}	0
22124762	22124533	How to make WinForms chart control primary Y axis to be drawn on both sides of the chart?	chart1.ChartAreas[ChartName].AxisY2.Enabled = AxisEnabled.True;	0
3566822	3560370	Custom Action in C# used via WiX fails with error 1154	using Microsoft.Deployment.WindowsInstaller;	0
1230237	1230219	Is it possible to override a method in a class in a dll file?	object.ToString()	0
7820680	7819746	SharePoint 2007 : How to programmatically upload binary file into Document Library?	string destFile = file.Name;	0
29774116	29773476	How to make filtration query fast in my C# code with MySQL?	if (!String.IsNullOrWhiteSpace(Request["FilterReport"]))   \n{\n       string[] reportInfo = Request["FilterReport"].Split('-');\n       int reportId = int.Parse(reportInfo[0]);\n       int languageId = int.Parse(reportInfo[1]);\n       Listquests = Listquests.Where(q => q.Reports.Any(r => r.ReportType.Id == reportId && r.Language.Id == languageId)).OrderByDescending(q => q.Date).ToList();\n}	0
22891701	22891666	Define int to be with 3 number ,az	set{\n    if(value  <1000) {\n      num = value; \n    }else throw new ArgumentOutOfRangeException();\n}	0
15741165	15735049	A data structure for determining how many elements lie within a specific range?	count(j) - count(i)	0
4408382	4376912	Selecting a cell of a WPF DataGrid which is inside a RowDetailsTemplate	private void SubItemsGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)\n{\n   DataGrid selectedGrid = sender as DataGrid;\n   if (selectedGrid != null)\n   {\n       selectedGrid.BeginEdit();\n       selectedGrid.CancelEdit();\n   }\n}	0
8069144	8069059	Is there a way to determine the return-type of a method programmatically?	public T DoStuff<T>()\n{\n...\n}	0
8021116	8020635	C# Invoke Powershell with pre-created object	var objs= new PSDataCollection<CustomObj> {obj};\n\n        using (var ps = PowerShell.Create())\n        {\n            ps.Runspace.SessionStateProxy.SetVariable("objList", objs);\n            ps.AddScript(@"$objList| ForEach { $_.Run()}");\n            ps.AddCommand("Out-String");\n            var output = ps.Invoke();\n\n            var stringBuilder = new StringBuilder();\n            foreach (var obj in output)\n            {\n                stringBuilder.AppendLine(obj.ToString());\n            }\n\n            var result = stringBuilder.ToString().Trim();\n\n            //Evaluate result.\n        }	0
10434867	10421456	Sharing NLog configuration between applications with slight differences	EventLogTarget target = (EventLogTarget)LogManager.Configuration.FindTargetByName("eventlog");\ntarget.Source = "Application1";	0
202880	202002	How do I open a file in C# and change its properties?	Private Sub ProcessOfficeDocument(ByVal fileName As String)\nDim docDSO As New DSOFile.OleDocumentPropertiesClass\nDim docTitle, docModified, docAuthor, docKeywords As String\nTry\ndocDSO.Open(fileName, True)\nDim docSummary As DSOFile.SummaryProperties = docDSO.SummaryProperties\ndocTitle = docSummary.Title\ndocAuthor = docSummary.Author\ndocKeywords = docSummary.Keywords\ndocModified = CStr(docSummary.DateLastSaved)\n\nIf (Not String.IsNullOrEmpty(docTitle)) Then\n_Title = docTitle\nEnd If\n\nIf (Not String.IsNullOrEmpty(docAuthor)) Then\n_Author = docAuthor\nEnd If\n\nIf (Not String.IsNullOrEmpty(docModified)) Then\n_DateModified = DateTime.Parse(docModified)\nEnd If\n\nCatch ex As Exception\n'Do whatever you need to do here...'\nFinally\nIf (Not docDSO Is Nothing) Then\ndocDSO.Close()\nEnd If\nEnd Try\nEnd Sub	0
8820480	8820403	C# Retrieve Values from URL and insert records	string userc = GetContextInfo("User", "UserId");\nstring tools = Dispatch.EitherField("selectedTools");\nstring[] toolIds = tools.Split(',');\nforeach (string toolId in toolIds) \n{\n  Record recRelTool = new Record("RelatedTools");\n  recRelTool.SetField("rato_CreatedBy", userc);\n  recRelTool.SetField("rato_Status", "active");\n  recRelTool.SetField("rato_server", pID);\n  recRelTool.SetField("rato_tool", toolId);\n  recRelTool.SaveChanges();\n}\n\nDispatch.Redirect(Url("1453"));	0
28789845	28629074	Apply color for each and every point in PointCloud Using HelixToolkit	//create PointGeometryModel3D object\n    PointGeometryModel3D pgm = new PointGeometryModel3D();\n\n    //create positions\n    pgm.Geometry.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection();\n\n    pgm.Geometry.Positions.AddRange(\n        new SharpDX.Vector3[]\n        {   new SharpDX.Vector3(0,1,2), \n            new SharpDX.Vector3(1,2,3), \n            new SharpDX.Vector3(3,2,3), \n        });\n\n    //create colors\n    pgm.Geometry.Colors = new HelixToolkit.Wpf.SharpDX.Core.Color4Collection();\n\n    pgm.Geometry.Colors.AddRange(\n        new SharpDX.Color4[]\n        {   \n            new SharpDX.Color4(1f,0,0,1), \n            new SharpDX.Color4(0,1f,0,1), \n            new SharpDX.Color4(0,0,1f,1) \n        });\n\n    //create indices\n    pgm.Geometry.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection();\n\n    pgm.Geometry.Indices.AddRange(\n        new int[]\n        {   \n            0,\n            1,\n            2,\n        });	0
19396375	15001626	Detect trust level	public static class CodeAccessSecurity {\n        private static volatile bool _unrestrictedFeatureSet = false;\n        private static volatile bool _determinedUnrestrictedFeatureSet = false;\n        private static readonly object _threadLock = new object();\n\n        public static bool HasUnrestrictedFeatureSet {\n            get {\n#if __IOS__\n                return false;\n#elif __ANDROID__\n                return false;\n#else\n                if (!_determinedUnrestrictedFeatureSet)\n                    lock (_threadLock) {\n                        if (!_determinedUnrestrictedFeatureSet) {\n                            _unrestrictedFeatureSet = AppDomain.CurrentDomain.ApplicationTrust == null || AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet.IsUnrestricted();\n                            _determinedUnrestrictedFeatureSet = true;\n                        }\n                    }\n                return _unrestrictedFeatureSet;\n#endif\n            }\n        }\n\n    }\n}	0
629629	629617	How to convert string to "iso-8859-1"?	System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");\n        System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;\n\n        // Unicode string.\n        string s_unicode = "abc??abc";\n\n        // Convert to ISO-8859-1 bytes.\n        byte[] isoBytes = iso_8859_1.GetBytes(s_unicode);\n\n        // Convert to UTF-8.\n        byte[] utf8Bytes = System.Text.Encoding.Convert(iso_8859_1, utf_8, isoBytes);	0
19680859	19680628	using querystring to get a parameter c# windows phone 7	anim = Uri.UnescapeDataString(NavigationContext.QueryString["anim"]);	0
31404794	31404400	how to get column Index by column name?	dtGrid.Columns.IndexOf(dtGrid.Columns.FirstOrDefault(c => c.Header == strQ2));	0
11326580	11326543	How do i catch an error in a int parsed from string?	int myinput = 0;\nif(false == int.TryParse(Console.ReadLine(), out myInput))\n   // Error, not an integer\n   Console.WriteLine("Please input 1 or 2");\nelse\n{\n    if (myinput == 1) \n    { \n        FirstEvent(); \n    } \n    else if (myinput == 2) \n    { \n        SecondEvent(); \n    } \n    else\n        Console.WriteLine("Please input 1 or 2");\n}	0
5866560	5865760	Reversing the direction of an object after a collision	public void MoveBubble(Bubble b, double radians)\n{\n    if (b.stop == false)\n    {\n        {\n           //Move bubble 'up'\n            Y = (float)(speed * Math.Cos(radians));\n            X = (float)(speed * Math.Sin(radians));\n        }\n\n        b.bubblePosX += X;\n\n        //Problem area\n        if(b.bubblePosY <= 0 || b.bubblePosY >= 350)\n            b.bubblePosY -= Y;\n        else\n            b.bubblePosY += Y;\n    }\n}	0
3345185	3250476	Updating config file and updating the values in application	var client = \n System.ServiceModel.ChannelFactory<ISampleService>(\n  System.ServiceModel.Channels.Binding binding, \n  System.ServiceModel.EndpointAddress remoteAddress)	0
22768652	22768510	Use a string from app settings in a SQL query	const string query =\n      "SELECT Value"\n    + "FROM Types"\n    + "WHERE Value = @SomeValue";\n\nusing(var command = connection.CreateCommand())\n{\n    command.CommandText = query;\n    command.Parameters.AddWithValue("@SomeValue", strSomeValue[0]);\n    // TODO: open connection, execute command, get result\n}	0
16410086	16409303	dataGridView Image not displaying for first row, second Cell	namespace WindowsFormsApplication1   \n{\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        List<MyItem> items = new List<MyItem>();\n        for (int i = 0; i < 10; i++)\n        {\n            items.Add(new MyItem { Key = i, value = Image.FromFile(@"e:\test.jpg") });\n        }\n\n        this.dataGridView1.AutoGenerateColumns = false;\n        this.dataGridView1.Columns.Clear();\n        this.dataGridView1.Columns.Add("Key", "Key");\n        this.dataGridView1.Columns.Add(new DataGridViewImageColumn() { HeaderText="Status"});\n\n        this.dataGridView1.Columns[0].DataPropertyName = "Key";            \n        this.dataGridView1.Columns[1].DataPropertyName = "value";\n\n        this.dataGridView1.DataSource = items;\n\n    }\n}\n\npublic class MyItem\n{\n    public int Key { get; set; }\n    public Image value { get; set; }\n}	0
12467049	12466909	How to change login name of user in Active Directory	sAMAccountName    = User logon name, (pre-windows 2000) \n    Format/Usage: domain\user.name (note, your code will only populate user.name)\n\nuserPrincipalName = User logon name\n    Format/Usage: user.name@domain.local	0
1016491	1016471	how to compare ip addresses	var ips = new[] { IPAddress.Parse( "127.0.0.1"),\n                   IPAddress.Parse( "192.168.1.1"),\n                   IPAddress.Parse( "10.0.0.1" ) };\n\nvar ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);\n\nif (ips[0].Equals(ep.Address))\n{\n    Console.WriteLine("Equal!");\n}	0
23174368	23173222	Combinations Generation using Backtracking Algorithm	static void Combo(int a, int b, int c)\n{\n    if (a < 10)\n    {\n        if (b < 10)\n        {\n            if (c < 10)\n            {\n                Console.WriteLine("( {0}, {1}, {2})", a, b, c);\n                Combo(a, b, ++c);\n            }\n            else\n            {\n                c = 0;\n                Combo(a, ++b, c);\n            }\n        }\n        else\n        {\n            c = 0; b = 0;\n            Combo(++a, b, c);\n        }\n    }\n}	0
23063926	23063451	Waiting for a ThreadState to be "Stopped" in a Button Click Event	private void btnImportData_Click(object sender, EventArgs e)\n    {\n        imgBonne.Visible = false; //random image\n        rtConsole.Visible = true; //RichTextBox logger\n\n        btnImportData.Enabled = false;\n\n        Task.Run(ImportData).ContinueWith((Task task) =>\n        {\n            btnImportData.Enabled = true;\n            btnExportBellijst.Enabled = true;\n        }, TaskScheduler.FromCurrentSynchronizationContext());\n    }	0
26283992	26283037	c# Replace date with epoche	(Sun|Mon|Tue|Wed|Thu|Fri|Sat)[\s](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\s][1-31][\s][0-9]{2}:[0-9]{2}:[0-9]{2}[\s][0-9]{4}	0
14962874	14962244	Fire DLL event from another DLL (or Application)	public delegate void _Event(int code);\npublic event _Event TestEvent;\npublic void FireEvent(int val){TestEvent(val);}	0
7772458	7772284	Alt-Tab pedal with an Arduino	SendKeys.Send("%{TAB}");	0
22070366	22054408	Reading content of sundry text files in a WPF C# application	for (int i = 0; i <= Verkn?pfung.Count - 1; i += 2)\n            {\n                Image Icon = new Image();\n                Icon.Source = new BitmapImage(new Uri(@"Images\Fugue Icons\document.png", UriKind.Relative));\n                Icon.Height = 16;\n                Icon.Width = 16;\n                Icon.Stretch = Stretch.None;\n\n                var tmp = i;\n\n                MenuItem MenuItem = new MenuItem();\n                MenuItem.Click += delegate { Process.Start(Verkn?pfung[1 + tmp]); };\n                MenuItem.Header = Verkn?pfung[0 + i];\n                MenuItem.Icon = Icon;\n                MenuItem.Padding = new Thickness(5);\n\n                MI_Verkn?pfungen.Items.Add(MenuItem);\n            }	0
1897456	1897430	Linq - how to combine two enumerables	var query = from index in Enumerable.Range(0,a.Length)\n            select new { A = a[index], B = str[index] };	0
22573398	22572103	Custom ICollection List Setter in a Entity for code first	set\n{\n    _mySelections = value;\n}	0
19152990	19152517	Show text file data in textbox with Data binding	StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filenamebox.Text + ".txt");\nif ( file != null)\n{\n     // Do what you want\n}	0
21613585	21613255	How to track changes in a specified folder on c#	public void Watcher()\n{\n    //Create a new FileSystemWatcher.\n    FileSystemWatcher watcher = new FileSystemWatcher();\n\n    //Set the filter to only catch TXT files.\n    watcher.Filter = "*.txt";\n\n    //Subscribe to the Created event.\n    //Created Occurs when a file or directory in the specified Path is created.\n    //You can change this based on what you are trying to do.\n    watcher.Created += new FileSystemEventHandler(YOUR_EVENT_HANDLER);\n\n    //Set the path to you want to monitor\n    watcher.Path = @"C:\PATH\";\n\n    //Enable the FileSystemWatcher events.\n    watcher.EnableRaisingEvents = true;\n}	0
28807525	28806432	Post Json Dictionary to the controller	public JsonResult Tflow(string basedetails)\n{   \n    //some code\n    var model = new JavascriptSerializer().Deserialize<JsonFileContentInputs>(basedetails);\n    // Your code\n}	0
27297529	27297503	C# Array of objects, can't set values	City[] arr = new City[1];\narr[0] = new City();\narr[0].setName("New York");	0
32696844	32696540	Parse a string in c# after reading first and last alphabet	string CutString(string input)\n {\n      Match result =  Regex.Match(input, @"[a-zA-Z]+[0-9]+");\n      return result.Value;\n }	0
6110927	6110040	Deploying VSIX using MSI installer	"%VSInstallDir%\Common7\Ide\Extensions\Your Company\Your Product\Version"	0
818618	818583	How can I install a printer using .NET?	rundll32.exe printui.dll,PrintUIEntry /?	0
11509457	11509025	How do multiple layers work in the MVVM pattern?	public class WidgetListViewModel \n{\n    public ObservableCollection<WidgetViewModel> Widgets {get; set; } \n}\n\npublic class WidgetViewModel\n{\n    public string WidgetName { get; set; }\n    public string WidgetDescription { get; set; }\n    public ObservableCollection<WidgetPartViewModel> Parts { get; set; }\n}\n\npublic class WidgetPartViewModel\n{\n    public int PartId { get; set; }\n    public System.Windows.Media.Color Color { get; set; }\n}	0
12388722	12388686	C# Use returned web service String as XML Data source in Grid View	protected void Page_Load(object sender, EventArgs e)\n{\n    XmlDataSource1.Data = ResultOfMyWebService;\n}	0
23497735	23487535	Can't get date show in ActiveGantt CSN timeblocks	private void ActiveGanttCSNCtl1_CustomTierDraw(object sender, AGCSN.CustomTierDrawEventArgs e)\n    {\n        if (e.Interval == E_INTERVAL.IL_HOUR & e.Factor == 12)\n        {\n            e.Text = e.StartDate.ToString("tt").ToUpper();\n        }\n        if (e.Interval == E_INTERVAL.IL_MONTH & e.Factor == 1)\n        {\n            e.Text = e.StartDate.ToString("MMMM yyyy");\n        }\n        if (e.Interval == E_INTERVAL.IL_DAY & e.Factor == 1)\n        {\n            e.Text = e.StartDate.ToString("ddd d");\n        }\n    }	0
32827010	32826324	Parse xml with XDocument convert date to datetime	string xml = @"<root><date>2003-07-15T10:00:00</date>\n<enddate>2016-02-02</enddate>\n<startdate>2000-02-10</startdate>\n</root>";\n\n  XDocument doc = XDocument.Parse(xml);\n\n  DateTime t;\n  doc\n    .DescendantNodes()\n    .Where (d => d.NodeType == XmlNodeType.Text && \n      DateTime.TryParse(d.ToString(),out t))\n    .ToList()\n    .ForEach( n => n.Parent.SetValue(DateTime.Parse(n.ToString())));	0
31631997	31624597	Windows Phone - cancel back from mainpaga.xaml	protected override void OnBackKeyPress(CancelEventArgs e)\n{\n    if (MessageBox.Show("Wszystkie zmiany zostan?? odrzucone", "Odrzucenie Zmian", MessageBoxButton.OKCancel) != MessageBoxResult.OK)\n    {\n            e.Cancel = true; \n\n    }\n}	0
3006343	3005854	.NET C# MouseEnter listener on a Control WITH Scrollbar	private Form frmPopup;\n\n    private void treeView1_MouseEnter(object sender, EventArgs e) {\n        timer1.Enabled = true;\n        if (frmPopup == null) {\n            frmPopup = new Form2();\n            frmPopup.StartPosition = FormStartPosition.Manual;\n            frmPopup.Location = PointToScreen(new Point(treeView1.Right + 20, treeView1.Top));\n            frmPopup.FormClosed += (o, ea) => frmPopup = null;\n            frmPopup.Show();\n        }\n    }\n\n    private void timer1_Tick(object sender, EventArgs e) {\n        Rectangle rc = treeView1.RectangleToScreen(new Rectangle(0, 0, treeView1.Width, treeView1.Height));\n        if (!rc.Contains(Control.MousePosition)) {\n            timer1.Enabled = false;\n            if (frmPopup != null) frmPopup.Close();\n        }\n    }	0
29570969	29570839	encapsulation of an array of objects c#	class CFiles\n{\n    //private int[] v=new int[5];//dont want to specify the dimention of array here\n    private int[] v;\n    public int[] V { get { return v; } set { v = value; } }\n\n    private List<string> words;\n    public List<string> Words { get { return words; } set { words = value; } }\n\n    public CFiles()\n    {\n        words = new List<string>();\n        v = new int[51]; //needs to be 51 if you are going to assign to index 50 below\n    }\n}	0
24278461	24278368	Get the authorized application list through firewall	Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); \n  INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); \n  applications = \n    (INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications;	0
5085209	5085185	Compare with string values using IQueryable<T> and Expressions	myList.Where("propertyName > 1000");	0
104948	104918	Command Pattern : How to pass parameters to a command?	public class DeletePersonCommand: ICommand\n{\n     private Person personToDelete;\n     public DeletePersonCommand(Person personToDelete)\n     {\n         this.personToDelete = personToDelete;\n     }\n\n     public void Execute()\n     {\n        doSomethingWith(personToDelete);\n     }\n}	0
6913067	6912700	Adding new Columns to GridView with a new DataSource	Visible="<%= ShowColumnX %>"	0
13990	13963	Best method of Textfile Parsing in C#?	customer:\n  name: Orion\n  age: 26\n  addresses:\n    - type: Work\n      number: 12\n      street: Bob Street\n    - type: Home\n      number: 15\n      street: Secret Road	0
29151813	29149943	Closing mdi child in SplitContainer	while (splitContainer1.Panel1.Controls.Count > 0)\n        splitContainer1.Panel1.Controls[0].Dispose();\n    var accueil = new Accueil();\n    accueil.TopLevel = false;\n    accueil.Dock = DockStyle.Fill;\n    accueil.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n    accueil.Visible = true;\n    this.splitContainer1.Panel1.Controls.Add(accueil);	0
30301738	30301689	how to post a status in a group using Facebook graph explorer?	POST /v2.3/{group-id}/feed	0
14779874	14779836	Dynamically generate menustrip items	void AddMenuItem(string text, string action)\n{\n   ToolStripMenuItem item = new ToolStripMenuItem();\n   item.Text = text;\n   item.Click += new EventHandler(item_Click);\n   item.Tag = action;\n\n   //first option, inserts at the top\n   //historyMenu.Items.Add(item);\n\n   //second option, should insert at the end\n   historyMenuItem.DropDownItems.Insert(historyMenuItem.DropDownItems.Count, item);\n}\n\nprivate void someHistoryMenuItem_Click(object sender, EventArgs e)\n{\n   ToolStripMenuItem menuItem = sender as ToolStripMenuItem;\n\n   string args = menuItem.Tag.ToString();\n\n   YourSpecialAction(args);\n}	0
12844392	12844078	Adding very fast to a ListView from multiple threads	// Start of work\nflatListView1.SuspendLayout();\n\n// Below code inside your delegate\n\nflatListView1.Items.Add(name).SubItems.AddRange(row1);   \n\nif ((flatListView1.Items.Count % 1000) == 0)\n{\n    // Force a refresh of the list\n    flatListView1.ResumeLayout();\n    // Turn it off again\n    flatListView1.SuspendLayout();         \n}\n\n// End of code inside delegate\n\n// Resume layout when adding is finished\n\nflatListView1.ResumeLayout();	0
14845473	14845438	Remove characters not in string variable as pattern in Regex.Replace	// returns "gzaHQPKUgQjXPdajkl"\nRegex.Replace("gzaHQ6PKUgQjXP+/dajkl==", @"[^a-zA-Z0-9-_.~]", "");	0
33301661	33292080	Matching vb.net string value to c# enum	switch(textValue){\n    case "CRT":\n       return ParamChildKey.Create;\n    ...\n}	0
28245828	28234369	How to do internal interfaces visible for Moq?	[assembly: InternalsVisibleTo("InternalsVisible.DynamicProxyGenAssembly2")]\n[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]	0
20417751	18145985	Apply custom font to html in itextsharp	BaseFont rockwellBold = BaseFont.CreateFont(Server.MapPath("includes/fonts/") + "ROCKB.TTF", BaseFont.CP1250, BaseFont.EMBEDDED);\nFont rock_11_bold_header = new Font(rockwellBold, 11, Font.NORMAL, new BaseColor(190, 36, 34));\nPdfPCell descHeadrCell = new PdfPCell();\ndescHeadrCell.AddElement(new Phrase("Demo"), rock_11_bold_header));	0
30266646	30266562	Is there a way to stop the WinForms designer defaulting to control Load event	[DefaultEvent("Click")]\npublic class MyRadionButton : RadionButton {\n}	0
15406791	15406336	Databind a nullable type in XAML\Windows 8 store app	public class NullableValueConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, \n                          CultureInfo culture)\n    {\n        return value == null ? string.Empty : value.ToString();\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, \n                              CultureInfo culture)\n    {\n        string s = value as string;\n\n        int result;\n        if (!string.IsNullOrWhiteSpace(s) && int.TryParse(s, out result))\n        {\n            return result;\n        }\n\n        return null;\n    }\n}	0
11234901	11212358	Setting a relative path in crystal reports	using CrystalDecisions.CrystalReports.Engine;\n    using CrystalDecisions.Shared;\n\n    using (var report = new ReportClass { FileName = Server.MapPath("/AppName/Reports/MyReport.rpt") })\n    {\n        report.Load();\n    ...	0
29881046	29878093	Is it the best option to convert a java interface with static fields in a abstract class in c#?	public interface IHashStorage<T>\n{\n    float InitialLoadFactor { get; }\n    int InitialCapacity { get; }\n}\n\npublic class HashStorageBase<T> : IHashStorage<T>\n{\n    private readonly float _initialLoadFactor = 0.7f;\n    private readonly int _initialCapacity = 149;\n    public float InitialLoadFactor\n    {\n        get { return _initialLoadFactor; }\n    }\n\n    public int InitialCapacity\n    {\n        get { return _initialCapacity; }\n    }\n}\n\npublic class HashStorage1<T> : HashStorageBase<T>\n{\n    ...\n}	0
1612469	1612423	C# extracting certain parts of a string	Regex regex = new Regex("class=\\\"peopleCount\\\"\\>(?<data>[^\\<]*)",\nRegexOptions.CultureInvariant\n| RegexOptions.Compiled\n);	0
6292186	6291610	Reading only HTML Content from a Web site page	StringBuilder sb  = new StringBuilder();\nbyte[]        buf = new byte[8192];\n\nHttpWebRequest  request  = (HttpWebRequest)WebRequest.Create("http://www.your-url.com");\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\nStream resStream = response.GetResponseStream();\n\nstring tempString = null;\nint    count      = 0;\ndo\n{\n    count = resStream.Read(buf, 0, buf.Length);\n\n    if (count != 0)\n    {\n        tempString = Encoding.ASCII.GetString(buf, 0, count);\n        sb.Append(tempString);\n    }\n}\nwhile (count > 0);\n\nConsole.WriteLine(sb.ToString());	0
4510257	4510212	How I can get web page's content and save it into the string variable	WebClient client = new WebClient();\nstring downloadString = client.DownloadString("http://www.gooogle.com");	0
380238	380198	How to pass a function as a parameter in C#?	static object InvokeMethod(Delegate method, params object[] args){\n    return method.DynamicInvoke(args);\n}\n\nstatic int Add(int a, int b){\n    return a + b;\n}\n\nstatic void Test(){\n    Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4));\n}	0
11244708	11209059	DataGridView mouse wheel scrolling stoped working	private void SettingsGrid_MouseEnter(object sender, EventArgs e)\n{\n     dataGridView1.Focus();\n}	0
6697700	6697617	Selecting an option from a particular set	public abstract class Language\n{\n   public static readonly AsianLanguage Asian = AsianLanguage.Instance;\n   public static readonly EuropeanLanguage European = EuropeanLanguage.Instance;\n}\npublic class AsianLanguage\n{\n   public static readonly AsianLanguage Instance = new AsianLanguage ();\n   public Language Cantonese {get;private set};\n   public Language Mandarin {get;private set};\n   private AsianLanguage (){}\n}\npublic class EuropeanLanguage\n{\n   public static readonly EuropeanLanguage Instance = new EuropeanLanguage ();\n   public Language Italian {get;private set;}\n   public Language German {get;private set;}\n   private EuropeanLanguage (){}\n}	0
6202963	6202893	NullReferenceException on DropDownListFor after [HttpPost]	[HttpPost]\n        public ActionResult Index(Person person)\n        {\n            if (ModelState.IsValid)\n            {\n                personRepo.Add(person);\n                personRepo.Save();\n            }\n            return View(new PersonFormViewModel(person));\n        }	0
14302690	14301838	Opening an XML file and converting this to UTF-8	string path = @"C:\test\test.xml";\nstring path_new = @"C:\test\test_new.xml";\n\nEncoding utf8 = new UTF8Encoding(false);\nEncoding ansi = Encoding.GetEncoding(1252);\n\nstring xml = File.ReadAllText(path, ansi);\n\nXDocument xmlDoc = XDocument.Parse(xml);\n\nFile.WriteAllText(\n    path_new,\n    @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),\n   utf8\n);	0
10206031	10206000	how to have a function run inside a service every 10 minutes?	protected override void OnStart(string[] args)\n{\n     log.Info("Info - Service Started");\n    _timer = new Timer(10 * 60 * 1000); // every 10 minutes\n    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n    _timer.Start(); // <- important\n}	0
17503968	17503848	What do you do when you have to name a class that starts with a number?	Company{name}Analyzer	0
3187361	3185727	Order of Header/FooterParts in OpenXML document	Imports System.Linq\nImports <xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">\n\nModule Module1\n    Sub Main()\n        Dim doc As String = "C:\headers.docx"\n        Dim wordDoc = WordprocessingDocument.Open(doc, False)\n        Using wordDoc\n            Dim mainPart = wordDoc.MainDocumentPart\n            Dim docStream As System.IO.StreamReader = New IO.StreamReader(mainPart.GetStream)\n            Dim xDoc As XElement = XElement.Load(docStream)\n            Dim sectionHeaders = From e In xDoc...<w:sectPr> Select e.<w:headerReference>\n        End Using\n    End Sub\n\nEnd Module	0
31231024	31230933	Input string was not in a correct format even i have the right values in it	TotalPrice = Int32.Parse(txtTotalProducts.Text)	0
31125496	31125231	Onclick Button open a new Window only with Image inside	private void button1_Click(object sender, EventArgs e)\n{\n    Form form = new Form();\n    form.Show();\n\n    PictureBox pb = new PictureBox();\n    pb.ImageLocation = "https://www.google.com/images/srpr/logo11w.png";\n    pb.Size = form.Size;\n    pb.SizeMode = PictureBoxSizeMode.Zoom;\n\n    form.Controls.Add(pb);\n}	0
8418519	8418237	How do I get a console application to check for updates without using ClickOnce?	system.io	0
17951920	17951152	Show/Hide dropdown list values from other dropdown list value changed	protected void ddlLoanType_SelectedIndexChanged(object sender, EventArgs e)\n        {\n             if (ddlLoanType.SelectedValue =="2")\n            {\n                ddlDuration.Items.FindByValue("12").Enabled = false;\n                ddlDuration.Items.FindByValue("24").Enabled = false;\n\n\n            }\n        }	0
26372137	26372112	Occurrence of a string in all the file names within a folder	string searchTerm = "grape";\nint grapeCount = \n    new DirectoryInfo(directoryPath)\n        .EnumerateFiles(string.Format("*{0}*", searchTerm))\n        .Count();	0
2028115	2020984	A problem with Relative Path Resolution when setting an Image Source	var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};	0
60089	60032	Getting the array key in a foreach loop	int[] values = { 5, 14, 29, 49, 99, 150, 999 };\n\nfor (int key = 0; key < values.Length; ++key)\n  if (search <= values[key] && !stop)\n  {\n    // set key to a variable\n  }	0
13349622	13348654	SignalR send message to single connectionId	Clients.Client(someConnectionIdIWantToSendToSpecifically).doSomething();	0
30383524	30375216	Stop capture element in windows RT	_mediaCapture.Dispose();	0
31117334	31116709	How calculate screen position	Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, Camera.main.pixelHeight-20, camera.nearClipPlane));\ntransform.position = test1;	0
1021023	973838	State information corrupted after dynamically adding control	Page page = new Page();\n\n/*Not the exact way I init the control. But that's irrevelant*/\nControl control = new Control();\npage.Controls.Add(control)\nstring controlHtml;\n\nusing(StringWriter sw = new StringWriter())\n{\n   HttpContext.Current.Server.Execute(page, sw, false);\n   controlHtml = sw.ToString();\n}	0
29552457	29550320	Set Control Styles to ThemeResource Values Programmatically In Windows Phone 8.1	Brush accentBrush = Resources["PhoneAccentBrush"] as Brush;\nTextBlock textBlock = new TextBlock()\n{\n    Text = "Hello World",\n    Foreground = accentBrush \n};	0
11040792	11040717	Selecting a DGV Cell	if (cell.Value != null && cell.Value.ToString() == "323")	0
26775131	26774858	Change nested loop into Linq	var items = errors.SelectMany(entity => entity.Select(error => new { Entity = entity, Error = error }));\n\nforeach(var item in items)\n{\n    validationErrors.Add(\n        item.Entity.Entry.Entity.GetType().FullName \n            + "."\n            + item.Error.PropertyName,\n        errorMessage);\n}	0
18738429	18738313	How to set picture box height in percentage?	pictureBox1.Height = (int)(tableLayoutPanel1.Height * 0.7)	0
32119171	31946873	Email Audit API - 403 Forbidden	public static GOAuth2RequestFactory RefreshAuthenticate(){\nOAuth2Parameters parameters = new OAuth2Parameters(){\n    RefreshToken = "<YourRefreshToken>",\n    AccessToken = "<AnyOfYourPreviousAccessTokens>",\n    ClientId = "<YourClientID>",\n    ClientSecret = "<YourClientSecret>",\n    Scope = "https://apps-apis.google.com/a/feeds/compliance/audit/",\n    AccessType = "offline",\n    TokenType = "refresh"\n};\nOAuthUtil.RefreshAccessToken(parameters);\nreturn new GOAuth2RequestFactory(null, "<YourApplicationName>", parameters);\n}	0
2052124	2052003	HtmlTable, HtmlTableRow, HtmlTableCell - creating thead, tbody and tfoot	TableRow row = new TableHeaderRow();\n        TableRow row2 = new TableRow();\n        TableRow row3 = new TableFooterRow();\n        Table table = new Table();\n\n        var cell1 = new TableCell();\n        row.TableSection = TableRowSection.TableHeader;\n        cell1.Text = "Header";\n        row.Cells.Add(cell1);\n\n        var cell2 = new TableCell();\n        cell2.Text = "Contents";\n        row2.Cells.Add(cell2);\n\n        var cell3 = new TableCell();\n        cell3.Text = "Footer";\n        row3.Cells.Add(cell3);\n        row3.TableSection = TableRowSection.TableFooter;\n\n\n        table.Rows.Add(row);\n        table.Rows.Add(row2);\n        table.Rows.Add(row3);\n        this.Controls.Add(table);	0
27717324	27716888	What's the proper way to convert a Vector3DF into byte array?	//sample data\n    Vector3DF v3df = new Vector3DF(10, 20, 30);\n\n    //get data size\n    int size = Marshal.SizeOf(v3df);\n\n    //allocate memory\n    IntPtr ptr = Marshal.AllocHGlobal(size);\n\n    //copy data to memory\n    Marshal.StructureToPtr(v3df, ptr, false);\n\n    //copy data from memory to byte array\n    byte[] bytes = new byte[size];\n    Marshal.Copy(ptr, bytes, 0, bytes.Length);\n\n    //release memory\n    Marshal.FreeHGlobal(ptr);	0
11835648	11835512	Get the Value of XElements that dont has Child	document.Root.Elements("Company").Elements()\n                .Where(item => !item.HasElements).ToList();	0
6170301	6170207	Reading and setting base 3 digits from base 2 integer	public class Base3Handler\n{\n    private static int[] idx = {1, 3, 9, 27, 81, 243, 729, 729*3, 729*9, 729*81};\n\n    public static byte ReadBase3Bit(short n, byte position)\n    {\n        if ((position > 8) || (position < 0))\n            throw new Exception("Out of range...");\n        return (byte)((n%idx[position + 1])/idx[position]);\n    }\n\n    public static short WriteBase3Bit(short n, byte position, byte newBit)\n    {\n        byte oldBit = ReadBase3Bit(n, position);\n        return (short) (n + (newBit - oldBit)*idx[position]);\n    }\n}	0
11515874	11490104	FluentNHibernate exception with a generic base type	IgnoreBase(typeof(TreeItem<>))	0
6984735	6984527	C# Displaying revision/build number in webservice description?	WebServiceAttribute att = (NamespaceAttribute)t.GetCustomAttributes(WebServiceAttribute))[0];\n\natt.Description = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();	0
15581424	15581402	See if entered textbox value exists as part of an array	for (int x = 0; x < products.Length; x++)\n    {\n        if (products[x].productID == productChoice)\n        {\n            productprice = products[x].price;\n            CoinChange CC = Service.TotalChange(productprice, amountDeposited);\n            MessageBox.Show("Refund amount:" + "\r\n" + "Nickel: " + CC.Nickel.ToString() + "\r\n" + "Dime: " +\n                            CC.Dime.ToString() + "\r\n" + "Quarter: " + CC.Quarter.ToString());\n            return;  // Found and handled the product\n        }\n    }\n    // If we get here none of the products matched\n    MessageBox.Show("Invalid product ID.  Please check your catalog and try again.");	0
23159856	23135101	How to deselect a single Item in a listbox	var index = lstGroups.SelectedIndex;\n            lstGroups.SelectedIndex = -1;\n            lstGroups.Items[index].Attributes["style"] = "background-color:lightblue";	0
21560827	21560758	How to replice Entity Framework FirstOrDefaultAsync	public Task<MyUser> FindByNameAsync(string userName)\n{\n   var myusers = new List<MyUser> \n   { \n       new MyUser() { Id="1", UserName = "tom", Password = "secret" },\n       new MyUser() { Id="2", UserName = "mary", Password = "supersecret" }\n   };\n\n   var task = Task.FromResult(myusers.SingleOrDefault(u => u.UserName == userName));\n\n   return task;\n}	0
12941573	12916901	How to control winform mschart legend text alignment c#?	chartSel.Legends[ySeries.Name].CellColumns.Add(new LegendCellColumn("", LegendCellColumnType.SeriesSymbol, ""));\nchartSel.Legends[ySeries.Name].CellColumns[0].Alignment = ContentAlignment.TopLeft;\nchartSel.Legends[ySeries.Name].CellColumns[0].Margins = new System.Windows.Forms.DataVisualization.Charting.Margins(0, 0, 1, 1);\nchartSel.Legends[ySeries.Name].CellColumns[0].MinimumWidth = 250;\nchartSel.Legends[ySeries.Name].CellColumns[0].MaximumWidth = 250;\n\nchartSel.Legends[ySeries.Name].CellColumns.Add(new LegendCellColumn("", LegendCellColumnType.Text, ySeries.Name));\nchartSel.Legends[ySeries.Name].CellColumns[1].Alignment = ContentAlignment.MiddleLeft;\nchartSel.Legends[ySeries.Name].CellColumns[1].Margins = new System.Windows.Forms.DataVisualization.Charting.Margins(0, 0, 1, 1);\nchartSel.Legends[ySeries.Name].CellColumns[1].MinimumWidth = 1500;\nchartSel.Legends[ySeries.Name].CellColumns[1].MaximumWidth = 1500;	0
11607741	11518959	WCF was unable to deserialize List with in a Dictionary element	IsReference = true	0
6561469	6561316	How can I call a MYSQL SP from EF4	using(EFEntity ef = new EFEntity ())\n {\n    var results = from result in ef.YourSpName(Param1, param2,..)\n              select result\n }	0
6677098	6676856	DateTime.ParseExact, Ignore the timezone	DateTimeOffset dt =DateTimeOffset.Parse("2011-05-05T11:35:47.743-04:00", null);	0
10643181	10643102	Using XElement to edit attribute names	using System.Xml.Linq\n\nXElement books = XElement.Load("{file}");\n\nstring _Attribute;\nforeach (var bookID in books.Elements("book")) \n{\n    if(bookID.Attribute("id") != null)\n    {\n        _Attribute = bookID.Attribute("book").Value;\n        if(!Regex.IsMatch(_Attribute, @"-[0-9]+$"))\n        {\n            Regex.Replace(_Attribute, @"-[0-9]+$", "");\n        }\n        bookID.Attribute("id").Value = _Attribute;\n    }\n}	0
23491438	23491325	Finding whether a number is Prime or not by limiting the number of iterations-c#	public static bool Isprime(long i)\n{\n    if (i < 2)\n    {\n        return false;\n    }\n    else if (i < 4)\n    {\n        return true;\n    }\n    else if ((i & 1) == 0)\n    {\n        return false;\n    }\n    else if (i < 9)\n    {\n        return true;\n    }\n    else if (i % 3 == 0)\n    {\n        return false;\n    }\n    else\n    {\n        double r = Math.Floor(Math.Sqrt(i));\n        int f = 5;\n        while (f <= r)\n        {\n            if (i % f == 0) { return false; }\n            if (i % (f + 2) == 0) { return false; }\n            f = f + 6;\n        }\n        return true;\n    }  \n}	0
20274511	20274373	create a dropdonlist and add item on onload function	if (!Page.IsPostBack)\n        {\n            int x = DateTime.Now.Year;\n            List<string> str = new List<string>();\n\n            for (int i = x; i >= 1975; i--)\n            {\n\n                str.Add(i.ToString());\n            }\n\n            ddlYear.DataSource = str;\n            ddlYear.DataBind();\n        }	0
19851289	19851232	How to change the text of the multiple asp:label using for loop in C# ASP.NET	for(int i = 1; i <= 4; i++){\n  var label = ((Label)FindControl("lbl_Text" + i));\n  if(label != null){\n     label.Text = "hello";\n  }\n}	0
9397514	9380963	using MySQL to create JSON with C# and JSON.Net	var currentRoot = null;\n var rootObjects = new List<RootObject>();\n while (rdr.Read()){\n        string name= rdr.GetValue(0).ToString();\n        string serial = rdr.GetValue(1).ToString();\n        string bz = rdr.GetValue(2).ToString(); <-- made this up\n        if( currentRoot == null || currentRoot.name != name )\n        {\n            if( currentRoot != null ){\n               rootObjects.Add(currentRoot);\n            }\n            currentRoot = new RootObject();\n            currentRoot.name = name;\n        }\n        currentRoot.serials.Add(new Serial(){zone = bz});\n\n        ... instantiate other classes\n    }\n    rdr.Close();\n\n foreach( var rootObj in rootObjects) doSomethingWithRootObj(rootObj);	0
17764630	17764542	Access some data from list	List<string> description = youroriginalList\n                          .Select(x=>x.System_Description).ToList<string>();	0
5079368	4944813	Rtf to WordML Convert in C#	//your rtf string\nstring rtfStrx = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang2057{\\fonttbl{\\f0\\fnil\\fcharset0 Arial;}}\r\n\\viewkind4\\uc1\\pard\\fs20\\tab\\tab\\tab\\tab af\\par\r\n}\r\n"\n\n//convert string to bytes for memory stream\nbyte[] rtfBytex = Encoding.UTF8.GetBytes(rtfStrx);\nMemoryStream rtfStreamx = new MemoryStream(rtfBytex);\n\nDocument rtfDocx = new Document(rtfStreamx);\n\nrtfDocx.Save(@"C:\Temp.xml", SaveFormat.WordML);	0
20725762	20725681	Calculate angle between two points relative to the Y-Axis	static double GetAngle(double x1, double y1, double x2, double y2)\n{\n    var w = x2 - x1;\n    var h = y2 - y1;\n\n    var atan = Math.Atan(h/w) / Math.PI * 180;\n    if (w < 0 || h < 0)\n        atan += 180;\n    if (w > 0 && h < 0)\n        atan -= 180;\n    if (atan < 0)\n        atan += 360;\n\n    return atan % 360;\n}	0
29363763	29363582	How to add an image before a checkbox in Windows form application	TreeView1.ImageList = ImageList1\n// (Assumes that imageList1 contains at least two images and\n// the TreeView control contains a selected image.)\ntreeView1.SelectedNode.ImageIndex = 0;\ntreeView1.SelectedNode.SelectedImageIndex = 1;	0
8189971	8189928	linq with nullable datetime	var Output = from s in ....\n              select new MyModel() \n              {\n                  TheCloseDate = s.TheCloseDate ?? null // Or whatever you want, like DateTime.Now\n              }	0
25345730	25345104	Send Powershell from C# and return Array Object from results?	PSObject[] results = pipeline.Invoke().ToArray();	0
13034553	13034170	How do I set up multiple threads in a Worker and dispatch messages to them?	while (true)\n{\n    int maxThreadsPerWorkerRole = 3;//assuming each worker role can handle 3 jobs simultaneously\n    var messages = Queue.GetMessages(3);//Get 3 messages from the queue\n    if (messages != null && messages.Count > 0)//Ensuring there is some work which needs to be done\n    {\n        var myTasks = new List<Task>();\n        for (int i=0; i<messages.Count; i++)\n        {\n            Job MyJob = Kernel.Get<Job>();//Get the job\n            var task = Task.Factory.StartNew(() => MyJob.Run(messages[i])); \n            myTasks.Add(task);\n        }\n        Task.WaitAll(myTasks.ToArray());//Wait for all tasks to complete.\n        for (int i=0; i<messages.Count; i++)\n        {\n            //Write code to delete the message.\n        }\n        //Check if the queue is empty or not. If the queue is not empty, then repeat this loop\n        //Otherwise simply exit this loop.\n        if (Queue.RetrieveApproximateMessageCount() == 0)\n        {\n            break;\n        }\n    }\n}	0
9859679	9859619	using multithreading to do OCR with C#	Task[] tasks = new Task[2];\ndecimal[] numbers;\ntasks[0] = Task.Factory.StartNew(() =>\n   {numbers = getNumbers(bitmap, dictionary1);});\nstring[] text;\ntasks[1] = Task.Factory.StartNew(() =>\n   {text = getText(bitmap, dictionary2);});\n\nTask.WaitAll(tasks);  // Wait for all parallel tasks to finish \n                      // before using their output.\n\ntextBox1.Text = "" + text[0];	0
18202792	18202686	Sequence contains more than one matching element	this.DressingItems.Where(x=> x.DressingInfo.CatID == catId && \n                                x.ProductID == this.ProductID).ToList()\n                 .ForEach(item=>item.IsDefault = false);	0
11221495	11220837	Understanding how Trace works in C#	string logSource = "_myEventLogSource";\n        if (!EventLog.SourceExists(logSource))\n            EventLog.CreateEventSource(logSource, logSource);\n\n        EventLogTraceListener myTraceListener = new EventLogTraceListener(logSource);\n\n        // Add the event log trace listener to the collection.\n        System.Diagnostics.Trace.Listeners.Add(myTraceListener);\n\n        // Write output to the event log.\n        System.Diagnostics.Trace.WriteLine("Test output");	0
13493771	13477689	Find number of decimal places in decimal value regardless of culture	decimal argument = 123.456m;\nint count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];	0
11650321	11649803	Change the Selection Color of a WinForms ComboBox	private void comboBoxDb_DrawItem(object sender, DrawItemEventArgs e) \n{\n    var combo = sender as ComboBox;\n\n    if((e.State & DrawItemState.Selected) == DrawItemState.Selected)\n    {\n        e.Graphics.FillRectangle(new SolidBrush(Color.BlueViolet), e.Bounds);\n    }\n    else\n    {\n        e.Graphics.FillRectangle(new SolidBrush(SystemColors.Window), e.Bounds);\n    }\n\n    e.Graphics.DrawString(combo.Items[e.Index].ToString(),\n                                  e.Font,\n                                  new SolidBrush(Color.Black),\n                                  new Point(e.Bounds.X, e.Bounds.Y));\n}	0
22062729	22048080	Get specific (name) value from wcf dataservice	ServiceReference1.Product product = (ServiceReference1.Product)this.ProductsList.Items[productIndex];\nstring name = product.Name;	0
12092611	12081507	Open XML SDK Word Processing Vertical Orientation in Table Cell	TableCell cell = new TableCell(\n    new TableCellProperties(\n        new TextDirection() { Val = TextDirectionValues.BottomToTopLeftToRight }), \n    new Paragraph(\n        new Run(\n            new Text("test"))));	0
1349368	1349023	How Can I strip HTML from Text in .NET?	string StripHtml(string html)\n{\n    // create whitespace between html elements, so that words do not run together\n    html = html.Replace(">","> ");\n\n    // parse html\n    var doc = new HtmlAgilityPack.HtmlDocument();\n    doc.LoadHtml(html);\n\n    // strip html decoded text from html\n    string text = HttpUtility.HtmlDecode(doc.DocumentNode.InnerText);\n\n    // replace all whitespace with a single space and remove leading and trailing whitespace\n    return Regex.Replace(text, @"\s+", " ").Trim();\n}	0
21645290	21645120	How to delete values from two tables?	string strCommandText = @"DELETE FROM WINDOWSADMIN WHERE mcID=@MCID; \n                          DELETE FROM MEDICALCENTRE WHERE mcID=@MCID;";	0
7558253	7556367	How do I change the culture of a WinForms application at runtime	private void button1_Click(object sender, EventArgs e)\n{\n    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-BE");\n    ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));\n    resources.ApplyResources(this, "$this");\n    applyResources(resources, this.Controls);\n}\n\nprivate void applyResources(ComponentResourceManager resources, Control.ControlCollection ctls)\n{\n    foreach (Control ctl in ctls)\n    {\n        resources.ApplyResources(ctl, ctl.Name);\n        applyResources(resources, ctl.Controls);\n    }\n}	0
16340425	16340224	How Can Format Text Inside TextBoxes In WinForms	public void CreateMyRichTextBox()\n  {\n      RichTextBox richTextBox1 = new RichTextBox();\n      richTextBox1.Dock = DockStyle.Fill;\n\n\n      richTextBox1.LoadFile("C:\\MyDocument.rtf");\n      richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);\n\n      richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Bold);\n      richTextBox1.SelectionColor = Color.Red;\n\n      richTextBox1.SaveFile("C:\\MyDocument.rtf", RichTextBoxStreamType.RichText);\n\n      this.Controls.Add(richTextBox1);\n  }	0
5654637	5486526	WebDriver + swtichTo another browser	// This code assumes you start with only one browser window in your test.\n// If you have more than one browser window, your code will be more complex.\nstring originalHandle = driver.GetWindowHandle();\ndriver.FindElement(By.ClassName("power_buy_now_button")).Click();\n\n// May need to wait for window handles collection to have a .Count of 2,\n// as clicks are asynchronous.\nstring popupHandle = string.Empty;\nReadOnlyCollection<string> windowHandles = driver.GetWindowHandles();\nforeach (string handle in windowHandles)\n{\n    if (handle != originalHandle)\n    {\n        popupHandle = handle;\n        break;\n    }\n}\n\ndriver.SwitchTo().Window(popupHandle);\n// Do stuff in the popup window, eventually closing it with driver.Close()\ndriver.SwitchTo().Window(originalHandle);	0
16663337	16663028	Set ComboBox Text on Basis of SelectedIndex	private void tbTag_SelectedIndexChanged(object sender, EventArgs e)\n{\n    TagRecord tag = tbTag.SelectedItem as TagRecord;\n    BeginInvoke(new Action(() => tbTag.Text = tag.TagData));\n}	0
14085395	14085340	How would I optimize a nested for loop with linq	var query = from to in allCurrentTradeObjects\n            from ro in theseWantMe\n            where ro.Type == to.Type &&\n                  ro.MaxRent >= to.Rent &&\n                  ro.MinRooms <= to.Rooms &&\n                  ro.MinSquareMeters <= to.SquareMeters &&\n                  ro.MaxPrice >= to.Price &&\n                  ro.MinFloors <= to.Floors &&\n                  ro.TradeObjectId != to.TradeObjectId &&\n                  ro.TradeObjectId != myTradeObject.TradeObjectId\n            select new RatingListTriangleModel\n            {\n                To1Id = myTradeObject.TradeObjectId,\n                To2Id = to.TradeObjectId,\n                To3Id = ro.TradeObjectId,\n                T1OnT2Rating = 0,\n                T2OnT3Rating = 0,\n                T3OnT1Rating = 0,\n                TotalRating = 0\n            };\n\nforeach(var rlt in query)\n   this.InsertOrUpdate(rlt);\n\nthis.Save();	0
11970682	11970313	DelegatingHandler for response in WebApi	public class DummyHandler : DelegatingHandler\n{\n    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n    {\n        // work on the request \n       Trace.WriteLine(request.RequestUri.ToString());\n\n       return base.SendAsync(request, cancellationToken)\n           .ContinueWith(task =>\n           {\n               // work on the response\n               var response = task.Result;\n               response.Headers.Add("X-Dummy-Header", Guid.NewGuid().ToString());\n              return response;\n           });\n    }\n}	0
6842890	6842787	Help with regex c#	string input = @"access_token=f34b46f0f109d423sd4236af12d1bce7f10df108ec2183046b8f94641ebe&expires_in=0&user_id=37917395";\n\n\nvar result = Regex.Match(input, @"access_token=([^&]+).*?user_id=([^&]+)");\n\nvar access_token = result.Groups[1].Value;\nvar user_id = result.Groups[2].Value;	0
33748172	33747405	Get return value from stored procedure using ExecuteSqlCommand (using Entity Framework)	EXEC @ReturnValue = [StoredProc] @param1 ...	0
6600408	6600374	ASP.net -- Identifying a specific control in code behind	for( int i = 0; i < upperLimit; i++ )\n{\n    TextBox control = Page.FindControl("tbNumber" + i) as TextBox;\n    if( control != null ) {\n        // do what you need to do here\n        string foo = control.Text;\n    }\n}	0
28154864	28154288	ListView databinding to list of string arrays	gvBinding = new Binding();\ngvBinding.Mode = BindingMode.OneWay;                               \ngvBinding.Path = new PropertyPath("DocFields[" + FieldIndex.ToString() + "].DispValueShort");	0
3825631	3825528	Bind a Dictionary<K,V> to a DropDownList	ddl.DataSource = d.Select(r => new KeyValuePair<string, string>(r.Key, r.Value)).ToList();	0
17335868	17335794	How to create an array of RichTextBox's in c#	for (int i = 0; i < richboxes.Length; i++)\n        {\n            richboxes[i] = new RichTextBox(); // Instance the TextBox\n\n            Controls.Add(richboxes[i]);\n            richboxes[i].Location = new System.Drawing.Point(14, y);\n            richboxes[i].Name = "richTextBox" + (12 + j);\n            richboxes[i].Size = new System.Drawing.Size(671, 68);\n            richboxes[i].TabIndex = 41 + j;\n            richboxes[i].Text = "";\n            y += 70;\n            j++;\n        }	0
1949085	1948014	How to handle Form caption right click	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n    }\n    protected void OnTitlebarClick(Point pos) {\n        contextMenuStrip1.Show(pos);\n    }\n    protected override void WndProc(ref Message m) {\n        if (m.Msg == 0xa4) {  // Trap WM_NCRBUTTONDOWN\n            Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);\n            OnTitlebarClick(pos);\n            return;\n        }\n        base.WndProc(ref m);\n    }\n}	0
23550552	23544243	How to read most recent item from IObservable from Func?	var selectedItemOut = new Subject<int?>();\n\n// Hold the last result from the OnNext\nint? results = null;\n\n// idea: define some other IObservable or subject here\n\n// update var each time OnNext is called\nvar lastResult = selectedItemOut.Subscribe(i => results = i);\n\n// just a wrapper around the results var.\nvar getLatest = new Func<int?>(() => results);\nAssert.AreEqual(null, getLatest());\n\nselectedItemOut.OnNext(4);\nAssert.AreEqual(4, getLatest());\n\nselectedItemOut.OnNext(5);\nAssert.AreEqual(5, getLatest());\n\nselectedItemOut.OnNext(6);\nselectedItemOut.OnNext(7);\nAssert.AreEqual(7, getLatest());\n\n//Need to tell the observable to stop updating the results var.\nlastResultDispose.Dispose();	0
26669581	26660682	Get string values from database without null values C#	if (myreader["category"] != DBNull.Value)\n       {\n          string sName1 = myreader.GetString("category");\n          call2.Add(sName1);\n          comboBox1.Items.Add(sName1);\n       };\n\n  if (myreader["subcategory"] != DBNull.Value)\n       {\n          string sName2 = myreader.GetString("subcategory");\n          call.Add(sName2);\n          comboBox2.Items.Add(sName2);\n       };	0
2410536	2410438	Log4Net performance	class SomeClass\n{\n    private static readonly ILog log = LogManager.GetLogger(typeof(SomeClass));\n    ...\n}	0
16683441	16683412	How to find an average date/time in the array of DateTime values	var count = dates.Count;\ndouble temp = 0D;\nfor (int i = 0; i < count; i++)\n{\n    temp += dates[i].Ticks / (double)count;\n}\nvar average = new DateTime((long)temp);	0
28835009	28832190	HtmlAgilityPack - Extract links from a specific table	var linksOnPage = from lnks in document.DocumentNode.Descendants()\n              where lnks.Name == "a" && \n                   lnks.Attributes["href"] != null && \n                   lnks.InnerText.Trim().Length > 0\n              select new\n              {\n                 Url = lnks.Attributes["href"].Value,\n                 Text = lnks.InnerText\n              };	0
11413478	11407223	Updating data into Database	private void btnUpdate_Click(object sender, EventArgs e) {\n  using (testEntities Setupctx = new testEntities()) {\n    var toBeUpdatedStart = txtStart.Text;\n    var toBeUpdatedStop = txtStop.Text;\n    shifthour updateStartShift;\n    shifthour updateStopShift;\n    updateStartShift = Setupctx.shifthours.FirstOrDefault(u => u.shiftTiming_start == toBeUpdatedStart);\n    updateStopShift = Setupctx.shifthours.FirstOrDefault(p => p.shiftTiming_stop == toBeUpdatedStop);\n    if (updateStartShift != null)\n    {\n       updateStartShift.shiftTiming_start = txtStart.Text;\n    }\n    if (updateStopShift != null)\n    {\n        updateStopShift.shiftTiming_stop = txtStop.Text;\n    }\n    Setupctx.SaveChanges();\n    txtStart.Text = "";\n    txtStop.Text = "";\n    MessageBox.Show("Shift Timing Has Been Updated.");\n  }\n}	0
13697096	13696917	redirect to default	setTimeout(function () { window.location="Default.aspx" }, 5000);	0
17269326	17259466	How to overwrite extracted zip file in C#, WinForms?	using (ZipFile zip = ZipFile.Read(pathBackup))\n        {\n            zip.ExtractAll(Environment.CurrentDirectory, ExtractExistingFileAction.OverwriteSilently);                \n        }	0
22071290	22069660	Sanitizing string before adding it to XML?	private XmlDocument CreateMessage(string dirtyInput)\n{\n    XmlDocument xd = new XmlDocument();\n    xd.LoadXml(@"<Message><Request></Request></Message>");\n    xd["Message"]["Request"].InnerText = dirtyInput;\n\n    return xd;\n}	0
28813233	28812752	Parsing a 'Full Name' string to an email address	//Assuming example input "Stephen Smith-Jones" or "Stephen Smith Jones"\n//split on spaces and hyphens\nstring[] names = FullName.Text.ToString()\n                     .Split(new string[]{" ", "-"},\n                            StringSplitOptions.RemoveEmptyEntries); //in case of extra spaces?\n\n//Stephen.SmithJones@domain.com\nvar email = String.Format("{0}.{1}{2}@domain.com",\n                          names[0],\n                          names[1],\n                          (names.Length > 2) ? names[2] : "");	0
23679101	23679052	Specify allowed enum values in a property	class Object\n{\n    private Type _value;\n\n    public Type objType{ \n\n        get{ return _value; }\n        set{\n            if(value != Type.One && value != Type.Three)\n                throw new ArgumentOutOfRangeException();\n            else\n                _value = value;\n        }\n    }\n}	0
22220552	22220551	how to add conditional formatting on cells with values greater than a specific constant value using epplus	var cellAddress = new ExcelAddress(\n                        <startingRow>, \n                        <startingcolumn>, \n                        <endingRow>, \n                        <endingColumn>);\n\nvar cf = ws.ConditionalFormatting.AddGreaterThan(cellAddress);\ncf.Formula = "0";\ncf.Style.Fill.BackgroundColor.Color = Color.LightGreen;	0
697418	697385	How to deal with delays on telnet connection programmatically?	do    \n{      \n     bytes = this.Stream.Read(readBuffer, 0, readBuffer.Length);             \n     responseData = String.Concat(responseData, System.Text.Encoding.ASCII.GetString (readBuffer, 0, bytes));       \n} while (this.Stream.DataAvailable && !responseData.Contains("\n"));	0
6981492	6981430	Remove duplicate items from dropdownlist in .net	// ******\n        // Remove Any Duplicate Vehicles\n        // ********************\n        List<Vehicle> NoDuplicatesVehicleList = ListVehicle.AllVehicles;\n        NoDuplicatesVehicleList = NoDuplicatesVehicleList.GroupBy(x => x.VehicleID).Select(x => x.First()).ToList();	0
14708202	14643966	Register a device/service with the COM UPnP lib	IUPnPRegistrar registrar = (IUPnPRegistrar)new UPnPRegistrarClass();\nregistrar.RegisterDevice(\n    File.ReadAllText("DimmerDevice-Desc.xml"),\n    "My.Class",\n    "MyInitString",\n    "MyContainerId",\n    Path.GetFullPath("."),\n    3200);	0
18228436	18228330	Split a text in Label	if(Text.text.Length > 30)\n  label1.text = string.Format("{0}...", label1.text.Substring(0, 30));	0
25844236	25844180	Start a windows service only after method is finished	private void SomeMethod()\n{\n  A();\n\n  ServiceController controller = new ServiceController("WindowsServiceName");\n  controller.Start();\n}	0
24322679	24322539	CSV write data in same line	foreach (ModelName s in m)\n  {\n      sb.Append(s.FName.ToString().Replace("\n",""));\n      sb.Append(",");\n      sb.Append(s.SName.ToString().Replace("\n",""));\n      sb.Append(","); /* I doubt you want this one */\n\n      sb.AppendLine();\n  }	0
14048396	14048364	Find / Count Redundant Records in a List<T>	var duplicates = list.GroupBy(x => new { x.Amount, x.CardNumber, x.PersonName })\n                     .Where(x => x.Count() > 1);	0
18865801	18756573	Google earth crashing in c# application	ge.OpenKmlFile()	0
30062742	30060996	Xamarin, using Geolocation from Xlabs sample	DependencyService.Register<Geolocator> ();	0
604516	604501	Generating DLL assembly dynamically at run time	using System.CodeDom.Compiler;\nusing System.Diagnostics;\nusing Microsoft.CSharp;\n\nCSharpCodeProvider codeProvider = new CSharpCodeProvider();\nICodeCompiler icc = codeProvider.CreateCompiler();\nSystem.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();\nparameters.GenerateExecutable = false;\nparameters.OutputAssembly = "AutoGen.dll";\nCompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);	0
29001728	29001462	Is it possible in c# to do math with file names that contain numbers?	var files = Directory.GetFiles(path);\n\nforeach (var f in files)\n{\n    var info = new FileInfo(f);\n\n    var name = info.Name.Split('.')[0];\n    var extension = info.Name.Split('.')[1];\n\n    int i;\n    if (int.TryParse(name, out i))\n    {\n        File.Move(info.FullName, string.Format(@"{0}\{1}.{2}", path, i + 5, extension));\n    }\n}	0
28367470	28359165	How to remove a column from excel sheet in epplus	[TestMethod]\npublic void DeleteColumn_Test()\n{\n    //http://stackoverflow.com/questions/28359165/how-to-remove-a-column-from-excel-sheet-in-epplus\n\n    var existingFile = new FileInfo(@"c:\temp\temp.xlsx");\n    if (existingFile.Exists)\n        existingFile.Delete();\n\n    //Throw in some data\n    var datatable = new DataTable("tblData");\n    datatable.Columns.Add(new DataColumn("Col1"));\n    datatable.Columns.Add(new DataColumn("Col2"));\n    datatable.Columns.Add(new DataColumn("Col3"));\n\n    for (var i = 0; i < 20; i++)\n    {\n        var row = datatable.NewRow();\n        row["Col1"] = "Col1 Row" + i;\n        row["Col2"] = "Col2 Row" + i;\n        row["Col3"] = "Col3 Row" + i;\n        datatable.Rows.Add(row);\n    }\n\n    using (var pack = new ExcelPackage(existingFile))\n    {\n\n        var ws = pack.Workbook.Worksheets.Add("Content");\n        ws.Cells.LoadFromDataTable(datatable, true);\n        ws.DeleteColumn(2);\n\n        pack.SaveAs(existingFile);\n    }\n}	0
10201322	6335732	How do I add a border to a page using iTextSharp?	public override void OnEndPage(PdfWriter writer, Document document)\n{\n    base.OnEndPage(writer, document);\n\n    var content = writer.DirectContent;\n    var pageBorderRect = new Rectangle(document.PageSize);\n\n    pageBorderRect.Left += document.LeftMargin;\n    pageBorderRect.Right -= document.RightMargin;\n    pageBorderRect.Top -= document.TopMargin;\n    pageBorderRect.Bottom += document.BottomMargin;\n\n    content.SetColorStroke(BaseColor.RED);\n    content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);\n    content.Stroke();\n}	0
19775899	19775851	Ability to find WinForm control via the Tag property	private void FindTag(Control.ControlCollection controls)\n{\n    foreach (Control c in controls)\n    {\n        if (c.Tag != null)\n        //logic\n\n       if (c.HasChildren)\n           FindTag(c.Controls); //Recursively check all children controls as well; ie groupboxes or tabpages\n    }\n}	0
29211760	29210552	GroupBy a list of tuple c#	var tmp = (from r in x select (from v in r.Value select new { r.Key, v.Item1, v.Item2}))\n  .SelectMany(a=>a).ToLookup(a=>a.Item1 , a => new { a.Key, a.Item2});\n\nvar results = (from r in tmp select new \n     StructuredLocalized{ \n       NeutralText = r.Key , \n       LocalizedTexts = r.ToDictionary(a=>a.Key, a=>a.Item2) \n } ) ;\n\n\n\n\n\nint line = 1;\n foreach(var r in results)\n {\n    Console.Write ("{0}. {1}," , line++, r.NeutralText);\n\n    int j = 0;\n    foreach(var k in r.LocalizedTexts)\n    {\n        Console.Write(" [{0}]: {1} {2}, " , j++,  k.Key, k.Value);\n    }\n    Console.WriteLine();    \n}	0
2163323	2163040	How to add item to Repeater control manually	public List<int> Data\n    {\n        get\n        {\n            if (ViewState["Data"] == null)\n            {\n                // Get your data, save it and return it.\n                var data = new List<int> { 1, 2, 3 };\n                ViewState["Data"] = data;\n                return data;\n            }\n                return (List<int>)ViewState["Data"];\n        }\n        set\n        {\n            ViewState["Data"] = value;\n        }\n    }\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if (!IsPostBack)\n        { \n            BindData(Data); \n        }\n    }\n\n    private void BindData(List<int> data)\n    {\n        _ddlOptions.DataSource = data;\n        _ddlOptions.DataBind();\n    }\n\n    protected void OnAdd(object sender, EventArgs e)\n    {\n        var existing = Data;\n\n        existing.Add(_ddlOptions.SelectedItem);                        \n        _ddlOptions.Items.RemoveAt(_ddlOptions.SelectedIndex);\n\n        Data = existing;\n        BindData(existing);\n    }	0
32322675	32322189	How to differentiate by case when sorting a DataTable?	DataTable Dt18 = new DataTable();\nDt18.Columns.Add("Dosage", typeof(int));\nDt18.Columns.Add("Drug", typeof(string));\nDt18.Rows.Add(0, "Indocin");\nDt18.Rows.Add(1, "indocin");\nDt18.Rows.Add(17, "Indocin");\nDt18.Rows.Add(2, "Hydralazine");\nDt18.Rows.Add(3, "Combivent");\nDt18.CaseSensitive = true;\nDataView view = new DataView(Dt18);\nview.Sort = "Drug asc";\nDataTable dtSorted = view.ToTable();	0
24120540	24120300	Equivalent of Left outer join in LINQ	var leftFinal =\n    from l in lefts\n    join r in rights on l equals r.Left into lrs\n    from lr in lrs.DefaultIfEmpty()\n    select new { LeftId = l.Id, RightId = ((l.Key==r.Key) ? r.Id : 0 };	0
11932001	11931905	Checking for a duplicate email	if exists(select @EmailId from Profile_Master where EmailId=@EmailId) \n    set @result=0 \nelse \nbegin\n    set @result=1 \n\n    insert into Profile_Master(FirstName,LastName,Dob,Gender,MobileNo,Country,State,EmailId,Password) \n      values (@FirstName,@LastName,@Dob,@Gender,@MobileNo,@Country,@State,@EmailId,@Password) \n    set @id=SCOPE_IDENTITY() \nend	0
18248594	18248547	Get controller and action name from within controller?	string actionName = this.ControllerContext.RouteData.Values["action"].ToString();\nstring controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();	0
4458661	4458639	Compare a text file with a pattern of text in c#?	List<string> seen = new List<string>();\n    string line = string.Empty;\n    while ((line = file.ReadLine()) != null)\n    {\n        foreach (Match match in Regex.Matches(line, @"(\w*)\.\."))\n        {\n            if (!seen.Contains(line))\n            {\n                Console.WriteLine(line);\n                seen.Add(line);\n            }\n        }\n    }	0
20575952	20575337	Specific text in txt file in array	string[] wordsArray = null;\n       string s = string.Empty;\n       string path = "file_1.txt";\n       string[] lines = System.IO.File.ReadAllLines(path);\n       foreach (string aLine in lines)\n       {\n            s = aLine.Replace("||", "|");\n            wordsArray = s.Split('|');\n            //now you have the question in wordsArray[0], and the answers in the following\n            //array cells ([1],[2], etc.)\n            //You can do what you want here, including building a 2-d array using wordsArray.\n       }	0
17386990	17386978	How to get first 3 characters of a textbox's text?	string result = textBox1.Text.Substring(0,3);	0
17820761	17817104	InvalidCastException mapping Json string onto Guid property	[Required]\n[StringLength(36)] // NO-NO!\npublic Guid AppKey { get; set; }	0
2737709	2737636	C# LINQ to XML missing space character	XDocument doc = XDocument.Parse(@"\n<Item>\n    <ItemNumber>3</ItemNumber>\n    <English> </English>\n    <Translation>Ignore this one. Do not remove.</Translation>\n</Item>", LoadOptions.PreserveWhitespace);\n\nstring X_English = (string)doc.Root.Element("English");\n\n//  X_English == " "	0
11942166	11942145	is there any way I can generate a unique number that is NOT as long as a UUID (GUID)?	do {\n  newId = generateNewId();\n} while (idExists(newId));	0
7649298	7649243	How to Update an item in a collection using and C#	subscription.First(s => s.Period == 30).Trial = "new";	0
12839022	12799448	HttpWebResponse shows junk characters in Headers C#	pwd = HttpUtility.UrlEncodeUnicode(pwd); // encode string to unicode\n\npwd = HttpUtility.UrlDecode(pwd); // decode unicode to string	0
21706668	21706366	Search with multiple parameters in SQL Server	-- Parameters to a SQL sproc\nDECLARE @CustID INT, @EmpID INT, @AppointmentID INT\n\n-- Set Parameters here for testing\n\nSELECT *\nFROM Appointment as A\nINNER JOIN Employee as E\n  ON E.EmpID = A.EmpId\nINNER JOIN Customer as C\n  ON C.CusID = A.CusID\nWHERE (@CustID IS NULL OR C.CUsID = @CustID)\nAND (@EmpID IS NULL OR E.EmpID = @EmpID)\nAND (@AppointmentID IS NULL OR A.AppID = @AppointmentID)	0
4387530	4387434	'Cropping' a list in c#	// if your list is a concrete List<T>\nif (yourList.Count > newSize)\n{\n    yourList.RemoveRange(newSize, yourList.Count - newSize);\n}\n\n// or, if your list is an IList<T> or IList but *not* a concrete List<T>\nwhile (yourList.Count > newSize)\n{\n    yourList.RemoveAt(yourList.Count - 1);\n}	0
34112603	34107325	Uploading to a Windows network share on Android device using Mono on LAN	// This is NOT best-practice code, just showing a demo of an Jcifs api call\npublic async Task getFileContents ()\n{\n    await Task.Run (() => {\n        var smbStream = new SmbFileInputStream ("smb://guest@10.10.10.5/code/test.txt");\n        byte[] b = new byte[8192];\n        int n;\n        while ((n = smbStream.Read (b)) > 0) {\n            Console.Write (Encoding.UTF8.GetString (b).ToCharArray (), 0, n);\n        }\n        Button button = FindViewById<Button> (Resource.Id.myButton);\n        RunOnUiThread(() => {\n            button.Text = Encoding.UTF8.GetString (b);\n        });\n    }\n    ).ContinueWith ((Task arg) => {\n        Console.WriteLine (arg.Status);\n        if (arg.Status == TaskStatus.Faulted)\n            Console.WriteLine (arg.Exception);\n    }\n    );\n}	0
25854110	25853853	Ordering a List<> of Objects by another Linked Object ID	public static IEnumerable<Foo> Order(IEnumerable<Foo> sequence)\n{\n    var lookup = sequence.ToLookup(foo => foo.precedingObjectId);\n\n    var current = lookup[null];\n    while (current.Any())\n    {\n        var foo = current.Single();\n        yield return foo;\n        current = lookup[foo.Id];\n    }\n}	0
4270619	4270598	Applying a filter to subsequences of a sequence using Linq	var mostRecentById = from item in list\n                     group item by item.Id into g\n                     select g.OrderByDescending(x => x.Year).First();	0
1806533	1806511	Objects that represent trees	public class BinaryTree<T> : IVisitableCollection<T>, ITree<T>\n{\n  // Methods\n  public void Add(BinaryTree<T> subtree);\n  public virtual void breadthFirstTraversal(IVisitor<T> visitor);\n  public virtual void \n         DepthFirstTraversal(OrderedVisitor<T> orderedVisitor);\n  public BinaryTree<T> GetChild(int index);\n  public bool Remove(BinaryTree<T> child);\n  public virtual void RemoveLeft();\n  public virtual void RemoveRight();\n\n  // ...\n\n  // Properties\n  public virtual T Data { get; set; }\n  public int Degree { get; }\n  public virtual int Height { get; }\n  public virtual bool IsLeafNode { get; }\n  public BinaryTree<T> this[int i] { get; }\n  public virtual BinaryTree<T> Left { get; set; }\n  public virtual BinaryTree<T> Right { get; set; }\n\n  // ...\n}	0
7595647	7594439	Session getting cleared with Authorize attribute?	public class CustomAuthorizationAttribute : AuthorizeAttribute\n{\n    public override void OnAuthorization(AuthorizationContext filterContext)\n    {\n        base.OnAuthorization(filterContext);\n        if (filterContext.Result == null)\n        {\n\n            if (filterContext.HttpContext.Session != null )\n            {\n                //add checks for your configuration\n                //add session data\n\n                // if you have a url you can use RedirectResult\n                // in this example I use RedirectToRouteResult\n\n                RouteValueDictionary rd = new RouteValueDictionary();\n                rd.Add("controller", "Account");\n                rd.Add("action", "LogOn");\n                filterContext.Result = new RedirectToRouteResult("Default", rd);\n            }\n        }\n    }\n}	0
33269164	33269109	C# - Need string in format of characters separated by one and only one comma	string test = "0,,,,,,,1,,2,3,,,,5";\nstring result = Regex.Replace(test, ",+", ", ");	0
6735587	6735530	How do you trim a string that might be null in Linq?	QuestionText = query.Element("text")!=null ? query.Element("text").Value.Trim() : string.Empty;	0
21187806	21187526	how to get a list of entities without a particular attribute in EF 5?	try this     \n\n typeof(TestContext).GetProperties().Select(n => n.PropertyType) // here we get all properties of contect class\n.Where(n => n.Name.Contais("DbSet") && n.IsGenericType) // here we select only DBSet collections\n.Select(n=>n.GetGenericArgumenrs()[0])//Here we access to TEntiy type in DbSet<TEntity> \n.Where(n => n.GetCustomAttributes(true).OfType<DoNotAudit>().FirstOrDefault()== null) // here we check for attribute existence\n .OrderBy(n=>n.Name) // Here is sorting by Name\n.Select(n => n.Name).ToList(); // here we select the names of entity classes	0
4797700	4797469	Find sum of a column after using binding source filter	inventoryDatabaseDataSet.Tables["mytable"].Compute("SUM(mycolumn)", "PurchaseId = '" + pid + "'").ToString();	0
9999542	9999413	How to force control content redraw within event handler	private delegate void InlineDelegate();\nprivate void btnLogon_Click(object sender, RoutedEventArgs e)\n{\n    lblInvalidLogon.Content = string.Empty;\n    lblInvalidLogon.Dispatcher.Invoke(new InlineDelegate(() =>\n    {\n        //\n        // Process to verify logon credentials...\n        //\n    }), System.Windows.Threading.DispatcherPriority.Background, null);\n}	0
23263635	23263539	How to pass object with a back key press	public MyObjectType SelectedItem { get; private set; }	0
16611125	16610532	Using a style from a MergedDictionary multiple times	x:Shared="False"	0
2729091	2727228	Load a Lua script into a table named after filename	lua_newtable(L);\nlua_setglobal(L,filename);\nluaL_loadfile(L,filename);\nlua_getglobal(L,filename);\nlua_setfenv(L,-2);\nlua_pcall(L,...);	0
29531365	29531058	How to use client-side cursor for SqlConnection/SqlDataReader?	DataTable dt = new DataTable();\ndt.Load(reader);\nforeach (var row in dt.Rows) { /* Your data is in row now */}	0
21403478	21402888	How to set the background color of tab panel with default css class?	.ajax__tab_xp .ajax__tab_body {font-family:verdana,tahoma,helvetica;font-size:10pt;border:1px solid #999999;border-top:0;padding:8px;background-color:#ffffff !important;}	0
26748011	26747431	How to compare strings in a case-insensitive manner in linq, when they are a property of an object	void Main()\n{\n    var firstListOfPeople = new[]\n    {\n        new Person { Name = "Rufus" },\n        new Person { Name = "Bob" },\n        new Person { Name = "steve" },\n    };\n\n    var secondListOfPeople = new[]\n    {\n        new Person { Name = "john" },\n        new Person { Name = "Bob" },\n        new Person { Name = "rufus" },\n    };\n\n    var people = firstListOfPeople.Intersect(secondListOfPeople, new PersonNameComparer());\n\n    people.Dump(); // displays the result if you are using LINQPad\n}\n\npublic class Person\n{\n    public string Name { get; set; }\n}\n\npublic class PersonNameComparer: EqualityComparer<Person>\n{\n\n    public override bool Equals(Person p1, Person p2)\n    {\n        return p1.Name.Equals(p2.Name, StringComparison.OrdinalIgnoreCase);\n    }\n\n    public override int GetHashCode(Person p)\n    {\n        return p.Name.ToLower().GetHashCode();\n    }\n}	0
8967385	8967283	Passing values from SQL to WCF	Console.WriteLine("Insert Occured, {0}",Name);	0
17903395	17902287	How to store type T	void TheirMethod<T>(string text) { }\n\nvoid MyMethod<T>(string text)\n{\n    Action action = () => TheirMethod<T>(text);\n    // you can now return the action,\n    // construct a thread with it\n    // add it to a List...\n    var thread = new Thread(new ThreadStart(action));\n    thread.Start();\n}	0
6265725	6265650	Using a LINQ Where clause to filter by data in an associated table	var activeArticles = from a in ctx.Articles\n                     join s in ctx.statuses on a.status_id equals s.id\n                     select a;	0
24742502	24742298	Not listing XML elements as array	[XmlRoot(ElementName = "WebService", DataType = "WebService", IsNullable = false)]\n[XmlInclude(typeof(NodeCreateSnapshot))]\npublic class WebServiceXmlElement\n{\n    // ...\n}	0
26049520	26049452	Saving an image from an URL to a local file in C#	using (WebClient client = new WebClient())\n        {\n            client.DownloadFile(@"http://images.craigslist.org/00o0o_kFhPDdTGf2e_600x450.jpg",                                @"c:\\Tmp\test.jpg");\n        }	0
7387387	7387256	Annual calender in asp.net page	protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)\n{\n    // Check if there is a note attached to the day (e.Day.Date) which is being \n    // rendered.\n    bool hasNote = ....;\n\n    // Style cell (which contains the date) if it has a note\n    if (hasNote)\n    {\n       e.Cell.BackColor = System.Drawing.Color.Yellow;\n    }\n}	0
33863485	33863325	ulong to hex conversion clarification	using System;\n\nnamespace ConsoleApplication1\n{\n    public class Program\n    {\n        public static void Main(string[] args)\n        {\n            var value = 12288092688749907974u;\n            var bytes = BitConverter.GetBytes(value);\n\n            Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian Yes" : "IsLittleEndian No");\n            Console.WriteLine(" Value " + BitConverter.ToString(bytes));\n\n            Array.Reverse(bytes);\n            Console.Write(BitConverter.IsLittleEndian ? "IsLittleEndian No" : "IsLittleEndian Yes");\n            Console.WriteLine(" Value " + BitConverter.ToString(bytes));\n\n            Console.Read();\n        }\n    }\n}	0
206720	206717	How do I replace multiple spaces with a single space in C#?	RegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@"[ ]{2,}", options);     \ntempo = regex.Replace(tempo, @" ");	0
14420482	14420373	Convert decimal to binary but in an 8 bit format	string result = Convert.ToString(num, 2).PadLeft(8, '0');	0
55447	54991	Generating Random Passwords	System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters	0
7644944	7644920	C# - Convert one Enum to an other	SystemPersonTitles newValue = (SystemPersonTitles)(int)PersonTitle.Mr;	0
23478248	23477781	Replace part of XML by using regex capture group	Regex regex = new Regex("<ns1:AcctId>(?<AcctId>.*?)</ns1:AcctId>");\nMatch match = regex.Match(oldXml);\n\nstring AcctId = match.Groups["AcctId"].Value;\n\nstring IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);\n\nnewXml = oldXml.Replace(AcctId, IBANizedAcctId); //should work...	0
15334249	15288292	Is there any risk associated with trustworthy database for CLR (Assembly) implementation?	USE MASTER ;\nCREATE ASYMMETRIC KEY '<youKeyName>' FROM EXECUTABLE FILE = ' <Your dll file path>'   \nCREATE LOGIN '<yourUserName> 'FROM ASYMMETRIC KEY '<yourKeyName>' ;\nGRANT EXTERNAL ACCESS ASSEMBLY TO '<yourUserName>';\nUSE '<YOUR DB NAME>'\nCREATE ASSEMBLY '<Assembly name>'from '<Your dll file path>' WITH PERMISSION_SET = EXTERNAL_ACCESS ;	0
6138388	6138364	Parse int[] from "1,2,3"	Request["ID"].Split(',').Select(x=>int.Parse(x)).ToArray();	0
22929750	22929632	Error in c# subtracting 30 days from current date ? winforms	DateTime curdate = DateTime.Now;\ncurdate = curdate.AddDays(-30); // if i give -4 instead of -30 the query will bind data\nDateTime curdate1 = DateTime.Now;\n\nvalidateDept.InitializeConnection();\nOleDbConnection connection = new OleDbConnection(validateDept.connetionString);\nOleDbDataAdapter adapter = new OleDbDataAdapter(\n      "SELECT InvoiceId, InvoiceNumber, InvoiceDate, (Select CustomerId from Customer\n      Where Customer.CustomerId=NewInvoice_1.CustomerName) AS CustomerId, (Select\n      CustomerName from Customer where Customer.CustomerId = NewInvoice_1.CustomerName)\n      AS CustomerName, DueDate, Tax, GrandTotal, CompanyId FROM NewInvoice_1 WHERE\n      InvoiceDate >= #" + curdate.ToString("dd/MMM/yyyy") + "# AND InvoiceDate <= #" +         \n      curdate1.ToString("dd/MMM/yyyy") + "# ", connection);\n\nDataSet sourceDataSet = new DataSet();\nadapter.Fill(sourceDataSet);\ngridControl1.DataSource = sourceDataSet.Tables[0];	0
10813556	10313259	sqlite bit columns return 'false' value in every case	SQLiteCommand sqlite_command = new SQLiteCommand("SELECT Cast(AdditionalServices as nvarchar(10)) as AdditionalServices, Cast(VitalObservation as nvarchar(10)) as VitalObservation from tblReadonlyPatientData where SubscriptionID = 1306", sqlite_connection);	0
22897253	22897163	Select distinct objects from a List<Object>	var distinctBeams = beams\n    .GroupBy(b => b.Elevation)\n    .Select(g => g.First())\n    .ToList();	0
22162051	22161683	How to decompress/unarchive files compressed/archived using various techniques - zip, rar, gzip, tar	System.IO.Packaging	0
667472	667412	How to call a javascript function from a control within a masterpage?	if (timeSpan.Days < 30)\n{\n //Show JQuery Dialog Here\nScriptManager.RegisterClientScriptBlock(this, typeof(Page), "showExpiration", "showjQueryDialog()", true);\n}	0
29156945	29152826	Binding Model to List nested model	//used before\n@Html.ActionLink("Export Excel", "ExportToExcel", "Grid", new { GridID = "gridsid"}, new { id = "exportExcelLink" })\n\n//switched to\n<button type="submit" id="exportLink" name="exportBtn">[Export BTN]</button>	0
9318045	9318004	How many chars one line can contain?(C# printing text)	//This gives you a rectangle object with a length and width.\nRectangle bounds = e.MarginBounds;	0
25360573	25360488	Call a method that has already been called in a new thread	private void TryMultimpleImportExcel()\n{\n    Boolean canTryAgain = true;\n\n    while( canTryAgain)\n    {\n        try\n        {\n            ImportExcel();\n            canTryAgain = false;\n        }\n        catch(NotCriticalTryAgainException exc)\n        {\n            Logger.Log(exc);\n        }\n        catch(Exception critExc)\n        {\n            canTryAgain = false;\n        }\n    }\n}\n\n\n    // ...\n    ThreadStart theprogress = new ThreadStart(TryMultimpleImportExcel);\n    // ..\n    startprogress.Start();	0
22478699	22478029	how to get numeric position of an enum in its definition list	public static int GetStatusID(this StatusFlags flag)\n{\n    return Array.IndexOf(Enum.GetValues(typeof(StatusFlags)), flag);\n}	0
12742760	12742662	How to capture the Right variable in a Thread	int atPDFNumber = 0; \nforeach (var z in q)\n{\n    atPDFNumber++; \n    convertToImage(z.FullName);\n    int currentValue = atPDFNumber;\n    txtboxtest.BeginInvoke(((Action)(() => txtboxtest.Text += currentValue.ToString())));\n}	0
1034073	1034061	C# string split	var str = "google.com 220 USD 3d 19h";\nvar domain = str.Split(' ')[0];           // google.com\nvar tld = domain.Substring(domain.IndexOf('.')) // .com	0
29376610	29376344	Replace all elements name and attrbiutes that contains hyphens with underscore	var doc = XDocument.Parse(xml);\n\n        foreach (var element in doc.Descendants())\n        {\n            if (element.Name.LocalName.Contains("-"))\n            {\n                var newName = element.Name.LocalName.Replace('-', '_');\n                element.Name = element.Name.Namespace + newName;\n            }\n            var list = element.Attributes().ToList();\n            for (int i = 0; i < list.Count; i++)\n            {\n                var attr = list[i];\n                if (attr.Name.LocalName.Contains("-"))\n                {\n                    XAttribute newAttr = new XAttribute(attr.Name.Namespace + attr.Name.LocalName.Replace('-', '_'), attr.Value);\n                    list[i] = newAttr;\n                }\n            }\n            element.ReplaceAttributes(list);\n        }	0
21390475	21390214	How to check if string is xxxxx.xxxx format in c#?	\w{5}\x2E\w{4}\n\n//      Alphanumeric, exactly 5 repetitions\n//      Hex 2E (.)\n//      Alphanumeric, exactly 4 repetitions	0
10218830	10218700	400 bad request but cant find the issue	sb1.AppendLine("</Message>");\nsb1.AppendLine("<GroupMessage>" + this.textBox22.Text + "</GroupMessage>");\nsb1.AppendLine("</Message>");	0
11740536	11740211	How to access a property from another class / control, from within a custom class?	private string direction;\n\npublic string Direction\n{\n    get { return direction; }\n    set { direction = value; }\n}	0
10501797	10501738	How to send class equals implementation to client using a WCF Web Server	equals()	0
19641229	19641134	How to access a certain group of bytes in a MemoryStream?	byte[] GetLast5BytesRead(MemoryStream stream)\n{\n    // TODO: Validation that stream.Position is at least 5\n    byte[] ret = new byte[5];\n    stream.Position -= 5;\n    // TODO: Consider throwing an exception if this doesn't return 5\n    Stream.Read(ret, 0, 5);\n    return ret;\n}	0
17020048	17018028	Generate unique 16 character strings across multiple runs	//parse out hex digits in calling code\nstatic long NextHash(HashSet<long> hashes, int count)\n{\n    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();\n    long l = BitConverter.ToInt64(md5.ComputeHash(IntToArray(count)));\n    if(!hashes.Contains(l)){\n        hashes.Add(l);\n        return l;\n    } else return -1; //check this in calling code for failure\n}\nstatic byte[] IntToArray(int i)\n{\n    byte[] bytes = new byte[4];\n    for(int j=0;j<4;j++){\n    bytes[j] = (byte)i;\n    i>>=8;    \n    }\n}	0
9842967	9842916	How to round off decimals from string input and convert to int	int rounded;\nstring input = "2.53";\ndecimal startMiles;\n\nif (Decimal.TryParse(input, out startMiles))\n{     \n    rounded = Convert.ToInt32(startMiles);\n\n    // here is rounded == 3\n}	0
12723789	12723719	Cannot access WCF url hosted as a windows service	protected override void OnStart(string[] args)\n{\n    host = new ServiceHost(typeof(TestWCF.TestService));\n    host.Open(); // :-)\n}	0
20240050	20239869	UpdateOnSubmit from dbml?	Action action = nc.Actions.FristOrDefault(e=>e.Name="1234");\n\nif(action!=null)\n{\n  action.SomeOtherProperty="NewValue";\n}\n\nnc.SubmitChanges();	0
34293152	34292618	How to wait for all threads created within a method	QueryResultRows<PO> pos = Db.SQL<PO>("SELECT po FROM PO po");\nList<Task>tasks = new List<Task>();\nforeach (var po in pos)\n{\n    DbSession dbSession = new DbSession();\n    var task = Task.Run(()=>\n    dbSession.RunSync(() =>\n    {\n        // Do some stuff in the Starcounter database\n    }));\n    tasks.Add(Task);\n}\nTask.WaitAll(tasks.ToArray());	0
4498728	4498236	Referencing a static class from an array?	static public class ObjectMapping\n{\n    static Dictionary<int, object> dictionary = new Dictionary<int, object>();\n\n    static public object GetObjectForNumber(int x)\n    {\n        object o;\n        if (!dictionary.ContainsKey(x))\n        {\n            o = CreateObjectForNumberTheFirstTime(x);\n            dictionary.Add(x, o);\n            return o;\n        }\n        return dictionary[x];\n    }\n}	0
30758579	30758380	How to read Excel in Mac using C#	FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);\n\n//1. Reading from a binary Excel file ('97-2003 format; *.xls)\nIExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);\n\n//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)\nIExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);\n\n//3. DataSet - The result of each spreadsheet will be created in the result.Tables\nDataSet result = excelReader.AsDataSet();\n\n//4. DataSet - Create column names from first row\nexcelReader.IsFirstRowAsColumnNames = true;\nDataSet result = excelReader.AsDataSet();\n\n//5. Data Reader methods\nwhile (excelReader.Read())\n{\n    //excelReader.GetInt32(0);\n}\n\n//6. Free resources (IExcelDataReader is IDisposable)\nexcelReader.Close();	0
16414225	16414187	Numbers input in C#	string value="99999";\nstring concat= "PM" + value.PadLeft(10, '0');	0
12061924	12061872	Generating key-value to JToken	JObject jObj = new JObject();\njObj["1_type"] = "sound";\njObj["1url"] = "http://example.com/sound.mp3";\njObj["2_type"] = "url";\njObj["2url"] = "http://example.com";\nvar jsonString = jObj.ToString();	0
7747550	7747381	C# How to do WebBrowserDocumentComplete in a foreach loop	static AutoResetEvent autoEvent = new AutoResetEvent(false);\n\n\nwebBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); \nforeach(string oneWebsite in ALLWebSites) \n{ \nwebBrowser1.Navigate(oneWebsite); \nautoEvent.WaitOne(new TimeSpan(0, 1, 0), false))\n}  \n\nprivate void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)     \n{ \n//do work \nautoEvent.Set();\n}	0
2483164	2296625	ToolStripMenuItem not closing when a child ToolStripMenuItem is Clicked in a C# WinForm	this.menuItem.DropDown.Closing += new ToolStripDropDownClosingEventHandler(DropDown_Closing); \n\nvoid DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)\n            {\n                if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)\n                {\n                    e.Cancel = true;\n                    ((ToolStripDropDownMenu) sender).Invalidate();\n                } \n            }	0
15405692	15403231	GridView Delete Row	else if (e.CommandName == "Delete")\n    {     \n        int index = Convert.ToInt32(e.CommandArgument);\n        GridView1.DeleteRow(index);\n        ((DataTable)ViewState["DataTable"]).Rows[index].Delete();\n        ((DataTable)ViewState["DataTable"]).AcceptChanges();\n        GridView1.DataSource = (DataTable)ViewState["Data"];\n        GridView1.DataBind();\n    }	0
11790497	11790456	How would I add a WCF service to an existing winforms application?	using System;\nusing System.ServiceModel;\nusing System.ServiceProcess;\nusing QuickReturns.StockTrading.ExchangeService;\n\nnamespace QuickReturns.StockTrading.ExchangeService.Hosts\n{\n    public partial class ExchangeWindowsService : ServiceBase\n    {\n        ServiceHost host;\n\n        public ExchangeWindowsService()\n        {\n            InitializeComponent();\n        }\n\n        protected override void OnStart(string[] args)\n        {\n            Type serviceType = typeof(TradeService);\n            host = new ServiceHost(serviceType);\n            host.Open();\n        }\n\n        protected override void OnStop()\n        {\n            if(host != null)\n               host.Close();\n        }\n    }\n}	0
34312217	34311235	ComboBox binded to observable collection how to add 1 extra value	ObservableCollection<string> myCollection;\nObservableCollection<string> MyCollectionViewProp\n{\n    get\n    {\n        var tempCollection = new ObservableCollection<string>(myCollection);\n        tempCollection.Add("Extra element");\n        return tempCollection;\n    }\n}	0
26458369	26457805	How can I return an int value from a SQLite query?	latCount = db.ExecuteScalar<int>(sql);	0
28909097	28908676	how to prevent double post on click, when it takes long time to save to db?	[HttpPost]\n[ValidateAntiForgeryToken]\n[SessionStateActionFilter]\npublic ActionResult Edit(MonkeyJar voodooMonkey)\n{\n    //Prevent double-submit\n    if (Session.IsEditActive)\n    {\n        //TODO: determine if you want to show an error, or just ignore the request\n    }\n\n    Session.IsEditActive = true;\n\n    try\n    {\n        if (!this.service.EditMonkey(voodooMonkey))\n        {\n            //I'm thinking you need this line here in case the Redirect does the Thread.Abort() before the finally gets called. (Is that possible? Too lazy to test. :) Probably a race condition--I'd keep it for a guaruntee)\n            Session.IsEditActive = false;\n            return RedirectToAction("Edit",voodooMonkey);\n        }\n    }\n    finally\n    {\n        //Ensure that we re-enable edits, even on errors.\n        Session.IsEditActive = false;\n    }\n\n    return RedirectToAction("Index");\n}	0
18331882	18331769	How to change the label at the time of radio button selection is changed using asp.net?	int i = RbList.SelectedIndex;\nif (i == 0)\n   {\nlbltest.Text = "You have click on male";\n    }\nelse if (i == 1)\n{ lbltest.Text = "You have click on female"; }	0
14454720	14454463	Hooking into SMTP client events	String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + GetFullErrorMessage(x);\n\n.\n.\n.\n\nprivate string GetFullErrorMessage(Exception e)\n    {\n        string strErrorMessage = "";\n        Exception excpCurrentException = e;\n\n        while (excpCurrentException != null)\n        {\n            strErrorMessage += "\"" + excpCurrentException.Message + "\"";\n            excpCurrentException = excpCurrentException.InnerException;\n            if (excpCurrentException != null)\n            {\n                strErrorMessage += "->";\n            }\n        }\n\n        strErrorMessage = strErrorMessage.Replace("\n", "");\n\n        return strErrorMessage;\n    }	0
3064205	3064074	how to convert windows forms browser control's document object to mshtml.IHTMLDocument2	MSHTML.IHTMLDocument2 currentDoc =\n    (MSHTML.IHTMLDocument2)webBrowser1.Document.DomDocument;	0
27572191	27572104	Retain 0 in front of a number	string str = Console.ReadLine();\n\nstr = Regex.Replace(\n        str,\n        @"\d+",\n        m => (Double.Parse(m.Groups[0].Value) + 1).ToString().PadLeft(m.Groups[0].Value.Length, '0')\n        );	0
4261430	4261264	Extract 10 digits after decimal point and apply rounding up to 3 postions	Math.Ceiling(myNumber*1000)/1000;	0
5612665	5612557	Gridview paging	Gridview1.PagerSettings.Mode = PagerButtons.NextPreviousFirstLast\nGridview1.PagerSettings.NextPageText = "Next"\nGridview1.PagerSettings.PreviousPageText = "Prev"	0
6958094	6958018	indexof function for a custom list	var someName = "name_i_want_to_find";\nvar myItems = Test.FindAll(x => x.Name == someName);\n\nforeach (var item in myItems)\n    item.FieldToChange = "someNewValue";	0
2677298	2677278	WPF - How do I use the UserControl with a dependency property and view model?	public static readonly DependencyProperty Date =\n  DependencyProperty.Register("ReturnDate", typeof(DateTime), typeof(DatePicker),\n  new FrameworkPropertyMetadata(\n        DateTime.Now, \n        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,\n        new PropertyChangedCallback(dateChanged)));\n\npublic DateTime ReturnDate\n {\n    get { return Convert.ToDateTime(GetValue(Date)); }\n    set\n    {\n        SetDropDowns(value);\n        SetValue(Date, value);\n    }\n }\n\nprivate static void dateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n  DatePicker instance = d as DatePicker;\n  instance.SetDropDowns((DateTime)e.NewValue);\n}	0
4325364	4325273	nested property listbox	public partial class User {\n    public string ProductName { get { return this.Product.ProductName; } }\n}	0
8432999	8224229	Issue parsing arrays to json	int[] temp = new int[j.persons.Length];\nfor(var i = 0;i < j.persons.Length;i++){\n    temp[i] = (j.persons[i] is string)?Int32.Parse(j.persons[i]):(int)j.persons[i];\n}\nj.persons = temp;	0
25266805	25266626	Unpivot on a column that has dash on it	INNER JOIN REC_ITEM AS P\n    on replace(p.REC_ITEM_NAME_A, ' ', '_')  = upvt.ItemDesc	0
2376102	2374689	Automapper: Update property values without creating a new object	Mapper.Map<Source, Destination>(source, destination);	0
29169459	29168218	How to customize toolstrip button highlight color on mouse over	class MyRenderer : ToolStripProfessionalRenderer\n{\n    protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)\n    {\n        if (!e.Item.Selected)\n        {\n            base.OnRenderButtonBackground(e);\n        }\n        else\n        {\n            Rectangle rectangle = new Rectangle(0, 0, e.Item.Size.Width - 1, e.Item.Size.Height - 1);\n            e.Graphics.FillRectangle(Brushes.Green, rectangle);\n            e.Graphics.DrawRectangle(Pens.Olive, rectangle);\n        }\n    }\n}	0
25749297	25749046	Prevent WindowsService exiting	OnStart()\n{\n  while(!serviceNotStopped)\n  {\n   <do stuff, create threads >\n    <Sleep if required>\n  }\n\n <stop signal for all child thread if any >\n}\n\n\n\n\n OnStop()\n {\n  serviceNotStopped = true;\n }	0
25739828	25737537	Logging debug statements from multiple requests in parallel using log4net	protected void Application_BeginRequest(object sender, EventArgs e)\n{\n    StringBuilder sb = new StringBuilder();\n    HttpContext.Current.Items["DebugLog"] = sb;\n    Logger.LogMemory("Timestamp::" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));\n}\n\nprotected void Application_EndRequest(object sender, EventArgs e)\n{\n    Logger.Log(((StringBuilder)HttpContext.Current.Items["DebugLog"]).ToString());\n}\n\nclass Logger\n{\n    public static void Log(string message)\n    {\n        //Log here\n    }\n\n    public static void LogMemory(string message)\n    {\n        ((StringBuilder)HttpContext.Current.Items["DebugLog"]).Append(message);\n    }\n}\n\nclass A: Logger\n{\n    public void SomeMethod()\n    {\n        LogMemory("some message for logging");\n    }\n}	0
24409722	24409327	Draw square with center point and size	public void DrawRectangle(Pen pen, int xCenter, int yCenter, int width, int height)\n{\n    //Find the x-coordinate of the upper-left corner of the rectangle to draw.\n    int x = xCenter - width / 2;\n\n    //Find y-coordinate of the upper-left corner of the rectangle to draw. \n    int y = yCenter - height / 2;\n\n    Graphics.DrawRectangle(pen, x, y, width, height);\n}	0
34120642	34119709	Store SortExpression and SortDirection from GridView	// Set\n    Session["SortExpression"] = "Fname";\n    Session["SortDirection"] = (int)SortDirection.Ascending;\n\n   // Retrieve\n   SortDirection sortDir =     \n        (SortDirection)Enum.ToObject(typeof(SortDirection),  \n         (int)Session["SortDirection"]);\n   string sortExpression = Session["SortField"].ToString();	0
1208780	1201162	Deserializing xml with namespace prefixes that are undefined	// note this "XmlIncludeAttribute" references the derived type.\n// note that in .NET they are in the same namespace, but in XML they are in different namespaces.\n[System.Xml.Serialization.XmlIncludeAttribute(typeof(DerivedType))]\n[System.SerializableAttribute()]\n[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://BaseNameSpace")]\n[System.Xml.Serialization.XmlRootAttribute(Namespace="http://BaseNameSpace", IsNullable=true)]\npublic partial class MyBaseType : object\n{\n...\n}\n\n/// <remarks/>\n[System.SerializableAttribute()]\n[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://DerivedNameSpace")]\n[System.Xml.Serialization.XmlRootAttribute(Namespace="http://DerivedNameSpace", IsNullable=true)]\npublic partial class DerivedType: MyBaseType \n{\n...\n}	0
25912684	25912530	C#_WCF Xml Serialization	new StreamWriter("your-file-path", **true**);	0
29852461	29778670	Why does the batch file not copy files when invoked from Windows Forms app but it works from Console app?	RedirectStandardInput = true	0
8562800	8326996	Time increases to update private Observable Collection with each refresh	foreach (XViewModel m in _xCollection)\n                    {\n                        m.Cleanup();\n\n                     }	0
14937804	14937705	Issue regarding add html data to web browser control repeatedly	webBrowser1.DocumentText +=	0
3387876	3387873	How to round up a number	float num = (float)Math.Ceiling(x/y);	0
15709098	15707437	Consider using a DataContractResolver serialization error	public EventRepository()\n    {\n        HeronEntities context = new HeronEntities();\n        context.Configuration.LazyLoadingEnabled = false;\n        context.Configuration.ProxyCreationEnabled = false;\n        events = context.Events.ToList();\n    }	0
9058763	9052877	How to select and unselect the row in the GridView without having select button?	if (e.row.RowType == DataControlRowType.DataRow) { \n        e.row.Attributes["onmouseover"] =  \n           "this.style.cursor='hand';"; \n        e.row.Attributes["onmouseout"] =  \n           "this.style.textDecoration='none';"; \n        // Set the last parameter to True \n        // to register for event validation. \n        e.row.Attributes["onclick"] =  \n         ClientScript.GetPostBackClientHyperlink(CustomerGridView,  \n            "Select$" + row.RowIndex, true); \n    }	0
4949628	4949552	How to create recurring calendar events?	calendar entries table  <--->  link table  <--->  repeat rules table	0
11736207	11736157	Create a .txt file with header	Boolean writeHeader = (!File.Exists(fileName));\n\nusing (StreamWriter file = new StreamWriter(fileName, true))\n{\n    if (writeHeader)\n    {\n       file.WriteLine(headerLine);\n    }\n\n    file.WriteLine(line);\n}	0
8617494	8617456	How to get item from dictionary by value of property	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\ninternal class User\n    {\n        public string ID { get; set; }\n\n        public string Name { get; set; }\n    }\n\n    internal class Program\n    {\n        private static void Main(string[] args)\n        {\n            Dictionary<string, User> dic = new Dictionary<string, User>();\n            dic.Add("1", new User { ID = "id1", Name = "name1" });\n            dic.Add("2", new User { ID = "id2", Name = "name2" });\n            dic.Add("3", new User { ID = "id3", Name = "name3" });\n\n            User user = dic.Where(z => z.Value.ID == "id2").FirstOrDefault().Value;\n\n            Console.ReadKey();\n        }\n    }	0
1149255	1149243	C# 2.0 generics: How to create an Action object with zero parameters	BeginInvoke(new MethodInvoker(delegate()\n{\n    someCombobox.Text = "x";\n}));	0
21410315	21408611	Not able to to make panorama item visible in code behind in wp8	if (App.ViewModel.EnterpriseAppList.Count == 0)\n    {\n        int index1 = panorama.Items.IndexOf(enterpriseApps);\n        panorama.Items.RemoveAt(index1);\n        panorama.Items.Insert(index1, enterpriseApps);\n        enterpriseApps.Visibility = Visibility.Visible;\n\n        if (App.ViewModel.UATAppList.Count == 0)\n        {\n            int index2 = panorama.Items.IndexOf(uatApps);\n            panorama.Items.RemoveAt(index2);\n            panorama.Items.Insert(index2, uatApps);\n            uatApps.Visibility = Visibility.Visible;\n        }\n\n        if (App.ViewModel.DemoAppList.Count == 0)\n        {\n            int index3 = panorama.Items.IndexOf(demoApps);\n            panorama.Items.RemoveAt(index3);\n            panorama.Items.Insert(index3, demoApps);\n           demoApps.Visibility = Visibility.Visible;\n        }\n   }	0
17378561	17378329	How to select CompanyName and number of its products?	from s in db.Suppliers\njoin p in db.Products\n   on s.SupplierID equals p.SupplierID into g\nselect new {\n   s.CompanyName,\n   ProductsCount = g.Count()\n}	0
21875656	21851225	Adding a tool window to an exisiting VS extension package - FindToolWindow fails	Content = new System.Windows.Controls.UserControl();	0
29572002	29562659	How to handle WNS push notifications in Windows Phone 8.1 -silverlight	ToastNotificationFactory's\nClear and Remove	0
4158742	4158377	From C# - Is there a way to determine if a swf is AVM1 or AVM2?	// Bytes from start of file: Signature + Version + FileLength + FrameSize + FrameRate + FrameCount + FileAttributes Header \n3 + 1 + 4 + (ceil(((swf[8] >> 3) * 4 - 3) / 8) + 1) + 2 + 2 + 2	0
2406758	2406720	Paint on panel allowing auto scroll	private void panel1_Paint(object sender, PaintEventArgs e) {\n  e.Graphics.TranslateTransform(panel1.AutoScrollPosition.X, panel1.AutoScrollPosition.Y);\n  // etc\n  //...\n}	0
6306256	6306168	How to Sleep a thread until callback for asynchronous function is received?	class AsyncDemo\n{\n    AutoResetEvent stopWaitHandle = new AutoResetEvent(false);\n    public void SomeFunction()\n    {    \n        Stop();\n        stopWaitHandle.WaitOne(); // wait for callback    \n        Start();\n    }\n    private void Start()\n    {\n        // do something\n    }\n    private void Stop()\n    {\n        // This task simulates an asynchronous call that will invoke\n        // Stop_Callback upon completion. In real code you will probably\n        // have something like this instead:\n        //\n        //     someObject.DoSomethingAsync("input", Stop_Callback);\n        //\n        new Task(() =>\n            {\n                Thread.Sleep(500);\n                Stop_Callback(); // invoke the callback\n            }).Start();\n    }\n\n    private void Stop_Callback()\n    {\n        // signal the wait handle\n        stopWaitHandle.Set();\n    }\n\n}	0
11197775	11195753	How can I send a period with the Sendkeys.SendWait() function?	System.Windows.Forms.SendKeys.SendWait(Keys.OEMPeriod);	0
11421817	11419932	Increase selected ListViewItem height using converter	Mode=OneTime	0
34059808	34059656	String was not recognized as a valid DateTime.	foreach (DataRow row in ds.Tables[0].Rows)\n{\n    DateTime effectiveDateFrom;\n    DateTime effectiveDateTo;\n\n    if (!DateTime.TryParse(row["Effect_Date_From"], out effectiveDateFrom)\n        effectiveDateFrom = DateTime.MinValue;\n\n    if (!DateTime.TryParse(row["Effect_Date_To"], out effectiveDateTo)\n        effectiveDateTo = DateTime.MinValue;\n\n    row["Effective_Period"] = effectiveDateFrom.ToString("dd/MM/yyyy") + " - " +  effectiveDateTo.ToString("dd/MM/yyyy");\n}	0
8722125	8722034	Literal does not match format string	myDate.ToString("dd-MMM-yy").ToUpper()	0
7047572	7047012	How to call picturebox_Paint function from elsewhere	if (sw == 0) pictureBox1.Invalidate();	0
22483318	22483213	Create a Func<> with Roslyn	var code = @"Func<int, int> doStuffToInt = i =>\n{\n   var result = i;\n   for (var y = i; y <= i * 2; y++)\n   {\n      result += y;\n   }\n   return result;\n};\ndoStuffToInt"; // This is effectively the return statement for the script...	0
20243973	20242896	Data type mismatch in criteria expression in C# with MS Access?	OleDbCommand top = new OleDbCommand(\n        "INSERT INTO test_top (" +\n                "InvoiceNumber,Terms,[InvoiceDate],OurQuote," +\n                "SalesPerson,CustomerName,OrderNumber," +\n                "InvoiceAddress,DeliveryAddress,InclusiveStatus," +\n                "Price,Tax,GrandTotal" +\n            ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", conn);\ntop.Parameters.AddWithValue("?", invoicenumber);\ntop.Parameters.AddWithValue("?", terms);\ntop.Parameters.AddWithValue("?", date);\ntop.Parameters.AddWithValue("?", ourquote);\ntop.Parameters.AddWithValue("?", salesperson);\ntop.Parameters.AddWithValue("?", customername);\ntop.Parameters.AddWithValue("?", oderno);\ntop.Parameters.AddWithValue("?", invoiceaddress);\ntop.Parameters.AddWithValue("?", deliveryaddress);\ntop.Parameters.AddWithValue("?", inclusive);\ntop.Parameters.AddWithValue("?", Price);\ntop.Parameters.AddWithValue("?", tax);\ntop.Parameters.AddWithValue("?", grandtotal);\ntop.ExecuteNonQuery();	0
18125338	18125147	How to programmatically add a row to a datagridview when it is data-bound?	DataTAble dt = myDataGridView.DataSource as DataTAble;\n//Create the new row\nDataRow row = dt.NewRow();\n\n//Populate the row with data\n\n//Add the row to data table\ndt .Rows.Add(row);	0
8313495	8287379	How to paint certain areas of a Model3DGroup in a different color and how to add Visual shapes on Model3DGroup	Material material = new DiffuseMaterial(\n        new SolidColorBrush(Colors.DarkKhaki)); //Set color here\n    GeometryModel3D model = new GeometryModel3D(\n        mesh, material);	0
21159274	21159190	Substring or split word in clamp	using System.Text.RegularExpression;\n...\nstring result = Regex.Match(s, @"\((.*?)\)").Groups[1].Value;	0
2883204	2876971	Winforms MaskedTextBox - Reformatting pasted text to match mask	class MyMaskedTextbox : MaskedTextBox\n        {\n            const int WM_PASTE = 0x0302;\n\n            protected override void WndProc(ref Message m)\n            {\n                switch (m.Msg)\n                {\n                    case WM_PASTE:\n                        if (Clipboard.ContainsText())\n                        {\n                            string text = Clipboard.GetText();\n                            text = text.Replace(' ', '-');\n//put your processing here\n                            Clipboard.SetText(text);\n                        }\n                        break;\n                }\n                base.WndProc(ref m);\n            }\n        }	0
2305152	2304850	How to refer to a WinForms label from a class	public class AnyCLass\n   {\n       public string Message{get; set;}\n       // any other methods or properties in class ...\n       // note thatin any method which you change the Message content it should be \n       // used and if you do not call the method which change the Message value ,\n       // you have a string.Empty value\n       // to test this change the Message Value in Constructor like below\n\n       public AnyClass()\n       {\n          this.Message = "You have to change the value somewhere which call with user";\n       }\n   }\n\n   public partial class Form1.cs\n   {\n       AnyClass instance = new AnyClass();\n       Label1.Text = instance.Message;\n   }	0
3177021	3177009	How can I get an XML attribute?	var elem = XElement.Parse(str);\nvar attr = elem.Element("span").Attribute("style").Value;	0
13780007	13779663	Access PDF's script variables	onMessage()	0
20505981	20505914	Escape Special Character in Regex	string pattern = Regex.Escape("[") + "(.*?)]"; \nstring input = "The animal [what kind?] was visible [by whom?] from the window.";\n\nMatchCollection matches = Regex.Matches(input, pattern);\nint commentNumber = 0;\nConsole.WriteLine("{0} produces the following matches:", pattern);\nforeach (Match match in matches)\n   Console.WriteLine("   {0}: {1}", ++commentNumber, match.Value);  \n\n// This example displays the following output: \n//       \[(.*?)] produces the following matches: \n//          1: [what kind?] \n//          2: [by whom?]	0
8841281	8841063	How can I make a scrollable list of textboxes?	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        flowLayoutPanel1.Controls.Clear();\n\n        if (comboBox1.SelectedIndex == -1)\n            return;\n\n        int numberOfTextBoxes = int.Parse(comboBox1.SelectedItem.ToString());\n        for (int i = 0; i < numberOfTextBoxes; ++i)\n            flowLayoutPanel1.Controls.Add(new TextBox());\n    }	0
27120639	27120505	How to add a .js into a file in c#	string folderName = @"C:\Test";\n\nif (!Directory.Exists(folderName))\n{\n    Directory.CreateDirectory(folderName);\n}\n\nstring readMeFileName = Path.Combine(folderName, "ReadMe.txt");\nstring text = "This is used Test.";\nFile.WriteAllText(readMeFileName , text);\n\nstring jsFileName = Path.Combine(folderName, "Test.JS");\nFile.Copy("Test.js", jsFileName);	0
14938493	14938391	Delete listbox item that using DataSource that come from mdb(MS ACCESS)	MessageBox.Show(ListBox1.SelectedItem); //Check whether the Selected Item Rendered or NOT\n\nOleDbCommand cmd = new OleDbCommand("DELETE FROM ClientListing WHERE PCNO = " + listBox1.SelectedItem + "", GetConnection());\ncmd.ExecuteNonQuery() // it Executes the query...\n_pcno.Remove(selectedPCNo);	0
26859572	26857144	How can I open a file I've added to my Windows Store App project programatically?	StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///PlatypusTut.pdf"));\nawait Launcher.LaunchFileAsync(file);	0
10922380	10922163	C# How to make synchronous method waiting for events to fire?	var wait = new ManualResetEvent(false); \n    var handler = new EventHandler((o, e) => wait.Set()); \n    MyAsyncMethod(data, handler); // so it started and will fire handler soon \n    wait.WaitOne();	0
6046083	6035960	how to show different pop up window based on selected tab	OnClick()\n{\n  if (this.tabControl.SelectedTab == this.secondTab)\n  {\n    // Show different popup here\n  }\n  else\n  {\n    // Show common popup here\n  }\n}	0
5621918	5621899	Reading specific content from a web page?	HtmlDocument doc = new HtmlDocument();\n// replace with your own content\ndoc.Load("file.htm");\nforeach(HtmlNode meta in doc.DocumentElement.SelectNodes("/meta[@name='description'"])\n{\n    HtmlAttribute att = meta["content"];\n    Consol.WriteLine( att.Value );\n}	0
15606052	15605483	PInvoke struct with array of unspecified length	[StructLayout(LayoutKind.Sequential)]\npublic struct Info : IDisposable\n{\n    private IntPtr buf;\n    private int bufLen;\n\n    public Info(byte[] buf) : this() {\n        this.buf = Marshal.AllocHGlobal(buf.Length);\n        Marshal.Copy(buf, 0, this.buf, buf.Length);\n        this.bufLen = buf.Length;\n    }\n\n    public void Dispose() {\n        if (buf != IntPtr.Zero) {\n            Marshal.FreeHGlobal(buf);\n            buf= IntPtr.Zero;\n        }\n    }\n}	0
12186111	12185920	Access to the path is denied with the correct app.manifest settings	string path = "E://yo";                                \nfor (int i = 0; i < filePaths.Length; i++) \n{ \n     File.Move(filePaths[i], Path.Combine(path, Path.GetFileName(filePaths[i])); \n}	0
33884753	33851004	How can I remove the default "Paste" context menu entry of a TextBox control in a Windows 10 UWP app?	XAML:\n<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">\n        <TextBox x:Name="textBox" Text="test" Height="80" Width="100"  ContextMenuOpening="TextBox_ContextMenuOpening" />\n</Grid>\n\nC#:\n private void TextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)\n {\n       e.Handled = true;\n }	0
25717647	25717579	Set Statistics Time On retrieve total of elapsed time	//Import \nusing System.Diagnostics;\n\n//in your app\nStopwatch sw= new Stopwatch();\n// initialize your connection and your sql command with stored procedure \nws.Start();\nYourSQLCommand.ExecuteNoneQuery()\nws.Stop();\nDebug.Write("Time elapsed: {0}",\n    ws.Elapsed);	0
23268282	23252709	Read PKCS#7 from ASN1 with PasswordRecipientInfo	var bs = new MemoryStream();\n            var constructeddata = new DerSequenceGenerator(bs);\n            constructeddata.AddObject(new DerObjectIdentifier("1.2.840.1.113549.1.7.3"));\n            constructeddata.AddObject(new DerTaggedObject(true, 0, ed));\n            //constructeddata.AddObject(ed.ToAsn1Object());\n            constructeddata.Close();\n\n            var derdata = bs.ToArray();\n\n\n            var cms = new CmsEnvelopedData(derdata);	0
1860744	1849214	Render Empty XML Elements as Parent Elements	public class FullEndingXmlTextWriter : XmlTextWriter\n{\n    public FullEndingXmlTextWriter(TextWriter w)\n        : base(w)\n    {\n    }\n\n    public FullEndingXmlTextWriter(Stream w, Encoding encoding)\n        : base(w, encoding)\n    {\n    }\n\n    public FullEndingXmlTextWriter(string fileName, Encoding encoding)\n        : base(fileName, encoding)\n    {\n    }\n\n    public override void WriteEndElement()\n    {\n        this.WriteFullEndElement();\n    }\n}	0
21338074	21337123	Read and Store Bytes from Serial Port	SerialPort comport = new SerialPort("COM1");\ncomport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);\n\nprivate void port_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n    // Shortened and error checking removed for brevity...\n    if (!comport.IsOpen) return;\n    int bytes = comport.BytesToRead;\n    byte[] buffer = new byte[bytes];\n    comport.Read(buffer, 0, bytes);\n    HandleSerialData(buffer);\n}\n\n//private void ReadStoreArray(byte[] respBuffer)\nprivate void HandleSerialData(byte[] respBuffer)\n{\n   //I want to take what is in the buffer and combine it with another array\n   byte [] AddOn = {0x01, 0x02}\n   byte [] Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};\n}	0
19690321	19688601	Stuck with Angularjs	public JsonResult Index()\n{\n    var cards = ml.getSortedDeck(); \n    return Json(cards, JsonRequestBehavior.AllowGet);\n}	0
392800	392787	problem with splash screen - C# - VS2005	Application.Run(splash)	0
17427080	17426799	Replacing &nbsp; space character from web page in code behind	String s = Lbl1.InnerHtml.Replace("&nbsp;&nbsp;", "/"); //c#	0
19659494	19657027	Work on multiple windows of IE simultaneously using WatiN	var firstBrowser = new IE();\nvar secondBrowser = new IE();\nfirstBrowser.GoTo("www.google.com");\nsecondBrowser.GoTo("www.cnn.com");	0
2685002	2684918	DAL, Session, Cache architecture	T GetCached<T>(string cacheKey, Func<T> getDirect) {\n    object value = HttpContext.Current.Cache.Item(cacheKey);\n    if(value == null) {\n        value = getDirect();\n        HttpContext.Current.Cache.Insert(cacheKey, value);\n    }\n    return (T) value;\n}	0
9538851	9538716	Pass View Model into a Function	GetValuesForUserORMember(dynamic thisView)\n{\n    thisView.memID = (WebSessions.IsCUser) ? 0 : WebSessions.MemID;\n    thisView.caseUserID = (WebSessions.IsCUser) ? WebSessions.CUserID : 0;\n    thisView.isMember = !(WebSessions.IsCUser); \n    thisView.isUser = (WebSessions.IsCUser);\n}	0
9609143	9609042	C# Replace part of a string	using System.Text.RegularExpressions;\nRegex reg = new Regex(@"width='\d*'");\nstring newString = reg.Replace(oldString,"width='325'");	0
17065515	17065301	Finding all similar lines in a text file	var lines = File.ReadLines(myFilePath);\nvar lineGroups = lines\n                  .Where(line => line.Contains(","))\n                  .Select(line => new{key = line.Split(',')[0], line})\n                  .GroupBy(x => x.key);\nforeach(var lineGroup in lineGroups)\n{\n    var key = lineGroup.Key;\n    var keySpecificLines = lineGroup.Select(x => x.line);\n    //save keySpecificLines to file\n}	0
16413927	16297107	Fluent NHibernate HasMany mapping inserts null in foreign key	public ParentMap()\n    {\n        Map(x => x.Number).Not.Nullable();\n        HasMany(x => x.Children).Cascade.All();\n    }	0
28848712	28848530	Create fixed size array on stack	int* block = stackalloc int[100];	0
24662431	24560801	Javascript JSON serialize only first level	var clone = {};\nfor (prop in obj) {\n    if (typeof obj[prop] == "string" || typeof obj[prop] == "number" || typeof obj[prop] == "boolean") {\n        clone[prop] = obj[prop];\n    }\n}	0
20431458	20431415	How to stop a VLC player from another application?	Process.Kill();	0
17587822	17587588	How to convert this scientific notation to decimal?	Decimal h2 = 0;\nDecimal.TryParse("2.005E01", out h2);	0
10213085	10208098	how to go from using app.config of WCF binding and convert it to bind programmatically in correct manner	basicBinding.messageEncoding = WSMessageEncoding.Mtom	0
32197472	32073831	TPL Dataflow to be implemented for a Website scrapper	>> Execution Blocks\n    >> ActionBlock\n    >> TransformBlock\n    >> TransformManyBlock\n\n>> Buffering Blocks\n    >> BufferBlocl\n    >> BrodcastBlock\n    >> WriteOnceBlock\n\n>> Joining Blocks\n    >> BatchBlock\n    >> JoinBlock\n    >> BatchedJoinBlock	0
4040174	4039845	Is there any way to override what string value my custom type gets converted to when serializing via DataContract?	public sealed class Fraction {\n\n    private readonly long numer;\n    private readonly long denom;\n\n    [DataMember(Name="Fraction")\n    private string fractionString;	0
30626780	30620691	how to eliminate dependencies with mcs (mono) command in bash?	ILRepack.exe [options] /out:<path> <path_to_primary> [<other_assemblies> ...]	0
31962051	31941619	How to add custom table in ASP.NET IDENTITY?	public class ApplicationUser : IdentityUser\n{\n\n    public virtual ICollection<UserLog> UserLogs { get; set; }\n\n}\n\npublic class UserLog\n{\n    [Key]\n    public Guid UserLogID { get; set; }\n\n    public string IPAD { get; set; }\n    public DateTime LoginDate { get; set; }\n    public string UserId { get; set; }\n\n    [ForeignKey("UserId")]\n    public virtual ApplicationUser User { get; set; }\n}\n\npublic System.Data.Entity.DbSet<UserLog> UserLog { get; set; }	0
28731362	28725034	Azure: How to Delete "DeadLettered" Messages from Service Bus queue	QueueClient.FormatDeadLetterPath(queuePath)	0
19586641	19586554	C# Convert negative int to 11 bits	string s = Convert.ToString(value & 2047, 2);	0
28167198	28167141	getting the sum of the selected values in a listbox in c# MVC4	public int Index(IEnumerable<int> Selectedroles)\n  {\n    if (Selectedroles == null)\n       { return 0; }\n    else\n    {\n      var arr = Selectedroles.ToArray();\n        int result = 0;\n       for (int i = 0; i < arr.Length; i++)\n        {\n            result += Convert.ToInt32(arr[i]);\n        }\n   // another way\n      foreach(var r in Selectedroles)\n                  result += r;\n     return result;\n\n  }	0
22863865	22863188	Parsing HTML content with C# Parser	class RoomInfo\n    {\n        public String Name { get; set; }\n        public Dictionary<String, Double> Prices { get; set; }\n    }\n\n    private static void HtmlFile()\n    {\n        List<RoomInfo> rooms = new List<RoomInfo>();\n\n        HtmlDocument document = new HtmlDocument();\n        document.Load("file.txt");\n\n        var h2Nodes = document.DocumentNode.SelectNodes("//h2");\n        foreach (var h2Node in h2Nodes)\n        {\n            RoomInfo roomInfo = new RoomInfo\n            {\n                Name = h2Node.InnerText.Trim(),\n                Prices = new Dictionary<string, double>()\n            };\n\n            var labels = h2Node.NextSibling.NextSibling.SelectNodes(".//label");\n            foreach (var label in labels)\n            {\n                roomInfo.Prices.Add(label.InnerText.Trim(), Convert.ToDouble(label.Attributes["precio"].Value, CultureInfo.InvariantCulture));\n            }\n            rooms.Add(roomInfo);\n        }\n    }	0
33913820	33912394	How to bind values between two bindable properties in composite control Xamarin Forms?	public MyEditor()\n{\n...\n   editor.SetBinding(Editor.TextPropety, new Binding("Text", BindingMode.TwoWay,source:this));\n\n}	0
17978946	17978078	which sentence is largest and how many number contains	string[] txt = i.Split(new char[] { '.', '?', '!', ',' }); //this part you had correct\nvar stringsOrderedByLargest = txt.OrderByDescending(s => s.length);	0
17658820	17658723	How do I return Json serialized data from WCF?	[OperationContract]\n    [WebGet(ResponseFormat = WebMessageFormat.Json)]\n    ObjectName YourMethodName();	0
25938796	25938316	ASP.NET Application state - Creating a "requests per minute" counter	public BaseController() : base() \n{\n    CacheItemPolicy policy = new CacheItemPolicy();\n    policy.AbsoluteExpiration = DateTime.UtcNow.AddMinutes(10);\n\n    MemoryCache.Default.Add(Guid.NewGuid(), "RequestCount", policy);\n}\n\npublic int RequestCountPerMinute\n{\n    get\n    {\n        return MemoryCache.Default\n           .Where(kv => kv.Value.ToString() == "RequestCount").Count() / 10;\n    }\n}	0
34060613	34051783	Draw text with overlay in center of rectangle (ProgressBar)	StringFormat format = new StringFormat()\n{\n    Alignment = StringAlignment.Center,\n    LineAlignment = StringAlignment.Center\n};\nfloat emSize = graphics.DpiY * Font.Size / 72;\nvar p = new GraphicsPath();\np.AddString(\n    newText,\n    Font.FontFamily,\n    (int)Font.Style,\n    emSize ,\n    ClientRectangle, // !!!\n    format); // !!!	0
30956041	30955876	How to retrieve ATTRIBUTE VALUE from specific ELEMENT VALUE in C#	//Time[text() = '...']/@hours	0
18954065	18953998	How to set cursor position in textBox on button click event using c#?	textBox1.Focus();	0
9076219	9076154	How to compare values foreach inside a foreach	foreach (string fern in ferns)\n{\n\n    foreach (string fruit in fruits)\n    {\n        if(String.Compare(fern,fruit,false)==0)\n        {\n             Console.WriteLine("YES");\n        }\n    }\n\n\n}	0
1205043	1205025	c# How to downcast an object	Section section = slide as Section;\nif (section != null)\n{\n    // you know it's a section\n}\nelse\n{\n    // you know it's not\n}	0
28362614	28362535	LINQ version of SQL Group By	var query = from rec in dbo.TableName\n            group rec by rec.ItemName into ItemNameGroup\n            select new { \n                ItemName = ItemNameGroup.Key, \n                SumQuantity = ItemNameGroup.Sum(r => r.Quantity),\n                MaxPPU = ItemNameGroup.Max(r => r.PPU)\n            };	0
34189806	33895619	How to modify tabs for the secondary menu in a c# web page application	#MainContent_Menu1 a.static {\n      padding-left: 0.45em;\n      padding-right: 0.45em;\n  }	0
20550112	20549987	How to remove empty elements from Dictionary<string,string>?	MyDict = MyDict.Where(item => !string.IsNullOrEmpty(item.Value))\n                .ToDictionary(i => i.Key);	0
20460353	20459734	How can I reset my textbox value on Windows Phone 8	try\n{\n    iKredi[0] = Convert.ToInt16(kredi1.Text);\n}\ncatch (InvalidCastException)\n{\n    //handle exception here such as inform user to enter int\n}	0
442549	442334	Convert an array to object[]	_targetForm.dw_retailer.SetColumn(6);\n_targetForm.dw_retailer.SetText(retailer.text);\n_targetForm.dw_retailer.SetColumn(9);\n_targetForm.dw_retailer.SetText(retailer.webname);	0
12277780	12277613	String contains more than one word	var keywords = new List<string>();\nkeywords.AddRange(ddl_model.SelectedValue.Split(' '));\nkeywords.AddRange(ddl_language.SelectedValue.Split(' '));\n\nforeach(string str in list)\n   if (keywords.Any(keyword => str.Contains(keyword))\n      lstpdfList.Items.Add(str);	0
7226656	7226599	asp.net how to check if a file exist on external server given web address	bool exist = false;\n try\n {\n      HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://www.example.com/image.jpg");\n      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n      {\n           exist = response.StatusCode == HttpStatusCode.OK;\n      }\n }\n catch\n {\n }	0
16997531	16992442	WCF client application crashes when accessing service	try\n{\n MyServiceClient client = new MyServiceClient();\n Console.WriteLine(client.GetOrders().First().Date_Accepted.ToString());\n client.Close();\n Console.ReadLine();\n}\ncatch (Exception ex)\n{\n Console.WriteLine(ex);\n}	0
12560044	12555241	Dependency injection in BAL without adding a project reference to DAL	IQueryable<TEntity>	0
34422631	34422549	adding a item in listBox	ListItem item = new ListItem(TextBox1.Text);\n\nif (!ListBox1.Items.Contains(item))\n{\n//Add item here\n}	0
8359935	8350074	How do I get RedirectStandardOutput to work in NUnit?	[TestFixture]\npublic class InstallTest\n{\n    [Test]\n    public void InstallAgentNix()\n    {\n        Process process = new Process();\n        process.StartInfo.FileName = @"C:\Tools\plink.exe";\n        process.StartInfo.Arguments = @"10.10.9.27 -l root -pw PASSWORD -m C:\test.sh";\n        process.StartInfo.UseShellExecute = false;\n        process.StartInfo.RedirectStandardOutput = true;\n        process.StartInfo.RedirectStandardInput = true;\n        process.Start();\n\n        string output = process.StandardOutput.ReadToEnd();\n\n        process.WaitForExit();\n\n        output = output.Trim().ToLower();\n\n        Assert.AreEqual("pass", output, "Agent did not get installed");\n    }\n}	0
2179387	2179308	C# and Variable Scope in Winforms	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace Test\n{\n    public partial class Form1 : Form\n    {\n        foo a;\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, EventArgs e)\n        {\n            a = new foo();\n            a.name = "bar";\n\n\n\n        }\n\n        private void button2_Click(object sender, EventArgs e)\n        {\n            if (a != null && a.name != null)\n                MessageBox.Show(a.name);\n            else \n                MessageBox.Show("");\n        }\n    }\n\n    public class foo\n    {\n\n        string _name;\n        public string name\n        {\n            get {\n                return _name;\n            }\n            set {\n                _name = value;\n            }\n        }\n\n        public foo()\n        { \n\n        }\n    }\n}	0
27126701	27064857	HtmlHelper that Returns HTML from url (essentialy proxy)	public static IHtmlString RenderActionToSpecifiedAssembly(this HtmlHelper helper, string actionName, string controllerName, string parentAssembly)\n{\n        var parentWebConfigarentValue = new Uri(ConfigurationManager.AppSettings[parentAssembly]);\n        var path = controllerName + "/" + actionName;\n        var redirect = new Uri(parentWebConfigarentValue, path).AbsoluteUri;\n        var request = (HttpWebRequest)WebRequest.Create(redirect);\n\n        var result = (HttpWebResponse)request.GetResponse();\n\n        String responseString;\n\n        using (Stream stream = result.GetResponseStream())\n        {\n            StreamReader reader = new StreamReader(stream, Encoding.UTF8);\n            responseString = reader.ReadToEnd();\n        }\n\n        return new HtmlString(responseString);\n}	0
27181535	27181206	How can I get a list of all assemblies that have been called by the current program?	AppDomain.CurrentDomain.GetAssemblies()	0
5977941	5977903	How do you set scheduled task properly in a webapplication	private void MyPingThread(object state)\n{\n    ThreadExitState lstate = state as ThreadExitState;\n    EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);\n    while (true)\n    {\n        if (lstate != null)\n        {\n           if (!lstate.Active)\n               return;\n        }\n        handle.WaitOne(1000 * 60 * 60 * 4); // Run the task each 4 hours\n        //Do your work here\n    }\n}	0
32067376	31960178	Unity change RegisterType for controller (two contexts)	container.RegisterType<IDataContextAsync, TenantDataContext>("TenantContext", new InjectionConstructor());\ncontainer.RegisterType<IUnitOfWorkAsync, UnitOfWork>("UnitOfWork", new InjectionConstructor(new ResolvedParameter<IDataContextAsync>("TenantContext")));	0
5594050	5593669	Extracting text out of text file by parsing it using C#	using System.IO;\nusing System.Text.RegularExpressions;\npublic List<string> NaiveExtractor(string path)\n{\n    return \n    File.ReadAllLines(path)\n        .Select(l => Regex.Replace(l, @"[^\d]", ""))\n        .Where(s => s.Length > 0)\n        .ToList();\n}	0
24398198	24398165	Pass array of class as array of object	var separateDllFilters = oDataRequest.Filters.Select(of => new SeparateDLL.ViewFilterData\n{\n Table = of.Table,\n // so on\n}).ToArray();	0
2586064	2585963	Making A Dynamically Created Excel Report Downloadable	byte[] excelData = File.ReadAllBytes(Server.MapPath("test.xls"));\n\n  Response.AddHeader("Content-Disposition", "attachment; filename=test.xls");\n  Response.ContentType = "application/x-msexcel";\n  Response.BinaryWrite(excelData);	0
21047127	21046788	Adding node to existing xml element	XmlNode xhousing = xDoc.SelectSingleNode(@"//house[@windowsc='three']/windows");\nXmlNode xName = xDoc.CreateElement("Name");\nxName.InnerText = "hi";\nxhousing.AppendChild(xName);	0
1860311	1860306	.NET: How to efficiently check for uniqueness in a List<string> of 50,000 items?	HashSet<T>	0
798845	798814	ASP.NET Relative Paths in Referenced Libraries	public void LoadRulesFromXml( string in_xmlFileName, string in_type ) \n{   \n    // To see what's going on\n    Debug.WriteLine("Current directory is " +\n              System.Environment.CurrentDirectory);    \n\n    XmlDocument xmlDoc = new XmlDocument();    \n\n    // Use an explicit path\n    xmlDoc.Load( \n       System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,\n       in_xmlFileName) \n    );\n...	0
13627806	13627697	Find execution time of recursive function	using System.Diagnostics;\n\nnamespace StackOverflow.Demos\n{\n    class Program\n    {\n        public static void Main(string[] args) \n        {\n            Stopwatch timer = new Stopwatch();\n            timer.Start();\n            recur(10000, new object());\n            timer.Stop();\n            Console.WriteLine( timer.Elapsed.TotalMilliseconds.ToString());\n            Console.ReadKey();\n        }\n        private static void recur(int a, object b)\n        {\n            if (a > 0)\n                recur(--a, b);\n        }\n    }\n}	0
1399710	1399657	How do I make XmlSerialiser not start with <?xml ?>?	public static string SerializeExplicit(SomeObject obj)\n{    \n    XmlWriterSettings settings;\n    settings = new XmlWriterSettings();\n    settings.OmitXmlDeclaration = true;\n\n    XmlSerializerNamespaces ns;\n    ns = new XmlSerializerNamespaces();\n    ns.Add("", "");\n\n\n    XmlSerializer serializer;\n    serializer = new XmlSerializer(typeof(SomeObject));\n\n    //Or, you can pass a stream in to this function and serialize to it.\n    // or a file, or whatever - this just returns the string for demo purposes.\n    StringBuilder sb = new StringBuilder();\n    using(var xwriter = XmlWriter.Create(sb, settings))\n    {\n\n        serializer.Serialize(xwriter, obj, ns);\n        return sb.ToString();\n    }\n}	0
2515436	2514688	Destructor - does it get called if the app crashes	using System;\n\nclass Program {\n  static void Main(string[] args) {\n    var t = new Test();\n    throw new Exception("kaboom");\n  }\n}\nclass Test {\n  ~Test() { Console.WriteLine("finalizer called"); }\n}	0
5792448	5792366	How to make sure a user only gets added to a list once	if (! oList.Any(u => u.Name == user.Name ))\n {\n      oList.Add(user);\n }	0
2616159	2612151	Finding if a target number is the sum of two numbers in an array via LINQ and get the and Indices	int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nint target = 7;\n\nvar query = numbers\n              .SelectMany((num1,j) => numbers.Select((num2,i) => new {n1=num1, n2=num2, i=i, j=j}))\n              .Where(x => x.n1 + x.n2 == target && x.i < x.j);\n\nforeach (var x in query)        \n   Console.WriteLine(x.n1 + " and " + x.n2 + " occur at " + x.i + "," + x.j );	0
26686710	26686619	change textblock text that is inside Listbox in windowsphone 8	public class YourViewModel\n{\n    public List<YourModel> Models { get; set; }\n}\n\npublic class YourModel : INotifyPropertyChanged\n{\n     private string yourText;\n     public string YourText \n     { \n         get { return yourText; }\n         set\n         {\n             yourText = value;\n             NotifyPropertyChanged("YourText");\n         }\n      }\n\n      // add INotifyPropertyChanged implementation here\n}	0
31097379	31097356	Print even numbers with Range() in LINQ	Enumerable.Range(1, 10).Where(n => n%2 == 0).ToList().ForEach(Console.WriteLine);	0
2419958	2419890	How Can I Compare Any Numeric Type To Zero In C#	public bool IsGreaterThanZero(object value)\n{\n    if(value is IConvertible)\n    {\n        return Convert.ToDouble(value) > 0.0;\n    }\n\n    return false;\n}	0
21838862	21838660	GetField const in type's base class	c.GetType().GetField("ParentField", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)	0
2030702	2030665	How do I share a data context across various model repositories in ASP.NET MVC using linq2sql	public class MyRepository : IMyRepository\n{\n    private readonly DataContext dataContext;\n\n    public MyRepository(DataContext dataContext)\n    {\n        if(dataContext == null)\n        {\n            throw new ArgumentNullException("dataContext");\n        }\n\n        this.dataContext = dataContext;\n    }\n\n    // implement MyRepository using this.dataContext;\n}	0
30085184	30084977	Changing Host Names dynamically	string toRemove = new Uri(yourString).host;\nstring newString = yourString.Replace(String.format(@"\\{0})",toRemove)\n                                    , String.format(@"\\{0})",whateveryouwant));	0
9932524	9932485	Get the contents of a HTML tag via parsing	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(inputHtml);\n\nvar text = doc.DocumentNode\n              .Descendants("a")\n              .Where(x => x.Attributes["id"]!=null && \n                          x.Attributes["id"].Value == "def_")\n              .First()\n              .InnerText;	0
6270157	6270098	How correct set PropertyPath	binding.Path = new PropertyPath("DataContext")	0
3874343	3874291	Filling list data into a data model class C#	fieldName = String.Format( "band{0:00}", count)	0
21892091	20576995	Folder Browser Dialog from remote machine perspective like the one SSMS uses	public partial class RemoteFileDialog : Form\n{\n    public Server server = new Server( new ServerConnection("ServerName", "User", "Password") );\n\n    /* ... */\n\n    public void getServerDrives()\n    {\n        DataTable d = server.EnumAvailableMedia();\n        foreach (DataRow r in d.Rows)\n            treeView.Nodes.Add( new TreeNode(r["Name"].ToString() );\n    }\n\n    /* ... */\n\n    //populate a node with files and subdirectories when it's expanded\n    private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)\n    {\n        DataSet ds = server.ConnectionContext.ExecuteWithResults(string.Format("exec xp_dirtree '{0}', 1, 1", e.Node.FullPath));\n        ds.Tables[0].DefaultView.Sort = "file ASC"; // list directories first, then files\n        DataTable d = ds.Tables[0].DefaultView.ToTable();\n        foreach (DataRow r in d.Rows)\n            e.Node.Nodes.Add( new TreeNode(r["subdirectory"].ToString());\n    }\n}	0
21445104	21444675	How do i move each item one index up automatic in a listview?	int count;\nif ((count = listView1.Items.Count) > 0)\n{\n   var LastItem = listView1.Items[count - 1];\n   listView1.Items.Remove(LastItem);\n   listView1.Items.Insert(0, LastItem);\n}	0
19772560	19772035	Passing comma delimited string to stored procedure?	CREATE PROCEDURE [dbo].[uspPages_HotelPrices_Lookup_Select] \n    @HotelCodes dbo.MyCodesTable READONLY\nAS\nBEGIN\n    SET NOCOUNT ON;\n\n    SELECT * \n    FROM tPages_HotelPrices_Lookup a \n    INNER JOIN @HotelCodes b ON (a.ID = b.ID)\nEND	0
6503445	6503424	How to programatically set the Image source	BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));	0
11923963	11923785	Run one instance of program	using System;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;   // Add reference to Microsoft.VisualBasic\n\nnamespace WindowsFormsApplication1 {\n    class Program : WindowsFormsApplicationBase {\n        [STAThread]\n        static void Main(string[] args) {\n            var app = new Program();\n            app.Run(args);\n        }\n        public Program() {\n            this.IsSingleInstance = true;\n            this.EnableVisualStyles = true;\n            this.MainForm = new Form1();\n        }\n        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {\n            if (this.MainForm.WindowState == FormWindowState.Minimized) this.MainForm.WindowState = FormWindowState.Normal;\n            this.MainForm.Activate();\n        }\n    }\n}	0
7529080	7528924	Fileupload inside detailsview in edit mode	FileUpload fu1 = (FileUpload)FindControl(DetailsView1, "FileUpload1");\n\n...\n\nprivate Control FindControl(Control parent, string id)\n{\n    foreach (Control child in parent.Controls)\n    {\n        string childId = string.Empty;\n        if (child.ID != null)\n        {\n            childId = child.ID;\n        }\n\n        if (childId.ToLower() == id.ToLower())\n        {\n            return child;\n        }\n        else\n        {\n            if (child.HasControls())\n            {\n                Control response = FindControl(child, id);\n                if (response != null)\n                    return response;\n            }\n        }\n    }\n\n    return null;\n}	0
33322048	33319904	Coping actual transform in unity3d	Vector3 copyOfPosition = someTransform.position;	0
26460656	26460616	c# Make TcpServer Block	byte[] buf = new byte[1];\nstream.Read(buf, 0, 1);	0
9588651	9585586	Changing scale in Y-Axis	chart.ChartAreas[0].AxisY.Maximum = 10;	0
31687501	31670480	Making a Visio document page landscape c#	var pageSheet = Application.ActivePage.PageSheet;\n\n// set landsape\npageSheet.Cells["PageWidth"].FormulaU = "11 in";\npageSheet.Cells["PageHeight"].FormulaU = "8.5 in";\npageSheet.Cells["PrintPageOrientation"].FormulaU = "2";\n\n// set portrait\npageSheet.Cells["PageWidth"].FormulaU = "8.5 in"\npageSheet.Cells["PageHeight"].FormulaU = "11 in"\npageSheet.Cells["PrintPageOrientation"].FormulaU = "1"	0
27195940	27195889	Increment the number of votes button	public ActionResult OpenBidPanelOnItem() {\n   var model = GetModelFromSomewhere();\n   model.NumberOfVotes++;\n   SaveModelToPersistentDataStore(model);\n}	0
3532760	3532197	Is there a way to force Microsoft.Jet.OLEDB to get date Columns in MM/DD/YYYY format from Excel?	OleDbDataAdapter myCommand = \n  new OleDbDataAdapter("SELECT FORMAT([DateCol], 'MM/dd/yyyy' FROM [TableName]",\n                       connToExcel);	0
18254162	18254080	Require some text boxes to be filled in but not all	//Place textboxes in array for easy access\nTextBox[] validatedTexboxes = new TextBox[] {\n     textbox1, textbox2, textbox3, ...\n};\n\n//On submit, make sure 40 are filled in.\nvar filledTextboxes = validatedTexboxes.Count(x => !String.IsNullOrWhiteSpace(x.Text));\n\nif (filledTextboxes > 40)\n    //Do Something	0
27224612	27088077	create inkcanvas class dynamically in wpf with tool tip display	namespace strokecollectio\n{\n\n\n class mycan : InkCanvas\n{\n\n    public mycan()\n    {\n        this.Width = 300;\n        this.Height = 200;\n\n\n    }\n}\n}	0
15689678	15689623	Failure sending mail	client.Credentials = new System.Net.NetworkCredential(\n            @"email_account",\n            @"email_password");	0
10180885	10179460	How to share a bitmap on facebook as a photo in C#?	// Step 2: you have to research what TheScope will be from Facebook API that gives you access to photos\nResponse.Redirect(string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&scope={1}&redirect_uri={2}"), MyAppCode, TheScope, MyRedirectingURL);\n\n// Step 3: this is on the `Page_Load` of MyRedirectingURL.\n// AnotherRedirectingURL will be your final destination on your app\nusing (var wc = new WebClient())\n{\n    string token = wc.DownloadString(string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", MyAppCode, MyAppSecretCode, TheCode, AnotherRedirectingURL));   \n}\n\n// Step 4:  Use the token to start stream up or down\nusing (var wc = new WebClient())\n{    \n    Uri uploadUri = new Uri(string.Format("https://graph.facebook.com/{0}?{1}", PhotoUploadCommand, token));     \n\n    // Find out what the PhotoUploadCommand is supposed to be from the Facebook API\n    // use wc and uploadUri to upload the photo\n}	0
15000047	14999732	Get UserName and Password in WinRT?	CredentialCache.DefaultNetworkCredentials	0
14935815	14935102	How do I do the equivilent of '/controller/action/1#myid' with RedirectToAction?	return Redirect(\n            Url.RouteUrl(new \n            { \n                controller = "MyControllerName", \n                action = "MyActionName", \n                id = model.CustomerID \n            }) + "#mytabid");	0
2392158	2392122	Assigning values to the datagridview cell	myGridView[col,row].Value = myTextBox.Text;	0
31403585	31403532	Dynamically fill a <td> with a control asp.net	table { width:100%; }	0
20663055	20662919	How to get row values of a certain column on ASPXGridView	int indexOfColumnToGet = some number;\ngridview.Rows[rowIndex].Cells[indexOfColumnToGet].Text	0
14361685	14361255	Find Label by Name in a UserControl when the label's Parent is a PictureBox	Label GetLabelByTag(int _tag, string _family)\n{\n    return FindLabelByTag(_tag, _family, this);\n}\n\nLabel FindLabelByTag(int _tag, string _family, Control _control)\n{\n    Label rez = null;\n\n    foreach (Control lb in _control.Controls)\n    {\n        if (lb.Tag != null)\n        {\n            if (((int)lb.Tag == _tag) && (lb.Name == _family + _tag.ToString()))\n            {\n                return (Label)lb;\n            }\n        }\n        var inControl = FindLabelByTag(_tag, _family, lb);\n        if (inControl != null)\n            return inControl;\n    }\n\n    return null;\n}	0
24026084	24025741	Ensuring that items in one listbox does not appear in another listbox	var filteredAvailableUsers = availableUsers.Where(u => !selectedUsers.Any(s => s.Value == u.Value));	0
10549805	10549065	Show waiting cursor while starting and loading application	//Set the cursor to appear as busy\nCursor.Current = Cursors.WaitCursor;\n\n---Execute your code-------\n\n//Make the Cursor to default\nCursor.Current = Cursors.Default;	0
14325920	14325798	Retrieving Windows 8 product key	A small tool for finding your Windows product key. No install required, just a single executable file. \nIts open source so you can actually see what the program is doing with your key :P	0
19416531	19416272	Trying to load multiple XML input files into iDictionary<string,Ojbect>	Dictionary<string, msg> masterDictionary = new Dictionary<string, mgs>();\n\nforeach (string file in filePath)\n{\n    XDocument xdoc = XDocument.Load(file);\n    Dictionary<string, msg> fileDictionary = xdoc\n        .Descendants("msg")\n        .ToDictionary(m => m.Element("msgId").Value,\n                      m => new msg\n                           {\n                               msgId = m.Element("msgId").Value,\n                               msgType = m.Element("msgType").Value,\n                               name = m.Element("name").Value\n                           });\n\n    //now insert your new values into the master\n    foreach(var newValue in fileDictionary)\n        masterDictionary.Add(newValue.Key, newValue.Value);\n}	0
8142730	8142398	Multiple regex options with Regex.Replace	string result = Regex.Replace("aa cc bbbb","aa|cc","",RegexOptions.IgnoreCase).Trim();	0
24744313	24744054	Deleting from database from datagridview	"DELETE FROM AmmunitionTable WHERE Caliber='" + ammoDGV.SelectedRows[0].Cells[0].Value.ToString() + "'";	0
25840538	25840382	Group list of points	foreach (var point in Points)\n{\n    xCenterOfMass +=  point.X;\n    yCenterOfMass +=  point.Y;\n}\n\nxCenterOfMass /= Points.Count();\nyCenterOfMass /= Points.Count();	0
11366745	11366673	Need a method like Java's StringTokenizer hasTokens() method in Visual C#	List<string> list = txtboxInput.Text.Split(';').ToList();	0
11019563	11019121	How can I send a postback to a website?	ie.Link(Find.ByUrl("javascript:__doPostBack('GridView1','Select$0')")).Click();	0
2063936	2001046	How to correctly implement a modal dialog on top a non-modal dialog?	public partial class Window1 : Window\n{\n    public Window1()\n    {\n        InitializeComponent();\n    }\n\n    private void NonModalButtonClick(object sender, RoutedEventArgs e)\n    {\n        new Window1 { Owner = this }.Show();\n    }\n\n    private void ModalButtonClick(object sender, RoutedEventArgs e)\n    {\n        new Window1 { Owner = this }.ShowDialog();\n    }\n\n    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)\n    {\n        if (this.Owner != null)\n        {\n            this.Owner.Activate();\n        }\n    }\n}	0
2567204	2567163	Optional parameters for interfaces	public interface IFoo\n{\n    void Bar(int i, int j);\n}\n\npublic static class FooOptionalExtensions\n{\n    public static void Bar(this IFoo foo, int i)\n    {\n        foo.Bar(i, 0);\n    }\n}	0
18143675	18143393	How to create(export) excel file readonly using Open Xml 2.5 SDK	FileInfo cInfo = new FileInfo(Path);\ncInfo.IsReadonly = true;	0
6394992	6394967	C# build json string that has semicolons in the data	\"\n\\\n\/\n\b\n\f\n\n\n\r\n\t	0
13125045	13124975	Populating A New Object With Existing Objects Data	public MyUserSettings(UserSettings baseSettings)\n{\n    // TODO: set all properties\n}	0
19981352	19981289	Silverlight - access string format from Binding in code	dg.Columns\n    .OfType<DataGridBoundColumn>()\n    .Select(i => (i as DataGridBoundColumn).Binding.StringFormat)	0
160747	160742	How do you put { and } in a format string	string s = String.Format("{{ hello to all }}");\nConsole.WriteLine(s); //prints '{ hello to all }'	0
14534018	14518670	Redirect to https after ensuring ssl availability	public bool UrlExists(string url)\n    {\n        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n        request.Timeout = 15000;\n        request.Method = "HEAD"; \n\n        try\n        {\n            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n            {\n                return response.StatusCode == HttpStatusCode.OK;\n            }\n        }\n        catch (WebException)\n        {\n            return false;\n        }\n    }	0
3751521	3751468	Get number of pages for printing from Excel Interopb	ActiveSheet.PageSetup.Pages.Count	0
4431727	4428900	Autoplaying a movie in a PowerPoint presentation with C#	//While iterating through all slides i:\n   objShapes = objPres.Slides[i].Shapes;\n    foreach (Microsoft.Office.Interop.PowerPoint.Shape s in objShapes) {\n            if(s.Name.Contains(".wmv")){\n            s.AnimationSettings.PlaySettings.PlayOnEntry = MsoTriState.msoTrue;\n    }\n   }	0
1578683	1578397	Dont want textbox to enter null value in datatable	private void BindtoGridViewFromTextBoxes(DataTable dt)\n{\n    if (!String.IsNullOrEmpty(txtname.Text))\n    {\n        DataRow dr = dt.NewRow();\n        dr["firstName"] = txtName.Text;\n        dt.Rows.Add(dr);\n        Session["Data"] = dt;\n    }\n    GridView1.DataSource = dt;\n    GridView1.DataBind(); \n}	0
14536739	14536714	Entity Framework - How to navigate in List<T> elements	var garden = _db.Gardens.SingleOrDefault(g => g.Id == gardenId);\n\n Flower flower = null;\n\n if (garden != null)\n {\n     flower = garden.Flowers.SingleOrDefault(f => f.Id == flowerId);\n }	0
12556604	12556401	How do I copy just one part of a sentence and put it on a text control?	string DownloadFileName = Regex.Match(PageSource, DownloadFileLink + "\">(.*?)</a></li></div></ul>").Groups(1).Value;	0
25686888	25684214	XDocument Load Multiple XML Files From Multiple Folders At Once	string xmlFiles = "path_to_XMLFiles_folder/XMLFiles";\n                          //get all folders within XMLFiles folder. the years\nstring[] files = Directory.GetDirectories(xmlFiles)\n                          //get all folders within each year. the months\n                          .SelectMany(Directory.GetDirectories)\n                          //get all files within each montsh.\n                          .SelectMany(Directory.GetFiles)\n                          .Where(f => f.EndsWith(".xml"))\n                          .ToArray();\nforeach(var path in files)\n{  \n    XDocument xDoc = XDocument.Load(path);\n    //process each XML file\n}	0
32760161	32759789	How to add a delay before "InvokeMember()" in a C# Winforms project	private async void button1_Click(object sender, EventArgs e)\n{\n    await Task.Run(async () =>\n    {\n        await Task.Delay(3000);\n        MessageBox.Show("1");\n        button1.Invoke(new Action(() => { this.button1.Text = "1"; }));\n    });\n    MessageBox.Show("2");\n    button1.Invoke(new Action(() => { this.button1.Text = "2"; }));\n}	0
1586539	1586537	loop through an array and find partial string	array.Where(s => s.Contains("ack"));	0
13251653	13250642	Block double byte chars in a textbox	InputMethod.SetIsInputMethodEnabled(myTextBox, false)	0
32549016	32548880	Split with regular expression	Regex.Split(s, @"(;(?!(\w*\))))")	0
10735632	10734189	Create table using two dimensional array	foreach( var v in Muvees )\n{ListViewItem movieToAdd = new ListViewItem();\n movieToAdd.Text = v.movieid; \nmovieToAdd.SubItems.Add(v.rating); \nmovieToAdd.SubItems.Add(v.movieName); \nlistOfMovies.Items.Add( movieToAdd ).BackColor = Color.Green;}    //add colour just because you can	0
13826141	13826054	Item after current item in list	public Insert(Item newItem, Item refItem) {\n  newItem.Next = refItem.Next;\n  refItem.Next = newItem;\n}	0
31279719	31278912	How to get a correct method reference when performing a JMP instruction to a method that resides in a different assembly	byte[] ilCodes = new byte[5];\nint token = module.GetMetadataToken(methodFromOtherAssembly).Token;\nilCodes[0] = (byte)OpCodes.Jmp.Value;\nilCodes[1] = (byte)(token & 0xFF);\nilCodes[2] = (byte)(token >> 8 & 0xFF);\nilCodes[3] = (byte)(token >> 16 & 0xFF);\nilCodes[4] = (byte)(token >> 24 & 0xFF);	0
23183640	23183622	Properties file as simple as in Java?	Settings.Default.NameOfSetting	0
4695310	4695288	Wanted: .Net collection that stores a bunch of case insensitive strings fast and efficient	new HashSet<string>(StringComparer.OrdinalIgnoreCase)	0
13467137	13395096	How to add check box to series in a chart in c#?	CheckedListBox()	0
32497962	32497563	Fastest way to create json in C#	var jsonString = JsonConvert.SerializeObject(objectToSerialize);	0
34303604	34302702	How to create a generic method to populate List<SelectListItem> with specified model properties?	public List<SelectListItem> AllAsSelectListItemsSpecifyProperties(Expression<Func<T, string>> valueProperty, Expression<Func<T, string>> textProperty, string selectedValue = "")\n{\n    return AllAsQueryable().Select(i => new SelectListItem()\n    {\n        Value = GetPropertyValue(valueProperty),\n        Text = GetPropertyValue(textProperty),\n        Selected = (selectedValue == valueProperty)\n    })\n    .ToList();\n}\n\nprivate string GetPropertyValue(Expression<Func<T, string>> expression)\n{\n    return expression.Compile()(this).ToString();\n}	0
266173	255278	Determine value of object in C#	static bool IsZeroOrEmpty(object o1)\n{\n    bool Passed = false;\n    object ZeroValue = 0;\n\n    if(o1 != null)\n    {\n        if(o1.GetType().IsValueType)\n        {\n            Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))\n        }\n        else\n        {\n            if (o1.GetType() == typeof(String))\n            {\n                Passed = o1.Equals(String.Empty);\n            }\n        }\n    }\n\n    return Passed;\n}	0
16582441	15494158	set height of icon Image template programatically	bitmapImage = new BitmapImage();\n                bitmapImage.BeginInit();\n                bitmapImage.StreamSource = memoryStream;\n                bitmapImage.DecodePixelHeight = font.Size <= 9 ? font.Size + 2 : font.Size;\n                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n                bitmapImage.EndInit();\n                bitmapImage.Freeze();	0
15083961	15083727	How to create XML in C#	//Create XmlDocument\nXmlDocument xmlDoc = new XmlDocument();\n\n//Create the root element\nXmlNode outputsElement = xmlDoc.CreateElement("outputs");\n\n//Create the child element\nXmlElement Element = xmlDoc.CreateElement("output");\n\n//Create "name" Attribute\nXmlAttribute nameAtt = xmldoc.CreateAttribute("name");\nElement.Attributes.Append(nameAtt);\n\n//Create "value" Attribute\nXmlAttribute valueAtt = xmldoc.CreateAttribute("value");\nElement.Attributes.Append(valueAtt);\n\n//Create "type" Attribute\nXmlAttribute typeAtt = xmldoc.CreateAttribute("type");\nElement.Attributes.Append(typeAtt);\n\n//Append child element into root element\noutputsElement.AppendChild(Element);	0
7308107	7307812	How to make a listView item checked after comparing some string?	string[] itemInList =  listView1.Items.OfType<ListViewItem>( ).Select( p => p.Text ).ToArray( );\nstring[] lineInHosts = File.ReadAllLines( @"C:\Test.txt" ).ToArray<string>( );\n\nstring itemName;\nListViewItem foundItem;\n\nforeach ( var item in itemInList )\n{\n     if (lineInHosts.Contains(item))\n     {\n         itemName = item.ToString( );\n         foundItem = listView1.FindItemWithText( itemName );\n         foundItem.Checked = true;                    \n     }\n}	0
6372543	6354532	Vs 2010 Click Once application written in c# copies the xml files into other directory	string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile);	0
10341202	10341136	c# smart way to delete multiple occurance of a character in a string	List<string> strings = new List<string>();\nwhile ((line = file.ReadLine()) != null) \n    string.AddRange(line.Replace("\"").split(',').AsEnumerable());	0
4210020	4209973	Overzealous String Constants	public const string COLON = "*";	0
19023706	19023095	How can I bind custom enum values to a @Html.CheckBox	var enumList = Enum.GetValues(typeof(EType)).Cast<EType>().Skip(1);\n\n@foreach (var optVal in enumList)\n{ \n<label>\n    @Html.CheckBox(optVal.ToString(), false, new { value = Convert.ToInt32(optVal).ToString()})\n    @optVal\n\n</label>\n}	0
7579580	7579518	inserting into an array in foreach	var urisToProcess = new HashSet<Uri>(\n  lines.Where(s => Uri.IsWellFormedUriString(s, UriKind.Absolute)).Select(s => new Uri(s)));\nvar redirectedUris = new HashSet<Uri>();\nforeach (var uri in urisToProcess)\n{\n  Uri response;    \n  WebSiteIsAvailable(uri, out response); \n  if(response.Equals(uri))\n  {\n    // do work on actual URI\n    continue;\n  }\n  while (!response.Equals(uri))\n  {    \n    uri = response;\n    WebSiteIsAvailable(uri, out response); \n  }\n  if(!urisToProcess.Contains(uri))\n  {\n     redirectedUris.Add(uri);\n  }\n}\nforeach (var uri in redirectedUris)\n{\n  // do work on redirected URI\n}	0
5025055	4985826	How to use CanvasAuthorizer.GetLoginUrl in v5?	CanvasAuthorizer _authorizer = new CanvasAuthorizer {Perms = "publish_stream,offline_access"};\nif (!_authorizer.IsAuthorized())\n{\n    _authorizer.HandleUnauthorizedRequest();\n}	0
22803370	22803198	Polymorphism using interface	public interface IPrinter\n{\n    void SetPage();\n    void SendToPrint();\n} // eo interface IPrinter\n\n\npublic class BasePrinter : IPrinter /* Could well be abstract */\n{\n     protected virtual void SetPageImpl() { }      /* Also could be abstract */\n     protected virtual void SendToPrintImpl() { }  /* ........ditto .....    */\n\n\n     // IPrinter implementation\n     public void SetPage()\n     {\n         SetPageImpl();\n         // can do other stuff here.  Will always be called!\n     } // eo SetPage\n\n\n     public void SendToPrint()\n     {\n         SendToPrintImpl();\n         // ditto\n     }\n}  // eo class BasePrinter\n\n\npublic class ChildPrinter : BasePrinter\n{\n     // we only do something different when setting a page\n     protected override void SetPageImpl()\n     {\n        // ChildPrinter-specifics\n     } // eo SetPageImpl\n} // eo class ChildPrinter	0
16952443	16952400	Adding and removing elements of a ConcurrentBag during enumeration	ConcurrentBag<T>.GetEnumerator	0
33359633	33359339	Open only specific image to picturebox without opening File Dialog	private void button1_Click(object sender, EventArgs e)\n    {\n        string path = @".\";\n        string[] filename = Directory.GetFiles(path, "*.png");\n\n        pictureBox1.Load(filename[0]);\n    }	0
9627653	9627214	How do I sort a List of Dictionaries based off of a value in a key within the Dictionary in C# .NET Silverlight?	var dicts = new List<Dictionary<string, string>>();\n\nvar sort = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] : string.Empty);\nvar sort2 = dicts.OrderBy(x => x.ContainsKey("Title") ? x["Title"] + "xyz" : string.Empty);	0
4144863	4123314	How I can declare arrays in struct?	[StructLayout(LayoutKind.Sequential)]\n     public struct Struct1\n     {\n           [MarshalAs(UnmanagedType.ByValArray, SizeConst = sizeOfarray)]\n           private Struct2[] arrayStruct;\n     }	0
1840572	1840537	Populate a list of Objects (With Linq?)	IList<RoleViewModel> returnViewModel = PermServ.GetAllRoles()\n                                        .Select(x => new RoleViewModel(x))\n                                        .ToList();	0
23590783	23590569	how can get file in list box depend on creationdate time	protected void Button1_Click(object sender, EventArgs e)\n{\n    DirectoryInfo dinfo = new DirectoryInfo(@"D:\Local_temp");\n    FileInfo[] files = dinfo.GetFiles("*.msg");\n\n    DateTime dt;\n    if (DateTime.TryParse(this.TextBox1.Text, out dt))\n    {\n        files.Where(x => File.GetCreationTime(x.FullName).Date == dt.Date).ToList().ForEach(x => this.ListBox1.Items.Add(x.Name));\n    }\n}	0
21906378	21906239	Restricted all routes expect the alowed one	var controllerName = filterContext.RouteData.Values["controller"];\nvar actionName = filterContext.RouteData.Values["action"];	0
9535043	9531393	Get images from directory 	Uri uri = new Uri(uriString, UriKind.Relative);\n\n            String originalUriString = uri.OriginalString;\n            Uri resourceStreamUri = originalUriString.StartsWith("/", StringComparison.Ordinal) ? new Uri(originalUriString.TrimStart('/'), UriKind.Relative) : uri;\n            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(resourceStreamUri);\n\n            if (null != streamResourceInfo)\n            {\n                stream = streamResourceInfo.Stream;\n\n                BitmapImage bitmapImage = new BitmapImage();\n                bitmapImage.SetSource(stream);\n\n                Image image = new Image();\n                image.Source = bitmapImage;\n            }	0
1293038	1292985	Run a method thats name was passed as a string	CallStaticMethod("MainApplication.Test", "Test1");\n\npublic  static void CallStaticMethod(string typeName, string methodName)\n{\n    var type = Type.GetType(typeName);\n\n    if (type != null)\n    {\n        var method = type.GetMethod(methodName);\n\n        if (method != null)\n        {\n            method.Invoke(null, null);\n        }\n    }\n}\n\npublic static class Test\n{\n    public static void Test1()\n    {\n        Console.WriteLine("Test invoked");\n    }\n}	0
9193481	9095909	CreateProcessAsUser Creating Window in Active Session	..................\nUInt32 dwSessionId = 0;  // set it to session 0\nSetTokenInformation(hDupedToken, TokenInformationClass.TokenSessionId, ref dwSessionId, (UInt32) IntPtr.Size);\n.................\nCreateProcessAsUser(hDupedToken, ....)	0
2943206	2943148	How to programmatically connect a client to a WCF service?	var myBinding = new BasicHttpBinding();\nvar myEndpoint = new EndpointAddress("http://localhost/myservice");\nvar myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint);\n\nIMyService client = null;\n\ntry\n{\n    client = myChannelFactory.CreateChannel();\n    client.MyServiceOperation();\n    ((ICommunicationObject)client).Close();\n}\ncatch\n{\n    if (client != null)\n    {\n        ((ICommunicationObject)client).Abort();\n    }\n}	0
5514760	5514716	Get linq to xml descendants Elements with specific attribute value	Url = entry.Elements("link")\n           .Single(x => (string)x.Attribute("type") == "image/jpeg")\n           .Value;	0
16145097	16139879	Does a SQL CLR stored procedure prevent injection?	[Microsoft.SqlServer.Server.SqlProcedure]\n    public static void IsUserNameExists(string strUserName, out SqlBoolean returnValue)\n    {\n        using (SqlConnection connection = new SqlConnection("context connection=true"))\n        {\n            connection.Open();\n            SqlCommand command = new SqlCommand("Select count(UserName) from [User] where UserName=@UserName", connection);\n            command.Parameters.Add(new SqlParameter("@UserName", strUserName));\n\n            int nHowMany = int.Parse(command.ExecuteScalar().ToString());\n\n            if (nHowMany > 0)\n                returnValue = true;\n            else\n                returnValue = false;\n        }\n    }	0
7091377	7091093	How to generate a square wave using C#?	y[k] = Math.Sin(freq * k)>=0?A:-1*A;	0
21656631	21656391	How to set CheckListBox itemsSource to all properties of a class object?	chkListBoxPerson.ItemsSource = typeof(Person).GetProperties();\nchkListBoxPerson.DisplayMemberPath = "Name";	0
4495158	4495137	c# getting item in row from datatable	int i=0;\n    List<string> l=new List<string>();\n    foreach (DataRow row in dt.Rows)\n    {\n        l.Add(Convert.ToString(row[2]));\n    }\n    string[] stringArray=l.ToArray();	0
12839124	12837679	How to find child dynamically inside XML	XmlNodeList snode = xmldoc.SelectNodes("/product/section/subsection");\nforeach (XmlNode xn2 in snode)\n{\n    //it comes inside if there will be a child node.\n}	0
13419953	13419572	How to save a resource from .resx to hard drive?	byte[] b = Properties.Main.Something;    //Something being the name of the resource\nSystem.IO.File.WriteAllBytes(@"C:\temp\yourfile.ecfg", b);	0
27366185	27366042	Selecting data using varyng source column	int col = Convert.ToInt32(request["usercolumn"]);\nstring q = "SELECT h" + col + " FROM table";	0
7405555	7405495	Excel C# inputting into specific cell	var xl = new Excel.Application();\nxl.Visible = true;\nvar wb = (Excel._Workbook)(xl.Workbooks.Add(Missing.Value));\nvar sheet = (Excel._Worksheet)wb.ActiveSheet;\nsheet.Cells[6, 6] = "6";	0
15802773	15802666	Date Time to Seconds	var unixFileTimeOrigin = DateTime.Parse("1970-01-01");\nvar date = DateTime.Parse("2013-04-03 01:00:00");\n\nConsole.WriteLine((date - unixFileTimeOrigin).TotalSeconds);\n>>> 1364950800	0
19469225	19469142	Looking for a way to read and write a text file	using (System.IO.StreamReader sr = new System.IO.StreamReader("YourFile.txt"))\n{\n  String line = sr.ReadLine();\n  Console.WriteLine(line);\n}	0
26217574	26217384	Assign Static Value to Field in Model	// completely guessing on types/models here, but you should get the idea...\nholiday_date_table.ActionType = "Add";\ndb.HOLIDAY_DATE_TABLE.Add(holiday_date_table);\ndb.SaveChanges();	0
4747468	4744968	Decompiling a Method Implemented with extern keyword	HKCR\CLSID\{guid}	0
8014130	8014086	Map Oracle blob data to dataset direct	System.Byte()	0
2222400	2222348	Delete files older than 3 months old in a directory using .NET	using System.IO; \n\nstring[] files = Directory.GetFiles(dirName);\n\nforeach (string file in files)\n{\n   FileInfo fi = new FileInfo(file);\n   if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))\n      fi.Delete();\n}	0
11583480	11577245	GLSL - Opentk pass an array of Vector3's	GL.Uniform3(...)	0
3985784	3985710	How can I find the users windows login username from ASP.Net?	User.Identity.Name	0
20207192	20207126	Date With Endings	string date = DateTime.Now.Date.ToString("dd");\n    date = date + (date.EndsWith("11") \n                   ? "th"\n                   : date.EndsWith("12")\n                   ? "th"\n                   : date.EndsWith("13")\n                   ? "th"\n                   : date.EndsWith("1") \n                   ? "st"\n                   : date.EndsWith("2")\n                   ? "nd"\n                   : date.EndsWith("3")\n                   ? "rd"\n                   : "th");	0
18045711	18045184	JSON deserialization not working after changing response string	output = Regex.Match(output, @".+?\((.+?)\)").Groups[1].Value	0
33083398	33083070	How to retrieve current value that has assinged after button click in C# windows forms	public YourWindow \n{\n   int LastTokenNumberIssued;\n\n   private void btnPrintToken_Click(object sender, EventArgs e)\n   {\n      int nextTokenNumberIssued;\n\n      LastTokenNumberIssued = LastTokenNumberIssued++;\n      nextTokenNumberTobeIssued = LastTokenNumberIssued;\n   }\n}	0
29692394	29691951	How to display changed text for few seconds from its original text?	private void button1_Click(object sender, EventArgs e)\n{\n    // To keep the user from repeatedly pressing the button, let's disable it\n    button1.Enabled = false;\n\n    // Capture the current text ("ABC" in your example)\n    string originalText = label1.Text;\n\n    // Create a background worker to sleep for 2 seconds...\n    var backgroundWorker = new BackgroundWorker();\n    backgroundWorker.DoWork += (s, ea) => Thread.Sleep(TimeSpan.FromSeconds(2));\n\n    // ...and then set the text back to the original when the sleep is done\n    // (also, re-enable the button)\n    backgroundWorker.RunWorkerCompleted += (s, ea) =>\n    {\n        label1.Text = originalText;\n        button1.Enabled = true;\n    };\n\n    // Set the new text ("CDE" in your example)\n    label1.Text = "CDE";\n\n    // Start the background worker\n    backgroundWorker.RunWorkerAsync();\n}	0
6291982	6291933	Catch Application Exceptions in a Windows Forms Application	Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod)\n\nprivate static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t)\n{\n    //Exception handling...\n}	0
7914273	7912592	Getting All Classe names in a project	var referencedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies();\nvar referencedTypes = referencedAssemblies.SelectMany(x => Assembly.Load(x.FullName).GetTypes());	0
17903666	17903548	How declare a global array one time	private static int[] m_Array;\n\n    public static int[] Arr\n    {\n        get\n        {\n            if (m_Array == null)\n            {\n                m_Array = new int[6];\n            }\n            return m_Array;\n\n        }\n    }	0
2021708	2021681	Hide form instead of closing when close button clicked	private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n{\n   this.Hide();\n   e.Cancel = true;\n}	0
2409185	2409134	Running a vbs Sub from C#	Result = ScriptControl.Run("Name", arg1, arg2, ... argn)	0
7170082	7169912	How to Compare two "DataSet" in C#	foreach (DataTable TblDefault in ds.Tables) \\ gridview values\n{\n        foreach (DataTable Tbldefault1 in ds1.Tables) \\databasevalues\n         {\n             if (TblDefault.TableName.ToUpper().Trim() == Tbldefault1.TableName.ToUpper().Trim())\n             {\n                  //Here\n             }\n         }\n}	0
8279462	8278377	How to convert binary to string?	static string ConvertBinaryToText(List<List<int>> seq){\n    return new String(seq.Select(s => (char)s.Aggregate( (a,b) => a*2+b )).ToArray());\n}\n\nstatic void Main(){\n   string s = "stackoverflow";\n   var binary = new List<List<int>>();\n   for(var counter=0; counter!=s.Length; counter++){\n       List<int> a = ConvertTextToBinary(s[counter], 2);\n       binary.Add(a);\n       foreach(var bit in a){\n           Console.Write(bit);\n       }\n       Console.Write("\n");\n   }\n   string str = ConvertBinaryToText(binary);\n   Console.WriteLine(str);//stackoverflow\n}	0
17231472	17231344	How to delete all items from a group in ListView component c#	List<ListViewItem> remove = new List<ListViewItem>();\n\n        foreach (ListViewItem item in listView1.Groups[4].Items)\n        {\n            remove.Add(item);\n        }\n\n        foreach (ListViewItem item in remove)\n        {\n            listView1.Items.Remove(item);\n        }\n    }	0
1667674	1667501	Serialize error from user control	CheckedFolders.ToArray()	0
10019971	10011214	Ninject crashes on application start on appharbor	var kernel = new StandardKernel(new NinjectSettings { LoadExtensions = false })\nkernel.Load(new Ninject.Web.Mvc.MvcModule()); // same for all other extension modules	0
703771	703762	Populate list from array	string[] strings = { "hello", "world" };\nIList<string> stringList = strings.ToList();	0
26259508	26256409	Combination of docking and anchoring behaviours in winforms	userControl.Dock = DockStyle.Top;\npnlParent.Padding = new Padding((pnlParent.Width - userControl.Width) / 2, 0, 0, 0);\nuserControl.BringToFront();	0
27222831	27222758	How to get check box selected value from grid view? c#	foreach (GridViewRow row in GridView2.Rows)\n    {\n        if (row.RowType == DataControlRowType.DataRow)\n        {\n            CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);\n            bool chk = chkRow.Checked;\n            // Do your stuff\n        }\n    }	0
17701181	17700850	Null properties in asmx return value	XmlElement(IsNullable = true)	0
24512660	24511139	c# split string with " exception	string[] arrparams = Regex.Matches(input, @"\""(?<token>.+?)\""|(?<token>[^\s]+)")\n                    .Cast<Match>()\n                    .Select(m => m.Groups["token"].Value)\n                    .ToArray();	0
4204011	4203973	Date to String with pattern problem	String.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", yourdatetime);	0
26340933	24082305	How is PNG CRC calculated exactly?	static uint[] crcTable;\n\n// Stores a running CRC (initialized with the CRC of "IDAT" string). When\n// you write this to the PNG, write as a big-endian value\nstatic uint idatCrc = Crc32(new byte[] { (byte)'I', (byte)'D', (byte)'A', (byte)'T' }, 0, 4, 0);\n\n// Call this function with the compressed image bytes, \n// passing in idatCrc as the last parameter\nprivate static uint Crc32(byte[] stream, int offset, int length, uint crc)\n{\n    uint c;\n    if(crcTable==null){\n        crcTable=new uint[256];\n        for(uint n=0;n<=255;n++){\n            c = n;\n            for(var k=0;k<=7;k++){\n                if((c & 1) == 1)\n                    c = 0xEDB88320^((c>>1)&0x7FFFFFFF);\n                else\n                    c = ((c>>1)&0x7FFFFFFF);\n            }\n            crcTable[n] = c;\n        }\n    }\n    c = crc^0xffffffff;\n    var endOffset=offset+length;\n    for(var i=offset;i<endOffset;i++){\n        c = crcTable[(c^stream[i]) & 255]^((c>>8)&0xFFFFFF);\n    }\n    return c^0xffffffff;\n}	0
33435041	33434363	Using C# to remove custom xml tags from html	//for remove xml declarations\nhtmlString = Regex.Replace(texto, @"<\?xml.*\?>", "");\n\n//for remove costum tags like <o:p> and </o:p>\nhtmlString = Regex.Replace(texto, @"<(?:[\S]\:[\S])[^>]*>", "");\nhtmlString = Regex.Replace(texto, @"</(?:[\S]\:[\S])[^>]*>", "");	0
192146	192121	How do I use DateTime.TryParse with a Nullable<DateTime>?	DateTime? d=null;\nDateTime d2;\nbool success = DateTime.TryParse("some date text", out d2);\nif (success) d=d2;	0
1959343	1959274	filter xml based on query string	string xpath = "/Categories/Category";\nstring predicate = "";\n\nif (_food != "") {\n    predicate += "title='" + _food + "'";\n}\nif (_Cat != "") {\n    if (predicate!="") {\n        predicate += " and ";\n    }\n    predicate += "Cat='" + _Cat + "'";\n}\nif (_Description != "") {\n    if (predicate!="") {\n        predicate += " and ";\n    }\n    predicate += "Description='" + _Description + "'";\n}\n\nif (predicate!=""){\n    xpath += "[" + predicate + "]";\n}\nXPathExpression expression = nav.Compile(xpath);	0
1897948	1897872	Creating image or graphic in C# from decimal data?	using System.Drawing;\nusing System.Drawing.Imaging;\n.\n.  \n.\nusing (Bitmap bmp = new Bitmap(10, 10))\n{\n    using (Graphics g = Graphics.FromImage(bmp))\n    {\n        g.Clear(Color.White);\n        g.DrawLine(Pens.Black, new PointF(9.56f, 4.1f), new PointF(3.456789f, 2.12345f));\n    }\n    bmp.Save(@"c:\myimage.jpg", ImageFormat.Jpeg);\n}	0
31227270	31227063	How to create shortcut keys for different buttons in c#.net?	public partial class Form1 : Form\n{\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n    {\n        switch(keyData)\n        {\n            case Keys.F10:\n                Start();\n                return true;\n                break;\n\n            case Keys.F11:\n                Speak();\n                return true;\n                break;\n\n            case Keys.F1:\n                Skip();\n                return true;\n                break;\n\n            case Keys.F12:\n                Repeat();\n                return true;\n                break;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n\n}	0
15213136	15213007	Dropdownlist combined value	var query = from c in db.Persons\n            select new { id = c.ID,Names = c.FirstName + " " + c.LastName };\n\nViewBag.personid = new SelectList(query, "ID", "Names");	0
4793113	4792937	Getting KeyInput in Silverlight	protected override void OnKeyDown(KeyEventArgs e)\n{\n  // Distribute to listeners from here\n}	0
10052622	10052522	Leaving & alone in regex	new Regex(" ?&#[0-9]+").Replace("A&#1234", "")	0
4399531	4399488	adding values to the array without initialization the length	int[] a = {10};	0
26186775	26186263	Displaying different label text each second	private void Form3_Load(object sender, EventArgs e)\n    {\n        SetLabel1Text(); //reset label text\n        timer1.Interval = 5000;\n        timer1.Enabled = true;\n        timer1.Tick += new EventHandler(timer1_Tick);\n\n        timer2.Interval = 1000;\n        timer2.Start();\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        this.DialogResult = DialogResult.OK;\n        timer1.Stop();\n    }\n\n    int StopTime = 0;\n    private void timer2_Tick(object sender, EventArgs e)\n    {\n        StopTime++;\n        SetLabel1Text();\n        if (StopTime == 4)\n        {\n            StopTime = 0;\n            timer2.Stop();\n        }\n    }\n\n    private void SetLabel1Text()\n    {\n        string[] label1Text = { "  Connecting to smtp server..", "  Connecting to smtp server..", "     Fetching recipients..", "  Attaching G-code files..", "                Done!!" };\n        label1.Text = label1Text[StopTime]; //populate label from array of values\n    }	0
5193719	4845227	Weird left margin appears if using a listview	margin-left:-37px;	0
13880186	13879844	Add a custom property to a UserControl	public static readonly DependencyProperty VideoPlayerSourceProperty = DependencyProperty.Register("VideoPlayerSource", \n    typeof(System.Uri), typeof(Player),\n    new PropertyMetadata(null, (dObj, e) => ((Player)dObj).OnVideoPlayerSourceChanged((System.Uri)e.NewValue)));\n\npublic System.Uri VideoPlayerSource {\n    get { return (System.Uri)GetValue(VideoPlayerSourceProperty); } // !!!\n    set { SetValue(VideoPlayerSourceProperty, value); } // !!!\n}\nvoid OnVideoPlayerSourceChanged(System.Uri source) {\n    mediaElement.Source = source;\n}	0
25437233	18881344	RestSharp XML Deserialization into List	request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json";};	0
10679240	10678917	Convert Specific variable in XML to string C#	var xml = "<root><Data><One>data</One></Data></root>";\n\nvar xmlString = (from data in XElement.Parse(xml).Descendants("Data")\n                 where data.Descendants().Any()\n                 select data.Descendants().First().Value).FirstOrDefault();	0
17536303	17532175	Trouble getting file name from file path	try\n{\n  FileInfo fileInformation = new FileInfo(tempFileName);\n  String directory = fileInformation.DirectoryName;\n  if (tempFileName.StartsWith(directory))\n  {\n    filename = fileInformation.Name;\n  }\n}\ncatch (Exception arugmentException)\n{\n   if (!((arugmentException is ArgumentException) || \n     (arugmentException is NotSupportedException))) throw;\n}	0
27375814	27374526	Determine in a VSTO addin if a user is currently "using" Excel 2007	Public Class ThisAddIn\n\n    Private Declare Function GetForegroundWindow Lib "user32" Alias "GetForegroundWindow" () As Integer\n\n    Private Sub ThisAddIn_Startup() Handles Me.Startup\n        If GetForegroundWindow() = Application.Hwnd Then\n            MsgBox("on top")\n        End If\n    End Sub\n\n    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown\n\n    End Sub\n\nEnd Class	0
16834818	16828886	How do I reuse DataCacheFactory with Azure Caching (Co-Located)	public class DataCacheHelper\n{\n    public DataCacheHelper()\n    {\n        DataCacheFactory factory = new DataCacheFactory();\n        HttpContext.Current.Application.Lock();\n        HttpContext.Current.Application["dcf"] = factory;\n        HttpContext.Current.Application.Unock();\n    }\n\n    public DataCacheFactory GetFactory()\n    {\n        var factory = HttpContext.Current.Application["dcf"];\n        if (factory == null)\n        {\n            factory = new DataCacheFactory();\n            HttpContext.Current.Application.Lock();\n            HttpContext.Current.Application["dcf"] = factory;\n            HttpContext.Current.Application.Unock();\n        }\n        return factory;\n    }\n}	0
11297474	11297403	How to intertwine two strings or arrays, possibly with String.Join()	var query = from x in new[]{"A", "B", "C"}\n        from y in new[]{"t1", "t2"}\n        select y + "." + x;\n\nvar result = string.Join(", ", query.ToArray());	0
18045460	17862961	Matlab builder NE / MCR on Windows 8	[assembly: MathWorks.MATLAB.NET.Utility.MWMCROption("-nojit")]	0
26392225	26392176	How to escape an '&' in the password of a connection string	Ampersand = & = &amp;\nGreater Than = > = &gt;\nLess Than = < = &lt;\nApostrophe = ' = &apos;\nQuote = " = &quot;"	0
1006536	1006518	How can i make a Method that rounds to the next 5er digit?	int rounded  = 5 * Math.Ceiling( (double)original / 5 );	0
29592825	29590305	Open a website on client's computer from the server	Captive portal	0
2843204	2840925	How to change the coordinate of a point that is inside a GraphicsPath?	GraphicsPath UpdateGraphicsPath(GraphicsPath gP, RectangleF rF, PointF delta)\n{\n    // Find the points in gP that are inside rF and move them by delta.\n\n    PointF[] updatePoints = gP.PathData.Points;\n    byte[] updateTypes = gP.PathData.Types;\n    for (int i = 0; i < gP.PointCount; i++)\n    {\n        if (rF.Contains(updatePoints[i]))\n        {\n            updatePoints[i].X += delta.X;\n            updatePoints[i].Y += delta.Y;\n        }\n    }\n\n    return new GraphicsPath(updatePoints, updateTypes);\n}	0
8359510	8359267	XDocument Parse String - Null Terminator Issue	messageString.Trim(' ', '\0', ....);	0
30331168	30330201	Error retrieving a value from DataGrid	MyDataGridCell.Content	0
821116	820947	Databinding for checkbox with stringvalues	Binding binding = new Binding("checked", dt, "string_field");\n    binding.Format += new ConvertEventHandler(binding_Format);\n    binding.Parse += new ConvertEventHandler(binding_Parse);\n    this.checkbox1.DataBindings.Add(binding); \n\n    void binding_Format(object sender, ConvertEventArgs e)\n    {\n        if (e.Value.ToString() == "yep") e.Value = true;\n        else e.Value = false;\n    }\n\n    void binding_Parse(object sender, ConvertEventArgs e)\n    {\n        if ((bool)e.Value) e.Value = "yep";\n        else e.Value = "nope";\n    }	0
5463341	5460099	How to build a new NUnit constraint	public static void IsEither<T>(this T value, params T[] allowedValues)\n{\n    CollectionAssert.Contains(allowedValues, value);\n}	0
8109124	8059628	How to compute a summation to a specified number of terms in c#?	using System;\nusing W3b.Sine;\n\nnamespace summation\n{\n    public class Program\n    {\n        static BigNum doSummation(int maxPower)\n        {\n            BigNum sum = 0;\n            for (int i = 1; i <= maxPower; i++)\n            {\n                sum += Math.Pow(2, i * -1);\n            }\n            return sum;\n        }\n        static void Main(string[] args)\n        {\n          Console.WriteLine(doSummation(100));\n        }\n    }\n}	0
16965062	16103857	Build LambdaExpression with custom parameter selection	/// <summary>\n/// Returns a queryable sequence of TResult elements which is composed through specified property evaluation.\n/// </summary>\npublic static IQueryable<TResult> WithInfo<TItem, TProperty, TResult>(this IQueryable<TItem> q, Expression<Func<TItem, TProperty>> propertySelector, Expression<Func<TItem, TProperty, TResult>> resultSelector)\n{\n    ParameterExpression param = Expression.Parameter(typeof(TItem));\n    InvocationExpression prop = Expression.Invoke(propertySelector, param);\n\n    var lambda = Expression.Lambda<Func<TItem, TResult>>(Expression.Invoke(resultSelector, param, prop), param);\n    return q.Select(lambda);\n}	0
46384	46377	How do I specify multiple constraints on a generic type in C#?	public class Animal<SpeciesType,OrderType>\n    where SpeciesType : Species\n    where OrderType : Order\n{\n}	0
4996603	4996582	Default value for bool in c#	public bool? PrepaymentCalculating { get; set; }	0
3246567	3246505	How can I get the name of the field from an expression?	public string GetMemberName<T>(Expression<Func<T>> expr)\n{\n    var memberExpr = expr.Body as MemberExpression;\n    if (memberExpr == null)\n        throw new ArgumentException("Expression body must be a MemberExpression");\n    return memberExpr.Member.Name;\n}\n\n...\n\nMyClass x = /* whatever */;\nstring name = GetMemberName(() => x.Something); // returns "Something"	0
22770549	22770490	How can I convert part of a GUID to a long?	Guid g = new Guid("57F67098-00A9-4F78-A729-4234F5AC512C");\nint pos = g.ToString().LastIndexOf('-');\nstring part = g.ToString().Substring(pos+1);\nlong result = Convert.ToInt64(part, 16);\nConsole.WriteLine(result.ToString());	0
31803578	31803286	Image in body of the Mail C#	string attachmentPath = Environment.CurrentDirectory + @"\test.png";\nAttachment inline = new Attachment(attachmentPath);\ninline.ContentDisposition.Inline = true;\ninline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;\ninline.ContentId = contentID;\ninline.ContentType.MediaType = "image/png";\ninline.ContentType.Name = Path.GetFileName(attachmentPath);\n\nmessage.Attachments.Add(inline);	0
4247620	4247180	Using integer enum without casting in C#	switch ((Test)IntTest)\n{\n    case (Test.TestValue1) : DoSomething();\n                             break;\n    case (Test.TestValue2) : DoSomethingElse();\n                             break;\n    default                : DoNothing();\n}	0
29318017	29238024	How to remove a part of a image using another image	public static Bitmap RemovePart(Bitmap source, Bitmap toRemove)\n{\n    Color c1, c2, c3;\n    c3 = Color.FromArgb(0, 0, 0, 0);\n    for (int x = 0; x < source.Width; x++)\n    {\n       for (int y = 0; y < source.Height; y++)\n       {\n           c1 = source.GetPixel(x, y);\n           c2 = toRemove.GetPixel(x, y);\n           if (c2 != c3)\n           {\n               source.SetPixel(x, y, Color.FromArgb(c2.A, c1));\n           }\n       }\n    }\n}	0
4982435	4981526	Output to a Picture Box Alternative	private void pictureBox1_Paint(object sender, PaintEventArgs e)\n{\n    using (Font myFont = new Font("Microsoft Sans Serif", 10))\n    {\n        e.Graphics.DrawString("This time is...Hammertime", myFont, Brushes.Black, new Point(0,0));\n    }\n}	0
19488498	18851919	Write from Resource to file where resource could be text or image	/// <summary>\n    /// Copies all the files from the Resource Manifest to the relevant folders. \n    /// </summary>\n    internal void CopyAllFiles()\n    {\n        var resourceFiles = Assembly.GetExecutingAssembly().GetManifestResourceNames();\n\n        foreach (var item in resourceFiles)\n        {\n            string basePath = Resources.ResourceManager.BaseName.Replace("Properties.", "");\n\n            if (!item.Contains(basePath))\n                continue;\n\n\n            var destination = this._rootFolder + "\\" + this._javaScriptFolder + "\\" + item.Replace(basePath + ".", "");\n\n            using (Stream resouceFile = Assembly.GetExecutingAssembly().GetManifestResourceStream(item))\n            using (Stream output = File.Create(destination))\n            {\n                resouceFile.CopyTo(output);\n            }\n        }\n    }	0
18677390	18677308	Array null element HasValue construct	vm[0].CustomerId.HasValue	0
21852127	21849516	Setting image source dynamically using a converter- windows phone 8	public class typeconverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        string text = value.ToString();\n\n        if (text != null)\n        {\n            if (text == "1")\n            {\n               return "/Assets/call.png";                    \n            }\n            if (text == "2")\n            {\n               return "/Assets/wtp.png";                   \n            }\n\n        }\n\n        return value;\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n    {\n        return value;\n    }\n}	0
12249266	12243558	Open StorageItem in default program in WinRT?	Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(fileToOpen).done(\n            function (file) {\n                Windows.System.Launcher.launchFileAsync(file).done(\n                    function (success) {\n                        // anything you want to do after default program launched        });\n            });	0
7489149	7489035	How to turn textual qualified data to a tree	public class Main\n    {\n        public Main()\n        {\n            string treeStr = "";\n\n            string[] strArr = { "a.b.c.d.e.f.g", "b.c.d.e.f.g.h.x" };\n\n            List<Node> nodes = new List<Node>();\n            Node currentNode;\n\n            foreach (var str in strArr)\n            {\n                string[] split = str.Split('.');\n                currentNode = null;\n\n                for (int i = 0; i < split.Length; i++)\n                {\n                    var newNode = new Node { Value = str };\n\n                    if (currentNode != null)\n                    {\n                        currentNode.Child = newNode;\n                    }\n                    else\n                    {\n                        nodes.Add(newNode);\n                    }\n\n                    currentNode = newNode;\n                }\n            }\n        }\n\n\n    }\n\n    public class Node\n    {\n        public string Value { get; set; }\n        public Node Child { get; set; }\n    }	0
15359942	15359641	Entity Framework, how to get Sum<> accept a method?	db.FlightEntries().ToArray().Sum(f => f.GetTotalflightTimes());	0
16689783	16689636	how to maintain checkbox check status on paging link click in datagridview in C#	bool Checked	0
20399593	20399571	How to 'unescape' a string that is appearing different from the file it comes from?	Response.Write	0
17913678	17913567	Prevent decompilation of password data	System.Security.Cryptography	0
21179807	21178904	convert string to css c#	dotless.Core.Less.Parse("@abc:black")	0
22949035	17476037	Add watch without complete namespace in Visual Studio	// Main.cs\nusing System;\nnamespace TestCon\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Foo foo = new Foo();\n\n            Console.WriteLine(Convert.ToString(123));\n            Console.WriteLine(Convert.ToInt32("234"));\n        }\n    }\n}\n\n//Foo.cs (note that there are no using statements in this file)\nnamespace TestCon\n{\n    class Foo\n    {\n       public Foo()\n       { }\n    }  \n}	0
6294153	6293952	sql stored procedure - Having problems retreiving multiple rows of data with Idatareader	List<string> titles = new List<string>();\nusing (IDataReader test = ((IDataReader)(DataProvider.Instance().ExecuteReader("fetchtest"))))\n{\n    while (test.Read())\n    {\n       titles.Add(test.GetString(0));\n    }\n}\n\n\ntitle1.Text = titles[0];\ntitle2.Text = titles[1];\ntitle3.Text = titles[2];\ntitle4.Text = titles[3];	0
6860050	6860007	Abstract base class that inherits ICollection<T>	public abstract class BaseTimeCollection : ICollection<Time>\n{\n    protected abstract IEnumerator IEnumerable_GetEnumerator();\n    protected abstract IEnumerator<Time> GenericEnumerable_GetEnumerator();\n\n    IEnumerator IEnumerable.GetEnumerator() \n    { \n        return IEnumerable_GetEnumerator(); \n    }\n\n    IEnumerator<Time> IEnumerable<Time>.GetEnumerator()\n    {\n        return GenericEnumerable_GetEnumerator();\n    }\n}	0
23776444	23776323	How to pass ControllerBase as parameter	public ActionResult Index() {\n    this._someHelper.ReturnViewBag(this, someQuery);\n    return View();\n}	0
27660757	27505534	Json.Net - How to deserialize only if types are matching	public class Event\n{\n            [JsonProperty(PropertyName = "_id")]\n            public string Id { get; set; }\n            [JsonProperty(PropertyName = "status"]\n            public dynamic Status { get; set; }\n}	0
13295783	13295717	Set a Value Before Button is Pushed	UpdateSourceTrigger=PropertyChanged	0
1105614	1105593	Get file name from URI string in C#	Uri uri = new Uri(hreflink);\nif (uri.IsFile) {\n    string filename = System.IO.Path.GetFileName(uri.LocalPath);\n}	0
19213290	19211048	How to get page name with webBrowser	TabControl.SelectedTab.Text = webBrowser1.Url.AbsoluteUri;	0
9049170	9047390	Lock a single access variable for parallel threads in C#	int n = 2;\n\n        Task[] producers = Enumerable.Range(1, 3).Select(_ => \n            Task.Factory.StartNew(() =>\n                {\n                    while (queue.Count < n)\n                    {\n                        lock (queue)\n                        {\n                            if (!queue.Contains(n))\n                            {\n                                Console.WriteLine("Thread" + Task. CurrentId);\n                                queue.Add(n);\n\n                                Interlocked.Increment(ref n);\n                            }\n                        }\n\n                        Thread.Sleep(100);\n                    }\n                }))\n            .ToArray();	0
3828403	3826841	How can I see if one string loosely contains another (case, extra whitespace, and punctuation ignored)?	newSearchString = Regex.Replace(Regex.Escape(searchString), @"\s+", @"[\s\p{P}]+");	0
1225719	1225710	LINQ TO DataSet: Multiple group by on a data table	var groupQuery = from table in MyTable.AsEnumerable()\ngroup table by new { column1 = table["Column1"],  column2 = table["Column2"] }\n      into groupedTable\nselect new\n{\n   x = groupedTable.Key,  // Each Key contains column1 and column2\n   y = groupedTable.Count()\n}	0
6598999	6598903	LINQ ordering by highest value per unique value in a certain column	var query = (from bid in context.Bids\n            group bid by bid.userid into bidg\n            select new\n            {\n               bidId = bidg.OrderByDescending(b => b.bidValue).First().bidid,\n               userid = bidg.Key,\n               bidValue = bidg.Select(b => b.bidValue).Max()\n            }).OrderByDescending(b => b.bidvalue);	0
22804617	7057970	Motion detection regions for Aforge.Net	//Please explain here => if the motion region is out of bounds crop it to the image bounds\nrect.Intersect( imageRect );\n\n//Please explain here => gets the image stride (width step), the number of bytes per row; see:\n//http://msdn.microsoft.com/en-us/library/windows/desktop/aa473780(v=vs.85).aspx\nint stride = zonesFrame.Stride;\n\n//Please explain here => gets the pointer of the first element in rectangle area\nbyte* ptr = (byte*) zonesFrame.ImageData.ToPointer( ) + rect.Y * stride + rect.X;\n\n//mask the rectangle area with 255 value. If the image is color every pixel will have the    //(255,255, 255) value which is white color\nfor ( int y = 0; y < rectHeight; y++ )\n{\n    //Please explain here\n    AForge.SystemTools.SetUnmanagedMemory( ptr, 255, rectWidth );\n    ptr += stride;\n}	0
9496085	9495997	GroupBy, then order another list based on group in C#	from item in GetAllItems()\njoin vote in GetAllVotes() on item.ItemId equals vote.VoteId into votes\norderby votes.Count() descending, item.CreatedDate\nselect new { Item = item, Votes = votes.Count() };	0
5970610	5970581	Which encoding to use for reading a string from a file?	E2 80 94	0
8526268	8526214	C# Regex match anything inside Parentheses	resultString = Regex.Match(subjectString, @"(?<=\().+?(?=\))").Value;	0
32343768	32343750	Retrieve a date from DB and compare it with current date	if(DateTime.Now < Convert.ToDateTime(actual_checkout))\n  {\n      // do some operations here\n  }	0
30675233	30675110	Insert text between 2 delimeters	var s1 = "there~is~a~~cat";\nvar s2 = "super";\nvar words = s1.Split('~').ToList();\n//words.Insert(3, s2); // this will insert new token\nwords[3] = s2; // this will replace word at specific index\nvar res = string.Join("~", words.ToArray());	0
10604836	10604744	Linq to XML infanticide - Is there a simple expedient way to promote grandchildren to replace children?	var usurper = family.Root.Descendants("g").ToList();	0
33463172	33462874	Resizing controls in WinForm Designer by 32px-steps (VS15)	class MyGrid : Control {\n    private const int pitch = 32;\n\n    protected override void OnClientSizeChanged(EventArgs e) {\n        var w = pitch * ((this.ClientSize.Width + pitch/2) / pitch);\n        var h = pitch * ((this.ClientSize.Height + pitch/2) / pitch);\n        if (w != this.ClientSize.Width || h != this.ClientSize.Height)\n            this.ClientSize = new Size(w, h);\n        else base.OnClientSizeChanged(e);\n    }\n}	0
26753104	26753043	Find closest value in an array List with linq?	var x = 700;\nvar result = list.Select((subList, idx) => new { Value = subList[1], Idx = idx })\n                 .Where(elem => elem.Value < x)\n                 .Select(elem => new { Diff = Math.Abs(x - elem.Value), elem.Idx })\n                 .OrderBy(elem => elem.Diff).FirstOrDefault();\n\nif (result != null)\n{\n    return result.Idx;\n}\n\n// case - there is no such index	0
19895523	19895432	How to understand whether client connected to server in c#?	private void Accept()\n    {\n        try {\n            n = server_socket.Accept();\n            richTextBox_server_activity_log.AppendText("Connection Established...");\n        } catch (Exception ex) {\n            richTextBox_server_activity_log.AppendText("Failed to Connect...");\n        }\n    }	0
6299485	6299400	Can the debugger tell me a count/status of a foreach loop?	public class ATest\n    {\n        public int number { get; set; }\n        public int boo { get; set; }\n        public ATest()\n        {\n\n        }\n    }\n\n    protected void Go()\n    {\n        List<ATest> list = new List<ATest>();\n\n        foreach(var i in Enumerable.Range(0,30)) {\n            foreach(var j in Enumerable.Range(0,100)) {\n                list.Add(new ATest() { number = i, boo = j });                  \n            }\n        }\n\n        var o =0; //only for proving concept.\n        foreach (ATest aTest in list)\n        {               \n            DoSomthing(aTest);\n            //proof that this does work in this example.\n            o++;\n            System.Diagnostics.Debug.Assert(o == list.IndexOf(aTest));\n        }\n\n    }	0
23494909	23494367	Default getter for IList<T>	public static class PropertyHelper\n{\n    public static T Get<T, U>(ref T backingField, U initialValue = null)\n        where T : class\n        where U : class, T, new()\n    {\n        initialValue = initialValue ?? new U();\n        return backingField ?? (backingField = initialValue);\n    }\n}\n\npublic class MyClass\n{\n    private IList<int> myVar;\n\n    public IList<int> MyProperty\n    {\n        get { return PropertyHelper.Get<IList<int>, List<int>>(ref myVar); }\n        set { myVar = value; }\n    }\n\n    private IList<int> myVar2;\n\n    public IList<int> MyProperty2\n    {\n        get { return PropertyHelper.Get(ref myVar2, new List<int>()); }\n        set { myVar2 = value; }\n    }\n}	0
13554028	13553667	ListBox, Select index change	Visits v = new Visit();\nPickups p = new Pickup();\nlstVisits.Items.Add(v);\nlstVisits.Items.Add(p);    \n\n\nprivate void lstVisits_SelectedIndexChanged(object sender, EventArgs e)\n            {\n                if (listBox1.SelectedItems.Count > 0)\n                {\n                    object o = listBox1.SelectedItems[0];\n                    if (o is Visits)\n                    {\n                        Visits visit = (Visits)o;\n                        Visitsform.visits = visit;\n                        Visitsform.ShowDialog();\n                    }\n                    else\n                    {\n                        Deliveries delivery = (Deliveries)o;\n                        Deliveriesform.visits = visit;\n                        Deliveriesform.ShowDialog();\n                    }\n                }\n            }	0
3878828	3878820	C#: how to get first char of a string?	MyString[0]	0
4454519	4454423	C# Listbox Item Double Click Event	void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)\n    {\n         int index = this.listBox1.IndexFromPoint(e.Location);\n         if (index != System.Windows.Forms.ListBox.NoMatches)\n            {\n              MessageBox.Show(index.ToString());\n            }\n     }	0
31870110	31864259	SQL Server Compact Edition Data Access with the SqlCeResultSet in Visual Studio 2013	SqlCeCommand cmd = new SqlCeCommand("SELECT [Employee ID], [Last Name], [First Name], Photo FROM Employees",_conn);\n _conn.Open();\n SqlCeResultSet resultSet = cmd.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);\n this.bindingSource1.DataSource = resultSet;	0
9321886	9321844	How do I clear a combobox?	cboxHour.Items.Clear()	0
34252447	34117658	unclickable reblog button in tumblr (in pop up window)	Thread.Sleep(15000);\n//or \n_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));	0
23829688	23809044	C++ COM DLL for use in C#	inproc server	0
32419892	32419864	Combine items from two listboxes into a third listbox	private void button1_Click(object sender, EventArgs e)\n{\n    for (int i = 0; i < listBox1.Items.Count; i++)\n    {\n        A =  listBox1.Items[i].ToString();\n        for (int j = 0; j < listBox2.Items.Count; j++)\n        {\n            B = listBox2.Items[j].ToString();\n            listBox3.Items.Add(A + ": " + B);\n        }\n    }\n}	0
2326976	2326788	how to send email via smartermail?	var client = new SmtpClient("hostnameOfYourSmtpServer");\nvar from = new MailAddress("from@example.com");\nvar to = new MailAddress("to@example.com");\nvar message = new MailMessage(from, to);\nmessage.Subject = "test subject";\nmessage.Body = "This is a test e-mail message sent by an application. ";\nclient.Send(message);	0
15136173	15136041	Json.Net How to deserialize null as empty string?	[DataMember]\n[JsonProperty(PropertyName = "email")]\n[StringLength(40, ErrorMessage = "The Mobile value cannot exceed 40 characters. ")]\n[DefaultValue("")]\npublic string Email { get; set; }	0
14496441	14495883	Encapsulation of Text property in user control	// This is necessary to show the property on design mode.\n    [Browsable(true)] \n    // This is necessary to serialize the value.\n    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] \n    public override string Text\n    {\n        get\n        {\n            return this.label1.Text;\n        }\n        set\n        {\n            this.label1.Text = value;\n        }\n    }	0
25461345	25460729	How to create common method used in Web form as well as Windows form	abstract Class Demo\n{\n\n      public object GetData<T>(T obj) where T : objectname;\n\n}	0
15777856	15777841	Pass a function to another function in c# to call on a given model	IsAnswerValid<Answer>(survey, "1.1.1", i, a => a.Something || a.SomethingElse);	0
7586930	7586629	Implementing explicit interface members with generics	public abstract class Something: ISomething  \n{ \n    ISomething ISomething.Clone() \n    { \n        return CloneYouMust();\n    } \n    abstract ISomething CloneYouMust();\n}	0
16959555	16959361	C# min from datatable row	List<int> result = new List<int>();\nforeach (DataRow row in table.Rows)\n{\n    result.Add(row.ItemArray.Cast<int>().Min());\n}	0
8066767	8066535	WinForms - How to open and show a pdf you just saved using iTextSharp?	Process.Start("filename.pdf");	0
33980861	33686635	Populate Datagrid from WCF when page is loaded WPF	ContextOptions.ProxyCreationEnabled = false;	0
26085608	26085530	What is the easiest way to show difference between two dates into the largest date range description?	FromDays(1).Humanize(precision:2) => "1 day" // no difference when there is only one unit in the provided TimeSpan\nTimeSpan.FromDays(16).Humanize(2) => "2 weeks, 2 days"\n\n// the same TimeSpan value with different precision returns different results\nTimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"\nTimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"\nTimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"\nTimeSpan.FromMilliseconds(1299630020).Humanize(5) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"	0
21577689	21576929	Fill listboxes from XML-file	private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{    \n    XmlNode nodes = xDoc.SelectSingleNode(String.Format("/students/student[id={0}]/data", listBox1.SelectedItem));\n    foreach (XmlNode node in nodes.ChildNodes)\n    {\n         if (node.Attributes["status"].Value == "passed")\n             listBox2.Items.Add(node.Attributes["name"].Value);\n    }\n}	0
31247774	31247477	How to add weighting curve to random selection	public double GetWeightedRandom(int min, int max)\n{\nRandom random = new Random();\ndouble randomZeroToOne = random.NextDouble();\ndouble weightedRandom = randomZeroToOne * randomZeroToOne * (max - min) + min;\nreturn weightedRandom;\n}	0
4800763	4800731	How to omit checking for SqlNullValueException in Mysql Connector/NET	product.EndTime = reader["endtime"] as DateTime? ?? DateTime.MinValue;\nproduct.Description = reader["description"] as string;\nproduct.Type = reader["type"] as string;	0
8562457	8535102	Inconsistent Results with RichTextBox ScrollToCaret	[DllImport("user32.dll", CharSet = CharSet.Auto)]\nprivate static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);\nprivate const int WM_VSCROLL = 277;\nprivate const int SB_PAGEBOTTOM = 7;\n\npublic static void ScrollToBottom(RichTextBox MyRichTextBox)\n{\n    SendMessage(MyRichTextBox.Handle, WM_VSCROLL, (IntPtr)SB_PAGEBOTTOM, IntPtr.Zero);\n}	0
12293333	12293314	Regex matching IP	Uri url = new Uri("ftp://52.42.12.52:7000/");\nConsole.Write(url.Host);	0
3947619	3947596	Extract string between braces using RegEx, ie {{content}}	ICollection<string> matches =\n    Regex.Matches(s.Replace(Environment.NewLine, ""), @"\{\{([^}]*)\}\}")\n        .Cast<Match>()\n        .Select(x => x.Groups[1].Value)\n        .ToList();\n\nforeach (string match in matches)\n    Console.WriteLine(match);	0
24772472	24771767	how to add data to a specific range of cells in column	// Setup table with 5 columns\nDataTable table = new DataTable();\ntable.Columns.Add("A", typeof(bool));\ntable.Columns.Add("B", typeof(bool));\ntable.Columns.Add("C", typeof(bool));\ntable.Columns.Add("D", typeof(bool));\ntable.Columns.Add("E", typeof(bool));\n\n// Add 20 rows\nfor (int i = 0; i < 20; i++ )\n    table.Rows.Add(true, true, true, true, true);\n\n// Rows 10 - 15, set column 5 to true\nfor (int i = 9; i < 15; i++)\n    table.Rows[i].SetField<bool>(4, false);	0
12120304	12120188	How to insert a record in a child table?	com.CommandText = " Insert into recommendedvideos(Variable, User, Date, Status )"\n                + "VALUES(@Variable, @User, @Date, @Status )";\n\n        com.Parameters.AddWithValue("@Variable", Variable);\n        com.Parameters.AddWithValue("@User", User);\n        com.Parameters.AddWithValue("@Date", Date);\n        com.Parameters.AddWithValue("@Status", Status);\n\n        connect.Open();\n        com.ExecuteNonQuery();\n        connect.Close();	0
15613183	15612074	CopyTo with CancellationToken argument	public static void CopyTo(this Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken)\n{\n    var buffer = new byte[bufferSize];\n    int count;\n    while ((count = source.Read(buffer, 0, buffer.Length)) != 0)\n    {\n        cancellationToken.ThrowIfCancellationRequested();\n        destination.Write(buffer, 0, count);\n    }\n}	0
17142413	17142110	How To add gridview cell automatically	table.Rows.Clear(); //to ensure the table does not contains any rows\n table.Rows.Add(txt2-txt1);\n int i = txt1;\n  for (int j = 0; j < dataGridView1.Rows.Count; j++)\n      {\n         dataGridView1.Rows[j].Cells["id"].Value = i.ToString();\n         i++;\n      }	0
26416111	26416044	SQL Server - How to check a row can be deleteable before deleting	DELETE from TableA where ID in (select ID from tableA a left outer join tableB b on a.ID = b.ID where b.ID is NULL)	0
21956029	21955752	TextBox and On Screen Keyboard	On Screen Keyboard	0
17011903	17009736	Database isn't generated from model	: base("name=DatabaseContext")	0
5690198	5690125	C# application/game, best approach	class Question\n{\n     public string QuestionText {get;}\n     public Answer AnswerA { get; }\n     public Answer AnswerB { get; }\n     public Answer AnswerC { get; }\n     public Answer AnswerD { get; }\n     public Answer ChosenAnswer { get;set;}\n}\n\nclass Answer\n{\n    public string AnswerText { get; }\n}	0
33124638	33123998	Razor View Page as Email Template	RazorFolderHostContainer host = = new RazorFolderHostContainer();\nhost.ReferencedAssemblies.Add("NotificationsManagement.dll");\nhost.TemplatePath = templatePath;\nhost.Start();\nstring output = host.RenderTemplate(template.Filename, model);\n\nMailMessage mm = new MailMessage { Subject = subject, IsBodyHtml = true };\nmm.Body = output;\nmm.To.Add(email);\n\nvar smtpClient = new SmtpClient();\nawait smtpClient.SendMailAsync(mm);	0
16055179	15707927	get filespecs using a changelist number	int id = int.Parse(change);\nChangelist changelist= rep.GetChangelist(id);\nIList <Perforce.P4.FileMetaData> files= changelist.Files;\nforeach (FileMetaData fmd in files)\n    { \n                //get the depot path and create instances from filespec            \n\n    }	0
4035405	4031454	Two datagridviews in one windows form = not possible to save data to the second datagridview	private void tableMeLikeBindingNavigatorSaveItem_Click(object sender, EventArgs e)\n  {\n     try\n     {\n        this.Validate();\n        this.tableMeLikeBindingSource.EndEdit();\n\n        // IMPORTANT: the following predefined generic Update command\n        // does NOT work (sometimes)\n        // this.tableAdapterManager.UpdateAll(this.rESOURCE_DB_1DataSet);\n\n        // instead we explicitely points out the right table adapter and updates\n        // only the table of interest...\n        this.tableMeLikeTableAdapter.Update(this.rESOURCE_DB_1DataSet.TableMeLike);\n     }\n\n     catch (Exception ex)\n     {\n        myExceptionHandler.HandleExceptions(ex);\n     }\n  }	0
13971162	13944422	How can I set my comboBox values to a default value that they contain?	var item = comboBoxToHour.Items.FirstOrDefault(p => (p as ComboBoxItem).Content.ToString() == "4");\nif (item != null)\n{\n    comboBoxToHour.SelectedItem = item;\n}	0
2771310	2771287	how to find file's path according to filename?	public static String SearchFileRecursive(String baseFolderPath, String fileName)\n    {\n        // Returns, if found, the full path of the file; otherwise returns null.\n        var response = Path.Combine(baseFolderPath, fileName);\n        if (File.Exists(response))\n        {\n            return response;\n        }\n\n        // Recursion.\n        var directories = Directory.GetDirectories(baseFolderPath);\n        for (var i = 0; i < directories.Length; i++)\n        {\n            response = SearchFileRecursive(directories[i], fileName);\n            if (response != null) return response;\n        }\n\n        // { file was not found }\n\n        return null;\n    }	0
398694	398176	ListBox with overriden CreateParams doesn't raise item events	public partial class Form1 : Form {\n    MyListBox mList;\n    public Form1() {\n      InitializeComponent();\n    }\n\n    protected override void OnLoad(EventArgs e) {\n      mList = new MyListBox(this);\n      mList.Location = new Point(5, 10);\n      mList.Size = new Size(50, this.ClientSize.Height + 50);\n      for (int ix = 0; ix < 100; ++ix) mList.Items.Add(ix);\n      mList.SelectedIndexChanged += new EventHandler(mList_SelectedIndexChanged);\n    }\n\n    void mList_SelectedIndexChanged(object sender, EventArgs e) {\n      MessageBox.Show(mList.SelectedIndex.ToString());\n    }\n\n    protected override void Dispose(bool disposing) {\n      // Moved from Designer.cs file\n      if (disposing) mList.Dispose();\n      if (disposing && (components != null)) {\n        components.Dispose();\n      }\n      base.Dispose(disposing);\n    }\n\n  }	0
16596214	16595905	How to Remove ~ character from asp HyperLink	// root filesystem path for the application (C:\inetpub\wwwroot\ideaPark)\nstring virtualPathRoot = AppDomain.CurrentDomain.BaseDirectory;\n\n// path relative to the application root (/DesktopModules/ResourceModule/pdf_resources/)\nstring relativePath = savePathPDF_Resouce.TrimStart("~");\n\n// save here\nstring targetPath = Path.Combine(virtualPathRoot, relativePath);	0
18079984	18079880	writing returned results to JSON	var resultslist = _example.GetExample("Testing");\n\n var result = new DataSourceResult()\n {\n    Data = resultslist \n };\n return Json(result, JsonRequestBehavior.AllowGet);	0
12309705	12309598	parse hierarchic xml	using System.Xml.Linq;\nusing System.Xml.XPath;\n\n. . . \n\nvoid PrintMenu(XElement menuElement, string prefix)\n{\n  string newPrefix = prefix + "-";\n  foreach (XElement subMenuElement in menuElement.XPathSelectElements("MenuItem")) {\n    Console.WriteLine(prefix+(string)subMenuElement.Attribute("Name"));\n    PrintMenu(subMenuElement, newPrefix);\n  }\n}\n\n. . . \n\nXElement doc = XElement.Parse(DataXml); \nPrintMenu(doc, String.Empty);	0
28708225	28706431	How to deny access to directory contents (IIS served site) via browser	using (System.Security.Principal.WindowsImpersonationContext wic = \n     System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero))\n{\n    FileStream file = new FileStream(Server.MapPath("~/SiteFolder/example.txt"), FileMode.Append, FileAccess.Write, FileShare.Write);\n    using (StreamWriter fileWriter = new StreamWriter(file))\n    {\n         fileWriter.WriteLine("Something");\n    }\n}	0
30008553	30008530	TimeSpan countdown timer	private TimeSpan ts = TimeSpan.FromSeconds(10)\n...\nts = ts.Subtract(TimeSpan.FromSeconds(1));\nlabel4.Text = ts.ToString(@"hh\:mm\:ss");	0
16945481	16342757	how can I temporarily blank a Windows-7 2nd display monitor, in C#?	[DllImport("user32.dll")]\n    static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n\n    private const int WM_SYSCOMMAND = 0x0112;\n    private const int SC_MONITORPOWER = 0xF170;\n    private const int MonitorTurnOn = -1;\n    private const int MonitorShutoff = 2;\n\n    //Turn them off\n    public static void turn_off_monitors()\n    {\n        Form f = new Form();\n\n        SendMessage(f.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorShutoff);\n    }\n\n\n    //Turn them on\n    public static void turn_on_monitors()\n    {\n        Form f = new Form();\n\n        SendMessage(f.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorTurnOn);\n    }	0
34398793	34398140	how to code in this session log	Session session = new Session();\n  session.SessionLogPath =  "D:/pathForYourLogFile"	0
2366748	2366684	How to implement a cancel event in C#	private event _myEvent;\n\n// ...\n\n// Create the event args\nCancelEventArgs args = new CancelEventArgs();\n\n// Fire the event\n_myEvent.DynamicInvoke(new object[] { this, args });\n\n// Check the result when the event handler returns\nif (args.Cancel)\n{\n    // ...\n}	0
32344792	32344596	Get height of Parent	Canvas parentOfThumb = thumbSender.Parent as Canvas;\nif (parentOfThumb != null) //if in case Parent is not canvas\n    int p = parentOfThumb.ActualHeight;	0
5208384	5208360	Asynchrony, doing simple but time consuming actions	// Disable your UI...\n\n// Start your "work"\nvar task = Task.Factory.StartNew( () =>\n{\n    // Do your processing here...\n});\n\ntask.ContinueWith( t =>\n{\n    // Report results and re-enable UI here...\n\n}, TaskScheduler.FromCurrentSynchronizationContext());	0
16442459	16442414	How is an Enumerable converted to a Dictionary?	var row = sheetData.Elements<Row>()\n                   .FirstOrDefault(r => r.RowIndex == rowIndex);\nif (row != null)\n{\n    // Use row\n}	0
7530414	7529827	Replace strings only outside of quotes using RegEx	string a = "varA*varB%+Length('10%')";\n    string[] b = a.Split('\'');\n    string c = string.Empty;\n    int i = 0;\n    foreach (string sbs in b)\n    {\n        c += i%2==0?sbs.Replace("%","/100"):"'" + sbs + "'";//for the every odd value of i "%" is within single quotes\n        i++;\n    }	0
22411684	22407537	Linq to NHibernate return entities whose name starts with contents of string list	var query = session.QueryOver<Entity>();\nvar disjunction = new Disjunction();\n\nforeach (var s in listOfStrings)\n{\n    disjunction.Add(Restrictions.On<Entity>(e => e.Name)\n        .IsLike(s, MatchMode.Start));\n}\n\nvar result = query.Where(disjunction).List();	0
2705188	2705163	C#: Abstract classes need to implement interfaces?	interface IFoo\n{\n    void Bar();\n}\n\nabstract class Foo : IFoo\n{\n    public abstract void Bar();\n}	0
22696769	22696660	Data transfer issues using network stream	NetworkStream.Read	0
14831164	14831095	Register custom C# assemblies in the GAC	gacutil /i myown.dll	0
22913266	22913153	XDocument LINQ search based on attribute	IEnumerable<XElement> v = from narrationEvent in events.Descendants("NarrationEvent")\n                          where narrationEvent.Attribute("code").Value == code\n                          select narrationEvent;	0
1456550	1455206	Simple, quick way to get user input in WPF?	Microsoft.VisualBasic.Interaction.InputBox("Prompt here", \n                                           "Title here", \n                                           "Default data", \n                                           -1,-1);	0
17144636	17144441	Moq how determine a method was called with a list containing certain values	mockPaymentLogic.Verify(x => x.GeneratePaymentStatus(It.Is<IList<int>>(l => l.Contains(2) && l.Contains(3))));	0
3187608	3187468	Test Credentials to access a web page	.Credentials	0
2547687	2547617	Generic foreach loop in C#	public delegate Y Function<X,Y>(X x);\n\npublic class Map<X,Y>\n{\n    private Function<X,Y> F;\n\n    public Map(Function<X,Y> f)\n    {\n        F = f;\n    }\n\n    public ICollection<Y> Over(ICollection<X> xs){\n        List<Y> ys = new List<Y>();\n        foreach (X x in xs)\n        {\n            X x2 = x;//ys.Add(F(x));\n        }\n        return ys;\n    }\n}	0
33685670	33685128	Solving with only loop	public static int smallest(int n)\n    {\n        int i = 1;\n        for (; ; )\n        {\n            int contain = 0;\n            int temp = 0;\n            int myNum = 0;\n            for (int j = 1; j <= n; j++)\n            {\n                myNum = i * j;\n                temp = myNum;\n\n                while (true)\n                {\n                    if (temp % 10 == 2)\n                    {\n                        contain++;\n                        break;\n                    }\n\n                    temp = temp / 10;\n                    if (temp <= 0)\n                        break;\n                }\n            }\n            if (contain == n)\n                break;\n            i++;\n\n        }\n        return i;\n    }	0
18281259	18251148	how to open my computer through speech recognition	string resultText = e.Result.Text.ToLower();\n      if (resultText == "computer")\n        {\n          string myComputerPath = Environment. (Environment.SpecialFolder.MyComputer);\n          System.Diagnostics.Process.Start("explorer", myComputerPath);\n        //System.Diagnostics.Process.Start("explorer", "::{20d04fe0-3aea-1069-a2d8-08002b30309d}");\n       }	0
28709203	28708949	Converting a type to an array	var type = //get type\nTypeDescriptor.GetConverter(type).ConvertFrom(stringSerialization);	0
11782610	11782112	How to disable Null image in DataGridView image column when populated from DataTable	((DataGridViewImageColumn)this.emptyDataGridViewFromDesigner.Columns["Flags"]).DefaultCellStyle.NullValue = null;	0
12694853	12694646	WinForms: Adding custom ToolStripMenuItem to MenuStrip in designer	[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.MenuStrip)]\npublic class MyToolStrip : ToolStripMenuItem {\n\n}	0
10804612	10804388	Format GridView Auto Generated Columns	dataGridView1.Columns[columnName].AutoSizeMode= DataGridViewAutoSizeColumnMode.None;\ndataGridView1.Columns[columnName].Width = columnWidth;	0
4327471	4327223	How to build a mix-in architecture framework in C#?	var window=new HorizontalScrollingWindowDecorator(new VerticalScrollingWindowDecorator(new Window));	0
10805602	10805578	How to retreive column values seperately through sql data adapter class?	foreach (DataRow myRow in MyDataSet.Tables[0].Rows)\n    {\n        TextBox1.Text = myRow["DeptNo"].ToString(); \n        TextBox2.Text = myRow["DeptId"].ToString(); \n        ... \n    }	0
22805098	22804792	I want to search integers from string and store them in array	Console.WriteLine("Choose 7 numbers (1-39) by pressing ENTER after every number:");\n  int[] userLottery = new int[7];\n\n  int i = 0;\n  while (i < 7)\n  {\n      Console.Write("Your choice #{0}: ", i+1);\n      string userRow = Console.ReadLine();\n      int userNumber;\n\n      if (!Int32.TryParse(userRow, out userNumber) || userNumber < 1 || userNumber > 39)\n      {\n          Console.WriteLine("Invalid number! Please try again!");\n      }\n      else\n      {\n          userLottery[i++] = userNumber;\n      }\n  }	0
8828648	8822851	How to show a display value for selected node in treeview in C#?	foreach (DataRow dr in Db.Table("Employee").Rows)\n{ \n  TreeNode tn = new TreeNode(); \n  tn.Tag = dr["eeid"]; \n  tn.Text = dr["Name"].ToString(); \n  treeView1.Nodes.Add(tn); \n} \nprivate void treeView1_DoubleClick(object sender, EventArgs e) \n{ \n  MessageBox.Show(treeView1.SelectedNode.Tag.ToString()); \n}	0
1622448	890244	Change tiff pixel aspect ratio to square	using System.Drawing;\nusing System.Drawing.Imaging;\n\n// The memoryStream contains multi-page TIFF with different\n// variable pixel aspect ratios.\nusing (Image img = Image.FromStream(memoryStream)) {\n    Guid id = img.FrameDimensionsList[0];\n    FrameDimension dimension = new FrameDimension(id);\n    int totalFrame = img.GetFrameCount(dimension);\n    for (int i = 0; i < totalFrame; i++) {\n        img.SelectActiveFrame(dimension, i);\n\n        // Faxed documents will have an non-square pixel aspect ratio.\n        // If this is the case,adjust the height so that the\n        // resulting pixels are square.\n        int width = img.Width;\n        int height = img.Height;\n        if (img.VerticalResolution < img.HorizontalResolution) {\n            height = (int)(height * img.HorizontalResolution / img.VerticalResolution);\n        }\n\n        bitmaps.Add(new Bitmap(img, new Size(width, height)));\n    }\n}	0
31112389	31112062	Populate a mvc5 list?	using (var db = new YourDbContext())\n{\n    var post = db.Posts().Include(g => g.Game).FirstOrDefault();\n    var gameTitle = post.Game.Title;\n}	0
5442299	5442138	Fill the whole row of listbox selected items in form controles	private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n  {\n      textBox1.Text = listBox1.SelectedItem.ToString();\n  }	0
29921470	29892410	Updating records in foreach loop in Entity Framework 6	SaveChanges()	0
2562959	2562946	Cross-thread Winforms control editing	textbox1.Invoke((MethodInvoker)(() =>\n   {\n     textbox1.Text="some text";\n   }));	0
27933134	27933073	Can IComparer be used to hash a list as it is populated?	SortedSet<T>	0
8875573	8849496	Colorize a grayscale image	{{0.273372, 0.112407, 0.0415183}, \n {0.79436,  0.696305, 0.167884}, \n {0.235083, 0.999163, 0.848291}, \n {0.295492, 0.780062, 0.246481}, \n {0.584883, 0.460118, 0.940826}}	0
9926373	9926310	How to find which column throws unique key constraint exception when there are more than one unique key columns in table?	try\n{\n    ... (access the database here) ...\n}\ncatch (SqlException e)\n{\n    ... (look at e.Message)\n}	0
9430036	9429992	How to get a simple computer name (without the domain name) out of a full computer name in c#?	string fullName = "foobar.domain";\nstring hostName = fullName.Substring(0, fullName.IndexOf('.'));	0
28014056	28013879	New Row into SQL Server with Data Set [asp.net, c#]	string insertText = @"INSERT INTO Szkoda (Likwidator,FirmaObslugujaca, \n                      StanSzkody, CzyRegres, KrajZdarzenia) \n                      values (@lik, @fir, @sta, @czy, @kra);\n                      SELECT SCOPE_IDENTITY()";\n\nSqlCommand cmd = new SqlCommand(insertText, connection);\ncmd.Parameters.AddWithValue("@lik", tbLikwidator.Text);\ncmd.Parameters.AddWithValue("@fir", DdFirma.Text);\ncmd.Parameters.AddWithValue("@sta", DdStan.Text);\ncmd.Parameters.AddWithValue("@cay", DdRegres.Text);\ncmd.Parameters.AddWithValue("@kra", DdKraj.Text);\nobject result = cmd.ExecuteScalar();\nif(result != null)\n{\n   int lastInsertedID = Convert.ToInt32(result);\n   // now insert the row in your dataset table but instead of\n   // da.Update(ds, "Szkoda"); call \n   ds.Tables["Szkoda"].AcceptChanges();\n}	0
14423019	14422948	Do I really have to give an initial value to all my variables?	DateTime? currentEntryDate = null	0
8803901	8803859	How to bind a ListBox to a DataTable from a session object?	dt = (DataTable)Session["bestStocks"];\n\nDataView dv = new DataView(dt);\nBestStockslb.DataSource = dt;\nBestStockslb.DataTextField =  "Name";\nBestStockslb.DataValueField =  "ID"; \nBestStockslb.DataBind();	0
1408358	1407368	Need help with LINQ query that joins two tables containing periodic events	var a = from m in month\n        join h in holiday on m.Id equals h.MonthId\n        select new\n        {\n            MonthId = m.Id,\n            Month = m.Name,\n            Holiday = h.Name,\n            HolidayDay = h.DayOfMonth,\n            Appointment = "",\n            AppointmentDay = 0\n\n        };\n\nvar b = from m in month\n        join p in appointments on m.Id equals p.MonthId\n        select new\n        {\n            MonthId = m.Id,\n            Month = m.Name,\n            Holiday = "",\n            HolidayDay = 0,\n            Appointment = p.Description,\n            AppointmentDay = p.DayOfMonth\n        };\n\nvar events = from o in a.Union(b)\n            orderby o.MonthId, o.HolidayDay + o.AppointmentDay\n            select o;	0
10261969	10261816	Multiple labels	lblLeftUp[i].AutoSize = true;	0
31329665	31329252	Assign a random array string to a text component - Unity 4.6, uGUI	using UnityEngine;\nusing System.Collections;\nusing UnityEngine.UI;\n\npublic class Test : MonoBehaviour \n{\npublic Text myText;\n\npublic string[] animalDescriptions = \n{\n    "Description 1",\n    "Description 2",\n    "Description 3",\n    "Description 4",\n    "Description 5",\n};\n\nvoid Start()\n{\n    string myString = animalDescriptions [Random.Range (0, animalDescriptions.Length)];\n    myText.text = myString;\n}\n}	0
86483	86413	Creating a fixed width file in C#	string a = String.Format("|{0,5}|{1,5}|{2,5}", 1, 20, 300);\nstring b = String.Format("|{0,-5}|{1,-5}|{2,-5}", 1, 20, 300);\n\n// 'a' will be equal to "|    1|   20|  300|"\n// 'b' will be equal to "|1    |20   |300  |"	0
20774065	20774008	Getting XML namespace with prefix	var TARIF = doc.Descendants("TARIFV1").Select(x => x.Value).ToList();	0
3015839	3015390	Is it possible to load a UserControl into an anonymous object, instead of just instantiating it?	this.TopStrapline = doc.Elements("TopStrapline")\n  .Select(e => {\n      var control = (TopStrapline)LoadControl("~/Path/TropStrapLine.ascx");\n      control.StraplineText = e.Attribute("text");\n\n      return control;\n  }).FirstOrDefault();	0
16293837	16293704	How to convert SQL query to LINQ with Orderby, Groupby	var serverNames = new string[]{"ServerX", "ServerY"};\nvar result = db.Processes\n    .Where(p => serverNames.Contains(p.ID) && p.Type == "Complete")\n    .GroupBy(p => p.ProcessTime)\n    .Select(g => new\n    {\n        ProcessTime = g.Key,\n        AmountOfProcesses = g.Count()\n    })\n    .OrderBy(x => x.ProcessTime);	0
21410745	21410291	ReadXml from a Resource - Explanation	// Summary:\n//     Reads XML schema and data into the System.Data.DataSet using the specified\n//     file.\n//\n// Parameters:\n//   fileName:\n//     The filename (including the path) from which to read.\npublic XmlReadMode ReadXml(string fileName);	0
28480936	28480338	SendKeys.send with internet explorer	Dim w As New SendKeys.WINFOCUS\n    w = SendKeys.GetWinHandles("New Text Document - Notepad", 1, "Edit", 1)\n    SendKeys.Send("Hello", w)	0
7477102	7462978	Progress bar value is not synchronized with what gets rendered in windows 7	progressBar1.Value = value + 1; progressBar1.Value = value;	0
7684673	7684641	Public Enumeration with only string values	public static class MyConfigs\n{\n    public const string Configuration1 = "foo",\n                        Configuration2 = "bar"\n}	0
8005298	8005260	Query Access with wildcard	command.Parameters.AddWithValue("@searchTerm", searchTerm); \ncommand.CommandText = "SELECT [OA_Name] FROM [Operating_Authority_Table] WHERE [OA_Name] = '%' + @searchTerm + '%'";	0
1437984	1436985	How to get a list of methods on a table?	public static System.Collections.ArrayList getTableMethods(str _tableName)\n{\n    SysDictTable sdt;\n    TreeNode tn;\n    TableId tableId;\n    MethodInfo methodInfo;\n    System.Collections.ArrayList methodArr;\n    #AOT\n    ;\n\n    tableId = tableName2id(_tableName);\n\n    sdt = SysDictTable::newTableId(tableid);\n\n    methodArr = new System.Collections.ArrayList();\n    tn = TreeNode::findNode(#TablesPath + "\\" + _tableName + "\\" + "Methods");\n    tn = tn.AOTfirstChild();\n    while(tn)\n    {\n        methodArr.Add(tn.AOTname());\n        tn = tn.AOTnextSibling();\n    }\n\n    return methodArr;\n}	0
32701143	32700576	Concat two integers	//Input: 100 in dollars\nint dollars = 100;\n//Input: 00 in cents\nint cents = 0;\n\n//OutPut: 1000 // missing 1 zero due to input being 00.\nint output = dollars * 100 + cents;	0
29764796	29764730	Android Display images from url from api call	Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(image_url).getContent());	0
34413521	34413374	To find the second last indexof a value in a string	referrer = referrer.Substring(referrer.Substring(0, referrer.LastIndexOf("/")).LastIndexOf("/") + 1);	0
19371001	19370921	Load data form Azure/IEnumerable to ListBox	AzureData = _items;	0
7774720	7774648	How can convert this C# code to C++/CLI	using namespace System;\nusing namespace System::IO;\nusing namespace System::Security::Cryptography;\nusing namespace System::Text;\n\nref class Example {\nprotected:\n    String^ GetMD5HashFromFile(String^ fileName)\n    {      \n        FileStream file(fileName, FileMode::Open);\n        MD5CryptoServiceProvider md5;\n        array<Byte>^ retVal = md5.ComputeHash(%file);\n        return Convert::ToBase64String(retVal);\n    }\n};	0
17933815	17933689	Getting values with regex grouping construct in C#	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(htmlstring);\n\nvar imgUrls = doc.DocumentNode.Descendants("img")\n                .Select(img => img.Attributes["src"].Value)\n                .ToList();	0
7298262	7298243	Regex to match and remove parameter in URL	var url = "http://localhost:8001/?page=categories&catid=4&p=1888&country=1,2,3,6";\nvar urlBuilder = new UriBuilder(url);\nvar values = HttpUtility.ParseQueryString(urlBuilder.Query);\nvalues.Remove("p");\nurlBuilder.Query = values.ToString();\nvar newUrl = urlBuilder.ToString();	0
2734993	2734940	How to use a function for every C# WinForm instead of pasting 	public class CloseWindowBehavior : IMessageFilter {\n\n    const int WM_KEYDOWN = 0x100;\n    const int VK_ESCAPE = 0x1B;\n\n    bool IMessageFilter.PreFilterMessage(ref Message m) {\n        if (m.Msg == WM_KEYDOWN && (int)m.WParam == VK_ESCAPE) {\n            if (Form.ActiveForm != null) {\n                Form.ActiveForm.Close();\n            }\n            return true;\n        }\n        return false;\n    }\n\n}\n\nApplication.AddMessageFilter(new CloseWindowBehavior());	0
28743548	28743511	How to clear a binding source?	bindingSource.DataSource = typeof(CustomerType);	0
10020945	10020909	Is that possible to divide all elements in C# double list to that double list elements sum (which makes total = 1)	var sum = lstDouble.Sum();\nvar result = lstDouble.Select(d => d / sum);	0
8278107	8274636	call onclick method from c#	foreach (HtmlElement item in webBrowser1.Document.All)\n        {\n            if ( item.OuterHtml != null)\n            {\n                if (item.OuterHtml.Contains("submitEdgeStory"))\n                {\n\n                    item.InvokeMember("click");\n                    break;\n                }\n            }\n        }	0
34074380	34017286	Converting from C# string to C++ wchar_t [unmanaged]	hr = xAudio->CreateMasteringVoice(&masteringVoice, 0U, 0U, 0U, deviceID->Data);	0
32478827	32478059	Using Mailkit to save attachments using IMAP	attachment.ContentDisposition.FileName	0
27292140	27292045	How to run javascript using server side code in ASP.Net Web Form application in update panel?	ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, string.Format("alert('{0}')", "Server"), true);	0
22381047	22380943	How To Bind Array Of Images In c# To XAML Image Source?	imgBackground.ImageSource = new BitmapImage(new Uri("Images/" + imgChange[bgImgIndex], UriKind.Relative))\n\n                             or\nimgBackground.Source= new BitmapImage(new Uri("Images/" + imgChange[bgImgIndex], UriKind.Relative))	0
9120616	9120555	Measure wrapped string	SizeF size = g.MeasureString(someText, someFont, someRectangleF.Size.Width);\ng.DrawString(someText, someFont, someBrush, new PointF(0, 0), someRectangleF);\ng.DrawString(someMoreText, someFont, someBrush, new PointF(0, size.Height), someRectangleF);	0
7687266	7687169	How to disable a menu item on page load in asp.net 4.0	//Going through first level items\n if (e.item.NavigateUrl == "")\n    e.item.Enabled = false;\n\n //Going through submenu item\nforeach (MenuItem item in e.Item.Items)\n{\n     if (item.NavigateUrl == "")\n         item.Enabled = false;\n}	0
2392831	2366752	Visual Studio 2010: How do I create and/or update a specific file within a Project from an Editor Extension?	var bufferAdapter = AdaptersFactory.GetBufferAdapter(textBuffer);\nif (bufferAdapter != null)\n{\n    var persistFileFormat = bufferAdapter as IPersistFileFormat;\n    if (persistFileFormat != null)\n    {\n        string ppzsFilename;\n        uint iii;\n        persistFileFormat.GetCurFile(out ppzsFilename, out iii);\n\n        var dte2 = (DTE2) Shell.Package.GetGlobalService(typeof (SDTE));\n\n        ProjectItem prjItem = dte2.Solution.FindProjectItem(ppzsFilename);\n\n        var containingProject = prjItem.ContainingProject;\n\n        // Now use the containingProject.Items to find my file, etc, etc\n    }\n}	0
23091189	23091107	Get all attributes in XML	var xDoc = XDocument.Load("path");\n\nvar attributes = xDoc.Descendants()\n                 .SelectMany(x => x.Attributes())\n                 .ToDictionary(x => x.Name.LocalName, x => (string)x);	0
9369514	9369359	How to get a non generic cast method information?	MethodInfo[] methods = person.GetType().GetMethods();\nforeach (MethodInfo mi in methods)\n    if (mi.Name == "GetPersonType" && !mi.IsGenericMethodDefinition)\n        return mi;	0
7155222	7155119	problem with conversion of JSOn string to Mongo document	var bsonDoc = BsonDocument.Parse(jsonString);	0
3278685	3278622	Need help with a Regex for parsing human typed times	event: "Dinner" time |\n       "Dinner" location |\n       "Dinner" time location |\n       "Dinner" location time\n\ntime:  "at" number ":" number "am"/"pm"\n       /* etc. */	0
13382758	13382591	How do i use C# to to return element values using XPath?	"/computeraudit/category[@title=\"Loaded Modules\"]/subcategory/recordset/datarow/fieldvalue"	0
7565889	7563537	Calculate entropy of probability distribution of two data sets- text analysis & sentiment in C#	H(..) = -log(p(S1|g)) * p(S1|g)  - log(p(S2|g)) * p(S2|g) - ....	0
16582658	16582224	JSON parsing in windows phone returns an exception	public class RootObject1\n    {\n        public string[] runtime { get; set; }\n        public float rating { get; set; }\n        public string rated { get; set; }\n        public string title { get; set; }\n        public string poster { get; set; }\n        public string imdb_url { get; set; }\n        public string[] writers { get; set; }\n        public string imdb_id { get; set; }\n    }	0
9242896	9241902	need help converting my XNA PC Game to Xbox 360	if (isAI) {\n                Ball b = Game1.ball; //this is AI\n                if (b.Y > padMiddle)\n                    moveDown();\n                else if ((b.Y + height) < padMiddle)\n                    moveUp();\n            }\n            else\n            {\n                GamePadState currentState = GamePad.GetState(PlayerIndex.One);\n                if (currentState.IsButtonDown(Buttons.LeftThumbstickUp)\n                {\n                    moveUp();\n                }\n                else if (currentState.IsButtonDown(Buttons.LeftThumbstickDown)\n                {\n                    moveDown();\n                }\n            }	0
18099734	18098691	how to open facebook from my application	string myfbID = "54"; // facebook ID(my account)\nvar succes = await Windows.System.Launcher.LaunchUriAsync(new Uri("fb:"+ myfbID));	0
1852023	1852012	How to search for table in LinqToSQL?	if(from t in context.table where t.field.Equals(parameter) select t).Count() == 0)\n{\n  table t = new table(){ field1 = param1, field2 = param2};\n  context.table.InsertOnSubmit(t);\n  context.SubmitChanges();\n}	0
5308909	5308863	How can I draw an etched 3D line on a WinForm?	label1.AutoSize = false;\nlabel1.Height = 2;\nlabel1.BorderStyle = BorderStyle.Fixed3D;	0
356513	356330	Build dependency tree from csproj files	digraph G { \n      size="100,69"\n      center=""\n      ratio=All\n      node[width=.25,hight=.375,fontsize=12,color=lightblue2,style=filled]\n      1 -> 9;\n      1 -> 11;\n      9 -> 10;\n      11 -> 10;\n      1 [label="Drew.Controls.Map"];\n      9 [label="Drew.Types"];\n      10 [label="nunit.framework"];\n      11 [label="Drew.Util"];\n }	0
17321549	17321405	Create a console like information display in a windows form	TextBox1.text += "More text" + " \r\n";	0
31521086	31520895	How to insert multiple date in DateTimePicker?	this.monthCalendar1.AnnuallyBoldedDates = \n            new System.DateTime[] { new System.DateTime(2015, 7, 20, 0, 0, 0, 0),\n                                    new System.DateTime(2015, 7, 21, 0, 0, 0, 0)};	0
12182990	12182578	Use enum item name like an attribute parameter 	public static class HardCodedRoles\n{\n    public const string Managers = "Managers";\n    public const string Administrators = "Administrators";\n}\n\n[RequiresRole(HardCodedRoles.Managers)]	0
6825751	6825710	How to hide the grid lines of a DataGridView? Winforms C#	MyGrid.CellBorderStyle = DataGridViewCellBorderStyle.None;	0
3290878	3288023	How to preload class libraries in Dot Net Compact Framework?	class MyForm\n{\n    static void Main()\n    {\n        new Thread(delegate\n            {\n                AppInitialize();\n            })\n            {\n                IsBackground = true\n            }\n            .Start();\n\n        Application.Run(new MyForm());\n    }\n\n    static void AppInitialize()\n    {\n       // load app-wide resources, services, etc\n    }\n\n    public MyForm()\n    {\n        InitializeComponent();\n\n        ThreadPool.QueueUserWorkItem(\n            delegate\n            {\n                InitializeServices();\n            });\n    }\n\n    void InitializeServices()\n    {\n        // load up stuff the Form will need after loading/first rendering\n    }\n}	0
9356665	9356198	Need example of MVC3 project with 4 section directory structure with possible sitemap use	public ActionResult Section2(string id) \n{ \n    return View("Section2", new { id=id }); \n}	0
14449097	14446522	Using MVVM to Change an Applications Theme	public interface IMainView {\n   void ChangeTheme(string themeName);\n}\n\npublic class ViewModel {\n\n   public IMainView View { get; } //get the view somehow\n   public ICommand ChangeThemeCommand { get; }\n\n   private void OnChangeThemeCommandExecute(string themeName) {\n      View.ChangeTheme(themeName);\n   }\n}	0
21843794	21154801	How to fill dictionary from wcf ksoap2 response	list = new List<byte[]>();\n            for (int i = 0; i < arr1.Count; i++)\n            {\n                img = Image.FromFile(arr1[i].ToString());\n                ms = new MemoryStream();\n                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n                list.Add(ms.ToArray());\n            }\n\n            image_Name.Add(arr1, list);\n            //image_Name[arr1 as ArrayList] = [list as byte[]];\n            return image_Name;\n        }	0
25147740	25147541	Prompt user that input is out of range, based on comparing to sql query	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    int classRPM;\n    int fanRPM;\n    using (Fanrpm ds = new Fanrpm(....)\n    {\n        DataTable dt = ds.dataset.Tables[0];\n\n        // Get and convert the value in the field named ClassRPM (assuming is a string)\n        classRPM = Convert.ToInt32(dt.Rows[0].Field<string>("ClassRPM"));\n\n        // Now check if the textbox contains a valid number\n        if(!Int32.TryParse(txfanrpm.Text, out fanRPM))\n        {\n            MessageBox.Show("Not a number....");\n            return;\n        }\n\n        // Start your logic\n        if (fanRPM >= classRPM)\n        {\n            MessageBox.Show(.....);\n        }\n        else if (fanRPM < classRPM)\n        {\n            MessageBox.Show(.......);\n        }\n    }\n}	0
2897672	2894894	Closing a MenuStrip programatically	private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) {\n        if (e.KeyData == Keys.Enter) {\n            e.SuppressKeyPress = true;\n            toolStripTextBox1.Owner.Hide();\n        }\n    }	0
19195383	19195296	select file(s) with certain extension from disk	var files = di.EnumerateFiles(string.Format("{0}{1}.*", "thumb-", id))\n            .Where(x => fileExtensions.Contains(x.Extension));	0
20690552	20690525	How can I escape a dot in ToString()	fonenum.ToString("#0000\\.0000")	0
8551394	8550657	Excel C# COM addon returning an array with Dates and Doubles	range.NumberFormat="yyyy-mm-dd"	0
17172942	17172342	C# XML Comment Reuse	/// <summary>\n/// Verify a control on Beam dialog\n/// </summary>\n/// <param name="args"><token>CommonParamInfo</token></param>\n/// (...)	0
26179787	26179383	Searching for a specific string token in a collection	var result = from setting in settingList\n             where setting.UserIdList.Split(',').Contains("45")\n             select setting;	0
33159346	33159218	I'm unable to extract the Data from this XML	string query = String.Format("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22london%22&format=xml");\nXDocument xml = XDocument.Load(query);\nXNamespace ns = "http://where.yahooapis.com/v1/schema.rng";\nvar woeid = xml.Element("query").Element("results").Elements(ns + "place").FirstOrDefault().Element(ns +"woeid").Value;	0
584840	584820	How do you perform a left outer join using linq extension methods	var qry = Foo.GroupJoin(\n          Bar, \n          foo => foo.Foo_Id,\n          bar => bar.Foo_Id,\n          (x,y) => new { Foo = x, Bars = y })\n    .SelectMany(\n          x => x.Bars.DefaultIfEmpty(),\n          (x,y) => new { Foo=x.Foo, Bar=y});	0
8900823	8900772	How to call method of the main WPF window from the modal window?	// Code in main window\nModalWindow window = new ModalWindow();\nwindow.Owner = this; \nwindow.ShowDialog()\n\n//Code on the modal window\nvar myObject = this.Owner as MainWindow;\nmyObject.MyMethod(); // Call your method here.	0
20081731	20081205	Dreams about C# precompiler variables	public static class Config\n{\n public static readonly RelativeRoot;\n public static Config()\n {\n#if Debug\n   RelativeRoot = "..\..\folder"\n#else\n   RelativeRoot = "..\..\folder"\n#endif\n }\n}	0
1328619	1328373	XNA Rotating a tank properly	// smallest angle between the current direction and the desired direction\nminAngle1 = Math.Abs(Math.Min(tankAngle - desiredAngle, desiredAngle - tankAngle));\n\n// smallest angle between the opposite direction and the desired direction\noppositeAngle = (tankAngle + 180) % 360;\nminAngle2 = Math.Abs(Math.Min(oppositeAngle - desiredAngle, desiredAngle - oppositeAngle));\n\n// get the smaller of two to rotate to\nif (minAngle1 < minAngle2)  {\n  // we know that we should rotate the current direction to the desired direction\n} else {\n  // rotate the opposing direction to the desired direction\n}	0
10165043	10164677	Filtering Data by User's access rights	public interface ILeagueRepository \n{\n    IEnumerable<League> All;\n}\n\npublic interface ILeaguesProvider\n{\n    IEnumerable<League> GetUserLeagues(string Username);\n}\n\npublic class LeaguesProvider : ILeaguesProvider\n{\n    public LeaguesProvider(ILeagueRepository repository)\n    {\n         // ...\n    }\n    public IEnumerable<League> GetUserLeages(string Username)\n    {\n        return _repository.All.Where(league=>league.User == Username);\n    }\n}\n\npublic ActionResult LeaguesController\n{\n    public LeaguesController(ILeaguesProvider providerDependency, IRoleProvider roleDependency)\n    {\n        IEnumerable<League> leagues = providerDependency.GetUserLeagues(roleDependency.GetCurrentUser());\n    }\n}	0
11290837	11286512	Weird exception with OLEDB Parameter Insert	thisCommand.CommandText = "INSERT INTO Events (Venue_ID, Date_Start, " +\n    "Date_End, [Name], Description, Event_Type, Buy_Tickets_URL) " +\n    "VALUES (@VenID, @DStart, @DEnd, @Name, @Des, @EvType, @SysUrl);";\n\n\n    thisCommand.Parameters.AddWithValue("@Des", 1);\n    thisCommand.Parameters.AddWithValue("@Des", DateTime.Now.Date);\n    thisCommand.Parameters.AddWithValue("@Des", DateTime.Now.Date);\n    thisCommand.Parameters.AddWithValue("@Des", "abc");\n    thisCommand.Parameters.AddWithValue("@Des", "abc");\n    thisCommand.Parameters.AddWithValue("@Des", 1);\n    thisCommand.Parameters.AddWithValue("@Des", "abc");	0
7179995	7179969	Retrieving 16-bit big endian value from byte array?	byte[] array = new byte[] { 0x01, 0xF1 };\n\nint result = (array[0] << 8) | array[1];\n// result == 0x01F1	0
12369557	12369490	How to call a non static method from static method	[WebMethod]\npublic static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des)\n    {  string result;\n       if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals("")))\n        {\n            result="null";\n        }\n        else\n        {\n            int got_question_id = getting_question_id;\n            DataHandler.breg obj = new DataHandler.breg();\n            obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des);\n            result="inserted";\n       }\n        querystring object_new = new querystring();\n        object_new.show();\nreturn result;\n       }	0
24350169	24350049	Convert png to jpeg (quality of image after conversion)	// Get a bitmap.\nBitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");\nImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);\n\n// Create an Encoder object based on the GUID \n// for the Quality parameter category.\nSystem.Drawing.Imaging.Encoder myEncoder =\n    System.Drawing.Imaging.Encoder.Quality;\n\n// Create an EncoderParameters object. \n// An EncoderParameters object has an array of EncoderParameter \n// objects. In this case, there is only one \n// EncoderParameter object in the array.\nEncoderParameters myEncoderParameters = new EncoderParameters(1);\n\nmyEncoderParameter = new EncoderParameter(myEncoder, 100L);\nmyEncoderParameters.Param[0] = myEncoderParameter;\nbmp1.Save(@"c:\TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);	0
25009967	25009618	Cannot find HTMLControl in Page_LoadComplete	private Control FindControlRecursive(Control ctrl, string id)\n{\n    if(ctrl.ID == id)\n    {\n        return ctrl;\n    }\n    foreach (Control child in ctrl.Controls) \n    { \n        Control t = FindControlRecursive(child, id); \n        if (t != null) \n        { \n            return t; \n        } \n    } \n    return null;\n}	0
8182977	8182909	Is it safe to get the allocated only bytes form a byte array obtained from GetBuffer?	ms.ToArray()	0
10946290	10945825	DataContractJsonSerializer parsing iso 8601 date	[DataContract]\npublic class LibraryBook\n{\n    [DataMember(Name = "ReturnDate")]\n    // This can be private because it's only ever accessed by the serialiser.\n    private string FormattedReturnDate { get; set; }\n\n    // This attribute prevents the ReturnDate property from being serialised.\n    [IgnoreDataMember]\n    // This property is used by your code.\n    public DateTime ReturnDate\n    {\n        // Replace "o" with whichever DateTime format specifier you need.\n        get { return DateTime.ParseExact(FormattedReturnDate, "o", CultureInfo.InvariantCulture);\n        set { FormattedReturnDate = value.ToString("o");\n    }\n}	0
5425413	5425279	Where to add a notify icon in a multiple form based application c#	namespace WinformsTesting {\n\n    using System;\n    using System.Windows.Forms;\n    using System.Drawing;\n\n    public class NotifyIconManager {\n\n        private NotifyIcon _ni;\n\n        public void Init() {\n\n            _ni = new NotifyIcon();\n            _ni.MouseDoubleClick += new MouseEventHandler(_ni_MouseDoubleClick);\n            _ni.Text = "This is my notify icon";\n\n            Icon icon = new Icon(@"C:\temp\myicon.ico");\n            _ni.Icon = icon;\n            _ni.Visible = true;\n\n        }\n\n        void _ni_MouseDoubleClick(object sender, MouseEventArgs e) {\n            MessageBox.Show("Hello");\n        }\n    }\n}	0
14913111	14913101	What is the easiest way to seeing if there are any matches across a few DateTime arrays?	List<DateTime> common = list1.Intersect(list2).Intersect(list3).ToList();	0
14219416	13664121	Compare a Custom Model index against int array in C# using Linq	public bool IsSubsetof(int[] opciones, IEnumerable<Etiquetas> tags)\n{ \n    int[] tagens;\n    tagens= new int[tags.Count()];\n    for (int i = 0; i < tagens.Length; i++)\n    {\n        tagens[i] = tags.ToArray()[i].EtiquetaId;\n    }\n    return !opciones.Except(tagens).Any();\n}	0
11278205	11278157	How can I instantitate a list based on the specific object type?	public class BaseEntity<T> where T: class\n{\n    public List<T> List { set; get; }\n\n    public BaseEntity(IEnumerable<T> list)\n    {\n        this.List = new List<T>();\n        foreach (T k in list)\n        {\n            this.List.Add(k);\n        }\n    }\n}\n\npublic class KeyValuePair\n{\n    public string key;\n    public string value;\n    public string meta;\n}\n\npublic class KeyValuePairList : BaseEntity<KeyValuePair>\n{\n    public KeyValuePairList(IEnumerable<KeyValuePair> list) \n        : base(list) { }\n}	0
9504978	9504829	c# Retrieving information from a control in a dynamic created tab	int tabCount = 5;\n    tabControl.TabPages.Clear();\n\n    List<ComboBox> comboboxes = new List<ComboBox>(tabCount);\n    for (int i = 0; i < tabCount; i++)\n    {\n        TabPage tabPage = new TabPage();\n        ComboBox comboBox = new ComboBox();\n        comboboxes.Add(comboBox);\n        tabPage.Controls.Add(comboBox);\n        tabControl.TabPages.Add(tabPage);\n    }\n\n    // You can access the values using the 'comboboxes' list now.	0
2412496	2405758	DotNetZip: How to extract files, but ignoring the path in the zipfile?	using (var zf = Ionic.Zip.ZipFile.Read(zipPath))\n{\n    zf.ToList().ForEach(entry =>\n    {\n        entry.FileName = System.IO.Path.GetFileName(entry.FileName);\n        entry.Extract(appPath);\n    });\n}	0
26146564	26146439	Spaces in filepath cause multiple instances of my application to appear when executed via Windows Context Menu	string.Format("\"{0}\\GetCRC2.exe\" \"%1\"",appfilePath)	0
11913281	11913242	How to close WPF windows?	using System;\nusing System.Windows;\n\nnamespace WpfApplication1\n{\n    public partial class FlightWindow : Window\n    {\n        public FlightWindow()\n        {\n            InitializeComponent();\n        }\n\n        private void button1_Click(object sender, RoutedEventArgs e)\n        {\n            this.Close();\n        }\n    }\n}	0
2484302	2484290	How do i supress keypress being printed to console in .NET?	Console.ReadKey(true)	0
2493567	2493323	Using switch and enumerations as substitute for named methods	interface CommandProcessor{\n  void process(Command c);\n}	0
7178857	7178171	Windows Icon property in WPF, Markup Extension needed?	Icon="pack://application:,,,/ApplicationIcon.ico"	0
3931872	3931540	Invoke method in Func when passed as parameter	TimeSpan ts = cacheExpiration.SlidingExpiration(TimeSpan.FromSeconds(50));\n//or\nTimeSpan ts2 = cacheExpiration.AbsoluteExpiration(TimeSpan.FromSeconds(50));	0
30454661	30434969	How to add access-control-allow-methods to method in C# POST	client.DefaultRequestHeaders.Add("Access-Control-Allow-Methods", "POST");	0
2522502	2522461	C# How to check if a class implements generic interface?	MyClass myClass = new MyClass();\nType myinterface = myClass.GetType()\n                          .GetInterface(typeof(IMyInterface<int>).Name);\n\nAssert.That(myinterface, Is.Not.Null);	0
10138070	10130077	Mock IRavenQueryable with a Where() expression appended	[Test]\npublic void MyTest()\n{\n    using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true })\n    {\n        documentStore.Initialize();\n\n        using (var session = documentStore.OpenSession())\n        {\n            // test\n        }\n    }\n}	0
4411429	4411349	Change/Swap base class at runtime with another base class	static void Main(string[] args)\n{\n    ExampleClass ec = new ExampleClass();\n    // The following line causes a compiler error if exampleMethod1 has only\n    // one parameter.\n    //ec.exampleMethod1(10, 4);\n\n    dynamic dynamic_ec = new ExampleClass();\n    // The following line is not identified as an error by the\n    // compiler, but it causes a run-time exception.\n    dynamic_ec.exampleMethod1(10, 4);\n\n    // The following calls also do not cause compiler errors, whether \n    // appropriate methods exist or not.\n    dynamic_ec.someMethod("some argument", 7, null);\n    dynamic_ec.nonexistentMethod();\n}\n\nclass ExampleClass\n{\n    public ExampleClass() { }\n    public ExampleClass(int v) { }\n\n    public void exampleMethod1(int i) { }\n\n    public void exampleMethod2(string str) { }\n}	0
820601	820595	.net Determine at run time whether my app is an exe or a web app	bool isWebApp = HttpContext.Current != null;	0
11374788	11374596	Determining whether an assembly is loaded from a byte array	bool isFromBytes = module.FullQualifiedName.StartsWith("<")	0
32182294	32177861	Make data grid cells show less decimals when not focused	ColumnWidth="SizeToHeader"	0
4405599	4405060	How to Verify if the user belongs to an Active Directory user Group in C#.NET	PrincipalContext pc = new PrincipalContext(ContextType.Domain);\nUserPrincipal user = UserPrincipal.FindByIdentity(pc, "johndoe");\nvar groups = user.GetAuthorizationGroups()  // or user.GetUserGroups()	0
8846620	8842444	Updating Data in the gridview	protected void txtSmall_TextChanged(object sender, EventArgs e)\n    {\n        TextBox t = (TextBox)sender;\n        GridViewRow r = (GridViewRow)t.NamingContainer;\n        Txtchanged(r.RowIndex);\n    }\n\n    protected void txtMedium_TextChanged(object sender, EventArgs e)\n    {\n        TextBox t = (TextBox)sender;\n        GridViewRow r = (GridViewRow)t.NamingContainer;\n        Txtchanged(r.RowIndex);\n    }\n\n    private void Txtchanged(int row_index)\n    {\n        TextBox t1 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtSmall");\n        TextBox t2 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtMedium");\n        TextBox t3 = (TextBox)GridView1.Rows[row_index].Cells[0].FindControl("txtTotal");\n        t3.Text = (Convert.ToInt32(t1.Text) + Convert.ToInt32(t2.Text)).ToString();\n\n    }	0
21122361	21095839	C# +HTMLAgilityPack: retrive background-url value	foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))\n            {\n                string newImg = "new-value.png";\n                if (bodyNode.Attributes.Contains("style") && bodyNode.Attributes["style"].Value.Contains("background-image:url"))\n                {                     \n                    string style = bodyNode.Attributes["style"].Value;\n                    string oldImg = Regex.Match(style, @"(?<=\().+?(?=\))").Value;\n                    string oldStyle = bodyNode.Attributes["style"].Value;\n                    string newStyle = oldStyle.Replace(oldImg, newImg);\n\n                    bodyNode.Attributes.Remove("style");\n                    bodyNode.Attributes.Add("style", newStyle);\n                }\n\n            }	0
11787122	11787004	Non-blocking key/value storage	public class Registry<TKey, TValue>\n{\n    private Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();\n    private object Lock = new object();\n\n    public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)\n    {\n        TValue value;            \n        if (!dictionary.TryGetValue(key, out value))\n        {\n            lock(Lock)\n            {\n              var snapshot = new Dictionary<TKey, TValue>(dictionary);\n              if (!snapshot.TryGetValue(key, out value))\n              {\n                  value = valueFactory(key);\n                  snapshot.Add(key, value);\n                  dictionary = snapshot;\n              }\n            }   \n        }\n        return value;\n    }\n}	0
9633903	9633790	Change or parse CRM FetchXML with LINQ to XML	List<FetchResult> results =\n            (from result in xmlDoc.Descendants("result")\n             select new FetchResult\n             {\n                 FirstName = result.Elements().First(el => el.EndsWith("firstname")).Value\n             }).ToList<FetchResult>();	0
19736734	19736520	How to use Descendants and LINQ to get complex XML data to two classes	var objects = xmlDoc.Descendants("object");\nvar items = \n  objects\n    .Select(item => \n      new Script\n      {\n        Id = item.Attribute("Id").Value,\n        Expression = item.Descendant("Expression").Content.Value,\n        Results = \n          item\n            .Elements("Result")\n            .Select(result => \n              new ScriptItem\n              {\n                Value = result.Attribute("Value").Value,\n                Action = result.Attribute("Action").Value\n              }\n            )\n            .ToList()\n      }\n    );	0
26910279	26910204	Regex simultaneous lookahead and lookbehind	\d+\s+(.*?)\s+[A-Z]+	0
15705090	15705043	Cast generic type parameter into array	public void Print()\n{\n    var array = Value as Array;\n    if (array != null)\n        foreach (var item in array)\n            Console.WriteLine(item);\n}	0
16313052	16312857	Next Number Generate in LINQ	string nextCode = dc.tblItems.Count()==0 ? "IT-001" : // if it's empty, start with IT-001\n    "IT-" +\n    (int.Parse(dc.tblItems.OrderByDescending(i=>i.ItemCode) // order by code descending\n                          .First() // get first one (last code)\n                          .ItemCode.Split('-')[1]) // get only the number part\n     +1).ToString("000") // add 1 and format with 3 digits	0
26754655	26754615	how to remove particumar letter combination from a string in c#?	var result = "he/a0h/a0dv/a0jks".Replace("/a0", string.Empty);	0
21178294	20563310	Changing Legend marker of Devexpress rangebarchart	{\n        BarDrawOptions drawOptions = (BarDrawOptions)ev.LegendDrawOptions;\n        drawOptions.Color = costIncreaseColor;\n        drawOptions.FillStyle.FillMode = FillMode.Solid;\n        drawOptions.Border.Color = System.Drawing.Color.Transparent;\n};	0
22084974	22084813	Image opened from stream is different from opened from file	using (var stream = new FileStream(this.fileName, FileMode.Open)) \n    using (var image = Image.FromStream(stream) {\n        foreach (var property in this.propItems) {\n            image.SetPropertyItem(property);\n        }\n        image.Save(@"D:\Temp\1.jpg");\n    }	0
1194676	1194620	How do I display progress during a busy loop?	for (i = 0; i < count; i++)\n{\n    ... do analysis ...\n    worker.ReportProgress((100 * i) / count);\n}\n\nprivate void MyWorker_ProgressChanged(object sender,\n    ProgressChangedEventArgs e)\n{\n    taskProgressBar.Value = Math.Min(e.ProgressPercentage, 100);\n}	0
6770054	6769964	Using Regular Expressions for Pattern Finding with Replace	var inQuotes = false;\nvar sb = new StringBuilder(someText.Length);\n\nfor (var i = 0; i < someText.Length; ++i)\n{\n    if (someText[i] == '"')\n    {\n        inQuotes = !inQuotes;\n    }\n\n    if (inQuotes && someText[i] == ',')\n    {\n        sb.Append('$');\n    }\n    else\n    {\n        sb.Append(someText[i]);\n    }\n}	0
22008629	22008335	MySQL receiving inout parameters from stored procedure in c#	.......\ncmd.Parameters\n    .AddWithValue("@courriers_Count", MySqlDbType.Int32)\n    .Direction = ParameterDirection.InputOutput;\ncmd.Parameters\n    .AddWithValue("@dossiers_Count", MySqlDbType.Int32)\n    .Direction = ParameterDirection.InputOutput;\n.......	0
17697556	17697500	Missing Windows Forms Application	devenv /installvstemplates	0
14870561	14870315	Show image from datagridview when selectionchange	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n        {\n            if (dataGridView1.SelectedRows.Count > 0)\n            {\n                MemoryStream ms = new MemoryStream(dataGridView1.SelectedRows[0].Cells["Picture"].Value);\n                pictureBox2.Image = Image.FromStream(ms);\n            }\n        }	0
12396258	12393739	How to change correctly font-size:x% with pt or px?	font-size: 65%	0
30098111	30096554	reverse function with 2 unknowns	var a = u32timestamp&0xFF;\nvar number= u32timestamp >>8;\nvar en = a-16;	0
12035560	11744870	Listbox IsSelected with SelectionMode=Extended	ScrollViewer.CanContentScroll="False"	0
4464285	4461554	How can I set different colors in a ZedGraph histogram?	GraphPane pane = zedGraphControl1.GraphPane;\nPointPairList list = new PointPairList();\nRandom rand = new Random();\n\nfor (int i = 0; i < 50; i++)\n{\n    list.Add(i, rand.Next(15));\n}\n\nBarItem myBar = pane.AddBar("", list, Color.Red);\nColor[] colors = { Color.Red, Color.Yellow, Color.Green };\nmyBar.Bar.Fill = new Fill(colors);\nmyBar.Bar.Fill.Type = FillType.GradientByY;\nmyBar.Bar.Fill.RangeMin = 5;\nmyBar.Bar.Fill.RangeMax = 10;\n\nzedGraphControl1.AxisChange();	0
3838128	3838027	How to update an value in app.config file?	Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\nconfig.AppSettings.Settings["IP"].Value = "10.0.0.2";\nconfig.Save(ConfigurationSaveMode.Modified);\nConfigurationManager.RefreshSection("appSettings");	0
5401685	5401609	how can i decode this page using C#	public List<Result> HandleRequest(String json)\n{\n        RootObject ro = new RootObject(json); //This line solved the problem, as now it become totally easy to consume this JSON as C# objects...\n}	0
20084807	20069756	How to display data received from serial port in a textbox without the text disappearing in Visual Studio C#?	private void timer1_Tick(object sender, EventArgs e) //Timer to update textbox\n    {\n        if (tempDisplayBox.Text != globalVar.updateTemp) //Only update if temperature is different\n        {\n            try\n            {\n                tempDisplayBox.AppendText(Environment.NewLine);\n                tempDisplayBox.AppendText(globalVar.updateTemp);\n            }\n            catch (NullReferenceException)\n            { \n            }\n        }\n    }	0
1922817	1922736	How to make two WORD to DWORD	public static uint MakeDWord(ushort a, ushort b) {\n    return ((uint)a << 16) | b;\n  }	0
18914421	18847317	Call a Linq to SQL user defined function multiple times in one trip to the DB	// NumberRange is my user defined function, that returns a table with all a row per number\n// Here I take that number and calculate the date based on an offset from today\nvar test = from dayOffset in ARDC.NumberRange(1, 10)\n           select DateTime.Today.AddDays(dayOffset.Counter.Value); // Counter is the column name of the table returned\n\n// Using the dates, that are calculated on the server, I select a call to the SQL function\nvar testResults = from toDate in test\n                  select ARDC.Aqua_NumShipDays(DateTime.Today, toDate).Value;\n\nvar t = testResults.ToList(); // This results in ONE trip to the database! (yay!)	0
8395519	8395497	Convert this custom string format into DateTime?	string dateString = "20/11/2011 3:40:55 am";\nDateTime parsedDate = DateTime.ParseExact(\n   dateString,\n   "dd/MM/yyyy h:mm:ss tt",\n   CultureInfo.InvariantCulture);	0
15513836	15511992	Selecting all nodes containing text with XPath	string[] elements = getXPath(textNode).Split(new char[1] { '/' });\nreturn String.Join("/", elements, 0, elements.Length-2);	0
2008425	2008392	Storing a Method as a Member Variable of a Class in C#	private eventmethod MySavedEvent;\n\npublic void KeyEvent(eventmethod D) {\n    // Save the delegate\n    MySavedEvent = D;\n}\n\npublic void CallSavedEvent() {\n    if (MySavedEvent != null) {\n        MySavedEvent();\n    }\n}	0
9631412	8257568	XML Download works in emulator but not on phone	TITLE = x.Descendants("Title").First().Value	0
33661770	33661675	How to store two Binary Strings in C# and use OR operator	var str1 = "10101";\nvar str2 = "11100";\n\nvar num1 = Convert.ToByte(str1, 2);\nvar num2 = Convert.ToByte(str2, 2);\nvar or = num1 | num2;\n\n// We need to lookup only that bits, that are in original input values.\n// So, create a mask with the same number of bits.\nvar mask = byte.MaxValue >> sizeof(byte) * 8 - Math.Max(str1.Length, str2.Length);\nvar result = (or & mask) == mask;\n\n// True, when all bits after OR are 1, otherwise - False.\nConsole.WriteLine(result);	0
27024171	27022501	Determine whether Console Application is run from command line or Powershell	using System;\nusing System.Diagnostics;\n\nProcess p = Process.GetCurrentProcess();\nPerformanceCounter parent = new PerformanceCounter("Process", "Creating Process ID", p.ProcessName);\nint ppid = (int)parent.NextValue();\n\nif (Process.GetProcessById(ppid).ProcessName == "powershell") {\n  Console.WriteLine("running in PowerShell");\n} else {\n  Console.WriteLine("not running in PowerShell");\n}	0
17577154	17554238	How to send an email with its text/html encoded in UTF-8 using SendGrid for C#?	string normalizedString = InString.Normalize(NormalizationForm.FormKD);	0
18335870	18335365	how to create call function in windows phone 8 app?	string MyNumberPhone = "060000000000";\n\nPhoneCallTask phoneCallTask = new PhoneCallTask();\nphoneCallTask.PhoneNumber = MyNumberPhone ;\nphoneCallTask.DisplayName = "UserName";\nphoneCallTask.Show();	0
23763975	23763702	Unable to access inner Xml elements	foreach (XmlNode node in nodes) \n {\n      XmlDocument innerXmlDoc = new XmlDocument();\n\n      innerXmlDoc.LoadXml(node.InnerXml);\n\n      var list  = innerXmlDoc.GetElementsByTagName("Counters");\n\n      for (int i = 0; i < list.Count; i++)\n      {\n         string val = list[i].Attributes["total"].Value;\n      }\n };	0
25712873	25712809	How to read unknown data length in a TCP Client	size_t data_len = strlen(some_data_blob);\nchar lenstr[32];\nsprintf(lenstr, "%zd\n", data_len);\nsend(socket, lenstr, strlen(lenstr));\nsend(socket, some_data_blob, data_len);	0
23096262	23095832	Linq to get distinct subdirectories from list of paths	public static void Main()\n{\n    string[] paths = new[] { "/a/b", "/a/bb", "/a/bbb", "/b/a", "/b/aa", "/b/aaa", "/c/d", "/d/e" }; \n    string root = "/";\n\n    Console.WriteLine(string.Join(", ", paths.Select(s => GetSubdirectory(root, s)).Where(s => s != null).Distinct()));\n}\n\nstatic string GetSubdirectory(string root, string path)\n{\n    string subDirectory = null;\n    int index = path.IndexOf(root);\n\n    Console.WriteLine(index);\n    if (root != path && index == 0)\n    {\n        subDirectory = path.Substring(root.Length, path.Length - root.Length).Trim('/').Split('/')[0];\n    }\n\n    return subDirectory;\n}	0
3077077	3077069	How to get QueryString from a href?	Uri uri = new Uri("http://foo.com/page.html?query");\nstring query = uri.Query;	0
10861302	10636505	How I can do this using skip and take in linq	declare @Skip int = 20\ndeclare @Take int = 10\n\nselect SomeColumn\nfrom (\n   select SomeColumn,\n          row_number() over(order by SomeColumnToOrderBy) as rn\n   from YourTable\n ) T\nwhere rn > @Skip and \n  rn <= @Skip + @Take	0
14768473	14768404	Set groupbox invisible or make a shadow over it c#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        radioButton1.Checked = true;\n        radioButton3.Checked = true;\n        radioButton2.CheckedChanged += radioButton2_CheckedChanged;\n    }\n\n    void radioButton2_CheckedChanged(object sender, EventArgs e)\n    {\n        groupBox2.Enabled = !radioButton2.Checked;\n    }\n}	0
25710197	25709757	how to copy a method insted of copy-paste code in C#?	public Hotels GetAccommodation(string name, string location, int minPrice, int? beds = null)\n{\n    if (beds.HasValue)\n    {\n\n    }\n    else\n    {\n\n    }\n}	0
22883843	22883764	Define a method with out argument	// Us the class name ArgParseHelper (where the static method is defined) not one\n// of its instances\nif (ArgParseHelper.TryGetSecurityGuardModeValue(..)) {\n\n}	0
3966098	3963578	How can I get ValidationSummary messages programmatically?	StringBuilder sb = new StringBuilder();\n\nforeach (ModelState state in ModelState.Values)\n    foreach (ModelError error in state.Errors)\n        sb.AppendFormat("<div>{0}</div>", error.ErrorMessage);	0
15828715	14535507	Writing Special Chars in Xml Tag ( Google Product Xml Feed )	[DataMember]\n        [XmlElement("id", Namespace = "http://base.google.com/ns/1.0")] //g:id\n        public int Id { get; set; }	0
8936039	8935942	How can I know if a decimal terminates?	numerator % denominator	0
4167772	4164830	Geographic Midpoint between two coordinates	private Geocoordinate MidPoint(Geocoordinate posA, Geocoordinate posB)\n{\n   Geocoordinate midPoint = new Geocoordinate();\n\n   double dLon = DegreesToRadians(posB.Longitude - posA.Longitude);\n   double Bx = Math.Cos(DegreesToRadians(posB.Latitude)) * Math.Cos(dLon);\n   double By = Math.Cos(DegreesToRadians(posB.Latitude)) * Math.Sin(dLon);\n\n   midPoint.Latitude = RadiansToDegrees(Math.Atan2(\n                Math.Sin(DegreesToRadians(posA.Latitude)) + Math.Sin(DegreesToRadians(posB.Latitude)),\n                Math.Sqrt(\n                    (Math.Cos(DegreesToRadians(posA.Latitude)) + Bx) *\n                    (Math.Cos(DegreesToRadians(posA.Latitude)) + Bx) + By * By))); \n                 // (Math.Cos(DegreesToRadians(posA.Latitude))) + Bx) + By * By)); // Your Code\n\n   midPoint.Longitude = posA.Longitude + RadiansToDegrees(Math.Atan2(By, Math.Cos(DegreesToRadians(posA.Latitude)) + Bx));\n\n   return midPoint;\n}	0
23163325	23163287	DateTime conversion failed when converting date and/or time from character string	sqlCmd.CommandText = "SELECT * From Report_Sales where Date >= @startDate AND Date <= @endDate";\nsqlCmd.Parameters.AddWithValue("@startDate", startDate);\nsqlCmd.Parameters.AddWithValue("@endDate", endDate);	0
22688903	22688778	Binding to item instead of property inside list box	Visibility="{Binding Converter={StaticResource BetWagerPotentialReturnToVisibilityConverter1}}"	0
27653909	27653881	how to get <li> tags from Html String	HtmlStr = HtmlStr.Replace("<li>","<li class=\"NewClass\">");	0
18694651	18691957	how to set Listpicker items where SelectionMode is multiple	protected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    foreach (var o in GetSelectedObjects())\n    {\n        userCountryList.SelectedItems.Add(o);\n    }\n    base.OnNavigatedTo(e);\n}	0
17291763	17291644	How to get connection string from app.config in another class library project?	public sealed class Helper\n{\n    private Helper()\n    {\n    }\n\n    public static string GetBayrueConnectionString()\n    {\n        return DAL.Properties.Settings.Default.BayrueConnectionString;\n    }\n}	0
9354166	9354154	How do I interpolate strings?	string mystr = string.Format("This is {0}overflow", strVar);	0
33992354	33992306	How do I check if a word in a MS Word document is AllCaps?	private void IsItCaps(string myWord, Microsoft.Office.Interop.Word.Document myDoc)\n{\n    var find = myDoc.Application.ActiveDocument.Range().Find;\n\n    find.ClearFormatting();\n\n    if (find.Font.AllCaps != 0)\n    {\n        MessageBox.Show(myWord + " is AllCaps.");\n    }\n    else if(find.Font.AllCaps == 0)\n    {\n        MessageBox.Show(myWord + " is not AllCaps.");\n    }\n}	0
27247436	27245194	Restricting ManipulationDelta two finger touch	Private Sub gridLeft_ManipulationDelta(sender As Object, e As ManipulationDeltaEventArgs) Handles gridLeft.ManipulationDelta\n\n  Dim element As UIElement = TryCast(e.Source, UIElement)\n  Dim xform As MatrixTransform = TryCast(element.RenderTransform, MatrixTransform)\n  Dim matrix As Matrix = xform.Matrix\n  Dim delta As ManipulationDelta = e.DeltaManipulation\n  Dim center As Point = e.ManipulationOrigin\n  matrix.Translate(-center.X, -center.Y)\n  matrix.Scale(delta.Scale.X, delta.Scale.Y)\n  matrix.Translate(center.X, center.Y)\n  matrix.Translate(delta.Translation.X, delta.Translation.Y)\n\n  If matrix.Determinant >= 2.0 Or matrix.Determinant <= 1.0 Then\n     Return\n  End If\n\n  xform.Matrix = matrix\n  e.Handled = True\n  MyBase.OnManipulationDelta(e)\n\nEnd Sub	0
30380598	30380214	No text in dynamically created CheckBox	checkBox[nr] = new CheckBox();\ncheckBox[nr].Size = new Size(120, 43);\ncheckBox[nr].Name = name;\ncheckBox[nr].Text = name;\ncheckBox[nr].Location = new Point(40, 20 + (nr * 20));\nfrm.Controls.Add(checkBox[nr]);	0
17833310	17833295	To write a linq query to get selected name count	var count = names.Count(x=>x.Name=="Murugan");	0
12399778	12399712	how to remove specific xml elements from the xml content using C#4.0?	xmlString.Replace("<w:p />", "");	0
7629687	7629663	Parsing a .txt file as different data types	string stringData;\ndouble d;\nint i;\n\nstreamReader = new StreamReader(potato.txt);\nwhile (streamReader.Peek() > 0)\n{\n   data = streamReader.ReadLine();\n\n   if (int.TryParse(data, out i) \n   {       \n       Console.WriteLine("{0,8} {1,15}", i, i.GetType());\n   }\n   else if (double.TryParse(data, out d) \n   {       \n       Console.WriteLine("{0,8} {1,15}", d, d.GetType());\n   }\n   else Console.WriteLine("{0,8} {1,15}", data, data.GetType());\n}	0
28527985	28527674	Power a large number with a large number then mode the result	BigInteger number = 10;\nint exponent = 3;\nBigInteger modulus = 30;\nConsole.WriteLine("({0}^{1}) Mod {2} = {3}", \n                  number, exponent, modulus, \n                  BigInteger.ModPow(number, exponent, modulus));   \n//Result: (10^3) Mod 30 = 10	0
6092657	6092623	Pass a value if a checkbox is checked	foreach (KeyValuePair<CheckBox, TextBox> pair in checkToText)\n{\n//do what you need to do\n//pair.Key for checkbox\n//pair.Value for textbox\n}	0
16836465	16836299	C# -> dump all attributes of a class to a dictionary	var a = new A("a", "b", "c");\n    var fields = typeof(A).GetFields();\n    var dict = new Dictionary<string, string>(fields.Length);\n    foreach (var fieldInfo in fields)\n    {\n         dict.Add(fieldInfo.Name, (string)fieldInfo.GetValue(a));\n    }	0
7051976	7051525	How to prevent users from changing the location of windows	public Form1()\n    {\n        InitializeComponent();\n        pt = this.Location;\n    }\n\n    private Point pt;\n    private void Form1_Move(object sender, EventArgs e)\n    {\n        this.Location = pt;\n    }	0
2961060	2960599	.NET createuserwizard - how to provide a pre-filled (and disabled) email field	private TextBox UserName {\n        get { return GetWizardControl<TextBox>("UserName"); }\n    }\n\n    private TextBox Email {\n        get { return GetWizardControl<TextBox>("Email"); }\n    }\n\n    private T GetWizardControl<T>(string id) where T : Control {\n        return (T)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl(id);\n    }	0
23083163	23083051	Acessing properties of an object with initializers	var x = new TopTen\n{\n    Id = 1,\n    Photo = new Image\n    {\n       ImgUrl = "pic.jpg",\n       AlterText = "This is a picture"\n    }\n};	0
11833871	11833336	Work around for session for signalR	System.Runtime.Caching.MemoryCache	0
8572954	8550858	Updating live tiles from Backgroud audio agent?	using System.Linq	0
33371512	33370528	Combining two Datetime values	// take hour from first datetimepicker\nDateTime hour = dateTimePicker1.Value.Hour;\n// take minute from second datetimepicker\nDateTime minute = dateTimePicker2.Value.Minute;\n// combine hour and minute into an object\nDateTime hourAndMinute = hour + minute;\n// convert the combined DateTime into string\nhourAndMinute.ToString("hh:mm");	0
8176233	8175786	How do you extract the directory from a path including wildcards?	Path.GetDirectoryName(path)	0
12268244	12267965	Parse JS date to C# DateTime	string date = "Tue Sep 04 2012B0100 (GMT Daylight Time)";\nvar dt = DateTime.ParseExact(date.Split('(')[0].Replace("B","+").Trim(), "ddd MMM dd yyyyzzz", CultureInfo.InvariantCulture);	0
28040100	28039511	How to change font size dynamically when resize the row header in datagridview using c#?	private void dataGridView1_RowHeightChanged(object sender, DataGridViewRowEventArgs e)\n    {\n        float width =e.Row.Height-3;\n        dataGridView1.RowsDefaultCellStyle.Font = new Font("Arial", width, GraphicsUnit.Pixel);              \n    }	0
2163349	2162859	How to pass value by reference in C#?	IEnumerable<int> Frob(ref int x)\n{  return from foo in whatever where foo.bar == x select foo.bar; }\n\nIEnumerable<int> Blob()\n{ \n    int y = 123; \n    var r = Frob(ref y);    \n    y = 456;\n    return r;\n}\nvoid Grob()\n{\n    foreach(int z in Blob()) { ... }\n}	0
1834064	1833062	How to measure the pixel width of a digit in a given font / size (C#)	var font = new Font("Calibri", 11.0f, FontStyle.Regular);\nint underscoreWidth = TextRenderer.MeasureText("__", font).Width; \nfor (var i = 0; i < 10; i++)\n   {\n      int charWidth = TextRenderer.MeasureText(String.Concat("_", i.ToString(), "_"), font).Width - underscoreWidth;\n      Debug.WriteLine(charWidth);\n   }	0
28192747	28192468	How to make window to appear on center screen when restore down button is clicked? - WPF	void Window1_StateChanged(object sender, EventArgs e)\n{\n    if (this.WindowState == WindowState.Normal)\n       //set window location center to screen\n}	0
1923004	1918401	Need help with adding Where clauses in loop with Linq	foreach (DateClause clause in dateClauses)\n{\n    var capturedClause = clause;\n    switch (clause.Operator)\n    {\n            case Operator.GreaterThan:\n                    query = query.Where(l => l.date > capturedClause.Date);\n                    break;\n            case Operator.LessThan\n                    query = query.Where(l => l.date < capturedClause.Date);\n                    break;\n    }               \n}	0
23728993	23728954	foreach loop item removal from an enumerated collection	.ToList()	0
25651145	25651135	There is an identifier expected but i don't know what i need to put there	public static void playerLocationChange(int[] myIntArrayParam) \n                                        //Notice the name next to int[]\n                                        //This is the parameter's name\n{\n\n}	0
33278701	33210448	Merge 2 Autofac containers into one	public void Merge(this IContainer container1, IContainer container2)\n{ \n    var newBuilder = new ContainerBuilder();\n    newBuilder.RegisterInstance(container2.Resolve<ISomeService1>()).AsImplementedInterfaces();\n    newBuilder.RegisterInstance(container2.Resolve<ISomeService2>()).AsImplementedInterfaces();\n\n    newBuilder.Update(container1);\n    return container1;\n}	0
4393330	4349863	C# Type Availability - Using Application Settings Architecture across applications - Strongly Typed Config	public class ConfigManager : ExternalProjectNamespace.ConfigManager	0
10236560	10234912	How to seed data with AddOrUpdate with a complex key in EF 4.3	context.People.AddOrUpdate(p => new { p.FirstName, p.LastName }, people);	0
28424296	28410540	How to convert this event method from C# to java?	public class BorderPhoto{\n\n    IPhoto pho;\n    Color color;\n\n    public BorderPhoto(IPhoto p, Color c)\n    {\n        pho = p;\n        color = c;\n        this.addPaintEventhandler(new IPhoto(){\n            public void Drawer(object sender, ...other parameters...){\n                // put your code here\n            }\n        }); \n    }\n\n    public void addPaintEventHandler(Iphoto pho){\n        this.pho = pho;\n    }\n\n    public void onDraw(this, ...other parameters...){\n        pho.Drawer(this, ...other parameters...);\n    }\n}	0
4191782	4191575	How to use C# Stream Reader to save a completion of a process?	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.Win32;\nusing System.Diagnostics;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n   static void Main(string[] args)\n   {\n       Process process = new Process();\n       process.StartInfo.FileName = "C:\\temp\\bin\\fls.exe";\n       process.StartInfo.Arguments = "-m C: -r C:\\temp\\image.dd";\n       process.StartInfo.UseShellExecute = false;\n       process.StartInfo.RedirectStandardOutput = true;\n       process.StartInfo.RedirectStandardInput = true;\n       process.StartInfo.RedirectStandardError = true;\n       process.Start();\n\n       System.IO.StreamReader reader = process.StandardOutput;\n       string sRes = reader.ReadToEnd();\n       StreamWriter SW;\n       SW = File.CreateText("C:\\temp\\ntfs.bodyfile");\n       SW.WriteLine(sRes);\n       SW.Close();\n       Console.WriteLine("File Created SucacessFully");\n       reader.Close();  \n   }   \n  }\n}	0
9787184	9787162	A Query Copy from 1 table into another + Values	insert into Table1 (CL1,CL2) SELECT 'TEST', CL2 from Table2 where ID = 2	0
8987369	8987339	How can I guarantee that T is a class?	public static T GetSerializedCopy<T>(T src) where T : class\n    {\n        //some code to obtain a copy\n        return default(T);\n    }	0
33388535	33388312	Order by sum of digits of number	String a = "56 65 74 100 99 68 86 180 90";\n\n  // 100 180 90 56 65 74 68 86 99\n  String result = String.Join(" ", a\n    .Split(' ')\n    .OrderBy(item => item.Sum(ch => ch - '0')) // sum of digits\n    .ThenBy(item => item));                    // lexicographic ("as string")	0
18651190	18649437	How to Add Tile Icon in Windows 8 app development?	.appxmanifest	0
17001231	17001193	Odbc connection string results in login failed	connectionString = @"Driver={SQL Server};Server=local);" + \n                    "Trusted_Connection=Yes;Database=??????;";	0
14404272	14403677	display database datatable info as label array	for (index = 0; index < iLength; index++)	0
2512096	2511670	other way to add item to List<>	arrays arr = new arrays();\n        arr.PriorityQueue = new List<element>(\n            new [] { \n                new element {node = 1, priority =2 }, \n                new element { node = 2, priority = 10}\n                //..\n                //..\n            });\n\n\n        arrays arr2 = new arrays();\n        arr2.PriorityQueue = new List<element>(\n            arr.PriorityQueue\n            );\n\n\n        arrays arr3 = new arrays();\n        arr3.PriorityQueue = new List<element>(arr2.PriorityQueue.FindAll(z => (1 == 1)));\n\n\n        arrays arr4 = new arrays();\n        arr4.PriorityQueue = new List<element>(arr3.PriorityQueue.ToArray());	0
14478377	14477500	Adding object to DataTable and create a dynamic GridView	// remove that line\n// for (int i = 0; i < products.Count; i++)\nint i = 0;\n{    \n    foreach (Product item in products)\n    {    \n        drow = dt.NewRow();\n        dt.Rows.Add(drow);\n        dt.Rows[i][col1] = item.ProductName.ToString();// i.ToString();\n        dt.Rows[i][col2] = item.ProductDescription.ToString();\n        dt.Rows[i][col3] = String.Format("{0:C}", item.Price);\n        dt.Rows[i][col4] = String.Format("{0:.00}", item.Price);\n        // and here move to next\n        i++;\n    }    \n}	0
3337165	3337125	How to get integer quotient when divide two values in c#?	Math.Truncate	0
1519704	1519678	Removing Tabpage from Tabcontrol	tabControl1.TabPages.RemoveByKey("tabPage1");	0
17266230	17082740	C# console application Streaming API 1.1 + Oauth	// Creating the stream and specifying the delegate\nSimpleStream myStream = new SimpleStream("https://stream.twitter.com/1.1/statuses/sample.json");\n// Create the credentials\nIToken token = new Token("userKey", "userSecret", "consumerKey", "consumerSecret");\n// Starting the stream by specifying credentials thanks to the Token\nmyStream.StartStream(token, x => Console.WriteLine(x.Text));	0
10567935	10567701	Regex Replace of Mirc Colour Codes	msg = Regex.Replace(msg, @"[\x02\x1F\x0F\x16]|\x03(\d\d?(,\d\d?)?)?", String.Empty);	0
30467298	30467090	exporting to excel from asp.net getting line breaks to display	sb.AppendFormat(@" <Alignment ss:WrapText=""1"" ss:Vertical=""Bottom""/>{0}", Environment.NewLine);	0
32953890	32953256	Inserting data after checking if table is empty	IF NOT EXISTS (SELECT hostName FROM chtbuster.hostnametable WHERE hostName=@machineName)\n  INSERT INTO chtbuster.hostnametable(hostName_id) VALUES(@machineName);	0
13869751	13868395	Convert this sql query to LINQ to Lambda Left Outer Join	var res = RequiredApplicationDocuments.GroupJoin(Places,\n            p => p.Id,\n            d => d.RequiredApplicationDocumentId,\n            (d, places) => new\n            {\n                Document = d,\n\n                Place = places.Where(p => p.SecondPlaceId == 4).FirstOrDefault(),\n\n                // if don't want to exclude documents with "non-4" places only, \n                // remove this and last where clause\n                // but this is what your SQL does\n                HasNoPlaces = places.Count() == 0 \n\n            }).Where(r => r.HasNoPlaces || r.Place != null);	0
28666444	28666353	C#: Get Most Occurring Element in a List?	var query = activityList.GroupBy(x => x.Location)\n    .Select(group => new {Location = group.Key, Count = group.Count()})\n    .OrderByDescending(x => x.Count);\n\nvar item = query.First();\n\nvar mostfrequent = item.Location;\nvar mostfrequentcount = item.Count;	0
7298207	7298185	Select a DataGridView row after TextBox value C#	foreach (DataGridViewRow row in dataGridView1.Rows)\n{\n    // Test if the first column of the current row equals\n    // the value in the text box\n    if ((string)row.Cells[0].Value == textBox1.Text)\n    {\n        // we have a match\n        row.Selected = true;\n    }\n    else\n    {\n        row.Selected = false;\n    }\n}	0
20773022	20772846	How to attach SQL Server database file (.mdf) during creating of installation file in Visual Studio 2010 using data directory	string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename={0}\\Seminar Library CSE KU\\bookdb.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";\n\n#if DEBUG\n    connectionString = string.Format(connectionString, "E:\\Software\\Projects\\Visual Studio project\\");\n#else\n    connectionString = string.Format(connectionString, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));\n#endif\n\n// Use your connection string here.	0
12345453	12343533	Extension for Umbraco /base	Node SelectedCollection = currentNode.Children.OfType<Node>().Where(elm => elm.Name == collectionID).SingleOrDefault();	0
16524755	16524018	Windows CE. How to kill a process by name?	ProcessInfo[] list = ProcessCE.GetProcesses();\n\n        foreach (ProcessInfo pinfo in list)\n        {\n            if (pinfo.FullPath.EndsWith("MyExe.exe"))\n                pinfo.Kill();\n        }	0
28411609	28411447	C# - JSON to Key Value & vice versa	dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");\n\nConsole.WriteLine(d.number);\nConsole.WriteLine(d.str);\nConsole.WriteLine(d.array.Count);	0
26972471	26972290	Correct pattern for Regex.Split	//Based on:\n\n//.NET 4.5\n\n//Program that uses Match, Regex: C#\n\nusing System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main()\n    {\n        String subject = "ABC123456DEF\n123456\nABC123456\n123456DEF"\n        Regex regex = new Regex(@"([a-zA-Z]+)|([0-9]+)");\n        foreach (Match match in regex.Matches(subject))\n        {\n            MessageBox.Show(match.Value);\n        }\n    }\n}	0
32601062	32600972	Format decimal to number of decimal places without scientific notation	0.1234567.ToString("0.####")	0
18120556	18120406	How to get from points array points with biggest Y and smallest Y?	Point Max = Points.MaxBy(p => p.Y);\nPoint Min = Points.MinBy(p => p.Y);	0
27937071	27936271	use a master report viewer to show all reports in RDLC	DataSet ds = SomeMethodToRetrieveDataSet(); // e.g. via DataAdapter\n// Set parameters, \nReportParameter[] parameters = new ReportParameter[...];  \nReportDataSource reportDataSource = new ReportDataSource();\n//match the DataSource in the RDLC\nreportDataSource.Name = "ReportData"; \nreportDataSource.Value = ds.Tables[0];\n\n// Addparameters to the collection\nreportViewer1.LocalReport.SetParameters(parameters); \nreportViewer1.LocalReport.DataSources.Add(reportDataSource);\nreportViewer1.DataBind();	0
13384811	13384709	Unique Dictionaries in a list of dictionaries(c#)	class DictionaryComparer<TKey, TValue> \n    : IEqualityComparer<Dictionary<TKey, TValue>>	0
12229280	12212407	Can I map multiple query string values to a single controller (object) parameter?	public HttpResponseMessage Post([FromUri] MyModel model) { ... }	0
25529955	25485295	Couchbase configuring client programmatically	var config = new CouchbaseClientConfiguration();\n            foreach (var uri in uris)\n            {\n                config.Urls.Add(uri);\n            }\n            config.Bucket = bucketName;\n            config.BucketPassword = bucketPassword;\n\n            _cbc = new CouchbaseClient(config);	0
5966637	5966526	Conditionally hide or show Aspx Menu Control Item	MenuItem mnuItem = mnu.FindItem(""); // Find particular item\nmnu.Items.Remove(mnuItem);	0
14018456	13801453	error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near	MySqlParameter userName = new MySqlParameter("?UserName", MySqlDbType.VarChar);\nuserName.Value = txtUserName.Text;\nMySqlParameter password = new MySqlParameter("?Password", MySqlDbType.VarChar);\npassword.Value = txtPassword.Text;\nMySqlParameter FirstName = new MySqlParameter("?FirstName", MySqlDbType.VarChar);\nFirstName.Value = txtFirstName.Text;\nMySqlParameter LastName = new MySqlParameter("?LastName", MySqlDbType.VarChar);\nLastName.Value = txtLastName.Text;\n\nentities.ExecuteStoreCommand("CALL uspInsertUsers(?UserName,?Password,?FirstName,?LastName)", userName,password,FirstName,LastName);	0
23453469	23453365	How To Collect all listbox items in a textbox in c#	foreach (string item in listBox1.Items)\n      textBox1.Text += item.Contains("@") ? string.Format("{0}#", item.Split('@')[0]) : string.Empty;	0
610198	610183	Printing WebBrowser control content	private void PrintHelpPage()\n{\n    // Create a WebBrowser instance. \n    WebBrowser webBrowserForPrinting = new WebBrowser();\n\n    // Add an event handler that prints the document after it loads.\n    webBrowserForPrinting.DocumentCompleted +=\n        new WebBrowserDocumentCompletedEventHandler(PrintDocument);\n\n    // Set the Url property to load the document.\n    webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");\n}\n\nprivate void PrintDocument(object sender,\n    WebBrowserDocumentCompletedEventArgs e)\n{\n    // Print the document now that it is fully loaded.\n    ((WebBrowser)sender).Print();\n\n    // Dispose the WebBrowser now that the task is complete. \n    ((WebBrowser)sender).Dispose();\n}	0
9088022	9087983	Regular expression to make sure of the word GO	Regex regex = new Regex("^GO$", RegexOptions.IgnoreCase), RegexOptions.IgnoreCase);\nMatch match = regex.Match(text);\nwhile (match.Success) \n{\n    // Logic\n    match = match.NextMatch();\n}	0
13126907	13126702	How can I read X lines down from another line in a text file?	string[] readText = File.ReadAllLines("myfile.txt");\n\nfor (int i = 0; i < readText.Length; i++)\n{\n    if (readText[i].StartsWith("OTI") && readText[i+2].StartsWith("REF*11")){\n       string number = readText[i+2].Substring("REF*11".Length, 10);\n       //do something \n    }\n}	0
29195546	29195432	Fill dictionary with lists	var AB = A.Select(e => new { Key = e, Value = "A" }).Union(\n         B.Select(e => new { Key = e, Value = "B" }) )\n        .ToDictionary(e => e.Key, e => e.Value);	0
3586715	3586647	How to cast binary resource to short array?	using (var reader = new BinaryReader(new MemoryStream(Properties.Resources.IndexTable)))\n{\n    var firstValue = reader.ReadInt16();\n    ...\n}	0
3844229	3844208	Html Agility Pack: Find Comment Node	htmlDoc.DocumentNode.SelectSingleNode("//comment()[contains(., 'Buying Options')]/following-sibling::script")	0
34178921	34178833	Linq query to Check and get dictionary item from list of dictionary items	List<Dictionary<string, string>> lstOfDict = new List<Dictionary<string, string>>();            \nlstOfDict.Add(new Dictionary<string, string> \n{ \n    ["name"] = "Adam", \n    ["mail"] = "abc@abc.com"\n}); \n\nvar containsEmail = lstOfDict.SelectMany(x => x).Where(x => x.Key == "mail");	0
29042159	29019272	How can I partially load handlers with NServiceBus?	configuration.AssembliesToScan(myListOfAssemblies);	0
9462428	9461599	how to compare Dictionary key value and Tuple key value	foreach (var item in PathList)\n {\n    Tuple<int, int> temp = new Tuple<int, int>(item.Key, 0);\n       //if (x.Equals(item.Key) && x[item.Key].Equals(0))\n    if (x.Contains<Tuple<int, int>>(temp))\n      {\n         string path1 = Path.Combine(GetDirectory(item.Value), item.Value);\n         File.Delete(path1);\n       }\n   }	0
1235464	1235386	Unregister a DLL on a Pocket PC	regsvrce.exe	0
7682571	7682560	Printing a comma (,) after each item in an array	Console.WriteLine(string.Join(",", A));	0
22565221	22564953	if return date is expired make background color red?	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "return_date")\n    {\n        var returnDate = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["return_date???"].Value);\n        var borrowDate = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["borrow_date"].Value);\n        if (returnDate > borrowDate)\n        {\n            e.CellStyle.BackColor = Color.Red;\n        }\n        else\n        {\n            e.CellStyle.BackColor = SystemColors.Window;\n        }\n    }\n}	0
12345484	12345150	Save list of entity with Entity Framework	using (var context = new MyContext())\n{\n    try\n    {\n        foreach(var row in accounts){\n            context.AddToAccounts(row);\n        }\n        context.SaveChanges();\n    }catch (Exception ex){\n        //Log any exception here.\n    }     \n}	0
13529071	13528730	Suppress Microsoft.Reliability warning on lambda	private readonly Lazy<IWindsorContainer> LazyContainer =\n    new Lazy<IWindsorContainer>(() => { \n        var container = new WindsorContainer();\n        try { container.Install(new WindsorInstaller())); }\n        catch { using(container) {} throw; }\n        return container; });	0
16800314	16800241	Get Average TimeSpan from a Group	foreach (var group in _groupedItems) {\n   var avg = TimeSpan.FromSeconds(group.Average(i => i.Duration.TotalSeconds));\n}	0
17521910	17490202	Windows phone 8 GeoFencing using Nokia Maps	projects.developer.nokia.com	0
29869561	29869286	Set style of TextBlock programatically	var MyText = new TextBlock();\nMyText.Text = drop;\nMyText.Style = (Style)Application.Current.Resources["ListViewItemTextBlockStyle"];	0
5824222	5824182	Copy image file from web url to local folder?	byte[] data;\nusing (WebClient client = new WebClient()) {\n  data = client.DownloadData("http://testsite.com/web/abc.jpg");\n}\nFile.WriteAllBytes(@"c:\images\xyz.jpg", data);	0
17468666	17468596	Can string.format sequence appear in any order	return  string.Format("/{0}/abc.aspx?IDA={1}&Name={2}&Teacher={3}",\n                    NewPropertyValue, ID, Name, Teacher);	0
13899461	13899315	Skipping validation for closing the form from the controlbox	private void Form2_FormClosing(object sender, FormClosingEventArgs e)\n        {\n            if (textBox1.CausesValidation)\n            {\n                textBox1.CausesValidation = false;\n                Close();\n            }\n        }	0
30938519	30938260	Getting inherited public static field with Reflection in Portable Class Libraries	public static FieldInfo[] DeclaredFields(TypeInfo type)\n{\n    var fields = new List<FieldInfo>();\n\n    while (type != null)\n    {\n        fields.AddRange(type.DeclaredFields);\n\n        Type type2 = type.BaseType;\n        type = type2 != null ? type2.GetTypeInfo() : null;\n    }\n\n    return fields.ToArray();\n}	0
31333984	31333936	Make selection frame follow picturebox after resize	pictureBox3.Left += (this.Width - windowWIDTH)/2;\npictureBox3.Top += (this.Height - windowHEIGHT)/2;	0
21999688	21785556	Read a file that is already open in Word	StorageFile tempFile = await storageFile.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.GenerateUniqueName);\nusing (var stream = await tempFile.OpenReadAsync())\n{\n    // Do stuff with the stream.\n}	0
12055878	12055702	Create context for a part of code	class Context : IDisposable {\n    [ThreadStatic]\n    private static Context _instance;\n    [ThreadStatic]\n    private static int _instanceCounter;\n\n    public static Context Instance() {\n        if (_instanceCounter == 0) {\n            _instance = new Context();\n        }\n        _instanceCounter++;\n        return _instance;\n    }\n\n    private static void Release() {\n        _instanceCounter--;\n        if (_instanceCounter == 0) {\n            if (_instance != null)\n                _instance.Dispose();\n            _instance = null;\n        }\n    }\n\n    public void Dispose() {\n        Release();\n    }\n}\n\npublic class Test {\n    public void Test1() {\n        using (var context = Context.Instance()) {\n            // do something\n            Test2();\n        }\n    }\n\n    private void Test2() {\n        using (var context = Context.Instance()) {\n            // identical context as in Test1\n            // do something\n        }\n    }\n}	0
21537653	21537639	Check if List value matches a list value in another list	if(MyGlobals.ListOfItemsToControl.Any\n     (x => MyGlobals.lstNewItems.Any(y => y.sItemName == x.sItemName))) \n{\n...\n}	0
6889458	6889400	Comparing Bytes to Hex?	//byte[] A2S_PLAYER = StringToByteArray("\xFF\xFF\xFF\xFF\x55");\nbyte[] A2S_PLAYER = new byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x55} ;	0
22914478	22913755	Trigger an event continuously in KinectExplorer-WPF solution	CompositionTarget.Rendering	0
2642760	2642754	XML how to check if node is returning null?	var n = doc.SelectSingleNode("WhoisRecord/registrant/email");\nif (n != null) { // here is the check\n  DoSomething(n.InnerText);\n}	0
19643207	18465504	HttpWebRequest is slow with chunked data	ServicePointManager.UseNagleAlgorithm = false	0
8498416	8498246	Getting SetDesktopBounds to stick	static void Main() {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        var main = new Form1();\n        main.Load += delegate { main.SetDesktopBounds(100, 100, 300, 300);  };\n        Application.Run(main);\n    }	0
6783552	6783466	Attach to an open instance of Power Point	Marshal.GetActiveObject ("Powerpoint.Application")	0
8471463	7886710	Mapping databases for new login	public static void MapUserToAllTheDatabases(String Server, String Server_UserName, String Server_Password, String LoginName,String user_Username)\n    {\n        ServerConnection conn = new ServerConnection(Server, Server_UserName, Server_Password);\n        Server srv = new Server(conn);\n        DatabaseCollection dbs = srv.Databases;\n        foreach (Database d in dbs)\n        {\n            bool ifExists = false;\n            foreach (User user in d.Users)\n                if (user.Name == user_Username)\n                    ifExists = true;\n\n            if (ifExists == false)\n            {\n                User u = new User(d, user_Username);\n                u.Login = LoginName;\n                u.Create();\n                u.AddToRole("db_owner");\n            }\n        }\n        srv.Refresh();\n    }	0
3664818	3664638	Downloading Files in Silverlight 3	Uri downloadLink = new Uri("http://www.google.com/intl/en_com/images/srpr/logo1w.png", UriKind.Absolute);\n// try to download the file via browser\nSystem.Windows.Browser.HtmlPage.Window.Navigate(downloadLink, "_blank", "height=300,width=600,top=100,left=100");	0
1344914	1344898	Implementing Nullable Types in Generic Interface	public class MyWrapperClass<T> where T : struct \n{\n    public Nullable<T> Item { get; set; }   \n}\n\npublic class MyClass<T> where T : class \n{\n\n}	0
10279007	10278822	Bind only specific items to gridview from list	GridView.DataSource = from t in yourList\n                      select new \n                       {\n                       t.Name,\n                       t.Enable\n                       };	0
13257480	13257454	Get enum index from string	int animalNumber = (int)Enum.Parse(typeof(Animals), "Dog");	0
7803574	498079	Agent-less method to enumerate certificates on a remote machine	X509Store store = new X509Store(@"\\machinename\MY", StoreLocation.LocalMachine);	0
18098882	18016699	Can I show selective grid lines in a devexpress chart?	private void Form1_Load(object sender, EventArgs e)\n    {\n        Series series1 = new Series("Series 1", ViewType.Point);\n        series1.Points.Add(new SeriesPoint(1, 50));\n        series1.Points.Add(new SeriesPoint(2, 150));\n        series1.Points.Add(new SeriesPoint(4, 20));\n        series1.Points.Add(new SeriesPoint(7, 210));\n        series1.Points.Add(new SeriesPoint(12, 70));\n        chartControl1.Series.Add(series1);\n\n        XYDiagram diagram = chartControl1.Diagram as XYDiagram;\n        foreach (SeriesPoint item in series1.Points)\n        {\n            DrawConstantLines(diagram, int.Parse(item.Argument), diagram.AxisX);\n            DrawConstantLines(diagram, (int)item.Values[0], diagram.AxisY);\n        }\n    }\n\n    private void DrawConstantLines(XYDiagram diagram, int value, Axis axis)\n    {\n        ConstantLine constantLine1 = new ConstantLine();\n        axis.ConstantLines.Add(constantLine1);\n        constantLine1.AxisValue = value;\n    }	0
2325230	2325213	How to compare in C#	string a = "50";\nstring b = "60";\nbool isBGreaterThanA = Convert.ToInt32(b) > Convert.ToInt32(a);	0
3353759	3352358	Overlay two bitmap images in WPF	var group = new DrawingGroup();\ngroup.Children.Add(new ImageDrawing(new BitmapImage(new Uri(@"...\Some.jpg", UriKind.Absolute)), new Rect(0, 0, ??, ??)));\ngroup.Children.Add(new ImageDrawing(new BitmapImage(new Uri(@"...\Some.png", UriKind.Absolute)), new Rect(0, 0, ??, ??)));\n\nMyImage.Source = new DrawingImage(group);	0
10252742	10249714	How can I get the latest change-set number via TFS API	TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, true);\ntpp.ShowDialog();\n\nvar tpc = tpp.SelectedTeamProjectCollection;\n\nVersionControlServer versionControl = tpc.GetService<VersionControlServer>();\n\nvar tp = versionControl.GetTeamProject("MyTeamProject");\nvar path = tp.ServerItem;\n\nvar q = versionControl.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.Full, null, VersionSpec.Latest, VersionSpec.Latest, Int32.MaxValue, true, true, false, false);\n\nChangeset latest = q.Cast<Changeset>().First();\n\n// The number of the changeset\nint id = latest.ChangesetId;	0
14621031	14620359	Getting error while fetching information from windows live server	// I do not know how you create the byteArray\nbyte[] byteArray = Encoding.UTF8.GetBytes(postData);\n// but you need to send a string\nstring strRequest = Encoding.ASCII.GetString(byteArray);\n\nWebRequest request = WebRequest.Create("https://oauth.live.com/token");\nrequest.ContentType = "application/x-www-form-urlencoded";\n\n// not the byte length, but the string\n//request.ContentLength = byteArray.Length;\nrequest.ContentLength = strRequest.Length;\n\nrequest.Method = "POST"; \n\nusing (StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))\n{\n    streamOut.Write(strRequest);\n    streamOut.Close();\n}\n\nstring strResponse;\n// get the response\nusing (StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))\n{\n    strResponse = stIn.ReadToEnd();\n    stIn.Close();\n}\n\n// and here is the results\nFullReturnLine = HttpContext.Current.Server.UrlDecode(strResponse);	0
21630575	21630446	Convert IDictionary<Guid,string> to the IEnumerable<SelectListItem>	dictionary.Select(x => new SelectListItem  { Text = x.Value, Value = x.Key })	0
5182244	5182178	How to convert PNG to BMP at runtime?	using(MemoryStream stream = new MemoryStream())\n{\n    Dummy.Save(stream, ImageFormat.Bmp); \n}	0
912644	912636	How to create a const member for an immutable type?	public static readonly Point3 Origin = new Point3(0,0,0);	0
6890657	6890572	How get list of datetimes from date range?	DateTime checkIn = new DateTime(_checkInYear, _checkInMonth, _checkInDay);\nDateTime checkOut = new DateTime(_checkOutYear, _checkOutMonth, _checkOutDay);\n\nTimeSpan span = checkOut - checkIn;\nList<DateTime> range = new List<DateTime>();\nfor(int day = 0; day <= span.Days; day++) \n{\n    range.Add(checkIn.AddDays(day));\n}	0
6143233	6143162	Get the intersect of two list with specific criteria	var result = from c1 in List1\n             join c2 in List2 on c1.Name equals c2.Name\n             select new CarInfo()\n             {\n                 Name = c1.Name, // Doesn't really matter which you take\n                 Year = c1.Price < c2.Price ? c1.Year : c2.Year,\n                 Price = c1.Price < c2.Price ? c1.Price : c2.Price\n             };	0
9876113	9875940	How to properly decode accented characters for display	System.Web.HttpUtility.HtmlDecode("Caf&eacute;")	0
1249263	1249249	Convert below C# dynamic data context registration code to VB?	MetadataProviderFactory = Function(type) new DefaultTypeDescriptionProvider(\n    type, new AssociatedMetadataTypeTypeDescriptionProvider(type))	0
10768528	10767591	Activator Crashes on combobox set autocomplete mode	thread.SetApartmentState(ApartmentState.STA);	0
5747629	5747496	Detecting button enable in another application	[DllImport("user32.dll", CharSet=CharSet.Auto)]\npublic static extern IntPtr FindWindow(string strClassName, int nptWindowName);	0
30232757	30232704	How to split elements of the group in many lists?	List<List<MyType>> myResultList = \n      myOriginalList.GroupBy(x=>x.IDReferenceElement)\n                    .Select(gr=>gr.ToList()) // convert each group into List\n                    .ToList();	0
10423310	10423292	How do I using linq-only unwrap multi-dimentional array into a one-dimentional?	IEnumerable<string> Unwrap(IEnumerable<IEnumerable<string>> data)\n{\n    return data.SelectMany(d => d);\n}	0
30829649	30828893	Unity setting GUIText of another object	gameController = GetComponent<GameController> ();	0
22492726	22492576	On converting a string to a DateTime object	string inputDate = "Tue Mar 18 14:37:34 PDT 2014";\ninputDate = inputDate.Replace("PDT", "-7");\nDateTime d = DateTime.ParseExact(inputDate, "ddd MMM dd HH:mm:ss z yyyy", culture);\nConsole.WriteLine(d);	0
9019284	9017240	Clean implementation of storing current row index	int i = 0;\ntry\n{\n    // Some code here - which could throw an exception\n\n    try{\n        foreach (DataRow row in DataTables[0].Rows)\n        {\n            // My stuff\n            i++;\n        }\n        // Some code here - which could throw an exception\n    }\n    catch{\n      i--;\n      throw;\n    }\n\n}\ncatch\n{\n    // Use the counter\n    DataRow row = DataTables[0].Rows[i];\n}	0
33178727	33177237	How to Get Exception Detail	private static CustomServiceFault GetCustomException(Exception exception)\n{                       \n    var customServiceFault = new CustomServiceFault\n    {\n        ErrorMessage = exception.Message,\n        Source = exception.Source,\n        StackTrace = exception.StackTrace,\n        Target = exception.TargetSite.ToString(),\n\n        // You should fill this property with details here.\n        InnerExceptionMessage = exception.InnerException.Message;\n    };    \n\n    return customServiceFault;\n}	0
27855324	27824674	How do I assert that a property was set on a StrictMultiMock using RhinoMocks	AssertWasCalled(m => p.Thing = new ThingClass()	0
1855533	1831071	Real-time video encoding for mobile	System.IO.MemoryStream	0
7754930	7754889	Validate user input C# (console)	int number = 0;\nbool result = Int32.TryParse(value, out number);\nif (result)\n{\n   Console.WriteLine("Converted '{0}' to {1}.", value, number);         \n}	0
7888299	7888041	Split pdf a4 to a5 with a command line tool	var _readerGlobal = new PdfReader(@"c:\temp\bicicleta.pdf");\nMemoryStream _thePdfFile = new MemoryStream();\n\nvar _documentGlobal = new Document(PageSize.A5, 50, 50, 50, 50);\n\nvar _writerGlobal = PdfWriter.GetInstance(_documentGlobal, _thePdfFile);\n_writerGlobal.SetFullCompression();\n\n_documentGlobal.Open();\n\nvar _cbGlobal = _writerGlobal.DirectContent;\nPdfImportedPage page1 = _writerGlobal.GetImportedPage(_readerGlobal, 1);\n_cbGlobal.AddTemplate(page1, 1f, 0, 0, 1f, 0, 0);\n\n_documentGlobal.CloseDocument();\n\nvar _pdfBytes = _thePdfFile.ToArray();\nFile.WriteAllBytes(@"c:\temp\bicicletaA5.pdf", _pdfBytes);	0
14394350	14384151	Type safe enum pattern implementation with generics	public class KnownSetting : Setting<object>\n{\n    private KnownSetting(string key, object defaultValue, Func<string, object> converter) : base(key, defaultValue, converter) { }\n\n    public readonly static Setting<string> Name = Create<string>("name", "Default Name", t => t);\n    public readonly static Setting<int> Size = Create<int>("size", 25, t => Convert.ToInt32(t));\n}\n\npublic class Setting<T>\n{\n    public string Key { get; set; }\n    public T DefaultValue { get; set; }\n    public Func<string, T> Converter { get; set; }\n\n    protected static Setting<U> Create<U>(string key, U defaultValue, Func<string, U> converter)\n    {\n        return new Setting<U>(key, defaultValue, converter);\n    }\n\n    protected Setting(string key, T defaultValue, Func<string, T> converter)\n    {\n        Key = key;\n        DefaultValue = defaultValue;\n        Converter = converter;\n    }\n}\npublic static class Program\n{\n    static void Main(string[] args)\n    {\n        var x = KnownSetting.Name;\n    }\n}	0
22511062	22510970	How to Escape Characters in String Parameters	"Data Source=laptop4\\laptop4;...	0
8532420	8532225	Compare values of two hash tables in loop	Hashtable OldTable = new Hashtable();\nHashtable NewTable = new Hashtable();\n\n        foreach (DictionaryEntry entry in OldTable)\n        {\n            if(NewTable.ContainsKey(entry.Key))\n            {\n                //Do something?\n            }\n        }	0
2727265	2727246	Mouse coordinates on Screen	SetWindowsHookEx()	0
25605270	25605001	C# storing value for T to convert back later	typeof(DoSomethingClass).GetMethod("DoSomething")\n.MakeGenericMethod(message.MessageType).Invoke(InstanceOfDoSomething, message);	0
8513551	8513491	Select a random single record in controller	var selection = db.CJAds.Where(c => c.category_id == 1 && c.ad_active);\nCJAd cjad = selection\n    .OrderBy(c => c.id)\n    .Skip(new Random().Next(selection.Count()))\n    .First();	0
27295426	27295349	How can i check if listView items contains FileInfo variable?	if (listView1.Items.Cast<ListViewItem>().Any(item=>item.Text == fi.FullName))\n{\n   // whatever you want\n}	0
10840971	10840711	C# - Get Seed from Sequence	23,56,45,78,80	0
375777	375764	Update the date of a datetime object when using datetime.addhours(-1)	DateTime.Now.Subtract(new TimeSpan(1, 0, 0));	0
12016830	12016745	How to make a list with Unique entries?	class Item\n{\n    public string ItemNo { get; set; }\n    public string FileName { get; set; }\n}\n\nvar result = list.GroupBy(item => item.ItemNo)\n                 .Select(g => new Item\n                   {\n                       ItemNo = g.Key,\n                       FileName = string.Join(", ",  g.Select(s => s.FileName))\n                   });	0
20817926	20817829	Obtaining Object ID of SelectedValue from WPF ListBox	_currentCustomer = _repository.GetCustomerGraph(\n                  ((int)customerListBox.SelectedValue)\n                  );	0
873055	873044	How to transform an enumeration of long to a single string with LINQ	string str = string.Join(", ", myLongs.Select(l => l.ToString()).ToArray());	0
10479380	10450353	Update/Insert into table	if (ds_dok.Tables[0].Rows.Count <= 0)\n                    {\n                        myQuery = " INSERT INTO ordersstavke (BrDok, " +\n                                  " SifParFil) " +\n                                  " VALUES ('" + rw_mat["brdok"] + "', '" +\n                                                 rw_mat["sifskl_kor"] + "')";\n                    }\n                    else if (ds_dok.Tables[0].Rows.Count >= 1)\n                    {\n\n                        myQuery = "UPDATE ordersstavke " +\n                                  "SET BrDok = '" + rw_mat["brdok"] + "', " +\n                                  "SifParFil = '" + rw_mat["sifskl_kor"] + "', " +\n                                  "WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";\n\n                    }	0
12495440	12494694	Maskfield selected values	ArrayList maGroupNames; // This is my array of options (string)\nint mCategory; // This is my maskfield's result\n\nfor (int i = 0; i < maGroupNames.Count; i++)\n{\n    int layer = 1 << i;\n    if ((mCategory & layer) != 0)\n    {\n        //This group is selected\n    }\n}	0
7848554	7848496	remove a value from an int array c#	public void Linq50()\n{\n    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };\n    int[] numbersB = { 1, 3, 5, 7, 8 };\n\n    var commonNumbers = numbersA.Intersect(numbersB);\n\n    Console.WriteLine("Common numbers shared by both arrays:");\n    foreach (var n in commonNumbers)\n    {\n        Console.WriteLine(n);\n    }\n}	0
22484479	22480796	Formatting a summed number within an iif in RDLC	//set value\nYourTextBox.Value = Sum(IIf(expression, num1 + num2 + num3, num4 + num5 + num6))\n\n//format value\nYourTextBox.Format = IIf(ReportItems!YourTextBox.Value >= 10000000, "c2", "f2")\n\n//format style\nYourTextBox.BackgroundColor = IIf(ReportItems!YourTextBox.Value >= 10000000, "Red", "Lime")	0
11660157	11660127	Faster way to swap endianness in C# with 32 bit words	public static unsafe void SwapX4(Byte[] Source)  \n{  \n    fixed (Byte* pSource = &Source[0])  \n    {  \n        Byte* bp = pSource;  \n        Byte* bp_stop = bp + Source.Length;  \n\n        while (bp < bp_stop)  \n        {\n            *(UInt32*)bp = (UInt32)(\n                (*bp       << 24) |\n                (*(bp + 1) << 16) |\n                (*(bp + 2) <<  8) |\n                (*(bp + 3)      ));\n            bp += 4;  \n        }  \n    }  \n}	0
6753016	6752844	AutoMapper Data Filling	var foo = new Foo { PropA = "", PropB = "Foo" };\nvar bar = new Bar { PropertyA = "Bar", PropertyB = "" };\n\nMapper.CreateMap<Foo, Bar>()\n      .ForMember(dest => dest.PropertyA, opt => opt.MapFrom(src => src.PropA));\n\nMapper.Map<Foo, Bar>(foo, bar);	0
15267801	15267636	How I can remove a item in my ListView?	if (e.CommandName == "Delete")\n        {\n            int index = Convert.ToInt32(e.CommandArgument);\n\n            int listcount = ListView.Items.Count;\n\n            if (listcount - 1 == index)\n            {\n                dataTable.Rows[index].Delete();\n\n                ListView.datasource = datatable;\n                ListView.DataBind();\n            }\n\n        }	0
11401982	11401947	Styling from code behind	dg.Style = this.Resources["DataGridStyle"] as Style;	0
3727061	3726896	C# Cookies based on login information	private static void ExpireCookies(HttpContext current)\n    {\n        var allCookies = current.Request.Cookies.AllKeys;\n\n        foreach (var cook in allCookies.Select(c => current.Response.Cookies[c]).Where(cook => cook != null))\n        {\n            cook.Value = "";\n            cook.Expires = DateTime.Now.AddDays(-1);\n            current.Response.Cookies.Remove(cook.Name);\n        }\n\n    }	0
5986817	5986794	Saving to a class variable	List<string> myField;	0
19186272	19186112	AbsolutePath with QueryString	string myUrl = Request.RawUrl.toString();\nif (myUrl.Contains("/Guidance.aspx")\n    {\n        if (Request.IsSecureConnection)\n        {\n          var queryString = myUrl.Substring(myUrl.IndexOf("?"));\n          Reponse.Redirect("http://www.example.com/Guidance.aspx" + queryString);\n        }\n        return;\n    }	0
4750737	4749676	Finding a user in an OU	using System.DirectoryServices\n\nDirectoryEntry de = new DirectoryEntry();\nde.Path = "LDAP://**Your connection string here**";\nde.AuthenticationType = AuthenticationTypes.Secure;\n\nDirectorySearcher search = new DirectorySearcher(de);\nsearch.Filter = "(SAMAccountName=" + account + ")";\n\n//What properties do we want to return?\nsearch.PropertiesToLoad.Add("displayName");\nsearch.PropertiesToLoad.Add("mail");\n\nsearch.SearchScope = SearchScope.OneLevel //this makes it only search the specified level\n\nSearchResult result = search.FindOne();\n\nif (result != null)\n{\n     //Get Him!    }\nelse\n{\n    //Not Found\n}	0
16052039	16051609	Use Linq to read data from an online XML file	XDocument xdoc = XDocument.Load(@"MyFile.xml");\n        var lv1s = from lv1 in xdoc.Descendants("type")\n                   .Where(l => (string) l.Attribute("id") == "17392")\n                   .Descendants("buy")\n                   select (string)lv1.Element("max");\n\n\n        string Result = "";\n        foreach (var lv1 in lv1s)\n        {\n            Result = lv1.ToString();\n        }	0
4503225	4503161	How do I render DateTime after it passes through Json	string dateStr = dateObject.ToString("dd-MMM-yyyy"); // format depends on your need or preference	0
5030544	5018472	How can i get my friends using my facebook App with graph api asp.net	string query = "SELECT uid FROM user WHERE has_added_app=1 and uid IN (SELECT uid2 FROM friend WHERE uid1 =" + su.FbId + ")";\n        JsonArray friendsArray = (JsonArray)facebook.Query(query);	0
1244837	1242825	How to set datasource for fields in XtraReports without having a dataset at design time?	myDataSet.WriteXml("C:\myDataSourceSchema.xml", System.Data.XmlWriteMode.WriteSchema)	0
31678395	31663378	How do I convert a Value2 string to a DateTime (Excel Interop)	for (int i = 2; i <= rowCount; i++)\n        {\n            string storeId = xlRange.Cells[i, 1].Value2.ToString();\n            string employeeId = xlRange.Cells[i, 2].Value2.ToString();\n            string employeeName = xlRange.Cells[i, 3].Value2.ToString();\n            string position = xlRange.Cells[i, 4].Value2.ToString();\n            string hDate = Convert.ToString(xlRange.Cells[i, 5].Value);\n            string cDate = Convert.ToString(xlRange.Cells[i, 6].Value);\n\n            table.Rows.Add(storeId, employeeId, employeeName, position, hDate, cDate);\n        }	0
28997492	28997387	Adding a shuffle to a WMPlib playlist	wplayer.currentPlaylist = playlist;\nwplayer.settings.setMode("shuffle", true); // this does the trick\nwplayer.controls.play();	0
13320965	13320910	String FormatException	if (name.Any(char.IsNumber))\n{\n    Console.WriteLine("Invalid Name.");\n}\nConsole.ReadLine();	0
7366784	7333574	Calculate weight between known points on a graph?	Find the two point p1 and p2 that are on the "left" and "right" of p\ndistance = distance(p1, p2)\ndistance_p1 = distance(p, p1)\nweight_diff = p1.weight - p2.weight\nweight_p = p1.weight + (distance_p1 / distance) * weight_diff	0
7670668	7670633	Maximum columns for a Console in C#	Console.LargestWindowWidth\nConsole.LargestWindowHeight	0
3107614	3107550	how to store a list of objects in session	[Serializable]	0
22371446	22370564	How to highlight Tree path of selected node in TreeView control?	protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)\n{\n    HighlightPath(TreeView1.SelectedNode);\n}\nprivate void HighlightPath(TreeNode node)\n{\n    //  node.["style"] = "color: orange";\n    node.SelectAction = TreeNodeSelectAction.None;\n    node.Text = "<div style='color:orange'>" + node.Text + "</div>";\n    if (node.Parent != null)\n        HighlightPath(node.Parent);\n\n}	0
28501738	28501675	LINQ statement needs to be optimized	var dbQuery = from e in db.Employees\n              where e.id == 746\n              join f in db.CoWorker on e.CoWorkerID equals f.ID into fa\n              from fr in fa.DefaultIfEmpty()\n              select new { e.id, e.name, fr.FirstName, fr.LastName };\nvar query = dbQuery.AsEnumerable()\n                   .Select(x => new {\n                       x.id,\n                       x.name,\n                       coWorkerName = x == null \n                           ? ""\n                           : x.FirstName + " " + x.LastName\n                   });	0
32724115	32210879	Windows 10: HID Communication in C#	private void ControlDevice_InputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args)\n    {\n        HidInputReport inputReport = args.Report;\n        IBuffer buffer = inputReport.Data;\n        DataReader dr = DataReader.FromBuffer(buffer);\n        byte[] bytes = new byte[inputReport.Data.Length];\n        dr.ReadBytes(bytes);\n\n        String receivedMessage = System.Text.Encoding.ASCII.GetString(bytes);\n        handleRead_HID(receivedMessage);\n    }	0
6842854	6842750	Merge two png images with transparency and retain transparency	Bitmap source1; // your source images - assuming they're the same size\nBitmap source2;\nvar target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb);\nvar graphics = Graphics.FromImage(target);\ngraphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear\n\ngraphics.DrawImage(source1, 0, 0);\ngraphics.DrawImage(source2, 0, 0);\n\ntarget.Save("filename.png", ImageFormat.Png);	0
33460239	33459925	Setting the window title of a C# Windows Universal app	var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();\nappView.Title = "Minesweeper Classic";	0
16578681	16578512	c# trying to access something from another method	protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)\n{\n\n  // your Code \n  Session["filepathImage"] = filepathImage ; // put the path in session variable \n\n}\n\nprotected void btnDone_Click(object sender, EventArgs e)\n{\n    if(Session["filepathImage"]!=null)\n    {\n         string filepathImage = Session["filepathImage"] as string;\n         // your code ...\n    }\n}	0
5034381	5034178	Resizing Image From Graphics?	Bitmap b = new Bitmap(control.Width, control.Height);\nusing (Graphics g = Graphics.FromImage(b)) {\n   g.CopyFromScreen(control.Parent.RectangleToScreen(control.Bounds).X, \n      control.Parent.RectangleToScreen(control.Bounds).Y, 0, 0, \n      new Size(control.Bounds.Width, control.Bounds.Height),\n      CopyPixelOperation.SourceCopy);\n}\nBitmap output = new Bitmap(newWidth, newHeight);\nusing (Graphics g = Graphics.FromImage(output)) {\n  g.DrawImage(b, 0,0,newWidth, newHeight);\n}	0
10828985	10828946	Make a partialview into html "string" in my controller, for json request	[HttpPost]\npublic ActionResult HtmlJsonTryout(int amount)\n{\n    if (first.CartID == 0)\n    {               \n        var viewData = m_cartViewDataFactory.Create();\n        string miniCart = this.PartialViewToString("_FullCart", viewData);\n        string cart = this.PartialViewToString("_CartSum", viewData);\n\n        return Json(new\n        {\n            Status = "OK",\n            MiniCart = miniCart,\n            Cart = cart\n        });\n    }\n}	0
14212569	14211015	Sending Image by using callback to server by javascript	File.OpenRead	0
24134282	24134163	How do I override this onPaint method to pass a list?	Object obj = new Object();\nList<int> _list = new List<int>();\nPublic void PassList(List<int> myList)\n{\n     lock(obj)\n     {\n         _list = myList;\n     }\n}\n\nprotected override void OnPaint(PaintEventArgs e)\n{\n     lock(obj)\n     {\n           // Do something with the _list\n     }\n}	0
5899214	5899109	How to ignore leading whitespace in XML file?	using (StreamReader sr = new StreamReader(@"C:\example.xml"))\n {\n      XmlDocument docXML = new XmlDocument(); \n      docXML.LoadXml(sr.ReadToEnd().Trim());\n      ...\n }	0
6864949	6354614	Check if string contains atleast one XML node	static void Main(string[] args)\n    {\n\n        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"<([^>]+)>[^<]*</(\1)>");\n\n        Console.WriteLine(r.IsMatch("<a>One Element</a>").ToString());\n        Console.WriteLine(r.IsMatch("<a>Not An Element</b>").ToString());\n        Console.WriteLine(r.IsMatch("<a>One Element</a><b>Two Element</b><c>Red Element</c><d>Blue Element</d>").ToString());\n        Console.ReadLine();\n    }	0
25092450	25091753	How to disable manual input in a Telerik RadDatePicker	private void spacebarHandler_PreviewKeyDown(object sender, KeyEventArgs e)\n {\nif (e.Key == Key.Space)\n    e.Handled = true;\n}	0
3158048	3157905	Convert Expression<Func<T, T2, bool>> to Expression<Func<T2, bool>> by introducing a constant for T	static Expression<Func<T2, bool>> PartialApply<T, T2>(Expression<Func<T, T2, bool>> expr, T c)\n{\n    var param = Expression.Parameter(typeof(T2), null);\n    return Expression.Lambda<Func<T2, bool>>(\n        Expression.Invoke(expr, Expression.Constant(c), param), \n        param);\n}	0
1143750	1143639	Binding multiple fields to listbox in ASP.NET	var datasource = from employee in employees \n                 select new\n                 { \n                     Name = employee.lastName + ", " + employee.firstName, \n                     Id = employee.ID \n                 };\n\nmyListBox.DataSource = datasource;\nmyListBox.DataTextField = "Name";\nmyListBox.DataValueField = "Id";\nmyListBox.DataBind();	0
7809052	7808853	Handle basic/full retreival of a database object in entity framework	var customerBasicList = context.Customers\n                               .Where(...)\n                               .Select( c => new CustomerBasic() \n                               {\n                                 FirstName = c.FirstName,\n                                 LastName = c.LastName,\n                               }).ToList();	0
23262990	23157500	Using WCF to start a remote process by WMI	public static int StartProcess(string machineName, string processPath, ManagementScope connnectionScope, int timeout)\n{\n    ManagementClass processTask = new ManagementClass(@"\\" + machineName + @"\root\CIMV2",\n                                                                    "Win32_Process", null);\n    processTask.Scope = connnectionScope;\n    ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");\n    methodParams["CommandLine"] = processPath;\n    InvokeMethodOptions options = new InvokeMethodOptions();\n    options.Timeout = TimeSpan.FromSeconds(timeout);\n    ManagementBaseObject exitCode = processTask.InvokeMethod("Create", methodParams, null);\n\n    return Convert.ToInt32(exitCode["ReturnValue"].ToString());\n}	0
22008863	22008084	Receiving Request Data as an HTTP Server Properly Through Sockets	var listen = new TcpListener(IPAddress.Parse("127.0.0.1"), 8070);\n        listen.Start();\n        var con = listen.AcceptSocket();\n        listen.Stop();\n\n        string input = "";\n        while (!input.EndsWith("\r\n\r\n"))\n        {\n            var buffer = new byte[8000];\n            int read = con.Receive(buffer);\n            input += Encoding.ASCII.GetString(buffer, 0, read);\n        }	0
11434245	11434164	Download a file through ASP.Net website	Response.ClearContent();\nResponse.ContentType = "application/text";\n...	0
1144813	1144517	How can I handle a shortcut key in every WPF window?	CommandManager.RegisterClassCommandBinding(typeof(Window),\n    new CommandBinding(ApplicationCommands.Help,\n        (x, y) => MessageBox.Show("Help")));	0
1886087	1886080	Can constructor chaining be used in place of overloaded constructor	:this(intPrimaryDocumentId)	0
22539638	22538554	Drag&Drop with WPF WebBrowser control - Drop event not firing	test.AllowDrop = true;	0
12310928	12310640	How to bind a single action to multiple event listeners in windows forms	public partial class MyForm : Form\n{\n    public MyForm()\n    {\n        InitializeComponent();\n    }\n\n    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)\n    {\n        SyncListToTextBox();\n    }\n\n    private void listBox1_KeyUp(object sender, KeyEventArgs e)\n    {\n        if (e.KeyCode == Keys.Return)\n        {\n            SyncListToTextBox();\n        }\n    }\n\n    private void SyncListToTextBox() \n    {\n        this.textBox1.Text = this.listBox1.SelectedItem.ToString();\n    }\n}	0
20321571	20320595	EF Multiple Schema CodeFirst	Context.Set<TPoco>()	0
13222050	13222005	getting index of elements by from a list	var theObj = TheListOfMyObjects.First(x => x.TheProperty == someValue);\nvar index = TheListOfMyObjects.IndexOf(theObj);\n//and from there it's obvious.	0
3065399	3065295	What is the usefulness of placing attributes on specific parameters of a method?	[DllImport("yay.dll")]\npublic static extern int Bling([MarshalAs(UnmanagedType.LPStr)] string woo);	0
7741323	7741229	Updating database in Transaction from List<T>	using(var connection = new SqlConnection(connectionString)) {\n    connection.Open();\n    using(var transaction = connection.BeginTransaction("Transaction")) {\n        foreach(var item in list) {\n            using(var command = connection.CreateCommand()) {\n                command.Transaction = transaction;\n                command.CommandText = // set the command text using item\n                command.ExecuteNonQuery();\n            }\n        }\n        transaction.Commit();\n    }\n}	0
8223649	8223554	Comparing byte array hex values in c#	(array[0] << 8) + array[1]	0
15608902	15607665	Do I have to create a datasource in aspx? Can I do sqldatasource (sql SPROC), parameters and databind in C#	SqlDataAdapter da = new SqlDataAdapter(cmdMeasureHist);\n    DataTable dt = new DataTable();\n    da.Fill(dt);\n\n    gvHistory.DataSource = dt;\n    gvHistory.DataBind();	0
18350115	18350077	need to combine to lists in a view	myList1 = myList1.Concat(myList2).ToList();	0
2024184	2024088	Right click with SendKeys in .NET	using System;\nusing System.Runtime.InteropServices;\n\nnamespace WinApi\n{  \n    public class Mouse\n    { \n            [DllImport("user32.dll")]\n            private static extern void mouse_event(UInt32 dwFlags,UInt32 dx,UInt32 dy,UInt32 dwData,IntPtr dwExtraInfo);\n\n            private const UInt32 MouseEventRightDown = 0x0008;\n            private const UInt32 MouseEventRightUp = 0x0010;\n\n            public static void SendRightClick(UInt32 posX, UInt32 posY)\n            {\n                mouse_event(MouseEventRightDown, posX, posY, 0, new System.IntPtr());\n                mouse_event(MouseEventRightUp, posX, posY, 0, new System.IntPtr());\n            }    \n    }\n}	0
2117261	2117241	Is implementing a singleton using an auto-property a good idea?	public class MySingleton\n{\n    private static readonly MySingleton mySingleton;\n    public static MySingleton MySingleton { get { return mySingleton; } }\n\n    private MySingleton() {}\n\n    static MySingleton() { mySingleton = new MySingleton(); }\n}	0
14984550	14982646	Make a custom score counter in unity with c#	public GUITexture textureScore;\npublic Texture2D zero;\npublic Texture2D one;\npublic Texture2D two;\npublic Texture2D three;\npublic Texture2D four;\npublic Texture2D five;\n\n\nvoid Update () {\n    if(score == 0){\n            textureScore.guiTexture.texture = zero;     \n        }else if(score == 1){\n            textureScore.guiTexture.texture = one;              \n        }else if(score == 2){\n            textureScore.guiTexture.texture = two;              \n        }else if(score == 3){\n            textureScore.guiTexture.texture = three;                \n        }else if(score == 4){\n            textureScore.guiTexture.texture = four;             \n        }else if(score == 5){\n            textureScore.guiTexture.texture = five;             \n        }\n}	0
12526714	12525701	How can I make a dynamic treeview in c#?	private void AddNodesRecursive(TreeNode parent, object childData)\n{\n    string strChildNode = string.Empty;\n    XmlElement childDoc = null;\n    if (parent != null)\n    {\n        if ((childData as string) != null)\n        {\n            parent.ChildNodes.Add(new TreeNode((childData as string)));\n            return;\n        }\n        childDoc = childData as XmlElement;\n        if (childDoc != null)\n        {\n            TreeNode subParent = new TreeNode(childDoc.InnerText);\n            parent.ChildNodes.Add(subParent);\n            foreach (XmlElement grandChild in childDoc.ChildNodes)\n                AddNodesRecursive(subParent, grandChild);\n        }\n    }\n}	0
10248440	10248358	Java Integer.ValueOf method equivalence in C# With Radix Parameter	int.Parse (tmp, NumberStyles.HexNumber);	0
22016357	22016205	Debug an application that was launched via explorer context menu	Debugger.Break();	0
27559574	27559441	How can I import Excel float data into SQL Server with ASP.NET and C#	int num = string.IsNullOrEmpty(PersonID) ? 0 : int.Parse(PersonID);\ndouble bugged = Convert.ToDouble(PersonBugged);	0
8565596	7152253	How to Generate Pre-signed url for Amazon S3 without using the SDK	AmazonS3Config s3Config = new AmazonS3Config();\n    s3Config.UseSecureStringForAwsSecretKey = false;\n    AmazonS3Client s3Client = new AmazonS3Client(accessKey, secretKey, s3Config);	0
29863390	29859745	C# How to pool the objects of a node tree efficiently?	List bestNodes;\n\nbool evalNode(node, score)\n{\n    if (childCount == 0)\n    {\n        if (score > bestScore)\n        {\n            bestScore = score;\n            bestNode = node;\n            bestNodes.Add(node);\n\n            return true;\n        }\n        else\n        {\n            freeNode(this);\n\n            return false;\n        }\n    }\n    else\n    {\n        bool inLongest = false;\n        foreach (child in children)\n        {\n            inLongest = evalNode(child, score + 1) || inLongest;\n        }\n\n        if (!inLongest)\n        {\n            freeNode(node);\n        }\n        else\n        {\n            free(bestNodes[score]);\n            bestNodes[score] = node;\n        }             \n\n        return inLongest;\n    }\n}	0
10948243	10948042	DataGrid in ASP .NET conflict of interest with Other postback events	void DataGrid1_SortCommand(Object sender, DataGridSortCommandEventArgs e)\n    {\n        // Retrieve the data source.\n        DataTable dt = YOURDATA;\n\n        // Create a DataView from the DataTable.\n        DataView dv = new DataView(dt);\n\n        // The DataView provides an easy way to sort. Simply set the\n        // Sort property with the name of the field to sort by.\n        dv.Sort = e.SortExpression;\n\n        // Rebind the data source and specify that it should be sorted\n        // by the field specified in the SortExpression property.\n        DataGrid1.DataSource = dv;\n        DataGrid1.DataBind();\n    }	0
6608940	6608916	Find elements existing in both collections using LINQ	int[] result = foo.Intersect(bar).ToArray();	0
6606245	6606189	How to get 50 results in a single Google Search result page?	&num=50\n\nhttp://www.google.com/search?q=tonneau&hl=en&biw=1148&bih=729&num=50&lr=&ft=i&cr=&safe=images&tbs=	0
21840549	21840280	WebAPI passed post parameters is null	POST http://localhost:50814/api/Values/ HTTP/1.1\nHost: localhost:50814\nContent-Type: application/json\nContent-Length: 10\n\n"MyString"	0
18884097	18883439	How to populate a gridview dropdown dynamically depending on another column's value?	void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n     {\n       DataRowView drv = (DataRowView)e.Row.DataItem; \n        if(e.Row.RowType == DataControlRowType.DataRow)\n      {\n         String State = drv["StateColumnName"].ToString();\n      //Now You Have State So You Can Get All Code Values By State Name\n         DataTable dtcodes = GetByState();\n      //Now Bind This Code To DropDownList Of Codes\n        DropDownList dropdownCodes = (DropDownList)e.Row.FindControl("dropdownCodes");\n        dropdownCodes.DataSource = dtcodes;\n        dropdownCodes.DataBind();\n\n        }\n\n     }	0
9463680	9456332	Mapping junction table to self	public class WikiPage\n{\n    public virtual int Id { get; protected set; }\n    public virtual IEnumerable<WikiPage> BackReferences { get; }\n    public virtual IEnumerable<WikiPage> References { get; }\n}\n\n// WikiPageMap : ClassMap<WikiPage>\npublic WikiPageMap()\n{\n    ...\n    HasManyToMany(wp => wp.References)\n        .Table("WikiPageLinks")\n        .ParentKeyColumn("parent_page_id")\n        .ChildKeyColumn("referenced_page_id");\n\n    HasManyToMany(wp => wp.BackReferences)\n        .Table("WikiPageLinks")\n        .ParentKeyColumn("referenced_page_id")\n        .ChildKeyColumn("parent_page_id")\n        .Inverse();\n\n    ...\n}	0
908366	908364	Double qoutes problem with string	string x= @"<Site name=""Stack Overflow"">\n           Inner content;\n          </Site>"	0
17167725	17167704	XmlSerializer is not serializing to a valid xml	FileMode.Create	0
9752671	9752287	How to delete a record with a foreign key constraint?	public class FoodJournalEntities : DbContext\n{\n    public DbSet<Journal> Journals { get; set; }\n    public DbSet<JournalEntry> JournalEntries { get; set; }\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Journal>()\n               .HasOptional(j => j.JournalEntries)\n               .WithMany()\n               .WillCascadeOnDelete(true);\n        base.OnModelCreating(modelBuilder);\n    }\n}	0
14849760	14849542	threading for a windows service	XmlDocument doc = new XmlDocument();\ndoc.Load("Data.xml");\nint count = doc.SelectNodes("Data/DataClass").Count;\nParallel.For(0,doc.SelectNodes("Data/DataClass").Count-1,i =>\n{\n    XmlNode node = doc.SelectNodes("Data/DataClass")[i];\n    XmlNodeList subnode = node.ChildNodes;\n    string pathO = "";\n    string pathI = subnode[0].InnerText;\n    string prefix = subnode[2].InnerText;\n    string freq = subnode[3].InnerText;\n    string[] filenames = Directory.GetFiles(pathI);\n    doc.Save("Data.xml");\n    foreach (var filename in filenames)\n    {\n        pathO = subnode[1].InnerText;\n        pathO = pathO + "\\" + prefix;\n        string fname = Path.GetFileName(filename);\n        pathO = pathO + fname;\n        System.IO.File.Move(filename, pathO);\n    }\n}\n);	0
29986146	29986093	New line in string with Date	DateTime.Now.ToString(\n             string.Format("dddd, d MMM {0}'hour.' HH:mm", System.Environment.NewLine)\n             , culture);	0
23955564	23915728	Active directory - get all domain controllers	DirectoryContext aContext = new DirectoryContext( DirectoryContextType.DirectoryServer, LDAPServer, LDAPUser, LDAPPassword );\nForest aForest = Forest.GetForest( aContext );\nforeach ( ApplicationPartition aPartition in aForest.ApplicationPartitions )\n{\n    ...\n}	0
4906500	4906468	Regular Expression to find separate words?	^\w+\s+\w+	0
5653996	5647427	Linq-Entities: Fetch data excluding the overlapping data ranges, pick the largest period	var oImportPeriods = \n    from o in Imports\n    where o.Administration.AdminID == 143\n    orderby o.Period.PeriodID\n    select o.Period;\n\nvar oIgnorePeriodList = (\n    from oPeriod in oImportPeriods\n    from oSearchPeriod in oImportPeriods\n        .Where(o => o.PeriodID != oPeriod.PeriodID)\n    where oPeriod.StartDate >= oSearchPeriod.StartDate\n    where oPeriod.EndDate <= oSearchPeriod.EndDate\n    select oPeriod.PeriodID)\n    .Distinct();\n\nvar oDeletablePeriods = oAdministrationPeriods\n    .Where(o => !oIgnorePeriodList.Contains(o.PeriodID));   \n\nforeach(var o in oDeletablePeriods)\n    Console.WriteLine(o.Name);	0
15898588	15898480	How to make ValidatesOnDataErrors bindable?	string Error { get; }\nstring this[string columnName] { get; }	0
22901244	22901225	How to remove a specific object from a List<T>	linkAcategory.RemoveAll(x=>x.link==link && x.cat==cat);	0
3741349	3741270	Is it possible to disable context menu items based on the selection on Treeview	private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)\n{\n  if ((int)treeView1.SelectedNode.Tag == 1)\n  {\n    removeToolStripMenuItem.Enabled = true;\n  }\n  else\n  {\n    removeToolStripMenuItem.Enabled = false;\n  }\n}	0
7850562	7848035	Templated ValidationSummary control	StringBuilder myCustomHtml = new StringBuilder();\nforeach (Control validator in this.Page.Validators)\n{\n    IValidator currentValidator = validator as IValidator;\n    if (currentValidator != null && !currentValidator.IsValid)\n    {\n        myCustomHtml.AppendFormat("Bla Foo is missing");\n    }\n}	0
3043134	3043111	How to restructure ASP.NET application	System.Data.dll	0
20032013	20024737	How do I assign a texture to a material in Unity	// This will search for 'cobblestone' in Assets/Resources/cobblestone.jpg:\nmesh_renderer.material.mainTexture = Resources.Load("cobblestone", typeof(Texture2D));	0
25878481	10178043	Levenshtein edit distance algorithm that supports Transposition of two adjacent letters in C#	//** Step 7 to make it Damerau???Levenshtein distance\n      if (i > 1 && j > 1 && (s[i - 1] == t[j - 2]) && (s[i - 2] == t[j - 1]))\n      {\n             d[i, j] = Math.Min(\n                            d[i, j],\n                            d[i - 2, j - 2] + cost   // transposition\n                         );\n      }	0
1879797	1879743	Is there a c# precompiler define for the CLR version	#if CLR_V2\n  #if CLR_V4\n    #error You can't define CLR_V2 and CLR_V4 at the same time\n  #endif\n\n  code for clr 2\n\n#elif CLR_V4\n\n  code for clr 4\n\n#else\n  #error Define either CLR_V2 or CLR_V4 to compile\n#endif	0
26462699	26461593	Updating Progress bar from a different thread in Windows 7	DispatcherPriority.ApplicationIdle	0
2506116	2504921	something like INotifyCollectionChanged fires on xml file changed	private static void StartMonitoring()\n    {\n        //Watch the current directory for changes to the file RssChannels.xml\n        var fileSystemWatcher = new FileSystemWatcher(@".\","RssChannels.xml");\n\n        //What should happen when the file is changed\n        fileSystemWatcher.Changed += fileSystemWatcher_Changed;\n\n        //Start watching\n        fileSystemWatcher.EnableRaisingEvents = true;\n    }\n\n    static void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)\n    {\n        Debug.WriteLine(e.FullPath + " changed");\n    }	0
9481485	9480991	Nested attributes and XML deserialization	[XmlRoot(ElementName="ExampleCol")]\npublic class Test\n{\n    [XmlElement("ElementWithAttribute")]\n    public ElementWithAttribute Element = new ElementWithAttribute();\n\n    [XmlArray(ElementName="AnotherCol")]\n    public List<Row> AnotherCol = new List<Row>();\n    public Test()\n    {\n\n    }\n}\n\npublic class ElementWithAttribute\n{\n    public ElementWithAttribute()\n    {\n\n    }\n    [XmlAttribute]\n    public string attr { get; set; }\n    [XmlText]\n    public string value { get; set; }\n}\n\npublic class Row\n{\n    public Row()\n    {\n\n    }\n    [XmlAttribute]\n    public string attr { get; set; }\n    [XmlText]\n    public string value { get; set; }\n}	0
24730549	24730383	How to call a method asynchronously in c#	Task t = new Task.Factory.StartNew(foo);	0
23843999	23843887	change datagridviewtextbox column value from dropdownlist control	dataGridView1[1, 2].Value = comboBox1.SelectedIndex.ToString();//Here, 1 represents row, 2 represents column.\ndataGridView1.Rows[2].Cells[1].Value = comboBox1.SelectedIndex.ToString();	0
1068534	1068502	create a datasource from a list	List<MyListItem> dataSource = new List<MyListItem>();\n\nMyListItem item1 = new MyListItem();\nitem1.Name = "Name 1";\nitem1.Url = "Url 1";\ndataSource.Add(item1);\n\nMyListItem item2 = new MyListItem();\nitem2.Name = "Name 2";\nitem2.Url = "Url 2";\ndataSource.Add(item2);\n\ndropDownList.DataSource = dataSource;\ndropDownList.DataTextField = "Name";\ndropDownList.DataValueField = "Url";\ndropDownList.DataBind();	0
5022136	5022021	Retrieve Value of DropDownList by Index ID	string valueAtIndex = myComboBox.Items[SomeIndexValue].Value;	0
3328543	3326884	instant messaging notification	public class Message{\n   public string Message{get;set;}\n   public string Type{get;set;}\n}	0
4388922	2582718	Create a custom control which has a fixed height in designer	using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\nnamespace MyControlProject\n{\n    [Designer(typeof(MyControlDesigner))]\n    public class MyControl : Control\n    {\n        protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)\n        {\n            height = 50;\n            base.SetBoundsCore(x, y, width, height, specified);\n        }\n    }\n\n    internal class MyControlDesigner : ControlDesigner\n    {\n        MyControlDesigner()\n        {\n            base.AutoResizeHandles = true;\n        }\n        public override SelectionRules SelectionRules\n        {\n            get\n            {\n                return SelectionRules.LeftSizeable | SelectionRules.RightSizeable | SelectionRules.Moveable;\n            }\n        }\n    }\n}	0
8111842	8111731	Unable to display dataset on WinForm application	Service1 MyService = new Service1();\n // Call the GetData method in the Web Service\n  DataSet ds = MyService.getdata("abc");\n // Bind the DataSet to the Grid\n  datagrid.DataSource=ds.Table[0];	0
23300173	23297133	Launching a WPF Window in a Separate Thread	private void button1_Click(object sender, RoutedEventArgs e)	0
18858344	18743696	Efficient query for only the first N rows for each unique ID	query = tableQueryable.Where(a =>\n          tableQueryable.Where(b => b.ID == a.ID)\n            .OrderByDescending(o => o.Timestamp)\n            .Take(N)\n            .Select(s => s.PK)\n          .Contains(a.PK)\n        ).OrderByDescending(d => d.Timestamp);	0
27998530	27998208	Data Table Copy not showing properly in GridView	static DataTable MergeDataTables(DataTable dt1, DataTable dt2)\n{\n     DataTable dt3 = dt1.Copy();\n     foreach (DataColumn dc in dt2.Columns)\n     {\n         dt3.Columns.Add(dc.ColumnName).DataType = dc.DataType;\n     }\n\n     for (int i = 0; i < dt3.Rows.Count; i++)\n     {\n         foreach (DataColumn dc in dt2.Columns)\n         {\n             string col = dc.ColumnName;\n             dt3.Rows[i][col] = dt2.Rows[i][col];\n         }\n     }\n     return dt3;\n}	0
17270591	17265359	Get DataContext from TextBlock MouseDown	private void NameCol_mousedown(object sender, MouseButtonEventArgs e)\n{\n    var tb = (TextBlock)e.OriginalSource;\n    var dataCxtx = tb.DataContext;\n    var dataSource = (DocProp)dataCxtx;\n}	0
7436792	7436578	NHibernate: Where clause containing child collection as subquery building improper T-SQL statements	var issues = _issueRepo.All();\nif (!string.IsNullOrWhiteSpace(searchWords)) \n{\n    issues = issues.Where(i => i.Subject.Contains(searchWords)\n                            || i.Description.Contains(searchWords)\n                            || i.Locations.Any(l => l.Organization.Contains(searchWords))\n                            || i.Locations.Any(l => l.City.Contains(searchWords)) )\n}	0
28382746	28382671	JSON post from c# fails with 500 error	string fullURL = RootServiceUrl + "MemberCheckIn?scanCode=X&siteID=1...etc.	0
25754918	25753194	Explicitly set multiple transports in SignalR .Net client	var httpClient = new DefaultHttpClient();\n_hubCn.Start(new AutoTransport(httpClient, \n    new IClientTransport[] \n    { \n        new WebSocketTransport(httpClient), \n        new LongPollingTransport(httpClient))\n    });	0
5503866	5503759	How to instantiate or mock a Window programatically?	if(Application.ResourceAssembly == null)\n    Application.ResourceAssembly = typeof(MainWindow).Assembly;\nvar window = new MainWindow();	0
10179999	10176878	CompareAttribute error taking precedence from RequiredAttribute one	[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\npublic class CompareAndValidateAttribute : CompareAttribute\n{\n    public override bool IsValid(object value)\n    {\n        return base.IsValid(value) && !string.IsNullOrEmpty((string)value);\n    }\n}	0
15982039	15934523	declaring a vary generic class	public class ButtonInputHandler<T> : IButtonInputHandler<T>\n{\n    //implement IButtonInputHandler<T> here\n}\n\npublic class NumericInputHandler<T> : INumericInputHandler<T>\n{\n    //implement INumericInputHandler<T> here\n}\n\npublic class ButtonAndNumericInputHandler<TButton, TNumeric> :\n    ButtonInputHandler<TButton>, INumericInputHandler<TNumeric>\n{\n    //implement INumericInputHandler<TNumeric> here\n    //(the implementation for IButtonInputHandler<TButton> will be inherited)\n}	0
12323832	12254972	How to make the x-axis to ignore the order of the x values?	Chart.AlignDataPointsByAxisLabel();	0
9363195	9363166	Trim property in get method	private string _zipcode;\n\npublic virtual string zipcode {\n   get { return _zipcode.Trim(); }\n}	0
11908910	11908230	Remove all files created by specifed user	[Test]\n    public void Test()\n    {\n        string user = @"Domain\UserName";\n        var files = Directory.EnumerateFiles(@"C:\TestFolder")\n            .Where(x => IsOwner(x, user));\n        Parallel.ForEach(files, File.Delete);\n    }\n\n    private static bool IsOwner(string filePath, string user)\n    {\n        return string.Equals(File.GetAccessControl(filePath).GetOwner(typeof (NTAccount)).Value, user,\n                             StringComparison.OrdinalIgnoreCase);\n    }	0
22521991	22521738	How do you invoke a 'Enter' keypress with webkitbrowser?	SendKeys.Send("{ENTER}");	0
2713817	2713800	Access the path to the app.config programmatically	AppDomain.CurrentDomain.SetupInformation.ConfigurationFile	0
24926447	24887348	Alternative for SetModifiedProperty in EF 6	public TObject Update(TObject entityObj, List<String> properties)\n        {\n\n            var entities = _context.Set<TObject>().Attach(entityObj);\n            foreach (var property in properties)\n            {\n                _context.Entry(entities).Property(property).IsModified = true;\n            }\n            _context.SaveChanges();\n            return entityObj;\n        }	0
3293823	3293806	Calculating the disk space a string would take up without saving it to disk	Encoding encoding = Encoding.UTF8; // Or whatever\nint size = encoding.GetByteCount(text);	0
11751856	5459006	DateTimePicker ValueChanged Event repeats with month arrow	private bool _calendarDroppedDown = false;\n//called when calendar drops down\nprivate void dateStartDateTimePicker_DropDown(object sender, EventArgs e)\n{\n  _calendarDroppedDown = true;\n}\n//called when calendar closes\nprivate void dateStartDateTimePicker_CloseUp(object sender, EventArgs e)\n{\n  _calendarDroppedDown = false;\n  RefreshToolbox(null, null); //NOW we want to refresh display\n}\n\n//This method is called when ValueChanged is fired\npublic void RefreshToolbox(object sender, EventArgs e)\n{ \n  if(_calendarDroppedDown) //only refresh the display once user has chosen a date from the calendar, not while they're paging through the days.\n    return;\n  ...\n}	0
15606979	15602036	Open another view with caliburn micro	[Export(typeof(IShell))]\n    public class MainViewModel : Screen\n    {\n        public string Path{ get; set; }\n\n        [Import]\n        IWindowManager WindowManager {get; set;}\n\n        public void Open()\n        {\n            OpenFileDialog fd = new OpenFileDialog();\n            fd.Filter = "Text|*.txt|All|*.*";\n            fd.FilterIndex = 1;\n\n            fd.ShowDialog();\n\n            Path= fd.FileName;\n            NotifyOfPropertyChange("Path");\n\n            WindowManager.ShowWindow(new BViewModel(), null, null);\n        }    \n    }	0
773410	773396	How to show only part of an int in c# (like cutting off a part of a credit card number)	// assumes that ccNumber is actually a string\nstring hidden = "*" + ccNumber.Substring(ccNumber.Length - 4);	0
19708763	19708657	Convert DateTime axis data back to DateTime	DateTime dt = new DateTime(1899,12,31);\ndt = dt.AddDays(data.X);	0
16378922	16378880	String Comparisons with chars	for (int i = 0; i < s1.Length - 2; i++)\n    if (s2.Contains(s1.Substring(i, 3)))\n        return true;\nreturn false;	0
4473108	4473061	Getting the values from a grouped row using LINQ	group.Select(s => s.Seat).ToArray()	0
3154440	3153674	Create tree hierarchy in JSON with LINQ	var list = new[] { "Banana", "Apple", "Cheery", "Lemon", "Orange" };\n\nvar js = new JObject(from y in Enumerable.Range(0, 9)\n                     join x in list\n                     on y equals (x[0] - 'A') / 3\n                     into g\n                     let k = string.Join(", ", from i in Enumerable.Range(0, 3)\n                                               select (char)(3 * y + i + 'A'))\n                     let v = string.Join(", ", from s in g orderby s select s)\n                     select new JProperty(k, new JValue(v)));	0
6204170	6203193	how do I change the order of treenodes	void MoveNodeUp(TreeNode node)\n{\n  TreeNode parentNode = node.Parent;\n  int originalIndex = node.Index;\n  if (node.Index == 0) return;\n  TreeNode ClonedNode = (TreeNode)node.Clone();\n  node.Remove();\n  parentNode.Nodes.Insert(originalIndex - 1, ClonedNode);\n  parentNode.TreeView.SelectedNode = ClonedNode;\n  }	0
18518189	18517969	Send string with non-ascii characters out serial port c#	using System.Text;\n\n// ...\n\npublic static byte[] EmbedDataInString(string Cmd, byte Data)\n{\n    byte[] ConvertedToByteArray = new byte[Cmd.Length + 2];\n    System.Buffer.BlockCopy(Encoding.ASCII.GetBytes(Cmd), 0, ConvertedToByteArray, 0, ConvertedToByteArray.Length - 2);\n\n    ConvertedToByteArray[ConvertedToByteArray.Length - 2] = Data;\n\n    /*Add on null terminator*/\n    ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00;\n\n    return ConvertedToByteArray;\n}	0
12590199	12590104	How to map XML to a class/dataset when elements/attributes are known, but don't occur everytime?	XmlDocument doc = new XmlDocument();\n        doc.Load("myXML.xml");\n        XmlNode node = doc.SelectSingleNode("//sometypeinfo1");\n\n        foreach (XmlAttribute a in node.Attributes)\n        {\n            Console.Write(a.Name);\n            Console.Write(a.Value);\n        }	0
21801506	21801223	Read data from text file as list array	double[] x =\n    // Read all lines inside an IEnumerable<string>\n    File.ReadAllLines(@"E:\TestFile.txt")\n    // Create a single string concatenating all lines with a space between them\n    .Aggregate("", (current, newLine) => current + " " + newLine)\n    // Create an array with the values in the string that were separated by spaces\n    .Split(' ')\n    // Remove all the empty values that can be due to multiple spaces\n    .Where(s => !string.IsNullOrWhiteSpace(s))\n    // Convert each string value into a double (Returning an IEnumerable<double>)\n    .Select(s => double.Parse(s))\n    // Convert the IEnumerable<double> to an array\n    .ToArray();	0
29194278	29194186	Setting the background image of a window with uniformtofill	this.Background = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/myapp;component/Images/icon.png")))\n                 {\n                       Stretch = Stretch.UniformToFill\n                 };	0
21760136	21759840	String Format fixed bound chars, variable chars inside	string phone = "112223333";\nvar m = Regex.Match(phone, @"(\d{2})(\d+)(\d{4})");\nvar formatted = String.Format("({0}) {1}-{2}", m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);	0
9331029	9330587	A form of IPC that works for my situation	I can only create one Pipe server for any given server name.	0
29093622	29054533	Reordering in Windows Phone 8.1 ListView	if (ListView != null && ListView.ReorderMode != ListViewReorderMode.Enabled)\n        {\n            ListView.ReorderMode = ListViewReorderMode.Enabled;\n        }	0
20748376	18702533	How to execute Selenium Chrome WebDriver in silent mode?	ChromeOptions options = new ChromeOptions();\noptionsChrome.AddArgument("--log-level=3");\nIWebDriver driver = new ChromeDriver(options);	0
25708790	25708697	FileWatcher - NullObjectReference	fWatcher = null;    //You cannot do this "fWatcher." after this line \n                      //(Until you call fWatcher = new FileSystemWatcher() at least)\n  fWatcher.Dispose(); //You cannot do this !!!!!	0
769420	769378	DateTime Object Representing Day of Week	DayOfWeek day = (DayOfWeek)myInt;	0
10701106	10700859	Regex pattern for house letter	string sPattern = "[a-zA-Z 0-9]*([a-zA-Z]),.*";\nint i = 0;\nforeach (string s in address)\n{\n     Match m = Regex.Match(s, sPattern);\n     if (m.Success){\n         houseLetter[i] = m.ToString(); \n     } else {\n         houseLetter[i] = "Not Found";\n     }\n     i++;\n}	0
21293995	21293955	Pull all numbers from a column in a DataGridView and write to a int list	foreach (DataGridViewRow row in dataGridView1.Rows)\n   {\n       int result;\n       if(int.TryParse((string)row.Cells[2].Value,out result)) data.Add(result);\n   }	0
29670445	29670339	How to extract specific value from xml string?	var s = "<P align=justify><STRONG>Pricings<BR></STRONG>It was another active week for names leaving the database. The week's prints consisted of two ILS, and sever ITS.</P>";\n\nvar doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(s);\n\nstring result;\nvar p = doc.DocumentNode.SelectSingleNode("p");\nif (p.ChildNodes.Count == 2)\n    result = p.ChildNodes[1].InnerText;	0
19023441	19023359	How to allign control in code behind	Grid.SetRow(dt,1); // set position\nLayoutRoot.Children.Add(dt); // add control into the Grid	0
4368915	4368857	Read from a file starting at the end, similar to tail	using (var reader = new StreamReader("foo.txt"))\n{\n    if (reader.BaseStream.Length > 1024)\n    {\n        reader.BaseStream.Seek(-1024, SeekOrigin.End);\n    }\n    string line;\n    while ((line = reader.ReadLine()) != null)\n    {\n        Console.WriteLine(line);\n    }\n}	0
3994530	3994480	How can I make sender in an eventhandler my custom control and not the labels inside it	public partial class UserControl1 : UserControl\n{\n    public UserControl1()\n    {\n        InitializeComponent();\n    }\n\n    public event EventHandler MyCustomClickEvent;\n\n    protected virtual void OnMyCustomClickEvent(EventArgs e)\n    {\n        // Here, you use the "this" so it's your own control. You can also\n        // customize the EventArgs to pass something you'd like.\n\n        if (MyCustomClickEvent != null)\n            MyCustomClickEvent(this, e);\n    }\n\n    private void label1_Click(object sender, EventArgs e)\n    {\n        OnMyCustomClickEvent(EventArgs.Empty);\n    }\n}	0
3306110	3302535	Find the scroll unit of a window	hdc = GetDC (hwnd); \n    // Extract font dimensions from the text metrics. \n    GetTextMetrics (hdc, &tm); \n    int pixelCnt= tm.tmHeight + tm.tmExternalLeading;	0
22796637	22796494	Array.Sort for strings with numbers	var orderedList = test\n            .OrderBy(x => new string(x.Where(char.IsLetter).ToArray()))\n            .ThenBy(x =>\n            {\n                int number;\n                if (int.TryParse(new string(x.Where(char.IsDigit).ToArray()), out number))\n                    return number;\n                return -1;\n            }).ToList();	0
22394611	22394488	How do i parse json with web client and display it in the console?	var client = new WebClient();\n\n  client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(loadHTMLCallback);\n  client.DownloadStringAsync(new Uri("http://www.myurl.com/myFile.txt"));\n//...\n\npublic void loadHTMLCallback(Object sender, DownloadStringCompletedEventArgs e)\n{\n  var textData = (string)e.Result;\n  // Do cool stuff with result\n  Debug.WriteLine(textData);\n}	0
2773473	2773448	c# run process without freezing my App's GUI	void Your_Method()\n{\n   //Start process here\n}\n\n\nMethodInvoker myProcessStarter= new MethodInvoker(Your_Method);\n\nmyProcessStarter.BeginInvoke(null, null);	0
23588257	23559498	Linq to Entities - group by on multiple joined tables	var query = context.ProcessFlows\n                .GroupBy(p => new\n                {\n                 FlowPropertyName = p.Flow.FlowProperty.Name\n                 })\n                .SelectMany(pf => pf.Select(p => new IntermediateFlow\n                {\n                    FlowPropertyName = p.Flow.FlowProperty.Name,\n                    ReferenceUnit = p.Flow.FlowProperty.UnitGroup.Name\n                })).AsQueryable();\n            return query.OrderBy(pFlow => new { pFlow.FlowPropertyName, pFlow.ReferenceUnit });	0
22031986	22031956	combine foreach with linq	(from s in db.WfRADocStates.Include(x=>x.WfStateStatu).Include(xx=>xx.WfState).Include(xxx=>xxx.WfState.Dept).Include(d=>d.RADoc)\n         where\n            s.RADocID == docID &&\n            !s.isHistory &&\n            s.StatusID == 1 &&\n            s.WfStateStatu.isToNotifyCNH\n         select s).ToList().ForEach(\n                s => EmailHelper.notify(s)\n         );	0
7959203	7959151	How best to handle interdependent properties?	SolveForA()	0
7323143	7323118	Add numbers in c#	String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();	0
22922792	22918711	How to start a service in C# on Linux	Process proc = new System.Diagnostics.Process();\nproc.StartInfo.FileName = "/bin/bash";\nproc.StartInfo.Arguments = "-c 'your command here'";\nproc.StartInfo.UseShellExecute = false; \nproc.StartInfo.RedirectStandardOutput = true;\nproc.Start();	0
10456032	10455773	select a row in datagridview programatically	private void tbljobdata_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        if (e.ColumnIndex == 0)\n            tbljobdata.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\n        else\n            tbljobdata.SelectionMode = DataGridViewSelectionMode.CellSelect;\n    }	0
272044	272035	How do I get the icon associated with a file type?	FileAssociationInfo fai = new FileAssociationInfo(".bob");\nProgramAssociationInfo pai = new ProgramAssociationInfo(fai.ProgID);\nProgramIcon icon = pai.DefaultIcon;	0
12284367	12284177	WinForms Custom Control Colors	public CMSLabel()\n{\n  base.BackColor = cmsLabelBackColor;            \n}	0
18722098	18722039	Adding Int to DateTime in format DD/MM/YYYY	DateTime today = DateTime.Parse(maskedTextBox1.Text);\nDateTime answer = today.AddDays(Convert.ToInt32(zpocdnu.Text));\n\nmaskedTextBox2.Text = answer.ToString() ;	0
30256833	30256569	How to show array of integer numbers in a listview	listView1.Items.Add(TimeRand[i].ToString());	0
1157302	1157258	Find specific data in html with HtmlElement(Collection) and webbrowser	HtmlDocument doc = webBrowser.Document;\nHtmlElementCollection col = doc.GetElementsByTagName("div");\nforeach (HtmlElement element in col)\n{\n    string cls = element.GetAttribute("className");\n    if (String.IsNullOrEmpty(cls) || !cls.Equals("XYZ"))\n        continue;\n\n    HtmlElementCollection childDivs = element.Children.GetElementsByName("ABC");\n    foreach (HtmlElement childElement in childDivs)\n    {\n        //grab links and other stuff same way\n    }\n}	0
6007001	6006866	Win32 User Impersonation Curiosity	DuplicateToken( token, 2, ref tokenDuplicate )	0
31056042	31055543	set selected row datagridview by cell's value	foreach(DataGridViewRow row in dataGridView1.Rows)\n{\n    // 0 is the column index\n    if (row.Cells[0].Value.ToString().Equals("LSN"))\n    {\n        row.Selected = true;\n        break;\n    }\n}	0
9420613	9420582	Flatten a C# Dictionary of Lists with Linq	var list = dictionary.Values              // To get just the List<string>s\n                     .SelectMany(x => x)  // Flatten\n                     .ToList();           // Listify	0
13348446	13348202	How to keep the button "Control" pressed?	Send,{Ctrl DOWN}	0
11195331	11195177	CSS access colums in table	#ContentPlaceHolderHome_GridView1 tr:nth-child(3) td:nth-child(2)	0
15834854	15834653	Formating a string without having to make countless manipulations	string first = yourString.Split('\n')[0]; //Blades of Steel\n  string second = yourString.Split('\n')[9]; //$8.47	0
18165617	18160113	How can I compare two C# collections and issue Add, Delete commands to make them equal?	var toBeUpdated =\n            objectiveDetail1.Where(\n            a => objectiveDetail2.Any(\n                b => (b.ObjectiveDetailId == a.ObjectiveDetailId) && \n                     (b.Number != a.Number || !b.Text.Equals(a.Text))));\n\nvar toBeAdded =\n            objectiveDetail1.Where(a => objectiveDetail2.All(\n            b => b.ObjectiveDetailId != a.ObjectiveDetailId));\n\nvar toBeDeleted =\n            objectiveDetail2.Where(a => objectiveDetail1.All(\n            b => b.ObjectiveDetailId != a.ObjectiveDetailId));	0
21442334	21442243	How to restrict users to a tab	hlRegister.NavigateUrl = null;	0
18687049	18686980	How to get path of a file which is in IsolatedStorage?	tile.BackgroundImage = new Uri("isostore:/MyFolder/MyFile.png", UriKind.Absolute);	0
2578454	2578376	How can I load assembly dynamically thru internet?	Assembly.Load (byte[])	0
959092	82058	Deserializing Client-Side AJAX JSON Dates	new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))	0
3851257	3851244	C# Regex: Get all matches w/ name?	foreach (var c in m.Groups["class"].Captures)\n{\n    Console.WriteLine(c);\n}	0
29121872	29121490	How to reorder columns in excel using C# interop	Excel.Range copyRange = xlWs.Range["C:C"];\n        Excel.Range insertRange = xlWs.Range["A:A"];\n        insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, copyRange.Cut());	0
17262174	17262086	Bind Icon into contextMenuStrip add command c#	var item = new ToolStripMenuItem("Name");\n    item.Image = Properties.Resources.Icon;\n    contextMenuStrip1.Items.Add(item);	0
25734797	25734616	Using .GroupBy to remove list duplicates and also keep value from first list	var q = items\n    .GroupBy(x => new { x.Id, x.Value})\n    .Select(group => new \n             {\n                 Id = group.Key.Id, \n                 Green = group.Any(item => item.Color == "Green"), \n                 Red = group.Any(item => item.Color == "Red"),\n                 Value = group.Key.Value,\n             });	0
8655681	8655637	C# Convert Char to KeyValue	[DllImport("user32.dll")]\nstatic extern short VkKeyScan(char ch);\n\nstatic public Key ResolveKey(char charToResolve)\n{\n    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));\n}	0
15268089	15267819	DatePicker Issue in WPF, selects only current date	DateTime date = datePickerDate.SelectedDate.Value.Date;	0
5612479	5612306	Converting long string of binary to hex c#	public static string BinaryStringToHexString(string binary)\n{\n    StringBuilder result = new StringBuilder(binary.Length / 8 + 1);\n\n    // TODO: check all 1's or 0's... Will throw otherwise\n\n    int mod4Len = binary.Length % 8;\n    if (mod4Len != 0)\n    {\n        // pad to length multiple of 8\n        binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');\n    }\n\n    for (int i = 0; i < binary.Length; i += 8)\n    {\n        string eightBits = binary.Substring(i, 8);\n        result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));\n    }\n\n    return result.ToString();\n}	0
7690838	7690496	Changing location values of Form Objects in a List Array	private void downButton_Click(object sender, EventArgs e)\n{\n    string NameSet = (sender as Button).Name.Split(new char[] { '_' })[1];\n    int itemNo = Int32.Parse(NameSet);\n    if (itemNo>0)\n    {\n       //swap row locations\n       var temp = _myControls[itemNo-1].Y;\n       _myControls[itemNo-1].Y = _myControls[itemNo].Y;\n       _myControls[itemNo].Y = temp;\n       //swap list order\n       var tempObj = _myControls[itemNo];\n       _myControls.RemoveAt(itemNo);\n       _myControls.Insert(tempObj, itemNo-1);\n    }\n}	0
3798876	3390016	How do you make a Generic Generic Factory?	namespace GenericFactoryPatternTestApp\n{\n    public class Factory< T >\n    {\n        private readonly Dictionary< string, Type > _factoryDictionary = new Dictionary< string, Type >();\n\n        public Factory()\n        {    \n            Type[] types = Assembly.GetAssembly(typeof (T)).GetTypes();\n\n            foreach (Type type in types)\n            {\n                if (!typeof (T).IsAssignableFrom(type) || type == typeof (T))\n                {\n                    // Incorrect type\n                    continue;\n                }\n\n                // Add the type\n                _factoryDictionary.Add(type.Name, type);\n            }\n        }\n\n        public T Create< V >(params object[] args)\n        {\n            return (T) Activator.CreateInstance(_factoryDictionary[typeof (V).Name], args);\n        }\n    }\n}	0
20934812	20934691	How to use table twice in entity framework?	from a in db.Account\nwhere !db.Account.Any(a2 => a2.ParentID == a.AccountID)\nselect a;	0
4366713	4366265	Bing maps Pushpins from XML Feed	var xmlns = XNamespace.Get("http://www.tfl.gov.uk/tfl/syndication/namespaces/geo");\n\nvar events = from ev in document.Root.Descendants("item")\n                select new\n                        {\n                            Latitude = Convert.ToDouble(ev.Element(xmlns + "Point").Element(xmlns + "lat").Value),\n                            Longitude = Convert.ToDouble(ev.Element(xmlns + "Point").Element(xmlns + "long").Value),\n                        };	0
13979628	13979590	Getting a Windows credentials username in c# windows form application	Environment.UserName	0
16107839	16094965	How to show a "cover page" for a Servicestack api site / Redirect to another website	SetConfig(new EndpointHostConfig\n{\n    RawHttpHandlers =\n    {\n         httpReq => httpReq.PathInfo == "/metadata" ? \n            new RedirectHttpHandler { AbsoluteUrl = "http://www.abc.com" } \n            : null\n     },\n});	0
1807028	1807004	C# Forms Picturebox to show a solid color instead of an image	imgBox.BackColor = Color.Red;	0
5856270	5855821	Looping through the boundary of a rectangle between two points on the rectangle?	(P1.y == P2.y)\n?\n(\n    C.x >= P1.x && C.x <= P2.x\n)\n:\n(\n  (C.x >= P2.x && C.x <= R.right && C.y == P2.y) || \n  (C.x >= P1.x && C.x <= R.right && C.y == P1.y) || \n  (C.x == R.x && C.y <= P1.y && C.y >= P2.y)\n)	0
2301286	2301235	Finding the string excluding the html tags	string html = "Your html string";\nstring x = Regex.Replace(html,@"<(.|\n)*?>", string.Empty);	0
23752134	23751919	How to turn off the mesh renderer	public List<Gem> gems = new List<Gem>();\n    public int GridWidth;\n    public int GridHeight;\n    public GameObject gemprefab;\n\n\n    // Use this for initialization\n    void Start () {\n\n       for (int  y = 0; y<GridHeight; y++) { \n                 for (int x= 0; x<GridHeight; x++) {\n\n\n          GameObject g =  Instantiate(gemprefab, new Vector3 (x, y, 0), Quaternion.identity) as GameObject;\n                    g.transform.parent = gameObject.transform;\n                    gemComponent = g.GetComponent<Gem>();\n                    gems.Add(gemComponent);\n\n\n          if(y==3 && x==3)\n          { //   eslot=new Vector3 (3, 3, 0) as GameObject;\n\n              //gemprefab.renderer.enabled = false;\n              gemComponent.sphere.renderer.enabled = false;\n\n          }\n\n          }\n          }\n       gameObject.transform.position = new Vector3 (-1.453695f, -1.409445f, 0);\n\n\n    }	0
30001650	30001540	POST SHA512 Encrypted String as HTTP Header (in C#)	return System.Convert.ToBase64String(hash);	0
17702951	17686028	Model not supported for deserialization	data = JSON.stringfy(/*myDataToSend*/)	0
2448546	2448303	Converting a int to a BCD byte array	static byte[] Year2Bcd(int year) {\n        if (year < 0 || year > 9999) throw new ArgumentException();\n        int bcd = 0;\n        for (int digit = 0; digit < 4; ++digit) {\n            int nibble = year % 10;\n            bcd |= nibble << (digit * 4);\n            year /= 10;\n        }\n        return new byte[] { (byte)((bcd >> 8) & 0xff), (byte)(bcd & 0xff) };\n    }	0
29613535	29613365	In my C# XAML Windows 8.1 app, how do I make programmatic binding work?	binding.Source = this; binding.Path = new PropertyPath("Str")	0
33587878	33587688	C# - modify doubles in string	Regex regex = new Regex(@"[1-9][0-9]*\.?[0-9]*([Ee][+-]?[0-9]+)?");\n        string testString ="1/(2.342/x) * x^3.45";\n        MatchCollection collection = regex.Matches(testString);\n        foreach(Match item in collection)\n        {\n            double extract =Convert.ToDouble(item.Value);\n            //change your decimal here...\n            testString = testString.Replace(item.Value, extract.ToString());\n        }	0
2871673	2871634	How to disable Alt + Shift + Tab using c#?	var altShift = Keys.Alt | Keys.Shift;	0
25423096	25423022	ListPicker Data Showing in Windows Phone	listPicker1.ItemsSource = list.Take(50);	0
12414347	12414243	Fetch nested query parameters in URL	var u = new Uri(returnParam); var newparams = u.Query;	0
2101060	2096318	delay Application Close best practice?	private void MainForm_FormClosing(object sender, FormClosingEventArgs e)\n{\n    // If it wasn't the user who asked for the closing, we just close\n    if (e.CloseReason != CloseReason.UserClosing)\n        return;\n\n    // If it was the user, we want to make sure he didn't do it by accident\n    DialogResult r = MessageBox.Show("Are you sure you want this?", \n                                     "Application is shutting down.",\n                                     MessageBoxButtons.YesNo, \n                                     MessageBoxIcon.Question);\n    if (r != DialogResult.Yes)\n    {\n        e.Cancel = true;\n        return;\n    }\n}\n\nprotected override void OnFormClosed(FormClosedEventArgs e)\n{\n    // Start the task\n    var thread = new Thread(DoTask)\n    {\n        IsBackground = false,\n        Name = "Closing thread.",\n    };\n    thread.Start();\n\n    base.OnFormClosed(e);\n}\n\nprivate void DoTask()\n{\n    // Some task to do here\n}	0
5968103	5968038	How to add x-webkit-speech tag to asp:TextBox	uxTextInput.Attributes.Add("x-webkit-speech", "x-webkit-speech");	0
17241162	17241122	Override a virtual method in a partial class	public class MyOrderProcessingService : OrderProcessingService\n{\n    public override PlaceOrderResult PlaceOrder(ProcessPaymentRequest processPaymentRequest) { //....\n}	0
10198278	10179588	Keeping ViewBag value after postback	public PartialViewResult CustomerStatus()\n {\n  ...here I called my private GetCustomerStatus methods\n  ViewBag.CustomerStatus = GetCustomerStatus();\n  Return PartialView("\n }	0
8547911	8544936	How to return formatting type Double mapping in NHibernate	FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),\n                new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));	0
3745061	3744953	Why does ConfigurationValidator validate the default value of a ConfigurationProperty even if IsRequired is true?	public class CustomConfigurationSection : ConfigurationSection\n{\n    public CustomConfigurationSection()\n    {\n        Properties.Add(new ConfigurationProperty(\n            "x",\n            typeof(string),\n            null,\n            null,\n            new StringValidator(1),\n            ConfigurationPropertyOptions.IsRequired));\n    }\n\n\n    public string X\n    {\n        get { return (string)this["x"]; }\n        set { this["x"] = value; }\n    }\n}	0
27721525	27721183	Drop SQLite tables using list of tables names	List<string> models = new List<string> { "WebBrowser", "Notebook", "Members"};\n\nforeach (string mod in models)\n{\n    using (var dbConn = new SQLiteConnection(app.DBPath))\n    {\n        SQLiteCommand command = new SQLiteCommand(dbConn);\n        command.CommandText = string.Format("DROP TABLE {0};", mod);\n        command.ExecuteNonQuery();\n    }\n}	0
8291696	8291680	Parse JSON String to JSON Object in C#.NET	new JavaScriptSerializer.Deserialize<object>(jsonString)	0
6948279	6947881	How do I serialize a dynamic object?	[DataContract]\npublic class ConfigurationInfo\n{\n    [DataMember]\n    public string Foo;\n    ...\n    // This string is a json/xml blob specific to the 'svcType' parameter\n    [DataMember]\n    public string ServiceConfig;\n}\n\n[DataContract]\npublic interface IServiceHost\n{\n    ConfigurationInfo GetConfigurationData(string svcType);\n}	0
3088328	3088241	How to filter off of a country code?	List<string> europeanEmailCountries = new List<string>();\neuropeanEmailCountries.AddRange("fr", "de"); // etc\n\n...\n\nif(europeanEmailCountries.Contains(countryCode))\n{\n    sendTo = europeanEmailAddress;\n}	0
9851599	9851583	Regex pattern with a slash	"\d{6}(/\d{1,2})?"	0
8627024	8626838	Smart search with one input	relational databases	0
21386345	21386242	Taking pixels from one image and enlarging them on a new image to create a larger version of original	for (int x = 0; x < 500; x++)\n{\n  for (int y = 0; y < 500; y++)\n  {\n    newImg.SetPixel(x*2, y*2, Color.FromArgb(oldImg.GetPixel(x, y).ToArgb()));\n    newImg.SetPixel(x*2 + 1, y*2, Color.FromArgb(oldImg.GetPixel(x, y).ToArgb()));\n    newImg.SetPixel(x*2, y*2 + 1, Color.FromArgb(oldImg.GetPixel(x, y).ToArgb()));\n    newImg.SetPixel(x*2 + 1, y*2 + 1, Color.FromArgb(oldImg.GetPixel(x, y).ToArgb()));\n  }\n}	0
10435597	10435570	Show values of List<string[]> without using extra variables or using the foreach loop	Console.WriteLine(definitions[0][0]  + "\tdef: " + definitions[0][1]);	0
5852435	5852415	How to refresh binding to property that doesn't support INotyfyPropertyChanged?	textBox1.GetBindingExpression(TextBox.TextProperty).UpdateTarget();	0
6839429	6839334	Checking data with commas in a DataTable	public static DataTable DataTableCommaReplce(DataTable dt) {\n    foreach (DataRow row in dt.Rows) {\n        foreach (DataColumn col in dt.Columns) {\n            string s = row[col] as string;\n            if (s != null) {\n                if (s.Contains(',')) {\n                    row[col] = string.Format("\"{0}\"", s);\n                }\n            }\n         }\n    }\n    return dt;\n}	0
9332763	9332723	Binding TimeSpan to a DataGridView column	public class MyObject\n{\nprivate TimeSpan _myTimeSpan;\n\n// ...\n\npublic string TimeSpanFormatted\n{\n    get\n    {\n         return _myTimeSpan.ToString("c");\n    }\n}\n\n// ...\n}	0
8626223	8626143	Need Help Converting Regex From VB.NET To C#	private string getBetween(string strSource, string strStart, string strEnd)\n        {\n            int Start, End;\n            if (strSource.Contains(Starting) && strSource.Contains(Ending))\n            {\n                Start = strSource.IndexOf(Starting, 0) + strStart.Length;\n                End = strSource.IndexOf(strEnd, Start);\n                return strSource.Substring(Start, End - Start);\n            }\n            else\n            {\n                return "";\n            }\n        }	0
15334282	15264018	How to validate namespace name in CodeDOM?	public bool IsValidNamespace(string input)  \n        {  \n            //Split the string from '.' and check each part for validity  \n            string[] strArray = input.Split('.');  \n            foreach (string item in strArray)  \n            {                  \n                if (! CodeGenerator.IsValidLanguageIndependentIdentifier(item))  \n                    return false;  \n            }  \n            return true;   \n        }	0
5229311	5229292	Get folder name from full file path - C#, ASP.NET	string dirName = new DirectoryInfo(@"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;	0
6201688	6201671	MVC 3 Razor, don't show default value	public class Model\n{\n    public int? Field { get; set; }\n}	0
23085586	23085486	Returning the name of a control	private void HandleEsc(object sender, KeyEventArgs e)\n{\n    if (e.Key == Key.Escape) Close();\n    if (e.Key == Key.Enter ||\n        e.Key == Key.Tab) SearchAndDisplay(e.OriginalSource)\n}   \n\nprivate void SearchAndDisplay(object sender)\n{\n    if(sender is Control)\n    {\n        MessageBox.Show(((Control)sender).Name);\n    }\n}	0
3704560	3704496	Limited string replacement using regex?	Regex cat = new Regex("cat");\nstring input = "cat cat cat cat cat";\nConsole.WriteLine(cat.Replace(input, "dog", 3));\nConsole.ReadLine();	0
131467	131456	How do you apply a .net attribute to a return type	[return: MarshalAs(<your marshal type>)]\npublic ISomething Foo()\n{\n    return new MyFoo();\n}	0
8454948	8435926	How to create a simple menu which works out of the application in C# WPF	mouse = new MouseKeyboardActivityMonitor.MouseHookListener(new GlobalHooker());\nmouse.MouseMove += (sd, args) =>\n        {\n            movingCount = 0;\n            mouseLeft = args.X; //set the window.left to mouseLeft before showing it\n            mouseTop = args.Y; //set the window.top to mouseTop before showing it\n        };\n\nmouse.Enabled = true;	0
20996537	20994841	Display pdf file from oracle database (pdf path is stored in database) using C#?	if (reader.HasRows)\n{\n    context.Response.Clear();\n    context.Response.ContentType = "application/pdf";\n    context.Response.TransmitFile(reader["pdfpath"].ToString()); //the path must be actual physical path of the file\n    contest.Response.End();\n}\nelse\n{\n    context.Response.Clear();\n    context.Response.ContentType = "text/plain";\n    context.Response.Write("No file found");\n    contest.Response.End();\n}	0
9503040	9503008	Deleting rows in a table with Linq to SQL	var items = removeFromGroup.ToList();\nforeach (var item in items)\n  dataContext.GroupMembers.DeleteOnSubmit(item);	0
22519646	22519125	Converting Flat data to hierarchical	public class Mark\n{\npublic string markname { get; set; }\npublic int mark { get; set; }\n}\n\npublic class SubjectSubcategory\n{\npublic string name { get; set; }\npublic List<Mark> Marks { get; set; }\n}\n\npublic class SubjectCategory\n{\npublic string name { get; set; }\npublic List<SubjectSubcategory> Subject_subcategory { get; set; }\n}\n\n public class Major\n{\npublic string name { get; set; }\npublic List<SubjectCategory> Subject_category { get; set; }\n }\n\n public class Frequency\n {\npublic string name { get; set; }\npublic List<Major> Major { get; set; }\n }\n\npublic class Product\n{\npublic string studentname { get; set; }\n public List<Frequency> frequency { get; set; }\n }\n\npublic class RootObject\n{\npublic List<Product> product { get; set; }\n}	0
20355682	20355448	get x and y from listbox (windows phone 7.1)	public void searchResult_Click(object sender, RoutedEventArgs e)\n    {\n        var button = sender as Button; //Assuming your trigger is a button UI element.\n\n        if (button != null)\n        {\n            var place = button.DataContext as TestMap.Classes.Global.Place;\n\n            if (place != null)\n            {\n                Classes.Global.posx = place.posx;\n                Classes.Global.posy = place.posy;\n            }\n        }\n\n        NavigationService.GoBack();\n    }	0
7648700	7648569	How can I use only a part of my assembly?	#if APPA\n// code for AppA\n#endif	0
922260	922250	How do I programmatically add an unknown number of columns to an ASP.NET page using a repeater where some of the columns are declared at runtime in the SQL string?	protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    DataRowView rowView = (DataRowView)e.Row.DataItem;\n\n    for (int i = 0; i < rowView.Row.ItemArray.Length; i++)\n    {\n        DateTime? tmpDate = rowView[i] as DateTime?;\n\n        if (tmpDate.HasValue)\n        {\n            if (tmpDate.Value.Second > 0)\n                e.Row.Cells[i].Text = tmpDate.Value.ToShortTimeString();\n            else\n                e.Row.Cells[i].Text = tmpDate.Value.ToShortDateString();\n        }\n    }\n}	0
8795064	8794877	Using .NET SqlTypes with MySQL	string myStringField = reader["someVarCharField"].ToString();\nbool myBoolField = reader.GetBoolean("booleanField");\netc....	0
14771348	14771148	Flashing when clearing and repopulating a ListBox	listBox1.BeginUpdate();\nlistBox1.Items.Clear();\nlistBox1.Items.AddRange(thingys);\nlistBox1.EndUpdate();	0
9848903	9848539	Most standard way to set configuration settings in a Class Library	Function Add (FirstNumber, SecondNumber, Config)	0
24261385	24261264	Regex match case and ignore rest of file	(?<=until\s)\d[2]-[A-Za-z]+-\d+	0
4278992	4278868	Search a file for a sequence of bytes (C#)	int GetPositionAfterMatch(byte[] data, byte[]pattern)\n{\n  for (int i = 0; i < data.Length - pattern.Length; i++)\n  {\n    bool match = true;\n    for (int k = 0; k < pattern.Length; k++)\n    {\n      if (data[i + k] != pattern[k])\n      {\n        match = false;\n        break;\n      }\n    }\n    if (match)\n    {\n      return i + pattern.Length;\n    }\n  }\n}	0
4635093	4635041	permutation of array items	var result = \n    from a in myString\n    from b in myString\n    where a != b\n    select a + b;	0
13079794	13068683	Random crashes in Visual Studio extension with command filters	Marshal.AllocCoTaskMem(16);	0
3063129	3063099	Using a Linq-To-SQL class automagically generates the connection string for me; is there a way to manually set it?	MyDbContext _context = MyDbContext(connString);	0
14853241	14844412	How to assign value to form tag from user control?	HtmlForm frm = new HtmlForm();\nfrm = (HtmlForm)Page.FindControl("Form1");\nfrm.Enctype = "multipart/form-data";	0
18446086	18445982	How can I put data from my datagridview to textboxes?	yourTextBox.Text = yourDataGridView.SelectedRows[0].Cells["Title"].Value.ToString();\nyourTextBox2.Text = yourDataGridView.SelectedRows[0].Cells["ISBN"].Value.ToString();	0
9841932	9841708	winform in console application	if (args.Contains["--GUI"])\n{\n   Application.Run(new Form1());\n}\nelse\n{\n  if (hastolaunchForm)\n  {\n     // use Process.start to run another version of your app with --GUI parameter\n     // and close\n  }\n  else\n  {\n     // do console stuff.\n  }\n  }\n}	0
18935375	18253647	ClickOnce fails to initialize with no network	private static bool _isNetworkDeployed;\n    private static bool _isNetworkDeployedChecked;\n\n    public static bool IsNetworkDeployed\n    {\n        get\n        {\n            if (!_isNetworkDeployedChecked)\n            {\n                _isNetworkDeployed = (\n                    AppDomain.CurrentDomain != null &&\n                    AppDomain.CurrentDomain.ActivationContext != null &&\n                    AppDomain.CurrentDomain.ActivationContext.Identity != null &&\n                    AppDomain.CurrentDomain.ActivationContext.Identity.FullName != null);\n                //_isNetworkDeployed = ApplicationDeployment.IsNetworkDeployed;\n                _isNetworkDeployedChecked = true;\n            }\n            return _isNetworkDeployed;\n        }\n    }	0
15394179	15394057	How can you check if a list of strings match all the words in your phrase?	string[] arr = new string[] { "hello world", "how are you", "what is going on" };\nstring s = "hello are going on";\nstring s2 = "hello world man";\nbool bs = s.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word)));\nbool bs2 = s2.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word)));	0
9443536	9139026	Outputting Programmatically to MSword; sensing end of line	LineCount = range.ComputeStatistics(Word.WdStatistic.wdStatisticLines);	0
3732234	1772004	How can I make the xmlserializer only serialize plain xml?	// To Clean XML\n    public string SerializeToString(T value)\n    {\n        var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });\n        var serializer = new XmlSerializer(value.GetType());\n        var settings = new XmlWriterSettings();\n        settings.Indent = true;\n        settings.OmitXmlDeclaration = true;\n\n        using (var stream = new StringWriter())\n        using (var writer = XmlWriter.Create(stream, settings))\n        {\n            serializer.Serialize(writer, value, emptyNamepsaces);\n            return stream.ToString();\n        }\n    }	0
30681572	30681384	Find keys with min difference in dictionary	var items = new Dictionary<int, string>();\n         items.Add(1, "SomeData");\n         items.Add(5, "SomeData");\n         items.Add(23, "SomeData");\n         items.Add(22, "SomeData");\n         items.Add(2, "SomeData");\n         items.Add(7, "SomeData");\n         items.Add(59, "SomeData"); \n\n         var sortedArray = items.Keys.OrderBy(x => x).ToArray();\n\n         int minDistance = int.MaxValue;\n\n         for (int i = 1; i < sortedArray.Length; i++)\n         {\n             var distance = Math.Abs(sortedArray[i] - sortedArray[i - 1]);\n             if (distance < minDistance)\n                 minDistance = distance;\n         }\n\n         Console.WriteLine(minDistance);	0
5396299	5395961	Object A has a reference to Object B which has Object A as public property - bad design?	// Reaches too far.  Makes this depend on the interface of SomeProperty\nthis.Context.SomeProperty.DoSomething();\n\n// ...\n\n// Not reaching too far.  Only depends on Context.\n// This might forward to SomeProperty.DoSomething()\nthis.Context.DoSomething();	0
18991390	18991360	Using Linq to return a Comma separated string	var s = string.Join(",", products.Where(p => p.ProductType == someType)\n                                 .Select(p => p.ProductId.ToString()));	0
33817615	33817591	Custom Control, bind to code behind	private Double _ProfilePhotoSize = 50;\n    public Double ProfilePhotoSize\n    {\n        get { return _ProfilePhotoSize; }\n        set\n        {\n            if (_ProfilePhotoSize != value)\n                _ProfilePhotoSize = value;\n        }\n    }	0
29173099	29172613	Trying to produce a maze from a text file using c# in unity	int y = 0;\n\n// Accesses each line one at a time\nforeach (string line in eachLine)\n{\n    // reset the x position to the beginning of each line.\n    int x = 0;\n\n    // Accesses each character in each line one at a time\n    foreach(char c in line)\n    {\n        string currentNum = c.ToString();\n        thisNum = Convert.ToInt32(currentNum);\n\n        if (thisNum == 1)\n        {\n            // Create a single object at x,y (no looping here)\n            ObjectSpawnPosition = new Vector3(x,y,0);\n            Instantiate(obj, ObjectSpawnPosition, Quaternion.identity);\n        }\n        // increment x inside the inner loop.\n        x++;\n    }\n    // done with a line, so increment y to go to the next line.\n    y++;\n}	0
27917975	27875631	Configure cron job that is executing every 15 minutes on Hangfire	RecurringJob.AddOrUpdate(() => Console.Write("Recurring"), "*/15 * * * *");	0
675827	675815	What is the correct syntax to represent subobjects in JSON?	{\n    Name             : 'ObjectName',\n    Host             : 'http://localhost',\n    ImagesPath       : '/Images/',\n    MoreInformation  : {TestString : 'hello world'}\n};\n\n// And to access the nested object property:\nobj.MoreInformation.TestString	0
1811892	1811846	How to get the second highest number in an array in Visual C#?	int secondHighest = (from number in numbers\n                     orderby number descending\n                     select number).Skip(1).First();	0
9101912	9100811	Double click timer event 	Timer timer = new System.Timers.Timer(5000);//5 seconds\n    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);\n\n    private void form_MouseHover(object sender, System.EventArgs e) \n    {            \n        timer.Start();\n    }\n\n    private void form_MouseLeave(object sender, System.EventArgs e) \n    {            \n        timer.Stop();\n    }\n\n    void timer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        timer.Stop();\n        OpenFileOrFolder();//Edit : implement your file / folder opening logic here\n    }	0
1527388	1527370	Load a DataGridView using Linq to SQL	DCDataContext db = new DCDataContext();\n    dataGridViewJobs.DataSource = (from jobs in db.jobs\n                                    where p.closeDate <= DateTime.Now\n                                    select jobs);	0
6213481	6213452	Search $needle in $haystack	if (pageName.Contains("account"))\n{\n    // do something\n}	0
22403356	22403215	How to get list of record within a range using LINQ	NearByPlaces = (from p in ctx.places\n                where p.Latitude > s.Latitude - latrange && \n                      p.Latitude < s.Latitude + latrange &&\n                      p.Longitude > s.Longitude - longrange && \n                      p.Longitude < S.Longitude + longrange\n                select /* whatever */).ToArray()	0
17771006	17770778	Problems with finding a "Shared" directory in isolated storage	var appStorage = IsolatedStorageFile.GetUserStoreForApplication();\nvar listDirectories = appStorage.GetDirectoryNames().Where(l => l != "Shared");	0
27010318	27010273	Linq query how to select last one week data from today's date	var dateCriteria = DateTime.Now.Date.AddDays(-7);\nvar QueryDeatils = from M in db.Tr_Mealcode\n                   where M.codeDate >= dateCriteria \n                   group M by M.merchantID into G\n                   select new\n                   {\n                      MerchantId=G.Select(m=>m.merchantID)\n                   };	0
13532883	13532704	Looking for a clean way to convert a string list to valid List<long> in C#	string addressBookEntryIds = "41,42x,43";\n\nFunc<string, long?> safeParse = (s) => {\n            long val;\n            if (Int64.TryParse(s, out val))\n            {\n                return val;\n            }\n            return null;    \n};\n\n\nvar longs = (from s in addressBookEntryIds.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries)\n            let cand = safeParse(s)\n            where cand.HasValue\n            select cand.Value).ToList();	0
6710150	6708430	How to capture thumbnail for video while uploading it in ASP.NET?	//Create Thumbs\nstring thumbpath, thumbname;\nstring thumbargs;\nstring thumbre;\nthumbpath = AppDomain.CurrentDomain.BaseDirectory + "Video\\Thumb\\";\nthumbname = thumbpath + withoutext + "%d" + ".jpg";\nthumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;\nProcess thumbproc = new Process();\nthumbproc = new Process();\nthumbproc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";\nthumbproc.StartInfo.Arguments = thumbargs;\nthumbproc.StartInfo.UseShellExecute = false;\nthumbproc.StartInfo.CreateNoWindow = false;\nthumbproc.StartInfo.RedirectStandardOutput = false;\ntry\n{\nthumbproc.Start();\n}\ncatch (Exception ex)\n{\nResponse.Write(ex.Message);\n}\nthumbproc.WaitForExit();\nthumbproc.Close();	0
15387500	15387300	css opacity to argb	alpha = (int)(textOpacity*255);	0
15150025	15149966	Extracting Numbers From Between String	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string test = "/store/457987680928164?id=2";\n            int start = test.IndexOfAny("0123456789".ToCharArray());\n            int end = test.IndexOf("?");\n\n            Console.WriteLine(test.Substring(start, end - start));\n\n            Console.ReadLine();\n        }\n    }\n}	0
33737772	33737310	How are data annotations transformed at runtime?	void Main()\n{\n    Console.WriteLine (Foo.Bar.GetAttribute<ExampleAttribute>().Name);\n    // Outputs > random name\n}\n\npublic enum Foo\n{\n    [Example("random name")]\n    Bar\n}\n\n[AttributeUsage(AttributeTargets.All)]\npublic class ExampleAttribute : Attribute\n{\n    public ExampleAttribute(string name)\n    {\n        this.Name = name;\n    }\n\n    public string Name { get; set; }\n}\n\npublic static class Extensions\n{\n    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)\n            where TAttribute : Attribute\n    {\n        return enumValue.GetType()\n                        .GetMember(enumValue.ToString())\n                        .First()\n                        .GetCustomAttribute<TAttribute>();\n    }\n}\n// Define other methods and classes here	0
5921315	5915025	Detecting invalid data in the data binding source	Binding SelectedValueBinding = new Binding("SelectedValue", repository, "RepositoryValue", true, DataSourceUpdateMode.OnPropertyChanged);\nSelectedValueBinding.Format += new ConvertEventHandler(SelectedValueBinding_Format);\nmyComboBox.DataBindings.Add(SelectedValueBinding);\n\nvoid SelectedValueBinding_Format(object sender, ConvertEventArgs e)\n{\n        // if e.Value is Invalid\n        // myComboBox.SelectedValue = "Default Value";\n}	0
22081630	22081496	Trying to build a class with a string array	display.Text = was.answer;	0
29460050	29459999	Sort multiple arrays based on an ID array	List<Tuple<int,int>> arraySortHelperList = new List<Tuple<int,int>>();\nfor(...)\n{\n     int id = ...\n     arraySortHelperList.Add(new Tuple<int,int>(id, n++));\n}	0
30919044	30917110	How can i save my players position in unity without using playerprefs in C#	using UnityEngine;\nusing System;\nusing System.Runtime.Serialization;\n\n[Serializable]\npublic class BasePrefabSaveData : ISerializable\n{\n   public Vector3 _Position;\n\n   public BasePrefabSaveData()\n   {\n   }\n\n   public BasePrefabSaveData(SerializationInfo info, StreamingContext context)\n   {\n      _Position.x = (float)info.GetValue( "Position.x", typeof( float ) );\n      _Position.y = (float)info.GetValue( "Position.y", typeof( float ) );\n      _Position.z = (float)info.GetValue( "Position.z", typeof( float ) );\n   }\n\n   public virtual void GetObjectData(SerializationInfo info, StreamingContext context)\n   {\n      info.AddValue( "Position.x", _Position.x, typeof( float ) );\n      info.AddValue( "Position.y", _Position.y, typeof( float ) );\n      info.AddValue( "Position.z", _Position.z, typeof( float ) );\n   }\n}	0
1048672	1048643	Format a double value like currency but without the currency sign (C#)	string forDisplay = currentBalance.ToString("N2");	0
1717349	1717318	Creating an entry point in a C# DLL to call from WIX	[CustomAction] \npublic static ActionResult MyThing(Session session) \n{ \n  // do your  stuff...\n  return ActionResult.Success; \n}	0
7640142	7639657	Create sql server compact file in appdata folder	AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));\n\n<connectionStrings>\n  <add name="DataContext" \n       connectionString="Data source=|DataDirectory|Database.sdf;"\n       providerName="System.Data.SqlServerCe.4.0"/>\n</connectionStrings>	0
8260649	8260501	Corrupt zip file while download by URL	using (var wc = new WebClient())\n{\n  wc.DownloadFile(Url, ResultFileName);\n}	0
12816637	12816308	Do triggers have any performance impact on the stored procedure	BEFORE or  AFTER	0
30688152	30687849	Use a foreach within a new object declaration	ChildItems = r["ChildItems"].Select(x=>new ItemObject{Prop1 = x.Prop1, Prop2 = x.Prop2 ... }).ToList()	0
14567773	14567525	C# random string generator with atleast one numeric	var charsALL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";\nvar randomIns = new Random();\nint N = 6;\nvar rndChars = Enumerable.Range(0, N)\n                .Select(_ => charsALL[randomIns.Next(charsALL.Length)])\n                .ToArray();\nrndChars[randomIns.Next(rndChars.Length)] = "0123456789"[randomIns.Next(10)];\n\nvar randomstr = new String(rndChars);	0
23105078	23105045	how to make Value cannot be null, null	public List<GSMData> GetGSMList()\n        {\n            return meters.Where(x=>x.Gsmdata!=null && x.Gsmdata.Any()).Select(x => x.Gsmdata.Last())\n                         .ToList();\n        }	0
3618786	3582140	Winforms Updating UI Asynchronously Pattern - Need to Generalize	private void RunOperationWithMainProgressFeedback(\n    Func<bool> operation,\n    string startMessage,\n    string completionMessage,\n    string cancellationMessage,\n    string errorMessage)\n{\n    this._UpdateMainForm.BeginInvoke(startMessage, false, null, null);\n    try\n    {\n        if (operation.Invoke())\n        {\n            this._UpdateMainForm.BeginInvoke(completionMessage, true, null, null);\n        }\n        else\n        {\n            this._UpdateMainForm.BeginInvoke(cancellationMessage, true, null, null);\n        }\n    }\n    catch (Exception)\n    {\n        this._UpdateMainForm.BeginInvoke(errorMessage, true, null, null);\n        throw;\n    }\n}\n\nprivate void btnX_Click(object sender, EventArgs e)\n{\n    this.RunOperationWithMainProgressFeedback(\n        this.UpdateOperationA,\n        "StartA",\n        "CompletedA",\n        "CanceledA",\n        "ErrorA");\n}	0
990671	990623	C# Winform Alter Sent Keystroke	protected override void OnKeyUp(KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Right)\n    {\n       Control activeControl = this.ActiveControl;\n\n       if(activeControl == null)\n       {\n            activeControl = this;\n       }\n\n       this.SelectNextControl(activeControl, true, true, true, true);\n       e.Handled = true;\n    }\n\n    base.OnKeyUp(e);\n}	0
10280057	10175463	Change text backgroundcolor in Word	Range r = this.Application.ActiveDocument.Range();\nr.Text = "blabla";\nr.Font.Shading.BackgroundPatternColor =(WdColor)ColorTranslator.ToOle(0, 214, 227,188);	0
5594525	5594505	string manipulation in c#	var list = mainString.Split('\\');\nreturn list[list.Length-1];	0
1585375	1585354	Get return value from process	Process P = Process.Start(sPhysicalFilePath, Param);\nP.WaitForExit();\nint result = P.ExitCode;	0
11918723	11918656	Access object from Event Handler	b.MessageRecievedEvent += (e) => HandleMessage(b, e);\n....\nprivate static void HandleMessage(IBattleNet b, BattleMessageEventArgs args) {\n....	0
19409699	19395193	How to Remove QueryString Values to Avoid Tombstoning Issues	string fromLensPicker = null;\nif (NavigationContext.QueryString.TryGetValue("fromLensPicker", out fromLensPicker))\n{\n    if (fromLensPicker == "fromLensPicker")\n    {\n        NavigationContext.QueryString.Remove("fromLensPicker");\n        //...\n    }\n}	0
797712	797698	Linq To Sql - How to get # of inserted records	_db.GetChangeSet().Inserts.Count();	0
31302456	31297218	C# / RegEx - Modify Lines in Text File	DTP*348	0
20316315	20316218	Asp.net MVC ActionResult how to detect optional parameters?	public ActionResult Register(string id)\n    {\n        var model = new RegisterViewModel();\n        if (!string.IsNullOrWhiteSpace(id) && id.ToLower() == "professional")\n        {\n            model.IsProfessional = true;\n        }\n        else\n        {\n            model.IsProfessional = false;\n        }\n        return View();\n    }	0
6053538	6052845	How to use Insert method of a datasource when data is not coming form a databaound control?	protected void Button1_Click(object sender, EventArgs e)\n{\n    SqlDataSource1.InsertParameters.Add("ParameterName", "ParameterValue");\n    ......Set parameters for Insert....................\n    ..........................\n    SqlDataSource1.Insert(); // then Call the insert method to perform insertion\n}	0
3178208	3178036	Handling a save on a separate thread	public List<object> CreateListCopy()\n{\n    List<object> result = new List<object>();\n    lock(_list)\n    {\n        foreach(object o in _list)\n        {\n            result.Add(o.Clone());\n        }\n    }\n\n    return result;\n}	0
19752636	19752523	How to copy data to clipboard when user selects "Copy" from ContextMenu	var hitTestInfo = dataGridView1.HitTest(e.X, e.Y);\nif (hitTestInfo.Type != DataGridViewHitTestType.Cell) { return; }\n\nvar mi = new MenuItem("Copy")\nmi.Tag = hitTestInfo;\nmi.Click += (s, e) =>\n{\n    var hti = ((MenuItem)s).Tag as HitTestInfo;\n    var val = dataGridView1.Rows[hti.RowIndex].Cells[hti.ColumnIndex].Value;\n\n    Clipboard.SetData(DataFormats.Text, val);\n}\n\nm.MenuItems.Add(mi);	0
14451222	14450991	Update database table based on textbox values	protected void Page_Load(object sender, EventArgs e)\n{\n   if (!IsPostBack)\n   {\n     Info();\n   }\n}	0
17514091	15016296	Move a point towards another point, by a certain distance	yDiff = Math.Abs(Start.Y - End.Y);\nxDiff = Math.Abs(Start.X - End.X);\ndistance = Math.Sqrt(yDiff * yDiff + xDiff * xDiff)	0
4902482	4902464	How to add text to a WPF Label in code?	DesrLabel.Content	0
24136489	24057203	Keypress event in cell of datagridview with key return	void TextBox1_KeyDown(object sender, KeyEventArgs e) \n{ \n    if (e.KeyCode == Keys.Enter) \n    { \n        e.Handled = true; \n    } \n}\n\nvoid TextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) \n{ \n    if (e.KeyCode == Keys.Return)\n    {\n        /* Your code here! */ \n    }\n}	0
4182886	4182594	Grab all text from html with Html Agility Pack	var root = doc.DocumentNode;\nvar sb = new StringBuilder();\nforeach (var node in root.DescendantNodesAndSelf())\n{\n    if (!node.HasChildNodes)\n    {\n        string text = node.InnerText;\n        if (!string.IsNullOrEmpty(text))\n            sb.AppendLine(text.Trim());\n    }\n}	0
6269712	6269679	LINQ: String.Join a list but add a character to that string beforehand	string.Join(",", mylist.Select(s => "@" + s));	0
5020136	5019977	Using AutoMapper to map object fields to array?	IDictionary<string, object> GetDictionaryFromObject(object obj)\n{\n    if(obj == null) return new Dictionary<string, object>();\n    return obj.GetType().GetProperties().\n                ToDictionary(p => p.Name,\n                             p => p.GetValue(obj, null) ?? DBNull.Value);\n}	0
8702920	8702370	Algorithm find every child by idParent property	public void myMethod(int value)\n{\n    List<int> intList = new List<int>();\n    List<Drinking> drinkingList= (from d in myEntities.Drinking\n                          select d).ToList();\n    foreach (var d in drinkingList)\n    {\n       if (d.Drinking2Reference.EntityKey != null)\n       {\n          if(d.idCategory == value)\n             intList.Add(value);\n          else {\n             for(int i=0; i < intList.Count; i++) {\n                if(intList.ElementAt(i) == d.idParentCategory)\n                   intList.Add(d.idCategory);\n             }\n          }\n\n       }\n    }\n    //Print numbers    \n}	0
28232751	28232750	How to make HTTPS SOAP request bypassing SSL certificate in .Net C#?	ServicePointManager.ServerCertificateValidationCallback +=\n                (mender, certificate, chain, sslPolicyErrors) => true;	0
17920244	17920125	Get confirm-box value via code-behind at C#	type=   ClientScript.RegisterStartupScript(typeof(Page), "exampleScript", "if(confirm('are you confirm?')) { document.getElementById('btn').click(); } ", true);	0
4934156	4933980	How do I correctly populate a listbox from an observable collection?	public string Name {get; set;}	0
7175944	7175701	Converting wav file to wav file (changing format)	WaveFormat target = new WaveFormat(8000, 8 , 1);\nWaveStream stream =new WaveFileReader("c:\\test.wav");\nWaveFormatConversionStream str = new WaveFormatConversionStream(target, stream);\nWaveFileWriter.CreateWaveFile("c:\\converted.wav", str);	0
3913975	3913868	How to get the caller of a WPF Converter?	public class SeparatorTabStyleSelector : StyleSelector\n{\n    #region " StyleSelector Implementation "\n\n    public override Style SelectStyle(\n        object item,\n        DependencyObject container)\n    {\n        object data = item as 'Your Bindable Object';\n        if ('Your Condition Based upon item object')\n        {\n            return (Style)((FrameworkElement)container).FindResource("Style1");\n        }\n        else if ('If Condition is not true Based upon item object')\n        {\n            return (Style)((FrameworkElement)container).FindResource("Style2");\n        }\n\n        return base.SelectStyle(item, container);\n    }\n\n    #endregion " StyleSelector Implementation "\n\n}	0
3681682	3681574	How to implement this pluggable mechanism in C# and java?	interface D {\n   static final String ORDER_PROPERTY="ORDER";\n   void setOrder(Order order);\n   Order getOrder();\n}\n\nclass B implements D {\n   // delegate object to implement support for event listeners and event firing\n   private java.beans.PropertyChangeSupport propertyChangeSupport = new java.beans.PropertyChangeSupport(this);\n   private Order order = null; // field that holds current order\n   @Override\n   public void setOrder(Order order) {\n      Order old = this.order;\n      this.order = order;\n      propertyChangeSupport.firePropertyChange(ORDER_PROPERTY, old, order);\n   }\n   // more B code here\n}	0
32091649	32090319	Copying one datatable to another datatable c#	dt3 = dt.AsEnumerable()\n              .Where(rows => rows.Field<DateTime?>("date") == cellData )\n              .CopyToDataTable();	0
1471515	1471490	Writing the results of a FOR XML query to a file with C#.NET	myDataSet.ReadXml(cmd_Org.ExecuteXmlReader(), XmlReadMode.Auto);	0
27126635	27125800	How can I set output path and assembly name in Visual Studio 2010?	using System;\n    using System.Collections.Generic;\n    using System.Linq;\n    using System.Text;\n\n    namespace RectangleApplication\n    {\n        public class Rectangle\n        {\n            public double width;\n            public double length;\n\n            public double GetArea()\n            {\n                return width * length;\n            }\n\n            public void Display()\n            {\n                Console.WriteLine("Lenght:{0}", length);\n                Console.WriteLine("Width: {0}", width);\n                Console.WriteLine("Area: {0}", GetArea());\n            }\n        }\n\n        public class ExecuteRectangle\n        {\n            public static void Main(string[] args)\n            {\n                Rectangle r = new Rectangle();\n                r.length = 3.5;\n                r.width = 4.5;\n                r.Display();\n                Console.ReadLine();\n\n            }\n        }\n    }	0
25641440	25640618	Background color of Gridview row on RowDataBound is not working in IE11	protected void Grd_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            string Status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Visit_Status"));\n\n            if (Status == "1")\n            {\n                e.Row.Attributes["style"] = "background-color: #28b779";\n            }\n            else\n            {\n                e.Row.Attributes["style"] = "background-color: #da5554";\n            }\n        }        \n    }	0
26583068	26582438	Combobox Item doesnt update	void Names_PropertyChanged(object sender, PropertyChangedEventArgs e)\n{\n    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>\n    {\n        if (e.PropertyName == "Stuff" && m_Stuff != things.a)\n        {\n            Stuff = things.a;\n        }\n    }));\n}	0
1942012	1941951	XML Serialization in C# without XML attribute nodes	var s= new System.Xml.Serialization.XmlSerializer(typeof(TypeToSerialize));\n  var ns= new System.Xml.Serialization.XmlSerializerNamespaces();\n  ns.Add( "", "");\n  System.IO.StreamWriter writer= System.IO.File.CreateText(filePath);\n  s.Serialize(writer, objectToSerialize, ns);\n  writer.Close();	0
27685604	27685435	How to cast 'System.IntPtr' to 'float[]'?	Marshal.Copy	0
7007739	6999667	How to programmatically create rectangle and textblock with binding element with c#?	Binding b = new Binding { Path = new PropertyPath("Behaviour.Behaviours[0].CurrentPoints[" + i +"].Y?) };	0
314475	314466	Generating an array of letters in the alphabet in C#	char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();	0
31105631	31105190	Calling Base REST API	User-Agent	0
19241054	19240971	How to create an object instance of class with internal constructor via reflection?	var myClass = Activator.CreateInstance(typeof(MyClass), true);//say nonpublic	0
2072044	2070985	Programmatically finding an Excel file's Excel version	var doc = new OleDocumentPropertiesClass();            \ndoc.Open(@"c:\spreadhseet.xls", false, dsoFileOpenOptions.dsoOptionDefault);\nConsole.WriteLine(doc.OleDocumentType);	0
28710099	28708740	How to add minutes in DateTime value from SQL Server to C#	if (e.Row.DataItem == null)\n   return;\n\nvar lb = e.Row.FindControl("lblDateUpdated") as Label;\nvar value = ((string)lb.Content).Trim();	0
29549284	29549120	Read in from multiple type files all in different locations	IEnumerable<string> fileContents = Directory.EnumerateFiles("E:", "*.*", SearchOption.TopDirectoryOnly)\n            .Select(x => new FileInfo(x))\n            .Where(x => x.CreationTime > DateTime.Now.AddHours(-1) || x.LastWriteTime > DateTime.Now.AddHours(-1))\n            .Where(x => x.Extension == ".xml" || x.Extension == ".txt")\n            .Select(file => ParseFile(file));\n\n    private string ParseFile(FileInfo file)\n    {\n        using (StreamReader sr = new StreamReader(file.FullName))\n        {\n            string line;\n            string endResult;\n            while ((line = sr.ReadLine()) != null)\n            {\n                //Logic here to determine if this is the correct file and append accordingly\n                endResult += line + Environment.Newline;\n            }\n            return endResult;\n        }\n    }	0
7368409	7368387	How do I assert that a method is called only once?	var mock = MockRepository.GenerateMock<ICanBeProcessedOnceADay>();\nmock.Expect(a => a.Process()).Repeat.Times(1);\n...\nmock.VerifyAllExpectations();	0
2822803	1483597	Getting the byte bits as string	private string byteToBitsString(byte byteIn)\n{\n    char[] bits = new char[8];\n    bits(0) = Convert.ToString((byteIn / 128) % 2);\n    bits(1) = Convert.ToString((byteIn / 64) % 2);\n    bits(2) = Convert.ToString((byteIn / 32) % 2);\n    bits(3) = Convert.ToString((byteIn / 16) % 2);\n    bits(4) = Convert.ToString((byteIn / 8) % 2);\n    bits(5) = Convert.ToString((byteIn / 4) % 2);\n    bits(6) = Convert.ToString((byteIn / 2) % 2);\n    bits(7) = Convert.ToString((byteIn / 1) % 2);\n    return bits;\n}	0
10922672	10922042	Window SizeToContent and ListBox sizing	public MainWindow()\n{\n    InitializeComponent();\n\n    Loaded += OnLoaded;\n}\n\nprivate void OnLoaded(object sender, RoutedEventArgs routedEventArgs)\n{\n    SizeToContent = SizeToContent.Manual;\n\n    var messages = new ObservableCollection<string>\n        {\n            "This is a long string to demonstrate that the list" + \n            " box content is determining window width"\n        };\n\n    for (int i = 0; i < 16; i++)\n    {\n        messages.Add("Test" + i);\n    }\n\n    for (int i = 0; i < 4; i++)\n    {\n        messages.Add("this text should be visible by vertical scrollbars only");\n    }\n\n    ListBox1.ItemsSource = messages;\n}	0
858349	858236	Remove column from datareader	public void MakeMyCSV(string MyFileName, SQLDataReader DataToOutput) \n{\n    MakeMyCSV(MyFileName, DataToOutput, null);\n}\n\npublic void MakeMyCSV(string MyFileName, SQLDataReader DataToOutput, int[] ExcludedColumns) //if this is your current method signature...\n{\n    //iterate through each record\n    //    iterate through each column\n    //        if ExcludedColumns is not null then see if this column is in it\n    //            if it is not in it, output it\n}	0
30155674	30155549	Change control colour, and change it back to original	private void button1_Click(object sender, EventArgs e)\n{\n    button1.BackColor = Color.Azure;\n    var aTimer = new System.Timers.Timer(2000);\n    aTimer.Elapsed += OnTimedEvent;\n    aTimer.Enabled = true;\n}\n\nprivate  void OnTimedEvent(Object source, ElapsedEventArgs e)\n{\n    button1.BackColor =  SystemColors.Control;\n}	0
27650438	27650364	If string.Contains two numbers + "x" + one number then	var list = new List<string>();\n\nlist.Add("Lost 04x01");\nlist.Add("Lost 04x02");\nlist.Add("Lost 4x3");\nlist.Add("Lost 4x04");\nlist.Add("Lost S04E05");\nlist.Add("Lost S04E6");\n\nRegex regex = new Regex(@"S?\d{1,2}[X|E]?\d{1,2}", RegexOptions.IgnoreCase);\n\nforeach (string file in list) {\n    if (regex.IsMatch(file))\n    {\n        // true\n    }\n}	0
12114883	12114842	Html Agility Pack Load method issue	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\nusing (var wc = new WebClient())\n{\n    doc.LoadHtml(wc.DownloadString(TextBoxUrl.Text));\n}	0
25817559	25817492	Reading text only in parentheses c#	var matches = Regex.Matches(File.ReadAllText(filename), @"\( T\d+ .+?\)")\n              .Cast<Match>()\n              .Select(m => m.Value)\n              .ToList();	0
13993811	13993700	Passing method as parameter to function	nodes.Sort(new Comparison<TreeNode>(sortMethod));	0
18589613	18589430	SqlCommand - Select multiple rows and INSERT them into table	string sqcom = "INSERT INTO zajsluz(akce,text,castka,rocnik) SELECT rocnik,text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='" + klientClass.Rocnik() + "'"\n\n    SqlCommand sc = new SqlCommand(sqcom,spojeni);\n\n                        spojeni.Open();\n                        sc.ExecuteNonQuery();\n                        spojeni.Close();	0
6890312	6890217	How do I get every combination of strings in a set order using recursion?	private List<string> GetStringCombinations(List<List<string>> collection)\n{\nList<string> ls = new List<string>();\n\n// if the collection is empty, return null to stop the recursion\nif (!collection.Any())\n{\n    return null;\n}\n// recurse down the list, selecting one letter each time\nelse\n{\n    foreach (var letter in collection.First())\n    {\n        // get the collection sans the first item\n        var nextCollection = collection.Skip(1).ToList();\n\n        // construct the strings using yield return and recursion\n        foreach (var tail in GetStringCombinations(nextCollection))\n        {\n            ls.add(letter + tail);\n        }\n    }\n}\nreturn ls;	0
6723793	6723761	Create a class proxy within a castle windsor facility	container.Register(\n   Component.For<SomeClass,ISomeInterface>().Lifestyle.Whatever.Interceptors<SomeInterceptor>()\n);	0
8218963	8218739	C# Loop through and set all fields in a struct	object a = new Speakers(); // required boxing, otherwise you cannot change a struct\nPropertyInfo[] info = a.GetType().GetProperties();\nfor (int i = 0; i < info.Length; i++)\n{                \n    info[i].SetValue(a, false, null);\n}	0
22196861	22196434	How to force a new empty EF Migration?	public override void Up(){\n    var dirBase = AppDomain.CurrentDomain.BaseDirectory.Replace(@"\bin",string.Empty) + @"\Migrations\SqlScripts";\n    Sql(File.ReadAllText(dirBase + @"\CreateMyViews.sql"));\n    Sql(File.ReadAllText(dirBase + @"\CreateMySproc.sql"));\n}\n\npublic override void Down(){\n        var dirBase = AppDomain.CurrentDomain.BaseDirectory.Replace(@"\bin",string.Empty) + @"\Migrations\SqlScripts";\n    Sql(File.ReadAllText(dirBase + @"\DropMySproc.sql"));\n    Sql(File.ReadAllText(dirBase + @"\DropMyViews.sql"));\n}	0
4768647	4768643	how to measure the page time load?	var watch = Stopwatch.StartNew();\n// Run your code here\nwatch.Stop();\nlong milliseconds = watch.ElapsedMilliseconds;	0
34076176	34075907	Sort and Match List Item	public void UpdateEndValues(List<TypeLogSettingsCellItem> list)\n {\n    int highestEndValue = list.Max (x => x.End);\n\n    for(int i = 0; i < list.Count -1; i++)\n    {\n        list[i].End = list[i+1].Start;\n    }\n\n    list.Last.End = (list.Last.Start > highestEndValue) ? list.Last.Start : highestEndValue;\n}	0
19733453	19733286	Insert SQL Statement into SQL Server column	using (SqlCommand com = new SqlCommand("INSERT INTO SqlUpdateInsertHistory(Statement, AffectedRows) VALUES (@Statement, @AffectedRows)", con))\n{\n    com.Parameters.AddWithValue("@Statement", statement);\n    com.Parameters.AddWithValue("@AffectedRows", rows);\n\n    com.ExecuteNonQuery();\n}	0
27368518	27368404	Building a table from string C#	for (char c = '1'; c <= '7'; c++) {\n  if (breakfastDays.Contains(c)) {\n    sb.Append("<td class=\"active\">&nbsp;</td>");\n    switch (c) {\n      case '1': mo++; break;\n      case '2': tu++; break;\n      case '3': we++; break;\n      case '4': th++; break;\n      case '5': fr++; break;\n      case '6': sa++; break;\n      case '7': su++; break;\n    }\n  } else {\n    sb.Append("<td>&nbsp;</td>");\n  }\n}	0
29892614	29891963	How to open Windows Settings Pages from code in C#?	Process.Start("ncpa.cpl");\nProcess.Start("explorer.exe", @"shell:::{BB06C0E4-D293-4f75-8A90-CB05B6477EEE}");	0
29461403	29460991	Retrieve Image to a picturebox from access database	void loadpicture()\n            {\n\n\n                OleDbCommand command = new OleDbCommand();\n                command.Connection = connection;\n                command.CommandText = "select pic from EmployeeInfo where FirstName = '" + listBox1.Text + "'";\n                OleDbDataAdapter da = new OleDbDataAdapter(command);\n                DataSet ds = new DataSet();\n                da.Fill(ds);\n                byte[] content = (byte[])ds.Tables[0].Rows[0].ItemArray[0];\n                MemoryStream stream = new MemoryStream(content);\n                pb1.Image = Image.FromStream(stream);\n\n            }	0
22971323	22970726	Error while reading XML in a dictionary	XDocument xdoc = XDocument.Load(path);    \nvar apiMap = xdoc.Root.Elements()\n                 .Select(a => new\n                     {\n                         ApiName = (string)a.Attribute("apiName"),\n                         ApiMessage = (string)a.Attribute("apiMessage")\n                     });\nvar duplicateKeys = (from x in apiMap\n                     group x by x.ApiName into g\n                     select new { ApiName = g.Key, Cnt = g.Count() })\n                     .Where(x => x.Cnt > 1)\n                     .Select(x => x.ApiName);\nif (duplicateKeys.Count() > 0)\n    throw new InvalidOperationException("The following keys are present more than once: " \n            + string.Join(", ", duplicateKeys));\n\nDictionary<string, string> apiMapDict = \n    apiMap.ToDictionary(a => a.ApiName, a => a.ApiMessage);	0
7208108	7208032	make List items readonly	private List<Status> m_Log = new List<Status>();\n\npublic ReadOnlyCollection<Status> Log {\n    get {\n        return m_Log.AsReadOnly();\n    }\n}	0
11955553	11955304	asp net web api custom filter and http verb	public override void OnActionExecuting(HttpActionContext actionContext)\n{\n    string methodType = actionContext.Request.Method.Method;\n    if (methodType.ToUpper().Equals("POST") \n            || methodType.ToUpper().Equals("PUT"))\n    {\n         // Your errors\n    }\n}	0
3422001	3421979	how to order asc/dsc with lambda or linq	Enumerable.OrderByDescending	0
29132362	29132284	Find the intersection of two lists using multiple search terms	var User = UserBatch1.FirstOfDefault(i => i.department == "finance" && i.jobtitle = "admin");	0
11188231	11187865	Onclick event on a link (<a>)	int counter = 1;\nforeach (Node node in this._nodes)\n{\n    LinkButton lnkPost = new LinkButton();\n    lnkPost.ID = "lnk" + i.ToString();\n    lnkPost.Text = node.Title;\n    lnkPost.Click += new EventHandler(LinkPost_OnClick);\n\n    parent.Controls.Add(lnkPost);\n}\n\nprotected void LinkPost_OnClick(object sender, EventArgs e)\n{\n    //add your handler code here\n}	0
8696914	8696894	how to get default network connection name used via C#?	// Get the default adapter\nstring defaultAdapter = Registry.GetValue(@"HKEY_CURRENT_USER\RemoteAccess", "InternetProfile", "") as string;\n\nforeach (RasConnection connection in RasConnection.GetActiveConnections())\n{\n    if (connection.EntryName.Equals(defaultAdapter, StringComparison.InvariantCultureIgnoreCase))\n    {\n        if (connection.GetConnectionStatus().ConnectionState == RasConnectionState.Connected)\n        {\n             // Do something\n        }\n    }\n    // Done searching\n    break;\n}	0
26458669	26458331	Programmically Create Columns in DataGridiew in-between other columns	private void AddColumnsProgrammatically()\n{\n    // I created these columns at function scope but if you want to access \n    // easily from other parts of your class, just move them to class scope.\n    // E.g. Declare them outside of the function...\n    var col3 = new DataGridViewTextBoxColumn();\n    var col4 = new DataGridViewCheckBoxColumn();\n\n    col3.HeaderText = "Column3";\n    col3.Name = "Column3";\n\n    col4.HeaderText = "Column4";\n    col4.Name = "Column4";\n\n    // dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});\n    dataGridView1.Columns.Insert(1, col3);\n    dataGridView1.Columns.Insert(2, col4);	0
25331336	25331039	Xml Array Deserialization to C# object without top level arrayElement	public class Head{\n     public String Name {get;set;}\n\n     public Config Config {get;set;}       \n\n  }\n\n  public class Config\n  {       \n      [XmlElement(ElementName="Section")]\n      public Section[] Sections { get; set; }\n  }\n\n  public class Section\n  {\n      [XmlAttribute(AttributeName="name")]\n      public String Name { get; set; }\n\n  }	0
7830207	7830050	Jagged array of 2d arrays	Magazine[][,] myMags = new Magazine[5][,];\n    myMags[0] = new Magazine[14, 14];\n    myMags[1] = new Magazine[14, 14];\n    myMags[2] = new Magazine[14, 14];\n    myMags[3] = new Magazine[14, 14];\n    myMags[4] = new Magazine[14, 14];	0
1521086	1521052	How to get the last object in a generic list?	List<BuildNumber> projBuildNos = tcRepository.GetProjectBuildNos().ToList();\nBuildList = new SelectList(projBuildNos, "ID", "value", projBuildNos.Last().ID);	0
20248345	20246515	Converting List of base to derived class	var ds = GetData(...);\nif(ds.Any()){\n    var m = typeof(Queryable).GetMethod("Cast",BindingFlags.Static | BindingFlags.Public, null,new[] { typeof(IQueryable<Base>) }, null).MakeGenericMethod(ds.First().GetType());\n    var r = m.Invoke(ds, new[] {ds});\n}	0
24411802	24410398	Calling methods with different parameters	Dictionary<string, Delegate> _callbacks = new Dictionary<string, Delegate>();\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        _callbacks.Add("move", new Action<Point, Point>(Move));\n        _callbacks.Add("remove", new Action(Remove));\n\n        Application.Current.Dispatcher.BeginInvoke(_callbacks["move"], new Point(5, 6), new Point(1, 3));\n        Application.Current.Dispatcher.BeginInvoke(_callbacks["remove"]);\n    }\n\n    public void Move(Point something1, Point something2)\n    {\n    }\n\n    public void Remove()\n    {\n    }	0
2676986	2676961	Returning a collection of objects from a webmethod	[WebMethod]\npublic object[] GetObjects()\n{\n   ...\n   return new object[] { objA, objB, objC };\n}	0
4950288	4949532	Custom MediaElement	Dictrionary <string, MediaElement>	0
1327863	1327853	Can you add attributes to a GridView in code behind?	GridView1.OnRowDataBound += gridView_OnRowDataBound;	0
1007224	1007184	how to mark folders for deletion C#	///\n/// Consts defined in WINBASE.H\n///\ninternal enum MoveFileFlags\n{\n    MOVEFILE_REPLACE_EXISTING = 1,\n    MOVEFILE_COPY_ALLOWED = 2,\n    MOVEFILE_DELAY_UNTIL_REBOOT = 4,\n    MOVEFILE_WRITE_THROUGH  = 8\n}\n\n\n/// <summary>\n/// Marks the file for deletion during next system reboot\n/// </summary>\n/// <param name="lpExistingFileName">The current name of the file or directory on the local computer.</param>\n/// <param name="lpNewFileName">The new name of the file or directory on the local computer.</param>\n/// <param name="dwFlags">MoveFileFlags</param>\n/// <returns>bool</returns>\n/// <remarks>http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx</remarks>\n[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll",EntryPoint="MoveFileEx")]\ninternal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName,\nMoveFileFlags dwFlags);\n\n//Usage for marking the file to delete on reboot\nMoveFileEx(fileToDelete, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);	0
4260525	4260511	C# - Parsing a string to DateTime with just the hours:minutes:seconds	var timeOfDay = TimeSpan.ParseExact(a, "H:m:s", null);	0
19731646	19731604	C# add XMLNode to XMLNodeList	XmlNodeList xmlNodeList = xmlNode.SelectNodes(".");	0
14611805	14611764	C#: How to concatenate bits to create an UInt64?	long mask = 0;\n\n// For each bit that is set, given its position (0-63):\nmask |= 1 << position;	0
13259469	13259426	how to get values in GridView using C#	foreach (GridViewRow gr in GridView1.Rows)\n{\n   var cells = gr.Cells;\n   CheckBox cb = (CheckBox)gr.FindControl("chkItem");\n   if (cb.Checked)\n   {\n      string strTargetDate = cells[0].Text;\n   }\n}	0
17093437	17093368	Complete an action AFTER a process loads	Process.WaitForInputIdle()	0
7593246	7593231	How to select default button in wpf dialog?	yourButton.Focus();	0
1440137	1440121	ActionFilterAttribute - apply to actions of a specific controller type	[CustomAuthorize]\npublic class AuthorizedControllerBase : CustomControllerBase\n{\n}\n\npublic class OpenAccessControllerBase : CustomControllerBase\n{\n}\n\npublic class MyRealController : AuthorizedControllerBase \n{\n    // GET: /myrealcontroller/index\n    public ActionResult Index()\n    {\n        return View();\n    }\n}	0
15105372	15105219	Need to retrieve list for my sitemap in SharePoint 2010	static void Main(string[] args)\n    {\n        try\n        {\n            SPSite site = new SPSite("http://xxx");\n            foreach (SPWeb web in site.AllWebs)\n            {\n                Console.WriteLine(web.Title);\n                foreach (SPList list in web.Lists)\n                    Console.WriteLine("List: " + list.Title);\n            }\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex);\n        }\n        Console.WriteLine("End");\n        Console.Read();            \n    }	0
7963188	7963144	How to Find the Greatest and lowest value in listbox	var numbers = listBox1.Items.Cast<object>().Select(obj => Convert.ToInt32(obj));\nint min = numbers.Min();\nint max = numbers.Max();	0
7232624	7232526	Read and Write a String in/from Stream without Helper Classes	var data = "hello, world";\n\n        // Encode the string (I've chosen UTF8 here)\n\n        var inputBuffer = Encoding.UTF8.GetBytes(data);\n\n        using (var ms = new MemoryStream())\n        {\n            ms.Write(inputBuffer, 0, inputBuffer.Length);\n\n            // Now decode it back\n\n            MessageBox.Show(Encoding.UTF8.GetString(ms.ToArray()));\n        }	0
31436355	31436106	Entering a Username to Check another website?	string userName = HttpUtility.UrlEncode("idontexist");\nstring notFoundText = "No player found with this ingame.";\nusing (WebClient wc = new WebClient())\n{\n    if (wc.DownloadString("https://news.omertabeyond.net/userhistory/" + userName).Contains(notFoundText))\n    {\n        // doesn't exist\n    }\n    else\n    {\n        // does exist\n    }\n}	0
27579037	27579001	Filtering columns in datatable	string[] colnames = new string[] {"col1", "col2"};\nnewDatableName= OldDt.ToTable(false,colnames);	0
34227137	34227101	Retrieve a list B from a list A	var allActivities = leads.SelectMany(x=>x.Activities);	0
5527349	5527316	How to set the content of an HttpWebRequest in C#?	byte[]  buffer = ...request data as bytes\nvar webReq = (HttpWebRequest) WebRequest.Create("http://127.0.0.1/target");\n\nwebReq.Method = "REQUIRED METHOD";\nwebReq.ContentType = "REQUIRED CONTENT TYPE";\nwebReq.ContentLength = buffer.Length;\n\nvar reqStream = webReq.GetRequestStream();\nreqStream.Write(buffer, 0, buffer.Length);\nreqStream.Close();\n\nvar webResp = (HttpWebResponse) webReq.GetResponse();	0
1504547	1504451	How to implement a multi-index dictionary?	Dictionary<TKey1, KeyValuePair<TKey2, TValue>> dict1;\nDictionary<TKey2, KeyValuePair<TKey1, TValue>> dict2;	0
16820914	16748312	Call back to main thread from a Task	Task.StartNew(() =>\n{\n   // Do Something Async\n\n   Dispatcher.BeginInvoke(() =>\n   {\n      // Update Your UI Here \n   });\n});	0
4573110	4573043	Queyring container with Linq + group by?	var query = from entry in myList\n            where status.Contains(entry.Status)\n            group entry.Routes.First() // take the first item in each route\n                by new // assuming each id has a unique name\n                {\n                    entry.ItemID,\n                    entry.Name\n                }\n                into g\n            select new\n            {\n                g.Key.ItemID,\n                g.Key.Name,\n                ListOfRoutes = g.ToList() // return the grouping as list\n            };	0
4502866	4502821	How do I translate a List<string> into a SqlParameter for a Sql In statement?	string sql = "SELECT dscr FROM system_settings WHERE setting IN ({0})";\nstring[] paramArray = settingList.Select((x, i) => "@settings" + i).ToArray();\ncmd.CommandText = string.Format(sql, string.Join(",", paramArray));\n\nfor (int i = 0; i < settingList.Count; ++i)\n{\n    cmd.Parameters.Add(new SqlParameter("@settings" + i, settingList[i]));\n}	0
1527746	1527612	how to point to back of generic list c#	List<int> myList = new List<int>();\n\nfor( int i = 0; i < 5; i++ )\n{\n   myList.Add (i);\n}\n\nConsole.WriteLine (String.Format ("Last item: {0}", myList[myList.Count - 1]));	0
182924	181596	How to convert a column number (eg. 127) into an excel column (eg. AA)	private string GetExcelColumnName(int columnNumber)\n{\n    int dividend = columnNumber;\n    string columnName = String.Empty;\n    int modulo;\n\n    while (dividend > 0)\n    {\n        modulo = (dividend - 1) % 26;\n        columnName = Convert.ToChar(65 + modulo).ToString() + columnName;\n        dividend = (int)((dividend - modulo) / 26);\n    } \n\n    return columnName;\n}	0
6512858	6512645	How to use proxy with C# application	string key = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";\n        string serverName = "";//your proxy server name;\n        string port = ""; //your proxy port;\n        string proxy = serverName + ":" + port;\n\n        RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(key, true);\n        RegKey.SetValue("ProxyServer", proxy);\n        RegKey.SetValue("ProxyEnable", 1);	0
7916371	7915683	C# Change selection Font via Devexpress RichEditControl	//Gets selected text range\nDocumentRange range = richEditControl1.Document.Selection;\n//Begin selected text update\nCharacterProperties characterProperties = richEditControl1.Document.BeginUpdateCharacters(range);\n//Change font\ncharacterProperties.Italic = true;\n//End update\nrichEditControl1.Document.EndUpdateCharacters(characterProperties);	0
9203154	9174225	Databound PivotControl jumps over pivots when they come from similar objects [WP7]	Type.GetHashCode() ^ Data.GetHashCode() ^ User.GetHashCode();	0
3150794	3150753	Why is it okay for an enum to have two different names with the same numeric value?	public enum Colour\n{\n    Red=10,\n    Rouge=10,\n    Blue=11,\n    Bleu=11,\n    Green=12,\n    Vert=12,\n    Black=13,\n    Noir=13\n}	0
2092912	2092530	How do i use Activator.CreateInstance with strings?	var oType = oVal.GetType();\nif (oType == typeof(string)) return oVal as string;\nelse return Activator.CreateInstance(oType, oVal);	0
15580116	15571486	Query based on Checkboxes	string str_Checkboxes="";\nstring str_SQL = "SELECT Name, File, Action, Fantasy, Horror, Thriller, Adventure, Animation, Comedy, Crime, Documentary, Drama, Family, Games, Mystery, Romance, SciFi, War FROM tbl_Main WHERE ";\n\n//Loop through each control on the form, we are looking for checkboxes\nforeach (Control c in this.Controls)\n {\n  if(c is CheckBox)\n    {\n      if (((CheckBox)c).Checked)\n        {\n         //Bypass putting AND at the beginning of str_Checkboxes\n         if(str_Checkboxes != "")\n           str_Checkboxes+=" AND ";\n         //Checkbox text is the same as the field name in the database\n           str_Checkboxes += (((CheckBox)c).Text) + " = True";\n        }\n     }\n   }\n//build the SQL\nstr_SQL += str_Checkboxes + ";"; \n//Fill the grid\nFill_Grid(str_SQL);	0
1939884	1939869	How do I set the Alternate DNS server?	string[] s = { "127.0.0.1", "127.0.0.2" };	0
2720403	2720298	How to outperform this regex replacement?	private static string RemoveDuplicateSpaces(string text) {\n  StringBuilder b = new StringBuilder(text.Length);\n  bool space = false;\n  foreach (char c in text) {\n    if (c == ' ') {\n      if (!space) b.Append(c);\n      space = true;\n    } else {\n      b.Append(c);\n      space = false;\n    }\n  }\n  return b.ToString();\n}	0
20567842	20567669	How to work with RadioGroup in RibbonControl in WInforms Devexpress?	repositoryItemRadioGroup1.Items.AddRange(new RadioGroupItem[] \n{\n     new RadioGroupItem(1, "Item1"),\n     new RadioGroupItem(2, "Item2")\n});\n\nprivate void gridView1_BeforeLeaveRow(object sender, DevExpress.XtraGrid.Views.Base.RowAllowEventArgs e)\n{ \n    if(barEditItemRadio.EditValue==null)\n       return;//Or do whatever \n    int editValue = (int)barEditItemRadio.EditValue;\n    if(editValue ==1)//Item1 is selected \n    {\n    total = ((a + b + c) - d).ToString("n2"); \n    }\n    else if(editValue ==2)//Item2is selected \n    {\n     total = (a + b + c).ToString("n2");\n    }\n}	0
3053848	3053792	Validate SQL Server Connection	using (var connection = new SqlConnection("connectionString"))\n{\n    try\n    {\n        connection.Open();\n        Console.WriteLine("Connection Ok");\n    }\n    catch (SqlException)\n    {\n        Console.WriteLine("Connection Not Ok");\n    }\n}	0
28566072	28564201	SCROLLINFO PInvoke from WinForms C#	public RichTextBoxScrollBars ScrollBars {\n  get {\n    return this.sb;\n  }\n  set {\n    this.sb = value;\n    this.RecreateHandle();\n  }\n}\n\nprotected override void OnHandleCreated(EventArgs e) {\n  base.OnHandleCreated(e);\n  UpdateScrollBars();\n}	0
26810415	26808118	Change combobox item back color when hovering over it	if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)\n{\n    e.DrawBackground();\n    e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds);\n    Font f = cboCategory.Font;\n    e.Graphics.DrawString(cboCategory.Items[e.Index].ToString(), f, new SolidBrush(ColorTranslator.FromHtml(cat_color2[e.Index])), e.Bounds, StringFormat.GenericDefault);\n    e.DrawFocusRectangle();\n}	0
18979967	18979941	How to output a list of integers constructed from a single index from a list of lists using LINQ?	var output = Data.Select(list => list[2]).ToList();	0
21833990	21811046	Keep external disk spinning	Automatic Acoustic Management (AAM)\nAdvanced Power Management (APM)	0
8051802	8051751	How to make Mock return a new list every time the method is called using Moq	selfMock.Setup(f => f.Validate()).Returns(() => new List<Correlation>{ new Correlation() { Code = "SelfError1" }, new Correlation() { Code = "SelfError2" } });	0
6183777	6183748	How to pass a json object to a mvc controller	data: {pFrame : JSON.stringify(window.image.pinpoints)},	0
19661055	19660482	How to open mail client in asp.net by cliking image	mailto:	0
13198273	13198167	Why can't I set the property value of a class object without being in a method?	public class SomeClass\n{\n    Car car = new Car() {\n        year = 2012;\n    };\n}	0
2363741	2363306	Cancel Unloaded event in a WPF application	CustomApplicationObjectCache[CACHE_KEY_CONSTANT_STRING] = new VisualBrush(...); //Or whatever type you have	0
502204	502199	How to open a web page from my application?	System.Diagnostics.Process.Start("http://www.webpage.com");	0
11567511	11567379	Create image from file programmaticaly asp.net C#	form1.Controls.Add(image);	0
19553225	19553141	How do you initialize and add data to variable of "[][]" in C#?	OutputReportTypeReportsReport[][] reportsField = new OutputReportTypeReportsReport[100][];\nreportsField [0] = new OutputReportTypeReportsReport[1] { object1 };\nreportsField [1] = new OutputReportTypeReportsReport[2] { object2, object3 };\n...	0
12184440	12184366	Retrieving value from a select tag in asp.net from controller to view	var stopId = document.getElementById("stop").value;	0
23532404	23532153	Choose where to save a file during runtime	private void button1_Click(object sender, System.EventArgs e)\n{\n    SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n\n    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; // or just "txt files (*.txt)|*.txt" if you only want to save text files\n    saveFileDialog1.FilterIndex = 2 ;\n    saveFileDialog1.RestoreDirectory = true ;\n\n    if(saveFileDialog1.ShowDialog() == DialogResult.OK)\n    {\n        using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))\n        {\n            // Insert your code to write the stream here.\n            writer.Close();\n        }\n    }\n}	0
9733975	9733635	How to read web.config section as XML in C#?	XmlDocument doc = new XmlDocument();\ndoc.Load(Server.MapPath("~/Web.config"));	0
4217781	4217752	How can I get a unique ID for a 2d array?	int hash = 17;\nfor (int i = 0; i < 3; i++) {\n  for (int j = 0; j < 3; j++) {\n    hash = hash * 31 + array[i, j];\n  }\n}\nreturn hash;	0
14468753	14468702	Can you compare two numbers stored as strings without knowing the datatype they represent?	var max = Math.Max(Double.Parse("100.1"), Double.Parse("200"));	0
5907391	5907332	How to String.Format an Int64 into an 'obfuscated' string (for a Credit Card) C#?	string strNum = num.ToString().PadLeft(16,'0');\nfor(int i = 1; i < 12; i++) strNum[i] = '*';	0
2562426	2562411	C#: Change format Day with Leading zero In DateTime	DateTime.Now.Day.ToString("00");\nDateTime.Now.ToString("dd");	0
609928	609907	How do I specify the database isolation level to be used, at a high level?	using (var txn = new TransactionScope(\n    TransactionScopeOption.Required, \n    new TransactionOptions\n    {\n        IsolationLevel = IsolationLevel.ReadUncommitted\n    }\n))\n{\n    // Your LINQ to SQL query goes here\n}	0
12506448	12488442	Get nested table cell with HtmlAgilityPack	string value = doc.DocumentNode.SelectNodes("//table[@class='PortalGadget']/tr/td/table/tr/td")[0].InnerText;	0
2714358	2714333	How can I use Linq to create an array of dictionaries from XML?	x.Elements("course")\n .Select(c => c.Elements().ToDictionary(y => y.Name, y => y.Value))\n .ToArray();	0
31161234	31161049	How to convert nullable int to SQL Null value?	var updateCmd = "UPDATE [SomeTable] SET fieldID =" + (newFieldID == null ? "null" : Convert.ToString(newFieldID)) + " WHERE keyID = " + someKeyID;	0
3036095	3036079	foreach statement (get string values)	label1.Text += prods[0].ToString();	0
9236331	9236295	How do I get distinct rows along with the count of identical rows in Linq?	var query =\n    from t in traffic\n    group t by new { t.browser, t.browser_version, t.page_name } into g\n    select new\n    {\n        g.Key.browser,\n        g.Key.browser_version,\n        g.Key.page_name,\n        Count = g.Count()\n    }	0
5336826	5330116	How do I popup the compose / create mail dialog using web based email such as Gmail or Yahoo mail using c#	mailtoLink.href = "https://mail.google.com/mail?view=cm&tf=0" + \n                (emailTo ? ("&to=" + emailTo) : "") + \n                (emailCC ? ("&cc=" + emailCC) : "") +\n                (emailSubject ? ("&su=" + emailSubject) : "") +\n                (emailBody ? ("&body=" + emailBody) : "");	0
33694195	33673347	Finding and unchecking all MenuItems in ContextMenu created dynamically with ContextMenu.ItemTemplate	private void toggleFilterOn(object sender, RoutedEventArgs e)\n{\n  var filterItem = (sender as CheckBox);\n  var parent = filterItem.FindAncestorOfType<ContextMenu>();\n  var children = parent.FindAllChildren().Where(item => item is CheckBox);\n  foreach (CheckBox cb in children)\n  {\n      cb.IsChecked = false;\n  }  \n}	0
18281870	18281679	Update DataGrid for multiple tables	CREATE PROCEDURE MyTablesUpdate(@TrackingID int, @OrderDate datetime, @CustID int, @CustomerName varchar(250)) \nAS\nBEGIN\n     UPDATE ORDERS SET OrderDate = @OrderDate WHERE TrackingID = @TrackingID \n\n     UPDATE CUSTOMERS SET CustomerName = @CustomerName WHERE CustID = @CustID\nEND	0
24479328	24479291	how to open all text files from a directory	foreach (var file in Directory.GetFiles(MainFolder, "*.txt", SearchOption.AllDirectories))\n{\n    var text = File.ReadAllText(file);\n\n    //do processing\n    File.WriteAllText(file, text);\n}	0
16708540	16708493	how can i get list of values in LINQ	var q = db.Answers.Where(a => a.Question == "q1")\n       .SelectMany(a => a.Answers).ToList();	0
5962469	5960534	How to change the visibility of a template button in a listbox?	public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged\n{\n       ...\n    Visibility sampleProperty;\n    public Visibility SampleProperty\n    {\n        get\n        {\n            return sampleProperty;\n        }\n        set\n        {\n            sampleProperty = value;\n            // Call OnPropertyChanged whenever the property is updated\n            OnPropertyChanged("SampleProperty");\n        }\n\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n    protected void OnPropertyChanged(string name)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(name));\n        }\n  }\n}	0
18775628	18775571	C# Prefix Radio Button List Option with Alphabet Character	char letter = 'A';\n\nfor (int i = 0; i < SomeCollection.Count; i++)\n{\n    var answer = SomeCollection[i]\n    System.Web.UI.WebControls.ListItem listItem = new System.Web.UI.WebControls.ListItem();\n    listItem.Value = answer.ID.ToString();\n    listItem.Text = letter + "." + answer.AnswerText;\n    listControl.Items.Add(listItem);\n    letter++;\n}	0
25261700	25261608	Get textBlock text that is inside a datatemplate from C# (XAML)	private void buss_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n{\n    TextBlock txt = (TextBlock)sender;\n    MessageBox.Show(txt.Text);\n}	0
5471000	5470904	Doubts in MVVM pattern?	RelayCommand<T>	0
15646352	15646155	Decompiled assembly - unusual code	add { lock(this) { changed = changed + value; } }	0
21569428	21569372	how to insert a summation of 2 values in back end in sql database	string SQL = "Update Stock_Entry Set No_of_Items= No_of_Items +" + (Convert.ToDecimal(100));	0
12634889	12634833	How to populated selected columns in GridView and update from code behind?	SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name," + Label1.Text + " as Home_Profile FROM Home_Profile_Master", con);	0
7310740	7310697	Convert int to hex and then into a format of 00 00 00 00	string.Join(" ", BitConverter.GetBytes(myInt).Select(x=>x.ToString("x")).ToArray());	0
28596482	28592563	Get Device/OS version and country/language codes in a Windows Universal app	// Returns the following format: en-US\nvar tag = Windows.Globalization.Language.CurrentInputMethodLanguageTag;	0
13783080	13782664	LINQ with if statement	if (attribute > 0)\n   query = query.Where(a => a.Table2.Attribute == attribute);	0
20132748	20132003	How to send messages to Azure Service Bus over Port 80?	ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;	0
23199731	23199714	Convert an Int to a WinTextBox	Textbox1.Text=integervariable.Tostring();	0
27226338	27225822	getting a sh.exe for every background task	exec /MyApp arg1 arg2&	0
31175153	31175030	How to submit the browser type when download a web stream	Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");\n        Headers.Add("Accept-Encoding", "gzip, deflate");\n        Headers.Add("Accept-Language", "en-US,en;q=0.5");\n        Headers.Add("Cookie", "has_js=1");\n        Headers.Add("DNT", "1");\n        Headers.Add("Host", host);\n        Headers.Add("Referer", url);\n        Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");	0
1774863	283417	How do I add a ContextMenuStrip to a ToolStripButton?	public class MyTextBox : ToolStripTextBox\n{\n    ContextMenuStrip _contextMenuStrip;\n\n    public ContextMenuStrip ContextMenuStrip\n    {\n        get { return _contextMenuStrip; }\n        set { _contextMenuStrip = value; }\n    }\n\n    protected override void OnMouseDown(MouseEventArgs e)\n    {\n        if (e.Button == MouseButtons.Right)\n        {\n            if (_contextMenuStrip !=null)\n                _contextMenuStrip.Show(Parent.PointToScreen(e.Location));\n        }\n    }\n}	0
12221019	12220989	How do you pass a model from Editor for model into a controller? (using asp.net)	[HttpPost]\npublic ActionResult MyMethodName (YourModel model)\n{\n    ... some code here.\n\n}	0
21056932	21056898	How to move file to a new folder after renaming with datetime in the previous folder	string newPath = System.IO.Path.Combine(currentDir, newName)\nSystem.IO.File.Move(file.FullName, newPath);	0
10258426	10258405	Regular expression for allowing a user to enter alphanumeric characters and only one non-alphanumeric character	\w*(\W\w*)?	0
25941709	25941554	How to serialize Linq to SQL data to JSON in C#	public static string jsonData() {\n    var buffer = null;\n    using (OpsDBDataContext dc = new OpsDBDataContext()) {\n        buffer = dc.ReportSalesCounts().ToList();\n    } \n    return JsonConvert.SerializeObject(buffer);\n}	0
31873293	31854530	How I can read parameter value from controller constructor in asp.net web API 2?	protected override void Initialize(HttpControllerContext controllerContext)\n    {\n        base.Initialize(controllerContext);\n    }	0
23048556	23048531	How do I make the foreach instruction iterate in 2 places?	int i = 0;\nforeach(var file in files)\n{\n   var name = names[i++];\n   // TODO: do something with name and file\n}	0
12349615	12349498	Minimum number of bits to represent number	int v = 30000; // 32-bit word to find the log base 2 of\nint r = 0; // r will be lg(v)\n\nwhile ( (v >>= 1) != 0) // unroll for more speed...\n{\n  r++;\n}	0
3199754	3199674	Opening byte[] as a file without actually saving it as a file first	string fullPathToATempFile = System.IO.Path.GetTempFileName();\n// or\n  string tempDirPath = System.IO.Path.GetTempPath();	0
15419742	15419387	Custom PropertyDescriptor always readonly	public override Type PropertyType\n    {\n        get { return _innerPropertyDescriptor.PropertyType; }\n    }	0
978815	978790	Showing Datetime using C#	Console.WriteLine(DateTime.Now + " " + TimeZone.CurrentTimeZone.StandardName);	0
2886517	2886480	Concatenate all list content in one string in C#	List<string> list = new List<string>(); // { "This ", "is ", "your ", "string!"};\nlist.Add("This ");\nlist.Add("is ");\nlist.Add("your ");\nlist.Add("string!");\n\nstring concat = String.Join(" ", list.ToArray());	0
2471404	2471336	How can I find out if an instance is a MarshalByRef proxy?	RemotingServices.IsTransparentProxy()	0
29902123	29858713	Trying to fire/call OnLoggedIn event from Page_Load event	protected void Page_Load(object sender,EventArgs e)\n{\nstring username = usernameTextbox.Text.Trim();\n**FormsAuthentication.SetAuthCookie(username, true);**\ncallLogin();// this method where in my user authentication logic resides\n}	0
22177929	21989344	Black screen after rendering multiple video streams	VMR9NormalizedRect r1 = new VMR9NormalizedRect(0, 0, 0.5f, 1);\nVMR9NormalizedRect r2 = new VMR9NormalizedRect(0.5f, 0, 1, 1);\nhr = (HRESULT)mix.SetOutputRect(0, ref r1);\nhr = (HRESULT)mix.SetOutputRect(1, ref r2);	0
12973818	12973719	UserProfile table to delete user	dcUser.Entry<string>(userToDelete).State = System.Data.EntityState.Deleted;	0
30607606	30607435	Create List of strings from the string inputted by the user c#	char[] splitter1 = new char[] { '|' };\nchar[] splitterComma = new char[] { ',' };\npublic List<string> AdvMultiKeySearch(string key)\n{\n    List<string> strings = new List<string>();\n\n    string[] commaSplit = key.Split(splitterComma);\n    string[] leftSideSplit = commaSplit[0].Split(splitter1);\n    string[] rightSideSplit = commaSplit[1].Split(splitter1);\n\n    for (int l = 0; l < leftSideSplit.Length; l++)\n    {\n        for (int r = 0; r < rightSideSplit.Length; r++)\n        {\n            strings.Add(leftSideSplit[l] + "," + rightSideSplit[r]);\n        }\n    }\n\n    return strings;\n}	0
30080061	30079416	Decorators in Unity with many arguments	Bind<T>().To<T1>().WhenInjectedInto(typeof(T2));	0
16612706	16598877	Add Title to DataGrid	protected void DataGrid1_ItemCreated(object sender, DataGridItemEventArgs e){\n    for(int i = 0; i < e.Item.Cells.Count; i++){\n        e.Item.Cells[i].Attributes.Add("title", DataGrid1.Columns[i].HeaderText);\n    }\n}	0
15153489	15152963	How to update stock quantity in the database?	public void UpdateStock()\n{\n    foreach (var listBoxItem in listBox1.Items)\n    {\n        string result = Update(listBoxItem.ToString());\n    }\n}\n\npublic string Update(string product)\n{\n    // Create connection object\n    string rTurn = "";\n    OleDbConnection oleConn = new OleDbConnection(connString);\n    try\n    {\n        oleConn.Open();\n        string sql = "UPDATE [Product] SET [Quantity]=[Quantity] - 1 WHERE [Product Name] = @product";\n        OleDbCommand oleComm = new OleDbCommand(sql, oleConn);\n\n        oleComm.Parameters.Add("@product", OleDbType.VarChar, 50).Value = product;\n\n        oleComm.ExecuteNonQuery();\n\n        rTurn = "Stock Updated";    \n    }\n    catch (Exception ex)\n    {\n        rTurn = "Update Failed";\n    }\n    finally\n    {\n        oleConn.Close();\n    }\n    return rTurn;\n}	0
9006492	9005385	Object doesn't support this property or method: 'eof' on recordset opened from xml	set rs= RecordsetFromXMLString(node.text)	0
30207208	30206405	How to pass enum value to method through reflection	var args = new[] { "A", error };\n        parentType.GetMethod("TestMethod").Invoke(null, "A",args);\n        error = args[1];	0
21362974	21356938	GetProperties of an EF object: need to ignore "RelationshipManager"	var xml = new XElement(\n                        "array",\n                        data.Select(d =>\n                        new XElement("dict",ObjectContext.GetObjectType(d.GetType   ()).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)\n\n                                                .Select(\n                                                 p => new[] { \n                                                 new XElement("key",p.Name), \n                                                    new XElement("string", p.GetValue(d, null)) }\n                                                        )\n                                            )\n                                 ));	0
13740676	13740553	How to Handle File Directories	AppDomain.CurrentDomain.BaseDirectory	0
11133573	11133495	Can I get the Original Install Date of the Windows using C#?	public static DateTime GetWindowsInstallationDateTime(string computerName)\n{\n    Microsoft.Win32.RegistryKey key = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, computerName);\n    key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);\n    if (key != null)\n    {\n        DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0);\n        Int64 regVal = Convert.ToInt64(key.GetValue("InstallDate").ToString());\n\n        DateTime installDate = startDate.AddSeconds(regVal);\n\n        return installDate;\n    }\n\n    return DateTime.MinValue;\n}	0
13084876	13084802	How to validate if the input contains a valid .Net regular expression?	try{\n  new Regex(expression)\n}\ncatch(ArgumentException ex)\n{\n  // invalid regex\n}\n\n// valid regex	0
25417851	25417839	Store consts in a struct or a static class	abstract sealed	0
9274660	9274593	Sql query with the current date	var query = @"\nSELECT trainid, trainnum\nFROM trains \nWHERE CONVERT(varchar(10), trainstartdate, 104)=\nCONVERT(varchar(20), GetDate(), 104)\nORDER BY trainnum";	0
20818069	20772640	How to filter data for dxChart	dataSource: { \n  store: db.sonolcum3,\n  filter: ["DeviceID", "=", 123456]\n}	0
7137535	7137430	How to modify specific lines in text file using C#?	const string format = @"hh\:mm\:ss\,fff";\n        static void Main(string[] args)\n        {\n            string input = File.ReadAllText("sb.srt");\n            Regex r = new Regex(@"(\d\d):(\d\d):(\d\d),(\d\d\d)");\n            input = r.Replace(input, m=> AddTime(m));\n            File.WriteAllText("sb.srt", input);\n        }\n\n        private static string AddTime(Match m)\n        {\n            TimeSpan t = TimeSpan.ParseExact(m.Value, format, CultureInfo.InvariantCulture);\n            t += new TimeSpan(0, 1, 0);\n            return t.ToString(format);\n        }	0
34413471	34413178	Javascript send innerHTML to server ASP.NET	ValidateRequest="false"	0
7149178	7149148	Set Email Attachment name in C#	System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachmentPath);\nattachment.Name = "file.txt";  // set name here\nmsg.Attachments.Add(attachment);	0
11184151	11184107	Changing from single select to multiple select in ListBox winform C#	private void Form1_Load(object sender, EventArgs e)\n    {\n        bkmNameListBox.SelectionMode = SelectionMode.MultiExtended;\n    }\n    private void button1_Click(object sender, EventArgs e)\n    {\n\n        while (bkmNameListBox.SelectedItems.Count > 0)\n        {\n            Removedatabasefiled(bkmNameListBox.SelectedItems[0]);\n            bkmNameListBox.Items.Remove(bkmNameListBox.SelectedItems[0]);\n        }\n    }	0
9113390	9100901	Accessing main window properties from its child tabs	newFrame = new Frame();\nnewFrame.Navigate(new LoginPage(this));\nnewFrame.IsTabStop = false;\ntabItem = new TabItem();\ntabItem.Header = "Login";\ntabItem.Content = newFrame;\nwizardTabs.Items.Add(tabItem);	0
3671384	3671267	Forcing Binding Validation in WPF	Dispatcher.BeginInvoke(new Action(() => {\n          BindingExpression bx = myTextBox.GetBindingExpression(TextBox.TextProperty);\n\n          if (bx != null)\n            bx.UpdateSource();\n    }));	0
12825545	12803563	how to update items in an array/list with mongo c# driver?	var update = Update<Album>.Set(x => x.Ratings[0].Number, 10);	0
16002275	16002177	reading xml returns nothing	foreach (XmlNode file in xdoc.SelectNodes("//file"))\n        {\n            string filename = file.Attributes["name"].Value;\n\n            foreach (XmlNode folder in file.SelectNodes("./ancestor::folder"))\n            {\n                string foldername = folder.Attributes["name"].Value;\n                filename = foldername + "\\" + filename;\n            }\n            System.Diagnostics.Debug.WriteLine(filename);\n        }	0
22123210	22122618	Selecting Data Using Entity Framework based on optional search parameters	var query = (from oData in DbContext.Movies select oData);\nif (!string.IsNullOrEmpty(moviename))\n  query = query.Where(m => m.MovieName.Contains(moviename));\n...	0
5770195	5768366	LINQ to SQL: How to setup associations between two tables to populate a list of strings	void GetTags(IEnumerable<Photo> photos)\n{\nvar ids = photos.Select(p=>p.ID).ToList();\nvar tagsG = (from tag in context.GetTable<Tag>() where ids.Contains(tag.PhotoID) select new {PhotoID, Name}).GroupBy(tag=>tag.PhotoID);\nforeach(ph in photos){\nph.Tags = tagsG[ph.ID].Select(tag=>tag.Name).ToList();\n}\n}	0
9759940	9759879	DataGridCheckboxColumn with SQL Server Express	DataGridCheckBoxColumn \n        Header="New?" \n        Width="40"\n        Binding="{Binding IsNew}"	0
1014378	1014295	new keyword in method signature	public class A\n{\n   public virtual void One();\n   public void Two();\n}\n\npublic class B : A\n{\n   public override void One();\n   public new void Two();\n}\n\nB b = new B();\nA a = b as A;\n\na.One(); // Calls implementation in B\na.Two(); // Calls implementation in A\nb.One(); // Calls implementation in B\nb.Two(); // Calls implementation in B	0
34325050	34325016	IF Statement check if Control has Tag Value	List<Rectangle> MaskBlocks = new List<Rectangle>();\nforeach (StackPanel gr in FindVisualChildren<StackPanel>(Container))\nif (gr.Tag!= null && gr.Tag.ToString() == "Blur")\n{\n    System.Windows.Point tmp = gr.TransformToAncestor(this).Transform(new System.Windows.Point(0, 0));\n    MaskBlocks.Add(new System.Drawing.Rectangle(new System.Drawing.Point((int)tmp.X,(int)tmp.Y), new System.Drawing.Size((int)gr.ActualWidth, (int)gr.ActualHeight)));\n}	0
16764578	16744445	Form: emptytext - display text in empty row at the bottom of a dataGrid	private void dgvKlanten2_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {\n      int rows = ds1.Tables["Klanten"].Rows.Count;\n      //when loading\n      if (e.RowIndex == rows  - 1) {\n        dgvKlanten2.Rows[e.RowIndex+1].Cells[2].Value = "add a record here";\n        dgvKlanten2.Rows[e.RowIndex+1].Cells[2].Style.ForeColor = Color.Gray;\n      }\n\n      //when adding a new row\n      if (e.RowIndex > rows ) {\n        dgvKlanten2.Rows[rows].Cells[1].Value = getNieuwKlantNummer();\n        dgvKlanten2.Rows[e.RowIndex].Cells[2].Value = "add a record here";\n        dgvKlanten2.Rows[e.RowIndex].Cells[2].Style.ForeColor = Color.Gray;\n        dgvKlanten2.Rows[e.RowIndex-1].Cells[2].Style.ForeColor = Color.Black;\n        dgvKlanten2.Rows[e.RowIndex-1].Cells[2].Value = String.Empty;\n      }\n    }	0
32725751	32725698	Starting a task that doesn't need to be awaited on	Task.WhenAll(a, b).ContinueWith(_ => /* handle errors */);	0
12947160	12947093	Can I write to the console log to debug a web application with C#	System.Diagnostics.Debug.WriteLine(topTitle + " " + subTitle);	0
9945817	9943360	How can I generate only a single PDF	PdfReader reader = new PdfReader(InputFile);\nusing (Stream output = new FileStream(\n    OutputFile, FileMode.Create, FileAccess.Write, FileShare.None\n))\n{\n  PdfEncryptor.Encrypt(\n    reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS\n  );    \n}	0
5562431	5562098	Things to consider before move to VS2010 from VS2008 C#	[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]	0
25570388	25569827	Rotate image (byte array) in datatable	using (var memoryStream = new MemoryStream(byteArray))\n{\n    var rotateImage = Image.FromStream(memoryStream);\n    rotateImage.RotateFlip(RotateFlipType.Rotate90FlipNone);\n    rotateImage.Save(memoryStream, rotateImage.RawFormat);\n    byteArray = memoryStream.ToArray();\n}	0
5717209	5717186	How to avoid captured variables?	foreach(var category in categories)\n{\n    var catCopy = category;\n    foreach(var word in words)\n    {\n        var wordCopy = word;\n        var waitCallback = new WaitCallback(state =>\n        {\n            DoSomething(wordCopy, catCopy);\n        });\n\n        ThreadPool.QueueUserWorkItem(waitCallback);\n    }\n}	0
332444	331568	How do I add multiple namespaces to the root element with XmlDocument?	XmlDocument doc = new XmlDocument();\n\nXmlElement root = doc.CreateElement("JOBS");\nroot.SetAttribute("xmlns:JOBS", "http://www.example.com");\nroot.SetAttribute("xmlns:JOB", "http://www.example.com");\ndoc.AppendChild(root);\n\nXmlElement job = doc.CreateElement("JOB");\n\nXmlElement docInputs    = doc.CreateElement("JOB", "DOCINPUTS", "http://www.example.com");\nXmlElement docInput     = doc.CreateElement("JOB", "DOCINPUT", "http://www.example.com");\ndocInputs.AppendChild(docInput);\njob.AppendChild(docInputs);\n\nXmlElement docOutputs   = doc.CreateElement("JOB", "DOCOUTPUTS", "http://www.example.com");\nXmlElement docOutput    = doc.CreateElement("JOB", "DOCOUTPUT", "http://www.example.com");\ndocOutputs.AppendChild(docOutput);\njob.AppendChild(docOutputs);\n\ndoc.DocumentElement.AppendChild(job);	0
10783758	10783502	C# get a certain part of a string for multiple occurences in a string	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(members);\n\nvar links = doc.DocumentNode\n    .Descendants("h3")\n    .Where(h => h.Attributes["class"] != null && h.Attributes["class"].Value == "ipsType_subtitle")\n    .Select(h => h.Descendants("a").First().Attributes["href"].Value)\n    .ToArray();	0
12423303	12423207	Maximize C# Application from System Tray using Keyboard Shortcut	Hotkey hk = new Hotkey();\nhk.KeyCode = Keys.1;\nhk.Windows = true;\nhk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };\n\nif (!hk.GetCanRegister(myForm))\n{ \n    Console.WriteLine("Whoops, looks like attempts to register will fail " +\n                      "or throw an exception, show error to user"); \n}\nelse\n{ \n    hk.Register(myForm); \n}\n\n// .. later, at some point\nif (hk.Registered)\n{ \n   hk.Unregister(); \n}	0
7952346	7952253	Performance when setting a large DataSource of a DataGridView	protected BackgroundWorker _bw;\n_bw = new BackgroundWorker;\n_bw.DoWork += DoWorkMethod;\n\npublic void DoWorkMethod(object sender, DoWorkEventArgs e)\n{\n//Do work here.\n}	0
8075063	8075057	How can I return the value of a field in C# if I want to execute a function on that field?	public string SubjectText {\n    get {\n         return SubjectReference.GetSubjectText(Model.PageMeta.SubjectID);\n    }\n}	0
7992004	7991851	C# double precision issue, how to detect and handle in a safe way	if(abs(big_radius - distance_small_pos_from_center) < epsilon)	0
11993968	11993857	Read all XML child nodes of each specific node	foreach(var imovel in doc2.Root.Descendants("Imovel"))\n{\n  //Do something with the Imovel node\n  foreach(var children in imovel.Descendants())\n  {\n     //Do something with the child nodes of Imovel.\n  }\n}	0
11632865	11632699	xml serialization of double	double _mfe;\ndouble _mae;\n        public double mfe\n        {\n             get\n             {\n                return Math.Round((decimal)_mfe, 4, MidpointRounding.AwayFromZero)\n             }\n             set\n             {\n                 _mfe = value;\n             }\n        }\n\n        public double mae\n        {\n             get\n             {\n                return Math.Round((decimal)_mae, 4, MidpointRounding.AwayFromZero)\n             }\n             set\n             {\n                 _mae= value;\n             }\n        }	0
5855499	5855364	Use case of IEqualityComparer<TKey> on generic dictionary	Dictionary<Student, List<Result>>	0
677707	677321	Determine ListboxItem position in a canvas?	Point p = listboxItem.TranslatePoint(new Point(0.0,0.0),Window.GetWindow(listboxItem));	0
6809390	6809309	How to combine an array of png images like layers using C#?	Image i = new Image(...)\nGraphics g = Graphics.FromImage(i)\nfor(...)\n{\n    g.Draw(...)\n}\n\ni.Save(...)	0
7528638	7528595	C# Render color in image as transparent	myBitmap.MakeTransparent(Color.Black)	0
9258576	9160339	Implementing double click event using timer	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n\n        this.MouseHover += new EventHandler(MouseHoverEvent);\n        this.MouseLeave +=new EventHandler(MouseLeaveEvent);\n        timer1.Tick += new EventHandler(timer1_Tick);\n\n        foreach (Control item in this.Controls)\n        {\n            item.MouseHover += new EventHandler(MouseHoverEvent);\n            item.MouseLeave += new EventHandler(MouseLeaveEvent);\n        }\n\n    }\n\n    void timer1_Tick(object sender, EventArgs e)\n    {\n        timer1.Stop();\n        DoubleClickEvent();\n    }\n\n    void MouseLeaveEvent(object sender, EventArgs e)\n    {\n        timer1.Stop();\n    }\n\n    void MouseHoverEvent(object sender, EventArgs e)\n    {\n        timer1.Start();\n    }\n}	0
5125554	5125021	The input is not a valid Base-64 string as it contains a non-base 64 character?	[HttpPost]\n    [Authorize]\n    public ActionResult Create([Bind(Exclude = "DownloadFile")] Download dl, HttpPostedFileBase DownloadFile)\n    {	0
21728126	21727987	How to do background processing in MonoMac	Task.Factory.StartNew(() => {\n    for (...) \n    {\n        ...\n        // update UI\n        uiControl.BeginInvoke(() => {\n            uiControl.Text = "Updated from thread";\n        });\n    }\n});	0
6849364	6849315	How do I segment the elements iterated over in a foreach loop	int i = 0;\nforeach (var grouping in Class.Students.GroupBy(s => ++i / 20))\n    Console.WriteLine("You belong to Group " + grouping.Key.ToString());	0
23708817	23708739	C# application staying open due to processes	using(Process notePad = Process.Start("notepad.exe","")) { }\nApplication.Exit();	0
18683527	18683445	Get the value of a Label from a general item	foreach (var t in Grid1.Children)\n    {\n         if (t is Label)\n         {\n                string val = ((Label)t).Content.ToString()\n         }\n    }	0
10122214	10122086	how to pass arguments to windows services in c#?	Process.Start(@"C:\Program Files\macro.exe", String.Join(" ", args))	0
15495608	15495488	Cannot insert explicit value for identity column in table 'Student' when IDENTITY_INSERT is set to OFF	cmd.CommandText = "SET IDENTITY_INSERT Student ON;" + \n                   "insert into Student(SId,FirstName,LastName,StartDate,EndDate) " + \n                    "values(@id, @firstname, @lastname, @startdate, @enddate);" + \n                    "SET IDENTITY_INSERT Student OFF;" ;\n cmd.Parameters.AddWithValue("@id", SId);\n cmd.Parameters.AddWithValue("@firstname", FirstName);\n cmd.Parameters.AddWithValue("@lastname", LastName);\n cmd.Parameters.AddWithValue("@startdate", StartDate);\n cmd.Parameters.AddWithValue("@enddate", endDate);	0
4036552	4036008	Quartz.NET - how to detect whether a job is paused?	if (scheduler.GetTriggerState(triggerName, triggerGroup) == TriggerState.Paused)\n{\n    //paused\n}	0
22166754	22166433	How to specify file path name from text box in Ole Db connection	string fileName = NameYourFile.Text + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".csv";\nstring folderName = Application.StartupPath;  \nstring sconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +\n       folderName + ";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";\n\nOleDbCommand command = new OleDbCommand("Select * From ["+fileName+"]",connection);	0
15204989	15204830	Get Index of Line from Textbox C#	public static int GetLineIndex(this TextBox textbox, int line)\n{\n    var text = textbox.Text;\n    var thisLine = 0;\n    for (var i = 0; i < text.Length; i++)\n    {\n        if (thisLine == line)\n            return i;\n\n        if (text[i] == '\n')\n            ++thisLine;\n    }\n\n    throw new ArgumentOutOfRangeException();\n}	0
5654967	5654867	Databinding a list to a GridView. GridView can't find my property!	class MyObject\n    {\n      public string Field1 { get; set; }\n      public string Field2 { get; set; }\n    }	0
23572118	23199546	Convert Distinguished Name to Canonical Name	var de = new DirectoryEntry("CN=Murdock\, James,OU=Disabled Users,OU=GOG,DC=contoso,DC=local");\nde.RefreshCache(new string[] {"canonicalName"});	0
16609227	16608843	How to get HTTP status code from a backgroundWorker	var worker = new BackgroundWorker();\n\nworker.DoWork += (sender, args) => {\n    var request = HttpWebRequest.Create(url);\n    request.Credentials = new NetworkCredential(email, password);\n    // TODO: set proxy settings if necessary\n    try {\n        args.Result = ((HttpWebResponse)request.GetResponse()).StatusCode;\n    } catch (WebException we) {\n        args.Result = ((HttpWebResponse)we.Response).StatusCode;\n    }\n};\n\nworker.RunWorkerCompleted += (sender, e) => {\n    String msg = "";\n    var code = (HttpStatusCode)e.Result;\n    if (code == HttpStatusCode.OK)\n        msg = "Connectivity OK";\n    else if (code == HttpStatusCode.Forbidden)\n        msg = "Wrong username or password";\n    else if (code == HttpStatusCode.NotFound)\n        msg = "Wrong organisation";\n    else\n        msg = "Connectivity Error: " + code;\n    label.Text = msg;\n    log.d(msg);\n};	0
9399094	9398500	Razor Substring of Name	public static class HtmlHelpers\n{\n    public static MvcHtmlString CustomDisplayFor(this HtmlHelper<Person> htmlHelper, Expression<Func<Person, string>> expression)\n    {\n          var customBuildString = string.Empty;\n          //Make your custom implementation here\n          return MvcHtmlString.Create(customBuildString);\n    }\n}	0
13682904	13682863	Refreshing contents of an XML file dynamically	string file ="c:\\newxml.txt";\nSystem.IO.File.WriteAllText(file, ds.GetXml());	0
8996079	8995854	Code-first changing the name of bridge entity table	public class MyContext : DbContext\n{    \n     protected override void OnModelCreating(DbModelBuilder modelBuilder)\n     {\n         modelBuilder.Entity<Foo>()\n           .HasMany(e => e.Bars)\n           .WithMany(s => s.Foos)\n           .Map(l =>\n             {\n                l.ToTable("FooBar");\n                l.MapLeftKey("FooId");\n                l.MapRightKey("BarId");\n             }\n           );\n    }\n}	0
17392843	17392789	How do I update database without TryUpdateModel()	// get a fresh copy of the user model for the purposes of getting the id (there may be a simpler way to do this) \nvar rawUser = this.Bind<User>();\n// read the user from the db\nvar user = db.Users.Single(u => u.Id == rawUser.Id);\n// bind again, but using the db user as the target\nthis.BindTo(user);\n// commit (I think EF may be smart enough not to do anything if BindTo() didn't actually change anything)\ndb.SaveChanges();	0
14026020	14025300	JIT & loop optimization	double temp = Math.Sqrt(2.0);\nfor (int i = 0; i < 1000000; ++i)\n    res += temp;	0
28259495	28259436	Comparing char arrays method	text.Contains(wordInText);	0
1239408	1239360	How to Fill DataGrid By SQLQuery	dataGrid1.DataSource = ds.Tables["yourtablename"].DefaultView; //yourtablename can be set table index\n    dataGrid1.DataBind();	0
11318745	11318663	Prevent a user from deleting, moving or renaming a file	var fs = File.Open(@"C:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\nMessageBox.Show("File Locked");  // While the messagebox is up, try to open or delete the file.\n// Do your work here\nfs.Close();	0
21724094	21723697	Regex to extract date time from given string	string s = "log-bb-2014-02-12-12-06-13-diag";\nRegex r = new Regex(@"\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}");\nMatch m = r.Match(s);\nif(m.Success)\n{\n    DateTime dt = DateTime.ParseExact(m.Value, "yyyy-MM-dd-hh-mm-ss", CultureInfo.InvariantCulture);\n}	0
16144333	16144253	How to access connection string in VS2012 WPF application from app.config?	System.Configuration	0
7204927	7204246	sending null values from datetimepicker to the database	//cmd.Parameters.Add("@purchasedate", SqlDbType.DateTime).Value = Date.Text;\n   if (Date.Checked)\n        cmd.Parameters.AddWithValue("@purchasedate", Date);\n   else\n        cmd.Parameters.AddWithValue("@purchasedate", DBNull.Value);	0
21326107	21325925	How to remove span when generating HtmlGenericControls from Code Behind	HtmlGenericControl _ul = new HtmlGenericControl("ul");	0
15605500	11494976	ProgressBar resets at 60%	progressBar1.Value = e.ProgressPercentage;\n     if (e.ProgressPercentage != 0)\n      ???progressBar1.Value = e.ProgressPercentage - 1;\n     progressBar1.Value = e.ProgressPercentage;\n     if (progressBar1.Maximum == e.ProgressPercentage)\n??      ?progressBar1.Value = 0;	0
14914795	14914771	How to calculate seconds from now to exact datetime?	TimeSpan t = YourDateTime - DateTime.Now;\nt.TotalSeconds; //is what you're looking for	0
1265112	1263990	How does a user control pass focus to a control on the parent form?	private void InputsUserControl_Load(object sender, EventArgs e)\n{\n    altNameTextBox.GotFocus += new EventHandler(altNameTextBox_GotFocus);\n}\n\nvoid altNameTextBox_GotFocus(object sender, EventArgs e)\n{\n    string s = nameTextBox.Text.Trim();\n\n    if (!string.IsNullOrEmpty(s))\n    {\n        this.Parent.SelectNextControl(this, true, true, true, false);\n    }\n\n}	0
12068169	12068111	How to get the details of another file info using getter & setter methods in c#?	Assembly.GetEntryAssembly()	0
17487903	11974190	How to get subsites that a logged user has access in sharepoint 2010	ClientContext clientContext =\n new ClientContext(string.Format("http://{0}:{1}/", \n                                            server, \n                                            port)); \n\nWebCollection webs = clientContext.Web.GetSubwebsForCurrentUser(null);	0
6012011	6011983	Help with EntityQuery Loading	loadTic.Completed += (s, a) =>\n    {\n        List<int> takenSeats = new List<int>();\n        foreach (Web.Ticket ticket in  ((LoadOperation<Web.Ticket>)s).Entities.ToList())\n        {\n            takenSeats.Add((int)ticket.seatId);\n            MessageBox.Show(ticket.seatId.ToString());\n        }\n    };	0
21356335	21355992	Serialize list of complex objects to JSON	[JsonProperty]	0
17869575	17869452	deserialization with the JavaScriptSerializer is missing fields	public void myMethod()\n{\n    string myContent = @"\n        [\n            {\n                ""json_content"": {\n                    ""city"": ""city 1"", \n                    ""myAge"": 15\n                }\n            },\n            {\n                ""json_content"": {\n                    ""city"": ""city 2"", \n                    ""myAge"": 18\n                }\n            }\n        ]";\n\n    JavaScriptSerializer serializer = new JavaScriptSerializer();\n    List<wrapper> list = serializer.Deserialize<List<wrapper>>(myContent);\n}\n\npublic class wrapper\n{\n    public json_content json_content { get; set; }\n}\n\npublic class json_content\n{\n    public string city { get; set; }\n    public int myAge { get; set; }\n}	0
27187638	27187555	How to spawn enemy at random intervals?	public GameObject myObj;\n\nvoid Start () \n{\n    enemy = GameObject.Find("enemy");\n    InvokeRepeating("SpawnEnemy", 1.6F, 1F);                \n}\n\npublic void SpawnEnemy() \n{       \n\n    Vector3 position = new Vector3(Random.Range(35.0F, 40.0F), Random.Range(-4F, 2F), 0);       \n    Instantiate(myObj, position, Quaternion.identity);\n\n}	0
10316953	10310510	Copy file into install directory of metro-style-app	var fop = new FileOpenPicker();\nfop.FileTypeFilter.Add(".txt");\nStorageFile file = await fop.PickSingleFileAsync();\nif (file != null)\n    await file.CopyAsync(ApplicationData.Current.LocalFolder);	0
34431400	34427696	Send file from folder to Java .jar file as parameter/argument?	doctorProc.StartInfo.FileName = "java";\ndoctorProc.StartInfo.Arguments = "-jar unluac.jar " + fileDirectory;\nFile.Open((selectedDirectory + newFileDirectory), FileMode.Open, FileAccess.ReadWrite)));\ndoctorProc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();\ndoctorProc.StartInfo.RedirectStandardOutput = true;\ndoctorProc.StartInfo.UseShellExecute = false;\ndoctorProc.Start();\nString luaScript = doctorProc.StandardOutput.ReadToEnd();\nFile.WriteAllText(Path.Combine(finalOutputDirectory,fileName), luaScript);\ndoctorProc.WaitForExit();	0
4428192	4428151	How to round 7.97708892975923E+15?	double d = Convert.ToDouble("79.77088691596279", CultureInfo.InvariantCulture);\nConsole.WriteLine(Math.Round(d, 2));	0
22596337	22596298	I need help understanding how C# uses Virtual and also how ICollection is used when Virtual is applied	public class Shape\n{\n    public const double PI = Math.PI;\n    protected double x, y;\n    public Shape()\n    {\n    }\n    public Shape(double x, double y)\n    {\n        this.x = x;\n        this.y = y;\n    }\n\n    public virtual double Area()\n    {\n        return x * y;\n    }\n}\n\npublic class Circle : Shape\n{\n    public Circle(double r) : base(r, 0)\n    {\n    }\n\n    public override double Area()\n    {\n        return PI * x * x;\n    }\n}	0
9923714	9923608	Can I achieve a 'copy constructor' in C# that copies from a derived class?	Mapper.CreateMap<ModelMetaData , ExtendedModelMetadata>();	0
24196475	24196394	Entity Framework update based on database values?	var direct = mydbContext.Database;\nusing (var command = direct.Connection.CreateCommand())\n{\n    if (command.Connection.State != ConnectionState.Open) \n    { \n        command.Connection.Open(); \n    }\n\n    command.CommandText = query.ToString(); // Some query built with StringBuilder.\n    command.Parameters.Add(new SqlParameter("@id", someId));\n    using (var reader = command.ExecuteReader())\n    {\n        if (reader.Read()) \n        {\n            ... code here ...\n            reader.Close();\n        }\n        command.Connection.Close();\n    }\n}	0
4229806	4226348	Adding a background graphic to http handler image	TempImage.Save(context.Response.OutputStream, ImageFormat.gif);	0
7784643	7781249	Solr: How to search multiple fields	var query = Query.Field("title").Is(mytitle) || Query.Field("Description").Is(mydescription);\nvar results = solr.Query(query);	0
12350335	12350015	StringBuilder's AppendFormat Method to create Table	System.Text.StringBuilder sb = new System.Text.StringBuilder();\n\nsb.Append("<table>");\nsb.AppendFormat("<tr><td>Request Name:</td><td>{0}</td></tr>", txtBugName.Text.Trim());\nsb.AppendFormat("<tr><td>Category:</td><td>{0}</td></tr>", ddlModule.SelectedValue);\nsb.AppendFormat("<tr><td>Sub-Category:</td><td>{0}</td></tr>", ddlPage.SelectedValue);\nsb.AppendFormat("<tr><td>Description:</td><td>{0}</td></tr>", txtComments.Text.Trim());\nsb.AppendFormat("<tr><td>Email is:</td><td>{0}</td></tr>", txtemail.Text.Trim());\nsb.Append("<table>");	0
23677565	23677418	Get Version from this XML (XElement)	var result = (doc.Descendants("key")\n                 .Single(e => e.Value == "Version")\n                 .NextNode as XElement).Value;	0
1243035	1242988	Subsonic: Using SharedDbConnectionScope together with TransactionScope seems to be broken	using (TransactionScope ts = new TransactionScope())\n{\n    using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())           \n    {\n            // update here\n    }\n}	0
19774430	19753103	Node.JS Send request via web proxy	var request = require('request');\n\nrequest.get({\n    uri: 'http://whatismyipaddress.com/',\n    proxy: 'http://127.0.0.1:8118'\n}, function (err, resp, body) {\n    if (err || resp.statusCode != 200) {\n        console.log('oops! something failed.');\n    }\n    else {\n        // process body here\n    }\n});	0
7801958	7801917	How to loop through each discrete instance of a class within another instance of a different class and call a specific method	foreach (var property in MyObject.GetType().GetProperties()\n    .Select(pi => pi.GetValue(MyObject, null)))\n{\n    property.GetType().GetMethod("doStuff").Invoke(property, null);\n}	0
30844171	30727397	c# How to sort an array and put in a listbox?	int[] sortArray = new int[listBox2.Items.Count];\n        for (int i = 0; i < listBox2.Items.Count; i++)\n        {\n            sortArray[i] = Convert.ToInt16(listBox2.Items[i]);\n        }\n        int aantal = listBox2.Items.Count;\n\n        listBox2.Items.Clear();\n\n        Array.Sort(soorteerArray);\n\n\n        foreach (int value in sortArray)\n        {\n            listBox2.Items.Add(value);\n        }	0
5803713	5803571	How to Managed ALL running Threads in C# console appication?	private List<Thread> threads = new List<Thread>();\n\nprivate void ThreadFunction() {\n  // do something\n  // here before the lock\n  lock (threads) {\n    threads.Remove(Thread.CurrentThread);\n    if (thread.Count < 10) {\n      Thread t = new Thread(ThreadFunction);\n      threads.Add(t);\n      t.Start();\n    }\n  }\n}	0
26103544	26103474	C# - Comparing strings of different encodings	(int) str[0]	0
8412462	8412251	How to add multiple items so it displays data through out columns in ListView in detailed mode using a loop?	ListViewItem item;\n    SqlDataReader reader = command.ExecuteReader();\n\n    if (reader.HasRows)\n    {\n        while (reader.Read())\n        {\n            item = new ListViewItem(reader.getString(0));\n            item.SubItems.Add(reader.getString(1));\n            item.SubItems.Add(reader.getString(2));\n\n            listView1.Items.Add(item);\n        }\n    }\n\n}	0
17094015	17093669	Google doc JSON request response time?	using (var w = new WebClient())\n{\n    w.Proxy = null;\n    ...	0
8467341	8023333	HttpWebRequest Date Header Format	Request.Headers.Get("Date")	0
20488901	20486472	RDLC - display list of objects on rdlc report	public Address StudentAddress {get; set;}	0
4515615	4515550	Get all 'where' calls using ExpressionVisitor	internal class WhereFinder : ExpressionVisitor\n    {\n        private IList<MethodCallExpression> whereExpressions = new List<MethodCallExpression>();\n\n        public IList<MethodCallExpression> GetWhere(Expression expression)\n        {\n            Visit(expression); \n            return whereExpressions;\n        }\n\n        protected override Expression VisitMethodCall(MethodCallExpression expression)\n        {\n            if (expression.Method.Name == "Where")\n                whereExpressions.Add(expression);\n\n            Visit(expression.Arguments[0]);\n\n            return expression;\n        }\n    }	0
1722611	1722590	Using C# Timer to stop executing a Program	Thread.Sleep()	0
14632291	14631928	Querying XML with LINQ using attribute	List<XElement> subjects = template.Descendants("Subject")\n            .Elements("Topic")\n                .Where(elementNode => elementNode.Attribute("Code").Value == "111" && elementNode.Attribute("isDisplay").Value == "Y").ToList();	0
8237587	8237429	Entity Framework 4.1.Code first - Explicit use of foreign keys in models	var student = service.GetStudent();\nvar class = service.GetClassById(student.ClassId);	0
16550662	16549744	Reading data from a RS232 port with RFID	void SetLabel(String s)\n{\n   if (this.InvokeRequired) {\n      this.Invoke (new Action<String>(SetLabel), s);\n      return;\n   }\n\n   Label1.Text = s;\n}	0
14407829	14407762	C# split textfile into a 2 dimensional string array	File.ReadLines("myfilename.txt").Select(s=>s.Split(',')).ToArray()	0
20967834	20967678	Can ASP.Net Drop Down List Control Be Used to Navigate to Another Page in Same Site	protected override void OnInit(EventArgs)\n{\n  dropDownList.selectedIndexChanged += new EventHandler(ddlIndexChanged);\n  base.OnInit(ea);\n}\n\n//Your Page_Load Here\n\nprivate void ddlIndexChanged(object sender, EventArgs ea)\n{\n  //This is called when the index is changed, you could redirect here\n}	0
32466238	32466119	C# Get JSON value	dynamic dynObj = JsonConvert.DeserializeObject(theItems);\nforeach (var desc in dynObj.rgDescriptions)\n{\n    Console.WriteLine("{0} => {1}", desc.Name, desc.Value.name);\n}	0
10868654	10868623	Converting Print page Graphics to Bitmap C#	private void doc_PrintPage(object sender, PrintPageEventArgs ev)\n{\n    var bitmap = new Bitmap((int)graphics.ClipBounds.Width,\n                            (int)graphics.ClipBounds.Height);\n\n    using (var g = Graphics.FromImage(bitmap))\n    {\n        // Draw all the graphics using into g (into the bitmap)\n        g.DrawLine(Pens.Black, 0, 0, 100, 100);\n    }\n\n    // And maybe some control drawing if you want...?\n    this.label1.DrawToBitmap(bitmap, this.label1.Bounds);\n\n    ev.Graphics.DrawImage(bitmap, 0, 0);\n}	0
4518230	4517905	How to send the Anonymous type object to a method	void SomeMethod(dynamic d)\n{\n    Console.WriteLine(d.Client);\n    Console.WriteLine(d.GlobalList.Count);\n}	0
7682822	7682722	C# find all open Excel sheets and kill only one	string bookTitle = "test"; // The book title that you want to close.\n Process[] AllProcesses = Process.GetProcessesByName("excel");\n foreach (var process in AllProcesses)\n {\n    string tempTitle = process.MainWindowTitle.Split('-')[1].TrimStart();\n    if (bookTitle == tempTitle)\n        {\n            process.Kill();\n        }\n }	0
27603529	27603515	C# Linq, Find highest number from list using linq	var result = numbers.Max();	0
4786953	4786873	How to remove whitespace between specific characters in a string?	string s = "this - is a string   - with hyphens  -     in it";\nstring[] groups = s.Split(\n                       new[] { '-', ' ' },\n                       StringSplitOptions.RemoveEmptyEntries\n                  );\nstring t = String.Join("-", groups);	0
6183953	6183640	How to get powered list of a string in C#	string[] chars = new string[] { "a", "b", "c" };\n\nList<string> result = new List<string>();\nforeach (int i in Enumerable.Range(0, 4))\n{\n    IEnumerable<string> coll = chars;\n    foreach (int j in Enumerable.Range(0, i))\n    {\n        coll = coll.SelectMany(s => chars, (c, r) => c + r);\n    }\n    result.AddRange(coll);\n}	0
17086263	17086025	Take all elements of .Split (' ') and take last OR exclude last item	static void Main(string[] args)\n    {\n        Regex regex = new Regex(@"(?<words>[A-Za-z ]+)(?<digits>[0-9]+)");\n\n        string input = "At the gates 42";\n\n        var match = regex.Match(input);\n        var a = match.Groups["words"].Value; //At the gates \n        var b = match.Groups["digits"].Value; //42\n    }	0
32432039	31992752	How to use nested TransactionScopes against an Azure SQL Database	MultipleActiveResultSets=True;	0
23808951	23808864	How to convert string[] to int in C#	string[] x = { "1", "2", "0", ",", "1", "2", "1", ",", "1", "2", "2" };\nint[] y = string.Join(string.Empty, x)\n                .Split(',')\n                .Select(s => int.Parse(s))\n                .ToArray();	0
14081043	14080093	Subitems in Listview not showing	parent.SubItems.Add(entry)	0
23614057	23612435	Display String in a Database as a Checkbox	this.myCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("CheckState", this.Table1BindingSource, "CheckBox1", true));	0
13794196	13794118	How to extend list of objects to automatically update property based on position in list	BindingList<car> list = new BindingList<car>();\nlist.ListChanged += new ListChangedEventHandler(list_ListChanged);\n\nvoid list_ListChanged(object sender, ListChangedEventArgs e)\n        {\n            list[e.OldIndex].position = e.NewIndex;\n            for (int i = e.NewIndex; i < list.Count; i++)\n            {\n                list[i].position = i+1;\n            }\n        }	0
20198938	20198770	How do you create a ArrayOfString for a WCF web service?	arrString.AddRange(strList);	0
6388684	6388503	Change Default Printer within WPF Application	var query = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"); \nvar printers = query.Get();\nstring printerName = "Printer to set as default" ;\nforeach(ManagementObject printer in printers) \n{ \n   if (printer["name"].ToString() == printerName.ToString()) \n   { \n      printer.InvokeMethod("SetDefaultPrinter", new object[] { printerName }); \n   } \n}	0
6309903	6282536	how to access child node from node in htmlagility pack	HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]");\nforeach (HtmlAgilityPack.HtmlNode node in nodes) {\n    //Do you say you want to access to <h2>, <p> here?\n    //You can do:\n    HtmlNode h2Node = node.SelectSingleNode("./h2"); //That will get the first <h2> node\n    HtmlNode allH2Nodes= node.SelectNodes(".//h2"); //That will search in depth too\n\n    //And you can also take a look at the children, without using XPath (like in a tree):        \n    HtmlNode h2Node = node.ChildNodes["h2"];\n}	0
20091904	20068465	Application crashes after 15min, WCE 6.0 CF 3.5 Motorola MC3190	delegate void setBoolAlpha(bool alpha);\npublic void checkAlpha()\n{\n  while(true)\n  {\n    KeyPad KP = new KeyPad();\n    bool alpha = KP.AlphaMode;\n    showAlpha(alpha);\n    Thread.Sleep(500);\n    //checkAlpha();\n    }\n  }\n}	0
15775550	15672072	Installer class that receives parameters used in the 'Install' method	public override void Uninstall(System.Collections.IDictionary stateSaver)\n{\n    string userName = this.Context.Parameters["UserName"];\n    if (userName == null)\n    {\n        throw new InstallException("Missing parameter 'UserName'");\n    }\n\n    string password = this.Context.Parameters["Password"];\n    if (password == null)\n    {\n        throw new InstallException("Missing parameter 'Password'");\n    }\n\n    _process = new ServiceProcessInstaller();\n    _process.Account = ServiceAccount.User;\n    _process.Username = userName;\n    _process.Password = password;\n    _service = new ServiceInstaller();\n    _service.ServiceName = _serviceName;\n    _service.Description = "My service description";\n    _service.StartType = ServiceStartMode.Automatic;\n    Installers.Add(_process);\n    Installers.Add(_service);\n\n    base.Uninstall(stateSaver);\n}	0
8122975	8122948	How to clear elements in a List<> which are similar to each other in c#	myDistinctList = myList.Distinct();	0
18321395	18319986	Windows Phone ListPicker selectedItem without databinding	private void brewMethodSelectionChange(object sender, SelectionChangedEventArgs e)\n    {\n        var brewMethodList = sender as ListPicker;\n        if (brewMethodList.SelectedItem == manual_list)\n        {\n            brewMethod = MANUAL;\n        }\n        else\n        {\n            brewMethod = AUTO_DRIP;\n        }\n        update();\n    }	0
26379218	26379065	C# how to add 3 textboxes into 1 label	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    changeText();\n}\n\nprivate void textBox1_TextChanged(object sender, EventArgs e)\n{\n    changeText();\n}\n\nprivate void textBox2_TextChanged(object sender, EventArgs e)\n{\n    changeText();\n}\n\nprivate void changeText()\n{\n    if (comboBox1.SelectedItem.ToString() == "Man")\n        label1.Text = "Geachte heer " + textBox1.Text + " " + textBox2.Text;\n    else\n        label1.Text = "Geachte mevrouw " + textBox1.Text + " " + textBox2.Text;\n}\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    label1.Text = "";\n    comboBox1.Items.Add("Man");\n    comboBox1.Items.Add("Woman");\n    comboBox1.SelectedIndex = 0;\n}	0
5125365	5125129	How can I check the null cell value in the DataGridView?	if(!Convert.IsDBNull(dataGridView1.Rows[0].Cells[i].Value))\n{\n    if (i != 0)\n    {\n       ar[i] = dataGridView1.Rows[0].Cells[i].Value.ToString ();\n    }\n    else\n    {\n       ar[i] = dataGridView1.Rows[0].Cells[i].Value.ToString();\n    }\n}	0
17747910	17686863	SourceGrid: how to disable a single cell?	private void dataGrid1_DoubleClick(object sender, EventArgs e)\n{\n    SourceGrid.DataGrid dg = (SourceGrid.DataGrid)sender;\n    //Get the position of the clicked cell\n    int c = dg.MouseCellPosition.Column;\n    int r = dg.MouseCellPosition.Row;\n    //create a Cell context \n    SourceGrid.CellContext cc = new SourceGrid.CellContext(dg, new SourceGrid.Position(r,c));\n    //and retrieve the value to be compared with a pre-defined text\n    if (String.Compare(cc.DisplayText, "SOMETEXT") == 0)\n        this.dataGrid1.GetCell(r, c).Editor.EnableEdit = false; //Disable the editing \n    else\n        this.dataGrid1.GetCell(r, c).Editor.EnableEdit = true;  //Enable the editing\n}	0
18221480	18221418	How can I load an image on button press?	private void button1_Click(object sender, EventArgs e)\n{\n    pictureBox1.ImageLocation = "http://i.imgur.com/7ikw7ye.png";\n}	0
11262155	11261363	How do I group by sequence in LINQ?	var aggr = new List<Tuple<Int,List<String>>>();\nvar res = sequence.Aggregate(aggr, (d, x) => {\n    int i;\n    if (Int32.TryParse(x, out i)) {\n        var newDict = d.Add(new Tuple(i, new List<string>()));\n        return newDict;\n    } \n    else {\n        var newDict = d[d.Count - 1].Item2.Add(x);\n        return newDict;\n    }\n}).ToDictionary(x => x.Item1, x => x.Item2);	0
2408884	2408784	How do i validate classfields?	public class Customer\n{\n    [StringLengthValidator(20)]\n    public virtual string CustomerId { get; set;}\n}	0
16094823	16094481	Passing childs of a specific parent class, with type constraints definition, as argument	public void TestMethod<T>(SharedClass<T> obj) where T : class\n{\n    //DoSomething\n}	0
7018672	7018471	Show/Hide GridViewColumns through ContextMenu	public class MainViewModel\n{\n  public MainViewModel()\n  {\n    ColumnChecked_a = true;\n    ColumnChecked_b = true;\n    ColumnChecked_c = true;\n  }\n}	0
31887149	31886759	WebApi - How to include relative paths for included App_Data XML files?	var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/yourXmlFile.xml");	0
8143043	8142709	In Subsonic 2.1 how do I get a strongly typed object from find?	IDataReader result = Animal.Find(criteria);\nAnimalCollection coll = new AnimalCollection();\ncoll.Load(result);\nresult.Close();\n\n// do something with coll\nforeach (Animal anm in coll)\n{\n    // do something with animal object\n}	0
19221711	19221593	Accessing element of a List. C#	var student = GetStudents().FirstOrDefault(student => student.StudentId /* your student id here */>);\nif (student != null)\n{\n    var houseNumber = student.Address.HouseNumber;\n}	0
17061997	17061651	Accessing bitbucket api 403 Forbidden	request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes("username:password")));	0
32275832	32275750	nly assignment, call, increment, decrement, await, and new object expressions can be used as a statement	wksht.Cells[1, 1].Select();	0
1497511	1497414	Getting the Text from a Selected Item in a RadioButtonList in a GridView in ASP.NET	string strAnswer = String.Empty;\nforeach (ListItem item in rblAnswer.Items)\n{\n    if (item.Selected) \n    {\n         strAnswer = item.Value;\n    }\n}	0
238129	238110	Anonymous Types in a signature 	public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)\n{\n    var sortedGameList =\n        from g in Games\n        group g by g.Date;\n\n    return sortedGameList.ToList();\n}	0
34355856	34355663	How to split a string by line breaks and not lose multiple line breaks in a row?	StringSplitOptions.RemoveEmptyEntries	0
20585256	20583757	Threading and Thread Safety - How to managed data in and out of a thread	public void GenrateRandomNumbers()\n    {\n        randomNumbers=new List<int>();\n        for (int i = 0; i < numberToStore; i++)\n        {\n            randomNumbers[i] = rnd.Next(1,13);\n        }\n    }	0
1873415	1798153	Scrolling problem with a WebBrowser control contained in a Panel control	class AutoScrollPanel : Panel\n{\npublic AutoScrollPanel()\n{\nEnter += PanelNoScrollOnFocus_Enter;\nLeave += PanelNoScrollOnFocus_Leave;\n}\n\nprivate System.Drawing.Point scrollLocation;\n\nvoid PanelNoScrollOnFocus_Enter(object sender, System.EventArgs e)\n{\n// Set the scroll location back when the control regains focus.\nHorizontalScroll.Value = scrollLocation.X;\nVerticalScroll.Value = scrollLocation.Y;\n}\n\nvoid PanelNoScrollOnFocus_Leave(object sender, System.EventArgs e)\n{\n// Remember the scroll location when the control loses focus.\nscrollLocation.X = HorizontalScroll.Value;\nscrollLocation.Y = VerticalScroll.Value;\n}\n\nprotected override System.Drawing.Point ScrollToControl(Control activeControl)\n{\n// When the user clicks on the webbrowser, .NET tries to scroll to \n//  the control. Since it's the only control in the panel it will \n//  scroll up. This little hack prevents that.\nreturn DisplayRectangle.Location;\n}\n}	0
27309542	27309483	C# read file line into List and use as parameters	while (sr.Peek() >= 0)\n{\n    string line = sr.ReadLine(); // store the value in a variable\n    if (!String.IsNullOrWhiteSpace(line)) // check if not empty\n    {\n        string[] val = line.Split(','); // assuming it returns three values\n\n        // you can add extra validation here\n        // array should have 3 values\n        // otherwise it will throw invalid index exception\n        emp.Add(new Employee(val[0], val[1], Convert.ToInt32(val[2])));\n    }\n}\n\nreturn emp;	0
26605772	26602890	How to format textboxes in MDI child form in c#	private void btnFormat_Click(object sender, EventArgs e)\n    {\n        if (ActiveMdiChild != null)\n        {\n            Form testform = ActiveMdiChild;\n            Control cont = testform.ActiveControl;\n            if (cont is TextBox)\n            {\n                //((TextBox)cont).Text = "Nasir Khan";\n                FontDialog fontDialog1 = new FontDialog();\n                // Show the dialog.\n                DialogResult result = fontDialog1.ShowDialog();\n                // See if OK was pressed.\n                if (result == DialogResult.OK)\n                {\n                    // Get Font.\n                    Font font = fontDialog1.Font;\n                    ((TextBox)cont).Font = font;\n                }\n            }\n        }\n    }	0
11665433	11665324	Order of execution of static elements initializes	internal static class Resources\n{\n    public static readonly Something DefaultSomething = Factory.Create();\n\n    static Resources()\n    {\n    }\n}	0
935162	935063	How to insert a unicode character in a rich text box?	private void button_Click(object sender, RoutedEventArgs e)\n{\n    MyRtb.CaretPosition.InsertTextInRun("???");\n}	0
13844429	13844253	How to capture an app start-up in a service?	OnStart()	0
21518319	21518126	How to change TextBox's background when it got focus?	textbox1.Background = new SolidColorBrush(Colors.Cyan); //Cyan for example.	0
33261470	33261289	get Database row column value with OleDbCommand	string test;\nwhile (rowItems.Read())\n    test = rowItems[0].ToString();	0
13869152	13869092	How to select a list of the latest times per day from a list of dates	var dates = list.GroupBy(dt => dt.Date).Select(g => g.Max());	0
5497062	5497012	.Net Applications performance optimizer	1. For Profiling\n   VS Profiler\n    Jet Brains - i again vote for it\n    Red Gate\n2 For Code Optimization\n  Code Rush\n  Just Code\n  Resharper - i vote for it	0
544245	544141	How to convert a character in to equivalent System.Windows.Input.Key Enum value?	[DllImport("user32.dll")]\nstatic extern short VkKeyScan(char ch);\n\nstatic public Key ResolveKey(char charToResolve)\n{\n    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));\n}	0
25584652	25584387	What is the fastest way to get a process name from a process id in C#	private IDictionary<int, string> _map;\nprivate ManagementEventWatcher _watcher;\n\n_watcher = new ManagementEventWatcher("SELECT ProcessID, ProcessName FROM Win32_ProcessStartTrace");\n_watcher.EventArrived += ProcessStarted;            \n_watcher.Start();\n\nprivate void ProcessStarted(object sender, EventArrivedEventArgs e)\n{\n    // add proc to _map\n}	0
8393671	8393612	How to find first occurrence with LINQ	var results = collection\n               .Where(item => item.PID == 0 || item.PID == 1)\n               .GroupBy(item => item.Name)\n               .Select(g => g.OrderBy(item => item.PID).First());	0
11078643	11077390	xpath get specific child	//body/table[2]	0
11884651	11880078	How to save custom data in Orchard CMS database	// MyType is a content type having StatePart attached\n        var item = _contentManager.New("MyType");\n\n        // Setting parts is possible directly like this.\n        // NOTE that this is only possible if the part has a driver (even if it's empty)!\n        item.As<StatePart>().StateName = "California";\n\n        _contentManager.Create(item);	0
29636189	29636139	how to access input type=submit value in c# mvc controller	[AcceptVerbs(HttpVerbs.Get)]\n    public ActionResult Index(string sortOrder, string currentNameFilter, string currentNumberFilter, string nameSearchString, string numberSearchString, int? page, \n        string searchButton, string searchByNumber, bool? activeProjectsOnly = true)\n    {	0
30935778	30927278	Is there a way to call generic repository methods on an entity that was generated at run time with codeDOM?	public void Insert(object entity)\n{\n    if (entity == null)\n        throw new ArgumentNullException("entity");\n\n    if (!(entity is IBusinessEntity))\n        throw new ArgumentInvalidException("entity is not an IBusinessEntity");\n\n    object existing = Existing(entity);\n    if (existing == null)\n    {\n        _context.Set(entity.GetType()).Add(entity);\n        this._context.SaveChanges();\n    }	0
24631267	24631111	Take values from list and assign to new property	string city1 = cities[0];\nstring city2 = cities[1];\nstring city3 = cities[2];\nstring city4 = cities[3];	0
12876044	12875945	Perform File Operation On Button Click in WPF	//Inside void WriteFileCommandExecuted()\n\n System.IO.StreamReader sr = new System.IO.StreamReader("File Path");\n                textBox1.Text =  sr.ReadToEnd();\n\n        //Or if you need more control\n\n        System.IO.FileStream fs = new System.IO.FileStream(FirmwarePath, System.IO.FileMode.CreateNew);\n        System.IO.StreamReader sr = new System.IO.StreamReader(fs);\n        string textdata = sr.ReadToEnd();\n        int fileSize = (int)new System.IO.FileInfo(FirmwarePath).Length;\n\n        Byte f_buffer = new Byte();\n        f_buffer = Convert.ToByte(textdata);\n        int cnt = 0;\n\n    //The FirmwarePath is the path returned to you by your file dialog box.\n    //If you want to write the class you will need to instantiate is System.IO.StreamWriter then //invoke the "write" method	0
15544448	15530631	SQLite under ORMLite doesn't allow any action after transaction if finished	public void Can_query_after_transaction_is_committed()\n        {\n            var connection = new OrmLiteConnectionFactory(":memory:", true, SqliteDialect.Provider, true);\n            using (var db = connection.OpenDbConnection())\n            {\n                db.DropAndCreateTable<SimpleObject>();\n                using (var trans = db.OpenTransaction()) \n                {\n                   db.Insert(new SimpleObject {test = "test"});\n                   trans.Commit();\n                }\n                Assert.DoesNotThrow(()=> db.Select<SimpleObject>());\n            }\n        }	0
14220063	14219927	ConfigurationManager.Read reading from unknown source	class:      ConfigurationManager \nNamespace:  System.Configuration\nAssembly:  System.Configuration (in System.Configuration.dll)	0
15953519	15925006	Excel Date Format changes in Dataset?	public DateTime ExcelSerialDateToDT(int nSerialDate)\n{\n\nint l = nSerialDate + 68569 + 2415019;\nint n = ((4 * l) / 146097);\nl = l - ((146097 * n + 3) / 4);\nint i = ((4000 * (l + 1)) / 1461001);\nl = l - ((1461 * i) / 4) + 31;\nint j = ((80 * l) / 2447);\nint nDay = l - ((2447 * j) / 80);\nl = (j / 11);\nint nMonth = j + 2 - (12 * l);\nint nYear = 100 * (n - 49) + i + l;\n\nreturn DateTime.Parse(nMonth + "/" + nDay + "/" + nYear);\n\n }	0
3372116	3371660	C#/Java/Ruby - Hash Alogrthym for Passwords - Cross-Lang/Platform	let h = get_hash_hunction("SHA-512")\nlet k = get_key_for_user("Justice")\nlet hmac = get_hmac(h, k)\nlet test = get_bytes("utf-8", http_request_params["password"])\nfor(i in 0 .. (2^16 - 1))\n    let test = run_hmac(hmac, test)\nreturn test == get_hashed_password_for_user("Justice")	0
8466353	8466298	Using Watin to log into chase website	browser.Form(Find.ById("logonform")).Submit();	0
28692112	28672384	Find control of specific class in another application	private IntPtr FindHandle()\n {\n    while (true)\n    {\n       IntPtr handle = FindWindowEx(this.ApplicationHandle,IntPtr.Zero,"TRichEdit", null);\n       if (handle == null)\n       {\n           throw new Exception("No handle found");\n       }\n       if (handle != this.Handle_01)\n       {\n           return handle;\n       }\n    }\n }	0
20033038	20032479	How to sort a GridView by column in descending order?	using System.Linq;\n\n...\n\n/* your list of hardcoded employees */\nlist<object> listEmployees = your_list;\n\n/* Sort the list by using linq and save it as sortedEmployees\n   The Sorting is done based on the property ID */\nlist<object> sortedEmployees = listEmployees.OrderByDescending(t => t.ID);\n\n/* set the datasource of your gridview */\nGridView1.DataSource = sortedEmployees;\n\n...	0
15953323	15953237	Building a custom|progressive query in LINQ?	var db = new BookDBDataContext();\n\n var q = (from a in db.Books\n          where a.Title.Contains(txtBookTitle));\n\n if(!String.IsNullOrEmpty(txtAuthor)) \n {\n      q = q.Where(a => a.Author.Contains(txtAuthor));\n }\n\n\n if(!String.IsNullOrEmpty(txtAuthor)) \n {\n      q = q.Where(a => a.Publisher.Contains(txtPublisher));\n }\n\n var id = q.Select(a => a.ID);	0
14069736	14069694	How to serialize attribute	[XmlRoot("request")]\npublic class Request\n{\n    [XmlElement("employee")]\n    public Employee Employee { get; set; }\n}\n\n[XmlRoot("employee")]\npublic class Employee\n{\n    [XmlText]\n    public string Name { get; set; }\n\n    [XmlAttribute("id")]\n    public string EmployeeId { get; set; }\n}	0
1799186	1799064	Filling custom C# objects from data received stored procedure	SqlConnection cn = new SqlConnection("<ConnectionString>");\ncn.Open();\n\nSqlCommand Cmd = new SqlCommand("<StoredProcedureName>", cn);\nCmd.CommandType = System.Data.CommandType.StoredProcedure;\n\nSqlDataReader dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);\n\nwhile ( dr.Read() ) {\n    // populate your first object\n}\n\ndr.NextResult();\n\nwhile ( dr.Read() ) {\n    // populate your second object\n}\n\ndr.Close();	0
17088823	17088716	Keyboard hook get key combination (WPF)	var lastKey;\nvoid KListener_KeyDown(object sender, RawKeyEventArgs args)\n        {\n\n            Console.WriteLine(args.Key.ToString());\n            if (lastKey == Key.LeftCtrl && args.Key == Key.C)\n            {\n                MessageBox.Show(args.Key.ToString());\n            }\n           lastKey = args.Key;\n        }	0
24930443	24657224	ServiceStack How generate an Json response with only the Primary Key?	// Add PatientSession via POST\npublic class PatientSessionADD : IReturn<PatientSessionResponseId>\n{\n    public int PatientSessionId { get; set; }\n    public int ByPatientId { get; set; }\n    public DateTime PatientStartSessionTime { get; set; }\n    public int PatientStartSessionByUserId { get; set; }\n    public DateTime PatientEndSessionTime { get; set; }\n    public int PatientEndSessionByUserId { get; set; }\n\n}\n\npublic class PatientSessionResponseId\n{\n    public int PatientSessionId { get; set; }\n}\n\n\npublic object Post(PatientSessionADD request)\n    {\n        var p =new PatientSession()\n        {\n                ByPatientId = request.ByPatientId,\n                PatientStartSessionTime = request.PatientStartSessionTime,\n                PatientStartSessionByUserId = request.PatientStartSessionByUserId\n        };\n\n        return new PatientSessionResponseId\n        {\n            PatientSessionID = Convert.ToInt16( Db.Insert<PatientSession>(p, selectIdentity: true) )\n        };\n    }	0
4646795	4646705	How can I loop through all the open instances of a particular form?	var formsList  = Application.OpenForms.OfType<Form2>();\nlistBox.Items.AddRange(formsList.Select(f=>f.Text).ToArray());	0
31037953	31037789	EF 6 Code First From Database - Calling existing stored procdure	dbContext.Database.CommandTimeout = 3600;\nList<CarsDTO> objs = dbContext.Database.SqlQuery<CarsDTO>(\n         "spGetCars @carMakeId", new SqlParameter("carMakeId", id)\n).ToList();	0
6815545	6815492	Clear checked items from a listbox without firing itemcheck event	_checkBox.CheckedChanged -= new System.EventHandler(yourEventHandler);\n// Do Check as you want.\n_checkBox.CheckedChanged += new System.EventHandler(yourEventHandler);	0
14479474	14479251	Allow User to Re-Order DataGridViewComboBoxColumn	TaskEntryCombo.SortMode = DataGridViewColumnSortMode.Automatic	0
7289872	7289761	C# how to split text file in multi files	string baseName = current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".";\n\nStreamWriter writer = null;\ntry\n{\n    using (StreamReader inputfile = new System.IO.StreamReader(new_path))\n    {\n        int count = 0;\n        string line;\n        while ((line = inputfile.ReadLine()) != null)\n        {\n\n            if (writer == null || count > 300)\n            {\n                count = 0;\n                if (writer != null)\n                {\n                    writer.Close();\n                    writer = null;\n                }\n\n                writer = new System.IO.StreamWriter(baseName + count.ToString() + ".txt", true);\n            }\n\n            writer.WriteLine(line.ToLower());\n\n            ++count;\n        }\n    }\n}\nfinally\n{\n    if (writer != null)\n        writer.Close();\n}	0
3971783	3971512	C# How to Select an Open Application Window	using System;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Runtime.InteropServices;\n\nnamespace StackOverflow.Test\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var proc = Process.GetProcessesByName("notepad").FirstOrDefault();\n            if (proc != null && proc.MainWindowHandle != IntPtr.Zero)\n                    SetForegroundWindow(proc.MainWindowHandle);\n        }\n\n        [DllImport("user32")]\n        private static extern bool SetForegroundWindow(IntPtr hwnd);\n    }\n}	0
1759753	1759733	Are custom Winforms control auto generated designer files needed?	Dispose()	0
3706667	3706591	Is it a best practice to refactor an Interface method -- extracting a code fragment of a Interface method to create a new wrapping method?	var enumerator = peopleList.GetEnumerator();\n        while (enumerator.MoveNext())\n            Console.WriteLine(enumerator.Current.firstName); //compile error.	0
18862475	18862455	Use console in another project	System.Console	0
6941330	6941291	Is there any way to convert a Dataset to a List which can be used as a datasource for a combobox?	cbStockID.DataSource = comboBoxItems.Tables[0];\ncbStockID.DisplayMember = "{DisplayTableColumnName}"; //Displayed items in the combo box.\ncbStockID.ValueMember = "{ValueTableColumnName}"; //Value for items displayed in combo box.	0
1402246	1284156	DataGridView CurrentRow excludes new row	private void uiEntries_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    Console.WriteLine(e.RowIndex == uiEntries.NewRowIndex);\n}	0
9165326	9165290	how to keep datagridview record colors while using a buttonfield	string correctedString = row.Cells[3].Text.Replace(" ", "").ToLower();	0
14160595	14160473	Cannot store Url in session from Global.asax file	protected void Application_Error(object sender, EventArgs e)\n{\n    var exception = Server.GetLastError();\n    var httpException = exception as HttpException;\n\n    if (exception is HttpException && ((HttpException)exception).GetHttpCode() == 404) \n    {\n        Server.ClearError();\n\n        // get the url\n        var url = Request.RawUrl;\n\n        var routeData = new RouteData();\n        routeData.Values["controller"] = "Cms";\n        routeData.Values["action"] = "Cms";\n        routeData.Values["aspxerrorpath"] = url;\n\n        IController cmsController = new CmsController();\n        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);\n        cmsController.Execute(rc);\n    }\n}	0
10783180	10781801	How to get the executing SQL query from a table adapter?	var usersTableAdapter = new testDataSetTableAdapters.usersTableAdapter();\n\n\n            usersTableAdapter.Insert(4, "home", "origin", "email@host.com", "realname", "spec", 1, "username", "usernick", "whereform");\n            var cmd = usersTableAdapter.Adapter.InsertCommand;\n            var text = cmd.CommandText;\n            var sb = new StringBuilder(text);\n            foreach (SqlParameter cmdParam in cmd.Parameters)\n            {\n                if (cmdParam.Value is string)\n                    sb.Replace(cmdParam.ParameterName, string.Format("'{0}'", cmdParam.Value));\n                else\n                    sb.Replace(cmdParam.ParameterName, cmdParam.Value.ToString());\n            }\n            Console.WriteLine(sb.ToString());	0
7638586	7638432	How can I get integer and char separately in such a simple string?	string letters = Seperate( "95d",  c => Char.IsLetter( c ) );\nstring numbers = Seperate( "95d", c => Char.IsNumber( c ) );\n\nstatic string Seperate( string input, Func<char,bool> p )\n{\n    return new String( input.ToCharArray().Where( p ).ToArray() );\n}	0
7070780	7070703	Cast a dropdown list from a gridview	protected void Page_Load(object sender, EventArgs e)\n{\n    grvbillDetail.RowDataBound += grvbillDetail_RowDataBound;\n}\n\nvoid grvbillDetail_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType != DataControlRowType.DataRow)\n        return;\n    var ddl = e.Row.FindControl("ddlCalculateGrid") as DropDownList;\n    if (ddl != null)\n    {\n        ddl.DataSource = rcta.GetDataByTrueValue();\n        ddl.DataBind();\n    }\n}\n}	0
12285292	12285215	Lost some keyboard keys while working on an application	Alt + Enter	0
11457655	11456764	How to wait for WCF proxy client to be ready?	_proxy = new WCFBlackjack(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/blackjack/IWCFBlackjack"));\n\nwhile(!_proxy.State.Equals(CommunicationState.Opened)) {\n    if(!_proxy.State.Equals(CommunicationState.Opening)) {\n        try {\n            _proxy.Open();\n        } catch(EndpointNotFoundException enfe) {\n            /* ... */\n            _proxy.Abort();\n            _proxy = new WCFBlackjack(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/blackjack/IWCFBlackjack"));\n        }\n    }\n    System.Threading.Thread.Sleep(1);\n}	0
28342664	28342090	get list of opened Excel documents in C#?	//Excel Application Object\nMicrosoft.Office.Interop.Excel.Application oExcelApp;\n\nthis.Activate ( );\n\n//Get reference to Excel.Application from the ROT.\noExcelApp = ( Microsoft.Office.Interop.Excel.Application ) System.Runtime.InteropServices.Marshal.GetActiveObject ( "Excel.Application" );\n\n//Display the name of the object.\nMessageBox.Show ( oExcelApp.ActiveWorkbook.FullName );\n\n//Release the reference.\noExcelApp = null;	0
6033219	6023722	How can I dynamically replace portions of text with TextBoxes?	private void tokenize(PlaceHolder ph, string str)\n{\n    int index = str.IndexOf('@') + 1;\n\n    if (index == 0)\n    {\n        ph.Controls.Add(new Label { Text = str });\n        return;\n    }\n\n    ph.Controls.Add(new Label { Text = str.Substring(0, index - 1) });\n\n    if (Tokens.Keys.Any(k => str.Substring(index).StartsWith(k + "@")))\n    {\n        int next = str.IndexOf("@", index);\n        string key = str.Substring(index, next - index);\n\n        ph.Controls.Add(new TextBox\n        {\n            ID = "txt" + key,\n            Text = Tokens[key],\n            TextMode = TextBoxMode.MultiLine,\n            Rows = 2\n        });\n\n        index = next + 1;\n    }\n\n    tokenize(ph, str.Substring(index));\n}	0
13818337	13818054	array returned from a web service to an android text view prints anyTpe{String instead of the values only	for (int i = 0; i < intPropertyCount; i++) {\n    SoapObject responseChild = (SoapObject) response.getProperty(i);\n    for (int j = 0; j < lengthOfResponseChild; j++)\n        result[j].setText(responseChild[j].toString());\n    }\n}	0
13500256	13483087	WPF properties not working correctly in windows 8	private class ErrorHighlightAdorner : Adorner\n  {\n      public ErrorHighlightAdorner(UIElement adornedElement)\n          : base(adornedElement)\n      {\n      }\n\n      protected override void OnRender(DrawingContext drawingContext)\n      {\n          Rect sourceRect = new Rect();\n          FrameworkElement fe = AdornedElement as FrameworkElement;\n          if (fe != null)\n          {\n              sourceRect = new Rect(fe.RenderSize);\n          }\n          else\n          {\n              sourceRect = new Rect(AdornedElement.DesiredSize);\n          }\n\n          Pen renderPen = new Pen(new SolidColorBrush(Colors.Red), 2.0);\n          drawingContext.DrawRectangle(null, renderPen, sourceRect);\n      }\n  }	0
24534878	24534753	How to convert this block to for loop	foreach (Point p in Snake.Body.ToArray())	0
4466775	4466756	get files from multiple directories	tempBatchAddresses = Directory.GetFiles(@"c:\", "*.log").ToList();\n\ntempBatchAddresses.AddRange(Directory.GetFiles(@"d:\", "*.log").ToList());\n\ntempBatchAddresses.AddRange(Directory.GetFiles("some dir", "some pattern").ToList());	0
16913358	16912665	How to Find Out the Dates when Windows was Not Started	EventID Source              Description\n12      Kernel General      Operating System Start\n13      Kernel General      Operating System Shutdown\n1       Power-Troubleshooter    Operating System Woke up from Sleep\n42      Kernel-Power        Operating System going to Hibernate/Sleep	0
19509845	19228779	NHibernate JOIN to temp table	sessionFactory.OpenSession(myConnection);	0
6032318	6032032	How do I compute the non-client window size in WPF?	var titleHeight = SystemParameters.WindowCaptionHeight\n  + SystemParameters.ResizeFrameHorizontalBorderHeight;\nvar verticalBorderWidth = SystemParameters.ResizeFrameVerticalBorderWidth;	0
16328947	16328919	Getting minutes from two DateTimes on different dates	(DateTimeA - DateTimeB).TotalMinutes % 24*60	0
32079211	32078931	How to convert from datetime to store as Hex in SQL?	DECLARE \n    @Date   DateTime = getdate()\n,   @Hex    varbinary(8)\n;\n\nDECLARE @Temp TABLE ( value varbinary(8) );\n\nINSERT INTO @Temp VALUES (0x0000214900000000),(cast(@Date AS varbinary));\n\nSelect\n    value\n,   cast(value AS DateTime)\nfrom @Temp\n\nSELECT @Hex = cast(cast('2015-04-01' AS DateTime) AS varbinary)\n\nINSERT INTO @Temp VALUES (@Hex)\n\nSelect\n    value\n,   cast(value AS DateTime)\nfrom @Temp	0
15053479	15053461	Shifting a String in C#	public static string ShiftString(string t)\n{\n    return t.Substring(1, t.Length - 1) + t.Substring(0, 1); \n}	0
18077483	18076771	Compare screenshot image with last one, use only if changed	if (bsize != ms.Length)\n                        {\n                            bsize = ms.Length;\n                            writer.Write((int)ms.Length);\n                            writer.Write(ms.GetBuffer(), 0, (int)ms.Length);\n                        }	0
5813530	5813464	LINQ orderby on date field in descending order	var ud = env.Select(d => new \n                         {\n                             d.ReportDate.Year,\n                             d.ReportDate.Month,\n                             FormattedDate = d.ReportDate.ToString("yyyy-MMM")\n                         })\n            .Distinct()\n            .OrderByDescending(d => d.Year)\n            .ThenByDescending(d => d.Month)\n            .Select(d => d.FormattedDate);	0
13386205	13385356	Mongodb in a portable C# app	//starting the mongod server (when app starts)\nProcessStartInfo start = new ProcessStartInfo();     \nstart.FileName = dir + @"\mongod.exe";\nstart.WindowStyle = ProcessWindowStyle.Hidden;\n\nstart.Arguments = "--dbpath d:\test\mongodb\data";\n\nProcess mongod = Process.Start(start);\n\n//stopping the mongod server (when app is closing)\nmongod.Kill();	0
2838412	2838398	how to convert an instance of an anonymous type to a NameValueCollection	var foo = new { A = 1, B = 2 };\n\nNameValueCollection formFields = new NameValueCollection();\n\nfoo.GetType().GetProperties()\n    .ToList()\n    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));	0
15705263	15705033	Allow User Input To Determine SQL Server Connection String	string ConnectionString;\n    switch (comboBox1.SelectedIndex)\n    {\n        case 0:\n            ConnectionString = "Data Source=server1;Initial Catalog=database1;User ID=user1;Password=password1";\n            break;\n        case 1:\n            ConnectionString = "Data Source=server2;Initial Catalog=database2;User ID=user1;Password=password2";\n            break;\n        case 3:\n            ConnectionString = "Data Source=server3;Initial Catalog=database3;User ID=user1;Password=password3";\n            break;\n    }\n    SqlConnection Con = new SqlConnection(ConnectionString);\n    Con.Open();	0
6357820	6357720	Lambda expression help	db.KUNDs.Where(k => !db.KundInfos.Any(ki => k.KUNDNR == ki.KundID.ToString()))\n        .OrderBy(k => k.KUNDNR);	0
4983094	4982554	How to parse dictionary<string,string> in c#	var keyToLookUp = "SomeText";\n        string value;\n\n        if (dictionary.ContainsKey(keyToLookUp))\n        {\n            value = dictionary[keyToLookUp];\n        }\n        else\n        {\n            //Handle key not found here.\n        }	0
29800405	29798908	How to Change transparency of button image in Unity 5.0?	using UnityEngine;\n            using System.Collections;\n            using UnityEngine.UI;\n\n            public class SetTransparancy : MonoBehaviour {\n                public Button myButton;\n                // Use this for initialization\n                void Start () {\n                    myButton.image.color = new Color(255f,0f,0f,.5f);\n                }\n\n                // Update is called once per frame\n                void Update () {\n\n                }\n            }	0
13593646	13593377	Looking for a HttpUtility.ParseQueryString alternative	WwwFormUrlDecoder.GetFirstValueByName()	0
28309923	28309764	C# Move item in Listbox to the top	ListItem myItem=new ListItem("ALL","value");\nmyListbox.Items.Insert(0, myItem);	0
3590263	3589110	WCF 4 Rest Getting IP of Request?	OperationContext context = OperationContext.Current;\nMessageProperties messageProperties = context.IncomingMessageProperties;\nRemoteEndpointMessageProperty endpointProperty =\n  messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;	0
7542990	7542920	Calling methods side by side in a table	public void BuildNumbers()\n    {\n\n        while (decimal1 <= topLimit)\n        {\n            string binary = Convert.ToString(decimal1, 2);\n            string dec = Convert.ToString(decimal1);\n            string oct = Convert.ToString(decimal1, 8);\n            string hex = Convert.ToString(decimal1, 16);\n            Console.Write(binary);\n            Console.Write('\t');\n            Console.Write(dec);\n            Console.Write('\t');\n            Console.Write(oct);\n            Console.Write('\t');\n            Console.Write(hex);\n            Console.WriteLine();\n            decimal1++;\n        }\n    }	0
17403692	17403544	Exclude rows starting from certain characters using Linq	where a.name.StartsWith("x")	0
4079174	4079135	Splitting a string with uppercase	string output = "";\n\nforeach (char letter in str)\n{\n   if (Char.IsUpper(letter) && output.Length > 0)\n     output += " " + letter;\n   else\n     output += letter;\n}	0
5790066	5539255	Dynamic TabItems c# Wpf	private void PopulateTabControl()\n    {\n        DataView = (CollectionViewSource)(this.Resources["DataView"]);\n        AddGrouping();            \n        tabcontrol.DataContext = DataView;            \n    }\n\n    private void AddGrouping()\n    {\n        PropertyGroupDescription grouping = new PropertyGroupDescription();\n        grouping.PropertyName = "categoryID";\n        DataView.GroupDescriptions.Add(grouping);\n    }	0
774873	774375	Using a resource image in code behind	buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Images/InchDOWN.png")));	0
14279858	14168009	Using PHP to display a SQL table for usage on C# program	for(int x = 0;x < ArrayList.Size();x++)\n{\n      String[] Details = x.Split(new char[] { '-' });\n      Lists.items.add(Details[0].trim());\n}	0
3572386	3572364	Binding Date of DateTime in a control	Text="{Binding Path=PostData.Data, StringFormat={}{0:MM/dd/yyyy}}"	0
11873813	11873760	Compile Time Conversion of uint to int in C#	[Flags]\npublic enum Example\n{\n    Foo = 0x00000001,\n    Bar = unchecked((int)0xC0000000);\n}	0
7401459	7401262	Calculate Random color with method parameters	protected static string RandomColor(int metaDataId, int operationId, int dataType)\n{\n    var names = (KnownColor[])Enum.GetValues(typeof(KnownColor));\n\n    metaDataId = Math.Abs(metaDataId);\n    operationId = Math.Abs(operationId);\n    dataType = Math.Abs(dataType);\n\n    // compute a hash of the 3 values modulo the number of colors\n    unchecked\n    {\n        var index = (17 + metaDataId * 23 + operationId * 23 + dataType * 23) % names.Length;\n    }\n\n    Color color;\n    while (true)\n    {\n        var colorName = names[index];\n        color = Color.FromKnownColor(randomColorName);\n        var brightness = randomColor.GetBrightness();\n        if (brightness < 0.7 && brightness > 0.2)\n        {\n            break;\n        }\n        ++index;\n    }\n    return ColorTranslator.ToHtml(color);\n}	0
30535604	30523704	Invoke Windows 8 Maps application from WPF application	System.Diagnostics.Process.Start("bingmaps:?rtp=adr.Paris~adr.London&sty=a&trfc=1");	0
136625	136615	How can I test a connection to a server with C# given the server's IP address?	IPAddress IP = new IPAddress();\nif(IP.TryParse("127.0.0.1",out IP)){\n    Socket s = new Socket(AddressFamily.InterNetwork,\n    SocketType.Stream,\n    ProtocolType.Tcp);\n\n    try{   \n        s.Connect(IPs[0], port);\n    }\n    catch(Exception ex){\n        // something went wrong\n    }\n}	0
4975407	4975377	Encrypt connection string in NON ASP.Net applications	private void ProtectSection(String sSectionName)\n{\n    // Open the app.config file.\n    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n    // Get the section in the file.\n    ConfigurationSection section = config.GetSection(sSectionName);\n    // If the section exists and the section is not readonly, then protect the section.\n    if (section != null)\n    {\n    if (!section.IsReadOnly())\n        {\n        // Protect the section.\n            section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");\n            section.SectionInformation.ForceSave = true;\n            // Save the change.\n            config.Save(ConfigurationSaveMode.Modified);\n         }\n     }\n}	0
18635530	18635496	How can I correct a NullReferenceException in the following code?	oTracking.Projects = new List<ProjectInfo>()	0
7552762	7552651	Multidimensional Binding in WPF ListView	myList.DataSource = myListOfMyItemList.SelectMany(i=>i.Items);	0
3897823	3897565	ContextMenuStrip renders at top left Windows	private void listView1_MouseClick(object sender, MouseEventArgs e) {\n        if (allowContextMenu(listView1.SelectedItems) {\n            contextMenuStrip1.Show(listView1, e.Location);\n        }\n    }	0
20966182	20966122	Specifying item list contents in EF with 2 condtions	var conditionarr = new []{"cake","bread","toast","drink"}; // your array or list of string\nCartItem Item = Items.Find(c => c.ProductID == ProductID \n && conditionarr.Contains(c.ProductName));	0
6185561	6185508	Confused with Model vs ViewModel	public ActionResult CustomerInfo(int customerId)\n{\n   // Fetch the customer from the Repository.\n   var customer = _repository.FindById(customerId);\n\n   // Map domain to ViewModel.\n   var model = Mapper.Map<Customer,CustomerViewModel>(customer);\n\n   // Return strongly-typed view.\n   return View(model);\n}	0
5055766	5055730	How to pass parameters in windows service from Installer to Main function in Program.cs?	OnStart(string[] args)	0
1730615	1730464	Replacing hyphens in querystring via Regular Expression	string newstring = yourstring.Replace("-", " ").Replace("   ", " - ").Replace("  ", " -");	0
29490215	29488158	Replace data/value of csv file	public void CountMacNames(String macName)\n{\n    string path = @"D:\Counter\macNameCounter.csv";\n\n    // Read all lines, but only if file exists\n    string[] lines = new string[0];\n    if (File.Exists(path))\n        lines = File.ReadAllLines(path);\n\n    // This is the new CSV file\n    StringBuilder newLines = new StringBuilder();\n    bool macAdded = false;\n\n    foreach (var line in lines)\n    {\n        string[] parts = line.Split(',');\n        if (parts.Length == 2 && parts[0].Equals(macName))\n        {\n            int newCounter = Convert.ToIn32(parts[1])++;\n            newLines.AppendLine(String.Format("{0},{1}", macName, newCounter));\n            macAdded = true;\n        }\n        else\n        {\n            newLines.AppendLine(line.Trim());\n        }\n    }\n\n    if (!macAdded)\n    {\n        newLines.AppendLine(String.Format("{0},{1}", macName, 1));\n    }\n\n    File.WriteAllText(path, newLines.ToString());\n}	0
4187240	4187209	.NET XML Output Loses Line Breaks	xmlDoc.PreserveWhitespace = true;	0
16425390	16425102	Finding a value from within a List of Dictionary objects	var dict = Foo.FirstOrDefault(d => d.ContainsKey(key));\nif (dict != null) { dict.TryGetValue(key, out name); }	0
5866858	5866770	Get the application standard resource manager	ResourceManager rm = new ResourceManager("rmc",Assembly.GetCallingAssembly());	0
4846579	4846532	I want my C# winforms program to copy it self to system32	string localPath = Application.StartupPath;\nEnvironment.SetEnvironmentVariable("EXAMPLE", localPath);	0
4855841	4855714	Restructuring Suggestions to remove lots of generic constraints	interface INode {}\nclass Node: INode {}\n\ninterface IVisit\nclass Visit: IVisit\n{\n    Visit(INode node) {}\n}\n\ninterface ISolution {}\nclass Solution: ISolution\n{\n   Solution(IList<IRoute> routes)\n   {\n   }\n}	0
19596387	19596386	Using a custom value for HttpMethod	new HttpMethod("MYMETHOD");	0
28584652	28578982	AppFabric Caching with Azure SQL as configuration storage	// Microsoft.ApplicationServer.Caching.Configuration.ConfigurationBase\n...\nif (provider.Equals("System.Data.SqlClient"))\n{\n    ConfigurationBase.ValidateSqlConnectionString(connectionString);\n}\n...\ninternal static void ValidateSqlConnectionString(string connectionString)\n{\n    SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);\n    if (!sqlConnectionStringBuilder.IntegratedSecurity || !string.IsNullOrEmpty(sqlConnectionStringBuilder.UserID) || !string.IsNullOrEmpty(sqlConnectionStringBuilder.Password))\n    {\n        int errorCode = 17032;\n        string sqlAuthenticationNotSupported = Resources.SqlAuthenticationNotSupported;\n        throw new DataCacheException("DistributedCache.ConfigurationCommands", errorCode, sqlAuthenticationNotSupported);\n    }\n}	0
164932	164926	c# - How do I round a decimal value to 2 decimal places (for output on a page)	decimalVar.ToString ("#.##");	0
13429182	13429140	Linq select from two tables order by list	//your query\n ...\nfrom eventOther in Events_before_after\nselect new DataEvent ()\n{\n    eventId = eventOther.Id,\n    start = eventOther.start,\n    end = eventOther.end,\n    type = eventOther.type\n}\ninto NewEvent\norder by NewEvent.eventId\nselect NewEvent;	0
12735950	12732274	Context menu appears on the blank space as well as on the Ultra grid header when right click	private void grid_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)\n{\n    UltraGridCell currentCell = null;\n    grid.ContextMenu = null;\n\n    if (e.Button == MouseButtons.Right)\n    {\n        Point ulPoint = new Point(e.X, e.Y);\n        UIElement el = grid.DisplayLayout.UIElement.ElementFromPoint(ulPoint); \n        if (el != null)\n            currentcell = (UltraGridCell)el.GetContext(typeof(UltraGridCell)); \n        if (currentcell != null && currentCell.Row.IsDataRow == true)\n        {\n            grid.ActiveCell = currentcell;\n            grid.ContextMenu = menuPopup;\n        }\n    }\n}	0
11685161	11638399	How to serialize a collection of derived data-sets	[Serializable]\npublic class ResultsCollection : CollectionBase\n{\n  // indexer\n  public MyDataSet this[int index] { get { return (MyDataSet)List[index]; } }\n}\n[Serializable]\npublic class MyDataSet : DataSet, ISerializable\n{\n  // member variable that *overrides* the Tables property of the standard DataSet class\n  public new TablesCollection Tables;\n}\n[Serializable]\npublic class TablesCollection : CollectionBase\n{\n  // indexer\n  public MyDataTable this[int index] { get { return (MyDataTable)List[index]; } }\n}\n[Serializable]\npublic class MyDataTable : DataTable, ISerializable\n{\n  ...\n}	0
17411217	17293790	show all columns in datagridview	private void Form1_Load(object sender, EventArgs e)\n    {\n        GetICD10();\n        FreezeBand(dataGridView1.Columns[0]);   // Client requested to have ICD code column "frozen" by default\n\n        // Cannot seem to select both autosize and allow user to size in designer, so below is the "code around".\n        //  Designer has autosize set to displayedcells.\n        dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;   // Turn off autosize\n        dataGridView1.AllowUserToResizeRows = true;                                 // Turn on letting user size columns\n        dataGridView1.AllowUserToOrderColumns = true;\n\n        // Create tooltip and populate it\n        var toolTip1 = new ToolTip { AutoPopDelay = 5000, InitialDelay = 1000, ReshowDelay = 500, ShowAlways = true };\n        toolTip1.SetToolTip(tbCode, "Enter an ICD code to search for");\n        toolTip1.SetToolTip(tbDescriptionLong, "Enter a description to search for");\n\n\n    }	0
12105882	12055926	Programmatically creating an article in Dynamics CRM 2011	Entity kbarticle = new Entity("kbarticle");\n\nkbarticle["title"] = title;\nkbarticle["subjectid"] = new EntityReference(subject_LogicalName, subject_Guid);\nkbarticle["kbarticletemplateid"] = new EntityReference(template_LogicalName, template_Guid);\n\nservice.Create(kbarticle);	0
13882717	13874981	How to schedule a repeating task to count down a number in windows phone 8	public partial class MainPage : PhoneApplicationPage\n{\n    private DispatcherTimer _timer;\n    private int _countdown;\n\n    // Constructor\n    public MainPage()\n    {\n        InitializeComponent();\n\n        _countdown = 100;\n        _timer = new DispatcherTimer();\n        _timer.Interval = TimeSpan.FromSeconds(1);\n        _timer.Tick += (s, e) => Tick();\n        _timer.Start();\n    }\n\n    private void Tick()\n    {\n        _countdown--;\n\n        if (_countdown == 0)\n        {\n            _timer.Stop();\n        }\n\n        countText.Text = _countdown.ToString();\n    }\n}	0
17936228	17936073	Windows Phone 8 - Small Cycle Template Live Tile (159x159)	CycleTileData.CycleImages	0
26148472	26148171	Reading barcodes from pdf	private string DecodeText(string sFileName)\n{\n    DmtxImageDecoder decoder = new DmtxImageDecoder();\n    System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(sFileName);\n    List<string> oList = decoder.DecodeImage(oBitmap);\n\n    StringBuilder sb = new StringBuilder();\n    sb.Length = 0;\n    foreach (string s in oList)\n    {\n        sb.Append(s);\n    }\n    return sb.ToString();\n}	0
562107	561954	ASP.Net URLEncode Ampersand for use in Query String	Server.UrlEncode	0
2994962	2994774	ReSharper conventions for names of event handlers	button.Click += (sender, args) => SaveCurrentDocument();	0
13007548	12978102	Custom validation in MVC can't seem to find the declared method	[CustomValidation(typeof(InvoiceValidator), "ValidateInvoiceDate")]	0
1923463	1923445	How to specify to Regex (in a LINQ Query) to only compare the start of a string?	var regEx = new Regex("^" + filterTerm);	0
18352548	18352473	Remove whitespace near a character using regex in a long text	Regex rgx = new Regex(pattern);\nstring input = "This is   text with   far  too   much   " + \n                 "whitespace.";\nstring pattern = "\\s*!\\s*";\nstring replacement = "!";\nRegex rgx = new Regex(pattern);\nstring result = rgx.Replace(input, replacement);	0
2686385	2686328	Query decendants in XML to Linq	list = (from portfolio in xmlDoc.Descendants("item")\n            select new PortfolioItem()\n           {\n               Title = portfolio.Element("title").Value,\n               Description = portfolio.Element("description").Value,\n               Url = portfolio.Element("url").Value,\n               Photos = (From P In portfilio.Element("photos").Elements("photo")\n                   Select new Photo(P.Attribute("url").Value)\n                       {\n                           .Thumbnail = bool.Parse(P.Attribute("thumbnail").Value),\n                           .Description = P.Attribute("description").Value\n                       }).ToList()\n           }).ToList();	0
26298094	26297624	Visual C# Access item from other class file	namespace Test{\n    public partial class Form1 : Form \n    {\n    MyClass MyClassObject;\n        public Form1()\n        {\n            InitializeComponent();\n            MyClassObject=new MyClass(this);\n            MyClassObject.test("hello");\n        }   \n    }\n    }\n\nnamespace Test{\n    class MyClass\n    {\n\n       Form1 parent;\n\n       public MyClass(Form1 parentForm)\n       {\n             parent=parentForm;\n       }\n       public void test (string text) \n       {\n         parent.richtextbox1.clear();\n       }\n    }	0
27040065	25976798	Partial view in a non-web application	public class ExtendedTemplateBase<TModel> : TemplateBase<TModel>\n    {\n        public string Partial<TPartialModel>(string path, TPartialModel model)\n        {\n            var template = File.ReadAllText(path);\n            var partialViewResult = Razor.Parse(template, model);\n            return partialViewResult;           \n        }\n    }	0
17502521	17499351	Is it possible to run a .net 4.5 app on XP?	OPTIONAL HEADER VALUES\n             10B magic # (PE32)\n            ...\n            4.00 operating system version\n            0.00 image version\n            4.00 subsystem version              // <=== here!!\n               0 Win32 version\n            ...	0
1119021	1119004	C#: What style of data containers are preferred in general?	var obj = new Person {Name="Fred", DateOfBirth=DateTime.Today};	0
12857920	12836370	How to open a Template WorkBook and load its WorkSheets?	FileInfo existingFile = new FileInfo(filePath);\n\n            using (var package = new ExcelPackage(existingFile))\n            {\n                ExcelWorkbook workBook = package.Workbook;\n\n                if (workBook != null)\n                {\n                    if (workBook.Worksheets.Count > 0)\n                    {\n                        int i = 0;\n                        foreach(ExcelWorksheet worksheet in workBook.Worksheets)\n                        {\n                            xlWorkSeet1[i] = worksheet;\n                            i = i + 1;\n                        }\n\n                    }\n                }	0
27271112	27271046	Save Console contents as log.txt	myApplication.exe > log.txt	0
9429032	7876014	WPF Calendar Weekend Coloring	Figure 8	0
3197803	3197536	How to check the existence of an element in an XML file using XML to LINQ in C#	XDocument xdoc = XDocument.Load("../../Sample.xml");\n        Int32 val = (from item in xdoc.Descendants("TestElement")\n                     select (item.Attribute("Count") != null) ? Int32.Parse(item.Attribute("Count").Value) : 0).FirstOrDefault();	0
28948928	28948380	How to check if a word matches to bulk of words in text file?	string[] words = File.ReadAllLines(@"C:\Users\Rider\Documents\Visual Studio 2012\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Resources\enable3.txt");\nint index = Array.BinarySearch(words, textBox1.Text);\nif (index >= 0) {\n  MessageBox.Show("String Match, found a string in notepad file");\n}	0
32846078	32797283	Remove Escape character from object or string in c#?	var obj = new JavaScriptSerializer().Deserialize(payload,targetType:null);	0
2128074	2128067	Manually fetch values from asp.net control	TextBox myTextBox = (TextBox)MyFormView.Row.FindControl("controlID");	0
11682489	11681429	how to sort gridview based on drop down list selection	DataView dvItems = new DataView((DataTable)ds.Tables["datatable1"]);\n\n if (ddl_itemsorderby.SelectedValue == "MenuGroup")\n     dvItems.Sort = "Menu_Group, Item_Name ASC";\n else if (ddl_itemsorderby.SelectedValue == "Item")\n     dvItems.Sort = "Item_Name, Menu_Group ASC";\n else if (ddl_itemsorderby.SelectedValue == "Rate")\n     dvItems.Sort = "Item_rate, Item_Name ASC";\n else if (ddl_itemsorderby.SelectedValue == "Quantity")\n     dvItems.Sort = "Item_Quantity, Item_Name ASC";\n\n gridview1.DataSource = dvItems;\n gridview1.DataBind();	0
5489591	5489507	Calculating corresponding calendar day of previous years	var originalDate = new DateTime(2012,03,28);\nvar newDate = originalDate.AddYears(-6);\nvar daysToAdd = originalDate.DayOfWeek - newDate.DayOfWeek;\nif(daysToAdd < -3)\n    daysToAdd += 7;\nif(daysToAdd > 3)\n    daysToAdd -= 7;\nnewDate = newDate.AddDays(daysToAdd);	0
4756471	4756415	What is difference between a action with HTTPPOST or without it	[HttpPost]	0
22303964	22303836	Synchronization over objects in a dictionary	private object privateLock = new object();\n\nvoid update(){\n    lock(privateLock)\n    {\n        //change state \n    }\n}\n\nvalueclass createclone(){\n    lock(privateLock)\n    {\n        //Clone \n    }\n}	0
9324983	9178684	How to read xt: tagged fields from Atom feeds?	var XmlContainer = XElement.Load(url);\n\nXNamespace nsXt = "http://xstream.dk/";\nvar Elements = from item in XmlContainer.Descendants("item")\n               select new {\n                       Title = item.Element("title").Value,\n                       Year = item.Elements(nsXt + "details").Value,\n               };	0
11154578	11138748	NavigationService WithParam of Caliburn Micro for WP	private string _symbol;     \npublic string Symbol     \n{         \n    get { return _symbol;}         \n\n    set         \n    {             \n        _symbol = value;            \n        NotifyOfPropertyChange(() => Symbol);   \n        NotifyOfPropertyChange(() => Snapshot);        \n    }     \n}      \npublic StockSnapshot Snapshot     \n{         \n    get { return Symbol!=null? GlobalData.Current.Snapshots[Symbol]:null; }     \n}	0
25353636	25353589	How to remove a control from window programmatically?	mybutton.Visibility = Visibility.Collapsed;	0
32099437	32099015	How to inner join(filtering for nested properties) with expression tree?	var dutExpression = Expression.Property(psuExpression, "DUT");\nvar referenceCodeExp = = Expression.Property(dutExpression, "ReferenceCode ");\nvar constExpr = Expression.Constant("HKR566");\nvar eqExp = Expression.Equal(referenceCodeExp , constExpr);\ndutsExpression = Expression.Or(dutsExpression, eqExp);	0
8936198	8936148	Passing values from CLR Trigger to WCF	cmd = new SqlCommand(@"SELECT * FROM INSERTED", conn);	0
19110209	19109787	Passing a variable to a method at runtime	private async void pushpin_Tapped(object sender, TappedRoutedEventArgs e)\n{\n    MessageDialog myMessage = new MessageDialog(((Pushpin)sender).Name);\n    await myMessage.ShowAsync();\n}	0
23527899	23527408	Need some with a regular expression for C# returning one or more multiple matches	\{Value(OR\[(.*)\])?:(.*)\}	0
18766374	18766333	What is the scope of a friend assembly statement?	assembly:	0
30505679	30502720	Combine IdentityDbContext and TrackerContext	TrackerEnabledDbContext.Identity	0
11143019	11140090	Add help button, but keep maximize and minimize	private void Help_Click(object sender, EventArgs e) {\n        Help.Capture = false;\n        SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_CONTEXTHELP, IntPtr.Zero);\n    }\n\n    private const int WM_SYSCOMMAND = 0x112;\n    private const int SC_CONTEXTHELP = 0xf180;\n    [System.Runtime.InteropServices.DllImport("user32.dll")]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);	0
13179714	13179645	DateTime difference	double differenceInMilliseconds = (b - a).TotalMilliseconds;	0
22713701	22713192	How to programmatically add a double-click event to a WPF DataGrid Row?	myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick);	0
3680492	3680387	Excluding the GroupBoxes that are inside another GroupBox	void soSomething(Control ctrl)\n{\n    if (ctrl is GroupBox && (ctrl.Parent is null || !(ctrl.Parent is GroupBox)))\n    {\n         //do something here\n    }\n    foreach(Control child in ctrl.Controls)\n    {\n        doSomething(child);\n    }\n}	0
10055859	10055847	Input string was not in the correct format	string.Format("http://localhost:8000/Service/AddTagtoGroup/{0}/{1}", \n                textBox6.Text, textBox7.Text);	0
13052884	13052403	How duplicate entries be prevented while using SqlBulkCopy?	CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY	0
13843130	13843042	Starting Explorer with UNC Path Argument That Contains Comma Fails To Open Folder	public void OpenWindowsExplorer(string path) {\n    path = string.Format("\"{0}\"", path);\n    var runExplorer = new ProcessStartInfo { FileName = "explorer.exe",\n                                             Arguments = path };\n    Process.Start(runExplorer);\n}	0
2122634	2122511	Simple way to convert datarow array to datatable	foreach (DataRow row in rowArray) {\n   dataTable.ImportRow(row);\n}	0
1334860	1334695	SharePoint: How to add an attachment to a list item programatically?	foreach (FileInfo attachment in attachments)\n        {\n            FileStream fs = new FileStream(attachment.FullName , FileMode.Open,FileAccess.Read);\n\n            // Create a byte array of file stream length\n            byte[] ImageData = new byte[fs.Length];\n\n            //Read block of bytes from stream into the byte array\n            fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));\n\n            //Close the File Stream\n            fs.Close();\n\n            item.Attachments.Add(attachment.Name, ImageData); \n\n\n        }	0
17790814	17763060	PreviewMouseDownEvent of Listbox blocking Command from Button	style.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, \n  new MouseButtonEventHandler(Input_Down)));\n\nprivate void Input_Down(object sender, RoutedEventArgs e)\n{\n    if (EventTriggeredByButtonWithCommand(e))\n        return;\n\n    var draggedItem = sender as FrameworkElement;\n\n    if(draggedItem !=null)\n        StartDrag(draggedItem);\n\n}\nbool EventTriggeredByButtonWithCommand(RoutedEventArgs e)\n{\n    var frameWorkElement = e.OriginalSource as FrameworkElement;\n\n    if (frameWorkElement == null) \n        return false;\n\n    var button = frameWorkElement.TemplatedParent as Button;\n\n    if (button == null) \n        return false;\n\n    return button.Command != null;\n}	0
6084478	6084398	Pick a Random Brush	private Brush PickBrush()\n    {\n        Brush result = Brushes.Transparent;\n\n        Random rnd = new Random();\n\n        Type brushesType = typeof(Brushes);\n\n        PropertyInfo[] properties = brushesType.GetProperties();\n\n        int random = rnd.Next(properties.Length);\n        result = (Brush)properties[random].GetValue(null, null);\n\n        return result;\n    }	0
15576952	15576757	How to return LINQ query to View Model	stores.Stores.Where(o=>o.CompanyID==curCompany.ID).ToList()	0
4384085	4383896	How do I make the Console window show when a program is running in non-debug mode?	Console.ReadLine();	0
264849	264817	Variable number of results from a function	dbParams[MEMBER_CODE]\ndbParams[PASSWORD]\ndbParams[USERNAME]\ndbParams[REASON_CODE]	0
6861340	6860081	How to use StringComparison for strings in C#?	if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))	0
5700314	5700090	Programatically assging network service access rights to folder using c#	DirectoryInfo dirInfo = new DirectoryInfo("C:\\TestDir2");\nDirectorySecurity dirSecurity = dirInfo.GetAccessControl();\n\ndirSecurity.AddAccessRule(new FileSystemAccessRule("ASPNET", FileSystemRights.Write|FileSystemRights.DeleteSubdirectoriesAndFiles, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));\n\ndirInfo.SetAccessControl(dirSecurity);	0
18124772	18099624	Control.PointToScreen on Windows Phone	var control = this;    // assign the control you want to get the position of.\nvar transform = control.TransformToVisual(Application.Current.RootVisual);\nvar controlPosition = transform.Transform(new Point(0, 0));	0
27217774	27214549	Linq2sql update each row in a huge table	ObjectTrackingEnabled = false	0
23780037	23779824	C# adding to list of tuples with a function	public class Album\n{\n    public string Name {get;set;}\n    public string Artist {get; set;}\n    public Album(string _name, string _artist)\n    {\n         Name = _name;\n         Artist = _artist;\n    }\n}\n\n\nAlbum example = new Album("a", "good idea");\n\nList<Album> listOfAlbums = new List<Album>();\nlistOfAlbums.Add(example);	0
32254239	32252524	How to modify Custom XML parts in Excel 2010/2013	IEnumerator e = workbook.CustomXMLParts.GetEnumerator();\nCustomXMLPart p;\nwhile (e.MoveNext())\n{\n    p = (CustomXMLPart) e.Current;\n    //p.BuiltIn will be true for internal buildin excel parts \n    if (p != null && !p.BuiltIn && p.NamespaceURI == NS.NamespaceName)\n        p.Delete();\n}	0
8173941	8171980	RegularExpression validating format (ABC_123)	Regex match = new Regex(@"^[a-zA-Z]{3}_[0-9]{3}$");	0
18199057	18198785	Handling DATETIME and DATE for Start and End dates	public string AvailableToday\n{\n    get\n    {\n        if (NonAvailibility != null)\n        {\n            var i = NonAvailibility.FirstOrDefault(t => DateTime.UtcNow.Date <= t.EndDate && DateTime.UtcNow.Date >= t.StartDate);\n            if (i != null) return i.NonAvailibilityType ;\n            return "";\n        }\n        return "";\n    }\n}	0
17198027	17184517	Bind IsSelected Property of ListBoxItem in ListBox with Multiple selection mode	public class MyListBox : ListBox\n{\n    protected override void PrepareContainerForItemOverride(\n        DependencyObject element, object item)\n    {\n        base.PrepareContainerForItemOverride(element, item);\n\n        if (item is Item)\n        {\n            var binding = new Binding\n            {\n                Source = item,\n                Path = new PropertyPath("IsSelected"),\n                Mode = BindingMode.TwoWay\n            };\n\n            ((ListBoxItem)element).SetBinding(ListBoxItem.IsSelectedProperty, binding);\n        }\n    }\n}	0
1648231	1648221	Deleting whole sections of my XML file	XmlDocument doc = new XmlDocument();\ndoc.Load("yourXmlFile.xml");\n\nXmlNode userNo3 = doc.SelectSingleNode("//Users/User[@ID='3']");\n\nif(userNo3 != null)\n{\n   userNo3.ParentNode.RemoveChild(userNo3);\n}\n\ndoc.Save("YourNewXmlFile.xml");	0
33848214	33847983	how can i delay UI update until after calculations are finished?	private void main_Load(object sender, EventArgs e)\n{\n    main_tabcontrol.SelectedIndex = 0; \n    loadData();\n    doSomeCalculations();\n    main_tabcontrol.SelectedIndex = 2; \n}	0
21022906	21022470	Generate MB of random data in C#	string text128Enc = text128.Replace("+", "%2b").Replace("/", "%2f").Replace("=", "%3d");	0
1425175	1424088	Formview Insert Mode	if (!Page.IsPostBack)\n    {\n        if (FormView1.DataItemCount == 0)\n        {\n            FormView1.ChangeMode(FormViewMode.Insert);\n        }\n    }	0
3914651	3914599	Raising an exception when trying to see if a item is selected in a listbox	SelectedIndex == -1	0
4254696	4254636	How to Create a Custom Event Handling class Like EventArgs	public class MyEventArgs : EventArgs\n{\n    private string m_Data;\n    public MyEventArgs(string _myData)\n    {\n        m_Data = _myData;\n    } // eo ctor\n\n    public string Data {get{return m_Data} }\n} // eo class MyEventArgs\n\n\npublic delegate void MyEventDelegate(MyEventArgs _args);\n\npublic class MySource\n{\n    public void SomeFunction(string _data)\n    {\n        // raise event\n        if(OnMyEvent != null) // might not have handlers!\n            OnMyEvent(new MyEventArgs(_data));\n    } // eo SomeFunction\n    public event MyEventDelegate OnMyEvent;\n} // eo class mySource	0
19378464	19351400	How can I open the Facebook App for sharing a link on WP8?	// Open official Facebook app for sharing\nawait Windows.System.Launcher.LaunchUriAsync(new Uri("fb:post?text=foo"));	0
1889173	1889144	c# listbox search algorithm	if(yourString.Contains(<the textbox text>)	0
16944890	16944751	Iterate through a database's tables using datagridview	USE your_database\nSELECT name FROM sys.tables	0
24440877	24440824	How should I correctly dispose of an object?	private static void ReadOrderData(string connectionString)\n{\n    string queryString = \n        "SELECT OrderID, CustomerID FROM dbo.Orders;";\n    using (SqlConnection connection = new SqlConnection(\n               connectionString))\n    {\n        SqlCommand command = new SqlCommand(\n            queryString, connection);\n        connection.Open();\n        SqlDataReader reader = command.ExecuteReader();\n        try\n        {\n            while (reader.Read())\n            {\n                Console.WriteLine(String.Format("{0}, {1}",\n                    reader[0], reader[1]));\n            }\n        }\n        finally\n        {\n            // Always call Close when done reading.\n            reader.Close();\n        }\n    }\n}	0
3205241	3205213	Setting Timeouts?	bool FlagSuccess = false;\nDateTime timeout = DateTime.UtcNow.AddSeconds(5);\nwhile (FlagSuccess == false && DateTime.UtcNow < timeout)\n{\n    try\n    {\n    //Blah blah blah\n    FlagSuccess=true;\n    }\n    catch\n    {\n    }\n}	0
1268430	1268394	How to mock just a method?	fooMock =  MockRepository.GenerateStub<IFoo>();\nfooMock.Stub(x => x.Method1()).Return("Whatever");	0
2006639	2005777	Inheriting from a User Control to use a different child Control	interface IGrid {...}\nclass Grid : IGrid { ...}\nclass EditableGrid : IGrid { ... }\n\nabstract class AbstractGridMasterControl\n{\n    protected IGrid Grid\n    {\n        set { this.panelControl.Controls.Add(value as Control);}\n    }\n}\n\nclass GridMasterConrol : AbstractGridMasterControl\n{\n    public GridMasterControl()\n    {\n        this.Grid = new Grid();\n    }\n}\n\nclass EditableGridMasterConrol : AbstractGridMasterControl\n{\n    public GridMasterControl()\n    {\n        this.Grid = new EditableGrid();\n    }\n}	0
11110016	11032701	WPF TabItem Style - Redraw tab after changing header text	TabItem.Style = null;\nTabItem .Style = (Style)FindResource("Tabitem112");	0
4646291	4615367	C# Finding a socket ID?	socket()	0
7722043	7715747	Word Interop Delete results in Wrong Parameter	Dim rng As Range\nDim doc As Document\nSet doc = ActiveDocument\nSet rng = doc.Bookmarks("BM").Range\n\nDim s As Long, e As Long\nrng.Select\ns = Application.Selection.Start\ne = Application.Selection.Next(wdLine, 1).End\n\nApplication.Selection.SetRange s, e\nApplication.Selection.Delete	0
31981571	31961883	Compare stored procedure returned dates with console application current date	static void Main()\n    {\n        DateTime currentDate = DateTime.Now.Date;            \n\n        //Mock dataTable is used instead of stored procedure resultset\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Date", typeof(DateTime));\n        dt.Rows.Add("2015-08-11");\n        dt.Rows.Add("2015-08-13");\n\n        string xmlFile = "hours.xml";            \n\n        var isDateFound = from row in dt.AsEnumerable()\n                          where row.Field<DateTime>("Date") == currentDate\n                          select row;\n        if (isDateFound.Count() > 0)\n        {\n            XmlDocument doc = new XmlDocument();\n            doc.Load(xmlFile);\n            var node = doc.DocumentElement.SelectSingleNode("TotalHours");\n            node.InnerText = (Convert.ToInt32(node.InnerText) + 8).ToString();\n            doc.Save(xmlFile);\n        }         \n\n    }	0
2660394	2660375	WinForms: How to prevent textbox from handling alt key and losing focus?	private void textBox1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.Alt)\n    {\n        e.Handled = true;\n    }\n}	0
2431076	2431061	optional search parameters in sql query and rows with null values	coalesce(firstName, '') like '%{firstname}%'	0
11313381	11313106	Populate rich Text box without openFile Dialog C#	const string Myfile = @"c:\test\myfile.rtf";\n\nrichTextBox1.Loadfile(Myfile);	0
1945453	1945440	dropdownlist fill at pageload and save to db	if (!IsPostBack)\n    {\n        //fill your dropdownlist here\n\n    }	0
15562041	15559051	Web Api Custom Action Selector without Attribute	var config = new HttpSelfHostConfiguration(baseAddress);\nconfig.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector());	0
11538530	11537714	Create a generic list from multiple different lists	public static List<T> o<T>(List<T> a)\n        {\n             return a = new List<T>();\n        }	0
25327664	24891365	Attached Properties via Model Item	var canvasLeftIdentifier = new Microsoft.Windows.Design.Metadata.PropertyIdentifier(typeof(System.Windows.Controls.Canvas), "Left");\nmyModelItem.Properties[canvasLeftIdentifier].SetValue(newValue);	0
29560470	29544648	Get last N elements for each group	public IList<ApplicationSession> GetLastNGroupedSessions(int count)\n  {\n\n     var sqlQuery = string.Format(@";with ranking as\n     (\n     select *, row_number() over (partition by session_type_id order by start_ts desc) as rn\n     from application_sessions\n     )\n     select app.application_session_id,\n        app.session_type_id,\n        app.start_ts,\n        app.end_ts,\n        app.is_successful \n     from ranking as app\n     where rn <= {0}", count);\n\n     return _session.CreateSQLQuery(sqlQuery)\n        .AddEntity("app", typeof(ApplicationSession))\n        .List<ApplicationSession>();\n  }	0
3720538	3720349	silverlight grid background image	ImageBrush img = new ImageBrush();\nimg.ImageSource = (ImageSource)new ImageSourceConverter().ConvertFromString("Image.jpg");\nSystem.Windows.Controls.Grid g = new System.Windows.Controls.Grid();\ng.Background = img;	0
92982	92841	Is there a .NET function to validate a class name?	System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)	0
2446761	2446728	how to tell in code if we are running from a testmethod .net test	Environment.SetEnvironmentVariable	0
34511698	26465483	How to check Microsoft Security Essential running in background?	Process[] processlist = Process.GetProcessesByName("msseces");;\nforeach(Process theprocess in processlist){\n   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);\n}	0
9333573	9333209	Getting image out of a C# 2D jagged array	byte[] pdf = image[0];	0
16271814	16144900	the file you are trying to open is in a different format than specified by the file extension in Asp.Net	public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)\n{\n    XLWorkbook wb = new XLWorkbook();\n    var ws = wb.Worksheets.Add(sheetName);\n    ws.Cell(2, 1).InsertTable(data);\n    HttpContext.Current.Response.Clear();\n    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";\n    HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx",sheetName.Replace(" ","_")));\n\n    using (MemoryStream memoryStream = new MemoryStream())\n    {\n        wb.SaveAs(memoryStream);\n        memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);\n        memoryStream.Close();\n    }\n\n    HttpContext.Current.Response.End();\n}	0
20103704	20103261	Sorting array of structs on multiple elements in c#	Array.Sort(MyArray.Item, (a, b) =>\n    {\n        var comparison = a.Y.CompareTo(b.Y);\n        return comparison == 0 ? a.X.CompareTo(b.X) : comparison;\n    });	0
8408868	8408654	After upgrading my web app from .Net 3.5 to .Net4.0, I get a security transparency rules failed	private void Application_Start(HttpApplication application) \n{ \n    if (applicationStartupComplete) return; \n    try \n    { \n        object osm = new System.Web.UI.ScriptManager(); \n    } \n    catch(Exception)\n    {}\n}	0
30694369	30694103	Log in through active directory	System.Security.Principal.WindowsIdentity WI =  System.Security.Principal.WindowsIdentity.GetCurrent();\n        string sUserName = WI.Name;\n        bool bAuthorized = false;\n        string allowedGroup = "Admins";\n        IdentityReferenceCollection irc = WI.Groups;\n        foreach (IdentityReference ir in irc)\n        {\n            if(ir.Translate(typeof(NTAccount)).Value == allowedGroup)\n            {\n                bAuthorized = true;\n                break;\n            }\n        }\n        if(string.IsNullOrEmpty(sUserName))\n        {\n            MessageBox.Show("Your Name in domain doesn't exist");\n        }\n        if(bAuthorized == false)\n        {\n            MessageBox.Show("You don't have permissions to log in");\n        }\n        else\n        {\n            MessageBox.Show("Hello");\n        }	0
21491763	21468825	How to filter OpenSURF invalid matches using RANSAC in C#	var correlationPoints1 = matches[0];\nvar correlationPoints2 = matches[1];\nvar ransac = new RansacHomographyEstimator(0.10, 0.99);\nvar homography = ransac.Estimate(correlationPoints1, correlationPoints2);\nvar inliers1 = correlationPoints1.Submatrix(ransac.Inliers);\nvar inliers2 = correlationPoints2.Submatrix(ransac.Inliers);\nvar result = new IntPoint[][]\n                    {\n                        inliers1,\n                        inliers2\n                    };	0
13675506	13675449	String.Format certain argument	string foo = String.Format("{0} is {1} when {2}", "{0}", "cray", "{2}");	0
17561158	17561107	Hide some controls in MDI parent if a child being re-sized	//Form parent\npublic frmMenu()\n        {\n            InitializeComponent();\n            pnlHide = panel1;\n        }\n\npublic static Panel pnlHide= new Panel();\n\n\n//Form Child\nprivate void frmChiled_Resize(object sender, EventArgs e)\n        {\n            if (WindowState == FormWindowState.Maximized)\n            {\n                frmMenu.pnlHide.Hide();\n            }\n            else\n            {\n                frmMenu.pnlHide.Show();\n            }\n        }	0
8224336	8224282	How to modify by loading and saving the same xml file	web.config	0
640452	640404	.Net & C#: Trying to have a transparent image on a button (assigned from IDE)	Bitmap b = Properties.Resources.MyImage;\nb.MakeTransparent(b.GetPixel(0, 0));	0
20944965	20944683	call a method through string dynamically	typeof(UIMap).GetProperty("FirstName").GetValue(this.UIMap)	0
19963767	19963738	How to make list contents appear side by side in textbox	textBox1.Text = "Seq".PadRight(10) +  "MaxLen";\n\n        for (int i = 0; i < Math.Max(MaxLen.Count, SeqIrregularities.Count); i++)\n        {\n            textBox1.Text += Environment.NewLine;\n            string text = String.Empty;\n            if (i < MaxLen.Count)\n            {\n                text = MaxLen[i].ToString();\n            }\n            text = text.PadRight(10);\n            if (i < SeqIrregularities.Count)\n            {\n                text += SeqIrregularities[i];\n            }\n            textBox1.Text += text;\n        }	0
24640305	24639750	Proper way of using Newtonsoft Json ItemConverterType	string json = @"{str1:""abc"",list:""[1,2,3]"", str2:""def""}";\nvar temp = JsonConvert.DeserializeObject<Temp>(json);\n\npublic class Temp\n{\n    public string str1;\n    [JsonConverter(typeof(StringConverter<List<int>>))]\n    public List<int> list;\n    public string str2;\n}\n\npublic class StringConverter<T> : JsonConverter\n{\n    public override bool CanConvert(Type objectType)\n    {\n        throw new NotImplementedException();\n    }\n\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        return JsonConvert.DeserializeObject<T>((string)reader.Value);\n    }\n\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        throw new NotImplementedException();\n    }\n}	0
20121084	20120534	Removing white space added by CreateTextNode after Removechildnode	public static void RemoveEmptyElementsAndWhiteSpaces(this XDocument document)\n    {\n        if(null == document)\n            throw new ArgumentNullException("document");\n\n        document.Descendants()\n            .Where(e => e.IsEmpty || string.IsNullOrWhiteSpace(e.Value))\n            .Remove();\n    }	0
1488450	1488400	How to generate download file name?	Response.AddHeader("Content-Disposition", "attachment;filename=image1.jpg");\nResponse.ContentType = "image/jpeg";\nResponse.WriteFile(pathToFileOnYourServer);	0
8990006	8989859	How can I map an IP Address to an eight character long string?	void Main()\n{\n    var addr = IPAddress.Parse("192.80.24.200");\n    var str = IPAddressToString(addr);\n    Console.WriteLine(str);\n}\n\npublic string IPAddressToString(IPAddress address)\n{\n    var result = new StringBuilder(8);\n    foreach(var b in address.GetAddressBytes())\n    {\n        result.AppendFormat("{0:x2}", b);\n    }\n    return result.ToString();\n}	0
24452916	24452847	Getter/setter for two way encrypted property in a model	[WhateverYourDataLayerNeeds("Property")]\npublic string EncryptedProperty {get;set;}\n\npublic string DecryptedProperty\n{\n    get { return DecryptString(EncryptedProperty); }\n    set { EncryptedProperty = EncryptString(value); }\n}	0
21340625	21340516	Extract 2 int value inside a string C#?	while (buffer != null)\n{\n    var words = buffer.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);\n    int.TryParse(words[0], out matSong[0, i]);\n    int.TryParse(words[1], out matSong[1, i]);\n    buffer = fp.ReadLine();\n    i++;\n}	0
21890087	21890003	Split string base on the last N numbers of delimiters	var parts = s1.Split(new[] { " \\ " }, StringSplitOptions.None);\nvar partsCount = parts.Count();\nvar result = new[] { string.Join(" ", parts.Take(partsCount - 2)) }.Concat(parts.Skip(partsCount - 2));	0
31367261	31367057	Start app at a specific page whenever app is suspended WP 8.1	Window.Current.Activated += (sender, eventArgs) =>\n{\n     var rootFrame = Window.Current.Content as Frame;\n\n     if (rootFrame.BackStack.Count > 0)\n     {\n         rootFrame.BackStack.Clear();\n         rootFrame.Navigate(typeof(Page01));\n     }\n};	0
28261907	28261533	Get existing arabic data from SQL Server database	Code Page	0
6558599	6555955	Connect WinForms project with WPF project	private void button1_Click(object sender, EventArgs e)\n{\n    var wpfWindow = new WpfProject.MainWindow();\n    wpfWindow.Show();\n}	0
621836	621813	Removing alternate elements in a List<T>	int pos = 0;\nfor (int i = 0; i < values.Count; i += 2, pos++) {\nvalues[pos] = values[i];\n}\nvalues.RemoveRange(pos, values.Count - pos);	0
10644675	10644107	How to detect when application is being compiled with aspnet_compiler?	public static bool IsPerformingPrecompilation()\n{\n    var simpleApplicationHost = Assembly.GetAssembly(typeof(HostingEnvironment))\n                                    .GetType("System.Web.Hosting.SimpleApplicationHost", throwOnError: true, ignoreCase: true);\n\n    return HostingEnvironment.InClientBuildManager && \n           HostingEnvironment.ApplicationID.EndsWith("_precompile", StringComparison.InvariantCultureIgnoreCase) && \n           HostingEnvironment.ApplicationHost.GetType() == simpleApplicationHost;\n}	0
6653242	6653103	LINQ Select Distinct While Evaluating Multiple Rows	var query = from item in source\n            group item by new { item.VendorCode, item.GroupType } into g\n            select new { g.Key.VendorCode,\n                         g.Key.GroupType,\n                         Variance = ComputeVariance(g) };\n\n...\n\nstring ComputeVariance(IEnumerable<YourItemType> group)\n{\n    var distinctVariance = group.Select(x => x.Variance)\n                                .Distinct();\n    using (var iterator = distinctVariance.GetEnumerator())\n    {\n        iterator.MoveNext(); // Assume this will return true...\n        var first = iterator.Current;\n        return iterator.MoveNext() ? "custom" : first.ToString();\n    }\n}	0
14789827	14787762	DataGridView CellDrag too sensitive	private int thCount = 0;\n    private void gridOperations_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        if ((e.Button & MouseButtons.Left) == MouseButtons.Left && thCount==5)\n        {\n            //... \n            thCount = 0;\n        }\n        else\n        {\n            thCount++;\n        }\n    }	0
11556914	11556835	How to assign a font for IElement with itextsharp	foreach (IElement t in htmlarraylist)\n{\n        t.Font = font;\n        document.Add(t);\n}	0
8118944	7753431	How can I insert an Blank Line using a Open XML SDK class	using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\LineBreaks.docx", WordprocessingDocumentType.Document))\n        {\n            package.AddMainDocumentPart();\n\n            Run run1 = new Run();\n            Text text1 = new Text("The quick brown fox");\n            run1.Append(text1);\n\n            Run lineBreak = new Run(new Break());\n\n            Run run2 = new Run();\n            Text text2 = new Text("jumps over a lazy dog");\n            run2.Append(text2);\n\n            Paragraph paragraph = new Paragraph();\n            paragraph.Append(new OpenXmlElement[] { run1, lineBreak, run2 });\n\n            Body body = new Body();\n            body.Append(paragraph);\n\n            package.MainDocumentPart.Document = new Document(new Body(body));\n        }	0
13416799	13416761	How to remove or hide particular column in a datatable?	DataTable t;\n   t.Columns.Remove("columnName");\n   t.Columns.RemoveAt(columnIndex);	0
29262133	29260645	change background color of a specific Row asp.net c#	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowIndex == 1)\n    {\n        e.Row.BackColor = Color.Red;\n    }\n}	0
26983576	26902909	Sort the List based on number of times a word appear in the string	var results = items.Search(x => s.content)\n                   .Containing("abc")\n                   .ToRanked()\n                   .OrderByDescending(x => x.Hits)\n                   .Select(x => x.Item);	0
16682220	16682104	regex how to extract strings between delimiters and not double delimiters	(?<!\{)\{\w+\}(?!\})	0
18100054	18099294	How to get the Rows Count in datagrid rather than datasource or datatable when using autogenerated?	if(dal.getNumOfRows("Table1")< dgStatus.Items.Count)	0
1401499	1401458	Can I change a private readonly inherited field in C# using reflection?	var fi = this.GetType()\n             .BaseType\n             .GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);\n\nfi.SetValue(this, 1);	0
16015210	16015073	Is there a way to open Windows date and time settings dialog from a WinForms application?	timedate.cpl	0
21955753	21955475	LINQ - group/sum multiple columns	var invoiceSum =\nDSZoho.Tables["Invoices"].AsEnumerable()\n.Select (x => \n    new {  \n        InvNumber = x["invoice number"],\n        InvTotal = x["item price"],\n        Contact = x["customer name"],\n        InvDate = x["invoice date"],\n        DueDate = x["due date"],\n        Balance = x["balance"],\n        }\n )\n .GroupBy (s => new {s.InvNumber, s.Contact, s.InvDate, s.DueDate} )\n .Select (g => \n        new {\n            InvNumber = g.Key.InvNumber,\n            InvDate = g.Key.InvDate,\n            DueDate = g.Key.DueDate,\n            Contact = g.Key.Contact,\n            InvTotal = g.Sum (x => Math.Round(Convert.ToDecimal(x.InvTotal), 2)),\n            Balance = g.Sum (x => Math.Round(Convert.ToDecimal(x.Balance), 2)),\n            } \n );	0
2737299	2737090	Generate number sequences with LINQ	IEnumerable<List<int>> AllSequences(int start, int end, int size)\n{\n    if (size == 0)\n        return Enumerable.Repeat<List<int>>(new List<int>(), 1);\n\n    return from i in Enumerable.Range(start, end - size - start + 2)\n           from seq in AllSequences(i + 1, end, size - 1)\n           select new List<int>{i}.Concat(seq).ToList();\n}	0
11534672	11516076	MVC Music Store linked table data	private Entities = new Entities();\n// private MyProjectDb = new MyProjectDb();	0
21470646	21470619	How to remove special characters from start of string but leave in the body of the string?	var result = Regex.Replace(source, "^[^a-zA-Z]+", "");	0
26811262	26811064	Windows Scheduler - switch Task status to Fail	static int Main() {\n    return -1;\n}	0
9686980	9684645	SelectionChanged Event for ListBox. Pass parameters between pages	private void allTaskListTasksListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{   \n    if(e.AddedItems.Count > 0) // the items that were added to the "selected" collection\n    {\n        var mySelectedItem = e.AddedItems[0] as myItemType;\n        if(null != mySelectedItem) // prevents errors if casting fails\n        {\n            NavigationService.Navigate(\n               new Uri("/View/Details.xaml?msg=" + mySelectedItem.Crm_object_id, \n                       UriKind.RelativeOrAbsolute)\n            );\n        }\n    }\n}	0
23413700	23385843	Sharing example tables between scenarios	Background: \n    Given my table looks like\n    | .... | .... |	0
603005	602987	Can you filter an xml document to a subset of nodes using XPath in C#?	XmlDocument doc = new XmlDocument();\n    XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("root"));\n    XmlNodeList list = // your query\n    foreach (XmlElement child in list)\n    {\n        root.AppendChild(doc.ImportNode(child, true));\n    }	0
16011924	15951042	Windows Phone 7: delay in mp3 streaming	BackgroundAudioPlayer.Instance.PlayStateChanged -> PlayState.Playing	0
26333074	26331210	OnNavigatedFrom in Window Phone 8.1	protected async override void OnNavigatedFrom(NavigationEventArgs e)\n{\n    Debug.WriteLine("OnNavigatedFrom");\n    Hub.Background = new SolidColorBrush(Colors.Red);\n    this.navigationHelper.OnNavigatedFrom(e);\n}	0
13543751	13543695	Regex match and substring in one?	Regex regex = new Regex(@"<meta[^>]+content\s*=\s*['"]([^'"]+)['"][^>]*>");\nMatch match = regex.Match(input);	0
20540448	20539358	Displaying date underscore template	importHistories.AddRange(context.Imports.ToList().Select(t =>\nnew\n{\n     DateCreated = t.DateCreated.ToString("MMMM dd, yyyy"),\n     ImportHistoryId = t.ImportHistoryId,	0
8285708	8284159	How to hide textboxes, labels and buttons C# WPF	"<Window x:Class="..."	0
3959578	3958131	Getting a bitmap from the cache	// When saving to the cache, use a MemoryStream to save off the bitmap as an array of bytes\nusing (MemoryStream ms = new MemoryStream()) {\n    bitmap.Save(ms, bitmap.RawFormat);\n    context.Cache.Insert(key, (byte[])ms.ToArray(), ...\n    ...\n}\n\n...\n\n// When retrieving, create a new Bitmap based on the bytes retrieved from the cached array\nif (context.Cache[key] != null) {\n    using (MemoryStream ms = new MemoryStream((byte[])context.Cache[key])) {\n        using (Bitmap bmp = new Bitmap(ms)) {\n            bmp.Save(context.Response.OutputStream ...\n...	0
13043500	13043490	How can I add one DataColumn in two different DataTable?	DataColumn imgCount = new DataColumn("imgCount",Type.GetType("System.Int32"));\nDataColumn imgCount2 = new DataColumn("imgCount",Type.GetType("System.Int32"));\n\ndtS = dvSho.ToTable("shooters");\ndtS.Columns.Add(imgCount);\n\ndtF = dvFys.ToTable("fyshwick");\ndtF.Columns.Add(imgCount2);	0
22206419	22206185	Remove a letter from a character array	var theString = "OVERFLOW";\nvar aStringBuilder = new StringBuilder(theString);\naStringBuilder.Remove(3, 1);\naStringBuilder.Insert(3, "T");\ntheString = aStringBuilder.ToString();	0
2288034	2287791	treeview with more than one parent	void expandParentNode(TreeNode node)\n{\n    if (node == null)\n        return;\n\n    node.Expand();\n    expandParentNode(node.Parent);\n}	0
29607918	29029584	C# Data Structure to allow fast finding of objects in a large dataset with a property between two given doubles	Dictionary<double, _LIST_<Point>>	0
32623327	32623013	How can I determine whether a property is a Generic Type in DNX Core 5.0?	typeof(MyClass).GetTypeInfo().DeclaredProperties.Any(p => p.PropertyType.GetTypeInfo().IsGenericType)	0
11714412	11714250	Inheritance from Parent Controller breaks Parent Controller	public RandomController : Controller\n{\n    ...\n    protected abstract IContext Db { get; }\n    ...\n}\n\npublic MenuController : RandomController\n{\n    private SomeContext db = new SomeContext();\n\n    ...\n\n    protected override IContext Db { get { return db; } }\n\n    ...\n}	0
32333505	32324574	Move gameobject to click position in unity 2d	Transform projectile;\nfloat speed = 5f;\n\nvoid Update()\n{\n    if(Input.GetMouseButtonDown(0))\n    {\n        Vector3 target = Camera.main.ScreenToWorldPoint(Input.mousePosition);\n        target.z = projectile.position.z;\n\n        Vector3 offset = target - projectile.position;\n        Vector3 direction = offset.normalized;\n        float power = offset.magnitude;\n        projectile.GetComponent<RigidBody2D>().AddForce(direction * power * speed);\n    }\n}	0
23027753	23027715	How to add zeros to the left of a number in C#	var padded = base3.PadLeft(6, char.Parse("0"));	0
13540702	13540365	How to create optimal query?	var items = dbContext.Table\n    .Where(item => item.ParentID == null)\n    .Union(dbContext.Table\n        .Where(x => x.ParentID != null)\n        .GroupBy(x => x.ParentID)\n        .Select(g => g.FirstOrDefault()));	0
18734430	18733810	Programmatically getting the total no. of rows having data in excel sheet using C#	var rowCount =  worksheet .Dimension.End.Row	0
8966171	8966156	LINQ List Initializer not keeping order from initialization	db.SA_BamaType\n            .AsEnumerable()\n            .Select(b => new BamaTypeModel()\n            {\n                id = b.p_bamatype,\n                bamatypeNames = new Dictionary<string, string>\n                {\n                    { "NL", b.bamatypeafdrukNL },\n                    { "FR", b.bamatypeafdrukFR },\n                    { "EN", b.bamatypeafdrukEN }\n                }\n            }).ToList();	0
7261863	7261758	Design question: Multiple threads needing to access log files for read/write in c# application	ConcurrentQueue<T>	0
11385580	11385561	Initializing a Dictionary<string, string> while chaining constructors	public SqlCeDB(string filename, Dictionary<string, string> options)\n    : this(new Dictionary<string, string>(options) {\n               { "DataSource", filename }\n           })\n{\n}	0
18831528	18831316	How to create SQL Server 2012 database with C#?	static void Main(string[] args)\n{\n  using (var conn = new SqlConnection("data source=DBServer; uid=UserName; pwd=Password;"))\n  {\n    using (var cmd = new SqlCommand())\n    {\n      conn.Open();\n      cmd.Connection = conn;\n      cmd.CommandText = "Create Database NewDB;";\n      cmd.ExecuteNonQuery();\n      cmd.CommandText = "Use NewDB;CREATE TABLE dbo.Table1 (ID int, Data nvarchar(128));";\n      cmd.ExecuteNonQuery();\n    }\n  }\n}	0
3338204	3338151	Creating a C++ COM client for C# COM server	tlbexp ComServerProject.dll /out:ComServerProject.tlb	0
14078922	14065573	WCF and EF - How to force host to use its own connection string	Service1 MyService = new Service1();	0
25131789	25131532	delete multiple rows in gridview using checkboxes	for (int i = 0; i < GridView1.Rows.Count; i++)\n       {\n        CheckBox checkboxdelete = ((CheckBox)GridView1.Rows[i].FindControl("checkboxdelete"));\n\n        if (checkboxdelete.Checked == true)\n        {\n            Label lblrollno = ((Label)GridView1.Rows[i].FindControl("lblrollno"));\n\n            int rolNo = Convert.ToInt32(lblrollno.Text);\n            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);\n            SqlCommand cmd = new SqlCommand("delete from student where rollno = @rollno ", con);\n            cmd.CommandType = CommandType.Text;\n\n            SqlParameter param = new SqlParameter("@rollno", SqlDbType.Int);\n            param.Value = rolNo;\n            cmd.Parameters.Add(param);\n            con.Open();\n            cmd.ExecuteNonQuery();\n            con.Close();\n            cmd.Dispose();\n        }\n      }	0
3140608	3140453	how to add the selected item from a listbox to list <string> in c#	List<String> lstitems = new List<String>();\n\n        for (int i = 0; i < ListBox1.Items.Count; i++)\n        {\n            if (ListBox1.Items[i].Selected)\n                lstitems.Add(ListBox1.Items[i].Value);\n        }	0
29391417	29388543	File Upload path needed	protected void Button1_Click(object sender, EventArgs e)\n    {\n      string g = Server.MapPath(FileUpload1.FileName);\n\n      string b =Convert.ToString(FileUpload1.PostedFile.InputStream);\n\n      //string filepath = Path.GetFullPath(FileUpload1.FileName.toString());\n\n      Label1.Text = g;\n      Label2.Text =b;\n\n    }	0
27630770	27630499	Get datetime value from registry	public static void SetDate(string keyName, string valueName, DateTime dateTime) \n{\n   Registry.SetValue(keyName,valueName, dateTime.ToBinary(), RegistryValueKind.QWord);\n}\n\npublic static DateTime GetDate(string keyName, string valueName)\n{\n   var result = (long)Registry.GetValue(keyName,valueName, RegistryValueKind.QWord);\n   return DateTime.FromBinary(result);\n}	0
24935176	24934513	Assignment expression that sets a dynamically-created enum value	Type enumType = enumBuilder.CreateType();\nvar assign = Expression.Assign(code, Expression.Constant(2, enumType));	0
19290330	19289973	Devexpress PopupMenu Closing event like Windows Contextmenu Closing event	private void barEditItem1_EditValueChanged(object sender, EventArgs e) {\n           popupMenu1.Manager.Bars[0].Tag = false;\n      }\n\n       using DevExpress.XtraBars;\n       using DevExpress.XtraBars.ViewInfo;\n\n        public class MyBarManager : BarManager {\n            protected override BarSelectionInfo CreateSelectionInfo() {\n                return new MyBarSelectionInfo(this);\n            }\n        }\n\n        public class MyBarSelectionInfo : BarSelectionInfo {\n            public MyBarSelectionInfo(BarManager manager)\n                : base(manager) {\n            }\n\n            public override void ClosePopup(IPopup popup) {\n                if (!(bool)Manager.Bars[0].Tag) {\n                    Manager.Bars[0].Tag = true;\n                    return;\n                }\n\n                base.ClosePopup(popup);\n            }\n        }	0
7615792	7615640	what is a good structure to save this data	Dictionary<string, KeyValuePair<double, double>>	0
5052119	5049197	In the nhibernate, how can I determine if a mapped entity has cascade = "all"?	var persister = (NHibernate.Persister.Entity.AbstractEntityPersister)thisClass;\nvar cascadeStyle = persister.GetCascadeStyle(i);	0
8065221	8064706	XmlDocument query taking two values	XmlDocument xmldoc = new XmlDocument();\nxmldoc.Load(new StringReader(xmlstr));\nXmlNode node = xmldoc.GetElementsByTagName("Extensions").Item(0);\nstring id =  node.Attributes["ParameterId"].Value;\nstring val = node.Attributes["ToParameterValue"].Value;	0
9049957	9049115	Changing Control property in foreach loop	Enabled = false	0
3500734	3500569	Convert a string to a hierarchyid in C#	SqlCommand command = new SqlCommand("INSERT Structure (Path,Description,ParentID) " +\n    "VALUES(CAST('"+path+"' AS hierarchyid).GetDescendant(" + lastChildPath +\n    ", NULL) " +\n    ",@description, @parentId", _connection);	0
1330936	1330898	Xml Serialize Object and Add Elements even when missing values	public class Person\n{\n    [XmlElement(IsNullable = true)]\n    public string Name { get; set; }\n}	0
30787437	30785870	the size of a string is the same size of a image after convert the image into string?	var slices = Enumerable.Range(0, longString.Length/ blockSize + 1)\n   .Select(blockIndex => longString.Substring(\n       startIndex: blockIndex * blockSize, \n       length: Math.Min(longString.Length - blockIndex * blockSize, blockSize)));	0
11092036	11092022	How to test two dateTimes for being the same date?	if (dt.Date == DateTime.Now.Date)	0
10001256	10000848	Group DateTime rows in datatable by DateTime - C#	var query = from r in table.Rows.Cast<DataRow>()\n        let eventTime = (DateTime)r[0]\n        group r by new DateTime(eventTime.Year, eventTime.Month, eventTime.Day, eventTime.Hour, eventTime.Minute, eventTime.Second)\n            into g\n        select new {\n                g.Key,\n                Sum = g.Sum(r => (int)r[2]),\n                Average = g.Average(r => (int)r[3])\n            };	0
7152011	7151980	String list remove	lineList = theFinalList.Select( line => \n{\n    if (line.PartDescription != "")\n        return line.PartDescription + " " + line.PartNumber + "\n";\n    else\n        return "N/A " + line.PartNumber + "\n";\n})\n.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))\n.ToList();	0
26283743	26283607	How can i change in Graphics DrawString the text font size?	using (Font bigFont = new Font(SystemFonts.DefaultFont.FontFamily, 14, FontStyle.Regular)) {\n  SizeF size = g.MeasureString(texttodraw, bigFont, 14);\n  g.DrawString(texttodraw, bigFont, Brushes.Red, pictureBox1.Location.X + (pictureBox1.Width / 2) - (size.Width / 2),\n                                                          pictureBox1.Location.Y - 30);\n}	0
21751942	21751545	How to make a console app exit gracefully when it is closed	class Program\n{\n    [DllImport("Kernel32")]\n    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);\n\n    // A delegate type to be used as the handler routine \n    // for SetConsoleCtrlHandler.\n    public delegate bool HandlerRoutine(CtrlTypes CtrlType);\n\n    // An enumerated type for the control messages\n    // sent to the handler routine.\n    public enum CtrlTypes\n    {\n        CTRL_C_EVENT = 0,\n        CTRL_BREAK_EVENT,\n        CTRL_CLOSE_EVENT,\n        CTRL_LOGOFF_EVENT = 5,\n        CTRL_SHUTDOWN_EVENT\n    }\n\n    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)\n    {\n        if (ctrlType == CtrlTypes.CTRL_CLOSE_EVENT)\n            File.AppendAllText(@"Log.txt", "closed");\n\n        return true;\n    }\n\n    private static void Main(string[] args)\n    {\n        SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);\n        Console.WriteLine("Close me");\n        Console.ReadLine();\n    }\n}	0
27634540	27633930	Put text into 3 columns	listView1.Items.Add(new ListViewItem(new string[] {"ID String Value ", "Title String Value", "Link String Value"}));	0
14252753	14252632	How to kill all threads in wpf application on window close button click	volatile bool shouldClose;	0
29881250	29881106	How to write List<int> items into an xml file?	private static void ToXml(List<int> list)\n{\n    var doc = new XDocument(new XElement("List", list.Select(x =>\n                          new XElement("itemValue", x))));\n    doc.Save("test.xml");\n}	0
196599	196591	Integer formatting, padding to a given length	output = String.Format("{0:0000}", intVariable);	0
29720	29696	How do you stop the Designer generating code for public properties on a User Control?	[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic string Name\n{\n    get;\n    set;\n}	0
1531149	1531113	How to restrict to add an item to List<T>?	public IList<Person> Children \n{ \n  get\n  {\n     return _children.AsReadOnly();\n  } \n}	0
22334973	22334812	Is it possible, through FileSystemWatcher or something else, to be able to retrieve only the new entries of a text/log file that is being watched?	private static int counter;\nprivate static string[] currentLines;\nprivate static void Main(string[] args)\n{\n    FileSystemWatcher watcher = new FileSystemWatcher("myfile.txt");\n    watcher.Changed += fileChanged;\n    currentLines = File.ReadLines("myFile.txt").ToArray();\n    counter = currentLines.Length;\n    Console.ReadLine();\n}\n\nprivate static void fileChanged(object sender, FileSystemEventArgs e)\n{\n     var temp = File.ReadLines("myFile.txt").Skip(counter).ToArray();\n     if (temp.Any())\n     {\n         currentLines = temp;\n         counter += temp.Length;\n     }\n}	0
8035976	8035895	Generate database blob files to save data	MySqlCommand cmd;\ncmd.CommandText = "INSERT INTO mytable (id, blobcol) VALUES (1,:blobfile)";\ncmd.Parameters.Add("blobfile", File.ReadAllBytes(your_jpeg_file));	0
15639339	15638484	run JQuery dialog window from code behind	ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "<script> $('#dialog').dialog('open');return false;  </script>");	0
34331831	34331686	How to Get current day of the week in a dropdaownlist in c#	ddldays.SelectedValue = DateTime.Today.DayOfWeek	0
981661	981632	Lambda expression from C# to VB.Net	Dim s As String = blockRenderer.Capture(Function() RenderPartialExtensions.RenderPartial (h, userControl, viewData))	0
1604734	1604704	Custom ListView in Winforms?	class MyCustomlistView : ListView\n    {\n        public MyCustomlistView()\n            : base()\n        {\n            SetStyle(ControlStyles.UserPaint, true);\n        }\n        protected override void OnPaint(PaintEventArgs e)\n        {\n            base.OnPaint(e);\n            e.Graphics.DrawString("This is a custom string", new Font(FontFamily.GenericSerif, 10, FontStyle.Bold), Brushes.Black, new PointF(0, 50));\n        }\n\n    }	0
5893219	5893158	how to connect to a database on select of any value from combobox	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n    // A connection string for testing.\n    string connectString = "Server=OracleDemo;Integrated Security=True"\n    var builder = new OracleConnectionStringBuilder(connectString);\n    // Show your connection string before any change.\n    Console.WriteLine("ConnString before: {0}", builder.ConnectionString);\n    builder.DataSource = comboBox1.SelectedItem.ToString();\n    // This will show your conn string has been updated with the user selected database name.\n    Console.WriteLine("ConnString  after: {0}", builder.ConnectionString);\n\n    // At this point you're ready to use the updated connection string.\n}	0
12002100	12000298	Update SQL Server database using Excel	''Reference: Microsoft ActiveX Data Objects x.x Library\n\nDim cn As New ADODB.Connection\nDim cmd As New ADODB.Command\ncn.Open ServerCon\n\ncmd.ActiveConnection = cn\n\ncmd.CommandText = "insert_user"\ncmd.CommandType = adCmdStoredProc\ncmd.Parameters("@username").Value = Worksheets("Sheet1").Cells(2, 2)\ncmd.Execute	0
16248929	16246554	How to get the count of tables in an html file with C# and html-agility-pack	HtmlDocument doc = new HtmlDocument();\ndoc.Load(myTestFile);\n\n// get all TABLE elements recursively\nint count = doc.DocumentNode.SelectNodes("//table").Count;\n\n// output to a text file\nFile.WriteAllText("output.txt", count.ToString());	0
13269372	13269221	Reading XML file via XML nodes	GameSteps = xd.SelectNodes("/GameData/GamePlayStep");	0
2153561	2153544	Can we make a enum as a generic data type?	An enumeration is a named constant whose underlying type is any integral type	0
4033109	4033054	Fixed statement with jagged array	GCHandle h = GCHandle.Alloc(array, GCHandleType.Pinned);	0
5791579	5791525	Linq to XML Parsing Help - getting elements?	XNamespace ns = "http://xxx/webservices/wsDocumentIndex/";\nforeach (XElement documentElement in documentElements)\n{\n    XElement id = documentElement.Element(ns + "locatorNum");\n    XElement file_type = documentElement.Element(ns + "fileFormat");\n    ...\n}	0
16947924	16947775	How can i set a new file name and directory?	ffmp.Start()	0
11809000	11807292	Update panel in master page and asp fileupload in child page	protected void Page_Load(object sender, EventArgs e)\n{\n    UpdatePanel updatePanel = Page.Master.FindControl("UpdatePanel1") as UpdatePanel;\n    UpdatePanelControlTrigger trigger  = new PostBackTrigger();\n    trigger.ControlID = Announcement_Update.UniqueID;\n    updatePanel.Triggers.Add(trigger);\n}	0
8531806	8531748	How to add a where clause on a linq join (lambda)?	query.Join(_ctx.ContactOperationPlaces, c => c.Id, cop => cop.ContactId,\n           (c, cop) => new {c, cop}).Where(o => o.cop.municipalityId == 301)\n                                    .Select(o => o.c)\n                                    .Distinct();	0
22325376	22324732	EWS only reading my inbox	//creates an object that will represent the desired mailbox\nMailbox mb = new Mailbox(@"othermailbox@domain.com");\n\n//creates a folder object that will point to inbox folder\nFolderId fid = new FolderId(WellKnownFolderName.Inbox, mb); \n\n//this will bind the mailbox you're looking for using your service instance\nFolder inbox = Folder.Bind(service, fid);\n\n//load items from mailbox inbox folder\nif(inbox != null) \n{\n    FindItemsResults<Item> items = inbox.FindItems(new ItemView(100));\n\n    foreach(var item in items)\n        Console.WriteLine(item);\n}	0
21606706	21606570	Limit references to public fields in a project	public partial class MyClass1\n{\n    private const string myClass1Const1 = "myClass1Const1";\n    private const string myClass1Const2 = "myClass1Const2";\n}\n\npublic partial class MyClass2\n{\n    private const string myClass2Const1 = "myClass2Const1";\n    private const string myClass2Const2 = "myClass2Const2";\n}	0
3995392	3995342	Namespaces to avoid conflicts - example?	MyClass o = new MyClass()	0
9076337	9067062	Injecting a module that contains an injected module using mef2	[Export(typeof(ICoupon))]\npublic class CouponManager : ICoupon \n{\n  private IWallet _iWallet;\n\n  [ImportingConstructor]\n  public CouponManager(IWallet iwallet)\n  {\n     this._iWallet= iwallet;\n  }\n}	0
3120758	2978243	Using C# WATIN, how do I get the value of a INPUT tag html element?	ElementCollection elementCol = ie.Elements;\n        elementCol = elementCol.Filter(Find.ByClass("myclass"));\n        string value = elemntCol[1].GetAttributeValue("value");	0
1313938	1313847	FileSystemWatcher - how to determine when file is closed?	DateTime EndTime = System.DateTime.Now.AddMinutes((double)timeOut);\n\n        while (System.DateTime.Now <= EndTime)\n        {\n            try\n            {\n                using (Stream stream = System.IO.File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))\n                {\n                    if (stream != null)\n                    {\n                        break;\n                    }\n                }\n            }\n            catch (FileNotFoundException)\n            {\n                //\n            }\n            catch (IOException)\n            {\n                //\n            }\n            catch (UnauthorizedAccessException)\n            {\n                //\n            }\n\n\n            System.Threading.Thread.Sleep(sleepTime);\n        }	0
17187838	17187675	Failed to pass JSON Object	data: JSON.stringify({report:DailyReport}),	0
16263629	16263377	DataGridView: Scroll down automatically only if the scroll is at the bottom	int firstDisplayed = liveDataTable.FirstDisplayedScrollingRowIndex;\nint displayed = liveDataTable.DisplayedRowCount(true);\nint lastVisible = (firstDisplayed + displayed) - 1;\nint lastIndex = liveDataTable.RowCount - 1;\n\nliveDataTable.Rows.Add();  //Add your row\n\nif(lastVisible == lastIndex)\n{\n     liveDataTable.FirstDisplayedScrollingRowIndex = firstDisplayed + 1;\n}	0
2438955	2438924	Is it possible to Take object members directly from a queue of type object?	queue.OfType<CustomObject>().Select(o => o.doubleArray[0]).Take(1).ToArray();	0
22566633	22566537	collect score from mouse click event in c# silverlight	public class Window\n{\n    private int _clicks = 0;\n\n    private void redballoon_click(object sender, MouseButtonEventArgs e)\n    {\n        _clicks++; \n    }\n}	0
24938141	24938065	Disallow specific chars using regex for Dropbox	private static string MakeValidFileName( string name )\n{\n   string invalidChars = System.Text.RegularExpressions.Regex.Escape( new string( System.IO.Path.GetInvalidFileNameChars() ) );\n   string invalidRegStr = string.Format( @"([{0}]*\.+$)|([{0}]+)", invalidChars );\n\n   return System.Text.RegularExpressions.Regex.Replace( name, invalidRegStr, "_" );\n}	0
3137253	3137238	Shove a delimited string into a List<int>	string str = "123;3344;4334;12";\nList<int> list = new List<int>();\n\nforeach (string s in str.Split(';'))\n{\n    list.Add( Int32.Parse(s));\n}	0
29696363	29696340	Trying to insert a row into my table using sql query INSERT INTO	INSERT INTO dbo.Questions ([Question Type])\nVALUES (1)	0
32480196	32471235	Add restriction conditionally	ICriterion criterion;\n\n         if(Setting.SomeSettings)    \n         {\n           criterion = Restrictions.And(\n                            **//new restriction**\n                             Restrictions.Eq("Some", user.Some))\n                             Restrictions.Eq("Status", user.Status))\n                             ...\n                        ));\n        }\n        else\n        {\n           criterion = Restrictions.And(\n                          Restrictions.And(                 \n                             Restrictions.Eq("Status", user.Status))\n                             ...\n                        ));\n        }\n\n        new List < ICriterion > {\n                    Restrictions.Not(Restrictions.Eq("Name", user.Name)),\n                    Restrictions.Or(\n                       Restrictions.And(\n                        criterion   \n                        ...\n                 };	0
33081258	33081102	json add new object to existing json file C#	var list = JsonConvert.DeserializeObject<List<Person>>(myJsonString);\nlist.Add(new Person(1234,"carl2");\nvar convertedJson = JsonConvert.SerializeObject(list, Formatting.Indented);	0
5868464	5868438	C# Generate a random Md5 Hash	Guid.NewGuid()	0
1479789	1479781	How do I open a new page from code behind?	Response.Redirect("path_to/newpage.aspx");	0
16457289	16212137	How do I add a reference for an assembly using c#	var a = Activator.CreateInstance(assemblytype, argtoppass);\nSystem.Type type = a.GetType();\nif (type != null)\n{\n  string methodName = "methodname";\n  MethodInfo methodInfo = type.GetMethod(methodName);\n  object resultpath = methodInfo.Invoke(a, argtoppass);\n  res = (string)resultpath;\n}	0
14384802	14384609	Need help converting a SQL left join query into LINQ format	from m in Db.Media\njoin g in Db.Galleries on m.GalleryID equals g.GalleryID into MediaGalleries\nfrom mg in MediaGalleries.DefaultIfEmpty()\nwhere m.MediaDate >= DateTime.Today.AddDays(-30)\norderby m.Views descending\nselect new\n{\n    GalleryTitle = mg != null ? mg.GalleryTitle : null,\n    Media = m\n};	0
2823121	2823076	Forcing an app to run single core only?	Process.ProcessorAffinity	0
22576707	22561584	Windows API Code Pack TaskDialog missing icon	taskDialog.Opened += new EventHandler(taskDialog_Opened);\n\n...\n\npublic void taskDialog_Opened(object sender, EventArgs e)\n{\n    TaskDialog taskDialog = sender as TaskDialog;\n    taskDialog.Icon = taskDialog.Icon;\n    taskDialog.FooterIcon = taskDialog.FooterIcon;\n    taskDialog.InstructionText = taskDialog.InstructionText;\n}	0
17767005	17766258	Split string separated by comma but without splitting double value	private string[] ParseCsv(string line)\n    {\n        var parser = new TextFieldParser(new StringReader(line));\n        parser.TextFieldType = FieldType.Delimited;\n        parser.SetDelimiters(",");\n        while (!parser.EndOfData)\n        {\n            return parser.ReadFields();\n        }\n        parser.Close();\n        return new string[0];\n    }	0
1368007	1367962	Container Control is losing focus	Application.AddMessageFilter	0
20591940	20591897	How to populate a list inside a dictionary?	ClientsData[0].Languages = new Dictionary<int,List<string>>();\nClientsData[0].Languages.Add(2376,new List<string>(){ "english", "french"});	0
11838615	11838552	referencing a variable using concatenation C#	var listVariables = new Dictionary<string, int>\n                    {\n                        { "foo1", 1 },\n                        { "foo2", 2 },\n                        { "foo3", 3 },\n                        { "foo4", 4 },\n                    };\n\nfor (int x = 1; x <= 4; x++)\n{\n   listVariables["foo" + x] = bar;\n}	0
2710072	2710009	nhibernate, Retrieve the latest row in a table	User user = ...;\n    var crit = DetachedCriteria.For<UserAddress>()\n        .Add(Restrictions.Eq("User", user))\n        .AddOrder(Order.Desc("InsertedAt"))\n        .SetMaxResults(1);	0
22635399	22624762	Using iTextSharp, is there a way to keep text from staying in a rectangle	Phrase myText = new Phrase(text);\n\nPdfPTable table = new PdfPTable(1);\n\ntable.TotalWidth = 300;\ntable.LockedWidth = true;\n\nPdfPCell cell = new PdfPCell(myText);\ncell.Border = 0;\ncell.FixedHeight = 40;\n\ntable.AddCell(cell);\ntable.WriteSelectedRows\n(\n 0, \n -1, \n 300,\n 700,\n writer.DirectContent\n);	0
26097036	26096859	how to get .bak extension while creating backup in 3 tier project	saveFileDialog1.Filter = "All Files|*.bak"\nsaveFileDialog1.ShowDialog();	0
2314843	2314611	setting position of a control doesn't seem to work when scroll is 'moved' (c#, winforms)	private void button1_Click(object sender, EventArgs e)\n  {\n     int y = list[0].Location.Y;\n     foreach (UserControl2 c in list)\n     {\n        c.Location = new Point(0, y);\n        y += c.Height;\n     }\n  }	0
16626691	16626643	How do you find at what line a word is located in a textbox?	string splitstring = stringToSplit.Split(new char[] { ' ', '\n', '\r' });	0
19141165	19141105	How would i go about creating a win count and guess count for my random number guessing game C#	int gessNum = 0;\n       do\n       {\n            if (gessNum++ == maxGuesses){\n                Console.WriteLine("You lost");\n                break;\n            }\n            Console.WriteLine(string.Format(" Enter Guess {0}: ", gessNum));\n            currentGuess = Int32.Parse(Console.ReadLine());\n\n            if (currentGuess == randomNumber)\n            {\n                Console.WriteLine("You got it!");\n            }\n            if (currentGuess > randomNumber)\n            {\n                Console.WriteLine("Too High");\n            }\n            if (randomNumber > currentGuess)\n            {\n                Console.WriteLine("Too Low");\n            }\n            Console.ReadLine();\n        } while (currentGuess != randomNumber);	0
5956937	5956909	Regex to match full lines of text excluding crlf	[^\r\n]+	0
19624653	19624447	Select node from XML and Create a new XML	private void button1_Click(object sender, EventArgs e)\n{\n    var xDoc = XDocument.Load(XML_Path)\n    string keep = "EmpId,Sex,Address,Zip";\n    string[] strArr = keep.Split(',');\n\n    var nodesToDelete = xDoc.Root.Descendants("Employee")\n        .SelectMany(e => e.Descendants()\n                          .Where(a => !strArr.Contains(a.Name.ToString())));\n\n    foreach (var node in nodesToDelete.ToList())\n        node.Remove();\n\n    richTextBox1.Text = xDoc.ToString();\n}	0
14382917	14382009	Word 2010 Interop: Change the name of the default document	Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();\n\n    object missing = System.Reflection.Missing.Value;\n    object fileName = "Report";\n    object isReadOnly = false;\n    object isVisible = true;\n\n    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref isVisible);\n\n    doc.SaveAs2(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref isReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);          \n    wordApp.Visible = true;	0
26329154	26060656	XmlDeserization with encoding	private T ExtractResponse<T>(byte[] response) where T : class\n{\n    T obj = null;\n    if (response != null && response.Length > 0)\n    {\n        var serializer = new XmlSerializer(typeof(T));\n        using (TextReader reader = new StreamReader(\n            new MemoryStream(response), \n            System.Text.Encoding.GetEncoding("iso-8859-1")))\n        {\n            obj = (T)serializer.Deserialize(reader);\n        }\n    }\n    return obj;\n}	0
5654382	5654355	How to read XML using Linq to XML?	XDocument doc = XDocument.Load("feed.xml");\n\nXElement client = doc.Root.Element("client");\nstring name = (string) client.Element("Name");\nint number = (int) client.Element("Number");\n\nXElement info = doc.Root.Element("Info");\nstring title = (string) info.Element("Title");\n\nXElement basicInfo = doc.Root.Element("BasicInfo");\nstring comment = (string) basicInfo.Element("Comment");	0
11012515	11012101	remove a duplicate element(with specific value) from xml using linq	using System.Linq;\n using System.Xml.Linq;\n using System.Xml.XPath;\n\n var element = XElement.Parse(@"<?xml version=""1.0"" encoding=""utf-8""?>\n                            <super>\n                              <A value=""1234"">\n                                <a1 xx=""000"" yy=""dddddd"" />\n                                <a1 xx=""111"" yy=""eeeeee"" />\n                                <a1 xx=""222"" yy=""ffffff""/>\n                              </A>\n                            </super>");\n\n  // select all the a1's that have xx = 222\n  var a1Elements = element.XPathSelectElement("A/a1[@xx='222']"); \n\n  if (a1Elements != null)\n     a1Elements.Remove();\n\n  Console.WriteLine(element);	0
25668676	25668480	unit test to detect a new field/property addition in C#	void TheUnitTest()\n{\n    var p = new Person();\n    Assert.That(p.GetType().GetProperties().Count() == 3);\n}\n\npublic class Person { public String Name{ get; set; } public int age { get; set; } public String job { get; set; } }	0
13402444	13402404	How to use pointer from COM object on C#?	Object[] item = s.GetObjects() as Object[];	0
10032659	9999772	How to turn off AxisAngleRotation3D animation in code behind? wpf	rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, null);	0
10509172	10509141	calling base method using new keyword	base.Method();	0
22678268	22678234	I want add Textboxs in windows form application in user specified number	TextBox[] txtBoxes = new TextBox[userValue];\nfor (int i = 0; i < txtBoxes.Length; i++) \n{\n  var txt = new TextBox();\n  txtBoxes[i] = txt;\n}	0
21589343	21588914	Deleting child objects with EF6	var removedRecords = person.SicknessRecords.Except(model.SicknessRecords);\nfor (var record in removedRecords)\n{\n    person.SicknessRecords.Remove(record);\n}	0
12838396	12838207	C# - Linq to XML - Exclude elements from query	var mandatoryElements = new List<string>() {\n                   "MandatoryElement1", \n                   "MandatoryElement2", \n                   "MandatoryElement3"\n                };\n\n var result = xDoc.Root.Descendants()\n                  .Where(x => !mandatoryElements.Contains(x.Name.LocalName));	0
27143576	27012535	How to set up Web API to allow Acces Token in the URL as a parameter with DotnetOpenAuth in WEB API 2	void Application_BeginRequest(object sender, EventArgs e)\n    {\n        if (ReferenceEquals(null, HttpContext.Current.Request.Headers["Authorization"]))\n        {\n            var token = HttpContext.Current.Request.Params["Authorization"];\n            if (!String.IsNullOrEmpty(token))\n            {\n                HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + token);\n            }\n        }\n    }	0
30030333	30029009	Exception in configuring Transport Security in Self Hosted Service using NetTcpBinding in WCF	include this in your client side in endpoint behaviours\n\n    <endpointBehaviors>\n          <behavior name="clientBehave">\n            <clientCredentials>\n               <serviceCertificate>              \n<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>\n              </serviceCertificate>\n            </clientCredentials>\n          </behavior>\n        </endpointBehaviors>	0
5209754	5209723	Lambda Expressions and Method calls	List<People> someList;\nsomeList.ForEach(person => person.Save());	0
1417504	1417362	Distribution of MDI children in an MDI parent	**ArrangeIcons**     child window icons are arranged within the parent\n**Cascade**          arrange the child windows within the parent window in a cascaded fashion\n**TileHorizontal**   tile the child windows horizontally\n**TileVertical**     tile the child windows vertically\n\n\n//Cascade all child forms.        \nthis.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);	0
11251745	11251557	Find .NET Recognizable Guids in a String	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n  static void Main()\n  {\n    string input = "Random string CA761232-ED42-11CE-BACD-00AA0057B223 random string";\n    Match match = Regex.Match(input,\n      @"((?:(?:\s*\{*\s*(?:0x[\dA-F]+)\}*\,?)+)|(?<![a-f\d])[a-f\d]{32}(?![a-f\d])|" +\n      @"(?:\{\(|)(?<![A-F\d])[A-F\d]{8}(?:\-[A-F\d]{4}){3}\-[A-F\d]{12}(?![A-F\d])(?:\}|\)|))");\n    if (match.Success)\n    {\n      string key = match.Groups[1].Value;\n      Console.WriteLine(key);\n    }\n    else\n    {\n      Console.WriteLine("NO MATCH");\n    }\n  }\n}	0
32189036	32188457	Whether the windows side bar explorer in windows explorer is tree view control or custom control?	private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)\n    {\n        e.Node.StateImageIndex = 0; // assuming 0 is the const for expanded navigation \n    }\n\n    private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)\n    {\n        e.Node.StateImageIndex = 1; // assuming 1 is the const for collapsed navigation \n    }	0
16546756	16546664	How to save in asp.net mvc multiple input boxes text in one record	var allValues = \n    string.Format("{0}{1}{2}",\n       form["txtNumber"],\n       form["txtMonth"],\n       form["txtYear"]);	0
8030025	8030005	How to get items from an array and display them in a textbox;	foreach (string file in files) {\n  textbox1.Text += file + Environment.NewLine;\n}	0
25593079	25447551	Need to update dataGridView, Trying to update dataGridView, but no way	roleBindingSource.DataSource = roleTableAdapter.GetData();\ndataGridView1.DataSource = roleBindingSource;\nroleBindingSource.ResetBindings(false);	0
26078227	26078038	How to create and organize non UI related elements using the MVVM pattern	private void Application_Startup(object sender, StartupEventArgs e)\n{\n    ConnectionManager connMan = new ConnectionManager();\n    MainViewModel mvm = new MainViewModel(connMan);\n    new MainWindow(mvm).ShowDialog();\n\n    // TODO: save settings, etc. here\n\n    this.Shutdown();\n}	0
21292294	21291404	Can't get attribute name of xml element	if (pReader.NodeType == XmlNodeType.Element)\n        {\n            if (pReader.HasAttributes)\n            {\n                while (pReader.MoveToNextAttribute())\n                {\n                    /* ...Here I want a label with attribute name not value)*/\n                    Label lblAttribute = new Label();\n                    lblAttribute.Text = pReader.Name;\n                    TextBox txbAttribute = new TextBox();\n                    txbAttribute.Text = pReader.Value;\n                    Page.FindControl("form1").Controls.Add(txbAttribute);\n                }   \n\n                // Move the reader back to the element node.\n                reader.MoveToElement();\n            }\n        }	0
5603599	5603558	C# Adding a tabpage to a listView	private void Form1_Load(object sender, EventArgs e)\n{            \n   TabControl tbl = new TabControl();\n   tbl.TabPages.Add("page1");            \n   lstView.Controls.Add(tbl);\n}	0
4253771	4253567	How to have Column, Rows array (not vice versa)	//Breadth-first\nfor(int x = 0; x < col.Length; x++)\n{    \n     for(int y = 0; y < row.Length; y++)\n     {             \n     }    \n}\n\n//Depth-first\nfor(int y = 0; y < row.Length; y++)\n{    \n     for(int x = 0; x < col.Length; x++)\n     {    \n     }    \n}	0
726290	726100	How do I programatically download a file from a sharepoint site?	wget.exe <url>	0
13728643	13728532	Storing items from MySQL into muliple variables	List<string> weight = new List<string>();\n\nwhile(dataReader.Read())\n{\n     weight.Add(dataReader["weight"]);\n}	0
258921	258908	How to find amount of parameters in a constructor	System.Type.GetType("MYClassName").GetConstructors()	0
26377150	26376590	How to truncate a FileStream to read just specific bytes?	int bytesLeft = ...; // initialized to whatever\n\nwhile (bytesLeft > 0)\n{\n    int bytesRead = fs.Read(rgb, 0, Math.Min(rgb.Length, bytesLeft));\n\n    bytesLeft -= bytesRead;\n}	0
782760	782729	Need a pattern to call Verify method for every instance method pattern	if(!Size) \n    return;	0
19035158	19035103	Getting windows special folder in code when provided by a user	Environment.ExpandEnvironmentVariables	0
15664689	15664490	What's the purpose of access modifier in overriden method?	class LevelOne\n{\n    public virtual void SayHi()\n    {\n        Console.WriteLine("Hi!");\n    }\n}\nclass LevelTwo : LevelOne\n{\n    override void SayHi()\n    {\n        Console.WriteLine("Hi!");\n    }\n}\nclass LevelThree : LevelTwo\n{\n    override void SayHi()\n    {\n        Console.WriteLine("Hi!");\n    }\n}	0
32842264	32820992	C# - Possible to restore double precision from a text input?	168000 / 3.666     = 45826.5139\n  168000 / 3.666666  = 45818.1901488\n  168000 * 3 / 11    = 45818.1818182	0
5765295	5765258	c# Best way to break up a long string	public static string Abbreviate(this string text, int length) {\n    if (text.Length <= length) {\n        return text;\n    }\n\n    char[] delimiters = new char[] { ' ', '.', ',', ':', ';' };\n    int index = text.LastIndexOfAny(delimiters, length - 3);\n\n    if (index > (length / 2)) {\n        return text.Substring(0, index) + "...";\n    }\n    else {\n        return text.Substring(0, length - 3) + "...";\n    }\n}	0
25665760	25665637	How to add checklistbox items into tablelayoutpanel?	CheckedListBox cbl = new CheckedListBox();\ncbl.Items.Add("Item 1");\ncbl.Items.Add("Item 2");\ntableLayoutPanel1.Controls.Add(cbl);	0
24774240	24774147	how to load panorama item when it is opnened	private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    switch (((Panorama)sender).SelectedIndex)\n    {\n        case 0: // defines the first PanoramaItem Loaded\n            MessageBox.Show("First Item is on ForeGround");\n            break;\n        case 1: // second one\n            MessageBox.Show("Second Item is on ForeGround");\n            break;\n\n        case 2: // third one\n            MessageBox.Show("Third Item is on ForeGround");\n            break;\n    }\n}	0
2844494	2844458	Serialize an object using DataContractJsonSerializer as a json array	[DataContract]\npublic class MyItem\n{\n    [DataMember]\n    public string Name { get; set; }\n\n    [DataMember]\n    public string Description { get; set; }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var graph = new List<MyItem>\n        {\n            new MyItem { Name = "one", Description = "desc1" },\n            new MyItem { Name = "two", Description = "desc2" }\n        };\n        var serializer = new DataContractJsonSerializer(graph.GetType());\n        serializer.WriteObject(Console.OpenStandardOutput(), graph);\n    }\n}	0
25372796	25372741	Manual GC Gen2 data allocation	GC.GetGeneration	0
13861874	13856018	Insert custom Button inside Gridview pager	if (e.Row.RowType == DataControlRowType.Pager)\n{\n    Table pagerTable = (e.Row.Cells[0].Controls[0] as Table);\n    TableRow row = new TableRow();\n    row = pagerTable.Rows[0];\n    TableCell cell1 = new TableCell();\n    cell1.Controls.Add(ImageButton1);\n\n    row.Cells.AddAt(1,cell1);\n}	0
7091550	7091440	how to enable start button after clicking stop buttons	public void MyButtonClick(object sender, EventArgs e)\n{\n\n    if (sender == btn1)\n    {\n        Clock.Stop();\n    }\n\n    if (sender == btn2)\n    {\n        Clock1.Stop();\n    }\n\n    if (sender == btn3)\n    {\n        Clock2.Stop();\n    }\n    Finish();\n\n    if(!Clock.Enabled && !Clock1.Enabled && !Clock2.Enabled)\n       btn4.Enabled = true;\n}	0
33072594	33072331	How to convert z coordinate to an angle in c#?	private float XYZToDegrees(double deltaX, double deltaY, double deltaZ)\n{\n    double deltaXY = Math.Sqrt(deltaY * deltaY + deltaX * deltaX);\n    double radAngle = Math.Atan2(deltaZ, deltaXY);\n    double degreeAngle = radAngle * 180.0 / Math.PI;\n\n    return (float)degreeAngle;\n}	0
30126758	30126401	Define two tables in c# with foreign key	string query = "CREATE TABLE IF NOT EXISTS Projects" + "(" + "project_id INT AUTO_INCREMENT PRIMARY KEY," + "team_id INT,"+"name VARCHAR(30)," +\n            "description VARCHAR(30)," + "FOREIGN KEY (team_id) REFERENCES Teams(team_id)" + ");";	0
28821220	28792196	How does ConnectionMultiplexer deal with disconnects?	private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {\n    return ConnectionMultiplexer.Connect("mycache.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");\n});\n\npublic static ConnectionMultiplexer Connection {\n    get {\n        return lazyConnection.Value;\n    }\n}	0
6607857	6607835	How to extract XML data	XDocument doc = XDocument.Load("test.xml");\n\nint code = doc.Descendants("extCode")\n              .Where(x => (string) x.Attribute("Type") == "abc")\n              .First()\n              .Attribute("Code");	0
27248779	27244685	Unable to find out reason of error Cross-thread operation not valid from C++ callback to C#	ProgressCallback callback = (theValue) =>\n                    {\n                        label1.Invoke((MethodInvoker)delegate {\n                             label1.Text = theValue.ToString();\n                        });\n                    };	0
3169104	3169072	C# - Console Keystrokes	ConsoleKeyInfo keypress;\nkeypress = Console.ReadKey(); // read keystrokes \n\nif (keypress.Key == ConsoleKey.LeftArrow)\n{\n    Console.BackgroundColor = ConsoleColor.Cyan;\n}	0
4614984	4612383	Dealing with array of IntPtr	private static extern bool Open(out int n,[MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] [In,Out] IntPtr[] ptr);	0
3025389	3025361	C# DateTime to "YYYYMMDDHHMMSS" format	DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive	0
12947484	12947212	How do Extract information from a very generic xml document?	var list = XDocument.Load("C:\\test.xml")\n            .Descendants("section")\n            .Where(e => e.Attribute("name").Value.Equals("DOBs"))\n            .Descendants("row")\n            .Descendants("cell")\n            .Attributes("value").ToList();\n\nvar dic = Enumerable.Range(0, list.Count/2)\n    .ToDictionary(i => list[2*i], i => list[2*i + 1]);	0
20372510	20368793	Trouble with JObject.Parse to dynamic type in Windows Phone 8	var id = result["id"];	0
11772381	11772288	How to get default value for DependencyProperty	var metadata = dependencyProperty.GetMetadata(typeof(SomeDependencyObject));\nvar defaultValue = metadata.DefaultValue;	0
29516066	29515421	Accessing packages of newly created package EA	Package newPackage = root.Packages.AddNew("New Package", "Package");\nnewPackage.Update();\nroot.Packages.Refresh();	0
17276999	17275533	FormCollection to expandoObject	[HttpPost]\npublic ActionResult Test(FormCollection collection)\n{\n    dynamic expando = new ExpandoObject();\n    var dictionary = (IDictionary<string, object>) expando;\n\n    foreach (var item in collection.AllKeys.ToDictionary(key => key, value => collection[value]))\n    {\n        dictionary.Add(item.Key, item.Value);\n    }\n    // your expando will be populated here ...\n    // do awesomeness\n}	0
25660616	25660411	Key Value Pair Comparison based on key only	var list2 = new List<KeyValuePair<string, int>>();\n\n     for (int i=0;i<list.Count-1;i++)\n    {\n       if (list[i].Value>list[i+1].Value)\n        {         \n          list2.Add(new KeyValuePair<string, int>(list[i].Key,list[i].Value)\n        }\n    }	0
28341404	28335929	Connect MongoDB with Web API	public IEnumerable<Book> Get()\n{     \n    var client = new MongoClient("mongodb://localhost:27017");\n    var server = client.GetServer();\n    var db = server.GetDatabase("BookStore");\n    var collection = db.GetCollection<Book>("Book");\n    Book[] books =\n    {\n         new Book { Id = 1, Title = "Book Name 1" }, \n         new Book { Id = 2, Title = "Book Name 2" },\n         new Book { Id = 3, Title = "Book Name 3" }, \n         new Book { Id = 4, Title = "Book Name 4" }\n    };\n    foreach (var book in books)\n    {\n        collection.Save(book);\n    }\n    return books;\n}	0
33354733	33354590	C# query to update textbox value from gridview double click event	SqlCommand str_Cmd = new SqlCommand("UPDATE Personal_Info SET Name = '"+ txtBx_Name.Text +"' WHERE Name = '"+ txtBx_Name.Text.ToString() +"'", str_Conn);	0
15556689	15555765	Comparing two lists with multiple conditions in Entity Framework	var fb =\n    (from m in db.Members\n     let friendIds = \n         from ff db.FacebookFriends\n         where ff.UserID == CurrentUserID\n         select ff.FacebookId\n     let followerIds = \n         from uf db.UserFollowers\n         select uf.FollowerID\n     where friendIds.Contains(m.ProviderUserId) && !followerIds.Contains(m.UserID)\n     select m)\n    .Take(6)\n    .ToList();	0
17906263	17906201	How to share a screenshot?	using Microsoft.Xna.Framework.Media.PhoneExtensions;\n\n...\n\nvar picture = mediaLibrary.SavePicture(fileName, stream);\nshareMediaTask = new ShareMediaTask();\nshareMediaTask.FilePath = picture.GetPath();\nshareMediaTask.Show();	0
2985919	2985854	Custom calendar drag drop event: Find date dropped to	DateTime datetime = (DateTime)((DropTarget)sender).DataContext;	0
24255212	24255123	C# Converting Console.Writeline outputs to String for email	myReader = myCommand.ExecuteReader();\nvar message = new StringBuilder();\n        while (myReader.Read())\n        {\n            string datetype = (myReader["Expiry_Date"].ToString());\n            DateTime dateformat = DateTime.Parse(datetype); \n\n            if(dateformat.Date <= calDate3b && dateformat.Date>=timenow)\n            {\n                message.AppendLine(myReader["Number"].ToString());\n                message.AppendLine(myReader["Name"].ToString());\n                message.AppendLine(myReader["Number_Yolo"].ToString());\n                message.AppendLine(myReader["Date"].ToString());\n                message.AppendLine();                    \n            }\n        }\n\nConsole.WriteLine(message.ToString());\nmail.Body = message.ToString();	0
19239799	19237886	Can't Add Tab Page To TabControl Inside The Constructor Of My WinForms Application	InitializeComponent();\n\n    TabControl tc = new TabControl();\n    tc.Location = new Point(10, 10);\n    tc.Size = new Size(100, 100);           \n    tc.Visible = true;\n    tc.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left |           AnchorStyles.Top);\n    this.Controls.Add(tc)\n    addImage("c:\pathToImage\image.bmp");	0
15782416	15781945	How to write a Web API route mapping so that it allows me make a parameter optional?	sites/{siteName}/User/SearchByEmail/{providerName}	0
32503905	32503623	Remove an item in a list while it's in a foreach loop c#	List<Type> temp = new List<Type>()\nforeach(item in mainList)\n{\n   if (item.Delete)\n   {\n      temp.Add(item);\n   }\n}\n\nforeach (var item in temp)\n{\n   mainList.Remove(item);\n}	0
1970248	1969935	how to give a grid row a row command	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    GridView GridView1 = (GridView)frmViewClaimantPE.FindControl("GridView1");\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n\n        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";\n        e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);\n\n    }\n\n}	0
30926294	30911297	Outlook Addin appointmentitem PropertyChange event firing too much	ItemChange("RequiredAttendees")	0
20079233	20079087	C# - Highlight wrong controls when validating	private void createButton_Click(object sender, EventArgs e)\n{\n     bool gotIssues = this.ValidateChildren();\n     if (gotIssues) \n     {\n         // someone didn't validate well...\n     }\n}	0
15956789	15956716	Using LINQ how can I prioritise an IEnumerable based on ranges?	var band1 = myList.Where(c => c <= 3);\nvar band2 = myList.Where(c => c => 4 && c <= 8);\nvar band3 = myList.Where(c => c >= 9);\n\nvar result = band1.Concat(band2).Concat(band3);	0
27008389	27008232	C# how to set a timer in method?	void LongMethod(CancellationToken token)\n{\n    for (int i=0; i<51; ++i)\n    {\n        token.ThrowIfCancellationRequested();\n        Thread.Sleep(1000); // some sub operation\n    }\n}\n\nvoid Run()\n{\n    var source = new CancellationTokenSource(50000); // 50 sec delay\n    var task = new Task(() => LongMethod(source.Token), source.Token);\n    task.Wait();\n}	0
12662749	12662541	How to create an ItemTemplate for a ComboBox programmatically?	Style style = new Style(typeof(ComboBox));\nvar d = new DataTemplate();\n\nMultiBinding mb = new MultiBinding();\nmb.StringFormat = "{0} {1} Mitglied(er)";\nmb.Bindings.Add(new Binding("Name"));\nmb.Bindings.Add(new Binding("MemberCount"));\n\nFrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));\ntextElement.SetBinding(TextBlock.TextProperty, mb);\nd.VisualTree = textElement;\n\nstyle.Setters.Add(new Setter(ComboBox.ItemTemplateProperty, d));\nthis.Resources.Add("ComboBox_EntityCreation_GroupSelect_Style", style);	0
21656198	21656183	Loading a different view with a parameter	return RedirectToAction("Index", new{id=yourId});	0
745992	745985	Cache lookup performance	Dictionary<int, Customer>	0
3921561	3921518	how to get copy file progress	CopyFileCallbackAction callback(\n    FileInfo source, FileInfo destination, object state, \n    long totalFileSize, long totalBytesTransferred)\n{\n  Console.WriteLine("Copied so far {0}%",\n      totalBytesTransferred * 100 / totalFileSize);\n}\n\nFileRoutines.CopyFile(src, dest, options, callback)	0
2917253	2917239	C# modify a config file for a windows service	Configuration cfg = ConfigurationManager.OpenExeConfiguration("your path here");\n// perform unspeakable acts upon cfg using your GUI\ncfg.Save();	0
15780652	15742948	Can i use RouteLink to change the parameter of the route depending on link clicked, MVC3	routes.MapRoute(\n        "Default", // Route name\n        "{controller}/{action}/{pagename}", // URL with parameters\n        new { controller = "Home", action = "Menu", PageName="Index" } // Parameter defaults\n    );	0
21080360	21080306	Variable text Replace	string extraction = text.SubString(text.IndexOf("Password:"), 34)	0
19660910	19660265	How to share a static method amongst several class	class Program\n{\n    static void Main(string[] args)\n    {\n        var types = new[] {typeof(A), typeof(B), typeof(C)};\n        foreach (var type in types)\n        {\n            var attribute = type.GetCustomAttribute<NameAttribute>();\n            if (attribute != null)\n                Console.WriteLine(attribute.Name);\n        }\n        Console.ReadLine();\n    }\n\n    public sealed class NameAttribute : Attribute\n    {\n        public string Name { get; private set; }\n\n        public NameAttribute(string name)\n        {\n            Name = name;\n        }\n    }\n\n    [Name("A Name")]\n    public class A\n    {\n    }\n\n    [Name("B Name")]\n    public class B\n    {\n    }\n\n    [Name("C Name")]\n    public class C\n    {\n    }\n}	0
3599129	3598969	checking if gridview has a selected item	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Col1");\n        dt.Columns.Add("Col2");\n        dt.Columns.Add("Col3");\n\n        for (int i = 0; i < 20; i++)\n        {\n            DataRow dr = dt.NewRow();\n            dr["Col1"] = string.Format("Row{0}Col1", i + 1);\n            dr["Col2"] = string.Format("Row{0}Col2", i + 1);\n            dr["Col3"] = string.Format("Row{0}Col3", i + 1);\n            dt.Rows.Add(dr);\n        }\n\n        GridView1.DataSource = dt;\n        GridView1.DataBind();\n\n        SetButtonState();\n    }\n}\n\nprotected void GridView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    SetButtonState();\n}\n\nprivate void SetButtonState()\n{\n    btactivate.Visible = GridView1.SelectedIndex > -1;\n    btdeactivate.Visible = GridView1.SelectedIndex > -1;\n}	0
30775711	30775474	Simulate the use of a website with a client	public void SearchForWatiNOnGoogle()\n{\n  using (var browser = new IE("http://www.google.com"))\n  {\n    browser.TextField(Find.ByName("q")).TypeText("WatiN");\n    browser.Button(Find.ByName("btnG")).Click();\n\n    bool contains = browser.ContainsText("WatiN");\n  }\n}	0
9618181	9617887	autocapture values from a textbox based on some characters 	string Name=Regex.Match(SubjectString, "@(.*?) ").Groups[1].Value;\nstring Comp=Regex.Match(SubjectString, "#(.*?) ").Groups[1].Value;\nstring Priort=Regex.Match(SubjectString, "!(.*?) ").Groups[1].Value;	0
6857196	6857155	How can I concatenate a where clause using OR on LINQ?	-- Get all the package IDs you want to select on.\nvar packIDs = from pack in Packages\n    select pack.ID;\n\n-- Return all results where the ID is in the package ids above.\nfilteredResults = from result in filteredResults\n    where packIDs.Contains(result.ID)\n    select result;	0
11693488	11693142	How to set a foreign key value in EF?	BudgetLineItem actualLi = new BudgetLineItem();\nactualLi.YearId = be.lu_FiscalYear.FirstOrDefault(t => t.Year == actualYear);\nactualLi.TypeId = be.lu_Type.FirstOrDefault(t => t.Name == "Actual");\nactualLi.Dept = be.lu_Department.FirstOrDefault(t => t.Name == DeptName)\nactualLi.LineItemId = be.lu_LineItem.FirstOrDefault(t => t.Name == revenueType)\nactualLi.Amount = actualAmount;\nbe.AddToBudgetLineItems(actualLi);\nbe.SaveChanges();	0
29384979	29384639	Unit testing in C# of private-static method accepting other private-static method as a delegate parameter	[TestMethod]\n        public void MyTest()\n        {\n            PrivateType privateType = new PrivateType(typeof(MyClass));\n            Type[] parameterTypes =\n                    {\n                        typeof(int),\n                        typeof(int)\n                    };\n            var myPrivateDelegateMethod = typeof(MyClass).GetMethod("MyDelegateMethod", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);\n            var dele = myPrivateDelegateMethod.CreateDelegate(typeof(Func<int, int, int>));\n            object[] parameterValues =\n                        {\n                            33,22,dele\n                        };\n            string result = (string)privateType.InvokeStatic("MyMethodToTest", parameterValues);\n            Assert.IsTrue(result == "result is 55");\n        }	0
16312830	16270225	Assign indices to a range of values	private int step = 3;\nint StepDivider (int value, int maximum) {\n  return value / (maximum / step);\n}	0
21673424	21673300	How to instantiate a generic class with an abstract constraint in C#	public interface IThingOwner<out ThingType> where ThingType : ThingBase { }\n\npublic class ThingOwner<ThingType> : IThingOwner<ThingType>\n    where ThingType : ThingBase\n{\n\n}\n\n\nIThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>();	0
31383454	31382968	How to perform word search using LINQ?	string[] filters = SearchKey.ToLower().Split(new[] { ' ' });\nobjSuppliersList = (from x in objSuppliersList\n                    where filters.All(f => x.SupplierName.ToLower().Contains(f))\n                    select x).ToList();	0
7015506	7014902	Load XML in Isolated Storage	if (!storage.FileExists("Achievements.xml"))\n    using (Stream stream = storage.OpenFile("Achievements.xml", FileMode.Create, FileAccess.Write))\n    {\n        XDocument xml = XDocument.Load("Achievements.xml");\n        xml.Save(stream,SaveOptions.None);\n    }	0
29415980	29415840	c# compare date time dates with time-span parameter	using System;\n\npublic class Program\n{\n    public static void Main()\n    {\n        DateTime dt = new DateTime();\n        DateTime dt2 = new DateTime();\n\n        dt = DateTime.Now;\n        dt2 = dt.AddDays(20);\n\n\n        TimeSpan ts = dt2.Subtract(dt);\n\n        Console.WriteLine(dt.ToString());\n        Console.WriteLine(dt2.ToString());\n\n        if(ts.Days > 30)\n        {\n        Console.WriteLine("It has been at least a month since last check up");\n        }\n        else\n        {\n            Console.WriteLine("It has been "+ ts.Days+" days since last check up");\n        }\n\n    }\n}	0
19165533	19165320	Retrieve only files from previous day	//gets all files in source directory & moves to destination directory(archive)\n        foreach (var file in new DirectoryInfo(sourceDir).GetFiles(pattern))\n        {\n            DateTime dt = File.GetCreationTime(file.FullName);\n\n            if (dt >= DateTime.Today.AddDays(-1) && dt < DateTime.Today)\n            {\n                file.MoveTo(Path.Combine(destDir, file.Name));\n            }\n        }	0
2584550	2584107	How to write linq query in Entity Framework but my table includes foreign key?	genSatisCtx.AddToKartlar(kartlar);\ngenSatisCtx.SaveChanges();\nint newKartlarID = kartlar.KartID;//kartID or whatever you call your primary key\nreturn newKartlarID;	0
16073787	16073753	Initialize an array of a class in a constructor	private Car[] carLot = new Car[size];\npublic Car[] CarLot\n{\n     get { return carLot; }\n     set { carLot = value; }\n}	0
26246450	26246266	How to display a value from a ComboBox in a TextBox?	void cmbCourse_onSelectedIndexChanged(object sender,EventArgs e) {\nyourTextBoxName.Text=CMB_COURSE.SelectedItem.ToString();}	0
6682727	6682569	C# Override OnValidating to support null value but breaks Data Binding	// Add binding\nvar b = new Binding("Text", myDataSource, "BoundProperty");\nb.Parse += OnNullableTextBindingParsed;\nmyTextBox.DataBindings.Add(b);\n\n\n// Sample parse handler\nprivate void OnNullableTextBindingParsed(object sender, ConverterEventArgs e)\n{\n    if (e.Value == String.Empty) e.Value = null;\n}	0
23764698	23683184	Enable/Disable a button	linkButton1.get_element().style.display="inline-block";	0
13840064	13839865	How to parse my json string in C#(4.0)using Newtonsoft.Json package?	foreach (var data in dynObj.quizlist)\n{\n    foreach (var data1 in data.QUIZ.QPROP)\n    {\n        Response.Write("Name" + ":" + data1.name + "<br>");\n        Response.Write("Intro" + ":" + data1.intro + "<br>");\n        Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");\n        Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");\n        Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");\n        Response.Write("Noofques" + ":" + data1.noofques + "<br>");\n\n        foreach (var queprop in data1.QUESTION.QUEPROP)\n        {\n            Response.Write("Questiontext" + ":" + queprop.questiontext  + "<br>");\n            Response.Write("Mark" + ":" + queprop.mark  + "<br>");\n        }\n    }\n}	0
17383005	17382972	How to Safely Access Property of Object	Control ctrl = sender as Control;\nif (ctrl != null)\n    MessageBox.Show(ctrl.Tag.ToString());	0
18888737	18887063	Changing cell background color based on two cell data value in Datagridview	for (int n = 0; n < (dataGridView1.Rows.Count - 1); n++)\n            {\n                double i = Convert.ToDouble(dataGridView1.Rows[n].Cells["tamount"].Value.ToString().Replace('.', ','));\n                double j = Convert.ToDouble(dataGridView1.Rows[n].Cells["paymentamount"].Value.ToString().Replace('.', ','));\n                double total = i - j;\n                if (total >= 1)\n                {\n                    dataGridView1.Rows[n].Cells["tamount"].Style.BackColor = Color.LightPink;\n                    dataGridView1.Rows[n].Cells["paymentamount"].Style.BackColor = Color.LightPink;\n\n                }\n                else\n                {\n                    dataGridView1.Rows[n].Cells["tamount"].Style.BackColor = Color.LightGreen;\n                    dataGridView1.Rows[n].Cells["paymentamount"].Style.BackColor = Color.LightGreen;\n                }\n\n            }	0
15270474	15269715	Call to HttpWebRequest from a Command in a ViewModel (MVVM)	private void GetNewsResponseCallback(IAsyncResult asynchronousResult)\n    {\n        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;\n\n        // End the operation\n        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);\n        Stream streamResponse = response.GetResponseStream();\n\n        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObservableCollection<NewsSerializer>));\n        var res = (IList<NewsSerializer>)ser.ReadObject(streamResponse);\n\n        News.Clear();\n        foreach(var item in res)\n        {\n            News.Add(item);\n        }\n    }	0
21324682	21324518	How to get first username in database with linq?	Database1Entities db = new Database1Entities();\nvar YourFirstUser = db.tblMembers.OrderBy( u => u.CreatedTime).Select( u => u.UserName).FirstOrDefault();	0
19423511	19423282	Putting in ValueMember and getting ValueMember out of Listbox	for (int i = 0; i < lb_Chosen.Items.Count; i++) \n{ \n   MessageBox.Show((lb_Chosen.Items[i] as YourAccountClass).ID.ToString()); \n}	0
26845257	26839653	Get public and private key of an encrypted app.config	key.Result	0
3647956	3647942	Listbox in reverse order (template)	var sortedItems =\n            from item in myObservableCollection\n            orderby item.Score descending\n            select item;	0
23243206	23243002	How Do You Programmatically Go To The End Of The A NotePad File If Opened By A Windows Form Application	SendKeys.Send("^{END}");	0
245388	245369	How do I get an array of repeated characters from a string using LINQ?	String text = "dssdfsfadafdsaf";\nvar repeatedChars = text.ToCharArray().GroupBy(x => x).Where(y => y.Count() > 1).Select(z=>z.Key);	0
24395481	24395457	Convert String Extension to Linq	return (1 + s.Take(Pos).Count(c => c == '\n'));	0
12405139	12405080	How to have DLL specific config file?	var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);\nstring dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;	0
15040534	15032238	Silverlight is ignore the [Required] Data annotation	Validator.ValidateProperty(valueToValidate, \n    new ValidationContext(this, null, null) { MemberName = "MyProperty" } );	0
28936962	28936841	How do i add an Edge to a graph which is a List<list<int>>?	graph[u].Add(v);\ngraph[v].Add(u);	0
13209176	13208996	evade deleted row of dataset in database table	foreach (DataRow row in ds.Tables["Table_Name"].Rows)\n        {\n            if (row.RowState != DataRowState.Deleted)\n            {\n                if (row.RowState == DataRowState.Added)\n                { \n                    // Perform insertion in to database\n                }\n                if (row.RowState == DataRowState.Modified)\n                { \n                    // perform updation in to databse\n                }\n            }\n        }	0
28035355	28035220	Validate to ensure that text has been entered in a text box before pressing a button that moves them to a new form	private void button1_Click(object sender, EventArgs e)\n{\n    if (txtName.Text.Length == 0)\n    {\n        MessageBox.Show("Please enter a name!");\n        return;\n    }\n    File.AppendAllText(@"..\..\..\Files\playerdetails.txt", txtName.Text);\n    MessageBox.Show("You are now ready to play");\n    Form1 myForm1 = new Form1();\n    myForm1.Show();\n}	0
9047030	9046978	Returning interface but concrete may have properties not on the interface, can I get them with a cast?	if(obj is Class1) {	0
30791885	30791592	Is there a way to create a common event?	public partial class Form1 : Form, IMessageFilter\n{\n    public Form1()\n    {\n        InitializeComponent();\n        Application.AddMessageFilter(this);\n    }\n\n    public bool PreFilterMessage(ref Message m)\n    {\n        if (m.Msg == 0x0201) // This is left click\n        {\n            var ctrl = Control.FromHandle(m.HWnd);\n            if (ctrl is Button)\n                Debug.WriteLine(ctrl.Name);\n        }\n        return false;\n\n    }\n}	0
16363704	16363459	Is it possible to use Actions in an interface with add/remove?	public event Action MyAction\n{\n    add \n    { \n         SomeLibraryClass.StaticAction += value;\n    }\n    remove\n    { \n         SomeLibraryClass.StaticAction -= value;\n    }\n}	0
9740487	9739944	ASP.NET textbox validation with hebrew input	[??????????????????????????\s\.]*	0
34003926	34003882	Why can a read only property be assigned via constructor?	class Person\n{\n    private readonly string _name;\n\n    // Old school: public string Name { get { return _name; } }\n    public string Name => _name; \n\n    public Person(string name)\n    {\n        _name = name;\n    }\n}	0
12784671	12784550	Uploading a WebImage to FTP	byte [] fileContents = photo.GetBytes();\nrequest.ContentLength = fileContents.Length;                       \n\nStream requestStream = request.GetRequestStream();\nrequestStream.Write(fileContents, 0, fileContents.Length);\nrequestStream.Close();	0
10011107	10011079	Round double to top - C#	double roundedUp = Math.Ceiling(number);	0
18084169	18083978	Reading data from SQL server "no data present" error message	SqlCommand("SELECT * FROM dbo.b_Pulp_PI_Forte WHERE keyprinter_datetime <  '" + GlobalVariables.Date + "'");	0
2941444	2941441	How to separate the year from a birthdate?	DateTime parsed = DateTime.ParseExact(birthDate, "MM/dd/yy", null);\nstring dateNoYear = parsed.ToString("MM/dd");\nstring year = parsed.ToString("yy");	0
14303146	14302915	How can I create a lock with Mutex?	private DateTime lastTap;\n\nprivate void Image_Tap_1(...)\n{\n    var now = DateTime.Now;\n\n    if ((now - lastTap).TotalSeconds < 3)\n    {\n        return;\n    }\n\n    lastTap = now;\n\n    // More than 3 seconds since last tap\n    ...\n}	0
421602	421516	How to write c# service that I can also run as a winforms program?	static void Main(string[] args)\n{\n    Guts guts = new Guts();\n\n    if (runWinForms)\n    {\n        System.Windows.Forms.Application.EnableVisualStyles();\n        System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);\n\n        FormWrapper fw = new FormWrapper(guts);\n\n        System.Windows.Forms.Application.Run(fw);\n    }\n    else\n    {\n        ServiceBase[] ServicesToRun;\n        ServicesToRun = new ServiceBase[] { new ServiceWrapper(guts) };\n        ServiceBase.Run(ServicesToRun);\n    }\n}	0
1969985	1969977	how would I peform a SHA1 hash on a file?	using (FileStream stream = File.OpenRead(@"C:\File.ext"))\n{\n    using (SHA1Managed sha = new SHA1Managed())\n    {\n        byte[] checksum = sha.ComputeHash(stream);\n        string sendCheckSum = BitConverter.ToString(checksum)\n            .Replace("-", string.Empty);\n    }\n}	0
2415053	2415033	How do you generate a user defined amount of prime numbers?	x < numberOfPrimes	0
34189124	34188981	Async method result arrive too late so it return a wrong values	var r = await oneMoreAsyncCall()\nif (r.IsCompleted == true)\n{                   \n    return Request.CreateResponse(HttpStatusCode.OK, someData); // Hit second!\n}	0
26441941	26438533	Make DraggablePoint Unmoveable on chartplotter (Dynamic Data Display) C#	Point p = new Point(x1, y1);\nvar globalPoint = new DraggablePoint(p);\n\nglobalPoint.PositionChanged += (s, e) => \n{ \n    globalPoint.Position = p; \n};	0
17255058	17255024	C# Too many connections in MySQL	string commandLine = "SELECT * FROM Table WHERE active=1";\ncommandLine = commandLine.Remove(commandLine.Length - 3);\nusing(MySqlConnection connect = new MySqlConnection(connectionStringMySql))\nusing(MySqlCommand cmd = new MySqlCommand(commandLine, connect))\n{\n    connect.Open();\n    using(SqlDataReader msdr = cmd.ExecuteReader())\n    {\n        while (msdr.Read())\n        {\n            //Read data\n        }\n    }\n} // Here the connection will be closed and disposed.  (and the command also)	0
12393318	12393297	How can I get the correct enum Value from an int c#	MyEnum m = (MyEnum)((int)otherEnum);\n\n\n  var en = (StringSplitOptions)SeekOrigin.Begin;	0
13937273	13937247	How do I check if DataRow contains no nulls	if (dc.ColumnName != "id" && dr[dc] == DBNull.Value)	0
8389292	8389084	Is there a way to not return a value from last part of a ternary operator	namespace Blah\n{\npublic class TernaryTest\n{\npublic static void Main(string[] args)\n{\nbool someBool = true;\nstring someString = string.Empty;\nstring someValue = "hi";\nobject result = null;\n\n// if someBool is true, assign someValue to someString,\n// otherwise, effectively do nothing.\nresult = (someBool) ? someString = someValue : null;\n} // end method Main\n} // end class TernaryTest\n} // end namespace Blah	0
27591532	27591193	How to add button click to show next item from database	protected void Button2_Click(object sender, EventArgs e)\n{\n            int i = ViewState["cnt"]!=null? (int) ViewState["cnt"]:1;\n            i = i + 1;\n            TextBox1.Text = GridView1.Rows[i].Cells[1].Text;\n            TextBox2.Text = GridView1.Rows[i].Cells[2].Text;\n            TextBox3.Text = GridView1.Rows[i].Cells[31].Text;\n            TextBox4.Text = GridView1.Rows[i].Cells[5].Text;\n            ViewState["cnt"] = i;\n}	0
8139391	8054359	Keep div displayed on postback	if(campo.value == "NO")\n   {               \n      document.getElementById("<% =hidHiddenField.ClientID %>").value = "SI";  \n   }\n   else\n   {\n      document.getElementById("<% =hidHiddenField.ClientID %>").value = "NO";\n   }	0
10549701	10549640	How to set CommandTimeout for DbContext?	public class YourContext : DbContext\n{\n  public YourContext()\n    : base("YourConnectionString")\n  {\n    // Get the ObjectContext related to this DbContext\n    var objectContext = (this as IObjectContextAdapter).ObjectContext;\n\n    // Sets the command timeout for all the commands\n    objectContext.CommandTimeout = 120;\n  }\n}	0
7170853	7170798	Disabling a button doesn't fire click event on server side	function disableButton(button) { \n    button.disabled = true; \n    __doPostBack(<%= btnProcessPayment.ClientID %>,'');   // need to manually submit\n    return true; \n}	0
2424357	1082625	Windows Mobile: using phone's camera with C#	string originalFileName;\n    using (CameraCaptureDialog dlg = new CameraCaptureDialog()) {\n        dlg.Mode = CameraCaptureMode.Still;\n        dlg.StillQuality = CameraCaptureStillQuality.Low;\n        //dlg.Resolution = new Size(800, 600);\n        dlg.Title = "Take the picture";\n        DialogResult res;\n        try {\n            res = dlg.ShowDialog();\n        }\n        catch (Exception ex) {\n            Trace.WriteLine(ex);\n            return null;\n        }\n\n        if (res != DialogResult.OK)\n            return null;\n        this.Refresh();\n        originalFileName = pictureFileName = dlg.FileName;\n    }	0
2489636	2456496	Programmatically trigger a copy or paste in c#	SendKeys.Send("^c");	0
21838166	21838083	How To Convert The String (X cm) To INT (X) X = Number	Convert.ToInt32(Form1.sendproductprice1.Split(' ')[0])*Convert.ToInt32(Form1.sendamount));	0
981786	981590	Having trouble rendering xhtml to page	XhtmlTextWriter xtw = XhtmlTextWriter(new TextWriter(Response.OutputStream));	0
27085747	27085497	C# XMLReader ReadString how to read everything include nested xml in an element?	List<string> bananas = new List<>string();\n string contents = string.Empty;\n    xmlr.ReadToFollowing("HTML");\n    do\n    {   \n        contents = xmlr.ReadInnerXML();\n        if(!string.IsNullOrEmpty(contents))\n        {        \n            bananas.Add(contents);  \n        }\n\n    }while(!string.IsNullOrEmpty(contents))	0
30404814	30404703	Getting data from selected dataGridView to string	if ( dataGridView1.SelectedRows.Count > 0)\n    {\n        string itemid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();\n        string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();\n        string description = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); \n    }	0
15205935	15205700	How to attach to COM event in Javascript	myComComponent.attachEvent("MyFirstEvent", myJavascriptHandler);	0
12462901	12462863	How do you implement Any<> to find something (preferably case insensitive) in the database?	db.PhotoAlbums.Where(b => b.NAME == inputName).ToList();	0
9414495	9414152	Get target of shortcut folder	namespace Shortcut\n{\n    using System;\n    using System.Diagnostics;\n    using System.IO;\n    using Shell32;\n\n    class Program\n    {\n        public static string GetShortcutTargetFile(string shortcutFilename)\n        {\n            string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);\n            string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);\n\n            Shell shell = new Shell();\n            Folder folder = shell.NameSpace(pathOnly);\n            FolderItem folderItem = folder.ParseName(filenameOnly);\n            if (folderItem != null)\n            {\n                Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;\n                return link.Path;\n            }\n\n            return string.Empty;\n        }\n\n        static void Main(string[] args)\n        {\n            const string path = @"C:\link to foobar.lnk";\n            Console.WriteLine(GetShortcutTargetFile(path));\n        }\n    }\n}	0
2367543	2366969	CreateFile fails on opening fs driver	\\.\FsFilter	0
13552663	13548293	Change row value's of the Gtk.ListStore	TreeIter iter; TreeModel model;\n\nif( MyTreeView.Selection.GetSelected(out model, out iter))\n    TreeViewListStore.SetValues(iter,"column1_1","column1_2","column1_3");	0
7839518	7838582	Calculate top-left and bottom right of a Rectangle GIven Origin, Direction & Size	Vector3[] vertices(Vector2 size, Vector3 center, Vector3 normal, Vector3 tangent)\n    {\n        Vector3 planeY = Vector3.Normalize(Vector3.Cross(normal, tangent));\n        Vector3 planeX = Vector3.Normalize(Vector3.Cross(normal, planeY));\n\n        planeX *= size.X / 2;\n        planeY *= size.Y / 2;\n\n        vertices = new Vector3[]\n        {\n            (center - planeX - planeY),\n            (center - planeX + planeY),\n            (center + planeX - planeY),\n            (center + planeX + planeY),\n        };\n        return vertices;\n    }	0
22490170	22283493	What are the options for saving data locally upon a failed Postgres SQL connection	var backupfile = String.Format("ModifiedGridTotals_Backup_{0}.xml", DateTime.Now.ToString("d-MMM-yyyy-HHmmss"));\n var serializer = new XmlSerializer(typeof(List<GridTotal>));\n serializer.Serialize(new XmlTextWriter(backupfile, Encoding.UTF8), ModifiedGridTotals);	0
18555063	18553691	Metro getting the base64 string of a StorageFile	private async Task<string> StorageFileToBase64(StorageFile file)\n{\n    string Base64String = "";\n\n    if (file != null)\n    {\n        IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);\n        var reader = new DataReader(fileStream.GetInputStreamAt(0));\n        await reader.LoadAsync((uint)fileStream.Size);\n        byte[] byteArray = new byte[fileStream.Size];\n        reader.ReadBytes(byteArray);\n        Base64String = Convert.ToBase64String(byteArray);\n    }\n\n    return Base64String;\n}	0
585822	585812	Using Xpath With Default Namespace in C#	XmlElement el = ...; //TODO\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(\n    el.OwnerDocument.NameTable);\nnsmgr.AddNamespace("x", el.OwnerDocument.DocumentElement.NamespaceURI);\nvar nodes = el.SelectNodes(@"/x:outerelement/x:innerelement", nsmgr);	0
15336764	15336722	Filter begin and end characters from a string	var input = "v03400216000000001FC5H240108206B-RAMBOX=[03]";\nvar version = input.Substring(1, 8);	0
1349687	1349674	Using C# extension methods from managed C++/CLI	IPAddressExtensions::GetSubnetMask(address);	0
14297688	14297592	How to get selected item from LoopingSelector Windows Phone	TypeOfTheItem s= (TypeOfTheItem)selectorString.DataSource.SelectedItem;	0
105793	105770	.NET String.Format() to add commas in thousands place for a number	String.Format("{0:n}", 1234);\n\nstring.Format("{0:n0}", 9876); // no digits after the decimal point.	0
5542646	5542610	Access folders in root directory	string imageUrl = HttpContext.Current.Server.MapPath("~/images/img1.bmp");	0
3803031	3803004	C# Parsing hidden fields with the HTML Agility Pack	var value = docroot.SelectSingleNode("//input[@type='hidden' and @name='foo']")\n                .Attributes["value"].Value;	0
4109540	4109500	How to restrict T to value types using a constraint?	public static Chart PopulateInto<T>(List<T> yAxis, List<int> xAxis)\n{\n    // Do stuff here\n}\n\npublic static Chart PopulateInto<T>(List<T> yAxis, List<decimal> xAxis)\n{\n    // Do stuff here\n}	0
28278340	28278156	check that string key entered correctly in the entry point of c# program?	static void Main(string[] args)\n{\n    if (args.Length != 2)\n    {\n        Console.WriteLine("Use: app.exe -c config.xml");\n        return;\n    }\n\n    if (args[0] != "-c")\n    {\n       Console.WriteLine("wrong, please input key '-c' for xml file.");\n       return; \n    }\n}	0
5155235	5155206	Is it possible to create one dimension array from two using LINQ?	string[] dirFiles = dirs.SelectMany(Directory.GetFiles).ToArray();	0
1231408	1231374	How to remove whitespace from an XmlDocument	XmlDocument doc = new XmlDocument();\ndoc.PreserveWhitespace = false;\ndoc.Load("foo.xml");\n// doc.InnerXml contains no spaces or returns	0
3803720	3803657	Custom role provider cache troubleshooting	var isInRole = User.IsInRole("ABC_DEV")	0
9854016	9853983	How can I inherit all properties from all Base classes in C#	public class BigRedBird : Bird \n{ \n\n    public BigRedBird(Game game ,Rectangle area,Texture2D image) \n        : base(game) \n    { \n        // TODO: Construct any child components here \n        this.Position= ....\n\n    } \n    ..................... \n}	0
1530920	1530844	Regex to remove onclick="" attributes from HTML elements in ASP.NET C# (Server-side)	returnValue = \n    Regex.Replace(\n        returnValue,\n        @"(<[\s\S]*?) on.*?\=(['""])[\s\S]*?\2([\s\S]*?>)", \n        delegate(Match match)\n        {\n            return String.Concat(match.Groups[1].Value, match.Groups[3].Value);\n        }, RegexOptions.Compiled | RegexOptions.IgnoreCase);	0
15958583	13639890	Extract public key from an XML file with X509certificate?	var document = new XmlDocument();\n  document.LoadXml(txtXml.Text);\n  var cert = document.SelectSingleNode("X509Data/X509Certificate").InnerText;\n  /*...Decode text in cert here (may need to use Encoding, Base64, UrlEncode, etc) ending with 'data' being a byte array...*/ \n  var x509 = new X509Certificate2(data);	0
30004068	30004016	Generate XML file with subnodes from xsd file using c#	data.SalesInvoice = new [] { sales };	0
27334859	27278532	C# Passing a pointer of array to function starting at specific offset	using System.Runtime.InteropServices;\n\nnamespace MyDLL\n{\n    public class TestLib\n    {\n         [DllImport( "name_of_your_dll" )]\n        public static extern DoSomething( double p[] );\n    }\n}	0
9110824	9110732	Typecast object in class based on type in SET	public decimal Duration {get;set;}\npublic void SetDuration(object duration)\n{\n   if(duration is decimal)\n      Duration = (decimal)duration;\n   else if(duration is string)\n   { \n      Duration = decimal.Parse((string)duration);\n   }\n}	0
12511920	12511655	c#: WinForm : How to Prevent firing of EventHandlers while data is retrieved from backend	private void DisableAllHandlers()\n{\n    foreach (var control in this.Controls)\n    {\n       // use reflection\n    }\n}	0
27367759	27366315	How can i update a ListBox from a static class?	public class SuperClass \n{\n    public Arguments Args { get; set; }\n\n    public class Stat\n    {\n        public int DownloadCount { get; set; }\n    }\n\n    public class File\n    {\n        public int Id { get; set; }\n        public string Name { get; set; }\n        public List<Stat> SomeStats { get; set; }\n    }\n\n    public class Arguments \n    {\n        public ObservableCollection<File> Files { get; set; }\n    }\n}	0
26496396	26486175	Get index of last created page in SharePoint 2010 library	var wikiPages = ctx.Web.Lists.GetByTitle(listTitle);\nvar query = new CamlQuery\n                {\n                    ViewXml = "<View><Query><OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy></Query><RowLimit>1</RowLimit></View>"\n                };\nvar items = wikiPages.GetItems(query);\nctx.Load(items, icol => icol.Include(i => i.File));\nctx.ExecuteQuery();\nif (items.Count == 1)\n{\n    var pageFile = items[0].File; \n    Console.WriteLine(pageFile.Name);\n}	0
13946309	13946226	Programmatically generate and assign ComboBox DataSource	public class WeekDay\n{\n    public int Index { get; set; }\n    public string DayName { get; set; }\n}	0
7589862	7589812	How would I achieve a unique result using the Linq method syntax	SQLiteDataReader.GetString(1).Split(',').First().Trim()	0
19403777	19394806	Add a scroll event to repaint form	protected override void OnScroll(ScrollEventArgs se) {\n  base.OnScroll(se);\n  this.Invalidate();\n}	0
1627650	1551566	How to set the Icon property in code? How to understand the way it is done in XAML?	var window=new Window();\nvar uri=new Uri("pack://application:,,,/MyAssembly;component/Icon.ico",\n                 UriKind.RelativeOrAbsolute));\n// var uri=new Uri("icon.ico",UriKind.Relative) works just as well\nwindow.Icon = BitmapFrame.Create(uri);	0
2584204	2584169	What algorithm .Net use for searching a pattern in a string?	String.IndexOf	0
11786478	11786364	How to validate two out parameters do not point to the same address?	private static void AreSameParameter(out int one, out int two)\n{\n    one = 1;\n    two = 1;\n    one = 2;\n    if (two == 2)\n        Console.WriteLine("Same");\n    else\n        Console.WriteLine("Different");\n}\n\nstatic void Main(string[] args)\n{\n    int a;\n    int b;\n    AreSameParameter(out a, out a); // Same\n    AreSameParameter(out a, out b); // Different\n    Console.ReadLine();\n}	0
13660822	13660761	How to convert Turkish chars to English chars in a string?	var text = "??ST";\nvar unaccentedText  = String.Join("", text.Normalize(NormalizationForm.FormD)\n        .Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark));	0
12081615	10318693	C# - getting value of SelectedItem in Windows Forms application	int? nStoreNumber = cmbABSM.SelectedValue as int?;\nif (nStoreNumber==null)\n    return;	0
24221489	24221432	How to get a wav file to play in the background when a form is opened?	var player = new System.Media.SoundPlayer();\n     player.SoundLocation = @"D:\.....\some file.wav";\n     player.Load();\n     player.Play();	0
6368100	6368067	Load XML from Disk in C#	var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\nvar path = Path.Combine(dir, "Dump", "GetAddressById.xml")	0
6617152	6614061	Create timeout for blocking method call with TPL	Timer stopIdleTimeoutTimer = new Timer(\n    _ => client.StopIdle(),\n    null,\n    TimeSpan.FromMinutes(1),\n    TimeSpan.FromMilliseconds(-1));\n\nclient.Idle();\n\nstopIdleTimeoutTimer.Dispose();	0
23278405	23278368	Count how many children are contained inside a specific element	int cout = xmlDoc.Element("HomeTeam").Elements().Count();	0
33485370	33485224	Wiring all dynamically-created checkboxes to the same event handler	bool somethingChecked = false;\nforeach (CheckBox cb in pnlCamTicky.Controls.OfType<CheckBox>()) {\n  if (cb.Checked) {\n    somethingChecked = true;\n  }\n}\nchkAllCameras.Checked = somethingChecked;	0
15222140	15221937	Display running Process Icons in ListView	ListViewItem itemProcess = new ListViewItem(theprocess.ProcessName);\nitemProcess.SubItems.Add(theprocess.Id.ToString());\nlvAppProg.Items.AddRange(new ListViewItem[] {itemProcess});\nitemProcess.ImageList = imageListSmall;\nitemProcess.ImageIndex = YOURIMAGEINDEX	0
12073811	12071948	ListView Larget Icon vertical alignment of the images	public static void AddCenteredImage(ImageList list, Image image) {\n    using (var bmp = new Bitmap(list.ImageSize.Width, list.ImageSize.Height))\n    using (var gr = Graphics.FromImage(bmp)) {\n        gr.Clear(Color.Transparent);   // Change background if necessary\n        var size = image.Size;\n        if (size.Width > list.ImageSize.Width || size.Height > list.ImageSize.Height) {\n            // Image too large, rescale to fit the image list\n            double wratio = list.ImageSize.Width / size.Width;\n            double hratio = list.ImageSize.Height / size.Height;\n            double ratio = Math.Min(wratio, hratio);\n            size = new Size((int)(ratio * size.Width), (int)(ratio * size.Height));\n        }\n        var rc = new Rectangle(\n            (list.ImageSize.Width - size.Width) / 2,\n            (list.ImageSize.Height - size.Height) / 2,\n            size.Width, size.Height);\n        gr.DrawImage(image, rc);\n        list.Images.Add(bmp);\n    }\n}	0
11055413	11055258	How to use saveFileDialog for saving images in C#?	SaveFileDialog sfd = new SaveFileDialog();\nsfd.Filter = "Images|*.png;*.bmp;*.jpg";\nImageFormat format = ImageFormat.Png;\nif (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n{\n    string ext = System.IO.Path.GetExtension(sfd.FileName);\n    switch (ext)\n    {\n        case ".jpg":\n            format = ImageFormat.Jpeg;\n            break;\n        case ".bmp":\n            format = ImageFormat.Bmp;\n            break;\n    }\n    pictureBox1.Image.Save(sfd.FileName, format);\n}	0
26903943	26903828	How to overload a method that has params object[] as parameter	public Client FindClient(DbKey key)\n{\n  Context db = new Context();\n  Client result = Extensions.Find(db.Clients, key);\n  return result;\n}	0
29965942	29965637	SaveImage of ChartControl without display It in the screen	var theChart = new Chart();\n\n        //missing part\n        var chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();\n        theChart.ChartAreas.Add(chartArea1);\n\n        var theSeries = new Series("values");\n        theSeries.IsVisibleInLegend = false;\n        theChart.Series.Add(theSeries);\n        theSeries.Points.AddXY(1, 1);\n        theSeries.Points.AddXY(2, 2);\n        theSeries.Points.AddXY(3, 3);\n        theChart.SaveImage(@"D:\T?l?chargements\HiddenChart6.png", ChartImageFormat.Png);	0
210619	210607	Exact time between 2 DateTime?	DateTime dt1 = DateTime.Now;\nDateTime dt2 = DateTime.Now.AddDays(1);\n\nint diff = dt2.Subtract(dt1).TotalMinutes;	0
11358664	11358550	Check for equality of doubles in a list with a threshold	return (max > 0.01) || (min < -0.01);	0
27748545	27741063	Invalid cross-thread access in GeocodeQuery on Windows Phone	Dispatcher.BeginInvoke(async() => { ... });	0
25849060	25848904	Display for on target Monitor	frm.StartPosition = FormStartPosition.Manual;	0
22970284	22970131	Saving to xml file	xml.Save(PathToSaveTo);	0
25242660	25242177	NHibernate: Updating database multiple times in a transaction	Monitor monitor = monitorDao.Get(id);\nif (someStatus)\n{\n    using(var tx = session.BeginTransaction()) \n    {\n        monitor.status = 1;    // initially monitor.status == 0 in DB\n        tx.Commit();\n    }\n    // Point 1: some codes that might return or throw exception\n}\nelse\n{\n    using(var tx = session.BeginTransaction()) \n    {\n        monitor.status = 2;    // initially monitor.status == 0 in DB\n        tx.Commit();\n    }\n    // Point 2: some codes that might return or throw exception\n}\n\n using(var tx = session.BeginTransaction()) \n {\n      monitor.status = 3;\n      tx.Commit();\n }	0
28857220	28856224	Set top and bottom row border in excel 2010	ExFrame.Borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;	0
8197295	8197288	Create a string by appending lines?	StringBuilder builder = new StringBuilder();\nbuilder.AppendLine("Something happended");\nbuilder.AppendLine("Wow ");	0
6743113	6743083	how to detect a change in any excel cell in C#?	Excel.Application.SheetChange	0
13883513	13883392	Defining a variable inside a loop vs outside	{\n   int a;\n   ...\n}\n{\n   int b;\n   ...\n}	0
15134659	15073168	Add other dataset to display a combination chart	chart.AllSeries.Gallery = Gallery.Bar;\n\nchart.Series[2].Gallery = Gallery.Lines; // Third series is the Line	0
24456598	24455950	How do I get the Nth largest element from a list with duplicates, using LINQ?	public static IEnumerable<T> Foo<T>(this IEnumerable<T> source, int n)\n{\n    return source.GroupBy(x => x)\n        .OrderByDescending(group => group.Key)\n        .SkipWhile(group =>\n        {\n            n -= group.Count();\n            return n > 0;\n        })\n        .First();\n}	0
23522960	23522716	How to get method name using RegEx if parameters are split across multiple lines	private static readonly Regex MethodNamesExtractor = new Regex(@"^.*?(\S*)\({1}.*?ref\s*SqlConnection", RegexOptions.Singleline | RegexOptions.Compiled);	0
19837667	19829982	Scrapyd Post schedule.json from asp.net	public static string StartCraling(string URI, string Parameters)\n        {\n            WebRequest req = WebRequest.Create(URI);\n\n            req.ContentType = "application/x-www-form-urlencoded";\n            req.Method = "POST";\n\n            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);\n            req.ContentLength = bytes.Length;\n\n            using (Stream os = req.GetRequestStream())\n            {\n                os.Write(bytes, 0, bytes.Length); //Push it out there\n            }\n\n            using (WebResponse resp = req.GetResponse())\n            {\n                using (StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))\n                {\n                    return sr.ReadToEnd().Trim();\n                }\n            }\n        }	0
34176231	33993626	Accessing TextBox in inner radgrid of nested parent radgrid	var NestedradGrid = \n    ((TargetRadGrid.MasterTableView.Items[0].ChildItem as GridNestedViewItem)\n    .FindControl("NestedradGridID") as RadGrid);	0
21906064	21905768	Image resources in object array	Public object[,] CharacterImages =\n{       \n    {0, global::ProjectName.Properties.Resources.flower.bmp;}\n};	0
3895092	3892660	navigating dom in htmlagilitypack	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing HtmlAgilityPack;\n\nnamespace ConsoleApplication2\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = "http://www.stackoverflow.com";\n\n            HtmlWeb hw = new HtmlWeb();\n            HtmlDocument doc = hw.Load(s);\n\n            HtmlNodeCollection items = doc.DocumentNode.SelectNodes("//a[@class='question-hyperlink']");\n            foreach (HtmlNode item in items)\n            {\n                Console.WriteLine(item.InnerHtml);\n            }\n\n            Console.ReadLine();\n        }\n    }\n}	0
24140399	24139382	In sql, How to get the highest unique primary key record, out of multiple foreign key of same ID records	create  procedure [dbo].[usp_SelectAllAspirantDetails]\nas\nbegin\n\n\n;WITH CTE as\n(\nselect AID,ID,Qualification,InstituteName,YearOfPass,Percentage,\n       row_number () over (partition by AID order by ID desc) as rownum\nfrom AspirantQualification\n)\nSelect A.[AID]\n      ,A.[Name]\n      ,A.[Gender]\n      ,A.[ContactNo]\n      ,A.[EmailID]\n      ,A.[SkillSet]\n      ,A.[Experience]\n      ,A.[CompanyName] \n      ,Aq.[Qualification]\n      ,Aq.[InstituteName]\n      ,Aq.[YearOfPass]\n      ,Aq.[Percentage] \n      ,Aq.ID\nFROM [Aspirant] A \nLEFT JOIN CTE Aq ON A.AID=Aq.AID and Aq.rownum = 1\n\nend	0
26602359	26601947	Constructing a SOAP envelope using LINQ to XML	XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";\n\nXElement element = new XElement(soap + "Envelope", \n    new XAttribute(XNamespace.Xmlns + "SOAP-ENV", soap),\n    new XElement(soap + "Body"));	0
10459781	10459714	Reading password from TextBox	text = passwordBox.Text;	0
16631777	16631758	Importing Excel Data using Oledb	OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn);	0
20813161	20812854	how to use group by in linq	var query = db.News\n           .OrderBy(n => n.News_date)\n           .GroupBy(n => n.News_date, n => n.News_text);\n\nforeach (var g in query)\n{   \n     foreach(var t in g)\n     {\n         DataRow dr = dt.NewRow();\n         dr["News_text"] = t.ToString();\n         dr["News_date"] = g.Key.ToString("dd/MM/yyyy");\n         dt.Rows.Add(dr);\n     }\n}	0
10227862	10226890	Howto split genericList items with delimiter?	List<string> fileLines = File.ReadAllLines(fileName).Skip(4).ToList();\n      foreach (var item in fileLines)\n      {\n        values = item.Split(' ');\n        string[] vl=values[3].Substring(2).Trim().Split('\t');\n        sList1.Add(vl[0]);\n        sList2.Add(vl[1]);\n      }	0
2640162	2638905	XML deserialization doubling up on entities	List<Report>	0
28293054	28292785	How to set storedprocedure selected datas in a dataset and retrive it in a c# code?	public void bindgrid()\n    {\n\n        SqlConnection con = new SqlConnection(connStr);\n        SqlDataAdapter adapter = new SqlDataAdapter();\n        DataSet ds = new DataSet();\n        con.Open();\n        SqlCommand cmd = new SqlCommand(connStr, con);\n        cmd.CommandType = CommandType.StoredProcedure;\n        cmd.CommandText = "your sp";\n\n        cmd.ExecuteNonQuery();\n        adapter = new SqlDataAdapter(cmd);\n        adapter.Fill(ds);\n        Session["datasource"] = ds; // In case u want to store ur dataset in session and use it anywhere further\n        Gridview1.DataSource = ds.Tables[0];\n        Gridview1.DataBind();\n    }	0
1400564	1400464	Enumerating Application Pools in IIS	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.DirectoryServices;\n\nnamespace AppPoolEnum\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            DirectoryEntries appPools = \n                new DirectoryEntry("IIS://localhost/W3SVC/AppPools").Children;\n\n            foreach (DirectoryEntry appPool in appPools)\n            {\n                Console.WriteLine(appPool.Name);\n            }\n        }\n    }\n}	0
29238095	27783340	Uploading to S3 but nothing appears in the Web Console	PutObjectRequest request = new PutObjectRequest();\nrequest.BucketName = "WorkFolder"; \nrequest.Key = "CSV/" + date + "/" + file; // where file is the name of the file \nrequest.FilePath = s; \ns3client.PutObject(request);	0
540766	540746	How to get enum value by keyname	string name = GetFromDatabase("attribute");\nEnum.Parse(typeof(aa),name);	0
22967503	22967108	How to modify the name of a wcf service method's json result	[return: MessageParameter(Name = "MyServiceResponse")]	0
16558161	16518599	How to implement "--print-media-type" with c#?	string args = string.Format("--print-media-type \"{0}\" - ", Request.Url.AbsoluteUri);	0
7764628	7764565	Firing application exit on Windows shutdown	protected override void OnFormClosing(FormClosingEventArgs e)\n        {\n            try\n            {\n                ConfirmClose = true;\n                base.OnFormClosing(e);\n                if (e.CloseReason == CloseReason.WindowsShutDown)\n               {\n                    //Do some action\n               }\n            }\n          }\n            catch (Exception ex)\n            {\n\n            }\n        }	0
27618702	27618542	C# Chart change colour when a series point goes over a certain value	if (c.Series[s].YValuesPerPoint >= 255) c.Series[s].Color = Color.Red;	0
28469361	28469313	Deleting controls from a tabPage	var buttons = tabControl.SelectedTab.Controls.OfType<Button>()\nfor (int i = 0; i < buttons.Count; i++) {\n   tabControl.SelectedTab.Controls.Remove(buttons[i]);\n}	0
15937887	15934802	Authenticating in a web api vs just a normal web app	config.Routes.MapHttpRoute(\n            name: "DefaultApi",\n            routeTemplate: "api/{controller}/{id}",\n            defaults: new { id = RouteParameter.Optional }\n        );	0
15656364	15656058	How to check if the application has access to a Directory?	public static bool HasWritePermissionOnDir(string path)\n    {\n        var writeAllow = false;\n        var writeDeny = false;\n        var accessControlList = Directory.GetAccessControl(path);\n        if (accessControlList == null)\n            return false;\n        var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n        if (accessRules == null)\n            return false;\n\n        foreach (FileSystemAccessRule rule in accessRules)\n        {\n            if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue;\n\n            if (rule.AccessControlType == AccessControlType.Allow)\n                writeAllow = true;\n            else if (rule.AccessControlType == AccessControlType.Deny)\n                writeDeny = true;\n        }\n\n        return writeAllow && !writeDeny;\n    }	0
6414433	6414337	How do I set a max numeric value in a Devexpress TextEdit box?	\d|[0-2]\d|30	0
7377047	7377017	How to make the button_Click event opens the page in a pop-up window in ASP.NET?	Response.Write("<script type='text/javascript'>window.open('Page.aspx?ID=" + YourTextField.Text.ToString() + "','_blank');</script>");	0
29552957	29552373	Playing sounds in WPF as a resource	var notificationSound = new SoundPlayer(Timer.Properties.Resources.NotificationSound);\nnotificationSound.PlaySync();	0
27884993	27884979	How to use foreach loop on list except elements at some index?	foreach(var e in myList.Skip(1)){\n\n}	0
24767895	24767756	Enter key firing Gridview Row Command Event	protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    e.Row.Attributes.Add("onkeypress", "javascript:if (event.keyCode == 13) { \n        // do whatever you want with the event\n    } \n}	0
10192861	10192827	Using Indexof to check if string contains a character	var allDWords = box1.Text.Split(' ').Where(w => w.StartsWith("D"));\nbox2.Text = String.Join(" ", allDWords);	0
25091433	25091205	Window phone 8.1: Change Background Color of Button	button.Background = new SolidColorBrush(Windows.UI.Colors.Red);	0
8680930	8680898	How to programmatically check if a variable is approaching x?	double x = ...\ndouble someVariable = ...\n\n// define the precision you are working with\ndouble epsilon = 1e-6;\n\n// now test whether someVariable is approaching x\nif (Math.Abs(someVariable - x) < epsilon)\n{\n    // someVariable is approaching x given the precision you have defined\n}	0
29728576	29728523	how to delete one column and row from jagged array in c#	int[][] finalDists = dists.Where((arr, i)=>i!=2) //skip row#3\n                          .Select(arr=>arr.Where((item,i)=>i!=2) //skip col#3\n                                          .ToArray())\n                          .ToArray();	0
12476813	12476686	What is equivalent to clause between, for comparasion strings in LINQ or lambda expression of?	yourDataContext.Country.Where(c => c.Name >= "Argentina" && c.Name <= "Jamaica");	0
1265392	1265378	How do I add multiple Namespace declarations to an XDocument?	new XAttribute(XNamespace.Xmlns + "ns4", ns4),\n            new XAttribute(XNamespace.Xmlns + "ns3", ns3),\n            new XAttribute(XNamespace.Xmlns + "ns2", ns2),	0
31197897	31188740	Copying contents of downdown menu to database	protected void Button4_Click(object sender, EventArgs e)\n{\nInsertdata()\n}\n\npublic void Insertdata()\n{\nSqlConnection sc = new SqlConnection();\n        SqlCommand com = new SqlCommand();\n        sc.ConnectionString = ("Data Source=FRMDEVSQL03; Initial Catalog=VisualStudioTest; User ID=Aghosh; Password=SummerClerk");\n        sc.Open();\n        com.Connection = sc;\n        com.CommandText = (@"INSERT INTO ticket(person_created, category_id, summary, ticket_status) VALUES ('" + txtName.Text + "',  '" + Label5.selectedvalue + "', '" + txtName0.Text + "', '" + Label4.selectedvalue + "');");\n        com.CommandText = (@"INSERT INTO persons(LanID) VALUES ('" + txtName.Text + "');");\n        //com.CommandText = (@"INSERT INTO ticket(person_created, summary) VALUES ('" + txtName.Text + "','" + txtName0.Text + "');");\n        com.ExecuteNonQuery();\n        sc.Close();\n        Response.Redirect(Request.RawUrl);\n}	0
18537038	18477574	Can I use an extension method to add a column AND a foreign key constraint with Fluent Migrator?	public static ICreateTableColumnOptionOrWithColumnSyntax WithUser(this ICreateTableWithColumnSyntax tableWithColumnSyntax)\n{\n    return tableWithColumnSyntax\n        .WithColumn("UserId")\n            .AsInt32()\n            .Nullable()\n            .ForeignKey("Users", "Id");\n}	0
31730351	31680998	ListView - how to add item to the front of the list	collection.Insert(0, item);	0
1949309	1949273	How to have an exception define its own message in C#?	public FieldFormatException(Fields field, string value): \n        base(BuildMessage(field, value))\n    {\n    }\n\n    private static string BuildMessage(Fields field, string value)\n    {\n       // return the message you want\n    }	0
33603046	33601449	How to update XML file in C#?	string path = "path";\n        var element = "first_name";\n        var value = "Dev";\n\n        try\n        {\n            string fileLoc = path;\n            XmlDocument doc = new XmlDocument();\n            doc.Load(fileLoc);\n            XmlNode node = doc.SelectSingleNode("/NameList/personDetail/" + element);\n            if (node != null)\n            {\n                node.InnerText = value;\n            }\n            else\n            {\n                XmlNode root = doc.DocumentElement;\n                XmlElement elem;\n                elem = doc.CreateElement(element);\n                elem.InnerText = value;\n                root.AppendChild(elem);\n            }\n            doc.Save(fileLoc);\n            doc = null;\n        }\n        catch (Exception)\n        {\n\n        }	0
14381487	14381290	Media player c# playing from network	m_player = new MediaPlayer();\nm_player.Stop();\nm_player.Open(new Uri(path, UriKind.Relative));\nm_player.Play();	0
4707440	4707407	Creating a Grid - What is an efficient way to do this	List<List<IEntity>>	0
18626083	18625221	Change Format LeftIndent value	Word.Application	0
11373832	11368025	Resizing a DockPanel to DockZone height and width	function setDockPanelFill() {\n    var dockPanel = dockZone1.GetPanelByUID('dockPanel1');\n    dockPanel.SetHeight(dockZone1.GetHeight());\n    dockPanel.SetWidth(dockZone1.GetWidth());\n}	0
19549142	19548913	Random color text	static readonly IList<Color> myColors =\n        new[] { Color.Red, Color.Blue, Color.Green, Color.White, Color.Yellow };\nprivate void btnGelb_Click(object sender, EventArgs e)\n{\n    int summe = 0, z;\n    lblAnzeige.Text = " ";\n    while (summe <= 0)\n    {\n        z = r.Next(1, 6);\n        summe = summe + z;\n    }\n    lblAnzeige.Text += colors[summe - 1] + "\n";\n    lblAnzeige.ForeColor = myColors[Farbe.Next(myColors.Count)];\n}	0
1542893	1539134	ASP.NET Can not Change Visibility of a Formview control	protected void FormView1_DataBound(object sender, EventArgs e)\n{\n    if (FormView1.CurrentMode == FormViewMode.Edit)\n    {\n        btn_resolve = (Button)FormView1.FindControl("btn_resolve");\n        resolve.Visible = true;\n    }\n}	0
5116668	5116625	How can we declare Optional Parameters in C#.net?	public void ExampleMethod(int required, string optionalstr = "default string",\nint optionalint = 10)\n{\n}	0
14462040	14461452	Dynamically load user controls on button click, postback issue	protected void Page_Load(object sender, EventArgs e)\n{\n    if (IsUserControl)\n    {\n        CreateUserControlAllNews();        \n    }\n}\n\nprivate void CreateUserControlAllNews()\n{\n    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");\n    featuredProduct.ID = "1234";\n    plh1.Controls.Add(featuredProduct);\n}	0
13178607	13177551	Physical, Relative, Absolute and other paths	var paths = new[]\n{\n   @"C:\Temp",\n   @"\\Temp",\n   "Temp",\n   "/Temp",\n   "~/Temp",\n   "file://C:/Temp",\n   "file://Temp",\n   "http://something/Temp"\n};\n\nforeach (string p in paths)\n{\n   Uri uri;\n   if (!Uri.TryCreate(p, UriKind.RelativeOrAbsolute, out uri))\n   {\n      Console.WriteLine("'{0}' is not a valid URI", p);\n   }\n   else if (!uri.IsAbsoluteUri)\n   {\n      Console.WriteLine("'{0}' is a relative URI", p);\n   }\n   else if (uri.IsFile)\n   {\n      if (uri.IsUnc)\n      {\n         Console.WriteLine("'{0}' is a UNC path", p);\n      }\n      else\n      {\n         Console.WriteLine("'{0}' is a file URI", p);\n      }\n   }\n   else\n   {\n      Console.WriteLine("'{0}' is an absolute URI", p);\n   }\n}	0
8601529	8600365	Getting NewLine character in FreeTextBox control in Asp.net	char enter=(char)111;\ntemp= str.Replace(enter+"", "\n");	0
16249550	16249175	Add Data to gridview dynamically in ASp.net	DataRow row = new DataRow();             \n\nrow["columnName"] = textBox1.Text; \n\nDTable.Rows.Add(row);\n\ngvOrders.DataSource=Dtable;\ngvOrders.DataBind();	0
7045863	7045609	Iterate through selected gridview cells by row index	var q = dataGridView1.SelectedCells.OfType<DataGridViewCell>().OrderBy(x => x.RowIndex);	0
3188421	3188380	One Time initialization for Nunit	[SetUpFixture]	0
2811837	2811768	Issues querying google sitemap.xml with Linq to XML	XDocument xDoc = XDocument.Load(@"C:\Test\sitemap.xml");\nXNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";\n\nvar sitemapUrls = (from l in xDoc.Descendants(ns + "url")\n                    select l.Element(ns + "loc").Value);\nforeach (var item in sitemapUrls)\n{\n    Console.WriteLine(item.ToString());\n}	0
24291106	24257969	Matching ViewModel and View in MVVMCross	...\n xmlns:views="using:Cirrious.MvvmCross.WindowsStore.Views"\n ...\n<views:MvxStorePage	0
27070217	27069907	taking every subsequence in F#?	let subsequences words =\n    seq {\n        let len = Array.length words\n        for i = 1 to len - 1 do\n            for j = 0 to len - i do\n                yield words.[j..j+i-1]\n    }	0
5417496	5417367	.NET sending email attachment with custom Mime type	Mail.Attachment attach = New Mail.Attachment(attachmentData, New Mime.ContentType("application/x-EDIORDER"));	0
2398922	2398863	Tree View / File View Control for C#	private void fileView_ItemActivate(object sender, EventArgs e)\n    {\n        //Loop thru all selected items\n        foreach (ListViewItem item in ((BrowserListView)sender).SelectedItems)\n        {\n            //Do your stuuf here. MessageBox is only used for demo\n            MessageBox.Show(item.Text);\n        }\n    }	0
13495435	13491331	Using ch.ethz.ssh2 in a C# application	SshTransferProtocolBase tx = new Scp(_hostname, _username, _password);\nSshExec exec = new SshExec(_hostname, _username, _password);\n\ntx.Connect();\nexec.Connect();\n\nexec.RunCommand("sudo mount -o remount,rw /");\nexec.RunCommand("sudo rm /tmp/" + Path.GetFileName(sshTarget));\ntx.Put(sshSource.FullName, "/tmp/" + Path.GetFileName(sshTarget));	0
19604117	19603974	How to get number of seconds between two button clicks	static Stopwatch sw = new Stopwatch();\n\n\n    private void Start_Click(object sender, EventArgs e)\n    {\n        sw.Start();\n    }\n\n    private void stopButton_Click(object sender, EventArgs e)\n    {\n        sw.Stop();\n\n        TimeSpan ts = sw.Elapsed;\n\n        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", \n            ts.Hours, ts.Minutes, ts.Seconds,\n            ts.Milliseconds / 10);\n\n        MessageBox.Show("Elapsed time = " + elapsedTime);\n    }	0
19687109	19682626	c# console keeps on in process	Process consoleProcess = Process.Start(@"C:\Users\Krijn\Desktop\CarWorks\Parts\bin\Debug\Parts");\n\n// Do some stuff here...\n\nif (!consoleProcess.HasExited)\n{\n    // Terminate the process\n    consoleProcess.Kill();\n}\n\n// Wait until the process is really terminated.\nconsoleProcess.WaitForExit();	0
493055	493033	Regex: Why no group for every found item?	using System;\nusing System.Text.RegularExpressions;\n\nclass Test\n{\n    static void Main()\n    {\n        string text = \n"<i><b>It is noticeably faster.</b></i> <i><b>They take less disk space.</i>";\n        Regex pattern = new Regex(@"(</[b|i|u]>)+(\s*)(<[b|i|u]>)+");\n\n        Match match = pattern.Match(text);\n        foreach (Group group in match.Groups)\n        {\n            Console.WriteLine("Next group:");\n            foreach (Capture capture in group.Captures)\n            {\n                Console.WriteLine("  " + capture.Value);\n            }\n        }\n    }\n}	0
12352065	12351787	Linq-to-Entities, compare int values in different fields/columns and return max value	var queryParent = from row in tableParent     \n                      where row.Name == a\n                      select new \n                      {\n\n                         Parent = row.Name,\n                         status = \n                         (new int[]{row.int1,row.int2,row.int3,row.int4,\n                         row.int5,row.int6,row.int7,row.int8}).Max();\n                          ...\n\n                      };	0
15338884	15336497	Control no longer transparent after refresh	protected override void OnPaint(PaintEventArgs e)\n    {\n        if (ImageForBackGround != null)\n        {\n           e.Graphics.DrawImage(ImageForBackGround, new Point(0, 0));\n           this.SetStyle(ControlStyles.Opaque, true);\n\n        }\n    }	0
30000122	29999802	Similar Columns Relation in Entity Framework	dbEnteties.Products.Include(product => product.User);\n            dbEnteties.Products.Include(product => product.User1);	0
6454431	6454392	How to append two stringBuilders?	StringBuilder sb = new StringBuilder();\n        StringBuilder sb1 = new StringBuilder();\n        sb.Append(sb1.ToString());	0
9969921	9969861	IQueryable queried data count	this.lblSth.Text = new Repository<Sth>().GetAll().Count(p => p.PersonId == personId).ToString();	0
19683749	19682996	Datatable to html Table	public static string ConvertDataTableToHTML(DataTable dt)\n    {\n        string html = "<table>";\n        //add header row\n        html += "<tr>";\n        for(int i=0;i<dt.Columns.Count;i++)\n            html+="<td>"+dt.Columns[i].ColumnName+"</td>";\n        html += "</tr>";\n        //add rows\n        for (int i = 0; i < dt.Rows.Count; i++)\n        {\n            html += "<tr>";\n            for (int j = 0; j< dt.Columns.Count; j++)\n                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";\n            html += "</tr>";\n        }\n        html += "</table>";\n        return html;\n    }	0
5721392	5721363	proper way assign numer to elements in a List Collection	for(int i = 0; i < localList.Count;i++)\n{\n  Console.WriteLine( i + " " + localList[i]);\n}	0
4928200	4927329	Displaying array items in an irregular grid format	for (int i = 0; i <= 7; i++)\n            {\n                for (int j = 0; j <= 7; j++)\n                {\n                    grid[i, j].posX = i * 50;\n                    grid[i, j].posY = j * 50;                      \n\n                    if (i % 2 > 0)\n                    {\n                        grid[i, j].posY += 25;\n\n                        if (j == 7)\n                        {\n                            //remove grid[i, j] from array/sight\n                        }\n                }\n            }	0
5548857	5548800	From string fo DataSet without passing through HTML file	XmlTextReader reader = new XmlTextReader(new StringReader(validXml));\nDataSet aDataSet = new DataSet();\naDataSet.ReadXml(reader);	0
2565088	2565041	Task manager close is not detected second time in a WinForms Application	FieldInfo fi = typeof(Form).GetField("closeReason", BindingFlags.Instance | BindingFlags.NonPublic);\n\nfi.SetValue(this, CloseReason.None);	0
32235362	32235353	How to get UserCustomData in Kentico CMS	// instantiate a UserInfo object and populate it with data\n// by passing in the user's UserID.  Here I've passed in\n// the current user's UserID\nUserInfo ui = UserInfoProvider.GetUserInfo(CMSContext.CurrentUser.UserID);\n\n// retrieve data from the db by passing in the field name\nvar aVariable = ui.GetValue("FieldName");	0
10364044	10364008	Using reflection in C# to modify fields in a loop, extension method	MethodInfo mField = typeof(Dvd).GetMethod("Field");\nMethodInfo genericMethod = mField.MakeGenericMethod(new Type[] { fi.FieldType });\n\nGenericMethod.Invoke(aDvd,new Object[]{fi.Name});	0
30164140	30155565	Automapping only under specific namespace	.Mappings(m => m.AutoMappings.Add( AutoMap.AssemblyOf<T>()\n .IgnoreBase(typeof(BaseClass<>))	0
29231007	29230879	Change tab on button click	tabControl1.SelectedTab = DesiredTabPage;	0
717460	717454	Accessing Class members with Invoke from a different thread in C#	this.Invoke((MethodInvoker)delegate {\n    this.Memo.Text += txt + "\n";\n});	0
1323148	1322880	How to convert delegate from c# to vb.net?	Public Function Invoke(ByVal instance As Object, ByVal inputs As Object(), ByRef outputs As Object()) As Object Implements System.ServiceModel.Dispatcher.IOperationInvoker.Invoke\n        Dim staOutputs As Object() = Nothing\n        Dim retval As Object = Nothing\n        Dim thread As New Thread(AddressOf DoWork)\n        _instance = instance\n        _inputs = inputs\n        _staOutPuts = staOutputs\n        thread.SetApartmentState(ApartmentState.STA)\n        thread.Start()\n        thread.Join()\n        outputs = staOutputs\n        Return retval\n    End Function\n\n    Private Function DoWork() As Object\n        Return _innerInvoker.Invoke(_instance, _inputs, _staOutPuts)\n    End Function	0
19179977	19179703	Access Windows Form from a Folder	Application.Run(new Solution_Name.Folder_1.File());	0
5266462	5266439	How do I dynamiclly define this button?	var b = new Button { Text = "Hello World", Left = 100, Top = 100, Width = 50, Height = 25 };\nControls.Add(b);	0
20155525	20154313	How can I generate a list of datetime intervals that are in between two dates?	m: current time's minute \nnew minute part: m - (m % interval)	0
17931551	17931502	Reverse a list c#	List<Entities.Notification> ProgramList = EventData.ToList();\nProgramList.Reverse();\nListViewEvents.DataSource = ProgramList;\nListViewEvents.DataBind();	0
20838560	20838440	Passing parameters from WPF application to another WPF application?	var applicationPath = "Path to application B exe";\nvar process = new Process();\nprocess.StartInfo = new ProcessStartInfo(applicationExePath);\nprocess.Arguments = "/login=abc /password=def";\nprocess.Start();	0
27229422	26868974	Coordinate API OAuth2 authentication with refresh token	using Google.Apis.Auth.OAuth2;\n        using Google.Apis.Coordinate.v1;\n        using Google.Apis.Coordinate.v1.Data;\n        using Google.Apis.Services;\n        using Google.Apis.Util.Store;\n\n\n        using (var stream = new FileStream(@"client_secret.json", FileMode.Open, FileAccess.Read))\n        {\n            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,\n            new[] { CoordinateService.Scope.Coordinate },\n            "user", CancellationToken.None,new FileDataStore(folder));\n        }\n\n        var service = new CoordinateService(new BaseClientService.Initializer()\n        {\n        HttpClientInitializer = credential,\n        ApplicationName = "appname",\n        });\n\n        var list = await service.Location.List("teamid", "team@mailid.com", 2000).ExecuteAsync();	0
9398283	9372100	Non Transactional Execution Within a TransactionScope	SqlConnectionStringBuilder csBuilder = new SqlConnectionStringBuilder(existingCon.ConnectionString);\ncsBuilder.Enlist = false;\nSqlConnection newConnection = new SqlConnection(csBuilder.ConnectionString);     \nSqlCommand commandNotInTheTx = newConnection.CreateCommand();	0
30028984	30028922	IP Address validation in maskedTextBox C#	IPAdressBox.Mask = @"###\.###\.###\.###";	0
10946251	10946161	A complex generation of type at runtime	var stringType = Type.GetType("System.String");\nvar listType = typeof (List<>);\nvar stringListType = listType.MakeGenericType(stringType);\nvar list = Activator.CreateInstance(stringListType) as IList;\n\nlist.Add("Foo");\nlist.Add("Bar");\nlist.Add("Baz");	0
3392541	3392529	C# string.Contains using variable	if (keywords.Any(k => pslower.Contains(k)))	0
24917643	24917338	Day of the week for extended forecast	DayOfWeek day1 = DateTime.Now.DayOfWeek;\nDayOfWeek day2 = (DayOfWeek)((byte)(day1 + 1) % 7);\nDayOfWeek day3 = (DayOfWeek)((byte)(day2 + 1) % 7);\nDayOfWeek day4 = (DayOfWeek)((byte)(day3 + 1) % 7);\nDayOfWeek day5 = (DayOfWeek)((byte)(day4 + 1) % 7);\nDayOfWeek day6 = (DayOfWeek)((byte)(day5 + 1) % 7);\nDayOfWeek day7 = (DayOfWeek)((byte)(day6 + 1) % 7);\n\n// Rest of code omitted	0
23661236	23661217	Refactoring of the if statement	button1.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3].ToString();\nbutton3.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3 + 1].ToString();\nbutton4.Text = textForFoodButtons[FoodLevel + PlayersLevel * 3 + 2].ToString();	0
12753741	12753616	Working with List	var common = ListA.Intersect(ListB)\n    .Concat(\n        ListA.Where(a => \n             ListB.Any(\n                b => b.EndsWith("000") && \n                b.StartsWith(a.Substring(0, a.Length - 3))\n             )\n        )\n    );\nvar uncommon = ListA.Except(common);	0
21162004	21161149	Get Files In Project Folder	Properties.Resources	0
4626572	4625749	How to place PowerShell help file in GAC	PS> help about_module	0
2566095	2566050	How to remove Parent of Control	myListControl.Controls.Remove(myControlToRemove);	0
2404677	2404311	How to refactor logging in C#?	AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);	0
14260205	14260173	Split() string except for certain character combination	string[] result = Regex.Split(s, "(?<!Y)X");	0
23954755	23946811	Save current page to image	var canvas = document.getElementById("mycanvas");\nvar img    = canvas.toDataURL("image/png");\ndocument.write('<img src="'+img+'"/>');	0
22334164	22332863	How to use EntityFramework.BulkInsert?	using EntityFramework.BulkInsert.Extensions;	0
2966934	2966895	How can I get the bitmask value back out of an enum with the flag attribute in C#?	int newPermissions = (int)permissions.	0
6345169	6345078	Ideas for transferring data to Web Service	System.Runtime.Cache	0
8518267	8507374	AvalonEdit: Regex Capturing Groups in XSHD-File	RegexOptions.ExplicitCapture	0
8145583	6955710	Using Razor LINQ .Where() to find umbraco nodes with a certain date value	var values = new Dictionary<string,object>();\nvalues.Add("queryStartDate", DateTime.Parse(Request["queryStartDate"])) ;\nvalues.Add("queryEndDate", DateTime.Parse(Request["queryEndDate"])) ;\nvar results = Model.Children.Where("newsDate > queryStartDate && newsDate < queryEndDate", values);	0
25976408	25976041	Is it possible to do a "where <property> in <set>" query with Breeze js	var userIds = [1, 4, 78];\n\n    var predicate = breeze.Predicate("userId", "==", userIds[0]);\n    for (var i = 1; i < userIds.length; i++) {\n        var userId = userIds[i];\n        predicate = predicate.or(breeze.Predicate("userId", "==", userId));\n    }\n\n    breeze.EntityQuery\n        .from("Orders")\n        .using(this.manager)\n        .where(predicate)\n        .execute();	0
13776417	13776377	Regex match all inside brackets inside brackets?	PROCEDURE\s+\w+\s*\{(?:.*?\{.*?\})*.*?\}	0
26299996	26299336	Is it possible with Fixture to create a list of N objects?	/// <summary>\n/// This is a class containing extension methods for AutoFixture.\n/// </summary>\npublic static class AutoFixtureExtensions\n{\n    #region Extension Methods For IPostprocessComposer<T>\n\n    public static IEnumerable<T> CreateSome<T>(this IPostprocessComposer<T> composer, int numberOfObjects)\n    {\n        if (numberOfObjects < 0)\n        {\n            throw new ArgumentException("The number of objects is negative!");\n        }\n\n        IList<T> collection = new List<T>();\n\n        for (int i = 0; i < numberOfObjects; i++)\n        {\n            collection.Add(composer.Create<T>());\n        }\n\n        return collection;\n    }\n\n    #endregion\n}	0
4202302	4201816	Add context menu in a datagrid view in a winform application	int currentRowIndex;\n    private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        currentRowIndex = e.RowIndex;\n    }  \n    private void deleteToolStripMenuItem_Click(object sender, EventArgs e)\n    {    \n        dataGridView1.Rows.Remove(dataGridView1.Rows[currentRowIndex]);\n    }	0
25525926	25525874	How to cast nullable int to nullable short?	private static short? GetShortyOrNada(int? input)\n{\n    checked//For overflow checking\n    {\n        return (short?) input;\n    }\n}	0
9021927	9005029	XamlWriter.Save loses ItemsSource binding from a ListBox	[Bindable(true), CustomCategory("Content"),     DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic IEnumerable ItemsSource { get; set; }	0
16236509	16231241	Serial reading, only first 128 values taken into account	SerialPort1.Encoding = System.Text.Encoding.GetEncoding(28591)	0
1252379	1252371	initialize a class by string variable in c#?	System.Activator.CreateInstance(Type.GetType(className))	0
23713097	23712688	Constructing a linq query to get associations	var results = ProductCategory\n    .GroupBy(g => g.CategoryId)\n    .Select(new { \n        Category = g.Key, \n        Associations = g.Count() \n        })\n    .ToList();	0
3828323	3825791	Dependency injection / IoC in Workflow Foundation 4	public class MyBookmarkedActivity : NativeActivity\n{\n    protected override void CacheMetadata(NativeActivityMetadata metadata)\n    {\n        base.CacheMetadata(metadata);\n        metadata.AddDefaultExtensionProvider<MyExtension>(() => new MyExtension());\n    }\n\n    protected override void Execute(NativeActivityContext context)\n    {\n        var extension = context.GetExtension<MyExtension>();\n        extension.DoSomething();\n\n    }\n}	0
14430300	14430078	Update multiple pictureboxes at the same time	SuspendLayout();\n// set images to pictureboxes\nResumeLayout(false);	0
17894999	17439684	How to upload multiple files and insert them into database using ajaxfileupload	protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)<br>\n    {\n        string filepath = (Server.MapPath("~/Images/") +Guid.NewGuid()+ System.IO.Path.GetFileName(e.FileName));<br>\n        AjaxFileUpload1.SaveAs(filepath);<br>\n        string fl = filepath.Substring(filepath.LastIndexOf("\\"));<br>\n        string[] split = fl.Split('\\');<br>\n        string newpath = split[1];<br>\n        string imagepath = "~/Images/" + newpath;<br>\n        string Insert = "Insert into IMAGE_PATH (IMAGE_PATH) values (@IMAGE_PATH)";<br>\n        SqlCommand cmd = new SqlCommand(Insert, con);<br>\n        cmd.Parameters.AddWithValue("@IMAGE_PATH", newpath);<br>\n        con.Open();<br>\n        cmd.ExecuteNonQuery();<br>\n        con.Close();<br>\n        cmd.Dispose();<br>\n\n    }	0
8975493	8975464	Install SQL Server Express from WinForms on Button Click	Process.Start()	0
2037363	2016992	Custom Control's Controls.Count Zero	var htmlString = new StringBuilder();\nvar mywriter = new HtmlTextWriter(new StringWriter(htmlString));\nbase.RenderControl(mywriter);	0
9533754	9533722	Algorithmic analysis:Random Number	RandomNum()	0
32061104	32060882	Read Input on same line as another Read Input	using System;\n\nclass Test\n{\n    static void Main()\n    {\n        //split input by spaces into array\n        string[] name = Console.ReadLine().Split(); \n        Console.WriteLine("First name: " + name[0]);\n        Console.WriteLine("Last Name: " + name[1]);\n    }\n}	0
6409570	6409200	Change the background color of list item selected in check box list	for (int i = 0; i < chklstTelpas.Items.Count; i++)\n        {\n            if (chklstTelpas.Items[i].Selected)\n            {\n                chklstTelpas.Items[i].Attributes.Add("style", "background-color: red;");\n            }\n            else\n            {\n                chklstTelpas.Items[i].Attributes.Add("style", "background-color: white;");\n            }\n        }	0
4025029	4025007	Is there a way of using orderby in a forloop C#?	List<Item> myItems = new List<Item>();\n//load myitems\nforeach(Item i in myItems.OrderBy(t=>t.name))\n{\n //Whatever\n}	0
18272815	18270136	Cube seems to go in reverse direction as in script in Unity3D	transform.Translate(Camera.main.transform.forward * speed, Space.World);	0
10517117	10516997	Add Control Value before another Control value in C#	var prevIndex = mainPanel.Controls.IndexOf(previouslyAdded)\nmainPanel.Controls.Add(fx);\nmainPanel.Controls.SetChildIndex(fx, prevIndex);	0
21997932	21997883	How to remove last 10 elements from the list using c#?	if(Content.Count >= 10)\n  Content.RemoveRange(Content.Count - 10, 10);\nelse\n  Content.Clear()	0
2066063	2065933	Need help in Regex Replace C#	Regex.Replace("This is IV item.", "(?<=[^A-Za-z0-9])(IV)(?=[^A-Za-z0-9])", "fourth");	0
12814290	12814202	How to find a HTML tag with runat=server into a repeater?	Visible=<%= SetVisiblity() %>	0
30347627	30308200	Parse unique string from complicated serial data C#	private void IncomingData(string data)\n{\n  //Show received data in textbox\n  tb_incomingData.AppendText(data);\n  tb_incomingData.ScrollToCaret();\n\n  //Append data inside longdata (string)\n  longData = longData + data;\n  if (longData.Contains('@') && longData.Contains(',') && longData.Contains('!')) \n  {\n    try\n    {\n      indexSeru = longData.IndexOf('!'); //retrieve index number of the symbol !\n      indexComma = longData.IndexOf(','); //retrieve index number of the symbol ,\n      indexAlias = longData.IndexOf('@'); //retrieve index number of the symbol ,\n      rotation = longData.Substring(indexSeru + 1, 5); //first string is taken after symbol ! and 5 next char\n      subRotation = longData.Substring(indexComma + 1, 5); //second string is taken after symbol ! and 5 next char\n      //tss_distance.Text = rotation + "," + subRotation;\n      longData = null; //clear longdata string      \n    }\n    catch\n    {\n      indexSeru = 0;\n      indexComma = 0;\n      indexAlias = 0;\n    }\n  }\n}	0
21467976	21467825	InsertCommand.Parameters.Add size parameter for datetime	adapter.InsertCommand.Parameters.Add("@deliveryDateAndTime", SqlDbType.DateTime)\n                                .SourceColumn = "deliveryDateAndTime";	0
12236313	12236236	using solution folder in web config connection string	Solution Items	0
11381459	11381219	Which datatype and which insertion parameter for large data	cmdIns.Parameters.Add( new SqlParameter( "story", SqlDbType.NText )\n{\n    Value = yourVariable;\n} );	0
1572901	1572877	return column values as IEnumerable	IEnumerable<string> result = DataContext.ExecuteQuery<string>(sqlstring)	0
2484737	2483233	How can I make datagridview can only select the cells in the same column at a time?	Public Class DataGridView\n    Inherits System.Windows.Forms.DataGridView\n\n    Protected Overrides Sub OnSelectionChanged(ByVal e As System.EventArgs)\n        Static fIsEventDisabled As Boolean\n\n        If fIsEventDisabled = False Then\n\n            If Me.SelectedCells.Count > 1 Then\n                Dim iColumnIndex As Integer = Me.SelectedCells(0).ColumnIndex\n                fIsEventDisabled = True\n                ClearSelection()\n                SelectColumn(iColumnIndex) 'not calling SetSelectedColumnCore on purpose\n                fIsEventDisabled = False\n            End If\n\n        End If\n\n        MyBase.OnSelectionChanged(e)\n\n    End Sub\n\n    Public Sub SelectColumn(ByVal index As Integer)\n        For Each oRow As DataGridViewRow In Me.Rows\n            If oRow.IsNewRow = False Then\n                oRow.Cells.Item(index).Selected = True\n            End If\n        Next\n    End Sub\n\nEnd Class	0
7924271	7924160	Parsing a URL into an array	var uri = new Uri(@"http://sharepoint/webname/libraryname/subfolder1/"\n    + "subfolder2/subfolder3/documentname");\n\nvar segments =\n    uri.Segments\n        .Select(s => s.EndsWith("/") ? s.Substring(0, s.Length - 1) : s)\n        .ToArray();\n\nvar array = new []\n{\n    String.Format("{0}://{1}", uri.Scheme, uri.Host),\n    segments[1],\n    segments[2],\n    String.Join("/", segments.Skip(3).Take(segments.Length - 4)),\n    segments[segments.Length - 1],\n};	0
29881745	29881567	C# parse 12 hours time into datetime 24 hours	string data = "2:30, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 12:00, 1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00, 8:00, 9:00, 10:00, 11:00, 12:00, 1:00, 2:00";\nstring[] parts = data.Split(',');\n\nDateTime lastInput = DateTime.MinValue;\nList<DateTime> dates = new List<DateTime>();\nstring currentAMPM = "AM";\nforeach(string s in parts)\n{\n    DateTime temp;\n\n    if(DateTime.TryParse(s + " " + currentAMPM, out temp))\n    {\n        if(temp < lastInput)\n        {\n            currentAMPM = (currentAMPM == "AM" ? "PM" : "AM");\n            DateTime.TryParse(s + " " + currentAMPM, out temp);\n        }\n        dates.Add(temp);\n        lastInput = temp;\n\n    }\n}	0
2044275	2043839	Is there a library or tool for zipping numerous files	progressBarzipping.Minimum = 0; \nprogressBarzipping.Maximum = listBoxfiles.Items.Count;\nusing (Stream fs = new FileStream(PathToNewZip, FileMode.Create, FileAccess.Write))\n{\n    using (ZipFile zip = new ZipFile()) \n    { \n       zip.AddFiles(listboxFiles.Items);\n\n       // do the progress bar: \n       zip.SaveProgress += (sender, e) => {\n          if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) {\n             progressBarzipping.PerformStep();\n          }\n       };\n\n       zip.Save(fs); \n    }\n}	0
22151773	22151280	Get from html page only images, br and p- tags with HtmlAgilityPack	foreach (var node in descriptionDive\n            .DescendantNodes()\n            .Where(x => x.Name == "p" || x.Name == "br" || x.Name == "img" ))\n{\n  sb.Append(node.InnerText);\n}	0
31166283	31033112	Parse XML doc (Clinical Document Architecture-CDA,HL7 standard) using Everest Framework	using(XmlStateReader xr = new XmlStateReader(XmlReader.Create(@"C:\path-to-file.xml")))\n{\n    var fmtr = new XmlIts1Formatter();\n    fmtr.ValidateConformance = false;\n    fmtr.GraphAides.Add(new ClinicalDocumentDatatypeFormatter());\n    var parseResult = fmtr.Parse(xr, typeof(ClinicalDocument));\n    // There is a variable called structure which will contain your\n    var cda = parseResult.Structure as ClinicalDocument;\n}	0
29058245	29058107	store image name into database from directory	List<string>directories= yourlistofdirectories.\n\n    foreach(dir in directories)\n  {\n\n        DirectoryInfo d = new DirectoryInfo(dir);//Assuming Test is your Folder\n        FileInfo[] Files = d.GetFiles("*.jpg"); //Getting image files\n        foreach(FileInfo file in Files )\n        {\n          String query = "INSERT INTO dbo.Name (name) VALUES(@name)";\n          SqlCommand command = new SqlCommand(query, db.Connection);\n          command.Parameters.Add("@name",dir+file.Name);\n          command.ExecuteNonQuery();\n\n        }	0
12968510	12968411	How to stop a custom ThrowHelper from appearing in your StackTrace?	class ThrowHelper\n{\n    [DebuggerStepThrough]\n    public static void Throw()\n    {\n        throw new InvalidOperationException();\n    }\n}	0
8464958	8464781	How to show toolPopup for text longer than control (Textbox) length?	private void textBox1_MouseHover(object sender, EventArgs e)\n{\n    ToolTip t = new ToolTip();\n    t.Show(textBox1.Text, textBox1, 0,0, 5000);\n}	0
6205014	6065464	Ninject passing in constructor values	.ToMethod(Func<IContext, T> method)\n\nBind<IWeapon>().ToMethod(context => new Sword());	0
6932197	6932059	C# overriding an interface contract method of a base class	public class NotInConverter : InConverter, IValueConverter\n{\n  new public object Convert(...)\n  {\n    return !base.Convert(...);\n  }\n\n  new public object ConvertBack(...)\n  {\n    return !base.ConvertBack(...);\n  }\n}	0
11933930	11933440	parsing almost well formed XML fragments: how to skip over multiple XML headers	string.Replace(badXml, "<?xml version=\"1.0\"?>, "")	0
18446392	18446278	how to print a huge number of images in asp.net?	public ControlsTypeHere PrintImages(int take, int skip)\n{\n    int filesPrinted;\n\n    for (int i = skip; i < Files.Count; i++)\n    {\n        if(filesPrinted >= take)\n            break;\n\n        HtmlImage image=new HtmlImage();\n        image.ID="ImageAN"+i.ToString();\n        image.Src=Files[i].ToString();\n        image.Alt="PrintImage";\n        image.Attributes.Add("class","PrintImage");\n\n        div_Print.Controls.Add(image);\n\n        filesPrinted++;\n    }\n\n    return div_Print.Controls;\n}	0
13211589	13211334	How do I wait until Task is finished in C#?	private static string Send(int id)\n{\n    Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");\n    string result = string.Empty;\n    Task continuation = responseTask.ContinueWith(x => result = Print(x));\n    continuation.Wait();\n    return result;\n}\n\nprivate static string Print(Task<HttpResponseMessage> httpTask)\n{\n    Task<string> task = httpTask.Result.Content.ReadAsStringAsync();\n    string result = string.Empty;\n    Task continuation = task.ContinueWith(t =>\n    {\n        Console.WriteLine("Result: " + t.Result);\n        result = t.Result;\n    });\n    continuation.Wait();  \n    return result;\n}	0
27108171	27107857	eventlog source - string/message table lookup failed	try\n        {\n            EventLog.WriteEntry("LogSource", "test", EventLogEntryType.Error, 6285);\n        }\n        catch\n        {\n            MessageBox.Show("Could not write to log.");\n        }	0
25906349	25906301	How to skip first element in each line of matrix?	string[] fileLines = System.IO.File.ReadAllLines(@"input_5_5.txt", Encoding.GetEncoding(1250));\nfor(int line = 0; line < fileLines.Length; line++)\n{\n    string[] splittedLines = fileLines[line].Trim().Split(' ');\n    for(int col = 1; col < splittedLines.Length; col++)\n    {\n        // do whatever you want here\n    }\n}	0
4608635	4608545	Two sliders that depend on each other	Mode=TwoWay	0
11898843	11898694	looking up a value in xml C#	XDocument doc = XDocument.Load("test.xml");\nstring key = "BillOfMaterials";\nvar element = doc.Root.Elements("key")\n                      .Where(key => key.Attribute("name").Value == key)\n                      .Elements("translation")\n                      .Where(tr => tr.Attribute("culture").Value == "en-GB")\n                      .FirstOrDefault();\nstring result = (string) element ?? key;	0
29110260	29110109	C# Regular Expression Reversing Match	var re = new Regex(@"substringof\('([^']+)',([^)]+)\)");\nstring output = re.Replace(input, @"contains($2, '$1')");	0
33916846	33915565	ASP.Net 5 rc1 Localization in Views	Views.{ControllerName}.{ViewName}.cshtml.{culture code}.resx\ne.g. Views.Home.About.cshtml.de-DE.resx	0
12457881	12426191	How to tell if a control comes from MasterPage	public static bool IsFromMasterPage(Control control)\n{\n    if (control.Page.Master != null)\n    {\n        // Get all controls on the master page, excluding those from ContentPlaceHolders\n        List<Control> masterPageControls = FindControlsExcludingPlaceHolderChildren(control.Page.Master);\n        bool match = masterPageControls.Contains(control);\n        return match;\n    }\n    return false;\n}    \n\npublic static List<Control> FindControlsExcludingPlaceHolderChildren(Control parent)\n{\n    List<Control> controls = new List<Control>();\n    foreach (Control control in parent.Controls)\n    {\n        controls.Add(control);\n        if (control.HasControls() && control.GetType() != typeof(ContentPlaceHolder))\n        {\n            controls.AddRange(FindControlsExcludingPlaceHolderChildren(control));\n        }\n    }\n    return controls;\n}	0
13878193	13878016	How a file downloader work?	using(var wc=new WebClient())\n{\n    wc.DownloadFile("http://some/internet/resource",@"c:\some\local\filename");\n}	0
13107372	13107129	Table name as part of primary key	public IQueryable<AuditRecord> AuditRecords\n{\n    get\n    {\n        MyContext ctx = new MyContext();\n\n        var ars = from ar in ctx.AuditRecords\n                  where ar.EntityTable.Equals(this.GetType().Name)\n                  select ar;\n\n        return ars;\n    }\n}	0
12183380	12183276	Deserializing JSON that contains a variable that begins with "@"	[DataContract]\npublic class HotelDetails\n{\n    [DataMember(Name="@order")]\n    public string order;\n\n    [DataMember(Name="hotelId")]    \n    public string hotelId;\n\n    [DataMember(Name="name")]  \n    public string name;\n\n    [DataMember(Name="address1")]  \n    public string address1;\n}	0
32358156	32357884	Calculate End Date when specific duration of days given	var startDate = DateTime.Now;  // Put your actual start date here\nfor (int i = 0; i < 5;)        // Put number of days to add instead of 5\n{\n    startDate = startDate.AddDays(1);\n    if (startDate.DayOfWeek == DayOfWeek.Saturday || startDate.DayOfWeek == DayOfWeek.Sunday)\n    {              \n        continue;\n    }\n    i++;\n}\nvar finalDate = startDate;	0
9426073	9426019	How to use Razor View Engine in a console application?	string template = "Hello @Model.Name! Welcome to Razor!";\nstring result = Razor.Parse(template, new { Name = "World" });	0
5362374	5362226	linq to sql for CRUD framework	public class SomeTypeMap : ClassMap<SomeType>\n{\n    Id(x => x.Id);\n    Map(x => x.Property1);\n    Map(x => x.Property2);\n    // ....\n    Map(x => x.PropertyN);\n}	0
25685184	25683049	How to set VirtualDirectory credentials	newVDir.Properties["UNCUserName"][0] = username;\nnewVDir.Properties["UNCPassword"][0] = password;	0
31921796	31788660	Excel Chart colorize 3D bars	chartRange = xlsSheet.Range[xlsSheet.Cells[1, 1], xlsSheet.Cells[array.GetLength(0), array.GetLength(1)]];\nchartPage.SetSourceData(chartRange, Excel.XlRowCol.xlRows);\n\nExcel.Series series = (Excel.Series)chartPage.SeriesCollection(1);\nExcel.Point pt = series.Points(2);\npt.Format.Fill.ForeColor.RGB = (int)Excel.XlRgbColor.rgbPink;\n\nchartPage.ChartType = Excel.XlChartType.xl3DColumn;\nchartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet, oOpt);	0
30175568	30172307	Import frames from a video	LoadVideo();\n//Add event handler to the Changed event.\nGetFirstFrame();\n//Change video Position.\n//When the Changed event fires: \nGetCurrentFrame();	0
12076510	12074552	Insert extra custom fields from DetailsView	protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)\n{\n    e.Values["date_submitted"] = DateTime.Now.ToShortDateString();\n}	0
24124141	24121665	Gridview sorting method - Numbers being sorted as strings - How to change the datatype	private void SortGridView(string sortExpression, string direction)\n    {\n\n        DataTable dt = (DataTable)Session["QueryTable"];\n\n        if (direction == ASCENDING)\n        {\n            suiteReport.DataSource = dt.AsEnumerable().OrderBy(x => x[sortExpression]);\n        }\n        else\n        {\n            suiteReport.DataSource = dt.AsEnumerable().OrderByDescending(x => x[sortExpression]);\n        }\n\n        suiteReport.DataBind();\n    }	0
5349330	5348833	how to Add new property to system class?	public class CustomResource: Telerik.Windows.Controls.Resource\n    {\n        private int noOfAppointments;\n        public int NoOfAppointments\n        {\n            get { return noOfAppointments; }\n            set\n            {\n                if (value > 0)\n                    noOfAppointments = value;\n                else\n                    noOfAppointments = 0;\n            }\n        }\n    }	0
5343021	5342975	Get a TextReader from a Stream?	TextReader tr = new StreamReader(stream);	0
7117162	7117134	How to make Test Method using job of another Test Method?	[TestInitialize]	0
811599	811436	Dynamically rendering controls, determine type from string/XML File?	public interface IControlProvider {\n    public Control GetControl(XmlElement controlXml);\n};\n\npublic class ControlProviderFactory : IControlProvider {\n    private Dictionary<string,IControlProvider> providers = new Dictionary<string,IControlProvider>();\n\n    public ControlProviderFactory() {\n        //Add concrete implementations of IControlProvider for each type\n    }\n\n    public Control GetControl(XmlElement controlXml) {\n        string type = (controlXml.SelectSingleNode("type") as XmlElement).InnerText;\n        if(!providers.ContainsKey(type) throw new Exception("No provider exists for " + type);\n        return providers[type].GetControl(controlXml);\n    }\n}	0
19180520	19180402	WPF Application Crash After running from C:\Program Files (x86)\ OR by C:\Program Files	// Sample for the Environment.GetFolderPath method \nusing System;\n\nclass Sample \n{\n    public static void Main() \n    {\n       var folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\n       Console.WriteLine(folder);\n       Console.ReadLine();\n    }\n}	0
16274001	16272479	Detecting if a Winform was launched from the console?	#Region " App Is Launched From CMD? "\n\n    ' [ App Is Launched From CMD? Function ]\n    '\n    ' // By Elektro H@cker\n    '\n    ' Examples:\n    ' MsgBox(App_Is_Launched_From_CMD)\n    ' If App_Is_Launched_From_CMD() Then Console.WriteLine("Help for this application: ...")\n\n    Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean\n    Declare Function FreeConsole Lib "kernel32.dll" () As Boolean\n\n    Private Function App_Is_Launched_From_CMD()\n        If AttachConsole(-1) Then\n            FreeConsole()\n            Return True\n        Else\n            Return False\n        End If\n    End Function\n\n#End Region	0
12710490	12710390	Drawing a grid on a PictureBox	private void pictureBox1_Paint(object sender, PaintEventArgs e)\n        {\n            Graphics g = e.Graphics;\n            int numOfCells = 200;\n            int cellSize = 5;\n            Pen p = new Pen(Color.Black);\n\n            for (int y = 0; y < numOfCells; ++y)\n            {\n                g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);\n            }\n\n            for (int x = 0; x < numOfCells; ++x)\n            {\n                g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);\n            }\n        }	0
23920021	23919948	Randomize but exclude the random variable	var rnd = new Random();\nvar numList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\nvar extracted =  from n1 in numList\n                 from n2 in numList\n                 from n3 in numList\n                 from n4 in numList\n                 where n1 + n2 + n3 + n4 > 20\n                 orderby rnd.NextDouble()\n                 select new { n1, n2, n3, n4 }; // you can use ToList()	0
7648751	7648174	Splitting a list<> that each item contains comma separated strings and formatting it out	var query = QR.ToLookup(i=>i.DeviceName, i => new {i.GroupName, i.PinName})\n              .Select(i=> \n                     new {DeviceName = i.Key, \n                          Groups = i.ToLookup(g=>g.GroupName, g=>g.PinName)});\n\n        var sb = new StringBuilder();\n        foreach ( var device in query)\n        {\n            sb.AppendLine(device.DeviceName);\n            foreach ( var gr in device.Groups)\n            {\n               sb.Append(gr.Key + ": ");\n               sb.Append(String.Join(", ", gr.ToArray()));\n               sb.AppendLine();\n            }\n            sb.AppendLine();\n        }\n        var stringToWrite = sb.ToString();	0
18627940	18627873	SQL Server: Datagridview display column value from table	private void button3_Click(object sender, EventArgs e)\n    {\n        string connectionString = @"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;\n        string sql = "SELECT account FROM user_account";\n        SqlConnection connection = new SqlConnection(connectionString) ;\n        SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);\n        DataSet ds = new DataSet();\n        connection.Open();\n        dataadapter.Fill(ds, "account");\n        connection.Close();\n        dataGridView1.DataSource = ds;\n\n    }	0
10509925	10508000	mapping many-to-many with interfaces	essentially type IList<IFaqTagReference> is not type IList<FaqTagReference>	0
34167381	34166899	Creating table which changes a column in order to remove repeated values in rows	// First, generate a linq query\nvar query = from a in Persons\n            join t in Repairs on a.PID equals t.Repairman_PID\n            group new { a, t } by new { a.PID, a.Name, a.Surname } into g\n            select new\n            {\n                PID = g.Key.PID,\n                Name = g.Key.Name,\n                Surname = g.Key.Surname,\n                PhoneCount = g.Count()\n            };\n\n// Then order by PhoneCount descending and take top 3 items\nvar list = query.OrderByDescending(t => t.PhoneCount).Take(3).ToList();	0
8801073	8800931	Access database - Retrieve names of stored queries?	OleDbConnection connection = new OleDbConnection(@"connection_string");\nconnection.Open();\nDataTable schemaTable = connection.GetOleDbSchemaTable(\n         OleDbSchemaGuid.Tables,\n           new object[] { null, null, null, "VIEW" });\nforeach (DataRow row in schemaTable.Rows )\n{\n    Console.WriteLine(row["TABLE_NAME"]);\n}	0
17588964	17574509	Isometric Map Drawing	int isox = (Width / 2) - (tileLength / 2) + x - y;	0
17804272	17804075	Parsing DateTime to Universal Time C#	var formats = new[] \n    {\n        "M/dd/yyyy hh:mm tt",\n        "M/dd/yyyy hh:mmtt",\n        "M/dd/yyyy h:mm tt",\n        "M/dd/yyyy h:mmtt",\n        "M/dd/yyyy hhtt",\n        "M/dd/yyyy htt",\n        "M/dd/yyyy h tt",\n        "M/dd/yyyy hh tt"\n    };\n\n    var date = "7/23/2013 4:00pm";\n\n    DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,\n                                                  DateTimeStyles.AssumeUniversal |\n                                                  DateTimeStyles.AdjustToUniversal);	0
6682721	6682678	Accessing an open Excel Workbook in C#	try\n{\n  Microsoft.Office.Interop.Excel.Application app = \n      System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");\n}\ncatch\n{\n  // Excel is not running.\n}	0
33826780	33824509	sort entity data source in command text	CommandText="select UPPER(it.[NAME]), co.[TEXT] from USER as it, COMMENT as co where it.[User_ID] = co.[User_ID] order by UPPER(it.[NAME])">	0
29496412	29496306	How to specify that DateTime objects retrieved from EntityFramework should be DateTimeKind.UTC	DateTimeKind.Unspecified	0
30725218	30711940	run oncomplete event in async	while ((lOPCServer.IsConnected == false) && (lTimeout < 60000)) //1 min timeout\n{\n    Thread.Sleep(10);\n    lTimeout += 10;\n}\n\nif (lTimeout >= 60000)\n{\n    return ""; //Server initaite timed out\n}	0
14908992	14908919	InsertItemTemplate From ListView Doesn't Appear	protected void btn_Click(object sender, EventArgs e)\n    {\n        ChatListView.InsertItemPosition = InsertItemPosition.FirstItem;\n    }	0
14692490	14657417	Writing a C# method to parse string for Word Text how to iterate to get forms too?	else\n                        {\n                            st += Doc.FormFields.get_Item(x).Result;\n                            x++;\n                        }	0
21580098	21566174	Button Overlay on ListView Hides on MouseMove	btnAddName.SetBounds(\n                    bounds.Right - btnAddName.Width + lvVertices.Left,\n                    bounds.Top + lvVertices.Top,\n                    bounds.Width, bounds.Height);\n\n                //-->\n                iColBtnAdd = iCol;\n                iRowBtnAdd = iRow;\n                //<--\n\n                if (!btnAddName.Visible)\n                {	0
21819993	21819954	replace file with new one with timestamp	String source = Path.Combine(dir1, "participants.txt");\nif (File.Exists(source)) {\n    File.Copy(source, Path.Combine(dir1, "participants" + Stopwatch.GetTimestamp().ToString() + ".txt"));\n    File.WriteAllLines(source, lines);\n}	0
5894456	3700555	Enable KeyDown Event only in active child of a MDI Application c#	if(ActiveMdiChild != null)\n  return;	0
33545601	33545249	Create a Tuple in a Linq Select	codes = codesRepo.SearchFor(predicate)\n    .Select(c => new { c.Id, c.Flag })\n    .AsEnumerable()\n    .Select(c => new Tuple<string, byte>(c.Id, c.Flag))\n    .ToList();	0
20105903	20105848	How do I group by an ID within a child collection	listConfigs.SelectMany(c=>c.Features).GroupBy(f=>f.Id)	0
28298316	28297737	Cropped Label due to Big Font	void OnGUI()\n{\n    var style = GUI.skin.label;\n    var size = style.CalcSize(new GUIContent("Number is 16")); // ****\n\n    GUI.Label(new Rect(Screen.width - size.x - 100, \n              Screen.height / 2, size.x, size.y), "Number is 16");\n}	0
9226237	9226163	C# reflection activator create instance using a generic parameter	Activator.CreateInstance(genericParams[0]);	0
19325695	19325478	Get windows that are on top of form	System.Windows.Rect.Intersect()	0
12420791	12420751	Return named JSON object from c# service in .NET	return JsonConvert.SerializeObject(\n  new { file = System.Convert.ToBase64String(image) }\n);	0
11053399	11043334	HtmlAgilityPack replace paragraph tags with linebreaks	string rawHtml = "<p><strong><span>1.0 Purpose</span></strong></p><p><span>The role</span></p><p><span>NOTE: Defined...</span></p>";\n\nHtmlDocument doc = new HtmlDocument();\nHtmlNode.ElementsFlags["br"] = HtmlElementFlag.Empty;\ndoc.LoadHtml(rawHtml);\ndoc.OptionWriteEmptyNodes = true;\n\nHtmlNode linebreak1 = doc.CreateElement("br");\nHtmlNode linebreak2 = doc.CreateElement("br");\nvar paragraphTags = doc.DocumentNode.SelectNodes("p");\nfor (int i = 0; i < paragraphTags.Count; i++)\n{\n    if (i > 0)\n    {\n        doc.DocumentNode.InsertBefore(linebreak1, paragraphTags[i]);\n        doc.DocumentNode.InsertBefore(linebreak2, paragraphTags[i]);\n    }\n    doc.DocumentNode.InsertBefore(HtmlNode.CreateNode(paragraphTags[i].InnerHtml), paragraphTags[i]);\n    paragraphTags[i].ParentNode.RemoveChild(paragraphTags[i]);\n}	0
31481347	31481323	Split String by char Character	var tokens = Regex.Split(stringToSplit, @"'", RegexOptions.None);	0
9172442	9081610	Starting and debugging a service that executes a SoapUI testrunner.bat batch file	using (System.Diagnostics.Process proc = new System.Diagnostics.Process())\n{\n    proc.StartInfo.FileName = "testrunner.bat";\n    proc.StartInfo.Arguments = "blah blah blah";\n    proc.StartInfo.RedirectStandardError = true;\n    proc.StartInfo.RedirectStandardOutput = true;\n    proc.StartInfo.UseShellExecute = false;\n    proc.Start();\n    outputMessage = proc.StandardOutput.ReadToEnd();\n\n    logFile = File.AppendText("D:\\temp\\SoapUITest.log");\n    logFile.AutoFlush = true;\n    logFile.Write(outputMessage);\n    logFile.Close();\n}	0
24706746	11238141	Validate Windows Identity Token	public class ActiveDirectoryHelper\n{\n    [DllImport("advapi32.dll", SetLastError = true)]\n    private static extern bool LogonUser(\n        string lpszUsername,\n        string lpszDomain,\n        string lpszPassword,\n        int dwLogonType,\n        int dwLogonProvider,\n        out IntPtr phToken\n        );\n\n    [DllImport("kernel32.dll", SetLastError = true)]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    public static extern bool CloseHandle(IntPtr hObject);\n\n    public static bool Authenticate(string userName, string password, string domain)\n    {\n        IntPtr token;\n        LogonUser(userName, domain, password, 2, 0, out token);\n\n        bool isAuthenticated = token != IntPtr.Zero;\n\n        CloseHandle(token);\n\n        return isAuthenticated;\n    }\n\n    public static IntPtr GetAuthenticationHandle(string userName, string password, string domain)\n    {\n        IntPtr token;\n        LogonUser(userName, domain, password, 2, 0, out token);\n        return token;\n    }\n\n\n}	0
20777	20762	How do you remove invalid hexadecimal characters from an XML-based data source prior to constructing an XmlReader or XPathDocument that uses the data?	/// <summary>\n/// Removes control characters and other non-UTF-8 characters\n/// </summary>\n/// <param name="inString">The string to process</param>\n/// <returns>A string with no control characters or entities above 0x00FD</returns>\npublic static string RemoveTroublesomeCharacters(string inString)\n{\n    if (inString == null) return null;\n\n    StringBuilder newString = new StringBuilder();\n    char ch;\n\n    for (int i = 0; i < inString.Length; i++)\n    {\n\n        ch = inString[i];\n        // remove any characters outside the valid UTF-8 range as well as all control characters\n        // except tabs and new lines\n        //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')\n        //if using .NET version prior to 4, use above logic\n        if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4\n        {\n            newString.Append(ch);\n        }\n    }\n    return newString.ToString();\n\n}	0
15525968	15524186	How to find highlighted text from Word file in C# using Microsoft.Office.Interop.Word?	Sub TestFind()\n\n  Dim myRange As Range\n\n  Set myRange = ActiveDocument.Content    '    search entire document\n\n  With myRange.Find\n\n    .Highlight = True\n\n    Do While .Execute = True     '   loop while highlighted text is found\n\n      Debug.Print myRange.Text   '   myRange is changed to contain the found text\n\n    Loop\n\n  End With\n\nEnd Sub	0
2673753	2673686	Calling a javascript function from Page_Load in code-behind	ClientScript.RegisterStartupScript(GetType(), "hiya", "alert('hi!')", true);	0
26778702	11848051	See if other assembly is being debugged	public static class ProcessExtensions\n{\n    [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]\n    static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);\n\n    public static bool IsDebuggerAttached(this Process process)\n    {\n        try\n        {\n            var isDebuggerAttached = false;\n            CheckRemoteDebuggerPresent(process.Handle, ref isDebuggerAttached);\n\n            return isDebuggerAttached;\n        }\n        catch (Exception)\n        {\n            return false;\n        }\n    }\n}	0
7744051	7743706	update a listbox item	class Eco {\n  public Eco() { }\n  public void SetEcoValues(string text, double value) {\n    Text = text;\n    Value = value;\n  }\n  public string Text { get; set; }\n  public double Value { get; set; }\n  public override string ToString() {\n    if (!String.IsNullOrEmpty(Text)) {\n      return Text;\n    }\n    return base.ToString();\n  }\n}\n\nListView listView1; // initialized somewhere, I presume.\n\nvoid Update_Click(object sender, EventArgs e) {\n  if ((listView1.SelectedItems != null) || (0 < listView1.SelectedItems.Count)) {\n    ListViewItem item = listView1.SelectedItems[0];\n    Eco y = item.Tag as Eco;\n    if (y == null) {\n      y = new Eco();\n    }\n    y.SetEcoValues(textBox1.Text, Convert.ToDouble(textBox2.Text));\n    item.Text = y.Text;\n    if (item.SubItems.Count < 2) {\n      item.SubItems.Add(y.Value.ToString());\n    } else {\n      item.SubItems[1].Text = y.Value.ToString();\n    }\n    item.Tag = y;\n  }\n}	0
2985993	2985554	How to bind a complex dictionary to a Gridview in asp.net?	Literal _href = e.Row.FindControl("href") as Literal;  \nif(_href != null)\n{\n  _href = ((LinkInfo)e.Row.DataItem).href;\n}	0
27796411	27794937	Detect redirect standard output to nul	int mode;\nbool success = Win32Native.GetConsoleMode(ioHandle, out mode);\nreturn !success;	0
27290603	27289971	How to bring data from database to excel sheet?	foreach (DataRow row in rows)\n{\n    string name = Convert.ToString(row["Fname"]);\n    string code = Convert.ToString(row["Middle Name"]);\n\n    // Setting Value in cell\n    ws.Cells[colIndex, rowIndex].Value = name;\n    ws.Cells[colIndex + 1, rowIndex].Value = code;       \n\n    // Move to the next row in the sheet.\n    rowIndex++;\n}	0
25139437	25043213	using Composition in c# android activity to access the data	var secondActivity = StartActivity(typeof(SecondActivity));\nsecondActivity.SetMyData(data);	0
24925125	24924640	Not able to take Value for json in MVC 5 Application	var employees = context.Employees\n   .OrderBy(p=>p.EmployeeId)\n   .Skip(pageIndex * pageSize)\n   .Take(pageSize)\n   .ToArray(); // Add this.	0
4071070	4070560	How to Change Database on a Entity Framework Connection	private MyEntities _db;\nprivate string entityConnectionString = ConfigurationManager.ConnectionStrings["MyEntities"].ConnectionString;\n\npublic IQueryable<MyObject> GetMyObjects(string database)\n{\n    var ecsb = new EntityConnectionStringBuilder(entityConnectionString);\n    var scsb = new SqlConnectionStringBuilder(ecsb.ProviderConnectionString)\n    scsb.InitialCatalog = database;\n    ecsb.ProviderConnectionString = scsb.ToString();\n    _db = new MyEntities(ecsb.ToString());    \n    return _db.MyObjects\n}	0
3078468	3078461	How to join Jagged array with separator using string.Join?	Console.WriteLine(string.Join(", ", row.Select(x => x.ToString()).ToArray()));	0
26352518	26332394	How to autostart windows services in C#	namespace curUsers\n{\n[RunInstaller(true)]\npublic partial class ProjectInstaller : System.Configuration.Install.Installer\n{\n    public ProjectInstaller()\n    {\n        var processInstaller = new ServiceProcessInstaller();\n        var serviceInstaller = new ServiceInstaller();\n\n        //set the privileges\n        processInstaller.Account = ServiceAccount.LocalSystem;\n\n        serviceInstaller.DisplayName = "curUsers";\n        serviceInstaller.StartType = ServiceStartMode.Automatic;\n\n        //must be the same as what was set in Program's constructor\n        serviceInstaller.ServiceName = "curUsers";\n\n        this.Installers.Add(processInstaller);\n        this.Installers.Add(serviceInstaller);\n    }\n\n    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)\n    {\n\n    }\n\n    private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)\n    {\n\n    }\n}\n}	0
28102424	28042161	EF returns old values	.Include()	0
14764428	14764217	Access dynamically created text box in a custom template for an ajax tab	string strQuantity=((System.Web.UI.WebControls.TextBox)(((AjaxControlToolkit.TabContainer)(BTN.Parent.FindControl("tabcontainer"))).Tabs[0].FindControl("TbxQuantity"))).Text	0
26013668	26013232	How to loop through List<dynamic>	foreach (var v in (i as IEnumerable<object>))\n    {\n        if (v is KeyValuePair<string, string>)\n        {\n            // Do stuff\n        }\n        else if (v is List<string>)\n        {\n            //Do stuff\n        }\n\n        else throw new InvalidOperationException();\n    }	0
24249819	24249717	User Control Visibility	Visibility = Visibility.Collapsed;	0
24562855	24562800	WPF binding to DataGrid - displaying data	public Car(string company, string model, int price, string city)\n{\n    Company = company;\n    Model = model;\n    Price = price;\n    City = city;\n}	0
19448003	19247340	How to download On demand Confluence page content image to local machine?	image=https://{companyName}.atlassian.net/wiki/download/attachments/524312/worddave1f7873c424d7824e580764369e7ee68.png;\nimageLocation =@"C:\Images";\nstring[] FileName = image.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);\nWebClient client = new WebClient();\nclient.DownloadFile(new Uri(image+"?&os_username=xxx&os_password=yyy"), imageLocation + "\\" + FileName[FileName.Count() - 1]);	0
27780237	25962195	get status info Windows Media Player (stand-alone application)	wmp help	0
14754074	14753918	linq-To-SQL not getting updated db data	using(somethingEntities db = new somethingEntities()){\n  Document d = (from c in db.Documents where c.Id = myID select c).First();\n  // do something here\n}	0
31965511	31945654	Make singleton of view in android	[Activity(Label = "App47", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]\npublic class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity\n{\n    private static double calculationResult;\n    private static bool calculationsDone;\n\n    static MainActivity()\n    {\n        PerformCalculation().ContinueWith(t =>\n        {\n            calculationResult = t.Result;\n            calculationsDone = true;\n        }\n        );\n    }\n\n    private static Task<double> PerformCalculation()\n    {\n        var tcs = new TaskCompletionSource<double>();\n        tcs.SetResult(10.6);\n        return tcs.Task;\n    }\n\n    protected override void OnCreate(Bundle bundle)\n    {\n        base.OnCreate(bundle);\n\n        global::Xamarin.Forms.Forms.Init(this, bundle);\n        LoadApplication(new App());\n    }\n}	0
30082340	30080979	Deeper fetch in nHibernate returns a proxy object	AuthorBook authorBooks = null;\n        Book book = null;\n\n        session.QueryOver<Author>()\n            .Where(x => x.Id = AuthorId)\n            .JoinAlias(a => a.AuthorBooks, () => authorBooks,JoinType.LeftOuterJoin)\n            .JoinAlias(() => authorBooks.Book, () => book)\n            .SingleOrDefault();	0
16961449	16961306	Remove an XElement from another XDocument	doc.Root.Descendants(actualNode.Parent.Name)\n        .Elements(actualNode.Name)\n        .Remove();	0
11541734	11541659	Efficient way for updating data in a data table from another data table	dtOriginal.Merge(dtNew);	0
3841906	3837168	How to rewrite the same XAML DataBinding in Code	private GridViewColumn GetGridViewColumn(string header, double width, string bindingProperty, Type type)\n    {\n        GridViewColumn column = new GridViewColumn();\n        column.Header = header;\n\n        FrameworkElementFactory controlFactory = new FrameworkElementFactory(type);\n\n        var itemsBinding = new System.Windows.Data.Binding(bindingProperty);\n        controlFactory.SetBinding(TextBox.TextProperty, itemsBinding);\n\n        DataTemplate template = new DataTemplate();\n        template.VisualTree = controlFactory;\n\n        column.CellTemplate = template;\n        return column;\n    }	0
9212563	9212020	Strange behavior when converting String to DateTime	Application Excel = new Application();\n\nWorkbook workbook = Excel.Workbooks.Add(1);\nWorksheet sheet = workbook.Sheets[1];\nsheet.Cells[1, 1] = DateTime.Now;\nsheet.Cells[2, 1] = DateTime.Now.AddDays(1);\nsheet.Cells[3, 1] = DateTime.Now.AddDays(2);\nsheet.UsedRange.Columns["A:A", Type.Missing].NumberFormat = "MM/dd/yyyy"; \nworkbook.Sheets.Add(sheet);\n\n// Save the workbook or make it visible	0
20173744	20173699	Store textbox value into a string?	private void ButtonOK_Click(object sender, EventArgs e)\n{\n    string a = textbox1.Text;\n    int b;\n    if (Int32.TryParse(a, out b))\n    {\n        label1.Text = b.ToString();       \n    }\n}	0
14212674	14212568	Eliminate null entry in combobox	comboBox.SelectedIndex	0
4757786	4757733	How can I programmatically clear cache?	protected void Page_Load(object sender, EventArgs e)\n{\n    Response.Cache.SetCacheability(HttpCacheability.NoCache);\n    Response.Cache.SetExpires(DateTime.Now);\n    Response.Cache.SetNoServerCaching();\n    Response.Cache.SetNoStore();\n}	0
18294163	18287653	How to bind MembershipUsersCollection to GridView	public IQueryable<System.Web.Security.MembershipUser> GridView1_GetData()\n{\n  return Membership.GetAllUsers().Cast<MembershipUser>().AsQueryable<MembershipUser>();            \n}	0
23751322	23751256	Remove a record in entity framework	// no trip to database\nvar rec = db.TableName.Local.SingleOrDefault(r => r.Id == primaryKey);\n\nif (rec == null) throw NotFoundOrWhateverException();\n\n// still no trip to database, if I remember right\ndb.TableName.Remove(rec);\n\n// trip to database\ndb.SaveChanges();	0
7348068	7346174	Return multiple values from sql to label	protected string ImageCheck()\n    {\n\n      var result = new StringBuilder();\n\n    using(var connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\***.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))\n    {\n        string CommandText2 = "SELECT * FROM Machreta WHERE noImage = 1";\n        SqlCommand command2 = new SqlCommand(CommandText2, connection);\n        connection.Open();\n\n      using(var reader = command2.ExecuteReader())\n      {\n        while (reader.Read())\n        {\n          result.Append(reader.GetString(0));\n        }\n      }\n\n      return result.ToString();\n\n    }\n }	0
9208108	9207916	Trying to create Moq object	var testData = new List<Person>(){new Person()\n                                                 {\n                                                        SITE_ID = "test",\n                                                        MPAN = "test",\n                                                        ADDLINE1 = "test",\n                                                        ADDLINE2 = "test",\n                                                        ADDRESS_LINE_1 = "test",\n                                                        ADDRESS_LINE_2 = "test"\n                                                 }};\nvar result = GetPersonsePerSite(testData);	0
19956917	19956069	List of file's extension can be edited text in an editor	var textExtensions = new HashSet<string> { ".txt", ".css", ".htm", ".html", ".xml", ".c",  /*etc.*/ };\n\n...\n\nelse if textExtensions.Contains(fileExtension)\n{\n  ((Label)e.Item.FindControl("imagelabel")).Text = "<img src='pic/Text.gif'>";\n  //add Edit Text function here\n  ((LinkButton)e.Item.FindControl("lbtnEditText")).Text = "<img src='pic/pe.png'/>Edit Text";\n}	0
21631414	21630609	How do you set a value in codebehind depending on which radio button is chosen?	int type = (vyAlpha.Checked) ? 1 : ((vyBeta.Checked) ? 2 : 0);	0
33211641	33211350	BSTR string manipulation within a loop	pks[i].StrVal = SysAllocString(L"abcdefghij");	0
13736529	13736069	Centering or manually positioning dynamic controls on a WPF Canvas	string[] titles = { "Acorn", "Banana", "Chrysanthemum" };\n  double col = 20.0;\n  foreach (string s in titles) {\n    var lbl = new Label() { Content = s };\n    lbl.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));\n    lbl.SetValue(Canvas.LeftProperty, col - (lbl.DesiredSize.Width / 2.0));\n    myCanvas.Children.Add(lbl);\n    col += 150.0;\n  }	0
13883762	13883707	How to change WCF contract name?	[ServiceContract(ConfigurationName="NewName")]\npublic interface IMyService {\n    ...\n}	0
28171760	28171712	EventHandler for all controls in form	private void Form1_Load(object sender, EventArgs e)\n    {\n        foreach (Control c in this)\n        {\n            c.GotFocus += new EventHandler(AnyControl_GotFocus);\n        }\n    }\n\nvoid AnyControl_GotFocus(object sender, EventArgs e)\n    {\n       //You'll need to identify the sender, for that you could:\n\n       if( sender == tb_page) {...}\n\n       //OR:\n       //Make sender implement an interface\n       //Inherit from control\n       //Set the tag property of the control with a string so you can identify what it is and what to do with it\n       //And other tricks\n       //(Read @Steve and @Taw comment below) \n    }	0
18592277	18592138	How to marshal a double pointer?	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic class xyz\n{\n    IntPtr np;\n    IntPtr foo;\n}	0
27743112	27742863	Using HttpClient with Windows-1252 encoded url	string name = "Arnar A??alsteinsson"; \n        string encodedName = HttpUtility.UrlEncode(name, Encoding.GetEncoding(1252));\n        string url = string.Format("http://website.com/find?name={0}", encodedName);\n\n        HttpClient httpClient = new HttpClient();\n        try\n        {\n            **string result = httpClient.GetStringAsync(url).Result;**\n\n        }\n        catch (System.AggregateException ex) {\n\n            Debug.WriteLine(ex.Message);\n\n\n        }	0
31215909	31215873	Get Heart Rate From Microsoft Band	await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, \n               () => \n               {\n                   Textblock.Text =  e.SensorReading.HeartRate.ToString())\n               }).AsTask();	0
11393000	11392414	How to get request contents in ASP.Net	{\n    HttpFileCollection files = Request.Files;\n    HttpPostedFile file = files[0];\n    int filelength = file.ContentLength;\n    byte[] input = new byte[filelength ];\n    file.InputStream.Read(input, 0, filelength );\n\n   }	0
21857689	21714093	Windows Authentication with Active Directory Groups	[Authorize(Roles=@"SomeDomain\SomeGroup")]	0
3223897	3223182	Snap to Road with direction in concern	double roadDrctn = Math.Atan2(point2.y - point2.y, point2.x - point1.x)	0
8670444	8512413	How to play same sound repeatedly with XAudio2?	// ------ code piece \n\n        /// <summary>\n        /// Gets the available voice.\n        /// </summary>\n        /// <returns>New SourceVoice object is always returned. </returns>\n        private SourceVoice GetAvailableVoice()\n        {\n            return new SourceVoice(_player.GetDevice(), _stream.Format);\n        }\n\n        /// <summary>\n        /// Plays this sound asynchronously.\n        /// </summary>\n        public void Play()\n        {\n            // get the next available voice\n            var voice = GetAvailableVoice();\n            if (voice != null)\n            {\n                // submit new buffer and start playing.\n                voice.FlushSourceBuffers();\n                voice.SubmitSourceBuffer(_buffer);\n\n                voice.Start();\n            }\n        }	0
13194859	13194804	Updating the database using the value which is stored in variable	string sql=string.Format("UPDATE batch SET NoOfStudents= {0}",x);\nMySqlCommand cmd2 = new MySqlCommand(sql, connection);	0
3598809	3598757	How to call a method that takes multiple parameters in a thread?	Thread thread = new Thread(() => Send(arg1, arg2, arg3));\nthread.Start();	0
30668589	30668513	how to save a pdf to folder in root directory and return it to client	File.WriteAllBytes(path,fileContents);	0
24579961	24539730	force log4net to overwrite file	public static void StartNewLogFile()\n{\n    Hierarchy hierachy = (Hierarchy)log4net.LogManager.GetRepository();\n    Logger logger = hierachy.Root;\n\n    var rootAppender = logger.Appenders.OfType<FileAppender>().FirstOrDefault();\n    string filename = rootAppender != null ? rootAppender.File : string.Empty;\n\n    while (logger != null)\n    {\n        foreach (IAppender appender in logger.Appenders)\n        {\n            FileAppender fileAppender = appender as FileAppender;\n            if (fileAppender != null)\n            {\n                fileAppender.File = filename + "a";\n                fileAppender.File = filename;\n                fileAppender.ActivateOptions();\n            }\n        }\n        logger = logger.Parent;\n    }\n\n    File.Delete(filename + "a");\n}	0
13874720	13874684	How to check if two rectangles intersect in WPF	if (rectangle1.IntersectsWith(rectangle2))\n{\n   // Do something\n}	0
672821	672807	generating jpg thumbnails in dotnet	public Image ResizeImage(Image openImage, int NewWidth, int NewHeight) {\n        var openBitmap = new Bitmap(openImage);\n        var newBitmap = new Bitmap(NewWidth, NewHeight);\n        using (Graphics g = Graphics.FromImage(openBitmap))\n        {\n            g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n            g.PixelOffsetMode = PixelOffsetMode.HighQuality;\n            g.DrawImage(newBitmap, new Rectangle(0, 0, NewWidth, NewHeight));\n        }\n        openBitmap.Dispose(); //Clear The Old Large Bitmap From Memory\n\n        return (Image)newBitmap;\n    }	0
7628744	7628656	How to internationalize data that came from Database?	---------------------------------------------------------\n| Id | Locale | Translation                             |\n---------------------------------------------------------\n| 1  | en-US  | Something happened on the way to heaven |\n| 1  | pl     | Co? si? sta?o na drodze do nieba        |\n---------------------------------------------------------	0
28318087	28318010	C# save multiple values	class Entity\n{\n    private String question;\n    private String answer;\n    private int _posX;\n    private int _posY;\n    private int _direction;\n    Crosswords cr = new Crosswords();\n\n    public Entity(int posX, int posY, int direction)\n    {\n        _posX = posX;\n        _posY = posY;\n        _direction = direction;\n    }\n\n    public int getLength()\n    {\n        return cr.getSpaceLength(_posX, _posY, _direction);\n    }\n}	0
25476730	25476710	No overload for method 'select' takes 2 arguments	.Select(a => new myType \n            { \n               anId = a.Key, \n               aCost = a.Sum(p => p["Cost"].ToFloat())\n            })	0
32443796	32443715	c# how do you use a loop to repeat a stage in an array?	string[] Ques = new string[5];\nQues[0] = "How do you say Good morning  in Portuguese";\nQues[1] = "how do you say how are you;";\nQues[2] = "how do you say I am fine thank you";\nQues[3] = "How do you say is everything ok";\nQues[4] = "how do you say yes";\n\nforeach (string Q in Ques)\n{\n    Console.WriteLine(Q);\n    string Answer = Console.ReadLine();\n    int value;\n    while (int.TryParse(Answer, out value))\n    {\n        Console.WriteLine("please enter a word");\n        Answer = Console.ReadLine();\n    }\n}	0
1471324	1471297	issues coming under XML description	6b25ad0c-8223-49e7-ad94-a132127692c3	0
34136578	34136504	Adding value to a dictionary that its values is a list	List<string> list;\nif(!providerLevelChanges.TryGetValue(someKey, out list))\n{\n    list = new List<string>();\n    providerLevelChanges.Add(someKey, list);\n}\n\nlist.Add(someNewValue);	0
26201596	26198500	Dynamically add all pictureboxes to list?	foreach(var pb in this.Controls.OfType<PictureBox>())\n{\n  //do stuff\n}	0
12280503	12277858	Pass a parameter to a WCF service constructor	var uris = new Uri[1];\n        uris[0] = new Uri("http://localhost:8793//Service/ntService/");\n        var serviceHost = new CustomServiceHost(Container,typeof(Service),uris);\n        serviceHost.AddDefaultEndpoints();	0
22045682	22045577	Using LINQ to create pairs from two different list where the entries have same attribute	var requestWithMatches = from req in _requests\n                          join resp in _responses\n                             on req.RequestId equals resp.RequestId\n                          select new CallPair(req, resp);	0
10380800	10380609	Create SQL Server database during application installation	Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);	0
1008104	1004316	range : apply formatting to a sub section in the range	object srchText="Text to be searched and formatted differently from the rest of the range";\n    oTable.Cell(countRow, 2).Range.Select();\n    var selectUpdateComment=oTable.Cell(countRow, 2).Range.Application.Selection;\n    selectUpdateComment.Find.Execute2007(ref srchText, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing);\n\n    if(selectUpdateComment.Find.Found) {\n        selectUpdateComment.Font.Bold=1;\n        selectUpdateComment.Font.Underline=WdUnderline.wdUnderlineSingle;\n    }	0
11229246	11229077	Searching Files with sequence number in a specific order in C#	var path = //your path\nvar files = Directory.GetFiles(path, "*_*.jpg");\n//group only by the bit of the filename before the '_'\nvar groupedBySamePre_Value = files.GroupBy(p => Path.GetFileNameWithoutExtension(p).Split('_')[0]);\nforeach (var group in groupedBySamePre_Value)\n{\n  //this is a new file group pdf\n  foreach (var file in group.OrderBy(p => p))\n  {\n    //add the file to the pdf\n  }\n  //end of file group pdf\n}	0
9562675	9559606	Regex date time matching	string f0 = "(?:(\\d{1,2})/(\\d{1,2})/(\\d{2,4}))";\nstring f1 = "(?:(\\s\\d{1,2})\\s+(jan(?:uary){0,1}\\.{0,1}|feb(?:ruary){0,1}\\.{0,1}|mar(?:ch){0,1}\\.{0,1}|apr(?:il){0,1}\\.{0,1}|may\\.{0,1}|jun(?:e){0,1}\\.{0,1}|jul(?:y){0,1}\\.{0,1}|aug(?:ust){0,1}\\.{0,1}|sep(?:tember){0,1}\\.{0,1}|oct(?:ober){0,1}\\.{0,1}|nov(?:ember){0,1}\\.{0,1}|dec(?:ember){0,1}\\.{0,1})\\s+(\\d{2,4}))";\n string f2 = "(?:(jan(?:uary){0,1}\\.{0,1}|feb(?:ruary){0,1}\\.{0,1}|mar(?:ch){0,1}\\.{0,1}|apr(?:il){0,1}\\.{0,1}|may\\.{0,1}|jun(?:e){0,1}\\.{0,1}|jul(?:y){0,1}\\.{0,1}|aug(?:ust){0,1}\\.{0,1}|sep(?:tember){0,1}\\.{0,1}|oct(?:ober){0,1}\\.{0,1}|nov(?:ember){0,1}\\.{0,1}|dec(?:ember){0,1}\\.{0,1})\\s+([0-9]{1,2})[\\s,]+(\\d{2,4}))";\n\nMatchCollection mc = Regex.Matches(content, f0 + "|" + f1 + "|" + f2, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);	0
536699	536636	Write Array to Excel Range	object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];\n        for (int r = 0; r < dt.Rows.Count; r++)\n        {\n            DataRow dr = dt.Rows[r];\n            for (int c = 0; c < dt.Columns.Count; c++)\n            {\n                arr[r, c] = dr[c];\n            }\n        }\n\n        Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];\n        Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];\n        Excel.Range range = wsh.get_Range(c1, c2);\n\n        range.Value = arr;	0
5996952	5996841	JavaScriptSerializer. How to ignore property	public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\n{\n  //...\n  if (!object.ReferenceEquals(dictionary["MyProperty"],null)){\n    // My Code\n  }\n  //...\n}	0
784898	784886	Need UltraTree Clone Method - Problem with reference	private ItemType CloneDeep(ItemType node)\n{\n    ItemType clone = new ItemType();\n    clone.Property1 = node.Property1;\n    clone.Property2 = node.Property2;\n\n    foreach ( ItemType child in node.Nodes)\n    {\n        clone.Nodes.add(CloneDeep(child));\n    }\n    return clone;\n}	0
1972000	1967383	WPF Datagrid doesn't show resultset	dataGrid1.ItemsSource = search.ToList();	0
25890674	25889930	Reverse a boolean of an ObservableCollection	foreach (var data in DonneesBrutes.SelectedItems)\n{\n    foreach (var item in viewModel.ActiviteCollection.Where(c => c.PMRQTOTMActivite == DonneesBrutes.CurrentItem.ToString()))\n    {\n        item.MyBoolean = !item.MyBoolean;\n    }\n}	0
18698865	18698824	Compare 2 List<string> with a LIKE clause	var results = files.Where(x => fileStub.Any(y => x.Contains(y))).ToList();	0
10476306	10476130	Competitions: Storing an arbitrary number of fields	t_Comp_Data\n-----------    \nCompId  \nName  \nSurname  \nEmail \nField1 \nField2 \nField3 \n... \nFieldn	0
4114895	4114631	Run process in BackgroundWorker	fflush(stdout);	0
23488766	23461299	C# IMAP SMTP mail client for Windows Phone 8	System.Net.Sockets	0
5225537	5225418	GridView from CodeBehind select row and postback	void dataGrid_ItemCreated(object sender, DataGridItemEventArgs e)\n    {\n        if(e.Item.ItemType == ListItemType.Item)\n        {\n            var item = e.Item.DataItem;  // <- entity object that's bound, like person\n            var itemIndex = e.Item.ItemIndex; // <- index\n        }\n\n    }	0
32040690	32040408	C# json loop parse using json.net	List<string> namesList = new List<string>();\n        dynamic json = JsonConvert.DeserializeObject(jsonText);\n\n        foreach (var item in json["libraries"])\n        {\n            namesList.Add((string)item["name"]);\n        }	0
7712685	7712418	How can I check a method is called with a specific parameter on a mock object?	Arg<IViewModel>.Matches (vm => vm.Person.Name == "Peter" )	0
12885967	12885322	Entity Framework - Foreign key in sub-object	this.HasRequired(t => t.Author).WithMany().Map(m => m.MapKey("AuthorId"));	0
20171140	20162561	How to do test expectations in container.Resolve with arguments	public static T Resolve<T>(this IUnityContainer container, \n                            params ResolverOverride[] overrides);	0
32262464	32262382	How do I parse an integer, using the rule that +5 is not valid but 5 is?	int number;\nvar input = numberTextBox.Text;\nif (!input.StartsWith("+") && int.TryParse(input, out number))\n{\n    //valid input, check if it's between 1-10\n}	0
18108252	18107039	Timer Elapsed Event with Kinect SDK	Private timer As New Windows.Threading.DispatcherTimer\n\ntimer.Interval = New TimeSpan(0, 0, 0, 1)\nAddHandler timer.Tick, AddressOf timer_Tick\ntimer.Start()\n\nPrivate Sub timer_Tick(ByVal Sender As Object, ByVal e As EventArgs)\n    'do something\nEnd Sub	0
23094476	23079031	Separating IdentityUser from UserProfile	if (ModelState.IsValid)\n        {\n            var user = new ApplicationUser {UserName = model.UserName};\n            var result = await UserManager.CreateAsync(user, model.Password);\n\n            if (result.Succeeded)\n            {\n                var newUser = db.ApplicationUsers.Find(user.Id);\n\n                var profile = new Profile\n                {\n                    FirstName = model.FirstName,\n                    LastName = model.LastName,\n                    Email = model.Email,\n                    Identity = newUser,\n                };\n\n                db.Profiles.Add(profile);\n                db.SaveChanges();\n\n                await SignInAsync(user, isPersistent: false);\n                return RedirectToAction("Index", "Home");\n            }\n            else\n            {\n                AddErrors(result);\n            }\n        }	0
32415387	32415281	Persisting Nodatime Instant in SQL Server with ServiceStack / OrmLite	[CustomField]	0
21128881	21128872	How do I convert part of a string to int in C#?	var myString = "john10smith250";\nvar myNumbers = myString.Where(x => char.IsDigit(x)).ToArray();\nvar myNewString = new String(myNumbers);	0
31681378	31681275	Automated way to write a wrapper and interface for dependency injection of third party libraries?	class MyFooWrapper : IFoo\n{\n   private Foo _foo;\n    // methods exposed by IFoo\n }	0
27622269	27621916	mscorlib Source Stream should throw a StackOverflowException	public readonly Stream Null=new NullStream()	0
9688199	9688159	How to quote \" (slash double-quote) in a string literal?	string s = "\\\"\\\"";	0
3800071	3800035	textbox always putting cursor at beginning of text	private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {\n        e.KeyChar = char.ToUpper(e.KeyChar);\n    }	0
25035362	25035286	Attachment is not going with email	String sFile = "abc.pdf";\nvar oAttch = new System.Web.Mail.MailAttachment(Server.MapPath(sFile));\n\noMail.Attachments.Add(oAttch);	0
11300401	11299457	Apply background color to all labels in a GridView	protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n\n            foreach (DataControlFieldCell dcfc in e.Row.Controls)\n            {\n                DataControlFieldCell dataControlFieldCell = dcfc;\n\n                foreach(var control in dataControlFieldCell.Controls)\n                    if (control is Label)\n                        HighLight_Hours((Label) control);\n\n            }\n        }\n    }	0
4617609	4617571	How to implement this with a pattern or maybe lambda syntax?	void SetupAndCleanup( Action<int> methodCode )\n{\n    // Setup code here\n    int x = 1;\n\n    try\n    {\n        methodCode(x);\n    }\n    finally\n    {\n        // cleanup code here\n        x = 0;\n    }\n}	0
3718648	3718380	Winforms Double Buffering	protected override CreateParams CreateParams {\n  get {\n    CreateParams cp = base.CreateParams;\n    cp.ExStyle |= 0x02000000;  // Turn on WS_EX_COMPOSITED\n    return cp;\n  }\n}	0
13382958	13382823	Find failed validators asp.net	function performCheck()\n{\n\nif(Page_ClientValidate())\n{\n\n//Do something to log true/ false\n}\n\n}	0
2874698	2874620	Linq to SQL - Inserting entities with relations	var recipe = new Recipe { Name = "Dough" };\n\nvar ingredients = new []\n{ \n   new Ingredient { Name = "water", Unit = "cups", Amount = 2.0 }, \n   new Ingredient { Name = "flour", Unit = "cups", Amount = 6.0 }, \n   new Ingredient { Name = "salt", Unit = "teaspoon", Amount = 2.0 }\n};\n\nforeach (var ingredient in ingredients)\n{\n   var relation = new IngredientsRecipesRelations();\n\n   relation.Ingredient = ingredient;\n\n   recipe.IngredientsRecipesRelations.Add(relation);\n}\n\nDataContext.Recipes.InsertOnSubmit(recipe);\nDataContext.SubmitChanges();	0
15416070	15415987	calling the sum of certain values only from a parameter array	foreach (int val in vals)\n{\n    if(val < 10)\n    {\n        sum += val;\n    }\n}	0
32267774	32267688	Convert Epoch to DateTime SQL Server	1440753397054 / 1000 = 1440753397,054	0
27318710	27301718	Get user groups in AD with nested groups	DirectorySearcher searcher = new DirectorySearcher();\nDirectoryEntry rootEntry = new DirectoryEntry(_ldap, _loginName, _password, AuthenticationTypes.ReadonlyServer);\n\nsearcher.SearchRoot = rootEntry;\nsearcher.SearchScope = SearchScope.Subtree;\nsearcher.Filter = "(&(sAMAccountName=" + filter.Split('\\')[1] + ")(objectClass=user))";\nsearcher.PropertiesToLoad.Add("memberOf");\nsearcher.PropertiesToLoad.Add("displayname");\n\nSearchResult sr = searcher.FindOne();\nDirectoryEntry userDirectoryEntry = result.GetDirectoryEntry();\nuserDirectoryEntry.RefreshCache(new string[] { "tokenGroups" });\n\nforeach (byte[] byteEntry in userDirectoryEntry.Properties["tokenGroups"])\n{\n   if (CompareByteArrays(byteEntry, objectSid))\n   {\n         isMember = true;\n         break;\n   }\n}	0
5664416	5664286	C# Capitalizing string, but only after certain punctuation marks	string expression = @"[\.\?\!,]\s+([a-z])";\nstring input = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi";\nchar[] charArray = input.ToCharArray();\nforeach (Match match in Regex.Matches(input, expression,RegexOptions.Singleline))\n{\n    charArray[match.Groups[1].Index] = Char.ToUpper(charArray[match.Groups[1].Index]);\n}\nstring output = new string(charArray);\n// "I ate something. But I didn't: instead, No. What do you think? I think not! Excuse me.moi"	0
23224163	23223755	How to update/change/empty data in txtbox without showing error	string myVar1;\n\n//Something that assigns a value to myVar1\n\nif(String.IsNullOrEmpty(myVar1))\n{\n myVar1 = "0";\n}\nelse\n{\n  int number;\n  bool result = Int32.TryParse(myVar1, out number);\n  if (result)\n  {\n     //you have a valid input and valid parse, do whatever you need with number     variable     \n  }\n  else\n  {\n    //bad input, reset to blank and show error message\n  }	0
6453038	5493843	How to gracefully unload a child AppDomain that has threads running	runnerThread.IsBackground = true;	0
7705403	7705386	Is it possible to have a delegate as attribute parameter?	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]\npublic class WorkspaceAttribute : Attribute\n{\n    public ConnectionPropertiesDelegate ConnectionDelegate { get; set; }\n\n    public WorkspaceAttribute(Type delegateType, string delegateName)\n    {\n         ConnectionDelegate = (ConnectionPropertiesDelegate)Delegate.CreateDelegate(delegateType, delegateType.GetMethod(delegateName));\n    }\n}\n\n[Workspace(typeof(TestDelegate), "GetConnection")]\npublic class Test\n{\n}	0
21697716	21697585	How to make QR Barcode using c#	class Programm\n{\n    static void Main(string[] args)\n    {\n        System.QRCode qrcode = new System.QRCode();\n    }\n}	0
11247398	11247303	Getting the MethodInfo of static method of a static class	var methods = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);	0
8233763	8233411	Randomizing regex string replacement	private const string ValidCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@<()!?~+";\nprivate Random random = new Random();\n\nprivate string RandomPasswordGenerator(int length)\n{\n    string password = string.Empty;\n    while (length > 0)\n    {\n        password += ValidCharacters[random.Next(0, ValidCharacters.Length - 1)];\n        length--;\n    }\n    return password;\n}	0
15304225	15304142	Server.MapPath with ~	string driveLetter =  Server.MapPath("~/Docs");	0
24764853	24764796	If Statement with Multiple Empty Textboxes	if (txtUserID.Text == String.Empty || txtFN.Text == String.Empty || txtMI.Text == String.Empty || txtLN.Text == String.Empty || txtUsername.Text == String.Empty || txtPassword.Text == String.Empty || txtConfirm.Text == String.Empty)\n        {\n            XtraMessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\n        }	0
23238781	23102775	USSD received message decoding	String origin = "0645063306280642002006270644062F06410639003A00200037002C003600320035002E0030003000200020000A06270644063506440627062D064A0629003A0030002E0030003000200020000A00200627064406440627062D0642002006270644062F06410639003A0030002E003000300020";\nif (origin.Count() % 2 == 0)\n            {\n                List<short> list = new List<short>();\n                List<byte> bytes = new List<byte>();\n                var encode = Encoding.GetEncoding("UCS-2");\n                for (int i = 0; i < origin.Count(); i += 4)\n                {\n                    list.Add(Convert.ToInt16(origin.Substring(i, 4), 16));\n                }\n                foreach (var item in list)\n                {\n                    bytes.Add((byte)(item & 255));\n                    bytes.Add((byte)(item >> 8));\n                }\n                return encode.GetString(bytes.ToArray());\n            }	0
10981029	10927298	Reactive Extensions: Process events in batches + add delay between every batch	var tick = Observable.Interval(TimeSpan.FromSeconds(5));\n\neventAsObservable\n.Buffer(50)\n.Zip(tick, (res, _) => res)\n.Subscribe(DoProcessing);	0
20324756	20324668	how to convert mm-dd-yyyy hh-mit-sec pm to yyyy-mm-dd date format	DateTime.Now.ToString("yyyy-MM-dd");	0
3993542	3993520	c#: initialize a DateTime array	DateTime[] dateTimes = new DateTime[]\n{\n    new DateTime(2010, 10, 1),\n    new DateTime(2010, 10, 2),\n    // etc\n};	0
11031795	11014148	How to decrypt  a pdf file by supplying password of the file as argument using c#?	string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nstring InputFile = Path.Combine(WorkingFolder, "test.pdf");\nstring OutputFile = Path.Combine(WorkingFolder, "test_dec.pdf");//will be created automatically\n//You must provide owner password but not the user password .\nprivate void DecryptFile(string inputFile, string outputFile)\n{\n\n    string password = @"secret"; // Your Key Here           \n    try\n    {\n        PdfReader reader = new PdfReader(inputFile, new System.Text.ASCIIEncoding().GetBytes(password));\n\n            using (MemoryStream memoryStream = new MemoryStream())\n            {\n                PdfStamper stamper = new PdfStamper(reader, memoryStream);\n                stamper.Close();\n                reader.Close();\n                File.WriteAllBytes(outputFile, memoryStream.ToArray());\n            }\n\n    }\n    catch (Exception err)\n    {\n        Console.WriteLine(err.Message);\n    }\n}	0
13279545	13279436	See command line arguments being passed to a program	wmic process	0
16373122	16373027	Redirect on button click in alert-dialog	ClientScript.RegisterStartupScript(typeof(Page), "alertMessage", \n "<script type='text/javascript'>alert('Inserted Successfully');window.location.replace('http://stackoverflow.com');</script>");	0
10797858	10797787	How download file from blob?	Content-Type: application/octet-stream	0
27169210	27148418	Posting to Facebook wall using HttpMethod.POST unity3D	FB.API ("/me/feed", HttpMethod.POST, LogCallback,   new Dictionary<string, string>() {{"access_token", FB.AccessToken},{"message","Test"}});	0
4036197	4036172	A simple C# question I hope! Add additional properties to Buttons	public class MyButton : Button\n{\n  public string ExtraProperty {get;set;}\n}	0
28896318	28896211	"value must be a number less than infinity" error when the variable is a integer	var variavels =  DataAccess.Instance.tabela1vert0caso1W.AsEnumerable()\n    .Select(row => row.Field<int>("Variavel"));\ndouble max = variavels.Where(d => d >= value).Max();\ndouble min = variavels.Where(d => d <= value).Min();	0
30790187	30789447	Instead of dataGridView in C# windows application, what should I use for console application to display a table from sql server?	using System;\nusing System.Data;\nusing System.Data.SqlClient;\n\nSqlConnection conn = new SqlConnection(***Your Connection String Here***);\nconn.Open();\n\nSqlDataAdapter adpt = new SqlDataAdapter("Select ID, Dish, Price From RestaurantMenu", conn);\n\nDataTable dt = new DataTable();\nadpt.fill(dt);\n\nconn.Close();\n\nforeach (DataRow dr in dt.Rows){\n\n     console.WriteLine(dr["ID"].ToString() + " | " + dr["Dish"].ToString() + " | " + dr["Price"].ToString());\n\n}	0
31589412	31589118	Fix the height of table in html while printing	400 / 8 = 50	0
161565	161556	Convert IDictionary<string, string> keys to lowercase (C#)	StringComparer.OrdinalIgnoreCase	0
24509386	24508911	Populate DropDownList inside template field in GridView with data from CodeBehind	protected void GrdPDataEdit_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        //Replace your find corntrol code with this \n        DropDownList drpnop  = (DropDownList)e.Row.FindControl("dropdownnop");\n\n        if (drpnop != null)\n        {\n            drpnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");\n            drpnop.DataTextField = "DESC";\n            drpnop.DataValueField = "DESC";\n            drpnop.DataBind();\n        }\n    }\n}	0
20462517	20462494	Length of array created by using split string	int length = strSplit.length	0
28056117	28048346	Change Backcolor of a button in a cell of a DataGridViewButtonColumn	private void dataGridView1_CellPainting(object sender, \n                                        DataGridViewCellPaintingEventArgs e)\n{\n   if (e.CellStyle.BackColor == Color.Yellow)\n   {\n        int pl = 12;  //  padding left & right\n        int pt = 2;   // padding top & bottom\n        int cw = e.CellBounds.Width;\n        int ch = e.CellBounds.Height;\n        int x = e.CellBounds.X;\n        int y = e.CellBounds.Y;\n\n        e.PaintBackground(e.ClipBounds, true);\n        e.PaintContent(e.CellBounds);\n\n        Brush brush = SystemBrushes.Window;\n        e.Graphics.FillRectangle(brush, x, y, pl + 1 , ch - 1);\n        e.Graphics.FillRectangle(brush, x + cw - pl - 2, y, pl + 1, ch - 1);\n        e.Graphics.FillRectangle(brush, x, y, cw -1 , pt + 1 );\n        e.Graphics.FillRectangle(brush, x, y + ch - pt - 2 , cw -1 , pt + 1 );\n\n        e.Handled = true;\n    }\n}	0
7416736	7416686	How to search for a specific string in an string array in C# 3.0	int index = -1;\nstring find = "Five";\n\nfor(int i = 0; i < this_array.Length; i++)\n{\n   if(string.IsNullOrEmpty(this_array[i]))\n      continue;\n   if(this_array[i].ToLowerInvariant().Contains(find.ToLowerInvariant()))\n   {\n      index = i;\n      break;\n   }\n}	0
2643390	2643000	Changing the user language in an asp.net application based on user choice	protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)\n{           \n if (Session["userCultureInfo"] != null)\n  {             \n   Thread.CurrentThread.CurrentUICulture = new CultureInfo(Session["userCultureInfo"].ToString());\n   }           \n}	0
29737542	29731099	WaitForSeconds in Unity3D	FixedUpdate()	0
15339915	15218348	How to detect writeable capacity of nfc chip	int writeableSize = System.BitConverter.ToInt32(message.Data.ToArray(), 0);	0
3502930	3501966	Enums with string values and finding enum by value	public enum Fruit\n{\n    [Description("Apple")]\n    A,\n    [Description("Banana")]\n    B,\n    [Description("Cherry")]\n    C\n}\n\npublic static class Util\n{\n    public static T StringToEnum<T>(string name)\n    {\n        return (T)Enum.Parse(typeof(T), name);\n    }\n\n    public static string ToDescriptionString(this Enum value)\n    {\n        FieldInfo fi = value.GetType().GetField(value.ToString());\n\n        DescriptionAttribute[] attributes =\n            (DescriptionAttribute[])fi.GetCustomAttributes(\n            typeof(DescriptionAttribute),\n            false);\n\n        if (attributes != null &&\n            attributes.Length > 0)\n            return attributes[0].Description;\n        else\n            return value.ToString();\n    }\n}	0
13161375	10312347	Sending Cart items to Paypal using the SOAP API in ASP.Net	PaymentDetailsType[] pmtDetails = new PaymentDetailsType[1];\n    pmtDetails[0] = new PaymentDetailsType();\n    var pmtIndex = 0;\n\n    PaymentDetailsItemType[] items = new PaymentDetailsItemType[cartItems.Count];\n\n    foreach (var item in cartItems)\n    {\n        var i = new PaymentDetailsItemType()\n        {\n            Name = item.productName,\n            Number = item.productID.ToString(),\n            Quantity = item.quantity.ToString(),\n            Amount = new BasicAmountType(){ currencyID = CurrencyCodeType.GBP, Value = item.productPrice.ToString() }\n        };\n        items[pmtIndex] = i;\n        pmtIndex++;\n    }\n    //reqDetails.p\n    //reqDetails.PaymentDetails = pmtDetails;\n    //hOrderTotal.Value\n    // \n    pmtDetails[0].PaymentDetailsItem = items;\n    pmtDetails[0].OrderTotal = new BasicAmountType() { currencyID = CurrencyCodeType.GBP, Value = HttpContext.Current.Session["_OrderTotalLessShippingAmount"].ToString() };\n    reqDetails.PaymentDetails = pmtDetails;	0
2832465	2831535	Help creating a ColumnName Convention using FluentNHibernate	public class ColumnNameConvention : IPropertyConvention\n{\n    public void Apply(IPropertyInstance instance)\n    {\n        instance.Column(instance.Property.Name.ChangeCamelCaseToUnderscore());\n    }\n}	0
2290311	2290275	Clean way to pass an enum to a function with the option of passing null in C#	int CountWires(EStatus? status, ESize? size, EVoltage? voltage, EPhase? phase)\n{\n    int count = 0;\n    foreach (Wire wire in _connectedWires)\n    {\n        if (status.HasValue && wire.Status != status.Value) continue;\n        if (size.HasValue && wire.Size != size.Value) continue;\n        ...\n        ++count;\n    }\n    return count;\n}	0
15061825	15061802	How to delete sub folders and files if resides using asp.net c#	global::System.IO.Directory.Delete(@"C:\Files\aaa-426962", true);	0
11722239	11722176	Searching pdfs in a C# winform	var reader = new PdfReader(pdfPath); \nStringWriter output = new StringWriter();  \n\nfor (int i = 1; i <= reader.NumberOfPages; i++) \n    output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));\n\n//now you can search for the text from outPut.ToString();	0
23021798	23021739	How to convert a passing string paramatre to int on asp.net MVC 3	public ViewResult Search(string textboxmvc)\n{\n    int parsedId;\n    int.TryParse(textboxmvc, out parsedId);\n    var student = from i in db.StudentSet  select i;\n\n    if (!String.IsNullOrEmpty(textboxmvc))\n    {\n        student = student.Where(s => s.FirstName.ToUpper().Contains(textboxmvc.ToUpper())\n                                   || s.LastName.ToUpper().Contains(textboxmvc.ToUpper())||s.Id==parsedId);\n\n    }\n\n     return View(student);\n\n}	0
13898918	13898190	Trying to set fill color of xaml rectangle in C# but changes not reflected at runtime	c.A = 255;	0
32509363	32509275	How i can check for to file extentions with if statement for FileUpload	var files = new [] { FileExtention, FileExtention2, FileExtention3, FileExtention4, FileExtention5 };\nvar extensions = new [] {".jpg", ".png"};\nif (files.All(f => extensions.Contains(f.ToLower())))\n{\n   //...do stuff...\n}	0
18314260	18313317	Replace same multiple chars with one char	Regex reg = new Regex(@"(-){2,}");\nstring s = reg.Replace("-----regex----is---cool", "$1");//=> -regex-is-cool	0
1498437	1498431	Is there any easy way to increment a DateTime by monthly/yearly/daily units without having to parse it out like crazy?	DateTime myDateTime = DateTime.Now.AddMonths(1);	0
13623596	13623554	Parallel loop in winrt	Parallel.ForEach	0
2797728	2797669	Removing specific XML tags	XElement document = XElement.Load("path to the file");\n\nList<string> sources = new List<string>();\nforeach (var mediaElement in document.Descendents("media"))\n{\n   if (sources.Contains((string)mediaElement.Attributes("src"))\n   {\n      mediaElement.Remove();\n   }\n   else\n   {\n      sources.Add((string)mediaElement.Attributes("src"));\n   }\n}\n\ndocument.Save("path to the file");	0
26494266	26484454	How to send message from client to server using Apache Thrift	// put together a protocol/transport stack as required by the server\nTTransport transport = new TSocket("localhost", 9090);\nTProtocol protocol = new TBinaryProtocol(transport);\nCalculator.Client client = new Calculator.Client(protocol);\n\n// make sure the transport is open\ntransport.Open();\n\n// call a method via RPC\nclient.ping();	0
7958233	7958174	How to open Excel File In ASP.NET with C#	connStr  = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + absoluteDir + ";Extended Properties="Excel 12.0 Xml;HDR=YES";	0
16677799	16527609	Powershell v3 Remoting from C# using Enter-PSsession	int iRemotePort = 5985;\nstring strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell";\nstring strAppName = @"/wsman";\nAuthenticationMechanism auth = AuthenticationMechanism.Negotiate;\n\nWSManConnectionInfo ci = new WSManConnectionInfo(\n    false,\n    sRemote,\n    iRemotePort,\n    strAppName,\n    strShellURI,\n    creds);\nci.AuthenticationMechanism = auth;\n\nRunspace runspace = RunspaceFactory.CreateRunspace(ci);\nrunspace.Open();\n\nPowerShell psh = PowerShell.Create();\npsh.Runspace = runspace;	0
16659330	16656492	Obtaining a list of direct reports from the current user	foreach (string objProperty in rs.Properties["DirectReports"])\n            {\n                isManager = true;\n                string emp = objProperty.ToString();\n                string[] setp = new string[1];\n                setp[0] = "DC"; //If your users are in a OU use OU \n\n                emp = emp.Split(setp, StringSplitOptions.None)[0];\n                emp = emp.Replace("CN=", "");\n                emp = emp.TrimEnd(',');\n                emp = emp.Replace("\\, ", ", ");\n                emp = emp.Split(',')[0];\n                //emps.Add(emp);\n            }	0
27156626	27141762	How do we set the AutoCAD layer viewport override values	Dim oLay As LayerTableRecord = TryCast(oTr.GetObject(oId, OpenMode.ForWrite), LayerTableRecord)\n\noLay.GetViewportOverrides(oVpId).Color or .Linetype	0
4338763	4338714	Creating dynamic Linq query based on property values	IQueryable<Accommodation> query = db.Accommodation;\n\nif (filterModel.Hotel)      query = query.Where(a => a.Hotel);\nif (filterModel.Apartment)  query = query.Where(a => a.Apartment);\nif (filterModel.Guesthouse) query = query.Where(a => a.Guesthouse);\n\nreturn query;	0
3107195	3107170	LINQ Find Null Objects in List	return myLists.Count(ml => ml.Defects.Contains(null));	0
1477854	1477818	Anyway to make a IList.Contains() act more like a wildcard contains?	if (DBExclusionList.Any(s => s.Contains(dbx.Name.ToString())))	0
283402	283378	LinqToXML XElement to XmlNode	XmlDocument myXmlNode = new XmlDocument();\nusing (XmlReader reader = myXElement.CreateReader())\n{\n    myXmlNode.Load(reader);\n}	0
4730891	4721888	how to parse or convert	public class Parsers\n    {\n        private Parsers() { }\n\n        public static void SetLong(ref long item, object value)\n        {\n            long temp;\n            if (value != null && long.TryParse(value.ToString(), out temp)) { item = temp; }\n        }\n\n        public static void SetDateTime(ref DateTime item, object value)\n        {\n            DateTime temp;\n            if (value != null && DateTime.TryParse(value.ToString(), out temp)) { item = temp; }\n        }\n\n        public static void SetInt(ref int item, object value)\n        {\n            int temp;\n            if (value != null && int.TryParse(value.ToString(), out temp)) { item = temp; }\n        }\n\n        public static void SetString(ref string item, object value)\n        {\n            if (value != null) { item = value.ToString(); }\n        }\n    }	0
9281524	9281496	How do I order results of a List<IDictionary> object using Linq?	var orderedList = dictionaryList.OrderBy(d => d["Color"]);	0
15029523	15029216	selecting previous day files from huge list of files	FileInfo[] files = (new DirectoryInfo(dirPath)).GetFiles("*.xml");\n\nDateTime lowDate = DateTime.Today.AddDays(-1);\nDateTime highDate = DateTime.Today.AddHours(-2.0);\n\n string[] selectedFiles = (from c in files\n                                          where c.CreationTime >= lowDate && c.CreationTime < highDate\n                                          select c.FullName).ToArray();	0
27580439	27580398	How do I create a new line in TextBox whenever it starts a new row in C#?	textBox1.GetFirstCharIndexFromLine(line);	0
13616805	13615708	How can I Read more info ZipEntry(s) inside of a ZipEntry with sharpZipLibrary?	using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n{\n  foreach (ZipEntry e in zip)\n  {\n    if (header)\n    {\n      System.Console.WriteLine("Zipfile: {0}", zip.Name);\n      if ((zip.Comment != null) && (zip.Comment != "")) \n        System.Console.WriteLine("Comment: {0}", zip.Comment);\n      System.Console.WriteLine("\n{1,-22} {2,8}  {3,5}   {4,8}  {5,3} {0}", "Filename", "Modified", "Size", "Ratio", "Packed", "pw?");\n      System.Console.WriteLine(new System.String('-', 72));\n      header = false;\n    }\n      System.Console.WriteLine("{1,-22} {2,8} {3,5:F0}%   {4,8}  {5,3} {0}", e.FileName, e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), e.UncompressedSize, e.CompressionRatio, e.CompressedSize, (e.UsesEncryption) ? "Y" : "N");  \n  }\n}	0
21303670	21303620	Recording time/date from C# windows application form is inserted into access database?	INSERT INTO electricity (Asset_name,Asset_number,Emp_id,timestamp) \n   VALUES (@Asset_name, @Asset_number,@Emp_id,now())	0
25734492	25722196	c# Find and Replace Text in a Word Document	var templateEngine = new swxben.docxtemplateengine.DocXTemplateEngine();\ntemplateEngine.Process(\n    source = "template.docx",\n    destination = "dest.docx",\n    data = new {\n       Name = "SWXBEN"\n    }\n);	0
5561257	5561016	Delete items from a list box with checkboxs enabled. By checking the files you wish to delete	private void btnSubmit_Click(object sender, EventArgs e)\n{\n       int listCount = listView1.CheckedItems.Count;\n       itemsChecked.Text = listCount.ToString(); \n}	0
28281671	28274227	How to add looped items from ItemTemplate into array	var reference = (PageReference)CurrentPage["Root"];\nvar children = DataFactory.Instance.GetChildren(reference);\nvar list = new List<DateTime>();\n\nforeach (PageData pd in children)\n{\n    list.Add((DateTime)pd["Date"]);\n}	0
5232424	5232396	Use Lambda Expressions in a Query (C#)	context.Orders.Where(o => o.OrderDetails.Any(d => d.Description == "PickMe" || d.Description == "TakeMe"));	0
23301189	23300469	Intersection with image only in a picturebox	Bitmap.GetPixel	0
22340302	22340213	saveFileDialog create new folder and save inside it	string pathDestination = System.IO.Path.Combine(path, System.IO.Path.GetFileName(mySaveFileDialog.FileName));	0
7614747	7614682	Marshal structure with integer references to C#	[StructLayout(LayoutKind.Sequential)]\npublic struct MyCStruct {\n  public int a;\n  public IntPtr b;\n}	0
10682259	10681796	Button click Open richTextBox and display the readfile	private void button1_Click(object sender, EventArgs e)\n{\n    //test call of the rtBox\n    ShowRichMessageBox("Test", File.ReadAllText("test.txt"));\n}\n\n/// <summary>\n/// Shows a Rich Text Message Box\n/// </summary>\n/// <param name="title">Title of the box</param>\n/// <param name="message">Message of the box</param>\nprivate void ShowRichMessageBox(string title, string message)\n{\n    RichTextBox rtbMessage = new RichTextBox();\n    rtbMessage.Text = message;\n    rtbMessage.Dock = DockStyle.Fill;\n    rtbMessage.ReadOnly = true;\n    rtbMessage.BorderStyle = BorderStyle.None;\n\n    Form RichMessageBox = new Form();\n    RichMessageBox.Text = title;\n    RichMessageBox.StartPosition = FormStartPosition.CenterScreen;\n\n    RichMessageBox.Controls.Add(rtbMessage);\n    RichMessageBox.ShowDialog();\n}	0
19676794	19676588	How to access Children Node of Children in Tree view WPF	foreach (var parent in Nodes)\n{\n\n\nif (parent.IsChecked == true)\n{\nforeach (var item in parent.Children)\n{\nif (item.IsChecked == true)\n{\n}\nelse\n{\n} \n foreach(var vtemp in item.Children)\n {\n  foreach (var vtemp1 in vtemp.Children)\n     {\n       // and did my logic\n     }\n   }\n}\nelse\n{\n}   \n}	0
4120280	4120202	Load a bitmap to a PictureBox control	pictureBox2.Image = objBitmap;	0
13375417	13249220	Using text SQL with LINQ	context.viewSavedFromYourSql.Where(x => x.Name.Contains("Anonymous")).Take(20);	0
6320414	6320393	How to create a class which can only have a single instance in C#	public sealed class Singleton\n{\n     public static readonly Singleton instance = new Singleton();\n     private Singleton() {}\n}	0
15016076	14034380	Is there a way to get an object from the context if I only have the entitysetname and the value of a unique property?	public TEntity GetEntityByRowId<TEntity>( Guid rowId) where TEntity : LoggedEntity\n    {\n        return Db.Set<TEntity>().SingleOrDefault(x => x.RowId == rowId);\n    }	0
1981494	1981451	How to pick row from DataGridView?	private void MyGrid_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.KeyData == Keys.Enter)\n        {\n            e.Handled = true;\n            DataGridViewRow currentRow = MyGrid.CurrentRow;\n            MessageBox.Show( Convert.ToString(currentRow.Cells[0].Value));\n        }\n    }	0
21489754	21489435	Trim off last directory/folder without using GetParent()	string input = "/var/mobile/Documents/";\nvar parts = input.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries).ToList();\nparts.RemoveAt(parts.Count - 1);\nstring output = string.Concat("/", string.Join("/", parts), "/");	0
24891034	24890994	Having a contructor extend into a sub-class from an abstract class?	class UsersTypeOne : Users\n{\n    public UsersTypeOne(List<string> SelectedUsers)\n        : base(SelectedUsers)\n    {\n\n    }\n}	0
1275824	1275492	How can I create an unique random sequence of characters in C#?	private string alphabet = "abcdefghijklmnopqrstuvwxyz"; \n   // or whatever you want.  Include more characters \n   // for more combinations and shorter URLs\n\npublic string Encode(int databaseId)\n{\n    string encodedValue = String.Empty;\n\n    while (databaseId > encodingBase)\n    {\n        int remainder;\n        encodedValue += alphabet[Math.DivRem(databaseId, alphabet.Length, \n            out remainder)-1].ToString();\n        databaseId = remainder;\n    }\n    return encodedValue;\n}\n\npublic int Decode(string code)\n{\n    int returnValue;\n\n    for (int thisPosition = 0; thisPosition < code.Length; thisPosition++)\n    {\n        char thisCharacter = code[thisPosition];\n\n        returnValue += alphabet.IndexOf(thisCharacter) * \n            Math.Pow(alphabet.Length, code.Length - thisPosition - 1);\n    }\n    return returnValue;\n}	0
9918424	9918293	How do you do custom validation on FileHelpers?	if (!isEmailValid)\n{\n    throw new InvalidDataException("Email is not valid.");\n}	0
4818730	4818484	Is it possible to parameterize a nunit test	public void CheckAsserts(string value)\n{\n    Assert.IsNotNull(value);\n}\n\n[TestCase("yes!")]\npublic void MyTest(string value)\n{\n    CheckAsserts(value);\n}	0
18050949	18050898	Splitting 2-d array into several 1-d arrays in C#	int[][] data = new int[max number of columns][]	0
18466488	18465853	Add a element at a specific position within xml in wpf c#	string yourxml = "<Profile><profile number = \"1\"><mode>1</mode><mode>2</mode></profile><profile number = \"2\"><mode>1</mode><mode>2</mode></profile><profile number = \"3\"><mode>1</mode><mode>2</mode></profile></Profile>";\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(yourxml);\n\n    //Selecting node with number='3'\n    XmlNode profile;\n    XmlElement root = doc.DocumentElement;\n    profile = root.SelectSingleNode("profile[@number = '3']");\n    XmlElement newChild = doc.CreateElement("mode");\n    newChild.InnerText = "1";\n    profile.AppendChild(newChild);\n    doc.Save("file path");	0
19404242	19403820	Which iterator(other than for, foreach) can be used to count the number of character in a string?	public void CountChar() {\n  String s = Ipstring();\n  foreach (var g in s.GroupBy(c => c)) {\n    Console.WriteLine("{0} : {1}", g.Key, g.Count());\n  }\n}	0
11412260	11412029	C# XML, find node and all his parents	XElement el = doc.Descendants("siteNode")\n                    .FirstOrDefault(child => \n                        child.Attribute("action").Value == ActionName \n                        && \n                        child.Attribute("controller").Value == ControlerName);\n    if (el != null)\n    {\n        var result2 = el.AncestorsAndSelf();\n    }	0
21330641	21330151	Displaying progress dialog only if a task did not finish in specified time	var uploadTask = service.UploadAsync(imagePath);\nvar delayTask = Task.Delay(1000);//Your delay here\nif (await Task.WhenAny(new[] { uploadTask, delayTask }) == delayTask)\n{\n    //Timed out ShowProgress\n    ShowMyProgress();\n    await uploadTask;//Wait until upload completes\n    //Hide progress\n    HideProgress();\n}	0
19786918	19786770	How can I get a node by id in XML?	string filePath = "D:\\XML\\LanguagePack.xml";\nvar fileInfo = new FileInfo(filePath);\nvar xmlDocument = new XmlDocument();\nxmlDocument.Load(fileInfo.FullName);\n\nvar node = xmlDocument.SelectSingleNode("//*[@id='10001']");\nreturn node.InnerText; // return 'Word1_French'	0
8278860	8274976	assistance with writing a unit test for a method with rhino mocks	[Test]\npublic void UsingPartialMocks()\n{\n  MockRepository mocks = new MockRepository();\n  YourClass partialMock =  mocks.PartialMock<YourClass>();\n  Expect.Call(partialMock.Notify(null)).IgnoreArguments();\n  mocks.ReplayAll();\n  partialMock.Initialize(null);\n  mocks.VerifyAll();\n}	0
16635109	16634939	remove item selected of first comboBox from second comboBox c# windows form application	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n        {\n\n            for (int i = 0; i < comboBox2.Items.Count; i++)\n            {\n                if (comboBox2.Items[i] == comboBox1.SelectedItem)\n                {\n                    comboBox2.Items.Remove(comboBox2.Items[i]);\n\n                    i--;\n                }\n            }\n        }	0
5104868	5089310	How to deserialize XML attribute of type long to UTC DateTime?	[XmlRoot]\n[XmlType("Root")]\npublic class MyRoot\n{\n    // ...\n\n    [XmlIgnore]\n    public Dictionary<string, Tuple<int, ChildState>> Children { get; set; }\n\n    [XmlElement("Child")]\n    public MyChild[] ChildrenRaw\n    {\n        get\n        {\n            return Children.Select(c => new MyChild { Key = c.Key, Value = c.Value.Item1, State = c.Value.Item2 }).ToArray();\n        }\n\n        set\n        {\n            var result = new Dictionary<string, Tuple<int, ChildState>>(value.Length);\n            foreach(var item in value)\n            {\n                result.Add(item.Key, new Tuple<int, ChildState>(item.Value, item.State));\n            }\n            Children = result;\n        }\n    }\n}	0
7333283	7333061	How to avoid spaces and empty sections in the report in the state of empty data sources	Set the tablix/table visibility hidden property to = CountRows() = 0\n\nThe CountRows() for a dataset return's the number of rows the query returns.\n\nWhen CountRows() returns 0 rows (no data) the condition return's TRUE \nfor the hidden property of tablix, so it hides the tablix control	0
1144881	1144840	Pad byte[] to 16-byte multiple for AES Encryption	private static void PadToMultipleOf(ref byte[] src, int pad)\n{\n    int len = (src.Length + pad - 1) / pad * pad;\n    Array.Resize(ref src, len);\n}	0
15233046	15232766	How to get values from a table row of textboxes into a List of objects , from ContentPlaceholder	private Siblings GetSiblings(string name, string school, string id)\n{\nSiblings siblings = new Siblings()\n  {\n     Name = name,\n     School = school,\n     Id= id\n\n   }\n\nreturn siblings;\n}\n\n\nprivate CreateSiblingsList()\n{\n   List<Siblings> list = new List<Siblings>();\n\n  // First Sibling, carry on for rest siblings\n   list.Add(GetSiblings(sib1name.Text,sibling1school.Text,sib1id.Text)); \n}	0
7459451	7459397	How to easily run shell commands using c#?	// Start the child process.\n Process p = new Process();\n // Redirect the output stream of the child process.\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.FileName = "YOURBATCHFILE.bat";\n p.Start();\n // Do not wait for the child process to exit before\n // reading to the end of its redirected stream.\n // p.WaitForExit();\n // Read the output stream first and then wait.\n string output = p.StandardOutput.ReadToEnd();\n p.WaitForExit();	0
3458474	3458318	How can I get a List from all nodes in a tree using LINQ?	class Node\n    {\n    public Node()\n    {\n        Children = new List<Node>();\n    }\n\n    public IEnumerable<Node> GetSubTree()\n    {\n        return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });\n        //Post-order traversal\n    }\n\n    public List<Node> Children { get; set; }\n}\n\nclass Tree\n{\n    public Tree()\n    {\n        Roots = new List<Node>();\n    }\n\n    public IEnumerable<Node> GetAllNodes()\n    {\n        return Roots.SelectMany(root => root.GetSubTree());\n    }\n\n    List<Node> Roots { get; set; }\n}	0
19945908	19941569	Populate datagridview combobox	(dataGridView1.Columns[0] as DataGridViewComboBoxColumn).DataSource \n = new List<string> { "Apples", "Oranges", "Grapes"};    \n\n     for (int i = 0; i < list[0].Count; i++)\n    {\n        int number = dataGridView1.Rows.Add();\n        dataGridView1.Rows[number].Cells[0].Value = list[3][i]; //list[3][1]=="Apples"\n    }\n}	0
24954746	24954638	Adding EF object as a foreign key	var id = 2; // id of item \n\nusing (var context = new Context())\n      {\n            var item = context.YourTable.Single(m => m.Id== id);\n\n            item.ForeinKey = someNewForeinKey;\n\n            context.SubmitChanges();\n      }	0
19302208	19302143	How do I instantiate an object in VB.NET without storing to a variable?	Dim rslt As Integer = New Adder(1, 2).getSum()	0
3035779	3035739	how to put value in Label inside gridview during runtime?	List<double> productQty = //Filled with your quantity values\n        int i = 0;\n        foreach (GridViewRow row in grvProducts.Rows)\n        {\n            ((Label)row.FindControl("lblQuantity")).Text = productQty[i];\n            i++;\n        }	0
18261103	18261063	How to cast a Generic<T> to a Generic<R> where T is a subclass of R?	IGeneric<out T>	0
16188666	16188321	converting uri to string in c#	public static string FindRelativePath(string basePath, string targetPath)\n{\n           return Uri.UnescapeDataString(\n                basePath.MakeRelativeUri(targetPath)\n                    .ToString()\n                    .Replace('/', Path.DirectorySeparatorChar)\n                );\n}	0
9559137	9535779	OpenXML table copy gives OpenXmlUnknownElement	for (int i = 0; i < pages; ++i)\n{\n    doc.MainDocumentPart.Document.Body.InsertAfter(doc.MainDocumentPart.Document.Body.Elements<Table>().First().CloneNode(true), MDP.Document.Body.Elements<Table>().First());\n}	0
20847153	20846956	Fill data in SQL Server table	string stmt = "INSERT INTO dbo.Test(id, name) VALUES(@ID, @Name)";\n\nSqlCommand cmd = new SqlCommand(stmt, _connection);\ncmd.Parameters.Add("@ID", SqlDbType.Int);\ncmd.Parameters.Add("@Name", SqlDbType.VarChar, 100);\n\nfor (int i = 0; i < 10000; i++)\n{\n    cmd.Parameters["@ID"].Value = i;\n    cmd.Parameters["@Name"].Value = i.ToString();\n\n    cmd.ExecuteNonQuery();\n}	0
3581311	3581162	How can one get a ContextMenuStrip to show on left click of a NotifyIcon?	if (e.Button == MouseButtons.Left)\n{\n   MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", \n            BindingFlags.Instance |BindingFlags.NonPublic);\n    mi.Invoke(taskbarIcon, null);\n}	0
2611682	2611667	How to remove all ListBox items?	listBox1.Items.Clear();	0
20397022	20396183	how to split single data from string..?	dynamic stuff = JsonConvert.DeserializeObject(res);\n\nint id=stuff.id;	0
22655588	22655482	How to use Timer Elapsed event in Thread	private static Timer tmrDoviz = new Timer(3600000);\n tmrDoviz.Elapsed += new ElapsedEventHandler(OntmrDoviz_Elapsed);\n\n\n private static void OntmrDoviz_Elapsed(object source, ElapsedEventArgs e)\n {\n    Thread thDoviz = new Thread(SomeOtherFunctionToRunFromThread);\n    thDoviz .Start();\n }	0
29950315	29949092	Show content with button click without postback	public void lbSave1_Click(object sender, EventArgs e)\n{\n    customAlertDisplay.RemoveClass("hideTag");\n    upTaskInfo.Update();\n}\n\npublic static class CE\n{\n    public static void RemoveClass(this HtmlControl control, string cssClassName)\n    {\n        var val = control.Attributes["class"];\n        val = val.Replace(cssClassName, string.Empty);\n        control.Attributes["class"] = val;\n    }\n}	0
10971529	10919124	Telerik Radgrid's CRUD operations (Insert, Update,Delete) by MVP pattern	// view interface\npublic interface IGridView \n{\n    Telerik.Web.UI.RadGrid myGrid { get; }\n}\n\n// presenter\nprotected readonly IGridView _view;\n\npublic GridPresenter(IGridView view)\n{\n    _view = view;\n\n    _view.myGrid.UpdateCommand += new Telerik.Web.UI.GridCommandEventHandler(onUpdateCommand);\n    _view.myGrid.InsertCommand += new Telerik.Web.UI.GridCommandEventHandler(onInsertCommand);\n    _view.myGrid.EditCommand += new Telerik.Web.UI.GridCommandEventHandler(onEditCommand);\n}\n\nprivate void onUpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)\n{\n    // Code for updating \n}\n\nprivate void onInsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)\n{\n    // Code for inserting\n}\n\nprivate void onEditCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)\n{\n    // Code for editcommand\n}	0
20894382	20892191	SimpleInjector - trying to set up for construction injection (using parameters or multiple constructors)	container.Register<IDAL>(() => new DAL("db"));	0
6028323	6028178	how can manipulate the different kind of array (string, int, char) as same format such as string in C#?	IEnumerable array = queryObj["Capabilities"] as IEnumerable;\nif(array != null)\n{\n    foreach(var item in array)\n    {\n        Console.WriteLine(item.ToString());\n    }\n}\nelse\n{\n    Console.WriteLine(queryObj["Capabilities"].ToString());\n}	0
11568267	11568177	How to use parallel linq when two enumerables need to be combined	var formattedLine=messageList.AsParallel().AsOrdered().Select((message, index) =>\n{\n    ... // Some work here to be done in parallel\n    return string.Format(...); // Some formatting here of message using index\n});	0
6764827	6764403	Extracting variable number of token pairs from a string to a pair of arrays	class Program\n  {\n\n    static void Main()\n    {\n\n        string input = "<parameter1(value1)>< parameter2(value2)>";\n        string[] Items = input.Replace("<", "").Split('>');\n\n        List<string> parameters = new List<string>();\n        List<string> values = new List<string>();\n\n        foreach (var item in Items)\n        {\n            if (item != "")\n            {\n                KeyValuePair<string, string> kvp = GetInnerItem(item);\n                parameters.Add(kvp.Key);\n                values.Add(kvp.Value);\n            }\n        }\n\n        // if you really wanted your results in arrays\n        //\n        string[] parametersArray = parameters.ToArray();\n        string[] valuesArray = values.ToArray();\n\n    }\n\n\n    public static KeyValuePair<string, string> GetInnerItem(string item)\n    {\n        //expects parameter1(value1)\n        string[] s = item.Replace(")", "").Split('(');\n        return new KeyValuePair<string, string>(s[0].Trim(), s[1].Trim());\n    }\n}	0
27474006	27473973	C# with yahoo weather api	private void button1_Click(object sender, EventArgs e)\n    {\n        GetWeather();\n        textBox1.AppendText(Temperature);\n        textBox2.AppendText(Humidity);\n    }	0
7291810	7291693	C# prepending bytes to the beginning of a file?	int numberOfBytes = 100;\nbyte newByte = 0x1;\n\nusing ( var newFile = new FileStream( @"C:\newfile.dat", FileMode.CreateNew, FileAccess.Write ) )\n{\n    for ( var i = 0; i < numberOfBytes; i++ )\n    {\n        newFile.WriteByte( newByte );\n    }\n    using ( var oldFile = new FileStream( @"C:\oldfile.dat", FileMode.Open, FileAccess.Read ) )\n    {\n        oldFile.CopyTo(newFile);\n    }\n}\n\n// Rename and delete files, or whatever you want to do	0
19644265	19642318	Is this possible with regex?	\s+((H.{8})|(G.{9}))(?<user>.*)\r\n	0
15007862	14997896	Extending ApiExplorer using XML Documentation	private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)\n    {\n        HelpPageApiModel apiModel = new HelpPageApiModel();\n        apiModel.ApiDescription = apiDescription;\n\n        HttpActionDescriptor currentActionDescriptor = apiDescription.ActionDescriptor;\n\n        IEnumerable<HttpParameterDescriptor> currentActionParamDescriptors = ad.GetParameters();	0
3573423	3573302	Fields validation in winforms	private List<Control> m_lstControlsToValidate;\n    private void SetupControlsToValidate()\n    {\n        m_lstControlsToValidate = new List<Control>();\n\n        //Add data entry controls to be validated\n\n        m_lstControlsToValidate.Add(sometextbox);\n        m_lstControlsToValidate.Add(sometextbox2);\n\n    }\n   private void ValidateSomeTextBox()\n   {\n        //Call this method in validating event.\n        //Validate and set error using error provider\n   }\n\n   Private void Save()\n   {\n        foreach(Control thisControl in m_lstControlsToValidate)\n        {\n            if(!string.IsNullOrEmpty(ErrorProvider.GetError(thisControl)))\n            {                    \n                //Do not save, show messagebox.\n                return;\n            }\n        }\n     //Continue save\n   }	0
5383059	5383050	How can I calculate divide and modulo for integers	int a = 5;\nint b = 3;\n\nint div = a / b; //div is 1\nint mod = a % b; //mod is 2	0
836436	836427	How to Run a C# console application with the console hidden	System.Diagnostics.ProcessStartInfo start =\n      new System.Diagnostics.ProcessStartInfo();     \nstart.FileName = dir + @"\Myprocesstostart.exe";\nstart.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;	0
28242652	28242395	Can't find controls that don't have enough defined properties in Coded UI	var container = new HtmlControl(bw); //where bw is the browser window \nHtmlDiv parentDiv = new HtmlDiv(container);\nparentDiv.SearchProperties[HtmlDiv.PropertyNames.Id] = "theIdOfYourDiv";\n\nHtmlEdit edt = new HtmlEdit(parentDiv); //the search scope is narrowed down to the div only. This may be enough to find your control with the search property.\nedt.SearchProperties[HtmlEdit.PropertyNames.Type] = "SINGLELINE";	0
9099798	9029822	How can I bring google-like recrawling in my application(web or console)	Last-Modified	0
23466868	23465222	PhotoChooserTask how to pass extra parameter Windows Phone	public partial class MainPage : PhoneApplicationPage\n{\n    string tag;\n\n    // Constructor\n    public MainPage()\n    {\n        InitializeComponent();\n    }\n\n    private void photoChooserBtn_Click(object sender, RoutedEventArgs e)\n    {\n        photoChooserTask = new PhotoChooserTask();\n        tag = (sender as Button).Name;\n        photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);\n        photoChooserTask.Show();\n    }\n\n    private void photoChooserTask_Completed(object sender, PhotoResult e)\n    {\n        if (e.TaskResult == TaskResult.OK)\n        {\n            BitmapImage bmp = new BitmapImage();\n            bmp.SetSource(e.ChosenPhoto);\n            imagecontrol.Source = bmp;\n\n            switch(tag)\n            {\n                case tag1:\n                case tag2:\n                ........\n            }\n\n            tag = null;\n        }\n    }	0
1438295	1438198	How to inherit from the treenode class?	TreeNode[] parentNode = treeView1.Nodes.Find (parentid, true);\nforeach(TreeNode node in parentNode)\n{\n    ExtendedTreeNode ext_tree_node = node as ExtendedTreeNode;\n    if(ext_tree_node != null)\n    {\n        // Do your work\n    }\n}	0
19176290	19159230	Windows Phone: Display GeoCoordinate accuracy on a map	double myAccuracy = ...;\nGeoCoordinate myCoordinate = ...;\n\ndouble metersPerPixels = (Math.Cos(myCoordinate.Latitude * Math.PI / 180) * 2 * Math.PI * 6378137) / (256 * Math.Pow(2, myMap.ZoomLevel));\ndouble radius = myAccuracy / metersPerPixels;\n\nEllipse ellipse = new Ellipse();\nellipse.Width = radius * 2;\nellipse.Height = radius * 2;\nellipse.Fill = new SolidColorBrush(Color.FromArgb(75, 200, 0, 0));	0
31416512	31416107	Get view DataSource of GridControl in DevExpress	for(var i = 0; i < myGridView.DataRowCount; i++){\n    myGridView.GetRowCellValue(i, "columnName");\n}	0
331983	331976	How do I serialize a C# anonymous type to a JSON string?	JavaScriptSerializer serializer = new JavaScriptSerializer();\nvar output = serializer.Serialize(your_anon_object);	0
6852192	6850837	Reading local security policy	cmd /c secedit /export /cfg myfile.inf /areas USER_RIGHTS	0
30172519	30149184	Is there any way to add color to Model3D in WPF?	var importer = new HelixToolkit.Wpf.ModelImporter();\nvar point = importer.Load("hand.obj");\nGeometryModel3D model = point.Children[0] as GeometryModel3D;\n\nDiffuseMaterial material = new DiffuseMaterial(new SolidColorBrush(Colors.Black));\nmodel.Material = material;	0
4713530	4713444	shortest way to get first char from every word in a string	string str = "This is my style"; \nstr.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));	0
7009296	6997122	Extracting Specific Items from an XML File	double dTotalICostMM = 0.0, dTotalDCostMM = 0.0;\ndecimal dCost = Decimal.Zero, iCost = Decimal.Zero;\nusing (XmlReader reader = XmlReader.Create(strFileName))\n{\n    while (reader.Read())\n    {\n        if (reader.NodeType == XmlNodeType.Element && reader.Name == "episodeCost")\n        {\n            dCost = Convert.ToDecimal(reader.GetAttribute("dCost"));\n            iCost = Convert.ToDecimal(reader.GetAttribute("iCost"));\n        }\n    }\n\n    // Add each cost to its total for the month\n    dTotalDCostMM += (double)dCost;\n    dTotalICostMM += (double)iCost;\n}	0
12381770	12354134	oldvalues of SqlDatasource for dynamic gridview-templates	protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n    {\n        //GET THE OLD VALUES\n        myOldValues.Clear();\n        GridView gv = (GridView)sender;\n        gv.EditIndex = e.NewEditIndex;\n        gv.DataBind();\n\n        //populate \n        for (int i = 0; i < Gridview1.Columns.Count; i++)\n        {\n            DataControlFieldCell cell = gv.Rows[e.NewEditIndex].Cells[i] as DataControlFieldCell;\n            gv.Columns[i].ExtractValuesFromCell(myOldValues, cell, DataControlRowState.Edit, true);\n        }\n\n        Session["MyOldValues"] = myOldValues;\n\n    }	0
29019286	29018726	How to set basefont color?	cb2.SetColorFill(BaseColor.WHITE);	0
9618822	9618746	How to serialize a C# class into Javascript on Response?	[WebService(Namespace = "http://tempuri.org/")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n[ScriptService]\npublic class SimpleWebService : System.Web.Services.WebService \n{\n    [WebMethod]\n    public string GetServerTime() \n    {\n        string serverTime =\n            String.Format("The current time is {0}.", DateTime.Now);\n\n        return serverTime;\n    }\n}	0
13020605	13020574	How to convert Collection<object> to ArrayList< Dictionary<string, string> >?	lst = content.Cast<Dictionary<string, string>>().ToList();	0
5222867	5222828	Array of a generic class with unspecified type	ShaderParam[] params = new ShaderParam[5]; // Note no generics\nparams[0] = new ShaderParam<float>(); // If ShaderParam<T> extends ShaderParam	0
3772188	3772120	Howto call an unmanaged C++ function with a std::vector as parameter from C#?	void findNeigborsWrapper(\n  Point p,\n  double maxDist, \n  Point** ppNeighbors,\n  size_t* pNeighborsLength)	0
20506772	20481097	Issue with many-to-many relationship + TPH inhertitance in Entity Framework 6	public class DeviceType\n{\n    public long Id { get; set; }\n\n    public virtual ICollection<SoftwareFirmware> AvailableVerions { get; private set; }\n\n    public virtual IEnumerable<Firmware> AvailableFirmwareVerions\n    {\n        get\n        {\n            return this.AvailableVerions.OfType<Firmware>();\n        }\n    }\n\n    public virtual IEnumerable<Software> AvailableSoftwareVerions\n    {\n        get\n        {\n            return this.AvailableVerions.OfType<Software>();\n        }\n    }\n\n    public DeviceType()\n    {\n        AvailableVerions = new HashSet<SoftwareFirmware>();\n    }\n}	0
17057410	17057341	How to populate dropdown list from database?	protected void Page_Load(object sender, EventArgs e)\n{\n    SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));\n    con.Open();\n    SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);\n    SqlDataAdapter adp =new   SqlDataAdapter(mycommand);\n    DataSet ds =new DataSet();\n    adp.Fill(ds);\n    ddlTransactionCategory.DataSource = ds;\n    ddlTransactionCategory.DataTextField = "categoryCode";\n    ddlTransactionCategory.DataValueField = "OrgID";\n    ddlTransactionCategory.DataBind();\n\n\n    mycommand.Connection.Close();\n    mycommand.Connection.Dispose();\n}	0
5256193	5256158	to get all public methods in the project	MethodInfo[] methods = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).SelectMany(x => x.GetMethods().Where(y => y.IsPublic)).ToArray();	0
24626767	24626719	How To remove a specific tag from XElement	XElement  rootElement = .... // init your rootElement as you want \n\nrootElement.Elements("Person").Skip(1).Remove() ;	0
24651055	24650923	Mvc pick out 1 item from each category	foreach (var item in \n                list.GroupBy(catForHome => catForHome.Category)\n                    .Select(group => group.OrderBy(catForHome => catForHome.Name).First()))\n{\n    // got item with the lowest name in every category\n}	0
28262666	28262644	Console window exits when debugging	Console.Read()	0
14111473	14111442	Convert binary data to a pdf file	Conn.Open();\n    SqlCommand cmd = Conn.CreateCommand();\n    cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')";\n    byte[] binaryData = (byte[])cmd.ExecuteScalar();\n    File.WriteAllBytes(("algo.pdf", binaryData);\n    string s = Encoding.UTF8.GetString(binaryData);	0
20990861	20990348	How to execute external program from custom directory in Silverlight 5	public enum ShowCommands : int\n{\n    SW_HIDE = 0,\n    SW_SHOWNORMAL = 1,\n    SW_NORMAL = 1,\n    SW_SHOWMINIMIZED = 2,\n    SW_SHOWMAXIMIZED = 3,\n    SW_MAXIMIZE = 3,\n    SW_SHOWNOACTIVATE = 4,\n    SW_SHOW = 5,\n    SW_MINIMIZE = 6,\n    SW_SHOWMINNOACTIVE = 7,\n    SW_SHOWNA = 8,\n    SW_RESTORE = 9,\n    SW_SHOWDEFAULT = 10,\n    SW_FORCEMINIMIZE = 11,\n    SW_MAX = 11\n}\n\n[DllImport("shell32.dll")]\nstatic extern IntPtr ShellExecute(\n        IntPtr hwnd,\n        string lpOperation,\n        string lpFile,\n        string lpParameters,\n        string lpDirectory,\n        ShowCommands nShowCmd);\n\npublic static void ExecuteMyCode(string filePath)\n{\n    IntPtr retval = ShellExecute(System.IntPtr.Zero, string.Empty, filePath, string.Empty, string.Empty, ShowCommands.SW_NORMAL);\n}	0
12145351	12129905	How to find what message I just deserialized with protobuf-net?	if(msg.map != null) {\n    // ...\n}\n\nif(msg.block != null) {\n    // ...\n}\n\nif(msg.tile != null) {\n    // ...\n}	0
26357633	26357589	Get 3 maximum values in linq	var topDiscounts = (from p in db.Products\n                    orderby p.Discount descending\n                    select p).Take(3);	0
12820438	12820213	inserting a & into a label	myTable.myColumn =" Me & You";\n\nstring testString="";\nSQLConnection con = new SQLConnection(...)\nSQLCommand command=new SQLCommand("Select Top 1 * from myTable",con)\nSQLDataReader reader= command.ExecuteQuery()\nwhile (reader.read())\n{\n    testString=reader["myColumn"].ToString().Replace("&","&&");\n    MessageBox.Show(testString);\n}	0
9567105	9566651	Create COM-object on server in C#	public static object CreateObject(string progid, string server) {\n        var t = Type.GetTypeFromProgID(progid, server, true);\n        return Activator.CreateInstance(t);\n    }	0
5374704	5374404	EF4 Code First: how to update specific fields only	using (var _cnt = new STQContext())\n{\n   _cnt.Users.Attach(user);\n   _cnt.Entry<User>(user).Property(u => u.PasswordHash).IsModified = true;\n   _cnt.SaveChanges();\n}	0
22355270	22355012	Having problems with a datetime string	DateTime.Parse(dateTimeString, System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat)	0
5701064	5700992	Programmatically set Nhibernate to lower logging level for log4net	public static void SetLevel(string loggerName, string levelName)\n{\n    ILog log = LogManager.GetLogger(loggerName);\n    Logger l = (Logger)log.Logger;\n\n    l.Level = l.Hierarchy.LevelMap[levelName];\n}\n\n\nSetLevel("NHibernate","Error");	0
27067241	27066622	Debug a compiled program? c# wpf	System.Diagnostics.Debugger.Launch()	0
8691862	8680168	Building Validation Service Layer	IValidator<T>	0
8146549	8146523	How can I split the last instance of a character in a C# string?	string mystring = "/root/test/test2/tesstset-werew-1";\n\nvar mysplitstring = mystring.split("/");\n\nstring lastword = mysplitstring[mysplitstring.length - 1];	0
4586350	4586242	ISO latin 1 byte to char	private static readonly Encoding Iso88591 = Encoding.GetEncoding("ISO8859-1");\n\npublic static void Main() {\n    var bytes = new Byte[] { 65 };\n    var chars = Iso88591.GetChars(bytes);\n}	0
19607436	19607341	Read from single line where file contains multiple lines	var data = File\n    .ReadLines("itemdata.txt")\n    .Where(x => x.Contains("5624"))\n    .Take(1)\n    .SelectMany(x => x.Split('\t'))\n    .Select(x => x.Split('='))\n    .Where(x => x.Length > 1)\n    .ToDictionary(x => x[0].Trim(), x => x[1]);	0
24627034	24626954	XML without root in Linq Select	System.Xml.Linq.XDocument.Parse(\n     String.Format("<myRootNode>{0}</myRootNode>" , a.Text)\n    )	0
6322262	6322094	Efficent way to sample and convert arrays of binary data using C#	byte[] input = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; //sample data\nbyte[] buffer = new byte[4]; //4 byte buffer for conversion from 3-> 4 byte int\nint[] output = new int[input.Length / 3];\n\nfor (int i = 0, j = 0; i < input.Length; i += 3, j++)\n{\n    Buffer.BlockCopy(input, i, buffer, 0, 3);\n\n    int signed32 = BitConverter.ToInt32(buffer, 0);\n\n    output[j] = signed32;\n}	0
32510759	32510291	Set the 'onClick' to call a client method when dynamically adding control in Code Behind	protected void Page_Init(Object sender, EventArgs e) {\n        RadioButtonList radiobuttonlist = new RadioButtonList();\n\n        radiobuttonlist.SelectedIndexChanged += radiobuttonList_CheckedChanged;\n\n        //Set the AutoPostBack to true proptery to that the user action\n        // will immediately post-back to the server\n\n        radiobuttonlist.AutoPostBack = true;\n    }\n\n    private void radiobuttonList_CheckedChanged(object sender, EventArgs e) {\n        //Code you want to execut when a user selects a different item\n    }	0
25009964	24858243	datagridview on yesterday	private void button6_Click(object sender, EventArgs e)\n   {\n        try\n        {\n            da.SelectCommand = new SqlCommand("Select * from Jobs Where Jobs_Date = dateadd(day,datediff(day,1,GETDATE()),0) ", con);\n            //  da.SelectCommand = new SqlCommand("Select * from Jobs", con);\n            ds.Reset();\n            da.Fill(ds);\n        }\n        catch\n        {\n            MessageBox.Show("No SQL connection");\n        }\n        try\n        {\n            dataGridView1.DataSource = ds.Tables[0];\n            bs.DataSource = ds.Tables[0];                \n        }\n        catch (Exception i)\n        {\n            MessageBox.Show(i.Message, "Error");\n        }	0
23813160	23809868	Trying to port old encryption algorithm to C#	if(streamToEncrypt.Length.Dump("Length") % 8 != 0) {}	0
4226345	4226317	Generate a unique value for a combination of two numbers	ulong F(int x, int y) {\n    ulong id = x > y ? (uint)y | ((ulong)x << 32) :  \n                       (uint)x | ((ulong)y << 32);\n    return id;\n}	0
6022723	6022702	does DateTime keep itself updated in C#?	DateTime.Now	0
5305406	5305299	add data to sql database? Using odbc	string tbValue = textbox1.text("Name"); //added variable name\n\n  OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite; User=root; Password=;");\n  cn.Open();\n  OdbcCommand cmd = \n        new OdbcCommand("INSERT INTO User (Name) VALUES (?)"); // fixed incomplete insert statement.\n\n  cmd.Parameters.Add(tbValue); //add the parameter to the command\n  cmd.ExecuteNonQuery(); //actually run the sql	0
28932870	28932805	Replace every symbol of comments by whitespace	public static string ReplaceComments(string input)\n{\n    return Regex.Replace(input, @"(/\*[\w\W]*\*/)|//(.*?)\r?\n",\n        s => GenerateWhitespace(s.ToString()));\n}\n\npublic static string GenerateWhitespace(string input)\n{\n    var builder = new StringBuilder();\n    builder.Append(' ', input.Length);\n\n    return builder.ToString();\n}	0
31811531	31811494	Select records from one table, check if it exists in another table then insert into a 3rd table in C#	insert into C(id, Name)\nselect id, name from A\n      inner join B on A.id = B.id	0
33732706	33732471	Access tables from SqlProcedure written in an external C# DLL	using(SqlConnection c = new SqlConnection("context connection=true")) {\n    c.Open();\n    // do something with the connection\n}	0
25357292	25356616	C# xsd xmlreader, how to count attribute names	var xml = XDocument.Load(@"PathToXml");\nvar testCount = xml.Descendants().Attributes("Test1").Count();	0
4849271	4848854	add image into html table dynamically	HtmlTable tbProductImage = new HtmlTable();\nHtmlTableRow trImageRow = new HtmlTableRow();\nfor (int j = 0; j < columnCount; j++)\n{\n    if (filteredFileList.Count != 0)\n    {\n\n        HtmlTableCell tdImageCell = new HtmlTableCell();\n        Image imageProduct = new Image();\n        imageProduct.ID = "id";\n        imageProduct.ImageUrl = "url";\n        tdImageCell.Controls.Add(imageProduct);\n        trImageRow.Cells.Add(tdImageCell);\n    }\n}\ntbProductImage.Rows.Add(trImageRow);	0
9174534	9163086	How to get the session timeout value in a session provider when it's not set in the configuration?	Configuration conf = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);\nSessionStateSection section = (SessionStateSection) conf.GetSection("system.web/sessionState");\nint timeout = (int) section.Timeout.TotalMinutes;	0
33282049	33281932	The right way to add indexes for Entity Framework code-first applications?	modelBuilder \n    .Entity<Company>() \n    .Property(t => t.Name) \n    .HasColumnAnnotation( \n        "Index",  \n        new IndexAnnotation(new IndexAttribute("IX_Company_Name")\n        {\n            IsUnique = true \n        }));	0
1912885	1912880	Best practice for crash reporting in C# my application	StackTrace st = new StackTrace(true);\n        for(int i =0; i< st.FrameCount; i++ )\n        {\n            // Note that high up the call stack, there is only\n            // one stack frame.\n            StackFrame sf = st.GetFrame(i);\n            Console.WriteLine();\n            Console.WriteLine("High up the call stack, Method: {0}",\n                sf.GetMethod());\n\n            Console.WriteLine("High up the call stack, Line Number: {0}",\n                sf.GetFileLineNumber());\n        }	0
18308035	18307888	Changing size and position of a window belonging to another process	foreach window in EnumWindows()\n    if GetWindowModuleFileName(window) == "program.exe"\n        SetWindowPos(window, ...)	0
10268449	10268376	fileupload not found in a accordion	FileUpload fu = Accordion1.FindControl("FileUpload1") as FileUpload;	0
2374253	2374221	Loading Access DB Table to Datatable	string connString = \n    "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";\n\nDataTable results = new DataTable();\n\nusing(OleDbConnection conn = new OleDbConnection(connString))\n{\n    OleDbCommand cmd = new OleDbCommand("SELECT * FROM Clientes", conn);\n\n    conn.Open();\n\n    OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);\n\n    adapter.Fill(results);\n}	0
3720041	3719719	Fastest safe sorting algorithm implementation	public unsafe static void UnsafeQuickSort(int[] data)\n    {\n        fixed (int* pdata = data)\n        {\n            UnsafeQuickSortRecursive(pdata, 0, data.Length - 1);\n        }\n    }\n\n    private unsafe static void UnsafeQuickSortRecursive(int* data, int left, int right)\n    {\n        int i = left - 1;\n        int j = right;\n\n        while (true)\n        {\n            int d = data[left];\n            do i++; while (data[i] < d);\n            do j--; while (data[j] > d);\n\n            if (i < j)\n            {\n                int tmp = data[i];\n                data[i] = data[j];\n                data[j] = tmp;\n            }\n            else\n            {\n                if (left < j) UnsafeQuickSortRecursive(data, left, j);\n                if (++j < right) UnsafeQuickSortRecursive(data, j, right);\n                return;\n            }\n        }\n    }	0
3516548	3516477	What's the best way to get data from the app.config?	global::myProj.Properties.Settings.Default.sqlconnectionstring;	0
24759140	24758897	I need regular expression for HTML comment which contains any word	String result = Regex.Replace(content, @"<!-- saved[^>]*>", String.Empty);	0
24204154	24204062	How can i read from string[] each second line?	var brushes = new []{new SolidBrush(Color.Red), new SolidBrush(Color.Green)};\n\nfor (int i = 0; i < m_text.Lenght; i++)\n{\n    ... //other codes\n    e.Graphics.DrawString(test, drawFonts1, brushes [i % 2], pt);\n}	0
20576403	20388436	Enum.Parse method returns a different enum member than the one passed into it as the parameter	GroupBy(LanguageIndex)	0
3232012	3231916	c# - how do i make application run as a service?	[RunInstaller(true)]\npublic partial class PollingServiceInstaller : Installer\n{\n    public PollingServiceInstaller()\n    {\n        //Instantiate and configure a ServiceProcessInstaller\n        ServiceProcessInstaller PollingService = new ServiceProcessInstaller();\n        PollingService.Account = ServiceAccount.LocalSystem;\n\n        //Instantiate and configure a ServiceInstaller\n        ServiceInstaller PollingInstaller = new ServiceInstaller();\n        PollingInstaller.DisplayName = "SMMD Polling Service Beta";\n        PollingInstaller.ServiceName = "SMMD Polling Service Beta";\n        PollingInstaller.StartType = ServiceStartMode.Automatic;\n\n        //Add both the service process installer and the service installer to the\n        //Installers collection, which is inherited from the Installer base class.\n        Installers.Add(PollingInstaller);\n        Installers.Add(PollingService);\n    }\n}	0
19215116	19214987	How to Inherit from Generic Parent	class MyBase { public MyBase(object art) { } }\nclass Derived : MyBase {\n    public Derived() : base(null) { }\n }	0
14806945	14806910	How to convert enum to int	Convert.ToInt32	0
28973186	28972882	Entity Framework losing data after restarting from List	public class DowntimeEventModel\n{\n    [Key]\n    public int ID { get; set; }\n    [Required]\n    public DateTime StartDateTime { get; set; }\n    [Required]\n    public DateTime EndDateTime { get; set; }\n    public int LocationID { get; set; }\n    [Required]\n    public string Description { get; set; }\n    public virtual ICollection<SystemModel> AffectedSystems { get; set; }\n    public virtual ICollection<DepartmentModel> AffectedDepartments { get; set; }\n}	0
13417375	13417226	Logic for AddWorkingDays to Date	public static DateTime AddWorkingDays(this DateTime date, int days)\n    {\n        if (days == 0)\n            return date;\n        int sign = days < 0 ? -1 : 1;\n        while (days % 5 != 0 || !date.IsWorkingDay())\n        {\n            date = date.AddDays(sign);\n            if (!date.IsWorkingDay())\n                continue;\n            days -= sign;\n        }\n        int nWeekEnds = days / 5;\n        DateTime result = date.AddDays(days + nWeekEnds * 2);\n        return result;\n    }\n\n    public static bool IsWorkingDay(this DateTime date)\n    {\n        return !(date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday);\n    }	0
7255424	7255200	How do I find a Unicode character's bidirectional character type in C#?	System.Globalization.CharUnicodeInfo.GetBidiCategory(ch)	0
27750695	27741618	Entity Framework 6 Relationship	this.HasRequired (a => a.User)\n    .WithMany    ()\n    .Map         (m => m.MapKey ("UserID"));	0
9081229	9081186	How can I read a secure XML URI in C#?	WebRequest request = WebRequest.Create(url);\nrequest.Credentials = new NetworkCredential("usernamne", "password")\n\nusing (WebResponse response = request.GetResponse())\nusing (XmlReader reader = XmlReader.Create(response.GetResponseStream()))\n{\n    // Blah blah...\n}	0
13179293	13178968	Filtering xml file on attributes on similarly named elements using linq to xml	var employeesWithHomePhone = from e in xdocument.Root.Elements("Employee")\n                             where e.Elements("Phone").Any( p => (string)p.Attribute("Type") == "Home") \n                             select e;	0
33103229	33102669	c# how to properly write into a .dbf (foxpro)	string dataFolder = Path.Combine(Application.StartupPath, "Daten");\nString query = @"INSERT INTO TB_KUVG \n          (KDNR, Kuvg_id) \n          VALUES \n          (?,?)";\nusing (OleDbConnection dbfcon = new OleDbConnection("Provider=VFPOLEDB;Data Source=" + dataFolder))\n{\n  OleDbCommand cmd = new OleDbCommand(query, dbfcon);\n  cmd.Parameters.AddWithValue("@KDNR", 1);\n  cmd.Parameters.AddWithValue("@Kuvg_id", 1);\n\n  dbfcon.Open();\n  new OleDbCommand("set null off",dbfcon).ExecuteNonQuery();\n  cmd.ExecuteNonQuery();\n  dbfcon.Close();\n}	0
32973909	32973426	Load template on top of another	z-index	0
11872828	11872309	Building Lua Modules for LuaInterface	extern "C"	0
10833244	10833220	Writing an Action Invoker - How can I call a method on user choice?	operation = TakeDataFromGui;\n...\noperation();	0
9761824	9761805	Calc utf-8 string size in bytes?	string s = // your string\nint len = Encoding.UTF8.GetByteCount(s);	0
15274000	15273799	Most efficient way to rewrite a html page to a string (MVC 3)?	public static string RenderPartialToString(Controller controller, string viewName, object model)\n{\n\n    controller.ViewData.Model = model;\n\n    using (StringWriter sw = new StringWriter())\n    {\n        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);\n        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);\n        viewResult.View.Render(viewContext, sw);\n\n        return sw.GetStringBuilder().ToString();\n    }\n}	0
31940374	31940323	How to print a String	e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));\n try\n {\n     p.Print();\n }\n catch (Exception ex)\n {\n     throw new Exception("Exception Occured While Printing", ex);\n }	0
12680382	12680053	How to bind a List<string[]> to a gridview?	var query = from c in row\n            select new { SomeProperty = c };\n\nGridView.DataSource=query;\nGridView.DataBind();	0
27095818	27095749	Editing DataTable based on Query Result	.....\nstring[] words = message.Split(' ');\n\n// Execute the loop ONLY for the required words (the ones that starts with #)\nforeach (string word in words.Where(x => x.StartsWith("#")))\n{\n    // Search if the table contains a row with the current word in the Hashtag column\n    DataRow[] selection = hashtags.Select("Hashtag = '" + word + "'");\n    if(selection.Length > 0)\n    {\n        // We have a row with that term. Increment the counter\n        // Notice that selection is an array of DataRows (albeit with just one element)\n        // so we need to select the first row [0], second column [1] for the value to update\n        int count = Convert.ToInt32(selection[0][1]) + 1;\n        selection[0][1] = count;\n    }\n    else\n    {\n        row = hashtags.NewRow();\n        row["Hashtag"] = word;\n        row["Count"] = "1";\n        hashtags.Rows.Add(row);\n    }\n\n}	0
2817046	2816958	DateTime c# parsing	bool success = DateTime.TryParse("30-05-2010", out dt);\n\nConsole.Write(success); // false\n\n// use French rules...\nsuccess = DateTime.TryParse("30-05-2010", new CultureInfo("fr-FR"),\n              System.Globalization.DateTimeStyles.AssumeLocal, out dt);\n\nConsole.Write(success); // true	0
6997708	6997657	Assigning current time stamp to a variable	DateTime timetora = DateTime.Now;	0
2282040	2281900	Selective ordering with LINQ, partial ordering	items.OrderBy(x.Order => x.Order == -1).ThenBy(x.Order => x.Order);	0
8532847	8532212	Refer to an other columns value in a MVC3 Razor WebGrid	grid.Column("Summary", "Sum", format: (item) =>\n{\n    if (item.WeekNumber == ViewBag.CurrentWeekNo)\n    {\n        return "Dolor";\n    }\n    else\n    {\n        return "Sit";\n    }\n}	0
30214579	30213709	Linq to SQL - MDF DB in debug folder being altered on Insert, not the attached copy?	?In database explorer\n?Right click on the database\n?Select modify connection\n?Advanced options\n?Search for the property AttachDbFileName\n?Change it to the DB from debug folder c:...\bin\debug\DB.mdf\n?Once you point your database to the Debug directory, in VS Server Explorer, you can then delete the database in the solution explorer and all updates will transpire in the Debug database.	0
3332461	3332430	Use Enterprise library for OLEDB Access database	string query = "INSERT INTO DB (EmployeeID, Name) VALUES (@EmployeeID, @Name)"\n\nDatabase db = DatabaseFactory.CreateDatabase();\n\nDbCommand command = db.db.GetSqlStringCommand(query);\ndb.AddInParameter(command, "@EmployeeID", this.EmployeeID);\ndb.AddInParameter(command, "@Name", this.Name);\ndb.ExecuteNonQuery(command);	0
28450194	28449714	MongoDB Get names of all keys in collection using c#	string map = @"function() { \n        for (var key in this) { emit(key, null); }\n        }";\nstring reduce = @"function(key, stuff) { return null; }";\nstring finalize = @"function(key, value){\n            return key;\n        }";\nMapReduceArgs args = new MapReduceArgs();\nargs.FinalizeFunction = new BsonJavaScript(finalize);\nargs.MapFunction = new BsonJavaScript(map);\nargs.ReduceFunction = new BsonJavaScript(reduce);\nvar results = collection1.MapReduce(args);\nforeach (BsonValue result in results.GetResults().Select(item => item["_id"]))\n{\n    Console.WriteLine(result.AsString);\n}	0
18532559	18531158	Getting an exception writing a boolean to sql using a datatable and SqlBulkCopy	bulk.ColumnMappings.Add("Ex", "Ex");	0
25669583	25666222	How to disable resizing of rowheader?	myGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;	0
26423784	26423575	enable a disabled button by exiting off a form inside a form	private void button2_Click(object sender, EventArgs e)\n{\n        this.IsMdiContainer = true;\n        InchMm_Conversion f = new InchMm_Conversion();\n        f.MdiParent = this;\n//Here you set an event. When the form closes the here specified method is called \n        f.FormClosed += f_FormClosed; \n        f.Show();\n        button2.Enabled = false;\n}\n\n\nprivate void button3_Click(object sender, EventArgs e)\n{\n    this.LayoutMdi(MdiLayout.ArrangeIcons);\n}       \n\n//This method is executed when the form is closed\n    void f_FormClosed(object sender, FormClosedEventArgs e)\n    {\n           button2.Enabled = true;\n    }	0
5276744	5276475	Add items to Properties.Settings at runtime in an ASP.NET application	ConfigurationManager.GetSection()	0
16852862	16852829	How to make use of Try and Catch for setting values	private void validateInput(char x)\n{\n    if ( ( (int)x >= 65 && (int)x <= 90 ) || ( (int)x >= 97 && (int)x <= 122 )  )\n    {\n       storedChar = x;\n    }\n    else\n    {\n       throw new OutOfRangeException("Incorrect letter!");\n    }\n}	0
26609807	26609373	Entity Framework Virtual ICollection How to Query	public IQueryable<EventInstance> GetInstances(int scheduleID) \n{\n    // only returning instances that are 3 months back\n    DateTime dateRange = DateTime.Now.AddDays(-180);\n    return EventDBContext.EventInstances.Where(x => \n            x.CustomerID == MultiTenantID && \n            x.StartDateTime >= dateRange && \n            x.EventTimeInstances.Any(a => a.EventTimeID == scheudleID) ).OrderBy(x => x.StartDateTime).AsQueryable();\n}	0
4691779	4691721	How to find the exact date of the next 2:00 am in .net	DateTime dt = DateTime.Today.AddHours(2);\nif (dt < DateTime.Now)\n    dt = dt.AddDays(1);	0
11395261	11395069	How is it possible to use get_IsConnectedToInternet in C#	[DllImport("wininet.dll")]\n    private extern static bool InternetGetConnectedState( out int Description, int ReservedValue ) ;\n\n    public static bool IsConnectedToInternet( )\n    {\n        try\n        {\n            int Desc;\n            return InternetGetConnectedState(out Desc, 0);\n        }\n        catch \n        {\n            return false;\n        }\n    }	0
12999977	12998640	Options To Employ MDI in WPF	void Main_Loaded(object sender, RoutedEventArgs e)\n{\n    var mdiChild = new MdiChild\n    {\n        Title = "Window Using Code",\n        Content = new ExampleControl(),\n        Width = 500,\n        Height = 450,\n        Position = new Point(200, 30)\n    };\n    Container.Children.Add(mdiChild);\n    mdiChild.Loaded +=new RoutedEventHandler(mdiChild_Loaded);\n}\n\nvoid mdiChild_Loaded(object sender, RoutedEventArgs e)\n{\n    if (sender is MdiChild)\n    {\n        var mdiChild = (sender as MdiChild);\n        mdiChild.WindowState = WindowState.Maximized;\n    }\n}	0
30978053	30977493	Access manager information from Active Directory	var loginName = @"loginNameOfInterestedUser";\n        var ldap = new DirectoryEntry("LDAP://domain.something.com");\n        var search = new DirectorySearcher(ldap)\n        {\n            Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))"\n        };\n        var result = search.FindOne();\n        if (result == null)\n            return;\n        var fullQuery = result.Path;\n        var user = new DirectoryEntry(fullQuery);\n        DirectoryEntry manager;\n        if (user.Properties.PropertyNames.OfType<string>().Contains("manager"))\n        { \n            var managerPath = user.Properties["manager"].Value;\n            manager = new DirectoryEntry("LDAP://" + managerPath);\n        }	0
3806559	3806279	Creating a new Event with Objects	Browser.ProgressChanged += Browser_ProgressChanged;\n...\n\n        void Browser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e) {\n            if (e.MaximumProgress > 0) {\n                int prog = (int)(100 * e.CurrentProgress / e.MaximumProgress);\n                progressBar1.Value = prog;\n            }\n        }\n\n        private ProgressBar progressBar1;	0
9484893	9484638	SQL level paging without total rows	using(SqlConnection cnn = GetAConnection())\n{\n    string sql = @"WITH cols\n        AS\n        (\n        SELECT table_name, column_name, \n            ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, \n            ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows\n        FROM [INFORMATION_SCHEMA].columns\n        )\n        SELECT table_name, column_name, totrows + seq -1 as TotRows\n        FROM cols\n        WHERE seq BETWEEN @startRow AND @startRow + 49\n        ORDER BY seq";\n\n   SqlCommand cmd = new SqlCommand(sql,cnn);\n   cmd.Parameters.AddWithValue("@startRow",50);\n\n   cnn.Open();\n   using(SqlDataReader rdr = cmd.ExecuteReader())\n   {\n\n         //Do something with the reader here.\n   }\n\n}	0
26159982	19452757	How can I get a list of camera devices from my PC C#	DsDevice[] captureDevices;\n\n  // Get the set of directshow devices that are video inputs.\n  captureDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);    \n\n  for (int idx = 0; idx < captureDevices.Length; idx++)\n  {\n    // Do something with the device here...\n  }	0
11272449	11272417	How to get DayOfWeek in a local CultureInfo?	DateTime dt = DateTime.Now;\n// Sets the CurrentCulture property to U.S. English.\nThread.CurrentThread.CurrentCulture = new CultureInfo("en-US");\n// Displays dt, formatted using the ShortDatePattern\n// and the CurrentThread.CurrentCulture.\nConsole.WriteLine(dt.ToString("d"));	0
2418848	2418299	how to determine count of tag	XmlNodeList nodes = doc1.GetElementsByTagName("inv:Port");\n        int count = 0;\n        foreach (XmlNode childNode in nodes)\n        {\n            XmlNodeReader nodeReader = new XmlNodeReader(childNode);\n\n            while (nodeReader.Read())\n            {\n                if (nodeReader.GetAttribute("PartitionName") == "AIX")\n                {\n                    count++;\n                }               \n\n            }               \n        }       \n\n        Console.WriteLine("Count = {0}", count);\n        Console.ReadLine();	0
27131406	27116530	How to programmatically set App Pool Identity	myAppPool .Properties["AppPoolIdentityType"].Value = 3;\nmyAppPool .Properties["WAMUserName"].Value = Environment.MachineName + @"\" + username;\nmyAppPool .Properties["WAMUserPass"].Value = password;	0
33705129	33694294	SQL Performance Issue ASP.Net App	try\n        {\n            using (SqlConnection conn = new SqlConnection(connectionString))\n            {\n                using (SqlCommand cmd = new SqlCommand(sql, conn))\n                {\n                    conn.Open();\n                    cmd.CommandTimeout = int.Parse(commandTimeOut);\n                    SqlDataAdapter adapter = new SqlDataAdapter();\n                    adapter.SelectCommand = cmd;\n                    adapter.Fill(result);\n                    adapter.Dispose();\n                    conn.Close();\n                    pDate = result.Tables[0].Rows[0]["PDate"].ToString();\n                }\n            }\n        }\n        catch(Exception ex)\n        {\n            throw ex;\n        }\n        return pDate;	0
4750468	4750015	Regular expression to find URLs within a string	text = Regex.Replace(text,\n                @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)",\n                "<a target='_blank' href='$1'>$1</a>");	0
26895373	26895253	Constant in a key value pair	[HttpPost]\n    public void MyAction(string value)\n    {\n        Session["myKey"] = value;\n    }	0
1059236	1059226	C# Linq XML Find Specified element	public static bool HasNumber(XDocument doc, string number)\n{\n    return doc.Descendants("Number")\n              .Any(element => element.Value == number);\n}	0
12597593	12597536	How can I access city name from my list by zip?	string city = Address\n    .Where(a => a.Zip == 822)\n    .Select(a => a.City)\n    .FirstOrDefault();	0
21112685	20971814	How to specify the location of the signature in an xml document BEFORE computing the signature?	XmlDocument xpdoc = new XmlDocument { PreserveWhitespace = true };\n            xpdoc.Load(@fpath);\n\n            using (Stream stream = webRequest.GetRequestStream())\n            {\n                xpdoc.Save(stream); //writes the request body into the http web request stream \n            }	0
30429703	30429455	Entity Framework to json - grouping data	from b in db.Bases\nselect new BaseDTO\n{\n    BaseName = b.BaseName,\n    BaseStart = b.BaseStart,\n    BaseEnd = b.BaseEnd,\n    Clients = \n        from ba in b.BaseAssignments\n        from c in ba.Client\n        select new ClientDTO\n        {\n            ClientId = c.ClientId,\n            CompanyName = c.CompanyName,\n            Owner = c.Owner\n        }\n}	0
1945365	1945358	Is it possible to call the JIT debugger window from a c# program?	if( System.Diagnostics.Debugger.IsAttached )\n    System.Diagnostics.Debugger.Break ();\nelse\n    System.Diagnostics.Debugger.Launch ();	0
8094970	8094911	send a String array as parameter to a function	int counter = Function.SearchedRecords(file);	0
3820486	3820444	Having one method wait until a specific event has finished	Application.DoEvents()	0
20261038	20260809	Convert flat list to objects	var list = new []{\n    new { PersonId = 1, Name = "Is", Lastname = "Shin", VisitName = "a" },\n    new { PersonId = 1, Name = "Is", Lastname = "Shin", VisitName = "b" },\n};\n\n(\nfrom i in list\ngroup i by i.PersonId into g\nlet first = g.First()\nselect new {\n    Person = new { ID = first.PersonId, Name = first.Name, Lastname = first.Lastname },\n    Visits = g.Select(gi => new { VisitName = gi.VisitName } )\n}\n).Dump();	0
34286984	34286489	What Syntax Do I need to Use?	var input = " $dsf$ ddd $4rrr2$. $spoif$ $1d4dd$";\nvar regexp = new Regex(@"\$(.*?)\$");\nforeach (Match match in regexp.Matches(input))\n{\n     Console.WriteLine(match.Groups[1]);\n}	0
24301896	24299974	Use singleton with Dependency Injection (Castle Windsor)	container.Register(\nComponent\n.For<IOfflineUserService>()\n.ImplementedBy<OfflineUserService>()\n.LifestyleSingleton())	0
9221633	9172606	Getting 401 Youtube C# API with Google Secure AuthSub	YouTubeRequestSettings settings = new YouTubeRequestSettings("my app name", "Google.Client.ID", "Google.Youtube.DeveloperKey", (string)Session["YT_Token"]);\nYouTubeRequest ytRequest = new YouTubeRequest(settings);\nytRequest.Service.RequestFactory =\n                new GAuthSubRequestFactory("youtube", "my app name")\n                { PrivateKey = getRsaKey(), Token = (string)Session["YT_Token"] };\n...\nVideo newVideo = new Video();\n...\nFormUploadToken formToken = ytRequest.CreateFormUploadToken(newVideo);\nForm.Action = formToken.Url.Replace("http://", "https://") + "?nexturl=some page";	0
18801485	18801390	Need To transfer DataBase Data From datalist from Page To textbox in Another page	NavigateUrl='<%# "page2.aspx?id="+ Eval("AticleID") %>'	0
32293851	32290186	show only Date in auto generated grid view WPF C#	private void yourDatagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n{\n    if (e.PropertyType == typeof(DateTime))//if a column is typeof DateTime\n    {\n        (e.Column as DataGridTextColumn).Binding.StringFormat = "yyyy-MM-dd";//set your date format \n    }\n}	0
9401550	9381847	I can't update rows after I delete a invalid row from a DataGrid	protected override void RemoveItem(int index)\n    {\n        this[index] = new EngineStatusUserFilter();\n        base.RemoveItem(index);\n        Refresh();\n\n    }\n\n    public void Refresh() {\n        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); }	0
10213591	10213422	disposing of old dataset and refilling it with new entries with C#	//ds.Clear(); \n//ds = null; \nds.Dispose();  // not really needed but out of general principle\nds = stats.loadStats();  // gets a new instance	0
8102626	8102521	WinForms - How to call the Window Documents Context Menu	[DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, int lParam);\n\n    private void callSysMenu()\n    {\n        int point = ((this.Location.Y << 16) | ((this.Location.X) & 0xffff));\n        SendMessage(this.Handle, 0x313, IntPtr.Zero, point);\n    }	0
32793258	32787721	Lambda expression C# Union Where	Person[] p2 = p1\n            .Where(c => string.IsNullOrEmpty(c.Error))\n            .Select(\n                c => new Person { Name = c.Name, Age = c.Age }\n             )\n            .Union(\n            p1.Where(d => !string.IsNullOrEmpty(d.Error))\n            .Select(\n                d => new Person { Error = d.Error }\n             )\n             ).ToArray();	0
26639357	26637765	Comparing Enum Values within IronPython	if myObject.TotalGrade.value__ == Grade.Fail.value__:\n    pass  # your code here...	0
19621876	19620220	How to add link Labels at run time in Windows form	Label lbl = new Label();\nlbl.Text = "Hello World!";\nlbl.Location = new Point(100, 25);\nthis.Controls.Add(lbl);	0
2265165	2265128	Can I use the same content page with two different master pages?	private void Page_PreInit(object sender, EventArgs e)\n{\n    this.MasterPageFile = "MyMasterPage.master"\n}	0
14182810	13142701	Docking an Encapsulated Control	private DerivedTab CreateTab(string name)\n{\n    DerivedTab tab = new DerivedTab(this, name);\n    tab.SuspendLayout();\n\n    MainTab.Controls.Add(tab);\n    tab.ResumeLayout();\n    return tab;\n}	0
30682056	30681800	How to add records in many to many table using DbContext	using (var db = new MovieDbModel("Server=localhost;Database=test;Trusted_Connection=True;"))\n    {\n        var movie = new Movie()\n        {\n            Title = "Test",\n            Year = 1990\n        };\n\n        var actor = new Actor\n        {\n            FirstName = "Al",\n            LastName = "Pacino"\n        };\n\n        db.Actor.Add(actor);\n\n        actor.Movie.Add(movie);\n\n        db.SaveChanges();\n\n    }	0
2145577	2144629	Binding a model without controller/http.context	public static T Bind<T>(IDictionary<string, string> hash, T channel)\n{\n   foreach (var item in hash)\n   {\n        var prop = typeof(T).GetProperty(item.Key);\n        prop.SetValue(channel, Convert.ChangeType(item.Value, prop.PropertyType), new object[0]);\n   }\n}	0
2781184	2777082	Is this a good way to setup Moq to return a particular value only a certain number of times?	const int max = 5;\nvar callCount = 0;\n_dal.Setup(x => x.ShouldIKeepGoing())\n    .Returns(()=> ++callCount <= max )\n    .AtMost(max+1);	0
7231876	7197967	How do you open a local html file in a web browser when the path contains an url fragment	private static string GetDefaultBrowserPath()\n    {\n       string key = @"HTTP\shell\open\command";\n       using(RegistryKey registrykey = Registry.ClassesRoot.OpenSubKey(key, false))\n       {\n          return ((string)registrykey.GetValue(null, null)).Split('"')[1];\n       }\n    }\n\n    private static void Navigate(string url)\n    {\n       Process.Start(GetDefaultBrowserPath(), "file:///{0}".FormatWith(url));\n    }	0
18888379	18887966	How does this color matrix make image black and white?	0.3*R + 0.59*B + 0.11*G	0
8229570	8229322	How to deep copy a matrix in C#?	var myList = new List<List<CustomClass>>();\n\n//populate myList\n\nvar clonedList = new List<List<CustomClass>>();\n\n//here's the beef\nforeach(var sublist in myList)\n{\n   var newSubList = new List<CustomClass>();\n   clonedList.Add(newSubList);\n   foreach(var item in sublist)\n      newSublist.Add((CustomClass)(item.Clone()));\n}	0
27699001	27698922	Removing all non letter characters from a string in C#	public static string RemoveBadChars(string word)\n{\n    char[] chars = new char[word.Length];\n    int myindex=0;\n    for (int i = 0; i < word.Length; i++)\n    {\n        char c = word[i];\n\n        if ((int)c >= 65 && (int)c <= 90)\n        {\n            chars[myindex] = c;\n            myindex++;\n        }\n        else if ((int)c >= 97 && (int)c <= 122)\n        {\n            chars[myindex] = c;\n            myindex++;\n        }\n        else if ((int)c == 44)\n        {\n            chars[myindex] = c;\n            myindex++;\n        }\n    }\n\n    word = new string(chars);\n\n    return word;\n}	0
2274244	2274207	How to calculate the aspect ration from a floating point number	double ar = 1.7777773452;\nfor (int n = 1; n < 20; ++n) {\n    int m = (int)(ar * n + 0.5); // Mathematical rounding\n    if (fabs(ar - (double)m/n) < 0.01) { /* The ratio is m:n */ }\n}	0
3666555	3665823	Load Resources ".resx" from folder in Silverlight	Text={StaticResource L_MenuHome}	0
10503920	10503909	How can I launch a URL in the users default browser from my application?	Process.Start("http://www.google.com");	0
16213877	16213255	How to read cell values from existing excel file	xlRng = xlWorkSheet.get_Range("A1", "A20");\n\nObject arr = xlRng.Value;\n\nforeach (object s in (Array)arr)\n{\n    MessageBox.Show(s.ToString());\n}	0
5512958	5512882	c# return all specific elements from an xml	public IEnumerable<custInformation> getcustInfo(string file) {      \n    //Load the xml file\n    var xe = XDocument.Load(_server.MapPath(file)).Root;\n\n    //Get information\n    return (from p in xe.Descendants("cust-account").Descendants("cust-info")\n            select new custInformation\n            {\n                firstName = (string)p.Element("cust-fname"),\n                lastName = (string)p.Element("cust-lname"),\n                address = (string)p.Element("cust-address1"),\n            }).ToList();\n}	0
16551861	16551498	Is it possible to implement property setter explicitly while having a getter publicly available?	public class ModuleScreen : IModuleScreenData\n{\n    string IModuleScreenData.Name\n    {\n        set { Name = value; }\n    }\n\n    public string Name { get; private set; }\n}	0
21267701	21267526	Reset tap Counter WP8	private object previousSender;\nprivate void CheckSender(object sender)\n{\n    if (sender != previousSender)\n    {\n        TapCount = 0;\n    }\n\n    previousSender = sender;\n}	0
27722730	27720344	How to get only postal_code data from google api?	string _Postcode = (from x in gpr.results[0].address_components.AsQueryable()\n                                                where x.types.Contains("postal_code")\n                                                select x.long_name).FirstOrDefault();	0
966384	966323	How to programmatically modify WCF app.config endpoint address setting?	copy "$(ProjectDir)ServiceReferences.ClientConfig.$(ConfigurationName)" "$(ProjectDir)ServiceReferences.ClientConfig" /Y	0
2177457	2177373	Changing a border color on a Windows Form	protected override void OnPaintBackground(PaintEventArgs e) {\n  base.OnPaintBackground(e);\n  Rectangle rc = new Rectangle(dataGridView1.Left - 1, dataGridView1.Top - 1,\n    dataGridView1.Size.Width + 1, dataGridView1.Size.Height + 1);\n  e.Graphics.DrawRectangle(Pens.Fuchsia, rc);\n}	0
32605131	32605005	Add multiple pictureBox objects to a list using a loop	for (int i=0; i<=7; i++)\n    Pb.Add((PictureBox)Controls.Find("pictureBox" +i, true)[0]);	0
18164510	18164156	how can i use 1 contextmenustrip on many buttons	private void changeColorToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        Control ctl = contextMenuStrip1.SourceControl;\n        ctl.BackColor = Color.Red;\n    }	0
12726621	12726448	close a windows form after another form has been opened	static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        MainForm mf  = new MainForm();\n        if (mf.ShowDialog() == DialogResult.OK) \n        {  \n           subForm newSubForm = new subForm();   \n           newSubForm.RegisterMainForm(this);                        \n           Application.Run(newSubForm); \n        }\n    }	0
9834600	9834562	Use data from returning datatable?	DataTable dt = Scdal.LoadCategory(ScBo);\ndatagrid.Datacontext=dt.DefaultView;	0
4412322	4411809	How can i access the index of an XML Child using an XPathNavigator?	private string HOWDOIGETTHISNUMBER(XPathNavigator theNode)\n    {\n        XPathExpression query = theNode.Compile("count(preceding-sibling::"+theNode.LocalName+")+1");\n        return theNode.Evaluate(query).ToString();\n    }	0
11877456	11877434	How to force close button to terminate all childforms?	Application.Exit()	0
15977892	15977709	C# - Writing a string next to a line or delete a string	string[] lines = File.ReadAllLines("admin.txt");\nfor (int i = 0; i < lines.Length; i++)\n{\n        if (lines[i].StartsWith(string.Format("#{0}: ", Server.Name.ToLower()))\n        {\n            if (!lines[i].Split(';').Contains(Channel.Name.ToLower()))\n                lines[i] += ";" + Channel.Name.ToLower();\n        }\n    }\nFile.WriteAllLines("admin.txt", lines);	0
10086766	10086591	Create multiple versions of a project in Visual Studio using Build Configurations	#if DEVELOPMENT	0
6606354	6606307	How to map a hash key with a list of values in c#?	Dictionary<string, List<string>>	0
14790227	14790199	How can I group multiple controls together so that they are accessible by a method?	List< Control >	0
3504134	3500956	linqDataSource bound to dynamic list	protected void LinqDS_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n  e.Result = RetrieveUsers();\n}	0
11171956	11171864	Set all PDF Fields to ReadOnly	foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)\n{\n  formFields.SetFieldProperty(de.Key.ToString(), \n                             "setfflags", \n                              PdfFormField.FF_READ_ONLY, \n                              null);\n}	0
22353280	22331771	Debug C# source using windows debugger	"No CLR support in the latest debugger release"	0
3830979	3830941	How to catch a subscription to event?	private event EventHandler<EventArgs> shibby;\n\n    public event EventHandler<EventArgs> Shibby\n    {\n        add\n        {\n            // your logic here\n            this.shibby += value;\n            // or here\n        }\n        remove\n        {\n            // your logic here\n            this.shibby -= value;\n            // or here\n        }\n    }	0
21038587	21037848	Removing a row from table with two foreign keys entity framework	Role role = //Whatever Role;\ngroup.Roles.Remove(role);	0
8153495	8057072	send plain/text email and getting =0D=0A in email response from server	MailMessage emailmsg = new MailMessage("from@address.co.za", "to@address.co.za")\nemailmsg.Subject = "Subject";\nemailmsg.IsBodyHtml = false;\nemailmsg.ReplyToList.Add("from@address.co.za");\nemailmsg.BodyEncoding = System.Text.Encoding.UTF8;\nemailmsg.HeadersEncoding = System.Text.Encoding.UTF8;\nemailmsg.SubjectEncoding = System.Text.Encoding.UTF8;\nemailmsg.Body = null;\n\nvar plainView = AlternateView.CreateAlternateViewFromString(EmailBody, emailmsg.BodyEncoding, "text/plain");\nplainView.TransferEncoding = TransferEncoding.SevenBit;\nemailmsg.AlternateViews.Add(plainView);\n\nSmtpClient sSmtp = new SmtpClient();\nsSmtp.Send(emailmsg);	0
7740222	7740143	Refresh asp.net page from a code-behind file	System.Web.HttpContext.Current.Response	0
22201143	22200945	print the contents of a list <> in a textbox	for (int k = 0; k < Miarchivo[i].Count(); k++)\n{\n    textBox1.Text += leerArchivo[k] + Environment.NewLine;\n}	0
19806508	19805507	Using WaitHandle	readonly Semaphore _semaphore = new Semaphore(0, int.MaxValue);\n\npublic void Enqueue<T>(T item)\n{\n     _internalQueue.Enqueue(item);\n     _semaphore.Release();  // Informs that deque task to unblock if waiting. Equivalent to the  WaitHandle.Set() method. Increases the semaphore counter\n}\n\npublic T Dequeue()\n{\n     _semaphore.WaitOne();   // Blocks as long as there are no items in the queue. Decreases the semaphore counter when "let through". Blocks the thread as long as semaphore counter is zero.\n     return _internalQueue.Dequeue();\n}	0
33662047	33659796	C# Outlook Add-in optimization	string query = "@SQL=\"http://schemas.microsoft.com/mapi/string/{00020329-0000-0000-C000-000000000046}/MyPropName/0x0000001F\" = 'SomeValue' "\nOutlook.Items items = taskFolder.Items;\nOutlook.TaskItem ti = items.Find(query);\nwhile (ti != null)\n{\n   //do something \n   ti = items.FindNext();\n}	0
22716112	22711924	working with treeview list from ObjectListView control	private void tvView_SelectedIndexChanged(object sender, EventArgs e) {\n    // cast your TreeView to ObjectListView to access the selected Object\n    ObjectListView olv = sender as ObjectListView;\n\n    // get the selected child (you may want to check the type and if it really was a child that was selected here)\n    MyChildModelObject child = olv.SelectedObject as MyChildModelObject;\n    MyParentModelObject parent = _tvView.GetParent(child);\n\n    // ...\n}	0
13164301	13037231	Re-evaluating CanExecute on property change	private EventHandler currentHandler;\n\nprivate void UnhookCommand(ICommand command)\n{\n    if (currentHandler != null)\n        command.CanExecuteChanged -= currentHandler;\n    UpdateCanExecute();\n}\n\nprivate void HookCommand(ICommand command)\n{\n    if (currentHandler == null) return;\n\n    command.CanExecuteChanged += currentHandler;\n    UpdateCanExecute();\n}	0
5735789	5735686	How To Programmatically Set Text Displayed In UITableViewCell	yourcell.TextLabel.Text = "Hello World!";	0
7890397	7890322	Apply arbitrary number of OrderBy() in LINQ	// Slightly more generic, although it's still requiring projections to string...\npublic static IEnumerable<T> ApplyOrdering<T>(this IEnumerable<T> source,\n                                              params Func<T, string>[] sorts)\n{\n    // TODO: Argument validation\n    if (sorts.Length == 0)\n    {\n        return source;\n    }\n\n    IOrderedEnumerable<T> ordered = source.OrderBy(sorts[0]);\n    foreach (var ordering in sorts.Skip(1))\n    {\n        ordered = ordered.ThenBy(ordering);\n    }\n    return ordered;\n}	0
25978391	25978135	DateTime automatically return validation message in asp.net?	ModelState.IsValid	0
15590767	15590741	add user input in database	string sql1 = "insert into items values ( '" + this.name + "')";	0
15158763	15096169	How to get the text value from textbox within a FormView from ascx file in the ascx.cs file	string value = (myFrmView.FindControl("txtBox1") as TextBox).Text;	0
7304733	7304692	How to call javascript in for loop code behind?	for (int i = 0; i < 100; i++)\n        {\n            Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript" + i, "<script>alert('hello world');</script>");\n        }	0
22663049	22662902	how to check whether the entered table exists in database?	string tabExist = "IF EXIST ( SELECT * FROM sys.Tables WHERE TABLE_NAME =" + combCustomerName.Text +")";\n    SqlCommand tabExistCmd = new SqlCommand(tabExist, con);\n    tabExistCmd.ExecuteNonQuery();	0
3146336	3146325	Is there an elegant way to set a default value for a property in c#?	private int _speed = 100;\npublic int Speed { get { return _speed; } set { _speed = value; } }	0
4587611	4587513	How to calculate number of leap years between two years in C#	static int LeapYearsBetween(int start, int end)\n        {\n            System.Diagnostics.Debug.Assert(start < end);\n            return LeapYearsBefore(end) - LeapYearsBefore(start + 1);\n        }\n\n        static int LeapYearsBefore(int year)\n        {\n            System.Diagnostics.Debug.Assert(year > 0);\n            year--;\n            return (year / 4) - (year / 100) + (year / 400);\n        }	0
7788226	7788166	Redirect output of one exe to another exe : C#	ConsoleApp1.exe | ConsoleApp2.exe	0
21122926	21122590	ASP.net Change Password Validator	Page.Validate("signup");\n\nif (!Page.IsValid)\n{\n    return;\n}	0
6695275	6695204	How could one efficiently check for a 401 response from a URL in C#?	request.Method = "HEAD";	0
26460754	26460718	Retrieving data from database using Entity Framework	var vehicleList = (from v in context.Vehicles\n                         select new\n                         {\n                              Number = v.LicencePlateNumber,\n                              Make = v.Make,\n                              Model = v.Model,\n                              Year = v.PurchaseYear\n                         }).ToList();\n                    DG_Details.ItemsSource = vehicleList;\n                    DG_Details.Items.Refresh();	0
11566901	11566857	Grabbing a part of the List<Item> by start and end indices	List<Item> myList = new List<Item>;\nmyList.GetRange(50, 10); // Retrieves 10 items starting with index #50	0
5088641	5088399	Custom TaskScheduler to start task by DateTime	System.Threading.Task.TaskScheduler	0
14482630	14482236	Assembly not being located in GAC but gacutil shows it's there	%winddir%\Microsoft.NET\Assembly	0
17402560	17402364	Use XmlDocument to get XML data in Metro apps	XmlNodeList itemNodes = xmlDoc1.GetElementsByTagName("item");\n            if (itemNodes.Count > 0)\n            {\n               foreach (XmlElement node in itemNodes)\n               {\n                 ids3list.Add(node.Attributes["href"].Value);\n               }\n            }	0
25564806	25402819	How to release mouse captured by wpf control when clicking on winforms control	AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, \n                   new MouseButtonEventHandler((s, e) =>\n                       {\n                           Mouse.Capture(null);\n                           if (e.LeftButton == MouseButtonState.Pressed)\n                           {\n                               MouseInterop.LeftClick();\n                           }\n                        }));\n\n\npublic static class MouseInterop\n{\n    public static void LeftClick()\n    {\n        var x = (uint) Cursor.Position.X;\n        var y = (uint) Cursor.Position.Y;\n        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);\n    }\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]\n    private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);\n\n    private const int MOUSEEVENTF_LEFTDOWN = 0x02;\n}	0
15738926	15738638	Remove complete text on BackSpace button press of keyboard in WinForms	void txt_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (e.KeyChar == '\b')\n        {\n            TextEdit textBox1 = sender as TextEdit;\n            if (textBox1 != null)\n            {\n                textBox1.Text = "";\n            }\n\n        }\n    }	0
16705466	16705303	Writing a connection string to access a remote SQL Server database	Data Source=abcs.efgh.ed-1.eee.sss.com,1433;Initial Catalog=mydb;Integrated Security=False;User ID=a;Password=a	0
10515039	10514984	Downloading files with WP7	System.Uri targetUri = new System.Uri("http://www.dot.com/yourFile.zip");\n    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);\n    request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);	0
9513954	9513824	Parse text from textbox	const string oldPointer = "Old-Values: ";\nvar text = "New-Value = 12,34   -- Old-Values: 12,31,";\nvar old = text.Substring(text.IndexOf(oldPointer) + oldPointer.Length).TrimEnd(',');	0
12040653	12040403	What kind of timezone is TimeOfDay in TimeZoneInfo AdjustmentRule	System.TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time").GetAdjustmentRules().Dump();	0
16861133	16860123	SaveFileDialog removes extension from set filename	string filename = "test.xyz";\n\n        SaveFileDialog dialog = new SaveFileDialog();\n        dialog.Title = "SpeedDating App";\n        dialog.RestoreDirectory = true;\n        dialog.CheckFileExists = false;\n        dialog.CheckPathExists = false;\n        dialog.SupportMultiDottedExtensions = true;\n        dialog.Filter = "All files (*.*)|*.*";\n\n        dialog.DefaultExt = System.IO.Path.GetExtension(filename);\n        if (dialog.DefaultExt.Length > 0)\n        {\n            dialog.AddExtension = true;\n            dialog.Filter = dialog.DefaultExt + " files (*." + dialog.DefaultExt + ")|*." + dialog.DefaultExt + "|" + dialog.Filter;\n            dialog.FilterIndex = 0;\n        }\n\n        dialog.FileName = DateTime.Now.ToString("yyyyMMdd");\n\n        DialogResult result = dialog.ShowDialog();\n        if (result == DialogResult.OK && dialog.FileName != "")\n        {\n            Console.WriteLine(dialog.FileName);\n        }	0
2669721	2655061	C# Problem with getPixel & setting RTF text colour accordingly	richTextBox1.Append("x");\nrichTextBox1.Append("\n");	0
9257477	9214022	Programming Outlook Addin to automatically close and reload	COMAddIns comAddIns = application.COMAddIns;\n                COMAddIn addIn = null;\n\n                foreach (COMAddIn addin in comAddIns)\n                {\n                    string.Equals(addin.Description, "Your Addin Name", StringComparison.OrdinalIgnoreCase))\n                    {\n                        addIn = addin;                           \n                        break;\n                    }\n                }\n                if (addIn != null)\n                {\n                    Console.WriteLine("Reloading....");\n                    addIn.Connect = false;\n                    addIn.Connect = true;\n                    Console.WriteLine("Reloading complete!");\n                }	0
560131	560123	Convert from BitArray to Byte	byte ConvertToByte(BitArray bits)\n{\n    if (bits.Count != 8)\n    {\n        throw new ArgumentException("bits");\n    }\n    byte[] bytes = new byte[1];\n    bits.CopyTo(bytes, 0);\n    return bytes[0];\n}	0
14676210	14676081	I get a query string as return value from LINQ to SQL and WCF Services and no concrete value	var id = result.FirstOrDefault();\nstring returnValue = Convert.ToString(id);	0
4216952	4216874	Add to int array from dataset	List<int> promotionLst = new List<int>();\nforeach (DataRow dr in ds.Tables[0].Rows) {\n    if (dr["Status"].ToString() == "Active") {\n        promotionLst.Add(Convert.ToInt32(dr["Id"]));\n    }\n}\nint[] promotion = promotionLst.ToArray();	0
3510239	3503264	Create Selectlist with separator in Html Helper	var fullList = new StringBuilder();\n\nvar selectList = new TagBuilder("select");\nselectList.Attributes.Add("name", "currencies");\nselectList.Attributes.Add("id", "selectCurrency");\n\nforeach (var currency in currencies)\n{\n    var option = new TagBuilder("option") {InnerHtml = currency.Id};\n    option.Attributes.Add("value", currency.Id);\n    fullList.AppendLine(option.ToString());\n}\n\nvar separator = new TagBuilder("option") { InnerHtml = "-------" };\nseparator.Attributes.Add("disabled", "disabled");\nfullList.AppendLine(separator.ToString());\n\nselectList.InnerHtml = fullList.ToString();	0
8394901	8394859	Locking tables on read	INSERT \n  INTO TableName (RecordNumber) \nSELECT ISNULL(MAX(RecordNumber, 0) + 1 \n  FROM TableName WITH (UPDLOCK)	0
14018965	13736740	How can I combine my FTP queries?	// Partial class declaration\nclass FTPManager : IDisposable\n{\n    void Dispose();\n    FTPManager(string host, string username, string password)\n    void UploadFile(string remoteDir, string localfile);\n    void CreateDirectory(string remotePath);\n    void DeleteFile(string remotePath);\n}\n\n// and here I use it:\nvoid Main()\n{\n    using (var manager = new FTPManager("ftp.somehosting.org","login","password")) {\n        manager.CreateDirectory("/newfolder/");\n        manager.UploadFile("/newfolder/","C:\\Somefile.txt");\n        manager.DeleteFile("/newfolder/anotherfile.txt");\n    }\n}	0
8070550	7986560	Hiding a property of a WPF control from the Designer (Visual Studio 2010)	[Browsable(false)]\npublic new object Content\n{\n    get { return base.Content; }\n    set { base.Content = value; }\n}	0
14697308	14690870	Parsing text with random line breaks from a serial tool in C#	var reader = new StreamReader("Test.txt");\n        var contents = reader.ReadToEnd();\n        var strippedContents = contents.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");\n        var regex = new Regex(@"(?<packet>Packet \d+: )");\n        var matches = regex.Split(strippedContents);	0
27862571	27862400	Cant Install PCLStorage using nuget	portable-net45+wp8+wpa81+win8+monoandroid+monotouch+Xamarin.iOS+Xamarin.Mac	0
7923854	7921085	Find Which Silverlight Out of Browser App is Running Under sllauncher.exe	var processQuery = new SelectQuery("SELECT Commandline FROM Win32_Process");\nvar scope = new System.Management.ManagementScope(@"\\.\root\CIMV2");\nvar searcher = new ManagementObjectSearcher(scope, processQuery);\nManagementObjectCollection processes = searcher.Get();\nforeach (var process in processes)\n{\n     Console.WriteLine(process["Commandline"]);\n}	0
28932335	28888838	How to relate audio data to time	sampleCount * bytesPerSample * channels	0
12209495	12209423	How to insert image in word document header	Document doc = new Document();\n  doc.LoadFromFile(@"E:\JaneEyre.docx", FileFormat.Docx);\n HeaderFooter header = doc.Sections[0].HeadersFooters.Header;\n  header.Paragraphs[0].Text = "Preview";\n  Image logo = Image.FromFile(@"D:\E-ICEBLUE.png");\n  header.Paragraphs[0].AppendPicture(logo).TextWrappingStyle = TextWrappingStyle.Tight;\n  HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer;\n  doc.SaveToFile("Sample.docx", FileFormat.Docx);\n  System.Diagnostics.Process.Start("Sample.docx");footer.Paragraphs[0].Text = "Author: Charlotte Bront??";	0
6925405	6908983	WPF RichTextBox scroll to TextPointer	public void Foo(FlowDocumentScrollViewer viewer) {\n    TextPointer t = viewer.Selection.Start;\n    FrameworkContentElement e = t.Parent as FrameworkContentElement;\n    if (e != null)\n         e.BringIntoView();\n}	0
11159579	11159270	How do I bind template with style?	Background="{TemplateBinding Background}"	0
3187203	3186866	reload dll functions from anothe dll, C#	[DllImport("one.dll", EntryPoint = "_test_mdl")]\npublic static extern string _test_mdl1(string s);\n\n[DllImport("two.dll", EntryPoint = "_test_mdl")]\npublic static extern string _test_mdl2(string s);\n\npublic static string _test_mdl(string s)\n{\n    if (condition)\n        return _test_mdl1(s);\n    else\n        return _test_mdl2(s);\n}	0
13183019	13182421	Disable username validation on edit	public override bool IsValid(object value)\n{\n    var user = (User)value;\n    if (user == null) return true;\n\n    FinanceDataContext _db = new FinanceDataContext();\n    var u = _db.Users.Where(x => x.Username.ToLower() == user.Username.ToLower() && x.ID != user.ID).SingleOrDefault();\n    if (u == null) return true;\n    return false;\n}	0
6391588	6391501	How can I store and use an array of different types derived from a common base type?	class BasePanel\n{\n    public virtual void Draw(string blah)\n    {\n        Console.WriteLine("Base: " + blah);\n    }\n}\n\nclass UIButton : BasePanel\n{\n    public override void Draw(string blah)\n    {\n        Console.WriteLine("UIButton: " + blah);\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        List<BasePanel> list = new List<BasePanel>();\n\n        list.Add(new BasePanel());\n        list.Add(new UIButton());\n        list.Add(new BasePanel());\n        list.Add(new UIButton());\n        list.Add(new UIButton());\n\n        foreach (var b in list)\n        {\n            b.Draw("just a string");\n        }\n    }\n}	0
18408617	18408336	Xml attributes to string array	var doc = new XmlDocument();\ndoc.Load(fname);\n\nList<string> list = new List<string>();\nforeach(XmlNode node in doc.GetElementsByTagName("D"))\n{\n    list.Add(node.Attributes["cc"].Value);\n}	0
1457946	1457940	Multiple attachment file in email using C#	...\nmail.Body = txtComments.Text;\n//Attach file\nmail.Attachments.Add(new Attachment(txtAttachments.Text.ToString()));\nmail.Attachments.Add(new Attachment(txtAttachments2.Text.ToString()));\nmail.Attachments.Add(new Attachment(txtAttachments3.Text.ToString()));\nmail.Attachments.Add(new Attachment(txtAttachments4.Text.ToString()));\nSmtpServer.Port = 587;\n...	0
29187901	29185064	Fire an action as soon as an iframe appears using FirefoxDriver	ff.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5))\n\n//to start the job after 5 second , and skip waiting for all DOM document to be Ready !\n\n   Try\n            ff.Navigate().GoToUrl("http://exemple.com")\n\n45         Try\n           ff.SwitchTo().DefaultContent() // if ifrm1 is loaded and not iframe 2 , you should switch back to default !\n           ff.SwitchTo().Frame("ifrm1")\n           ff.SwitchTo().Frame("ifrm2")\n           Dim oo As IWebElement = ff.FindElement(By.TagName("a"))\n           oo.Click()\n           ff.Close()\n           Catch ex As Exception\n                GoTo 45\n            End Try\n        Catch ex As WebDriverTimeoutException\n//To Skip the wait of all document ...\n            GoTo 45\nEnd Try	0
9252602	9235928	get picture from media library using file name in windows phone	MediaLibrary.Pictures	0
23589745	23589703	Long in C# won't fit the same value as Long in Java	long.MaxValue = 9223372036854775807\nyour value 1  = 18374686479671623680\nyour value 2  = 9259542123273814144	0
28821603	28820209	C# XML Diffing algorithm	I need to check that user have only added new elements \nbut have not deleted or changed old ones.	0
8246369	8246238	Paging in Gridview with Linq	public static class PagingExtensions\n{\n    //used by LINQ to SQL\n    public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int pageSize)\n    {\n        return source.Skip((page - 1) * pageSize).Take(pageSize);\n    }\n\n    //used by LINQ\n    public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int page, int pageSize)\n    {\n        return source.Skip((page - 1) * pageSize).Take(pageSize);\n    }\n}	0
32355329	32355211	Convert decimal with comma and floating point	decimal t = 3.82822;\ndecimal.Round(t, 2);	0
1967455	1966951	Sqlite Subsonic C#: Guid is saving as Guid with SQL, but with strange characters when using code	public int LoginEnabledPropertyValue { get; set; }\n\n[SubSonicIgnore]\npublic bool LoginEnabled\n{\n     get\n     {\n          return (LoginEnabledPropertyValue > 0 ? true : false);\n     }\n     set\n     {\n          LoginEnabledPropertyValue = (value ? 1 : 0);\n     }\n }	0
4119833	4119280	Implement Search from database as alphabets are entered	table = new DataTable();\ntable.Columns.Add("Name");\ntable.Columns.Add("Type");\ntable.Columns.Add("Status");\ntable.Columns.Add("Date Created");\ntable.Columns.Add("Action");\n\nvar db = new DbDataContext();\nvar users = (from u in db.users\n             where u.Contains(textBoxSearch.Text)\n             select u).ToList();\nforeach(var user in users)\n{\n     MessageBox.Show(user.uName + user.uType + user.uStatus);\n            row = table.NewRow();\n            row["Name"] = user.uName;\n            row["Type"] = duser.uType;\n            row["Status"] = user.uStatus;\n            row["Date Created"] = user.uDate.ToShortDateString();\n            table.Rows.Add(row);\n}\n\nUsersView.DataSource = table;	0
319312	319304	C# - How to call an exe added into project solution	Process p = new Process();\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = "myExec.exe";\np.Start();	0
28416838	28416010	Display the correct Label in jquery AutoComplete with LINQ	var model = db.UserProfiles.Select(r => new\n            {\n                label = (u.FirstName + " " + u.LastName).Contains(term)  ? (u.FirstName + " " + u.LastName) :\n                                            u.Department.Contains(term)  ? u.Department :\n                                            u.JobTitle.Contains(term)    ? u.JobTitle :\n                                            u.PhoneNumber.Contains(term) ? u.PhoneNumber :\n                                            u.Extension.Contains(term)   ? u.Extension :\n                                            u.Location.Contains(term)    ? u.Location : null\n            }).Where(l => l != null).Distinct().Take(10);\n\n        return Json(model, JsonRequestBehavior.AllowGet);	0
857473	857435	Winform root directory path.How to again!	Path.Combine(Application.StartupPath, "Reports", "report.rpt")	0
13472131	13470446	Correct deserializing of hierarchical XML	[Serializable]\n[XmlRoot("Path")]\npublic class Brunch\n{\n    [XmlAttribute("Name")]\n    public string Name { get; set; }\n\n    [XmlElement(typeof(BinaryCortege), ElementName="Binary"),\n        XmlElement(typeof(TextCortege), ElementName = "Text"),\n        XmlElement(typeof(ExpandedTextCortege), ElementName = "ExpandText"),\n        XmlElement(typeof(MultylineTextCortege), ElementName = "MultylineText"),\n        XmlElement(typeof(IntCortege), ElementName = "DWord32"),\n        XmlElement(typeof(LongCortege), ElementName="DWord64")]\n    public List<Cortege> Corteges { get; set; }\n}	0
7271243	7271166	Increment number of passes	public void q_sort(int left, int right, int currentPass)\n{\n    /* ... */\n\n    Display(currentPass);\n\n    /* ... */\n\n    q_sort(left, pivot - 1, currentPass + 1);\n    q_sort(pivot + 1, right, currentPass + 1);\n\n    /* ... */\n}\n\npublic void Display(int currentPass)\n{\n    ResultText.AppendText("Pass " + currentPass);\n\n    // output the array contents as you currently do\n}	0
28681478	28680678	Create a list depending on the values of another list c#	public List<string> HeatGet(int heatNumbers, List<string> list)\n    {\n        List<string> heatStringList = new List<string>();\n        for (int i = 0; i < list.Count; i++)\n        {\n            heatStringList.Add("T" + Math.Ceiling((i + 1) *  (float)heatNumbers / list.Count));\n        }\n        return heatStringList;\n    }	0
4230118	4226852	Get oAuth 2.0 access token from asp.net webforms iframe canvas application	FacebookApp app = new FacebookApp();\nvar accessToken = app.Session.AccessToken;	0
34273936	34273646	Composing URL from single hierarchical table of pages with URL parts in SQL Server	DECLARE @t TABLE \n(   ID INT NOT NULL,\n    ParentID INT NULL,\n    Name VARCHAR(255) NOT NULL,\n    URLPart VARCHAR(255) NOT NULL\n);\n\nINSERT @T (ID, ParentID, Name, URLPart) \nVALUES \n    (1, NULL, 'Wildlife', 'Wildlife'), \n    (2, 1, 'Otters and beavers', 'otters-beavers'), \n    (3, 1, 'Canines', 'canines'), \n    (4, 3, 'dogs', 'dogs');\n\nWITH CTE AS\n(   SELECT  ID, ParentID, Name, URLPart, RecursionLevel = 1, FullURL = URLPart\n    FROM    @T\n    UNION ALL\n    SELECT  cte.ID, \n            t.ParentID, \n            cte.Name, \n            cte.URLPart, \n            cte.RecursionLevel + 1,\n            CAST(t.URLPart + '/' + cte.FullURL AS VARCHAR(255))\n    FROM    CTE\n            INNER JOIN @T AS t \n                ON t.ID = cte.ParentID\n)\nSELECT  ID, Name, URLPart, FullURL\nFROM    CTE\nWHERE   NOT EXISTS \n        (   SELECT 1 \n            FROM    CTE AS CTE2 \n            WHERE   CTE2.ID = CTE.ID \n            AND     CTE2.RecursionLevel > CTE.RecursionLevel\n        )\nORDER BY ID;	0
1881076	1881050	Creating a Huge Dummy File in a Matter of Seconds in C#	FileStream fs = new FileStream(@"c:\tmp\huge_dummy_file", FileMode.CreateNew);\nfs.Seek(2048L * 1024 * 1024, SeekOrigin.Begin);\nfs.WriteByte(0);\nfs.Close();	0
2676525	2676471	Get a string representation of a property in C# at run-time	string columnName = GetPropertyName(() => myNewData[0].fieldName);\n\n// ...\n\npublic static string GetPropertyName<T>(Expression<Func<T>> expr)\n{\n    // error checking etc removed for brevity\n\n    MemberExpression body = (MemberExpression)expr.Body;\n    return body.Member.Name;\n}	0
14935659	14934274	Un-/Marshalling nested structures containing arrays of structures	[StructLayout(LayoutKind.Sequential, Pack = 1)]\n    public struct NestedStruct\n    {\n        public Int16 someInt;\n        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 242)]\n        public Byte[] characterArray; // an array of fixed length 242\n    }\n\n     [StructLayout(LayoutKind.Sequential, Pack = 1)]\n     public struct OtherNestedStruct\n     {\n         public Int16 someInt;\n         public Int16 someOtherInt;\n\n     }\n\n\n     [StructLayout(LayoutKind.Sequential, Pack = 1)]\n     public struct MainStruct\n     {\n         public double someDouble;\n         public NestedStruct nestedContent;\n         [MarshalAs(UnmanagedType.ByValArray, SizeConst = 13 * 4)]\n         public OtherNestedStruct[] arrayOfStruct; // fixed array length 13\n\n    }  \n\n    static void Main(string[] args)\n    {\n        var x = Marshal.SizeOf(typeof(MainStruct));\n        //x == 460\n    }	0
30992085	30988895	How to map between two entities before paging	public ActionResult Index(int? page)\n{\n    List<ProviderViewModel> viewModel = new List<ProviderViewModel>();\n    List<Provider> businessModel = db.Providers\n                                     .OrderBy(t => t.Name);\n\n    int pageSize = 9;\n    int pageNumber = (page > 0 ? page : 1);\n    int totalCount = businessModel.Count();\n\n    foreach (Provider provider in businessModel.Skip(pageSize * (pageNumber - 1))\n                                               .Take(pageSize))\n    {\n       viewModel.Add(new ProviderViewModel(provider));\n    }\n\n    return View(new StaticPagedList(viewModel, pageNumber, pageSize, totalCount));\n}	0
31004957	31004922	Passing a condition into Func<bool> of a Tuple<string, string, Func<bool>>	var properties = new List<Tuple<string, string, Func<bool>>> \n{\n    Tuple.Create<string, string, Func<bool>>(\n                 FirstName, \n                 "User first name is required",\n                 () => FirstName == null),\n};	0
7856739	7850790	Moving from LINQ2SQL to LINQ to Entities	public override int SaveChanges()\n    {\n        var modified = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Modified);\n        // set whatever values you want on modified entities\n        return base.SaveChanges();\n    }	0
9635270	9632484	Migradoc Picture on a picture on a pcture	myImage.RelativeVertical = RelativeVertical.Page;\nmyImage.RelativeHorizontal = RelativeHorizontal.Page;	0
27959715	27959243	C# How to parse XML File	var result = xdcoc.Descendants("PID")\n          .Select(x => new\n          {\n              OffetX = (string)x.Attribute("OffsetX"),\n              OffsetY = (string)x.Attribute("OffsetY"),\n              ObjectName = x.Parent.Descendants("Object")\n                           .Where(z => z.Attribute("OID").Value == \n                                                      x.Attribute("TRef").Value)\n                            .Select(z => (string)z.Attribute("ObjectName"))\n                            .FirstOrDefault()\n           });	0
27698035	19341591	The application called an interface that was marshalled for a different thread - Windows Store App	Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,\n() =>\n    {\n        // Your UI update code goes here!\n    }\n);	0
15225342	15225212	Regex length validation: Ignore leading and trailing whitespaces	body.ValidationExpression = string.Format("^((\S)|((\s+|\n+|(\r\n)+)+\S)|(\S(\s+|\n+|(\r\n)+))+){{{0},{1}}}$",\n    MinimumBodyLength,\n    MaximumBodyLength);	0
16010866	16000537	how to print something that is not shown on the screen	private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)\n{\n    //Create bitmap\n    Bitmap image = new Bitmap(dataGridView1.Width, dataGridView1.Height);\n    //Create form\n    Form f = new Form();\n    //add datagridview to the form\n    f.Controls.Add(dataGridView1);\n    //set the size of the form to the size of the datagridview\n    f.Size = dataGridView1.Size;\n    //draw the datagridview to the bitmap\n    dataGridView1.DrawToBitmap(image, new Rectangle(0, 0, dataGridView1.Width, dataGridView1.Height));\n    //dispose the form\n    f.Dispose();\n    //print\n    e.Graphics.DrawImage(image, 0, 0);\n}	0
8312531	4772273	InterpolationMode HighQualityBicubic introducing artefacts on edge of resized images	using (ImageAttributes wrapMode = new ImageAttributes())\n{\n    wrapMode.SetWrapMode(WrapMode.TileFlipXY);\n    g.DrawImage(input, rect, 0, 0, input.Width, input.Height, GraphicsUnit.Pixel, wrapMode);\n}	0
8149257	8149235	Write to log every X time	public partial class Form1 : Form\n{\n    Timer timer = null;\n\n    public Form1()\n    {\n        InitializeComponent();\n\n        timer = new Timer();\n        timer.Interval = 3 * 60 * 60 * 1000;\n        timer.Tick += new EventHandler(timer_Tick);\n        timer.Enabled = true;\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n        // Do what you need\n        File.AppendAllText(log_file, your_message);\n\n    }\n\n    private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n    {\n        timer.Stop();\n        timer.Tick -= timer_Tick;\n    }\n}	0
25561832	25536088	Custom Value Types in Entity Framework	modelBuilder.Types<ClassAttachmentTypeIsUsedIn>()\n.Configure(ctc => ctc.Property(cust => cust.AttachmentType.EnumProperty)\n.HasColumnName("AttachmentType"));	0
10929897	10929608	How to get 14 days prior to the given date avoiding holidays	public static DateTime AddBusinessDays(DateTime date, int days)\n {\n    if (days == 0) return date;\n\n   if (date.DayOfWeek == DayOfWeek.Saturday)\n   {\n    date = date.AddDays(2);\n    days -= 1;\n  }\n  else if (date.DayOfWeek == DayOfWeek.Sunday)\n  {\n    date = date.AddDays(1);\n    days -= 1;\n  } \n\n\n\n date = date.AddDays(days / 5 * 7);\n int extraDays = days % 5;\n\n if ((int)date.DayOfWeek + extraDays > 5)\n {\n    extraDays += 2;\n }\n\nint extraDaysForHolidays =-1;\n//Load holidays from DB into list\nList<DateTime> dates = GetHolidays();\n\nwhile(extraDaysForHolidays !=0)\n{\n\n var days =  dates.Where(x => x >= date  && x <= date.AddDays(extraDays)).Count;\n extraDaysForHolidays =days;\n extraDays+=days;  \n}\n\n\nreturn date.AddDays(extraDays);	0
11789663	11689474	How to create a file in sharepoint using asp.net	String fileToUpload = @"C:\YourFile.txt";\n        String sharePointSite = "http://yoursite.com/sites/Research/";\n        String documentLibraryName = "Shared Documents";\n\n        using (SPSite oSite = new SPSite(sharePointSite))\n        {\n            using (SPWeb oWeb = oSite.OpenWeb())\n            {\n                if (!System.IO.File.Exists(fileToUpload))\n                    throw new FileNotFoundException("File not found.", fileToUpload);                    \n\n                SPFolder myLibrary = oWeb.Folders[documentLibraryName];\n\n                // Prepare to upload\n                Boolean replaceExistingFiles = true;\n                String fileName = System.IO.Path.GetFileName(fileToUpload);\n                FileStream fileStream = File.OpenRead(fileToUpload);\n\n                // Upload document\n                SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);\n\n                // Commit \n                myLibrary.Update();\n            }\n        }	0
416632	416524	How to determine whether an IP is from the same LAN programatically in .NET C#	NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();\n\n        foreach (NetworkInterface iface in interfaces)\n        {\n            IPInterfaceProperties properties = iface.GetIPProperties();\n\n            foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)\n            {\n                Console.WriteLine(\n                    "{0} (Mask: {1})",\n                    address.Address,\n                    address.IPv4Mask\n                    );\n            }\n        }	0
1709395	1709373	Get File Bytes from Resource file in C#	public static byte[] ReadResource(string resourceName)\n{\n    using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))\n    {\n        byte[] buffer = new byte[1024];\n        using (MemoryStream ms = new MemoryStream())\n        {\n            while (true)\n            {\n                int read = s.Read(buffer, 0, buffer.Length);\n                if (read <= 0)\n                    return ms.ToArray();\n                ms.Write(buffer, 0, read);\n            }\n        }\n    }\n}	0
4628303	4628080	How can I create an antlr tree of a given shape?	rule:\nID (COMMA ID)*  -> ^(ITEM ID)+\n;	0
20364513	20364480	How do I count how many double letters are in a string?	if (characters[i] == characters[i + 1])\n    {\n        doubleLetters++;\n        i++;\n    }	0
12423820	12408134	do a PostBack and add the items server-side for dynamically created checkboxlist item	private void AddingDynamicCheckBoxList(string listitem_name, string listitem_value)\n{ chkBxLst1.Items.Add(new ListItem(listitem_name, listitem_value)); }	0
14490874	14490757	Writing a C# synch app using USB	public void SendDataOverSerial(string data) {\n  try {\n     SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); \n     port.Open(); \n     port.Write(data); \n  }\n  finally {\n     port.Close();    \n  }\n}	0
989079	989062	Determining with C# Whether a SQL Backup File is Password Protected	IF (1==1)\n{\n//It's not password protected\n}	0
10016073	10015632	How to make 'not contains' regular expression	string line = <YourLine>\nvar result = new StringBuilder();\nvar inQuotes = false;\n\nforeach(char c in line)\n{\n    switch (c)\n    {\n        case '"':\n            result.Append()\n            inQuotes = !inQuotes;\n            break;\n\n        case ',':\n            if (!inQuotes)\n            {\n                yield return result.ToString();\n                result.Clear();\n            }\n\n        default:\n            result.Append()\n            break;                \n    }\n}	0
1454110	1453958	Databinding to a custom class in C#	public partial class Form1 : Form\n    {\n        Person person;\n        public Form1()\n        {\n            InitializeComponent();\n\n            person = new Person();\n            this.titleTextBox.DataBindings.Add("Text", person, "DisplayName");\n            this.firstNameTextBox.DataBindings.Add("Text", person.MainDetail, "FirstName");\n        }\n    }\n\n    public class Person\n    {\n        public Int32 ID { get; set; }\n        public Boolean IsMarried { get; set; }\n        public String DisplayName { get; set; }\n        public Detail MainDetail { get; set; }\n        public Detail PartnerDetail  { get; set; }\n\n        public Person()\n        {\n            MainDetail = new Detail();\n            PartnerDetail = new Detail();\n        }\n    }\n\n    public class Detail\n    {\n        public String FirstName { get; set; }\n        public String LastName { get; set; }\n        public DateTime DateOfBirth { get; set; }\n        public String Address { get; set; }\n    }	0
22417402	22417222	Multiple Type Variable C#	class Foo\n{\n  public dynamic Value { get; set; }\n}\n\nclass FooHandler\n{\n  public void Serialize(Foo foo)\n  {\n    SerializeField(foo.Value);\n  }\n\n  void SerializeField(int field)\n  {\n    Console.WriteLine("handle int");\n  }\n\n  void SerializeField<T>(T field)\n  {\n    throw new NotImplementedException("Serialization not implemented for type: " + typeof(T));\n  }\n}\n\nclass Program\n{\n  [STAThread]\n  static void Main(string[] args)\n  {\n    Foo f = new Foo();\n    f.Value = 1;\n\n    FooHandler handler = new FooHandler();\n    handler.Serialize(f);\n\n    Console.ReadKey();\n  }\n}	0
8730513	8011038	Outlook 2010 and href to open folders/messages	MAPIFolder.FolderPath	0
22629167	22628912	Session timeout different just for one variable	public class ExpiringSessionValue<T>\n{\n    private T _value;\n    private DateTime _created = DateTime.Now;\n\n    public ExpiringSessionValue(T value)\n    {\n        _value = value;\n    }\n\n    public T Value\n    {\n        get\n        {\n            if (_created >= DateTime.Now.AddMinutes(-10))\n                return _value;\n            else\n                return default(T);\n        }\n    }\n}	0
23468310	23462367	Encrypt data by using a public key in c# and decrypt data by using a private key in php	OpenSSL.Crypto.RSA.Padding.PKCS1	0
21707407	21698794	Extracting embedded XML File from PDF A/3 using abcpdf in C# - ZUGFeRD	PDF-Implementierungsguide-ZUGFeRD.pdf	0
28391625	28391092	i want to retrieve image in this way but it wont	Byte[] image=(Byte[])(reader["Can_Pic"]); \n\n    if (image.Length == 0)\n    {\n        Picture.Image = null;\n    }\n    else\n    {\n        MemoryStream stream = new MemoryStream();\n        stream.Write(image, 0, image.Length);\n        Picture.Image = new Bitmap(stream);\n    }	0
33587472	33587356	How big is the performance loss when printing a progress information via carriage return in C#?	Stopwatch stopWatch = new Stopwatch();\nstopWatch.Start();\n\ndouble i = 0;\ndouble size = zip.Count\nforeach(ZipEntry element in zip)\n{\n    if(i % 500 == 0)\n    {\n        Console.Write("\rInstalling "+ name +"... "+ (i/size)*100 +"%");\n        Console.Out.Flush();\n    }\n    element.Extract(destinationPath, ExtractExistingFileAction.OverwriteSilently);\n    i++;\n}\n\nstopWatch.Stop();\n\nMessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,...	0
17093029	12510299	Get DateTime as UTC with Dapper	class Foo\n{\n    private DateTime _modificationDate;\n    public DateTime ModificationDate\n    {\n        get { return _modificationDate; }\n        set { _modificationDate = DateTime.SpecifyKind(value, DateTimeKind.Utc); }\n    }\n    //Ifs optional? since it's always going to be a UTC date, and any DB call will return unspecified anyways\n}	0
11987611	11987230	how do I copy a folder to a USB? C#	private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)\n{\n    DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n    DirectoryInfo[] dirs = dir.GetDirectories();\n\n    if (!dir.Exists)\n    {\n        throw new DirectoryNotFoundException(\n            "Source directory does not exist or could not be found: "\n            + sourceDirName);\n    }\n\n    if (!Directory.Exists(destDirName))\n    {\n        Directory.CreateDirectory(destDirName);\n    }\n\n    FileInfo[] files = dir.GetFiles();\n    foreach (FileInfo file in files)\n    {\n        string temppath = Path.Combine(destDirName, file.Name);\n        file.CopyTo(temppath, false);\n    }\n\n    if (copySubDirs)\n    {\n        foreach (DirectoryInfo subdir in dirs)\n        {\n            string temppath = Path.Combine(destDirName, subdir.Name);\n            DirectoryCopy(subdir.FullName, temppath, copySubDirs);\n        }\n    }\n}	0
12546261	12545718	How to avoid duplicate items being added from one CheckBoxList to another CheckBoxList	for (int i = 0; i <= CheckBoxList2.Items.Count - 1; i++)\n        {\n            if (CheckBoxList2.Items[i].Selected)\n            {\n                CheckBoxList4.Items.Add(CheckBoxList2.Items[i].ToString().Trim());\n\n            }\n        }\n\nforeach (ListItem item in CheckBoxList4.Items)\n        {\n            if (!CheckBoxList3.Items.Contains(item))\n            {\n                CheckBoxList3.Items.Add(item);\n            }\n        }	0
28972370	28972047	Extra Digits being appended to a Double	private decimal CalculateOrderOfMagnitude(int n)\n{\n    if (n < 0)\n        return CalculateOrderOfMagnitude(n + 1) / 10m;\n    if (n > 0)\n        return CalculateOrderOfMagnitude(n - 1) * 10m;\n\n    return 1m;\n}	0
18794521	18794462	Parsing html in win8 store app using linq and Html Agility Pack	HtmlAgilityPack.HtmlDocument doc= new HtmlAgilityPack.HtmlDocument(); htmlDoc.LoadHtml(stringWithHtml);        \n  var names = doc.DocumentNode.Descendants().Where(n => n.Name == "td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "sivo");\n\n    var links = doc.DocumentNode.Descendants().Where(n => n.Name == "td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "sivo").Select(x => x.Descendants().Where(s => s.Name == "a"));\n    foreach (var item in names)\n    {\n        var blabla = item.InnerText;\n    }\n    foreach (var item in links)\n    {\n        var lnks = item.Select(x => x.Attributes["href"].Value);//links\n        var times = item.Select(x => x.InnerText);  //times\n    }	0
11020692	11019574	Every possible combination of X split into N stacks	class Program\n{\n    static void Main(string[] args)\n    {\n        var v = Partitions(5, 3, 5);\n\n        for (int i = 0; i < v.Count; i++)\n        {\n            for (int x = 0; x < v[i].Count; x++)\n                Console.Write(v[i][x] + " "); \n            Console.WriteLine();\n        }\n    }\n\n    static private List<List<int>> Partitions(int total, int stacks, int max)\n    {\n        List<List<int>> partitions = new List<List<int>>();\n\n        if (total <= 1 || stacks == 1)\n        {\n            if (total <= max)\n            {\n                partitions.Add(new List<int>());\n                partitions[0].Add(total);\n            }\n\n            return partitions;\n        }\n        for (int y = Math.Min(total, max); y >= 1; y--)\n        {\n            var w = Partitions(total - y, stacks - 1, y);\n            for (int i = 0; i < w.Count; i++)\n            {\n                w[i].Add(y);\n                partitions.Add(w[i]);\n            }\n        }\n\n        return partitions;\n    }\n}	0
10684915	10629499	Muting refresh sound in webbrowser control c# winform	const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;\n\nconst int SET_FEATURE_ON_PROCESS = 0x00000002;\n\n[DllImport("urlmon.dll")]\n[PreserveSig]\n[return: MarshalAs(UnmanagedType.Error)]\nstatic extern int CoInternetSetFeatureEnabled(\n    int FeatureEntry,\n    [MarshalAs(UnmanagedType.U4)] int dwFlags,\n    bool fEnable);\n\nstatic void DisableClickSounds()\n{\n    CoInternetSetFeatureEnabled(\n        FEATURE_DISABLE_NAVIGATION_SOUNDS,\n        SET_FEATURE_ON_PROCESS,\n        true);\n}	0
8269515	8235452	Save open application dimensions and positions on Windows to reopen them via configuration file?	[DllImport("User32.dll")]\n    public static extern IntPtr FindWindow(string className, string windowName);\n\n    [DllImport("User32.dll")]\n    [return: MarshalAs(UnmanagedType.Bool)]\n    public static extern bool SetWindowPos(IntPtr windowHandle, IntPtr parentWindowHandle, int x, int y, int width, int height, PositionFlags positionFlags);\n\n    public static readonly IntPtr HWND_TOP = new IntPtr(0);\n\n    [Flags]\n    public enum PositionFlags : uint\n    {\n        ShowWindow = 0x40\n    }\n\n    static void Main(string[] args)\n    {\n        var windowHandle = FindWindow(null, "Untitled - Notepad");\n        SetWindowPos(windowHandle, HWND_TOP, 0, 0, 640, 480, PositionFlags.ShowWindow);\n    }	0
30358601	30358088	How to set the background of a column for specific row to different color	protected void RowDataBound(Object sender, GridViewRowEventArgs e)\n{\n//Check if it is not header or footer row\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n        if(e.Row.RowIndex == 0)\n             e.Row.Cells[0].BackColor = Color.Red;\n        if(e.Row.RowIndex == 1)\n e.Row.Cells[0].BackColor = Color.Green;\n    }\n}	0
17850360	17843407	to get coordinates for tap or click on windows 8 app	private void tempCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)\n    {\n        PointerPoint pt = e.GetCurrentPoint(tempCanvas);\n\n        TextBlock textblock = new TextBlock();\n        textblock.Text = "hello i am here";\n        textblock.Height = 200;\n        textblock.Width = 300;\n        Canvas.SetLeft(textblock, pt.Position.X);\n        Canvas.SetTop(textblock, pt.Position.Y);\n        textblock.Foreground = new SolidColorBrush(Colors.Red);\n        tempCanvas.Children.Add(textblock);\n    }	0
7148616	7132193	WCF web service client with Castle windsor	Component.For<IMyWCFServiceProxy>()\n                .ActAs(DefaultClientModel\n                           .On(WcfEndpoint.FromConfiguration("wsHttpEndpoint"))).\n                ImplementedBy<MyWCFServiceProxy>());	0
24651487	24651347	How to save a newly created pdf file using SaveFileDialog	SaveFileDialog svg = new SaveFileDialog();\nsvg.ShowDialog();\n\nusing (FileStream stream = new FileStream( svg.FileName+ ".pdf", FileMode.Create))\n{\n    Document pdfDoc = new Document(PageSize.A1, 10f, 10f, 10f, 0f);\n    PdfWriter.GetInstance(pdfDoc, stream);\n    pdfDoc.Open();\n    pdfDoc.Add(pdfTable);\n    pdfDoc.Close();\n    stream.Close();\n}	0
12171978	12171806	How to join two entities in Entity Framework?	BioStarEntities BS = new BioStarEntities();\n        var tuserS = BS.TB_USERS.ToList();	0
7914213	7914105	Using LINQ MIN() function with a JOIN	var minOrders = from customer in DataSet.Customers\n                let order = (from o in DataSet.Orders\n                             where o.CustomerId == customer.CustomerId\n                             order by o.OrderTimestamp\n                             select o).first()\n                select new\n                 {\n                    customer.Name,\n                    order.OrderAmount\n                 });	0
18796825	18796617	how to save XML URL content into text file using C#	XmlDocument document = new XmlDocument();\ndocument.Load("http://www.w3schools.com/php/links.xml");\n\nFile.WriteAllText("c:\\links.xml", document.InnerXml);	0
12277370	12260586	Passing parameter programmatically and displaying in crystal reports	crystalReportViewer1.RefreshReport();	0
938491	925719	Change type of ViewData in extended controller	public new AbcViewData ViewData { \n    get { return base.ViewData as [bcViewData; }\n    set { base.ViewData = value; }\n}	0
25410902	25410565	WPF - Controltemplate child to access usercontrol's custom dependancy properties	Source="{Binding ButtonImageSource,\n                 RelativeSource={RelativeSource Mode=TemplatedParent}}"	0
8914522	8914477	Determining file extension given a FileStream	string extension = Path.GetExtension(myFileStream.Name);	0
7801085	7799367	publish a event on FB wall	if (!response || response.error) {\n                    alert(name + ' Success');\n                } else {\n                    alert(name + ' Fail');\n                }	0
31985065	31984922	mysql select command in C# with dynamic column names	cmdDataBase.CommandText = "select " + shown_itemsName + " from employee.transaction where department = @department AND MONTH(date) = @month_ AND YEAR(date) = @year_";\n\ncmdDataBase.Parameters.AddWithValue("@department", this.department.Text);\ncmdDataBase.Parameters.AddWithValue("@month_", this.dateTimePicker1.Value.Month);\ncmdDataBase.Parameters.AddWithValue("@year_", this.dateTimePicker1.Value.Year);\n\nusing(var reader = cmdDataBase.ExecuteReader()) {\n    while(reader.Read()) {\n        // ...\n    }\n    reader.Close();\n}	0
32856841	32856693	Need to use IEnumerable.except to compare two dimensional dice roll	Class DiceRoles : IEquatable<T>\n{\n     public int Role1 { get ; set ; }\n     public int Role2 { get ; set ; }\n\n     public bool Equals(Product other)\n     {\n         //your code to compare for equity here\n     }\n\n     public override int GetHashCode()\n     {\n         //your code here\n     }\n}	0
3686041	3685980	Simplifying Regex's - escaping	bool isInputValid = inputString.All(c => allowedChars.Contains(c));	0
8347842	8347608	Lambda least occuring element	var teachers = taughtSubjects\n   .GroupBy(ts => ts.SubjectId)\n   .OrderBy(g => g.Count())\n   .ThenBy(g=>g.Key) //tiebreaker\n   .First() //gets the IEnumerable of Teachers that teach this least-taught subject\n   .GroupBy(t=>t.FormId)\n   .OrderBy(g=>g.Count())\n   .ThenBy(g=>g.Key) //as a tiebreaker\n   .First() //gets the teacher(s) with the lowest specified FormId.	0
5181427	5181356	Call C++ programs from C# /WPF	Process myProcess = new Process();\n\ntry\n{\n    myProcess.StartInfo.UseShellExecute = false;\n    // You can start any process; HelloWorld is a do-nothing example.\n    myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";\n    myProcess.StartInfo.CreateNoWindow = true;\n    myProcess.Start();\n    // This code assumes the process you are starting will terminate itself. \n    // Given that is is started without a window so you cannot terminate it \n    // on the desktop, it must terminate itself or you can do it programmatically\n    // from this application using the Kill method.\n}\ncatch (Exception e)\n{\n    Console.WriteLine(e.Message);\n}	0
15685548	15685458	How do I set my label's text with a value from the database?	label1.Text = dr["Klantnummes"].ToString();	0
26857655	26857336	Read and update xml file with multi level	XmlNodeList nodes= doc.SelectNodes("Board/Datas/Data/Parameters/Parameter");\n\n        foreach(XmlNode n in nodes)\n        {\n            string s = n.Attributes["Value"].Value.ToString();\n        }	0
31392699	31391954	Changing subitem background color c#	for (int i = 0; i < Variables.NSeqSNP; i++)\n{\n    char res = Variables.SequencesSNP[i].ToString()[pos];\n    ListViewItem lvi = new ListViewItem(Variables.SeqNameSNP[i].ToString());\n    lvi.SubItems.Add(res + " ");\n    lvi.UseItemStyleForSubItems = false;\n    if (res == 'A') lvi.SubItems[1].BackColor = Color.Blue;\n    else if (res == 'T') lvi.SubItems[1].BackColor = Color.Red;\n    else if (res == 'C') lvi.SubItems[1].BackColor = Color.Green;\n    else if (res == 'G') lvi.SubItems[1].BackColor = Color.Yellow;\n\n    lstOutputSNP.Items.Add(lvi);\n}	0
1517996	1517848	Counting common bits in a sequence of unsigned longs	values.Length	0
2446824	2446772	How to validate field length	myTextBox.MaxLength = 50	0
23366267	23365996	FluentAssertions: match each object of a collection	collection.Should().OnlyContain(predicate)	0
246750	246710	How to implement a singleton in C#?	public static class GlobalSomething\n{\n   public static int NumberOfSomething { get; set; }\n\n   public static string MangleString( string someValue )\n   {\n   }\n}	0
9361153	9361112	C# open multiple images to array	images = openFileDialog1.FileNames.Select(fn=>new Bitmap(fn)).ToArray();	0
17489629	17489447	How To Pass Lists of data from C# to MySQL Stored Procedures	using (MySqlConnection c = new MySqlConnection("cstring"))\n{\n    c.Open();\n    var t = c.BeginTransaction();\n\n    try\n    {\n        foreach (var o in list)\n        {\n            using (MySqlCommand cmd = new MySqlCommand("EXECUTE sp @field1, @field2", c, t))\n            {\n                cmd.Parameters.AddWithValue("@field1", o.field1);\n                cmd.Parameters.AddWithValue("@field2", o.field2);\n\n                cmd.ExecuteNonQuery();\n            }\n        }\n\n        t.Commit();\n    }\n    catch (Exception ex)\n    {\n        t.Rollback();\n        // do something with ex\n    }\n}	0
8393856	8393758	Not a pagination, a small navigation between the results	public void NavigateNext(Post current)\n{\n  var post = (from p in db.Posts\n             where p.CreateDate > current.CreateDate\n             order by p.CreateDate).Take(1).FirstOrDefault();\n\n //do something\n\n}\n\npublic void NavigateBack(Post current)\n{\n  var post = (from p in db.Posts\n             where p.CreateDate < current.CreateDate\n             order by p.CreateDate desc).Take(1).FirstOrDefault();\n\n //do something\n\n}	0
1683221	1683205	How do I Programmatically change Connection String un LINQ C# Winforms	var db = new MyDataContext(myconnectionstring);	0
16084701	16082330	Communicating with Windows7 Display API	[DllImport("User32.dll")]\npublic static extern int SetDisplayConfig(\n    uint numPathArrayElements, \n    [In] DisplayConfigPathInfo[] pathArray,\n    uint numModeInfoArrayElements, \n    [In] DisplayConfigModeInfo[] modeInfoArray,\n    SdcFlags flags\n);\n\n[DllImport("User32.dll")]\npublic static extern int QueryDisplayConfig(\n    QueryDisplayFlags flags, \n    ref int numPathArrayElements,\n    [Out] DisplayConfigPathInfo[] pathInfoArray, \n    ref int modeInfoArrayElements,\n    [Out] DisplayConfigModeInfo[] modeInfoArray,\n    IntPtr z\n);	0
899216	899198	WPF Hyperlink Child	ContentPresenter presenter = (ContentPresenter)sender.TemplatedParent;\nDataTemplate template = presenter.ContentTemplate;\nTextBlock textBlock = (TextBlock)template.FindName("data1", presenter);	0
26138818	26138499	label priting via button	int dayOfWeek;\nif (!int.TryParse(textBox1.Text, out dayOfWeek))\n{\n  // you can remove the MessageBox if you're not interested in feedback \n  MessageBox.Show("Value entered is not a valid day number!");\n  return;\n}\n\nString dayName = null;\nswitch (dayOfWeek)\n{\n  case 1:\n    dayName = "Sunday";\n    break;\n  case 2:\n    dayName = "Monday";\n    break;\n  case 3:\n    dayName = "Tuesday";\n    break;\n  case 4:\n    dayName = "Wednesday";\n    break;\n  case 5:\n    dayName = "Thursday";\n    break;\n  case 6:\n    dayName = "Friday";\n    break;\n  case 7:\n    dayName = "Saturday";\n    break;\n  default:\n    dayName = "Mad Day!!!";\n    break;\n  }\n  // Set the label's text to what was defined above\n  label1.Text = dayName;\n}	0
15127481	15126700	Consume WSDL that requires action level authorization in C#	using (var scope = new OperationContextScope(ltClient.InnerChannel))\n{\n    var reqProperty = new HttpRequestMessageProperty();\n    reqProperty.Headers[HttpRequestHeader.Authorization] = "Basic " \n             + Convert.ToBase64String(Encoding.ASCII.GetBytes(\n               ltClient.ClientCredentials.UserName.UserName + ":" + \n               ltClient.ClientCredentials.UserName.Password));\n\n    OperationContext.Current\n        .OutgoingMessageProperties[HttpRequestMessageProperty.Name] = reqProperty;\n\n    var ltResponse = ltClient.searchEmailAddressStatusWS(ltRequest);\n}	0
29703197	29696488	Get the seasons within a range of dates	// get start and end as DateTime\n\nint year;\nDateTime springStart, summerStart, autumnStart, winterStart;\n\nfor (DateTime date = start; date < end; date = date.AddMonths(3))\n{ \n    year = date.Year;\n    springStart = new DateTime(year, 3, 21);\n    //etc...\n    if (date >= springStart && date < summerStart)\n    { //etc...}\n    else if (date >= winterStart || date < springStart)\n    { //etc...}\n}	0
31148775	31146552	Open file location without using process.Start	Process.Start("C:\\");\nProcess.Start("C:\\books");\nProcess.Start("C:\\Common7");	0
7799575	7795657	Get snapshot from streaming video (newbie)	using (Bitmap bmpFrame = new Bitmap(_video.CurrentFrame.Bitmap)\n{\n\n   lock (bmpFrame)\n   {\n       TagForm f = new TagForm(bmpFrame);\n       f.Show();\n   }\n\n}	0
32820062	32819752	how to change color of equal signs in richtextbox c#	Add event to your richtext box for  text changed:\n\nprivate void richTextBox1_TextChanged(object sender, EventArgs e)\n    {\n        this.ChangeColor("=", Color.Purple);\n\n    }\n\n\n\nprivate void ChangeColor(string word, Color color)\n{\n    if (this.richTextBox1.Text.Contains(word))\n    {\n        int index = -1;\n        int selectStart = this.richTextBox1.SelectionStart;\n\n        while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1)\n        {\n            this.richTextBox1.Select((index), word.Length);\n            this.richTextBox1.SelectionColor = color;\n            this.richTextBox1.Select(selectStart, 0);\n            this.richTextBox1.SelectionColor = Color.Black;\n        }\n    }\n}	0
15665228	15665121	ASP.NET MVC render view from string to generete report	Html.Raw()	0
16671713	16552276	What Are Some Options To Convert Url-Encoded Form Data to JSON in .Net	// Example query string from the question\nString test="Property1=A&Property2=B&Property3%5B0%5D%5BSubProperty1%5D=a&Property3%5B0%5D%5BSubProperty2%5D=b&Property3%5B1%5D%5BSubProperty1%5D=c&Property3%5B1%5D%5BSubProperty2%5D=d";\n// Convert the query string to a JSON-friendly dictionary\nvar o=QueryStringHelper.QueryStringToDict(test);\n// Convert the dictionary to a JSON string using the JSON.NET\n// library <http://json.codeplex.com/>\nvar json=JsonConvert.SerializeObject(o);\n// Output the JSON string to the console\nConsole.WriteLine(json);	0
2803530	2803488	Is it bad practise to initialise fields outside of an explicit constructor	string _string;\n\n    public ConstructorExample2()\n    {\n        _string = "John";\n    }	0
5984459	5984232	linq where clause with 2 datetime conditions	a) use >= and <= \n b) remove the .Date	0
34121494	34121354	Group the GROUP BY results	WITH Balances\nAS (\n    SELECT \n        (coalesce(sum(Ledger.Debit), 0) - coalesce(sum(Ledger.Credit), 0)) + Accounts.PreviousBalance  [Balance] \n    FROM \n        Accounts\n    LEFT join \n        Ledger on Accounts.ID = Ledger.AccountId\n    Where \n        Accounts.Status = 'Active'\n    GROUP BY \n        Accounts.ID, Accounts.PreviousBalance\n),\nReceipts AS (\n    SELECT SUM(Balance) Balance\n    FROM Balances\n    WHERE Balance > 0\n),\nPayments AS (\n    SELECT SUM(Balance) Balance\n    FROM Balances\n    WHERE Balance < 0\n)    \nSELECT Balance FROM Receipts \nUNION \nSELECT Balance FROM Payments	0
14387632	14387568	Razor Foreach model list	public class MenuItems\n{\n    public static List<Menu> Items;\n\n    static MenuItems()\n    {\n       Items = new List<Menu>();\n\n       Items.Add(new Menu\n       {\n           Alt = "test item",\n           ItemName = "item 1",\n       });\n       Items.Add(new Menu\n       {\n            Alt = "test item",\n            ItemName = "item 2",\n        });\n     }\n}	0
10997541	10997446	Finding X & Y positions	MouseState mouseState = Mouse.GetState();\n\n        var x = mouseState.X;\n        var y = mouseState.Y;	0
8328581	8317080	How to determine field type from a field in a PDF document using iTextSharp?	FormObject fo = new FormObject();\nList<FormField> form_fields = new List<FormField>();\n\nPdfReader reader = new PdfReader(file_name);\nAcroFields reader_fields = reader.AcroFields;\n\n\n\nforeach (KeyValuePair<String, iTextSharp.text.pdf.AcroFields.Item> entry in reader_fields.Fields)\n{\n    FormField ff = new FormField();\n    ff.Field_name = entry.Key.ToString();\n    int field_type = reader_fields.GetFieldType(entry.Key.ToString());\n    form_fields.Add(ff);\n}	0
20564805	20563451	Storing pdf file inside sql server using nhibernate, byte[] value exceeds	Map(x => x.PDFFile).CustomType("BinaryBlob").Length(100000);	0
14584945	14584695	Issue with string manipulation in c#	public static string UNID =  ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity).Claims\n  .Where(c => c.ClaimType.Contains("nameidentifier"))\n  .Select(c => c.Value.Substring(c.Value.IndexOf('/')+1))\n  .Single();	0
29771266	29488576	Check whether all nodes in a particular Level are selected in Telerik RadtreeControl using C#	List<RadTreeNode> lvlOneNodes = RadTreeView1.GetAllNodes().Where(node => node.Level == 1).ToList();\n    foreach (RadTreeNode item in lvlOneNodes)\n    {\n        Response.Write(item.Checked);\n    }	0
7993187	7993167	Execution flow of a linq query	IEnumerable<int> query = numbers.Select (n => n * 10);	0
20839485	20837470	How do I create a set of equidistant points between two known points?	private static List<PointF> ExtendPoints(PointF pt1, PointF pt4, int numberOfPoints)\n{\n       extendedPoints = new List<PointF>();\n       extendedPoints.Add(pt1);\n\n       for(double d = 1; d < numberOfPoints-1; d++)\n       {\n            float a = (Math.Max(pt1.X, pt4.X) - Math.Min(pt1.X, pt4.X)) * d / (double)(numberOfPoints-1) + Math.Min(pt1.X, pt4.X);\n            float b = (Math.Max(pt1.Y, pt4.Y) - Math.Min(pt1.Y, pt4.Y)) * d / (double)(numberOfPoints-1) + Math.Min(pt1.Y, pt4.Y);\n            var pt2 = new PointF(a, b);\n            extendedPoints.Add(pt2);\n       }\n\n       extendedPoints.Add(pt4);\n       return extendedPoints;\n}	0
1577568	1577540	Retrieve two values in the same linq query	var all = (from t in db.tax select new ClsTax { Tax = t.tax1, Increase = t.increase });\nvar count = all.Count();\nvar result = all.Take(25);	0
10696420	10696357	Remove a character when between two numbers (regular expression)	String str = "2012-15 - 2012-20";\n        String newStr = Regex.Replace(str, "(\\d+)-(\\d+)", "$1 v$2");\n        Console.WriteLine(str);\n        Console.WriteLine(newStr);\n        Console.ReadLine();	0
16775535	16775493	Parse multiple values from string c#	string input="5+5";\n\nvar numbers = Regex.Matches(input, @"\d+")\n                   .Cast<Match>()\n                   .Select(m => m.Value)\n                   .ToList();	0
33747219	33705547	Recursively remove element from start and end of list at same time	public IList<Day> RemoveDays(IList<Day> days)\n{\n    while (true)\n    {\n        if (days.Count <= 0 || !(days.First().IsActive || days.Last().IsActive)) return days;\n        if (days.First().IsActive)\n            days.RemoveAt(0);\n        if (days.Count > 0 && days.Last().IsActive)\n            days.RemoveAt(days.Count - 1);\n    }\n}	0
13656895	13656223	Dependency Injection linking two objects	var engine = new Engine();\nengine.Component = new Component(engine);	0
32910564	32910508	FileHelperEngine Library Mapping to Datetime Exception	[FieldConverter(ConverterKind.Date, "yyyy-MM-dd HH:mm:ss.fff")]	0
23217717	23217363	Remove specific string from given URL	temp_url.replace("-resize","");	0
19663416	19663276	Can i order/sort data from ResXResourceReader?	SortedDictionary<string, ResXDataNode>	0
11964964	11964955	How to check what filter is applied	SaveFileDialog dlg = new SaveFileDialog();\n        dlg.Filter = "xpdl 2.1|*.xpdl|xpdl 2.2|*.xpdl";\n        if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n        {\n            switch (dlg.FilterIndex)\n            {\n                case 1:\n                    //selected xpdl 2.1\n                    break;\n                case 2:\n                    //selected xpdl 2.2\n                    break;\n            }\n        }	0
5692193	5692171	Couldn't write file to Application.StartupPath in Windows 7	Environment.GetFolderPath(SpecialFolder.ApplicationData)	0
19380222	19379823	Showing data like a tree in code behind	public class Item\n{\n    public Item()\n    {\n        Children = new List<Item>();\n    }\n\n    public int Id { get; set; } \n    public string Name { get; set; } \n    public int ParentId { get; set; }\n    public List<Item> Children { get; set; } \n}\n\npublic class TreeBuilder\n{\n    public TreeBuilder(IEnumerable<Item> items)\n    {\n        _items = new HashSet<Item>(items);\n        TreeRootItems = new List<Item>();\n        TreeRootItems.AddRange(_items.Where(x => x.ParentId == 0));\n        BuildTree(TreeRootItems);\n    }\n\n    private readonly HashSet<Item> _items;\n    public List<Item> TreeRootItems { get; private set; }\n\n\n    public void BuildTree(List<Item> result)\n    {\n        foreach (var item in result)\n        {\n            item.Children.AddRange(_items.Where(x => x.ParentId == item.Id));\n            BuildTree(item.Children);\n        }\n    }\n}	0
11797021	11781494	WPF application settings - resetting a single property	Settings.Default.PropertyValues["MyPropertyName"].SerializedValue = Settings.Default.Properties["MyPropertyName"].DefaultValue;\nSettings.Default.PropertyValues["MyPropertyName"].Deserialized = false;	0
2025418	2025059	How to Manage User Modifiable Lookup Tables	lkpTable\nPK Identity\nDescription\nFK LogicEnum NULL\n\nlkpLogic\nPK EnumValue\nLogicParamColumns	0
7287238	7287134	How to open a toolbar menu by Keyboard short-cuts?	protected override void OnKeyDown(KeyEventArgs e)\n{\n\n    if (e.Alt && e.KeyCode == Keys.A)\n    {\n        toolStripDropDownButton1.ShowDropDown();\n    }\n    base.OnKeyDown(e);\n}	0
15747444	15746285	Read structure from file c#	info1=exampleinfo\ninfo2=exampleinfo2\ninfo3=example\n    example2\n    example3\ninfo4=example\n    example2\n    example3	0
3062442	3060004	Scroll a ListBox's VirtualizingStackPanel with buttons	public void ShowNextPage()\n{\n   InvokeOnScrollViewer(listBox, viewer => viewer.PageDown());\n}\n\npublic void ShowPriorPage()\n{\n   InvokeOnScrollViewer(listBox, viewer => viewer.PageUp());\n}\n\npublic void InvokeOnScrollViewer(ItemsControl control, Action<ScrollViewer> action)\n{\n  for(Visual vis = control as Visual; VisualTreeHelper.GetChildCount(vis)!=0; vis = VisualTreeHelper.GetChild(vis, 0))\n    if(vis is ScrollViewer)\n    {\n      Action((ScrollViewer)vis);\n      break;\n    }\n}	0
3123807	3123757	Data Binding to DataGridView	public class Patient\n{\n    public string Initials { get; set; }\n    public string LastName { get; set; }\n\n    public string InitialsAndLastName\n    {\n        get { return this.Initials + " " + this.LastName; }\n    }\n}	0
28498768	28498679	Make C# function stored in XML	string one = "format me {0}{1}";\n    string two = "here, and here";\n    Console.WriteLine(one, two.Split(','));	0
2870169	2870155	How do you identify authentcated user in WCF?	string login = OperationContext.Current\n                               .ServiceSecurityContext\n                               .PrimaryIdentity\n                               .Name;	0
1546843	1546818	Nth root of small number return an unexpected result in C#	MessageBox.Show(Math.Pow(1.07,(1/3).toString()));	0
8674124	8674003	Making control docking and scrollbars play nicely	bool resizingTlp;\n\n    private void tableLayoutPanel1_Resize(object sender, EventArgs e) {\n        if (resizingTlp) return;\n        resizingTlp = true;\n        if (tableLayoutPanel1.Height <= panel1.ClientSize.Height) tableLayoutPanel1.Width  panel1.ClientSize.Width;\n        else tableLayoutPanel1.Width = panel1.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;\n        resizingTlp = false;\n    }	0
15213257	15213130	dropdownList insert NULL	model.CategoryMenu = db.Categories.Select(c => new SelectListItem {\n                                                    Text = c.Name,\n                                                    Value = c.Id.ToString(),\n                                                   }\n                                          );	0
9992206	9991394	APPBAR space allocation issue in Windows XP	public static void RemoveAppBar(Window appbarWindow)\n        {\n            RegisterInfo info = GetRegisterInfo(appbarWindow);\n\n            if (info.IsRegistered)\n            {\n                APPBARDATA abd = new APPBARDATA();\n                abd.cbSize = Marshal.SizeOf(abd);\n                abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;\n                SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);\n            }\n        }	0
10827937	10827399	Do I have to declare variables public to use [Dependency] with Unity?	public class ContentsController : BaseController\n{\n  private readonly IContentService service;\n  public ContentsController(IContentService service)\n  {\n    if(service == null) throw new ArgumentNullException("service");\n    this.service = service;\n  }\n}\n\nvar container = new UnityContainer();\ncontainer.RegisterType<IContentService, MyContentService>();\nvar controller = container.Resolve<ContentsController>();	0
206615	206611	How to set a default value using "short style" properties in VS2008 (Automatic Properties)?	public class Person\n{\n   public Person()\n   {\n       this.FirstName = string.Empty;\n   }\n\n   public string FirstName { get; set; }\n}	0
26827317	26827285	parse string contains time of day	rad_from_time.SelectedTime = DateTime.ParseExact(pro[0].FromTime, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;	0
32264599	32264504	How to obtain mouse cursor coordinates from lParam from a low level mouse callback method?	[StructLayout(LayoutKind.Sequential)]\n public struct MSLLHOOKSTRUCT\n {\n     public POINT pt;\n     public int mouseData; // be careful, this must be ints, not uints (was wrong before I changed it...). regards, cmew.\n     public int flags;\n     public int time;\n     public UIntPtr dwExtraInfo;\n }	0
21628199	21623685	How to prevent blinking cursor for TextBox in C# (little bit more complicated)	using System;\nusing System.Windows.Forms;\n\nclass TextBoxLabel : TextBox {\n    public TextBoxLabel() {\n        this.SetStyle(ControlStyles.Selectable, false);\n        this.TabStop = false;\n    }\n    protected override void WndProc(ref Message m) {\n        // Workaround required since TextBox calls Focus() on a mouse click\n        // Intercept WM_NCHITTEST to make it transparent to mouse clicks\n        if (m.Msg == 0x84) m.Result = IntPtr.Zero;\n        else base.WndProc(ref m);\n    }\n}	0
13520083	13519978	Google-drive-sdk-samples, how to fetch with SVN	hg clone https://code.google.com/p/google-drive-sdk-samples/	0
18886716	18886587	View files in WebBrowser	//Response.AddHeader("content-disposition", String.Format("inline;attachment; filename={0}",filePath));\nResponse.AddHeader("Content-Disposition", "inline; filename=" + filePath);	0
24930654	24889255	Can I Populate A Lookup/Optionset based on the results of a Lookup	var accountid; // contains id from your Account Lookup control\n\nvar fetchfilter = '<filter type="and"><condition attribute="customerid" operator="eq" value="' + accountid + '" /></filter>';\n\nXrm.Page.getControl('YOUR_ORDER_LOOKUP_ATTRIBUTE_NAME_HERE').addCustomFilter(fetchfilter)	0
15063357	13090070	Get License from Payload Id	Path.GetDirectoryName(this.GetType().Assembly.Location);	0
30247013	30246190	Trying to get data shown in a drop down list	var data = \n            from p in db.Contacts\n                   select new \n                   {\n                      Name = p.FirstName + " " + p.LastName,\n                      Id = p.IdContact\n                   };\n        SelectList personList = new SelectList(data, "Id", "Name");	0
30090187	30090125	Updating 2 rows in SQL database with one query string "UPDATE"	string query = "UPDATE Photos Set PhotoName = '@PhotoNewName' ,Details  = '@DetailsNew' WHERE PhotoID = '@PhotoID'";	0
5639452	5639364	How can I convert this join to LINQ syntax?	var tools = from p in products where p.X == 14 select p.Tool;	0
24851259	24850326	Windows phone 8 Textbox accept return as submit button	private void SomeTextBox_KeyDown(object sender, KeyEventArgs e)\n{\n    if(e.Key == Key.Enter)\n    {\n         this.Focus(); // dismiss the keyboard\n         // Call the submit method here\n    }\n}	0
4561548	4560693	Getting the Last Modified Date of an assembly in the GAC	static void Main(string[] args)\n{\n  // Run the method with a few test values\n  GetAssemblyDetail("System.Data"); // This should be in the GAC\n  GetAssemblyDetail("YourAssemblyName");  // This might be in the GAC\n  GetAssemblyDetail("ImaginaryAssembly"); // This just plain doesn't exist\n}\n\nprivate static DateTime? GetAssemblyDetail(string assemblyName)\n{\n  Assembly a;\n  a = Assembly.LoadWithPartialName(assemblyName);\n  if (a != null)\n  {\n    Console.WriteLine("'{0}' is in GAC? {1}", assemblyName, a.GlobalAssemblyCache);\n    FileInfo fi = new FileInfo(a.Location);\n    Console.WriteLine("'{0}' Modified: {1}", assemblyName, fi.LastWriteTime);\n    return fi.LastWriteTime;\n  }\n  else\n  {\n    Console.WriteLine("Assembly '{0}' not found", assemblyName);\n    return null;\n  }\n}	0
18786017	18785895	asp.net DetailView datetime field format doesn't match the SQL Server format	DateTime.Now.ToString(yyyy-MM-dd)	0
19827411	19827346	Quickly escape special characters while building a string	public JsonResult getAutoCompletedata(string query)\n{\n    var query = from p in dt.AsEnumerable() //dt is the datatable\n                        where p.Field<string>("code") == query\n                        select new\n                        {\n                            value = p.Field<string>("yourColumnName"),\n                            lable= p.Field<string>("YourAnotherColumnName")                         \n                        }.ToList();\n    return Json(query, JsonRequestBehavior.AllowGet);\n}	0
31637813	31615116	Microsoft Ribbon button to execute function from add-in	Globals.ThisAddin	0
10108430	10107788	Email: how to set a name of the embedded image in C# / System.Mail?	lr.ContentType.Name = "my image name.jpg";	0
14887001	14871325	Resize a Graphics Path on MouseMove	Matrix m = new Matrix();\nm.Scale(scaleX, scaleY, MatrixOrder.Append);\nm.Translate(offsetX, offsetY, MatrixOrder.Append);\npath.Transform(m);	0
20115060	20113515	Cannot save data c# Windows Application	When using a .sdf file (SQL Server Compact Edition), you need to use SqlCeConnection and not SqlConnection (that works against a full SQL Server):	0
25321424	25321295	Count occurrence for each day of the week between two dates	DateTime start = new DateTime(2014,07,20);\nDateTime end = new DateTime(2014,07,27);\nTimeSpan ts = end - start;\nint limit = ts.Days;\nvar result = Enumerable.Range(0,limit+1)\n            .Select(x => start.AddDays(x))\n            .GroupBy(x => x.DayOfWeek)\n            .Select(x => new {day = x.Key, count = x.Count()});	0
11466125	11364818	how to call another process from a c# project?	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.CreateNoWindow = false;\nstartInfo.UseShellExecute = false;\nstartInfo.FileName = "dcm2jpg.exe";\nstartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nstartInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;\n\ntry\n{\n        // Start the process with the info we specified.\n        // Call WaitForExit and then the using statement will close.\n        using (Process exeProcess = Process.Start(startInfo))\n        {\n           exeProcess.WaitForExit();\n        }   \n}\ncatch\n{\n    // Log error.\n}	0
15936041	15936014	OR statement in lambda expression	var list = db.Tasks\n             .Where(t => t.CategoryId == 1 || \n                         t.CategoryId == 2 ||\n                         t.CategoryId == 3)\n             .ToList();	0
3556188	3556144	How to create a .NET DateTime from ISO 8601 format	DateTime d2= DateTime.Parse("2010-08-20T15:00:00Z",  null, System.Globalization.DateTimeStyles.RoundtripKind);	0
32184550	32067659	Setting ContextMenu Style to 2013	var dv = wd.Context.Services.GetService<DesignerView>();\ndv.MenuItemStyle = null;\ndv.MenuSeparatorStyle = null;\ndv.Resources[typeof(ContextMenu)] = new Style(typeof(ContextMenu));	0
26342780	26341974	Windows Form - auto increment form number from last acess table value	using(OleDbConnection conn = new OleDbConnection(......))\nusing(OleDbCommand cmd = new OleDbCommand("SELECT @@IDENTITY", conn))\n{\n      conn.Open();\n      int newServiceRequestNumber = Convert.ToInt32(cmd.ExecuteScalar());\n      ....\n}	0
32086707	32086691	How to open a directory using c#	Process.Start(pathOfDir);	0
29620097	29619857	Need help accessing the specific value of an array in a seperate method	for (int i = 0; i <= 1; i++) {\n    //do stuff\n    var index = Array.IndexOf(searchRainFall, RainFall);\n    if (index > -1) {\n        Console.WriteLine(searchMonths[index] + " was the first month to have " + RainFall + " inches fell this year.");\n    } else {\n        Console.WriteLine("No rainfall of " + RainFall + " inches fell that year.");\n    }\n}	0
14270477	14270460	regex check second letter of string	var flag = char.IsLetter(s[s.Length - 1]) || \n           s[1] == 'p' || \n           s[1] == 'r';	0
1226210	1195110	WCF UriTemplate with large query strings	var ut = new UriTemplate("Api.jsp{query}");\n    var u = ut.BindByName(new Uri("http://localhost"), new Dictionary<string, string>() { { "query", "?param1=a&param2=b" } });\n    Console.WriteLine(u); // http://localhost/Api.jsp%3Fparam1=a&param2=b	0
33688886	33670884	Using digest of your site's authentication cookie for CSRF	X-Requested-With	0
2103872	2103632	guest denied access to admin folder redirected to Login.aspx	if (!IsPostBack)\n        {\n\n            if (User.Identity.IsAuthenticated)\n            {\n                if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))\n                {\n                    Response.Redirect("~/Guest/Pagedenied.aspx");\n                }\n            }\n\n        }	0
518423	518379	How to get model data from a ViewResult in ASP.NET MVC RC1?	result.ViewData.Model	0
15420371	15420128	How to serialize a nested list in c# into XML without specifying a list element?	public class Foo\n{\n    public string FooName{get;set;}\n    [XmlElement("Bar")]\n    public List<Bar> Bars{get;set;}\n}	0
32366926	32366853	How to add comma in random generated numbers C# winforms	String.Format("{0:N2}", new Random().NextDouble()*10000)	0
27892632	27891024	How to download multiple files? Getting "Server cannot clear headers after HTTP headers have been sent."	var outputStream = new MemoryStream();\n\nusing (var zip = new ZipFile())\n{\n    zip.AddFile("path to file one");\n    zip.AddFile("path to file two");\n    zip.AddFile("path to file three");\n    zip.AddFile("path to file four");\n    zip.Save(outputStream);\n}\n\noutputStream.Position = 0;\nreturn File(outputStream, "application/zip","zip file name.zip");	0
3995157	3889734	Programmatic way of refreshing VS Item Template cache from within Visual Studio Add-In	DTE2.GetProjectItemTemplate(releativeLocation, projectLanguage)	0
14458878	14458766	Generate TextBlock From codebehind in a particular	TextBlock MyTextBlock = New TextBlock();\n    Grid.SetRow( MyTextBlock, 1 );\n    Grid.SetColumn( MyTextBlock, 2 );\n    grid1.Children.Add( MyTextBlock );	0
26141191	26137777	sort and group a list of objects by multiple properties	theList.GroupBy(o => o.EventName).Select(s => s.OrderBy(a => a.Start).ThenBy(a => a.End)).SelectMany(sm => sm).ToList();	0
19150543	19150468	Get SHA1 binary base64 hash of a file on C#	string GetBase64EncodedSHA1Hash(string filename)\n{\n    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))\n    using (SHA1Managed sha1 = new SHA1Managed())\n    {\n        return Convert.ToBase64String(sha1.ComputeHash(fs));\n    }\n}	0
10088342	10088302	Design without default constructor	private DerivedClass()\n{\n    // code\n}	0
10370199	10370187	Programmatically add a TextBlock to a DataTemplate	var newTextBlock = new FrameworkElementFactory(typeof(TextBlock));\nnewTextBlock.Name = "txt";\nnewTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA"));\nDataTemplate newDataTemplate = new DataTemplate(){VisualTree = newTextBlock};	0
16685122	16678415	Validate data in Radgrid before changing pages	protected void RadGrid1_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)\n{\n    if (Mapvalues(false))\n    {\n        e.Canceled = true; //Prevent to execute pagging functionality\n    }\n}\nprotected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)\n{\n    if (Mapvalues(false))\n    {\n        e.Canceled = true; //Prevent to execute pagging functionality\n    }\n}	0
2593411	2593313	how to execute console application from windows form?	System.Diagnostics.Process.Start( @"cmd.exe", @"/k c:\path\my.exe" );	0
6266007	6265977	Saving an Assembly as a byte array suitable for Assembly.Load	File.ReadAllBytes	0
5395996	5395783	How to evaluate and process a simple string syntax-tree in C#?	Set Eval (Tree t) {\n\n    switch (t.Operator) {\n        case OR:\n             Set result = emptySet;\n             foreach(child in T.Children) {\n                 result = Union(result, Eval(child));\n             }\n             return result;\n        case AND:\n             Set result = UniversalSet;\n             foreach(child in T.Children) {\n                 result = Intersection(result, Eval(child));\n             }\n             return result;\n        case blah: // Whatever.\n    }\n    // Unreachable.\n}	0
33789499	33789343	Find all the child controls in wpf	private void FindAllChildren()\n{\n    var depObj = dataGrid;\n\n    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)\n    {\n        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);\n        if (child is DataGridTemplateColumn)\n        {\n            // do a thing\n        }\n    }\n}	0
19342040	19239295	Querying an Excel File from C# - No Results	da.Fill(ds);\n        dgsResults.DataSource = ds.Tables[0]; //this is the line to be added	0
5112031	5111893	How to display part of a line in a .txt file - C#	StreamReader Reader = new StreamReader(MainFileName);\n            char c = Convert.ToChar(@"/");\n            Char[] splitChar = { c, c };\n            String Line;\n            while (!Reader.EndOfStream)\n            {\n                Line = Reader.ReadLine();\n                String[] Parts;\n                Parts = Line.Split(splitChar);\n                foreach (string s in Parts)\n                {\n                    Console.WriteLine(s);\n                }\n            }\n            Reader.Close();\n            Console.WriteLine("Done");	0
23153402	23132735	Hide console window, not the taskbar button	ITaskbarList::AddTab	0
22230663	22230547	How do I access methods that are not part of an interface definition? (while still programming to interfaces)	public interface ITestableTextProcessor : ITextProcessor\n{\n    void TestMethod();\n}\n\npublic class FileProcessorTest : ITestableTextProcessor {...}	0
9510342	9510048	How can I retrieve all files sizes of a folder based on file name and/or extension?	var directory = @"c:\myfolder";\nvar files = Directory.GetFiles(directory, "file.zip", SearchOption.AllDirectories)\n.Select(name => new FileInfo(name))\n.Where(f => f.Length == 0).ToArray();	0
14919334	14919318	c# MySQL like query not taking parameters	string cmdText = "SELECT * FROM tblshareknowledge where title LIKE @myTitle";\ncmd = new MySqlCommand(cmdText, con);\ncmd.Parameters.AddWithValue("@myTitle", "%" + title + "%");	0
15652807	14998572	Linq to full outer join multiple tables in a Dataset	var rowData =\n                        from row1 in dsResults.Tables[0].AsEnumerable()\n                        join row2 in dsResults.Tables[1].AsEnumerable()\n                            on row1.Field<decimal>("RecordId") equals row2.Field<decimal>("RecordId2")\n                        join row3 in dsResults.Tables[2].AsEnumerable()\n                            on row1.Field<decimal>("RecordId") equals row3.Field<decimal>("RecordId3")\n                        select row1.ItemArray.Concat(row2.ItemArray).Concat(row3.ItemArray).ToArray();	0
27041895	27038314	Extract subdocuments array from a MondoDB document using C#	var fields = Fields.Exclude("_id").Include("Hierarchy.Region.Area");\nvar queryString = Query.EQ("Hierarchy.Region.Name", "Dhaka");\nvar result = collection.Find(queryString).SetFields(fields).SetFields().ToList();	0
31168608	31168177	How can I make an Optional 1:1 Relationship in EF6 with the same Entity Type on both sides?	modelBuilder.Entity<Donut>()\n        .HasOptional(e => e.ChildDonut)\n        .WithMany()\n        .HasForeignKey(t => t.ChildDonutId);\n\n modelBuilder.Entity<Donut>()\n        .HasOptional(e => e.ParentDonut)\n        .WithMany()\n        .WithMany(t => t.ParentDonutId);	0
13161176	13161016	Location in Windows 8	Geoposition pos = await geo.GetGeopositionAsync();	0
5422107	5422024	Array of string from Arraylist of Arraylist	var allList = \n    MainList.\n        Cast<ArrayList>().\n        SelectMany(a => a.Cast<string>()).\n        ToArray();\n\nvar onlySome = \n    MainList.\n        Cast<ArrayList>().\n        Select(a => \n            a.Cast<string>().\n                Skip(1).\n                First()).\n        ToArray();	0
7035717	7035708	How to launch external application that keeps alive after closing the calling program in C#?	Process.Start	0
24562406	24561338	Saving multiple objects at once in parse.com	List<ParseObject> scores = new List<ParseObject>();\nforeach (DataRow row in dataTable.Rows) //imagine here I am saving 1000 objects\n{\n      gameScore = new ParseObject("SALON");\n      gameScore["NAME"] = "NAMETEMP";\n      scores.Add(gameScore);\n}\nawait ParseObject.SaveAllAsync(scores);	0
6679610	6679577	How to update an XML string	XmlElement.SetAttribute	0
9470177	9468306	select row in GridEx in runTime	int row = myGrid.Row;\n\n// Perform update\n\ntry\n{\n    vJanusDataGridMeasures.Row = row;\n}\n// The row index that was selected no longer exists.\n// You could avoid this error by checking this first.\ncatch (IndexOutOfRangeException)\n{\n    // Check to see if there are any rows and if there are select the first one\n    if(vJanusDataGridMeasures.GetRows().Any())\n    {\n        vJanusDataGridMeasures.Row = 0;\n    }\n}	0
34242574	34242472	Is it possible to Linq Directly to a Dictionary?	IEnumerable<T>	0
13186810	13169526	Using a relative path in connection string for Access DB in C#	AppDomain.CurrentDomain.SetData("DataDirectory", Server.MapPath("~/App_Data/"));	0
27906094	27905808	How to compare strings at C# like in SQL server case insensitive and accent insensitive	string.Compare(s1,s2,\n               CultureInfo.InvariantCulture,\n               CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)	0
12196905	12196819	string.format() with at least one decimal place	string.Format("{0:0.0###########}",myval);	0
12514509	12513989	Rapidly removing (and adding) many items to a Canvas in WPF	Canvas.Children.RemoveRange(a);	0
10117891	10117477	how to change checkbox size in datagridview winform	if (e.ColumnIndex == 0 && e.RowIndex >= 0)//Assuming the checkbox is in Column 0\n        {\n            e.PaintBackground(e.ClipBounds, false);\n            int index = 0;//Unchecked image\n            if (e.Value != null && (bool)e.Value == true)\n                index = 1;//Checked image\n                e.Graphics.DrawImageUnscaled(imageList1.Images[index], e.CellBounds.X + 5, e.CellBounds.Y + 5);\n\n            e.Handled = true;\n        }	0
15089809	15089513	How to call a keyboard key press programmaticly?	using System;\nusing System.Runtime.InteropServices;\n\npublic class CapsLockControl\n{\n\n    public const byte VK_NUMLOCK = 0x90;\n    public const byte VK_CAPSLOCK = 0x14;\n\n    [DllImport("user32.dll")]\n        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,UIntPtr dwExtraInfo);\n    const int KEYEVENTF_EXTENDEDKEY = 0x1;\n    const int KEYEVENTF_KEYUP = 0x2;\n\n    public static void Main()\n    {\n        if (Control.IsKeyLocked(Keys.CapsLock))\n        {\n            Console.WriteLine("Caps Lock key is ON.  We'll turn it off");\n            keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);\n            keybd_event(CapsLockControl.VK_CAPSLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,\n                (UIntPtr) 0);\n        }\n        else\n        {\n            Console.WriteLine("Caps Lock key is OFF");\n        }\n    }\n}	0
28045588	28045232	Serialize JSON from Web service in Windows Phone 8.1	public string ts { get; set; }	0
10932874	10932795	C#:Enable button if datagrid cell value is a number	if (!int.TryParse(e.FormattedValue.ToString(),\n             out newInteger) || newInteger < 0)\n{\n   e.Cancel = true;\n   ThermalDatGrid.Rows[e.RowIndex].ErrorText = "Only Numerical and Non Negative Values";\n}\nelse\n{\n   yourButton.Enabled=true;\n}	0
7348821	7348771	Linq to XML parses files in a folder	Directory.EnumerateFiles(@"C:\Something", "*.xml")	0
22535418	22531218	EF 6 delete fails with The select list for the Insert statement contains more items than the insert list	dbo.Product	0
18409628	18409627	How to dynamically load Page from xaml file/resource?	Page p = (Page)Application.LoadComponent(new Uri(@"relative/uri/to/xaml/file.xaml", UriKind.Relative));	0
11585749	11585721	create a byte[] from a bmp c#	.Save()	0
354961	354945	Most effective way to grab a table name in the following string	string q = @"SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1] FROM [SchemaName].[TableName] AS [t0] WHERE ([t0].[Id] <> @p0)";\n            int fromIndex = q.IndexOf("FROM")+5;\n            int asIndex = q.IndexOf("AS",fromIndex);\n            q = q.Substring(fromIndex, asIndex - fromIndex);	0
2782727	2774740	Silverlight 4 how to format a binded decimal value	{Binding Source={StaticResource Valor}, Path=ValorReal, ValidatesOnExceptions=True, Mode=TwoWay, ValidatesOnDataErrors=True, StringFormat=c, NotifyOnValidationError=True}	0
24308154	24285441	Two Custom User Controls That Should Update Each Other But Only One Does (ASP.Net)	protected void gvPlayers_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n\n    if (e.CommandName == "Delete")\n    {\n        int ndex = int.Parse(e.CommandArgument.ToString());\n        int key = int.Parse(gvPlayers2.DataKeys[ndex].Value.ToString());\n\n        PlayersLogic pl = new PlayersLogic();\n        pl.RemovePlayerFromTeam(key);\n    }\n}\n\n\nprotected void gvPlayers2_RowDeleting(object sender, GridViewDeleteEventArgs e)\n{\n\n    if (OnPlayerRemovedFromTeam != null)\n    {\n        OnPlayerRemovedFromTeam(this, e);\n    }\n\n    LoadPlayers(true);\n}	0
3837830	3837816	Windows Version	Environment.OSVersion	0
30087512	30079379	SslStream, disable session caching	var sslAssembly = Assembly.GetAssembly(typeof(SslStream));\n\nvar sslSessionCacheClass = sslAssembly.GetType("System.Net.Security.SslSessionsCache");\n\nvar cachedCredsInfo = sslSessionCacheClass.GetField("s_CachedCreds", BindingFlags.NonPublic | BindingFlags.Static);\nvar cachedCreds = (Hashtable)cachedCredsInfo.GetValue(null);\n\ncachedCreds.Clear();	0
32892800	32892066	Find all string parts starting with [ and ends with ] in long string	string[] result = Regex.Matches(input, @"\[(col_\d+)\]").\n                            Cast<Match>().\n                            Select(x => x.Groups[1].Value).\n                            ToArray();	0
22669617	22669496	Accessing a function in polymorphism	public class A\n{\n    public virtual void Foo()\n    {\n\n    }\n}\n\npublic class B : A\n{\n    public override void Foo()\n    {\n\n    }\n}\n\npublic class C : A\n{\n    public override void Foo()\n    {\n\n    }\n}	0
17425699	17367480	Setting custom control properties from Style XAML	public int FramesCount\n    {\n        get { return _framesCount; }\n        set\n        {\n            _framesCount = value;\n            if (ImageFileMask != null) ReloadFrames();\n        }\n    }\n\n    public static readonly DependencyProperty FramesCountProperty =\n        DependencyProperty.Register(\n            "FramesCount",\n            typeof(int),\n            typeof(MyControl),\n            new PropertyMetadata(false, (d, e) =>\n            {\n                (d as MyControl).FramesCount = (int)e.NewValue;\n            })\n        );	0
12918447	12918405	Cannot open DBF with spaces in the path	Connection.ConnectionString = @"Driver={Microsoft Visual FoxPro Driver};Exclusive=No;SourceType=DBF;SourceDB=""" + strFilename + """;";	0
15980238	15979356	translate gaussian noise in opencv to emgu cv	//Create your image as Image<Bgr,byte> here, for example.\nMatrix<byte> matrix = new Matrix<byte>(img.Width, img.Height);\nCvInvoke.cvConvert(img, matrix);\nmatrix.SetRandNormal(new MCvScalar(128), new MCvScalar(30));\n//And Here you can convert back to image and do whatever you want.	0
18449521	10890516	Rewrite Recursive algorithm more simply - Euler 15	const int n = 4;\nint a[n + 2][n + 2] = {0};\n\na[0][0] = 1;\nfor (int i = 0; i < n + 1; ++i)\n    for (int j = 0; j < n + 1; ++j) {\n        a[i][j + 1] += a[i][j];\n        a[i + 1][j] += a[i][j];\n    }\n\nstd::cout << a[n][n] << std::endl;	0
24914688	24914631	s(String) is a 'field' but is used like a 'type' C#	public class SForceTest\n{\n    String s = "";\n\n    public SForceTest()\n    {\n        s = "asdsa";\n    }\n}	0
23758063	23757910	Get a string to reference another in C#	unsafe\n{\n    string* a = &ArrayOfReallyVeryLongStringNames[439];     // no compile\n}	0
14786328	14780767	How to map to a Dictionary object from database results using Dapper Dot Net?	var dict = conn.Query(sql, args).ToDictionary(\n    row => (string)row.UniqueString,\n    row => (int)row.Id);	0
8275165	8272125	More Linq Data Pivoting	var temp = reportDataTable.AsEnumerable().GroupBy(a => a["ItemCode"]).Select(b => \n    new{ItemCode = b.Key, \n        companyWide = b.Where(a => (string)a["Name"] == "-1").Select(a =>a["Rank"]).FirstOrDefault(),\n        myGroup = b.Where(a => (string)a["Name"] == "*PLACEHOLDER*").Select(a => a["Rank"]).FirstOrDefault() }) ;	0
18608384	18608208	Convert single XElement to object	[Serializable()]\n[XmlRoot(ElementName = "row")]\npublic class ProductAttribute\n{\n    [XmlAttribute("flag")]\n    public string Flag { get; set; }\n    [XmlAttribute("sect")]\n    public string Sect { get; set; }\n    [XmlAttribute("header")]\n    public string Header { get; set; }\n    [XmlAttribute("body")]\n    public string Body { get; set; }\n    [XmlAttribute("extrainfo")]\n    public string Extrainfo { get; set; }\n}	0
3173034	3173013	How to get overlapping rectangle coordinates	Rectangle.Intersect	0
3179565	3179538	Remove case sensitivity from FormsAuthentication.Authenticate of user name/password	string uid = UserText.Text.Trim().ToUpper();\nstring pwd= PwdText.Text.Trim().ToUpper();	0
2917525	2917506	how to tell a user exactly why login failed in asp.net	public override bool ValidateUser(string username, string password)\n{\n   // in membership provider\n   HttpContext.Current.Items["loginFailureReason"] = "Locked Out";\n   return false;\n}\n\n// in login codebehind\nprotected void Login1_LoginError(object sender, EventArgs e)\n {\n     Login1.FailureText = (string) HttpContext.Current.Items["loginFailureReason"];\n }	0
21030293	21029870	How to center dynamic buttons in a groupbox Windows form application	Button[,] buttons = new Button[4, 4];\n        int c, r;\n\n        int xOffset = (groupBox1.Width - (40 * 4)) / 2;\n        int yOffset = (groupBox1.Height - 25 * 4) / 2;\n\n        for (r = 0; r < 4; r++) for (c = 0; c < 4; c++)\n            {\n                buttons[r, c] = new Button {Parent = groupBox1, Top = yOffset + r*25, Left = xOffset + c*40, Width = 40};\n            }\n        buttons[0, 0].Text = "1";	0
11978517	11975293	Make ColdFusion accept ASP.NET credentials	cookie.Domain=".mydomain.com";	0
18568608	18568588	How to create a Guid with all zero elements?	var guid = Guid.Empty;	0
28148920	28148881	how to implement a function when cancel button is clicked return 0 but when save is clicked return 1 and refresh grid	if(f2.ShowDialog() == DialogResult.OK))\n  // User hits the OK button, refresh\nelse\n  // No refresh here...	0
30409576	30409355	How can i run sql server script with c#?	Microsoft.SqlServer.Server	0
19865284	19864956	Change field in all instances of a class using a static field that changes all the instances	public class KewlButton : Button {\n  public delegate void SetBackColor(Color color);\n  static SetBackColor setBackColor;\n  public KewlButton(){\n    setBackColor += ChangeBackColor;\n    Disposed += (s,e) => {\n       setBackColor -= ChangeBackColor;\n    };\n  }\n  private void ChangeBackColor(Color color){ \n     BackColor = color;\n  }\n  public class Crossdress {\n    public static Color BackColor { \n        set {\n            if(setBackColor!=null) setBackColor(value);\n        }\n    }\n  }\n}\n\n//Usage\nKewlButton.Crossdress.BackColor = Color.Red;	0
9425314	8897862	Automatic log in with Facebook C# SDK?	FB.getLoginStatus(function(response) {\n  if (response.status === 'connected') {\n    // the user is logged in and has authenticated your\n    // app, and response.authResponse supplies\n    // the user's ID, a valid access token, a signed\n    // request, and the time the access token \n    // and signed request each expire\n    var uid = response.authResponse.userID;\n    var accessToken = response.authResponse.accessToken;\n  } else if (response.status === 'not_authorized') {\n    // the user is logged in to Facebook, \n    // but has not authenticated your app\n  } else {\n    // the user isn't logged in to Facebook.\n  }\n });	0
17725336	17725246	Group a set of rows based on a column	listOfItems.GroupBy(key => new { key.LessonNumber, key.LessonTitle },\n     data => new {data.Status, data.TargetDate, data.EventTitle});	0
18269543	18269395	get the value of dropdown on asp button click	string selectedValue = Request.Form[ddlDepartment.UniqueID];	0
27617390	27617198	Allow me being new to app domain, how can i run a constructor using app domain	AppDomain domain = AppDomain.CreateDomain("New domain name");\nstring pathToDll = @"C:\Users\user1\Desktop\Aspose.Words.dll";\nType t = typeof(Aspose.Words.Document);\nObject[] constructorArgs = new Object[1];\nconstructorArgs[0] = inputFileName;\nAspose.Words.Document myObject = (Aspose.Words.Document)domain.CreateInstanceFromAndUnwrap(\n    pathToDll, \n    t.FullName,\n    false,            //ignoreCase\n    0,                //bindingAttr\n    null,             //binder, use Default \n    constructorArgs,  //the constructor parameters\n    null,             //culture, use culture of current thread\n    null);            //activationAttributes	0
18607818	18606538	How can I make no line space using regex?	private void button1_Click(object sender, EventArgs e)\n    {\n        List<string> rt = new List<string>();\n        foreach (string line in richTextBox1.Lines)\n        {\n            if (!string.IsNullOrEmpty(line.Trim()))\n            {\n                rt.Add(line);\n            }\n            if (line.Trim().EndsWith(";"))\n            {\n                rt.Add("\n");\n            }\n        }\n        richTextBox1.Lines = rt.ToArray();\n        richTextBox1.Refresh();\n    }	0
3890955	3890754	Using HttpWebRequest to POST data/upload image using multipart/form-data	------WebKitFormBoundarySkAQdHysJKel8YBM \nContent-Disposition: form-data;name="key"\n\nKeyValueGoesHere\n------WebKitFormBoundarySkAQdHysJKel8YBM \nContent-Disposition: form-data;name="param2"\n\nValueHere\n------WebKitFormBoundarySkAQdHysJKel8YBM \nContent-Disposition: form-data;name="fileUpload"; filename="y1.jpg"\nContent-Type: image/jpeg \n\n[image data goes here]	0
15691025	15690991	Find number of common elements between two lists or hashsets with millions of elements	// assuming HashSet<T> hashSetA\n//     and an IEnumerable<T> collectionB\nhashSetA.IntersectWith(collectionB);	0
18470730	18469129	MS Word cannot add to reference	Microsoft.Office.*	0
8022892	8022859	Shooting the enemy, how to calculate the next position of the projectile	Vector2 target = objectToShootAt.position();\nVector2 origin = tower.position();\nVector2 direction = target - origin;\n\ndirection.normalize(); // or direction *= 1/direction.length()\ndirection *= speed;	0
623726	623716	How can I pass an event to a function in C#?	public static void Helper(ref EventHandler<EventArgs> e)\n{\n    e+= (x,y) => {};\n}	0
29110465	29108920	How to get boolean value from selectedrow in gridview ASP.NET	CheckBox c = (CheckBox)GridViewSokEvent.SelectedRow.FindControl("CheckBox1");\n            if(c.Checked == true)\n            {\n                 //do something\n            }\n            else if(c.Checked == false)\n            {\n                 //do something \n            }	0
11612672	11611777	How to find the text inside that are not contained inside braces	result = Regex.Split(teststring, "\{[^}]*\}");	0
25855967	25855863	How to create a list of panels already existing in WinForm Application (C#)	public class Form {\n    List<Panel> myPanels = new List<Panel>();\n    public Form() {\n          myPanels.Add(aPnl);\n          myPanels.Add(bPnl);\n          //etc\n    }\n    public TurnOffPanels(){\n        foreach(var panel in myPanels){\n             panel.Enabled = false;\n        }\n    }\n}	0
3625461	3563691	How to programatically log PerformanceCounter	System.Diagnostics.Process.Start()	0
2101929	2101884	Determine if a JavaScript file is already included via a user control	Page.ClientScript.RegisterClientScriptBlock	0
10953040	10952905	Re-Associating an ImageList with it's Keys	il.Images.SetKeyName(i, app.path);	0
9073519	9073469	can a c# lock serialize access to an external resouce?	class MySerialPort\n{\n   static object synchLock = new object();\n\n   public void DoSomething()\n   {\n      lock (synchLock)\n      {\n        // whatever\n      }\n   }\n}	0
9889426	9200141	Change Enter for Tab	GridView.Attributes.Add("onkeydown", "if(event.keyCode==13)return false;");	0
7777393	7777261	set variable in httpmodule read in masterpage & content page, asp.net C#	//Store data in Step1:\nHttpContext.Current.Items.Add("Key", "Value");\n\n//Retrieve data in Step2:\nobject value = HttpContext.Current.Items["Key"];	0
17665542	17665435	How to restart app without Command Line Arguments	Process.Start	0
11938759	11937742	Command Line Control over a network	cmd = new Process();\n        cmd.StartInfo.FileName = "cmd.exe";\n        cmd.StartInfo.CreateNoWindow = true;\n        cmd.StartInfo.UseShellExecute = false;\n        cmd.StartInfo.RedirectStandardOutput = true;\n        cmd.StartInfo.RedirectStandardInput = true;\n        cmd.StartInfo.RedirectStandardError = true;\n        cmd.OutputDataReceived += new\n        DataReceivedEventHandler(CmdOutputDataHandler);\n        cmd.Start();\n        cmd.BeginOutputReadLine();\n\npublic void CmdOutputDataHandler(object sendingProcess,\n    DataReceivedEventArgs cmdout)\n    {                         \n                output.Append(cmdout.Data);\n                writer.WriteLine(output);\n                writer.Flush();                \n\n    }\n\n// Run this in a separate thread to prevent blocking\nwhile (true)\n{\ninput.Append(reader.ReadLine());\ninput.Append("\n");\ncmd.StandardInput.WriteLine(input);\ninput.Remove(0, input.Length);\n}	0
26333683	26333617	How to create dynamic checkboxes on Winform by passing checkbox name in List C#?	private void Form1_Load(object sender, EventArgs e)\n{\n    this.Size = new Size(200, 200);\n    List<string> yourList = new List<string>();\n    yourList.Add("A");\n    yourList.Add("B");\n    yourList.Add("C");\n    yourList.Add("D");\n    yourList.Add("E");\n    yourList.Add("F");\n    CheckBox box;\n    int innitialOffset = 20;\n    int xDistance = 80;\n    int yDistance = 50;\n\n    for (int i = 0; i < yourList.Count; i++)\n    {\n        box = new CheckBox();\n        box.Tag = yourList[i];\n        box.Text = yourList[i].ToString();\n        box.AutoSize = true;\n        box.Location = new Point(innitialOffset + i % 2 * xDistance, innitialOffset + i / 2 * yDistance); \n\n        this.Controls.Add(box);\n    }\n}	0
24510906	24394181	How do I correctly publish my app?	BingoGame\n    Application Files\n        Bingo Game_1_0_0_0\n            *.deploy\n            Bingo.Game.exe.manifest\n        Bingo Game_1_0_0_1\n            *.deploy\n            Bingo.Game.exe.manifest\n    Bingo.Game.Application\n    setup.exe	0
32377784	32377663	how to output shrot number in double datatape ( C#.Net )	double number = 65.536584144;\n       var newNumber = Math.Round(number , 2);	0
848916	848886	How can I return a response from a WCF call and then do more work?	string ProcessOrder(Order order)\n{\n  if(order.IsValid)\n  {\n            //Starts a new thread\n            ThreadPool.QueueUserWorkItem(th =>\n                {\n                    //Process Order here\n\n                });\n\n      return "Great!";\n  }\n}	0
27636388	27561487	How to Find the path of an recently opened/ Currently Active file with a Mouse pointer in it using c#	private string GetMainModuleFilepath(int processId)\n    {\n        string wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;\n        using (var searcher = new ManagementObjectSearcher(wmiQueryString))\n        {\n            using (var results = searcher.Get())\n            {\n                ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();\n                if (mo != null)\n                {\n                    return (string)mo["CommandLine"];\n                }\n            }\n        }\n        Process testProcess = Process.GetProcessById(processId);\n        return null;\n    }	0
4961011	4960831	Entity Framework Insert Many to many creates duplicated data	public static void InserirTipoMetadata( TA_TIPO_METADATA tipoMetadata ) {\n            using ( EnterpriseContext context = new EnterpriseContext() ) {\n                List<TA_REGRA_VALID> regras = new List<TA_REGRA_VALID>();\n                foreach ( var v in tipoMetadata.TA_REGRA_VALID ) {\n                    regras.Add(context.Regra.Single(p => p.CO_SEQ_REGRA == v.CO_SEQ_REGRA));\n                }\n                tipoMetadata.TA_REGRA_VALID = regras;\n                context.TipoMetadata.AddObject(tipoMetadata);\n                context.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);\n            }\n        }	0
2192079	2192014	ObjectDataSource with Composite Lists	var lsStudentWithMarks = context.GetTable<Student>().Where( p => p.M_id.Equals(1))\n                                .Join( context.GetTable<Mark>().Where( p => p.M_StudentId.Equals(1), (o,i) => o.M_Id == i.M_StudentId, (o,i) => new { o.M_StudentName, i.M_Mark } )\n                                .Select( j => new { j.M_StudentName, j.M_Mark } )\n                                .ToList();	0
26613173	26466821	Windows Application Log Events being 'missed' somehow with my EventLog	private void eventLog_Application_EntryWritten(object sender, EntryWrittenEventArgs e)\n{\n    // Process e.Entry    \n}	0
17112343	17111409	How am i able to have a string override one from an inherited class?	public class MyBase\n{\n    public override string ToString()\n    {\n        return "I'm a base class";\n    }\n}\npublic class MyFixedChild : MyBase\n{\n    public override string ToString()\n    {\n        return "I'm the fixed child class";\n    }\n}\npublic class MyFlexiChild : MyBase\n{\n    public new string ToString()\n    {\n        return "I'm the flexi child class";\n    }\n}\n\npublic class MyTestApp\n{\n    public static void main()\n    {\n        MyBase myBase = new MyBase();\n        string a = myBase.ToString();                 // I'm a base class\n\n        MyFixedChild myFixedChild = new MyFixedChild();\n        string b = myFixedChild.ToString();           // I'm the fixed child class\n        string c = ((MyBase)myFixedChild).ToString(); // I'm the fixed child class\n\n        MyFlexiChild myFlexiChild = new MyFlexiChild();\n        string d = myFlexiChild.ToString();           // I'm the flexi child class\n        string e = ((MyBase)myFlexiChild).ToString(); // I'm a base class\n    }\n}	0
12143198	12141416	How do I find out the page type of a PageNode? (Composite C1)	using (var conn = new DataConnection())\n{\n    Guid pageTypeIdInQuestion = Guid.Empty; // put type id here\n\n    var siteMapNav = new SitemapNavigator(conn);\n    var pagesOfDesiredType = conn.Get<IPage>().Where(f => f.PageTypeId == pageTypeIdInQuestion).Select(f => f.Id);\n    var pages = siteMapNav.CurrentHomePageNode.GetPageNodes(SitemapScope.DescendantsAndCurrent).Where(f=> pagesOfDesiredType.Contains(f.Id));\n}	0
18912307	18912106	loading form attributes from file parsing strings to ints c#	string size = streamReader.ReadLine();\nint iSize = 0;\nif (int.TryParse(size, out iSize)) {\n     this.Size = new Size(iSize, iSize);\n} else {\n // error, maybe load default size\n}	0
23240913	23240682	In a C# Web Method is it possible to store data retrieved via Entity Framework for subsequent calls?	[WebMethod(CacheDuration = 180)]\npublic string GetProducts() {	0
13863963	13863871	How use Transaction in EntityFramework 5?	using (gasstationEntities ctx = new gasstationEntities(Resources.CONS))\n{\n   using (var scope = new TransactionScope())\n   {\n      [... your code...]\n\n      scope.Complete();\n   }\n}	0
22546937	22544998	Injecting/resolving object that is almost a singleton	public class ProjectDataService : IProjectDataService\n{\n    private static IProjectModel _projectModel;\n\n    public IProjectModel Create(string fileName)\n    {\n        if (_projectModel == null)\n        {\n            //create it\n        }\n        return _projectModel;\n      }\n }	0
4201496	4200475	How do I marshal a C# string array to a VB6 array?	Dim strArr() As String\nstrArr = test.OneTwoThree	0
8398746	8398635	Gridview WebUserControl access selected row	GridView gView = ContentPlaceHolder1.FindControl("GridView1") as GridView;\n// use gView.SelectedIndex to manipulate the row, edit it, etc	0
18061347	18060559	unable to connect to remote server c# while sending mail	var smptClient = new SmtpClient("smtp.gmail.com", 587)\n {\n     Credentials = new NetworkCredential("isavepluscom@gmail.com", "123456789"),\n     EnableSsl = true\n };\n  smptClient.Send("isavepluscom@gmail.com", "test@gmail.com", "Testing Email", "testing the email");	0
2005685	2005637	How to determine if user account is enabled or disabled	private bool IsActive(DirectoryEntry de)\n{\n  if (de.NativeGuid == null) return false;\n\n  int flags = (int)de.Properties["userAccountControl"].Value;\n\n  return !Convert.ToBoolean(flags & 0x0002);\n}	0
10452992	10452968	Non-generic IEnumerable to string	String.Join(", ", thingy.Cast<object>());	0
8993466	8993442	C# How to access static field of a public struct	public struct AT_CMD\n{\n    public static int x = 7;\n}  \n\nstatic void Main()\n{\n    int y = AT_CMD.x;\n}	0
9775159	9774612	Writing a sub query in LINQ with Top X	from l in links\nwhere\n    (from l2 in links\n     where l2.SiteID == l.SiteID\n     orderby l2.ID\n     select l2.ID).Take(3).Contains(l.ID)\nselect l	0
10704924	10567558	C# Transactionscope - insert/select in same transaction, multiple connections	SqlCommand command = new SqlCommand(...);\nSqlDataReader reader = command.ExecuteReader();\nif (reader.read()) {\n  return buildMyObject(reader);\n}\n\nprivate MyObject buildMyObject(SqlDataReader reader) {\n  MyObject o1 = new MyObject();\n  // set fields on my object from reader\n\n  // broken! i was attempting create a new sql connection here and attempt to use a reader\n  // but the reader is already in use.\n  return o1;\n}	0
6923753	6919608	ObservableCollection and displaying its data question, Windows Phone 7	void Main()\n{\n   var page1 = new Page1();\n   var page2 = new Page2();\n\n   foreach (var txt in ImageList.Instance)\n   {\n        Console.WriteLine (txt);\n        // prints:\n        // Instance created\n        // page1\n        // page2\n   }\n}\n\npublic class ImageList : ObservableCollection<string>\n{\n    private static ImageList _instance;\n    public static ImageList Instance \n    { \n        get\n        {\n            if(_instance==null)\n            {\n                _instance = new ImageList();\n                _instance.Add("Instance created");      \n            }\n            return _instance;\n        }\n    }\n\n    private ImageList() \n    {\n    }\n}\n\npublic class Page1\n{\n    public Page1()\n    {\n        ImageList.Instance.Add("page1");\n    }\n}\n\npublic class Page2\n{\n    public Page2()\n    {\n        ImageList.Instance.Add("page2");\n    }\n}	0
15457352	15457060	How to pass values from webgrid using javascript to another action page?	Html.ActionLink(article.Title, \n                "Item",   // <-- ActionMethod\n                "Login",  // <-- Controller Name.\n                new { ItemID = Model.ItemID }, // <-- Route arguments.\n                null  // <-- htmlArguments .. which are none. You need this value\n                      //     otherwise you call the WRONG method ...\n                )	0
28033518	28032500	Controls within grid column don't respect size of column	MinWidth="0"	0
21913738	21911648	How to handle ParseErrors in Html Agility Pack	document.OptionFixNestedTags = true;	0
8519989	8519931	Programming Context Menu	public Loader()\n{\n    var menu = new ContextMenuStrip();\n    var menuItem = menu.Items.Add("Set Complete");\n    menuItem.Click += OnMenuItemSetCompleteClick;\n    menuItem = menu.Items.Add("Set Review");\n    menuItem.Click += OnMenuItemSetReviewClick;\n    menuItem = menu.Items.Add("Set Missing");\n    menuItem.Click += OnMenuItemSetMissingClick;\n}\n\nprivate void OnMenuItemSetCompleteClick(object sender, EventArgs e)\n{\n    // Do something\n}\n\nprivate void OnMenuItemSetReviewClick(object sender, EventArgs e)\n{\n    // Do something\n}\n\nprivate void OnMenuItemSetMissingClick(object sender, EventArgs e)\n{\n    // Do something\n}	0
17070806	17070756	How can I select a number and value from an enum in C#?	var contentTypes =\n    from value in Enum.GetValues(typeof(ContentTypes)).Cast<int>()\n    select new\n    {\n        id = value,\n        name = Enum.GetName(typeof(ContentTypes), value)\n    };	0
7057552	7057537	how to catch changes in a member variable? (C#)	private bool _isCommitted;\n\npublic bool IsCommitted\n{\n  get { return _isCommitted; }\n  set\n  {\n     if(value)\n     {\n        //do something\n     }\n\n     _isCommitted = value;\n  }\n}	0
4507500	4507466	How to run one NUnit test under a user with certain privileges	runas.exe /user:DOMAIN\someUser "nunit-console.exe somelibrary.dll"	0
12303374	12303072	HttpWebResponse -> How Find A Link With Specific id and class and title?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(somehtmlstring);\n\nstring value = doc.DocumentNode.Descendants("a")\n    .First(n => n.Attributes["class"].Value == "someclass")\n    .Attributes["href"]\n    .Value;	0
22104144	22103981	How do i access and create txt files in the same directory as the program in c#	string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);	0
9655428	9655376	Write Contents in a Txt file in a tabular order using C#	string.Format("{0:D15}{1:D20}", rowColumn1, rowColumn2);	0
27243864	27189704	Unexpected behavior of DataGrid	ParentGroups = new ObservableCollection<Group>(db.Groups.OrderBy(x => x.GroupName));	0
3374111	3374069	Getting insert query from a grid	Dim tblRanked AS System.Data.DataTable = ViewState("tblRanked")\n\nFor Each row As DataRow In tblRanked.Rows\n   db.ExecuteNonQuery("usp_AddRankingForUser", loginId, row("RequestID"), count)\n   'updates the depthead field for later use\nNext	0
13898606	13898566	Property is getting set to null after I set it to something?	private List<SelectionBox> _boxes;\npublic List<SelectionBox> Boxes { get { return _boxes; } set { _boxes = value; } }	0
11274102	11274013	How to change some text in a file by StreamWriter	string[] lines = File.ReadAllLines(path1);\n\nfor(int i = 0; i < lines.Length; i++)\n{\n  if(lines[i] == "25") lines[i] = "27";\n}\n\nFile.WriteAllLines(path1, lines);	0
21731909	21711182	How to clear ObjectStateManager	private static int __lastProcessedIndex = 0;\nprivate static DbContext _oldContext = null;\n\npublic void DoYourMagic(DbContext context)\n{\n    if (ReferenceEquals(context, _oldContext) == false)\n    {\n        _oldContext = context;\n        _lastProcessedIndex = 0;\n    }\n\n    var objectContext = (context as IObjectContextAdapter).ObjectContext;\n    var unchanged = objectContext.ObjectStateManager.GetObjectSateEntires(EntityState.Unchanged).ToArray();\n\n    for (int i = _lastProcessedIndex; i < unchanged.Length; i++)\n    {\n        //do your magic with unchanged entities...\n    }\n\n    context.SaveChanges();\n\n    //Now all entries in objectstatemanager are in state Unchanged\n    //I am setting the index to the Count() - 1\n    //So that my next call of the method "DoYourMagic" starts the for with this index\n    //This will than ignore all the previously attached ones\n    _lastProcessedIndex = objectContext.ObjectStateManager.GetObjectSateEntires(EntityState.Unchanged).Count();\n}	0
6270336	6270287	How to read from two COM ports?	using System.IO.Ports;\n\n...\n\nSerialPort port1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);\nSerialPort port2 = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);\n\nport1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);\nport2.DataReceived += new SerialDataReceivedEventHandler(port2_DataReceived);\nport1.Open();\nport2.Open();\n\n...\n\nprivate void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n    // Show all the incoming data in the port's buffer\n    Console.WriteLine(port1.ReadExisting());\n}\nprivate void port2_DataReceived(object sender, SerialDataReceivedEventArgs e)\n{\n    // Show all the incoming data in the port's buffer\n    Console.WriteLine(port2.ReadExisting());\n}	0
18098126	18097970	WPF C# - Live countdown visible in string	DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();\ndispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);\ndispatcherTimer.Interval = new TimeSpan(0,0,1);\ndispatcherTimer.Start();\n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n    // Update myCountdownLabel here\n    dispatcherTimer.Interval = new TimeSpan(0,0,10); // Set next time interval\n}	0
3987782	3981518	LIKE with Linq to Entities	var matching = Context.Users.Where("it.Name LIKE 'rodrigo%otavio%diniz%waltenberg'");	0
26560113	26009275	WrapPanel with last-in-row fill	private void ArrangeLine(double y, Size lineSize, double boundsWidth, int start, int end)\n{\n    double x = 0;\n    UIElementCollection children = InternalChildren;\n    for (int i = start; i < end; i++)\n    {\n        UIElement child = children[i];\n        var w = child.DesiredSize.Width;\n        if (LastChildFill && i == end - 1) // last ??hild fills remaining space\n        {\n            w = boundsWidth - x;\n        }\n        child.Arrange(new Rect(x, y, w, lineSize.Height));\n        x += w;\n    }\n}	0
8929040	8928926	csv reading into datatable makes one row a column name	string connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Text;HDR=No", System.IO.Path.GetDirectoryName(openFileDialog1.FileName));	0
8940277	8940224	Perform a event certain so many times every so many seconds	While (true)\n{\nfor (int i=0; i<5; i++)\n{\n console ("Hello");\n}\n//this will pause for 1 sec (1000msec)\nThread.sleep(1000);\n}	0
22725181	22724904	Sane View / Controller approach for multiple route action	return View("SharedViewName", yourNotes);	0
10306512	10306437	Linq-to-SQL concatenate two columns in where clause	var selected = dc.Where(x => x.prefix + x.value == "ABC1234");	0
19229963	19229860	Splitting a single string into an array	string[] s = filename.Split('\');	0
26672706	26670415	Entity framework multiple composite keys, cascade on delete	modelBuilder.Entity<Table3>().HasKey(m => new {m.Id, m.Table2Id, m.Table1Id});	0
22237157	22236918	Move from a controller to different views	public ActionResult Test()\n{\n    return PartialView("index.cshtml");\n}	0
9020297	9020159	While attempting to traverse relationships, my entity framework table objects are null	var users = entity.Users.include("Groups").where(x => x.UserID == 20);	0
29851766	29851625	separate a particular chunk of line through file handling	var str = @"col1 col2 col3\n21312 51245 1235\n21311 12 6235";\n\nstring[] rows = str.Split('\n')\n                   .Select(r => r.Split(' ')[2])\n                   .Skip(1)\n                   .ToArray();	0
23036454	23036352	DropDownList - Get custom property of selected Item	//repopulate the List<RoleIdSelection>\nList<RoleIdSelection> roles = GetTheRoles();\n\nRoleIdSelection role = roles.First(r => r.RoleID==ddlUserProfile.SelectedItem.Value);	0
4975274	4975256	Checking the result of running process with C#	Process.ExitCode	0
12845342	12845105	Disposing a member TcpClient properly	"Can I release them correctly any earlier"	0
11164778	9823489	EWS - how do I find all incomplete tasks?	//Create the extended property definition.\nExtendedPropertyDefinition taskCompleteProp = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Task, 0x0000811C, MapiPropertyType.Boolean);\n//Create the search filter.\nSearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(taskCompleteProp, false);                    \n//Get the tasks.\nFindItemsResults<Item> tasks = service.FindItems(WellKnownFolderName.Tasks, filter, new ItemView(50));	0
10649600	10649439	LINQ: Sort a list depending on parameter	return result.OrderBy(x => x.GetType().GetProperty(SortProperty).GetValue(x, null));	0
9661133	9243433	How to render a Razor View to a string in ASP.NET MVC 3?	string template = "Hello @Model.Name! Welcome to Razor!";\nstring result = Razor.Parse(template, new { Name = "World" });	0
17088383	17088353	RGB/Hexdecimal color to Decimal Value	Dim decValue as String = Convert.ToInt32("FFFFFF", 16)	0
3932897	3932821	How to implement conditional encapsulation in C#	interface IUsableByPassenger\n{\n    MeterReading MeterReading\n    {\n        get; set;\n    }\n}\n\ninterface IUsableByDriver\n{\n    Mileage Mileage\n    {\n        get; set;\n    }\n}\n\ninterface IUsableByMechanic : IUsableByDriver\n{\n    Engine Engine\n    {\n        get; set;\n    }\n}\n\nclass Car : IUsableByMechanic, IUsableByPassenger\n{\n    Mileage IUsableByDriver.Mileage\n    {\n        // implement mileage access\n    }\n\n    Engine IUsableByMechanic.Engine\n    {\n        // implement engine access\n    }\n\n    MeterReading IUsableByPassenger.MeterReading\n    {\n        // implement engine access\n    }\n}\n\nclass Mechanic\n{\n    public Mechanic(IUsableByMechanic usable)\n    {\n        // usable.MeterReading is not here\n    }\n}	0
16768880	16756068	WebClient freezes when async-downloading a second file if I'm getting the original filename from Content-Disposition	private void Download(string url, string downloadDirectory)\n{\n    WebClient wc = new WebClient();\n\n    wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);\n    wc.DownloadFileCompleted += new AsyncCompletedEventHandler((sender, e) => DownloadComplete(sender, e, wc));\n\n    wc.DownloadFileAsync(new Uri(url), downloadDirectory + "temp");\n}\n\nprivate void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)\n{\n    downloadProgressBar.Value = e.ProgressPercentage;\n}\n\nprivate void DownloadComplete(object sender, AsyncCompletedEventArgs e, WebClient wc)\n{\n    string filename = new ContentDisposition(wc.ResponseHeaders["Content-Disposition"].ToString()).FileName;\n    if (File.Exists(downloadDirectory + "temp"))\n    {\n        if (File.Exists(downloadDirectory + filename))\n            File.Delete(downloadDirectory + filename);\n        File.Move(downloadDirectory + "temp", downloadDirectory + filename);\n    }\n\n    // ...\n}	0
28019660	28015366	c# send key strokes to directx application	[Flags]\npublic enum KeyFlag\n{       \n    KeyDown = 0x0000,\n    ExtendedKey = 0x0001,\n    KeyUp = 0x0002,\n    UniCode = 0x0004,\n    ScanCode = 0x0008\n}	0
17121564	17066581	PInvoke Nikon c++ DLL Function from c#	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] \npublic struct struktur\n{\n    public uint ulSize;          // size of the NkflLibraryParam structure\n    public uint ulVersion;       // version number of the interface specification\n    public uint ulVMMMemorySize; // upper limit of the physical memory that can be used\n    public IntPtr pNkflPtr;      // pointer to the StratoManager object\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)]\n    public byte[] VMFileInfo;      // swap file information\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)]\n    public byte[] DefProfPath; // <- this one is not included in the doc of NIKON (I still don't now what this should hold but it works if it's empty...)\n}	0
33090444	33090415	Using GetCurrentDirectory as a path to save/create a file	System.IO.Path.Combine(Directory.GetCurrentDirectory(), "example.txt");	0
15076222	15076176	How to call a particular explicitly declared interface method in C#	static void Main()\n    {\n        Model m = new Model();\n\n        // Set to IA\n        IA asIA = m;\n        asIA.Display();\n\n        // Or use cast inline\n        ((IB)m).Display();\n\n        Console.ReadLine();\n    }	0
14191490	14191406	Use angular brackets in label	Protected Overrides Sub OnLoad(ByVal e As EventArgs)\n    MyBase.OnLoad(e)\n    Label1.Text = HttpUtility.HtmlEncode("send email to <name@gmail.com> me")\nEnd Sub	0
8486140	8485805	Get local drives without hitting floppy	ConnectionOptions opts = new ConnectionOptions();\nManagementScope scope = new ManagementScope(@"\\.\root\cimv2", opts);\nSelectQuery diskQuery = new SelectQuery("SELECT * FROM Win32_LogicalDisk WHERE (MediaType != 0 AND MediaType = 11 OR MediaType = 12)");\n\nManagementObjectSearcher searcher = new ManagementObjectSearcher(diskQuery);\nManagementObjectCollection diskObjColl = searcher.Get();	0
15632111	15632036	How Can Convert DataRow to DataRowView in c#	DataTable dt=ds.Tables[0];\nDataRow dr= dt.NewRow();         \nDataRowView drv= dt.DefaultView[dt.Rows.IndexOf(dr)];	0
14514717	14514696	Generic methods with constraints that are generic	void DoMethod<TEvent, TArgs>() where TEvent : IEvent<TArgs> where TArgs : EventArgs {}	0
22341724	22341620	How to update Xml contents in a database?	using (SqlConnection con = new SqlConnection("your connection string")) {\n  string sql = "UPDATE table1 Set field1 = '" + xdoc.OuterXml + "'";\n  SqlCommand com = new SqlCommand(sql, con);\n  con.Open();\n  com.ExecuteNonQuery();\n  con.Close();\n}	0
33357164	33356964	C# Linq Join Lambda (a key selector contains the other key selector)	var query =\n    context\n        .Table1\n        .SelectMany(table1 =>\n            context\n                .Table2\n                .Where(table2 => table1.strStringContainsIntegers.Contains(table2.intInteger.ToString()))\n                .Select(\n                    table2 => new {table1.SomeField, table2.SomeField}));	0
1713371	1713288	C#: passing array of strings to a C++ DLL	[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)]\nstatic extern void printnames(String[] astr, int size);\n\nList<string> names = new List<string>();\nnames.Add("first");\nnames.Add("second");\nnames.Add("third");\n\nprintnames(names.ToArray(), names.Count);	0
12276889	12276764	ClientSideEvents on ASP:Net repeater control	protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)\n    {\n        if(e.Item.ItemType == ListItemType.Item)\n        {\n            TextBox mytxt = e.Item.FindControl("txtWeekly") as TextBox;\n            // you can just pass "this" instead of "mytxt.ClientID" and get the ID from the DOM element\n            mytxt.Attributes.Add("onchange", "doStuff('" + mytxt.ClientID + "');");\n        }\n    }	0
16267702	16267628	Require some help deciphering a regular expression	[a-z]+       = Match any character from a to z, 1 or more times\n\(           = Match "(" literally\n[^()]+       = Match anything that's NOT "(" or ")", 1 or more times\n\)           = Match ")" literally	0
31112207	31111668	How to keep checking if a user presses esc while Reading lines?	int number = 0;\n        do\n        {\n            while (!Console.KeyAvailable)\n            {\n                string a = Console.ReadLine();\n                bool bWriteNumber = false;\n                try\n                {\n                    number = int.Parse(a);\n                    bWriteNumber = true;\n                }\n                catch\n                {\n                    Console.WriteLine("Sorry! I only accept int");\n                }\n                finally\n                {\n                    if (bWriteNumber)\n                        Console.WriteLine(number);\n                }\n            }\n        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);	0
18272045	18222563	how to reattach the IQueryable object to a new instance of Context object	Func<entityContex, IQueryable</*Table1 type*/>> queryExecutor = null;\n\nprivate void SearchMethod()\n{\n   using(var ctx = new entityContex())\n   {\n      queryExecutor = c => c.Table1.Where(t=> t.Name.StartWith(txtName.Text)).Take(100);\n\n      var qry = queryExecutor(ctx);\n\n      dgvResult.DataSource = qry.ToList();\n   }\n}\n\nprivate void RefreshResult()\n{\n   using(var ctx = new entityContex())\n   {\n      if(queryExecutor != null)\n      dgvResult.DataSource = queryExecutor(ctx).ToList();\n   }\n}	0
11342813	11342195	C# save/retrieve an array of structures from settings file	Example:\n    Properties.Settings.Default.Example.Add("Setting1", new CameraSyncSettings());\n    Properties.Settings.Default.Example.Add("Setting2", new CameraSyncSettings());\n    Properties.Settings.Default.Example.Add("Setting3", new CameraSyncSettings());\n\n    Properties.Settings.Default.Save();	0
13931244	13931180	ASP.Net :Error while uploading a file to remote location from localhost?	FileUpload.SaveAs	0
4408894	4408727	How to split  E-mail address from a text?	private void Match()\n{\n        Regex validationExpression = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");  \n        string text = "whatever@gmail;a@hotmail.com,gmail@sync,b@hotmail.com,c@hotmail.com,what,dhinesh@c";  \n        MatchCollection matchCollection = validationExpression.Matches(text);  \n        foreach (var matchedEmailAddress in matchCollection)  \n        {  \n            Console.WriteLine(matchedEmailAddress.ToString());  \n        }  \n        Console.ReadLine();  \n}	0
13304903	13303809	reading executable until next MZ	UInt32 startAddress = IMAGE_DOS_HEADER.e_lfanew + 4 + Marshal.SizeOf(typeof(IMAGE_FILE_HEADER)) + [IMAGE_FILE_HEADER][6].SizeOfOptionalHeader \n\nfor(UInt32 loop = 0;loop < sectionHeadersCount;loop++)\n{\n    IMAGE_SECTION_HEADER section = /*Map offset to IMAGE_SECTION_HEADER structure Method*/(startAddress);\n    startAddress += Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER));//Offset to next section\n}\n\n// Example of Mapping function:\npublic T PtrToStructure<T>(UInt32 offset) where T : struct\n{\n    Byte[] bytes = this.ReadBytes(offset, (UInt32)Marshal.SizeOf(typeof(T)));\n\n    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);\n    try\n    {\n         T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n         return result;\n    } finally\n    {\n         handle.Free();\n    }\n}	0
17822573	17822388	How to map multiple fields to the same field?	var items = new Item[]\n{\n   new Item { ID = order.ID, Value = order.RXEAmount },\n   new Item { ID = order.ID, Value = order.RXOAmount }\n}	0
23831939	23814547	Control display of streamed PDF in browser	Content-Disposition: attachment; filename="example.pdf"	0
4803419	756031	Using the Web Application version number from an assembly (ASP.NET/C#)	private const string AspNetNamespace = "ASP";\n\n    private static Assembly getApplicationAssembly()\n    {\n        // Try the EntryAssembly, this doesn't work for ASP.NET classic pipeline (untested on integrated)\n        Assembly ass = Assembly.GetEntryAssembly();\n\n        // Look for web application assembly\n        HttpContext ctx = HttpContext.Current;\n        if (ctx != null)\n            ass = getWebApplicationAssembly(ctx);\n\n        // Fallback to executing assembly\n        return ass ?? (Assembly.GetExecutingAssembly());\n    }\n\n    private static Assembly getWebApplicationAssembly(HttpContext context)\n    {\n        Guard.AgainstNullArgument(context);\n\n        object app = context.ApplicationInstance;\n        if (app == null) return null;\n\n        Type type = app.GetType();\n        while (type != null && type != typeof(object) && type.Namespace == AspNetNamespace)\n            type = type.BaseType;\n\n        return type.Assembly;\n    }	0
22523228	22523122	How do I make timer wait until done?	// code change starts\nprivate bool _isGridRefreshing\n{\n   get\n   {\n      var flag = HttpContext.Current.Session["IsGridSession"];\n      if(flag != null)\n      {\n         return (bool)flag;\n      }\n\n      return false;\n   }\n   set\n   {\n      HttpContext.Current.Session["IsGridSession"] = value;\n   }\n}\n// code change ends\n\nprotected void Timer1_Tick(object sender, EventArgs e)\n{\n   if(_isGridRefreshing == false)\n   {\n       RefreshGrid();\n   }\n}\n\nprivate void RefreshGrid()\n{\n   _isGridRefreshing = true;\n\n   //code to refresh the grid.\n}	0
24427424	24427101	Iterate objects in assemblies that implements generic interface	var assembly = Assembly.GetExecutingAssembly(); //or whatever else\n\n        var types =\n            from t in assembly.GetTypes()\n            from i in t.GetInterfaces()\n            where i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IFoo<,>))\n            select new \n            {\n                Type = t,\n                Args = i.GetGenericArguments().ToList()\n            };\n\n        foreach (var item in types)\n        {\n            Console.WriteLine("Class {0} implements with {1}, {2}", item.Type.Name, item.Args[0].Name, item.Args[1].Name);\n        }	0
31841274	31838939	Linq Expression: Using Case Min Max from SQL in a Linq Expression	var sql = (from CLD in db.CLD\n           join AnswerComment in db.AnswerComment on CLD.Id equals AnswerComment.IdCLD\n           join ListDef in db.ListDef on CLD.IdListDef equals ListDef.Id\n           where ListDef.IdInspection == idInspec\n           group new { CLD, AnswerComment } by new ComentRespostaLFDModels\n           {\n               IdComment = CLD.Id,\n               Comment = CLD.Comments\n           } into coments\n           select new ComentRespostaLFDModels\n           {\n               IdComment = coments.Key.IdComment,\n               Comment = coments.Key.Comment,\n               StatusDifference = comments.Min(c=>c.AnswerComment.IdStatus) != comments.Max(c=>c.AnswerComment.IdStatus) ? 1 : 0\n           }).ToList();	0
2810483	2810465	Convert string value back to GUID value	try\n{\n  Guid guid = new Guid("{D843D80B-F77D-4655-8A3E-684CC35B26CB}");\n}\ncatch (Exception ex) // There might be a more appropriate exception to catch\n{\n  // Do something here in case the parsing fails.\n}	0
8706093	8705861	Decimal stores precision from parsed string in C#? What are the implications?	[Serializable]\npublic class Foo\n{\n    public decimal Value;\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        decimal d1 = decimal.Parse("1.0000");\n        decimal d2 = decimal.Parse("1.00");\n\n        Debug.Assert(d1 ==d2);\n\n        var foo1 = new Foo() {Value = d1};\n        var foo2 = new Foo() {Value = d2};\n\n        IFormatter formatter = new BinaryFormatter();\n        Stream stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None);\n        formatter.Serialize(stream, d1);\n        stream.Close();\n\n        formatter = new BinaryFormatter();\n        stream = new FileStream("data.bin", FileMode.Open, FileAccess.Read, FileShare.Read);\n        decimal deserializedD1 = (decimal)formatter.Deserialize(stream);\n        stream.Close();\n\n        Debug.Assert(d1 == deserializedD1);\n\n        Console.WriteLine(d1); //1.0000\n        Console.WriteLine(d2); //1.00\n        Console.WriteLine(deserializedD1); //1.0000\n\n        Console.Read();\n    }\n}	0
7519352	7507389	IIS delays a lot between each response with async requests	[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]\npublic class BaseController : Controller{}	0
1258192	1258162	Linq: How to group by maximum number of items	var result =\n        from i in array.Select((value, index) => new { Value = value, Index = index })\n        group i.Value by i.Index / chunkSize into g\n        select g;	0
4696778	4696753	A LINQ Challenge	var result = input.GroupBy(e => e.Name)\n                  .Select(gr => new { Name = gr.Key,\n                                      All = gr.All(e => e.Process) });	0
28558454	28558137	Linq How to compute row count?	from table in Mapping.GetTables()\nfrom member in table.RowType.DataMembers\nwhere member.Type == typeof(string)\nlet count = ExecuteQuery<int>(String.Format(\n                "SELECT COUNT(DISTINCT {0}) FROM {1}",\n                member.Name,\n                table.TableName)).FirstOrDefault()\nselect new { table.TableName, member.Name, count }	0
22682814	22682446	List Picker selected value and listbox selected value in Windows Phone	void client_live_permissionCompleted(object sender, ServiceReference1.live_permissionCompletedEventArgs e)\n        {\n          //var selectedItem = listBox or listicker.SelectedItem as yourType\n            LIST data = YourListBox.SelectedItem as LIST;\n            long id = data.Id;\n            string name = data.Name;\n        }	0
11945256	11945201	How to get content type of a web address?	var request = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;\n    if (request != null)\n    {\n        var response = request.GetResponse() as HttpWebResponse;\n\n        string contentType = "";\n\n        if (response != null)\n            contentType = response.ContentType;\n    }	0
5703179	5700578	How to select a date interval in IQueryable<>?	if (tb_DateFrom.Text != "") {\n    journeys = from j in journeys\n               where j.DateTo.CompareTo(tb_DateFrom.Text) >= 0\n               select j;\n}\n\nif (tb_DateTo.Text != "") {\n    journeys = from j in journeys\n               where j.DateFrom.CompareTo(tb_DateTo.Text) <= 0\n               select j;\n}	0
1198306	1198296	Creating a generic method to cache an entity	public object Clone()\n {\n     DataContractSerializer serializer = new DataContractSerializer(this.GetType());\n     using (MemoryStream memStream = new MemoryStream())\n     {\n         serializer.WriteObject(memStream, this);\n         memStream.Position = 0;\n         return serializer.ReadObject(memStream);\n     }\n  }	0
24741783	24741271	How to convert a string c# equation to an answer	MathParser.SetExpression("sin(3)+cos(3)");\ndouble value = MathParser.getValueAsDouble();	0
7817596	7817552	Storing Controls in a variable	public List<Control> MyControls;	0
2043369	2043334	How to force all dlls to add to Current Domain?	Type temp = typeof(ClassInAssemblyA);\ntemp = typeof(ClassInAssemblyB);\ntemp = typeof(ClassInAssemblyC);	0
8349099	8348954	How do I run multiple events in a specific order?	private void myslider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n        {\n           HandleValueSliderChanged();\n        }\n        private void HandleValueSliderChanged() {\n          //Code here\n        }\n\n        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)\n        {\n          //Code here\n           HandleValueSliderChanged();\n        }	0
8327542	8327472	Repository Pattern For Accessing Text File	public IEnumerable<Payment> Find(Expression<Func<Payment, bool>> where)\n{\n    this.reader = new StreamReader(this.paymentFile.FullName);\n    this.payments = new List<Payment>();\n\n    while (!reader.EndOfStream)\n    {\n        string line = reader.ReadLine();\n        Payment payment = new Payment()\n        {\n            AccountNo = line.Substring(0, 11),\n            Amount = double.Parse(line.Substring(11, 10))\n        };\n        if (where(payment) \n        {\n           this.payments.Add(payment);\n        }\n    }\n\n    return this.payments;\n}	0
4477291	4477271	Copy Matrix Value to a New Matrix Efficiently	double[,] result = (double[,])aMatrix.Clone();	0
3628903	3628881	Make A Date Null	Dim _dtSWO As Nullable(Of Date)\n\n    If String.IsNullOrEmpty(_swoDate) Then\n        _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)\n    Else\n        _dtSWO = Nothing\n    End If	0
11492051	11490588	Error when binding a DataGridView to a BindingNavigator	// uxDGVtable.DataSource = ds.Tables["rawTable"];\nuxDGVtable.DataSource = this.rawtableBindingSource;	0
16753196	16753090	Add column into datagridview taken from database	dg.Columns("Tel").Visible = checkBox_Tel.Checked	0
19707847	18821393	How to read sitemap url text from robots.txt file	string contentsOfRobotsTxtFile = new WebClient().DownloadString("uri");\nRobots robots = Robots.Load(content);\nvar sitemaps = robots.Sitemaps;	0
17306915	17306805	Locate nodes in XML file	foreach(XmlNode node in xmlDoc.GetElementsByTagName("RecordFilingRequest")[0].GetElementsByTagName("nc:DocumentIdentification"))\n{\n    int ID = Convert.ToInt32(node.FirstChild().InnerText);\n}	0
14962955	14962365	How do I use a storyboard for more than 1 target object?	var animationA = new DoubleAnimation(...);\nStoryboard.SetTarget(animationA, ButtonA);\nStoryboard.SetTargetProperty(animationA, new PropertyPath(UIElement.OpacityProperty));\n\nvar animationB = new DoubleAnimation(...);\nStoryboard.SetTarget(animationB, ButtonB);\nStoryboard.SetTargetProperty(animationB, new PropertyPath(UIElement.OpacityProperty));\n\nvar storyboard = new Storyboard();\nstoryboard.Children.Add(animationA);\nstoryboard.Children.Add(animationB);\nstoryboard.Begin();	0
24032597	23904809	How to Detect if Grid Control vertical scroll bar is visible or Hidden. Dev express	private GridViewInfo GetViewInfo(GridView view)\n    {\n        FieldInfo fi;\n\n        fi = typeof(GridView).GetField("fViewInfo", BindingFlags.NonPublic | BindingFlags.Instance);\n\n        GridViewInfo griInfo = fi.GetValue(view) as GridViewInfo;\n        if (griInfo != null)\n         {\n          // check if scrollbar\n          if (griInfo.VScrollBarPresence == ScrollBarPresence.Visible)\n          {\n              Console.WriteLine("Scrollbar visible");\n          }\n          else\n          {\n              Console.WriteLine("Scrollbar not visible");\n          }\n        }\n        return griInfo;\n    }	0
25367559	25367197	C# - How to create progress bars dynamically	//Create a new progressbar each time you start an upload in code\nvar progressbar = new ProgressBar()\n\n//add it to the form\nuploadForm.Controls.Add(progressbar );	0
7813224	7472202	Change cursor in Windows Store Apps	Window.Current.CoreWindow.PointerCursor = \n    new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Hand, 1);	0
3023100	3022978	Delphi - Is there any equivalent to C# lock?	type\n  TSomeClass = class\n  private\n    FLock : TCriticalSection;\n  public\n    constructor Create();\n    destructor Destroy; override;\n\n    procedure SomeMethod;\n  end;\n\nconstructor TSomeClass.Create;\nbegin\n  FLock := TCriticalSection.Create;\nend;\n\ndestructor TSomeClass.Destroy;\nbegin\n  FreeAndNil(FLock);\nend;\n\nprocedure TSomeClass.SomeMethod;\nbegin\n  FLock.Acquire;\n  try\n    //...do something with mySharedObj\n  finally\n    FLock.Release;\n  end;\nend;	0
2791297	2791208	find string in DataGridView	var table = new HashSet<string>();\n\ntable.Add("aa");\ntable.Add("bb");\ntable.Add("aa");\n\ndataGridView1.AutoGenerateColumns = true;\ndataGridView1.DataSource = table.ToList();	0
6178021	6177916	How to read shared file from Ubuntu/Samba using C#?	String errorLogFile = @"\\198.168.0.2\sharedfolder\" + finaldate + ".wmv";	0
12897986	12897921	c# Regex Match Search String Plus Next Word	\b\w*foobar foo\w*\s+\w+\b	0
13715854	13715763	combine 2 listboxes into a new listbox c#	listBox3.Items.Clear();\nlistBox3.Items.AddRange(listAll().ToArray());	0
24090615	24090594	DateTime difference from current date to figure out a past date	var myDate = DateTime.UtcNow;\nvar newDate = myDate.AddYears(-5);	0
22614629	22614561	How do I get GMT in this format +0100?	"{0}{1:00}{2:00}"	0
22050229	21970236	EF 6 Code First Stored Procedure - Read Only	public virtual List<Jobs> uspGetJobs(string startDate)\n {\n    var startDateParameter = startDate != null ?\n                             new SqlParameter("startDate", startDate) :\n                             new SqlParameter("startDate", typeof(string));\n\n    return this.Database.SqlQuery<PlannedJobs>("uspGetPlannedJobs @startDate, @locationCode", startDateParameter, locationCodeParameter).ToList();\n }	0
284129	284090	How to get a ReadOnlyCollection<T> of the Keys in a Dictionary<T, S>	var dictionary = ...;\nvar readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)\n);	0
29810747	29810219	Loading a specific image using the name of a variable handed to a function	var imageToShow = Properties.Resources.ResourceManager.GetObject(teamName);	0
30829606	30829563	c# Windows Phone cannot find json file	var filename = "Assets/BazaDanych.json";\nvar sFile = await StorageFile.GetFileFromPathAsync(filename);\nvar fileStream = await sFile.OpenStreamForReadAsync();	0
1256538	1256471	Can you bind separate date and time fields to a single DateTime in C#?	public DateTime GetDateTime(){\n    return new DateTime(DateControl.Year,DateControl.Month,DateControl.Day,TimeControl.Hour,TimeControl.Minute);\n}	0
18344299	18344248	How to tell if object is an enum?	Type.IsEnum	0
20046812	20046563	LINQ: Order By Count of most common value	var newList = List.GroupBy(x=>x.ImdbId)\n                  .OrderByDescending(g=>g.Count())\n                  .SelectMany(g=>g).ToList();	0
7348441	7348404	Expression beeing assigned must be constant - it is	private readonly static int MaxTextLength = "Text i want to use".Length;	0
8710011	8709799	Convert string to proper URI format?	string url = "http://mywebsite.com/validate_email/3DE4ED727750215D957F8A1E4B117C38E7250C33/myemail@yahoo.com";\nint index = url.LastIndexOf("/");\n\nstring queryString = url.Substring(index + 1, url.Length - (index + 1));\nurl = url.Substring(0, index) + "/" + HttpUtility.UrlEncode(queryString);\n\n// url is now\n// http://mywebsite.com/validate_email/3DE4ED727750215D957F8A1E4B117C38E7250C33/myemail%40yahoo.com	0
26815410	26814668	Bind property of root to value of child element in XAML	public MyTestControl()\n{\n   InitializeComponent();\n   Binding b = new Binding("Text");\n   b.Source = MyTextBox;\n   SetBinding(TextProperty, b);\n}	0
939455	939400	Simple formula for determining date using week of month?	static DateTime GetDate(int year, int month, DayOfWeek dayOfWeek,\n        int weekOfMonth) {\n    // TODO: some range checking (>0, for example)\n    DateTime day = new DateTime(year, month, 1);\n    while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1);\n    if (weekOfMonth > 0) {\n        return day.AddDays(7 * (weekOfMonth - 1));\n    } else { // treat as last\n        DateTime last = day;\n        while ((day = day.AddDays(7)).Month == last.Month) {\n            last = day;\n        }\n        return last;\n    }\n}	0
6813319	6813306	C# Console App Not Calling Finally Block	Thread.Sleep	0
26420142	26420101	How to use (.) instead of (,) as the grouping separator when displaying a number with String.Format?	ToString(new CultureInfo("nl-NL"))	0
27014410	27014310	How to find a control from tooltip	var c = this.Controls.OfType<Control>().Where(p => toolTipHCP.GetToolTip(p) == "toolTipText");	0
22072528	22067462	How to get linux distribution info in mono?	DISTRIB_ID=Ubuntu\nDISTRIB_RELEASE=12.04\nDISTRIB_CODENAME=precise\nDISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"	0
1008812	1008810	Write a file "on-the-fly" to the client with C#	protected void streamToResponse()\n{\n    Response.Clear();\n    Response.AddHeader("content-disposition", "attachment; filename=testfile.csv");\n    Response.AddHeader("content-type", "text/csv");\n\n    using(StreamWriter writer = new StreamWriter(Response.OutputStream))\n    {\n        writer.WriteLine("col1,col2,col3");\n        writer.WriteLine("1,2,3");\n    }\n    Response.End();\n}	0
15145990	15101072	How to remove a comma from a token using a Custom TokenFilter in Lucene.net	private final TermAttribute termAtt; // instance variable\n\ntermAtt = addAttribute(TermAttribute.class); // initialization in constructor \n\n....\n\n\n else if (bufferLength > 1 && buffer[0] == ',')\n        {\n\n            // strip the starting , off !\n            offsetAtt.SetOffset(offsetAtt.StartOffset + 1, offsetAtt.EndOffset);\n\n        // update the termAtt\n            termAtt.setTermBuffer("sub-content of the buffer");\n\n        }\n\n....	0
32639896	4764752	Casting a expression result on SQLite, from float to decimal	ROUND(SUM(Detail.Qty * Products.Weight), 2) AS MovedWeight	0
28899703	28899497	How to keep the page in Portrait mode in Windows Universal Apps?	DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;	0
24230921	24230751	Getting numbers from a matrix	for (int i = 0; i < arr.GetLength(0); i++)\n{\n    for (int j = 0; j < arr.GetLength(1); j++)\n    {\n        int randNUm = rand.Next(0, 20);\n        arr[i, j] = randNUm;\n        Console.Write(arr[i, j] + " ");\n        if (arr[i, j] >= 10)\n        {\n            arr2[i,j] = arr[i,j]\n        }\n    }\n}\n\nConsole.WriteLine("---Proceeding to 2 digit numbers---");\n\nfor (int i = 0; i < arr2.GetLength(0); i++)\n{\n    for (int j = 0; j < arr2.GetLength(1); j++)\n    {\n        Console.Write(arr2[i, j] + " ");\n    }\n}	0
7418793	7406077	Problem with ItemsSource binding in Silverlight ListBox	public class MyListBox : ListBox\n{\n    protected override bool IsItemItsOwnContainerOverride(object item)\n    {\n        return false;\n    }\n\n    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n    {\n        base.PrepareContainerForItemOverride(element, item);\n        ((ListBoxItem)element).ContentTemplate = ItemTemplate;\n    }\n}	0
17347307	17347206	Replace part of matched string with Regex.Replace	var input = ".1.12.3.4.12.4.";\nvar output = Regex.Replace(input, @"\.(\d)(?=\.)", ".0$1");\nConsole.WriteLine(output); // .01.12.03.04.12.04.	0
10305391	10305161	Proper Way To Use .Net DateTime in Parameterized SQL String	cmd.Parameters.AddRange(new DbParameter[] { idParam, fromDate, toDate });	0
7332047	7331948	C# window application	telnet.exe serverip serverport	0
2490560	2490523	How to Parse XML having multiple Default Namespace?	XNamespace ns = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";\n\nvar xDIDL = xResponse.Element(ns + "DIDL-Lite");	0
28544088	28542534	Cannot delete a datagrid row and save the remaining rows back in database	ole_da.SelectCommand = yourSelectCommand;             \nOleDbCommandBuilder oleDbCommandBuilder = new OleDbCommandBuilder(ole_da);\nole_da.Update(dTable);	0
24762886	24760288	Pagination using Request URL for WebAPI	var pageValue = Request.RequestUri.ParseQueryString().Get("page");\n        int currentPage;\n        if (!int.TryParse(pageValue, out currentPage))\n        {\n            currentPage = 0;\n        }	0
27508580	27487081	Using an MVC model to populate and validate a kendo multiselect?	.DataTextField("HierarchyName") \n.DataValueField("HierarchyID") \n\n.DataTextField("Text") \n.DataValueField("Value")	0
664357	664229	Need to override method that is in a namspace with another class which constructs it	public override string FormatTags(string[] tagList)\n{\n    // strip special tags\n    string[] newTagList = stripTags(tagList);\n    return base.FormatTags(newTagList);\n}	0
3018630	3018576	Logging to TextFile from SharePoint	SPSecurity.RunWithElevatedPrivileges(delegate() {\n    using (StreamWriter sw = new StreamWriter(@"C:\log.txt"))\n    {\n        //log information here\n    }\n});	0
12322516	12322499	cast string to datetime	DateTime startDateTime = Convert.ToDateTime(strDate + " " + startTime);	0
21436475	21436181	Send button from c# to client side	function ehDisplayFileNames(event) {\n    console.log(event.target.id + ' has fired the event!');\n}	0
22412766	22402830	Set BingMap Zoom greater LocationRect	public double CalculateZoomLevel(LocationRect boundingBox, double buffer, Map map)\n{\n    double zoom1=0, zoom2=0; \n\n    //best zoom level based on map width\n    zoom1 = Math.Log(360.0 / 256.0 * (map.ActualWidth - 2*buffer) / boundingBox.Width) / Math.Log(2);\n\n    //best zoom level based on map height\n    zoom2 = Math.Log(180.0 / 256.0 * (map.ActualHeight - 2*buffer) / boundingBox.Height) / Math.Log(2);\n\n    //use the most zoomed out of the two zoom levels\n    var zoomLevel = (zoom1 < zoom2) ? zoom1 : zoom2;\n\n    return zoomLevel;\n}	0
11757171	11757142	I want to make RadioButton ListItems ReadOnly without changing the appearance of control in asp.net	Enabled="False"	0
11816366	11816295	Splitting a byte[] into multiple byte[] arrays in C#	byte[] buffer = new byte[512];\nwhile(true) {\n    int space = 512, read, offset = 0;\n    while(space > 0 && (read = stream.Read(buffer, offset, space)) > 0) {\n        space -= read;\n        offset += read;\n    }\n    // either a full buffer, or EOF\n    if(space != 0) { // EOF - final\n       if(offset != 0) { // something to send\n         Array.Resize(red buffer, offset);\n         Upload(buffer);\n       }\n       break;\n    } else { // full buffer\n       Upload(buffer);\n    }\n}	0
1178622	1178605	How to get height of horizontal scrollbar in a ListView	SystemInformation.HorizontalScrollBarHeight	0
23067056	23066999	Getting a particular substring	String myStr = "Macro HarryAnd6767 exist Open Search Panel Star23 else Proceed with DavidAnd6768"\nString[] strTbl = myStr.Split(' ')\nString Name1 = strTbl[1]\nString Name2 = strTbl[10]	0
2543087	2542970	How to access Main Form Public Property WPF	FrameworkElement parent = (FrameworkElement)this.Parent;\n        while (true)\n        {\n            if (parent == null)\n                break;\n            if (parent is Page)\n            {\n                //Do your stuff here. MessageBox is for demo only\n                MessageBox.Show(((Window)parent).Title);\n                break;\n            }\n            parent = (FrameworkElement)parent.Parent;\n        }	0
8165274	8152382	Create a VS2010 Addin to collapse every methods of my active document	// reduce everything like Ctrl+M+O\n_applicationObject.ExecuteCommand("Edit.CollapsetoDefinitions");\n\n// save the cursor position\nTextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection;\nvar selectedLine = selection.ActivePoint.Line;\nvar selectedColumn = selection.ActivePoint.DisplayColumn;\n\n// open the regions\nselection.StartOfDocument();\nwhile (selection.FindText("#region", (int)vsFindOptions.vsFindOptionsMatchInHiddenText))\n{\n    // do nothing since FindText automatically expands any found #region\n}\n\n// put back the cursor at its original position\nselection.MoveToDisplayColumn(selectedLine, selectedColumn);	0
24834575	24834382	String format double with arbitrary precision, fixed decimal position	public static string PrintRow(string token, string unit, double value, string desc)\n{\n    // convert the number to a string and separate digits\n    // before and after the decimal separator\n    string[] tokens = value\n        .ToString()\n        .Split(new string[] { CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);\n\n    // calculate padding based on number of digits\n    int lpad = 11 - tokens[0].Length;\n    int rpad = 19 - tokens[1].Length;\n\n    // format the number only\n    string number = String.Format("{0}{1}.{2}{3}",\n        new String(' ', lpad),\n        tokens[0],\n        tokens[1],\n        new string(' ', rpad));\n\n    // construct the whole string\n    return string.Format(" {0,-4}.{1,-4}{2}  : {3,-23}\n",\n        token, unit, number, desc);\n}	0
19495964	19495318	StartsWith change in Windows Server 2012	private static void Main(string[] args) {\n    var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);\n    string byteOrderMark = encoding.GetString(encoding.GetPreamble());\n    Console.WriteLine("Hello".StartsWith(byteOrderMark, StringComparison.Ordinal));\n    Console.WriteLine("Hello".StartsWith("\ufeff", StringComparison.Ordinal));\n    Console.WriteLine("Hello"[0] == '\ufeff');\n    Console.ReadKey();\n}	0
17530451	17530323	Adding new user control programmatically in windows forms	MainScreen home = new MainScreen();\n    home.Show();\n    EntrySuggestion t_ES = new EntrySuggestion();\n    home.Controls.Add(t_ES);	0
19560096	19557677	WPF Listbox multi selection	listBox.SelectedItems.Add( listBox.Items.GetItemAt(rowIndex) );	0
11859804	11859553	Accessing properties from object initializer	void Foo()\n{ \n  String FullName = "";\n\n  Person p = new Person()\n  {\n    FirstName = "John",\n    LastName  = "Doe",\n    Children  = GetChildrenByFullName(FullName); // is this p.FullName \n                                                 // or local variable FullName?\n  };\n}	0
29859685	29858974	RX - Group/Batch bursts of elements in an observable sequence	var source = Observable.Concat(Observable.Timer(TimeSpan.FromSeconds(6)).Select(o => 1),\n                           Observable.Timer(TimeSpan.FromSeconds(1)).Select(o => 2),\n                           Observable.Timer(TimeSpan.FromSeconds(4)).Select(o => 3),\n                           Observable.Never<int>());\n\nConsole.WriteLine("{0} => Started", DateTime.Now);\nsource\n    .GroupByUntil(x => 1, g => Observable.Timer(TimeSpan.FromSeconds(4)))\n    .Select(x => x.ToArray())\n    .Switch()\n    .Subscribe(i => Console.WriteLine("{0} => [{1}]", DateTime.Now, string.Join(",", i)));	0
15644012	15643619	Following DRY with WinForms MDI Child windows	// for multiple instance forms (and instantiating a "singleton" form)\nprivate void AddNewChild<T>() where T: Form\n{\n    T newForm = new T();\n    newForm.MdiParent = this;\n    newForm.Disposed += new EventHandler(ChildDisposed);\n    newForm.Show();   \n}\n\n// for "singleton" forms\nprivate void ActivateChild<T>() where T: Form\n{\n    // off-the-cuff guess, this line may not work/compile\n    var child = this.MdiChildren.OfType<T>().FirstOrDefault();\n\n    if (child == null) \n    {\n        AddNewChild<T>();\n    }\n    else\n    {\n        child.Show();\n    }\n}\n\n// usage\nlogToolStripMenuItem.Click += (s,e) => ActivateChild<LogForm>();\ntestConfigurationToolStripMenuItem.Click += (s,e) => ActivateChild<ConfigurationForm>();\nmultipleInstanceFormMenuItem.Click += (s,e) => AddNewChild<FormX>();\n...	0
7407570	7341473	Gradual cursor move algorithm - Kinect SDK	float currentX = ..., currentY = ..., targetX = ..., targetY = ...; \nfloat diffX = targetX - currentX;\nfloat diffY = targetY - currentY;\nfloat delta = 0.5f; // 0 = no movement, 1 = move directly to target point. \n\ncurrentX = currentX + delta * diffX;\ncurrentY = currentY + delta * diffY;	0
30071572	30070899	Get User's Manager Details from Active Directory	DirectoryEntry dirEntry = new DirectoryEntry("LDAP://DC=company,DC=com");\nDirectorySearcher search = new DirectorySearcher(dirEntry);\nsearch.PropertiesToLoad.Add("cn");\nsearch.PropertiesToLoad.Add("displayName");\nsearch.PropertiesToLoad.Add("manager");\nsearch.PropertiesToLoad.Add("mail");\nsearch.PropertiesToLoad.Add("sAMAccountName");\nif (username.IndexOf('@') > -1)\n{\n    // userprincipal username\n    search.Filter = "(userPrincipalName=" + username + ")";\n}\nelse\n{\n    // samaccountname username\n    String samaccount = username;\n    if (username.IndexOf(@"\") > -1)\n    {\n        samaccount = username.Substring(username.IndexOf(@"\") + 1);\n    }\n    search.Filter = "(sAMAccountName=" + samaccount + ")";\n}\nSearchResult result = search.FindOne();\nresult.Properties["manager"][0];	0
6521231	6521147	How to calculate the size of a struct instance?	public struct Coordinate\n{\n    public Coordinate(double latitude, double longitude) : this()\n    {\n        Latitude = latitude;\n        Longitude = longitude;\n    }\n\n    public double Latitude { get; private set; }\n    public double Longitude { get; private set; }\n}	0
4811739	4811664	Set cell value using Excel interop	Application.ScreenUpdating = false	0
14300777	14300746	GetJSON check for Empty data	if (data.Id) {\n  // We got back something with an Id property... probably a Person\n} else {\n  // What else could we get back?!?\n}	0
13564916	13564789	WPF Listbox SelectedItems	foreach (var item in combo_course_op.SelectedItems)\n{\n    string s = "select cid from tms_course where course_title = '" \n             + (item["Title"] as string) + "'"; // if Title is column name. Otherwise replace "Title" with actual column header name\n}	0
30546939	30546892	Remove elements in an array containing a certain word/string in a single line of statement	TagArray.RemoveAll(item => item.Contains("AAA");	0
27809646	27809359	How can XML be parsed into custom classes?	XmlSerializer serializer = new XmlSerializer(typeof(List<SiteMapping>)); \n            XmlReader reader = XmlReader.Create(new StringReader(xmlData));\n            List<SiteMapping> siteMappings;\n            siteMappings = (List<SiteMapping>)serializer.Deserialize(reader);	0
22938466	22927219	Where clause in windows phone using sql server compact tool 3.5	var bud = from MonthBud in c.Budgets where MonthBud = monthBud select MonthBud;\nbudgetAmount.Text= bud.ToString();	0
8731503	8730511	Random number generator - variable length	public static string GenerateNewCode(int CodeLength)\n{\n    Random random = new Random();\n    do\n    {\n        StringBuilder output = new StringBuilder();\n\n        for (int i = 0; i < CodeLength; i++)\n        {\n            output.Append(random.Next(0, 9));\n        }\n    }\n    while (!ConsumerCode.isUnique(output.ToString()));\n    return output.ToString();\n}	0
14909807	14909720	Reducing number of very long constructor overloads with just a few different parameters	SomeButton button = new SomeButton()\n{\n    Text = "",\n    MoreStuff = false\n};	0
12948107	12947870	Bindingdata into Table according to selection in the dropdowns	string s1 = "";\n        string s2 = "";\n        if (dropdown1.SelectedIndex > -1)\n           s2 = dropdown1.Text.Trim();\n        else\n           s2 = "";\n        if (dropdown2.SelectedIndex > -1)\n            s1 = dropdown2.Text.Trim();\n        else\n            s1 = "";	0
14376859	7572912	Get list of properties of an entity	foreach (var entry in newEntities)\n{\n    if (entry.State == EntityState.Added)\n    {\n        // continue and get property list\n        var currentValues = entry.CurrentValues;\n        for (var i = 0; i < currentValues.FieldCount; i++)\n        {\n            var fName = currentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;\n            var fCurrVal = currentValues[i];\n        }\n    }\n}	0
13159802	13153529	How do I create a property that all sessions in a WCF service have access to?	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]\n[ServiceContract(SessionMode = SessionMode.Required)]\npublic class MyService : IMyService {\n\n    // this is your static data store which is accessible from all your sessions\n    private static List<string> strList = new List<string>();\n\n    // an object to synchronize access to strList\n    private static object syncLock = new object();\n\n    public void AddAction(string data) {\n\n        // be sure to synchronize access to the static member:\n        lock(syncLock) {\n            strList.Add(data);\n        }\n    }\n\n}	0
4326917	4326736	How can I create an open Delegate from a struct's instance method?	public struct A\n{\n    private int _Value;\n\n    public int Value\n    {\n        get { return _Value; }\n        set { _Value = value; }\n    }\n\n    private int SomeMethod()\n    {\n        return _Value;\n    }\n}\n\ndelegate int SomeMethodHandler(ref A instance);\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var method = typeof(A).GetMethod("SomeMethod", BindingFlags.Instance | BindingFlags.NonPublic);\n\n        SomeMethodHandler d = (SomeMethodHandler)Delegate.CreateDelegate(typeof(SomeMethodHandler), method);\n\n        A instance = new A();\n\n        instance.Value = 5;\n\n        Console.WriteLine(d(ref instance));\n    }\n}	0
5796664	5687313	How do I scale image in DirectX device?	var transformMatrix = Matrix.Scaling(scaleWidth, scaleHeight, 0.0F);	0
20565578	20564234	Parsing Text from a Masked Text Box	string val= maskedTextBox1.Text.Replace("?","");\n        Decimal.Parse(val);	0
5667188	5667086	How to access child object's properties using ASP.NET ReportViewer?	public class MyTopLevelObject {\n\n     public int MyChildsProperty {\n         get {\n              return _myChild.Property;\n         }\n     }\n }	0
23273157	23263051	Asp.Net Identity 2 Password reset link No of clicks	userManager.UpdateSecurityStampAsync()	0
5067467	5067412	C# TPL how to know that all tasks are done?	Parallel.ForEach(...,  () => myMethod(a), ...)	0
17304556	17304364	Castle Windsor IoC inject Property into Constructor	container.Register(Component.For<ISession>()\n    .UsingFactoryMethod(() => container\n        .Resolve<ISessionManager>().CurrentSession)\n    .LifeStyle.Transient);	0
19180228	19180143	Convert list of integers to Unicode C#	int[] list = { 350, 290, 10 };\n\nSystem.Text.Encoding encoding = System.Text.Encoding.Unicode;\n\nvar result = list.Select(i => encoding.GetString(BitConverter.GetBytes(i))).ToList();	0
21060541	21060346	SQL Connection using XML	var doc = new XPathDocument(Application.StartupPath + "/DBConn.xml");\n\nvar navigator = doc.CreateNavigator();\n\nvar serverName = navigator.SelectSingleNode("//appsettings/servername");\nvar username = navigator.SelectSingleNode("//appsettings/username");\nvar password = navigator.SelectSingleNode("//appsettings/password");\nvar database = navigator.SelectSingleNode("//appsettings/database");\n\nusing (SqlConnection sqlConnection = new SqlConnection(@"Data Source=" + serverName + ";Initial Catalog=" + database + ";User Id=" + username + ";Password=" + password + ";MultipleActiveResultSets = True"))\n{\nSqlCommand cmd = new SqlCommand("use TelecomNames SELECT xName FROM dbo.Character", connection);\nconnection.Open();\ncmd.ExecuteNonQuery();\nSqlDataReader reader = cmd.ExecuteReader();\nAutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();\nwhile (reader.Read())\n{\n\n}\n\nconnection.Close();\n\n}	0
5609691	5608561	Overriding properties of abstract class	public override IQueryable<ListData> listQuery()\n{\n    var dc = new NorthwindDataContext();\n    var allrows = from emp in dc.Employees\n                select new EmployeeData()\n                {\n                    EmployeeId = emp.EmployeeID,\n                    ReportsToId = emp.ReportsTo, ...\n                } as ListData;\n    return allrows.OfType<ListData>();\n}	0
26768772	26765725	Using Microsoft Membership Provider Outside of ASP.NET	WebSecurity.InitializeDatabaseConnection	0
23218203	23218071	How to retrieve specific value from XML document in Windows Phone	var doc = XDocument.Parse(\n@"<?xml version=""1.0"" encoding=""UTF-8""?>\n  <root>\n     <row>\n       <Id>22608</Id>\n       <Name>ABC</Name>\n  </row>\n<root>");\nvar nameElement = doc.Root.Element("row").Element("Name");	0
3829561	3829459	parsing a dynamic collection	var test = from object[] line in results\n                   select new OrderProduct()\n                   {\n                       Id = (int)line[0],\n                       Name = (string)line[1],\n                       Quantity = (decimal)line[2]\n                   };	0
14587935	14575686	Enabling a Textbox using a checkbox in ASP.NET?	textbox.Enabled = checkBox.Checked;	0
26650226	26649798	how to get day of the week only if entered date is falling between last monday	//Get the date of the previous Monday\nDateTime prevMonday = DateTime.Now;\nwhile(prevMonday.DayOfWeek != DayOfWeek.Monday)\n      prevMonday = prevMonday.AddDays(-1);\n\n\n//get user's date \nDateTime aa = Convert.ToDateTime(rr.detail);\n\n//check if the user's date is after the Monday\nif (aa > prevMonday && aa <= DateTime.Now.Date)    \n    Console.WriteLine(aa.DayOfWeek);\nelse\n    Console.WriteLine(aa);	0
22536711	22536489	How to compress a random string?	// base 16, 50 random bytes (length 100)\nbe01a140ac0e6f560b1f0e4a9e5ab00ef73397a1fe25c7ea0026b47c213c863f88256a0c2b545463116276583401598a0c36\n// base 64, same 50 random bytes (length 68)\nvgGhQKwOb1YLHw5KnlqwDvczl6H+JcfqACa0fCE8hj+IJWoMK1RUYxFidlg0AVmKDDY=	0
4817903	4817852	Linq to Sql issue with Long DateTime	var p from products\nwhere p.PostedDate.Date == myDateSelected\nselect p	0
2386748	2386325	C# divide two binary numbers	// convert from binary representation\nint x = Convert.ToInt32("01000100", 2);\nint y = Convert.ToInt32("000000100", 2);\n\n// Bitwise and the values together\nint z = x & y; // This will give you 4\n\n// convert back to binary\nstring z_bin = Convert.ToString(z, 2);	0
4731638	4731622	Insert a new row into DataTable	// get the data table\nDataTable dt = ...;\n\n// generate the data you want to insert\nDataRow toInsert = dt.NewRow();\n\n// insert in the desired place\ndt.Rows.InsertAt(toInsert, index);	0
34102621	34099025	c# 2d array in to datagrid view	for (int r = 0; r < height; r++)\n        {\n\n         //Fix : create a new instance of row every time\n          DataGridViewRow row = new DataGridViewRow();\n\n\n        row.CreateCells(this.dataGridView1);\n\n            for (int c = 0; c < width; c++)\n            {\n            row.Cells[c].Value = iArray[r, c];\n\n            }\n\n            this.dataGridView1.Rows.Add(row);\n        }	0
32206057	32204854	Is it possible to use a loop for this type of query set?	for(int i = 1; i < avgTimeArray.length; i++){\nsc = new     MySqlCommand("Update tbName set AvgTime = @AvgTime where PatternId = @PatternID", msc);\nsc.Parameters.Add(new ObjectParameter("AvgTime", avgTimeArray[i].ToString())); \nsc.Parameters.Add(new ObjectParameter("PatternID", i.ToString())); \nsc.ExecuteNonQuery();}	0
2400540	2400468	GetDate in a string in c#	string text = "75000+ Sept.-Oct. 2004";\n MatchCollection dates = Regex.Matches(text, @"[0-9]{5,}[+][\s](jan|feb|fev|mar|apr|avr|may|mai|jun|jui|jul|jui|aug|ao?|sept|oct|nov|dec)[\.][\-](jan|feb|fev|mar|apr|avr|may|mai|jun|jui|jul|jui|aug|ao?|sept|oct|nov|dec)[\.]\s([0-9]{4})", RegexOptions.IgnoreCase);\n Console.WriteLine(dates[0].Groups[1] + " " + dates[0].Groups[3]);\n Console.WriteLine(dates[0].Groups[2] + " " + dates[0].Groups[3]);	0
20411180	19788127	save a JPEG in progressive format	using (MagickImage image = new MagickImage("input.png"))\n{\n  // Set the format and write to a stream so ImageMagick won't detect the file type.\n  image.Format = MagickFormat.Pjpeg;\n  using (FileStream fs = new FileStream("output.jpg", FileMode.Create))\n  {\n    image.Write(fs);\n  }\n  // Write to .jpg file\n  image.Write("PJEG:output.jpg");\n  // Or to a .pjpeg file\n  image.Write("output.pjpg");\n}	0
15625119	15625034	how to open ToolStripMenuItem Window by moving mouse on ToolStripSplitButton	public Form1() {\n  InitializeComponent();\n  toolStripDropDownButton1.MouseEnter += toolStripDropDownButton1_MouseEnter;\n}\n\nvoid toolStripDropDownButton1_MouseEnter(object sender, EventArgs e) {\n  toolStripDropDownButton1.ShowDropDown();\n}	0
10192318	10190566	Permutations of arrays within an array	var perms = from a in geneticsArray[0]\n                    from b in geneticsArray[1]\n\n                    select new string[] { a, b };\n\n        var dict = new Dictionary<string, int>();\n        foreach (var ent in perms)\n        {\n            Array.Sort(ent);\n            var _ent = string.Join(",", ent);\n            if (dict.ContainsKey(_ent))\n            {\n                dict[_ent]++;\n            }\n            else\n            {\n                dict.Add(_ent, 1);\n            }\n        }\n\n        return dict;	0
10942915	10939426	serialization of entity model c#	using System.Runtime.Serialization;\n[DataContract]\npublic class Account\n{\n        [DataMember]\n        public System.Guid ID { get; set; }\n        [DataMember]\n        public System.Guid AccountSubTypeID { get; set; }\n        [DataMember]\n        public Nullable<int> IndustryTypeID { get; set; }\n}	0
20022053	20021786	Get list of referencing tables in SQL Server using C#, SMO	var tbl = db.Tables["person"];\nvar dw = new DependencyWalker(server);\nvar tree = dw.DiscoverDependencies(new SqlSmoObject[] {tbl}, DependencyType.Children);\nvar cur = tree.FirstChild.FirstChild;\nwhile (cur != null)\n{\n    var table = server.GetSmoObject(cur.Urn) as Table;\n    if (table != null && table.ForeignKeys.Cast<ForeignKey>().Any(fk => fk.ReferencedTable == tbl.Name))\n    {\n        //do something with table.Name\n    }\n    cur = cur.NextSibling;\n}	0
22868023	22868022	How to move CSS inline with PreMailer.Net whilst using MvcMailer for sending HTML emails	public virtual MvcMailMessage Welcome()\n{\n    var message = Populate(x => {\n        x.ViewName = "Welcome";\n        x.To.Add("some-email@example.com");\n        x.Subject = "Welcome";\n    });\n    message.Body = PreMailer.Net.PreMailer.MoveCssInline(message.Body).Html;\n    return message;\n}	0
21645807	21645760	How to Get Specific Line from a ListBox Based on Integer	string value = playerList.Items[index].ToString();	0
3005294	3005168	How to reference a class that implements certain interface?	//Usage of logger with factory\nIExceptionLogger logger = ExceptionLoggerFactory.GetLogger();\n\npublic static class ExceptionLoggerFactory\n{\n  public static IExceptionLogger GetLogger()\n  {\n    //logic to choose between the different exception loggers\n    //e.g.\n    if (someCondition)\n      return new DBExceptionLogger();\n    //else etc etc \n  }\n}	0
21732282	21730302	Binding string property to a status bar text	TimeBase timeBaseInstance;\n    public MainWindow()\n    {\n        timeBaseInstance = new TimeBase();\n\n        //Set the dataContext so bindings can iteract with your data\n        DataContext = timeBaseInstance;\n        InitializeComponent();\n    }	0
34259692	34259358	DynamoDb: Delete all items having same Hash Key	You have to know both your (hash + range) to delete the item.	0
5655215	5655195	How do I project an object into a list using Linq?	var spositions = positions.Select(\n                     position => new SPosition\n                         {\n                             latitude = position.Latitude,\n                             longitude = position.Longitude\n                         }).ToList();	0
23878215	23878166	multiplying int with double in C#	employeeSalaries[i] = Convert.ToInt32(Math.Round(baseSalary + (s * commission), 0));	0
5387328	5360515	Autocomplete box pops a default message when no item exist	public NewRecord()\n{\n    InitializeComponent();\n    List<string> ledgerList = new List<string>();\n    ledgerList = DAL_LedgerNameList.LoadLedgers();\n    if (ledgerList.Length==0) \n    {\n        sellerText.ItemsSource = new string() {"No Sellers Exist"}\n    }\n    else\n    {\n        sellerText.ItemsSource = ledgerList;\n    }\n}	0
8896135	8896030	Pass string from C# to C DLL	public static extern bool StreamReceiveInitialise(string filepath);	0
9300552	9300291	Rendering out a table	TableRow tRow\nTableCell tCell\nfor(int i = startTemp; i < endTemp; i += iterator)\n{\ntRow = new TableRow();\ntRow.CssClass = (i % 2 == 0 ? "white" : "grey");\ntempTable.Rows.Add(tRow);\n\ntCell = new TableCell();\ntCell.Text = i.ToString();\ntRow.Cells.Add(tCell);\ntCell = new TableCell();\n\ntCell.Text = convert(i);\n\ntRow.Cells.add(tCell);\ntempTable.Rows.Add(tRow);\n\n}	0
6883533	6883475	Cannot set RibbonTextBox isEnable to False	public class FixedRibbonTextBox : RibbonTextBox\n{\n    protected override bool IsEnabledCore\n    {\n        get { return true; }\n    }\n}	0
33617908	29008630	Explorer Namespace Extension- what is the entering method of Save in third party application?	if (m_fileOpenDialog != NULL)\n\n        {\n\n            m_fileOpenDialog->Unadvise(m_cookie);\n\n            m_fileOpenDialog->Release();\n\n            m_fileOpenDialog = NULL;\n\n            m_cookie = 0;\n\n        }	0
5207004	5206857	Convert NTP timestamp to utc	long ntp = 3490905600; \nDateTime start = new DateTime(1900, 1, 1);\nDateTime dt = start.AddSeconds(ntp);\n\nConsole.WriteLine(dt.ToString());\nConsole.WriteLine(dt.ToUniversalTime().ToString());	0
31960216	31960051	Recursive generic class declaration without using interface	AudienceOperators<object> op3 = new AudienceOperators<object>(new List<object> { op1, op2 }, "AND");	0
8854897	8854842	Insert data into tables linked with foreign key	SqlCommand myCommand2 = new SqlCommand(@"INSERT INTO [Order] (Status, CustomerID) " + " SELECT 13016, ID FROM Customers WHERE FirstName = 'Garderp')", myConnection);	0
2691775	2691750	Using the XElement.Elements method, can I find elements with wildcard namespace but the same name?	xml.Elements().Where(e => e.Name.LocalName == "PropertyGroup")	0
3467796	3467765	Find methods that have custom attribute using reflection	var methods = assembly.GetTypes()\n                      .SelectMany(t => t.GetMethods())\n                      .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)\n                      .ToArray();	0
8649300	8649161	inserting datatables into sql server that are linked	SET IDENTITY_INSERT QuickLabDump ON	0
22250687	22240980	Unique properties from model with ASP.NET Identity	[Validator(typeof(ApplicationUserValidator))]\nclass ApplicationUser : IdentityUser\n{\n    public string Email { get; set; }\n    //...Model implementation omitted\n}\n\npublic class ApplicationUserValidator : AbstractValidator<ApplicationUser>\n{\n    public ApplicationUserValidator()\n    {\n\n        RuleFor(x => x.Email).Must(IsUniqueEmail).WithMessage("Email already exists");\n    }\n    private bool IsUniqueEmail(string mail)\n    {\n        var _db = new DataContext();\n        if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;\n        return false;\n    }\n    //implementing additional validation for other properties:\n    private bool IsUniqueTelephoneNumber(string number)\n    {\n      //...implement here\n    }\n}	0
8212941	8212562	Sort GridView by column populated in RowDataBound event	System.Web.Security.MembershipUserCollection users = System.Web.Security.Membership.GetAllUsers();\ngrid.DataSource = users.OfType<MembershipUser>().OrderBy(GetUserFullName, StringComparer.OrdinalIgnoreCase);\n\nprivate static string GetUserFullName(MembershipUser user)\n{\n    // return here user's full name\n    return user.Email;\n}	0
4289179	4289162	How to collapse an expander	expander.IsExpanded = false;	0
20372707	20372379	Saving a wpf layout to pdf using pdfsharp, c#	MemoryStream lMemoryStream = new MemoryStream();\nPackage package = Package.Open(lMemoryStream, FileMode.Create);\nXpsDocument doc = new XpsDocument(package);\nXpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);\nwriter.Write(dp);\ndoc.Close();\npackage.Close();\n\nvar pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(lMemoryStream);\nPdfSharp.Xps.XpsConverter.Convert(pdfXpsDoc, d.FileName, 0);	0
24255321	24236701	How to receive URLs with Xamarin Intent Filters	[Activity (Label = "LinkToDesktop", MainLauncher = true)]\n[IntentFilter (new[] { Intent.ActionSend }, Categories = new[] {\n    Intent.CategoryDefault,\n    Intent.CategoryBrowsable\n}, DataMimeType = "text/plain")]\npublic class MainActivity : Activity\n    {\n    protected override void OnCreate (Bundle bundle)\n        {\n        base.OnCreate (bundle);\n        if (!String.IsNullOrEmpty (Intent.GetStringExtra (Intent.ExtraText)))\n            {\n            string subject = Intent.GetStringExtra (Intent.ExtraSubject) ?? "subject not available";\n            Toast.MakeText (this, subject, ToastLength.Long).Show ();\n            }\n        }\n    }	0
26053321	26053122	Setting checkbox values	string str = mas.empdetadd(Convert.ToInt32(CheckBox1.Checked),Convert.ToInt32(CheckBox2.Checked), Convert.ToInt32(CheckBox3.Checked), Convert.ToInt32(CheckBox4.Checked),txtnom.Text, ddgroup.SelectedItem.Text);	0
1408690	1408686	Join two tables on different databases	test2.dbo.tblFoo	0
23709262	23709234	How do i add int items to comboBox in jumps of 10 ?	for (int i = 10; i <= 90; i+=10)\n        {\n        comboBox1.Items.Add("Reduced by: " + i.ToString());\n        }	0
11427344	11427000	How do I create a dot prefixed cookie uri?	Cookie(string name, string value, string path, string domain);	0
10259372	10259310	how to move anew button at run time?	public void myText_MouseMove(object sender, MouseEventArgs e)\n    {\n        Button button = (Button)sender;\n        if (e.Button == MouseButtons.Left)\n        {\n            button .Left += e.X - move.X;\n            button .Top += e.Y - move.Y;\n        }\n    }	0
14115717	13600564	How to get date time from PointPair in X axis using ZedGraph in C#?	PointPair pt = curve[iPt];\n    XDate the_date = new XDate(pt.X);\n\n    if( curve.Label.Text == "Temperature" )\n        return curve.Label.Text + " is " + pt.Y.ToString("f2") + " ??C at " + the_date.DateTime;\n    else\n        return curve.Label.Text + " is " + pt.Y.ToString("f2") + " % at " + the_date.DateTime;	0
18593429	18590659	Excel with c#: Exculde first rows when copying a range	Excel.Range dataWithoutFirstRow = mySheet.Range[mySheet.UsedRange.Cells[2, 1],\n      mySheet.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeLastCell)];	0
15925269	15925189	Creating a dictionary with GroupBy and Sum as Key/Value	messages.SelectMany(message => message.Properties)\n        .Where(prop => prop.Key == "language")\n        .GroupBy(prop => prop.Value)\n        .ToDictionary(grp => grp.Key,\n                      grp => grp.Count());	0
4099251	4099174	How to place something inside DIV with C#	protected void Page_Load(object sender, EventArgs e)\n{\n   if (IsPostBack)\n      return;\n\n    myDiv.InnerText = "some text";\n    myDiv.Controls.Add(new Banner("someBannerArgs"));\n    myDiv.Controls.AddAt(1,new Banner("someBannerArgs"));\n}	0
17056443	17056391	How open URL in a default browser with XAML ( windows-8 Application )	private async void LaunchSite(string siteAddress)\n{\n    try\n    {\n        Uri uri = new Uri(siteAddress);\n        var launched = await Windows.System.Launcher.LaunchUriAsync(uri);\n    }\n    catch (Exception ex)\n    {\n        //handle the exception\n    }\n}	0
21636656	21633854	Extracting data for specific key in json	[DataContract]\npublic class ProfileType\n{\n    [DataMember]\n    public int ProfileTypeIDT { get; set; }\n    [DataMember]\n    public string SingularName { get; set; }\n    [DataMember]\n    public string PluralName { get; set; }\n    [DataMember]\n    public ProfileField[] Fields { get; set; }\n}\n\n[DataContract]\npublic class ProfileField\n{\n    [DataMember]\n    public int ProfileFieldIDT { get; set; }\n    [DataMember]\n    public int ProfileTypeIDT { get; set; }\n    [DataMember]\n    public string FieldName { get; set; }\n    [DataMember]\n    public string DataType { get; set; }\n    [DataMember]\n    public int Length { get; set; }\n}\n\nbyte[] byteArray = Encoding.Unicode.GetBytes(jsonString);\nMemoryStream stream = new MemoryStream(byteArray);\nDataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ProfileType[]));\nProfileType[] profileTypes = (ProfileType[])serializer.ReadObject(stream);	0
10319689	10319447	Release handle on file. ImageSource from BitmapImage	public static ImageSource BitmapFromUri(Uri source)\n{\n    var bitmap = new BitmapImage();\n    bitmap.BeginInit();\n    bitmap.UriSource = source;\n    bitmap.CacheOption = BitmapCacheOption.OnLoad;\n    bitmap.EndInit();\n    return bitmap;\n}	0
12128384	12128206	WCF Rest POST method to accept both JSON and XML	public class DataController : ApiController\n{\n    public void Post(DataModel model)\n    {\n        // Whether the body contains XML, JSON, or Url-form-encoded it will be deserialized\n        // into the model object which you can then interact with in a strongly-typed manner\n    }\n}\n\npublic class DataModel\n{\n    public string PropertyA { get; set; }\n    public string PropertyB { get; set; }\n}	0
349959	349943	Read a non .NET DLL version from C#?	public void GetFileVersion() {\n    // Get the file version for the notepad.\n    FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo("%systemroot%\\Notepad.exe");\n\n    // Print the file name and version number.\n    textBox1.Text = "File: " + myFileVersionInfo.FileDescription + '\n' +\n       "Version number: " + myFileVersionInfo.FileVersion;\n }	0
7254223	7254203	Is there a concise way to determine if any object in a list is true?	myBool = List.Any(r => r.property)	0
9081662	9079727	Image processing - Reduce object thickness without removing	img = ColorConvert[Import["http://i.stack.imgur.com/zPtl6.png"],  "Grayscale"];\nmax = MaxDetect[img, .55]\nThinning[max]	0
19302158	19302120	Adding the value of session variable to the inner Html of a span tag	runat="server"	0
25785321	25785151	Accessing DropDownList inside GridView in C#	protected void Grd_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            DropDownList drp = (DropDownList)e.Row.FindControl("ddlDesignation");\n        }\n}	0
2792949	2792623	Reading and parsing email from Gmail using C#, C++ or Python	import imaplib\nimport email\n\ndef extract_body(payload):\n    if isinstance(payload,str):\n        return payload\n    else:\n        return '\n'.join([extract_body(part.get_payload()) for part in payload])\n\nconn = imaplib.IMAP4_SSL("imap.gmail.com", 993)\nconn.login("user", "password")\nconn.select()\ntyp, data = conn.search(None, 'UNSEEN')\ntry:\n    for num in data[0].split():\n        typ, msg_data = conn.fetch(num, '(RFC822)')\n        for response_part in msg_data:\n            if isinstance(response_part, tuple):\n                msg = email.message_from_string(response_part[1])\n                subject=msg['subject']                   \n                print(subject)\n                payload=msg.get_payload()\n                body=extract_body(payload)\n                print(body)\n        typ, response = conn.store(num, '+FLAGS', r'(\Seen)')\nfinally:\n    try:\n        conn.close()\n    except:\n        pass\n    conn.logout()	0
31911841	31911798	Is there a reason for array declaration syntax in C#?	public class Foo\n{\n    private int[ , ] Bar;  // Bar will be null until initialized\n\n    public Foo(int a, int b)\n    {\n        Bar = new int[a, b];\n    }\n}	0
25326578	25326137	Converting Bitmap to ImageSource made my image's background black	public BitmapImage ToBitmapImage(Bitmap bitmap)\n{\n  using (MemoryStream stream = new MemoryStream())\n  {\n    bitmap.Save(stream, ImageFormat.Png); // Was .Bmp, but this did not show a transparent background.\n\n    stream.Position = 0;\n    BitmapImage result = new BitmapImage();\n    result.BeginInit();\n    // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."\n    // Force the bitmap to load right now so we can dispose the stream.\n    result.CacheOption = BitmapCacheOption.OnLoad;\n    result.StreamSource = stream;\n    result.EndInit();\n    result.Freeze();\n    return result;\n  }\n}	0
7009045	6993835	removing strongly signed from assembly	[assembly: AssemblyKeyName("")]	0
7915250	7912602	wpf xaml to c# TargetProperty	var path1 = new PropertyPath("RenderTransform.Children[3].Y");\nvar path2 = new PropertyPath("(0).(1)[3].(2)", UIElement.RenderTransformProperty, \n                                               TransformGroup.ChildrenProperty,\n                                               TranslateTransform.YProperty);	0
8944694	8944577	AutoMapper Map Child Property that also has a map defined	Mapper.CreateMap<DomainClass, Child>();\nMapper.CreateMap<DomainClass, Parent>()\n      .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))\n      .ForMember(d => d.A, opt => opt.MapFrom(s => s.A))\n      .ForMember(d => d.Child, \n                 opt => opt.MapFrom(s => Mapper.Map<DomainClass, Child>(s)));	0
30167216	30166617	Reading textfile skipping bunch of lines then proceeding to other lines	var lines = new List<string>();\nvar counter = 0;\nusing (var sr = new StreamReader(filename)) {\n    string line;\n    while ((line = sr.ReadLine()) != null) {\n        //ignore the first 3 lines\n        if (counter >= 3) {\n            //now work out where in the pattern of 7 (3 read, 4 skip) we are\n            var mod = (counter - 3) % 7;\n            //if the first 3 of the 7, keep it\n            if (mod < 3)\n                lines.Add(line);\n        }\n        counter++;\n    }\n}	0
29221892	29221743	How to convert a flat data collection into hierarachical one?	var list = new List<myClassFlat>\n    {\n        new myClassFlat() { historyId = 612, documentId = 2, statusId = 1},\n        new myClassFlat() { historyId = 612, documentId = 3, statusId = 2},\n        new myClassFlat() { historyId = 612, documentId = 4, statusId = 5},\n        new myClassFlat() { historyId = 612, documentId = 2, statusId = 4},\n    };\n\nvar result = list.GroupBy(x => new { x.historyId, x.documentId })\n                 .Select(g => new myClassHierarchical()\n                     {\n                         historyId = g.Key.historyId,\n                         documentId = g.Key.documentId,\n                         statusId = g.Select(x => x.statusId).ToArray()\n                     });	0
7244865	7244682	Get the version of an XML file without downloading it from the server	public void ProcessRequest(HttpContext context)\n{\n context.Response.ContentType = "text/plain";\n string fileName = context.Request.QueryString.Get("fileName");\n FileInfo fileInfo = new FileInfo(Server.MapPath(".") + "/" + fileName);\n context.Response.Write(fileInfo.LastWriteTime.ToString());\n}	0
26340739	26336557	From Free/Pro to In-App Purchase	CurrentApp.GetAppReceiptAsync()	0
16347040	16346612	How To Create XPath for XML?	XNamespace ns = "http://Citriz/Schemas";\nvar peopleRole = XDocument.Parse(xml)\n                    .Descendants(ns + "PeopleRole")\n                    .Where(p => p.Attribute("TypeCode").Value == "INSS")\n                    .ToList();	0
22848716	22848527	Using an interface to call a struct that is in a class	public class Config : CurveTracer.IConfig\n{\n    public bool Init()\n    {\n        return true;\n    }\n\n    public AppConfig AppConfig { get; set; }\n}\n\npublic class CurveTracer\n{\n    public interface IConfig\n    {\n        bool Init();\n\n        AppConfig AppConfig { get; set; }\n    }\n}\n\n// Are you sure this needs to be a struct? Just add cfgVersion and cfgSerial to CurveTracer.IConfig or make it a class.\npublic struct AppConfig\n{\n    public string cfgVersion;\n    public string cfgSerial;\n};	0
24022331	24022312	Inverse of XOR-Operation	byteVar3 = byteVar.Merge(byteVar2);	0
25076280	25075462	Changing the Visibility of PanoramaItem using C# in Windows Phone 8	private void BloodGroup_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n{\n    if (SelectGroup.Visibility == System.Windows.Visibility.Collapsed)\n        SelectGroup.Visibility = System.Windows.Visibility.Visible;\n    else\n        SelectGroup.Visibility = System.Windows.Visibility.Collapsed;\n}	0
30653540	30653420	Intercept a setter in C#	public class A\n{\n   private string xPrivate;\n   public string X {\n      get { return this.xPrivate; }\n      set { this.xPrivate = value; }}\n}	0
15839025	15838485	Multiple Fontstyles	FontStyle newFontStyle = new FontStyle();\nnewFontStyle = FontStyle.Regular;\nnewFontStyle = FontStyle.Bold | FontStyle.Italic;	0
20022774	20022717	I need to create a windows form from within a NUnit test	[SetUp]\npublic void SetUp()\n{\n    m_myForm = new MyTestForm();\n    m_myForm.Show(null);\n}\n\n[TearDown]\npublic void TearDown()\n{\n    m_myForm.Close();\n    m_myForm.Dispose();\n}\n[Test]\n//... some tests using the member variable	0
34288949	34288717	Get JSON value for IEnumerable<IEnumerable<string>> type	public class CustomType\n{\n    public string Type { get; set; }\n    public string Value { get; set; }\n\n    public Dictionary<string, string> AsJsonProperty()\n    {\n        return new Dictionary<string, string>\n        {\n            {Type, Value}\n        };\n    }\n}\n\nclass Class1\n{\n    public string ToJson(IEnumerable<IEnumerable<CustomType>> customTypes)\n    {\n        var asJsonFriendly = customTypes.Select(x => x.Select(y => y.AsJsonProperty()));\n        return JsonConvert.SerializeObject(asJsonFriendly);\n    }\n}	0
10186316	10039222	Invoking Astyle on a string or a file via C#	pProcess.StartInfo.Arguments = "--options=none --style=ansi --recursive  *.h *.cpp";\n       pProcess.StartInfo.UseShellExecute = false;\n       pProcess.StartInfo.RedirectStandardOutput = true;\n       pProcess.StartInfo.RedirectStandardError = true;\n       pProcess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(target_path);\n       try\n       {\n           pProcess.Start();\n           string strOutput = pProcess.StandardOutput.ReadToEnd();\n           string strError = pProcess.StandardError.ReadToEnd();\n           pProcess.WaitForExit();\n\n       }\n       catch { }\n   }	0
7903183	7903116	hex to float conversion	byte[] bytes = BitConverter.GetBytes(0x08fdc941);\n        if (BitConverter.IsLittleEndian)\n        {\n            bytes = bytes.Reverse().ToArray();\n        }\n        float myFloat = BitConverter.ToSingle(bytes, 0);	0
31066628	31066520	How to change specific value inside multiple datatables in dataset using C# ASP.Net	datatable.AsEnumerable()\n    .Where(row => row["value"].ToString()=="xy")\n    .ToList().ForEach(row => row["Collected"] = "xy_default");\n\n\npublic void UpdateRow(datatable,value)\n{\n     datatable.AsEnumerable()\n        .Where(row => row["value"].ToString()==value)\n        .ToList().ForEach(row => row["Collected"] = value + "_default");\n}	0
23489408	22805747	context menu to delete selected button	Button btn = new Button();\n        Label lbl = new Label();\n        CustomControl cst_btn = new CustomControl(btn, lbl);\n        cst_btn = sender as CustomControl;\n        DialogResult dialogResult = MessageBox.Show("Are you sure that you want to remove this object?", "Remove object", MessageBoxButtons.YesNo);\n        if (dialogResult == DialogResult.Yes)\n        {\n            cst_btn.Dispose();\n        }\n        else if (dialogResult == DialogResult.No)\n        {\n            //do nothing\n        }\n\n\n    }\n\n    public EventHandler handlerGetter(CustomControl button)\n    {\n        return (object sender, EventArgs e) =>\n        {\n            rmv_btn_click(button, e);\n        };\n    }	0
32525992	32525415	Problems with custom config section	protected override ConfigurationElement CreateNewElement()\n{\n    return new ExcludedUser();\n}	0
20631692	20631628	Make sure all virtual methods are overridden	public abstract class BaseClass\n{\n  public void Start()\n  {\n    // do something\n    OnStart();\n    // do something else\n  }\n  protected abstract void OnStart();\n}	0
2395335	2388021	Parameterizing a HQL IN clause using HqlBasedQuery?	SetParameterList()	0
16712006	16711970	c# declaring list and populate with values using one line of code	var list = new List<IMyCustomType>{ \n    new MyCustomTypeOne(), \n    new MyCustomTypeTwo(), \n    new MyCustomTypeThree() \n};	0
23017285	23017062	How to save data from C# in a txt file?	public void ConvertToTXTFile(string fileName)\n {\n     StringBuilder sb = new StringBuilder();\n     System.Text.Encoding Output = System.Text.Encoding.Default;\n     foreach (PersonInfos personinfos in PersonInfoDetails)\n     {\n         // Collect every personinfos selected in the stringbuilder\n         if (personinfos.SelectCheckBox == true)\n         {\n            string line = String.Format("L??" + personinfos.FirstName + "??" + personinfos.LastName + "??");\n            sb.AppendLine(line);\n         }\n     }\n\n     // Now write the content of the StringBuilder all together to the output file\n     File.WriteAllText(filename, sb.ToString())\n}	0
21680271	21680134	Carriage return or new line in xml comments	/// <summary> \n/// Your main comment \n/// <para>&#160;</para> \n/// <para>The rest of the comment</para> \n/// </summary> \npublic void CommentMethod()\n{\n}	0
1633542	1633490	How to detect programmatically whether code is running in shared DLL or exe?	bool isDll = this.GetType().Assembly.EntryPoint == null;	0
25283246	25279126	Read XML file in Windows Phone 8.1 Background task	XDocument xdoc = XDocument.Load("ms-appx:///MyPlaylistManager/Quran.xml");\n// or like this:\nStorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"MyPlaylistManager\Quran.xml");	0
12527105	12526849	RegularExpressionValidator - validate that a string does NOT match an expression	(?!.*AB)(?!.*F[WXYZ\d])	0
12564607	7750377	How to get the ID of the contact on Windows Phone contact list?	Contact c = new Contact();\nvar Id = c.GetHashCode(); //gives the Id property value.	0
7837848	7837826	In C#, how can I create a TextReader object from a string (without writing to disk)	using(TextReader sr = new StringReader(yourstring))\n{\n    DoSomethingWithATextReader(sr);\n}	0
2018363	2018272	preventing multiple instance of one form from displaying	class HelpForm : Form\n{\n   private HelpForm _instance;\n   public static HelpForm GetInstance()\n   {\n     if(_instance == null) _instance = new HelpForm();\n     return _instance; \n   }\n}\n\n.......\n\nprivate void heToolStripMenuItem_Click(object sender, EventArgs e)\n{\n     HelpForm form = HelpForm.GetInstance();\n     if(!form.Visible)\n     {\n       form.Show();\n     }\n     else\n     {\n       form.BringToFront();\n     }\n}	0
20453994	20453921	Call a Post Web API with multiple string parameters?	MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();\nHttpContent datas = new ObjectContent<dynamic>(new { \n    username= username, \n    password= password}, jsonFormatter);\n\nvar client = new HttpClient();\n\nclient.DefaultRequestHeaders.Accept.Add(\n    new MediaTypeWithQualityHeaderValue("application/json"));\n\nvar response = client.PostAsync("api/User/ValidateAdmin", datas).Result;\n\nif (response != null)\n{\n    try\n    {\n        response.EnsureSuccessStatusCode();\n        return response.Content.ReadAsAsync<bool>().Result;\n\n        ...	0
18637351	18635448	WebDriver C# how do i capture img src - verify image is present	driver.FindElement(By.XPath("//form/div[7]/div/div[2]/div[1]/a/img"));	0
30630725	30630459	Comparison and re-structuring of 3 lists into a single list?	var groupyName = list1.Concat(list2).Concat(list3).GroupBy(I => I.Name);	0
14899331	14899136	How to manage with dynamic CheckBox in C# WPF application?	CheckBox chx;\nchx.Tag = "Chart 1"; // put these tags in an enum or at least constants\nchx.Click += chx_Click; \n\nvoid chx_Click(object sender, RoutedEventArgs e)\n{\n    CheckBox chx = sender as CheckBox;\n    if (chx != null && chx.Tag != null)\n    {\n        switch (chx.Tag)\n        {\n            case "Chart 1": \n                        myChart1.Visibility = chx.IsChecked? Visibility.Visible: Visibility.Collapsed;  \n                break;\n            case "Chart 2": //...\n                break;\n            default:\n                break;\n        }\n    }\n}	0
22324709	22324403	GetHashCode for the object with several data members	public int GetHashCode(MyClass myobj)\n{\n     if(myObj == null)\n     {\n        return base.GetHashCode();\n     }\n     return (myObj.x != null ? myObj.x.GetGashCode() : 0) ^ (myObj.y != null ? myObj.y.GetGashCode() : 0)\n}	0
23094494	23090019	fastest formula to get Hue from RGB	If Red is max, then Hue = (G-B)/(max-min)\nIf Green is max, then Hue = 2.0 + (B-R)/(max-min)\nIf Blue is max, then Hue = 4.0 + (R-G)/(max-min)	0
29530963	29529887	How to enable and disable particular row in DataGridView by checking and unchecking of checkbox	private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{          \n     if (e.ColumnIndex == dataGridView1.Columns["Your Column Name"].Index) //To check that we are in the right column\n     {\n          dataGridView1.EndEdit();  //Stop editing of cell.\n          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Your Column Name"].Value)\n          {\n             //dataGridView1.Columns[3].ReadOnly = true;// for entire column \n               int colIndex = e.ColumnIndex;\n               int rowIndex = e.RowIndex;\n               dataGridView1.Rows[colIndex].Cells[rowIndex].ReadOnly = true;\n          }\n    }\n}	0
13773863	13773611	CefSharp - Strongly Named	Assembly.Load	0
6813977	6813696	Entity Model - How to insert / update data which involves navigational properties	Category c = new Category \n{\n    ID = 5\n};\nctx.AttachTo("Categories", c);\n\nProduct p = new Product\n{\n   ID = 5,\n   Name = "Bovril"\n};\nctx.AddToProducts(p);\n\np.Category = c;\nctx.SaveChanges();	0
3222094	3221887	How do you control the types of objects you can add to an XElement?	public class HtmlHead : XElement\n{\n    public HtmlHead(object content) : base("head")\n    {\n        this.Add(content);\n    }\n\n    public HtmlHead(params object[] content) : base("head", content) { }\n}	0
2188015	2187562	How do I create an executable application for a Excel macro procedure?	Dim fd As FileDialog\nDim sOldFile As String\nDim sNewFile As String\n\nSet fd = Application.FileDialog(msoFileDialogOpen)\n\n  fd.AllowMultiSelect = False\n\n  MsgBox "Please Select the Old File"\n  fd.Show\n  Workbooks.Open fd.SelectedItems(1)\n  sOldFile = ActiveWorkbook.Name\n\n  MsgBox "Please Select the New File"\n  fd.Show\n  Workbooks.Open fd.SelectedItems(1)\n  sNewFile = ActiveWorkbook.Name	0
10878658	10878307	DataGridView show Int instead of Double values	DataTable dtCloned = dt.Clone();\ndtCloned.Columns[0].DataType = typeof(Decimal);\nforeach (DataRow row in dt.Rows) \n{\n    dtCloned.ImportRow(row);\n}	0
5490502	5490427	How do I get a list of views back programatically in Sharepoint 2010	SPContext.CurrentWeb.Lists[0].Views	0
6681373	6681351	c# Check if all strings in list are the same	var allAreSame = list.All(x => x == list.First());	0
16787184	16715081	RoundtripKind mode xml serialize	[XmlIgnore]\npublic DateTime Time { get; set; }\n\n[XmlElement("Time")]\npublic string strTime\n{\n        get { return Time.ToString("o"); }\n        set { Time = DateTime.Parse(value); }\n}	0
2866777	2866765	Translating EventAggregators usage of SynchronizationContext to VB.Net	_context.Send(New SendOrPostCallback(AddressOf listener.Handle), message)	0
10767984	10765792	Show a form as a dialog on another form via thread	var owner = Application.OpenForms["Form1"];\nform2.Load += delegate {\n    // NOTE: just as a workaround for the Owner bug!!\n    Control.CheckForIllegalCrossThreadCalls = false;\n    form2.Owner = owner;\n    Control.CheckForIllegalCrossThreadCalls = true;\n    owner.BeginInvoke(new Action(() => owner.Enabled = false));\n\n};\nform2.FormClosing += new FormClosingEventHandler((s, ea) => {\n    if (!ea.Cancel) {\n        owner.Invoke(new Action(() => owner.Enabled = true));\n        form2.Owner = null;\n    }\n});\nform2.ShowDialog();	0
9618595	9618570	How to make sure that files on the server are not overwritten with files of the same name	if (File.Exists(fileName))\n{\n   fileName = Guid.NewGuid() + fileName;\n}	0
27230249	27227593	COMException after upgrading DTS package	Microsoft.SQLServer.ManagedDTS dll	0
26636737	26635317	Pad a Number with Leading Zeros via Text Box TextChanged event	private void radTextBoxNum_TextChanged(object sender, EventArgs e) {\n  radTextBoxNum.TextChanged -= radTextBoxNum_TextChanged;\n  string text = radTextBoxNum.Text.TrimStart('0');\n  radTextBoxNum.Text = text.PadLeft(15, '0');\n  radTextBoxNum.Select(radTextBoxNum.TextLength, 0);\n  radTextBoxNum.TextChanged += radTextBoxNum_TextChanged;\n}	0
5036264	5036237	Help With pattern matching	string case1 = "abcd:xyz:def";\nstring case2 = "def:xyz";\nstring case3 = "xyz:def";\n\nstring result1 = case1.Split(':')[1];\nstring result2 = case2.Split(':')[1];\nstring result3 = case3.Split(':')[0];	0
12692591	12692446	Concatenate DateTime string with Arabic String	var strArabic = "Jim ??? ?????? ????? ??? ?????? ??? John";\nvar strEnglish = dateTime.ToString() ; \nvar LRM = ((char)0x200E).ToString();  // This is a LRM\nvar result = strArabic  + LRM +  strEnglish ;	0
5466295	5465658	C# Converting a DynamicObject to arbitrary type	public class JSObject : DynamicObject\n{\n    class TestClassProxy : TestClass\n    {\n        private dynamic wrapper;\n        public TestClassProxy(dynamic obj)\n        {\n            wrapper = obj;\n            // assign copies of the fields\n            message = obj.message;\n        }\n        // override all required methods and properties\n        public override void SampleMethod()\n        {\n            wrapper.SampleMethod();\n        }\n        public override int SomeValue\n        {\n            get { return wrapper.SomeValue; }\n            set { wrapper.SomeValue = value; }\n        }\n        // etc...\n    }\n\n    public override bool TryConvert(ConvertBinder binder, out object result)\n    {\n        if (binder.Type == typeof(TestClass))\n        {\n            result = new TestClassProxy(this);\n            return true;\n        }\n        // your other conversions\n        return base.TryConvert(binder, out result);\n    }\n    // etc...\n}	0
2417754	2417692	Read a byte from Intptr	obj.byte1 = System.Runtime.InteropServices.Marshal.ReadByte(ip, 0);\nobj.byte2 = System.Runtime.InteropServices.Marshal.ReadByte(ip, 1);	0
24416227	24416151	Regex / C# String - Pseudo Wildcards into an Array	var res = Regex.Matches(targetString, @"%%(.+?)%%").Cast<Match>()\n                    .Select(m => m.Groups[1].Value)\n                    .ToList();	0
20029982	20029942	LINQ query to create a collection of objects combined from a collection of strings	string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };\nvar result = source\n    .Select((element, index) => new { element, index })\n    .GroupBy(x => x.index / 3)\n    .Select(x => new\n    {\n        Id = x.ElementAt(0).element,\n        Name = x.ElementAt(1).element,\n        Value = x.ElementAt(2).element\n    }).ToList();\n\n// at this stage the result variable will represent a list of 3 elements where\n// each element is an anonymous object containing the 3 properties. You could of course\n// replace the anonymous object with a model if you intend to use the result of the query\n// outside of the scope of the method it is being executed in.	0
29818556	29799918	How can I configure Ninject to inject my DbContext for use with ASP.NET Identity Framework?	DependencyResolver.Current.GetService<IMyContext>();	0
7090133	7090058	Can a c# service crash if there is a catch all	AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );	0
13768171	13768170	Write formatted XML output from stored procedure to file	using (XmlReader reader = xmlCommand.ExecuteXmlReader())\n{\n    XmlDocument dom = new XmlDocument();\n    dom.Load(reader);\n\n    var settings = new XmlWriterSettings();\n    settings.Indent = true;\n    settings.OmitXmlDeclaration = true;\n\n    using (var writer = XmlTextWriter.Create("file2.xml", settings))\n    {\n        dom.WriteContentTo(writer);\n    }\n}	0
15055878	15055867	Select specific value from list class	var player = playerList.FirstOrDefault(p => p.Username == "x");\nif(player != null)\n{\n    string id = player.PlayerID;\n}	0
19444546	19444452	How to calculate Total for particular column value?	var total = table.AsEnumerable()\n                 .Sum(dr => dr["col2"] is int ? (int)dr["col2"] : 0);	0
26201269	26201048	Add header property in a Rest call in C#	WebOperationContext webOperationContext = WebOperationContext.Current;\nif (webOperationContext != null)\n{\n    webOperationContext.OutgoingResponse.Headers.Add("X-Version", "1");\n}	0
4950871	4950859	find count of word in sentence	Regex reg = new Regex("\\bdear\\b", RegexOptions.IgnoreCase);\nint count = reg.Matches(input).Count;	0
8561748	8559835	Display Bit (YesNo) Data Type as Checkbox in Access Table	//Added reference to COM Microsoft DAO 3.6\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            DAO.DBEngine dbEng = new DAO.DBEngine(); \n            DAO.Workspace ws = dbEng.CreateWorkspace("", "admin", "", DAO.WorkspaceTypeEnum.dbUseJet); \n            DAO.Database db = ws.OpenDatabase("z:\\docs\\dbfrom.mdb", false, false, "");\n            DAO.TableDef tdf = db.TableDefs["Test"];\n\n            DAO.Field fld = tdf.Fields["AYesNo"];\n            //dbInteger  3 \n            //accheckbox  106 \n            DAO.Property prp = fld.CreateProperty("DisplayControl", 3,106);\n            fld.Properties.Append(prp);\n        }\n    }\n}	0
5445412	5445195	How to determine which UserControl is at the top of a FlowLayoutPanel?	private void flowLayoutPanel1_Scroll(object sender, ScrollEventArgs e) {\n        var top = new Point(1, 1);    // tweak if necessary\n        foreach (Control ctl in flowLayoutPanel1.Controls) {\n            if (ctl.Bounds.Contains(top)) {\n                // Found the control, do your stuff\n                //...\n                break;\n            }\n        }\n    }	0
12547531	12547457	WebClient Upload file with variables posted	webClient.Headers.Add("OurSecurityHeader", "encryptedvalue");	0
8944912	8944801	Custom control size on InitializeComponent()	// Set the width, height you want\nelement.Width = 123;\nelement.Height = 456;\n\n// Force measure/arrange\nelement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); \nelement.Arrange(new Rect(0, 0, element.DesiredWidth, element.DesiredHeight));   \n\n// Subject to sufficient space, the actual width, height will have \n// the values propagated from width/height after a measure and arrange call\ndouble width = element.ActualWidth;\ndouble height = element.ActualHeight;	0
33549429	33548861	Sum a DataGrid column	int amountSum = GetTransactionList().Sum(model => model.TransactionAmount)	0
6067828	6067757	how to cut the string at the time of update in gridview?	string filename = "file1.jpg";\nstring filenameonly=filename.Substring(0,filename.LastIndexOf('.'));	0
7880266	7869262	Unique ID of CreateUSer Button in CreateUserWizard asp.net	"StepNextButtonButton"	0
25059955	25047085	Ignore parent in PreviewMouseButtonDown on TreeviewItem	if (sender is TreeViewItem)\n{\n   Item = sender as TreeViewItem;\n\n    //make sure we have a leaf node, if we dont just move on.\n    if (Item.ItemsSource == null)\n    {\n     //do my stuff\n    }\n}	0
15980358	15978981	How can I locate an invisible menu item?	if (!mnuSetup.MenuItems.Contains(mnuUpdate))\n{\n    mnuSetup.MenuItems.Add(mnuUpdate);\n    UpdateMenuItemSelectable = true;\n}	0
8026464	8026149	Resolving urls from Route Values on server side	var httpContext = new HttpContextWrapper(HttpContext.Current);\nvar urlHelper = new UrlHelper(new RequestContext(httpContext, new RouteData()));\nvar url = urlHelper.Action(Action, Controller, RouteValues);	0
1104966	1104947	Looping Over Dictionary in C#	List<double> total = new List<double>();\nforeach (AKeyObject key in aDictionary.Keys.ToList())\n{\n   for (int i = 0; i < aDictionary[key].Count; i++)\n   {\n      total[i] += aDictionary[key][i];\n   }\n}	0
16075903	16075663	How can I read a C# Console app's entire command line, as it was typed?	Environment.CommandLine	0
28617978	28617725	Is this a DTO or a POCO or a combination of the two C#	public class SomeModel\n{\n    public int SomeModelID { get; set; }\n    public String Name { get; set; }\n}\n\npublic class SomeModelRepository\n{\n    public void Delete(int id)\n    {\n       // delete logic here\n    }\n}	0
6031280	6029932	Import Excel with HTML Format to DataTable	System.Xml.Linq.XDocument html = System.Xml.Linq.XDocument.Load (@"[xls doc]");\n        //this will pull all the Table Headers. \n        var q = from th in html.Descendants ("th") select (string)th.Value;	0
1585264	1579878	C# - Countdown Timer Using NumericUpDown as Interval	//class variable\n    private int totNumOfSec;\n\n    //set the event for the tick\n    //and the interval each second\n    timer1.Tick += new EventHandler(timer1_Tick);\n    timer1.Interval = 1000;\n\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        totNumOfSec = (int)this.numericUpDown1.Value; \n        timer1.Start();\n    }\n\n    void timer1_Tick(object sender, EventArgs e)\n    {\n        //check the timer tick\n        totNumOfSec--;\n        if (totNumOfSec == 0)\n        {\n            //do capture\n            MessageBox.Show("Captured");\n            timer1.Stop();\n        }\n        else\n            label1.Text = "Caputring in " + totNumOfSec.ToString();\n    }	0
30463275	30462528	WPF C# Not Closing Window Correctly - Retains old SQL Data	var wn = new Win2();	0
18241044	18240909	Accessing a network file share with C#	FileInfo myFile = new FileInfo(@"\\server\TPK\some-file-that-exists.pdf");\nbool exists = myFile.Exists;	0
16980828	15549541	get the n latest changelists in a specific period	opchanges.Add("-m n -u edk -s submitted 2010/04/01", "now");	0
20067756	20067670	C# User control with timer starts even in design mode	Timer_Tick(object sender, EventArgs e)\n{\n    if(this.DesignMode)\n       return;\n    //Rest of your code here\n}	0
24040319	24024737	Error with Autofac integration with Web Api	var builder = new ContainerBuilder();\n    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());\n\n    var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();\n    var appAssemblies = assemblies.Where(a => a.ToString().StartsWith("MyCustomer.MyApplicationName") && !a.ToString().Contains("Services")).ToArray();\n    builder.RegisterAssemblyTypes(appAssemblies).AsImplementedInterfaces();\n\n    var container = builder.Build();\n    var resolver = new AutofacWebApiDependencyResolver(container);\n    GlobalConfiguration.Configuration.DependencyResolver = resolver;	0
11883442	11251230	Dundas Charts for ASP.NET - Force chart to show 100%	Chart2.ChartAreas("Default").AxisY.Maximum = 100	0
24035306	24035233	Sort a list in C#	PriorityQueueList=PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();	0
10713817	10713777	Display next set of words in a string	string secondWords = Regex.Match(result.Substring(firstWords.Length).Trim(), regexMatch).Value;	0
4080647	4080557	How to process huge JSON data from Webservice in C#.Net	string jsonData = webservice.Request(params);\nJsonTextReader reader = new JsonTextReader(new StringReader(jsonData));	0
25009409	25008779	Thread to giu delegates with variable number of parameters	this.Invoke(m_dlgtReport, (Object) new Object[] { "text", 101, true });	0
9361030	9360556	open source codeplex library can be used for a commercial purpose?	license.txt	0
10004282	10003497	Getting full sentences from index of word	public static List<string> GetSentencesFromWords(List<string> words, string fileContents)\n    {\n        return fileContents.Split('.')\n            .Where(s => words.Any(w => s.IndexOf(w) != -1))\n            .Select(s => s.TrimStart(' ') + ".")\n            .ToList();\n    }	0
32472554	32471944	How to declare Filter attribute globally in Global.asax.cs file	public class ReplaceTagsAttribute : ActionFilterAttribute\n {\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n       var response = filterContext.HttpContext.Response;\n if (response.Filter == null) return; // <-----\nresponse.Filter = new BundleAndMinifyResponseFilter(response.Filter);\n\n    }\n }	0
8089973	8089929	How to get Sharepoint image in relative url format	var url = "http://sharepointsite.com/images/bob's picture.jpg";\n var basePath = System.IO.Path.GetDirectoryName(url);\n var fileName = System.IO.Path.GetFileName(url);\n var finalPath = basePath + "\\" + Uri.EscapeDataString(fileName);	0
33325372	33325198	Storing range of numbers in a String[] or an array in C#	static int[] SetNum()\n{\n    var initial = Enumerable.Range(1, 100).ToArray();\n    Console.WriteLine(String.Join(", ", initial));\n    return initial;\n}	0
15653405	12780632	Sample code for converting TFS work item to XML?	private TfsTeamProjectCollection GetTfsTeamProjectCollection()\n    {\n        TeamProjectPicker workitemPicker = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false, new UICredentialsProvider());\n        workitemPicker.AcceptButtonText = "workitemPicker.AcceptButtonText";\n        workitemPicker.Text = "workitemPicker.Text";\n        workitemPicker.ShowDialog();\n        if (workitemPicker.SelectedProjects != null || workitemPicker.SelectedProjects.Length > 0)\n        {\n            return workitemPicker.SelectedTeamProjectCollection;\n        }\n        return null;\n    }\n\n    private WorkItemCollection  WorkItemByQuery(TfsTeamProjectCollection projects, string query)  //query is likethis:SELECT [System.ID], [System.Title] FROM WorkItems WHERE [System.Title] CONTAINS 'Lei Yang'\n    {\n        WorkItemStore wis = new WorkItemStore(projects);\n        return wis.Query (query );\n    }	0
17355707	17355474	Parameter is not valid exception while converting Stream to Image	MemoryStream str = new MemoryStream(); \nint offset = 78;              \nstr.Write(b, offset, b.Length - offset);\nImage im = Image.FromStream(str);	0
17727309	17723873	Read Byte Array from a zip file in project folder in WP7	var res = Application.GetResourceStream(new Uri("yourFile", UriKind.Relative));\n\n    var fileStream = res.Stream;\n\n    byte[] buffer = new byte[fileStream.Length];\n\n    fileStream.Read(buffer, 0, (int)fileStream.Length);	0
3260780	3260762	Can I cast from a generic type to an enum in C#?	return (T)(object)value;	0
29693154	29692878	Return the same value for multiple function calls while a request is ongoing using async/await	private object padLock = new object();\nprivate Task<int> executingTask;\npublic async Task<int> GetValue() \n{  \n    lock(padLock)\n    {\n        if (executingTask  == null || executingTask.IsCompleted)\n            executingTask= GetValueFromServer();\n    }\n\n    var value = await executingTask;\n    return value;\n}	0
5431175	5431136	How to set Unicode character as Content of Label in the code-behind?	FalsePositiveInput.Content = "\u2713";	0
31304055	31303897	How do I change a value in the ModelState, so that it will be valid, using ASP.NET MVC?	ModelState.SetModelValue("PropertyID", new ValueProviderResult("New value", "", CultureInfo.InvariantCulture));	0
10645435	10645419	How to split items into columns (MVC3)	int i = 1; \n@foreach (var answer in @question.Answers) {\n   @Html.CheckBox("answer_CheckBox_" + answer.ID.ToString(), false, new { @id = answer.ID });  \n   <label style="margin-left: 0.5em;">@answer.Title</label>\n\n   i % 3 == 0 ? <br/> : ""\n   i++\n}	0
18275438	18275386	How to automatically delete records in sql server after a certain amount of time	SQL Job	0
29436984	29436899	Output images from "subfolders" in Windows Azure Blobs	blob prefix	0
1580658	1580136	Binding a POCO to an html document and generating the result to a string	class Program\n{\n    static void Main(string[] args)\n    {\n        Velocity.Init();\n\n        // Define a template that will represent your HTML structure.\n        var template = "<html><body><div>$key1</div><div>$key2.ToString('dd/MM/yyyy')</div></body></html>";\n        var context = new VelocityContext();\n        // The values you are passing here could be complex objects with many properties \n        context.Put("key1", "Hello World");\n        context.Put("key2", DateTime.Now);\n        var sb = new StringBuilder();\n        using (var writer = new StringWriter(sb))\n        using (var reader = new StringReader(template))\n        {\n            Velocity.Evaluate(context, writer, null, reader);\n        }\n        Console.WriteLine(sb.ToString());\n        // This will print: <html><body><div>Hello World</div><div>16/10/2009</div></body></html>\n    }\n}	0
6719304	6719293	Defining a working directory for executing a program (C#)	string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\nDirectory.SetCurrentDirectory(exeDir);	0
11735914	11735673	How to Retrieve XML using Linq Lambda?	IEnumerable<Customers> Customers = XDocument.Load("Customers.xml").Element("Customers")\n  .Descendants("Customer")\n    .Select(x => new Customers\n    {\n        Name = x.Element("Name").Value,\n        City = x.Element("City").Value,\n        Address = x.Element("Address").Value\n    });	0
4371824	4367899	How to detect a tag applied to a text in Gtk# TextView's?	TextIter.Tags	0
7480618	7480518	Programmatically detach debugger	BOOL WINAPI DebugActiveProcessStop(\n  __in  DWORD dwProcessId\n);\n\n\n[DllImport("kernel32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\npublic static extern bool DebugActiveProcessStop([In] int Pid );	0
8109163	8108976	Join two list comparing their elements properties	var q = from person in list1.Concat(list2)\n        group person by person.ID into g\n        select g.OrderByDescending(p => p.ChangeDate).First();	0
21889055	21888646	How to write data to an XML file?	XDocument doc = new XDocument();     \nXElement xml = new XElement("Info",\n    new XElement("Password", password),\n    new XElement("UserName", userName));\ndoc.Add(xml);\ndoc.Save(path);	0
122948	122821	ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call	protected override void OnLoad(EventArge e)\n { base.OnLoad(e);\n   EnsureChildControls();\n\n   var linkButtons = from c in AfterPageRepeater.Controls\n                                                .OfType<RepeaterItem>()\n                     where c.HasControls()\n                     select c into ris\n                        from lb in ris.OfType<LinkButton>()\n                        select lb;\n\n   foreach(var linkButton in linkButtons)\n    { linkButton.Click += PageNavigateButton_Click\n    }                          \n }	0
6860766	6860590	how to group many rows into one row?	var list = new List<KeyValuePair<int, string>>() {\n           new KeyValuePair<int, string>(1, "test1"),\n           new KeyValuePair<int, string>(1, "test2"),\n           new KeyValuePair<int, string>(2, "test1"),\n           new KeyValuePair<int, string>(2, "test2"),\n           new KeyValuePair<int, string>(2, "test3"),\n           new KeyValuePair<int, string>(3, "test1"),\n           new KeyValuePair<int, string>(4, "test1"),\n           new KeyValuePair<int, string>(4, "test2"),\n        };\n\n        var result = (from i in list\n                      group i by i.Key into g\n                      select new\n                      {\n                          Key = g.Key,\n                          Values = string.Join(", ", (from k in g\n                                                      select k.Value))\n                      });\n\n        foreach (var x in result)\n        {\n            Console.WriteLine(x.Key + " - " + x.Values);\n        }	0
4546155	4042345	Problem with skipping empty cells while importing data from .xlsx file in asp.net c# application	int offset = GetColDiff(lastCol, cell.CellReference);\n\n     //filling empty columns\n     while (offset-- > 1)\n        dt.Rows[rowCounter][cnt++] = DBNull.Value;\n     //filling regular column\n     dt.Rows[rowCounter][cnt++] = value;\n\n   lastCol = cell.CellReference;\n\n******************\n//calculating column distance\n    int GetColDiff(string prev, string curr)\n    {\n        int i=0;\n        int index1 = 0;\n        int index2 = 0;\n\n        while (prev!="0" && prev.Length>i && Char.IsLetter(prev[i]))//prev=="0"-startingcondition\n        {\n            index1 += ('Z' - 'A' + 1) * index1 + (prev[i] - 'A');\n            i++;\n        }\n        i = 0;\n        while (curr.Length>i && char.IsLetter(curr[i]))\n        {\n            index2 += ('Z' - 'A'+ 1) * index2 + (curr[i] - 'A');\n            i++;\n        }\n        return index2 - index1;\n    }	0
7204826	7194364	ASP.NET simple custom control with two way binding	private double _value = 0;\n    [\n    Bindable(true, BindingDirection.TwoWay),\n    Browsable(true),\n    DefaultValue(0),\n    PersistenceMode(PersistenceMode.Attribute)\n    ]\n    public double Value\n    {\n        get\n        {\n            double d = 0;\n            Double.TryParse(ValueControlTextBox.Text,out d);\n            return d;\n        }\n        set\n        {   \n            ValueControlTextBox.Text = String.Format("{0:0.00}", value);\n            _value = value;\n        }\n    }	0
18194337	18128307	How to pass a parameter in an expectation to the return value in Rhino Mocks?	var mockA = MockRepository.GenerateMock<IA>();\nmockA\n    .Stub(x => x.DoSomething(Arg<IC>.Is.Anything))\n    .Do((Func<IC, IB>)(arg => new B(arg)))\n    .Return(null);	0
33423672	33422165	How to Navigate to a user control on load?	regionManager.RegisterViewWithRegion("RegionName", typeof(View));	0
6266626	6266520	c# object to xml, rest service	XmlSerializer x = new XmlSerializer(d.GetType(), "http://www.eysnap.com/mPlayer");\nXmlSerializerNamespaces ns = new XmlSerializerNamespaces();\nns.Add(String.Empty, "http://www.eysnap.com/mPlayer");	0
5668594	5668569	I am using reflection to get property names and values in ASP.NET need some advice on optimization	public static class PropertyCache<T>\n{\n    public static SomeType SomeName { get { return someField; } }\n    static PropertyCache() {\n        // init someField\n    }\n}\n...\nvar foo = PropertyCache<Foo>.SomeName;	0
32229877	32229648	How to dereference ParameterType for parameters passed by ref	GetElementType()	0
571464	571457	Deleting a file in C#	foreach (string item in TempFilesList)\n{\n    path = System.Web.HttpContext.Current.Application["baseWebDomainUrl"] + "/temp/" + item;\n    path = Server.MapPath(path);\n    fileDel = new FileInfo(path);\n    fileDel.Delete();\n}	0
18999176	18998741	Check if animation is at the edge of screen in winform	private void playerTimer_Tick(object sender, EventArgs e)\n{\n    for (int i = 0; i < 6; i++)\n    {\n        if (PlayersActive[i])\n        {\n            Players[i].Move(randomNumber.Next(3,10));\n\n            // EDIT BELOW in the if statement!\n            // if the edge of the picture touches the end of the screen.\n            if (Players[i].X + Players[i].Image.Width >= this.Width)\n                MessageBox.Show("Congrats! Player" + i.ToString() + "won!");\n\n            //Players[i].X is the X cordinates(The length) from the left side of the winform.\n            //Players[i].Image.Width is the width of the picture ofcourse :D.\n            // if X cordinates + picture width is greater than or equal to screen width. YOU WON :D\n        }\n    }\n    this.Invalidate();\n}	0
17955966	17955753	Inserting data from a WPF form into a MySQL database via C#	cmd.CommandText = "INSERT INTO TestSubject (Subject,DOB) VALUES (@subjectId, @subjectDOB)";	0
10034789	10033743	xml to listbox from webservice	XDocument xDoc = XDocument.Load(url);\nvar students = xDoc.Descendants("Student")\n    .Select(n => new\n    {\n        StudentNo = n.Element("StudentID").Value,\n        Firstname = n.Element("FirstName").Value,\n        Surname = n.Element("LastName").Value\n    })\n    .ToList();\n\ndataGridView1.DataSource = students;	0
30097329	30089042	TypeLoadException using Moq on internal interface in signed assembly	// This assembly is the default dynamic assembly generated Castle DynamicProxy, \n// used by Moq. Paste in a single line.   \n[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]	0
3096223	3095695	Serializable vs Data Contract vs Nothing at all in a WCF Service	[DataContract]	0
31618683	31618584	Regex - Match If Not Before a Character	(?<!\.)\bSize\b(?!")	0
9926533	9926398	How to check the type of a list if inheritance is used	if (checkTask is Note)\n{\n\n}\n...	0
14487554	14487495	How to write a class to return textbox control	class Search\n{\n    public static TextBox FindControl(string controlToFind, Page page)\n    {\n         //find your text box\n    } \n}	0
27102651	22383035	Selenium Webdriver unable to access web element on Internet Explorer 8 - shown as disabled	IWebElement searchField = Global.driver.FindElement(by);\nbuilder.Click(searchField).SendKeys(searchField, textToEnter).Perform();	0
21494846	21494790	Add New Row at Middle of Gridview	DataRow row = table.NewRow();\ntable.Rows.InsertAt(row, 5);	0
4587780	4587729	Loops inside loops	void recursiveCall(int currentLevel)\n{\n if (currentLevel == 0)\n   return;\n\n for (int i0 = 0; i0 < 6; i0++)\n {\n    level = 0;\n    value = i0;\n    method();\n    if (next)\n      recursiveCall(currentLevel - 1);\n }\n}	0
12481393	12481189	WPF: Byte array to Image on a button in code behind	ImageBrush brush;\nBitmapImage bi;\nusing (var ms = new MemoryStream(myByteArray))\n{\n    brush = new ImageBrush();\n\n    bi = new BitmapImage();\n    bi.BeginInit();\n    bi.CreateOptions = BitmapCreateOptions.None;\n    bi.CacheOption = BitmapCacheOption.OnLoad;\n    bi.StreamSource = ms;\n    bi.EndInit();\n}\n\nbrush.ImageSource = bi;\nbutton.Background = brush;	0
17139195	17139078	MVC4 Web API Return json propertykey strings with special characters	public class MyClass\n        {\n            [JsonProperty(".Class1 #Id1")]\n            public string id1 { get; set; }\n            [JsonProperty(".Class1 #Id2")]\n            public string id2 { get; set; }\n        }	0
850136	849299	Get all (Properties.Resources) to be stored in a Dictionary	ResourceManager rm = Properties.Resources.ResourceManager;\n\nResourceSet rs = rm.GetResourceSet(new CultureInfo("en-US"), true, true);\n\nif (rs != null)\n{\n   var images = \n     from entry in rs.Cast<DictionaryEntry>() \n     where entry.Value is Image \n     select entry.Value;\n\n   foreach (Image img in images)\n   {\n     // do your stuff\n   } \n}	0
32907609	32907574	How to remove element from Dictionary that uses Tuple	var dict = new Dictionary<Tuple<string, string>, string>();\ndict.Add(new Tuple<string, string>("a", "b"), "c");\ndict.Remove(new Tuple<string, string>("a", "b"));\n\nSystem.Diagnostics.Debug.Assert(dict.Count == 0);	0
8976538	8975750	Xml response file: Received in browser, not via C#	string httpResponse = "";\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);\n\nWebResponse response = null;\nStreamReader reader = null;\ntry\n{\n    response = request.GetResponse();\n}\ncatch (WebException ex)\n{\n    response = ex.Response;\n}\n\nreader = new StreamReader(response.GetResponseStream());\nhttpResponse = reader.ReadToEnd();	0
2197453	2197417	Hide a Folder Using Silverlight 4	File.SetAttributes(@"..\foo\bar", FileAttributes.Hidden);	0
9926818	9926703	Entity Framework. SQL Group By to EF Group By	.GroupBy( x => new \n               {\n                  month = x.CreatedDate.Month,\n                  year = x.CreatedDate.Year,\n                  ...\n               });	0
34415737	34399803	how to display custom text in data bound GridViewComboBoxColumn	void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)\n    {\n        if (e.Column.Name == "column2" && e.Row.Cells["someColumn"].Value == something)\n        {\n            e.CellElement.Text = "some text";\n        }\n        else\n        {\n            e.CellElement.ResetValue(LightVisualElement.TextProperty, ValueResetFlags.Local);\n        }\n    }	0
12334025	12333892	how to write to beginning of file with Stream Writer?	string path = Directory.GetCurrentDirectory() + "\\test.txt";\n        string str;\n        using (StreamReader sreader = new StreamReader(path)) {\n            str = sreader.ReadToEnd();\n        }\n\n        File.Delete(path);\n\n        using (StreamWriter swriter = new StreamWriter(path, false))\n        {\n            str = "example text" + Environment.NewLine + str;\n            swriter.Write(str);\n        }	0
8448654	8448539	Display Format String to User	public static string ToUserFriendlyDateFormat(this string unfriendlyFormat) {\n    return unfriendlyFormat\n        .Replace("{0:", string.Empty)\n        .Replace("}", string.Empty);\n}	0
30390235	30389742	How to connect c# windows application with online access database	string connectionString = \n    @"Provider=Microsoft.Jet.OLEDB.4.0;" +\n    @"Data Source="Path of you hosting provider database";" +\n    @"User Id= "hosting db user id];Password=[hosting db password";";\n\nstring queryString = "SELECT Foo FROM Bar";\n\nusing (OleDbConnection connection = new OleDbConnection(connectionString))\nusing (OleDbCommand command = new OleDbCommand(queryString, connection))\n{\n    try\n    {\n        connection.Open();\n        OleDbDataReader reader = command.ExecuteReader();\n\n        while (reader.Read())\n        {\n            Console.WriteLine(reader[0].ToString());\n        }\n        reader.Close();\n    }\n    catch (Exception ex)\n    {\n        Console.WriteLine(ex.Message);\n    }\n}	0
3419442	3419341	How to calculate turning direction	public Direction GetDirection(Point a, Point b, Point c)\n{\n    double theta1 = GetAngle(a, b); \n    double theta2 = GetAngle(b, c);\n    double delta = NormalizeAngle(theta2 - theta1);\n\n    if ( delta == 0 )\n        return Direction.Straight;\n    else if ( delta == Math.PI )\n        return Direction.Backwards;\n    else if ( delta < Math.PI )\n        return Direction.Left;\n    else return Direction.Right;\n}\n\nprivate Double GetAngle(Point p1, Point p2)\n{\n    Double angleFromXAxis = Math.Atan ((p2.Y - p1.Y ) / (p2.X - p1.X ) ); // where y = m * x + K\n    return  p2.X - p1.X < 0 ? m + Math.PI : m ); // The will go to the correct Quadrant\n}\n\nprivate Double NormalizeAngle(Double angle)\n{\n    return angle < 0 ? angle + 2 * Math.PI : angle; //This will make sure angle is [0..2PI]\n}	0
13232760	13161767	Allow GridView sorting in Composite Control	protected override void Render(HtmlTextWriter writer)\n    {\n        if (innerGridView.HeaderRow != null)\n        {\n            for (int i = 0; i < innerGridView.HeaderRow.Cells.Count; i++)\n            {\n                innerGridView.HeaderRow.Cells[i].Attributes["onclick"] =\n                    Page.ClientScript.GetPostBackClientHyperlink(innerGridView, "Sort$" + InnerGridViewDataTable.Columns[i].Caption, true);\n            }\n        }\n\n        base.Render(writer);\n    }	0
16243109	16241751	Can't connect to Windows ServiceBus via HTTPS	ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;	0
1705230	1705223	Does Decrypting a cookie convert it to local time?	return ticket.Expiration.ToUniversalTime().Ticks;	0
19170949	19170722	Union or concat custom data in Entity Framework	var countries = (from c in GE.Countrys \n                 select new {Id = c.Id,Name = c.Name}).ToList();\n\ncountries.Add(new {Id = "00000000-0000-0000-0000-000000000000", Name = "All"});	0
16054146	16054090	Serialize char data type with XmlSerializer	[XmlIgnore]\npublic char TestProperty { get; set; }\n\n[XmlElement("Test"), Browsable(false)]\npublic string TestPropertyString {\n    get { return TestProperty.ToString(); }\n    set { TestProperty = value.Single(); }\n}	0
4146834	4146804	Xml serialization c#	[XmlElement]	0
3967571	3952811	Extract some Elements with LinqToXML from GPX-File for Geocaching	var cache = from e in gpx.Descendants(ns + "wpt")\n            select new\n            {\n                Name = e.Element(ns + "name").Value\n            };	0
11219878	11219692	How to reload page after 3 login attempts with 401 unauthorised access error? in asp.net	Declare @PasswordDB varchar(100)\nDeclare @InvalidDB int\nif exists(select 1 from tblUser where email=@email)\nbegin\n    set @PasswordDB= (Select password from tblUser where email=@email)\n    if @PasswordDB=@Password\n        begin\n                print'login Successfully.'\n        end\n    else\n        begin\n            set @InvalidDB=(select invalidattempts from tblUser where email=@email)\nupdate tblUser set invalidAttepmts=@InvalidDB+1 where email=@email \nselect 3\nend\nend\nelse\nbegin\nselect 2\nprint'username does not exists.'\nend	0
8112949	7858926	Capture Schema Information when validating XDocument	List<XElement> errorElements = new List<XElement>();\n\nserializedObject.Validate((sender, args) =>\n{\n    var exception = (args.Exception as XmlSchemaValidationException);\n\n    if (exception != null)\n    {\n        var element = (exception.SourceObject as XElement);\n\n        if (element != null)\n            errorElements.Add(element);\n     }\n\n});\n\nforeach element in errorElements\n{\n    var si = element.GetSchemaInfo; \n\n    // do something with SchemaInfo\n}	0
21146575	21146522	Best Practices with IF statement in Catch block	public static void addSomething(int id)\n{\n    string msg = getStringMsg(id);\n    try\n    {\n        //do lots of stuff\n        Console.WriteLine(msg)\n    }\n    catch (Exception e)\n    {\n        string errorMessage = (id == 1) ? \n           "Exception msg 1: " : "Exception msg 2: ";\n\n        throw new FooException(errorMessage + msg, e);\n    }\n}	0
3600036	3600006	Unboxing uint/int without knowing what's inside the box	int x = (o is int) ? (int)o : (int)(uint)o;	0
627259	627250	Host Page - User control communication ASP.NET	class MyPage : Page\n{\n    public string MyProperty;\n}\n\nclass MyUserControl : UserControl\n{\n    void Page_Load(object sender, EventArgs e)\n    {\n        ((MyPage)this.Page).MyProperty //casts Page as the specific page\n    }\n}	0
13915834	13915205	Retrieving nodes from xml document based on date	var xDoc = XDocument.Load("aa.xml");\nDateTime passedDate  = new DateTime(2010,11,11);\n\nvar books = xDoc.Descendants("book")\n              .Where(b=>DateTime.ParseExact(b.Element("release_date").Value,"yyyy-MM-dd",CultureInfo.InvariantCulture)>passedDate)\n              .ToList();	0
15988928	15988856	how to make rar file of full folder using c#	string cmdArgs = string.Format("A {0} {1} -ep -r",\n        String.Format("\"{0}\"", rarPackagePath),\n        fileList);	0
8360201	8360162	Read Excel in windows server	Provider=Microsoft.Jet.OLEDB.4.0;\n       Data Source=C:\MyExcel.xls;\n       Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";	0
888077	887802	How to select across a relationship using LINQPad?	where i.Links.Any(link => link.link_component_code == "x")	0
2849624	2849203	how to change mschart label arrow color	chartArea1.AxisX.MajorTickMark.LineColor = System.Drawing.Color.Red;\n        chartArea1.AxisX.MinorTickMark.LineColor = System.Drawing.Color.Red;	0
10209639	10209382	Check for Ajax Request	xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");	0
8373408	8372041	How to check if a Texture2D is transparent?	bool IsRegionTransparent(Texture2D texture, Rectangle r)\n{\n    int size = r.Width * r.Height;\n    Color[] buffer = new Color[size];\n    texture.GetData(0, r, buffer, 0, size);\n    return buffer.All(c => c == Color.Transparent);\n}	0
10491541	10489676	How to return 302 redirect from Web service environment	/// <summary>\n/// POST /movies\n/// \n/// returns HTTP Response => \n///     201 Created\n///     Location: http://localhost/ServiceStack.MovieRest/movies/{newMovieId}\n///     \n///     {newMovie DTO in [xml|json|jsv|etc]}\n/// \n/// </summary>\npublic override object OnPost(Movie movie)\n{\n    var newMovieId = DbFactory.Exec(dbCmd => {\n        dbCmd.Insert(movie);\n        return dbCmd.GetLastInsertId();\n    });\n\n    var newMovie = new MovieResponse {\n        Movie = DbFactory.Exec(dbCmd => dbCmd.GetById<Movie>(newMovieId))\n    };\n\n    return new HttpResult(newMovie) {\n        StatusCode = HttpStatusCode.Created,\n        Headers = {\n            { HttpHeaders.Location, this.RequestContext.AbsoluteUri.WithTrailingSlash() + newMovieId }\n        }\n    };\n}	0
25300	25297	Reserved Keyword in Enumeration in C#	public enum Test\n{\n    @as = 1,\n    @is = 2\n}	0
4266070	4266008	Endless loop in a code sample on serialization	public override XmlObjectSerializer CreateSerializer(\n  Type type, string name, string ns, IList<Type> knownTypes)\n{\n    return new DataContractSerializer(type, name, ns, knownTypes,\n        0x7FFF /*maxItemsInObjectGraph*/,\n        false/*ignoreExtensionDataObject*/,\n        true/*preserveObjectReferences*/,\n        null/*dataContractSurrogate*/);\n}\n\npublic override XmlObjectSerializer CreateSerializer(\n  Type type, XmlDictionaryString name, XmlDictionaryString ns,\n  IList<Type> knownTypes)\n{\n    return new DataContractSerializer(type, name, ns, knownTypes,\n        0x7FFF /*maxItemsInObjectGraph*/,\n        false/*ignoreExtensionDataObject*/,\n        true/*preserveObjectReferences*/,\n        null/*dataContractSurrogate*/);\n}	0
32104812	32104099	Lambda Expression for Not In a Collection	query = query.Where(e => e.validTrip == true && e.eProfile.Documents.Any(a=>a.DocumentTypeCode == "Passport" && a.ExpiryDate.HasValue && a.ExpiryDate.Value > DateTime.Now && e.Country!=d.Country));	0
25398956	25398860	Key Value pair regex confirmation	var dic=Regex.Matches(data, regex).Cast<Match>()\n             .ToDictionary(m=>m.Groups["name"].Value,m=>m.Groups["value"].Value);	0
31545327	31544966	WPF: How to get instance of a control in code declared in a resource xaml file	ToolBar toolBar = FindResource("MainWindowToolbar") as ToolBar;	0
21400093	21400045	Downloading multiple files at the same time and continue after all files finished downloading	var tasks=new List<Task>();\nforeach (var File in ServerFiles)\n{\n    string sFileName = File.Uri.LocalPath.ToString();\n    // some internal logic and initialization \n    Task downloadTask = oBlob.DownloadToStreamAsync(fileStream);\ntasks.Add(downloadTask);\n    sFiles += sFileName.Replace("/" + Container + "/", "") + ",";\n}\nTask.WaitAll(tasks);\n//Continue here	0
34012207	33864139	Is it normal for parallel processing to make UI stutter	Graphics.DrawImage()	0
8763110	8762678	Database connection pooling with multi-threaded service	//Assuming mySemaphore is a semaphore instance, e.g. \n// public static Semaphore mySemaphore = new Semaphore(100,100);\ntry {\n  mySemaphore.WaitOne(); // This will block until a slot is available.\n  DosomeDatabaseLogic();\n} finally {\n  mySemaphore.Release();\n}	0
18982249	18980135	how do i add items in combobox?	private void button4_Click(object sender, EventArgs e)\n    {\n\n        List<DateTime> lstDate = new List<DateTime>();\n        DateTime dt = DateTime.Now;\n        for (int i = 0; i < 20; i++)\n        {\n            lstDate.Add(dt);\n        }\n\n        List<string> lstDataSource = lstDate.Select(a => a.ToString("M/dd/yyyy")).ToList();\n        lstDataSource.Insert(0, "---Select Date---");\n        comboBox1.DataSource = lstDataSource;            \n        comboBox1.FormattingEnabled = true;\n\n    }	0
4679673	4679589	Whats wrong with my log4net configuration?	appender.ActivateOptions();	0
9143615	9143537	How to remove Symmetry from Cartesian product via Linq?	var IndexedStuff = Stuff.Select((item,index) => new { Item = item, Index = index});\n var result = (from a in IndexedStuff\n               from b in IndexedStuff\n               where a.Index < b.Index\n               select new { A = a.Item, B = b.Item });	0
15998210	15997942	Download to file and save to byte array	// declare file/memory stream here\nwhile ((len = stream.Read(buffer, 0, buffer.Length)) > 0)\n{\n      memoryStream.Write(buffer, 0, len);\n      fileStream.Write(buffer, 0, len);\n      // if you need to process "len" bytes, do it here\n}	0
2884565	2884551	Get individual query parameters from Uri	var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]\nSystem.Web.HttpUtility.ParseQueryString(queryString)	0
1215206	1215198	C# Copy Array by Value	interface ICloneable<T>\n{\n    T Clone();\n}\n\npublic static class Extensions\n{\n    public static T[] Clone<T>(this T[] array) where T : ICloneable<T>\n    {\n        var newArray = new T[array.Length];\n        for (var i = 0; i < array.Length; i++)\n            newArray[i] = array[i].Clone();\n        return newArray;\n    }\n    public static IEnumerable<T> Clone<T>(this IEnumerable<T> items) where T : ICloneable<T>\n    {\n        foreach (var item in items)\n            yield return item.Clone();\n    }\n}	0
11865050	11560521	Changing DataVisualization.Chart size without using WinForms	Chart1.Size = new Size(1000, 1000);	0
22227344	22226966	Parsing XML - LINQ to XML or any other method	var elements = XElement.Parse(xml);\n\n var files = elements.Element("project").Element("checkpoints").Element("checkpoint").Element("files").Elements("file").ToList();\n\n  var file_name = files[0].Attribute("file_name");\n  var M5 = files[0].Element("metrics").Elements("metric").Where(x => x.Attribute("id").Value.Equals("M5")).First().Value;\n  var M6 = files[0].Element("metrics").Elements("metric").Where(x => x.Attribute("id").Value.Equals("M6")).First().Value;	0
26632381	26632269	Prevent dictionary from modifications	class MyImmutableRefClass\n{\n    public readonly object ReferenceStrig;\n    public readonly int IntegerValue;\n\n    public MyImmutableRefClass(): this("Initialized string", 100)\n    {\n    }\n\n    public MyImmutableRefClass(string referenceStrig, int integerValue)\n    {\n        ReferenceStrig = referenceStrig;\n        IntegerValue   = integerValue;\n    }\n}	0
10569507	10569430	How do I extract a LinkedListNode<T> from a LinkedList<T>	var ranges = new LinkedList<ContiguousDataValue>();\n\nfor (var recentNode = ranges.First;\n     recentNode != null;\n     recentNode = recentNode.Next)\n{\n  var range = recentNode.Value; \n  ranges.AddAfter(recentNode,someNewNode);\n}	0
11955199	11954959	How can I know the index of a XML Tag	var userContacts = doc2.Root\n                       .Descendants()\n                       .Where(element => element.Name == "Contact")\n                       .Select((c, i) => new {Contact = c, Index = i});\n\nforeach(var indexedContact in userContacts)\n{\n     // indexedContact.Contact\n     // indexedContact.Index                 \n}	0
15255032	15254940	Get a list of resource text files	using System.Collections;\nusing System.Resources;\nusing System.Globalization;\n\nResourceSet resourceSet = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);\nforeach (DictionaryEntry entry in resourceSet)\n{\n    if (entry.Value is string)\n    {\n        if (entry.Value.ToString().Contains(x)) { /* etc. */ }\n    }\n}	0
26417779	26416252	restsharp how to add key value pair as parameter	const string baseUrl = "https://api.stripe.com/";\n  const string endPoint = "v1/charges";\n  var apiKey = this.SecretKey;\n\n  var client = new RestClient(baseUrl) { Authenticator = new HttpBasicAuthenticator(apiKey, "") };\n  var request = new RestRequest(endPoint, Method.POST);\n\n  request.AddParameter("card", token);\n  request.AddParameter("amount", wc.totalToPayForStripe);\n  request.AddParameter("currency", "eur");\n  request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);\n  request.AddParameter("metadata[cartid]", wc.crt.cartid);\n  request.AddParameter("metadata[oid]", wc.co.oid);\n  request.AddParameter("statement_description", "# " + wc.crt.cartid);\n  request.AddParameter("description", wc.crt.cartid + " - " + wc.co.oid);	0
13936739	13935492	MVC4 model binding to a dictionary (breaking change?)	[HttpGet]\npublic ActionResult Index()\n{\n    return View();\n}\n\n[HttpPost]\npublic ActionResult Index(IDictionary<long?, string> someData)\n{\n    if (ModelState.IsValid)\n    {\n        // do some stuff here...\n    }\n    return View();\n}	0
13952484	13952425	How to convert XML to Dictionary	var xdoc = XDocument.Load(path_to_xml);\n_dictionary = xdoc.Descendants("data")\n                  .ToDictionary(d => (string)d.Attribute("name"),\n                                d => (string)d);	0
34374589	34371065	c# how to call functions from function table?	MethodInfo handler = GetType.GetMethod("NameMethod");\nhandler.Invoke(context, new object[] {parameters}	0
28184200	28165490	Making POST API request via c# with hashed API Key	using (var client = new WebClient())\n            {\n                var values = new NameValueCollection();\n                values["api_key"] = "xxxx11112222333";\n                values["url"] = @"http://www.codeproject.com";\n                string destination = @"https://internalurl/api/shorten";\n                var response = client.UploadValues(destination, values);\n                var responseString = Encoding.Default.GetString(response);\n                MessageBox.Show(responseString);\n            }	0
2168519	2167943	WPF: Show Property Change without implementing INotifyPropertyChanged interface	public class ClosedSourceObjectViewModel : ViewModelBase\n{\n    private ClosedSourceObject ClosedSourceObject\n    {\n        get;\n        set;\n    }\n\n    public bool SomeProperty\n    {\n        get { return this.ClosedSourceObject.SomeProperty; }\n        set\n        {\n            if (value != this.ClosedSourceObject.SomeProperty)\n            {\n                RaisePropertyChanging("SomeProperty");\n                this.ClosedSourceObject.SomeProperty = value;\n                RaisePropertyChanged("SomeProperty");\n            }\n        }\n    }\n}	0
22236652	22235693	Turn JSON into a C# List of objects	using System;\nusing System.Collections.Generic;\nusing System.Web.Script.Serialization;\n\nnamespace ConsoleApplication1 {\n\n\n   class Program {\n\n      [Serializable]\n      public class ContactsListResult {\n         public string Contact { get; set; }\n         public int ContactID { get; set; }\n      } //\n\n      [Serializable]\n      public class CList {\n         public List<ContactsListResult> ContactsListResult = new   List<ContactsListResult>();\n      } //\n\n      static void Main(string[] args) {\n         string s = "{\"ContactsListResult\":[{\"Contact\":\"Fred Smith\",\"ContactID\":25},{\"Contact\":\"Bill Wilson\",\"ContactID\":45}]}";\n\n         JavaScriptSerializer lSerializer = new JavaScriptSerializer();\n         CList lItems = lSerializer.Deserialize<CList>(s);\n\n         foreach (ContactsListResult lItem in lItems.ContactsListResult) Console.WriteLine(lItem.Contact + " " + lItem.ContactID);\n\n         Console.ReadLine();\n      } //\n\n   } // class\n} // namespace	0
2250876	2250749	Add a control on a form, from another Thread	private void AddButton() { \n        if(this.InvokeRequired){\n            this.Invoke(new MethodInvoker(this.AddButton));\n        }\n        else {\n           Random random = new Random(2);\n           Thread.Sleep(20);\n           Button button = new Button();\n           button.Size = new Size(50,50);\n           button.Location = new Point(random.Next(this.Width),random.Next(this.Height));\n           this.Controls.Add(button);\n        }\n    }	0
8093879	8093670	how to migrate doubles and dates from System.Data.OracleClient to ODP.NET?	Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");	0
8812114	7491834	Send two packets (one with length and one with data) or send one concatenated packet?	//Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.\nSocket.Send Method (IList<ArraySegment<Byte>>, SocketFlags)	0
11318659	11294138	adding ASPxGridView to page with ObjectDataSource programmtically	gridLookup.Columns.Add(new GridViewDataColumn("Name"));\n  gridLookup.AutoGenerateColumns = false;	0
9268125	9267786	Getting value from MVC3 Action	using (WebClient client = new WebClient())\n{\n   string value = client.DownloadString("http://www.yoursite.com/Home/GetSomeValue");\n}	0
31809525	31809435	Get List of available Verbs (file association) to use with ProcessStartInfo in c#	startInfo = new ProcessStartInfo(fileName);\n\n    if (File.Exists(fileName))\n    {\n        i = 0;\n        foreach (String verb in startInfo.Verbs)\n        {\n            // Display the possible verbs.\n            Console.WriteLine("  {0}. {1}", i.ToString(), verb);\n            i++;\n        }\n    }	0
6260978	6260941	Get the data between tags in a xml file	var doc = XDocument.Parse(result);\nvar sw = doc.Descendants("viewport").Elements("southwest").SingleOrDefault();\nif (sw != null)\n{\n    var lat = (double)sw.Element("lat");\n    var lng = (double)sw.Element("lng");\n    // do stuff\n}	0
3356083	3356050	How to return a Enum value from a string?	public static TResult ParseEnum<TResult>(this string value, TResult defaultValue)\n    {\n        try\n        {\n            return (TResult)Enum.Parse(typeof(TResult), value, true);\n        }\n        catch (ArgumentException)\n        {\n            return defaultValue;\n        }\n    }	0
635757	635751	Getting rid of null/empty string values in a C# array	yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);	0
27391774	27391735	C# regular expression for American phone numbers with hyphens	using System.Text.RegularExpressions;\n...\n\npublic bool IsValidPhone(string input)\n{\n    return Regex.IsMatch(input, @"^[0-9]{3}-[0-9]{3}-[0-9]{4}$");\n}	0
12899095	12898263	Read text content from XElement	XElement t = XElement.Parse("<tag>Alice &amp; Bob<other>cat</other></tag>");\n string s = (t.FirstNode as XText).Value;	0
15840193	15836903	Writing to Azure Table Storage with BeginExecute	var result = _table.BeginExecute(op,\n    new AsyncCallback(onTableExecuteComplete), entity);\nresult.AsyncWaitHandle.WaitOne();	0
34253433	34251442	Best way to split files into UDP packet sized chunks for peer to peer file sharing?	List<Tuple<int, int>>	0
4371652	4371514	Get selected DataGridViewRows in currently displayed order	List<DataGridViewRow> l = new List<DataGridViewRow>();\nforeach (DataGridViewRow r in dgv.Rows)\n{\n    l.Add(r);\n}\n\nl.Sort((x, y) =>\n    {\n        IComparable yComparable = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;\n        IComparable yc = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;\n\n        if (dgv.SortOrder == SortOrder.Ascending)\n            return yc.CompareTo(yComparable);\n        else\n            return yComparable.CompareTo(yc);\n    }\n    );\n\nforeach(DataGridViewRow r in dgv.SelectedRows)\n{\n    int selectedIndex = l.IndexOf(r);\n}	0
26946948	26946821	Add item to collection of selected item of listbox	((style)this.all_styles.SelectedItem).Add(new subject("item"));	0
8696826	8696639	How to get the full root directory of a ContentManager in XNA 4.0	using System.IO;\nusing System.Windows.Forms;\n\n//blah blah\nstring GetAppDir()\n{\n    return Path.GetDirectoryName(Application.ExecutablePath);\n}	0
24476203	24466523	How to bold strings in a text	string pattern = @"<strong>(.*?)</strong>";\n       var matches = Regex.Matches(paragraf2.Range.Text, pattern)\n               .Cast<Match>()\n               .Select(m => m.Groups[1].Value)\n               .ToList();\n       Word.Find findObject = Application.Selection.Find;\n       foreach( string a in matches){ \n            findObject.ClearFormatting();\n            findObject.Text = a;\n            findObject.Replacement.ClearFormatting();\n            findObject.Replacement.Font.Bold = 1;\n            object replaceAll = Word.WdReplace.wdReplaceAll;\n            findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);  \n           }	0
17768036	17767990	Starting threads in a loop passing array elements to each	void ThreadsStarter()\n{\n    double[] data = new double[4];\n\n    for(int i = 0; i < 4; i++)\n    {\n        var temp = i;\n        Thread my_thread = new Thread(() => Work(ref data[temp]));\n        my_thread.Start();\n    }\n}\n\nvoid Work(ref double data)\n{\n}	0
23220049	23219956	Change items position in List<string>	var item = reg[0];\nreg.Remove(item); //Removes the specific item\nreg.Add(item); //add's an item to the end of the list	0
29947642	29933279	C# Outlook 2013 Addin Accessing Explorer	if(File.Exists(path)) \n        {\n            // This path is a file\n            ProcessFile(path); \n        }               \n        else if(Directory.Exists(path)) \n        {\n            // This path is a directory\n            ProcessDirectory(path);\n        }\n        else \n        {\n            Console.WriteLine("{0} is not a valid file or directory.", path);\n        }	0
25164363	25163186	Parsing for escape characters with a regular expression	(?<!\\),	0
13802442	13802382	Base constructor in base class instead of derived class in C#	public abstract class Foo\n{\n    protected Foo(int a, int b, int c)\n    {\n        this.a = a;\n        this.b = b;\n        this.c = c;\n    }\n\n    public abstract void doStuff();\n}\n\npublic class Bar : Foo\n{\n    public Bar(int a, int b, int c) : base(a, b, c)\n    {\n    }\n\n    public override void doStuff()\n    {\n        //does stuff\n    }\n}\n\n\npublic class BarY : Foo\n{\n    public BarY(int a, int b, int c) : base(a, b, c)\n    {\n    }\n\n    public override void doStuff()\n    {\n        //does stuff\n    }\n}	0
29262055	29261798	Create XML from multiple CSV's in multiple folders	XElement audxml = new XElement("root");\n\nforeach (string file in AudioXMLFiles)\n    {\n        string[] lines2 = File.ReadAllLines(file);\n       XElement filexml = new XElement("root",\n       from str in lines2\n       let columns = str.Split(',')\n       select new XElement("recording_info",\n               new XElement("recorded_accound_id", columns[1]),\n               new XElement("date_created_ts", String.Format("{0:####-##-##  ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))),                                    \n               new XElement("recorded_cid", columns[9]),//1\n               new XElement("recording_tag", columns[1]),\n               new XElement("filename", columns[1] + "_" + columns[2] + "_" + columns[3]),\n               new XElement("record", columns[3]),//Record in TimeoutException format\n               new XElement("from_caller_id", columns[10] + "  <" + columns[8] + ">")\n           ));\n\n           audXml.Add(fileXml);\n    }\n    audxml.Save(@"C:\XMLFile.xml");	0
18365162	18365089	Get parameter's value of a Data Annotation	private string GetPermissionFilerValue()\n    {\n        object[] attributes = typeof(YourControllerType).GetType().GetMethod("Index").GetCustomAttributes(typeof (PermissionFilterAttribute));\n\n        return attributes[0].Roles;\n    }	0
14839189	14839029	Designing a blocking method until a value in the dictionary changes	private static AutoResetEvent resetEvent = new AutoResetEvent(false); \n\nstatic void WaitForOpenSpot()\n{  \n    resetEvent.WaitOne();\n}\n\nstatic void ChangeStatus(string str, int val)\n{\n   Transfer[str] = val;\n   if (val == 1)\n   {\n       resetEvent.Set();\n   }\n}	0
1644126	1644107	Last day of year same week as first day of next year	DayOfWeek day = new DateTime(someYear, 12, 31).DayOfWeek;\nif(day < DayOfWeek.Saturday)\n   // January 1st must be within the same week	0
8601677	8571177	AWS .NET SDK Multipart File Upload from Http	// Create request to upload a part.\n        UploadPartRequest uploadRequest = new UploadPartRequest()\n            .WithBucketName(myBucket)\n            .WithKey(myKey)\n            .WithUploadId(myUploadId)                \n            .WithPartNumber(partNumber);\n\nuploadRequest = (UploadPartRequest)uploadRequest.WithInputStream(ftiObject.sourceStream);	0
25672585	25653326	C# WPF Pause processing until button has been pressed	while (AlertIsActive)\n    {\n        if (this.Dispatcher.HasShutdownStarted ||\n            this.Dispatcher.HasShutdownFinished)\n        {\n            break;\n        }\n\n        this.Dispatcher.Invoke(\n            DispatcherPriority.Background,\n            new ThreadStart(delegate { }));\n        Thread.Sleep(20);\n    }	0
15037919	15037550	How to send parameters to Subreport in Crystal Reports	objReportDocument.SetParameterValue("@QuoteID", ValQuoteID,objReportDocument.Subreports[0].Name.ToString());	0
22958955	22958605	Constant field at compiletime	public class ClassFieldNamePrefixes : BaseIntrospectionRule\n    {\n        public ClassFieldNamePrefixes() :\n            base("ClassFieldNamePrefixes", "TutorialRules.TutorialRules",\n                typeof (ClassFieldNamePrefixes).Assembly)\n        {\n        }\n\n        public override ProblemCollection Check(Member member)\n        {\n            if (!(member.DeclaringType is ClassNode))\n                return this.Problems;\n\n            Field fld = member as Field;\n            if (fld == null)\n                return this.Problems;\n\n            if (fld.IsLiteral && \n                fld.IsStatic && \n                field.Flags.HasFlag(FieldFlags.HasDefault))\n            {\n            ....\n            }\n\n            return this.Problems;\n        }\n    }	0
3537475	3533820	Replacing a db4o stored object with an instance of a subclass	IObjectContainer container = ... //\nforeach(var oldObject in container.Query<MyType>())\n{\n     NewSubType newCopy = copyToSubType(oldObject); // copy the data\n\n     var referencesFromTypeA = from TypeA a in container\n                               where a.ReferenceToMyType == oldObject\n                               select a\n     // repeat this for all types which can refer to the object which are copied\n     // it can certainly be generified\n     foreach(var referenceToUpdate in referencesFromTypeA)\n     {\n            referenceToUpdate.ReferenceToMyType=newCopy;\n            container.Store(referenceToUpdate);\n     }\n     container.Store(newCopy);\n     container.Delete(oldObject);\n}	0
16924381	16923904	How to put a ContextMenu into the header of a TabPage	public class MyTabControl : TabControl\n{\n\n    protected override void OnMouseUp(MouseEventArgs e)\n    {\n        if (e.Button == System.Windows.Forms.MouseButtons.Right)\n        {\n            for (int i = 0; i < TabCount; ++i)\n            {\n                Rectangle r = GetTabRect(i);\n                if (r.Contains(e.Location) /* && it is the header that was clicked*/)\n                {\n                    // Change slected index, get the page, create contextual menu\n                    ContextMenu cm = new ContextMenu();\n                    // Add several items to menu\n                    cm.MenuItems.Add("hello");\n                    cm.MenuItems.Add("world!");\n                    cm.Show(this, e.Location);\n                    break;\n                }\n            }\n        }\n        base.OnMouseUp(e);\n    }\n\n}	0
23419304	23419284	Copying Clipboard Text to ListBox	string text = Clipboard.GetText(TextDataFormat.Text);\nlstTarget.Items.AddRange(text.Split("\n")));	0
5422633	5422522	getting webservice's ApplicationPool	ServerManager manager = new ServerManager();\nmanager.ApplicationPools[\n    manager.Sites["yoursite"].Applications["servicePath"].ApplicationPoolName].\n    Enable32BitAppOnWin64 = true;	0
13194200	13194159	Custom InitialDirectory C# using app.config	sd .InitialDirectory = ConfigurationManager.AppSettings[key].ToString();	0
20644723	20644589	Dynamically changing image in a picturebox	System.Windows.Forms.Timer timer;\n\npublic Form1()\n{\n    InitializeComponent();\n    this.Controls.Add(pb);\n\n    timer = new System.Windows.Forms.Timer();\n    timer.Interval = 1000;\n    timer.Tick += (sender, args) => {\n        if (pb.ImageLocation == @"E:\folder\gas_jo.png")\n        {\n            pb.ImageLocation =@"E:\folder\gas_jo_1.png";\n        }\n        else if (pb.ImageLocation == @"E:\Real-time_Imi\gas_jo_1.png")\n        {\n            pb.ImageLocation = @"E:\Real-time_Imi\gas_jo.png";\n        }\n    };\n    timer.Start();\n}\n\nPictureBox pb = new PictureBox\n{\n    Location = new Point(0, 0),\n    SizeMode = PictureBoxSizeMode.Zoom,\n    Size = new Size(300,300),\n    ImageLocation = @"E:\folder\gas_jo.png"\n};	0
8142631	8142403	Navigating a Web Page and Submitting Data	private static string GetWebText(string url)\n    {\n        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);\n\n        request.UserAgent = "A .NET Web Crawler";\n\n        WebResponse response = request.GetResponse();\n        Stream stream = response.GetResponseStream();\n        StreamReader reader = new StreamReader(stream);\n        string htmlText = reader.ReadToEnd();\n\n        return htmlText;\n    }	0
23271671	23271635	Specify initial capacity of each list that store in the list array	static List<string>[] myList = new List<string>[1000];      \n\n// in static constructor:\nfor(int i = 0; i<myList.Length; i++)\n{\n  myList[i] = new List<string>(500);\n}	0
31026291	31022973	How to pass the some of values from the textbox grid to another page	Label TotalPrice = default(Label);\nTotalPrice.text = Session["Cart"].ToString	0
18069452	18069429	how to use linq to retrieve values from a 2 dimensional generic list	var smallestGroup = traysWithExtraAisles\n    .GroupBy(x => x.count)\n    .OrderBy(g => g.Key)\n    .First();\n\nforeach(var x in smallestGroup)\n{\n    var poolTray = x.tray;\n}	0
21518887	21518850	How to convert this SQL statement to ESQL	var idList = new List<int> { 1,2,3 };\ndbContext.MyList.Where(x => idList.Contains(x.ID))\n                .ToList()\n                .ForEach(x => x.Archived = true);\ndbContext.SaveChanges();	0
5586956	5586839	Matching a string with and without quotes with Regex	try \n{\n    Regex regex = new Regex(@"grep (.*?)( \||$)");\n    Match grepStrings = regex.Match(commandline);\n    while (grepStrings.Success) \n    {\n        // matched text: grepStrings.Value\n        // match start: grepStrings.Index\n        // match length: grepStrings.Length\n        grepStrings = grepStrings.NextMatch();\n    } \n} \ncatch (ArgumentException ex)\n{\n    // Syntax error in the regular expression\n}	0
33143839	33143522	c# filter listbox with textbox	private void textBox10_TextChanged(object sender, EventArgs e)\n    {\n        d2ngList.Items.Clear();\n        foreach(Games game in HandlerClass.Instance.Games)\n        {\n            if (!string.IsNullOrEmpty(textBox10.Text))\n            {\n                if (game.Name.Contains(textBox10.Text))\n                    d2ngList.Items.Add(game.Name);\n            }\n            else\n                d2ngList.Items.Add(game.Name);\n        }\n       // games.Where(item => filterList.Contains(item));\n    }	0
12709028	12708886	How to get the "Date" of an email?	message.Headers["Date"];	0
17052389	17048817	Windows Phone keyboard comma - dot conflict	private void txt_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)\n    {\n        if (e.Key == System.Windows.Input.Key.Unknown)\n        {\n            txt.Text = txt.Text.Replace('.', ',');\n\n            // reset cursor position to the end of the text (replacing the text will place\n            // the cursor at the start)\n            txt.Select(txt.Text.Length, 0);\n        }\n    }	0
2692579	2692544	Algorithm to see if keywords exist inside a string	IEnumerable<string> tweets, keywords;\n\nvar x = tweets.Select(t => new\n                           {\n                               Tweet = t,\n                               Keywords = keywords.Where(k => k.Split(' ')\n                                                               .All(t.Contains))\n                                                  .ToArray()\n                           });	0
30882958	30882884	How to check if my application is the Windows activate form	[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]\nprivate static extern IntPtr GetForegroundWindow();\n[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]\nprivate static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);\n\npublic static bool Activates()\n{\n    var x = GetForegroundWindow();\n    if (x == IntPtr.Zero) {\n        return false;      \n    }\n\n    var y = Process.GetCurrentProcess().Id;\n    int i;\n    GetWindowThreadProcessId(x, out i);\n\n    return i == y;\n}	0
13922395	13922327	C# control array as a method overload	private void IncreaseStat() {\n    foreach (TextBox textBox in this.Controls.OfType<TextBox>().Where(x => x.Name.Contains("stamina") || \n            x.Name.Contains("skill") || \n            x.Name.Contains("Luck"))) {\n        textBox.Text = "Altered";\n    }\n}	0
32509028	32466954	WPF DataGridCheckBoxColumn's state doesn't get updated from the ViewModel	namespace Example.Client.ExampleService\n{\n    public partial class Search // the rest of the definition is in Reference.cs\n    {\n        private bool _isSelected;\n\n        public bool IsSelected\n        {\n            get { return _isSelected; }\n            set\n            {\n                _isSelected = value;\n                RaisePropertyChanged("IsSelected");\n            }\n        }\n    }\n}	0
4973587	4973530	Extracting excel worksheet into a string in C#	Excel.Application oXL= new Excel.Application();\noXL.Visible = true;\nExcel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));\nExcel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet;\nstring s = (string)oSheet.Cells[1, 1].Value;	0
11357471	11357418	Get index from several columns in listView	ListView.FullRowSelect	0
10926578	10926538	calling a Asp.net web API from c# with multiple of parameters	var webClient = new WebClient();\nwebClient.Headers["Content-Type"] = "application/json";\nwebClient.Headers["X-JavaScript-User-Agent"] = "Google APIs Explorer";\n\nvar json = Newtonsoft.Json.JsonConvert.SerializeObject(new { longUrl = url });\nvar data = webClient.UploadString("https://www.googleapis.com/urlshortener/v1/url?pp=1", json);	0
11425067	11425033	image path into sql database	string strQuery = "UPDATE curriculum SET imagen = @imgPicture WHERE Nombre = ???";	0
16028558	15917991	How to parser JavaScript multidimensional array to c# array?	// using\nusing Newtonsoft.Json.Linq;\n\n\nstring JSarray_1 = @"[[""string 1"", 2013, ""string 2""], ""string 3"", [""string 4"", , ""string 5""]]";\nJObject j = JObject.Parse("{\"j\":" + JSarray_1 + "}");\nMessageBox.Show((string)j["j"][0][2]); // "string 2"	0
5988007	5987743	How to fetch data according to my search in a grid.. Help in the code please	DataGrid.DataSource = Fillgrid("title","description","keyword");\nDataGrid.Bind();	0
19568414	19567143	Set C# Picturebox to Bitmap	Bitmap img = new Bitmap(eventArgs.Frame);\n  if (pbImg.Image != null) pbImg.Image.Dispose();\n  pbImg.Image = img;	0
11726819	11726717	Checking for specific email addresses using data annotations	[RegularExpression( @"@(gmail|yahoo|live)\.com$", ErrorMessage = "Invalid domain in email address. The domain must be gmail.com, yahoo.com or live.com")]\npublic string EmailAddress { get ; set ; }	0
28536550	28536365	Row to column conversion	declare @x table \n(\n   A int,\n   B varchar(2),\n   C varchar,\n   D varchar,\n   E varchar,\n   F varchar\n)\n\ninsert into @x\nvalues\n(1, 'AA', 'a','b','v','d'),\n(2, 'BB', 'e','f','g','h')\n\nSELECT A,B,Col as C,letter as a\nFROM \n   (SELECT A,B,C,D,E,F\n   FROM @x) p\nUNPIVOT\n   (Letter FOR Col IN \n      (C,D,E,F)\n)AS unpvt;	0
17298291	17298034	Converting WriteableBitmap to Bitmap in C#	private System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)\n{\n  System.Drawing.Bitmap bmp;\n  using (MemoryStream outStream = new MemoryStream())\n  {\n    BitmapEncoder enc = new BmpBitmapEncoder();\n    enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));\n    enc.Save(outStream);\n    bmp = new System.Drawing.Bitmap(outStream);\n  }\n  return bmp;\n}	0
26023297	26001490	WPF MetroTheme = Icon Ressources	Install-Package MahApps.Metro	0
17678417	17664368	How to update a jira issue summary though the rest api using restsharp	public void SetJiraIssue(string issueKey, JiraIssue j)\n    {\n        RestRequest request = new RestRequest("issue/{key}", Method.PUT);\n        request.AddUrlSegment("key", issueKey);\n        request.RequestFormat = DataFormat.Json;\n\n        string jSonContent = @"{""fields"":{""summary"":""test changing summary""}}";\n        request.AddParameter("application/json", jSonContent, ParameterType.RequestBody);\n\n        var response = Execute(request);\n        Console.WriteLine(response);\n    }	0
14255051	14254831	Removing additional namespace definition in WCF SOAP message	xmlns:ns1="http://soaptest.webapi-beta.gratka.pl/dom.html"	0
30063929	30063677	How do I use regex to validate my string?	^[A-Z]{2}\d{3}	0
27129047	27128988	If statements on negative decimal values ranges	if(value >= -80 && value <= -60) {\n  doWork();\n}	0
24675582	24615484	MessageBox changes something seemingly unrelated	void MyUserControl_VisibleChanged(object sender, EventArgs e)\n{\n    UserControl us = sender as UserControl;\n    this.BeginInvoke(new Action(() => {\n        if (us.Visible)\n        {\n            CustomCommand();\n        }\n    });\n}	0
33109699	31706472	Extract an embedded xml file from a DICOM using MyDICOM	//  Set up the stream\nobject elem = element.Get(0);\nif (elem is DeferredStream)\n     stream = elem as DeferredStream;\nelse if (elem is MemoryStream)\n     stream = elem as MemoryStream;\n\n//  Set up the stream reader\nreader = new MyDicom.StreamReader(stream, dicom.MetaData.Tsn);\nreader.UseDeferredStream = (elem is DeferredStream);\nreader.EnforceEvenByteSizeElement = dicom.EnforceEvenByteSize;\nif (dicom.PrivateDictionary != null)\n     reader.PrivateDictionary = dicom.PrivateDictionary;\n\n//  Read the Stream into a String\nbyte[] read = reader.ReadBytes(Convert.ToInt32(stream.Length));\nString data = System.Text.Encoding.Default.GetString(read);\nint start = data.IndexOf("<PatientData>");\nint length = data.Substring(start).IndexOf("</PatientData>") + 15;\n\nif (start > 0 && length > 0)\n     result = data.Substring(start, length);\nelse\n     result = "";	0
25563199	25542172	Fluent assertions: Assert one OR another value	public static void BeAnyOf(this StringAssertions assertions, string[] expectations, string because, params string[] args) {\n    Execute.Assertion\n           .ForCondition(expectations.Any(assertions.Subject.Contains))\n           .BecauseOf(because, args)\n           .FailWith("Expected {context:string} to be any of {0}{reason}", expectations);\n}	0
26364225	26364083	Getting value and name from Enum in foreach loop	dic[Key] = row[key.ToString()].ToString();	0
3232184	3231541	Simple 2D rocket dynamics	Drag = angle*drag_coefficient*velocity + base_drag\nSideForce = angle*lift_coefficent*velocity	0
25690813	25686105	Telerik RadGrid - Get Value from column on ItemUpdate event	protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)\n{\n    GridEditableItem item = e.Item as GridEditableItem;\n\n    int Id = Convert.ToInt32(item.GetDataKeyValue("Id").ToString());\n    //Access edit row ID value here -- using datakey\n\n    string Name = (item["Name"].Controls[0] as TextBox).Text;\n    // Get Name field updated value here\n\n    int index = item.ItemIndex;\n    // Access edit row index here\n}	0
21637443	21637378	delete rows in datagridview	for (int rows = CPTData.Rows.Count - 2; rows >=0; --rows)\n{\n  double SampleDepth =(double)System.Convert.ToSingle(CPTData.Rows[rows].Cells[0].Value);\n  if (SampleDepth > (double)System.Convert.ToSingle(analysisDepth.Text))\n  {\n    CPTData.Rows.RemoveAt(rows);\n  }\n}	0
18358202	18355009	MassTransit is messing with my string data	[TestFixture]\npublic class IsoDateSerializationTest\n{\n    [Test]\n    public void Test()\n    {\n        JToken jtoken = JObject.Parse(@"{ IsoDate: ""1994-11-05T13:15:30Z"" }");\n        Type deserializeType = typeof (MessageWithIsoDate);\n        JsonSerializer serializer = new JsonSerializer();\n        object obj;\n\n        using (var jsonReader = new JTokenReader(jtoken))\n        {\n            obj = serializer.Deserialize(jsonReader, deserializeType);\n        }\n\n        MessageWithIsoDate msg = obj as MessageWithIsoDate;\n        Assert.That(msg.IsoDate, Is.EqualTo("1994-11-05T13:15:30Z"));\n    }\n}\n\npublic class MessageWithIsoDate\n{\n    public String IsoDate { get; set; }\n}	0
777033	769995	Debugging a release version of a DLL (with PDB file)	[System.Diagnostics.DebuggerStepThrough]\npublic class MyClass {\n    public void Test() { ... }\n}	0
3695185	3695163	FileStream and creating folders	string fileName = @"C:\Users\SomeUser\My Documents\Foo\Bar\Baz\text1.txt";\n\nDirectory.CreateDirectory(Path.GetDirectoryName(fileName));\n\nusing (FileStream fs = new FileStream(fileName, FileMode.Create))\n{\n    // ...\n}	0
15847993	15831680	Datagridview context menu always shows -1 in hittest	private void dgvResults_MouseClick(object sender, MouseEventArgs e)\n{\n  if (e.Button == MouseButtons.Right)\n  {\n    int currentMouseOverRow = dgvResults.HitTest(e.X, e.Y).RowIndex;\n    dgvResults.ClearSelection();\n    if (currentMouseOverRow >= 0) // will show Context Menu Strip if not negative\n    {\n      dgvResults.Rows[currentMouseOverRow].Selected = true;\n      cmsResults.Show(dgvResults, new Point(e.X, e.Y));\n       row = currentMouseOverRow;\n    }\n  }\n}	0
21584780	21584735	C# get character after a character from a string	string dex = "ab43kjh43434v34b";\nvar dex1 = String.Join("", dex.Where((c,i) => i % 2 == 1));	0
30345245	30341718	Increment a sum total with DispatchTimer C# WPF	private decimal grandTotal = 0;\n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n        decimal costperSec = 0.095703125m;\n        decimal total = costperSec + costperSec;\n        grandTotal += decimal.Add(total, costperSec);\n        // Forcing the CommandManager to raise the RequerySuggested event\n        CommandManager.InvalidateRequerySuggested();\n        lblSeconds.Content = grandTotal;\n        //For testing\n        //lblSeconds.Content = "-" + "$" + DateTime.Now.Second;\n}	0
13990590	13988751	How to handle Ctrl + Break or Ctrl + Pause in windows application	void myForm_KeyDown(object sender, KeyEventArgs e)\n{\n  if(e.KeyCode == Keys.Cancel) //Control + Pause\n  {\n    //Code for showing message goes here\n  }\n}	0
9812697	9812650	Application hashing for updated versions of software	-- v1.0\n-- v1.1\n-- v2.0\n-- v2.1	0
694450	690587	Using WebClient in C# is there a way to get the URL of a site after being redirected?	class MyWebClient : WebClient\n{\n    Uri _responseUri;\n\n    public Uri ResponseUri\n    {\n        get { return _responseUri; }\n    }\n\n    protected override WebResponse GetWebResponse(WebRequest request)\n    {\n        WebResponse response = base.GetWebResponse(request);\n        _responseUri = response.ResponseUri;\n        return response;\n    }\n}	0
7435616	7435487	How get range of numbers	public List<Range> getValidRanges(Range total, List<Range> banned)\n{\n  List<Range> valid = new ArrayList<Range>();\n  int start = total.getStartTime();\n  for(Range range: banned)\n   {\n     valid.add(new Range(start,banned.getStart()));\n     start = banned.getEnd();\n   }\n   valid.add(new Range(start,total.getEnd()));\n   return valid;\n}	0
22442429	22430687	MvvmCross Android: Binding lost after screen rotation	[Activity (ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize | ConfigChanges.KeyboardHidden)]	0
23232730	23200318	Store list of pairs in one table EF	public class Vertice\n{\n    public int VerticeID { get; set; }\n\n    [NotMapped]\n    public Point[] Data\n    {\n        get\n        {\n            string[] rawInternalData = this.VerticeDataText.Split(';');\n            Point[] dataResult = new Point[rawInternalData.Length / 2];\n            int count = 0;\n            rawInternalData.ToList().ForEach(p =>\n            {\n                var pairArray = p.Split(',');\n                dataResult[count++] = new Point { X = double.Parse(pairArray[0]), Y = double.Parse(pairArray[1])};\n            });\n            return dataResult;\n        }\n        set\n        {\n            StringBuilder sb = new StringBuilder();\n            value.ToList().ForEach(p => sb.AppendFormat("{0},{1};", p.X, p.Y));\n            this.VerticeDataText = sb.ToString();\n        }\n    }\n\n    public string VerticeDataText { get; set; }\n}	0
21690479	21690176	Get Specific String from huge text in C#	const string input = @"\n  ""standard_resolution"": {\n  ""url"": ""http://distilleryimage3.s3.amazonaws.com/59d6984092a211e392db12e25f465f4f_8.jpg"",\n  ""width"": 640,\n  ""height"": 640\n  }";\n\nvar pattern = @"\""standard_resolution\"".*?\""url\""\:\s\""(?<url>.*?)\""";\n\nvar urls = Regex.Matches(input.Replace("\r\n", string.Empty), pattern)\n    .Cast<Match>()\n    .Select(each => each.Groups["url"].Value);\n\nvar count = urls.Count();	0
13579243	13579027	RegEx: Match same string into 2 named groups	string MyString = "<a href=\"magnet:?xt=urn:btih:7f3befa467c4cac0787286c87ea264a0606066f5&dn=some.file.name.zip&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80\" title=\"Download this torrent using magnet\">...</a>[Some unwanted stuff here]<a href=[Another]>";\n\nMatchCollection MyMatches = Regex.Matches(MyString, "(?<URL>magnet:\\?.*(&dn=(?<File>[^&]+)).*?)(?:\"|')");           \nforeach(Match MyMatch in MyMatches)\n{\n    MessageBox.Show(MyMatch.Groups["URL"].Value);\n    MessageBox.Show(MyMatch.Groups["File"].Value);\n}	0
10735616	10735200	How to search via Entity Framework on objects and their children?	SqlFunctions.StringConvert((double)c.Id)	0
18470029	18469925	Adding new content to a session	protected void ddlClient_SelectedIndexChanged(object sender, EventArgs e)\n    {\n    int x = int.Parse(ddlClient.SelectedValue);\n\n    DataSet ds = GetRowFromDatabase( x);\n\n    //the first time initialize the session variable\n    if(Session["old"] == null)\n    {\n        Session["old"] = ds;\n    }\n    else\n    { \n        ((DataSet)Session["old"]).Merge(ds);\n    }\n\n    gridview.DataSource = Session["old"] ;\n    gridview.DataBind();\n\n}	0
20496593	20496396	How to change the color of content text in code behind	public ActionResult index()\n{\nreturn Content(@"<html>\n<head>\n<title>Thanks!</title>\n<style type="""text/css""">\n.alert\n{\ncolor:red;\n}\n</style>\n</head>\n<body>\n<p class="""alert""">Thanks - we'll see you there!</p>\n</body>\n</html>");\n}	0
10142649	10138223	How to create a Report Library?	site.Lists.Add("MyLibrary", \n    "MyLibrary", \n    "MyLibrary", \n    "{2510d73f-7109-4ccc-8a1c-314894deeb3a}", \n    433, \n    "101");	0
19655480	19655229	Load items from file and split them into array	string line;\n\nSystem.IO.StreamReader file = new System.IO.StreamReader(@"d:\\textFile.txt");\n\nwhile ((line = file.ReadLine()) != null)\n{\n    string output = "";\n    //replacing all ';' with space\n    output = line.Replace(";", " ");\n    StringBuilder sb = new StringBuilder(output);\n    //replacing character after number with ':'\n    sb[1] = ':';\n    output = sb.ToString();\n    MessageBox.Show(output);\n}\n\nfile.Close();	0
30578883	30578723	Getting minimum date from a list of records with date columns	var minRecord = records.Where(t => t.OriginalAppDate.HasValue).\n                        OrderBy(t => t.OriginalAppDate).FirstOrDefault();	0
27815608	27815362	How to convert isolated memory into File Storage in C#?	string fileContent = string.Empty;\n\n//Read file within IsolatedStorage\nusing (IsolatedStorageFile storage = IsolatedStorageFile.GetStore((IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly | IsolatedStorageScope.User), null, null))\n{\n   using (StreamReader reader = new StreamReader(storage.OpenFile("ReadMe.txt", FileMode.Open)))\n    {\n       fileContent = reader.ReadToEnd();\n    }\n}\n\n//Write to a textfile\nFile.WriteAllText(@"File path", fileContent);	0
28321862	28318664	How to properly notify the datagrid that its data set is outdated?	public class Car\n{\n  public string Model;\n  public int Speed;\n}\n\nclass MyViewModel: INotifyPropertyChanged\n{\n  List<Car> cars;\n\n  public List<Car> Cars { get {return cars;}}\n\n  // this method is invoked from GUI, ie from an event handler or a Command of a "Reload" button\n  public void ReloadData()\n  {\n    // do something to actually refresh cars\n\n    // notify GUI something changed\n    InternalPropertyChanged("Cars");\n  }\n\n  public event PropertyChangedEventHandler PropertyChanged;\n  protected void InternalPropertyChanged(string name)\n  {\n    if (PropertyChanged != null)\n      PropertyChanged(this, new PropertyChangedEventArgs(name));\n  }\n}	0
23686747	23686049	How to return difference value from Compare method? C#	while( !expected.Compare(actual, 5.0))\n {\n     const int numberOfMillisecondsToSleep = 1000;\n     System.Threading.Thread.Sleep(numberOfMillisecondsToSleep);\n }	0
13530663	13529301	Load bitmapImage from base64String	public async Task<BitmapImage> GetImage(string value)\n    {\n        if (value == null)\n            return null;\n\n        var buffer = System.Convert.FromBase64String(value);\n        using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())\n        {\n            using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))\n            {\n                writer.WriteBytes(buffer);\n                await writer.StoreAsync();\n            }\n\n            var image = new BitmapImage();\n            image.SetSource(ms);\n            return image;\n        }\n    }	0
19360105	19351473	DispatcherTimer doesn't work in Console	[TestMethod]\n    public void TestMethod1()\n    {\n        Action test = () =>\n            {\n                var dailyAlarm = new DailyAlarm(DateTime.Now.AddSeconds(5.0));\n                dailyAlarm.DailyAlarmEvent += dailyAlarm_DailyAlarmEvent;\n                dailyAlarm.Start();\n            };\n\n        DispatcherHelper.ExecuteOnDispatcherThread(test, 20);\n    }\n\n    void dailyAlarm_DailyAlarmEvent(EventArgs e)\n    {\n        // event invoked when DispatcherTimer expires\n    }	0
18015628	18013765	How to cancel HttpClient GET Web request	protected async override void OnNavigatedTo(NavigationEventArgs e)\n{\n    await HttpGetRequest();\n}\n\npublic CancellationTokenSource cts = new CancellationTokenSource();\nprivate async Task HttpGetRequest()\n{\n    try\n    {\n        DateTime now = DateTime.Now;\n        var httpClient = new HttpClient();\n        var message = new HttpRequestMessage(HttpMethod.Get, "https://itunes.apple.com/us/rss/toppaidapplications/limit=400/genre=6000/json");\n        var response = await httpClient.SendAsync(message, cts.Token);\n        System.Diagnostics.Debug.WriteLine("HTTP Get request completed. Time taken : " + (DateTime.Now - now).TotalSeconds + " seconds.");\n    }\n    catch (TaskCanceledException)\n    {\n        System.Diagnostics.Debug.WriteLine("HTTP Get request canceled.");\n    }\n}\n\nprivate void btnCancel_Click(object sender, RoutedEventArgs e)\n{\n    cts.Cancel();\n}	0
1090987	1090974	How to convert delegate to object in C#?	class Mathematician {\npublic delegate int MathMethod(int a, int b);\n\npublic int DoMaths(int a, int b, MathMethod mathMethod) {\nreturn mathMethod(a, b);\n}\n}\n\n[Test]\npublic void Test() {\nvar math = new Mathematician();\nMathematician.MathMethod addition = (a, b) => a + b;\nvar method = typeof(Mathematician).GetMethod("DoMaths");\nvar result = method.Invoke(math, new object[] { 1, 2, addition });\nAssert.AreEqual(3, result);\n}	0
21219451	21219403	Clearing WebBrowser Control Passwords in C#	private void button1_Click(object sender, EventArgs e)\n{\n    clearIECache();\n}\n\nvoid clearIECache()\n{\n    ClearFolder(new DirectoryInfo(Environment.GetFolderPath\n       (Environment.SpecialFolder.InternetCache)));\n}\n\nvoid ClearFolder(DirectoryInfo folder)\n{\n\n        foreach (FileInfo file in folder.GetFiles())\n        {\n            try\n            {\n                file.Delete();\n            }\n            catch (Exception ex) // files used by another process exception\n            {\n\n            }\n        }\n        foreach (DirectoryInfo subfolder in folder.GetDirectories())\n        {\n            ClearFolder(subfolder); \n        }\n\n}	0
6303852	3334702	Read validation message from external library	RVTest.ErrorMessage =MyLibrary.ValidationMessages.RequiredField;	0
13109141	13109015	Get all subfolders without using pre-built .net objects	private List<string> GetAllFolders()\n{\n    DirectoryInfo directoryInfo = new DirectoryInfo(this.sourceFolder);\n    List<string> allFolders = new List<string>();\n\n    foreach (DirectoryInfo subDirectoryInfo in directoryInfo.GetDirectories(("*.*", SearchOption.AllDirectories))\n    {\n        //logic\n        allFolders.Add(subDirectoryInfo.FullName);\n    }\n    return allFolders;\n}	0
11850129	11850084	Waiting for nested BackgroundWorkers to complete	Private Sub BackgroundWorkerMaster_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorkerMaster.DoWork\n    Do While bgwChild1.IsBusy AndAlso bgwChild2.IsBusy\n        System.Threading.Thread.Sleep(1) 'wait for a small amount of time\n    Loop\nEnd Sub	0
10335162	10335089	Checking each item in IEnumerable<List<int>>	var nested = new List<List<int>>();\n// put data in it\n\nnested.All((inner) => inner.Any());	0
13256385	13255832	Console application closes immediatly after opening in visual studio	using System;\n\nclass Program {\n    static void Main(string[] args) {\n        Console.WriteLine("Working on it...");\n        //...\n        Console.WriteLine("Done");\n        PressAnyKey();\n    }\n\n    private static void PressAnyKey() {\n        if (GetConsoleProcessList(new int[2], 2) <= 1) {\n            Console.Write("Press any key to continue");\n            Console.ReadKey();\n        }\n    }\n\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    private static extern int GetConsoleProcessList(int[] buffer, int size);\n}	0
12485780	12485691	C# Function that converts a string to a dictionary	var dict = x.Split('/').SelectMany(s => s.Split('|')).ToDictionary(t => t.Split(',')[0], t => t.Split(',')[1]);	0
20957053	20921727	Update EF5 Model ConnectionString in Runtime	public partial class MyContext: DbContext\n{\n    public MyContext(string efConnectionString):base(efConnectionString)\n    {\n\n    }\n\n    public static MyContext CreateContextFromAdoCS(string adoConnectionString)\n    {\n        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();\n\n        //Set the provider name.\n        entityBuilder.Provider = "System.Data.SqlClient";\n\n        // Set the provider-specific connection string.\n        entityBuilder.ProviderConnectionString = adoConnectionString;\n\n        // Set the Metadata location.\n        entityBuilder.Metadata = @"res://*/MyModel.csdl|\n                        res://*/MyModel.ssdl|\n                        res://*/MyModel.msl";\n        var efCs = entityBuilder.ToString();\n\n        return new MyContext(efCs);\n    }\n}	0
2074081	2073982	C# help to set a Row Css class of a Grid View	private DateTime _previousRowDateTime;\nprivate string[] _commentRowClasses = {"commentRow", "altCommentRow"};\nprivate int _commentRowClassesIndex = 0;\n\nprivate string SetRowColor()\n{\n  if( _AddDate != _previousRowDateTime ) \n  {\n    _commentRowClassesIndex = ( _commentRowClassesIndex + 1 ) % 2;\n    _previousRowDateTime = _AddDate;\n  }\n  return _commentRowClasses[_commentRowClassesIndex];\n}	0
16630870	16630751	Get XML with single Data	XmlDocument doc = new XmlDocument();\n    doc.Load("http://geoiptool.com/data.php");\n\n    var marker = doc.SelectSingleNode("//markers/marker");\n    string lat = marker.Attributes["lat"].Value;	0
9992729	9989943	Regex pattern that matches SQL object (table/function/view)?	string strSchema = "dbo";\nstring strRegexObjectName = System.Text.RegularExpressions.Regex.Escape(strObjectName);\nstring strPattern = @"[\s\+\-\(,/%=\*\\](\[?" + strSchema + @"\]?\.)?\[?" + strRegexObjectName + @"\]?([\s\+\-\),/%=\*\\]|$)";	0
3196841	3196759	Is there a way to span long method names across multiple lines?	[TestMethod, Description("My really long descriptive test name")]\npublic void Test99()\n{\n   Assert.Fail();\n}	0
9451019	9450984	HTTP Web Request is sending twice (How to fix?)	try\n    {\n        using (WebResponse response = request.GetResponse())\n        {\n            HttpWebResponse httpResponse = (HttpWebResponse)response;\n            if (httpResponse.StatusCode == HttpStatusCode.OK)\n            {\n                StreamReader reader = new StreamReader(response.GetResponseStream());\n                string result = reader.ReadToEnd();\n                if(result.StartsWith("NUMBER NOT IN LIST"))\n                {\n                    return "Number Not In List";\n                }\n                return result;\n            }\n            else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)\n            {\n                return statusCode = HttpStatusCode.Unauthorized.ToString();\n            }\n            else if (httpResponse.StatusCode == HttpStatusCode.BadRequest)\n            {\n                return statusCode = HttpStatusCode.BadRequest.ToString();\n            }\n\n        }\n    }	0
10960960	10960821	Bad text file after download it	void Main()\n{\n    WebClient _WebClient = new MyWebClient(); \n    string url = "http://bossa.pl/pub/metastock/forex/sesjafx/"; \n    string file= "20120601.prn";\n    string a = _WebClient.DownloadString(url + file); \n}\n\nclass MyWebClient : WebClient \n{ \n    protected override WebRequest GetWebRequest(Uri address) \n    { \n        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest; \n        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; \n        return request; \n    } \n}	0
5601811	5601752	How to sum columns in a dataTable?	DataTable dt = new DataTable();\n            int sum = 0;\n            foreach (DataRow dr in dt.Rows)\n            {\n                foreach (DataColumn dc in dt.Columns)\n                {\n                    sum += (int)dr[dc];\n                }\n            }	0
6222514	6222326	How to find Scope for ManagementScope?	ManagementScope scope = new ManagementScope("\\root\\cimv2");\nscope.Connect();	0
12484557	12484515	Read created last modified time-stamp of a file using C#	// local times\nDateTime creationTime = File.GetCreationTime(@"c:\file.txt");\nDateTime lastWriteTime = File.GetLastWriteTime(@"c:\file.txt");\nDateTime lastAccessTime = File.GetLastAccessTime(@"c:\file.txt");\n\n// UTC times\nDateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\file.txt");\nDateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\file.txt");\nDateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\file.txt");\n\n// write file last modification time (local / UTC)\nConsole.WriteLine(lastWriteTime);     // 9/30/2007 2:16:04 PM\nConsole.WriteLine(lastWriteTimeUtc);  // 9/30/2007 6:16:04 PM	0
26253518	26252930	Winforms Layout: Expand/Collapse parts of UI	private void radioButton1_CheckedChanged(object sender, EventArgs e) {\n        textBox1.Visible = textBox2.Visible = radioButton1.Checked;\n    }	0
1741248	1741210	Applying one test to two separate classes	abstract class BaseTest{\n\n @Test\n public void featureX(){\n    Type t = createInstance();\n    // do something with t\n }\n\n abstract Type createInstance();\n}\n\nConcreteTest extends BaseTest{\n\n    Type createInstace(){\n        return //instantiate concrete type here.\n    }\n}	0
25117236	25117171	Compare two lists and generate new one with matching results C#	List<string> listC = listA\n    .Select(str => listB.Contains(str) ? str : "null")\n    .ToList();	0
2449872	2433938	How to expose multi-element field in base class to derived classes	class Base {\n    private List<string> _elems = new List<string>();\n    protected ICollection<string> ElementStore { get { return _elems; } }\n}\n\nclass Derived : Base {\n    public Derived() {\n        ElementStore.Add("Foo");\n        ElementStore.Add("Bar");\n    }\n}	0
19535322	19518268	Telerik Radscheduler recurring appointments only shows first appointment	DataRecurrenceField="RecurrenceRule" DataRecurrenceParentKeyField="RecurrenceParentID"	0
13290619	13290553	What is the fastest way of comparing two huge CSV files for a change?	using (var md5 = MD5.Create())\n{\n    using (var stream = File.OpenRead(filename))\n    {\n        return md5.ComputeHash(stream);\n    }\n}	0
34441774	34436992	Is there a generic way to call another method whenever a method is called in C#	public SomeThing MyMethod()\n{\n    return Execute(() =>\n    {\n        return new SomeThing();\n    });\n}\n\n\npublic T Execute<T>(Func<T> func)\n{\n    if (func == null)\n        throw new ArgumentNullException("func");\n\n    try\n    {\n        Setup();\n\n        return func();\n    }\n    finally\n    {\n        TearDown();\n    }\n}	0
11644829	11644040	How to combine 2 datatable and create a new datatable with that in Windows application?	from table1 in dt1.AsEnumerable()\njoin table2 in dt2.AsEnumerable() on table1["Location"] equals table2["Location"]\nselect new\n{\n    Location = table1["Location"],\n    Visa_Q1 = (int)table1["Visa_Q1"],\n    Visa_Q2 = (int)table1["Visa_Q2"],\n    Visa_Q3 = (int)table2["Visa_Q3"],\n    Visa_Q4 = (int)table2["Visa_Q4"],\n};	0
4535158	4535134	How to hide and show silverlight user control on main Silverlight Control?	top10.Visibility = Visibility.Collapsed; // to hide\ntop10.Visibility = Visibility.Visible; // to show	0
14480713	14480642	add my own property to EF designer	public partial class MyEntity {\n\n    public string StringStatusCode { get;set;}\n}	0
13174270	13173614	Async await in Windows Phone web access APIs	public static class Extensions\n{\n    public static Task<string> DownloadStringTask(this WebClient webClient, Uri uri)\n    {\n        var tcs = new TaskCompletionSource<string>();\n\n        webClient.DownloadStringCompleted += (s, e) =>\n        {\n            if (e.Error != null)\n            {\n                tcs.SetException(e.Error);\n            }\n            else\n            {\n                tcs.SetResult(e.Result);\n            }\n        };\n\n        webClient.DownloadStringAsync(uri);\n\n        return tcs.Task;\n    }\n}	0
26701471	26701470	GetMember by MetadataToken	MemberInfo mi = type.Module.ResolveMember(metadataToken);	0
12017003	11862315	Changing the color of the title bar in WinForm	[DllImport("User32.dll", CharSet = CharSet.Auto)]\npublic static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);\n\n[DllImport("User32.dll")]\nprivate static extern IntPtr GetWindowDC(IntPtr hWnd);\n\nprotected override void WndProc(ref Message m)\n{\n    base.WndProc(ref m);\n    const int WM_NCPAINT = 0x85;\n    if (m.Msg == WM_NCPAINT)\n    {\n        IntPtr hdc = GetWindowDC(m.HWnd);\n        if ((int)hdc != 0)\n        {\n            Graphics g = Graphics.FromHdc(hdc);\n            g.FillRectangle(Brushes.Green, new Rectangle(0, 0, 4800, 23));\n            g.Flush();\n            ReleaseDC(m.HWnd, hdc);\n        }\n    }\n}	0
1801587	861061	Transparent Checkbox in Custom Control Using C#	public partial class MyControl : UserControl\n{\n    public MyControl()\n    {\n        InitializeComponent();\n        AttachMouseEnterToChildControls(this);\n    }\n\n    void AttachMouseEnterToChildControls(Control con)\n    {\n        foreach (Control c in con.Controls)\n        {\n            c.MouseEnter += new EventHandler(control_MouseEnter);\n            c.MouseLeave += new EventHandler(control_MouseLeave);\n            AttachMouseEnterToChildControls(c);\n        }\n    }\n    private void control_MouseEnter(object sender, EventArgs e)\n    {\n        this.BackColor = Color.AliceBlue;\n    }\n\n    private void control_MouseLeave(object sender, EventArgs e)\n    {\n        this.BackColor = SystemColors.Control;\n    }\n}	0
2220067	2220045	Assign a delegate that takes parameters	Action<int, object> reportProgressMethod = backgroundWorker.ReportProgress;	0
18265326	18265074	retrieving a datalist created in one void and displaying it in another	public OleDbConnection OpenConnection()\n{\n      var result = new OleDbConnection("My special connection string here"))\n     result.Open()\n     return result;\n }\n\npublic List<string> void DoSomethingWithConnection()\n {\n    using (var connection = OpenConnection());\n    {\n        List<string> dataList = new List<string>();\n\n        OleDbCommand command = new OleDbCommand("DoSomethingHere", connection);\n        var reader = command.ExecuteReader();\n        while (reader.Read())\n        {\n            dataList.Add(reader[0].ToString());\n        }\n\n        return dataList;\n    // The connection is automatically closed when the \n    // code exits the using block.\n    }\n}	0
12320948	12320768	How to Set TimeOut for WebClient on .net?	.Abort()	0
10010687	10010454	Assign button style at runtime	button.Style = (Style)Application.Current.Resources["ButtonStyle1"];	0
32398660	32398347	Bind wpf listbox to ObservableCollection of tuples	DisplayMemberPath="Item1"	0
55242	55203	How do I insert text into a textbox after popping up another window to request information?	parent.opener.document.getElemenyById('ParentTextBox').value = "New Text";	0
2104744	2104732	Regular Expression for determining serial number	^[A-Za-z]{3,4}[0-9]{3,4}	0
7145589	7145449	Select item from list according to weighting	struct Info\n    {\n        public string Name { get; set; }\n        public float Percent { get; set; }\n    }\n\n    class Statistics\n    {\n        public IEnumerable&ltstring&gt CreateSampleSet(int sampleSize, params Info[] infos)\n        {\n            var rnd = new Random();\n            var result = new List&ltstring&gt();\n            infos = infos.OrderByDescending(x =&gt x.Percent).ToArray();\n            foreach (var info in infos)\n            {\n                for(var _ = 0; _ &lt (int)(info.Percent/100.0*sampleSize); _++)\n                result.Add(info.Name);\n            }\n\n            if (result.Count &lt sampleSize)\n            {\n                while (result.Count &lt sampleSize)\n                {\n                    var p = rnd.NextDouble()*100;\n                    var value = infos.First(x =&gt x.Percent &lt= p);\n                    result.Add(value.Name);\n                }\n            }\n\n            return result;\n        }\n    }	0
6176433	6170232	Nhibernate QueryOver Left Outter Joins with conditions	Session.QueryOver<NewsPost>()\n            .Left.JoinAlias(x => x.PostedBy, () => userAlias)\n            .Left.JoinAlias(x => x.Category, () => categoryAlias)\n            .Where(x => !x.Deleted)\n            .And(x => !userAlias.Deleted)\n            .And(x => !categoryAlias.Deleted);	0
10060091	10060050	Which is more performant, passing a method the entire object, or a property of that object?	CouponModel coupon = GetFromSomewhere();\nif (!coupon.HasUniqueKey()) {\n  // ...\n}	0
3534625	3534525	Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'	public class SomeClass\n{\n    [XmlIgnore]\n    public DateTime SomeDate { get; set; }\n\n    [XmlElement("SomeDate")]\n    public string SomeDateString\n    {\n        get { return this.SomeDate.ToString("yyyy-MM-dd HH:mm:ss"); }\n        set { this.SomeDate = DateTime.Parse(value); }\n    }\n}	0
26934976	26934883	WPF NullReferenceException	public void MakeDraggable(Canvas theCanvas)\n{\n    if (theCanvas == null)\n    {\n        throw new ArgumentNullException("theCanvas");\n    }\n\n    _canvas = theCanvas;\n    _canvas.PreviewMouseDown += DPreviewMouseLeftButtonDown;\n}	0
2399897	2399686	How do I open a Windows Form returning only data from specific id	from orders in db.Orders\n  where orders.employeeID == 42 // supposing orders has an employeeID field\n  orderby orders.OrderID\n  select orders;	0
13320697	13320667	how to specify path and filename while creating a excel file in asp.net using c#?	object missing = System.Reflection.Missing.Value;\n\nworkbook.SaveAs(@"c:\documents\book1.xlsx",\n            Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,\n            false, false, Excel.XlSaveAsAccessMode.xlNoChange,\n            missing, missing, missing, missing, missing);	0
6708098	6707801	NUnit checking all the values of an array (with tolerance)	GlobalSettings.DefaultFloatingPointTolerance = 0.1;\nAssert.That(new[] {1.05, 2.05, 3.05}, Is.EquivalentTo(new[] {3.0, 2.0, 1.0}));	0
12457940	12457780	Redirection to action asp.net mvc3	[HttpPost]\npublic ActionResult Analyser(FormCollection collection)\n{\n    IList<float> sfr = new List<float>();\n    for (int i = 0; i < Global.seg.Count; i++)\n    {\n        if (collection.AllKeys.Contains(i.ToString())) \n        {\n            foreach (Point e in Global.seg[i]._pointsListe)\n            {\n                sfr.Add(e._latitude);\n                sfr.Add(e._longitude);\n            }\n        }\n    }\n\n    var rvd = new RouteValueDictionary();\n    for (int i = 0; i < sfr.Count; i++)\n    {\n        rvd[string.Format("sf[{0}]", i)] = sfr[i];\n    }\n\n    if (sfr.Count == 4) return RedirectToAction("_two", rvd);\n    if (sfr.Count == 6) return RedirectToAction("_two", rvd);\n    if (sfr.Count == 8) return RedirectToAction("_four", rvd);\n    if (sfr.Count == 10) return RedirectToAction("_five", rvd);\n    if (sfr.Count == 12) return RedirectToAction("_six", rvd);\n    else return RedirectToAction("_others", rvd);\n}	0
11288044	11288017	Saving image to media library WP7	public void SaveImageTo(string fileName = "ShareByQR.jpg") \n    {\n        fileName += ".jpg";\n        var myStore = IsolatedStorageFile.GetUserStoreForApplication();\n        if (myStore.FileExists(fileName))\n        {\n            myStore.DeleteFile(fileName);\n        }\n\n        IsolatedStorageFileStream myFileStream = myStore.CreateFile(fileName);\n        WritableBitmap wr = imageControl; // give the image source\n        wr.SaveJpeg(myFileStream, wr.PixelWidth, wr.PixelHeight, 0, 85);\n        myFileStream.Close();\n\n        // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.\n        myFileStream = myStore.OpenFile(fileName, FileMode.Open, FileAccess.Read);\n        MediaLibrary library = new MediaLibrary();\n        //byte[] buffer = ToByteArray(qrImage);\n        library.SavePicture(fileName, myFileStream);\n    }	0
32672106	32671719	UWP: Updating UI through data binding from a background thread	obj.Invoke((MethodInvoker) SomeMethod);	0
31166183	31166046	How to read a .CSV file into an array of a class (C#)	for (int loop2 = 0; loop2 < ReadPizzaArray.Length; loop2++)\n        {\n            ReadPizzaArray[loop2] = new PizzaOrder(Convert.ToInt32(PizzaRead[0]), PizzaRead[1].ToString(), Convert.ToDecimal(PizzaRead[3]));\n        }	0
7217735	7217732	How to get fully qualified assembly name	//s if the Fully Qualified assembly name\nType t = typeof(System.Data.DataSet);\nstring s = t.Assembly.FullName.ToString();	0
25313873	25291708	Operator overloading with generic function parameters	public static bool EqualOperatorGeneric<L, R>(L l, R r)\n{\n    dynamic dl = l, dr = r;\n    return dl == dr;\n}	0
27914172	27893599	Dependency Injection when controller called from another controller	public class HomeController : Controller {\n    public HomeController(IMyAppBusinessLogic bll) { ... }\n}\n\npublic class WebApiController : Controller {\n    public WebApiController(IMyAppBusinessLogic bll) { ... }\n}\n\npublic class MyAppBusinessLogic : IMyAppBusinessLogic {\n    public MyAppBusinessLogic(ITodoRepository repository) { ... }\n}	0
8887853	8884444	Retrieving BITS Version in C#	const string bitsDll = "QMgr.dll";\n\nvar bitsDllInfo = FileVersionInfo.GetVersionInfo(Path\n    .Combine(System.Environment.SystemDirectory, bitsDll));\n\nupdateDeliveryStatusRequest.BitsVersion = bitsDllInfo.FileVersion;	0
19347810	19347758	c# - Extract first integer from a string	var digits = input.SkipWhile(c => !Char.IsDigit(c))\n    .TakeWhile(Char.IsDigit)\n    .ToArray();\n\nvar str = new string(digits);\nint i = int.Parse(str);	0
33756112	33755954	Find children objects missing parents objects using LINQ	var childrenMissingParents = possible_child.Where(\n    c => !possible_parent.Any(\n        p => p.Country == c.Country\n     && p.Year == c.Year\n     && p.Season == c.Season\n     && p.SeasonType == c.SeasonType));	0
21578722	21578672	How to create a C# regex to accept only these characters?	"[-a-zA-Z?????????????????')(?????????????????????????????]*"	0
28752290	28751420	How to get the FieldInfo of a field from the value	class Program\n{\n    public static void Main()\n    {\n        var cls = new MyClass();\n        Console.WriteLine(GetMemberInfo(cls, c => c.myInt));\n        Console.ReadLine();\n    }\n\n    private static MemberInfo GetMemberInfo<TModel, TItem>(TModel model, Expression<Func<TModel, TItem>> expr)\n    {\n        return ((MemberExpression)expr.Body).Member;\n    }\n\n    public class MyClass\n    {\n        public int myInt;   \n    }\n\n\n}	0
9016537	9016444	Relative Path to load a library?	System.Reflection.Assembly.GetExecutingAssembly().Location	0
17829815	17828305	How To Get First Item of Array	Deployment.Current.Dispatcher.BeginInvoke(() =>\n{\n    HeadNew.DataContext = Headlines.Headline.FirstOrDefault();\n});	0
24712482	24712103	Separate each word from a text (maybe more gaps between the words )	String test = " This is test     method with more    space  ";\n\n        var Result = test.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x)).ToList();	0
2412457	2412292	C# update a varying property on each item within a collection	public class Something\n    {\n        public decimal Amount { get; set; }\n        public decimal OtherAmount { get; set; }\n    }\n\n    public static void UpdateAmounts<T, U>(IEnumerable<T> items, Action<T,U> setter, Func<T, U> getter)\n    {\n        foreach (var o in items)\n        {\n            setter(o, getter(o));\n        }\n    }\n\n    public void QuickTest()\n    {\n        var s = new [] { new Something() { Amount = 1, OtherAmount = 11 }, new Something() { Amount = 2, OtherAmount = 22 }};\n        UpdateAmounts(s, (o,v) => o.Amount = v, (o) => o.Amount + 1);\n        UpdateAmounts(s, (o,v) => o.OtherAmount = v, (o) => o.OtherAmount + 2);\n    }	0
7315087	7314995	how to change the text color of file chosen in asp:fileUpload in Safari?	input[type=file]\n{\n    color: white;\n}	0
3331772	3331762	Deselect text in a textbox	txtBox.Select(0, 0);	0
9635016	9618878	Selenium Webdriver wait on element click?	try\n{\n    element.Click();\n}\ncatch\n{\n    cnt++;\n    do\n    {\n      //wait for whatever\n      cnt++;\n      Thread.Sleep(1000);\n      // Wait for 30 seconds for popup to close\n    } while (!string.IsNullOrEmpty(browser.CurrentWindowHandle) && cnt < 30);\n}	0
16571174	16571020	Passing string from c++ to c#	[DllImport("SurfaceReader.dll", \n           CallingConvention = CallingConvention.Cdecl, \n           CharSet = CharSet.Unicode)]\nprivate static extern void GetSurfaceName(StringBuilder o_name);	0
9182951	9182910	How would I return top FileInfo object with the oldest date time?	var files = (from f in directory.EnumerateFiles()\n             orderby f.CreationTime ascending\n             select f).Take(1);	0
9035289	9035192	Mask out part first 12 characters of string with *?	using System;\n\nclass Program\n{\n    static void Main()\n    {\n        var str = "1234567890123456";\n        if (str.Length > 4)\n        {\n            Console.WriteLine(\n                string.Concat(\n                    "".PadLeft(12, '*'), \n                    str.Substring(str.Length - 4)\n                )\n            );\n        }\n        else\n        {\n            Console.WriteLine(str);\n        }\n    }\n}	0
17903227	17902882	How to enter a default value when a TextBox is empty	private void textBox1_Validated(object sender, EventArgs e)\n{\n    if (((TextBox)sender).Text == "")\n    {\n        ((TextBox)sender).Text = "0";\n    }\n}	0
8302564	8302509	Using Generics from an already known TypeObject in C#	var genericMethod = typeof(someClass).GetMethod("someGenericMethod");\nvar methodInstance = genericMethod.MakeGenericMethod(objectType);\nmethodInstance.Invoke(someInstance, null);	0
1059947	1059922	Temporarily lock folder from reading with ASP.NET	indexlock.donotuse	0
9366965	9366851	How to use SQLReader to return List<string>	public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)\n{\n    while (reader.Read())\n    {\n        yield return reader;\n    }\n}\n\n...\n\nusing (var reader = SqlHelper.ExecuteReader(connectionString, query))\n{\n    var list = reader.AsEnumerable().Select(r => r.GetString(0)).ToList();\n}	0
3432438	3432434	sorting listbox in c#	list = list.OrderBy(item => item.NumberValue).ToList();	0
17621049	17620648	Using Json in ASP.Net	using Newtonsoft.Json;	0
12069593	12068107	Sending shift+f10 over a terminal	t.SendAndWait(Char.ToString((char)0x19), "< ");	0
14168249	14168194	MVC4 View not binding to Model in Controller on POST	public class ApplicationModel\n{\n    public int SectionID {get; set;}\n    public Term Term {get; set;}\n    public User User {get; set;}\n    public string CurrentSectionName {get; set;}\n}	0
3603571	3516242	Add / remove logfiles during runtime in NLog	LoggingConfiguration config = LogManager.Configuration;\n\nvar logFile = new FileTarget();\nconfig.AddTarget("file", logFile);\n\nlogFile.FileName = fileName + ".log";\nlogFile.Layout = "${date} | ${message}";\n\nvar rule = new LoggingRule("*", LogLevel.Info, logFile);\nconfig.LoggingRules.Add(rule);\n\nLogManager.Configuration = config;\n\nlogger.Info("File converted!");	0
11440158	11439810	Program hangs while using ffprobe on file with teletext subtitles	string args = string.Format("-show_format -show_streams \"{0}\"", FileName);\n\nProcess p = new Process();\np.StartInfo = new ProcessStartInfo(FFPROBE_PATH);\np.StartInfo.Arguments = args;\np.StartInfo.CreateNoWindow = true;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.RedirectStandardError = true;\np.StartInfo.UseShellExecute = false;\np.StartInfo.WorkingDirectory = System.IO.Directory.GetCurrentDirectory();\np.Start();\n\nstring output = p.StandardOutput.ReadToEnd().Replace("\r\n", "\n");\np.WaitForExit();	0
22742532	22742490	How to deserealize JObj Collection	[JsonProperty("response")]\npublic int[] UserIds { get; set; }	0
3545412	3545371	C#: Am i validating filetype and using goto in a right manner?	using (SaveFileDialog dialog = new SaveFileDialog())\n{\n    dialog.Filter = "Text files|*.txt";\n    while(dialog.ShowDialog() == DialogResult.OK)\n        if (System.IO.Path.GetExtension(dialog.FileName).ToLowerInvariant() != ".txt")\n            MessageBox.Show("You must select a.txt file");\n        else // file is ok\n        {\n            File.WriteAllText(dialog.FileName, txtEditor.Text);\n            break;\n        }\n }	0
8220806	8215400	How to Change the Schema name	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    //It works fine\n    var schemaName = "SYSTEM";\n    modelBuilder.Entity<Account>().ToTable("TB_ACC_HOLDERS", schemaName);\n}	0
9949393	9948823	How to update an HTML control from code within SilverLight	HtmlPage.Window.Invoke("globalJSMethod", stringParam);	0
23415149	23415090	How to use SetWindowLong in C#?	SetWindowLong ( c, (int)WindowLongFlags.GWL_STYLE,\n    (uint) WindowStyles.WS_OVERLAPPED);	0
22656475	22656153	How to get all content of table in sql	List<string> unitNumbers = new List<string>();\n\nusing (SqlConnection con = new SqlConnection(_ConnectionString))\n{\n    con.Open();\n\n    using (SqlCommand command = new SqlCommand("SELECT CL_UnitNumber FROM COM_ConnectionLogRfmDevices", con))\n    {\n        SqlDataReader reader = command.ExecuteReader();\n\n        while (reader.Read())\n        {\n            unitNumbers.Add(reader.GetInt32(0)); // Or maybe reader.GetString(0)\n        }\n    }\n}	0
3779902	3779777	CreateChildControls issue with custom control	Public string Text\n{\n   get\n   {\n      EnsureChildControls();\n      return textBox1.Text;\n   }\n   set\n   {\n      EnsureChildControls();\n      textBox1.Text = value;\n   }\n}	0
6823327	6823291	Convert date to string format yyyy-mm-dd HH:MM:SS - C#	MyDateTime.ToString("yyyy-MM-dd hh:mm:ss");	0
10465117	10465099	Create an array populated with a range of values x through y	int[] numbers = Enumerable.Range(x, y - x + 1).ToArray();	0
11600829	11600518	Replace string only at end of a line	string matchPattern = ",,,,,$"; // $ to match the end of the line.\nstring replacement = ",EMPTY,EMPTY,EMPTY,EMPTY,EMPTY";\nstring filepent = String.Join(\n    Environment.NewLine, // or maybe just "\r\n"\n    File.ReadAllLines(yourFilePath)\n        .Select(line => Regex.Replace(line, matchPattern, replacement)));	0
7367053	7367006	C# Using block context, within another using block context	using (DataOneContext context1 = new DataOneContext()) \n{ \n     code... \n\n     using (DataTwoContext context2 = new DataTwoContext(context1.Connection)) \n     { \n         more code....\n     } \n}	0
32690399	32690299	Looping through all nodes in xml file with c#	private static void handleNode(XmlNode node)\n{\n  if(node.HasChildNodes)\n  {\n    foreach(XmlNode child in node.ChildNodes)\n    {\n      handleNode(child);\n    }\n  }  \n  else\n    Console.WriteLine(node.Name);\n}	0
16000948	16000879	how to make one control to show a property of any derived class in c#?	class Base\n{\n   public virtual int MyProperty {get { return 1;} }   \n}\n\nclass A: Base\n{\n   public override int MyProperty { get { return 5; } }\n}\n\nclass B: Base\n{\n   public override int MyProperty { get { retun 7; } }\n}	0
3046113	3046084	ASP.NET MVC: How do I validate a model wrapped in a ViewModel?	public class LoginVM\n{\n    [Required]\n    public Login login { get; set; }\n    public List<NewsItem> newsItems { get; set; }\n}	0
20505098	20442988	Read from a text file	file3 = await localFolder.GetFileAsync(path);\nIList<String> readFile = await Windows.Storage.FileIO.ReadLinesAsync(file3);	0
11765470	11765356	save my gpg file to a different directory	ProcessStartInfo startInfo = new ProcessStartInfo()\n        {\n            WorkingDirectory = @"C:\",\n            CreateNoWindow = false,\n            UseShellExecute = false,\n            RedirectStandardError = true,\n            RedirectStandardInput = true,\n            RedirectStandardOutput = true\n\n\n        };\n\n        startInfo.FileName = "gpg.exe";\n        startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n        startInfo.Arguments = @"-e -r myname c:\MYPATH\config.xml -o c:\MYPATH\config.xml.gpg";\n        using (Process exeProcess = Process.Start(startInfo))\n        {\n\n            exeProcess.WaitForExit();\n        }	0
31495949	31495672	c# url action with multiple parameter one is null	public class RouteConfig\n{\n    public static void RegisterRoutes(RouteCollection routes)\n    {\n        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n\n        routes.MapRoute(\n            name: "UserRoute",\n            url: "{\n                     controller}/{action}/{id}/{name}/{age}",\n                     defaults: new { \n                                    controller = "Home", \n                                    action = "Index", \n                                    id = UrlParameter.Optional, \n                                    name = UrlParameter.Optional, \n                                    age = UrlParameter.Optional }\n        );\n\n        routes.MapRoute(\n            name: "Default",\n            url: "{controller}/{action}/{id}",\n            defaults: new { \n                             controller = "Home", \n                             action = "Index", \n                             id = UrlParameter.Optional }\n        );\n    }\n}	0
15147661	15147601	How do i change a control location to be in the center of the screen?	x = (formWidth - chartWidth) / 2;\ny = (formHeight - chartHeight) / 2;	0
17890221	17888435	How to Create a new instance of class under an AppDomain	AppDomainSetup domainSetup = new AppDomainSetup \n                             {PrivateBinPath = binFolder+"\\TestProject.dll"};\nAppDomain ad = AppDomain.CreateDomain("New domain",null, domainSetup);\n\nTestClass remoteWorker = (TestClass)ad.CreateInstanceFromAndUnwrap(\n                          binFolder+"\\TestProject.dll",\n                          typeof(TestClass ).FullName);	0
33895595	33563813	How to set Grid.DataTable column values to not editable using C# in SAP	oGrid.Columns.Item(0).Editable = false;	0
247436	247422	How to I attach to a VSTO Excel Application Process to Debug?	Debugger.Launch();	0
13625704	13625637	c# Image from file close connection	Image img;\nusing (var bmpTemp = new Bitmap("image_file_path"))\n{\n     img = new Bitmap(bmpTemp);\n}	0
72822	72176	Using C#, what is the most efficient method of converting a string containing binary data to an array of bytes	public Byte[] ConvertToBytes(Char[] source)\n{\n    Byte[] result = new Byte[source.Length * sizeof(Char)];\n    IntPtr tempBuffer = Marshal.AllocHGlobal(result.Length);\n    try\n    {\n        Marshal.Copy(source, 0, tempBuffer, source.Length);\n        Marshal.Copy(tempBuffer, result, 0, result.Length);\n    }\n    finally\n    {\n        Marshal.FreeHGlobal(tempBuffer);\n    }\n    return result;\n}	0
6962313	6961421	LightSwitch Application and Doing //Something when a row value has been changed	public partial class Order\n{\n    partial void Status_Changed()\n    {\n      if (status == Status.Confirmed)\n      {\n         // Write code to send email\n      }\n    }\n}	0
16908972	16908866	Color Picker - C#	IntPtr hdc = GetDC(IntPtr.Zero);\nuint pixel = GetPixel(hdc, currentPoint.X, currentPoint.Y);\nReleaseDC(IntPtr.Zero, hdc);\nColor color = Color.FromArgb((int)(pixel & 0x000000FF),\n    (int)(pixel & 0x0000FF00) >> 8,\n    (int)(pixel & 0x00FF0000) >> 16);	0
14645960	14562765	Atomic write on writeshared opened file	new FileStream(FileName,\n    FileMode.Append,\n    System.Security.AccessControl.FileSystemRights.AppendData,\n    FileShare.ReadWrite, 4096, FileOptions.None);	0
22294899	22294813	How should I handle a potentially large number of edits in entity framework?	the process might take hours	0
16015153	16015056	SQL allow null in table in C#	InfoCommand.Parameters.AddWithValue("@Pareto", (Object)pareto ?? DBNull.Value);	0
22570875	22570215	Custom DataGridView returns object with columns	public class MyGrid : DataGridView {\n  public MyGrid(string columnName, string columnHeader) {\n    this.Columns.Add(columnName, columnHeader);\n  }\n}	0
3265049	3264789	How to convert a void* to a type that can be used in C#? Interoperability between C DLL and C#	[DllImport("myapi.dll")]\npublic static extern int myfunct( \n    [MarshalAs(UnmanagedType.LPTStr)] string lpDeviceName,\n    ref IntPtr hpDevice);	0
2684567	2684269	How to use LINQ for CRUD with a simple SQL table?	sqlmetal /server:myserver /database:northwind /namespace:nwind /code:nwind.cs /language:csharp	0
27951498	27945430	Intercept Session Start event for all applications	public void Init(HttpApplication context)\n    {\n        var sessionModule = context.Modules["Session"] as SessionStateModule;\n        if (sessionModule != null)\n        {\n            sessionModule.Start += this.Session_Start;\n        }\n    }\n    private void Session_Start(object sender, EventArgs e)\n    {\n        // Do whatever you want to do here.\n    }	0
3414966	3414932	Programmatically place a control inside a div	myDiv.Controls.Add(myTreeview);	0
7912100	7911148	Can't update Composite data with wcf ria servics	public void UpdateMyTab(MyTab currentMyTab) {          \n  var original = this.ChangeSet.GetOriginal(currentMyTab);\n\n  if (original != null) {\n    this.ObjectContext.MyTabs.AttachAsModified(currentMyTab, original);\n  }\n  else {\n    this.ObjectContext.MyTabs.Attach(currentMyTab);\n  }\n}	0
21856518	21855553	Binding issue in a list at a complex model to an mvc application	for(int i = 0; i < model.MyList.Count; i++)\n{\n    @Html.HiddenFor(model => model.MyList[i])\n    @Html.DisplayFor(model  => model.MyList[i])\n}	0
3182977	2677972	Silverlight 4: How to find source UI element from contextmenu's menuitem_click?	(sender as MenuItem).DataContext as TextBox	0
11570192	11569857	Restrict generic parameter on interface to subclass	Assembly.Load	0
12037178	12036913	LINQ query expression to explicit dot-notation	myResult = (from ... select new MyClass { ... }).Where(predicate);	0
4451111	4451073	Error in lambda: No implicit convertion between 	return (topics.Select(c => new TopicUi\n{\n    Bookmarks = new List<Bookmark> {\n      new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName }\n    }\n})).ToList();	0
10613199	10612937	How to write query for the below scenario in Entity Framework?	var result = \nfrom user in cxt.Users\njoin friend in cxt.Friends on user.UserId equals friend.FriendUserId\nwhere user.UserId == incId\nselect new\n{\n    FriendUserId = friend.FriendUserId,\n    UserName = user.UserName,\n    ImageUrl = user.ImageUrl,\n    Status = cxt.LogStatus.Any(s=>s.UserId == user.UserId)\n};	0
9820245	9820173	Setting an ID as an Integer with C#	int id=0;\nif (int.TryParse(Request.QueryString["ID"],out id)) {\n  .. logic for valid id\n} else {\n  .. logic for invalid id\n}	0
5236484	5235173	EF 4.0 get EntitySetMappings from MetadataWorkspace	string sql = ((System.Data.Objects.ObjectQuery)this.[AnyEntitySet]).ToTraceString();	0
27861104	27858176	VS consider ' as a comment note formula	oExcelsheet.Range("f2").Formula = "=IF(LEN(A2)=2,(CONCATENATE(""'00000"",A2))," _\n  & "IF(LEN(A2)=3,CONCATENATE(""'0000"",A2),IF(LEN(A2)=4,CONCATENATE(""'000"",A2)," _\n  & "IF(LEN(A2)=5,CONCATENATE(""'00"",A2),IF(LEN(A2)=6,CONCATENATE(""'0"",A2),A2)))))"	0
29844346	29839567	How to avoid two compose mail at a time in Outlook	Outlook.Application oApp = new Outlook.Application();	0
15112553	15107921	deserialize json array list in c#	public class Demo\n   {\n      public string Name;\n      public string Type;\n      public string Value;\n      public string ChildContentType;\n      public string ChildMetadata;\n   }\n\n    public void Deserialize()\n    {\n        string jsonObjString = "[{\"Name\": \"Description\",\"Type\": \"Text\",\"Value\": \"XXX\",\"ChildContentType\": \"Value\",\"C??hildMetadata\": \"YYY\"}]";\n         var ser = new JavaScriptSerializer();\n         var arreyDemoObj = ser.Deserialize<Demo[]>(jsonObjString);\n\n         foreach (Demo objDemo in arreyDemoObj)\n         {\n             //Do what you want with objDemo\n         }\n      }	0
14920007	14919959	Keeping count of items in a category	var model = db\n    .Categories\n    .Select(c => new MyViewModel\n    {\n        Name = c.Name,\n        ProductsCount = c.Products.Count()\n    })\n    .ToList();	0
11335129	11335074	Halting Execution of a program in C#	System.Threading.Thread.Sleep(int millisecondsTimeout);	0
10069517	10069472	Triggering an event after a specified number of clicks	private int counter = 0;\npublic event EventHandler Clicked5TimesEvent;\n\nprivate void OnClicked5TimesEvent() {\n  if (Clicked5TimesEvent != null) {\n       Clicked5TimesEvent(this, EventArgs.Empty);\n  }\n}\n\nprivate void button1_Click(object sender, EventArgs e) {\n  counter++;\n  if (counter % 5 == 0) {\n      OnClicked5TimesEvent();\n  }\n}	0
26668960	26668718	How to locate subarray from an array c#	byte[] subArray = { 0x00, 0x01, 0x00, 0x01 }; \nbyte[] array = { 0x1A, 0x65, 0x3E, 0x00, 0x01, 0x00, 0x01, 0x2B, 0x4C, 0xAA };\n\nvar matchIndexes =\n    from index in Enumerable.Range(0, array.Length - subArray.Length + 1)\n    where array.Skip(index).Take(subArray.Length).SequenceEqual(subArray)\n    select (int?)index;\n\nvar matchIndex = matchIndexes.FirstOrDefault();\nif (matchIndex != null)\n{\n    byte[] successor = array.Skip(matchIndex.Value + subArray.Length).ToArray();\n    // handle successor here\n}	0
32473249	32472999	Map XML child element to C# class	[Serializable()]\n[System.Xml.Serialization.XmlRoot("root")]\npublic class SomeClass\n{\n     public Data()\n    {\n        DataArray = new List<Data>(); \n    }\n\n    [XmlElement("data", typeof(Data))]\n    public List<Data> DataArray { get; set; }\n} \n\n[Serializable()]\npublic class Data\n{\n    public Data()\n    {\n        DocumentStatusArray = new List<DocumentStatus>(); \n    }\n\n    [XmlElement("item", typeof(DocumentStatus))]\n    public List<DocumentStatus> DocumentStatusArray { get; set; }\n} \n\n[Serializable()]\npublic class DocumentStatus\n{\n    [System.Xml.Serialization.XmlAttribute("StateId")]\n    public int StateId {get; set;}\n\n    [System.Xml.Serialization.XmlAttribute("StateName")]\n    public string StateName { get; set; }\n\n    [System.Xml.Serialization.XmlAttribute("GroupId")]\n    public GroupId groupId { get; set; } \n}	0
12371960	12371066	How to pass value from checkbox to controller?	//instead of: @{Html.RenderPartial("WorkList", Model.workList);} write code below inside using statement(below </fieldset>)\n\n\n    @for (int i = 0; i < Model.worklist.Count; i++)\n    {\n        <tr>\n            <td>\n            @Html.HiddenFor(x => x.workList[i].Id)\n            @Html.CheckBoxFor(x => x.workList[i].Selected)\n            </td>\n            ...\n        </tr>\n    }	0
5648408	5648367	How do I create a login screen?	form.showDialog	0
1038034	1038014	How do I dynamically change color in C# to a hex value?	var color = ColorTranslator.FromHtml("#FF1133");	0
1335335	1334510	How do I program a queue to launch external applications in ASP.NET?	void Application_Start(object sender, EventArgs e)	0
12989221	12989175	Stored procedure in C# datagridview instead of listbox	......\n   using (SqlDataAdapter adapter = new SqlDataAdapter()) \n   { \n        DataTable dt = new DataTable();\n        adapter.SelectCommand = cmd;            { \n        adapter.Fill(dt);\n        dataGridView1.DataSource = dt;\n   }    \n   ......	0
21678495	21678126	Parse json string to find and element (key / value)	string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";\nvar data = (JObject)JsonConvert.DeserializeObject(json);\nstring timeZone = data["Atlantic/Canary"].Value<string>();	0
32111682	32111482	C# how to get the data inside a List<array>	List<string[]> thisListOfArray = new List<string[]>();\nList<string> thisArrayA = new List<string>();\nList<string> thisArrayB = new List<string>();\nthisArrayA.Add("ItemA1");\nthisArrayA.Add("ItemA2");\nthisArrayA.Add("ItemA3");\nthisArrayB.Add("ItemB1");\nthisArrayB.Add("ItemB2");\nthisArrayB.Add("ItemB3");\nthisListOfArray.Add(thisArrayA.ToArray());\nthisListOfArray.Add(thisArrayB.ToArray());\n\nList<string> lstNewstring = new List<string>();\n\nforeach (var strArray in thisListOfArray)\n{\n    foreach (var str in strArray)\n    {\n        lstNewstring.Add(str);\n    }\n}\n\nMessageBox.Show(lstNewstring.Count.ToString());	0
29001105	29001023	How do I deserialize a JSON array that contains only values?	JsonConvert.DeserializeObject<List<string>>(json);	0
22872153	22871962	How to make multiple async call in a single call in C#.net	var tasks = uris.Select(async uri =>\n            {\n                using (var client = new HttpClient())\n                {\n                    return await client.GetStringAsync(uri)\n                }\n            })\n            .ToList();	0
6692831	6692803	i'm used to have the IDE to create the event signature for me under vb.net, how to do it with c#?	someControl.Click += <hit tab twice>	0
2195475	2195439	Open a web browser in C# XNA?	Process.Start(url)	0
13673887	13673784	Updating SQL database from DataGridView C#	DataGridViewButtonColumn clbt_delet = new DataGridViewButtonColumn();\n   clbt_delete.HeaderText = "DELETE"\n   clbt_delete.Text = "Delete";\n   clbt_delete.UseColumnTextForButtonValue = true;\n   dataGridView1.Columns.Add(clbt_delete);	0
5369822	5351350	How to mock protected virtual members in FakeItEasy?	A.CallTo(foo).Where(x => x.Method.Name == "MyProtectedMethod").WithReturnType<int>().Returns(10);	0
185475	185141	How to avoid screen flickering when a control must be constantly repainted in C#?	SetStyle(ControlStyles.SupportsTransparentBackColor |\n         ControlStyles.Opaque |\n         ControlStyles.UserPaint |\n         ControlStyles.AllPaintingInWmPaint, true);	0
31011149	31008808	Format navbar color and add dividers in Razor	#navigation li a{\n  border-right: 1px solid;\n}\n\n#navigation li:last-child a{ \n   border-right: none;\n}	0
20748807	20748697	Set ComboBox default value without directly changing SelectedIndex	public Form1()\n{\n    InitializeComponent();\n\n    comboBox1.SelectedIndex = 0;\n    comboBox1.SelectedIndexChanged += combobox_SelectedIndexChanged;\n}\n\nprivate void combobox_SelectedIndexChanged(object sender, EventArgs e)\n{\n    Process.Start(Application.ExecutablePath);\n    this.Close();\n}	0
7804115	7804046	How to clone a whole tree without affecting the original one?	public object Clone()\n{\n    Node clone = (Node)MemberwiseClone();\n    if (Left != null)\n        clone.Left = (Node)Left.Clone();\n    if (Right != null)\n        clone.Right = (Node)Right.Clone();\n    return clone;\n}	0
14746254	14746104	Best way to send related data to WCF with different Structs	DeviceUser\n- DeviceId (int)\n- Users (IEnumerable<User>)\n- Make (string)\n- Year (int)	0
30637572	30637538	How to convert Json in C#?	var lstrelations = _people.GetAllUsers();\nvar lstEmailAddresses = lstrelations.Select(p => new { EmailID = p.EmailID }).ToList();\nJson(lstEmailAddresses, JsonRequestBehavior.AllowGet);	0
22435736	22420047	ScheduledTaskAgent issue in updating WP8 app tiles programatically	#define DEBUG_AGENT	0
10731744	10721417	Facebook fan page app	void CallFacebookApi(string oAuthToken, string userId)\n{       \nstring userLikeUrl = "https://graph.facebook.com/me/Likes/" + pageId +"?access_token=" + oAuthToken;\n\n  response = requestFBData(userLikeUrl);\n  if (response.Length > 0)\n    {\n\n     JObject userLike = JObject.Parse(response);\n     int count = userLike["data"].Count();\n\n     if (count > 0){\n     //user liked your page.\n     } \n     else {\n      //user do not liked your page yet\n      }\n    }\n\n }\n\npublic string requestFBData(string action)\n{\n   string results = string.Empty;\n\n    try\n    {\n     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(action);\n     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();\n\n     StreamReader sr = new StreamReader(resp.GetResponseStream());\n     results = sr.ReadToEnd();\n     sr.Close();\n    }\n    catch (Exception e)\n    {\n      if (e.Message.Contains("400"))\n      {\n       //invalid reponse\n      }\n    }\n\n    return results;\n  }	0
4291074	4291059	How to iterate on all properties of an object in C#?	public class Foo\n{\n    public string Prop1 { get; set; }\n    public string Prop2 { get; set; }\n    public int Prop3 { get; set; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var foo = new Foo();\n\n        // Use reflection to get all string properties \n        // that have getters and setters\n        var properties = from p in typeof(Foo).GetProperties()\n                         where p.PropertyType == typeof(string) &&\n                               p.CanRead &&\n                               p.CanWrite\n                         select p;\n\n        foreach (var property in properties)\n        {\n            var value = (string)property.GetValue(foo, null);\n            if (value == null)\n            {\n                property.SetValue(foo, string.Empty, null);\n            }\n        }\n\n        // at this stage foo should no longer have null string properties\n    }\n}	0
6114151	6101162	How to embed CHM file in application	data.Count() - 1	0
25981188	25979812	How to return string with accent from controller to View via Ajax JSon	Encoding.Default.GetString(buffer).	0
14657204	14656927	How to add delay inside a for-loop using timers	private int loopVar = 0;\npublic void Form_Load()\n{\n    // Start 100ms after form load.\n    timer1.Interval = 100;\n    timer1.Enabled = true;\n}\n\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n   timer1.Enabled = false;\n   //  My Code Here\n   loopVar++;\n\n   if (loopVar < Max_Step)\n   {\n      // Come back to the _tick after 60 seconds.\n      timer1.Interval = 60000;\n      timer1.Enabled = true;\n\n   }\n}	0
19003649	16278230	How to insert before row in the OpenXml SDK SpreadsheetDocument Table?	public static void AppendRefRow(string path)\n    { \n        using (var pck = new ExcelPackage(new FileInfo(path)))\n        {\n\n            var ws = pck.Workbook.Worksheets.FirstOrDefault();\n            var refRowIndex = 9;\n            var refColumnIndex = 1; \n\n            for (int index = Items.Length - 1; index >= 0; index--)\n            {\n                ws.InsertRow(refRowIndex, 1, refRowIndex);\n\n                ws.Cells[refRowIndex, refColumnIndex + 0].Value = index + 1;\n                //TODO: write here other rows...\n\n            }\n\n            pck.Save();\n        }	0
6932089	6873527	Validation errors during model generation	A.B.C.A	0
27090758	27090139	Fetching results from MySQL	using(var conn = new MySqlConnection(connectionString))\nusing(var cmd = conn.CreateCommand())\n{\n    conn.Open();\n    cmd.ComamndText = query;\n\n    var adp = new MySqlDataAdapter(cmd);\n\n    var dt = new DataTable();\n    adp.Fill(dt);\n\n    // here you can use the table's rows array to retrieve results\n    // for example\n\n    foreach (var row in dt.Rows)\n    {\n        //Do what you want now with this row\n    }\n}	0
31604083	31603979	Create a json request object in c#	public class Request\n{\n    public int order_id { get; set; }\n    public string action { get; set; }\n}\n\npublic class RootObject\n{\n    public int channel_id { get; set; }\n    public List<Request> requests { get; set; }\n}	0
23925142	23924550	How do i Create a Pie Chart using Time duration as Parameters in C# Mine is not working	tags = new Dictionary<string, string>\n        {\n            {"WIN",DateTime.Now.Ticks.ToString()},\n            {"LOOSE",DateTime.Now.Ticks.ToString()}                  \n        };	0
4648010	4646004	Help me to split string with Regular Expression	Match match = Regex.Match(subjectString, \n    @"(.*?)     # Match any number of characters and capture them\n    =\{         # Match ={\n    (           # Match and capture the following group:\n     (?:        # One or more occurences of the following:\n      (?>[^$]+) # One or more characters except $, match possessively and capture\n      \$?       # Match the delimiting $ (optionally, because it's not there after the last item)\n     )+         # End of repeating group\n    )           # End of capturing group\n    \}          # Match }\n    ", \n    RegexOptions.IgnorePatternWhitespace);\nConsole.WriteLine("Matched text: {0}", match.Value);\nConsole.WriteLine("Word1 = \"{0}\"", match.Groups[1].Value);\nConsole.WriteLine("Word2 = \"{0}\"", match.Groups[2].Value);    \ncaptureCtr = 0;\nforeach (Capture capture in match.Groups[3].Captures) {\n    Console.WriteLine("      Capture {0}: {1}", \n                             captureCtr, capture.Value);\n    captureCtr++; \n}	0
8154208	8154094	C# - String sorting by other string as helper	var ordered = strings.OrderByDescending(s => s.StartsWith("Ma")).ThenBy(s => s);	0
17944520	17942938	How do I show busy window when button click in winform apps	private void btnSearch_Click(object sender, EventArgs e)\n    {\n        this.btnSearch.Enabled = false;\n        this.Cursor = Cursors.WaitCursor;\n        this.wfrm.Show();\n\n        Thread t = new Thread(this.Search);\n        t.Start();\n    }\n\n    private void Search()\n    {\n        while (isWorking)\n        {\n            DoHeavyWork();\n            this.Invoke(new Action(ReportToWaitForm);\n        }\n\n        this.Invoke(new Action(() =>\n            {\n                this.btnSearch.Enabled = true;\n                this.Cursor = Cursors.Default;\n                this.wfrm.Hide();\n            }));\n    }	0
22841384	22841241	Inserting into a MySQL database table, using C#, a string that can contain double quotes	string sqlStr = "INSERT INTO table(ID, Comment) VALUES ";\nforeach (KeyValuePair<string, string> kvp in myDict)\n{\n    string id = kvp.Key;\n    string comment = String.Format("'{0}'", kvp.Value);\n    sqlStr +=  String.Format("({0}, {1}), ";\n}\n// strip last comma\nsqlStr = sqlStr.Substring(0, sqlStr.Length - 2);\nconn.DoSql(sqlStr);	0
16912006	16911933	Copy datatable as columns in another datatable	List<DataTable> sourceTables = getYourSourceTablesMethod();\nif (sourceTables.Length>0)\n{\n    DataTable destTable = sourceTables[0].Copy();  \n\n    for (int i = 1; i < sourceTables; i++) \n    {\n       foreach (DataRow drow in sourceTables[i].Rows) \n       destTable.Rows.Add(drow.ItemArray);\n    }\n}	0
452802	452794	Returning null value from generic method	if (object.Equals(resultValue, default(K)))\n{\n    //...\n}	0
2092152	2092127	quiting a c# application leaves it in memory	new Thread()	0
2698274	2698221	Need sorted dictionary designed to find values with keys less or greater than search value	list.Where(e => A < e.Price || e.Price < B);	0
7644853	7644796	Read Value from Resource file using String	Resources.ResourceManager.GetString(test.Sun.ToString())	0
9029213	9028992	ASP.NET - Accessing All ImageButtons on a Page and Putting Two Images on an ImageButton	protected void ImageButton5_Click(object sender, ImageClickEventArgs e)\n{\n    ImageButton clickImageButton = sender as ImageButton;\n\n    // This example assumes all the image buttons have the same parent.\n    // Tweak as needed depending on the layout of your page\n    Control parentControl = clickImageButton.Parent;\n    List<ImageButton> allOtherImageButtons = parentControl.Controls.OfType<ImageButton>().AsQueryable().Where(i => i.ID != clickImageButton.ID).ToList();\n\n    // Highlight\n    clickImageButton.CssClass = "WhateverHighlights";\n\n    // Unhighlight\n    foreach (ImageButton button in allOtherImageButtons)\n    {\n        button.CssClass = "WhateverClears";\n    }\n}	0
18656083	18656005	C# - using value twice within object initialiser	People= xDocument.Root.Descendants("People")\n    .Select(se => new { ID=Get<int>(se.Element("ID")) })\n    .Where(x => x.ID != i1)\n    .Select(x => new Person\n          {\n             ID = x.ID,\n             Skills = GetPersonSkills(x.ID)\n          }\n    ).OrderBy(w => w.FirstName)\n    .ToList();	0
22108657	22108624	How to pass a derived class property to the constructor of a base class	class derivedClass:baseClass\n{\n    static string specialFilePath=@"x:\abc.def";\n\n    public derivedClass():base(specialFilePath)\n    {\n    }\n}	0
2069331	2069231	Writing a Modified Image to Disk	File.WriteAllBytes(dialog.FileName, ImageBytes);	0
1501187	1484992	Ninject 2.0 Constructor parameter - how to set when default constructor is also present?	[Inject] \npublic TestClass(string message){...}	0
3209831	3206591	How can I get my logger to overwrite old log file in C# using Enterprise Library?	logfile.log	0
4205949	4205907	Is it possible to define a local struct, within a method, in C#?	public void SomeMethod ()\n{\n    var anonymousTypeVar = new { x = 5, y = 10 };\n}	0
3157121	3156953	Draw dashed line in a WPF adorner	var pen = new Pen(new SolidColorBrush(Color.FromRgb(200, 10, 20)), 2);\npen.DashStyle = DashStyles.Dash;\ndrawingContext.DrawLine(pen, point1, point2);	0
10954926	10954834	How to find a DropDownList in a GridView ItemTemplate without RowDataBound?	DropDownList ddlRoom = null;\nforeach(var gridRow in gv.Rows)\n{\n    ddlRoom = gridRow.FindControl("ddlRoom") as DropDownList;\n    if (ddlRoom != null)\n    {\n        //your code here\n    }\n}	0
11950260	11949881	How I can open a ModalDialog about a LinkButton from a ListView	protected void myListView_ItemCommand(object sender, ListViewCommandEventArgs e)\n  {\n    if (String.Equals(e.CommandName, "Select"))\n    {\n      ModalPopupExtender1.Show();\n      //your code\n    }\n }	0
11504238	11504222	How to convert a space into non breaking space entity in c#	string s = " ";\nif(s == " ")\n{\n s = "&nbsp;"\n}\n\nOr use "My name  is this".Replace(" ", "&nbsp;");	0
12739488	12739448	Meaning of the underscore in WaitCallback	new WaitCallback(x => { MyMethod(param1, Param2); })	0
16325285	16325201	I resized uploaded images but it still have big size	bmw.Save(MapPath("~/image/thumb/") + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);	0
6239659	6239373	How to avoid "too many parameters" problem in API design?	public class Param\n{\n    public string A { get; private set; }\n    public string B { get; private set; }\n    public string C { get; private set; }\n\n    public class Builder\n    {\n        private string a;\n        private string b;\n        private string c;\n\n        public Builder WithA(string value)\n        {\n            a = value;\n            return this;\n        }\n\n        public Builder WithB(string value)\n        {\n            b = value;\n            return this;\n        }\n\n        public Builder WithC(string value)\n        {\n            c = value;\n            return this;\n        }\n\n        public Param Build()\n        {\n            return new Param { A = a, B = b, C = c };\n        }\n    }\n\n\n    DoSomeAction(new Param.Builder()\n        .WithA("a")\n        .WithB("b")\n        .WithC("c")\n        .Build());	0
16739205	16739093	ModelState.IsValid - Can you validate part of a model	RemoveValidationError("FunkyThingsOrder.CustomerName");\nRemoveValidationError("FunkyThingsOrder.ContactNumber");\nRemoveValidationError("FunkyThingsOrder.EmailAddress");\n\nprotected void RemoveValidationError(string name)\n{\n    for (var i = 0; i < ModelState.Keys.Count; i++)\n    {\n        if (ModelState.Keys.ElementAt(i) == name &&\n            ModelState.Values.ElementAt(i).Errors.Count > 0)\n        {\n            ModelState.Values.ElementAt(i).Errors.Clear();\n            break;\n        }\n    }\n}	0
30436230	30436184	Return From process	Process.StandardOutput	0
18516838	18319898	How to completely clear/set text of WinRT's RichEditBox?	string temp;\n        // Do not ask for RTF here, we just want the raw text\n        richEditBox.Document.GetText(TextGetOptions.None, out temp);\n        var range = richEditBox.Document.GetRange(0, temp.Length - 1);\n\n        string content;\n        // Ask for RTF here, if desired.\n        range.GetText(TextGetOptions.FormatRtf, out content);	0
12015842	12015812	How to sort strings so strings that start with a search term are at first?	.Where(x => x.Contains(search)).OrderBy(x => x.IndexOf(search)).ToArray()	0
4027893	4022724	Injecting a property when creating a Object	Bind<LoggedTextWriter>().ToSelf();\n\nBind<ICustomWriter>().To<MyCustomWriter>();\n\nBind<DataContext>().ToMethod(x => \n    new DataContext(@"Data Source=localhost\sqlexpress2008;Initial Catalog=MyDB;Integrated Security=True")\n    {\n        ObjectTrackingEnabled = true,\n        Log = x.Kernel.Get<LoggedTextWriter>()\n    });	0
11464707	11462199	Ignore ReSharper naming rules for DTOs	*.DTO.cs	0
7219929	7219796	C#: Insert strings to another string - performance issue	private string RestoreText(string text)\n{\n    var sb = new StringBuilder();\n    var totalLen = 0;\n    var orgIndex = 0;\n    foreach (var pair in _tags.OrderBy(t => t.Key))\n    {\n        var toAdd = text.Substring(orgIndex, pair.Key - totalLen);\n        sb.Append(toAdd);\n        orgIndex += toAdd.Length;\n        totalLen += toAdd.Length;\n\n        sb.Append(pair.Value);\n        totalLen += pair.Value.Length;\n    }\n    if (orgIndex < text.Length) sb.Append(text.Substring(orgIndex));\n    return sb.ToString();\n}	0
26608905	26608714	Can't resolve namespace while parsing a XML wih XDocument	var nodeValue = XDocument.Parse(resultado)\n                         .Descendants()\n                         .First(n => n.Name.LocalName == "MensajeError")\n                         .Value;\n\n//nodeValue = "error1"	0
8051250	8037815	Get List of DataKeyValues from RadGridView using LINQ	List<GridDataItem> Items = (from item in rgShipProducts.MasterTableView.Items.Cast<GridDataItem>()\n                                where  ((CheckBox)item.FindControl("chkChangeAddr")).Checked\n                                select item).ToList();\n\n    if (Items.Count > 0)\n    {\n        string strkey = Items[0].GetDataKeyValue("ID").ToString();\n    }	0
6683215	6680560	ASP.NET, Webservice response as a download link for Android	//Forces Download/Save rather than opening in Browser//\n  public static void ForceDownload(string virtualPath, string fileName)\n  { \n\n    Response.Clear();\n    Response.AddHeader("content-disposition", "attachment; filename=" + fileName);\n    Response.WriteFile(virtualPath);\n    Response.ContentType = "";\n    Response.End(); \n\n  }	0
31822141	31821790	StreamContent from HttpResponseMessage into XML	string response;\n\nusing(var http = new HttpClient())\n{\n    response = await http.GetStringAsync("http://localhost/api/info");\n}\n\nvar xml = new XmlDataDocument();\nxml.LoadXml(response);	0
5464380	5463980	Cleaner way of abstraction	interface IMyInterface\n{\n    void Step1();\n    void Step2();\n    void Step3();\n}\n\nabstract class MyBaseClass : IMyInterface\n{\n    public abstract void Step1();\n    public void Step2()\n    {\n        Step2_1();\n        Step2_2();\n    }\n    public abstract void Step3();\n\n    protected abstract void Step2_1();\n    protected abstract void Step2_2();\n}	0
13256724	13256687	wpf binding to another control property	"RelativeSource"	0
22467792	22446468	How can I dynamically include external files / user control?	// Include external files here\n// CustomControl variable can equal something like "home.ascx"\nUserControl uc = (UserControl)Page.LoadControl("~/pages/" + CustomControl);\n// PageCustomControl can be a Panel or PlaceHolder\nPageCustomControl.Controls.Add(uc);	0
30150842	30150472	LINQ to Objects: How to join different properties in the same List of objects	var listOfNames = items.Select(t => t.Name);\n\nvar answers = items.Where(item => i.ParentItemName != null && \n                         !listOfItems.Contains(i.ParentItemName));	0
13457795	13312667	How Can I connect AS/400 from MY simple ASP.net and C# program Which Take parameters from URL	iDB2Connection connDB2 = new iDB2Connection(\n            "DataSource=158.7.1.78;" +\n            "userid=*****;password=*****;DefaultCollection=MYTEST;");	0
22860465	22856885	How to make NHibernate auto-save dirty entities?	FlushMode.Always	0
4852881	4852834	How to set endianness when converting to or from hex strings	int otherEndian = (value << 16) | (((uint)value) >> 16);	0
5514365	5509967	Repeatation of Comboboxes	foreach (DataRow row in ds_PromotionDesignationTo.Tables["tbl_org_Desg"].Rows)\n        {\n            if ((int)row["DEG_ID"] != (int)cmbPromotionDesignationFrom.SelectedValue)\n            {\n                myAL.Add(new USState(row["DEG_ID"].ToString(), row["DEG_NAME"].ToString()));\n            }\n        }	0
15372974	15372930	Get all elements that only occur once	var result =\n    from x in xs\n    group xs by x into grp\n    where grp.Count() == 1\n    select grp.Key;	0
7227325	7227278	.NET DateTime to time_t in seconds	(dt - new DateTime (1970, 1, 1)).TotalSeconds	0
27807122	27792869	How to insert text into the cursor position in a powepoint shape's TextRange	With ActiveWindow.Selection.TextRange\n    .InsertAfter ("D")\nEnd With	0
23996521	23670444	How to find the index of a paragraph in word 2010	int i = 1;\n              foreach (Word.Paragraph aPar in oDoc.Paragraphs)\n              {\n              string sText = aPar.Range.Text;\n             if (sText != "\r")\n             {\n               if (sText == para[1].ToString() + "\r")\n               {\n               Word.Range range = oDoc.Paragraphs[i + 1].Range;\n               if (!range.Text.Contains("GUID:"))\n                   {\n                       int pEnd = aPar.Range.End;\n                       string guid = "GUID:" + para[0].Replace("{", "").Replace("}", "");\n                       int length = guid.Length;\n                       aPar.Range.InsertAfter(guid);\n                       Word.Range parRng = oDoc.Range(pEnd, pEnd + length);\n                       parRng.Font.Hidden = 1;\n                       parRng.InsertParagraphAfter();\n                       }\n                     }\n                   }\n                   i++;\n                 }	0
6474667	6472055	Update binding of property in silverlight	public class ViewModelBase : INotifyPropertyChanged\n{\n    protected delegate void OnUiThreadDelegate();\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected virtual void SendPropertyChanged(string propertyName)\n    {\n        if (this.PropertyChanged != null)\n        {\n            // Ensure property change is on the UI thread\n            this.OnUiThread(() => this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));\n        }\n    }\n\n    protected void OnUiThread(OnUiThreadDelegate onUiThreadDelegate)\n    {\n        // Are we on the Dispatcher thread ?\n        if (Deployment.Current.Dispatcher.CheckAccess())\n        {\n            onUiThreadDelegate();\n        }\n        else\n        {\n            // We are not on the UI Dispatcher thread so invoke the call on it.\n            Deployment.Current.Dispatcher.BeginInvoke(onUiThreadDelegate);\n        }\n    }\n}	0
9415021	9404740	Problems when executing SQL Where statement with a date	#YYYY/MM/DD#	0
29876257	29875959	How to keep some columns and rows of jagged array and remove unwanted columns and rows in c#	int[] day = {1,4,5};\nint[][] finalDists = \n        dists.Where((arr, i) => i == 0 || day.Contains(i)) //skip rows\n       .Select(arr=> arr.Where((item, i) => i == 0 || day.Contains(i)) //skip cols\n       .ToArray())\n       .ToArray();	0
17146834	17145750	Read public posts from Blogger using API	XDocument feed = XDocument.Load(rssUrl);   //rssUrl is the URL to the rss page that (most) blogs publish\nSyndicationFeed sf = SyndicationFeed.Load(feed.CreateReader());\nforeach (SyndicationItem si in sf.Items)\n{\n    ..you've now got your feed item...\n}	0
10611735	10611651	Populating a tree recursively with database contents	var root = new {TopLevelNodes = Table3.Select(t3=> new {Id = t3.Table2_id, SubLevel = t3.FieldA.Select(t2=>new {t2.FieldA})})};	0
5249833	5249468	How can I assign a .NET 4 WinForm application to the owner property of a Delphi 7 form?	Application.Handle	0
4208161	4205655	Sitecore Rich Text Editor - Using this control in a Webcontrol	sitecore\shell\controls\Rich Text Editor	0
6684661	6684480	Moq - How to return a mocked object from a method?	Person GetPerson()\n{\n    return new Person()\n                       {\n                           FirstName = "Joe",\n                           LastName = "Smith",\n                           PhoneNumber = "555-555-5555"\n                       };\n}	0
1003894	1003715	Using an interface in a C# xml web service	[Serializable]\npublic class TestClass\n{\n     private ICustomInterface _iCustomInterfaceObject;\n\n     public ICustomInterface CustomInterfaceProperty\n     {\n         get { return _iCustomInterfaceObject; }\n         set { _iCustomInterfaceObject = value; }\n     }\n}	0
31021706	31020428	How to get gridview row value in string without using rowindex?	int columnIndex = -1;\n\n    foreach (DataControlField col in grid.Columns)\n    {\n        if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())\n        {\n            columnIndex = grid.Columns.IndexOf(col);\n        }\n    }	0
7099521	7099485	Can't find a link button in a repeater	if(e.Item.ItemType == ItemType.Item || e.Item.ItemType == ItemType.AlternatingItem)\n {\n      LinkButton myButton = (LinkButton)e.Item.FindControl("editbutton");\n      myButton.OnClientClick = (popupWindow.GetTargetPopupCode("URL");\n }	0
20951403	20896699	Exchange Server 2007 Transport Agent Issue	using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nusing Microsoft.Exchange.Data.Transport;\nusing Microsoft.Exchange.Data.Transport.Routing;\n\n\n\nnamespace MyAgents\n{\n    public sealed class MyAgentFactory : RoutingAgentFactory\n    {\n        public override RoutingAgent CreateAgent(SmtpServer server)\n        {\n            return new MyAgent();\n        }\n    }\n    public class MyAgent : RoutingAgent\n    {\n        public MyAgent()\n        {\n            this.OnSubmittedMessage += new SubmittedMessageEventHandler(this.MySubmittedMessageHandler);            \n        }\n\n        public void MySubmittedMessageHandler(SubmittedMessageEventSource source, QueuedMessageEventArgs e)\n        {\n            e.MailItem.Message.Subject = "This message passed through my agent: " + e.MailItem.Message.Subject;\n        }\n    }\n}	0
1833909	1833557	Using Microsoft T4 to create data access classes	for(int i = 0; i < table.Columns.Count; i++)\n{\n    Write(string.Format("(ordinal_{0}_{1}.HasValue)", table.Name, table.Columns[i].Name));\n    if(i < (table.Columns.Count - 1))\n    {\n        WriteLine(" ||");\n    }\n}	0
5953078	5953045	How should I return an Image from a controller action c# asp.net-mvc-2?	return File(byteArray, "image/png");	0
616513	616491	Winforms: How can I programmatically display the last item in a C# listview when there are vertical scrollbars?	var items = listView.Items;\nvar last = items[items.Count-1];\nlast.EnsureVisible();	0
31520288	31520034	MS SQL ODBC Connection with NO Windows Authentication	Driver={SQL Server Native Client 11.0};Server=127.0.0.1;Database=HMS;Uid=sa;Pwd=root;	0
34225013	34224780	How to call event key_down only in specific situations in c#?	private void MyForm_KeyDown(object sender, KeyEventArgs e)\n        {\n            if (e.KeyCode == Keys.Enter)\n            {\n                if (textBox1.Focused) // or whatever your textbox is called\n                {\n                    buttonSearch_Click(sender, e);   \n                }\n            }\n\n        }	0
26491526	26491257	How do you merge two objects in AutoMapper?	var merged = new NameValueContainer\n{\n    Name = first.Name,\n    Values = first.Values.Union(second.Values).ToList()\n};\n//merged.Values: "Value1", "Value2", "Value3"	0
1010170	1009839	Split String by length	Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);	0
5915170	5915033	Use of Namespaces in C#	using System;\n...\nclass MyException : Exception \n...	0
9023176	9022936	Instead of scanning multiple ports I'm scanning only one and when port is closed my app closes	private void CallBack(IAsyncResult result) \n{ \n    var client = (TcpClient)result.AsyncState; \n    bool connected = false;\n\n    try\n    {\n        client.EndConnect(result);\n        connected = client.Connected;\n    }\n    catch (SocketException)\n    {\n    }\n    catch (ObjectDisposedException)\n    {\n    }\n    finally\n    {\n        if (client.Connected)\n        {\n            client.Close();\n        }\n\n        client.Dispose();\n    }\n\n    if (connected) \n    { \n        this.Invoke((MethodInvoker)delegate \n        { \n            txtDisplay.Text += "open2" + Environment.NewLine; \n        }); \n    } \n    else \n    { \n        this.Invoke((MethodInvoker)delegate \n        { \n            txtDisplay.Text += "closed2" + Environment.NewLine; \n        }); \n    } \n}	0
16145482	16144959	How to get a Type from an object in another DLL?	var myAssembly = Assembly.LoadFile(...);\nvar myType = myAssembly.GetType(...);\ndynamic myObject = Activator.CreateInstance(myType);\nif (myObject != null) {\n    var createdDate = myObject.CreatedDate;\n}	0
14992937	14992867	multithreading: starting a thread to execute a query while another process keeps going	Task.Factory.StartNew(() => x.ExecuteQuery());	0
25645562	25629864	COM Exception while inserting a multi dimensional list to an excel sheet	worksheet1.Cells[i, j].Value = listExport[i - 1].over;	0
7690134	7689284	Linq to Entities (EF 4.1): How to do a SQL LIKE with a wildcard in the middle ( '%term%term%')?	dt.Table.Where(p => SqlFunctions.PatIndex(term, p.fieldname) > 0);	0
3250904	3250794	Gems with .NET Applications - How do I set up the Executables so they run without error?	result = system(File.dirname(__FILE__) + "/rh.exe" ARGV.join(' '))\nexit 1 unless result	0
14549056	14549000	Draw a PNG Image on the Server	using (Bitmap b = new Bitmap(50, 50)) {\n  using (Graphics g = Graphics.FromImage(b)) {\n    g.Clear(Color.Green);\n }\n  b.Save(@"C:\green.png", ImageFormat.Png);\n}	0
25650296	25650039	Overloading a method in com visible dll	Write_2()	0
10264159	10264049	Byte to string for hash function?	student.Password = Convert.ToBase64String(passwordHash);	0
34126650	34035446	On asp.net application end page view count data in not updating	void Application_End(object sender, EventArgs e)\n{\n   // Code that runs on application shut`enter code here`down\n}	0
16943521	16937088	Entity framework connection string enable to conncet to DB server	public DistributionSSEntities Connection()\n    {\n        string ConString = "SERVER=192.168.1.100;DATABASE=DistributionSS;UID=sa;PASSWORD=125;";\n        SqlConnectionStringBuilder SCB= new SqlConnectionStringBuilder(ConString);\n        //------------------------\n        EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();\n        builder.Metadata = "res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";\n        builder.Provider = "System.Data.SqlClient";\n        builder.ProviderConnectionString = SCB.ConnectionString;\n        DistributionSSEntities db = new DistributionSSEntities(builder.ToString());\n        return db;\n    }	0
20199861	20199784	Gridview show empty row	public class showFacReq {\n  public string documentNumber {get;set;}\n  //do the same for others\n  //....\n}	0
32595563	32590466	Delegate in Python in combination with unity	butn.onClick.AddListener(lambda item=item: dicbrowser(holderdict[item],0))	0
8172284	8171910	How to retain executing thread's context during call to QueueUserWorkItem in ASP.Net?	public static bool QueueUserWorkItem(\n    WaitCallback callBack,\n    Object state\n)	0
10269441	10269207	How to Clone a child of an abstract class in WP7 XNA	class EnemyFactory\n{\n Enemy CreateEnemy(int id)\n {\n  if (id == 0)\n   return new Snake();\n  return new GenericEnemy();\n }\n\n}\n\n\nvoid LoadLevel()\n{\n // bla bla\n Level level = new Level();\n int enemyId = LoadFromFile();\n level.AddEnemy(EnemyFactory.CreateEnemy(enemyId));\n}	0
31766172	31765969	How to use a singleton timer in an attached behavior to change the background color on ListViewItems?	static void OnMyValueChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)\n{\n    var item = depObj as ListViewItem;\n    if (item == null) return;\n\n    View_encountertime vt = item.DataContext as View_encountertime;\n\n    ListTimer.ListTimerEvent += (sender, e) =>\n    {\n        Timer timer = sender as Timer;\n\n\n        var y = item.GetValue(MyValueProperty);\n        <--  put logic to set the background color here\n\n    }\n}	0
2692451	2692318	Using two namespaces when defining a new xml file (XDocument, XElement, XAttribute)	using System;\nusing System.Xml.Linq;\n\nclass Example\n{\n    static void Main()\n    {\n        XNamespace xnRD = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner";\n        XNamespace xnNS = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition";\n\n        XDocument doc = new XDocument(\n                new XDeclaration("1.0", "utf-8", "yes"),\n                    new XElement(xnNS + "Report",\n                    new XAttribute(XNamespace.Xmlns + "rd", xnRD),\n                        new XElement("DataSources"),\n                        new XElement("DataSets"),\n                        new XElement("Body"),\n                        new XElement("Width"),\n                        new XElement("Page"),\n                        new XElement(xnRD + "ReportID"),\n                        new XElement(xnRD + "ReportUnitType")));\n\n        Console.WriteLine(doc.ToString());\n    }\n}	0
29968300	29968224	Changing the Background color of GridView Row as per condition dynamically	protected void OnRowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow && !((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit)))\n    {\n        Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");\n        DateTime EndDate = DateTime.Parse(lblEndDate.Text);\n        if (EndDate<DateTime.Today)\n        {\n            e.Row.BackColor = System.Drawing.Color.MistyRose;\n        }\n    }	0
16662483	16662465	C# Send tweets on twitter from multiple accounts	var auth = new ApplicationOnlyAuthorizer\n    {\n        Credentials = new InMemoryCredentials\n        {\n            ConsumerKey = "twitterConsumerKey",\n            ConsumerSecret = "twitterConsumerSecret"\n        }\n    };\n\n    auth.Authorize();\n\n    var twitterCtx = new TwitterContext(auth);\n    var tweet = twitterCtx.UpdateStatus("Hello world");	0
1559902	1559863	How to remove proxy from WebRequest and leave DefaultWebProxy untouched	request.Proxy = new WebProxy();	0
29254703	29254585	Download Excel package as file without creating a physical file?	Response.Clear();\nResponse.AddHeader("content-disposition", "attachment; filename=LeadsExport.xlsx");\nResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";                    \nResponse.BinaryWrite(package.GetAsByteArray());\nResponse.End();	0
11869685	11868509	Copying a row from one table to another using LINQ and C#	INSTRUMENT_DATA_SHEET _original = (INSTRUMENT_DATA_SHEET)e.OriginalObject;\nINSTRUMENT_DATA_SHEET_HISTORY _history = new INSTRUMENT_DATA_SHEET_HISTORY();\n\nforeach (PropertyInfo pi in _original.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))\n{\n    _history.GetType().GetProperty(pi.Name).SetValue(_history, pi.GetValue(_original, null), null);\n}	0
12153514	12153489	Changeable config values	~/App_Data	0
16373362	16356630	How to document C# projects/assemblies with XML comments and Doxygen?	XML Documentation file	0
19152924	19152830	how to generate the buttons using Button class?	public void BindBatches()\n   {\n    DataTable dtgetbatches = new DataTable();\n    divBatches.Controls.Clear();\n    dtgetbatches = breederdailybal.GetBreederBatches();\n    if (dtgetbatches.Rows.Count > 0)\n    {\n\n        for (int i = 0; i < dtgetbatches.Rows.Count; i++)\n        {\n            Button btnbatch = new Button();\n            btnbatch.ID = dtgetbatches.Rows[i]["batch"].ToString();\n            btnbatch.Text = "Batch" + " " + dtgetbatches.Rows[i]["batch"].ToString();\n            btnbatch.Width = 90;\n            btnbatch.ForeColor = Color.White;\n            btnbatch.BackColor = Color.Green;\n            btnbatch.Click += new EventHandler(btnbatch_Click);\n\n            divBatches.Controls.Add(btnbatch);\n            LiteralControl @break1 = default(LiteralControl);\n            @break1 = new LiteralControl("&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp");\n            divBatches.Controls.Add(@break1);\n       }\n    }	0
9458971	9458938	Loading from string instead of document/url	string htmlString = 'Your html string here...';\n\nHtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();\nhtmlDocument.LoadHtml(htmlString);\n\n// Do whatever with htmlDocument here	0
3235819	3234903	Create a adapter without knowing the driver type	Public Overridable Function CreateDataAdapter() As System.Data.Common.DbDataAdapter\n     Member of System.Data.Common.DbProviderFactory\nSummary:\nReturns a new instance of the provider's class that implements the System.Data.Common.DbDataAdapter class.\n\nReturn Values:\nA new instance of System.Data.Common.DbDataAdapter.	0
8047316	8047249	How to do this in VB.NET?	context.Load(context.GetLecturesQuery(), AddressOf LoadLecturer, Nothing)	0
31760251	31697566	using <include> in xamarin android dynamically	LayoutInflater inflater = LayoutInflater.From(this);\n View  inflatedLayout = inflater.Inflate(Resource.Layout.yourlayput, null);                  \n LinearLayout ll =  this.Window.FindViewById<LinearLayout>(Resource.Id.container);\nll.AddView(inflatedLayout);	0
20771194	20771104	A generic error occurred in GDI+ when trying to save image downloaded with WebClient	byte[] oImageBytes = oWebClient.DownloadData("http://images1.ynet.co.il/PicServer3/2013/12/25/5058381/505838001000100396220.jpg");\n\nFile.WriteAllBytes("d:\\temp\\1.jpg", oImageBytes);	0
13290583	13254907	How can I create a matching HMAC value to verify a Shopify WebHook in .NET?	post '/' do\n\n  . . .\n\n  data = request.body.read\n  verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"])\n\n  . . .\n\nend	0
17344396	17343891	Authenticating to Google API with OAuth2	var provider = new AssertionFlowClient(\n            GoogleAuthenticationServer.Description,\n            new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))\n        {\n            ServiceAccountId = serviceAccountEmail,\n            Scope = DriveService.Scopes.Drive.GetStringValue(),\n            ServiceAccountUser = driveHolderAccountEmail\n        };\n        var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);\n\n        m_service = new DriveService(new BaseClientService.Initializer()\n        {\n            Authenticator = auth\n        });	0
14944362	14910374	binding windows 8 textBlock in MVVM light	xmlFileTextContent = await FileIO.ReadTextAsync(storageFile);	0
29436207	29433936	How to execute a SQL statement with SQL Server CE using a local database in C#	[Close], [Open], [Date]	0
18122801	18119624	SelectedValue for ComboBox not getting set	cmbContactType.SelectedValue =_row["ContactType"] != null ? Convert.ToInt16(_row["ContactType"]) : (Int16)(-1) ;	0
15115512	15101665	Improving SQLite Performance	using (SqliteConnection conn = new SqliteConnection(@"Data Source=:memory:")) \n{\n  conn.Open();\n  using(SqliteTransaction trans = conn.BeginTransaction())\n  {\n    using (SqliteCommand cmd = new SQLiteCommand(conn))\n    {\n      cmd.CommandText = File.ReadAllText(@"file.sql");\n      cmd.ExecuteNonQuery();\n    }\n    trans.Commit();\n  }\n  con.Close();\n}	0
2750956	2743321	Linq - get compare with transliterated value of fields	m_DataContext.Table\n .ToList()\n .Select(r => r.name=CTransliteration.Transliterate(r.Name));	0
6571535	6571075	Default data for installation	Session.Save()	0
26854673	26854567	C# converting byte array to string	public static void Main()\n{        \n    StringBuilder str = new StringBuilder();\n    byte[] x = { 0xB1, 0x53, 0x63 };\n    for (int i = 0; i < 3; i++)\n    {\n        str.Append(Convert.ToString(x[i], 2).PadLeft(8, '0'));\n    }\n    Console.WriteLine(str);\n    Console.ReadLine();\n}	0
842166	842135	Use C# regex to convert casing in a string	const string mod = @"^([a-z][a-z0-9]{1,2})(_\d{3}[a-z]{0,2}_[a-z]+_v{1}\d{3,5})$";\nvar converted = \n    new Regex(mod, RegexOptions.IgnoreCase)\n        .Replace(input1, \n            m => string.Format(\n                   "{0}_{1}",\n                   m.Groups[1].ToString().ToUpper(),\n                   m.Groups[2].ToString().ToLower()\n                 )\n                );	0
10092417	10092378	what attribute can open a controller's action to require no authentication?	[AllowAnonymousAttribute]	0
8497312	8497192	How do I put XML into a List of Dictionaries with C# on Windows Phone 7	public static void Main(string[] args)\n        {\n            string xml = @"\n<rss version='2.0'>\n    <item>\n        <date>01/01</date>\n        <word>aberrant</word>\n        <def>straying from the right or normal way</def>\n    </item>\n\n    <item>\n        <date>01/02</date>\n        <word>Zeitgeist</word>\n        <def>the spirit of the time.</def>\n    </item>\n</rss>";\n            var xdoc = XDocument.Parse(xml);\n            var result = xdoc.Root.Elements("item")\n                .Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))\n                .ToList();\n\n        }	0
11805200	11804590	How can I find the em height of a font in Silverlight?	Font Metric Class	0
23214959	23127647	How to set the isolation level for Entity Framework CodeFirst Migrations	internal sealed class Configuration : DbMigrationsConfiguration<SupplierEntities>\n{\n  public Configuration()\n  {\n    SetSqlGenerator("System.Data.SqlClient", new SqlMigrator());\n  }\n\n  private class SqlMigrator : SqlServerMigrationSqlGenerator\n  {\n    public override IEnumerable<MigrationStatement> Generate(\n      IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)\n    {\n      yield return new MigrationStatement { Sql = "set transaction isolation level read committed" };\n      foreach (var statement in base.Generate(migrationOperations, providerManifestToken))\n        yield return statement;\n    }\n  }\n}	0
11326739	11326564	Reading specific number of lines from text file in c#	var lines = File.ReadLines("yourfile").Take(300);\nreadlines[i] = string.Join("-", lines);	0
18320206	18319669	Map two enumerations to a third single enumeration	public enum A { X, ... }\npublic enum B { Y, Z, ... }\npublic enum C { Cat, Dog, ... }\n\nprivate static readonly Dictionary<Tuple<A, B>, C> lookup =\n    new Dictionary<Tuple<A, B>, C>\n    {\n        { Tuple.Create(A.X, B.Y), C.Cat },\n        { Tuple.Create(A.X, B.Z), C.Dog },\n        ...etc...\n    };\n\npublic static C Lookup(A a, B b)\n{\n    return lookup[Tuple.Create(a, b)];\n}	0
13768106	13767800	how do I display an image stored inside a variable in an MVC3 Razor View	for(int i= 0; i< MyModel.ImageCount(); i++){\n\n     <img src="@Url.Action("GetImage", "Home")" />\n\n\n}	0
15518869	15518830	How to give relative path in asp.net 2012	transform.Load(Server.MapPath("/XML/a.xsl"));	0
30477270	30473100	Adding a sub-application to an existing IIS application programmatically	ServerManager serverManager = new ServerManager();\n\nSite site = serverManager.Sites.Add("company.com", @"C:\tmp\company.com\www", 8080);\nsite.Applications.Add("/app", @"C:\tmp\company.com\app");\nsite.Applications.Add("/app/subApp1", @"C:\tmp\company.com\subApp1");\n\nserverManager.CommitChanges();	0
6507655	6507490	How to copy file from UNC-share to local system?	var token = default(IntPtr);\n    using (var context = default(WindowsImpersonationContext))\n    {\n       LogonUser(_config.Username, _config.Domain, _config.Password, 2, 0, out token);\n       context = WindowsIdentity.Impersonate(token);\n       var bytes = File.ReadAllBytes("remote-unc-path");\n       context.Undo();\n       CloseHandle(token);\n       File.WriteAllBytes("local-path", bytes);\n    }	0
3317704	3316613	Nerd Dinner pagginated list - how do I add a linq orderby clause dynamicaly? ANYONE?	class A\n    {\n        public String Foo { get; set; }\n        public Int32 Bar { get; set; }\n        public override string ToString()\n        {\n            return Foo + ":" + Bar.ToString();\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var x = new List<A> { new A { Foo = "ABC", Bar = 100 }, new A() { Foo = "ZZZ", Bar = 0 } };\n        Func<A, String> order1 = (a) => a.Foo;\n        Func<A, Int32> order2 = (a) => a.Bar;\n\n        PrintQuery(x, order1);\n        Console.WriteLine();\n        PrintQuery(x, order2);\n        Console.ReadLine();\n    }\n\n    static void PrintQuery<T>(IEnumerable<A> query, Func<A, T> orderFunc)\n    {\n        foreach (var e in query.OrderBy(orderFunc))\n            Console.WriteLine(e);\n    }	0
28266050	28265990	I need help to get URL with Regex?	(?<=\()['"]?(.+?)['"]?(?=\))	0
21907475	21905098	POST request without content pass model validation	public class ValidateModelAttribute : ActionFilterAttribute\n{\n    public override void OnActionExecuting(HttpActionContext actionContext)\n    {\n        if (!actionContext.ModelState.IsValid)\n        {\n            actionContext.Response = actionContext.Request.CreateErrorResponse(\n                HttpStatusCode.BadRequest, actionContext.ModelState);\n        } \n        else if (actionContext.ActionArguments.ContainsValue(null))              \n        {\n            actionContext.Response = actionContext.Request.CreateErrorResponse(\n                HttpStatusCode.BadRequest, "Request body cannot be empty");\n        }\n    }\n}	0
27451142	27449657	Implemented error logging with crazy results	routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(css|js|gif|jpg|ico)(/.*)?" });	0
31681407	31678931	Start multiple web servers with OWIN	var options = new FileServerOptions();\noptions.EnableDefaultFiles = true;\noptions.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };\noptions.DefaultFilesOptions.FileSystem = new PhysicalFileSystem("Web");\noptions.DefaultFilesOptions.RequestPath = PathString.Empty;\napp.UseFileServer(options);	0
7687737	7687415	Color item in a datagriedview combobox column	protected void ComboBox1_DrawItem(object sender, \n    System.Windows.Forms.DrawItemEventArgs e)\n{\n\n    float size = 0;\n    System.Drawing.Font myFont;\n    FontFamily font= null;\n\n    //Color and font based on index//\n    Brush brush;\n    switch(e.Index)\n    {\n        case 0:\n            size = 10;\n            brush = Brushes.Red;\n            family = font.GenericSansSerif;\n            break;\n        case 1:\n            size = 20;\n            brush = Brushes.Green;\n            font = font.GenericMonospace;\n            break;\n    }\n\n    myFont = new Font(font, size, FontStyle.Bold);\n    string text = ((ComboBox)sender).Items[e.Index].ToString();\n    e.Graphics.DrawString(text, myFont, brush, e.Bounds.X, e.Bounds.Y);	0
4276842	4276517	EntityDataSource Override with a custom Delete	public partial class AWEntities{ \n\npartial void OnContextCreated()\n{\n    this.SavingChanges += new EventHandler(context_SavingChanges);// Register the handler for the SavingChanges event.\n}\n\nprivate static void context_SavingChanges(object sender, EventArgs e)// SavingChanges event handler.\n{\n    // Get all in Deleted state\n    foreach (ObjectStateEntry entry in\n        ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))\n    {\n        if (entry.Entity.GetType() == typeof(MyType)))\n        {\n            // do what you want.\n        }\n    }\n}\n}	0
14525814	14525775	How do I represent date range for months that donot have 31 days in c#?	DateTime end = first.AddMonths(1).AddDays(-1);	0
10366011	10365925	How to load elements into array using for loop? C#	int min = 1;\nint max = 4;\nint num = 3;\nRandom r = new Random();\nInt[] ar ;\nar = new Int[num]; // Creates array with 3 palces {ar[0],ar[1],ar[2])\nfor(i = 0;i =< num - 1;i++) {\nar[i] = r.Next(min,max); // generate random number between 1-4 (include 1 & 4)\n}	0
24506019	24505967	Is it possible to pass variable as parameter in javascript function?	ScriptManager.RegisterStartupScript(this, this.GetType(), "anyname", "show(" + nid + ")", true);	0
17351244	17305249	How can I duplicate tabPage in c#?	for (int x = 0; x < 3; x++)\n    {\n        UserControl1 uc = new UserControl1();\n        TabPage tp = new TabPage();\n        tp.Controls.Add(uc);\n        this.TabControl1.TabPages.Add(tp);\n    }	0
7261784	7261323	DateTime as parameter to a WCF REST Service	[WebGet]\npublic IEnumerable<Statistics> GetStats( DateTime startDate )\n{\n    var stats = new Statistician();\n    return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics);\n}\n\n[WebGet]\npublic IEnumerable<Statistics> GetStats( string startDate )\n{\n  DateTime dt;\n  if ( DateTime.TryParse( startDate, out dt) )\n  {\n    return GetStats( dt );\n  }\n\n  throw new WebFaultException<Result>(new Result() { Title = "Error",\n    Description = "startDate is not of a valid Date format" },\n    System.Net.HttpStatusCode.BadRequest);\n}	0
3454947	3454931	In C#, how can you easily change the name of an event handler?	Refactor -> Rename...	0
22071520	22049606	How to retrieve object Column from DataSource RowFilter	CohortCollection cohortCol = (CohortCollection)Session["cohortCol"];\n\n        foreach(Cohort cohort in cohortCol.ToList())\n        {\n            if(cohort.Status.Id != int.Parse(ddlFormation.SelectedItem.Value))\n            {\n                cohortCol.Remove(cohort);\n            }\n        }\n\n        this.CohortGrid.DataSource = cohortCol;\n        this.CohortGrid.DataBind();	0
8306591	8306572	How does Array.Reverse() reverses a string without assignment?	Array.Reverse()	0
28026547	28025979	C# Selecting same index on multiple listBox	// Enumerable of all the synchronized list boxes\nIEnumerable<ListBox> mListBoxes = ...\n...\npublic void OnSelectedIndexChanged(object sender, EventArgs e) {\n    var currentListBox = (ListBox)sender;\n\n    // Do this for every listbox that isn't the one that was just updated\n    foreach(var listBox in mListBoxes.Where(lb => lb != currentListBox)) {\n        listBox.SelectedIndexChanged -= OnSelectedIndexChanged;\n        listBox.SelectedIndex = currentListBox.SelectedIndex;\n        listBox.SelectedIndexChanged += OnSelectedIndexChanged;\n    }\n}	0
5802676	5802257	Running a job in parallel with N concurrent threads	[TestMethod()]\npublic void DoSomethingTest()\n{\n    int n = 10; // changed to 10, see comment\n    Parallel.For(0, n, i =>  DoSomething());\n    // here all threads are completed \n}	0
20726009	20726005	How to use MySql select with c#	"SELECT id from residentes WHERE nome ='" + nomeres + "'"	0
8271483	8271322	Class members only accessible from methods of the same class  - How?	new Process().MainModule	0
6592208	6592109	how to compare string in lambda expression	var returnValue = (ItableDB.FindAllMatching(x => x.ColumnInTableThatHoldsString == enteredStringFromTextBoxOnFrontEnd) as IEnumerble<TableRepo>).Where(x => x.ColumnInTableThatHoldsString == enteredStringFromTextBoxOnFrontEnd);	0
2710192	2710182	Is it possible to load items from an Enum to a ComboBox in .NET 3.5?	combobox.DataSource = Enum.GetValues(typeof(SomeEnum));	0
6437402	6437056	How to make my app singleton application?	public static Process RunningInstance() \n{ \n    Process current = Process.GetCurrentProcess(); \n    Process[] processes = Process.GetProcessesByName (current.ProcessName); \n\n    //Loop through the running processes in with the same name \n    foreach (Process process in processes) \n    { \n        //Ignore the current process \n        if (process.Id != current.Id) \n        { \n            //Make sure that the process is running from the exe file. \n            if (Assembly.GetExecutingAssembly().Location.\n                 Replace("/", "\\") == current.MainModule.FileName) \n\n            {  \n                //Return the other process instance.  \n                return process; \n\n            }  \n        }  \n    } \n    //No other instance was found, return null.  \n    return null;  \n}\n\n\nif (MainForm.RunningInstance() != null)\n{\n    MessageBox.Show("Duplicate Instance");\n    //TODO:\n    //Your application logic for duplicate \n    //instances would go here.\n}	0
31788459	31788346	Set Selected DataGridView columns to true	foreach (DataGridViewRow row in dataGridView1.SelectedRows)\n{\n row.Cells[0].Value = true;\n}	0
23169555	23169476	How to Synchronize two tables on different sql servers by using Microsoft Sync Framework Programatically?	Microsoft.Synchronization.Data.dll\nMicrosoft.Synchronization.Data.Server.dll\nMicrosoft.Synchronization.Data.SqlServer.dll	0
13368253	13367818	set selected item of listview according to a value	var item = lstvClientes.FindItemWithText(idTextBox.Text);\nif (item != null)\n    item.Selected = true;	0
7230427	7230102	Writing to registry in a C# application	RegistryKey key = Registry.LocalMachine.OpenSubKey("Software",true);\n\nkey.CreateSubKey("AppName");\nkey = key.OpenSubKey("AppName", true);\n\n\nkey.CreateSubKey("AppVersion");\nkey = key.OpenSubKey("AppVersion", true);\n\nkey.SetValue("yourkey", "yourvalue");	0
6926854	6926811	c#, Controls in panel to be disposed	ControlCollection controlsCollection = (ControlCollection)Properties.GetObject(PropControlsCollection); \n\nif (controlsCollection != null) { \n\n    // PERFNOTE: This is more efficient than using Foreach.  Foreach\n    // forces the creation of an array subset enum each time we \n    // enumerate\n    for(int i = 0; i < controlsCollection.Count; i++) {\n        Control ctl = controlsCollection[i];\n        ctl.parent = null; \n        ctl.Dispose();\n    } \n    Properties.SetObject(PropControlsCollection, null); \n}	0
18519360	18519294	Check if variable corresponds with Enum	if(Enum.IsDefined(typeof(AlertType), val)) {}	0
5420938	5417754	Pointer to a dictionary<> in c#	var newGroups = (Dictionary<string, List<string>>)ser.ReadObject(reader,true);\nforeach(var kvp in newGroups)\n{\n    _groupsList.Add(kvp.Key,kvp.Value);\n}	0
2728730	2728714	Casting Between Data Types in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        A a1 = new A(1);\n        B b1 = a1;\n\n        B b2 = new B(1.1);\n        A a2 = (A)b2;\n    }\n}\n\nclass A\n{\n    public int Foo;\n\n    public A(int foo)\n    {\n        this.Foo = foo;\n    }\n\n    public static implicit operator B(A a)\n    {\n        return new B(a.Foo);\n    }\n}\n\nclass B\n{\n    public double Bar;\n\n    public B(double bar)\n    {\n        this.Bar = bar;\n    }\n\n    public static explicit operator A(B b)\n    {\n        return new A((int)b.Bar);\n    }\n}	0
16725333	16725322	Can you do shorter declarations in C#?	var Dict = new Dictionary<IPAddress, IWebSocketConnection>();	0
4086907	4086679	Add ints to listview for sorting	int intX = 0, intY = 0;\n            if(int.TryParse(listviewX.SubItems[ColumnToSort].Text, out intX)\n                && int.TryParse(listviewY.SubItems[ColumnToSort].Text, out intY))\n            {\n                return intX.CompareTo(inty);\n            }	0
2571744	2571716	Find Nth occurrence of a character in a string	public int GetNthIndex(string s, char t, int n)\n{\n    int count = 0;\n    for (int i = 0; i < s.Length; i++)\n    {\n        if (s[i] == t)\n        {\n            count++;\n            if (count == n)\n            {\n                return i;\n            }\n        }\n    }\n    return -1;\n}	0
8036172	8036082	A one line function to replace characters in a C# string	if(Session["CurrentUrl"] != null)\n{\n  var ip = new Uri(Session["CurrentUrl"]);\n  var ipNoPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);\n  return Redirect(ipNoPort);\n}\n\nreturn Home();	0
22374636	22374375	how to get data from list use c# and Linq	var data = new List<Data>()\n{\n    new Data() { Id = 1, Name = "Phone", ParentId = 0, Distance = 0 },\n    new Data() { Id = 2, Name = "TV", ParentId = 0, Distance = 0 },\n    new Data() { Id = 3, Name = "battery", ParentId = 1, Distance = 5 },\n    new Data() { Id = 4, Name = "button", ParentId = 1, Distance = 3 },\n    new Data() { Id = 5, Name = "webcam", ParentId = 2, Distance = 5 },\n};\n\nvar lookup = data.ToLookup(x => x.ParentId);\n\nvar devices =\n    lookup[0]\n        .Select(x => new\n        {\n            ID = x.Id,\n            x.Name,\n            Parts =\n                lookup[x.Id]\n                    .Select(y => new\n                    {\n                        y.Id,\n                        y.Name,\n                        y.Distance,\n                    })\n                    .ToList(),\n        })\n        .ToList();	0
10271566	10271181	C# - Multi Select List Box changing values	const int[] prices = new int[]{18,25,40,30};\nint total = 0;\nforeach(int index in lstSpecial.SelectedIndices)\n    total += prices[index];\nspecial1.Price = total;	0
30091139	30090759	How to read object of Session ASP.net in Javascript?	...\nvar full_name = '<%=((QLNT.DATA.USER_MOD) Session["OBJ"]).FULL_NAME%>';\nvar birth_day = '<%=((QLNT.DATA.USER_MOD) Session["OBJ"]).BIRTH_DAY%>';\n...	0
16502456	16501283	WPF: Revert changes after transforming an Image	void ResetTransformationOfImage()\n        {\n            TransformGroup group = new TransformGroup();\n\n            ScaleTransform xform = new ScaleTransform();\n            group.Children.Add(xform);\n\n            TranslateTransform tt = new TranslateTransform();\n            group.Children.Add(tt);\n\n            MainPic.RenderTransform = group;\n        }	0
20842231	20842099	Best way to create instance of child object from parent object	public class MyObject\n{\n    protected MyObject(MyObject other)\n    {\n        this.Prop1=other.Prop1;\n        this.Prop2=other.Prop2;\n    }\n\n    public object Prop1 { get; set; }\n    public object Prop2 { get; set; }\n}\n\npublic class MyObjectSearch : MyObject\n{\n\n    public double Distance { get; set; }\n\n    public MyObjectSearch(MyObject obj)\n         : base(obj)\n    {\n        this.Distance=0;\n    }\n    public MyObjectSearch(MyObjectSearch other)\n         : base(other)\n    {\n        this.Distance=other.Distance;\n    }\n}	0
4542049	4525476	Tweet An Update Using C# TweetSharp With New OAuth	var service = new TwitterService(_consumerKey, _consumerSecret);\nservice.AuthenticateWith(_accessToken, _accessTokenSecret);\nservice.SendTweet("I'm totally tweeting!");	0
20100746	20100705	Wrong appearence position of context menu	m.Show(ServersTable, ServersTable.PointToClient(\n    new Point(Cursor.Position.X, Cursor.Position.Y)));	0
13122515	13122360	how to find datagrid row in asp.net 2.0 C#	foreach (GridViewRow gvr in gvDemo.Rows) {\n        if (gvr.DataItem != null) { \n\n            //depending on how or what you want to find \n            //check a key\n            if (gvDemo.DataKeys[gvr.RowIndex].Values[0] == "xx") { \n\n            }\n            //or a field value\n            if (gvr.Cells[0].ToString() == "123") { \n\n            }\n\n            //or first cast your row data item back to a known class\n            CarBrand carBrand = (CarBrand)gvr.DataItem;\n            if (carBrand.Name == "Porsche") { \n            //\n            }\n\n            //or pass the whole row to whatever function\n            if (xx == yy) {\n                DoSomething(gvr);\n            }\n\n        }\n    }	0
6104961	6104887	C# Reflection Getting static property of concrete class from Interface	var staticProperty = instance.GetType()\n    .GetProperty("<PropertyName>", BindingFlags.Public | BindingFlags.Static);\nvar value = staticProperty.GetValue(instance, null);	0
17508678	17391230	can't download file from server using linkbutton in asp.net C#	// send the PDF document as a response to the browser for download\n System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;\n\n response.ContentType = "application/pdf";\n if (!displayOnBrowser)\n {  response.AddHeader("Content-Disposition", String.Format("attachment; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString())); \n }\n else\n {  response.AddHeader("Content-Disposition", String.Format("inline; filename=GettingStarted.pdf; size={0}", pdfBytes.Length.ToString()));\n }\n response.BinaryWrite(pdfBytes);\n // Note: it is important to end the response, otherwise the ASP.NET\n // web page will render its content to PDF document stream\n response.End();	0
20854004	20853734	Replace string with condition	string s = "[code class='c-sharp'][/code]";\nStringBuilder pre = new StringBuilder(s);\n\npre.Replace("[","<");\npre.Replace("]",">");\npre.Replace("code","pre");	0
7809284	7808708	How do I obtain row counts for protected sheets?	Excel._Worksheet.Rows.Count	0
25918893	25918746	regular expressions metacharacters screening	"^" + RegEx.Escape(value) + @"\s\w+\s\d+$"	0
8499027	8498932	how to convert to c# code in php pack('s') method	var obj     = new StandardClass { variable1 = 202, variable2 = 123 };\nvar initial = JsonConvert.SerializeObject(obj);\nvar header  = "\x0a\xff\x00\x10" + initial.Length.ToString("X") + initial;\n...\nsocket.Write(header);	0
8679176	8678883	c# - Read specific bytes of an file	byte[] test = File.ReadAllBytes(file).Skip(50).Take(10).ToArray();	0
10759979	10759948	How can I select items in ListA that have a property that matches an item's property in ListB?	var join = ListA.Join(ListB, la => la.TypeId, lb => lb.TypeId, (la, lb) => la);	0
11759107	11759050	Finding the root path from the given path	string directory = Path.GetDirectoryName(path);	0
5797877	5795792	NHibernate query-over with restriction on a referenced entity	Language language = null;\n\nvar localization = session.QueryOver<Localization>()\n            .JoinAlias(x => x.Language, () => language)\n            .Where(idFilter)\n            .AndRestrictionOn(() => language.IETFTag).IsLike(tag, MatchMode.End)\n            .SingleOrDefault();	0
13715543	13715529	check whether a List<string> contains an element in another List<string> using LINQ	List<string> a = ...\nList<string> b = ...\nvar inComon = a.Intersect(b).Any();	0
18315395	18315354	Is it possible to create a derived class from a base class constructor?	class Animal\n{\n   // Factory method\n   public static Animal Create(string name)\n   {\n      Animal animal = null;\n      ...  // logic based on 'name'\n      return animal;\n   }\n}	0
23987517	23951016	Get "Show as" for an appointment in EWS	CalendarView cv = new CalendarView(DateTime.Now,DateTime.Now.AddDays(200),100);\n        FindItemsResults<Appointment>findresults = service.FindAppointments(WellKnownFolderName.Calendar, cv);\n\n        foreach (Appointment aptval in findresults.Items)\n        {\n            Console.WriteLine(aptval.LegacyFreeBusyStatus);        \n        }	0
31174910	31174766	How to convert a Task<Tuple<E,R>> into a Task<E>	public async Task<E> SendCommandAsync(C command)\n{\n    var result = await _SendCommandAndRetrieveResponseAsync(command);\n    return result.Item1;\n}	0
14558593	14557655	Adding a refrence to wp8 sdk	System.Windows.Media.Color c;\nSystem.Windows.Shapes.Rectangle r;\nSystem.Windows.Media.SolidColorBrush b;\nSystem.Windows.Media.Imaging.BitmapImage bi;	0
20536038	20535785	LINQ to XML - Selecting with multiple attribute filters?	string timeSliceToSearchFor = "0 - 5";\nstring actionAreaToSearchFor = "1";\nstring aaTeamIdToSearchFor = "1001";\n\n// Returns 7\nstring value = xDoc .Descendants("action_areas")\n                    .Elements("time_slice")\n                    .Where(element => element.Attribute("name").Value == timeSliceToSearchFor)\n                    .Elements("action_area")\n                    .Where(element => element.Attribute("id").Value == actionAreaToSearchFor)\n                    .Elements("aa_team")\n                    .Where(element => element.Attribute("id").Value == aaTeamIdToSearchFor)\n                    .Single().Value;	0
14477209	14324869	get value on edititemtemplate from codebehind	protected void DetailsView1_DataBound(object sender, EventArgs e)\n{\n    Label l = DetailsView1.FindControl("FirstName") as Label;\n    if (DetailsView1.CurrentMode == DetailsViewMode.Edit)\n    {\n        //obtained from your sample\n        MemberProfile memberp = MemberProfile.GetuserProfile(data);\n        MembershipUser myuser = Membership.GetUser()\n\n        l.Text = memberp.fName;\n    }\n    else\n    { \n        l.Text = "Another text or nothing";\n    }\n }	0
21291304	21291238	Linq: filtering a list by time spans in another list	values.Where(v => times.Any(t => v.DateTime >= t.StartTime \n                              && v.DateTime <= t.EndTime)\n            )	0
33239914	33234254	Text Proper Formatting and alignment in itextsharp	Phrase phrase1 = new Phrase("Repair 2 - Tongue pig biltong picanha - ", newfntbld);\nPhrase phrase2 = new Phrase("Ham beef ball tip, pastrami sausage ribeye meatloaf salami kielbasa. Ground round bresaola pastrami ham capicola pork belly, tri-tip drumstick. Beef hamburger pork loin bacon doner chuck shank strip steak ham hock meatloaf. Flank meatball swine frankfurter.", newlightfnt);\nParagraph para = new Paragraph();\npara.Add(phrase1);\npara.Add(phrase2);	0
28379247	28378833	Property Injection with Autofac	builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();	0
1422174	1422155	C# assign values of array to separate variables in one line	strArr = new string[]{"foo","bar"};\nstring str1 = strArr[0], str2 = strArr[1];	0
21578732	21578147	How to Increment timer asynchronously ?	private int time = 60;\n    DateTime dt = new DateTime();\n    private int j = 15;\n    private Timer timer1 = new Timer();\n\n\n    void timer_tick(object sender, EventArgs e)\n    {\n        if (time > 0)\n        {\n            time--;\n            text.Text = TimeSpan.FromSeconds(time).ToString();\n        }\n        else\n        {\n            timer1.Stop();\n        }\n    }\n\n    public timer()\n    {\n        InitializeComponent();\n        timer1 = new Timer();\n        timer1.Interval = 1000;\n        timer1.Tick += timer_tick;\n        timer1.Start();\n    }\n\n\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        time += j;\n    }	0
641418	641373	How to convert a string to a ? function signature ? to create a delegate?	public delegate void deleg(string msg);\n\npublic class class1\n{\n  public void method1(string msg)\n  {\n    //does something with msg\n  }\n\n  public void i_make_a_class2()\n  {\n    class2 bob = new class2(method1);\n  }\n}\n\npublic class class2\n{\n  deleg deleg1;\n  string im_a_String = "Test";\n\n  public class2(deleg fct)\n  {\n    deleg1 = fct;\n    // Rest of the class constructor...\n  }\n  private void method2()\n  {\n    deleg1(im_a_String);\n  }\n}	0
2610503	2610470	How to convert string with unusual format into datetime	DateTime dt;\n        System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US"); \n\n        if ( DateTime.TryParseExact( "Tue Jan 20 20:47:43 GMT 2009", "ddd MMM dd H:mm:ss \"GMT\" yyyy", enUS, System.Globalization.DateTimeStyles.NoCurrentDateDefault , out dt  ))\n        {\n            Console.WriteLine(dt.ToString() );\n        }	0
612500	612415	Get values from the web.config section in an app.config file?	[TestMethod]\npublic void Test_Configuration_Used_Correctly()\n{\n    ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";\n    MyClass testObject = new MyClass();\n    testObject.ConfigurationHandler();\n    Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigValue");\n}\n\n[TestMethod]\npublic void Test_Configuration_Defaults_Used_Correctly()\n{\n    // you don't need to set AppSettings for a non-existent value...\n    // ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";\n\n    MyClass testObject = new MyClass();\n    testObject.ConfigurationHandler();\n    Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigDefaultValue");\n}	0
27895348	27895219	Set text property for Textbox created at runtime	for (int i = 1; i <= no_gb; i++)\n{\n    GroupBox g1 = new GroupBox();\n    g1.Text = "Window " + i;\n    g1.Size = new Size(207, 105);\n    g1.Name = "gbG1";\n    TextBox txt = new TextBox();\n    txt.Name = "txtwidth" + i;\n    g1.Controls.add(txt);\n    flowLayoutPanel1.Controls.Add(g1);\n}\n\nfor (int i = 1; i <= Hlk_WidthArray.Length; i++)\n{\n    Hlk_WidthArray[i] += Hlk_WidthArray[i];\n    ((TextBox)(((GroupBox)flowLayoutPanel1.Controls["gbG1"]).Controls["txtwidth" + i])).Text = Hlk_WidthArray[i].ToString();\n}	0
20425138	20425036	Is there a method that is ALWAYS called in a webform?	void Application_BeginRequest(Object sender, EventArgs e)\n{ \n    // your code goes here\n}	0
17448345	17439732	Recreating Keys (ECPublicKeyParameters) in C# with BouncyCastle	string curveName = "P-521";\nX9ECParameters ecP = NistNamedCurves.GetByName(curveName);\nFpCurve c = (FpCurve)ecP.Curve;\nECFieldElement x = new FpFieldElement(c.Q, xxx.Q.X.ToBigInteger());\nECFieldElement y = new FpFieldElement(c.Q, xxx.Q.Y.ToBigInteger());\nECPoint q = new FpPoint(c, x, y);\nECPublicKeyParameters xxpk = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);	0
28413341	28413094	NHibernate QueryOver with Many-to-Many	var result = session.QueryOver<Users>()\n            .Right.JoinQueryOver<Roles>(x => x.UserId )\n            .Where(c => c.RoleId == roleid)\n.TransformUsing(Transformers.DistinctRootEntity)\n.List();	0
19074122	19073392	How to get XML information from a child in an Element with a attribute using XmlDocument in C#?	var xdoc = XDocument.Load(@"C:\Temp\doc.xml");\nvar node = xdoc.XPathSelectElements("./response/payment[@loanType='thirtyYearFixed']");\nvar query = from payment in  node             \n            select new\n            {\n                rate                        = payment.XPathSelectElement("rate"),\n                monthlyPrincipalAndInterest = payment.XPathSelectElement("monthlyPrincipalAndInterest"),\n                monthlyMortgageInsurance    = payment.XPathSelectElement("monthlyMortgageInsurance")\n\n            };\n\n    foreach (var v in query)\n    {\n        Console.WriteLine(v.rate.Value);\n        Console.WriteLine(v.monthlyPrincipalAndInterest.Value);\n        Console.WriteLine(v.monthlyMortgageInsurance.Value);\n    }	0
2492170	2470996	Loading a ConfigurationSection with a required child ConfigurationElement with .Net configuration framework	private void ProcessMissingElements(ConfigurationElement element)\n{\n    foreach (PropertyInformation propertyInformation in element.ElementInformation.Properties)\n    {\n        var complexProperty = propertyInformation.Value as ConfigurationElement;\n        if (complexProperty == null) \n            continue;\n\n        if (propertyInformation.IsRequired && !complexProperty.ElementInformation.IsPresent)\n            throw new ConfigurationErrorsException("ConfigProperty: [{0}] is required but not present".FormatStr(propertyInformation.Name));\n        if (!complexProperty.ElementInformation.IsPresent)\n            propertyInformation.Value = null;\n        else\n            ProcessMissingElements(complexProperty);\n    }\n}	0
32860293	22166429	Sybase "Not enough values for host variables" with multiple SETs	BEGIN\n    DECLARE @id INT;\n    DECLARE @name NVARCHAR;\n    DECLARE @comment NCARCHAR;\n    SELECT :id, :name, :comment INTO @id, @name, @comment;\nEND;	0
8447049	8446589	How to communicate two classes?	abstract class MyBaseClass\n{\n    public Dictionary<int,string> dic { get; set; }\n\n    public MyBaseClass()\n    {\n        dic = new Dictionary<int, string>(5);\n    }\n\n    public void Add(int key, string value)\n    {\n        dic.Add(key, value);\n    }\n}\n\npublic class MyClass1 : MyBaseClass\n{\n    public MyClass1():base()\n    {          \n    }        \n}\n\npublic class MyClass2 : MyBaseClass\n{\n    public MyClass2():base()\n    {\n\n    }\n\n    public void Save()\n    {\n        Add(1, "somevalue");\n    }\n}	0
22404162	22402089	gridview doesn't show update data after click event	private void serach_click()\n{\n    // your code to retrieve your data\n\n    gridview.datasource = your data source;\n    gridview.databind();\n}	0
12653466	12653146	How to construct objects in one class from another class	List<FileData> listOfData = new List<FileData>();\n    void createOutputBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) \n    { \n        using (StreamReader sr = File.OpenText("D:/data.txt")) \n        { \n            String input; \n\n            while ((input = sr.ReadLine()) != null) \n            { \n                FileData fd = new FileData(new BatchData()); \n                string[] stringArray = input.Split(','); \n                for (int i = 0; i < stringArray.Length - 1; i+=2) \n                { \n                     switch(stringArray[i])\n                     {\n                          case "{$BATCH ID}":\n                             fd.BatchID = stringArray[i+1];\n                             break;\n                          // Other properties follow ..... \n                          case ......\n                     }\n                } \n                listOfData.Add(fd);\n            } \n        } \n    }	0
21607982	21591574	Convert a Json array to use it in Winforms C#	List<Client> listeclient = JsonConvert.DeserializeObject<List<Client>>(JsonEncoded);\n\n        foreach (Client nom in listeclient)\n        {\n            MessageBox.Show(nom.Nom);\n            MessageBox.Show(nom.Prenom);\n        }	0
11683968	11683530	Reflection is too slow while deserialising JSON strings into .NET objects	//New implementation, use TryGetValue from Dictionary to check for excising values.\ndynamic value = null;\nobj.TryGetValue(convTable[f.Name], out value);	0
8187112	8186943	C#: Windows App Reading CSV file and Writing to a Console Issue	if (fd.ShowDialog() == DialogResult.OK)\n{      \n    Application.DoEvents();\n    ...\n    ...\n}	0
6487401	6487370	make HttpCookie shorter	Response.Cookies.Add(new HttpCookie("UserID", "JLovus")\n{\n    Expires = DateTime.Now.AddMinutes(30)\n});	0
6944800	6944706	Is it possible to prevent a XAML element with an x:Name from being accessible outside of the class in which it is defined?	x:FieldModifier="private"	0
21228718	21224357	c# converting short array from mono wav file, to short array to write as stereo wav	short[] newBuffer = new short[writeBuffer.Length*2];\nint index = offset; //offset might be 0\nfor (int i=0; i< newBuffer.Length;i = i + 2)\n{\n    newBuffer[index++] = writeBuffer[i];\n    newBuffer[index++] = writeBuffer[i];\n}	0
8714243	8714197	C# StreamReader save to Array with separator	string[] parts = s.Split('\t');	0
8944367	8929334	Hide Scrollbars In DataGridView	if(e.Delta > 0)\n{\n\n}\nelse if(e.Delta < 0)\n{\n}	0
11734372	11734227	overriding operator to concat two byte array	public static byte[] AddTo(this byte[] bytaArray1, byte[] bytaArray2){...}	0
5253477	5253255	Date UTC issue with PST/EST	var utcToday = DateTime.Today.ToUniversalTime();	0
27707972	27707931	Upload generic list to database	// Create a table with some rows. \n        DataTable newProducts = MakeTable();\n\n        // Create the SqlBulkCopy object.  \n        // Note that the column positions in the source DataTable  \n        // match the column positions in the destination table so  \n        // there is no need to map columns.  \n        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))\n        {\n            bulkCopy.DestinationTableName = \n                "dbo.BulkCopyDemoMatchingColumns";\n\n            try\n            {\n                // Write from the source to the destination.\n                bulkCopy.WriteToServer(newProducts);\n            }\n            catch (Exception ex)\n            {\n                Console.WriteLine(ex.Message);\n            }\n        }	0
1650683	1650648	Catching Ctrl + C in a textbox	if (e.Control && e.KeyCode == Keys.C) {\n    //...\n    e.SuppressKeyPress = true;\n}	0
26634783	26632368	How to get an image from a file, and overwrite it in the same program?	using(var image = Image.FromFile(openFileDialog.FileName))\n{\n    ...\n    s.schetscontrol.MaakBitmapGraphics().DrawImageUnscaled(image, 0, 0);\n    ...\n}	0
10386056	10385686	Implementing VLC player in a Windows application: Programatically registering an ActiveX component	public static void RegisterDll(string filePath)\n    {\n        string fileinfo = String.Format(@"/s ""{0}""", filePath);\n        Process process = new Process();\n        process.StartInfo.FileName = "regsvr32.exe";\n        process.StartInfo.Arguments = fileinfo;\n        process.StartInfo.UseShellExecute = false;\n        process.StartInfo.CreateNoWindow = true;\n        process.StartInfo.RedirectStandardOutput = true;\n        process.Start();\n        process.WaitForExit();\n        process.Close();\n    }	0
389870	389677	Looking for Specific Date	var d1 = DateTime.Today;\nvar d2 = d1.AddDays(1);\nvar deposit = (from tempDeposit in entities.Deposit\n               where !tempDeposit.IsApproved\n                     && tempDeposit.CreatedDate >= d1\n                     && tempDeposit.CreatedDate < d2\n               select tempDeposit).FirstOrDefault();	0
2483702	2483604	Using IoC and Dependency Injection, how do I wrap an existing implementation with a new layer of implementation without changing existing code so as not to violate the Open-Closed principle?	public class CircuitBreakingFileDownloader : IFileDownloader\n{ \n    private readonly IFileDownloader fileDownloader;\n\n    public CircuitBreakingFileDownloader(IFileDownloader fileDownloader)\n    {\n        if (fileDownloader == null)\n        {\n            throw new ArgumentNullException("fileDownloader");\n        }\n\n        this.fileDownloader = fileDownloader;\n    }\n\n    public string Download(string url)\n    {\n        // Apply Circuit Breaker implementation around a call to\n        this.fileDownloader.Download(url)\n        // here...\n    }\n}	0
5822249	5821956	MVVM Model to ViewModel communication	Person.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Person_PropertyChanged);\n\nvoid Person_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)\n{\n    if(e.PropertyName == "Name")\n    {\n         //do something\n    }\n}	0
22842503	22840615	how programmatically execute batch file by another credential	System.Diagnostics.Process.Start(filenameToStart, username, password, domain);	0
7659577	7657137	Datagridview full row selection but get single cell value	private void datagridview1_SelectionChanged(object sender, EventArgs e)\n     {\n         if (datagridview1.SelectedCells.Count > 0)\n         {\n             int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;\n\n             DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];  \n\n              string a = Convert.ToString(selectedRow.Cells["you have to mention you cell  corresponding column name"].Value);           \n\n\n         }\n     }	0
10413779	10281170	Optional parameters with Specflow	[Given(@"(at ([0-9-]+) (really at ([0-9-]+) |)|)(\w+) Completed a transfer form to transfer \$(\d+) to account (\d+)"]\npublic void TransferStep(string dummy1, DateTime? atDate, string dummy2, DateTime? reallyAtDate, string name, decimal amount, int account)	0
27649737	27648977	How to convert this method to WPF in C#	if (e.Key == Key.Enter || ((e.KeyboardDevice.Modifiers == ModifierKeys.Shift) && e.Key == Key.D3 ))\n{\n    e.Handled = true;\n}	0
3070413	3070311	Detecting if an item is selected or not in a listbox (WPF)	foreach(Item item in MyListBox.Items)        \n    if(MyListBox.SelectedItems.Contains(item)\n        MyObject.Value = true;\n    else\n        MyObject.Value = false;	0
3729825	3729638	Unit Testing Virtual Methods in a Linq	//instantiate Mocks in class scope, as an instance of MockRepository\n\npublic ChildClass CreateChildClass(int value)\n{\n   var childClass = Mocks.PartialMock<ChildClass>();\n   childClass.Expect(x => x.Value).Return(value);\n   return childClass;            \n}	0
20235912	19924069	detecting a property of an item before placing it in array	public SuperCard[] GetCards(int number)\n{\n\n    SuperCard[] hand = new SuperCard[number];\n    int index;\n\n    for (int i = 0; i < number; i++)  // 5 cards\n    {\n        index = myRandom.Next(0, 51);\n        hand[i] = cardArray[index];\n        while (hand[i].inplay == true)\n        {  \n            index = myRandom.Next(0, 51);\n            hand[i] = cardArray[index];\n\n        }\n        hand[i].inplay = true;    \n    }\n\n    return hand;\n}	0
16297176	16297144	Translating anonymous methods into lamda expression	Func<int, int> f = i =>\n{\n     Debug.WriteLine("Inside the function!");\n     return i + 1;\n};	0
15204361	13020616	Play RTSP through VLC in VS2010 on 64bit machine	axVLCPlugin1.addTarget("rtsp://172.16.10.50:8554/Test", null, VLCPlaylistMode.VLCPlayListReplaceAndGo, 0);\naxVLCPlugin1.Play();	0
3839684	3833774	Combining mulitple fields in ASP.NET Dynamic Data foreign key display	[MetadataType(typeof(PersonMetaData))]\npublic partial class Person\n{\n    public override string ToString()\n    {\n        return lname.ToString() + ", " + fname.ToString();\n    }\n\n}	0
26176739	26176590	How to remove unsafe characters from string for logging in C#	Convert.ToBase64String("binary data")	0
15257443	15256594	Preventing SQL injections in a gridview	sqlParameter sqlParam = new SqlParameter();\nsqlParam.ParameterName = "@testParam";\nsqlCommand.Parameters.AddWithValue("@testParam", textBox1.Text);	0
11421183	11420755	Chose Type to populate from JSON data based on contents of that data	dynamic dynJson = JsonConvert.DeserializeObject(json);\nforeach (var item in dynJson.elements)\n{\n    if(item.type==0)\n    {\n        //Do your specific deserialization here using "item.ToString()"\n        //For ex,\n        var x = JsonConvert.DeserializeObject<MapElementConferenceRoom>(item.ToString());\n    }\n}	0
22393953	22215057	Static classes for variables instead of methods	public static class MyClass\n{\n    public static Entity SomeEntity01, SomeEntity02, SomeEntity03;\n\n    static MyClass() // static constructor\n    {\n        SomeEntity01 = new Entity(some, values);\n        SomeEntity02 = new Entity(some, new, values);\n        SomeEntity03 = new Entity(some, other, values);\n    }\n}	0
28776154	28681211	how to input content to a cell without create a new excel document?	Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;\nExcel.Workbook wbook = xlapp.ActiveWorkbook;\nExcel.Worksheet wsheet = wbook.ActiveSheet;	0
11805813	11805802	What format needs to be a property?	public int property\n{\n    get\n    {             \n         int defaultVal;\n         int.TryParse(tbText.Text, out defaultVal);\n         return defaultVal;\n    }\n    set\n    {\n         tbText.Text = value.ToString();\n    }\n}	0
25044126	25044043	Mistake passing parameters for simple RGB to HSL color converter	RGB2HSL(rgb, out h, out s, out l);	0
31157185	31156990	Linq with String Array Contains	var _tagIds = (from item in dbContext.Tags\n                    where keywords.contains(item.TagName)\n                    select item.TagId).ToList();	0
31197392	31197362	Splitting 1600 line cs project in to multiple files- eg one per class. How to compile with csc?	csc.exe /out:project.exe class1.cs class2.cs class3.cs	0
24223727	24223467	How do i bind an "Entry Cell" to a custom object using Xamarin?	EntryCell ec = new EntryCell ();\nec.BindingContext = _user;\nec.SetBinding (EntryCell.TextProperty, "Username");	0
17467541	17467128	keep radio button selected across postback	String selectedValue = rblYourRadioButtons.SelectedValue;\nSession["SelectedRadioButtonValue"] = selectedValue;	0
34381290	34379377	add where clauses to linq query with generic column name	public static IQueryable<T> RetrieveAll<T>(params Expression[] eagerProperties)\n{\n    var type = typeof(T);\n    var entitySet = ResolveEntitySet(type);\n    var query = context.CreateQuery<T>(entitySet);\n    foreach (var e in eagerProperties)\n    {\n        query = query.Expand(e);\n    }\n    var account = type.GetProperty("AccountId");\n    if (account != null)\n    {\n        Guid g = new Guid("3252353h....");\n        var parameter = Expression.Parameter(type);\n        var property = Expression.Property(parameter, account);\n        var guidValue = Expression.Constant(g);\n\n        var lambdaPredicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(property, guidValue), parameter);\n        return query.Where(lambdaPredicate);\n    }\n    return query;\n}	0
11789573	11761391	How to add specific SharePoint Group to List permission	list.BreakRoleInheritance(true);\nSPGroup groupAdmin = web.SiteGroups["IKM Manager"];\nSPRoleAssignment roleAssignmentAdmin = new SPRoleAssignment((SPPrincipal)groupAdmin);\nSPRoleDefinition roleAdmin = web.RoleDefinitions.GetByType(SPRoleType.Administrator);\nroleAssignmentAdmin.RoleDefinitionBindings.Add(roleAdmin);\nlist.RoleAssignments.Add(roleAssignmentAdmin);\nlist.Update();	0
23113075	23112852	Displaying DataTable containing DB tables names	// Add list of table names to string list\nList<string> names = new List<string>();\nfor (int i=0; i < userTables.Rows.Count; i++)\n    names.Add(userTables.Rows[i][2].ToString());	0
15678631	15678270	c# windows phone 8 how to add style to a button	deleteButton.Style =  App.Current.Resources["StyleKey"] as Style;	0
6201764	6201734	C# stored procedure with parameters	myCommand2.Parameters.Add("@TaskName", SqlDbType.NVarChar, 50).Value = t;	0
8495638	8495404	New window opens on click of actionLink	public ActionResult SendPdfStatement(string InvoiceNumber)\n\n    {\n    InvoiceNumber = InvoiceNumber.Trim();\n\n        ObjectParameter[] parameters = new ObjectParameter[1];\n        parameters[0] = new ObjectParameter("InvoiceNumber", InvoiceNumber);\n\n        List<Models.Statement> list = new List<Models.Statement>();\n        list = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters).ToList<Models.Statement>();\n\n        var statementResult = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters);\n        Models.Statement statement = statementResult.SingleOrDefault();\n\n        pdfStatementController.WriteInTemplate(statement); \n\n    return View();\n    }	0
19377157	18999188	Interfaces for fluent ordered constructor	public interface IMyObjectFactory: IObjectWithProperty\n{\n  int objectId { get; set; }\n}\n\npublic interface IObjectWithProperty\n{\n  IObjectWithProperty WithObjectId(int id);\n  MyObject Create();\n}\n\npublic class MyObjectFactory: IMyObjectFactory\n{\n  public int objectId;\n  private MyObjectFactory() { }\n\n  public static IObjectWithProperty BeginCreation()\n  {\n    return new MyObjectFactory();\n  }\n\n  public IObjectWithProperty WithObjectId(int id)\n  {\n    objectId = id;\n    return this;\n  }\n\n  public MyObject Create()\n  {\n    return new MyObject(this);\n  }\n}\n\npublic class MyObject\n{\n  public int Id { get; set; }\n  public MyObject(IMyObjectFactory factory)\n  {\n    this.Id = factory.objectId;\n  }\n}	0
10640817	10638153	Get CheckBox value from child form	Formes.CameraViewVS frmCamera;\n\npublic bool propertyZoomCam\n{\n    get \n    {\n        if (frmCamera!=null)\n            return frmCamera.checkBoxZoomCam.Checked; \n        else \n            return false;\n    }\n}\n\n\npublic void timer()\n{\n  for (int l = 0; l < 2; l++)        \n  {            \n    cameraInstance[l].Start();\n    if (cameraInstance[l].MoveDetection == true)\n    {\n      foreach (Form S in Application.OpenForms)\n      {\n        frmCamera = S as Formes.CameraViewVS;\n        if (frmCamera != null && frmCamera.Addresse == cameraInstance[l].adresse) {\n          // Match, activate it\n          cameraInstance[l].MoveDetection = false;\n          frmCamera.WindowState = FormWindowState.Normal;\n          frmCamera.Activate();\n          return;\n        }\n      }\n      // No match found, create a new one\n      frmCamera = new Formes.CameraViewVS(cameraInstance[l], adresseIPArray[l]);\n      frmCamera.Show(this);\n      if(propertyZoomCam)\n        zoom = 15;\n    }\n  }\n}	0
4746783	4746670	Can separate access modifiers be specified for the get and set accessors of a property?	public int Age\n{\n    get\n    {\n        return _age;\n    }\n    protected set\n    {\n        _age = value;\n    }\n}	0
12460333	12460256	inaccessible properties of objects	TextBlock.Background	0
11711908	11711842	Delete filename from a filepath in C#	var filepath = "/vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/TestMachine.vmx";\nvar directorypath = filepath.Substring(0, filepath.LastIndexOf("/", StringComparison.Ordinal) + 1);\n// /vmfs/volumes/50153b66-6aac5486-e942-080027a10080/TestMachine/\nvar dir = Path.GetDirectoryName(filepath);\n// \vmfs\volumes\50153b66-6aac5486-e942-080027a10080\TestMachine	0
4215927	4215888	asp.net textareafor - keep newlines	myHtml = myHtml.Replace("\n","<br />");	0
27706203	27706092	How to convert nested object from one type to another	public class Source\n{\n    public int Id { get; set; }\n    public List<Source> Children { get; set; }\n\n    public Destination GetDestination()\n    {\n        return new Destination\n        {\n            nodes = Children.Select(c => c.GetDestination()).ToList(),\n            key = Id\n        };\n    }\n}	0
19266324	19266164	How to pass variable to asp MenuItem	Menu.Items[0].Text = Session["user"].ToString();	0
5922660	5922467	StatusDescription Encoding in HttpResponse	response.StatusDescription =\n  exception.Message.Substring(0, Math.Min(exception.Message.Length, 512));	0
555783	555750	How do I get all the values of a Dictionary<TKey, TValue> as an IList<TValue>?	IDictionary<int, IList<MyClass>> dict;\nvar flattenList = dict.SelectMany( x => x.Value );	0
5188129	3872562	How to use markup extensions from C# code?	TranslateExtension ext = new TranslateExtension("LocalizedByMarkupExtension");	0
3909684	3909389	Login control and custom membership provider	protected void Login_Authenticate(object sender, AuthenticateEventArgs e)\n{\n    try\n    {\n       e.Authenticated = myMembershipProvider.ValidateUser(LoginControl1.UserName,LoginControl.Password);\n\n    }\n    catch(Exception ex)\n    {\n      LoginControl1.FailrureText = ex.Message;\n    }\n}	0
20693434	20177024	Programmically link all points	// Add the Polyline Element\nmyPolyline = new Polyline();\nmyPolyline.Stroke = System.Windows.Media.Brushes.SlateGray;\nmyPolyline.StrokeThickness = 2;\nmyPolyline.FillRule = FillRule.EvenOdd;\nSystem.Windows.Point Point4 = new System.Windows.Point(1, 50);\nSystem.Windows.Point Point5 = new System.Windows.Point(10, 80);\nSystem.Windows.Point Point6 = new System.Windows.Point(20, 40);\nPointCollection myPointCollection2 = new PointCollection();\nmyPointCollection2.Add(Point4);\nmyPointCollection2.Add(Point5);\nmyPointCollection2.Add(Point6);\nmyPolyline.Points = myPointCollection2;\nmyGrid.Children.Add(myPolyline);	0
11555901	11552214	Network communication between apps	var publisher = new ZmqPublishSocket {\n    Identity = Guid.NewGuid().ToByteArray(),\n    RecoverySeconds = 10\n};\n\npublisher.Bind( address: "tcp://127.0.0.1:9292" );\n\n// Add a subscriber.\nvar subscriber = new ZmqSubscribeSocket();\n\nsubscriber.Connect( address: "tcp://127.0.0.1:9292" );\nsubscriber.Subscribe( prefix: "" ); // subscribe to all messages\n\n// Add a handler to the subscriber's OnReceive event\nsubscriber.OnReceive += () => {\n    String message;\n    subscriber.Receive( out message, nonblocking: true );\n\n    Console.WriteLine( message );\n};\n\n// Publish a message to all subscribers.\n\npublisher.Send( "Hello world!" );	0
9055473	9055392	DotNetZip Library read from one zip into another	var ms = new MemoryStream();\n\nusing (ZipFile zip = ZipFile.Read(sourceZipFile))\n{\n    zip.Extract("NameOfEntryInArchive.doc", ms);\n}\n\nms.Seek(0);\n\nusing (ZipFile zip = new ZipFile())\n{\n    zip.AddEntry("NameOfEntryInArchive.doc", ms);\n    zip.Save(zipToCreate);\n}	0
15367821	15367729	EF how to sellect elements that are not in collection	var nonSelectedProducts = from product in db.Products\n                          where !order.Rows.Any(or => or.ProductId == product.Id)\n                          select product	0
14281154	14281117	How to apply -= to a string?	string test = "";\ntest = test.Replace("Text", "");	0
2097400	2097217	Sending an API CAll with PayPal SOAP API	using (var client = new PayPalAPIInterfaceClient())\n{\n    var credentials = new CustomSecurityHeaderType\n    {\n        Credentials = new UserIdPasswordType\n        {\n            Username = "username",\n            Password = "password"\n        }\n    };\n    var request = new AddressVerifyReq\n    {\n        AddressVerifyRequest = new AddressVerifyRequestType\n        {\n            Street = "some street",\n            Zip = "12345"\n        }\n    };\n    var response = client.AddressVerify(ref credentials, request);\n}	0
3677885	3677810	How to check the arguments with Regex?	switch(args[i])\n{\ncase "-?": ...\ncase "-help": ...\n...\ndefault:\n  if (args[i][0] == '-')\n    throw new Exception("Unrecognised option: " + args[i]);\n}	0
11426168	11426000	Control used for Microsoft Word Option Window?	Tab Control	0
22434325	22422917	Get simple text in body	HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();\nhtmlDoc.LoadHtml(webBrowser1.Document.Body.InnerHtml);\nforeach (var elm in htmlDoc.DocumentNode.Descendants())\n{\n    if (elm.NodeType == HtmlNodeType.Text)\n    {\n        //simple text is #text\n        var innerText=elm.InnerText;\n    }  \n}	0
7700861	7700777	dynamic name for DropDownList in a GridView	'<%# ((GridViewRow)Container).FindControl("ddlName").ClientID %>'	0
10513059	10512845	how to send email wth email template c#	string template =\n@"<html>\n<body>\nHi @Model.FirstName @Model.LastName,\n\nHere are your orders: \n@foreach(var order in Model.Orders) {\n    Order ID @order.Id Quantity : @order.Qty <strong>@order.Price</strong>. \n}\n\n</body>\n</html>";\n\nvar model = new OrderModel {\n    FirstName = "Martin",\n    LastName = "Whatever",\n    Orders = new [] {\n        new Order { Id = 1, Qty = 5, Price = 29.99 },\n        new Order { Id = 2, Qty = 1, Price = 9.99 }\n    }\n};\n\nstring mailBody = Razor.Parse(template, model);	0
9649843	9649814	Best method for determining if a row exists	bool usernameExists = db.QueryValue("SELECT usernameExists = CASE WHEN EXISTS \n (SELECT 1 FROM Users WHERE Username = ?) THEN 1 ELSE 0 END", username);\n\nif (!usernameExists) { Response.Redirect("Register.cshtml"); }	0
507938	507354	How do I get at the listbox item's "key" in c# winforms app?	DictionaryEntry de = (DictionaryEntry)listbox.SelectedItem;\nstring htKey = de.Key.ToString();	0
12660993	12660894	Set a ImageSource from FileSystem in Metro app	// Usage\nmyImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");\n\npublic static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)\n{\n    var uri = new Uri(parent.BaseUri, path);\n    BitmapImage result = new BitmapImage();\n    result.UriSource = uri;\n    return result;\n}	0
15731453	15731372	Closing Form with windows 'X' Button	protected override void OnFormClosing(FormClosingEventArgs e)\n{\n    if(e.CloseReason == CloseReason.UserClosing)\n       Application.Exit();\n    else\n       // it is not clear what you want to do in this case .....\n}	0
23490192	23489604	Open MS Word document model as new document using C#	app.Documents.Add(pathToTemplateFile)	0
12056703	12056295	Extracting a key-value pair from a web service XML response	object neededItem = null;\nforeach (string item in serverInfo.FeatureSet.Keys)\n{\n    if (item == "FileUploadUrl")\n    {\n        neededItem = serverInfo.FeatureSet[item];\n        break;\n    }\n}\nif (neededItem != null)\n{\n    //Do something\n}	0
8121919	8121803	How to popup a usercontrol to fullscreen from a WPF application?	A Popup that covers more than 75 percent of the screen, reduces its width first\n     and then its height to meet the maximum coverage limit of 75 percent.	0
11546691	11512539	Using wildcards with a LinqDataSource	protected void ldsData_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n    var result = db.INSTRUMENT_LOOP_DESCRIPTIONs.AsQueryable();\n\n    foreach (string key in Request.QueryString.Keys)\n    {\n        if (Request.QueryString[key].Trim() != "")\n        {\n            result = result.WhereLike(key, Request.QueryString[key].Replace("?", "_").Replace("*", "%"));\n        }\n    }\n\n    e.Result = result;\n}	0
895623	895595	How do I persist data without global variables?	public class Credentials\n{\n  public static string Username {get;set;}\n}\n\n//...somewhere in your code\n\nCredentials.Username = "MyUserName";	0
22736279	22735696	Casting the returnedData from a stored procedure in Entity Framework to List<ViewModel>	[HttpGet]\n  public ActionResult GetAllCars()\n  {\n        CarRentalEntities entities = new CarRentalEntities();\n        var cars = entities.GetAllCars();    \n\n        List<CarViewModel> carsViewModel = cars.Select(c=> new CarViewModel\n        {\n         Registration = c.Registration,\n         // and so on\n        }).ToList();\n\n        return View(carsViewModel); \n  }	0
31454690	31454492	Access the value after sorting using xdocument	void GetData(out Tuple<string, string> extracted) {\n  extracted = null;\n\n  // ...\n\n  extracted = xDoc.Root.Elements()\n                  .OrderBy(x => (string)x.Attribute("name"))\n                  .Select(n => Tuple.Create(\n                                       n.Attribute("name").Value, \n                                       n.Element("Status").Value\n                  ));\n               );\n}	0
1007456	1007405	Inheriting a web server control in a simple fashion?	get { return (int) (ViewState["RowCount"] ?? 0); }\n  set { ViewState["RowCount"] = value; }	0
14148891	14148699	Preventing UI from freezing while processing data	RunOnUiThread()	0
30227610	30224844	ASP.NET DropDownList in ListView's OnItemUpdating method always has a SelectedIndex of 0	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        DisplayListView();\n    }\n}	0
18694040	18694009	generate a unique ID in c#	int bookingID = 0;\nprotected void calculateButton_Click(object sender, EventArgs e)\n{ \n    bookingID += 1; // You can also use bookingID++\n    bookingIDTextBox.Text = bookingID.ToString();\n}	0
19719492	19716797	How do I create an ODataMessageReader from an HttpWebResponse?	using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, model))\n{\n   var feedReader = messageReader.CreateODataFeedReader(entityType, entitySet);\n   while (feedReader.Read())\n   {\n       switch(feedReader.State)\n       {\n          case ODataReaderState.EntryEnd:\n          {\n             ODataEntry entry = (ODataEntry) feedReader.Item;\n             // access entry.Properties, etc.\n             break;\n          }\n       }\n   }\n}	0
14677191	14677100	How to combine a tuple's two integer values into one for storage in a Hashset?	HashSet<long> _xyPairs = new HashSet<long>();\n\nprivate void SetTravelled(int x, int y, bool travelled)\n{\n    var t = Combine(x, y)\n    ...\n\nprivate bool HaveTravelled(int x, int y)\n{\n    return _xyPairs.Contains(Combine(x, y));\n}\n\nprivate static long Combine(int x, int y)\n{\n    return (long)(((ulong)x) | ((ulong)y) << 32);\n}	0
14335529	14335389	Cancel Requests on link clicked asp.net	function cancelPostBack() {\n  var prm = Sys.WebForms.PageRequestManager.getInstance();\n  if (prm.get_isInAsyncPostBack() {\n   prm.abortPostBack();\n  }\n}	0
7864707	7864572	Directly referencing ObjectContexts like in LinqPad	var db = this;\nint i = db.Categories.Count();	0
10656137	10646543	WPF MediaElement stops playing if moved to other screen	using System.Windows.Interop;\n...\n\n    protected override void OnSourceInitialized(EventArgs e)\n    {\n        HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;\n        HwndTarget hwndTarget = hwndSource.CompositionTarget;\n        hwndTarget.RenderMode = RenderMode.SoftwareOnly;\n        media.Play();\n        base.OnSourceInitialized(e);\n    }	0
11222162	11169144	How to modify PetaPoco class to work with Composite key comprising of non-numeric columns?	[PrimaryKey("ContractorName,ContractorGrade")]	0
15839036	15838075	Wanna add a number to the ASCII code of the characters or bit shift	Console.WriteLine("Enter your name:");\nstring name = Console.ReadLine();\nbyte[] ascii = Encoding.ASCII.GetBytes(name);\nshort[] shorts = bytes.Select(b => (short)b).ToArray();\nint[] finalBytes = new int[shorts.length];\nint[] randomKey = new int[shorts.length];\nint ndx = 0;\nRandom r = new Random();\n\nforeach (short b in shorts)\n{\n    int rByte = r.Next(1, 5000);\n    int singleByte = b + rByte;\n    finalBytes[ndx] = singleByte;\n    randomKey[ndx] = rByte;\n    ndx++;\n}\n\n// finalBytes now holds your data. Do something with it!\n// randomKey holds your hash data. To decode this, you'll\n// need to subtract the value in randomKey[n] from finalBytes[n]	0
1904532	1904475	Is this the best way for me to set events for my controls?	SetPictureBoxEvents()	0
11784485	11779455	How to auto crop an image?	map = 0's, size of image\nfunction f(x,y,image,map)\n    if map(x,y) is not  0\n        return\n    if pixel value at image(x,y)<T\n        map(x,y) = 1;\n        for all neighbors of x,y\n           function([neighbor coordinates],image,map)\n    else\n        map(x,y) = 2;\n end	0
6369445	6369339	How can I substitute characters in C#	var abc = "text1 text2 text3"\nabc = abc.Replace("text3", "textabc");	0
30857437	30852691	Loading MP3 files at runtime in unity	public void LoadSong()\n{\n    StartCoroutine(LoadSongCoroutine());    \n}\n\nIEnumerator LoadSongCoroutine()\n{\n    string url = string.Format("file://{0}", path); \n    WWW www = new WWW(url);\n    yield return www;\n\n    song.clip = www.GetAudioClip(false, false);\n    songName =  song.clip.name;\n    length = song.clip.length;\n}	0
4921985	4921972	How to select listbox item by ValueMember	Listbox1.SelectedValue = 345;	0
10466309	10466206	Match any 10-alphanumeric combination between % and %	(?<=%)[\da-zA-Z]{10}(?=%)	0
6523813	6523691	Find all UserControls of a certain type on a page, possibly using LINQ?	foreach(var control in page.Controls.OfType<BaseUserControl>()) {\n     var javascript = control.JavaScriptReference;\n}	0
26213189	26211622	Copying rows from a .txt file and transfer them into a batch file	string[] lines = File.ReadAllLines("myTXTWithAllLines").Where(s => s.Contains("wsdl")).ToArray();  \nFile.WriteAllLines("MyTXTWithOnlyWSDLLines", lines);	0
20159990	20159936	How do I check if GetStringAsync results in a 401 (for instance)?	try/catch	0
4822646	4822613	C++ function exported in dll and loaded from C#	extern "C" __declspec(dllexport) void foo(HWND wnd)	0
33782043	33781702	javascript, how to get a value from XML	var xmlStr = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope ...';    \nvar xml = new window.DOMParser().parseFromString(xmlStr, "text/xml");   \nvar value = xml.getElementsByTagName("GetTimeStringResult")[0].innerHTML;	0
19796139	19766092	Calculating a logarithmic percentage	double x = ...;\n\ndouble b = 10.0;\ndouble s = 100.0 / (b - 1);\ndouble t = -100.0 / (b - 1);\n\ndouble f = s * Math.Pow(b, x / 30000.0) + t;	0
21183644	21183606	Clear multiple column values in DataTable	dtTable.Rows.OfType<DataRow>().ToList().ForEach(r => \n{\n   r["Column1"] = DBNull.Value;\n   r["Column2"] = DBNull.Value;\n});	0
23918458	23916328	Get UserPrincipal by employeeID	string username = "";\n\nDirectoryEntry entry = new DirectoryEntry(_path);\n\n//search for a DirectoryEntry based on employeeID\nDirectorySearcher search = new DirectorySearcher(entry);\nsearch.Filter = "(employeeID=" + empID + ")";\n\n//username\nsearch.PropertiesToLoad.Add("sAMAccountName");\n\nSearchResult result = search.FindOne();\n\n//get sAMAccountName property\nusername = result.Properties["sAMAccountName"][0].ToString();	0
783469	778493	How do I save each certificate in the cert chain	Dim cert2 As X509Certificate2\nDim ch As New X509Chain()\nch.Build(cert2)\n\nDim element As X509ChainElement\n\nFor Each element In ch.ChainElements\n    blob = element.Certificate.RawData()\nNext Element	0
20014418	20014325	Inserting new XML Data at specific Point in document C# Using LINQ	var InsHere = from name in doc.Descendants("Users")\n              where name.Element("User").Attribute("Name").Value == "ServerManager"\n              select name.Element("User").Element("Permissions").Element("Permission");\nvar newElement = new XElement(InsHere); // this clones the found Permission element\nnewElement.Attribute("Dir").Value = "the new directory path to add";\nInsHere.AddAfterSelf(newElement);	0
23417612	23417559	WebApi2 CreatedAtRoute routing to different controller	return CreatedAtRoute("DefaultApi", new { controller = "messages", id = message.Id }, message);	0
6254328	6004923	NHibernate QueryOver subcollection using Max	var query = session.QueryOver<BlogPost>(); //get queryover however you implemented\nBlogPost bp = null;\nComment c = null;\n\nvar q = QueryOver.Of<BlogPost>(() => bp)\n    .JoinAlias(() => bp.Comments, () => c)\n    .SelectList(list => list.SelectMax(() => c.DateAdd));\n\nquery.JoinQueryOver<Comment>(x => x.Comments)\n    .WithSubquery\n    .WhereProperty(x => x.DateAdd).Eq(q)\n    .Where(x => x.TypeId == 1 || x.TypeId == 2);\n\n     query.List...	0
1362550	1359146	How can I perform this query using L2E?	var q = from a in Context.Activities\n        where a.Keywords.Any(k => k.Keyword == someKeyword)\n        select a;	0
4453285	4450231	Can I make a constant from a compile-time env variable in csharp?	echo namespace Some.Namespace > "$(ProjectDir)\CiInfo.cs"\necho { >> "$(ProjectDir)\CiInfo.cs"\necho     ///^<summary^>Info about the continuous integration server build that produced this binary.^</summary^> >> "$(ProjectDir)\CiInfo.cs"\necho     public static class CiInfo >> "$(ProjectDir)\CiInfo.cs"\necho     { >> "$(ProjectDir)\CiInfo.cs"\necho         ///^<summary^>The current build number, such as "153"^</summary^> >> "$(ProjectDir)\CiInfo.cs"\necho         public const string BuildNumber = ("%BUILD_NUMBER%" == "" ? @"Unknown" : "%BUILD_NUMBER%"); >> "$(ProjectDir)\CiInfo.cs"\necho         ///^<summary^>String of the build number and build date/time, and other useful info.^</summary^> >> "$(ProjectDir)\CiInfo.cs"\necho         public const string BuildTag = ("%BUILD_TAG%" == "" ? @"nohudson" : "%BUILD_TAG%") + " built: %DATE%-%TIME%"; >> "$(ProjectDir)\CiInfo.cs"\necho     } >> "$(ProjectDir)\CiInfo.cs"\necho } >> "$(ProjectDir)\CiInfo.cs"	0
10244075	10243992	Copy certain positions from a double array to another double array	Double[] inputxx = inputx.Where((x, i) => i % 5 == 0).ToArray();	0
17592061	17591420	Inserting UTF8 data into image field in sql server 2005 from c#	SqlCommand ImageCommand = new SqlCommand("", (SqlConnection)connection, (SqlTransaction)Transaction);\n\nImageCommand.CommandText = string.Format(@"Update xdpath set content = @ByteArray where dpath = '{0}'",file.Key);\n\nImageCommand.Parameters.Add("@ByteArray", SqlDbType.Image).Value = (object)encodedBytes ?? DBNull.Value;	0
12923516	12923272	change connection string for dataset	var dt1 = new CustomDataSet.CustomDataTable();\nvar connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString\nusing (var connection = new SqlConnection(connectionString))\n{\n    using (var da1 = new GetCustomDataTableAdapter() { Connection = connection })\n    {\n        da1.Fill(dt1, id);\n    }   \n}	0
32314882	32314799	UWP - Image Uri in Application Folder	BitmapImage bitmapImage = \n                     new BitmapImage(new Uri("ms-appx://[project-name]/Assets/image.jpg"));	0
1310892	1310867	Variable of an object getting changed when other object is modified	Quantity = OriginalProducts.ToList().Find(p => p.ProductId == (int)row["ProductId"]).Quantity,	0
4280019	4279892	Convert a string containing a hexadecimal value starting with "0x" to an integer or long	int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");	0
2432967	2432628	How to get the connection string value from hibernate.cfg.xml file?	NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();\nstring conString = cfg.Configuration.GetProperty(NHibernate.Cfg.Environment.ConnectionString);	0
15279233	15278228	Access PSObject property by name in C#	psobjectvariable.Properties["transactionName"].Value	0
24937700	24937677	Finding items of a list that are not in the other list	IEnumerable<MyObject> diffs = incomingList.Except(fullList);	0
3680922	3680881	DLL External Function Declarations in C#	internal static class UnsafeNativeMethods {\n   [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]\n   internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName );\n}\n\ninternal delegate int DllRegisterServerInvoker();\n\n// code snippet in a method somewhere, error checking omitted\nIntPtr fptr = UnsafeNativeMethods.GetProcAddress( hModule, "DllRegisterServer" );\nDllRegisterServerInvoker drs = (DllRegisterServerInvoker) Marshal.GetDelegateForFunctionPointer( fptr, typeof(DllRegisterServerInvoker) );\ndrs(); // call via a function pointer	0
24328516	24290028	Reading from buffer shows unrecognizable (Chinese) characters	Byte[] bytes = Encoding.Unicode.GetBytes(p);\nvar bUTF8 = Encoding.UTF8.GetString(bytes);	0
11028570	10781073	how to join 4 table in linq	var items = from c in context.COST_TYPES\n                    join o in context.CLEARANCE_COST .Where(d=>d.REQUEST_ID==8) on c.COST_ID equals o.COST_ID into outer\n                    from o in outer.DefaultIfEmpty()\n                    select new\n                               {\n                                   o.CLEARANCE_REQUEST.WAYBILL_NO,\n                                   c.COST_NAME,\n                                   o.CURRENCY_UNITS.CURRENCY_NAME,\n                                   Amount=o==null?0:o.COST_AMOUNT\n                               };	0
15268743	15268664	Is value in the dictionary becomes a pointer?	private void Update(string Name)\n    {\n        if (Name== null || Name=="")\n            return;\n        Dic[Name] = MyClass;\n    }	0
31633521	31630805	Chart in C# is displaying duplicate values	private void Form1_Load(object sender, EventArgs e)\n{\n    chart1.Series["G.R"].Points.AddXY("25/07/2015", 35);\n}	0
4622359	4622344	detect how many cores a client has using C#	Environment.ProcessorCount	0
27252282	27251892	Please suggest a Windows Object Picker C# wrapper	var dlg = new DirectoryObjectDialog\n{\n    MultiSelect = true\n};\ndlg.AddScope(DirectoryScope.Computer, users: true, groups: true);\ndlg.AddScope(DirectoryScope.Domain, users: true, groups: true);\nif (dlg.ShowDialog() == DialogResult.OK)\n{\n    foreach (var sel in dlg.Selections)\n        Console.WriteLine("{0}: {1}", sel.Principal.SamAccountName, sel.Principal.Sid);\n}	0
20673840	20673724	How to convert HEX value to Datetime in .Net	let seconds dt = Convert.ToInt32( (dt - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local ) ).TotalSeconds ) \nlet fromseconds (seconds : float, dtk : DateTimeKind) = (new DateTime(1970, 1, 1, 0, 0, 0 , ( dtk : DateTimeKind ) )).AddSeconds(seconds)	0
8857862	8856145	Find current day of week in c# ASP.Net	string selectSQL = string.Format("SELECT lec FROM schedule WHERE dbo.schedule.day = {0} ", testDay);	0
21528122	21523550	Windows Phone Toolkit CustomMessageBox long content scrolling	ScrollViewer viewer = new ScrollViewer() { Height = 500 /* fixed Height */ };\n\nTextBlock txtInfo = new TextBlock();\ntxtInfo.Text = @"some long text here.....";\ntxtInfo.TextWrapping = TextWrapping.Wrap;\n\nviewer.Content = txtInfo;\n\n\nCustomMessageBox Box = new CustomMessageBox();\nBox.Content = viewer;\nBox.Show();	0
18653694	18653566	Get all months names between two given dates	var start = new DateTime(2013, 1, 1);\nvar end = new DateTime(2013, 6, 22);\n\n// set end-date to end of month\nend = new DateTime(end.Year, end.Month, DateTime.DaysInMonth(end.Year, end.Month));\n\nvar diff = Enumerable.Range(0, Int32.MaxValue)\n                     .Select(e => start.AddMonths(e))\n                     .TakeWhile(e => e <= end)\n                     .Select(e => e.ToString("MMMM"));	0
28428425	28428348	Getting Percentage of TypeOf Item in a List with LINQ	var catPercent = list.OfType<Cat>().Count() / (float)list.Count();	0
21576026	21575819	How to take values as Key/value pair from database in C#	private KeyValuePair<string, int>[] GetData()\n{\nSqlConnection conn = new SqlConnection("connectionstring");\nSqlCommand comm = new SqlCommand("SELECT column1, column2 FROM mytable");\n\nconn.Open();\n\ntry\n{\n    SqlDataReader sr = comm.ExecuteReader();\n    IList<KeyValuePair<string, int>> returnColl = new List<KeyValuePair<string, int>>();\n    if (sr.HasRows)\n    {\n        while(sr.Read())\n        {\n            returnColl.Add(new KeyValuePair<string, int>(sr["column1"].ToString(), sr["column2"]));\n        }\n    }\n}\nfinally\n{\n    conn.Close();\n}\n\nreturn returnColl.ToArray();\n}	0
1772748	1772730	Need help with RegEx for ranges	string[] ranges = inputString.split(',');\n\nforeach (string rangeCandidate in ranges) {\n   // See if matches regex\n}	0
2221705	2221677	Get a registry key value	string s = reg.GetValue(null).ToString();	0
23490844	23490802	Does C# pass a List<T> to a method by reference or as a copy?	List<T>	0
10748058	10747782	How to query datetime literals and null values in Linq predicate?	CreateDateTime( year, month, day, hour, minute, second)	0
8177583	8177389	ASP.NET Delete Multiple GridView rows via Checkbox template	bool atLeastOneRowDeleted = false;\n    foreach (GridViewRow row in GridView1.Rows)\n    {\n        // Access the CheckBox\n        CheckBox cb = (CheckBox)row.FindControl("UserSelection");\n        if (cb != null && cb.Checked)\n        {\n            atLeastOneRowDeleted = true;\n            //assuming you have the ID column after the controls\n            string CusId = (row.Cells[3].Text);\n\n\n       SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");\n       string sql = string.Format("DELETE FROM [UserDB] where Employee like '%{0}%'",userID);\n       SqlCommand cmd = new SqlCommand(sql,conn);\n       conn.Open();\n       cmd.ExecuteNonQuery();\n        }\n    }	0
17654552	17654446	How to add files in solution explorer of visual studio?	public String SolutionPath()\n{\n    return Path.GetDirectoryName(_applicationObject.Solution.FullName);\n}	0
18038168	18038071	I'm trying to compress some files from one directory to another but I'm getting access denied on one of the directories why?	string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z");\n    .....\n\n    compressor.CompressDirectory(source, output);	0
2378405	2378379	How to check apartment state of current thread?	System.Threading.Thread.CurrentThread.GetApartmentState()	0
3725986	3721683	Localize a MasterPage	protected void Application_AcquireRequestState(object sender, EventArgs e)\n{\n    CultureInfo culture = new CultureInfo("en-NZ");\n    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;\n    System.Threading.Thread.CurrentThread.CurrentCulture = culture;\n}	0
14766593	14607099	JSON.NET with Custom Serializer to a custom object	var objects = JArray.Parse(jsonString)\nList<A> objectList = new List<A>();\nforeach (var obj in objects) {\n    A newObj = null;\n    switch ((string)obj["type"]) {\n        case "B":\n            newObj = obj.ToObject<B>();\n            break;\n        case "C":\n            newObj = obj.ToObject<C>();\n            break;\n    }\n    newObj.MyCollection.Clear();\n    foreach (var x in obj["myCollection"]) {\n        var newX = null;\n        switch ((string)x["type"]) {\n            case "Y":\n                newX = x.ToObject<Y>();\n                break;\n            case "Z":\n                newX = x.ToObject<Z>();\n                break;\n        }\n        newObj.MyCollection.Add(newX);\n    }\n    objectList.Add(newObj);\n}	0
9096465	9096386	Navigating with webbrowser using a string	class XMLR\n{\n    private string workshop1;\n\n    ...\n}	0
25972842	25868669	How to get data from SQL Server database in Xml format and from that Xml fill DataSet	SqlConnection conn = new SqlConnection(ConnectionString);\n\nSqlCommand cmd = new SqlCommand();\nSystem.Xml.XmlReader xmlreader;\nXmlDataDocument xmlDataDoc = new XmlDataDocument();\ntry\n{\n    cmd.Connection = conn;\n    conn.Open();\n    cmd.CommandText = _Query;\n    xmlreader = cmd.ExecuteXmlReader();\n    DataSet ds = new DataSet();\n    dt.Columns.Add("AcademicYearId", typeof(string));\n    dt.Columns.Add("AcademicYearName", typeof(string));\n    dt.Columns.Add("StartingYear", typeof(string));\n    dt.Columns.Add("EndingYear", typeof(string));\n    dt.Columns.Add("Comments", typeof(string));\n    dt.Columns.Add("RCO", typeof(string));\n    dt.Columns.Add("UserID", typeof(string));\n\n    ds.Tables.Add(dt);\n    while(xmlreader.Read()\n    {\n      xmlDataDoc.DataSet.ReadXml(xmlreader);\n    }\n    ds = xmlDataDoc.DataSet;\n    xmlreader.Close();\n    conn.Close();\n}\ncatch (Exception ex)\n{\n    throw ex;\n}\nfinally\n{\n    if (conn.State != ConnectionState.Closed)\n    {\n       conn.Close();\n    }\n}	0
15660510	15660194	Entity Framework: Add item using Include	var t = new Teacher();\nt.User = new User();\ncontext.Teachers.Add(t)\ncontext.SaveChanges();	0
33446072	33445977	Cannot assign to 'click' because it is a 'method group'	button.Clicked += new EventHandler (button_Click);	0
21450118	21450098	How can I convert bytes available to bytes available in KB, MB, GB etc?	static String BytesToString(long byteCount)\n    {\n        string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB\n        if (byteCount == 0)\n            return "0" + suf[0];\n        long bytes = Math.Abs(byteCount);\n        int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));\n        double num = Math.Round(bytes / Math.Pow(1024, place), 1);\n        return (Math.Sign(byteCount) * num).ToString() + suf[place];\n    }	0
6379323	6379292	C# - Import lines from a text file into a Process.Start statement	foreach(string exename in System.IO.File.ReadAllLines("yourfile.txt"))\n{\n  Process.Start("test.exe", "\"" + exename + "\"");\n}	0
11958251	11957384	DDD Domain Model Complex Validation	// repository\ninterface Users {\n  // implementation executes SQL COUNT in case of relation DB\n  bool IsNameUnique(String name);\n\n  // implementation will call IsNameUnique and throw if it fails\n  void Add(User user);\n}	0
6855966	6855839	Get data from wp7 Listbox in C#?	List<String> container = new List<String>();\nlistBox.ItemsSource = container;\nList<String> retrieve = (List<String>) listBox.ItemsSource;	0
17267458	17267021	How do I bind a WPF Image element to a PNG on the local hard drive using a relative filepath derived from a DB?	Image.Source	0
7436165	7435960	Help choosing my DDD aggregate roots within a provided scenerio?	public class EmployeeRepository\n{\n    public IList<Employee> GetAll() {}\n}\n\npublic class MeetingRepository\n{\n    public IList<Meeting> GetAll(){}\n\n    public IList<Meeting> GetMeetingsAttendedByEmployee( Employee emp ){}\n}	0
3596623	3497862	Three XML formatting problems with .NET XmlSerializer	public class XmlTextWriterFull : XmlTextWriter\n{\n    public XmlTextWriterFull(TextWriter sink) : base(sink) { }\n\n    public override void WriteEndElement()\n    {\n        base.WriteFullEndElement();\n    }\n\n    public override void WriteStartDocument()\n    {\n        base.WriteRaw("<?xml version=\"1.0\"?>");\n    }\n}\n\npublic class temp\n{\n    public int a = 0;\n    public List<int> x = new List<int>();\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        XmlTextWriterFull writer = new XmlTextWriterFull(Console.Out);\n\n        XmlSerializer xs = new XmlSerializer(typeof(temp));\n        xs.Serialize(writer,new temp());\n        Console.ReadKey();\n    }\n}	0
14809893	14809866	C# - remove whitespace from input number to have int	int n = Convert.ToInt32(args.Content.Replace(" ",""));\nif (n >= 1000) \nn = (int) (n - (n * 0.75));	0
29417412	28500156	Is there a difference in disposing Icon and Bitmap?	[DllImport("user32.dll", CharSet = CharSet.Auto)]\nextern static bool DestroyIcon(IntPtr handle);\n\nprivate void GetHicon_Example(PaintEventArgs e)\n{\n// Create a Bitmap object from an image file.\nBitmap myBitmap = new Bitmap(@"c:\FakePhoto.jpg");\n\n// Draw myBitmap to the screen.\ne.Graphics.DrawImage(myBitmap, 0, 0);\n\n// Get an Hicon for myBitmap.\nIntPtr Hicon = myBitmap.GetHicon();\n\n// Create a new icon from the handle.\nIcon newIcon = Icon.FromHandle(Hicon);\n\n// Set the form Icon attribute to the new icon.\nthis.Icon = newIcon;\n\n// Destroy the Icon, since the form creates\n// its own copy of the icon.\nDestroyIcon(newIcon.Handle);\n}	0
17623266	17623160	listview details not show data properly	foreach (MyData in dataList)\n{\n    var row = new ListViewItem(a.Code);\n    row.SubItems.Add(a.Name);\n    row.SubItems.Add(a.Price.ToString("F"));\n    listView1.Items.Add(row);\n}	0
8945433	8935161	How to add a case-insensitive option to Array.IndexOf	Array.FindIndex(myarr, t => t.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >=0);	0
27948629	27948552	How to create a list from a CSV file in c#?	for (int i = 0; i < linesInFile.Length; i++)\n{\n    string currentLine1 = linesInFile[i];\n    ProductDetails = currentLine1.Split(',');\n\n    foreach (var p in ProductDetails)\n    {\n        Product prod = new Product();\n        {\n            prod.ID = p;\n        };\n        products.Add(prod);\n    }\n}	0
23763793	23763538	EF6 One to Many and Many to One between same entities	modelBuilder.Entity<Team>().HasMany(t => t.Players).WithRequired(p => p.Team).HasForeignKey(p => p.TeamId);\nmodelBuilder.Entity<Team>().HasRequired(t => t.Captain).WithMany().HasForeignKey(t => t.CaptainId);	0
2585290	2585224	Problem with order by in LINQ	var query = (from c in vwAnimalsTaxon.All()\n    select new { taxRecID = c.ClaRecID, taxName = c.ClaName }\n).Distinct().OrderBy(t => t.taxName);	0
29108905	20136504	How can set a default value constraint with Entity Framework 6 Code First?	AddColumn("[table name]", "[column name]", c => c.Boolean(nullable: false, defaultValue: false));	0
9890425	9873668	How to update DOM content inside WebBrowser Control in C#?	HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];\nHtmlElement scriptElement = webBrowser1.Document.CreateElement("script");\nIHTMLScriptElement domScriptElement = (IHTMLScriptElement)scriptElement.DomElement;\ndomScriptElement.text = "function applyChanges(){/*DO WHATEVER YOU WANT HERE*/}";\nheadElement.AppendChild(scriptElement);\n\n// Call the nextline whenever you want to execute your code\nwebBrowser1.Document.InvokeScript("applyChanges");	0
28075984	27950110	SMO Equivalent to SET HADR OFF	Server primaryServer = new Server();\nAvailabilityDatabase pDb = primaryServer.AvailabilityGroups[agName].AvailabilityDatabases[dbName];\npDb.SuspendDataMovement();\nwhile (!pDb.IsSuspended)\n{\n  Thread.Sleep(1000);\n  pDb.Refresh();\n}\n\nforeach (var secondary in secondaryServers)\n{\n  AvailabilityDatabase sDb = secondary.AvailabilityGroups[agName].AvailabilityDatabases[dbName];\n  sDb.SuspendDataMovement();\n  while (!sDb.IsSuspended)\n  {\n    Thread.Sleep(1000);\n    sDb.Refresh();\n  }\n\n  sDb.LeaveAvailabilityGroup(); // this appears to be the equivalent of SET HADR OFF\n\n  Database db = secondary.Databases[dbName];\n  db.UserAccess = DatabaseUserAccess.Single;\n  secondary.KillAllProcesses(dbName);\n  db.Drop();\n}\n\npDb.Drop();\n\nDatabase db = primaryServer.Databases[dbName];\ndb.UserAccess = DatabaseUserAccess.Single;\nprimaryServer.KillAllProcesses(dbName);\ndb.Drop();	0
14782217	14781764	Returning XmlDocument from an XmlElement	cred.CredExecution mycredit = new cred.CredExecution();\nSystem.Xml.XmlElement XmlEle = mycredit.RetrieveParsedRawData(inquiry, true);\nSystem.Xml.XmlDocument XmlDoc = XmlEle.OwnerDocument;	0
867769	867754	how can i use a dataset for refinement	myDataSet.DefaultViewManager.DataViewSettings["myTableName"].RowFilter = "ID = 3";	0
7732448	7728741	SSIS read/write to variable in script task	public class scriptmain\ninherits usercomponent\n\ndim counter as integer\ndim Valint as integer\n.....\n\n\nPublic sub new()\ncounter = 0\nend sub\n\npublic overrides sub input0_processintputrow(byval row as input0buffer)\n    counter +=1\nEnd Sub\n\nPublic overrides sub PostExecute()\n    Dim vars as IDTSvariables100 = nothing\n\n    Me.variableDispenser.lockforread("User::Valint")\n    Me.variableDispenser.GetVariables(vars)\n\n    counter = CType (vars("User:: Valint").Value, integer)\n    vars.Unlock()\n    Me.VariableDispenser.LockoneForWrite("User::Valint", vars)\n    vars("User::Valint").Value = counter\n    vars.Unlock()\nEnd Sub	0
421654	405480	Best practices when applying conditional formatting in data bound controls?	MakePackageSelectionUrl(((System.Data.DataRowView)Container.DataItem)["PackageId"])	0
11502865	11502833	C# - Assigning the result of a boolean expression	status = user.Status == AccountStatus.Active;	0
11786420	11786382	Making a dynamic path string for saving an image	DateTime.Now.ToString("ddMMyyHHmmss");	0
18277016	18276969	How to extract the filename from a path	string filename = System.IO.Path.GetFileName("/Images/She.jpg");	0
9228849	9228671	JavaScriptSerializer.Deserialize() into a dictionary	public class CurrencyRateResponse\n{\n    public string disclaimer { get; set; }\n    public string license { get; set; }\n    public string timestamp { get; set; }\n    public string @base { get; set; }\n    public Dictionary<string,decimal> rates { get; set; }\n}\n\nJavaScriptSerializer ser = new JavaScriptSerializer();\nvar obj =  ser.Deserialize<CurrencyRateResponse>(json);\nvar rate = obj.rates["AMD"];	0
5684211	5635385	Is there any default strategy to prepare application for a resolution change?	ScrollViewer Background="GreenYellow" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" Name="layoutRoot">\n        Canvas Width="1024" Height="768">\n            dataInput:Label Height="50" Name="label1" Width="100" Canvas.Left="540" Canvas.Top="131" Content="aeeeeeeee" />\n            Button Canvas.Left="12" Canvas.Top="131" Content="Button" Height="23" Name="button1" Width="75" />\n            Button Canvas.Left="937" Canvas.Top="147" Content="Button" Height="23" Name="button2" Width="75" />\n            Button Canvas.Left="510" Canvas.Top="21" Content="Button" Height="23" Name="button3" Width="75" />\n            Button Canvas.Left="482" Canvas.Top="550" Content="Button" Height="23" Name="button4" Width="75" />\n        /Canvas>\n    /ScrollViewer>	0
30531590	30517646	How to apply strike formatting using EPPlus	[TestMethod]\npublic void Strike_Format_Test()\n{\n    //http://stackoverflow.com/questions/30517646/how-to-apply-strike-formatting-using-epplus\n\n    var existingFile = new FileInfo(@"c:\temp\StrikeFormat.xlsx");\n    using (var pck = new ExcelPackage(existingFile))\n    {\n        var wb = pck.Workbook;\n        var ws = wb.Worksheets.First();\n\n        var cell = ws.Cells["A1"];\n        Console.WriteLine(cell.Style.Font.Strike);\n    }\n}	0
3350132	2287134	How to manage write and read in serialport when write depends on read data	byte[] data = "Your message to be sent on serial port";\n    serialPort.Write(data, 0, data.Length);\n\n    byte[] buffer = new byte[16];\n    int vintctr = 0;\n                    while (vintctr < 16)\n                        vintctr  += serialPort.Read(buffer, 0, 16);\n\nDebug this and you you can get the reply from the port.	0
4672555	4672407	How to call a method in a UserControl after it is shown?	protected override void OnVisibleChanged(EventArgs e)\n{\n    base.OnVisibleChanged(e);\n\n    if (Visible && !Disposing) PopulateGridView(); //<-- your population logic\n}	0
22127577	22127347	Making An md5 hash of hashes	// Create the MD5 hash object.\nSystem.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create ();\n\nstring password = "password";\nstring salt = "salt";\n\n// Hash password and salt\nbyte[] passwordHash = md5.ComputeHash (System.Text.Encoding.ASCII.GetBytes (password));\nbyte[] saltHash = md5.ComputeHash (System.Text.Encoding.ASCII.GetBytes (salt));\n\n// Combine password and hash.\nstring passwordAndSalt = System.Text.Encoding.ASCII.GetString (passwordHash) + System.Text.Encoding.ASCII.GetString (saltHash);\n\n// Compute final hash against the password and salt.\nbyte[] finalHash = md5.ComputeHash (System.Text.Encoding.ASCII.GetBytes (passwordAndSalt));	0
22176564	22163329	Change name application	Product Code	0
12418764	12418716	How can i get a List<string> of images from a website link?	private List<string> retrieveImages()\n{\n  List<string> imgList = new List<string>();\n  HtmlDocument doc = new HtmlDocument();\n  doc.Load("file.htm"); //or whatever HTML file you have\n  HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img[@src]");\n  if (imgs == null) return new List<string>();\n\n  foreach (HtmlNode img in imgs)\n  {\n   if (img.Attributes["src"] == null)\n      continue;\n   HtmlAttribute src = img.Attributes["src"];\n\n   imgList.Add(src.Value);\n   //Do something with src.Value such as Get the image and save it locally\n   // Image img = GetImage(src.Value)\n   // img.Save(aLocalFilePath);\n  }\nreturn imgList;\n}\n\nprivate Image GetImage(string url)\n{\n    System.Net.WebRequest request = System.Net.WebRequest.Create(url);\n\n    System.Net.WebResponse response = request.GetResponse();\n    System.IO.Stream responseStream = response.GetResponseStream();\n\n    Bitmap bmp = new Bitmap(responseStream);\n\n    responseStream.Dispose();\n\n    return bmp;\n}	0
14049279	14049051	How do I get my console application to run a background process on another thread without exiting?	Module Module1\n        Dim x As New Threading.Thread(AddressOf tick)\n        Dim y As New Threading.Barrier(2)\n\n        Sub Main()\n            x.IsBackground = True\n            x.Start()\n            y.SignalAndWait()\n        End Sub\n\n        Sub tick()\n            Threading.Thread.Sleep(10000)\n            y.SignalAndWait()\n        End Sub\n    End Module	0
20679894	20678698	Byte array to xml with UTF8 and base64 encoding?	var base64AsAscii = Encoding.ASCII.GetString(bytesFromWebService);\nvar decodedBytes = Convert.FromBase64String(bytesAsAscii);\nvar text = Encoding.UTF8.GetString(decodedBytes);	0
3540187	3534628	Access raw JSON from inside asp.net WebMethod	protected void LogException(Exception ex, HttpContext context)\n{\n    context.Request.InputStream.Position = 0;\n    string rawJson = null;\n    using (StreamReader reader = new StreamReader(context.Request.InputStream))\n    {\n        rawJson = reader.ReadToEnd();\n    }\n    //write exception detail to log\n}	0
11255223	11255127	Getting Random File from Directory Tree	var random = new Random(); // this should be placed in a static member variable, but is ok for this example\nvar fileNames = System.IO.Directory.GetFiles(@"c:\temp", "*.mp3", SearchOption.AllDirectories);\nvar randomFile = fileNames[random.Next(0, fileNames.Length)];	0
14594038	14593975	How to Convert a integer value to String	Dropdown.Items.FindByValue(33).text	0
31710352	31710212	How to make a new window the size of the selected image	Form form = new Form();\n        form.Text = "Image Viewer";\n        form.AutoSize = true;\n        form.AutoSizeMode = AutoSizeMode.GrowAndShrink;\n\n        PictureBox pictureBox = new PictureBox();\n        pictureBox.Image = imageClicked;\n        pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;\n        pictureBox.Location = new Point(0, 0);\n\n        form.Controls.Add(pictureBox);\n        form.ShowDialog();	0
18482038	18481484	Url Routing for unknown number of params	routes.MapPageRoute(\n    "ManyParam",\n    "{*path}",\n    "~/Default.aspx",\n    false,\n    new RouteValueDictionary(),\n    new RouteValueDictionary { { "path", @".*\.html" } }\n );	0
9086086	9086001	Writing a C# string to a preallocated unmanaged buffer using UTF8 encoding	public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)	0
5571441	5571350	get flag from database and set within authentication	int flag =Int32.Parse(dr["flag"]);\n\nif(flag != 1)\nResponse.Redirect("Uploadpicture.aspx");\nelse\nResponse.Redirect("UserProfileWall.aspx");	0
27317975	27315124	How to get display resolution (screen size)?	_ScreenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;\n_ScreenHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;	0
1321862	1305324	Sharepoint accessing "User Information List" via a webservice	var node = ws.GetListItems("User Information List", String.Empty, null, null, String.Empty, null, null);	0
14401108	14401040	How to detect idle on monitor 2?	System.Windows.Forms.Cursor.Position	0
31298940	30737580	Custom UIRefreshControl animation	- (void)scrollViewDidScroll:(UIScrollView *)scrollView\n{\n    NSLog(@"Y Offset: %f", scrollView.contentOffset.y);\n}	0
10538536	10538507	Days, hours, minutes, seconds between two dates	TimeSpan span = (DateTime.Now - DateTime.Now);\n\nString.Format("{0} days, {1} hours, {2} minutes, {3} seconds", \n    span.Days, span.Hours, span.Minutes, span.Seconds);	0
8821180	8821031	Using all cores in pc with c#	Parallel.For(0, 2000000000, i =>\n{\n    var string inputData = "ninjas " + "like " + "taco";\n});	0
29079826	29066963	ASP.NET GridView Deletion 'Input string was not in a correct format'	DELETE FROM [Products] WHERE [Id] = @original_Id	0
4350810	4017714	binding to a list of tuples	public class Pair<T, U> \n{\n     public Pair() {\n     }\n\n     public Pair(T first, U second) {\n       this.First = first;\n       this.Second = second;\n     }\n\n     public T First { get; set; }\n     public U Second { get; set; }\n};	0
14442988	14439334	Digital Signatures - What is the optimal size of the seed data to sign	SignatureValue = EncryptWithPrivateKey(DigestOf(data))	0
11957156	11957066	How to convert a list of objects to two level dictionary?	var result = customers.GroupBy(c => c.Id)\n                      .ToDictionary(group => group.Key,\n                                    group => group.ToDictionary(c => c.City, \n                                                                c => c.DidLive));	0
3101994	3101823	Extract Chinese text from Query string	String text = Server.UrlDecode(Request.QueryString["text"]);	0
11428133	11419873	C#, Emgu webcam - choose capture size	imageBox1.SizeMode = PictureBoxSizeMode.StretchImage;	0
8063232	4733623	Getting the Range of a named area in Excel via C#.net	Range rng = myExcelWorksheet.get_Range("Tablename", misValue);	0
6847929	6847881	my sql returns only single value	for ( int i = 0; dt2 != null && i < dt2.Rows.Count; ++i )\n{\n    String tmp = dt2.Rows[ i ]["staff_AccessCode"].ToString();\n    if ( tmp.Equals( what_ever_variable_or_constant /* e.g., txtbox.Text */ ) )\n    {\n        accessname = tmp;\n        //break; ?\n    }\n}	0
210464	210446	What is the best way for a client app to find a server on a local network in C#?	using System.Net;\nusing System.Net.Sockets;\n\n[STAThread]\nstatic void Main(string[] args)\n{\n    Socket socket = new Socket(AddressFamily.InterNetwork,\n    SocketType.Dgram, ProtocolType.Udp);\n    socket.Bind(new IPEndPoint(IPAddress.Any, 8002));\n    socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));\n    socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));\n\n    int availableBytes = socket.Available;\n    if (availableBytes > 0)\n    {\n        byte[] buffer = new byte[availableBytes];\n        socket.Receive(buffer, 0, availableBytes, SocketFlags.None);\n        // buffer has the information on how to connect to the server\n    }\n}	0
21137364	20324941	Authentication in wp8	var username = uname.Text;\n                var password = pass.Password;\n\n                var postData = "email=" + username + "&password=" + password;\n                WebClient webClient = new WebClient();\n                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";\n                var uri = new Uri("Your URL here", UriKind.Absolute);\n                webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();\n                webClient.AllowWriteStreamBuffering = true;\n                webClient.Encoding = System.Text.Encoding.UTF8;\n                webClient.UploadStringAsync(uri, "POST", postData);\n                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postComplete);	0
19946279	19900791	How to create a datatable in xsd file using c#	dt.Columns.Add("Column1");\n        dt.Columns.Add("Column2");\n        dt.Columns.Add("Column3");\n        dt.Columns.Add("Column4");	0
23156266	23156032	C# Load a native dll dynamic simple	class Program\n{\n  static void Main(string[] args)\n  {\n    var dll = Assembly.LoadFile(@"C:\Test.dll");//The path of your dll\n\n    var theType = dll.GetType("dll.Test");\n    var c = Activator.CreateInstance(theType);\n    var method = theType.GetMethod("Output");//Your method in the class\n    method.Invoke(c, new object[]{@"Hello world"});\n\n    Console.ReadLine();\n  }\n}	0
9774697	9774351	model item in WF 4	.Add(new Variable<Dictionary<string, object>>( { "Provider", provider }));	0
14022714	13978164	How do I access X.509 certificates stored in a service account?	mmc.exe	0
16675362	16675190	VB.Net 'Overridable' is not valid on a member variable declaration	Imports System.Collections.Generic\nImports System.ComponentModel.DataAnnotations\n\nNamespace WingtipToys.Models\nPublic Class Category\n    <ScaffoldColumn(False)> _\n    Public Property CategoryID As Integer\n\n    <Required, StringLength(100), Display(Name := "Name")> _\n    Public Property CategoryName As String\n\n\n    <Display(Name := "Product Description")> _\n    Public Property Description As String         \n\n    Public Overridable Property Products As ICollection(Of Product)\nEnd Class\nEnd Namespace	0
9987258	9916659	dynamic binding of chart from database in VS2010 in C#	OleDbConnection con1 = new OleDbConnection(@"PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=RS.accdb");\n         String sqlo = "Select * from " + out_table + "";\n        OleDbDataAdapter da1 = new OleDbDataAdapter(sqlo, con);\n        DataSet ds = new DataSet();\n        da1.Fill(ds, in_table);\n        DataView firstView = new DataView(ds.Tables[0]);\n        chart1.Series[0].Points.DataBindXY(firstView, "ID", firstView, "ADX");	0
1893935	1893919	Quick fix for splitting a string using regexp	string s = "NIGHT.set('/xs:Service/xs:Location[2]/xs:Res/protocol','HOPR','SP')";\n    s = s.Replace("'", "");\n    Regex re = new Regex(@"^(.*)\((.*)\)$");\n    Match match = re.Match(s);\n    if (match.Success)\n    {\n        string function = match.Groups[1].Value;\n        string[] parameters = match.Groups[2].Value.Split(',');\n        // ...\n    }	0
14815915	14815441	Extract a vector from a two dimensional array efficiently in C#	Parallel.For(0, NTerms, i => myVec[i] = myMat[i, col]);	0
4173055	4172996	I need to write a big-endian single-precision floating point number to file in C#	var bytes = BitConverter.GetBytes(floatVal);	0
1167029	1166807	C# dynamically taking data from DataGridView	String dataYouWant = dataGridView1.Rows[e.RowIndex].Cells[1].Value;	0
27876323	27860502	Parse XML in c# with XMLReader for multiple similar Nodes	XDocument doc = XDocument.Load(response.GetResponseStream());\nXNamespace df = "http://tempuri.org/";\n\nList<payment_history> ph = doc.Descendants(df + "PaymentHistory_ST")\n                 .Select(g => new payment_history\n                 {\n                     tTRANSDATE = (DateTime)g.Element(df + "tTRANSDATE"),\n                     tPAIDTO = (DateTime)g.Element(df + "tPAIDTO"),\n                     dAMOUNT = (double)g.Element(df + "dAMOUNT"),\n                     dBALANCE = (double)g.Element(df + "dBALANCE"),\n                     TRANSKIND = (string)g.Element(df + "TRANSKIND")\n                 }).ToList();	0
28036896	28035183	Custom csv file upload	class Program\n{\n    static void Main(string[] args)\n    {\n        DataTable CarsImportedFromFile = new DataTable();\n        // load data in from CSV\n        List<Car> Cars = new List<Car>();\n\n        foreach (DataRow CurrentRow in CarsImportedFromFile.Rows)\n        {\n            Car MyCar = new Car();\n            MyCar.Model = CurrentRow["Model"].ToString();\n            MyCar.Color = CurrentRow["Color"].ToString();\n            Cars.Add(MyCar);\n        }\n    }\n}\n\nclass Car\n{\n    public string Model { get; set; }\n    public string Color { get; set; }\n}	0
20096230	20095883	Syntax for singleton object	public sealed class BrowserIE\n{\n    static readonly IE _Instance;\n\n    static BrowserIE()\n    {\n        Settings.Instance.MakeNewIeInstanceVisible = false;\n        _Instance = new IE();\n    }\n\n    BrowserIE()\n    {\n    }\n\n    public static IE Instance\n    {\n        get { return _Instance; }\n    }\n}	0
13374099	13373949	Chip8 Emulator - User Input	while (True):\n    processInput()\n    updateCPU()\n    outputGraphics()	0
10307839	10307819	Is there a TryInt() conversion for String values?	int result = 0;\nint.TryParse(stringValue, out result);	0
22608868	22558834	Make rotary knob control	if (this.isKnobRotating == true)\n        {\n            lastValue = Value;\n            this.Cursor = Cursors.Hand;\n            Point p = new Point(e.X, e.Y);\n            int posVal = this.getValueFromPosition(p);\n            Value = posVal;\n            if ((lastValue >= Maximum + radiusLeft - 1) && Value == 0)\n            {\n                numRounds++;\n            }\n            else if (lastValue <= Minimum && (Value == Maximum + radiusLeft - 1))\n            {\n                numRounds--;\n            }\n            finalValue = (Maximum + radiusLeft) * numRounds;\n            result = finalValue + Value;\n        }	0
3572634	3572419	Perform CellContent Click of DataGridView in c#	void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) {\n    CommonClickBehaviour(e.RowIndex);\n}\n\nvoid btnNext_Click(object sender, EventArgs e) {\n    if ((dataGridView.CurrentRow.Index + 1) < dataGridView.Rows.Count)\n        CommonClickBehaviour(dataGridView.CurrentRow.Index + 1);\n}\n\nvoid CommonClickBehaviour(int rowIndex) {\n    // respond to the event or psuedo-event here.\n}	0
22583303	22582769	How to obtain a reference to the Package object within VSPackage MSVS extension?	class MyPackage : Package\n{\n    private static MyPackage _instance;\n    public static MyPackage Instance\n    { \n        get\n        {\n            if(_instance != null)\n                _instance = new MyPackage();\n             return _instance;\n         }\n     }\n}\n\nclass SomeOtherClass\n{\n     void Whatever()\n     {\n           // use MyPackage.Instance\n     }\n}	0
295582	292883	Event Log SecurityException for Web Application?	Run regedt32\nNavigate to the following key:\nHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security\nRight click on this entry and select Permissions\nAdd the ASPNET user\nGive it Read permission\n\n2. Change settings in machine.config file\n\nRun Explorer\nNavigate to WINDOWS or WINNT folder\nOpen Microsoft.NET folder\nOpen Framework folder\nOpen v1.1.4322 folder (folder name may be different, depending on what dotnet version is installed)\nOpen CONFIG folder\nOpen machine.config file using notepad (make a backup of this file first)\nLocate processmodel tag (approx. at line 441)\nLocate userName="machine" (approx. at line 452)\nChange it to userName="SYSTEM"\nSave and close the file\nClose Explorer\n\n3. Restart IIS\n\nRun IISReset	0
11645458	11645400	Save data from textbox before page reload ASP.Net c#	if(!Page.IsPostBack)\n{\n}	0
11806184	11806166	How do I tell when the enter key is pressed in a TextBox?	private void input_KeyDown(object sender, KeyEventArgs e) \n{                        \n    if(e.KeyData == Keys.Enter)   \n    {  \n        MessageBox.Show("Pressed enter.");  \n    }             \n}	0
4951067	4950484	Zoom to Fit to canvas size in C#?	Rectangle c = new Rectangle(0, 0, 200, 100); //Canvas Rectancle (assume 200x100)\nRectangle v = new Rectangle(0, 0, 50, 50); //Viewport Rectangle (assume 50x50)\n\n//The maximum scale width we could use\nfloat maxWidthScale = (float)v.Width / (float)c.Width; \n\n//The maximum scale height we could use\nfloat maxHeightScale = (float)v.Height / (float)c.Height; \n\n//Use the smaller of the 2 scales for the scaling\nfloat scale = Math.Min(maxHeightScale, maxWidthScale);	0
3553749	3553734	How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)	int date = 1012009;\n\nvar month = date / 1000000;\nvar day = (date / 10000) % 100;\nvar year = date % 10000;\n\nvar formatted = new DateTime(year, month, day).ToString();	0
21468942	21468781	Change Key for a SortedList	timedEvQue.Add(3, "First");\ntimedEvQue.Add(7, "Second");\ntimedEvQue.Add(9, "Third");\nint decAmnt = (int)timedEvQue.Keys[0];\ntimedEvQue.RemoveAt(0);\n\nfor (int i = 0; i < timedEvQue.Count; ++i)\n{\n    int oldKey = timedEvQue.Keys[i];\n    string val = timedEvQue[oldKey];\n    int newKey = oldKey - decAmnt;\n    timedEvQue.Remove(oldKey);\n    timedEvQue.Add(newKey, val);\n}\n\ntimedEvQue.Add(5, "Forth");	0
4766165	4765913	populate drop down list with month/year	public static List<string> GetMonths(DateTime StartDate)\n  {\n   List<string> MonthList = new List<string>();\n   DateTime ThisMonth = DateTime.Now.Date;\n\n   while (ThisMonth.Date > StartDate.Date)\n   {\n    MonthList.Add(ThisMonth.ToString("MMMM") + " " + ThisMonth.Year.ToString());\n    ThisMonth = ThisMonth.AddMonths(-1);\n   }\n\n   return MonthList;\n  }	0
7161807	7161730	Is it possible to create a JPG from a Control?	Bitmap bmp = [Control.DrawToBitmap();\n            bmp.Save("", System.Drawing.Imaging.ImageFormat.Jpeg);	0
9194712	9194331	XML Deserialization without specifying XmlRootAttribute	StringReader re = new StringReader(ele.OuterXml);	0
4968813	4968267	How can I remove the border padding on container controls in WinForms?	//HACK: to ensure that the tabpage draws correctly (the border will get \n//  clipped and gradient fill will match correctly with the tabcontrol).\n//  Unfortunately, there is no good way to determine the padding used \n//  on the tabpage.\n//  I would like to use the following below, but GetMargins is busted \n//  in the theming API:\n//VisualStyleRenderer visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);\n//Padding themePadding = visualStyleRenderer.GetMargins(e.Graphics, MarginProperty.ContentMargins);	0
33862278	33862204	How can I have a c# program read each word in a line as a variable?	string sentence = "this is a sentence";\nstring[] parts = sentence.Split(null);	0
22412220	22412121	Concatenate two DataSet Column in dropdownlist DataTextField while Binding	string sqlGetClass = "select [pk_classID], [brachName] + '-' + [classYear] as [classText] from tbl_studentClass";\n...\nddlClass.DataTextField = "classText";	0
6920620	6920605	How to remove white spaces in XML Document in C#	XElement.Parse(str).ToString(SaveOptions.DisableFormatting)	0
19905984	19905860	Add delete option to Kendo Grid	template: '<input type="button" data-id=ID value="Delete" class="popupbutton" id="delButton" onclick="javascript:CheckAck(this);" id="Delete" /><br/>	0
6743698	6743660	Replace 1 line break with 2 line breaks in c#	var result = s.Replace(Environment.NewLine, Environment.NewLine + Environment.NewLine);	0
12044163	12044072	Math.Round with negative parameter	double a = Math.Round( b, 2 );	0
26147457	26115109	WP - Remove feature, but only for "new buyers"	CurrentApp.GetAppReceiptAsync	0
27234268	27233628	Serializing a field with protobuf results in a 0 bytes data file	private bool firstRun = true;\n[ProtoMember(1), DefaultValue(true)]\npublic bool FirstRun {\n    get { return firstRun; }\n    set { firstRun = value; }\n}	0
9092662	9092629	How to remove insignificant zeros from a string?	string str = "000001234";\nstr = str.TrimStart('0');	0
31465099	31464968	ADO.NET example that has no logic, dataGrid fill from uknown data	DROP TABLE IF EXIST Students	0
30900611	30899059	How do I check two different numbers?	if(answer1 >= 2 && answer1 <= 10)\n{\n    answer2 = 1;\n}\nelse\n{\n    answer1 = 1;\n}	0
889193	888399	Updating WebPart Properties using RunWithElevatedPrivileges in MOSS 2007	Random r = new Random(DateTime.Now.DayOfYear + 365 * DateTime.Now.Year);\nr.Next(count);	0
33365308	33365224	Is there a way so simplify this with less code?	Console.WriteLine ("Tn+1 = ({0})Tn +/- ({1})", numberOfTs, AOS);\nConsole.Write ("{0}", term1);\nint calc = term1;\n\nfor(int i = 0; i < 6; i++)\n{\n    calc = calc * numberOfTs + AOS;   \n    Console.Write (", {0}", calc);     \n}	0
16806116	16806015	How to avoiding calling redundancy in context of variable assignment?	void SetField(ref int field, object anotherObjectX)\n{\n  field = doSmth(anotherObjectX...);\n}\n\nSetField(ref object.field1, anotherObject1);\nSetField(ref object.field2, anotherObject2);\nSetField(ref object.field3, anotherObject3);	0
32649684	32178907	Date field is not getting null from GridView	if (string.IsNullOrEmpty(txt_scandt.Text))\n    {\n        cmd.Parameters.AddWithValue("scandt", DBNull.Value);\n    }\n    else\n    {\n        cmd.Parameters.AddWithValue("scandt", Convert.ToDateTime(txt_scandt.Text));\n    }	0
543195	543163	Replacing tags with content in a simple template system	foreach (string tag in values.Keys) {\n        content = r.Replace(content, \n            m => (m.Groups["TagName"].Value == tag ? \n                values[tag].ToString() : m.Value));\n    }	0
14615078	14614926	EF code-first with 2 non-null Foreign Keys in the same table	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Entity<Avaliacao>()\n                .HasRequired(a => a.LivroId)\n                .HasForeignKey(m => a.LivroId)\n                .WillCascadeOnDelete(false);\n\n    modelBuilder.Entity<Avaliacao>()\n                .HasRequired(a => a.AutorId)\n                .HasForeignKey(m => a.AutorId)\n                .WillCascadeOnDelete(false);\n\n}	0
10512317	10502806	Using WebRequest to POST parameters and data to TestFlight	var testflight = new RestClient("http://testflightapp.com");\n\nvar uploadRequest = new RestRequest("api/builds.json", Method.POST);\n\nuploadRequest.AddParameter("api_token", TESTFLIGHT_API_TOKEN);\nuploadRequest.AddParameter("team_token", TESTFLIGHT_TEAM_TOKEN);\nuploadRequest.AddParameter("notes", "autobuild");\n\nuploadRequest.AddFile("file", IPA_PATH);\n\nvar response = testflight.Execute(uploadRequest);\nSystem.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK, \n            "Build not uploaded, testflight returned error " + response.StatusDescription);	0
22927650	22927498	How do I Calculate Possible Savings In The Shopping Cart With Tiered Pricing	// find the current tier pricing of the product\nvar tierProductPrice = product.ProductPrice.FirstOrDefault(p => p.MinQty >= qtyInCart && p.MaxQty <= qtyInCart);\n\nif (tierProductPrice != null)\n{\n var maxTierQty = tierProductPrice.MaxQty;    \n var tierPrice = tierProductPrice.Price;\n\n // current price of the Cart\n var cartPrice = tierPrice * qtyInCart;\n\n // find next min price Tier\n var nextTierProductPrice = product.ProductPrice.FirstOrDefault(p => p.MinQty >= maxTierQty && p.MaxQty <= maxTierQty);\n\n if (nextTierProductPrice  != null)\n {\n  var itemsToAdd = nextTierProductPrice.MinQty - qtyInCart;\n\n  // calculate new price of the cart\n  var newPrice = nextTierProductPrice.MinQty * nextTierProductPrice.Price;\n\n  if (newPrice < cartPrice)\n  {\n   productSaving = new ProductSaving\n   {\n    QtyToAdd = itemsToAdd,\n    Savings = cartPrice - newPrice\n   };\n  }\n } \n}	0
18585011	18584644	How would I go about making a method that reverses the position of 4 variables?	static void Main(string[] args)\n    {\n        int first = 111;\n        int second = 222;\n        int third = 333;\n        int fourth = 444;\n        Console.WriteLine("Numbers in normal order: {0},{1},{2},{3}", first, second, third, fourth);\n        Reverse(ref first, ref second, ref third, ref fourth);\n        Console.WriteLine("Numbers in inverse order: {0},{1},{2},{3}", first, second, third, fourth);\n\n        Console.WriteLine("Press Enter To Exit");\n        Console.ReadLine();\n    }\n\n    public static void Reverse(ref int first1, ref int second2, ref int third3, ref int fourth4)\n    {\n\n        int temp, temp1;\n        temp = first1;\n        first1 = fourth4;\n        temp1 = second2;\n        second2 = third3;\n        third3 = temp1;\n        fourth4 = temp;\n}	0
12014336	12014295	How to test if Webbrowser gets a connection error when navigating to a new URL?	using System;\nusing System.Runtime;\nusing System.Runtime.InteropServices;\n\npublic class InternetCS\n{\n//Creating the extern function...\n[DllImport("wininet.dll")]\nprivate extern static bool InternetGetConnectedState( out int Description, int ReservedValue );\n\n//Creating a function that uses the API function...\npublic static bool IsConnectedToInternet( )\n{\n    int Desc ;\n    return InternetGetConnectedState( out Desc, 0 ) ;\n}\n}	0
9875055	9874971	DTO POCO conversion	public class MyPoco\n{\n    public static implicit operator MyPoco(MyDTO o)\n    {\n        if (o == null) return null;\n        return new MyPoco {\n            SomeAmount = Convert.ToDecimal(o.SomeAmount),\n            SomeBool   = Equals("Y", o.SomeBool     ),\n            Sub1       = o.Sub1,\n            Sub2       = o.Sub2,\n        };\n    }\n    public static implicit operator MyDTO(MyPoco o)\n    {\n        if (o == null) return null;\n        return new MyDTO {\n            SomeAmount = o.SomeAmount.ToString(),\n            SomeBool   = o.SomeBool     ? "Y":"N",\n            Sub1       = o.Sub1,\n            Sub2       = o.Sub2,\n        };\n    }\n    public decimal SomeAmount   { get; set; }\n    public bool SomeBool        { get; set; }\n    public MySubPoco1 Sub1      { get; set; }\n    public MySubPoco2 Sub2      { get; set; }\n}	0
7213495	7204741	Use Protobuf-net to stream large data files as IEnumerable	using (var file = File.Create("Data.bin")) {\n            Serializer.Serialize<IEnumerable<Asset>>(file, Generate(10));\n        }\n\n        using (var file = File.OpenRead("Data.bin")) {\n            var ps = Serializer.DeserializeItems<Asset>(file, PrefixStyle.Base128, 1);\n            int i = ps.Count(); // got them all back :-)\n        }	0
10420372	10126274	Calling a code-behind function from JavaScript that may return another JavaScript function	OnClientClick="Click_Alquilar(); return false"\ninstead of this use\nOnClientClick="return Click_Alquilar();\n\n\nand in javascript\nuse return false;\nin functions like\n\nfunction Click_Alquilar() {\n        if (index == '') {\n            alert("Debe elegir una pel?cula para alquilar");\nreturn false;\n        }\n        else {\n\n            if (confirm("?Quiere alquilar la pel?cula '" + selected.childNodes[2].innerText + "'?")) {\n                __doPostBack('<%= btnAlquilar.UniqueID %>', index);\n            }\n        }\n    }	0
7340801	7339832	Checking a File for matches	string line = "your line to append";\n\n// Read existing lines into list\nList<string> existItems = new List<string>();\n    using (StreamReader sr = new StreamReader(path))\n        while (!sr.EndOfStream)\n            existItems.Add(sr.ReadLine());\n\n// Conditional write new line to file\nif (existItems.Contains(line))\n    using (StreamWriter sw = new StreamWriter(path))\n        sw.WriteLine(line);	0
997752	997747	Accessing the fields of a struct	FieldInfo[] fi = typeof(MyStruct).GetFields(BindingFlags.Public | BindingFlags.Instance);\nforeach (FieldInfo info in fi)\n{\nConsole.WriteLine(info.Name);\n}	0
14353920	14353694	How clear all Pushpin on Map on Windows Phone 7?	foreach (var item in googlemap.Children.ToList())\n{\n    if (item is MapTileLayer) continue;\n    googlemap.Children.Remove(item);\n }	0
30281286	28138304	Reading from / Writing into a Text file in WP8 App	var str = Application.GetResourceStream(new Uri("Sample_File.txt", UriKind.Relative));\n            StreamReader sreader = new StreamReader(str.Stream);\n\n            int x = 0;\n            while(!sreader.EndOfStream)\n            {\n                x = x + 1;//increment the counter\n                if(x==7) //counter value matches the required number\n                {\n                    //perform necessary tasks\n                    break; //if required\n                }\n                sreader.ReadLine();\n            }	0
19877369	19877254	Get ControlToValidate Property From CustomValidator in Code Behind	var validator = (source as CustomValidator);\nstring controlToValidate = validator.ControlToValidate;            \nTextBox txt = validator.NamingContainer.FindControl(controlToValidate) as TextBox;	0
11926258	11926209	Converting 4 bytes (from String format) into one u32. C or C#	string ParseWeirdFormat(string input)\n{\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i < input.Length; i += 2)\n    {\n        string hex = input.Substring(i, 2);\n        int value = Convert.ToInt32(hex, 16);\n        char c = (char)value;\n        sb.Append(c);\n    }\n    return sb.ToString();\n}	0
19229673	19229367	Left Join tables in Linq	foreach (var item in res)\n        {\n            ResultsList rl = new ResultsList();\n\n            if (item.gr != null)\n            {\n                rl.Forename = item.f.Forename;\n                rl.Postcode = item.gr.postcode;\n                rl.ProductName = item.f.ProductName;\n            }\n            else\n            {\n                rl.Forename = item.f.Forename;\n                rl.ProductName = item.f.ProductName;\n\n            }	0
4950414	4949405	SQLDatasource parameters	SqlDataSourceArticole.SelectParameters.Add("@id", id);\nSqlDataSourceArticole.SelectParameters["id"].DefaultValue = id.ToString();	0
29279588	29279517	How to know thread alive not from the outside of thread	Thread t = new Thread(new ThreadStart(ThreadProc));\nt.Start();\nConsole.WriteLine("Still alive: " + t.IsAlive);	0
12890645	12890442	C# linq grouping with same name	var dst = data.FirstOrDefault(x => x.Status == "DST");\nif (dst != null) {\n    foreach (var group in data.Where(x => x != dst && x.Status.StartsWith("DST")) {\n        dst.StatusCount += group.StatusCount;\n    }\n}	0
30786737	30786704	Convert float to raw bits to int in C#	float f = 1234.5678F;\nvar bytes = BitConverter.GetBytes(f);\nvar result = string.Format("0x{0:x}{1:x}{2:x}{3:x}", bytes[0], bytes[1], bytes[2], bytes[3]);	0
4746805	4737233	Getting to certain member using datapager and datagrid	if (loadOperation.TotalEntityCount >= itemCount || !string.IsNullOrEmpty(FilterText))\n{\n    this.ItemCount = loadOperation.TotalEntityCount;\n}\nelse\n{\n    if (!DeleteMember)\n    {\n        pageIndex = (int)((this.ItemCount - loadOperation.TotalEntityCount) / this.PageSize);\n        RaisePropertyChanged("PageIndex");\n    }\n    else\n    {\n        DeleteMember = false;\n        itemCount -= 1;\n    }\n}	0
8863860	8863832	Validate password in asp.net	if ( Membership.ValidateUser( txtUserName.Text, txtPassword.Text ) )\n{\n}	0
766652	766626	Is there a better way in C# to round a DateTime to the nearest 5 seconds?	DateTime now = DateTime.Now;\n  DateTime rounded = new DateTime(((now.Ticks + 25000000) / 50000000) * 50000000);	0
17793986	17793880	Perform manipulation on all elements except last element in a List using Linq	var cars = _db.GetAllCars().Reverse().Select((x, i) => new Car {\n    Name = x.Name + (i == 0 ? "" : ", "),\n    Tires = x.Tires\n}).Reverse();	0
33920367	33919639	Generate multilevel list in Word from C#	Selection.Paragraphs[2].OutlineDemote	0
871062	870770	Automating certain repetive actions in IE based applications via a c# tool?	public void SearchForWatiNOnGoogle()\n{\n    using (IE ie = new IE("http://www.google.com"))\n    {\n        ie.TextField(Find.ByName("q")).TypeText("WatiN");\n        ie.Button(Find.ByName("btnG")).Click();\n    }\n}	0
7508164	7507527	Passing value from child window to parent window using WPF and MVVM pattern	private ObservableCollection<SchoolModel> _schoolList;\npublic ObservableCollection<SchoolModel> SchoolList{\n    get {\n        if ( _schoolList == null )\n            _schoolList = LoadSchoolList();\n        return _schoolList;\n    }\n}	0
32422511	32422257	How to call methods on an ASMX service client	var client = new YourServiceClient(); \nGetLastVehicleResponse getLastVehicleResponse = client.GetLastVehicle();	0
2369708	2369673	How to add List<> to a List<> in asp.net	List<string> initialList = new List<string>();\n// Put whatever you want in the initial list\nList<string> listToAdd = new List<string>();\n// Put whatever you want in the second list\ninitialList.AddRange(listToAdd);	0
15177308	15176337	Search within Datagrid and scroll & select newly added item	var lastRowUpdated = 0;\n        var i = 0;\n\n        if (_assetsavedData.AssetId == -1)\n        {\n            foreach (var rowItem in from object row in RadGridAssetTable.Items select row as AssetLinked)\n            {\n                Debug.WriteLine(rowItem.AssetItems.AssetCommonName);\n\n                if (rowItem.AssetItems.AssetCommonName.Equals(_assetsavedData.AssetCommonName))\n                {\n                    lastRowUpdated = i;\n                    Debug.WriteLine("found at " + i);\n                    break;\n                }\n\n                i++;\n            }\n        }\n        else\n        {\n            lastRowUpdated = RadGridAssetTable.Items.IndexOf(this.RadGridAssetTable.SelectedItem);\n        }	0
2835587	2835374	What event is sent to a Windows Forms window when its button from the taskbar is clicked?	"D:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\spyxx.exe"	0
23017603	23015893	Filtering Datagrid by Category	string myfilter = "categoryA";\n\nvar MyFilteredList = MyList.Where(item => item.category == myfilter);\n\ndatagridView1.DataSource = MyFilteredList;\ndatagridView1.Databind();	0
15426897	15425894	Insert the text in textbox at x, y coordinate postion	private void textBox1_DragDrop(object sender, DragEventArgs e)\n    {\n        TextBox textBox1 = sender as TextBox;\n        Point newPoint = new Point(e.X, e.Y);\n        newPoint = textBox1.PointToClient(newPoint);\n        int index = textBox1.GetCharIndexFromPosition(newPoint);\n\n        object item = listBox1.Items[listBox1.IndexFromPoint(p)];\n\n        if (textBox1.Text == "")\n        {\n            textBox1.Text = item.ToString();\n        }\n        else\n        {\n            var text = textBox1.Text;\n            var lastCharPosition = textBox1.GetPositionFromCharIndex(index);\n            if (lastCharPosition.X < newPoint.X)\n            {\n                text += item.ToString();\n            }\n            else\n            {\n                text = text.Insert(index, item.ToString());\n            }\n\n            textBox1.Text = text;\n        }\n        listBox1.Items.Remove(item);\n    }	0
7507062	7506762	asp.net: change color of listbox items	function colorproblemlist() {\n    ob = document.getElementById('lstProblems');\n    for (var i = 0; i < ob.options.length; i++) {\n        var option = ob.options[i];\n\n         switch(option.value.substr(0,2))\n         {\n            case "AA":\n                option.style.color = "Red";\n            break;\n            case "BB":\n                option.style.color = "Green";\n            break;\n         }\n\n         option.value = option.value.slice(3); //Assumption of 'AA '\n    }\n}	0
5244984	5244529	How to sort a list with two sorting rules?	methods.Sort((y, x) => \n{\n    int sort = x.GetChangingClassesCount().CompareTo(y.GetChangingClassesCount());\n    if (sort == 0)\n        sort = x.GetChangingMethodsCount().CompareTo(y.GetChangingMethodsCount());\n    return sort;\n});	0
11408373	11407992	Capture the mouse right click event of a web browser control	private void webCompareSQL_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n        {\n            if (webCompareSQL.Document != null)\n            {\n                webCompareSQL.Document.ContextMenuShowing += DocMouseClick;\n            }\n        }\n        void DocMouseClick(object sender, HtmlElementEventArgs e)\n        {\n            webCompareSQL.Document.ExecCommand("SelectAll", true, null);\n        }	0
22505796	22397993	MenuControl in asp.net from database	private void getMenu()\n{\n    DataSet ds = objSec.ShowMenu(s_UserId);\n    DataTable dt = ds.Tables[0];\n    AddMenuItems(dt, 0, menu.Items);\n}\n\nprivate void AddMenuItems(DataTable dt, int parentId, MenuItemCollection items)\n{\n    DataRow[] rows = dt.Select("ParentID=" + parentId.ToString());\n    foreach(var dr in rows)\n    {\n        var id = (int) dr["MenuID"];\n        var menuItem = new MenuItem(dr["MenuName"].ToString(), id.ToString(),\n                                    "", dr["URL"].ToString());\n        items.Add(menuItem);\n        // Add subitems\n        AddMenuItems(dt, id, menuItem.ChildItems); \n    }\n}	0
723965	723936	How do you dynamically get a particular method's name in a strongly typed way?	Blah blahInstance = new Blah();\n     System.Action fooFunc = blahInstance.Foo;\n     Console.WriteLine(fooFunc.Method.Name);	0
18593021	18590050	Using Impromptu-Interface to obtain the type of a property	var val = Impromptu.InvokeGet(domain, "fieldName");\nif(val is IMyInterface){\n    // ? profit\n}	0
2975461	2975410	Fastest way in C# to read block of bytes from file and converting to float[]	fixed (byte* bytePtr = data)\n    {\n        fixed (float* floatPtr = samples)\n        {\n            short* rPos = (short*)bytePtr;\n            float* fPos = floatPtr;\n\n            for (int sample = 0; sample < _samplesPerSplit; sample += 1)\n            {\n                *fPos++ = (float)(*rPos++);\n            }\n\n        }\n    }	0
8558457	8558410	Waiting for storyboard animation to finish before changing view in Silverlight 4 using MVVM	public Login(LoginVM vm) {\n    InitializeComponent();\n\n    LoginSuccessStoryboard.Completed += new EventHandler(NavigateToViewAfterAnimation);\n    DataContext = vm;\n    thisVM = vm;\n\n    vm.AnimateLoginSuccess += new EventHandler(vm_AnimateLoginSuccess);\n\n}\n\nprivate void NavigateToViewAfterAnimation(object sender, EventArgs e) {\n   thisVW.NavigateToFirstView();  // Navigates to the first view.\n}	0
5319799	5318718	PDFsharp Line Break	PdfDocument document = new PdfDocument();\n\nPdfPage page = document.AddPage();\nXGraphics gfx = XGraphics.FromPdfPage(page);\nXFont font = new XFont("Times New Roman", 10, XFontStyle.Bold);\nXTextFormatter tf = new XTextFormatter(gfx);\n\nXRect rect = new XRect(40, 100, 250, 220);\ngfx.DrawRectangle(XBrushes.SeaShell, rect);\ntf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft);	0
28473998	28473808	Is there a numericupdown event for value increasing in c#	Decimal OldValue;\nprivate void NumericUpDown1_Click(Object sender, EventArgs e) {\n\n   if (NumericUpDown1.Value>OldValue)\n      {\n         ///value increased, handle accordingly\n      }\n    else if (NumericUpDown1.Value<OldValue)\n      {\n        ///value decreased, handle accordingly\n      }\n    else\n      {\n        return;\n      }\n OldValue=NumericUpDown1.Value;\n}	0
17215463	17215282	reading from a table that I dont know the table structure	SqlConnection con = new SqlConnection(conString);\n        con.Open();\n        SqlCommand command = new SqlCommand("select * from vw_Haber_Baslik_Ozet", con);\n        SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, con);\n        DataSet ds = new DataSet();\n        adapter.Fill(ds);\n        foreach (DataColumn dc in ds.Tables[0].Columns)\n        {\n            String colName = dc.ColumnName;\n            String valueOfCol1 = ds.Tables[0].Rows[0][dc.ColumnName].ToString();\n        }\n        con.Close();	0
11635821	11617616	Creating Dynamic Locks at Runtime in ASP.NET	private static Object _lock = new Object();	0
25661138	25660973	Passing command line arguments into WPF C# application and accessing its value	//App\npublic partial class App : Application\n{\n    public string CustomerCode { get; set; }\n    protected override void OnStartup(StartupEventArgs e)\n    {\n\n        this.CustomerCode=e.Args[0].ToString();\n        base.OnStartup(e);\n    }\n}\n\n\n//MainWindow\n public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        var hereIsMyCode=(Application.Current as App).CustomerCode;\n        InitializeComponent();\n    }\n}	0
28652156	28651567	Enter various data types in a text box and input them into an Object array	List<object> items = new List<object>();\nstring data = "a, 1, 1.5, b";\n\nRegex.Matches(data, "[^,]+") // Get each object without a comma over the line.\n     .OfType<Match>()\n     .Select (mt => mt.ToString().Trim()) // Remove any whitespace (if any)\n     .ToList()\n     .ForEach(itm => items.Add(Regex.IsMatch(itm, "[a-zA-Z]")  ?          // Is it\n                                            (object) itm :                // a string\n                                            (object) Double.Parse(itm))); // a number\n\nConsole.WriteLine ( string.Join( " | ", items.Select (obj => obj.ToString())));\n// Writes:\n// a | 1 | 1.5 |  b\n\nConsole.WriteLine ( string.Join( ", ", items.Select (obj => obj.GetType())));\n// Writes:\n// System.String, System.Double, System.Double, System.String	0
32644612	32644302	Get word in betwen first and last of a string	string substring=str.Substring(3,str.Lenghth-6)	0
11350038	11350008	How to get .exe file version number from file path	var versionInfo = FileVersionInfo.GetVersionInfo(pathToExe);\nstring version = versionInfo.ProductVersion; // Will typically return "1.0.0" in your case	0
3183667	3183628	SubSonic SimpleRepository Find Method with nullable DateTime	.Where(fieldName).IsNull	0
4243871	4243816	Regex.Replace with compiled option in a cycle	Regex theRegex = new Regex(@"\p{Z}", RegexOptions.Compiled);\nforeach (String StrTmp in SomeList)\n  string replacementString = theRegex.Replace(StrTmp, "");	0
6262117	6262025	Obtaining IP Address of Callback Channel in WCF	OperationContext context = OperationContext.Current;\nMessageProperties messageProperties = context.IncomingMessageProperties;\nRemoteEndpointMessageProperty endpointProperty =\n                messageProperties[RemoteEndpointMessageProperty.Name]\n                as RemoteEndpointMessageProperty;\n\nvar address = endpointProperty.Address;	0
21393139	21393024	Comparing Strings in .NET	var test1 = System.Text.Encoding.UTF8.GetBytes(object.ID);\nvar test2 = System.Text.Encoding.UTF8.GetBytes("8jh0086s");	0
18630563	18622847	Parsing JSON from site to Windows Phone	RootObject root = JsonConvert.DeserializeObject<RootObject>(data);	0
14989535	14941954	Transfering frames of a Video over Socket	char shmName[MAX_PATH+1];\nsprintf( shmName, "shmVideo_%s", name );\nshmName[MAX_PATH] = '\0';\n_hMap =\n   CreateFileMapping(\n      INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, size, shmName );\nif( _hMap == 0 ) {\n   throw OSException( __FILE__, __LINE__ );\n}\n_owner = ( GetLastError() != ERROR_ALREADY_EXISTS );\n_mutex = Mutex::getMutex( name );\nSynchronize sync( *_mutex );\n_data = (char *)MapViewOfFile( _hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0 );\nif( _data == 0 ) {\n   throw OSException( __FILE__, __LINE__ );\n}	0
3460624	3460503	How to read a file from a URI using StreamReader?	WebRequest request=WebRequest.Create(url);\n  request.Timeout=30*60*1000;\n  request.UseDefaultCredentials=true;\n  request.Proxy.Credentials=request.Credentials;\n  WebResponse response=(WebResponse)request.GetResponse();\n  using (Stream s=response.GetResponseStream())\n    ...	0
29908005	29907913	get a value based on a Switch Statement	public int NumCandyBars (string candyBar)\n    {\n        int retval = 0;\n        switch (candyBar)\n        {\n            case "twix":\n                retval = _numTwix;\n                break;\n            case "snickers":\n                retval =_numSnickers;\n                break;\n            case "kitkat":\n                retval = _numKitKat;\n                break;\n        }\n        return retval;\n    }	0
11204809	11204771	SQLDataReader how to check for null column values?	for(int i=0; i<myarray.Length;i++){\n    if(reader.IsDBNull(i)){\n        myarray[i] = "";\n    }\n    else\n    {\n        myarray[i] = reader[i];\n\n    }\n}	0
14532443	14532339	Create ToolStripMenuItem with checked items	this.TopMost = alwaysOnTopToolStripMenuItem.Checked;	0
28921427	28920330	Call a method on ShellViewModell from ModalDialog	public void ShowConnection(){\n  var connvm = new ConnectionViewModel();\n\n   IDictionary settings = new Dictionary();\n            settings["WindowStartupLocation"] = WindowStartupLocation.CenterScreen;\n  //Does something with the connvm object, which allows \n  //continued process once dialog is closed.\n  windowManager.ShowDialog(connvm, null,settings);  \n\n  if( connvm != null && connvm.Connected){\n     ShowTables();\n  }\n}	0
4706842	4706796	C# Interface with method that returns an implementation of multiple interfaces	Contract.Ensures(Contract.Result<object>() is IEnumerable<string>);\nContract.Ensures(Contract.Result<object>() is INotifyCollectionChanged);	0
3983639	3983616	Get found items as list from regex	var n = (from Match match in m\n         select match.Value).ToList()	0
21764365	21763942	List of datetimes in MVC-project	return View( ((MyListOfDates != null) && (MyListOfDates.Any()) ?\n              MyListOfDates.FirstOrDefault(dtTime=> dtTime != DateTime.MinValue) :\n              DateTime.MinValue);	0
13193472	13193078	Changing Connection string from one database to another in c#.net	OleDbConnection connection = new OleDbConnection("old conn string>");                \n connection.Open();\n //do somthing with db 1\n connection.Close();\n\n //Change the connection string\n connection.ConnectionString="<new connection string>";\n\n connection.Open();\n //do somthing with db 2\n connection.Close();	0
9681260	9681102	How to Configure IIS Path for localhost	virtual path	0
21539200	21539187	cannot add integers	textBoxAns.Text = (val1 + val2).ToString();	0
21610050	21609956	Append Number to a Name (string)	Match match = Regex.Match(name, @"^(.*)-([0-9]+)$", RegexOptions.IgnoreCase);\nif (match.Success)\n{\n        return string.Format("{0}-{1}",match.Groups[1].Value, match.Groups[2].Value+ 1);\n} else {\n        return string.Format("{0}-{1}",name,count);\n    }	0
34307509	34307331	How to get string array method data into list or data set?	internal static class Program\n    {\n        private static void Main(string[] args)\n        {\n            string[] array = new [] { "Hi", "Hello"};\n            DataSet dataSet = array.AssignToDataSet();\n        }    \n\n\n        private static DataSet AssignToDataSet(this string[] myArray)\n        {\n            DataSet dataSet = new DataSet();\n            DataTable dataTable = dataSet.Tables.Add();\n            dataTable.Columns.Add();\n            Array.ForEach(myArray, c => dataTable.Rows.Add()[0] = c);\n            return dataSet;\n        }\n    }	0
22128939	22128879	not able to change selected value in dropdown list for current academic year	ListItem liId = ddlAcYear.Items.FindByValue(dr.ItemArray[0].ToString());\n if (liId != null) {\n     liId.Selected = true;\n }	0
11891151	11890909	How to Get Files From A Directory That's Open for Directory Listing?	WebRequest request = WebRequest.Create("http://yourwebsite/yourwebdirectory/");\n             var webResponse=request.GetResponse();\n             Stream dataStream = webResponse.GetResponseStream(); \n             StreamReader reader = new StreamReader(dataStream); \n             string responseFromServer = reader.ReadToEnd(); \n             Console.WriteLine(responseFromServer); \n             reader.Close();\n             webResponse.Close();	0
5998195	5998165	Looking to find how to add resize button	ResizeMode="CanResizeWithGrip"	0
4965643	4962571	combining DatePicker and TimePicker	DateTime date = DatePicker.Value.Date + TimePicker.Value.TimeOfDay;	0
19987783	19987090	Parse XML (Array with Index) to List<Object>	from element in xdoc.Descendants("fieldlist")\nselect new { \n    Name = element.Elements("field")\n                  .Single(e => e.Attribute("index").Value == "name")\n                  .Value,\n    ...	0
17540987	17540937	delaying read from the telnet connection	Thread.Sleep(8000);\nstring out_string = Encoding.Default.GetString(ReadFully(readStream,0));	0
29338525	29338463	Make css styles inline into html elements	string htmlSource = File.ReadAllText(@"C:\Workspace\testmail.html");\n\n var result = PreMailer.MoveCssInline(htmlSource);\n\n result.Html         // Resultant HTML, with CSS in-lined.\n result.Warnings     // string[] of any warnings that occurred during processing.	0
7735317	7718415	access IObservable inside same IObservable subscription	var list = new List<int> { 1, 2, 3 };\nvar obs = list.ToObservable().Select(i => new Tuple<int,IObservable<int>>(i,list.ToObservable()));\n\nobs.SubscribeOn(Scheduler.NewThread).Subscribe(t => {\n  Console.WriteLine(t.Item1);\n  SaveItems(t.Item2);\n});	0
34067531	34067530	Appending 'hd' parameter to redirectUrl ASP.NET 5 Identity 3	app.UseGoogleAuthentication(options => {\n    options.ClientId = Configuration["Authentication:Google:ClientId"];\n    options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];\n\n    options.Events = new OAuthEvents()\n    {\n        OnRedirectToAuthorizationEndpoint = context =>\n        {\n            context.Response.Redirect(context.RedirectUri + "&hd=contoso.com");\n            return Task.FromResult(0);\n        }\n    };\n});	0
5848815	5848782	Uploading a file using fileupload control in asp.net	FileUpload1.SaveAs(Server.MapPath("~/AppFolderName/" + FileName));	0
8585067	8584624	Using IDictionary with Json?	JavaScriptSerializer seri = new JavaScriptSerializer();\n            var items = seri.Deserialize<Dictionary<string, object>>(jsonData);\n        // As data in JSON is array get it deserialize as ArrayList of Dictionary<string,object>\n            var dataArray =  items["data"] as ArrayList;    \n        // Each item in array list contain key value pair of name and id\n            foreach (Dictionary<string,object> item in dataArray)\n                {\n        //Read Item\n                foreach (KeyValuePair<string, object> detailItem in item)\n                    {\n                    Console.WriteLine(detailItem.Key + " - " + detailItem.Value);\n                    }\n                Console.WriteLine("-------------------------------------------");\n        // Read Item\n                }	0
9279772	9279197	Copying data from SQL CE 3.0 to SQL CE 3.5	SqlCeEngine engine = new SqlCeEngine(String.Format("Data Source={0};Password={1};Persist Security Info=True",dataBasepath,password));\nengine.Upgrade();	0
8653976	8653930	Convert datetime to Time and show in a label in GridView	string sDateTime = DateTime.Now.ToString("MMMM dd") + " at " +\n                   DateTime.Now.ToString("hh:mm tt");	0
15227418	15227357	Retrieve Users with specific email address	Membership.FindUsersByEmail()	0
4937276	4936901	How can I retrieve column descriptions from an access database in C#?	catDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _\n"Data Source=" & CurrentProject.FullName\n\nSet tbl = catDB.Tables("New")\n\nSet fld = tbl.Columns("Test")\nDebug.Print fld.Properties("Description")	0
989297	989281	How can I programmatically limit my program's CPU usage to below 70%?	Process.PriorityClass	0
21437489	21437434	List take certain items skip remaning	int itemsToSkip = batch * i;\nmailAccounts.Skip(itemsToSkip).Take(batch);	0
1186652	1186575	Using WM_Close in c#	[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]\nstatic extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);\n\n[DllImport("user32.dll", CharSet = CharSet.Auto)]\nstatic extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\nstatic uint WM_CLOSE = 0x10;\n\nstatic bool CloseWindow(IntPtr hWnd)\n{\n    SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);\n    return true;\n}\n\n\nstatic void Main()\n{\n    IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");\n    bool ret = CloseWindow(hWnd);\n}	0
1992383	1992311	Counting occurrences of a string in an array and then removing duplicates	var notes = new []{ "Do", "Fa", "La", "So", "Mi", "Do", "Re" };\n\nvar counts = from note in notes \n             group note by note into g\n             select new { Note = g.Key, Count = g.Count() }\n\nforeach(var count in counts)\n    Console.WriteLine("Note {0} occurs {1} times.", count.Note, count.Count);	0
32120006	32095295	How to make custom shorcut key as ctrl+?(? is turkish char) for a menu item in c#	private void mniOpenW_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Control && e.KeyValue == 220)//this is keyvalue of '??' key.\n        {\n            mniOpenW.PerformClick();\n        }\n    }	0
2019189	2019175	How to programmatically retrieve smtp server details from web.config	Configuration configurationFile = WebConfigurationManager\n    .OpenWebConfiguration("~/web.config");\nMailSettingsSectionGroup mailSettings = configurationFile\n    .GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;\nif (mailSettings != null)\n{\n    int port = mailSettings.Smtp.Network.Port;\n    string host = mailSettings.Smtp.Network.Host;\n    string password = mailSettings.Smtp.Network.Password;\n    string username = mailSettings.Smtp.Network.UserName;\n}	0
6169529	6160629	returning byte array from stored procedure using linq to sql	using(var context = new MyDbDataContext())\n{\n    var byte_array = context.selecttempimage(user_id).SingleOrDefault();\n    //...do something with byte_array\n}	0
33308940	33308107	Insert into DB fails while encrypting the password in asp.net mvc	db.UserLogins.ExecuteSqlCommand(\n  string.Format("insert into Userlogin values('{0}','{1}','{2}')",\n    userlogin.UserName, userlogin.Email, EncodedPassowrd));	0
5071911	5071861	Gridview to Excel	GridView1.AutoGenerateDeleteButton = false;\n    GridView1.DataBind(); \n    GridView1.RenderControl(htmlWrite);\n    Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");	0
2194098	2194065	Is an array valid for vertex element data for programmable graphics pipline?	public struct Vertex\n{\n    public fixed float array[4];\n\n    public Vertex(float x, float, y, float z, float w)\n    { \n         array[0] = x; array[1] = y; array[2] = z; array[3] = w;\n    }\n}	0
2989993	2989536	.NET compact framework - where to put files so that they are accessible to emulator	Path.Combine(\n  Path.GetDirectoryName(\n   Assembly.GetExecutingAssembly().GetName().CodeBase\n  ), "users.xml");	0
8568023	8567992	How to modify method arguments using PostSharp?	[Serializable]\npublic class MyAspect : MethodInterceptionAspect\n{\n    public override void OnInvoke(MethodInterceptionArgs args)\n    {\n        string input = (string)args.Arguments[0];\n\n        if (input.Equals("123"))\n        {\n            args.Arguments.SetArgument(0, " 456");\n        }\n\n        args.Proceed();\n    }       \n}	0
7552329	7534150	Only count a download once it's served	Response.Buffer = false;\nResponse.TransmitFile("Tree.jpg");\nResponse.Close();\n// logging here	0
13399030	13398871	Opening a new Window Codebehind ASP.net	protected void Page_Load(object sender, EventArgs e)\n{\n    byte[] buffer = null;\n    buffer = File.ReadAllBytes("C:\\myfile.pdf");\n    //save file to somewhere on server, for example in a folder called PDFs inside your application's root folder\n    string newFilepath = Server.MapPath("~/PDFs/uploadedPDF.pdf");\n    System.IO.FileStream savedPDF = File.Create(newFilepath);\n    file.Write(buffer, 0, buffer.Length);\n    file.Close();\n\n    //register some javascript to open the new window\n    Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenPDFScript", "window.open(\"/PDFs/uploadedPDF.pdf\");", true);\n}	0
10895274	10895200	query base object based on a non related entity list using entity framework	_context.RequestBases\n.Where(rb => _context.Workflowconfiguration\n    .Any(wc => wc.Approvers\n        .Any(a => a.StepName == rb.CurrentStatus)));	0
18091238	18047395	C# Future implementation with time out detection	public Future(FutureDelegate<T> del, int timeout_ms)\n    {\n        Del = del;\n        Result = del.BeginInvoke(null, null);\n\n        if (!Result.IsCompleted)\n        {\n            if (!Result.AsyncWaitHandle.WaitOne(timeout_ms))\n            {\n                HasTimedOut = true;\n            }\n            else\n            {\n                HasTimedOut = false;\n            }\n        }\n\n        PValue = Del.EndInvoke(Result);             \n    }	0
7188474	7188335	Detect SQL Server 2008 R2	public static class MyClass\n    {\n        public static void Main()\n        {\n            ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");\n            foreach (ManagementObject mo in mos.Get())\n            {\n                Console.WriteLine(mo["Name"]);\n            }\n\n\n        }\n    }	0
4014770	4014692	C# and Pervasive, find the type of data in a column	PsqlDataReader.GetFieldType(PsqlDataReader.GetOrdinal("ColumnName"));	0
8655630	8655532	tokenize string to string array	string pattern = @"[0-9]{1}[a-z]{1}";            \n        var regexp = new System.Text.RegularExpressions.Regex(pattern);\n\n        var matches = regexp.Matches("2x3y5z");            \n\n        foreach (var match in matches)\n        {\n            Debug.WriteLine(match);\n        }	0
8321757	8321678	Creating abstract class with 'where' constraint that also implements interfaces	public abstract class BaseCollectionModel<T> : ObservableCollection<T>, IXMLEntity\nwhere T : IXMLEntity\n{\n\n}	0
31012500	31012150	Returning Enumeration Values From A Method	static ShotgunOption GetOptionFromUser()\n    {\n        char menuItem;\n        DisplayMenu();\n        Console.WriteLine("Please Select A Option");\n        menuItem = char.ToUpper(char.Parse(Console.ReadLine()));\n        while(true)\n        {\n            switch(menuItem)\n            {\n                case 'S': return ShotgunOption.Shoot;\n                case 'P': return ShotgunOption.Shield;\n                case 'R': return ShotgunOption.Reload;\n                case 'X': return ShotgunOption.Exit;\n                default:\n                    Console.WriteLine("Error - Invalid menu item");\n                    DisplayMenu();\n                    menuItem = char.ToUpper(char.Parse(Console.ReadLine()));\n            }\n        }\n\n        return ShotgunOption.Exit; // to keep compiler happy\n    }	0
21203227	21202851	Comobox selected value not correctly getting in WPF?	if (comboBox1.SelectedItem != null)\n\n    {\n\n    ComboBoxItem cbItem = (ComboBoxItem) comboBox1.SelectedItem;\n\n    MessageBox.Show(cbItem.Content.ToString());\n\n    }	0
20433346	20430457	Opening the second Wpf window	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        NavigationWindow navWin = new NavigationWindow();\n        navWin.Content = new UserControl1();\n        navWin.ShowsNavigationUI = false;\n        navWin.Show();\n    }\n}	0
25557221	25556999	C# Sendkeys how to send tilde without sending enter	SendKeys.SendWait("{~}");	0
13260286	13260131	How to parse XML header and nested sections using LINQ	var orders = doc.Descendants("Order").Select(x => new\n    {\n        OrderNumber = (int)x.Element("OrderNumber"),\n        ShipAddress = (string)x.Element("ShipAddress"),\n        ShipCity = (string)x.Element("ShipCity"),\n        ShipState = (string)x.Element("ShipState"),\n        ClientId = (int)x.Ancestors("Client").First().Element("ClientId"),\n        SettingId = (int)doc.Descendants("SettingId").First(),\n    });	0
16234779	16234688	Appropriate data structure for fast searching "between" pairs of longs	Dictionary<long, Guid?>	0
1137108	1137083	c# How do I select a list box item when I have the value name in a string?	int index = listBox1.FindString("item3");\n// Determine if a valid index is returned. Select the item if it is valid.\nif (index != -1)\n     listBox1.SetSelected(index,true);	0
31785532	31783693	Send string with Eventaggregator	public class SourceViewModel\n{\n    public string SourceText { ... }\n    // Publish SendString event on SourceText changes...\n}\n\npublic class DestinationViewModel\n{\n    private IEventAggregator _aggregator;\n    // Bind DestinationText to your destination text box...\n    public string DestinationText { .. }\n\n    public DestinationViewModel(IEventAggregator eventAggregator)\n    {\n        ...\n      _aggregator.GetEvent<SendStringEvent>().Subscribe(StringAction2,\n        ThreadOption.UIThread, false, i => DestinationText = i.Text);\n    }    \n}	0
29791300	29790592	How to attach a PDF document to SOAP and send it from windows client to WCF server in C# .net?	private string EncodeFileAsBase64(string inputFileName)\n    {\n        byte[] binaryData;\n        using (System.IO.FileStream inFile = new System.IO.FileStream(inputFileName,\n                                   System.IO.FileMode.Open,\n                                   System.IO.FileAccess.Read))\n        {\n            binaryData = new Byte[inFile.Length];\n            long bytesRead = inFile.Read(binaryData, 0,\n                                 (int)inFile.Length);\n            inFile.Close();\n        }\n\n        // Convert the binary input into Base64 UUEncoded output. \n        string base64String;\n        base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);\n        return base64String;\n    }	0
25746583	25746521	Dismiss keyboard on rotate	[self.view endEditing:YES];	0
9438515	9438480	Compiling HTML body for mail in c#	mail.IsBodyHTML = true	0
22588035	22587994	Regular Expressions for identifying harvard citations	\(([\w\&\.\s]+,\s\d{4}(;\s+[\w\&\.\s]+,\s\d{4})*)\)	0
5825417	5825383	XML Comments in C# don't show summary they show xml	/// <summary>My summary.</summary>	0
30117065	30018284	Query options for getting single value with the specified key in ASP.NET OData Controller	SingleResult result = SingleResult.Create(TestModels.AsQueryable());	0
20483512	20483219	How to be sure you sent proper decimal value?	decimal.Parse("20.000", \n    System.Globalization.CultureInfo.InvariantCulture.NumberFormat);	0
10625260	10584385	How do I initialize the MvvmCross framework without a splash Activity?	var setup = MvxAndroidSetupSingleton.GetOrCreateSetup(this.ApplicationContext);\nsetup.EnsureInitialized(this.GetType());	0
31426856	31424210	Handling dynamically generated elements in selenium webdriver via C#	//div[contains(@class, 'j-Ta-pb')]	0
22201109	22200895	Keyword used in Select From SQL Statement (C# OleDbDataAdapter)	[KeywordTableName]	0
18186172	18185864	Take the info from json file c#	// Loop through all instances of ?q=\nint i = 0;\nwhile ((i = s.IndexOf("?q=", i)) != -1)\n{\n\n    // Print out the substring. Here : windows8\n    Console.WriteLine(s.Substring(i));\n\n    // Increment the index.\n    i++;\n}	0
7335188	7335137	Removing Text with an Invoke?	private void DoStuff(string TextIWouldBeRemoving)\n{        \n    if (listboxname.InvokeRequired)\n    {\n        listboxname.Invoke(DoStuff, new object[] { TextIWouldBeRemoving )};   \n    }\n    else\n    {\n        // Actually remove the text here!\n    }\n}	0
2994120	2994014	C# getting mouse coordinates from a tab page when selected	public partial class Form1 : Form {\n    public Form1() {\n        InitializeComponent();\n        tabPage2.MouseMove += new MouseEventHandler(tabPage2_MouseMove);\n    }\n    private void tabPage2_MouseMove(object sender, MouseEventArgs e) {\n        Console.WriteLine(e.Location.ToString());\n    }\n}	0
5501059	5500981	how to replace some character b/w strings in c#?	yourString.Split("-").Select(s => Regex.Replace(s, "^5$", "2")).Aggregate((a,b) => a + "-" + b);	0
9672366	9632051	How can I use a sql reserved keyword in the name of a property in an entity framework data context?	Update-Package EntityFramework	0
4073576	4073540	Removing Accessors from an Object	IReadonlyPerson\n{\n  string Name { get; }\n  string Age { get; }\n}	0
4120445	4120400	Setting DataSource of a DataGridView control. Am I doing this right? C#	public string employeeNo { get; set; }\n    public string name { get; set; }	0
11396984	11384838	AllFramesReady Repeating Loop	for (int i = 0; i < Doctor_ShoulderX.Count; i++)	0
20353369	20352663	Linking string from Web Form to Web Service	protected void Button1_Click(object sender, EventArgs e)\n    {\n        if (!String.IsNullOrEmpty(TextBox1.Text))\n        {\n            localhost.Service obj = new localhost.Service();\n            TextBox1.Text = obj.Translate(TextBox1.Text);\n        }\n    }	0
5158729	5158659	Sort One Array from Another array order?	var results = listTwo.Intersect(listOne).Union(listOne);\nforeach (string r in results)\n{\n    Console.WriteLine(r);\n}	0
22767177	21787656	More Extensive Body for Gmail Atom Feed	using (var ic = new AE.Net.Mail.ImapClient("imap.gmail.com", "email", "pass", AE.Net.Mail.AuthMethods.Login, 993, true))\n{\n    ic.SelectMailbox("INBOX");\n    MailMessage[] mm = ic.GetMessages(0, 10);\n    // at this point you can download the messages\n}	0
15657318	15657209	Get a String from XamlWriter.Save(object obj, Stream stream)	StringWriter.ToString()	0
17763733	17763570	Change a File's ACL to Allow Full Access for Everyone	// Read the current ACL details for the file\nvar fileSecurity = File.GetAccessControl(fileName);\n\n// Create a new rule set, based on "Everyone"\nvar fileAccessRule = new FileSystemAccessRule(new NTAccount("", "Everyone"),\n      FileSystemRights.FullControl, \n      AccessControlType.Allow);\n\n// Append the new rule set to the file\nfileSecurity.AddAccessRule(fileAccessRule);\n\n// And persist it to the filesystem\nFile.SetAccessControl(fileName, fileSecurity);	0
23875410	23871865	Passing a StorageFile to OnNavigatedTo in a C# WinRT app	protected override async void OnNavigatedTo(NavigationEventArgs e)\n{\n    var file = e.Parameter as Windows.Storage.StorageFile;\n    if (file!=null)\n    {\n        ...\n    }\n}	0
32316113	32316001	Selecting rows in a DBSet with Entity Framework	workers.SingleOrDerfault(x => x.WorkerId == WorkerId);	0
13458700	13458642	JS bundles do not render without EnableOptimization set to true	public class BundleConfig\n{\n    public static void RegisterBundles(BundleCollection bundles)\n    {\n        ScriptBundle scriptBundle = new ScriptBundle("~/js");\n        string[] scriptArray =\n        {\n            "~/content/plugins/jquery/jquery-1.8.2.js",\n            "~/content/plugins/jquery/jquery-ui-1.9.0.js",\n            "~/content/plugins/jquery/jquery.validate.js",\n            "~/content/plugins/jquery/jquery.validate.unobtrusive.js",\n            "~/content/plugins/bootstrap/js/bootstrap.js",\n        };\n        scriptBundle.Include(scriptArray);\n        scriptBundle.IncludeDirectory("~/content/js", "*.js");\n        bundles.Add(scriptBundle);\n    }\n}	0
25758071	25756479	How to call an Async API in a synchronous fashion?	// current thread is the UI thread\n// so create/use a Task to wait for the call\nvar task = Task.Factory.StartNew( () => { DoJobAsync().Wait()});	0
13246004	13245741	Unique Id of a program in runtime	var id = Guid.NewId();	0
26729531	26729309	Binding WPF return default string	Binding="{Binding\n    Path=Message.Info.InfoName,\n    Mode=OneWay,\n    FallbackValue=No Information available}"	0
18928960	18918728	Query String and Custom Controls in asp.net	imageButton.ImageUrl = "~/Uploads/" + fi.Name;	0
24934305	24932917	How to build this json using .net C#?	new JProperty("conditions", new JArray((JContainer)new JArray("Language", "IN", new JArray(IsEnglish ? "en" : "es"))))	0
5883012	5882959	Methods referenced by other assemblies	var assemblyResolver = new DefaultAssemblyResolver();\nassemblyResolver.AddSearchDirectory(...);\nvar assemblyDefinition = assemblyResolver.Resolve(\n                             AssemblyNameReference.Parse(fullName));\nforeach(ModuleDefinition module in assemblyDefinition)\n{\n    foreach(TypeDefinition type in module.Types)\n    {\n        foreach(MethodDefinition method in type.Methods)\n        {\n            foreach(Instruction instruction in method.Body.Instructions)\n            {\n                // Analyze it - the hard part ;-)\n            }\n        }\n    }\n}	0
5660602	5633189	Facebook C# SDK - Posting message to a users wall	dataTest.from = senderFacebookId;	0
32624643	32624529	c# how can I read String of double correctly despite the number Format?	CultureInfo.Invariant	0
12097341	12096866	Replace the MS Outlook html source string using regex?	Regex.Replace(text, @"src=""cid:(?<FileName>[^@]+)@[^""]*""", @"src=""Attachments\${FileName}""",\n    RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);\nRegex.Replace(x, @"alt=""[^.]*cid:(?<FileName>[^@]+)@[^""]*""", @"alt=""${FileName}""",\n    RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);	0
11174204	11174068	Need help parsing XML feed in Windows Phone	XmlReader xmlReader = XmlReader.Create("http://webservices.nextbus.com/service/publicXMLFeed?   command=routeConfig&a=sf-muni&r=N");\nList<string> aTitle= new List<string>();\n\n// Add as many as attributes you have in your "stop" element\n\nwhile (xmlReader.Read())\n{\n //keep reading until we see your element\n if (xmlReader.Name.Equals("stop") && (xmlReader.NodeType == XmlNodeType.Element))\n {\n   string title = xmlReader.GetAttribute("title");\n   aTitle.Add(title);\n\n   // Add code for all other attribute you would want to store in list.\n  }\n}	0
25442945	25430885	Method to work out first day of financial year based on year parameter	public static DateTime FinancialPeriods(string financialYear, bool end)\n{\n    string startFinancialYear;\n    string endFinancialYear;\n    DateTime startOfFinancialYear;\n    DateTime endOfFinancialYear;\n\n    startFinancialYear = financialYear.Substring(0, 4);\n    endFinancialYear = financialYear.Substring(5, 4);\n\n    startOfFinancialYear = new DateTime(int.Parse(startFinancialYear), 4, 1);\n    endOfFinancialYear = new DateTime(int.Parse(endFinancialYear), 4, 1).AddDays(-1);\n\n    if (end == false)\n    {\n        return startOfFinancialYear;\n    }\n\n    else\n    {\n        return endOfFinancialYear;\n    }   \n}	0
6825674	6825651	How to get DropDownList Value for a random Index?	string value = DropDownList1.Items[8].Value;	0
27448487	27448455	Define a List of Objects in C#	List<Item> items = new List<Item>()\n{\n    new Item{ Id=1, Name="Ball", Description="Hello" },\n    new Item{ Id=2, Name="Hat", Description="Test" }\n}	0
25939996	25939762	How to display multiple max columns from the max ID	create table #Something\n(\n    LeaveID int\n    , EmployeeName varchar(25)\n    , DateOff date\n    , TimeBegin time\n    , TimeEnd time\n    , PayPeriod date\n    , Hours numeric(9,2)\n    , LeaveCode varchar(50)\n)\n\ninsert #Something\nselect 88, 'Polland, Sean', '2014-09-08', '08:30AM', '11:00AM', '2014-09-13', 2.5, 'P (Personal Leave Scheduled*)' union all\nselect 112, 'Polland, Sean', '2014-09-24', null, null, '2014-09-27', 8, 'P (Personal Leave Scheduled*)' union all\nselect 121, 'Polland, Sean', '2014-09-25', null, null, '2014-09-27', 8, 'P (Personal Leave Scheduled*)' union all\nselect 121, 'Polland, Sean', '2014-09-26', null, null, '2014-09-27', 8, 'P (Personal Leave Scheduled*)';\n\nwith SortedResults as\n(\n    select *\n     , DENSE_RANK() over(partition by PayPeriod order by LeaveID desc) as GroupDepth\n    from #Something\n)\n\nselect *\nfrom SortedResults\nwhere GroupDepth = 1\n\ndrop table #Something	0
32885587	32885487	Json Deserialise Issue	[JsonProperty(PropertyName = "When opening the account which of these applied?")]\npublic List<string> Whenopeningtheaccountwhichoftheseapplied { get; set; }	0
32200509	32162191	How can I categorize properties of my control to appear in appropriate sections in Blend and Visual studio designer?	namespace System.ComponentModel\n{\n    [AttributeUsage(AttributeTargets.All)]\n    public class CategoryAttribute : Attribute\n    {\n        public CategoryAttribute(string category)\n        {\n            Category = category;\n        }\n\n        public string Category { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            if (obj == this)\n                return true;\n\n            var other = obj as CategoryAttribute;\n            return other != null && other.Category == Category;\n        }\n\n        public override int GetHashCode()\n        {\n            return Category.GetHashCode();\n        }\n    }\n}	0
11932388	11931960	Quickly calculating the 'dirtied' areas between two similar images	int size = 1920 * 1080 * 3;\n        byte[] image1 = new byte[size];\n        byte[] image2 = new byte[size];\n        byte[] diff = new byte[size];\n\n        var sw = new System.Diagnostics.Stopwatch();\n        sw.Start();\n        for (int i = 0; i < size; i++)\n        {\n            diff[i] = (byte) (image1[i] - image1[i]);\n        }\n        sw.Stop();       \n        Console.WriteLine(sw.ElapsedMilliseconds);	0
3983560	3983544	Programatically set OnSelectedIndexChanged for a ddl	DropDownList1.SelectedIndexChanged += new EventHandler ( funTimes );	0
23156869	23156197	format a number with dots and decimals in C#	string xyz = "1234567";\n\n        // Gets a NumberFormatInfo associated with the en-US culture.\n        NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;\n\n        nfi.CurrencyDecimalSeparator = ",";\n        nfi.CurrencyGroupSeparator = ".";\n        nfi.CurrencySymbol = "";\n        var answer = Convert.ToDecimal(xyz).ToString("C3", \n              nfi);	0
2316196	1508179	How can I tell my application window is the foreground window	[System.Runtime.InteropServices.DllImport( "user32.dll" )]    \npublic static extern IntPtr GetForegroundWindow();	0
30897741	30895273	Join 2 tables with multiple references in LINQ	var query1 = \n    (from t1 in table1s\n    join t2 in table2s on t1.Id equals t2.Id1\n    where !string.IsNullOrEmpty(t1.Name)\n    select new {t1.Name, t2.Id1, t2.Id2, t2.MatchLevel});\n\nvar query2 =\n    (from t1 in table1s\n    join t2 in table2s on t1.Id equals t2.Id2\n    where !string.IsNullOrEmpty(t1.Name)\n    select new {t1.Name, t2.Id1, t2.Id2, t2.MatchLevel});\n\n\nvar query = query1.Union(query2).GroupBy(x => x.Name)\n    .Select(x => new \n    {\n        Name = x.Key, \n        MatchLevel = x.Max(y => y.MatchLevel)\n    });	0
918748	419518	"The parameter is incorrect" when setting Unicode as console encoding	FileStream testStream = File.Create("test.txt");\nTextWriter writer = new StreamWriter(testStream, Encoding.Unicode);\nConsole.SetOut(writer);            \nConsole.WriteLine("Hello World: \u263B");  // unicode smiley face\nwriter.Close(); // flush the output	0
10862017	10861833	Split string extension with generic type?	IEnumerable<int> ints = "1,2,3".Split(',').Select(int.Parse);	0
3560721	3560597	Problem sorting a list inside a databound object	.Reverse(lbCurrent.SelectedIndex - 1, 2);	0
5245021	5244943	Detecting User Activity	If Computer_is_Idle > 15 minutes Then\n    Do this\nElse\n    Do that or Wait more...	0
27601313	27600978	Take screenshot of selected area in pdf in windows application using c#	OpenFileDialog dlg = new OpenFileDialog();\ndlg.Filter = "Portable Document Format (*.pdf)|*.pdf";\nif (dlg.ShowDialog() == DialogResult.OK)\n{\n    _pdfDoc = new PDFLibNet.PDFWrapper();\n    _pdfDoc.LoadPDF(dlg.FileName);\n    _pdfDoc.CurrentPage = 1;\n\n   PictureBox pic =new PictureBox();\n   pic.Width=800;\n   pic.Height=1024;\n   _pdfDoc.FitToWidth(pic.Handle);\n   pic.Height = _pdfDoc.PageHeight;\n   _pdfDoc.RenderPage(pic.Handle);\n\n   Bitmap _backbuffer = new Bitmap(_pdfDoc.PageWidth, _pdfDoc.PageHeight);\n   using (Graphics g = Graphics.FromImage(_backbuffer))\n   {\n       _pdfDoc.RenderHDC(g.GetHdc);\n       g.ReleaseHdc();\n   }\n   pic.Image = _backbuffer;\n}	0
9754611	9754387	defining location of files at deployment time	System.Configuration.ConfigurationManager.AppSettings.Get("YourKey")	0
10588351	10588236	Getting parts of an xml file and bundle them up in a new one	XElement root1 = XElement.Load(file1);\nXElement root2 = XElement.Load(file2);\nXElement combined = new XElement("combined");\n\nforeach(XElement node1 in root1.Elements())\n    combined.Add(node1);\n\nforeach(XElement node2 in root2.Elements())\n    combined.Add(node2);\n\ncombined.Save(file3);	0
8745842	8745828	I need a function that I can apply to a string to return the string value or "00" if it is null	var abc = myVariable ?? "00";	0
28165931	28165859	how to get a list of all content type groups using sharepoint client model in c#	ClientContext ctx = new ClientContext("URL");\n\nSP.Web web = ctx.Web;\nctx.Load(web, w => w.AvailableContentTypes);\n\nvar cts = ctx.Web.AvailableContentTypes;\n\nctx.ExecuteQuery();\n\nvar groups = cts.ToList().Select(ct => ct.Group).Distinct();	0
11416240	11415809	Convert file received from jquery to byte array	int filelength = file.ContentLength;\n    byte[] imagebytes = new byte[filelength ];\n    file.InputStream.Read(imagebytes , 0, filelength );	0
1620271	1620265	Regex replace/search using values/variables in search text	{marker=(\d)}(.*?){/marker=(\1)}	0
7574411	7571406	handle OnCompleted with cold observables	var list = new List<int> { 1, 2, 3 };\nvar obs = list.ToObservable();\nvar subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p =>\n    {\n        Console.WriteLine(p.ToString());\n        Thread.Sleep(200);\n    },\n    error => Console.WriteLine("Error!"),\n    () => Console.WriteLine("sequence completed"));\nConsole.ReadLine();\nsubscription.Dispose();	0
32389696	32389448	Clear only 1 row of DataGridView in c#	YourDGVName.Rows.RemoveAt(YourDGVName.CurrentRow.Index);	0
5457703	5457685	How to define a property whose type in database is bit?	public bool MyBitDbProperty {get;set;}	0
7767577	7767530	Passing values into methods	CalculateBMI(123, 178); // What do the numbers mean?\nCalculateBMI(weightInKg: 123, heightInCentimeters: 178); // Clearer IMHO.	0
6820990	6820969	Read file-system into dataset	System.IO	0
31277922	31277790	Main window appears behind other windows after splash screen	Form1.Activate();	0
6234771	6234735	Try catch in a final statement?	public Task Update(Task task)\n{\n    isLocked = true;\n    try\n    {\n        //DO OTHER STUFF HERE\n    }\n    catch(Exception ex)\n    {\n        // error logging here\n    }\n    finally\n    {\n        UpdateToDB(task)\n    }\n    return task;\n}\n\nprivate Task UpdateToDB(Task task)\n{\n    try\n    {\n        task.locked = false\n        task.DateLocked = "6/3/1900";\n        task.Commit();     \n    }\n    catch(Exception e)\n    {\n        //LOG ERROR\n    }\n    catch(SqlException ex)\n    {\n       //LOG ERROR\n       // "database is down error to user"\n    }\n    isLocked = false;\n    return task\n}	0
17201833	17201629	Putting multiple arrays from GetValueNames() into one array in C#	RegistryKey regKey = Registry.CurrentUser;\nvar console = regKey.OpenSubKey("Console");\nvar dict = console.GetValueNames()\n          .ToDictionary(key => key, key => console.GetValue(key));\n\n\nforeach (var kv in dict)\n{\n    Console.WriteLine(kv.Key + "=" + kv.Value);\n}	0
13381145	13380939	Windows Application C# strings combobox	private List<string> songs = new List<string>();\n//...\nSelectComboBox.Items.Insert(0, "First song");\nsongs.Add("URL to song");\n//...\nPlayer.URL = songs[SelectComboBox.SelectedIndex];	0
9447330	9447175	Error passing Datetime as querystring parameter to Servicestack.net GET method	2012-02-24T17:13:02	0
10213240	10212982	Capture webBrowser control response	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n  HtmlDocument document =  webBrowser1.Document;\n  //now use any of the methods exposed by HtmlDocument to parse the output\n}	0
13424887	13416193	How to discover onvif devices in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        var endPoint = new UdpDiscoveryEndpoint( DiscoveryVersion.WSDiscoveryApril2005 );\n\n        var discoveryClient = new DiscoveryClient(endPoint);\n\n        discoveryClient.FindProgressChanged += discoveryClient_FindProgressChanged;\n\n        FindCriteria findCriteria = new FindCriteria();\n        findCriteria.Duration = TimeSpan.MaxValue;\n        findCriteria.MaxResults = int.MaxValue;\n        discoveryClient.FindAsync(findCriteria);\n\n        Console.ReadKey();\n    }\n\n    static void discoveryClient_FindProgressChanged(object sender, FindProgressChangedEventArgs e)\n    {\n        //Check endpoint metadata here for required types.\n\n    }\n}	0
5285568	5210506	Entity Framework 4.0 CTP5 Many to Many relation ship with a help table?	HasMany(c => c.Companies)\n          .WithMany(u => u.Users)\n          .Map(mc =>\n          {\n              mc.ToTable("CMS_USERS_TO_COMPANIES", "GMATEST");\n              mc.MapLeftKey(c => c.UserId, "USER_ID");\n              mc.MapRightKey(u => u.CompanyId, "COMPANY_ID");\n          });	0
16653459	16653403	How can I select items from a list lower bound to upper bound?	IEnumerable<TSource>.Skip(lowerBound).Take(upperBound-lowerBound)	0
6350934	6350779	Fluent nHibernate Join	References(x=>Category)\n    .Column("CategoryId")\n    .Inverse()\n    .Cascade.None();	0
16720017	16715429	"Link" items in a WPF TreeView	var myItem = (UIElement)myTreeView.SelectedItem;\nvar pos1 = myItem.TranslatePoint(new Point(), myTreeView);\nvar pos2 = myAnyOtherItem.TranslatePoint(new Point(), myTreeView);	0
5295411	5169410	Any way to snap animated TranslateTransform to pixel grid?	TextOptions.TextHintingMode="Animated"	0
30301865	30296692	Creating term fails in SP 2013	foreach (var tagName in tagNames)\n        {\n            var newTerm = termSet.CreateTerm(tagName, Thread.CurrentThread.CurrentUICulture.LCID, Guid.NewGuid());\n        }\n\n        termStore.CommitAll();\n        clientContext.Load(termStore);\n        clientContext.ExecuteQuery();	0
14948647	14948614	how to fix listbox item titles?	private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)\n    {\n        texbox1.text = (listBox.SelectedItem as ListBoxItem).Content.ToString();\n    }	0
18620503	18620277	Writing to Image using Lock Bits in C#	// Get the address of the first line.\n        IntPtr ptr = bmpData.Scan0;\n\n        // Declare an array to hold the bytes of the bitmap. \n        int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;\n       byte[] rgbValues = new byte[bytes];\n\n        // Copy the RGB values into the array.\n        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);	0
3578393	3578356	WPF INotifyPropertyChanged for linked read-only properties	onPropertyChanged(this, "bar")	0
14156129	14155975	How to query Link table based data in LINQ	var query = from s in db.Student\n            join scg in db.StudentCourseGroup on s.StudentID equals scg.StudentID\n            join c in db.Course on scg.CourseID equals c.CourseID\n            join g in db.Group on scg.GroupID equals g.GroupID\n            where c.CourseName == "xyz"\n            select new { s, g } into x\n            group x by x.s into studentGroups\n            select new MyStudent {\n                StudentName = studentGroups.Key.StudentName,\n                Groups = studentGroups.Select(sg => sg.g.GroupName)\n            };	0
29167413	29167293	Replace pattern values in c#	string input = "Test uid=1 Test2 uid=2 Test3 uid=3";\nvar replacements = new Dictionary<string,string> {\n    { "1", "2015" },\n    { "2", "2016" },\n    { "3", "3014" }\n};\nstring output = Regex.Replace(input, @"(?<=uid=)\d+", m => replacements[m.Value]);	0
11906806	11906774	How to subscribe to a DependencyProperty Change Notification	static void OnThePropChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n{\n     YourClass instance = (YourClass)obj;\n     instance.ThePropChanged(args); // Call non-static\n\n     // Alternatively, you can just call the callback directly:\n     // instance.CallbackMethod(...)\n}\n\n// This is a non-static version of the dep. property changed event\nvoid ThePropChanged(DependencyPropertyChangedEventArgs args)\n{\n      // Raise your callback here... \n}	0
875796	875723	How to debug/break in codedom compiled code	parameters.GenerateInMemory = false; //default\nparameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true);\nparameters.IncludeDebugInformation = true;	0
15968134	15967625	How to merge two datatables, which having different schema?	static void Main(string[] args)\n{\n    Program p = new Program();\n    DataTable dt1= p.Get1();\n    DataTable dt2 = p.Get2();          \n    DataTable dt3 = p.Get3(dt1, dt2);\n}\npublic DataTable Get1()\n{\n    DataTable dt1 = new DataTable();\n    dt1.Columns.Add("ID");\n    dt1.Columns.Add("Name");\n    dt1.Rows.Add("1", "JOHN");\n    dt1.Rows.Add("2", "GEORGE");\n    dt1.Rows.Add("3", "RAGU");        \n    return dt1;\n}\n\npublic DataTable Get2()\n{\n    DataTable dt2 = new DataTable();\n    dt2.Columns.Add("AGE");         \n    dt2.Rows.Add("23");\n    dt2.Rows.Add("23");\n    dt2.Rows.Add("22");\n    return dt2;\n}\n\npublic DataTable Get3(DataTable dt1,DataTable dt2)\n{\n    dt1.Columns.Add("Age");\n    for (int i = 0; i < dt1.Rows.Count; i++)\n    {\n        dt1.Rows[i]["Age"] = dt2.Rows[i]["Age"];\n    }\n    return dt1;\n}	0
24340415	7602328	Get filtered result from BindingSource to table/dataset?	sourceDataTable.DefaultView.RowFilter = bindingSource.Filter;\nDataTable destinationDataTable = sourceDataTable.DefaultView.ToTable();	0
3614385	3614377	Retrieve type of base type without knowing its derived type	public DoAThing()\n    {\n        Type myType = typeof(Base);\n    }	0
6639528	6639397	Partial view model for editing must contain all fields specified in MetadataType?	public interface IAdministrator : IAdministratorEdit	0
24123723	24122344	How to handle an exception without closing application?	bool success = false;\n            try { \n                //try to send the message\n                smtpmail.Send(message);\n                success = true;//everything is good\n            }\n            catch (Exception err)\n            {\n                //error with sending the message\n                errorMsg.Text = ("Unable to send mail at this time. Please try again later.");\n\n                //log the error \n                errorLog.Log(err); //note errorLog is another method to log the error\n\n\n                //other stuff relating to certain parts of the application visibility\n\n            }\n            finally\n            {\n                if (success)\n                { \n                    //what to do if the email was successfully sent\n                }\n            }	0
4168287	4168259	Set Silverlight grid columnwidth with "*" in codebehind?	MyColumn.Width = new GridLength(3, GridUnitType.Star);	0
17537886	17537604	Query Collection of all XML Elements	var xdoc = XDocument.Load(@"C:\test.xml");\n    foreach (var element in xdoc.Element("DiagReport").Elements().Elements())\n    {\n        if (element.Name == "Result")\n        {\n            string value = element.Value;\n        }\n    }	0
6513246	6512996	How To Include An Optional Null Parameter In SQL Server	select\n    *\nfrom\n    Products\nwhere\n    Name like '%Hasbro%' and\n    (\n      ( @ProductID is null ) or\n      ( @ProductID is not null and ProductID = @ProductID ) \n    )	0
20760919	20746437	Use Entity as property but make it a complex type	public class EntityA : EntityABase {\n\n\n}\n\npublic abstract class EntityABase {\n\n    [Key]\n    public int id { get; set; } \n\n    public int prop1 { get; set; }\n\n    public virtual AnotherEntity { get; set; }\n}\n\npublic class EntityB : EntityABase {\n\n    [Key]  \n    public virtual EntityC { get; set; }\n\n}	0
19499010	19074983	showing combobox item from database	SqlConnection con = new SqlConnection("Data Source=xxxxx;Initial Catalog=yyyyy;Integrated Security=true;");\n        SqlCommand cmnd = con.CreateCommand();\n\n        cmnd.CommandText = "Select * from BillingType";\n\n        con.Open();\n        SqlDataReader rd = cmnd.ExecuteReader();\n\n        while (rd.Read())\n            {\n                string someFieldText = rd[1].ToString();\n\n                comboBox1.Items.Add(someFieldText);\n            }\n        }\n        con.Close();	0
13761889	13761852	Binding data to label with static text	Text='<%# "ID: " +Eval("ID").ToString() %>'	0
19536265	19536110	Highlight text ignoring cases in word document in c#	if(String.Compare(w.Text.Trim(), text.ToString(), true) == 0)	0
2499628	2499479	How to round-off hours based on Minutes(hours+0 if min<30, hours+1 otherwise)?	public static DateTime Round( DateTime dateTime )\n{\n    var updated = dateTime.AddMinutes( 30 );\n    return new DateTime( updated.Year, updated.Month, updated.Day,\n                         updated.Hour,  0, 0, dateTime.Kind );\n}	0
25919010	25916673	Integrating SQL Reporting Service into a C# WebAPI app	LocalReport report = new LocalReport();\nreport.ReportPath = "SomePath";\nreport.DataSources.Clear();\nreport.DataSources.Add(new ReportDataSource("SomeDataSourceName", \n        SomeCollectionObject));\nreport.DataSources.Add(new ReportDataSource("SomeOtherDataSourceName", \n            SomeOtherCollectionObject));\nWarning[] warnings;\nstring[] streamids;\nstring mimeType, encoding, filenameExtension;\nbyte[] array = report.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);	0
887592	887586	Convert string to integer	int yourInteger;\n    string newItem;\n\n    newItem = textBox1.Text.Trim();\n    Int32 num = 0;\n    if ( Int32.TryParse(textBox1.Text, out num))\n    {\n        listBox1.Items.Add(newItem);\n    }\n    else\n    {\n        customValidator.IsValid = false;\n        customValidator.Text = "You have not specified a correct number";\n    }	0
19510898	19510636	Sharing cache between two MVC applications	System.Runtime.Caching	0
30572437	30570941	How to do optimal write rule definition in NRules	Expression<Func<T, bool>>	0
33287607	33287083	Getting Index of First Non Alpha character in a string C#	var s = "Payments Received by 08/14/2015 $0.00";\nvar re = new Regex("^([a-z ]+)(.+)", RegexOptions.IgnoreCase);\nvar m = re.Match(s);\nif (m.Success)\n{\n    Console.WriteLine(m.Groups[1]);\n    Console.WriteLine(m.Groups[2]);\n}	0
2693195	2691893	How to find the parent using the hierarchyid data type	DECLARE @val HIERARCHYID  \nSELECT @val = dbo.GetHierarchyIDbyID(30)  \nSELECT * FROM NodeHierarchy WHERE hid = @val.GetAncestor(1)	0
2188462	2188452	What is the leanest way to convert a Dictionary<string, string> to a Dictionary<string, object>?	var newMap = oldMap.ToDictionary(pair => pair.Key, pair=>(object)pair.Value);	0
13121418	13114698	ienumerable update in foreach loop	private void timer2_Tick(object sender, EventArgs e)\n{\n a++;\n imageFileName = "IMAGES\DB\"+a+".jpg"\n\\\my code\n}	0
8405556	8405496	Regular Expressions pattern with Special characters	foundMatch = Regex.IsMatch(SubjectString, @"\+/-");	0
28139795	28139064	Track key press and key release on WPF applications	private void PlotListView_KeyUp(object sender, KeyEventArgs e)\n    {\n        TrackUpDownKeyPress(e, false);\n    }\n\n    private void PlotListView_KeyDown(object sender, KeyEventArgs e)\n    {\n        TrackUpDownKeyPress(e, true);\n    }\n\n    private void TrackUpDownKeyPress(KeyEventArgs e, bool isPressed)\n    {\n        if (e.Key == Key.Up || e.Key == Key.Down)\n            _upDownKeyIsPressed = isPressed;\n    }	0
5774126	5770478	Plinq statement gets deadlocked inside static constructor	using System.Threading;\nclass Blah\n{\n    static void Main() { /* Won???t run because the static constructor deadlocks. */ }\n\n    static Blah()\n    {\n        Thread thread = new Thread(ThreadBody);\n        thread.Start();\n        thread.Join();\n    }\n\n    static void ThreadBody() { }\n}	0
1199956	1199176	How to select distinct rows in a datatable and store into an array.	DataView view = new DataView(table);\nDataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);	0
11515757	11515411	C# - Form user button click, get next window clicked by user	[DllImport("user32.dll")]\nstatic extern IntPtr GetForegroundWindow();\n\n[DllImport("user32.dll", SetLastError = true)]\nstatic extern bool GetWindowRect(IntPtr hWnd, out Rectangle lpRect); \n\n\nRect rect = new Rect ();\nGetWindowRect(GetForegroundWindow(), out rect);\n\n//calculate width and height from rect\n\nusing (Bitmap bitmap = new Bitmap(width, height))\n{\n    using (Graphics g = Graphics.FromImage(bitmap))\n    {\n        Size size = new System.Drawing.Size(width, height);\n        g.CopyFromScreen(new Point(rect.Left, rect.Top), Point.Empty, size);\n    }\n    bitmap.Save("C://test.jpg", ImageFormat.Jpeg);\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct Rect {\n    public int Left;\n    public int Top;\n    public int Right;\n    public int Bottom;\n}	0
2155699	2155668	remove last word in label split by \	name = name.TrimEnd('\\')\nname = name.Remove(name.LastIndexOf('\\') + 1);	0
5434195	5431906	treeview with radiobuttonlist	protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)\n{\n  e.Node.Text = "<input type='radio' />" + e.Node.Text;\n}\n\nprotected override void Render(HtmlTextWriter writer)\n{\n    base.Render(writer);\n    TreeView1.RenderControl(writer);\n}	0
5957557	5957542	ClickOnce Install button leads to text	.application	0
18890260	18546748	get image from web service and show on Winforms	var client = new RestClient();\nclient.BaseUrl = "http://www.abcd.com/image1.jpg";\nvar request = new RestRequest();\npicturebox1.Image = new Bitmap(new MemoryStream(client.DownloadData(request)));	0
16272594	16272498	Loop through current years month to next year month in c#	DateTime lastDate = DateTime.ParseExact("01/12/12", "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);\n\nList<DateTime> result = new List<DateTime>();\n\n//iterate until the difference is two months \nwhile (new DateTime((DateTime.Today - lastDate).Ticks).Month >= 2)\n{\n    result.Add(lastDate);\n    lastDate = lastDate.AddMonths(1);\n}\n\n//result: 12/1/2012\n//         1/1/2013\n//         2/1/2013\n//         3/1/2013	0
32622559	32620129	Add new item in ListView then update to database	for (int i = 0; i <= ListView1.Items.Count - 1; i++)\n{\n    string cd = @"INSERT INTO ProductSold (BillNo, DishName, DishRate, Quantity, TotalAmount)\n                  VALUES (@BillNo, @DishName, @DishRate, @Quantity, @TotalAmount)";\n\n    cmd = new OleDbCommand(cd);\n    cmd.Connection = con;\n    cmd.Parameters.AddWithValue("@BillNo", txtBillNoE.Text);\n    cmd.Parameters.AddWithValue("@DishName", ListView1.Items[i].SubItems[1].Text);\n    cmd.Parameters.AddWithValue("@DishRate", ListView1.Items[i].SubItems[2].Text);\n    cmd.Parameters.AddWithValue("@Quantity", ListView1.Items[i].SubItems[3].Text);\n    cmd.Parameters.AddWithValue("@TotalAmount", ListView1.Items[i].SubItems[4].Text);\n    cmd.ExecuteNonQuery();\n}	0
6607380	6607329	How To Put Data In 2D Array from Dataset Using Loop C#?	terms[runs,0] =output.Tables[0].Rows[runs][0].ToString();\nterms[runs,1] =output.Tables[0].Rows[runs][2].ToString();	0
6763332	6763032	How to pick a background color depending on font color to have proper contrast	public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n{\n    var c = (Color)value;\n    var l = 0.2126 * c.ScR + 0.7152 * c.ScG + 0.0722 * c.ScB;\n\n    return l < 0.5 ? Brushes.White : Brushes.Black;\n}	0
31451724	31446694	How to rotate PDF pages (permanent) to 90, 180, 270 degree c#	byte[] source = // some source of pdf byte array\n            MemoryStream outStream = new MemoryStream();\n            PdfReader reader = new PdfReader(scannedInvoice.imgImage);\n            PdfStamper stamper = new PdfStamper(reader, outStream);\n\n            for (int i = 1; i <= reader.NumberOfPages; i++)\n            {\n                PdfDictionary pageDict = reader.GetPageN(i);\n                int desiredRot = 90; // 90 degrees clockwise\n                PdfNumber rotation = pageDict.GetAsNumber(PdfName.ROTATE);\n                if (rotation != null)\n                {\n                    desiredRot += rotation.IntValue;\n                    desiredRot %= 360; // 0, 90, 180, 270\n                }\n                pageDict.Put(PdfName.ROTATE, new PdfNumber(desiredRot));\n            }\n            stamper.Close();\n            var rotatedpdfArray = outStream.ToArray(); // The rotated output	0
4726915	4580270	Display time data with telerik chart	IList<DateTime> ChartData = new List<DateTime>();\n        foreach (var row in formDataSource)\n        {\n            DateTime dt = DateTime.Parse(row["DateCompleted"]);\n            dt.AddHours(Convert.ToInt16(row["DateCompletedHour"]));\n            ChartData.Add(dt);\n        }\n\n        FormChart chart = new FormChart();\n        chart.DataSource = ChartData;\n        chart.DataBind();	0
9260509	9259772	Getting CPU usage of a process in C#	((total processor time at time T2) - (total processor time at time T1) / (T2 - T1))	0
3243816	3243800	In VS 2008, how to do re-assign all classes that use a global variable to another class with the new variable?	TypeName.variableName	0
8756278	8756179	how to get mac address of client that browse web site by asp.net mvc c#	var remoteIpAddress = Request.UserHostAddress;	0
767677	767624	Using WatIN to determine website's position in google	using (IE ie = new IE("http://www.google.co.il"))\n            {\n                ie.TextField(Find.ByName("q")).TypeText(keyword);\n                ie.Button(Find.ByName("btnG")).Click();\n                int position = 1;\n                label1.Text = "";\n                foreach (Span span in ie.Spans)\n                {\n                    if (span.OuterHtml.ToLower().StartsWith("<span dir=ltr>"))\n                    {\n                        label1.Text += position.ToString() + ": " + span.InnerHtml + "\n";\n                        position++;\n                    }\n                }\n            }	0
22234547	22234495	Is there a better method of calling a comparision over a list of objects in C#?	if(possible.Any(r=> line.Contains(r)))\n{\n\n}	0
7731764	7731686	Bring form2 to front from a deactivated form1	MyStaticClass.lastForm.WindowState = FormWindowState.Normal;	0
8070436	8070333	Return data from SQL Server using Stored Procedure	string returnvalue = (string)myCommand.ExecuteScalar();	0
23995106	23963098	no combination of intermediate filters could be found	SetupGraph()	0
34156699	34156290	How to filter data from tables and display it in DataGridView?	private void button1_Click(object sender, EventArgs e)\n\n    {   // display Order_details table into DataGridView\n\n        SqlConnection con = new SqlConnection("Data Source=PCN11-TOSH;Initial Catalog=mydb;Integrated Security=True");\n        con.Open();\n        SqlCommand cm = new SqlCommand(@"SELECT o.customer_name, p.product_name, d.Qty, p.price FROM Orders\n                                         JOIN order_details d ON d.order_ID = o.order_ID\n                                         JOIN products p ON p.product_ID = d.product_ID");\n        cm.Connection = con;\n\n        SqlDataAdapter da = new SqlDataAdapter(cm);\n        DataTable dt = new DataTable();\n        da.Fill(dt);\n\n        con.Close();\n\n        dataGridView1.DataSource = dt;	0
7721089	7720997	How to display multiple values in a combo box from a datatable	DataTable dt = new DataTable();\n            dt.Columns.Add("Id", typeof(int));\n            dt.Columns.Add("Col1", typeof(string));\n            dt.Columns.Add("Col2", typeof(string));\n            dt.Columns.Add("ConcatenatedField", typeof(string), "Col1 + ' : ' +Col2"); \n\n            Enumerable.Range(1, 10).ToList().ForEach(i => dt.Rows.Add(i, string.Concat("Col1", i), string.Concat("Col2", i)));\n\n            comboBox1.DataSource = dt;\n            comboBox1.DisplayMember = "ConcatenatedField";	0
18983189	18937357	How can I show number of unread articles on a live tile on Windows Phone?	If-Modified-Since	0
2279698	2279670	adding element to xml file from c#.net	XDocument doc = XDocument.Load("test.xml");\ndoc.Root.Add(new XElement("someNode", "some node value"));\ndoc.Save("test.xml");	0
3227369	3227211	How can I get the expiration date of an intermediate certificate and trusted root certificate by C# code?	X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadOnly);\n\nX509Certificate2Collection certs = store.Certificates.Find(\n    X509FindType.FindBySubjectDistinguishedName,\n    "name",\n    false);\n\nX509Certificate2 cert = certs[0];\n\ncert.GetExpirationDateString();	0
26533394	26532873	ParseXML how compare one attribute for take the value of the other in the same element	XDocument xDoc = XDocument.Parse(yourXMLString);\n\n//XDocument xDoc = XDocument.Load(yourXMLFilePath);\n\nvar res = xDoc.Descendants("Entry")\n              .Where(x => x.Attribute("type").Value == "fired")\n              .Elements("field")\n              .Where(y => y.Attribute("tag").Value == "34" || y.Attribute("tag").Value == "43")\n              .Select(a => a.Attribute("val").Value);	0
6542074	6542035	ListView not updated correctly with ObservableCollection	public class VeryObservableCollection<T> : ObservableCollection<T>\n\n/// <summary>\n/// Override for setting item\n/// </summary>\n/// <param name="index">Index</param>\n/// <param name="item">Item</param>\nprotected override void SetItem(int index, T item)\n{\n    try\n    {\n        INotifyPropertyChanged propOld = Items[index] as INotifyPropertyChanged;\n        if (propOld != null)\n            propOld.PropertyChanged -= new PropertyChangedEventHandler(Affecting_PropertyChanged);\n    }\n    catch (Exception ex)\n    {\n        Exception ex2 = ex.InnerException;\n    }\n    INotifyPropertyChanged propNew = item as INotifyPropertyChanged;\n    if (propNew != null)\n        propNew.PropertyChanged += new PropertyChangedEventHandler(Affecting_PropertyChanged);\n\n    base.SetItem(index, item);\n}	0
25952788	25952709	How to convert List<KeyValuePair<int,int>> to int[][]?	var result = list.Select(x => new[] { x.Key, x.Value }).ToArray();	0
20899444	20108575	WCF, xml creates ExtensionData tag which I want to remove	public StudentList ListStudents()\n{\n    // return new List<student>();\n       return new StudentList(); \n}\n\n[CollectionDataContractAttribute()]\npublic class StudentList : List<Student>\n{}	0
10820391	10820188	Handling blank string ("") text box values when doing select to a database with null values in C#	...\nWHERE ( @field1 IS NULL OR COALESCE(field1,'') like '%' + @field1 + '%' )\nAND   ( @field2 IS NULL OR COALESCE(field2,'') like '%' + @field2 + '%' )\nAND   ( @field3 IS NULL OR COALESCE(field3,'') like '%' + @field3 + '%' )	0
16609192	16609132	Get Value from XML	XElement doc = XElement.Parse(text);\nvar res = doc.Element("WebserviceURL").Value.Trim();	0
6415176	6415099	full screen mode, but don't cover the taskbar 	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void Form1_Load( object sender, EventArgs e )\n    {\n        FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;\n        Left = Top = 0;\n        Width = Screen.PrimaryScreen.WorkingArea.Width;\n        Height = Screen.PrimaryScreen.WorkingArea.Height;\n    }\n}	0
17955808	17955743	ASP.net Repeater -- setting N Maximum Repetitions?	var rand = new Random();\nvar myCollection = GetSomethingFromSomewhere();\nmyRepeater.DataSource = myCollection\n    .OrderBy(x => rand.Next())\n    .Take(4);\nmyRepeater.DataBind();	0
21176914	21176748	Lambda expression + Dictionary: An item with the same key has already been added	var groups = result.Items.GroupBy(r => r.itemType).Select(g => new { id = g.Key, count = g.Count() });\nvar res = new Dictionary<itemType, int>();\nres = groups.ToDictionary(a => a.id, a=>a.count);	0
17673094	17654553	How to give scopes in AspNet.Membership.OpenAuth and get extra data from facebook?	//following code will not work, although option is given\nvar extraData= new Dictionary<string, object>();\n        extraData.Add("scope",\n                               "email,publish_actions,create_event");\n        //facebookSocialData.Add("perms", "status_update");\n        OAuthWebSecurity.RegisterFacebookClient(\n             "xxxx",\n             "yyyy", "Facebook", extraData);	0
25857256	25856836	c# convert double to string and check length in one expression	if (Math.Truncate((oddOrEven / 100)) % 10 == 7)\nConsole.WriteLine("The third digit is a 7");	0
17744269	17739963	WPF close all window from the main window	private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)\n    {\n        var form = new LoginForm();\n        var result = form.ShowDialog();\n\n        if (result ?? false)\n        {\n            // Carry on opening up other windows\n        }\n        else\n        {\n            // Show some kind of error message to the user and shut down\n        }\n    }	0
16195668	16195266	How to draw lines with mouse in C#	private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n{\n    _pathFigure.Segments.Clear();\n    _pathFigure.StartPoint = e.GetPosition(this);\n}	0
20750796	20738362	Custom Service Locator with MEF and IOC container from galasoft	protected override object DoGetInstance(Type serviceType, string key)\n{\n    IEnumerable<Lazy<object, object>> exports = this.compositionContainer.GetExports(serviceType, null, key);\n    if ((exports != null) && (exports.Count() > 0))\n    {\n        // If there is more than one value, this will throw an InvalidOperationException, \n        // which will be wrapped by the base class as an ActivationException.\n        return exports.Single().Value;\n    }\n\n    throw new ActivationException(\n        this.FormatActivationExceptionMessage(new CompositionException("Export not found"), serviceType, key));\n}	0
30352567	30333859	Parse JSON forecast data from Wunderground	string tempCelsius = (string)jsonObject.SelectToken("forecast.simpleforecast.forecastday[0].high.celsius");	0
1105025	1104620	How to store file on server ASP.net	string log = String.Empty;\n\n// format log string using error message\n\ntry\n{\n    using (StreamWriter logFile = new StreamWriter(@"C:\WebSite\logs.txt", true))\n    {\n        logFile.WriteLine(log);\n    }\n}\ncatch\n{\n    // here I e-mail the error in case logging failed\n}	0
18118718	18081889	how to download files in zip format which are stored in database in binary format	protected void ZipDownload()\n    {\n        var list = db.Documents.Where(u => u.userId == (int)Session["usrId"]).Select(u => new { u.doc, u.docname, u.doctype });\n        ZipFile zip = new ZipFile();\n        foreach (var file in list)\n        {\n\n            zip.AddEntry(file.docname, (byte[])file.doc.ToArray());\n        }\n        var zipMs = new MemoryStream();\n        zip.Save(zipMs);\n        byte[] fileData = zipMs.GetBuffer();\n        zipMs.Seek(0, SeekOrigin.Begin);\n        zipMs.Flush();\n        Response.Clear();\n        Response.AddHeader("content-disposition", "attachment;filename=docs.zip ");\n        Response.ContentType = "application/zip";\n        Response.BinaryWrite(fileData);\n        Response.End();\n\n    }	0
23902661	23902617	How to call other class method with out parameter	class Program\n {\n    static void Main(string[] args)\n    {\n       int i;\n       int j = OtherClass.Test( out i);\n    }\n }	0
28460220	28460175	Lambda Expression with List<>	vbolErroDocTorObrigatorio = vlstDados.All(l => l.IcObrigatorio & string.IsNullOrEmpty(l.DsPathDocumento));	0
468685	468469	How do you upload a file to a document library in sharepoint?	String fileToUpload = @"C:\YourFile.txt";\nString sharePointSite = "http://yoursite.com/sites/Research/";\nString documentLibraryName = "Shared Documents";\n\nusing (SPSite oSite = new SPSite(sharePointSite))\n{\n    using (SPWeb oWeb = oSite.OpenWeb())\n    {\n        if (!System.IO.File.Exists(fileToUpload))\n            throw new FileNotFoundException("File not found.", fileToUpload);                    \n\n        SPFolder myLibrary = oWeb.Folders[documentLibraryName];\n\n        // Prepare to upload\n        Boolean replaceExistingFiles = true;\n        String fileName = System.IO.Path.GetFileName(fileToUpload);\n        FileStream fileStream = File.OpenRead(fileToUpload);\n\n        // Upload document\n        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);\n\n        // Commit \n        myLibrary.Update();\n    }\n}	0
6752396	6737581	C# control to display camera video with DirectShow.Net	IVideoWindow videowindow;\nvideowindow = FirstGraph as IVideoWindow;\nvideowindow.put_Owner(panel1.Handle);\nvideowindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipChildren);	0
7807231	7806109	Rookie thing: How to collect data from multiple tables most deftly?	public class Person\n{\n    public int ID { get; set; }\n    public string Surname { get; set; }\n    public string Name { get; set; }\n    public short Age { get; set; }\n\n    public Person()\n    {\n    }\n\n    public Person( Persistence.Person src )\n    {\n      this.ID = src.ID;\n      this.Surname = src.surname;\n      this.Name = src.name;\n      this.Age = src.age;\n    }\n}\n\n...\npublic List<Domain.Person> LoadPeople()\n{\n    using( var context = this.CreateContext() )\n    {\n        var personQuery = from p in context.Persons\n                          select new Domain.Person( p );\n\n        return personQuery.ToList();\n    }\n}\n\npublic Person LoadPerson( int personID )\n{\n    using( var context = this.CreateContext() )\n    {\n        var personQuery = from p in context.Persons\n                          where p.id == personID\n                          select new Domain.Person( p );\n\n        return personQuery.SingleOrDefault();\n    }\n}	0
15675949	15675883	Filter particular row of Datatable for all column values	List<string> result = dt.Columns.Cast<DataColumn>()\n            .Where(c => c.ColumnName != "pcode")\n            .Where(c => dt.Rows[0][c].ToString() == "1")\n            .Select(c => c.ColumnName)\n            .ToList();	0
647866	647833	rendering an aspx page in another one	StringWriter _writer = new StringWriter();\nHttpContext.Current.Server.Execute("MyPage.aspx", _writer);\n\nstring html = _writer.ToString();	0
34463021	34462997	Calculate distance between two points in ApiController (WebApi)	Harvesine formula	0
1169507	1169433	How to detect previous state of text field in C#?	uxName.TextChanged -= uxName_TextChanged;    \n\nuxName.Text = File.ReadAllText("something.txt");\n\nuxName.TextChanged += uxName_TextChanged;	0
23394088	23393912	XML wont parse attributes correctly	else //No children, so add the outer xml (trimming off whitespace)\n        //taskNode.Text = xmlNode.OuterXml.Trim();\n        taskNode.Text = xmlNode.InnerXml.Trim();	0
23746375	23704781	How to get the page number of a Destination (in a GoToAction Annotation)	Document pdfDocument = new Document(myDir + "test.pdf");\nint pageNumber = pdfDocument.Destinations.GetPageNumber("appendix-a", false);	0
4900233	4900208	Format DateTime in C#	visitDate.Value.ToString("dd-MMM-yyyy");	0
4020261	4020228	Need a sample of single producer / single consumer pattern with .NET 4.0 new features	BlockingCollection<T>	0
201889	201776	Submit Login control button when I hit Enter	DefaultButton="Login$LoginButton"	0
34392712	34392531	Saving values within if statement C#	//Users message\nstring usrMsg = null;	0
30380267	30308737	Mutliple business hours in full calendar with two shifts each day	businessHours:[ \n        {\n            start: '09:00',\n            end: '13:00',\n            dow: [1, 2]\n        },\n        {\n            start: '14:00',\n            end: '16:00',\n            dow: [1, 2]\n        },\n        {\n            start: '10:00',\n            end: '19:00',\n            dow: [4]\n        },\n        {\n            start: '06:00',\n            end: '10:30',\n            dow: [6]\n        },\n        {\n            start: '13:00',\n            end: '17:00',\n            dow: [6]\n        },\n        {\n            start: '20:00',\n            end: '23:00',\n            dow: [6]\n        }\n    ]	0
6178450	6178422	asp.net web app - check user exist in Active Directory group	public List<string> GetGroupNames(string userName)\n{\n    var pc = new PrincipalContext(ContextType.Domain);\n    var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);\n    var result = new List<string>();\n    src.ToList().ForEach(sr => result.Add(sr.SamAccountName));\n    return result;\n}	0
8458121	8458099	Using Mock objects with Dictionary	IDictionary<MyClass,IList<MyOtherClass>	0
9452433	9446919	PRISM: Nested regions in a region	Initialize()	0
8022550	8021097	insert value to foreign key	user.Logowanie = newlog;	0
9365713	9365644	ASP.NET - How to display javascript alert using C#?	private void MessageBox(string msg)\n{\n    Label lbl = new Label();\n    lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";\n    Page.Controls.Add(lbl);\n}	0
25582857	25582721	How do I order two GUIDs as the lowest first?	using System;\n\nnamespace ConsoleApplication1\n{\nclass Program\n{\n\n    static void Main(string[] args)\n    {\n\n        Guid g1 = Guid.Parse("c47632a3-274b-44d0-93df-f9626a033a6f");\n        Guid g2 = Guid.Parse("c47632a3-274b-43d0-93df-f9626a033a6f");\n        Console.WriteLine(g1);\n        Console.WriteLine(g2);\n        Console.WriteLine(GetResult(g1,g2));\n        Console.ReadLine();\n    }\n    public static string GetResult(Guid Guid1, Guid Guid2)\n    {\n        return Guid1.CompareTo(Guid2) < 0 ? Guid1.ToString() + Guid2.ToString() : Guid2.ToString() + Guid1.ToString();\n    }\n}\n\n}	0
18925730	18925556	Concatenating two fields in LINQ select	.Select( c => new {c.COURSE_ID, COURSE_TITLE =string.Format("{0} {1}" ,c.CIN ,c.COURSE_TITLE)})	0
8749686	8748806	How to set only few values of an enum as valuetype of a datagridviewcell?	enum MyEnum { me, bro, sis, mom, dad } \n\nenum Subset \n{ \n    mom = MyEnum.mom,\n    dad = MyEnum.dad\n}\n\ndgv[i, j].ValueType = typeof(Subset);     \n\n// to get the MyEnum value, cast it back:\nMyEnum cellVal = (MyEnum)dgv[i, j].Value;	0
12772673	12772618	What is wrong with my MVC4 Routes, Parameters, constructors?	public ActionResult Detail(int id)	0
15077139	14907183	Save bones position after rotation in xna	//this before the drawing loop\nmodel.CopyAbsoluteBoneTransformsTo(modelTransforms);\n//drawing loop .... \n//basiceffect loop\n......\n//after basiceffect loop\nMatrix rotationmatrix = Matrix.CreateRotationX(angle);\n// X,Y Z are the axis , angle is the rotaion value\nmesh.parentbone.Transform = rotationmatrix * mesh.parentbone.transform;\n\n//end drawing loop	0
11980795	11980732	Regex to split a string using a character preceded by a particular character	(?<=x):	0
10178719	10178528	User deleting row in datagridview	private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)\n            {\n              (if user don't want to delete the selected row)\n                e.Cancel = true; \n            }	0
33676533	33676532	How to initialize a list of dictionaries	List<Dictionary<string, object>> listaDeDicionarios = new List<Dictionary<string, object>>()\n{\n    new Dictionary<string,object>()\n    {\n        {"chave1","valor um"},\n        {"chave2","dois"},\n        {"chave3",true}\n    },\n    new Dictionary<string,object>()\n    {\n        {"chave4",4},\n        {"chave5",DateTime.Now},\n        {"chave6",long.MaxValue},\n        {"chave7","..."}\n    },\n    new Dictionary<string,object>()\n    {\n        {"chave8","utf string ??? / &url"},\n        {"chave9",null},\n        {"chave10",String.Empty},\n        {"chave11",new List<string>(){"aaa","bbb","ccc","oh my god, it's a miracle!"}}\n    }\n};	0
32563305	32563111	Get user input from textbox in WPF application	var h;\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    h = text1.Text;\n}\n\n// somewhere ...\nDoSomething(h);	0
14419903	14419863	Reduce the number of lines of code	string fullText = "Hmm... You right there??";\nint currentPos = 0;\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    currentPos++;\n    textBox2.Text = fullText.Substring(0, currentPos);\n\n    if (currentPos == fullText.Length)\n        timer1.Stop();\n}	0
9362367	9348536	Migration from MBUnit v2 to v3 and the ProviderFactory is gone	public static class ConnectionStringFactory\n{\n    public static IEnumerable<string> GetConnectionString()\n    {\n        yield return "connString";\n    }\n}\n\n[Factory(typeof(ConnectionStringFactory), "GetConnectionString")]\npublic class CustomerTests\n{\n    [Test]\n    public void GetCustomerTest(string connectionString)\n    {\n        Console.WriteLine(connectionString);\n    }\n\n    [Test]\n    public void GetCustomersTest(string connectionString)\n    {\n        Console.WriteLine(connectionString);\n    }\n}	0
32482994	32482672	How to copy-paste a file that already exists?	private static void MoveCopy(String source, String target) {\n      // assuming that target directory exists\n\n      if (!File.Exists(target))\n        File.Copy(source, target);\n      else\n        for (int i = 1; ; ++i) {\n          String name = Path.Combine(\n            Path.GetDirectoryName(target),\n            Path.GetFileNameWithoutExtension(target) + String.Format("(copy{0})", i) +\n            Path.GetExtension(target));\n\n          if (!File.Exists(name)) {\n            File.Copy(source, name);\n\n            break;\n          }\n        }\n    }\n\n...\n\n  MoveCopy(filename, temp_file);	0
11683542	11683484	Format decimal c# - Keep last zero	string s = number.ToString("0.00");\nif (s.EndsWith("00"))\n{\n    s = number.ToString("0");\n}	0
22647656	22647555	Using loop foreach in xml expression	StringWriter stringwriter = new StringWriter();\n\n            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);\n            xmlTextWriter.Formatting = Formatting.Indented;\n            xmlTextWriter.WriteStartDocument();           \n\n        foreach (var match in myCollection)\n        {\n\n\n            xmlTextWriter.WriteStartElement(match);\n            ;\n                         ...\n                         ...\n\n            xmlTextWriter.WriteEndElement();\n\n        }\n            xmlTextWriter.WriteEndDocument();\n            XmlDocument docSave = new XmlDocument();\n            docSave.LoadXml(stringwriter.ToString());\n            //write the path where you want to save the Xml file\n            docSave.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() +"Roting.xml");	0
20972515	20972085	.NET DataTable is mangling date field from an Excel file	DateTime.FromOADate(value)	0
14182282	14181439	Updating value in Redis with C#	public class Leader\n{\n    public long Id { get; set; }\n    public Employee Employee { get; set; }\n    public District District { get; set; }\n}	0
9002061	8823349	How do I use the cookie container with RestSharp and ASP.NET sessions?	var sessionCookie = response.Cookies.SingleOrDefault(x => x.Name == "ASP.NET_SessionId");\n if (sessionCookie != null)\n {\n    _cookieJar.Add(new Cookie(sessionCookie.Name, sessionCookie.Value, sessionCookie.Path, sessionCookie.Domain));\n }	0
10729517	10728644	Properly declare SP_DEVICE_INTERFACE_DETAIL_DATA for PInvoke	#ifdef _WIN64\n#include <pshpack8.h>   // Assume 8-byte (64-bit) packing throughout\n#else\n#include <pshpack1.h>   // Assume byte packing throughout (32-bit processor)\n#endif	0
12577467	12577367	Error in password decryption	string password = "prabu";\n    string encryptdata = Encryptdata(password);\n    string decryptdata = Decryptdata(password);	0
8017606	8017523	I want to click(or simulate) click to an image	InvokeScript("Stuffx");	0
18901852	18901720	Get Column DataType from Entity Framework Entity	foreach (DbEntityEntry entity in entities)\n{\n    foreach (string propertyName in entity.CurrentValues.PropertyNames)\n    {\n        var propertyInfo = entity.Entity.GetType().GetProperty(propertyName);\n        var propertyType = propertyInfo.PropertyType;\n\n    }\n}	0
21161237	21160822	proper model implementation for many-to-many tables with junction tables	public class Artist\n{\n    public int Id { get; set; }\n    public string ArtistName { get; set; }\n\n    #region Navigation Properties\n    public virtual ICollection<Album> Albums { get; set; }\n    #endregion\n}\n\npublic class Album\n{\n    public int Id { get; set; }\n    public string AlbumName { get; set; }\n\n    public virtual ICollection<Artist> Artists { get; set; }\n}	0
16025700	16012348	Detailsview on ModalPopUp only displays first row of gridview	protected void gvStudent_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        dvstudent.PageIndex = gvStudent.SelectedIndex;\n    }	0
34074792	34074600	List assigned to Json deserialize is null	{\n    "results":[\n      {"Seat":"5","createdAt":"2015-11-29T18:50:15.320Z","objectId":"BsDSolYPsT","updatedAt":"2015-11-29T19:40:55.020Z"},\n      {"Seat":"6","createdAt":"2015-12-02T22:31:36.892Z","objectId":"kQJ0R5TUvw","updatedAt":"2015-12-02T22:31:36.892Z"},\n      {"Seat":"7","createdAt":"2015-12-02T22:31:40.261Z","objectId":"sVtdj3aipb","updatedAt":"2015-12-02T22:31:40.261Z"},\n      {"Seat":"8","createdAt":"2015-12-02T22:31:43.082Z","objectId":"7oH2ySrDFH","updatedAt":"2015-12-02T22:31:43.082Z"}\n      ]\n}\n\npublic class Result\n{\n    public string Seat { get; set; }\n    public string createdAt { get; set; }\n    public string objectId { get; set; }\n    public string updatedAt { get; set; }\n}\n\npublic class RootObject\n{\n    public List<Result> results { get; set; }\n}	0
30094481	30093979	Deserialize using BinaryReader fails	int myInt = 100;\n        byte[] byteArray = BitConverter.GetBytes(myInt);\n\n        using (MemoryStream stream = new MemoryStream(byteArray)) {\n            using (BinaryReader reader = new BinaryReader(stream)) {\n                var i = reader.ReadInt32();\n            }\n        }	0
20995235	20995192	Access IIS Applications Connection Strings from C#	System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");\n\n        if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)\n        {\n            connString =\n                rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];\n\n            if (connString != null)\n                Console.WriteLine("Northwind connection string = \"{0}\"",\n                    connString.ConnectionString);\n            else\n                Console.WriteLine("No Northwind connection string");\n        }	0
22561730	22561446	Convert charArray to byteArray	validator.Select(c => (byte)c).ToArray()	0
4590285	4590264	Creating a function that will handle objects with common properties	interface IPerson {\n    string Name {get;set;}\n    string Salt {get;set;}\n}\n\nclass Teacher : IPerson...\n\nclass Student : IPerson...\n\npublic string GetEncryptedName(IPerson person)\n{\n //return encrypted name based on Name and Salt property\n return encrypt(person.Salt,person.Name)\n}	0
1049750	1049726	Why Not Close a Database Connection in a Finally Block	using (SqlConnection connection = new SqlConnection(connectionString))\n{\n    SqlCommand command = connection.CreateCommand();\n\n    command.CommandText = "select * from someTable";\n\n    // Execute the query here...put it in a datatable/dataset\n}	0
21599256	21598874	How to display images in datalist from database?	//Find your image control (Image1 lets say) on the item databound event of the datalist.\nByte[] myImage = GetMyImageFromMyDataSource();\nString st = Server.MapPath("myImageNameOrID.jpg"); // Try Name + ID to make it unique\nFileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);\nfs.Write(myImage, 0, myImage.Length);\nfs.Close();\nImage1.ImageUrl = "myImageNameOrID.jpg";	0
11589192	11587400	Reading a XML config file in soap	string applicationPath = HttpContext.Current.Server.MapPath(null);\n  string configPath = Path.Combine(applicationPath, "config.xml");	0
10619085	10619003	How to make the threads run in the correct order	Task.Factory.StartNew(() => tmh1.FillTable()).ContinueWith(() => tmh1.GetGeneralInfo(), TaskScheduler.FromCurrentSynchronizationContext());	0
15599214	15599182	How I can remove old items from list<> for the new run of application	files.Clear(); \nfiles.Add(new upload(FileName,contenttype,bytes));	0
13154372	13153745	How can I pause and continue a TPL task?	static ManualResetEvent mre = new ManualResetEvent(false);\n\nvar Task1=Task.Factory.StartNew(() =>\n{\n    Console.WriteLine("Executing Task 1");\n    Thread.Sleep(2000); //A Long running operation\n    Console.WriteLine("Task 1 Completed");\n    mre.Set(); //signal the task completion to task 2.\n});\n\n\nvar Task2=Task.Factory.StartNew(() =>\n{\n    if (!Task1.IsCompleted) //check if task1 is completed.\n    {\n        mre.WaitOne(); //wait until Task 1 Completes\n        Console.WriteLine("Executing Task 2");\n        Thread.Sleep(2000);\n        Console.WriteLine("Task 2 Completed");    \n        doSomeTask();\n    }\n     else\n    {\n        //Task 1 is already completed\n        doSomeTask();\n    }\n\n});	0
18122367	18122269	Fetching URL Based on InnerText C#	HtmlWeb hw = new HtmlWeb();\nHtmlAgilityPack.HtmlDocument doc = hw.Load(url);\nvar hrefs = doc.DocumentNode.SelectNodes("//a[@href]")\n             .Where(link => link.InnerHtml == str)\n             .Select(l=>l.Attributes["href"].Value).ToList();	0
4092169	4091427	Is there a cleaner/simpler way of doing an equivalent of WHERE a IN (aa, bb, cc)?	var properties = new []{\n  HorizontalContentAlignmentProperty,\n  VerticalContentAlignmentProperty };\n\nvar setters = from setter in Style.Setters.OfType<Setter>() \n              where properties.Contains(setter.Property) \n              select setter;	0
28669815	28669774	How to check string for null and assign its value in the same line	txt_objective.Text = dtReqMas.Rows[0].IsNull("objective") \n                     ? String.Empty : dtReqMas.Rows[0].Field<string>("objective");	0
18870852	18870733	passing a variable to javascript function from code behind	ScriptManager.RegisterStartupScript(this, typeof(string), "Registering", String.Format("RegisterTheUser('{0}');", myVariable), true);	0
5168484	5168404	Arrange Columns in a DataGridView	myGridView.Columns["myFirstCol"].DisplayIndex = 0;\nmyGridView.Columns["mySecondCol"].DisplayIndex = 1;	0
8856831	8841638	Send Direct Messages using twitter API	var service = new TwitterService(consumerKey, consumerSecret, accessToken, accessTokenSecret);\nvar user = service.VerifyCredentials();\nvar result = service.SendDirectMessage(recipient, message);	0
13857990	13855985	Setting custom paging url for Orchard pager shape used in child action	var context = ViewContext.ParentActionViewContext ?? ViewContext;\nViewContext.RouteData = context.RouteData;	0
16870184	16869942	can't sort data int properly with gridview	int num = 11111111;\nstring s = num.ToString("N0");	0
3543714	3543704	WPF Application still runs in background after closing	Application.MainWindow	0
11788067	11787493	How to dynamically change combobox on other combobox value change	**comboBox2.DataSource = null;**\n        if (ComboBox1.Text == "Customers")\n        {\n            var qry = (from u in dc.Customers\n                       select new { u.CustomerID, u.CompanyName }).ToList();\n            comboBox2.ValueMember = "CustomerID";\n            comboBox2.DisplayMember = "CompanyName";\n            comboBox2.DataSource = qry;\n        }\n        if (ComboBox1.Text == "Suppliers")\n        {\n            var qry = (from u in dc.Suppliers\n                       select new { u.SupplierID, u.CompanyName }).ToList();\n            comboBox2.ValueMember = "SupplierID";\n            comboBox2.DisplayMember = "CompanyName";\n            comboBox2.DataSource = qry;\n        }	0
6311024	6309402	C# Drawing in a Panel	private void InitOutput(object output)\n{\n    if (output is Control)\n    {\n        Control c = (Control)output;\n        c.Paint += new System.Windows.Forms.PaintEventHandler(c_Paint);\n        // Invalidate needed to rise paint event\n        c.Invalidate();\n    }\n}\nprivate void c_Paint(object sender, PaintEventArgs e)\n{\n    SolidBrush hb =  new SolidBrush(Color.Red);\n    e.Graphics.FillRectangle(hb, 7, 10, 30 - 19, 5);\n    e.Graphics.DrawString("test", DefaultFont, hb, new PointF(50, 50));\n}	0
18543093	18259087	Chinese Character Issue in AJAX with C# & Jquery	[WebMethod]\n    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]     \n    public Handler1.TicketResponse HelloWorld()\n    {\n        var ticketResponse = new Handler1.TicketResponse();\n        ticketResponse.AddedCount = 23;\n\n        // All tickets were available and were added to the cart\n        ticketResponse.Success = true;\n        ticketResponse.SuccessItems = new List<Handler1.SuccessfullItem>\n                                          {\n                                              new Handler1.SuccessfullItem()\n                                                  {\n\n                                                      OrderItemId = 1,\n                                                      Title = "????????????????"\n                                                  }\n                                          };\n\n        return ticketResponse;\n    }	0
9298052	9285777	mimic jQuery autocomplete with Selenium WebDriver ExecuteScript command	Element.SetHiddenFieldIdViaAutoCompleteJSON(driver, "/admin/discount/ajax-auto-complete/variation", "val", discount.Variation, "id", "variation_id");\n\npublic static void SetHiddenFieldIdViaAutoCompleteJSON(IWebDriver driver, string requestPage, string queryParam, string queryParamValue, string jsonObjectProperty, string hiddenFieldId)\n{\n    IJavaScriptExecutor js = driver as IJavaScriptExecutor;\n    js.ExecuteScript("$.ajax({ url: '" + Config.SITE_URL + requestPage + "',data:{'" + queryParam + "':'" + queryParamValue + "'},dataType:'json',type: 'GET',contentType: 'application/json',success: function(jsonObject) { $('#" + hiddenFieldId + "').val(jsonObject[0]." + jsonObjectProperty + "); } });");\n}	0
23666283	23463088	Compare the values of properties of two objects in LINQ	public static bool Compare(ref List<Student> list1, ref List<Student> list2)\n{\n        return Enumerable.SequenceEqual(list1,list2, new MyCustomComparer());\n}\n\npublic class MyCustomComparer : IEqualityComparer<Student>\n{\n    public bool Equals(Student x, Student y)\n    {\n        if (x.FirstName == y.FirstName && x.LastName == y.LastName && x.University == y.University)\n            return true;\n        return false;\n    }\n\n    public int GetHashCode(Student obj)\n    {\n        throw new NotImplementedException();\n    }\n}	0
12054324	12054209	How to Disabling all button but one in a WPF window	IsEnabled={Binding Path=IsEnabledProperty}	0
20070766	20070585	Split a string into groups	string message = "0123456789";//10char string\n        //string message = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";//161char string\n        int parts = (message.Length/ 153) + (message.Length % 153 > 0 ? 1 : 0);\n        for (int x = 1; x <= parts; x++)\n        {\n            Console.WriteLine("this Msg Part: " + x.ToString());\n            Console.WriteLine("this Msg Part Text:" + message.Substring( (x-1)* 153, message.Length < ((x-1)* 153 + 153) ? message.Length - (x-1)* 153 : 153));\n            Console.WriteLine("Total Msg Parts: " + parts.ToString());\n        }	0
31808913	31808090	Saving Table in database using a ViewModel database-first approach	dbServer.Entry(issue.uTable).State = EntityState.Modified;	0
25928888	25911193	How to find people with direct reports, without showing the direct reports in Active Directory?	DirectorySearcher searcher;\nSearchResultCollection results;\n\nsearcher = new DirectorySearcher();\nsearcher.Filter = "(&(objectClass=user)(objectCategory=person))";\nsearcher.PropertiesToLoad.Add("DirectReports");\nsearcher.PropertiesToLoad.Add("mail");\nsearcher.SearchRoot = utilityDomain;\n\nDictionary<string, string> managerEmailAddresses = new Dictionary<string, string>();\n\nusing (searcher)\n{\n    results = searcher.FindAll();\n\n    foreach (SearchResult result in results)\n    {\n        if (result.Properties["DirectReports"].Count > 0)\n        {\n            DirectoryEntry emp = result.GetDirectoryEntry();\n\n            String mail = "";\n            if (emp.Properties["mail"].Count > 0)\n            {\n                mail = emp.Properties["mail"][0].ToString();\n                string userName;\n                userName= mail.Split('@')[0];\n\n                managerEmailAddresses.Add(userName, mail);\n             }\n         }\n    }\n    return managerEmailAddresses;\n}	0
33900948	33898842	How to serialize XML without writing the type as a tag	public void WriteXml(XmlWriter writer)\n{\n    foreach (TKey key in this.Keys)\n    {\n        writer.WriteStartElement("Option");\n\n        writer.WriteElementString("key", key.ToString());\n\n        TValue value = this[key];\n        writer.WriteElementString("value", value.ToString());\n\n        writer.WriteEndElement();\n    }\n}	0
6495682	6495600	How to Convert VB hex to c# hex	string dd = String.Format("{0:x4}", ExpiryDate.Value.Day);	0
3081392	3081341	Ref argument through a RealProxy	public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)\n{\n    IMethodCallMessage call = msg as IMethodCallMessage;\n    var args = call.Args;\n    object returnValue = typeof(HelloClass).InvokeMember(call.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, _hello, args);\n    return new ReturnMessage(returnValue, args, args.Length, call.LogicalCallContext, call);\n}	0
11165117	11164948	How to update property bound to a textbox?	private void SaveButton_Click(object sender, EventArgs e)\n    {\n        if (NameTextBox.Text == _originalName) return;\n\n        Model.Name = NameTextBox.Text;\n        Model.Save();\n\n        if(NavigationService.CanGoBack) NavigationService.GoBack();\n    }	0
5891099	5891009	Access genereated INPUT Fields	var value = Form["txtThekeUpdate_" + thekenRow["ID"]];\nif (value != null)\n{\n      Data = value;\n}	0
17281832	17281650	Sorting a list alphabetically with lambda after a certain position	list.Take(3).Concat(list.Skip (3).OrderBy (x => x.Name))	0
6786975	6783874	How To Mock/Stub a Nhibernate QueryOver Call?	var queryover = MockRepository.GenerateMock<IQueryOver<Customer>>();\nqueryover.Stub(...).Return(...);\n\ndata.Stub(x => x.CustomersAsQueryOver).Return(queryover);	0
10903063	10902571	Retrieve [Display] Attribute Name in HTML Helper	ModelMetadata metadata = ModelMetadata.FromLambdaExpression(property, helper.ViewData);\nstring htmlFieldName = ExpressionHelper.GetExpressionText(property);\nstring labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();\nif (!String.IsNullOrWhiteSpace(labelText))\n    // labelText contains the label	0
19000486	18961325	c# EWS 2007 Adress from empty	EmailMessage messageInfo = EmailMessage.Bind(useService, item.Id);	0
25214802	25214753	Working on a C# hangman game, cant figure out how to detect multiple letters	if (j.Equals(leguess))// If the character = the letter guess\n{\n    int index = word.IndexOf(j);// Get the index of j\n    while (index > -1)\n    {\n        guess = guess.Remove(index, 1).Insert(index, j.ToString());\n        index = word.IndexOf(j, index + 1);\n    }\n}	0
22389006	22238054	Hide icon in title bar but not in task bar	using(Bitmap emptyImage = new Bitmap(1, 1))\n    Native.SendMessage(this.Handle, Native.WM_SETICON, Native.ICON_SMALL, emptyImage.GetHicon());	0
11403556	11403511	Translate values for SI_SCHEDULE_STATUS in XI query builder	COMPLETE 1 \nFAILURE  3 \nPAUSED   8 \nPENDING  9 \nRUNNING  0	0
20920806	20920736	how object members work in c#	public class Two\n{\n    public string Three {get;set;}\n }\n\n  public class One\n  {\n       public Two Two {get;set;}\n   }\n\n  public class Abc\n  {\n      public One One {get;set;}\n   }\n\n   //result.One.Two.Three	0
32990982	32990286	Persisting text as byte array to flat file	string publicKey = "AsdfsSDhysffsdfsdfZ09";\nConsole.Write("byte[] keyBytes = { ");\nConsole.Write(String.Join(", ", Array.ConvertAll(Encoding.ASCII.GetBytes(publicKey), b => String.Format("0x{0:X2}", b))));\nConsole.WriteLine("};");	0
8248256	8153286	Buffering log messages in NLog and manually flushes them to target	LogManager.Configuration.AllTargets\n    .OfType<BufferingTargetWrapper>()\n    .ToList()\n    .ForEach(b => b.Flush(e =>\n        {\n            //do nothing here\n        }));	0
7886619	7886592	How to get the auto incremented value in entity framework code first	product.Id	0
2966734	2966696	How do I make a button on a form behave like a button on a toolStrip? VS2008	toolStrip1.Dock = DockStyle.None;\ntoolStrip1.AutoSize = true	0
15050934	15050810	double[] -> double[,]	double[,] target = { { /* your list of values */ } };	0
7372587	7372481	Conversion of Coldfusion Date format to C Sharp format	DateTime before = DateTime.Now;\n\n// Some DB Operation here\n\nTimeSpan elapsed = DateTime.Now - before;\n\nConsole.Write(elapsed);	0
23951961	23924424	Read text file in project folder in Windows Phone 8.1 Runtime	string fileContent;\nStorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///example.txt"));\nusing (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))\nfileContent = await sRead.ReadToEndAsync();	0
21782045	21781994	named argument specifications must appear after all fixed arguments gave been specified	return View(unitOfWork.roleRepository.Get(s => s.OrderBy(z => z.Id), 15, p => p.Id == 1, u => u.RoleName != "null"));	0
9572718	9572591	Create A Method To Iterate Through Objects Properties	foreach(var propInfo in o.GetType().GetProperties())\n{\n    var dmAttr = propInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;\n    if (dmAttr == null)\n        continue;\n\n    object propValue = propInfo.GetValue(o, null);\n    if (dmAttr.IsRequired && propValue == null)\n        // It is required but does not have a value... do something about it here\n}	0
11757635	11757335	How to implement 3 tier approach using Entity Framework?	//DAL\npublic class DataAccess\n{\n    public static void GetCustomerByNumber(int number)\n    {\n        var objCustomer = dbContext.Customers.Where(c => c.CustCode == number).First();\n        return objCustomer;\n    }\n}\n\n//Models\npublic class Customer\n{\n    public string Name { get; set; }\n    public int Number { get; set; }\n\n    public Customer GetCustomerByNumber(int number) \n    {\n       return DataAccess.GetCustomerByNumber(number);\n    }\n\n    public void ChangeProfile(ProfileInfo profile)\n    {\n       //...\n    }\n}	0
1913596	1913552	C# Conversion of CSV to XML using LINQ	var xmlFile = new XElement("root", \n        from line in File.ReadAllLines(@"d:\sample.txt")\n        where !line.StartsWith("#") && line.Length>0\n        let parts=line.Split(',')\n        select new XElement("book",\n                            new XElement("ISBN",parts[0]),\n                            new XElement("Title",parts[1])\n                           )\n        );	0
14819452	14816439	Best OR/M for use with Interfaces	// mappings\npublic class FooMap : ClassMap<Foo>\n{\n    public FooMap()\n    {\n        Map(f => f.Name);\n        HasMany(f => f.Bars).KeyColumn("foo_Id");\n    }\n}\n\npublic class BarMap : ClassMap<Bar>\n{\n    public BarMap()\n    {\n        Map(f => f.Name);\n    }\n}\n\n// query\nvar john = session.Query<IFoo>()\n    .Where(f => f.Name == "John")\n    .Fetch(f => f.Bars)\n    .Single();\n\nConsole.Writeline(john.Bars.Count);	0
18071694	18071411	C# Winforms: Attach Scrollbar to Control	//inside your custom control class\nprotected override void OnMouseWheel(MouseEventArgs e){\n   vScrollBar1.Value += e.Delta > 0 ?  -vScrollBar1.LargeChange : vScrollBar1.LargeChange;\n}	0
10685579	9933460	Flash Socket connected, but not sending data	NetworkStream ns = clientTCP.GetStream();\nStreamWriter sw = new StreamWriter(ns);\nsw.WriteLine("<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0");\nsw.Close();	0
7900506	7900474	When closing forms close how to close all opened MessageBoxes	user32.MessageBox	0
1170316	1170311	Protecting class in a namespace	public class A\n{\n  private class B { ... }\n  ...\n}	0
23203582	23203503	Json.net custom serializer ; ouput without double/simple quote	JSON.parse()	0
20650798	20650259	Replace null value with default text	foreach (DataRow row in dataset.Tables[0].Rows)\n        {\n            if (row["USER_COMMENT"] is System.DBNull)\n            {\n                row["USER_COMMENT"] = "NO DATA";\n                Console.WriteLine("In if");\n            }\n            else\n            {\n                Console.WriteLine("out if");\n            }\n        }	0
32571188	32570201	LINQ: add/sum all timespans in a collection together	var model = _db.Tracks\n      .Where(r => r.UserID == WebSecurity.CurrentUserId)\n      .Select(x => new\n      {\n          averagePace = Math.Round(26.8224 / x.locations.Average(y => y.speed), 2),\n          createdDate = x.createdDate,\n          FirstName = x.UserProfile.FirstName,\n          totalDistance = x.totalDistance,\n          totalDuration = x.totalDuration,\n          trackId = x.TrackID\n      }).ToList()\n      .Select(x => new iOSHistoryListViewModel{\n          averagePace = x.averagePace,\n          createdDate = x.createdDate,\n          FirstName = x.FirstName,\n          totalDistance = Math.Round(x.totalDistance / 1609.344, 2),\n          totalDuration = TimeSpan.FromSeconds(x.totalDuration),\n          trackId = x.trackId\n      })\n      .OrderByDescending(x => x.createdDate)\n      .ToList();	0
6451499	6451298	Downloading ZIP file from FTP and copying to folder within website	try\n{\n    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddr + "test.zip");\n    request.Credentials = new NetworkCredential(userName, password);\n    request.UseBinary = true; // Use binary to ensure correct dlv!\n    request.Method = WebRequestMethods.Ftp.DownloadFile;\n\n    FtpWebResponse response = (FtpWebResponse)request.GetResponse();\n    Stream responseStream = response.GetResponseStream();\n    FileStream writer = new FileStream("test.zip", FileMode.Create);\n\n    long length = response.ContentLength;\n    int bufferSize = 2048;\n    int readCount;\n    byte[] buffer = new byte[2048];\n\n    readCount = responseStream.Read(buffer, 0, bufferSize);\n    while (readCount > 0)\n    {\n        writer.Write(buffer, 0, readCount);\n        readCount = responseStream.Read(buffer, 0, bufferSize);\n    }\n\n    responseStream.Close();\n    response.Close();\n    writer.Close();\n\n}\ncatch (Exception e)\n{\n    Console.WriteLine(e.ToString());\n}	0
18658383	18658340	Convert a large number, from Base 256 to Base 10	BigInteger(byte[])	0
18129714	18126793	Dynamic binding to CheckedListBox using entity model	((ListBox)lstchkTax).DataSource=ObjTax;\n((ListBox)lstchkTax).DisplayMember="CategoryName";\n((ListBox)lstchkTax).ValueMember="CategoryId";	0
19067685	19067580	Saving a file to project folder and save its path	private void button1_Click(object sender, EventArgs e)\n        {\n             var openFileDialog=new OpenFileDialog {Filter = @"Zip Files|*.zip|RAR Files|*.rar|All Files|*.*"};\n\n            if (DialogResult.OK == openFileDialog.ShowDialog())\n            {\n                File.Copy(openFileDialog.FileName, Application.StartupPath + @"\" \n                    + Path.GetFileName(openFileDialog.FileName));\n\n                yourvariable = Application.StartupPath + @"\"\n                               + Path.GetFileName(openFileDialog.FileName);\n            }\n        }	0
7417213	7417040	Why does formatting a DateTime as a string truncate and not round the milliseconds?	new DateTime(2011, 1, 1, 23, 59, 59, 999)	0
28707150	28687959	Multiple Binding updates from ViewModel	private async Task UpdateProcess()\n    {\n        UpdateStatus("Updating Database");\n        await Task.Run(UpdateDatabaseMethod);\n        UpdateStatus("Database updated");\n    }\n\n    private void UpdateDatabaseMethod()\n    {\n        //Do long-running stuff in background...\n        //Note that this will no longer be executing in the UI thread\n        //so you may need to watch out for thread safety issues that you could previously ignore\n        //This might mean adding some locks around your database access methods...\n    }	0
27903793	27902358	sqlite count results based whitin timeline	WITH RECURSIVE\nmin_time(t) AS (\n  SELECT datetime((strftime('%s',\n                            (SELECT MIN(Connection_Time)\n                             FROM currentUsers)\n                  ) / 300) * 300,\n                  'unixepoch')\n),\nmax_time(t) AS (\n  SELECT datetime((strftime('%s',\n                            (SELECT MAX(Last_Access)\n                             FROM currentUsers)\n                  ) / 300) * 300,\n                  'unixepoch')\n),\nintervals(t) AS (\n  SELECT t FROM min_time\n  UNION ALL\n  SELECT datetime(t, '+15 minutes')\n  FROM intervals\n  WHERE t <= (SELECT t FROM max_time)\n)\nSELECT t AS interval,\n       (SELECT COUNT(DISTINCT UserName)\n        FROM currentUsers\n        WHERE Connection_Time < datetime(intervals.t, '+15 minutes')\n          AND Last_Accessed >= intervals.t\n       ) AS Count\nFROM intervals;	0
18857222	18856424	How to subscribe on Resource Exhaustion Diagnosis Events?	System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("System", ".", "Resource-Exhaustion-Detector");\neventLog.EnableRaisingEvents = true;\neventLog.EntryWritten += eventLog_EntryWritten;\n\nstatic void eventLog_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)\n{\n   if (e.Entry.Message.Contains(Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)))\n   {\n      Logger.Error("Our application consumed too much memory `{0}`. So we stopping work right now to prevent reboot OS.", new object[] {e.Entry.Message},MethodBase.GetCurrentMethod());\n      GC.Collect();\n      //do smth                \n   }\n}	0
6843800	6843697	|DataDirectory| in Project properties > Settings	AppDomain.SetData()	0
15536075	14224765	How to pass a C# UIViewController to a C function receiving a UIViewController *	public class MyUI\n{\n    [DllImport("__Internal")]\n    protected extern static void MyUIInit(IntPtr viewController);\n\n    public MyUI(MonoTouch.UIKit.UIViewController viewController)\n    {\n        MyUIInit(viewController.Handle);\n    }\n}	0
28739216	28736553	How can I create a one time cron schedule that would execute only once in C#?	ITrigger trigger = TriggerBuilder.Create()\n                               .WithDescription("Once")\n                               .WithSimpleSchedule(x => x\n                               .WithIntervalInSeconds(40)\n                               .RepeatForever())\n                               .StartAt(DateBuilder.DateOf(14, 41, 00, 26, 2, 2015))\n                               .EndAt(DateBuilder.DateOf(15, 14, 20))\n                               .Build();	0
20402275	20402141	How to achieve transaction-like behavior for non-database operations?	using (IDbTransaction tran = conn.BeginTransaction()) {\n    try {\n\n        ...Delete File From DB Code...  // statement 2\n        MyClass.DeleteFile(fileId);             // statement 1\n\n        tran.Commit();\n    }  catch {\n        tran.Rollback();\n        throw;\n    }\n}	0
33774534	33770429	How do I find the local IP address on a Win 10 UWP project	private string GetLocalIp()\n{\n    var icp = NetworkInformation.GetInternetConnectionProfile();\n\n    if (icp?.NetworkAdapter == null) return null;\n    var hostname =\n        NetworkInformation.GetHostNames()\n            .SingleOrDefault(\n                hn =>\n                    hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId\n                    == icp.NetworkAdapter.NetworkAdapterId);\n\n    // the ip address\n    return hostname?.CanonicalName;\n}	0
3057978	2994220	Can you open a form or window in an Outlook Addin (VSTO)	Form myFrm = new frmFlightList();\nmyFrm.Show();	0
26119135	26118964	Validate and select entity set data in LINQ	var date = new DateTime(2014, 1, 1);\nvar result = from r in db.Table\n             where r.start_date > date\n             && r.start_date.AddMonths(3) == r.end_date\n             select r	0
15585875	15585684	Switch gears from TSQL to LINQ	var result = from ea in SimEA\n         join e in SimE\n         on ea.EmailID equals e.EmailMsgID\n     where ea.UserId = userId\n         select new { properties you want here or new object based on properties}	0
7374190	7374172	Determining condition of a checkbox in an event handler	if(((CheckBox)sender).Checked)	0
33461527	33451251	updating all list items	foreach (Sprite children in player.children) // player.children is the sprite list\n{\n    children.millisecondsPerFrame = value; // I assign the millisecondsPerFrame float value\n}	0
13149613	13148049	Windows 8 App, insert text into Search charm?	Windows.ApplicationModel.Search.SearchPane searchPane =\n     Windows.ApplicationModel.Search.SearchPane.GetForCurrentView();\nsearchPane.TrySetQueryText("default text");	0
25645466	25645361	Sum Of a column of generic list by passing column name anonymously	lbl.Text = list.Sum(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToString();	0
31912438	31911540	Mapping MultiList using Glass Mapper	[SitecoreType(TemplateId = DCP.Resources.TemplateIDS.CategoryTemplateID, AutoMap = true)]\npublic class ContentCategory : SCItem\n{\n   [SitecoreField(FieldName = "Category name")]\n   public virtual string CategoryName { get; set; }\n   [SitecoreField(FieldName = "Category icon")]\n   public virtual Image CategoryICON { get; set; }\n\n   [SitecoreField(FieldName = "text")]\n   public virtual string Text { get; set; }\n}	0
16045965	16020651	Windows Store App MediaCapture Simulator Crash	MediaCaptureInitializationSettings _cameraSettings1 = new MediaCaptureInitializationSettings();\n            _cameraSettings1.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;\n            await _mediaCapture.InitializeAsync(_cameraSettings1);	0
22333040	22332956	LINQ to create a calculated value based on the value of two other columns	context.People.Select(p => new {cv = p.DisplayName ?? p.RealName});	0
25304986	25304876	How can I read all files from directory and put in an existing datagrindview	// Declare an array, in which you will store the contents of your file.\nstring[] contents = new string[Files.Length];\n\n// For each file in you Files collection read it's contents and add it to the contents array\n for(int i=0; i<contents.Length; i++)\n     contents[i] = System.IO.File.ReadAllText(Files[i]);\n\n// Set the datasource of your data grid view and databind it.\ndataGridView1.DataSource = contents;\ndataGridView1.dataBind();	0
29601498	29601329	How to add more than one event for button click within a single event handler in Expression Blend?	private string _lastState = "DefaultState" \n\npublic void MyClickHandler()\n{\n    ChangeState();\n}\n\nprivate void ChangeState()\n{\nSwitch (_lastState)\ncase "Default": _lastState = "Red";\n            _myControl.Backgroung = Red; \ncase "Red": _lastState = "Yellow";\n            _myControl.Backgroung = Yellow;\ncase "Yellow": _lastState = "Green";\n            _myControl.Backgroung = Green;\n\n\n.. and so on..\n\n}\n\nwhere _myControl is your state .. may be just a string variable..\n\n}	0
19579282	19579187	Sending credentials with HttpWebRequest	request.Method = "POST";\nrequest.ContentType = "application/x-www-form-urlencoded";\nusing (var writer = new StreamWriter(request.GetRequestStream()))\n{\n    writer.Write("email=" + HttpUtility.UrlEncode(email));\n    writer.Write("&password=" + HttpUtility.UrlEncode(password));\n}	0
9636338	9635531	DDD and Repository pattern where to put behavior concerning CRUD	public enum UpdateResult\n    {\n         Success,\n         NoMyEntityFound,\n         StaleData,\n         InvalidRequest\n    }\n\n\npublic class MyService\n{\n\n\n     ...\n     ...\n\n\n     public UpdateResult Update(...)\n     {\n          ...Start Tran\n          ...Load var m = MyEntity\n          ...do the bare minimum here \n          ...m.Update()\n          ...Commit Tran\n\n          return UpdateResult.Success;\n     }\n\n}	0
24117470	24117372	how to automatically update label using thread	private void run(string data) {\n\n    //if (this.labelO2.InvokeRequired)\n    //{\n    //    SetRichBoxCallBack d = new SetRichBoxCallBack(run);\n    //    this.Invoke(d, new object[] { data });\n    //}\n    //else {\n    //    labelO2.Text = data;\n    //}\n\n    this.Invoke(new MethodInvoker(delegate {labelO2.Text = data;}));\n\n}	0
2017540	2017533	Best way to check if column returns a null value (from database to .net application)	if (! DBNull.Value.Equals(row[fieldName])) \n   {\n      //not null\n   }\n   else\n   {\n      //null\n   }	0
6118980	6118904	Substring without breaking html c#	var document = new HtmlDocument();\ndocument.LoadHtml("...");\ndocument.DocumentNode.InnerText;	0
5260280	5260209	Is it possible to use Regex to extract text from attributes repeated in a text file - c# .NET	(appid="(?<AppID>[^"]+)" appname="(?<AppName>[^"]+)" supportemail="(?<SupportEmail>[^"]+)")	0
15601027	15601006	How can I seed data in a for loop with C#	var names = new[] {"A", "B", "C"};\nvar apps = names.Select(x => new Application { Name = x });\napplications.AddRange(apps);	0
13261065	13242945	converting textbox string to int	private void button1_Click(object sender, EventArgs e)\n    {\n\n\n        int result = Convert.ToInt32(textBox4.Text); int x, z;\n\n        if (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text) == result)\n        {\n            correct++;\n            numbercorrect.Text = correct.ToString();\n            Randomnumber.Next(12);\n            textBox2.Text = Randomnumber.Next(12).ToString();\n            textBox3.Text = Randomnumber.Next(12).ToString();\n\n        }	0
3878607	3878590	Message box pops up evertime	public void errorcheck(int val)\n{\n\n        if (val == 0)\n        {\n            MessageBox.Show("Enter a number between 1 -20");\n        }\n\n}\n\nprivate void nudTwoByTwo_1_ValueChanged(object sender, EventArgs e)\n{\n    if (cbTwoBytwo.Checked)\n        errorcheck((int)nudTwoByTwo_1.Value);\n}\n\nprivate void nudTwoByTwo_2_ValueChanged(object sender, EventArgs e)\n{\n    if (cbTwoBytwo.Checked)\n        errorcheck((int)nudTwoByTwo_2.Value);  \n}	0
20955892	20955833	Error with download a file from https using webclient	ServicePointManager.ServerCertificateValidationCallback\n += (sender, certificate, chain, sslPolicyErrors) => true;	0
17518800	17518799	Compiler says I cannot take the address of a value type's field	struct S {\n    public int Value1;\n    public int Value2;\n}	0
29164125	29139313	How to schedule a toast notification for a specific date and time in windows 8 app?	int x = int.Parse(NewEventYear.SelectedItem.ToString());          \nint y = int.Parse(NewEventMonth.SelectedItem.ToString());\nint z = int.Parse(NewEventDate.SelectedItem.ToString());\nint a = int.Parse(NewEventHour.SelectedItem.ToString());\nint b = int.Parse(NewEventMinutes.SelectedItem.ToString()); \n\nDateTime EventDate = new DateTime(x,y,z,a,b,0)\nTimeSpan NotTime = EventDate.Subtract(DateTime.Now);\nDateTime dueTime = DateTime.Now.Add(NotTime);\n\nScheduledToastNotification scheduledToast = new ScheduledToastNotification(toastXml, dueTime);\nToastNotificationManager.CreateToastNotifier().AddToSchedule(scheduledToast);	0
10631713	10630828	Adding Items to ToolStrip at RunTime	private void buttonAddFav_Click(object sender, EventArgs e)\n    {\n        ToolStripItem item = new ToolStripMenuItem();\n        //Name that will apear on the menu\n        item.Text = "Jhon Smith";\n        //Put in the Name property whatever neccessery to retrive your data on click event\n        item.Name = "GridViewRowID or DataKeyID";\n        //On-Click event\n        item.Click += new EventHandler(item_Click);\n        //Add the submenu to the parent menu\n        favToolStripMenuItem.DropDownItems.Add(item);\n    }\n\n    void item_Click(object sender, EventArgs e)\n    {\n        throw new NotImplementedException();\n    }	0
16165077	16164923	Read txt file from line to line to list?	// Retrieve 10 lines from Somefile.txt, starting from line 1\nstring filePath = "C:\\Somefile.txt";\nint startLine = 1;\nint lineCount = 10;\nvar fileLines = System.IO.File.ReadAllLines(filePath)\n                .Skip((startLine-1))\n                .Take(lineCount);	0
9521348	9427849	Jagged Uint8 array convert to C# byte	byte[][] ras = new byte[][] {new byte[] {1,2,3}, new byte[] {4,5,6}};	0
5721478	5706225	Facebook Album Picture using Facebook C# SDK	FacebookClient client = new FacebookClient(this.Profile.AccessToken);\n        client.QueryAsync(String.Format("SELECT src_small, src_big, src FROM photo WHERE pid IN (SELECT cover_pid FROM album WHERE object_id={0})", this.ID));\n        client.GetCompleted += (s, e) =>\n        {\n            dynamic result = e.GetResultData();\n\n            Deployment.Current.Dispatcher.BeginInvoke(() => this.Picture = result[0].src_small);\n        };	0
28427449	28427347	Run method several times and delay one by a few seconds	private static void Main()\n{\n    SettingsComponent.LoadSettings();\n\n    while (true)\n    {\n        try\n        {\n             for(int x=0; x<4 ; x++){\n                GenerateRandomBooking(); // Will call 5 times\n             }\n\n             Thread.Sleep(2000) // 2 seconds sleep\n\n             GenerateRandomBids();\n\n             AllocateBids();           \n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(e.ToString());\n        }\n\n    }\n}	0
20867518	20866976	Converting XAML element to Image in silverlight?	//Convert UIElement to Image\nei = ImageExtensions.ToImage(myCanvas);\n\n//Save the image\nSaveFileDialog saveDlg = new SaveFileDialog();\nsaveDlg.Filter = "JPEG Files (*.jpeg)|*.jpeg";\nsaveDlg.DefaultExt = ".jpeg";\nif ((bool)saveDlg.ShowDialog())\n{\n    using (Stream fs = saveDlg.OpenFile())\n    {\n        ei.WriteToStream(fs);\n    }\n}	0
14697478	14696730	How do you get ASP.NET to insert a database record when a user logs in?	SqlConnection connection = new SqlConnection(connectionString))\nSqlCommand command = new SqlCommand(queryString, connection);\n\nconnection.Open();\nSqlDataReader reader = command.ExecuteQuery();	0
15170223	15170214	Remove words from string if they're NOT in a c# dictionary	var s = "5 x 3".Where(c => !operators.ContainsValue(c.ToString())).ToArray();\nstring NotInDictionary = new string(s);	0
26164211	26164015	Local machine registry shows wrong IE version	Version: 9.11.9600.17239\nW2kVersion: 9.11.9600.17239\nsvcUpdateVersion: 11.0.11\nsvcVersion: 11.0.9600.17239	0
17617411	17615617	How to click the DOM element in selenium webdriver thru C#	driver.FindElement(By.XPath("//input[@value='Individual']")).Click();	0
24033001	24032574	Streaming mp3 file from external server	private bool isMediaLoaded = false;\nprivate bool isPlayCalled = false;\nprivate void PlayMP3()\n{\n    if(isMediaLoaded)\n       media.Play();\n    else\n       isPlayCalled = true;\n}\nvoid MediaElement1_MediaOpened(object sender, RoutedEventArgs e)\n{\n    isMediaLoaded = true;\n    if(isPlayCalled)\n        MediaElement1.Play();\n\n}	0
1004319	1004300	How to read .net xml serialized datetimes from java?	import java.text.SimpleDateFormat;\nimport java.util.Date;\n\n\nSimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");\nDate d = sdf.parse("2009-05-11T16:47:08.6033346-04:00");	0
15777104	15291094	How I can control the Zoom ability of a chart in winform C#?	var ca = chart1.ChartAreas["ChartArea1"].CursorX;\nca.CursorX.IsUserEnabled = false;\nca.CursorX.IsUserSelectionEnabled = false;	0
9095223	9095190	Select n objects from collection based on ranked value	var bestAs = aList.OrderByDescending(a => a.x).Take(n);	0
5978941	5970758	I'm getting a NotImplementedException when trying to call a Reporting Services Web Method	ParameterValue[] values = null;\nDataSourceCredentials[] credentials = null;\nReportParameter[] parameters = null;	0
9028808	9028781	Get ImageSource from Bitmap?	public static Brush CreateBrushFromBitmap(Bitmap bmp)\n{\n    return new ImageBrush(Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()));\n}	0
3423032	3423018	How to not include line breaks when comparing two strings	string1.Replace("\n", "") != string2.Replace("\n", "")	0
686148	686132	Opening a form in C# without focus	protected override bool ShowWithoutActivation\n{\n    get\n    {\n        return true;\n    }\n}	0
248017	247946	Handling a Click for all controls on a Form	void initControlsRecursive(ControlCollection coll)\n { \n    foreach (Control c in coll)  \n     {  \n       c.MouseClick += (sender, e) => {/* handle the click here  */});  \n       initControlsRecursive(c.Controls);\n     }\n }\n\n/* ... */\ninitControlsRecursive(Form.Controls);	0
3615400	3615364	How to create stored procedure in sql server and call that procedure from C# code behind with some parameters to that procedure	CREATE FUNCTION spherical_distance(@a float, @b float, @c float)\nRETURNS float\nAS\nBEGIN\n    RETURN ( 6371 * ACOS( COS( (@a/@b) ) * COS(  (Lat/@b)  ) * COS( ( @c/@b ) - (@c/@b) )  + SIN( @a/@b ) * SIN(  @a/@b  ) ) )    \nEND	0
34106724	33996399	Can Oxyplot be used in a Unit Test Library (C#)	PlotModel model = new PlotModel() { Title = "Sample"};\n            model.IsLegendVisible = true;\n            model.LegendPosition = LegendPosition.RightMiddle;\n            model.LegendPlacement = LegendPlacement.Outside;\n            model.PlotType = PlotType.XY;     \n            using (var stream = File.Create(Environment.CurrentDirectory + "/image.png"))\n            {\n                OxyPlot.Wpf.PngExporter exporter = new OxyPlot.Wpf.PngExporter() { Width = 2200, Height = 1400, Resolution = 200 };\n                exporter.Export(model, stream);\n            }	0
18646905	18643936	Background colors in devexpress grid - winforms grid	private void dataGrid_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)\n    {\n        if (e.RowHandle >= 0)\n        {\n            ColumnView View = dataGrid.MainView as ColumnView;\n            DevExpress.XtraGrid.Columns.GridColumn col = View.Columns["ID"];\n            if (Convert.ToInt32(gridView1.GetRowCellValue(e.RowHandle, col)) % 2 == 0)\n            {\n                e.Appearance.BackColor = Color.LightCyan;\n            }\n            else\n            {\n                e.Appearance.BackColor = Color.White;\n            }\n        }\n    }	0
15342568	15342352	How to change username using mvc4 and simplemembership	WebSecurity.InitializeDatabaseConnection("DBname", "UserProfileTable", "IdColumn", "UsernameColumn", autoCreateTables: true);	0
22249972	22249700	how to add options in combobox in C# from mysql database column	string MyConString = "SERVER=localhost;" +\n                     "DATABASE=yourDB;" +\n                     "UID=root;" +\n                     "PASSWORD=yourPassword;";\nMySqlConnection connection = new MySqlConnection(MyConString);\nstring command = "select wine from menu-list";\nMySqlDataAdapter da = new MySqlDataAdapter(command,connection);\nDataTable dt = new DataTable();\nda.Fill(dt);\nforeach (DataRow row in dt.Rows)\n{\n   string wine = string.Format("{0}", row.Item[0]);\n   yourCombobox.Items.Add(wine);\n}\nconnection.Close();	0
1438327	138133	Is there a standard framework for .NET parameter validation that uses attributes?	public Rational(int numerator, int denominator)\n{\n    Contract.Requires(denominator ! = 0);\n\n    this.numerator = numerator;\n    this.denominator = denominator;\n}	0
13227771	13223629	How do I write DllGetClassObject as a C# delegate?	[UnmanagedFunctionPointer(CallingConvention.StdCall)]\npublic delegate uint DllGetClassObjectDelegate(\n    [MarshalAs(UnmanagedType.LPStruct)]\n    Guid rclsid,\n    [MarshalAs(UnmanagedType.LPStruct)]\n    Guid riid,\n    [MarshalAs(UnmanagedType.IUnknown, IidParameterIndex=1)]\n    out object ppv\n);	0
20045806	20045733	Sum in crystal report accordind to field data?	sum( CCur({ MycolumnName}) )	0
26943693	26942057	Excel Sheets into multiple C# datatables	for (int j = 0; j < excelSheets.Length; j++)\n    {\n        DataSet dataSet = new DataSet();\n        string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]");\n        .....\n    }	0
25416586	25416453	How to use the same key for the same task (Mouse Input)	if (option.Button1.Contains(MousePosition))\n{\n   if (mouseState.RightButton == ButtonState.Pressed)\n    {\n       graphics.IsFullScreen = !graphics.IsFullScreen;\n       graphics.ApplyChanges();\n    }\n }	0
13522371	13522207	How to add a custom component in real-time?	My_Namespace.My_Custom_Component my_component = new My_Namespace.My_Custom_Component();	0
11223469	11223413	c# date time format for SQL_Latin1_General_CP1_CI_AS	string SQLst = "UPDATE [LASTUPDATE] SET last_update = CONVERT(datetime, '"+DateTime.Now.ToString("yyyy-MM-dd")+"', 120)	0
3193266	3190553	Property Grid Color Picker control not allowing custom color editing	Define Color	0
2313011	2308374	LINQ JOIN + GROUP BY + SUM	var itineraryItems = from ii in this.ItineraryItemRecords \n   join t in this.TransactionRecords on ii.OperatorID equals t.TransactionActor.OperatorID \n   into g \n   select new \n   { \n       OperatorID = ii.OperatorID \n       //, TotalBuy = g.Sum(i => ii.TotalBuy) \n       , TotalBuy = g.Sum(i => i.TotalBuy) \n       //, TotalSell = g.Sum(i => ii.TotalSell) \n       , TotalSell = g.Sum(i => i.TotalSell) \n       , PaidTC = (0 - (g.Sum(t => t.AmountTC))) \n       , PaidAUD = (0 - (g.Sum(t => t.AmountAUD))) \n   };	0
7604305	7603519	Best way to populate SelectList for ViewModel on GET/POST	private SelectList GetFooTypesList()\n{\n    return new SelectList(repository.GetFooTypes(), "Id", "Value);\n}	0
32884221	32883569	How can I move mailItem from 1 store to another	Sub MoveItems() \n Dim myNameSpace As Outlook.NameSpace \n Dim myInbox As Outlook.Folder \n Dim myDestFolder As Outlook.Folder \n Dim myItems As Outlook.Items \n Dim myItem As Object \n\n Set myNameSpace = Application.GetNamespace("MAPI") \n Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox) \n Set myItems = myInbox.Items \n Set myDestFolder = myInbox.Folders("Personal Mail") \n Set myItem = myItems.Find("[SenderName] = 'Eugene'") \n While TypeName(myItem) <> "Nothing" \n  myItem.Move myDestFolder \n  Set myItem = myItems.FindNext \n Wend \nEnd Sub	0
23216154	23192696	Write to a File using CsvHelper in C#	var csv = new CsvWriter(writer);\ncsv.Configuration.Encoding = Encoding.UTF8;\nforeach (var value in valuess)\n{\n     csv.WriteRecord(value);\n}\nwriter.Close();	0
11570972	11570874	Writing an image file from array of xyz coordinate	System.Drawing.Bitmap myMap = new System.Drawing.Bitmap(200,300); //200x300 pixels	0
2747471	2745372	Getting an entity from a repository by a custom string	class Patient {\n  int Id {get;set;}\n  string PatientName {get;set;}\n}\n...\nActionResult SomeAction([MyCustomBinder("PatientName")] Patient patient) {...}	0
8503434	8503319	Creating DataTable variable without explicitly referencing to the DataSet	using AddressDataTable = UsersDataSet.AddressDataTable ;	0
11298576	11263787	How do I get the email address of the author of a SharePoint list item?	SPFieldUserValue userValue = \n    new SPFieldUserValue(web, item[SPBuiltInFieldId.Author].ToString());\nSPUser user = userValue.User;\nstring email = user.Email;	0
554315	553905	how to expand flagged enum	Keys key = Keys.Control | Keys.Shift | Keys.D;\n\nforeach (string s in key.ToString().Split(','))\n{\n    Keys k = (Keys) Enum.Parse(typeof(Keys), s.Trim());\n\n    Console.WriteLine(k);\n}	0
34007368	34007115	C# - parse xml nodes	var nodeList = Xmldocument.SelectNodes("level/info/ground/point");	0
20652512	20652416	Entity Framework is trying to save the Foreign key tables along with the entity save. How to prevent that?	[DataContract]\npublic class CounterpartyFrequency : EntityBase\n{\n    [DataMember]\n    [Key]\n    public int CounterpartyFrequencyId { get; set; }\n\n    [DataMember]\n    public string LegalEntityId { get; set; }\n\n    [ForeignKey("LegalEntityId")]\n    public virtual LegalEntity LegalEntity { get; set; }\n}	0
21996729	21996574	Formatting a number in C#(not VB) to show commas	var number = "128989899";\nConsole.WriteLine(String.Format("{0:N0}", Int32.Parse(number)));	0
13530564	13530314	Write XML in a string c#	string textresult = xdoc.ToString();	0
11261594	11261468	Why changing SelectedItem in one Combo changes all other Combos?	foreach (Control c in this.Controls)\n{\n    if (c is ComboBox)\n    {\n        DataTable dtTemp = DataSet1.Tables[0].Copy();\n        (c as ComboBox).DataSource = dtTemp \n        (c as ComboBox).DisplayMember = "Articles";\n    }\n}	0
12801611	12801488	Populating a DTO class List<> with ENtity Framework query	var dtoEntity = repo.RelatedClient.SingleOrDefault(x => x.LeadCode == ClodeCode);\n\nDTO d = new DTO();\nd.ClientName = dtoEntity.ClientName;\nforeach (var relatedCode in dtoEntity.RelatedCodes)\n{\n    d.RelatedCodes.Add(relatedCode);\n}\n\nreturn d;	0
18701389	18696130	ASP.NET / DotNetNuke - Prepend HTML to the body from of a User Control	var tp = (CDefault)Page;\ntp.Title = curArticle.Title;	0
5613134	5610887	Where is the best place to map from view model to domain model?	// Web layer (Controller)\npublic ActionResult Add(AddPersonViewModel viewModel)\n{\n    service.AddPerson(viewModel.FirstName, viewModel.LastName)\n    // some other stuff...\n}\n\n// Service layer\npublic void AddPerson(string firstName, string lastName)\n{\n    var person = new Person { FirstName = firstName, LastName = lastName };\n    // some other stuff...\n}	0
11946446	11946143	How to make custom border for a Form without Title Bar?	private void Form1_Paint(object sender, PaintEventArgs e)\n{\n   e.Graphics.DrawRectangle(new Pen(Color.Black, 3),\n                            this.DisplayRectangle);                                     \n}	0
6233490	6233482	How do I set a property to a default value in C#?	public YourUserControl(){\n   Count = 15;\n}	0
20200808	19375729	C# Gis add-in application	public class Person\n{\n // default constructor\n public Person()\n {\n }\n\n public Person(string name, int age)\n {\n  Name = name;\n  Age = age;\n }\n\n public string Name {get;set;}\n public int Age {get;set;}\n}\n\npublic class Employee\n{\n private Person _person;\n\n // default constructor\n // Option 1;\n public Employee()\n {\n  // create instance of person injecting name and age on instantiation\n  Person = new Person("John Doe", "42");\n }\n\n // Option 2\n public Employee(string name, int age)\n {\n  // create instance with default constructor \n  Person = new Person();\n\n  // set properties once object is created.\n  Person.Name = name;\n  Person.Age = age;\n }\n\n}	0
20800127	20800024	methods of a property	class MyClass\n{\n   public A PropA { get; set; }\n   public B PropB { get; set; }\n}\n\nclass A\n{\n    public void Foo() { ... }\n}\n\nclass B\n{\n    public void Bar() { ... }\n}	0
19640354	19640156	How to capture a timestamp in MySql programmatically?	DELIMITER //\nCREATE TRIGGER UserAcceptedNOW BEFORE UPDATE ON user\nFOR EACH ROW\n  BEGIN\n    IF (NEW.UserAccepted = 1) THEN\n      SET NEW.UserAcceptedWhen = NOW();\n    END IF;  \n  END\n//	0
29247329	28312979	asp:LinkButton, how to cancel OnClick event?	protected void DetailsView1_DataBound(object sender, EventArgs e)\n {\n     LinkButton lnk1 = (LinkButton)DetailsView1.FindControl("LinkButton1");\n     LinkButton lnk2 = (LinkButton)DetailsView1.FindControl("LinkButton2");\n     LinkButton lnk3 = (LinkButton)DetailsView1.FindControl("LinkButton3");\n     if (ListBox1.SelectedItem.Text == "** NO SCHOOL RECORDED **")\n     {\n         if (lnk1 != null) lnk1.Visible = false;\n         if (lnk2 != null) lnk2.Visible = false;\n         if (lnk3 != null) lnk3.Visible = false;\n     }\n     else\n     {\n         if (lnk1 != null) lnk1.Visible = true;\n         if (lnk2 != null) lnk2.Visible = true;\n         if (lnk3 != null) lnk3.Visible = true;\n     }\n }	0
33626284	27111912	How to Access Grid View from hub section Data Template Windows phone 8.1 in C#	static DependencyObject FindChildByName(DependencyObject from, string name)\n{\n    int count = VisualTreeHelper.GetChildrenCount(from);\n\n    for (int i = 0; i < count; i++)\n    {\n        var child = VisualTreeHelper.GetChild(from, i);\n        if (child is FrameworkElement && ((FrameworkElement)child).Name == name)\n            return child;\n\n        var result = FindChildByName(child, name);\n        if (result != null)\n            return result;\n    }\n\n    return null;\n}\n\nprivate TextBlock NoArticlesTextBlock;\n\nprivate void Page_Loaded(object sender, RoutedEventArgs e)\n{\n    // Note: No need to start searching from the root (this), we can just start\n    // from the relevant HubSection or whatever. Make sure your TextBlock has\n    // x:Name="NoArticlesTextBlock" attribute in the XAML.\n    NoArticlesTextBlock = (TextBlock)FindChildByName(this, "NoArticlesTextBlock");\n}	0
8598278	8597291	How to implement Interface which defines element of another Interface	public interface InterfaceA<T> where T : InterfaceB\n{\n    string x {get;set;}\n    IEnumerable<T> DetailList { get; set; }\n}\n\npublic interface InterfaceB\n{\n    int z { get; }\n    int y { get; }\n}\n\npublic class ClassB : InterfaceB\n{\n    public int z { get; private set; }\n    public int y { get; private set; }\n}\n\npublic class ClassA : InterfaceA<ClassB>\n{\n    public int z { get; private set; }\n\n    public string x { get; set; }\n\n    public IEnumerable<ClassB> DetailList {get;set;} \n}	0
1551977	1551968	Is there a fast way to get rows from a table by range as IQueryable in C# LINQ to SQL?	queryable.Skip(start - 1).Take(end - start + 1)	0
12981664	12981474	Desktop application cannot connect to database but web application can	Data Source=www.winhost.com;Initial Catalog=THEDATABASE;\n             User ID=USERNAME;Password=**;Integrated Security=False;	0
24074489	24074454	Need to format a string	get { return string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}", this.Address1, this.Address2, this.Address3,this.City,this.ZIPCode, this.County,this.State,this.Country); }	0
2512932	2512923	How to get parameter values from an XmlNode in C#	var node = xmldoc.SelectSingleNode("weather/weather-conditions");\nvar attr = node.Attributes["weather-summary"];	0
9738708	9738421	Double to string conversion (engineering format)	double d = -2.71405E-03;\nd.ToString("0.00000E+00");	0
21167286	21167018	CheckBoxList C# Values from a SQL Server database separated by ":"	string str = GetValue(9).ToString().TrimEnd(':');\n string[] strList = str.Split(':');\n\n\n foreach (string s in strList)\n        {\n            foreach (ListItem item in chkTopics.Items)\n            {\n                if (item.Value == s)\n                {\n                    item.Selected = true;\n                    break;\n                }\n\n            }\n\n        }	0
3275486	3275278	Navigating a many-to-many Tables relationship in a Dataset (Optimization)	string stdInfo = string.Empty;\nstring studentId = txtStudentID.Text;\n\nusing (var db = new CourseDataContext())\n{\n    Student student = (\n        from student in db.Students\n        where student.StudentID == studentId\n        select student).Single();\n\n    stdInfo += string.Format("Student {0} {1}:\nTaking Courses:",\n        student.FirstName, student.LastName);\n\n    var courseNames =\n        from taken in student.TakesCourses\n        select taken.Course.CourseName;\n\n    foreach (string courseName in courseNames)\n    {\n        stdInfo += string.Format("\nCourse: {0}", courseNames);\n    }\n}\n\nMessageBox.Show(stdInfo);	0
10738599	10736941	How to prevent a disabled Form from being dragged?	this.Enabled = false;\n        var prc = System.Diagnostics.Process.Start("notepad.exe");\n        prc.EnableRaisingEvents = true;\n        prc.SynchronizingObject = this;\n        prc.Exited += delegate { \n            this.Enabled = true;\n            this.Activate();\n        };	0
14102401	14091875	How to update <byte, string> dictionary in MongoDB Document	var messageDoc = new BsonDocument();\nvar bsonWriter = BsonWriter.Create(messageDoc);\nBsonSerializer.Serialize<Message>(bsonWriter, message);\n\nvar query = Query.EQ("_id", messageId);\nvar update = Update.Set("Contents", messageDoc["Contents"]);\nMessageCollection.Update(query, update);	0
20828250	20828214	Need to make C# timestamp, but documentation is in Ruby	"2013-12-29T17:48:17"	0
22974451	22973754	How can set android:layout_alignParentRight="true" programmatically for a layout in android in xamarin?	params.AddRule(LayoutRules.AlignParentRight);	0
3226723	3225807	How can I make a WinForms Form work as a DockableContent in AvalonDock?	var frm = new Form1();\n  frm.TopLevel = false;\n  frm.Visible = true;\n  frm.FormBorderStyle = FormBorderStyle.None;	0
5751140	5724669	Dynamic textbox generation with buttons to generate a child subset of textboxes	ID rather than Name	0
14946808	14946752	Get an array of images in my web application?	public class Photo\n    {\n      public byte[] Binary { get; set; }\n    }\n\n     var list=new List<Photo>();	0
937129	937102	Splash Screen that doesn't go away	Thread th = new Thread(new ThreadStart(DoSplash));\nth.Start();	0
27092147	27091868	getting closest possible date given NOW and original date in leap year	DateTime now = DateTime.Now;\n\nvar leapYearPointInTime = new DateTime(2016, 2, 29);\n\nif (DateTime.IsLeapYear(leapYearPointInTime.Year))\n    if (2 == leapYearPointInTime.Month)\n        if (29 == leapYearPointInTime.Day)\n            leapYearPointInTime = leapYearPointInTime.Add(new TimeSpan(-1, 0, 0, 0));\n\nvar closestDay2 = new DateTime\n(\n    now.Year,\n    leapYearPointInTime.Month,\n    leapYearPointInTime.Day,\n    leapYearPointInTime.Hour,\n    leapYearPointInTime.Minute,\n    leapYearPointInTime.Second,\n    leapYearPointInTime.Millisecond\n);	0
25043946	25043945	How to connect a ribbon button to a function defined in an Excel add-in?	private void butRefreshSelectedWorksheets_Click(object sender, RibbonControlEventArgs e)\n    {\n        try\n        {\n            Globals.ThisAddIn.RefreshWorksheetListings();\n        }\n        catch (Exception ex)\n        {\n            System.Windows.Forms.MessageBox.Show("Error [butRefreshSelectedWorksheets_Click]: " + ex);\n        }\n    }	0
14167827	14167712	2D Array Buttons Display X and Y	private void Form1_Load(object sender, EventArgs e)\n            { \n\n                   for (int i = 0; i < 2; i++)\n                      {\n                         for (int j = 0; j < 2; j++)\n                         {\n                            b[i, j].Click += new System.EventHandler(this.ClickedButton);\n                            b[i, j].Name =i+" "+j;\n                          }\n                      }\n            }\n    private void ClickedButton(object sender, EventArgs e)\n            {\n\n                Button s = (Button)sender;\n                MessageBox.Show("you have clicked button:" + s.Name);\n            }	0
23610899	23591723	Password hashing used to work, now I can't get into my software	// hash the login for comparison to stored password hash\n    HashGenerator h = new HashGenerator(password, auser.usersalt);\n    string hash = h.GetHash();\n\n    var us = ie.users.FirstOrDefault(u => String.Compare(u.emailaddress, emailaddress, false) == 0 && String.Compare(u.password, hash, false) == 0);	0
27826677	27826219	Keep clicked ellipse highlighted until other ellipse is clicked	private Ellipse selectedNodeEllipse;\nprivate Ellipse previousEllipse = null;\nprivate Brush previousBrush;\n\nprivate void ellipse_MouseDown(object sender, MouseButtonEventArgs e) {\n\n  e.Handled = true;\n  if (previousEllipse != null)\n  {\n    previousEllipse.Stroke = previousBrush;\n  }\n  selectedNodeEllipse = (Ellipse)sender;\n  previousEllipse = selectedNodeEllipse;\n  previousBrush = previousEllipse.Stroke;\n  SelectedNode = (Node)selectedNodeEllipse.Tag; //just displays some info about the node\n\n  selectedNodeEllipse.Stroke = Brushes.Black;\n\n}	0
10695052	10695026	How to fill a byte[] with 0xFF bytes?	MemoryStream.GetBuffer()	0
6465159	6463811	Creating a bitmap from a byte[]	public static Bitmap BytesToBitmap(byte[] byteArray)\n{\n   using (MemoryStream ms = new MemoryStream(byteArray))\n   {\n      Bitmap img = (Bitmap)Image.FromStream(ms);\n      return img;\n   }\n}	0
18511464	18511147	Change default date serialization in WCF	public Stream GetStaticData()\n        {\n            var objTobeReturned = something;\n            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";\n            return new MemoryStream(Encoding.UTF8.GetBytes(objTobeReturned.ToJson()));\n        }	0
4319247	4319185	How to selenium.GetXpathCount for this element?	//*[starts-with(@id,'ctl00_Content_ctl00_chkProduct_')]	0
16551559	16551450	How to add label dynamically in tab control in C#?	foreach (GenericType console in consoleList)\n{\n\n    if (console.HaveGame(a, ref indexResult))\n    {\n        title = console.GetTitle()[indexResult];\n        Results.SetTitle(title);\n        id = console.GetId()[indexResult];\n        Results.SetId(id);\n        price = console.GetPrice()[indexResult];\n        Results.SetPrice(price);\n    }\n}	0
10264816	10264805	How to render Zalgo text in C#	TextRenderer.DrawText	0
5289159	5289101	Get Photos From Album Facebook C#sdk	//Get the album data\ndynamic albums = app.Get("me/albums");\nforeach(dynamic albumInfo in albums.data)\n{\n   //Get the Pictures inside the album this gives JASON objects list that has photo attributes \n   // described here http://developers.facebook.com/docs/reference/api/photo/\n   dynamic albumsPhotos = app.Get(albumInfo.id +"/photos");\n}	0
1093179	1093134	StringBuilder AppendFormat with @	cJavaScript.AppendFormat(@"\n        function GetNextProductIDs(state) \n        {{\n\n            var productIDs = new Array();\n\n            var {0}lastProductFoundIndex = $.inArray({0}lastProductID, {0}allProductIDs);\n            return productIDs.join();\n        }}; ", ClientID);	0
25411247	25398839	Using binding conventions for ninject on windows phone	foreach (var type in (Assembly.GetExecutingAssembly().GetTypes())\n{\n    if (type.IsClass && !type.IsAbstract)\n    {\n           //registers the type for an interface it implements\n    }\n}	0
23863089	23862928	How to set the caret to the end of the text in TextBox (WP8)?	myTextBox.Select(tbPositionCursor.Text.Length, 0);	0
3668052	1961549	Resolving IEnumerable<T> with Unity	container.RegisterType<IEnumerable<IParserBuilder>, IParserBuilder[]>();	0
12629877	12629670	Remove specific text from textbox	StartInfo.Arguments = comboBox1.Text + " " + loginText.Text + " " + wachtwoordText.Text;	0
2287139	2287023	Formatting alphanumeric string	StringBuilder  splitMe = new StringBuilder("F4194E7CC775F003");\n        string joined = splitMe.Insert(12, "-").Insert(8, "-").Insert(4, "-").ToString();	0
4856578	4856550	Display images with PictureBox in c#	this.Controls.Add(p);	0
28576316	28576262	Get records modified within the last year from current date	int currentYear = DateTime.Now.Year; int currentMonth = DateTime.Now.Month;\n\nvar result = budgetData.Where(\n       b => (b.ForecastYea.Equals(currentYear - 1)  \n             && b.ForecastMonth >= currentMonth )\n             ||(b.ForecastYear.Equals(currentYear)                       \n             && b.ForecastMonth <= currentMonth - 1))\n             .ToList();	0
23249727	23246591	Generate unique number as image name	public char GenerateChar(System.Random random)\n {\n        char randomChar;\n        int next = random.Next(0, 62);\n        if (next < 10)\n        {\n            randomChar = (char) (next + '0'); //0, 1, 2 ... 9\n        }\n        else if (next < 36)\n        {\n            randomChar = (char) (next - 10 + 'A'); //A, B, C ... Z\n        }\n        else\n        {\n            randomChar = (char) (next - 36 + 'a'); //a, b, c ... z\n        }\n        return randomChar;\n}\n\npublic string GenerateString(System.Random random, int length)\n{\n        char[] randomStr = new char[length];\n        for (int i = 0; i < length; i++)\n        {\n            randomStr[i] = GenerateChar(random);\n        }\n        return new string(randomStr);\n}	0
12456660	12454663	Panel in Horizontal List item showing behind Button	ul \n{\n\n    padding: 0;\n    margin: 0 0 0 0 ;\n    list-style: none;\n    z-index: 499;\n}	0
19716389	19715876	Lambda expression for multiple foreach loops	results = groups\n  .SelectMany(group => languages\n     .SelectMany(language => Enum.GetValues(typeof(TestEnum))\n        .Cast<TestEnum>()\n           .Select(enumValue => GetResult(group, language, enumValue))))\n  .ToList();	0
14702509	14702478	How to get the previous month date in asp.net	DateTime d = DateTime.Now;\nd = d.AddMonths(-1);	0
15427897	15427728	nhibernate mapping decimal with precision and scale	Property(\n    x => x.Longitude,\n    m =>\n        {\n            m.Precision(9);\n            m.Scale(6);\n        }\n );	0
23866548	23866349	Create a login with two ASYMMETRIC KEYs	Thread.BeginThreadAffinity()	0
12267563	12267545	How to know if my current operating system is Windows Vista in C#?	var version = Environment.OSVersion.Version;\nbool isVista =  version.Major == 6 && version.Minor == 0;	0
19860466	19860419	c# data from datagrid to textbox?	for (int i = 0; i < dataGridView1.Rows.Count; i++)\n{\n    sendto.text += dataGridView1.Rows[i].Cells[3].Value.ToString() + (i < (dataGridView1.Rows.Count-1) ? "," : "");\n}	0
6320627	6320591	Getting values from Custom Field Attributes in C#	foreach( FieldInfo field in userType.GetFields() )\n{\n    DBDataTypeAttribute attribute = (DBDataTypeAttribute)Attribute.GetCustomAttribute(field, typeof(DBDataTypeAttribute));\n    if( attribute != null )\n    {\n        // Do something with it.\n    }\n}	0
12710969	12710926	Dividing by a higher number returning 0	2.0 / 7\n\n(double) 2 / 7	0
15476859	15422400	How to retrieve interface for a class from a different assembly?	Type type = Type.GetType(activation.Service);\nif (type != null)\n   Type[] interfaces = type.GetInterfaces();	0
12977240	12974050	Get filepath from a routed page	var pageName = Page.GetType().Name.Replace("_", ".");	0
30256687	30254990	Send email with attach file WinRT	private async void SendBtn_Click(object sender, RoutedEventArgs e)\n{\n    EmailMessage email = new EmailMessage { Subject = "Sending test file" };\n    email.To.Add(new EmailRecipient("myMailbox@mail.com"));\n\n    // Create a sample file to send\n    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("testFile.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);\n    await FileIO.WriteTextAsync(file, "Something inside a file");\n\n    email.Attachments.Add(new EmailAttachment(file.Name, file)); // add attachment\n    await EmailManager.ShowComposeNewEmailAsync(email); // send email\n}	0
533668	533617	Filtering a list	List<Items> allItems = /* initialize list */;\n\nList<Items> filteredList =\n    allItems.FindAll(item => item.Name.StartsWith("A"));	0
27812221	27812103	What do I need to learn to write a lexer parser interpreter for ZPL?	loop\n    parse ZPL fragment\n    execute ZPL fragment\nend loop	0
12626869	12626757	How to programmatically delete a row in custom collection	if (customerDetails.Count(i => i.Type == "D2") > 1) \n{\n    //additional code to remove nine digit id goes here                  \n    var remainingRowCount = customerDetails.RemoveAll(c => c.Type == "D2" && c.ID.ToString().Length == 9);\n}	0
3628244	3628182	How do I pass a plus sign in input parameter?	string email = "johnsmith+1@gmail.com"\nlnkThingy.NavigateUrl = "http://www.website.com/Page1.aspx?email=" + Server.UrlEncode(email);	0
31457309	31456929	.NET 5 vNext Resolving dependencies with parameters	services.AddInstance<IMyService>(new MyService("Hello"));	0
13072893	13072725	How to properly fake IQueryable<T> from Repository using Moq?	fakeUserRepo.Setup(r => r.Find(It.IsAny<Func<User, bool>>()))\n            .Returns(queryableUsers);	0
3737694	3737640	WinForm Application Prevents Machine Restart?	protected override void OnFormClosing(FormClosingEventArgs e) {\n        if (e.CloseReason == CloseReason.UserClosing) {\n            this.Hide();\n            e.Cancel = true;\n        }\n        else base.OnFormClosing(e);\n    }	0
20614408	19668935	Button inside template of another button	private void Inner_Click(object sender, RoutedEventArgs e) {\n  MessageBox.Show("Inner!");\n  e.Handled = true;\n}	0
15526812	15526763	How to pass C# string variable to .BAT file from Windows Form	proc.StartInfo.Arguments = " my arguments";	0
1470098	1465966	C# Silverlight - Building a Timeline?	public double ScaleDate(DateTime date)\n    {\n        TimeSpan span = this.StopDate - this.StartDate;\n        TimeSpan pos = date - this.StartDate;\n\n        double posDays = double.Parse(pos.Days.ToString());\n        double spanDays = double.Parse(span.Days.ToString());\n        double x = posDays / spanDays;\n\n        return x;\n    }	0
20015507	20015060	How to prevent panel content from being erased upon scroll	List<Tuple<Image, PointF>> Tiles = new List<Tuple<Image, PointF>>();\n\n    private void canvas_MouseClick(object sender, MouseEventArgs e)\n    {\n        if (currentTile != null)\n        {\n            float x1 = CommonUtils.GetClosestXTile(e.X);\n            float y1 = CommonUtils.GetClosestYTile(e.Y);\n            Tiles.Add(new Tuple<Image, PointF>(currentTile, new PointF(x1, y1)));\n            canvas.Refresh();\n\n            me.AddTile((int)currX, (int)currY, (int)x1, (int)y1, "C:\\DemoAssets\\tileb.png");\n        }\n    }\n\n    private void canvas_Paint(object sender, PaintEventArgs e)\n    {\n        foreach (Tuple<Image, PointF> tile in Tiles)\n        {\n            e.Graphics.DrawImage(tile.Item1, tile.Item2);\n        }\n    }	0
16705569	16705544	return only objects with count more than X	return this.enrollments\n                .Where(e => e.em_enrolled == false && e.em_result < _settings.PassMark)\n                .GroupBy(e => e.em_subject_id)\n                .Where(g => g.Count() >= x)\n                .Select(g => g.Key)\n                .ToList();	0
2132749	2132562	Merging Dictionary containing a List in C#	public static void MergeDictionaries<OBJ1, OBJ2>(this IDictionary<OBJ1, List<OBJ2>> dict1, IDictionary<OBJ1, List<OBJ2>> dict2)\n    {\n        foreach (var kvp2 in dict2)\n        {\n            // If the dictionary already contains the key then merge them\n            if (dict1.ContainsKey(kvp2.Key))\n            {\n                dict1[kvp2.Key].AddRange(kvp2.Value);\n                continue;\n            }\n            dict1.Add(kvp2);\n        }\n    }	0
11632606	11632453	Retrieve specific days of the week within a given range from Linq?	var start = DateTime.Parse("08/17/2012");\nvar end = DateTime.Parse("09/17/2012");\nint numberOfDays = end.Subtract(start).Days + 1;\nvar daysOfWeek = new[] { DayOfWeek.Tuesday, DayOfWeek.Thursday };\n\nvar dates = Enumerable.Range(0, numberOfDays)\n                      .Select(i => start.AddDays(i))\n                      .Where(d => daysOfWeek.Contains(d.DayOfWeek));	0
29068090	26678494	Can't wire-up Click event for dynamically created Buttons in a GridView	PostBackOptions opt = new PostBackOptions(this.YourButtonID);\nopt.AutoPostBack = true;\nopt.ClientSubmit = true;\nopt.PerformValidation = true;\nopt.RequiresJavaScriptProtocol = true;\n\n// This will put a '__doPostBack()' javascript call on the OnClick \n// event (using above options).\nthis.YourButtonID.OnClientClick = ClientScript.GetPostBackEventReference(opt);	0
1811694	1811658	How do websites find out which browser is visiting them	User-Agent: <%= Request.UserAgent %>\nID: <%= Request.Browser.Id %>\nBrowser: <%= Request.Browser.Browser %>\nType: <%= Request.Browser.Capabilities["type"] %>	0
24335018	24310580	ASP.net gridview, autorefresh, txt as source and maintain scroll position	function Func() {//document.getElementById("hdnScrollTop").value\n    document.getElementById("divScroll").scrollTop = document.getElementById("hdnScrollTop").value;\n}\nfunction Func2() {\n    var s = document.getElementById("divScroll").scrollTop;\n\n    document.getElementById('hdnScrollTop').value = s;	0
3228482	3228452	Array Clone bytes 10-40?	byte[] splice = new byte[length];\nArray.Copy(byteArray,offset,splice,0,length);	0
12203847	12202933	Using WebClient to ping a web site	using (var client = new WebClient())\n    {\n        client.Credentials = new NetworkCredential ("theUser", "thePassword", "theDomain"); \n        client.DownloadString("http://MyServer/dev/MyApp");\n    }	0
8573199	8572979	XPathSelectElements => string representation	var result = doc.Element("xml")\n                .Element("root")\n                .Element("Item")\n                .Element("taxids")\n                .ToString(SaveOptions.DisableFormatting);\n\n// result == "<taxids><string>330</string><string>374</string> ... </taxids>"	0
4970354	4968652	How do I OPEN a stored excel file in SQL Server 2008 via C#	System.Diagnostics.Process.Start(@"c:\" + DocumentName)	0
295427	295287	How can I prevent a public class that provides extension methods from appearing in Intellisense?	[EditorBrowsable(EditorBrowsableState.Never)]	0
13895840	13895473	What's the easiest way to create a console window for a windows phone 8 application project?	System.Diagnostics.Debug.WriteLine()	0
6215341	6215293	How to Verify using C# if a XML file is broken	var doc = new XmlDocument();\ntry {\n  doc.LoadXml(content);\n} catch (XmlException e) {\n  // put code here that should be executed when the XML is not valid.\n}	0
30892558	30892492	Code need to split string AND remove unwanted characters	string [] arr = input.Replace("T23:00:00.000Z","").Split(new string[] {","},StringSplitOptions.None);	0
13362728	5671093	Identify Current Domain Controller Name	DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");\n\n  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);\n  var controller = domain.FindDomainController();	0
5839244	5839203	how to parse value from previous tab to the next tab?	TabControl.Controls["NameOfControl"]	0
12100265	12100110	How can i search for specific files type in C:\ and any other drives ? Im getting exception access denied	public IEnumerator SearchFor(string fileExtension, DirectoryInfo at) {\n  try {\n    foreach (DirectoryInfo subDir in at.GetDirectories()) {\n        SearchFor(fileExtension, subDir);\n\n        foreach (FileInfo f in at.GetFiles()) {\n            // test f.name for a match with fileExtension\n            // if it matches...\n            //   yield return f.name;\n        }\n    }\n  } catch (UnauthroizedAccessException) { }\n}	0
12041640	12041592	Show shutdown dialog box from c#	shutdown.exe /i /t 0	0
10323905	10308015	Uploading image to WCF Api with RestSharp - Image not valid	MemoryStream imageStream = new MemoryStream();\n\n     MultipartParser parser = new MultipartParser(dataStream);\n        if (parser != null && parser.Success)\n        {\n            imageName = parser.Filename;\n            imageStream.Write(parser.FileContents, 0, parser.FileContents.Length);\n        }	0
33245981	33245607	Moving multiple files with openfiledialog	string MoveTo = "D:\\"; //Change to your path\nopenFileDialog1.Multiselect = true;\nif (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n    {\n        foreach (string _file in openFileDialog1.FileNames)\n        {\n            FileInfo fi = new FileInfo(_file);\n            File.Move(_file, Path.Combine(MoveTo, fi.Name));\n        }\n    }	0
1408980	1408952	Deleting a file in asp.net	String filename=@"c:\xyz\aa.txt";\nFileInfo file=new FileInfo(filename);\nfile.Delete();	0
12098213	12054276	How to change many-one relationship to many-many relationship in EF	modelBuilder\n            .Entity<Category>()\n            .HasMany(c => c.Items)\n            .WithMany()\n            ;	0
11433547	11433507	The differences of running on a server	using (new Impersonator(username, domain,password)) {\n      using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))\n      file.WriteLine("asfsd");\n      }\n }	0
12690558	12678435	Need to get name (DeviceID) of System Reserved partition	string sysGuid = "";\n        try\n        {\n            ManagementObjectSearcher ms = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");\n            foreach (ManagementObject mo in ms.Get())\n            {\n                if (mo["Label"].ToString() == "System Reserved")\n                {\n                    sysGuid = mo["DeviceID"].ToString();\n                    break;\n                }\n            }\n        }\n        catch (Exception) {}	0
6110605	5974728	lineTranslateAddress c++ to managed c#	[DllImport("coredll", SetLastError = true)]\nextern public static int lineTranslateAddress(\n    IntPtr hLineApp,\n    int dwDeviceID,\n    int dwAPIVersion,\n    string lpszAddressIn,\n    int dwCard,\n    int dwTranslateOptions,\n    byte[] lpTranslateOutput\n    );	0
21110510	21110415	Performance issues with nested loops and string concatenations	StringBuilder sb = new StringBuildeR();\n\nfor (int i = 0; i < m.rows; i++)\n{\n    bool first = true;\n\n    for (int j = 0; j < m.cols; j++)\n    {\n        sb.Append(m[i, j]);\n\n        if (first)\n        {\n            first = false;\n        }\n        else\n        {\n            sb.Append(",");\n        }\n    }\n\n    sb.AppendLine();\n}\n\nstring output = sb.ToString();	0
15146825	15143781	Wrong order of xmldocument	for (int i = lines; i > 0;i-- )\n                    {\n                        if (levels[i] < levels[lastSmallest])\n                        {\n                            checker = i;\n                            break;\n                        }\n                    }	0
4281144	4281101	Convert contents of DataGridView to List in C#	List<MyItem> items = new List<MyItem>();\n        foreach (DataGridViewRow dr in dataGridView1.Rows)\n        {\n            MyItem item = new MyItem();\n            foreach (DataGridViewCell dc in dr.Cells)\n            { \n                ...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value  \n            }\n\n            items.Add(item);\n        }	0
14500522	14499931	ASP MVC 3 Getting XML results from search engine	var xml = XDocument.Load("http://<Domain>/engine/ContactssCore/select?q=QUERY");	0
6387472	6387106	Need to determine smallest value in a List	Dictionary<Int64, Int64> dicJobLocum = New Dictionary<Int64, Int64>(); // This is the key value pair list\nDictionary<Int64, Int64> dicJobDistance = New Dictionary<Int64, Decimal>(); // This is to track the distance of the currently assigned locum\n\nforeach (LocumJobDistanceDifferenceObject locum in MindMapTier01) {\n    if (dicJobDistance.ContainsKey(locum.JobID) {\n       Decimal distance = dicJobDistance(locum.JobID);\n       // If the job has been assigned, check if the current locum is closer\n       if (locum.DistanceMiles < distance) {\n            dicJobDistance(locum.JobID) = locum.Distance;\n            dicJobLocum(locum.JobID) = locum.LocumID;\n       }\n    }\n    else {\n       // If the job has not been assigned yet\n       dicJobDistance.Add(locum.JobID, locum.DistanceMiles);\n       dicJobLocum.Add(locum.JobID, locum.LocumID);\n    }\n}	0
5865837	5865718	how to convert string of unicodes to the char?	string num = "0641"; // replace it with extracting logic of your preference\nchar c = (char)Int16.Parse(num, System.Globalization.NumberStyles.HexNumber);	0
8919286	8919013	How to get affected records using ExecuteNonQuery when multiple insert statements are used in C# for SQL	set nocount off\n\ndeclare @t table (a int)\ninsert into @t \nvalues(1)\n\nset nocount on\n\ndeclare @MyTable table (b int)\n\ninsert into @MyTable\nselect * from @t	0
11293450	11260843	Getting data from selected datagridview row and which event?	private void dataGridView_SelectionChanged(object sender, EventArgs e) {\n            foreach (DataGridViewRow row in dataGridView.SelectedRows) {\n                string value1 = row.Cells[0].Value.ToString();\n                string value2 = row.Cells[1].Value.ToString();\n                //...\n            }\n        }	0
521277	521261	Remove brackets with regular expression in C#	sql = Regex.Replace(sql, "\\[([^\\s]*)\\]", "$1");	0
22753658	22753562	Write a specific part of a .txt file	importFile = File.ReadAllText(fileName).Split('\n');\nStringBuilder newContents = new StringBuilder();\n\nforeach (string line in importFile)\n{\n    data = line.Split(',');\n    userName = data[0]; // "Ben"\n    password = data[1]; // "welcome1"\n\n    if (data[0] == UModel.UserName && UModel.UserPassword == data[1])\n    {\n        line = data[0] + "," + UModel.ConfirmPassword + "," + data[2];\n\n        newContents.Append(line);\n        newContents.AppendLine();\n    }\n}\n\nFile.WriteAllText(fileName, newContents.ToString());	0
20430027	20429994	mysql insert a query into a table column	insert into querylog (query,systemTime,user) \nvalues \n('INSERT INTO invoice(invoiceno,invoicenote,invoicetotal,nettotal,invoicedate,customer,receivedby,vehicleno) VALUES (''I 501'',''3223'',15000,15000,''2013-12-06'',''C 116'','''',''-'')',\n'12/6/2013 10:35:56 PM',\n'Lakmal')	0
2052197	2051028	Unit Test configuration for ASP.NET application	[TestMethod]\npublic void Test5()\n{\n    var sut = new Thing();\n    var expectedResult = new object();\n    sut.Bar = expectedResult;\n    var actual = sut.Bar;\n    Assert.AreEqual(expectedResult, actual);\n}	0
4514234	4495823	Fluent NHibernate: How to have a one-to-many reference in both directions?	public class PersonMap : ClassMap<Person>\n{\n  public PersonMap()\n  {\n    Table("Persons");\n    Id(x =>x.Id, "PersonId").GeneratedBy.Identity();\n    References(x => x.User).Column("UserId").Cascade.All();\n    Map(x => x.FirstName, "FirstName");\n    Map(x => x.LastName, "LastName");\n    Map(x => x.Address, "Address");\n    Map(x => x.Phone, "Phone");\n    // More property maps\n  }\n}\n\npublic class UserMap : ClassMap<User>\n{\n  public UserMap()\n  {\n    Id(x => x.Id, "UserId").GeneratedBy.Identity();\n    Map(x => x.Username, "Username");\n    Map(x => x.Password, "Password");\n    References<Person>(x => x.PrimaryPerson).ForeignKey("PrimaryPersonId").Cascade.All();\n  }\n}	0
11965168	11965141	the value of double when getter setter is used	double? MyDouble { get; set; }	0
961441	961383	Using HttpWebRequest to download html pages returns ContentLength as -1	class Program\n{\n    static void Main(string[] args)\n    {\n        var client = new WebClient();\n        client.DownloadProgressChanged += (sender, e) =>\n        {\n            Console.WriteLine("{0}% completed", e.ProgressPercentage);\n        };\n        client.DownloadStringCompleted += (sender, e) =>\n        {\n            // e.Result contains downloaded string\n            Console.WriteLine("finished downloading...");\n        };\n        client.DownloadStringAsync(new Uri("http://www.stackoverflow.com"));\n        Console.ReadKey();\n    }\n}	0
25688552	25686655	Exception while converting String to Double C#	if (fbalPrice.Contains(" "))\n     {\n     fbalPrice = fbalPrice.Remove(0, fbalPrice.IndexOf(" ") + 1).Replace(",","").Trim();\n     }\n if(fbalsPrice.Contains(" "))\n     {\n     fbalsPrice = fbalsPrice.Remove(0, fbalsPrice.IndexOf(" ") + 1).Replace(",", "").Trim();\n     }	0
9219512	9215492	Use DataSet for retrieving, updating and inserting data to SQLite	DataSet2TableAdapters.TableTestTableAdapter t = new DataSet2TableAdapters.TableTestTableAdapter();\n\n    DataSet2 ds = new DataSet2();\n    t.Fill(ds.TableTest); \n\n    foreach (DataSet2.TableTestRow row in ds.TableTest.Rows)\n    {\n        row.integer = 12345; // change value of column integer               \n    }\n\n    t.Update(ds2);	0
1322699	1322546	MVVM with TreeView - add nodes	ObservableCollection<T>	0
15954004	15515098	Send BASIC auth by default, rather than wait for HTTP 401	AuthenticationSection config = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");\n\nif(config.Mode == AuthenticationMode.Forms)\n{\n    module.Authenticate += OnEnter;\n    context.EndRequest += OnLeave;\n}	0
22007951	21989397	Unable to build JSIL	git submodule update --init --recursive	0
25748459	25729725	Dependency injection - named dependencies	using LightInject;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var container = new ServiceContainer();\n        container.Register<IUserRepository, UserRepositorySql>("Sql");\n        container.Register<IUserRepository, UserRepositoryDefault>("Default");\n        container.Register<string, IUserModule>(\n            (factory, serviceName) => new UserModule(factory.GetInstance<IUserRepository>(serviceName)));\n\n        var userModuleWithSqlRepository = container.GetInstance<string, IUserModule>("Sql");\n        var userModuleWithDefaultRepository = container.GetInstance<string, IUserModule>("Default");\n    }\n}\n\npublic interface IUserModule { }\n\npublic class UserModule : IUserModule\n{\n    public UserModule(IUserRepository repository)\n    {\n    }\n}\n\npublic interface IUserRepository { }\n\npublic class UserRepositorySql : IUserRepository { }\n\npublic class UserRepositoryDefault : IUserRepository { }	0
5047582	5047570	C# How to know if a given path represents a root drive?	DirectoryInfo d = new DirectoryInfo("");\nif(d.Parent == null) { IsRoot = true; }	0
9853104	9853048	How to make the StreamReader read from the start of the textfile	reader.DiscardBufferedData(); \nreader.BaseStream.Seek(0, SeekOrigin.Begin); \nreader.BaseStream.Position = 0;	0
2657231	2657040	udp can not receive any data	Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\nsck.Bind(new IPEndPoint(IPAddress.Any, 0));\n//Wait response from server\nSocket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\nsck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));\nbyte[] buffer = new byte[128];\nEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);\n\n// Broadcast to find server\nstring msg = "Imlookingforaserver:" + udp_listen_port;\nbyte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);\nIPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);\nsck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);\nsck.SendTo(sendBytes4, groupEP);\n\n\nsck2.ReceiveFrom(buffer, ref remoteEndPoint);	0
3904167	3904030	Need to do Multiple transaction with SQLServer database	createPROCEDURE MultipleTransaction\n\n    AS\n    BEGIN\n        -- SET NOCOUNT ON added to prevent extra result sets from\n        -- interfering with SELECT statements.\n        SET NOCOUNT ON;\n       declare @a int;\n      set @a=1;\n        -- Insert statements for procedure here\n        while((select distinct   id from a  where id =@a) is not null )\n        begin\n         declare @name varchar(100)\n         declare @id int\n\n         set @name =(select distinct   name2 from a  where id =@a)\n         set @id =(select distinct   id from a  where id =@a)\n\n         exec   GetRows  @name,@id -- calling another procedure\n       set @a =@a+1;\n        end\n    END\n\n\ncreate PROCEDURE  GetRows  \n     (@Para varchar(100),@id varchar(10)  )\nAS\nBEGIN\n    -- SET NOCOUNT ON added to prevent extra result sets from\n    -- interfering with SELECT statements.\n    SET NOCOUNT ON;\n\n    -- Insert statements for procedure here\n     UPDATE [Cube].[dbo].[b]\n   SET [name1] = @Para\n WHERE  id =@id\nEND	0
5432322	5431703	ServerManager How to get site's physical path on disk?	ServerManager m = new ServerManager();  \nm.Sites["default web site"].Applications["/"].VirtualDirectories["/"].PhysicalPath;	0
13315205	13315086	what corresponds string[] in C++\CLI	array<String^>^	0
17048405	17047296	Export Grid View to Excel	protected void btnExportToExcel_Click(object sender, EventArgs e)\n{\n    Response.Clear();\n\n    Response.AddHeader("content-disposition", "attachment;\n    filename=FileName.xls");\n\n    Response.Charset = "";\n\n    // If you want the option to open the Excel file without saving than\n\n    // comment out the line below\n\n    // Response.Cache.SetCacheability(HttpCacheability.NoCache);\n\n    Response.ContentType = "application/vnd.xls";\n\n    System.IO.StringWriter stringWrite = new System.IO.StringWriter();\n\n    System.Web.UI.HtmlTextWriter htmlWrite =\n    new HtmlTextWriter(stringWrite);\n\n    gvResults.RenderControl(htmlWrite);\n\n    Response.Write(stringWrite.ToString());\n\n    Response.End();	0
3766000	3765859	Is there a way to determine if a generic type is built from a specific generic type definition?	class Program\n{\n    static void Main(string[] args)\n    {\n        Example<IDictionary<int, string>>.IsDictionary();\n\n        Example<SortedDictionary<int, string>>.IsDictionary();\n\n        Example<Dictionary<int, string>>.IsDictionary();\n\n        Console.ReadKey();\n    }\n}\n\npublic class Example<T>\n{\n    public static void IsDictionary()\n    {\n        if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))\n        {\n            Console.WriteLine("Is IDictionary");\n        }\n        else\n        {\n            Console.WriteLine("Not IDictionary");\n        }\n    }\n}	0
2684006	2648169	How do I confirm a given page was displayed after calling ISelenium.open()?	[Then(@"the (.*) page should be displayed")]\npublic void ThenThePageShouldBeDisplayed(string pageName) {\n    Assert.IsTrue(selenium.GetLocation().Contains(pageName));\n}	0
11159741	11159578	Copy IPv4-address from byte array to string	byte[] some = { 192, 168, 0, 1 };\n        String ip = "" + some[0] + "." + some[1] + "." + some[2] + "." + some[3];\n        Console.WriteLine("ip=" + ip  );	0
23090039	23085721	XmlElement convert open tag to string c#	IEnumerable<XAttribute> attributes = (from XmlAttribute xmlAttribute in node.Attributes select new XAttribute(xmlAttribute.Name, xmlAttribute.Value));\n\nvar xElement = new XElement(node.Name, attributes);\n\nreturn xElement.ToString();	0
24563372	24563265	Get value of listbox item with item template	private void lbIps_bnClose_Click(object sender, RoutedEventArgs e)\n{\n   var vm = this.DataContext as [yourViewModelName];\n\n   var button = sender as Button;\n\n   var item = (string)button.DataContext;\n\n   vm.IpList.Remove(item);\n}	0
9762487	9762418	How to add a TextBlock to a Canvas using UserControl class?	Card : Control	0
16083093	16082793	How to add local database items into textBox using listBox in C#	private void button_retrieve_Click(object sender, EventArgs e)\n{\nvar selectSQL = "select Firstname, Lastname, Email, Address Inimesed where email = @email";\n\nstring connectionString = @"Data Source=myDatabase;Password=xxxxxx;";\nusing (var cn = new SqlCeConnection(connectionString))\nusing (var cmd = new SqlCeCommand(selectSQL, cn))\n{\n     cn.Open();\n\n    cmd.Parameters.Add("@Email", SqlDbType.NVarChar);\n    cmd.Parameters["Email"].Value = "emailaddresstofind";\n\n    var rdr = cmd.ExecuteReader();\n    try\n    {\n        if (rdr.Read())\n        {\n            textBox1_Firstname.Text = rdr.GetString(0);\n            textBox2_Lastname.Text = rdr.GetString(1);\n            textBox3_Email.Text = rdr.GetString(2);\n            textBox4_Address.Text = rdr.GetString(3);\n        }\n        else\n        {\n            MessageBox.Show("Could not find record");\n        }\n    }    \n    finally\n    {\n        rdr.Close();\n        cn.Close();\n    }\n}	0
12268393	12268360	Creating labels from reference call	private void createLabel()\n     {\n        label = new labels();        \n //error "Object reference not set to an instance of an object"\n        label.printHeader();\n     }	0
4977482	4977441	Display first value at dropdownlist	private void CreateHousingOptions()\n        {\n            string[] housingTypeNames = Enum.GetNames(typeof(Housing));\n            cmbHousing.Items.Clear();\n        for (int rbIndex = 0; rbIndex < housingTypeNames.Length; rbIndex++)\n        {\n            cmbHousing.Items.Add(housingTypeNames[rbIndex]);\n        }\n\n        cmbHousing.SelectedItem = housingTypeNames[0];\n    }	0
8250424	8185860	How to get "public link" of photo uploaded to Facebook album	public String GetPhotoLink(string photoID)\n{\n    var fb = new FacebookWebClient();\n    dynamic albums = fb.Get("me/albums");\n    foreach (dynamic albumInfo in albums.data)\n    {\n        dynamic photos = fb.Get(albumInfo.id + "/photos");\n        foreach (var photo in photos.data)\n        {\n            if (photo.id == photoID)\n            {\n                return photo.link;\n            }\n        }\n    }\n    return String.Empty;\n}	0
29213350	19121142	How can I validate nested model?	public ActionResult GetTitles(Model model)\n{\n    if(ModelState.IsValid && TryValidateModel(model.NestedModel, "NestedModel."))\n    {\n       //Submodel will be validated here.\n    }\n}	0
15588539	15588488	ASP.NET MVC render partial view to a string to return with JSON	public static string RenderPartialViewToString(Controller thisController, string viewName, object model)\n    {\n        // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way)\n        thisController.ViewData.Model = model;\n\n        // initialize a string builder\n        using (StringWriter sw = new StringWriter())\n        {\n            // find and load the view or partial view, pass it through the controller factory\n            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName);\n            ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw);\n\n            // render it\n            viewResult.View.Render(viewContext, sw);\n\n            //return the razorized view/partial-view as a string\n            return sw.ToString();\n        }\n    }	0
29424729	29423208	C# lambda event handler into VB.NET	AddHandler item.PropertyChanged, Sub(s, e)\n                                    If e.PropertyName = "SomeProperty" Then\n                                       'do something\n                                    End If\n                                 End Sub	0
4810426	4761695	How do I add labels to a Dundas Chart?	chart.Series["seriesName"].Points.DataBind(MyDataList, "xFieldPropertyName", "yFieldPropertyName", "Label=xFieldPropertyName{p2},LegendText=legendPropertyName");	0
14473128	14248455	how to implement navigational properties in nhibernate	class SetForeignKeyColumn : IAutomappingOverride<FirstClass>\n{\n    public ...\n    {\n        instance.HasMany(x => x.AnotherClassList).KeyColumn("baseclass_id");\n    }\n}	0
34279780	34279744	How can I both show and hide a form with same key?	bool visible = false;\n\nprivate void KeyPress(object sender, KeyEventArgs e)\n{\n    PlayerInfo playerInfo = new PlayerInfo(this);\n\n\n    if (e.KeyCode == Keys.C)\n    {\n        if (visible == false)\n        {\n            playerInfo.Show();\n            visible = true;\n        } \n        else if (visible)\n        {\n            playerInfo.Hide();\n            visible = false;\n        }\n    }\n}	0
15432047	15432022	Model Binder - how to make optional	public DateTime? DateOfBirth { get; set; }	0
6294861	6294809	Detect IE version from a WinForms application	string ver = (new WebBrowser()).Version.ToString();	0
90835	90751	Float/double precision in debug/release modes	class Foo\n{\n  double _v = ...;\n\n  void Bar()\n  {\n    double v = _v;\n\n    if( v == _v )\n    {\n      // Code may or may not execute here.\n      // _v is 64-bit.\n      // v could be either 64-bit (debug) or 80-bit (release) or something else (future?).\n    }\n  }\n}	0
12120955	12112617	Upload file to skydrive through SkyDrive API	//create a StorageFile (here is one way to do that if it is stored in your ApplicationData)\nStorageFile file = awaitApplicationData.Current.LocalFolder.GetFileAsync("yourfilename.txt");\n\ntry {\n   client = new LiveConnectClient(session);\n   LiveOperationResult operationResult = await client.BackgroundUploadAsync("me/skydrive", file.Name, file, OverwriteOption.Overwrite);\n}\ncatch (LiveConnectException exception) {\n  //handle exception                \n}	0
6739671	6737243	c# XML from descendants	XNamespace xns = "http://schemas.microsoft.com/search/local/ws/rest/v1";\n_xml = XElement.Parse(e.Result);\nresults.Items.Clear();\nforeach (XElement value in _xml\n    .Descendants(xns + "ResourceSets").Descendants(xns + "ResourceSet")\n    .Descendants(xns + "Resources").Descendants(xns + "Location"))\n{\n    Results _item = new Results();\n    _item.Place = value.Element(xns + "Name").Value;\n    _item.Lat = value.Element(xns + "Point").Element(xns + "Latitude").Value;\n    _item.Long = value.Element(xns + "Point").Element(xns + "Longitude").Value;\n    results.Items.Add(_item);\n}	0
23852131	23852087	How to Remove the Last Row in Grid using WPF?	grid1.RowDefinitions.RemoveAt(grid1.RowDefinitions.Count - 1);	0
3411715	3411701	how do I do sscanf in c#	string astring = ...;\nstring[] values = astring.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);\nint a = Int32.Parse(values[0]);\nint b = Int32.Parse(values[1]);\nint c = Int32.Parse(values[2]);	0
29630316	29630272	How to create an array to hold structrues?	static void Main(string[] args)\n    {\n        //Instantiating 5 students structures :\n        Student student1 = new Student();\n        Student student2 = new Student();\n        Student student3 = new Student();\n        Student student4 = new Student();\n        Student student5 = new Student();\n\n\n        //creating the array :\n        Student [] studentArray = new Student[5]; // <---- array of Student!\n        studentArray[0]=student1;\n        studentArray[1]=student2;\n        studentArray[2]=student3;\n        studentArray[3]=student4;\n        studentArray[4]=student5;\n    }	0
13027372	13027210	vs10 c# function run after click	public partial class Form1 : Form\n{\n\n    TextBox[] tb;\n\n    public Form1()\n    {\n        InitializeComponent();\n        tb = new TextBox[2];\n        //...\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        int a = Convert.ToInt32(tb[0].Text);\n    }\n}	0
1279874	1279859	How to replace multiple white spaces with one white space	string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");	0
19171237	19171219	C#: How to create a program that will only accept an integer value that's 0 or higher?	while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)\n{\n    Console.WriteLine("Invalid. Enter a number that's 0 or higher.");\n    numberIn = Console.ReadLine();\n}	0
9136711	9136255	EF4.1 Code First : How to disable delete cascade for a relationship without navigation property in dependant entity	modelBuilder.Entity<ParentEntity>()\n    .HasMany(p => p.Children)\n    .WithRequired()\n    .HasForeignKey(c => c.ParentEntityId)\n    .WillCascadeOnDelete(false);	0
3343324	3343288	Update textbox value into sql	SqlCommand com = new SqlCommand("insert into\n tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','" \n+ txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "')",con);	0
6853006	6852980	XML To ListView Errors	foreach (System.Xml.XmlNode nameNode in NewGame.SelectNodes("//Games//NewGame/Name"))\n{\n    listView1.Items.Add(nameNode.Value);\n}	0
6695757	6695729	C# How to save image from an OLE Object stored in a Database	using (MemoryStream stream = new MemoryStream(photo))\nusing (Image image = Image.FromStream(stream))\n{\n    image.Save(@"C:\Temp\images\test.jpg", ImageFormat.Jpeg);\n}	0
359967	358251	Does anyone know how to listen to build events from an already running cctray process, in C#?	ProjectStatus[] currentStatuses = managerFactory.GetCruiseManager(ServerUri).GetProjectStatus();	0
7493750	7259128	Limit Numbers after Decimal on Key Press Event	private void price_tb_KeyPress(object sender, KeyPressEventArgs e)\n        {\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\n        if (!char.IsControl(e.KeyChar))\n        {\n\n        TextBox textBox = (TextBox)sender;\n\n        if (textBox.Text.IndexOf('.') > -1 &&\n                 textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)\n        {\n            e.Handled = true;\n        }\n\n        }\n\n    }	0
1206252	1206160	transfer dataRow to new dataset	DataSet tempTaskDS = new DataSet("tempCars");\ntempTaskDS.Tables.Add("Cars");\ntempTaskDS.Tables[0].Rows.Add(carDataRow);	0
844874	844835	Sending mail through http proxy	MailAddress from = new MailAddress("from@mailserver.com");\n    MailAddress to = new MailAddress("to@mailserver.com");\n\n    MailMessage mm = new MailMessage(from, to);\n    mm.Subject = "Subject"\n    mm.Body = "Body";\n\n    SmtpClient client = new SmtpClient("proxy.mailserver.com", 8080);\n    client.Credentials = new System.Net.NetworkCredential("from@mailserver.com", "password");\n\n    client.Send(mm);	0
8045549	8044957	table schema to datatable c#	System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();\n    StreamWriter writer = new StreamWriter(xmlStream);\n    writer.Write(data);\n    writer.Flush();\n    xmlStream.Position = 0;//Add this to reset the position of the stream.	0
29376203	29376115	Get range of days in a week given a certain day	DateTime date = new DateTime(2015, 3, 31);\nDateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);\nDateTime weekLastDay = weekFirstDay.AddDays(6);	0
2054298	1056080	How can I avoid properties being reset at design-time in tightly bound user controls?	[Category("Appearance")]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]\npublic override string Text\n{\n     get { return uxLabel.Text; }\n     set { uxLabel.Text = value; }\n}	0
4696123	4695656	Add operationtimeout to channel implemented in code	((IContextChannel)channel).OperationTimeout = new TimeSpan(0,10,0);	0
1567351	1567328	Create single permutation with Linq in C#	List<int> list = Enumerable.Range(1, n).ToList();	0
9046464	9043410	Custom cursor for entire WPF application	...\n<FrameworkElement x:Key="KinectCursor" Cursor="pack://application:,,,/(AssemblyName);component/Resources/KinectCursor.cur"/>\n...	0
8983460	8983376	Fluent WPF API for inherited properties	public static TControl SetContent<TControl>(this TControl obj, object val)\nwhere TControl : ContentControl\n{ \n    obj.Content = val; \n    return obj; \n}	0
19974799	19959000	Add a listview programmatically to all lists in Sharepoint 2013 C#	for(int i = 0; i< myLists.Count; i++){\n  SPList list = myLists[i];\n  //etc..\n}	0
5041800	5041607	Using custom httphandler from a custom assembly	public class MyToolkitHandler : IHttpHandler\n{\n    public void ProcessRequest(HttpContext context)\n    {\n        IHttpHandler handler = Toolkit.GetHandler();\n        if (handler != null)\n        {\n            handler.ProcessRequest(context);\n        }\n    }\n}	0
2725618	2713965	Mocking objects with complex Lambda Expressions as parameters	[TestMethod]\n    public void ParserWorksWithCalcultaroProxy()\n    {\n        var calculatorMock = new Mock<CalculatorExample.ICalculator>();\n\n         calculatorMock.Setup(x => x.Add(2, 2)).Returns(4).Verifiable();\n\n        var validatorMock = new Mock<ILimitsValidator>();\n\n        var calculatorProxy = new CalculatorProxy(calculatorMock.Object, validatorMock.Object);\n\n        var mathParser = new MathParser(calculatorProxy, new MathLexer(new MathValidator()));\n        mathParser.ProcessExpression("2 + 2");\n\n        calculatorMock.Verify();\n    }	0
24034730	24032938	How to reset formula in Crystal Reports when trying to show a section on every page	If (MyBool = true  and PageNumber > 1)\ntrue // HTML and XLS case\nelse\nfalse // PDF case	0
12728908	12727652	ViewData[var] being populated by the same SelectList, not a different one	new SelectList(viewModel.bandQuestionList.Where(p => p.BandQuestTitleID == bandQuestTitleItem.BandQuestTitlesID)**.ToList()**, "BandQuestID", "BandQuestText");	0
3318190	3317706	FluentValidation Validator using arguments	public class BookingValidationService : IBookingValidationService\n{\n    public IRoomTypeService RoomTypeService { get; set; }\n\n    public IBookingValidator BookingValidator { get; set; }\n\n    public ValidationResult ValidateBooking(Booking booking, string tourCode)\n    {\n        BookingValidator.AvailableRooms = RoomTypeService.GetAvailableRoomTypesForTour(tourCode);\n\n        return BookingValidator.Validate(booking);\n    }\n}	0
8619766	8619729	C# Mapping a Calculated Column with Linq	IEnumerable<Log> logList = db.Logs.OrderBy(x => x.FinishTime - x.StartTime)	0
1687401	1685634	Implementing numeric pagination with asp.net	CREATE PROCEDURE GetTowns\n(\n@OutTotalRecCount INT OUTPUT,\n@CurrentPage INT,\n@PageSize INT\n)\nAS\n\n    SELECT * FROM     \n     (\n     SELECT \n      ROW_NUMBER() OVER (ORDER BY TownName) AS Row, \n      TownId,\n      TownName\n     FROM Towns\n     ) AS TownsWithRowNumbers\n    WHERE  Row >= (@CurrentPage - 1) * @PageSize + 1 AND Row <= @CurrentPage*@PageSize\n\n    SELECT @OutTotalRecCount = COUNT(*) FROM Towns	0
14871047	14870997	can i override a class variable in a sub class and change its type to a sub class	public class DerivedClass : BaseClass\n{\n    public DerivedClass():base() { }\n\n    protected override MyBase WorkField \n    { \n        get \n        { \n            return new MyExtend(); \n        }\n    }\n\n    //public new int WorkProperty\n    //{\n    //    get { return 0; }\n    //}\n}	0
19402461	19402008	one winform to add and update data	MyDataObj _myObject;\npublic AddEditForm()\n{\n    InitializeComponent();\n}\n\npublic AddEditForm(MyDataObj obj)\n    :this()\n{      \n    if(obj == null) //you're creating the object\n       _myObject = new MyDataObj();\n    else // you're editing it\n        _myObject = obj;\n}\n// Continue my work with _myObject	0
28543875	28543742	How to avoid a long case statement	var myEntity = new MyEntity();\nvar value = "The data";\nvar columnNumber = 1;\n\nPropertyInfo propertyInfo = MyEntity.GetType().GetProperty(string.Format("Col_{0}", columnNumber));\npropertyInfo.SetValue(myEntity, Convert.ChangeType(value, propertyInfo.PropertyType), null);	0
10952931	10952930	How to order by with 2 field	TbCusromers.OrderBy(x=>x.Family).ThenBy(x=>x.Name);	0
17117870	17117501	Application.OpenForms empty after minimizing from taskbar	protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n    }	0
14053569	13945073	Stop Firefox Flash from exiting full screen mode when focus leaves	protected override CreateParams CreateParams\n{\n    get\n    {\n       CreateParams cp = base.CreateParams;\n       cp.ExStyle |= 0x08000000/*WS_EX_NOACTIVATE*/;\n       return cp;\n    }\n}	0
10418350	10418215	Printing a control	private static void PrintControl(Control control)\n{\n    var bitmap = new Bitmap(control.Width, control.Height);\n\n    control.DrawToBitmap(bitmap, new Rectangle(0, 0, control.Width, control.Height));\n\n    var pd = new PrintDocument();\n\n    pd.PrintPage += (s, e) => e.Graphics.DrawImage(bitmap, 100, 100);\n    pd.Print();\n}	0
3156632	3156551	How to create a local user group (in C#)	var ad = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");\nDirectoryEntry newGroup = ad.Children.Add("TestGroup1", "group");\nnewGroup.Invoke("Put", new object[] { "Description", "Test Group from .NET" });\nnewGroup.CommitChanges();	0
8164624	8164175	Get current MessageBox	foreach (Form f in Application.OpenForms)\n{\n    if (f.Visible && ! f.CanFocus)\n    {\n        // whatever...\n    }\n}	0
8437733	8437595	C# and read values from an Excel file	string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcelFile.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";\nusing (var conn = new System.Data.OleDb.OleDbConnection(connString)) {\n    conn.Open();\n    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * From [SheetName$]", conn);\n    OleDbDataReader reader = cmd.ExecuteReader();\n    int firstNameOrdinal = reader.GetOrdinal("First Name");\n    int lastNameOrdinal = reader.GetOrdinal("Last Name");\n    while (reader.Read()) {\n        Console.WriteLine("First Name: {0}, Last Name: {1}", \n            reader.GetString(firstNameOrdinal), \n            reader.GetString(lastNameOrdinal));\n    }\n}	0
22377395	22377318	Apply string format form left to right	var padded = long.Parse((123).ToString().PadRight(8, '0'));\nstring.Format("{0:00-00-0000}", padded);	0
15758903	15758800	Parsing email responses using Regex	new Regex("\\n(.*)[\\r\\n]*On(?:.|\\r|\\n)*?wrote:\\r\\n", RegexOptions.IgnoreCase | RegexOptions.Multiline)	0
15780602	15780395	how to change a webbrowser's listbox defined in a user control from another form	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n {\n    HtmlElement opt = webBrowser1.Document.CreateElement("option");\n    HtmlElement ddlPopulate = webBrowser1.Document.GetElementById("Select1");\n    opt.InnerText = "TestValue";\n    ddlPopulate.AppendChild(opt);\n }	0
12525095	12525024	how to read and get the values from xml	System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.Load(@"c:\testapp\sample.xml");\n// Root element\nSystem.Xml.XmlElement root = doc.DocumentElement;\nSystem.Xml.XmlElement nameElement =(System.Xml.XmlElement)root.ChildNodes[0];\nstring name = name.InnerText;\nSystem.Xml.XmlElement ageElemnent =(System.Xml.XmlElement)root.ChildNodes[1];\nstring age = ageElemnent.InnerText;\nSystem.Xml.XmlElement sexElemnent =(System.Xml.XmlElement)root.ChildNodes[2];\nstring sex= sexElemnent.InnerText;	0
16750610	16748709	Receiving Json in HttpPost - ASP.net	Request.InputStream	0
28974054	28970969	How to do XML POST with FlUrl	public static class FlurlXmlExtensions\n{\n    // chain off an existing FlurlClient:\n    public static async Task<HttpResponseMessage> PostXmlAsync(this FlurlClient fc, string xml) {\n        try {\n            var content = new CapturedStringContent(xml, Encoding.UTF8, "application/xml");\n            return await fc.HttpClient.PostAsync(fc.Url, content);\n        }\n        finally {\n            if (AutoDispose)\n                Dispose();\n        }\n    }\n\n    // chain off a Url object:\n    public static Task<HttpResponseMessage> PostXmlAsync(this Url url, string xml) {\n        return new FlurlClient(url, true).PostXmlAsync(xml);\n    }\n\n    // chain off a url string:\n    public static Task<HttpResponseMessage> PostXmlAsync(this string url, string xml) {\n        return new FlurlClient(url, true).PostXmlAsync(xml);\n    }\n}	0
8731242	8731213	Initialization of C# String array	string[] matchingActiveLogFiles = {};\n            try\n            {\n                matchingFiles = Directory.GetFiles(FilePath, FileNamePattern);\n            }\n            catch (Exception ex)\n            {\n                //logerror\n            }	0
8665891	8665071	how show a message after closing a PoPupWindow in ParentWindow (In The Middle of CountDown Timer)?	var popup = window.open('http://www.google.com');\n\n    var timer = setInterval(function () {\n        if (popup.closed) {\n            alert('popup closed!');\n            clearInterval(timer);\n        }\n    }, 500);	0
23429947	23429742	How to create new method at runtime c#?	Dictionary<string, Action<object>> _methodDictionary = new Dictionary<string, Action<object>>();\n    public void Report(IEnumerable<Action<object>> actions)\n    {\n        foreach (var action in actions)\n        {\n            // you need to get your name somehow.\n            _methodDictionary.Add(action.GetType().FullName, action);\n        }\n    }\n    public void callMethod(string actionName, object itemToPass)\n    {\n        if(_methodDictionary.ContainsKey(actionName))\n            _methodDictionary[actionName].Invoke(itemToPass);\n    }	0
14975216	14975138	Group List<Person> by properties and get number of times grouped	people.GroupBy(x => new { x.Age, x.FirstName, x.LastName })\n      .Select(x => new { x.Key.Age, x.Key.FirstName, x.Key.LastName, Count = x.Count() });	0
6304262	6297028	Need any design ideas for filtering properties of an object	Item[] HouseHoldItems.Select(string criteria);	0
14295040	14278322	Take from Observable.Interval until another observable produces a value	public IObservable<DigitalInputHeldInfo> Adapt(\n  IObservable<EventPattern<AdsNotificationEventArgs>> messageStream) {\n\n  var startObservable = _digitalInputPressedEventAdapter.\n      Adapt(messageStream).\n      Publish();\n  var endObservable = _digitalInputReleasedEventAdapter.\n      Adapt(messageStream).\n      Publish();\n\n  startObservable.Connect();\n  endObservable.Connect();\n\n  return from notification in startObservable.Timestamp()\n         from interval in Observable.Interval(500.Milliseconds(), \n                                              _schedulerProvider.ThreadPool).\n                          Timestamp().\n                          TakeUntil(endObservable)\n         select new DigitalInputHeldInfo(\n                interval.Timestamp.Subtract(notification.Timestamp), \n                notification.Value);\n}	0
7675988	7675836	How should I handle creation of composite entities with a hand-rolled DAL?	class Customer\n{\n    string name; // etc\n    Address homeAddress;\n    Order[] orders;\n}\n\ninterface ICustomerTableGateway { ... }\n\ninterface IAddressTableGateway { ... }\n\ninterface IOrderTableGateway { ... }\n\nclass CustomerRepository\n{\n    Customer Get(int id)\n    {\n        customer = customerTableGateway.Get(id);\n        customer.Address = addressTableGateway.Get(customer.id);\n        customer.Orders = orderTableGateway.GetAll(customer.id);\n    }\n}	0
15403258	15403006	How to call API URL in asp.net	//Load XML (replace "apikey" in the query string by your API key)\n    XDocument xdoc = XDocument.Load(@"http://free.worldweatheronline.com/feed/weather.ashx?q=Mumbai&format=xml&num_of_days=2&key=apikey");\n\n    //Run query with LINQ\n        var query = from cc in xdoc.Descendants("current_condition")\n                   select cc;\n\n    //To convert memory stream .NET 3.5\n    MemoryStream ms = new MemoryStream();\n    XmlWriterSettings xws = new XmlWriterSettings();\n    xws.OmitXmlDeclaration = true;\n    xws.Indent = true;\n\n    using (XmlWriter xw = XmlWriter.Create(ms, xws))\n    {\n        xdoc.WriteTo(xw);\n    }\n\n    // to convert Memory stream if you are using .NET 4+\n   Stream stream = new MemoryStream();\n   xdoc.Save(stream);	0
2949021	2948878	How to delete VB code from an Excel sheet using C#?	VBProject project = workbook.VBProject;\n\n        for (int i = project.VBComponents.Count; i >= 1; i--)\n        {\n            VBComponent component = project.VBComponents.Item(i);\n            try\n            {\n                project.VBComponents.Remove(component);\n            }\n            catch(ArgumentException)\n            {\n                continue;\n            }\n        }\n\n        for (int i = project.VBComponents.Count; i >= 1; i--)\n        {\n            VBComponent component = project.VBComponents.Item(i);\n                component.CodeModule.DeleteLines(1, component.CodeModule.CountOfLines);\n        }	0
16145684	16145660	How to use "Contain" in List?	if(DB.Countries.Any(c => c.Country == newAddedCountry))\n{\n    // exists ..\n}	0
22089853	22083487	Excel interop conditional formatting with formula	"H4>=M4" try "$H$4>=$M$4$".	0
8504602	8504458	LINQ Groupby a Date in a List of Object	var listdategroup = from x in psrAlertLogItems.AsEnumerable<Item>()\n                    group x by x.DliveryDate.Date into s\n                    select s;	0
29756384	29756302	How to get the folder names present in the directory	List<string> lst = new List<string>();\n\nDirectoryInfo[] dir = new DirectoryInfo(@"C:\SomePath").GetDirectories("*.*", SearchOption.AllDirectories);\nforeach(DirectoryInfo d in dir) \n{\n    lst.Add(d.Name);\n}	0
21586275	21585758	Query using LINQ to SharePoint with lambda expression against PeoplePicker - client object model	double totalTT = collListItemAss\n    .Where(item => ( (item["EngineerAccount"].GetType == typeof(FieldUserValue)) && (((FieldUserValue)(item ["EngineerAccount"])) == usvAss.LookupValue)))\n    .Sum(sItem => Convert.ToDouble(sItem["field3"]));	0
16503831	16502966	HTTPContext User Set In BeginRequest Not Available In Controller	public MvcApplication()\n    {\n        this.AuthorizeRequest += MvcApplication_AuthorizeRequest;\n    }\n\n    void MvcApplication_AuthorizeRequest(object sender, EventArgs e)\n    {\n        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket("test", true, 30);\n        FormsIdentity id = new FormsIdentity(authTicket);\n\n        GenericPrincipal principal = new GenericPrincipal(id, new string[] { });\n        HttpContext.Current.User = principal;\n    }	0
10775768	10774722	Entity Framework : Fluent API makes duplicate foreign keys in one to zero or one	modelBuilder.Entity<Bill>() \n  .HasOptional(x => x.DomainRegOrder) \n  .WithOptionalDependent(c => c.Bill).Map(p => p.MapKey("DomainRegOrderID");	0
10821243	10820901	Protecting recursive operations from cycles	Parameter.Get(string, int)	0
12416864	12416835	Returning to top of program to try again	var retry = true;\nwhile (retry)\n    retry = false;\n    // your program\n    else { // or default: if you're going with switch\n        ...\n        retry = true;\n    }\n}	0
8327569	8327531	C# converting a decimal to an int safely	public static bool TryConvertToInt32(decimal val, out int intval)\n{\n    if (val > int.MaxValue || val < int.MinValue)\n    {\n      intval = 0; // assignment required for out parameter\n      return false;\n    }\n\n    intval = Decimal.ToInt32(val);\n\n    return true;\n}	0
11628894	11628769	asp.net searching for a string	List<string> found = (from str in listOfStringsToSearch \n                     where listOfKeywords.Any(keyword => str.Contains(keyword)) \n                     select str).ToList<string>();	0
324356	324341	Call a factory from Constructor to get a new version of "this"	public static Instance CreateInstance(int id)\n{\n    MyTemplate def = new MyTemplate();\n    return def.GetInstance(id);\n}	0
2672487	2672480	Is there an object in C# that allows for easy management of HTML DOM?	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
19488441	19487896	Making a OneWayToSource/TwoWay binding on custom control	UpdateSourceTrigger=PropertyChanged	0
19894372	19893980	Force a page constructor call on windows phone on back navigation	protected override async void OnNavigatedTo(NavigationEventArgs e)\n{\n    base.OnNavigatedTo(e);\n    // this method is called on each navigation to the page\n}\n\nprotected override void OnNavigatedFrom(NavigationEventArgs e)\n{\n    base.OnNavigatingFrom(e);\n    // this method is called on each navigation from the page\n}	0
5548363	5548308	How to get the IsChecked property of a WinForm control?	foreach (Control c in this.Controls) {             \n   if (c is CheckBox) {\n      if (((CheckBox)c).Checked == true) \n         // do something             \n      } \n}	0
12673827	12673653	Pictures in DOC file	document.InlineShapes	0
11112239	11112053	Parallel.ForEach with ListView	Parallel.ForEach(this.listView2.CheckedItems.Cast<ListViewItem>(),\n                    new ParallelOptions { MaxDegreeOfParallelism = 4 },\n                    (CheckedItem) =>\n                    {\n                         //do something\n                    });	0
21833619	21833290	Integer range overlapping validation	private static bool Overlaps(IEnumerable<Age> listOfRanges)\n{\n    bool isOverlaps = false;\n\n    foreach (var range in listOfRanges)\n    {\n        if (listOfRanges.Count(x => \n            (x.BeginingAge >= range.BeginingAge && x.BeginingAge <= range.EndingAge) \n            || (x.EndingAge >= range.BeginingAge && x.EndingAge <= range.EndingAge)) > 1)\n        {\n            isOverlaps = true;\n            break;\n        }\n    }\n\n    return isOverlaps;\n}	0
33456591	33456482	c# '' is a variable but is used as a type. How can i solve this issue?	public ActionResult Details()\n{\n    var checkingAccount = new CheckingAccount {AccountNumber = "0000123456", FirstName = "Michael", LastName = "Sullivan", Balance = 500 };\n    return View(checkingAccount);\n}	0
22193412	22187973	How to filter items from list using wildcard character?	List<string> myList = new List<string>();\n\nmyList.Add("Table1_Field1");\nmyList.Add("Table1_Field2");\nmyList.Add("Table1_Field3");\nmyList.Add("Table2_Field4");\nmyList.Add("Table2_Field4");\nmyList.Add("Table2_Field4");\n\nList<string> resultList = myList.FindAll(MyFunc);\n\n\nprivate static bool MyFunc(string s)\n{\n\n    // AndAlso prevents evaluation of the second Boolean\n    // expression if the string is so short that an error\n    // would occur.\n    if (s.Contains("Table1")) {\n        return true;\n    } else {\n        return false;\n    }\n}	0
1534359	1534298	WCF communicating with hosting app?	var host = new ServiceHost(_instance);\n//...\nhost.Open();	0
15512691	15509551	converting a composite collection with collection container from xaml to C#	ComboBox comboBox1 = new ComboBox { Height = 18, Width = 100, FontSize = 9.5 };\n\n CompositeCollection compositeCollection = new CompositeCollection();\n compositeCollection.Add(NameClass.NoName);\n\n CollectionContainer collectionContainer = new CollectionContainer();\n collectionContainer.Collection = ItemsSource1;\n\n compositeCollection.Add(collectionContainer);\n\n comboBox1.ItemsSource = compositeCollection;	0
6585161	6584533	How to check if DateTime object was not assigned?	if (mo.StartDate.GetValueOrDefault() != DateTime.MinValue) \n{\n  // True - mo.StartDate has value\n}\nelse\n{\n  // False - mo.StartDate doesn't have value\n}	0
11742637	11720901	Add field to content type in specific position	ct.FieldLinks.Reorder(stringArrayOfInternalFieldNames)	0
6420757	6420669	How to match duplicate words from a paragraph using C# or jquery?	string[] str1Words = ...\nstring[] str2Words = ...\nstring[] dontCheck = {"of", "a", "the"};\n\nvar greaterThanFive = str1Words.Join(str2Words, s1 => s1, s2 => s2, (r1, r2) => r1)\n                               .Distinct()\n                               .Where(s => !dontCheck.Contains(s))\n                               .Count() > 5;	0
20410463	20410420	How do I check if a string contains a string from an array of strings?	bool cont = false;\nstring test = "Hello World, I am testing this string.";\nstring[] myWords = { "testing", "string" };\nforeach (string a in myWords)\n{\n    if( test.Contains(a))\n    {\n        int no = a.Length;\n        test = test.Replace(a, new string('*', no));\n    }\n}	0
27550872	27549027	Entity Navigation Property IQueryable cannot be translated into a store expression	var toModel = ToModel();\n\nvar departments2 = db.departments\n    .AsExpandable()\n    .Include(p => p.employee)\n    .Where(p => true)\n    .Select(p => new CustomDepartmentModel()\n{\n    ID = p.ID,\n    Employees = toModel.Invoke(p.employee).ToList()\n});	0
3498966	3498956	how to create a null string?	MyObj(): this((string) null) {}	0
22152778	22152623	Panel change from ListBox	private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n    // Get the currently selected item in the ListBox. \n    string curItem = listBox1.SelectedItem.ToString();\n\n    switch(curItem)\n    {\n        case : "blah" \n            panel1.visible = false;\n            panel2.visible = true;\n            break;\n        case : "blah" \n            panel2.visible = false;\n            panel3.visible = true;\n            break;\n        case : "blah" \n            panel3.visible = false;\n            panel4.visible = true;\n            break;\n    }\n}	0
9906712	9887076	How to prevent command keys from being processed by hosting form when control has focus	protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n    if (keyData >= Keys.F1 && keyData <= Keys.F24)\n    {\n        WndProc(ref msg);\n        return true;\n    }\n    return base.ProcessCmdKey(ref msg, keyData);\n}	0
18490837	18490774	order list of objects by date	var orderedList = myList\n                 .OrderBy(x => x.GetType().GetProperty("Date").GetValue(x, null)).ToList();	0
31719991	31719846	How to align Column Header Text in to left Datagridview Windows Form C#	this.ColumnHeadersDefaultCellStyle.Padding = new Padding(0);\nthis.RowsDefaultCellStyle.Padding = new Padding(5);	0
1208988	1208974	How to get instances in all private fields of an object?	BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static	0
13748114	13748038	C# Convert hex string to color	string sColor = Request.QueryString["color"]; // sColor is now #AA4643\nInt32 iColorInt = Convert.ToInt32(sColor.Substring(1),16); \nColor curveColor = System.Drawing.Color.FromArgb(iColorInt);	0
15581195	15571083	Test data source in MBUnit like in NUnit	[TestFixture]\npublic class SampleFixture\n{\n  public IEnumerable<int> GetData()\n  {\n    yield return 1;\n    yield return 2;\n    yield return 3;\n  }\n\n  [Test, Factory("GetData")]\n  public void Test(int value)\n  {\n  }\n}	0
14731295	14654783	Moving WPF control with its templates to a new parent	FrameworkElement par = list;\nwhile((par = par.Parent as FrameworkElement) != null) {\n    DictionaryEntry[] resources = new DictionaryEntry[par.Resources.Count];\n    par.Resources.CopyTo(resources, 0);\n    var res = new ResourceDictionary();\n    foreach(DictionaryEntry ent in resources)\n        res.Add(ent.Key, ent.Value);\n    grid.Resources.MergedDictionaries.Add(res);\n}	0
20405244	20405203	Simplest way to get a single value out of an XML string?	XmlDocument doc = new XmlDocument();\n    doc.LoadXml("<item><name>wrench</name></item>");\n\n    doc["item"]["name"].InnerText; //WILL RETURN "wrench"	0
22068620	22068512	How can I tell what object called a method?	public void doAction([CallerMemberName] string fromWhere ="")\n{\n\n}	0
29387594	29387491	How do I get previous element of a List<T>	var result = myList.LastOrDefault(item => item.ID < 80);	0
10223151	10217924	WPF binding to a ListBox.Items	public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)\n{\n    System.Windows.Controls.ItemCollection items = values[0] \n                        as System.Windows.Controls.ItemCollection;\n\n    int index = (int)(values[1]) + 1;\n\n    ...\n}	0
16359160	16358934	List<> failing to serialize to JSON	public class ZoneModel {\n    public int Id { get; set; }\n    public int Number { get; set; }\n    public string Name { get; set; }\n    public bool LineFault { get; set; }\n    public bool Sprinkler { get; set; }\n    public int Resistance { get; set; }\n    public string ZoneVersion { get; set; }\n\n    // this property will not be serialized since it is private (by default)\n    List<DetectorModel> Detectors { get; set; }\n}	0
11287180	10987697	Creating Multiple DropDownLists	if (placeHolder != null)\n{\n    placeHolder.Controls.Add(ddl);\n}	0
21352523	21348882	I want to display a field from my current table and a field from other table but I got error	string strCommandText3 = "SELECT m.medicationType,ap.appointmentID,ap.aStatus FROM MEDICATION as m, (SELECT p.medicationID, a.appointmentID,a.aStatus from\nAPPOINTMENT a, PRESCRIPTION p WHERE a.appointmentID = p.appointmentID) ap WHERE m.medicationID = ap.medicationID ";	0
26232017	26231596	Regex Split String at particular word	var result = select outer in input.Split(",")\n             let p = outer.Split('-')  // will be string[2]\n             select new { identifier = p[0], value = p[1] }\n             into pair\n             group by pair.identifier into g\n             select new {\n               identifier = g.Key\n               values = String.Join(",", g)\n             }	0
7220837	7220753	PictureBox at Click	private void pictureBox94_Click(object sender, EventArgs e)\n{\n    if (!checkBox3.Checked)\n    {\n        pictureBox94.Image = Properties.Resources.select;\n    }\n    else\n    {\n        pictureBox94.Image = Properties.Resources.vuoto;\n    }\n\n    checkBox3.Checked = !checkBox3.Checked;\n}	0
14681377	14677631	How to get the XPath (or Node) for the location of an XML schema validation failure?	doc.Validate(schemas, (sender, args) => {\n  if (sender is XObject)\n  { \n     xpath = ((XObject)sender).GetXPath();\n  }\n});	0
1519187	1519127	How to display ndf files using SMO?	foreach (Database db in srv.Databases)  \n{\n    if (DB.Equals(db.Name))                 \n    { \n            foreach (FileGroup fg in db.FileGroups)\n            {\n                foreach(DataFile df in fg.Files)\n                {\n                    // do whatever you planned to do with df.FileName.\n                }\n            }\n            foreach (LogFile log in db.LogFiles)\n            {\n                // do whatever you planned to do with the log.FileName\n            }\n    }\n}	0
23036589	23036332	Automapper Many to one map configuration	CreateMap<Candidate, CandidateTextInfo>()\n.ForMember(x=> x.ProfilePicture, opt => opt.Ignore())\n.ForMember(... \n// repeat for all destination properties not existing in source properties	0
12156366	12156302	Excel Interop - Add a new worksheet after all of the others	workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);	0
29152464	29023795	How can you implement ZipLongest in Rx?	aSource.Publish(ap => bSource.Publish(bp =>\n    {\n        var lastA = ap.TakeLast(1).Replay();\n        var lastB = bp.TakeLast(1).Replay();\n        var lastAForEachB = bp.SelectMany(b => lastA);\n        var lastBForEachA = ap.SelectMany(a => lastB);\n\n        var aWithLengthB = ap.Concat(lastAForEachB);\n        var bWithLengthA = bp.Concat(lastBForEachA);\n\n        lastA.Connect();\n        lastB.Connect();\n        return aWithLengthB.Zip(bWithLengthA, (a, b) => new { a, b });\n    }));	0
26693374	26693066	Copying an array to a smaller array	int rowDif = g.GetLength(0) - n.GetLength(0);\nint colDif = g.GetLength(1) - n.GetLength(1);\n\nfor (int i = 0; i < n.GetLength(0); i++)  \n{\n  int mappedRow = i * 2 <= 2 * (rowDif - 1) ? 2 * i : 2 * rowDif + ( i - rowDif + 1);\n  for (int j = 0; j < n.GetLength(1); j++)\n  {    \n    int mappedCol = j * 2 <= 2 * (colDif - 1) ? 2 * j : 2 * colDif + ( j - colDif + 1);\n    n[i, j] = g[mappedRow, mappedCol];\n  }\n}	0
16876880	16876363	how would I show the original Form2 from inside Form1 when I press button on Form1 in C#	public partial class Form1 : Form\n{\n\n    Form2 F2 = null;\n\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        if (F2 == null || F2.IsDisposed)\n        {\n            F2 = new Form2();\n            F2.Show();\n        }\n        else\n        {\n            if (F2.WindowState == FormWindowState.Minimized)\n            {\n                F2.WindowState = FormWindowState.Normal;\n            }\n            F2.Activate();\n        }\n    }\n\n}	0
20106013	20057492	Execute Powershell Script from C# with users input command line	ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1 '"+container+"' "+numIPs+"}")[0].BaseObject as ScriptBlock;	0
24945155	24942167	Simplest way to get rid of zero-width-space in c# string	MailItem.Body.Replace("\u200B", "");	0
631031	630971	How to start creating an application API in .NET	/// <summary>\n/// Gets all active documents for the specified customer.\n/// </summary>\n/// <param name="customerId">The Id of the customer.</param>\n/// <returns>A list of documents for this customer.</returns>\npublic static List<Document> GetDocuments(int customerId)\n{\n    //... do something ...\n}	0
18823074	18822410	Best way to realize a polling service	private Timer _dbCheckTimer;\n\n    public void InitTimer()\n    {\n        _dbCheckTimer = new Timer();\n        _dbCheckTimer.Elapsed += DBCheckTimer_Elapsed;\n        _dbCheckTimer.Interval = 10000; // 10 seconds\n        _dbCheckTimer.Start();\n    }\n\n    public void DisposeTimer()\n    {\n        _dbCheckTimer.Dispose();\n    }\n\n    void DBCheckTimer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        _dbCheckTimer.Stop();\n        try\n        {\n            // check DB\n        }\n        finally\n        {\n            _dbCheckTimer.Start();\n        }\n    }	0
27154026	27153937	Simple XML file to store info	XDocument xDoc = XDocument.Load(".\\Resources\\Connection.xml");\n\nstring host = (string)xDoc.Root.Element("hostname");	0
4264197	4242766	binding a dropdownlist to a database	public void rebind()\n    {\n\n        try\n        {\n            OdbcConnection myConn = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);\n            string sql = "select casename,casecode from casetype";\n            myConn.Open();\n            OdbcCommand cmd = new OdbcCommand(sql, myConn);\n            OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);\n            DataTable dt = new DataTable();\n            adapter.Fill(dt);\n            DropDownList3.DataSource = dt;\n            DropDownList3.DataTextField = "casename";\n            DropDownList3.DataValueField = "casecode";\n            DropDownList3.DataBind();\n        }\n        catch (Exception ex)\n        {\n            Response.Write(ex.StackTrace);\n        }\n    }	0
10892974	10892359	How to display a new email using outlook and work on the outlook mailn window at the same time?	MailItem.Display(false)	0
25875079	25873076	How to update the change time of a file from c#?	using (var file = new System.IO.FileStream(@"sample.log", System.IO.FileMode.Open))\n        {\n            var fileInfo = new FILE_BASIC_INFO();\n            GetFileInformationByHandleEx(\n                file.Handle,\n                FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo,\n                out fileInfo,\n                (uint)System.Runtime.InteropServices.Marshal.SizeOf(fileInfo));\n\n            var changeTime = DateTime.FromFileTime(fileInfo.ChangeTime.QuadPart);\n            Console.WriteLine(changeTime);\n            System.TimeSpan changedForHowLong = DateTime.Now.Subtract(changeTime);\n            Console.WriteLine(changedForHowLong.Days);\n        }	0
12723542	12723442	Export listbox selected items to datatable	int numberofplants = 0;\n\nDataTable dtplants = new DataTable();\ndtplants.Columns.Add("Plants");\n\nforeach (ListItem li in lbxPlants.Items)\n{\n    if (li.Selected)\n    {\n        numberofplants++;\n\n        DataRow drplants = dtplants.NewRow();\n        drplants[0] = li.Value;\n        dtplants.Rows.Add(drplants);\n    }\n}	0
23870969	23869722	Get semantic model from a classifier VSIX	var doc = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();\nvar model = await doc.GetSemanticModelAsync();	0
5079014	5078841	Get the users email based on their username	var user = Membership.GetUser(username);\nvar email = null;\n\nif (user != null)\n{\n    email = user.Email;\n}	0
10106073	10105960	How to get value of editable field in Gridview	foreach (GridViewRow gvr in GridView2.Rows)  \n       {  \n           TextBox tb = (TextBox)gvr.FindControl("TextBox1");  \n           string txt = tb.Text;              \n       }	0
3122897	3122825	how to get datetimepicker value with Date and current time	dateval += DateTime.Now.TimeOfDay;	0
22056707	22055772	WP8 Applicationbar hidding on rotation change	this.ApplicationBar.IsVisible = true;	0
5473489	5473409	Find a control in Detailsview	TextBox TextBox1 = (TextBox)yourDetailsViewID.FindControl("TextBox1");	0
31148080	31148018	How to send email via c# SMTP	SmtpClient SmtpServer = new SmtpClient("mail.provider.com.br");\nmail.From = new MailAddress("noreply@provider.com.br");\nmail.To.Add("youremail@provider.com.br");\nmail.Subject = "Some title";\nmail.Body = "YOUR TEXT GOES HERE";\nSmtpServer.Port = 'port';\n//credentials\nSmtpServer.Credentials = new System.Net.NetworkCredential("youremail@provider.com.br", "pa$$word");\nSmtpServer.Send(mail);	0
8482652	8482542	Regex for extracing prices from text	string test = @"<td width='150'><b><font color='#000000' face='Arial' size='5'> 1.777,00</font><font color='#000000' face='Arial' size='2'>&nbsp;TL<td width='150'><b><font color='#000000' face='Arial' size='5'> 395,00</font><font color='#000000' face='Arial' size='2'>&nbsp;TL";\nvar result = Regex.Matches(test,@"[1-9]*\.?[0-9]*,[0-9]*");\nConsole.Write(result);	0
2291472	2291417	Filtering a texbox with a combobox	StringBuilder fileNames = new StringBuilder();\nDirectoryInfo dInfo = new DirectoryInfo(<string yourDirectory>);                                 \nFileInfo[] fileInfo = dInfo.GetFiles("*" + <string yourChosenFileExtension>);\nforeach (FileInfo file in fileInfo)\n{  \n   fileNames.Append(file.Name);\n}\nyourTextBox.Text = fileNames.ToString();	0
10180110	10179910	C# SMTP mail sending usually fails due to lack of credentials?	SmtpClient smtp = new SmtpClient  \nsmtp.Host = "smtp.yourbusiness.com"; \nNetworkCredential credentials = new NetworkCredential("your_user_name_on_smtpserver", "your_password_on_smtpserver"); \nsmtp.Credentials = credentials;	0
12689762	12689706	Reading operations inside NHibernate transaction	.ToFuture()	0
20812193	20812062	How to get Maximum of any column where date equals to somedate	private void tbvouch_Enter(object sender, EventArgs e)\n    {\n\n        DateTime d = Convert.ToDateTime(tbdate.Text);\n        int vcnum;\n        SqlConnection c = new SqlConnection();\n        c.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='D:\\Documents\\Visual Studio 2008\\Projects\\Accounts\\Accounts\\Database1.mdf';Integrated Security=True;User Instance=True";\n        c.Open();\n\n        string q = "IF EXISTS(SELECT 1 FROM lgr WHERE date = @date) \n                    BEGIN \n                         select max(vc_number)+1 from lgr where date = @date \n                    END \n                    ELSE \n                    BEGIN SELECT 05001 END";\n       using (var cmd = new SqlCommand(q, con))\n       {\n        cmd.CommandType = CommandType.Text;\n\n        cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = d;\n\n        vcum = (int)cmd.ExecuteScalar();\n        }\n}	0
5818579	5817285	Download files from Google Books	string url = "http://books.google.pl/books?id=yOz1ePt39WQC&pg=PA2&img=1&zoom=3&hl=pl&sig=ACfU3U0MDQtXGU_3YVqGvcsDiWLLcKh0KA&w=800&gbd=1";\nstring file = "002.png";\n\nWebClient wc = new WebClient();\nwc.DownloadFile(url, file);	0
6118182	6118116	Read a child control with multiple childs with classes having the same name?	IntPtr window = FindWindowEx("MainControl", "WindowTitle");\n\nIntrPtr child = GetWindow(window, GW_CHILD | GW_HWNDFIRST);\nwhile(child != IntPtr.Zero)\n{\n     child = GetWindow(child, GW_HWNDNEXT);\n}	0
9125830	9125321	Connecting MS Access while another application using the same MS Acess File	Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyFolder\MyDb.mdb;Persist Security Info=False;Jet OLEDB:Database Password=My_Password;Mode= Share Deny None	0
5051665	5051649	Remove elements in List<T> that are in Tuple<T1,T2>	cards.RemoveAll(c => c == ownedcards.Item1 || c == ownedcards.Item2)	0
34427356	34427246	Access 2013 syntax error on INSERT INTO statement	command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";	0
7838183	7835450	Retrieve property name from Fluently mapped column name	foreach (var prop in persistentclass.PropertyClosureIterator)\n{\n    IValue property = prop.Value;\n    if (prop.IsComposite)\n    {\n        var component = (NHibernate.Mapping.Component)prop.Value;\n\n        foreach (var prop2 in component.PropertyIterator)\n        {\n            foreach (var column in prop2.ColumnIterator)\n            {\n                if (column.Text == "my Column")\n                {\n                    // do something with the 'prop2'\n                }\n            }\n        }\n    }\n    else\n    {\n        foreach (var column in prop.ColumnIterator)\n        {\n            if (column.Text == "my Column")\n            {\n                // do something with the 'prop'\n            }\n        }\n    }\n}	0
1626825	1626801	Retrieve AssemblyCompanyName from Class Library	Assembly currentAssem = typeof(CurrentClass).Assembly;\nobject[] attribs = currentAssem.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);\nif(attribs.Length > 0)\n{\n    string company = ((AssemblyCompanyAttribute)attribs[0]).Company\n}	0
28669844	28669785	Displaying data in a table on a form	for (int i = 0; i < names.Length; i++)\n{\n    //names of columns\n    Columns.Add(names[i]);\n}\n\nforeach (Order order in orderDatabase.OrdersDatabase)\n{\n    table.Rows.Add(order.OrderId, order.NameOfOrder,order.PriceOfOrder, order.DateOfOrder, order.OrderDescription);\n}	0
32421505	32420721	I want my return from SQL to display in a message box in C#	string returnedValue = cmdDataBase.ExecuteScalar().ToString();\n        MessageBox.Show(returnedValue);	0
23549095	23545134	Delete row from 2 related tables	private void StergeElement(string nume)\n    {\n        conexiune.Open();\n\n\n        Comanda comanda = new Comanda("delete from staff where SID=@ID", conexiune);\n        comanda.Parameters.Add(new SqlParameter("@ID", nume));\n\n        comanda.ExecuteNonQuery();\n\n         comanda = new Comanda("delete from echipa where EID=@ID", conexiune);\n        comanda.Parameters.Add(new SqlParameter("@ID", nume));\n\n        comanda.ExecuteNonQuery();\n\n\n\n        conexiune.Close();\n        MessageBox.Show("Succes");\n    }	0
19911874	19910030	Linq Remove an uncommitted entity from an Entity Collection - How do you find the right one?	protected void rgEmployees_DeleteCommand(object source, GridCommandEventArgs e) {\n    Employee ee = context.Employee.AsEnumerable().ElementAt(e.Item.ItemIndex); \n    context.Employee.Remove(ee);\n}	0
9004490	9003697	How to I use TryParse in a linq query of xml data?	Func<string, DateTime?> tryToGetDate =\n        value =>\n            {\n                DateTime dateValue;\n                return DateTime.TryParse(value, out dateValue) ? (DateTime?) dateValue : null;\n            };\n\n    var makeInfo =\n         from s in doc.Descendants("quote")\n         where s.Element("LastTradeDate") != null\n                && s.Attribute("symbol") != null\n         let dateStr = s.Element("LastTradeDate").Value\n         let dateValue = tryToGetDate(dateStr)\n         where dateValue != null && (DateTime)dateValue == targetDate\n         select .... etc etc	0
24042448	24040070	Set Menu Flyout background color using c# in windows 8	MenuFlyout m = new MenuFlyout();\n  Style s = new Windows.UI.Xaml.Style { TargetType = typeof(MenuFlyoutPresenter) };\n  s.Setters.Add(new Setter(BackgroundProperty,new SolidColorBrush(Colors.Blue)));\n  MenuFlyoutItem mn = new MenuFlyoutItem();\n  m.MenuFlyoutPresenterStyle = s;\n  m.Items.Add(mn);	0
7083570	7083484	One Click Applications, and detecting first launch of new version	if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed && System.Deployment.Application.ApplicationDeployment.IsFirstRun)\n {\n    //do something\n }	0
3980460	3980341	Validate and sort a variety of serial numbers with different formats?	int MaxLength = 20;\n\nprivate string Pad(string val){\n   if(val.Length < 20){\n      val = new String('0', MaxLength - val.Length) + val;\n   }\n   return val;\n}\n\npublic bool IsBetween(string num, string start, string end){\n    num = Pad(num);\n    start = Pad(num);\n    end = Pad(num);\n    return String.Compare(num,start)>=0 && String.Compare(num,end)<=0;\n}	0
97584	97505	Binding a null value to a property of a web user control	bind receives field to get value from\nbind uses reflection to get the value\nbind attempts to set the ExportInfoID property // boom, error	0
14565877	14565716	winforms - messagebox in MDI form is showing multiple times before application is closed	DialogResult result = MessageBox.Show("Do you want to save changes ?", "Save",\n                                   MessageBoxButtons.YesNoCancel,\n                                   MessageBoxIcon.Information,\n                                   MessageBoxDefaultButton.Button3);\n\n            switch (result)\n            {\n\n                case DialogResult.Yes: \n                    closingPending = true;\n                    MessageBox.Show("To Do - validate and save");\n                    break;\n\n                case DialogResult.No: \n                    closingPending = true;\n                    Application.Exit();\n                    break;\n\n                case DialogResult.Cancel:\n                    closingPending = true;\n                    e.Cancel = true;\n                    break;\n            }	0
12646025	12645924	Wrapping methods generically to find performance?	public DCResultOfValidateSiteForUser ValidateSiteForUser(int UserId, int UserType, int SiteId)\n{\n    DCResultOfValidateSiteForUser result = null;\n    TestPerf<DCResultOfValidateSiteForUser>(() => result = Service.ValidateSiteForUser(UserId, UserType, SiteId));\n    return result;\n}	0
13610088	13436030	Regular Expression for UK postcodes	XX-YYY\nXXX-YYY\nXXXX-YYY	0
29393604	29355336	Format Text into Currency C# Monotouch IOS	string textValue = "12345";\n    var d = Convert.ToDecimal(textValue);\n    CultureInfo ui_culture = new CultureInfo("pt-BR");\n    Console.WriteLine(d.ToString("C", ui_culture));	0
19246123	19245647	Pass URL path to ReportViewer	this.ReportViewer1.ServerReport.ReportPath = x;	0
19318636	19318514	The given value of type String from the data source cannot be converted to type float of the specified target column	dt.Rows[i][3] = Math.Round(float.Parse(dt.Rows[i][3].ToString() + ".00"), 2);\ndt.Rows[i][4] = Math.Round(float.Parse(dt.Rows[i][4].ToString() + ".00"), 2);	0
24763820	24763604	Set Binding in ItemsSource in DataGrid programmaticaly	var binding = new Binding\n    {\n        Source = _viewModel,\n        XPath = "Setting/Element[@Name='...']/Field"\n    };\n\n    some_name.SetBinding(ItemsControl.ItemsSourceProperty, binding);	0
12780713	12771814	Access file in Windows LocalStorage (Metro)	StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt")	0
10169478	10124047	How to change DataTables in rdlc reports programmatically	DataTable dtTest =obj.SelectDepartment(1);//Here I am selecting the data from DB\n\n        this.reportViewer1.RefreshReport();\n        reportViewer1.Visible = true;\n        ReportDataSource rds = new ReportDataSource();\n        reportViewer1.Reset();\n        reportViewer1.ProcessingMode = ProcessingMode.Local;\n        LocalReport rep = reportViewer1.LocalReport;\n        rep.Refresh();\n\n        rep.ReportEmbeddedResource = "Report.rdlc";//Provide full path\n        rds.Name = "DataSet1_tblAdapter";//Provide refrerence to data set which is used to   design the rdlc. (DatasetName_TableAdapterName)\n        rds.Value = dtTest;\n\n        rep.DataSources.Add(rds);\n        this.reportViewer1.RefreshReport();	0
17657160	16634194	WPF Multiple CollectionView with different filters on same collection	ICollectionView filteredView = new CollectionViewSource { Source=messageList }.View;	0
10151311	10151006	looping through checkboxes and inserting checkbox values to DB	For i As Integer = 0 To lvSubjects.Items.Count - 1\n            Dim coll As ControlCollection = lvSubjects.Items(i).Controls\n            For Each c As Control In coll\n                If TypeOf c Is CheckBox Then\n                    Dim box As CheckBox = CType(c, CheckBox)\n                    If box.Checked Then\n                        MsgBox(box.Text)\n                    End If\n                End If\n            Next c\n        Next i	0
21887642	21887276	compare IPv4 addresses in c#	uint ipAsNum = BitConverter.ToUInt32( IPAddress.Parse( ipAsString ).GetAddressBytes(), 0 );	0
26903843	26903606	How to bind images to image control dynamically?	System.IO.MemoryStream ms = new System.IO.MemoryStream();\n\n\nimage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);\n  Response.ClearContent();\n  Response.ContentType = "image/Gif";\n  Response.BinaryWrite(ms.ToArray());\n\n\n<asp:Image ID="Image1" runat="server" ImageUrl="~/pic.aspx"/>	0
7828945	7827868	Microsoft chart control failing to set background transparent	chart.BackColor = Color.Transparent;	0
1755908	1755876	How to check if a position in a string is empty in c#	string line    = "  John Doe        Villa Grazia           323334I";\nstring name    = line.Substring(02, 16).Trim();\nstring address = line.Substring(18, 23).Trim();\nstring id      = line.Substring(41, 07).Trim();	0
7562403	7562202	Difference between these two lambdas?	synchronizationContext.Post(m => log.AppendText(message), null);	0
8639415	8639315	How to create a JSON.NET Date to String custom Converter	string str = JsonConvert.SerializeObject(new DateTimeClass(), new MyDateTimeConvertor());\n\npublic class DateTimeClass\n{\n    public DateTime dt;\n    public int dummy = 0;\n}\n\npublic class MyDateTimeConvertor : DateTimeConverterBase\n{\n    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n    {\n        return DateTime.Parse(reader.Value.ToString());\n    }\n\n    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)\n    {\n        writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );\n    }\n}	0
6428246	6428042	C# sorting List key value pair by a date string	responses.OrderByDescending(kvp => DateTime.Parse(kvp.Key));	0
4504190	4504043	help with linq to sql insert	Image img = new Image();\nimg.Path = @"https://s3.amazonaws.com/mystore/images/public/"\n  + FileUpload1.PostedFile.FileName;\n\nProductGroups_Image xref = new ProductGroups_Image();\nxref.Image = img;\n\nusing (StoreDataContext db = new StoreDataContext())\n{\n  ProductGroup pg = db.ProductGroups.Where(a => a.Name == txtName.Value).Single();\n\n  xref.ProductGroup = pg;\n\n  db.SubmitChanges();\n}	0
16864933	16864790	Getting MsAccess table names	DataTable schema = con.GetSchema("Tables");	0
26200119	26200087	C# - Calling a string from a different method?	private string[] B1file;\nprivate void B1_Click(object sender, EventArgs e)\n{\n    foreach (var item in B1file)\n    {\n        Process.Start(item);\n    }\n}\n\nprivate void B1_DragDrop(object sender, DragEventArgs e)\n{\n   B1file = (string[])e.Data.GetData(DataFormats.FileDrop, false);\n}	0
4576444	4576398	ASP.NET Login Controls	If(Request.IsAuthenticated){\n//user is logged-in - request is authenticated.\n}	0
25904010	25903911	Search file without extension in asp.net	protected void Button1_Click(object sender, EventArgs e)\n{\n       ListBox1.Items.Clear();\n       string[] files = Directory.GetFiles(Server.MapPath("~/files"));\n\n       foreach (string item in files)\n       {\n           string fileName = Path.GetFileName(item);\n           if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))\n           {\n               ListBox1.Items.Add(fileName);\n           }\n\n       }\n}	0
14261240	14260905	HTTP GET Request with Username & Password	var request = WebRequest.Create("http://myserver.com/service");\nstring authInfo = userName + ":" + userPassword;\nauthInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));\n\n//like this:\nrequest.Headers["Authorization"] = "Basic " + authInfo;\n\nvar response = request.GetResponse();	0
10579848	10579775	Checkbox validation with LINQ inside a group box windows form	btnAgree.Enabled = \n    (from chkbox in groupBox1.Controls.OfType<CheckBox>()\n     select chkbox).Count(b => b.Checked) >= 2;	0
3458261	3458201	how to read and write MP3 to database	private byte[] GetMp3Bytes(string connString)\n{\n   SqlConnection conn = null;\n   SqlCommand cmd = null;\n   SqlDataReader reader = null;\n\n   using (conn = new SqlConnection(connString))\n   {\n      conn.Open();\n\n      using (cmd = new SqlCommand("SELECT TOP 1 Mp3_File FROM MP3_Table", conn))\n      using (reader = cmd.ExecuteReader())\n      {\n          reader.Read();\n          return reader["Mp3_File"] as byte[];\n      }\n   }\n}	0
13814317	13814287	Pasting image in RichTextBox	private void RtbDocKeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)\n        {\n            DataFormats.Format df = DataFormats.GetFormat(DataFormats.Bitmap);\n            StringCollection strcollect = Clipboard.GetFileDropList();\n\n            Image image= Image.FromFile(strcollect[0]);\n            Clipboard.Clear();\n            Clipboard.SetImage(image);\n            if (Clipboard.ContainsImage())\n            {\n                rtbBody.Paste(df);\n                e.Handled = true;\n                Clipboard.Clear();\n            }\n        }	0
30511891	15546440	Accessing CurrentTestOutcome in ClassCleanup?	private static IList<TestContext> testResults;\n\npublic TestContext TestContext\n{\n    get\n    {\n        return testContext;\n    }\n    set\n    {\n        testContext = value;\n\n        testResults.Add(testContext);\n    }\n}\n\n[ClassInitialize()]\npublic static void MyClassInitialize(TestContext testContext)\n{\n    testResults = new List<TestContext>();\n}\n\n[ClassCleanup()]\npublic static void MyClassCleanup()\n{\n    if (testResults.All(t => t.CurrentTestOutcome == UnitTestOutcome.Passed ||\n        t.CurrentTestOutcome == UnitTestOutcome.Inconclusive))\n    {\n        // Perform conditional cleanup!\n    }\n}	0
14775797	14775698	Read in XmlElement value by given name	MyXmlElement.SelectSingleNode("//Response/fields[@name='ACES_ASP_ID']")\n            .InnerText	0
7315591	7309364	How to do multiple joins with NHibernate Criteria API	var criteria = session.CreateCriteria<Comment>()\n     .CreateAlias("Section", "section")\n     .CreateAlias("section.Page", "page")\n     .Add(Restrictions.Eq("page.Id", pageId))\n     .Add(Restrictions.Eq("page.Type", pageType))\n     .Add(Restrictions.Ge("Date", start))\n     .Add(Restrictions.Lt("Date", end));	0
6398028	6397969	Parsing string to DateTime format	date.ToString("M/dd/yyyy HH:mm:ss")	0
6509234	6507999	Line Breaks In CustomXMLPart	Environment.NewLine	0
26068547	26068277	Linq to SQL order by with Distinct	var Top5MFG = db.orders\n     .Where (x => x.manufacturer.Length > 0 && x.customerid == "blahblahblahblahblah")\n     .GroupBy(mfg => mfg.manufacturer)\n     .Select(g => g.First())\n     .OrderByDescending(d => d.date_created );\n     .Take(5);	0
2203983	2203935	Validation - looking for certain combinations of values	public List<string> Fruit = new List<string>{"apple", "banana"};\npublic List<string> Meat = new List<string>{"beef", "pork"};\n\nswitch (string1)\n{\n    case "fruit":\n        return Fruit.Contains(string2);\n    case "meat":\n        return Meat.Contains(string2);\n}	0
28980397	28980179	Populating dropdown lists based on EF child relationships	Public Shared Function getCarByID(CarID As Integer) As Car\n        Using db As MyAppContext = New MyAppContext\n            Dim car As New Car\n            car = db.Cars.Include("Owner").First(Function(x) x.CarID = CarID)\n            Return car\n        End Using\nEnd Function	0
20958660	20914413	DotNet.HighCharts - PieChart by populating data by code	.SetSeries(new Series\n {\n    Type = ChartTypes.Pie,\n    Name = "Browser share",\n    Data = new Data(browsers.ToArray())\n });	0
20771525	20771483	Convert foreach to LINQ with 'is' operator	var catalogItems = this.SelectedItems\n    .OfType<TreeViewItem>()//If the SelectedItems is IEnumerable\n    .Select(item => item.DataContext)\n    .OfType<CatalogItem>()\n    .ToList();	0
24501708	24501460	Background color of Div based on current date n time	function doBackground() {\n  var elements = document.querySelectorAll('.timeRowCell a');\n  var now = new Date();\n  var currentHour = now.getHours();\n  var ampm = currentHour < 12? 'am' : 'pm';\n\n  // To match on time only, use this line\n  var re = new RegExp((currentHour%12 || 12) + ':\\d\\d:\\d\\d ' + ampm, 'i');\n\n  // To match on date also, use these lines\n  function z(n){return (n<10?'0':'') + n}\n  var re = new RegExp(now.getDate() + '\\/' + z(now.getMonth()+1) +\n                      '\\/' + now.getFullYear() +\n                      ' ' + (currentHour%12 || 12) +\n                      ':\\d\\d:\\d\\d ' + ampm, 'i'\n            ); \n\n  // Loop over elements looking for matches to change the background of\n  for (var i=0, iLen=elements.length; i<iLen; i++) {\n\n    if (re.test(elements[i].title)) {\n      elements[i].parentNode.style.backgroundColor = 'red';\n    }\n  }\n}	0
14287210	14282186	Showing part of image in display area of WPF image control using ScaleTransform and TranslateTransform	public void SetImageCoordinate(double x, double y)\n    {\n\n        TransformGroup transformGroup = (TransformGroup)image.RenderTransform;\n        ScaleTransform transform = (ScaleTransform)transformGroup.Children[0];\n\n        ImageSource imageSource = image.Source;\n        BitmapImage bitmapImage = (BitmapImage) imageSource ;\n        //Now since you got the image displayed in Image control. You can easily map the mouse position to the Pixel scale.\n\n        var pixelMousePositionX = -(x ) / bitmapImage.PixelWidth * transform.ScaleX * image.ActualWidth;\n        var pixelMousePositionY = -(y) / bitmapImage.PixelHeight * transform.ScaleY * image.ActualHeight;\n\n        //MessageBox.Show("X: " + pixelMousePositionX + "; Y: " + pixelMousePositionY);\n\n        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);\n        tt.X = pixelMousePositionX;\n        tt.Y = pixelMousePositionY;            \n    }	0
28115134	28114922	Active Directory Lightweight Directory Services how to get data from AD DS	var fullName = string.Empty;\nusing (PrincipalContext context = new PrincipalContext(ContextType.Domain))\n{\n    using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"racerX")) //User.Identity.Name\n    {\n        if (user != null)\n        {\n            fullName = user.DisplayName;\n        }\n    }\n}	0
24798770	24798711	How to make a property set once and cannot be changed?	bool wasSetMessageId = false;\npublic Guid MesageUniqueId\n{\n    get { return messageUId; }\n    set \n    {\n       if (!wasSetMessageId) \n       {\n          messageUId = value;\n          wasSetMessageId = true;\n       } \n       else\n       {\n          throw new InvalidOperationException("Message id can be assigned only once");\n       }\n    } \n}	0
5664692	5664633	Multiple types in a SaveFileDialog filter	dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png|Tiff Image (.tiff)|*.tiff|Wmf Image (.wmf)|*.wmf";	0
7898709	7898214	LinqPad: Directly referencing ObjectContexts in a Class	void Main()\n{\n    DB.Categories = Categories;\n\n    MyAwesomeClass awesomeness = new MyAwesomeClass();\n    awesomeness.DumpNumOfCategories();\n}\n\nclass MyAwesomeClass {\n\n    public MyAwesomeClass(){\n\n    }\n\n    public void DumpNumOfCategories(){\n        DB.Categories.Count().Dump();\n    }\n\n}\n\nclass DB{\n    public static ISessionTable<Category> Categories { get; set; }\n}	0
1142817	1142793	nHibernate, how query a parent object with multiple relationships	return session.CreateCriteria(typeof(Incident))\n     .Add(Expression.Eq("User_created", UserID))\n     .List<Incident>();	0
12899552	12899325	How to use the .NET ZipArchive and ZipArchiveEntry classes to extract a file with a PASSWORD	using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n  {\n    ZipEntry e = zip["TaxInformation-2008.xls"];\n    e.ExtractWithPassword(BaseDirectory, Password);\n  }	0
16320633	16320479	To return a "manual override" value from a factory, is it better to check for null, or a boolean switch?	static class ThingFactory\n{\n  private static IThing _thingManualOverride = null;\n\n  public static IThing getTheThing() \n  {\n    if (_thingManualOverride != null)\n      return _thingManualOverride;\n\n    return new internalThingGetter();\n  }\n\n  public static void SetThing(IThing thing)\n  {\n    _thingManualOverride = thing;\n  }\n}	0
13904189	13904110	NotImplementedException when searching ListBox	throw new NotImplementedException();	0
4257026	4256991	How to set only time part of a DateTime variable in C#	var dateNow = DateTime.Now;\nvar date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);	0
23648056	23647993	Getting child element in XAML by type	private void Button_Click(object sender, RoutedEventArgs e)\n{\n        Button button = sender as Button;\n        DependencyObject child = VisualTreeHelper.GetChild(button, 0);\n        Image image = child as Image;\n        //Now you can access your image Properties\n}	0
7288915	7288833	StreamWriter ordering using Foreach	int garbage;\nfrom line in theList\nwhere line.PartNumber.ToUpper().StartsWith("FID")\norderby (Int32.TryParse(line.PartNumber.Substring(3),garbage)) ? (Int32.Parse(line.PartNumber.Substring(3))) : 0\nselect line;	0
10230473	10230349	Asynchronous Client Socket Example from MSDN	blocker.WaitOne();	0
5285308	5285276	How to call form several time but with diffrent variables!-C#-Winforms	using (Form2 form2 = new Form2(userInfo, flightBookingInfo))\n{\n    form2.ShowDialog();\n}	0
26346227	26346226	How to set up google-diff-match-patch C# library	using DiffMatchPatch;	0
24737756	24736843	How to check if datagrid row is empty?	var row = RegistrationDataGrid.SelectedItems[0];\nDataRowView castedRow = RegistrationDataGrid.SelectedItems[0] as DataRowView;\n\nif (castedRow != null && castedRow ["Tag"] != null) <------ DONT skip on checking castedRow for null, jumping directly to indexed access.\n{\n     //put the content of the cell into a textbox called tag\n     tag.Text = Convert.ToString(castedRow["Tag"]);\n}	0
8482780	8482711	Remove number from a textbox	double value = Math.Round(double.Parse(textbox.Text), 2);	0
6819025	6817531	IQ test to screen coordinates in Silverlight	EndPosition.To = ( (marginTop - marginBottom)*iq + 180*marginBottom - 40*marginTop )/140;	0
9437918	9437817	How to Split String with Containing Parantheses into multi-dimensional array	string data = "(X,Y,Z),(A,B,C),(R,S,T)";\n\nstring[][] stringses = data.Trim('(', ')')\n    .Split(new[] {"),("}, StringSplitOptions.RemoveEmptyEntries)\n    .Select(chunk => chunk.Split(','))\n    .ToArray();	0
10332088	10332002	How to access asp object	this.Controls["control"];	0
27978430	27962536	How to call an OData function/action generated by a OData client generator?	var entContainer = new Container(new Uri("http://someurl"));\nbool result = entContainer.Ents.ByKey(IdOfEnt).MethodX(p1, p2).GetValue();	0
12797289	12797029	Typecast two model and Return other model	return new RejectedCoupons {\n    prop1 = coupon.prop1,\n    prop2 = coupon.prop2,\n    ...\n}	0
16843930	16843870	Can I disable a combo box or dtp based on the value of a text box that's in another class?	private void ReadWriteTB_TextChanged(object sender, RoutedEventArgs e)\n{\n    if (condition)\n        comboBox.Enabled = false;\n\n}	0
15835055	15834709	Send url with web client	string URI = "http://ww.exmaple.com.tr/webservices/addlead.php?";\nstring myParameters = "first_name=" + r.Name + "&last_name=" + r.Surname + "&phone=" + r.Telephone + "&hash=" + r.HashCode;\n\nURI += myParameters;\n\nusing (WebClient wc = new WebClient())\n{\n try\n {\n  wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";\n  string HtmlResult = wc.DownloadString(URI);\n }\n catch(Exception ex)\n {\n  // handle error\n  MessageBox.Show( ex.Message );\n }\n}	0
16690231	16690144	How to dynamically change the backColour of a richTextBox to control in visual studio C#	tbx_description.BackColor = SystemColors.Control;	0
31089503	31088506	Upgrading WP8 to Silverlight WP8.1, assembly issue	Tools > Nuget package manager > Package manager console	0
5809584	5808724	NHibernate - How to use projections with associations paths to limit the result set?	var crit = Session.CreateCriteria<X>()\n    .CreateAlias("RefToY", "y")\n    .CreateAlias("y.RefToZ", "z")\n    .SetProjection(Projections.ProjectionList()\n        .Add(Projections.Property("Id"))\n        .Add(Projections.Property("z.data1"))\n        .Add(Projections.Property("z.data2"))\n        .Add(Projections.Property("z.data3")));	0
31267203	31267004	How to improve loop Xdocument	string myID = "123";\nvar description = reader.XPathSelectElements("/file/order/products/product")\n                .Where(x => x.Element("id").Value == myID)\n                .Select(x => x.Element("Description").Value).FirstOrDefault();	0
26630947	26630754	reading and retrieving xml elements	if (xndNode["SubQuestionAnswer"] != null)\n{\n    if (xndNode["SubQuestionAnswer"]["Question"] != null)\n        questionanswer = (xndNode["SubQuestionAnswer"]["Question"].InnerText);\n\n    if (xndNode["SubQuestionAnswer"]["Answer"] != null)\n        questionanswer = (xndNode["SubQuestionAnswer"]["Answer"].InnerText);\n}	0
5244548	5244470	Get current time and set a value in a combobox	var now = DateTime.Now;\n   if (now.Hours >=6 && now.Hours <=14)\n    .....\n   else if (now.Hours > 14 && now.Hours < = 22)\n    .........\n   else\n    ........	0
712960	92035	Set selected item on a DataGridViewComboboxColumn	DataGridView.Rows[rowindex].Cells[columnindex].Value	0
29241216	29227892	No CRC64 implementation equal to CommonCrypto?	#include <stddef.h>\n#include <stdint.h>\n\n#define POLY UINT64_C(0x42f0e1eba9ea3693)\n#define TOP UINT64_C(0x8000000000000000)\n\n/* Return crc updated with buf[0..len-1].  If buf is NULL, return the initial\n   crc.  So, initialize with crc = crc64_ecma182(0, NULL, 0); and follow with\n   one or more applications of crc = crc64_ecma182(crc, buf, len); */\nint64_t crc64_ecma182(int64_t crc, unsigned char *buf, size_t len)\n{\n    int k;\n\n    if (buf == NULL)\n        return 0;\n    while (len--) {\n        crc ^= (uint64_t)(*buf++) << 56;\n        for (k = 0; k < 8; k++)\n            crc = crc & TOP ? (crc << 1) ^ POLY : crc << 1;\n    }\n    return crc;\n}	0
17117118	17112314	Converting UIImage to Byte Array	using (NSData imageData = image.AsPNG()) {\n  Byte[] myByteArray = new Byte[imageData.Length];\n  System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));\n}	0
5463049	5462715	Generate an algorithm in C# to take hierarchy data to generate this html  	public static String Dump(List<Node> nodes)\n    {\n            if (nodes == null || nodes.Count == 0)\n                    return String.Empty;\n\n            StringBuilder sb = new StringBuilder("<ul>");\n            foreach (var n in nodes)\n            {\n                    sb.AppendFormat("<li>{0}", n.Name);\n                    sb.Append(Dump(n.Children));\n                    sb.Append("</li>");\n            }\n            sb.Append("</ul>");\n\n            return sb.ToString();\n    }	0
26224144	26165561	Button clicked in Site.Master page fires click event in content page.	//Created an Interface on .aspx page:\npublic interface ICommandable\n{\n    void LblMaintenanceClick(object argument, EventArgs e);\n    } \n\npublic partial class Default : Page, ICommandable\n{\n public void LblMaintenanceClick(object sender, EventArgs e)\n           {\n\n             }\n}\n\n    // On master page: \n      public void lbtnMaintenance_OnClick(object sender, EventArgs e)\n                 {\n                        if (Page is ICommandable)\n                    {\n                         (Page as ICommandable).LblMaintenanceClick(sender, e);\n                     }\n                 else\n                     throw new NotImplementedException("u NO WURK");\n\n            }	0
13179662	13148741	Get data type for DataRow[myColumn] and cast another variable as that type	public int MyMethod<T>(DataTable myDataTable)\n{\n    dynamic myTempVariable = default(T);\n    ...\n}	0
5611327	5611304	DATE datatype of SQL Server 2008 returing time!	((Date)red["expdate"]).ToString();	0
13492273	13492175	Tables without a clustered index are not supported in this version of SQL Server	CREATE UNIQUE CLUSTERED INDEX Idx_TableName ON TableName(yourGUIDColumn);	0
6507871	6452446	help with changing point attributes on chart	Chart1.Series["Series1"].MarkerSize = 15;	0
8402504	8402488	string.format format string containing {	string.Format("my format has this {{ in it {0}", abc);	0
25535912	25535451	How do you remove the href value and combine with text?	private static void Main(string[] args)\n    {\n        string text = @"<a href=""www.stackoverflow.com"">Hello World!</a> <a href=""www.secondsite.com"">Second Site!</a> <a href=""www.thirdsite.com"">Third Site!</a>";\n\n        var pattern = "(?<=href=\")([^\">]+)([^<]*)";\n        var newText = Regex.Replace(text, pattern, "$1$2 ($1)");\n\n        Console.WriteLine(newText);\n        Console.Read();\n    }	0
34256392	34256286	How to remove properties from a class	var result = (from m in model\nselect new\n{\n    Id = m.Id,\n    Dependency = shouldShow ? m.Dependency : null,\n    Description = shouldShow ? m.Description : null\n}).ToList();	0
5786438	5786388	SMTP server Configuration	smtp.yourISP.com	0
8767424	8767171	How to convert this weird string to DateTime format in ASP.net	string myDateString = "Sat Jan 07 03:18:58 +0000 2012";\nstring customFormat = "ddd MMM dd HH:mm:ss zzz yyyy";\n\nDateTimeOffset dto = DateTimeOffset.ParseExact(myDateString, customFormat, CultureInfo.InvariantCulture);	0
28728819	28728480	How to check if entered data in a TextBox is matching a list of words from notepad	//This code first read the words in text file one by one, \n//which are save in notepad file like one word per line \n\nint aCounter = 0; string aWordInTextFile;\n// Read the file and display it line by line.\nSystem.IO.StreamReader file = new System.IO.StreamReader("c:\notePadFile.txt");\nwhile((aWordInTextFile = file.ReadLine()) != null){\n   Console.WriteLine (aWordInTextFile);\n   if(textbox.text == aWordInTextFile){\n        messagebox.show("String Match, found a string in notepad file");\n   }\n   aCounter++;\n\n}\n\nfile.Close();\n\n// Suspend the screen.\nConsole.ReadLine();	0
1536187	1536141	How to draw directly on the Windows desktop, C#?	using System;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Runtime.InteropServices;\n\nclass Program {\n\n    [DllImport("User32.dll")]\n    static extern IntPtr GetDC(IntPtr hwnd);\n\n    [DllImport("User32.dll")]\n    static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);\n\n    static void Main(string[] args) {\n        IntPtr desktop = GetDC(IntPtr.Zero);\n        using (Graphics g = Graphics.FromHdc(desktop)) {\n            g.FillRectangle(Brushes.Red, 0, 0, 100, 100);\n        }\n        ReleaseDC(IntPtr.Zero, desktop);\n    }\n}	0
25691189	25690266	WPF DataGrid only calculate visible rows	... When the EnableRowVirtualization property is set to true, the DataGrid does not instantiate a DataGridRow object for each data item in the bound data source. Instead, the DataGrid creates DataGridRow objects only when they are needed ...	0
34033104	34032951	How can I retrieve an IEnumerable<T2> from an IEnumerable<T1>?	IEnumerable<test2> data = list.Select(x => x.obj).Where(x => x.isBool);	0
11696766	11695132	Forms authentication after a user session has expired	public void Extend(int SessionLimit)\n    {\n        FormsAuthenticationTicket OriginalTicket = ((FormsIdentity)Context.User.Identity).Ticket;\n        FormsAuthenticationTicket NewTicket = new FormsAuthenticationTicket(1, OriginalTicket.Name, DateTime.Now, DateTime.Now.AddMinutes(SessionLimit), false, OriginalTicket.UserData);\n        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(NewTicket));\n        authCookie.HttpOnly = true;\n        HttpContext.Current.Response.Cookies.Add(authCookie);\n    }	0
6445842	6445214	Combine Generic ICollection<T> Expression with an Any Accepting a Generic Predicate	childSelector.Combine(p => p.AsQueryable().Any<TEntity>(this.Predicate), true)	0
33909948	33903162	Randomly ordered long sequence	System.Random	0
8935787	8933821	Bind repository to base class only via Ninject?	Html.RenderAction	0
8587675	8587417	How can I set a method of a Stub object to return 5 on the first call, and then 7 on the second call?	var results = new[] {5, 7, 11};\nvar count = 0;\nservice.Expect(x => x.GetMyLuckyNumber()).Return(0)\n                                         .WhenCalled(x => { \n                                                x.ReturnValue = results[count];\n                                                count++;\n                                         });	0
1141940	1141510	How to load web user controls with interface type	namespace TypeTest{\n\n    public interface IMultiTextProvider {\n        bool Insert(string text, Guid campaignId);\n    }\n\n    public class BonusProvider : IMultiTextProvider {\n        public bool Insert(string text, Guid campaignId) {\n            return true;\n        }\n    }\n\n    class Program {\n        static void Main(string[] args) {\n\n            string typeName = "TypeTest.BonusProvider";\n            Type providerType = Type.GetType(typeName);\n            IMultiTextProvider provider = Activator.CreateInstance(providerType)\n                as IMultiTextProvider;\n            if (null == provider) {\n                throw new ArgumentException("ProviderType does not implement IMultiTextProvider interface");\n            }\n            Console.WriteLine(provider.Insert("test",new Guid()));\n        }\n    }\n}	0
5856075	5855948	How to play youtube in highest quality in a wpf application	Data API	0
11584940	11584860	Building a lambda with an Expression Tree	ParameterExpression parameter = Expression.Parameter(typeof(YourClass), "c");\nExpression property = Expression.PropertyOrField(parameter, "Property");\nExpression<Func<YourClass, PropertyType>> lamda = Expression.Lambda<Func<YourClass, PropertyType>>(property, parameter);	0
3652964	3652933	Mapping XML with Schema to Entity in C#	xsd.exe	0
23536279	23536220	How to update multiple tables using single query	CREATE PROCEDURE USP_UPDATEPRICE\n(\n@productcategory INT,\n@itemname INT\n@rate INT\n)\nAS\n\nUPDATE\n    pricefix \nSET\n    RATE = @rate\nFROM\n    pricefix\nINNER JOIN\n    PriceCAt\n         ON pricefix.id = pricecat.pricefix\nWHERE\n     pricecat.itemname = @pricename\nand\n     pricecat.cat = @cat	0
14289748	14289625	Parse string with encapsulated int to an array that contains other numbers to be ignored	string s = "{15} there are 194 red balloons, {26} there are 23 stickers, {40} there are 12 jacks";\n\n// Match all digits preceded by "{" and followed by "}"\nint[] matches = Regex.Matches(s, @"(?<={)\d+(?=})")\n    .Cast<Match>()\n    .Select(m => int.Parse(m.Value))\n    .ToArray(); \n\n// Yields [15, 26, 40]	0
8861899	8861878	How to set the name of a tabPage progragmatically	foreach (string s in hostnames)\n{\n    TreeNode newNode = new TreeNode(s);\n    hostView.SelectedNode.Nodes.Add(newNode);\n\n    TabPage myTabPage = new TabPage(s);\n    myTabPage.Name = "Name you want to set";\n    tabControl1.TabPages.Add(myTabPage);\n}	0
10753346	10753224	Strange values in an array - after I change them they remain the same	var items = tableInDatabase.All("WHERE [Order] > " + order);\nvar array = items.ToArray();\nforeach (var i in array)\n{\n    i.Order = 7;\n}\ntableInDatabase.Save(array);	0
17659411	17659274	How can I optimize these null-checking operations?	double x = reader.IsDBNull(1) ? 0 : reader.GetDouble(1);	0
27155674	27155547	Converting a fully lower case / uper case char array back to the user input	public static void Upper(char[] array, string input)\n{\n    Console.WriteLine("Reverse array :");\n    Console.Write(new string(input.AsEnumerable().Reverse().ToArray()));\n}	0
1594194	1594171	Write a method which accepts a lambda expression	void MyMethod(Func<int, int> objFunc)	0
22499807	22459592	Mapping values in dropdown	int[] table1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };\nint[] tableMaster = new int[] { 1, 2, 2, 4, 4, 9 };\nint[] tableChild = (from t in table1\n                    where !tableMaster.Contains(t)\n                    select t).ToArray();	0
14182512	14182385	Private accesor won't access private member	param0.SetField("b", false);	0
25651748	25651318	MySQL Connection String C#	using System;\n//etc etc\nusing MySql.Data.MySqlClient;\n//etc etc\n\nnamespace myapp\n{\n    class Myclass\n    {\n        static void Mymethod(string[] args)\n        {\n            string connStr = "server=server;user=user;database=db;password=*****;";\n            MySqlConnection conn = new MySqlConnection(connStr);\n            conn.Open();\n\n            string sql = "SELECT this FROM that";\n            MySqlCommand cmd = new MySqlCommand(sql, conn);\n            using (MySqlDataReader rdr = cmd.ExecuteReader()) {\n                while (rdr.Read()) {\n                    /* iterate once per row */\n                }\n            }\n        }\n    }\n}	0
3232101	3232042	Closing A Specific WinForm?	List<FormSomthing> _SomethingForms = new List<FormSomething>();\n\n    void DisplaySomething()\n    {\n        FormSomething FormSomething = new FormSomething(SomethingId);\n        _SomethingForms.Add(FormSomething);\n        FormSomething.Show();\n    }\n\n    void CloseThatSucka(int somethingId)\n    {\n        // You might as well use a Dictionary instead of a List (unless you just hate dictionaries...)\n        var form = _SomethingForms.Find(frm => frm.SomethingId == somethingId);\n        if(form != null)\n        {\n            form.Close();\n            _SomethingForms.Remove(form);\n        }\n    }	0
22669800	22669687	Object initializer with arguments of a generic type	public class Test\n{\n   public int Id {get;set;}\n}\n\nprivate ICollection<T> AddRelationalData<T>(List<int> relationalDataIds)\n    where T : Test, new()\n{\n    var relationalDataCollection = new Collection<T>()\n    if (relationalDataIds != null && relationalDataIds.Count > 0)\n    {\n        foreach (var entry in relationalDataIds.Select(id => new T {Id = id}))\n        {\n            relationalDataCollection.Add(entry);\n        }\n    }\n    return relationalDataCollection;\n}	0
9089769	9089693	Can you define an interface such that a class that implements it must contain a member that is also of that class?	interface IAccessibilityFeature<T> where T : IAccessibilityFeature<T>\n{\n    List<T> Settings { get; set; }\n}\n\nclass MyAccess : IAccessibilityFeature<MyAccess>\n{\n    List<MyAccess> Settings { get; set; }\n}	0
11086959	11086625	Are these the simplest ways to apply several different actions to a list of strings using LINQ?	var setOne = new HashSet<string>(textBoxWords.Text\n                               .Split(new char [] { '\r', '\n' })\n                               .Select(s1 => s1.Trim())\n                               .Where(s2 => !String.IsNullOrEmpty(s2)));	0
19805275	19734882	Upload file to Amazon S3 with non default permission	TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()\n{\n    BucketName = existingBucketName,\n    FilePath = fileName,\n    CannedACL = S3CannedACL.BucketOwnerFullControl\n};\n\n// Upload a file, file name is used as the object key name.\nfileTransferUtility.Upload(request);	0
7917087	7916920	Extension method that returns an the correct implementation of an interface?	public static S EnableLazyLoading<T, S>(this S service, bool lazyLoad = true)\n     where S : IBaseService<T>\n{\n     service.UnitOfWork.EnableLazyLoad(lazyLoad);\n     return service;\n}	0
516755	516689	How do I declare the constructor for a generic class with a non-generic base class with parameters	public abstract class EventHandlerBase<TDetail> : EventHandlerBase    \n  where TDetail : Contracts.DeliveryItemEventDetail\n{\n  public EventHandlerBase(AbstractRepository data, ILoggingManager loggingManager)\n    : base(data, loggingManager)\n  {\n     // Initialize generic class\n  }\n}	0
26889606	26889544	Trying to parse an xml file into an Object in C# aspx.net	[XmlElement("_lbl_msmr_text")]\npublic string lbl_msmr_text { get; set; }	0
12863766	12841108	Disable mvc3 client-side validations under certain conditions	RuleFor(model => model.Field).NotEmpty().When(model => model.FieldEnabled);	0
5092036	5091969	Data in Array from N Textboes using For loop	List<string> values = new List<string>();\nforeach(Control c in this.Controls)\n{\n    if(c is TextBox)\n    {\n        /*I didnt need to cast in my intellisense, but just in case!*/\n        TextBox tb = (TextBox)c;\n        values.Add(tb.Text);\n    }\n }\n string[] array = values.ToArray();	0
31940671	31940044	Is it possible to print a PDF document from a Windows Service?	PdfDocument pdfdocument = new PdfDocument();\n   pdfdocument.LoadFromFile(path);\n   pdfdocument.PrinterName = printername;\n   pdfdocument.PrintDocument.PrinterSettings.Copies = copiesNumber;\n   pdfdocument.PrintDocument.Print();\n   pdfdocument.Dispose();	0
20409372	20408993	LINQ returning only rows without any null fields, how to get the null fields too?	from p in GetPersonList()\n    join c in backEnd.GetCarList()\n     on p.PId equals c.PId\n        into joinResults\n    from c in joinResults.DefaultIfEmpty()\n    orderby p.PId descending\n    select new Person\n    {\n        PName = p.PName,\n        PId = p.PId,\n        CModel = c == null ? ( CModel )null : c.CModel,\n    }).ToList()	0
9804593	9804392	How to conditionally redirect depending on login name in ASP.NET C# framework 4	void Page_Load(object sender, EventArgs e)\n{\n    switch (User.Identity.Name)\n    {\n        case "user2":\n        case "user1":\n            Response.Redirect("defualt2.aspx");\n            break;\n        default:\n            Response.Redirect("default3.aspx");\n            break;\n    }\n }	0
31654335	31654161	How to use Parallel.ForEach with dataTable	Parallel.ForEach(dt.Rows.AsEnumerable() , row=>\n            {\n              //code here  \n\n            });	0
2584062	2583606	Mono doesn't write settings defaults	Settings.Default.MySetting1 = Settings.Default.MySetting1;\nSettings.Default.MySetting2 = Settings.Default.MySetting2;\n.........................................................\nSettings.Default.MySettingN = Settings.Default.MySettingN;	0
14773676	14773419	Simulating 'access denied' for a file in C# / Windows	using(File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))\n{\n    //hold here to keep file locked\n}	0
21431228	21232659	Retrieve values ??from the database with jquery	var fechaCadAux = jQuery("#FarmacoGrid").jqGrid('getRowData',rowId).FechaCaducidad;	0
26986592	26986290	Starting firefox with extensions enabled in Selenium	FirefoxProfile profile = new FirefoxProfile();\nprofile.AddExtension(@"C:\path\to\extension.xpi");\nIWebDriver driver = new FirefoxDriver(profile);	0
745070	700310	How do I add an object with the entity framework when it has a foreign key object that already exists	var post = new Post { Id=Guid.NewId(), AuthorReference.EntityKey = new EntityKey("Authors", "Id", authorIdValue) };\nentities.AddToPost(post);	0
5111692	5106736	ComboBox DropDownList and items from picture and text	if( (e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit ) \n{\n    // Do drawing logic just for the top edit part\n}\nelse\n{\n    // Draw logic here for rendering in the drop-down\n}	0
1817753	1817727	How to store results of a LINQ To SQL query in memory	yourTable.OrderBy(x => x.Date).Skip(5).Take(3)	0
14942265	10888754	How do i send a set of keys to my program to implement using code only no keyboard C#?	SendKeys.Send("ABC");	0
10417334	10188285	HTML Agility Pack stripping self-closing tags from input	sXHTML = Regex.Replace(sXHTML, "<input(.*?)>", "<input $1 />");	0
4330499	4330473	List<long> to comma delimited string in C#	var list = new List<long> {1, 2, 3, 4};\nvar commaSeparated = string.Join(",", list);	0
11897843	11897697	Opening Excel Document using EPPlus	protected void BtnTest_Click(object sender, EventArgs e)\n{\n    FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls");\n\n    ExcelPackage pck = new ExcelPackage(newFile);\n    //Add the Content sheet\n    var ws = pck.Workbook.Worksheets.Add("Content");\n    ws.View.ShowGridLines = false;\n\n    ws.Column(4).OutlineLevel = 1;\n    ws.Column(4).Collapsed = true;\n    ws.Column(5).OutlineLevel = 1;\n    ws.Column(5).Collapsed = true;\n    ws.OutLineSummaryRight = true;\n\n    //Headers\n    ws.Cells["B1"].Value = "Name";\n    ws.Cells["C1"].Value = "Size";\n    ws.Cells["D1"].Value = "Created";\n    ws.Cells["E1"].Value = "Last modified";\n    ws.Cells["B1:E1"].Style.Font.Bold = true;\n\n    pck.Save();\n    System.Diagnostics.Process.Start("C:\\Users\\Scott.Atkinson\\Desktop\\Book.xls");\n}	0
13098171	13097449	Reading a stream that may have non-ASCII characters	byte[] data = new byte[len];\nint read, offset = 0;\nwhile(len > 0 &&\n    (read = input_stream.Read(data, offset, len)) > 0)\n{\n    len -= read;\n    offset += read;\n}\nif(len != 0) throw new EndOfStreamException();	0
30130153	30130091	Getting incorrect value after Split	string trimmed = lable_name.Text.Trim();	0
24525982	24525889	Is there a way to send array on javascript to controller other than get or post method??	Url.Action	0
20614537	20563010	How to change the shape of legend entry?	item1.ImageStyle = LegendImageStyle.Line	0
4217669	4216894	Creating and save an image from a byte[] causes Parameter is not valid exception	var fs = new BinaryWriter(new FileStream(@"C:\\tmp\\" + filename + ".ico", FileMode.Append, FileAccess.Write));\nfs.Write(imageByteArray);\nfs.Close();	0
4601870	4601139	How to read a xml string into XMLTextReader type	string szInputXml = "<TestDataXml><DataName>testing</DataName></TestDataXml>";\nXmlTextReader reader = new XmlTextReader( new System.IO.StringReader( szInputXml ) );\nreader.Read();\nstring inner = reader.ReadInnerXml();	0
18815516	18815101	Binding to custom buttons	public static readonly DependencyProperty ButtonText = DependencyProperty.Register("BText", typeof(string), typeof(ButtonImage), new PropertyMetadata(ButtonTextChanged));\n\n    private static void ButtonTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n        txtButtonText.Text = e.NewValue;\n    }	0
533504	533491	How to use SetConsoleHandler() to block exit calls	SetConsoleCtrlHandler()	0
2554581	2554535	How to get only the last two files within a folder using c#	List<FileInfo> lastTwoFiles = directoryInfo.GetFiles()\n                              .OrderBy(x => x.CreationTime).Take(2).ToList()	0
5009451	5009421	How do I return number of members from user controls in ASP.NET 3.5?	Membership.GetAllUsers().Count	0
14003054	14001199	Issue in Parsing Json image in C#	private static string ExtractImageFromTag(string tag)\n {\n int start = tag.IndexOf("src=\""),\n    end = tag.IndexOf("\"", start + 6);\nreturn tag.Substring(start + 5, end - start - 5);\n}\nprivate static string ExtractTitleFromTag(string tag)\n{\nint start = tag.IndexOf(">"),\n    end = tag.IndexOf("<", start + 1);\nreturn tag.Substring(start + 1, end - start - 1);\n}	0
11540230	11540025	How do I activate another Enumerator inside the first one	public IEnumerator<IResult> DoStuffIndependently() {\n    yield return this;\n    yield return that;\n}\n\npublic IEnumerator<IResult> DoStuffBeforeSometimes() {\n    yield return AffectThis;\n    yield return AffectThat;\n\n    var dsi = DoStuffIndependently();\n    while (dsi.MoveNext()) yield return dsi.Current;\n}	0
20064323	20064034	lambda string order by dates with number	private static void sortList()\n{\n    var dates = getDates();\n    var sorted = dates.OrderBy(f1).ThenByDescending(f2);\n}\n\nprivate static DateTime f1(string parse)\n{\n    return DateTime.Parse(parse.Substring(0, 10));\n}\n\nprivate static int f2(string parse)\n{\n    int sort;\n    if (parse.Length > 10) int.TryParse(parse.Substring(18), out sort);\n    else sort = 0;\n    return sort;\n}	0
16070171	16069798	Log-in to a website on button click within the web browser control	private void button4_Click(object sender, EventArgs e)\n{\n   //Set username and password strings\n   string usernameString = "username";\n   string passwordString = "password";\n\n   //Input in to username field\n   var x = webBrowser1.Document.All.GetElementsByName("j_username");\n   x[0].InnerText = (usernameString);\n\n   //Input in to password fields\n   var y = webBrowser1.Document.All.GetElementsByName("j_password");\n   y[0].InnerText = (passwordString);\n\n   //Click the login button\n   var s = webBrowser1.Document.All.GetElementsByName("submit");\n   s[0].InvokeMember("click");\n}	0
24621358	24619917	How can I preload a page I want to navigate to?	var page = new MainPage();	0
2957570	2957489	How do I construct a more complex single LINQ to XML query?	IEnumerable<XElement> ms =\n    from el in mss.Elements("measuresystem")\n    where (string)el.Attribute("name") == "SI"\n    from e2 in el.Elements("dimension")\n    where (string)e2.Attribute("name") == "mass"\n    from e3 in e2.Elements("unit")\n    where (string)e3.Attribute("name") == "kilogram"\n    from e4 in e3.Elements("factor")\n    where (string)e4.Attribute("name") == "pound" \n        && (string)e4.Attribute("foreignsystem") == "US"    \n    select e4;	0
824321	823591	Sending a web page by email programmatically. Image URLs not resolved	HtmlDocument htmlDoc = new HtmlDocument();\n            htmlDoc.LoadHtml(htmlMessage);\n\n//This selects all the Image Nodes\n            HtmlNodeCollection hrefNodes = htmlDoc.DocumentNode.SelectNodes("//img");\n\n            foreach (HtmlNode node in hrefNodes)\n            {\n                string imgUrl = node.Attributes["src"].Value;\n                node.Attributes["src"].Value = webAppUrl + imgUrl;\n            }\n\n    StringBuilder sb = new StringBuilder();\n            StringWriter sw = new StringWriter(sb);\n\n            htmlDoc.OptionOutputAsXml = false;\n            htmlDoc.Save(sw);\n            htmlMessage = sb.ToString();	0
13853953	13853835	Using POP3 how can we download excel attachment	foreach (OpenPop.Mime.MessagePart attachment in attachments)\n                        {\n                            if (attachment != null)\n                            {\n                                string ext = attachment.FileName.Split('.')[1];\n\n                                Filename = DateTime.Now.Ticks.ToString();\n                                FileInfo file = new FileInfo((AppDomain.CurrentDomain.BaseDirectory + "Downloaded//") + Filename + ".csv" );\n\n                                // Check if the file already exists\n                                if (!file.Exists)\n                                {\n                                    attachment.Save(file);\n                                }\n\n                            }\n                  }	0
14308315	14308269	C# double to integer	Decimal m = 42.433243m;\n\nwhile (m % 1 != 0) m *= 10;\nint i = (int)m;	0
29044737	29044699	Splitting data from an array and pulling specific data	class ContactList\n{\nstring firstName, lastName, eMail, ContactNo;\n//Properties (getters/setters for above attributes/fields\n}\n\nclass ContactListHandler\n{\n\npublic List<string> GetFirstNames(string[] contactsText)\n{\n\nList<string> stringList = new List<string>();\n\nforeach (string s in contactsText)\n\n{\nvar x = contactsText.split(',');\nstringList.Add(x[0]);\n}\n\nreturn stringList;\n}\n\n//and other functions\n}\n\nMain()\n{\nContactListHandler cHandler = new ContactListHandler();\nList<string> contactsString = cHandler.GetFirstNames(//your string variable containing the contacts);\n\nforeach(string s in contactsString)\n{\nConsole.WriteLine(s);\n}\n}	0
9496731	9496386	CustomControl inherited from DataGridColumn: problems with styling	Style myStyle = new Style();\nSetter myBlackBackgroundSetter = new Setter();\nmyBlackBackgroundSetter.Property = DataGridCell.BackgroundProperty;\nmyBlackBackgroundSetter.Value = Brushes.Black;\nmyStyle.Setters.Add(myBlackBackgroundSetter);\nCellStyle = myStyle;	0
2646570	2645293	Automapper failing to map on IEnumerable	Mapper.CreateMap<SentEmailAttachment, SentEmailAttachmentItem>();\nvar attachments = Mapper.Map<IEnumerable<SentEmailAttachment>, List<SentEmailAttachmentItem>>(someList);	0
25981592	25977406	Upload a text file with Azure Mobile Services	// Get the new image as a stream.\nusing (var fileStream = await media.OpenStreamForReadAsync())\n{\n    ...\n}	0
15552444	15552275	How to split string in regex	string[] lines = Regex.Split(str, "@"\|\|\^\^");	0
7677163	7676147	How to Reduce the Memory usage of ImageList	using (var tempImage = Image.FromFile(f))\n{\n    Bitmap bmp = new Bitmap(thumbnailWidth, thumbnailHeight);\n    using (Graphics g = Graphics.FromImage(bmp))\n    {\n        g.DrawImage(tempImage, new Rectangle(0, 0, bmp.Width, bmp.Height);\n    }\n    t.Images.Add(bmp);\n}	0
11186792	10992528	binding data to many textboxes with C#	String str = textbox1.Text;\nstr = str + ',' + textbox2.text;\nstr = str + ',' + textbox3.text;	0
27021008	27018654	OpenGL texture+lightning+blending trouble	Color3  (Double red, Double green, Double blue)\nColor3  (SByte red, SByte green, SByte blue)	0
3269944	3267528	Performing a LINQ query with optional search clauses	from p in People.All()\nwhere (firstname == null || string.Equals (firstname, p.FirstName, StringComparison.InvariantCultureIgnoreCase)) &&\n      (lastname == null || string.Equals (lastname, p.LastName, StringComparison.InvariantCultureIgnoreCase))\nselect p	0
21732979	21732897	Deserialization XML in a List	toolList  = (List<Tool>)deserializer.Deserialize(reader);	0
25572275	25570937	Selenium Web Page in Text Search	driver.getPageSource().contains("Text");	0
587007	586827	How do I get a reference to a WCF service object from the code that creates it?	ServiceHost host = new ServiceHost(\n  StringReverser.Instance,\n  new Uri[]{new Uri("net.pipe://localhost")}\n);	0
8467290	8467227	Apply attribute to return value - In F#	let SomeFunc x : [<return: SomeAttribute>] SomeType =\n    SomeOperation x	0
24207655	24207034	How to sort XML elements in parent element?	// No need to specify "Issue" if that's all that's in myXML. Prefer explicit\n// attribute conversion over "manual" parsing\nvar orderedIssues = myXML.Elements().OrderBy(x => (int) x.Attribute("id"));\nmyXML.ReplaceNodes(orderedIssues);	0
18485399	18484577	How to get a random number from a range, excluding some values	private int GiveMeANumber()\n{\n    var exclude = new HashSet<int>() { 5, 7, 17, 23 };\n    var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));\n\n    var rand = new System.Random();\n    int index = rand.Next(0, 100 - exclude.Count);\n    return range.ElementAt(index);\n}	0
6883140	6883097	How can I process this file in C#?	string fileName = "Myfile.txt";\n\nstring[] delimiter = new string[] { " " };\n\nList<string[]> rows = new List<string[]>();\n\nstring[] liens = File.ReadAllLines(fileName);\n\nforeach (string line in liens)\n{\n    rows.Add(line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries));\n}\n\n//Now if you want to display them each one row item separated by tab "`\t"` or csv `","`\nstring separator = "\t";\n\nList<string> output = new List<string>();\n\nforeach (string[] row in rows)\n{\n    output.Add(string.Join(separator, row));\n}\n\nstring newFile = "result.txt";\nFile.WriteAllLines(newFile, output.ToArray());//save the output to new file.	0
12215678	12215551	What FileMode if I want to select a file with FileStream and make a copy?	var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);	0
15945021	15944732	Create a Checkbox for a Winform	if (Checkboxname.Checked = true)\n{\n // Do Stuff when checked\n}	0
427737	427725	How to put an encoding attribute to xml other that utf-16 with XmlWriter?	public sealed class StringWriterWithEncoding : StringWriter\n{\n    private readonly Encoding encoding;\n\n    public StringWriterWithEncoding (Encoding encoding)\n    {\n        this.encoding = encoding;\n    }\n\n    public override Encoding Encoding\n    {\n        get { return encoding; }\n    }\n}	0
11640375	11639412	Adding Key, Value XML Element using C#	function UpdateOrCreateAppSetting(XMLDocument doc, string key, string value)\n{\n    var list = from appNode in doc.Descendants("appSettings").Elements()\n            where appNode.Attribute("key").Value == key\n            select appNode;\n    var e = list.FirstOrDefault();\n\n    // If the element doesn't exist, create it\n    if (e == null) {\n        e = doc.CreateElement("add")\n        e.Attributes.Append("key", key);\n        e.Attributes.Append("value", value);\n        doc.Descendants("appSettings").AppendChild(e);\n\n    // If the element exists, just change its value\n    } else {\n        e.Attribute("value").SetValue(value);\n    }\n}	0
14448556	14448023	How to define a function with an array of pointers of a struct as parameter from C to C#	IntPtr[] lpptr = new IntPtr[iNumber];\nfor (int i=0; i<iNumber; i++)\n    lpptr[i] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SomeStruct)));	0
2997908	2997885	Setting the service URL at runtime	YourService service = new YourService();\nservice.Url = "http://some.other.url/";\n\n// Now you're ready to call your service method\nservice.SomeUsefulMethod();	0
20108762	20103855	Specify the name of a parent-child join table using EF6 Code-First EntityTypeConfiguration	HasMany(n => n.Children).WithMany().Map(\n    m => m.ToTable("OrgRelationship").MapLeftKey("ParentId").MapRightKey("ChildId"));	0
18791181	18791127	Reading all lines from file asynchronously and safely	public static void GetLines(Action<string> callback)\n{\n    var encoding = new UnicodeEncoding();\n    byte[] allText;\n    FileStream stream = File.Open(_path, FileMode.Open);\n    allText = new byte[stream.Length];\n    //something like this, but does not compile in .net 3.5\n    stream.ReadAsync(allText, 0, (int)allText.Length);\n    stream.BeginRead(allText, 0, allText.Length, result =>\n    {\n        callback(encoding.GetString(allText));\n        stream.Dispose();\n    }, null);\n}	0
18379626	18379492	Extract some numbers and decimals from a string	string input = "   a.1.2.3 #4567   ";\nint poundIndex = input.IndexOf("#");\nif(poundIndex >= 0)\n{\n    string relevantPart = input.Substring(0, poundIndex).Trim();\n    IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));\n    string result = new string(numPart.ToArray());\n}	0
6441784	6441673	Map Data From Array To ListView	listView1.Items.AddRange\n    (\n        (\n            from c in classList\n            where c.Status = 1\n            select new ListViewItem(c.Text1 + c.Text2, c.Text3)\n        ).ToArray()\n    );	0
33446666	33446571	Set properties of an object to be relative to another property of the same object	public class Ball : IBall\n{\n    public int Y { get; set; }\n    public int X { get; set; }\n    public int VX { get; set; }\n    public int VY { get; set; }\n    public static int Width;\n    public static int Speed;\n\n    public int Top\n    {\n        get\n        {\n            return Y; \n        }\n    }\n\n    public int Left\n    {\n        get\n        {\n            return X;\n        }\n    }\n\n    public int Right\n    {\n        get\n        {\n            return X + Ball.Width;\n        }\n    }\n\n    public int Bottom\n    {\n        get\n        {\n            return Y + Ball.Width;\n        }\n    }\n}	0
1507194	1507153	c#: How can I verify methods are called in a certain order?	var mocks = new MockRepository();\nvar printer = mocks.DynamicMock<IPrinter>();\nusing (mocks.Ordered())\n{\n    printer.Expect(x => x.PrintComment());\n    printer.Expect(x => x.PrintSpecial());\n    printer.Expect(x => x.PrintComment());\n}\nprinter.Replay();\nScript = new Script(printer);\n\n... Execute Test...\n\nprinter.VerifyAllExpectations();	0
12217903	12217533	Dynamically adjusting the DropDownHeight of a custom ComboBox C#	private void ShowDropDown() \n{\n   if (dropDown != null)\n   {\n      treeViewHost.Width = DropDownWidth;\n      treeViewHost.Height = DropDownHeight;\n      dropDown.Show(this, 0, this.Height);\n   }\n}	0
536964	536932	how to create expression tree / lambda for a deep property from a string	setProperyValue(obj, propertyName, value)\n{\n  head, tail = propertyName.SplitByDotToHeadAndTail(); // Person.Address.Postcode => {head=Person, tail=Address.Postcode}\n  if(tail.Length == 0)\n    setPropertyValueUsingReflection(obj, head, value);\n  else\n    setPropertyValue(getPropertyValueUsingReflection(obj, head), tail, value); // recursion\n}	0
18344432	18344397	Regex Pattern that Looks for a String between two Specified Strings	string input = @"Date: 8/20/2013 12:00:00 AM Source Path: \\build\PM\11.0.25.9\ Destination Path: C:\Users\Documents\testing\11.0.25.9\etc\ Folder Updated: 11.0.25.9 File Copied: 11052_0_X.pts";\nstring pattern = @"Source Path:(.+?)Destination Path:";\n\nvar src = Regex.Match(input,pattern).Groups[1].Value.Trim();	0
3334966	3298896	Suppress exception popup window for .NET application launched from unattended code	int waitTimeSecs = 120;    \n\nbool cleanExit = process.WaitForExit(waitTimeSecs * 1000);\nif (!process.HasExited)\n{\n    process.CloseMainWindow();\n    System.Threading.Thread.Sleep(2000);\n}\n\nif (!process.HasExited)\n{\n    process.Kill();\n    process.WaitForExit();\n    // if an exception window has popped up, that needs to be killed too\n    // DW20 is the Dr. Watson application error handling process\n    foreach (var process in Process.GetProcessesByName("DW20"))\n    {\n        process.CloseMainWindow();\n        System.Threading.Thread.Sleep(2000);\n        if (!process.HasExited)\n            process.Kill();\n    }\n}	0
17339125	17338639	C# - Change value of all rows of a specific colum of a DataTable	int columnNumber = 5; //Put your column X number here\nfor(int i = 0; i < yourDataTable.Rows.Count; i++)\n{\n    if (yourDataTable.Rows[i][columnNumber].ToString() == "TRUE")\n    { yourDataTable.Rows[i][columnNumber] = "Yes"; }\n    else\n    { yourDataTable.Rows[i][columnNumber] = "No"; }\n}	0
21865870	21865745	What is the purpose of having a private variable when creating a public property?	private int _widget = 123;\npublic int widget\n{\n  get{ return _widget; }\n  set{ _widget = value; }\n}	0
7601887	7601759	C# - Add XML Namespace (xmlns) tag to document	using System;\nusing System.Xml.Linq;\n\nclass Test\n{\n    static void Main()\n    {\n        XNamespace ns = "http://www.acme.com/ABC";\n        DateTimeOffset date = new DateTimeOffset(2011, 9, 16, 10, 43, 54, 91,\n                                                 TimeSpan.FromHours(1));\n        XDocument doc = new XDocument(\n            new XElement(ns + "ABC",\n                         new XAttribute("xmlns", ns.NamespaceName),\n                         new XAttribute(XNamespace.Xmlns + "xsi",\n                              "http://www.w3.org/2001/XMLSchema-instance"),\n                         new XAttribute("fileName", "acmeth.xml"),\n                         new XAttribute("date", date),\n                         new XAttribute("origin", "TEST"),\n                         new XAttribute("ref", "XX_88888")));\n\n        Console.WriteLine(doc); \n    }\n}	0
17036356	17035876	xml display in asp.net page	...\n  Response.ContentType = "text/xml"; \n  Response.Write(contacts);	0
14269728	14257428	Reverse PInvoke from native C++	#include <mscoree.h>\n#include <stdio.h>\n#pragma comment(lib, "mscoree.lib") \n\nvoid Bootstrap()\n{\n    ICLRRuntimeHost *pHost = NULL;\n    HRESULT hr = CorBindToRuntimeEx(L"v4.0.30319", L"wks", 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (PVOID*)&pHost);\n    pHost->Start();\n    printf("HRESULT:%x\n", hr);\n\n    // target method MUST be static int method(string arg)\n    DWORD dwRet = 0;\n    hr = pHost->ExecuteInDefaultAppDomain(L"c:\\temp\\test.dll", L"Test.Hello", L"SayHello", L"Person!", &dwRet);\n    printf("HRESULT:%x\n", hr);\n\n    hr = pHost->Stop();\n    printf("HRESULT:%x\n", hr);\n\n    pHost->Release();\n}\n\nint main()\n{\n    Bootstrap();\n}	0
17370053	17368740	WinStore App Listview: Avoiding multiple lines with the same name	XDocument doc = XDocument.Load("Music.xml");\nvar data = doc.Descendants("singer").Select(x => new Singer {\n    Name = (string)x.Element("name"),\n    Song = (string)x.Element("song"),\n    Lyrics = (string)x.Element("lyrics")\n});\nList<string> dataToBind = data.Select(x => x.Name).Distinct().ToList();	0
6354214	6353883	How to show video file and word file in gridview from the database?	1. Convert the binary file to a byte array as follows,\n\n                byte[] byteArray=GetBinaryFromDB().TOArray();\n\n  2. Then pass the byte array to the following function within System.IO namespace,\n\n                File.WriteAllBytes (strng path, byte[] bytes) //This will save your file in the path you specified as first argument.	0
5166902	5166289	multiple controllers in Areas and Main site	context.MapRoute(\n    "Admin_default",\n    "Admin/{controller}/{action}/{id}",\n    new { controller = "Home", action = "Index", id = UrlParameter.Optional },\n    new string[] { "MvcBase.Areas.Admin.Controllers" }\n);	0
14798792	14798751	How to calculate a new lat long based on distance from a point	decimal lat0 = startingLat + dLat * (180 * pi);\n    decimal lon0 = startingLon + dLon * (180 / pi);	0
27014844	27014689	Reading XMl Data same nodes in C#	XElement elem = XElement.Parse(xmldata);\n\nIEnumerable<XElement> addresses = elem.Descendants("streetAddress");	0
5067380	5066659	How do I save this object to a file?	Aspose.Words.Document d = new Document(@"C:\users\john\desktop\embeddedPDF.docx");\n        foreach (Aspose.Words.Drawing.Shape shp in d.GetChildNodes(NodeType.Shape, true))\n        {\n        shp.OleFormat.Save(@"C:\Temp\testoutput.pdf");\n        }	0
3397234	3396744	how to calculate(sum up) an a row value of an datatable	DataTable sumDataTable = new DataTable();\n        sumDataTable.Columns.Add("total", typeof(string));\n        sumDataTable.Columns.Add("workedhours", typeof(int));\n        sumDataTable.Columns.Add("tfshours", typeof(int));\n\n        DataRow row = sumDataTable.NewRow();\n        row["total"] = "Total";\n        row["workedhours"] = oldDataTable.Compute("Sum(workedhours)", "workedhours > 0");\n        row["tfshours"] = oldDataTable.Compute("Sum(tfshours)", "tfshours > 0");\n        sumDataTable.Rows.Add(row);	0
27623283	27622627	Getting Data From IEnumerable	var codes = File\n    .ReadLines(@"C:/AirCodes/RAPT.TXT")\n    .Select(line => line.Split(','))\n    .Select(items => new {\n       // I've created a simple anonymous class, \n       // you'd probably want to create you own one\n       Code = items[0].Trim('"'),    //TODO: Check numbers\n       Airport = items[2].Trim('"'),\n       Country = items[3].Trim('"')\n    })\n    .ToList();\n\n  ...\n\n  foreach(var item in codes) \n    Console.WriteLine(item);	0
18942752	18942636	Console Application Input Validation for Int & Float Max Values C#	bool validated = false;\nint integerRequired;\nConsole.WriteLine("Type an integer number:");\nwhile(validated == false)\n{    \n    string userInput = Console.ReadLine();\n    validated  = int.TryParse (userInput, out integerRequired);\n    if (!validated )\n        Console.WriteLine("Not a valid integer, please retype a valid integer number");\n}\n\nfloat singleRequired;\nvalidated = false;\nConsole.WriteLine("Type a floating point number:");\nwhile(validated == false)\n{    \n    string userInput = Console.ReadLine();\n    validated  = Single.TryParse (userInput, out singleRequired);\n    if (!validated)\n        Console.WriteLine("Not a valid float, please retype a valid float number");\n}	0
3483589	3483451	Is there any way to get the PropertyInfo from the getter of that property?	PropertyInfo property = GetType()\n                            .GetProperty(MethodBase\n                                             .GetCurrentMethod()\n                                             .Name\n                                             .Substring("get_".Length)\n                                        );	0
545748	545735	How can I navigate deeper in XML and append data in it	XmlElement parent = (XmlElement)doc.SelectSingleNode("/report/section/hosts")\nparent.AppendChild(subRoot);	0
19815925	19810374	entity framework unidirectional association from one to many	public class A \n{\n   public Guid Id {get; set;}\n\n   public Account Account{get; set;}\n   // FK-Nav property\n   public Guid AccountKey{get;set;}\n   public class EntityConfiguration : EntityConfigurationBase<A>\n   {   \n       public EntityConfiguration()\n       {\n\n           HasOptional(x => x.Account).HasMany().HasForeignKey(x=>x.AccountKey);\n        }\n    }\n}	0
23461473	23458813	Controling EF database creation and migration	var migrator = new DbMigrator(new MyMigrationsConfiguration());\nmigrator.Update();	0
34530325	34508446	Connecting to a paired BLE Device	uncached mode	0
2983026	2951752	No DocBrokers are configured	dfc.docbroker.host[0]=[docbroker host]	0
10419680	10419553	How to raise property changed event from outside of Entity?	public partial class MyEntity\n{    \n    public void RaisePropertyChanged(string propertyName)\n    {\n       this.RaisedPropertyChanged(propertyName);\n    }\n}	0
10503278	10503229	Navigate between two Placeholders with a LinkButton in asp.net	plh1.Visible = true;\nplh2.Visible = false;	0
1169232	1168976	WPF DataGrid - Button in a column, getting the row from which it came on the Click event handler	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    MyObject obj = ((FrameworkElement)sender).DataContext as MyObject;\n    //Do whatever you wanted to do with MyObject.ID\n}	0
24417998	24416597	ComboBox in DataGridView changes colors when I leave cell	DataGridViewComboBoxColumn myCombo = new DataGridViewComboBoxColumn();\n  dataGridView1.DataSource = dataSetFromDatabaseCall.Tables[0];\n  myCombo.HeaderText = "My Combo";\n  myCombo.Name = "myCombo";\n  this.dataGridView1.Columns.Insert(1, myCombo);\n\n  myCombo.Items.Add("test1");\n  myCombo.Items.Add("test2");\n  myCombo.Items.Add("test3");\n\n\n\n //event to check the cell value changed\n private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n {\n        if (e.ColumnIndex == myCombo.Index && e.RowIndex >= 0) //check if it is the combobox column\n        {\n            dataGridView1.CurrentCell.Style.BackColor = System.Drawing.Color.Yellow;\n        }\n }\n\n private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)\n {\n        if (dataGridView1.IsCurrentCellDirty)\n        {\n            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);\n        }\n }	0
31577367	31577193	Use POST to send data to multiple aspx files	function UpdateToModifyForm() {\n    document.nameOfTheForm.action = "modify.aspx";\n}\n\nfunction UpdateToDeleteForm() {\n    document.nameOfTheForm.action = "delete.aspx";\n}	0
10831868	10829979	Sending notifications client	try\n{\n    // Establish the remote endpoint for the socket.\n\n    // This example uses port 11000 on the local computer.\n    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())\n\n    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n\n    IPAddress ipAddress = ipHostInfo.AddressList[0];\n    IPEndPoint remoteEP = new IPEndPoint(ipAddress,15000);\n    string notification = "new_update";\n    byte[] sendBuffer = Encoding.ASCII.GetBytes(notification);\n    sock.SendTo(sendBuffer, remoteEP );\n    sock.Close();  \n}\ncatch() {}	0
2390837	2390830	Is there a class like Dictionary<> in C#, but for just keys, no values?	HashSet<T>	0
24404056	24403150	DataGridView in winforms application && List of structs	public string Jour; { get; set; }\npublic string LaDate; { get; set; }\npublic int Heures; { get; set; }\npublic int Minutes; { get; set; }	0
23413561	23413473	How to detect if an app is running on Windows RT or Windows 8 Pro?	using System.Management;\nvar name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()\n                      select x.GetPropertyValue("Caption")).FirstOrDefault();\nreturn name != null ? name.ToString() : "Unknown";	0
22860763	22860724	Best way to lookup numbers in multiples of 3's C#	int number = 4;\nint result = number % 3;	0
3887274	3887083	Hashing strings to Color in C#	var words = ("She sells sea shells on the sea shore but the sea " +\n             "shells she sells are sea shells no more.").Split(' ');\nvar md5 = MD5.Create();\nvar box = new ListBox\n    {\n        Dock = DockStyle.Fill,\n        DrawMode = DrawMode.OwnerDrawFixed\n    };\nbox.Items.AddRange(words);\nbox.DrawItem += (sender, e) =>\n    {\n        var value = (string) box.Items[e.Index];\n        var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(value));\n        var color = Color.FromArgb(hash[0], hash[1], hash[2]);\n        using (var backBrush = new SolidBrush(color))\n        using (var foreBrush = new SolidBrush(e.ForeColor))\n        {\n            e.Graphics.FillRectangle(backBrush, e.Bounds);\n            e.Graphics.DrawString(value, e.Font, foreBrush, e.Bounds);\n        }\n        e.DrawFocusRectangle();\n    };\nnew Form {Controls = {box}}.ShowDialog();	0
401356	401348	How to build DataContractJsonSerialize convenience function	public static string GenerateJsonString(object o) \n{\n    DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());\n    using (MemoryStream ms = new MemoryStream())\n    {\n        ser.WriteObject(ms, o);\n        json = Encoding.Default.GetString(ms.ToArray());\n        ms.Close();\n        return json;\n    }\n}	0
11105512	11105459	How to get value inside observable collection?	void proxy_FindProfileCompleted(object sender, FindProfileCompletedEventArgs e)\n{             \n    ListBox1.ItemsSource = e.Result;\n    ObservableCollection<Customer> Customers = \n        this.ListBox1.ItemsSource as ObservableCollection<Customer>;  \n    foreach(Customer cust in Customers)\n    {\n        // You can get cust.CustName\n        // and you can get cust.CustEmail\n    }\n}	0
17793001	17792978	How to specify the get/set internal var in a property in C#	private int _myInt;\npublic int MyInt { get { return _myInt; } }\n\n// or\n\nprivate int _myInt;\npublic int MyInt { get { return _myInt; } private set { _myInt = value; } }	0
33613822	33613512	Add image source to HTML using C# variable	var url - communityHeader.LeftLogo.MediaUrl;\nLeftLogo2.Attributes["src"]=url;	0
2012251	2012222	Determining colour hex value for image in C#	Bitmap bmp = new Bitmap ("somefile.jpg");\nColor pixelColor = bmp.GetPixel (0, 0);	0
8491098	8490599	How to create ImageBrush from System.Drawing.Image in WPF?	var image = System.Drawing.Image.FromFile("..."); // or wherever it comes from\n      var bitmap = new System.Drawing.Bitmap(image);\n      var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),\n                                                                            IntPtr.Zero,\n                                                                            Int32Rect.Empty,\n                                                                            BitmapSizeOptions.FromEmptyOptions()\n            );\n      bitmap.Dispose();\n      var brush = new ImageBrush(bitmapSource);	0
23074453	23005157	Html Decode with Lambda Expression in .Net	Address = x.Address,\n                        UserPic = x.UserPic,\n                        CoverPic = x.CoverPic,\n                        Detail = Regex.Replace(x.Detail, "<.*?>", string.Empty),\n                        FollowerCount = x.FollowerCount,\n                        Name = x.Name,\n                        IsFollow = x.IsFollow,\n                        Categories = x.Categories,\n                        Followers = x.Followers\n\n                    }).FirstOrDefault();	0
8242414	8242066	Arbitrary data types in Settings file	Settings.Designer.cs	0
1350070	1348188	Simplfying DSL written for a C# app with IronPython	var objOps = _engine.Operations;\nvar lib = new Lib();\n\nforeach (string memberName in objOps.GetMemberNames(lib)) {\n    _scope.SetVariable(memberName, objOps.GetMember(lib, memberName));\n}	0
16686880	16686098	How I can fill a treeView with a List<string>?	XmlReader xr = XmlReader.Create(new StringReader(final_output));\n\n       while (xr.Read())\n       {\n           switch (xr.Name)\n           {\n               case "FEATURE":\n                    TreeNode root = MyTreeView.Nodes.Add("FEATURE");\n                   if (xr.HasAttributes)\n                   {\n                       while (xr.MoveToNextAttribute())\n                       {\n                           if (xr.Name == "NAME")\n                           {\n                               TreeNode workingNode = root.Nodes.Add(xr.Value.ToString());\n                               liste.Add(xr.Value);\n                           }\n                       }\n                   }\n                   break;\n\n           }\n       }	0
7309638	7309599	Activating Console window	[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);	0
10825099	10825033	RichTextBox is satisfied when finding one match; I want it to keep searching	int pos = 0;\npos = richText.IndexOf(textToFind, 0);\nwhile(pos != -1)\n{\n    tOut.Select(pos, textToFind.Length); \n    tOut.SelectionBackColor = Color.Red; \n    pos = richText.IndexOf(textToFind, pos + 1);\n}	0
25860248	25860183	How do I use LINQ to compare a date and a datetime?	.Where(d => d.DateTime.Date == new DateTime(2014, 09, 05))	0
13968006	13957707	Unable to edit item of a SelectListItem	public class AppointmentStatus \n{\n     public int Id {get;set;}\n     public string I18NKey {get;set;}\n     public string Translation {get;set;}\n}\n\npublic static IEnumerable<AppointmentStatus> TranslateValue(IEnumerable<AppointmentStatus> list)\n    {\n        foreach (var tmp in list)\n        {\n            tmp.Translation = I18nHelper.Message(tmp.I18NKey);\n        }\n        return list;\n    }\n\nHtml.DropDownListFor(x=>x.Id, new SelectList(HelperClass.TranslateValue(MyListOfStatus), "Id","Translation")	0
29265567	29262620	Unity3D v5 setting up a vertex shader from a old custom shader	Shader "Depth Mask" {\n    SubShader {\n        Tags {"Queue" = "Geometry-10"}\n        Lighting Off\n        ZTest LEqual\n        ZWrite On\n        ColorMask 0\n        Pass {}\n    }\n}	0
25916996	25916662	Animate DropShadowEffect Color	Moon.Effect.BeginAnimation(DropShadowEffect.ColorProperty, (AnimationTimeline)DS_Moonlight);	0
17221876	17221590	Connecting to web-service without metadata	svcutil.exe	0
1951026	1951004	Convert dd/MM/yyyy hh:mm:ss.fff from String to DateTime in C#	string timeString = "11/12/2009 13:30:00.000";\nIFormatProvider culture = new CultureInfo("en-US", true); \nDateTime dateVal = DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss.fff", culture);	0
13089090	12488876	All possible combinations of boolean variables	public string CombinationFinder(){\n        for(int i=0;i<2^8;i++){\n        String ans= Convert.ToInt32(i,2).ToString();\n        if(myMethod(ans)) return ans;\n        }\nreturn null;\n    }	0
21684271	21684243	Accessing single-dimensional array entries with index array	string[] someWords = indices.Select(index => myWords[index]).ToArray();	0
30117496	30117375	Adding items to List after reading from JSON	listItemsJson.Add(new prepackList());\n\nvar updatedJson = JsonConvert.SerializeObject(listItemsJson);	0
1152589	1152583	C#:DateTime.Now Month output format	DateTime.Now.Month.ToString("d2")	0
24536541	24536491	Time elapsed between two dates	totalTime = \n    (daysEl  == 0 ? "" : (daysEl  + " days "))\n  + (hoursEl == 0 ? "" : (hoursEl + " hours "))\n  + (minsEl  == 0 ? "" : (minsEl  + " minutes "))\n  + (secsEl  == 0 ? "" : (secsEl  + " seconds "));	0
6181000	6180927	Removing all records from navigation properties in Entity Framework	program.Students.Clear()	0
3670811	3670765	Set the background color of all objects in C#	ChangeColor_Click\n{\n   ChangeAllBG(this);\n}\n\nvoid ChangeAllBG(Control c)\n{\n    c.BackColor=Color.Teal;\n    foreach (Control ctl in c.Controls)\n        ChangeAllBG(ctl);\n}	0
27561690	27561615	Is there a equivalent of boost::timer::cpu_timer in c#?	Process.GetCurrentProcess().TotalProcessorTime	0
3682726	3682708	How to Nested Case in Select SQL?	;with SuperSelect as \n(\n SELECT  dpl.CaseNumber as 'CASE NO.'\n     ,dpl.ItemNumber as 'BOM NO.'\n     ,dpl.Quantity as 'QTY'\n     ,CASE WHEN dpl.Quantity >= 31 and dpl.Quantity <= 36 then '1090x730x1460'\n     WHEN dpl.Quantity >= 25 and dpl.Quantity <= 30 then '1090x730x1230'\n     WHEN dpl.Quantity >= 19 and dpl.Quantity <= 24 then '1090x730x1000'\n     WHEN dpl.Quantity >= 13 and dpl.Quantity <= 18 then '1090x720x790'\n     WHEN dpl.Quantity >= 7 and dpl.Quantity <= 17 then '1090x720x570'\n     WHEN dpl.Quantity >= 1 and dpl.Quantity <= 6 then '1090x720x350'\n     ELSE 'Unkown'\n   end as 'TOTAL VOLUME (MM3)'\n FROM    DropshipPackinglist dpl\n INNER JOIN HuaweiDescription hd ON dpl.ItemNumber = hd.ItemNumber\n WHERE   (dpl.BatchCode LIKE '%0005041007100AHWA11HG')\n)\nselect *, sum([QTY]) over (partition by ss.[CASE NO.]) [TotalVolume]\nfrom SuperSelect ss	0
26689377	26689259	Categorizing string based on input in C#	static void Main(string[] args)   \n{ \n    var inputList = new List<string>\n    {\n        "John likes pancakes",\n        "John hates watching TV",\n        "I like my TV",\n    };\n\n    var dic = new Dictionary<string, int>();\n    inputList.ForEach(str => AddToDictionary(dic, str));\n\n    foreach (var entry in dic)\n        Console.WriteLine(entry.Key + ": " + entry.Value);\n}\n\nstatic void AddToDictionary(Dictionary<string, int> dictionary, string input)\n{\n    input.Split(' ').ToList().ForEach(n =>\n    {\n        if (dictionary.ContainsKey(n))\n            dictionary[n]++;\n        else\n            dictionary.Add(n, 1);\n    });\n}	0
11858798	11858663	Computing a constant based on current time	static string GetValue(DateTime date)\n{\n    var time = date.TimeOfDay;\n    if (time.TotalHours >= 6 && time.TotalHours < 14)\n    {\n        return "A";\n    }\n\n    if (time.TotalHours >= 14 && time.TotalHours < 22)\n    {\n        return "B";\n    }\n\n    return null;\n}	0
13027138	13026980	Wait with return statement until Timer elapsed	public static bool RecognizePushGesture()\n    {\n        AutoResetEvent ar = new AutoResetEvent(false);\n        List<Point3D> shoulderPoints = new List<Point3D>();\n        List<Point3D> handPoints = new List<Point3D>();\n        shoulderPoints.Add(Mouse.shoulderPoint);\n        handPoints.Add(Mouse.GetSmoothPoint());\n        Timer dt = new Timer(1000);\n        bool click = false;\n        dt.Elapsed += (o, s) =>\n        {\n            shoulderPoints.Add(Mouse.shoulderPoint);\n            handPoints.Add(Mouse.GetSmoothPoint());\n            double i = shoulderPoints[0].Z - handPoints[0].Z;\n            double j = shoulderPoints[1].Z - handPoints[1].Z;\n            double k = j - i;\n            if (k >= 0.04)\n            {\n                click = true;\n                dt.Stop();\n            }\n            ar.Set();\n        };\n        dt.Start();\n\n        //should wait with returning the value until timer raises elapsed event\n        ar.WaitOne();\n        return click;\n    }	0
9062983	9062851	Insert dot after each words in string	dotted = string.Join(". ","Hello! It is nice day today.".Split(' ')) + ".";	0
2337036	2337001	Patterns / design suggestions for permission handling	bool UserHasPermission( SOME_PERMISSION )	0
16492578	16492555	While it is impossible to create a constant property, is there a way to avoid breaking DRY-rule when working with constant fields?	class BaseClass\n{\n    public const int MAX_STEPS = 0;\n    protected int currentSteps;\n\n    public BaseClass() { currentSteps = MAX_STEPS; }\n    protected BaseClass(int maxSteps)\n    {\n        currentSteps = maxSteps;\n    }\n}\n\nclass ChildClass1 : BaseClass\n{\n    public const int MAX_STEPS = 5;\n    public ChildClass1() : base(MAX_STEPS) { }\n}\n\nclass ChildClass2 : BaseClass\n{\n    public const int MAX_STEPS = 10;\n    public ChildClass2() : base(MAX_STEPS) { }\n}	0
24909982	24906802	Issue in binding Image Source with two different file format	public static BitmapImage BitmapImageFromBitmapSourceResized(BitmapSource bitmapSource, int newWidth)\n    {\n        BmpBitmapEncoder encoder = new BmpBitmapEncoder();\n        MemoryStream memoryStream = new MemoryStream();\n        BitmapImage bImg = new BitmapImage();\n\n        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));\n        encoder.Save(memoryStream);\n\n        bImg.BeginInit();\n        bImg.StreamSource = new MemoryStream(memoryStream.ToArray());\n        bImg.DecodePixelWidth = newWidth;\n        bImg.EndInit();\n        memoryStream.Close();\n        return bImg;\n    }	0
1182238	1182227	Check if a value is in a collection with LINQ	if( ! employee.TypeOfWorks.Any(tow => tow.Id == theNewGUID) )\n    //save logic for TypeOfWork containing theNewGUID	0
1053178	1053162	send mouseclick message in .net	Control.InvokeOnClick	0
28328913	28328220	Awesomium WebControl load string	var uri = new Uri("data:text/html,<!DOCTYPE html><html>...", UriKind.Absolute);\n\n            webControl.Source = uri;	0
8752659	8752586	How to Convert C# Variable DateTime Into SqlDbType.DateTime	var cmd = new SqlCommand();\n            cmd.Connection = conn;\n\n            DateTime MyDate = DateTime.Now;\n\n            cmd.CommandText = @"SELECT * FROM TABLE WHERE CreateDt = @MyDate";\n            cmd.Parameters.AddWithValue("@MyDate", @MyDate);\n\n            SqlDataAdapter adapter = new SqlDataAdapter();\n            adapter.SelectCommand = cmd;\n            adapter.FillSchema(Table, SchemaType.Source);\n            adapter.Fill(Table);	0
29567885	29567319	When I try to filter my data and then apply a sort, I get back all results	DataView custView = new DataView(dt);\n\nif (DropDownList1.SelectedValue != "All")\n{\n   custView.RowFilter = "category='" + DropDownList1.SelectedValue.ToString() + "'";\n\n}\ncustView.Sort = e.SortExpression + " " + SortDirection;	0
3549128	3549062	Create function to loop through properties of a method in C#?	ABC abc = new ABC();\ntry {\n    a.xyz = "Runtime value";\n    //Exception thrown here ...\n}\ncatch (Exception ex)\n{    \n    Log.LogDebugFormatted(\n      "Exception caught. abc.xyz value: {0}. Exception: {1}", abc.xyz, ex);\n    throw ex;\n}	0
22222332	22003737	Setting up FormsAuthentication after SSO authentication	protected void Session_Start()\n    {\n        if (!Request.IsAuthenticated && !IsSignoutURL)\n            AcceptSessionRequest(); //process local authentication\n\n        else if (IsSignoutURL)\n            RejectSessionRequest(); //kill the sessions\n    }	0
30902143	30303748	Sharepoint Provider Hosted User Permissions	public SharePointPermissionsAuthorizationAttribute( params string group) { _groups = groups; } \n\n\n\n\n[SharePointEffectivePermissionsFilter("Engineer"]\n public ActionResult Index() { ... } }	0
7384890	7384802	Regex replace all function	var result = Regex\n    .Replace(input, @"(?<=\$)\d+(?=\$)", m => (int.Parse(m.Value) + 1).ToString());	0
4380220	4380125	How to minimize if's to a for in c#	foreach (ctl in page.ctls)\n{\n  TextBox tempTextBox = ctl as TextBox;\n  if (tempTextBox != null)\n  {\n    doTheSameForEveryTextBox(tempTextBox)\n  }\n\n  DropDownList tempDropDownList as DropDownList; // not sure if this is the right Type...\n  if (tempDropDownList != null)\n  {\n    doTheSameForEveryTextBox(tempDropDownList)\n  }\n}\n\nvoid doTheSameForEveryTextBox(TextBox tempTextBox)\n{\n  if (tempTextBox.Text == "")\n  {\n    //TODO: implement your code here\n  }\n}\n\nvoid doTheSameForEveryDropDownList(DropDownList tempDropDownList)\n{\n  if (tempDropDownList.SelectedIndex == 0)\n  {\n    //TODO: implement your code here\n  }\n}	0
17953297	17953173	How can I assign the value selected in a listbox to an enum var?	Array values = Enum.GetValues(typeof(BeltPrinterType));//If this doesn't help in compact framework try below code\nArray values = GetBeltPrinterTypes();//this should work, rest all same\nforeach (var item in values)\n{\n    listbox.Items.Add(item);\n}\n\nprivate static BeltPrinterType[] GetBeltPrinterTypes()\n{\n    FieldInfo[] fi = typeof(BeltPrinterType).GetFields(BindingFlags.Static | BindingFlags.Public);\n    BeltPrinterType[] values = new BeltPrinterType[fi.Length];\n    for (int i = 0; i < fi.Length; i++)\n    {\n        values[i] = (BeltPrinterType)fi[i].GetValue(null);\n    }\n    return values;\n    }\n\nprivate void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)\n{\n    if(!(listBoxBeltPrinters.SelectedItem is BeltPrinterType))\n    {\n        return;\n    }\n    PrintUtils.printerChoice = (BeltPrinterType)listBoxBeltPrinters.SelectedItem;\n}	0
13310736	2593768	Convert a image to a monochrome byte array	Rectangle rect = new Rectangle(0, 0, Bitmap.Width, Bitmap.Height);\nSystem.Drawing.Imaging.BitmapData bmpData = null;\nbyte[] bitVaues = null;\nint stride = 0;\ntry\n{\n    bmpData = Bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, Bitmap.PixelFormat);\n    IntPtr ptr = bmpData.Scan0;\n    stride = bmpData.Stride;\n    int bytes = bmpData.Stride * Bitmap.Height;\n    bitVaues = new byte[bytes];\n    System.Runtime.InteropServices.Marshal.Copy(ptr, bitVaues, 0, bytes);\n}\nfinally\n{\n    if (bmpData != null)\n        Bitmap.UnlockBits(bmpData);\n}	0
13700085	13699865	Merge a collection with duplicate objects and update some properties with LINQ	var f = units.First(u => u.ID == "F");\nint newFIndex = 2;\nvar updateUnits = units\n    .Where(u => u.Index >= newFIndex && u.Index < f.Index)\n    .ToList();\nforeach (OrganisationUnit u in updateUnits)\n    u.Index++;\nf.Index = newFIndex;	0
9868355	9839231	Restrict tab order to a single user control	private int WM_KEYDOWN = 0x100;\n\n    public override bool PreProcessMessage(ref Message msg)\n    {\n        Keys key = (Keys)msg.WParam.ToInt32();\n\n        if (msg.Msg == WM_KEYDOWN && key == Keys.Tab)\n        {\n            if (itemSearchControl.Visible)\n            {\n                bool moveForward = !IsShiftKeyPressed();\n                bool result = itemSearchControl.SelectNextControl(itemSearchControl.ActiveControl, true, true, true, true);\n                return true;\n            }\n        }\n\n        return base.PreProcessMessage(ref msg);\n    }	0
1263715	1263706	Performing your own runtime analysis of your code in C#	public class TraceAttribute : OnMethodBoundaryAspect \n{ \n  public override void OnEntry( MethodExecutionEventArgs eventArgs) \n  { Trace.TraceInformation("Entering {0}.", eventArgs.Method);  } \n\n  public override void OnExit( MethodExecutionEventArgs eventArgs) \n  { Trace.TraceInformation("Leaving {0}.", eventArgs.Method);   } \n}	0
8055991	8055902	LINQ to XML without knowing the nodes	public static XElement ElementOrDummy(this XElement parentElement, \n                                      XName name, \n                                      bool ignoreCase)\n{\n    XElement existingElement = null;\n\n    if (ignoreCase)\n    {\n        string sName = name.LocalName.ToLower();\n\n        foreach (var child in parentElement.Elements())\n        {\n            if (child.Name.LocalName.ToLower() == sName)\n            {\n                existingElement = child;\n                break;\n            }\n        }\n    }\n    else\n        existingElement = parentElement.Element(name);\n\n    if (existingElement == null)\n        existingElement = new XElement(name, string.Empty);\n\n    return existingElement;\n\n}	0
23743061	23742969	How to databind multiple column names in checkboxlist in asp.net?	SqlCommand cmd=new SqlCommand("Select subj + ' ' + numb + ' ' + section as [combined] from Courses where term=@term",CommonFunctions.con);\ncmd.Parameters.AddWithValue("@term",CommonFunctions.currentTerm);\nSqlDataAdapter da=new SqlDataAdapter(cmd);\nda.Fill(dt);\ncheckboxlist_courses.DataSource = dt;\ncheckboxlist_courses.DataTextField = "combined";\ncheckboxlist_courses.DataBind();	0
1918067	1917999	C# Adding a Datatable to a Datatable	DataTable dt = ml.getRegistration();\nDataTable dt2 = new DataTable();\n\nforeach (DataRow row in dt.Rows)\n{\n\ndt2.merge(ml.getRegistrationExport(row["ID"]));\n\n}\n\nGridView1.DataSource = dt2;\nGridView1.DataBind();	0
26294755	26294553	How do i dynamically cast a child class from its parent class?	abstract class ParentForm{\n    ...\n    public abstract void Update<T>(T updateValue)\n}\n\npublic class f1 : ParentForm{\n    ...\n    private List<string> list;\n    public override void Update(string value){\n    list.Add(value);\n}\n}\n\npublic class f2 : ParentForm{\n    ....\n    private List<int> list;\npublic override void Update(int val){\n ...\n}\n}	0
10674606	10674468	Finding the shortest route using Dijkstra algorithm	List<int> shortestPath = new List<int>();\nint current = end;\nwhile( current != start ) {\n     shortestPath.Add( current );\n     current = parent[current];\n}\n\nshortestPath.Reverse();	0
10598183	10597997	LeftAlt Keybinding in WPF	protected override void OnKeyDown(KeyEventArgs e)\n    {\n        if(e.SystemKey == Key.LeftAlt)\n        {\n            myMenu.Visibility = Visibility.Visible;\n            // e.Handled = true; You need to evaluate if you really want to mark this key as handled!\n        }\n\n        base.OnKeyDown(e);\n    }	0
19979791	19907648	object string Coalesce	return historyListItem == null ? string.Empty : historyListItem.ToString();	0
6908572	6908142	clearing a mapItemsControl.Itemtemplate WP7 Maps	LocationItems.Clear()	0
8829573	8829550	Escaping String.Format Placeholder	String.Format("ListId={{1CC8...156D}}&amp;ID={0}&amp;...", MyValue)	0
18640253	18640134	How to convert Hexa to Binary in 4 Bits format?	string hexa = "01";\nstring binary = Convert.ToString(Convert.ToInt32(hexa, 16), 2).PadLeft(8, '0');	0
4135276	4135150	Deserialize XML into a C# object	var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +\n    "<CatalogProducts>" +\n        "<CatalogProduct Name=\"MyName1\" Version=\"1.1.0\"/>" +\n        "<CatalogProduct Name=\"MyName2\" Version=\"1.1.0\"/>" +\n    "</CatalogProducts>";\nvar document = XDocument.Parse(xml);\n\nIEnumerable<CatalogProduct> catalogProducts =\n        from c in productsXml.Descendants("CatalogProduct")\n        select new CatalogProduct\n        {\n            Name = c.Attribute("Name").Value,\n            Version = c.Attribute("Version").Value\n        };	0
24894724	24894485	MySql Inner join of 2 table with WHERE Clauses	"(c.szClubPrefix = 'CLM' OR u.iClubID2 =' 2 ')  AND " +\n           "u.bActive = 1 " +\n           "AND u.charType= 'c'"	0
10905514	10905358	Create Regex search instance for each item in a string	string partNumbers = @"1017Foo\n1121BAR\nSomethingElse";\nstring searchText = @"SUPERCOLA A 51661017FOOAINDO\nDASUDAMA C 89891121BARBLO5W";\n\nstring[] searchTerms = partNumbers.Split('\n');\nstring[] searchedLines = searchText.Split('\n');\n\nStringBuilder output = new StringBuilder();\n\nforeach(string searchTerm in searchTerms){\n    int matchCount = 0;\n\n    output.AppendLine(string.Format("For term: {0}", searchTerm.Trim()));\n    foreach(string searchedLine in searchedLines){\n        if(searchedLine.Trim().ToLower().Contains(searchTerm.Trim().ToLower())){\n            output.AppendLine(searchedLine.Trim());\n            matchCount++;\n        }\n    }\n\n    if(matchCount == 0){\n        output.AppendLine("There was no match");\n    }\n\n    output.AppendLine("== End of search ==");\n}\n\nConsole.WriteLine(output.ToString());	0
18445351	18445318	How to make a readonly c# List by non declaring its set attribute	public List<string> myList {get; private set;}	0
34335295	34335170	passing multiple informations in anonymous object using razor helper	Html.ReadOnlyTextBox(MyObject.SomeId.ToString(), MyObject.PersonName.ToString(), true, new { @class = (field.IsWarned ? "myCssClassName" : string.Empty), @someVar = (a > b ? false: true) })	0
662204	662160	How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?	groupBox1.ForeColor = Color.Pink;\nforeach (Control ctl in groupBox1.Controls) {\n    ctl.ForeColor = SystemColors.ControlText;\n}	0
15146792	15146497	RNG hidden field parameter	Random random = new Random(); int num = random.Next();\n\n    NameValueCollection PostFields = new NameValueCollection();\n    PostFields.Add("LMID", "093204"); \n    PostFields.Add("unique_id", num.ToString());	0
21354658	21354169	How to properly convert returned JSON to C# class?	public long GetID()\n    {\n        var testDict = new Dictionary<string, apiDataObject>();\n        var returnedData = "{\"name\":{\"id\":1,\"name\":\"name\",\"pID\":1,\"revisionDate\":1390580000000}}";\n        JsonConvert.PopulateObject(returnedData, testDict);\n        return testDict["name"].id;\n    }	0
14980794	14823669	Cannot create a TypeConverter for a generic type	public MyGenericConverter(Type type)\n{\n    if (type.IsGenericType \n        && type.GetGenericTypeDefinition() == typeof(MyGenericClass<>)\n        && type.GetGenericArguments().Length == 1)\n    {\n        _genericInstanceType = type;\n        _innerType = type.GetGenericArguments()[0];\n        _innerTypeConverter = TypeDescriptor.GetConverter(_innerType);            \n    }\n    else\n    {\n        throw new ArgumentException("Incompatible type", "type");\n    }\n}	0
16688764	16688647	Counting number of occurences of characters from array in string?	var count = password.Count(nonAlphaNumericCharSet.Contains);	0
22160922	22137747	Attaching an email as an attachment to another email	try\n                {\n                    Outlook.MailItem tosend = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);\n                    tosend.Attachments.Add(mailItem);\n                    tosend.To = "blah@blah.com";\n                    tosend.Subject = "test";\n                    tosend.Body = "blah";\n                    tosend.Save();\n                    tosend.Send();\n                }\n                catch (Exception ex)\n                {\n                    Console.WriteLine("{0} Exception caught: ", ex);\n                }	0
2484837	2484806	Accessing Textboxes in Repeater Control	foreach (RepeaterItem item in Repeater1.Items)\n{\n      TextBox txtName= (TextBox)item.FindControl("txtName");\n      if(txtName!=null)\n      {\n      //do something with txtName.Text\n      }\n      Image img= (Image)item.FindControl("Img");\n      if(img!=null)\n      {\n      //do something with img\n      }\n}	0
18181647	18140622	Must Declare a scalar variable @Code	SqlDataAdapter lSqlDataAdapter = new SqlDataAdapter(lSqlCommand);	0
31885634	31885418	copy a table to another table with this conditions	Insert Into New_Table\nSelect  *\nFrom    Old_Table\nWhere   NOT EXISTS ( Select * from New_Table )\n\nUpdate New_Table NT\nFrom     Old_Table OT\nWhere   NT.PK = OT.PK\n   and    ( NT.attrib_fld_1   <>   OT.atrib_fld_1\n    OR\n     NT.attrib_fld_1   <>   OT.atrib_fld_1\n    OR\n     NT.attrib_fld_1   <>   OT.atrib_fld_1\n    OR\n     NT.attrib_fld_1   <>   OT.atrib_fld_1\n    -- etc..for as many non key fields as need evaluated \n    )	0
14936022	14894796	Per Pixel Collision - Could do with some general tips	//In Class-scope:\nColor[] CollisionMapData;\nTexture2D CollisionMap;\n\npublic void LoadContent()  \n{  \n    CollisionMap = Content.Load<Texture2D>("map");  \n    CollisionMapData = new Color[CollisionMap.Width * CollisionMap.Height];  \n    CollisionMap.GetData<Color>(CollisionMapData);  \n}  \n\npublic Boolean Collision(Vector2 position)  \n{  \n    int index = (int)position.Y * CollisionMap.Width + (int)position.X;\n\n    if (index < 0 || index >= CollisionMapData.Length) //Out of bounds  \n        return true;\n\n    if (CollisionMapData[index] == Color.Black)\n        return true;\n\n    return false;\n}	0
4908465	4908437	saving thumbnail, getting A generic error occurred in GDI+	using(var ms = new MemoryStream()) {\n    str.CopyTo(ms); // a 4.0 extension method\n    ms.Position = 0;\n    // TODO: read from ms etc\n}	0
25326693	25324755	C# copy .csv file from local machine to remote postresql server	NpgsqlCommand dbcmd = dbcon.CreateCommand();\n        string sql =\n            "COPY table_name FROM STDIN;";\n        dbcmd.CommandText = sql;\n        serializer = new NpgsqlCopySerializer(dbcon);\n        copyIn = new NpgsqlCopyIn(dbcmd, dbcon, serializer.ToStream);\n        copyIn.Start();\n        foreach(...){\n            serializer.Add... \n            serializer.EndRow();\n            serializer.Flush();\n        }\n        copyIn.End();\n        serializer.Close();	0
29201985	6883364	Simple .Net based HTTP server	string myFolder = @"C:\folderpath\to\serve";\nSimpleHTTPServer myServer;\n\n//create server with auto assigned port\nmyServer = new SimpleHTTPServer(myFolder);\n\n\n//Creating server with specified port\nmyServer = new SimpleHTTPServer(myFolder, 8084);\n\n\n//Now it is running:\nConsole.WriteLine("Server is running on this port: " + myServer.Port.ToString());\n\n//Stop method should be called before exit.\nmyServer.Stop();	0
17939166	17939118	Getting data from different SQL tables and adding it to comboBox	for (int i = 0; i < ds.Tables[0].Rows.Count; i++)\n            {\n                    comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());\n            }	0
24851612	24842036	How to get asp:Table cell values using javascript?	var table = document.getElementById('<%=tableID.ClientID %>');\nfor (var i = 0; i < table.rows.length; i++) {\n    //get first column (labels)\n    var lblCtrl = table.rows[i].cells[0].childNodes[0];\n    //get second column (textBoxes)\n    var txtCtrl = table.rows[i].cells[1].childNodes[0];\n    //check that the second column is a textBox\n    if (txtCtrl.tagName == "INPUT" || txtCtrl.tagName == "SELECT") {\n        alert(txtCtrl.value);\n    }\n    if (!(lblCtrl.tagName == "INPUT" || lblCtrl.tagName == "SELECT"))\n    {\n        alert(lblCtrl.innerHTML);\n    }\n}	0
32078372	32078253	Windows Phone Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)	Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>\n        {\n            tbx.Text = data;\n        });	0
12016864	12016817	Resize image to specific width and fix height	private Bitmap ScaleImage(Image oldImage)\n{\n    double resizeFactor = 1;\n\n    if (oldImage.Width > 150 || oldImage.Height > 150)\n    {\n        double widthFactor = Convert.ToDouble(oldImage.Width) / 150;\n        double heightFactor = Convert.ToDouble(oldImage.Height) / 150;\n        resizeFactor = Math.Max(widthFactor, heightFactor);\n\n    }\n    int width = Convert.ToInt32(oldImage.Width / resizeFactor);\n    int height = Convert.ToInt32(oldImage.Height / resizeFactor);\n    Bitmap newImage = new Bitmap(width, height);\n    Graphics g = Graphics.FromImage(newImage);\n    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n    g.DrawImage(oldImage, 0, 0, newImage.Width, newImage.Height);\n    return newImage;\n}	0
27109996	27109829	How to issue a find command using MongoDB C# Driver with native JSON criteria syntax?	var json = "{'_id': 3456}";\nvar doc= BsonDocument.Parse(json);\nvar query = new QueryDocument(doc);\nvar result = coll.Find(query);	0
26424160	26423991	Open a directory and process files/folders in background worker query	public class Form1\n{\n    private String _filePath = null;\n\n    private void btnFiles_Click(object sender, EventArgs e)\n    {\n        //get your file and assign _filePath here...\n        _filePath = folderBrowserDialog1.SelectedPath;\n    }\n\n    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n    {\n        //use _filePath here...\n    }\n}	0
7283465	7283244	Replace placeholders in order	// Begin with '{' followed by any number of word like characters and then end with '}'\nvar pattern = @"{\w*}"; \nvar regex = new Regex(pattern);\n\nvar replacementArray = new [] {"abc", "cde", "def"};\nvar sourceString = @"/home/{value1}/something/{anotherValue}";\n\nvar matchCollection = regex.Matches(sourceString);\nfor (int i = 0; i < matchCollection.Count && i < replacementArray.Length; i++)\n{\n    sourceString = sourceString.Replace(matchCollection[i].Value, replacementArray[i]);\n}	0
32227420	32226793	How to Disable Actionfilter for only one method?	actionContext\n       .ActionDescriptor\n       .GetCustomAttributes<SkipActionExemptionsAttribute>()\n       .Any()	0
20947570	20947422	Handle unhandled exception from a reference dll	Application.ThreadException += new ThreadExceptionEventHandler(Error_.MyExc);\nApplication.SetUnhandledExceptionMode(Error_.MyCatchExc);\n\n// from your code \nAppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyErrorHandler);	0
21239649	21239603	How to user a group by with lambda?	var query = DataTable.GroupBy(item => item.continent,\n    (key, group) => new\n    {\n        Continent = key,\n        Countries = group.GroupBy(item => item.country)\n    });	0
18155225	18155024	ASP.NET Application - Accessing details about a drop down list's DataSource	ddlExtRouteBusyID.SelectedItem.Text\nddlExtReouteBusyID.SelectedItem.Value	0
19870458	19870261	Nullable property in Infragistics Ignite UI grid	column.For( p => p.Role )\n      .HeaderText( "Role" )\n      .DataType( "object" )\n      .FormatterFunction( "function(obj) { if (!obj) return 'None'; return obj.Description; }" );	0
30554430	30554182	How to solve ASP.NET custom login page error?	protected void Button1_Click(object sender, EventArgs e)\n{\n    conn.Open();\n    string SQL = "select UserID from [User] where UserName=@UserName AND Password=@Password"; \n    SqlCommand com = new SqlCommand(SQL, conn);\n    com.Parameters.AddWithValue("@UserName", TextBoxUN.Text);\n    com.Parameters.AddWithValue("@Password", TextBoxPass.Text);\n    SqlDataReader data = com.ExecuteReader();\n    if (data.HasRows) // username and password match\n    {\n        conn.Close();\n        Response.Redirect("Registration.aspx");\n    }\n    else\n    {\n        conn.Close();\n        // display error here\n    }\n}	0
1405507	1405486	How does a C# evaluate floating point in hover over and intermediate window versus compiled?	if (1.0 < 1.0)\n                Console.WriteLine("Wrong");	0
25791243	25790792	Add, Update, Remove between collections using Linq	var listIDsA = collectionA.Select(s => s.Id).Distinct().ToList();\n\nvar listIDsB = collecitonB.Select(s => s.Id).Distinct().ToList();\n\nvar idsToRemove  = listIDsB.Select (s => !listIDsA.Contains(s.Id)).ToList();\n\nvar idsToUpdate = listIDsB.Select(s => listIDsA.Contains(s.Id)).ToList();\n\nvar idsToAdd = listIDsA.SelecT(s => !listIDsB.Contains(s.Id)).ToList();	0
10403663	10395830	How can I invoke a dynamic external dll	Assembly.LoadFrom	0
736550	736533	How do you convert a string to ascii to binary in C#?	var str = "Hello world";\n\nWith LINQ\nforeach (string letter in str.Select(c => Convert.ToString(c, 2)))\n{\n  Console.WriteLine(letter);\n}\n\nPre-LINQ\nforeach (char letter in str.ToCharArray())\n{\n  Console.WriteLine(Convert.ToString(letter, 2));\n}	0
6435302	6435124	Linq2XML Create Object Model	class ProductList : List<Product>\n{\n   public ProductList(items IEnumerable<Product>) \n         : base (items)\n   {\n   }\n}\n\nclass Product\n{\n  public string ID { get; set;}\n  public string Name{ get; set;}\n}\n\nvar products = xDocument.Desendants("product");\nvar productList = new ProductList(products.Select(s => new Product()\n    {\n      ID = s.Element("id").Value,\n      Name= s.Element("name").Value\n    });	0
12963493	12963143	List All Controls in a C# ASP.NET Project	Activator.CreateInstance	0
14433820	14353475	hardware identification to be open a web page on cliet side	User-Agent	0
23434173	23433338	How to get properties from COM Object using the dynamic keyword	var myObject = ((dynamic)comObject.someProperty);\n        foreach (var index in myObject)\n        {\n           // This will loop over each object in the array\n        }	0
1728397	1728367	How to prevent auto implemented properties from being serialized?	public class ClassWithNonSerializedProperty {\n\n  [NonSerialized]\n  private object _data;  // Backing field of Property Data that is not serialized\n\n  public object Data{\n    get { return _data; }\n    set { _data = value; }\n  }\n}	0
27333018	27272095	OWIN Cookie Authentication	config.SuppressDefaultHostAuthentication();	0
5528713	5528460	Editing a DataGrid in WPF causes a System.NullReferenceException	var query = from a in db.Albums\n            where a.AlbumID == ((AlbumCase)e.AddedItems[0]).Album.AlbumID\n            select a.Tracks;\n\nvar dataSource = new ObservableCollection<Track>();\nforeach (var item in query)\n    dataSource.Add(item);\n\ntrackDataGrid.ItemsSource = dataSource;	0
17188608	17188341	how to continue a loop despite error in parsing byte data	try\n{\n    using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.ASCII))\n    {\n        while (reader.BaseStream.Position != reader.BaseStream.Length)\n        {\n            inputCharIdentifier = reader.ReadChar();\n            if(inputCharIdentifier != null)\n            {\n               switch (inputCharIdentifier)\n                 case 'A':\n                    field1 = reader.ReadUInt64();\n                    field2 = reader.ReadUInt64();\n                    field3 = reader.ReadChars(10);\n                    string strtmp = new string(field3);\n                    //and so on\n                    using (TextWriter writer = File.AppendText("outputA.txt"))\n                    {\n                       writer.WriteLine(field1 + "," + field2 + "," + strtmp); \n                    }\n                 case 'B':\n                   //code...\n            }\n        }\n    }\n}\ncatch\n{\n}	0
27385439	27384064	Is checking a property value before setting, and setting only if different, quicker or slower than setting blindly?	if (myObject.IsActive != newActiveState)\n{\n    myObject.IsActive = newActiveState;\n}	0
15140761	15140722	How to access SqlParameter array with name	parameters.First(parameter => parameter.ParameterName == "@test")	0
3567824	3567558	Display picture box faster	private void loadImage(string path) {\n        using (var srce = new Bitmap(path)) {\n            var dest = new Bitmap(pictureBox1.Width, pictureBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);\n            using (var gr = Graphics.FromImage(dest)) {\n                gr.DrawImage(srce, new Rectangle(Point.Empty, dest.Size));\n            }\n            if (pictureBox1.Image != null) pictureBox1.Dispose();\n            pictureBox1.Image = dest;\n        }\n    }	0
7642810	7642694	LINQ suming nested groups in one statement	var query = (from product in Products\n                from smallPack in product.ItemPacks\n                select new\n                {\n                    ItemCode = smallPack.ItemCode,\n                    Item = smallPack.Item,\n                    Quantity = smallPack.Quantity * product.Quantity,\n                })\n                .GroupBy(p => p.ItemCode)\n                .Select(p => new\n                {\n                    ItemCode = p.Key,\n                    Item = p.FirstOrDefault(),\n                    Quantity = p.Sum(x=>x.Quantity)\n                })\n                .ToDictionary(p=>p.ItemCode);	0
10543127	10542988	How can I save the values from fields in a Windows Forms GUI to a file, and then restore them?	//...\nList<string> lines = new List<string>();\n\nusing (StreamReader sr = new StreamReader(file))\n{\n    while(!sr.EndOfStream)\n    {\n        lines.Add(sr.ReadLine());\n    }\n}\n\ntask1_name.Text = lines[0];\ntask1_desc.Text = lines[1];\n//...	0
9402376	9402342	Using inline expression with SessionParameter fails	DateTime.Now.ToString("M/d/yyyy")	0
692033	692022	Extension Method to assign value to a field in every item?	IQueryable<Entity> en = from e in IDB.Entities select e;\nen.ToList().ForEach(foo => foo.status = "Complete");	0
34168328	34168005	How to compile c# csproj into exe in Visual Studio 2015 - error CS0579	[assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.0,Profile=Cl??ient", FrameworkDisplayName=".NET Framework 4 Client Profile")]	0
21930431	21930264	how to read text file in server from client in windows application using C# 4.0	string line;\nstring path = @"\\server1\TextFolder\Text.txt";\nStringBuilder sb = new StringBuilder();\nint counter = 0;\n\nusing (StreamReader file = new StreamReader(path))\n{\n  while ((line = file.ReadLine()) != null)\n      {\n         if (line.Contains(searchstring))\n          {\n               if (line.Contains(searchfromdate)) //|| line.Contains(searchtodate)) \n                  {\n                        sb.AppendLine(line.ToString());\n                        counter++;\n                  }\n          }\n      }\n}\n\nResultTextBox.Text = sb.ToString();\nCountLabel.Text = counter.ToString();	0
4172005	4171976	Filestream prepends junk characters while read	File.ReadAllText(fileName,Encoding.UTF8)	0
24175506	24174798	Using String of Bytes in a Byte Array	using System;\nusing System.Globalization;\n\npublic class Program\n{\n    public static void Main()\n    {\n\n        string MYBytes = "{ 0x4D, 0x5A, 0x90 }";\n\n        string[] hexParts = MYBytes.Split(new char[] { ',', '{', '}' }, StringSplitOptions.RemoveEmptyEntries);\n\n        byte[] bytes = new byte[hexParts.Length];\n\n        for(int i = 0; i < hexParts.Length; i++)\n            bytes[i] = Byte.Parse(hexParts[i].Substring(3), NumberStyles.HexNumber);\n\n\n        foreach(byte b in bytes)\n            Console.WriteLine("{0:X2}", b);\n    }\n}	0
2746709	2746680	Conversion of Single to two UInt16 values in .NET	float value = 1.1f;\n        byte[] bytes = BitConverter.GetBytes(value);\n        short upper = BitConverter.ToInt16(bytes, 0);\n        short lower = BitConverter.ToInt16(bytes, 2);	0
7507359	7507161	Help with building object model	public abstract class Unit { \n\n    protected Unit(int count) {\n      Count=count;\n    }\n\n    protected int Count { get; private set; }\n    protected abstract int Defense {get;}\n\n    public int TotalDefense {\n      get { return Count*Defense; }\n    }\n\n}\n\npublic class Tank : Unit {\n\n   public Tank(int count) : base(count) {}\n\n   protected override int Defense {\n     get { return 5; }\n   }\n}\n\npublic class Troop {\n\n   private Unit[] Troops;\n\n   public Troop(int soldiers, int tanks, int jets, int forts) {\n     Troops = new Unit[] {\n                new Soldier(soldiers),\n                new Tank(tanks),\n                new Jet(jets),\n                new Fort(forts)\n              };\n   }\n\n   // The using System.Linq you can do\n   public int TotalDefense {\n     get { return Troops.Sum(x=>x.TotalDefense);}\n   }\n}	0
9976896	9976533	Detecting if a button was clicked from another class	public static bool button1Clicked;	0
6579952	6579805	Save Image to particular folder from Openfiledialog?	private void button2_Click(object sender, EventArgs e)\n      {\n        Bitmap myBitmap = new Bitmap();\n        this.saveFileDialog1.FileName = Application.ExecutablePath;\n        if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n        {\n            myBitmap.Save(this.saveFileDialog1.FileName);\n        }\n      }	0
30329592	30319378	Query user data from a specific AD DC	public static List<UserPrincipal> GetInactiveUsers(TimeSpan inactivityTime)\n{\n    List<UserPrincipal> users = new List<UserPrincipal>();\n\n    using (Domain domain = Domain.GetCurrentDomain())\n    {\n        foreach (DomainController domainController in domain.DomainControllers)\n        {\n            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainController.Name))\n            using (UserPrincipal userPrincipal = new UserPrincipal(context))\n            using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))\n            using (PrincipalSearchResult<Principal> results = searcher.FindAll())\n            {\n                users.AddRange(results.OfType<UserPrincipal>().Where(u => u.LastLogon.HasValue));\n            }\n        }\n    }\n\n    return users.Where(u1 => !users.Any(u2 => u2.UserPrincipalName == u1.UserPrincipalName && u2.LastLogon > u1.LastLogon))\n        .Where(u => (DateTime.Now - u.LastLogon) >= inactivityTime).ToList();\n}	0
5744995	5744930	DataPointCollection Clear performance	public void ClearPointsQuick()\n    {\n        Points.SuspendUpdates();\n        while (Points.Count > 0)\n            Points.RemoveAt(Points.Count - 1);\n        Points.ResumeUpdates();\n    }	0
22326053	22325972	Invariant decimal variable	decimal actualVal = 1247315.93m;\nvar culture = CultureInfo.CreateSpecificCulture("sv-SE");\n\nstring inSwedish = actualVal.ToString(culture));\n\ndecimal invariant = decimal.Parse(inSwedish, culture);\n\nConsole.WriteLine(inSwedish);  \nConsole.WriteLine(invariant.ToString(CultureInfo.InvariantCulture)); \nConsole.Read();	0
8210059	8209522	How to get Battery charging status from WPF applicatioin using WMI?	static string GetBatteryStatus() {\n    ManagementScope scope = new ManagementScope("//./root/cimv2");\n    SelectQuery query = new SelectQuery("Select BatteryStatus From Win32_Battery");\n    using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) {\n        using(ManagementObjectCollection objectCollection = searcher.Get()) {\n            foreach(ManagementObject mObj in objectCollection) {\n                PropertyData pData = mObj.Properties["BatteryStatus"];\n                switch((Int16)pData.Value) { \n                    //...\n                    case 2:return "Not Charging";\n                    case 3:return "Fully Charged";\n                    case 4:return "Low";\n                    case 5: return "Critical";\n                    //...\n                }\n            }\n        }\n    }\n    return string.Empty;\n}	0
2148750	2148722	How can I escape a string in classic ASP for use in XPath query?	xpath = "//node[@attribute='" & SecurityElementEscape(value) & "']"\n\nFunction SecurityElementEscape(value)\n    SecurityElementEscape = \n        Replace(Replace(Replace(Replace(Replace(value, \n            "&" , "&amp;" ), '' // must be first one\n            "<" , "&lt;"  ),\n            ">" , "&gt;"  ), \n            """", "&quot;"), \n            "'" , "&apos;") \nEnd Function	0
23567147	23566614	c# error passing a string in POST from jquery to a WebAPI project method	data: '=' + tag,	0
2473151	2472932	Is there a way to remove Alt-character shortcuts from controls at runtime?	public partial class dlgSample : Form {\n    public dlgSample(bool isReadOnly) {\n        InitializeComponent();\n        if (isReadOnly) ZapMnemonics(this.Controls);\n    }\n\n    private void ZapMnemonics(Control.ControlCollection ctls) {\n        foreach (Control ctl in ctls) {\n            if (ctl is Label || ctl is Button) ctl.Text = ctl.Text.Replace("&", "");\n            ZapMnemonics(ctl.Controls);\n        }\n    }\n}	0
8329927	8326446	How do I (quickly) find the longest matching string in C#/.Net	ROOT\n            |\n           0|\n            |\n            A\n          / | \\n         /  |  \\n       1/  2|  3\\n       /    |    \\n      /     |     \\n     B      B      C\n     |\n    2|\n     |\n     D	0
11571214	11571183	Compare system Day and DateTime	DateTime systemtime = DateTime.Now;\nif(systemtime.DayOfWeek == DayOfWeek.Monday)\n{\n...\n}	0
4667601	4667532	Colour Individual Items in a winforms ComboBox?	private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)\n{    \n    // Draw the background \n    e.DrawBackground();        \n\n    // Get the item text    \n    string text = ((ComboBox)sender).Items[e.Index].ToString();\n\n    // Determine the forecolor based on whether or not the item is selected    \n    Brush brush;\n    if (YourListOfDates[e.Index] < DateTime.Now)// compare  date with your list.  \n    {\n        brush = Brushes.Red;\n    }\n    else\n    {\n        brush = Brushes.Green;\n    }\n\n    // Draw the text    \n    e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);\n}	0
18288665	18243817	Converting from C++ (GetAsyncKeyState) to C# - WPF	public partial class MainWindow : Window\n{\nprivate bool toggle = true;\n}\n\nprivate void fireUp(rwKey hotKey)\n    {\n        byte[] byt ={0xC7,0x83,0x1A,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0x8B,0x74,0x24,\n        0x40,0x48,0x8B,0x6C,0x24,0x48,0x48,0x8B,0x5C,0x24,0x50,0x48,0x83,0xC4,0x58,0xC3};\n        for (int i = 6; i < 10; ++i) { byt[i] = (byte)(atkSpd & 0xFF); atkSpd = atkSpd >> 8; }\n\n        bool kd = (toggle = !toggle);\n\n        if (kd)\n        {\n            Write(vMemory + 8, byt, 30);\n            Write(vMemory, BitConverter.GetBytes((vMemory + 8)), 8);\n            Write(atkBase, new byte[] { 0xFF, 0x24, 0x25 }, 3);\n            Write(atkBase + 3, BitConverter.GetBytes((vMemory)), 4);\n        }\n        else\n        {\n            Write(atkBase, new byte[] { 0x66, 0x89, 0xB3, 0x1A, 0x05, 0x00, 0x00 }, 7);\n        }\n    }	0
34256683	34256631	Implementation of adding SqlCeParameters in a loop	SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");\ncmd.CommandType = CommandType.Text;\ncmd.Connection = connection;\n\ncmd.Parameters.Add("@date", DbType.DateTime);\n// other parameters\n\nconnection.Open();\nfor (int i = 0; i <= bought.Length; i++)\n{\n    cmd.Parameters["@date"].Value = dateOperation[i];\n    // other parameters\n    cmd.ExecuteNonQuery();\n}	0
2129802	2126878	Windows Forms Control - Huge list of filenames	VirtualListMode = true\nVirtualListSize= 300000	0
11842217	11842097	Is it possible to execute a Parallel.For loop starting max value, then decrementing	System.Threading.Tasks.Parallel.For(0, 25, i => { Console.WriteLine(i); });	0
1971155	1971076	Decimal Casting	CultureInfo german = new CultureInfo("de-DE");\ndecimal d = decimal.Parse("62.000,0000000", german);\nint i = (int) d;\n\nConsole.WriteLine(i); // Prints 62000	0
32184885	32184843	C#, in List<>.ConvertAll method using lambda expression, how to make a filter when the object is null?	string[] myTargetArray=myClassList.ConvertAll<string>(xi => xi==null ? string.Empty : xi.objStr).ToArray();	0
23848585	23848444	C# subtraction of strings	string alphabet = "abcdefghijklmnopqrstuvwxyz_*";\n        string special = textBox2.Text;\n        if (alphabet.ToLowerInvariant().Contains(special))\n        {\n            textBox3.Text =  alphabet.Replace(special, "");\n        }	0
12950190	12949971	How can i stop/resume a backgroundworker/recursive loop?	_busy.WaitOne();	0
14442450	14442296	in a console app what's the best way to prevent special sequences in command line arguments from being escaped?	--folder "C:\my folder\\" --username john	0
18877050	18860553	Parsing email body with c#	public void addMessage(string message, string header) {\n  string full_body = header + "\n" + message;\n  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();\n  Byte[] full_body_bytes = encoding.GetBytes(full_body);\n  Message mm = new Message(full_body_bytes);\n\n  //do stuff here.\n}	0
7464255	7463595	Negative scaling with spritebatch in XNA vs Primitives	basicEffect.View = Matrix.CreateScale(1.0f, -1.0, 1.0f) * Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 1.0f), Vector3.Zero, Vector3.Up);	0
7072388	7072344	Displaying a server-side alert message and then redirecting to a new page	alert('....'); window.location='home.aspx';	0
31821072	31820905	INSERT INTO without column names with OUTPUT INSERTED	INSERT INTO DF_FILES (col1, col2 , col3 ...)\n  OUTPUT INSERTED.TableID\n  SELECT col1, col2 , col3 ...\n  FROM DF_FILES\n  WHERE DOC = "myFile.txt"	0
1266758	1266547	How do you find out when you've been loaded via XML Serialization?	using System.Xml.Serialization;\n\nnamespace Custom.Xml.Serialization\n{\n    public interface IXmlDeserializationCallback\n    {\n        void OnXmlDeserialization(object sender);\n    }\n\n    public class CustomXmlSerializer : XmlSerializer\n    {\n        protected override object Deserialize(XmlSerializationReader reader)\n        {\n            var result = base.Deserialize(reader);\n\n            var deserializedCallback = result as IXmlDeserializationCallback;\n            if (deserializedCallback != null)\n            {\n                deserializedCallback.OnXmlDeserialization(this);\n            }\n\n            return result;\n        }\n    }\n}	0
26437836	26404360	How do I configure NancyFx to work with Spring.net?	NancyBootstrapperWithRequestContainerBase<TContainer>	0
13947317	13947224	How to add an IEumerable Collection to a Queue and Process each item asynchronously in .NET?	foreach (var item in findResults)\n{\n    emailInformations.Add(new ExchangeEmailInformation ...);\n\n    // start new task\n    Task.Factory.Start(() => {\n        AddAttachment(item.Subject, item.docId, item.User ...);\n    })\n}	0
28077802	28045242	Get custom claims from a JWT using Owin	var identity = User.Identity as ClaimsIdentity;\n\n        return identity.Claims.Select(c => new\n        {\n            Type = c.Type,\n            Value = c.Value\n        });	0
5854254	5854077	Display Messagebox Buttons / Icon as an integer	MessageBoxButton[] mbs = new[]\n                                     {\n                                         MessageBoxButton.OK,\n                                         MessageBoxButton.OKCancel, \n                                         MessageBoxButton.YesNo,\n                                         MessageBoxButton.YesNoCancel\n                                     };\n\n        MessageBoxImage[] mbi = new[]\n                                    {\n                                        MessageBoxImage.Asterisk, MessageBoxImage.Error, MessageBoxImage.Exclamation,\n                                        MessageBoxImage.Hand, MessageBoxImage.Information, MessageBoxImage.None,\n                                        MessageBoxImage.Question, MessageBoxImage.Stop, MessageBoxImage.Warning\n                                    };\n        MessageBox.Show("Message Text", "Message Title", mbs[2], mbi[4]);	0
33438700	33438626	Is there a more succinct/elegant way to find and select a particular ComboBoxItem by its content?	myComboBox.SelectedItem = myComboBox.Items.Cast<ComboBoxItem>().FirstOrDefault(item => item.Content.ToString().Equals("myString", StringComparison.CurrentCultureIgnoreCase));	0
26798813	26798489	Retrieving Issue regarding stored procedures data type	SqlParameter[] param = {\n                                        new SqlParameter("@param1", SqlDbType.VarChar, 100),\n                                        new SqlParameter("@param2", SqlDbType.Int),\n                                        new SqlParameter("@param3", SqlDbType.DateTime)\n                                   };\n\n            //@param1, @param2, @param3 should match your parameters name in stored procedure\n\n            param[0].Value = "test"; //pass the value to your parameter here\n            param[1].Value = 2;\n            param[2].Value = DateTime.Now;\n\n            SqlCommand sqlcmd = new SqlCommand();\n\n            foreach (SqlParameter x in param)\n            {\n                sqlcmd.Parameters.Add(x);\n            }	0
16159339	16159221	How to send child objects to an MVC view in a list of parent objects	IEnumerable<Elephant> elephants = new List<Elephant>();\nIEnumerable<Animal> animals = elephants;	0
117374	117348	Can you force the serialization of an enum value into an integer?	[XmlIgnore]\npublic MyThing MyThing { get; set; }\n\n[XmlElement("MyThing")]\n[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]\npublic string MyThingForSerialization\n{\n    get { return //convert MyThing to string; }\n    set { MyThing = //convert string to MyThing; }\n}	0
3045513	3045395	Hold the command prompt until user close it from close button	ProcessStartInfo psi = new ProcessStartInfo\n{\n    FileName = "cmd",\n    Arguments = @"/k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe"""\n};\nProcess.Start(psi);	0
22620563	22620499	TextBox text update with MultiThreading	private readonly object _lock = new object();\n\nlock(_lock)\n{\n    if (results.Lines.Count() != 0)\n        this.InvokeEx(f => f.results.Text += Environment.NewLine);\n\n    this.InvokeEx(f => f.results.AppendText("0\t1"));\n}	0
5648274	5648102	Get ID of a radio button with Selenium CSS selector	selenium.GetAttribute("css=.class1@id");	0
31620040	31619905	Is there any way to avoid the need for absurdly simplistic WPF/XAML Converters?	public Visibility ShouldTheButtonBeShown \n  { \n     get { return isValid ? Visbility.Visible : Visibility.Hidden; }\n  }	0
4391433	4391408	How to use a .NET CommandArgument as a non-string object?	return Context.C1.ToString()	0
10733322	10733064	Invoke jquery function from codebehind, switching the querystring	Request.QueryString[key].ToString()	0
14889809	14888488	How to set max byte length of datagridview when paste	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    var textBytes = Encoding.UTF8.GetBytes(textBox1.Text);\n    var textByteCount = Encoding.UTF8.GetByteCount(textBox1.Text);\n    var textCharCount = Encoding.UTF8.GetCharCount(textBytes);\n\n    if (textCharCount != textByteCount && textByteCount >= 12)\n    {\n        textBox1.Text = Encoding.UTF32.GetString(Encoding.UTF32.GetBytes(textBox1.Text), 0, 12);\n    }\n    else if (textBox1.Text.Length >= 6)\n    {\n        textBox1.Text = textBox1.Text.Substring(0, 6);\n    }\n}	0
13374610	13374575	Value of Selected dataGridView cell in Textbox	foreach (DataGridViewRow RW in dataGridView1.SelectedRows) {\n    //Send the first cell value into textbox'\n    Txt_GangApproved.Text = RW.Cells(0).Value.ToString;\n}	0
22524983	22523993	How to add a date in windows phone app	DateTime endDate = DateTime.Parse(date).AddDays(Convert.ToDouble(days));	0
2479169	2479133	How can I overlay one image onto another?	Image image = new Image();\nimage.Source = new BitmapImage(new Uri(@"c:\test\rectangle.png"));\nimage.Stretch = Stretch.None;\nimage.HorizontalAlignment = HorizontalAlignment.Left;\n\nImage imageSticker = new Image();\nimageSticker.Source = new BitmapImage(new Uri(@"c:\test\sticker.png"));\nimageStiker.Margin = new Thickness(10, 10, 0, 0);\n\nGrid grid = new Grid();\ngrid.Children.Add(image);\ngrid.Children.Add(imageSticker);\n\nTheContent.Content = grid;	0
4377831	4376907	Subsonic 3.0 ActiveRecord with dates	var myDb = new MyDB(); //Database context renamed for privacy\nvar select = myDb.Select.Top("100")\n                        .From("Visitor")\n                        .Where("Date_Moderated")\n                        .IsLessThan(dateTime.ToString("yyyy-MM-dd HH:mm:ss"))\n                        .OrderDesc("Date_Moderated");\n\nvar visitors = select.ExecuteTypedList<Visitor>();	0
27722324	27721858	How to remove the focus border of a CheckBox in C# Visual Studio?	using System.Windows.Forms;\n\nclass MyCheckBox : CheckBox {\n    protected override bool ShowFocusCues {\n        get { return false; }\n    }\n}	0
29708211	29707953	Get drive letter from USB via VolumeLabel	var alldrives = DriveInfo.GetDrives();\nstring destd="";\nforeach (var drvs in alldrives)\n{\n    try\n    {\n          if (drvs.VolumeLabel.Equals("UB64"))\n              destd = drvs.Name;\n              break;\n     }\n     catch\n     {\n        continue;\n     }\n}	0
16388200	16388153	How to set font size, family and colour of listview in ASP.NET (C#)	runat='server'	0
16428219	16428047	Comparing the properties of two lists	var result = from contentA in contentObjectA\n             join contentB in contentObjectB on contentA.Id equals contentB.Id into contentBB\n             from contentB in contentBB.DefaultIfEmpty(null)\n             select new {\n                ContentAId = contentA.Id\n                //Check if Id exists\n                ExistsInB = contentB == null ? false : true,\n                ModifiedDateDiff = contentB.ModifiedDate == null ? true : contentA.ModifiedDate == contentB.ModifiedDate,\n                DescriptionDiff = contentB.Description == null ? true : contentA.Description == contentB.Description,\n                HtmlMarkupDiff = contentB.HtmlMarkup == null ? true : contentA.HtmlMarkup == contentB.HtmlMarkup\n             };	0
5544782	5544731	regex for { } within ' 's	(?<='[^']+\{)[^\{\}]+(?=\}[^']+')	0
7300210	7300029	Update Label Without Button	private void onLongitudeTextChanged(object sender, EventArgs e) {\n           updateDistanceAndBearing();\n        }	0
32932234	32927743	Get RightTapped GridViewItem	private void Song_RightTapped(object sender, RightTappedRoutedEventArgs e)\n{\n    Song song = (sender as Grid).DataContext as Song;\n    // Show PopupMenu\n    // ...\n}	0
21490880	21490343	Detect Printable Area Width in OpenXml.Wordprocessing	// ...\nvar sectionProperties = body.GetFirstChild<SectionProperties>();\n// pageSize contains Width and Height properties\nvar pageSize = sectionProperties.GetFirstChild<PageSize>();\n\n// this contains information about surrounding margins\nvar pageMargin = sectionProperties.GetFirstChild<PageMargin>();\n\n// this contains information about spacing between neighbouring columns of text\n// this can be useful if You use page layout with multiple text columns\nvar columns = sectionProperties.GetFirstChild<Columns>();\nvar spaceBetweenColumns = columns.Space.Value;\nvar columnsCount = columns.ColumnCount.Value;	0
17150477	16974346	How can I write a method that returns all records from a Matisse table in a list structure?	public List<Users> FindUsers()\n    {\n        List<Users> users = new List<Users>();\n        executeCmd("SELECT REF(Users) FROM Users c");\n        while (Reader.Read())\n        {\n            MtObject obj = Reader.GetObject(0);\n            users.Add(new Users(db, obj.MtOid));\n        }\n        Reader.Close();\n        return users;\n    }	0
3659733	3659721	Best way to get a List of a property of T from a List<T>	List<string> usernames = users.Select(u => u.UserName).ToList();	0
24219402	24219339	How to access the control by its ID	Control ctrl = this.Parent.FindControl(ID);\nif(ctrl is TextBox){\n  TextBox txt = (TextBox)ctrl;\n  //Do anything Textbox specific\n}\nif(ctrl is RadDatePicker){\n  RadDatePicker rad = (RadDatePicker)ctrl;\n  //Do anything RadDatePicker specific\n}	0
10498115	10497531	Populate a listBox with XML values for current day, and the next three days?	where int.Parse(c.Attribute("Day").Value) >= myDay.Day && int.Parse(c.Attribute("Day").Value) < (myDay.Day + 3)	0
31014731	31005912	Caching module / Caching in Orchard CMS	[OutputCache(Duration = 0)]	0
30372597	30343232	how to add the caller IP to a webget UriTemplate parameters	var clientIp = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty??new RemoteEndpointMessageProperty("",0);	0
23469289	23469002	IOException in WPF GUI	var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlPicturesBig + urlresource);\nMemoryStream memory= new MemoryStream();\nusing (var httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())\n{\n     var stream = httpWebReponse.GetResponseStream();\n     //read the entire stream into memory to ensure any network issues\n     //are exposed\n     stream.CopyTo(memory);\n}\nvar tmpimg = System.Drawing.Image.FromStream(memory);            {\ntmpimg.Save(@appDirectory + "\\resources\\" + urlresource);	0
19668177	19641495	DataContract Serializer doesnt de-serialize List	var memberGoals = from v in doc.Root.Descendants(Common.Constants.NameSpace + "memberGoal")\n                              select new MemberGoalModel\n                              {\n                                  goalDescription = v.Element(Common.Constants.NameSpace + "goalDescription").Value,\n//Assign Other Properties here. \n\n                              };\n            //return Deserialize<MemberCarePlanModel>(ms);\n            return memberGoals.ToList()	0
12147482	12147333	How to fetch an XML feed using asp.net	WebClient client = new WebClient();\nString htmlCode = client.DownloadString("url");	0
31223877	31223585	Access Denied C# Winform Closing	Environment.Exit(0);	0
2670199	716256	Creating a circularly linked list in C#?	static class CircularLinkedList {\n    public static LinkedListNode<object> NextOrFirst(this LinkedListNode<object> current) {\n        if (current.Next == null)\n            return current.List.First;\n        return current.Next;\n    }\n\n    public static LinkedListNode<object> PreviousOrLast(this LinkedListNode<object> current) {\n        if (current.Previous == null)\n            return current.List.Last;\n        return current.Previous;\n    }\n}	0
26174574	26167387	Run git commands from a C# function.	string gitCommand = "git";\nstring gitAddArgument = @"add -A" ;\nstring gitCommitArgument = @"commit ""explanations_of_changes"" "\nstring gitPushArgument = @"push our_remote"\n\nProcess.Start(gitCommand, gitAddArgument );\nProcess.Start(gitCommand, gitCommitArgument );\nProcess.Start(gitCommand, gitPushArgument );	0
27982613	27678210	Print Gives Unlimited Pages	_Line = 0; 
\n
\nvoid printDocument1_PrintPage( object sender, System.Drawing.Printing.PrintPageEventArgs e )
\n                
\n            {
\n
\n                float lineHeight = NormalFont.GetHeight(e.Graphics) + 4;
\n     
\n                    float yLineTop = e.MarginBounds.Top;
\n                    yLineTop = yLineTop + 100;
\n
\n                    for ( ; _Line <= 100 ; _Line++ )
\n                    {
\n
\n                        if ( yLineTop + lineHeight > e.MarginBounds.Bottom )
\n                        {
\n                            e.HasMorePages = true;
\n                            return;
\n                        }
\n     
\n                        e.Graphics.DrawString( "TEST: " + _Line, NormalFont, Brushes.Black, new PointF( e.MarginBounds.Left, yLineTop ) );
\n
\n                        yLineTop += lineHeight;
\n
\n                    }
\n
\n                    e.HasMorePages = false;
\n              
\n            }	0
9045399	9042861	How to make an absolute path relative to a particular folder?	Uri fullPath = new Uri(@"C:\RootFolder\SubFolder\MoreSubFolder\LastFolder\SomeFile.txt", UriKind.Absolute);\nUri relRoot = new Uri(@"C:\RootFolder\SubFolder\", UriKind.Absolute);\n\nstring relPath = relRoot.MakeRelativeUri(fullPath).ToString();\n// relPath == @"MoreSubFolder\LastFolder\SomeFile.txt"	0
5407726	5407624	Mark elements in WPF	FrameworkElement.Tag	0
22478893	22478638	How to Explicit event accessors	delegate void EventHandler (SomeObject m, EventArgs e);\n EventHandler _priceChanged; //Private Delegate\n private Object _myLock = new Object();\n\n public event EventHandler PriceChanged\n {\n    add {\n       lock(_myLock)\n       {_priceChanged += value;}\n    }\n    remove {\n       lock(_myLock)\n       {_priceChanged -= value;} \n    }\n }	0
11158489	11158044	DataGridView navigating to next row	int nRow;\nprivate void Form1_Load(object sender, EventArgs e)\n{\n\n    nRow = dataGridView1.CurrentCell.RowIndex;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    if (nRow < dataGridView1.RowCount )\n    {\n        dataGridView1.Rows[nRow].Selected = false;\n        dataGridView1.Rows[++nRow].Selected = true;\n    }\n}	0
5740957	5740868	Use a Enum Bastetype as Key in a abstract Dictionary	public interface IClass<TEnum>\n{ \n    Dictionary<TEnum, ISecondClass> { get; } \n}\n\npublic abstract class ClassBase<TEnum> : IClass<TEnum>\n{\n    public abstract Dictionary<TEnum, ISecondClass> { get; protected set;}\n}\n\npublic class ConcreteClass : ClassBase<ConcreteEnum>\n{\n    public override Dictionary<ConcreteEnum, ISecondClass> { get; protected set;}\n}	0
19833285	19832975	OOP - Get sum of one property in another property of the same class	Class ProductionManager\n{\n  List<ProductionItem> _ProductionItems\n\n  AddProductionItem(ProductionItem)\n  {\n    // Add the production items to _ProductionItems List\n\n    // Now \n    // 1) enumerate the current collection of _ProductionItems\n    // 2) keep running totals\n    // 3) now re-enumerate the current collection of _ProductionItems\n    //    updating each item with its respective percentage of the totals \n    //    you calculated in step 2.\n    // and populate each ProductionItem with the respective percentages\n  }\n}	0
8400580	8400315	how to get EPPlus OpenXML row count (c#)	workBook.Worksheets.Count	0
14702106	14215460	How to correctly use a button in a listbox itemtemplate / datatemplate?	listboxitem.AddHandler(UIElement.MouseLeftButtonDownEvent, new System.Windows.Input.MouseButtonEventHandler(MyMouseLeftButtonDownEventHandler), true);	0
6734974	6734862	Two CalendarExtenders?	var datetimeForQuery = extenderVariable.SelectedDate.ToString("yyyyMMdd");	0
655402	655326	Clean way to reduce many TimeSpans into fewer, average TimeSpans?	foreach(var set in source.ToList().Chunk(10)){\n    target.Enqueue(TimeSpan.FromMilliseconds(\n                            set.Average(t => t.TotalMilliseconds)));\n}	0
5154972	5154837	How do I determine that the key or vector are incorrect using Rijndael to decrypt a file?	using (FileStream fsInput = new FileStream(strInputFile, FileMode.Open, FileAccess.Read))\n{\n    using (FileStream fsOutput = new FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write))\n    {\n        CryptoStream csCryptoStream = null;\n        RijndaelManaged cspRijndael = new RijndaelManaged();\n        cspRijndael.BlockSize = 256;\n        switch (Direction)\n        {\n            case CryptoAction.ActionEncrypt:\n                csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV),\n                                                  CryptoStreamMode.Write);\n                break;\n            case CryptoAction.ActionDecrypt:\n                csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV),\n                                                  CryptoStreamMode.Write);\n                break;\n        }\n        fsInput.CopyTo(csCryptoStream);\n        csCryptoStream.Close();\n    }\n}\npRet = true;	0
23897620	23897534	parse excel file best practise	Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());\n\nSystem.Array myvalues = (System.Array)range.Cells.Value;\n\nstring[] strArray = ConvertToStringArray(myvalues);	0
4329431	4328354	How to tell if the control or control interface is editable by the user?	Public Shared Function IsControlEditable(ByVal ctrl As Control) As Boolean\n    Return TypeOf ctrl Is IPostBackDataHandler\nEnd Function	0
11081309	11031081	How to send keystrokes to application UI automation -C#	System.Diagnostics.Process.Start("osk.exe");	0
10981265	10981189	Comparing dates, looking for the next instance of a specific time	private static DateTime GetNext4AM(DateTime input)\n{\n    var result = new DateTime(input.Year, input.Month, input.Day, 4, 0, 0);\n\n    if (result > input)\n    {\n        return result;\n    }\n    else\n    {\n        return result.AddDays(1);   \n    }\n}	0
6201136	6200901	Updating only part of a model	[HttpPost]\npublic ActionResult Update(Product productPassedInFromView)\n{ \n    Product productToEdit = db.Products.Find(productPassedInFromView.ID);\n\n    productToEdit.Property1 = productPassedInFromView.Property1;\n    productToEdit.Property2 = productPassedInFromView.Property2;\n    //Continue for all the fields you want to edit.\n\n    db.SaveChanges();\n}	0
10129345	10123697	How to configure DirectSound's MaxSampleRate above 20000	DeviceInformation.Description	0
33412690	32453440	Convert BitmapImage to byte[]	public static BitmapImage BytesToImage(byte[] bytes)\n    {\n        BitmapImage bitmapImage = new BitmapImage();\n        try\n        {\n            using (MemoryStream ms = new MemoryStream(bytes))\n            {\n                bitmapImage.SetSource(ms);\n                return bitmapImage;\n            }\n        }\n        finally { bitmapImage = null; }\n    }\n\n    public static byte[] ImageToBytes(BitmapImage img)\n    {\n        using (MemoryStream ms = new MemoryStream())\n        {\n            WriteableBitmap btmMap = new WriteableBitmap(img);\n            System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);\n            img = null;\n            return ms.ToArray();\n        }\n    }	0
30503026	30486114	Potential cause for ExecuteReaderAsync to lose context	Task.Run(() => SomethingAsync()).Result	0
3389222	3001132	parse google maps geocode json response to object using Json.Net	public class GoogleGeoCodeResponse\n{\n\n    public string status { get; set; }\n    public results[] results { get; set; }\n\n}\n\npublic class results\n{\n    public string formatted_address { get; set; }\n    public geometry geometry { get; set; }\n    public string[] types { get; set; }\n    public address_component[] address_components { get; set; }\n}\n\npublic class geometry\n{\n    public string location_type { get; set; }\n    public location location { get; set; }\n}\n\npublic class location\n{\n    public string lat { get; set; }\n    public string lng { get; set; }\n}\n\npublic class address_component\n{\n    public string long_name { get; set; }\n    public string short_name { get; set; }\n    public string[] types { get; set; }\n}	0
29514414	29510969	How to show a list of objects with one extra property (which is not part of the class)?	namespace Solution.Project.Model\n{\n  partial class Title\n  {\n    public bool IsChecked {get;set;}\n  }\n}	0
31990951	31990822	How to close all open instances of a modeless dialog box?	foreach(var f in Application.OpenForms.OfType<GetDetails>().ToList())\n{\n    f.Close();\n}	0
8652160	8651682	Thumbnails and a photo album	g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\ng.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;\ng.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;	0
3477121	3474925	When I pass xml string as a request i get an Bad Request exception in WCF REST?	string value = "<?xml version=1.0?><person><firstname>john</firstname><lastname>smith</lastname> <person/>";\n\nvar content = HttpContentExtentions.CreateDataContract(value, typeof(string));\nusing (HttpResponseMessage response = m_RestHttpClient.Post("new/customerxml/"+value2, content)\n    {\n      ...\n    }	0
18189574	18189434	RichTextBox selective syntax highlighting	(?<=<tagStart>)(.*)(?=<tagEnd>)	0
176906	176877	ShowDialog() from keyboard hook event in C#	ShowDialog()	0
431058	431050	C# Reflection: Getting the fields of a DataRow from a Typed DataSet	row.Table.Columns	0
13662664	13662493	Extracting words between all tags in html c#	String openUrl = @"http://www.ebay.com/sch/-/11724/i.html?_nkw=" + some_part_number + "&_armrs=1&LH_Complete=1";\n\n                HtmlWeb hw = new HtmlWeb();\n                hw.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";\n                HtmlAgilityPack.HtmlDocument doc = hw.Load(openUrl);\n\n                foreach (HtmlNode nd in doc.DocumentNode.SelectNodes("//tr[@itemprop='offers']"))\n                {\n                    String title = "";\n                    title = Regex.Split(nd.InnerHtml.ToString(), ("title='"))[1].Trim();\n                    title = Regex.Split(title, "'")[0].Trim();\n                }	0
27324965	27324844	Prevent page reload when setting session variable	protected void btn_login_Click(object sender, EventArgs e)\n{       \n    Session.Add("user-id", _id);\n    Response.Redirect("AnotherPage.aspx");\n}	0
6686635	6686350	C# - Regex problem finding/displaying lines to RichTextBoxes	var placementOneList = new List<string>();\nvar placementTwoList = new List<string>();\nvar placementUserDefinedList = new List<string>();\n\n// For each line in the file\nforeach(string line in File.ReadAllLines("filename"))\n{\n    // Split the line to get only the "whatIWantToMatch" token\n    // (Error handling omitted for simplicity)\n    var match = line.Split(new String[] {" ", "\t"}, \n        StringSplitOptions.RemoveEmptyEntries)[5];\n\n    // Put the line in the appropriate list depending upon its "whatIWantToMatch" value\n    if(match.StartsWith("RES.") { placementOneList.Add(line); }\n    else if(match.StartsWith("0603.") { placementOneList.Add(line); }\n    // ...\n    else if(match.StartsWith("BGA.") { placementTwoList.Add(line); }\n    // ...\n    else { throw new ApplicationException(); } // No match found\n}	0
13128792	13128550	Thread-safe calls to WPF controls	System.Windows.Shapes.Ellipse PlayerEllipse = new System.Windows.Shapes.Ellipse();	0
16515038	16514966	How to copy excel worksheets Into another excel workbook without opening the excel file in c# winforms?	Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];\nExcel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(\n                Type.Missing, Type.Missing, Type.Missing, Type.Missing\n                );\nws.Copy(Before: sheet);	0
491161	491147	Should static variables be replaced with enums?	enum OrderState \n{\n  pending = 1,\n  shipped = 2\n}\n\npublic IList<Order> GetOrdersInState( OrderState )\n{\n}	0
24980155	24980017	Limiting input to just a, b, or d	using System.Linq;\n\nstatic void Main()\n{\n    var validInputs = new List<string> {"a", "b", "c", "d"};\n\n    string input = Console.ReadLine();\n\n    //validate and retry\n    while(! validInputs.Contains(input))\n    {\n        Console.WriteLine("Input was not valid. Please try again.");\n        input = Console.ReadLine();\n    }\n\n    //do something here with the valid input\n}	0
1700222	1700165	how to iterative thorugh an table using foreach condition	for(int i=0; i<= datatable.rows.count-1; i++)\n{\n    if(datatable.Rows[i]["ColName"] == "1")\n    {\n     //do something\n    }\n    else\n    {\n      //do something\n    }\n}	0
31576799	31575729	How to find the record with max field value	var builder = Builders<BsonDocument>.Sort;\nvar sort = builder.Descending("dt");\nvar CursorToResults =  col.Find<BsonDocument>(new BsonDocument()).Sort(sort);\nvar RecordwithMax_dt_Value = await CursorToResults.FirstOrDefaultAsync();	0
13901400	13901383	Search in Item2 in List<Tuple>	/* initialization */ List<Tuple<string, string, string>> mytuple = new List<Tuple<string, string, string>>();\n//pseudocode\nbool containsHello = mytuple.Any(c=>c.Item2.Contains("hello"));\n\nif(containsHello )\n{\n    Console.Write("Success");\n}	0
7208365	7207728	Is there a BeforeCheck for WPF checkboxes?	IsEnabled="False"	0
33095089	32975522	how to combine data from two table?	drop table Tbl1\n    Create table Tbl1\n    (\n        iSrno int identity(1,1) not null,\n        c_id numeric(18,2),\n        city_name nvarchar(500) \n        ,t_name nvarchar(500)\n    )\n\n    Insert into Tbl1 \n    select c_id,city_name as city_name, '' as t_name from CityDetails\n    Union\n    select c_id, 't_address','t_name'  from CityDetails\n\n    Insert into Tbl1 \n    select b.c_id,a.t_address,a.t_name  from TheaterDetail as a \n    Inner join CityDetails b on a.c_id= b.c_id\n\nselect * from Tbl1 Order by c_id asc , iSrno asc	0
20420231	20420184	Checking if a string contains a particular word	if (!stt.ToUpperInvariant().Contains("TIME"))	0
22193681	22193287	How to check if a list contains item in dynamic list using linq	return new DynamicXml(from item in _elements\n                 where attValues.Any(v => item.Attribute("attName").Value.Contains(v))\n                 select item);	0
17447597	17447513	How to find out which interfaces a .net class implements?	[SerializableAttribute]\npublic class ObservableCollection<T> : Collection<T>, \n    INotifyCollectionChanged, INotifyPropertyChanged	0
22796430	22795919	how to show past 20 days in this SQL Query	WHERE A.DATEDISPENSED >= DATEADD(dd,-20,GetDate())	0
5915832	5915825	In C# 4, how can I have constructors with optional parameters in a subclass of a parent with an overloaded constructor?	class Foo {\n    Foo(String arg0) \n    {\n      // do some stuff with arg0\n    }\n\n    Foo(String arg0, List<x> arg1)\n        : this(arg0)\n    {\n      // do some other stuff with arg1\n    }\n}\n\nclass Bar : Foo {\n    Bar(String arg0, List<y> arg2 = null, String arg3 = "") \n        : base(arg0)\n    {\n        this.Initialize( arg2, arg3);\n    }\n\n    Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "")\n        : base(arg0, arg1)\n    {\n      this.Initialize( arg2, arg3);\n    }\n\n    private void Initialize(List<y> arg2, String arg3)\n    {\n      // some third thing with arg2 and arg3\n    }\n}	0
8069239	8069190	Closure on a Query Expression	public static Expression<Func<Item, bool>> IsKnownByIn(string[] query )\n{\nvar i = PredicateBuilder.False<Item>();\nforeach (string keyword in query)\n{\n    string temp = keyword;\n    i = i.Or(p=> p.Name.Contains(temp) || p.ID.ToString().Contains(temp));\n}\nreturn i;	0
8718981	8713010	SVN pre-commit-hook, is there a way to set the logmessage in the client window?	svn log	0
30423283	30423236	Sum listview decimal	decimal total;\nforeach (Stock c in stock)\n{\n    string[] subitems = new string[4];\n    subitems[0] = c.ID.ToString();\n    subitems[1] = c.ItemDescription;\n    subitems[2] = "?" + c.PurchasePrice;\n    subitems[3] = "?" + c.SalePrice;\n\n    total += c.SalePrice;\n\n    ListViewItem listItem = new ListViewItem(subitems);\n    SalelistView.Items.Add(listItem);\n\n    ItemNumberTofFnd.Text = "";\n}\nSalelistView.Items.Add("Total " + total);	0
3767555	3767515	Retrieving property value from a form element in a thread-safe way	string calStatus = string.Empty;\nSynchronizedInvoke(lblCurrCalStatus, () => calStatus = lblCurrCalStatus.Text);	0
13021930	13019625	How to use Npoco FetchOneToMany?	var sql = "select a.*, b.* from tablea a \n    inner join tableb b on a.id = b.id \n    where EffectiveDate = @0"\n\nList<TableA> results = \n    db.FetchOneToMany<TableA,TableB>(x=>x.Id, sql, new DateTime(2012,10,18))	0
19416882	19415658	Check each string value in dictionary for specific characters c#	if (GUI.Button (new Rect(0, 30 + Screen.height-Screen.height + 40* i, 100, 20),dictionary[dictionary.Keys.ElementAt(indx)][i]))\n        {\nif (dictionary[dictionary.Keys.ElementAt(indx)][i].EndsWith ("(A)"))\n                {\n                    print ("Correct");\n            } \n            else\n            {\n                print ("Incorrect");        \n\n\n                }\n    }	0
27693084	27693063	Foreach with a where clause?	foreach(object obj in listofObjects.Where(w => !w.property))	0
3372802	3372734	How to invoke generic lambda expressions?	ExecuteCommand(() => _gc.ChargeCancellation(""));	0
20105272	20104471	How to name a map association with fluent api	class Skill\n{\n    ...\n    public virtual List<Employee> Employees { get; set; }\n}\n\nclass Employee\n{\n    ...\n    public virtual List<Skill> Skills { get; set; }\n}	0
20230957	20230937	C# Find Text After Word In Textbox	sub = textT.Substring(textT.IndexOf("in") + 3);	0
26193920	26193858	how to call non static method into a static?	class ClassName {\n   private static void data2() {\n       var data1Obj = new ClassName();\n       data1Obj.data1();\n   }\n\n   private void data1() {\n      //execute code here\n   }\n}	0
5160798	5160564	How to attach a database using a program deployed by C#?	SQLConnection conn;\n    try\n    {\n        conn = new SQLConnection(String.Format("Server={0};AttachDbFilename={1};Database=dbname; Trusted_Connection=Yes;", "Server Address", @"Path To Database"));\n        conn.Open();\n        conn.Close();\n    }\n    catch (Exception ex)\n    {\n        throw;\n    }\n    finally\n    {\n        conn.Dispose();\n    }	0
13213230	13213130	How can yield return statement return no elements?	private static IEnumerable<INode> YieldEmpty()\n{\n    yield break;\n}	0
5488362	5488234	How do I connect to a local host using PrincipalContext?	PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);	0
20554345	20554139	Reference control using string with value of name	var list = YourForm.Controls.OfType<TextBox>()\n                   .Where(x => x.Name.EndsWith("YourString"));\n\nforeach(TextBox t in list)\n{\n   Console.WriteLine(t.Name);\n   ......\n}	0
7181815	7181127	Drawing rectangle on picturebox - how to limit area of rectangle?	private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)\n{       \n  if (e.Button == MouseButtons.Left)\n  {\n    // Draws the rectangle as the mouse moves\n    rect = new Rectangle(rect.Left, rect.Top, Math.Min(e.X - rect.Left, pictureBox1.ClientRectangle.Width - rect.Left), Math.Min(e.Y - rect.Top, pictureBox1.ClientRectangle.Height - rect.Top));\n  }\n  this.Invalidate();     \n}	0
19189783	19189711	multiple checks for file extension	string[] files = Directory.GetFiles(\n    DirectoryPath, \n    String.Format("{0}.*", fileNameOnly));	0
12244726	12244562	How to select data for particular date in linq using C#	var selectionDate = new DateTime(2012,8,29);\n\nvar serialNumbers = from sn in code \n            where DateTime.Parse(\n                         sn.Trim().Substring(sn.Trim().Length-8,8), \n                         new DateTimeFormatInfo {ShortDatePattern="dd/MM/yy"}) == \n                              selectionDate;\n             group sn by sn.Substring(0, 10) into g \n             select new { Key = g.Key,  \n                          Cnt = g.Count(),  \n                          Min = g.Min(v => v.Substring(10)),  \n                          Max = g.Max(v => v.Substring(10)) };	0
9264294	9262356	Retrieve element within html hierarchy	IE myIE = new IE();\nmyIE.GoTo("[theurl]");\nstring theText = myIE.Table("someId").Divs[0].Text;	0
6117127	6116979	wpf detect clicked event finished without delaying main process	public void click_event() \n{\n    <start new thread>\n         <foreach(thread in threads)>\n            <do work>\n         <join threads>\n         <do your work here>\n}	0
1030879	1030869	How do I get TimeSpan in minutes given two Dates?	TimeSpan span = end-start;\ndouble totalMinutes = span.TotalMinutes;	0
22967437	22967300	Upload a picture using ASP.NET MVC4 RAZOR	public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)\n        {\n            if (files != null)\n            {\n                TempData["UploadedFiles"] = GetFileInfo(files);\n            }\n\n            return RedirectToAction("Result");\n        }\n\n        public ActionResult Result()\n        {\n            return View();\n        }\n\n        private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> files)\n        {\n            return\n                from a in files\n                where a != null\n                select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);\n        }	0
10144513	10144439	asp.net OnClick events for controls	public Default() {\n\n    this.Init += (_o, _e) => {\n         this.Wizard.NextButtonClick += WZTestResult_NextButtonClick;\n    }\n}	0
31902198	31178283	Working with UMat in Emgu wrapper	private UMat CvAndHsvImage(Image<Bgra, Byte> imgFrame, byte lowerHue, byte upperHue, byte lowerSat, byte upperSat, byte lowerBright, byte upperBright,\n    byte erosion = 0, byte dilate = 0, bool hue = false, bool sat = false, bool bright = false, bool invert = false)\n{\n    // <snip>\n\n    // Final image that will be returned.\n    UMat ResultImage = new UMat();\n    UMat ResultImageH = new UMat();\n    UMat ResultImageS = new UMat();\n    UMat ResultImageV = new UMat();\n\n    // << Replaced this >>\n    // UMat[] hsvChannels = new UMat[3];\n    // hsvChannels = hsvImage.Split();\n    // << with this >>\n    VectorOfUMat hsvChannels = new VectorOfUMat();\n    CvInvoke.Split(hsvImage, hsvChannels);\n\n    // </snip>\n}	0
9826862	9824934	Cannot parse XML using Xpath	XPathDocument doc = new XPathDocument(fileloc);\nXPathNavigator nav = doc.CreateNavigator();\n\nXmlNamespaceManager manager = new XmlNamespaceManager(nav.NameTable);\nmanager.AddNamespace("bk", "http://www.microsoft.com/networking/WLAN/profile/v1");\n\n\nXPathNodeIterator iterator = nav.Select("/bk:WLANProfile/bk:MSM/bk:security/bk:sharedKey/bk:keyMaterial", manager);	0
5932505	5932424	Unchecking item in a context menu	displayOnScreenControls.IsChecked = false;	0
7124795	7124740	How to translate the following SQL to Linq?	var result = from record in context.customer \n    where record.joindate > DateTime.Now && \n        (record.customertype == "system" || record.customerstatus == "active") && \n        record.customerlocation == "europe"\n    select record	0
14165451	14161211	How to perform a LINQ GroupBy, Select, and then Take without performance hit?	ToList()	0
18199218	18199169	How do I add a loop to my code so the code keeps going until the user types '!'?	while (true)\n{\n    var inputCharacter = Console.ReadKey().KeyChar;\n    if (inputCharacter == '!')\n    {\n        break;\n    }\n\n    if (char.IsLower(inputCharacter))\n    {\n        Console.WriteLine("OK");\n    }\n    else\n    {\n        Console.WriteLine("The character is not a lowercase letter.");\n    }\n}	0
10467659	10467654	Centralize before and after actions around a new task created by TPL	public void DoIt(Action ThingToDo) {\n    ComponentViewModel.Instance.IsApplicationBusy = true;\n    ComponentViewModel.Instance.BusyMessage = "Loading...";\n\n    var loadProviderTask = Task.Factory.StartNew(ThingToDo);\n    loadProviderTask.ContinueWith(antecdent =>\n    {\n        ComponentViewModel.Instance.IsApplicationBusy = false;\n    }\n}	0
16843566	16843328	Add Image to Grid - WPF	for (int i = 0; i < NumofImages; i++)\n{\n  Image mole = new Image();\n  mole.Source = new BitmapImage(new Uri(MoleImageFunction));\n  mole.Name = "Mole" + i;  \n  Grid.SetColumn(mole, i);\n  grid_Main.Children.Add(mole);\n}	0
20720844	20720365	In NHibernate, how to delete all elements of an associated set?	ISession session = sessionFactory.OpenSession();\nITransaction tx = session.BeginTransaction();\n\nString hqlDelete = "delete Children c where c.ParentId = :parentId";\n\nint deletedEntities = s.CreateQuery( hqlDelete )\n        .SetString( "parentId", parentId )\n        .ExecuteUpdate();\ntx.Commit();\nsession.Close();	0
27921268	27920986	wpf webbrowser control not applying css	var fileName = System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);\nSetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", fileName, GetBrowserEmulationMode());	0
28571989	28571713	Adding context menu to richtextbox in a tab	TabPage tp = new TabPage("New Document");\nRichTextBox rtb = new RichTextBox();\nrtb.Dock = DockStyle.Fill;\nContextMenuStrip ctx = new ContextMenuStrip();\nctx.Items.Add(new ToolStripMenuItem("Cut",null, cutClick));\nctx.Items.Add(new ToolStripMenuItem("Copy", null, copyClick))\nctx.Items.Add(new ToolStripMenuItem("Paste", null, pasteClick));\n// Add other menu items as you need\n\nrtb.ContextMenuStrip = ctx;\n.....\n\n\n\nvoid cutClick(object sender, EventArgs e)\n{\n    RichTextBox rtb = sender as RichTextBox;\n    if(rtb.SelectedText.Length > 0)\n        rtb.Cut();\n}\nvoid copyClick(object sender, EventArgs e)\n{\n    RichTextBox rtb = sender as RichTextBox;\n    if(rtb.SelectedText.Length > 0)\n       rtb.Copy();\n}\nvoid pasteClick(object sender, EventArgs e)\n{\n    RichTextBox rtb = sender as RichTextBox;\n    DataFormats.Format textFormat = DataFormats.GetFormat(DataFormats.Text);\n    if(rtb.CanPaste(textFormat))\n        rtb.Paste();\n}	0
24168367	24149126	Implementing a Windows form that changes during run-time based on a Listener class	public partial class FormRecord : Form\n{\n    Controller controller;\n\n    public FormRecord()\n    {\n        InitializeComponent();\n        controller = new Controller();\n    }\n\n    public void UpdateGUI()\n    {\n         Frame frame = controller.frame();\n\n        //get information from captured frame \n        //update the GUI (specifically labels)\n        customLabel0.Text = someValueFromFrame.ToString();\n    }	0
1508554	1154023	Printing a dwf/dwfx file from WPF	private PrintQueue printQueue;\n\nPrintDialog pDialog = new PrintDialog();\npDialog.PageRangeSelection = PageRangeSelection.AllPages;\npDialog.UserPageRangeEnabled = true;\n\nif (pDialog.ShowDialog() == true)\n    PrintSystemJobInfo xpsPrintJob = printQueue.AddJob(v.FileName, v.FilePath, false);	0
15042507	15041973	How to know a row's value before its inserted in gridview?	SqlCommand cmdEvent = new SqlCommand("SELECT COUNT(date) FROM patients WHERE date= '2012/02/23'", yourSqlConnection);\nobject myCount;\nif (yourSqlConnection.State == ConnectionState.Closed){ yourSqlConnection.Open(); }\nmyCount = cmdEvent.ExecuteScalar();\nif (yourSqlConnection.State == ConnectionState.Open){ yourSqlConnection.Close(); }\n\nif (myCount != null)\n{\n  if ((int)myCount >= 10)\n  {\n    // Logic here e.g myLabel.Text = "You have reached your maximum of 10 visits!";\n    return;\n  }\n}	0
23223518	23207050	How do I implement a WPF control with its own DataTemplate DependencyProperty?	foreach (object point in PointsSource)\n        {\n            FrameworkElement pointElement = _PointsTemplate.LoadContent() as FrameworkElement;\n            pointElement.DataContext = point;\n            this.Children.Add(pointElement);\n        }	0
26285860	26137323	How do I convert a string based time to hh:mm format in excel using EPPlus?	var package = new ExcelPackage(new FileInfo("text.xlsx"));\nvar sheet = package.Workbook.Worksheets.Add("Sheet 1");\n\nvar someTime = "10:10:00";\nvar timeSpan = TimeSpan.Parse(someTime);\nsheet.Cells[1, 1].Value = timeSpan;\nsheet.Column(1).Style.Numberformat.Format = "hh:mm";\n\npackage.Save();	0
2835774	2835734	How to handle recurring execution?	Timer tmr = new Timer(DoSomething, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 10, 0))	0
951737	951624	How to create a delegate to an instance method with a null target?	delegate void OpenInstanceDelegate(A instance, int a);\n\nclass A\n{\n    public void Method(int a) {}\n\n    static void Main(string[] args)\n    {\n        A a = null;\n        MethodInfo method = typeof(A).GetMethod("Method");\n        OpenInstanceDelegate action = (OpenInstanceDelegate)Delegate.CreateDelegate(typeof(OpenInstanceDelegate), a, method);\n\n        PossiblyExecuteDelegate(action);\n    }\n}	0
2496730	2496662	SQL Server parameters array bol --> dal	var sqlParams = new SqlParameter[]\n        {\n            new SqlParameter("@p1", SqlDbType.VarChar, 30) {Value = "val1"},\n            new SqlParameter("@p2", SqlDbType.VarChar, 30) {Value = "val2"},\n        };	0
2826807	2823639	Only send populated object properties over WCF?	[DataContract(Namespace = "...")]\npublic class Monkey\n{\n        [DataMember(EmitDefaultValue=false, ....)]\n        public string Arms { get; set; }\n\n        ........    \n\n        /* repeat another X times */\n}	0
7272599	7272071	Setting max autogenerate width on autogenerated columns in a datagrid	foreach(var c in grid.Columns)\n{\n    var width = c.Width;\n    if(width > threshold)\n    {\n        c.Width = threshold;\n    }\n}	0
3015625	3015541	How to add ONLY system tray icon to application?	Application.Run(); //remove the Form oject from this call	0
21809659	21786221	Query Sitecore Lucene-index with ContentSearch-API on DateTime-range	private void GetItems(int month, int year)\n        {\n            DateTime startDate = new DateTime(year,month,1);\n            DateTime endDate = new DateTime(year,month, DateTime.DaysInMonth(year, month));\n            using ( IProviderSearchContext context = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())\n            {\n                List<EventSearchResultItem> allEvents = context.GetQueryable<EventSearchResultItem>(new CultureExecutionContext(Sitecore.Context.Language.CultureInfo))\n                .Where(s =>\n                       s.TemplateId == this.EventTemplateID &&\n                       ((s.BeginDate >= startDate) || (s.EndDate <= endDate))\n                           )\n               .ToList();\n            }\n        }	0
34353238	34267840	Modifying DataGrid cell values on CellEditEnding event	public class MyDataGrid : DataGrid\n{\n    protected override void OnBeginningEdit(DataGridBeginningEditEventArgs e)\n    {\n        base.OnBeginningEdit(e);\n        this.CommitEdit();\n    }\n\n    protected override void OnCellEditEnding(DataGridCellEditEndingEventArgs e)\n    {\n        base.OnCellEditEnding(e);\n        (e.Row.Item as DataRowView).Row[1] = "a string that should be displayed immediatly";\n    }\n}	0
13432672	13432623	Converting a Matrix to a grid of colors	using System.Drawing;\n\nvoid SaveMatrixAsImage(Matrix mat, string path)\n{\n    using (var bmp = new Bitmap(mat.ColumnCount, mat.RowCount))\n    {\n        for (int r = 0; r != mat.RowCount;    ++r)\n        for (int c = 0; c != mat.ColumnCount; ++c)\n            bmp.SetPixel(c, r, MakeMatrixColor(mat[r, c]));\n        bmp.Save(path);\n    }\n}\n\nColor MakeMatrixColor(int n)\n{\n    switch (n)\n    {\n        case 0: return Color.White;\n        case 1: return Color.Black;\n        case 2: return Color.Blue;\n        case 3: return Color.Red;\n    }\n    throw new InvalidArgumentException("n");\n}	0
4102107	4102003	get all strings in c# code file	Localizable(false)	0
18088619	18088290	Select HTML tag with multiple values in the same attribute	SelectSingleNode("//span[contains(@class, 'test1')]");	0
8277391	8277345	How can i make a Regex such that is should allow only 2 characters M or F	var match = Regex.Match("M", @"^M(ale)?$|^F(emale)?$");\nvar result = match.Success;	0
13092911	12948304	MSChart insert, move, delete point	Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n        Chart1.Series(0).ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line\n        Chart1.Series(0).Points.AddXY(0, 10)\n        Chart1.Series(0).Points.AddXY(1440, 100)\n        Chart1.Series(0).Points.AddXY(600, 80)\n\n        Chart2.Series(0).ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line\n        Chart2.Series(0).Points.AddXY(0, 10)\n        Chart2.Series(0).Points.AddXY(1440, 100)\n        Chart2.Series(0).Points.AddXY(600, 80)\n\n        Chart1.DataManipulator.Sort(System.Windows.Forms.DataVisualization.Charting.PointSortOrder.Descending, Chart1.Series(0))\n\n    End Sub	0
10188474	10188339	Access an object properties without casting to a type	foreach(object s in St)\n{\n   Type type = s.GetType();\n   PropertyInfo property = type.GetProperty("Name");\n   if(property !=null)\n   {\n       string name= (string )property.GetValue(s, null);\n   }\n}	0
30442857	30436227	C# lambda call in for loop references to last object	var action = new Func<Entity, Action>(p => \nnew Action(() => { p.isDoingAction = false; Debug.Log(p.name + " finished")); })(player);\nplayer.actions.Dequeue().Execute(action);	0
18368843	18368808	How to make asynchronous calls from a WCF client to WCF Service in parallel	var task1 = proxy.PrintCustomerHistoryAsync(customerListOne, @"c:\DestinationOne\");\nvar task2 = proxy.PrintCustomerHistoryAsync(customerListTwo, @"c:\DestinationTwo\");\n\n// The two tasks are running, if you need to wait until they're done:\nawait Task.WhenAll(task1, task2);	0
14155058	14153873	A lock designed for asynchronous applications	IDisposable myLock;\n\nmyLock = sharedLock.ObtainLock(delegate() {\n     socket = new Socket();\n     socket.BeginConnect(hostname, connectcallback);\n});\n\nvoid connectcallback(IAsyncResult result) {\n    socket.EndConnect(result);\n    isConnected = true;\n    myLock.Dispose();\n}	0
13501411	13501064	Load an ObservableCollection<string> with a Task	public void FetchAndLoad()\n    {\n        // Called from the UI, run in the ThreadPool\n        Task.Factory.StartNew( () =>\n        this.FetchAsync(e => this.Dispatcher.InvokeAsync(\n            () => this.observableCollection.Add(e)\n            )\n        ));\n    }\n\n    public void Fetch(Action<string> addDelegate)\n    {\n                    // Dummy operation\n        var list = new List<string>("Element1", "Element2");\n\n        foreach (var item in list)\n            addDelegate(item);\n    }	0
14051615	14050507	Get Element Node Value of XML using XElement in C#	string text = "<E:Events xmlns:E=\"Event-Details\"><Date>12/27/2012</Date><Time>???11:12 PM</Time><Message>Happy Birthday</Message></E:Events>";\nXElement myEle = XElement.Parse(text);\nConsole.WriteLine(myEle.Element("Date").Value);\nConsole.WriteLine(myEle.Element("Time").Value);\nConsole.WriteLine(myEle.Element("Message").Value);	0
9763720	9642528	How to add an image to the header of MVC3 Grid - @grid.GetHtml?	public class GridView : System.Web.UI.WebControls.GridView\n{\n   protected override void OnSorted(EventArgs e)\n   {\n      string imgArrowUp = ...;\n      string imgArrowDown = ...;\n\n      foreach (DataControlField field in this.Columns)\n      {\n         // strip off the old ascending/descending icon\n         int iconPosition = field.HeaderText.IndexOf(@" <img border=""0"" src=""");\n         if (iconPosition > 0)\n            field.HeaderText = field.HeaderText.Substring(0, iconPosition);\n\n         // See where to add the sort ascending/descending icon\n         if (field.SortExpression == this.SortExpression)\n         {\n            if (this.SortDirection == SortDirection.Ascending)\n               field.HeaderText += imgArrowUp;\n            else\n               field.HeaderText += imgArrowDown;\n         }\n      }\n\n      base.OnSorted(e);\n   }\n}	0
11310719	11310486	Regex returning null while searching for a string	var fileNames = (from Match m in Regex.Matches(pageSource, @"[0-9]+_+[A-Za-z]+_+[0-9]+-+[0-9]+-+[0-9]+(_+[0-9]+)?\.+(acc|zip|app|xml|def|enr|exm|fpr|pnd|trm)")                         select m.Value).ToList();	0
22754819	22754781	Add List objects from a single list to a new List using LINQ	var newList = myList.SelectMany(x => x.innerList);	0
11626034	11625976	How do i change the timer interval according to numericupdown value in real time?	timer3.Stop();\ntimer3.Interval = Convert.ToInt32(numericUpDown1.Value); \ntimer3.Start();	0
26291994	26291926	Go back to parent node using XmlReader	r.ReadToFollowing("last_modified_at");\nstring lastModified = r.ReadElementContentAsString("last_modified_at", r.NamespaceURI);	0
13497004	13496978	Why isnt this C# If statement finding a null value?	string.IsNullOrEmpty()	0
17545121	17544897	insert into database using context doesn't work	JobTable jobTable = new JobTable();\n\nusing(var context = new JobEntities())\n{\n    jobTable.JobDate = DateTime.Now;\n    jobTable.JobProcess = processName;\n\n    context.JobTable.Add(jobTable);\n\n    var result = context.SaveChanges();\n    Console.WriteLine("Result => " + result.ToString());\n\n    return jobTable.JobId;\n}	0
23458319	23458302	going through a list with a for loop	for(int i = (checkpoints.Count - 1); i >= 0; i--)  // your mistake was here\n{\n    if(checkpoints[i].active == 1)\n    {\n        playerPositionX = checkpoints[i].xPosition;\n        playerPositionY = checkpoints[i].yPosition;\n\n        camPositionX = checkpoints[i].xPosition;\n\n       break;\n    }\n}	0
3117714	3117087	extract last match from string in c#	string input = "[abc].[some other string].[can.also.contain.periods].[our match]";\n\nvar search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);\n\nstring ourMatch = search.Match(input).Groups[1]);	0
8748762	8748251	Feed YouTube in listbox Error	XmlDocument RSSXml = new XmlDocument(); \n     RSSXml.Load("http://gdata.youtube.com/feeds/api/users/google/uploads");  \n\n    XmlNamespaceManager nsmgr = new XmlNamespaceManager(RSSXml.NameTable);\n    nsmgr.AddNamespace("tns", "http://www.w3.org/2005/Atom");\n\n    XmlNodeList RSSNodeList = RSSXml.SelectNodes("//tns:entry", nsmgr); \n    XmlNode RSSDesc = RSSXml.SelectSingleNode("tns:feed",nsmgr);   \n\n    foreach (XmlNode RSSNode in RSSNodeList)  {      \n        XmlNode RSSSubNode;      \n        RSSSubNode = RSSNode.SelectSingleNode("tns:title", nsmgr);      \n        string title = RSSSubNode != null ? RSSSubNode.InnerText : "";      \n        RSSSubNode = RSSNode.SelectSingleNode("tns:link/@href",nsmgr);      \n        string link = RSSSubNode != null ? RSSSubNode.InnerText : "";      \n\n        Console.WriteLine("{0} {1}",title, link);\n    }	0
10423773	10421791	Waiting on GET response	private string requestByProxy(string url)\n{\n    string responseString, proxyAddress;\n\n    while (responseString == null)\n    {\n        try\n        {\n            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n            // set properties, headers, etc\n\n            proxyAddress = getNextProxy();\n\n            if (proxyAddress == null)\n                throw new Exception("No more proxies");\n\n            request.Proxy = new WebProxy(proxyAddress);\n            request.Timeout = 15 * 1000;\n\n            HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n            StreamReader sr = new StreamReader(response.GetResponseStream());\n            responseString = sr.ReadToEnd();\n        }\n        catch (WebException wex)\n        {\n            continue;\n        }\n    }\n\n    return responseString;\n}	0
31436893	31436645	Advantage of using Dependency Injection when the implementation changes	class MyClass\n{\n         public MyClass(ADependency dep1,OtherDependency dep2){}\n }	0
19104424	19104100	Assigning Events to newly created controls	List<Label> myLabels = new List<Label>(txt);\n\nfor (int i = 0; i < txt; i++)\n{\n    newLabel = new Label();\n    newLabel.MouseMove += MyControl_MouseMove;\n    newLabel.MouseDown += MyControl_MouseDown;\n    myLabels.Add(newLabel);\n.......\n\n// Later in Dispose\nforeach (var lbl in myLabels)\n{\n     lbl -= MyControl_MouseMove;\n     lbl -= MyControl_MouseDown;\n}\nmyLabels.Clear();	0
14937140	14935765	editing one column of data grid view	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        add();\n    }\n\n    //If you are using template field\n\n    ((TemplateField)gvGridView.Columns[index]).EditItemTemplate = null;\n\n    //If you are using boundfield\n\n    ((BoundField)gvGridView.Columns[index]).ReadOnly = true;\n}	0
16904817	16904644	How to properly call JsonResult method in controller from view model?	public ActionResult Index()\n{\n    MyViewModel model = new MyViewModel();\n    model.data = GetData();\n    return View(model);\n}\n\npublic JsonResult GetJson(DateTime startDate,DateTime endDate)\n{\n    var result=GetData(startDate,endDate);\n    return Json(result);\n}\n\nprivate IEnumerable<MyData> GetData(DateTime startDate=null,DateTime endDate=null)\n{\n    return something;\n}	0
23821698	23821627	How to get first column value of DataGridView double clicked row?	dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value	0
12484628	12484038	linq variables to datagridview in c#	var query = from word in words\n    group word by word.Length into gr\n    orderby gr.Key ascending\n    select new { Length = gr.Key, Words = gr.Aggregate((left, right)=>string.Format("{0}, {1}", left, right)) };	0
1543247	1540281	A problem with MyThread and the Timer Control	public byte[] ReadAllBytesFromStream(Stream input)\n{\n    if(this.InvokeRequired)\n    {\n        this.Invoke(new MethodInvoker(clock.Start));\n    }\n    else\n    {\n        clock.Start();\n    }\n\n    using (...)\n    {\n        while (some conditions) //here we read all bytes from a stream (FTP)\n        {\n            ...\n (int-->)   ByteCount = aValue;\n            ...\n         }\n        return .... ;\n    }\n}\n\nprivate void clock_Tick(object sender, EventArgs e)\n{\n    this.label6.Text = ByteCount.ToString() + " B/s"; //show how many bytes we have read in each second\n}	0
12678554	12678467	How to return the derived type from the base type	public interface IBall\n{\n}\npublic class BilliardBall : IBall\n{\n}\npublic abstract class Sport\n{\n    protected abstract IBall Ball { get; }\n\n}\npublic class Billiards : Sport\n{\n    protected override IBall Ball\n    {\n        get { return new BilliardBall(); }\n    }\n}	0
20320211	20320174	C# XML Search For Node Value	//forecastday[title='tuesday']/fcttext	0
12240876	10666062	MVC3 Html Helper Method To Access Parent Container?	new HtmlString("<li>" + \n               htmlHelper.ActionLink(linkText, actionName, controllerName)\n               + "</li>");	0
5511644	5511603	How to select *some* items with LINQ?	var results = source.Select(item => \n  {\n    try\n    { \n      return TResult.Parse(item);\n    }\n    catch\n    { return null; }\n  }).Where(result => result != null).ToList();	0
5184924	5184888	C# Split String and Use in If Statement	string people = "John;Joe;Jane;Mike";\nList<string> names = new List<string>(people.Split(';'));\n\nif(names.Contains(person))\n{\n    ....\n}\nelse\n{\n    ....\n}	0
17409190	17408793	Changing background color of words in richTextBox after typing a special character	int lastStart = 0;\n    int lastEnd = 0;\n    private void richTextBox1_TextChanged(object sender, EventArgs e)\n    {\n        richTextBox1.Select(lastStart, lastEnd + 1);\n\n        if (richTextBox1.SelectedText.ToLower() == "anything")\n        {\n            richTextBox1.SelectionBackColor = Color.Red;\n            lastStart = richTextBox1.SelectionStart + richTextBox1.SelectionLength;\n        }\n        else\n        {\n            richTextBox1.SelectionBackColor = Color.White;\n        }\n\n        lastEnd = richTextBox1.SelectionStart + richTextBox1.SelectionLength;\n        richTextBox1.Select(lastEnd, 1);\n    }	0
27726655	27726550	Combine two list values into one	List<string> values = new List<string>();\nforeach (Feature f in allFeatures)\n{\n    var columnValues = f.ColumnValues;\n    var firstLayerCode = columnValues[layercode].ToString();\n    var secondLayerCode = columnValues[layercode2].ToString();\n\n    if (columnValues.ContainsKey(layercode) && columnValues.ContainsKey(layercode2))\n    {\n        if (!values.Contains(firstLayerCode) && !values.Contains(secondLayerCode))\n        {\n            var combinedValue = firstLayerCode + ";" + secondLayerCode;\n            values.Add(combinedValue);\n        }\n    }\n}	0
21632524	21631888	unity3d - Accelerometer sensitivity	Vector3 aNew = Input.acceleration;\na = 0.1 * aNew + 0.9 + a;	0
4205011	4202989	Convert empty cells in a data table to 0	amountColumn.DefaultCellStyle.NullValue = "0";	0
2021153	2021137	Position of character to the left of current position in string	yourstring.LastIndexOf("foo", 0, currentPosition)	0
11260595	11237891	What is the recommended way to create maps in AutoMapper within a stand-alone, reusable library?	private static readonly object MappingLock = new object();\nprivate static bool _ready = false;\n\npublic static bool IsMappingInitialised()\n{\n    if (!_ready)\n    {\n        lock (MappingLock)\n        {\n            if (!_ready)\n            {\n                Mapper.CreateMap<ServerWidget, Widget>();\n                _ready = true;\n            }\n        }\n    }\n\n    return _ready;\n}	0
8129806	8129705	C# IsEqual with ignorable list	public static bool AreEqual<T>(this T first, T second, \n  bool recurse = false, params string[] propertiesToSkip)\n{\n  if (Equals(first, second)) return true;\n\n  if (first == null)\n    return second == null;\n  else if (second == null)\n    return false;\n\n  if (propertiesToSkip == null) propertiesToSkip = new string[] { };\n  var properties = from t in first.GetType().GetProperties()\n                   where t.CanRead\n                   select t;\n\n  foreach (var property in properties)\n  {\n    if (propertiesToSkip.Contains(property.Name)) continue;\n\n    var v1 = property.GetValue(first, null);\n    var v2 = property.GetValue(second, null);\n\n    if (recurse)\n      if (!AreEqual(v1, v2, true, propertiesToSkip))\n        return false;\n      else\n        continue;\n\n    if (!Equals(v1, v2)) return false;\n  }\n  return true;\n}	0
9545731	9545619	A fast hash function for string in C#	static UInt64 CalculateHash(string read)\n{\n    UInt64 hashedValue = 3074457345618258791ul;\n    for(int i=0; i<read.Length; i++)\n    {\n        hashedValue += read[i];\n        hashedValue *= 3074457345618258799ul;\n    }\n    return hashedValue;\n}	0
3338766	3337450	Display captured Jpeg File	private void SetBitmap(byte[] image, int width, int height, int dpi)\n  {\n    MainWindow.Instance.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate()\n    {\n        BMemoryStream ms = new MemoryStream(image);\n        JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n        BitmapSource bitmapSource = decoder.Frames[0];               \n\n        HwModeScreen.BarcodeImageCanvas.Children.Clear();\n        Image myImage = new Image();\n        myImage.Width = HwModeScreen.BarcodeImageCanvas.ActualWidth;\n        myImage.Height = HwModeScreen.BarcodeImageCanvas.ActualHeight;\n        myImage.Stretch = Stretch.Fill;\n        myImage.Source = bitmapSource;\n        HwModeScreen.BarcodeImageCanvas.Children.Add(myImage);\n    });	0
17331889	17323609	decorate IEnumerable without looping	public static IEnumerable<DocumentSearch> BuildDocumentSearch(IQueryable<Document> documents)\n{\n    return documents.Select(doc => new DocumentSearch(doc));\n}	0
6900389	6900383	TFS 2010 : how to retrieve a deleted file?	Get Latest	0
10503224	10503121	Having trouble with inherited classes, constructors with generics	public abstract class MyBaseObject\n{\n    public MyBaseObject(IEnumerable<MyBaseObject> parent)\n    {\n        this.Parent = parent;\n    }\n\n    public IEnumerable<MyBaseObject> Parent { get; set; }\n}\n\npublic class MyRealObject : MyBaseObject\n{ \n    public MyRealObject(MyRealCollection parent)\n        : base(parent)\n    { }\n\n    public new MyRealCollection Parent { get { return (MyRealCollection)base.Parent; } }\n}\n\npublic class MyRealCollection : IEnumerable<MyRealObject>\n{ }	0
28856117	28855123	Is there a way to programmatically change a font size?	//XAML\n\n<Grid>\n        <TextBox x:Name="box1" HorizontalAlignment="Left" Height="23" Margin="90,192,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>\n        <Label x:Name="label1" Content="This is a label" HorizontalAlignment="Left" Margin="90,98,0,0" VerticalAlignment="Top" Width="120"/>\n        <Button x:Name="btn1" Content="Enter" HorizontalAlignment="Left" Margin="106,258,0,0" VerticalAlignment="Top" Width="75" Click="btn1_Click"/>\n    </Grid>\n\n//Programmatically changing font\nprivate void btn1_Click(object sender, RoutedEventArgs e)\n        {\n            label1.FontSize = int.Parse(box1.Text);\n        }	0
13279702	13274597	Entity Framework 5 upgrade from 4	var objectContext = ((IObjectContextAdapter)context).ObjectContext;\nvar query = objectContext.CreateQuery<MyEntity>(\n    WhereClause.ToString(),\n    Params.ToArray());	0
6271375	6271358	How can I tell if a value in Request.Form is a number? (C#)	int value;\nif (int.TryParse(Request.Form["foo"], out value)) {\n    // it's a number use the variable 'value'\n} else {\n    // not a number\n}	0
6757409	6757355	How to find out next word in a sentence in c#?	string s = "bat and ball not pen or boat not phone";\nRegex reg = new Regex("not\\s\\w+");\nMatchCollection matches = reg.Matches(s);\nforeach (Match match in matches)\n{\n    string sub = match.Value;\n}	0
27530135	27488201	GridView and placeholders that never disapper in Windows 8 and Windows Phone app	ShowsScrollingPlaceholders=false	0
13009989	12999240	Animation using AniMate with Unity3D doesn't interact with physical objects	void FixedUpdate () {\n    if (Input.GetKey(KeyCode.LeftArrow)) {\n        StartCoroutine(TweenCoroutine());\n    }\n}\n\nIEnumerator TweenCoroutine() {\n    // To point 1\n    Hashtable props = new Hashtable();\n    props.Add("position", new Vector3(756f,112f,1124f));\n    props.Add("physics", true);\n    // Start first tween and wait for it to finish\n    yield return Ani.Mate.To(transform, 2, props);  \n\n    // To point 2\n    Hashtable props2 = new Hashtable();\n    props2.Add("position", new Vector3(731f,112f,1124f));\n    props2.Add("physics", true);\n    // Start second tween and wait for it to finish\n    yield return Ani.Mate.To(transform, 2, props2);\n\n    // etc...\n}	0
3651308	3651183	Save stream as image	Image img = System.Drawing.Image.FromStream(myStream);\n\nimg.Save(System.IO.Path.GetTempPath() + "\\myImage.Jpeg", ImageFormat.Jpeg);	0
12735913	12735334	Get object with generic type from interface that only sets the type in the method	public Table<T2> getTable<T2>() where T2:MasterClass\n{\n    return (Table<T2>)(object)table;\n}	0
1240216	1228871	Settings.settings File Keeps Getting Reset	if (Properties.Settings.Value.CallUpgrade)\n{\n    Properties.Settings.Value.Upgrade();\n    Properties.Settings.Value.CallUpgrade = false;\n}	0
10614811	10586478	Refreshing UpdatePanel after click event of a Button inside a modalpopup inside a UserControl	if (FunctionButtonPressedOk!= null)\n        {\n            //FunctionButtonPressedOk();\n            Page.GetType().InvokeMember(FunctionButtonPressedOk.Method.Name, BindingFlags.InvokeMethod, null, Page, new []{sender, e});\n        }	0
11561646	11561517	How can I get all the link titles?	foreach (HtmlNode linkItem in doc.DocumentNode.SelectNodes("//table[3]/tr//a"))\n{\n    Console.WriteLine(linkItem.Attributes["title"].Value());\n    Console.WriteLine(linkItem.Attributes["alt"].Value());\n}	0
4414878	4414659	How to read/write complex object with XmlWriter/XmlReader	public static void WriteElement(XmlWriter writer, string name, object value)\n    {\n        var serializer = new XmlSerializer(value.GetType(), new XmlRootAttribute(name));\n        serializer.Serialize(writer, value);\n    }	0
5342715	5332544	Returning ClickOnce version doesn't work when launching application on startup from the Windows Registry	string allProgramsPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs);\nstring shortcutPath = Path.Combine(allProgramsPath, keyName);\nshortcutPath = Path.Combine(shortcutPath, keyName) + ".appref-ms";	0
9528825	9528470	How do I add SQL auth to a C# forms app?	using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))\n        {\n            UGIcon.Open();\n\n            string userText = textBox11.Text;\n            string passText = textBox12.Text;\n\n            SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);\n\n            using (SqlDataReader rdr = cmd.ExecuteReader())\n            {\n                if (rdr.HasRows)\n                {\n                    while (rdr.Read())\n                    {\n                        string role = rdr["stRole"].ToString();\n                        MessageBox.Show(role);\n                    }\n                }\n                else\n                {\n                    MessageBox.Show("Access Denied!!");\n                }\n            }\n        }	0
7781126	7780157	Multiple Optional Parameters with ServiceStack.Net	Routes.Add("/save/{Year}/{Week}/{DaysString*}");	0
4355547	4355538	C# datagrid index was out of range	Student selected = dataGrid1.SelectedItem as Student;\nvar imagePath = selected.ImagePath;	0
5633155	5633048	Parse xml and apply formating to text	Foreach XMLnode node in xmlnodes\n{\n    if (node.attribute == "bold")\n    {\n        // apply bold to node text\n    }\n}	0
4335836	4333764	WPF:Enclose controls within a child window chrome which has a close button	var childWindow = new MyChildWindow();\nchildWindow.Show();	0
23228115	23213476	How to store value from datepicker into string variable	datepicker.Text = DateTime.Now.ToShortDateString();	0
34208668	34174281	How to implement Continuous Delivery with DNX and ASP.NET 5	dnu publish --runtime <name of runtime> --no-source	0
6675541	6675487	Is there a LINQ way to iterate through an array of strings?	var result = test.Select((s, i) => string.Format("{0}. {1}", i + 1, s));	0
14101304	14100678	disable a cell based on another cell value in a row in aspxgridview	e.GetValue("fieldname")	0
3305120	3255236	How to get only user created properties using microsoft.cci Members?	foreach (PropertyNode property in type.Members\n                .Where(m => m.NodeType == NodeType.Property)\n                .Cast<PropertyNode>())\n{\n    //...\n}	0
1617960	1617940	Expecting an exception in a test but wanting to verify dispose is called anyway	mockTcpClient.Setup(x => x.Dispose());\n\ntry \n{\n    using (var popClient = new PopClient(null, mockTcpClient.Object))\n    {\n\n    }\n}\nfinally \n{\n    mockTcpClient.VerifyAll();\n}	0
21093063	21092880	Accessing programmatically created controls	foreach (Control ctr in ctrl.Controls)\n        {\n            if (ctr is TextBox)\n            {\n                //Do your things\n                // ((TextBox)ctr).Text \n            }\n        }	0
13644254	13644078	Return min value in group with lambda/linq query	radios.GroupBy(x=> x.Channel).Select(x=>x.OrderBy(y=>y.Price)).Select(x=>x.First());	0
16448162	16439447	How to set the Selected item in the tree view on the Left side of CHM file	private void btnHelpTopic1_Click(object sender, EventArgs e)\n{\n    // sHTMLHelpFileName_ShowWithNavigationPane = "CHM-example_ShowWithNavigationPane.chm"\n    // This is a HelpViewer Window with navigation pane for show case only \n    // created with Microsoft HTMLHelp Workshop\n    helpProvider1.HelpNamespace = Application.StartupPath + @"\" + sHTMLHelpFileName_ShowWithNavigationPane;\n    Help.ShowHelp(this, helpProvider1.HelpNamespace, @"/Garden/tree.htm");\n}\n\nprivate void btnHelpTopic2_Click(object sender, EventArgs e)\n{\n    helpProvider1.HelpNamespace = Application.StartupPath + @"\" + sHTMLHelpFileName_ShowWithNavigationPane;\n    Help.ShowHelp(this, helpProvider1.HelpNamespace, @"/Garden/flowers.htm");\n}	0
31054788	31052271	Append DataVizualisation Chart Control to text file	consoleFile.WriteLine(chartBP.Text);\n            consoleFile.Close();\n\n            FileStream imgFile = File.Open(filename, FileMode.Append);\n            chartBP.SaveImage(imgFile, ChartImageFormat.Jpeg);\n            imgFile.Close();\n\n            consoleFile = new StreamWriter(filename, true);\n            consoleFile.WriteLine("\n\n");\n            consoleFile.Close();	0
2810474	2810295	Serialization of non-required fields in protobuf-net	bool {memberName}Specified {get;set;}	0
26359386	26358388	How convert the width of a column of a table in migradoc from uint pixel	Unit.FromCentimeter()	0
6339208	6339191	can you use output caching in asp.net-mvc based on the parameters of your controller action	[OutputCache(Duration=int.MaxValue, VaryByParam="id")]\npublic ActionResult Details(int id)\n{\n}	0
29529142	29528698	LINQ JSON add JProperty	from index in Enumerable.Range(0, q.subjectType.Length)\nselect\n    new JObject(\n    new JProperty("SubjectName", q.subjectName[index]),\n    new JProperty("Auditory", q.auditory[index]),\n    new JProperty("SubjectType", q.subjectType[index]),\n    new JProperty("TimeStart", q.TimeStart[index]),\n    new JProperty("TimeEnd", q.TimeEnd[index]),\n    new JProperty("Teacher", q.Teacher[index])))))));	0
27921945	27921855	Bracket a string that's inside single quotes with percentage sign	String r = Regex.Replace(s, @"'([^']*)'", "'%$1%'");	0
22067364	22067319	Proper way to get the windows UserName	System.Security.Principal.WindowsIdentity.GetCurrent().Name	0
13433922	13433313	How to crop a portion from tiff image	Rectangle crop = new Rectangle(158, 247, 823, 1183);\nvar bmp = new Bitmap(823, 1183);	0
21342421	21313016	Using MEF with abstract base class	var extensionFolder = ConfigurationManager.AppSettings["ExtensionPath"];\n var solutionPath = Directory.GetParent( System.IO.Directory.GetCurrentDirectory() ).Parent.FullName;\n var catalog = new AggregateCatalog();\n catalog.Catalogs.Add( new DirectoryCatalog( solutionPath + extensionFolder ) );\n var container = new CompositionContainer( catalog );\n container.ComposeParts( this );	0
5314763	5314264	how do i convert string to datetime in c#	string dtString = "18/03/2011 15:16:57.487";\n\n        System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");           \n\n        DateTime dt = DateTime.Parse(dtString.Split('.')[0], culture);\n\n        Double milliseconds = Double.Parse(dtString.Split('.')[1]);\n\n        dt = dt.AddMilliseconds(milliseconds);	0
26095564	26095431	OutOfMemory when removing rows > 500000 EntityFramework 6	context.Users.Delete(u => u.FirstName == "firstname");	0
10222326	10222278	Visual C#, process keeps growing until I get memory errors relating to a UserControl using a loop to draw graphics	using (Bitmap myBitmap = new Bitmap(a, b))\nusing (Graphics g = Graphics.FromImage(myBitmap)) {\n    for (int x = 0; x <= e - 1; x++) {\n        for (int y = 0; y <= f - 1; y++) {\n            g.DrawRectangle(Pens.LightBlue, g, h, i);\n        }\n    }\n\n    ScorePictureBox.Image = myBitmap;\n}	0
24408055	24407925	How to Set Background Image from IsolatedStorage	else\n    ib.ImageSource = await tsh.RetrievePhoto(Constants.BackgroundImageName);	0
22486666	22486602	Adding every day from TimeDate.ElaspedDays to a list	int totalDays = endTime.Subtract(startTime).TotalDays as int;\nList<DateTime> dates = new List<DateTime>(totalDays + 1); // using this constructor will make filling in the list more performant\n\ndates.Add(startTime); // since you mentionned start and end should be included\n\nfor (var i = 1; i < totalDays; i++)\n{\n    dates.Add(startTime.AddDays(i));\n}\n\ndates.Add(endTime);	0
23376937	23349575	How to convert a IStorageItem item to a BitmapImage	else {\n    using (var stream = await item.OpenReadAsync())\n    {\n        await Images[i].SetSourceAsync(stream);\n    }\n}	0
5147535	5147327	Disabling input in C# Console until certain task is completed	while (!Done)\n{\n    while (Console.KeyAvailable) Console.ReadKey(true);\n    ConsoleKeyInfo key = Console.ReadKey(true);\n    // etc..\n}	0
24022884	24022552	Raise event from multiple worker threads?	private static readonly object Locker = new object();\nprivate bool _closing = false;\n\nprivate void YourErrorHandler(object sender, EventArgs args)\n{\n    if(!_closing)\n       lock (Locker)\n          if(!_closing)\n          {\n              _closing = true;\n              //What ever you need to do here\n          }\n}	0
3241818	3241723	Convert from byte* to byte[]	byte* source = whatever;\nint size = source[0]; // first byte is size;\nbyte[] target = new byte[size];\nfor (int i = 0; i < size; ++i)\n    target[i] = source[i+1];	0
10655557	10655379	Generate XML and HTML from MemoryStream	// This Function creates \nprotected string ConvertToHtml(MemoryStream xmlOutput)\n{\n        XPathDocument document = new XPathDocument(xmlOutput);\n        XmlDocument xDoc = new XmlDocument();\n        xDoc.Load(xmlOutput);\n\n        StringWriter writer = new StringWriter();\n        XslCompiledTransform transform = new XslCompiledTransform();\n        transform.Load(reportDir + "MyXslFile.xsl");\n        transform.Transform(xDoc, null, writer);\n\n        // These lines are the problem\n        //xmlOutput.Position = 1;\n        //StreamReader sr = new StreamReader(xmlOutput);\n        //return sr.RearToEnd();\n\n        return writer.ToString()\n}	0
6357362	6356952	Making exported excel sheet as readonly	var fileInfo = new FileInfo(FilePathName );\nfileInfo.IsReadOnly = true;	0
17315544	17315427	How to get numerical suffix from a string?	var x = "various text 1234";\nvar digits = x.Reverse().TakeWhile(c => char.IsDigit(c));\nvar number = new string(digits.Reverse().ToArray());	0
1604771	1604750	how to set bold and italics when using the outlook interop from C#	.BodyFormat = OlBodyFormat.olFormatHTML\n.HTMLBody = "<html><body><h2>The body of this message will appear in HTML." + \n            "</h2>Type the Message text here.</body></html>";	0
25541756	25541657	Shake Gesture Library in WP8	Deployment.Current.Dispatcher.BeginInvoke(\n        () =>\n        {\n            PlayButton_Click(null, null); \n        });	0
4314175	4208413	Mapping a List<string> to a delimited string with Fluent NHibernate	public class Product\n{\n    protected string _features; //this is where we'll store the pipe-delimited string\n    public List<string> Features {\n        get\n        {\n            if(string.IsNullOrEmpty(_features)\n                return new List<String>();\n            return _features.Split(new[]{"|"}, StringSplitOptions.None).ToList();\n        }\n        set\n        {\n            _features = string.Join("|",value);\n        }\n    }\n}\n\npublic class ProductMapping : ClassMap<Product>\n{\n    protected ProductMapping()\n    {\n        Map(x => x.Features).CustomType(typeof(string)).Access.CamelCaseField(Prefix.Underscore);\n    }\n}	0
6740491	6740355	How to get only the different fields	public Dictionary<string, object> GetDifferences(A target)\n{\n    Dictionary<string, object> differences = new Dictionary<string, object>();\n    foreach (PropertyInfo pi in typeof(A).GetProperties())\n    {\n        if (!pi.GetValue(this, null).Equals(pi.GetValue(target, null)))\n            differences.Add(pi.Name, pi.GetValue(target, null));\n    }\n    return differences;\n}	0
18303907	18303897	Test if all values in a list are unique	bool isUnique = theList.Distinct().Count() == theList.Count();	0
27584207	27584098	Are there ways to not recreate a connection string in a solution which references a dll with a connection string?	MySettingsFile.Default.MyConnectionString	0
13290172	13290021	How to get Unique records via LINQ	var EmpRecList = (from ur in db.Users\n                  join ug in db.UserGroups on ur.UserGroupID equals ug.UserGroupID\n                  select new\n                  {\n                      lastName = ur.LastName, \n                      userID = ur.UserID,\n                      firstName = ur.FirstName,\n                      userGroupName = ug.UserGroupNameLang1\n                   })\n                  .Where(oh => oh.userGroupName.StartsWith(userCur.UserGroupName))\n                  .GroupBy(g => g.userID).Select(s => s.First()).ToList().OrderBy(x => x.lastName)	0
21018943	21018900	Save datagridview to mysql	cmd.Parameters.Clear()	0
12527878	12527415	Group by column one, group by column two and then count column two on an EnumerableRowCollection	var result = from row in queryableData\n          group row by new { ProductName = row["Product Name"], \n                             ProductPrice = row["Product Price"] } into grp\n          select new { grp.Key.ProductName , \n                       grp.Key.ProductPrice, \n                       Count = grp.Count()  };	0
7026321	7026269	Repeater which Event to use to find a control inside the repeater	(YourClass)e.Item.FindControl("its name");	0
26262778	26262668	Add control to a panel with autoscroll (c#)	{ Top = top + this.AutoScrollPosition.Y };	0
13104885	13104783	How to add two different properties of the same class to one POCO class?	public class Xpto {\n\n    [ForeignKey("User")]\n    public string Username { get; set; }\n\n    public virtual User User { get; set; }\n\n    [ForeignKey("User2")]\n    public string Username2 { get; set; }\n\n    public virtual User User2 { get; set; }\n}	0
4159619	4159601	Strange characters in textbox after receiving via socket	textBox_received.Text = Encoding.UTF8.GetString(buffer,0,count);	0
13566106	13565812	Using Objects vs Local Variables & Parameters in .NET	public FormRespose() \n{\n     public string Name {get; set;}\n     public string FirstName { // use Name here to get first name from it, or turn uppercase, lowercase, whatever }\n}	0
13092155	13092050	Disable event handler from a method	DTURradGridView.Columns[2].ReadOnly = true;\nDTURradGridView.Columns[3].ReadOnly = true;\nDTURradGridView.Columns[4].ReadOnly = true;	0
20528167	20528019	I needed to do Bulk insert with dapper rainbow	Parallel.ForEach()	0
17279926	17279086	Windows Phone 7.8 - Finding properties of ContextMenu's parent	(((sender as MenuItem).Parent as ContextMenu).Owner as HubTile).Title	0
1606370	1606349	Can I prevent a StreamReader from locking a text file whilst it is in use?	using (var file = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\nusing (var reader = new StreamReader (file, Encoding.Unicode)) {\n}	0
24735255	24734954	How to handle whitespace in DataTrigger binding for WPF DataGrid?	Binding={Binding 'Last Value', Converter= {StaticResource DecimalToBoolConverter}}"	0
19006062	18852827	NHibernate IUserType get mapped property name	public abstract Class CodeTableBase\n{\n    public virtual int Id { get; protected set; }\n    public virtual string CodeType { get; protected set; }\n    public virtual int Value { get; protected set; }\n    public virtual string Description { get; protected set; }\n}\n\npublic class City : CodeTableBase {}\n\npublic abstract class CodeTableMap<T> : ClassMap<T> where T : CodeTableBase\n{\n    public CodeTableMap() \n    {\n        Table("CodeTable");\n        Id(x => Id, "id").your id generation strategy\n        CodeType(x => x.CodeType, "code_type");\n        Value(x => x.Value, "code_value");\n        Description(x => x.Description, "code_description");\n    }\n\n    public CodeTableMap(string codeType) : this()\n    {\n        Where("code_type = '" + codeType + '"); // may need to use property name\n    }\n}\n\npublic class CityMap : CodeTableMap<City>\n{\n    public CityMap : base("city") {}\n}	0
15867849	15867758	read only given last x lines in txt file	List <string> text = File.ReadLines("file.txt").Reverse().Take(2).ToList()	0
22000504	21995335	App Settings using Castle Dictionary Adapter - adding behavior at runtime	Configure(component => component.UsingFactoryMethod(\n                () =>\n                {\n                    var attrib = (AppSettingsFromConfigAttribute)Attribute.GetCustomAttribute(component.Implementation, typeof(AppSettingsFromConfigAttribute));\n\n                    var prop = new PropertyDescriptor();\n\n                    prop.AddBehavior(new AppSettingsBehavior(attrib.KeyPrefix));\n\n                    var meta = configFactory.GetAdapterMeta(component.Implementation);\n\n                    foreach (var entry in meta.Properties)\n                    {\n                        entry.Value.Fetch = true;\n                    }\n\n                    return meta.CreateInstance(new NameValueCollectionAdapter(ConfigurationManager.AppSettings), prop);\n                })));	0
26492353	26492338	Calling method from another method, no extension method accepting a first argument of type	List<T>	0
7769362	7769241	How to get the amount of colums from a SQL database with LinqDataSource?	var columnNames = db.ColumnNames<Orders>().Where(n => n.Member.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).FirstOrDefault() != null).Select(n => n.Name);	0
10771020	10770920	How to change a label from another class? c# windows forms visual studio	Form2 frm = new Form2(); // Form 2 contains label8 and calling in a method (i.e.buttonclick) of form1\n\nif (List<WhoLovesMe>.Count > 0)\n{\n   frm.Label8.Text = "Someone Loves Me :)";\n}\nelse\n{\n   frm.Label8.Text = "Noone Loves Me :(";\n}	0
10450325	10448186	How to add a child entity collection to an entity on its creation using datagridview selected rows	foreach (DataGridViewRow r in dgvTags.SelectedRows)\n{\n    l.Tags.Add(r.DataBoundItem as Tag);\n}	0
23870874	23870795	use task<string> method in overriden	public override string DoSomething()\n{\n    //does something...\n    base.DoSomething();\n\n    return GetName().Result;\n}	0
7962609	7962587	Unable to load image in img control in asp.net	src="Templates/Default/icons/Computer.png"	0
3539250	3539230	How to receive strings from C# in Visual-C++ based .net DLL?	static void init_1(System::String^ a, System::String^ b);	0
27931143	27930864	Using classes from other modules	public class MyType\n{\n    // Your own implementation\n    // Properties\n    // And methods\n\n    public static MyType Create(TheirEntity entity)\n    {\n        // Create an instance of your type from their object\n    }\n\n    // Or provide a conversion operator, it could be implicit if you'd like\n    public static explicit MyType(TheirEntity entity)\n    {\n         // Implement a conversion here\n    }\n}	0
8883090	8883049	How to copy an xml file and rename it and save in the same root directory using c#?	File.Copy("root.xml", "copy.xml");	0
9322764	9314036	How to stub a method returning void with ref arguments with Rhino	Interface1 interface1 = MockRepository.GenerateStub<Interface1>();\nint i = 1;\ninterface1.Stub(x => x.Method1(ref Arg<int>.Ref(Is.Anything(), i).Dummy);\nint j = 0;\ninterface1.Method1(ref j);\nif (j == 1) Console.WriteLine("OK");	0
28026037	27922509	How to get Hex String of Storage File in Windows Phone 8.1	using C1.Phone.Pdf;\nusing C1.Phone.PdfViewer;\n\nC1PdfDocument pdf = new C1PdfDocument(PaperKind.PrcEnvelopeNumber3Rotated);\npdf.Landscape = true;\n\nvar rc = new System.Windows.Rect(20,30,300,200);\npdf.DrawImage(wbitmp, rc);\n\nvar fillingName = "Test.pdf";\nvar gettingFile = IsolatedStorageFile.GetUserStoreForApplication();\n\nusing (var loadingFinalStream = gettingFile.CreateFile(fillingName))\n{\n   pdf.Save(loadingFinalStream);\n   MemoryStream leadingMemoryStream = new MemoryStream();\n   loadingFinalStream.Position = 0;\n   loadingFinalStream.CopyTo(leadingMemoryStream);\n   byte[] leadingBytes = leadingMemoryStream.ToArray();\n   lastHexString = BitConverter.ToString(leadingBytes);\n}	0
8795534	8794658	ObservableCollection<T> fires SelectionChanged event if populated in views constructor	InitializeComponent();	0
5815064	5815014	How to Bind a DataGrid to a DataTable all in code behind?	datagrid.ItemsSource = dataset.Tables[0].DefaultView;	0
24714907	24714687	Is there a way to count isolated storage files in WP8 app	IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n\nif (!settings.Contains("filesCount"))\n{\n    settings.Add("filesCount", "1");\n    //your file name is "1"\n}\nelse\n{\n   int count = int.Parse(settings["filesCount"]);\n   //name your file\n    settings["filesCount"] = (count+1).ToString()\n}\nsettings.Save();	0
30095691	30095577	c# changing background color of cell in dataGridView if its value changed	private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n{\n    if (dataGridView1.Columns[e.ColumnIndex].Name == "Version")\n    {\n        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.AliceBlue;\n    }\n}	0
6241459	6241451	Access to a private method in C#	public class MyClass\n{ \n    private int[] myInt;\n\n    public void Form2_Load(...) {\n        myInt = ...;\n    }\n\n}	0
25464740	25464493	How to print Address of a method in c#?	static void foo()\n{\n}\n\nstatic void Main(string[] args)\n{\n    Delegate fooDelegate = new Action(foo);\n\n    IntPtr p = Marshal.GetFunctionPointerForDelegate(fooDelegate);\n\n    Console.WriteLine(p);\n}	0
17862248	17842531	Reading XML Into A DataTable - System.Xml.XmlException: Root element is missing	MemoryStream memStream = new MemoryStream();\nusing (Stream s = file.PostedFile.InputStream)\n{\n     s.CopyTo(memStream);\n}	0
16599562	16599536	Removing a TextBox from the Controls collection has no effect	List<Control> toBeRemoved = new List<Control>();\nforeach (Control c in this.Controls)\n{\n    if (c instanceof TextBox)\n    {\n        toBeRemoved.Add(c);\n    }\n}\nforeach (Control c in toBeRemoved)\n{\n    this.Controls.Remove(c);\n    c.Dispose();\n}	0
3500402	3499226	OpenRasta Default Codec	ResourceSpace.Has.ResourcesOfType<object>()\n                 .WithoutUri\n                 .TranscodedBy<MyCustomCodec>()\n                 .ForMediaType("application/json");	0
8191187	8191111	LINQ for querying a DTO for a specific Name-Value pair in a generic and recursive manner	class Foo : IEnumerable<int>\n    {\n        List<int> first = new List<int>();\n        List<int> second = new List<int>();\n\n\n        public Foo()\n        {\n            first.Add( 1 );\n            first.Add( 2 );\n\n            second.Add( 11 );\n            second.Add( 12 );\n        }\n\n\n        public IEnumerator<int> GetEnumerator()\n        {\n            foreach (var f in first)\n            {\n                yield return f;\n            }\n\n            foreach (var f in second)\n            {\n                yield return f;\n            } \n        }\n    }\n\n    static void Main(string[] args)\n    {\n        Foo f = new Foo();\n\n        foreach (var d in f.Where(x => x % 2 == 0))\n        {\n            Console.WriteLine(d);\n        }\n\n\n        Console.ReadLine();\n    }	0
26047492	26047285	Split on every fourth comma in a string and count	var cnt = (thestring.Count(x => x == ',') + 1) / 4;	0
21315511	21294733	How to access .h file information from C#	public ref class OTRM_Ovd_FPGA\n{\npublic:\n    static System::String^ GetFilename() { return gcnew System::String(NiFpga_M_OTRM_OVDFPGA_Bitfile);};\n    static System::String^ GetSignature() { return gcnew System::String(NiFpga_M_OTRM_OVDFPGA_Signature);};\n\n    enum class RegisterAddress : System::UInt16\n    {\n        InitialPulseAmplitude = NiFpga_M_OTRM_OVDFPGA_IndicatorU16_ExtPulseAmplitudeDisplay,\n        CurrentPulseAmplitude = NiFpga_M_OTRM_OVDFPGA_IndicatorU16_ExtPulseAmplitudeDisplay,\n        PulseAmplitudeDecrement = NiFpga_M_OTRM_OVDFPGA_ControlU16_Decrement_Step,\n        PollPeriod = NiFpga_M_OTRM_OVDFPGA_ControlI16_Frequency_ms,\n        HvprotState = NiFpga_M_OTRM_OVDFPGA_ControlI16_HVProt,\n        PaceThreshold = NiFpga_M_OTRM_OVDFPGA_ControlI16_VVIThreshold,\n    };\n};	0
14645294	14645233	Detecting a left button mouse click Winform	public Form1()\n{\n    InitializeComponent();\n    // This line should you place in the InitializeComponent() method.\n    this.MouseClick += mouseClick;\n}	0
699594	699572	insert records in database from an xml	DataSet reportData = new DataSet();\nreportData.ReadXml(Server.MapPath(?report.xml?));\n\nSqlConnection connection = new SqlConnection(?CONNECTION STRING?);\nSqlBulkCopy sbc = new SqlBulkCopy(connection);\nsbc.DestinationTableName = ?report_table?;\n\n//if your DB col names don?t match your XML element names 100%\n//then relate the source XML elements (1st param) with the destination DB cols\nsbc.ColumnMappings.Add(?campaign?, ?campaign_id?);\nsbc.ColumnMappings.Add(?cost?, ?cost_USD?);\n\nconnection.Open();\n\n//table 4 is the main table in this dataset\nsbc.WriteToServer(reportData.Tables[4]);\nconnection.Close();	0
1037910	480872	Entity Framework: Setting a Foreign Key Property	Locker locker = new Locker();\nlocker.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", userID);\nlocker.LockerStyleReference.EntityKey = new EntityKey("entities.LockerStyle", "ID", lockerStyleID);\nlocker.NameplateReference.EntityKey = new EntityKey("entities.Nameplate", "ID", nameplateID);\nentities.AddLocker(locker);\nentities.SaveChanges();	0
15845468	15845274	How to get an angle between a direction faced and a point in 3D space	aH = Angle in the horizontal plane between the line of sight (LOS) and the object.  (angleHoriz)\n\naV = Angle in the vertical plane of the LOS.  (angleVert)\n\nd = Distance to the object in the horizontal plane.  (distance)\n\nh = Height of the object above the horizontal plane.  (height)\n\ndO = Distance from the origin to the object.\n   = sqrt( d * d + h * h )\n\noH = Horizontal offset from the LOS to the object at the base of the wall.\n   = sin( aH ) * d\n\ndH = Horizontal distance from the origin to the wall.\n   = cos( aH ) * d\n\nhLOS = Height at which the LOS intersects the wall.\n     = tan( aV ) * dH\n\ndLOS = Distance from the observer to the LOS at the wall.\n     = sqrt( dH * dH + hLOS * hLOS )\n\ndW = Distance along the wall between the line of sight and the object.\n   = sqrt( oH * oH + ( h - hLOS ) * ( h - hLOS ) )\n\nanswer = acos( ( dLOS * dLOS + dO * dO - dW * dW ) / ( 2 * dLOS * dO ) )	0
1830769	1830715	Need advice for building a search in an ASP.NET MVC application	char[] delimiterChars = { ' ', ','};\nstring[] searchterms = SearchBox.Split(delimiterChars);\n\nvar temp = _db.Books.AsQueryable();\nforeach (string term in searchterms)\n{ \n  temp = temp.Where(e => \n    (e.Title.Contains(term) || e.Author.Name.Contains(term));\n}\n\nIQueryable<SearchResult> results = temp.Select(e => new SearchResult\n{\n  Title = e.Title,\n  Type = "Book",\n  Link = "Book/" + e.BookID\n});	0
19426412	19419510	add new list into nested list	public static List<List<string>> GetAnagramEquivalents(List<string> InputArray)\n    {\n        Dictionary<string, List<string>> DictionaryList = new Dictionary<string, List<string>>();\n        List<List<string>> ReturnList = new List<List<string>>();\n        for (int x = 0; x < InputArray.Count; ++x)\n        {\n            char[] InputCharArray = InputArray[x].ToCharArray();\n            Array.Sort(InputCharArray);\n            string InputString = new string(InputCharArray);\n            if (DictionaryList.ContainsKey(InputString))\n            {\n                DictionaryList[InputString].Add(InputArray[x]);\n            }\n            else\n            {\n                DictionaryList.Add(InputString, new List<string>());\n                DictionaryList[InputString].Add(InputArray[x]);\n            }\n        }\n        foreach (var item in DictionaryList)\n        {\n            ReturnList.Add(item.Value);\n        }\n        return ReturnList;\n    }	0
25882091	25882008	Getting the application directory for File I/O in C#	StreamReader reader =\n    new StreamReader(HttpContext.Current.Server.MapPath(@"files\randomlist.txt"));	0
6758116	6757792	C# xml documentation: How to create Notes?	/// <summary><c>Increment</c> method increments the stored number by one. \n/// <note type="caution">\n/// note description here\n/// </note>\n/// </summary>	0
22916778	22916544	How to show both the bottom and the top border of a cell in iTextSharp?	Border = PdfPCell.BOTTOM_BORDER | PdfPCell.TOP_BORDER	0
273292	273081	Storing static user data in a C# windows application	if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) {\n   btnDelete.Visible = false;\n}	0
26284805	26284566	How do I select a random object when a button is clicked? C# XAML Win Store App	using System.Linq\n\n    public void SetItemSourceToRandomCard()\n    {\n        var cardsList = new List<CardsComp>();\n        cardsList.Add(card1);\n        cardsList.Add(card2);\n        cardsList.Add(card3);\n\n        var myRandomCard = PickRandom(cardsList);\n\n        listOfCardsComp.ItemsSource = new List<CardsComp> { myRandomCard };\n    }\n\n    public T PickRandom<T>(IEnumerable<T> objects)\n    {\n        var randomItemIndex = new Random().Next(objects.Count());\n        return (T)objects.ElementAt(randomItemIndex);\n    }	0
9363333	8712300	Wcf RESTful service returning xml without xml schema	var serializer = new XmlSerializer(typeof(myObject));\nvar myNamespace = new XmlSerializerNamespaces();\nvar myFile = File.Open(mypath, FileMode.OpenOrCreate);\nmyNamespace.Add("", "");\nserializer.Serialize(myFile, myObject, myNamespace);	0
14566635	14566381	How can I retreive only controls with Name property when iterating through container?	foreach (var child in this.SearchCriteriaStackPanel.Children.OfType<FrameworkElement>())\n{\n   ...\n}	0
32250942	32250754	C# Read from a Networkstream	void ReadBuffer(byte[] buffer, int offset, int count)\n{\n    int num;\n    int num2 = 0;\n    do\n    {\n        num2 += num = _stream.Read(buffer, offset + num2, count - num2);\n    }\n    while ((num > 0) && (num2 < count));\n    if (num2 != count)\n        throw new EndOfStreamException\n            (String.Format("End of stream reached with {0} bytes left to read", count - num2));\n    }	0
11098621	11083881	How to displace the origin of the Y axis on a polar Mschart?	// disable grid a long X\nchart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;\nchart1.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;\n\n// set Y axis\nchart1.ChartAreas[0].AxisY.Minimum = -20;  // creates the 'hole' by setting min Y\nchart1.ChartAreas[0].AxisY.MajorGrid.IntervalOffset = 20; // so the major grid does not fill the 'hole'\nchart1.ChartAreas[0].AxisY.MajorGrid.Interval = 5;\nchart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;	0
17646535	17646522	Most efficient way of setting a bit to 0 when 1 in another field	(110101 ^ 011001) & 011001 = 100100	0
10687481	10687438	How to let a method accept two types of data as argument?	public class FormResourceSelector<T>\n    where T : Effect\n{\n    public FormResourceSelector(Dictionary<string, T> resourceList, string type)\n    {\n    }\n}	0
15330708	15330696	How to copy List in C#	List<MyClass> copy = original.ToList();	0
7465274	7465172	Filter date in Generic List	var lower =\n    from d in dates\n    where d <= inputDate\n    orderby d descending\n    select d;\n\nvar upper =\n    from d in dates\n    where d >= inputDate\n    orderby d\n    select d;\n\nvar range = lower.Take(1)\n    .Concat(upper.Take(1))\n    .Distinct();	0
28646108	28646058	Windows Phone ListView Binding	MedSaved_ListView.ItemsSource = root.medNames;	0
29121049	29120552	How can I add .aspx inside HyperLink in DataList?	Eval("itemName", "~/{0}.aspx")	0
17297134	17296906	WCF SharedInterface definition with Async Services	[ServiceContract(Name = "IMyService", ...)]\npublic interface IMyService {\n   [OperationContract(IsOneWay=false)]\n   SecurityOperationInfo LogonUser(string sessionId, string username, string password);\n\n   // other methods ...\n}\n\n[ServiceContract(Name = "IMyService", ...)]\npublic interface IMyServiceAsync : IMyService {\n    [OperationContract(IsOneWay = false, AsyncPattern = true)]\n    IAsyncResult BeginLogonUser(string sessionId, string username, string password, AsyncCallback callback, object state);        \n    SecurityOperationInfo EndLogonUser(IAsyncResult result);\n}	0
4382522	4379785	How to defer data querying in Silverlight ViewModel class?	private DelegateCommand UpdateData1Command { get; set; }\n\n    public MyViewModel()\n    {\n        this.UpdateData1Command = new DelegateCommand(_ => this.GetData1(), _ => this.IsGraph1Visible);\n    }\n\n    private bool isGraph1Visible;\n\n    public bool IsGraph1Visible\n    {\n        get { return isGraph1Visible; }\n        set\n        {\n            isGraph1Visible = value;\n            OnPropertyChanged("IsGraph1Visible");\n\n            if(UpdateData1Command.CanExecute(null))\n                UpdateData1Command.Execute(null);\n        }\n    }\n\n    private void RunQueries()\n    {\n        if (UpdateData1Command.CanExecute(null))\n            UpdateData1Command.Execute(null);\n    }\n\n    private void GetData1()\n    {\n        // call wcf service to get the data\n    }	0
2587408	2547788	Subcontrols not visible in custom control derived from another control	InitializeComponent()	0
9790045	9789963	Regular expression to extract items from a string	var matches = Regex.Matches("KRIC-KLAX - IAD / I69", @"(\w+)");	0
25987685	25987445	Installed InputSimulator via NuGet, no members accessible	InputSimulator s = new InputSimulator();\n  s.Keyboard.TextEntry("Hello sim !");	0
7685446	7675983	Is it possible to order data in a datatable by a related datatable in the dataset?	DataTable source = ds.Tables["source"];\n            DataTable chart = ds.Tables["chart"];\n\n            var joinedTable =\n                from s in source.AsEnumerable()\n                join c in chart.AsEnumerable()\n                on s.Field<Int64>("intRowId") equals\n                    c.Field<Int64>("intItemId")\n                select new\n                {\n                    intRowId = s.Field<Int64>("intRowID"),\n                    strTitle = s.Field<string>("strTitle"),\n                    intWeight = c.Field<Int64>("intWeight")\n                };\n\n            var sortedTable = from j in joinedTable\n                              orderby j.intWeight descending\n                              select j;	0
26238	26233	Fastest C# Code to Download a Web Page	public static void DownloadFile(string remoteFilename, string localFilename)\n{\n    WebClient client = new WebClient();\n    client.DownloadFile(remoteFilename, localFilename);\n}	0
25222635	25222547	How to come back to parent form without creating new instance of parent class in C# windows application	//Click event of your button.\nprivate void goToSecondForm_Click(object sender, EventArgs e)\n{\n   this.Hide(); //Hides the parent form.\n   subform.ShowDialog(); //Shows the sub form.\n   this.Show(); //Shows the parent form again, after closing the sub form.\n}	0
15132014	15131736	Passing data from selected item to viewmodel in WinRT	SelectedItem={Binding MyProperty, Mode=TwoWay}	0
24527274	24515032	How to swap selected datagridview row	private void btnUrediStavku_Click(object sender, EventArgs e)\n{\n   if (dgvNoveStavke.SelectedRows.Count > 0)\n   {\n       dgvNoveStavke.SelectedCells[0].Value = txtIdStavke.Text;\n       dgvNoveStavke.SelectedCells[1].Value = txtIzabranaStavka.Text;\n       dgvNoveStavke.SelectedCells[2].Value = txtKolicina.Text;\n       dgvNoveStavke.SelectedCells[3].Value = txtPopust.Text;\n   }      \n}	0
18108005	18107937	Call method every time a controller method is ending	protected override void OnActionExecuted(ActionExecutedContext filterContext)\n{\n    //Do your stuff\n    base.OnActionExecuted(filterContext);\n}	0
704864	704743	Getting the Type of a ContextBoundObject when intercepting a method call	public IMessage SyncProcessMessage(IMessage msg)\n{\n      Type type = Type.GetType(msg.Properties["__TypeName"].ToString());\n\n      object[] custom = type.GetMethod("Method").GetCustomAttributes(false);\n      TimeoutAttribute ta = custom[0] as TimeoutAttribute;\n      int time = ta.Ticks;\n\n      IMessage returnedMessage = _nextSink.SyncProcessMessage(msg);\n      return returnedMessage;\n}	0
27864374	27864143	How to do multiple select sum sub-queries	Select\n    BoatName,  \n    Sum(Case When Day = 1 Then tblScores.Points Else 0 End) AS [Day1],\n    Sum(Case When Day = 2 Then tblScores.Points Else 0 End) AS [Day2],\n    Sum(Case When Day = 3 Then tblScores.Points Else 0 End) AS [Day3],\n    Sum(Case When Day = 4 Then tblScores.Points Else 0 End) AS [Day4],\n    Sum(Case When Day = 5 Then tblScores.Points Else 0 End) AS [Day5],\n    Sum(tblScores.Points) As Total\nFrom tblScores \nINNER JOIN tblAnglers ON tblScores.Fk_AnglerID=tblAnglers.Pk_AnglerID\nINNER JOIN tblBoats ON tblAnglers.Fk_BoatID=tblBoats.Pk_BoatID\nGROUP BY BoatName\nOrder By BoatName	0
15154260	15154110	Remove item from List and get the item simultaneously	public static class Extensions\n{\n    public static T RemoveAndGet<T>(this IList<T> list, int index)\n    {\n        lock(list)\n        {\n            T value = list[index];\n            list.RemoveAt(index);\n            return value;\n        }\n    }\n}	0
25779830	19152357	Not able to make my web app logout of ADFS	public void LogOut()\n    {          \n        var module = FederatedAuthentication.WSFederationAuthenticationModule;\n        module.SignOut(false);\n        var request = new SignOutRequestMessage(new Uri(module.Issuer), module.Realm);\n        Response.Redirect(request.WriteQueryString());\n    }	0
3323157	3323145	convert from EST/EDT to GMT	TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");\nDateTime someDateTimeInUtc = TimeZoneInfo.ConvertTimeToUtc(someDateTime, est);	0
29680058	29679973	Code behind Data Context is null, even though its values are showing on the page - Windows Phone 8.1	public MyUserControl1()\n        {\n            this.InitializeComponent();\n            DataContextChanged += OnDataContextChanged;\n        }\n\n        private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)\n        {\n            if (this.DataContext != null)\n            {\n               bar = (Bar)DataContext;\n               this.DoSomething((bar);\n            }\n        }	0
8353417	8353306	How to pass anonymous type to method as a parameter?	public class Program\n{\n    private static void Thing(dynamic other)\n    {\n        Console.WriteLine(other.TheThing);\n    }\n\n    private static void Main()\n    {\n        var things = new { TheThing = "Worked!" };\n        Thing(things);\n    }\n}	0
20203509	20200873	partial constructor to remove initialization from getter	public List<Contact> FilterContacts(Contact con)\n{\n    var copy = new List<Contact>();\n    foreach (Contact cn in Contacts)\n    {\n        if (cn.number == con.number)\n            copy.add(cn);\n        else\n            if (cn.name == con.name)\n                copy.add(cn);\n    }\n    return copy;\n}	0
26274894	26272974	Set value of property with private accessor	var dateTimeType = typeof (DateTime);\nMethodInfo[] privateMthods = dateTimeType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);\nprivateMthods.ToList().ForEach(a=> Console.WriteLine(a.Name.ToString()));	0
7858515	7858132	Stop raising of create event for Filewatcher control for automatic generated temporary file of Original content	FileAttributes attr = System.IO.File.GetAttributes(e.FullPath);\n\nFileInfo fi = new FileInfo(e.FullPath);     \n\nif ((attr & FileAttributes.Hidden) == FileAttributes.Hidden || fi.Extension == ".tmp")\n{\n     return;\n}	0
27077291	27072627	ILNumerics equivalent of MatLab/Octave statement	x[isnan(x)] = 0;	0
10229798	10229219	loading a text file for quick access C# windows form app	count(*) .. group by Name	0
13897367	13893312	How stop a model animation on XNA?	if (!key.IsKeyDown(Keys.W) && !key.IsKeyDown(Keys.A) && !key.IsKeyDown(Keys.D) && !key.IsKeyDown(Keys.S))\n{\n             //Stop animation for player walking\n             animationPlayer.Update(new TimeSpan(0, 0, 0), true, Matrix.Identity);\n}\nelse\n{\n             //Continue the animation \n             animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);\n}	0
8348552	8348444	How do you parse a decimal string like .09?	Dim l = Decimal.Parse(".765")	0
8590275	8590231	click event of a button that contains more buttons, fires events wrong	private void b1_Click(object sender, RoutedEventArgs e)\n{\n    e.Handled = true;\n}	0
33878178	33877795	How to know if a user can read and list files of a directory	using System.IO;\nusing System.Security.AccessControl;\npublic static FileSystemRights GetDirectoryPermissions(string user, string domainName, string folderPath)\n{\n    if (!Directory.Exists(folderPath))\n    {\n        return (0);\n    }\n\n    string identityReference = ((domainName + @"\" + user) as string).ToLower();\n    DirectorySecurity dirSecurity = Directory.GetAccessControl(folderPath, AccessControlSections.Access);\n    foreach (FileSystemAccessRule fsRule in dirSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))\n    {\n        if (fsRule.IdentityReference.Value.ToLower() == identityReference)\n        {\n            return (fsRule.FileSystemRights);\n        }\n    }\n    return (0);\n}	0
2222741	2222718	C# delete a folder and all files and folders within that folder	dir.Delete(true); // true => recursive delete	0
20963769	20963648	How to reference the current user logged in MVC 4 EF	using Microsoft.AspNet.Identity;\n\n...\n\nUser.Identity.Name\nUser.Identity.IsAuthenticated	0
3326286	3326201	Padding (left, right, top, bottom) in WPF	Padding="3, 10, 30, 10"	0
30357114	30344083	NewMeRequest in the Facebook Android API in C#	Request.NewMeRequest (currentSession, this).ExecuteAsync ();	0
34004194	34000408	Null Reference Exception being thrown when using a data template selector in a user control WPF	public CouponViewerViewModel()\n    {\n\n        if (DesignerProperties.IsInDesignMode == true)\n        {\n            return;\n        }\n        if (DesignerProperties.IsInDesignMode)\n        {\n            LoadDesignTimeData();\n        }\n\n    }	0
23656225	23656051	Remove entries from list of a generic list	_interestlist.ForEach(i => i.interests.RemoveAll(x => x.id == "1234"));	0
28089697	28089066	Copying a smaller array into a larger one	map [10, 10] = roomDoors [0, 0];	0
5760286	5752314	How to save a SQL "Select" result in a variable in C#	using (OdbcConnection connection = SomeMethodReturningConnection())\nusing (OdbcCommand command = SomeMethodReturningCommand())\n{\n    command.Parameters.Add(new OdbcParameter("@username", username.Text));\n    command.CommandText = "Select Count(*) From Users where Username = ?";\n    connection.Open();\n    int output = (int)command.ExecuteScalar();\n\n    if (output > 0)\n    {\n        // username already exists, provide appropriate action\n    }\n    else\n    {\n        // perform insert \n        // note: @username parameter already exists, do not need to add again\n        command.Parameters.Add(new OdbcParameter("@password", password.Text));\n        command.CommandText = "Insert Into Users (Username, Password) Values (?,?)**";\n        command.ExecuteNonQuery();\n    }\n}	0
22355400	22340905	Disabling mouse Input to a GameObject	this.gameObject.layer = LayerMask.NameToLayer("Ignore Raycast");	0
3399518	3399475	MySQL with C#, from a PHP Developer's Standpoint	DataTable results = new DataTable();\n\nusing(MySqlConnection conn = new MySqlConnection(connString))\n{\n    using(MySqlCommand command = new MySqlCommand(sqlQuery, conn))\n    {\n        MySqlDataAdapter adapter = new MySqlDataAdapter(command);\n        conn.Open();\n        adapter.Fill(results);\n    }\n}\n\nsomeDataGrid.DataSource = results;\nsomeDataGrid.DataBind();	0
5327552	5327475	Using Any LINQ function to set model property	selected = (userselections.Select(t => t.PlayerID).ToList().Contains(x.id) == true)	0
30711506	30711331	Not displaying content by its URL string - absolute urls	var uri = HttpContext.Current.Request.Url.AbsoluteUri;\nvar parts = uri.Split('/');\n\nif (parts.Length < 6)\n{\n    // doesn't contain 3rd level\n    // html here\n}	0
27420287	27420088	Take groups of 5 strings from List	List<List<string>> groupsOf5 = list\n    .Select((str, index) => new { str, index })\n    .GroupBy(x => x.index / 5)\n    .Select(g => g.Select(x => x.str).ToList())\n    .ToList();	0
16749691	16749631	Check if two variables are of the same when the type is dynamic and both variables are the derivatives of same base class	Type targetType = pObject.GetType();\nif (SomeList.Any(o => targetType.Equals(o.GetType()))) {\n    ...\n}	0
29526995	29526929	Web Browser in c# not displaying up to date css information	webBrowser.Refresh(WebBrowserRefreshOption.Completely)	0
6748341	6713389	Fluent NHibernate Mapping Left Join	public abstract class Tier\n{\n    public abstract void DoSomething();\n}\n\nclass TierMap : ClassMap<Tier>\n{\n    public TierMap()\n    {\n        DiscriminateSubClassesOnColumn("TierName");\n    }\n}\n\npublic class LessThan100K : Tier\n{\n    public override void DoSomething()\n    {\n        // Do something useful\n    }\n}\n\nclass LessThan100KMap : SubclassMap<LessThan100K>\n{\n    public LessThan100KMap()\n    {\n        DiscriminatorValue("<$100K");\n    }\n}	0
23771100	23771045	WPF C# Opening files in multiple directories	string startLocationForDialog1 = "C:\";\nstring startLocationForDialog2 = "C:\";\nstring startLocationForDialog3 = "C:\";	0
27417936	27417263	What to Use to Pick Multiple files (Media files) and retrieve them in a StorageFile collection at custom/desired index?	List<StorageFile> fileList; // don't forget to initialize this somewhere!\nprivate async void addmusicbtn_Click(object sender, RoutedEventArgs e)\n{\n        var fop = new FileOpenPicker();\n        fop.FileTypeFilter.Add(".mp3");\n        fop.FileTypeFilter.Add(".mp4");\n        fop.FileTypeFilter.Add(".avi");\n        fop.FileTypeFilter.Add(".wmv");\n        fop.ViewMode = PickerViewMode.List;\n\n        IReadOnlyList<StorageFile> pickedFileList;\n\n        pickedFileList= await fop.PickMultipleFilesAsync();\n        // add the picked files to our existing list\n        fileList.AddRange(pickedFileList);\n\n        // I'm not sure if you want fileList or pickedFileList here:\n        foreach (StorageFile file in fileList)\n        {\n            mlist.Items.Add(file.Name);\n            stream = await file.OpenAsync(FileAccessMode.Read);\n            mediafile.SetSource(stream, file.ContentType);\n        }\n        mediafile.Play();\n\n}	0
17481017	17480990	Get name of generic class without tilde	string typeName = typeof(T).Name;\nif (typeName.Contains('`')) typeName = typeName.Substring(0, typeName.IndexOf("`"));	0
33427211	33427189	C# Global Variables for Instances of a class	private CreateAccountController ctr;\npublic void loadCreateAccountCtr()\n{\n    // Create Controller\n    ctr = new CreateAccountController();\n    // Start Controller\n    ctr.start();\n    // Session is active\n}\n\npublic void checkCredentials(string appNum)\n{\n    if (ctr != null)\n    {\n        ctr.create();\n    }\n    else\n    {\n        //handle this case here\n    }\n}	0
26899545	26899489	Using a windows forms timer to trigger a method from in a different class	namespace MyApplication\n{\n    public partial class MainPage : Form\n    {\n        public MainPage()\n        {\n            InitializeComponent();\n        }\n\n        public static void SetTextBox(string Message)\n        {\n            Textbox_Status.Text = Message;\n        }\n\n        private void timer1_Tick(object sender, EventArgs e)\n        {\n            string result = Device.DeviceCheck();\n            SetTextBox(result);\n        }\n    }\n\n    public class Device : MainPage\n    {\n        public string DeviceCheck()\n        { \n            //Do other stuff here\n            return("Some text");\n        }\n    }\n}	0
10593986	10593239	Using asp.net mvc3, how do I display data in a different format to how it's stored in the database?	class MyTimeField \n{\n    public int Hours { get; set; }\n    public int Minutes { get; set; }\n\n    public MyTimeField(String timeString)\n    {\n        var stringParts = timeString.Split(":");\n        if(stringParts.length != 2) throw ArgumentException();\n        Hours = Int32.Parse(stringParts[0]);\n        Minutes = Int32.Parse(stringParts[1]);\n    }\n\n    public override String ToString()\n    {\n        return Hours + ":" + Minutes;\n    }\n}	0
7393686	7393663	Get a file through Response without giving it an extension	Response.ContentType = "application/unknown";	0
6518922	6512446	NHibernate get next Birthdays	var result =\nsession.CreateQuery(@"from Person \n                      where 1 = (FLOOR(DATEDIFF(dd,Birthday,GETDATE()+10) / 365.25))\n                                    -\n                                (FLOOR(DATEDIFF(dd,Birthday,GETDATE()-5) / 365.25))")\n       .List<Person>();	0
15496319	15479615	Serialization of objects (created with xsd containing complextypes) returns complextype as element	[XmlElement("Example2")]\n        public List<Example2Type> Example2\n        {\n            get\n            {\n                return this.example2Field;\n            }\n            set\n            {\n                this.example2Field = value;\n            }\n        }	0
7161538	7158849	Rendering a partial view from viewbag in c# mvc 3	public ActionResult Index()\n{\n\n    var form = pa.Index(); // <-- This is the controller from controller A\n\n    using (var sw = new StringWriter())\n    {\n        // Find the actual partial view.\n        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, form.ViewName);\n        // Build a view context.\n        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);\n        // Render the view.\n        viewResult.View.Render(viewContext, sw);\n        // Get the string rendered.\n        ViewBag.CMSForm = sw.GetStringBuilder().ToString();\n    }\n\n    return View();\n}	0
21654398	21618817	AccessViolationException from WebBrowser control with custom IDownloadManager	[DllImport("urlmon.dll"), PreserveSig]\n[return: MarshalAs(UnmanagedType.Error)]\nstatic extern int CoInternetSetFeatureEnabled(int FeatureEntry, [In, MarshalAs(UnmanagedType.U4)]uint dwFlags, bool fEnable);\n\nCoInternetSetFeatureEnabled(ComInteropConstants.FEATURE_MIME_HANDLING, (uint)ComInteropConstants.SET_FEATURE_ON_PROCESS, true);\nCoInternetSetFeatureEnabled(ComInteropConstants.FEATURE_MIME_SNIFFING, (uint)ComInteropConstants.SET_FEATURE_ON_PROCESS, true);	0
26192658	26192380	Getting the UserName of an ApplicationUser into a view	public ActionResult Index()\n{\n     return View(db.Questions.Include(q => q.ApplicationUser).ToList());\n}	0
1101323	1101294	Can a method be overriden with a lambda function	class MyClass {  \n    public MyClass(Action<int> myMethod)\n    {\n        this.MyMethod = myMethod ?? x => { };\n    }\n\n    public readonly Action<int> MyMethod;\n}	0
10387428	10387299	How to enable Remote Desktop Connection Pro-grammatically?	try\n        {\n            RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, TargetMachine.Name);\n            key = key.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server", true);\n            object val = key.GetValue("fDenyTSConnections");\n            bool state = (int)val != 0;\n            if (state)\n            {\n                key.SetValue("fDenyTSConnections", 0, RegistryValueKind.DWord);\n                MessageBox.Show("Remote Desktop is now ENABLED");\n            }\n            else\n            {\n                key.SetValue("fDenyTSConnections", 1, RegistryValueKind.DWord);\n                MessageBox.Show("Remote Desktop is now DISABLED");\n            }\n            key.Flush();\n            if (key != null)\n                key.Close();\n        }\n        catch\n        {\n            MessageBox.Show("Error toggling Remote Desktop permissions");\n        }	0
28422022	28419463	How do I just get a list of JSON objects from RestSharp?	var serializer = new RestSharp.Deserializers.JsonDeserializer();\nvar list = serializer.Deserialize<List<Dictionary<string, string>>>(json).SelectMany(d => d.Values).ToList();	0
17168957	17168851	If statement in repeaters ItemTemplate	protected void OnCheckboxListItemBound(Object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n        HtmlTableRow itemRow = (HtmlTableRow) e.Item.FindControl("itemRow");\n        itemRow.Visible = e.Item.ItemIndex % 2 == 0;\n    }\n}	0
12656279	12656172	Windows 8 - How To Change Live Tile Background Image?	XmlNodeList tileImageAttributes = tileXml.GetElementsByTagName("image");\n((XmlElement)tileImageAttributes[0]).SetAttribute("src", "ms-appx:///images/redWide.png");\n((XmlElement)tileImageAttributes[0]).SetAttribute("alt", "red graphic");	0
11326795	11326633	How to make BalloonPopupExtender appears and disappears with Tab key from the keyboard?	DisplayOnFocus="true"	0
31040855	31016872	How can I quickly distribute files equally across multiple partitions / servers?	public List<SourceFile>[] Distribute(List<SourceFile> files, int partitionCount)\n{\n    List<SourceFile> sourceFilesSorted =\n        files\n            .OrderByDescending(sf => sf.Size)\n            .ToList();\n\n    List<SourceFile>[] groups =\n        Enumerable\n            .Range(0, partitionCount)\n            .Select(l => new List<SourceFile>())\n            .ToArray();\n\n    foreach (var f in files)\n    {\n        groups\n            .Select(grp => new { grp, size = grp.Sum(x => x.Size) })\n            .OrderBy(grp => grp.size)\n            .First()\n            .grp\n            .Add(f);\n    }\n\n    return groups;\n}	0
5117585	5117308	Problem with serializing a dictionary wrapper	[XmlArray(ElementName = "Translations")]\npublic Translation[] TranslationArray\n{\n    get\n    {\n        return TranslationsList.ToArray();\n    }\n\n    set\n    {\n        TranslationsList = new List<Translation>(value);\n    }\n}\n\n[XmlIgnore]\npublic List<Translation> TranslationsList\n....	0
2977496	2977413	LINQ Numerical Grouping	var values = new []{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\ngroups = values.Select((v, i) => new { index = i, value = v })\n    .GroupBy(k => k.index / n, e => e.value);	0
8913132	8912613	BinarySearch limits for numbers within range	var numbers = new[] { 1, 4, 8, 9, 16, 25, 27, 32 };\n\nvar lowerBound = 4;\nvar upperBound = 17;\n\nint lowerIndex = Array.BinarySearch(numbers, lowerBound);\nif (lowerIndex < 0) lowerIndex = ~lowerIndex;\n\n// - 1 here because we want the index of the item that is <= upper bound.\nint upperIndex = Array.BinarySearch(numbers, upperBound);\nif (upperIndex < 0) upperIndex = ~upperIndex - 1;\n\nreturn (upperIndex - lowerIndex) + 1;	0
10488278	10488245	How can I convert a number's digits into ASCII bytes?	System.Text.Encoding.ASCIIEncoding.GetBytes(x.ToString());	0
18569754	18569721	Find duplicate in a list from a reference list	bool hasRef = listref.Any(r => listA.Count(a => a == r) > 1);	0
130641	130617	How do you check for permissions to write to a directory or file?	public void ExportToFile(string filename)\n{\n    var permissionSet = new PermissionSet(PermissionState.None);    \n    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);\n    permissionSet.AddPermission(writePermission);\n\n    if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))\n    {\n        using (FileStream fstream = new FileStream(filename, FileMode.Create))\n        using (TextWriter writer = new StreamWriter(fstream))\n        {\n            // try catch block for write permissions \n            writer.WriteLine("sometext");\n\n\n        }\n    }\n    else\n    {\n        //perform some recovery action here\n    }\n\n}	0
24867019	24866300	Multi child in MDI	(children[CHOSEN_CHILD] as Excel_form).Odebrane(odebrane, ktory_form_pyta);	0
33800825	33799321	Display a list of objects and return values to view	return View(chmdls);	0
26070748	26070558	How to insert a bulleted list from a text box?	string[] unbulleted = textBox1.Lines;\nstring[] bulleted = new string[unbulleted.Length];\nfor (int i = 0; i < bulleted.Length; i++)\n    bulleted[i] = "\u2022" + unbulleted[i];	0
3592525	3588739	How do I load a text grammar in a SAPI 5.4 C# program?	SpSharedRecoContext reco = new SpSharedRecoContext();\nISpeechRecoGrammar grammar;\ngrammar = reco.CreateGrammar();\ngrammar.CmdLoadFromFile("sol.xml");\ngrammar.CmdSetRuleIdState(0, SpeechRuleState.SGDSActive);	0
22126642	22126528	How to create a right click event handler in c#	public Form1()\n    {\n        InitializeComponent();\n\n        //Create right click menu..\n        ContextMenuStrip s = new ContextMenuStrip();\n\n        // add one right click menu item named as hello           \n        ToolStripMenuItem hello = new ToolStripMenuItem();\n        hello.Text = "Hello";\n\n        // add the clickevent of hello item\n        hello.Click += hello_Click;\n\n        // add the item in right click menu\n        s.Items.Add(hello);\n\n        // attach the right click menu with form\n        this.ContextMenuStrip = s;\n    }\n\n    void hello_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show("Hello Clicked");\n    }	0
32178897	32178756	How to use a method with an out parameter in a lambda expression	IEnumerable<ID> ids = names.Select\n(\n    name =>\n    {\n        ID id;\n        GetName(name, out id);\n\n        return id;\n    }\n);	0
14547678	14539688	how to sort mapreduce results?	var results = collection.MapReduce(wordMap, wordReduce, options);\n            IEnumerable<BsonDocument> resultList = results.GetResults();\n            List<BsonDocument> orderedList = resultList.ToList().OrderByDescending(x => x[1]).ToList();	0
33794119	33794019	Extract and validate a date from a CSV value	string format = "d-MMM-yyyy";	0
26431953	26431875	Replacing double quotes with html quote tags for a given string in C#	var str = "This string \"contains\" double \"aaaaa\"quotes."; \n\nvar str2 = Regex.Replace(str,@"""(.+?)""", m => "<b>" + m.Groups[1].Value + "</b>");	0
23063097	23063020	Put an array in to a column	public class Task\n{\n    [Ignore]\n    public string[] Attempts { get; set; }\n\n    public string AttemptsMetadata\n    {\n        get\n        {\n            return Attempts != null && Attempts.Any()\n                ? Attempts.Aggregate((ac, i) => ";" + ac + i).Substring(1)\n                : null;\n        }\n        set { Attempts = value.Split(';'); }\n    }\n}	0
22642092	22639114	How to force release of mouse capture while moving a form in C#?	public static class User32_DLL\n{\n    [DllImportAttribute("user32.dll")]\n    public static extern bool ReleaseCapture();\n}\n\n\npublic partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        this.SetStyle(ControlStyles.EnableNotifyMessage, true);\n    }\n\n\n    protected override void OnNotifyMessage(Message m)\n    {\n        const int WM_MOVING = 0x0216;\n\n        if (m.Msg == WM_MOVING)\n        {\n            if (Control.ModifierKeys == Keys.Control)\n            {\n                User32_DLL.ReleaseCapture();\n            }\n        }\n        base.OnNotifyMessage(m);\n    }\n\n}	0
2957329	2957311	C#:Saving image to folder	IO.Path.Combine	0
32335377	32335228	How can i auto search from multiple column in my datagridview?	dv.RowFilter = string.Format("Title LIKE '%{0}%' OR AUTHOR LIKE '%{0}%' OR Name LIKE '%{0}%'", txtsearch.Text);	0
2088137	2087947	Using scope_identity() with ASP.NET controls	//Read the value of the @Identity OUTPUT parameter\nint lastID = e.Command.Parameters["@Identity"].Value;\n...	0
10094280	10094197	WPF window throws TypeInitializationException at start up	Environment.SetEnvironmentVariable("windir", Environment.GetEnvironmentVariable("SystemRoot"));	0
18744548	18743741	CRC 16 for DECT in C#	if (BitString[i] == '1')\n    DoInvert = true ^ CRC[15];\nelse\n    DoInvert = false ^ CRC[15];	0
23937005	23936900	Order a list based on a fixed format	var c = ListB.Count();\nListB = ListB\n    .OrderBy(id => OrderedListToFollow.Contains(id)\n        ? OrderedListToFollow.ToList().IndexOf(id)\n        : c + 1    // This will always pace invalid objects at the end\n    );	0
11324811	11324718	Min Date and Max date	nameList.Max()	0
2959232	2958767	Label displaying Timespan disappearing in XP but not in newer Windows versions	private static string HMS(TimeSpan tms) {\n        return new DateTime(tms.Ticks).ToString("H:mm:ss");\n    }	0
31437787	31437739	Creating Login Page Using C#/SQL Window Application .	string query = "select * from [User] where User_Name = '" + textBox1.Text + "'and User_Password = '" + this.textBox2.Text + "'";	0
24954314	24954226	Append rich formatted text from 2 RichTextboxes into another RichTextBox in C#	richTextBox3.Rtf = richTextBox1.Rtf\nrichTextBox3.Select(richTextBox3.TextLength, 0);\nrichTextBox3.SelectedRtf = richTextBox2.Rtf;	0
29434328	29433861	How to update excel file data using row and column in C# using OleDbConnection	using (OleDbConnection cn = new OleDbConnection(connectionString))\n        {\n            cn.Open();\n            using (OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [MySheet$] (COLUMN1, COLUMN2) VALUES ('Count', 1);", cn))\n            {\n                cmd1.ExecuteNonQuery();\n            }\n\n            using (OleDbCommand cmd1 = new OleDbCommand("UPDATE [MySheet$] SET COLUMN2 = 5 WHERE ID = 1", cn))\n            {\n                cmd1.ExecuteNonQuery();\n            }\n        }	0
32463337	32461586	Drawing a box with meshes in AutoCAD (C#)	PolygonMesh acPolyMesh = new PolygonMesh();\nacPolyMesh.MSize = 2;\nacPolyMesh.NSize = 4;	0
19137941	19137268	How to find that a text file contains a specific paragraph in c#.net	/// <summary>\n    /// Finds the text files that contain paragraph.\n    /// </summary>\n    /// <param name="paragraph">The paragraph to check for.</param>\n    /// <param name="textFilePaths">A list of paths to text files to check.</param>\n    /// <returns></returns>\n    List<string> FindFilesWithParagraph(string paragraph, List<string> textFilePaths)\n    {\n        List<string> foundPaths = new List<string>(); // list of paths to text files w/ paragraph\n\n        foreach (string path in textFilePaths) // iterate through each file\n        {\n            if (!File.Exists(path)) // check files actually exist\n                throw new ArgumentException();\n\n            using (var sr = new System.IO.StreamReader(path))\n            {\n                if (sr.ReadToEnd().Contains(paragraph)) // read contents of file\n                    foundPaths.Add(path); // and add it to list if it contains the paragraph\n            }\n        }\n\n        return foundPaths;\n    }	0
18474654	18473945	Fade in/out programmatically a Circle in a Windows Store Application	var storyboard = new Storyboard();\n\nvar timeline = new DoubleAnimationUsingKeyFrames\n{\n    KeyFrames = new DoubleKeyFrameCollection\n    {\n        new EasingDoubleKeyFrame(0),\n        new EasingDoubleKeyFrame(1, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 4)))\n    }\n};\nstoryboard.BeginAnimation(OpacityProperty, timeline);	0
25047111	25047041	Move controls between multiple containers in a single form	Control.SaveToBitmap	0
17646164	17646110	Serialize object into string	Class1 example = new Class1();\nIFormatter formatter = new BinaryFormatter();\nusing (MemoryStream ms = new MemoryStream())\n{\n   formatter.Serialize(ms, example);\n\n   ms.Position = 0;\n   StreamReader sr = new StreamReader(ms);\n   String text = sr.ReadToEnd();\n\n   server.Send(text);\n}	0
33399239	33397094	Programmatically Set Data Binding in WPF for Dynamic TextBoxes from a Dynamic ComboBox	ComboBox companyComboBox = new ComboBox();\ncompanyComboBox.ItemsSource = Rails.DefaultView;  // Rails being DataTable\ncompanyComboBox.IsEditable = true;\ncompanyComboBox.IsTextSearchEnabled = true;\ncompanyComboBox.DisplayMemberPath = "rr_code";\n\nBinding b = new Binding("SelectedItem.rr_addr");  // The selected item's 'rr_addr' column ...\nb.Source = companyComboBox;                       // ... of the companyComboBox ...\n\nTextBox streetTextBox = new TextBox();    \nstreetTextBox.SetBinding(TextBox.TextProperty,b); // ... is bound to streetTextBox's Text property.	0
17821823	17816335	Assert statement to compare two files for equality	public string GetFileHash(string filename)\n{\n    var hash = new SHA1Managed();\n    var clearBytes = File.ReadAllBytes(filename);\n    var hashedBytes = hash.ComputeHash(clearBytes);\n    return ConvertBytesToHex(hashedBytes);\n}\n\npublic string ConvertBytesToHex(byte[] bytes)\n{\n    var sb = new StringBuilder();\n\n    for(var i=0; i<bytes.Length; i++)\n    {\n        sb.Append(bytes[i].ToString("x"));\n    }\n    return sb.ToString();\n}\n\n[Test]\npublic void CompareTwoFiles()\n{\n    const string originalFile = @"path_to_file";\n    const string copiedFile = @"path_to_file";\n\n    var originalHash = GetFileHash(originalFile);\n    var copiedHash = GetFileHash(copiedFile);\n\n    Assert.AreEqual(copiedHash, originalHash);\n}	0
4766139	4766059	Inheritance problem. How to create multiple instances of a base class?	public class PrinterState\n{\n     public Boolean IsPaperTrayEmpty { get; set; }\n     public Int32 CartridgeLevel { get; set; }\n}\n\npublic class ColorPrintProvider\n{\n     public PrinterState CurrentState { get; private set; }\n\n     private void UpdateCurrentState()\n     {\n         // update the current state\n         // based on / after some events like RequestForPrint, PrintCompleted...\n     }\n}	0
15950788	15950477	how i can insert an image in web browser control in c# with out open image ui?	private void Form1_Load_1(object sender, EventArgs e)\n    {\n        webBrowser1.DocumentText = "<html><body></img></body></html>";\n    }\n\n    private void insert_image_btn_Click(object sender, EventArgs e)\n    {\n        HtmlElement userimage = webBrowser1.Document.CreateElement("img");\n        userimage.SetAttribute("src", "image location");\n        userimage.Id = "imageid";\n        webBrowser1.Document.Body.AppendChild(userimage);\n    }\n    private void btn_set_aliign_Click(object sender, EventArgs e)\n    {\n        webBrowser1.Document.GetElementById("imageid").SetAttribute("float", "right");\n    }	0
26607118	26605493	XDocument or XmlDocument to JSON with C#	JsonConvert.SerializeXNode(x, Formatting.None, true);	0
6019513	6019480	Constructor Initialization of Properties in C#	public Brand { get; set; }	0
21339893	21339822	trapping a key before it gets to the Console	Console.ReadKey(true)	0
9530597	9528538	How can i check the panel status	if(PanelName.Enabled)	0
6742137	6304773	How to get X509Certificate from certificate store and generate xml signature data?	static void Main(string[] args)\n    {\n        X509Certificate2 cer = new X509Certificate2();\n        cer.Import(@"D:\l.cer");\n        X509Store store = new X509Store(StoreLocation.CurrentUser);\n        store.Certificates.Add(cer);\n\n         X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, "My Cert's Subject Name", false);\n        if (cers.Count>0)\n        {\n            cer = cers[0];\n        };\n        store.Close();\n    }	0
20216240	20215605	Xml search for a specific node and add child node c#	var user = document.SelectSingleNode("/Bruger/Spejder[Navn/text() = '" + label15.Text + "']")\nif (null != user)\n{\n   var register = document.CreateElement("tilmeld");\n   register.InnerText = "new child";\n   user.AppendChild(register);\n}	0
17689610	17689449	Pulling required data using XPath but getting null value	XmlNamespaceManager nsmgr = new XmlNamespaceManager(rateQuote3);\n     nsmgr.AddNamespace("rq", "http://ratequote.usfnet.usfc.com/v2/x1");\n     XmlNode cost = rateQuote3.SelectSingleNode("//rq:TOTAL_COST", nsmgr);	0
25540669	25538916	How to parse this Json with C# using json.net	JObject myJsonNetObject = JObject.Parse(jsonCode);\n\nforeach (JObject item in myJsonNetObject["result"])\n{\n    if (item["ContentType"].ToString() == "comment")\n    {\n        Console.WriteLine("CommentId: " + item["CommentId"]);\n        Console.WriteLine("City: " + item["City"]);\n        // etc..\n    }\n}	0
22445123	22443765	Windows Phone XNA animation	int timer = 0;\nRectangle position = new Rectangle(100, 100, 80, 80); // position 100x, 100y, and size is 80 width and height.\nRectangle source = new Rectangle(0, 0, 80, 80); // Position on the spritesheet is 0, 0 which should be first frame, and the frames are all 80*80 pixels in size.\n\nprivate void OnUpdate(object sender, GameTimerEventArgs e)\n{\n    timer += e.ElapsedTime.TotalMilliseconds;\n    if(timer > 30) // If it has been 0.03 seconds = 33 frames per second\n    {\n        timer = 0; // reset timer\n        source.X += 80; // Move x value to next frame\n        if(source.X > widthOfYourSpriteSheet) source.X = 0; // Reset the animation to the beginning when we are at the end\n    }\n}	0
25671186	25670181	How to move a item from 1 workflow to another workflow and then back to the 1st workflow in Sitecore?	public class AddVersionWorkflowAction\n{\n    public void Process(WorkflowPipelineArgs args)\n    {\n        // TODO: check for nulls, assertions, etc.\n\n        args.DataItem.Versions.AddVersion();\n    }\n}	0
20995513	20995330	C# merge two list, without duplicates and sum a field values	var list_collapsed = list\n    .GroupBy(p => new { Id = p.Id, Name = p.Name } )\n    .Select(g => new Product(g.Key.Id, g.Key.Name, g.Sum(p => p.Quantity)))\n    .ToList();	0
18025140	18025043	WPF Tooltip data binding	Text="{Binding DataContext.Name, RelativeSource={RelativeSource AncestorType=ListViewItem}}"	0
17836078	17813243	Passing ASP.NET values into an external web servers iframe using GET	var iframe_doc = document.getElementById('iframe_id').contentWindow.document;	0
1468724	1468707	How to pass a property from an ASP.Net page to a user control	public MyCustomType SoftwareItem {get; set;}	0
11341369	11316322	bitmap save a generic error occurred in gdi+	ImageConverter img_converter = new ImageConverter();\n                System.Drawing.Image img = imageProcessor.Resize(orgImage, width, height);\n\n                byte[] bytes = (byte[])img_converter.ConvertTo(img, typeof(byte[]));\n\n                File.WriteAllBytes(filePath + fileName, bytes);	0
7363832	7363768	I added a registry key, but I cannot find it programmatically	HKLM\SOFTWARE\Wow6432Node\Foo\Bar	0
33888538	33888361	How can i add an if statement in my script?	using System.IO;\n\n    private IWshNetwork_Class network = new IWshNetwork_Class();\n\n    private void button4_Click(object sender, EventArgs e)\n    {  \n      string drive = Path.GetPathRoot("k:");\n\n      if(!Directory.Exists(drive))\n      {               \n       network.MapNetworkDrive(drive, @"\\10.*.*.*\d$\test", Type.Missing, "local\\blabla", "*******");\n\n       System.Diagnostics.Process.Start("file:///K:\\gemy.exe");                        \n      }\n      else\n      {  \n        //This is the closing part\n        network.RemoveNetworkDrive("k:");\n      }\n    }	0
30409114	30409057	Getting selected dialog item to another button method	private String filename = null;\n\nprivate void btnChooseFile_Click(object sender, EventArgs e)\n{\n    OpenFileDialog dlg = new OpenFileDialog();\n    dlg.Multiselect = false;\n    dlg.Filter = "XML documents (*.xml)|*.xml|All Files|*.*";\n\n    if (dlg.ShowDialog() == DialogResult.OK)\n    {\n        tbxXmlFile.Text = dlg.FileName;\n        XmlDocument invDoc = new XmlDocument();\n        invDoc.Load(dlg.FileName);\n        ....\n        ....\n        this.filename = dlg.FileName;\n    }\n}\n\nprivate void btnStore_Click(object sender, EventArgs e)\n{\n    try\n    {\n        string cs = @"Data Source=localhost;Initial Catalog=db;integrated security=true;";\n        using (SqlConnection sqlConn = new SqlConnection(cs))\n        {\n            DataSet ds = new DataSet();\n            ds.ReadXml(this.filename);\n            ....\n            ....\n        }\n    }\n}	0
2044968	2044954	C# multiple arguments in one to DRY out parameter-passing	Func<Thing> f = () => new Thing(arg1, arg2, arg3, arg4);\nThing thing1 = f();\nThing thing2 = f();\nThing thing3 = f();\nThing thing4 = f();	0
3744864	3744031	Comparing byte[] in LINQ-to-SQL and in a unit test that uses mocking	var user = (by name).SingleOrDefault();\nif(user==null) #fail\nbool hashMatch = /* compare array */\nif (!hashMatch) #fail\nreturn user;	0
19332150	19332131	Change Canvas.ZIndex for Grid in C#	Canvas.SetZIndex(obj, N);	0
7889074	7887117	Suggest implementation of String.Replace(string oldValue, Func<string> newValue) function	public static string Replace(this string str, string oldValue, Func<string> newValueFunc)\n{\n  return Regex.Replace( str,\n                        Regex.Escape(oldValue),\n                        match => newValueFunc() );\n}	0
1400140	1400091	Search and remove item from listbox	while(LB_upload.Items.Count > 0)\n{\n  ftp.Upload(LB_upload.Items[0].ToString());\n  LB_upload.Items.RemoveAt(0);\n}	0
12126855	12126832	how do I add if statement in linq statement	testDictionary.Keys.ToList().ForEach(k => \n{\n    //if(true){add toReturn list}\n});	0
20980885	20980838	Not all code routes produce a value, with a procedure I am sure it produces always something. C#	public static int[,] TablaContingencia(MAnalitica[] M)\n    {\n      int[,] TablaContingencia = new int[2, 2]; //Inicializes with size 2x2\n      int categ = M.GetLength(0);\n      for (int m = 0; m <= categ - 1; m = m + 1)\n      {\n        int k = M[m].P;\n        int Pr0 = Convert.ToInt16(M[m].Conteo * (1 - M[m].PCliente));\n        int Pr1 = Convert.ToInt16(M[m].Conteo * M[m].PCliente);\n        TablaContingencia[k, 0] = TablaContingencia[k, 0] + Pr0;\n        TablaContingencia[k, 1] = TablaContingencia[k, 1] + Pr1;\n\n       }\n       return TablaContingencia;\n   }	0
26663496	26663189	Binding multiple DataSources to a single ListView	var images = from i in PiccyPic.Images\njoin user in PiccyPic.Users on i.UserId equals user.Id\nselect new { property1 = i.Property1, property2 = user.Property2, etc. }	0
18249510	18249082	Providing values to enum properties generated at runtime for propertygrid	context.PropertyDescriptor.Name	0
8375662	8369685	In Script#, how can one enumerate a list that one inherits from?	abstract class MyList\n{\n    private List<Object> innerList = new List<Object>();\n\n    public Object Find(int? id)\n    {\n        foreach(Object obj in innerList)\n        {\n            if(Compare(id, obj))\n                return obj;\n        }\n        return default(Object);\n    }\n\n    protected abstract bool Compare(int? id, Object obj);\n}	0
13702257	13702212	Value cannot be null. Parameter name: String	public void ProcessRequest(HttpContext context)\n{\n    context.Response.ContentType = "application/json";\n    string requestId = context.Request.QueryString["requestId"];\n    string isPinned = context.Request.QueryString["isPinned"];\n    var facade = new RequestManagementFacade();\n    facade.PinRequest(Int32.Parse(requestId), Boolean.Parse(isPinned));\n}	0
8262652	8262522	A variable for user ID, reachable during the whole process of page creation.(instead of session)	// Global.asax\nvoid Application_BeginRequest(object sender, EventArgs e)\n{\n    HttpContext.Current.Items["hello"] = DateTime.Now;\n}\n// Default.aspx\npublic partial class _Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        Label1.Text = HttpContext.Current.Items["hello"].ToString();\n    }\n}	0
8684987	8684852	Looping Forever in a Windows Forms Application	System.Threading.Thread t;\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        //create and start a new thread in the load event.\n        //passing it a method to be run on the new thread.\n        t = new System.Threading.Thread(DoThisAllTheTime);\n        t.Start();\n    }\n\n    public void DoThisAllTheTime()\n    {\n        while (true)\n        {\n            //you need to use Invoke because the new thread can't access the UI elements directly\n            MethodInvoker mi = delegate() { this.Text = DateTime.Now.ToString(); };\n            this.Invoke(mi);\n        }\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        //stop the thread.\n        t.Suspend();\n    }	0
11062076	11062044	Issue with removing symbols from a string	Words[i] = Words[i].Replace("\n", "");	0
5493759	5493731	Writing XML document containing multiple objects in C#	using System.Linq;\nusing System.Xml.Linq;\n\n...\n\nXDocument doc = new XDocument(\n    new XElement("as",\n        a.Select(item => new XElement("a",\n           new XAttribute("value", item)\n        )\n    ),\n    new XElement("bs",\n        b.Select(item => new XElement("b",\n           new XAttribute("value", item)\n        )\n    ),\n    new XElement ("cs",\n        c.Select(item => new XElement("c",\n           new XAttribute("key", item.Key),\n           new XAttribute("value", item.Value)\n        )\n    )\n);	0
631737	630827	Linq to sql: properties of properties that may be null	from x in Foo\nlet y = x.Bar\nwhere y != null\nselect y.Baz;	0
25165238	25155980	OWIN interferes with log4net	Trace.Listeners.Remove("HostingTraceListener");\nTrace.Listeners.Remove("HostingTraceSource");	0
16824411	16815595	Prevent duplicate registrations - Castle Windsor	var registeredServices = new List<Type>();\n\nforeach (var node in container.Kernel.GraphNodes)\n{\n    foreach (var t in ((Castle.Core.ComponentModel)node).Services)\n    {\n        if (registeredServices.Contains(t))\n            throw new Exception(string.Format("service {0} already registered", t));\n        registeredServices.Add(t);\n    }\n}	0
20909207	20908845	string array to Int array using RegEx	int outputValue;\nint.TryParse(Regex.Replace(inputString, @"[\D]", ""), out outputValue);	0
3163738	3155215	how can i pass a parameter from ASP.NET to SSRS Report?	ReportViewer1.ServerReport.ReportServerUrl = new System.Uri("http://MyPC/reportserver");\n        ReportViewer1.ServerReport.ReportPath = "/ReportFolder/Reportname";\n\n        Microsoft.Reporting.WebForms.ReportParameter[] Param = new Microsoft.Reporting.WebForms.ReportParameter[3];\n        Param(2) = new Microsoft.Reporting.WebForms.ReportParameter("SDATE", "02/02/2002");\n        Param(1) = new Microsoft.Reporting.WebForms.ReportParameter("EDATE", "09/06/2000");\n        Param(0) = new Microsoft.Reporting.WebForms.ReportParameter("TASK", 0);\n\n        View.ReportViewer.ShowParameterPrompts = false;\n        View.ReportViewer.ServerReport.SetParameters(Param);\n        View.ReportViewer.ServerReport.Refresh();	0
3469610	3469399	Question on searching a string using regex and storing in a List	static void TestRegularExpression()\n{\n    String line = "Some text here, blah blah Identity=\"EDN\\nuckol\" and FRAMEworkSiteID=\"DesotoGeneral\" and other stuff.";\n    Match m1 = Regex.Match(line, "((identity)(=)('|\")([a-zA-Z]*)([\\\\]*)([a-zA-Z]*)('|\"))", RegexOptions.IgnoreCase);\n    Match m2 = Regex.Match(line, "((frameworkSiteID)(=)('|\")([a-zA-Z]*)('|\"))", RegexOptions.IgnoreCase);\n\n    if (m1.Success && m2.Success)\n    {\n        //...\n        Console.WriteLine("Success!");\n        Console.ReadLine();\n    }\n}	0
17941753	17941015	How can I add a new object to an existing Entity, PUT the data and have EF add it to my database?	public class Answer\n{\n    public int AnswerId { get; set; }\n    public string Text { get; set; }\n    public int QuestionId { get; set; }\n    public virtual Question Question { get; set; }\n}	0
1537928	1537835	Handling SaveChanges exceptions in a loop	while(i < 1000)\n{\n    MyEntity Wibble = new MyEntity();\n    Wibble.Name = "Test " + i.ToString();\n\n    Context.AddToTests(Wibble);\n\n    try\n    {\n        Context.SaveChanges();\n    }\n    catch\n    {\n        Context.ObjectStateManager.GetObjectStateEntry(Wibble).Delete();\n    }\n\n}	0
12104360	12102956	permutations save to disk	var polar=new string[]{"A", "B"};\nvar nonPolar=new string[]{"a", "b"};\nvar all = new string[]{"a", "b"};\nvar query=from pos1 in polar \nfrom pos2 in nonPolar \nfrom pos3 in all\nselect pos1 + pos2 + pos3;\n  foreach (var element in query)\n                Console.WriteLine(element);	0
9251215	9249456	How to get TextBox's real height?	private int GetTextHeight(TextBox tBox) {\n  return TextRenderer.MeasureText(tBox.Text, tBox.Font, tBox.ClientSize,\n           TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl).Height;\n}	0
4971639	4971601	Sorting a list in C# (with various parameters)	list.Sort((x,y)=>string.Compare(x.Name,y.Name));\n\nlist.Sort((x,y)=>y.Age.CompareTo(x.Age)); // desc\nlist.Sort((x,y)=>x.Age.CompareTo(y.Age)); // asc	0
1143768	1143726	Building up a LINQ query based on bools	List<string> types = new List<string>();\n\nif (criteria.SearchFreshFoods) { types.Add("Fresh Foods"); }\nif (criteria.SearchFrozenFoods) { types.Add("Frozen Foods"); }\nif (criteria.SearchBeverages) { types.Add("Beverages"); }\nif (criteria.SearchDeliCounter) { types.Add("Deli Counter"); }\n\nreturn _DB.FoodItems.Where(x => x.FoodTitle == SearchString &&\n                                types.Contains(x.Type));	0
21485217	21484961	Using group by in linq	var groupedList = myList\n    .GroupBy(i => i.factorId)\n    .Select(g => new \n    { \n        FactorId = g.Key, \n        SumAmount = g.Sum(i => i.Amount), \n        SumRemains = g.Sum(i => i.Remains) \n    });	0
5605648	5605561	Navigation in Windows Forms using enter key	public partial class CustomTextbox : TextBox\n{\n    public CustomTextbox()\n    {\n        InitializeComponent();            \n    }\n\n    protected override void OnKeyPress(KeyPressEventArgs e)\n    {\n        if (e.KeyChar == '\r')\n        {\n            e.Handled = true;\n            SendKeys.Send("{TAB}");\n        }\n\n    }\n}	0
26420273	26420159	Retrieving data from Oracle	string cmdText = @"select Initcap(ZZFNAME) ZZFNAME \n                   from sap_empmst \n                   where substr(GBDAT,1,6) = substr(sysdate,1,6) and stat2 =3 \n                         and werks in('RIGC','IPGC') \n                         and plans<99999999 \n                   order by persk";\nusing(OracleConnection con = new OracleConnection(.....))\nusing(OracleCommand cmd = new OracleCommand(cmdText, con))\n{\n    con.Open();\n    using(OracleDataReader dr = cmd.ExecuteReader())\n    {\n       while(dr.Read())\n          Label1.Text += dr.GetString(0);\n    }\n}	0
17431297	17431235	null values on integers and strings but they are already assigned	// Need to add:\npntrs = new int[Pntrnum];\n\nfor (int i = 0; i < Pntrnum; i++)\n{\n    stream.Position = Pntrstrt;\n    stream.Read(data, 0, data.Length);\n    pntrs[i] = BitConverter.ToInt32(data, 0);\n}\n\n// Need to add:\nStrs = new string[Pntrnum];\n\nfor (int i = 0; i < Pntrnum; i++)\n{\n    byte[] sttrings = new byte[pntrs[i + 1] - pntrs[i]];\n    stream.Position = pntrs[i];\n    stream.Read(sttrings, 0, sttrings.Length);\n    Strs[i] = Encoding.GetEncoding("SHIFT-JIS").GetString(sttrings);	0
25938756	25938654	How can I detect the direction of a dragging event?	Point mouseDownPoint;\nPoint mouseUpPoint;\nfloat deltaX = mouseUpPoint.X - mouseDownPoint.X;\nfloat deltaY = mouseUpPoint.Y - mouseDownPoint.Y;\nif (deltaX > 0)\n{\n    // Moved right\n}\nelse if (deltaX < 0)\n{\n     // Moved left\n}\nif (deltaY > 0)\n{\n     // Moved down\n}\nelse if (deltaY < 0)\n{\n    // Moved up\n}	0
17286048	17285843	c# xml into datagrid different level of child	XDocument doc = XDocument.Load(@"XMLFile.xml");\n\n            var query = from c in doc.Root.Descendants("candidate")\n                        let cat = c.Element("cat")\n                        select new\n                        {\n                            FirstName = c.Element("firstName").Value,\n                            LastName = c.Element("lastName").Value,\n                            Age = c.Element("age").Value,\n                            Salary = c.Element("salaryoff").Value,\n                            Exp = c.Element("exp").Value,\n                            Award = cat.Element("award").Value,\n                            Hst = cat.Element("hst").Value,\n                            Previous = cat.Element("previous").Value,\n                            Flex = cat.Element("flex").Value,\n                            Travel = cat.Element("travel").Value,\n                        };\n            dgv.DataSource = query.ToList();	0
2718052	2718030	Improving method to read signed 8-bit integers from hexadecimal	private int HexToInt(string _hexData)\n{\n    int number = Convert.ToInt32(_hexData, 16);\n    if (number >= 0x80)\n       return -(number & 0x7F);\n    return number;\n}	0
27796816	27782849	CookieContainer from HttpWebRequest has path directly to file - How to ignoring path?	CookieContainer cc = new CookieContainer();\n\n    HttpWebRequest request = WebRequest.Create("http://127.0.0.1/index.html") as HttpWebRequest;\n    //request.CookieContainer = cc;\n    HttpWebResponse response = request.GetResponse() as HttpWebResponse;\n\n    foreach (Cookie cookie in response.Cookies)\n    {\n        Cookie newCookie = new Cookie(cookie.Name, cookie.Value, "/", "127.0.0.1");\n        cc.Add(new Uri("http://127.0.0.1"), cookie);\n    }\n\n    StreamReader sr = new StreamReader(response.GetResponseStream());\n    MessageBox.Show(sr.ReadToEnd());\n    sr.Close();\n    response.Close();	0
11643379	11643316	Get parameters for SelectParameters from another dropdown in c# .net	protected void DropDownVisaType_SelectedIndexChanged(object sender, EventArgs e)\n{\n  Int32 value = Convert.ToInt32(DropDownVisaType.SelectedItem.Value);\n  DropDownVisaTypeSpecific.DataSource=Method_Name(Value);\n  DropDownVisaTypeSpecific.DataBind();\n}	0
17418301	17418258	datetime format to SQL format using C#	DateTime myDateTime = DateTime.Now;\nstring sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");	0
15584382	15584353	Code Behind Manipulations/Giving custom names to Variables/Combining names	ArrayList<CheckBox> checkboxes = new ArrayList<CheckBox>();\nfor(int i=0;i<5;i++)\n{\n    checkboxes.Add(new CheckBox());\n}	0
521844	521795	How to sort a DataView in a case-insensitive manner?	DataTable dt = GetDataFromSource();\ndt.CaseSensitive = false;\ndt.DefaultView.Sort = "city asc";	0
1311663	1311395	Google maps - show marker window from result list	GEvent.trigger(googleMarker[i], googleMarker[i].getLatLng());	0
7037810	7037447	WPF CustomControl ControlTemplate update TemplateBinding at Runtime	public string Title\n{\n    get { return (string)this.GetValue(TitleProperty); }\n    set { this.SetValue(TitleProperty, value); } \n}	0
3828752	3828600	Convert Excel Cell Value From Text To Number Using C#	my_range.NumberFormat = "0.0"; // change number of decimal places as needed	0
1884185	1884130	how to optimize time in webservice while sending request and receiving response?	keep alive	0
2330106	2330026	Is it possible to set this static private member of a static class with reflection?	using System;\nusing System.Reflection;\n\nclass Example\n{\n    static void Main()\n    {\n        var field = typeof(Foo).GetField("bar", \n                            BindingFlags.Static | \n                            BindingFlags.NonPublic);\n\n        // Normally the first argument to "SetValue" is the instance\n        // of the type but since we are mutating a static field we pass "null"\n        field.SetValue(null, "baz");\n    }\n}\n\nstatic class Foo\n{\n    static readonly String bar = "bar";\n}	0
2402314	2402304	How to refer to items in Dictionary<string, string> by integer index?	Dictionary<TKey, TValue>	0
24050281	24034872	How to do grouping and aggregations when data bind by ajax in Telerik Grid	public ActionResult _AjaxBinding([DataSourceRequest]DataSourceRequest request)\n{\n  return Json(MyModelToReturn.ToDataSourceResult(request));\n}	0
13197658	13197404	Want to assign HTML value to String variable	string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello\n\n        var doc = new XmlDocument();\n        doc.LoadXml(div);\n        string text = doc.InnerText;	0
9112073	9111768	Remove from list where all items not included using LINQ	int distinctIDs = items.Select(x => x.ItemID).Distinct().Count();\nvar newList = items\n    .GroupBy(x => x.ListID)\n    .Where( x => x.Select(y=>y.ItemID).Distinct().Count() ==  distinctIDs)\n    .SelectMany(x => x.ToList())\n    .ToList();	0
15680646	15680563	How to remove from the list the items that have parents in the same list	var Children = List.Where(child => List.Any(parent => parent.Id == child.ParentID)).ToList();\nList.RemoveAll(child => Children.Contains(child));	0
23289946	23287303	Load BitmapImage into WriteableBitmap but no method existing	BitmapImage bi = new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));\nWriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);\n\nvar streamFile = await GetFileStream(myFile);\nawait wb.SetSourceAsync(streamFile);\nwb = wb.Convolute(WriteableBitmapExtensions.KernelGaussianBlur5x5);	0
11079903	11069113	How to Refresh datagridview continously after Updating	yourDataGridview.DataSource = yourDataRetrievingMethod  // in your situation your dataset and/or table	0
30133081	30132824	Edit Method WPF | Dynamic Parameters	foreach (BaseMember bm in members)\n        {\n\n            if (Username == bm.username)\n            {  \n                Type type = bm.GetType();\n\n                PropertyInfo prop = type.GetProperty(parameter);\n\n                prop.SetValue (bm, newValue, null);\n            }\n        }	0
19661609	19661512	How to Optmize a multiple if else with LINQ	var type = typeof(ConfigurationDetails);\nvar flags = BindingFlags.Static | BindingFlags.Public;\n\nforeach(var kvp in configValues)\n{        \n    var property = type.GetProperty(kvp.Key, flags);\n    if (property != null)\n       property.SetValue(null, kvp.Value);\n}	0
6478387	6478175	Remove object from generic list by id	public virtual void RemoveNote(int id)\n{\n   //remove the note from the list here\n\n   Notes = Notes.Where(note => note.Id != id).ToList();\n}	0
1437369	1437339	Merge Two DateTime types in C#	return DateTime.Parse(date) + DateTime.UtcNow.TimeOfDay;	0
12790061	12790021	How to end Periodic Updates to a Windows 8 Live Tile	PeriodicUpdateRecurrence recurrence = PeriodicUpdateRecurrence.Hour;\nSystem.Uri url = new System.Uri(polledUrl);\nvar tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();\n\ntileUpdater.StartPeriodicUpdate(url, recurrence);\n\n// ...\n\ntileUpdater.StopPeriodicUpdate();	0
20446444	20446351	How to add to an XML serialization a Class independent tag	public class AllInfo\n{\n    public string Image {get;set;}\n    public Module[] Modules {get;set;}\n}	0
25997011	25995609	XmlSerializer - node containing text + xml + text	[Serializable]\npublic class TestClass\n{\n    [XmlText(typeof(string))]\n    [XmlAnyElement]\n    public object[] Items { get; set; }\n}	0
3396446	3396353	Foreach to find the subordinates of my subordinates and so on	private List<Subordinate> GetSubordinates(Subordinate you){\n        List<Subordinate> subs = new List<Subordinate>();\n        if(!you.HasSubordinates){\n              return subs;\n         }\n\n         foreach(Subordinate s in you.Subordinates){\n            subs.AddRange(GetSubordinates(s));\n        }\n  }	0
21363786	21363322	Creating a ListView with updating Progress bar for downloads Windows 8 C# XAML	public class DownloadItem : INotifyPropertyChanged\n{\n    public double downloadPercent { get; set; }\n    public string episodeTitle { get; set; }\n    public string podcastFeedTitle { get; set; }\n    public DownloadOperation operation { get; set; }\n\n    private double percent;\n    public double Percent\n    {\n        get { return percent; }\n        set\n        {\n            if (percent == value)\n                return;\n\n            percent = value;\n            OnPropertyChanged("Percent");\n        }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    public void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n        {\n            handler(this, new PropertyChangedEventArgs(propertyName));\n        }\n    }\n}	0
5406817	5405859	Predicate in a method signature, Lambda expression	public static bool IsValid(T obj, Predicate<T> condition)\n{\n        return condition(obj);\n}\n\nValidator.IsValue(foo,f=>f.Value==1);	0
2956192	2955580	HOW TO SElect line number in TextBox Multiline	string str = textBox2.Text;\n\n            int index = textBox1.Text.IndexOf(str);\n\n            if (index !=-1)\n            {                \n\n              int  lineNo = textBox1.GetLineFromCharIndex(index);\n            }	0
20944766	20944585	Enum Size in Bytes	Marshal.SizeOf(Enum.GetUnderlyingType(typeof(MMTPCnxNckRsn))).	0
15341622	15333167	Find All the bool variables from .aspx file by Regex	bool\s*([^;]+);	0
28895292	28895035	How to convert approximate white to transparent background	public static Bitmap MakeTransparent(Image image)\n    {\n        Bitmap b = new Bitmap(image);\n\n        var replacementColour = Color.FromArgb(255, 255, 255);\n        var tolerance = 10;\n\n        for (int i = b.Size.Width - 1; i >= 0; i--)\n        {\n            for (int j = b.Size.Height - 1; j >= 0; j--)\n            {\n                var col = b.GetPixel(i, j);\n\n                if (255 - col.R < tolerance && \n                    255 - col.G < tolerance && \n                    255 - col.B < tolerance)\n                {\n                    b.SetPixel(i, j, replacementColour);\n                }\n            }\n        }\n\n        b.MakeTransparent(replacementColour);\n\n        return b;\n    }	0
17256139	17255774	Is there a way to have a countdown timer while waiting for input?	//Add Using Statement\nusing System.Windows.Threading;\n\n//Create Timer\nDispatcherTimer mytimer;\n\n//Setup Timer\nmyTimer = new DispatcherTimer();\nmyTimer.Interval = System.TimeSpan.FromSeconds(10);\nmyTimer.Tick += myTimer_Tick;\n\n// When you type the +=, this method skeleton should come up\n// automatically. But type this in if it doesn't.\nvoid myTimer_Tick(object sender, EventArgs e)\n{\n    //This runs when ever the timer Goes Off (In this case every 10 sec)\n}\n\n//Run Timer\nmyTimer.Start()\n\n//Stop Timer\nmyTimer.Stop()	0
24997162	24997095	Save DIalogue that copies/loads another file	if (savefile.ShowDialog() == DialogResult.OK)\n{\n    // you can use File.Copy\n    System.IO.File.Copy(fileName, saveFile.Filename);\n}	0
6513302	6512998	How can I find all data with a given time span	var gaps = samples.Zip(samples.Skip(1),\n    (s0, s1) =>\n        new\n        {\n            Sample = s0,\n            Delta = s1.DateSample - s0.DateSample,\n        })\n    .Where(result => result.Delta.TotalMinutes >= 15)\n    .Select(result => result.Sample);	0
33973299	33972949	Pyramid of letters based on input C#	int i=0,j=0; char ch='g';\nfor(i='a';i<=ch;i=i+2){\n    for(j=(ch-i)/2;j>0;j--){\n        printf(" ");\n    }\n    for(j='a';j<i+1;j++){\n        printf("%c", i);\n    }\n    printf("\n");\n}	0
12429328	12429252	How can I compare an integer to the value I get from an enum?	public CONTENT GetRowType(string pk) \n{\n    int temp = Convert.ToInt32(pk.Substring(2, 2));\n    if (Enum.IsDefined(typeof(CONTENT), temp)) \n    { \n        return (CONTENT)temp;\n    }\n    else throw new IndexOutOfRangeException();\n}	0
18381614	18365899	How to access local resource : MVC	using Myproject.Areas.Models.Support.Localization;\n...\nMyResouces.option1	0
30763329	30763263	Controls doesn't show if heavy process	HeavyFunction()	0
23965283	23964985	Get a value of particular column from Database Winforms	foreach (DataGridViewRow dr in gvShipment.Rows)\n        {\n            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)dr.Cells["Select"];\n            {\n                if (Convert.ToBoolean(chk.Value) == true)\n                {\n                    IsApproved += dr.Cells["IsApproved"].Value.ToString() ;\n                }\n            }\n        }\n        if (IsApproved == "False")\n        {\n            MessageBox.Show("This Order is not Approved.", "Message");\n            return;\n        }	0
5939162	5918614	Invalid Character in base64 string when decoding XML	if (brData.ChunkNo == 1)\n    {\n\n        // Set the Content-type of the file\n        if (brData.MimeType.Length < 1)\n        {\n            mimeType = "application/unknown";\n        }\n        else\n        {\n            mimeType = brData.MimeType;\n        }\n\n        msbase64Out = new MemoryStream();\n    }\n\n\n    if (brData.bytesJustRead > 0)\n    {\n        fileMS.WriteTo(msbase64Out);\n\n    }\n\n\n   if (brData.bytesRemaining < 1)\n    {\n        byte[] imgBytes = msbase64Out.ToArray();\n\n        string img64 = Convert.ToBase64String(imgBytes);\n\n        viewdocWriter.WriteString(img64);\n    }	0
190254	190227	Building a LINQ query programatically without local variables tricking me	foreach (Attribute a in requiredAttributes)\n{\n    Attribute copy = a;\n    result = result.Where(p => p.Attributes.Contains(copy));\n}	0
6440871	6440422	Count number of minus signs in a PDF document using C#	int minusCount = 0;\nusing (PdfTextDocument doc = new PdfTextDocument(pdfStream)) {\n    using (PdfTextReader reader = doc.GetPdfTextReader()) {\n        int c = 0;\n        while ((c = reader.Read()) >= 0) { // return < 0 at end\n           if ((char)c == '-') minusCount++;\n        }\n    }\n}	0
34205211	34204676	How add items to a list in foreach loop using c#	List<string> guids = ec1.Entities\n   .Select(entity => Convert.ToString(entity.Attributes["accountid"]))\n   .ToList();	0
16077420	16076683	Using Sql data after binding to repeater	void Repeater_Beskeder_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {\n\n      // This event is raised for the header, the footer, separators, and items.\n\n      // Execute the following logic for Items and Alternating Items.\n      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {\n         Panel Vis_Panel = (Panel)row.FindControl("Panel_Vis_Besked");\n        if (Request.QueryString["id"].ToString() == reader["id"])\n        {\n            Vis_Panel.Visible = true;\n        }\n      }\n   }	0
7766325	7653841	Editing different types of files from gridview	using System.Diagnostics;\nusing System.ComponentModel;\nprotected void GridView1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    GridViewRow row = GridView1.SelectedRow;\n\n    string Datalink = row.Cells[2].Text;\n    string myPath = @"C:\Users\abc\" + Datalink;\n    Process prc = new Process();\n    prc.StartInfo.FileName = myPath;\n    prc.Start();\n}	0
1709027	1708591	Get Just the Body of a WCf Message	class Program\n{\n    [DataContract]\n    public class Person\n    {\n        [DataMember]\n        public string FirstName { get; set; }\n\n        [DataMember]\n        public string LastName { get; set; }\n\n        public override string ToString()\n        {\n            return string.Format("{0}, {1}", LastName, FirstName);\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var person = new Person { FirstName = "Joe", LastName = "Schmo" };\n        var message = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.Default, "action", person);\n\n        var reader = message.GetReaderAtBodyContents();\n        var newMessage = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.Default, "newAction", reader);\n\n        Console.WriteLine(message);\n        Console.WriteLine();\n        Console.WriteLine(newMessage);\n        Console.WriteLine();\n        Console.WriteLine(newMessage.GetBody<Person>());\n        Console.ReadLine();\n    }\n}	0
2176873	2176866	How to create a DateTime nicely which is today at 23:00	var eleven = DateTime.Today.AddHours(23);	0
4778828	4778775	Copy parameters from DbCommand to another DbCommand	public DbCommand RecycledParameters(string sql, IList<DbParameter> parameters)\n{\n    var result = db.GetSqlStringCommand(sql);\n    foreach(DbParameter p in parameters)\n    {  \n        db.AddInParameter(result, p.ParameterName, p.DbType, p.Value);\n    }\n    return result;\n}	0
15832840	15832376	How do I open a window as a modal dialog in MonoMac using C#?	NSApplication.SharedApplication.RunModalForWindow(ewc.Window);	0
11714624	11702795	Get value of a cell in a row in a datagrid in the 'Paint' function?	protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum,\n    Brush backBrush, Brush foreBrush, bool alignToRight) {\n  DateTime date = (DateTime)GetColumnValueAtRow(source, rowNum);\n  Rectangle rect = bounds;\n  g.FillRectangle(backBrush, rect);\n  rect.Offset(0, 2);\n  rect.Height -= 2;\n  g.DrawString(date.ToString("d"), this.DataGridTableStyle.DataGrid.Font, foreBrush, rect);\n}	0
19472297	19472249	Homework Help: Max and min value with if statements	int a = 10, b = 20, c=30;\n\nint max = a, min = b;\n\nif ( a < b )\n{\n    min = a;\n    max = b;\n}\n\nif ( c < min )\n   min = c;\nif ( c > max )\n   max = c;	0
4649335	4649302	Convert 6 digit number to time in asp.net	int timeNumber = 134501;\nDateTime time = DateTime.ParseExact(timeNumber.ToString().PadLeft(6, '0'), "HHmmss", null);	0
34538574	34536348	How can I save the contents of a DataTable to an XML file to be stored within my Web API project's App_Data folder?	public void Get()\n{\n    string jsonString = JsonConvert.SerializeObject(datatable, Formatting.Indented);\n\n    string path = HttpContext.Current.Server.MapPath("~/App_Data/");\n\n    //Generate a filename with your logic..\n    string fileName = string.Concat(Guid.NewGuid().ToString(), ".json");\n\n    //Create the full Path\n    string fullPath = System.IO.Path.Combine(path, fileName);\n\n    //Create the json file\n    System.IO.File.WriteAllText(fullPath, jsonString);\n}	0
16110035	16109853	How to search words in richtextbox with different orders(up and down)?	if (System.Text.RegularExpressions.Regex.IsMatch("text string including test", "test", System.Text.RegularExpressions.RegexOptions.IgnoreCase))\n{\n    //test found\n}	0
20691219	20691045	Trying to exclude certain wpf windows when getting a collection of windows in c#	public static List<BitmapSource> RenderWindows()\n{\n    var windows = Application.Current.Windows\n                                     .OfType<Window>()\n                                     .Where(x => x.GetType() != typeof(AskAQuestionDialog));\n\n    var bitmaps = new List<BitmapSource>();\n\n    foreach (var window in windows)\n    {\n        var bitmap = new RenderTargetBitmap((int)window.width, (int)window.height, 96d, 96d, PixelFormats.Default));\n        bitmap.Render(window);\n\n        bitmaps.Add(bitmap);\n    }\n\n    return bitmaps;\n}	0
5894363	5893884	How to read key value from XML in C#	public string GetXMLValue(string XML, string searchTerm)\n{\n  XmlDocument doc = new XmlDocument();\n  doc.LoadXml(XML);\n  XmlNodeList nodes = doc.SelectNodes("root/key");\n  foreach (XmlNode node in nodes)\n  {\n    XmlAttributeCollection nodeAtt = node.Attributes;\n    if(nodeAtt["name"].Value.ToString() == searchTerm)\n    {\n      XmlDocument childNode = new XmlDocument();\n      childNode.LoadXml(node.OuterXml);\n      return childNode.SelectSingleNode("key/value").InnerText;\n    }\n    else\n    {\n      return "did not match any documents";\n    }\n  }\n}	0
11627052	11626736	OrmLite pasing data do SP like object	var data = db.Query<User>("SuspendUser", new { ID = 21 },\n   commandType: CommandType.StoredProcedure);	0
4833125	4833111	C# Insert value in certain position in string?	txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);	0
25154074	25152520	How can I bind to Methods rather than Variables in WPF following MVVM structure?	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"\n\n<TextBox Margin="0,287,0,0">\n     <i:Interaction.Triggers>\n          <i:EventTrigger EventName="LostFocus">\n               <i:InvokeCommandAction Command="{Binding LostFocusCommand}" />\n          </i:EventTrigger>\n     </i:Interaction.Triggers>\n</TextBox>	0
20760654	20760477	How to get Value Member of a ComboBox by using its associated Display Text typed by user?	comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest	0
10693874	10693793	How to select specific cells (from different rows or columns) from an excel file using VS 2010, C#, oledbconnection	this.dataGridView1.Columns[0].Visible = false;\n....\n\nthis.dataGridView1.Rows[1].Visible = false;\n....	0
26943702	26943649	Posting List<Object> to a webapi 2	name="[0].OatherName"\nname="[1].OatherName"	0
20773121	20772976	Reading string from resource file and editing it programmatically	//Read\nString settingValue = Settings.Default.TestSetting;\n//Write\nSettings.Default.TestSetting = "newVal";\n//Write settings to disk\nSettings.Default.Save();	0
26331670	26292354	how to display image on ultra tree node?	Dim utNode As New UltraTreeNode\n\n    utNode.Text = UltraTree1.Nodes.Count + 1\n\n    utNode.LeftImages.Add(Me.ImageList1.Images((UltraTree1.Nodes.Count) Mod 5))\n\n    utNode.RightImages.Add(Me.ImageList1.Images((UltraTree1.Nodes.Count) Mod 5))\n\n    UltraTree1.Nodes.Add(utNode)	0
8967772	8967763	How to get controls in static method	[WebMethod]	0
5857801	5857596	Conversion of character set in C#	string first = @"M&#275;r&#257; n&#257;ma nitina hai";\nfirst = System.Web.HttpUtility.HtmlDecode(first);\n\nbyte[] ansi = System.Text.Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(1252), Encoding.Unicode.GetBytes(first));\nstring output = Encoding.Unicode.GetString(System.Text.Encoding.Convert(Encoding.GetEncoding(1252), Encoding.Unicode, ansi));\nMessageBox.Show(output);	0
7865778	7865724	How would I use regex to obtain a piece of a link?	MatchCollection matches = Regex.Matches(html, @"<a href="".*?subtopic=characters&name=.*?"".*?>(.*?)</a>.*?<td.*?>(\d+)</td><td.*?>(.*?)</td>);	0
6998436	6998364	Validate C# syntax with C#	foreach(CompilerError CompErr in results.Errors)\n{\n textBox2.Text = textBox2.Text +\n     "Line number " + CompErr.Line + \n     ", Error Number: " + CompErr.ErrorNumber + \n     ", '" + CompErr.ErrorText + ";" + \n     Environment.NewLine + Environment.NewLine;\n}	0
16583603	16583486	How to add javascript code to a LinkButton via server code c#?	linkButton.Attributes.Add("onclick", "dialogfunction('" + Link.ToString() + "');");	0
24490655	24490575	using if statement under using case	if (erisim == "A")\n{\n    return redisUser.GetAll();// .Where(c=>c.Sube=="Y");\n}\nelse if (erisim == "P")\n{\n    return redisUser.GetAll().Where(c => c.Sube == sube);\n}\nelse if (erisim == "C")\n{\n    return redisUser.GetAll().Where(c => c.CagriAcan == sicil);\n}\nelse\n{\n    return Enumerable.Empty<RequestCall>();\n}	0
13229230	13208827	Read image file in Image object from zip file	using (ZipFile zip = ZipFile.Read(enrollment))\n        {\n\n            foreach (ZipEntry e1 in zip)\n            {\n\n                    CrcCalculatorStream reader = e1.OpenReader();\n                    MemoryStream memstream = new MemoryStream();\n                    reader.CopyTo(memstream);\n                    byte[] bytes = memstream.ToArray();\n                    Image img1 = Image.FromStream(memstream);\n                    imageList.Images.Add(getThumbnaiImage(imageList.ImageSize.Width, img1));\n\n\n            }\n        }	0
5815347	5815041	Sort List<T> using string without Linq	private List<Employee> CreateSortList<T>(\n                    IEnumerable<Employee> dataSource,\n                    string fieldName, SortDirection sortDirection)\n    {\n        List<Employee> returnList = new List<Employee>();\n        returnList.AddRange(dataSource);\n        // get property from field name passed\n        System.Reflection.PropertyInfo propInfo = typeof(T).GetProperty(fieldName);\n        Comparison<Employee> compare = delegate(Employee a, Employee b)\n        {\n            bool asc = sortDirection == SortDirection.Ascending;\n            object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);\n            object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);\n            //comparing the items\n            return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;\n        };\n        returnList.Sort(compare);\n        return returnList;\n    }	0
8149623	8149527	How to make a route unique	if (Request.Url.PathAndQuery.StartsWith("/blog/") && postType = "blog") ...	0
15952645	15952457	Subtracting two arrays using Linq	var q = from a in arr1\n                  join b in arr2 on a.IdProduct equals b.IdProduct into c\n              from x in c.DefaultIfEmpty()\n              select new Data {\n                IdProduct = a.IdProduct,\n                Price = x == null ? a.Price : a.Price - x.Price\n              };\n\narr1 = q.ToArray();	0
3115766	3115637	How to create a XML file using XDocument and LINQ in C#?	// First build up a single list to work with, using an anonymous type\nvar singleList = l_lstData1.Select(x => new { Value = x, Level = 2})\n         .Concat(l_lstData2.Select(x => new { Value = x, Level = 1})\n         .Concat(l_lstData3.Select(x => new { Value = x, Level = 0});\n\nvar doc = new XDocument(\n    new XElement("FileDetails",\n        new XElement("Date",new XAttribute("FileModified", DateTime.Now)),\n        singleList.Select((item, index) => new XElement("Data",\n            new XAttribute("Name", "Data_" + (index + 1)),\n            new XAttribute("DataList", item.Value),\n            new XAttribute("Level", item.Level))));	0
12452584	12452551	C# can't declare public double array of Int: Field is never assigned to, and will always have its default value null	public int[][] mySpiros;\n\n//create three reference variables to hold array references\nmySpiros=new int[3][];\n\nmySpiros[0]=new int[4];\nmySpiros[1]=new int[] {11,22,33,44};\nmySpiros[2]=new int[40];	0
26287603	25509596	Change Label for an Excel Button	Excel.Shape ButtonXX = ws.Shapes.AddFormControl(Excel.XlFormControl.xlButtonControl, 700, 35, 150, 22);\nButtonXX.OLEFormat.Object.Text = "Text I Want";	0
12041617	12041433	How do I populate a listView that has two columns, given a LINQ query?	var groups = orignalFiles.GroupBy(o => o.Split('_')[0])\n                       .Select(o => new { \n                                           Name = o.FirstOrDefault().Split('_')[0], \n                                           Total = o.Count() \n                                        });	0
31779975	31719862	How to invoke a .Net method with unsigned integer argument from IronPython	import clr\nclr.AddReference('ClassLibrary1')\nfrom ClassLibrary1 import MmsValue\nfrom System import UInt32    \n\nuint32_mmsValue = MmsValue.__new__.Overloads[UInt32](MmsValue, 1)	0
22481012	22480941	Converting Array length to Mega byte	readerQuotas.MaxArrayLength = 1024 * 1024 * 50; // 50 MB	0
9210008	9209761	Traybar application shown on start	/// </summary>\n    private void InitializeContext() \n    {\n        ....\n        this.exitContextMenuItem.Click += new System.EventHandler(this.exitContextMenuItem_Click);\n        ShowForm();\n    }	0
9039521	9039337	Opening winform from wpf application programmatically	YourForm form = new YourForm();\nform.Show();	0
24749106	21851412	Xamarin iOS C# Open Links in Safari from UIWebView	private bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navType)\n{\n  if (navType == UIWebViewNavigationType.LinkClicked)\n  {\n    UIApplication.SharedApplication.OpenUrl(request.Url);\n    return false;\n  }\n    return true;\n}	0
27103564	27101711	How do I put a full screen window on top in C# after screen is cloned?	public void ExtendDisplays()\n{\n    SetDisplayConfig(0, IntPtr.Zero, 0, IntPtr.Zero, (SDC_APPLY | SDC_TOPOLOGY_EXTEND));\n    this.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); //Force update\n    current_window.hide();\n    current_window.show();\n}	0
11656773	11656613	DataBindings on a checkbox	Check.DataBindings.Add("Checked", dt, "check");	0
11758625	8727882	Detect when SplitContainer collapsed changes	private void splitContainer_Panel2_ClientSizeChanged(object sender, EventArgs e)\n{\n        btnToggle.Checked = !splitContainer.Panel2Collapsed;\n}\n\nprivate void splitContainer_Panel1_ClientSizeChanged(object sender, EventArgs e)\n{\n        btnToggle.Checked = !splitContainer.Panel2Collapsed;\n}	0
16851628	16851553	loop through checkedListBox items without the select all item	foreach (var s in checkedListBoxDepts.CheckedItems)\n{\n      if (checkedListBoxDepts.IndexOf(s) == 0)\n          continue;\n      list.Add(s.ToString());\n}	0
25452673	25449513	How to display a dictionary which contains a list in a listBox C#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n\n        listBox1.DataSource = new BindingSource(new Dictionary<string, List<string>>\n        {\n            {"Four-Legged Mammals", new List<string>{"Cats", "Dogs", "Pigs"}},\n            {"Two-Legged Mammals", new List<string>{"Humans", "Chimps", "Apes"}}\n        }, null);\n\n        listBox1.DisplayMember = "Value";\n        listBox1.ValueMember = "Key";\n    }\n\n    private void listBox1_SelectedValueChanged(object sender, EventArgs e)\n    {\n        if (listBox1.SelectedItem != null)\n        {\n            var keyValue = (KeyValuePair<string, List<String>>) listBox1.SelectedItem;\n            listBox2.DataSource = keyValue.Value;\n        }\n        else\n        {\n            listBox2.DataSource = null;\n        }\n    }	0
19207416	19207362	Interface polymorphism in C#	public interface INode<T> where T : INode<T>\n{\n    T Parent { get; set; }\n}\n\npublic interface ISpecificNode : INode<ISpecificNode>\n{\n}\n\npublic class SpecificNode : ISpecificNode\n{\n    public ISpecificNode Parent { get; set; }\n}	0
31375321	31290406	Add a row at a specific index of the datagrid	MyData.Insert(2, myrow);	0
2553478	2553453	Create a Generic IEnumerable<T> given a IEnumerable and the member datatypes	IEnumerable<T>	0
8241759	8241722	C# Closing a specific form in a multiform application	private void closeForm(int id)\n\n    {\n        foreach (Form f in Application.OpenForms)\n\n            if (Convert.ToString(id) == f.Name)\n            {\n                f.Close();\n                break;\n\n            }\n    }	0
3045439	3045304	How to create NAMED-PIPE in .NET-4?	using System; \nusing System.Text; \nusing System.IO; \nusing System.IO.Pipes; \n\nnamespace CSPipe \n{ \n  class Program \n  { \n    static void Main(string[] args) \n    { \n      NamedPipeClientStream pipe = new NamedPipeClientStream(".", "HyperPipe", PipeDirection.InOut); \n      pipe.Connect(); \n      using (StreamReader rdr = new StreamReader(pipe, Encoding.Unicode)) \n      { \n        System.Console.WriteLine(rdr.ReadToEnd()); \n      } \n\n      Console.ReadKey(); \n    } \n  } \n}	0
4518337	4518291	How to pass compiler checked property names / Expression tree to a custom attribute	#if DEBUG	0
4975299	4975242	Dynamically replace SQL string with parameters in C#	[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]\npublic static SqlString sqlsig(SqlString querystring)\n{\n    return (SqlString)Regex.Replace(\n       querystring.Value,\n       @"([\s,(=<>!](?![^\]]+[\]]))(?:(?:(?:(?:(?# expression coming\n       )(?:([N])?(')(?:[^']'')*('))(?# character\n       )(?:0x[\da-fA-F]*)(?# binary\n       )(?:[-+]?(?:(?:[\d]*\.[\d]*[\d]+)(?# precise number\n       )(?:[eE]?[\d]*)))(?# imprecise number\n       )(?:[~]?[-+]?(?:[\d]+))(?# integer\n       )(?:[nN][uU][lL][lL])(?# null\n       ))(?:[\s]?[\+\-\*\/\%\&\\^][\s]?)?)+(?# operators\n       )))",\n       @"$1$2$3#$4");\n}	0
5960388	5960366	How can I better populate two arrays in a class?	var subTopic = new SubTopic\n{\n    SubTopicId = new[] { 1, 2, 3 },\n    Description = new[] { "afds).", "afas.", "aees." }\n};	0
33914828	33914568	Get current path in Windows 8 WPF app	StorageFolder temp = Windows.Storage.ApplicationData.Current.TemporaryFolder;	0
2484263	2484239	how to do: what i pick on combobox1 will show on combobox2?	private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        object selectedValue = this.comboBox1.SelectedValue;\n        this.comboBox2.SelectedValue = selectedValue;\n    }	0
18190547	18190376	c# How to check every single line with Regex.IsMatch	bool match = sStringToCheck\n            .Split(new string[] {Environment.NewLine}, StringSplitOptions.None)\n            .Any(line => new Regex(@"^\S+ [A-Z]{1,3}$").IsMatch(line));	0
22220689	22220542	Serialize DateTime property to XML in C#	public class Loan : IXmlSerializable\n{\n    public void WriteXml(XmlWriter writer)\n    {\n        if(dateIn.HasValue)\n        {\n            writer.WriteElementString("dateIn", dateIn.Value.ToString());\n        }\n    }\n}	0
22050971	21973229	How to take an image of Exception "No messageBox"	[TestMethod]\n    public void CodedUITestMethod1()\n    {\n        WinWindow window = new WinWindow();\n        window.SearchProperties[WinWindow.PropertyNames.Name] = "Error Window";\n        WinButton okButton = new WinButton(window);\n        okButton.SearchProperties[WinButton.PropertyNames.Name] = "OK";\n\n        try\n        {\n            throw new Exception("Coded UI is throwing an exception.  No idea about the Internet explorer state.");\n        }\n        catch(Exception ex)\n        {\n            Task.Run(() =>\n                {\n                    MessageBox.Show(ex.Message, "Error Window");\n                }).Start();\n            throw new Exception("An unexpected exception occurred in Coded UI",ex);\n        }\n        finally\n        {\n            Image pic = window.CaptureImage();\n            pic.Save(@"C:\result.bmp");\n            Mouse.Click(okButton);\n        }\n\n\n    }	0
5236080	5235967	get the position of picturebox that has been clicked	private void pb_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) \n{\n    Point mouseDownLocation = (Control)sender.PointToClient(new Point(e.X, e.Y));\n    //here goes your if condition ...\n}	0
334586	334532	Render HTML as an Image	Bitmap FinalBitmap = new Bitmap();\nMemoryStream msStream = new MemoryStream();\n\nstrInputParameter == Request.Params("MagicParm").ToString()\n\n// Magic code goes here to generate your bitmap image.\nFinalBitmap.Save(msStream, ImageFormat.Png);\n\nResponse.Clear();\nResponse.ContentType = "image/png";\n\nmsStream.WriteTo(Response.OutputStream);\n\nif ((FinalBitmap != null)) FinalBitmap.Dispose();	0
18725862	18643101	getJSON breaks on page refresh (F5). How to fix?	postRequest('realTimeActivity/GetRealTimeData?u=' + (new Date).getTime(), null, function (response) {	0
14559664	14521314	Can I preserve an Excel template's formatting	xlWorkSheet.Cells[i + 1, j + 1].Value = data;	0
11182154	11178739	How to remove gaps on TabControl?	//HACK: to ensure that the tabpage draws correctly (the border will get clipped and\n    // and gradient fill will match correctly with the tabcontrol).  Unfortunately, there is no good way to determine\n    // the padding used on the tabpage.\n    // I would like to use the following below, but GetMargins is busted in the theming API:\n    //VisualStyleRenderer visualStyleRenderer = new VisualStyleRenderer(VisualStyleElement.Tab.Pane.Normal);\n    //Padding themePadding = visualStyleRenderer.GetMargins(e.Graphics, MarginProperty.ContentMargins);	0
32997862	32997176	Draw Rectangle all directions	private void pictureBox1_MouseMove(object sender, MouseEventArgs e)\n{\n    if (e.Button == System.Windows.Forms.MouseButtons.Left)\n    {\n        Point tempEndPoint = e.Location;\n\n        var point1 = new Point(\n            Math.Max(0, Math.Min(RectStartPoint.X, tempEndPoint.X)),\n            Math.Max(0, Math.Min(RectStartPoint.Y, tempEndPoint.Y)));\n\n        var point2 = new Point(\n            Math.Min(this.picImagem.Width, Math.Max(RectStartPoint.X, tempEndPoint.X)),\n            Math.Min(this.picImagem.Height, Math.Max(RectStartPoint.Y, tempEndPoint.Y)));\n\n\n        Rect.Location = point1;\n        Rect.Size = new Size(point2.X - point1.X, point2.Y - point1.Y);\n\n\n        picImagem.Refresh();\n        picImagem.CreateGraphics().DrawRectangle(cropPen, Rect);\n\n    }\n}	0
12848713	12848696	How to clear the background image of a button with code in a C# Windows Forms application?	myButton.BackgroundImage = null;	0
29920998	29915658	Add, remove or replace references in MS Access .mdb programmatically with C#	accessApp = new Microsoft.Office.Interop.Access.Application();\nint numReferences = accessApp.References.Count;	0
2941224	2941048	How to simplify fractions in C#?	void Simplify(int[] numbers)\n{\n    int gcd = GCD(numbers);\n    for (int i = 0; i < numbers.Length; i++)\n        numbers[i] /= gcd;\n}\nint GCD(int a, int b)\n{\n    while (b > 0)\n    {\n        int rem = a % b;\n        a = b;\n        b = rem;\n    }\n    return a;\n}\nint GCD(int[] args)\n{\n    // using LINQ:\n    return args.Aggregate((gcd, arg) => GCD(gcd, arg));\n}	0
14025322	14022825	Serialization settings for MongoDB	public class Car\n{\n    public string Brand;\n\n    public string Model;\n\n    [BsonIgnore]\n    public double Price;\n}	0
23191345	23164276	How to set Count function field of select query in crystal report detail section?	Count ({Table.Value})	0
23886164	23886032	how to change a image size in C#	public static Image resizeImage(Image imgToResize, Size size)\n{\n   return (Image)(new Bitmap(imgToResize, size));\n}\n\nyourImage = resizeImage(yourImage, new Size(1280,1280));	0
4467581	787279	Is this a good way to factor DragDrop logic out of a control?	private void HandleMouseDown(object sender, MouseEventArgs e) \n{ \n    dragState.MouseMove(new Point(e.X,e.Y), (d,e) => DoDragDrop(d,e)); \n}	0
10237275	10131568	Go to insert mode when DetailsView has no data	Listview.ChangeMode(FormViewMode.Edit);	0
9165530	9165255	Primary Video Controller	private static string GetVideoControllerDescription()\n    {\n        Console.WriteLine("GetVideoControllerDescription");\n\n        var s1 = new ManagementObjectSearcher("select * from Win32_VideoController");\n        foreach (ManagementObject oReturn in s1.Get())\n        {\n            var desc = oReturn["AdapterRam"];\n            if ( desc == null) continue;\n            return oReturn["Description"].ToString().Trim();\n        }\n        return string.Empty;\n    }	0
31746241	31745450	Escape Sequence Issue with File Path: \ is stored as \\	RegistryKey rkApp =\n            Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n\n            if (rkApp.GetValue("MyTestRun_Key_Value") == null)\n            {\n                checkbox1.Checked = false;\n            }\n\n            else\n            {\n                checkbox1.Checked = true;\n            }	0
20864170	20864055	C# - insert values from file into two arrays	string[] lines = File.ReadAllLines("sample.txt");\nList<string> list1 = new List<string>();\nList<string> list2 = new List<string>();\n\nforeach (var line in lines)\n{\n    string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n    list1.Add(values[0]);\n    list2.Add(values[1]);\n }	0
6203866	6203823	Notes Document as an objects in array	List<t>	0
24761580	24749318	Calculate correct cursor position with pan and zoom	private void panel1_Paint(object sender, PaintEventArgs e)\n{\n    using (Bitmap bmp = new Bitmap(filename))\n    {\n        e.Graphics.ScaleTransform(zoom, zoom);\n        e.Graphics.DrawImage(bmp, trb_offsetX.Value, trb_offsetY.Value);\n    }\n}\n\nfloat zoom = 1f;\n\nprivate void panel1_MouseMove(object sender, MouseEventArgs e)\n{\n\n  Point mouseLocation = e.Location;\n  Point imageLocation = new Point((int)((mouseLocation.X / zoom - trb_offsetX.Value)),\n                                  (int)((mouseLocation.Y / zoom - trb_offsetY.Value)));\n\n   st_mousePos.Text = "   "  +  imageLocation.ToString();\n\n}\n\n\nprivate void trackBar1_Scroll(object sender, EventArgs e)\n{\n    zoom = trackBar1.Value;\n    panel1.Invalidate();\n}	0
14777848	14776940	XML Application Settings Path	Properties.Settings.Default.Upgrade();\n        Properties.Settings.Default.Save();\n        label1.Text = Properties.Settings.Default.Option1;	0
22396696	22396660	How do I save a screen capture in memory and use Ctrl+P to paste it on other application (e.g Outlook)	Clipboard.SetImage(m_memoryImage);	0
11348583	11348493	Resizing a 3D array	Array.Copy	0
17868026	17867757	Adding zero numbers to my decimal value	var myValue = 5.3;\nlblTotal.Text = myValue.ToString("0.000");	0
13046377	13046211	Dynamic Linq Datetime where	var z = queryResults\n            .Where(result => result.DateTime >= sr.FromDate)\n            .ToDictionary(g => g.FirstOrDefault().ServiceInstanceId, g => g.ToList());	0
26118781	26113947	Open Outlook from WPF Application	var url = "mailto:foo@bar.com?subject=Test&body=Hello";\nSystem.Diagnostics.Process.Start(url);	0
22165835	22165305	Entering value into Excel sheet at particular location only thru linq to excel in c#	public class Demo\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public string Status { get; set; }\n}\n\nstring pathToExcelFile = @"path\to\file.xslx";  \nstring sheetName = "Tabelle1";\n\nvar excelFile = new ExcelQueryFactory(pathToExcelFile);\n    //strongly type the result\nDemo rowToUpdate = (from xc in excelFile.Worksheet<Demo>(sheetName) \n                   where xc.ID == 1\n                   select xc).FirstOrDefault();\n    //update retrieved record\nrowToUpdate.Status = "Active";\n    //output in linqpad\nrowToUpdate.Dump();\n    //no submitchanges or save method available :(	0
27759260	27758837	C# ZipOutputStream getting invalid files from output stream	public static byte[] CompressToZip(List<Tuple<byte[], string>> fileItemList, int zipLevel = 3)\n    {\n        MemoryStream zipMemoryStream = new MemoryStream();\n        ZipOutputStream zOutput = new ZipOutputStream(zipMemoryStream);\n        zOutput.SetLevel(zipLevel);\n        ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();\n        foreach (var file in fileItemList)\n        {\n            ZipEntry entry = new ZipEntry(file.Item2);\n            entry.DateTime = DateTime.Now;\n            zOutput.PutNextEntry(entry);\n            var memStreamCurrentfile = new MemoryStream(file.Item1);\n            StreamUtils.Copy(memStreamCurrentfile, zOutput, new byte[4096]);\n            zOutput.CloseEntry();\n        }\n        zOutput.IsStreamOwner = false;\n        zOutput.Finish();\n        zOutput.Close();\n        zipMemoryStream.Position = 0;\n\n        byte[] zipedFile = zipMemoryStream.ToArray();\n        return zipedFile;\n    }	0
24195012	24194826	Convert Binary string to Hex string without losing leading zeros	Convert.ToInt32(value,2).ToString("X3")	0
18007998	18006361	Recursively update values based on rows parent id SQL Server	create procedure usp_temp_update\n(\n  @id int,\n  @value int = 1\n)\nas\nbegin\n    with cte as (\n        -- Take record\n        select t.id, t.parentid from temp as t where t.id = @id\n        union all\n        -- And all parents recursively\n        select t.id, t.parentid\n        from cte as c\n            inner join temp as t on t.id = c.parentid\n    )\n    update temp set\n        cnt = cnt + @value\n    where id in (select id from cte)\nend	0
11683004	11682668	Countdown after clicking a button that goes from 10 to 0 setting text on a label C#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n        timer1.Enabled = false; // Wait for start\n        timer1.Interval = 1000; // Second\n        i = 10; // Set CountDown Maximum\n        label1.Text = "CountDown: " + i; // Show\n        button1.Text = "Start";\n    }\n\n    public int i;\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        // Switch Timer On/Off\n        if (timer1.Enabled == true)\n        { timer1.Enabled = false; button1.Text = "Start"; }\n        else if (timer1.Enabled == false)\n        { timer1.Enabled = true; button1.Text = "Stop"; }\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n        if (i > 0)\n        {\n            i = i - 1;\n            label1.Text = "CountDown: " + i;\n        }\n        else \n        { timer1.Enabled = false; button1.Text = "Start"; }\n    }\n}	0
14664845	14664767	Get all themes in solution	var path = Server.MaPPath("~/App_Themes");\nvar list = Directory.GetDirectories(path)\n                    .Select(folder => new DirectoryInfo(folder).Name)\n                    .ToList();	0
31911494	31911385	Why some variable in a new form i'm getting warning that they are never assigned?	void Main()\n{\n    Foo f1 = new Foo("good",6);\n    Foo f2;\n    string temp_string;\n\n    // You can do this\n    temp_string = f1.S;\n    // Bot not this\n    // temp_string = f2.S; --> Use of unassigned local variable 'f2'\n\n    // You can also do this: \n    int temp_int = Foo.I;\n    // But  not\n    // temp_int = f1.I; \n\n    // You can do\n    bool b = TestFoo(f1);\n    // But not\n    // b = TestFoo(f2); --> Use of unassigned local variable 'f2'\n}\n\npublic class Foo {\n    // static class property, can be accessed with "Foo.I"\n    public static int I {get; set;}\n\n    // instance property, can be accessed with "f1.S"\n    public string S { get; set; }\n\n    public Foo(string s, int i = 0) {\n        S = s;\n        I = i;\n    }\n}\n\npublic bool TestFoo(Foo foo) {\n    return foo != null;\n}	0
2684037	2683996	Convert 64bit Binary to Long equivalent	long l = Convert.ToInt64(bin,2);	0
19876957	19874602	How can i sign soap headers in WCF client	[MessageHeader(ProtectionLevel=System.Net.Security.ProtectionLevel.Sign)]	0
5376835	5376785	Get all properties for a class name using reflection	_Type.SingleOrDefault(t => t.Name == "CLASS_NAME").GetProperties();	0
25835377	25835323	How can I write RSS reader for windows phone 8.1?	public async void GetRSS()\n{\n    HttpClient httpClient = new HttpClient();\n    var rssContent = await httpClient.GetStringAsync("http://teknoseyir.com/feed");\n\n    var RssData = from rss in XElement.Parse(rssContent).Descendants("item")\n                  .....\n                  .....\n\n    RssList.ItemsSource = RssData;\n}	0
17325593	17208089	Finding the searched text in google search result with selenium webdriver in Chrome	IWebDriver driver = new ChromeDriver();\ndriver.Navigate().GoToUrl("http://google.com");\n\nIWebElement element = driver.FindElement(By.Id("gbqfq"));\nelement.SendKeys("selenium webdriver");\n\n// Get the search results panel that contains the link for each result.\nIWebElement resultsPanel = driver.FindElement(By.Id("search"));\n\n// Get all the links only contained within the search result panel.\nReadOnlyCollection<IWebElement> searchResults = resultsPanel.FindElements(By.XPath(".//a"));\n\n// Print the text for every link in the search results.\nforeach (IWebElement result in searchResults)\n{\n    Console.WriteLine(result.Text);\n}	0
7902140	7902095	How to pass values between two pages in WPF	string myText = (string)Application.Current.Properties["test"];	0
28774314	10803706	Get the AppDomain of object	public static int GetObjectAppDomain(object proxy)\n{\n    RealProxy rp = RemotingServices.GetRealProxy(proxy);\n    int id = (int)rp.GetType().GetField("_domainID", BindingFlags.Instance|BindingFlags.NonPublic).GetValue(rp);\n    return id;\n}	0
9023595	9022563	Retrieve a positive or a negative angle from 3 points	double v1x = Xb - Xc;\ndouble v1y = Yb - Yc;\ndouble v2x = Xa - Xc;\ndouble v2y = Ya - Yc;\n\ndouble angle = Math.atan2(v1x, v1y) - Math.atan2(v2x, v2y);	0
30121787	30121334	How to find the last item from list have the same item using linq	public class SOProblem1\n{\n    public static void Main()\n    {\n        var records = new List<Record>\n        {\n            new Record {recordID = "1", recordName = "name1"},\n            new Record {recordID = "2", recordName = "name2"},\n            new Record {recordID = "3", recordName = "name3"},\n            new Record {recordID = "4", recordName = "name4"},\n            new Record {recordID = "1", recordName = "name1"},\n            new Record {recordID = "2", recordName = "name2"},\n            new Record {recordID = "3", recordName = "name3"}\n        };\n\n        var t = records.GroupBy(x => x.recordID);\n\n        foreach (var record in t)\n        {\n            Console.WriteLine(record.Last().recordName);\n        }\n\n        Console.ReadKey();\n    }\n}\n\npublic class Record\n{\n    public string recordID { get; set; }\n\n    public string recordName { get; set; }\n}	0
4453536	4453436	code translation: repeating a string until some maximum	string text = "hello, world";\nStringBuilder builder = new StringBuilder(BIGSTRINGLEN);\nwhile (builder.Length + text.Length <= BIGSTRINGLEN) {\n    builder.Append(text);\n}\nstring result = builder.ToString();	0
11271337	11271094	Get Directories with Parallel ForEach	public string[] RecurseFolders(string dirString) {\n      List<string> list = new List<string>();\n      DirectoryInfo nodeDir = new DirectoryInfo(dirString);\n      Parallel.ForEach(nodeDir.GetDirectories(), dir => {\n//Just continue writing here. This is an Action. Google it for more info. But for the purposes of this example you may consider it as method which will be called for each of the items\n      });\n      return list.ToArray();\n    }	0
4369749	4369720	How to restrict a program to a single instance	static void Main()\n  {\n     string mutex_id = "MY_APP";\n     using (Mutex mutex = new Mutex(false, mutex_id))\n     {\n        if (!mutex.WaitOne(0, false))\n        {\n           MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\n           return;\n        }\n        // Do stuff\n     }\n  }	0
11321384	11321123	Generate an image/email attachment with a chart in C#	chartObject.SaveAs("file.png", ChartImageFormat.Png);	0
10104571	10104526	Lambda Expression for Latest Date	var latest = model.OrderByDescending(m => m.Date).FirstOrDefault();	0
15299226	15299145	Drawing onto a picturebox in a Windows Form from a different class	public MyRectangles(Graphics g, int x, int y)\n{\n    Pen p = new Pen(Color.Turquoise, 2);\n    Rectangle r = new Rectangle(x, y, 5, 5);\n    g.DrawRectangle(p, r);\n    p.Dispose();\n}	0
29042897	29042818	How can i use a variable from form1 with a User Control?	public partial DopplerEffect : UserControl \n{\n    private string m_nextFile;\n\n    public string NextFile\n    {\n        get { return m_nextFile; }\n        set \n        { \n           m_nextFile = value; \n           DoSomethingWithNextFile(); // do loading of your image\n        }\n    }\n\n    public DopplerEffect() { ... }\n}	0
24126380	24126235	Handling checkbox values being modified from 'true'	public ActionResult Survey()\n{\n    return View(new Survey());\n}\n\n[HttpPost]\npublic ActionResult Survey(Survey model)\n{\n    //do something worthwhile with the model, like validation, etc. etc.\n\n    //even setting the model's boolean doesn't help the rendering.\n    model.LikesCandy = true;\n\n    //clear model state so that the change on the line above is applied\n    ModelState.Clear();\n\n    //then return to the page\n    return View(model);\n}	0
15985824	15985791	How to track logout details when browser is closed explicitly without Logout using ASP.Net	UpdateLastVisited(this.User)\n                {  \n                       "UPDATE [dbo].[User] set LastVisited = @date WHERE Id = @userId";\n                        AddParameters etc..\n                 }	0
9677313	9677304	C# DateTime Convert or Parse specific format?	DateTime.ParseExact(yourString, "d MMMM yyyy", new CultureInfo("en-US"))	0
3667690	3666660	Custom validation through Web-method	PageMethods.ValidateLogin(login,OnRequestComplete, OnRequestError);	0
5145419	4740969	How to databind a gridview to an ExpandoObject	IEnumerable<dynamic> tProxiedObject = listOfExpandos.Select(x=>Impromptu.ActLikeProperties(x, x.ToDictionary(k=>k.Key,v=>typeof(object))));	0
10724109	10723269	Problems while converting characters in a XmlText node (From &#39; to &amp;#39)	using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing System.Xml;       \n\nnamespace TestProject1\n{\n    [TestClass]\n    public class UnitTest1\n    {\n        private const string testString = "Surfin&#39; USA";\n        [TestMethod]\n        public void TestMethod1()\n        {\n            XmlDocument xmlDoc = new XmlDocument();\n            XmlText xmlMyText;\n\n            xmlMyText = xmlDoc.CreateTextNode(testString);\n\n            Assert.AreEqual(testString, xmlMyText.InnerText);\n\n        }\n    }\n}	0
10809059	10796815	LINQtoSQL LEFT JOIN on 1 to 1 relation, method-based	customer\n.invoices\n.OrderByDescending(i => i.Date)\n.GroupJoin(context.Orders,\n    invoice => invoice.OrderID,\n    order => order.OrderID,\n    (invoice, orders) => new\n    {\n        invoice = invoice,\n        OrderNotes = orders.SingleOrDefault()==null?"":orders.SingleOrDefault().Notes\n    })\n.ToList()	0
12123738	12123630	Passing key/value anonymous object as parameter	public static string TestFunction(object obj)\n{\n    //To dictionary\n    //var dict = obj.GetType().GetProperties()\n    //                .ToDictionary(p=>p.Name,p=>p.GetValue(obj,null));\n\n    //Directly ToString\n    string result = String.Join(",", obj.GetType().GetProperties()\n                                        .Select(p=>p.Name + ":" + p.GetValue(obj,null)));\n\n    return result;\n}	0
11672844	11671043	Finding matches between high quality and low quality, pixelated images - is it possible ? How?	badness := 0.0\nFor x, y over the entire image:\n  r, g, b := color at x,y in image 1\n  R, G, B := color at x,y in image 2\n  badness += (r-R)*(r-R) + (g-G)*(g-G) + (b-B)*(b-B)\nbadness /= (image width) * (image height)	0
33953678	33952804	How do i get data from records in C# MVC	var model = iDConfig.Select(ic => new iDealModel {\n        SaPrefix = ic.PrefixSA,\n        CalendarCode = ic.CodeCalendar,\n        CashnCarry = ic.isCashnCarry,\n        FreeMM = ic.isFreeMM,\n        OnContract = ic.isOnContract,\n        ProductId = ic.Product,\n        RequestTypeId = ic.RequestType\n    });	0
5821674	5820646	How to pass an object to a web service in .web project from silverlight project?	[DataContract]\npublic class Person\n{\n    [DataMember]\n    public string FirstName;\n\n    [DataMember]\n    public string LastName;\n}	0
5747542	5747061	Regular Expression For Alphanumeric String With At Least One Alphabet Or Atleast One Numeric In The String	if (Regex.IsMatch(subjectString, @"\n    # Match string having one letter and one digit (min).\n    \A                        # Anchor to start of string.\n      (?=[^0-9]*[0-9])        # at least one number and\n      (?=[^A-Za-z]*[A-Za-z])  # at least one letter.\n      \w+                     # Match string of alphanums.\n    \Z                        # Anchor to end of string.\n    ",\n    RegexOptions.IgnorePatternWhitespace)) {\n    // Successful match\n} else {\n    // Match attempt failed\n}	0
2776339	2775524	using STI and ActiveRecordBase<> with full FindAll	[ActiveRecord("companies", \n  DiscriminatorColumn="type", \n  DiscriminatorType="String", \n  DiscriminatorValue="NA")]\npublic abstract class Company : ActiveRecordBase<Company>, ICompany {\n    [PrimaryKey]\n    private virtual int Id { get; set; }\n\n    [Property]\n    public virtual String Name { get; set; }\n}\n\n[ActiveRecord(DiscriminatorValue="firm")]\npublic class Firm : Company {\n    [Property]\n    public virtual string Description { get; set; }\n}\n\n[ActiveRecord(DiscriminatorValue="client")]\npublic class Client : Company {\n    [Property]\n    public virtual int ChargeRate { get; set; } \n}\n\nvar allClients = ActiveRecordMediator<Client>.FindAll();\nvar allCompanies = ActiveRecordMediator<Company>.FindAll(); // Gets all Companies (Firms and Clients). Same as Company.FindAll();	0
6526737	6523973	asp.net user control displays with different font size	table p {\n   font-size: 70%\n}	0
26890281	26889898	Get current line width in OpenTK	float currentLineWidth = GL.GetFloat(GetPName.LineWidth);	0
16287130	16287051	How can I programmatically create a ListView full of strings containing columns and rows in WPF using C#?	GridView myGridView = new GridView();\nmyGridView.AllowsColumnReorder = true;\n\nGridViewColumn gvc1 = new GridViewColumn();\ngvc1.DisplayMemberBinding = new Binding("ColumnOneHeader");\ngvc1.Header = "Column One Header";\ngvc1.Width = 100;\nmyGridView.Columns.Add(gvc1);\nGridViewColumn gvc2 = new GridViewColumn();\ngvc2.DisplayMemberBinding = new Binding("Column2Header");\ngvc2.Header = "Column 2 Header";\ngvc2.Width = 100;\nmyGridView.Columns.Add(gvc2);\nGridViewColumn gvc3 = new GridViewColumn();\ngvc3.DisplayMemberBinding = new Binding("ColumnThreeHeader");\ngvc3.Header = "Column Three Header";\ngvc3.Width = 100;\nmyGridView.Columns.Add(gvc3);\n\n\nlistView.View = myGridView;	0
28809882	28809816	How can i Sort a List<Tuple<int, double>>	Ratings = Ratings.OrderByDescending (t => t.Item2).ToList();	0
3762370	3762113	How can an UIntPtr object be converted to IntPtr in C#?	IntPtr intPtr = unchecked((IntPtr)(long)(ulong)uintPtr);	0
23470418	23468241	C# - How to download SOAP Attachment using ResponseSoapContext	Stream stream = ws.ResponseSoapContext.Attachments[0].Stream;    \n\n                //XmlTextReader reader = new XmlTextReader(stream);\n\n                StreamReader sr = new StreamReader(stream);\n\n                wsXmlOutput = sr.ReadToEnd();	0
7036993	7036953	Allowed Menustrip only one child at moment	private Lordre orderForm = null;\nprivate void ordresToolStripMenuItem_Click(object sender, EventArgs e)\n{\n    if (orderForm == null)\n        orderForm = new Lordre(ClientId);\n        // Set the Parent Form of the Child window.\n        orderForm .MdiParent = this;\n\n    }\n    // Display the form.\n    orderForm.Show(); \n    orderForm.Activate();\n}	0
33762151	33738864	Opening Master page from MasterDetailPage	MasterDetailPageVariable.isPresented = true;	0
25569768	25569675	FInding a letter in VB script	Dim x\nx = InStr(account2, "T")\nIf x > 0 Then\n    account2 = "3" & Mid(account2, x + 2)\n    'probably not a good idea to read the next line here\nEnd If\nx = InStr(account2, "M")\nIf x > 0 Then\n    account2 = "2" & Mid(account2, x + 1)\nEnd If	0
27255750	27254173	C# generic handler query string parameters in array	var searchString = context.Request["search[value]"];\n\nvar sortColumnIndex = Convert.ToInt32(context.Request["order[0][column]"]);\nvar sortDirection = context.Request["order[0][dir]"]; // asc or desc	0
12554814	12554721	Attributes and XML Documentation for method/property	/// <summary>\n/// Something here\n/// </summary>\n[MyAttribute]\npublic void MyMethod() {}	0
10525863	10525440	Checkbox in a column Grid	grid.Column(\n    header: "Active",\n    format: (col) => @Html.Raw("<input type='checkbox' checked='" + ((col.Active) ? "checked" : "") + "' disabled='true' />")\n)	0
5284162	5283993	How to hide Non-CLS compliant code from projects using other languages?	public static class Interop {\n    public static void Print2(SecurityService obj) {\n        obj.PRINT();\n    }\n}	0
9465409	9389154	How to post the data from ASCX javascript to the same ascx control?	xhr.open('POST', '../Controls/test1.ashx?Id=' + '<%=Id%>', true);	0
25508365	25507898	how to add a new field if a option from combobox is selected	private void cbxOptions_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        pnlFurtherOptions.Visible = (cbxOptions.SelectedIndex == 1);\n    }	0
20747018	20746715	Insert command on row from .SelectedRow	da.InsertCommand = new OleDbCommand("INSERT INTO UserProfile (UserName) VALUES (@UserName)", conn);\n        {\n          string usrName =  Convert.ToString(Add_Usertoprof.SelectedRow.Cells[0].Text); //whatever your cell num is \n          da.InsertCommand.Parameters.AddWithValue("@UserName", usrName);\n        }\n        conn.Open();\n\n        da.InsertCommand.ExecuteNonQuery();\n\n        conn.Close();	0
15916865	15898458	DLLImport fails to find the DLL file	class Caller\n{\n    [DllImport("kernel32.dll")]\n    private extern static IntPtr LoadLibrary(String path);\n    [DllImport("kernel32.dll")]\n    private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);\n    [DllImport("kernel32.dll")]\n    private extern static bool FreeLibrary(IntPtr lib);\n\n    private IntPtr _hModule;\n\n    public Caller(string dllFile)\n    {\n        _hModule = LoadLibrary(dllFile);\n    }\n\n    ~Caller()\n    {\n        FreeLibrary(_hModule);\n    }\n\n    delegate string VersionFun();\n\n    int main()\n    {\n        Caller caller = new Caller("abcdef.dll");\n        IntPtr hFun = GetProcAddress(_hModule, "Version");\n        VersionFun fun = Marshal.GetDelegateForFunctionPointer(hFun, typeof(VersionFun)) as VersionFun;\n        Console.WriteLine(fun());\n\n        return 0;\n    }\n}	0
21466929	21466837	How to pass a string to a VB.NET project's function that is referenced by a C# website?	var commandText = "ProcedureName";\nvar commandType = CommandType.StoredProcedure;\nsqlTool.GetScalar(ref commandText, ref commandType);	0
18957767	18957707	Asp.Net set format text for DropDownList	ddl_dat.DataTextFormatString="{0: ddd d/MM/yyyy HH:mm}";	0
17529388	17455052	how to set the value of a json path using json.net	public string SetPreference(string username, string path, string value)\n    {\n        if (!value.StartsWith("[") && !value.StartsWith("{"))\n            value = string.Format("\"{0}\"", value);\n\n        var val = JObject.Parse(string.Format("{{\"x\":{0}}}", value)).SelectToken("x");\n\n        var prefs = GetPreferences(username);\n\n        var jprefs = JObject.Parse(prefs ?? @"{}");\n\n        var token = jprefs.SelectToken(path) as JValue;\n\n        if (token == null)\n        {\n            dynamic jpart = jprefs;\n\n            foreach (var part in path.Split('.'))\n            {\n                if (jpart[part] == null)\n                    jpart.Add(new JProperty(part, new JObject()));\n\n                jpart = jpart[part];\n            }\n\n            jpart.Replace(val);\n        }\n        else\n            token.Replace(val);\n\n        SetPreferences(username, jprefs.ToString());\n\n        return jprefs.SelectToken(path).ToString();\n    }	0
20675228	20675106	How to calculate the number of months between two dates in C#	12 * (date1.Year - DateOfDeposit.Year) + (date1.Month - DateOfDeposit.Month)	0
6779472	6779445	how to make a webbrowser control go blank in c#?	webBrowser1.Navigate("about:blank");	0
7332470	7331865	How to compare column names from entity framework to content of class fields?	PropertyInfo pi = seatsRow.GetType().GetProperty(*columnName*);\n            pi.SetValue(seatsRow, *value*, null);	0
32485854	32485550	How to set http request queue length when self hosting webapi?	netsh http show servicestate	0
11202004	11201784	Can't cast derived type to base abstract class with type parameter	interface IWheel\n{\n}\n\nclass CarWheel : IWheel\n{\n}\n\ninterface IVehicleBase<T> \n{\n}\n\nclass Car : IVehicleBase<CarWheel>\n{\n}\n\nclass VehicleFactory\n{\n    public static IVehicleBase<T> GetNew<T>() \n    {\n        if (typeof(T) == typeof(CarWheel))\n        {\n            return (IVehicleBase<T>)new Car();\n        }\n        else\n        {\n            throw new NotSupportedException();\n        }\n    }\n}	0
25983328	25983327	Dynamically read the value of configSource from connectionStrings in ASP.NET	ConnectionStringsSection connectionStringsSection = \n      System.Web.Configuration.WebConfigurationManager\n     .GetSection("connectionStrings", "/Web.config") as ConnectionStringsSection;\nstring configSource = connectionStringsSection.SectionInformation.ConfigSource;	0
2187118	2186861	String was not recognized as a valid DateTime ParseExact	DateTime parsed = DateTime.ParseExact(\n    "Tue Feb 16 12:36:41 CST 2010".Replace("CST", "+02:00"), \n    "ddd MMM dd HH:mm:ss zzz yyyy",\n    new CultureInfo("en-GB"));	0
17181008	17180657	Match groups of elements in a list to all elements of a dictionary	var result = userSkills.AsEnumerable()\n      .GroupBy(userRow => userRow.Field<int>("UserId"))\n      .Where(userGroup => userGroup\n                .Join(skillList,\n                      user => new { sID = user.Field<int>("SkillId"), slID = user.Field<int>("SkillLevelId") },\n                      skill => new { sID = skill.Key, slID = skill.Value },\n                      (user, skill) => true).Count() == skillList.Count())\n      .Select(match => new { userID = match.Key });	0
29144475	29144187	Conversion of DataTable to Dictionary<String,StringBuilder>	datatable.AsEnumerable()\n          .GroupBy(r => (string)r["Name"])\n          .Select(g => new\n            {\n                Key = g.Key,\n                // Preferred Solution\n                Value = new StringBuilder(\n                             g.Select(r => string.Format("{0}, {1}, {2}",   \n                                      r["Value"], r["Type"], r["Info"]))\n                                 .Aggregate((s1, s2) => s1 + "?:" + s2))                    \n                /*\n                //as proposed by juharr\n                Value = new StringBuilder(string.Join("?:", g.Select( r => string.Format("{0}, {1}, {2}", r["Value"], r["Type"], r["Info"]))))\n                */\n            })\n          .ToDictionary(p => p.Key, p => p.Value);	0
4301982	4301770	How to show MessageBox on asp.net?	Type cstype = this.GetType();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager cs = Page.ClientScript;\n\n// Check to see if the startup script is already registered.\nif (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))\n{\n    String cstext = "alert('Hello World');";\n    cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);\n}	0
14248276	14247921	How to return oracle output parameters from a stored procedure in .NET	ora_cmd.Parameters.Add("Lc_Exito", OracleDbType.Int32).Direction = ParameterDirection.Output;\n\nora_cmd.ExecuteNonQuery();\n\nif (ora_cmd.Parameters["Lc_Exito"].value == 0)	0
10206242	10206177	How do tsql query in linq	var t = from u in table\n               where new[] { 5, 7, 8 }.Contains(u.id)\n               select u	0
20101880	20101650	Convert SQL to Lambda Expression with one to many relationships	var result = from profile in db.PatientProfile.Include(p => p.Visit)\n             from visit in profile.Visits\n             select new\n                    {\n                        profile.PatientLastName,\n                        visit.VisitId,\n                        visit.VisitDate,\n                        visit.EndVisitDate\n                    };	0
8887910	8875246	Silverlight Bing Map with bindable amount of MapItemsControl	public class SpecialLayer : MapLayer\n{\n    public static readonly DependencyProperty ItemsSource ... \n    OnPropertyChanged(...) \n    {\n        var layer = sender as SpecialLayer;\n        foreach(Object in Routes){\n            layer.Add(new Pushpin(...));\n        }\n    }\n}	0
34109056	34108872	Reflection between projects based on attributes	static IEnumerable<Type> TypesWithAttribute(Assembly a, string attributeName )\n{\n  return\n    a\n    .GetTypes( )\n    .Where\n    (\n      t =>\n        Attribute\n        .GetCustomAttributes( t )\n        .Any\n        (\n          att =>\n          att.GetType( ).Name == attributeName\n      ) \n    );\n}	0
197326	197302	How to: unset variable in C#?	MyType myvar = default(MyType);\nstring a = default(string);	0
16164279	16156217	Wrap in an element with HtmlAgilityPack?	HtmlDocument doc = new HtmlDocument();\ndoc.Load(MyTestHtm);\nHtmlNode body = doc.DocumentNode.SelectSingleNode("//body");\nif (body == null)\n{\n    HtmlNode html = doc.DocumentNode.SelectSingleNode("//html");\n    // we presume html exists\n\n    body = CloneAsParentNode(html.ChildNodes, "body");\n}\n\n\nstatic HtmlNode CloneAsParentNode(HtmlNodeCollection nodes, string name)\n{\n    List<HtmlNode> clones = new List<HtmlNode>(nodes);\n    HtmlNode parent = nodes[0].ParentNode;\n\n    // create a new parent with the given name\n    HtmlNode newParent = nodes[0].OwnerDocument.CreateElement(name);\n\n    // insert before the first node in the selection\n    parent.InsertBefore(newParent, nodes[0]);\n\n    // clone all sub nodes\n    foreach (HtmlNode node in clones)\n    {\n        HtmlNode clone = node.CloneNode(true);\n        newParent.AppendChild(clone);\n    }\n\n    // remove all sub nodes\n    foreach (HtmlNode node in clones)\n    {\n        parent.RemoveChild(node);\n    }\n    return newParent;\n}	0
17099783	17080971	Update DataGridView based on Combobox value	db.Dispose();\ndb = new UniformDataContainer();\nint id = Convert.ToInt32(textBox1.Text);\ndb.Items.Where(i => i.TransactionId == id).Load();\nbs.DataSource = db.Items.Local.ToBindingList();	0
3956307	3956256	Data Transfer Object (DTO) to DisplayObject (DO) - How to flatten DTO's into a DO collection property	from x in DTOs\ngroup new DataValue() {MonthPeriod = x.Month, Data = x.Data}\n  by new {Product = x.Product, Location = x.Location}\n  into g\nselect new DO()\n{\n  product = g.Key.Product,\n  location = g.Key.Location,\n  value = g.ToList()\n};	0
3192424	3013692	getting windows username with javascript	string winlogon = Request.ServerVariables["LOGON_USER"];	0
11866245	11866171	Change the length of FileStream in c#	Stream.SetLength	0
25354206	25286160	Entity Framework: Ambiguous match found	public partial class customers\n{\n    public enum CustomerStatusEnum : long\n    {\n        Closed = 3,\n        Open = 1,\n        Potential = 2\n    }\n\n    public CustomerStatusEnum CustomerStatus\n    {\n        get\n        {\n            return (CustomerStatusEnum)Status;\n        }\n    }\n}	0
34475157	34474938	JSON.net format output like I need	string finalJSON = "";\n\ntry\n{\n   connection.Open();\n   command = new SqlCommand(sql, connection);\n   SqlDataReader read = command.ExecuteReader();\n\n   // Create a new object that matches the structure of the JSON file.\n   var root = new RootObject\n   {\n       DATA = new DATA { clocked = new List<Clocked>() }\n   };\n\n   while (read.Read())\n   {\n      root.DATA.firstName = read["firstName"].ToString();\n      root.DATA.lastName = read["lastName"].ToString();\n      // Continue with the other attributes...\n      root.DATA.clocked.Add(new Clocked {date = read["date"].ToString(), type = read["type"].ToString() });\n   }\n\n   // Serialize the object using JSON.Net.\n   finalJSON = JsonConvert.SerializeObject(root);\n\n   read.Close();\n   command.Dispose();\n   connection.Close();\n}	0
3135608	3135569	How to change symbol for decimal point in double.ToString()?	Console.WriteLine(value.ToGBString());\n\n// ...\n\npublic static class DoubleExtensions\n{\n    public static string ToGBString(this double value)\n    {\n        return value.ToString(CultureInfo.GetCultureInfo("en-GB"));\n    }\n}	0
28771288	28771214	Retrieve some text from sql	Request.Querystring("id")	0
19936817	19936561	ToString() filling Decimal number with zeroes at the right	.ToString("G29")	0
11552051	11551915	Is there anyway to access this textblock?	void GamesListBox_SelectionChanged(object sender, EventArgs e)\n{\n    var myObject = GamesListBox.SelectedItem as MyObject;\n    string gameName = myObject.AllGamesTitle;\n    // Do something with gameName\n}	0
10169692	10169557	Split C# MultiSelectList into smaller ones using LINQ	var multiSelectList= new MultiSelectList(new List<string>()); //your mutli-select list\nvar multiSelectListGroupedByValue=ms.GroupBy(x => x.Value)\n                                  .Select(x=>new MultiSelectList(x.Select(y=>y.Value)));	0
7833915	7833845	Error connecting to Amazon EC2 MySQL from C#	l_DBConn.open()	0
6550342	6550302	How to parse XML contained in a string to an IList<BusinessObject>?	XDocument doc = XDocument.Load(...);\nvar businessObjects = doc.Descendants("Row")\n                         .Select(x => new BusinessObject {\n                                     Id = (int) x.Element("id"),\n                                     Name = (string) x.Element("name")\n                                 })\n                         .ToList();	0
2451658	2451453	TwoWay Binding to ListBox SelectedItem on more than one list box in WPF	public Object SelectedObject\n{\n    get\n    {\n        return _selectedObject;\n    }\n    set\n    {\n        if (value != _selectedObject)\n        {\n            //HACK\n            //Pulse 'null' between changes to reset listening list controls\n            if (value != null)\n                SelectedObject = null;\n\n            if (_selectedObject != null)\n                SelectedObjects.Remove(_selectedObject);\n\n            _selectedObject = value;\n            if (value != null)\n                SelectedObjects.Add(value);\n        }\n    }\n}	0
15075933	15073565	How to stop EntityFramework migrations from creating my schema automatically?	Database.SetInitializer<MyContext>(null);	0
34435029	34434616	How to Find 5th or ending date of a particular day in a month based on date of the same month	DateTime dayInMonth = DateTime.Now;\n DayOfWeek dayToFind = DayOfWeek.Friday;\n\n var fifth= Enumerable.Range(1, DateTime.DaysInMonth(dayInMonth.Year, dayInMonth.Month))\n            .Select(day => new DateTime(dayInMonth.Year, dayInMonth.Month, day))\n            .Where(day => day.DayOfWeek == dayToFind)\n            .Skip(4)\n            .FirstOrDefault();	0
30564490	30563828	Entity Framework AddOrUpdate implementation	var equalityExpr = Expression.Equal(identifierExpression.Body, Expression.Constant(id));\nvar findMatchExpr = Expression.Lambda<Func<TEntity, bool>>(equalityExpr, identifierExpression.Parameters);\nvar persistedEntity = set.FirstOrDefault(findMatchExpr);	0
10810003	10809976	Can I combine these two C# functions into one?	protected SelectList GetReferenceOptions(string pk, string value = null)\n{\n    var options = new SelectList(_reference.Get(pk)\n        .AsEnumerable()\n        .OrderBy(o => o.Order), "RowKey", "Value", value);\n    return options;\n}	0
17298786	17298730	Generic base class with multiple children	public class BaseClass<T> {\n    public Subject<T> Results;\n}\n\npublic class ChildA : BaseClass<AssociatedClassA> {\n}\n\npublic class ChildB : BaseClass<AssociatedClassB> {\n}	0
20738522	20738187	searching firstname and lastname from a field containing fullname in linq c#	namelist.Any( n => person.ps_fullname.ToLower().Contains(n.ToLower()))	0
28179439	28176963	Linq to entities query that returns a count and a list of objects	Customer[] CustomerList;\nint CustomerID;\nvar x = CustomerList\n   .Where(r => r.CustomerID == CustomerID)\n   .Select(r => new { \n      OrderCount = r.Orders.Count(), \n      OrderPageList = r.Orders.Skip(500).Take(100).ToArray() });\nint totalCount = x.OrderCount;\nOrder[] orderList = x.OrderPageList;	0
34405975	34405904	Implementation issue with TransformBlock using TPL Dataflow	var transBlock = new TransformBlock<int, Tuple<int,int>>(async n =>\n{\n    await Task.Delay(1000)\n    return Tuple.Create(n, n * 2);\n});\n\n\nvar tuple = transBlock.Receive();\nConsole.WriteLine(string.Format("double for {0} is {1}", tuple.Item1, tuple.Item2));	0
10831975	10831777	how to read a xml file and write into list then get the path for txt file and read it	XmlDocument xml_Document = new XmlDocument();\nxml_Document.Load("C:\\settings.xml");\nvar list = xml_Document.SelectNodes("//LogType [@value='Debug']");\nvar logLocation = list.Item(0).SelectNodes("//FileLocation").Item(0).Value;	0
28365411	28365147	C# / SQLServer: Merge Rows in a table by similar column values	IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'coords1' )\n    BEGIN\n        DROP TABLE dbo.coords1\n    END\n    GO\n\nCREATE TABLE coords1 ( [x] DECIMAL(12,4),  [y] DECIMAL(12,4), [z] DECIMAL(12,4) )\nGO\n\nINSERT INTO coords1 ( x, y, z)\nVALUES(2660000, 1270000, 421.8513),\n(2660000, 1270000, -1415.6297), \n(2660000, 1269960, 421.0372),\n(2660000, 1269960, -1415.7926)\nGO\n\nIF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'coords2' )\nBEGIN\n    DROP TABLE dbo.coords2\nEND\nGO\n\nCREATE TABLE coords2 ( [x] DECIMAL(12,4), [y] DECIMAL(12,4), [ztop] DECIMAL(12,4), [zbase] DECIMAL(12,4) )\nGO\n\nINSERT INTO coords2 ([x], [y], [ztop], [zbase])\nSELECT [x], [y], MAX([z]) AS [ztop], MIN([z]) AS [zbase]\nFROM coords1\nGROUP BY x, y\n\nSELECT * FROM coords2	0
13844185	13843454	Printing List<PictureBox> - One Image per page	int bmpIndex = 0;\nList<Bitmap> bmps = new List<Bitmap>();\n\nvoid pd_BeginPrint(object sender, PrintEventArgs e) {\n  bmpIndex = 0;\n}\n\nvoid pd_PrintPage(object sender, PrintPageEventArgs e) {\n  e.Graphics.DrawImage(bmps[bmpIndex], new Point(e.MarginBounds.Left, \n                                                 e.MarginBounds.Top));\n\n  ++bmpIndex;\n  if (bmpIndex < bmps.Count) {\n    e.HasMorePages = true;\n  }\n}	0
34301120	34301030	Intersect 2 different kinds of collections based on string property of different name	var overlap = empsColl.Where(e => pets.Any(p => p.SocialSecurityNumber == e.SSN)).ToList();	0
9288907	9288308	regex replace matchEvaluator using string Array	string[] phrases = ...\nvar re = String.Join("|", phrases.Select(s => Regex.Escape(s)).ToArray());\ntext = Regex.Replace(re, text, new MatchEvaluator(SomeFunction), RegexOptions.IgnoreCase);	0
26060496	26060237	multithreading program with webrequests c#	private static void Main(string[] args)\n{\n    var urlsAndPaths = new Dictionary<string, string>();\n    urlsAndPaths.Add("http://i.forbesimg.com/media/lists/people/lionel-messi_416x416.jpg","messi.jpg");\n    urlsAndPaths.Add("http://sizzlingsuperstars.com/wp-content/uploads/2014/07/Cristiano-Ronaldo-2-480x309.jpg", "cristiano.jpg");            \n    foreach (var kvp in urlsAndPaths)\n    {\n        var wc = new WebClient();\n        wc.DownloadFileAsync(new Uri(kvp.Key),kvp.Value);\n    }\n    Console.ReadKey();\n}	0
18693302	18693262	Entity Framework: How to set model as Serializable in Entity Framework	[Serializable]\npublic partial class user\n{\n\n}	0
5172430	5172390	Divide a large IEnumerable into smaller IEnumerable of a fix amount of item	var result = items.Select((value, index) => new { Index = index, Value = value})\n                  .GroupBy(x => x.Index / 5)\n                  .Select(g => g.Select(x => x.Value).ToList())\n                  .ToList();	0
27003360	26999943	How to get an object from the webgrid.	UserSearchDisplayModel user = grid.Rows[grid.SelectedIndex].Value;\n    @Html.Partial("_AdminUserDetails", user)	0
5184283	5184250	Will this usage of List<T> be a miracle or a mess	myControl.childControl.Parent	0
29913008	29912905	How to send value from C# to java script on Asp.Net's Button click event?	protected void btnsubmit_Click(object sender, EventArgs e)\n {\n      string abc="xyz";       \n\n      //If the string can contain apostrophes or backslashes, you would need to escape them\n      string value = abc.Replace("\\", "\\\\").Replace("'", "\\'");\n      Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","myfunction('" +value + "')",true);\n }	0
11409560	11409350	Printing SVG-PictureFiles in C# PrintDocument GDI+	//Create a window that matches the desired output bitmap\nSvgWindow window = new SvgWindow(width, height);\nwindow.Src = svgSource;\n\n//Create a GDI renderer for SVG, and use white background\nGdiRenderer gdirender = new GdiRenderer(window, Color.White);\nBitmap bitmap = gdirender.Render();	0
29359244	29343432	How to fetch entity records from CRM	EntityMetadata entityMetaData = retrieveEntityResponse.EntityMetadata;\nfor (int count = 0; count < entityMetaData.Attributes.ToList().Count; count++)\n{\n    if (entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels.Count > 0)\n    {\n        string displayName = entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels[0].Label;\n        string logicalName = entityMetaData.Attributes.ToList()[count].LogicalName;\n        AttributeTypeCode dataType = (AttributeTypeCode)entityMetaData.Attributes.ToList()[count].AttributeType;\n    }\n}	0
14413835	14412186	Read XML file as DataSet	// Here your xml file\nstring xmlFile = "Data.xml";\n\nDataSet dataSet = new DataSet();\ndataSet.ReadXml(xmlFile, XmlReadMode.InferSchema);\n\n// Then display informations to test\nforeach (DataTable table in dataSet.Tables)\n{\n    Console.WriteLine(table);\n    for (int i = 0; i < table.Columns.Count; ++i)\n        Console.Write("\t" + table.Columns[i].ColumnName.Substring(0, Math.Min(6, table.Columns[i].ColumnName.Length)));\n    Console.WriteLine();\n    foreach (var row in table.AsEnumerable())\n    {\n        for (int i = 0; i < table.Columns.Count; ++i)\n        {\n            Console.Write("\t" + row[i]);\n        }\n        Console.WriteLine();\n    }\n}	0
4652013	4651995	how do i force a DLL to be built with the exe so there is only one file?	ilmerge /out:Combined.exe mainFile.exe  otherDll.dll	0
27536244	27536187	Looking for a linq solution to replace a for-loop	mysb.AppendLine(String.Join(Environment.NewLine,\n    files.Select((fi, i) => String.Format(fi.Name, i == 0 ? "FIRST" : "NOTFIRST"))));	0
31092047	31091986	How can I get my C# and MySql to return more than one entry from the database?	movieBox.Items.Clear();\ntry\n{\n    db_connection.Open();\n    sql_command = new MySqlCommand("select * from mov_db.movies where title like '%" + searchBox.Text + "%'", db_connection);\n    sql_reader = sql_command.ExecuteReader();\n    if(sql_reader.HasRows)\n        while(sql_reader.Read())\n        {\n            movieBox.Items.Add(sql_reader.GetString("title"));\n            movieBox.Items.Add(sql_reader.GetString("year"));\n            movieBox.Items.Add(sql_reader.GetString("genre"));\n            movieBox.Items.Add(sql_reader.GetString("rating"));\n        }\n    }\n    else\n    {\n        MessageBox.Show("Sorry, but that title is unavailable.");\n    }\n}	0
20478748	20478183	Append to a string in an infinite iteration inside a windows service	private void DoWork()\n{\n    byte ch ;\n    byte[] data = new byte[1024];\n    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8888);\n    UdpClient newsock = new UdpClient(ipep);\n\n    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);\n\n    StringBuilder sbCardNo = new StringBuilder();\n\n    while (true)\n    {\n        do\n        {\n            data = newsock.Receive(ref sender);\n            ch = data.GetValue(0)\n            sbCardNo.Append(ch);\n        } while (ch != 'Z') ;\n\n        using (StreamWriter m_streamwriter = new StreamWriter( folderPath + "\\AuthService.txt"))\n        {\n            m_streamwriter.WriteLine(sbCardNo.toString());\n        }\n    }\n}	0
17054760	17054683	Accessing and Setting Array-Type Properties	public class Test\n{\n    // no actual implementation of myProperty is required in this form\n    public int[,] myProperty { get; set; }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Test t = new Test();\n        t.myProperty = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\n        Console.WriteLine(t.myProperty[1, 2]);\n        t.myProperty[1, 2] = 0;\n        Console.WriteLine(t.myProperty[1, 2]);\n    }\n}	0
19153412	19153278	How to open and detect closing of an exe in c#	try\n{\n     Process myProcess = new Process();\n     myProcess.StartInfo.FileName = "notepad.exe";\n     myProcess.StartInfo.Arguments = @"C:\PathToYourFile";\n     myProcess.EnableRaisingEvents = true;\n     myProcess.Exited += new EventHandler(myProcess_Exited);\n     myProcess.Start();\n }\n catch (Exception ex)\n {\n     //Handle ERROR\n     return;\n }\n\n// Handle Exited event and display process information. \nprivate void myProcess_Exited(object sender, System.EventArgs e)\n{\n     eventHandled = true;\n     Console.WriteLine("Exit time:    {0}\r\n" +\n            "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);\n}	0
16194751	16194220	Json Serializing EF object without relationships	public int? ContactsExtraId { get; set; }\npublic virtual tblContactsExtra tblContactsExtra { get; set; }\n\npublic int? InventoryId { get; set; }\npublic virtual TblInventory TBLINVENTORY { get; set; }	0
30509319	30505937	Validate collection using sum on a property	public class ParentValidator : AbstractValidator<Parent> \n{\n    public ParentValidator()\n    {\n        RuleFor(x => x.Children)\n            .SetCollectionValidator(new ChildValidator())\n            .Must(coll => coll.Sum(item => item.Percentage) == 100);\n    }\n}	0
15198207	15196381	display messagebox in asp.net	string script = "alert(\"Hello!\");";\nScriptManager.RegisterStartupScript(this, GetType(), \n                      "ServerControlScript", script, true);	0
15970656	15970575	Parsing String into a C# DateTime Object	var EventEntity = new Event()\n{\n    Book = e.Book,\n    BookImgUrl = e.BookImgUrl,\n    Info = e.Info,\n    Start = DateTime.ParseExact(...) // or DateTime.TryParseExact(...)\n};	0
32178453	32178328	C# variable in link to textbox	var pnlMain = new System.Windows.Forms.Panel(); // replace with your container (where your textboxes exists)\nfor (i = 1; intCOUNTRIES > i; i++)\n{\n   LC = ((TextBox)pnlMain.Controls.Find("inputCOUNTRY" + i)[0]).Text;\n   strCountryName = Country(LC);\n   strCountries += strCountryName + ", ";  \n}	0
7618584	7618504	If I close one of my forms, they all close 	using System;\nusing System.Threading;\nusing System.Windows.Forms;\n\npublic partial class MyForm: Form\n{\n    public MyForm()\n    {\n        InitializeComponent();\n    }\n\n    private void Button1Click(object sender, EventArgs e)\n    {\n        var t = new Thread(() => Application.Run(new MyForm()));\n        t.Start();\n    }\n}	0
29478117	29477545	Split array and add to new array in while loop	private void button1_Click(object sender, EventArgs e)\n    {\n        List<string[]> myArrayList = new List<string[]>();\n        StreamReader read = new StreamReader(@"C:\test\Accounts.txt");\n\n        string line;\n        while ((line = read.ReadLine()) != null)\n        {\n            string[] parts = line.Split('|');\n            //Console.WriteLine(parts[0]);\n            myArrayList.Add(parts);\n        }\n\n        foreach (var account in myArrayList)\n        {\n            richTextBox1.Text = richTextBox1.Text + account[0].ToString() + Environment.NewLine;\n        }\n    }	0
18023674	18023575	C#, How to run a .bat file without a popup console window	p.StartInfo.CreateNoWindow=true;	0
10708424	10708313	How to iterate over this particular type of Dictionary<int, Result>?	foreach (Result r in dict.Values)\n{\n    mynewstring = result.Location;\n    mynewstringtwo = result.Posted;\n}	0
8218056	8217713	How to add a sorted array of elements to a binary search tree (in c#)	int splitIndex = (int)Math.Ceiling((double)(start + end) / 2);\nBNode sub_root = new BNode(arr[splitIndex]);\nsub_root.Left = Dup(arr, start, splitIndex  - 1);\nsub_root.Right = Dup(arr, splitIndex + 1, end);\nreturn sub_root;	0
20342830	20342801	How to avoid age ranges overlapping C#	return !list.Any(x => x.min <= min && x.max >= min || x.min <= max && x.max >= max);	0
8180295	8154667	Right click menu in Console app	string filelocation = Assembly.GetExecutingAssembly().Location;\n\nstring filename = Process.GetCurrentProcess().MainModule.ModuleName;\nfilename = filename.Replace(".exe", "");\n\nProcess[] processArray = Process.GetProcesses();\n\nint processesExists = 0;\n\n\nfor (int i2 = 0; i2 < (processArray.Length - 1); i2++)\n{\n    if (processArray[i2].ProcessName.Contains(filename))\n    {\n        processesExists++;\n    }\n}\n\nif (processesExists == 1 && !Console.Title.Contains("cmd"))\n{\n    Process.Start("cmd.exe", "/C " + "\"" + filelocation + "\"");\n}\n\nif (!Console.Title.Contains("cmd"))\n{\n    Process.GetCurrentProcess().Kill();\n}	0
872624	872589	How do you launch a URL in the default browser from within a winmobile application?	try\n{\nSystem.Diagnostics.Process myProcess = new System.Diagnostics.Process();\nmyProcess.StartInfo.UseShellExecute = true;\nmyProcess.StartInfo.FileName = url;\nmyProcess.Start();\n}\ncatch (Exception e) {}	0
12640303	12640232	Order IEnumerable without LINQ	List<byte> list = new List<byte>(indexes);\nlist.Sort();\n// list is now a sorted clone of the data	0
17909344	17909307	Unchecking event ListView Windows Form Application	private void myListView_ItemCheck(object sender, ItemCheckEventArgs e)\n{\n    if (e.NewValue == CheckState.Unchecked)\n    { \n        //unchecked\n    }       \n    else if(e.NewValue == CheckState.Checked)\n    {\n        //checked\n    }               \n}	0
22410444	22410256	How to validate number of items in a list in mvc model	public ActionResult TheAction(AssessorsViewModel model)\n{\n    if (model.Assessors == null\n        || model.Assessors.Count < 3\n        || model.Assessors.Count > 7)\n    {\n        ModelState.AddModelError("Assessors", "Please enter note less than 3 and not more than 7 assessors.");\n        return View(model);\n    }\n    ...\n}	0
17079298	17079267	VB Equivalent of "To" in C#	System.Array.Resize(ref indexCorr, fDefMatchs.Length);	0
34071375	34051748	insert footnotes into all on a new page using c#	Sub PageBreakBeforeEndNotesAndNoSeparator()\n  Dim rngDoc As word.Range, rngEndNoteSep As word.Range\n\n  Set rngDoc = ActiveDocument.content\n  Set rngEndNoteSep = ActiveDocument.StoryRanges(wdEndnoteSeparatorStory)\n  rngEndNoteSep.Delete\n  rngDoc.Collapse wdCollapseEnd\n  rngDoc.InsertBreak word.WdBreakType.wdPageBreak\nEnd Sub	0
14304825	14297322	How to detect tapping (touch input) globally instead of mouse clicking?	switch(Msg)  \n{  \n...  \ncase WM_POINTERENTER:  \ncase WM_NCPOINTERDOWN:  \ncase WM_NCPOINTERUP:  \ncase WM_NCPOINTERUPDATE:  \ncase WM_POINTERACTIVATE:  \ncase WM_POINTERCAPTURECHANGED:  \ncase WM_POINTERDOWN:  \ncase WM_POINTERLEAVE:  \ncase WM_POINTERUP:  \ncase WM_POINTERUPDATE:  \n    {  \n        UINT32 pointerId = GET_POINTERID_WPARAM(wParam);  \n        POINTER_INPUT_TYPE pointerType;  \n\n        if (GetPointerType(pointerId, &pointerType))  \n        {\n            if (pointerType == PT_TOUCH)   \n            {  \n                ...  \n            }  \n        }  \n    }  \n    break;  \n...	0
15677381	15677321	c# ammend SQL data	if( !IsPostBack )\n{\n   // load initial form values here from DB\n}	0
33219772	33219480	Reloading/replacing a new table into WPF DataGrid at runtime	public class YourViewModel : INotifyPropertyChanged\n{\n    ...\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private DataView displayView;\n    public DataView DisplayView\n    {\n        get { return displayView; }\n        set \n        {    \n            displayView = value;\n\n            if (PropertyChanged != null)\n            {                \n                PropertyChanged(this, new PropertyChangedEventArgs(nameof(DisplayView)));\n            }\n        }\n    }\n\n    ...\n}	0
1903958	1903901	How can I access my applications images that are in my resources?	public Image GetImage(string name)\n    {\n        switch (name)\n        {\n            case "PictureBox1":\n                return Properties.Resources.Picture1;\n            case "PictureBox2":\n                return Properties.Resources.Picture2;\n            default:\n                return null;\n        }\n    }	0
20856142	20853941	How to fetch a excel file from a folder?	if (File.Exists(filePath)) {   \n    byte[] data = File.ReadAllBytes(filePath);\n    string fileName = Path.GetFileName(filePath);\n\n    const string query = "INSERT INTO Files (FileName, Data, Path) VALUES (@FileName, @Data, @Path)";\n\n    using (var connection = new SqlConnection(connectionString))\n    using (var command = new SqlCommand(query, connection)) {\n        command.Parameters.AddWithValue("@FileName", fileName);\n        command.Parameters.AddWithValue("@Data", data);\n        command.Parameters.AddWithValue("@Path", filePath);\n\n        connection.Open();\n        command.ExecuteNonQuery();\n    }\n}	0
8350507	8346995	moq No setups configured error, how to quickly add a setup properly	this.prvFacServiceMgr.Setup(call =>     call.SearchProviderFacility(It.IsAny<ProviderFacilitySearchCriteria>())).Returns(new List<ProviderFacilitySearchResult>() \n        { \n            new ProviderFacilitySearchResult()\n            { \n                ProviderName="TestProvider"\n            } \n        });	0
11439751	11439711	Returning to previous page with search results after clicking cancel	history.back(-1)	0
5339045	5339031	how to save bitmap in byte[] c#?	System.Drawing.Image originalImage = dpgraphic.image;// replace your image here i.e image bitmap\n//Create empty bitmap image of original size\nfloat width=0, height=0;\nBitmap tempBmp = new Bitmap((int)width, (int)height);\nGraphics g = Graphics.FromImage(tempBmp);\n//draw the original image on tempBmp\ng.DrawImage(originalImage, 0, 0, width, height);\n//dispose originalImage and Graphics so the file is now free\ng.Dispose();\noriginalImage.Dispose();\nusing (MemoryStream ms = new MemoryStream())\n{\n    // Convert Image to byte[]\n    tempBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);\n    //dpgraphic.image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);\n    byte[] imageBytes = ms.ToArray();\n}	0
27892925	27892640	Android Location TimeStamp Conversion To C-Sharp DateTime	double seconds = Location.Time / 1000;\nDateTime utcConverted = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime();	0
15521135	15520665	How to add an event dynamically by its name	public void TextBox1_Validating(object sender, CancelEventArgs args)\n{\n    // handle the event\n}\n\n\npublic void RegisterEvent()\n{\n    CancelEventHandler handler = (CancelEventHandler)Delegate.CreateDelegate(\n        typeof(CancelEventHandler), \n        this,\n        "TextBox1_Validating");\n    textBox1.Validating += handler;\n}	0
29479753	29479572	Select records from concurrent dictionary using lambda	var value = dictionary.Where(x => x.Key.Day == 5).Max(x=>x.Value);	0
1838208	1838072	cannot convert from 'out T' to 'out Component'	bool TryGetValue(Type key, out Component result)\n{\n       if (this.Contains(key))\n       {\n           result = this[key]; // the type of result is Component!\n           return true;\n       }\n\n      return false;\n}	0
15706045	15705969	Can I call a sql command parameter from another class?	public static OleDbConnection GetConnection()\n    {\n        var myCon = new OleDbConnection();\n        myCon.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C\:... Database2.mdb";\n\n        return myCon;\n    }\n    public static void Insert(string id, string name)\n    {\n        var con = GetConnection();\n        OleDbCommand cmd = new OleDbCommand();\n        cmd.CommandType = CommandType.Text;\n        cmd.CommandText = "INSERT INTO Table1 (ID, Name)";\n        cmd.Parameters.AddWithValue("@ID", id);\n        cmd.Parameters.AddWithValue("@Name", name);\n        cmd.Connection = con;\n        con.Open();\n        cmd.ExecuteNonQuery();\n        con.Close();\n    }\n\n    private void Insertbtn_Click(object sender, EventArgs e)\n    {\n        Insert(IDTxt.Text, NameTxt.Text);\n    }	0
34499589	34496518	WP white icons in taskbar	private void InitializeThemes()\n    {\n        switch (AnalyticsInfo.VersionInfo.DeviceFamily)\n        {\n            case "Windows.Mobile":\n                StatusBar statusBar = StatusBar.GetForCurrentView();\n\n                break;\n            case "Windows.Desktop":\n                ApplicationView applicationView = ApplicationView.GetForCurrentView();\n\n                break;\n        }\n    }	0
21552005	21551900	Delete a specific row from datatable	DataRow[] rows;\nrows=dt.Select("STOK_KODU='HAMMADDE_2'"); \nforeach(DataRow r in rows)\nr.Delete();	0
21709792	21683861	Autofac - changing injected components based on object tree	builder.RegisterAssemblyTypes(typeof(OurObjectContext).Assembly)\n    .InNamespace("Company.Core.Services")\n    .AsImplementedInterfaces()\n    .InstancePerHttpRequest()\n    .WithParameter(new ResolvedParameter((parameterInfo, componentContext) =>\n    {\n        // in predicate we select only IRepository<> types\n        return parameterInfo.ParameterType.GetGenericTypeDefinition() == typeof(IRepository<>);\n\n    }, (parameterInfo, componentContext) =>\n    {\n        // firstly we get a generic parameter type \n        var genericArgument = parameterInfo.ParameterType.GetGenericArguments()[0];\n        // then we construct a new generic type with the parameter, suppose it's LoggingRepository<> and it's registered\n        var typeToResolve = typeof(LoggingRepository<>).MakeGenericType(genericArgument);\n\n        // resolve the type and Autofac will put it instead of IRepository<>\n        return componentContext.Resolve(typeToResolve);\n    }));	0
23984173	23984136	picturebox array click event	picturebox[0, 0].Click += picturebox_Click; // in your form load event, this is only for one picture box\n\nvoid picturebox_Click(object sender, EventArgs e)\n{\n    // do whatever you want to do when the picture box is clicked\n}	0
2432092	2432025	Selecting rows from DataTable by DateTime column (hours)	dt.Columns[0].Caption + " LIKE '" + x.ToString("dd/MM/yyyy HH") + "*'"	0
10370823	9693792	Create eigenfaces vector from database	List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();\n    trainingImages.Add(new Image<Gray, byte>("test.pgm"));	0
30869263	30868794	Format DateTime.ParseInfo	using System.Globalization; \n\nvar value = "Mon Jun 15 2015 00:00:00 GMT+0200 (Central Europe Daylight Time)";\nvar trimedValue = value.Substring(0, value.IndexOf(" ("));\nvar dateTime = DateTime.ParseExact(trimedValue, "ddd MMM dd yyyy HH:mm:ss 'GMT'zzz", CultureInfo.InvariantCulture);	0
26517203	26517142	How to make all the code in a try block run before the catch statement executes	class Program\n{\n    static void Main(string[] args)\n    {\n        Employee EmPy1 = TryCreateCmployee("111-11-111", -4.0);\n        Employee EmPy2 = TryCreateCmployee("222-22-222", 7.5);\n        Employee EmPy3 = TryCreateCmployee("333-33-333", 750);\n    }\n\n    static Employee TryCreateCmployee(string id, double hourlyWage)\n    {\n        try\n        {\n            return new Employee(id, hourlyWage);\n        }\n        catch (EmployeeException ex)\n        {\n            Console.WriteLine(ex.Message);\n            return null;\n        }\n\n    }\n}	0
15925683	15925487	How to convert a web page that using a Master page to one without a Master page	void Page_PreInit(Object sender, EventArgs e)\n{\nthis.MasterPageFile = "~/NewMaster.master";\n}	0
15763185	15762868	Join on compare keys on one side of equals (startswith)	Dictionary<string, string[]> disksPerBus = new Dictionary<string, string[]>();\nforeach(var bkv in busesHWPath)\n{\n    string[] disks = disksHWPath.Where(dkv => dkv.Key.StartsWith(bkv.Key))\n                     .Select(dkv => dkv.Value).ToArray();\n    disksPerBus.Add(bkv.Value, disks); // this may fail if the value is not unique\n}	0
22954788	22954729	Get or set accessor expected	class LoadReflexTime\n{    \n   public string[,] reflexTime(){\n\n    //YOUR CODE\n\n    }\n}	0
7649418	7649274	How to get a substring from a large string?	using System;\nusing System.Collections.Generic;\n\npublic class MyClass\n{\n    public static void Main()\n    {\n        List<string> columns = new List<string>(); // columns collection\n\n        string sql = "SELECT column_name1, column_name2, column_name3, column_name4 FROM table1 JOIN table2 ON table1.field1 = table2.field1";\n        string[] parts = sql.Split(new char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);\n\n        for (int i=1; i<parts.Length; i++)\n        {\n            if (parts[i].Equals("FROM")) break;\n\n            columns.Add(parts[i]); // add cols to collection\n        }\n\n        foreach(string column in columns)\n            Console.WriteLine(column); // print out the columns\n    }\n}	0
7268786	7255840	Edit a specific row in an asp repeater	for (int repeaterCount = 0; count < repeaterID.Items.Count; count++)\n    {\n        Label label = (Label)repeaterID.Items[repeaterCount].FindControl("labelID");\n        label.Text = "Text";\n    }	0
34125007	34124971	C# Minimize Whole Application	foreach (Form form in Application.OpenForms)\n{\n    form.WindowState = FormWindowState.Minimized;\n}	0
12575756	12575240	Turn off Gurobi Logging	GRBEnv env = new GRBEnv("mip1.log");\nenv.Set(GRB.IntParam.LogToConsole, 0);\nGRBModel model = new GRBModel(env);	0
4051893	4051872	How to remove trailing characters after a blank space in C#?	DateTime d;\nDateTime.TryParse("12/10/2010 00:00:00", d);\nd.ToString("MM/dd/yyyy");	0
5147498	5147402	Display only one column in combo box from List collection Items	List<MyHeaders> headers = new List<MyHeaders>();\nheaders.Add( new MyHeaders{ID=10, Name="Yo"} );\nheaders.Add( new MyHeaders{ID=2, Name="OY"} );\nheaders.Add( new MyHeaders{ID=3, Name="Pickles"} );\nheaders.Add( new MyHeaders{ID=4, Name="Florky"} );\n\nthis.comboBox1.DataSource = headers;\nthis.comboBox1.DisplayMember = "Name";\nthis.comboBox1.ValueMember = "ID";	0
25910628	25910266	Need to Append Xml Data to the XmlDocument object inside for each	_prod = new XmlDocument();\nstring[] sn = {"first", "second", "third"}\nforeach(int i=0; i<sn.Length; i++)\n{\n    //build _prod based on the first XML\n    if(i==0) _prod = Getdata(sn[i]);\n    //then from next XMLs, add <product> nodes as child of _prod's <products>\n    else\n    {\n        var _temp = Getdata(sn[i]);\n        //select <products> node from _prod\n        var product = _prod.SelectSingleNode("//products");\n        //select <product> nodes to be appended to _prod\n        var products = _temp.SelectNodes("//products/product");\n        foreach(XmlNode p in products)\n        {\n            product.AppendChild(p);\n        }\n    }\n}	0
14090140	14090010	How to send image files to/from server	public static byte[] SaveToPng(this BitmapSource bitmapSource)\n    {\n        return SaveWithEncoder<PngBitmapEncoder>(bitmapSource);\n    }\n\n    private static byte[] SaveWithEncoder<TEncoder>(BitmapSource bitmapSource) where TEncoder : BitmapEncoder, new()\n    {\n        if (bitmapSource == null) throw new ArgumentNullException("bitmapSource");\n\n        using (var msStream = new MemoryStream())\n        {\n            var encoder = new TEncoder();\n            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));\n            encoder.Save(msStream);\n            return msStream.ToArray();\n        }\n    }\n\n\n    public static BitmapSource ReadBitmap(Stream imageStream)\n    {\n        BitmapDecoder bdDecoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);\n        return bdDecoder.Frames[0];\n    }	0
9712239	9712177	C# DateTime Parse/convert this format "20120314T130000"	DateTime.ParseExact(date, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture)	0
21079486	21028326	Is it possible to wait until other thread processes input messages posted to it?	using namespace System.Diagnostics;\n...\n    public static bool WaitForInputIdle(IntPtr hWnd, int timeout = 0) {\n        int pid;\n        int tid = GetWindowThreadProcessId(hWnd, out pid);\n        if (tid == 0) throw new ArgumentException("Window not found");\n        var tick = Environment.TickCount;\n        do {\n            if (IsThreadIdle(pid, tid)) return true;\n            System.Threading.Thread.Sleep(15);\n        }  while (timeout > 0 && Environment.TickCount - tick < timeout);\n        return false;\n    }\n\n    private static bool IsThreadIdle(int pid, int tid) {\n        Process prc = System.Diagnostics.Process.GetProcessById(pid);\n        var thr = prc.Threads.Cast<ProcessThread>().First((t) => tid == t.Id);\n        return thr.ThreadState == ThreadState.Wait &&\n               thr.WaitReason == ThreadWaitReason.UserRequest;\n    }\n\n    [System.Runtime.InteropServices.DllImport("User32.dll")]\n    private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int pid);	0
10740807	10740398	How to set up MySQL database to connect to from another computer?	Client 1: This is moe. Here's a message for curly:  "Look at the grouse, look at the grouse".\nServer: OK\n\nClient 2: This is curly: any new messages?\nServer: moe says "Look at the grouse, look at the grouse".\n\nClient 1: This is moe. When did curly last collect my messages?\nServer: ten minutes ago.\n\nClient 2: This curly. any new messages?\nServer: NO	0
3197369	3196865	PostSharp on assemblies I don't have source for	[assembly: Trace("MyCategory",\n                 AttributeTargetAssemblies="xyz",\n                 AttributeTargetTypes = "My.BusinessLayer.*")]	0
32997306	32997037	Select individual columns in EF	IEnumerable<LEA> query = default(IEnumerable<LEA>);\n\nvar query = from l in bModel.leas\n    join la in bModel.LondonAreas on l.LEANo equals la.LeaNo\n    where la.AreaNo == areaNo\n    select new\n    {\n        LEANo = l.LEANo,\n        AreaNo = la.AreaNo\n    };	0
21589212	21587306	Need to read a value in a XDocument based on the value of an attribute	List<Album> albums = xDoc\n    .Root\n    .Descendants("ALBUM")\n    .Select(e =>\n        new Album()\n        {\n            CoverArt = e\n                .Elements("URL")\n                .First(u => u.Attribute("TYPE").Value == "COVERART")\n                .Value\n                .ToString(),\n            ArtistBio = e\n                .Elements("URL")\n                .First(u => u.Attribute("TYPE").Value == "ARTIST_BIOGRAPHY")\n                .Value\n                .ToString()\n        }\n    ).ToList();	0
15052120	15052093	How can I show the relationship based SQL Server table value in label in C#	label20.Text = koo["Aurthorname"].ToString();\nlabel21.Text = koo["CatagoryName"].ToString();	0
31625517	31623708	Create JSON from 2 strings from Database (Latency and Formatting Issues)	var array = (from coa in db.MSTs\n             select new { Code = coa.S2, Name = coa.S1 }).ToArray();\n\nstring jsonfile = JsonConvert.SerializeObject(array, Formatting.Indented);\nstring path = @"C:\Users\Awais\Desktop\accounts.json";\nSystem.IO.File.WriteAllText(path, jsonfile);	0
12964881	12964790	Using C# as my DSL -- is this possible, if so, how?	Microsoft.CSharp.CSharpCodeProvider	0
20694710	20694543	Adding DateTime to filename during rename	string strNewPath = SavePath + NewFileName + Path.GetExtension(UploadedFile.FileName);\n\nif (System.IO.File.Exists(strNewPath)) {\n  System.IO.File.Move(strNewPath, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + Path.GetExtension(UploadedFile.FileName));\n  UploadedFile.SaveAs(strNewPath);\n}\nelse {\n  UploadedFile.SaveAs(strNewPath);\n}\n\nusing (db) {\n  File NewFile = new File() {\n    FileName = NewFileName + Path.GetExtension(UploadedFile.FileName),\n    ContentType = UploadedFile.ContentType\n  };\n\n  db.Files.Add(NewFile);\n  db.SaveChanges();\n\n  return NewFile.ID;\n}	0
4374454	4367507	XML data extraction using LINQ	Dim l_PricesTable = From rows In l_Xml.Descendants("tr") _ \n               Where ((rows.Descendants("td") IsNot Nothing) AndAlso (rows.Descendants("td").Count >= 1)) _ \n                      Select Data = rows.Descendants("td")(0).Value, \n                      AsOfDate = rows.Parent.Parent.ElementsBeforeSelf("p")(rows.Parent.Parent.ElementsBeforeSelf("p").Count - 1).Descendants("b").Value	0
10388400	10387513	Issue with password in user login system. C#	public bool Login(String uName, String pasw)\n{\n    using (SqlConnection myConnection = new SqlConnection(connString))\n    {\n        string oString = "Select ID from yourTable where username = @username AND paswoord = @password";\n        SqlCommand oCmd = new SqlCommand(oString, myConnection);\n        oCmd.Parameters.AddWithValue("@username", uName);\n        oCmd.Parameters.AddWithValue("@password", pasw);\n        string id = null;\n        myConnection.Open();\n        using (SqlDataReader oReader = oCmd.ExecuteReader())\n        {              \n            while (oReader.Read())\n            {\n                id = oReader["id"].ToString();\n            }\n            myConnection.Close();\n        }\n        if (id == null)\n        {\n            return false;\n        }\n        else\n        {\n            return true;\n        }         \n    }\n}	0
11589738	11589713	C# Socket - How do I keep socket open?	server.Stop();	0
31100388	31099617	How can I take over, another running application within a panel of my C# program?	foreach (var process in Process.GetProcesses())\n{\n    if (process.ProcessName == "notepad")\n    // or\n    //if (process.MainWindowTitle == "Untitled - Notepad")\n    {\n        SetParent(process.MainWindowHandle, panel1.Handle);\n    }\n};	0
28046449	28046275	How to get the duration of mp3 track?	var audioFile = await mp3FilesFolder.GetFileAsync("sound.mp3");\n   MusicProperties properties = await audioFile.Properties.GetMusicPropertiesAsync();\n   TimeSpan myTrackDuration = properties.Duration;	0
22908210	22908126	How to cache the following variable that holds class properties	public static class FullTextSearch<T>\n{\n    private List<Func<T, string>> _properties;\n\n    static FullTextSearch()\n    {\n        _properties = GetPropertyFunctions<T>().ToList();\n    }\n\n    public bool Match(T item, string searchTerm)\n    {\n        bool match = _properties.Select(prop => prop(item)).Any(value => value != null && value.ToLower().Contains(searchTerm.ToLower()));\n        return match;\n    }\n}	0
29013527	29013102	xpath to select all leaf nodes with given ancestors attribute	//*[not(child::*) and not(ancestor-or-self::*[@isOptional = 'True'])]	0
14507138	14506616	Determining size of an array of arrays in C#?	int newSize = 7;\nstring[][] newArray = new string[oldArray.Length][];\nfor (int i = 0; i < oldArray.Length; i++)\n{\n    newArray[i] = new string[newSize];\n    Array.Copy(oldArray[i], newArray[i], oldArray[i].Length);\n}	0
32653054	32652502	How to stop looping in Resizing event of Winform?	bool _resizing;\n\nprivate void Form_Resize(object sender, EventArgs e)\n{\n    if (_resizing) return;\n    _resizing = true;\n\n    int tabHeight = 100;\n    Height = tabHeight + 20;\n    Top = (Screen.PrimaryScreen.Bounds.Height / 2) - (Height / 2);\n\n    _resizing = false;\n}	0
27879787	27879560	Microsoft Speech Platform: recognize word repetitions	gb.Append(choices, 1, 10);	0
732796	732205	How can I avoid AmbiguousMatchException between two controller actions?	[AcceptVerbs(HttpVerbs.Get)]\npublic ActionResult Show(int id, bool? asHtml)\n{\n    var result = Stationery.Load(id);\n\n    if (asHtml.HasValue && asHtml.Value)\n        return Content(result.GetHtml());\n    else\n        return new XmlResult(result);\n}	0
33465301	33465180	Authenticate SignalR from MVC Controller	public void Configuration(IAppBuilder app)\n{\n\n        app.UseCookieAuthentication(new CookieAuthenticationOptions\n        {\n            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,\n            LoginPath = new PathString("/Home/Index")\n        });\n\n        //...\n\n        app.MapSignalR();    \n}	0
13719191	13718989	Generics in C# with multiple generic types leads to allowed and disallowed ambiguity	interface I1<T> {...}\ninterface I2<T> {...}\nclass G1<U>\n{\n    int F1(U u);                    // Overload resulotion for G<int>.F1\n    int F1(int i);                  // will pick non-generic\n    void F2(I1<U> a);               // Valid overload\n    void F2(I2<U> a);\n}\nclass G2<U,V>\n{\n    void F3(U u, V v);          // Valid, but overload resolution for\n    void F3(V v, U u);          // G2<int,int>.F3 will fail\n    void F4(U u, I1<V> v);      // Valid, but overload resolution for   \n   void F4(I1<V> v, U u);       // G2<I1<int>,int>.F4 will fail\n    void F5(U u1, I1<V> v2);    // Valid overload\n    void F5(V v1, U u2);\n    void F6(ref U u);               // valid overload\n    void F6(out V v);\n}	0
25248031	25213727	Gathering information from Google+ Sign in with C#/ASP.NET MVC 4	var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);\nvar extEmailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);\nvar extEmail = emailClaim.Value;	0
21824706	21824523	GridView100% Browser Width with horizontal scoll	position:relative	0
12190679	12190636	how to insert data from excel sheet to datatable in asp.net?	"select * from [Sheet1$]"	0
18783912	18783884	Convert jagged array to a list	List<int> list = jaggedArray.SelectMany(T => T).ToList();	0
13175321	13175133	Allow only a text file in drag drop on a textbox using C#.Net	var files = (string[])e.Data.GetData(DataFormats.FileDrop);\n\nforeach(var file in files)\n{\n    if(System.IO.Path.GetExtension(file).Equals(".txt", StringComparison.InvariantCultureIgnoreCase))\n    {\n        //file has correct extension, do something with file\n    }\n    else\n    {\n        MessageBox.Show("Not a text file");\n    }\n}	0
3979381	3979046	DB2 REORG TABLE from client side with Migrator.NET	Database["DB2"].ExecuteNonQuery("call SYSPROC.ADMIN_CMD ('REORG TABLE MyTable')");	0
11242731	11241844	How can I set text direction RightToLeft in ms word document in c#?	wordParagraph.ReadingOrder = WdReadingOrder.wdReadingOrderRtl;	0
15976940	15976687	Drag and drop from windows explorer to custom C# app that actually works with Windows 7	this.Load += new System.EventHandler(this.Form1_Load);	0
1649490	1649464	Writing to a COM port with .Net	SerialPort port = new SerialPort("COM1");\nport.Open();\nif (port.IsOpen)\n{\n}\nport.Close();	0
22988567	22988513	Find out if string list items startswith another item from another list	foreach (var t in firstList) {\n    foreach (var u in keyWords) {\n        if (t.StartsWith(u) {\n            // Do something here.\n        }\n    }\n}	0
20910423	20910408	How can I remove all extraneous spaces from a *.docx file?	private void RemoveSuperfluousSpaces(string filename)\n{\n    bool superfluousSpacesFound = true;\n    using (DocX document = DocX.Load(filename))\n    {\n        List<int> multipleSpacesLocs;\n        while (superfluousSpacesFound)\n        {\n            document.ReplaceText("  ", " ");\n            multipleSpacesLocs = document.FindAll("  ");\n            superfluousSpacesFound = multipleSpacesLocs.Count > 0;\n        }\n        document.Save();\n    }\n}	0
26816741	26816713	ASP NET select object from list	var user = SomeList.FirstOrDefault(u => u.Id == UserId)	0
13909544	13909049	Resetting app data setting using background worker in wp7	DateTime.Now > deleteTime	0
16601083	16600198	XNA - How to dim a section of the screen?	for(int i = 0; i < texturesToDraw.Count; i++)\n{\n    if(i == selected) \n    {\n         spriteBatch.Draw(texturesToDraw[i], position, Color.White)\n    }\n    else\n    {\n         spriteBatch.Draw(texturesToDraw[i], position, Color.SomeDarkColor)\n    }\n}	0
10757469	10757378	how can I create a truly immutable doubly linked list in C#?	public sealed class Node<T> { \n  readonly T m_data;\n  readonly Node<T> m_prev;\n  readonly Node<T> m_next;\n\n  // Data, Next, Prev accessors omitted for brevity      \n\n  public Node(T data, Node<T> prev, IEnumerator<T> rest) { \n    m_data = data;\n    m_prev = prev;\n    if (rest.MoveNext()) {\n      m_next = new Node(rest.Current, this, rest);\n    }\n  }\n}\n\npublic static class Node {    \n  public static Node<T> Create<T>(IEnumerable<T> enumerable) {\n    using (var enumerator = enumerable.GetEnumerator()) {\n      if (!enumerator.MoveNext()) {\n        return null;\n      }\n      return new Node(enumerator.Current, null, enumerator);\n    }\n  }\n}\n\nNode<string> list = Node.Create(new [] { "a", "b", "c", "d" });	0
12378586	12378547	Linq to XML: Get all nodes that contain certain children	var capabilites = root.Descendants("Capability")\n            .Where(c => c.Descendants("Relation")\n                         .Any(r => (string)r.Attribute("RelatedTo") == "5"))\n            .ToList();	0
18886300	18757027	Colour percentage in Bitmap	Image page= new Image(filePath);\ndouble nTotal = page.Width * page.Height;	0
31220296	31219054	Selecting whole text with backslashes in it	private void textBox2_Click(object sender, EventArgs e)\n{\n    int line = textBox2.GetLineFromCharIndex(textBox1.SelectionStart);\n    if (line >= 0 && line < textBox2.Lines.Length) \n        Console.WriteLine(textBox2.Lines[line]);  // or whatever you want to do with it..\n}	0
3137613	3137004	Displaying and editing a concatenated string enumerable in a bound WPF DataGrid	public class JoinConverter\n    : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        var enumerable = value as IEnumerable<string>;\n        if (enumerable == null)\n        {\n            return DependencyProperty.UnsetValue;\n        }\n        else\n        {\n            return string.Join(Environment.NewLine, enumerable.ToArray());\n        }\n    }\n\n    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n    {\n        return value.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);\n    }\n}	0
2451284	2450917	Dealing with large number of text strings	varchar(4000)	0
27401297	27401232	Equivalent of isSiteLocalAddress in C#	private bool isIPLocal(IPAddress ipaddress)\n{\n    String[] straryIPAddress = ipaddress.ToString().Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries);\n    int[] iaryIPAddress = new int[] { int.Parse(straryIPAddress[0]), int.Parse(straryIPAddress[1]), int.Parse(straryIPAddress[2]), int.Parse(straryIPAddress[3]) };\n    if (iaryIPAddress[0] == 10 || (iaryIPAddress[0] == 192 && iaryIPAddress[1] == 168) || (iaryIPAddress[0] == 172 && (iaryIPAddress[1] >= 16 && iaryIPAddress[1] <= 31)))\n    {\n        return true;\n    }\n    else\n    {\n        // IP Address is "probably" public. This doesn't catch some VPN ranges like OpenVPN and Hamachi.\n        return false;\n    }\n}	0
6918725	6918545	How to read byte blocks into struct	class FileEntry {\n     byte Value1;\n     char[] Filename;\n     byte Value2;\n     byte[] FileOffset;\n     float whatever;\n}\n\n  using (var reader = new BinaryReader(File.OpenRead("path")) {\n     var entry = new FileEntry {\n        Value1 = reader.ReadByte(),\n        Filename = reader.ReadChars(12) // would replace this with string\n        FileOffset = reader.ReadBytes(3),\n        whatever = reader.ReadFloat()           \n     };\n  }	0
13228101	13228056	Using a (to a class) unknown function	((Insert)f).SwitchTab(tab)	0
17451154	17450614	delete data on SQL table based on datatable input	string updateString =\n                    "UPDATE dbo.testTable SET datecol = @datecol where clientId=@clientID";\n\n conn.Open();\n using (SqlCommand cmd = new SqlCommand(updateString, conn))\n       {\n\n         cmd.Parameters.Add("@datecol", SqlDbType.Date).Value = DbNull.Value;\n         cmd.Parameters.Add("@clientID", SqlDbType.Int).Value = 1212;\n\n         cmd.ExecuteNonQuery();\n       }\n       conn.Close();	0
10688710	9091255	Convert datatable to datareader	DataTable table = new DataTable(); \n//Fill table with data \n//table = YourGetDataMethod(); \nDataTableReader reader = table.CreateDataReader();	0
9083008	9081340	How to set default values for the properties of a derived control?	[Browsable(false)]\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new ObjectCollection Items\n{\n  get { return ((ComboBox)this).Items; }\n}	0
4145028	4144961	Multiple insert statements in single ODBC ExecuteNonQuery (C#)	INSERT INTO test(id, name) VALUES ('1', 'Foo'), ('2', 'bar');	0
30188752	30186661	Get the index of Array List	List<string> data = new List<string>\n{\n    "- LQI Request",\n    "- 0123456",\n    "- LQI Request",\n    "- 456789",\n    "- LQI Request",\n    "- 6789"\n};\n\nvar result = data.Select((x, i) => // x is the element, i is the index\n                        {\n                            if (x.Contains("LQI"))\n                                if(i + 1 < data.Count) // is the index inside the bounds of the array\n                                    return data[i + 1].Substring(2); // don't take the "- "\n                            return string.Empty;\n                        }).Where(x => !string.IsNullOrEmpty(x)) // ignore empty results\n                          .ToArray();\n\n// result: ["0123456", "456789", "6789"]	0
18468920	18449370	XML Serialization control order on list	[XmlRoot("FCS_SET_SCH")]\npublic class DDCSendReceiveScheduleXml : IXmlSerializable\n{\n     ...\n    public XmlSchema GetSchema()\n    {\n        return null;\n    }\n\n    public void WriteXml(XmlWriter writer)\n    {\n        Debug.Assert(ScheduleList.Count == TimeTableXmlList.Count, "ScheduleList and TimeTableXml Count isn't same");\n        XmlSerializer scheduleSerializer = new XmlSerializer(typeof(ScheduleXml));\n        XmlSerializer timeTableSerializer = new XmlSerializer(typeof(TimeTableXml));\n        for (int i = 0; i < ScheduleList.Count; i++)\n        {\n            scheduleSerializer.Serialize(writer, ScheduleList[i]);\n            timeTableSerializer.Serialize(writer, TimeTableXmlList[i]);\n        }\n    }	0
13566824	13566556	SqlConnection - The timeout period elapsed prior to obtaining a connection from the pool	try {\n    using (var sqlConn = new SqlConnection(myConnectionString)) {\n        using (SqlCommand cmd = sqlConn.CreateCommand()) {\n            sqlConn.Open();\n            AttachParameters(cmd, e);\n            cmd.ExecuteNonQuery();\n        }\n    }\n} catch (Exception ex) {\n    Logger.Instance.Fatal(ex);\n}	0
31626515	31626420	XML Parsing using C#	string s = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?><GeocodeResponse><status>OK</status><result><type>neighborhood</type><type>political</type><formatted_address>Phase 1, Sector 57, Sahibzada Ajit Singh Nagar, Punjab, India</formatted_address><address_component><long_name>Phase 1</long_name><short_name>Phase 1</short_name><type>neighborhood</type><type>political</type></address_component><place_id>ChIJDTCn80PuDzkRFK0l5i2S0iQ</place_id></result></GeocodeResponse>";\nvar doc = new XmlDocument();\ndoc.LoadXml(s);\nvar elmts = doc.GetElementsByTagName("formatted_address");\nif (elmts.Count > 0)\n{\n    MessageBox.Show(elmts[0].InnerText); // will show "Phase 1, Sector 57, Sahibzada Ajit Singh Nagar, Punjab, India"\n}	0
12215952	12214253	Changing normal values in dataview	void Control_RowDataBound(Object sender, GridViewRowEventArgs e)\n  {\n\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n      if(e.Row.Cells[3].Text == "1")\n      {\n         e.Row.Cells[4].Text = ""; // erase the value of cell\n         //You can use also to cell : Attributes["style"] = "display:none";\n\n\n      }\n      else\n      {\n        .... \n      }\n  }	0
16282446	16279065	Access Ironpython dictionary from C#	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Scripting.Hosting;\nusing Microsoft.Scripting.Utils;\nusing Microsoft.Scripting.Runtime;\nusing IronPython;\nusing IronPython.Hosting;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ScriptEngine pyEngine = Python.CreateEngine();\n            ScriptScope pyScope = pyEngine.CreateScope();\n            ScriptSource pyScript = pyEngine.CreateScriptSourceFromString("d = {'a':1,'b':2,'c':3}");\n            CompiledCode pyCompiled = pyScript.Compile();\n            pyCompiled.Execute(pyScope);\n            IronPython.Runtime.PythonDictionary d = pyScope.GetVariable("d");\n            Console.WriteLine(d.get("a"));\n            Console.Read();\n        }\n    }\n}	0
5230861	5229035	Crystal Report : How to stop opening new window on double-click of the group section?	this.crystalReportViewer1.EnableDrillDown = false;	0
9102919	9102697	Pattern for knowing when a method can be called in a new thread	public interface IDevice\n{\n    string GroupBy {get;}\n    double Measure();\n}	0
23748331	23746530	Detecting checkbox touch	private bool _isLoaded = false;\n\npublic CheckBoxPage()\n{\n    InitializeComponent();\n\n    AvailableCheckBox.IsChecked = true;\n\n    _isLoaded = true; // enable the AvailableCheckBox_Checked handler\n}\n\nvoid AvailableCheckBox_Checked(object sender, RoutedEventArgs e)\n{\n    if (!_isLoaded) return; // stop here if not loaded yet\n\n    // everything is loaded so let's execute some stuff\n    MessageBox.Show("Changed");\n}	0
13769813	13661916	Implementing Project structure using EF 5	Const inputFile As String = "..\..\..\SFHDDATA\OP.edmx"	0
2713594	2713046	How to get image from relative URL in C#, the image cannot be in the project	if (child.Name == "photo" &&\n    child.Attributes["href"] != null &&\n    File.Exists(Environment.CurrentDirectory + child.Attributes["href"].Value))\n{\n    Image image = new Image();\n    image.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));\n    images.Add(image);\n}	0
31954160	31370539	How to get device carrier and country within Windows Phone 8 SL	string val = Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("OriginalMobileOperatorName") as string;\n\n//I wanted this value...	0
27230932	27230786	Accessing a public class member dynamically	public class Names\n{\n    public string Name1 { get; set; }\n    public string Name2 { get; set; }\n    public string Name3 { get; set; }\n}\n\nfor (int i = 1; i <= collection.Count(); i++)\n{\n    var col = collection.ElementAt(i);\n    col.GetType().GetProperty("Name + i").SetValue(col, longString.Substring(11, 4), null);\n}	0
19534371	19534257	Flattening an nested object into a single row in NHidernate	Property(x => x.OuterProp1);\nProperty(x => x.OuterProp2);\nComponent(\n    x => x.InnerClass,\n    comp =>\n    {\n        comp.Property(x => x.InnerProp1);\n        comp.Property(x => x.InnerProp2);\n    });	0
23405979	23405898	Converting SQL query to LINQ to Entities Lambda Expression1	private Entities db = new Entities();\n\nvar city = db.cities.select(c => new { c.CityName , c.CityId}).OrderBy(c=> c.CityName);\n\ndb.citites.add(city);\n\ndb.SaveChanges();	0
13070965	13030082	Parallel reading from SQL Server	Parallel.ForEach(etqC, cv => {\n\n        BindingList<ItemsClass> etqM = new BindingList<ItemsClass>();\n\n        readData(ref etqM, "tableA", "WHERE ID LIKE '" + cv.Name + "%'");\n        IList<ItemsClass> eResults = etqM.OrderBy(f => f.ID).ToList();\n\n        foreach (ItemsClass R in eResults)\n        {\n            //calculations comes here\n\n            etqM[rID] = R;\n        }\n\n        Parallel.ForEach(etqM, r => {\n            // part 2 of calculations comes here\n            }\n        });\n        exportList(etqM, "tableB", true);\n    });	0
3839363	3839086	Foreground listbox color	if (e.Index < 0)\n    return;\n\nBrush foreBrush = Brushes.Black; // non-selected text color\nif ((e.State & DrawItemState.Selected) == DrawItemState.Selected)\n{\n    foreBrush = Brushes.White; // selected text color\n    e = new DrawItemEventArgs(e.Graphics,\n                              e.Font,\n                              e.Bounds,\n                              e.Index,\n                              e.State ^ DrawItemState.Selected,\n                              e.ForeColor,\n                              Color.Red); // Choose the color \n}\n\n// Draw the background of the ListBox control for each item. \ne.DrawBackground();\n// Draw the current item text\ne.Graphics.DrawString((sender as ListBox).Items[e.Index].ToString(), e.Font, foreBrush, e.Bounds, StringFormat.GenericDefault);\n// If the ListBox has focus, draw a focus rectangle around the selected item. \ne.DrawFocusRectangle();	0
11074639	11074575	c# HTMLElement get specific child	//table/tr/td[position()=2]	0
13877813	13875858	How can i edit a HTTP a request C# using fiddlercore	session.RequestBody = myBytes;	0
24994415	24992304	How to Set BlackOutDates for Multiple Months in WPF DateTimePick	private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)\n    {\n        if (e.PropertyName == "DisplayDate")\n        {\n            BlackOutDates = new List<DateTime> { DisplayDate.Date.AddDays(randm.Next(1, 5)), DisplayDate.AddDays(randm.Next(1, 5)) };\n        }\n    }	0
5557026	5556472	How to parse formula values as text in Excel via C#	using Microsoft.Office.Interop.Excel;\n\nstring fileName = @"C:\TestSheet.xls";\nApplication xlApp = new Application();\nWorkbook book = xlApp.Workbooks.Open(fileName);\nWorksheet sheet = xlApp.Worksheets[1];\nRange range = sheet.get_Range("A1");\nConsole.WriteLine(range.get_Value(XlRangeValueDataType.xlRangeValueDefault));	0
11913833	11913268	How to replace a sequence of items in a collection, using other collections?	static IEnumerable<T> Replace<T>(IEnumerable<T> source, IDictionary<IEnumerable<T>, IEnumerable<T>> values)\n{\n  foreach (var kvp in values)\n    source = ReplaceOne(source, kvp.Key, kvp.Value);\n  return source;\n}\n\nstatic IEnumerable<T> ReplaceOne<T>(IEnumerable<T> source, IEnumerable<T> fromSeq, IEnumerable<T> toSeq)\n{\n  var sArr = source.ToArray();\n\n  int replLength = fromSeq.Count();\n  if (replLength != toSeq.Count())\n    throw new NotSupportedException();\n\n  for (int idx = 0; idx <= sArr.Length - replLength; idx++)\n  {\n    var testSeq = Enumerable.Range(idx, replLength).Select(i => sArr[i]);\n    if (testSeq.SequenceEqual(fromSeq))\n    {\n      Array.Copy(toSeq.ToArray(), 0, sArr, idx, replLength);\n      idx += replLength - 1;\n    }\n  }\n\n  return sArr;\n}	0
16156034	16147116	Generic Lists in a HttpSessionState stored in SQL	Page.Controls	0
4040222	4040172	How to tell in protobuf-net how many bytes were read from a NetworkStream on a call to DeserializeWithLengthPrefix	out bytesRead	0
16081120	9820962	Deleting a chlid object from a collection with MVC3 Entity Framework 4.3 Code First	foreach(Email email in User.Emails)\n{\n    if(string.IsNullOrEmpty(email.Address))\n    {\n        db.Entry(email).State = System.Data.EntityState.Deleted;\n    }\n}\ndb.SaveChanges();	0
7218287	7218158	How can I create a pop-up window using a new page as the pop-up source?	///Perform server side process. If successfully executed close this window. \n  protected void btnSubmit_Click(object sender, EventArgs e)\n  if(EverythingOK) \n        { \n           StringBuilder cstext2 = new StringBuilder();\n  cstext2.Append("<script type=\"text/javascript\"> function CloseMe() {");\n  cstext2.Append("window.close();} </");\n  cstext2.Append("script>");\n  cs.RegisterStartupScript(cstype, csname2, cstext2.ToString(), false);\n        } \n\n    }	0
30449064	30448697	Data is Null in my case in my List.Add	RequestID = key,\n                        PartDesc = reader.IsDBNull(17) ? null : reader.GetString(17),\n                        PartNumber = reader.IsDBNull(23) ? null : reader.GetString(23),\n                        SupplierID = reader.IsDBNull(18) ? null : reader.GetString(18),\n                        FullName = reader.IsDBNull(7) ? null : reader.GetString(7),\n                        AccountType = reader.IsDBNull(19) ? null :  reader.GetString(19),\n                        CurrName = reader.IsDBNull(20) ? null :  reader.GetString(20),\n                        PartQuantity = (double)reader.GetDecimal(21),\n                        PiecePrice = (double)reader.GetDecimal(22),\n                        Amount = dAmount	0
8520602	8508393	How do I properly cast this?	FileAccess fa = new FileAccess();\nIAccess<T> test = fa as IAccess<T>;	0
1026986	1025816	how to reload saved "Embed Source" clipboard data?	System.IO.FileStream s = System.IO.File.Open("c:\\temp\\dxf.ole",System.IO.FileMode.Open);\n\n        Clipboard.SetData("Embed Source", s);\n\n        s.Close();	0
6822127	6821787	Loading XML into a memorystream	using(StringReader reader = new StringReader(strInstallDataSet)) \n{\n    dsInstallData.ReadXml(reader);\n}	0
13837386	13837354	C# - Search for digits in string with Regex	var matches = Regex.Matches(foo, @"%(\d+?)%").Cast<Match>()\n                   .Select(m => m.Groups[1].Value)\n                   .ToList();	0
32914645	32914436	adding to a list from within method	private static List<string> test;\n\nprotected void Page_Init(object sender, EventArgs e) {\n    test = test ?? new List<string>();\n    // ... additional initalization\n}	0
22627354	22627122	How to create table by giving width option?	string width = string.IsNullOrEmpty(txtWidth.Text.Trim()) ? string.Empty : "(" + txtWidth.Text.Trim() + ")"\nstring s = "CREATE TABLE [" + "" + rchtxtFieldCode.Text + "] " + " (" + rchFieldTitle.Text + " " + combDataType.Text + width + ")";	0
22888978	22883953	Custom Action with LinqPad Hyperlinq()	dim h = New Hyperlinq(Function() "foo".Dump, "Click me")\nh.Dump	0
2014311	2014287	How to auto scroll down in WinForms ListView control when update new item?	listView1.Items[listView1.Items.Count - 1].EnsureVisible();	0
7539742	7538900	How to convert a strongname public key (snk) to <RSAKeyValue>?	Console.WriteLine (new StrongName (data).RSA.ToXmlString (false));	0
1799401	1799370	Getting attributes of Enum's value	var type = typeof(FunkyAttributesEnum);\nvar memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());\nvar attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),\n    false);\nvar description = ((DescriptionAttribute)attributes[0]).Description;	0
31687662	31687484	Creating LINQ statement against an EF Context with no relationships	int humanId = 1234;\n\nusing (var context = new MyContext())\n{\n    var human = (from h in context.Humans\n                 join lf in context.Foods on h.LastFoodEatenId equals lf.foodId into lfg\n                 from lf in lfg.DefaultIfEmpty() // left join\n                 join ff in context.Foods on h.FavoriteFoodId equals lf.foodId into ffg\n                 from ff in ffg.DefaultIfEmpty() // left join\n                 join cf in context.Foods on h.CurrentlyDesiredFoodId equals lf.foodId into cfg\n                 from cf in cfg.DefaultIfEmpty() // left join\n                 join p in context.Pets on h.humanId equals p.humanId into pg // group\n                 join t in context.Toys on h.humanId equals t.humanId into tg // group\n                 where h.humanId = humanId\n                 select new QueryResult { human = h, LastEatenFood = lf, FavoriteFood = ff, CurrentlyDesiredFood = cf, Toys = tg, Pets = pg }\n                 ).SingleOrDefault();\n}	0
22643871	22643370	changing button location on panel,Group box or Table layout panel	TableLayoutPanelCellPosition cell1 = tlp.GetCellPosition(button1);\ntlp.SetCellPosition(button1, tlp.GetCellPosition(button2));\ntlp.SetCellPosition(button2, cell1);	0
23453628	23453320	C# - Getting minimum value from dataGridView specific column?	private void button1_Click(object sender, EventArgs e)\n{\n    List<int> costs = new List<int>();\n\n    //Iterate through each row in the grid\n    foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n        if (null != row && null != row.Cells[1].Value)\n        {\n           //Add cost value to list\n           costs.Add(Convert.ToInt32(row.Cells[1].Value.ToString()));\n        }\n    }\n\n    //get 50% of min value(lowest)\n    int result = costs.Min() / 2;\n}	0
12514540	12514507	Display a gridView row information in another form	DataRow row = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);\n  Form2 frm = new Form2(row);\n  frm.Show();	0
19692798	19692435	How do I prevent a form from closing and display a confirmation dialog?	protected override void OnFormClosing(FormClosingEventArgs e) {\n  if (e.CloseReason == CloseReason.UserClosing) {        \n    if (MessageBox.Show("Do you want to close?", \n                        "Confirm", \n                        MessageBoxButtons.YesNo,\n                        MessageBoxIcon.Question) == DialogResult.No) {\n      e.Cancel = true;\n    }\n  }\n  base.OnFormClosing(e);\n}	0
16209324	16209288	log4net in WCF service hosted on a windows service	[assembly: log4net.Config.XmlConfigurator(Watch=true)]	0
20423008	20422896	Add only 1 category to a MailItem when saving multiple attachments	if (!mailItem.Categories.Contains(OutlookCategories.CategorieBijlage))\n{\n     //if attachment is being saved add "attachment saved" category to mailitem\n     mailItem.Categories = string.Format("{0}, {1}", OutlookCategories.CategorieBijlage, mailItem.Categories);\n     //Opslaan van MailItem.\n     mailItem.Save();\n}	0
9297024	9296981	Read Global Application property from WCF Service	var yourData=HttpContext.Current.Application["data"];	0
34285009	34284908	Checking equality with a HashSet of objects	var setComparer = HashSet<Location>.CreateSetComparer();\nreturn other.Variable.Equals(this.Variable) && setComparer.Equals(this.LocationList, other.LocationList);	0
1381036	1381026	Regular Expression to help with Rewriting a URL	Regex.Replace(stringToCleanUp, "[^a-zA-Z0-9/;\-%:]", string.Empty);	0
5673060	5672862	Check if datetime instance falls in between other two datetime objects	// Assuming you know d2 > d1\nif (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)\n{\n    // targetDt is in between d1 and d2\n}	0
24298521	24298372	extract password protected sfx archive using c#	Process process = new Process();\nprocess.StartInfo.FileName = "unrar.exe";\nprocess.StartInfo.Arguments = "x -p123456 file.rar d:\myFolder";\nprocess.Start();\nprocess.WaitForExit();	0
19579680	19533453	How to detect which thread is holding the application from shut down in .NET	protected override void OnStartup(StartupEventArgs e)\n        {\n              Current.ShutdownMode = ShutdownMode.OnMainWindowClose;\n}	0
9130922	9128934	Unable to access my repository with Dependency Injection (variable is still null)	ninject.mvc3	0
3123525	3121688	Performance Counter Input string was not in a correct format C#	---------------------------\nPerformance Monitor Control\n---------------------------\nUnable to add these counters:\n\n\Memory\Available MBytes\n\Memory\% Committed Bytes In Use\n\Memory\Cache Faults/sec\n\Memory\Cache Faults/sec\n\PhysicalDisk(*)\% Idle Time\n\PhysicalDisk(*)\Avg. Disk Queue Length\n\Network Interface(*)\Bytes Total/sec	0
15979513	15978912	programatically change proxy address on win 7	string keyName = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";\nusing (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))\n{\n    if (key != null)\n    {\n        key.SetValue("ProxyEnable", 0);\n    }\n}	0
28707067	28706870	How to execute a scheduled task with ?schtasks? without opening a new command line window using C# process?	using (var ts = new TaskService())\n{\n    Task task = ts.GetTask("My task");                \n    task.Run();                \n}	0
2876172	2872739	Map Literals to Object Properties/Values	public class Common\n{\n    public const string STARTDATE = "STARTDATE";\n    public const string CUSTOMERNAME = "CUSTOMERNAME";\n\n    public static string GetMappedValue(string inputVariable)\n    {\n        string mappedTo = null;\n\n        switch(inputVariable)\n        {\n            case "abc":\n                mappedTo = SOME_OTHER_CONSTANT_HERE; //map it \n                break;\n            case "xyz":\n                mappedTo = FOO;\n                break;\n            //etc etc...\n        }\n\n        return mappedTo;\n    }	0
2683910	2683892	Attribute to skip over statement in unit test c#	public MyClass(IMessageBoxDisplayService messageBoxDisplayService)\n{ \n    ...\n    if (messageBoxDisplayService.Show(message)) ...	0
5306538	5277962	How to show the PI tagsearch dialog and return tagname as string?	private void Button1_Click(object sender, EventArgs e) {\n    TagSearch dialog = new TagSearch();\n\n    PointList results = dialog.showTagSearch(\n        new string[] { }, SearchOptions.SingleSelect);\n\n    if (results.Count > 0) {\n        object index = 1;\n        string serverTag = \n            string.Format(\n                CultureInfo.InvariantCulture, \n                @"\\{0}\{1}", \n                results.get_Item(ref index).Server.Name, \n                results.get_Item(ref index).Name);\n    }\n}	0
32924624	32924198	Extract String Regex	string s = "LogHit('EJI2BLMIF9T9HVC','E','MK9LBROIB0MPI23');";\nMatch match = Regex.Match(s, "^LogHit\\('([^']+)'");\n\nConsole.WriteLine(match.Groups[1].Value); // EJI2BLMIF9T9HVC	0
22102440	22102380	How to promise the compiler that the generic type will have a certain property?	public interface IMyInterface\n{\n    public object Value { get; set; }\n}\n\npublic class C<T> where T:IMyInterface	0
9453686	9421715	How to activate the next or last view of a region?	private void Next(object commandArg)\n    {\n        IRegion myRegion = _regionManager.Regions["TopLeftRegion"];\n        object activeView = myRegion.ActiveViews.FirstOrDefault();  //Here we're trusting that nobody changed the region to support more than one active view\n        List<object> myList = myRegion.Views.ToList<object>();      //Cast the list of views into a List<object> so we can access views by index\n\n        int currentIndex =  myList.FindIndex(theView => theView == activeView);\n        int nextIndex = (currentIndex + 1) % (myList.Count);        //Wrap back to the first view if we're at the last view\n        object nextView = myList[nextIndex];\n        myRegion.Activate(nextView);  \n    }	0
11055093	11053598	How to mock the CreateResponse<T> extension method on HttpRequestMessage	request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());	0
34043013	34042735	XML parsing in C#	string myFilter = "LngCode";\n    var xDoc = XDocument.Load(@"C:\temp.xml");\n    var elements = xDoc.Descendants("AttrName")\n        .Where(d => d.Value.Equals(myFilter))\n        .Select(d => d.ElementsAfterSelf().FirstOrDefault());\n\n    foreach (var element in elements)\n    {\n        Console.WriteLine(element.Value);\n    }	0
1252330	1246263	Get log details for a specific revision number in a post-commit hook with SharpSVN?	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
20579980	20579816	Windows phone Web scraping	private void button1_Click(object sender, EventArgs e)\n{\n    var webget = new HtmlWeb();\n    var doc = webget.Load("http://www.dmp.gov.bd/application/index/pressdetails/press_159");\n\n    HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='span8 inner_mess']");\n\n    TraverseNodes(node.ChildNodes);\n}\n\nprivate void TraverseNodes(HtmlNodeCollection nodes)\n{\n    foreach (HtmlNode node in nodes)\n    {\n        textBox1.Text += node.InnerText;\n\n        TraverseNodes(node.ChildNodes);\n    }\n}	0
28805742	28761877	how to insert text from c# application into MS word document and save it as new file	private void btnSave_Click(object sender, EventArgs e)\n    {\n\n\n        SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n\n        saveFileDialog1.Filter = "Word document|*.doc";\n        saveFileDialog1.Title = "Save the Word Document";\n        saveFileDialog1.FileName = "MS word document.docx";\n\n        if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n        {\n            File.WriteAllText(saveFileDialog1.FileName,txtResult.Text.ToString());\n        }\n    }	0
13957160	13854068	DTD prohibited in xml document exception	XmlReaderSettings settings = new XmlReaderSettings();\nsettings.ProhibitDtd = false;	0
17733802	17733777	Using C# to loop through and insert data	cmd.ExecuteNonQuery();	0
1496459	1496421	Reading line by line	MatchCollection lines = Regex.Matches(File.ReadAllText(fileName), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n");\nforeach (Match match in lines) {\n   string control = match.Groups[1].Value;\n   string text = match.Groups[2].Value;\n   int x = Int32.Parse(match.Groups[3].Value);\n   int y = Int32.Parse(match.Groups[4].Value);\n   Console.WriteLine("{0}, \"{1}\", {2}, {3}", control, text, x, y);\n}	0
12982637	12982588	How can I use LINQ and C# to find the oldest date from 3 different files?	var result = dates.Min();	0
24965262	24964985	Trying to duplicate api authentication from iOS app into java, don't userstand code	header = 'Basic ' + base64(email:password)	0
33981672	33923356	How to get list of paired bluetooth devices on Windows 10 Universal Application	var selector = BluetoothDevice.GetDeviceSelector();\nvar devices = await DeviceInformation.FindAllAsync(selector);	0
10106774	10106716	LINQ to JSon response	List<Student> students = GetStudentList();\nreturn Json(students));	0
6000606	6000517	C# - StyleCop - SA1121: UseBuiltInTypeAlias - Readability Rules	BinaryReader br = new BinaryReader(...);\nfloat val = br.ReadSingle(); // OK, but feels unnatural\nSingle val = br.ReadSingle(); // OK and feels good	0
3279690	3279666	In Linq, how to find if a set contains an element without using Count(predicate)?	if (Products.Any(c => c.ProductId = 1234))\n{\n//do stuff\n}	0
24791939	24791920	converting IntPtr as c# struct pointer	Marshal.PtrToStructure	0
30339511	30335358	Execute Stored Procedure using current LightSwitch ConnectionString	string _ConnectionString = ConfigurationManager.ConnectionStrings["DataSourceName"].ConnectionString;\n\nSqlConnection sqlconn = new SqlConnection(_ConnectionString);\nSqlCommand sqlcmd = new SqlCommand("sp_StoredProcName", sqlconn);\nsqlcmd.CommandType = CommandType.StoredProcedure;\nsqlconn.Open();\n\nSqlParameter sqlParam1 = sqlcmd.Parameters.AddWithValue("@param", "ParamText");\n\nSqlDataReader reader = sqlcmd.ExecuteReader();	0
16605168	16605125	Transform from array to data table	foreach (DataRow row in rowArray) {\n       dataTable.ImportRow(row);\n    }	0
11665019	11664924	Fetching data from database and passing to another form	con.Open();\nSqlCommand cmd1 = new SqlCommand("select balance from customer where namee='" \n                        + textBox1.Text + "'", con);\nlabel4.Text = cmd1.ExecuteScalar();	0
18940981	18940968	Databind XML to C# using LINQ returning one result	var data = from query in xdoc.Descendants("AppID")\n                   select new AppToDownload\n                   {\n                       AppID = query.Value\n                   };	0
29793049	29792806	Calculation using grouped data in Linq to entities	(int?)(Math.Round(((Decimal)wi2Complete.Count() / wiAll.Count()) * 100))	0
16150209	16148447	ListBox with switches or observable dictionary	public class SettingsModel : ViewModelBase\n{\n    private bool _value;\n    public bool Value\n    {\n        get { return _value; }\n        set { Set(() => Value, ref _value, value); }\n    }\n\n    private string _kind;\n    public string Kind\n    {\n        get { return _kind; }\n        set { Set(() => Kind, ref _kind, value); }\n    }\n}	0
15482150	15449343	Get the public key of a website's SSL certificate	Uri u = new Uri(url);\n        ServicePoint sp = ServicePointManager.FindServicePoint(u);\n\n        string groupName = Guid.NewGuid().ToString();\n        HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest;\n        req.ConnectionGroupName = groupName;\n\n        using (WebResponse resp = req.GetResponse())\n        {\n\n        }\n        sp.CloseConnectionGroup(groupName);\n        byte[] key = sp.Certificate.GetPublicKey();\n\n        return key;	0
6088768	6088737	Working on Console.Write String Formatting with	if((i % n) == 0) {\n  Console.WriteLine();\n}	0
14829217	14829145	C# callback parameter	public void callback(object value)	0
220166	220100	How do I enable double-buffering of a control using C# (Windows forms)?	this.DoubleBuffered = true;\nthis.SetStyle(ControlStyles.UserPaint | \n              ControlStyles.AllPaintingInWmPaint |\n              ControlStyles.ResizeRedraw |\n              ControlStyles.ContainerControl |\n              ControlStyles.OptimizedDoubleBuffer |\n              ControlStyles.SupportsTransparentBackColor\n              , true);	0
9023986	9023946	How to capture command line arguments in WPF application?	Environment.GetCommandLineArgs()	0
12368299	12368136	Is it possible to perform Bulk Insert in MSAccess	var cmdText = "INSERT INTO Table1 SELECT * FROM Table2";\nvar command = new OleDbCommand(cmdText, connection);\ncommand.ExecuteNonQuery();	0
14074454	14074309	Order a List<T> by Date, but it has a String ID, if that ID is repeated with different date in the collection with should appear below of it	var result = oList.OrderByDescending(x => x.OperationDate)\n                  .GroupBy(x => x.IdFinder)\n                  .SelectMany(x => x);	0
22768064	22761716	Print to File Programatically using Adobe Acrobat	...\n    printDocument1.PrinterSettings.PrintToFile = true\n    printDocument1.PrinterSettings.PrintFileName = "c:\temp\test.ps"\n    printDocument1.Print()	0
13008129	12956226	Read AppSettings from MEF plugin	[Export(IPlugin)]\npublic class Plugin\n{\n    public Plugin()\n    {\n        var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);\n        var value = config.AppSettings.Settings["Key2"].Value;\n    }\n}	0
21377544	21377049	LINQ/EF - How to select range of data	int key=10;\nint range=2;\n\nvar v= employeeList.GetRange((employeeList.FindIndex(x => x == key) - range), (range + range + 1));	0
23754817	23754534	Windows Phone 8 APP Deployment with Capabilities?	if (ProximityDevice.GetDefault() != null)\n   MessageBox.Show("NFC present");\n else\n   MessageBox.Show("Your phone has no NFC or NFC is disabled");	0
11206962	8248000	How to programatically login on sharepoint	private bool loginSharePoint()\n    {\n        lbLoginStatus.Text = "Logging in Sharepoint server";\n\n        bool isValid = false;\n\n        //validating Sharepoint login\n        string spUsername = tbSharePointUsername.Text;\n\n        string spPassword = tbSharePointPassword.Text;\n\n\n        pc = new PrincipalContext(ContextType.Domain, spUsername.Split('\\')[0]);\n\n        pbLogin.PerformStep();\n        // validate the credentials\n        isValid = pc.ValidateCredentials(spUsername.Split('\\')[1], spPassword);\n        if (isValid)\n        {\n            pbLogin.PerformStep();\n\n            pbLogin.PerformStep();\n            site = new SPSite(tbSharePointUrl.Text);\n\n            pbLogin.PerformStep();\n            web = site.OpenWeb();\n\n            pbLogin.PerformStep();\n            if (web.DoesUserHavePermissions(spUsername, SPBasePermissions.Open))\n                isValid = true;\n            else\n                isValid = false;\n        }\n\n\n        return isValid;\n    }	0
21452022	21448115	how to map image to image button in asp.net with session using c#?	public static void DisablePageCaching()\n{\n    //Used for disabling page caching\n    HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));\n    HttpContext.Current.Response.Cache.SetValidUntilExpires(false);\n    HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);\n    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n    HttpContext.Current.Response.Cache.SetNoStore();\n}	0
18638178	18636080	How do I get a list of tasks for an instance in cDevworkFlow?	string connectString = ""; //get your workflow db connection string\n        string currentUserId = ""; //get current userid\n        string instanceId = ""; //get instance id to get the tasks\n\n        deRuntime oRuntime = new deRuntime(connectString, currentUserId);\n        deInstance oInstance = oRuntime.getInstance(instanceId);\n        DataTable oTasks = oInstance.getTasks();\n\n        //from the datatable oTasks you can see the status of each task	0
10158774	10158746	Cant add roles automatically	Roles.AddUserToRole(model.UserName, "roleName");	0
4794140	4793981	Converting Expression<T, bool> to String	Expression<Func<Product, bool>> exp = (x) => (x.Id > 5 && x.Warranty != false);\n\nstring expBody = ((LambdaExpression)exp).Body.ToString(); \n// Gives: ((x.Id > 5) AndAlso (x.Warranty != False))\n\nvar paramName = exp.Parameters[0].Name;\nvar paramTypeName = exp.Parameters[0].Type.Name;\n\n// You could easily add "OrElse" and others...\nexpBody = expBody.Replace(paramName + ".", paramTypeName + ".")\n                 .Replace("AndAlso", "&&");\n\n\nConsole.WriteLine(expBody);\n// Output: ((Product.Id > 5) && (Product.Warranty != False))	0
17290448	17290283	image rotation with white background	public Bitmap RotateBitmap(Image bitmap, float angle) {\n    Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);\n    using(Graphics graphics = Graphics.FromImage(result)) {\n        graphics.TranslateTransform((float)bitmap.Width / 2f, (float)bitmap.Height / 2f);\n        graphics.RotateTransform(angle);\n        graphics.TranslateTransform(-(float)bitmap.Width / 2f, -(float)bitmap.Height / 2f);\n        graphics.DrawImage(bitmap, Point.Empty);\n    }\n    return result;\n}	0
31237764	31140065	SqlBulkCopy insert order	Step1: var dt = select *, id as tempId from server1.dbo.TableA order by id;\nStep2: SQL bulk copy into server2 bulkCopy.WriteToServer(dt);\nStep3: var resultDt = select top 4 id, tempId from server2.dbo.TableA order by id desc. Since we know the number of records we inserted I am using "top 4".	0
4287823	4286473	List<int> takes long time to instantiate with Nhibernate Criteria	var sql =\n            String.Format(\n                @"select circt_id as CircuitId from normal_upstream\n                where dni_equip_type = 'FDR_OCR'\n                        start with up_equip_stn_no in ({0})\n                        connect by prior equip_stn_no = up_equip_stn_no\n                        union\n                        select circt_id as CircuitId\n                        from normal_upstream \n                        where up_equip_stn_no in ({0})",\n                String.Join(",",upstreamStations.Select(x=>"'"+x+"'").ToArray()));\n        var criteria =\n            GetSession().CreateSQLQuery(sql)\n                .AddScalar("CircuitId", NHibernateUtil.Int32)\n                .List();\n            return criteria;	0
28719192	28718899	How to create 2 dimensional json object in chsarp	var Obj = new \n{ \n    username = new \n    { \n        username = "Test", \n        password = "TEST" \n    }, \n    key = new \n    { \n        Key1 = "OK" \n    } \n};	0
9336234	9336188	Index Array with TimSort in C#	public static void TimSort<T>(this IList<T> array, Comparison<T> comparer, bool buffered = true)	0
13024620	13024506	How to map a parent/child collection model using Automapper?	AutoMapper.Mapper.CreateMap<Order, DTOOrder>()\n    .ForMember(o => o.OrderItems, dto => dto.DTOOrderItems)	0
6230976	6230950	linq insert: getting the row number	using (var dc = new MyDataContext())\n{\n    MyEntity entity = new MyEntity();\n\n    dc.MyEntities.InsertOnSubmit(entity);\n    dc.SubmitChanges();\n\n    int pkValue = entity.PKColumn\n}	0
18472407	18472128	Creating custom Html Helper: MyHelperFor	public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)\n{\n    var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);\n    string propertyName = data.PropertyName;\n    TagBuilder span = new TagBuilder("span");\n    span.Attributes.Add("name", propertyName);\n    span.Attributes.Add("data-something", "something");\n\n    if (htmlAttributes != null)\n    {\n        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n        span.MergeAttributes(attributes);\n    }\n\n    return new MvcHtmlString(span.ToString());\n}	0
34175770	34175668	How to define base class and generic constraint	public class ServiceAccessBase<TResult, TResultBase> : IServiceAccessBase\n             where TResult : class, TResultBase, new()\n{ }	0
21586573	21586276	Get integer list from a webapi	client.GetAsync("api/category/getkeywordidsbyid/" + id).Result.Content.ReadAsAsync<List<int>>().Result;	0
17614769	17594672	After button having postback	Try this  \n    if(IsPostBack)\n     {                      \n       if(btnNew.Style.Value == "Display:none;")\n      {\n             GenerateBlankTableHtml("");\n      }                     \n    }\n\n   protected void btnNew_Click(object sender, EventArgs e)\n    {\n      GenerateBlankTableHtml("");\n    }	0
29865393	29865276	How can I take objects from the second set of objects which don't exist in the first set of objects in fast way?	// Some people1 and people2 lists of models already exist:\nvar sw = Stopwatch.StartNew();\nvar removeThese = people1.Select(x=>Tuple.Create(x.FirstName,x.LastName));\nvar dic2 = people2.ToDictionary(x=>Tuple.Create(x.Name,x.Surname),x=>x);\nvar result =  dic2.Keys.Except(removeThese).Select(x=>dic2[x]).ToList();\nConsole.WriteLine(sw.Elapsed);	0
7820149	7820070	How to bind DataRow to the GridView?	var Temp = dt.AsEnumerable().Take(1).CopyToDataTable();	0
32645031	32644862	Inserting a text box into a usercontrol dynamically	TextBox tb1=new TextBox();\n    tb1.ID="TbA";\n    Uc1.Controls.Add(tb1);//here Uc1 is the Id of the userControl.Which is registered in .aspx file	0
17398166	17397439	Sample for wpf detail master view	IsSynchronizedWithCurrentItem="true"	0
4862448	4862416	How do I move items in an array to the immediate next index?	shift (list, index, index2) {\n  if (index < list.size()){\n    shift(index+1, index2+2)\n    list[index2] = list[index]\n  }\n}	0
10656230	10656111	How do I make a report that constantly updates when I set values?	reportViewer.RefreshReport();	0
10928828	10928319	Get all users, only when they don't occur in another table	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n            var usersTakenTest = new List<string>() { "Bob", "Jim", "Angel" };\n            var allUsers = new List<string> { "Bob", "Jim", "Angel", "Mike", "JimBobHouse" };\n\n            var users = from user in allUsers\n                        join userTakenTest in usersTakenTest on user equals userTakenTest into tempUsers\n                        from newUsers in tempUsers.DefaultIfEmpty()\n                        where string.IsNullOrEmpty(newUsers)\n                        select user;\n\n            foreach (var user in users)\n            {\n                Console.WriteLine("This user has not taken their test: " + user);\n            }\n            Console.ReadLine();\n        }\n    }\n}	0
6874261	6874219	How can i sort by a string property but not alphabetically	public enum Status\n     {\n        Pending,\n        Closed,\n        Open\n      }	0
411332	411316	How to access properties of a usercontrol in C#	class MyUserControl\n{\n  // expose the Text of the richtext control (read-only)\n  public string TextOfRichTextBox\n  {\n    get { return richTextBox.Text; }\n  }\n  // expose the Checked Property of a checkbox (read/write)\n  public bool CheckBoxProperty\n  {\n    get { return checkBox.Checked; }\n    set { checkBox.Checked = value; }\n  }\n\n\n  //...\n}	0
13940400	13940287	regexp to put one var into the value of regexp of another	string userId = "ololoawd";\nstring did = Regex.Match(content, @"""dID"":""(.*?)"",""dOF"":true,""dOID"":""" + userId + @""",""usS"":").Groups[1].Value;	0
9114374	9114013	Regular Expression match ID in ClientId	using System;\n\nnamespace ConsoleApplication3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string text = "master$maincontentplaceholder$ucsearchresults$ucfilter$hdnvalue";\n            string id = text.Substring(text.LastIndexOf("$") + 1);\n            Console.WriteLine(id);\n            Console.ReadLine();\n        }\n    }\n}	0
1888884	1888514	How can I pass addition parameters to my centralized event handlers?	public class CommonEventHandler\n{\n    private CommonEventHandler() { }\n\n    private object Context { get; set; }\n\n    public static EventHandler CreateShowHandlerFor(object context)\n    {\n        CommonEventHandler handler = new CommonEventHandler();\n\n        handler.Context = context;\n\n        return new EventHandler(handler.HandleGenericShow);\n    }\n\n    private void HandleGenericShow(object sender, EventArgs e)\n    {\n        Console.WriteLine(this.Context);\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        EventHandler show5 = CommonEventHandler.CreateShowHandlerFor(5);\n        EventHandler show7 = CommonEventHandler.CreateShowHandlerFor(7);\n\n        show5(null, EventArgs.Empty);\n        Console.WriteLine("===");\n        show7(null, EventArgs.Empty);\n    }\n}	0
17390805	17389615	Create a sysprep provider with C#	class Test\n{\n    [DllExport( "add", CallingConvention = CallingConvention.Cdecl )]\n    public static int TestExport( int left, int right )\n    {\n        return left + right;\n    } \n}	0
22556563	22556365	How to get a IEnumerable<class> from c# in JavaScript	public string SerializedPointOffices\n{\n    get { return JsonConvert.SerializeObject(this.PointOffices); }\n}	0
11466208	11466160	Get filename of my crystal report as Caption in a form in c#	string path = @"C:\PerxClub\PerxClub\Reports\CrystalReport1.rpt";\nstring result = Path.GetFileName(path);	0
21734944	21734692	How to convert resulted thresolded image in picturebox to 8bbp pixel format	Bitmap newBitmap = new Bitmap(bm.Width, bm.Height);\n  Graphics graphics = Graphics.FromImage(newBitmap);\n  graphics.DrawImage(bm, 0, 0);	0
18869387	18868384	calling a view in clicking on menu item using javascript	function loadSearchPage() {\n        window.location.href = '@Url.Action("SearchDisplay", "Controller")';\n    }	0
14046930	14046864	How to use Regular Expression with FindWindow?	EnumWindows()	0
15095014	15094819	How to connect to a remote MySQL server using C#?	GRANT ALL PRIVILEGES ON *.* TO root@"%" IDENTIFIED BY 'rootPass';	0
21703959	21703811	Xml Serializing and Writer	XmlSerializer serializer = new XmlSerializer(tool.GetType());\n            using (var writer = new StreamWriter(@Start.userConfigurePath + "\\config.xml"))\n            {\n                serializer.Serialize(writer.BaseStream, tool);\n            }	0
10920066	10919838	C# how to open two windows and make one control certain variables	private string _Message;\n    public string Message\n    {\n        get { return _Message; }\n        set\n        {\n            _Message = value;\n            if (PropertyChanged != null)\n                PropertyChanged(this, new PropertyChangedEventArgs("Message"));\n        }\n    }	0
2568723	1360944	Force GUI update from UI Thread	private void SetStatus(string status) \n{\n    lblStatus.Text = status;\n    lblStatus.Invalidate();\n    lblStatus.Update();\n    lblStatus.Refresh();\n    Application.DoEvents();\n}	0
28078106	28078006	Error: Is a physical path, but a virtual path was expected	using (StreamWriter myStream = new StreamWriter("~/path/tofolder/" + filename))\n{\n    myStream.Write(stringWrite.ToString());\n}	0
26898078	26879270	How to refactor to reduce nesting depth with try/multiple catches (NDepend)	try\n{\n   /* Your code */\n}\ncatch(Exception ex)\n{\n    var exceptionHandler = _exceptionHandlers[ex.GetType()];\n    exceptionHandler.Execute(ex);\n}	0
21720270	21720218	MySQL Syntax error near ' ' at line 1	CREATE TABLE IF NOT EXISTS PlantAreaCode (\nACId INT NOT NULL AUTO_INCREMENT,\nAreaCode INT,\nAreaName CHAR(25),\nComments TEXT,\nPRIMARY KEY (ACId)\n);	0
12962024	12961916	How to automatically set IsSelected on a GridViewItem?	protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n{\n    base.PrepareContainerForItemOverride(element, item);\n\n    var listItem = element as GridViewItem;\n    listItem.IsSelected = true;\n}	0
2384489	2384208	Paginate rows from SQL	SELECT\n    *\nFROM\n    (\n        SELECT\n            row_number() over(ORDER BY news_id DESC) AS row_number,\n            *\n        FROM\n            news\n        WHERE\n            --user filter goes here\n            news_cat = 'Pizza'\n    ) AS T\nWHERE\n    row_number BETWEEN @start AND @start + 10	0
11125555	11125420	DataContext does not contain a constructor with 0 parameters	public AppDatabaseDataContext()\n    : this(@"Data Source=localhost;Initial Catalog=Foo;Integrated Security=True")\n{\n}	0
10823072	10823026	Pass lambda to parameterized NUnit test	MatrixOperatorOperandIsNullThrows((l,r) => l + r);	0
1553271	1544336	How to change passwords using System.DirectoryServices.Protocols	using System.DirectoryServices.Protocols;\nusing System.Net;\n\n//...\n\n// Connect to the directory:\nLdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier("theServerOrDirectoryName");\n// You might need to specify a full DN for "theUsername" (I had to):\nNetworkCredential nc = new NetworkCredential("theUsername", "theOldPassword");\n// You might need to experiment with setting a different AuthType:\nLdapConnection connection = new LdapConnection(ldi, nc, AuthType.Negotiate);\n\nDirectoryAttributeModification modifyUserPassword = new DirectoryAttributeModification();\nmodifyUserPassword.Operation = DirectoryAttributeOperation.Replace;\nmodifyUserPassword.Name = "userPassword";\nmodifyUserPassword.Add("theNewPassword");\n\nModifyRequest modifyRequest = new ModifyRequest("theUsername", modifyUserPassword);\nDirectoryResponse response = connection.SendRequest(modifyRequest);	0
2095771	2085422	How to do a full outer join in Linq?	var studentIDs = StudentClasses.Select(sc => sc.StudentID)\n  .Union(StudentTeachers.Select(st => st.StudentID);\n  //.Distinct(); -- Distinct not necessary after Union\nvar q =\n  from id in studentIDs\n  join sc in StudentClasses on id equals sc.StudentID into jsc\n  from sc in jsc.DefaultIfEmpty()\n  join st in StudentTeachers on id equals st.StudentID into jst\n  from st in jst.DefaultIfEmpty()\n  where st == null ^ sc == null\n  select new { sc, st };	0
19181853	19181647	How to hide and show table in c#?	protected void txtGrade_TextChanged(object sender, EventArgs e)\n    {\n        if (txtGrade.Text == "II-61")\n        {  \n            if(tableCarDetails.css("display") == "none")\n            {\n                  tableCarDetails.Style.Add("display","block");\n            }\n         }\n        }\n    }	0
18050570	18050059	Downloading all spreadsheets to Excel in a Google account using C#	entry.Title.ToString() + "." + DownloaderSettings.Default.FileFormat	0
2146308	2146296	Adding a Time to a DateTime in C#	DateTime date = DateTime.Now;\nTimeSpan time = new TimeSpan(36, 0, 0, 0);\nDateTime combined = date.Add(time);\nConsole.WriteLine("{0:dddd}", combined);	0
7556941	7556493	How do I recognize a mouse click on a line?	private void myCanvas_Loaded(object sender, RoutedEventArgs e)\n        {\n            Line line = new Line();\n\n            line.MouseDown += new MouseButtonEventHandler(line_MouseDown);\n            line.MouseUp   += new MouseButtonEventHandler(line_MouseUp);\n\n            line.Stroke = Brushes.Black;\n            line.StrokeThickness = 2;\n            line.X1 = 30; line.X2 = 80;\n            line.Y1 = 30; line.Y2 = 30;\n\n            myCanvas.Children.Add(line);\n        }\n\nvoid line_MouseUp(object sender, MouseButtonEventArgs e)\n        {\n            // Change line colour back to normal \n            ((Line)sender).Stroke = Brushes.Black;\n        }\n\nvoid line_MouseDown(object sender, MouseButtonEventArgs e)\n        {\n            // Change line Colour to something\n            ((Line)sender).Stroke = Brushes.Red;\n        }	0
17694247	17694193	select row from winforms listview	private void buttonDelete_Click(object sender, EventArgs e)\n    {\n        //selected data is of custom type MyData\n        var selected = yourListView.SelectedItems.First();\n    }	0
16963371	16963370	freeze top row using spreadsheetgear	worksheet.Cells[1,0].Select();\nworksheet.WindowInfo.FreezePanes = true;	0
25429780	25429146	Post model and 2 checkbox lists to controller with Jquery Ajax	url: "@Url.Action("UpdateCommodityList", "ProductLine")",	0
1395065	1395058	Is there a naming convention for enum values that have a leading digit?	public enum EthernetLinkSpeed {\n Link10BaseT, Link1000BaseT, LinkDisconnected\n}	0
14900844	14900666	Windows Phone list is not displaying data	public List<Fellow> fellowList { get; set; }\n// Constructor\npublic MainPage()\n{\n    InitializeComponent();\n\n    fellowList = new List<Fellow>();\n    for (int i = 0; i < 2; i++)\n    {\n        Fellow fellow = new Fellow();\n        fellow.Name = "Danish " + i;\n        fellow.Email = "Email " + i;\n        fellowList.Add(fellow);\n    }\n    this.DataContext = this;\n    //lbFellows.ItemsSource = null;\n    lbFellows.ItemsSource = fellowList;\n}\n\npublic class Fellow\n{\n    public string Name { get; set; }\n    public string Email { get; set; }\n}	0
6698406	6698329	Dock or Anchor properties for microsoft reporting in winforms?	ReportViewer1.SizeToReportContent = true;\nReportViewer1.ZoomMode = ZoomMode.FullPage;	0
26572118	26572052	how do you Notify the ViewModel if you change values of a collection in the View	private ObservableCollection<TestVariable> testVariables;\npublic ObservableCollection<TestVariable> TestVariables \n{ \n   get{return testVariables;}\n   set\n   {\n     if(testVariables != value)\n       {\n         testVariables = value;\n         OnPropertyChanged("TestVariables");\n       }\n   }\n}	0
30225403	30225053	SQL Rows as CheckBoxes	List<string> listOfMarkets=new List<string>();    \n   while (sdr.Read())\n    {\n        listOfMarkets.Add(sdr["MarketID"].ToString());\n    }\n        Market1CheckBox.Checked = listOfMarkets.Contains("1")?true:false;\n        Market2CheckBox.Checked = listOfMarkets.Contains("2")?true:false;\n        Market3CheckBox.Checked = listOfMarkets.Contains("3")?true:false;\n        Market4CheckBox.Checked =listOfMarkets.Contains("4")?true:false;	0
7801124	7800882	Unity RegisterType for a constructor that takes services itself	container.RegisterType<IServiceA, ServiceA>();\ncontainer.RegisterType<IServiceB, ServiceB>(\n        new InjectionConstructor(path, new ResolvedParameter<IServiceA>()));	0
24640327	24170501	Cancelling TabPage.Validating locks my UI	private void tabControl1_Deselecting(object sender, TabControlCancelEventArgs e)\n{\n    switch (e.TabPageIndex)\n    {\n        case 0: \n            if (!validateTab1())\n            {\n                e.Cancel = true;\n            }\n            break;\n        case 1: \n            if (!validateTab2())\n            {\n                e.Cancel = true;\n            }\n            break;\n        default:\n            break;\n    }\n}	0
21994170	21993960	C# performing a task every hour	{\n    DateTime lastReset = DateTime.Min;\n    TimeSpan resetInterval = TimeSpan.FromMinutes(50);\n\n    foreach (var whatever in enumerable)\n    {\n        if ((DateTime.Now - lastReset) > resetInterval)\n        {\n            ResetAuthToken();\n            lastReset = DateTime.Now;\n        }\n        ProcessWhatever();\n    }\n}	0
12067549	11986941	Need to stop timer , because it is looping and opening the same window over and over	int count; \ncount = 0; \n\npublic Windowsplash \n\n    System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();\n    dispatcherTimer.Interval = new TimeSpan(0,0,0,500); \n    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); \n    dispatcherTimer.Start(); \n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e) \n{ \n    System.Windows.Threading.DispatcherTimer dispatcherTimer = sender as System.Windows.Threading.DispatcherTimer; \n\n        dispatcherTimer.Stop(); \n        MainWindow _new = new MainWindow(); \n        _new.Show(); \n        this.Close(); \n}	0
15368537	15367028	Select statement ignoring parameters?	string SelectOleDb = "SELECT Top 1 * From [Employee Info] Where Employee_Name= @EmployeeName Order By ID DESC";\n\n        OleDbConnection OleDbCon = new OleDbConnection(EmployeeInfo.Properties.Settings.Default.cstrEmployeeInfoDatabase);\n        OleDbDataAdapter OleDbAdpt = new OleDbDataAdapter();\n        OleDbCommand OleDbCom = new OleDbCommand(SelectOleDb, OleDbCon);\n        OleDbCom.Parameters.AddWithValue("@EmployeeName", employee_NameComboBox.Text);\n        OleDbAdpt.SelectCommand = OleDbCom;\n\n            DataSet EmployeeInfoDS = new DataSet();\n            OleDbCon.Open();\n            OleDbAdpt.Fill(EmployeeInfoDS);\n            OleDbCon.Close();\n            OleDbCon.Dispose();\n            DataTable EmployeeInfoDT = EmployeeInfoDS.Tables[0];	0
649476	649444	Testing equality of arrays in C#	var q = from a in ar1\n        join b in ar2 on a equals b\n        select a;\n\nbool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;	0
10127226	10126925	Retrieve value of enum given description of enum	// 1. define a method to retrieve the enum description\npublic static string ToEnumDescription(this Enum value)\n{\n    FieldInfo fi = value.GetType().GetField(value.ToString());\n\n    DescriptionAttribute[] attributes =\n        (DescriptionAttribute[])fi.GetCustomAttributes(\n        typeof(DescriptionAttribute),\n        false);\n\n    if (attributes != null &&\n        attributes.Length > 0)\n        return attributes[0].Description;\n    else\n        return value.ToString();\n}\n\n//2. this is how you would retrieve the enum based on the description:\npublic static MyEnum GetMyEnumFromDescription(string description)\n{\n    var enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();\n\n    // let's throw an exception if the description is invalid...\n    return enums.First(c => c.ToEnumDescription() == description);\n}\n\n//3. test it:\nvar enumChoice = EnumHelper.GetMyEnumFromDescription("Third");\nConsole.WriteLine(enumChoice.ToEnumDescription());	0
15678193	15678163	Passing values with session and adding to session one each page	var incident = Session["MyIncident"] != null ? (Incident)Session["MyIncident"] : new Incident();	0
7809172	7797074	Disable ajax for an imagebutton control inside a GridTemplateColumn of an ajaxified RadGrid	e.CommandName == "fbEdit"	0
18997842	18997798	How to loop controls in Content Place holder	Protected void btnbatch_Click(object sender, EventArgs e)\n{\n\n    Button btnactual= sender as Button;\n    ContentPlaceHolder myContent = \n   (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");\n\n    foreach (Control ctrl in myContent.FindControl("divBatches").Controls)\n    {\n        if (ctrl.ID == btnactual.ID)\n        {\n           //blah blah\n        }\n     }\n  }	0
12500115	12500091	DateTime.ToString() format that can be used in a filename or extension?	DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");	0
23242228	23223488	Documenting API model response model	[HttpGet]\n [ResponseType(typeof(CourseModel))]\n public HttpResponseMessage GetById(string id)\n {	0
3473079	3472842	Accessing a sibling property from within a collection	public class TestClass\n{\n    public DateTime Date { get; set; }\n    public IEnumerable<My_SiteReportResult> Reports {get;set;}\n}\n\npublic class UIDateAndReport\n{\n    public DateTime Date { get; set; }\n    public My_SiteReportResult Report { get; set; }\n}\n\nTestClass tst = new TestClass();\n...\nvar DatedReports =\n        (from r in tst.Reports\n         select new UIDateAndReport { Date = tst.Date, Report = r });	0
15228846	15228226	Extract SOAP Method from HttpRequest object in C#	public static void LogApiCall(HttpRequest httpRequest, string resultText = "Success", int resultCode = 0)\n{\n\n    XDocument bodyRequest = XDocument.Parse(GetDocumentContents(httpRequest));\n    string methodName = bodyRequest.Root\n                                    .Elements()\n                                    .Where(e => e.Name.LocalName == "Body")\n                                    .Elements()\n                                    .FirstOrDefault().Name.LocalName;\n}\n\nprivate static string GetDocumentContents(HttpRequest request)\n{\n    string documentContents;\n    using (Stream receiveStream = request.InputStream)\n    {\n        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))\n        {\n            documentContents = readStream.ReadToEnd();\n        }\n    }\n    return documentContents;\n}	0
7257890	7257768	How to remove duplicates from List<string> without LINQ?	private void RemoveDuplicates(ref List<string> list_lines, ref int Duplicate_Count)\n{\n    Duplicate_Count = 0;\n    List<string> list_lines2 = new List<string>();\n    HashSet<string> hash = new HashSet<string>();\n\n    foreach (string line in list_lines)\n    {\n        string[] split = line.Split('|');\n        string firstPart = split.Length > 0 ? split[0] : string.Empty;\n\n        if (hash.Add(firstPart)) \n        {\n            list_lines2.Add(line);\n        }\n        else\n        {\n            Duplicate_Count++;\n        }\n    }\n\n    list_lines = list_lines2;\n}	0
13119119	13112258	StructureMap auto-registration for interface with more than 1 generic type	For(typeof(IMyFactory<,>)).Use(typeof(GenericMyFactory<,>)));	0
32092653	32092086	How to turn a for loop using table models into a lambda expression	private List<String> GetCurrentListRows(GridTableModel modl, int col)\n{\n    List<String> list = Enumerable\n        .Range(0, modl.RowCount)\n        .Where(i => modl[i, col].Text != "" && modl[i, col].Text != "Called")\n        .Select(i => modl[i, 9].Text)\n        .ToList(); \n    return list;\n}	0
12711066	12710787	How to determine if a row in ObservableCollection<T> actually changed	UpdateSourceTrigger=LostFocus	0
30719491	30719176	Algorithm to find the Gregorian date of the Chinese New Year of a certain Gregorian year	ChineseLunisolarCalendar chinese   = new ChineseLunisolarCalendar();\nGregorianCalendar        gregorian = new GregorianCalendar();\n\nDateTime utcNow = DateTime.UtcNow;\n\n// Get Chinese New Year of current UTC date/time\nDateTime chineseNewYear = chinese.ToDateTime( utcNow.Year, 1, 1, 0, 0, 0, 0 );\n\n// Convert back to Gregorian (you could just query properties of `chineseNewYear` directly, but I prefer to use `GregorianCalendar` for consistency:\n\nInt32 year  = gregorian.GetYear( chineseNewYear );\nInt32 month = gregorian.GetMonth( chineseNewYear );\nInt32 day   = gregorian.GetDayOfMonth( chineseNewYear );	0
5681359	5681279	Java - Send a UTF-8 string via web service and XML that may contain illegal characters	transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")	0
27298017	27297906	Merge two lists by id and select the item of with a max value	List<Level> newLevels = from x in Enumerable.Concat(Levels, otherLevels)\n                        group x by x.Index into grp\n                        select grp.OrderByDescending(x => x.HighScore).First()	0
8655919	8655807	How to read this XML in asp.net using c#	protected void ddlmonth_OnSelectedIndexChanged(object sender, EventArgs e)\n{\n    XmlTextReader reader = null;\n    reader = new XmlTextReader(Server.MapPath("/Scoops/Archives/2010-Mumbai.xml"));\n    XmlDocument xmldoc = new XmlDocument();\n    xmldoc.Load(reader);\n\n    // no need to call Trim(), ASP.NET did that already\n    XmlNodeList nodeList = xmldoc.GetElementsByTagName(ddlmonth.SelectedItem.Text);\n\n    foreach (XmlNode node in nodeList[0].SelectNodes("scoop"))\n    {\n        someDropDownList.Add(node.Attributes["name"].Value);\n    }\n\n\n}	0
9603949	9603878	How can I search users in active Directory based on Name and first name	searcher1.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", aName, aSName);	0
12257376	12257309	How to hide and unhide a page of XtraTabControl?	xtraTabPage.PageVisible = !xtraTabPage.PageVisible;	0
4203551	4203540	Generate C# class from XML	D:\temp>xsd test.xml\nMicrosoft (R) Xml Schemas/DataTypes support utility\n[Microsoft (R) .NET Framework, Version 4.0.30319.1]\nCopyright (C) Microsoft Corporation. All rights reserved.\nWriting file 'D:\temp\test.xsd'.\n\nD:\temp>xsd test.xsd /classes\nMicrosoft (R) Xml Schemas/DataTypes support utility\n[Microsoft (R) .NET Framework, Version 4.0.30319.1]\nCopyright (C) Microsoft Corporation. All rights reserved.\nWriting file 'D:\temp\test.cs'.	0
32081218	32066827	JSON serialization - convert enum to number	public class MyModel\n{\n    public Dictionary<int, string> MySettings { get; set; }\n\n    //One way of handling it.\n    private Dictionary<Settings, string> MyBetterSettings\n    {\n        get { return MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value); }\n        set { MySettings = value.ToDictionary(setting => (int) setting.Key, setting => setting.Value); }\n    }\n\n    //Simple C# 6 methods\n    public Dictionary<Settings, string> GetSettings => MySettings.ToDictionary(setting => (Settings) setting.Key, setting => setting.Value);\n    public void SetSettings(Dictionary<Settings, string> settings) => MySettings = settings.ToDictionary(setting => (int)setting.Key, setting => setting.Value);\n}	0
33712289	33711766	Error: Download a file from directory using ASP.NET	Response.ClearHeaders();\nResponse.ClearContent();\nResponse.ContentType = "Application/octect-stream";\nResponse.AppendHeader("Content-disposition", "attachment; filename=SampleFile.xlsx");\nResponse.WriteFile(Server.MapPath("~/SampleExcel/SampleFile.xlsx"));	0
14292664	14292652	How to double-quote a string in C#	string s = "\"blabla\"";	0
20120574	20077685	How to fix this validation? C#	while (iBinaryNum1 < 0 || iBinaryNum1 > 1)\n        {\n            Console.WriteLine("The value entered was incorrect");\n            Console.WriteLine("Please Re-enter this value: ");\n            iBinaryNum1 = Convert.ToInt32(Console.ReadLine());\n        }	0
27660284	27658750	Roslyn - find declarations with fully qualified name	Compilation.GetTypeByMetadataName()	0
6405118	6405088	Code to enter a preset value into a textbox	Textbox.Text	0
5468158	5468078	How to - Split an int into two ints?	Int32 I = Convert.ToChar(Console.ReadLine());\nvar chars = I.ToString().ToCharArray();	0
2657506	2656663	Help Migrating mixins from Castle.DynamicProxy to DynamicProxy2	public IColoredShape CreateColoredShapeMixin(IHasShape shape, IHasColor color)\n{\n    var options = new ProxyGenerationOptions();\n    options.AddMixinInstance(shape);\n    options.AddMixinInstance(color);\n    var proxy = generator.CreateClassProxy(typeof(object), new[] { typeof(IColoredShape ) }, options) as IColoredShape;\n    return proxy;\n}	0
8608162	8608022	setting variable in if statement, then told it's unassigned	List<string> lstLinesFromFile = new List<string>(File.ReadAllLines(yourFilePath+ "file.txt"));	0
4447949	4447926	OleDBDataType for smalldatetime	OleDbType.DBTimeStamp	0
33597894	33597838	Console application is displaying incorrect answer for radius of a circle	Console.Write("\nThe area of the circle is: {0:f3}", squareSum(radius));	0
14716390	14713471	How to conditionally add data points to a chart rendered with MSChart	chart1.ChartAreas.Add(new ChartArea());\n        chart1.Series[0].IsValueShownAsLabel = true;\n\n        int[] dataset = { 10, 40, 100, 600, 300 };\n        var series1 = chart1.Series[0];\n\n        foreach (var i in dataset)\n        {               \n            series1.ChartType = SeriesChartType.StackedBar;\n            var index1 = series1.Points.AddY(i);\n        }\n\n        int j = 0;\n        foreach (var point in series1.Points)\n        {\n            if (dataset[j] > 20)\n            {\n                point.LabelForeColor = Color.Black;\n            }\n            else\n            {\n                point.LabelForeColor = Color.Transparent;\n            }\n            j++;\n        }	0
14215574	14215515	Usage of custom data types on client and server wcf service	SharedTypes.District	0
33526731	33526602	Getting the list of days of the current week from DateTime.Now	DateTime today = DateTime.Today;\nint currentDayOfWeek = (int) today.DayOfWeek;\nDateTime sunday = today.AddDays(-currentDayOfWeek);\nDateTime monday = sunday.AddDays(1);\n// If we started on Sunday, we should actually have gone *back*\n// 6 days instead of forward 1...\nif (currentDayOfWeek == 0)\n{\n    monday = monday.AddDays(-7);\n}\nvar dates = Enumerable.Range(0, 7).Select(days => monday.AddDays(days)).ToList();	0
13545321	13545169	how to union 2 dictionaries	var result = \n   dictionary1.Union(dictionary2)\n    .GroupBy(kv => kv.Key)\n    .ToDictionary(g => g.Key, g => g.SelectMany(v => v.Value).Distinct().ToList());	0
22778576	22778445	Why set up a constructor in a class to set a base parameter when I could do the same in a class it inherits from?	public abstract class ApiBaseController : ApiController\n{\n    public ApiBaseController(IUow uow)\n    {\n        Uow = uow;\n    }\n    protected IUow Uow { get; private set; }\n}\npublic class ContentStatusController : ApiBaseController\n{\n    public ContentStatusController(IUow uow) : base(uow) //<-- This is needed\n    {\n    }\n}	0
6763732	6763429	Writing stars with specific shape	private static void WriteStars(int width, int height)\n    {\n        int j = 0;\n        for (int i = 0; i < height; i++)\n        {\n            Console.Write("|");\n            for (int f = 0; f < width; f++)\n            {\n                if (f == Math.Abs(j))\n                {\n                    Console.Write("*");\n                }\n                else\n                {\n                    Console.Write(" ");\n                }\n            }\n            j++;\n            if (Math.Abs(j) == width - 1)\n            {\n                j *= -1;\n            }\n            Console.WriteLine("|");\n        }\n    }	0
12738959	12738772	Invisible controls drawing over graphic object	void MyMethod() \n{ \n    //... \n    mycontrol.enabled = false; \n    mycontrol.visible = false; \n    mycontrol.Invalidate(); \n    mycontrol.Update(); \n    this.Invalidate(); \n} \n\n\nprivate void Form1_Paint(object sender, PaintEventArgs e)\n{\n    //Conditional Logic to determine what you are drawing\n    // myPoints is a Point array that you fill elsewhere in your program\n\n    e.Graphics.DrawLines(new Pen(Brushes.Red), myPoints);\n\n}	0
16204094	16203779	How to set property of control from another class	class feedAllCinemas\n{\n   ProgressBar m_ProgressBar;\n\n   public feedAllCinemas(ProgressBar pbar)\n   {\n        m_ProgressBar = pbar;\n   }\n\n   void someMethod()\n   {\n         m_ProgressBar.Visibility = Visibility.Collapsed;\n   }\n}	0
315721	315708	C# Technique - Getting Constant Values By String	using Microsoft.Office.Interop.Excel;\n\nXlConslidationFunction func = (XlConsolidationFunction)\n                               Enum.Parse( typeof(XlConsolidationFunction),\n                                           stringVal );	0
11157714	11157683	C# Casting the Foreach value to one of it's properties	foreach (Windshield ws in _cars.Select(car => car.Windshield))\n{\n    ws.DoWorkA();\n    ws.DoWorkB();\n    ws.DoWorkC();\n}	0
14892501	14891530	How to retrieve the text of a dynamically created textbox and display its as a content of dynamically created button in wpf c#	private void click(object sender, RoutedEventArgs e)\n{\n    var button = sender as Button;\n    var parent = button.Parent as FrameworkElement;\n    var textBox = parent.FindName("textbox1") as TextBox;\n    button.Content = textBox.Text;\n}	0
3096354	3081368	Make scrollviewer not capture control left and control right in WPF	public class MyScrollViewer : ScrollViewer\n{\n    protected override void OnKeyDown(KeyEventArgs e)\n    {\n        if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)\n        {\n            if (e.Key == Key.Left || e.Key == Key.Right)\n                return;\n        }\n        base.OnKeyDown(e);\n    }\n}	0
9367671	9367640	Insert last Second of day	--returns time as 12:35\nSELECT CAST('2000-05-08 12:35:29.998' AS smalldatetime)\nGO\n--returns time as 12:36\nSELECT CAST('2000-05-08 12:35:29.999' AS smalldatetime)\nGO	0
34450988	34449453	Update Gridview with data from radio button list on button click	protected void btnUpdate_Click(object sender, EventArgs e)\n{\n    foreach (GridViewRow row in GridView1.Rows)\n    {\n        RadioButtonList RadioButtonList1 = row.FindControl("RadioButto nList1") \n                                               as RadioButtonList;\n        row.Cells[6].Text = RadioButtonList1.SelectedValue;\n    }\n}	0
4153960	4153940	How to access GetGlobalResourceObject()	_sErrors = (string) HttpContext.GetGlobalResourceObject("resource",\n    "FriendlyErrors.txt");	0
1314000	1307204	How to Generate Unique Public and Private Key via RSA	public static string ConvertToNewKey(string oldPrivateKey)\n{\n\n    // get the current container name from the database...\n\n    rsa.PersistKeyInCsp = false;\n    rsa.Clear();\n    rsa = null;\n\n    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...\n\n       // re-encrypt existing data to use the new keys and write to database...\n\n    return privateKey;\n}\npublic static string AssignNewKey(bool ReturnPrivateKey){\n     string containerName = DateTime.Now.Ticks.ToString();\n     // create the new key...\n     // saves container name and public key to database...\n     // and returns Private Key XML.\n}	0
7069814	7063321	How to get the Active Workbook?	Globals.ThisAddin.Application.ActiveWorkbook.Name	0
19321059	19320858	Only do Where condition if a value is passed in	int? reportingPeriod = ...;\n\nIQueryable<dExp> resultsQuery =         // don't use `var` here.\n        ctx.dExp.Include("datLab");   \n\nif (values != null)\n   resultsQuery = resultsQuery.Where(exp => values.Contains(exp.datL.Lab_ID));\n\nif (reportingPeriod.Hasvalue)\n   resultsQuery = resultsQuery.Where(exp => exp.reportingPeriod == reportingPeriod.Value);\n\n// additional .Where(), .OrderBy(), .Take(), .Skip() and .Select()\n\n// The SQL query is made and executed on the line below\n// inspect the string value in the debugger\nList<dExp> results = resultsQuery.ToList();	0
6708248	6708215	Regex to match a pattern only if its length is bigger than a value	(?=.{5})s?t?a?c?k?o?v?e?r?f?l?o?w?	0
33411615	33411065	Using variables from json - Google play games quests	string reward = "{ \"Coins\" : 10 }";\n\nJSONObject rewardJSON = new JSONObject(reward);\nint coins = int.Parse(rewardJSON.GetField("Coins").ToString());	0
16144927	16144860	How to verify in a foreach loop whether the element is last in the collection?	for (int i = 0; i <= list.Count-1; i++)\n{\n    if (i == list.Count-1)\n    {\n        // so something special with last item\n    }\n}	0
27317701	27317563	Index of List containing dictionaries of strings based on dictionary values	int index = listOfDictionaries.FindIndex(dict => dict.ContainsValue("some value"));	0
14395540	14395471	How to use less code for this situation	static void Main()\n{\n        int whichClass = 0;\n        TestAbstract clTest = null;\n        if (whichClass == 0)\n            clTest = new ClassA();\n        else if (whichClass == 1)\n             clTest = new ClassB();\n        else if (whichClass == 10)\n             clTest = new ClassX();\n        if(clTest != null)\n             clTest.MainFunc();	0
18086773	18086712	How to retrieve one record from SQL Server database in MVC Model	var someobj = db.someEnumerable.FirstOrDefault(x => // Condition);	0
15382491	15382447	Create object from element name and value of xml	var entityCollection = doc.Root\n                          .Elements()\n                          .Select(x => new MyElement {\n                                           ElementName = x.Name.LocalName,\n                                           ElementValue = x.Value\n                                       });	0
33616495	33613726	How can i parse a link from a line in a html source?	var web = new HtmlAgilityPack.HtmlWeb();\nvar doc = web.Load("http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/");\n\nvar links = doc.DocumentNode.SelectNodes("//a[@href]")\n            .Select(x => x.Attributes["href"].Value)\n            .ToList();	0
26390902	26390414	Convert C++ union of structs to C#	struct firststruct\n{\n    UInt32 a;\n}\n\nstruct secondstruct\n{\n    UInt32 p;\n    UInt32 q;\n    UInt32 r;\n    UInt32 s;\n}\n\nstruct thirdstruct\n{\n    UInt32 x;\n    UInt32 y;\n    UInt32 z;\n}\n\n[StructLayout(LayoutKind.Explicit)]\nstruct union\n{\n    [FieldOffset(0)]\n    firststruct firststruct;\n    [FieldOffset(0)]\n    secondstruct secondstruct;\n    [FieldOffset(0)]\n    thirdstruct thirdstruct;\n}\n\nstruct outerstruct\n{\n    UInt32 outervar;\n    UInt32 othervar;\n    union union;\n}	0
6668833	6665307	OpenXML add new row to existing Excel file	public static void InsertRow(WorksheetPart worksheetPart)\n    {\n        SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();  \n        Row lastRow = sheetData.Elements<Row>().LastOrDefault();\n\n        if (lastRow != null)\n        {\n            sheetData.InsertAfter(new Row() { RowIndex = (lastRow.RowIndex + 1) }, lastRow); \n        }\n        else\n        {\n            sheetData.Insert(new Row() { RowIndex = 0 });\n        }\n    }	0
24719168	24719117	Concatenate CheckboxList values and Insert Into table	const string query = "INSERT INTO deductiblePlan (planName) VALUES (@planName)";\n\nusing (var command = new SqlCommand(query, conn))\n{\n    string planName ="";\n    foreach (var item in CheckBoxList1.Items.Cast<ListItem>().Where(item => item.Selected))\n    {\n       planName =planName+item.Text\n    }\n    command.Parameters.Clear();\n    command.Parameters.AddWithValue("@planName",planName );\n    command.ExecuteNonQuery();\n\n}	0
21752073	21751525	Checkbox name with For counter	for (int iTeller = 0; iTeller < bits.Count(); iTeller++)\n            {\n                if (bits[iTeller] == 1)\n                {\n                    var myCheckbox = (CheckBox)this.FindName("Led" + iTeller);\n                    myCheckbox.Background = Brushes.Green;\n                }\n\n            }	0
20919634	20919610	Combine two double jagged array in one jagged array in C#	double[][] result = jaggedOne.Concat(jaggedTwo).ToArray();	0
12118208	12118077	Using javascript for custom purposes	Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));\n\ndynamic obj = Activator.CreateInstance(scriptType, false);\nobj.Language = "javascript";\nobj.AddObject("MyClass",new JSAccessibleClass());\n\nobj.Eval("MyClass.MsgBox('Hello World')"); //<--1\nvar result = obj.Eval("3+5"); //<--2\n\n\n[ComVisible(true)]\npublic class JSAccessibleClass\n{\n    public void MsgBox(string s)\n    {\n        MessageBox.Show(s);\n    }\n}	0
14968364	14968198	How to deselect all MenuStripItems?	foreach (ToolStripMenuItem item in mapStripMenuItem.DropDownItems ) {\n  item.Checked = false;\n}	0
12578192	12577719	serializing an object with a byte array of a file as a field	using (FileStream fs = new FileStream(@"C:\...\file.txt", FileMode.Open))\n  {\n    byte[] buffer = new byte[1024];\n    int len;\n    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)\n    {\n      //client.Send(buffer, 0, len);\n    }\n  }	0
12167105	11674170	Root Element Missing when deserializing an XML response using XmlSerializer	Console.WriteLine(String.Format("{0}", readerOK.ReadToEnd()));	0
34346513	34346405	Match the nodes in xml to Entity framework class	public static XElement XmlSerialize(object obj, bool returnNullOnError = false)\n    {\n        try\n        {\n            XmlSerializer serializer = new XmlSerializer(obj.GetType());\n            StringWriter stream = new StringWriter();\n            serializer.Serialize(stream, obj);\n\n            XDocument xml = XDocument.Parse(stream.ToString());\n\n            return xml.Root;\n        }\n        catch\n        {\n            if (returnNullOnError)\n                return null;\n            throw;\n        }\n    }\n\n    public static object DeSerialize(XElement xmlSerialized, Type objectType)\n    {\n        XmlSerializer serializer = new XmlSerializer(objectType);\n        XDocument d = new XDocument(xmlSerialized);\n        object obj = null;\n\n        using (XmlReader r = d.CreateReader())\n        {\n            obj = serializer.Deserialize(r);\n        }\n        return obj;\n    }	0
25300367	25299135	How to send an url in an email in a wp8 app	EmailComposeTask task = new EmailComposeTask();\n    task.To = "Set Email here";\n    task.Subject = "Subject goes here";\n    task.Body = "Your Mesage goes here \n http://www.google.com";\n    task.Show();	0
2867481	2867470	Subtracting from a 'DateTime'	var result = date1.AddMinutes(-15);	0
14226487	14225840	Session change in between Request and Process user authorization	Session["UserIsHere"] = true;	0
11721952	11721851	Is it good to have windows service or console application?	net start <scriptname>	0
13001749	13001578	I need a slow C# function	public void Slow()\n{\n    long nthPrime = FindPrimeNumber(1000); //set higher value for more time\n}\n\npublic long FindPrimeNumber(int n)\n{\n    int count=0;\n    long a = 2;\n    while(count<n)\n    {\n        long b = 2;\n        int prime = 1;// to check if found a prime\n        while(b * b <= a)\n        {\n            if(a % b == 0)\n            {\n                prime = 0;\n                break;\n            }\n            b++;\n        }\n        if(prime > 0)\n        count++;\n        a++;\n    }\n    return (--a);\n}	0
3051834	3051715	trouble configuring WCF to use session	[ServiceContract(SessionMode = SessionMode.Required)]\npublic interface IService1\n{\n  [OperationContract]\n  string AddData(int value);\n}	0
29081664	29081292	Whats the best way to search files in a directory for multiple extensions and get the last write time according to filename	string GetDatabaseFile(string folder, string dbName)\n{\n    var files =\n        Directory.EnumerateFiles(folder, dbName + "*.*")\n                 .Select(x => new { Path = x, Extension = Path.GetExtension(x) })\n                 .Where(x => x.Extension == ".7z" || x.Extension == ".bak")\n                 .ToArray();\n\n    if(files.Length == 0)\n        return null;\n    if(files.Length == 1)\n        return files[0].Path;\n    var zippedFiles = files.Where(x => x.Extension == ".7z").ToArray();\n    if(zippedFiles.Length == 1)\n        return zippedFiles[0].Path;\n    return zippedFiles.OrderByDescending(x => File.GetLastWriteTime(x.Path))\n                      .First().Path;\n}	0
19150575	19150504	How to replace a numeric character with empty character in C#?	var input = "1 69 / EMP1094467 EMP1094467 :  2 69 / ScreenLysP ";\nvar output = Regex.Replace(input, @"\b[\d]+\b", string.Empty);	0
12353147	12353068	How can I get my C# .exe to automatically recognize the directory that it's running FROM?	Application.StartupPath	0
4593458	4593348	How can I change size of PictureBox?	Bitmap img = new Bitmap(dgOpenFile.FileName);\npicture.Image = img;\npicture.Size = picture.Image.Size;	0
22395169	22394978	Crystal Report Crosstab String Data	count()	0
1765551	1765543	String representation of small amounts of money	NumberFormatInfo.CurrencySymbol	0
3113704	3113698	How to sort a list of objects by a specific member?	var sortedEnumerable = myPeople.OrderBy( p => p.LastName );	0
2437831	2427551	Problem with persisting a collection, that references an internal property, at design time in winforms, .net	Private _InternalProperty\nPublic ReadOnly Property InternalProperty\n    Get\n        Return Me._ProxyInternalProperty \n    End Get\nEnd Property\n\n<Browsable(False), EditorBrowsable(Never), DesignerSerializationVisibility(Content)> _\nPublic ReadOnly Property _ProxyInternalProperty\n    Get\n        Return Me._InternalProperty\n    End Get\nEnd Property	0
16760599	16758142	set navigation property from different schema in entity framework	[Table("Voucher", Schema = "acc")]\n public class Voucher {...}\n\nand \n\n[Table("App", Schema = "prf")]\npublic class App{...}	0
33863749	33863668	How to cast DataTableReader object to bytes array?	employee.Image = DevExpress.XtraEditors.Controls.ByteImageConverter.FromByteArray((byte[])Convert.FromBase64String(dtReader["profilePic"]));	0
6479871	6479855	Removing a line in a text file, by specifying an item from a ListBox	var str = File.ReadAllText("c:\\test.txt");\nFile.WriteAllText("c:\\test.txt", str.Replace(strToRemove, ""));	0
12618404	12581849	Replace element in xdocument placed in a treeview with another xelement	XmlElement XMLE = (XmlElement)TreeV.SelectedItem;// selection from treeview(TreeV) that we want to edit (2nd element)\n  XmlDocument XD = new XmlDocument();\n  XD.LoadXml(text);// text is edited part save as a string\n  XmlNode root=XD.DocumentElement;\n  XmlDocument xml = XMLE.ParentNode.OwnerDocument;\n  XmlNode import= xml.ImportNode(root, true);\n  XMLE.ParentNode.ReplaceChild(import, XMLE);\n  xml.Save(scd_file); //scd_file path	0
7947014	7946830	Create XML with XDocument with a variable number of XElements using for loop	int e = 3;\nXDocument doc = new XDocument(\n          new XElement(ns + "LineItemList",\n               Enumerable.Range(0, e).Select(i => new XElement("ItemNumber", i))\n          ));	0
8448268	8447239	C# to Excel - Custom formatting?	FormatCondition f = (FormatCondition)r.FormatConditions.Add(XlFormatConditionType.xlCellValue,\n                                                       XlFormatConditionOperator.xlLess, 0, misValue, misValue,\n                                                       misValue, misValue, misValue);\n            f.Font.Color = ColorTranslator.ToOle(Color.Red);	0
13353896	13353799	Get entire XML except root element	XmlDocument xml= new XmlDocument();\n        xml.LoadXml(@"<Employees>\n                      <Product_Name>\n                        <hello1>product1</hello1>\n                        <hello2>product2</hello2>\n                        <hello3>product3</hello3>\n                        <hello4>product4</hello4>\n                      </Product_Name>\n                      <product_Price>\n                        <hello1>111</hello1>\n                        <hello2>222</hello2>\n                        <hello3>333</hello3>\n                        <hello4>444</hello4>\n                      </product_Price>\n                    </Employees>");\n        var nodeList = xml.SelectNodes("Employees");\n        foreach (XmlNode node in nodeList)\n        {\n           Console.WriteLine(node.InnerXml); //this will give you your desired result\n        }	0
16699405	16699340	Passing a Type to a generic method at runtime	Type MyType = Type.GetType(FromSomewhereElse);\n\nvar typeOfContext = context.GetType();\n\nvar method = typeOfContext.GetMethod("GetList");\n\nvar genericMethod = method.MakeGenericMethod(MyType);\n\ngenericMethod.Invoke(context, null);	0
23513359	23513267	Display date time with hours and minutes	DateTime date = DateTime.Now;\nstring formattedDate = date.ToString("dddd, dd MMMM yyyy HH:mm");\n// Wednesday, 07 May 2014 12:05	0
26134874	26134791	Raise an event from Child View Model	public event SearchPerformed OnSearchPerformed;	0
20480942	20480436	Linq group by date when using multiple group by fields	kw.GroupBy(x => new { \n                      Date = DbFunctions.TruncateTime(g.SummaryHour),\n                      x.KeywordID\n                    })	0
18968515	18940141	linq-to-sql: GROUP BY and MIN() in SELECT part	var q = \n  from mt in db.MasterTable\n  join ct in db.ChildTable on mt.ID equals ct.MasterID\n  where\n    ct.ColumnB = 1 &&\n    ...\n  group new { ct, mt } by new { ct.ColumnA } into g\n  select\n    new\n    {\n      g.Key.ColumnA,\n      ResultCol = g.Min(x => myConstant + x.mt.ColA > x.mt.ColB\n                                ? myConstant + x.mt.ColA\n                                : x.mt.ColB)\n    };	0
25305137	25305010	Execute functions sequentially without blocking ui, in a loop	private void Foo()\n{\n    Task.Run(() => NormalMethod());\n}\n\nprivate void NormalMethod()\n{\n    string[] files = GetFilesFromDir(@"C:\Bar\");\n    if (files == null || files.Length < 0) { return; }\n\n    for (int i = 0; i < files.Length; i++)\n    {\n        tbSked.Text = files[i];\n        LoadFile();\n        SQLUpdate();\n        RestartTimer();\n    }\n}	0
2110475	2110142	Writing an Inverted Index in C# for an information retrieval application	struct WordInfo\n {\n     public int position;\n     public int fieldID;\n }\n\n Dictionary<string,List<WordInfo>> invertedIndex=new Dictionary<string,List<WordInfo>>();\n\n       public void BuildIndex()\n       {\n            foreach (int  fieldID in GetDatabaseFieldIDS())\n            {    \n                string textField=GetDatabaseTextFieldForID(fieldID);\n\n                string word;\n\n                int position=0;\n\n                while(GetNextWord(textField,out word,ref position)==true)\n                {\n                     WordInfo wi=new WordInfo();\n\n                     if (invertedIndex.TryGetValue(word,out wi)==false)\n                     {\n                         invertedIndex.Add(word,new List<WordInfo>());\n                     }\n\n                     wi.Position=position;\n                     wi.fieldID=fieldID;\n                     invertedIndex[word].Add(wi);\n\n                }\n\n            }\n        }	0
34260976	34260243	How Do I Make A Change A Volume With A Slider?	public float slidervalue=0.0f;\npublic AudioSource audiocccenter;\npublic AudioClip myaudiocc;\n\n\nslidervalue = GUI.HorizontalSlider (new Rect (padding +370 * wdpi, 440* hdpi, 90 * wdpi, 44* hdpi), slidervalue,  0.0f, 1.0f);\n\naudiocccenter = (AudioSource)gameObject.AddComponent ("AudioSource");\n\nmyaudiocc = (AudioClip)Resources.Load ("Clip name");\naudiocccenter.clip = myaudiocc;\n\naudiocccenter.Play();\nAudioListener.volume = slidervalue;	0
9072035	9071829	Caliburn.Micro when setting VM to inherit Screen, overrides title field in View	public ViewModel() {\n    this.DisplayName = "MyTitle";\n}	0
5022607	5022527	Lambda Expression casting to Observable Collection	AddressList = new ObservableCollection<PersonAddressJoins>(PersonResults.SelectMany(x => x.PersonAddressJoins));	0
26764958	26764287	String.Format, single trailign space only for positives	var numbers = new List<double> {123.45, -123.45, 0, -1, -100000.12345, 100000.12345};\n\nforeach (var number in numbers)\n{\n    var numberString = number.ToString("#,##0.00 ;(#,##0.00)");\n\n    // This is the only way I know how to right-align in console window\n    Console.CursorLeft = (Console.BufferWidth - 1) - numberString.Length;\n\n    Console.WriteLine(numberString);\n}\n\n// Output:\n//                                       123.45\n//                                      (123.45)\n//                                         0.00\n//                                        (1.00)\n//                                  (100,000.12)\n//                                   100,000.12	0
10077168	10077114	How To Call XML POST API	WebClient client = new WebClient();\nstring response = client.UploadString(\n                  "http://localhost/myAPI/?options=blue&type=car", \n                  "POST data");	0
19028865	19024355	Test if a local TCP port is free	using (var listener = new TcpListener(IPAddress.Loopback, port))\n    listener.Start();	0
2893354	2893318	Building a balanced binary search tree	public class Program\n{\n    class TreeNode\n    {\n        public int Value;\n        public TreeNode Left;\n        public TreeNode Right;\n    }\n\n    TreeNode constructBalancedTree(List<int> values, int min, int max)\n    {\n        if (min == max)\n            return null;\n\n        int median = min + (max - min) / 2;\n        return new TreeNode\n        {\n            Value = values[median],\n            Left = constructBalancedTree(values, min, median),\n            Right = constructBalancedTree(values, median + 1, max)\n        };\n    }\n\n    TreeNode constructBalancedTree(IEnumerable<int> values)\n    {\n        return constructBalancedTree(\n            values.OrderBy(x => x).ToList(), 0, values.Count());\n    }\n\n    void Run()\n    {\n        TreeNode balancedTree = constructBalancedTree(Enumerable.Range(1, 9));\n        // displayTree(balancedTree); // TODO: implement this!\n    }\n\n    static void Main(string[] args)\n    {\n        new Program().Run();\n    }\n}	0
25915078	25915021	Get next item from the queue(list)	item = _tasks[0];\n_tasks.RemoveAt(0);	0
29479947	29479200	Roslyn : How to get the Namespace of a DeclarationSyntax with Roslyn C#	model.GetTypeInfo(cl).Type.ContainingNamespace	0
30285131	30284840	update a div data dynamically	Page.Response.Redirect(Page.Request.Url.ToString(), true);	0
6352040	6350824	How to move folders maintaining folder structure in c#	void DirSearch(string sDir, string relativeDir)\n            {\n\n                foreach (string f in Directory.GetFiles(sDir,txtfile.Text))\n                    {\n                        //doing something...\n\n                        string outputPath = destinationDir + relativeDir + getFileNameFromPathString(f.ToString()) + ".jpg";\n\n                        //doing more...\n\n                    }\n                foreach (string d in Directory.GetDirectories(sDir))\n                {\n\n                     int lst = d.LastIndexOf("\\") + 1;\n                    string newRelative = relativeDir + d.Substring(lst, d.Length - lst) + "\\";\n                    //relativeDir = relativeDir + d.Substring(lst, d.Length - lst) + "\\";\n                    DirSearch(d, newRelative);\n                }\n            }	0
18642674	18642611	Trim spaces between value	Response.Redirect(section.Text.Replace(" ", string.Empty) + ".aspx");	0
26674993	26673338	C# correct Syntax for Networkconnection with adminshare	bool test = Directory.Exists(@"\\192.168.10.102\C$\Program Files")	0
8017293	8017171	select the last 700 entry in my access database and the 10 first words from a memo field	INSTR(Start_Posn, String_Being_Searched, Sought_String_Item, Compare_Type)	0
27294753	17690378	how to show publish version in a textbox?	if (ApplicationDeployment.IsNetworkDeployed)\n{\n    this.Text = string.Format("Your application name - v{0}", ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(4));\n}	0
9823935	9823748	Removing items in Jagged array using index	var notInToRemove = MainArray\n    .Where((arr ,index) => !toRemove.Contains(index)).ToArray();	0
848367	848337	How to find the next august? C#	public static class DateTimeExtensions\n    {\n        public static DateTime GetNextAugust31(this DateTime date)\n        {\n            return new DateTime(date.Month <= 8 ? date.Year : date.Year + 1, 8, 31);\n        }\n    }	0
21789759	21789700	filtering a table by ids of another table in linq	var results = _context.MappedIds\n                      .Where(x => !_context.FinishedDownloads\n                                           .Select(f => f.categoryID)\n                                           .Contains(x.CategoryID));	0
8619105	7699381	How can I get the page title in WebBrowser control?	String title = (string)browser.InvokeScript("eval", "document.title.toString()");	0
30876079	30875984	Storing Check Box Selection in Cookies	if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)\n{\n    userNameTxtBox.Text = Request.Cookies["UserName"].Value;\n    passwordTxtBox.Attributes["value"] = Request.Cookies["Password"].Value;\n    chkBoxRememberMe.Checked = true; // <-- here\n}	0
26897334	26897103	Selenium for IE11 NoSuchElementException	IWebDriver driver = new InternetExplorerDriver(@"C:\Users\Mike\Documents\selenium\IEDriverServer.exe");	0
5413149	5413117	How do I add items to a C# array so that I have exactly 3 of each item?	int[] myArray = new int(12);\nfor (i = 0; i < 12; ++i)\n{\n    myArray[i] = i/3;\n}\n\nRandom rnd = new Random();\nfor (i = 0; i < 12; ++i)\n{\n    //int swapWith = rnd.Next(12);\n    // Corrected to avoid bias.  See comments.\n    int swapWith = rnd.Next(i+1);\n    int temp = myArray[i];\n    myArray[i] = myArray[swapWith];\n    myArray[swapWith] = temp;\n}	0
11972493	11971924	OnPropertyChange Firing Order	public MyObjectViewModel MyObject            {\n            get { return myObject; }\n            set\n            {\n                myObject=null;\n                OnPropertyChanged("MyObject");\n\n                myObject= value;\n                OnPropertyChanged("MyObject");\n            }\n        }	0
18016932	18015762	Finding the .exe of a Click Once App - Task Scheduler	start c:\Tasks\MemberInterestFollowUp.application	0
6999914	6998523	How to get the value of a ConstantExpression which uses a local variable?	class Visitor : ExpressionVisitor {\n\n  protected override Expression VisitBinary( BinaryExpression node ) {\n\n    var memberLeft = node.Left as MemberExpression;\n    if ( memberLeft != null && memberLeft.Expression is ParameterExpression ) {\n\n      var f = Expression.Lambda( node.Right ).Compile();\n      var value = f.DynamicInvoke();\n      }\n\n    return base.VisitBinary( node );\n    }\n  }	0
27662854	27662534	how to check file format	var bytes = File.ReadAllBytes(someFileNameHere);\nvar match = Encoding.UTF8.GetBytes("%PDF-");\nvar isPDF = match.SequenceEqual(bytes.Take(match.Length));	0
20804706	20804647	String converted to DateTime	public DateTime FromUnixTime(long unixTime)\n{\n    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n    return epoch.AddSeconds(unixTime);\n}	0
26665467	26663486	React on state change in content (Windows Phone)	Foreground="{Binding ElementName=xpand,Path=IsActive,Converter={StaticResource ActiveToColorConverter}}"	0
12758606	12758038	C# tab order with radio buttons	namespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n\n        private List<RadioButton> allMyButtons;\n\n        public Form1()\n        {\n            InitializeComponent();\n            allMyButtons = new List<RadioButton>\n            {\n                radioButton1,\n                radioButton2\n            };\n        }\n\n        private void radioButton_CheckedChanged(object sender, EventArgs e)\n        {\n            RadioButton sendingRadio = (sender as RadioButton);\n            if(sendingRadio == null) return;\n            if(sendingRadio.Checked == true){\n                foreach(var rb in (from b in allMyButtons where b != sendingRadio select b))\n                {\n                    rb.Checked = false;\n                }\n            }\n        }\n\n    }\n}	0
15440709	15440527	How to split on number>letter or letter>number	string[] result = Regex.Split("test123tersre23", @"(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)");	0
14816937	14815912	How to have Internet Explorer hold on to a stream?	Response.ContentType = "application/download"	0
26276111	26274428	I can not get the date of birth from Google Plus API	//request for user prifile\n   void RequestForUserProfile()\n        {\n          //  var urlProfile = "https://www.googleapis.com/plus/v1/people/me?access_token=" + thisApp.AccessToken;\n            var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="+thisApp.AccessToken;\n            // web request user profile\n            WebRequest request = WebRequest.Create(urlProfile); \n            request.BeginGetResponse(new AsyncCallback(this.ResponseCallbackProfile), request);\n        }	0
6539612	6532497	Preventing user from tabbing outside of Frame	KeyboardNavigation.TabNavigation="Cycle"	0
6375602	6374824	C# PInvoke Finding the window handle of a child window from a known window	var descendantwindows = childWindows[0].AllDescendantWindows; // Get all descendant windows of CMainWindow\n\n        for (int i = 0; i<descendantwindows.Length; i++)\n        {\n            if (descendantwindows[i].ClassName == "RichEdit20W")\n                childHandle = descendantwindows[i].HWnd;\n        }	0
17747921	17747883	Convert a byte to a number C#	// If the system architecture is little-endian (that is, little end first),\n// reverse the byte array.\nif (BitConverter.IsLittleEndian)\n   Array.Reverse(bytes);\nint i = BitConverter.ToInt32(bytes, 0);	0
13896618	13896540	HtmlAgilityPack Get all links inside a DIV	var div = doc.DocumentNode.SelectSingleNode("//div[@class='myclass']");\nif(div!=null)\n{\n     var links = div.Descendants("a")\n                    .Select(a => a.InnerText)\n                    .ToList();\n}	0
9743051	9742903	How to get rid of specific warning messages	#pragma warning	0
6017030	6016306	Cannot insert explicit value for identity column in table 'ClientDetails' when IDENTITY_INSERT is set to OFF	[Column(Storage="_ClientNo", DbType="Int NOT NULL", **IsDbGenerated=true,** IsPrimaryKey=true, UpdateCheck=UpdateCheck.Never)] \npublic int ClientNo	0
6248736	6248717	How to get screen resolution of a client system by using JavaScript	var windowWidth = document.documentElement.clientWidth;\n     var windowHeight = document.documentElement.clientHeight;	0
26106384	26106308	Getting string value from SQL function inside a CLR	command.CommandType = CommandType.StoredProcedure;\n command.CommandText = @"dbo.get_parameter";\n\n // here you add the paramters needed for your procedure/function\n //   in your case it will be just one (make sure you add the correct name for you function)\n command.Parameters.Add(new SqlParamter("SelectedParameterName", SqlDbType.NVarChar));\n\n command.Prepare();\n\n command.Parameters[0].Value = "filecount";\n\n string cnt = (string)command.ExecuteScalar();	0
16437216	16437094	Nhibernate add filter to query	Order orderAlias = null;\nUnit unitsAlias = null;\nvar query = session.QueryOver<Order>(() => orderAlias)\n  .JoinAlias(() => orderAlias.Units, () => unitsAlias, JoinType.InnerJoin)\n  .Where(() => unitsAlias.Amount == 5)\n  .OrderBy(x => x.PONumber).Desc.Take(5);	0
31324493	31324328	Conditionally Insert Where Clause in LINQ Method Syntax with Select Many	public ICollection<Organization> getNetworkServiceRecipients(string serviceId = null)\n{\n    var services = get_all_children().SelectMany(o => o.receives_these_services);\n    if (serviceId != null)\n        services = services.Where(s => s.serviceId == serviceId);\n\n    return services.Select(o => o.serviceRecipient)\n                   .Distinct()\n                   .ToList();\n}	0
24388060	24387831	How to read merged cell from word document	Table table = Globals.ThisDocument.Tables[1];\nRange range = table.Range;\nfor (int i = 1; i <= range.Cells.Count; i++)\n{\n    if(range.Cells[i].RowIndex == table.Rows.Count)\n    {\n        range.Cells[i].Range.Text = range.Cells[i].RowIndex + ":" + range.Cells[i].ColumnIndex;\n        MessageBox.Show(range.Cells[i].Range.Text);\n    }\n}	0
18251144	18223314	Designing PDF component for easy access	// load the source PDF doucment\nPdfFileInfo fileInfo = new PdfFileInfo(dataDir + "protected.pdf");\n// determine that source PDF file is Encrypted with password\nbool encrypted = fileInfo.IsEncrypted;\nMessageBox.Show("Encrypted: " + encrypted);	0
29221328	29220656	Parse SOAP message to list	var xDoc = XDocument.Parse(xmlstr);\nvar list = xDoc.Descendants()\n           .Select(x=>new{\n               Name =  x.Name.LocalName,\n               Namespace = x.Name.Namespace.ToString(),\n               Attributes =  x.Attributes().ToDictionary(a=>a.Name.LocalName, a=>a.Value),\n               Value = x.HasElements ? "" :  x.Value\n            })\n           .ToList();	0
26890911	26888922	Getting requesting client's IP address on server	string clientIP = context.Request.RemoteEndPoint.ToString());	0
7506811	7506103	How does this CGPDFDictionaryGetString translate into Monotouch?	public bool GetString (string key, out string result)	0
4006915	4006897	Building an MSI/Setup with VS2008 - How to Create Sub-Folders for Logs and Temporary Files	%appdata%/yourapplication/logfiles	0
12466271	12466188	How do I convert an ISO8601 TimeSpan to a C# TimeSpan?	TimeSpan ts = XmlConvert.ToTimeSpan("PT72H");	0
22454611	22451856	Wix - File is locked for delete after opening its database	//removing read only from file in order to interact with it\nFileInfo fileInfo = new FileInfo(msiPath);\n if (fileInfo.IsReadOnly)\n {\n   fileInfo.IsReadOnly = false;\n }	0
19767947	19767826	Having trouble with limiting the input of a textbox to numbers C#	try{\n    int input = int.Parse(InputBox.Text);\n    //add any addition logic you need here\n}\ncatch{\n    Result.Text="Not a number";\n}	0
24902741	24901440	Where to SaveState on App Suspension	// in your Page\nprivate void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)\n{\n    e.PageState.Add("yourKey", data);\n}	0
28336248	28335463	Getting Specific Data in DataSet Column and export in excel	int i =0;\n      for(i = 0; DsNow.Tables[0].Rows.Count - 1; i ++)\n            {\n                  ExcelAp.Cells[i + 6, 1] = DsNow.Tables[0].Rows[i]["name"].ToString();\n                  ExcelAp.Cells[i + 6, 2] = DsNow.Tables[0].Rows[i]["address"].ToString();\n                  ExcelAp.Cells[i + 6, 3] = DsNow.Tables[0].Rows[i]["contactnumber"].ToString(); \n            }	0
14382728	14382633	How to set webclient proxy to null?	System.Net.WebClient	0
30221562	30221460	Convert a string to shape	int row1 = 1;\nstring var2 = "ell_1_" + row1;\nEllipse var1 = Controls.Find(var2, true)[0] as Ellipse;\nvar1.Fill = new SolidColorBrush(Colors.Red);\nrow1++;	0
3374620	3374433	I want to call a C# delegate from C++ unmanaged code. A parameterless delegate works fine , but a delegate with parameters crashed my program	int (__stdcall * pt2Func)(args...)	0
31418677	31418645	Connection to SQL Server fails if executed from a Windows Service	trusted_connection=true	0
28515781	28515733	Changing the row background color of DataGridView	private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index\n    // check the cell value under your specific column and then you can toggle your colors\n    row.DefaultCellStyle.BackColor = Color.Green;\n}	0
10616645	10616572	How to create simple short hash value? C#	public static void Main() \n    {\n        DisplayHashCode( "Abcdei" );\n    }\n\nstatic void DisplayHashCode( String Operand )\n{\n    int     HashCode = Operand.GetHashCode( );\n    Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}",\n                      Operand, HashCode );\n}	0
5594288	5248727	Searching public Outlook contacts folder from C#	Microsoft.Office.Interop.Outlook._Application objOutlook; //declare Outlook application\n            objOutlook = new Microsoft.Office.Interop.Outlook.Application(); //create it\n            Microsoft.Office.Interop.Outlook._NameSpace objNS = objOutlook.Session; //create new session\n            Microsoft.Office.Interop.Outlook.MAPIFolder oAllPublicFolders; //what it says on the tin\n            Microsoft.Office.Interop.Outlook.MAPIFolder oPublicFolders; // as above\n            Microsoft.Office.Interop.Outlook.MAPIFolder objContacts; //as above\n            Microsoft.Office.Interop.Outlook.Items itmsFiltered; //the filtered items list\n            oPublicFolders = objNS.Folders["Public Folders"];\n            oAllPublicFolders = oPublicFolders.Folders["All Public Folders"];\n            objContacts = oAllPublicFolders.Folders["Global Contacts"];\n\n            itmsFiltered = objContacts.Items.Restrict(strFilter);//restrict the search to our filter terms	0
18520893	18504544	Insert "http" image in MigraDoc table	static string MigraDocFilenameFromByteArray(byte[] image)\n{\n    return "base64:" +\n           Convert.ToBase64String(image);\n}	0
10187904	10174585	Setting ACE slow for folder with many files	public override void DenyAccessInherited(string FolderPath,string DomainAndSamAccountName)\n    {\n        using (Impersonator imp = new Impersonator(this.connection.GetSamAccountName(), this.connection.GetDomain(), this.connection.Password))\n        {\n            FileSystemAccessRule rule = new FileSystemAccessRule(DomainAndSamAccountName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, System.Security.AccessControl.PropagationFlags.InheritOnly, AccessControlType.Deny);\n            DirectoryInfo di = new DirectoryInfo(FolderPath);\n            DirectorySecurity security = di.GetAccessControl(AccessControlSections.All);\n            bool modified;\n            security.ModifyAccessRule(AccessControlModification.Add, rule, out modified);\n            if (modified)\n                di.SetAccessControl(security);\n\n        }\n    }	0
30136044	30128098	How to get difference between xdocument1 and xdocument2	var query =\n    new XDocument(\n        new XElement(\n            "prices",\n            from p1 in xdocument1.Root.Elements("price")\n            join p2 in xdocument2.Root.Elements("price")\n                on p1.Element("productid").Value equals p2.Element("productid").Value\n            where p1.Element("effectivedate").Value != p2.Element("effectivedate").Value\n            select p1));	0
34091197	34090752	Contain method, check string previous char	if(new Regex(@"\b" + keyword + @"\b").IsMatch(description))\n{\n  //\n}	0
18841174	18841022	Specific Row Coloring on DataGrid	For Each row As DataGridViewRow In DataGridView1.Rows\n        If row.Index Mod 2 Then\n            row.DefaultCellStyle.BackColor = Color.Red\n        Else\n            row.DefaultCellStyle.BackColor = Color.Blue\n        End If\n    Next	0
1093406	1069285	Border in ControlTemplate causing odd selection behavior with DataGrid	protected void DataGridRow_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    // GetVisualChild<T> helper method, simple to implement\n    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);\n\n    // try to get the first cell in a row\n    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);\n    if (cell != null)\n    {\n        RoutedEventArgs newEventArgs = new RoutedEventArgs(MouseLeftButtonDownEvent);\n        //if the DataGridSelectionUnit is set to FullRow this will have the desired effect\n        cell.RaiseEvent(newEventArgs);\n    }\n}	0
26153398	26051927	Knockout JS Creating a Dirty flag	var koRowMapping = {\n    rows: {\n        create: function (options) {\n            return createRow(options.data);\n        }\n    },\n    dirtyItems: ko.computed(function() {\n        return ko.utils.arrayFilter(this.rows, function(row) {\n            return row.dirtyFlag.isDirty();\n        });\n    }, this)\n};	0
7890309	7890255	Using DateTime to find the amount of months (inclusive) between two dates	date2.Month - date1.Month + 1 + (date2.Year - date1.Year) * 12	0
3780264	3780197	Eager Loading Children for a LINQ stored procedure call	List<DistributorViewModel> distQuery =  \n    (from d in connection.spDistFindLocal(Lat, Long)\n     select new DistributorViewModel\n     {\n         Name = d.Name,\n         State = d.State.Name,\n         Country = d.Country.Name\n     })ToList();	0
11790185	11790132	How many clients are connected to specified UDP port number in c#	IPGlobalProperties.GetUdpIPv4Statistics	0
3878155	3877983	Looking for a good WPF solution for a transparent, click-through overlay	IsHitTestVisible="False"	0
31049257	31048235	Selecting the shortest item string from dropdownlist in C# Asp.net	List<int> stringLength = new List<int> { }; // storing every length\n\n    foreach (string entry in ddlTemplate.Items)\n    {\n        stringLength.Add(entry.Length); // saving each string-length\n    }\n\n    int index = stringLength.FindIndex(a => a == stringLength.Min()); // get index of lowst length\n    ddlTemplate.SelectedIndex = index; // set selected value to index from above	0
14643177	14643037	How to Split complex string to get filename and base64 string	var split = src.Split('\n').Select(p => p.Trim()).ToList();\n\nvar filename = split.First(p => p.StartsWith("filename="));\nfilename = filename.Substring(10, filename.Length - 11);\n\nvar base64 = split[split.Count - 2];	0
12804905	12804879	Is it OK to use a string as a lock object?	HashSet<>	0
16464376	16239742	How to generate an RTF document server side in c#	{\shp{\*\shpinst\shpleft3801\shptop1\shpright8300\shpbottom4500\shpfhdr0\shpbxcolumn\shpbxignore\shpbypara\shpbyignore\shpwr2\shpwrk0\shpfblwtxt0\shpz0\n{\sp\n{\sn pib}\n{\sv\n{\pict\pngblip\pichgoal4499\picwgoal4499\n-- image binary data goes here --\n}}}\n{\sp\n{\sn fLine}\n{\sv 0}}}}	0
9374505	9324748	Empty DataGridView after adding values from DataTable with large number of columns	foreach (DataRow row in dataTable.Rows)\n            {\n                var dataGridRow = new DataGridViewRow();\n                dataGridRow.CreateCells(dataGrid);\n\n                for (int i = 0; i < row.ItemArray.Length; i++)\n                {\n                    dataGridRow.Cells[i].Value = row.ItemArray[i];\n                }\n\n                dataGrid.Rows.Add(dataGridRow);\n            }	0
1225702	1225642	Retrieving the name of the invoked method executed in a Func	private static string ExtractMethodName(Func<MyObject, object> func)\n{\n    var il = func.Method.GetMethodBody().GetILAsByteArray();\n\n    // first byte is ldarg.0\n    // second byte is callvirt\n    // next four bytes are the MethodDef token\n    var mdToken = (il[5] << 24) | (il[4] << 16) | (il[3] << 8) | il[2];\n    var innerMethod = func.Method.Module.ResolveMethod(mdToken);\n\n    // Check to see if this is a property getter and grab property if it is...\n    if (innerMethod.IsSpecialName && innerMethod.Name.StartsWith("get_"))\n    {\n        var prop = (from p in innerMethod.DeclaringType.GetProperties()\n                    where p.GetGetMethod() == innerMethod\n                    select p).FirstOrDefault();\n        if (prop != null)\n            return prop.Name;\n    }\n\n    return innerMethod.Name;\n}	0
32404477	32363122	Html.BeginForm Wont Keep Guid Set	return RedirectAction("ActionName", "ControllerName", new {Id =     Guid.NewGuid()}):	0
1936679	1936668	c# how to FormWindowState.Normal	private void aboutToolStripMenuItem_Click(object sender, EventArgs e)\n{\n    this.WindowState = FormWindowState.Minimized;\n    about About = new about();\n    About.ShowDialog();\n    this.WindowState = FormWindowState.Normal;\n}	0
22870284	22870226	Generate a random sequence of chars and concatenate with itself into a list.	var concatenare = string.Join(",", lista.SelectMany(c => new []{c, c}));	0
5841978	960032	Close application from captive IE session	private volatile bool _isDisposed = false;\n\n  /**\n  * _isDisposed stops the two "partners" in the conversation (us and \n  * Internet Explorer) from going into "infinite recursion", by calling \n  * each others Dispose methods within there Dispose methods.\n  *\n  * NOTE: I **think** that making _isDisposed volatile deals adequately\n  * with the inherent race condition, but I'm NOT certain! Comments\n  * welcome on this one.\n  */\n  public void Dispose() {\n    if (!_isDisposed) {\n      _isDisposed = true;\n      try {\n        try { release my unmanaged resources } catch { log }\n        try {\n          IE calls MyApp.Dispose() here // and FALLOUT on failure\n          MyApp calls IE.Dispose(); here\n        } catch {\n          log\n        }\n      } finally {\n        base.Dispose(); // ALLWAYS dispose base, no matter what!\n      }\n    }\n  }	0
16782996	16781725	Is there a thread safe way to combine images in C# on an asp.net web app	System.Drawing	0
7496011	7495790	Mapping variables from a string formula	var e = new Expression("basic / workingDays * attendingDays);\n\n//Set up a custom delegate so NCalc will ask you for a parameter's value\n//   when it first comes across a variable\ne.EvaluateParameter += delegate(string name, ParameterArgs args)\n{\n   if (name == "basic")\n       args.Result = GetBasicValueFromSomeWhere();\n   else if (/* etc. */)\n   {\n       //....\n   }\n\n   //Or if the names match up you might be able to something like:\n   args.Result = dataRow[name];\n};\n\nvar result =  e.Evaluate();	0
3268441	3268428	Saving Files in the Root Website Directory in Apache	string filename = Server.MapPath("~/temp/test.txt");\nusing (TextWriter tw = new StreamWriter(filename))\n{\n\n}	0
1546909	1546905	Dynamically adding items to a List<T> through reflection	System.Collections.IList	0
19526622	19526522	Using Linq-To-SQL, how can I ensure forced execution on a complex type?	public Context()\n{\n    this.Configuration.LazyLoadingEnabled = false;	0
6882913	6882873	calculate percentile for each entry in the data list	(TotalNumberOfStudents - Rank of Student) / (TotalNumberOfStudents - 1)	0
3931498	3931447	c# can i create a dynamic file name with streamwriter?	string datetimeString = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}.txt",DateTime.Now);	0
21486418	21486313	Cannot Deserialize xml to List<T>	XmlSerializer serializer = new XmlSerializer(typeof(List<Note>), \n                                new XmlRootAttribute("ArrayOfNote") { \n                                    Namespace = "http://schemas.datacontract.org/2004/07/NotebookService" \n                                });	0
2393211	2393171	Link To SQL Join Statement with or Clause	var myresult = from f in foo\n               from b in bar\n               where b.BarName == f.FooName ||\n                     b.BarName + 'hello' == F.FooName\n               select new {f, b};	0
28111451	28018147	EmguCV: Get coordinates of pixels in a line between two points	public static List<Point> GetBresenhamLine(Point p0, Point p1)\n    {\n        int x0 = p0.X;\n        int y0 = p0.Y;\n        int x1 = p1.X;\n        int y1 = p1.Y;\n        int dx = Math.Abs(x1 - x0);\n        int dy = Math.Abs(y1 - y0);\n\n        int sx = x0 < x1 ? 1 : -1;\n        int sy = y0 < y1 ? 1 : -1;\n\n        int err = dx - dy;\n\n        var points = new List<Point>();\n\n        while (true)\n        {\n            points.Add(new Point(x0, y0));\n            if (x0 == x1 && y0 == y1) break;\n\n            int e2 = 2 * err;\n            if (e2 > -dy)\n            {\n                err = err - dy;\n                x0 = x0 + sx;\n            }\n            if (e2 < dx)\n            {\n                err = err + dx;\n                y0 = y0 + sy;\n            }\n        }\n\n        return points;\n    }	0
16513398	16381488	How to create a enumerable / class string or int and serialized?	[DataContract]\npublic enum Color\n{\n    [DataMember]\n    Red,\n    [DataMember]\n    Blue,\n    [DataMember]\n    Green,\n}	0
20234179	20234071	Replace one specific line in a huge text file	string line;\nint couinter = 0;\n\n// Read the file and display it line by line.\nSystem.IO.StreamReader reader = new System.IO.StreamReader(path);\nSystem.IO.StreamWriter writer = new System.IO.StreamWriter(new_path);\n\nwhile((text = reader.ReadLine()) != null)\n{\n   // Check for your content and replace if required here  \n   if ( counter == line ) \n      text = targetText;\n\n   writer.writeline(text);\n   counter++;\n}\n\nreader.Close();\nwriter.Close();	0
17391932	17391691	How to incluse a csv file within WCF service on Azure	var filepath = HostingEnvironment.MapPath("~/simple.csv");	0
12060813	12060721	optimizing streaming in of many small files	Directory.EnumerateFiles	0
1598929	1449393	How to make Quartz.net job to run in a single-threaded apartment?	public void Execute(JobExecutionContext context)\n{\n    Thread t= new Thread(DoSomeWork);\n    t.SetApartmentState(ApartmentState.STA);\n    t.Start();\n    t.Join();\n}	0
31213643	31212655	How to add PrimaryButtonCommad to ContentDialog in WindowsPhone 8.1?	private async void secondBtn_Click(object sender, RoutedEventArgs e)\n{\n    var box = new ContentDialog()\n            {\n                Title = "File Name",\n                Content = fileName,\n                PrimaryButtonText = "Ok",\n                PrimaryButtonCommand = new RelayCommand(myAction),\n                SecondaryButtonText = "Cancel"\n            };\n    await box.ShowAsync();\n}\n\nprivate async void myAction()\n{\n    await (new MessageDialog("User clicked ok")).ShowAsync();\n}	0
26902903	26902326	How to Multiply values like math	List<double> lst = new List<double>();\n        string strInput2 = txtInput2.Text;\n        for (int i = 0; i < strInput2.Length; i++)\n        {\n            double dbl = Convert.ToDouble(txtInput1.Text) * Convert.ToDouble(strInput2[strInput2.Length - (i + 1)].ToString());\n            string zeros = new String('0', i);\n            lst.Add(Convert.ToDouble(dbl + zeros));\n\n            //richTextBoxResult.Text += lst[i] + Environment.NewLine;\n        }\n\n        for (int i = lst.Count - 1; i >= 0; i--)\n        {\n            richTextBoxResult.Text += lst[i] + Environment.NewLine;\n        }\n\n        richTextBoxResult.Text += "________________" + Environment.NewLine;\n\n        richTextBoxResult.Text += lst.Sum();	0
12782634	12781915	BinaryWriter puts dirty chars at the begin writing in AppendMode	BinaryWriter w = new BinaryWriter(fsw);\n\n    w.Write(UTF8Encoding.Default.GetBytes(report));	0
21493957	21492352	Searching values	string searchValue = textBox1.Text;\n\ndataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;\ntry\n{\n    foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n        if (row.Cells[2].Value.ToString().Equals(searchValue))\n        {\n            row.Selected = true;\n        }\n        else\n        {\n            dataGridView1.Rows.RemoveAt(row.Index); //Remove\n        }\n    }\n}\ncatch (Exception exc)\n{\n    MessageBox.Show(exc.Message);\n}	0
15841422	15841392	How to get the primary key of an object after it is saved with DbContext	db.Entry(calibration).Reload();	0
6458320	6458221	Creating a WCF service using http	[ServiceContract]\npublic interface IMSDNMagazineService\n{\n    [OperationContract]\n    [WebGet(UriTemplate="/")]\n    IssuesCollection GetAllIssues();\n    [OperationContract]\n    [WebGet(UriTemplate = "/{year}")]\n    IssuesData GetIssuesByYear(string year);\n    [OperationContract]\n    [WebGet(UriTemplate = "/{year}/{issue}")]\n    Articles GetIssue(string year, string issue);\n    [OperationContract]\n    [WebGet(UriTemplate = "/{year}/{issue}/{article}")]\n    Article GetArticle(string year, string issue, string article);\n    [OperationContract]\n    [WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]\n    Article AddArticle(string year, string issue, Article article);\n\n}	0
22707467	22698823	Get Max from column datatable or Default Value using Linq	Datatable.AsEnumerable()\n         .Select(x => Convert.ToInt32(x.Field<string>(Framework.SomeStringField)))\n         .DefaultIfEmpty(0)\n         .Max(x => x);	0
7712233	7712197	Logout action method bring data from browser's cache	// to clear cache problems\n        this.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));\n        this.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n        this.Response.Cache.SetNoStore();	0
25603201	25595672	Parsing JSON with fastJson in C#	var result000 = (Dictionary<string, object>)dictionaryObject["Result:000"];\nvar result000Score = Convert.ToDouble(result000["Score"]);	0
564476	564397	Localization using msi file	CultureInfo.CurrentUICulture	0
6085449	6085391	How to Delete Data from Two tables in single query	if (sql_cmd.ExecuteNonQuery() > 1)	0
14433356	14433234	How to obtain the immediate substring between the two specific characters before a (*.*) formatted file [abc.tx, file.html etc]	FileInfo file = new FileInfo(@"C:\folder\subfolder\abc.txt");\nDirectoryInfo dir = file.Directory;\nstring dirName = dir.Name;	0
26892961	26892385	How to read an array of objects	var ecoResProductMaster = product.Product[0].EcoResProductMaster; // Product type\nvar modelingPolicy = ecoResProductMaster.ModelingPolicy;	0
6871141	6871102	C#. WPF. observablecollection how to get current items	foreach (CheckInData coll in CheckInCollection.Where(s => s.IsSelected))\n{\n ...	0
20780121	20776146	How I can print document correctly	counter = 1;\nlastindex = 0;\n\nprivate void PrinBt_Click(object sender, EventArgs e)\n{\n    if (PagePrintSetup.ShowDialog() == DialogResult.OK)\n    {\n       counter = 1;\n       lastindex = 0;\n\n        PrintDocument Pages = new PrintDocument();\n        Pages.DefaultPageSettings.PrinterSettings = PagePrintSetup.PrinterSettings;\n        Pages.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(Pages_PrintPage);\n        Pages.Print();\n    }\n}	0
1529511	1529501	How to exporting data from a List<T> to excel file?	List<Person> persons; // populated earlier\nusing(StreamWriter wr = new StreamWriter("myfile.csv"))\n{\n   foreach(Person person in persons)\n   {\n     wr.WriteLine(person.Name + "," + person.City + "," + person.Age);\n   }\n}	0
16434541	16434450	Curly Brackets in Regex Expression { }	Match match = Regex.Match(yourString, @"{[^}]*}");	0
22253961	22249939	How to invoke SSL enabled Web Api?	X509Certificate2 cert;\nX509Store store = new X509Store(StoreName.My);\n\ntry\n{\n    store.Open(OpenFlags.ReadOnly);\n    cert = store.Certificates.OfType<X509Certificate2>().First(p => p.Thumbprint == "...");\n    cert.Dump();\n}\nfinally\n{\n    if (store != null)\n        store.Close();\n}   \n\nvar clientHandler = new WebRequestHandler();\nclientHandler.ClientCertificates.Add(cert);\nvar client = new HttpClient(clientHandler);	0
17404533	17404420	Error HRESULT E_FAIL has been returned from a call to a COM component	string strImagePath = pptdirectoryPath + currentSlide + "_" + shape.Id + ".png";	0
31110763	31109454	How to combine many rows into single text?	var entgr = (from fx in ph\n                         group fx by fx.SectionId.ToString() into id\n                         select new\n                         {\n                             Section = id.Key,\n                             TelPhone = string.Join(", ",id.Select(s => s.PhoneNumber.ToString()))\n                         });	0
9963951	9963594	Accessing to a ListView at runtime to update an item	object contentToReplace = ...;\nobject newContent = ...;\nListViewItem item = listView.Items.Cast<ListViewItem>().FirstOrDefault(\n    lvi => lvi.Content == contentToReplace);\nif (item != null)\n{\n    item.Content = newContent;\n}	0
9606714	9606640	User verification code, in a method/s	public void VerifyData()\n{\n    if(FileExists())\n    {\n        LogError("The file specified is incorrect")\n        return;\n    }\n\n    if(CorrectExtension())	0
12713121	12712836	Set Window Top, Left, Width & Height and only redraw once	public partial class MainWindow : Window\n{\n    private bool suspended;\n\n    public MainWindow()\n    {\n        this.InitializeComponent();\n    }\n\n    protected override void OnRender(DrawingContext drawingContext)\n    {\n        if (suspended)\n            return;\n\n        base.OnRender(drawingContext);\n    }\n\n    private void Button_Click_1(object sender, RoutedEventArgs e)\n    {\n        suspended = true;\n\n        Left = 0;\n        Top = 0;\n        Width = 100;\n        Height = 100;\n\n        suspended = false;\n\n        this.InvalidateVisual();\n    }\n}	0
29283225	29282604	LINQ to XML row with two attributes	return rows\n    .Where(row =>\n        row.Elements("col").Any(col =>\n            col.Attributes("name").Any(attr => attr.Value.Equals("WOJ")) &&\n            col.Value.Equals(value1)) &&\n\n        row.Elements("col").Any(col =>\n            col.Attributes("name").Any(attr => attr.Value.Equals("POW")) &&\n            col.Value.Equals(value2)));	0
20574129	20574093	Determining if a date field contains a NULL value	if(value == DBNull.Value)	0
1802297	1802227	convert comma separated string to list using linq	string FirstName ="John1, John2, John3";\nstring MiddleInitial = "K1, K2, K3";\nstring LastName = "Kenndey1, Kenndey2, Kenndey3";\nList<String> fn = new List<String>(FirstName.Split(','));\nList<String> mi = new List<String>(MiddleInitial.Split(','));\nList<String> ln = new List<String>(LastName.Split(','));\n\nIEnumerable<NameDetails> result = from f in fn\n        join i in mi on fn.IndexOf(f) equals mi.IndexOf(i)\n        join l in ln on fn.IndexOf(f) equals ln.IndexOf(l)\n        select new NameDetails {f, i, l};	0
11407451	11403965	With Rhino Mocks how to stub a method that makes use of the params keyword?	var resourceRepo = MockRepository.GenerateMock<IResourceRepository>();\nresourceRepo\n  .Expect(r => r.GetById(\n    Arg<int>.Is.Equal(123),\n    Arg<string[]>.List.ContainsAll(new[]\n                                   {\n                                       "Name",\n                                       "Super",\n                                       "Mario",\n                                       "No",\n                                       "Yes",\n                                       "Maybe"\n                                   })))\n  .Return(String.Empty);	0
16510137	16509860	Failed to insert data into Acces DB	Bin\Debug	0
29648410	29647570	How to create ZipArchive from files in memory in C#?	using (var ms = new MemoryStream())\n{\n    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))\n    {\n        foreach (var attachment in attachmentFiles)\n        {\n            var entry = zipArchive.CreateEntry(attachment.FileName, CompressionLevel.Fastest);\n            using (var entryStream = entry.Open())\n            {\n                attachment.InputStream.CopyTo(entryStream);\n            }\n        }\n    }\n    ...\n}	0
26005904	25855404	Client-Server application message exchange over Internet	203.183.172.196:3478 (s1.taraba.net)	0
19417235	19417214	Convert an array to an array of arrays of arrays	var arrayOfArrayOfArrays = test.Select(s => new[] { new[] { s } }).ToArray();	0
25504401	25498805	Correct way of doing data validation when calling methods depending on validity of property	public int Age\n{\n    get { return _age; }\n    set\n    {\n        int oldVal = _age;\n        _age = value;\n        if(Validate("Age") == null)\n        {\n           // Do whatever you want\n\n           OnPropertyChanged("Age");\n        }\n        else\n        {\n            // You can rollback value or not, it wouldnt matter...\n            // PropertyChanged will not be fired!!!\n            _age = oldVal;\n        }\n    }\n}\n\npublic string this[string columnName]\n{\n    get\n    {\n       return Validate(columnName);\n    }\n}\n\npublic string Validate(string propertyName)\n{\n    string error = null;\n    switch (propertyName)\n    {\n        case "Age":\n            if (_age< 10 || _age > 100)\n                error = "The age must be between 10 and 100";\n    }\n\n    return error;\n}	0
33870122	33867091	How to change ResourceDictionary Dynamically	public partial class App : Application\n    {\n        public ResourceDictionary ThemeDictionary\n        {\n            // You could probably get it via its name with some query logic as well.\n            get { return Resources.MergedDictionaries[0]; }\n        }\n\n        public void ChangeTheme(Uri uri)\n        {\n            ThemeDictionary.MergedDictionaries.Clear();\n            ThemeDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = uri });\n        } \n\n    }\n\n\n\n <Application.Resources>\n        <ResourceDictionary>\n            <ResourceDictionary.MergedDictionaries>\n                <ResourceDictionary x:Name="ThemeDictionary">\n                    <ResourceDictionary.MergedDictionaries>\n                        <ResourceDictionary Source="/Themes/ShinyRed.xaml"/>\n                    </ResourceDictionary.MergedDictionaries>\n                </ResourceDictionary>\n            </ResourceDictionary.MergedDictionaries>	0
5344344	5343772	Code that return True if only one or two of three params are true	bool MyFourthAnswer(bool a, bool b, bool c)\n{\n   return (a != b) || (b != c);\n}	0
32368732	32368651	LINQ multiple joins with multiple conditions	from t1 in dbo.Table1\nwhere t1.[Type] == 3 // <--- PUT THIS ONE HIGHER\njoin t1Parent in dbo.Table1 on t1.ParentId equals t1Parent.Id\njoin t2 in dbo.MappingT1T3 on t1Parent.Id equals Id = t2.ExternalId\nwhere (int)t2.[Type] == 1 // <--- SEPARATE CONDITION\njoin t3 in dbo.Table3 on t2.ForeignId equals t3.Id;	0
6266836	6266783	how to decide a nullable value type	void Main()\n{\n\n   test<int>(null);\n\n   test<bool>(null);\n\n   test<DateTime>(null);\n\n}\n\nvoid test<T>(Nullable<T> p)\nwhere T : struct, new()\n{\n   var typeOfT = typeof(T);\n\n}	0
1700256	1700203	How do I get the scroll position from Microsoft Excel	Private Sub DirtyTest()\nDim MyW As Window, TopRow As Long, TopCol As Long\n\n    Set MyW = Windows(1)                ' index 1 always refers to the window displayed\n    TopRow = MyW.VisibleRange.Cells.Row\n    TopCol = MyW.VisibleRange.Cells.Column\n\n    ' any other code\n\nEnd Sub	0
12643483	12643428	validate sharepoint link in c# without using microsoft.sharepoint dll	WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");\n// If required by the server, set the credentials.\nrequest.Credentials = CredentialCache.DefaultCredentials;\n// Get the response.\nHttpWebResponse response = (HttpWebResponse)request.GetResponse ();	0
15009042	15008764	Delete string into string	int start = im.IndexOf("<a href");\nint stop = im.IndexOf("</a>", start);\nim = im.Remove(start, stop + 4 - start) // 4 is the length of the stop string	0
19551269	19550985	Unit test repositories with XML as datasource	public class UserRepository : IUserRepository\n{\n    public Configs CustomConfig {get;set;}\n    public User GetUserById(string id)\n    {\n        return CustomConfig.Users.FirstOrDefault(u => u.UserId == id);\n    }\n}	0
22220480	22220236	Is it Possible to develop Windows Mobile Apps in Windows 7 and Visual Studio 2012	Windows Mobile	0
25123805	25123784	Check if all Values of an array are the interger 1	bool allAreOne = Array.TrueForAll(\n                   globalVariables.singlePeriodClasses, \n                   value => value == 1);	0
8384871	8384791	How to add parameters to a OleDbDataWriter	public void CreateMyOleDbCommand(OleDbConnection connection,\n    string queryString, OleDbParameter[] parameters) \n{\n    OleDbCommand command = new OleDbCommand(queryString, connection);\n    command.CommandText = \n        "SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";\n    command.Parameters.Add(parameters);\n\n    for (int j=0; j<parameters.Length; j++)\n    {\n        command.Parameters.Add(parameters[j]) ;\n    }\n\n    string message = "";\n    for (int i = 0; i < command.Parameters.Count; i++) \n    {\n        message += command.Parameters[i].ToString() + "\n";\n    }\n    MessageBox.Show(message);\n}	0
8343787	8343548	HTML elements in C#	List<Control> ctrl = new List<Control>();\nHtmlAnchor anchor = new HtmlAnchor();\nanchor.ID = "myAnchor";\nctrl.Add(anchor);\n\nButton btn = new Button();\nbtn.ID = "MyBtn";\n\nctrl.Add(btn);\n\nforeach (Control c in ctrl.ToList())\n{\n    if (c is Button)\n    {\n        // Do Something\n    }\n}	0
18718974	18718876	How to compare a string to the different arguments of an object in a array of object?	var filteredItems = collaborateurs.Where(\n            item => item.Name.Contains(term) || item.Name.Function.Contains(term)\n            );	0
34454297	34446377	Modify a Custom Property with a Custom Color	defaultGreen = "#" + 50.ToString("X2") + 0.ToString("X2") + 200.ToString("X2") + 0.ToString("X2");	0
27690349	27690187	Creating an MVC Controller Proxy for a Web API Controller	public class HomeController : Controller {\n\n    public async Task<JsonResult> CallToWebApi() {\n\n        return this.Content(\n            await new WebApiCaller().GetObjectsAsync(),\n            "application/json"\n        );\n    }\n}\n\npublic class WebApiCaller {\n\n    readonly string uri = "your url";\n\n    public async Task<string> GetObjectsAsync() {\n\n        using (HttpClient httpClient = new HttpClient()) {\n\n            return await httpClient.GetStringAsync(uri);\n        }\n    }\n}	0
17390148	17390097	Regex for Adding Forward Slash on Character Casing	Regex regex = new Regex(@"(?<=[\p{Ll}\d])(?=\p{Lu})");\nnewStr = regex.Replace(str, "/");	0
2300397	2300376	Store array in SQL Server 2008	CREATE TABLE Contacts (contactId int, name varchar(128), etc, etc\nCREATE TABLE ContactEmail (contactId int, emailAddress varchar(128), etc\nCREATE TABLE ContactPhone (contactId int, phoneNumber varchar(128), etc	0
12605461	12604424	Console Application stopped working	Well, its not the right way to go, but right click and run as Admin, works butter smooth. Should I go ahead and modify all executables to - Run as Administrator under Properties->Compatibility??	0
25024731	25024554	Getting subdirectories of a path that have specific file extensions	List<string> imageDirectories = Directory.GetDirectories(sourceTextBox.Text, "*", SearchOption.AllDirectories)\n    .Where(d => Directory.EnumerateFiles(d)\n        .Select(Path.GetExtension)\n        .Where(ext => ext == ".png" || ext == ".jpg")\n        .Any())\n    .ToList();	0
11004457	11004172	Linq to SQL Referential Integrity without database	public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)\n    {\n        bool everythingIsOK = true;\n\n        var changes = GetChangeSet();\n        var inserts = changes.Inserts;\n        var deletes = changes.Deletes;\n        var updates = changes.Updates;\n\n        //verify everything is valid\n        //...\n\n        //if you need to, you can get the original state of the updated objects like this:\n        foreach(object x in updates) {\n            var original = this.GetTable(x.GetType()).GetOriginalEntityState(x);\n            //verify the change doesn't break anything\n            //...\n        }\n\n        if(everythingIsOK){ base.SubmitChanges(failureMode); }\n    }	0
52470	52449	IQuery NHibernate - does it HAVE to be a list?	query.UniqueResult<T>()	0
15188604	15188500	Get value from listBox using List	if (listTime.SelectedIndex != -1)\n{\n    var item = listTime.SelectedItem as Duration;\n    //or as suggested by 'Stu'\n    var item = (Duration)listTime.SelectedItem;\n    MessageBox.Show(item.Value.ToString());\n}	0
2876379	2876309	Castle Windsor : Configure a generic service and provide a non-generic implementation fails	container.AddComponent("entity", typeof(IEntity<string>), typeof(ConcreteEntity));	0
26754219	26748467	How to select all text in textbox when it gets focus	private void TextBox_GotFocus(object sender, RoutedEventArgs e)\n    {\n        TextBox textBox = (TextBox)sender;\n\n        textBox .CaptureMouse()\n    }\n\n    private void TextBox_GotMouseCapture(object sender, RoutedEventArgs e)\n    {\n        TextBox textBox = (TextBox)sender;\n\n        textBox.SelectAll();\n    }\n\nprivate void TextBox_IsMouseCaptureWithinChanged(object sender, RoutedEventArgs e)\n    {\n        TextBox textBox = (TextBox)sender;\n\n        textBox.SelectAll();\n    }	0
9283588	9283494	Outlook window goes behind - C# Windows Application	public class MoveToForeground\n{\n    [DllImportAttribute("User32.dll")]\n    private static extern int FindWindow(string ClassName, string WindowName);\n\n    [DllImport("user32.dll", EntryPoint="SetWindowPos")]\n    public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);\n\n    const int SWP_NOMOVE = 0x0002;\n    const int SWP_NOSIZE = 0x0001;            \n    const int SWP_SHOWWINDOW = 0x0040;\n    const int SWP_NOACTIVATE = 0x0010;\n\n    public static void DoOnProcess(string processName)\n    {\n        var process = Process.GetProcessesByName(processName);\n        if (process.Length > 0)\n        {\n            int hWnd = FindWindow(null, process[0].MainWindowTitle.ToString());\n            SetWindowPos(new IntPtr(hWnd), 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);\n        }\n    }\n}\n\n\nMoveToForeground.DoOnProcess("OUTLOOK.EXE");	0
3637027	3633484	How to create a non-selectable TreeView node?	if(myNode.Nodes.Count == 0)\n{\n   //Open your form\n}\nelse\n{\n   //Show error or perform alternative actions\n}	0
2989337	2989311	Remove non-alphanumerical characters excluding space	var winCaption = "Hello | World!?";\nString cap = Regex.Replace(winCaption, @"[^\w\.@\- ]", "");	0
22033062	22032773	How to get the values from list of objects in c#	JObject obj = JObject.Parse(json);\n        int count = (int)obj["Count"];\n        var Items = obj["Items"];\n        foreach (var item in Items)\n              var admin = item["Admin"];	0
19731601	19731347	Where does DefaultCredentials pull out "UserName" as a username for a web request?	control keymgr.dll	0
23156255	23154163	C# String Get Between in a HTML Code	string input = "(<b><a href=\"#post9736461\" title=\"Show\">Permalink</a></b>)";\nstring value = Regex.Match(input, @"(?<=#post)\d+").Value;	0
17860039	17859951	How to Get Closest Location in LINQ to Entities	var coord = new GeoCoordinate(loc.Latitude, loc.Longitude);\n                var nearest = ctx.Locations\n                    .Select(x => new LocationResult {\n                        location = x,\n                        coord = new GeoCoordinate { Latitude = x.Latitude ?? 0, Longitude = x.Longitude ?? 0 }\n                    })\n                    .OrderBy(x => x.coord.GetDistanceTo(coord))\n                    .First();\n\n                return nearest.location.Id;	0
445886	445883	Generate List<> of custom object	var emp = new List<Employee>\n{\n    new Employee{ID=1, EmpFname="matt", EmpLName="Cook"},\n    new Employee{ID=2, EmpFname="mary", EmpLname="John"}\n};	0
23135033	23134970	Replace URL in a string	string replacement = "ato-svn3-sslv3.of.lan";\nurl = url.Replace("svn1", replacement);	0
11077220	11077152	Get All elements in between two elements in Array	alphabetList = alphabet.ToList();\nstring[] range = (alphabetList.GetRange(alphabetList.IndexOf("A"), alphabetList.IndexOf("D") + 1)).ToArray();	0
32129540	32119487	how to get elements from element selenium c#	private static readonly By divBlock =By.XPath("//*[@contains(@id, 'qst_8220_qst_8235')]");\n\nprivate static readonly By elementType = By.XPath(".//*[@type='radio']");\n\nIWebElement Block = Driver.FindElement(divBlock);\n\nList<IWebElement> elementTypes = Block.FindElements(elementType);\n\nConsole.WriteLine(elementTypes.count);\n\nforeach (var elem in elementTypes)\n{\n    elem.Click();\n}	0
12938032	12937891	How can I browse a specific level on a XML?	var xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)\nvar list =  xDoc.Descendants("ordinanza")\n                .Select(n => new\n                {\n                    Numero = n.Element("numero").Value,\n                    Titolo = n.Element("titolo").Value,\n                })\n                .ToList();	0
6199560	6199465	checking for the last element in a foreach	int i = 1;\nforeach (Object element in elements.under)\n{\n    if (i == elements.under.Count) //Use count or length as supported by your collection\n    { \n      //last element \n    }\n    else \n    { i++; }\n}	0
15075935	15075512	SqlConnection ignores default schema for user	Trusted_Connection=no	0
30874628	30874506	Selenium C# Element Not Found Taking a Long Time	// In C# you can use\nChromeDriver driver = new ChromeDriver("Path to Driver");\ndriver.Manage().Timeouts().ImplicitlyWait(new Timespan(0,0,2));	0
802252	802022	NHibernate: a reverse version of in()?	session.CreateQuery("select new AudienceListDTO(e.AudienceList) from EventItems e").List();	0
2523095	2522750	Calculate Total Value In Gridvew In ASP.net C#	DataColumn totalColumn = new DataColumn("Total");\ntotalColumn.Expression = "Quantity * Price";\ntotalColumn.DataType = //double,integer \ndataTable.Columns.AddAt(totalColumn, 0);	0
19240833	19240761	How do I create a method, and make a constructer that calls the method	public class SomeClass\n    {\n        public SomeClass() //constructor\n        {\n            SomeMethod(); //Calling the method in constructor\n        }\n        public void SomeMethod() // Method\n        {\n            //Method implementation\n        }\n    }	0
31300908	31300779	C# Timer inside a property	private System.Timers.Timer timer = new System.Timers.Timer();\npublic MyObject()\n{\n    timer.Elapsed += new ElapsedEventHandler(capturecolor_timer);\n    timer.Interval = 5000;\n}	0
19540376	19538720	How to add a keyup event in android in c#?	editText.addTextChangedListener(new TextWathcer(){\n      @Override\n        public void onTextChanged(CharSequence s, int start, int before, int count) {\n\n            // TODO Auto-generated method stub\n        }\n\n        @Override\n        public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n            // TODO Auto-generated method stub\n        }\n\n        @Override\n        public void afterTextChanged(Editable s) {\n\n            // TODO Auto-generated method stub\n        }\n\n});	0
11342446	11342088	TemplateControl Checkbox Event in Custom GridView Control	protected override void OnRowCreated(GridViewRowEventArgs e)\n    {\n        if (e.Row.RowIndex == -1)\n        {\n            CheckBox chk = e.Row.GetAllControls().OfType<CheckBox>().FirstOrDefault();\n\n            if (chk != null)\n            {\n                chk.CheckedChanged += new EventHandler(chk_CheckedChanged);\n            }\n        }\n        base.OnRowCreated(e);\n    }	0
33131069	33130446	Deserialize JSON Web Response in C#	var response = "{blueplates :[{\"Appetizer\":26,\"Salad\":21,\"Soup\":\"SheCrab\",\"Entree\":6434,\"Side\":2303093,\"Desert\":0,\"Beverage\":\"Sweet Tea + SoCO\"}, {\"Appetizer\":27,\"Salad\":21,\"Soup\":\"Tomato Bisque\",\"Entree\":6434,\"Side\":2303093,\"Desert\":0,\"Beverage\":\"Lemonade + Rum\"}, {\"Appetizer\":28,\"Salad\":21,\"Soup\":\"Peanut\",\"Entree\":6434,\"Side\":2303093,\"Desert\":0,\"Beverage\":\"Ginger Ale + Whiskey\"}]}";\n\n    JavaScriptSerializer deSerializedResponse = new JavaScriptSerializer();\n    RootObject root = (RootObject)deSerializedResponse.Deserialize(response, typeof(RootObject));\n\n    foreach (Blueplate plate in root.blueplates)\n    {\n        Console.WriteLine(plate.Appetizer);\n        Console.ReadLine();\n    }	0
15648824	15648026	How to get method name from Action in WinRT	public class Test2\n{\n    public static Action<int> TestDelegate { get; set; }\n\n    public static void PrintInt(int x)\n    {\n        Debug.WriteLine("int {0}", x);\n    }\n\n    public static void TestGetMethodName()\n    {\n        TestDelegate = PrintInt;\n        Debug.WriteLine("TestDelegate method name is {0}", TestDelegate.GetMethodInfo().Name);\n    }\n}	0
1058787	1050965	Get .sln file from Team Foundation Server SDK	// Enumerate the checked pending changes.\nPendingChange[] changes = m_pendingCheckin.PendingChanges.CheckedPendingChanges;\n\nforeach ( PendingChange change in changes )\n{\n    // this contains the full local path to whatever is being checked in\n    // can use this to find the solution file\n    change.LocalItem;\n}	0
28158445	28157598	Is there a way to check if Ektron is loading a page in Edit mode in my codebehind? (C#)	if (_host != null) // make sure widget is being used inside a PageBuilder page\n    {\n        var p = this.Page as PageBuilder; // get PageBuilder object\n        if (p.Status == Mode.Editing) // check for Editing mode\n        {\n             ux.Visible = true //Display UX\n        }\n    }	0
21922708	21922115	How to retrieve data from table "a" based on different values in table "b"	var cfk = from p in db.Questions\n              where c.Contains(p.ItemId)\n              select p;	0
4443593	4443511	Can't open an image in WPF app	BitmapImage image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(@"..\Images\DocumentAccess_16x16.png", UriKind.Relative);\nimage.EndInit();	0
10973676	10973625	Parameterized query with dynamic where clasue	SELECT\n     Column1\n    ,Column2\nFROM \n     YourTable\nWHERE\n    (\n        @SerialNum IS NULL\n        OR\n        Column3 LIKE '%' + @SerialNum + '%'\n    )\n    AND\n    (\n        @Code IS NULL\n        OR\n        Column4 LIKE '%' + @Code + '%'\n    )	0
170463	170455	How can I read multiple tables into a dataset?	using (SqlConnection conn = new SqlConnection(connection))\n{\n    SqlDataAdapter adapter = new SqlDataAdapter();\n    adapter.SelectCommand = new SqlCommand(query, conn);\n    adapter.Fill(dataset);\n    return dataset;\n}	0
22380440	22380385	How to return a List<string> based from a List<KeyValuePair>	return adGroups.Where(p => p.Key.Equals("")) //no reason to check it twice\n               .Select(item => item.Value)\n               .ToList();	0
12330837	12330818	How to center the text in listbox item when owner draw mode	void listTypes_DrawItem(object sender, DrawItemEventArgs e)\n    {\n        ListBox list = (ListBox)sender;\n        if (e.Index > -1)\n        {\n            object item = list.Items[e.Index];\n            e.DrawBackground();\n            e.DrawFocusRectangle();\n            Brush brush = new SolidBrush(e.ForeColor);\n            SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font);\n            e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); \n        }\n    }	0
5571232	5571045	Linq subquery - getting InvalidOperationException as soon as I'm trying to iterate trough the results set	var movies = from m in data.Movies \n             where m.Rating > -1 && \n                   m.GenreLinks.Any(gr => gr.GenreID == queryGenre) \n             orderby m.InsteredIn desc \n             select m;	0
16764470	16764371	MVC 4 - hand over changed value from View to Controller	[HttpPost]\npublic ActionResult (FormCollectio collection)\n{\n\n    string Verkaufspreis1=collection["Verkaufspreis"].ToString();\n\n}	0
22479430	22479127	Applying multiple group functions on IQuerable<T>	var q = from foo in foos\n        group foo by 1 into g\n        select new {\n           Total = g.Count(),\n           FlagOneTotal = g.Count(p => p.FlagOne),\n           FlagTwoTotal = g.Count(p => p.FlagTwo)\n        };\n\nvar list = q.ToList();	0
18074653	18073965	WinForms PropertyGrid: dynamic StandardValuesCollection changing	public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)\n{\n    // get the current property value\n    string value = (string)context.PropertyDescriptor.GetValue(context.Instance);\n    return new StandardValuesCollection(GetFilteredList(value));\n}	0
6923156	6919761	Azure Queue Storage Message Size	var byteSize = System.Text.Encoding.UTF8.GetBytes(xml).GetLength(0);	0
17854099	17854027	IList in interface, List in implementation	public static void AddRange<T>(this IList<T> list, IEnumerable<T> values) {\n    foreach(var value in values)\n        list.Add(value);\n}	0
20992337	20991806	Reading and Editing XML file	using System.Xml.Linq;\n...\nXDocument xDoc = XDocument.Load(@"Your xml file path goes here"); // or XDocument.Parse("Your xml string goes here");\nxDoc.Root.Elements("Employee").First(xe => xe.Attribute("id").Value == "1").Element("Name").Value = "your value";	0
1053123	1053052	A generic error occurred in GDI+, JPEG Image to MemoryStream	// At this point the new bitmap has no MimeType\n// Need to output to memory stream\nusing (var m = new MemoryStream())\n{\n       dst.Save(m, format);\n\n       var img = Image.FromStream(m);\n\n       //TEST\n       img.Save("C:\\test.jpg");\n       var bytes = PhotoEditor.ConvertImageToByteArray(img);\n\n\n       return img;\n }	0
27463415	27463261	Converting a Color to and from a 6-bit color	Color.FromArgb(255, 85 * ((color >> 4) & 3), 85 * ((color >> 2) & 3), 85 * (color & 3))	0
17847251	17847237	How to add a new column to datagridview after binding it with database	string query = "SELECT player_name AS [Player Name] ,\nskill As [Skill], '' AS [CurrentScore]\nFROM Players WHERE Team_id= " + teamID;	0
20432401	20432188	Implementing tags functionality with Entity Framework	if (entity.Tags.All(t => t.Label != tag))\n{\n    var tagEntity = _context.Tags.FirstOrDefault(t => t.Label == tag);\n\n    if(tagEntity == null)\n        tagEntity = _context.Tags.Add(new Tag {Label = tag});\n    entity.Tags.Add(tagEntity);\n}	0
33698478	33697864	Debugging inconsistent results from C# WebMethod in IIS	[WebMethod]\npublic static object getData(string id, string type, string[] filters)\n{    \n    //do some validation of inputs\n    //execute a stored procedure and process with LINQ\n\n    var _lock = new object();\n\n    lock(_lock)\n    {\n        return new { Result = "OK", Records = results, TotalRecordCount = unpagedTotal };\n    }\n}	0
10944544	10857777	Binding data with chart's points	for each (DataRow row in dssearchgrid.Tables[0].Rows)\n    {\n        string seriesName = row["sno"].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 < dssearchgrid.Tables[0].Columns.Count; colIndex++)\n        {\n            // For each column (column 1 and onward) add the value as a point\n            string columnName = dssearchgrid.Tables[0].Columns[colIndex].ColumnName;\n            if (row[columnName] != "")\n            {\n                YVal = Convert.ToInt32(row[columnName]);\n            }\n            else\n            {\n                YVal = 0;\n            }\n\n            Chart1.Series[seriesName].Points.AddXY(columnName, YVal);\n        }	0
785617	785527	get mail address from ActiveDirectory	// get a DirectorySearcher object\nDirectorySearcher search = new DirectorySearcher(entry);\n\n// specify the search filter\nsearch.Filter = "(&(objectClass=user)(anr=" + account + "))";\n\n// specify which property values to return in the search\nsearch.PropertiesToLoad.Add("givenName");   // first name\nsearch.PropertiesToLoad.Add("sn");          // last name\nsearch.PropertiesToLoad.Add("mail");        // smtp mail address\n\n// perform the search\nSearchResult result = search.FindOne();	0
27928224	27898256	How to force the migration to use connection string of the client context triggered the migration	Database.SetInitializer(new MigrateDatabaseToLatestVersion<ClientContext, Configuration>(true));	0
14351347	14350771	Removing multiple selected objects from a listbox/list	private void buttonRemoveRental_Click(object sender, EventArgs e)\n    {\n       var selectedItems= listBoxRental.SelectedItems.Cast<String>().ToList();\n       foreach (var item in selectedItems)\n            listBoxRental.Items.Remove(item);\n    }	0
11944971	11944921	How do I join two control collections for use with foreach statement	var allControls = leftPanel.Controls.Cast<Control>().Concat(rightPanel.Controls.Cast<Control>());\nforeach(Control temp in allControls)\n{\n     //...\n}	0
14904443	14904369	Removing a certain part of a string	var input = "string(1)_2013-02-15";\nvar result = Regex.Replace(input, "\\([0-9]+\\)", string.Empty);	0
21430211	21430150	How to assign a bool variable directly using a condition	type = (((sDataSet.Shipment[0].CI_TYPE == Constants.ShipType.CI_R) &&\n                             (shipType == Constants.ShipType.CI_R)) ||\n            ((sDataSet.Shipment[0].CI_TYPE == Constants.ShipType.CI_P) &&\n                            (shipType == Constants.ShipType.CI_R))  ||\n            ((sDataSet.Shipment[0].CI_TYPE == Constants.ShipType.CI_R) &&\n                            (shipType == Constants.ShipType.CI_P)))	0
21916628	21916422	Parsing String Into List of Integers with Ranges	var input = "1001, 1003, 1005-1010";\n\nvar results = (from x in input.Split(',')\n               let y = x.Split('-')\n               select y.Length == 1\n                 ? new[] { int.Parse(y[0]) }\n                 : Enumerable.Range(int.Parse(y[0]), int.Parse(y[1]) - int.Parse(y[0]) + 1)\n               ).SelectMany(x => x).ToList();	0
32564370	32564260	Saving data from sql server Database into a PDF file	FileStream fs = new FileStream(filename, FileMode.CreateNew);\nDocument doc = new Document(PageSize.A4);\nPdfWriter pdfWriter = PdfWriter.GetInstance(doc, fs);\nPdfPage page = new PdfPage();\npdfWriter.PageEvent = page;\ndoc.Open();\nPdfContentByte cb = pdfWriter.DirectContent;\ndoc.Add(new Paragraph("the data from sql server:"));\npdfWriter.CloseStream = true;            \ndoc.Close();\nfs.Close();	0
5586602	5586575	C#: Test if a class in an instance of a super class instead of a subclass	if (theObject.GetType() == typeof(Vehicle))\n{\n   // it's really a Vehicle instance\n}	0
16857788	16857291	FeedData into a FooterPart	foreach (var section in mainPart.Document.Body.Elements<WP.SectionProperties>())\n{\n    section.PrependChild<WP.HeaderReference>(new WP.HeaderReference() { Id = mainPart.GetIdOfPart(headerPart) });\n    section.PrependChild<WP.FooterReference>(new WP.FooterReference() { Id = mainPart.GetIdOfPart(footerPart) });\n}	0
16131123	16131082	Method returns a list of superclasses instead of subclasses	public List<T> GetElementsByType<T>() where T : X\n{  \n        return Elementen.OfType<T>().ToList();\n}	0
26007360	25859020	How do I zip files in Xamarin for Android?	ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));\nzos.PutNextEntry(entry);\n\nbyte[] fileContents = File.ReadAllBytes(arrFiles[i]);\nzos.Write(fileContents);\nzos.CloseEntry();	0
18446165	18446119	Concatenation of two string in razor view	name="num@(i)"	0
14303156	14303112	Entity framework - how to not insert new value if that value exists already	var authors = myDb.Authors;\nif((comment.AuthorId != null || comment.AuthorId !=0) && !authors.Exists(a=>a.AuthorID == comment.AuthorId))\n{\n   //do your creation of new Author and then post the article\n}\nelse//author exists\n{\n   //just post article\n}	0
1700396	1700364	How to wake up from Hibernation at a given day/time?	[DllImport("kernel32.dll")]\npublic static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);\n\n[DllImport("kernel32.dll", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\npublic static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);	0
10130369	10129446	Eventlog listener - Applications and Services	....\n    EventLog myNewLog = new EventLog();\n    myNewLog.Log = "MyCustomLog";                      \n\n    myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);\n    myNewLog.EnableRaisingEvents = true;                 \n\n}       \n\npublic static void MyOnEntryWritten(object source, EntryWrittenEventArgs e){\n\n}	0
29203248	29203049	how to Pass data from dropdownlist to database	DateTime.Parse\n    (\n    purchinvoice_dropdownlist_monthdate.SelectedItem.Text + "/" + \n    purchinvoice_dropdownlist_daydate.SelectedItem.Text + "/" + \n    purchinvoice_dropdownlist_yeardate.SelectedItem.Text\n    );	0
7129276	7129231	how to click this javascript button?	using SHDocVw;\nusing mshtml;\n\n\nSHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();\nie.Visible = true;\nobject o = new object();\nie.Navigate("http://www.google.com", ref o, ref o, ref o, ref o);\n\nwhile (!(ie.ReadyState >= tagREADYSTATE.READYSTATE_LOADED))\n       Application.DoEvents();\n\nvar doc = ie.Document;\n\nvar win = (IHTMLWindow2)doc.parentWindow;\n// here you call the Javascript\nwin.execScript("SubmitAction();", "javascript");	0
10955830	10955794	Replaced InnerHtml Displays as a String	string image = "<img src=\"" + DropList1.SelectedItem.Value + "\" />";	0
19721707	19721671	How to automatically detect non-empty textbox?	protected void txtData_TextChanged(object sender, EventArgs e)\n{\n    btnSearch.Enabled = txtData.Text.Length > 0;\n}	0
13180256	13179969	2 in a row game in c#	game.MakeMove(0, 0);	0
25891134	25891033	Get a random float within range excluding sub-range	var excluded = maxExclusive - minExclusive;\nvar newMax = max - excluded;\nvar outcome = Random.Range(min, newMax);\n\nreturn outcome > minExclusive ? outcome + excluded : outcome;	0
3160040	3159977	How to encapsulate private fields that only apply to a few methods	public class DiscountEngine\n{\n    public Cart As Cart { get; set;}\n    public Discount As Discount { get; set;}\n\n    private class SKUGroup\n    {\n        public int ItemDiscountsApplied = 0\n        public int TotalDiscounts = 0\n        public int ID = 0\n    }\n\n    public void ApplySKUGroupDiscountToCart()\n    {\n        ...\n    }\n\n    private void ApplyDiscountToSingleCartItem(ref CartItem cartI, \n                                               ref DiscountItem discountI)\n    {\n        ...\n    }\n}	0
2993442	2993418	Need to trim a string till end after a particular combination of characters	string s = "test\1\2\3\0\0\0\0\0\0\0\0\0_asdfgh_qwerty_blah_blah_blah";\n\nint offset = s.IndexOf("\\0");\nif (offset >= 0)\n    s = s.Substring(0, offset);	0
16636613	16636554	Sorting an array alphabetically in C#	Array.Sort(names, (x,y) => String.Compare(x.Name, y.Name));	0
11538892	11538848	Prevent child process from showing a shell window in c#	ProcessStartInfo si = new ProcessStartInfo();\nsi.WindowsStyle = ProcessWindowStyle.Hidden;\nsi.CreateNoWindow = true;\nsi.UseShellExecute = false;\n......	0
28556255	28556138	Looping through ListBox to add selected values to database	var items = new List<string>();           \nforeach (ListItem li in ListBox1.Items)\n{\n    if (li.Selected)\n    {\n        items.Add(li.Text);\n    }\n}\ncmd.Parameters.AddWithValue("@TestName", string.Join(",", items));	0
5382363	5373862	Get the height of a TreeViewItem's Header in WPF	private FrameworkElement GetHeaderControl(TreeViewItem item)\n{\n   return (FrameworkElement)item.Template.FindName("PART_Header", item);\n}	0
33234682	33172907	CREATE FULLTEXT INDEX/CATALOG statement cannot be used inside a user transaction	SqlConnection cnn = new SqlConnection("cstring");\nSqlTransaction trn = null;\n\ncnn.Open();\n\nusing (SqlCommand cmd = cnn.CreateCommand())\n{\n    cmd.Connection = cnn;\n\n    if(!SQLScript.Contains("FULLTEXT"))\n    {\n        trn = cnn.BeginTransaction();\n        cmd.Transaction = trn;\n    }        \n\n    cmd.CommandText = SQLScript;\n    cmd.CommandType = CommandType.Text;\n    cmd.ExecuteNonQuery();\n}\n\nif(trn!=null)\n    trn.Commit();\n\ncnn.Close();	0
37336	37317	How do you return the focus to the last used control after clicking a button in a winform app?	public Form1()\n    {\n        InitializeComponent();\n\n        foreach (Control ctrl in Controls)\n        {\n            if (ctrl is TextBox)\n            {\n                ctrl.Enter += delegate(object sender, EventArgs e)\n                              {\n                                  _lastEnteredControl = (Control)sender;\n                              };\n            }\n        }\n    }	0
6288997	6287508	How to set the first item as selected	private void listView1_SelectedIndexChanged(object sender, EventArgs e)  \n    {  \n        try  \n        {      \n            //listView.Focus();              \n            listView2.Items[0].Selected = true;  \n        }  \n        catch { }  \n    }	0
26734911	26726022	I want to be able to hold down control by code	//Release Ctrl\n\nInputSimulator.SimulateKeyUp(VirtualKeyCode.CONTROL);	0
6444865	6393651	Export to Excel - ThreadAbortException	protected void addTrigger_PreRender(object sender, EventArgs e)\n{\n    if (sender is ImageButton)\n    {\n        ImageButton imgBtn = (ImageButton)sender;\n        ScriptManager ScriptMgr = (ScriptManager)this.FindControl("ScriptManager1");\n        ScriptMgr.RegisterPostBackControl(ImgBtn);\n    }\n}	0
19341525	19341462	Using generic class as a parameter in method	private void SaveClass<T>(DCGSerializeableDict<T,T> save,string name){}	0
20954738	20954668	How to get Text from Textbox created during runtime	var sum = this.Controls.OfType<TextBox>()\n    .Where(t => char.IsDigit(t.Name.Reverse().Take(1).FirstOrDefault())\n        && t.Enabled)\n    .Select(t =>\n    {\n        double i;\n        if (!double.TryParse(t.Text, out i)) { return 0d; }\n        return i / 100d;\n    })\n    .Sum();	0
17096470	17096360	C# For Loop Retains Value In Uninstantiated Variable	int taco	0
20458060	20458016	How to call struct data members?	struct stuctName\n{\n      public char dataMemberOne;\n      public char dataMemberTwo;\n}\n\nstatic void Main()\n{\n    structName structOne = new structName();\n    structName structTwo = new structName();\n\n    structOne.dataMemberOne = 'a'; //aassign a value\n\n    Console.WriteLine(structOne.dataMemberOne);  // will output 'a'\n\n    return 0;\n}	0
2122358	2116733	DependencyProperty with TwoWay Binding	UpdateSourceTrigger=Explicit	0
25650585	25611231	In C# webforms, how to validate two textbox values in two SQL Server columns?	(convert(bigint, UPC) BETWEEN '1000' AND '9999') \n            or\n            (\n                UPC IN \n                (\n                    SELECT [UPC]\n                    FROM [JS_Data].[dbo].[ItemMaster]\n                    WHERE (convert(bigint, AlternateUPC) between '1000' and '9999')\n                )\n            )\n)	0
23251951	23250313	Add new row into Header of GridView	Private Sub GridView1_DataBound(sender As Object, e As EventArgs) Handles GridView1.DataBound\n\n    // Add checks for row count.\n\n    // create a new row\n    Dim gvr As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal)\n\n    Dim gvc As TableCell\n\n    // Create a new empty cell\n    gvc = New TableCell()\n\n    //add a new TextBox to the cell\n    gvc.Controls.Add(New TextBox())\n\n    // Add the cell to the row\n    gvr.Cells.Add(gvc)\n\n    // repeat above as necessary\n\n    // Add row to Gridview at index 1 (0 is bound header)\n    // GridView1.Controls(0) is the Gridview table\n    GridView1.Controls(0).Controls.AddAt(1, gvr)\nEnd Sub	0
6352489	6352428	Preventing selection of the same value in seperate comboboxes on a C# form	private void TestUniqueSelection(object sender, System.EventArgs e)\n{\n      var controls = new List<System.Windows.Forms.ComboBox>();\n      controls.Add(...); // <-- Add all of your controls here.\n\n      ComboBox changedBox = (ComboBox) sender;\n\n      if (controls\n           .Where(a => a != changedBox && a.SelectedItem == changedBox.SelectedItem)\n           .Count() > 0)\n           MessageBox.Show("Selected Option has already been chosen");\n}	0
15090928	15090777	How to read from a process that hasn't closed?	process.StartInfo.RedirectStandardOutput = true;\n    process.OutputDataReceived += \n        new DataReceivedEventHandler(process_OutputDataReceived);\n\n    process.StartInfo.RedirectStandardError = true;\n    process.ErrorDataReceived += \n        new DataReceivedEventHandler(process_ErrorDataReceived);\n\n    if (process.Start())\n    {\n        process.BeginOutputReadLine();\n        process.BeginErrorReadLine();\n        process.WaitForExit();\n    }\n}\n\nvoid process_OutputDataReceived(object sender, DataReceivedEventArgs e)\n{\n    Console.WriteLine(e.Data);\n}\n\nvoid process_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n{\n    Console.WriteLine(e.Data);\n}	0
3976265	3976238	How to use compound key for dictionary?	public enum SomeEnum\n{\n value1, value2\n}\n\npublic struct Key\n{\n  public SomeEnum;\n  public int counter;  \n}\n\nDictionary<Key, object>	0
2777386	2777322	C# equivalent of typeof for fields	public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression)\n{\n    MemberExpression memberExpression = null;\n\n    if (expression.Body.NodeType == ExpressionType.Convert)\n    {\n        memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;\n    }\n    else if (expression.Body.NodeType == ExpressionType.MemberAccess)\n    {\n        memberExpression = expression.Body as MemberExpression;\n    }\n\n    return memberExpression.Member as PropertyInfo;\n}\n\n// usage:\nPropertyInfo p = GetProperty<MyClass>(x => x.MyCompileTimeCheckedPropertyName);	0
1158747	1148780	How to set clipboard to copy files?	private void CopyFile(string[] ListFilePaths)\n{\n  System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();\n\n  foreach(string FileToCopy in ListFilePaths)\n  {\n    FileCollection.Add(FileToCopy);\n  }\n\n  Clipboard.SetFileDropList(FileCollection);\n}	0
24857163	24857118	Cancelling sending information upon clicking on "Cancel" from VSTO Add in	private Thread td;\n\nvoid Save()\n{\n    //initialize the thread here\n    //...\n    td.Start();\n    //...\n}\n\nvoid Cancel()\n{\n    if (td != null && td.IsAlive)\n    {\n        //warning canceling\n        //...\n        td.Abort();\n    }\n\n}	0
12226492	12226444	How can I check for a null inside of a linq query?	protected IEnumerable<string> GetErrorsFromModelState()\n{        \n    var exceptions = ModelState.SelectMany(x => x.Value.Errors\n                            .Where(error => (error != null) && \n                                            (error.Exception != null) &&\n                                            (error.Exception.Message != null))\n                            .Select(error => error.Exception.Message));\n\n    var errors = ModelState.SelectMany(x => x.Value.Errors\n                            .Where(error => (error != null) && \n                                            (error.ErrorMessage != null))\n                            .Select(error => error.ErrorMessage));\n\n    return exceptions.Union(errors);\n}	0
14528945	14517295	Edit option in Deal for Wallet in Windows Phone 8	public class myWalletAgent : WalletAgent\n{\n    protected override void OnRefreshData(RefreshDataEventArgs args)\n    {\n        foreach (WalletItem item in args.Items)\n        {\n            item.SetUserAttentionRequiredNotification(true);\n        }\n\n        base.OnRefreshData(args);\n        NotifyComplete();\n    }\n}	0
20442680	20442350	Multiple instance of application but run only one	static void Main()\n{\n    Mutex mutex = new Mutex(false, "MyApp");\n    if (mutex.WaitOne())\n    {\n        try\n        {\n            Application.Run(new Form1());\n        }\n        finally\n        {\n            mutex.ReleaseMutex();\n        }\n    }\n}	0
19229959	19229699	Read Changes on a text file dynamically c#	var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); \n        using (var sr = new StreamReader(fs)) {\n            // etc...\n        }	0
4144817	4144778	Get properties and values from unknown object	Type myType = myObject.GetType();\nIList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());\n\nforeach (PropertyInfo prop in props)\n{\n    object propValue = prop.GetValue(myObject, null);\n\n    // Do something with propValue\n}	0
11122880	11122836	Is it possible to OrderBy a List after a certain element?	list.Take(1).Concat(list.Skip(1).OrderBy(predicate))	0
457708	457676	Check if a class is derived from a generic class	static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {\n    while (toCheck != null && toCheck != typeof(object)) {\n        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;\n        if (generic == cur) {\n            return true;\n        }\n        toCheck = toCheck.BaseType;\n    }\n    return false;\n}	0
30497456	25342705	seesion value conflict on server not in localhost in asp.net	string Emp_Name	0
702947	702895	Break into C# debugger for divide by zero	double a = double.NaN;\nConsole.Out.WriteLine(a == double.NaN); // false\nConsole.Out.WriteLine(a == a); // false\nConsole.Out.WriteLine(double.IsNaN(a)); // true	0
30627182	30626405	How to download the uploaded files?	if (!Directory.Exists(Server.MapPath("~/App_Data/Upload")))\n{\n    Directory.CreateDirectory(Server.MapPath("~/App_Data/Upload"));\n}\n\nfile.SaveAs(path);	0
6584858	6584817	Direct method from SQL command text to DataSet	public DataSet GetDataSet(string ConnectionString, string SQL)\n{\n    SqlConnection conn = new SqlConnection(ConnectionString);\n    SqlDataAdapter da = new SqlDataAdapter();\n    SqlCommand cmd = conn.CreateCommand();\n    cmd.CommandText = SQL;\n    da.SelectCommand = cmd;\n    DataSet ds = new DataSet();\n\n    conn.Open();\n    da.Fill(ds);\n    conn.Close();\n\n    return ds;\n}	0
13660120	13659919	How to animate a simple shape moving vertically?	private void timer1_Tick(object sender, EventArgs e)\n // no need to use your while loop anymore :))\n  {       \n   If(count< 300) //set to your own criteria\n   {\n     //e.g. myrect.location=new point(x,y);\n     // rectangle1.Location = new Point(160, rectangle1.Location.Y -1);       \n   }\n\n    count += 2;\n}	0
29369022	29356618	Get datakey multinested gridview	protected void grdInnerGridView_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n\n    //Accessing GridView from Sender object\n    GridView childGrid = (GridView)sender;\n\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n\n        //Retreiving the GridView DataKey Value\n        string cID = childGrid.DataKeys[e.Row.RowIndex].Value.ToString();\n\n\n    }\n}	0
31928606	31926492	Entity Framework Non static method needs a target. Null values in Lambda	// optional query parameters coming from somewhere...\nDateTime? date;\nint? age;\nstring username;\n\nIQueryable<T_USER> query = db.T_USER.AsQueryable();\n\nif(date != null)\n    query = query.Where(u => u.JoinDate == date);\n\nif(age != null)\n    query = query.Where(u => u.Age == age);\n\nif(username != null)\n    query = query.Where(u => u.Username == username);\n\nvar results = query.ToList();	0
23958355	23956217	Trying to build a WinForms application with all satellite resource assemblies included	AppDomain.CurrentDomain.AssemblyResolve	0
23260265	23210944	How to enter in new line using windows phone emulator	AcceptsReturn = "True"	0
5538894	5538829	How do I default a parameter to DateTime.MaxValue in C#?	public void Problem(DateTime? optional = null)\n{\n   DateTime dateTime = optional != null ? optional.Value : DateTime.MaxValue;\n   // Now use dateTime\n}	0
9494412	9494390	Having trouble with saving rows in database using stored procedures in ASP.NET	cmd.ExecuteNonQuery()	0
12403859	10729383	Error when attempting to Resume a Windows Workflow	var instanceStore = new SqlWorkflowInstanceStore(connStr); \nvar instanceHandle = instanceStore.CreateInstanceHandle();\nvar createOwnerCmd = new CreateWorkflowOwnerCommand();\nvar view = instanceStore.Execute(instanceHandle, createOwnerCmd, TimeSpan.FromSecond(30));\ninstanceStore.DefaultInstanceOwner = view.InstanceOwner; \n// Do whatever needs to be dome with multiple WorkflowApplications \nvar deleteOwnerCmd = new    DeleteWorkflowOwnerCommand();\ninstanceStore.Execute(instanceHandle, deleteOwnerCmd, TimeSpan.FromSeconds(30));	0
14424296	14423627	azure shared access signiture creation	FileInfo fInfo = new FileInfo(fileName);//fileName is the full path of the file.\n                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(blobSaSUrl);\n                NameValueCollection requestHeaders = new NameValueCollection();\n                requestHeaders.Add("x-ms-blob-type", "BlockBlob");\n                req.Method = "PUT";\n                req.Headers.Add(requestHeaders);\n                req.ContentLength = fInfo.Length;\n                byte[] fileContents = new byte[fInfo.Length];\n                using (FileStream fs = fInfo.OpenRead())\n                {\n                    fs.Read(fileContents, 0, fileContents.Length);\n                    using (Stream s = req.GetRequestStream())\n                    {\n                        s.Write(fileContents, 0, fileContents.Length);\n                    }\n                    using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())\n                    {\n                    }\n                }	0
4383916	4383787	Handling Mouse Scroll event of window datagrid in C#	if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)\n {\n      int i = dataGridView1.FirstDisplayedCell.RowIndex;\n }	0
18298796	18298737	Add item in listview in Form1 from textbox in Form2 C#	private void button1_Click(object sender, EventArgs e)\n{\n     ListViewItem item = new ListViewItem(textBox1.Text);\n     Form1 f1 = new Form();\n     f1.listView1.Items.Add(item);\n}	0
2432212	2431987	How to refactor these generic methods?	public static string ToCSVList<T>(this IEnumerable<T> collection)\n{ return string.Join(",", collection.Select(x => x.ToString()).ToArray()); }\n\npublic static string ToCSVList(this IEnumerable<AssetDocument> assets)\n{ return assets.Select(a => a.AssetID).ToCSVList(); }\n\npublic static string ToCSVList(this IEnumerable<PersonDocument> persons)\n{ return persons.Select(p => p.PersonID).ToCSVList(); }	0
17551857	17546055	Trying to access the label in ListView	protected void ListEvent_ItemDataBound(object sender, ListViewItemEventArgs e)\n    {\n        if (e.Item.ItemType == ListViewItemType.DataItem)\n        {\n           ListViewDataItem dataItem = (ListViewDataItem) e.Item;\n           Label LabelBody = (Label)e.Item.FindControl("LabelBody");\n           LabelBody.Text = (string) DataBinder.Eval(dataItem.DataItem, "Body");\n        }\n    }	0
28836269	28699107	How to show data table in report viewer in visual studio 2013	var ConnString = System.ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString;\nSqlDataAdapter dataadapter;\nDataTable someDataTable = new DataTable("ReportViewResults);\nusing (SqlConnection connStr = new SqlConnection(ConnString))\n{\n    using (SqlCommand cmd = new SqlCommand("yourStoredProc or Sql Query", connStr))\n    {\n        cmd.CommandType = CommandType.StoredProcedure;//change to Text if your passing sql string\n        dataadapter= new SqlDataAdapter(cmd);\n        new SqlDataAdapter(cmd).Fill(someDataTable);\n    }\n}	0
3398848	3398831	Get a distinct list of ids from IEnumerable<T>	tankReadings.Select(o => o.MaterialID).Distinct();	0
6025868	6025858	Get names of the params passed to a C# method	MyMethod("abc", new object[5]);\nMyMethod("abc", "def");\nMyMethod("abc", var1 + var2);\nMyMethod("abc", SomeMethod());\nMyMethod("abc", b ? a : c);\nMyMethod("abc", new object()); \nMyMethod("abc", null);	0
6468812	6457382	Retrieving entity from context after Add() yet before SaveChanges() has been called	Dictionary<string, Person> newPeople = ...\n\nforeach(row in fileRows)\n{\n    Person person;\n\n    //if the person is already tracked by the dictionary, work with it, if not use the repository\n    if(!newPeople.TryGetValue(row.SSN, out person))\n    {\n        person = personRepository.GetBySSN(row.SSN);\n    }\n\n    if(person == null)\n    {\n        //insert logic\n\n        //keep track that this person is already in line for inserting\n        newPeople.Add(row.SSN, person);\n    }\n    else\n    {\n        //update logic\n    }\n}\n\npersonRepository.SaveChanges();	0
26163301	25794071	Is there a system Task that can take a photo in the WinRT API?	using Windows.Media.Capture; \nusing Windows.Storage; \n\nCameraCaptureUI dialog = new CameraCaptureUI(); \nStorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);	0
2526750	2526719	Getting a set of elements using linq	XDocument xml = XDocument.Parse(@"<your XML>");\nfrom field in xml.Elements("ObsCont")\nwhere field.Attribute("xCampo") != null && \nfield.Attribute("xCampo").Value == "field2"\nselect field.Element("xTexto").Value;	0
4485414	4362175	RuntimeBinderException on dynamic Linq with Facebook C# SDK	var result = (JsonArray)fb.Fql(query);\nreturn result.Select((Func<dynamic, string>)(x => x.uid)).ToList();	0
30920391	30908073	play audio periodically from a memory stream c#	SoundEffect mySoundPlay = new SoundEffect(mStrm.ToArray(), 16000,AudioChannels.Mono);\nSoundEffectInstance instance = mySoundPlay.CreateInstance();\ninstance.IsLooped = true;\ninstance.Play();	0
13370422	13370372	How to program async processing of widgets?	BackgroundWorker worker = new BackgroundWorker();\nworker.WorkerReportsProgress = true;\nworker.DoWork += (sender, args) => {\n    var documents = GetDocuments();\n    foreach(var document in documents)\n    {\n        ProcessDocument(document);\n        worker.ReportProgress(0, status);\n    }\n};\nworker.ProgressChanged += (sender, args) => {\n    this.TextBox.Text += args.UserState.ToString();\n};\nworker.RunWorkerAsync();	0
4825782	4825612	How to fix position of Mdichild forms?	{\n\n        this.Location = new Point(x, y); //give fixed postion as you want\n    }	0
6432567	6423351	Determine sender object from event handler	public class MyClass\n{\n   private COMClass instance;\n   public event EventHandler<BetterEventArgs> MyBetterEvent;\n\n   public MyClass()\n   {\n      instance.event += new EventHandler(Handle_COM_event); // ... or whatever\n   }\n\n   public void Handle_COM_event(EventArgs)\n   {\n      if(MyBetterEvent != null) MyBetterEvent(this, new BetterEventArgs());\n   }\n\n}	0
7226029	7225863	How to check if column of GridView is empty, and if it is, make a button invisible?	if (data.Count() == 0)//this if statement is wrong\n{\n    BtnImport1.Visible = false;\n}	0
26528678	26513280	Save data on exit Windows Phone 8.1 (Universal Apps)	private void OnSuspending(object sender, SuspendingEventArgs e)\n{\n    var deferral = e.SuspendingOperation.GetDeferral();\n    // TODO: Save application state and stop any background activity\n    Debug.WriteLine("SUSPENDING");\n    // Wait fir Save to finish its a sync operations\n    await HabitManager.HabitSerializer.Save();\n    deferral.Complete();\n}\n\npublic async static Task Save()\n{\n    // Same save code\n}	0
33619843	33616240	Inserting many rows with Entity Framework is extremely slow	// Add all workers to database\nvar workforce = allWorkers.Values\n   .Select(i => new Worker\n   {\n      Reference = i.EMPLOYEE_REF,\n      Skills = i.GetSkills().Select(s => dbSkills[s]).ToArray(),\n      DefaultRegion = "wa",\n      DefaultEfficiency = i.TECH_EFFICIENCY\n   });\n\ndb.BulkInsert(workforce);	0
18480218	18479578	how to override windows back button in windows phone 8 ?	protected override void OnBackKeyPress(CancelEventArgs e)\n{\n    if(MessageBox.Show("Are you sure you want to exit?","Confirm Exit?", \n                            MessageBoxButton.OKCancel) != MessageBoxResult.OK)\n    {\n        e.Cancel = true; \n\n    }\n}	0
19655967	19618223	FluentNhibernate Map IDictionary<Entity1,Entity2>	public class Entity3Map : ClassMap<Entity3>\n{\n    public Entity3Map()\n    {\n        Id(x => x.Id);\n\n        HasManyToMany(x => x.Dict)\n            .Table("linkTable")\n            .Cascade.All()\n            .AsEntityMap();\n    }\n}\n\n\nvar e1 = new Entity1();\nvar e2 = new Entity2();\nusing (var tx = session.BeginTransaction())\n{\n    session.Save(e1);\n    session.Save(new Entity3 { Dict = { { e1, e2 } } });\n    tx.Commit();\n}\nsession.Clear();\n\nvar entity3 = session.Query<Entity3>().FetchMany(x => x.Dict).ToList().First();\n\nAssert.Equal(1, entity3.Dict.Count);\nAssert.Equal(e1.Id, entity3.Dict.First().Key.Id);\nAssert.Equal(e2.Id, entity3.Dict.First().Value.Id);	0
19078257	19078219	How to get the exact position of string one into string 2 c#	int pos = Str1.IndexOf(Str2);	0
23044551	23044426	Replace the particular part of string?	var str = "asp,mvc,c#,wpf";\nvar anotherStr = "<b>asp</b>,<b>wpf</b>";\nvar myArr = anotherStr.Replace("<b>", "").Replace("</b>", "").Split(',');\nforeach (string value in myArr)\n{\n    str = str.Replace(value, "<b>" + value + "</b>");\n}\nConsole.WriteLine(str);	0
34433301	34433105	Start another EXE with command line parameters in C#	Process.Start(new ProcessStartInfo(Application.StartupPath + "\\Tool.exe")\n{\n    Arguments = String.Format(@"""{0} {1}""", UserName, Password)\n}\n);	0
23048441	23037138	Unable to create a shared link using the Box API V2	string uri = String.Format(UriFiles, fileId);\n        string response = string.Empty;\n        string body = "{\"shared_link\": {\"access\": \"open\"}}";\n        byte[] postArray = Encoding.ASCII.GetBytes(body);\n\n        try\n        {\n            using (var client = new WebClient())\n            {\n                client.Headers.Add("Authorization: Bearer " + token);\n                client.Headers.Add("Content-Type", "application/json");\n                response = client.UploadString(uri, "PUT", body);\n            }\n        }\n        catch (Exception ex)\n        {\n            return null;\n        }\n        return response;	0
13852085	13851854	How to find the default dateformat of a Culture	var cultureLanguageTag = CultureInfo.CurrentCulture.IetfLanguageTag;\nvar defaultCulture =  CultureInfo.GetCultureInfoByIetfLanguageTag( cultureLanguageTag );	0
1145562	972636	Casting a variable using a Type variable	public T CastExamp1<T>(object input) {   \n    return (T) input;   \n}\n\npublic T ConvertExamp1<T>(object input) {\n    return (T) Convert.ChangeType(input, typeof(T));\n}	0
16506033	16505324	fetch attribute values of repeated named xml elements	var i = 0;\n\nvar lstOptions = new List<string>();\n\nXDocument xdoc = XDocument.Load("Assets/xml_files/flags.xml");                    \n\n        foreach (var item in xdoc.Descendants("item").Elements())\n        {\n            switch (item.Name.LocalName)\n            {\n                case "img":\n                    questions.ImageName = item.Attribute("src").Value;\n                    break;\n                case "option":           \n                    lstOption.add(item.Attribute("value").Value);\n                    break;\n                case "desc":\n                    questions.Description = item.Value;\n                    break;\n            }\n        } \n\n        questions.OptionA = lstOption[0];\n        questions.OptionB = lstOption[1];\n        questions.OptionC = lstOption[2];\n        questions.OptionD = lstOption[3];	0
26065666	26043108	Building a module in C# for Powershell 2 without Visual Studio or access to an SDK	[Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()\csc.exe	0
17781017	17780935	.SELECT statement using lambda and Entity Framework	var sumPerLocation = locations.Select(l => l.Payouts.Sum(p => p.Amount));\nforeach (var sum in sumPerLocation)\n{\n    Console.WriteLine(sum);\n}	0
10181905	10181651	WebRequest enter URL	myRequest = WebRequest.Create(txtUrl.Text);	0
21010880	21010867	How to iterate and compare through a list of string inside if statement	if (new[] { "Channel", "QueueManager", "QueueServer" , "QueueName" }.Contains( node.FirstChild.InnerText)){ }	0
19491716	19491652	How to validate using Regex	int val;\nif (Int32.TryParse("00ABFSSDF".Substring(0, 2), out val))\n{\n    if (val >= 0 && val <= 32)\n    {\n        // valid\n    }\n}	0
5612384	5612200	Application Setting Modification in ASP c#	System.Configuration.Configuration updateWebConfig =\n        System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("\\");\n System.Configuration.ConnectionStringSettings conStringSettings = updateWebConfig.ConnectionStrings.ConnectionStrings["testConString"]; //your connection string name here as specified in the web.Config file\n conStringSettings.ConnectionString = txtCon.Text; //Your Textbox value here\n conStringSettings.CurrentConfiguration.Save();	0
25737396	25737054	EF Database first how to update model for database changes?	CREATE TABLE	0
1256133	1255982	Dynamically change size of splitContainer Panel	splitContainer.IsSplitterFixed = false.\n\nsplitContainer.DataBindings.Add("Height", <yourcontrol>, "Height")	0
23203084	23185985	Azure Mobile Service LoginAsync with Facebook Token is Unauthorized	WWW-Authenticate	0
9620310	9620261	How to delete user accounts in asp.net?	Membership.DeleteUser("username");	0
17699123	17699031	Upload files to a specific folder in dropbox	var file = api.UploadFile("dropbox", @"myfolder\photo.jpg", @"C:\Pictures\photo.jpg");	0
33487233	33487191	VB to C# in InStrRev	String.LastIndexOf	0
13065626	13065438	How to convert List<string> to List<int> where empty or null string to be converted as 0 using LINQ in C#	var stringlist = new List<String> { "1", "2", "", null };\n        var intList = stringlist.Select(s => { int i; return int.TryParse(s, out i) ? i : 0; }).ToList();\n        Debug.Print("{0},{1},{2},{3}", intList[0], intList[1], intList[2], intList[3]);	0
2445940	2445885	How to check the type of object in ArrayList	if( obj.GetType() == typeof(int) )\n{\n    // int\n}	0
9486161	9485907	dynamically created list of link buttons, link buttons not posting back	protected override void OnInit(EventArgs e)\n    {\n        base.OnInit(e);\n\n        int listItemIds = 1;\n\n        for (int i = 0; i < 10; i++)\n        {\n            HtmlGenericControl li = new HtmlGenericControl("li");\n            LinkButton lnk = new LinkButton();\n\n            lnk.ID = "lnk" + listItemIds;\n            lnk.Text = "text" + i;\n            lnk.Click += Clicked;\n            //lnk.Command += new CommandEventHandler(lnkColourAlternative_Click);\n            //lnk.Click \n            li.Controls.Add(lnk);\n            ul1.Controls.Add(li);\n            listItemIds++;\n        }\n    }\n\n    private void Clicked(object sender, EventArgs e)\n    {\n        var btn = sender as LinkButton;\n        btn.Text = "Clicked";\n    }	0
29499948	29499505	How to export part of a huge Canvas to PNG	var size = new Size(main.Width, main.Height);\nmain.Measure(size);\n\nvar cropOffset = new Point(-256, -256);\nmain.Arrange(new Rect(cropOffset, size));\n\nvar renderBitmap = new RenderTargetBitmap(256, 256, 96d, 96d, PixelFormats.Pbgra32);\nrenderBitmap.Render(main);	0
31391435	31391389	How to address controller in another namespace?	Html.BeginForm("Signup", "Customer", FormMethod.Post, new { area="AreaName" })	0
12437503	12435340	How to change highlight colour of a portion of a text in rich text box?	Run run = new Run("Red is the third line.\n");\n    // run.Foreground = Brushes.Red;\n    run.Background = Brushes.Red;\n    para.Inlines.Add(run);	0
3073155	3073110	Calling original method with Moq	var mock = new Mock<ProductRepository>() { CallBase = true };	0
6406852	6406841	How to get number of arguments in a constructor	ConstructorInfo ctor = /* ... */\nint numberOfArguments = ctor.GetParameters().Length;	0
2316940	2316594	How to include non-compiled content alongside a C# program published via Visual Studio	XmlDocument document = new XmlDocument();\ndocument.Load("Resources/DefaultConfig.xml");	0
5532064	5532016	Meaningful Auto Rename of File using ASP.NET	string fileName = downloadFileName;\nstring fileExt = downloadFileExtention;\n\nstring fullFileName = string.Format("{0}.{1}", fileName, fileExt);\n\nint counter = 0;\nwhile(File.Exists(fullFileName))\n{\n    counter++;\n    fullFileName = string.Format("{0}({1}).{2}", fileName, counter, fileExt);\n}\n\n// Write the file to fullFileName	0
15548008	15547812	c# combobox filtering one combobox based on the value of another combobox	if(comboBox2.SelectedValue != null)\n{\n    DataView dv = comboBox1.DataSource as DataView;\n    dv.RowFilter = "pcatid = " + comboBox2.SelectedValue.ToString();\n}	0
17428628	17371649	How can the WCF RoutingService route callback messages from two different WCF servers with the same contract to a client?	routingConfiguration.FilterTable.Add(new MatchAllMessageFilter(), new List<YourServiceType> { yourService }, 1);	0
6839937	6836949	Fluent nHibernate Join is doing insert into joined table	x.Inverse();	0
14649674	14649436	Saving multiple files	if (System.IO.File.Exists(path))\n System.IO.File.Delete(path);\nfile.SaveAs(path);	0
10409805	10409681	change font size in windows application	public partial class MainForm : Form\n{\n    public MainForm()\n    {\n        InitializeComponent();\n                    this.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));\n    }\n}	0
3160192	3160163	How can I find a parameter's original variable name as a string at runtime?	this.setTextBoxPrixEnter(((TextBox)sender).Name);	0
12649433	12649296	While reading text file, date format is changed in c#	DateTime d = Convert.ToDateTime(sa1[0]);\n\nstring wline = d.ToString("yyyy-MM-dd") + "," + sa1[1] + "," + sa1[5] + "," + sa1[6] + "," + sa1[7];	0
1607333	1605845	How to bind a ComboBox to generic dictionary via ObjectDataProvider	SelectedValuePath="Key" DisplayMemberPath="Value"	0
1799190	1799158	Programmatically add a span tag, not a Label control?	var span = new HtmlGenericControl("span");\nspan.InnerHtml = "From<br/>Date";\nspan.Attributes["class"] = "nonExpense";\nheaderCell.Controls.Add(span);	0
14446891	14431584	Updating Multiple Child Entities from a Parent Edit Form?	for (int i = 0; i < Model.ResultNotes.Count(); i++ )	0
19766693	19763301	How can I limit the number of selected items in a radTreeListView?	private void radTreeListView_SelectionChanging(object sender, Telerik.Windows.Controls.SelectionChangingEventArgs e)\n    {\n        if (radTreeListView.SelectedItems.Count >= 5 && e.AddedItems.Count>0)\n            e.Cancel = true;\n    }	0
19165864	19141360	Using ClearUsernameBinding without App.Config	binding.SetMessageVersion(System.ServiceModel.Channels.MessageVersion.Soap11);	0
14148749	8653452	Naudio: How to play MP3 and WAV file?	WaveStream mainOutputStream = new MP3FileReader(path_of_the_file_you_want_to_play);\nWaveChannel32 volumeStream = new WaveChannel32(mainOutputStream);\n\nWaveOutEvent player = new WaveOutEvent();\n\nplayer.Init(volumeStream);\n\nplayer.Play();	0
22143246	22142997	How to parse expression tree to extract a type condition OfType	IQueryable queryable = ...\n\nvar methodCall = queryable.Expression as MethodCallExpression;\n\nif(methodCall != null)\n{\n   var method = methodCall.Method;\n\n   if(method.Name == "OfType" && method.DeclaringType == typeof(Queryable))\n   {\n      var type = method.GetGenericArguments().Single();\n      Console.WriteLine("OfType<{0}>", type);\n   }\n}	0
14617049	14611838	How can I resolve MSI paths in C#?	using System;\nusing Microsoft.Deployment.WindowsInstaller;\nusing Microsoft.Deployment.WindowsInstaller.Package;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            using (var package = new InstallPackage("foo.msi", DatabaseOpenMode.ReadOnly))\n            {\n                foreach (var filePath in package.Files)\n                {\n                    Console.WriteLine(filePath.Value);\n                }\n                Console.WriteLine("Finished");\n                Console.Read();\n            }\n        }\n    }\n}	0
12693177	12692739	Signed int array typecast C#	var final = new int[1];\nvar calc = new[] { -0.02043936f };\nfinal[0] = (int)Math.Floor(calc[0]);\n\nConsole.WriteLine(\n    "calc:{0} final:{1} test:{2}",\n    calc[0],\n    final[0],\n    (int)Math.Floor(calc[0]));	0
4845225	4845194	Is this a bad way to cache pages for my screen-scraper?	webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);	0
11814492	11805950	Configuration settings properties read in dynamically	dynamic country = new ExpandoObject();\n var countryDic = country as IDictionary<string, object>;\n\n dynamic metadata = new ExpandoObject();\n var metadataDic = metadata as IDictionary<string, object>;\n metadataDic["filePath"] = "your file path";\n\n countryDic["metadata"] = metadata;\n var filePath = country.metadata.filePath;	0
29906081	29905983	Convert MM:SS string to HH:MM:SS in C#	for (int i = 0; i < nrdaily.Rows.Count; i++)\n{\n     string time = nrdaily.Rows[i][3].ToString();\n     if (time.Length == 5)\n          time = "00:" + time;\n     double NRT = TimeSpan.Parse(time).TotalSeconds;\n     nrdaily.Rows[i][3] = NRT;\n}	0
7938346	7891303	Decode Signed Request Without Authentication	if (Request.Params["signed_request"] != null)\n{\n    string payload = Request.Params["signed_request"].Split('.')[1];\n    var encoding = new UTF8Encoding();\n    var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');\n    var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));\n    var json = encoding.GetString(base64JsonArray);\n    var o = JObject.Parse(json);\n    var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");\n    var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");\n    var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");\n}	0
1883773	1883743	to open up an excel file, do I need any special references?	Micorsoft.Office.Interop.Excel	0
5716502	5716422	C# instantiating a Class that hold a ListArray into a method	public class ListEx\n{\n   public List<string> name = new List<string>();\n}\n\nvoid StoreName()\n{\n  ListEx nm = new ListEx();\n  List<string> localList = new List<string>();\n\n  localList.Add ( "whatever" );\n\n  nm.name = localList;\n}\n\nvoid StoreNameShort()\n{\n  ListEx nm = new ListEx();\n\n  nm.name.Add( "whatever" );\n}	0
26534500	26534256	Window close on keypress?	void Update() \n{\n    if (Input.GetKey("escape"))\n    {\n        Application.Quit();\n    }        \n}	0
23707373	23707179	Save CheckBoxlist values to database using asp.net	string s;\n for (int i = 0; i < CheckBoxList1.Items.Count - 1;i++ )\n    {\n        if(CheckBoxList1.Items[i].Selected)//changed 1 to i \n            s += CheckBoxList1.Items[i].Text.ToString() + ","; //changed 1 to i\n    }\n\n cmd.Parameters.AddWithValue("@qual",s);	0
23432661	23431896	Access text from dynamically added textboxes	public void Page_Init(object sender, EventArgs e)\n{\n    CreateDynamicControls();\n}\n\nprivate void CreateDynamicControls()\n{\n    notifications = (List<TextBox>)(Session["Notifications"]);\n\n    if (notifications != null)\n    {\n        foreach (TextBox textBox in notifications)\n        {\n            NotificationArea.Controls.Add(textBox);\n        }\n    }\n}	0
20879105	20879026	Determine programmatically the index in the solution of project- C#	string yourProject = "ProjectName";\nvar query = Solution.Projects.Cast<Project>()\n            .Select((p, i) => new { Name = p.Name, Index = i})\n            .First(p => p.Name == yourProject).Index;	0
12492243	12474825	Digital signature with itextsharp	public byte[] sign(string text)\n         {\n//Password for the PFX certificate\n            string password = "1234";\n//Importing the PFX certificate that contains the private key which will be used for creating the digital signature\n            X509Certificate2 cert = new X509Certificate2("c:\\certificate.pfx", password);\n//declaring RSA cryptographic service provider\n            RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;\n//cryptographic hash of type SHA1\n            SHA1Managed sha1 = new SHA1Managed();\n//encoding the data to be signed\n            UnicodeEncoding encoding = new UnicodeEncoding();\n            byte[] data = encoding.GetBytes(text);\n//generate Hash\n            byte[] hash = sha1.ComputeHash(data);\n//sign Hash\n            return crypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));\n        }	0
4923614	4923413	How to extract the useful data with regular expression in C#	string url = "<a href=\"/KB/ajax/\" id=\"ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL\">Ajax</a>";\n\nRegex finder = new Regex("href=\"([^\"]*)\"");\nstring first = finder.Match(url).Groups[1].Value;\n\nfinder = new Regex(">([^<]*)<");\nstring second = finder.Match(url).Groups[1].Value;	0
1402244	1402195	Unable to extract data after PtrToStructure through NamedPipe [C#]	// Corresponding C# MESSAGE structure\n[ StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]\npublic struct MESSAGE\n{\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]\n    public string cSender;\n\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]\n    public string cCommand;\n}	0
4407550	4407444	Explicit cast operator in Managed C++ for a .NET DLL	static explicit operator System::String^(Field^ obj)\n    {      \n        // etc..\n    }	0
6310950	6310866	Removing an item from a generic Dictionary?	(states as IDictionary).Remove(controlID);	0
31466845	31446074	Find a specific element anywhere in an arbitrary JSON	List<CartItem> GetAllCartItemsFromArbitraryJson(string jsonStr) {\n  JObject json = JObject.Parse(jsonStr);\n\n  return json.Descendants().OfType<JProperty>()  // so we can filter by p.Name below\n             .Where(p => p.Name == "cartitems")\n             .SelectMany(p => p.Value)           // selecting the combined array (joined into a single array)\n             .Select(item => new CartItem {\n                 Id  = (int)item["id"],\n                 Qty = (int)item["qty"]\n             }).ToList();\n}	0
9789127	9789027	How do I format a number as a string, so that zero is replaced by the empty string	string formattedResult1 = string.Format("{0:0.######;-0.######;\"\"}", myInt);	0
8254186	8253836	Explain this odd behavior with IEnumerable / yield	yield return	0
4859186	4859023	Find an array (byte[]) inside another array?	static int search(byte[] haystack, byte[] needle)\n{\n    for (int i = 0; i <= haystack.Length - needle.Length; i++)\n    {\n        if (match(haystack, needle, i))\n        {\n            return i;\n        }\n    }\n    return -1;\n}\n\nstatic bool match(byte[] haystack, byte[] needle, int start)\n{\n    if (needle.Length + start > haystack.Length)\n    {\n        return false;\n    }\n    else\n    {\n        for (int i = 0; i < needle.Length; i++)\n        {\n            if (needle[i] != haystack[i + start])\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n}	0
14402548	14346412	Collect a list of user classes in a project using EnvDTE	var project = env.ActiveDocument.ProjectItem.ContainingProject;\nforeach(EnvDTE.CodeElement element in project.CodeModel.CodeElements)\n{\n    if (element.Kind == EnvDTE.vsCMElement.vsCMElementClass)\n    {\n        var myClass = (EnvDTE.CodeClass)element;\n        // do stuff with that class here\n    }\n}	0
31357143	31357043	Generate property stub showing instead of generate method stub	book.NameChanged += (OnNameChanged)	0
6485622	6485585	Help with a function that is going out of scope (C#)	class ....\n{\n    WebClient webClient;\n\n    private void Download_Click(object sender, EventArgs e)\n    {\n        webClient = new WebClient();\n    }\n\n\n    private void Button1_Click(object sender, EventArgs e)\n    {\n        webClient.CancelAsync();\n    }	0
14121879	14121644	Convert int to hex format 0xyy c#	static string Int32ToBigEndianHexByteString(Int32 i)\n{\n    byte[] bytes = BitConverter.GetBytes(i);\n    string format = BitConverter.IsLittleEndian\n        ? "0x{3:X2} 0x{2:X2} 0x{1:X2} 0x{0:X2}"\n        : "0x{0:X2} 0x{1:X2} 0x{2:X2} 0x{3:X2}";\n    return String.Format(format, bytes[0], bytes[1], bytes[2], bytes[3]);\n}	0
31606114	31606053	Connect node.js based socket.io websocket server from a C# program	WebSocket webSocketClient = new WebSocket("ws://localhost:8080/socket.io/?EIO=3&transport=websocket");	0
6335803	6335569	How to make a .msi file that has no clickable screens (fully automated)?	msiexec /i myapp.msi /qn	0
7971980	7970559	populate div kinda like what innerhtml does in js	htmlElementListener.SetProperty("innerHTML", "my new text to populate in the div");	0
5893134	5893095	How can I share data between multiple user controls?	public class Page : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    { \n        string data = DoXMLRequest();\n        ucControl1.Data = data;\n        ucControl2.Data = data;\n        ucControl3.Data = data;\n    }\n}	0
3597752	3597732	How Do I add only TIME in C#	var t1 = TimeSpan.Parse("00:12:34");\nvar t2 = TimeSpan.Parse("00:52:12");\nvar t3 = TimeSpan.Parse("23:19:56");\n\nvar result = t1 + t2 + t3\n\nConsole.WriteLine("Total time is {0} Hours {1} Mins {2} secs", \nresult.Days * 24 + result.Hours, result.Minutes, results.Seconds);	0
5112189	5112141	How do I save a file to disk?	string nameAndLocation = "~/UploadedFiles/" + hpf.FileName;\nhpf.SaveAs(Server.MapPath(nameAndLocation));	0
9984366	9980904	WPF webbrowser - get HTML downloaded?	dynamic doc = webBrowser.Document;\nvar htmlText = doc.documentElement.InnerHtml;	0
13837815	13836097	Parsing large json	List<string> d = new List<string>();\n\n        using (\n            StreamReader stream =\n                File.OpenText(\n                    "C:\\path\\Sources.json")\n            )\n        {\n            JObject sources = (JObject) JToken.ReadFrom(new JsonTextReader(stream));\n\n            var a = sources["on"];\n            var b = a["sources"];\n            var c = b["prgs"];\n            foreach (JObject item in c["prg"].ToList())\n            {\n                d.Add(item.Value<string>("name"));\n            }\n\n        }\n\n        //part below is just for testing\n        foreach (var VARIABLE in d)\n        {\n            Console.WriteLine(VARIABLE);\n        }\n        Console.ReadLine();	0
23103234	23095863	Panel displays scaled images	set {\n        mImage = value;\n        if (value == null) this.AutoScrollMinSize = new Size(0, 0);\n        else {\n            var size = value.Size;\n            using (var gr = this.CreateGraphics()) {\n                size.Width = (int)(size.Width * gr.DpiX / value.HorizontalResolution);\n                size.Height = (int)(size.Height * gr.DpiY / value.VerticalResolution);\n            }\n            this.AutoScrollMinSize = size;\n        }\n        this.Invalidate();\n    }	0
13462776	13462081	Regex to extract Variable Part	\[[^[\]]*\]	0
8406303	8402798	Multi-color diagonal gradient in winforms	void MainFormPaint(object sender, PaintEventArgs e)\n{\n  LinearGradientBrush br = new LinearGradientBrush(this.ClientRectangle, Color.Black, Color.Black, 0 , false);\n  ColorBlend cb = new ColorBlend();\n  cb.Positions = new[] {0, 1/6f, 2/6f, 3/6f, 4/6f, 5/6f, 1};\n  cb.Colors = new[] {Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet};\n  br.InterpolationColors= cb;\n  // rotate\n  br.RotateTransform(45);\n  // paint\n  e.Graphics.FillRectangle(br, this.ClientRectangle);\n}	0
32243550	32242509	How to loop multiple Data Tables and Perform print all in same page	string csvId = string.Empty;\n\nfor (int i = 0; i < grdTests.Rows.Count; i++)\n{\n    CheckBox chkTest = (CheckBox)grdTests.Rows[i].FindControl("chkTest");\n    Label lblPtestid = (Label)grdTests.Rows[i].FindControl("lbltestid");\n    string id= lblPtestid.Text;\n    if (chkTest.Checked)\n    {\n        csvId += id + ",";\n        // GetData(id)\n        // Print()\n    }\n    else {} // This is not required actually.\n}\n\nif(!string.IsNullOrEmpty(csvId))\n{\n    // Trim the extra comma at the end.\n    csvId = csvId.Remove(csvId.Length - 1);\n\n    // Get data for all selected records.\n    GetData(csvId);\n    Print();\n}\n\npublic static DataTable gettable(string id)\n{\n    string Query = "select * from table where id IN ('" + id + "')";\n    DataTable dt = DAL.getData(Query);\n    return dt;\n}	0
26779640	26779338	How to avoid control right to left property be affected by container	[System.ComponentModel.DesignerCategory("Code")]\npublic class MyLabel : Label\n{\n    [DefaultValue(true)]\n    public new bool AutoSize\n    {\n        get { return base.AutoSize; }\n        set { base.AutoSize = value; }\n    }\n\n    public MyLabel()\n    {\n        AutoSize = true;\n    }\n}	0
19770036	19767115	Razor DropDownList for each and all elements	return View(unitofwork.DomainRepository.Filter(n => n.Name.Contains(searchFullName), n => (String.IsNullOrEmpty(searchExtension) || n.Extension == searchExtension), n => (String.IsNullOrEmpty(searchProject) || n.Project == searchProject)));	0
9166200	9165850	Deserializing a List of KeyValuePairs	[XmlArray("Values")]\n[XmlArrayItem("KeyValuePair")]\npublic List<KeyValuePair<string, string>> Values { get; set; }	0
7093373	7093212	how to remove [ ] in the mailer	string address = "Shankar[admin@contentraven.com]";\nstring name = address.Substring(0, address.IndexOf('[') - 1);\n// here, name contains "Shankar"	0
5661386	5661072	Get next item in a tree	public Node GetBelowNode()\n{\n    if (GetChildrenNodes().count > 0)\n        return GetChildrenNodes()[0];\n    else\n        if (GetNextSiblingNode() != null)\n            return GetNextSiblingNode();\n        else\n        {\n            Node curr = this;\n            Node parent; \n            while (true)\n            {\n                parent = curr.GetParentNode();\n                if (parent == null)\n                    return null;\n                else\n                {\n                    if (parent.GetNextSiblingNode() != null)\n                        return parent.GetNextSiblingNode();\n                    else\n                        curr = parent;\n                }\n            }\n        }\n}	0
25144374	25144201	How to search list with diacritics, when base character is entered?	string MyRegEx = "";\nfor(int i=0; i<input.Length; i++)\n{\n    switch(input[i])\n    {\n        case 'a':\n            MyRegEx += [a??];\n            break;\n        case 'c':\n            MyRegEx += [c?];\n            break;\n\n        ....\n\n        default: //for letters that do not have any accented variants\n            MyRegEx += input[i];\n            break;\n    }\n}\n\nSystem.Text.RegularExpressions.RegEx R = new System.Text.RegularExpressions.RegEx(MyRegEx);\nvar Your Results = SuggestionsList.Where(s => R.IsMatch(s.ToLower()));	0
16916925	16916811	Properties of a parsed JSON object are null	public class City\n{\n   public int id { get; set; }\n   public string name { get; set; }\n   public string coords { get; set; }\n   public string relationship { get; set; }\n}	0
31019632	31019345	Data retrieving from XElemnt using LINQ	var data = item.Elements().Single(x => x.Attribute("name").Value == "field2").Value;	0
17601358	17601196	Zero filling null datetimes and formatting datetime	if date field is null\n{\n    return "00000000"\n}\nelse\n{\n    return string of date formatted as "MMddyyyy"\n}	0
9114788	9114748	Set multiple properties in a List<T> ForEach()?	list.ForEach(i => { i.a = "hello!"; i.b = 99; });	0
26140318	26139129	Clear file content with FileSavePicker in Windows store app / RT	await FileIO.WriteTextAsync(saveFile, string.Empty);	0
29538485	29537852	DataVisualisation Donut Chart slice clicked event	private void chart1_Click(object sender, EventArgs e)\n{\n    HitTestResult results = chart1.HitTest((e as MouseEventArgs).X, (e as MouseEventArgs).Y);\n}	0
19555569	19539089	JSON Serializing confusion	JobsList jobList = JsonConvert.DeserializeObject<JobsList>(JsonString);	0
22215180	22215049	How to set the size of an array via an InputBox? c#	var size = Interaction.InputBox("Enter the array size:");\n int arraySize;\n if (int.TryParse(size, out arraySize))\n {\n      var myArray = new int[arraySize];\n }	0
2726004	2725988	Setting the initial value of a property when using DataContractSerializer	[OnDeserialized]\nvoid OnDeserialized(StreamingContext context)\n{\n    this.IsNew = true;\n}	0
7545800	7545775	How to loop through all controls in a Windows Forms form or how to find if a particular control is a container control?	private void AddEvent(Control parentCtrl)\n{\n  foreach (Control c in parentCtrl.Controls)\n  {\n    c.KeyDown += new KeyEventHandler(c_KeyDown);\n    AddEvent(c);\n  }\n}	0
31290467	31290300	Apply bold font to two consecutive rows in a datagridview	cashBookRowsMarchTotals.Rows[0].DefaultCellStyle.Font = new Font(cashBookRowsMarchTotals.Font, FontStyle.Bold);\n            cashBookRowsMarchTotals.Rows[1].DefaultCellStyle.Font = new Font(cashBookRowsMarchTotals.Font, FontStyle.Bold);	0
5114433	5114299	I need help converting a C# string from one character encoding to another?	// LINQPad -- Encoding is System.Text.Encoding\nvar enc = Encoding.GetEncoding(1252);\nstring.Join(" ", enc.GetBytes("Sin??ad O'Connor")).Dump();\n// -> 83 105 110 233 97 100 32 79 39 67 111 110 110 111 114	0
11056218	11056049	how to identify if a thread has been aborted or completed	public static void TestThreadAbort()\n{\n    var t = new Thread(() => Thread.Sleep(50000));\n    t.Start();\n    t.Abort();\n    Thread.Sleep(50);\n    // Prints "Aborted"\n    Console.WriteLine(t.ThreadState);\n}	0
6369284	6369224	How can I do this regex on C#?	string s = "hello <div>bye bye</div> marco <img />";\n\n        Regex rgx = new Regex("(<div>[^<]*</div>)|(<img */>)");\n        s = rgx.Replace(s, "");	0
18016089	18016016	How to select columns and sum of columns using group by keyword from data table in c#	DtTest\n.AsEnumerable()\n.GroupBy\n(\n   x=>\n   new\n   {\n       BNO = x.Field<int>("BNO"),\n       INO = x.Field<int>("INO"),\n       Desp = x.Field<string>("Desp"),\n       Rate= x.Field<decimal>("Rate")\n   }\n)\n.Select\n(\n   x=>\n   new \n   {\n      x.Key.BNO,\n      x.Key.INO,\n      x.Key.Desp,\n      Qty = x.Sum(z=>z.Field<int>("Qty")),\n      x.Key.Rate,\n      Amount = x.Sum(z=>z.Field<decimal>("Amount"))\n   }\n);	0
16062921	16062711	No overload for method 'GetKennel' takes 1 arguments c#	DataTable dt = _kennelDAL.GetKennel("MyName", "MyAddress1", "MyAddress2", "MyAddress3", "MyPostCode", 10);	0
22817765	22817611	Regex to identify file pattern	var expectedName = FilePrefix + " " + DateTime.Now.ToString("yyyyMMdd") + ".csv"; \n\nString.Compare(fileName, expectedName, StringComparison.OrdinalIgnoreCase) == 0	0
4552024	4552010	How can I determine if a subdirectory exists in C#?	Directory.Exists	0
19621719	19621695	Trying combination logic in Lists in C#	UserManager U = UM.Find(\n  item => item.Username == Username && item.Password == Password\n);	0
2826963	2825252	How to create Local Data Caching in c# WinApps?	static List<T>	0
16981402	16980875	Using GAC assemblies needs permissions	cacls.exe %windir%/assembly /e /t /p DOMAIN\SSRSSvcAccount:R	0
14154315	14154204	Getting grid.column property of a control in a general styled event handler	private void GeneralTextBoxMouseEnter(object sender, MouseEventArgs e)\n    {\n        TextBox tb = (TextBox)sender;\n\n        MessageBox.Show(Grid.GetColumn(tb));\n\n    }	0
19536490	19536197	How to read value of a web form field from C# Application	string fieldValue = \n      webBrowser1.Document.GetElementById(YOUR_FIELD_ID).GetAttribute("value");	0
5428581	5428433	Dynamic User Controls get and maintain values after postbacks	private void InitControls()\n{\n  var numControlsToBuild = SomeDatabaseCallToGetNumControls();\n  int idCounter = 1;\n  foreach(var controlData in numControlsToBuild)\n  {\n    var control = this.Page.LoadControl("MyControl.ascx") as MyUserControl;\n    control.ID = "MyControl" + idCounter.ToString();\n    idCounter++;\n    UserControlPlaceHolder.Controls.Add(myControl);\n    _MyUserControls.Add(control);\n\n    // probably code load control data into control\n  }\n}	0
3154933	3154526	How to Raise an Event Once I Reach End of Method?	combobox_SelectedIndexChanged(null, null);	0
32492866	29642007	SwiPlCs throws 'Precondition Failed' when trying to get list as result from swi-prolog	vuelos([A|[]],X,Y,B):-vDirecto(A,X,Y,B).\nvuelos([A|[]],X,Y,B):-vEscalaSimple([A|[]],X,Y,B).\nvuelos([A|T],X,Y,B):-vDirecto(A,X,Z,D),vEscalaSimple(T,Z,Y,C),suma(D,C,B),reversa(J,X,Z),X\=Y,not(member(A,T)),not(member(J,T)).	0
23697859	23696535	EF needs Update DB every time I debug my project	Database.SetInitializer<ProjectServiceDBContext>(null);	0
8491588	8491483	C# ListView index and column to string	int i = 0;\nwhile (i < listView1.Items.Count)\n{\n    if (listView.Items[i].Checked)\n    {\n        string sql = "uscolumn = '" + listView1.Items[i].SubItems[0].Text + "' and ukcolumn = '" + listView1.Items[i].SubItems[1].Text + "'";                 \n        listView.Items.RemoveAt(i);\n    }\n    else\n    {\n        i++;\n    }\n}	0
17341562	17341532	How to set timeout feature for FileSystemWatcher?	A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor and the time (in milliseconds) to wait before timing out.	0
23680375	23676324	Running a Batch (which run an exe) from ASP .NET	public void Page_Load(Object s, EventArgs e)\n{\n    if(impersonateValidUser("username", "domain", "password"))\n    {\n        //Insert your code that runs under the security context of a specific user here.\n        undoImpersonation();\n    }\n    else\n    {\n        //Your impersonation failed. Therefore, include a fail-safe mechanism here.\n    }\n}	0
25528596	25528029	Reading the file one row in advance	var dataLines = File.ReadLines(@"C:\Temp\SplitFileTest\BigFile.txt")\n    .SkipWhile(l => String.IsNullOrWhiteSpace(l)).Skip(1); //skip header\nvar dataIdGroups = dataLines\n    .Select(l => new { Line = l.Trim(), Fields = l.Trim().Split('|') })\n    .Where(x => x.Fields.Length == 4)\n    .Select(x => new\n    {\n        Name = x.Fields[0],\n        ID = x.Fields[1],\n        Phone = x.Fields[2],\n        Address = x.Fields[3],\n        Line = x.Line\n    })\n    .GroupBy(x => x.ID);\n\nvar allFileLines = new List<List<string>>();\nforeach (var userGroup in dataIdGroups)\n{\n    if (userGroup.Count() > 50 || allFileLines.Count == 0 || allFileLines.Last().Count + userGroup.Count() > 50)\n        allFileLines.Add(userGroup.Select(x => x.Line).ToList());\n    else\n        allFileLines.Last().AddRange(userGroup.Select(x => x.Line));\n}\n\n\nfor(int i = 0; i < allFileLines.Count; i++)\n    File.WriteAllLines(\n        string.Format(@"C:\Temp\SplitFileTest\UserFile_{0}.txt", i + 1), \n        allFileLines[i]);	0
13965191	13964803	Mistake for In-App Purchase Tutorial at Microsoft Website	protected override async void OnLaunched(LaunchActivatedEventArgs args)\n    {\n        Frame rootFrame = Window.Current.Content as Frame;\n\n        // Do not repeat app initialization when the Window already has content,\n        // just ensure that the window is active\n\n        if (rootFrame == null)\n        {\n#if DEBUG\n            licenseInformation = CurrentAppSimulator.LicenseInformation;\n#else\n            licenseInformation = CurrentApp.LicenseInformation;\n#endif\n\n            // other init here...\n        }\n    }	0
32063325	32062898	How to convert from DbGeometry to String using Automapper?	AutoMapper.Mapper.Initialize(cfg =>\n{\n    cfg.CreateMap<Tile, TileDto>()\n       .ForMember(tileDto => tileDto.Geometry,\n                  map => map.MapFrom(tile => tile.Geometry.AsText()));\n\n    cfg.CreateMap<TileDto, Tile>()\n       .ForMember(tile => tile.Geometry,\n                  map => map.MapFrom(tileDto => DbGeometry.FromText(tileDto.Geometry)));\n\n    cfg.CreateMap<Tile, TileDto>();\n    cfg.CreateMap<TileDto, Tile>();\n});	0
2918634	2901981	How to compare dictonary key with xml attribute value in xml using LINQ in c #?	Dictonary<string,string> dict2=new Dictonary<string,string>()\n    XDocument XDOC=XDocument.Load("sample.xml");\n    dict2=(from key in dictSample from element in XDOC.Descendants("element") where\n           key.Value == element.Attribute("id").Value select new { ID = \n           element.Attribute("id").Value,Val = element.Attribute\n           ("value").Value}).ToDictionary(X => X.ID, X => X.Val);	0
2822513	2822326	A DLL with WinForms that can be launched from A main app	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Windows.Forms;\nusing ****your DLL namespace here****\nnamespace WindowsFormsApplication2\n{\n    static class Program\n    {\n        /// <summary>\n        /// The main entry point for the application.\n        /// </summary>\n        [STAThread]\n        static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.SetCompatibleTextRenderingDefault(false);\n            Application.Run(new [****your startup form (from the DLL) here****]);\n        }\n    }\n}	0
24598877	24597541	Entity framework issue with join two objects	var data = from c in context.Cities\n           join t in context.CityTranslations\n               on c.CityId equals t.CityId\n           where t.LanguageCode == language	0
20814825	20814676	Sort a list by multiple fields	bananas.Sort(\n    delegate(Banana b1, Banana b2)\n    {          \n        int res = b1.Color.CompareTo(b2.Color);\n        return res != 0 ? res : b1.Position.CompareTo(b2.Position);\n    });	0
2256186	2240320	In Emacs, how can I use imenu more sensibly with C#?	namespace foo {\n   class bar {\n       int somemethod();\n   }\n}	0
25268294	25158304	Registry Watcher C# implement RegistryKeyChangeEvent	ManagementScope Scope = new ManagementScope("\\\\.\\root\\default");\nEventQuery Query = new EventQuery(@"SELECT * FROM RegistryKeyChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE' AND KeyPath='SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall'");\nManagementEventWatcher watcher = new ManagementEventWatcher(Scope, Query);\nm_watcher.EventArrived += new EventArrivedEventHandler(RegistryWatcher_EventArrived);\nm_watcher.Start();	0
12919051	12919005	Splitting string variable on a space or 2 spaces in C#	var allId = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);	0
3199548	3197439	Return same instance for multiple interfaces	builder.RegisterType<StandardConsole>()\n   .As<IStartable>()\n   .As<IConsumer<ConsoleCommand>>()\n   .SingleInstance();	0
14741215	14739971	How to match default TabPage styles with programaticlaly created tab pages?	tPage.UseVisualStyleBackColor = true;	0
23041887	23032180	How do I suppress CA1725?	[module: SuppressMessage("Microsoft.Naming",\n                         "CA1725",\n                         MessageId = "0#",\n                         Scope = "member",\n                         Target = "MyNamespace.MyBackgroundWorker.MyNamespace.IBackgroundWorker.set_WorkerSupportsCancellation(System.Boolean):System.Void")]	0
34235744	34235601	C# how to get a return in a void event args?	private static bool levelup = false;\nprivate static void Obj_AI_Base_OnLevelUp(Obj_AI_Base sender, EventArgs args)\n{\n    Game.PrintChat("you leveled up!");\n    levelup = true;\n}\n\npublic bool results()\n{\n    return levelup;            \n}	0
20501319	20501193	Reading data off SQL Rows sequentially	SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);\n      conn.Open();\n      SqlCommand comm = new SqlCommand("SELECT * FROM Accounts WHERE ID = @ID AND Open = 1", conn);\n      comm.Parameters.AddWithValue("@ID", Session["ID"]);\n      using(var dataReader = comm.ExecuteReader())\n      {\n          if(dataReader.HasRows)\n           {\n                while(dataReader.Read())\n                {\n                    var myRowColumn1 = dataReader["NameOfColumnInDataBase"].ToString();\n                 }\n           }\n      }	0
9559873	9559777	Validation on a partial class	public class Customer \n{\n   public void Customer()  //<- You cannot do this, remove the void Customer should only be the constructor\n   { } \n}	0
4541166	4541135	Find the right parameters for an event without using Design Mode in Visual Studio 2010	[SerializableAttribute]\n[ComVisibleAttribute(true)]\npublic delegate void EventHandler(\n    Object sender,\n    EventArgs e\n)	0
24566753	22218159	how to import media library in windows store app?	IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary; \n// to store the library\n\n\nresultsLibrary = await Windows.Storage.KnownFolders.MusicLibrary.GetFilesAsync(CommonFileQuery.OrderByName);\n// this is the list created.\n\n\n//and this is what shows the media library in a list in xaml\n length = resultsLibrary.Count;\n            list.Items.Clear();\n\n\n            for (int j = 0; j < length; j++)\n            {\n                list.Items.Add(resultsLibrary[j].Name);\n            }	0
21676139	21676001	Report progress inside for loop	private void bgworker1_DoWork(object sender, DoWorkEventArgs e)\n{\n    BackgroundWorker worker = sender as BackgroundWorker;\n\n    for (int i = 1; i <= 100; i++)\n    {\n        if (worker.CancellationPending == true)\n        {\n            e.Cancel = true;\n            break;\n        }\n        else\n        {\n            //Insert your logic HERE\n            worker.ReportProgress(i * 1);\n        }\n    }\n}	0
12875725	12874501	Having troubles with a particular Linq-To-Entity expression	context.Classes.Where(C => \n                (context.CDS.Where(CD => CD.sid == "1" && CD.did == "24")\n                .Distinct(CD => CD.CID)).Contains(C.CID))\n                .Select(C => new { \n                                    className = C.className, \n                                    abbreviation = C.abbreviation, \n                                    cid = C.cid \n                                 });	0
12587470	9868929	How to edit a WritableBitmap.BackBuffer in non UI thread?	//Put this code in a method that is called from the background thread\n        long pBackBuffer = 0, backBufferStride = 0;\n        Application.Current.Dispatcher.Invoke(() =>\n        {//lock bitmap in ui thread\n            _bitmap.Lock();\n            pBackBuffer = (long)_bitmap.BackBuffer;//Make pointer available to background thread\n            backBufferStride = Bitmap.BackBufferStride;\n        });\n        //Back to the worker thread\n        unsafe\n        {\n            //Carry out updates to the backbuffer here\n            foreach (var update in updates)\n            {\n                long bufferWithOffset = pBackBuffer + GetBufferOffset(update.X, update.Y, backBufferStride);\n                *((int*)bufferWithOffset) = update.Color;\n            }\n        }\n        Application.Current.Dispatcher.Invoke(() =>\n        {//UI thread does post update operations\n            _bitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, width, height));\n            _bitmap.Unlock();\n        });	0
6270439	6115690	SSRS importer in C# 4.0, move reports from one server to another w/o changing format	// Determine filename without extension (used as name in SSRS)\nFileInfo fileInfo = new FileInfo(FileSystemPath);\nstring fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.FullName);\ntry\n{\n    // Determine filecontents\n    Byte[] fileContents = File.ReadAllBytes(fileInfo.FullName);\n\n    // Publish report\n    rsService.Warning[] warnings = this.rs.CreateReport(fileNameWithoutExtension, this.SSRSFolder, true, fileContents, null);\n\n    if (warnings != null)\n    {\n       foreach (rsService.Warning warning in warnings)\n       {\n          //Log warnings\n       }\n    }\n}\ncatch\n{\n   //handle error\n}	0
5618413	5618390	Efficient way to remove duplicate strings from a string array in C#	string[] a = { "abc", "xyz","abc", "def", "ghi", "asdf", "ghi","xd", "abc" };\nvar b = new HashSet<string>(a);	0
28721660	28717869	Umbraco Omitting Media files from search results	var searchCriteria = searcher.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content, BooleanOperation.Or);	0
34437809	34436265	Restarting App Pool via c# using poweshell script	var serverManager = ServerManager.OpenRemote("000.000.000.000"); // Ip Address of Remote server\n\n            var appPool = serverManager.ApplicationPools["MyAppPool"];\n\n            if (appPool == null) return;\n\n            if (appPool.State == ObjectState.Stopped)\n            {\n                appPool.Start();\n            }\n            else\n            {\n                appPool.Recycle();\n            }	0
6634228	6633566	Rollback a transaction on NHibernate and Enterprise Library	System.Transactions	0
33103010	33102733	How to make matrix from string in c#	string t = "{  { 1, 3, 23 } ,  { 5, 7, 9 } ,  { 44, 2, 3 }  }";\n\nvar cleanedRows = Regex.Split(t, @"}\s*,\s*{")\n                        .Select(r => r.Replace("{", "").Replace("}", "").Trim())\n                        .ToList();\n\nvar matrix = new int[cleanedRows.Count][];\nfor (var i = 0; i < cleanedRows.Count; i++)\n{\n    var data = cleanedRows.ElementAt(i).Split(',');\n    matrix[i] = data.Select(c => int.Parse(c.Trim())).ToArray();\n}	0
10103539	10103220	regex specific tags from text?	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\nvar list = doc.DocumentNode.Descendants("ul")\n    .Select(n => n.Descendants("li").Select(li => new {id=li.Id,text=li.InnerText }).ToList())\n    .ToList();\n\nforeach (var ul in list)\n{\n    foreach(var li in ul)\n    {\n        Console.WriteLine(li.id + " " +  li.text);\n    }\n    Console.WriteLine();\n}	0
4019615	4019520	Is the reflection namespace a building block for writing a quine in C#?	using System;      \nclass Q      \n{   \n    static void Main()    \n    {\n        string s = "using System;class Q{2}static void Main(){2}string s ={1}{0}{1};\n        Console.Write(string.Format(s, s, (char)34, (char)123, (char)125));{3}{3}";             \n        Console.Write(string.Format(s, s, (char)34, (char)123, (char)125));          \n    }   \n}	0
26816361	26813695	Handling asymmetric headers in a web service	enableUnsecuredResponse="true"	0
28691688	28691454	LINQ - looping through rows of 2d array	var count = Enumerable.Range(0, myarr.GetUpperBound(0)+1)\n                      .Count(r => myarr[r,1] == "vpp");	0
18435443	18435343	How to use 'In' SQL keyword in Entity Framework?	var query = from c in db.COMPANY\n            where (from u in db.USER_COMPANY\n                   where u.UserId == UserId\n                   select u.KEY).Contains(c.KEY)\n            orderby c.NAME\n            select c.KEY, c.NAME;	0
16206293	16206149	How to split a string at the last '.' value	string str = "123.1.1.QWE";    \nint index = str.LastIndexOf(".");\nstring[] seqNum = new string[] {str.Substring(0, index), str.Substring(index + 1)};	0
9909544	9909475	Find the count of duplicate items in a C# List	var numberOfTestcasesWithDuplicates = \n    scenarios.GroupBy(x => x.ScenarioID).Count(x => x.Count() > 1);	0
33167293	33167165	C#, parsing data in a separate thread and updating GUI	Thread.Sleep	0
16817664	16817465	How to read a file from nth byte to a string - C#	Encoding encoding = Encoding.ASCII; //? (Encoding.Default)\nusing (var f = File.Open(fileName, FileMode.Open))\n{\n    f.Position = 27;\n    var yourString = new StreamReader(f,encoding).ReadToEnd();\n}	0
21266045	21264581	Parsing Non-Standard XML Data from SQL Server	var doc = new XmlDocument();\n\ndoc.LoadXml(columnValueFromSql);\n\nConsole.WriteLine("XCoord={0}, YCoord={1}",\n    doc.SelectSingleNode("//Attribute[Name='XCoord']/Value").InnerText,\n    doc.SelectSingleNode("//Attribute[Name='YCoord']/Value").InnerText);\n\n/* Outputs:\n\nXCoord=482557.53208923, YCoord=240588.72462463\n\n*/	0
15221591	14813661	How to avoid groupPrincipal.Members.Add throwing a NoMatchingPrincipalException	Domain.DomainControllers	0
2540434	2540402	List of Objects to be used on ascx view with Inherits data already loaded MVC	List<LossCauses> selectProperty = TempData["Select"] as List<LossCauses>;	0
23576195	23555168	Extending IQueryable<T> to add a property	var firstRankResult1 = firstRankResult.Select(r => new\n        {\n            baseType = r,\n            RankId = 1\n        });\n        var secondRankResult1 = secondRankResult.Except(firstRankResult).Select(r => new\n        {\n            baseType = r,\n            RankId = 2\n        });\n\n        var unionedResult = firstRankResult1.Concat(secondRankResult1).OrderBy(o => o.RankId).Select(o => o.baseType);\n        return unionedResult;	0
16214850	16213237	WinForms scrollable control touch behavior	// adapt the gesture registration for this window\nGESTURECONFIG[] gestureConfig = new[]\n{\n    // register for zoom gesture\n    new GESTURECONFIG { dwID = GID_ZOOM, dwWant = GC_ZOOM, dwBlock = 0 },\n    // register for pan gestures but ignore single finger (only use two-finger-pan to scroll)\n    new GESTURECONFIG { dwID = GID_PAN, dwWant = GC_PAN, dwBlock = GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY | GC_PAN_WITH_SINGLE_FINGER_VERTICALLY }\n};\nSetGestureConfig(this.Handle, 0, (uint)gestureConfig.Length, gestureConfig, (uint)Marshal.SizeOf(typeof(GESTURECONFIG)));	0
9402719	9402674	Quickly generating random numbers in C#	Random rand0, rand1, rand2;\n\nvoid init()\n{\n      int baseSeed = (int) DateTime.Now.Ticks;\n      rand0 = new Random(baseSeed);\n      rand1 = new Random(baseSeed + 1);\n      rand2 = new Random(baseSeed + 2);\n}	0
16834704	16833704	How to get the files in numeric order from the specified directory in c#?	var vv = new DirectoryInfo(@"C:\Image").GetFileSystemInfos("*.bmp").OrderBy(fs=>int.Parse(fs.Name.Split('_')[1].Substring(0, fs.Name.Split('_')[1].Length - fs.Extension.Length)));	0
10806339	10804822	insert at bookmark	//BOOK MARK FOR START OF SELECTION\n\nObject oBookmarkStart = "BookMark__Start";\n\nObject oRngoBookMarkStart = oWordDoc.Bookmarks.get_Item(ref oBookmarkDesignInfoStart).Range.Start;\n\n\n\n//BOOK MARK FOR END OF SELECTION\n\nObject oBookmarkEnd = "BookMark__End";\n\nObject oRngoBookMarkEnd = oWordDoc.Bookmarks.get_Item(ref oBookmarkDesignInfoEnd).Range.Start;\n\n\n\n//SETTING THE RANGE ON THE BOOKMARK BETWEEN TWO BOOKMARKS\n\nWord.Range rngBKMarkSelection = oWordDoc.Range(ref oRngoBookMarkStart, ref oRngoBookMarkEnd);\n\n\n\n//SELECTING THE TEXT\n\nrngBKMarkSelection.Select();\nrngBKMarkSelection.Delete(ref oMissing, ref oMissing);	0
2012228	2012195	How to open webpage in WebBrowser control in a loop	List<string> hyperlinks = new List<string>();\n\nforeach (string str in hyperlinks)\n{\n\nmybrowser.Navigate(str);\n\n}	0
24567312	24553008	Converting a fisheye image to landscape and diving it into four parts using c#	while (run<4)\n        {\n            Bitmap bmDestination = new Bitmap(l, l);\n\n            for (i = 0; i < bmDestination.Height; ++i)\n            {\n                radius = (double)(l - i);\n\n                for (j = run * l, k = 0; j < lastWidth * l||k < bmDestination.Width; ++j, ++k)\n                {\n                    // theta = 2.0 * Math.PI * (double)(4.0 * l - j) / (double)(4.0 * l);\n                    theta = 2.0 * Math.PI * (double)(-j) / (double)(4.0 * l);\n\n                    fTrueX = radius * Math.Cos(theta);\n                    fTrueY = radius * Math.Sin(theta);\n\n                    // "normal" mode\n                    x = (int)(Math.Round(fTrueX)) + l;\n                    y = l - (int)(Math.Round(fTrueY));\n                    // check bounds\n                    if (x >= 0 && x < iSourceWidth && y >= 0 && y < iSourceWidth)\n                    {\n                        bmDestination.SetPixel(k, i, bm.GetPixel(x, y));\n                    }\n                }	0
9137397	9136931	Getting data from listboxitem on tap	var selected = ((ListBox) sender).SelectedItem as MyCustomControl;	0
24321827	24321318	Singleton execution for multiple application requests with persession WCF service object	public static Class1 Current\n{\n    get\n    {\n        if (HttpContext.Current != null) /* ASP.NET / ASMX / ASHX */\n        {\n            if (HttpContext.Current.Session["Class1"] == null)\n                HttpContext.Current.Session["Class1"] = new Class1();\n\n            return (Class1)HttpContext.Current.Session["Class1"];\n        }\n        else if (OperationContext.Current != null) /* WCF */\n        {\n            if (WcfInstanceContext.Current["Class1"] == null)\n                WcfInstanceContext.Current["Class1"] = new Class1();\n\n            return (Class1)WcfInstanceContext.Current["Class1"];\n        }\n        else /* WPF / WF / Single instance applications */\n        {\n            if (Class1.current == null)\n                Class1.current = new Class1();\n\n            return Class1.current;\n        }\n    }\n}	0
813741	373230	Check for column name in a SqlDataReader object	public static class DataRecordExtensions\n{\n    public static bool HasColumn(this IDataRecord dr, string columnName)\n    {\n        for (int i=0; i < dr.FieldCount; i++)\n        {\n            if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))\n                return true;\n        }\n        return false;\n    }\n}	0
12180009	12179979	How do I get the current Date in C#	DateTime.Now	0
1412320	1412008	Join DataTable with List<SomeObject>	List<ListItem> listItems = //whatever\nDataTable dtItems = //whatever\n\nIEnumerable<DataRow> matchingRows = listItems\n    .Join(dtItems.AsEnumerable(),\n    listItem => listItem.MembershipID,\n    row => row.Field<int>("MembershipID"),\n    (r,li) => new { DifferentId = li.DifferentId, Row = r })\n    .Where( ji => ji.DifferentID == "B")\n    .Select( ji => ji.Row);	0
25892208	25521681	Calling a REST service keeps failing (with RESTSharp)	_restClient = new RestClient();\n_restClient.BaseUrl = url;\n\nvar request = new RestRequest(_baseServiceUrl + GetTokenUrl, Method.POST);\nrequest.RequestFormat = DataFormat.Json;\nrequest.AddHeader("Authorization", "Basic " + baseAuth); \nrequest.AddBody(new {\n    root = new { \n        clientIdentifier = "Outlook", \n        clientId = "52c600f6-262c-4fca-a4bc-e0e322e0571e" \n    }\n});	0
8996718	8995156	server side validation in asp.net application not working	protected void Button1_Click(object sender, EventArgs e)\n{\n    validation();\n}\n\nprivate void validation() \n{ \n    Alert("Invalid Name"); \n} \n\n\n   // Alert mesage \npublic void Alert(string msg) \n{ \n    ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('" + msg + "');</script>"); \n}	0
11063168	11062945	How do I control the position of ToolTipText for a ToolStripStatusLabel	ToolTip tt = new ToolTip();\n\npublic Form1() {\n  InitializeComponent();\n}\n\nprivate void toolStripStatusLabel1_MouseHover(object sender, EventArgs e) {\n  tt.Show("This is my tool tip", \n          statusStrip1,\n          new Point(toolStripStatusLabel1.Bounds.Right, \n                    toolStripStatusLabel1.Bounds.Top - 10));\n}\n\nprivate void toolStripStatusLabel1_MouseLeave(object sender, EventArgs e) {\n  tt.Hide(statusStrip1);\n}	0
2437655	2258413	Open C: Directly with `FileStream` without `CreateFile` API	new FileStream(@"C:\$Volume", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);	0
7226707	7226683	How to register an event handler in C# to a notification in Oracle	dbms_alert.signal	0
32359325	32359123	Separating data within a foreach datarow	foreach (string emailAddy in userEmailList.Keys)\n    {\n        StringBuilder sbDue = new StringBuilder();\n        StringBuilder sbNotDue = new StringBuilder();\n        sbDue.Append("<html><head></head><body>");\n        sbDue.Append("<h2>Tasks Due</h2><ul>");\n        foreach (DataRow row in userEmailList[emailAddy])\n        {\n            if (!String.IsNullOrEmpty(row["dueDate"].ToString()))\n            {\n                dueDate = Convert.ToDateTime(row["dueDate"]).ToShortDateString();\n                sbDue.AppendFormat("<li><strong>{0}</strong> - {1}</li>", dueDate, row["details"].ToString());\n            }\n            else\n                 sbNotDue.AppendFormat("<li>{0}</li>", row["details"].ToString());\n        }\n        if(sbNotDue.Length > 0)\n        {\n           sbNotDue.Insert("<h2>No Due Date</h2><ul>");\n           sbDue.Append(sbNotDue.ToString());\n        } \n\n        sbDue.Append("</ul></body><html>");\n    }	0
2247568	2247553	How to pass variable of type "Type" to generic parameter	var method =\n    typeof(MetaDataUtil)\n    .GetMethod("GetColumnasGrid")\n    .MakeGenericMethod(new [] { type })\n    .Invoke(null, null);	0
9215757	9215460	Displaying html links in a different order on page load	1. Create the .txt file\n2. Make note of the file location.\n3. Save the file with the links in them\n4. use this code in your project to load the links \n\nList<string> strUrlLinks = new List<string>(File.ReadAllLines(FilePath + FileName.txt));	0
21546437	21546257	Sorting all the XmlNode in XmlDocument	var xDoc = XDocument.Load("path");\nvar documents = xDoc.Descendants("document").Where(x => (string)x.Attribute("name") != "Page1")\n              .OrderBy(x => (int)(x.Elements("attribute").First().Attribute("value")))\n              .ToList();\n\nvar data = xDoc.Descendants("data").First();\ndata.Remove();\nvar document = xDoc.Descendants("document").First(x => (string)x.Attribute("name") == "Page1");\ndocument.Add(new XElement("data", documents));\nxDoc.Save("path");	0
23609657	23605903	How to bind and add data in my datagrid from code behind?	var myDataObject = ... // VM possibly\n  var myBinding = new Binding("FirstName");\n  myBinding.Source = myDataObject;\n  myTextBlock.SetBinding(TextBlock.TextProperty, myBinding);	0
5382349	5382330	Divide List in Equal Parts	Parallel.ForEach()	0
18759581	18759439	How to return JSON not associative array	List<object[]> entries;\nusing (IDbConnection db = Connection.Instance()) {\n  db.Open();\n  entries = db.Query<Response.MapEntries>(query.ToString(), parameters)\n    .Select(e => new object[] { e.Id, e.Type_id, e.Latitude, e.Longitude })\n    .ToList();\n}\n\nreturn entries;	0
1118020	1117083	Lucene AddIndexes (merge) - how to avoid duplicates?	mark the indexes by I1..Im.\nfor i in 1..m, let Ci = all the indexes but Ii\n  for all the documents Dj in Ii,\n  let cur_term = "id:<Dj's id>"\n  for Ik in Ci\n    Ik.deleteDocuments(cur_term)\nmerge all indexes	0
24143640	24142982	IndexOf can't find last element in a List	[Test, Explicit]\npublic void Test()\n{\n  List<Rule> rules = new List<Rule>();\n  Rule n = new Rule();\n  rules.Add(n);\n  Assert.AreEqual(n , rules.Last());\n  Assert.AreEqual(0, rules.IndexOf(n));\n}	0
8499583	8499528	Audio filename doesnt take escape sequence character	... set FileName='" + newfileName.Replace("'", "''") + "'??...	0
28901176	28895466	How to change default naming convention in Entity Framework CodeFirst?	modelBuilder.Conventions.AddBefore<System.Data.Entity.ModelConfiguration.Conven??tions.ForeignKeyIndexConvention>(new ForeignKeyNamingConvention());	0
19777269	19755201	C# Get Speech From Within Speech Marks	Regex SpeechMatch = new Regex("\".+?\"");	0
7811890	7811586	Property name as variable	static void Main()\n{\n    // Demo data\n    myClass[] myPa = new myClass[2];\n    myPa[0] = new myClass();\n    myPa[0].S = "1";\n    myPa[0].I = 0;\n    myPa[1] = new myClass();\n    myPa[1].S = "12";\n    myPa[1].I = 1;\n\n    PrintMaxLengthsOfStringProperties(myPa);\n}\n\npublic static void PrintMaxLengthsOfStringProperties<T>(IEnumerable<T> items)\n{\n    var t = typeof(T);\n    t.GetProperties().Where(p => p.PropertyType == typeof(string)) // TODO: Add other filters\n                        .SelectMany(p => items.Select(o => (string)p.GetValue(o, null)).Select(v => new { Property = p, Value = v }))\n                        .GroupBy(u => u.Property)\n                        .Select(gu => new { Property = gu.Key, MaxLength = gu.Max(u => u.Value != null ? u.Value.Length : 0) })\n                        .ToList()\n                        .ForEach(u2 => Console.WriteLine("Property: {0}, Biggest Size: {1}", u2.Property.Name, u2.MaxLength))\n                        ;\n}	0
26041661	26041358	Map multiple columns to single property with Dapper	public class MyData\n{\n    public int? Mo { get; set; }\n    public int? Lines { get; set; }\n    public decimal Balance { get; set; }\n\n    public int Term\n    {\n        get\n        {\n            if (Mo == null && Lines != null)\n            {\n                return Lines.Value;\n            }\n            if (Mo != null && Lines == null)\n            {\n                return Mo.Value;\n            }\n\n            return default(int);\n        }\n    }\n}	0
2707451	2707447	How to expand environment variable %CommonProgramFiles%\system\ in .NET	Environment.ExpandEnvironmentVariables	0
1276361	1276329	DataGridView Control with Grouping Capabilities	gridControl1.DataSource = myDataTable;	0
33044587	33043999	Slow EF query grouping data by Month/Year	var monthlySales = db.Orders\n                 .GroupBy(c => new { Year = c.CreateDateTime.Year, Month = c.CreateDateTime.Month })\n                 .Select(c => new\n                 {\n                     Month = c.Key.Month,\n                     Year = c.Key.Year,\n                     Total = c.Sum(d => d.Total)\n                 })\n                 .OrderByDescending(a => a.Year)\n                 .ThenByDescending(a => a.Month)\n                 .ToList();	0
23711465	23505772	How do I can set a fixed play area in xaml monogame?	public override Texture2D Draw(SpriteBatch spriteBatch)\n    {\n        spriteBatch.GraphicsDevice.SetRenderTarget(gameRenderTarget);\n        spriteBatch.Begin(SpriteSortMode.FrontToBack, null);\n        sky.Draw(spriteBatch);\n        ground.Draw(spriteBatch);\n        background.Draw(spriteBatch);\n        player.Draw(spriteBatch);\n        spriteBatch.End();\n\n        return (Texture2D)finalRenderTarget;\n    }	0
1426404	1426345	Form1 Autoscroll = Verticle Scroll	Form.HorizontalScroll.Enabled = false;	0
30871015	30870952	Hyper-V Get-VM in powershell via asp.net c#	foreach (PSObject vm in results)\n    {       \n           builder.Append(vm.Members["Name"].Value + "\r\n");\n    }	0
30315747	30314888	Shared a ko.computed between two ViewModels Knockoutjs	function BaseVM(){\n    var self = this;\n    self.someValue = ko.observable();\n    self.grandTotal = ko.computed(function () {\n       return self.someValue()+1; \n    });\n}\n\nfunction Vm1(initValue){\n    var self = this;\n    self.someValue(initValue);\n}\n\nVm1.prototype = new BaseVM();\nVm1.prototype.constructor=Vm1;\n\n\n\nfunction Vm2(){\n    var self = this;\n    self.someValue(13); \n}\n\nVm2.prototype = new BaseVM();\nVm2.prototype.constructor=Vm2;\n\n\nko.applyBindings(new Vm1(4),document.getElementById("View1"));\nko.applyBindings(new Vm2(),document.getElementById("View2"));	0
28917193	28915091	Change Image Url at button click	protected void btnUpload_Click(object sender, EventArgs e)\n{\n    // Do your upload stuff here...\n    imgLogo.ImageUrl = "~/images/myimage.png?" + DateTime.Now;\n }	0
26471292	26468710	Use Table Valued Parameter (TVP) instead of 'where in'	// 1. declare the custom data type\n// this is just to make it re-runnable; normally you only do this once\ntry { connection.Execute("drop type MyIdList"); } catch { }\nconnection.Execute("create type MyIdList as table(id int);");\n\n// 2. prepare the data; if this isn't a sproc, also set the type name\nDataTable ids = new DataTable {\n    Columns = {{"id", typeof(int)}},\n    Rows = {{1},{3},{5}}\n};\nids.SetTypeName("MyIdList");\n\n// 3. run the query, referencing the TVP (note @tmp represents the db data)\nint sum = connection.Query<int>(@"\n-- spoof some data\ndeclare @tmp table(id int not null);\ninsert @tmp (id) values(1), (2), (3), (4), (5), (6), (7);\n-- the actual query\nselect * from @tmp t inner join @ids i on i.id = t.id", new { ids }).Sum();\nsum.IsEqualTo(9); // just checks the result	0
23312940	23312797	SQL how to identify first time and last time from a day timestamp records	-- Helps creating entries blocks\nDECLARE @maxHoursBetweenEntries int = 4;\n\nCASE\n    WHEN (\n        SELECT MIN(timestamp)\n        FROM timesheet_import_temp tsi1\n        WHERE \n            rfidcard = tsi.rfidcard\n            AND sensortype = 0\n            AND ISNULL(DATEDIFF(\n              hour,\n              (\n                  SELECT MAX(timestamp)\n                  FROM timesheet_import_temp\n                  WHERE\n                      AND rficard = tsi1.rficard\n                      AND timestamp < tsi1.timestamp\n                      AND sensortype = 1\n              ),\n              timestamp\n            ), maxHoursBetweenEntries) >= @maxHoursBetweenEntries\n    ) = tsi.timestamp THEN 1\n    ...\nEND	0
8763266	8700432	asp.net dynamically add GridViewRow	protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) \n{ \n    GridViewRow row = new GridViewRow(e.Row.RowIndex+1, -1, DataControlRowType.DataRow, DataControlRowState.Insert); \n    TableCell cell = new TableCell();\n    cell.ColumnSpan = some_span;\n    cell.HorizontalAlign = HorizontalAlign.Left;\n\n    Control c = new Control(); // some control\n    cell.Controls.Add(c);\n    row.Cells.Add(cell);\n\n    ((GridView)sender).Controls[0].Controls.AddAt(some_index, row);\n}	0
26448962	26448914	add multiple datatype using collection in c#	List<Bike> myList = new List<Bike>();\nBike b = new Bike();\nHonda h = new Honda();\nHero r = new Hero();\nmyList.Add(b);\nmyList.Add(h);\nmyList.Add(r);\n\nforeach(var x in myList)\n    Console.WriteLine(x.GetBikedetails());	0
6303534	6303514	How can I call a control event in my code?	btnSubmitTxn_Click(new object(), new EventArgs())	0
2254823	2254772	C#, parsing HTML page, using HTML Agility Pack	List facts = new List();\nforeach (HtmlNode li in doc.DocumentNode.SelectNodes("//div[@id='res']/li")) {\n    facts.Add(li.InnerText);\n}	0
13666424	13666399	Multiple Boxs C#	int XCoordinate = 10;\nint YCoordinate = 5;\nforeach (Image ile in  retrurnImagesInList())\n{\n    try\n    {   \n        PictureBox imageControl = new PictureBox();\n        imageControl.Height = 100;\n        imageControl.Width = 100;\n        XCoordinate += imageControl.Width+2;\n        if(XCoordinate  > this.Width - imageControl.Width)\n        {\n            YCoordinate += imageControl.Height + 2;\n            XCoordinate = 10;\n        }\n        imageControl.Visible = true;\n        imageControl.Location = new Point(XCoordinate, YCoordinate);\n        Controls.Add(imageControl);\n        imageControl.Image = file;\n    }\n    catch (Exception ex)\n    {\n        MessageBox.Show("Error: " + ex.Message);\n    }\n}	0
8896675	8896573	Accessing/Changing UI Element Properties from a different thread	this.Dispatcher.Invoke(new Action<object>((context) => \n                {\n                    this.DataContext = context; // your implementation goes here\n                }), \n                new object[1] \n                { \n                    "you object" // the object(s) you'd like to pass in\n                });	0
22457209	22457016	Increment through a list on a button list	int lastStep = 0;\n\nif(Input.GetKeyDown(KeyCode.O))\n{\n    claddingMaterial.color = claddingColor[lastStep++];\n    if (lastStep == claddingColor.Count)\n        lastStep = 0;\n}	0
33917153	33764125	Getting "A From phone number is required" in JSON call to Twilio	_client.PostAsync(_url, new FormUrlEncodedContent(new Dictionary<string, string>(){\n { "To", "0123456789" }, \n { "From", "9876543210" }, \n { "Body", "Hi" } }));	0
27398394	27306205	Connecting to MySQL in Windows Phone 8.1	Local IIS	0
28031878	28030297	When using EF Fluent API to map my entities relationships, do I need to map on both entities involved?	.Entity<Organization>().HasRequired(o => o.Owner).WithMany(u => u.OrganizationsOwned)	0
19086328	19086239	How to retrieve an image using web service to aspx website C#?	public class ImageHandler : IHttpHandler \n{ \n  public bool IsReusable { get { return true; } } \n\n  public void ProcessRequest(HttpContext ctx) \n  { \n    var myImage = GetImageSomeHow();\n    ctx.Response.ContentType = "image/png"; \n    ctx.Response.OutputStream.Write(myImage); \n  } \n}	0
3008417	2905342	How can I internationalize strings representing C# enum values?	public static string getEnumResourceString(Enum value)\n    {\n        System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());\n        EnumResourceAttribute attr = (EnumResourceAttribute)System.Attribute.GetCustomAttribute(fi, typeof(EnumResourceAttribute));\n        return (string)HttpContext.GetGlobalResourceObject(attr.BaseName, attr.Key);\n    }	0
6020856	6020720	Facebook Like button, can it be made read only?	{\n   "id": "141265189223470",\n   "name": "The Huffington Post - Breaking News and Opinion",\n   "picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/188056_141265189223470_1131566_s.jpg",\n   "link": "http://www.huffingtonpost.com/",\n   "category": "Personal blog",\n   "likes": 15,\n   "website": "http://www.huffingtonpost.com/",\n   "description": "Breaking News and Opinion"\n}	0
7919897	7919797	Refactoring Many Methods into One	[WebMethod(EnableSession = true)]\npublic string ReadUserAdditional()\n{\n    return GetUserInfo(new [] \n    {\n        new FieldInfo {Name = "Image", u => u.Image},\n        new FieldInfo {Name = "Biography", u => u.Biography} \n    });\n}\n\nprivate string GetUserInfo(FieldInfo[] infos) \n{\n    EUser user = (EUser)Session["user"];\n\n    var dict = new Dictionary<string, object>{ { "result", true } };\n    foreach(var info in infos) \n    {\n        dictionary.Add(info.Name, info.Accessor(user));\n    }\n\n    return new JavaScriptSerializer().Serialize(dict );\n}\n\npublic class FieldInfo \n{\n    public Func<EUser, object> Accessor { get; set; }\n    public string Name { get; set;}\n}	0
22636485	22636354	Change scrollviewer margin on button click c#	YourScroller.Margin = new Thickness(0,0,0,90);	0
26341172	26340931	Finding Index of in combination with RegEx	foreach (Match match in Regex.Matches("  {AAA(1)}  {XXX(2)} ", @"\{[A-Z]+\("))\n{\n   if (match.Success)\n      int pos = match.Index;	0
12881309	12879539	How to Remove FILE LOCKS? C#	public static Bitmap LoadBitmapNolock(string path) {\n    using (var img = Image.FromFile(path)) {\n        return new Bitmap(img);\n    }\n}	0
16599736	16599675	how to catch exception for invalid data entry?	if (String.IsNullOrEmpty(fName)) {\n  // handle empty string input\n}\n\nif (ContainsNumbers(fName)) {\n  // handle invalid input\n}\n\nprivate bool ContainsNumbers(string str) {\n  ...\n}	0
5059235	5059072	formatting html in c#	string ReplaceNewLinesWithBrIfNotInsideDiv(string input) {\n\n        int divNestingLevel = 0;\n        StringBuilder output = new StringBuilder();\n        StringComparison comp = StringComparison.InvariantCultureIgnoreCase;\n\n        for (int i = 0; i < input.Length; i++) {\n            if (input[i] == '<') {\n                if (i < (input.Length - 3) && input.Substring(i, 4).Equals("<div", comp)){\n                    divNestingLevel++;\n                } else if (divNestingLevel != 0 && i < (input.Length - 5) && input.Substring(i, 6).Equals("</div>", comp)) {\n                    divNestingLevel--;\n                }\n            }\n\n            if (input[i] == '\n' && divNestingLevel == 0) {\n                output.Append("<br/>");\n            } else {\n                output.Append(input[i]);\n            }\n        }\n\n        return output.ToString();\n    }	0
18987170	18986927	How to use automapper from string to List of Strings	Mapper.CreateMap<data,myFooList>()\n    .ForMember(d=>d.mListOfStrings, s=>s.MapFrom(s=>s.Data.Split()));	0
8671875	8670231	How to add column to .DBF file?	comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";	0
993048	992997	IPrincipal from WCF request	ServiceSecurityContext current = ServiceSecurityContext.Current;\n\nif (!current.IsAnonymous && current.WindowsIdentity != null)\n{\n    string userName = current.WindowsIdentity.Name;\n}	0
19447328	19443818	How to filter stored procedure result using linq	struct DBRecord\n{\npublic string id\npublic string name {get;set;}\npublic string address {get;set;}\npublic string type {get;set;}\n}\n\n\n//Selection:\n\nList<DBRecord> aList = typeList.FindAll(p => ((DBRecord)p).type == "A");\n\nList<DBRecord> bList = typeList.FindAll(p => ((DBRecord)p).type == "B");	0
12106602	12106522	Cannot convert from Decimal to Int32	property.SetValue(Objects[0],Decimal.ToInt32(Convert.ToDecimal(oValue)) , null);	0
6403092	6402975	How to use the read/writeable local XML settings?	public class Settings\n{\n    public string Setting1 { get; set; }\n    public int Setting2 { get; set; }\n}\n\nstatic void SaveSettings(Settings settings)\n{\n    var serializer = new XmlSerializer(typeof(Settings));\n    using (var stream = File.OpenWrite(SettingsFilePath))\n    {\n        serializer.Serialize(stream, settings);\n    }\n}\n\nstatic Settings LoadSettings()\n{\n    if (!File.Exists(SettingsFilePath))\n        return new Settings();\n\n    var serializer = new XmlSerializer(typeof(Settings));\n    using (var stream = File.OpenRead(SettingsFilePath))\n    {\n        return (Settings)serializer.Deserialize(stream);\n    }\n}	0
12396099	12396021	updating a data that is bound to a datagrid	public class ViewModel\n{\n    //collection of subviewmodel to bind to datagrid\n}\n\npublic class SubViewModel\n{\n    //Model instance\n    //property to expose db value from model instance\n    //field to store old db value\n}\npublic class Model\n{\n    //db value\n    //db information\n}	0
1545277	1545270	How to determine if a process ID exists	private bool ProcessExists(int id) {\n  return Process.GetProcesses().Any(x => x.Id == id);\n}	0
9062170	9062155	Get N max numbers from a List<int> using lambda expression	var result = numbers.OrderByDescending(n => n).Take(4);	0
14460025	14323332	How do I set a DataSource to a DropDownList?	DataSet ds = SomeMethodToFillTheDataSet()\n\nforeach(DataRow row in ds.tables[0].Rows)\n{\n  ListItem item = new ListItem();\n  item.text = "fieldName";  e.g  Name\n  item.value = "FieldName"; e.g  ID\n  DropDOwnList.Items.Add(item);\n}	0
1822544	1822448	How can i find a control in the footer template of a data repeater	Protected Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound\n    If e.Item.ItemType = ListItemType.Footer Then\n        Dim Lit As Literal = CType(e.Item.FindControl("findme"), Literal)\n    End If\nEnd Sub	0
29274448	29237498	Create Byte[] from DirectoryEntry C#	(byte[])deTempForSID.Properties["objectSid"].Value	0
20914845	20914691	use c++ unsigned int *array in c#	[DllImport("mydll.dll")]\npublic static extern int foobar(\n    IntPtr ptr, //Need more details on this parameter\n    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)] uint[] arr,\n    uint arrSize);	0
23473091	23472966	GPS Coordinates Regex and combine them as a string	string output = string.Join(";", Regex.Matches("GPS: 48.8896 N - 2.37586 W", @"-?\d+\.\d+")\n                                      .OfType<Match>()\n                                      .Select(m => m.Value));	0
11917718	11917647	Data still getting added in spite of TextBox validation	private void button1_Click(object sender, EventArgs e)\n    {\n        if(string.IsNullOrEmpty(textBox1.Text.Trim()))\n        {\n            MessageBox.Show("Null String !!!!!!!!");\n            return;\n        }\n        SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");\n        SqlCommand sql1 = new SqlCommand("INSERT into Book VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + dateTimePicker1.Value.ToShortDateString() + "')", con);\n        con.Open();\n        sql1.ExecuteNonQuery();\n        con.Close();\n        this.bookTableAdapter.Fill(this.booksDataSet.Book);\n        MessageBox.Show("Data Added!");\n        this.Close();\n\n    }	0
1665478	1660932	How do I send formatted text in email using C#?	//The text will be loaded here\n            string s2= textBox6.Text;     \n\n            //All blank spaces would be replaced for html subsitute of blank space(&nbsp;) \n            s2 = s2.Replace(" ", "&nbsp;");          \n\n            //Carriage return & newline replaced to <br/>\n            s2=s2.Replace("\r\n", "<br/>");                \n            string Str = "<html>";\n            Str += "<head>";\n            Str += "<title></title>";\n            Str += "</head>";\n            Str += "<body>";\n            Str += "<table border=0 width=95% cellpadding=0 cellspacing=0>";\n            Str += "<tr>";\n            Str += "<td>" + s2 + "</td>";\n            Str += "</tr>";\n            Str += "</table>";\n            Str += "</body>";\n            Str += "</html>";                        \n            mail.Subject = textBox4.Text;                          \n            mail.Body = Str;	0
13175893	13175484	Need help on session variable	public string GetUserID(string EmailAdd, string Password)\n    {\n        SqlConnection myConnection = new SqlConnection(@"user id=BankUser;password=Computer1;server=(local)\sql2008;database=BillionBank;");\n        myConnection.Open();\n        SqlCommand myCommand = new SqlCommand("SELECT * FROM [BillionBank].[dbo].[tblCustomerProfile] WHERE EmailAdd='" + EmailAdd + "' AND Password ='" + Password + "'", myConnection);\n        SqlDataReader myreader;\n        string result = "";\n\n        myreader = myCommand.ExecuteReader();\n        if (myreader.Read())\n        {\n            result = Convert.ToString(myreader["UserID"]);\n        }\n\n        return result;\n\n    }\n\nprotected void btnLogin_Click(object sender, EventArgs e)\n{\n    Session["UserID"] = GetUserID(YOUR_EMAILID, YOUR_PASSWORD);\n}	0
4137440	4137404	Find and replace using regular expressions	// Assuming 'input' is the original string, and that 'replacementstring1'\n// and 'replacementstring2' contain the new info you want to replace\n// the matching portions.\n\ninput = Regex.Replace(input, "#TEST1#AT#", replacementstring2); // This search pattern wholly\n                                                                // contains the next one, so\n                                                                // do this one first.\n\ninput = Regex.Replace(input, "#TEST1#", replacementstring1);	0
2191531	2188652	MVC2 IModelBinder and parsing a string to an object - How do I do it?	bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue	0
18539280	18539057	ApiController Action Failing to parse array from querystring	public KeysModel Get([FromUri]int[] ids){...}	0
22282290	22282209	joins in Linq using lists<strings> with no id to index from	var gridview = a.Zip(num, (A,n)=>new{TName = A,RName = n}).ToList();	0
17952998	17952900	How can I assign enum values to a listbox in .NET 1.1 on the Compact Framework?	Type type = typeof(EnumType);\nforeach (FieldInfo field in type.GetFields(BindingFlags.Static |\n                                           BindingFlags.Public))\n{\n    // Fortunately unboxing to the enum's underlying field type works\n    int value = (int) field.GetValue(null);\n    ListItem item = new ListItem(field.Name, value.ToString());\n    TheListBox.Items.Add(item);\n}	0
4405929	4404516	C# / WPF: Richtextbox: Find all Images	public static void ResizeRtbImages(RichTextBox rtb)\n    {\n        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                            image.Width = image.ActualWidth + 1;\n                            image.Height = image.ActualHeight + 1;\n                        }\n                    }\n                }\n            }\n        }\n    }	0
13818678	13818558	How to modify / delete keys the AppConfig file	m_Configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n m_Configuration.AppSettings.Settings.Remove(key);\n m_Configuration.AppSettings.Settings.Add(key, value);\n m_Configuration.Save(ConfigurationSaveMode.Modified);	0
9986909	9986871	Didn't pass parameter	Response.Redirect("repStudReport.aspx?Date=" + Date + "&studNam=" + studNam + "&subject=" + subject);	0
2621327	2621303	Is there any way to check for properties of a class for a particular value in c#	var values = from prop in typeof(License).GetProperties()\n             where prop.PropertyType == typeof(bool)\n             select (bool) prop.GetValue(instance, null);\n\nif (!values.Any(x => x))\n{\n    // Nope, everything's false\n}	0
27444909	20328268	ValueInjecter injecting from a method	var sourceProps = source.GetProps();\n    var targetProps = target.GetProps();	0
2456511	2456471	C# + Format TimeSpan	Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);	0
30298069	30297510	Compare Dictionary Key of type string to another string in C#	String headLine = oStreamReader.ReadLine().Trim().Replace("\"", ""); \nString columnNames = headLine.Split(new[] { ';' });\n\n\n\nforeach (string readColumn in columnNames)  {\n\nif (typeNames.Keys.Contains(readColumn, StringComparer.CurrentCultureIgnoreCase)==true)\n    {\n      DataColumn oDataColumn = new DataColumn(readColumn,typeof(System.String));\n      oDataTable.Columns.Add(oDataColumn);\n    }	0
26776285	26775850	Get MAC address of device	ulong input = 254682828386071;\nvar tempMac = input.ToString("X");\n//tempMac is now 'E7A1F7842F17'\n\nvar regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";\nvar replace = "$1:$2:$3:$4:$5:$6";\nvar macAddress = Regex.Replace(tempMac, regex, replace);\n//macAddress is now 'E7:A1:F7:84:2F:17'	0
1336802	1336756	finding and replacing a tree node in C#	private void replaceInTreeView()\n{\n    TreeView myTree = new TreeView();\n    ReplaceTextInAllNodes(myTree.Nodes, "REPLACEME", "WITHME");\n}\n\nprivate void ReplaceTextInAllNodes(TreeNodeCollection treeNodes, string textToReplace, string newText)\n{\n    foreach(TreeNode aNode in treeNodes)\n    {\n        aNode.Text = aNode.Text.Replace(textToReplace, newText);\n\n        if(aNode.ChildNodes.Count > 0)\n            ReplaceTextInAllNodes(aNode.ChildNodes, textToReplace, newText);\n        }\n    }\n}	0
8339407	8329245	Expiring an IE session using WatiN	Browser.Eval(@"document.execCommand(""ClearAuthenticationCache"", false);");	0
17499642	17499586	Write XmlReader XML to immediate window in Visual Studio?	reader.MoveToContent();\nreader.ReadOuterXml();	0
9476680	9473149	Implementing AutoSize in a custom UserControl	public virtual Size GetPreferredSize(Size constrainingSize)\n    {\n      constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize);\n      return this.InternalLayout.GetPreferredSize(constrainingSize - this.Padding.Size) + this.Padding.Size;\n    }	0
29328519	29318842	Drawing 2D polygons in openGL	gl.drawElements(GL.TRIANGLES, triangles.length, GL.UNSIGNED_SHORT, 0);	0
24422386	24422208	want to change window color using XAML RESOURCE FILE	xmlns:local="Yournamespace:YourApplication"\n\n<Style  TargetType="local:MainMenuView">\n     <Setter Property="Background" Value="Green" />\n</Style>	0
1876621	1876589	How to accept ANY delegate as a parameter	bool DoesItThrowException(Action a)\n{\n  try\n  {\n    a();\n    return false;\n  }  \n  catch\n  {\n    return true;\n  }\n}\n\nDoesItThrowException(delegate { desomething(); });\n\n//or\n\nDoesItThrowException(() => desomething());	0
32157841	32157795	How to create a route with dynamic count of parameters	routes.MapRoute(\n            name: "YourRoute",\n            url: "{controller}/{action}/{catalog}/{subcatalog}/{model}",\n            defaults: new { \n               controller = "Home", \n               action = "Index", \n               catalog = UrlParameter.Optional, \n               subcatalog = UrlParameter.Optional, \n               model = UrlParameter.Optional }\n        );	0
14465265	14465187	Get available disk free space for a given path on Windows	[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool GetDiskFreeSpaceEx(string lpDirectoryName,\n   out ulong lpFreeBytesAvailable,\n   out ulong lpTotalNumberOfBytes,\n   out ulong lpTotalNumberOfFreeBytes);\n\nulong FreeBytesAvailable;\nulong TotalNumberOfBytes;\nulong TotalNumberOfFreeBytes;\n\nbool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",\n                                  out FreeBytesAvailable,\n                                  out TotalNumberOfBytes,\n                                  out TotalNumberOfFreeBytes);\nif(!success)\n    throw new System.ComponentModel.Win32Exception();\n\nConsole.WriteLine("Free Bytes Available:      {0,15:D}", FreeBytesAvailable);\nConsole.WriteLine("Total Number Of Bytes:     {0,15:D}", TotalNumberOfBytes);\nConsole.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);	0
19886854	19886667	Add character after each fourth symbol of the string	string bla = "blabllabnsdfsdfsd";\n\nbla = Regex.Replace(bla, ".{4}", "$0-");\nbla = bla.Remove(bla.Length - 1);	0
17342017	17341920	Rotate bunch of points thourgh an origin	public static Point Rotate(Point point, Point pivot, double angleDegree)\n{\n    double angle = angleDegree * Math.PI / 180;\n    double cos = Math.Cos(angle);\n    double sin = Math.Sin(angle);\n    int dx = point.X - pivot.X;\n    int dy = point.Y - pivot.Y;\n    double x = cos * dx - sin * dy + pivot.X;\n    double y = sin * dx + cos * dy + pivot.X;\n\n    Point rotated = new Point((int)Math.Round(x), (int)Math.Round(y));\n    return rotated;\n}\nstatic void Main(string[] args)\n{\n    Console.WriteLine(Rotate(new Point(1, 1), new Point(0, 0), 45));\n}	0
4254191	4253626	How to use .Foreground?	if (((SolidColorBrush)txtMelding.Foreground).Color == Colors.Gray)	0
3349465	3349374	Is it possible to make a DataTable as a AutoCompleteSource in a TextBox? (C#)	DataTable dtPosts = new DataTable();\nusing (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["StackOverflow"].ConnectionString))\n{\n    conn.Open();\n    using (SqlDataAdapter adapt = new SqlDataAdapter("SELECT TOP 100 Id, Title, Body, CreationDate FROM Posts WHERE Title IS NOT NULL ORDER BY Id", conn))\n    {\n        adapt.SelectCommand.CommandTimeout = 120;\n        adapt.Fill(dtPosts);\n    }\n}\n\n//use LINQ method syntax to pull the Title field from a DT into a string array...\nstring[] postSource = dtPosts\n                    .AsEnumerable()\n                    .Select<System.Data.DataRow, String>(x => x.Field<String>("Title"))\n                    .ToArray();\n\nvar source = new AutoCompleteStringCollection();\nsource.AddRange(postSource);\ntextBox1.AutoCompleteCustomSource = source;\ntextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\ntextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;	0
4916399	4916046	SharePoint Web Service: Need to fetch list in a sub-site	ListsService.Url = "http://yourserver/sites/yoursite/_vti_bin/lists.asmx"	0
4856685	4856644	How to call a C# method only if it exists?	dynamic d = 5;\ntry\n{\n    Console.WriteLine(d.FakeMethod(4));\n}\ncatch(RuntimeBinderException)\n{\n    Console.WriteLine("Method doesn't exist");\n}	0
1254691	1254677	Change in AppSettings needs restart my Application how can I avoid?	ConfigurationManager.RefreshSection("appSettings")	0
17971766	17971548	How to get HttpRequestMessage data	[HttpPost]\npublic void Confirmation(HttpRequestMessage request)\n{\n    var content = request.Content;\n    string jsonContent = content.ReadAsStringAsync().Result;\n}	0
1900448	1900390	C# Windows Application Doesnt Show In System Tray Correctly	this.Resize +=new EventHandler(Form1_Resize);\nprivate void Form1_Resize(object sender, EventArgs e)\n{\n    if (this.WindowState == FormWindowState.Minimized)\n    {\n        this.Hide();\n    }\n}	0
14925266	14784241	JSON Cannot Deserialize JSON array into type	JsonConvert.DeserializeObject<BibleGatewayVerses[]>(jsonData);	0
1497091	1386055	Split wmv/wav file in WinForms application	Int32 StartTime = 60 * 1000;\nInt32 EndTime = 120 * 1000;\nString SourceName = "original.mp3";\nString DestinationName = "split.mp3";\nWMEncBasicEdit SplitFile = new WMEncBasicEdit();\nSplitFile.MediaFile = SourceName;\nSplitFile.OutputFile = DestinationName;\nSplitFile.MarkIn = StartTime;\nSplitFile.MarkOut = EndTime;\nSplitFile.Start();	0
1613204	1594970	How do you save a Linq object if you don't have its data context?	internal static T CloneEntity<T>(T originalEntity)\n{\n    Type entityType = typeof(T);\n\n    DataContractSerializer ser =\n        new DataContractSerializer(entityType);\n\n    using (MemoryStream ms = new MemoryStream())\n    {\n        ser.WriteObject(ms, originalEntity);\n        ms.Position = 0;\n        return (T)ser.ReadObject(ms);\n    }\n}	0
27432630	27431723	Binding a ASP.Net Identity object to a Func using ninject	kernel.Bind<UserManager<AppUserModel>>().ToMethod(context => Startup.UserManagerFactory());	0
21080185	21079698	Show sql table data in datagridview with 3 parameters	string query = "select * from Kartice where ID=" + combobox.SelectedItem.ID.ToString() + " AND Datum_Izvedbe BETWEEN @SDate AND @EDate";	0
11447926	11447660	Regex to parse out IP next to a set value	var match = Regex.Match(inputString, \n                    @"X_Value_B:\s*(?<ip>\d+.\d+.\d+.\d+)");\n\nif(match .Success)\n    String strIp = match.Groups["ip"].Value;	0
3539668	3539547	Display datatable in ListView control	listView.ItemsSource = dataTable.DefaultView;	0
5269192	5269145	LINQ to find count of all Datapoints in ASP.NET Chart	var total = Chart1.Series.Sum(s => s.Points.Count);	0
991996	991944	MessageInterceptor doesn't kick in second time with window mobile application	public partial class Form1 : Form\n    {\n\n        protected MessageInterceptor smsInterceptor = null;\n\n        public Form1()\n        {\n            InitializeComponent();\n            debugTxt.Text = "Calling Form cs";\n            //Receiving text message\n            this.smsInterceptor  = new MessageInterceptor(InterceptionAction.NotifyandDelete);\n            this.smsInterceptor.MessageReceived += this.SmsInterceptor_MessageReceived;                  \n        }\n\n        public void SmsInterceptor_MessageReceived(object sender, \n         MessageInterceptorEventArgs e)\n        {\n              SmsMessage msg = new SmsMessage();\n              msg.To.Add(new Recipient("James", "+16044352345"));\n              msg.Body = "Congrats, it works!";\n              msg.Send();  \n        }\n    }	0
6650936	6650922	Binding a list of images to a ListBox	ToString()	0
4461806	4461181	DataGridView: How to make some cells unselectable?	private int selectedCellRow = 0;\nprivate int selectedCellColumn = 0;\n\nprivate void grid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)\n{\n    if (e.Cell == null || e.StateChanged != DataGridViewElementStates.Selected)\n        return;\n\n    //if Cell that changed state is to be selected you don't need to process\n    //as event caused by 'unselectable' will select it again\n    if (e.Cell.RowIndex == selectedCellRow && e.Cell.ColumnIndex == selectedCellColumn)\n        return;\n\n    //this condition is necessary if you want to reset your DataGridView\n    if (!e.Cell.Selected)\n        return;\n\n    if (e.Cell.RowIndex == 0 || e.Cell.ColumnIndex == 0 || e.Cell.RowIndex == 1 && e.Cell.ColumnIndex == 1)\n    {\n        e.Cell.Selected = false;\n        grid.Rows[selectedCellRow].Cells[selectedCellColumn].Selected = true;\n    }\n    else\n    {\n        selectedCellRow = e.Cell.RowIndex;\n        selectedCellColumn = e.Cell.ColumnIndex;\n    }       \n}	0
33524245	33522084	Updating nodes from multiple xml strings	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        const string FILENAME = @"\temp\test.xml";\n        static void Main(string[] args)\n        {\n            XDocument callvalidate = XDocument.Load(FILENAME);\n\n            List<XElement> bankAccountNumbers = callvalidate.Descendants("Bankaccountnumber").ToList();\n            for(int index = 0; index < bankAccountNumbers.Count; index++)\n            {\n                XElement bankAccountNumber = bankAccountNumbers[index];\n\n                int accountNumber = int.Parse(bankAccountNumber.Value);\n                XElement newBankAccountNumber = new XElement("Bankaccountnumber", new object[] {\n                    accountNumber,\n                    new XElement("Banksortcode",accountNumber)\n                });\n                bankAccountNumber = newBankAccountNumber;\n            }\n        }\n    }\n}\n???	0
9805020	9804281	SelectNodes with XPath ignoring cases	//*[contains(translate(./@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'footer')]/@id	0
32749062	32736268	How can I specify schema for Kendo using helper?	multiselect.dataSource.reader.data = function (data) { return data.values};	0
956197	956165	WPF - OnPropertyChanged for a property within a collection	class ClassA : INotifyPropertyChanged\n{\n    private bool _isEnabled;\n    public bool IsEnabled\n    {\n        get { return _isEnabled; }\n        set\n        {\n            if (value != _isEnabled)\n            {\n                _isEnabled = value;\n                OnPropertyChanged("IsEnabled");\n            }\n        }\n    }\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    protected void OnPropertyChanged(string propertyName)\n    {\n        PropertyChangedEventHandler handler = PropertyChanged;\n        if (handler != null)\n            handler(this, new PropertyChangedEventArgs(propertyName));\n    }\n}	0
19115277	19115089	Console Application Args to Task Scheduler Parameters (CLOSED)	"C:\My Documents\xxx" x@y.z 10	0
12608665	12608439	Loop over values in an IEnumerable<> using reflection	foreach (var property in yourObject.GetType().GetProperties())\n{\n    if (property.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))\n    {\n        foreach (var item in (IEnumerable)property.GetValue(yourObject, null))\n        {\n             //do stuff\n        }\n    }\n}	0
1554002	1553819	C# CodeFunction2 - How do you prevent creation of 'return'?	TextPoint startPoint = method.GetStartPoint(vsCMPart.vsCMPartBody);\nTextPoint endPoint = method.GetEndPoint(vsCMPart.vsCMPartBody);\n\nvar editPoint = startPoint.CreateEditPoint();\neditPoint.Delete(endPoint);	0
11713315	11713295	Populating a listbox control in asp.net	lstDepartment.DataSource = oCorp.GetEmployeeList(emp);\n     lstDepartment.DataTextField = "EmployeeID";\n     lstDepartment.DataValueField = "EmployeeID";\n     lstDepartment.DataBind()	0
3382253	3300515	how to determine datagridview current state (insert - edit - display) mode vs2008 windows app	trans_dBindingSource.EndEdit();\n\nif (stock_dataset.trans_d.GetChanges(DataRowState.Added) != null)\n{\n    saveToolStripButton.PerformClick();\n}\nif (stock_dataset.trans_d.GetChanges(DataRowState.Modified) != null)\n{\n    saveToolStripButton.PerformClick();\n}\nif (stock_dataset.trans_d.GetChanges(DataRowState.Unchanged) != null)\n{\n    return;\n}	0
24068625	24068573	How to insert item as LAST option in a dropdown list	ddlTest.Items.Add(new ListItem("---New First Item---", "-1"));	0
17694239	17693087	Template method pattern without inheritance	public class BaseClass \n{\n    IDependent _dependent;\n\n    public BaseClass(IDependent dependent)\n    {\n         _dependent = dependent;\n    }\n\n    public void Alpha() {\n        _depdendent.Beta();\n    }\n\n    public void Gamma() {\n        _depdendent.Delta();\n    }\n\n}	0
6420444	6420419	How can I get a list of the columns in a SQL SELECT statement?	SqlDataReader mySDR = cmd.ExecuteReader();\nfor(int i = 0;i < mySDR.FieldCount; i++)\n{\n   Console.WriteLine(mySDR.GetName(i));\n}	0
28568079	28566966	Measure HTTP Response Time from a REST Client	GetResponse()	0
11528843	11528767	Write text file from excel using C#	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\nusing Bytescout.Spreadsheet;\n\nnamespace Converting_XLS_to_TXT\n{\nclass Program\n{\nstatic void Main(string[] args)\n{\n// Create new Spreadsheet from SimpleReport.xls file\nSpreadsheet document = new Spreadsheet("SimpleReport.xls");\n\n// delete output file if exists already\nif (File.Exists("SimpleReport.txt")){\nFile.Delete("SimpleReport.txt");\n}\n\n// save into TXT\ndocument.Workbook.Worksheets[0].SaveAsTXT("SimpleReport.txt");\n\n}\n}\n}	0
30710967	30709548	Nhibernate QueryOver Project enum description to string	// this projection\nProjections\n    .Property(() => tenantOrderAlias.InstallationStatus)\n    .WithAlias(() => tenantDto.InstallationStatusName //?   ));\n\n// could be converted into string values with this statement\nProjections\n    .Conditional(\n        Restrictions.Where<TenantOrder>(to => \n            to.InstallationStatus == TenantInstallationStatusEnum.TS0),\n        Projections.Constant("MS3_TenantInstallationStatus_TS0"),\n        Projections.Constant("MS3_TenantInstallationStatus_TS2")\n    ).WithAlias(() => tenantOrderAlias.InstallationStatusName)\n);	0
4120729	4120660	How to test if one rect is in another rect?	intersects(Rectangle r)	0
24908026	24889405	BaseEntity in Entity Framework Model First	public string EntityClassOpening(EntityType entity)\n    {\n        return string.Format(\n            CultureInfo.InvariantCulture,\n            "{0} {1}partial class {2}{3}",\n            Accessibility.ForType(entity),\n            _code.SpaceAfter(_code.AbstractOption(entity)),\n            _code.Escape(entity),\n            _code.StringBefore(" : ", "BaseEntity"));\n\n public string Property(EdmProperty edmProperty)\n    {\n        if (edmProperty.Name != "Id")\n        {\n            return string.Format(\n                CultureInfo.InvariantCulture,\n                "{0} {1} {2} {{ {3}get; {4}set; }}",\n                Accessibility.ForProperty(edmProperty),\n                _typeMapper.GetTypeName(edmProperty.TypeUsage),\n                _code.Escape(edmProperty),\n                _code.SpaceAfter(Accessibility.ForGetter(edmProperty)),\n                _code.SpaceAfter(Accessibility.ForSetter(edmProperty)));\n        }\n        else\n        {\n            return String.Empty;\n        }\n    }	0
30269700	30269609	Accesing child class value from list	private void SearchItemOnList()\n{\n   foreach (InDate c in newList)\n    {                \n        if (c.IEMI == txtSearchIEMI.Text)\n        {\n            txtDesciption.Text = c.Description;\n            txtInPrice.Text = Convert.ToString(c.Price);\n            txtInDate.Text = ""; //can't access inDate?\n        }\n    }\n}	0
16214810	16214441	randomly Select XML nodes with same names	XmlDocument xml = new XmlDocument();\nxml.Load("QA.xml");\n\nXmlNodeList xList = xml.SelectNodes("Main/QA");\nforeach (XmlNode xn in xList)\n{\n    string Question = xn["question"].InnerText;\n    if (Question == txtQuestion.Text)\n    {\n        XmlNodeList answerlist = xn.SelectNodes("./answer");\n        foreach (XmlNode ans in answerlist\n            .Cast<XmlNode>()\n            .OrderBy(elem => Guid.NewGuid()))\n        {\n            Console.WriteLine(ans.InnerText);\n        }\n    }\n}	0
12351011	12350670	How to extract zipped file received from HttpWebResponse?	var response = webRequest.GetResponse() as HttpWebResponse;\nvar stream = response.GetResponseStream();\nvar s = new ZipInputStream(stream);	0
25035202	25034500	Deep Copy a BindingList<Object>	BindingList<Equation> NewEquationList = \n                     new BindingList<Equation>(OldEquations.ToList());	0
2371882	2371835	How to read HTTP header from response using .NET HttpWebRequest API?	X-RateLimit-Limit	0
7231994	7231967	Equiv to get week of year by datepart in c#?	public static int GetWeekNumber(DateTime dtPassed)\n{\n        CultureInfo ciCurr = CultureInfo.CurrentCulture;\n        int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);\n        return weekNum;\n}	0
22405488	22405402	How can I create my own exception if an object parameter is null in C#	if (myObject != null)\n{\n     string json = myObject.ToJSONString(); \n     // other logic\n}\nelse\n{\n     // handle the situation where myObject is null\n}	0
15779942	15779564	Resize image in WPF	private static BitmapFrame CreateResizedImage(ImageSource source, int width, int height, int margin)\n{\n    var rect = new Rect(margin, margin, width - margin * 2, height - margin * 2);\n\n    var group = new DrawingGroup();\n    RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);\n    group.Children.Add(new ImageDrawing(source, rect));\n\n    var drawingVisual = new DrawingVisual();\n    using (var drawingContext = drawingVisual.RenderOpen())\n        drawingContext.DrawDrawing(group);\n\n    var resizedImage = new RenderTargetBitmap(\n        width, height,         // Resized dimensions\n        96, 96,                // Default DPI values\n        PixelFormats.Default); // Default pixel format\n    resizedImage.Render(drawingVisual);\n\n    return BitmapFrame.Create(resizedImage);\n}	0
13165346	13164045	How to visually update checkboxes in UI that are bounded to boolean isChecked variable in WPF c#?	public bool MyBool \n{ \n   get { return _mybool; }\n   set {\n         _mybool = value;\n         NotifyPropertyChanged("MyBool");\n       }\n}\n\npublic void NotifyPropertyChanged(string propertyName)\n{\n   if (PropertyChanged != null)\n       PropertyChanged(this, new PropertyChangedEventArgs(propertyName);\n}	0
22749889	22271628	Maximum Submatrix Sum of nxn matrices	(int i=0; i<row; i++)\n            tempArray[i] += matrix[i][right];	0
25262772	25262709	Server error in '/' application ASP.NET when enter directly into URL browser	[HttpPost]	0
20967742	20967570	display three array of byte in picture box	Bitmap bmp = new Bitmap(width,height);\nfor(int i=0;i<width;i++)\nfor(int j=0;j<height;j++) {\n    SetPixel(i,j,Color.FromArgb(R[i,j],G[i,j],B[i,j]));\n}\npicturebox.image=bmp;	0
15176428	15176173	Identify problematic characters in a string	CONVERT(NVARCHAR, CONVERT(VARCHAR, @originalNVarchar)) = @originalNVarchar	0
26712775	26638940	How to set font in TextOut in AfterDraw event using MonoTouch and TeeChart	private void chart_AfterDraw(object sender, Steema.TeeChart.Drawing.Graphics3D g)\n{\n    g.Font.Name = "Arial";\n    g.Font.Color = UIColor.Red.CGColor;\n    g.Font.Size = 18;\n\n    g.TextOut(xpos, ypos, "label");\n}	0
8762350	8762067	Common method among multiple controllers	newViewModel.Status = GetStatus();	0
24828903	24828719	Read the data from a Key in Registry and parse it	RegistryKey rk = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32).OpenSubKey("Software\\MyKeys");\n\nstring filePath = (string)rk.GetValue("Weekday");	0
963144	962888	Even if DropDownList has its viestate disabled, SelectedValue should still return a value	public partial class _Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        if (IsPostBack)\n        {\n            Label1.Text = DropDownList1.SelectedValue;\n        }\n    }\n\n    protected void Page_Init(object sender, EventArgs e)\n    {\n        string[] number = { "first", "second", "third" };\n        DropDownList1.DataSource = number;\n        DropDownList1.DataBind();\n    }\n}	0
15528514	13685724	How to add GetFileFromPathAsync's Path in Windows Store Apps	Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;\nXDocument document = XDocument.Load(installedLocation.Path + @"/Assets/Configuration/Menu.xml");	0
14052922	14043412	Deserialize Json Object - DateTime	public async static Task<T> Deserialize<T>(string json)\n    {\n        var value = await Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json);\n        return value;\n    }	0
5050431	5048886	How can I have the primary key of one entity be another entity in EF4 code-first?	public class Post {\n    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]\n    public int Id { get; set; }\n\n    public virtual ICollection<PostHistory> Histories { get; set; }\n}\n\npublic class PostHistory {\n    [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]\n    public int Id { get; set; }\n\n    public int PostId { get; set; }\n    public virtual Post Post { get; set; }\n\n   //... properties of the posthistory object\n}	0
34421634	34421535	Regular expression to validate version numbers	string Expressao = @"^\d{4}\.\d(?:\.\d{1,2}(?:\.\d{1,4}(?:\.RE)?)?)?$";	0
34302988	34302748	auto run multiple terminal program commands on a swf file then print results using python	from subprocess import call, check_output\n\nswf_file  = "filename.swf"\ndump_file = "dump_swf.txt"\n\n# run TrID on file and get results\nresult_string = check_output(["trid", "-v", filename])\n\n# parse result_string - is it compressed?\n??? YOUR CODE GOES HERE ???\n\nif is_compressed:\n    # decompress it\n    call(["flasm", "-x", filename])\n\n# decompile it\ndump = check_output(["swfdump", "-D", filename])\n\n# save the decompiled result\nwith open(dump_file, "w") as outf:\n    outf.write(dump)	0
13988256	13987997	TryParseExact - Finding Date in the Middle of a Line of Text	DateTime d;\nvar format1 = "dd/MM/yyyy";\nRegex r = new Regex("[0-3][0-9]/[0-1][0-9]/[0-9]{4}");\nvar linesWithDates = System.IO.File.ReadAllLines(z)\n    .Where(l => r.Matches(l).Cast<Match>()\n         .Any(DateTime.TryParseExact(m.Value, format1, ...)));	0
11583308	11583068	C# Initialize local variable once	string Method(string dot = string.Empty)\n{\n   if(dot == "...") return string.Empty;\n   else return dot + ".";\n}\n\nvar result = Method(Method(Method(Method(Method(Method()))))) // etc...	0
16213771	16213732	Sort generic list descending order	public ActionResult Index()\n    {\n        return View(db.Posts.OrderByDescending(p => p.Id).ToList());\n    }	0
33231389	33231228	How to generate Expression<Func<T, TPaginatedKey>> expression based on a string?	MethodCallExpression orderByCallExpression = Expression.Call(\n    typeof(Queryable),\n    "OrderBy",\n    new Type[] { queryableData.ElementType, queryableData.ElementType },\n    whereCallExpression,\n    Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));\n\n// Create an executable query from the expression tree.\nIQueryable<string> results = queryableData.Provider.CreateQuery<string>(orderByCallExpression);	0
1602851	1602836	Comparing 5 Integers in least number of comparisons	bool allEqual = (result1 == result2) && \n                (result1 == result3) && \n                (result1 == result4) &&  \n                (result1 == result5);	0
18872706	18852325	WP8 e.ChosenPhoto to Base64 String	byte[] bytearray = null;\n\n        using (var ms = new MemoryStream())\n        {\n            if (imgPhoto.Source != null)\n            {\n                var wbitmp = new WriteableBitmap((BitmapImage) imgPhoto.Source);\n\n                wbitmp.SaveJpeg(ms, 46, 38, 0, 100);\n                bytearray = ms.ToArray();\n            }\n        }\n        if (bytearray != null)\n        {\n            Sighting.Instance.ImageData = Convert.ToBase64String(bytearray);\n            PhotoModel.Instance.BitmapImage = bitmapImage;\n        }	0
4563391	4558415	C# Winforms: Accessing Outlook with Multiple Mailboxes	try\n        {\n            Outlook.Application oApp = new Outlook.Application();\n            Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("MAPI");\n            oNS.Logon(Missing.Value, Missing.Value, false, true);\n            Outlook.MAPIFolder theInbox = oNS.Folders["Mailbox - Name Here"].Folders["Inbox"];\n\n            ....Do you want with that Folder here....\n        }\n        catch (Exception e)\n        {\n            MessageBox.Show(e.ToString());\n        }	0
27298714	27298646	Use reflection to call method and get a string value back	return (string)value.GetValue(_clientDetails, null);	0
21927190	21908616	How to get the Row Number in Excel using c#.net	Microsoft.Office.Interop.Excel.Application ExcelObj = null;\nExcelObj = new Microsoft.Office.Interop.Excel.Application();\nMicrosoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open("abc.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true);\nMicrosoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;\nMicrosoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);\n\nvar value = (worksheet.Cells[58,1] as Microsoft.Office.Interop.Excel.Range).Value;	0
14050094	14050027	how can I upload a image on server side in asp.net	Image folder	0
17721534	17721288	unable to add value to html textbox of type password	txtPassword.Attributes.Add("value", Request.Cookies["SN"]["Password"])	0
31786751	31775893	Show variable herited from interface on Unity inspector	public class BasicUnit : ExposableMonoBehaviour, IUnit {\n\n    [SerializeField, HideInInspector]\n    private int _healthPoint;\n    [ExposeProperty]\n    public int HealthPoint { \n        get { return (_healthPoint); } \n        set { _healthPoint = value; } \n    }\n\n\n}	0
19289043	19286476	AutoFixture: how do I assign a property on only a subrange of items in a list?	var foos = fixture.CreateMany<Foo>(10).ToList();\nfoos.Take(5).ToList().ForEach(f => f.Bar = "Baz");\nfoos.Skip(5).Take(3).ToList().ForEach(f => f.Bar = "Qux");\nfoos.ForEach(f => f.Blub = 11);	0
11797141	11796992	Ranges of dates overlapping	where DateStart <= @DatePicker2\n  and DateEnd >= @DatePicker1	0
9846952	9846917	Combining 2 bytes	byte C = (byte)(\n    (A & 0x80) |\n    ((A & 0x20) << 1) |\n    ((A & 0x08) << 2) |\n    ((A & 0x02) << 3) |\n    ((B & 0x80) >> 4) |\n    ((B & 0x20) >> 3) |\n    ((B & 0x08) >> 2) |\n    ((B & 0x02) >> 1));	0
28438351	28437664	trouble Adding new row to datagridview in runtime using c#	var index = dataGridView1.Rows.Add();\ndataGridView1.Rows[index].Cells["Sno"].Value = 2;\ndataGridView1.Rows[index].Cells["Product_Name"].Value = "DHAWAT Brown Rice";	0
11645204	11645112	keeping the data in a form after it has been sent	var age = 0;\n\n    if (IsPost)\n    {\n        age = Request["frmage"].AsInt(0);\n\n    }\n\n<input class="formTextField" type="text" name="frmAge" size="3" value="@age"/>	0
7574843	7574776	Faster way to fill a 160x43 byte array from colors of Bitmap class	*( ( ( byte* )bmpData.Scan0 ) + ( y * bmpData.Stride ) + x ) = (byte)((tmp.R == 255 && tmp.G == 255 && tmp.B == 255) ? 0 : 255);	0
9847722	9846540	Open an Application .exe window inside another application	var hwnd = ..;\nShowWindow(hwnd, SW_MAXIMIZE);\nBringWindowToTop(hwnd);\n\n[DllImport("user32.dll", SetLastError=true)]\nstatic extern bool BringWindowToTop(IntPtr hWnd)	0
612996	612976	Determine number of elements of each type in a heterogeneous containercontainer	Dictionary<Type, List<object>> numTypes = new Dictionary<Type, List<object>>();\n\nforeach(KeyValuePair<string, object> pair in _Table){\n    Type type = object.GetType();\n    if (!numTypes.ContainsKey(type)){\n    numTypes[type] = new List<object>();\n     }\n\n    numTypes[type].Add(object);\n}	0
15678244	15675942	Read Xls file having Date Format Column	mCon.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + openFileDialog1.FileName + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX = 1\";");	0
10985661	10985328	How to give feedback to a visual interface, from a dll call?	public interface ICrawler\n {\n     void StartCrawling(Action<SomeCrawlingMessageType> callback);\n }	0
8653947	8653925	Day time to string conversion	.ToString("ddd MMM d hh:mm:ss yyyy")	0
16076645	16076510	Thread that talk with UI?	try\n    {\n        ... some operation ....\n    }\ncatch (Exception err)\n    {\n       if (txtErrors.InvokeRequired)\n        {\n            txtErrors.BeginInvoke(new MethodInvoker(\n                delegate { txtErrors.AppendText(err.Message); })\n                );\n        }\n    }	0
15661336	15661287	Getting object from SelectionChangedEventArgs e Windows Phone 8	if(e.AddedItems.Length > 0)       // make sure there is at least one item..\n{\n   MainViewModel firstItem = e.AddedItems[0] as MainViewModel;    // cast..\n   if(firstItem != null)                                          // if not null..\n   {\n       string fileName = firstItem.FileName;                      // get the file name\n   }\n}	0
4340895	4340849	Unit testing methods with a local Thread	[TestMethod]\n[HostType("Moles")]\npublic void AddDelegateToScanner_ScanHappens_ScanDelegateIsCalled()\n{\n    // Arrange\n    var scanCalledEvent = new ManualResetEvent(false);\n    MCoreDLL.GetTopWindow = () => (new IntPtr(FauxHandle));\n\n    // Act\n    _scanner.AddDelegateToScanner(_formIdentity, ((evnt) => { scanCalledEvent.Set(); }));\n    _scanner.SendScan(new BarcodeScannerEventArgs("12345678910"));\n\n    // Wait for event to fire\n    bool scanCalledInTime = scanCalledEvent.WaitOne(SOME_TIMEOUT_IN_MILLISECONDS);\n\n    // Assert\n    Assert.IsTrue(scanCalledInTime);\n}	0
5941340	5940800	Can't add programmatic controls in ASP.NET	var controls = this.displaytable.Rows[i].Cells[j].Controls;\nvar button = new TableButton(j, i);\nbutton.Click += new EventHandler(this.button_Click);\nbutton.UseSubmitBehavior = false;\nbutton.Text = "Available";\nbutton.Id = string.Format("TableButton_{0}_{1}", j, i);\ncontrols.Add(button);	0
1774512	1773426	convert a list of structs from c# to c++	using namespace System;\nusing namespace System::Collections::Generic;\n\npublic ref class Candidate\n{\npublic:  \n    Candidate()\n    {\n    }\n    property String^ Name\n    {\n        String^ get() { return this->name; }\n        void set(String^ value) { this->name = value; }\n    }\n    property String^ LastName\n    {\n       String^ get() { return this->lastName; }\n       void set(String^ value) { this->lastName = value; }\n    }\nprivate:\n    String^ name;\n    String^ lastName;\n};\n\npublic value class Results\n{\npublic:\n    Int32 Vote1;\n    Int32 Vote2;\n    Int32 Vote3;\n    Candidate^ precinctCandidate;\n};\n\nint main(array<String^>^ args)\n{\n    List<Results> votes = gcnew List<Results>();\n    return 0;\n}	0
16947330	16947265	How do you organize your Models/Views/ViewModels in WPF	Project MyApp.Model\n    |---> Models\n\n\nProject MyApp.Client\n    |--> Orders\n    |      |--> OrderCRUDView\n    |      |--> OrderCRUDViewModel\n    |      |--> OrderListView\n    |      |--> OrderListViewModel\n    |--> Accounts\n           |--> AccountCRUDView\n           |--> AccountCRUDViewModel\n           |--> AccountListView\n           |--> AccountListViewModel\n    ...etc	0
6852248	6539034	How to make a C# application using HttpWebRequest behave like fiddler	ServicePointManager.Expect100Continue = false;	0
16402079	16402007	Difficulty appending to XML file using Linq	loadedDoc.Element("Settings").Add(\n        new XElement("Config",\n                     new XElement("type", "stuff"),\n                     new XElement("length", "stuff"),\n                     new XElement("ID", "2")));	0
21332201	21332083	How to set value in drop down on button click?	protected void btnsubmit_Click(object sender, EventArgs e)\n            {\n    ddl.item.FindByValue("yourvalue").selected = true;\n\n//or\n    ddl.selectedindex=0;//will set first value. \n\n    }	0
12393331	12393254	FindControl recursive - error when finding my FileUpload control in GridView	protected void btnGem_Click(object sender, EventArgs e)\n    {\n        FileUpload FileUpload1 = (FileUpload)Tools.FindControlRecursive(GridView1, "FileUpload1");\nTextBox txtBox = (TextBox)Tools.FindControlRecursive(GridView1, txtBox.Text); //This seems to work fine\n\n    }	0
6737426	6737291	Loading form2 many times from form1	secondForm = new Form2();	0
14805382	14805208	Uploading a xml file to ftp server in C#, file has been successfully uploaded but there is no contents in it?	using (Stream stream = File.Open("main.xml", FileMode.Open))	0
19219883	19219648	WPF set visibility of item in listbox - code behind	mainCycle(list);\n\npreviousButton = (Control)list.Items.GetItemAt(list.Items.Count - 1);\n\n        if (itemCounts >= 4)\n        {\n            MessageBox.Show("" + previousButton.Name);\n            previousButton.Visibility = Visibility.Collapsed;\n        }	0
23704441	23704380	Get a subsection from XML	var xDoc = XDocument.Load(filename);\nvar dirs = xDoc.XPathSelectElements("//Directory[@ValidateEntireFolder='true']");	0
7662966	7662913	How do I perform a SelectMany in C# query syntax using a many-to-many joining table?	var dealers = from d in Dealers\n              from col in d.Brands\n              where d.StatusId == 1\n              select new { Name = d.Name, \n                           Brand = col.Name, \n                           StatusId = d.StatusId };	0
10609001	10608890	What's wrong with declaration of this routed event?	public static readonly RoutedEvent CollectionChangedEvent = EventManager.RegisterRoutedEvent( \n    "CollectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ReplacementPatternEditor)); \n\npublic event RoutedEventHandler CollectionChanged\n{\n    add { AddHandler(CollectionChangedEvent, value); } \n    remove { RemoveHandler(CollectionChangedEvent, value); }\n}\n\n\nvoid RaiseCollectionChangedEvent() \n{ \n    RoutedEventArgs newEventArgs = new RoutedEventArgs(ReplacementPatternEditor.CollectionChanged); \n    RaiseEvent(newEventArgs); \n}	0
13116021	13116004	Cannot Convert from Method Group to Object - C#	select.Average()	0
3247792	3247728	TextBox Validation - C#	private void txtType_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (e.KeyChar == (char)Keys.Back || (e.KeyChar == (char)'.') && !(sender as TextBox).Text.Contains("."))\n        {\n            return;\n        }\n        decimal isNumber = 0;\n        e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);\n    }	0
23653493	23652267	Json.NET fails to serialize dictionary of sets	TypeNameAssemblyFormat = FormatterAssemblyStyle.Full	0
3178826	3178797	How to implement simple multithreaded function	private object padLock = new object();  // 1-to-1 with _ConditionalOrderList\n\nif (Monitor.TryEnter(padLock))\n{\n   try \n   {\n      // cancel other orders\n\n      return true;\n   } \n   finally \n   {\n       Monitor.Exit(padLock);\n   }\n}\nelse\n{\n   return false;\n}	0
12510474	12510418	How to parse the text out of html in c#	string html = @"This is <h4>Some</h4> Text" + Environment.NewLine +\n                "This is some more <h5>text</h5>";\n\nHtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\nvar str = doc.DocumentNode.InnerText;	0
6451464	6451041	Injecting the same instance with StructureMap	For<IConnection>().Singleton().Add<TcpConnection>().Named("Connection");\nFor<IFoo>().Add<Foo>().Ctor<IConnection>().Is(i=>i.GetInstance<IConnection>("Connection"));\nFor<IBar>().Add<Bar>().Ctor<IConnection>().Is(i=>i.GetInstance<IConnection>("Connection"));	0
14935231	14930867	Crossbar filter change current input to Composite	IAMCrossbar::Route	0
7556290	7555325	Using the latest value from IObservable	var ubar = bar.Select(x => Unit.Default);\nvar ubaz = baz.Select(x => Unit.Default);\n\nubar.Merge(ubaz)\n    .CombineLatest(foo.Where(f => f.Id == 1), (u, f) => f)\n    .Subscribe(f => DoWork(f));	0
3264968	3264946	XDocument.Save creating 3 bad characters in XML	// http://msdn.microsoft.com/en-us/library/s064f8w2.aspx\nusing (XmlWriter xw = new XmlTextWriter(fcService.SetCIRIFilePath(), new System.Text.UTF8Encoding(false)))\n        {\n            debts.Save(xw);\n            xw.Flush();\n        }	0
9884249	9877644	Can Fluent Assertions use a string-insensitive comparison for IEnumerable<string>?	[TestMethod()] \npublic void foo() \n{ \n   var actual = new List<string> { "ONE", "TWO", "THREE", "FOUR" }; \n   var expected = new List<string> { "One", "Two", "Three", "Four" }; \n\n  actual.Should().Equal(expected, \n    (o1, o2) => string.Compare(o1, o2, StringComparison.InvariantCultureIgnoreCase))\n}	0
15762224	15761719	c# sending image via socket	clientSocket.ReceiveBufferSize	0
13988871	13987408	Convert RenderTargetBitmap to BitmapImage	var renderTargetBitmap = getRenderTargetBitmap();\nvar bitmapImage = new BitmapImage();\nvar bitmapEncoder = new PngBitmapEncoder();\nbitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));\n\nusing (var stream = new MemoryStream())\n{\n    bitmapEncoder.Save(stream);\n    stream.Seek(0, SeekOrigin.Begin);\n\n    bitmapImage.BeginInit();\n    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n    bitmapImage.StreamSource = stream;\n    bitmapImage.EndInit();\n}	0
7567243	7567149	Setting Color Using Number in C#	var x = (Color)ColorConverter.ConvertFromString("#faffff");	0
9882248	9881930	How to mark up your C# object to Deserialize this XML	public class Library\n{\n    [XmlArray("Rows")]\n    [XmlArrayItem("Row")]\n    public List<Book> Books { get; set; }\n}	0
29094775	29094171	how to find controls in custom window in wpf	public partial class MainWindow : Window\n{\n    public MainWindow()\n    {\n        InitializeComponent();\n        var label = Template.FindName("lbl_title", this) as Label;\n        Loaded += MainWindow_Loaded;\n    }\n\n    void MainWindow_Loaded(object sender, RoutedEventArgs e)\n    {\n        var label = Template.FindName("lbl_title", this) as Label;\n    }\n}	0
23279731	23277308	Where do I put DispID when a interace implements a interface for COM Interop	public interface IBPBarcodeDevice : IBarcodeEvents	0
23227314	23227287	How to implement a generic OpenForm method to allow any type of Form	void OpenFrom<T>() where T : Form, new()\n {\n     new T().Show();\n }	0
7872994	7872934	Loading a WPF control embedded in a DLL in runtime	UserControl myControl = null;    \n  Assembly asm = Assembly.LoadFile(Your dll path);\n  Type[] tlist = asm.GetTypes();\n  foreach (Type t in tlist)\n  {\n     if(t.Name == "Your class name" )\n     {\n         myControl = Activator.CreateInstance(t) as UserControl;\n         break;\n     }               \n  }	0
24146777	24146739	Is there a reason to return null inside parentheses	return null;	0
24805548	24805381	Creating a middleman application between a website and a locally installed appplication	Private Sub myform_Resize(sender As Object, e As EventArgs) Handles Me.Resize\n    If Me.WindowState = FormWindowState.Minimized Then\n        Me.ShowInTaskbar = False\n\n        'show notification\n\n        With myNotifyIcon\n            .BalloonTipIcon = ToolTipIcon.Info\n            .BalloonTipText = "Running, but hidden"\n            .BalloonTipTitle = "Going going gone..."\n            .ShowBalloonTip(3000)\n        End With\n\n    End If\nEnd Sub	0
9038155	9038070	How do I get the location of the user.config file in programmatically?	var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);\n\nMessageBox.Show(config.FilePath);	0
14448733	14448510	How to get the caller's URL in WCF netTcpBinding windows service?	((RemoteEndpointMessageProperty)OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]).Address;	0
3651020	3650998	How to grab the parent url from an iFrame using c#	var parentUrl = window.parent.location.href;	0
1050445	1050417	How do you take an image (passed in as a Base64 encoded string) and save it to the server in Asp.Net C#?	byte[] contents = Convert.FromBase64String(file);\nSystem.IO.File.WriteAllBytes(Server.MapPath(fileName), contents);	0
8100782	8100413	Events on items in databound repeater don't fire	protected void Bars_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    if (e.Item != null && e.Item.DataItem != null)\n    {\n        var b = e.Item.DataItem as Bar;\n        var Name = e.Item.FindControl("Name") as TextBox;\n        var Description = e.Item.FindControl("Description") as TextBox;\n        // Commented\n        // Name.TextChanged += new EventHandler(Name_TextChanged);\n    }\n}\n\n<asp:TextBox ID="Name" Text='<%# Eval("Name") %>' runat="server" \nAutoPostBack="true" OnTextChanged="Name_TextChanged" /> \n\n<asp:TextBox ID="Description" Text='<%# Eval("Description") %>' \nrunat="server" AutoPostBack="true" OnTextChanged="Name_TextChanged" />	0
26674716	26674290	Depth of a relationship	int GetDepth(Comment comment, \n                IDictionary<int, Comment> comments,  /*key=commentId, val=Comment*/\n                IDictionary<int, int> depthMemoization, /* key=commentId, val=depth*/\n                int currentDepth = 0)\n{\n    if(depthMemoization.ContainsKey(comment.Id))\n        return depthMemoization[comment.Id];\n\n    if(comment.ParentId==null)\n        return currentDepth;\n\n    var parentComment = comments[comment.ParentId.Value];\n\n    int calculatedDepth = GetDepth(parentComment, comments, \n                            depthMemoization,\n                            ++currentDepth);\n\n    depthMemoization[comment.Id] = calculatedDepth ;\n\n    return depth;\n}	0
17037299	17037238	Load from text file at program startup	class TestClass\n {\n     static void Main(string[] args)\n     {\n           //Now you have all arguments in the string array\n           if(args.Length != 0)\n           {\n                 string pathToTextfile = args[0];\n           }\n\n           StreamReader textFile = new StreamReader(pathToTextfile);\n           string fileContents = textFile.ReadToEnd();\n           textFile.Close();\n\n\n     }\n }	0
7172430	7172030	How to access x:Name-property in code - for non FrameworkElement objects?	public string GetName(GridViewColumn column)\n{\n    var findMatch = from field in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)\n                    let fieldValue = field.GetValue(this)\n                    where fieldValue == column\n                    select field.Name;\n\n    return findMatch.FirstOrDefault();\n}	0
18445984	18445316	Put focus back on previously focused control on a button click event C# winforms	using System;\nusing System.Windows.Forms;\n\nclass CalculatorButton : Button, IMessageFilter {\n    public string Digit { get; set; }\n\n    protected override void OnClick(EventArgs e) {\n        var box = lastFocused as TextBoxBase;\n        if (box != null) {\n            box.AppendText(this.Digit);\n            box.SelectionStart = box.Text.Length;\n            box.Focus();\n        }\n        base.OnClick(e);\n    }\n    protected override void OnHandleCreated(EventArgs e) {\n        if (!this.DesignMode) Application.AddMessageFilter(this);\n        base.OnHandleCreated(e);\n    }\n    protected override void OnHandleDestroyed(EventArgs e) {\n        Application.RemoveMessageFilter(this);\n        base.OnHandleDestroyed(e);\n    }\n\n    bool IMessageFilter.PreFilterMessage(ref Message m) {\n        var focused = this.FindForm().ActiveControl;\n        if (focused != null && focused.GetType() != this.GetType()) lastFocused = focused;\n        return false;\n    }\n    private Control lastFocused;\n}	0
11050756	11050678	Show tooltip text by clicking a control	private void PictureBox1_Click(object sender, EventArgs e)\n{\n    int durationMilliseconds = 10000;\n    ToolTip1.Show(ToolTip1.GetToolTip(PictureBox1), PictureBox1, durationMilliseconds);\n}	0
13335743	13335498	How to use an AudioProfile with an Expression Encoder Job	mediaItem.OutputFormat.AudioProfile = wmaProfile;	0
12915707	12915650	What is the cleanest way to ensure a set of values are all unique?	new [] {a, b, c, d, e}.Distinct().Count() == 5	0
24875456	24748143	How to delete files in AppData/Temp after file upload with .NET WebAPI 2? File in use error	S3Helper.Upload(fi.FullName, extension)	0
32723410	32723297	Stored variable that shouldn't be getting changed is getting changed	public class PanelInformation\n{\n    public int Height { get; set; }\n    public int Width { get; set; }\n    public int X { get; set; }\n    public int Y { get; set; }\n}	0
23312500	23303175	Get Response Back from ASPX page in Android	Response.AddHeader(CONFIG.REG_RESPONSE, CONFIG.REG_ADDED)	0
6465873	6464136	Make Contract.Assert throw an exception rather than display a Dialog box	namespace QuickGraph.Tests  \n{  \n    [TestClass]  \n    public class AssemblyContextTest  \n    {  \n        [AssemblyInitialize]  \n        public static void Initialize(TestContext ctx)  \n        {  \n            // avoid contract violation kill the process  \n            Contract.ContractFailed += new EventHandler<ContractFailedEventArgs>(Contract_ContractFailed);  \n        }  \n\n        static void Contract_ContractFailed(object sender, System.Diagnostics.Contracts.ContractFailedEventArgs e)  \n        {  \n            e.SetHandled();  \n            Assert.Fail("{0}: {1} {2}", e.FailureKind, e.Message, e.Condition);  \n        }  \n    }  \n}	0
4393342	4337562	Hierarchical Data Grid Child	IEnumerable<Student> list = (IEnumerable<Student>)this.DataContext;\nforeach(Student stu in Students)\n{\n    Debug.WriteLine(stu.StudentID + ":");\n    foreach(Subject sub in stu.Subjects)\n    {\n        Debug.WriteLine("\\t" + sub.SubjectID)\n    }\n}	0
12597736	12597513	Extract multiple sub-strings from a string in C#?	string str = "12345678901234";\n\nstring str1 = string.Empty;\nstring str2 = string.Empty;\nstring str3 = string.Empty;\nfor (int i = 0; i < str.Length; i++)\n{\n    if (i < 2)\n        str1 += str[i];\n    else if (i > 1 && i < 8)\n        str2 += str[i];\n    else\n        str3 += str[i];\n}	0
14719827	14661338	When to clean up a command-binded control?	CommandBindings.Clear()	0
4344965	4344929	Passing Parameters to SQL Server 2008	List<SqlParameter> parameters = new List<SqlParameter> { };\n\nstring status = "dummystatus";\nstring date = Datetime.Now;\nparameters.Add(new SqlParameter("@Status", status));\nparameters.Add(new SqlParameter("@date", date));\n\nSqlCommand cmd = new SqlCommand();\ncommand.Connection = connection;\n\n//set the command text (stored procedure name or SQL statement)\ncommand.CommandText = commandText;\ncommand.CommandType = commandType;\nforeach (SqlParameter p in parameters)\n{\n    command.Parameters.Add(p);\n}\nSqlDataAdapter da = new SqlDataAdapter(command);\nDataSet ds = new DataSet();\n\n//fill the DataSet using default values for DataTable names, etc.\nda.Fill(ds);\n\n// detach the SqlParameters from the command object, so they can be used again.         \ncmd.Parameters.Clear();	0
16197196	16196118	Remove and add GridRow definitions in C#	RowDefinitionCollection defs = myGrid.RowDefinitions;\n    defs.Add(new RowDefinition() { Height = new GridLength(140) });\n    defs.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });	0
26812647	26812570	How to Return 3 values / substitutions of values	array_of_arrays[0]	0
11309634	11309482	Programatically binding to a changing ViewModel	class WizardStepVm : INotifyPropertyChanged {\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private void NotifyPropertyChanged(String info)\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(info));\n        }\n    }\n    private string m_stepName;\n    public string StepName {\n      get {\n        return m_stepName;\n      }\n      set {\n        m_stepName = value; \n        NotifyPropertyChanged("StepName");\n      }\n    }\n    /* etc... */\n}	0
3181632	3181594	Handling a click over a balloon tip displayed with TrayIcon's ShowBalloonTip()	NotifyIcon notifyIcon = null;\npublic Form1()\n{\n    InitializeComponent();\n    notifyIcon = new NotifyIcon();\n    // Initializing notifyIcon here...\n    notifyIcon.BalloonTipClicked += new EventHandler(notifyIcon_BalloonTipClicked);\n}\n\nvoid notifyIcon_BalloonTipClicked(object sender, EventArgs e)\n{\n    // Operation you want...\n}	0
20144168	20143910	Struct from C++ to C#	private static extern int pst_get_sensor(PSTSensor ref sensor);	0
13768296	13768127	Correct Linq conversion from C# to Vb.net	Dim btnUp As Button = DirectCast(sender, Button)\nDim row As GridViewRow = DirectCast(btnUp.NamingContainer, GridViewRow)\nDim rows = GridView1.Rows.Cast(Of GridViewRow)().Where(Function(a) a <> row).ToList()	0
30993786	30993676	String Format: How to add any number of zeros before string	int num = 4;    \nstring a = num.ToString("D4");	0
27280958	27280697	Constantly switching dynamic data type performance in C#	object objectThing = dataString;\nw.Restart();\nobjectThing = dataDouble;\ndouble objectDouble = (double)objectThing;\nobjectThing = dataString;\nstring objectString = (string)objectThing;\nw.Stop();	0
3812294	3812289	Is there any way to get a file name from a path? 	string filename = Path.GetFileName(@"c:\MyPic\OldPic\me.jpg");	0
10540408	10540383	show decimal places on client side division	(((ListData)Container.DataItem).TotalMinutes / 60.00).ToString("N2")	0
6567	6557	In C#, why can't a List<string> object be stored in a List<object> variable	List<object> ol = new List<object>();List<string> sl;sl = (List<string>)ol;	0
27673010	27626378	Creating an rtf custom mail item	RDOMail.RtfBody	0
23236771	23236641	Linq with Lambda equivalent of SQL	var list = from s in Staff\njoin sr in StaffRole on s.StaffId equals sr.StaffId\njoin r in Role on sr.RoleId equals r.RoleId\nwhere r.Description == 'SpecialisedHealthManager' && s.PrimaryShm == 0\nselect new\n{\n   StaffId = s.StaffId,\n   FirstName = s.Staff.FirstName,\n   Surname = s.Staff.Surname, \n   SamAccountName = s.Staff.SamAccountName,\n   RoleId = r.Description\n});	0
6105311	6094287	NAudio to split mp3 file	string strMP3Folder = "<YOUR FOLDER PATH>";\nstring strMP3SourceFilename = "<YOUR SOURCE MP3 FILENAMe>";\nstring strMP3OutputFilename = "<YOUR OUTPUT MP3 FILENAME>";\n\nusing (Mp3FileReader reader = new Mp3FileReader(strMP3Folder + strMP3SourceFilename))\n{\n    int count = 1;\n    Mp3Frame mp3Frame = reader.ReadNextFrame();\n    System.IO.FileStream _fs = new System.IO.FileStream(strMP3Folder + strMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);\n\n    while (mp3Frame != null)\n    {\n        if (count > 500) //retrieve a sample of 500 frames\n            return;\n\n        _fs.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);\n        count = count + 1;\n        mp3Frame = reader.ReadNextFrame();\n     }\n\n     _fs.Close();\n}	0
4048417	4048371	passing parameter to DownloadStringCompletedEventHandler in C#	client.DownloadStringAsync(yourUri, yourListBox);	0
8290654	1006069	How do I get the position of the text baseline in a Label and a NumericUpDown?	Font myFont = Label1.Font;\nFontFamily ff = myFont.FontFamily;\n\nfloat lineSpace = ff.GetLineSpacing(myFont.Style);\nfloat ascent = ff.GetCellAscent(myFont.Style);\nfloat baseline =  myFont.GetHeight(ev.Graphics) * ascent / lineSpace;\n\nPointF renderPt = new PointF(pt.X, pt.Y  - baseline));\nev.Graphics.DrawString("Render this string", myFont, textBrush, renderPt);	0
19923567	19923128	Digit grouping with two decimal places in c#	double s=123.345345;\n\n           string str=string.Empty;\n\n           str = s.ToString("#,0.##");\n\n            MessageBox.Show(str);	0
5963337	5963237	Custom Validation is only run once	if (_otherPhone == value) return;	0
17721969	17721418	Where is DefaultRenderMvcControllerResolver located in Umbraco Api	Umbraco.Web.Mvc	0
21860072	20749484	How to properly close a client proxy (An existing connection was forcibly closed by the remote host)?	private async Task<string> TestTask()\n{\n    Service1Client proxy = null;\n\n    try\n    {\n        Console.WriteLine("Calling service");\n\n        proxy = new Service1Client();\n        return await proxy.DoWorkAsync();\n    }\n    finally\n    {\n        if (proxy.State != System.ServiceModel.CommunicationState.Faulted)\n        {\n            Console.WriteLine("Closing client");\n            proxy.ChannelFactory.Close();\n            proxy.Close();\n        }\n        else\n        {\n            Console.WriteLine("Aborting client");\n            proxy.Abort();\n        }\n    }\n}	0
22113782	22113480	how to not delete a single particular session variable?	var value = Session["tokeep"]; \nSession.RemoveAll(); \nSession["tokeep"] = value;	0
1435594	1435501	How to parse DateTime SubString out of variable String	string input = "IF;Thermal >=20 and SYSTEM_TIME >= Tue 15 Sep 2009    23:00:21 ";\nstring pattern = @"[A-Z]+\s+\d+\s+[A-Z]+\s+\d{4}\s+(?:\d+:){2}\d{2}";\nMatch match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);\n\nif (match.Success)\n{\n    string result = match.Value;\n    DateTime parsedDateTime;\n    if (DateTime.TryParse(result, out parsedDateTime))\n    {\n    // successful parse, date is now in parsedDateTime\n    Console.WriteLine(parsedDateTime);\n    }\n    else\n    {\n    // parse failed, throw exception\n    }\n}\nelse\n{\n    // match not found, do something, throw exception\n}	0
13814470	13814190	Append Item to the end of List	FruitTrees item = Trees.Retrieve(0); \nwhile (item.Next != null)\n{\n  item = item.Next;\n}\nitem.Next = NewItem	0
31268847	31268563	How to get value from one form to an other?	using (Bevestiging myForm = new Bevestiging())\n{\n    DialogResult result = myForm.ShowDialog();\n\n    if (result != DialogResult.OK)\n    {\n        int returnedValue = myForm.Aantal;\n    }\n}	0
32539866	32539798	How to convert a string json to a dictionary in C#	var dictionary = JsonConvert.DeserializeObject<IDictionary<string, string>>(json)	0
5279393	5279326	How to get node count with XPathDocument and C#?	int errorCount = navigator.Select("/api/error").Count;	0
4725610	4725524	C# text file deduping based on split	string inputFile; // = ...\nstring outputFile; // = ...\nHashSet<string> keys = new HashSet<string>();\n\nusing (StreamReader reader = new StreamReader(inputFile))\nusing (StreamWriter writer = new StreamWriter(outputFile))\n{\n    string line = reader.ReadLine();\n    while (line != null)\n    {\n        string candidate = line.Split('|')[0];\n        if (keys.Add(candidate))\n            writer.WriteLine(line);\n\n        line = reader.ReadLine();\n    } \n}	0
24046749	24046399	Enforcing the generic delegate parameter based on a Type	private Dictionary<Type, Func<TContract, Task>> _processorDictionary = new Dictionary<Type, Func<TContract, Task>>();\n\npublic void AddEntry<TContract>(Func<TContract, Task> func)\n{\n    _processorDictionary[typeof(TContract)] = func;\n}	0
6383668	6383417	How to create a dynamic property in this scenario	dynamic expando = new ExpandoObject();\nvar p = expando as IDictionary<String, object>;\n\nfor(int i=0;i<list.count;i++)\n{\n     p[id+i] = list[i].id;\n}\n\n//do something with the expando object	0
27142789	27142564	Find all string in 2d array like template	List<List<string>> myStuff = ...;\nRegex regex = new Regex("192:(24|19):[0-9]{6}:[0-9A-Za-z]*")\nvar matchingRows = myStuff.Where(x => regex.IsMatch(x[1]);	0
23997407	23996592	How to convert LINQ nested Selectmany to SQL Regular Statements	;WITH prog AS\n(\n    SELECT \n        ej.ResourceItemId,\n        SUM(et.Progress) / COUNT(*) AS totalProg\n    FROM EncodingJobs ej\n    JOIN EncodingTasks et ON ej.Id = et.EncodingJobId\n    GROUP BY\n        ej.ResourceItemId\n)\nSELECT\n    ri.Id\n    ,ri.CreationDate\n    ,ri.FolderId\n    ,ri.Name\n    ,ri.ResourceType\n    ,ri.Url\n    ,ri.Size\n    ,ri.MediaAssetUuid\n    ,ri.Blob\n    ,ri.Container\n    ,ri.GroupId\n    ,ISNULL(prog.totalProg, 0) AS Progress\n    ,ri.Uuid\n    ,u.Id AS UserId\n    ,u.UserName\n    ,u.FirstName\n    ,u.LastName\nFROM ResourceItem ri\nINNER JOIN ResourceItemsTree rit ON ri.FolderId = rit.Id\nINNER JOIN [User] u ON u.Id = ri.CreatedBy\nLEFT JOIN prog ON ri.Id = prog.ResourceItemId\nWHERE\n    ri.IsDeleted = CAST(0 as BIT)	0
16045985	16042214	How to remove a property from a custom user control	.+\.SomeProperty.+	0
10299956	10299873	Changes to an SDF database file are never saved	DataTable.Clear	0
25815655	25815405	How can you create a c# dependent variable?	var tb = FindControl(type+"IdlabelChange") as Textbox;\nif(tb != null && tb.Value != null){\n    ....\n}	0
8601906	8601801	Call a function of parent aspx page from web user control	public event EventHandler CancelClicked;\n\nprotected Cancel_Click(object sender, EventArgs e)\n{\n  if(CancelClicked != null)\n  {\n    CancelClicked(this, e);\n  }\n}	0
14984789	14981321	Post values to URL without redirecting	Dim result As String = New System.Net.WebClient().DownloadString("http://...")	0
6455114	6455066	How to test a ViewModel that loads with a BackgroundWorker?	public class MyViewModel\n{\n    private IBackgroundWorker _bgworker;\n\n    public MyViewModel(IBackgroundWorker bgworker)\n    {\n        _bgworker = bgworker;\n    }\n\n    private void OnLoadData()    \n    {        \n        IsBusy = true; // view is bound to IsBusy to show 'loading' message.        \n\n        _bgworker.DoWork += (sender, e) =>        \n        {          \n            MyData = wcfClient.LoadData();        \n        };        \n        _bgworker.RunWorkerCompleted += (sender, e) =>        \n        {          \n            IsBusy = false;        \n        };        \n        _bgworker.RunWorkerAsync();    \n    }\n\n}	0
2737676	2737663	Reflection and Generics get value of property	object value = info.GetValue(item, null);	0
5083690	5083565	How can I quickly up-cast object[,] into double[,]?	object[,] src = new object[2, 3];\n\n// Initialize src with test doubles.\nsrc[0, 0] = 1.0;\nsrc[0, 1] = 2.0;\nsrc[0, 2] = 3.0;\nsrc[1, 0] = 4.0;\nsrc[1, 1] = 5.0;\nsrc[1, 2] = 6.0;\n\ndouble[,] dst = new double[src.GetLength(0), src.GetLength(1)];\nArray.Copy(src, dst, src.Length);	0
1624244	1624226	How to create a thread-safe single instance of an IDisposable?	Action<DBClass>	0
18811557	18811472	Windows phone 8 Bluetooth development	IAsyncOperation <IReadOnlyList<PeerInformation>>  peers;	0
13493903	13250501	Windows 8 Store App Global ViewModel	public class MyViewModel\n{\n    private static MyViewModel instance;\n\n    private MyViewModel()\n    {\n        // Private constructor\n    }\n\n    public static MyViewModel Instance\n    {\n        get\n        {\n            if (instance == null)\n                instance = new MyViewModel();\n\n            return instance;\n        }\n    }\n}	0
16925625	16925474	Parsing Lines of Log File for Specific Entries	regExPattern = @"(?<tag>\bXml Sent to Engine\b)\s+(.*)$"	0
7926836	7926779	how to get all the controls on the windows form page	foreach (Control ctrl in this.Controls)\n{\n    if (ctrl is NumberEntry)\n    {\n        ((NumberEntry)ctrl).Clear();\n    }\n}	0
25976781	25897451	c# - IDENT_CURRENT in Linq-to-Entities	var id = hmd.ExecuteStoreQuery<decimal>(@"SELECT IDENT_CURRENT ({0}) AS Current_Identity;",\n"HMDAdvertiseManage").First();	0
22096471	22096054	Difference between two List with same entries but not the same count	var groups1 = List1\n    .GroupBy(c => new { c.Firstname, c.LastName, c.IsAdmin });\nvar groups2 = List2\n    .GroupBy(c => new { c.Firstname, c.LastName, c.IsAdmin });\n\nvar diffs = from g1 in groups1\n            join g2 in groups2\n            on g1.Key equals g2.Key into gj\n            from g2 in gj.DefaultIfEmpty(Enumerable.Empty<Contact>())\n            where g1.Count() > g2.Count()\n            select new { g1, g2 };\nList<Contact> allDiffs = diffs\n    .SelectMany(x => x.g1.Take(x.g1.Count() - x.g2.Count()))\n    .ToList();	0
28545098	28499778	C# How to extract bytes from byte array? With known starting byte	byte[] results = new byte[16];\n        int index = Array.IndexOf(readBuffer, (byte)0x55);\n        Array.Copy(readBuffer, index, results, 0, 16);	0
13985378	13983420	How to stop ScrollViewer from scrolling down	VerticalScrollBarVisibility="disabled"	0
29205248	29168444	Is this a correct implementation of a FuSM (Fuzzy State Machine)	pow(numOfVariables, numOfStates)	0
23500349	16531059	Entering values for a Byte array in WCF Test client	byte[] myClassLevelArray1 = new byte[10];\nbyte[] myClassLevelArray2 = new byte[10];\n\npublic void SetArrayOne()\n{\n    SetArray(myClassLevelArray1, 1, 2, 3, 4, 5);\n}\n\npublic void SetArrayTwo()\n{\n    SetArray(myClassLevelArray2, 1, 2, 3, 4, 5, 8, 9, 10, 11, 15, 20, 5, 98, 5, 4);\n}\n\npublic static void SetArray(byte[] myArray, params byte[] newValues)\n{\n    Array.Copy(newValues, myArray, Math.Min(newValues.Length, myArray.Length));\n}	0
21408039	21407806	Formatting the JSON date value	DateTime eventDate = DateTime.MinValue;\nif (DateTime.TryParse(ja[count]["date"], out eventDate))\n{\n    content.str_eventDate = string.Format("{0:dddd dd}{1} {0:MMMM yyyy}",\n        eventDate, \n        (eventDate.Day == 1) \n                         ? "st"\n                         : (eventDate.Day == 2)\n                               ? "nd"\n                               : (eventDate.Day == 3)\n                                     ? "rd"\n                                     : "th"); \n}	0
19676691	19675593	Taking an Object from one Collection to another	foreach (var obj in SelectedObjects)\n    ToBeProcessed.Add(obj);\n\nSelectedObjects.ClearItems();	0
16834154	16833898	How to get value of a class's array in c#?	Byte Payment_Type_Id = 2; // <- int will be better here\nString val = Payment_Type.PaymentTypeList()[Payment_Type_Id].value.ToString();	0
30394479	30394315	Generate random string using options	private static Random gen = new Random();\n\n  ...\n  String source = "{Hi|Hello|Hey}, how are you {today|doing}?";\n\n  String result = Regex.Replace(source, @"\{(\w|\|)*\}", (MatchEvaluator) (\n    (match) => {\n       var items = match.Value.Trim('{','}').Split('|');\n\n       return items[gen.Next(items.Length)];\n     }));	0
1601327	1601241	C# - Regex - Matching file names according to a specific naming pattern	string pattern = @"I[A-Z]{3}_\d{5}-\d_\d{8}_\d{8}_\d{6}\.zip";\n    var matches = Directory.GetFiles(@"c:\temp")\n        .Where(path => Regex.Match(path, pattern).Success);\n\n    foreach (string file in matches)\n        Console.WriteLine(file); // do something	0
1258017	1258013	Porting file preprocessing code from C to C#	List<string>	0
27135154	27134838	Calling signalR hub methods from console application	var ctx = GlobalHost.ConnectionManager.GetHubContext<yourhub>();\n  ctx.Clients.Client(connectionId).<your method>	0
405503	405493	Is it possible to setup a shared folder for DLLs with relative pathing in Visual Studio 2008?	+-- MySolution\n    | // The solution is in source control\n    |\n    +-- MyProject1\n    |   |\n    |   +-- Project and source code files for a specific project\n    |\n    +-- MyProject1.Test\n    |   |\n    |   +-- Test files for MyProject1\n    |\n    +-- Third Party\n    |   |\n    |   +-- Library dll's are stored here.\n    |\n    |\n    +-- Solution files, more project folders, user settings (user settings are not in source control) etc???	0
8984814	8984534	Importing excel file to SQL database, how to ignore 2nd row; asp.net & C#	...\nOleDbDataReader dReader;\ndReader = cmd.ExecuteReader();\nif( !dReader.Read() || !dReader.Read()) \n  return "No data";\nSqlBulkCopy sqlBulk = new SqlBulkCopy(connectionString);\n...	0
8464357	8464256	C#: Changing picture in form, using picture from resourses	pictureBox.Image = Properties.Resources.PictureName	0
23836834	23836222	How to add a new row in a combobox?	SqlCeCommand sql3 = new SqlCeCommand("SELECT (ACM_EMPL.NUM_EMPL + '~' + ACM_EMPL.NOM_EMPL) AS NUM_EMPL FROM ACM_EMPL INNER JOIN ACM_ACT ON ACM_EMPL.NUM_EMPL = ACM_ACT.NUM_EMPL WHERE (ACM_ACT.NUM_ACTIVO = '" + oc.Text + "'AND ACM_ACT.NUM_CIA = '" + CIA.Text + "' AND ACM_ACT.NUM_TIPO = '" + TIPO.Text + "' AND ACM_ACT.SUB_NUM_ACT = '" + SUBNUM.Text + "') ", conn);\n        sql3.ExecuteNonQuery();\n        SqlCeDataAdapter cb3 = new SqlCeDataAdapter(sql3);\n        DataTable dt3 = new DataTable();\n        cb3.Fill(dt3);\n        if (dt3.Rows.Count > 0)\n        {\n\n            ma.cmbEmpleado.DataSource = dt;\n            ma.cmbEmpleado.DataValueField = dt3.Columns["NUM_EMPL"].ToString();\n            ma.cmbEmpleado.DataTextField = dt3.Columns["NUM_EMPL"].ToString();\n        }\n        ma.cmbEmpleado.Items.Insert(0, "---------");\n        ma.cmbEmpleado.Items[0].Value = "0";	0
21100955	21100698	Restore row CssStyle with Javascript?	function onGridViewRowSelected(rowIdx) {\n    var selRow = getSelectedRow(rowIdx);\n    if (curSelRow != null) {\n        curSelRow.style.backgroundColor = curRowSty;\n    } if (null != selRow) {\n        curSelRow = selRow;\n        curRowSty = curSelRow.style.backgroundColor;\n        curSelRow.style.backgroundColor = '#ababab';\n    }\n    clearTimeout(rowHighLightTimeOut);\n}	0
21569883	21569800	how to tackle with textblock in wp8	TextBlock diffBlock = new TextBlock();\n\n\n        diffBlock.FontSize = 30;\n\n        diffBlock.Text = " ";\n      if(income!=null)\n        diffBlock.Text = (total - double.Parse(income.Inc)).ToString();\n       else\n         diffBlock.Text = total.ToString();\n         ContentPanel.Children.Add(diffBlock);\n\n        Difference.Foreground = new SolidColorBrush(Colors.Black);\n\n        Difference.Text = "Remaining Budget: " + diffBlock.Text;	0
5158542	5138344	Twitterizer - Search API Example	TwitterResponse<TwitterSearchResultCollection> result = TwitterSearch.Search("#hashtag");	0
3293721	3293077	Get ip adresses on a lan with backgroundworker control	var worker = new BackgroundWorker()\n  {\n    WorkerReportsProgress = true,\n    WorkerSupportsCancellation = true\n  };\n\n  /// runs on background thread\n  worker.DoWork += (s, e) =>\n  {\n    while (!done)\n    { \n      DoSomeWork();\n      // send a message to the Ui\n      // via the ProgressChanged event\n      worker.ReportProgress(percent, statusMessage); \n    }\n  };\n\n  /// the ProgressChanged event runs on the UI thread\n  worker.ProgressChanged += (s, e) =>\n  {\n    var msg = (MyStatusMessage)e.UserState;\n    someUiControl.Items.Add(msg.Text);\n  };\n\n  /// also runs on Ui thread\n  worker.RunWorkerCompleted += (s, e) =>\n  {\n\n  };\n\n  worker.RunWorkerAsync();	0
7708043	7707985	How to convert array<System::Byte> to char* in C++ CLR?	void TestByteArray(array<System::Byte>^ byteArray)\n{\n    pin_ptr<System::Byte> p = &byteArray[0];\n    unsigned char* pby = p;\n    char* pch = reinterpret_cast<char*>(pby);\n\n    // use it...\n}	0
12765894	12765819	More efficient way to get all indexes of a character in a string	string s = "abcabcabcabcabc";\n    var foundIndexes = new List<int>();\n\n    long t1 = DateTime.Now.Ticks;\n    for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))\n        {\n         // for loop end when i=-1 ('a' not found)\n                foundIndexes.Add(i);\n        }\n    long t2 = DateTime.Now.Ticks - t1; // read this value to see the run time	0
12644808	12644752	Break a while loop using external event	[Fact]\npublic void StartAndCancel()\n{\n    var cancellationTokenSource = new CancellationTokenSource();\n    var token = cancellationTokenSource.Token;\n    var tasks = Enumerable.Repeat(0, 2)\n                          .Select(i => Task.Run(() => Dial(token), token))\n                          .ToArray(); // start dialing on two threads\n    Thread.Sleep(200); // give the tasks time to start\n    cancellationTokenSource.Cancel();\n    Assert.Throws<AggregateException>(() => Task.WaitAll(tasks));\n    Assert.True(tasks.All(t => t.Status == TaskStatus.Canceled));\n}\n\npublic void Dial(CancellationToken token)\n{\n    while (true)\n    {\n        token.ThrowIfCancellationRequested();\n        Console.WriteLine("Called from thread {0}", Thread.CurrentThread.ManagedThreadId);\n        Thread.Sleep(50);\n    }\n}	0
18121357	18121202	Get all textblock's property value on click wp8	var myrow = control.GetValue(Grid.RowProperty);	0
5063103	5049982	problem with mysql export to file in c#	string path = fol.SelectedPath;\npath = path.Replace("\\","/");\n...	0
26189026	26189007	Edit a List<Tuple> item	var tuple = List.Find(s => s.Item1 == box.Text); \n//assuming you're searching for the first string, but you can change the predicate anyway. \ntuple = new Tuple<string, string>(new String, tuple.Item2);	0
31901631	31893601	Get Open Graph Data by Facebook API	using (WebClient client = new WebClient())\n        {\n            try\n            {\n               var json =\n                    client.UploadString(String.Format(\n                        "https://graph.facebook.com/v2.4/?id={0}&access_token={1}", url, at), "POST");\n            }\n            catch (Exception e)\n            {\n            }\n        }	0
9284890	9284532	Dynamically creating a Texture2D	const int TEX_WIDTH = 640;\nconst int TEX_HEIGHT = 480\nTexture2D redScreen;\n\nvoid GenerateTextures(GraphicsDevice device)\n{\n    redScreen = new Texture2D(device, TEX_WIDTH, TEX_HEIGHT);\n    uint[] red = new uint[TEX_WIDTH * TEX_HEIGHT];\n    for (int i = 0; i < TEX_WIDTH * TEX_HEIGHT; i++)\n        red[i] = new Color(255, 0, 0) * Alpha;\n    redScreen.SetData<uint>(red);\n}	0
29820158	29818048	Display a PDF in winforms	Process.Start(@"c:\gs\gs.exe",\n            String.Format("-o {0} -sDEVICE=tiffg4 -dFirstPage={1} -dLastPage={2} {3}", "tiffPages.tif", fromPage, toPage, "inputfile.pdf"));	0
7568889	7568613	How to merge two excel files into one with their sheet names?	Excel.Application app = new Excel.Application();\napp.Visible = true;\napp.Workbooks.Add("");\napp.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");\n  app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");\nfor (int i = 2; i <= app.Workbooks.Count; i++)\n{\n    for (int j = 1; j <= app.Workbooks[i].Worksheets.Count;j++ )\n    {\n        Excel.Worksheet ws = app.Workbooks[i].Worksheets[j];\n        ws.Copy(app.Workbooks[1].Worksheets[1]);\n    }\n}	0
31129162	31123422	How to wait for a StartCoroutine() to finish before proceeding	IEnumerator query (WWW web)\n{\n   //yield return web;\n   while(!web.isDone && web.Error == null)\n   {\n    //this will loop until your query is finished\n    //do something while waiting...\n      yield return null;\n   }\n   if(web.Error != null)\n     Debug.Log("Errors on web");\n\n}	0
10417707	10417497	checking user input submitted via ajax method	System.String.IsNullOrEmpty()	0
17577193	17576937	Managing multiple write request in SQLite	public class ConnectionClass\n{\n    private static object lockobj = new object();\n\n    public Result ExecuteQuery(Query query)\n    {\n        // wait until the resource is available\n        lock (lockobj)\n        {\n            // open connection, get results\n        }\n    }\n}	0
1554693	1554689	Evaluate Expressions in Switch Statements in C#	if (num < 0)\n{\n    ...\n}\nelse\n{\n    switch(num)\n    {\n        case 0: // Code\n        case 1: // Code\n        case 2: // Code\n        ...\n    }\n}	0
12221704	12221618	how to transfer and use a lot of parameters of different types via function argument?	public static class Ext\n{\n  public static void set(this YOUR_LIB_TYPE lib, object value)\n  {\n    if(value is int)\n    {\n      lib.set((int) value);\n    }\n    else if(value is string)\n    {\n      lib.set((string) value);\n    }\n    ...\n  }\n}	0
18934365	18934310	Show a form without taking focus	ShowActivated="False"	0
33694518	33694385	Getting incorrect date format when retrieving data from SQL in asp.net	Eval("Date", "{0:d}")	0
3557805	3440015	Multiple Description Attribute in c#	public class ExtraDescriptionAttribute : DescriptionAttribute\n{\n    private string extraInfo; public string ExtraInfo { get { return extraInfo; } set { extraInfo = value; } }\n    public ExtraDescriptionAttribute(string description)\n    {\n        this.DescriptionValue = description;\n        this.extraInfo = String.Empty;\n    }\n}	0
7318954	7318887	how to get number of columns in an entity, like datatable?	PropertyInfo[] propertyInfos;\npropertyInfos = typeof(MyClass).GetProperties();\nvar numberCol = propertyInfos.Length;	0
5346124	5346076	Linq XML query - How do I return a node that meets a condition within its own nested nodes?	RootElement.XPathSelectElements("//administrator[provinces/province = '" + provinceId + "']");	0
3742298	3737547	Communicate with a REST service inside a REST service	using (new OperationContextScope(service as IContextChannel))\n{\n    service.DoSomething();\n}	0
8261309	8256578	Powershell statement in C#	var ps = PowerShell.Create();\nps.Commands.AddScript("$myvariable = New-PSSessionOption ...");\nps.Invoke();	0
16711171	16711020	How to convert base 64 string to array of bytes without data loss?	byte[] b = Convert.FromBase64String(s);	0
16196284	16194182	datagrid selected index gives troubles	DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];	0
26279198	26279104	i don't input any accounts but in still logs in	string login = "SELECT ID, Username, [Password] FROM Employee where Username=@? and [Password]= @? ";	0
31864785	31863803	LINQ to Datatable Group By	var grouped = from d in sampleData\n                group d by d.Country\n                into g\n                select new {\n                         Country = g.Key,\n                         Data = g.Select(i => new {\n                                             Religion = i.Religion,\n                                             Population = i.Population\n                                         })\n                          };	0
31190610	31190524	Using Edge.js from a C# console application	Edge.Func(@"\n        return function (data, callback) {\n            callback(null, 'hello world');\n        }\n    ");	0
20991149	20970849	how to display data from webservice in listbox	void myClient_getarvindNewsCompleted(object sender, KejriwalService.getarvindNewsCompletedEventArgs e)\n          {\nstring result = e.Result.ToString();\n List<Newss> listData = new List<Newss>();\n            XDocument doc = XDocument.Parse(result);\n            // Just as an example of using the namespace...\n            //var b = doc.Element("NewDataSet").Value;\n            foreach (var location in doc.Descendants("UserDetails"))\n            {\n                Newss data = new Newss();\n                data.News_Title = location.Element("News_Title").Value;\n                data.News_Description = location.Element("News_Description").Value;\n                data.News_Date_Start = location.Element("Date_Start").Value;\n                listData.Add(data);\n            }\n              listBox1.ItemsSource = listData;\n\n          }	0
5274648	5274552	WPF :: Custom control how to Fire a method when a user change a property	public static readonly DependencyProperty CountProperty =\n                DependencyProperty.Register("Count", typeof(int), typeof(YourClass), new UIPropertyMetadata(OnCountChanged));\n\npublic int Value\n{\n       get { return (int)GetValue(CountProperty); }\n       set { SetValue(CountProperty, value); }\n}\n\nprivate static void OnCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)\n{\n       YourClass cp = obj as YourClass;\n       MethodToExecute();\n}	0
5436504	5436464	Return a variable as soon as it is set to a certain value. Equality overloading	areEqual = (this._valOne == myClass._valOne) \n    && (this._valTwo == myClass._valTwo) \n    && (this._valThree == myClass._valThree);	0
19368910	19368834	remove duplicate words from string in C#	foreach (string s in x.Distinct())\n{\n        Console.WriteLine(s.ToLower());\n}	0
11886655	11886046	How to specify a name to which object will be serialized by WebApi?	[DataContract(Name = "Employee")]\npublic class EmployeeApiModel\n{\n    [DataMember(Name = "Name2")]\n    public string Name { get; set; }\n\n    [DataMember]\n    public string Email { get; set; }\n}	0
27146889	27146104	Raise error in ajax call from server side asp.net	Response.StatusCode = (int)HttpStatusCode.NoContent;\nResponse.ContentType = "text/plain";\nResponse.Write("No data");	0
6532649	6532498	Mocks to verify interaction	public class MockEmailSender : IEmailSender\n{\n    public int SendCount = 0;\n\n    public void SendMail(...)\n    {\n        SendCount++;\n    }\n\n    // ... other IEmailSender methods ...\n}	0
15675350	15655387	Diffrent First Page in a document using microsoft office interop word in c#	Microsoft.Office.Interop.Word.Application w = new icrosoft.Office.Interop.Word.Application();\n Microsoft.Office.Interop.Word.Document doc;\n doc = w.ActiveDocument;\n doc.PageSetup.DifferentFirstPageHeaderFooter = -1;\n\n // Setting Different First page Header & Footer\n doc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.Text = "First Page Header";\n doc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.Text = "First Page Footer";\n\n // Setting Other page Header & Footer\n doc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "Other Page Header";\n doc.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "Other Page Footer";	0
9829660	9829503	Getting Data That Function Had That Threw An Exception IErrorHandler	public class AddressException : Exception\n{\n public string InputData { get; set; }\n public AddressException(string message, string inputData) : base(message)\n {\n   InputData = inputData;\n }\n}	0
20486758	20486354	How to define a byte array use the string style in .net?	string source = "\x90<>";\n byte[] bytes = Encoding.Default.GetBytes(source);	0
22121665	22121646	How to pick a random string from string array only once	static readonly List<string> Words = new List<string>(wordArr);\nstatic readonly Random Rnd = new Random();\n\npublic string Next()\n{\n    if(Words.Count < 1)\n        return "There are no more new words!! :(";\n\n    var index = Rnd.Next(0, Words.Length);\n    var result = Words[index];\n    Words.RemoveAt(index);\n\n    return result;\n}	0
3460713	3460703	.NET date formatting	ToString("d MMM yyyy", CultureInfo.CreateSpecificCulture("en-US")	0
9777978	9777742	Xml InnerXml indentation issue	XElement root = XElement.Parse("<Root><Settings><PresentationSettings></PresentationSettings></Settings></Root>");\nXElement pSettings = root.Element("Settings").Element("PresentationSettings");\npSettings.Add(otherContentXml);\nroot.Save(fileName);\nor\nstring formattedXml = root.ToString();	0
19553608	19553586	Assign multiple values of the structure in C#	User bill = new User{\n  ID = 1,\n  name = "Bill",\n  isAlive = false\n};	0
28175799	28175252	How to get index names through SQL or OLEDB from .NET?	using(OleDbConnection cnn = new OleDbConnection("...."))\n{\n    cnn.Open();\n    DataTable schemaIndexes = cnn.GetSchema("Indexes");\n    foreach(DataRow row in schemaIndexes.Rows)\n    {\n       Console.WriteLine("Table={0}, Index={1} on field={2}",\n           row.Field<string>("TABLE_NAME"),\n           row.Field<string>("INDEX_NAME"),\n           row.Field<string>("COLUMN_NAME"));\n    }\n}	0
9720205	9720143	ASP.NET Web Application Message Box	ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);	0
12265775	12265734	Run an application located in a directory from the PATH environment variable	Process.Start("CMD", "/C you_app_name.exe");	0
26331892	26331569	Variable continuously add up in Update()	else if (Input.GetKeyDown(KeyCode.DownArrow))\n{   \n    Debug.Log("s Down");\n\n    counter=counter+1;\n\n    Debug.Log (string.Format("counter {0} ",counter));\n    Debug.Log("Finish s down");\n}	0
13796851	13796817	Unit Testing Interfaces with Moq	private FooController _controller; // object under test, real object\nprivate Mock<IServiceAdapter> _serviceAdapter; // dependency of controller\n\n[TestInitialize]\npublic void Initialize()\n{\n    _serviceAdapter = new Mock<IServiceAdapter>();\n    _controller = new FooController(_serviceAdapter.Object);\n}\n\n[TestMethod()]\npublic void SaveTest()\n{\n    // Arrange\n    string name = "Name1"; \n    string type = "1";\n    string parentID = null;\n\n    _serviceAdapter.Setup(x => x.Save(name , type, parentID))\n                   .Returns("Success").Verifiable();\n\n    // Act on your object under test!\n    // controller will call dependency\n    var result =  _controller.Bar(name , type, parentID); \n\n    // Assert\n    Assert.True(result); // verify result is correct\n    _serviceAdapter.Verify(); // verify dependency was called\n}	0
5002881	5002834	saving a file (from stream) to disk using c#	FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);\n// Initialize the bytes array with the stream length and then fill it with data\nbyte[] bytesInStream = new byte[stream.Length];\nstream.Read(bytesInStream, 0, bytesInStream.Length);    \n// Use write method to write to the file specified above\nfileStream.Write(bytesInStream, 0, bytesInStream.Length);	0
22527756	22527575	How to set focus on a textbox when I close another Form?	private void button1_Click(object sender, EventArgs e)\n    {\n        Form2 f = new Form2();\n        f.Show();\n        f.FormClosed += f_FormClosed;\n\n    }\n\n    void f_FormClosed(object sender, FormClosedEventArgs e)\n    {\n         textBox1.Focus();\n    }	0
5628424	5628374	Parse JSON block with dynamic variables	Dictionary<string, dynamic>	0
26873354	26865539	Create Ldap search filter with join method refactor	public string GetFilter(IEnumerable<string> logins)\n{\n    return string.Format("(|{0})", \n           string.Concat(logins.Select(x => string.Format("(loginName={0})", x))));\n}	0
31598882	31592880	How do I redraw something that moves off screen? c#	static void Main(string[] args)\n    {\n        while(true)\n        {\n            Console.Clear();\n            Console.WriteLine("Top");\n            for (int x = 0; x < Console.WindowWidth; x++)\n            {\n                for (int y = 1; y < Console.WindowHeight - 1; y++)\n                {\n                    Console.SetCursorPosition(x, y);\n                    Console.Write("X");\n                }\n            }\n            Console.SetCursorPosition(0, Console.WindowHeight - 1);\n            Console.Write("Prompt: ");\n            Console.ReadLine();\n        }\n    }	0
8789652	8789424	How do I Copy Properties From one HttpWebRequest to Another?	foreach(var prop in m_HttpWebRequest.GetType().GetProperties())\n{\n    if(!(prop.CanWrite && prop.CanRead))\n        continue;\n\n    var val = prop.GetValue(m_HttpWebRequest, BindingFlags.GetProperty, null, null, null);\n    if (val == null)\n        continue;\n\n    prop.SetValue(m_HttpWebRequest2, val, BindingFlags.SetProperty, null, null, null);\n}	0
19333332	19333174	how to get data from my database using dates between two dates	private void button1_Click(object sender, EventArgs e)\n   {\n        string cmdText = "SELECT * FROM BillingSystem " + \n                         "WHERE DateOfTransaction BETWEEN ? AND ?";\n\n        DateTime dt = this.dateTimePicker1.Value.Date;\n        DateTime dt2 = this.dateTimePicker1.Value.Date.AddMinutes(1440);\n        command.CommandText = cmdText;\n        command.Parameters.AddWithValue("@p1",dt1);\n        command.Parameters.AddWithValue("@p2",dt2);\n        OleDbDataAdapter adapter = new OleDbDataAdapter(command, connectionBilling);\n        DataSet ds = new DataSet();\n        adapter.Fill(ds);\n        dataGridView1.DataSource = ds.Tables[0];\n        connectionBilling.Close();\n    }	0
16151124	16113227	DateTime.Parse always throws exception in a specific culture	CultureInfo cultureInfo = new CultureInfo( "es-MX" , true );\n     Date = DateTime.Parse( date.Replace( "p. m." , "PM" ).Replace( "p.m." , "PM" ).Replace( "." , "" ).ToUpper() , cultureInfo );	0
8594634	8594497	Linq-to-sql query group by while still selecting details	var query = (from d in details\n                     join a in\n                        (from animal in animals\n                         group animal by animal.Name into g\n                         select new { Name = g.Key }) on d.Name equals a.Name\n                     select new { a.Name, d.Height, d.Weight }).ToList();	0
6664178	6663644	How do I expose a WCF web service call response header in C#	using (var scope = new OperationContextScope())\n{\n    var client = new FoodPreferenceServiceClient(); \n    response = client.GetFoodPreference();\n\n    var httpProperties = (HttpResponseMessageProperty)OperationContext.Current\n                             .IncomingMessageProperties[HttpResponseMessageProperty.Name];\n\n    var headers = httpProperties.Headers;\n    // Now you should be able to work with WebHeaderCollection and find the header you need\n}	0
32282481	32281806	how do i compare a number in one array with a number in another array and find the difference? im using C#	int chevyWins = 0, fordWins = 0;\nfor (int i = 0; i < 8; i++)\n{\n    if (chevy[i] < ford[i])\n    {\n        //Note the difference with your code, your are doing \n        //the subtraction chevy[i] - ford[i] that will give you negative numbers.\n        chevyWins++;\n        Console.WriteLine(String.Format("Chevy won by {0}", (ford[i] - chevy[i])));\n    }\n    else if (chevy[i] > ford[i])\n    {\n        fordWins++;\n        Console.WriteLine(String.Format("Ford won by {0}", (chevy[i] - ford[i])));\n    }\n    else\n    {\n        Console.WriteLine("Tie!");\n    }\n}\n\nif (chevyWins > fordWins)\n{\n    Console.WriteLine("Chevy Wins the competition!");\n}\nelse if (chevyWins < fordWins)\n{\n    Console.WriteLine("Ford Wins the competition!");\n}\nelse\n{\n    Console.WriteLine("The competition was tie!");\n}	0
14407823	14361121	Manipulate a MVC4 view's DOM and generate a CSS formatted PDF	theDoc.AddImageUrl("http://www.google.com/")	0
1763336	1763050	Accessing controls added programmatically on postback	protected override void OnInit(EventArgs e)\n{\n\n    string dynamicControlId = "MyControl";\n\n    TextBox textBox = new TextBox {ID = dynamicControlId};\n    placeHolder.Controls.Add(textBox);\n}	0
8417520	8233451	DataSet validation in ColumnChanging event	TypedDataSet set = new TypedDataSet();\nTypedDataTable.TypedDataRow row = set.TypedDataTable.NewRow();\nrow.ColumnA = "Bad Data";\nset.TypedDataTable.AddTypedDataRow(row);\n\n// At this point the DataSet has column errors and can be checked for...\nif (set.HasErrors)\n{\n    // Build some error string container here\n    TypedDataSet.TypedDataRow row = tempSet.TypedDataTable.Single();\n\n    var errors = from column in row.GetColumnsInError()\n                 select row.GetColumnError(column);\n\n    foreach (var error in errors)\n    {\n        // Add to error container here\n    }\n}	0
9689277	9689143	Async return to the caller function from foreach loop	class DataProvider\n{\n   public System.Collections.IEnumerable<Result> PerformQuery(string param1, string param2)\n   {\n       var m_queryRes = DataAccessor.GetResults(param1, param2);\n\n       foreach(var res in m_queryRes)\n       {    \n              Result result = new Result();\n              result.Name = res.FirstName + res.SecondName;\n              result.Code = res.Code + "Some business logic";\n              yield return result;            \n       }\n\n   }\n}\nclass Result\n{\n   Property Name;\n   Property Code;\n}	0
5113210	5113013	Raise an event via reflection in c#	var eventInfo = currentType.GetEvent(eventName); \n  var eventRaiseMethod = eventInfo.GetRaiseMethod()\n  eventRaiseMethod.Invoke()	0
3343188	3342271	Rounding up a free text date field, for use a 'Date To' criteria field	string inputDate = "May 2010";\nint year = 0;\nDateTime date = new DateTime();\n\n// Try to parse just by year.\n// Otherwise parse by the input string.\nif (int.TryParse(inputDate, out year))\n{\n    date = new DateTime(year, 12, 31);\n}\nelse\n{\n    // Parse the date and set to the last day of the month.\n    if (DateTime.TryParse(inputDate, out date))\n    {\n        date = date.AddMonths(1).AddMilliseconds(-1);\n    }\n    else\n    {\n        // Throw exception for invalid date?\n    }\n}	0
13398940	13383378	Custom control properties for an internal TextBox	private TextBox _txtValue;\n\npublic EMRow()\n{\n    if (_txtValue == null)\n        _txtValue = new TextBox();\n}\n\npublic string Value\n{\n    get\n    {\n        return _txtValue.Text;\n    }\n    set\n    {\n        _txtValue.Text = value;\n    }\n}\n\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic TextBox ValueTextBox\n{\n    get\n    {\n        return _txtValue;\n    }\n    set\n    {\n        _txtValue = value;\n    }\n}	0
25252135	25251224	C# CultureInfo.CurrentCulture says en_US but my Windows settings are set to South Africa	CultureInfo.CurrentCulture	0
137183	136836	C# Array initialization - with non-default value	Enumerable.Repeat(true, result.TotalPages + 1).ToArray()	0
10761426	10761372	How to make two similar functions into one function?	public interface IDescribable\n{\n    int ID { get; set; }\n    string Description { get; set; }\n}\n\npublic class ClassA\n{\n    public int ID { get; set; }\n    public string Description { get; set; }\n\n    public int ColorID \n    { \n        get { return ID; } \n        set { ID = value; } \n    }\n\n    public string ColorDescription \n    { \n        get { return Description; } \n        set { Description = value; } \n    }\n}\n\npublic class ClassB\n{\n    public int ID { get; set; }\n    public string Description { get; set; }\n\n    public int TypeID \n    { \n        get { return ID; } \n        set { ID = value; } \n    }\n\n    public string TypeDescription \n    { \n        get { return Description; } \n        set { Description = value; } \n    }\n}\n\npublic void ExFunctionSave(IDescribable d, int id, string desc)    \n{\n    d.ID = id;\n    d.Description = desc;\n    Save();\n}	0
13406504	13406451	.NET RegEx replace escape character with tag	string input = @"This is the first part of the text #this should be formatted in bold# this should be normal text and then #this should be formatted in bold again# and so on.";\nvar output = Regex.Replace(input, @"#(.+?)#", "<b>$1</b>");	0
25387601	25374384	How to change Font type in Unity?	using UnityEngine;\nusing System.Collections;\n\npublic class ChangeFont : MonoBehaviour {\n\n    public UILabel label; \n    public Font otherFont;\n\n    IEnumerator Start() {\n        label.text = "This is a bit of text"; //show text\n        yield return new WaitForSeconds(2f); //wait 2 seconds\n        label.trueTypeFont = otherFont; //change font\n    }\n\n}	0
13105712	13105690	Change the Windows 8 lock screen background?	LockScreen API	0
3194165	3193894	how do I use mvc data annotations in conjunction with auto generated linqtosql classes	namespace MvcApplication1.Models\n{\n    [MetadataType(typeof(MovieMetaData))]\n    public partial class Movie\n    {\n    }\n\n\n    public class MovieMetaData\n    {\n        [Required]\n        public object Title { get; set; }	0
22596523	22595948	Reliable way to capture gamepad button press (non-game application)	class Input\n{\n    State old;\n\n    void GetInput()\n    {\n        State new = controller.GetState();\n        if (this.old.GamePad.Buttons == GamepadButtonFlags.A && new.GamePad.Buttons == GamepadButtonFlags.A)\n        {\n            // Do stuff that will be called only once.\n        }\n        this.old = new;\n    }\n}	0
34307078	29536795	Trying to put togehter all values from a list using linq	var query = collection.AsQueryable<File>().Select(x => x.pop).ToList();	0
13273586	13057682	Custom validation class - How to make universal	public class RequiredIfTrueAttribute: ValidationAttributeBase\n{\n\n    public string DependentPropertyName { get; private set; }\n\n    public RequiredIfTrueAttribute(string dependentPropertyName) \n        : base()\n    {\n            this.DependentPropertyName = dependentPropertyName;\n    }\n\n    protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n    {\n        // Get the property we need to see if we need to perform validation\n        PropertyInfo property = validationContext.ObjectType.GetProperty(this.DependentPropertyName);\n        object propertyValue = property.GetValue(validationContext.ObjectInstance, null);\n\n        // ... logic specific to my attribute\n\n        return ValidationResult.Success;\n    }\n\n\n}	0
17508715	17508586	Set RedirectUrl in JsonResult Action method	[Authorize]	0
20251637	20250729	Apply button in Catel's DataWindow	public MyDataWindow()\n  : base(DataWindowMode.OkCancelApply)\n{\n\n}	0
22837384	22833897	Unable to change back color of selected tabitem in silverlight	TabControl currentTab = (TabControl)sender;\n    TabItem selectedItem = currentTab.SelectedItem as TabItem;\n    if (selectedItem != null)\n    {\n        foreach (TabItem currentItem in currentTab.Items)\n        {\n            if (currentItem == selectedItem)\n            {\n                selectedItem.BorderBrush = new SolidColorBrush() { Color = Colors.Green };\n                selectedItem.Background = new SolidColorBrush() { Color = Colors.LightGray };\n            }\n            else\n            {\n                currentItem.BorderBrush = new SolidColorBrush() { Color = Colors.Blue };\n                currentItem.Background = new SolidColorBrush() { Color = Colors.Gray };\n            }\n        }\n    }	0
2283385	2283336	'orderby' in linq using a string array c#	var ordering = CustomerIDs.ToList();\nvar query = db.Customer.Join( db.Order, (a,b) => a.CustomerID == b.CustomerID )\n                       .AsEnumerable()\n                       .OrderBy( j => ordering.IndexOf( j.Customer.CustomerID ) )\n                       .Select( j => new CustomerOrderData {\n                          // do selection\n                        })\n                       .ToArray();	0
29401588	29401546	How to assign a value to a checkbox and use it in a formula?	int energy = 0;\nforeach(Control control in this.Controls)\n{\n    //you can have additional checks like name starts with to identify energy checkboxes\n    if (control is CheckBox) \n    {\n        energy = energy + Convert.ToInt32(control.Tag);\n    }\n}	0
18849629	18831803	How do I create a manual reset event that only allows access to particular user accounts in C++?	TCHAR *szSD = TEXT("D:")        // Discretionary ACL.\n        TEXT("(A;OICI;GA;;;BA)");   // Allow full control to administrators.\n        TEXT("(A;OICI;GA;;;SY)");   // Allow full control to the local system.\n    SECURITY_ATTRIBUTES sa;\n    sa.nLength = sizeof(SECURITY_ATTRIBUTES);\n    sa.bInheritHandle = FALSE;\n    ConvertStringSecurityDescriptorToSecurityDescriptor(szSD, SDDL_REVISION_1, &((&sa)->lpSecurityDescriptor), NULL);\n    HANDLE result = CreateEvent(&sa, TRUE, FALSE, L"Global\\CustomManualResetEvent");	0
2524679	2524643	.NET Reflection - Getting the Assembly object instance to a Referenced Assembly	Assembly.GetAssembly(typeof(StoreExample.Core.SomeClassInCore));	0
2906339	2903980	Is it possible to output the results of an sql command to a text file, when sent via SMO in C#?	catch (Exception ex)\n        {\n            executedSuccessfully = false;\n\n            SqlException sqlex = ex.InnerException as SqlException;\n\n            if (sqlex != null)\n            {\n                exceptionText = sqlex.Message;\n            }\n        }	0
25884163	25883833	Getting allow users from web.config	protected void Application_EndRequest(Object sender, EventArgs e)\n{\n    if (HttpContext.Current.Response.Status.StartsWith("401"))\n    {\n        HttpContext.Current.Response.ClearContent();\n        Response.Redirect("UnauthorizedUsers.aspx");\n    }\n}	0
16076007	16074590	I want to return a sublist of object and Total size of the Original List	Map<Integer, String> sample() {\n    Map map = new HashMap();\n    List<String> list = new ArrayList<String>(0);\n\n    for ( int i = 0; i < 50; i++)\n        list.add(i + "");\n\n    List<String> sublist = list.subList(0, 10);\n    Integer totalsize = list.size();\n\n    map.put("sublist", sublist);\n    map.put("original_list_length", totalsize);\n\n    return map;\n}	0
10383874	10375967	Windows phone 7 add items asynchronously to stackpanel	ThreadPool.QueueUserWorkItem(_ => {\n                foreach (int item in Enumerable.Range(1,50)) {\n                  Thread.Sleep(500);//simulate some calculations here\n                  int item1 = item;\n                  Deployment.Current.Dispatcher.BeginInvoke(() => {\n                      stackPanel.Children.Add(new TextBlock(){Text = "Text "+item1});\n                  });\n                }\n            });	0
4152076	4152056	Matching Zero Using Regular expression	Regex ex = new Regex("0");	0
25068433	25068351	How to initialize an array of dictionaries	Row = new Dictionary<string, string>[] \n{ \n    new Dictionary<string, string> { {"A", "A"} }, \n    new Dictionary<string, string> { {"B", "B"} } \n};	0
16900180	16899741	How to get route data keys from url parameter in custom Route constructor via Regex?	var myRoute = "{controller}/{action}/{id}";\nstring[] results = myRoute.Split(new[] { '{', '}', '/' }, StringSplitOptions.RemoveEmptyEntries);	0
3013569	3013442	Convert string to decimal retaining the exact input format	decimal value = Decimal.Parse("0.02", CultureInfo.GetCultureInfo("en-US"));\ndecimal value = Decimal.Parse("0,02", CultureInfo.GetCultureInfo("de-DE"));	0
4913237	4913177	Get an Label reference without using name	formlist[i].Controls["somename"].Text = "mumble";	0
20891091	20890826	How to concatenate ReadOnlyCollection	return (new ReadOnlyCollectionBuilder<T>(a.Concat(b))).ToReadOnlyCollection();	0
14991273	14988398	Sending JSON in POST from WP8 to AppEngine - Error 500	// Write the request Asynchronously \n    using (var stream = await Task.Factory.FromAsync<Stream>\n    (httpWebRequest.BeginGetRequestStream,httpWebRequest.EndGetRequestStream, null))\n    {\n        //create some json string\n        string json = "action="+JSONData;\n\n        // convert json to byte array\n        byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);\n\n        // Write the bytes to the stream\n        await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);\n    }	0
22814305	22811194	Multiple operations under linq2Entities	var ids = new List<Guid>();\n            foreach (var id in ids)\n            {\n                Employee employee = new Employee();\n                employee.Id = id;\n                entityEntry = context.Entry(employee);\n                entityEntry.State = EntityState.Deleted;\n            }\n            context.SaveChanges();	0
3504269	3504079	Designing Dependecy Injection and reuse of a single data context	interface IDataContextFactory\n{\n    ??? CreateContext();\n}\n\nclass DataContextFactory : IDataContextFactory\n{\n    public ??? CreateContext()\n    {\n        // Create and return the LINQ data context here...\n    }\n}\n\nclass Foo\n{\n    IDataContextFactory _dataContextFactory;\n\n    public Foo(IDataContextFactory dataContextFactory)\n    {\n        _dataContextFactory = dataContextFactory;\n    }\n\n    void Poll()\n    {\n        using (var context = _dataContextFactory.CreateContext())\n        {\n            //...\n        }\n    }\n}	0
15535090	15534974	Very confused about how to Group by in LINQ, and even more confused about HAVING	from entry in SomeTable\ngroup entry by entry.SomeValue into grp\nwhere grp.Sum(x => x.OtherValue) > 0\nselect grp.Key;	0
30672719	30672512	How to get number of matches from Regex.Replace	using System;\nusing System.Text.RegularExpressions;           \n\npublic class Program\n{\n    public static void Main()\n    {\n        int count = 0;\n        var b = Regex.Replace("gooodbaaad", "[oa]", m=> { count++; return "x"; });\n\n        Console.WriteLine(b);\n        Console.WriteLine(count);           \n    }\n}	0
7836440	7836390	How to compare last 3 char of a input string in asp.net website	if(link.ToLower().EndsWith("mp3"))\n        {\n\n        }	0
10305669	10291460	dynamically create a cascading delegate	public class Node\n{\n    protected Node Next { get; private set; }\n\n    private Delegate m_actionDel;\n    private object[] m_args;\n\n    public Node(Node next, Delegate actionToPerform)\n    {\n        Next = next;\n        m_actionDel = actionToPerform;\n    }        \n\n    public void InvokeChain()\n    {\n        try\n        {\n            m_actionDel.DynamicInvoke(m_args);\n        }\n        catch(Exception e)\n        {\n            // handle exception\n        }\n\n        if (Next != null)\n            Next.InvokeChain();\n    }\n}	0
23858074	23857947	C# - Detect if is the user using Windows 7 or Windows 8	var version = Environment.OSVersion.Version;\n\nif (version < new Version(6, 2))\n{\n    Console.WriteLine("This program isn't compatible with Windows 7 and older.");\n}\nelse\n{\n    Console.WriteLine("This os is compatible");\n}\n\nConsole.ReadLine();	0
4205379	4203848	How do I set the generic parameter to only specific type parameters in this Windsor installer using the fluent API?	container.Register(Component.For(typeof(IRepository<>)).ImplementedBy(typeof(ARRepository<>)));	0
13170956	13170939	Use of unassigned local variable 'bar'	class OutExample\n{\n    static void Method(out int i)\n    {\n        i = 44;\n    }\n    static void Main()\n    {\n        int value;\n        Method(out value);\n        // value is now 44\n    }\n}	0
18201538	18200909	creating dynamic div tag and place the data in that div tag, the data which is fetched from the database	StringBuilder stringBuilder = new StringBuilder();\n    foreach (DataRow row in t.Rows) {\n    stringBuilder.AppendFormat("<a href=\"category.aspx?refid=" + {0} + "\">" + {1} + "</a><br />", row["cid"], row["catname"]);\n    }\n    bdy.InnerHtml = stringBuilder.toString();\n    stringBuilder.Clear();	0
2612790	2611313	Problems with FlowLayoutPanel inside Panel with AutoSize	Form\n    TableLayoutPanel (1 column, 2 rows with 50% size type)\n        FlowLayoutPanel1 (AutoSize = true, in first row of the TableLayoutPanel, Dock = Fill)\n            Button1, Button2, Button3, Button4, ...\n        FlowLayoutPanel2 (SutoSize = true, in second row of the TableLayoutPanel, Dock = Fill)\n            Button1, Button2, Button3, Button4, ...	0
3446156	3446093	Logging state of object. Getting all its property values as string	public static string GetLogFor(object target)\n{\n    var properties =\n        from property in target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)\n        select new\n        {\n            Name = property.Name,\n            Value = property.GetValue(target, null)\n        };\n\n    var builder = new StringBuilder();\n\n    foreach(var property in properties)\n    {\n        builder\n            .Append(property.Name)\n            .Append(" = ")\n            .Append(property.Value)\n            .AppendLine();\n    }\n\n    return builder.ToString();\n}	0
663433	663332	Localized group name	var rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n                               MutexRights.Modify\n                                | MutexRights.Synchronize \n                                | MutexRights.TakeOwnership\n                                | MutexRights.ReadPermissions,\n                               AccessControlType.Allow)	0
33030579	33029123	Remove the Sunday on DateTime And Execute On For Loop In Datagrid	var fromDate = date_from.Value; // tool from datetime\n// My For Loop\nfor (int count = 0; count < 45; count++)\n{\n    if (fromDate.DayOfWeek == DayOfWeek.Sunday)\n    {\n       fromDate = fromDate.AddDays(1);\n    }\n    if(fromDate > date_from.Value.AddDays(45))\n       break;\n    dgv_result.Rows[count].Cells[0].Value = fromDate.ToShortDateString();\n    fromDate = fromDate.AddDays(1);\n\n}	0
17238800	17233742	Prevent Paste strings into Combo Box which are not items of that Combo Box in C#	private void comboBox1_TextChanged(object sender, EventArgs e)\n{\n    // Called whenever text changes.\n    if (combobox1.findstringexact(comboBox1.Text) > -1)\n        {\n        // codes if the text not in the lists\n        } \n}	0
10038957	10038771	Get total days in a list of dates C#	days = Dates.Max() - Dates.Min();\nConsole.WriteLine(days.TotalDays);	0
8385201	8365720	How to add a custom tuplizer for a Component programmatically?	config.ClassMappings\n    .SelectMany(cm => cm.PropertyIterator)\n    .Where(prop => prop.IsComposite)\n    .Select(prop => prop.Value)\n    .Cast<NHibernate.Mapping.Component>()\n    .ForEach(c => c.TuplizerMap[NHibernate.EntityMode.Map] = "tuplizerClassName");	0
429248	426573	How do you kill a process for a particular user in .NET (C#)?	Process[] processlist = Process.GetProcesses();\n            bool rdpclipFound = false;\n\n            foreach (Process theprocess in processlist)\n            {\n                String ProcessUserSID = GetProcessInfoByPID(theprocess.Id);\n                String CurrentUser = WindowsIdentity.GetCurrent().Name.Replace("SERVERNAME\\",""); \n\n                if (theprocess.ProcessName == "rdpclip" && ProcessUserSID == CurrentUser)\n                {\n                    theprocess.Kill();\n                    rdpclipFound = true;\n                }\n\n            }\n            Process.Start("rdpclip");\n            if (rdpclipFound)\n            {\n               MessageBox.Show("rdpclip.exe successfully restarted"); }\n            else\n            {\n               MessageBox.Show("rdpclip was not running under your username.  It has been started, please try copying and pasting again.");\n            }\n\n            }	0
29968071	29967082	how to open webform page in new tab of browser?	ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('../Update Pages/RegCustUpdateAndDelete.aspx','_blank');", true);	0
8267520	8267286	how to view record within date range?	SqlCommand cmd = new SqlCommand("select Fname,Lname,Insert_Date from Test where Convert(datetime,Insert_Date,103) >= '" + Convert.ToDateTime(TextBox1.Text).ToString(format) + "' and Convert(datetime,Insert_Date,103) <= '" + Convert.ToDateTime(TextBox2.Text).ToString(format) + "'  ", con);	0
5753013	5752576	How to restart windows service?	var sc = new ServiceController("MyService");\nsc.Stop();\nsc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));\nsc.Start();\nsc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));	0
26646491	26646429	how to assign value in to array in c#	public override string[] GetRolesForUser(string username)\n{\n    DEV_Context OE = new DEV_Context();\n    string role = OE.UserRefs.Where(x => x.UserName == username).FirstOrDefault().RoleName;\n\n    string[] result= OE.RolePermissionRefs.Where(x => x.RoleName == role).Select(x=>x.FunctionCode).ToArray(); \n\n    return result;\n}	0
5274263	5269279	Update a single item in a DataGrid's ItemsSource	((IEnumerable)grid.ItemsSource)[grid.SelectedIndex] = newItem;	0
22554571	22554466	Find specific file by last modified date and text inside the file	var dispenser =\n   directory.GetFiles("Dispenser*")\n            .OrderByDescending(f => f.LastWriteTime)\n            .Where(f => (File.ReadLines(f.FullName)\n                             .Skip(2)\n                             .FirstOrDefault()\n                               ?? String.Empty).Contains("MY_EXPECTED_LINE"))\n            .FirstOrDefault();	0
32842490	32825418	How to navigate to a frame from different thread?	Dispatcher.CurrentDispatcher.Invoke(()=>\n{\n        _mainFrame.Source = new System.Uri("AboutPage.xaml", UriKind.Relative); \n});	0
11225539	11225286	Bind Combo Box based on another Combo Box's selected item - MVVM WPF	public class Musics : INotifyPropertyChanged\n{\n   public event PropertyChangedEventHandler PropertyChanged;\n\n   private void OnPropertyChanged(string propertyName)\n    {\n        if (PropertyChanged != null)\n            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\n    }\n\n   private void initialiseAlbums()\n   {\n       if (selectedArtist != null)\n       {\n            //Your code\n            OnPropertyChanged("Albums");\n       }\n    }\n}	0
27419466	27418569	OnCollisionEnter2D making my object to disappear from game screen	Vector3 dir = selectedTarget.position - transform.position;\nfloat angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;\ntransform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);	0
28365386	28346722	Pattern matching with extraction of found substrings to variables	const string tokenPrefix = "px";\nconst string tokenSuffix = "sx";\nconst string tokenVar = "var";\n\nstring r = string.Format(@"(?<{0}>.*)\$\((?<{1}>.*)\)(?<{2}>.*)",\n                         tokenPrefix, tokenVar, tokenSuffix);\nRegex regex = new Regex(r);\nMatch match = regex.Match("Foo$(Something)Else");\n\nif (match.Success)\n{\n  string prefix = match.Groups[tokenPrefix].Value; // = "Foo"\n  string suffix = match.Groups[tokenSuffix].Value; // = "Something"\n  string variable = match.Groups[tokenVar].Value;  // = "Else" \n}	0
26233936	26230208	Keeping the relative position of a picturebox on another picturebox while resizing with SizeMode.Zoom, Winforms	double imgWidth = 0.0;\ndouble imgHeight = 0.0;\ndouble imgOffsetX = 0.0;\ndouble imgOffsetY = 0.0;\ndouble dRatio = pb.Image.Height / (double)pb.Image.Width; //dRatio will not change during resizing\n\npb.MouseClick += (ss, ee) =>\n{\n    test30x30.Location = new Point(ee.X - test30x30.Image.Width / 2, ee.Y - test30x30.Image.Height);\n    //x = ...\n    //y = ...\n};\n\nthis.Resize += (ss, ee) =>\n{\n    pb.Size = new Size(this.ClientSize.Width - 100, this.ClientSize.Height - 100);  \n};\n\npb.SizeChanged += (ss, ee) =>\n{\n    //recalculate image size and offset\n    if (pb.Height / pb.Width > dRatio) //case 1 \n    {\n        imgWidth = pb.Width;\n        imgHeight = pb.Width * dRatio;\n\n        imgOffsetX = 0.0;\n        imgOffsetY = (pb.Height - imgHeight) / 2;\n    }\n    else //case 2 \n    {\n        imgHeight = pb.Height;\n        imgWidth = pb.Height / dRatio;\n        imgOffsetY = 0.0;\n        imgOffsetX = (pb.Width - imgWidth) / 2;\n    }\n\n    //test30x30.Location = ...\n}	0
6638674	6636323	if statement to control input text in code behind	Static variable or Application level object	0
31699538	31699460	C# IRC Bot Error: 'Cannot read from a closed text reader'	while (true)\n            {\n                while ((inputLine = reader.ReadLine()) != null)\n                {\n                   ....\n                }            \n            }\n  // Close all streams\n                writer.Close();\n                reader.Close();\n                irc.Close();	0
33039560	33037817	Edit the background of a button in c#	private static void DrawLinesOnBitmap(Bitmap bmp)\n{\n   using (var p = new Pen(Color.Black, 5))\n   {\n      using (var g = Graphics.FromImage(bmp))\n      {\n         g.DrawLine(p, 0, 0, bmp.Width, bmp.Height);\n      }\n   }\n}	0
5907121	5906139	Setting up Ninject with the new WCF Web API	public class NinjectResourceFactory : IResourceFactory\n{\n    private readonly IKernel _kernel;\n\n    public NinjectResourceFactory(IKernel kernel)\n    {\n        _kernel = kernel;\n    }\n\n    public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)\n    {\n        return _kernel.Get(serviceType);\n    }\n\n    public void ReleaseInstance(InstanceContext instanceContext, object service)\n    {\n        // no op\n    }\n}	0
2153445	2153407	Output control in Bitmap	Bitmap myBitmap = new Bitmap(button1.Width, button1.Height);\n\n// button1.Draw..., not 'this.Draw...'!\nbutton1.DrawToBitmap(myBitmap, button1.DisplayRectangle); \n\nmyBitmap.Save(@"C:\test.bmp");	0
10623828	10623656	Streamreader to a relative filepath	string dir =System.IO.Path.GetDirectoryName(\n      System.Reflection.Assembly.GetExecutingAssembly().Location);\n\n    string file = dir + @"\TestDir\TestFile.txt";	0
19385650	19367271	MongoDB C# Driver - Update without Set/Replace	_caseCollection.Update(Query<Case>.EQ(x => x.Id, caseItem.Id), Update.Replace(existingDocument.Merge(caseItem.ToBsonDocument(), true)));	0
6226316	6226256	How to create runing text in WinForm Label? (like photoshop loading page)	For(int i =0; i<3;i++)\n{\n  label1.Text = "Please Wait.";\n  label1.Update();\n  system.Threading.Thread.Sleep(500);\n  label1.Text = "Please Wait..";\n  label1.Update();\n  system.Threading.Thread.Sleep(500);\n  label1.Text = "Please Wait...";\n}	0
4068943	4068912	C# iterator with string key	class Foo\n{\n    public object this[string key]\n    {\n        get\n        {\n            // Get the value.\n        }\n        set\n        {\n            // Set the value.\n        }\n    }\n}	0
2129407	2129357	Assert all in A belongs to B and all in B belongs to A	IComparer<T> comparer = new TComparer();\nbool equal = !A.Except(B, comparer).Any() && !B.Except(A, comparer).Any();	0
3924166	3923966	Logging into Ebay with C#	var selenium = new DefaultSelenium(host,port,browserString,startUrl);\nselenium.Open("http://www.site.com");\nselenium.Type("username","myusername");\nselenium.Type("password","mypassword");\nselenium.Click("submit");	0
6750103	6748944	How do I map similar linq2sql generated results to a single object?	private static List<DistroHeader> getHeaders<T>(Func<IEnumerable<T>> getHeaders)\n{\n    List<MyObj> myObj = new List<MyObj>();\n\n    var result = from a in getMyObjData()\n                 select a;\n\n    var pi = new List<PropertyInfo>(typeof(T).GetProperties());\n\n    foreach (var row in result)\n    {\n        myObj.Add(new MyObj()\n        {\n            Id = (int)pi.Find(x => x.Name == "id").GetValue(row, null),\n            Description = (string)pi.Find(x => x.Name == "descr").GetValue(row, null),\n            // ...etc      \n        });\n    }\n}	0
6080729	6080703	Mapping a large set of items to a smaller set of position markers	int imgnum = 569;\nint thumbmap [10];\nfor (int i = 0; i < 10; i++) thumbmap [i] = imgnum * i / 9;	0
11061720	11061705	Unable to extract value from XDocument using xpath	var username = xmldoc.XPathSelectElement(String.Format("Students/Student[StudentId={0}]/StudentName", StudentId)).Value;	0
1261644	1261624	Any repercussions to shorthand dialog display?	new TestForm().ShowDialog();	0
4847895	4843578	How to read the value in the first cell in a selected row of a Datagrid?	class DataClass {\n   string ID { get; set; }\n   ...\n}\n\n...\n\nDataClass current = (DataClass)dataGrid.SelectedItem;\nstring id = current.ID;	0
11452265	11452006	C# Append in XML file from recursive function	string rootPath = @"......";\nXElement xRoot = new XElement("Root",new XAttribute("Path",rootPath));\nRecurseDirs(rootPath, xRoot);\nvar xmlString = xRoot.ToString();\n\n\n\nvoid RecurseDirs(string root, XElement xRoot)\n{\n    foreach (var dir in Directory.EnumerateDirectories(root))\n    {\n        XElement xdir = new XElement("Directory",\n                                        new XAttribute("Name",Path.GetFileName(dir)),\n                                        new XAttribute("CreationTime",Directory.GetCreationTime(dir)));\n        xRoot.Add(xdir);\n        RecurseDirs(dir,xdir);\n    }\n\n    foreach (var dir in Directory.EnumerateFiles(root))\n    {\n        XElement xfile = new XElement("File", \n            new XAttribute("Name", Path.GetFileName(dir)),\n            new XAttribute("CreationTime", File.GetCreationTime(dir)));\n        xRoot.Add(xfile);\n    }\n}	0
22763201	22759322	How to append text value of a label control with textbox control. How to insert this value into database?	protected void btnsub_Click(object sender, EventArgs e)\n{\n    try\n    {\n        if (txtdetails.Text != "")\n        {\n            lblsource.Text=lblsource.Text+ txtdetails.Text;\n            txtdetails.Text = txtdetails.Text.Replace(System.Environment.NewLine, "<br>");\n            maxid = g1.generate_max_reg_id("select max(id) from tbl_content");\n            rows = g1.ExecDB("insert into tbl_content values(" + maxid + ",'" + txtdetails.Text.ToString() + string.Format("{0}<strong>MyName</strong>", lblsource.Text)+"')");\n            txtdetails.Text = string.Empty;\n         }\n         if (rows > 0)\n         {\n             ClientScript.RegisterStartupScript(typeof(Page), "AlertMessage", "alert('Successful!!!');window.location='textare_append.aspx';", true);\n         }\n     }\n     catch (Exception ex)\n     {\n         Response.Write(ex.ToString());\n     }\n }	0
15542402	15476299	Winform: Panel with scroll needs to have their width/height defined?	private void panel1_Resize(object sender, EventArgs e)\n{\n    panel1.AutoScrollMinSize = new System.Drawing.Size(panel1.Width, panel1.Height);\n}	0
28412658	28412564	Asp.net post multiple parameters to javascript function	Page.RegisterClientScriptBlock("Pass", "<script>pass('" + sle_password.Text.Trim() + "','" + sle_username.Text.Trim() + "','" + txt_reseller_ID.Text.Trim() + "');</script>");	0
4719050	4718960	DateTime.TryParse issue with dates of yyyy-dd-MM format	DateTime dt;\nDateTime.TryParseExact(dateTime, \n                       "yyyy-dd-MM hh:mm tt", \n                       CultureInfo.InvariantCulture, \n                       DateTimeStyles.None, \n                       out dt);	0
16090915	16090826	Extracting a JSON object from a serialized string in C#	string s = "{ \"id\": \"1\", something:{xx:22, yyy: \"3\"}, \"name\" : \"Test\" } has other text in the same string";\nvar regexp = new Regex("([{].+[}])");\nvar match = regexp.Match(s);	0
5938133	5934046	DAAB, do we need to handle connection opening closing manually?	public DataSet someMethod()\n{\n    database = new SqlDatabase(connectionString);\n    return database.ExecuteDataSet("procName", valparam1, valparam2);\n}	0
30436743	30436643	Validate whether a string is valid for IP Address or not	string s = "123.123.123.123";\n\nvar parts = s.Split('.');\n\nbool isValid = parts.Length == 4\n               && !parts.Any(\n                   x =>\n                   {\n                       int y;\n                       return Int32.TryParse(x, out y) && y > 255 || y < 1;\n                   });	0
7680450	7679753	Writing to a file and formatting rows .Suggestion needed	public class Customer\n            {\n                public string Name { get; set; }\n                public string Surname { get; set; }\n                public string Address { get; set; }\n                public string Country { get; set; }\n                public string DOB { get; set; }\n                public string MaritalStatus { get; set; }\n\n                public override string ToString()\n                {\n                    return String.Format("{0}{1}{2}",\n                        Name.PadRight(20),\n                        Surname.PadRight(30),\n                        Address.PadRight(40)\n                        );\n                }\n            }	0
6065460	5872131	Castle Windsor won't inject Logger in a property!	public ILogger Logger\n    {\n        get { return logger; }\n        set { logger = value; }\n    }\n\n    public LogicClass1()\n    {\n        logger.Debug("Here logger is NullLogger!");\n    }	0
25275935	25275588	Reading data from HTML source file	string input = new WebClient().DownloadString(@"http://eu.battle.net/wow/en/character/Kazzak/Ierina/simple");\n\n        // Here we call Regex.Match for <span class="equipped">560</span>\n        Match match = Regex.Match(input, @"<span class=\""equipped\"">([0-9]+)</span>",\n            RegexOptions.IgnoreCase);\n\n        // Here we check the Match instance.\n        if (match.Success)\n        {\n\n             string key = match.Groups[1].Value; //result here\n\n        }	0
1855593	1855462	Group objects by equality	public static IEnumerable<IEnumerable<T>> Group<T>(IEnumerable<T> items)\n    where T : IEquatable<T>\n{\n    IList<IList<T>> groups = new List<IList<T>>();\n\n    foreach (T t in items)\n    {\n        bool foundGroup = false;\n\n        foreach (IList<T> group in groups)\n        {\n            Debug.Assert(group.Count() >= 1);\n            if (group[0].Equals(t))\n            {\n                group.Add(t);\n                foundGroup = true;\n                break;\n            }\n        }\n\n        if (!foundGroup)\n        {\n            IList<T> newGroup = new List<T>() { t };\n            groups.Add(newGroup);\n        }\n    }\n\n    foreach (IList<T> group in groups)\n    {\n        yield return group;\n    }\n}	0
5645096	5644375	How to write nested group by LINQ query with sub-expression?	var itemGroups = from item in items.Cast<SPListItem>()\n                    let siteId = (string) item["siteId"]\n                    group item by siteId\n                    into siteGroup\n                    let siteGroups = from siteItem in siteGroup\n                                    let webId = (string) siteItem["webId"]\n                                    group siteItem by webId\n                                    into webGroup\n                                    select new\n                                                {\n                                                    WebId = webGroup.Key,\n                                                    WebGroups = (from wg in webGroup select wg).ToList()\n                                                }\n                    select new\n                            {\n                                SiteId = siteGroup.Key,\n                                SiteGroups = siteGroups.ToList()\n                            };	0
19630518	17019574	ScheduleActionService for Windows RT	BackgroundExecutionManager.RequestAccessAsync	0
460234	457565	How do I update a change using SubSonic and MySQL	User u = User.FetchByID(2);\nu.Ulevel = ulevel;\nu.save();	0
10078259	10067414	HasMany Mapping but getting one element or get some of	public class Category\n{\n    public virtual int Id { set; get; }\n    public virtual string Name { set; get; }\n    public virtual int CategoryOrder { set; get; }\n    public virtual IEnumerable<News> AllNews { set; get; }\n    public virtual News LatestNews \n    {\n        get\n        {\n            // probably needs some work\n            return this.AllNews.OrderByDescending(n => n.SomeDateField).Take(1);\n        }\n    }\n}\n\npublic sealed class CategoryMap :ClassMap<Category>\n{\n\n    public CategoryMap()\n    {\n        LazyLoad();\n        Id(x => x.Id);\n        Map(x => x.Name);\n        Map(x => x.CategoryOrder);\n        HasMany(x => x.AllNews);\n    }\n\n}	0
6646248	6570356	Datagridview with multiple Tableadapters, view different colums for each view	dg.AutoGenerateColumns = true;	0
23820668	23820603	One to many relationship, configure which field is referenced in Entity Framework	HasRequired(pc => pc.Person).WithMany(p => p.Children).HasForeignKey(pc => pc.PersonId);	0
31764190	31757003	How to access iOS VPN API from Xamarin	NetworkExtension.framework	0
10103148	10102733	C# MouseEnter-Event for the whole window	protected override void WndProc(ref Message m)\n        {\n            base.WndProc(ref m);\n            // mouse in window or in Border and max, close & min buttons     \n            if (m.Msg == 0xa0 || m.Msg == 0x200)\n            {\n                //Do some thing\n            }\n        }	0
5036722	5036586	How do I create two associated entities at one time with EF4 Code-First	Post post = new Post \n{ \n    Text = "Blah" \n    PostHistory = new List() \n    { \n        new PostHistory { Text = "Blah" }\n    }\n};        \ncontext.Posts.Add(post);\ncontext.SaveChanges();	0
933627	933613	How do I use Assert to verify that an exception has been thrown?	[TestMethod]\n[ExpectedException(typeof(ArgumentException),\n    "A userId of null was inappropriately allowed.")]\npublic void NullUserIdInConstructor()\n{\n   LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");\n}	0
11856502	11853929	Is it a good idea using UserId from aspnet membership table as a foreign key?	var username = HttpContext.Current.User.Identity.Name;\nvar user = Membership.GetUser(username);\nvar userid = user.ProviderUserKey as Guid?;\n\n// Look-up user info based on UserId GUID\nvar info = QueryOtherTables(userid);	0
29746932	29744076	How to get parent entity property in child entity with foreign key relation in code first?	var DoctorName=DoctorPayment.Doctor.Name	0
15930061	15929982	Trying to make a try catch continuously loop until service resumes	Invoke()	0
13196769	13180120	RadGrid CommandItemTemplate: accessing controls in ItemCommand event	protected void rgvDepts_ItemCommand(object source, GridCommandEventArgs e)\n    {\n        if (e.CommandName.Equals(RadGrid.InitInsertCommandName))\n        {\n            GridCommandItem item = e.Item as GridCommandItem;\n            GridTableView masterTable = item.OwnerTableView;\n            GridBoundColumn gbc = null;\n            if (item != null && masterTable != null)\n            {                    \n                gbc = (GridBoundColumn)masterTable.GetColumn("LIFNR");\n                if (gbc != null)\n                {\n                    gbc.ReadOnly = false;\n                    gbc.Visible = true;                       \n                }\n            }\n        }\n    }	0
27301160	27301118	Hwo to parse Timezone Offset string?	var time = "+7:30";\ntime = time.Replace("+", "");  // Remove the + if it is there.\n\nvar hours = TimeSpan.Parse(time).TotalHours;	0
3197368	3197134	How Would I Write This In LINQ2SQL?	var query = Pages.Where( p => p.DomainId == 1 && p.PageContent.IndexOf("display:") > 0).OrderBy( o => o.URL );\n\nvar regex = new Regex(@"display\:[\t]*none");\n\nforeach (var page in query)\n{\n    if( regex.IsMatch(page.PageContent) )\n    {\n        // Do whatever...                    \n    }                    \n}	0
11751971	11751858	How to select items from two lists where the ids don't match	var result = crabs.Where(c => whales.All(w => w.Id != c.Id));	0
17184302	17183983	How to read a textfile line by line from FTP server?	var lines = fileString.Split(new string[] { "\r\n", "\n" }, \n                                   StringSplitOptions.None);	0
3141055	2876022	Asp.net renders string with wrong encoding, but PHP doesn't (MySQL)	System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Default.GetBytes("convert me"))	0
29513319	29512851	Remove rows from a DataTable	var checkValues = new string[]  { "Some value1", "Some value3" };\n        DataTable dt = new DataTable();\n        DataTable dt1 = new DataTable();\n        dt.Columns.Add("Column1");\n        dt.Columns.Add("Column2");\n        dt.Columns.Add("Column3");\n        dt.Rows.Add(new string[] {"Some value1", "Some value2", "Some value3" });\n        dt.AsEnumerable().ToList().ForEach(x =>\n            {\n                if (checkValues.Contains(x["Column1"]))\n                {\n                    dt1.ImportRow(x);\n                    dt.Rows.Remove(x);\n                }\n            });	0
